[
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "docgen/src/main.rs",
        "content": "use regex::Regex;\nuse std::fs;\nuse std::path::Path;\n\nfn main() {\n    // TENSOR DOC\n    let trait_path = \"src/operators/tensor/core.cairo\";\n    let doc_path = \"docs/framework/operators/tensor\";\n    let label = \"tensor\";\n    let trait_name = \"TensorTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // NN DOC\n    let trait_path = \"src/operators/nn/core.cairo\";\n    let doc_path = \"docs/framework/operators/neural-network\";\n    let label = \"nn\";\n    let trait_name = \"NNTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // SEQUENCE DOC\n    let trait_path = \"src/operators/sequence/core.cairo\";\n    let doc_path = \"docs/framework/operators/sequence\";\n    let label = \"sequence\";\n    let trait_name = \"SequenceTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // FIXED POINT DOC\n    let trait_path = \"src/numbers/fixed_point/core.cairo\";\n    let doc_path = \"docs/framework/numbers/fixed-point\";\n    let label = \"fp\";\n    let trait_name = \"FixedTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // COMPLEX NUMBER DOC\n    let trait_path = \"src/numbers/complex_number/complex_trait.cairo\";\n    let doc_path = \"docs/framework/numbers/complex-number\";\n    let label = \"complex\";\n    let trait_name: &str = \"ComplexTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // TREE ENSEMBLE CLASSIFIER DOC\n    let trait_path = \"src/operators/ml/tree_ensemble/tree_ensemble_classifier.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/tree-ensemble-classifier\";\n    let label = \"tree_ensemble_classifier\";\n    let trait_name: &str = \"TreeEnsembleClassifierTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // TREE ENSEMBLE REGRESSOR DOC\n    let trait_path = \"src/operators/ml/tree_ensemble/tree_ensemble_regressor.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/tree-ensemble-regressor\";\n    let label = \"tree_ensemble_regressor\";\n    let trait_name: &str = \"TreeEnsembleRegressorTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // LINEAR REGRESSOR DOC\n    let trait_path = \"src/operators/ml/linear/linear_regressor.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/linear-regressor\";\n    let label = \"linear_regressor\";\n    let trait_name: &str = \"LinearRegressorTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // LINEAR CLASSIFIER DOC\n    let trait_path = \"src/operators/ml/linear/linear_classifier.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/linear-classifier\";\n    let label = \"linear_classifier\";\n    let trait_name: &str = \"LinearClassifierTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // SVM REGRESSOR DOC\n    let trait_path = \"src/operators/ml/svm/svm_regressor.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/svm-regressor\";\n    let label = \"svm_regressor\";\n    let trait_name: &str = \"SVMRegressorTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // SVM CLASSIFIER DOC\n    let trait_path = \"src/operators/ml/svm/svm_classifier.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/svm-classifier\";\n    let label = \"svm_classifier\";\n    let trait_name: &str = \"SVMClassifierTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n\n    // NORMALIZER DOC\n    let trait_path = \"src/operators/ml/normalizer/normalizer.cairo\";\n    let doc_path = \"docs/framework/operators/machine-learning/normalizer\";\n    let label = \"normalizer\";\n    let trait_name: &str = \"NormalizerTrait\";\n    doc_trait(trait_path, doc_path, label);\n    doc_functions(trait_path, doc_path, trait_name, label);\n}\n\nfn doc_trait(trait_path: &str, doc_path: &str, label: &str) {\n    // Open and read core.cairo file\n    let path_str = format!(\"../{}\", trait_path);\n    let path = Path::new(&path_str);\n    let contents = fs::read_to_string(&path).expect(\"Could not read the file\");\n\n    // Create a regular expression to match the comment lines\n    let re = Regex::new(r#\"/// (\\w+) - (.*)\"#).unwrap();\n\n    // Initialize an empty string to store our new formatted table\n    let mut table = String::from(\"| function | description |\\n| --- | --- |\\n\");\n\n    // Go through the file and look for comments with our specific format\n    for cap in re.captures_iter(&contents) {\n        // Check if the function is the Trait definition and skip it\n        if &cap[1] == \"Trait\" {\n            continue;\n        }\n\n        // Add the function name and description to our table\n        let func_name = format!(\n            \"[`{}.{}`]({}.{}.md)\",\n            label,\n            &cap[1],\n            label,\n            &cap[1].replace('_', r\"\\_\")\n        );\n        let func_desc = &cap[2];\n        table += &format!(\"| {} | {} |\\n\", func_name, func_desc);\n    }\n\n    // Open the README.md file\n    let readme_path_str = format!(\"../{}/README.md\", doc_path);\n    let readme_path = Path::new(&readme_path_str);\n    let readme = fs::read_to_string(&readme_path).expect(\"Could not read the file\");\n\n    // Use regex to replace the table\n    let re_table = Regex::new(r\"(?ms)\\n\\n\\| fun.*?(\\n[^|]|\\z)\").unwrap();\n    let new_readme = re_table.replace(&readme, &(\"\\n\\n\".to_owned() + &table + \"\\n\"));\n\n    // Write the updated contents back to README.md\n    fs::write(&readme_path, &*new_readme).expect(\"Could not write the file\");\n}\n\nfn doc_functions(trait_path: &str, doc_path: &str, trait_name: &str, label: &str) {\n    let filepath_str = format!(\"../{}\", trait_path);\n    let filepath = Path::new(&filepath_str);\n    let contents = fs::read_to_string(filepath).expect(\"Something went wrong reading the file\");\n\n    // Find the trait block\n    let trait_re = Regex::new(&format!(\n        r\"(?s)trait\\s+{}\\s*(<[\\w\\s,]*>)?\\s*\\{{.*?\\n\\s*\\}}\",\n        trait_name\n    ))\n    .unwrap();\n\n    let trait_match = trait_re.captures(&contents).unwrap();\n    let trait_block = trait_match.get(0).unwrap().as_str();\n\n    // Iterate over each function\n    let func_re = Regex::new(r\"(?s)(///.*?\\n)\\s*fn (\\w+)\\((.*?)\\) -> (.*?);\").unwrap();\n    for func_match in func_re.captures_iter(trait_block) {\n        let func_name = func_match.get(2).unwrap().as_str();\n        let doc_comment = func_match.get(1).unwrap().as_str();\n\n        // Go to the appropriate markdown file and write the transformed doc comment\n        let markdown_filename = format!(\"../{}/{}.{}.md\", doc_path, label, func_name);\n\n        let transformed_comment = doc_comment\n            .lines()\n            .map(|line| {\n                line.trim_start().strip_prefix(\"/// \").unwrap_or(\n                    line.trim_start()\n                        .strip_prefix(\"///\")\n                        .unwrap_or(line.trim_start()),\n                )\n            })\n            .collect::<Vec<_>>()\n            .join(\"\\n\");\n\n        // Write or replace the transformed comment into the markdown file\n        fs::write(markdown_filename, transformed_comment).expect(\"Unable to write file\");\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/__init__.py",
        "content": ""
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/file_manager.py",
        "content": "import os\nfrom pathlib import Path\n\n\nBASE_PATH = \"./tests/nodes\"\n\n\nclass ModFile:\n    def __init__(self):\n        \"\"\"\n        Initialize a ModFile object.\n\n        This method creates a new file with a .cairo extension in the BASE_PATH directory.\n        If the directory doesn't exist, it's created. The contents of the file are then read\n        into the buffer attribute.\n        \"\"\"\n        self.path = Path(f\"{BASE_PATH}.cairo\")\n        self.path.parent.mkdir(parents=True, exist_ok=True)\n        with self.path.open(\"r\") as f:\n            self.buffer = f.readlines()\n\n    def update(self, name: str):\n        \"\"\"\n        Update the .cairo file with a new module statement.\n\n        Args:\n            name (str): The name of the module to be added.\n\n        This method checks if a module statement for the given name already exists in the buffer.\n        If it doesn't, the new module statement is appended to the file.\n        \"\"\"\n        statement = f\"mod {name};\"\n        if any([line.startswith(statement) for line in self.buffer]):\n            return\n\n        with self.path.open(\"a\") as f:\n            f.write(f\"{statement}\\n\")\n\n\nclass File:\n    def __init__(self, path: str):\n        \"\"\"\n        Initialize a File object.\n\n        Args:\n            path (str): The file path where the File object will operate.\n\n        This method creates a new file at the specified path. If the file already exists, its\n        contents are read into the buffer attribute.\n        \"\"\"\n        self.path = Path(path)\n        self.path.parent.mkdir(parents=True, exist_ok=True)\n        self.buffer = []\n\n        if os.path.isfile(path):\n            with self.path.open(\"r\") as f:\n                self.buffer = f.readlines()\n\n    def dump(self):\n        \"\"\"\n        Write the contents of the buffer to the file.\n\n        This method writes each line in the buffer to the file, ensuring each line is\n        properly terminated with a newline character.\n        \"\"\"\n        with self.path.open(\"w\") as f:\n            f.writelines([f\"{line}\\n\" for line in self.buffer])\n\n\nclass CairoTest(File):\n    def __init__(self, file: str):\n        super().__init__(os.path.join(BASE_PATH, file))\n\n    @classmethod\n    def base_template(\n        cls, name: str, arg_cnt: int, refs: list[str], func_sig: str, out_cnt: int = 1\n    ) -> list[str]:\n        \"\"\"\n        Create a template for a Cairo test function which expects a tensor output.\n\n        Args:\n            name (str): Name of the test function.\n            arg_cnt (int): Number of arguments for the function.\n            refs (list[str]): List of references (modules) to be used in the function.\n            func_sig (str): The function signature.\n            out_cnt (int): Number of outputs for the function. Defaults to 1.\n\n        Returns:\n            list[str]: A list of strings that together form the template of a Cairo test function.\n\n        This method generates a list of strings that form the template of a Cairo test function,\n        including module imports, function definition, and assertions.\n        \"\"\"\n        template = [\n            *[f\"mod input_{i};\" for i in range(arg_cnt)],\n            *[f\"mod output_{i};\" for i in range(out_cnt)],\n            \"\",\n            \"\",\n            *[f\"use {ref};\" for ref in refs],\n            \"\",\n            \"#[test]\",\n            \"#[available_gas(2000000000)]\",\n            f\"fn test_{name}()\" + \" {\",\n            *[f\"    let input_{i} = input_{i}::input_{i}();\" for i in range(arg_cnt)],\n            *[f\"    let z_{i} = output_{i}::output_{i}();\" for i in range(out_cnt)],\n            \"\"\n        ]\n\n        # Handling conditional function signature based on the number of outputs\n        if out_cnt > 1:\n            template.append(f\"    let ({', '.join(f'y_{i}' for i in range(out_cnt))}) = {func_sig};\")\n        else:\n            template.append(f\"    let y_0 = {func_sig};\")\n\n        # Continue appending to the template\n        template.extend([\n            \"\",\n            *[f\"    assert_eq(y_{i}, z_{i});\" for i in range(out_cnt)],\n            \"}\"\n        ])\n\n        return template\n\n    @classmethod\n    def sequence_template(cls, name: str, arg_cnt: int, refs: list[str], func_sig: str) -> list[str]:\n        \"\"\"\n        Create a template for a Cairo test function which expects a tensor sequence.\n\n        Args:\n            name (str): Name of the test function.\n            arg_cnt (int): Number of arguments for the function.\n            refs (list[str]): List of references (modules) to be used in the function.\n            func_sig (str): The function signature.\n\n        Returns:\n            list[str]: A list of strings that together form the template of a Cairo test function.\n\n        This method generates a list of strings that form the template of a Cairo test function,\n        including module imports, function definition, and assertions.\n        \"\"\"\n        return [\n            *[f\"mod input_{i};\" for i in range(arg_cnt)],\n            *[ \"mod output_0;\"],\n            *[ \"\"],\n            *[ \"\"],\n            *[f\"use {ref};\" for ref in refs],\n            *[ \"\"],\n            *[ \"#[test]\"],\n            *[ \"#[available_gas(2000000000)]\"],\n            *[f\"fn test_{name}()\"+\" {\"],\n            *[f\"    let input_{i} = input_{i}::input_{i}();\" for i in range(arg_cnt)],\n            *[ \"    let z = output_0::output_0();\"],\n            *[ \"\"],\n            *[f\"    let y = {func_sig};\"],\n            *[ \"\"],\n            *[ \"    assert_seq_eq(y, z);\"],\n            *[ \"}\"],\n        ]\n\n\nclass CairoData(File):\n    def __init__(self, file: str):\n        super().__init__(os.path.join(BASE_PATH, file))\n\n    @classmethod\n    def base_template(\n        cls, func: str, dtype: str, refs: list[str], data: list[str], shape: tuple\n    ) -> list[str]:\n        \"\"\"\n        Create a base template for data representation in Cairo.\n\n        Args:\n            func (str): The function name.\n            dtype (str): The data type of the tensor.\n            refs (list[str]): A list of module references.\n            data (list[str]): The data to be included in the tensor.\n            shape (tuple): The shape of the tensor.\n\n        Returns:\n            list[str]: A list of strings that together form the template of a data function in Cairo.\n\n        This method generates a list of strings representing a function in Cairo for data handling,\n        defining the shape and contents of a tensor.\n        \"\"\"\n        template = [\n            *[f\"use {ref};\" for ref in refs],\n            *[\"\"],\n            *[f\"fn {func}() -> Tensor<{dtype}>\" + \" {\"],\n            *[\"    let mut shape = ArrayTrait::<usize>::new();\"],\n            *[f\"    shape.append({s});\" for s in shape],\n            *[\"\"],\n            *[\"    let mut data = ArrayTrait::new();\"],\n            *[f\"    data.append({d});\" for d in data],\n            *[\"    TensorTrait::new(shape.span(), data.span())\"],\n            *[\"}\"],\n        ]\n\n        return template\n\n    @classmethod\n    def sequence_template(\n        cls,\n        func: str,\n        dtype: str,\n        refs: list[str],\n        data: list[list[str]],\n        shape: list[tuple],\n    ) -> list[str]:\n        \"\"\"\n        Create a template for handling tensor sequences in Cairo.\n\n        Args:\n            func (str): The function name.\n            dtype (str): The data type of the tensor sequence.\n            refs (list[str]): A list of module references.\n            data (list[list[str]]): The data to be included in each tensor.\n            shape (list[tuple]): The shapes of each tensor in the sequence.\n\n        Returns:\n            list[str]: A list of strings that together form the template of a sequence tensor function in Cairo.\n\n        This method generates a list of strings representing a function in Cairo for handling a sequence\n        of tensors, each with its own data and shape.\n        \"\"\"\n\n        def expand_sequence_init(s: list[tuple], d: list[list[str]]) -> list[str]:\n            snippet = []\n            for i in range(len(s)):\n                snippet += [\n                    *[\"    let mut shape = ArrayTrait::<usize>::new();\"],\n                    *[f\"    shape.append({s});\" for s in s[i]],\n                    *[\"\"],\n                    *[\"    let mut data = ArrayTrait::new();\"],\n                    *[f\"    data.append({d});\" for d in d[i]],\n                    *[\"\"],\n                    *[\n                        \"    sequence.append(TensorTrait::new(shape.span(), data.span()));\"\n                    ],\n                    *[\"\"],\n                ]\n\n            return snippet\n\n        template = [\n            *[f\"use {ref};\" for ref in refs],\n            *[\"\"],\n            *[f\"fn {func}() -> Array<Tensor<{dtype}>>\" + \" {\"],\n            *[\"    let mut sequence = ArrayTrait::new();\"],\n            *[\"\"],\n            *expand_sequence_init(shape, data),\n            *[\"    sequence\"],\n            *[\"}\"],\n        ]\n\n        return template"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/helpers.py",
        "content": "from enum import Enum\nimport os\nfrom typing import List\n\nfrom .file_manager import CairoTest, CairoData, ModFile\n\nimport numpy as np\n\n\nclass FixedImpl(Enum):\n    FP8x23 = 'FP8x23'\n    FP16x16 = 'FP16x16'\n    FP32x32 = 'FP32x32'\n    \n\n\ndef to_fp(x: np.ndarray, fp_impl: FixedImpl):\n    match fp_impl:\n        case FixedImpl.FP8x23:\n            return (x * 2**23).astype(np.int64)\n        case FixedImpl.FP16x16:\n            return (x * 2**16).astype(np.int64)\n        case FixedImpl.FP32x32:\n            return (x * 2**32).astype(np.int64)\n\n\n\nclass Dtype(Enum):\n    FP8x23 = 'FP8x23'\n    FP16x16 = 'FP16x16'\n    FP32x32 = 'FP32x32'\n    I8 = 'i8'\n    I32 = 'i32'\n    U32 = 'u32'\n    BOOL = 'bool'\n    COMPLEX64 = 'complex64'\n\n\nclass Tensor:\n    def __init__(self, dtype: Dtype, shape: tuple, data: np.ndarray):\n        self.dtype = dtype\n        self.shape = shape\n        self.data = data\n\n\nSequence = List[Tensor]\n\n\nclass Trait(Enum):\n    TENSOR = 'TENSOR'\n    NN = 'NN'\n    SEQUENCE = 'SEQUENCE'\n\n\ndef make_test(inputs: list[Tensor | Sequence], output: Tensor | Sequence, func_sig: str, name: str, trait: Trait = Trait.TENSOR):\n    \"\"\"\n    Generate and write Cairo tests based on the provided inputs and output.\n\n    Args:\n        inputs (list[Tensor | list[Tensor]]): A list of input tensors or tensor sequences.\n        output (Tensor | list[Tensor]): The expected output tensor or tensor sequences.\n        func_sig (str): The signature of the function to be tested.\n        name (str): The name of the test.\n        trait (Trait, optional): The trait of the tensors. Defaults to Trait.TENSOR.\n    \"\"\"\n    ModFile().update(name)\n\n    for i, input in enumerate(inputs):\n        input_data = CairoData(os.path.join(name, f\"input_{i}.cairo\"))\n        match input:\n            case list():\n                input_data.buffer = CairoData.sequence_template(\n                    func=f\"input_{i}\",\n                    dtype=input[0].dtype.value,\n                    refs=get_data_refs(input[0].dtype),\n                    data=get_data_statement_for_sequences(\n                        input, input[0].dtype),\n                    shape=[x.shape for x in input],\n                )\n            case Tensor():\n                input_data.buffer = CairoData.base_template(\n                    func=f\"input_{i}\",\n                    dtype=input.dtype.value,\n                    refs=get_data_refs(input.dtype),\n                    data=get_data_statement(input.data, input.dtype),\n                    shape=input.shape,\n                )\n\n        input_data.dump()\n\n    match output:\n        case list():\n            output_data = CairoData(os.path.join(name, \"output_0.cairo\"))\n            output_data.buffer = CairoData.sequence_template(\n                func=\"output_0\",\n                dtype=output[0].dtype.value,\n                refs=get_data_refs(output[0].dtype),\n                data=get_data_statement_for_sequences(output, output[0].dtype),\n                shape=[x.shape for x in output],\n            )\n            output_data.dump()\n\n        case tuple():\n            for i, out in enumerate(output):\n                output_data = CairoData(\n                    os.path.join(name, f\"output_{i}.cairo\"))\n                output_data.buffer = CairoData.base_template(\n                    func=f\"output_{i}\",\n                    dtype=out.dtype.value,\n                    refs=get_data_refs(out.dtype),\n                    data=get_data_statement(out.data, out.dtype),\n                    shape=out.shape,\n                )\n                output_data.dump()\n\n        case Tensor():\n            output_data = CairoData(os.path.join(name, \"output_0.cairo\"))\n            output_data.buffer = CairoData.base_template(\n                func=\"output_0\",\n                dtype=output.dtype.value,\n                refs=get_data_refs(output.dtype),\n                data=get_data_statement(output.data, output.dtype),\n                shape=output.shape,\n            )\n            output_data.dump()\n\n    test_file = CairoTest(f\"{name}.cairo\")\n    match output:\n        case list():\n            test_file.buffer = CairoTest.sequence_template(\n                name=name,\n                arg_cnt=len(inputs),\n                refs=get_all_test_refs(find_all_types([*inputs, *output]), trait),\n                func_sig=func_sig,\n            )\n        case Tensor():\n            test_file.buffer = CairoTest.base_template(\n                name=name,\n                arg_cnt=len(inputs),\n                refs=get_all_test_refs(find_all_types([*inputs, output]), trait),\n                func_sig=func_sig,\n            )\n        case tuple():\n            test_file.buffer = CairoTest.base_template(\n                name=name,\n                arg_cnt=len(inputs),\n                out_cnt=len(output),\n                refs=get_all_test_refs(find_all_types([*inputs, output]), trait),\n                func_sig=func_sig,\n            )\n\n    test_file.dump()\n\n\ndef get_data_refs(dtype: Dtype) -> list[str]:\n    refs = [\n        *trait_to_ref[Trait.TENSOR],\n        *dtype_to_tensor[dtype],\n        *dtype_to_numbers[dtype],\n    ]\n\n    return refs\n\n\ndef get_data_statement(data: np.ndarray, dtype: Dtype) -> list[str]:\n    match dtype:\n        case Dtype.U32:\n            return [f\"{int(x)}\" for x in data.flatten()]\n        case Dtype.I32:\n            return [f\"{int(x)}\" for x in data.flatten()]\n        case Dtype.I8:\n            return [f\"{int(x)}\" for x in data.flatten()]\n        case Dtype.FP8x23:\n            return [\"FP8x23 { \"+f\"mag: {abs(int(x))}, sign: {str(x < 0).lower()} \"+\"}\" for x in data.flatten()]\n        case Dtype.FP16x16:\n            return [\"FP16x16 { \"+f\"mag: {abs(int(x))}, sign: {str(x < 0).lower()} \"+\"}\" for x in data.flatten()]\n        case Dtype.FP32x32:\n            return [\"FP32x32 { \"+f\"mag: {abs(int(x))}, sign: {str(x < 0).lower()} \"+\"}\" for x in data.flatten()]\n        case Dtype.BOOL:\n            return [str(x).lower() for x in data.flatten()]\n        case Dtype.COMPLEX64:\n            return [\"complex64 { \"+\"real: FP64x64 { \"+f\"mag: {abs(int(np.real(x)))}, sign: {str(np.real(x) < 0).lower()} \"+\"} , img: FP64x64 { \"+f\"mag: {abs(int(np.imag(x)))}, sign: {str(np.imag(x) < 0).lower()} \"+\"} }\" for x in data.flatten()]\n        \n\n\n\n\ndef get_data_statement_for_sequences(data: Sequence, dtype: Dtype) -> list[list[str]]:\n    return [get_data_statement(x.data, dtype) for x in data]\n\n\ndef get_all_test_refs(dtypes: list[Dtype], trait: Trait) -> list[str]:\n    refs = []\n    for dtype in dtypes:\n        # refs += [*dtype_to_numbers[dtype]]\n        refs += get_test_refs(dtype, trait)\n\n    return list(set(refs))\n\n\ndef get_test_refs(dtype: Dtype, trait: Trait) -> list[str]:\n    if trait == Trait.NN and dtype == Dtype.BOOL:\n        raise Exception(\"NN trait does not support bool dtype\")\n\n    if trait == Trait.NN:\n        dtype_ref = dtype_to_nn[dtype]\n    elif trait == Trait.SEQUENCE:\n        dtype_ref = dtype_to_sequence[dtype]\n    else:\n        dtype_ref = dtype_to_tensor[dtype]\n\n    refs = [\n        *trait_to_ref[trait],\n        *dtype_ref,\n        *dtype_to_partial_eq[dtype],\n        \"orion::utils::{assert_eq, assert_seq_eq}\",\n    ]\n\n    return refs\n\n\ndef find_all_types(tensors: list[Tensor | Sequence]) -> list[Dtype]:\n    dtypes = []\n    for tensor in tensors:\n        if isinstance(tensor, list) or isinstance(tensor, tuple):\n            dtypes += [x.dtype for x in tensor]\n        else:\n            dtypes.append(tensor.dtype)\n\n    return list(set(dtypes))\n\n\ntrait_to_ref = {\n    Trait.TENSOR: [\n        \"core::array::{ArrayTrait, SpanTrait}\",\n        \"orion::operators::tensor::{TensorTrait, Tensor}\",\n    ],\n    Trait.NN: [\n        \"orion::numbers::FixedTrait\",\n        \"orion::operators::nn::NNTrait\",\n    ],\n    Trait.SEQUENCE: [\n        \"core::array::{ArrayTrait, SpanTrait}\",\n        \"orion::operators::sequence::SequenceTrait\",\n    ],\n}\n\n\ndtype_to_tensor = {\n    Dtype.U32: [\"orion::operators::tensor::{U32Tensor, U32TensorAdd}\",],\n    Dtype.I32: [\"orion::operators::tensor::{I32Tensor, I32TensorAdd}\",],\n    Dtype.I8: [\"orion::operators::tensor::{I8Tensor, I8TensorAdd}\",],\n    Dtype.FP8x23: [\"orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd}\",],\n    Dtype.FP16x16: [\"orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd}\",],\n    Dtype.BOOL: [\"orion::operators::tensor::BoolTensor\",],\n    Dtype.COMPLEX64: [\"orion::operators::tensor::Complex64Tensor\",],\n    Dtype.FP32x32: [\"orion::operators::tensor::FP32x32Tensor\",],\n}\n\n\ndtype_to_nn = {\n    Dtype.U32: [\"orion::operators::nn::U32NN\",],\n    Dtype.I32: [\"orion::operators::nn::I32NN\",],\n    Dtype.I8: [\"orion::operators::nn::I8NN\",],\n    Dtype.FP8x23: [\"orion::operators::nn::FP8x23NN\",],\n    Dtype.FP16x16: [\"orion::operators::nn::FP16x16NN\",],\n}\n\n\ndtype_to_sequence = {\n    Dtype.U32: [\"orion::operators::sequence::U32Sequence\",],\n    Dtype.I32: [\"orion::operators::sequence::I32Sequence\",],\n    Dtype.I8: [\"orion::operators::sequence::I8Sequence\",],\n    Dtype.FP8x23: [\"orion::operators::sequence::FP8x23Sequence\",],\n    Dtype.FP16x16: [\"orion::operators::sequence::FP16x16Sequence\",],\n}\n\n\ndtype_to_partial_eq = {\n    Dtype.U32: [\"orion::operators::tensor::U32TensorPartialEq\",],\n    Dtype.I32: [\"orion::operators::tensor::I32TensorPartialEq\",],\n    Dtype.I8: [\"orion::operators::tensor::I8TensorPartialEq\",],\n    Dtype.FP8x23: [\"orion::operators::tensor::FP8x23TensorPartialEq\",],\n    Dtype.FP16x16: [\"orion::operators::tensor::FP16x16TensorPartialEq\",],\n    Dtype.FP32x32: [\"orion::operators::tensor::FP32x32TensorPartialEq\",],\n    Dtype.BOOL: [\"orion::operators::tensor::BoolTensorPartialEq\",],\n    Dtype.COMPLEX64: [\"orion::operators::tensor::Complex64TensorPartialEq\",],\n}\n\n\ndtype_to_numbers = {\n    Dtype.U32: [\"orion::numbers::NumberTrait\"],\n    Dtype.I32: [\"orion::numbers::NumberTrait\"],\n    Dtype.I8: [\"orion::numbers::NumberTrait\"],\n    Dtype.FP8x23: [\"orion::numbers::{FixedTrait, FP8x23}\",],\n    Dtype.FP16x16: [\"orion::numbers::{FixedTrait, FP16x16}\",],\n    Dtype.FP32x32: [\"orion::numbers::{FixedTrait, FP32x32}\",],\n    Dtype.BOOL: [],\n    Dtype.COMPLEX64: [\"orion::numbers::{NumberTrait, complex64}\",],\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/__init__.py",
        "content": "import argparse\nimport importlib\nimport os\nimport sys\n\n\nclass RunAll:\n    @classmethod\n    def run_all(cls):\n        for method_name in dir(cls):\n            if method_name.startswith('__') or method_name == 'run_all':\n                continue\n            method = getattr(cls, method_name)\n            if callable(method):\n                method()\n\n\n# Add the path to the 'orion' directory to the Python path\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Generate nodes.\")\n    parser.add_argument('node_class', help=\"The class of node to run.\")\n    args = parser.parse_args()\n\n    class_name = args.node_class.capitalize()\n\n    # Verify that the specified Python file exists\n    filename = os.path.join('nodegen/node', args.node_class + '.py')\n    if not os.path.exists(filename):\n        print(f\"Error: {filename} does not exist.\")\n        return\n\n    # Import the module dynamically\n    module = importlib.import_module('nodegen.node.' + args.node_class)\n\n    # Get the class from the module\n    node_class = getattr(module, class_name)\n\n    # Instantiate the class and call the run_all method\n    node_instance = node_class()\n    node_instance.run_all()\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/abs.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Abs(RunAll):\n    @staticmethod\n    def abs_i32():\n        x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n        y = abs(x)\n\n        x = Tensor(Dtype.I32, x.shape, x.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"abs_i32\"\n        make_test([x], y, \"input_0.abs()\", name)\n\n    @staticmethod\n    def abs_i8():\n        x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n        y = abs(x)\n\n        x = Tensor(Dtype.I8, x.shape, x.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"abs_i8\"\n        make_test([x], y, \"input_0.abs()\", name)\n\n    @staticmethod\n    def abs_fp8x23():\n        x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                    ).astype(np.int64), FixedImpl.FP8x23)\n        y = abs(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n        y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n        name = \"abs_fp8x23\"\n        make_test([x], y, \"input_0.abs()\", name)\n\n    @staticmethod\n    def abs_fp16x16():\n        x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                    ).astype(np.int64), FixedImpl.FP16x16)\n        y = abs(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n        y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n        name = \"abs_fp16x16\"\n        make_test([x], y, \"input_0.abs()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/acos.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nclass Acos(RunAll):\n   \n    @staticmethod\n    def acos_fp8x23():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.arccos(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        name = \"acos_fp8x23\"\n        make_test([x], y, \"input_0.acos()\", name)\n     \n    @staticmethod\n    def acos_fp16x16():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.arccos(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"acos_fp16x16\"\n        make_test([x], y, \"input_0.acos()\", name)\n     \n\n\n\n\n\n \n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/acosh.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Acosh(RunAll):\n    @staticmethod\n    def acosh_fp8x23():\n        x = np.random.uniform(1, 5, (2, 2)).astype(np.float64)\n        y = np.arccosh(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"acosh_fp8x23\"\n        make_test([x], y, \"input_0.acosh()\", name)\n\n    @staticmethod\n    def acosh_fp16x16():\n        x = np.random.uniform(1, 5, (2, 2)).astype(np.float64)\n        y = np.arccosh(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"acosh_fp16x16\"\n        make_test([x], y, \"input_0.acosh()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/add.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Add(RunAll):\n    @staticmethod\n    def add_u32():\n        def default():\n            x = np.random.randint(0, 3, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (3, 3, 3)).astype(np.uint32)\n            z = x + y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"add_u32\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 3, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (1, 3, 1)).astype(np.uint32)\n            z = x + y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"add_u32_broadcast\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def add_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = x + y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"add_i32\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int32)\n            z = x + y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"add_i32_broadcast\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def add_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = x + y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"add_i8\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int8)\n            z = x + y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"add_i8_broadcast\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def add_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x + y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"add_fp8x23\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x + y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"add_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def add_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x + y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"add_fp16x16\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x + y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"add_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0 + input_1\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/and.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass And(RunAll):\n    @staticmethod\n    def and_bool():\n        def default():\n            x = (np.random.randn(3, 4) > 0).astype(bool)\n            y = (np.random.randn(3, 4) > 0).astype(bool)\n            z = np.logical_and(x, y)\n\n            x = Tensor(Dtype.BOOL, x.shape, x.flatten())\n            y = Tensor(Dtype.BOOL, y.shape, y.flatten())\n            z = Tensor(Dtype.BOOL, z.shape, z.flatten())\n\n            name = \"and_bool\"\n            make_test([x, y], z, \"BoolTensor::and(@input_0, @input_1)\", name)\n\n        def broadcast():\n            x = (np.random.randn(3, 4, 5) > 0).astype(bool)\n            y = (np.random.randn(3, 4, 5) > 0).astype(bool)\n            z = np.logical_and(x, y)\n\n            x = Tensor(Dtype.BOOL, x.shape, x.flatten())\n            y = Tensor(Dtype.BOOL, y.shape, y.flatten())\n            z = Tensor(Dtype.BOOL, z.shape, z.flatten())\n\n            name = \"and_bool_broadcast\"\n            make_test([x, y], z, \"BoolTensor::and(@input_0, @input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/argmax.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\ndef argmax_use_numpy(data: np.ndarray, axis: int = 0, keepdims: int = 1) -> np.ndarray:\n    result = np.argmax(data, axis=axis)\n    if keepdims == 1:\n        result = np.expand_dims(result, axis)\n    return result.astype(np.int64)\n\n\ndef argmax_use_numpy_select_last_index(\n    data: np.ndarray, axis: int = 0, keepdims: int = True\n) -> np.ndarray:\n    data = np.flip(data, axis)\n    result = np.argmax(data, axis=axis)\n    result = data.shape[axis] - result - 1\n    if keepdims:\n        result = np.expand_dims(result, axis)\n    return result.astype(np.int64)\n\n\nclass Argmax(RunAll):\n\n    @staticmethod\n    def no_keepdims():\n        data = np.array([[2, 1], [3, 10]], dtype=np.float32)\n        axis = 1\n        keepdims = 0\n        result = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_no_keepdims\"\n        make_test(\n            [x], y, \"input_0.argmax(1, Option::Some(false), Option::None(()))\", name)\n\n    @staticmethod\n    def keepdims():\n        data = np.array([[2, 1], [3, 10]], dtype=np.float32)\n        axis = 1\n        keepdims = 1\n        result = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_keepdims\"\n        make_test(\n            [x], y, \"input_0.argmax(1, Option::Some(true), Option::None(()))\", name)\n\n    @staticmethod\n    def default_axes_keepdims():\n        data = np.array([[2, 1], [3, 10]], dtype=np.float32)\n        keepdims = 1\n        result = argmax_use_numpy(data, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_default_axes_keepdims\"\n        make_test(\n            [x], y, \"input_0.argmax(0, Option::Some(true), Option::None(()))\", name)\n\n    @staticmethod\n    def negative_axis_keepdims():\n        data = np.array([[2, 1], [3, 10]], dtype=np.float32)\n        axis = -1\n        keepdims = 1\n        result = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_negative_axis_keepdims\"\n        make_test(\n            [x], y, \"input_0.argmax(-1, Option::Some(true), Option::None(()))\", name)\n\n    @staticmethod\n    def no_keepdims_select_last_index():\n        data = np.array([[2, 2], [3, 10]], dtype=np.float32)\n        axis = 1\n        keepdims = 0\n        result = argmax_use_numpy_select_last_index(\n            data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_no_keepdims_select_last_index\"\n        make_test(\n            [x], y, \"input_0.argmax(1, Option::Some(false), Option::Some(true))\", name)\n\n    @staticmethod\n    def keepdims_select_last_index():\n        data = np.array([[2, 2], [3, 10]], dtype=np.float32)\n        axis = 1\n        keepdims = 1\n        result = argmax_use_numpy_select_last_index(\n            data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_keepdims_select_last_index\"\n        make_test(\n            [x], y, \"input_0.argmax(1, Option::Some(true), Option::Some(true))\", name)\n\n    @staticmethod\n    def default_axes_keepdims_select_last_index():\n        data = np.array([[2, 2], [3, 10]], dtype=np.float32)\n        keepdims = 1\n        result = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_default_axes_keepdims_select_last_index\"\n        make_test(\n            [x], y, \"input_0.argmax(0, Option::Some(true), Option::Some(true))\", name)\n\n    @staticmethod\n    def negative_axis_keepdims_select_last_index():\n        data = np.array([[2, 2], [3, 10]], dtype=np.float32)\n        axis = -1\n        keepdims = 1\n        result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\n\n        x = Tensor(Dtype.FP16x16, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, result.shape, result.flatten())\n\n        name = \"argmax_negative_axis_keepdims_select_last_index\"\n        make_test(\n            [x], y, \"input_0.argmax(-1, Option::Some(true), Option::Some(true))\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/argmin.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\ndef argmin_use_numpy(data: np.ndarray, axis: int = 0, keepdims: int = 1, dtype=np.int64) -> np.ndarray:\n    result = np.argmin(data, axis=axis)\n    if keepdims == 1:\n        result = np.expand_dims(result, axis)\n    return result.astype(dtype)\n\n\ndef argmin_use_numpy_select_last_index(\n    data: np.ndarray, axis: int = 0, keepdims: int = True, dtype=np.int64\n) -> np.ndarray:\n    data = np.flip(data, axis)\n    result = np.argmin(data, axis=axis)\n    result = data.shape[axis] - result - 1\n    if keepdims:\n        result = np.expand_dims(result, axis)\n    return result.astype(dtype)\n\n\nclass Argmin(RunAll):\n\n    @staticmethod\n    def argmin_u32():\n        def argmin_1D():\n            def default_params():\n                x = np.random.randint(0, 255, (3)).astype(np.uint32)\n                y = argmin_use_numpy(x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_1D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(0, 255, (3)).astype(np.uint32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_1D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(0, 255, (3)).astype(np.uint32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_1D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_1D()\n\n        def argmin_2D():\n            def default_params():\n                x = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_2D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_2D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_2D()\n\n        def argmin_3D():\n            def default_params():\n                x = np.random.randint(0, 255, (2, 2, 2)).astype(np.uint32)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_3D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(0, 255, (2, 2, 2)).astype(np.uint32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_3D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(0, 255, (2, 2, 2)).astype(np.uint32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_u32_3D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_3D()\n\n    @staticmethod\n    def argmin_i32():\n        def argmin_1D():\n            def default_params():\n                x = np.random.randint(-127, 127, (3)).astype(np.int32)\n                y = argmin_use_numpy(x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_1D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (3)).astype(np.int32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_1D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(0, 255, (3)).astype(np.int32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_1D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_1D()\n\n        def argmin_2D():\n            def default_params():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_2D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_2D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_2D()\n\n        def argmin_3D():\n            def default_params():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int32)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_3D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int32)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_3D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int32)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i32_3D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_3D()\n\n    @staticmethod\n    def argmin_i8():\n        def argmin_1D():\n            def default_params():\n                x = np.random.randint(-127, 127, (3)).astype(np.int8)\n                y = argmin_use_numpy(x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_1D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (3)).astype(np.int8)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_1D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(0, 255, (3)).astype(np.int8)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_1D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_1D()\n\n        def argmin_2D():\n            def default_params():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_2D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_2D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.int8)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_2D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_2D()\n\n        def argmin_3D():\n            def default_params():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int8)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_3D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int8)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_3D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int8)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_i8_3D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_3D()\n\n    @staticmethod\n    def argmin_fp16x16():\n        def argmin_1D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (3)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_1D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (3)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_1D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(0, 255, (3)).astype(\n                    np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_1D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_1D()\n\n        def argmin_2D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_2D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_2D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.int8)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_2D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_2D()\n\n        def argmin_3D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_3D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_3D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP16x16)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp16x16_3D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_3D()\n\n    @staticmethod\n    def argmin_fp8x23():\n        def argmin_1D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (3)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_1D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (3)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_1D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(0, 255, (3)).astype(\n                    np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32).reshape((1))\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_1D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_1D()\n\n        def argmin_2D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_2D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_2D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_2D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_2D()\n\n        def argmin_3D():\n            def default_params():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_3D_default\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::None(()))\", name)\n\n            def keepdims_false():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy(\n                    x, keepdims=0, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_3D_keepdims_false\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::Some(false), Option::None(()))\", name)\n\n            def last_index():\n                x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                            ).astype(np.int8), FixedImpl.FP8x23)\n                y = argmin_use_numpy_select_last_index(\n                    x, dtype=np.uint32)\n\n                x = Tensor(Dtype.FP8x23, x.shape,\n                           x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"argmin_fp8x23_3D_last_index\"\n                make_test(\n                    [x], y, \"input_0.argmin(0, Option::None(()), Option::Some(true))\", name)\n\n            default_params()\n            keepdims_false()\n            last_index()\n        argmin_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/array_feature_extractor.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Array_feature_extractor(RunAll):\n\n    @staticmethod\n    def array_feature_extractor_3D():\n        def array_feature_extractor_i32():\n            x = np.random.randint(-3, 3, (2, 3, 4)).astype(np.int32)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"array_feature_extractor_3D_i32\"\n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n\n        def array_feature_extractor_fp8x23():\n            x = np.random.randint(-3, 3, (2, 3, 4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"array_feature_extractor_3D_fp8x23\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        \n        def array_feature_extractor_fp16x16():\n            x = np.random.randint(-3, 3, (2, 3, 4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"array_feature_extractor_3D_fp16x16\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        array_feature_extractor_i32()\n        array_feature_extractor_fp8x23()\n        array_feature_extractor_fp16x16()\n\n\n    @staticmethod\n    def array_feature_extractor_2D():\n        def array_feature_extractor_i32():\n            x = np.random.randint(-3, 3, (3, 4)).astype(np.int32)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"array_feature_extractor_2D_i32\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n\n        def array_feature_extractor_fp8x23():\n            x = np.random.randint(-3, 3, (3, 4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"array_feature_extractor_2D_fp8x23\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        \n        def array_feature_extractor_fp16x16():\n            x = np.random.randint(-3, 3, (3, 4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"array_feature_extractor_2D_fp16x16\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        array_feature_extractor_i32()\n        array_feature_extractor_fp8x23()\n        array_feature_extractor_fp16x16()\n\n\n    @staticmethod\n    def array_feature_extractor_1D():\n        def array_feature_extractor_i32():\n            x = np.random.randint(-3, 3, (4)).astype(np.int32)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"array_feature_extractor_1D_i32\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n\n        def array_feature_extractor_fp8x23():\n            x = np.random.randint(-3, 3, (4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"array_feature_extractor_1D_fp8x23\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        \n        def array_feature_extractor_fp16x16():\n            x = np.random.randint(-3, 3, (4)).astype(np.float64)\n            y = np.array([1, 3]).astype(np.uint32)\n            z = (x[..., y])\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"array_feature_extractor_1D_fp16x16\"\n            \n            make_test([x, y], z, \"TensorTrait::array_feature_extractor(@input_0, input_1)\", name)\n\n        array_feature_extractor_i32()\n        array_feature_extractor_fp8x23()\n        array_feature_extractor_fp16x16()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/asin.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nclass Asin(RunAll):\n   \n    @staticmethod\n    def asin_fp8x23():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.arcsin(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        name = \"asin_fp8x23\"\n        make_test([x], y, \"input_0.asin()\", name)\n     \n    @staticmethod\n    def asin_fp16x16():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.arcsin(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"asin_fp16x16\"\n        make_test([x], y, \"input_0.asin()\", name)\n     \n\n\n\n\n\n \n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/asinh.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Asinh(RunAll):\n\n    @staticmethod\n    def asinh_fp8x23():\n        x = np.random.uniform(1, 5, (2, 2)).astype(np.float64)\n        y = np.arcsinh(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"asinh_fp8x23\"\n        make_test([x], y, \"input_0.asinh()\", name)\n\n    @staticmethod\n    def asinh_fp16x16():\n        x = np.random.uniform(1, 5, (2, 2)).astype(np.float64)\n        y = np.arcsinh(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"asinh_fp16x16\"\n        make_test([x], y, \"input_0.asinh()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/atan.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Atan(RunAll):\n    @staticmethod\n    def atan_fp8x23():\n        x = np.random.uniform(-10, 127, (2, 2)).astype(np.float64)\n        y = np.arctan(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"atan_fp8x23\"\n        make_test([x], y, \"input_0.atan()\", name)\n\n    @staticmethod\n    def atan_fp16x16():\n        x = np.random.uniform(-10, 127, (2, 2)).astype(np.float64)\n        y = np.arctan(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"atan_fp16x16\"\n        make_test([x], y, \"input_0.atan()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/binarizer.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_node, make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Binarizer(RunAll):\n\n    @staticmethod\n    def binarizer_fp8x23():\n        x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n        threshold = np.float64(1)\n        y = (x > threshold).astype(np.float64)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"binarizer_fp8x23\"\n        make_node([x], [y], name)\n        make_test([x], y, \"TensorTrait::binarizer(@input_0, Option::Some(FixedTrait::new(8388608, false));\", name)\n\n    \n    @staticmethod\n    def binarizer_fp16x16():\n        x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n        threshold = np.float64(1)\n        y = (x > threshold).astype(np.float64)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"binarizer_fp16x16\"\n        make_node([x], [y], name)\n        make_test([x], y, \"TensorTrait::binarizer(@input_0, Option::Some(FixedTrait::new(65536, false));\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/blackman_window.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait, get_data_statement\n\ndef blackman_window(size, output_datatype=None, periodic=None) -> np.ndarray:  # type: ignore\n    if periodic == 1:\n        N_1 = size\n    else:\n        N_1 = size - 1\n    ni = np.arange(size, dtype=output_datatype)\n    alpha = 0.42\n    beta = 0.08\n    y = np.cos((ni * (np.float64(np.pi).astype(output_datatype) * 2)) / N_1).astype(output_datatype) * (-0.5)\n    y += np.cos((ni * (np.float64(np.pi).astype(output_datatype) * 4)) / N_1) * beta\n    y += alpha\n    return y.astype(output_datatype)\n\nclass Blackman_window(RunAll):\n     \n    @staticmethod\n    # We test here with fp8x23 implementation.\n    def fp8x23():\n        args = [3]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP8x23), Dtype.FP8x23)\n        y = blackman_window(*args, np.float64)\n        \n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        # Define the name of the generated folder. \n        name = \"blackman_window_fp8x23\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::blackman_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with fp16x16 implementation.\n    def fp16x16():\n        print(get_data_statement(to_fp(np.array([np.pi]).flatten(), FixedImpl.FP16x16), Dtype.FP16x16))\n        args = [3]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP16x16), Dtype.FP16x16)\n        y = blackman_window(*args, np.float16, 1)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        \n        # Define the name of the generated folder. \n        name = \"blackman_window_fp16x16\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::blackman_window({','.join(args_str)}, Option::Some(1))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    # @staticmethod\n    # # We test here with i8 implementation.\n    # def i8():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I8))\n    #     args = [5]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I8)\n    #     y = blackman_window(*args, np.int8)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I8, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"blackman_window_i8\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::blackman_window({','.join(args_str)}, Option::Some(1))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n    \n    # @staticmethod\n    # # We test here with i32 implementation.\n    # def i32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I32)\n    #     y = blackman_window(*args, np.int32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"blackman_window_i32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::blackman_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n     \n    # @staticmethod\n    # # We test here with u32 implementation.\n    # def u32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.U32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.U32)\n    #     y = blackman_window(*args, np.uint32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.U32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"blackman_window_u32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::blackman_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n        "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/ceil.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nclass Ceil(RunAll):\n   \n    @staticmethod\n    def ceil_fp8x23():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.ceil(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        name = \"ceil_fp8x23\"\n        make_test([x], y, \"input_0.ceil()\", name)\n     \n    @staticmethod\n    def ceil_fp16x16():\n        x = np.random.uniform(-1, 1, (2, 2)).astype(np.float64)\n        y = np.ceil(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"ceil_fp16x16\"\n        make_test([x], y, \"input_0.ceil()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/clip.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Clip(RunAll):\n    @staticmethod\n    def clip_u32():\n        def clip_2D():\n            x = np.random.randint(0, 255, (2, 4)).astype(np.uint32)\n            y = np.clip(x, np.uint32(10), np.uint32(20))\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"clip_u32_2d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(10_u32), Option::Some(20_u32))\", name)\n\n        def clip_3D():\n            x = np.random.randint(0, 255, (20, 10, 5)).astype(np.uint32)\n            y = np.clip(x, np.uint32(10), np.uint32(20))\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"clip_u32_3d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(10_u32), Option::Some(20_u32))\", name)\n\n        clip_2D()\n        clip_3D()\n\n    @staticmethod\n    def clip_i32():\n        def clip_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int32)\n            y = np.clip(x, np.int32(-10), np.int32(20))\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"clip_i32_2d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(-10_i32), Option::Some(20_i32))\", name)\n\n        def clip_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int32)\n            y = np.clip(x, np.int32(-10), np.int32(20))\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"clip_i32_3d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(-10_i32), Option::Some(20_i32))\", name)\n\n\n        clip_2D()\n        clip_3D()\n\n    @staticmethod\n    def clip_i8():\n        def clip_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int8)\n            y = np.clip(x, np.int8(-10), np.int8(20))\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"clip_i8_2d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(-10_i8), Option::Some(20_i8))\", name)\n\n        def clip_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int8)\n            y = np.clip(x, np.int8(-10), np.int8(20))\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"clip_i8_3d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(-10_i8), Option::Some(20_i8))\", name)\n\n        clip_2D()\n        clip_3D()\n\n    @staticmethod\n    def clip_fp8x23():\n        def clip_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.clip(x, to_fp(np.int64(-10), FixedImpl.FP8x23), to_fp(np.int64(20), FixedImpl.FP8x23))\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"clip_fp8x23_2d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(FP8x23 { mag: 83886080, sign: true }), Option::Some(FP8x23 { mag: 167772160, sign: false }))\", name)\n\n        def clip_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.clip(x, to_fp(np.int64(-10), FixedImpl.FP8x23), to_fp(np.int64(20), FixedImpl.FP8x23))\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"clip_fp8x23_3d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(FP8x23 { mag: 83886080, sign: true }), Option::Some(FP8x23 { mag: 167772160, sign: false }))\", name)\n\n        clip_2D()\n        clip_3D()\n\n    @staticmethod\n    def clip_fp16x16():\n        def clip_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.clip(x, to_fp(np.int64(-10), FixedImpl.FP16x16), to_fp(np.int64(20), FixedImpl.FP16x16))\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"clip_fp16x16_2d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(FP16x16 { mag: 655360, sign: true }), Option::Some(FP16x16 { mag: 1310720, sign: false }))\", name)\n\n        def clip_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.clip(x, to_fp(np.int64(-10), FixedImpl.FP16x16), to_fp(np.int64(20), FixedImpl.FP16x16))\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"clip_fp16x16_3d\"\n            make_test(\n                [x], y, \"input_0.clip(Option::Some(FP16x16 { mag: 655360, sign: true }), Option::Some(FP16x16 { mag: 1310720, sign: false }))\", name)\n\n        clip_2D()\n        clip_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/col2im.py",
        "content": "\n\nimport numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef col2im(data, image_shape, block_shape, dilations=None, pads=None, strides=None):  # type: ignore\n    if dilations is None:\n        dilations = [1 for s in image_shape]\n    if pads is None:\n        pads = [0 for s in image_shape] * 2\n    if strides is None:\n        strides = [1 for s in image_shape]\n    bl = np.prod(block_shape)\n    C = data.shape[1] // bl\n    data = data.reshape(data.shape[:1] + (C,) + (bl,) + data.shape[2:])\n    ks = tuple(block_shape)\n    res = None\n    for n in range(data.shape[0]):\n        for c in range(data.shape[1]):\n            out = col2im_naive_implementation(\n                data[n, c, ...], image_shape, ks, dilations, pads, strides\n            )\n            if res is None:\n                new_shape = data.shape[:2] + out.shape\n                res = np.empty(new_shape, dtype=data.dtype)\n            res[n, c, ...] = out\n    return (res,)  # type: ignore\n\ndef _get_indices(i, shape):\n    res = np.empty((len(shape),), dtype=np.int64)\n    k = len(shape) - 1\n    while k > 0:\n        m = i % shape[k]\n        res[k] = m\n        i -= m\n        i /= shape[k]\n        k -= 1\n    res[0] = i\n    return res\n\ndef _col2im_shape_check(X, output_shape, kernel_shape, dilations, pads, strides):  # type: ignore\n    n_input_plane = X.shape[0]\n\n    kernel_size = np.prod(kernel_shape)\n\n    if n_input_plane % kernel_size != 0:\n        raise ValueError(\n            f\"Expected size of input's dimension 1 to be divisible by the \"\n            f\"product of kernel_size={kernel_size}, \"\n            f\"but got input.size(1)={n_input_plane} \"\n            f\"and kernel_shape={kernel_shape}, X.shape={X.shape}, output_shape={output_shape}.\"\n        )\n\n    input_length = X.shape[1]\n    n_dims = len(output_shape)\n    n_blocks = []\n\n    \n    for i in range(n_dims):\n        n_block = (\n            output_shape[i]\n            + pads[i, :].sum()\n            - dilations[i] * (kernel_shape[i] - 1)\n            - 1\n        ) // strides[i] + 1\n        n_blocks.append(n_block)\n\n    \n    block_size = np.prod(n_blocks)\n    if input_length != block_size:\n        raise ValueError(\n            f\"Given n_input_plane={n_input_plane}, X.shape={X.shape}, \"\n            f\"output_shape={output_shape}, kernel_shape={kernel_shape}, \"\n            f\"dilations={dilations}, pads={pads}, strides={strides}, \"\n            f\"expected size of input's dimension 2 to match the calculated number of \"\n            f\"sliding blocks {n_blocks} = {block_size}, \"\n            f\"but got input.size(2)={input_length}.\",\n        )\n\n\ndef col2im_naive_implementation(data, image_shape, kernel_shape, dilations, pads, strides):  # type: ignore\n\n    n_dims = len(pads) // 2\n    new_pads = np.array([(pads[i], pads[i + n_dims]) for i in range(n_dims)])\n    _col2im_shape_check(data, image_shape, kernel_shape, dilations, new_pads, strides)\n\n    data_col = data\n    data_im = np.zeros(image_shape, dtype=data.dtype)\n\n    dim_col = []\n    for i in range(n_dims):\n        col = (\n            image_shape[i]\n            + new_pads[i, :].sum()\n            - (dilations[i] * (kernel_shape[i] - 1) + 1)\n        ) // strides[i] + 1\n        dim_col.append(col) \n    kernel_size = np.prod(kernel_shape)\n    col_size = np.prod(dim_col)\n    for c_col in range(kernel_size):\n        offset = _get_indices(c_col, kernel_shape)     \n\n        for col in range(col_size):\n            \n            ind_col = _get_indices(col, dim_col)\n            ind_im = []\n            for i in range(n_dims):\n                ind = (\n                    ind_col[i] * strides[i] - new_pads[i, 0] + offset[i] * dilations[i]\n                )\n                ind_im.append(ind)\n            if not _is_out(ind_im, data_im.shape):\n                data_im[tuple(ind_im)] += data_col[c_col, col]\n\n\n    return data_im\n\n\ndef _is_out(ind, shape):  \n    for i, s in zip(ind, shape):\n        if i < 0:\n            return True\n        if i >= s:\n            return True\n    return False\n    \n\n\nclass Col2im(RunAll):\n\n    @staticmethod\n    def export_col2im() -> None:\n        x = np.array(\n            [\n                [\n                    [1.0, 6.0, 11.0, 16.0, 21.0],  # (1, 5, 5)\n                    [2.0, 7.0, 12.0, 17.0, 22.0],\n                    [3.0, 8.0, 13.0, 18.0, 23.0],\n                    [4.0, 9.0, 14.0, 19.0, 24.0],\n                    [5.0, 0.0, 15.0, 20.0, 25.0],\n                ]\n            ]\n        ).astype(np.float32)\n\n        image_shape = np.array([5, 5]).astype(np.int64)\n        block_shape = np.array([1, 5]).astype(np.int64)\n    \n        y = col2im(x,image_shape,block_shape)\n        y = np.array(y[0])\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"col2im\"\n        func_sig = \"NNTrait::col2im(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"array![5, 5].span(),\"\n        func_sig += \"array![1, 5].span(),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x], y, func_sig, name, Trait.NN)\n        \n\n    @staticmethod\n    def export_col2im_strides() -> None:\n        x = np.array(\n            [\n                [\n                    [0.0, 0.0, 0.0, 0.0],  # (1, 9, 4)\n                    [1.0, 1.0, 1.0, 1.0],\n                    [1.0, 1.0, 1.0, 1.0],\n                    [1.0, 1.0, 1.0, 1.0],\n                    [0.0, 0.0, 0.0, 0.0],\n                    [0.0, 0.0, 0.0, 0.0],\n                    [0.0, 0.0, 0.0, 0.0],\n                    [1.0, 1.0, 1.0, 1.0],\n                    [0.0, 0.0, 0.0, 0.0],\n                ]\n            ]\n        ).astype(np.float32)\n        image_shape = np.array([5, 5]).astype(np.int64)\n        block_shape = np.array([3, 3]).astype(np.int64)\n\n        y = col2im(x,image_shape,block_shape,strides=[2, 2])\n        y = np.array(y[0])\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"col2im_strides\"\n        func_sig = \"NNTrait::col2im(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"array![5, 5].span(),\"\n        func_sig += \"array![3, 3].span(),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![2, 2].span()))\"\n        make_test(\n            [x], y, func_sig, name, Trait.NN)\n\n    @staticmethod\n    def export_col2im_pads() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        1.0, 6.0, 11.0, 16.0, 21.0, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71,\n                    ],  # (1, 5, 15)\n                    [\n                        2.0, 7.0, 12.0, 17.0, 22.0, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72,\n                    ],\n                    [\n                        3.0, 8.0, 13.0, 18.0, 23.0, 28, 33, 38, 43, 48, 53, 58, 63, 68, 73,\n                    ],\n                    [\n                        4.0, 9.0, 14.0, 19.0, 24.0, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74,\n                    ],\n                    [\n                        5.0, 10.0, 15.0, 20.0, 25.0, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75,\n                    ],\n                ]\n            ]\n        ).astype(np.float32)\n        image_shape = np.array([5, 5]).astype(np.int64)\n        block_shape = np.array([1, 5]).astype(np.int64)\n\n        y = col2im(x,image_shape,block_shape,pads=[0, 1, 0, 1])\n        y = np.array(y[0])\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"col2im_pads\"\n        func_sig = \"NNTrait::col2im(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"array![5, 5].span(),\"\n        func_sig += \"array![1, 5].span(),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![0, 1, 0, 1].span()),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_col2im_dilations() -> None:\n        x = np.array(\n            [\n                [\n                    [1.0, 5.0, 9.0, 13.0, 17],  # (1, 4, 5)\n                    [2.0, 6.0, 10.0, 14.0, 18],\n                    [3.0, 7.0, 11.0, 15.0, 19],\n                    [4.0, 8.0, 12.0, 16.0, 20],\n                ]\n            ]\n        ).astype(np.float32)\n        image_shape = np.array([6, 6]).astype(np.int64)\n        block_shape = np.array([2, 2]).astype(np.int64)\n\n\n        y = col2im(x,image_shape,block_shape, dilations=[1, 5])\n        y = np.array(y[0])\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"col2im_dilations\"\n        func_sig = \"NNTrait::col2im(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"array![6, 6].span(),\"\n        func_sig += \"array![2, 2].span(),\"\n        func_sig += \"Option::Some(array![1, 5].span()),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_col2im_5D() -> None:\n        x = np.array(\n            [\n                [\n                    [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56],  # (1, 10, 12)\n                    [2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57],\n                    [3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58],\n                    [4, 9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59],\n                    [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],\n                    [61, 66, 71, 76, 81, 86, 91, 96, 101, 106, 111, 116],\n                    [62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117],\n                    [63, 68, 73, 78, 83, 88, 93, 98, 103, 108, 113, 118],\n                    [64, 69, 74, 79, 84, 89, 94, 99, 104, 109, 114, 119],\n                    [65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120],\n                ]\n            ]\n        ).astype(np.float32)\n        image_shape = np.array([3, 4, 5]).astype(np.int64)\n        block_shape = np.array([1, 1, 5]).astype(np.int64)\n    \n        y = col2im(x,image_shape,block_shape)\n        y = np.array(y[0])\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"col2im_5D\"\n        func_sig = \"NNTrait::col2im(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"array![3, 4, 5].span(),\"\n        func_sig += \"array![1, 1, 5].span(),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x], y, func_sig, name, Trait.NN)\n\n\n        "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/compress.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nclass Compress(RunAll):\n\n    @staticmethod\n    def compress_fp16x16():\n            \n        def compress_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=0)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"compress_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(0))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.arange(0,180).reshape(3,4,3,5).astype(np.int64)\n                x2 = np.array([1, 1, 1, 0]).astype(np.int64)\n                y = x1.compress(x2, axis=1)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"compress_fp16x16_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(1))\", \n                    name= name)\n                \n            def axis2():\n                x1 = np.arange(0,48).reshape(4,3,4).astype(np.int64)\n                x2 = np.array([1, 0, 1, 1]).astype(np.int64)\n                y = x1.compress(x2, axis=2)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"compress_fp16x16_3d_axis2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            def axis3():\n                x1 = np.arange(0,96).reshape(4,3,4, 2).astype(np.int64)\n                x2 = np.array([1, 0]).astype(np.int64)\n                y = x1.compress(x2, axis=3)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"compress_fp16x16_3d_axis3\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(3))\", \n                    name= name)\n                \n            def noaxis():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.array([1, 0, 1, 0, 1, 1, 1, 1, 1]).astype(np.int64)\n                y = x1.compress(x2)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"compress_fp16x16_3d_noaxis\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::None(()))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis2()\n            axis3()\n            noaxis()\n        compress_3D()\n\n    @staticmethod\n    def compress_fp8x23():\n            \n        def compress_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=0)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"compress_fp8x23_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(0))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())  \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"compress_fp8x23_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(1))\", \n                    name= name)\n                \n            def axis2():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"compress_fp8x23_3d_axis2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis2()\n        compress_3D()\n\n    @staticmethod\n    def compress_i8():\n            \n        def compress_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int8)\n                x2 = np.array([0, 1, 1]).astype(np.uint8)\n                y = x1.compress(x2, axis=0)\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"compress_i8_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(0))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int8)\n                x2 = np.array([0, 1, 1]).astype(np.uint8)\n                y = x1.compress(x2, axis=1)\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"compress_i8_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(1))\", \n                    name= name)\n                \n            def axis2():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int8)\n                x2 = np.array([0, 1, 1]).astype(np.uint8)\n                y = x1.compress(x2, axis=2)\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"compress_i8_3d_axis2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis2()\n        compress_3D()\n\n    \n    @staticmethod\n    def compress_i32():\n            \n        def compress_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int32)\n                x2 = np.array([0, 1, 1]).astype(np.int32)\n                y = x1.compress(x2, axis=0)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"compress_i32_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(0))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int32)\n                x2 = np.array([0, 1, 1]).astype(np.int32)\n                y = x1.compress(x2, axis=1)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"compress_i32_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(1))\", \n                    name= name)\n                \n            def axis2():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int32)\n                x2 = np.array([0, 1, 1]).astype(np.int32)\n                y = x1.compress(x2, axis=2)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"compress_i32_3d_axis2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis2()\n        compress_3D()\n\n    @staticmethod\n    def compress_u32():\n            \n        def compress_3D():\n            def default():\n                x1 = np.arange(0,48).reshape(4,4,3).astype(np.uint32)\n                x2 = np.array([1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=0)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"compress_u32_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(0))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.arange(0,36).reshape(3,4,3).astype(np.uint32)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=1)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"compress_u32_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(1))\", \n                    name= name)\n                \n            def axis2():\n                x1 = np.arange(0,48).reshape(3,4,4).astype(np.uint32)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=2)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"compress_u32_3d_axis2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            def axis2_2():\n                x1 = np.arange(0,60).reshape(3,4,5).astype(np.uint32)\n                x2 = np.array([0, 1, 1]).astype(np.uint32)\n                y = x1.compress(x2, axis=2)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"compress_u32_3d_axis2_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(2))\", \n                    name= name)\n                \n            def axis3():\n                x1 = np.arange(0,270).reshape(3,3,5,6).astype(np.uint32)\n                x2 = np.array([0, 1, 1,1,0,1]).astype(np.uint32)\n                y = x1.compress(x2, axis=3)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"compress_u32_3d_axis3\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.compress(condition:input_1, axis:Option::Some(3))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis2()\n            axis2_2()\n            axis3()\n        compress_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/concat.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n# 687\nclass Concat(RunAll):\n    @staticmethod\n    def concat_u32():\n\n        def concat_1D():\n            x1 = np.arange(0,3).astype(np.uint32)\n            x2 = np.arange(3,6).astype(np.uint32)\n            y = np.concatenate((x1, x2))\n\n            x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"concat_u32_1d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n                    \n            \n        def concat_2D():\n            x1 = np.arange(0,4).astype(np.uint32).reshape(2,2)\n            x2 = np.arange(4,8).astype(np.uint32).reshape(2,2)\n            y = np.concatenate((x1, x2), axis=0)\n\n            x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"concat_u32_2d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n            \n        def concat_3D():\n            def default():\n                x1 = np.arange(0,27).astype(np.uint32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.uint32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=0)\n\n                x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"concat_u32_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_1():\n                x1 = np.arange(0,27).astype(np.uint32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.uint32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=1)\n\n                x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"concat_u32_3d_axis_1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_2():\n                x1 = np.arange(0,27).astype(np.uint32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.uint32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=2)\n\n                x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"concat_u32_3d_axis_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def three_tensors_axis_1():\n                x1 = np.arange(0,27).astype(np.uint32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.uint32).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.uint32).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=1)\n\n                x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"concat_u32_3d_three_tensors_axis_1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n                \n            def three_tensors_axis_2():\n                x1 = np.arange(0,27).astype(np.uint32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.uint32).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.uint32).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=2)\n\n                x1 = Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"concat_u32_3d_three_tensors_axis_2\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            default()\n            axis_1()\n            axis_2()\n            three_tensors_axis_1()\n            three_tensors_axis_2()\n    \n        concat_1D()\n        concat_2D()\n        concat_3D()\n\n    @staticmethod\n    def concat_i32():\n        def concat_1D():\n            x1 = np.arange(0,3).astype(np.int32)\n            x2 = np.arange(3,6).astype(np.int32)\n            y = np.concatenate((x1, x2))\n\n            x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"concat_i32_1d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR.TENSOR)\n                    \n            \n        def concat_2D():\n            x1 = np.arange(0,4).astype(np.int32).reshape(2,2)\n            x2 = np.arange(4,8).astype(np.int32).reshape(2,2)\n            y = np.concatenate((x1, x2), axis=0)\n\n            x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"concat_i32_2d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n            \n        def concat_3D():\n            def default():\n                x1 = np.arange(0,27).astype(np.int32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=0)\n\n                x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"concat_i32_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_1():\n                x1 = np.arange(0,27).astype(np.int32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=1)\n\n                x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"concat_i32_3d_axis_1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_2():\n                x1 = np.arange(0,27).astype(np.int32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int32).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=2)\n\n                x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"concat_i32_3d_axis_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def three_tensors_axis_1():\n                x1 = np.arange(0,27).astype(np.int32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int32).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int32).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=1)\n\n                x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.I32, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"concat_i32_3d_three_tensors_axis_1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n                \n            def three_tensors_axis_2():\n                x1 = np.arange(0,27).astype(np.int32).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int32).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int32).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=2)\n\n                x1 = Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.I32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.I32, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"concat_i32_3d_three_tensors_axis_2\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            default()\n            axis_1()\n            axis_2()\n            three_tensors_axis_1()\n            three_tensors_axis_2()\n\n        concat_1D()\n        concat_2D()\n        concat_3D()\n        \n    @staticmethod\n    def concat_i8():\n        def concat_1D():\n            x1 = np.arange(0,3).astype(np.int8)\n            x2 = np.arange(3,6).astype(np.int8)\n            y = np.concatenate((x1, x2))\n\n            x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"concat_i8_1d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR.TENSOR)\n                    \n            \n        def concat_2D():\n            x1 = np.arange(0,4).astype(np.int8).reshape(2,2)\n            x2 = np.arange(4,8).astype(np.int8).reshape(2,2)\n            y = np.concatenate((x1, x2), axis=0)\n\n            x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n            x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"concat_i8_2d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n            \n        def concat_3D():\n            def default():\n                x1 = np.arange(0,27).astype(np.int8).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int8).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=0)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"concat_i8_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_1():\n                x1 = np.arange(0,27).astype(np.int8).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int8).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"concat_i8_3d_axis_1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_2():\n                x1 = np.arange(0,27).astype(np.int8).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int8).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"concat_i8_3d_axis_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def three_tensors_axis_1():\n                x1 = np.arange(0,27).astype(np.int8).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int8).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int8).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.FP8x23, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"concat_i8_3d_three_tensors_axis_1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n                \n            def three_tensors_axis_2():\n                x1 = np.arange(0,27).astype(np.int8).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int8).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int8).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.FP8x23, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.FP8x23, x3.shape, x3.flatten())\n\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"concat_i8_3d_three_tensors_axis_2\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            default()\n            axis_1()\n            axis_2()\n            three_tensors_axis_1()\n            three_tensors_axis_2()\n\n        concat_1D()\n        concat_2D()\n        concat_3D()\n        \n    @staticmethod\n    def concat_fp8x23():\n        def concat_1D():\n            x1 = np.arange(0,3).astype(np.int64)\n            x2 = np.arange(3,6).astype(np.int64)\n            y = np.concatenate((x1, x2))\n\n            x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))  \n            x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n            name = \"concat_fp8x23_1d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR.TENSOR)\n                    \n            \n        def concat_2D():\n            x1 = np.arange(0,4).astype(np.int64).reshape(2,2)\n            x2 = np.arange(4,8).astype(np.int64).reshape(2,2)\n            y = np.concatenate((x1, x2), axis=0)\n\n            x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n            x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n            name = \"concat_fp8x23_2d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n            \n        def concat_3D():\n            def default():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=0)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n                y = Tensor(Dtype.FP8x23, y.shape,to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"concat_fp8x23_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_1():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"concat_fp8x23_3d_axis_1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_2():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"concat_fp8x23_3d_axis_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def three_tensors_axis_1():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int64).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n                x3 = Tensor(Dtype.FP8x23, x3.shape,to_fp(\n                x3.flatten(), FixedImpl.FP8x23)) \n\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"concat_fp8x23_3d_three_tensors_axis_1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n                \n            def three_tensors_axis_2():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int64).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP8x23)) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(\n                x3.flatten(), FixedImpl.FP8x23)) \n\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"concat_fp8x23_3d_three_tensors_axis_2\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            default()\n            axis_1()\n            axis_2()\n            three_tensors_axis_1()\n            three_tensors_axis_2()\n\n        concat_1D()\n        concat_2D()\n        concat_3D()\n    \n    staticmethod\n    def concat_fp16x16():\n        def concat_1D():\n            x1 = np.arange(0,3).astype(np.int64)\n            x2 = np.arange(3,6).astype(np.int64)\n            y = np.concatenate((x1, x2))\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))  \n            x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"concat_fp16x16_1d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR.TENSOR)\n                    \n            \n        def concat_2D():\n            x1 = np.arange(0,4).astype(np.int64).reshape(2,2)\n            x2 = np.arange(4,8).astype(np.int64).reshape(2,2)\n            y = np.concatenate((x1, x2), axis=0)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"concat_fp16x16_2d\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                name= name, trait= Trait.TENSOR)\n            \n        def concat_3D():\n            def default():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=0)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"concat_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 0)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_1():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=1)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n                y = Tensor(Dtype.FP16x16, y.shape ,to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"concat_fp16x16_3d_axis_1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def axis_2():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                y = np.concatenate((x1, x2), axis=2)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"concat_fp16x16_3d_axis_2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            def three_tensors_axis_1():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int64).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=1)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(\n                x3.flatten(), FixedImpl.FP16x16)) \n\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"concat_fp16x16_3d_three_tensors_axis_1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 1)\", \n                    name= name, trait= Trait.TENSOR)\n                \n            def three_tensors_axis_2():\n                x1 = np.arange(0,27).astype(np.int64).reshape(3,3,3)\n                x2 = np.arange(27,54).astype(np.int64).reshape(3,3,3)\n                x3 = np.arange(54,81).astype(np.int64).reshape(3,3,3)\n\n                y = np.concatenate((x1, x2, x3), axis=2)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(\n                x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(\n                x2.flatten(), FixedImpl.FP16x16)) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(\n                x3.flatten(), FixedImpl.FP16x16)) \n\n                y = Tensor(Dtype.FP16x16, y.shape,to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"concat_fp16x16_3d_three_tensors_axis_2\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"TensorTrait::concat(array![input_0, input_1, input_2].span(), 2)\", \n                    name= name, trait= Trait.TENSOR)\n\n            default()\n            axis_1()\n            axis_2()\n            three_tensors_axis_1()\n            three_tensors_axis_2()\n\n        concat_1D()\n        concat_2D()\n        concat_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/concat_from_sequence.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nclass Concat_from_sequence(RunAll):\n\n    @staticmethod\n    def concat_from_sequence_u32():\n        def new_axis_zero():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.U32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_u32_new_axis_zero\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0))\", name, Trait.SEQUENCE)\n\n        def new_axis_one():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(1)\n\n            concatenated_tensor = np.stack(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.U32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_u32_new_axis_one\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1))\", name, Trait.SEQUENCE)\n\n        def new_axis_default():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.U32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_u32_new_axis_default\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()))\", name, Trait.SEQUENCE)\n\n        new_axis_zero()\n        new_axis_one()\n        new_axis_default()\n\n\n    @staticmethod\n    def concat_from_sequence_i32():\n        def new_axis_zero():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i32_new_axis_zero\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0))\", name, Trait.SEQUENCE)\n\n        def new_axis_one():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(1)\n\n            concatenated_tensor = np.stack(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i32_new_axis_one\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1))\", name, Trait.SEQUENCE)\n\n        def new_axis_default():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I32, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i32_new_axis_default\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()))\", name, Trait.SEQUENCE)\n\n        new_axis_zero()\n        new_axis_one()\n        new_axis_default()\n\n\n    @staticmethod\n    def concat_from_sequence_i8():\n        def new_axis_zero():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I8, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i8_new_axis_zero\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0))\", name, Trait.SEQUENCE)\n\n        def new_axis_one():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(1)\n\n            concatenated_tensor = np.stack(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I8, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i8_new_axis_one\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1))\", name, Trait.SEQUENCE)\n\n        def new_axis_default():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.I8, concatenated_tensor.shape, concatenated_tensor.flatten())\n\n            name = \"concat_from_sequence_i8_new_axis_default\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()))\", name, Trait.SEQUENCE)\n\n        new_axis_zero()\n        new_axis_one()\n        new_axis_default()\n\n\n    @staticmethod\n    def concat_from_sequence_fp8x23():\n        def new_axis_zero():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP8x23, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP8x23))\n\n            name = \"concat_from_sequence_fp8x23_new_axis_zero\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0))\", name, Trait.SEQUENCE)\n\n        def new_axis_one():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(1)\n\n            concatenated_tensor = np.stack(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP8x23, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP8x23))\n\n            name = \"concat_from_sequence_fp8x23_new_axis_one\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1))\", name, Trait.SEQUENCE)\n\n        def new_axis_default():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP8x23, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP8x23))\n\n            name = \"concat_from_sequence_fp8x23_new_axis_default\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()))\", name, Trait.SEQUENCE)\n\n        new_axis_zero()\n        new_axis_one()\n        new_axis_default()\n\n\n    @staticmethod\n    def concat_from_sequence_fp16x16():\n        def new_axis_zero():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP16x16, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP16x16))\n\n            name = \"concat_from_sequence_fp16x16_new_axis_zero\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0))\", name, Trait.SEQUENCE)\n\n        def new_axis_one():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(1)\n\n            concatenated_tensor = np.stack(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP16x16, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP16x16))\n\n            name = \"concat_from_sequence_fp16x16_new_axis_one\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1))\", name, Trait.SEQUENCE)\n\n        def new_axis_default():\n            sequence = []\n            values_array = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n                sequence.append(tensor)\n                values_array.append(values)\n\n            axis = np.int32(1)\n            new_axis = np.uint32(0)\n\n            concatenated_tensor = np.concatenate(values_array, axis)\n            concatenated_tensor = Tensor(Dtype.FP16x16, concatenated_tensor.shape, to_fp(concatenated_tensor.flatten(), FixedImpl.FP16x16))\n\n            name = \"concat_from_sequence_fp16x16_new_axis_default\"\n            make_test([sequence], concatenated_tensor, \"SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()))\", name, Trait.SEQUENCE)\n\n        new_axis_zero()\n        new_axis_one()\n        new_axis_default()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/conv.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nimport numpy as np\n\ndef r_index_check(r_index, shape_out):\n    for i in range(len(r_index)):\n        if r_index[i] >= shape_out[i]:\n            return False\n    return True    \n\ndef stride(arr):\n    stride = np.zeros(len(arr))\n    acc = 1\n    for i in range(len(arr)):\n        stride[i] = acc\n        acc *= arr[-(i + 1)]\n    return np.flip(stride) \n        \ndef conv(\n        X,\n        W,\n        B=None,\n        auto_pad=None,\n        dilations=None,\n        group=None,\n        kernel_shape=None,\n        pads=None,\n        strides=None,\n):\n    if dilations is None:\n        dilations = [1 for s in X.shape[2:]]\n    if kernel_shape is None:\n        kernel_shape = W.shape[2:]\n    if pads is None:\n        pads = [0 for s in X.shape[2:]] * 2\n    if strides is None:\n        strides = [1 for s in X.shape[2:]]\n\n    if X.shape[1] != W.shape[1] * group or W.shape[0] % group != 0:\n        raise ValueError(\n            f\"Shape inconsistencies, X.shape={X.shape}, W.shape={W.shape}, group={group}, \"\n            f\"W should be {(W.shape[0], X.shape[1] // group, np.prod(W.shape[1:]) // X.shape[1] * group)}.\"\n        )\n    if group > 1:\n        res = []\n        td = 0\n        mg = W.shape[0] // group\n        dw = W.shape[1]\n\n        for b in range(X.shape[0]):\n            for g in range(group):\n                gx = X[b : b + 1, g * dw : (g + 1) * dw]\n                gw = W[g * mg : (g + 1) * mg]\n                try:\n                    cv = conv(\n                        gx,\n                        gw,\n                        None,\n                        auto_pad,\n                        dilations,\n                        1,\n                        kernel_shape,\n                        pads,\n                        strides,\n                    )\n                except (ValueError, RuntimeError) as e:\n                    raise ValueError(\n                        f\"Shape inconsistencies, X.shape={X.shape}, W.shape={W.shape}, group={g}/{group}, \"\n                        f\"gx.shape={gx.shape}, gw.shape={gw.shape}, auto_pad={auto_pad}, \"\n                        f\"dilations={dilations}, kernel_shape={kernel_shape}, pads={pads}, \"\n                        f\"strides={strides}.\"\n                    ) from e\n                if b == 0:\n                    td += cv.shape[1]\n                res.append((b, cv))\n\n        new_shape = [X.shape[0], *list(res[0][1].shape[1:])]\n\n        new_shape[1] = td\n        final = np.zeros(tuple(new_shape), dtype=res[0][1].dtype)\n        p = 0\n        for b, cv in res:\n            final[b : b + 1, p : p + cv.shape[1]] = cv\n            p += cv.shape[1]\n            if p >= final.shape[1]:\n                p = 0\n        if B is not None:\n            new_shape = [1 for s in final.shape]\n            new_shape[1] = B.shape[0]\n            b = B.reshape(tuple(new_shape))\n            final += b\n        return final\n\n    if dilations[0] != 1 or min(dilations) != max(dilations):\n        # Let's compute the dilated kernel.\n        nd = len(dilations)\n        new_kernel_shape = []\n        new_shape = list(W.shape[:-nd])\n        for i, d in enumerate(dilations):\n            di = len(W.shape) - nd + i\n            new_shape.append(W.shape[di] + (W.shape[di] - 1) * (d - 1))\n            new_kernel_shape.append(kernel_shape[i] + (kernel_shape[i] - 1) * (d - 1))\n        new_w = np.zeros(tuple(new_shape), dtype=W.dtype)\n        indices = [slice(0, new_w.shape[0]), slice(0, new_w.shape[1])]\n        for i, d in enumerate(dilations):\n            di = len(W.shape) - nd + i\n            indices.append(slice(0, new_w.shape[di], d))\n        new_w[tuple(indices)] = W\n        W = new_w\n        kernel_shape = new_kernel_shape\n\n    if auto_pad in {\"SAME_LOWER\", \"SAME_UPPER\", \"VALID\"}:\n        head = []\n        tail = []\n        for i in range(len(X.shape) - 2):\n            d = X.shape[i]\n            target_size = (d + strides[i] - 1) // strides[i]\n            pad_needed = (target_size - 1) * strides[i] + kernel_shape[i] - d\n            if auto_pad == \"SAME_LOWER\":\n                pad_head = (pad_needed + 1) // 2\n            else:\n                pad_head = pad_needed // 2\n            pad_tail = pad_needed - pad_head\n            head.append(pad_head)\n            tail.append(pad_tail)\n        pads = head + tail\n\n    if len(X.shape) == 3:\n        sN, sC, sH = X.shape\n        # M, C_group, kH, kW = W.shape\n        (kh,) = kernel_shape\n        (sth,) = strides\n\n        h_out = int(((sH - kh + pads[0] + pads[1]) / sth) + 1)\n\n        h0 = pads[0]\n        oh = -1 * (kh % 2)\n        bh = -h0\n        eh = h_out * sth\n        res = np.zeros((X.shape[0], W.shape[0], h_out))  # type: ignore[assignment]\n        if B is not None:\n            res[:, :, :] += B.reshape((1, -1, 1))  # type: ignore\n\n        for n in range(0, sN):\n            for nw in range(W.shape[0]):\n                for c in range(0, sC):\n                    w = W[nw : nw + 1, c : c + 1]\n                    for io in range(bh, eh, sth):\n                        hr = (io - bh) // sth\n                        if hr >= h_out:\n                            continue\n                        i = io + kh % 2\n                        ih1, ih2 = max(0, i + oh), min(i + oh + kh, sH)\n                        img = X[n : n + 1, c : c + 1, ih1:ih2]\n                        if img.shape != w.shape:\n                            jh1, jh2 = max(-oh - i, 0), min(kh, kh + sH - (i + oh + kh))\n                            w_ = w[:1, :1, jh1:jh2]\n                            \n                            if img.shape != w_.shape:\n                                raise RuntimeError(\n                                    f\"Unexpected shape {img.shape} != {w_.shape}, oh={oh}, \"\n                                    f\"i={i}, kh={kh}, sH={sH}, sth={sth}.\"\n                                )\n                            s = np.dot(img.reshape((1, -1)), w_.reshape((-1, 1)))[\n                                0, 0\n                            ]  # (img * w_).sum()\n                        else:\n                            s = np.dot(img.reshape((1, -1)), w.reshape((-1, 1)))[\n                                0, 0\n                            ]  # (img * w).sum()\n                        res[n, nw, hr] += s  # type: ignore\n\n        return res\n\n    if len(X.shape) == 4:\n        sN, sC, sH, sW = X.shape\n        # M, C_group, kH, kW = W.shape\n        kh, kw = kernel_shape\n        sth, stw = strides\n\n        h_out = int(((sH - kh + pads[0] + pads[2]) / sth) + 1)\n        w_out = int(((sW - kw + pads[1] + pads[3]) / stw) + 1)\n\n        h0, w0 = pads[0], pads[1]\n        oh, ow = -1 * (kh % 2), -1 * (kw % 2)\n        bh, bw = -h0, -w0\n        eh, ew = h_out * sth, w_out * stw\n        res = np.zeros((X.shape[0], W.shape[0], h_out, w_out))  # type: ignore[assignment]\n        if B is not None:\n            res[:, :, :, :] = B.reshape((1, -1, 1, 1))  # type: ignore\n\n        for n in range(0, sN):\n            for nw in range(W.shape[0]):\n                for c in range(0, sC):\n                    w = W[nw : nw + 1, c : c + 1]\n                    for io in range(bh, eh, sth):\n                        hr = (io - bh) // sth\n                        if hr >= h_out:\n                            continue\n                        i = io + kh % 2\n                        ih1, ih2 = max(0, i + oh), min(i + oh + kh, sH)\n                        for jo in range(bw, ew, stw):\n                            wr = (jo - bw) // stw\n                            if wr >= w_out:\n                                continue\n                            \n                            j = jo + kw % 2\n                            iw1, iw2 = max(0, j + ow), min(j + ow + kw, sW)\n                            img = X[n : n + 1, c : c + 1, ih1:ih2, iw1:iw2]\n\n                            if img.shape != w.shape:\n                                jh1, jh2 = max(-oh - i, 0), min(\n                                    kh, kh + sH - (i + oh + kh)\n                                )\n                                jw1, jw2 = max(-ow - j, 0), min(\n                                    kw, kw + sW - (j + ow + kw)\n                                )\n                                w_ = w[:1, :1, jh1:jh2, jw1:jw2]\n                                if img.shape != w_.shape:\n                                    raise RuntimeError(\n                                        f\"Unexpected shape {img.shape} != {w_.shape}, oh={oh}, ow={ow}, \"\n                                        f\"i={i}, j={j}, kh={kh}, kw={kw}, sH={sH}, sW={sW}, sth={sth}, stw={stw}.\"\n                                    )\n                                s = np.dot(img.reshape((1, -1)), w_.reshape((-1, 1)))[\n                                    0, 0\n                                ]  # (img * w_).sum()\n                            else:\n                                s = np.dot(img.reshape((1, -1)), w.reshape((-1, 1)))[\n                                    0, 0\n                                ]  # (img * w).sum()\n                            res[n, nw, hr, wr] += s  # type: ignore\n\n        return res\n\n    if len(X.shape) == 5:\n        sN, sC, sH, sW, sZ = X.shape\n        kh, kw, kz = kernel_shape\n        sth, stw, stz = strides\n\n        h_out = int(((sH - kh + pads[0] + pads[3]) / sth) + 1)\n        w_out = int(((sW - kw + pads[1] + pads[4]) / stw) + 1)\n        z_out = int(((sZ - kz + pads[2] + pads[5]) / stz) + 1)\n\n        h0, w0, z0 = pads[0], pads[1], pads[2]\n        oh, ow, oz = -1 * (kh % 2), -1 * (kw % 2), -1 * (kz % 2)\n        bh, bw, bz = -h0, -w0, -z0\n        eh, ew, ez = h_out * sth, w_out * stw, z_out * stz\n        res = np.zeros((X.shape[0], W.shape[0], h_out, w_out, z_out))  # type: ignore[assignment]\n        if B is not None:\n            res[:, :, :, :, :] = B.reshape((1, -1, 1, 1, 1))  # type: ignore\n\n        for n in range(0, sN):\n            for nw in range(W.shape[0]):\n                for c in range(0, sC):\n                    w = W[nw : nw + 1, c : c + 1]\n                    for io in range(bh, eh, sth):\n                        hr = (io - bh) // sth\n                        if hr >= h_out:\n                            continue\n                        i = io + kh % 2\n                        ih1, ih2 = max(0, i + oh), min(i + oh + kh, sH)\n                        for jo in range(bw, ew, stw):\n                            wr = (jo - bw) // stw\n                            if wr >= w_out:\n                                continue\n                            j = jo + kw % 2\n                            iw1, iw2 = max(0, j + ow), min(j + ow + kw, sW)\n                            for zo in range(bz, ez, stz):\n                                zr = (zo - bz) // stz\n                                if zr >= z_out:\n                                    continue\n                                z = zo + kz % 2\n                                iz1, iz2 = max(0, z + oz), min(z + oz + kz, sZ)\n                                img = X[n : n + 1, c : c + 1, ih1:ih2, iw1:iw2, iz1:iz2]\n                                \n                                ### ICI\n                                if img.shape != w.shape:\n                                    jh1, jh2 = max(-oh - i, 0), min(\n                                        kh, kh + sH - (i + oh + kh)\n                                    )\n                                    jw1, jw2 = max(-ow - j, 0), min(\n                                        kw, kw + sW - (j + ow + kw)\n                                    )\n                                    jz1, jz2 = max(-oz - z, 0), min(\n                                        kz, kz + sZ - (z + oz + kz)\n                                    )\n                                    w_ = w[:1, :1, jh1:jh2, jw1:jw2, jz1:jz2]\n                                    if img.shape != w_.shape:\n                                        raise RuntimeError(\n                                            f\"Unexpected shape {img.shape} != {w_.shape}, oh={oh}, ow={ow}, oz={oz}, \"\n                                            f\"i={i}, j={j}, z={z}, kh={kh}, kw={kw}, kz={kz}, \"\n                                            f\"sH={sH}, sW={sW}, sZ={sZ}, sth={sth}, stw={stw}, stz={stz}.\"\n                                        )\n                                        \n                                    s = np.dot(\n                                        img.reshape((1, -1)), w_.reshape((-1, 1))\n                                    )[\n                                        0, 0\n                                    ]  \n                                else:\n                                    \n                                    s = np.dot(\n                                        img.reshape((1, -1)), w.reshape((-1, 1))\n                                    )[\n                                        0, 0\n                                    ]  \n                                res[n, nw, hr, wr, zr] += s  # type: ignore\n\n        return res\n\n    else:\n        nd = len(X.shape[2:])\n        sN, sC = X.shape[:2]\n        \n        x_stride = stride(X.shape)\n        w_stride = stride(W.shape)\n        x_flatten = X.reshape(int(x_stride[0] * X.shape[0]))\n        \n        \n        shape_out = [int(((X.shape[2+i] - kernel_shape[i] + pads[i] + pads[i + nd]) / strides[i]) + 1) for i in range(nd)]\n        o_index = [-1 * (kernel_shape[i] % 2) for i in range(nd)]\n        b_index = [-pads[i] for i in range(nd)]\n        e_index = [shape_out[i] * strides[i] for i in range(nd)]\n        \n        \n        range_len = [e_index[i] - b_index[i] / strides[i] for i in range(nd)]\n        range_stride = stride(range_len)\n        \n        res_shape = [X.shape[0], W.shape[0]] + shape_out\n        res = np.zeros(res_shape) \n        \n        res_strides = stride(res_shape)\n        if B is not None:\n            res[:, :, :, :, :] = B.reshape((1, -1, 1, 1, 1))  # type: ignore\n\n        for n in range(0, sN):\n            for nw in range(W.shape[0]):\n                for c in range(0, sC):\n                    w = W[nw : nw + 1, c : c + 1]\n                    for i in range(int(range_len[0] * range_stride[0])):\n                        flatten_index = i\n                        io_index = np.zeros(nd)\n                        r_index = np.zeros(nd)\n                        for nx in range(nd):    \n                            n_index, rem = divmod(flatten_index, range_stride[nx])\n                            flatten_index = rem\n                            io_index[nx] = n_index * strides[nx] + b_index[nx]\n                            r_index[nx] = n_index\n                        if r_index_check(r_index, shape_out):\n                            indices = [io_index[nx] + (kernel_shape[nx] % 2) for nx in range(nd)]\n                            i1_index = [max(0, indices[nx] + o_index[nx]) for nx in range(nd)]\n                            i2_index = [min(X.shape[2 + nx], indices[nx] + o_index[nx] + kernel_shape[nx]) for nx in range(nd)]\n                            idiff_index = [int(i2_index[nx] - i1_index[nx]) for nx in range(nd - 1)]\n                        \n                            i_stride = stride(idiff_index)\n                            img = []\n                            for ii in range(int(i_stride[0] * idiff_index[0])):\n                                flatten_index = ii\n                                start = n * x_stride[0] + c * x_stride[1]\n                                for nx in range(nd - 1):    \n                                    ii_index, rem = divmod(flatten_index, i_stride[nx])\n                                    flatten_index = rem\n                                    start += (i1_index[nx] + ii_index) * x_stride[2 + nx]\n                                start += i1_index[nd-1]   \n                                end = start + (i2_index[nd-1] - i1_index[nd-1])\n                                img.append(x_flatten[int(start):int(end)])\n                            img_shape = [1, 1] + idiff_index\n                            w = w.reshape(np.prod(kernel_shape))\n                            if len(img) != len(w):\n                                j1_index = [max(0, -indices[nx] - o_index[nx]) for nx in range(nd)]\n                                j2_index = [min(X.shape[2 + nx] - indices[nx] - o_index[nx], kernel_shape[nx]) for nx in range(nd)]\n                                jdiff_index = [j2_index[nx] - j1_index[nx] for nx in range(nd - 1)]\n\n\n                                w_ = []\n\n                                j_stride = stride(jdiff_index)\n\n                                for jj in range(int(j_stride[0] * jdiff_index[0])):\n                                    flatten_index = jj\n                                    start = 0\n                                    for nx in range(nd):    \n                                        jj_index, rem = divmod(flatten_index, range_stride[nx])\n                                        flatten_index = rem\n                                        start += (j1_index[nx] + jj_index) * kernel_shape[nx]\n                                    w_.append(w[int(start + j1_index[-1]):int(start + j1_index[-1] + j2_index[nd-1] - j1_index[nd-1])])\n                                \n                                \n                                img = np.array(img)                                \n                                s = np.dot(\n                                    np.array(img).reshape((1, -1)), np.array(w_).reshape((-1, 1))\n                                )[\n                                    0, 0\n                                ]  \n                            else:\n                                img = np.array(img)\n                                s = np.dot(\n                                    np.array(img).reshape((1, -1)), np.array(w_).reshape((-1, 1))\n                                )[\n                                    0, 0\n                                ]  \n\n                            res_index = []\n                            for nx in range(nd):\n                                res_index.append(int(r_index[nx]))\n\n                            index = tuple([n, nw]) + tuple(res_index)\n                            res[index] += s  # type: ignore\n            return res\n\n\n\nclass Conv(RunAll):\n    \n    @staticmethod\n    def export_conv_1D_no_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        0.0, 1.0, 2.0, 3.0, 4.0\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        1.0, 1.0, 1.0\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        \n        y = conv(x, w, group = 1)\n        \n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n\n        name = \"conv_1D_no_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n    \n    @staticmethod\n    def export_conv_1D_with_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        0.0, 1.0, 2.0, 3.0, 4.0\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        1.0, 1.0, 1.0\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        \n        y = conv(x, w, group = 1, pads=[1, 1])\n        \n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n\n        name = \"conv_1D_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![1, 1].span()),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_conv_2D_no_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0, 4.0], \n                        [5.0, 6.0, 7.0, 8.0, 9.0],\n                        [10.0, 11.0, 12.0, 13.0, 14.0],\n                        [15.0, 16.0, 17.0, 18.0, 19.0],\n                        [20.0, 21.0, 22.0, 23.0, 24.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [1.0, 1.0, 1.0],  \n                        [1.0, 1.0, 1.0],\n                        [1.0, 1.0, 1.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        \n        y = conv(x, w, group = 1, kernel_shape=[3, 3],pads=[0, 0, 0, 0],)\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_2D_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_con_2D_with_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0, 4.0], \n                        [5.0, 6.0, 7.0, 8.0, 9.0],\n                        [10.0, 11.0, 12.0, 13.0, 14.0],\n                        [15.0, 16.0, 17.0, 18.0, 19.0],\n                        [20.0, 21.0, 22.0, 23.0, 24.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [1.0, 1.0, 1.0], \n                        [1.0, 1.0, 1.0],\n                        [1.0, 1.0, 1.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv(x, w, group = 1, kernel_shape=[3, 3],pads=[1, 1, 1, 1],)\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_2D_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![1, 1, 1, 1].span()),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n        \n    @staticmethod\n    def export_conv_3D_no_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [\n                            [  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]\n                        ],\n                        [\n                            [ 25,  26,  27,  28,  29],[ 30,  31,  32,  33,  34],[ 35,  36,  37,  38,  39],[ 40,  41,  42,  43,  44],[ 45,  46,  47,  48,  49]\n                        ],\n                        [\n                            [ 50,  51,  52,  53,  54],[ 55,  56,  57,  58,  59],[ 60,  61,  62,  63,  64],[ 65,  66,  67,  68,  69],[ 70,  71,  72,  73,  74]\n                        ],\n                        [\n                            [ 75,  76,  77,  78,  79],[ 80,  81,  82,  83,  84],[ 85,  86,  87,  88,  89],[ 90,  91,  92,  93,  94],[ 95,  96,  97,  98,  99]\n                        ],\n                        [\n                            [100, 101, 102, 103, 104],[105, 106, 107, 108, 109],[110, 111, 112, 113, 114],[115, 116, 117, 118, 119],[120, 121, 122, 123, 124]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ],\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ],\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        \n        y = conv(x, w, group = 1)\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_3D_no_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)    \n    \n    @staticmethod\n    def export_conv_3D_with_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [\n                            [  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]\n                        ],\n                        [\n                            [ 25,  26,  27,  28,  29],[ 30,  31,  32,  33,  34],[ 35,  36,  37,  38,  39],[ 40,  41,  42,  43,  44],[ 45,  46,  47,  48,  49]\n                        ],\n                        [\n                            [ 50,  51,  52,  53,  54],[ 55,  56,  57,  58,  59],[ 60,  61,  62,  63,  64],[ 65,  66,  67,  68,  69],[ 70,  71,  72,  73,  74]\n                        ],\n                        [\n                            [ 75,  76,  77,  78,  79],[ 80,  81,  82,  83,  84],[ 85,  86,  87,  88,  89],[ 90,  91,  92,  93,  94],[ 95,  96,  97,  98,  99]\n                        ],\n                        [\n                            [100, 101, 102, 103, 104],[105, 106, 107, 108, 109],[110, 111, 112, 113, 114],[115, 116, 117, 118, 119],[120, 121, 122, 123, 124]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ],\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ],\n                        [\n                            [1., 1., 1.],[1., 1., 1.],[1., 1., 1.]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        \n        y = conv(x, w, group = 1, pads=[1, 1, 1, 1, 1, 1])\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_3D_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![1, 1, 1, 1, 1, 1].span()),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)  \n        \n    @staticmethod\n    def export_conv_4D_no_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [\n                            [\n                                [ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8]\n                            ],\n                            [\n                                [ 9, 10, 11],[12, 13, 14],[15, 16, 17]\n                            ],\n                            [\n                                [18, 19, 20],[21, 22, 23],[24, 25, 26]\n                            ]\n                        ],\n                        [\n                            [\n                                [27, 28, 29],[30, 31, 32],[33, 34, 35]\n                            ],\n                            [\n                                [36, 37, 38],[39, 40, 41],[42, 43, 44]\n                            ],\n                            [\n                                [45, 46, 47],[48, 49, 50],[51, 52, 53]\n                            ]\n                        ],\n                        [\n                            [\n                                [54, 55, 56],[57, 58, 59],[60, 61, 62]\n                            ],\n                            [\n                                [63, 64, 65],[66, 67, 68],[69, 70, 71]\n                            ],\n                            [\n                                [72, 73, 74],[75, 76, 77],[78, 79, 80]\n                            ]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [\n                            [\n                                [1., 1.],[1., 1.]\n                            ],\n                            [\n                                [1., 1.],[1., 1.]\n                            ]\n                        ],\n                        [\n                            [\n                                [1., 1.],[1., 1.]\n                            ],\n                            [\n                                [1., 1.],[1., 1.]\n                            ]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        \n        y = conv(x, w, group = 1)\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_4D_no_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_conv_4D_with_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [\n                            [\n                                [ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8]\n                            ],\n                            [\n                                [ 9, 10, 11],[12, 13, 14],[15, 16, 17]\n                            ],\n                            [\n                                [18, 19, 20],[21, 22, 23],[24, 25, 26]\n                            ]\n                        ],\n                        [\n                            [\n                                [27, 28, 29],[30, 31, 32],[33, 34, 35]\n                            ],\n                            [\n                                [36, 37, 38],[39, 40, 41],[42, 43, 44]\n                            ],\n                            [\n                                [45, 46, 47],[48, 49, 50],[51, 52, 53]\n                            ]\n                        ],\n                        [\n                            [\n                                [54, 55, 56],[57, 58, 59],[60, 61, 62]\n                            ],\n                            [\n                                [63, 64, 65],[66, 67, 68],[69, 70, 71]\n                            ],\n                            [\n                                [72, 73, 74],[75, 76, 77],[78, 79, 80]\n                            ]\n                        ]\n                    ]\n                ]\n            ]\n    ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [\n                            [\n                                [1., 1.],[1., 1.]\n                            ],\n                            [\n                                [1., 1.],[1., 1.]\n                            ]\n                        ],\n                        [\n                            [\n                                [1., 1.],[1., 1.]\n                            ],\n                            [\n                                [1., 1.],[1., 1.]\n                            ]\n                        ]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        \n        y = conv(x, w, group = 1, pads=[1, 1, 1, 1, 1, 1, 1, 1])\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   #\n        \n        name = \"conv_4D_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![1, 1, 1, 1, 1, 1, 1, 1].span()),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n        \n    \n    @staticmethod\n    def export_conv_with_autopad_same() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0, 4.0], \n                        [5.0, 6.0, 7.0, 8.0, 9.0],\n                        [10.0, 11.0, 12.0, 13.0, 14.0],\n                        [15.0, 16.0, 17.0, 18.0, 19.0],\n                        [20.0, 21.0, 22.0, 23.0, 24.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [1.0, 1.0, 1.0],  \n                        [1.0, 1.0, 1.0],\n                        [1.0, 1.0, 1.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)  \n        \n        y = conv(x, w, group = 1, kernel_shape=[3, 3],auto_pad=\"SAME_LOWER\",strides = [2, 2])\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_2D_with_autopad_same\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(AUTO_PAD::SAME_LOWER),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![3, 3].span()),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![2, 2].span()))\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN) \n        \n    @staticmethod\n    def export_conv_with_strides_asymmetric_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0, 4.0], \n                        [5.0, 6.0, 7.0, 8.0, 9.0],\n                        [10.0, 11.0, 12.0, 13.0, 14.0],\n                        [15.0, 16.0, 17.0, 18.0, 19.0],\n                        [20.0, 21.0, 22.0, 23.0, 24.0],\n                        [25.0, 26.0, 27.0, 28.0, 29.0],\n                        [30.0, 31.0, 32.0, 33.0, 34.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [1.0, 1.0, 1.0],  \n                        [1.0, 1.0, 1.0],\n                        [1.0, 1.0, 1.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv(x, w, group = 1, kernel_shape=[3, 3],pads=[1, 0, 1, 0],strides = [2, 2])\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_2D_with_strides_asymmetric_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![3, 3].span()),\"\n        func_sig += \"Option::Some(array![1, 0, 1, 0].span()),\"\n        func_sig += \"Option::Some(array![2, 2].span()))\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN) \n        \n    @staticmethod\n    def export_conv_with_strides_with_padding() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0, 4.0], \n                        [5.0, 6.0, 7.0, 8.0, 9.0],\n                        [10.0, 11.0, 12.0, 13.0, 14.0],\n                        [15.0, 16.0, 17.0, 18.0, 19.0],\n                        [20.0, 21.0, 22.0, 23.0, 24.0],\n                        [25.0, 26.0, 27.0, 28.0, 29.0],\n                        [30.0, 31.0, 32.0, 33.0, 34.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w = np.array(\n            [\n                [\n                    [\n                        [1.0, 1.0, 1.0], \n                        [1.0, 1.0, 1.0],\n                        [1.0, 1.0, 1.0],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        \n        y = conv(x, w, group = 1, kernel_shape=[3, 3],pads=[1, 1, 1, 1],strides = [2, 2])\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))   \n        \n        name = \"conv_2D_with_strides_with_padding\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![3, 3].span()),\"\n        func_sig += \"Option::Some(array![1, 1, 1, 1].span()),\"\n        func_sig += \"Option::Some(array![2, 2].span()))\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN) \n        \n    @staticmethod\n    def export_conv_with_2_groups() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],\n                    [\n                        [9.0, 10.0, 11.0], [12.0, 13.0, 14.0], [15.0, 16.0, 17.0]]\n                ]\n            ]\n        ).astype(np.float32)\n        w =  np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ], \n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ]\n            ]\n        ).astype(np.float32)\n        y = conv(x, w, group = 2)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16)) \n        \n        name = \"conv_2D_with_2_groups\"\n        func_sig = \"NNTrait::conv(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(2),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN) \n\n    "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/conv_transpose.py",
        "content": "\n\nimport numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef conv_transpose( \n    X,\n    W,\n    B=None,\n    auto_pad=None,\n    dilations=None,\n    group=None,\n    kernel_shape=None,\n    output_padding=None,\n    output_shape=None,\n    pads=None,\n    strides=None,\n):\n    if dilations is None:\n        dilations = [1 for s in X.shape[2:]]\n    if kernel_shape is None:\n        kernel_shape = W.shape[2:]\n    if output_padding is None:\n        output_padding = [0 for s in X.shape[2:]] * 2\n    if strides is None:\n        strides = [1 for s in X.shape[2:]]\n    if pads is None and auto_pad not in {\"SAME_UPPER\", \"SAME_LOWER\"}:\n        pads = [0 for i in range(2 * len(strides))]\n    if pads is None:\n        if output_shape is None:\n            output_shape = [\n                X.shape[i + 2] * strides[i] for i in range(len(strides))\n            ]\n        total_padding = [\n            strides[i] * (X.shape[i + 2] - 1)\n            + output_padding[i]\n            + ((kernel_shape[i] - 1) * dilations[i] + 1)\n            - output_shape[i]\n            for i in range(len(output_shape))\n        ]\n        pads_1 = []\n        pads_2 = []\n        for i in range(len(output_shape)):\n            if auto_pad == \"SAME_UPPER\":\n                pads_1.append(total_padding[i] // 2)\n                pads_2.append(total_padding[i] - (total_padding[i] // 2))\n            else:\n                pads_1.append(total_padding[i] - (total_padding[i] // 2))\n                pads_2.append(total_padding[i] // 2)\n        pads = pads_1 + pads_2\n        n_dims = len(pads) // 2\n    else:\n        n_dims = len(X.shape) - 2\n        new_pads = np.array([(pads[i], pads[i + n_dims]) for i in range(n_dims)])\n        if output_shape is None:\n            output_shape = [\n                strides[i] * (X.shape[i + 2] - 1)\n                + output_padding[i]\n                + ((kernel_shape[i] - 1) * dilations[i] + 1)\n                - new_pads[i, :].sum()\n                for i in range(n_dims)\n            ]\n    kernel_shape = W.shape[2:]\n    kernel_size = np.prod(kernel_shape)\n    num_output_channels = W.shape[1] * group\n    kernel_dim = num_output_channels // group * kernel_size\n    C = X.shape[1]  # num_inputs_channels\n    m = kernel_dim  # kernel_dim\n    n = np.prod(X.shape[2:])  # input_image_size\n    k = C // group\n    w_reshaped = W.reshape((group, k, m))\n    final = None\n\n    # N x C x H x W = X.shape\n    # C x M/group x k1 x k2 = W.shape\n    if group == 1:\n        for image_id in range(X.shape[0]):\n            w_t = w_reshaped[0].T\n            gemm = np.matmul(w_t, X[image_id].reshape((k, n)))\n            gemmc = gemm.reshape((num_output_channels, -1, gemm.shape[-1]))\n            for c in range(num_output_channels):\n                res = col2im_naive_implementation(\n                    gemmc[c], output_shape, kernel_shape, dilations, pads, strides\n                )\n                if final is None:\n                    final = np.empty(\n                        X.shape[:1] + (num_output_channels,) + res.shape,\n                        dtype=X.dtype,\n                    )\n                if B is not None:\n                    res += B[c]\n                final[image_id, c, ...] = res[...]\n    else:\n        final = np.zeros((X.shape[0], num_output_channels ) + tuple(output_shape))\n\n        output_array = []\n\n        for group_id in range(group):\n            group_X = X[:, group_id * C // group : (group_id + 1) * C // group, ...]\n            group_W = W[group_id * num_output_channels // group : (group_id + 1) * num_output_channels // group, ...]\n\n            group_output = conv_transpose(\n                group_X,\n                group_W,\n                B=B,  \n                auto_pad=auto_pad,\n                dilations=dilations,\n                group=1, \n                kernel_shape=kernel_shape,\n                output_padding=output_padding,\n                output_shape=output_shape,\n                pads=pads,\n                strides=strides,\n            )\n            group_output = np.array(group_output[0])\n\n            output_array.append(group_output)\n\n            \n        for image_id in range(X.shape[0]):\n            for group_id in range(group):\n                group_output = output_array[group_id]\n                final[image_id, group_id:(group_id+1), ...] = group_output[image_id, ...]\n\n\n    return (final.astype(X.dtype),) \n\n\n\ndef _get_indices(i, shape):\n    res = np.empty((len(shape),), dtype=np.int64)\n    k = len(shape) - 1\n    while k > 0:\n        m = i % shape[k]\n        res[k] = m\n        i -= m\n        i /= shape[k]\n        k -= 1\n    res[0] = i\n    return res\n\ndef _col2im_shape_check(X, output_shape, kernel_shape, dilations, pads, strides):  # type: ignore\n    n_input_plane = X.shape[0]\n\n    kernel_size = np.prod(kernel_shape)\n\n    if n_input_plane % kernel_size != 0:\n        raise ValueError(\n            f\"Expected size of input's dimension 1 to be divisible by the \"\n            f\"product of kernel_size={kernel_size}, \"\n            f\"but got input.size(1)={n_input_plane} \"\n            f\"and kernel_shape={kernel_shape}, X.shape={X.shape}, output_shape={output_shape}.\"\n        )\n\n    input_length = X.shape[1]\n    n_dims = len(output_shape)\n    n_blocks = []\n\n    \n    for i in range(n_dims):\n        n_block = (\n            output_shape[i]\n            + pads[i, :].sum()\n            - dilations[i] * (kernel_shape[i] - 1)\n            - 1\n        ) // strides[i] + 1\n        n_blocks.append(n_block)\n\n    block_size = np.prod(n_blocks)\n    if input_length != block_size:\n        raise ValueError(\n            f\"Given n_input_plane={n_input_plane}, X.shape={X.shape}, \"\n            f\"output_shape={output_shape}, kernel_shape={kernel_shape}, \"\n            f\"dilations={dilations}, pads={pads}, strides={strides}, \"\n            f\"expected size of input's dimension 2 to match the calculated number of \"\n            f\"sliding blocks {n_blocks} = {block_size}, \"\n            f\"but got input.size(2)={input_length}.\",\n        )\n\n\ndef col2im_naive_implementation(data, image_shape, kernel_shape, dilations, pads, strides):  # type: ignore\n\n    n_dims = len(pads) // 2\n    new_pads = np.array([(pads[i], pads[i + n_dims]) for i in range(n_dims)])\n    _col2im_shape_check(data, image_shape, kernel_shape, dilations, new_pads, strides)\n\n    data_col = data\n    data_im = np.zeros(image_shape, dtype=data.dtype)\n\n    dim_col = []\n    for i in range(n_dims):\n        col = (\n            image_shape[i]\n            + new_pads[i, :].sum()\n            - (dilations[i] * (kernel_shape[i] - 1) + 1)\n        ) // strides[i] + 1\n        dim_col.append(col) \n    kernel_size = np.prod(kernel_shape)\n    col_size = np.prod(dim_col)\n    for c_col in range(kernel_size):\n        offset = _get_indices(c_col, kernel_shape)     \n\n        for col in range(col_size):\n            \n            ind_col = _get_indices(col, dim_col)\n            ind_im = []\n            for i in range(n_dims):\n                ind = (\n                    ind_col[i] * strides[i] - new_pads[i, 0] + offset[i] * dilations[i]\n                )\n                ind_im.append(ind)\n            if not _is_out(ind_im, data_im.shape):\n                data_im[tuple(ind_im)] += data_col[c_col, col]\n\n\n    return data_im\n\n\ndef _is_out(ind, shape):  \n    for i, s in zip(ind, shape):\n        if i < 0:\n            return True\n        if i >= s:\n            return True\n    return False\n\n\nclass Conv_transpose(RunAll):\n\n    @staticmethod\n    def export_conv_transpose() -> None:\n        x = np.array(\n            [[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]]  # (1, 1, 3, 3)\n        ).astype(np.float32)\n\n        w = np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],  # (1, 2, 3, 3)\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=1)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n\n    @staticmethod\n    def export_convtranspose_1d() -> None:\n        x = np.array([[[0.0, 1.0, 2.0]]]).astype(np.float32)  # (1, 1, 3)\n\n        w = np.array([[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]).astype(  # (1, 2, 3)\n            np.float32\n        )\n\n        y = conv_transpose(x, w, group=1)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose_1d\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n\n    @staticmethod\n    def export_convtranspose_3d() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [\n                            [0.0, 1.0, 2.0, 3.0, 4.0],  # (1, 1, 3, 4, 5)\n                            [5.0, 6.0, 7.0, 8.0, 9.0],\n                            [10.0, 11.0, 12.0, 13.0, 14.0],\n                            [15.0, 16.0, 17.0, 18.0, 19.0],\n                        ],\n                        [\n                            [20.0, 21.0, 22.0, 23.0, 24.0],\n                            [25.0, 26.0, 27.0, 28.0, 29.0],\n                            [30.0, 31.0, 32.0, 33.0, 34.0],\n                            [35.0, 36.0, 37.0, 38.0, 39.0],\n                        ],\n                        [\n                            [40.0, 41.0, 42.0, 43.0, 44.0],\n                            [45.0, 46.0, 47.0, 48.0, 49.0],\n                            [50.0, 51.0, 52.0, 53.0, 54.0],\n                            [55.0, 56.0, 57.0, 58.0, 59.0],\n                        ],\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n\n        w = np.array(\n            [\n                [\n                    [\n                        [\n                            [1.0, 1.0, 1.0],  # (1, 2, 3, 3, 3)\n                            [1.0, 1.0, 1.0],\n                            [1.0, 1.0, 1.0],\n                        ],\n                        [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                        [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                    ],\n                    [\n                        [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                        [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                        [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                    ],\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=1)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"conv_transpose_3d\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n\n\n    @staticmethod\n    def export_convtranspose_attributes() -> None:\n        x = np.array(\n            [[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]]  # (1, 1, 3, 3)\n        ).astype(np.float32)\n\n        w = np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],  # (1, 2, 3, 3)\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=1)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"conv_transpose_attributes\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n\n\n\n    @staticmethod\n    def export_convtranspose_pads() -> None:\n        x = np.array(\n            [[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]]  # (1, 1, 3, 3)\n        ).astype(np.float32)\n\n        w = np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],  # (1, 2, 3, 3)\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=1,strides=[3, 2],output_shape=[10, 8], kernel_shape=[3, 3], output_padding=[1, 1],)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"conv_transpose_pads\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(array![3, 3].span()),\"\n        func_sig += \"Option::Some(array![1, 1].span()),\"\n        func_sig += \"Option::Some(array![10, 8].span()),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![3, 2].span()))\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n    @staticmethod\n    def export_convtranspose_dilations() -> None:\n        x = np.array(\n            [[[[3.0, 8.0, 1.0], [9.0, 5.0, 7.0], [3.0, 2.0, 6.0]]]]  # (1, 1, 3, 3)\n        ).astype(np.float32)\n        w = np.array([[[[7.0, 2.0], [1.0, 9.0]]]]).astype(np.float32)  # (1, 1, 2, 2)\n\n        y = conv_transpose(x, w, group=1,  dilations=[2, 2])[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose_dilations\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![2, 2].span()),\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n\n    @staticmethod\n    def export_convtranspose_autopad_same() -> None:\n        x = np.array(\n            [[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]]  # (1, 1, 3, 3)\n        ).astype(np.float32)\n\n        w = np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],  # (1, 2, 3, 3)\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],\n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=1, auto_pad=\"SAME_UPPER\", strides=[2, 2])[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose_autopad_same\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(AUTO_PAD::SAME_UPPER),\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(array![2, 2].span()))\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n\n    @staticmethod\n    def export_convtranspose_group_2() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],\n                    [\n                        [9.0, 10.0, 11.0], [12.0, 13.0, 14.0], [15.0, 16.0, 17.0]]\n                ]\n            ]\n        ).astype(np.float32)\n        w =  np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ], \n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=2)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose_group_2\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(2),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_convtranspose_group_2_image_3() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],\n                    [\n                        [9.0, 10.0, 11.0], [12.0, 13.0, 14.0], [15.0, 16.0, 17.0]\n                    ]\n                ], \n                [\n                    [\n                        [18.0, 19.0, 20.0], [21.0, 22.0, 23.0], [24.0, 25.0, 26.0]\n                    ],\n                    [\n                        [9.0, 10.0, 11.0], [12.0, 13.0, 14.0], [15.0, 16.0, 17.0]\n                    ]\n                ],   \n                [\n                    [\n                        [0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]\n                    ],\n                    [\n                        [9.0, 10.0, 11.0], [12.0, 13.0, 14.0], [15.0, 16.0, 17.0]\n                    ]\n                ]\n            ]\n        ).astype(np.float32)\n        w =  np.array(\n            [\n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ], \n                [\n                    [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], \n                ]\n            ]\n        ).astype(np.float32)\n\n        y = conv_transpose(x, w, group=2)[0]\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(w.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"conv_transpose_group_2_image_3\"\n        func_sig = \"NNTrait::conv_transpose(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(2),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,)\"\n        make_test(\n            [x, w], y, func_sig, name, Trait.NN)\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/cos.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Cos(RunAll):\n\n    @staticmethod\n    def cos_fp8x23():\n        x = np.random.uniform(-10, 127, (2, 2)).astype(np.float64)\n        y = np.cos(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"cos_fp8x23\"\n        make_test([x], y, \"input_0.cos()\", name)\n\n    @staticmethod\n    def cos_fp16x16():\n        x = np.random.uniform(-10, 127, (2, 2)).astype(np.float64)\n        y = np.cos(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"cos_fp16x16\"\n        make_test([x], y, \"input_0.cos()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/cosh.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Cosh(RunAll):\n\n    @staticmethod\n    def cosh_fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.cosh(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"cosh_fp8x23\"\n        make_test([x], y, \"input_0.cosh()\", name)\n\n    @staticmethod\n    def cosh_fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.cosh(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"cosh_fp16x16\"\n        make_test([x], y, \"input_0.cosh()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/cumsum.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Cumsum(RunAll):\n    @staticmethod\n    def cumsum_u32():\n        def cumsum_1D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.uint32)\n                y = np.array([1, 3, 6, 10, 15]).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_1d_default\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.uint32)\n                y = np.array([0, 1, 3, 6, 10]).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_1d_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(false))\", name)\n\n            def reverse():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.uint32)\n                y = np.array([15, 14, 12, 9, 5]).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_1d_reverse\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(false), Option::Some(true))\", name)\n\n            def reverse_exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.uint32)\n                y = np.array([14, 12, 9, 5, 0]).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_1d_reverse_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(true))\", name)\n\n            default()\n            exclusive()\n            reverse()\n            reverse_exclusive()\n        cumsum_1D()\n\n        def cumsum_2D():\n            def axis_0():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.uint32).reshape((2, 3))\n                y = np.array([1, 2, 3, 5, 7, 9]).astype(\n                    np.uint32).reshape((2, 3))\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_2d_axis_0\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.uint32).reshape((2, 3))\n                y = np.array([1, 3, 6, 4, 9, 15]).astype(\n                    np.uint32).reshape((2, 3))\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"cumsum_u32_2d_axis_1\"\n                make_test(\n                    [x], y, \"input_0.cumsum(1, Option::None(()), Option::None(()))\", name)\n\n            axis_0()\n            axis_1()\n        cumsum_2D()\n\n    @staticmethod\n    def cumsum_i32():\n        def cumsum_1D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int32)\n                y = np.array([1, 3, 6, 10, 15]).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_1d_default\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int32)\n                y = np.array([0, 1, 3, 6, 10]).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_1d_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(false))\", name)\n\n            def reverse():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int32)\n                y = np.array([15, 14, 12, 9, 5]).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_1d_reverse\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(false), Option::Some(true))\", name)\n\n            def reverse_exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int32)\n                y = np.array([14, 12, 9, 5, 0]).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_1d_reverse_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(true))\", name)\n\n            default()\n            exclusive()\n            reverse()\n            reverse_exclusive()\n        cumsum_1D()\n\n        def cumsum_2D():\n            def axis_0():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int32).reshape((2, 3))\n                y = np.array([1, 2, 3, 5, 7, 9]).astype(\n                    np.int32).reshape((2, 3))\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_2d_axis_0\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int32).reshape((2, 3))\n                y = np.array([1, 3, 6, 4, 9, 15]).astype(\n                    np.int32).reshape((2, 3))\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"cumsum_i32_2d_axis_1\"\n                make_test(\n                    [x], y, \"input_0.cumsum(1, Option::None(()), Option::None(()))\", name)\n\n            axis_0()\n            axis_1()\n        cumsum_2D()\n\n    @staticmethod\n    def cumsum_i8():\n        def cumsum_1D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int8)\n                y = np.array([1, 3, 6, 10, 15]).astype(np.int8)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_1d_default\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int8)\n                y = np.array([0, 1, 3, 6, 10]).astype(np.int8)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_1d_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(false))\", name)\n\n            def reverse():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int8)\n                y = np.array([15, 14, 12, 9, 5]).astype(np.int8)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_1d_reverse\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(false), Option::Some(true))\", name)\n\n            def reverse_exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int8)\n                y = np.array([14, 12, 9, 5, 0]).astype(np.int8)\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_1d_reverse_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(true))\", name)\n\n            default()\n            exclusive()\n            reverse()\n            reverse_exclusive()\n        cumsum_1D()\n\n        def cumsum_2D():\n            def axis_0():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int8).reshape((2, 3))\n                y = np.array([1, 2, 3, 5, 7, 9]).astype(\n                    np.int8).reshape((2, 3))\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_2d_axis_0\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int8).reshape((2, 3))\n                y = np.array([1, 3, 6, 4, 9, 15]).astype(\n                    np.int8).reshape((2, 3))\n\n                x = Tensor(Dtype.I8, x.shape, x.flatten())\n                y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"cumsum_i8_2d_axis_1\"\n                make_test(\n                    [x], y, \"input_0.cumsum(1, Option::None(()), Option::None(()))\", name)\n\n            axis_0()\n            axis_1()\n        cumsum_2D()\n\n    @staticmethod\n    def cumsum_fp8x23():\n        def cumsum_1D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([1, 3, 6, 10, 15]).astype(np.int64)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_1d_default\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([0, 1, 3, 6, 10]).astype(np.int64)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_1d_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(false))\", name)\n\n            def reverse():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([15, 14, 12, 9, 5]).astype(np.int64)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_1d_reverse\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(false), Option::Some(true))\", name)\n\n            def reverse_exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([14, 12, 9, 5, 0]).astype(np.int64)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_1d_reverse_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(true))\", name)\n\n            default()\n            exclusive()\n            reverse()\n            reverse_exclusive()\n        cumsum_1D()\n\n        def cumsum_2D():\n            def axis_0():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int64).reshape((2, 3))\n                y = np.array([1, 2, 3, 5, 7, 9]).astype(\n                    np.int64).reshape((2, 3))\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_2d_axis_0\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int64).reshape((2, 3))\n                y = np.array([1, 3, 6, 4, 9, 15]).astype(\n                    np.int64).reshape((2, 3))\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"cumsum_fp8x23_2d_axis_1\"\n                make_test(\n                    [x], y, \"input_0.cumsum(1, Option::None(()), Option::None(()))\", name)\n\n            axis_0()\n            axis_1()\n        cumsum_2D()\n\n    @staticmethod\n    def cumsum_fp16x16():\n        def cumsum_1D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([1, 3, 6, 10, 15]).astype(np.int64)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_1d_default\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([0, 1, 3, 6, 10]).astype(np.int64)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_1d_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(false))\", name)\n\n            def reverse():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([15, 14, 12, 9, 5]).astype(np.int64)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_1d_reverse\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(false), Option::Some(true))\", name)\n\n            def reverse_exclusive():\n                x = np.array([1, 2, 3, 4, 5]).astype(np.int64)\n                y = np.array([14, 12, 9, 5, 0]).astype(np.int64)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_1d_reverse_exclusive\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::Some(true), Option::Some(true))\", name)\n\n            default()\n            exclusive()\n            reverse()\n            reverse_exclusive()\n        cumsum_1D()\n\n        def cumsum_2D():\n            def axis_0():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int64).reshape((2, 3))\n                y = np.array([1, 2, 3, 5, 7, 9]).astype(\n                    np.int64).reshape((2, 3))\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_2d_axis_0\"\n                make_test(\n                    [x], y, \"input_0.cumsum(0, Option::None(()), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([1, 2, 3, 4, 5, 6]).astype(\n                    np.int64).reshape((2, 3))\n                y = np.array([1, 3, 6, 4, 9, 15]).astype(\n                    np.int64).reshape((2, 3))\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"cumsum_fp16x16_2d_axis_1\"\n                make_test(\n                    [x], y, \"input_0.cumsum(1, Option::None(()), Option::None(()))\", name)\n\n            axis_0()\n            axis_1()\n        cumsum_2D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/depth_to_space.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\ndef depth_to_space(data: np.ndarray, blocksize: int = 2, mode = \"DCR\") -> np.ndarray:\n    if len(data.shape) != 4:\n        raise RuntimeError(f\"Unexpected shape {data.shape!r}.\")\n    b, c, h, w = data.shape\n    if mode == \"DCR\":\n        tmpshape = (\n            b,\n            blocksize,\n            blocksize,\n            c // (blocksize * blocksize),\n            h,\n            w,\n        )\n        reshaped = data.reshape(tmpshape)\n        transposed = np.transpose(reshaped, [0, 3, 4, 1, 5, 2])\n    else:\n        # assert mode == \"CRD\"\n        tmpshape = (\n            b,\n            c // (blocksize * blocksize),\n            blocksize,\n            blocksize,\n            h,\n            w,\n        )\n        reshaped = data.reshape(tmpshape)\n        transposed = np.transpose(reshaped, [0, 1, 4, 2, 5, 3])\n    finalshape = (\n        b,\n        c // (blocksize * blocksize),\n        h * blocksize,\n        w * blocksize,\n    )\n    y = np.reshape(transposed, finalshape)\n    return y\n\nclass Depth_to_space(RunAll):\n\n    @staticmethod\n    def fp8x23():\n        x = np.random.uniform(-3, 3, (1, 4, 2, 2)).astype(np.float64)\n        y = depth_to_space(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"depth_to_space_fp8x23\"\n        make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'DCR')\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fp16x16():\n        x = np.random.uniform(-3, 3, (1, 4, 2, 2)).astype(np.float16)\n        y = depth_to_space(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"depth_to_space_fp16x16\"\n        make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'DCR')\",\n                    name, Trait.NN)\n        \n    # @staticmethod\n    # def fp64x64():\n    #     x = np.random.uniform(-3, 3, (1, 4, 2, 2)).astype(np.float64)\n    #     y = depth_to_space(x)\n\n    #     x = Tensor(Dtype.FP64x64, x.shape, to_fp(\n    #         x.flatten(), FixedImpl.FP64x64))\n    #     y = Tensor(Dtype.FP64x64, y.shape, to_fp(\n    #         y.flatten(), FixedImpl.FP64x64))\n\n    #     name = \"depth_to_space_fp64x64\"\n    #     make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'DCR')\",\n    #                 name, Trait.NN)\n\n    @staticmethod\n    def fpi8():\n        x = np.random.randint(-3, 3, (1, 4, 2, 2)).astype(np.int8)\n        y = depth_to_space(x)\n\n        x = Tensor(Dtype.I8, x.shape, x.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"depth_to_space_i8\"\n        make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'DCR')\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fpi32():\n        x = np.random.randint(-3, 3, (1, 4, 2, 2)).astype(np.int32)\n        y = depth_to_space(x)\n\n        x = Tensor(Dtype.I32, x.shape, x.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"depth_to_space_i32\"\n        make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'CRD')\",\n                    name, Trait.NN)\n\n\n    @staticmethod\n    def fpu32():\n        x = np.random.randint(-3, 3, (1, 4, 2, 2)).astype(np.uint32)\n        y = depth_to_space(x)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"depth_to_space_u32\"\n        make_test([x], y, \"NNTrait::depth_to_space(@input_0, 2, 'CRD')\",\n                    name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/div.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Div(RunAll):\n    @staticmethod\n    def div_u32():\n        def default():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(1, 3, (3, 3, 3)).astype(np.uint32)\n            z = x / y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"div_u32\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(1, 3, (1, 3, 1)).astype(np.uint32)\n            z = x / y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"div_u32_broadcast\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def div_i32():\n        def default():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(1, 3, (3, 3, 3)).astype(np.int32)\n            z = x / y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"div_i32\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(1, 3, (1, 3, 1)).astype(np.int32)\n            z = x / y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"div_i32_broadcast\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def div_i8():\n        def default():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(1, 3, (3, 3, 3)).astype(np.int8)\n            z = x / y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"div_i8\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(1, 3, (1, 3, 1)).astype(np.int8)\n            z = x / y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"div_i8_broadcast\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def div_fp8x23():\n        def default():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            z = x / y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"div_fp8x23\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(1, 3, (1, 3, 1)).astype(np.float64)\n            z = x / y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"div_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def div_fp16x16():\n        def default():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            z = x / y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"div_fp16x16\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(1, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(1, 3, (1, 3, 1)).astype(np.float64)\n            z = x / y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"div_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0 / input_1\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/equal.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Equal(RunAll):\n    @staticmethod\n    def equal_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_u32\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_u32_broadcast\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def equal_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_i32\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int32)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_i32_broadcast\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def equal_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_i8\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int8)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_i8_broadcast\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def equal_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_fp8x23\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def equal_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_fp16x16\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"equal_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.equal(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/erf.py",
        "content": "import numpy as np\nfrom math import erf\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Erf(RunAll):\n\n    @staticmethod\n    def erf_fp8x23():\n        x = np.asarray([0.12, -1.66, 3.4, 4.8, 2.7]).astype(np.float64).reshape(1,5)\n        y = np.asarray([erf(value) for value in x[0]]).astype(np.float64).reshape(1,5)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"erf_fp8x23\"\n        make_test([x], y, \"input_0.erf()\", name)\n        \n\n    @staticmethod\n    def erf_fp16x16():\n        x = np.asarray([0.12, -1.66, 3.4, 4.8, 2.7]).astype(np.float64).reshape(1,5)\n        y = np.asarray([erf(value) for value in x[0]]).astype(np.float64).reshape(1,5)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"erf_fp16x16\"\n        make_test([x], y, \"input_0.erf()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/exp.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Exp(RunAll):\n\n    @staticmethod\n    def exp_fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.exp(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"exp_fp8x23\"\n        make_test([x], y, \"input_0.exp()\", name)\n\n    @staticmethod\n    def exp_fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.exp(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"exp_fp16x16\"\n        make_test([x], y, \"input_0.exp()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/gather.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nclass Gather(RunAll):\n\n    @staticmethod\n    def gather_fp16x16():\n            \n        def default():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.array([[0,1], [2,1], [0, 2]]).astype(np.uint32)\n            y = x1.take(x2, axis=0)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_fp16x16_3d_default\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather(indices:input_1, axis:Option::Some(0))\", \n                name= name)\n            \n        def axis1():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.array([[0,1], [2,1], [0, 2]]).astype(np.int64)\n            y = x1.take(x2, axis=1)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_fp16x16_3d_axis1\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather(indices:input_1, axis:Option::Some(1))\", \n                name= name)\n            \n        def axis2():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.array([[0,1], [2,1], [0, 2]]).astype(np.int64)\n            y = x1.take(x2, axis=2)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_fp16x16_3d_axis2\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather(indices:input_1, axis:Option::Some(2))\", \n                name= name)\n        \n        def negative_indices():\n            x1 = np.arange(10).astype(np.float32)\n            x2 = np.array([0, -9, -10]).astype(np.int64)\n            y = np.take(x1, x2, axis=0)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_negative_indices\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather(indices:input_1, axis:Option::Some(0))\", \n                name= name)\n        \n        def negative_axis():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.array([[0,1], [2,1], [0, 2]]).astype(np.uint32)\n            y = x1.take(x2, axis=-1)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_negative_axis\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather(indices:input_1, axis:Option::Some(-1))\", \n                name= name)\n            \n        default()\n        axis1()\n        axis2()\n        negative_indices()\n        negative_axis()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/gather_elements.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\ndef gather_elements(data, indices, axis=0):  # type: ignore\n    data_swaped = np.swapaxes(data, 0, axis)\n    index_swaped = np.swapaxes(indices, 0, axis)\n    gathered = np.choose(index_swaped, data_swaped, mode=\"wrap\")\n    y = np.swapaxes(gathered, 0, axis)\n    return y\n\nclass Gather_elements(RunAll):\n\n    @staticmethod\n    def gather_elements_fp16x16():\n        def default():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.random.randint(low = 0,high=2, size=(3,3,3)).astype(np.uint32)\n            y = gather_elements(x1, x2, axis=0)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_elements_default\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather_elements(indices:input_1, axis:Option::Some(0))\", \n                name= name)\n            \n        def axis1():\n            x1 = np.array([[1, 2], [3, 4]], dtype=np.float32)\n            x2 = np.array([[0, 0], [1, 0]], dtype=np.int32)\n            y = gather_elements(x1, x2, axis=1)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_elements_axis1\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather_elements(indices:input_1, axis:Option::Some(1))\", \n                name= name)\n            \n        def axis2():\n            x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n            x2 = np.random.randint(low = 0,high=3, size=(3,3,3)).astype(np.uint32)\n            y = gather_elements(x1, x2, axis=2)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_elements_axis2\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather_elements(indices:input_1, axis:Option::Some(2))\", \n                name= name)\n        \n        def negative_indices():\n            x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)\n            x2 = np.array([[-1, -2, 0], [-2, 0, 0]], dtype=np.int32)\n            y = gather_elements(x1, x2, axis=0)\n\n            x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n            x2 = Tensor(Dtype.I32, x2.shape, x2.flatten()) \n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16)) \n\n            name = \"gather_elements_negative_indices\"\n            make_test(\n                inputs = [x1, x2], output = y, func_sig = \"input_0.gather_elements(indices:input_1, axis:Option::Some(0))\", \n                name= name)\n            \n        default()\n        axis1()\n        axis2()\n        negative_indices()\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/gather_nd.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\ndef gather_nd_impl(\n    data: np.ndarray, indices: np.ndarray, batch_dims: int\n) -> np.ndarray:\n    # Note the data rank - will be reused multiple times later\n    data_rank = len(data.shape)\n\n    # Check input tensors' shape/rank condition\n    assert indices.shape[-1] <= data_rank\n\n    # The list of data/indice shape of batch_dims\n    batch_dims_shape = []\n\n    # The number of elements in the batch_dims for data/indice array\n    batch_dims_size = 1\n\n    # Check the shape of indice and data are identicial for batch dims.\n    for i in range(batch_dims):\n        batch_dims_shape.append(indices.shape[i])\n        batch_dims_size *= indices.shape[i]\n\n    # Compute output of the op as below\n\n    # Compute shape of output array\n    output_shape = (\n        batch_dims_shape + list(indices.shape)[batch_dims:-1]\n        if (indices.shape[-1] == data_rank - batch_dims)\n        else batch_dims_shape\n        + list(indices.shape)[batch_dims:-1]\n        + list(data.shape)[batch_dims + indices.shape[-1] :]\n    )\n\n    # Placeholder for output data\n    output_data_buffer = []\n\n    # Flatten 'indices' to 2D array\n    reshaped_indices = indices.reshape(batch_dims_size, -1, indices.shape[-1])\n\n    # Flatten 'data' to array of shape (batch_dim_size, data.shape[batch_dimes:])\n    reshaped_data = data.reshape((batch_dims_size,) + data.shape[batch_dims:])\n\n    # gather each scalar value from 'data'\n    for batch_dim in range(reshaped_indices.shape[0]):\n        for outer_dim in range(reshaped_indices.shape[1]):\n            gather_index = tuple(reshaped_indices[batch_dim][outer_dim])\n            output_data_buffer.append(reshaped_data[(batch_dim, *gather_index)])\n    return np.asarray(output_data_buffer, dtype=data.dtype).reshape(output_shape)\n\n        \nclass Gather_nd(RunAll):\n\n    @staticmethod\n    def gather_nd_fp16x16():\n        def gather_nd_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,3)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=0)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"gather_nd_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(0))\", \n                    name= name)\n                \n            def batch_dims1():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=1)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"gather_nd_fp16x16_3d_batch_dims1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(1))\", \n                    name= name)\n                \n            def batch_dims2():\n                x1 = np.arange(0,54).reshape(3,3,3,2).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=2)\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"gather_nd_fp16x16_3d_batch_dims2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            batch_dims1()\n            batch_dims2()\n        gather_nd_3D()\n\n\n    @staticmethod\n    def gather_nd_fp8x23():\n        def gather_nd_3D():\n            def default():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,3)).astype(np.int64)\n                y = gather_nd_impl(x1, x2, batch_dims=0)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"gather_nd_fp8x23_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(0))\", \n                    name= name)\n                \n            def batch_dims1():\n                x1 = np.arange(0,27).reshape(3,3,3).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.int64)\n                y = gather_nd_impl(x1, x2, batch_dims=1)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"gather_nd_fp8x23_3d_batch_dims1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(1))\", \n                    name= name)\n                \n            def batch_dims2():\n                x1 = np.arange(0,54).reshape(3,3,3,2).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=2)\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"gather_nd_fp8x23_3d_batch_dims2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            batch_dims1()\n            batch_dims2()\n        gather_nd_3D()\n\n\n    @staticmethod\n    def gather_nd_i8():\n        def gather_nd_3D():\n            def default():\n                x1 = np.arange(0,9).reshape(3,3).astype(np.int8)\n                x2 = np.random.randint(low = 0,high=2, size=(3,2)).astype(np.int8)\n                y = gather_nd_impl(x1, x2, batch_dims=0)\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"gather_nd_i8_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(0))\", \n                    name= name)\n                \n            def batch_dims1():\n                x1 = np.arange(0,9).reshape(3,3).astype(np.int8)\n                x2 = np.random.randint(low = 0,high=2, size=(3,1)).astype(np.int8)\n                y = gather_nd_impl(x1, x2, batch_dims=1)\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"gather_nd_i8_3d_batch_dims1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(1))\", \n                    name= name)\n                \n           \n            default()\n            batch_dims1()\n        gather_nd_3D()\n\n\n    @staticmethod\n    def gather_nd_i32():\n        def gather_nd_3D():\n            def default():\n                x1 = np.arange(0,24).reshape(4,2,3).astype(np.int32)\n                x2 = np.random.randint(low = 0,high=2, size=(3,2)).astype(np.int32)\n                y = gather_nd_impl(x1, x2, batch_dims=0)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"gather_nd_i32_3d_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(0))\", \n                    name= name)\n                \n            def batch_dims1():\n                x1 = np.arange(0,108).reshape(4,3,3,3).astype(np.int32)\n                x2 = np.random.randint(low = 0,high=3, size=(4,2,3)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=1)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"gather_nd_i32_3d_batch_dims1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(1))\", \n                    name= name)\n                \n            def batch_dims2():\n                x1 = np.arange(0,54).reshape(3,3,3,2).astype(np.int64)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=2)\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"gather_nd_i32_3d_batch_dims2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(2))\", \n                    name= name)\n                \n            default()\n            batch_dims1()\n            batch_dims2()\n        gather_nd_3D()\n\n    @staticmethod\n    def gather_nd_u32():\n        def gather_nd_3D():\n            def default():\n                x1 = np.arange(0,108).reshape(3,3,4,3).astype(np.int32)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=0)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"gather_nd_u32_default\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(0))\", \n                    name= name)\n                \n            def batch_dims1():\n                x1 = np.arange(0,108).reshape(3,3,4,3).astype(np.int32)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=1)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"gather_nd_u32_batch_dims1\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(1))\", \n                    name= name)\n                \n            def batch_dims2():\n                x1 = np.arange(0,108).reshape(3,3,4,3).astype(np.int32)\n                x2 = np.random.randint(low = 0,high=2, size=(3,3,2)).astype(np.uint32)\n                y = gather_nd_impl(x1, x2, batch_dims=2)\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"gather_nd_u32_batch_dims2\"\n                make_test(\n                    inputs = [x1, x2], output = y, func_sig = \"input_0.gather_nd(indices:input_1, batch_dims:Option::Some(2))\", \n                    name= name)\n                \n            \n            default()\n            batch_dims1()\n            batch_dims2()\n        gather_nd_3D()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/gemm.py",
        "content": "from typing import Optional\n\nimport numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef gemm_reference_implementation(\n    A: np.ndarray,\n    B: np.ndarray,\n    C: Optional[np.ndarray] = None,\n    alpha: float = 1.0,\n    beta: float = 1.0,\n    transA: int = 0,\n    transB: int = 0,\n) -> np.ndarray:\n    A = A if transA == 0 else A.T\n    B = B if transB == 0 else B.T\n    C = C if C is not None else np.array(0)\n\n    Y = alpha * np.dot(A, B) + beta * C\n    return Y\n\n\nclass Gemm(RunAll):\n\n    @staticmethod\n    def gemm_default_zero_bias():\n        a = np.random.ranf([3, 5]).astype(np.float32)\n        b = np.random.ranf([5, 4]).astype(np.float32)\n        c = np.zeros([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_default_no_bias\"\n        make_test(\n            [a, b], y, \"NNTrait::gemm(input_0, input_1, Option::None(()), Option::None(()), Option::None(()), false, false)\", name, Trait.NN)\n        \n    @staticmethod\n    def gemm_default_vector_bias():\n        a = np.random.ranf([2, 7]).astype(np.float32)\n        b = np.random.ranf([7, 4]).astype(np.float32)\n        c = np.random.ranf([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        c = Tensor(Dtype.FP16x16, c.shape, to_fp(\n            c.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_default_vector_bias\"\n        make_test(\n            [a, b, c], y, \"NNTrait::gemm(input_0, input_1, Option::Some(input_2), Option::None(()), Option::None(()), false, false)\", name, Trait.NN)\n        \n    @staticmethod\n    def gemm_default_matrix_bias():\n        a = np.random.ranf([3, 6]).astype(np.float32)\n        b = np.random.ranf([6, 4]).astype(np.float32)\n        c = np.random.ranf([3, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        c = Tensor(Dtype.FP16x16, c.shape, to_fp(\n            c.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_default_matrix_bias\"\n        make_test(\n            [a, b, c], y, \"NNTrait::gemm(input_0, input_1, Option::Some(input_2), Option::None(()), Option::None(()), false, false)\", name, Trait.NN)\n\n    @staticmethod\n    def gemm_transposeA():\n        a = np.random.ranf([6, 3]).astype(np.float32)\n        b = np.random.ranf([6, 4]).astype(np.float32)\n        c = np.zeros([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c, transA=1)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_transposeA\"\n        make_test(\n            [a, b], y, \"NNTrait::gemm(input_0, input_1, Option::None(()), Option::None(()), Option::None(()), true, false)\", name, Trait.NN)\n\n    @staticmethod\n    def gemm_transposeB():\n        a = np.random.ranf([3, 6]).astype(np.float32)\n        b = np.random.ranf([4, 6]).astype(np.float32)\n        c = np.zeros([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c, transB=1)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_transposeB\"\n        make_test(\n            [a, b], y, \"NNTrait::gemm(input_0, input_1, Option::None(()), Option::None(()), Option::None(()), false, true)\", name, Trait.NN)\n\n    @staticmethod\n    def gemm_alpha():\n        a = np.random.ranf([3, 5]).astype(np.float32)\n        b = np.random.ranf([5, 4]).astype(np.float32)\n        c = np.zeros([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c, alpha=0.5)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_alpha\"\n        make_test(\n            [a, b], y, \"NNTrait::gemm(input_0, input_1, Option::None(()), Option::Some(FixedTrait::new(32768, false)), Option::None(()), false, false)\", name, Trait.NN)\n\n    @staticmethod\n    def gemm_beta():\n        a = np.random.ranf([2, 7]).astype(np.float32)\n        b = np.random.ranf([7, 4]).astype(np.float32)\n        c = np.random.ranf([1, 4]).astype(np.float32)\n        y = gemm_reference_implementation(a, b, c, beta=0.5)\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        c = Tensor(Dtype.FP16x16, c.shape, to_fp(\n            c.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_beta\"\n        make_test(\n            [a, b, c], y, \"NNTrait::gemm(input_0, input_1, Option::Some(input_2), Option::None(()), Option::Some(FixedTrait::new(32768, false)), false, false)\", name, Trait.NN)\n\n    @staticmethod\n    def gemm_all_attributes():\n        a = np.random.ranf([4, 3]).astype(np.float32)\n        b = np.random.ranf([5, 4]).astype(np.float32)\n        c = np.random.ranf([1, 5]).astype(np.float32)\n        y = gemm_reference_implementation(\n            a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35\n        )\n\n        a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n            a.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        c = Tensor(Dtype.FP16x16, c.shape, to_fp(\n            c.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"gemm_all_attributes\"\n        make_test(\n            [a, b, c], y, \"NNTrait::gemm(input_0, input_1, Option::Some(input_2), Option::Some(FixedTrait::new(16384, false)), Option::Some(FixedTrait::new(22938, false)), true, true)\", name, Trait.NN)\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/greater.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Greater(RunAll):\n    @staticmethod\n    def greater_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_u32\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_u32_broadcast\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_i32\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int32)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_i32_broadcast\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_i8\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int8)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_i8_broadcast\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_fp8x23\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_fp16x16\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.greater(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.greater(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/greater_equal.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Greater_equal(RunAll):\n    @staticmethod\n    def greater_equal_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_u32\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 3, 1)).astype(np.uint32)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_u32_broadcast\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_equal_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_i32\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int32)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_i32_broadcast\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_equal_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_i8\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int8)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_i8_broadcast\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_equal_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_fp8x23\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def greater_equal_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_fp16x16\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = np.greater_equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"greater_equal_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.greater_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/grid_sample.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\nfrom .resize import _get_all_coords\nimport numbers\nfrom typing import List\n\nimport numpy as np\n\n#from onnx.reference.ops.op_resize import _get_all_coords\n\ndef grid_sample(X, grid, mode='linear', padding_mode='zeros', align_corners=0):\n    x_dims = X.shape\n    grid_dims = grid.shape\n    N = x_dims[0]\n    C = x_dims[1]\n    y_dims = (N, C, *grid_dims[1:-1])\n    if np.prod(y_dims) == 0:\n        return np.array([], dtype=X.dtype)\n    Y = np.empty(y_dims, dtype=X.dtype)\n    for n in range(N):\n        grid_data = grid[n]\n        for c in range(C):\n            X_data = X[n, c]\n            num_dims = len(x_dims[2:])\n            dims = x_dims[2:]\n            border = _prepare_border(dims, align_corners=align_corners)\n            for ox in _get_all_coords(Y[n, c]):\n                nx = grid_data[tuple(ox)]\n                nx = nx[::-1]\n                x = _gs_denormalize_coordinates(\n                    n=nx, dims=dims, align_corners=align_corners\n                )\n                if mode == \"nearest\":\n                    x = np.rint(x)\n                for i, v in enumerate(x):\n                    x_min = border[i]\n                    x_max = border[i + num_dims]\n                    if v < x_min or v > x_max:\n                        if padding_mode == \"border\":\n                            x[i] = _clamp(v, 0, dims[i] - 1)\n                        elif padding_mode == \"reflection\":\n                            x[i] = _gs_reflect(v, x_min, x_max)\n                if mode == \"nearest\":\n                    x = x.astype(np.int32)\n                    Y[n][c][tuple(ox)] = _pixel_at_ndarray(\n                        ndarray=X_data,\n                        x=x,\n                        border=border,\n                        padding_mode=padding_mode,\n                    )\n                    \n                elif mode == \"linear\":\n                    Y[n][c][tuple(ox)] = _gs_linear_interpolation_nd_with_x(\n                        data=X_data, x=x, border=border, padding_mode=padding_mode\n                    )\n                elif mode == \"cubic\":\n                    Y[n][c][tuple(ox)] = _gs_cubic_interpolation_nd_with_x(\n                        data=X_data, x=x, border=border, padding_mode=padding_mode\n                    )\n                else:\n                    raise RuntimeError(\n                        \"GridSample interpolation only supports nearest, linear, and cubic modes.\"\n                    )\n    return (Y.astype(X.dtype),)\n\n\ndef _gs_denormalize(n, length: int, align_corners: bool):  \n    if align_corners:\n        x = (n + 1) / 2.0 * (length - 1)\n    else:\n        x = ((n + 1) * length - 1) / 2.0\n    return x\n\ndef _gs_denormalize_coordinates(n, dims, align_corners: bool):\n    x = np.zeros(len(n), dtype=np.float32)\n    for i, (v, dim) in enumerate(zip(n, dims)):\n        x[i] = _gs_denormalize(n=v, length=dim, align_corners=align_corners)\n    return x\n\ndef _gs_reflect(x, x_min, x_max):  # type: ignore\n    \"\"\"Reflect by the near border till within the borders\n    Use float for borders to avoid potential issues with integer T\n    \"\"\"\n    fx = x\n    rng = x_max - x_min\n    if fx < x_min:           \n        dx = x_min - fx\n        n = int(dx / rng)\n        r = dx - n * rng\n        if n % 2 == 0:\n            fx = x_min + r\n        else:\n            fx = x_max - r\n    elif fx > x_max:\n        dx = fx - x_max\n        n = int(dx / rng)\n        r = dx - n * rng\n        if n % 2 == 0:\n            fx = x_max - r\n        else:\n            fx = x_min + r\n    return fx\n\ndef _gs_get_cubic_coeffs(x, coeffs):  # type: ignore\n    \"\"\"Calculate cubic convolution interpolation coefficients\n    ROBERT G. KEYS https://ieeexplore.ieee.org/document/1163711\n    Use float to avoid potential issues with integer.\n    \"\"\"\n    cubic_alpha = -0.75\n    x = abs(x)\n    coeffs[0] = (\n        (cubic_alpha * (x + 1) - 5 * cubic_alpha) * (x + 1) + 8 * cubic_alpha\n    ) * (x + 1) - 4 * cubic_alpha\n    coeffs[1] = ((cubic_alpha + 2) * x - (cubic_alpha + 3)) * x * x + 1\n    coeffs[2] = ((cubic_alpha + 2) * (1 - x) - (cubic_alpha + 3)) * (1 - x) * (\n        1 - x\n    ) + 1\n    coeffs[3] = (\n        (cubic_alpha * (2 - x) - 5 * cubic_alpha) * (2 - x) + 8 * cubic_alpha\n    ) * (2 - x) - 4 * cubic_alpha\n    \ndef _gs_get_linear_coeffs(x, coeffs):\n    x = abs(x)\n    coeffs[0] = 1 - x\n    coeffs[1] = x\n    \ndef _gs_bicubic_interpolate(p, x, y):  # type: ignore\n    v = np.empty((4,), dtype=p.dtype)\n    coeffs = np.empty((4,), dtype=p.dtype)\n    _gs_get_cubic_coeffs(x, coeffs)\n    for i in range(4):\n        v[i] = coeffs @ p[i, :]\n    _gs_get_cubic_coeffs(y, coeffs)\n    return coeffs @ v\n\ndef _gs_cubic_interpolation_1d_with_x(data, x, border, padding_mode):\n    v = np.empty((4,), dtype=data.dtype)\n    coeffs = np.empty((4,), dtype=data.dtype)\n    x_0 = int(np.floor(x))\n    x_1 = x_0 + 1\n    x_2 = x_0 + 2\n    x_minus_1 = x_0 - 1\n    _gs_get_cubic_coeffs(x - x_0, coeffs)\n    v[0] = _pixel_at_array(\n        array=data, i=x_minus_1, border=border, padding_mode=padding_mode\n    )\n    v[1] = _pixel_at_array(\n        array=data, i=x_0, border=border, padding_mode=padding_mode\n    )\n    v[2] = _pixel_at_array(\n        array=data, i=x_1, border=border, padding_mode=padding_mode\n    )\n    v[3] = _pixel_at_array(\n        array=data, i=x_2, border=border, padding_mode=padding_mode\n    )\n    return coeffs @ v\n\ndef _gs_linear_interpolation_1d_with_x(data, x, border, padding_mode):\n    v = np.empty((2,), dtype=data.dtype)\n    coeffs = np.empty((2,), dtype=data.dtype)\n    x_0 = int(np.floor(x))\n    x_1 = x_0 + 1\n    _gs_get_linear_coeffs(x - x_0, coeffs)\n    v[0] = _pixel_at_array(\n        array=data, i=x_0, border=border, padding_mode=padding_mode\n    )\n    v[1] = _pixel_at_array(\n        array=data, i=x_1, border=border, padding_mode=padding_mode\n    )\n    return coeffs @ v\n\ndef _gs_linear_interpolation_nd_with_x(data, x, border, padding_mode):\n    num_dims = data.ndim\n    assert num_dims == len(x) == int(len(border) / 2)\n    if num_dims == 1:\n        return _gs_linear_interpolation_1d_with_x(\n            data=data, x=x[0], border=border, padding_mode=padding_mode\n        )\n    res1d = []\n    for i in range(data.shape[0]):\n        r = _gs_linear_interpolation_nd_with_x(\n            data=data[i],\n            x=x[1:],\n            border=list(border[1:num_dims])\n            + list(border[1 + num_dims : 2 * num_dims]),\n            padding_mode=padding_mode,\n        )\n        res1d.append(r)\n    res1d = np.array(res1d)\n    return _gs_linear_interpolation_1d_with_x(\n        data=res1d,\n        x=x[0],\n        border=[border[0], border[num_dims]],\n        padding_mode=padding_mode,\n    )\n    \ndef _gs_cubic_interpolation_nd_with_x(data, x, border, padding_mode):\n    num_dims = data.ndim\n    assert num_dims == len(x) == int(len(border) / 2)\n    if num_dims == 1:\n        return _gs_cubic_interpolation_1d_with_x(\n            data=data, x=x[0], border=border, padding_mode=padding_mode\n        )\n    res1d = []\n    for i in range(data.shape[0]):\n        r = _gs_cubic_interpolation_nd_with_x(\n            data=data[i],\n            x=x[1:],\n            border=list(border[1:num_dims])\n            + list(border[1 + num_dims : 2 * num_dims]),\n            padding_mode=padding_mode,\n        )\n        res1d.append(r)\n    res1d = np.array(res1d)\n    return _gs_cubic_interpolation_1d_with_x(\n        data=res1d,\n        x=x[0],\n        border=[border[0], border[num_dims]],\n        padding_mode=padding_mode,\n    )\n    \ndef _clamp(val, lo, hi):  # type: ignore\n    if val < lo:\n        return lo\n    if val > hi:\n        return hi\n    return val\n\ndef _pixel_at_ndarray(ndarray, x: List, border, padding_mode):  # type: ignore\n    # boarder: [x_1_min, x_2_min, ..., x_1_max, x_2_max, ...]\n    num_dims = ndarray.ndim\n    assert num_dims == len(x) == int(len(border) / 2)\n    if num_dims == 1:\n        return _pixel_at_array(\n            array=ndarray, i=x[0], border=border, padding_mode=padding_mode\n        )\n    i = x[0]\n    d = ndarray.shape[0]\n    if padding_mode == \"zeros\":\n        if i >= 0 and i < d:\n            ndarray = ndarray[i]\n        else:\n            # Trick\n            i = 0\n            ndarray = np.zeros_like(ndarray[i])\n    elif padding_mode == \"border\":\n        i = _clamp(i, 0, d - 1)\n        ndarray = ndarray[i]\n    else: \n        i = int(_gs_reflect(i, border[0], border[num_dims]))\n        ndarray = ndarray[i]\n    return _pixel_at_ndarray(\n        ndarray=ndarray,\n        x=x[1:],\n        border=list(border[1:num_dims]) + list(border[1 + num_dims : 2 * num_dims]),\n        padding_mode=padding_mode,\n    )\ndef _pixel_at_array(array, i: int, border, padding_mode):  # type: ignore\n    assert array.ndim == 1\n    d = array.shape[0]\n    if padding_mode == \"zeros\":\n        if i >= 0 and i < d:\n            pixel = array[i]\n        else:\n            pixel = 0\n    elif padding_mode == \"border\":\n        i = _clamp(i, 0, d - 1)\n        pixel = array[i]\n    else: \n        i = int(_gs_reflect(i, border[0], border[1]))\n        pixel = array[i]\n    return pixel\n\ndef _prepare_border(dims, align_corners: bool):\n    # boarder: [x_1_min, x_2_min, ..., x_1_max, x_2_max, ...]\n    num_dims = len(dims)\n    borders = np.zeros(num_dims * 2)\n    for i in range(num_dims):\n        # min\n        borders[i] = -0.5\n        # max\n        borders[i + num_dims] = dims[i] - 0.5\n        if align_corners:\n            # min\n            borders[i] = 0.0\n            # max\n            borders[i + num_dims] = dims[i] - 1.0\n    return borders\n\n\nclass Grid_sample(RunAll):\n    \n    @staticmethod\n    def export_gridsample() -> None:\n        x = np.array(\n            [\n                [\n                    [\n                        [0.0, 1.0, 2.0, 3.0],\n                        [4.0, 5.0, 6.0, 7.0],\n                        [8.0, 9.0, 10.0, 11.0],\n                        [12.0, 13.0, 14.0, 15.0],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n        \n        grid = np.array(\n            [\n                [\n                    [\n                        [-1.0000, -1.0000],\n                        [-0.6000, -1.0000],\n                        [-0.2000, -1.0000],\n                        [0.2000, -1.0000],\n                        [0.6000, -1.0000],\n                        [1.0000, -1.0000],\n                    ],\n                    [\n                        [-1.0000, -0.6000],\n                        [-0.6000, -0.6000],\n                        [-0.2000, -0.6000],\n                        [0.2000, -0.6000],\n                        [0.6000, -0.6000],\n                        [1.0000, -0.6000],\n                    ],\n                    [\n                        [-1.0000, -0.2000],\n                        [-0.6000, -0.2000],\n                        [-0.2000, -0.2000],\n                        [0.2000, -0.2000],\n                        [0.6000, -0.2000],\n                        [1.0000, -0.2000],\n                    ],\n                    [\n                        [-1.0000, 0.2000],\n                        [-0.6000, 0.2000],\n                        [-0.2000, 0.2000],\n                        [0.2000, 0.2000],\n                        [0.6000, 0.2000],\n                        [1.0000, 0.2000],\n                    ],\n                    [\n                        [-1.0000, 0.6000],\n                        [-0.6000, 0.6000],\n                        [-0.2000, 0.6000],\n                        [0.2000, 0.6000],\n                        [0.6000, 0.6000],\n                        [1.0000, 0.6000],\n                    ],\n                    [\n                        [-1.0000, 1.0000],\n                        [-0.6000, 1.0000],\n                        [-0.2000, 1.0000],\n                        [0.2000, 1.0000],\n                        [0.6000, 1.0000],\n                        [1.0000, 1.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n        \n        y = grid_sample(x, grid, mode =\"linear\")\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_gridsample_paddingmode_zeros() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-10.0000, -10.0000],\n                        [-5.0000, -5.0000],\n                        [-0.2000, -0.2000],\n                        [10.0000, 10.0000],\n                    ],\n                    [\n                        [10.0000, 10.0000],\n                        [-0.2000, -0.2000],\n                        [5.0000, 5.0000],\n                        [10.0000, 10.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"linear\")\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_padding_zeros\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_gridsample_paddingmode_border() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-10.0000, -10.0000],\n                        [-5.0000, -5.0000],\n                        [-0.2000, -0.2000],\n                        [10.0000, 10.0000],\n                    ],\n                    [\n                        [10.0000, 10.0000],\n                        [-0.2000, -0.2000],\n                        [5.0000, 5.0000],\n                        [10.0000, 10.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"linear\", padding_mode=\"border\")\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_padding_border\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(PADDING_MODE::BORDER))\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_gridsample_paddingmode_reflection() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-10.0000, -10.0000],\n                        [-5.0000, -5.0000],\n                        [-0.2000, -0.2000],\n                        [10.0000, 10.0000],\n                    ],\n                    [\n                        [10.0000, 10.0000],\n                        [-0.2000, -0.2000],\n                        [5.0000, 5.0000],\n                        [10.0000, 10.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n        \n        y = grid_sample(x, grid, mode =\"linear\", padding_mode=\"reflection\")\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_padding_reflection\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(PADDING_MODE::REFLECTION))\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_gridsample_mode_aligncorners() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-1.0000, -1.0000],\n                        [-0.5000, -0.5000],\n                        [-0.2000, -0.2000],\n                        [0.0000, 0.0000],\n                    ],\n                    [\n                        [0.0000, 0.0000],\n                        [-0.2000, -0.2000],\n                        [0.5000, 0.5000],\n                        [1.0000, 1.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"linear\", align_corners=1)\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_aligncorners\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n              \n        \n    @staticmethod\n    def export_gridsample_nearest() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-1.0000, -1.0000],\n                        [-0.5000, -0.5000],\n                        [-0.2000, -0.2000],\n                        [0.0000, 0.0000],\n                    ],\n                    [\n                        [0.0000, 0.0000],\n                        [-0.2000, -0.2000],\n                        [0.5000, 0.5000],\n                        [1.0000, 1.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"nearest\", align_corners=0)\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_nearest\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::Some(0),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n  \n    @staticmethod\n    def export_gridsample_nearest_align_corner() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-1.0000, -1.0000],\n                        [-0.5000, -0.5000],\n                        [-0.2000, -0.2000],\n                        [0.0000, 0.0000],\n                    ],\n                    [\n                        [0.0000, 0.0000],\n                        [-0.2000, -0.2000],\n                        [0.5000, 0.5000],\n                        [1.0000, 1.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"nearest\", align_corners=1)\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_nearest_aligncorner\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n        \n    @staticmethod\n    def export_gridsample_cubic() -> None:\n        x = np.array(\n            [[[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]]],\n            dtype=np.float32,\n        )\n        grid = np.array(\n            [\n                [\n                    [\n                        [-1.0000, -1.0000],\n                        [-0.5000, -0.5000],\n                        [-0.2000, -0.2000],\n                        [0.0000, 0.0000],\n                    ],\n                    [\n                        [0.0000, 0.0000],\n                        [-0.2000, -0.2000],\n                        [0.5000, 0.5000],\n                        [1.0000, 1.0000],\n                    ],\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        y = grid_sample(x, grid, mode =\"cubic\", align_corners=0)\n        y = np.array(y[0])\n        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        grid = Tensor(Dtype.FP16x16, grid.shape, to_fp(grid.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n\n        name = \"grid_sample_cubic\"\n        func_sig = \"NNTrait::grid_sample(\"\n        func_sig += \"@input_0,\"\n        func_sig += \"@input_1,\"\n        func_sig += \"Option::Some(0),\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None)\"\n        make_test(\n            [x, grid], y, func_sig, name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/hamming_window.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait, get_data_statement\n\ndef hamming_window(size, output_datatype=None, periodic=None) -> np.ndarray:  # type: ignore\n    if periodic == 1:\n        N_1 = size\n    else:\n        N_1 = size - 1\n    ni = np.arange(size, dtype=output_datatype)\n    alpha = 25.0 / 46.0\n    beta = 1 - alpha\n    res = alpha - np.cos(ni * np.float64(np.pi).astype(output_datatype) * 2 / N_1).astype(output_datatype) * beta\n    return res.astype(output_datatype)\n\nclass Hamming_window(RunAll):\n     \n    @staticmethod\n    # We test here with fp8x23 implementation.\n    def fp8x23():\n        args = [4]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP8x23), Dtype.FP8x23)\n        y = hamming_window(*args, np.float64)\n        \n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        # Define the name of the generated folder. \n        name = \"hamming_window_fp8x23\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::hamming_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with fp16x16 implementation.\n    def fp16x16():\n        args = [10]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP16x16), Dtype.FP16x16)\n        y = hamming_window(*args, np.float16)\n        \n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        \n        # Define the name of the generated folder. \n        name = \"hamming_window_fp16x16\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::hamming_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    # @staticmethod\n    # # We test here with i8 implementation.\n    # def i8():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I8))\n    #     args = [5]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I8)\n    #     y = hamming_window(*args, np.int8)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I8, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hamming_window_i8\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hamming_window({','.join(args_str)}, Option::Some(1))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n    \n    # @staticmethod\n    # # We test here with i32 implementation.\n    # def i32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I32)\n    #     y = hamming_window(*args, np.int32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hamming_window_i32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hamming_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n     \n    # @staticmethod\n    # # We test here with u32 implementation.\n    # def u32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.U32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.U32)\n    #     y = hamming_window(*args, np.uint32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.U32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hamming_window_u32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hamming_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n        "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/hann_window.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait, get_data_statement\n\ndef hann_window(size, output_datatype=None, periodic=None) -> np.ndarray:  # type: ignore\n    if periodic == 1:\n        N_1 = size\n    else:\n        N_1 = size - 1\n    ni = np.arange(size, dtype=output_datatype)\n    res = np.sin((ni * np.float64(np.pi).astype(output_datatype) / N_1).astype(output_datatype)) ** 2\n    return res.astype(output_datatype)\n\nclass Hann_window(RunAll):\n     \n    @staticmethod\n    # We test here with fp8x23 implementation.\n    def fp8x23():\n        print(get_data_statement(to_fp(np.array([np.pi]).flatten(), FixedImpl.FP8x23), Dtype.FP8x23))\n        args = [4]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP8x23), Dtype.FP8x23)\n        y = hann_window(*args, np.float64)\n        print(y)\n        \n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        # Define the name of the generated folder. \n        name = \"hann_window_fp8x23\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::hann_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with fp16x16 implementation.\n    def fp16x16():\n        print(get_data_statement(to_fp(np.array([np.pi]).flatten(), FixedImpl.FP16x16), Dtype.FP16x16))\n        args = [10]\n        # x = np.float64(4)\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP16x16), Dtype.FP16x16)\n        y = hann_window(*args, np.float16)\n        print(y)\n        \n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        \n        # Define the name of the generated folder. \n        name = \"hann_window_fp16x16\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::hann_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n            name # The name of the generated folder.\n        )\n     \n    # @staticmethod\n    # # We test here with i8 implementation.\n    # def i8():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I8))\n    #     args = [5]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I8)\n    #     y = hann_window(*args, np.int8)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I8, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hann_window_i8\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hann_window({','.join(args_str)}, Option::Some(1))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n    \n    # @staticmethod\n    # # We test here with i32 implementation.\n    # def i32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.I32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.I32)\n    #     y = hann_window(*args, np.int32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.I32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hann_window_i32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hann_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n     \n    # @staticmethod\n    # # We test here with u32 implementation.\n    # def u32():\n    #     print(get_data_statement(np.array([np.pi]).flatten(), Dtype.U32))\n    #     args = [4]\n    #     # x = np.float64(4)\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.U32)\n    #     y = hann_window(*args, np.uint32)\n    #     print(y)\n        \n    #     # Convert the floats values in `y` to fixed points with `to_fp` method:\n    #     y = Tensor(Dtype.U32, y.shape, y.flatten())\n        \n    #     # Define the name of the generated folder. \n    #     name = \"hann_window_u32\"\n    #     # Invoke `make_test` method to generate corresponding Cairo tests:\n    #     make_test(\n    #         [], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::hann_window({','.join(args_str)}, Option::Some(0))\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n        "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/hard_sigmoid.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nclass Hard_sigmoid(RunAll):\n\n    @staticmethod\n    def fp8x23():\n        alpha = 0.2\n        beta = 0.5\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float32)\n        y = np.maximum(0, np.minimum(1, alpha * x + beta))\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"hard_sigmoid_fp8x23\"\n        make_test([x], y, \"NNTrait::hard_sigmoid(@input_0, @FixedTrait::new(1677721, false), @FixedTrait::new(4194304, false))\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fp16x16():\n        alpha = 0.2\n        beta = 0.5\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float32)\n        y = np.maximum(0, np.minimum(1, alpha * x + beta)) \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"hard_sigmoid_fp16x16\"\n        make_test([x], y, \"NNTrait::hard_sigmoid(@input_0, @FixedTrait::new(13107, false), @FixedTrait::new(32768, false))\",\n                    name, Trait.NN)\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/identity.py",
        "content": "import numpy as np \nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Identity(RunAll):\n\n    @staticmethod\n    def identity_fP8x23():\n        def identity():\n            x = np.array([[1, 2], [3, 4]])\n            y = x\n           \n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"identity_fP8x23\"\n\n            make_test(\n                [x], y, \"input_0.identity()\", name)\n        identity()\n\n    @staticmethod\n    def identity_fP16x16():\n        def identity():\n            x = np.array([[1, 2], [3, 4]])\n            y = x\n           \n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"identity_fP16x16\"\n\n            make_test(\n                [x], y, \"input_0.identity()\", name)\n        identity()\n\n    @staticmethod\n    def identity_i8():\n        def identity():\n            x = np.array([[1, 2], [3, 4]])\n            y = x\n           \n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"identity_i8\"\n\n            make_test(\n                [x], y, \"input_0.identity()\", name)\n        identity()\n\n    @staticmethod\n    def identity_i32():\n        def identity():\n            x = np.array([[1, 2], [3, 4]])\n            y = x\n           \n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"identity_i32\"\n\n            make_test(\n                [x], y, \"input_0.identity()\", name)\n        identity()\n\n    @staticmethod\n    def identity_u32():\n        def identity():\n            x = np.array([[1, 2], [3, 4]])\n            y = x\n           \n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"identity_u32\"\n\n            make_test(\n                [x], y, \"input_0.identity()\", name)\n        identity()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/is_inf.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nINF = 2**32 - 1\n\nclass Is_inf(RunAll):\n\n    @staticmethod\n    def is_inf_u32():\n        def default():\n            input_0 = np.array([1, 0, INF, 8, -INF, INF], dtype=np.uint32)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.U32, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n\n            name = \"is_inf_u32\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::None, Option::None)\", name)\n\n        default()\n\n    @staticmethod\n    def is_inf_i32():\n        def default():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int32)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.I32, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_inf_i32\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::None, Option::None)\", name)\n\n        def positive():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int32)\n            output = np.array([False, False, True, False, False, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.I32, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_pos_inf_i32\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1))\", name)\n\n        def negative():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int32)\n            output = np.array([False, False, False, False, True, False], dtype=bool)\n\n            input_0 = Tensor(Dtype.I32, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_neg_inf_i32\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0))\", name)\n\n        default()\n        positive()\n        negative()\n\n    @staticmethod\n    def is_inf_i8():\n        def default():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int8)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.I8, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_inf_i8\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::None, Option::None)\", name)\n\n        def positive():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int32)\n            output = np.array([False, False, True, False, False, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.I8, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_pos_inf_i8\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1))\", name)\n\n        def negative():\n            input_0 = np.array([-1, 0, INF, 8, -INF, INF], dtype=np.int32)\n            output = np.array([False, False, False, False, True, False], dtype=bool)\n\n            input_0 = Tensor(Dtype.I8, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_neg_inf_i8\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0))\", name)\n\n        default()\n        positive()\n        negative()\n\n    @staticmethod\n    def is_inf_fp8x23():\n        def default():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP8x23, input_0.shape, to_fp(\n                input_0.flatten(), FixedImpl.FP8x23))\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_inf_fp8x23\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::None, Option::None)\", name)\n\n        def positive():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, True, False, False, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP8x23, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_pos_inf_fp8x23\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1))\", name)\n\n        def negative():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, False, False, True, False], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP8x23, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_neg_inf_fp8x23\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0))\", name)\n\n        default()\n        positive()\n        negative()\n\n    @staticmethod\n    def is_inf_fp16x16():\n        def default():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP16x16, input_0.shape, to_fp(\n                input_0.flatten(), FixedImpl.FP16x16))\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_inf_fp16x16\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::None, Option::None)\", name)\n\n        def positive():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, True, False, False, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP16x16, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_pos_inf_fp16x16\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1))\", name)\n\n        def negative():\n            input_0 = np.array([-1.2, 0, INF, 2.8, -INF, INF], dtype=np.float64)\n            output = np.array([False, False, False, False, True, False], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP16x16, input_0.shape, input_0.flatten())\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_neg_inf_fp16x16\"\n            make_test([input_0], output, \"TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0))\", name)\n\n        default()\n        positive()\n        negative()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/is_nan.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\n# NaN is represented with -0\nNaN = -0\n\nclass Is_nan(RunAll):\n\n    @staticmethod\n    def is_nan_fp8x23():\n        def default():\n            input_0 = np.array([-1.2, 0, NaN, 2.8, NaN, NaN], dtype=np.float64)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP8x23, input_0.shape, to_fp(\n                input_0.flatten(), FixedImpl.FP8x23))\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_nan_fp8x23\"\n            make_test([input_0], output, \"TensorTrait::is_nan(@input_0)\", name)\n\n        default()\n\n    @staticmethod\n    def is_nan_fp16x16():\n        def default():\n            input_0 = np.array([-1.2, 0, NaN, 2.8, NaN, NaN], dtype=np.float64)\n            output = np.array([False, False, True, False, True, True], dtype=bool)\n\n            input_0 = Tensor(Dtype.FP16x16, input_0.shape, to_fp(\n                input_0.flatten(), FixedImpl.FP16x16))\n            output = Tensor(Dtype.BOOL, output.shape, output.flatten())\n            \n            name = \"is_nan_fp16x16\"\n            make_test([input_0], output, \"TensorTrait::is_nan(@input_0)\", name)\n\n        default()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/label_encoder.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n# Copyright (c) ONNX Project Contributors\n\n# SPDX-License-Identifier: Apache-2.0\n# pylint: disable=R0913,R0914,W0221\ndef labelEncoder(  # type: ignore\n    x,\n    default_float=None,\n    default_int64=None,\n    default_string=None,\n    keys_floats=None,\n    keys_int64s=None,\n    keys_strings=None,\n    values_floats=None,\n    values_int64s=None,\n    values_strings=None,\n):\n    keys = keys_floats if keys_floats is not None else (keys_int64s if np.any(keys_int64s) else keys_strings)\n    values = values_floats if values_floats is not None else (values_int64s if np.any(values_int64s) else values_strings)\n\n    classes = dict(zip(keys, values))\n    if id(keys) == id(keys_floats):\n        cast = float\n    elif id(keys) == id(keys_int64s):\n        cast = int  # type: ignore\n    else:\n        cast = str  # type: ignore\n    if id(values) == id(values_floats):\n        defval = default_float\n        dtype = np.float32\n    elif id(values) == id(values_int64s):\n        defval = default_int64\n        dtype = np.int64  # type: ignore\n    else:\n        defval = default_string\n        if not isinstance(defval, str):\n            defval = \"\"\n        dtype = np.str_  # type: ignore\n    shape = x.shape\n    if len(x.shape) > 1:\n        x = x.flatten()\n    res = []\n    for i in range(0, x.shape[0]):\n        v = classes.get(cast(x[i]), defval)\n        res.append(v)\n    return np.array(res, dtype=dtype).reshape(shape)\n\nclass Label_encoder(RunAll):\n\n    @staticmethod\n    def label_encoder_fp16x16():\n            \n        def labelencoder():\n            def default():\n                x = np.array([1, 2, 3, 4, 5, 6, 1, 2, 3]).astype(np.int64)\n                keys = np.array([1, 2, 5, 6, ]).astype(np.int64)\n                values = np.array([11, 22, 55, 66]).astype(np.int64)\n                default = np.array(99).astype(np.int64)\n\n                y = labelEncoder(x=x, keys_int64s=keys, values_int64s=values, default_int64=default)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n                default = Tensor(Dtype.FP16x16, default.shape, to_fp(default.flatten(), FixedImpl.FP16x16))\n                keys = Tensor(Dtype.FP16x16, keys.shape, to_fp(keys.flatten(), FixedImpl.FP16x16))\n                values = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"label_encoder_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x, default, keys, values], output = y, func_sig = \"\"\"input_0.label_encoder(default_list:Option::None, default_tensor: Option::Some(input_1), \n                    keys:Option::None, keys_tensor: Option::Some(input_2),\n                    values: Option::None, values_tensor: Option::Some(input_3))\"\"\", \n                    name= name)\n            \n            default()\n        labelencoder()\n\n    @staticmethod\n    def label_encoder_fp8x23():\n            \n        def label_encoder():\n            def default():\n                \n                x = np.array([1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8]).astype(np.int64)\n                keys = np.array([1, 2, 5, 6, 7]).astype(np.int64)\n                values = np.array([11, 22, 55, 66, 77]).astype(np.int64)\n                default = np.array(99).astype(np.int64)\n\n                y = labelEncoder(x=x, keys_int64s=keys, values_int64s=values, default_int64=default)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(x.flatten(), FixedImpl.FP8x23))\n                default = Tensor(Dtype.FP8x23, default.shape, to_fp(default.flatten(), FixedImpl.FP8x23))\n                keys = Tensor(Dtype.FP8x23, keys.shape, to_fp(keys.flatten(), FixedImpl.FP8x23))\n                values = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"label_encoder_fp8x23_default\"\n\n                make_test(\n                    inputs = [x, default, keys, values], output = y, func_sig = \"\"\"input_0.label_encoder(default_list:Option::None, default_tensor: Option::Some(input_1), \n                    keys:Option::None, keys_tensor: Option::Some(input_2),\n                    values: Option::None, values_tensor: Option::Some(input_3))\"\"\", \n                    name= name)\n\n          \n                \n            default()\n        label_encoder()\n\n    @staticmethod\n    def label_encoder_i8():\n            \n        def label_encoder_3D():\n            def default():\n\n                x = np.array([1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8]).astype(np.int8)\n                keys = np.array([1, 2, 5, 6, 7]).astype(np.int8)\n                values = np.array([11, 22, 55, 66, 77]).astype(np.int8)\n                default = np.array(99).astype(np.int8)\n\n                y = labelEncoder(x=x, keys_int64s=keys, values_int64s=values, default_int64=default)\n\n                x =  Tensor(Dtype.I8, x.shape, x.flatten())\n                default =  Tensor(Dtype.I8, default.shape, default.flatten())\n                keys =  Tensor(Dtype.I8, keys.shape, keys.flatten())\n                values =  Tensor(Dtype.I8, values.shape, values.flatten())\n                y =  Tensor(Dtype.I8, y.shape, y.flatten())\n\n                name = \"label_encoder_i8_default\"\n                make_test(\n                    inputs = [x, default, keys, values], output = y, func_sig = \"\"\"input_0.label_encoder(default_list:Option::None, default_tensor: Option::Some(input_1), \n                    keys:Option::None, keys_tensor: Option::Some(input_2),\n                    values: Option::None, values_tensor: Option::Some(input_3))\"\"\", \n                    name= name)\n                \n           \n            default()\n        label_encoder_3D()\n\n\n    @staticmethod\n    def label_encoder_i32():\n        def label_encoder_3D():\n            def default():\n                x = np.array([1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8]).astype(np.int32)\n                keys = np.array([1, 2, 5, 6, 7]).astype(np.int32)\n                values = np.array([11, 22, 55, 66, 77]).astype(np.int32)\n                default = np.array(99).astype(np.int32)\n\n                y = labelEncoder(x=x, keys_int64s=keys, values_int64s=values, default_int64=default)\n\n                x =  Tensor(Dtype.I32, x.shape, x.flatten())\n                default =  Tensor(Dtype.I32, default.shape, default.flatten())\n                keys =  Tensor(Dtype.I32, keys.shape, keys.flatten())\n                values =  Tensor(Dtype.I32, values.shape, values.flatten())\n                y =  Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"label_encoder_i32_default\"\n                make_test(\n                    inputs = [x, default, keys, values], output = y, func_sig = \"\"\"input_0.label_encoder(default_list:Option::None, default_tensor: Option::Some(input_1), \n                    keys:Option::None, keys_tensor: Option::Some(input_2),\n                    values: Option::None, values_tensor: Option::Some(input_3))\"\"\", \n                    name= name)\n                \n                \n           \n                \n            default()\n        label_encoder_3D()\n\n\n    @staticmethod\n    def label_encoder_u32():\n            \n        def label_encoder_3D():\n            def default():\n\n                x = np.array([1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8]).astype(np.uint32)\n                keys = np.array([1, 2, 5, 6, 7]).astype(np.uint32)\n                values = np.array([11, 22, 55, 66, 77]).astype(np.uint32)\n                default = np.array(99).astype(np.uint32)\n\n                y = labelEncoder(x=x, keys_int64s=keys, values_int64s=values, default_int64=default)\n\n                x =  Tensor(Dtype.U32, x.shape, x.flatten())\n                default =  Tensor(Dtype.U32, default.shape, default.flatten())\n                keys =  Tensor(Dtype.U32, keys.shape, keys.flatten())\n                values =  Tensor(Dtype.U32, values.shape, values.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten())\n                \n                name = \"label_encoder_u32_default\"\n\n                make_test(\n                    inputs = [x, default, keys, values], output = y, func_sig = \"\"\"input_0.label_encoder(default_list:Option::None, default_tensor: Option::Some(input_1), \n                    keys:Option::None, keys_tensor: Option::Some(input_2),\n                    values: Option::None, values_tensor: Option::Some(input_3))\"\"\", \n                    name= name)\n                \n           \n            default()\n        label_encoder_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/layer_normalization.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\nimport numpy as np\n\nimport onnx\nfrom onnx.backend.test.case.base import Base\nfrom onnx.backend.test.case.node import expect\n\n\ndef _layer_normalization(X, W, B, axis=-1, epsilon=1e-5): \n    X_shape = X.shape\n    X_rank = len(X_shape)\n    if axis < 0:\n        axis = axis + X_rank\n    unsqueezed_rank = X_rank - axis\n    reduction_shape = X_shape[0:axis] + (1,) * unsqueezed_rank\n\n    row_number = 1\n    col_number = 1\n    for i in range(X_rank):\n        if i < axis:\n            row_number *= X_shape[i]\n        else:\n            col_number *= X_shape[i]\n    x_mat = np.reshape(X, (row_number, col_number))\n    x_mean = np.sum(x_mat, axis=1, keepdims=True) / col_number\n    x_diff = x_mat - x_mean\n    x_squared_diff = x_diff * x_diff\n    variance = np.sum(x_squared_diff, axis=1, keepdims=True) / col_number\n    variance_eps = variance + epsilon\n    std_dev = np.sqrt(variance_eps)\n    inv_std_dev = np.reciprocal(std_dev)\n    y_mat = x_diff * inv_std_dev\n    Y = np.reshape(y_mat, X_shape) * W + B\n    X_mean = np.reshape(x_mean, reduction_shape)\n    X_inv_std_dev = np.reshape(inv_std_dev, reduction_shape)\n\n    return Y, X_mean, X_inv_std_dev\n\n\ndef calculate_normalized_shape(X_shape, axis):  \n    X_rank = len(X_shape)\n    if axis < 0:\n        axis = axis + X_rank\n    return X_shape[axis:]\n\n\nclass Layer_normalization(RunAll):\n    @staticmethod\n    def export4d() -> None:\n        X = np.random.randn(2, 3, 4, 5).astype(np.float32)\n\n        def case(axis: int) -> None:\n            normalized_shape = calculate_normalized_shape(X.shape, axis)\n            W = np.random.randn(*normalized_shape).astype(np.float32)\n            B = np.random.randn(*normalized_shape).astype(np.float32)\n            Y, mean, inv_std_dev = _layer_normalization(X, W, B, axis)\n\n            if axis < 0:\n                name = f\"layer_normalization_4d_axis_negative_{-axis}\"\n                func_sig = f\"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::Some({-axis}),Option::None,Option::None)\"\n            else:\n                name = f\"layer_normalization_4d_axis{axis}\"\n                func_sig = f\"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::Some({axis}),Option::None,Option::None)\"\n\n\n            x = Tensor(Dtype.FP8x23, X.shape, to_fp(X.flatten(), FixedImpl.FP8x23))\n            w = Tensor(Dtype.FP8x23, W.shape, to_fp(W.flatten(), FixedImpl.FP8x23))\n            b = Tensor(Dtype.FP8x23, B.shape, to_fp(B.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, Y.shape, to_fp(Y.flatten(), FixedImpl.FP8x23))\n            \n            make_test([x,w,b], y, func_sig, name)\n\n\n        for i in range(len(X.shape)):\n            case(i)\n            case(i - len(X.shape))\n\n    @staticmethod\n    def export_default_axis() -> None:\n        X = np.random.randn(2, 3, 4, 5).astype(np.float32)\n\n        normalized_shape = calculate_normalized_shape(X.shape, -1)\n        W = np.random.randn(*normalized_shape).astype(np.float32)\n        B = np.random.randn(*normalized_shape).astype(np.float32)\n        Y, mean, inv_std_dev = _layer_normalization(X, W, B)\n\n        x = Tensor(Dtype.FP16x16, X.shape, to_fp(X.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, W.shape, to_fp(W.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, B.shape, to_fp(B.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, Y.shape, to_fp(Y.flatten(), FixedImpl.FP16x16))\n        \n        name = \"layer_normalization_default_axis\"\n        make_test([x,w,b], y, \"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::None,Option::None,Option::None)\", name)\n\n    @staticmethod\n    def export3d_epsilon() -> None:\n        epsilon = 1e-1\n        X = np.random.randn(2, 3, 5).astype(np.float32)\n\n        def case(axis: int) -> None:\n            normalized_shape = calculate_normalized_shape(X.shape, axis)\n            W = np.random.randn(*normalized_shape).astype(np.float32)\n            B = np.random.randn(*normalized_shape).astype(np.float32)\n            Y, mean, inv_std_dev = _layer_normalization(X, W, B, axis, epsilon)\n\n            if axis < 0:\n                name = f\"layer_normalization_3d_axis_negative_{-axis}_epsilon\"\n                func_sig = f\"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::Some({-axis}),Option::Some(FixedTrait::new(6554, false)),Option::None)\"\n            else:\n                name = f\"layer_normalization_3d_axis{axis}_epsilon\"\n                func_sig = f\"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::Some({axis}),Option::Some(FixedTrait::new(6554, false)),Option::None)\"\n\n            x = Tensor(Dtype.FP16x16, X.shape, to_fp(X.flatten(), FixedImpl.FP16x16))\n            w = Tensor(Dtype.FP16x16, W.shape, to_fp(W.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, B.shape, to_fp(B.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, Y.shape, to_fp(Y.flatten(), FixedImpl.FP16x16))\n            \n            make_test([x,w,b], y, func_sig, name)\n\n\n        for i in range(len(X.shape)):\n            case(i)\n            case(i - len(X.shape))\n\n    @staticmethod\n    def test_2d_example() -> None:\n        X = np.random.randn(3, 4).astype(np.float32)\n\n        def case(axis: int) -> None:\n            normalized_shape = calculate_normalized_shape(X.shape, axis)\n            W = np.random.randn(*normalized_shape).astype(np.float32)\n            B = np.random.randn(*normalized_shape).astype(np.float32)\n            Y, mean, inv_std_dev = _layer_normalization(X, W, B, axis=axis)\n\n            node = onnx.helper.make_node(\n                \"LayerNormalization\",\n                inputs=[\"X\", \"W\", \"B\"],\n                outputs=[\"Y\", \"Mean\", \"InvStdDev\"],\n                axis=axis,\n            )\n\n            x = Tensor(Dtype.FP16x16, X.shape, to_fp(X.flatten(), FixedImpl.FP16x16))\n            w = Tensor(Dtype.FP16x16, W.shape, to_fp(W.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, B.shape, to_fp(B.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, Y.shape, to_fp(Y.flatten(), FixedImpl.FP16x16))\n\n            name = \"layer_normalization_test\"\n            make_test([x,w,b], y, \"input_0.layer_normalization(@input_1,Option::Some(@input_2),Option::None,Option::None,Option::None)\", name)\n\n        case(-1)"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/leaky_relu.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\nimport tensorflow as tf\n\n\nclass Leaky_relu(RunAll):\n\n    @staticmethod\n    def leaky_relu_fp8x23():\n\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        layer = tf.keras.layers.LeakyReLU(alpha=0.1)\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"leaky_relu_fp8x23\"\n        make_test([x], y, \"NNTrait::leaky_relu(@input_0, @FixedTrait::new(838861, false))\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def leaky_relu_fp16x16():\n\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        layer = tf.keras.layers.LeakyReLU(alpha=0.1)\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"leaky_relu_fp16x16\"\n        make_test([x], y, \"NNTrait::leaky_relu(@input_0, @FixedTrait::new(6554, false))\",\n                  name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/less.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Less(RunAll):\n    @staticmethod\n    def less_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_u32\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 3, 1)).astype(np.uint32)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_u32_broadcast\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_i32\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int32)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_i32_broadcast\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_i8\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int8)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_i8_broadcast\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_fp8x23\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_fp16x16\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = np.less(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.less(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/less_equal.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Less_equal(RunAll):\n    @staticmethod\n    def less_equal_u32():\n        def default():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_u32\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_u32_broadcast\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_equal_i32():\n        def default():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_i32\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int32)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_i32_broadcast\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_equal_i8():\n        def default():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_i8\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int8)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_i8_broadcast\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_equal_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_fp8x23\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def less_equal_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_fp16x16\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.less_equal(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"less_equal_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.less_equal(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/linear.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\nfrom typing import Optional\n\n\ndef linear(\n    i: np.ndarray,\n    w: np.ndarray,\n    b: Optional[np.ndarray] = None,\n\n) -> np.ndarray:\n    return np.dot(i, w.T) + b\n\n\nclass Linear(RunAll):\n\n    @staticmethod\n    def linear_i32():\n        i = np.random.randint(-5, 9, (3)).astype(np.int32)\n        w = np.random.randint(-5, 9, (2, 3)).astype(np.int32)\n        b = np.random.randint(-5, 9, (2)).astype(np.int32)\n        y = linear(i, w, b)\n\n        i = Tensor(Dtype.I32, i.shape, i.flatten())\n        w = Tensor(Dtype.I32, w.shape, w.flatten())\n        b = Tensor(Dtype.I32, b.shape, b.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"linear_i32\"\n        make_test([i, w, b], y, \"NNTrait::linear(input_0, input_1, input_2)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def linear_i8():\n        i = np.random.randint(-3, 3, (3)).astype(np.int8)\n        w = np.random.randint(-3, 3, (2, 3)).astype(np.int8)\n        b = np.random.randint(-3, 3, (2)).astype(np.int8)\n        y = linear(i, w, b)\n\n        i = Tensor(Dtype.I8, i.shape, i.flatten())\n        w = Tensor(Dtype.I8, w.shape, w.flatten())\n        b = Tensor(Dtype.I8, b.shape, b.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"linear_i8\"\n        make_test([i, w, b], y, \"NNTrait::linear(input_0, input_1, input_2)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def linear_u32():\n        i = np.random.randint(0, 6, (3)).astype(np.uint32)\n        w = np.random.randint(0, 6, (2, 3)).astype(np.uint32)\n        b = np.random.randint(0, 6, (2)).astype(np.uint32)\n        y = linear(i, w, b)\n\n        i = Tensor(Dtype.U32, i.shape, i.flatten())\n        w = Tensor(Dtype.U32, w.shape, w.flatten())\n        b = Tensor(Dtype.U32, b.shape, b.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"linear_u32\"\n        make_test([i, w, b], y, \"NNTrait::linear(input_0, input_1, input_2)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def linear_fp8x23():\n        i = np.random.uniform(-5, 7, (3)).astype(np.float64)\n        w = np.random.uniform(-5, 7, (2, 3)).astype(np.float64)\n        b = np.random.uniform(-5, 7, (2)).astype(np.float64)\n        y = linear(i, w, b)\n\n        i = Tensor(Dtype.FP8x23, i.shape, to_fp(\n            i.flatten(), FixedImpl.FP8x23))\n        w = Tensor(Dtype.FP8x23, w.shape, to_fp(\n            w.flatten(), FixedImpl.FP8x23))\n        b = Tensor(Dtype.FP8x23, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"linear_fp8x23\"\n        make_test([i, w, b], y, \"NNTrait::linear(input_0, input_1, input_2)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def linear_fp16x16():\n        i = np.random.uniform(-5, 7, (3)).astype(np.float64)\n        w = np.random.uniform(-5, 7, (2, 3)).astype(np.float64)\n        b = np.random.uniform(-5, 7, (2)).astype(np.float64)\n        y = linear(i, w, b)\n\n        i = Tensor(Dtype.FP16x16, i.shape, to_fp(\n            i.flatten(), FixedImpl.FP16x16))\n        w = Tensor(Dtype.FP16x16, w.shape, to_fp(\n            w.flatten(), FixedImpl.FP16x16))\n        b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n            b.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"linear_fp16x16\"\n        make_test([i, w, b], y, \"NNTrait::linear(input_0, input_1, input_2)\",\n                  name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/log.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Log(RunAll):\n\n    @staticmethod\n    def log_fp8x23():\n        x = np.random.uniform(1, 127, (2, 2)).astype(np.float64)\n        y = np.log(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"log_fp8x23\"\n        make_test([x], y, \"input_0.log()\", name)\n\n    @staticmethod\n    def log_fp16x16():\n        x = np.random.uniform(1, 127, (2, 2)).astype(np.float64)\n        y = np.log(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"log_fp16x16\"\n        make_test([x], y, \"input_0.log()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/logsoftmax.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef logsoftmax(x: np.ndarray, axis: int = -1) -> np.ndarray:\n    x_max = np.max(x, axis=axis, keepdims=True)\n    tmp = np.exp(x - x_max)\n    s = np.sum(tmp, axis=axis, keepdims=True)\n    return (x - x_max) - np.log(s)\n\n\nclass Logsoftmax(RunAll):\n\n    def logsoftmax_fp8x23():\n        def axis_0():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = logsoftmax(x, 0)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"logsoftmax_fp8x23_axis_0\"\n            make_test([x], y, \"NNTrait::logsoftmax(@input_0, 0)\",\n                      name, Trait.NN)\n\n        def axis_1():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = logsoftmax(x, 1)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"logsoftmax_fp8x23_axis_1\"\n            make_test([x], y, \"NNTrait::logsoftmax(@input_0, 1)\",\n                      name, Trait.NN)\n\n        axis_0()\n        axis_1()\n\n    def logsoftmax_fp16x16():\n        def axis_0():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = logsoftmax(x, 0)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"logsoftmax_fp16x16_axis_0\"\n            make_test([x], y, \"NNTrait::logsoftmax(@input_0, 0)\",\n                      name, Trait.NN)\n\n        def axis_1():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = logsoftmax(x, 1)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"logsoftmax_fp16x16_axis_1\"\n            make_test([x], y, \"NNTrait::logsoftmax(@input_0, 1)\",\n                      name, Trait.NN)\n\n        axis_0()\n        axis_1()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/matmul.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Matmul(RunAll):\n\n    @staticmethod\n    def matmul_u32():\n        def matmul_1D():\n            a = np.random.randint(0, 255, (3)).astype(np.uint32)\n            b = np.random.randint(0, 255, (3)).astype(np.uint32)\n            y = np.matmul(a, b).reshape((1))\n\n            a = Tensor(Dtype.U32, a.shape, a.flatten())\n            b = Tensor(Dtype.U32, b.shape, b.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"matmul_u32_1d\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x2():\n            a = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n            b = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.U32, a.shape, a.flatten())\n            b = Tensor(Dtype.U32, b.shape, b.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"matmul_u32_2x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x1():\n            a = np.random.randint(0, 255, (2, 1)).astype(np.uint32)\n            b = np.random.randint(0, 255, (1, 2)).astype(np.uint32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.U32, a.shape, a.flatten())\n            b = Tensor(Dtype.U32, b.shape, b.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"matmul_u32_2x1\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_1x2():\n            a = np.random.randint(0, 255, (1, 2)).astype(np.uint32)\n            b = np.random.randint(0, 255, (2, 1)).astype(np.uint32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.U32, a.shape, a.flatten())\n            b = Tensor(Dtype.U32, b.shape, b.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"matmul_u32_1x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        matmul_1D()\n        matmul_2x2()\n        matmul_2x1()\n        matmul_1x2()\n\n    @staticmethod\n    def matmul_i32():\n        def matmul_1D():\n            a = np.random.randint(-127, 127, (3)).astype(np.int32)\n            b = np.random.randint(-127, 127, (3)).astype(np.int32)\n            y = np.matmul(a, b).reshape((1))\n\n            a = Tensor(Dtype.I32, a.shape, a.flatten())\n            b = Tensor(Dtype.I32, b.shape, b.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"matmul_i32_1d\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x2():\n            a = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n            b = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I32, a.shape, a.flatten())\n            b = Tensor(Dtype.I32, b.shape, b.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"matmul_i32_2x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x1():\n            a = np.random.randint(-127, 127, (2, 1)).astype(np.int32)\n            b = np.random.randint(-127, 127, (1, 2)).astype(np.int32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I32, a.shape, a.flatten())\n            b = Tensor(Dtype.I32, b.shape, b.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"matmul_i32_2x1\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_1x2():\n            a = np.random.randint(-127, 127, (1, 2)).astype(np.int32)\n            b = np.random.randint(-127, 127, (2, 1)).astype(np.int32)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I32, a.shape, a.flatten())\n            b = Tensor(Dtype.I32, b.shape, b.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"matmul_i32_1x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        matmul_1D()\n        matmul_2x2()\n        matmul_2x1()\n        matmul_1x2()\n\n    @staticmethod\n    def matmul_i8():\n        def matmul_1D():\n            a = np.random.randint(-4, 5, (3)).astype(np.int8)\n            b = np.random.randint(-4, 5, (3)).astype(np.int8)\n            y = np.matmul(a, b).reshape((1))\n\n            a = Tensor(Dtype.I8, a.shape, a.flatten())\n            b = Tensor(Dtype.I8, b.shape, b.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"matmul_i8_1d\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x2():\n            a = np.random.randint(-4, 5, (2, 2)).astype(np.int8)\n            b = np.random.randint(-4, 5, (2, 2)).astype(np.int8)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I8, a.shape, a.flatten())\n            b = Tensor(Dtype.I8, b.shape, b.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"matmul_i8_2x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x1():\n            a = np.random.randint(-4, 5, (2, 1)).astype(np.int8)\n            b = np.random.randint(-4, 5, (1, 2)).astype(np.int8)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I8, a.shape, a.flatten())\n            b = Tensor(Dtype.I8, b.shape, b.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"matmul_i8_2x1\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_1x2():\n            a = np.random.randint(-4, 5, (1, 2)).astype(np.int8)\n            b = np.random.randint(-4, 5, (2, 1)).astype(np.int8)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.I8, a.shape, a.flatten())\n            b = Tensor(Dtype.I8, b.shape, b.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"matmul_i8_1x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        matmul_1D()\n        matmul_2x2()\n        matmul_2x1()\n        matmul_1x2()\n\n    @staticmethod\n    def matmul_fp8x23():\n        def matmul_1D():\n            a = np.random.randint(-3, 4, (3)).astype(np.int64)\n            b = np.random.randint(-3, 4, (3)).astype(np.int64)\n            y = np.matmul(a, b).reshape((1))\n\n            a = Tensor(Dtype.FP8x23, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP8x23))\n            b = Tensor(Dtype.FP8x23, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"matmul_fp8x23_1d\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x2():\n            a = np.random.randint(-3, 4, (2, 2)).astype(np.int64)\n            b = np.random.randint(-3, 4, (2, 2)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP8x23, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP8x23))\n            b = Tensor(Dtype.FP8x23, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"matmul_fp8x23_2x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x1():\n            a = np.random.randint(-3, 4, (2, 1)).astype(np.int64)\n            b = np.random.randint(-3, 4, (1, 2)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP8x23, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP8x23))\n            b = Tensor(Dtype.FP8x23, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"matmul_fp8x23_2x1\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_1x2():\n            a = np.random.randint(-3, 4, (1, 2)).astype(np.int64)\n            b = np.random.randint(-3, 4, (2, 1)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP8x23, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP8x23))\n            b = Tensor(Dtype.FP8x23, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"matmul_fp8x23_1x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        matmul_1D()\n        matmul_2x2()\n        matmul_2x1()\n        matmul_1x2()\n\n    @staticmethod\n    def matmul_fp16x16():\n        def matmul_1D():\n            a = np.random.randint(-3, 4, (3)).astype(np.int64)\n            b = np.random.randint(-3, 4, (3)).astype(np.int64)\n            y = np.matmul(a, b).reshape((1))\n\n            a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"matmul_fp16x16_1d\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x2():\n            a = np.random.randint(-3, 4, (2, 2)).astype(np.int64)\n            b = np.random.randint(-3, 4, (2, 2)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"matmul_fp16x16_2x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_2x1():\n            a = np.random.randint(-3, 4, (2, 1)).astype(np.int64)\n            b = np.random.randint(-3, 4, (1, 2)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"matmul_fp16x16_2x1\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        def matmul_1x2():\n            a = np.random.randint(-3, 4, (1, 2)).astype(np.int64)\n            b = np.random.randint(-3, 4, (2, 1)).astype(np.int64)\n            y = np.matmul(a, b)\n\n            a = Tensor(Dtype.FP16x16, a.shape, to_fp(\n                a.flatten(), FixedImpl.FP16x16))\n            b = Tensor(Dtype.FP16x16, b.shape, to_fp(\n                b.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"matmul_fp16x16_1x2\"\n            make_test(\n                [a, b], y, \"input_0.matmul(@input_1)\", name)\n\n        matmul_1D()\n        matmul_2x2()\n        matmul_2x1()\n        matmul_1x2()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/max.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nclass Max(RunAll):\n\n    @staticmethod\n    def max_u32_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"max_u32_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"max_u32_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_i32_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"max_i32_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int32)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"max_i32_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_i8_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"max_i8_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int8)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int8)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"max_i8_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_fp8x23_two_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"max_fp8x23_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"max_fp8x23_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_fp16x16_two_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"max_fp16x16_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.maximum(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"max_fp16x16_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::max(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n\n    @staticmethod\n    def max_u32_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n            m = Tensor(Dtype.U32, m.shape, m.flatten())\n\n            name = \"max_u32_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.uint32)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n            m = Tensor(Dtype.U32, m.shape, m.flatten())\n\n            name = \"max_u32_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_i32_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n            m = Tensor(Dtype.I32, m.shape, m.flatten())\n\n            name = \"max_i32_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int32)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.int32)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n            m = Tensor(Dtype.I32, m.shape, m.flatten())\n\n            name = \"max_i32_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_i8_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n            m = Tensor(Dtype.I8, m.shape, m.flatten())\n\n            name = \"max_i8_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int8)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int8)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.int8)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n            m = Tensor(Dtype.I8, m.shape, m.flatten())\n\n            name = \"max_i8_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_fp8x23_three_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))  \n            m = Tensor(Dtype.FP8x23, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP8x23)) \n\n            name = \"max_fp8x23_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.random.randint(-3, 3, (1, 1)).astype(np.float64)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))  \n            m = Tensor(Dtype.FP8x23, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP8x23))\n\n            name = \"max_fp8x23_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def max_fp16x16_three_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))    \n            m = Tensor(Dtype.FP16x16, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP16x16))   \n\n            name = \"max_fp16x16_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.random.randint(-3, 3, (1, 1)).astype(np.float64)\n            m = np.maximum(np.maximum(x, y), z)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))    \n            m = Tensor(Dtype.FP16x16, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP16x16)) \n\n            name = \"max_fp16x16_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::max(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/min.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\nclass Min(RunAll):\n\n    @staticmethod\n    def min_u32_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"min_u32_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"min_u32_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_i32_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"min_i32_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int32)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"min_i32_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_i8_two_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"min_i8_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int8)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int8)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"min_i8_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_fp8x23_two_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"min_fp8x23_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"min_fp8x23_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_fp16x16_two_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"min_fp16x16_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.minimum(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"min_fp16x16_broadcast_two_tensors\"\n            make_test([x, y], z, \"TensorTrait::min(array![input_0, input_1].span())\", name)\n\n        default()\n        broadcast()\n\n\n    @staticmethod\n    def min_u32_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n            m = Tensor(Dtype.U32, m.shape, m.flatten())\n\n            name = \"min_u32_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.uint32)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n            m = Tensor(Dtype.U32, m.shape, m.flatten())\n\n            name = \"min_u32_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_i32_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n            m = Tensor(Dtype.I32, m.shape, m.flatten())\n\n            name = \"min_i32_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int32)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.int32)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n            m = Tensor(Dtype.I32, m.shape, m.flatten())\n\n            name = \"min_i32_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_i8_three_tensors():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            z = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n            m = Tensor(Dtype.I8, m.shape, m.flatten())\n\n            name = \"min_i8_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int8)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int8)\n            z = np.random.randint(0, 6, (1, 1)).astype(np.int8)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n            m = Tensor(Dtype.I8, m.shape, m.flatten())\n\n            name = \"min_i8_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_fp8x23_three_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))  \n            m = Tensor(Dtype.FP8x23, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP8x23)) \n\n            name = \"min_fp8x23_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.random.randint(-3, 3, (1, 1)).astype(np.float64)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))  \n            m = Tensor(Dtype.FP8x23, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP8x23))\n\n            name = \"min_fp8x23_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def min_fp16x16_three_tensors():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))    \n            m = Tensor(Dtype.FP16x16, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP16x16))   \n\n            name = \"min_fp16x16_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.random.randint(-3, 3, (1, 1)).astype(np.float64)\n            m = np.minimum(np.minimum(x, y), z)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))    \n            m = Tensor(Dtype.FP16x16, m.shape,  to_fp(\n                m.flatten(), FixedImpl.FP16x16)) \n\n            name = \"min_fp16x16_broadcast_three_tensors\"\n            make_test([x, y, z], m, \"TensorTrait::min(array![input_0, input_1, input_2].span())\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/mul.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Mul(RunAll):\n    @staticmethod\n    def mul_u32():\n        def default():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (3, 3, 3)).astype(np.uint32)\n            z = x * y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"mul_u32\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (1, 3, 1)).astype(np.uint32)\n            z = x * y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"mul_u32_broadcast\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def mul_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = x * y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"mul_i32\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int32)\n            z = x * y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"mul_i32_broadcast\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def mul_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = x * y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"mul_i8\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int8)\n            z = x * y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"mul_i8_broadcast\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def mul_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x * y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"mul_fp8x23\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x * y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"mul_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def mul_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x * y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"mul_fp16x16\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x * y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"mul_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0 * input_1\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/neg.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Neg(RunAll):\n    @staticmethod\n    def neg_i32():\n        x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n        y = np.negative(x)\n\n        x = Tensor(Dtype.I32, x.shape, x.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"neg_i32\"\n        make_test([x], y, \"input_0.neg()\", name)\n\n    @staticmethod\n    def neg_i8():\n        x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n        y = np.negative(x)\n\n        x = Tensor(Dtype.I8, x.shape, x.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"neg_i8\"\n        make_test([x], y, \"input_0.neg()\", name)\n\n    @staticmethod\n    def neg_fp8x23():\n        x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                    ).astype(np.int64), FixedImpl.FP8x23)\n        y = np.negative(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n        y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n        name = \"neg_fp8x23\"\n        make_test([x], y, \"input_0.neg()\", name)\n\n    @staticmethod\n    def neg_fp16x16():\n        x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                    ).astype(np.int64), FixedImpl.FP16x16)\n        y = np.negative(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n        y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n        name = \"neg_fp16x16\"\n        make_test([x], y, \"input_0.neg()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/nonzero.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Nonzero(RunAll):\n    @staticmethod\n    def nonzero_u32():\n        def nonzero_2D():\n            x = np.random.randint(0, 255, (2, 4)).astype(np.uint32)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_u32_2d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        def nonzero_3D():\n            x = np.random.randint(0, 255, (20, 10, 5)).astype(np.uint32)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_u32_3d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        nonzero_2D()\n        nonzero_3D()\n\n    @staticmethod\n    def nonzero_i32():\n        def nonzero_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int32)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_i32_2d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        def nonzero_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int32)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_i32_3d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n\n        nonzero_2D()\n        nonzero_3D()\n\n    @staticmethod\n    def nonzero_i8():\n        def nonzero_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int8)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_i8_2d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        def nonzero_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int8)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_i8_3d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        nonzero_2D()\n        nonzero_3D()\n\n    @staticmethod\n    def nonzero_fp8x23():\n        def nonzero_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            \n            name = \"nonzero_fp8x23_2d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        def nonzero_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            \n            name = \"nonzero_fp8x23_3d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        nonzero_2D()\n        nonzero_3D()\n\n    @staticmethod\n    def nonzero_fp16x16():\n        def nonzero_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_fp16x16_2d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        def nonzero_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.array(np.nonzero(x), dtype=np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"nonzero_fp16x16_3d\"\n            make_test(\n                [x], y, \"input_0.nonzero()\", name)\n\n        nonzero_2D()\n        nonzero_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/not.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_node, make_test, Tensor, Dtype\n\nclass Not(RunAll):\n    @staticmethod\n    def not_bool():\n        x = np.random.uniform(True, False, (1, 1)).astype(bool)\n        y = ~(x)\n\n        x = Tensor(Dtype.Bool, x.shape, x.flatten())\n        y = Tensor(Dtype.Bool, y.shape, y.flatten())\n\n\n        name = \"not_bool\"\n        make_node([x], [y], name)\n        make_test([x], y, \"input_0\", name)"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/or.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Or(RunAll):\n    @staticmethod\n    def or_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_u32\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_u32_broadcast\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def or_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_i32\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int32)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_i32_broadcast\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def or_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_i8\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int8)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_i8_broadcast\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def or_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_fp8x23\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def or_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_fp16x16\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.logical_or(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"or_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.or(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/pow.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Pow(RunAll):\n    @staticmethod\n    def pow_fp8x23():\n        def default():\n            x = np.array([1, 2, 3]).astype(np.float64)\n            y = np.array([1, 2, 3]).astype(np.float64)\n            z = np.array(pow(x, y), dtype=np.float64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"pow_fp8x23\"\n            make_test([x, y], z, \"input_0.pow(@input_1)\", name)\n\n        def broadcast():\n            x = np.array([1, 2, 3]).astype(np.float64)\n            y = np.array([2]).astype(np.float64)\n            z = np.array(pow(x, y), dtype=np.float64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"pow_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.pow(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def and_fp16x16():\n        def default():\n            x = np.array([1, 2, 3]).astype(np.float64)\n            y = np.array([1, 2, 3]).astype(np.float64)\n            z = np.array(pow(x, y), dtype=np.float64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"pow_fp16x16\"\n            make_test([x, y], z, \"input_0.pow(@input_1)\", name)\n\n        def broadcast():\n            x = np.array([1, 2, 3]).astype(np.float64)\n            y = np.array([2]).astype(np.float64)\n            z = np.array(pow(x, y), dtype=np.float64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"pow_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.pow(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/random_uniform_like.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\ndef random_uniform_like(x: np.ndarray, high: int=1,low: int=0,seed: int=25) ->np.ndarray:\n    dtype = np.float64\n    if seed is None or np.isnan(seed):  # type: ignore\n        state = np.random.RandomState()\n    else:\n        state = np.random.RandomState(seed=int(seed))  # type: ignore\n    res = state.rand(*x.shape).astype(dtype)\n    res *= high - low  # type: ignore\n    res += low  # type: ignore\n    return (res.astype(dtype),)\n\ndef get_data_statement(data: np.ndarray, dtype: Dtype) -> list[str]:\n    match dtype:\n        case Dtype.FP8x23:\n            return [\"Option::Some(FP8x23 { \"+f\"mag: {abs(int(x))}, sign: {str(x < 0).lower()} \"+\"})\" for x in data.flatten()]\n        case Dtype.FP16x16:\n            return [\"Option::Some(FP16x16 { \"+f\"mag: {abs(int(x))}, sign: {str(x < 0).lower()} \"+\"})\" for x in data.flatten()]\n        case Dtype.U32:\n            return [f\"Option::Some({int(x)})\" for x in data.flatten()]\n\nclass Random_uniform_like(RunAll):\n\n    @staticmethod\n    def fp8x23():\n        x = np.random.uniform(1, 10, (1, 2, 2, 4)).astype(np.float64)\n        y = random_uniform_like(x)\n\n        args = [10, 1]\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP8x23), Dtype.FP8x23)\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y[0].shape, to_fp(\n            y[0].flatten(), FixedImpl.FP8x23))\n\n        name = \"random_uniform_like_fp8x23\"\n        make_test(\n            [x], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::random_uniform_like(@input_0, {','.join(args_str)}, Option::Some(354145))\", # The code signature.\n            name # The name of the generated folder.\n        )\n\n    @staticmethod\n    def fp16x16():\n        x = np.random.uniform(1, 10, (1, 2, 2, 4)).astype(np.float16)\n        y = random_uniform_like(x)\n\n        args = [10, 1]\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP16x16), Dtype.FP16x16)\n\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y[0].shape, to_fp(\n            y[0].flatten(), FixedImpl.FP16x16))\n\n        name = \"random_uniform_like_fp16x16\"\n        make_test(\n            [x], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::random_uniform_like(@input_0, {','.join(args_str)}, Option::Some(354145))\", # The code signature.\n            name # The name of the generated folder.\n        )\n\n    # @staticmethod\n    # def fp64x64():\n    #     x = np.random.uniform(-3, 3, (1, 2, 2, 4)).astype(np.float64)\n    #     y = random_uniform_like(x)\n\n    #     x = Tensor(Dtype.FP64x64, x.shape, to_fp(\n    #         x.flatten(), FixedImpl.FP64x64))\n    #     y = Tensor(Dtype.FP64x64, y[0].shape, to_fp(\n    #         y[0].flatten(), FixedImpl.FP64x64))\n\n    #     name = \"random_uniform_like_fp64x64\"\n    #     make_test([x], y, \"TensorTrait::random_uniform_like(@input_0, 5, 1, 10)\",\n    #                 name)\n\n    # @staticmethod\n    # def fpi8():\n    #     x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.int8)\n    #     y = random_uniform_like(x)\n\n    #     x = Tensor(Dtype.I8, x.shape, x.flatten())\n    #     y = Tensor(Dtype.I8, y[0].shape, y[0].flatten())\n\n    #     name = \"random_uniform_like_i8\"\n    #     make_test([x], y, \"TensorTrait::random_uniform_like(@input_0, 5, 1, 10)\",\n    #                 name)\n\n    # @staticmethod\n    # def fpi32():\n    #     x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.int32)\n    #     y = random_uniform_like(x)\n\n    #     x = Tensor(Dtype.I32, x.shape, x.flatten())\n    #     y = Tensor(Dtype.I32, y[0].shape, y[0].flatten())\n\n    #     name = \"random_uniform_like_i32\"\n    #     make_test([x], y, \"TensorTrait::random_uniform_like(@input_0, 5, 1, 10)\",\n    #                 name)\n\n\n    # @staticmethod\n    # def fpu32():\n    #     x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.uint32)\n    #     y = random_uniform_like(x)\n    #     args = [5, 1, 10]\n    #     args_str = get_data_statement(np.array(args).flatten(), Dtype.U32)\n\n\n    #     x = Tensor(Dtype.U32, x.shape, x.flatten())\n    #     y = Tensor(Dtype.U32, y[0].shape, y[0].flatten())\n\n    #     name = \"random_uniform_like_u32\"\n    #     make_test(\n    #         [x], # List of input tensors.\n    #         y, # The expected output result.\n    #         f\"TensorTrait::random_uniform_like(@input_0, {','.join(args_str)})\", # The code signature.\n    #         name # The name of the generated folder.\n    #     )\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/range.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait, get_data_statement\n\n\n\nclass Range(RunAll):\n     \n    @staticmethod\n    # We test here with fp8x23 implementation.\n    def fp8x23():\n        args = [1, 5, 0.3]\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP8x23), Dtype.FP8x23)\n        y = np.arange(*args)\n        print(y)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        # Define the name of the generated folder. \n        name = \"range_fp8x23\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::range({','.join(args_str)})\", # The code signature.\n            name, # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with fp16x16 implementation.\n    def fp16x16():\n        args = [1, 25, 3]\n        args_str = get_data_statement(to_fp(np.array(args).flatten(), FixedImpl.FP16x16), Dtype.FP16x16)\n        y = np.arange(*args)\n        print(y)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        \n        # Define the name of the generated folder. \n        name = \"range_fp16x16\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::range({','.join(args_str)})\", # The code signature.\n            name, # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with i8 implementation.\n    def i8():\n        args = [-1, 25, 3]\n        args_str = get_data_statement(np.array(args).flatten(), Dtype.I8)\n        y = np.arange(*args)\n        print(y)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n        \n        # Define the name of the generated folder. \n        name = \"range_i8\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::range({','.join(args_str)})\", # The code signature.\n            name, # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with i32 implementation.\n    def i32():\n        args = [21, 2, -3]\n        args_str = get_data_statement(np.array(args).flatten(), Dtype.I32)\n        y = np.arange(*args)\n        print(y)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n        \n        # Define the name of the generated folder. \n        name = \"range_i32\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::range({','.join(args_str)})\", # The code signature.\n            name, # The name of the generated folder.\n        )\n     \n    @staticmethod\n    # We test here with u32 implementation.\n    def u32():\n        args = [1, 25, 3]\n        args_str = get_data_statement(np.array(args).flatten(), Dtype.U32)\n        y = np.arange(*args)\n        print(y)\n        # Convert the floats values in `y` to fixed points with `to_fp` method:\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n        \n        # Define the name of the generated folder. \n        name = \"range_u32\"\n        # Invoke `make_test` method to generate corresponding Cairo tests:\n        make_test(\n            [], # List of input tensors.\n            y, # The expected output result.\n            f\"TensorTrait::range({','.join(args_str)})\", # The code signature.\n            name, # The name of the generated folder.\n        )\n        "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_l1.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\nimport numpy as np\n\n\nclass Reduce_l1(RunAll):\n    @staticmethod\n    def reduce_l1_fp8x23():\n        def reduce_l1_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=False).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp8x23_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, false)\", name)\n            \n        def reduce_l1_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp8x23_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, true)\", name)\n            \n        def reduce_l1_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp8x23_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(0, true)\", name)\n\n        \n        reduce_l1_export_do_not_keepdims()\n        reduce_l1_export_keepdims()\n        reduce_l1_axis_0()\n\n    @staticmethod\n    def reduce_l1_fp16x16():\n        def reduce_l1_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=False).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp16x16_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, false)\", name)\n            \n        def reduce_l1_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp16x16_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, true)\", name)\n            \n        def reduce_l1_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l1_fp16x16_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(0, true)\", name)\n\n        \n        reduce_l1_export_do_not_keepdims()\n        reduce_l1_export_keepdims()\n        reduce_l1_axis_0()\n\n    @staticmethod\n    def reduce_l1_i8():\n        def reduce_l1_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int8)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=False).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_l1_i8_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, false)\", name)\n            \n        def reduce_l1_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int8)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_l1_i8_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, true)\", name)\n            \n        def reduce_l1_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int8)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_l1_i8_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(0, true)\", name)\n\n        \n        reduce_l1_export_do_not_keepdims()\n        reduce_l1_export_keepdims()\n        reduce_l1_axis_0()\n\n    @staticmethod\n    def reduce_l1_i32():\n        def reduce_l1_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int32)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=False).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_l1_i32_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, false)\", name)\n            \n        def reduce_l1_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_l1_i32_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, true)\", name)\n            \n        def reduce_l1_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_l1_i32_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(0, true)\", name)\n\n        \n        reduce_l1_export_do_not_keepdims()\n        reduce_l1_export_keepdims()\n        reduce_l1_axis_0()\n\n    @staticmethod\n    def reduce_l1_u32():\n        def reduce_l1_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.uint32)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=False).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_l1_u32_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, false)\", name)\n            \n        def reduce_l1_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.uint32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_l1_u32_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(2, true)\", name)\n            \n        def reduce_l1_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.uint32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.abs(x), axis=tuple(axes), keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_l1_u32_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_l1(0, true)\", name)\n\n        \n        reduce_l1_export_do_not_keepdims()\n        reduce_l1_export_keepdims()\n        reduce_l1_axis_0()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_l2.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_node, make_test, to_fp, Tensor, Dtype, FixedImpl\nimport numpy as np\n\n\n\nclass Reduce_l2(RunAll):\n    @staticmethod\n    def reduce_l2_fp8x23():\n        def reduce_l2_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=False)).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp8x23_export_do_not_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(2, false)\", name)\n            \n        def reduce_l2_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=True)).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp8x23_export_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(2, true)\", name)\n            \n        def reduce_l2_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=True)).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp8x23_export_negative_axes_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(0, true)\", name)\n\n        \n        reduce_l2_export_do_not_keepdims()\n        reduce_l2_export_keepdims()\n        reduce_l2_axis_0()\n\n    @staticmethod\n    def reduce_l2_fp16x16():\n        def reduce_l2_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=False)).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp16x16_export_do_not_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(2, false)\", name)\n            \n        def reduce_l2_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=True)).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp16x16_export_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(2, true)\", name)\n            \n        def reduce_l2_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sqrt(np.sum(a=np.square(x), axis=tuple(axes), keepdims=True)).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_l2_fp16x16_export_negative_axes_keepdims\"\n            make_node([x], [y], name)\n            make_test(\n                [x], y, \"input_0.reduce_l2(0, true)\", name)\n\n        \n        reduce_l2_export_do_not_keepdims()\n        reduce_l2_export_keepdims()\n        reduce_l2_axis_0()\n\n    @staticmethod\n    def reduce_l2_complex64():\n        \n\n\n        def reduce_l2_axis_0():\n            shape = [2, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.array([1.+2.j,  2.-1.j,  3.-3.j,  3.-2.j,  3.+5.j, 4.- 1.j]), shape)\n            y = np.sqrt(np.sum(a=np.square(abs(x)), axis=tuple(axes), keepdims=True))\n            print(to_fp(x.flatten(), FixedImpl.FP64x64))\n\n            x = Tensor(Dtype.COMPLEX64, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP64x64))\n            \n            y = Tensor(Dtype.COMPLEX64, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP64x64))\n\n            name = \"reduce_l2_complex64_axis_0\"\n            make_test(\n                [x], y, \"input_0.reduce_l2(0, true)\", name)\n\n        reduce_l2_axis_0()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_log_sum.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import  make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\n\nclass Reduce_log_sum(RunAll):\n    @staticmethod\n    def reduce_log_sum_fp8x23():\n        def reduce_log_sum_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=False))\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp8x23_export_do_not_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(2, false)\", name)\n            \n        def reduce_log_sum_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=True))\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp8x23_export_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(2, true)\", name)\n            \n        def reduce_log_sum_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1), shape)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=True))\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp8x23_export_negative_axes_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(0, true)\", name)\n\n        \n        reduce_log_sum_export_do_not_keepdims()\n        reduce_log_sum_export_keepdims()\n        reduce_log_sum_axis_0()\n\n    @staticmethod\n    def reduce_log_sum_fp16x16():\n        def reduce_log_sum_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=False))\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp16x16_export_do_not_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(2, false)\", name)\n            \n        def reduce_log_sum_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=True))\n\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp16x16_export_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(2, true)\", name)\n            \n        def reduce_log_sum_axis_0():\n            shape = [2, 2, 2]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.log(np.sum(x, axis=tuple(axes), keepdims=True))\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_log_sum_fp16x16_export_negative_axes_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum(0, true)\", name)\n\n        \n        reduce_log_sum_export_do_not_keepdims()\n        reduce_log_sum_export_keepdims()\n        reduce_log_sum_axis_0()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_log_sum_exp.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, Tensor, Dtype, FixedImpl, to_fp\n\nclass Reduce_log_sum_exp(RunAll):\n    @staticmethod\n    def reduce_log_sum_exp_fp32x32():\n        def reduce_log_sum_exp_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1), shape)\n            y = np.log(np.sum(np.exp(x), axis=tuple(axes), keepdims=False)).astype(np.float64)\n\n            x = Tensor(Dtype.FP32x32, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP32x32))\n            y = Tensor(Dtype.FP32x32, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP32x32))\n\n            name = \"reduce_log_sum_exp_fp32x32_export_do_not_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum_exp(2, false)\", name)\n            \n        def reduce_log_sum_exp_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1), shape)\n            y = np.log(np.sum(np.exp(x), axis=tuple(axes), keepdims=True)).astype(np.float64)\n\n            x = Tensor(Dtype.FP32x32, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP32x32))\n            y = Tensor(Dtype.FP32x32, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP32x32))\n\n            name = \"reduce_log_sum_exp_fp32x32_export_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum_exp(2, true)\", name)\n            \n        def reduce_log_sum_exp_axis_0():\n            shape = [3, 2, 2]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1), shape)\n            y = np.log(np.sum(np.exp(x), axis=tuple(axes), keepdims=True)).astype(np.float64)\n\n            x = Tensor(Dtype.FP32x32, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP32x32))\n            y = Tensor(Dtype.FP32x32, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP32x32))\n\n            name = \"reduce_log_sum_exp_fp32x32_export_negative_axes_keepdims\"\n            make_test(\n                [x], y, \"input_0.reduce_log_sum_exp(0, true)\", name)\n\n        \n        reduce_log_sum_exp_export_do_not_keepdims()\n        reduce_log_sum_exp_export_keepdims()\n        reduce_log_sum_exp_axis_0()\n\n  \n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_mean.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Reduce_mean(RunAll):\n    @staticmethod\n    def reduce_mean_u32():\n        def reduce_mean_1D():\n            x = np.array([0, 1, 2,]).astype(np.uint32)\n            y = np.mean(x, keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_mean_u32_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_mean_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.mean(x, keepdims=True).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_mean_u32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.mean(x, keepdims=False).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_mean_u32_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.mean(x, axis=(1), keepdims=True).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_mean_u32_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_mean_1D()\n        reduce_mean_2D()\n\n    @staticmethod\n    def reduce_mean_i32():\n        def reduce_mean_1D():\n            x = np.array([0, 1, 2,]).astype(np.int32)\n            y = np.mean(x, keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_mean_i32_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_mean_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.mean(x, keepdims=True).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_mean_i32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.mean(x, keepdims=False).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_mean_i32_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.mean(x, axis=(1), keepdims=True).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_mean_i32_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_mean_1D()\n        reduce_mean_2D()\n\n    @staticmethod\n    def reduce_mean_i8():\n        def reduce_mean_1D():\n            x = np.array([0, 1, 2,]).astype(np.int8)\n            y = np.mean(x, keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_mean_i8_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_mean_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.mean(x, keepdims=True).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_mean_i8_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.mean(x, keepdims=False).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_mean_i8_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.mean(x, axis=(1), keepdims=True).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_mean_i8_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_mean_1D()\n        reduce_mean_2D()\n\n    @staticmethod\n    def reduce_mean_fp8x23():\n        def reduce_mean_1D():\n            x = np.array([0, 1, 2,]).astype(np.int64)\n            y = np.mean(x, keepdims=True)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_mean_fp8x23_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_mean_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, keepdims=True)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_mean_fp8x23_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, keepdims=False)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_mean_fp8x23_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, axis=(1), keepdims=True)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_mean_fp8x23_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n            \n        reduce_mean_1D()\n        reduce_mean_2D()\n\n    @staticmethod\n    def reduce_mean_fp16x16():\n        def reduce_mean_1D():\n            x = np.array([0, 1, 2,]).astype(np.int64)\n            y = np.mean(x, keepdims=True)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"reduce_mean_fp16x16_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_mean_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, keepdims=True)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_mean_fp16x16_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, keepdims=False)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_mean_fp16x16_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.mean(x, axis=(1), keepdims=True)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_mean_fp16x16_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_mean(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n\n        reduce_mean_1D()\n        reduce_mean_2D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_min.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Reduce_min(RunAll):\n    @staticmethod\n    def reduce_min_u32():\n        def reduce_min_1D():\n            x = np.array([0, 1, 2,]).astype(np.uint32)\n            y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_min_u32_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_min_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_min_u32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=False).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_min_u32_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.uint32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=(1), keepdims=True).astype(np.uint32)\n\n                x = Tensor(Dtype.U32, x.shape, x.flatten())\n                y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n                name = \"reduce_min_u32_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_min_1D()\n        reduce_min_2D()\n\n    @staticmethod\n    def reduce_min_i32():\n        def reduce_min_1D():\n            x = np.array([0, 1, 2,]).astype(np.int32)\n            y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_min_i32_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_min_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_min_i32_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=False).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_min_i32_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int32).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=(1), keepdims=True).astype(np.int32)\n\n                x = Tensor(Dtype.I32, x.shape, x.flatten())\n                y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n                name = \"reduce_min_i32_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_min_1D()\n        reduce_min_2D()\n\n    @staticmethod\n    def reduce_min_i8():\n        def reduce_min_1D():\n            x = np.array([0, 1, 2,]).astype(np.int8)\n            y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_min_i8_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_min_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=True).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_min_i8_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=False).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_min_i8_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int8).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=(1), keepdims=True).astype(np.int8)\n\n                x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n                y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n                name = \"reduce_min_i8_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n        reduce_min_1D()\n        reduce_min_2D()\n\n    @staticmethod\n    def reduce_min_fp8x23():\n        def reduce_min_1D():\n            x = np.array([0, 1, 2,]).astype(np.int64)\n            y = np.minimum.reduce(x, axis=None, keepdims=True)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"reduce_min_fp8x23_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_min_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=True)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_min_fp8x23_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=False)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_min_fp8x23_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=(1), keepdims=True)\n\n                x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP8x23))\n\n                name = \"reduce_min_fp8x23_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n            \n        reduce_min_1D()\n        reduce_min_2D()\n\n    @staticmethod\n    def reduce_min_fp16x16():\n        def reduce_min_1D():\n            x = np.array([0, 1, 2,]).astype(np.int64)\n            y = np.minimum.reduce(x, axis=None, keepdims=True)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"reduce_min_fp16x16_1D\"\n            make_test(\n                [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n        def reduce_min_2D():\n            def default():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=True)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_min_fp16x16_2D_default\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::None(()), Option::None(()))\", name)\n\n            def keepdims():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=None, keepdims=False)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_min_fp16x16_2D_keepdims\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::None(()), Option::Some(false), Option::None(()))\", name)\n\n            def axis_1():\n                x = np.array([0, 1, 2, 3]).astype(np.int64).reshape(2, 2)\n                y = np.minimum.reduce(x, axis=(1), keepdims=True)\n\n                x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                    x.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                    y.flatten(), FixedImpl.FP16x16))\n\n                name = \"reduce_min_fp16x16_2D_axis_1\"\n                make_test(\n                    [x], y, \"input_0.reduce_min(Option::Some(array![1].span()), Option::None(()), Option::None(()))\", name)\n\n            default()\n            keepdims()\n            axis_1()\n\n        reduce_min_1D()\n        reduce_min_2D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_sum.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Reduce_sum(RunAll):\n\n    @staticmethod\n    def reduce_sum_no_keep_dims():\n        axes = np.array([1], dtype=np.uint32)\n        keepdims = 0\n\n        x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [\n                     [9, 10], [11, 12]]]).astype(np.uint32)\n        y = np.sum(x, axis=tuple(axes.tolist()), keepdims=keepdims == 1)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"reduce_sum_no_keep_dims\"\n        make_test(\n            [x], y, \"input_0.reduce_sum(Option::Some(array![1].span()), Option::Some(false), Option::None)\", name)\n\n    @staticmethod\n    def reduce_sum_keep_dims():\n        axes = np.array([1], dtype=np.uint32)\n        keepdims = 1\n\n        x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [\n            [9, 10], [11, 12]]]).astype(np.uint32)\n        y = np.sum(x, axis=tuple(axes.tolist()), keepdims=keepdims == 1)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"reduce_sum_keep_dims\"\n        make_test(\n            [x], y, \"input_0.reduce_sum(Option::Some(array![1].span()), Option::Some(true), Option::None)\", name)\n\n    @staticmethod\n    def reduce_sum_default_axes_keepdims():\n        keepdims = 1\n\n        x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [\n            [9, 10], [11, 12]]]).astype(np.uint32)\n        y = np.sum(x, axis=None, keepdims=keepdims == 1)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"reduce_sum_default_axes_keepdims\"\n        make_test(\n            [x], y, \"input_0.reduce_sum(Option::Some(array![].span()), Option::Some(true), Option::None)\", name)\n        \n    @staticmethod\n    def reduce_sum_negative_axes_keepdims():\n        axes = np.array([-2], dtype=np.int64)\n        keepdims = 1\n\n        x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [\n            [9, 10], [11, 12]]]).astype(np.uint32)\n        y = np.sum(x, axis=tuple(axes.tolist()), keepdims=keepdims == 1)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"reduce_sum_negative_axes_keepdims\"\n        make_test(\n            [x], y, \"input_0.reduce_sum(Option::Some(array![-2].span()), Option::Some(true), Option::None)\", name)\n\n    @staticmethod\n    def reduce_sum_empty_axes_input_noop():\n        x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [\n            [9, 10], [11, 12]]]).astype(np.uint32)\n        y = np.array(x)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"reduce_sum_empty_axes_input_noop\"\n        make_test(\n            [x], y, \"input_0.reduce_sum(Option::None, Option::Some(true), Option::Some(true))\", name)"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reduce_sum_square.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\nimport numpy as np\n\n\nclass Reduce_sum_square(RunAll):\n    @staticmethod\n    def reduce_sum_square_fp8x23():\n        def reduce_sum_square_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=False).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp8x23_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, false)\", name)\n            \n        def reduce_sum_square_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp8x23_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, true)\", name)\n            \n        def reduce_sum_square_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp8x23_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(0, true)\", name)\n\n        \n        reduce_sum_square_export_do_not_keepdims()\n        reduce_sum_square_export_keepdims()\n        reduce_sum_square_axis_0()\n\n    @staticmethod\n    def reduce_sum_square_fp16x16():\n        def reduce_sum_square_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=False).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp16x16_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, false)\", name)\n            \n        def reduce_sum_square_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp16x16_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, true)\", name)\n            \n        def reduce_sum_square_axis_0():\n            shape = [2, 2, 2]\n            axes = np.array([0], dtype=np.int64)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int64)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int64)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_fp16x16_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(0, true)\", name)\n\n        \n        reduce_sum_square_export_do_not_keepdims()\n        reduce_sum_square_export_keepdims()\n        reduce_sum_square_axis_0()\n\n    @staticmethod\n    def reduce_sum_square_i8():\n        def reduce_sum_square_export_do_not_keepdims():\n            shape = [2, 2, 2]\n            axes = np.array([2], dtype=np.int8)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=False).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i8_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, false)\", name)\n            \n        def reduce_sum_square_export_keepdims():\n            shape = [2, 2, 2]\n            axes = np.array([2], dtype=np.int8)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i8_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, true)\", name)\n            \n        def reduce_sum_square_axis_0():\n            shape = [2, 2, 2]\n            axes = np.array([0], dtype=np.int8)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int8)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int8)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i8_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(0, true)\", name)\n\n        \n        reduce_sum_square_export_do_not_keepdims()\n        reduce_sum_square_export_keepdims()\n        reduce_sum_square_axis_0()\n\n    @staticmethod\n    def reduce_sum_square_i32():\n        def reduce_sum_square_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int32)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=False).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i32_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, false)\", name)\n            \n        def reduce_sum_square_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.int32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i32_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, true)\", name)\n            \n        def reduce_sum_square_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.int32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.int32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_i32_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(0, true)\", name)\n\n        \n        reduce_sum_square_export_do_not_keepdims()\n        reduce_sum_square_export_keepdims()\n        reduce_sum_square_axis_0()\n\n    @staticmethod\n    def reduce_sum_square_u32():\n        def reduce_sum_square_export_do_not_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.uint32)\n            keepdims = False\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=False).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_u32_export_do_not_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, false)\", name)\n            \n        def reduce_sum_square_export_keepdims():\n            shape = [3, 2, 2]\n            axes = np.array([2], dtype=np.uint32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_u32_export_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(2, true)\", name)\n            \n        def reduce_sum_square_axis_0():\n            shape = [3, 3, 3]\n            axes = np.array([0], dtype=np.uint32)\n            keepdims = True\n            x = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape).astype(np.uint32)\n            y = np.sum(a=np.square(x), axis=tuple(axes), keepdims=True).astype(np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"reduce_sum_square_u32_export_negative_axes_keepdims\"\n            \n            make_test(\n                [x], y, \"input_0.reduce_sum_square(0, true)\", name)\n\n        \n        reduce_sum_square_export_do_not_keepdims()\n        reduce_sum_square_export_keepdims()\n        reduce_sum_square_axis_0()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/relu.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, Trait, FixedImpl\nimport tensorflow as tf\n\n\nclass Relu(RunAll):\n\n    @staticmethod\n    def relu_i32():\n        x = np.random.randint(-5, 9, (2, 2)).astype(np.int32)\n        layer = tf.keras.layers.ReLU()\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.I32, x.shape, x.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"relu_i32\"\n        make_test([x], y, \"NNTrait::relu(@input_0)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def relu_i8():\n        x = np.random.randint(-5, 9, (2, 2)).astype(np.int8)\n        layer = tf.keras.layers.ReLU()\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.I8, x.shape, x.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"relu_i8\"\n        make_test([x], y, \"NNTrait::relu(@input_0)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def relu_fp8x23():\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        layer = tf.keras.layers.ReLU()\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"relu_fp8x23\"\n        make_test([x], y, \"NNTrait::relu(@input_0)\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def relu_fp16x16():\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        layer = tf.keras.layers.ReLU()\n        y = layer(x).numpy()\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"relu_fp16x16\"\n        make_test([x], y, \"NNTrait::relu(@input_0)\",\n                  name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reshape.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, Tensor, Dtype\n\noriginal_shape = [2, 3, 4]\ndata = np.random.random_sample(original_shape).astype(np.int32)\n\n\ndef reshape_reference_implementation(\n    data: np.ndarray, shape: np.ndarray, allowzero: int = 0\n) -> np.ndarray:\n    # replace zeros with corresponding dim size\n    # we need to do this because np.reshape doesn't support 0 by default unless 'allowzero' is set\n    new_shape = np.copy(shape)\n    if allowzero == 0:\n        zeros_index = np.where(shape == 0)\n        new_shape[zeros_index] = np.array(data.shape)[zeros_index]\n    reshaped = np.reshape(data, new_shape)\n    return reshaped\n\n\nclass Reshape(RunAll):\n    @staticmethod\n    def reshape_reordered_all_dims():\n        y = reshape_reference_implementation(\n            data, np.array([4, 2, 3], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_reordered_all_dims\"\n        make_test([x], y, \"input_0.reshape(array![4,2,3].span(), false)\", name)\n\n    @staticmethod\n    def reshape_reordered_last_dims():\n        y = reshape_reference_implementation(\n            data, np.array([2, 4, 3], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_reordered_last_dims\"\n        make_test([x], y, \"input_0.reshape(array![2,4,3].span(), false)\", name)\n\n    @staticmethod\n    def reshape_reduced_dims():\n        y = reshape_reference_implementation(\n            data, np.array([2, 12], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_reduced_dims\"\n        make_test([x], y, \"input_0.reshape(array![2,12].span(), false)\", name)\n\n    @staticmethod\n    def reshape_extended_dims():\n        y = reshape_reference_implementation(\n            data, np.array([2, 3, 2, 2], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_extended_dims\"\n        make_test([x], y, \"input_0.reshape(array![2, 3, 2, 2].span(), false)\", name)\n\n    @staticmethod\n    def reshape_one_dim():\n        y = reshape_reference_implementation(\n            data, np.array([24], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_one_dim\"\n        make_test([x], y, \"input_0.reshape(array![24].span(), false)\", name)\n\n    @staticmethod\n    def reshape_negative_dim():\n        y = reshape_reference_implementation(\n            data, np.array([2, -1, 2], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_negative_dim\"\n        make_test([x], y, \"input_0.reshape(array![2, -1, 2].span(), false)\", name)\n\n    @staticmethod\n    def reshape_negative_extended_dims():\n        y = reshape_reference_implementation(\n            data, np.array([-1, 2, 3, 4], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_negative_extended_dims\"\n        make_test([x], y, \"input_0.reshape(array![-1, 2, 3, 4].span(), false)\", name)\n\n    @staticmethod\n    def reshape_zero_dim():\n        y = reshape_reference_implementation(\n            data, np.array([2, 0, 4, 1], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_zero_dim\"\n        make_test([x], y, \"input_0.reshape(array![2, 0, 4, 1].span(), false)\", name)\n\n    @staticmethod\n    def reshape_zero_and_negative_dim():\n        y = reshape_reference_implementation(\n            data, np.array([2, 0, 1, -1], dtype=np.int64))\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_zero_and_negative_dim\"\n        make_test([x], y, \"input_0.reshape(array![2, 0, 1, -1].span(), false)\", name)\n\n    @staticmethod\n    def reshape_zero_and_negative_dim():\n        original_shape = [0, 3, 4]\n        data = np.random.random_sample(original_shape).astype(np.int32)\n\n        y = reshape_reference_implementation(\n            data, np.array([3, 4, 0], dtype=np.int64), allowzero=1)\n\n        x = Tensor(Dtype.I32, data.shape, data.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"reshape_zero_and_negative_dim\"\n        make_test([x], y, \"input_0.reshape(array![3, 4, 0].span(), true)\", name)\n\n    "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/resize.py",
        "content": "# Python test implementation from ONNX library : https://github.com/onnx/onnx/blob/main/onnx/reference/ops/op_resize.py\n\nimport numpy as np\nfrom typing import Any, Callable\n\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\ndef _cartesian(arrays: list[np.ndarray], out: np.ndarray | None = None) -> np.ndarray:\n    #From https://stackoverflow.com/a/1235363\n    arrays = [np.asarray(x) for x in arrays]\n    dtype = arrays[0].dtype\n\n    n = np.prod([x.size for x in arrays])\n    if out is None:\n        out = np.zeros([n, len(arrays)], dtype=dtype)\n\n    m = n // arrays[0].size\n    out[:, 0] = np.repeat(arrays[0], m)\n    if arrays[1:]:\n        _cartesian(arrays[1:], out=out[0:m, 1:])\n        for j in range(1, arrays[0].size):\n            out[j * m : (j + 1) * m, 1:] = out[0:m, 1:]\n    return out\n\n\ndef _get_neighbor_idxes(x: float, n: int, limit: int) -> np.ndarray:\n    idxes = sorted(range(limit), key=lambda idx: (abs(x - idx), idx))[:n]\n    idxes = sorted(idxes)\n    return np.array(idxes)\n\n\ndef _get_neighbor(x: float, n: int, data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n\n    pad_width = np.ceil(n / 2).astype(int)\n    padded = np.pad(data, pad_width, mode=\"edge\")\n    x += pad_width\n\n    idxes = _get_neighbor_idxes(x, n, len(padded))\n\n\n    ret = padded[idxes]\n    return idxes - pad_width, ret\n\ndef linear_coeffs(ratio: float, scale: float | None = None) -> np.ndarray:\n    del scale  \n    return np.array([1 - ratio, ratio])\n\n\ndef linear_coeffs_antialias(ratio: float, scale: float) -> np.ndarray:\n    scale = min(scale, 1.0)\n\n    start = int(np.floor(-1 / scale) + 1)\n    footprint = 2 - 2 * start\n    args = (np.arange(start, start + footprint) - ratio) * scale\n    coeffs = np.clip(1 - np.abs(args), 0, 1)\n\n    return np.array(coeffs) / sum(coeffs) \n\ndef cubic_coeffs_antialias(ratio: float, scale: float, A: float = -0.75) -> np.ndarray:\n    scale = min(scale, 1.0)\n\n    def compute_coeff(x: float) -> float:\n        x = abs(x)\n        x_2 = x * x\n        x_3 = x * x_2\n        if x <= 1:\n            return (A + 2) * x_3 - (A + 3) * x_2 + 1\n        if x < 2:\n            return A * x_3 - 5 * A * x_2 + 8 * A * x - 4 * A\n        return 0.0\n\n    i_start = int(np.floor(-2 / scale) + 1)\n    i_end = 2 - i_start\n    args = [scale * (i - ratio) for i in range(i_start, i_end)]\n    coeffs = [compute_coeff(x) for x in args]\n    return np.array(coeffs) / sum(coeffs)\n\ndef nearest_coeffs(\n    ratio: float | int | np.ndarray, mode: str = \"round_prefer_floor\"\n) -> np.ndarray:\n    if isinstance(ratio, int) or ratio.is_integer():\n        return np.array([0, 1])\n    if mode == \"round_prefer_floor\":\n        return np.array([ratio <= 0.5, ratio > 0.5])\n    if mode == \"round_prefer_ceil\":\n        return np.array([ratio < 0.5, ratio >= 0.5])\n    if mode == \"floor\":\n        return np.array([1, 0])\n    if mode == \"ceil\":\n        return np.array([0, 1])\n    raise ValueError(f\"Unexpected value {mode!r}.\")\n\n\n\ndef _interpolate_1d_with_x(\n    data: np.ndarray,\n    scale_factor: float,\n    output_width_int: int,\n    x: float,\n    get_coeffs: Callable[[float, float], np.ndarray],\n    roi: np.ndarray | None = None,\n    extrapolation_value: float = 0.0,\n    coordinate_transformation_mode: str = \"half_pixel\",\n    exclude_outside: bool = False,\n) -> np.ndarray:\n    \n    input_width = len(data)\n    output_width = scale_factor * input_width\n\n    if coordinate_transformation_mode == \"align_corners\":\n        if output_width == 1:\n            x_ori = 0.0\n        else:\n            x_ori = x * (input_width - 1) / (output_width - 1)\n    elif coordinate_transformation_mode == \"asymmetric\":\n        x_ori = x / scale_factor\n    elif coordinate_transformation_mode == \"tf_crop_and_resize\":\n        if roi is None:\n            raise ValueError(\"roi cannot be None.\")\n        if output_width == 1:\n            x_ori = (roi[1] - roi[0]) * (input_width - 1) / 2\n        else:\n            x_ori = x * (roi[1] - roi[0]) * (input_width - 1) / (output_width - 1)\n        x_ori += roi[0] * (input_width - 1)\n\n        if x_ori < 0 or x_ori > input_width - 1:\n            return np.array(extrapolation_value)\n    elif coordinate_transformation_mode == \"pytorch_half_pixel\":\n        if output_width == 1:\n            x_ori = -0.5\n        else:\n            x_ori = (x + 0.5) / scale_factor - 0.5\n    elif coordinate_transformation_mode == \"half_pixel\":\n        x_ori = (x + 0.5) / scale_factor - 0.5\n    elif coordinate_transformation_mode == \"half_pixel_symmetric\":\n        adjustment = output_width_int / output_width\n        center = input_width / 2\n        offset = center * (1 - adjustment)\n        x_ori = offset + (x + 0.5) / scale_factor - 0.5\n    else:\n        raise ValueError(\n            f\"Invalid coordinate_transformation_mode: {coordinate_transformation_mode!r}.\"\n        )\n\n    x_ori_int = np.floor(x_ori).astype(int).item()\n\n    if x_ori.is_integer():\n        ratio = 1\n    else:\n        ratio = x_ori - x_ori_int\n\n    coeffs = get_coeffs(ratio, scale_factor)\n    n = len(coeffs)\n\n    idxes, points = _get_neighbor(x_ori, n, data)\n\n    if exclude_outside:\n        for i, idx in enumerate(idxes):\n            if idx < 0 or idx >= input_width:\n                coeffs[i] = 0\n        coeffs /= sum(coeffs)\n\n    return np.dot(coeffs, points).item()  \n\n\ndef _interpolate_nd_with_x(\n    data: np.ndarray,\n    n: int,\n    scale_factors: list[float],\n    output_size: list[int],\n    x: list[float],\n    get_coeffs: Callable[[float, float], np.ndarray],\n    roi: np.ndarray | None = None,\n    exclude_outside: bool = False,\n    **kwargs: Any,\n) -> np.ndarray:\n    \n    if n == 1:\n        return _interpolate_1d_with_x(\n            data,\n            scale_factors[0],\n            output_size[0],\n            x[0],\n            get_coeffs,\n            roi=roi,\n            exclude_outside=exclude_outside,\n            **kwargs,\n        )\n    res1d = []\n\n    for i in range(data.shape[0]):\n        r = _interpolate_nd_with_x(\n            data[i],\n            n - 1,\n            scale_factors[1:],\n            output_size[1:],\n            x[1:],\n            get_coeffs,\n            roi=None if roi is None else np.concatenate([roi[1:n], roi[n + 1 :]]),\n            exclude_outside=exclude_outside,\n            **kwargs,\n        )\n        res1d.append(r)\n    \n\n    return _interpolate_1d_with_x(\n        res1d, \n        scale_factors[0],\n        output_size[0],\n        x[0],\n        get_coeffs,\n        roi=None if roi is None else [roi[0], roi[n]], \n        exclude_outside=exclude_outside,\n        **kwargs,\n    )\n\n\ndef _get_all_coords(data: np.ndarray) -> np.ndarray:\n    return _cartesian(\n        [list(range(data.shape[i])) for i in range(len(data.shape))]  \n    )\n\n\ndef interpolate_nd(\n    data: np.ndarray,\n    get_coeffs: Callable[[float, float], np.ndarray],\n    output_size: list[int] | None = None,\n    scale_factors: list[float] | None = None,\n    axes: list[int] | None = None,\n    roi: np.ndarray | None = None,\n    keep_aspect_ratio_policy: str | None = \"stretch\",\n    exclude_outside: bool = False,\n    **kwargs: Any,\n) -> np.ndarray:\n    if output_size is None and scale_factors is None:\n        raise ValueError(\"output_size is None and scale_factors is None.\")\n\n    r = len(data.shape)\n    if axes is not None:\n        if scale_factors is not None:\n            new_scale_factors = [1.0] * r\n            for i, d in enumerate(axes):\n                new_scale_factors[d] = scale_factors[i]\n            scale_factors = new_scale_factors\n\n        if output_size is not None:\n            new_output_size = [data.shape[i] for i in range(r)]\n            for i, d in enumerate(axes):\n                new_output_size[d] = output_size[i]\n            output_size = new_output_size\n\n\n        if roi is not None:\n            new_roi = ([0.0] * r) + ([1.0] * r)\n            naxes = len(axes)\n            for i, d in enumerate(axes):\n                new_roi[d] = roi[i]\n                new_roi[r + d] = roi[naxes + i]\n            roi = new_roi \n    else:\n        axes = list(range(r))\n\n    if output_size is not None:\n        scale_factors = [output_size[i] / data.shape[i] for i in range(r)]\n        if keep_aspect_ratio_policy != \"stretch\":\n            if keep_aspect_ratio_policy == \"not_larger\":\n                scale = np.array(scale_factors)[axes].min()\n            elif keep_aspect_ratio_policy == \"not_smaller\":\n                scale = np.array(scale_factors)[axes].max()\n            else:\n                raise ValueError(\n                    f\"Invalid keep_aspect_ratio_policy={keep_aspect_ratio_policy!r}\"\n                )\n\n            scale_factors = [scale if i in axes else 1.0 for i in range(r)]\n\n            def round_half_up(x: float) -> int:\n                return int(x + 0.5)\n\n            output_size = [\n                round_half_up(scale * data.shape[i]) if i in axes else data.shape[i]\n                for i in range(r)\n            ]\n\n    else:\n        output_size = (scale_factors * np.array(data.shape)).astype(int) \n    if scale_factors is None:\n        raise ValueError(\"scale_factors is None.\")\n    if output_size is None:\n        raise ValueError(\"output_size is None.\")\n\n    ret = np.zeros(output_size)\n    for x in _get_all_coords(ret):\n        ret[tuple(x)] = _interpolate_nd_with_x(\n            data,\n            len(data.shape),\n            scale_factors,\n            output_size,\n            x,\n            get_coeffs,\n            roi=roi,\n            exclude_outside=exclude_outside,\n            **kwargs,\n        )\n    return ret\n\n\ndef cubic_coeffs(\n    ratio: float, scale: float | None = None, A: float = -0.75\n) -> np.ndarray:\n    del scale  # Unused\n    coeffs = [\n        ((A * (ratio + 1) - 5 * A) * (ratio + 1) + 8 * A) * (ratio + 1) - 4 * A,\n        ((A + 2) * ratio - (A + 3)) * ratio * ratio + 1,\n        ((A + 2) * (1 - ratio) - (A + 3)) * (1 - ratio) * (1 - ratio) + 1,\n        ((A * ((1 - ratio) + 1) - 5 * A) * ((1 - ratio) + 1) + 8 * A)\n        * ((1 - ratio) + 1)\n        - 4 * A,\n    ]\n    return np.array(coeffs)\n\n\n    \n\nclass Resize(RunAll):\n\n    @staticmethod\n    def resize_upsample_scales_nearest() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_nearest\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::HALF_PIXEL_SYMMETRIC),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_scales_nearest() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_nearest\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_upsample_sizes_nearest() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n           \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_nearest\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_sizes_nearest() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_sizes_nearest\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_scales_linear() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: linear_coeffs(x, None), scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_linear\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n        \n    @staticmethod\n    def resize_upsample_scales_linear_align_corners() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x, None),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"align_corners\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_linear_align_corners\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ALIGN_CORNERS),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_scales_linear() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: linear_coeffs(x, None), scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_linear\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_scales_linear_align_corners() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x, None),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"align_corners\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_linear_align_corners\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ALIGN_CORNERS),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_scales_cubic() -> None:\n\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: cubic_coeffs(x, None), scale_factors=scales\n        ).astype(np.float32)\n        \n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_cubic\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_scales_cubic_align_corners() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: cubic_coeffs(x),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"align_corners\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_cubic_align_corners\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ALIGN_CORNERS),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_scales_cubic() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n        output = interpolate_nd(\n            data, lambda x, _: cubic_coeffs(x), scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_cubic\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_scales_cubic_align_corners() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: cubic_coeffs(x),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"align_corners\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_cubic_align_corners\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ALIGN_CORNERS),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n        \n    @staticmethod\n    def resize_upsample_sizes_cubic() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 9, 10], dtype=np.int64)\n        output = interpolate_nd(\n            data, lambda x, _: cubic_coeffs(x), output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_cubic\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n        \n    @staticmethod\n    def resize_downsample_sizes_cubic() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: cubic_coeffs(x), output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_sizes_cubic\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n\n\n    @staticmethod\n    def resize_upsample_scales_cubic_A_n0p5_exclude_outside() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n        output = interpolate_nd(\n            data,\n            lambda x, _: cubic_coeffs(x, A=-0.5),\n            scale_factors=scales,\n            exclude_outside=True,\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_cubic_A_n0p5_exclude_outside\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(FixedTrait::<FP16x16>::new(32768, true)),\"\n        func_sig += \"Option::Some(true),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_scales_cubic_A_n0p5_exclude_outside() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n        output = interpolate_nd(\n            data,\n            lambda x, _: cubic_coeffs(x, A=-0.5),\n            scale_factors=scales,\n            exclude_outside=True,\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_cubic_A_n0p5_exclude_outside\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(FixedTrait::<FP16x16>::new(32768, true)),\"\n        func_sig += \"Option::Some(true),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_upsample_scales_cubic_asymmetric() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: cubic_coeffs(x, A=-0.75),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"asymmetric\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_cubic_asymmetric\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ASYMMETRIC),\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_tf_crop_and_resize() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n        roi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\n        sizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            output_size=sizes,\n            roi=roi,\n            coordinate_transformation_mode=\"tf_crop_and_resize\",\n        ).astype(np.float32)\n        x = [data, sizes, roi]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.FP16x16, x[2].shape, to_fp(x[2].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_tf_crop_and_resize\"\n        func_sig = \"data.resize(\"\n        func_sig += \"roi,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::TF_CROP_AND_RESIZE),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n    @staticmethod\n    def resize_tf_crop_and_resize_extrapolation_value() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        roi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\n        sizes = np.array([1, 1, 3, 3], dtype=np.int64)\n        \n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            output_size=sizes,\n            roi=roi,\n            coordinate_transformation_mode=\"tf_crop_and_resize\",\n            extrapolation_value=10.0,\n        ).astype(np.float32)\n\n        x = [data, sizes, roi]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.FP16x16, x[2].shape, to_fp(x[2].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_tf_crop_and_resize_extrapolation_value\"\n        func_sig = \"data.resize(\"\n        func_sig += \"roi,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::TF_CROP_AND_RESIZE),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(FixedTrait::<FP16x16>::new(655360, false)),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_sizes_linear_pytorch_half_pixel() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 3, 1], dtype=np.int64)\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            output_size=sizes,\n            coordinate_transformation_mode=\"pytorch_half_pixel\",\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_downsample_sizes_linear_pytorch_half_pixel\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::PYTORCH_HALF_PIXEL),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_floor_align_corners() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 8, 8], dtype=np.int64)\n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x, mode=\"floor\"),\n            output_size=sizes,\n            coordinate_transformation_mode=\"align_corners\",\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_upsample_sizes_nearest_floor_align_corners\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ALIGN_CORNERS),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::Some(NEAREST_MODE::FLOOR),)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x, mode=\"round_prefer_ceil\"),\n            output_size=sizes,\n            coordinate_transformation_mode=\"asymmetric\",\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::ASYMMETRIC),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::Some(NEAREST_MODE::ROUND_PREFER_CEIL),)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_ceil_half_pixel() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x, mode=\"ceil\"), output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_upsample_sizes_nearest_ceil_half_pixel\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::HALF_PIXEL),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::Some(NEAREST_MODE::CEIL),)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_scales_linear_antialias() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, linear_coeffs_antialias, scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_linear_antialias\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_sizes_linear_antialias() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, linear_coeffs_antialias, output_size=sizes\n        ).astype(np.float32)\n\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_downsample_sizes_linear_pytorch_half_pixel\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n    @staticmethod\n    def resize_downsample_scales_cubic_antialias() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, cubic_coeffs_antialias, scale_factors=scales\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_cubic_antialias\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_downsample_sizes_cubic_antialias() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n        output = interpolate_nd(data, cubic_coeffs_antialias, output_size=sizes).astype(\n            np.float32\n        )\n        x = [data, sizes]\n        y = output\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten())  \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n        name = \"resize_downsample_sizes_cubic_antialias\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"sizes,\"\n        func_sig += \"Option::Some(1),\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::CUBIC),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_scales_nearest_axes_2_3() -> None:\n        axes = np.array([2, 3], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        scales = np.array([2.0, 3.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), scale_factors=scales, axes=axes\n        ).astype(np.float32)\n\n        x = [data, scales, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.FP16x16, x[1].shape, to_fp(x[1].flatten(), FixedImpl.FP16x16)) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_nearest_axes_2_3\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_scales_nearest_axes_3_2() -> None:\n        \n        axes = np.array([3, 2], dtype=np.int64)\n        data = np.array([[[[1, 2],[3, 4],]]],dtype=np.float32,)\n\n        scales = np.array([3.0, 2.0], dtype=np.float32)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), scale_factors=scales, axes=axes\n        ).astype(np.float32)\n        x = [data, scales, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.FP16x16, x[1].shape, to_fp(x[1].flatten(), FixedImpl.FP16x16)) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_nearest_axes_3_2\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_axes_2_3() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([7, 8], dtype=np.int64)\n        axes = np.array([2, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), output_size=sizes, axes=axes\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_nearest_axes_2_3\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_axes_3_2() -> None:\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([8, 7], dtype=np.int64)\n        axes = np.array([3, 2], dtype=np.int64)\n\n        output = interpolate_nd(\n            data, lambda x, _: nearest_coeffs(x), output_size=sizes, axes=axes\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_nearest_axes_3_2\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n        \n    @staticmethod\n    def resize_tf_crop_and_resize_axes_2_3() -> None:\n        axes = np.array([2, 3], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        roi = np.array([0.4, 0.6, 0.6, 0.8], dtype=np.float32)\n        sizes = np.array([3, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            output_size=sizes,\n            roi=roi,\n            axes=axes,\n            coordinate_transformation_mode=\"tf_crop_and_resize\",\n        ).astype(np.float32)\n\n        x = [data, sizes, roi, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.FP16x16, x[2].shape, to_fp(x[2].flatten(), FixedImpl.FP16x16)) \n        x[3] = Tensor(Dtype.U32, x[3].shape, x[3].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_tf_crop_and_resize_axes_2_3\"\n        func_sig = \"data.resize(\"\n        func_sig += \"roi,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::TF_CROP_AND_RESIZE),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2], x[3]], y, func_sig, name)\n\n    @staticmethod\n    def resize_tf_crop_and_resize_axes_3_2() -> None:\n        axes = np.array([3, 2], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                        [9, 10, 11, 12],\n                        [13, 14, 15, 16],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        roi = np.array([0.6, 0.4, 0.8, 0.6], dtype=np.float32)\n        sizes = np.array([3, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            output_size=sizes,\n            roi=roi,\n            axes=axes,\n            coordinate_transformation_mode=\"tf_crop_and_resize\",\n        ).astype(np.float32)\n\n        x = [data, sizes, roi, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.FP16x16, x[2].shape, to_fp(x[2].flatten(), FixedImpl.FP16x16)) \n        x[3] = Tensor(Dtype.U32, x[3].shape, x[3].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_tf_crop_and_resize_axes_3_2\"\n        func_sig = \"data.resize(\"\n        func_sig += \"roi,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::TF_CROP_AND_RESIZE),\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2], x[3]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_not_larger() -> None:\n        keep_aspect_ratio_policy = \"not_larger\"\n        axes = np.array([2, 3], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([7, 8], dtype=np.int64) \n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x),\n            output_size=sizes,\n            axes=axes,\n            keep_aspect_ratio_policy=keep_aspect_ratio_policy,\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_nearest_not_larger\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(KEEP_ASPECT_RATIO_POLICY::NOT_LARGER),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_upsample_sizes_nearest_not_smaller() -> None:\n        keep_aspect_ratio_policy = \"not_smaller\"\n        axes = np.array([2, 3], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2],\n                        [3, 4],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([7, 8], dtype=np.int64)  # Results in 8x8\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x),\n            output_size=sizes,\n            axes=axes,\n            keep_aspect_ratio_policy=keep_aspect_ratio_policy,\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_sizes_nearest_not_smaller\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(KEEP_ASPECT_RATIO_POLICY::NOT_SMALLER),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n\n\n\n    @staticmethod\n    def resize_downsample_sizes_nearest_not_larger() -> None:\n        keep_aspect_ratio_policy = \"not_larger\" \n        axes = np.array([2, 3], dtype=np.int64)\n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 3], dtype=np.int64)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x),\n            output_size=sizes,\n            axes=axes,\n            keep_aspect_ratio_policy=keep_aspect_ratio_policy,\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_sizes_nearest_not_larger\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(KEEP_ASPECT_RATIO_POLICY::NOT_LARGER),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_downsample_sizes_nearest_not_smaller() -> None:\n        keep_aspect_ratio_policy = \"not_smaller\"\n        axes = np.array([2, 3], dtype=np.int64)\n        \n        data = np.array(\n            [\n                [\n                    [\n                        [1, 2, 3, 4],\n                        [5, 6, 7, 8],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n\n        sizes = np.array([1, 3], dtype=np.int64)  \n        output = interpolate_nd(\n            data,\n            lambda x, _: nearest_coeffs(x),\n            output_size=sizes,\n            axes=axes,\n            keep_aspect_ratio_policy=keep_aspect_ratio_policy,\n        ).astype(np.float32)\n\n        x = [data, sizes, axes]\n        y = output\n\n        x[0] = Tensor(Dtype.FP16x16, x[0].shape, to_fp(x[0].flatten(), FixedImpl.FP16x16)) \n        x[1] = Tensor(Dtype.U32, x[1].shape, x[1].flatten()) \n        x[2] = Tensor(Dtype.U32, x[2].shape, x[2].flatten())  \n\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_sizes_nearest_not_smaller\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"sizes,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"axes,\" \n        func_sig += \"Option::None,\" \n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(KEEP_ASPECT_RATIO_POLICY::NOT_SMALLER),\"\n        func_sig += \"Option::Some(MODE::NEAREST),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1], x[2]], y, func_sig, name)\n\n\n\n\n    @staticmethod\n    def resize_downsample_scales_linear_half_pixel_symmetric() -> None:\n        data = np.array([[[[1, 2, 3, 4]]]], dtype=np.float32)\n        scales = np.array([1.0, 1.0, 1.0, 0.6], dtype=np.float32)\n\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"half_pixel_symmetric\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_downsample_scales_linear_half_pixel_symmetric\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::HALF_PIXEL_SYMMETRIC),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n    @staticmethod\n    def resize_upsample_scales_linear_half_pixel_symmetric() -> None:\n        data = np.array([[[[1, 2], [3, 4]]]], dtype=np.float32)\n        scales = np.array([1.0, 1.0, 2.3, 2.94], dtype=np.float32)\n\n        output = interpolate_nd(\n            data,\n            lambda x, _: linear_coeffs(x),\n            scale_factors=scales,\n            coordinate_transformation_mode=\"half_pixel_symmetric\",\n        ).astype(np.float32)\n\n        x = [data, scales]\n        y = output\n        for i in range(len(x)):\n            x[i] = Tensor(Dtype.FP16x16, x[i].shape, to_fp(x[i].flatten(), FixedImpl.FP16x16)) \n        \n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"resize_upsample_scales_linear_half_pixel_symmetric\"\n        func_sig = \"data.resize(\"\n        func_sig += \"Option::None,\"\n        func_sig += \"scales,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\" \n        func_sig += \"Option::Some(TRANSFORMATION_MODE::HALF_PIXEL_SYMMETRIC),\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::None,\"\n        func_sig += \"Option::Some(MODE::LINEAR),\"\n        func_sig += \"Option::None,)\"\n        make_test([x[0], x[1]], y, func_sig, name)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/reverse_sequence.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Reverse_sequence(RunAll):\n    @staticmethod\n    def Reverse_sequence_u32():\n        def reverse_sequence_u32_4x4_batch():\n            x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=np.uint32).reshape((4, 4))\n            y = np.array([0, 1, 2, 3, 5, 4, 6, 7, 10, 9, 8, 11, 15, 14, 13, 12], dtype=np.uint32).reshape((4, 4))\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_u32_4x4_batch\"\n        \n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![1,2,3,4].span()), Option::Some(0), Option::Some(1))\", \n                name\n            )\n\n        def reverse_sequence_u32_4x4_time():    \n            x = np.array([0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15], dtype=np.uint32).reshape((4, 4))\n            y = np.array([3, 6, 9, 12, 2, 5, 8, 13, 1, 4, 10, 14, 0, 7, 11, 15], dtype=np.uint32).reshape((4, 4))\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_u32_4x4_time\"\n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![4,3,2,1].span()), Option::Some(1), Option::Some(0))\", \n                name\n            )\n        def reverse_sequence_u32_3x3_batch():\n            x = np.array([0,1,2,3,4,5,6,7,8], dtype=np.uint32).reshape(3,3)\n            y = np.array([2,1,0,3,4,5,7,6,8], dtype=np.uint32).reshape(3,3)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_u32_3x3_batch\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![3].span(), array![3,1,2].span()), Option::Some(0), Option::Some(1))\",\n                name\n                )\n        def reverse_sequence_u32_3x3_time():\n            x = np.array([0,1,2,3,4,5,6,7,8], dtype=np.uint32).reshape(3,3)\n            y = np.array([0,7,8,3,4,5,6,1,2], dtype=np.uint32).reshape(3,3)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_u32_3x3_time\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![3].span(), array![1,3,3].span()), Option::Some(1), Option::Some(0))\",\n                name\n                )\n            \n        reverse_sequence_u32_4x4_batch()\n        reverse_sequence_u32_4x4_time()\n        reverse_sequence_u32_3x3_batch()\n        reverse_sequence_u32_3x3_time()\n\n    \n    @staticmethod\n    def Reverse_sequence_i32():\n        def reverse_sequence_i32_batch():\n            x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=np.int32).reshape((4, 4))\n            y = np.array([0, 1, 2, 3, 5, 4, 6, 7, 10, 9, 8, 11, 15, 14, 13, 12], dtype=np.int32).reshape((4, 4))\n            _x = Tensor(Dtype.I32, x.shape, x.flatten())\n            _y = Tensor(Dtype.I32, y.shape, y.flatten())\n            name = \"reverse_sequence_i32_batch_equal_parts\"\n        \n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![1,2,3,4].span()), Option::Some(0), Option::Some(1))\", \n                name\n            )\n\n        def reverse_sequence_i32_time():    \n            x = np.array([0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15], dtype=np.int32).reshape((4, 4))\n            y = np.array([3, 6, 9, 12, 2, 5, 8, 13, 1, 4, 10, 14, 0, 7, 11, 15], dtype=np.int32).reshape((4, 4))\n            _x = Tensor(Dtype.I32, x.shape, x.flatten())\n            _y = Tensor(Dtype.I32, y.shape, y.flatten())\n            name = \"reverse_sequence_i32_time_equal_parts\"\n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![4,3,2,1].span()), Option::Some(1), Option::Some(0))\", \n                name\n            )\n        \n        reverse_sequence_i32_batch()\n        reverse_sequence_i32_time()\n    \n    @staticmethod\n    def Reverse_sequence_i8():\n        def reverse_sequence_batch():\n            x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=np.int8).reshape((4, 4))\n            y = np.array([0, 1, 2, 3, 5, 4, 6, 7, 10, 9, 8, 11, 15, 14, 13, 12], dtype=np.int8).reshape((4, 4))\n            _x = Tensor(Dtype.I8, x.shape, x.flatten())\n            _y = Tensor(Dtype.I8, y.shape, y.flatten())\n            name = \"reverse_sequence_i8_batch_equal_parts\"\n        \n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![1,2,3,4].span()), Option::Some(0), Option::Some(1))\", \n                name\n            )\n\n        def reverse_sequence_time():    \n            x = np.array([0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15], dtype=np.uint32).reshape((4, 4))\n            y = np.array([3, 6, 9, 12, 2, 5, 8, 13, 1, 4, 10, 14, 0, 7, 11, 15], dtype=np.uint32).reshape((4, 4))\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_i8_time_equal_parts\"\n            make_test(\n                [_x], \n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![4,3,2,1].span()), Option::Some(1), Option::Some(0))\", \n                name\n            )\n        reverse_sequence_batch()\n        reverse_sequence_time()\n\n    def Reverse_sequence_fp16x16():\n        def reverse_sequence_batch():\n            x = to_fp(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=np.int64).reshape(4, 4), FixedImpl.FP16x16)\n            y = to_fp(np.array([0, 1, 2, 3, 5, 4, 6, 7, 10, 9, 8, 11, 15, 14, 13, 12], dtype=np.int64).reshape(4, 4), FixedImpl.FP16x16)\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n            name = \"reverse_sequence_fp16x16_batch_equal_parts\"\n            make_test(\n                [_x],\n                _y, \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![1,2,3,4].span()), Option::Some(0), Option::Some(1))\", \n                name\n            )\n        def reverse_sequence_time():\n            x = to_fp(np.array([0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15], dtype=np.int64).reshape(4, 4), FixedImpl.FP16x16)\n            y = to_fp(np.array([3, 6, 9, 12, 2, 5, 8, 13, 1, 4, 10, 14, 0, 7, 11, 15], dtype=np.int64).reshape(4, 4), FixedImpl.FP16x16)\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n            name = \"reverse_sequence_fp16x16_time_equal_parts\"\n            make_test(\n                [_x],\n                _y, \n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![4,3,2,1].span()), Option::Some(1), Option::Some(0))\", \n                name\n            )\n        reverse_sequence_batch()\n        reverse_sequence_time()\n\n    def reverse_sequence_different_dimensions():\n        def reverse_sequence_different_dimensions_4_5():\n            x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.uint32).reshape(4,5)\n            y = np.array([5,4,3,2,1,9,8,7,6,10,13,12,11,14,15,17,16,18,19,20], dtype=np.uint32).reshape(4,5)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_different_dimensions_4_5\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![5,4,3,2].span()), Option::Some(0), Option::Some(1))\",\n                name\n                )\n        \n        def reverse_sequence_different_dimensions_2_4():\n            x = np.array([1,2,3,4,5,6,7,8], dtype=np.uint32).reshape(2,4)\n            y = np.array([5,6,7,8,1,2,3,4], dtype=np.uint32).reshape(2,4)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_different_dimensions_2_4\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![4].span(), array![2,2,2,2].span()), Option::Some(1), Option::Some(0))\",\n                name\n                )\n        def reverse_sequence_different_dimensions_1_6():\n            x = np.array([0,1,2,3,4,5], dtype=np.uint32).reshape(1,6)\n            y = np.array([4,3,2,1,0,5], dtype=np.uint32).reshape(1,6)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_different_dimensions_1_6\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![1].span(), array![5].span()), Option::Some(0), Option::Some(1))\",\n                name\n                )\n            \n        def reverse_sequence_different_dimensions_3x9_batch():\n            x = np.array([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,25,26], dtype=np.uint32).reshape(3,9)\n            y = np.array([6,5,4,3,2,1,0,7,8,16,15,14,13,12,11,10,9,17,26,25,24,23,22,21,20,19,18], dtype=np.uint32).reshape(3,9)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_different_dimensions_3x9_batch\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![3].span(), array![7,8,9].span()), Option::Some(0), Option::Some(1))\",\n                name\n                )\n        def reverse_sequence_different_dimensions_3x9_time():\n            x = np.array([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,25,26], dtype=np.uint32).reshape(3,9)\n            y = np.array([18,10,20,12,22,14,24,16,8,9,1,11,3,13,5,15,7,17,0,19,2,21,4,23,6,25,26], dtype=np.uint32).reshape(3,9)\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = Tensor(Dtype.U32, y.shape, y.flatten())\n            name = \"reverse_sequence_different_dimensions_3x9_time\"\n            make_test(\n                [_x],\n                _y,\n                \"input_0.reverse_sequence(TensorTrait::<usize>::new(array![9].span(), array![3,2,3,2,3,2,3,2,1].span()), Option::Some(1), Option::Some(0))\",\n                name\n                )\n            \n        reverse_sequence_different_dimensions_4_5()\n        reverse_sequence_different_dimensions_2_4()\n        reverse_sequence_different_dimensions_1_6()\n        reverse_sequence_different_dimensions_3x9_batch()\n        reverse_sequence_different_dimensions_3x9_time()\n            "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/round.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nclass Round(RunAll):\n   \n    @staticmethod\n    def round_fp8x23():\n        x = np.array([0.1, 0.5, 0.9, 1.2, 1.5, 1.8, 2.3, 2.5, 2.7, -1.1, -1.5, -1.9, -2.2, -2.5, -2.8]).astype(np.float64)\n        y = np.array([0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, -1.0, -2.0, -2.0, -2.0, -3.0, -3.0]).astype(np.float64)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n        \n        name = \"round_fp8x23\"\n        make_test([x], y, \"input_0.round()\", name)\n     \n    @staticmethod\n    def round_fp16x16():\n        x = np.array([0.1, 0.5, 0.9, 1.2, 1.5, 1.8, 2.3, 2.5, 2.7, -1.1, -1.5, -1.9, -2.2, -2.5, -2.8]).astype(np.float64)\n        y = np.array([0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, -1.0, -2.0, -2.0, -2.0, -3.0, -3.0]).astype(np.float64)        \n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(y.flatten(), FixedImpl.FP16x16))\n\n        name = \"round_fp16x16\"\n        make_test([x], y, \"input_0.round()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/running.py",
        "content": "import os\nimport glob\n\n# Directory path where Python files/modules are located\ndirectory_path = 'nodegen/node/'\n\n# Get all files in the directory\nall_files = os.listdir(directory_path)\n\n# Filter Python files using glob and '*.py' pattern\npython_files = [file[:-3] for file in all_files if file.endswith('.py')]\n\n\nfixed = [\n    'abs',\n    'argmax',\n    'argmin',\n    'concat',\n    'cumsum',\n    'div',\n    'equal',\n    'less_equal',\n    'greater',\n    'linear',\n    'matmul',\n    'mul',\n    'or',\n    'reduce_sum',\n    'sub',\n    'transpose',\n    'xor',\n    'less',\n    'greater_equal',\n    'slice',\n    'gather',\n    'nonzero',\n    'squeeze',\n    'unsqueeze',\n    'sign',\n    'clip',\n    '__init__',\n    'running'\n]\nfor node in python_files:\n    if node not in fixed:\n        current_dir = os.getcwd()\n        command = f'python nodegen/node/__init__.py {node}'\n        os.system(command)"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/scatter.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n# The below ScatterElements' numpy implementation is from https://stackoverflow.com/a/46204790/11767360\ndef scatter_elements(data, indices, updates, axis=0, reduction=\"none\"):  # type: ignore\n    if axis < 0:\n        axis = data.ndim + axis\n\n    idx_xsection_shape = indices.shape[:axis] + indices.shape[axis + 1 :]\n\n    def make_slice(arr, axis, i):  # type: ignore\n        slc = [slice(None)] * arr.ndim\n        slc[axis] = i\n        return slc\n\n    def unpack(packed):  # type: ignore\n        unpacked = packed[0]\n        for i in range(1, len(packed)):\n            unpacked = unpacked, packed[i]\n        return unpacked\n\n    def make_indices_for_duplicate(idx):  # type: ignore\n        final_idx = []\n        for i in range(len(idx[0])):\n            final_idx.append(tuple(idx_element[i] for idx_element in idx))\n        return list(final_idx)\n\n    # We use indices and axis parameters to create idx\n    # idx is in a form that can be used as a NumPy advanced indices for scattering of updates param. in data\n    idx = [\n        [\n            unpack(np.indices(idx_xsection_shape).reshape(indices.ndim - 1, -1)),\n            indices[tuple(make_slice(indices, axis, i))].reshape(1, -1)[0],\n        ]\n        for i in range(indices.shape[axis])\n    ]\n    idx = list(np.concatenate(idx, axis=1))\n    idx.insert(axis, idx.pop())\n\n    # updates_idx is a NumPy advanced indices for indexing of elements in the updates\n    updates_idx = list(idx)\n    updates_idx.pop(axis)\n    updates_idx.insert(\n        axis, np.repeat(np.arange(indices.shape[axis]), np.prod(idx_xsection_shape))\n    )\n\n    scattered = np.copy(data)\n    if reduction == \"none\":\n        scattered[tuple(idx)] = updates[tuple(updates_idx)]\n    else:\n        idx, updates_idx = make_indices_for_duplicate(idx), make_indices_for_duplicate(\n            updates_idx\n        )\n        for iter, idx_set in enumerate(idx):\n            if reduction == \"add\":\n                scattered[idx_set] += updates[updates_idx[iter]]\n            elif reduction == \"mul\":\n                scattered[idx_set] *= updates[updates_idx[iter]]\n            elif reduction == \"max\":\n                scattered[idx_set] = np.maximum(\n                    scattered[idx_set], updates[updates_idx[iter]]\n                )\n            elif reduction == \"min\":\n                scattered[idx_set] = np.minimum(\n                    scattered[idx_set], updates[updates_idx[iter]]\n                )\n    return scattered\n\nclass Scatter(RunAll):\n\n    @staticmethod\n    def scatter_fp16x16():\n            \n        def scatter():\n            def default():\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'none')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(x2.flatten(), FixedImpl.FP16x16))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis_1():\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'none')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(x2.flatten(), FixedImpl.FP16x16))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_fp16x16_3d_axis1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis_1_add():\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'add')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.FP16x16, x2.shape, to_fp(x2.flatten(), FixedImpl.FP16x16))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_fp16x16_3d_axis1_add\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('add'))\", \n                    name= name)\n                \n            default()\n            axis_1()\n            axis_1_add()\n        scatter()\n\n    @staticmethod\n    def scatter_fp8x23():\n            \n        def scatter():\n            def default():\n\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'none')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(x2.flatten(), FixedImpl.FP8x23))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"scatter_fp8x23_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('none'))\", \n                    name= name)\n                \n\n            def axis1():\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'none')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(x2.flatten(), FixedImpl.FP8x23))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"scatter_fp8x23_axis1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis1_mul():\n                x1 = np.zeros((3, 3)).astype(np.int64)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int64)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'mul')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.FP8x23, x2.shape, to_fp(x2.flatten(), FixedImpl.FP8x23))\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(y.flatten(), FixedImpl.FP8x23))\n\n                name = \"scatter_fp8x23_mul\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('mul'))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis1_mul()\n        scatter()\n\n    @staticmethod\n    def scatter_i8():\n            \n        def scatter_3D():\n            def default():\n                x1 = np.zeros((3, 3)).astype(np.int8)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int8)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'none')\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I8, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"scatter_i8_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.zeros((3, 3)).astype(np.int8)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int8)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'none')\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I8, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"scatter_i8_axis1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('none'))\", \n                    name= name)\n                \n                \n            def axis1_max():\n                x1 = np.zeros((3, 3)).astype(np.int8)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int8)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'max')\n\n                x1 =  Tensor(Dtype.I8, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I8, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I8, y.shape, y.flatten()) \n\n                name = \"scatter_i8_axis1_max\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('max'))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis1_max()\n        scatter_3D()\n\n\n    @staticmethod\n    def scatter_i32():\n        def scatter_3D():\n            def default():\n                x1 = np.zeros((3, 3)).astype(np.int32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'none')\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"scatter_i8_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis1():\n                x1 = np.zeros((3, 3)).astype(np.int32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'none')\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"scatter_i8_axis1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis_min():\n                x1 = np.zeros((3, 3)).astype(np.int32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.int32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'min')\n\n                x1 =  Tensor(Dtype.I32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.I32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.I32, y.shape, y.flatten()) \n\n                name = \"scatter_i8_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('min'))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis_min()\n        scatter_3D()\n\n\n    @staticmethod\n    def scatter_u32():\n            \n        def scatter_3D():\n            def default():\n                x1 = np.zeros((3, 3)).astype(np.uint32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.uint32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'none')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_u32_default\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('none'))\", \n                    name= name)\n                \n                \n            def axis1():\n                x1 = np.zeros((3, 3)).astype(np.uint32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.uint32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 1, 'none')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_u32_axis1\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(1), reduction:Option::Some('none'))\", \n                    name= name)\n                \n            def axis_add():\n                x1 = np.zeros((3, 3)).astype(np.uint32)\n                x2 = np.arange(1, 10).reshape((3, 3)).astype(np.uint32)\n                x3 = np.array(\n                        [[0,1,2],\n                        [2,0,1],\n                        [1,0,1]],\n                        )\n                y = scatter_elements(x1, x3, x2, 0, 'add')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 = Tensor(Dtype.U32, x3.shape, x3.flatten()) \n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_u32_add\"\n                make_test(\n                    inputs = [x1, x2, x3], output = y, func_sig = \"input_0.scatter(updates:input_1, indices:input_2, axis:Option::Some(0), reduction:Option::Some('add'))\", \n                    name= name)\n                \n            default()\n            axis1()\n            axis_add()\n        scatter_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/scatter_nd.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\ndef scatter_nd_impl(data, indices, updates, reduction=\"none\"):  # type: ignore\n    # Check tensor shapes\n    assert indices.shape[-1] <= len(data.shape)\n    assert updates.shape == indices.shape[:-1] + data.shape[indices.shape[-1] :]\n\n    # Compute output\n    output = np.copy(data)\n    for i in np.ndindex(indices.shape[:-1]):\n        # NOTE: The order of iteration in this loop is not specified.\n        if reduction == \"add\":\n            output[tuple(indices[i])] += updates[i]\n        elif reduction == \"mul\":\n            output[tuple(indices[i])] *= updates[i]\n        elif reduction == \"max\":\n            output[tuple(indices[i])] = np.maximum(output[indices[i]], updates[i])\n        elif reduction == \"min\":\n            output[tuple(indices[i])] = np.minimum(output[indices[i]], updates[i])\n        else:\n            output[tuple(indices[i])] = updates[i]\n    return output\n\ndata = np.array(\n            [\n                [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n                [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n                [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n                [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n            ],\n            dtype=np.float32,\n        )\nindices = np.array([[0], [2]], dtype=np.int64)\nupdates = np.array(\n            [\n                [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n                [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n            ],\n            dtype=np.float32,\n        )\n\nclass Scatter_nd(RunAll):\n\n    @staticmethod\n    def scatter_nd_fp16x16():\n        def scatter_nd_3D():\n            def default():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='none')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(x3.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_nd_fp16x16_3d_default\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::None(()))\", \n                    name= name)\n                \n            def add():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='add')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(x3.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_nd_fp16x16_3d_add\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('add'))\", \n                    name= name)\n                \n            def mul():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='mul')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(x3.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_nd_fp16x16_3d_mul\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('mul'))\", \n                    name= name)\n                \n            def max():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='max')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(x3.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_nd_fp16x16_3d_max\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('max'))\", \n                    name= name)\n                \n            def min():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='min')\n\n                x1 = Tensor(Dtype.FP16x16, x1.shape, to_fp(x1.flatten(), FixedImpl.FP16x16))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP16x16, x3.shape, to_fp(x3.flatten(), FixedImpl.FP16x16))\n                y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16)) \n\n                name = \"scatter_nd_fp16x16_3d_min\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('min'))\", \n                    name= name)\n                \n            default()\n            add()\n            mul()\n            max()\n            min()\n        scatter_nd_3D()\n\n\n    @staticmethod\n    def scatter_nd_fp8x23():\n        def scatter_nd_3D():\n            def default():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='none')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(x3.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"scatter_nd_fp8x23_3d_default\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::None(()))\", \n                    name= name)\n                \n            def add():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='add')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(x3.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"scatter_nd_fp8x23_3d_add\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('add'))\", \n                    name= name)\n                \n            def mul():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='mul')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(x3.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"scatter_nd_fp8x23_3d_mul\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('mul'))\", \n                    name= name)\n                \n            def max():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='max')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(x3.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"scatter_nd_fp8x23_3d_max\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('max'))\", \n                    name= name)\n                \n            def min():\n                x1 = data.astype(np.int64)\n                x2 = indices.astype(np.int64)\n                x3 = updates.astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='min')\n\n                x1 = Tensor(Dtype.FP8x23, x1.shape, to_fp(x1.flatten(), FixedImpl.FP8x23))\n                x2 = Tensor(Dtype.U32, x2.shape, x2.flatten()) \n                x3 = Tensor(Dtype.FP8x23, x3.shape, to_fp(x3.flatten(), FixedImpl.FP8x23))\n                y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23)) \n\n                name = \"scatter_nd_fp8x23_3d_min\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('min'))\", \n                    name= name)\n                \n            default()\n            add()\n            mul()\n            max()\n            min()\n        scatter_nd_3D()\n\n    @staticmethod\n    def scatter_nd_u32():\n        def scatter_nd_3D():\n            def default():\n                x1 =  np.arange(0,12).reshape((4,3)).astype(np.int32)\n                x2 = np.array([[0],[1]]).astype(np.uint32)\n                x3 = np.random.randint(low = 0,high=100, size=(2,3)).astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='none')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 =  Tensor(Dtype.U32, x3.shape, x3.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_nd_u32_default\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::None(()))\", \n                    name= name)\n                \n            def add():\n                x1 =  np.arange(0,12).reshape((4,3)).astype(np.int32)\n                x2 = np.array([[1],[0]]).astype(np.uint32)\n                x3 = np.random.randint(low = 0,high=100, size=(2,3)).astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='add')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 =  Tensor(Dtype.U32, x3.shape, x3.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_nd_u32_add\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('add'))\", \n                    name= name)\n                \n            def mul():\n                x1 =  np.arange(0,12).reshape((4,3)).astype(np.int32)\n                x2 =np.array([[0],[1]]).astype(np.uint32)\n                x3 = np.random.randint(low = 0,high=100, size=(2,3)).astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='mul')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 =  Tensor(Dtype.U32, x3.shape, x3.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_nd_u32_mul\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('mul'))\", \n                    name= name)\n                \n            def max():\n                x1 =  np.arange(0,12).reshape((4,3)).astype(np.int32)\n                x2 =np.array([[0],[1]]).astype(np.uint32)\n                x3 = np.random.randint(low = 0,high=100, size=(2,3)).astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='max')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 =  Tensor(Dtype.U32, x3.shape, x3.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_nd_u32_max\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('max'))\", \n                    name= name)\n                \n            def min():\n                x1 =  np.arange(0,12).reshape((4,3)).astype(np.int32)\n                x2 = np.array([[0],[1]]).astype(np.uint32)\n                x3 = np.random.randint(low = 0,high=100, size=(2,3)).astype(np.uint32)\n                y = scatter_nd_impl(x1, x2, x3, reduction='min')\n\n                x1 =  Tensor(Dtype.U32, x1.shape, x1.flatten())\n                x2 =  Tensor(Dtype.U32, x2.shape, x2.flatten())\n                x3 =  Tensor(Dtype.U32, x3.shape, x3.flatten())\n                y =  Tensor(Dtype.U32, y.shape, y.flatten()) \n\n                name = \"scatter_nd_u32_min\"\n                make_test(\n                    inputs = [x1, x3, x2], output = y, func_sig = \"input_0.scatter_nd(updates:input_1, indices:input_2, reduction:Option::Some('min'))\", \n                    name= name)\n                \n            default()\n            add()\n            mul()\n            max()\n            min()\n        scatter_nd_3D()\n\n\n   "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_at.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nscalar = lambda x: Tensor(Dtype.I32, (), np.array([x]).astype(np.int32).flatten())\n\n\nclass Sequence_at(RunAll):\n\n    @staticmethod\n    def sequence_at_u32():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            name = \"sequence_at_u32_positive\"\n            make_test([sequence, position], sequence[2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            name = \"sequence_at_u32_negative\"\n            make_test([sequence, position], sequence[-2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n\n\n    @staticmethod\n    def sequence_at_i32():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            name = \"sequence_at_i32_positive\"\n            make_test([sequence, position], sequence[2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            name = \"sequence_at_i32_negative\"\n            make_test([sequence, position], sequence[-2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n\n\n    @staticmethod\n    def sequence_at_i8():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            name = \"sequence_at_i8_positive\"\n            make_test([sequence, position], sequence[2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            name = \"sequence_at_i8_negative\"\n            make_test([sequence, position], sequence[-2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n\n\n    @staticmethod\n    def sequence_at_fp8x23():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            name = \"sequence_at_fp8x23_positive\"\n            make_test([sequence, position], sequence[2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            name = \"sequence_at_fp8x23_negative\"\n            make_test([sequence, position], sequence[-2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n    \n\n    @staticmethod\n    def sequence_at_fp16x16():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            name = \"sequence_at_fp16x16_positive\"\n            make_test([sequence, position], sequence[2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            name = \"sequence_at_fp16x16_negative\"\n            make_test([sequence, position], sequence[-2], \"SequenceTrait::sequence_at(input_0, input_1)\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_construct.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nclass Sequence_construct(RunAll):\n\n    @staticmethod\n    def sequence_construct_u32():\n        sequence = []\n        tensor_cnt = np.random.randint(1, 10)\n        shape = np.random.randint(1, 4, 2)\n\n        for _ in range(tensor_cnt):\n            values = np.random.randint(0, 6, shape).astype(np.uint32)\n            tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n            sequence.append(tensor)\n\n        name = \"sequence_construct_u32\"\n        make_test([sequence], sequence, \"SequenceTrait::sequence_construct(input_0)\", name, Trait.SEQUENCE)\n\n\n    @staticmethod\n    def sequence_construct_i32():\n        sequence = []\n        tensor_cnt = np.random.randint(1, 10)\n        shape = np.random.randint(1, 4, 2)\n\n        for _ in range(tensor_cnt):\n            values = np.random.randint(-6, 6, shape).astype(np.int32)\n            tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n            sequence.append(tensor)\n\n        name = \"sequence_construct_i32\"\n        make_test([sequence], sequence, \"SequenceTrait::sequence_construct(input_0)\", name, Trait.SEQUENCE)\n\n\n    @staticmethod\n    def sequence_construct_i8():\n        sequence = []\n        tensor_cnt = np.random.randint(1, 10)\n        shape = np.random.randint(1, 4, 2)\n\n        for _ in range(tensor_cnt):\n            values = np.random.randint(-6, 6, shape).astype(np.int8)\n            tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n            sequence.append(tensor)\n\n        name = \"sequence_construct_i8\"\n        make_test([sequence], sequence, \"SequenceTrait::sequence_construct(input_0)\", name, Trait.SEQUENCE)\n\n\n    @staticmethod\n    def sequence_construct_fp8x23():\n        sequence = []\n        tensor_cnt = np.random.randint(1, 10)\n        shape = np.random.randint(1, 4, 2)\n\n        for _ in range(tensor_cnt):\n            values = np.random.randint(-6, 6, shape).astype(np.float64)\n            tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n            sequence.append(tensor)\n\n        name = \"sequence_construct_fp8x23\"\n        make_test([sequence], sequence, \"SequenceTrait::sequence_construct(input_0)\", name, Trait.SEQUENCE)\n\n\n    @staticmethod\n    def sequence_construct_fp16x16():\n        sequence = []\n        tensor_cnt = np.random.randint(1, 10)\n        shape = np.random.randint(1, 4, 2)\n\n        for _ in range(tensor_cnt):\n            values = np.random.randint(-6, 6, shape).astype(np.float64)\n            tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n            sequence.append(tensor)\n\n        name = \"sequence_construct_fp16x16\"\n        make_test([sequence], sequence, \"SequenceTrait::sequence_construct(input_0)\", name, Trait.SEQUENCE)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_empty.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, Dtype, Tensor, Trait\n\n\nclass Sequence_empty(RunAll):\n\n    @staticmethod\n    def sequence_empty_u32():\n        def default():\n            shape=(0,)\n            x = np.zeros(shape, dtype=np.uint32)\n            t = Tensor(Dtype.U32, shape, x.flatten())\n            make_test(\n                inputs=[],\n                output=[t],\n                func_sig=\"SequenceTrait::sequence_empty()\",\n                name=\"sequence_empty_u32\",\n                trait=Trait.SEQUENCE\n            )\n\n        default()\n\n    @staticmethod\n    def sequence_empty_i32():\n        def default():\n            shape=(0,)\n            x = np.zeros(shape, dtype=np.int32)\n            t = Tensor(Dtype.I32, shape, x.flatten())\n            make_test(\n                inputs=[],\n                output=[t],\n                func_sig=\"SequenceTrait::sequence_empty()\",\n                name=\"sequence_empty_i32\",\n                trait=Trait.SEQUENCE\n            )\n\n        default()\n\n    @staticmethod\n    def sequence_empty_i8():\n        def default():\n            shape=(0,)\n            x = np.zeros(shape, dtype=np.int8)\n            t = Tensor(Dtype.I8, shape, x.flatten())\n            make_test(\n                inputs=[],\n                output=[t],\n                func_sig=\"SequenceTrait::sequence_empty()\",\n                name=\"sequence_empty_i8\",\n                trait=Trait.SEQUENCE\n            )\n\n        default()\n\n    @staticmethod\n    def sequence_empty_fp8x23():\n        def default():\n            shape=(0,)\n            x = np.zeros(shape, dtype=np.float64)\n            t = Tensor(Dtype.FP8x23, shape, x.flatten())\n            make_test(\n                inputs=[],\n                output=[t],\n                func_sig=\"SequenceTrait::sequence_empty()\",\n                name=\"sequence_empty_fp8x23\",\n                trait=Trait.SEQUENCE\n            )\n\n        default()\n\n    @staticmethod\n    def sequence_empty_fp16x16():\n        def default():\n            shape=(0,)\n            x = np.zeros(shape, dtype=np.float64)\n            t = Tensor(Dtype.FP16x16, shape, x.flatten())\n            make_test(\n                inputs=[],\n                output=[t],\n                func_sig=\"SequenceTrait::sequence_empty()\",\n                name=\"sequence_empty_fp16x16\",\n                trait=Trait.SEQUENCE\n            )\n\n        default()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_erase.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nscalar = lambda x: Tensor(Dtype.I32, (), np.array([x]).astype(np.int32).flatten())\n\n\nclass Sequence_erase(RunAll):\n\n    @staticmethod\n    def sequence_erase_u32():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(2)\n\n            name = \"sequence_erase_u32_positive\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n            \n            output_sequence = sequence.copy()\n            output_sequence.pop(-2)\n\n            name = \"sequence_erase_u32_negative\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def empty_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n            \n            output_sequence = sequence.copy()\n            output_sequence.pop(-1)\n\n            name = \"sequence_erase_u32_empty\"\n            make_test([sequence], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::None(()))\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n        empty_position()\n\n\n    @staticmethod\n    def sequence_erase_i32():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(2)\n\n            name = \"sequence_erase_i32_positive\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-2)\n\n            name = \"sequence_erase_i32_negative\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def empty_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-1)\n\n            name = \"sequence_erase_i32_empty\"\n            make_test([sequence], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::None(()))\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n        empty_position()\n\n\n    @staticmethod\n    def sequence_erase_i8():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(2)\n\n            name = \"sequence_erase_i8_positive\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-2)\n\n            name = \"sequence_erase_i8_negative\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def empty_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-1)\n\n            name = \"sequence_erase_i8_empty\"\n            make_test([sequence], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::None(()))\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n        empty_position()\n\n\n    @staticmethod\n    def sequence_erase_fp8x23():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(2)\n\n            name = \"sequence_erase_fp8x23_positive\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-2)\n\n            name = \"sequence_erase_fp8x23_negative\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def empty_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-1)\n\n            name = \"sequence_erase_fp8x23_empty\"\n            make_test([sequence], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::None(()))\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n        empty_position()\n\n\n    @staticmethod\n    def sequence_erase_fp16x16():\n        def positive_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            position = scalar(2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(2)\n\n            name = \"sequence_erase_fp16x16_positive\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def negative_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            position = scalar(-2)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-2)\n\n            name = \"sequence_erase_fp16x16_negative\"\n            make_test([sequence, position], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::Some(input_1))\", name, Trait.SEQUENCE)\n\n        def empty_position():\n            sequence = []\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(5):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            output_sequence = sequence.copy()\n            output_sequence.pop(-1)\n\n            name = \"sequence_erase_fp16x16_empty\"\n            make_test([sequence], output_sequence, \"SequenceTrait::sequence_erase(input_0, Option::None(()))\", name, Trait.SEQUENCE)\n\n        positive_position()\n        negative_position()\n        empty_position()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_insert.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nscalar = lambda x: Tensor(Dtype.I32, (), np.array([x]).astype(np.int32).flatten())\n\n\nclass Sequence_insert(RunAll):\n\n    @staticmethod\n    def sequence_insert_u32():\n        def default():\n            sequence = []\n            tensor_cnt = 3\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                val = np.random.randint(0, 6, shape).astype(np.uint32)\n                t = Tensor(Dtype.U32, val.shape, val.flatten())\n\n                sequence.append(t)\n\n            val = np.random.randint(0, 6, shape).astype(np.uint32)\n            tensor = Tensor(Dtype.U32, val.shape, val.flatten())\n\n            position = np.random.randint(-2, 2)\n\n            expected_sequence = sequence.copy()\n            expected_sequence.insert(position, tensor)\n\n            name = \"sequence_insert_u32\"\n            make_test([sequence, tensor, scalar(position)], expected_sequence, \"input_0.sequence_insert(@input_1,Option::Some(input_2))\", name, Trait.SEQUENCE)\n\n        default()\n\n    @staticmethod\n    def sequence_insert_i32():\n        def default():\n            sequence = []\n            tensor_cnt = 3\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                val = np.random.randint(0, 6, shape).astype(np.int32)\n                t = Tensor(Dtype.I32, val.shape, val.flatten())\n\n                sequence.append(t)\n\n            val = np.random.randint(0, 6, shape).astype(np.int32)\n            tensor = Tensor(Dtype.I32, val.shape, val.flatten())\n\n            position = np.random.randint(-2, 2)\n\n            expected_sequence = sequence.copy()\n            expected_sequence.insert(position, tensor)\n\n            name = \"sequence_insert_i32\"\n            make_test([sequence, tensor, scalar(position)], expected_sequence, \"input_0.sequence_insert(@input_1,Option::Some(input_2))\", name, Trait.SEQUENCE)\n\n        default()\n\n    @staticmethod\n    def sequence_insert_i8():\n        def default():\n            sequence = []\n            tensor_cnt = 3\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                val = np.random.randint(0, 6, shape).astype(np.int8)\n                t = Tensor(Dtype.I8, val.shape, val.flatten())\n\n                sequence.append(t)\n\n            val = np.random.randint(0, 6, shape).astype(np.int8)\n            tensor = Tensor(Dtype.I8, val.shape, val.flatten())\n\n            position = np.random.randint(-2, 2)\n\n            expected_sequence = sequence.copy()\n            expected_sequence.insert(position, tensor)\n\n            name = \"sequence_insert_i8\"\n            make_test([sequence, tensor, scalar(position)], expected_sequence, \"input_0.sequence_insert(@input_1,Option::Some(input_2))\", name, Trait.SEQUENCE)\n\n        default()\n\n    @staticmethod\n    def sequence_insert_fp8x23():\n        def default():\n            sequence = []\n            tensor_cnt = 3\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                val = np.random.randint(0, 6, shape).astype(np.float64)\n                t = Tensor(Dtype.FP8x23, val.shape, to_fp(\n                    val.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(t)\n\n            val = np.random.randint(0, 6, shape).astype(np.float64)\n            tensor = Tensor(Dtype.FP8x23, val.shape, to_fp(\n                val.flatten(), FixedImpl.FP8x23))\n\n            position = np.random.randint(-2, 2)\n\n            expected_sequence = sequence.copy()\n            expected_sequence.insert(position, tensor)\n\n            name = \"sequence_insert_fp8x23\"\n            make_test([sequence, tensor, scalar(position)], expected_sequence, \"input_0.sequence_insert(@input_1,Option::Some(input_2))\", name, Trait.SEQUENCE)\n\n        default()\n\n    @staticmethod\n    def sequence_insert_fp16x16():\n        def default():\n            sequence = []\n            tensor_cnt = 3\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                val = np.random.randint(0, 6, shape).astype(np.float64)\n                t = Tensor(Dtype.FP16x16, val.shape, to_fp(\n                    val.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(t)\n\n            val = np.random.randint(0, 6, shape).astype(np.float64)\n            tensor = Tensor(Dtype.FP16x16, val.shape, to_fp(\n                val.flatten(), FixedImpl.FP16x16))\n\n            position = np.random.randint(-2, 2)\n\n            expected_sequence = sequence.copy()\n            expected_sequence.insert(position, tensor)\n\n            name = \"sequence_insert_fp16x16\"\n            make_test([sequence, tensor, scalar(position)], expected_sequence, \"input_0.sequence_insert(@input_1,Option::Some(input_2))\", name, Trait.SEQUENCE)\n\n        default()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sequence_length.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nscalar = lambda x: Tensor(Dtype.U32, (), np.array([x]).astype(np.uint32).flatten())\n\n\nclass Sequence_length(RunAll):\n    @staticmethod\n    def sequence_length_u32():\n        def default():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_u32\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        def broadcast():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n\n            for _ in range(tensor_cnt):\n                shape = np.random.randint(1, 4, 2)\n                values = np.random.randint(0, 6, shape).astype(np.uint32)\n                tensor = Tensor(Dtype.U32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_u32_broadcast\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sequence_length_i32():\n        def default():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_i32\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        def broadcast():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n\n            for _ in range(tensor_cnt):\n                shape = np.random.randint(1, 4, 2)\n                values = np.random.randint(-6, 6, shape).astype(np.int32)\n                tensor = Tensor(Dtype.I32, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_i32_broadcast\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sequence_length_i8():\n        def default():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_i8\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        def broadcast():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n\n            for _ in range(tensor_cnt):\n                shape = np.random.randint(1, 4, 2)\n                values = np.random.randint(-6, 6, shape).astype(np.int8)\n                tensor = Tensor(Dtype.I8, values.shape, values.flatten())\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_i8_broadcast\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sequence_length_fp8x23():\n        def default():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_fp8x23\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        def broadcast():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n\n            for _ in range(tensor_cnt):\n                shape = np.random.randint(1, 4, 2)\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP8x23, values.shape, to_fp(values.flatten(), FixedImpl.FP8x23))\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_fp8x23_broadcast\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sequence_length_fp16x16():\n        def default():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n            shape = np.random.randint(1, 4, 2)\n\n            for _ in range(tensor_cnt):\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_fp16x16\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        def broadcast():\n            sequence = []\n            tensor_cnt = np.random.randint(1, 10)\n\n            for _ in range(tensor_cnt):\n                shape = np.random.randint(1, 4, 2)\n                values = np.random.randint(-6, 6, shape).astype(np.float64)\n                tensor = Tensor(Dtype.FP16x16, values.shape, to_fp(values.flatten(), FixedImpl.FP16x16))\n\n                sequence.append(tensor)\n\n            name = \"sequence_length_fp16x16_broadcast\"\n            make_test([sequence], scalar(len(sequence)), \"input_0.sequence_length()\", name, Trait.SEQUENCE)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/shrink.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\ndef shrink(input_array: np.ndarray, bias: float, lambd: float) -> np.ndarray:\n    output_array = np.where(input_array > lambd, input_array - bias, \n                            np.where(input_array < -lambd, input_array + bias, 0))\n    return output_array\n\n\nclass Shrink(RunAll):\n\n    @staticmethod\n    def shrink_fp8x23():\n        def shrink_hard():\n            x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n            bias = np.float64(0) # Default value\n            lambd = np.float64(1)\n            y = shrink(x, bias, lambd)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"shrink_hard_fp8x23\"\n            make_test([x], y, \"TensorTrait::shrink(input_0, Option::None(()), Option::Some(FixedTrait::new(8388608, false)))\", name)\n\n        def shrink_soft():\n            x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n            bias = np.float64(1)\n            lambd = np.float64(1)\n            y = shrink(x, bias, lambd)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"shrink_soft_fp8x23\"\n            make_test([x], y, \"TensorTrait::shrink(input_0, Option::Some(FixedTrait::new(8388608, false)), Option::Some(FixedTrait::new(8388608, false)))\", name)\n\n        shrink_hard()\n        shrink_soft()\n\n\n    @staticmethod\n    def shrink_fp16x16():\n        def shrink_hard():\n            x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n            bias = np.float64(0) # Default value\n            lambd = np.float64(1)\n            y = shrink(x, bias, lambd)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"shrink_hard_fp16x16\"\n            make_test([x], y, \"TensorTrait::shrink(input_0, Option::None(()), Option::Some(FixedTrait::new(65536, false)))\", name)\n\n        def shrink_soft():\n            x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n            bias = np.float64(1)\n            lambd = np.float64(1)\n            y = shrink(x, bias, lambd)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"shrink_soft_fp16x16\"\n            make_test([x], y, \"TensorTrait::shrink(input_0, Option::Some(FixedTrait::new(65536, false)), Option::Some(FixedTrait::new(65536, false)))\", name)\n\n        shrink_hard()\n        shrink_soft()"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sigmoid.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\nimport tensorflow as tf\n\n\nclass Sigmoid(RunAll):\n\n    @staticmethod\n    def fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float32)\n        y = tf.keras.activations.sigmoid(x).numpy()\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"sigmoid_fp8x23\"\n        make_test([x], y, \"NNTrait::sigmoid(@input_0)\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float32)\n        y = tf.keras.activations.sigmoid(x).numpy()\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"sigmoid_fp16x16\"\n        make_test([x], y, \"NNTrait::sigmoid(@input_0)\",\n                    name, Trait.NN)\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sign.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\nclass Sign(RunAll):\n    @staticmethod\n    def sign_i8():\n        def sign():\n            x = np.array(range(-5, 6)).astype(np.int8)\n            y = np.array([-1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  1]).astype(np.int8)\n            \n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"sign_i8\"\n            make_test(\n                [x], y, \"input_0.sign()\", name)\n        sign()\n\n    @staticmethod\n    def sign_i32():\n        def sign():\n            x = np.array(range(-5, 6)).astype(np.int32)\n            y = np.array([-1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  1]).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"sign_i32\"\n            make_test(\n                [x], y, \"input_0.sign()\", name)\n        sign()\n\n    @staticmethod\n    def sign_fail():\n        def sign():\n\n            x = np.array(range(-5, 6)).astype(np.int32)\n            y = np.array([1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  -1]).astype(np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"sign_fail\"\n            make_test(\n                [x], y, \"input_0.sign()\", name)\n        sign()\n    \n    @staticmethod\n    def sign_fP16x16():\n        def sign():\n\n            x = to_fp (np.array(range(-5, 6)).astype(np.int64), FixedImpl.FP16x16)\n            y = to_fp (np.array([-1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  1]).astype(np.int64), FixedImpl.FP16x16)\n            \n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"sign_fP16x16\"\n            make_test(\n                [x], y, \"input_0.sign()\", name)\n        sign()\n\n    @staticmethod\n    def sign_fP8x23():\n        def sign():\n\n            x = to_fp (np.array(range(-5, 6)).astype(np.int64), FixedImpl.FP8x23)\n            y = to_fp (np.array([-1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  1]).astype(np.int64), FixedImpl.FP8x23)            \n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"sign_fP8x23\"\n            make_test(\n                [x], y, \"input_0.sign()\", name)\n        sign()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sin.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Sin(RunAll):\n    \n    @staticmethod\n    def sin_fp8x23():\n        x = np.random.uniform(-3, 7, (2, 2)).astype(np.float64)\n        y = np.sin(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"sin_fp8x23\"\n        make_test([x], y, \"input_0.sin()\", name)\n\n    @staticmethod\n    def sin_fp16x16():\n        x = np.random.uniform(-3, 7, (2, 2)).astype(np.float64)\n        y = np.sin(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"sin_fp16x16\"\n        make_test([x], y, \"input_0.sin()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sinh.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Sinh(RunAll):\n\n    @staticmethod\n    def sinh_fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.sinh(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"sinh_fp8x23\"\n        make_test([x], y, \"input_0.sinh()\", name)\n\n    @staticmethod\n    def sinh_fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.sinh(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"sinh_fp16x16\"\n        make_test([x], y, \"input_0.sinh()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/slice.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Slice(RunAll):\n    @staticmethod\n    def slice_u32():\n        def slice_2D():\n            x = np.random.randint(0, 255, (2, 4)).astype(np.uint32)\n            y = x[0:2, 2:4]\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"slice_u32_2d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 2].span(), array![2, 4].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 1].span()))\", name)\n\n        def slice_3D():\n            x = np.random.randint(0, 255, (20, 10, 5)).astype(np.uint32)\n            y = x[0:3, 0:10:3]\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"slice_u32_3d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 0].span(), array![3, 10].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 3].span()))\", name)\n\n        slice_2D()\n        slice_3D()\n\n    @staticmethod\n    def slice_i32():\n        def slice_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int32)\n            y = x[0:2, 2:4]\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"slice_i32_2d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 2].span(), array![2, 4].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 1].span()))\", name)\n\n        def slice_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int32)\n            y = x[0:3, 0:10:3]\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"slice_i32_3d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 0].span(), array![3, 10].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 3].span()))\", name)\n\n\n        slice_2D()\n        slice_3D()\n\n    @staticmethod\n    def slice_i8():\n        def slice_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int8)\n            y = x[0:2, 2:4]\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"slice_i8_2d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 2].span(), array![2, 4].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 1].span()))\", name)\n\n        def slice_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int8)\n            y = x[0:3, 0:10:3]\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"slice_i8_3d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 0].span(), array![3, 10].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 3].span()))\", name)\n\n        slice_2D()\n        slice_3D()\n\n    @staticmethod\n    def slice_fp8x23():\n        def slice_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = x[0:2, 2:4]\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"slice_fp8x23_2d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 2].span(), array![2, 4].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 1].span()))\", name)\n\n        def slice_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = x[0:3, 0:10:3]\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"slice_fp8x23_3d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 0].span(), array![3, 10].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 3].span()))\", name)\n\n        slice_2D()\n        slice_3D()\n\n    @staticmethod\n    def slice_fp16x16():\n        def slice_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = x[0:2, 2:4]\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"slice_fp16x16_2d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 2].span(), array![2, 4].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 1].span()))\", name)\n\n        def slice_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = x[0:3, 0:10:3]\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"slice_fp16x16_3d\"\n            make_test(\n                [x], y, \"input_0.slice(array![0, 0].span(), array![3, 10].span(), Option::Some(array![0, 1].span()), Option::Some(array![1, 3].span()))\", name)\n\n        slice_2D()\n        slice_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/softmax.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:\n    x_max = np.max(x, axis=axis, keepdims=True)\n    tmp = np.exp(x - x_max)\n    s = np.sum(tmp, axis=axis, keepdims=True)\n    return tmp / s\n\n\nclass Softmax(RunAll):\n        \n    @staticmethod\n    def axis_0():\n        x = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\n        y = softmax(x, axis=0)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"softmax_axis_0\"\n        make_test([x], y, \"NNTrait::softmax(@input_0, Option::Some(0))\",\n                  name, Trait.NN)\n    \n    @staticmethod\n    def axis_1():\n        x = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\n        y = softmax(x, axis=1)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"softmax_axis_1\"\n        make_test([x], y, \"NNTrait::softmax(@input_0, Option::Some(1))\",\n                  name, Trait.NN)\n    \n    @staticmethod\n    def axis_2():\n        x = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\n        y = softmax(x, axis=2)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"softmax_axis_2\"\n        make_test([x], y, \"NNTrait::softmax(@input_0, Option::Some(2))\",\n                  name, Trait.NN)\n    \n    @staticmethod\n    def axis_minus_1():\n        x = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\n        y = softmax(x, axis=-1)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"softmax_axis_minus_1\"\n        make_test([x], y, \"NNTrait::softmax(@input_0, Option::None)\",\n                  name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/softmax_zero.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef softmax_zero(x: np.ndarray, axis: int = -1) -> np.ndarray:\n    x_max = np.max(x, axis=axis, keepdims=True)\n    tmp = np.exp(x - x_max)\n    tmp = np.where(x == 0.0, 0.0, tmp)\n\n    s = np.sum(tmp, axis=axis, keepdims=True)\n    s = np.where(s == 0.0, 1, s)\n\n    \n    return tmp / s\n\n\nclass Softmax_zero(RunAll):\n\n\n    @staticmethod\n    def fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = softmax_zero(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"softmax_zero_fp8x23\"\n        make_test([x], y, \"NNTrait::softmax_zero(@input_0, 1)\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = softmax_zero(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"softmax_zero_fp16x16\"\n        make_test([x], y, \"NNTrait::softmax_zero(@input_0, 1)\",\n                    name, Trait.NN)\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/softplus.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef softplus(x: np.ndarray) -> np.ndarray:\n    return np.log(np.exp(x) + 1)\n\n\nclass Softplus(RunAll):\n\n    @staticmethod\n    def softplus_fp():\n        def fp8x23():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = softplus(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"softplus_fp8x23\"\n            make_test([x], y, \"NNTrait::softplus(@input_0)\",\n                      name, Trait.NN)\n\n        def fp16x16():\n            x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n            y = softplus(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"softplus_fp16x16\"\n            make_test([x], y, \"NNTrait::softplus(@input_0)\",\n                      name, Trait.NN)\n\n        fp8x23()\n        fp16x16()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/softsign.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\ndef softsign(x: np.ndarray) -> np.ndarray:\n    return x / (1 + np.abs(x))\n\n\nclass Softsign(RunAll):\n\n    @staticmethod\n    def softsign_fp():\n        def fp8x23():\n            x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n            y = softsign(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n\n            name = \"softsign_fp8x23\"\n            make_test([x], y, \"NNTrait::softsign(@input_0)\",\n                      name, Trait.NN)\n\n        def fp16x16():\n            x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n            y = softsign(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n\n            name = \"softsign_fp16x16\"\n            make_test([x], y, \"NNTrait::softsign(@input_0)\",\n                      name, Trait.NN)\n\n        fp8x23()\n        fp16x16()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/space_to_depth.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\ndef space_to_depth(data: np.ndarray, blocksize: int = 2) -> np.ndarray:\n    if len(data.shape) != 4:\n        raise RuntimeError(f\"Unexpected shape {data.shape!r}.\")\n    b, C, H, W = data.shape\n    tmpshape = (\n        b,\n        C,\n        H // blocksize,\n        blocksize,\n        W // blocksize,\n        blocksize,\n    )\n    reshaped = np.reshape(data, tmpshape)\n    transposed = np.transpose(reshaped, [0, 3, 5, 1, 2, 4])\n    finalshape = (\n        b,\n        C * blocksize * blocksize,\n        H // blocksize,\n        W // blocksize,\n    )\n    y = np.reshape(transposed, finalshape).astype(data.dtype)\n    return y\n\nclass Space_to_depth(RunAll):\n\n\n    @staticmethod\n    def fp8x23():\n        x = np.random.uniform(-3, 3, (1, 2, 2, 4)).astype(np.float64)\n        y = space_to_depth(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"space_to_depth_fp8x23\"\n        make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fp16x16():\n        x = np.random.uniform(-3, 3, (1, 2, 2, 4)).astype(np.float16)\n        y = space_to_depth(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"space_to_depth_fp16x16\"\n        make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n                    name, Trait.NN)\n        \n    # @staticmethod\n    # def fp64x64():\n    #     x = np.random.uniform(-3, 3, (1, 2, 2, 4)).astype(np.float64)\n    #     y = space_to_depth(x)\n\n    #     x = Tensor(Dtype.FP64x64, x.shape, to_fp(\n    #         x.flatten(), FixedImpl.FP64x64))\n    #     y = Tensor(Dtype.FP64x64, y.shape, to_fp(\n    #         y.flatten(), FixedImpl.FP64x64))\n\n    #     name = \"space_to_depth_fp64x64\"\n    #     make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n    #                 name, Trait.NN)\n\n    @staticmethod\n    def fpi8():\n        x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.int8)\n        y = space_to_depth(x)\n\n        x = Tensor(Dtype.I8, x.shape, x.flatten())\n        y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n        name = \"space_to_depth_i8\"\n        make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n                    name, Trait.NN)\n\n    @staticmethod\n    def fpi32():\n        x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.int32)\n        y = space_to_depth(x)\n\n        x = Tensor(Dtype.I32, x.shape, x.flatten())\n        y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n        name = \"space_to_depth_i32\"\n        make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n                    name, Trait.NN)\n\n\n    @staticmethod\n    def fpu32():\n        x = np.random.randint(-3, 3, (1, 2, 2, 4)).astype(np.uint32)\n        y = space_to_depth(x)\n\n        x = Tensor(Dtype.U32, x.shape, x.flatten())\n        y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n        name = \"space_to_depth_u32\"\n        make_test([x], y, \"NNTrait::space_to_depth(@input_0, 2)\",\n                    name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/split.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Split(RunAll):\n    @staticmethod\n    def split_u32():\n        def split_1D():\n            x = np.random.randint(0, 255, 6).astype(np.uint32)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:4]).astype(np.uint32),\n                np.array(x[4:6]).astype(np.uint32),\n            ]\n\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_u32_1d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::Some(3), Option::None(()))\", name)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:6]).astype(np.uint32),\n            ]\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_u32_1d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        def split_2D():\n            x = np.random.randint(0, 255, (2, 6)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.uint32),\n                np.array(x[0:2, 3:6]).astype(np.uint32),\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_u32_2d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::Some(2), Option::None(()))\", name)\n\n            y = [\n                np.array(x[0:2, 0:2]).astype(np.uint32), \n                np.array(x[0:2, 2:6]).astype(np.uint32)\n            ]\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_u32_2d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        \n        def split_zero_size():\n            # 1-dimensional tensor with dimension_size=0\n            x = np.array([]).astype(np.uint32)\n            y = [\n                np.array([]).astype(np.uint32),\n                np.array([]).astype(np.uint32),\n                np.array([]).astype(np.uint32),\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n            # Split emtpy tensor to tensors of size zero\n            name = \"split_u32_zero_size\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 0, 0].span(),)))\", name)\n            \n        \n        def split_1d_uneven():\n            x = np.random.randint(0, 255, 7).astype(np.uint32)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:4]).astype(np.uint32),\n                np.array(x[4:6]).astype(np.uint32),\n                np.array(x[6:7]).astype(np.uint32),\n            ]\n            \n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.U32, y[3].shape, y[3].flatten()),\n            ]\n\n            name = \"split_u32_1d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::Some(4), Option::None(()))\", name)\n            \n\n        def split_2d_uneven():\n            x = np.random.randint(0, 255, (2, 8)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.uint32), \n                np.array(x[0:2, 3:6]).astype(np.uint32), \n                np.array(x[0:2, 6:8]).astype(np.uint32)\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_u32_2d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::Some(3), Option::None(()))\", name)\n\n        \n        split_1D()\n        split_2D()\n        split_zero_size()\n        split_1d_uneven()\n        split_2d_uneven()\n\n    @staticmethod\n    def split_fp16x16():\n        def split_1D():\n            x = to_fp(np.random.randint(-127, 127, 6\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:4]).astype(np.int64),\n                np.array(x[4:6]).astype(np.int64),\n            ]\n\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_fp16x16_1d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::Some(3), Option::None(()))\", name)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:6]).astype(np.int64),\n            ]\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_fp16x16_1d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        def split_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 6)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.int64),\n                np.array(x[0:2, 3:6]).astype(np.int64),\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_fp16x16_2d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::Some(2), Option::None(()))\", name)\n\n            y = [\n                np.array(x[0:2, 0:2]).astype(np.int64), \n                np.array(x[0:2, 2:6]).astype(np.int64)\n            ]\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_fp16x16_2d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        \n        def split_zero_size():\n            # 1-dimensional tensor with dimension_size=0\n            x = to_fp(np.array([]).astype(np.int64\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array([]).astype(np.int64),\n                np.array([]).astype(np.int64),\n                np.array([]).astype(np.int64),\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n            # Split emtpy tensor to tensors of size zero\n            name = \"split_fp16x16_zero_size\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::None(()), Option::Some(TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 0, 0].span(),)))\", name)\n            \n        \n        def split_1d_uneven():\n            x = to_fp(np.random.randint(-127, 127, 7\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:4]).astype(np.int64),\n                np.array(x[4:6]).astype(np.int64),\n                np.array(x[6:7]).astype(np.int64),\n            ]\n\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.FP16x16, y[3].shape, y[3].flatten()),\n            ]\n\n            name = \"split_fp16x16_1d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split(0, Option::Some(4), Option::None(()))\", name)\n            \n\n        def split_2d_uneven():\n            x = to_fp(np.random.randint(-127, 127, (2, 8)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.int64), \n                np.array(x[0:2, 3:6]).astype(np.int64), \n                np.array(x[0:2, 6:8]).astype(np.int64)\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_fp16x16_2d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split(1, Option::Some(3), Option::None(()))\", name)\n\n        \n        split_1D()\n        split_2D()\n        split_zero_size()\n        split_1d_uneven()\n        split_2d_uneven()\n    "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/split_to_sequence.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Split_to_sequence(RunAll):\n    @staticmethod\n    def split_to_sequence_u32():\n        def split_to_sequence_1D():\n            x = np.random.randint(0, 255, 6).astype(np.uint32)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:4]).astype(np.uint32),\n                np.array(x[4:6]).astype(np.uint32),\n            ]\n\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_to_sequence_u32_1d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![3].span(),)))\", name)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:6]).astype(np.uint32),\n            ]\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_u32_1d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        def split_to_sequence_2D():\n            x = np.random.randint(0, 255, (2, 6)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.uint32),\n                np.array(x[0:2, 3:6]).astype(np.uint32),\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_u32_2d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![2].span(),)))\", name)\n\n            y = [\n                np.array(x[0:2, 0:2]).astype(np.uint32), \n                np.array(x[0:2, 2:6]).astype(np.uint32)\n            ]\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_u32_2d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        \n        def split_to_sequence_zero_size():\n            # 1-dimensional tensor with dimension_size=0\n            x = np.array([]).astype(np.uint32)\n            y = [\n                np.array([]).astype(np.uint32),\n                np.array([]).astype(np.uint32),\n                np.array([]).astype(np.uint32),\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n            # Split emtpy tensor to tensors of size zero\n            name = \"split_to_sequence_u32_zero_size\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 0, 0].span(),)))\", name)\n            \n        \n        def split_to_sequence_1d_uneven():\n            x = np.random.randint(0, 255, 7).astype(np.uint32)\n            y = [\n                np.array(x[0:2]).astype(np.uint32), \n                np.array(x[2:4]).astype(np.uint32),\n                np.array(x[4:6]).astype(np.uint32),\n                np.array(x[6:7]).astype(np.uint32),\n            ]\n            \n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.U32, y[3].shape, y[3].flatten()),\n            ]\n\n            name = \"split_to_sequence_u32_1d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![4].span(),)))\", name)\n            \n\n        def split_to_sequence_2d_uneven():\n            x = np.random.randint(0, 255, (2, 8)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.uint32), \n                np.array(x[0:2, 3:6]).astype(np.uint32), \n                np.array(x[0:2, 6:8]).astype(np.uint32)\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_to_sequence_u32_2d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![3].span(),)))\", name)\n        \n        def split_to_sequence_2d_scalar():\n            x = np.random.randint(0, 255, (2, 8)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:1]).astype(np.uint32), \n                np.array(x[0:2, 1:2]).astype(np.uint32), \n                np.array(x[0:2, 2:3]).astype(np.uint32), \n                np.array(x[0:2, 3:4]).astype(np.uint32), \n                np.array(x[0:2, 4:5]).astype(np.uint32), \n                np.array(x[0:2, 5:6]).astype(np.uint32), \n                np.array(x[0:2, 6:7]).astype(np.uint32),\n                np.array(x[0:2, 7:8]).astype(np.uint32)\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.U32, y[3].shape, y[3].flatten()),\n                Tensor(Dtype.U32, y[4].shape, y[4].flatten()),\n                Tensor(Dtype.U32, y[5].shape, y[5].flatten()),\n                Tensor(Dtype.U32, y[6].shape, y[6].flatten()),\n                Tensor(Dtype.U32, y[7].shape, y[7].flatten()),\n            ]\n\n            name = \"split_to_sequence_2d_scalar\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::None(()))\", name)\n        \n        def split_to_sequence_2d_nokeepdims():\n            x = np.random.randint(0, 255, (2, 8)).astype(np.uint32)\n            y = [\n                np.array(x[0:2, 0:1]).astype(np.uint32), \n                np.array(x[0:2, 1:2]).astype(np.uint32), \n                np.array(x[0:2, 2:3]).astype(np.uint32), \n                np.array(x[0:2, 3:4]).astype(np.uint32), \n                np.array(x[0:2, 4:5]).astype(np.uint32), \n                np.array(x[0:2, 5:6]).astype(np.uint32), \n                np.array(x[0:2, 6:7]).astype(np.uint32),\n                np.array(x[0:2, 7:8]).astype(np.uint32)\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.U32, y[3].shape, y[3].flatten()),\n                Tensor(Dtype.U32, y[4].shape, y[4].flatten()),\n                Tensor(Dtype.U32, y[5].shape, y[5].flatten()),\n                Tensor(Dtype.U32, y[6].shape, y[6].flatten()),\n                Tensor(Dtype.U32, y[7].shape, y[7].flatten()),\n            ]\n\n            name = \"split_to_sequence_2d_nokeepdims\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 0, Option::None(()))\", name)\n            \n        def split_to_sequence_1d_nokeepdims():\n            x = np.random.randint(0, 255, 8).astype(np.uint32)\n            y = [\n                np.array(x[0:1]).astype(np.uint32), \n                np.array(x[1:2]).astype(np.uint32), \n                np.array(x[2:3]).astype(np.uint32), \n                np.array(x[3:4]).astype(np.uint32), \n                np.array(x[4:5]).astype(np.uint32), \n                np.array(x[5:6]).astype(np.uint32), \n                np.array(x[6:7]).astype(np.uint32),\n                np.array(x[7:8]).astype(np.uint32)\n            ]\n            _x = Tensor(Dtype.U32, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.U32, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.U32, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.U32, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.U32, y[3].shape, y[3].flatten()),\n                Tensor(Dtype.U32, y[4].shape, y[4].flatten()),\n                Tensor(Dtype.U32, y[5].shape, y[5].flatten()),\n                Tensor(Dtype.U32, y[6].shape, y[6].flatten()),\n                Tensor(Dtype.U32, y[7].shape, y[7].flatten()),\n            ]\n\n            name = \"split_to_sequence_1d_nokeepdims\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 0, Option::None(()))\", name)\n\n        \n        split_to_sequence_1D()\n        split_to_sequence_2D()\n        split_to_sequence_zero_size()\n        split_to_sequence_1d_uneven()\n        split_to_sequence_2d_uneven()\n        split_to_sequence_2d_scalar()\n        split_to_sequence_1d_nokeepdims()\n        split_to_sequence_2d_nokeepdims()\n\n    @staticmethod\n    def split_to_sequence_fp16x16():\n        def split_to_sequence_1D():\n            x = to_fp(np.random.randint(-127, 127, 6\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:4]).astype(np.int64),\n                np.array(x[4:6]).astype(np.int64),\n            ]\n\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_to_sequence_fp16x16_1d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![3].span(),)))\", name)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:6]).astype(np.int64),\n            ]\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_fp16x16_1d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        def split_to_sequence_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 6)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.int64),\n                np.array(x[0:2, 3:6]).astype(np.int64),\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_fp16x16_2d_equal_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![2].span(),)))\", name)\n\n            y = [\n                np.array(x[0:2, 0:2]).astype(np.int64), \n                np.array(x[0:2, 2:6]).astype(np.int64)\n            ]\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n            ]\n            name = \"split_to_sequence_fp16x16_2d_variable_parts\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![2].span(), data: array![2, 4].span(),)))\", name)\n        \n        def split_to_sequence_zero_size():\n            # 1-dimensional tensor with dimension_size=0\n            x = to_fp(np.array([]).astype(np.int64\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array([]).astype(np.int64),\n                np.array([]).astype(np.int64),\n                np.array([]).astype(np.int64),\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n            # Split emtpy tensor to tensors of size zero\n            name = \"split_to_sequence_fp16x16_zero_size\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 0, 0].span(),)))\", name)\n            \n        \n        def split_to_sequence_1d_uneven():\n            x = to_fp(np.random.randint(-127, 127, 7\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2]).astype(np.int64), \n                np.array(x[2:4]).astype(np.int64),\n                np.array(x[4:6]).astype(np.int64),\n                np.array(x[6:7]).astype(np.int64),\n            ]\n\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n                Tensor(Dtype.FP16x16, y[3].shape, y[3].flatten()),\n            ]\n\n            name = \"split_to_sequence_fp16x16_1d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(0, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![4].span())))\", name)\n            \n\n        def split_to_sequence_2d_uneven():\n            x = to_fp(np.random.randint(-127, 127, (2, 8)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = [\n                np.array(x[0:2, 0:3]).astype(np.int64), \n                np.array(x[0:2, 3:6]).astype(np.int64), \n                np.array(x[0:2, 6:8]).astype(np.int64)\n            ]\n            _x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            _y = [\n                Tensor(Dtype.FP16x16, y[0].shape, y[0].flatten()),\n                Tensor(Dtype.FP16x16, y[1].shape, y[1].flatten()),\n                Tensor(Dtype.FP16x16, y[2].shape, y[2].flatten()),\n            ]\n\n            name = \"split_to_sequence_fp16x16_2d_uneven\"\n            make_test(\n                [_x], _y, \"input_0.split_to_sequence(1, 1, Option::Some(TensorTrait::<u32>::new(shape: array![1].span(), data: array![3].span(),)))\", name)\n\n        \n        split_to_sequence_1D()\n        split_to_sequence_2D()\n        split_to_sequence_zero_size()\n        split_to_sequence_1d_uneven()\n        split_to_sequence_2d_uneven()\n    "
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sqrt.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Sqrt(RunAll):\n\n    @staticmethod\n    def sqrt_fp8x23():\n        x = np.random.uniform(0, 6, (2, 2)).astype(np.float64)\n        y = np.sqrt(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"sqrt_fp8x23\"\n        make_test([x], y, \"input_0.sqrt()\", name)\n\n    @staticmethod\n    def sqrt_fp16x16():\n        x = np.random.uniform(0, 6, (2, 2)).astype(np.float64)\n        y = np.sqrt(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"sqrt_fp16x16\"\n        make_test([x], y, \"input_0.sqrt()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/squeeze.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Squeeze(RunAll):\n    @staticmethod\n    def squeeze_i8():\n        def squeeze():\n            x = np.ones((1, 2, 1, 2, 1), dtype=np.int8)\n            y = np.ones((2, 2, 1), dtype=np.int8)\n            \n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"squeeze_i8\"\n            make_test(\n                [x], y, \"input_0.squeeze(Option::Some(array![0, 2].span()))\", name)\n        squeeze()\n\n    @staticmethod\n    def squeeze():\n        def squeeze():\n            x = np.ones((1, 2, 1, 2, 1), dtype=np.int32)\n            y = np.ones((2, 2, 1), dtype=np.int32)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"squeeze\"\n            make_test(\n                [x], y, \"input_0.squeeze(Option::Some(array![0, 2].span()))\", name)\n        squeeze()\n\n    @staticmethod\n    def squeeze_u32():\n        def squeeze():\n            x = np.ones((1, 2, 1, 2, 1), dtype=np.uint32)\n            y = np.ones((2, 2, 1), dtype=np.uint32)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"squeeze_u32\"\n            make_test(\n                [x], y, \"input_0.squeeze(Option::Some(array![0, 2].span()))\", name)\n        squeeze()\n    \n    @staticmethod\n    def squeeze_fP16x16():\n        def squeeze():\n            x = to_fp(np.random.randint(0, 255, (1, 2, 1, 2, 1)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = to_fp(np.random.randint(0, 255, (2, 2, 1)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"squeeze_fP16x16\"\n            make_test(\n                [x], y, \"input_0.squeeze(Option::Some(array![0, 2].span()))\", name)\n        squeeze()\n\n    @staticmethod\n    def squeeze_fP8x23():\n        def squeeze():\n            x = to_fp(np.random.randint(0, 255, (1, 2, 1, 2, 1)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = to_fp(np.random.randint(0, 255, (2, 2, 1)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"squeeze_fP8x23\"\n            make_test(\n                [x], y, \"input_0.squeeze(Option::Some(array![0, 2].span()))\", name)\n        squeeze()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/sub.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Sub(RunAll):\n    @staticmethod\n    def sub_u32():\n        def default():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (3, 3, 3)).astype(np.uint32)\n            z = x - y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"sub_u32\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(3, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 3, (1, 3, 1)).astype(np.uint32)\n            z = x - y\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"sub_u32_broadcast\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sub_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = x - y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"sub_i32\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int32)\n            z = x - y\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"sub_i32_broadcast\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sub_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = x - y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"sub_i8\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.int8)\n            z = x - y\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"sub_i8_broadcast\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sub_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x - y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"sub_fp8x23\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x - y\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"sub_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def sub_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = x - y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"sub_fp16x16\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 3, 1)).astype(np.float64)\n            z = x - y\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape, to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"sub_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0 - input_1\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/tanh.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Tanh(RunAll):\n\n    @staticmethod\n    def tanh_fp8x23():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.tanh(x)\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"tanh_fp8x23\"\n        make_test([x], y, \"input_0.tanh()\", name)\n\n    @staticmethod\n    def tanh_fp16x16():\n        x = np.random.uniform(-3, 3, (2, 2)).astype(np.float64)\n        y = np.tanh(x)\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"tanh_fp16x16\"\n        make_test([x], y, \"input_0.tanh()\", name)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/thresholded_relu.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl, Trait\n\n\nclass Thresholded_relu(RunAll):\n\n    @staticmethod\n    def thresholded_relu_fp8x23():\n\n        alpha = 1.0\n\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        y = np.clip(x, alpha, np.inf)\n        y[y == alpha] = 0\n\n        x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP8x23))\n        y = Tensor(Dtype.FP8x23, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP8x23))\n\n        name = \"thresholded_relu_fp8x23\"\n        make_test([x], y, \"NNTrait::thresholded_relu(@input_0, @FixedTrait::new(256, false))\",\n                  name, Trait.NN)\n\n    @staticmethod\n    def thresholded_relu_fp16x16():\n\n        alpha = 1.0\n\n        x = np.random.uniform(-5, 7, (2, 2)).astype(np.float64)\n        y = np.clip(x, alpha, np.inf)\n        y[y == alpha] = 0\n\n        x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n            x.flatten(), FixedImpl.FP16x16))\n        y = Tensor(Dtype.FP16x16, y.shape, to_fp(\n            y.flatten(), FixedImpl.FP16x16))\n\n        name = \"thresholded_relu_fp16x16\"\n        make_test([x], y, \"NNTrait::thresholded_relu(@input_0, @FixedTrait::new(65536, false))\",\n                  name, Trait.NN)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/transpose.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Transpose(RunAll):\n    @staticmethod\n    def transpose_u32():\n        def transpose_2D():\n            x = np.random.randint(0, 255, (2, 2)).astype(np.uint32)\n            y = np.transpose(x, [1, 0])\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"transpose_u32_2d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 0].span())\", name)\n\n        def transpose_3D():\n            x = np.random.randint(0, 255, (2, 2, 2)).astype(np.uint32)\n            y = np.transpose(x, [1, 2, 0])\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"transpose_u32_3d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 2, 0].span())\", name)\n\n        transpose_2D()\n        transpose_3D()\n\n    @staticmethod\n    def transpose_i32():\n        def transpose_2D():\n            x = np.random.randint(-127, 127, (2, 2)).astype(np.int32)\n            y = np.transpose(x, [1, 0])\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"transpose_i32_2d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 0].span())\", name)\n\n        def transpose_3D():\n            x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int32)\n            y = np.transpose(x, [1, 2, 0])\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"transpose_i32_3d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 2, 0].span())\", name)\n\n\n        transpose_2D()\n        transpose_3D()\n\n    @staticmethod\n    def transpose_i8():\n        def transpose_2D():\n            x = np.random.randint(-127, 127, (2, 2)).astype(np.int8)\n            y = np.transpose(x, [1, 0])\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"transpose_i8_2d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 0].span())\", name)\n\n        def transpose_3D():\n            x = np.random.randint(-127, 127, (2, 2, 2)).astype(np.int8)\n            y = np.transpose(x, [1, 2, 0])\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"transpose_i8_3d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 2, 0].span())\", name)\n\n        transpose_2D()\n        transpose_3D()\n\n    @staticmethod\n    def transpose_fp8x23():\n        def transpose_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.transpose(x, [1, 0])\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"transpose_fp8x23_2d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 0].span())\", name)\n\n        def transpose_3D():\n            x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.transpose(x, [1, 2, 0])\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"transpose_fp8x23_3d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 2, 0].span())\", name)\n\n        transpose_2D()\n        transpose_3D()\n\n    @staticmethod\n    def transpose_fp16x16():\n        def transpose_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 2)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.transpose(x, [1, 0])\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"transpose_fp16x16_2d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 0].span())\", name)\n\n        def transpose_3D():\n            x = to_fp(np.random.randint(-127, 127, (2, 2, 2)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.transpose(x, [1, 2, 0])\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"transpose_fp16x16_3d\"\n            make_test(\n                [x], y, \"input_0.transpose(array![1, 2, 0].span())\", name)\n\n        transpose_2D()\n        transpose_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/trilu.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Trilu(RunAll):\n    @staticmethod\n    def trilu_u32():\n        def tril():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_neg():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n        def tril_one_row():\n            x = np.random.randint(0, 255, (3, 1, 5)).astype(np.uint32)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_out_neg():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.tril(x, k=-7)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -7)\", name)\n\n\n        def tril_out_pos():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def tril_pos():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.tril(x, k=2)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 2)\", name)\n\n\n        def tril_square():\n            x = np.random.randint(0, 255, (2, 3, 3)).astype(np.uint32)\n            y = np.tril(x, k=0)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n\n        def tril_square_neg():\n            x = np.random.randint(0, 255, (2, 3, 3)).astype(np.uint32)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n\n        def tril_zero():\n            x = np.random.randint(0, 255, (3, 0, 5)).astype(np.uint32)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"tril_u32_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def triu():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_neg():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n        def triu_one_row():\n            x = np.random.randint(0, 255, (3, 1, 5)).astype(np.uint32)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_out_neg():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.triu(x, k=-7)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -7)\", name)\n\n\n        def triu_out_pos():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n\n        def triu_pos():\n            x = np.random.randint(0, 255, (4, 5)).astype(np.uint32)\n            y = np.triu(x, k=2)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 2)\", name)\n\n\n        def triu_square():\n            x = np.random.randint(0, 255, (2, 3, 3)).astype(np.uint32)\n            y = np.triu(x, k=0)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n\n        def triu_square_neg():\n            x = np.random.randint(0, 255, (2, 3, 3)).astype(np.uint32)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n\n        def triu_zero():\n            x = np.random.randint(0, 255, (3, 0, 5)).astype(np.uint32)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"triu_u32_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n        tril()\n        tril_neg()\n        tril_one_row()\n        tril_out_neg()\n        tril_out_pos()\n        tril_pos()\n        tril_square()\n        tril_square_neg()\n        tril_zero()\n        triu()\n        triu_neg()\n        triu_one_row()\n        triu_out_neg()\n        triu_out_pos()\n        triu_pos()\n        triu_square()\n        triu_square_neg()\n        triu_zero()\n\n\n    @staticmethod\n    def trilu_i32():\n        def tril():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_neg_i32\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n        def tril_one_row():\n            x = np.random.randint(-127, 127, (3, 1, 5)).astype(np.int32)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_out_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.tril(x, k=-7)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -7)\", name)\n\n\n        def tril_out_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def tril_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.tril(x, k=2)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 2)\", name)\n\n\n        def tril_square():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int32)\n            y = np.tril(x, k=0)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n\n        def tril_square_neg():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int32)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n\n        def tril_zero():\n            x = np.random.randint(-127, 127, (3, 0, 5)).astype(np.int32)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"tril_i32_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def triu():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n        def triu_one_row():\n            x = np.random.randint(-127, 127, (3, 1, 5)).astype(np.int32)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_out_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.triu(x, k=-7)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -7)\", name)\n\n\n        def triu_out_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n\n        def triu_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int32)\n            y = np.triu(x, k=2)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 2)\", name)\n\n\n        def triu_square():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int32)\n            y = np.triu(x, k=0)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n\n        def triu_square_neg():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int32)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n\n        def triu_zero():\n            x = np.random.randint(-127, 127, (3, 0, 5)).astype(np.int32)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"triu_i32_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n        tril()\n        tril_neg()\n        tril_one_row()\n        tril_out_neg()\n        tril_out_pos()\n        tril_pos()\n        tril_square()\n        tril_square_neg()\n        tril_zero()\n        triu()\n        triu_neg()\n        triu_one_row()\n        triu_out_neg()\n        triu_out_pos()\n        triu_pos()\n        triu_square()\n        triu_square_neg()\n        triu_zero()\n\n\n    @staticmethod\n    def trilu_i8():\n        def tril():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n        def tril_one_row():\n            x = np.random.randint(-127, 127, (3, 1, 5)).astype(np.int8)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_out_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.tril(x, k=-7)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -7)\", name)\n\n\n        def tril_out_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def tril_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.tril(x, k=2)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 2)\", name)\n\n\n        def tril_square():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int8)\n            y = np.tril(x, k=0)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n\n        def tril_square_neg():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int8)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n\n        def tril_zero():\n            x = np.random.randint(-127, 127, (3, 0, 5)).astype(np.int8)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"tril_i8_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def triu():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n        def triu_one_row():\n            x = np.random.randint(-127, 127, (3, 1, 5)).astype(np.int8)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_out_neg():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.triu(x, k=-7)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -7)\", name)\n\n\n        def triu_out_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n\n        def triu_pos():\n            x = np.random.randint(-127, 127, (4, 5)).astype(np.int8)\n            y = np.triu(x, k=2)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 2)\", name)\n\n\n        def triu_square():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int8)\n            y = np.triu(x, k=0)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n\n        def triu_square_neg():\n            x = np.random.randint(-127, 127, (2, 3, 3)).astype(np.int8)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n\n        def triu_zero():\n            x = np.random.randint(-127, 127, (3, 0, 5)).astype(np.int8)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"triu_i8_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n        tril()\n        tril_neg()\n        tril_one_row()\n        tril_out_neg()\n        tril_out_pos()\n        tril_pos()\n        tril_square()\n        tril_square_neg()\n        tril_zero()\n        triu()\n        triu_neg()\n        triu_one_row()\n        triu_out_neg()\n        triu_out_pos()\n        triu_pos()\n        triu_square()\n        triu_square_neg()\n        triu_zero()\n\n\n    @staticmethod\n    def trilu_fp8x23():\n        def tril():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n        def tril_one_row():\n            x = to_fp(np.random.randint(-127, 127, (3, 1, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_out_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=-7)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -7)\", name)\n\n\n        def tril_out_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def tril_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=2)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 2)\", name)\n\n\n        def tril_square():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=0)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n\n        def tril_square_neg():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n\n        def tril_zero():\n            x = to_fp(np.random.randint(-127, 127, (3, 0, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"tril_fp8x23_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def triu():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n        def triu_one_row():\n            x = to_fp(np.random.randint(-127, 127, (3, 1, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_out_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=-7)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -7)\", name)\n\n\n        def triu_out_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n\n        def triu_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=2)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 2)\", name)\n\n\n        def triu_square():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=0)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n\n        def triu_square_neg():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n\n        def triu_zero():\n            x = to_fp(np.random.randint(-127, 127, (3, 0, 5)).astype(np.int64), FixedImpl.FP8x23)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n\n            name = \"triu_fp8x23_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n        tril()\n        tril_neg()\n        tril_one_row()\n        tril_out_neg()\n        tril_out_pos()\n        tril_pos()\n        tril_square()\n        tril_square_neg()\n        tril_zero()\n        triu()\n        triu_neg()\n        triu_one_row()\n        triu_out_neg()\n        triu_out_pos()\n        triu_pos()\n        triu_square()\n        triu_square_neg()\n        triu_zero()\n\n        \n    @staticmethod\n    def trilu_fp16x16():\n        def tril():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n        def tril_one_row():\n            x = to_fp(np.random.randint(-127, 127, (3, 1, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n        def tril_out_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=-7)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -7)\", name)\n\n\n        def tril_out_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def tril_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=2)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 2)\", name)\n\n\n        def tril_square():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=0)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 0)\", name)\n\n\n        def tril_square_neg():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=-1)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, -1)\", name)\n\n\n        def tril_zero():\n            x = to_fp(np.random.randint(-127, 127, (3, 0, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.tril(x, k=6)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"tril_fp16x16_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(false, 6)\", name)\n\n\n        def triu():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n        def triu_one_row():\n            x = to_fp(np.random.randint(-127, 127, (3, 1, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_one_row\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n        def triu_out_neg():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=-7)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_out_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -7)\", name)\n\n\n        def triu_out_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_out_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n\n        def triu_pos():\n            x = to_fp(np.random.randint(-127, 127, (4, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=2)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_pos\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 2)\", name)\n\n\n        def triu_square():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=0)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_square\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 0)\", name)\n\n\n        def triu_square_neg():\n            x = to_fp(np.random.randint(-127, 127, (2, 3, 3)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=-1)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_square_neg\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, -1)\", name)\n\n\n        def triu_zero():\n            x = to_fp(np.random.randint(-127, 127, (3, 0, 5)).astype(np.int64), FixedImpl.FP16x16)\n            y = np.triu(x, k=6)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"triu_fp16x16_zero\"\n            \n            make_test(\n                [x], y, \"input_0.trilu(true, 6)\", name)\n\n        tril()\n        tril_neg()\n        tril_one_row()\n        tril_out_neg()\n        tril_out_pos()\n        tril_pos()\n        tril_square()\n        tril_square_neg()\n        tril_zero()\n        triu()\n        triu_neg()\n        triu_one_row()\n        triu_out_neg()\n        triu_out_pos()\n        triu_pos()\n        triu_square()\n        triu_square_neg()\n        triu_zero()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/unique.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\nfrom typing import Optional\n\n\ndef _unsort_outputs(\n    x: np.ndarray,\n    axis: Optional[int],\n    unique_values: np.ndarray,\n    indices: np.ndarray,\n    inverse_indices: np.ndarray,\n    counts: np.ndarray,\n) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray):\n    \"\"\"Unsort the result of np.unique().\n\n    This is done because numpy unique does not retain original order (it sorts\n    the output unique values).\n    (see: https://github.com/numpy/numpy/issues/8621)\n\n    Code taken from onnx:\n    https://github.com/onnx/onnx/blob/main/onnx/backend/test/case/node/unique.py\n    \"\"\"\n    argsorted_indices = np.argsort(indices)\n    inverse_indices_map = dict(\n        zip(argsorted_indices, np.arange(len(argsorted_indices)))\n    )\n    indices = indices[argsorted_indices]\n    unique_values = np.take(x, indices, axis=axis)\n    inverse_indices = np.asarray(\n        [inverse_indices_map[i] for i in inverse_indices], dtype=np.int32\n    )\n    counts = counts[argsorted_indices]\n    return (unique_values, indices, inverse_indices, counts)\n\n\nclass Unique(RunAll):\n    @staticmethod\n    def unique_u32():\n        def without_axis_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = None\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_without_axis_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::None(()), Option::Some(true))\",\n                name,\n            )\n\n        def without_axis_not_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = None\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n            unique_values, indices, inverse_indices, counts = _unsort_outputs(\n                x, axis, unique_values, indices, inverse_indices, counts\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_without_axis_not_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::None(()), Option::Some(false))\",\n                name,\n            )\n\n        def with_axis_zero_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = 0\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_with_axis_zero_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::Some(0), Option::Some(true))\",\n                name,\n            )\n\n        def with_axis_zero_not_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = 0\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n            unique_values, indices, inverse_indices, counts = _unsort_outputs(\n                x, axis, unique_values, indices, inverse_indices, counts\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_with_axis_zero_not_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::Some(0), Option::Some(false))\",\n                name,\n            )\n\n        def with_axis_one_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = 1\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_with_axis_one_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::Some(1), Option::Some(true))\",\n                name,\n            )\n\n        def with_axis_one_not_sorted():\n            x = np.random.randint(0, 5, (3, 3, 3)).astype(np.uint32)\n            axis = 1\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n            unique_values, indices, inverse_indices, counts = _unsort_outputs(\n                x, axis, unique_values, indices, inverse_indices, counts\n            )\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            unique_values = Tensor(\n                Dtype.U32, unique_values.shape, unique_values.flatten()\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_u32_with_axis_one_not_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::Some(1), Option::Some(false))\",\n                name,\n            )\n\n        without_axis_sorted()\n        without_axis_not_sorted()\n        with_axis_zero_sorted()\n        with_axis_zero_not_sorted()\n        with_axis_one_sorted()\n        with_axis_one_not_sorted()\n\n    @staticmethod\n    def unique_fp16x16():\n        def without_axis_sorted():\n            x = np.random.uniform(0, 3, (3, 3, 3)).astype(np.float64)\n            axis = None\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n            unique_values = unique_values.astype(np.float16)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n            unique_values = Tensor(\n                Dtype.FP16x16,\n                unique_values.shape,\n                to_fp(unique_values.flatten(), FixedImpl.FP16x16),\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_fp16x16_without_axis_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::None(()), Option::Some(true))\",\n                name,\n            )\n\n        def with_axis_zero_sorted():\n            x = np.random.uniform(-3, 3, (3, 3, 3)).astype(np.float64)\n            axis = 0\n\n            unique_values, indices, inverse_indices, counts = np.unique(\n                x, axis=axis, return_index=True, return_inverse=True, return_counts=True\n            )\n            unique_values = unique_values.astype(np.float16)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(x.flatten(), FixedImpl.FP16x16))\n            unique_values = Tensor(\n                Dtype.FP16x16,\n                unique_values.shape,\n                to_fp(unique_values.flatten(), FixedImpl.FP16x16),\n            )\n            indices = Tensor(Dtype.I32, indices.shape, indices.flatten())\n            inverse_indices = Tensor(\n                Dtype.I32, inverse_indices.shape, inverse_indices.flatten()\n            )\n            counts = Tensor(Dtype.I32, counts.shape, counts.flatten())\n\n            name = \"unique_fp16x16_with_axis_zero_sorted\"\n            make_test(\n                [x],\n                (unique_values, indices, inverse_indices, counts),\n                \"input_0.unique(Option::Some(0), Option::Some(true))\",\n                name,\n            )\n\n        without_axis_sorted()\n        with_axis_zero_sorted()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/unsqueeze.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Unsqueeze(RunAll):\n    @staticmethod\n    def unsqueeze_u32():\n        def unsqueeze_2D():\n            x = np.random.randint(0, 255, (2, 4)).astype(np.uint32)\n            y = np.expand_dims(x, axis=0)\n            y = np.expand_dims(y, axis=1)\n            y = np.expand_dims(y, axis=4)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"unsqueeze_u32_2d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![1, 4, 0].span())\", name)\n\n        def unsqueeze_3D():\n            x = np.random.randint(0, 255, (20, 10, 5)).astype(np.uint32)\n            y = np.expand_dims(x, axis=2)\n            y = np.expand_dims(y, axis=4)\n            y = np.expand_dims(y, axis=5)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n\n            name = \"unsqueeze_u32_3d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![5, 4, 2].span())\", name)\n\n        unsqueeze_2D()\n        unsqueeze_3D()\n\n    @staticmethod\n    def unsqueeze_i32():\n        def unsqueeze_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int32)\n            y = np.expand_dims(x, axis=0)\n            y = np.expand_dims(y, axis=1)\n            y = np.expand_dims(y, axis=4)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"unsqueeze_i32_2d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![1, 4, 0].span())\", name)\n\n        def unsqueeze_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int32)\n            y = np.expand_dims(x, axis=2)\n            y = np.expand_dims(y, axis=4)\n            y = np.expand_dims(y, axis=5)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n\n            name = \"unsqueeze_i32_3d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![5, 4, 2].span())\", name)\n\n\n        unsqueeze_2D()\n        unsqueeze_3D()\n\n    @staticmethod\n    def unsqueeze_i8():\n        def unsqueeze_2D():\n            x = np.random.randint(-127, 127, (2, 4)).astype(np.int8)\n            y = np.expand_dims(x, axis=0)\n            y = np.expand_dims(y, axis=1)\n            y = np.expand_dims(y, axis=4)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"unsqueeze_i8_2d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![1, 4, 0].span())\", name)\n\n        def unsqueeze_3D():\n            x = np.random.randint(-127, 127, (20, 10, 5)).astype(np.int8)\n            y = np.expand_dims(x, axis=2)\n            y = np.expand_dims(y, axis=4)\n            y = np.expand_dims(y, axis=5)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n\n            name = \"unsqueeze_i8_3d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![5, 4, 2].span())\", name)\n\n        unsqueeze_2D()\n        unsqueeze_3D()\n\n    @staticmethod\n    def unsqueeze_fp8x23():\n        def unsqueeze_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.expand_dims(x, axis=0)\n            y = np.expand_dims(y, axis=1)\n            y = np.expand_dims(y, axis=4)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"unsqueeze_fp8x23_2d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![1, 4, 0].span())\", name)\n\n        def unsqueeze_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP8x23)\n            y = np.expand_dims(x, axis=2)\n            y = np.expand_dims(y, axis=4)\n            y = np.expand_dims(y, axis=5)\n\n            x = Tensor(Dtype.FP8x23, x.shape, x.flatten())\n            y = Tensor(Dtype.FP8x23, y.shape, y.flatten())\n            \n            name = \"unsqueeze_fp8x23_3d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![5, 4, 2].span())\", name)\n\n        unsqueeze_2D()\n        unsqueeze_3D()\n\n    @staticmethod\n    def unsqueeze_fp16x16():\n        def unsqueeze_2D():\n            x = to_fp(np.random.randint(-127, 127, (2, 4)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.expand_dims(x, axis=0)\n            y = np.expand_dims(y, axis=1)\n            y = np.expand_dims(y, axis=4)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"unsqueeze_fp16x16_2d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![1, 4, 0].span())\", name)\n\n        def unsqueeze_3D():\n            x = to_fp(np.random.randint(-127, 127, (20, 10, 5)\n                                        ).astype(np.int64), FixedImpl.FP16x16)\n            y = np.expand_dims(x, axis=2)\n            y = np.expand_dims(y, axis=4)\n            y = np.expand_dims(y, axis=5)\n\n            x = Tensor(Dtype.FP16x16, x.shape, x.flatten())\n            y = Tensor(Dtype.FP16x16, y.shape, y.flatten())\n\n            name = \"unsqueeze_fp16x16_3d\"\n            make_test(\n                [x], y, \"input_0.unsqueeze(array![5, 4, 2].span())\", name)\n\n        unsqueeze_2D()\n        unsqueeze_3D()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/where.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Where(RunAll):\n\n    @staticmethod\n    def where_u32():\n        def default():\n            cond = np.random.choice([1, 0], (3, 3, 3)).astype(np.uint32)\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.U32, cond.shape, cond.flatten())\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"where_u32\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        def broadcast():\n            cond = np.random.choice([1, 0], (1, 1)).astype(np.uint32)\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.U32, cond.shape, cond.flatten())\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"where_u32_broadcast\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def where_i32():\n        def default():\n            cond = np.random.choice([1, 0], (3, 3, 3)).astype(np.int32)\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int32)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.I32, cond.shape, cond.flatten())\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"where_i32\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        def broadcast():\n            cond = np.random.choice([1, 0], (1, 1)).astype(np.int32)\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int32)\n\n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.I32, cond.shape, cond.flatten())\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.I32, z.shape, z.flatten())\n\n            name = \"where_i32_broadcast\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def where_i8():\n        def default():\n            cond = np.random.choice([1, 0], (3, 3, 3)).astype(np.int8)\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.int8)\n\n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.I8, cond.shape, cond.flatten())\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"where_i8\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        def broadcast():\n            cond = np.random.choice([1, 0], (1, 1)).astype(np.int8)\n            x = np.random.randint(0, 6, (2, 2)).astype(np.int8)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.int8)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.I8, cond.shape, cond.flatten())\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.I8, z.shape, z.flatten())\n\n            name = \"where_i8_broadcast\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def where_fp8x23():\n        def default():\n            cond = np.random.choice([1, 0], (3, 3, 3)).astype(np.float64)\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.float64)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.FP8x23, cond.shape, to_fp(\n                cond.flatten(), FixedImpl.FP8x23))\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"where_fp8x23\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        def broadcast():\n            cond = np.random.choice([1, 0], (1, 1)).astype(np.float64)\n            x = np.random.randint(0, 6, (2, 2)).astype(np.float64)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.float64)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.FP8x23, cond.shape, to_fp(\n                cond.flatten(), FixedImpl.FP8x23))\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.FP8x23, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP8x23))\n\n            name = \"where_fp8x23_broadcast\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def where_fp16x16():\n        def default():\n            cond = np.random.choice([1, 0], (3, 3, 3)).astype(np.float64)\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.float64)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.FP16x16, cond.shape, to_fp(\n                cond.flatten(), FixedImpl.FP16x16))\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n            \n            name = \"where_fp16x16\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        def broadcast():\n            cond = np.random.choice([1, 0], (1, 1)).astype(np.float64)\n            x = np.random.randint(0, 6, (2, 2)).astype(np.float64)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.float64)\n            \n            z = np.where(cond, x, y).astype(x.dtype)\n\n            cond = Tensor(Dtype.FP16x16, cond.shape, to_fp(\n                cond.flatten(), FixedImpl.FP16x16))\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.FP16x16, z.shape,  to_fp(\n                z.flatten(), FixedImpl.FP16x16))\n\n            name = \"where_fp16x16_broadcast\"\n            make_test([cond, x, y], z, \"input_0.where(@input_1,@input_2)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/node/xor.py",
        "content": "import numpy as np\nfrom nodegen.node import RunAll\nfrom ..helpers import make_test, to_fp, Tensor, Dtype, FixedImpl\n\n\nclass Xor(RunAll):\n\n    @staticmethod\n    def xor_u32():\n        def default():\n            x = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            y = np.random.randint(0, 6, (3, 3, 3)).astype(np.uint32)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_u32\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(0, 6, (2, 2)).astype(np.uint32)\n            y = np.random.randint(0, 6, (1, 2)).astype(np.uint32)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.U32, x.shape, x.flatten())\n            y = Tensor(Dtype.U32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_u32_broadcast\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def xor_i32():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int32)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_i32\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int32)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int32)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.I32, x.shape, x.flatten())\n            y = Tensor(Dtype.I32, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_i32_broadcast\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def xor_i8():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.int8)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_i8\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.int8)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.int8)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.I8, x.shape, x.flatten())\n            y = Tensor(Dtype.I8, y.shape, y.flatten())\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_i8_broadcast\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def xor_fp8x23():\n        def default():\n            x = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            y = np.random.randint(-3, 3, (3, 3, 3)).astype(np.float64)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_fp8x23\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.FP8x23, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP8x23))\n            y = Tensor(Dtype.FP8x23, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP8x23))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_fp8x23_broadcast\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        default()\n        broadcast()\n\n    @staticmethod\n    def xor_fp16x16():\n        def default():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_fp16x16\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        def broadcast():\n            x = np.random.randint(-3, 3, (2, 2)).astype(np.float64)\n            y = np.random.randint(-3, 3, (1, 2)).astype(np.float64)\n            z = np.logical_xor(x, y)\n\n            x = Tensor(Dtype.FP16x16, x.shape, to_fp(\n                x.flatten(), FixedImpl.FP16x16))\n            y = Tensor(Dtype.FP16x16, y.shape,  to_fp(\n                y.flatten(), FixedImpl.FP16x16))\n            z = Tensor(Dtype.U32, z.shape, z.flatten())\n\n            name = \"xor_fp16x16_broadcast\"\n            make_test([x, y], z, \"input_0.xor(@input_1)\", name)\n\n        default()\n        broadcast()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "nodegen/test_list.py",
        "content": "import os\nimport glob\nimport subprocess\n\n# Directory path where Python files/modules are located\ndirectory_path = 'nodegen/node/'\n\n# Get all files in the directory\nall_files = os.listdir(directory_path)\n\n# Filter Python files using glob and '*.py' pattern\npython_files = [file[:-3] for file in all_files if file.endswith('.py')]\n\n# Print the names of Python files/modules\ncommand = 'python --version'\nos.system(command)"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/lib.cairo",
        "content": "mod operators;\nmod numbers;\nmod utils;\nmod test_helper;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers.cairo",
        "content": "mod fixed_point;\nmod complex_number;\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{ONE as ONE_fp8x23};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{ONE as ONE_fp16x16};\nuse orion::numbers::fixed_point::implementations::fp64x64::core::{ONE as ONE_fp64x64};\nuse orion::numbers::fixed_point::implementations::fp32x32::core::{ONE as ONE_fp32x32};\n\n// Common methods from Fixed Point and Signed Integers.\ntrait NumberTrait<T, MAG> {\n    fn new(mag: MAG, sign: bool) -> T;\n    fn new_unscaled(mag: MAG, sign: bool) -> T;\n    fn from_felt(val: felt252) -> T;\n    fn abs(self: T) -> T;\n    fn neg(self: T) -> T;\n    fn ceil(self: T) -> T;\n    fn exp(self: T) -> T;\n    fn exp2(self: T) -> T;\n    fn floor(self: T) -> T;\n    fn ln(self: T) -> T;\n    fn log2(self: T) -> T;\n    fn log10(self: T) -> T;\n    fn pow(self: T, b: T) -> T;\n    fn round(self: T) -> T;\n    fn sqrt(self: T) -> T;\n    fn acos(self: T) -> T;\n    fn asin(self: T) -> T;\n    fn atan(self: T) -> T;\n    fn cos(self: T) -> T;\n    fn sin(self: T) -> T;\n    fn tan(self: T) -> T;\n    fn acosh(self: T) -> T;\n    fn asinh(self: T) -> T;\n    fn atanh(self: T) -> T;\n    fn cosh(self: T) -> T;\n    fn sinh(self: T) -> T;\n    fn tanh(self: T) -> T;\n    fn zero() -> T;\n    fn is_zero(self: T) -> bool;\n    fn half() -> T;\n    fn one() -> T;\n    fn is_one(self: T) -> bool;\n    fn neg_one() -> T;\n    fn min_value() -> T;\n    fn max_value() -> T;\n    fn min(self: T, other: T) -> T;\n    fn max(self: T, other: T) -> T;\n    fn mag(self: T) -> MAG;\n    fn is_neg(self: T) -> bool;\n    fn xor(lhs: T, rhs: T) -> bool;\n    fn or(lhs: T, rhs: T) -> bool;\n    fn sign(self: T) -> T;\n    fn and(lhs: T, rhs: T) -> bool;\n    fn where(self: T, x: T, y: T) -> T;\n    fn NaN() -> T;\n    fn is_nan(self: T) -> bool;\n    fn INF() -> T;\n    fn is_inf(self: T) -> bool;\n    fn is_pos_inf(self: T) -> bool;\n    fn is_neg_inf(self: T) -> bool;\n    fn bitwise_and(lhs: T, rhs: T) -> T;\n    fn bitwise_xor(lhs: T, rhs: T) -> T;\n    fn bitwise_or(lhs: T, rhs: T) -> T;\n    fn add(lhs: T, rhs: T) -> T;\n    fn sub(lhs: T, rhs: T) -> T;\n}\n\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{\n    FP8x23Impl, FP8x23, FP8x23Add, FP8x23Sub\n};\nuse orion::numbers::fixed_point::implementations::fp8x23::math::core as core_fp8x23;\nuse orion::numbers::fixed_point::implementations::fp8x23::math::comp as comp_fp8x23;\n\nimpl FP8x23Number of NumberTrait<FP8x23, u32> {\n    fn new(mag: u32, sign: bool) -> FP8x23 {\n        FP8x23Impl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u32, sign: bool) -> FP8x23 {\n        FP8x23Impl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP8x23 {\n        FP8x23Impl::from_felt(val)\n    }\n\n    fn ceil(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::ceil(self)\n    }\n\n    fn exp(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::exp(self)\n    }\n\n    fn exp2(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::exp2(self)\n    }\n\n    fn floor(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::floor(self)\n    }\n\n    fn ln(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::ln(self)\n    }\n\n    fn log2(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::log2(self)\n    }\n\n    fn log10(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::log10(self)\n    }\n\n    fn pow(self: FP8x23, b: FP8x23) -> FP8x23 {\n        FP8x23Impl::pow(self, b)\n    }\n\n    fn round(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::round(self)\n    }\n\n    fn sqrt(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::sqrt(self)\n    }\n\n    fn acos(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::acos(self)\n    }\n\n    fn asin(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::asin(self)\n    }\n\n    fn atan(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::atan(self)\n    }\n\n    fn cos(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::cos(self)\n    }\n\n    fn sin(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::sin(self)\n    }\n\n    fn tan(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::tan(self)\n    }\n\n    fn acosh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::acosh(self)\n    }\n\n    fn asinh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::asinh(self)\n    }\n\n    fn atanh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::atanh(self)\n    }\n\n    fn cosh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::cosh(self)\n    }\n\n    fn sinh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::sinh(self)\n    }\n\n    fn tanh(self: FP8x23) -> FP8x23 {\n        FP8x23Impl::tanh(self)\n    }\n\n    fn zero() -> FP8x23 {\n        FP8x23Impl::ZERO()\n    }\n    fn is_zero(self: FP8x23) -> bool {\n        core_fp8x23::eq(@self, @FP8x23Impl::ZERO())\n    }\n\n    fn half() -> FP8x23 {\n        FP8x23Impl::HALF()\n    }\n\n    fn one() -> FP8x23 {\n        FP8x23Impl::ONE()\n    }\n\n    fn neg_one() -> FP8x23 {\n        FP8x23 { mag: core_fp8x23::ONE, sign: true }\n    }\n\n    fn is_one(self: FP8x23) -> bool {\n        core_fp8x23::eq(@self, @FP8x23Impl::ONE())\n    }\n\n    fn abs(self: FP8x23) -> FP8x23 {\n        core_fp8x23::abs(self)\n    }\n\n    fn neg(self: FP8x23) -> FP8x23 {\n        core_fp8x23::neg(self)\n    }\n\n    fn min_value() -> FP8x23 {\n        FP8x23 { mag: core_fp8x23::MAX, sign: true }\n    }\n\n    fn max_value() -> FP8x23 {\n        FP8x23 { mag: core_fp8x23::MAX, sign: false }\n    }\n\n    fn min(self: FP8x23, other: FP8x23) -> FP8x23 {\n        comp_fp8x23::min(self, other)\n    }\n\n    fn max(self: FP8x23, other: FP8x23) -> FP8x23 {\n        comp_fp8x23::max(self, other)\n    }\n\n    fn mag(self: FP8x23) -> u32 {\n        self.mag\n    }\n\n    fn is_neg(self: FP8x23) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP8x23, rhs: FP8x23) -> bool {\n        comp_fp8x23::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP8x23, rhs: FP8x23) -> bool {\n        comp_fp8x23::or(lhs, rhs)\n    }\n\n    fn sign(self: FP8x23) -> FP8x23 {\n        core_fp8x23::sign(self)\n    }\n\n    fn and(lhs: FP8x23, rhs: FP8x23) -> bool {\n        comp_fp8x23::and(lhs, rhs)\n    }\n\n    fn where(self: FP8x23, x: FP8x23, y: FP8x23) -> FP8x23 {\n        comp_fp8x23::where(self, x, y)\n    }\n\n    fn NaN() -> FP8x23 {\n        FP8x23Impl::NaN()\n    }\n\n    fn is_nan(self: FP8x23) -> bool {\n        FP8x23Impl::is_nan(self)\n    }\n\n    fn INF() -> FP8x23 {\n        FP8x23Impl::INF()\n    }\n\n    fn is_inf(self: FP8x23) -> bool {\n        FP8x23Impl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP8x23) -> bool {\n        FP8x23Impl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP8x23) -> bool {\n        FP8x23Impl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        comp_fp8x23::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        comp_fp8x23::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        comp_fp8x23::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        FP8x23Add::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        FP8x23Sub::sub(lhs, rhs)\n    }\n}\n\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    FP8x23WImpl, FP8x23W, FP8x23WAdd, FP8x23WSub\n};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::core as core_fp8x23wide;\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::comp as comp_fp8x23wide;\n\nimpl FP8x23WNumber of NumberTrait<FP8x23W, u64> {\n    fn new(mag: u64, sign: bool) -> FP8x23W {\n        FP8x23WImpl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP8x23W {\n        FP8x23WImpl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP8x23W {\n        FP8x23WImpl::from_felt(val)\n    }\n\n    fn ceil(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::ceil(self)\n    }\n\n    fn exp(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::exp(self)\n    }\n\n    fn exp2(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::exp2(self)\n    }\n\n    fn floor(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::floor(self)\n    }\n\n    fn ln(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::ln(self)\n    }\n\n    fn log2(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::log2(self)\n    }\n\n    fn log10(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::log10(self)\n    }\n\n    fn pow(self: FP8x23W, b: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::pow(self, b)\n    }\n\n    fn round(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::round(self)\n    }\n\n    fn sqrt(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::sqrt(self)\n    }\n\n    fn acos(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::acos(self)\n    }\n\n    fn asin(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::asin(self)\n    }\n\n    fn atan(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::atan(self)\n    }\n\n    fn cos(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::cos(self)\n    }\n\n    fn sin(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::sin(self)\n    }\n\n    fn tan(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::tan(self)\n    }\n\n    fn acosh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::acosh(self)\n    }\n\n    fn asinh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::asinh(self)\n    }\n\n    fn atanh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::atanh(self)\n    }\n\n    fn cosh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::cosh(self)\n    }\n\n    fn sinh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::sinh(self)\n    }\n\n    fn tanh(self: FP8x23W) -> FP8x23W {\n        FP8x23WImpl::tanh(self)\n    }\n\n    fn zero() -> FP8x23W {\n        FP8x23WImpl::ZERO()\n    }\n    fn is_zero(self: FP8x23W) -> bool {\n        core_fp8x23wide::eq(@self, @FP8x23WImpl::ZERO())\n    }\n\n    fn half() -> FP8x23W {\n        FP8x23WImpl::HALF()\n    }\n\n    fn one() -> FP8x23W {\n        FP8x23WImpl::ONE()\n    }\n\n    fn neg_one() -> FP8x23W {\n        FP8x23W { mag: core_fp8x23wide::ONE, sign: true }\n    }\n\n    fn is_one(self: FP8x23W) -> bool {\n        core_fp8x23wide::eq(@self, @FP8x23WImpl::ONE())\n    }\n\n    fn abs(self: FP8x23W) -> FP8x23W {\n        core_fp8x23wide::abs(self)\n    }\n\n    fn neg(self: FP8x23W) -> FP8x23W {\n        core_fp8x23wide::neg(self)\n    }\n\n    fn min_value() -> FP8x23W {\n        FP8x23W { mag: core_fp8x23wide::MAX, sign: true }\n    }\n\n    fn max_value() -> FP8x23W {\n        FP8x23W { mag: core_fp8x23wide::MAX, sign: false }\n    }\n\n    fn min(self: FP8x23W, other: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::min(self, other)\n    }\n\n    fn max(self: FP8x23W, other: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::max(self, other)\n    }\n\n    fn mag(self: FP8x23W) -> u64 {\n        self.mag\n    }\n\n    fn is_neg(self: FP8x23W) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        comp_fp8x23wide::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        comp_fp8x23wide::or(lhs, rhs)\n    }\n\n    fn sign(self: FP8x23W) -> FP8x23W {\n        core_fp8x23wide::sign(self)\n    }\n\n    fn and(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        comp_fp8x23wide::and(lhs, rhs)\n    }\n\n    fn where(self: FP8x23W, x: FP8x23W, y: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::where(self, x, y)\n    }\n\n    fn NaN() -> FP8x23W {\n        FP8x23WImpl::NaN()\n    }\n\n    fn is_nan(self: FP8x23W) -> bool {\n        FP8x23WImpl::is_nan(self)\n    }\n\n    fn INF() -> FP8x23W {\n        FP8x23WImpl::INF()\n    }\n\n    fn is_inf(self: FP8x23W) -> bool {\n        FP8x23WImpl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP8x23W) -> bool {\n        FP8x23WImpl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP8x23W) -> bool {\n        FP8x23WImpl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        comp_fp8x23wide::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        FP8x23WAdd::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        FP8x23WSub::sub(lhs, rhs)\n    }\n}\n\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    FP16x16Impl, FP16x16, FP16x16Add, FP16x16Sub\n};\nuse orion::numbers::fixed_point::implementations::fp16x16::math::core as core_fp16x16;\nuse orion::numbers::fixed_point::implementations::fp16x16::math::comp as comp_fp16x16;\n\nimpl FP16x16Number of NumberTrait<FP16x16, u32> {\n    fn new(mag: u32, sign: bool) -> FP16x16 {\n        FP16x16Impl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u32, sign: bool) -> FP16x16 {\n        FP16x16Impl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP16x16 {\n        FP16x16Impl::from_felt(val)\n    }\n\n    fn ceil(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::ceil(self)\n    }\n\n    fn exp(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::exp(self)\n    }\n\n    fn exp2(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::exp2(self)\n    }\n\n    fn floor(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::floor(self)\n    }\n\n    fn ln(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::ln(self)\n    }\n\n    fn log2(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::log2(self)\n    }\n\n    fn log10(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::log10(self)\n    }\n\n    fn pow(self: FP16x16, b: FP16x16) -> FP16x16 {\n        FP16x16Impl::pow(self, b)\n    }\n\n    fn round(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::round(self)\n    }\n\n    fn sqrt(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::sqrt(self)\n    }\n\n    fn acos(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::acos(self)\n    }\n\n    fn asin(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::asin(self)\n    }\n\n    fn atan(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::atan(self)\n    }\n\n    fn cos(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::cos(self)\n    }\n\n    fn sin(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::sin(self)\n    }\n\n    fn tan(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::tan(self)\n    }\n\n    fn acosh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::acosh(self)\n    }\n\n    fn asinh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::asinh(self)\n    }\n\n    fn atanh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::atanh(self)\n    }\n\n    fn cosh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::cosh(self)\n    }\n\n    fn sinh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::sinh(self)\n    }\n\n    fn tanh(self: FP16x16) -> FP16x16 {\n        FP16x16Impl::tanh(self)\n    }\n\n    fn zero() -> FP16x16 {\n        FP16x16Impl::ZERO()\n    }\n    fn is_zero(self: FP16x16) -> bool {\n        core_fp16x16::eq(@self, @FP16x16Impl::ZERO())\n    }\n\n    fn half() -> FP16x16 {\n        FP16x16Impl::HALF()\n    }\n\n    fn one() -> FP16x16 {\n        FP16x16Impl::ONE()\n    }\n\n    fn neg_one() -> FP16x16 {\n        FP16x16 { mag: core_fp16x16::ONE, sign: true }\n    }\n\n    fn is_one(self: FP16x16) -> bool {\n        core_fp16x16::eq(@self, @FP16x16Impl::ONE())\n    }\n\n    fn abs(self: FP16x16) -> FP16x16 {\n        core_fp16x16::abs(self)\n    }\n\n    fn neg(self: FP16x16) -> FP16x16 {\n        core_fp16x16::neg(self)\n    }\n\n    fn min_value() -> FP16x16 {\n        FP16x16 { mag: core_fp16x16::MAX, sign: true }\n    }\n\n    fn max_value() -> FP16x16 {\n        FP16x16 { mag: core_fp16x16::MAX, sign: false }\n    }\n\n    fn min(self: FP16x16, other: FP16x16) -> FP16x16 {\n        comp_fp16x16::min(self, other)\n    }\n\n    fn max(self: FP16x16, other: FP16x16) -> FP16x16 {\n        comp_fp16x16::max(self, other)\n    }\n\n    fn mag(self: FP16x16) -> u32 {\n        self.mag\n    }\n\n    fn is_neg(self: FP16x16) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP16x16, rhs: FP16x16) -> bool {\n        comp_fp16x16::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP16x16, rhs: FP16x16) -> bool {\n        comp_fp16x16::or(lhs, rhs)\n    }\n\n    fn sign(self: FP16x16) -> FP16x16 {\n        core_fp16x16::sign(self)\n    }\n\n    fn and(lhs: FP16x16, rhs: FP16x16) -> bool {\n        comp_fp16x16::and(lhs, rhs)\n    }\n\n    fn where(self: FP16x16, x: FP16x16, y: FP16x16) -> FP16x16 {\n        comp_fp16x16::where(self, x, y)\n    }\n\n    fn NaN() -> FP16x16 {\n        FP16x16Impl::NaN()\n    }\n\n    fn is_nan(self: FP16x16) -> bool {\n        FP16x16Impl::is_nan(self)\n    }\n\n    fn INF() -> FP16x16 {\n        FP16x16Impl::INF()\n    }\n\n    fn is_inf(self: FP16x16) -> bool {\n        FP16x16Impl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP16x16) -> bool {\n        FP16x16Impl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP16x16) -> bool {\n        FP16x16Impl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        comp_fp16x16::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        comp_fp16x16::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        comp_fp16x16::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        FP16x16Add::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        FP16x16Sub::sub(lhs, rhs)\n    }\n}\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    FP16x16WImpl, FP16x16W, FP16x16WAdd, FP16x16WSub\n};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::core as core_fp16x16wide;\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::comp as comp_fp16x16wide;\n\nimpl FP16x16WNumber of NumberTrait<FP16x16W, u64> {\n    fn new(mag: u64, sign: bool) -> FP16x16W {\n        FP16x16WImpl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP16x16W {\n        FP16x16WImpl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP16x16W {\n        FP16x16WImpl::from_felt(val)\n    }\n\n    fn ceil(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::ceil(self)\n    }\n\n    fn exp(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::exp(self)\n    }\n\n    fn exp2(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::exp2(self)\n    }\n\n    fn floor(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::floor(self)\n    }\n\n    fn ln(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::ln(self)\n    }\n\n    fn log2(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::log2(self)\n    }\n\n    fn log10(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::log10(self)\n    }\n\n    fn pow(self: FP16x16W, b: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::pow(self, b)\n    }\n\n    fn round(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::round(self)\n    }\n\n    fn sqrt(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::sqrt(self)\n    }\n\n    fn acos(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::acos(self)\n    }\n\n    fn asin(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::asin(self)\n    }\n\n    fn atan(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::atan(self)\n    }\n\n    fn cos(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::cos(self)\n    }\n\n    fn sin(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::sin(self)\n    }\n\n    fn tan(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::tan(self)\n    }\n\n    fn acosh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::acosh(self)\n    }\n\n    fn asinh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::asinh(self)\n    }\n\n    fn atanh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::atanh(self)\n    }\n\n    fn cosh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::cosh(self)\n    }\n\n    fn sinh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::sinh(self)\n    }\n\n    fn tanh(self: FP16x16W) -> FP16x16W {\n        FP16x16WImpl::tanh(self)\n    }\n\n    fn zero() -> FP16x16W {\n        FP16x16WImpl::ZERO()\n    }\n    fn is_zero(self: FP16x16W) -> bool {\n        core_fp16x16wide::eq(@self, @FP16x16WImpl::ZERO())\n    }\n\n    fn half() -> FP16x16W {\n        FP16x16WImpl::HALF()\n    }\n\n    fn one() -> FP16x16W {\n        FP16x16WImpl::ONE()\n    }\n\n    fn neg_one() -> FP16x16W {\n        FP16x16W { mag: core_fp16x16wide::ONE, sign: true }\n    }\n\n    fn is_one(self: FP16x16W) -> bool {\n        core_fp16x16wide::eq(@self, @FP16x16WImpl::ONE())\n    }\n\n    fn abs(self: FP16x16W) -> FP16x16W {\n        core_fp16x16wide::abs(self)\n    }\n\n    fn neg(self: FP16x16W) -> FP16x16W {\n        core_fp16x16wide::neg(self)\n    }\n\n    fn min_value() -> FP16x16W {\n        FP16x16W { mag: core_fp16x16wide::MAX, sign: true }\n    }\n\n    fn max_value() -> FP16x16W {\n        FP16x16W { mag: core_fp16x16wide::MAX, sign: false }\n    }\n\n    fn min(self: FP16x16W, other: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::min(self, other)\n    }\n\n    fn max(self: FP16x16W, other: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::max(self, other)\n    }\n\n    fn mag(self: FP16x16W) -> u64 {\n        self.mag\n    }\n\n    fn is_neg(self: FP16x16W) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        comp_fp16x16wide::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        comp_fp16x16wide::or(lhs, rhs)\n    }\n\n    fn sign(self: FP16x16W) -> FP16x16W {\n        core_fp16x16wide::sign(self)\n    }\n\n    fn and(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        comp_fp16x16wide::and(lhs, rhs)\n    }\n\n    fn where(self: FP16x16W, x: FP16x16W, y: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::where(self, x, y)\n    }\n\n    fn NaN() -> FP16x16W {\n        FP16x16WImpl::NaN()\n    }\n\n    fn is_nan(self: FP16x16W) -> bool {\n        FP16x16WImpl::is_nan(self)\n    }\n\n    fn INF() -> FP16x16W {\n        FP16x16WImpl::INF()\n    }\n\n    fn is_inf(self: FP16x16W) -> bool {\n        FP16x16WImpl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP16x16W) -> bool {\n        FP16x16WImpl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP16x16W) -> bool {\n        FP16x16WImpl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        comp_fp16x16wide::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        FP16x16WAdd::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        FP16x16WSub::sub(lhs, rhs)\n    }\n}\n\nuse orion::numbers::fixed_point::implementations::fp64x64::core::{\n    FP64x64Impl, FP64x64, FP64x64Add, FP64x64Sub\n};\nuse orion::numbers::fixed_point::implementations::fp64x64::{core as core_fp64x64};\nuse orion::numbers::fixed_point::implementations::fp64x64::comp as comp_fp64x64;\nuse cubit::f128 as fp64x64;\n\nimpl FP64x64Number of NumberTrait<FP64x64, u128> {\n    fn new(mag: u128, sign: bool) -> FP64x64 {\n        FP64x64Impl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u128, sign: bool) -> FP64x64 {\n        FP64x64Impl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP64x64 {\n        FP64x64Impl::from_felt(val)\n    }\n\n    fn ceil(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::ceil(self)\n    }\n\n    fn exp(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::exp(self)\n    }\n\n    fn exp2(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::exp2(self)\n    }\n\n    fn floor(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::floor(self)\n    }\n\n    fn ln(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::ln(self)\n    }\n\n    fn log2(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::log2(self)\n    }\n\n    fn log10(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::log10(self)\n    }\n\n    fn pow(self: FP64x64, b: FP64x64) -> FP64x64 {\n        FP64x64Impl::pow(self, b)\n    }\n\n    fn round(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::round(self)\n    }\n\n    fn sqrt(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::sqrt(self)\n    }\n\n    fn acos(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::acos(self)\n    }\n\n    fn asin(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::asin(self)\n    }\n\n    fn atan(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::atan(self)\n    }\n\n    fn cos(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::cos(self)\n    }\n\n    fn sin(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::sin(self)\n    }\n\n    fn tan(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::tan(self)\n    }\n\n    fn acosh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::acosh(self)\n    }\n\n    fn asinh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::asinh(self)\n    }\n\n    fn atanh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::atanh(self)\n    }\n\n    fn cosh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::cosh(self)\n    }\n\n    fn sinh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::sinh(self)\n    }\n\n    fn tanh(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::tanh(self)\n    }\n\n    fn zero() -> FP64x64 {\n        FP64x64Impl::ZERO()\n    }\n    fn is_zero(self: FP64x64) -> bool {\n        fp64x64::ops::eq(@self, @FP64x64Impl::ZERO())\n    }\n\n    fn half() -> FP64x64 {\n        FP64x64Impl::HALF()\n    }\n\n    fn one() -> FP64x64 {\n        FP64x64Impl::ONE()\n    }\n\n    fn neg_one() -> FP64x64 {\n        FP64x64 { mag: core_fp64x64::ONE, sign: true }\n    }\n\n    fn is_one(self: FP64x64) -> bool {\n        core_fp64x64::eq(@self, @FP64x64Impl::ONE())\n    }\n\n    fn abs(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::abs(self)\n    }\n\n    fn neg(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::neg(self)\n    }\n\n    fn min_value() -> FP64x64 {\n        FP64x64 { mag: core_fp64x64::MAX, sign: true }\n    }\n\n    fn max_value() -> FP64x64 {\n        FP64x64 { mag: core_fp64x64::MAX, sign: false }\n    }\n\n    fn min(self: FP64x64, other: FP64x64) -> FP64x64 {\n        fp64x64::comp::min(self, other)\n    }\n\n    fn max(self: FP64x64, other: FP64x64) -> FP64x64 {\n        fp64x64::comp::max(self, other)\n    }\n\n    fn mag(self: FP64x64) -> u128 {\n        self.mag\n    }\n\n    fn is_neg(self: FP64x64) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP64x64, rhs: FP64x64) -> bool {\n        comp_fp64x64::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP64x64, rhs: FP64x64) -> bool {\n        comp_fp64x64::or(lhs, rhs)\n    }\n\n    fn sign(self: FP64x64) -> FP64x64 {\n        FP64x64Impl::sign(self)\n    }\n\n    fn and(lhs: FP64x64, rhs: FP64x64) -> bool {\n        comp_fp64x64::and(lhs, rhs)\n    }\n\n    fn where(self: FP64x64, x: FP64x64, y: FP64x64) -> FP64x64 {\n        comp_fp64x64::where(self, x, y)\n    }\n\n    fn NaN() -> FP64x64 {\n        FP64x64Impl::NaN()\n    }\n\n    fn is_nan(self: FP64x64) -> bool {\n        FP64x64Impl::is_nan(self)\n    }\n\n    fn INF() -> FP64x64 {\n        FP64x64Impl::INF()\n    }\n\n    fn is_inf(self: FP64x64) -> bool {\n        FP64x64Impl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP64x64) -> bool {\n        FP64x64Impl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP64x64) -> bool {\n        FP64x64Impl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        comp_fp64x64::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        comp_fp64x64::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        comp_fp64x64::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        FP64x64Add::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        FP64x64Sub::sub(lhs, rhs)\n    }\n}\n\nuse orion::numbers::fixed_point::implementations::fp32x32::core::{\n    FP32x32Impl, FP32x32, FP32x32Add, FP32x32Sub\n};\nuse orion::numbers::fixed_point::implementations::fp32x32::core as core_fp32x32;\nuse orion::numbers::fixed_point::implementations::fp32x32::comp as comp_fp32x32;\nuse cubit::f64 as fp32x32;\n\nimpl FP32x32Number of NumberTrait<FP32x32, u64> {\n    fn new(mag: u64, sign: bool) -> FP32x32 {\n        FP32x32Impl::new(mag, sign)\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP32x32 {\n        FP32x32Impl::new_unscaled(mag, sign)\n    }\n\n    fn from_felt(val: felt252) -> FP32x32 {\n        FP32x32Impl::from_felt(val)\n    }\n\n    fn ceil(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::ceil(self)\n    }\n\n    fn exp(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::exp(self)\n    }\n\n    fn exp2(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::exp2(self)\n    }\n\n    fn floor(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::floor(self)\n    }\n\n    fn ln(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::ln(self)\n    }\n\n    fn log2(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::log2(self)\n    }\n\n    fn log10(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::log10(self)\n    }\n\n    fn pow(self: FP32x32, b: FP32x32) -> FP32x32 {\n        FP32x32Impl::pow(self, b)\n    }\n\n    fn round(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::round(self)\n    }\n\n    fn sqrt(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::sqrt(self)\n    }\n\n    fn acos(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::acos(self)\n    }\n\n    fn asin(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::asin(self)\n    }\n\n    fn atan(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::atan(self)\n    }\n\n    fn cos(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::cos(self)\n    }\n\n    fn sin(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::sin(self)\n    }\n\n    fn tan(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::tan(self)\n    }\n\n    fn acosh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::acosh(self)\n    }\n\n    fn asinh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::asinh(self)\n    }\n\n    fn atanh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::atanh(self)\n    }\n\n    fn cosh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::cosh(self)\n    }\n\n    fn sinh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::sinh(self)\n    }\n\n    fn tanh(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::tanh(self)\n    }\n\n    fn zero() -> FP32x32 {\n        FP32x32Impl::ZERO()\n    }\n    fn is_zero(self: FP32x32) -> bool {\n        fp32x32::ops::eq(@self, @FP32x32Impl::ZERO())\n    }\n\n    fn half() -> FP32x32 {\n        FP32x32Impl::HALF()\n    }\n\n    fn one() -> FP32x32 {\n        FP32x32Impl::ONE()\n    }\n\n    fn neg_one() -> FP32x32 {\n        FP32x32 { mag: core_fp32x32::ONE, sign: true }\n    }\n\n    fn is_one(self: FP32x32) -> bool {\n        core_fp32x32::eq(@self, @FP32x32Impl::ONE())\n    }\n\n    fn abs(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::abs(self)\n    }\n\n    fn neg(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::neg(self)\n    }\n\n    fn min_value() -> FP32x32 {\n        FP32x32 { mag: core_fp32x32::MAX, sign: true }\n    }\n\n    fn max_value() -> FP32x32 {\n        FP32x32 { mag: core_fp32x32::MAX, sign: false }\n    }\n\n    fn min(self: FP32x32, other: FP32x32) -> FP32x32 {\n        fp32x32::comp::min(self, other)\n    }\n\n    fn max(self: FP32x32, other: FP32x32) -> FP32x32 {\n        fp32x32::comp::max(self, other)\n    }\n\n    fn mag(self: FP32x32) -> u64 {\n        self.mag\n    }\n\n    fn is_neg(self: FP32x32) -> bool {\n        self.sign\n    }\n\n    fn xor(lhs: FP32x32, rhs: FP32x32) -> bool {\n        comp_fp32x32::xor(lhs, rhs)\n    }\n\n    fn or(lhs: FP32x32, rhs: FP32x32) -> bool {\n        comp_fp32x32::or(lhs, rhs)\n    }\n\n    fn sign(self: FP32x32) -> FP32x32 {\n        FP32x32Impl::sign(self)\n    }\n\n    fn and(lhs: FP32x32, rhs: FP32x32) -> bool {\n        comp_fp32x32::and(lhs, rhs)\n    }\n\n    fn where(self: FP32x32, x: FP32x32, y: FP32x32) -> FP32x32 {\n        comp_fp32x32::where(self, x, y)\n    }\n\n    fn NaN() -> FP32x32 {\n        FP32x32Impl::NaN()\n    }\n\n    fn is_nan(self: FP32x32) -> bool {\n        FP32x32Impl::is_nan(self)\n    }\n\n    fn INF() -> FP32x32 {\n        FP32x32Impl::INF()\n    }\n\n    fn is_inf(self: FP32x32) -> bool {\n        FP32x32Impl::is_inf(self)\n    }\n\n    fn is_pos_inf(self: FP32x32) -> bool {\n        FP32x32Impl::is_pos_inf(self)\n    }\n\n    fn is_neg_inf(self: FP32x32) -> bool {\n        FP32x32Impl::is_neg_inf(self)\n    }\n\n    fn bitwise_and(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        comp_fp32x32::bitwise_and(lhs, rhs)\n    }\n\n    fn bitwise_xor(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        comp_fp32x32::bitwise_xor(lhs, rhs)\n    }\n\n    fn bitwise_or(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        comp_fp32x32::bitwise_or(lhs, rhs)\n    }\n\n    fn add(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        FP32x32Add::add(lhs, rhs)\n    }\n\n    fn sub(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        FP32x32Sub::sub(lhs, rhs)\n    }\n}\n\nimpl I8Number of NumberTrait<i8, i8> {\n    fn new(mag: i8, sign: bool) -> i8 {\n        if sign {\n            return -mag;\n        }\n\n        mag\n    }\n\n    fn new_unscaled(mag: i8, sign: bool) -> i8 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: i8, b: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn zero() -> i8 {\n        0\n    }\n    fn is_zero(self: i8) -> bool {\n        self == 0\n    }\n\n    fn half() -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> i8 {\n        1\n    }\n\n    fn neg_one() -> i8 {\n        -1\n    }\n\n    fn is_one(self: i8) -> bool {\n        self == 1\n    }\n\n    fn abs(self: i8) -> i8 {\n        if self >= 0 {\n            self\n        } else {\n            self * -1_i8\n        }\n    }\n\n    fn neg(self: i8) -> i8 {\n        self * -1_i8\n    }\n\n    fn min_value() -> i8 {\n        -127\n    }\n\n    fn max_value() -> i8 {\n        127\n    }\n\n    fn min(self: i8, other: i8) -> i8 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: i8, other: i8) -> i8 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: i8) -> i8 {\n        self\n    }\n\n    fn is_neg(self: i8) -> bool {\n        self < 0\n    }\n\n    fn xor(lhs: i8, rhs: i8) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: i8, rhs: i8) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: i8) -> i8 {\n        if self == 0 {\n            0_i8\n        } else if self > 0 {\n            1_i8\n        } else {\n            -1_i8\n        }\n    }\n\n    fn and(lhs: i8, rhs: i8) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: i8, x: i8, y: i8) -> i8 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: i8) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> i8 {\n        127\n    }\n\n    fn is_inf(self: i8) -> bool {\n        self == 127 || self == -127\n    }\n\n    fn is_pos_inf(self: i8) -> bool {\n        self == 127\n    }\n\n    fn is_neg_inf(self: i8) -> bool {\n        self == -127\n    }\n\n    fn bitwise_and(lhs: i8, rhs: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: i8, rhs: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: i8, rhs: i8) -> i8 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: i8, rhs: i8) -> i8 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: i8, rhs: i8) -> i8 {\n        lhs - rhs\n    }\n}\n\nimpl I8Div of Div<i8> {\n    fn div(lhs: i8, rhs: i8) -> i8 {\n        assert(rhs != 0, 'divisor cannot be 0');\n\n        let mut lhs_positive = lhs;\n        let mut rhs_positive = rhs;\n\n        // making sure everything is positive\n        if lhs < 0 {\n            lhs_positive = lhs * -1;\n        }\n        if rhs < 0 {\n            rhs_positive = rhs * -1;\n        }\n\n        //felt252 plays role of a bridge for type casting\n        let lhs_felt: felt252 = lhs_positive.into();\n        let rhs_felt: felt252 = rhs_positive.into();\n        let lhs_u128: u128 = lhs_felt.try_into().unwrap();\n        let rhs_u128: u128 = rhs_felt.try_into().unwrap();\n        let mut result = lhs_u128 / rhs_u128;\n        let felt_result: felt252 = result.into();\n        let signed_int_result: i8 = felt_result.try_into().unwrap();\n\n        if lhs * rhs < 0 {\n            signed_int_result * -1\n        } else {\n            signed_int_result\n        }\n    }\n}\n\nimpl I8DivEq of DivEq<i8> {\n    #[inline(always)]\n    fn div_eq(ref self: i8, other: i8) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl I8IntoFP8x23 of Into<i8, FP8x23> {\n    fn into(self: i8) -> FP8x23 {\n        let number_sign: bool = self < 0;\n        let mut self_positive: i8 = self;\n\n        if number_sign {\n            self_positive = self_positive * -1_i8\n        }\n\n        let number_felt: felt252 = self_positive.into();\n        let number_u32: u32 = number_felt.try_into().unwrap();\n\n        FP8x23 { mag: number_u32 * ONE_fp8x23, sign: number_sign }\n    }\n}\n\nimpl I8IntoFP16x16 of Into<i8, FP16x16> {\n    fn into(self: i8) -> FP16x16 {\n        let number_sign: bool = self < 0;\n        let mut self_positive: i8 = self;\n\n        if number_sign {\n            self_positive = self_positive * -1_i8\n        }\n\n        let number_felt: felt252 = self_positive.into();\n        let number_u32: u32 = number_felt.try_into().unwrap();\n\n        FP16x16 { mag: number_u32 * ONE_fp16x16, sign: number_sign }\n    }\n}\n\nimpl I8IntoFP64x64 of Into<i8, FP64x64> {\n    fn into(self: i8) -> FP64x64 {\n        let number_sign: bool = self < 0;\n        let mut self_positive: i8 = self;\n\n        if number_sign {\n            self_positive = self_positive * -1_i8\n        }\n\n        let number_felt: felt252 = self_positive.into();\n        let number_u128: u128 = number_felt.try_into().unwrap();\n\n        FP64x64 { mag: number_u128 * ONE_fp64x64, sign: number_sign }\n    }\n}\n\nimpl I8IntoFP32x32 of Into<i8, FP32x32> {\n    fn into(self: i8) -> FP32x32 {\n        let number_sign: bool = self < 0;\n        let mut self_positive: i8 = self;\n\n        if number_sign {\n            self_positive = self_positive * -1_i8\n        }\n\n        let number_felt: felt252 = self_positive.into();\n        let number_u128: u64 = number_felt.try_into().unwrap();\n\n        FP32x32 { mag: number_u128 * ONE_fp32x32, sign: number_sign }\n    }\n}\n\nimpl I16Number of NumberTrait<i16, i16> {\n    fn new(mag: i16, sign: bool) -> i16 {\n        if sign {\n            return -mag;\n        }\n\n        mag\n    }\n\n    fn new_unscaled(mag: i16, sign: bool) -> i16 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: i16, b: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn zero() -> i16 {\n        0\n    }\n    fn is_zero(self: i16) -> bool {\n        self == 0\n    }\n\n    fn half() -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> i16 {\n        1\n    }\n\n    fn neg_one() -> i16 {\n        -1\n    }\n\n    fn is_one(self: i16) -> bool {\n        self == 1\n    }\n\n    fn abs(self: i16) -> i16 {\n        if self >= 0 {\n            self\n        } else {\n            self * -1_i16\n        }\n    }\n\n    fn neg(self: i16) -> i16 {\n        self * -1_i16\n    }\n\n    fn min_value() -> i16 {\n        -32767\n    }\n\n    fn max_value() -> i16 {\n        32767\n    }\n\n    fn min(self: i16, other: i16) -> i16 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: i16, other: i16) -> i16 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: i16) -> i16 {\n        self\n    }\n\n    fn is_neg(self: i16) -> bool {\n        self < 0\n    }\n\n    fn xor(lhs: i16, rhs: i16) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: i16, rhs: i16) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: i16) -> i16 {\n        if self == 0 {\n            0_i16\n        } else if self > 0 {\n            1_i16\n        } else {\n            -1_i16\n        }\n    }\n\n    fn and(lhs: i16, rhs: i16) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: i16, x: i16, y: i16) -> i16 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: i16) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> i16 {\n        32767\n    }\n\n    fn is_inf(self: i16) -> bool {\n        self == 32767 || self == -32767\n    }\n\n    fn is_pos_inf(self: i16) -> bool {\n        self == 32767\n    }\n\n    fn is_neg_inf(self: i16) -> bool {\n        self == -32767\n    }\n\n    fn bitwise_and(lhs: i16, rhs: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: i16, rhs: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: i16, rhs: i16) -> i16 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: i16, rhs: i16) -> i16 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: i16, rhs: i16) -> i16 {\n        lhs - rhs\n    }\n}\n\nimpl I16Div of Div<i16> {\n    fn div(lhs: i16, rhs: i16) -> i16 {\n        assert(rhs != 0, 'divisor cannot be 0');\n\n        let mut lhs_positive = lhs;\n        let mut rhs_positive = rhs;\n\n        // making sure everything is positive\n        if lhs < 0 {\n            lhs_positive = lhs * -1;\n        }\n        if rhs < 0 {\n            rhs_positive = rhs * -1;\n        }\n\n        //felt252 plays role of a bridge for type casting\n        let lhs_felt: felt252 = lhs_positive.into();\n        let rhs_felt: felt252 = rhs_positive.into();\n        let lhs_u128: u128 = lhs_felt.try_into().unwrap();\n        let rhs_u128: u128 = rhs_felt.try_into().unwrap();\n        let mut result = lhs_u128 / rhs_u128;\n        let felt_result: felt252 = result.into();\n        let signed_int_result: i16 = felt_result.try_into().unwrap();\n\n        if lhs * rhs < 0 {\n            signed_int_result * -1\n        } else {\n            signed_int_result\n        }\n    }\n}\n\nimpl I16DivEq of DivEq<i16> {\n    #[inline(always)]\n    fn div_eq(ref self: i16, other: i16) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl I32Number of NumberTrait<i32, i32> {\n    fn new(mag: i32, sign: bool) -> i32 {\n        if sign {\n            return -mag;\n        }\n\n        mag\n    }\n\n    fn new_unscaled(mag: i32, sign: bool) -> i32 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: i32, b: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn zero() -> i32 {\n        0\n    }\n    fn is_zero(self: i32) -> bool {\n        self == 0\n    }\n\n    fn half() -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> i32 {\n        1\n    }\n\n    fn neg_one() -> i32 {\n        -1\n    }\n\n    fn is_one(self: i32) -> bool {\n        self == 1\n    }\n\n    fn abs(self: i32) -> i32 {\n        if self >= 0 {\n            self\n        } else {\n            self * -1_i32\n        }\n    }\n\n    fn neg(self: i32) -> i32 {\n        self * -1_i32\n    }\n\n    fn min_value() -> i32 {\n        -2147483647\n    }\n\n    fn max_value() -> i32 {\n        2147483647\n    }\n\n    fn min(self: i32, other: i32) -> i32 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: i32, other: i32) -> i32 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: i32) -> i32 {\n        self\n    }\n\n    fn is_neg(self: i32) -> bool {\n        self < 0\n    }\n\n    fn xor(lhs: i32, rhs: i32) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: i32, rhs: i32) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: i32) -> i32 {\n        if self == 0 {\n            0_i32\n        } else if self > 0 {\n            1_i32\n        } else {\n            -1_i32\n        }\n    }\n\n    fn and(lhs: i32, rhs: i32) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: i32, x: i32, y: i32) -> i32 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: i32) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> i32 {\n        2147483647\n    }\n\n    fn is_inf(self: i32) -> bool {\n        self == 2147483647 || self == -2147483647\n    }\n\n    fn is_pos_inf(self: i32) -> bool {\n        self == 2147483647\n    }\n\n    fn is_neg_inf(self: i32) -> bool {\n        self == -2147483647\n    }\n\n    fn bitwise_and(lhs: i32, rhs: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: i32, rhs: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: i32, rhs: i32) -> i32 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: i32, rhs: i32) -> i32 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: i32, rhs: i32) -> i32 {\n        lhs - rhs\n    }\n}\n\nimpl I32Div of Div<i32> {\n    fn div(lhs: i32, rhs: i32) -> i32 {\n        assert(rhs != 0, 'divisor cannot be 0');\n\n        let mut lhs_positive = lhs;\n        let mut rhs_positive = rhs;\n\n        // making sure everything is positive\n        if lhs < 0 {\n            lhs_positive = lhs * -1;\n        }\n        if rhs < 0 {\n            rhs_positive = rhs * -1;\n        }\n\n        //felt252 plays role of a bridge for type casting\n        let lhs_felt: felt252 = lhs_positive.into();\n        let rhs_felt: felt252 = rhs_positive.into();\n        let lhs_u128: u128 = lhs_felt.try_into().unwrap();\n        let rhs_u128: u128 = rhs_felt.try_into().unwrap();\n        let mut result = lhs_u128 / rhs_u128;\n        let felt_result: felt252 = result.into();\n        let signed_int_result: i32 = felt_result.try_into().unwrap();\n\n        if lhs * rhs < 0 {\n            signed_int_result * -1\n        } else {\n            signed_int_result\n        }\n    }\n}\n\nimpl I32DivEq of DivEq<i32> {\n    #[inline(always)]\n    fn div_eq(ref self: i32, other: i32) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl I32IntoU32 of Into<i32, u32> {\n    fn into(self: i32) -> u32 {\n        let number_sign: bool = self < 0;\n        let mut self_positive: i32 = self;\n\n        if number_sign {\n            self_positive = self_positive * -1_i32\n        }\n\n        let number_felt: felt252 = self_positive.into();\n        let number_u32: u32 = number_felt.try_into().unwrap();\n\n        number_u32\n    }\n}\n\nimpl I64Number of NumberTrait<i64, i64> {\n    fn new(mag: i64, sign: bool) -> i64 {\n        if sign {\n            return -mag;\n        }\n\n        mag\n    }\n\n    fn new_unscaled(mag: i64, sign: bool) -> i64 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: i64, b: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn zero() -> i64 {\n        0\n    }\n    fn is_zero(self: i64) -> bool {\n        self == 0\n    }\n\n    fn half() -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> i64 {\n        1\n    }\n\n    fn neg_one() -> i64 {\n        -1\n    }\n\n    fn is_one(self: i64) -> bool {\n        self == 1\n    }\n\n    fn abs(self: i64) -> i64 {\n        if self >= 0 {\n            self\n        } else {\n            self * -1_i64\n        }\n    }\n\n    fn neg(self: i64) -> i64 {\n        self * -1_i64\n    }\n\n    fn min_value() -> i64 {\n        -9223372036854775807\n    }\n\n    fn max_value() -> i64 {\n        9223372036854775807\n    }\n\n    fn min(self: i64, other: i64) -> i64 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: i64, other: i64) -> i64 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: i64) -> i64 {\n        self\n    }\n\n    fn is_neg(self: i64) -> bool {\n        self < 0\n    }\n\n    fn xor(lhs: i64, rhs: i64) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: i64, rhs: i64) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: i64) -> i64 {\n        if self == 0 {\n            0_i64\n        } else if self > 0 {\n            1_i64\n        } else {\n            -1_i64\n        }\n    }\n\n    fn and(lhs: i64, rhs: i64) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: i64, x: i64, y: i64) -> i64 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: i64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> i64 {\n        9223372036854775807\n    }\n\n    fn is_inf(self: i64) -> bool {\n        self == 9223372036854775807 || self == -9223372036854775807\n    }\n\n    fn is_pos_inf(self: i64) -> bool {\n        self == 9223372036854775807\n    }\n\n    fn is_neg_inf(self: i64) -> bool {\n        self == -9223372036854775807\n    }\n\n    fn bitwise_and(lhs: i64, rhs: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: i64, rhs: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: i64, rhs: i64) -> i64 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: i64, rhs: i64) -> i64 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: i64, rhs: i64) -> i64 {\n        lhs - rhs\n    }\n}\n\nimpl I64Div of Div<i64> {\n    fn div(lhs: i64, rhs: i64) -> i64 {\n        assert(rhs != 0, 'divisor cannot be 0');\n\n        let mut lhs_positive = lhs;\n        let mut rhs_positive = rhs;\n\n        // making sure everything is positive\n        if lhs < 0 {\n            lhs_positive = lhs * -1;\n        }\n        if rhs < 0 {\n            rhs_positive = rhs * -1;\n        }\n\n        //felt252 plays role of a bridge for type casting\n        let lhs_felt: felt252 = lhs_positive.into();\n        let rhs_felt: felt252 = rhs_positive.into();\n        let lhs_u128: u128 = lhs_felt.try_into().unwrap();\n        let rhs_u128: u128 = rhs_felt.try_into().unwrap();\n        let mut result = lhs_u128 / rhs_u128;\n        let felt_result: felt252 = result.into();\n        let signed_int_result: i64 = felt_result.try_into().unwrap();\n\n        if lhs * rhs < 0 {\n            signed_int_result * -1\n        } else {\n            signed_int_result\n        }\n    }\n}\n\nimpl I64DivEq of DivEq<i64> {\n    #[inline(always)]\n    fn div_eq(ref self: i64, other: i64) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl I128Number of NumberTrait<i128, i128> {\n    fn new(mag: i128, sign: bool) -> i128 {\n        if sign {\n            return -mag;\n        }\n\n        mag\n    }\n\n    fn new_unscaled(mag: i128, sign: bool) -> i128 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: i128, b: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn zero() -> i128 {\n        0\n    }\n    fn is_zero(self: i128) -> bool {\n        self == 0\n    }\n\n    fn half() -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> i128 {\n        1\n    }\n\n    fn neg_one() -> i128 {\n        -1\n    }\n\n    fn is_one(self: i128) -> bool {\n        self == 1\n    }\n\n    fn abs(self: i128) -> i128 {\n        if self >= 0 {\n            self\n        } else {\n            self * -1_i128\n        }\n    }\n\n    fn neg(self: i128) -> i128 {\n        self * -1_i128\n    }\n\n    fn min_value() -> i128 {\n        -170141183460469231731687303715884105727\n    }\n\n    fn max_value() -> i128 {\n        170141183460469231731687303715884105727\n    }\n\n    fn min(self: i128, other: i128) -> i128 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: i128, other: i128) -> i128 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: i128) -> i128 {\n        self\n    }\n\n    fn is_neg(self: i128) -> bool {\n        self < 0\n    }\n\n    fn xor(lhs: i128, rhs: i128) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: i128, rhs: i128) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: i128) -> i128 {\n        if self == 0 {\n            0_i128\n        } else if self > 0 {\n            1_i128\n        } else {\n            -1_i128\n        }\n    }\n\n    fn and(lhs: i128, rhs: i128) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: i128, x: i128, y: i128) -> i128 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: i128) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> i128 {\n        170141183460469231731687303715884105727\n    }\n\n    fn is_inf(self: i128) -> bool {\n        self == 170141183460469231731687303715884105727\n            || self == -170141183460469231731687303715884105727\n    }\n\n    fn is_pos_inf(self: i128) -> bool {\n        self == 170141183460469231731687303715884105727\n    }\n\n    fn is_neg_inf(self: i128) -> bool {\n        self == -170141183460469231731687303715884105727\n    }\n\n    fn bitwise_and(lhs: i128, rhs: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: i128, rhs: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: i128, rhs: i128) -> i128 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: i128, rhs: i128) -> i128 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: i128, rhs: i128) -> i128 {\n        lhs - rhs\n    }\n}\n\nimpl I128Div of Div<i128> {\n    fn div(lhs: i128, rhs: i128) -> i128 {\n        assert(rhs != 0, 'divisor cannot be 0');\n\n        let mut lhs_positive = lhs;\n        let mut rhs_positive = rhs;\n\n        // making sure everything is positive\n        if lhs < 0 {\n            lhs_positive = lhs * -1;\n        }\n        if rhs < 0 {\n            rhs_positive = rhs * -1;\n        }\n\n        //felt252 plays role of a bridge for type casting\n        let lhs_felt: felt252 = lhs_positive.into();\n        let rhs_felt: felt252 = rhs_positive.into();\n        let lhs_u128: u128 = lhs_felt.try_into().unwrap();\n        let rhs_u128: u128 = rhs_felt.try_into().unwrap();\n        let mut result = lhs_u128 / rhs_u128;\n        let felt_result: felt252 = result.into();\n        let signed_int_result: i128 = felt_result.try_into().unwrap();\n\n        // assigning the sign and returning\n        if lhs * rhs < 0 {\n            signed_int_result * -1\n        } else {\n            signed_int_result\n        }\n    }\n}\n\nimpl I128DivEq of DivEq<i128> {\n    #[inline(always)]\n    fn div_eq(ref self: i128, other: i128) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl u32Number of NumberTrait<u32, u32> {\n    fn new(mag: u32, sign: bool) -> u32 {\n        mag\n    }\n\n    fn new_unscaled(mag: u32, sign: bool) -> u32 {\n        mag\n    }\n\n    fn from_felt(val: felt252) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp2(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn floor(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn log2(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn log10(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: u32, b: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn tan(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn atanh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n\n    fn zero() -> u32 {\n        0\n    }\n    fn is_zero(self: u32) -> bool {\n        self == 0\n    }\n\n    fn half() -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> u32 {\n        1\n    }\n\n    fn neg_one() -> u32 {\n        panic(array!['not supported'])\n    }\n\n    fn is_one(self: u32) -> bool {\n        self == 1\n    }\n\n    fn abs(self: u32) -> u32 {\n        self\n    }\n\n    fn neg(self: u32) -> u32 {\n        panic(array!['not supported'])\n    }\n\n    fn min_value() -> u32 {\n        0\n    }\n\n    fn max_value() -> u32 {\n        4294967295\n    }\n\n    fn min(self: u32, other: u32) -> u32 {\n        if self < other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn max(self: u32, other: u32) -> u32 {\n        if self > other {\n            self\n        } else {\n            other\n        }\n    }\n\n    fn mag(self: u32) -> u32 {\n        self\n    }\n\n    fn is_neg(self: u32) -> bool {\n        false\n    }\n\n    fn xor(lhs: u32, rhs: u32) -> bool {\n        if (lhs == 0 || rhs == 0) && lhs != rhs {\n            true\n        } else {\n            false\n        }\n    }\n\n    fn or(lhs: u32, rhs: u32) -> bool {\n        if lhs == 0 && rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn sign(self: u32) -> u32 {\n        panic(array!['not supported!'])\n    }\n\n    fn and(lhs: u32, rhs: u32) -> bool {\n        if lhs == 0 || rhs == 0 {\n            false\n        } else {\n            true\n        }\n    }\n\n    fn where(self: u32, x: u32, y: u32) -> u32 {\n        if self == 0 {\n            y\n        } else {\n            x\n        }\n    }\n\n    fn NaN() -> u32 {\n        4242424242\n    }\n\n    fn is_nan(self: u32) -> bool {\n        self == 4242424242\n    }\n\n    fn INF() -> u32 {\n        4294967295\n    }\n\n    fn is_inf(self: u32) -> bool {\n        self == 4294967295\n    }\n\n    fn is_pos_inf(self: u32) -> bool {\n        self == 4294967295\n    }\n\n    fn is_neg_inf(self: u32) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_and(lhs: u32, rhs: u32) -> u32 {\n        lhs & rhs\n    }\n\n    fn bitwise_xor(lhs: u32, rhs: u32) -> u32 {\n        lhs ^ rhs\n    }\n\n    fn bitwise_or(lhs: u32, rhs: u32) -> u32 {\n        lhs | rhs\n    }\n\n    fn add(lhs: u32, rhs: u32) -> u32 {\n        lhs + rhs\n    }\n\n    fn sub(lhs: u32, rhs: u32) -> u32 {\n        lhs - rhs\n    }\n}\n\n\nuse orion::numbers::complex_number::complex_trait::ComplexTrait;\nuse orion::numbers::complex_number::complex64::{\n    Complex64Impl, complex64, Complex64Add, Complex64Sub\n};\n\n\nimpl Complex64Number of NumberTrait<complex64, FP64x64> {\n    fn new(mag: FP64x64, sign: bool) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn new_unscaled(mag: FP64x64, sign: bool) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn from_felt(val: felt252) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: complex64) -> complex64 {\n        Complex64Impl::exp(self)\n    }\n\n    fn exp2(self: complex64) -> complex64 {\n        Complex64Impl::exp2(self)\n    }\n\n    fn floor(self: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn ln(self: complex64) -> complex64 {\n        Complex64Impl::ln(self)\n    }\n\n    fn log2(self: complex64) -> complex64 {\n        Complex64Impl::log2(self)\n    }\n\n    fn log10(self: complex64) -> complex64 {\n        Complex64Impl::log10(self)\n    }\n\n    fn pow(self: complex64, b: complex64) -> complex64 {\n        Complex64Impl::pow(self, b)\n    }\n\n    fn round(self: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: complex64) -> complex64 {\n        Complex64Impl::sqrt(self)\n    }\n\n    fn acos(self: complex64) -> complex64 {\n        Complex64Impl::acos(self)\n    }\n\n    fn asin(self: complex64) -> complex64 {\n        Complex64Impl::asin(self)\n    }\n\n    fn atan(self: complex64) -> complex64 {\n        Complex64Impl::atan(self)\n    }\n\n    fn cos(self: complex64) -> complex64 {\n        Complex64Impl::cos(self)\n    }\n\n    fn sin(self: complex64) -> complex64 {\n        Complex64Impl::sin(self)\n    }\n\n    fn tan(self: complex64) -> complex64 {\n        Complex64Impl::tan(self)\n    }\n\n    fn acosh(self: complex64) -> complex64 {\n        Complex64Impl::acosh(self)\n    }\n\n    fn asinh(self: complex64) -> complex64 {\n        Complex64Impl::asinh(self)\n    }\n\n    fn atanh(self: complex64) -> complex64 {\n        Complex64Impl::atanh(self)\n    }\n\n    fn cosh(self: complex64) -> complex64 {\n        Complex64Impl::cosh(self)\n    }\n\n    fn sinh(self: complex64) -> complex64 {\n        Complex64Impl::sinh(self)\n    }\n\n    fn tanh(self: complex64) -> complex64 {\n        Complex64Impl::tanh(self)\n    }\n\n    fn zero() -> complex64 {\n        Complex64Impl::zero()\n    }\n\n    fn is_zero(self: complex64) -> bool {\n        if self == Complex64Impl::zero() {\n            return true;\n        }\n\n        false\n    }\n\n    fn half() -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn one() -> complex64 {\n        Complex64Impl::one()\n    }\n\n    fn neg_one() -> complex64 {\n        Complex64Impl::new(FP64x64 { mag: core_fp64x64::ONE, sign: true }, FP64x64Impl::ZERO())\n    }\n\n    fn is_one(self: complex64) -> bool {\n        if self == Complex64Impl::one() {\n            return true;\n        }\n\n        false\n    }\n\n    fn abs(self: complex64) -> complex64 {\n        Complex64Impl::new(Complex64Impl::mag(self), FP64x64Impl::ZERO())\n    }\n\n    fn neg(self: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn min_value() -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn max_value() -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn min(self: complex64, other: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn max(self: complex64, other: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn mag(self: complex64) -> FP64x64 {\n        Complex64Impl::mag(self)\n    }\n\n    fn is_neg(self: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn xor(lhs: complex64, rhs: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn or(lhs: complex64, rhs: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn sign(self: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn and(lhs: complex64, rhs: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn where(self: complex64, x: complex64, y: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn NaN() -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn INF() -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn is_inf(self: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn is_pos_inf(self: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn is_neg_inf(self: complex64) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_and(lhs: complex64, rhs: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(lhs: complex64, rhs: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(lhs: complex64, rhs: complex64) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn add(lhs: complex64, rhs: complex64) -> complex64 {\n        Complex64Add::add(lhs, rhs)\n    }\n\n    fn sub(lhs: complex64, rhs: complex64) -> complex64 {\n        Complex64Sub::sub(lhs, rhs)\n    }\n}\n\nimpl U32IntoI32 of Into<u32, i32> {\n    fn into(self: u32) -> i32 {\n        let number_felt: felt252 = self.into();\n        let number_i32: i32 = number_felt.try_into().unwrap();\n\n        number_i32\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/complex_number.cairo",
        "content": "mod complex_trait;\nmod complex64;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/complex_number/complex64.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::complex_number::complex_trait::ComplexTrait;\nuse orion::numbers::{FP64x64, FP64x64Impl, FP32x32, FP32x32Impl, FixedTrait};\n\n// ====================== Complex 64 ======================\n\n// complex64 represents a complex number in the Cartesian form z = a + bi where a and b are Fixed Points FP64x64.\n// The real field holds the value of the real part.\n// The img field holds the value of the imaginary part.\n#[derive(Serde, Copy, Drop)]\nstruct complex64 {\n    real: FP64x64,\n    img: FP64x64,\n}\n\n// CONSTANTS for FP64x64\nconst PI: u128 = 57952155664616982739;\nconst HALF_PI: u128 = 28976077832308491370;\nconst TWO: u128 = 36893488147419103232;\nconst E: u128 = 50143449208471493718;\nconst HALF: u128 = 9223372036854775808;\n\nimpl Complex64Impl of ComplexTrait<complex64, FP64x64> {\n    fn new(real: FP64x64, img: FP64x64) -> complex64 {\n        complex64 { real, img }\n    }\n\n    fn real(self: complex64) -> FP64x64 {\n        self.real\n    }\n\n    fn img(self: complex64) -> FP64x64 {\n        self.img\n    }\n\n    fn conjugate(self: complex64) -> complex64 {\n        ComplexTrait::new(self.real, -self.img)\n    }\n\n    fn zero() -> complex64 {\n        complex64 { real: FixedTrait::ZERO(), img: FP64x64Impl::ZERO() }\n    }\n\n    fn one() -> complex64 {\n        complex64 { real: FP64x64Impl::ONE(), img: FP64x64Impl::ZERO() }\n    }\n\n    fn mag(self: complex64) -> FP64x64 {\n        let two = FP64x64Impl::new(TWO, false);\n\n        (self.real.pow(two) + self.img.pow(two)).sqrt()\n    }\n\n    fn arg(self: complex64) -> FP64x64 {\n        atan2(self.real, self.img)\n    }\n\n    fn exp(self: complex64) -> complex64 {\n        let real = self.real.exp() * self.img.cos();\n        let img = self.real.exp() * self.img.sin();\n\n        complex64 { real, img }\n    }\n\n    fn exp2(self: complex64) -> complex64 {\n        let two = complex64 { real: FP64x64Impl::new(TWO, false), img: FP64x64Impl::ZERO() };\n\n        two.pow(self)\n    }\n\n    fn sqrt(self: complex64) -> complex64 {\n        let x = self.real;\n        let y = self.img;\n        let two = FP64x64Impl::new(TWO, false);\n        let real = (((x.pow(two) + y.pow(two)).sqrt() + x) / two).sqrt();\n        let img = if y == FP64x64Impl::ZERO() {\n            FP64x64Impl::ZERO()\n        } else {\n            (((x.pow(two) + y.pow(two)).sqrt() - x) / two).sqrt()\n        };\n        let img = FP64x64Impl::new(img.mag, y.sign);\n\n        complex64 { real, img }\n    }\n\n    fn ln(self: complex64) -> complex64 {\n        let real = self.mag().ln();\n        let img = self.arg();\n\n        complex64 { real, img }\n    }\n\n    fn log2(self: complex64) -> complex64 {\n        let ln_2 = FP64x64Impl::new(12786309186476892720, false);\n        let ln = self.ln();\n\n        complex64 { real: (ln.real / ln_2), img: (ln.img / ln_2) }\n    }\n\n    fn log10(self: complex64) -> complex64 {\n        let ln_10 = FP64x64Impl::new(42475197399893398429, false);\n        let ln = self.ln();\n\n        complex64 { real: (ln.real / ln_10), img: (ln.img / ln_10) }\n    }\n\n    fn pow(self: complex64, b: complex64) -> complex64 {\n        let two = FP64x64Impl::new(TWO, false);\n        let x = self.real;\n        let y = self.img;\n\n        //z^2=(a^2-b^2)+2abi\n        if (b.real == two && b.img == FP64x64Impl::new(0, false)) {\n            let real = x.pow(two) - y.pow(two);\n            let img = two * x * y;\n            return complex64 { real, img };\n        }\n\n        //(a+bi)^n=r^n(cos(n\u03b8)+isin(n\u03b8))\n        if (b.img == FP64x64Impl::new(0, false)) {\n            let mag_pow_n = self.mag().pow(b.real);\n            let arg_mul_n = b.real * self.arg();\n            let real = mag_pow_n * arg_mul_n.cos();\n            let img = mag_pow_n * arg_mul_n.sin();\n            return complex64 { real, img };\n        }\n\n        //let z = (a+bi)  (a+bi)^(c+di)= e^(c * ln(mag(z)) - d arg(z)) * cos (c * arg(z) + d ln(mag(r))) + i * e^(c * ln(mag(z)) - d arg(z)) * cos (c * arg(z) + d ln(mag(r)))\n        //let A = e^(c * ln(mag(z)) - d arg(z)) and B = c * arg(z) + d ln(mag(r))\n        //(a+bi)^(c+di)= A * cos (B) + i * A * sin B\n        let A = FP64x64Impl::new(E, false).pow(b.real * self.mag().ln() - b.img * self.arg());\n        let B = b.real * self.arg() + b.img * self.mag().ln();\n        let real = A * B.cos();\n        let img = A * B.sin();\n\n        complex64 { real, img }\n    }\n\n    //cos(z) = cos(a+bi) = cos(a)cosh(b)-isin(a)sinh(b)\n    fn cos(self: complex64) -> complex64 {\n        let a = self.real;\n        let b = self.img;\n\n        complex64 {\n            real: FP64x64Impl::cos(a) * FP64x64Impl::cosh(b),\n            img: -FP64x64Impl::sin(a) * FP64x64Impl::sinh(b)\n        }\n    }\n\n    //sin(z) = sin(a+bi) = sin(a)cosh(b)+icos(a)sinh(b)\n    fn sin(self: complex64) -> complex64 {\n        let a = self.real;\n        let b = self.img;\n\n        complex64 {\n            real: FP64x64Impl::sin(a) * FP64x64Impl::cosh(b),\n            img: FP64x64Impl::cos(a) * FP64x64Impl::sinh(b)\n        }\n    }\n\n    //tan(z) = tan(a+bi) = sin(2a) / (cosh(2b) + cos(2a)) + i sinh(2b) / (cosh(2b) + cos(2a))\n    fn tan(self: complex64) -> complex64 {\n        let two = FP64x64Impl::new(TWO, false);\n        let a = self.real;\n        let b = self.img;\n        let den = FP64x64Impl::cosh(two * b) + FP64x64Impl::cos(two * a);\n\n        complex64 { real: FP64x64Impl::sin(two * a) / den, img: FP64x64Impl::sinh(two * b) / den }\n    }\n\n    //acos(z) = pi/2 + i ln (iz sqrt(1 - z**2))\n    fn acos(self: complex64) -> complex64 {\n        let pi = Complex64Impl::new(FP64x64Impl::new(PI, false), FP64x64Impl::ZERO());\n        let two = Complex64Impl::new(FP64x64Impl::new(TWO, false), FP64x64Impl::ZERO());\n        let i = Complex64Impl::new(FP64x64Impl::ZERO(), FP64x64Impl::ONE());\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let acos = pi / two\n            + i * Complex64Impl::ln(i * self + Complex64Impl::sqrt(one - (self.pow(two))));\n\n        acos\n    }\n\n    //asin(z) = - i ln (iz sqrt(1 - z**2))\n    fn asin(self: complex64) -> complex64 {\n        let two = Complex64Impl::new(FP64x64Impl::new(TWO, false), FP64x64Impl::ZERO());\n        let i = Complex64Impl::new(FP64x64Impl::ZERO(), FP64x64Impl::ONE());\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let asin = -i * Complex64Impl::ln(i * self + Complex64Impl::sqrt(one - (self.pow(two))));\n\n        asin\n    }\n\n    //atan(z) = 1/2 * i[ln (1 - iz) - ln(1 + iz)]\n    fn atan(self: complex64) -> complex64 {\n        let two = Complex64Impl::new(FP64x64Impl::new(TWO, false), FP64x64Impl::ZERO());\n        let i = Complex64Impl::new(FP64x64Impl::ZERO(), FP64x64Impl::ONE());\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let atan = one\n            / two\n            * i\n            * (Complex64Impl::ln(one - i * self) - Complex64Impl::ln(one + i * self));\n\n        atan\n    }\n\n    //acosh(z) = ln (z + sqrt(z + 1) * sqrt(z - 1)) \n    fn acosh(self: complex64) -> complex64 {\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let acosh = Complex64Impl::ln(\n            self + Complex64Impl::sqrt(self + one) * Complex64Impl::sqrt(self - one)\n        );\n\n        acosh\n    }\n\n    //asinh(z) = ln (z + sqrt(z**2 + 1)) \n    fn asinh(self: complex64) -> complex64 {\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let two = Complex64Impl::new(FP64x64Impl::new(TWO, false), FP64x64Impl::ZERO());\n        let asinh = Complex64Impl::ln(self + Complex64Impl::sqrt(one + (self.pow(two))));\n\n        asinh\n    }\n\n    //atanh(z) = 1/2 * [ln (1 + z) - ln(1 - z)]\n    fn atanh(self: complex64) -> complex64 {\n        let two = Complex64Impl::new(FP64x64Impl::new(TWO, false), FP64x64Impl::ZERO());\n        let one = Complex64Impl::new(FP64x64Impl::ONE(), FP64x64Impl::ZERO());\n        let atanh = (Complex64Impl::ln(one + self) - Complex64Impl::ln(one - self)) / two;\n\n        atanh\n    }\n\n    //acos(z) = acos(a+bi) = cosh a * cos b + i sinh a * sin b\n    fn cosh(self: complex64) -> complex64 {\n        let a = self.real;\n        let b = self.img;\n\n        complex64 {\n            real: FP64x64Impl::cosh(a) * FP64x64Impl::cos(b),\n            img: FP64x64Impl::sinh(a) * FP64x64Impl::sin(b)\n        }\n    }\n\n    //sinh(z) = sin(a+bi) = sinh(a)cos(b)+icosh(a)sin(b)\n    fn sinh(self: complex64) -> complex64 {\n        let a = self.real;\n        let b = self.img;\n\n        complex64 {\n            real: FP64x64Impl::sinh(a) * FP64x64Impl::cos(b),\n            img: FP64x64Impl::cosh(a) * FP64x64Impl::sin(b)\n        }\n    }\n\n    //tanh(z) = tan(a+bi) = sin(2a) / (cosh(2a) + cos(2b)) + i sinh(2b) / (cosh(2a) + cos(2b))\n    fn tanh(self: complex64) -> complex64 {\n        let two = FP64x64Impl::new(TWO, false);\n        let a = self.real;\n        let b = self.img;\n        let den = FP64x64Impl::cosh(two * a) + FP64x64Impl::cos(two * b);\n\n        complex64 { real: FP64x64Impl::sinh(two * a) / den, img: FP64x64Impl::sin(two * b) / den }\n    }\n\n\n    fn to_polar(self: complex64) -> (FP64x64, FP64x64) {\n        let mag = self.mag();\n        let arg = self.arg();\n\n        (mag, arg)\n    }\n\n    fn from_polar(mag: FP64x64, arg: FP64x64) -> complex64 {\n        let real = mag * arg.cos();\n        let img = mag * arg.sin();\n\n        complex64 { real, img }\n    }\n\n    fn reciprocal(self: complex64) -> complex64 {\n        let two = FP64x64Impl::new(TWO, false);\n        let x = self.real;\n        let y = self.img;\n\n        let real = x / (x.pow(two) + y.pow(two));\n        let img = -y / (x.pow(two) + y.pow(two));\n\n        complex64 { real, img }\n    }\n}\n\nfn atan2(x: FP64x64, y: FP64x64) -> FP64x64 {\n    let two = FP64x64Impl::new(TWO, false);\n    if (y != FP64x64Impl::ZERO() || x > FP64x64Impl::ZERO()) {\n        return two * (y / (x + (x.pow(two) + y.pow(two)).sqrt())).atan();\n    } else if x < FP64x64Impl::ZERO() {\n        return FP64x64Impl::new(PI, false);\n    } else {\n        panic(array!['undifined'])\n    }\n}\n\nimpl Complex64Print of PrintTrait<complex64> {\n    fn print(self: complex64) {\n        self.real.print();\n        '+'.print();\n        self.img.print();\n        'i'.print();\n    }\n}\n\n// Implements the Add trait for complex64.\nimpl Complex64Add of Add<complex64> {\n    fn add(lhs: complex64, rhs: complex64) -> complex64 {\n        complex64_add(lhs, rhs)\n    }\n}\n\n// Implements the AddEq trait for complex64.\nimpl Complex64AddEq of AddEq<complex64> {\n    #[inline(always)]\n    fn add_eq(ref self: complex64, other: complex64) {\n        self = Add::add(self, other);\n    }\n}\n\n// Implements the Sub trait for complex64.\nimpl Complex64Sub of Sub<complex64> {\n    fn sub(lhs: complex64, rhs: complex64) -> complex64 {\n        complex64_sub(lhs, rhs)\n    }\n}\n\n// Implements the SubEq trait for complex64.\nimpl Complex64SubEq of SubEq<complex64> {\n    #[inline(always)]\n    fn sub_eq(ref self: complex64, other: complex64) {\n        self = Sub::sub(self, other);\n    }\n}\n\n// Implements the Mul trait for complex64.\nimpl Complex64Mul of Mul<complex64> {\n    fn mul(lhs: complex64, rhs: complex64) -> complex64 {\n        complex64_mul(lhs, rhs)\n    }\n}\n\n// Implements the MulEq trait for complex64.\nimpl Complex64MulEq of MulEq<complex64> {\n    #[inline(always)]\n    fn mul_eq(ref self: complex64, other: complex64) {\n        self = Mul::mul(self, other);\n    }\n}\n\n// Implements the Div trait for complex64.\nimpl Complex64Div of Div<complex64> {\n    fn div(lhs: complex64, rhs: complex64) -> complex64 {\n        complex64_div(lhs, rhs)\n    }\n}\n\n// Implements the DivEq trait for complex64.\nimpl Complex64DivEq of DivEq<complex64> {\n    #[inline(always)]\n    fn div_eq(ref self: complex64, other: complex64) {\n        self = Div::div(self, other);\n    }\n}\n\n// Implements the PartialEq trait for complex64.\nimpl Complex64PartialEq of PartialEq<complex64> {\n    fn eq(lhs: @complex64, rhs: @complex64) -> bool {\n        complex64_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @complex64, rhs: @complex64) -> bool {\n        complex64_ne(*lhs, *rhs)\n    }\n}\n\n// Implements the Neg trait for complex64.\nimpl Complex64Neg of Neg<complex64> {\n    fn neg(a: complex64) -> complex64 {\n        complex64_neg(a)\n    }\n}\n\n/// Cf: ComplexTrait::new docstring\n\n// Adds two complex64 complex numbers.\n//\n// The sum of two complex numbers (x + yi) + (u + vi) = (x + u) + (y + v)i.\n// The result is a new complex number where the real part equals (x + u) and the imaginary part equals (y + v).\n// # Arguments\n// * `a` - The first complex64 to add.\n// * `b` - The second complex64 to add.\n// # Returns\n// * `complex64` - The sum of `a` and `b`.\nfn complex64_add(a: complex64, b: complex64) -> complex64 {\n    let real = a.real + b.real;\n    let img = a.img + b.img;\n\n    ComplexTrait::new(real, img)\n}\n\n// Subtracts complex64 complex numbers.\n//\n// The sum of two complex numbers (x + yi) - (u + vi) = (x - u) + (y - v)i.\n// The result is a new complex number where the real part equals (x - u) and the imaginary part equals (y - v).\n// # Arguments\n// * `a` - The first complex64 to subtract.\n// * `b` - The second complex64 to subtract.\n// # Returns\n// * `complex64` - The difference of `a` and `b`.\nfn complex64_sub(a: complex64, b: complex64) -> complex64 {\n    let real = a.real - b.real;\n    let img = a.img - b.img;\n\n    ComplexTrait::new(real, img)\n}\n\n// Multiplies two complex64 integers.\n// \n// The sum of two complex numbers (x + yi) * (u + vi) = (xu - yv) + (xv - yu)i.\n// The result is a new complex number where the real part equals (xu - yv) and the imaginary part equals (xv - yu).\n// # Arguments\n//\n// * `a` - The first complex64 to multiply.\n// * `b` - The second complex64 to multiply.\n//\n// # Returns\n//\n// * `complex64` - The product of `a` and `b`.\nfn complex64_mul(a: complex64, b: complex64) -> complex64 {\n    let real = a.real * b.real - a.img * b.img;\n    let img = a.real * b.img + a.img * b.real;\n\n    ComplexTrait::new(real, img)\n}\n\n// Divides the first complex64 by the second complex64.\n// # Arguments\n// * `a` - The complex64 dividend.\n// * `b` - The complex64 divisor.\n// # Returns\n// * `complex64` - The quotient of `a` and `b`.\nfn complex64_div(a: complex64, b: complex64) -> complex64 {\n    complex64_mul(a, b.reciprocal())\n}\n\n// Compares two complex64 complex numbers for equality.\n// # Arguments\n// * `a` - The first complex64 complex number to compare.\n// * `b` - The second complex64 complex number to compare.\n// # Returns\n// * `bool` - `true` if the two complex numbers are equal, `false` otherwise.\nfn complex64_eq(a: complex64, b: complex64) -> bool {\n    // Check if the two complex numbers have the same real part and the same imaginary part.\n    if a.real == b.real && a.img == b.img {\n        return true;\n    }\n\n    false\n}\n\n// Compares two complex64 complex numbers for inequality.\n// # Arguments\n// * `a` - The first complex64 complex number to compare.\n// * `b` - The second complex64 complex number to compare.\n// # Returns\n// * `bool` - `true` if the two complex numbers are not equal, `false` otherwise.\nfn complex64_ne(a: complex64, b: complex64) -> bool {\n    // The result is the inverse of the equal function.\n    !complex64_eq(a, b)\n}\n\n// Negates the given complex64 complex number.\n// # Arguments\n// * `x` - The complex64 complex number to negate.\n// # Returns\n// * `complex64` - The negation of `x`.\nfn complex64_neg(x: complex64) -> complex64 {\n    // The negation of an complex number is obtained by negating its real part and its imaginary part.\n    ComplexTrait::new(-x.real, -x.img)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/complex_number/complex_trait.cairo",
        "content": "/// Trait\n///\n/// new - Constructs a new `complex_number`.\n/// from_felt - Creates a new `complex_number` instance from two felt252 values.\n/// real - Returns the real part of the `complex_number`.\n/// img - Returns the imaginary part of the `complex_number`.\n/// conjugate - Returns the conjugate of the `complex_number`.\n/// zero - Returns the additive identity element zero.\n/// one - Returns the multiplicative identity element one.\n/// mag - Returns the magnitude of the `complex_number`.\n/// arg - Returns the argument of the `complex_number`.\n/// exp - Returns the value of e raised to the power of the `complex_number`.\n/// exp2 - Returns the value of 2 raised to the power of the `complex_number`.\n/// ln - Returns the natural logarithm of the `complex_number`.\n/// log2 - Returns the base-2 logarithm of the `complex_number`.\n/// log10 - Returns the base-10 logarithm of the `complex_number`.\n/// pow - Returns the result of raising the `complex_number` to the power of another `complex_number`.\n/// sqrt - Returns the value of the squre root of the `complex_number`.\n/// acos - Returns the  arccosine (inverse of cosine) of the `complex_number`.\n/// asin - Returns the  arcsine (inverse of sine) of the `complex_number`.\n/// atan - Returns the arctangent (inverse of tangent) of the input `complex_number`.\n/// cos - Returns the cosine of the `complex_number`.\n/// sin - Returns the sine of the `complex_number`.\n/// tan - Returns the tangent of the `complex_number`.\n/// acosh - Returns the value of the inverse hyperbolic cosine of the `complex_number`.\n/// asinh - Returns the value of the inverse hyperbolic sine of the `complex_number`.\n/// atanh - Returns the value of the inverse hyperbolic tangent of the `complex_number`.\n/// cosh - Returns the value of the hyperbolic cosine of the `complex_number`.\n/// sinh - Returns the value of the hyperbolic sine of the `complex_number`.\n/// tanh - Returns the value of the hyperbolic tangent of the `complex_number`.\n/// to_polar - Returns the polar coordinates of the `complex_number`.\n/// from_polar - Returns a `complex_number` from the polar coordinates of the `complex_number`.\n/// reciprocal - Returns a the reciprocal of the `complex_number`.\n///\ntrait ComplexTrait<T, F> {\n    /// # ComplexTrait::new\n    /// \n    /// ```rust\n    /// fn new(real: F, img: F) -> T;\n    /// ```\n    ///\n    /// ## Args\n    ///\n    /// * `real`(`F`) - The real part of the complex number.\n    /// * `img`(`F`) - The imaginary part of the complex number.\n    ///\n    /// ## Returns\n    /// \n    /// A new complex number.\n    /// \n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// \n    /// fn new_complex64_example() -> complex64 {\n    ///     ComplexTrait::new(FixedTrait::new(184467440737095516160, false), FixedTrait::new(18446744073709551616, false))\n    /// }\n    /// >>> {real: {mag: 184467440737095516160, sign: false}, im: {mag: 18446744073709551616, sign: false}} // 10 + i\n    /// ```\n    /// \n    fn new(real: F, img: F) -> T;\n    /// # ComplexTrait::real\n    /// \n    /// ```rust\n    /// fn real(self: T) -> F;\n    /// ```\n    /// \n    /// Returns the real part of a complex number. The complex number is represented in Cartesian form `z = a + bi` where `a` is the real part.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The complex number from which we want the real part.\n    ///\n    /// ## Returns\n    /// \n    /// A fixed point number `<F>`, representing the real part of `self` .\n    /// \n    /// ## Examples\n    /// \n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn real_complex64_example() -> FP64x64 {\n    ///     let z: complex64 = ComplexTrait::new(FixedTrait::new(184467440737095516160, false), FixedTrait::new(18446744073709551616, false));\n    ///     z.real()\n    /// }\n    /// >>> {mag: 184467440737095516160, sign: false} // 10\n    /// ```\n    /// \n    fn real(self: T) -> F;\n    /// # ComplexTrait::img\n    /// \n    /// ```rust\n    /// fn img(self: T) -> F;\n    /// ```\n    /// \n    /// Returns the imaginary part of a complex number. The complex number is represented in Cartesian form `z = a + bi` where `b` is the imaginary part.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The complex number from which we want the imaginary part.\n    ///\n    /// ## Returns\n    /// \n    /// A fixed point number `<F>`, representing the imaginary part of `self` .\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn img_complex64_example() -> FP64x64 {\n    ///     let z: complex64 = ComplexTrait::new(FixedTrait::new(184467440737095516160, false), FixedTrait::new(18446744073709551616, false));\n    ///     z.img()\n    /// }\n    /// >>> {mag: 18446744073709551616, sign: false} // 1\n    /// ```\n    /// \n    fn img(self: T) -> F;\n    /// # ComplexTrait::conjugate\n    /// \n    /// ```rust\n    /// fn conjugate(self: T) -> T;\n    /// ```\n    ///   \n    /// Returns the conjugate of a complex number. The complex number is represented in Cartesian form `z = a + bi`.\n    /// The conjugate of `z = a + bi` is `z\u0305 = a - bi`\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The complex number from which we want the conjugate.\n    ///\n    /// ## Returns\n    /// \n    /// A complex number `<T>`, representing the imaginary part of `self` .\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn conjugate_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(FixedTrait::new(184467440737095516160, false), FixedTrait::new(18446744073709551616, false));\n    ///     z.conjugate()\n    /// }\n    /// >>> {real: {mag: 184467440737095516160, sign: false}, im: {mag: 18446744073709551616, sign: true}} // 10 - i\n    /// ```\n    /// \n    fn conjugate(self: T) -> T;\n    /// # ComplexTrait::zero\n    /// \n    /// ```rust\n    /// fn zero(self: T) -> T;\n    /// ```\n    ///   \n    /// Returns the additive identity element zero\n    ///\n    /// ## Returns\n    /// \n    /// A complex number `<T>`, representing the additive identity element of the complex field `0`.\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn zero_complex64_example() -> complex64 {\n    ///     ComplexTrait::zero()\n    /// }\n    /// >>> {real: {mag: 0, sign: false}, im: {mag: 0, sign: false}} // 0 + 0i\n    /// ```\n    /// \n    fn zero() -> T;\n    /// # ComplexTrait::one\n    /// \n    /// ```rust\n    /// fn one(self: T) -> T;\n    /// ```\n    ///   \n    /// Returns the multiplicative identity element one\n    ///\n    /// ## Returns\n    /// \n    /// A complex number `<T>`, representing the multiplicative identity element of the complex field : `1 + 0i`. \n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn one_complex64_example() -> complex64 {\n    ///     ComplexTrait::one()\n    /// }\n    /// >>> {real: {mag: 18446744073709551616, sign: false}, im: {mag: 0, sign: false}} // 1 + 0i\n    /// ```\n    /// \n    fn one() -> T;\n    /// # ComplexTrait::mag\n    /// \n    /// ```rust\n    /// fn mag(self: T) -> F;\n    /// ```\n    ///\n    /// Returns the magnitude of the complex number\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number\n    ///\n    /// ## Returns\n    /// \n    /// A fixed point number '<F>', representing the magnitude of the complex number. \n    /// 'mag(z) = sqrt(a^2 + b^2)'.\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn mag_complex64_example() -> FP64x64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.mag()\n    /// }\n    /// >>> {mag: 0x2a30a6de7900000000, sign: false} // mag = 42.190046219457976\n    /// ```\n    /// \n    fn mag(self: T) -> F;\n    /// # ComplexTrait::arg\n    /// \n    /// ```rust\n    /// fn arg(self: T) -> F;\n    /// ```\n    ///\n    /// Returns the argument of the complex number\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number\n    ///\n    /// ## Returns\n    /// \n    /// A fixed point number '<F>', representing the argument of the complex number in radian. \n    /// 'arg(z) = atan2(b, a)'.\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn arg_complex64_example() -> FP64x64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.arg()\n    /// }\n    /// >>> {mag: 27224496882576083824, sign: false} // arg = 1.4758446204521403 (rad)\n    /// ```\n    /// \n    fn arg(self: T) -> F;\n    /// # ComplexTrait::exp\n    /// \n    /// ```rust\n    /// fn exp(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of e raised to the power of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number\n    ///\n    /// ## Returns\n    ///\n    /// The natural exponent of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn exp_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     ComplexTrait::exp(z)\n    /// }\n    /// >>> {real: {mag: 402848450095324460000, sign: true}, im: {mag: 923082101320478400000, sign: true}} // -21.838458238788455-50.04038098170736 i\n    /// ``` \n    ///\n    fn exp(self: T) -> T;\n    /// # ComplexTrait::exp2\n    /// \n    /// ```rust\n    /// fn exp2(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of 2 raised to the power of the complex number.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`T`) - The input complex number\n    ///\n    /// ## Returns\n    ///\n    /// The binary exponent of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn exp2_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     ComplexTrait::exp2(z)\n    /// }\n    /// >>> {real: {mag: 197471674372309809080, sign: true}, im: {mag: 219354605088992285353, sign: true}} // -10.70502356986 -11.89127707 i\n    /// ``` \n    ///\n    fn exp2(self: T) -> T;\n    /// # ComplexTrait::ln\n    ///\n    /// ```rust\n    /// fn ln(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the natural logarithm of the complex number.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns \n    ///\n    /// A complex number representing the natural logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn ln_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.ln()\n    /// }\n    /// >>> {real: {mag: 69031116512113681970, sign: false}, im: {mag: 27224496882576083824, sign: false}} // 3.7421843216430655 + 1.4758446204521403 i\n    ///  ```\n    ///\n    fn ln(self: T) -> T;\n    /// # ComplexTrait::log2\n    /// \n    /// ```rust\n    /// fn log2(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the base-2 logarithm of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the input is negative.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the binary logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn log2_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.log2()\n    /// }\n    /// >>> {real: {mag: 34130530934667840346, sign: false}, im: {mag: 26154904847122126193, sign: false}} // 1.85021986 + 1.41787163 i\n    ///  ```\n    /// \n    fn log2(self: T) -> T;\n    /// # ComplexTrait::log10\n    /// \n    /// ```rust\n    /// fn log10(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the base-10 logarithm of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the base 10 logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn log10_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.log10()\n    /// }\n    /// >>> {real: {mag: 10274314139629458970, sign: false}, im: {mag: 7873411322133748801, sign: false}} // 0.5569716761 + 0.4268218908 i\n    ///  ```\n    ///\n    fn log10(self: T) -> T;\n    /// # ComplexTrait::pow\n    /// \n    /// ```rust\n    /// fn pow(self: T, b: T) -> T;\n    /// ```\n    /// \n    /// Returns the result of raising the complex number to the power of another complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    /// * `b`(`T`) - The exponent complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the result of z^w.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::complex_trait::ComplexTrait;\n    /// use orion::numbers::complex_number::complex64::{TWO, complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn pow_2_complex64_example() -> complex64 {\n    ///     let two = ComplexTrait::new(FP64x64Impl::new(TWO, false),FP64x64Impl::new(0, false));\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.pow(two)\n    /// }\n    /// >>> {real: {mag: 32244908640844296224768, sign: true}, im: {mag: 6198106008766409342976, sign: false}} // -1748 + 336 i\n    /// \n    /// fn pow_w_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    /// \n    ///     let w: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(18446744073709551616, false)\n    ///     ); // 2 + i\n    ///     z.pow(w)\n    /// }\n    /// >>> {real: {mag: 6881545343236111419203, sign: false}, im: {mag: 2996539405459717736042, sign: false}} // -373.0485407816205 + 162.4438823807959 i\n    /// ```\n    ///\n    fn pow(self: T, b: T) -> T;\n    /// # ComplexTrait::sqrt\n    /// \n    /// ```rust\n    /// fn arg(self: T) -> F;\n    /// ```\n    /// \n    /// Returns the value of the squre root of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number\n    ///\n    /// ## Returns\n    /// \n    /// A complex number '<T>', representing the square root of the complex number. \n    /// 'arg(z) = atan2(b, a)'.\n    /// \n    /// ## Examples\n    ///\n    /// ```rust    \n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn sqrt_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.sqrt()\n    /// }\n    /// >>> {real: {mag: 88650037379463118848, sign: false}, im: {mag: 80608310115317055488, sign: false}} // 4.80572815603723 + 4.369785247552674 i\n    /// ```\n    /// \n    fn sqrt(self: T) -> T;\n    /// # ComplexTrait::acos\n    /// \n    /// ```rust\n    /// fn acos(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arccosine (inverse of cosine) of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the acos  of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn acos_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.acos()\n    /// }\n    /// >>> {real: {mag: 18449430688981877061, sign: false}, im: {mag: 36587032881711954470, sign: true}} //  1.000143542473797 - 1.98338702991653i\n    ///  ```\n    ///\n    fn acos(self: T) -> T;\n    /// # ComplexTrait::asin\n    /// \n    /// ```rust\n    /// fn asin(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arcsine (inverse of sine) of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the asin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn asin_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.asin()\n    /// }\n    /// >>> {real: {mag: 10526647143326614308, sign: false}, im: {mag: 36587032881711954470, sign: false}} // 0.57065278432 + 1.9833870299i\n    ///  ```\n    ///\n    fn asin(self: T) -> T;\n    /// # ComplexTrait::atan\n    /// \n    /// ```rust\n    /// fn atan(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the arctangent (inverse of tangent) of the input complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the arctangent (inverse of tangent) of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn atan_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.atan()\n    /// }\n    /// >>> {real: {mag: 26008453796191787243, sign: false}, im: {mag: 4225645162986888119, sign: false}} // 1.40992104959 + 0.2290726829i\n    ///  ```\n    ///  \n    fn atan(self: T) -> T;\n    /// # ComplexTrait::cos\n    /// \n    /// ```rust\n    /// fn cos(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the cosine of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the cosine of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn cos_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.cos()\n    /// }\n    /// >>> {real: {mag: 77284883172661882094, sign: true}, im: {mag: 168035443352962049425, sign: true}} // -4.18962569 + -9.10922789375i\n    ///  ```\n\n    ///\n    fn cos(self: T) -> T;\n    /// # ComplexTrait::sin\n    /// \n    /// ```rust\n    /// fn sin(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the sine of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the sin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn sin_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.sin()\n    /// }\n    /// >>> {real: {mag: 168870549816927860082, sign: false}, im: {mag: 76902690389051588309, sign: true}} // 9.15449914 - 4.168906959 i\n    ///  ```\n    ///\n    fn sin(self: T) -> T;\n    /// # ComplexTrait::tan\n    /// \n    /// ```rust\n    /// fn tan(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the tangent of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// A complex number representing the tan of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn tan_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.tan()\n    /// }\n    /// >>> {real: {mag: 69433898428143694, sign: true}, im: {mag: 18506486100303669886, sign: false}} // -0.00376402 + 1.00323862i\n    ///  ```\n    ///\n    fn tan(self: T) -> T;\n    /// # ComplexTrait::acosh\n    /// \n    /// ```rust\n    /// fn acosh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic cosine of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic cosine of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn acosh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.acosh()\n    /// }\n    /// >>> {real: {mag: 36587032878947915965, sign: false}, im: {mag: 18449360714192945790, sign: false}} // 1.9833870 + 1.0001435424i\n    ///  ```\n    ///\n    fn acosh(self: T) -> T;\n    /// # ComplexTrait::asinh\n    /// \n    /// ```rust\n    /// fn asinh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic sine of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic sine of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn asinh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.asinh()\n    /// }\n    /// >>> {real: {mag: 36314960239770126586, sign: false}, im: {mag: 17794714057579789616, sign: false}} //1.9686379 + 0.964658504i\n    ///  ```\n    ///\n    fn asinh(self: T) -> T;\n    /// # ComplexTrait::atanh\n    /// \n    /// ```rust\n    /// fn atanh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic tangent of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic tangent of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn atanh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.atanh()\n    /// }\n    /// >>> {real: {mag: 2710687792925618924, sign: false}, im: {mag: 24699666646262346226, sign: false}} //  0.146946666 + 1.33897252i\n    ///  ```\n\n    ///\n    fn atanh(self: T) -> T;\n    /// # ComplexTrait::cosh\n    /// \n    /// ```rust\n    /// fn cosh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic cosine of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic cosine of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn cosh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.cosh()\n    /// }\n    /// >>> {real: {mag: 68705646899632870392, sign: true}, im: {mag: 9441447324287988702, sign: false}} // -3.72454550491 + 0.511822569987i\n    ///  ```\n    ///\n    fn cosh(self: T) -> T;\n    /// # ComplexTrait::sinh\n    /// \n    /// ```rust\n    /// fn sinh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic sine of the complex number.\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic sine of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn sinh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.sinh()\n    /// }\n    /// >>> {real: {mag: 66234138518106676624, sign: true}, im: {mag: 9793752294470951790, sign: false}} // -3.59056458998 + 0.530921086i\n    ///  ```\n    ///\n    fn sinh(self: T) -> T;\n    /// # ComplexTrait::tanh\n    /// \n    /// ```rust\n    /// fn tanh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic tangent of the complex number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic tangent of the input complex number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn tanh_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(36893488147419103232, false),\n    ///         FixedTrait::new(55340232221128654848, false)\n    ///     ); // 2 + 3i\n    ///     z.tanh()\n    /// }\n    /// >>> {real: {mag: 17808227710002974080, sign: false}, im: {mag: 182334107030204896, sign: true}} // 0.96538587902 + 0.009884375i\n    ///  ```\n    ///\n    fn tanh(self: T) -> T;\n    /// # ComplexTrait::to_polar\n    /// \n    /// ```rust\n    /// fn to_polar(self: T) -> (F, F);\n    /// ```\n    /// \n    /// Returns the polar coordinates (magnitude and argument) of the complex number.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns \n    ///\n    /// A tuple of two fixed point numbers representing the polar coordinates of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn to_polar_complex64_example() -> (FP64x64, FP64x64) {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.to_polar()\n    /// }\n    /// >>> ({mag: 778268985067028086784, sign: false},  {mag: 27224496882576083824, sign: false}) // mag : 42.190046219457976 + arg : 1.4758446204521403 \n    ///  ```\n    ///\n    fn to_polar(self: T) -> (F, F);\n    /// # ComplexTrait::from_polar\n    ///\n    /// \n    /// ```rust\n    /// fn from_polar(mag: F, arg: F) -> T;\n    /// ```\n    /// \n    /// Returns a complex number (in the Cartesian form) from the polar coordinates of the complex number.\n    /// \n    /// ## Args\n    ///\n    /// * `mag`(`F`) - The input fixed point number representing the magnitude.\n    /// * `arg`(`F`) - The input fixed point number representing the argument.\n    ///\n    /// ## Returns \n    ///\n    /// The complex number representing the Cartesian form calculated from the input polar coordinates.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn from_polar_complex64_example() -> complex64 {\n    ///     let mag: FP64x64 = FixedTrait::new(778268985067028086784, false); // 42.190046219457976\n    ///     let arg: FP64x64 = FixedTrait::new(27224496882576083824, false); //1.4758446204521403\n    ///     ComplexTrait::from_polar(mag,arg)\n    /// }\n    /// >>> {real: {mag: 73787936714814843012, sign: false}, im: {mag: 774759489569697723777, sign: false}} // 4 + 42 i\n    ///  ```\n    ///\n    fn from_polar(mag: F, arg: F) -> T;\n    /// # ComplexTrait::reciprocal\n    ///\n    /// \n    /// ```rust\n    /// fn reciprocal(self: T) -> T;\n    /// ```\n    /// \n    /// Returns a the reciprocal of the complex number (i.e. 1/z).\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input complex number.\n    ///\n    /// ## Returns \n    ///\n    /// The reciprocal of the complex number \\(a + bi\\) is given by:\n    /// \\[\n    /// \\frac{1}{a + bi} = \\frac{a}{a^2 + b^2} - \\frac{b}{a^2 + b^2}i\n    /// \\]\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::complex_number::{complex_trait::ComplexTrait, complex64::complex64};\n    /// use orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\n    /// \n    /// fn reciprocal_complex64_example() -> complex64 {\n    ///     let z: complex64 = ComplexTrait::new(\n    ///         FixedTrait::new(73786976294838206464, false),\n    ///         FixedTrait::new(774763251095801167872, false)\n    ///     ); // 4 + 42i\n    ///     z.reciprocal()\n    /// }\n    /// >>> {real: {mag: 41453357469010228, sign: false}, im: {mag: 435260253424607397, sign: true}} // 0.002247191011 - 0.0235955056 i\n    ///  ```\n    ///\n    fn reciprocal(self: T) -> T;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point.cairo",
        "content": "//! Fixed-Point implemented from https://github.com/influenceth/cubit and adjusted to Q8.23\nmod core;\nmod implementations;\nmod utils;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/core.cairo",
        "content": "/// Trait\n///\n/// new - Constructs a new fixed point instance.\n/// new_unscaled - Creates a new fixed point instance with the specified unscaled magnitude and sign.\n/// from_felt - Creates a new fixed point instance from a felt252 value.\n/// abs - Returns the absolute value of the fixed point number.\n/// ceil - Returns the smallest integer greater than or equal to the fixed point number.\n/// exp - Returns the value of e raised to the power of the fixed point number.\n/// exp2 - Returns the value of 2 raised to the power of the fixed point number.\n/// floor - Returns the largest integer less than or equal to the fixed point number.\n/// ln - Returns the natural logarithm of the fixed point number.\n/// log2 - Returns the base-2 logarithm of the fixed point number.\n/// log10 - Returns the base-10 logarithm of the fixed point number.\n/// pow - Returns the result of raising the fixed point number to the power of another fixed point number.\n/// round - Rounds the fixed point number to the nearest whole number.\n/// sqrt - Returns the square root of the fixed point number.\n/// acos - Returns the  arccosine (inverse of cosine) of the fixed point number.\n/// acos_fast - Returns the  arccosine (inverse of cosine) of the fixed point number faster with LUT.\n/// asin - Returns the  arcsine (inverse of sine) of the fixed point number.\n/// asin_fast - Returns the  arcsine (inverse of sine) of the fixed point number faster with LUT.\n/// atan - Returns the arctangent (inverse of tangent) of the input fixed point number.\n/// atan_fast - Returns the arctangent (inverse of tangent) of the input fixed point number faster with LUT.\n/// cos - Returns the cosine of the fixed point number.\n/// cos_fast - Returns the cosine of the fixed point number fast with LUT.\n/// sin - Returns the sine of the fixed point number.\n/// sin_fast - Returns the sine of the fixed point number faster with LUT.\n/// tan - Returns the tangent of the fixed point number.\n/// tan_fast - Returns the tangent of the fixed point number faster with LUT.\n/// acosh - Returns the value of the inverse hyperbolic cosine of the fixed point number.\n/// asinh - Returns the value of the inverse hyperbolic sine of the fixed point number.\n/// atanh - Returns the value of the inverse hyperbolic tangent of the fixed point number.\n/// cosh - Returns the value of the hyperbolic cosine of the fixed point number.\n/// sinh - Returns the value of the hyperbolic sine of the fixed point number.\n/// tanh - Returns the value of the hyperbolic tangent of the fixed point number.\n/// sign - Returns the element-wise indication of the sign of the input fixed point number.\n/// erf - Returns the error function of the input fixed point number computed element-wise.\n/// \ntrait FixedTrait<T, MAG> {\n    /// # FixedTrait::new\n    /// \n    /// ```rust\n    /// fn new(mag: MAG, sign: bool) -> T;\n    /// ```\n    /// \n    /// Constructs a new fixed point instance.\n    ///\n    /// ## Args\n    /// \n    /// * `mag`(`MAG`) - The magnitude of the fixed point.\n    /// * `sign`(`bool`) - The sign of the fixed point, where `true` represents a negative number.\n    ///\n    /// ## Returns\n    ///\n    /// A new fixed point instance.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn new_fp_example() -> FP16x16 {\n    ///     // We can call `new` function as follows. \n    ///     FixedTrait::new(65536, false)\n    /// }\n    /// >>> {mag: 65536, sign: false} // = 1 in FP16x16\n    /// ```\n    ///\n    fn new(mag: MAG, sign: bool) -> T;\n    /// # FixedTrait::new\\_unscaled\n    /// \n    /// ```rust\n    ///     fn new_unscaled(mag: MAG, sign: bool) -> T;\n    /// ```\n    ///\n    /// Creates a new fixed point instance with the specified unscaled magnitude and sign.\n    /// \n    /// ## Args\n    ///\n    /// `mag`(`MAG`) - The unscaled magnitude of the fixed point.\n    /// `sign`(`bool`) - The sign of the fixed point, where `true` represents a negative number.\n    ///\n    /// ## Returns\n    /// \n    /// A new fixed point instance.\n    /// \n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn new_unscaled_example() -> FP16x16 {\n    ///     // We can call `new_unscaled` function as follows. \n    ///     FixedTrait::new_unscaled(1, false)\n    /// }\n    /// >>> {mag: 65536, sign: false}\n    /// ```\n    ///\n    fn new_unscaled(mag: MAG, sign: bool) -> T;\n    /// # FixedTrait::from\\_felt\n    ///\n    /// \n    /// ```rust\n    /// fn from_felt(val: felt252) -> T;\n    /// ```\n    /// \n    /// Creates a new fixed point instance from a felt252 value.\n    ///\n    /// ## Args\n    /// \n    /// * `val`(`felt252`) - `felt252` value to convert in fixed point.\n    ///\n    /// ## Returns \n    ///\n    /// A new fixed point instance.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn from_felt_example() -> FP16x16 {\n    ///     // We can call `from_felt` function as follows . \n    ///     FixedTrait::from_felt(190054)\n    /// }\n    /// >>> {mag: 190054, sign: false} // = 2.9\n    /// ```\n    ///\n    fn from_felt(val: felt252) -> T;\n    /// # fp.abs\n    /// \n    /// ```rust\n    /// fn abs(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the absolute value of the fixed point number.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The absolute value of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// \n    /// fn abs_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, true);\n    /// \n    ///     // We can call `abs` function as follows.\n    ///     fp.abs()\n    /// }\n    /// >>> {mag: 65536, sign: false} // = 1\n    /// ```\n    /// \n    fn abs(self: T) -> T;\n    /// # fp.ceil\n    /// \n    /// ```rust\n    /// fn ceil(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the smallest integer greater than or equal to the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// *`self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The smallest integer greater than or equal to the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn ceil_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::from_felt(190054); // 2.9\n    /// \n    ///     // We can call `ceil` function as follows.\n    ///     fp.ceil()\n    /// }\n    /// >>> {mag: 196608, sign: false} // = 3\n    /// ```\n    ///\n    fn ceil(self: T) -> T;\n    /// # fp.exp\n    /// \n    /// ```rust\n    /// fn exp(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of e raised to the power of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The natural exponent of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn exp_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `exp` function as follows.\n    ///     fp.exp()\n    /// }\n    /// >>> {mag: 484249, sign: false} // = 7.389056317241236\n    /// ``` \n    ///\n    fn exp(self: T) -> T;\n    /// # fp.exp2\n    /// \n    /// ```rust\n    /// fn exp2(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of 2 raised to the power of the fixed point number.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The binary exponent of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn exp2_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `exp2` function as follows.\n    ///     fp.exp2()\n    /// }\n    /// >>> {mag: 262143, sign: false} // = 3.99999957248\n    /// ``` \n    ///\n    fn exp2(self: T) -> T;\n    /// # fp.floor\n    /// \n    /// ```rust\n    /// fn floor(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the largest integer less than or equal to the fixed point number.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// Returns the largest integer less than or equal to the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn floor_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::from_felt(190054); // 2.9\n    /// \n    ///     // We can call `floor` function as follows.\n    ///     fp.floor()\n    /// }\n    /// >>> {mag: 131072, sign: false} // = 2\n    /// ```\n    /// \n    fn floor(self: T) -> T;\n    /// # fp.ln\n    ///\n    /// \n    /// ```rust\n    /// fn ln(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the natural logarithm of the fixed point number.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns \n    ///\n    /// A fixed point representing the natural logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn ln_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, false);\n    /// \n    ///     // We can call `ln` function as follows.\n    ///     fp.ln()\n    /// }\n    /// >>> {mag: 0, sign: false}\n    /// ```\n    ///\n    fn ln(self: T) -> T;\n    /// # fp.log2\n    /// \n    /// ```rust\n    /// fn log2(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the base-2 logarithm of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the input is negative.\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point representing the binary logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn log2_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(3, false);\n    /// \n    ///     // We can call `log2` function as follows.\n    ///     fp.log2()\n    /// }\n    /// >>> {mag: 103872, sign: false} // = 1.58496250072\n    /// ```\n    /// \n    fn log2(self: T) -> T;\n    /// # fp.log10\n    /// \n    /// ```rust\n    /// fn log10(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the base-10 logarithm of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point representing the base 10 logarithm of the input number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn log10_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(3, false);\n    /// \n    ///     // We can call `log10` function as follows.\n    ///     fp.log10()\n    /// }\n    /// >>> {mag: 31269, sign: false} // = 0.47712125472\n    /// ```\n    ///\n    fn log10(self: T) -> T;\n    /// # fp.pow\n    /// \n    /// ```rust\n    /// fn pow(self: T, b: T) -> T;\n    /// ```\n    /// \n    /// Returns the result of raising the fixed point number to the power of another fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point.\n    /// * `b`(`T`) - The exponent fixed point number.\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the result of x^y.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn pow_fp_example() -> FP16x16 {\n    ///     // We instantiate FixedTrait points here.\n    ///     let a = FixedTrait::new_unscaled(3, false);\n    ///     let b = FixedTrait::new_unscaled(4, false);\n    /// \n    ///     // We can call `pow` function as follows.\n    ///     a.pow(b)\n    /// }\n    /// >>> {mag: 5308416, sign: false} // = 81\n    /// ```\n    ///\n    fn pow(self: T, b: T) -> T;\n    /// # fp.round\n    /// \n    /// ```rust\n    /// fn round(self: T) -> T;\n    /// ```\n    /// \n    /// Rounds the fixed point number to the nearest whole number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the rounded value.\n    ///\n    /// ## Examples\n    ///\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn round_fp_example() -> FP16x16 {\n    ///     // We instantiate FixedTrait points here.\n    ///     let a = FixedTrait::from_felt(190054); // 2.9\n    /// \n    ///     // We can call `round` function as follows.\n    ///     a.round()\n    /// }\n    /// >>> {mag: 196608, sign: false} // = 3\n    /// ```\n    /// \n    fn round(self: T) -> T;\n    /// # fp.sqrt\n    /// \n    /// ```rust\n    /// fn sqrt(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the square root of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// `self`(`T`) - The input fixed point\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the input is negative.\n    ///\n    /// ## Returns\n    /// \n    /// A fixed point number representing the square root of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn sqrt_fp_example() -> FP16x16 {\n    ///     // We instantiate FixedTrait points here.\n    ///     let a = FixedTrait::new_unscaled(9, false);\n    /// \n    ///     // We can call `round` function as follows.\n    ///     a.sqrt()\n    /// }\n    /// >>> {mag: 196608, sign: false} // = 3\n    /// ```\n    ///\n    fn sqrt(self: T) -> T;\n    /// # fp.acos\n    /// \n    /// ```rust\n    /// fn acos(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arccosine (inverse of cosine) of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the acos  of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn acos_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, true);\n    /// \n    ///     // We can call `acos` function as follows.\n    ///     fp.acos()\n    /// }\n    /// >>> {mag: 205887, sign: false} // = 3.14159265\n    /// ``` \n    ///\n    fn acos(self: T) -> T;\n    /// # fp.acos_fast\n    /// \n    /// ```rust\n    /// fn acos_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arccosine (inverse of cosine) of the fixed point number faster with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the acos  of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn acos_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, true);\n    /// \n    ///     // We can call `acos_fast` function as follows.\n    ///     fp.acos_fast()\n    /// }\n    /// >>> {mag: 205887, sign: false} // = 3.14159265\n    /// ``` \n    ///\n    fn acos_fast(self: T) -> T;\n    /// # fp.asin\n    /// \n    /// ```rust\n    /// fn asin(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arcsine (inverse of sine) of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the asin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn asin_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, false);\n    /// \n    ///     // We can call `asin` function as follows.\n    ///     fp.asin()\n    /// }\n    /// >>> {mag: 102943, sign: true} // = 1.57079633\n    /// ``` \n    ///\n    fn asin(self: T) -> T;\n    /// # fp.asin_fast\n    /// \n    /// ```rust\n    /// fn asin_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the  arcsine (inverse of sine) of the fixed point number faster with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the asin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn asin_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(1, false);\n    /// \n    ///     // We can call `asin_fast` function as follows.\n    ///     fp.asin_fast()\n    /// }\n    /// >>> {mag: 102943, sign: true} // = 1.57079633\n    /// ``` \n    ///\n    fn asin_fast(self: T) -> T;\n    /// # fp.atan\n    /// \n    /// ```rust\n    /// fn atan(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the arctangent (inverse of tangent) of the input fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the arctangent (inverse of tangent) of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn atan_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `atan` function as follows.\n    ///     fp.atan()\n    /// }\n    /// >>> {mag: 72558, sign: false} // = 1.10714872\n    /// ``` \n    ///  \n    fn atan(self: T) -> T;\n    /// # fp.atan_fast\n    /// \n    /// ```rust\n    /// fn atan_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the arctangent (inverse of tangent) of the input fixed point number faster with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the arctangent (inverse of tangent) of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn atan_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `atan_fast` function as follows.\n    ///     fp.atan_fast()\n    /// }\n    /// >>> {mag: 72558, sign: false} // = 1.10714872\n    /// ``` \n    ///\n    fn atan_fast(self: T) -> T;\n    /// # fp.cos\n    /// \n    /// ```rust\n    /// fn cos(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the cosine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the cosine of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn cos_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `cos` function as follows.\n    ///     fp.cos()\n    /// }\n    /// >>> {mag: 27273, sign: true} // = -0.41614684\n    /// ``` \n    ///\n    fn cos(self: T) -> T;\n    /// # fp.cos_fast\n    /// \n    /// ```rust\n    /// fn cos_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the cosine of the fixed point number fast with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the cosine of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn cos_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `cos_fast` function as follows.\n    ///     fp.cos_fast()\n    /// }\n    /// >>> {mag: 27273, sign: true} // = -0.41614684\n    /// ``` \n    ///\n    fn cos_fast(self: T) -> T;\n    /// # fp.sin\n    /// \n    /// ```rust\n    /// fn sin(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the sine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the sin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn sin_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `sin` function as follows.\n    ///     fp.sin()\n    /// }\n    /// >>> {mag: 59592, sign: false} // = 0.90929743\n    /// ``` \n    ///\n    fn sin(self: T) -> T;\n    /// # fp.sin_fast\n    /// \n    /// ```rust\n    /// fn sin_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the sine of the fixed point number faster with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the sin of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn sin_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `sin_fast` function as follows.\n    ///     fp.sin_fast()\n    /// }\n    /// >>> {mag: 59592, sign: false} // = 0.90929743\n    /// ``` \n    ///\n    fn sin_fast(self: T) -> T;\n    /// # fp.tan\n    /// \n    /// ```rust\n    /// fn tan(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the tangent of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the tan of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn tan_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `tan` function as follows.\n    ///     fp.tan()\n    /// }\n    /// >>> {mag: 143199, sign: true} // = -2.18503986\n    /// ``` \n    ///\n    fn tan(self: T) -> T;\n    /// # fp.tan_fast\n    /// \n    /// ```rust\n    /// fn tan_fast(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the tangent of the fixed point number faster with LUT.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// A fixed point number representing the tan of the input value.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn tan_fast_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `tan_fast` function as follows.\n    ///     fp.tan_fast()\n    /// }\n    /// >>> {mag: 143199, sign: true} // = -2.18503986\n    /// ``` \n    ///\n    fn tan_fast(self: T) -> T;\n    /// # fp.acosh\n    /// \n    /// ```rust\n    /// fn acosh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic cosine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic cosine of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn acosh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `acosh` function as follows.\n    ///     fp.acosh()\n    /// }\n    /// >>> {mag: 86308, sign: false} // = 1.3169579\n    /// ``` \n    ///\n    fn acosh(self: T) -> T;\n    /// # fp.asinh\n    /// \n    /// ```rust\n    /// fn asinh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic sine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic sine of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn asinh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `asinh` function as follows.\n    ///     fp.asinh()\n    /// }\n    /// >>> {mag: 94610, sign: false} // = 1.44363548\n    /// ``` \n    ///\n    fn asinh(self: T) -> T;\n    /// # fp.atanh\n    /// \n    /// ```rust\n    /// fn atanh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the inverse hyperbolic tangent of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The inverse hyperbolic tangent of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn atanh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::from_felt(32768); // 0.5\n    /// \n    ///     // We can call `atanh` function as follows.\n    ///     fp.atanh()\n    /// }\n    /// >>> {mag: 35999, sign: false} // = 0.54930614\n    /// ``` \n    ///\n    fn atanh(self: T) -> T;\n    /// # fp.cosh\n    /// \n    /// ```rust\n    /// fn cosh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic cosine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic cosine of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn cosh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `cosh` function as follows.\n    ///     fp.cosh()\n    /// }\n    /// >>> {mag: 246559, sign: false} // = 3.76219569\n    /// ``` \n    ///\n    fn cosh(self: T) -> T;\n    /// # fp.sinh\n    /// \n    /// ```rust\n    /// fn sinh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic sine of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic sine of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn sinh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `sinh` function as follows.\n    ///     fp.sinh()\n    /// }\n    /// >>> {mag: 237690, sign: false} // = 3.62686041\n    /// ``` \n    ///\n    fn sinh(self: T) -> T;\n    /// # fp.tanh\n    /// \n    /// ```rust\n    /// fn tanh(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the value of the hyperbolic tangent of the fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The hyperbolic tangent of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn tanh_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, false);\n    /// \n    ///     // We can call `tanh` function as follows.\n    ///     fp.tanh()\n    /// }\n    /// >>> {mag: 63179, sign: false} // = 0.96402758\n    /// ``` \n    ///\n    fn tanh(self: T) -> T;\n    /// # fp.sign\n    /// \n    /// ```rust\n    /// fn sign(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the element-wise indication of the sign of the input fixed point number.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The element-wise indication of the sign of the input fixed point number.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn sign_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new_unscaled(2, true);\n    /// \n    ///     // We can call `sign` function as follows.\n    ///     fp.sign()\n    /// }\n    /// >>> {mag: 65536, sign: true} // = -1\n    /// ``` \n    ///\n    fn sign(self: T) -> T;\n    /// # fp.erf\n    /// \n    /// ```rust\n    /// fn erf(self: T) -> T;\n    /// ```\n    /// \n    /// Returns the error function of the input fixed point number computed element-wise.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`T`) - The input fixed point\n    ///\n    /// ## Returns\n    ///\n    /// The error function of the input fixed point number computed element-wise.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn erf_fp_example() -> FP16x16 {\n    ///     // We instantiate fixed point here.\n    ///     let fp = FixedTrait::new(65536, false);\n    /// \n    ///     // We can call `erf` function as follows.\n    ///     fp.erf()\n    /// }\n    /// >>> {mag: 55227, sign: false} // = -1\n    /// ``` \n    ///\n    fn erf(self: T) -> T;\n\n    fn ZERO() -> T;\n    fn HALF() -> T;\n    fn ONE() -> T;\n    fn MAX() -> T;\n    fn NaN() -> T;\n    fn is_nan(self: T) -> bool;\n    fn INF() -> T;\n    fn POS_INF() -> T;\n    fn NEG_INF() -> T;\n    fn is_inf(self: T) -> bool;\n    fn is_pos_inf(self: T) -> bool;\n    fn is_neg_inf(self: T) -> bool;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations.cairo",
        "content": "mod fp8x23;\nmod fp16x16;\nmod fp64x64;\nmod fp32x32;\nmod fp16x16wide;\nmod fp8x23wide;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16.cairo",
        "content": "mod core;\nmod math;\nmod helpers;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::math::{\n    core as core_math, trig, hyp, erf\n};\nuse orion::numbers::fixed_point::utils;\n\n/// A struct representing a fixed point number.\n#[derive(Serde, Copy, Drop)]\nstruct FP16x16 {\n    mag: u32,\n    sign: bool\n}\n\n// CONSTANTS\nconst TWO: u32 = 131072; // 2 ** 17\nconst ONE: u32 = 65536; // 2 ** 16\nconst HALF: u32 = 32768; // 2 ** 15\nconst MAX: u32 = 2147483648; // 2 ** 31\n\nimpl FP16x16Impl of FixedTrait<FP16x16, u32> {\n    fn ZERO() -> FP16x16 {\n        FP16x16 { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP16x16 {\n        FP16x16 { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP16x16 {\n        FP16x16 { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP16x16 {\n        FP16x16 { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u32, sign: bool) -> FP16x16 {\n        FP16x16 { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u32, sign: bool) -> FP16x16 {\n        FP16x16 { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP16x16 {\n        let mag = core::integer::u32_try_from_felt252(utils::felt_abs(val)).unwrap();\n\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP16x16) -> FP16x16 {\n        core_math::abs(self)\n    }\n\n    fn acos(self: FP16x16) -> FP16x16 {\n        trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP16x16) -> FP16x16 {\n        trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP16x16) -> FP16x16 {\n        hyp::acosh(self)\n    }\n\n    fn asin(self: FP16x16) -> FP16x16 {\n        trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP16x16) -> FP16x16 {\n        trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP16x16) -> FP16x16 {\n        hyp::asinh(self)\n    }\n\n    fn atan(self: FP16x16) -> FP16x16 {\n        trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP16x16) -> FP16x16 {\n        trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP16x16) -> FP16x16 {\n        hyp::atanh(self)\n    }\n\n    fn ceil(self: FP16x16) -> FP16x16 {\n        core_math::ceil(self)\n    }\n\n    fn cos(self: FP16x16) -> FP16x16 {\n        trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP16x16) -> FP16x16 {\n        trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP16x16) -> FP16x16 {\n        hyp::cosh(self)\n    }\n\n    fn floor(self: FP16x16) -> FP16x16 {\n        core_math::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP16x16) -> FP16x16 {\n        core_math::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP16x16) -> FP16x16 {\n        core_math::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP16x16) -> FP16x16 {\n        core_math::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP16x16) -> FP16x16 {\n        core_math::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP16x16) -> FP16x16 {\n        core_math::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP16x16, b: FP16x16) -> FP16x16 {\n        core_math::pow(self, b)\n    }\n\n    fn round(self: FP16x16) -> FP16x16 {\n        core_math::round(self)\n    }\n\n    fn sin(self: FP16x16) -> FP16x16 {\n        trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP16x16) -> FP16x16 {\n        trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP16x16) -> FP16x16 {\n        hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP16x16) -> FP16x16 {\n        core_math::sqrt(self)\n    }\n\n    fn tan(self: FP16x16) -> FP16x16 {\n        trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP16x16) -> FP16x16 {\n        trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP16x16) -> FP16x16 {\n        hyp::tanh(self)\n    }\n\n    fn sign(self: FP16x16) -> FP16x16 {\n        core_math::sign(self)\n    }\n\n    fn NaN() -> FP16x16 {\n        FP16x16 { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP16x16) -> bool {\n        self == FP16x16 { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP16x16 {\n        FP16x16 { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP16x16 {\n        FP16x16 { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP16x16 {\n        FP16x16 { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP16x16) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP16x16) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP16x16) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP16x16) -> FP16x16 {\n        erf::erf(self)\n    }\n}\n\n\nimpl FP16x16Print of PrintTrait<FP16x16> {\n    fn print(self: FP16x16) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP16x16IntoFelt252 of Into<FP16x16, felt252> {\n    fn into(self: FP16x16) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP16x16IntoI32 of Into<FP16x16, i32> {\n    fn into(self: FP16x16) -> i32 {\n        _i32_into_fp(self)\n    }\n}\n\nimpl FP16x16TryIntoI8 of TryInto<FP16x16, i8> {\n    fn try_into(self: FP16x16) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\n\nimpl FP16x16TryIntoU128 of TryInto<FP16x16, u128> {\n    fn try_into(self: FP16x16) -> Option<u128> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP16x16TryIntoU64 of TryInto<FP16x16, u64> {\n    fn try_into(self: FP16x16) -> Option<u64> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP16x16TryIntoU32 of TryInto<FP16x16, u32> {\n    fn try_into(self: FP16x16) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some(self.mag / ONE)\n        }\n    }\n}\n\nimpl FP16x16TryIntoU16 of TryInto<FP16x16, u16> {\n    fn try_into(self: FP16x16) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP16x16TryIntoU8 of TryInto<FP16x16, u8> {\n    fn try_into(self: FP16x16) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP16x16PartialEq of PartialEq<FP16x16> {\n    #[inline(always)]\n    fn eq(lhs: @FP16x16, rhs: @FP16x16) -> bool {\n        core_math::eq(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn ne(lhs: @FP16x16, rhs: @FP16x16) -> bool {\n        core_math::ne(lhs, rhs)\n    }\n}\n\nimpl FP16x16Add of Add<FP16x16> {\n    fn add(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        core_math::add(lhs, rhs)\n    }\n}\n\nimpl FP16x16AddEq of AddEq<FP16x16> {\n    #[inline(always)]\n    fn add_eq(ref self: FP16x16, other: FP16x16) {\n        self = Add::add(self, other);\n    }\n}\n\nimpl FP16x16Sub of Sub<FP16x16> {\n    fn sub(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        core_math::sub(lhs, rhs)\n    }\n}\n\nimpl FP16x16SubEq of SubEq<FP16x16> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP16x16, other: FP16x16) {\n        self = Sub::sub(self, other);\n    }\n}\n\nimpl FP16x16Mul of Mul<FP16x16> {\n    fn mul(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        core_math::mul(lhs, rhs)\n    }\n}\n\nimpl FP16x16MulEq of MulEq<FP16x16> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP16x16, other: FP16x16) {\n        self = Mul::mul(self, other);\n    }\n}\n\nimpl FP16x16Div of Div<FP16x16> {\n    fn div(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        core_math::div(lhs, rhs)\n    }\n}\n\nimpl FP16x16DivEq of DivEq<FP16x16> {\n    #[inline(always)]\n    fn div_eq(ref self: FP16x16, other: FP16x16) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl FP16x16PartialOrd of PartialOrd<FP16x16> {\n    #[inline(always)]\n    fn ge(lhs: FP16x16, rhs: FP16x16) -> bool {\n        core_math::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP16x16, rhs: FP16x16) -> bool {\n        core_math::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP16x16, rhs: FP16x16) -> bool {\n        core_math::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP16x16, rhs: FP16x16) -> bool {\n        core_math::lt(lhs, rhs)\n    }\n}\n\nimpl FP16x16Neg of Neg<FP16x16> {\n    #[inline(always)]\n    fn neg(a: FP16x16) -> FP16x16 {\n        core_math::neg(a)\n    }\n}\n\nimpl FP16x16Rem of Rem<FP16x16> {\n    #[inline(always)]\n    fn rem(lhs: FP16x16, rhs: FP16x16) -> FP16x16 {\n        core_math::rem(lhs, rhs)\n    }\n}\n\n/// INTERNAL\nfn _i32_into_fp(x: FP16x16) -> i32 {\n    let number_felt: felt252 = (x.mag / ONE).into();\n    let number_i32: i32 = number_felt.try_into().unwrap();\n    if x.sign {\n        return number_i32 * -1_i32;\n    }\n\n    number_i32\n}\n\nfn _i8_try_from_fp(x: FP16x16) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/helpers.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, TWO, FP16x16, FP16x16Impl, FP16x16Sub, FP16x16Div, FixedTrait, FP16x16Print\n};\n\nconst DEFAULT_PRECISION: u32 = 7; // 1e-4\n\n// To use `DEFAULT_PRECISION`, final arg is: `Option::None(())`.\n// To use `custom_precision` of 430_u32: `Option::Some(430_u32)`.\nfn assert_precise(result: FP16x16, expected: felt252, msg: felt252, custom_precision: Option<u32>) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = (result - FixedTrait::from_felt(expected)).mag;\n\n    if (diff > precision) {\n        result.print();\n        assert(diff <= precision, msg);\n    }\n}\n\nfn assert_relative(\n    result: FP16x16, expected: felt252, msg: felt252, custom_precision: Option<u32>\n) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = result - FixedTrait::from_felt(expected);\n    let rel_diff = (diff / result).mag;\n\n    if (rel_diff > precision) {\n        result.print();\n        assert(rel_diff <= precision, msg);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math.cairo",
        "content": "mod core;\nmod comp;\nmod lut;\nmod trig;\nmod hyp;\nmod erf;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/comp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16::core::{\n    FP16x16, FixedTrait, FP16x16Impl, FP16x16PartialOrd, FP16x16PartialEq\n};\n\nfn max(a: FP16x16, b: FP16x16) -> FP16x16 {\n    if a >= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn min(a: FP16x16, b: FP16x16) -> FP16x16 {\n    if a <= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn xor(a: FP16x16, b: FP16x16) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP16x16, b: FP16x16) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP16x16, b: FP16x16) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP16x16, b: FP16x16, c: FP16x16) -> FP16x16 {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP16x16, b: FP16x16) -> FP16x16 {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP16x16, b: FP16x16) -> FP16x16 {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP16x16, b: FP16x16) -> FP16x16 {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use super::{FixedTrait, max, min, bitwise_and, bitwise_xor, bitwise_or};\n\n    #[test]\n    fn test_max() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(max(a, a) == a, 'max(a, a)');\n        assert(max(a, b) == a, 'max(a, b)');\n        assert(max(a, c) == a, 'max(a, c)');\n\n        assert(max(b, a) == a, 'max(b, a)');\n        assert(max(b, b) == b, 'max(b, b)');\n        assert(max(b, c) == b, 'max(b, c)');\n\n        assert(max(c, a) == a, 'max(c, a)');\n        assert(max(c, b) == b, 'max(c, b)');\n        assert(max(c, c) == c, 'max(c, c)');\n    }\n\n    #[test]\n    fn test_min() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(min(a, a) == a, 'min(a, a)');\n        assert(min(a, b) == b, 'min(a, b)');\n        assert(min(a, c) == c, 'min(a, c)');\n\n        assert(min(b, a) == b, 'min(b, a)');\n        assert(min(b, b) == b, 'min(b, b)');\n        assert(min(b, c) == c, 'min(b, c)');\n\n        assert(min(c, a) == c, 'min(c, a)');\n        assert(min(c, b) == c, 'min(c, b)');\n        assert(min(c, c) == c, 'min(c, c)');\n    }\n\n    #[test]\n    fn test_bitwise_and() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(94208, false); // 1.4375\n\n        assert(bitwise_and(a, b) == c, 'bitwise_and(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_xor() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(4160880640, true);\n\n        assert(bitwise_xor(a, b) == c, 'bitwise_xor(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_or() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(4160974848, true);\n\n        assert(bitwise_or(a, b) == c, 'bitwise_or(a,b)')\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/core.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, MAX, FP16x16, FP16x16Impl, FP16x16Add, FP16x16AddEq, FP16x16Sub, FP16x16Mul,\n    FP16x16MulEq, FP16x16TryIntoU128, FP16x16PartialEq, FP16x16PartialOrd, FP16x16SubEq, FP16x16Neg,\n    FP16x16Div, FP16x16IntoFelt252, FixedTrait\n};\nuse orion::numbers::fixed_point::implementations::fp16x16::math::lut;\n\n// PUBLIC\nfn abs(a: FP16x16) -> FP16x16 {\n    FixedTrait::new(a.mag, false)\n}\n\nfn add(a: FP16x16, b: FP16x16) -> FP16x16 {\n    if a.sign == b.sign {\n        return FixedTrait::new(a.mag + b.mag, a.sign);\n    }\n\n    if a.mag == b.mag {\n        return FixedTrait::ZERO();\n    }\n\n    if (a.mag > b.mag) {\n        FixedTrait::new(a.mag - b.mag, a.sign)\n    } else {\n        FixedTrait::new(b.mag - a.mag, b.sign)\n    }\n}\n\nfn ceil(a: FP16x16) -> FP16x16 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div + 1, false)\n    } else if div == 0 {\n        FixedTrait::new_unscaled(0, false)\n    } else {\n        FixedTrait::new_unscaled(div, true)\n    }\n}\n\nfn div(a: FP16x16, b: FP16x16) -> FP16x16 {\n    let a_u64 = integer::u32_wide_mul(a.mag, ONE);\n    let res_u64 = a_u64 / b.mag.into();\n\n    // Re-apply sign\n    FixedTrait::new(res_u64.try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn eq(a: @FP16x16, b: @FP16x16) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n// Calculates the natural exponent of x: e^x\nfn exp(a: FP16x16) -> FP16x16 {\n    exp2(FixedTrait::new(94548, false) * a) // log2(e) * 2^23 \u2248 12102203\n}\n\n// Calculates the binary exponent of x: 2^x\nfn exp2(a: FP16x16) -> FP16x16 {\n    if (a.mag == 0) {\n        return FixedTrait::ONE();\n    }\n\n    let (int_part, frac_part) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n    let int_res = FixedTrait::new_unscaled(lut::exp2(int_part), false);\n    let mut res_u = int_res;\n\n    if frac_part != 0 {\n        let frac = FixedTrait::new(frac_part, false);\n        let r7 = FixedTrait::new(1, false) * frac;\n        let r6 = (r7 + FixedTrait::new(10, false)) * frac;\n        let r5 = (r6 + FixedTrait::new(87, false)) * frac;\n        let r4 = (r5 + FixedTrait::new(630, false)) * frac;\n        let r3 = (r4 + FixedTrait::new(3638, false)) * frac;\n        let r2 = (r3 + FixedTrait::new(15743, false)) * frac;\n        let r1 = (r2 + FixedTrait::new(45426, false)) * frac;\n        res_u = res_u * (r1 + FixedTrait::ONE());\n    }\n\n    if a.sign {\n        FixedTrait::ONE() / res_u\n    } else {\n        res_u\n    }\n}\n\nfn exp2_int(exp: u32) -> FP16x16 {\n    FixedTrait::new_unscaled(lut::exp2(exp), false)\n}\n\nfn floor(a: FP16x16) -> FP16x16 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div, false)\n    } else {\n        FixedTrait::new_unscaled(div + 1, true)\n    }\n}\n\nfn ge(a: FP16x16, b: FP16x16) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn gt(a: FP16x16, b: FP16x16) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn le(a: FP16x16, b: FP16x16) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\n// Calculates the natural logarithm of x: ln(x)\n// self must be greater than zero\nfn ln(a: FP16x16) -> FP16x16 {\n    FixedTrait::new(45426, false) * log2(a) // ln(2) = 0.693...\n}\n\n// Calculates the binary logarithm of x: log2(x)\n// self must be greather than zero\nfn log2(a: FP16x16) -> FP16x16 {\n    assert(a.sign == false, 'must be positive');\n\n    if (a.mag == ONE) {\n        return FixedTrait::ZERO();\n    } else if (a.mag < ONE) {\n        // Compute true inverse binary log if 0 < x < 1\n        let div = FixedTrait::ONE() / a;\n        return -log2(div);\n    }\n\n    let whole = a.mag / ONE;\n    let (msb, div) = lut::msb(whole);\n\n    if a.mag == div * ONE {\n        FixedTrait::new_unscaled(msb, false)\n    } else {\n        let norm = a / FixedTrait::new_unscaled(div, false);\n        let r8 = FixedTrait::new(596, true) * norm;\n        let r7 = (r8 + FixedTrait::new(8116, false)) * norm;\n        let r6 = (r7 + FixedTrait::new(49044, true)) * norm;\n        let r5 = (r6 + FixedTrait::new(172935, false)) * norm;\n        let r4 = (r5 + FixedTrait::new(394096, true)) * norm;\n        let r3 = (r4 + FixedTrait::new(608566, false)) * norm;\n        let r2 = (r3 + FixedTrait::new(655828, true)) * norm;\n        let r1 = (r2 + FixedTrait::new(534433, false)) * norm;\n\n        r1 + FixedTrait::new(224487, true) + FixedTrait::new_unscaled(msb, false)\n    }\n}\n\n// Calculates the base 10 log of x: log10(x)\n// self must be greater than zero\nfn log10(a: FP16x16) -> FP16x16 {\n    FixedTrait::new(19728, false) * log2(a) // log10(2) = 0.301...\n}\n\nfn lt(a: FP16x16, b: FP16x16) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\nfn mul(a: FP16x16, b: FP16x16) -> FP16x16 {\n    let prod_u128 = integer::u32_wide_mul(a.mag, b.mag);\n\n    // Re-apply sign\n    FixedTrait::new((prod_u128 / ONE.into()).try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn ne(a: @FP16x16, b: @FP16x16) -> bool {\n    (*a.mag != *b.mag) || (*a.sign != *b.sign)\n}\n\nfn neg(a: FP16x16) -> FP16x16 {\n    if a.mag == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new(a.mag, !a.sign)\n    } else {\n        FixedTrait::new(a.mag, false)\n    }\n}\n\n// Calclates the value of x^y and checks for overflow before returning\n// self is a FP16x16 point value\n// b is a FP16x16 point value\nfn pow(a: FP16x16, b: FP16x16) -> FP16x16 {\n    let (_, rem) = integer::u32_safe_divmod(b.mag, integer::u32_as_non_zero(ONE));\n\n    // use the more performant integer pow when y is an int\n    if (rem == 0) {\n        return pow_int(a, b.mag / ONE, b.sign);\n    }\n\n    // x^y = exp(y*ln(x)) for x > 0 will error for x < 0\n    exp(b * ln(a))\n}\n\n// Calclates the value of a^b and checks for overflow before returning\nfn pow_int(a: FP16x16, b: u32, sign: bool) -> FP16x16 {\n    let mut x = a;\n    let mut n = b;\n\n    if sign {\n        x = FixedTrait::ONE() / x;\n    }\n\n    if n == 0 {\n        return FixedTrait::ONE();\n    }\n\n    let mut y = FixedTrait::ONE();\n    let two = integer::u32_as_non_zero(2);\n\n    while n > 1 {\n        let (div, rem) = integer::u32_safe_divmod(n, two);\n\n        if rem == 1 {\n            y = x * y;\n        }\n\n        x = x * x;\n        n = div;\n    };\n\n    x * y\n}\n\nfn rem(a: FP16x16, b: FP16x16) -> FP16x16 {\n    a - floor(a / b) * b\n}\n\nfn round(a: FP16x16) -> FP16x16 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if (HALF <= rem) {\n        FixedTrait::new_unscaled(div + 1, a.sign)\n    } else {\n        FixedTrait::new_unscaled(div, a.sign)\n    }\n}\n\n// Calculates the square root of a FP16x16 point value\n// x must be positive\nfn sqrt(a: FP16x16) -> FP16x16 {\n    assert(a.sign == false, 'must be positive');\n\n    let root = integer::u64_sqrt(a.mag.into() * ONE.into());\n\n    FixedTrait::new(root.into(), false)\n}\n\nfn sub(a: FP16x16, b: FP16x16) -> FP16x16 {\n    add(a, -b)\n}\n\nfn sign(a: FP16x16) -> FP16x16 {\n    if a.mag == 0 {\n        FixedTrait::new(0, false)\n    } else {\n        FixedTrait::new(ONE, a.sign)\n    }\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp16x16::math::trig::{PI, HALF_PI};\n\n    use super::{\n        FixedTrait, ONE, FP16x16, ceil, floor, sqrt, round, lut, pow, exp, exp2, exp2_int, ln, log2,\n        log10, eq, add, ne, HALF\n    };\n\n    #[test]\n    fn test_into() {\n        let a = FixedTrait::<FP16x16>::new_unscaled(5, false);\n        assert(a.mag == 5 * ONE, 'invalid result');\n    }\n\n    #[test]\n    fn test_try_into_u128() {\n        // Positive unscaled\n        let a = FixedTrait::<FP16x16>::new_unscaled(5, false);\n        assert(a.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Positive scaled\n        let b = FixedTrait::<FP16x16>::new(5 * ONE, false);\n        assert(b.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Zero\n        let d = FixedTrait::<FP16x16>::new_unscaled(0, false);\n        assert(d.try_into().unwrap() == 0_u128, 'invalid result');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_negative_try_into_u128() {\n        let a = FixedTrait::<FP16x16>::new_unscaled(1, true);\n        let _a: u128 = a.try_into().unwrap();\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_acos() {\n        let a = FixedTrait::<FP16x16>::ONE();\n        assert(a.acos().into() == 0, 'invalid one');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_asin() {\n        let a = FixedTrait::ONE();\n        assert_precise(a.asin(), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(a.atan(), 72558, 'invalid two', Option::None(()));\n    }\n\n    #[test]\n    fn test_ceil() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(ceil(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_floor() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(floor(a).mag == 2 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_round() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(round(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_sqrt_fail() {\n        let a = FixedTrait::new_unscaled(25, true);\n        sqrt(a);\n    }\n\n    #[test]\n    fn test_sqrt() {\n        let mut a = FixedTrait::new_unscaled(0, false);\n        assert(sqrt(a).mag == 0, 'invalid zero root');\n        a = FixedTrait::new_unscaled(25, false);\n        assert(sqrt(a).mag == 5 * ONE, 'invalid pos root');\n    }\n\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_msb() {\n        let a = FixedTrait::<FP16x16>::new_unscaled(100, false);\n        let (msb, div) = lut::msb(a.mag / ONE);\n        assert(msb == 6, 'invalid msb');\n        assert(div == 64, 'invalid msb ceil');\n    }\n\n    #[test]\n    #[available_gas(600000)]\n    fn test_pow() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new_unscaled(4, false);\n        assert(pow(a, b).mag == 81 * ONE, 'invalid pos base power');\n    }\n\n    #[test]\n    #[available_gas(900000)]\n    fn test_pow_frac() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new(32768, false); // 0.5\n        assert_relative(\n            pow(a, b), 113512, 'invalid pos base power', Option::None(())\n        ); // 1.7320508075688772\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_exp() {\n        let a = FixedTrait::new_unscaled(2, false);\n        assert_relative(exp(a), 484249, 'invalid exp of 2', Option::None(())); // 7.389056098793725\n    }\n\n    #[test]\n    #[available_gas(400000)]\n    fn test_exp2() {\n        let a = FixedTrait::new_unscaled(5, false);\n        assert(exp2(a).mag == 2097152, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(20000)]\n    fn test_exp2_int() {\n        assert(exp2_int(5).into() == 2097152, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_ln() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        assert(ln(a).mag == 0, 'invalid ln of 1');\n\n        a = FixedTrait::new(178145, false);\n        assert_relative(ln(a), ONE.into(), 'invalid ln of 2.7...', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log2() {\n        let mut a = FixedTrait::new_unscaled(32, false);\n        assert(log2(a) == FixedTrait::new_unscaled(5, false), 'invalid log2 32');\n\n        a = FixedTrait::new_unscaled(10, false);\n        assert_relative(log2(a), 217706, 'invalid log2 10', Option::None(())); // 3.321928094887362\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log10() {\n        let a = FixedTrait::new_unscaled(100, false);\n        assert_relative(log10(a), 2 * ONE.into(), 'invalid log10', Option::None(()));\n    }\n\n    #[test]\n    fn test_eq() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = eq(@a, @b);\n        assert(c, 'invalid result');\n    }\n\n    #[test]\n    fn test_ne() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = ne(@a, @b);\n        assert(!c, 'invalid result');\n    }\n\n    #[test]\n    fn test_add() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        assert(add(a, b) == FixedTrait::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_add_eq() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a += b;\n        assert(a == FixedTrait::<FP16x16>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_sub() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        let c = a - b;\n        assert(c == FixedTrait::<FP16x16>::new_unscaled(3, false), 'false result invalid');\n    }\n\n    #[test]\n    fn test_sub_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a -= b;\n        assert(a == FixedTrait::<FP16x16>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_mul_pos() {\n        let a = FP16x16 { mag: 190054, sign: false };\n        let b = FP16x16 { mag: 190054, sign: false };\n        let c = a * b;\n        assert(c.mag == 551155, 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_neg() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        let c = a * b;\n        assert(c == FixedTrait::<FP16x16>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        a *= b;\n        assert(a == FixedTrait::<FP16x16>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_div() {\n        let a = FixedTrait::new_unscaled(10, false);\n        let b = FixedTrait::<FP16x16>::new(190054, false); // 2.9\n        let c = a / b;\n        assert(c.mag == 225986, 'invalid pos decimal'); // 3.4482758620689653\n    }\n\n    #[test]\n    fn test_le() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16>::new_unscaled(1, true);\n\n        assert(a <= a, 'a <= a');\n        assert(!(a <= b), 'a <= b');\n        assert(!(a <= c), 'a <= c');\n\n        assert(b <= a, 'b <= a');\n        assert(b <= b, 'b <= b');\n        assert(!(b <= c), 'b <= c');\n\n        assert(c <= a, 'c <= a');\n        assert(c <= b, 'c <= b');\n        assert(c <= c, 'c <= c');\n    }\n\n    #[test]\n    fn test_lt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16>::new_unscaled(1, true);\n\n        assert(!(a < a), 'a < a');\n        assert(!(a < b), 'a < b');\n        assert(!(a < c), 'a < c');\n\n        assert(b < a, 'b < a');\n        assert(!(b < b), 'b < b');\n        assert(!(b < c), 'b < c');\n\n        assert(c < a, 'c < a');\n        assert(c < b, 'c < b');\n        assert(!(c < c), 'c < c');\n    }\n\n    #[test]\n    fn test_ge() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16>::new_unscaled(1, true);\n\n        assert(a >= a, 'a >= a');\n        assert(a >= b, 'a >= b');\n        assert(a >= c, 'a >= c');\n\n        assert(!(b >= a), 'b >= a');\n        assert(b >= b, 'b >= b');\n        assert(b >= c, 'b >= c');\n\n        assert(!(c >= a), 'c >= a');\n        assert(!(c >= b), 'c >= b');\n        assert(c >= c, 'c >= c');\n    }\n\n    #[test]\n    fn test_gt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16>::new_unscaled(1, true);\n\n        assert(!(a > a), 'a > a');\n        assert(a > b, 'a > b');\n        assert(a > c, 'a > c');\n\n        assert(!(b > a), 'b > a');\n        assert(!(b > b), 'b > b');\n        assert(b > c, 'b > c');\n\n        assert(!(c > a), 'c > a');\n        assert(!(c > b), 'c > b');\n        assert(!(c > c), 'c > c');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_cos() {\n        let a = FixedTrait::<FP16x16>::new(HALF_PI, false);\n        assert(a.cos().into() == 0, 'invalid half pi');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(a.sin(), ONE.into(), 'invalid half pi', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_tan() {\n        let a = FixedTrait::<FP16x16>::new(HALF_PI / 2, false);\n        assert(a.tan().mag == 65536, 'invalid quarter pi');\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_sign() {\n        let a = FixedTrait::<FP16x16>::new(0, false);\n        assert(a.sign().mag == 0 && !a.sign().sign, 'invalid sign (0, true)');\n\n        let a = FixedTrait::<FP16x16>::new(HALF, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (HALF, true)');\n\n        let a = FixedTrait::<FP16x16>::new(HALF, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (HALF, false)');\n\n        let a = FixedTrait::<FP16x16>::new(ONE, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (ONE, true)');\n\n        let a = FixedTrait::<FP16x16>::new(ONE, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (ONE, false)');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(2000000)]\n    fn test_sign_fail() {\n        let a = FixedTrait::<FP16x16>::new(HALF, true);\n        assert(a.sign().mag != ONE && !a.sign().sign, 'invalid sign (HALF, true)');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/erf.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16::core::{ONE, FP16x16, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp16x16::math::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u32 = 100;\nconst ROUND_CHECK_NUMBER: u32 = 10;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u32 = 229376;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u32 = 131072;\n\nfn erf(x: FP16x16) -> FP16x16 {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u32 = 0;\n\n    if x.mag < MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP16x16 { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/hyp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, TWO, FP16x16, FP16x16Impl, FP16x16Add, FP16x16AddEq, FP16x16Sub, FP16x16Mul,\n    FP16x16MulEq, FP16x16TryIntoU128, FP16x16PartialEq, FP16x16PartialOrd, FP16x16SubEq, FP16x16Neg,\n    FP16x16Div, FP16x16IntoFelt252, FixedTrait\n};\n\n// Calculates hyperbolic cosine of a (fixed point)\nfn cosh(a: FP16x16) -> FP16x16 {\n    let ea = a.exp();\n\n    (ea + (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic sine of a (fixed point)\nfn sinh(a: FP16x16) -> FP16x16 {\n    let ea = a.exp();\n\n    (ea - (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic tangent of a (fixed point)\nfn tanh(a: FP16x16) -> FP16x16 {\n    let ea = a.exp();\n    let ea_i = FixedTrait::ONE() / ea;\n\n    (ea - ea_i) / (ea + ea_i)\n}\n\n// Calculates inverse hyperbolic cosine of a (fixed point)\nfn acosh(a: FP16x16) -> FP16x16 {\n    let root = (a * a - FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic sine of a (fixed point)\nfn asinh(a: FP16x16) -> FP16x16 {\n    let root = (a * a + FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic tangent of a (fixed point)\nfn atanh(a: FP16x16) -> FP16x16 {\n    let one = FixedTrait::ONE();\n    let ln_arg = (one + a) / (one - a);\n\n    ln_arg.ln() / FixedTrait::new(TWO, false)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16::helpers::assert_precise;\n\n    use super::{FixedTrait, TWO, cosh, ONE, sinh, tanh, acosh, asinh, atanh, HALF};\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_cosh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(cosh(a), 246550, 'invalid two', Option::None(())); // 3.5954653836066\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 101127, 'invalid one', Option::None(())); // 1.42428174592510\n\n        let a = FixedTrait::ZERO();\n        assert_precise(cosh(a), ONE.into(), 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 101127, 'invalid neg one', Option::None(())); // 1.42428174592510\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(cosh(a), 246568, 'invalid neg two', Option::None(())); // 3.5954653836066\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_sinh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(sinh(a), 237681, 'invalid two', Option::None(())); // 3.48973469357602\n\n        let a = FixedTrait::ONE();\n        assert_precise(sinh(a), 77018, 'invalid one', Option::None(())); // 1.13687593250230\n\n        let a = FixedTrait::ZERO();\n        assert(sinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(sinh(a), -77018, 'invalid neg one', Option::None(())); // -1.13687593250230\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(sinh(a), -237699, 'invalid neg two', Option::None(())); // -3.48973469357602\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_tanh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(tanh(a), 63179, 'invalid two', Option::None(())); // 0.75314654693321\n\n        let a = FixedTrait::ONE();\n        assert_precise(tanh(a), 49912, 'invalid one', Option::None(())); // 0.59499543433175\n\n        let a = FixedTrait::ZERO();\n        assert(tanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(tanh(a), -49912, 'invalid neg one', Option::None(())); // -0.59499543433175\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(tanh(a), -63179, 'invalid neg two', Option::None(())); // 0.75314654693321\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_acosh() {\n        let a = FixedTrait::new(246559, false); // 3.5954653836066\n        assert_precise(acosh(a), 131072, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(101127, false); // 1.42428174592510\n        assert_precise(acosh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ONE(); // 1\n        assert(acosh(a).into() == 0, 'invalid zero');\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_asinh() {\n        let a = FixedTrait::new(237690, false); // 3.48973469357602\n        assert_precise(asinh(a), 131072, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(77018, false); // 1.13687593250230\n        assert_precise(asinh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(asinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(77018, true); // -1.13687593250230\n        assert_precise(asinh(a), -ONE.into(), 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(237690, true); // -3.48973469357602\n        assert_precise(asinh(a), -131017, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_atanh() {\n        let a = FixedTrait::new(58982, false); // 0.9\n        assert_precise(atanh(a), 96483, 'invalid 0.9', Option::None(())); // 1.36892147623689\n\n        let a = FixedTrait::new(HALF, false); // 0.5\n        assert_precise(atanh(a), 35999, 'invalid half', Option::None(())); // 0.42914542526098\n\n        let a = FixedTrait::ZERO();\n        assert(atanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(HALF, true); // 0.5\n        assert_precise(atanh(a), -35999, 'invalid neg half', Option::None(())); // 0.42914542526098\n\n        let a = FixedTrait::new(58982, true); // 0.9\n        assert_precise(atanh(a), -96483, 'invalid -0.9', Option::None(())); // 1.36892147623689\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16::core::ONE;\n\n// Calculates the most significant bit\nfn msb(whole: u32) -> (u32, u32) {\n    if whole < 256 {\n        if whole < 2 {\n            return (0, 1);\n        }\n        if whole < 4 {\n            return (1, 2);\n        }\n        if whole < 8 {\n            return (2, 4);\n        }\n        if whole < 16 {\n            return (3, 8);\n        }\n        if whole < 32 {\n            return (4, 16);\n        }\n        if whole < 64 {\n            return (5, 32);\n        }\n        if whole < 128 {\n            return (6, 64);\n        }\n        if whole < 256 {\n            return (7, 128);\n        }\n    } else if whole < 65536 {\n        if whole < 512 {\n            return (8, 256);\n        }\n        if whole < 1024 {\n            return (9, 512);\n        }\n        if whole < 2048 {\n            return (10, 1024);\n        }\n        if whole < 4096 {\n            return (11, 2048);\n        }\n        if whole < 8192 {\n            return (12, 4096);\n        }\n        if whole < 16384 {\n            return (13, 8192);\n        }\n        if whole < 32768 {\n            return (14, 16384);\n        }\n        if whole < 65536 {\n            return (15, 32768);\n        }\n    }\n\n    (16, 65536)\n}\n\nfn exp2(exp: u32) -> u32 {\n    if exp <= 16 {\n        if exp == 0 {\n            return 1;\n        }\n        if exp == 1 {\n            return 2;\n        }\n        if exp == 2 {\n            return 4;\n        }\n        if exp == 3 {\n            return 8;\n        }\n        if exp == 4 {\n            return 16;\n        }\n        if exp == 5 {\n            return 32;\n        }\n        if exp == 6 {\n            return 64;\n        }\n        if exp == 7 {\n            return 128;\n        }\n        if exp == 8 {\n            return 256;\n        }\n        if exp == 9 {\n            return 512;\n        }\n        if exp == 10 {\n            return 1024;\n        }\n        if exp == 11 {\n            return 2048;\n        }\n        if exp == 12 {\n            return 4096;\n        }\n        if exp == 13 {\n            return 8192;\n        }\n        if exp == 14 {\n            return 16384;\n        }\n        if exp == 15 {\n            return 32768;\n        }\n        if exp == 16 {\n            return 65536;\n        }\n    }\n\n    65536\n}\n\nfn sin(a: u32) -> (u32, u32, u32) {\n    let slot = a / 402;\n\n    if slot < 128 {\n        if slot < 64 {\n            if slot < 32 {\n                if slot < 16 {\n                    if slot == 0 {\n                        return (0, 0, 402);\n                    }\n                    if slot == 1 {\n                        return (402, 402, 804);\n                    }\n                    if slot == 2 {\n                        return (804, 804, 1206);\n                    }\n                    if slot == 3 {\n                        return (1206, 1206, 1608);\n                    }\n                    if slot == 4 {\n                        return (1608, 1608, 2010);\n                    }\n                    if slot == 5 {\n                        return (2011, 2010, 2412);\n                    }\n                    if slot == 6 {\n                        return (2413, 2412, 2814);\n                    }\n                    if slot == 7 {\n                        return (2815, 2814, 3216);\n                    }\n                    if slot == 8 {\n                        return (3217, 3216, 3617);\n                    }\n                    if slot == 9 {\n                        return (3619, 3617, 4019);\n                    }\n                    if slot == 10 {\n                        return (4023, 4019, 4420);\n                    }\n                    if slot == 11 {\n                        return (4423, 4420, 4821);\n                    }\n                    if slot == 12 {\n                        return (4825, 4821, 5222);\n                    }\n                    if slot == 13 {\n                        return (5228, 5222, 5623);\n                    }\n                    if slot == 14 {\n                        return (5630, 5623, 6023);\n                    }\n                    if slot == 15 {\n                        return (6032, 6023, 6424);\n                    }\n                } else {\n                    if slot == 16 {\n                        return (6434, 6424, 6824);\n                    }\n                    if slot == 17 {\n                        return (6836, 6824, 7224);\n                    }\n                    if slot == 18 {\n                        return (7238, 7224, 7623);\n                    }\n                    if slot == 19 {\n                        return (7640, 7623, 8022);\n                    }\n                    if slot == 20 {\n                        return (8042, 8022, 8421);\n                    }\n                    if slot == 21 {\n                        return (8445, 8421, 8820);\n                    }\n                    if slot == 22 {\n                        return (8847, 8820, 9218);\n                    }\n                    if slot == 23 {\n                        return (9249, 9218, 9616);\n                    }\n                    if slot == 24 {\n                        return (9651, 9616, 10014);\n                    }\n                    if slot == 25 {\n                        return (10053, 10014, 10411);\n                    }\n                    if slot == 26 {\n                        return (10455, 10411, 10808);\n                    }\n                    if slot == 27 {\n                        return (10857, 10808, 11204);\n                    }\n                    if slot == 28 {\n                        return (11259, 11204, 11600);\n                    }\n                    if slot == 29 {\n                        return (11662, 11600, 11996);\n                    }\n                    if slot == 30 {\n                        return (12064, 11996, 12391);\n                    }\n                    if slot == 31 {\n                        return (12466, 12391, 12785);\n                    }\n                }\n            } else {\n                if slot < 48 {\n                    if slot == 32 {\n                        return (12868, 12785, 13180);\n                    }\n                    if slot == 33 {\n                        return (13270, 13180, 13573);\n                    }\n                    if slot == 34 {\n                        return (13672, 13573, 13966);\n                    }\n                    if slot == 35 {\n                        return (14074, 13966, 14359);\n                    }\n                    if slot == 36 {\n                        return (14476, 14359, 14751);\n                    }\n                    if slot == 37 {\n                        return (14879, 14751, 15143);\n                    }\n                    if slot == 38 {\n                        return (15281, 15143, 15534);\n                    }\n                    if slot == 39 {\n                        return (15683, 15534, 15924);\n                    }\n                    if slot == 40 {\n                        return (16081, 15924, 16314);\n                    }\n                    if slot == 41 {\n                        return (16487, 16314, 16703);\n                    }\n                    if slot == 42 {\n                        return (16889, 16703, 17091);\n                    }\n                    if slot == 43 {\n                        return (17291, 17091, 17479);\n                    }\n                    if slot == 44 {\n                        return (17693, 17479, 17867);\n                    }\n                    if slot == 45 {\n                        return (18096, 17867, 18253);\n                    }\n                    if slot == 46 {\n                        return (18498, 18253, 18639);\n                    }\n                    if slot == 47 {\n                        return (18900, 18639, 19024);\n                    }\n                } else {\n                    if slot == 48 {\n                        return (19302, 19024, 19409);\n                    }\n                    if slot == 49 {\n                        return (19704, 19409, 19792);\n                    }\n                    if slot == 50 {\n                        return (20113, 19792, 20175);\n                    }\n                    if slot == 51 {\n                        return (20508, 20175, 20557);\n                    }\n                    if slot == 52 {\n                        return (20910, 20557, 20939);\n                    }\n                    if slot == 53 {\n                        return (21313, 20939, 21320);\n                    }\n                    if slot == 54 {\n                        return (21715, 21320, 21699);\n                    }\n                    if slot == 55 {\n                        return (22117, 21699, 22078);\n                    }\n                    if slot == 56 {\n                        return (22519, 22078, 22457);\n                    }\n                    if slot == 57 {\n                        return (22921, 22457, 22834);\n                    }\n                    if slot == 58 {\n                        return (23323, 22834, 23210);\n                    }\n                    if slot == 59 {\n                        return (23725, 23210, 23586);\n                    }\n                    if slot == 60 {\n                        return (24127, 23586, 23961);\n                    }\n                    if slot == 61 {\n                        return (24530, 23961, 24335);\n                    }\n                    if slot == 62 {\n                        return (24932, 24335, 24708);\n                    }\n                    if slot == 63 {\n                        return (25334, 24708, 25080);\n                    }\n                }\n            }\n        } else {\n            if slot < 96 {\n                if slot < 80 {\n                    if slot == 64 {\n                        return (25736, 25080, 25451);\n                    }\n                    if slot == 65 {\n                        return (26138, 25451, 25821);\n                    }\n                    if slot == 66 {\n                        return (26540, 25821, 26190);\n                    }\n                    if slot == 67 {\n                        return (26942, 26190, 26558);\n                    }\n                    if slot == 68 {\n                        return (27344, 26558, 26925);\n                    }\n                    if slot == 69 {\n                        return (27747, 26925, 27291);\n                    }\n                    if slot == 70 {\n                        return (28149, 27291, 27656);\n                    }\n                    if slot == 71 {\n                        return (28551, 27656, 28020);\n                    }\n                    if slot == 72 {\n                        return (28953, 28020, 28383);\n                    }\n                    if slot == 73 {\n                        return (29355, 28383, 28745);\n                    }\n                    if slot == 74 {\n                        return (29757, 28745, 29106);\n                    }\n                    if slot == 75 {\n                        return (30159, 29106, 29466);\n                    }\n                    if slot == 76 {\n                        return (30561, 29466, 29824);\n                    }\n                    if slot == 77 {\n                        return (30964, 29824, 30182);\n                    }\n                    if slot == 78 {\n                        return (31366, 30182, 30538);\n                    }\n                    if slot == 79 {\n                        return (31768, 30538, 30893);\n                    }\n                } else {\n                    if slot == 80 {\n                        return (32171, 30893, 31248);\n                    }\n                    if slot == 81 {\n                        return (32572, 31248, 31600);\n                    }\n                    if slot == 82 {\n                        return (32974, 31600, 31952);\n                    }\n                    if slot == 83 {\n                        return (33376, 31952, 32303);\n                    }\n                    if slot == 84 {\n                        return (33778, 32303, 32652);\n                    }\n                    if slot == 85 {\n                        return (34181, 32652, 33000);\n                    }\n                    if slot == 86 {\n                        return (34583, 33000, 33347);\n                    }\n                    if slot == 87 {\n                        return (34985, 33347, 33692);\n                    }\n                    if slot == 88 {\n                        return (35387, 33692, 34037);\n                    }\n                    if slot == 89 {\n                        return (35789, 34037, 34380);\n                    }\n                    if slot == 90 {\n                        return (36194, 34380, 34721);\n                    }\n                    if slot == 91 {\n                        return (36593, 34721, 35062);\n                    }\n                    if slot == 92 {\n                        return (36995, 35062, 35401);\n                    }\n                    if slot == 93 {\n                        return (37398, 35401, 35738);\n                    }\n                    if slot == 94 {\n                        return (37800, 35738, 36075);\n                    }\n                    if slot == 95 {\n                        return (38202, 36075, 36410);\n                    }\n                }\n            } else {\n                if slot < 112 {\n                    if slot == 96 {\n                        return (38604, 36410, 36744);\n                    }\n                    if slot == 97 {\n                        return (39006, 36744, 37076);\n                    }\n                    if slot == 98 {\n                        return (39408, 37076, 37407);\n                    }\n                    if slot == 99 {\n                        return (39810, 37407, 37736);\n                    }\n                    if slot == 100 {\n                        return (40227, 37736, 38064);\n                    }\n                    if slot == 101 {\n                        return (40615, 38064, 38391);\n                    }\n                    if slot == 102 {\n                        return (41017, 38391, 38716);\n                    }\n                    if slot == 103 {\n                        return (41419, 38716, 39040);\n                    }\n                    if slot == 104 {\n                        return (41821, 39040, 39362);\n                    }\n                    if slot == 105 {\n                        return (42223, 39362, 39683);\n                    }\n                    if slot == 106 {\n                        return (42625, 39683, 40002);\n                    }\n                    if slot == 107 {\n                        return (43027, 40002, 40320);\n                    }\n                    if slot == 108 {\n                        return (43429, 40320, 40636);\n                    }\n                    if slot == 109 {\n                        return (43832, 40636, 40951);\n                    }\n                    if slot == 110 {\n                        return (44234, 40951, 41264);\n                    }\n                    if slot == 111 {\n                        return (44636, 41264, 41576);\n                    }\n                } else {\n                    if slot == 112 {\n                        return (45038, 41576, 41886);\n                    }\n                    if slot == 113 {\n                        return (45440, 41886, 42194);\n                    }\n                    if slot == 114 {\n                        return (45842, 42194, 42501);\n                    }\n                    if slot == 115 {\n                        return (46244, 42501, 42806);\n                    }\n                    if slot == 116 {\n                        return (46646, 42806, 43110);\n                    }\n                    if slot == 117 {\n                        return (47048, 43110, 43412);\n                    }\n                    if slot == 118 {\n                        return (47451, 43412, 43713);\n                    }\n                    if slot == 119 {\n                        return (47853, 43713, 44011);\n                    }\n                    if slot == 120 {\n                        return (48252, 44011, 44308);\n                    }\n                    if slot == 121 {\n                        return (48657, 44308, 44604);\n                    }\n                    if slot == 122 {\n                        return (49059, 44604, 44898);\n                    }\n                    if slot == 123 {\n                        return (49461, 44898, 45190);\n                    }\n                    if slot == 124 {\n                        return (49863, 45190, 45480);\n                    }\n                    if slot == 125 {\n                        return (50265, 45480, 45769);\n                    }\n                    if slot == 126 {\n                        return (50668, 45769, 46056);\n                    }\n                    if slot == 127 {\n                        return (51070, 46056, 46341);\n                    }\n                }\n            }\n        }\n    } else {\n        if slot < 192 {\n            if slot < 160 {\n                if slot < 144 {\n                    if slot == 128 {\n                        return (51472, 46341, 46624);\n                    }\n                    if slot == 129 {\n                        return (51874, 46624, 46906);\n                    }\n                    if slot == 130 {\n                        return (52285, 46906, 47186);\n                    }\n                    if slot == 131 {\n                        return (52678, 47186, 47464);\n                    }\n                    if slot == 132 {\n                        return (53080, 47464, 47741);\n                    }\n                    if slot == 133 {\n                        return (53482, 47741, 48015);\n                    }\n                    if slot == 134 {\n                        return (53885, 48015, 48288);\n                    }\n                    if slot == 135 {\n                        return (54287, 48288, 48559);\n                    }\n                    if slot == 136 {\n                        return (54689, 48559, 48828);\n                    }\n                    if slot == 137 {\n                        return (55091, 48828, 49095);\n                    }\n                    if slot == 138 {\n                        return (55493, 49095, 49361);\n                    }\n                    if slot == 139 {\n                        return (55895, 49361, 49624);\n                    }\n                    if slot == 140 {\n                        return (56297, 49624, 49886);\n                    }\n                    if slot == 141 {\n                        return (56699, 49886, 50146);\n                    }\n                    if slot == 142 {\n                        return (57102, 50146, 50404);\n                    }\n                    if slot == 143 {\n                        return (57504, 50404, 50660);\n                    }\n                } else {\n                    if slot == 144 {\n                        return (57906, 50660, 50914);\n                    }\n                    if slot == 145 {\n                        return (58308, 50914, 51166);\n                    }\n                    if slot == 146 {\n                        return (58710, 51166, 51417);\n                    }\n                    if slot == 147 {\n                        return (59112, 51417, 51665);\n                    }\n                    if slot == 148 {\n                        return (59514, 51665, 51911);\n                    }\n                    if slot == 149 {\n                        return (59916, 51911, 52156);\n                    }\n                    if slot == 150 {\n                        return (60320, 52156, 52398);\n                    }\n                    if slot == 151 {\n                        return (60721, 52398, 52639);\n                    }\n                    if slot == 152 {\n                        return (61123, 52639, 52878);\n                    }\n                    if slot == 153 {\n                        return (61525, 52878, 53114);\n                    }\n                    if slot == 154 {\n                        return (61927, 53114, 53349);\n                    }\n                    if slot == 155 {\n                        return (62329, 53349, 53581);\n                    }\n                    if slot == 156 {\n                        return (62731, 53581, 53812);\n                    }\n                    if slot == 157 {\n                        return (63133, 53812, 54040);\n                    }\n                    if slot == 158 {\n                        return (63536, 54040, 54267);\n                    }\n                    if slot == 159 {\n                        return (63938, 54267, 54491);\n                    }\n                    if slot == 160 {\n                        return (64343, 54491, 54714);\n                    }\n                }\n            } else {\n                if slot < 176 {\n                    if slot == 161 {\n                        return (64742, 54714, 54934);\n                    }\n                    if slot == 162 {\n                        return (65144, 54934, 55152);\n                    }\n                    if slot == 163 {\n                        return (65546, 55152, 55368);\n                    }\n                    if slot == 164 {\n                        return (65948, 55368, 55582);\n                    }\n                    if slot == 165 {\n                        return (66350, 55582, 55794);\n                    }\n                    if slot == 166 {\n                        return (66753, 55794, 56004);\n                    }\n                    if slot == 167 {\n                        return (67155, 56004, 56212);\n                    }\n                    if slot == 168 {\n                        return (67557, 56212, 56418);\n                    }\n                    if slot == 169 {\n                        return (67959, 56418, 56621);\n                    }\n                    if slot == 170 {\n                        return (68361, 56621, 56823);\n                    }\n                    if slot == 171 {\n                        return (68763, 56823, 57022);\n                    }\n                    if slot == 172 {\n                        return (69165, 57022, 57219);\n                    }\n                    if slot == 173 {\n                        return (69567, 57219, 57414);\n                    }\n                    if slot == 174 {\n                        return (69970, 57414, 57607);\n                    }\n                    if slot == 175 {\n                        return (70372, 57607, 57798);\n                    }\n                } else {\n                    if slot == 176 {\n                        return (70774, 57798, 57986);\n                    }\n                    if slot == 177 {\n                        return (71176, 57986, 58172);\n                    }\n                    if slot == 178 {\n                        return (71578, 58172, 58356);\n                    }\n                    if slot == 179 {\n                        return (71980, 58356, 58538);\n                    }\n                    if slot == 180 {\n                        return (72382, 58538, 58718);\n                    }\n                    if slot == 181 {\n                        return (72784, 58718, 58896);\n                    }\n                    if slot == 182 {\n                        return (73187, 58896, 59071);\n                    }\n                    if slot == 183 {\n                        return (73589, 59071, 59244);\n                    }\n                    if slot == 184 {\n                        return (73991, 59244, 59415);\n                    }\n                    if slot == 185 {\n                        return (74393, 59415, 59583);\n                    }\n                    if slot == 186 {\n                        return (74795, 59583, 59750);\n                    }\n                    if slot == 187 {\n                        return (75197, 59750, 59914);\n                    }\n                    if slot == 188 {\n                        return (75599, 59914, 60075);\n                    }\n                    if slot == 189 {\n                        return (76001, 60075, 60235);\n                    }\n                    if slot == 190 {\n                        return (76401, 60235, 60392);\n                    }\n                    if slot == 191 {\n                        return (76806, 60392, 60547);\n                    }\n                }\n            }\n        } else {\n            if slot < 224 {\n                if slot < 208 {\n                    if slot == 192 {\n                        return (77208, 60547, 60700);\n                    }\n                    if slot == 193 {\n                        return (77610, 60700, 60851);\n                    }\n                    if slot == 194 {\n                        return (78012, 60851, 60999);\n                    }\n                    if slot == 195 {\n                        return (78414, 60999, 61145);\n                    }\n                    if slot == 196 {\n                        return (78816, 61145, 61288);\n                    }\n                    if slot == 197 {\n                        return (79218, 61288, 61429);\n                    }\n                    if slot == 198 {\n                        return (79621, 61429, 61568);\n                    }\n                    if slot == 199 {\n                        return (80023, 61568, 61705);\n                    }\n                    if slot == 200 {\n                        return (80423, 61705, 61839);\n                    }\n                    if slot == 201 {\n                        return (80827, 61839, 61971);\n                    }\n                    if slot == 202 {\n                        return (81229, 61971, 62101);\n                    }\n                    if slot == 203 {\n                        return (81631, 62101, 62228);\n                    }\n                    if slot == 204 {\n                        return (82033, 62228, 62353);\n                    }\n                    if slot == 205 {\n                        return (82435, 62353, 62476);\n                    }\n                    if slot == 206 {\n                        return (82838, 62476, 62596);\n                    }\n                    if slot == 207 {\n                        return (83240, 62596, 62714);\n                    }\n                } else {\n                    if slot == 208 {\n                        return (83642, 62714, 62830);\n                    }\n                    if slot == 209 {\n                        return (84044, 62830, 62943);\n                    }\n                    if slot == 210 {\n                        return (84446, 62943, 63054);\n                    }\n                    if slot == 211 {\n                        return (84848, 63054, 63162);\n                    }\n                    if slot == 212 {\n                        return (85250, 63162, 63268);\n                    }\n                    if slot == 213 {\n                        return (85652, 63268, 63372);\n                    }\n                    if slot == 214 {\n                        return (86055, 63372, 63473);\n                    }\n                    if slot == 215 {\n                        return (86457, 63473, 63572);\n                    }\n                    if slot == 216 {\n                        return (86859, 63572, 63668);\n                    }\n                    if slot == 217 {\n                        return (87261, 63668, 63763);\n                    }\n                    if slot == 218 {\n                        return (87663, 63763, 63854);\n                    }\n                    if slot == 219 {\n                        return (88065, 63854, 63944);\n                    }\n                    if slot == 220 {\n                        return (88467, 63944, 64031);\n                    }\n                    if slot == 221 {\n                        return (88869, 64031, 64115);\n                    }\n                    if slot == 222 {\n                        return (89271, 64115, 64197);\n                    }\n                    if slot == 223 {\n                        return (89674, 64197, 64277);\n                    }\n                }\n            } else {\n                if slot < 240 {\n                    if slot == 224 {\n                        return (90076, 64277, 64354);\n                    }\n                    if slot == 225 {\n                        return (90478, 64354, 64429);\n                    }\n                    if slot == 226 {\n                        return (90880, 64429, 64501);\n                    }\n                    if slot == 227 {\n                        return (91282, 64501, 64571);\n                    }\n                    if slot == 228 {\n                        return (91684, 64571, 64639);\n                    }\n                    if slot == 229 {\n                        return (92086, 64639, 64704);\n                    }\n                    if slot == 230 {\n                        return (92491, 64704, 64766);\n                    }\n                    if slot == 231 {\n                        return (92891, 64766, 64827);\n                    }\n                    if slot == 232 {\n                        return (93293, 64827, 64884);\n                    }\n                    if slot == 233 {\n                        return (93695, 64884, 64940);\n                    }\n                    if slot == 234 {\n                        return (94097, 64940, 64993);\n                    }\n                    if slot == 235 {\n                        return (94499, 64993, 65043);\n                    }\n                    if slot == 236 {\n                        return (94901, 65043, 65091);\n                    }\n                    if slot == 237 {\n                        return (95303, 65091, 65137);\n                    }\n                    if slot == 238 {\n                        return (95705, 65137, 65180);\n                    }\n                    if slot == 239 {\n                        return (96108, 65180, 65220);\n                    }\n                } else {\n                    if slot == 240 {\n                        return (96514, 65220, 65259);\n                    }\n                    if slot == 241 {\n                        return (96912, 65259, 65294);\n                    }\n                    if slot == 242 {\n                        return (97314, 65294, 65328);\n                    }\n                    if slot == 243 {\n                        return (97716, 65328, 65358);\n                    }\n                    if slot == 244 {\n                        return (98118, 65358, 65387);\n                    }\n                    if slot == 245 {\n                        return (98520, 65387, 65413);\n                    }\n                    if slot == 246 {\n                        return (98922, 65413, 65436);\n                    }\n                    if slot == 247 {\n                        return (99325, 65436, 65457);\n                    }\n                    if slot == 248 {\n                        return (99727, 65457, 65476);\n                    }\n                    if slot == 249 {\n                        return (100129, 65476, 65492);\n                    }\n                    if slot == 250 {\n                        return (100531, 65492, 65505);\n                    }\n                    if slot == 251 {\n                        return (100933, 65505, 65516);\n                    }\n                    if slot == 252 {\n                        return (101335, 65516, 65525);\n                    }\n                    if slot == 253 {\n                        return (101737, 65525, 65531);\n                    }\n                    if slot == 254 {\n                        return (102139, 65531, 65535);\n                    }\n                }\n            }\n        }\n    }\n\n    (102542, 65535, 65536)\n}\n\nfn atan(a: u32) -> (u32, u32, u32) {\n    let slot = a / 459;\n\n    if slot == 0 {\n        return (0, 0, 459);\n    }\n    if slot == 1 {\n        return (459, 459, 917);\n    }\n    if slot == 2 {\n        return (918, 917, 1376);\n    }\n    if slot == 3 {\n        return (1376, 1376, 1835);\n    }\n    if slot == 4 {\n        return (1835, 1835, 2293);\n    }\n    if slot == 5 {\n        return (2294, 2293, 2751);\n    }\n    if slot == 6 {\n        return (2753, 2751, 3209);\n    }\n    if slot == 7 {\n        return (3211, 3209, 3666);\n    }\n    if slot == 8 {\n        return (3670, 3666, 4123);\n    }\n    if slot == 9 {\n        return (4129, 4123, 4580);\n    }\n    if slot == 10 {\n        return (4591, 4580, 5036);\n    }\n    if slot == 11 {\n        return (5046, 5036, 5492);\n    }\n    if slot == 12 {\n        return (5505, 5492, 5947);\n    }\n    if slot == 13 {\n        return (5964, 5947, 6402);\n    }\n    if slot == 14 {\n        return (6423, 6402, 6856);\n    }\n    if slot == 15 {\n        return (6881, 6856, 7310);\n    }\n    if slot == 16 {\n        return (7340, 7310, 7762);\n    }\n    if slot == 17 {\n        return (7799, 7762, 8214);\n    }\n    if slot == 18 {\n        return (8258, 8214, 8665);\n    }\n    if slot == 19 {\n        return (8716, 8665, 9116);\n    }\n    if slot == 20 {\n        return (9181, 9116, 9565);\n    }\n    if slot == 21 {\n        return (9634, 9565, 10014);\n    }\n    if slot == 22 {\n        return (10093, 10014, 10462);\n    }\n    if slot == 23 {\n        return (10551, 10462, 10908);\n    }\n    if slot == 24 {\n        return (11010, 10908, 11354);\n    }\n    if slot == 25 {\n        return (11469, 11354, 11798);\n    }\n    if slot == 26 {\n        return (11928, 11798, 12242);\n    }\n    if slot == 27 {\n        return (12386, 12242, 12684);\n    }\n    if slot == 28 {\n        return (12845, 12684, 13125);\n    }\n    if slot == 29 {\n        return (13304, 13125, 13565);\n    }\n    if slot == 30 {\n        return (13762, 13565, 14004);\n    }\n    if slot == 31 {\n        return (14221, 14004, 14442);\n    }\n    if slot == 32 {\n        return (14680, 14442, 14878);\n    }\n    if slot == 33 {\n        return (15139, 14878, 15313);\n    }\n    if slot == 34 {\n        return (15598, 15313, 15746);\n    }\n    if slot == 35 {\n        return (16056, 15746, 16178);\n    }\n    if slot == 36 {\n        return (16515, 16178, 16609);\n    }\n    if slot == 37 {\n        return (16974, 16609, 17038);\n    }\n    if slot == 38 {\n        return (17433, 17038, 17466);\n    }\n    if slot == 39 {\n        return (17891, 17466, 17892);\n    }\n    if slot == 40 {\n        return (18353, 17892, 18317);\n    }\n    if slot == 41 {\n        return (18809, 18317, 18740);\n    }\n    if slot == 42 {\n        return (19268, 18740, 19161);\n    }\n    if slot == 43 {\n        return (19726, 19161, 19581);\n    }\n    if slot == 44 {\n        return (20185, 19581, 19999);\n    }\n    if slot == 45 {\n        return (20644, 19999, 20416);\n    }\n    if slot == 46 {\n        return (21103, 20416, 20830);\n    }\n    if slot == 47 {\n        return (21561, 20830, 21243);\n    }\n    if slot == 48 {\n        return (22020, 21243, 21655);\n    }\n    if slot == 49 {\n        return (22479, 21655, 22064);\n    }\n    if slot == 50 {\n        return (22944, 22064, 22472);\n    }\n    if slot == 51 {\n        return (23396, 22472, 22878);\n    }\n    if slot == 52 {\n        return (23855, 22878, 23282);\n    }\n    if slot == 53 {\n        return (24314, 23282, 23685);\n    }\n    if slot == 54 {\n        return (24773, 23685, 24085);\n    }\n    if slot == 55 {\n        return (25231, 24085, 24484);\n    }\n    if slot == 56 {\n        return (25690, 24484, 24880);\n    }\n    if slot == 57 {\n        return (26149, 24880, 25275);\n    }\n    if slot == 58 {\n        return (26608, 25275, 25668);\n    }\n    if slot == 59 {\n        return (27066, 25668, 26059);\n    }\n    if slot == 60 {\n        return (27534, 26059, 26448);\n    }\n    if slot == 61 {\n        return (27984, 26448, 26835);\n    }\n    if slot == 62 {\n        return (28443, 26835, 27220);\n    }\n    if slot == 63 {\n        return (28901, 27220, 27603);\n    }\n    if slot == 64 {\n        return (29360, 27603, 27984);\n    }\n    if slot == 65 {\n        return (29819, 27984, 28363);\n    }\n    if slot == 66 {\n        return (30278, 28363, 28740);\n    }\n    if slot == 67 {\n        return (30736, 28740, 29115);\n    }\n    if slot == 68 {\n        return (31195, 29115, 29488);\n    }\n    if slot == 69 {\n        return (31654, 29488, 29859);\n    }\n    if slot == 70 {\n        return (32113, 29859, 30228);\n    }\n    if slot == 71 {\n        return (32571, 30228, 30595);\n    }\n    if slot == 72 {\n        return (33030, 30595, 30960);\n    }\n    if slot == 73 {\n        return (33489, 30960, 31323);\n    }\n    if slot == 74 {\n        return (33948, 31323, 31683);\n    }\n    if slot == 75 {\n        return (34406, 31683, 32042);\n    }\n    if slot == 76 {\n        return (34865, 32042, 32398);\n    }\n    if slot == 77 {\n        return (35324, 32398, 32753);\n    }\n    if slot == 78 {\n        return (35783, 32753, 33105);\n    }\n    if slot == 79 {\n        return (36241, 33105, 33455);\n    }\n    if slot == 80 {\n        return (36700, 33455, 33804);\n    }\n    if slot == 81 {\n        return (37159, 33804, 34150);\n    }\n    if slot == 82 {\n        return (37618, 34150, 34494);\n    }\n    if slot == 83 {\n        return (38076, 34494, 34836);\n    }\n    if slot == 84 {\n        return (38535, 34836, 35175);\n    }\n    if slot == 85 {\n        return (38994, 35175, 35513);\n    }\n    if slot == 86 {\n        return (39453, 35513, 35849);\n    }\n    if slot == 87 {\n        return (39911, 35849, 36183);\n    }\n    if slot == 88 {\n        return (40370, 36183, 36514);\n    }\n    if slot == 89 {\n        return (40829, 36514, 36843);\n    }\n    if slot == 90 {\n        return (41288, 36843, 37171);\n    }\n    if slot == 91 {\n        return (41746, 37171, 37496);\n    }\n    if slot == 92 {\n        return (42205, 37496, 37819);\n    }\n    if slot == 93 {\n        return (42664, 37819, 38141);\n    }\n    if slot == 94 {\n        return (43123, 38141, 38460);\n    }\n    if slot == 95 {\n        return (43581, 38460, 38777);\n    }\n    if slot == 96 {\n        return (44040, 38777, 39092);\n    }\n    if slot == 97 {\n        return (44499, 39092, 39405);\n    }\n    if slot == 98 {\n        return (44958, 39405, 39716);\n    }\n\n    (45416, 39716, 40025)\n}\n\nfn erf_lut(x: u32) -> u32 {\n    // Construct the erf lookup table\n    if x <= 5898 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 655 {\n            return 739;\n        }\n        if x <= 1310 {\n            return 1478;\n        }\n        if x <= 1966 {\n            return 2217;\n        }\n        if x <= 2621 {\n            return 2956;\n        }\n        if x <= 3276 {\n            return 3694;\n        }\n        if x <= 3932 {\n            return 4431;\n        }\n        if x <= 4587 {\n            return 5168;\n        }\n        if x <= 5242 {\n            return 5903;\n        }\n        if x <= 5898 {\n            return 6637;\n        }\n    }\n    if x <= 12451 {\n        if x <= 6553 {\n            return 7370;\n        }\n        if x <= 7208 {\n            return 8101;\n        }\n        if x <= 7864 {\n            return 8831;\n        }\n        if x <= 8519 {\n            return 9559;\n        }\n        if x <= 9175 {\n            return 10285;\n        }\n        if x <= 9830 {\n            return 11009;\n        }\n        if x <= 10485 {\n            return 11731;\n        }\n        if x <= 11141 {\n            return 12451;\n        }\n        if x <= 11796 {\n            return 13168;\n        }\n        if x <= 12451 {\n            return 13883;\n        }\n    }\n    if x <= 19005 {\n        if x <= 13107 {\n            return 14595;\n        }\n        if x <= 13762 {\n            return 15304;\n        }\n        if x <= 14417 {\n            return 16010;\n        }\n        if x <= 15073 {\n            return 16713;\n        }\n        if x <= 15728 {\n            return 17412;\n        }\n        if x <= 16384 {\n            return 18109;\n        }\n        if x <= 17039 {\n            return 18802;\n        }\n        if x <= 17694 {\n            return 19491;\n        }\n        if x <= 18350 {\n            return 20177;\n        }\n        if x <= 19005 {\n            return 20859;\n        }\n    }\n    if x <= 25559 {\n        if x <= 19660 {\n            return 21536;\n        }\n        if x <= 20316 {\n            return 22210;\n        }\n        if x <= 20971 {\n            return 22880;\n        }\n        if x <= 21626 {\n            return 23545;\n        }\n        if x <= 22282 {\n            return 24206;\n        }\n        if x <= 22937 {\n            return 24863;\n        }\n        if x <= 23592 {\n            return 25515;\n        }\n        if x <= 24248 {\n            return 26162;\n        }\n        if x <= 24903 {\n            return 26804;\n        }\n        if x <= 25559 {\n            return 27442;\n        }\n    }\n    if x <= 32112 {\n        if x <= 26214 {\n            return 28075;\n        }\n        if x <= 26869 {\n            return 28702;\n        }\n        if x <= 27525 {\n            return 29325;\n        }\n        if x <= 28180 {\n            return 29942;\n        }\n        if x <= 28835 {\n            return 30554;\n        }\n        if x <= 29491 {\n            return 31161;\n        }\n        if x <= 30146 {\n            return 31762;\n        }\n        if x <= 30801 {\n            return 32358;\n        }\n        if x <= 31457 {\n            return 32948;\n        }\n        if x <= 32112 {\n            return 33532;\n        }\n    }\n    if x <= 38666 {\n        if x <= 32768 {\n            return 34111;\n        }\n        if x <= 33423 {\n            return 34684;\n        }\n        if x <= 34078 {\n            return 35251;\n        }\n        if x <= 34734 {\n            return 35813;\n        }\n        if x <= 35389 {\n            return 36368;\n        }\n        if x <= 36044 {\n            return 36917;\n        }\n        if x <= 36700 {\n            return 37461;\n        }\n        if x <= 37355 {\n            return 37998;\n        }\n        if x <= 38010 {\n            return 38530;\n        }\n        if x <= 38666 {\n            return 39055;\n        }\n    }\n    if x <= 45219 {\n        if x <= 39321 {\n            return 39574;\n        }\n        if x <= 39976 {\n            return 40087;\n        }\n        if x <= 40632 {\n            return 40593;\n        }\n        if x <= 41287 {\n            return 41094;\n        }\n        if x <= 41943 {\n            return 41588;\n        }\n        if x <= 42598 {\n            return 42076;\n        }\n        if x <= 43253 {\n            return 42557;\n        }\n        if x <= 43909 {\n            return 43032;\n        }\n        if x <= 44564 {\n            return 43501;\n        }\n        if x <= 45219 {\n            return 43964;\n        }\n    }\n    if x <= 51773 {\n        if x <= 45875 {\n            return 44420;\n        }\n        if x <= 46530 {\n            return 44870;\n        }\n        if x <= 47185 {\n            return 45313;\n        }\n        if x <= 47841 {\n            return 45750;\n        }\n        if x <= 48496 {\n            return 46181;\n        }\n        if x <= 49152 {\n            return 46606;\n        }\n        if x <= 49807 {\n            return 47024;\n        }\n        if x <= 50462 {\n            return 47436;\n        }\n        if x <= 51118 {\n            return 47841;\n        }\n        if x <= 51773 {\n            return 48241;\n        }\n    }\n    if x <= 58327 {\n        if x <= 52428 {\n            return 48634;\n        }\n        if x <= 53084 {\n            return 49021;\n        }\n        if x <= 53739 {\n            return 49401;\n        }\n        if x <= 54394 {\n            return 49776;\n        }\n        if x <= 55050 {\n            return 50144;\n        }\n        if x <= 55705 {\n            return 50506;\n        }\n        if x <= 56360 {\n            return 50862;\n        }\n        if x <= 57016 {\n            return 51212;\n        }\n        if x <= 57671 {\n            return 51556;\n        }\n        if x <= 58327 {\n            return 51894;\n        }\n    }\n    if x <= 64880 {\n        if x <= 58982 {\n            return 52226;\n        }\n        if x <= 59637 {\n            return 52552;\n        }\n        if x <= 60293 {\n            return 52872;\n        }\n        if x <= 60948 {\n            return 53186;\n        }\n        if x <= 61603 {\n            return 53495;\n        }\n        if x <= 62259 {\n            return 53797;\n        }\n        if x <= 62914 {\n            return 54094;\n        }\n        if x <= 63569 {\n            return 54386;\n        }\n        if x <= 64225 {\n            return 54672;\n        }\n        if x <= 64880 {\n            return 54952;\n        }\n    }\n    if x <= 71434 {\n        if x <= 65536 {\n            return 55227;\n        }\n        if x <= 66191 {\n            return 55496;\n        }\n        if x <= 66846 {\n            return 55760;\n        }\n        if x <= 67502 {\n            return 56019;\n        }\n        if x <= 68157 {\n            return 56272;\n        }\n        if x <= 68812 {\n            return 56520;\n        }\n        if x <= 69468 {\n            return 56763;\n        }\n        if x <= 70123 {\n            return 57001;\n        }\n        if x <= 70778 {\n            return 57234;\n        }\n        if x <= 71434 {\n            return 57462;\n        }\n    }\n    if x <= 77987 {\n        if x <= 72089 {\n            return 57685;\n        }\n        if x <= 72744 {\n            return 57903;\n        }\n        if x <= 73400 {\n            return 58116;\n        }\n        if x <= 74055 {\n            return 58325;\n        }\n        if x <= 74711 {\n            return 58529;\n        }\n        if x <= 75366 {\n            return 58728;\n        }\n        if x <= 76021 {\n            return 58923;\n        }\n        if x <= 76677 {\n            return 59113;\n        }\n        if x <= 77332 {\n            return 59299;\n        }\n        if x <= 77987 {\n            return 59481;\n        }\n    }\n    if x <= 84541 {\n        if x <= 78643 {\n            return 59658;\n        }\n        if x <= 79298 {\n            return 59831;\n        }\n        if x <= 79953 {\n            return 60000;\n        }\n        if x <= 80609 {\n            return 60165;\n        }\n        if x <= 81264 {\n            return 60326;\n        }\n        if x <= 81920 {\n            return 60483;\n        }\n        if x <= 82575 {\n            return 60636;\n        }\n        if x <= 83230 {\n            return 60785;\n        }\n        if x <= 83886 {\n            return 60931;\n        }\n        if x <= 84541 {\n            return 61072;\n        }\n    }\n    if x <= 91095 {\n        if x <= 85196 {\n            return 61211;\n        }\n        if x <= 85852 {\n            return 61345;\n        }\n        if x <= 86507 {\n            return 61477;\n        }\n        if x <= 87162 {\n            return 61604;\n        }\n        if x <= 87818 {\n            return 61729;\n        }\n        if x <= 88473 {\n            return 61850;\n        }\n        if x <= 89128 {\n            return 61968;\n        }\n        if x <= 89784 {\n            return 62083;\n        }\n        if x <= 90439 {\n            return 62194;\n        }\n        if x <= 91095 {\n            return 62303;\n        }\n    }\n    if x <= 97648 {\n        if x <= 91750 {\n            return 62408;\n        }\n        if x <= 92405 {\n            return 62511;\n        }\n        if x <= 93061 {\n            return 62611;\n        }\n        if x <= 93716 {\n            return 62708;\n        }\n        if x <= 94371 {\n            return 62802;\n        }\n        if x <= 95027 {\n            return 62894;\n        }\n        if x <= 95682 {\n            return 62983;\n        }\n        if x <= 96337 {\n            return 63070;\n        }\n        if x <= 96993 {\n            return 63154;\n        }\n        if x <= 97648 {\n            return 63235;\n        }\n    }\n    if x <= 104202 {\n        if x <= 98304 {\n            return 63314;\n        }\n        if x <= 98959 {\n            return 63391;\n        }\n        if x <= 99614 {\n            return 63465;\n        }\n        if x <= 100270 {\n            return 63538;\n        }\n        if x <= 100925 {\n            return 63608;\n        }\n        if x <= 101580 {\n            return 63676;\n        }\n        if x <= 102236 {\n            return 63742;\n        }\n        if x <= 102891 {\n            return 63806;\n        }\n        if x <= 103546 {\n            return 63867;\n        }\n        if x <= 104202 {\n            return 63927;\n        }\n    }\n    if x <= 110755 {\n        if x <= 104857 {\n            return 63985;\n        }\n        if x <= 105512 {\n            return 64042;\n        }\n        if x <= 106168 {\n            return 64096;\n        }\n        if x <= 106823 {\n            return 64149;\n        }\n        if x <= 107479 {\n            return 64200;\n        }\n        if x <= 108134 {\n            return 64249;\n        }\n        if x <= 108789 {\n            return 64297;\n        }\n        if x <= 109445 {\n            return 64343;\n        }\n        if x <= 110100 {\n            return 64388;\n        }\n        if x <= 110755 {\n            return 64431;\n        }\n    }\n    if x <= 117309 {\n        if x <= 111411 {\n            return 64473;\n        }\n        if x <= 112066 {\n            return 64514;\n        }\n        if x <= 112721 {\n            return 64553;\n        }\n        if x <= 113377 {\n            return 64590;\n        }\n        if x <= 114032 {\n            return 64627;\n        }\n        if x <= 114688 {\n            return 64662;\n        }\n        if x <= 115343 {\n            return 64696;\n        }\n        if x <= 115998 {\n            return 64729;\n        }\n        if x <= 116654 {\n            return 64760;\n        }\n        if x <= 117309 {\n            return 64791;\n        }\n    }\n    if x <= 123863 {\n        if x <= 117964 {\n            return 64821;\n        }\n        if x <= 118620 {\n            return 64849;\n        }\n        if x <= 119275 {\n            return 64876;\n        }\n        if x <= 119930 {\n            return 64903;\n        }\n        if x <= 120586 {\n            return 64928;\n        }\n        if x <= 121241 {\n            return 64953;\n        }\n        if x <= 121896 {\n            return 64977;\n        }\n        if x <= 122552 {\n            return 64999;\n        }\n        if x <= 123207 {\n            return 65021;\n        }\n        if x <= 123863 {\n            return 65043;\n        }\n    }\n    if x <= 130416 {\n        if x <= 124518 {\n            return 65063;\n        }\n        if x <= 125173 {\n            return 65083;\n        }\n        if x <= 125829 {\n            return 65102;\n        }\n        if x <= 126484 {\n            return 65120;\n        }\n        if x <= 127139 {\n            return 65137;\n        }\n        if x <= 127795 {\n            return 65154;\n        }\n        if x <= 128450 {\n            return 65170;\n        }\n        if x <= 129105 {\n            return 65186;\n        }\n        if x <= 129761 {\n            return 65201;\n        }\n        if x <= 130416 {\n            return 65215;\n        }\n    }\n    if x <= 222822 {\n        if x <= 131072 {\n            return 65229;\n        }\n        if x <= 137625 {\n            return 65340;\n        }\n        if x <= 144179 {\n            return 65413;\n        }\n        if x <= 150732 {\n            return 65461;\n        }\n        if x <= 157286 {\n            return 65490;\n        }\n        if x <= 163840 {\n            return 65509;\n        }\n        if x <= 170393 {\n            return 65520;\n        }\n        if x <= 176947 {\n            return 65527;\n        }\n        if x <= 183500 {\n            return 65531;\n        }\n        if x <= 190054 {\n            return 65533;\n        }\n        if x <= 196608 {\n            return 65534;\n        }\n        if x <= 203161 {\n            return 65535;\n        }\n        if x <= 209715 {\n            return 65535;\n        }\n        if x <= 216268 {\n            return 65535;\n        }\n        if x <= 222822 {\n            return 65535;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16/math/trig.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp16x16::math::lut;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, TWO, FP16x16, FP16x16Impl, FP16x16Add, FP16x16Sub, FP16x16Mul, FP16x16Div,\n    FP16x16IntoFelt252, FixedTrait\n};\n\n// CONSTANTS\nconst TWO_PI: u32 = 411775;\nconst PI: u32 = 205887;\nconst HALF_PI: u32 = 102944;\n\n// PUBLIC\n\n// Calculates arccos(a) for -1 <= a <= 1 (fixed point)\n// arccos(a) = arcsin(sqrt(1 - a^2)) - arctan identity has discontinuity at zero\nfn acos(a: FP16x16) -> FP16x16 {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin(asin_arg);\n\n    if a.sign {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\nfn acos_fast(a: FP16x16) -> FP16x16 {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin_fast(asin_arg);\n\n    if a.sign {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\n// Calculates arcsin(a) for -1 <= a <= 1 (fixed point)\n// arcsin(a) = arctan(a / sqrt(1 - a^2))\nfn asin(a: FP16x16) -> FP16x16 {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan(a / div)\n}\n\nfn asin_fast(a: FP16x16) -> FP16x16 {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan_fast(a / div)\n}\n\n// Calculates arctan(a) (fixed point)\n// See https://stackoverflow.com/a/50894477 for range adjustments\nfn atan(a: FP16x16) -> FP16x16 {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 45875) {\n        let sqrt3_3 = FixedTrait::new(37837, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let r10 = FixedTrait::new(120, true) * at;\n    let r9 = (r10 + FixedTrait::new(3066, true)) * at;\n    let r8 = (r9 + FixedTrait::new(12727, false)) * at;\n    let r7 = (r8 + FixedTrait::new(17170, true)) * at;\n    let r6 = (r7 + FixedTrait::new(2865, false)) * at;\n    let r5 = (r6 + FixedTrait::new(12456, false)) * at;\n    let r4 = (r5 + FixedTrait::new(90, false)) * at;\n    let r3 = (r4 + FixedTrait::new(21852, true)) * at;\n    let r2 = r3 * at;\n    let mut res = (r2 + FixedTrait::new(65536, false)) * at;\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(34315, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\nfn atan_fast(a: FP16x16) -> FP16x16 {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 45875) {\n        let sqrt3_3 = FixedTrait::new(37837, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let (start, low, high) = lut::atan(at.mag);\n    let partial_step = FixedTrait::new(at.mag - start, false) / FixedTrait::new(459, false);\n    let mut res = partial_step * FixedTrait::new(high - low, false) + FixedTrait::new(low, false);\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(34315, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::<FP16x16>::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\n// Calculates cos(a) with a in radians (fixed point)\nfn cos(a: FP16x16) -> FP16x16 {\n    sin(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn cos_fast(a: FP16x16) -> FP16x16 {\n    sin_fast(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn sin(a: FP16x16) -> FP16x16 {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, partial_rem) = integer::u32_safe_divmod(a1, integer::u32_as_non_zero(PI));\n    let a2 = FixedTrait::new(partial_rem, false);\n    let partial_sign = whole_rem == 1;\n\n    let loop_res = a2 * _sin_loop(a2, 7, FixedTrait::ONE());\n\n    FixedTrait::new(loop_res.mag, a.sign ^ partial_sign && loop_res.mag != 0)\n}\n\nfn sin_fast(a: FP16x16) -> FP16x16 {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, mut partial_rem) = integer::u32_safe_divmod(a1, integer::u32_as_non_zero(PI));\n    let partial_sign = whole_rem == 1;\n\n    if partial_rem >= HALF_PI {\n        partial_rem = PI - partial_rem;\n    }\n\n    let (start, low, high) = lut::sin(partial_rem);\n    let partial_step = FixedTrait::new(partial_rem - start, false) / FixedTrait::new(402, false);\n    let res = partial_step * (FixedTrait::new(high, false) - FixedTrait::new(low, false))\n        + FixedTrait::<FP16x16>::new(low, false);\n\n    FixedTrait::new(res.mag, a.sign ^ partial_sign && res.mag != 0)\n}\n\n// Calculates tan(a) with a in radians (fixed point)\nfn tan(a: FP16x16) -> FP16x16 {\n    let sinx = sin(a);\n    let cosx = cos(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\nfn tan_fast(a: FP16x16) -> FP16x16 {\n    let sinx = sin_fast(a);\n    let cosx = cos_fast(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\n// Helper function to calculate Taylor series for sin\nfn _sin_loop(a: FP16x16, i: u32, acc: FP16x16) -> FP16x16 {\n    let div = (2 * i + 2) * (2 * i + 3);\n    let term = a * a * acc / FixedTrait::new_unscaled(div, false);\n    let new_acc = FixedTrait::ONE() - term;\n\n    if (i == 0) {\n        return new_acc;\n    }\n\n    _sin_loop(a, i - 1, new_acc)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16PartialEq, FP16x16Print\n    };\n\n    use super::{\n        FixedTrait, acos, HALF_PI, ONE, acos_fast, PI, atan_fast, atan, asin, cos, cos_fast, sin,\n        sin_fast, tan\n    };\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_acos() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos(a), 68629, 'invalid half', error); // 1.3687308642680\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos(a), 137258, 'invalid neg half', error); // 2.737461741902\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_acos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos_fast(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos_fast(a), 68629, 'invalid half', error); // 1.3687308642680\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos_fast(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos_fast(a), 137258, 'invalid neg half', error); // 2.737461741902\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos_fast(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(8000000)]\n    fn test_acos_fail() {\n        let a = FixedTrait::new(2 * ONE, true);\n        acos(a);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_atan_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan_fast(a), 72558, 'invalid two', error);\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan_fast(a), 51472, 'invalid one', error);\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan_fast(a), 30386, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert(atan_fast(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan_fast(a), -30386, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan_fast(a), -51472, 'invalid neg one', error);\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan_fast(a), -72558, 'invalid neg two', error);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan(a), 72558, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan(a), 51472, 'invalid one', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan(a), 30386, 'invalid half', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(atan(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan(a), -30386, 'invalid neg half', Option::None(()));\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan(a), -51472, 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan(a), -72558, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_asin() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert_relative(asin(a), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(asin(a), 34315, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert_precise(asin(a), 0, 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(asin(a), -34315, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(asin(a), -HALF_PI.into(), 'invalid neg one', Option::None(())); // -PI / 2\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(8000000)]\n    fn test_asin_fail() {\n        let a = FixedTrait::new(2 * ONE, false);\n        asin(a);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_cos() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_relative(cos(a), 46341, 'invalid quarter pi', Option::None(())); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert_relative(cos(a), -1 * ONE.into(), 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_relative(cos(a), -18033, 'invalid 17', Option::None(())); // -0.21497123284870\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_relative(cos(a), -18033, 'invalid -17', Option::None(())); // -0.21497123284870\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_cos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos_fast(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(cos_fast(a), 46341, 'invalid quarter pi', error); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(cos_fast(a), -1 * ONE.into(), 'invalid pi', error);\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(cos_fast(a), -18033, 'invalid 17', error); // -0.21497123284870\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin(a), ONE.into(), 'invalid half pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin(a), 46341, 'invalid quarter pi', Option::None(())); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin(a), -ONE.into(), 'invalid neg half pi', Option::None(())\n        ); // 0.78124999999529\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin(a), -63006, 'invalid 17', Option::None(())); // -0.75109179053073\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin(a), 63006, 'invalid -17', Option::None(())); // 0.75109179053073\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_sin_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin_fast(a), ONE.into(), 'invalid half pi', error);\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin_fast(a), 46341, 'invalid quarter pi', error); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin_fast(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(sin_fast(a), -ONE.into(), 'invalid neg half pi', error); // 0.78124999999529\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin_fast(a), -63006, 'invalid 17', error); // -0.75109179053073\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin_fast(a), 63006, 'invalid -17', error); // 0.75109179053073\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_tan() {\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(tan(a), ONE.into(), 'invalid quarter pi', Option::None(()));\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(tan(a), 0, 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(tan(a), 228990, 'invalid 17', Option::None(())); // 3.3858731852805\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(tan(a), -228952, 'invalid -17', Option::None(())); // -3.3858731852805\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide.cairo",
        "content": "mod core;\nmod math;\nmod helpers;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::{fixed_point::core::FixedTrait, FP16x16};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::{\n    core as core_math, trig, hyp, erf\n};\nuse orion::numbers::fixed_point::utils;\n\n/// A struct representing a fixed point number.\n#[derive(Serde, Copy, Drop)]\nstruct FP16x16W {\n    mag: u64,\n    sign: bool\n}\n\n// CONSTANTS\nconst TWO: u64 = 131072; // 2 ** 17\nconst ONE: u64 = 65536; // 2 ** 16\nconst HALF: u64 = 32768; // 2 ** 15\nconst MAX: u64 = 2147483648; // 2 ** 31\n\nimpl FP16x16WImpl of FixedTrait<FP16x16W, u64> {\n    fn ZERO() -> FP16x16W {\n        FP16x16W { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP16x16W {\n        FP16x16W { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP16x16W {\n        FP16x16W { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP16x16W {\n        FP16x16W { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u64, sign: bool) -> FP16x16W {\n        FP16x16W { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP16x16W {\n        FP16x16W { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP16x16W {\n        let mag = core::integer::u64_try_from_felt252(utils::felt_abs(val)).unwrap();\n\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP16x16W) -> FP16x16W {\n        core_math::abs(self)\n    }\n\n    fn acos(self: FP16x16W) -> FP16x16W {\n        trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP16x16W) -> FP16x16W {\n        trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP16x16W) -> FP16x16W {\n        hyp::acosh(self)\n    }\n\n    fn asin(self: FP16x16W) -> FP16x16W {\n        trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP16x16W) -> FP16x16W {\n        trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP16x16W) -> FP16x16W {\n        hyp::asinh(self)\n    }\n\n    fn atan(self: FP16x16W) -> FP16x16W {\n        trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP16x16W) -> FP16x16W {\n        trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP16x16W) -> FP16x16W {\n        hyp::atanh(self)\n    }\n\n    fn ceil(self: FP16x16W) -> FP16x16W {\n        core_math::ceil(self)\n    }\n\n    fn cos(self: FP16x16W) -> FP16x16W {\n        trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP16x16W) -> FP16x16W {\n        trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP16x16W) -> FP16x16W {\n        hyp::cosh(self)\n    }\n\n    fn floor(self: FP16x16W) -> FP16x16W {\n        core_math::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP16x16W) -> FP16x16W {\n        core_math::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP16x16W) -> FP16x16W {\n        core_math::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP16x16W) -> FP16x16W {\n        core_math::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP16x16W) -> FP16x16W {\n        core_math::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP16x16W) -> FP16x16W {\n        core_math::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP16x16W, b: FP16x16W) -> FP16x16W {\n        core_math::pow(self, b)\n    }\n\n    fn round(self: FP16x16W) -> FP16x16W {\n        core_math::round(self)\n    }\n\n    fn sin(self: FP16x16W) -> FP16x16W {\n        trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP16x16W) -> FP16x16W {\n        trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP16x16W) -> FP16x16W {\n        hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP16x16W) -> FP16x16W {\n        core_math::sqrt(self)\n    }\n\n    fn tan(self: FP16x16W) -> FP16x16W {\n        trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP16x16W) -> FP16x16W {\n        trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP16x16W) -> FP16x16W {\n        hyp::tanh(self)\n    }\n\n    fn sign(self: FP16x16W) -> FP16x16W {\n        core_math::sign(self)\n    }\n\n    fn NaN() -> FP16x16W {\n        FP16x16W { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP16x16W) -> bool {\n        self == FP16x16W { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP16x16W {\n        FP16x16W { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP16x16W {\n        FP16x16W { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP16x16W {\n        FP16x16W { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP16x16W) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP16x16W) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP16x16W) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP16x16W) -> FP16x16W {\n        erf::erf(self)\n    }\n}\n\n\nimpl FP16x16WPrint of PrintTrait<FP16x16W> {\n    fn print(self: FP16x16W) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP16x16WIntoFelt252 of Into<FP16x16W, felt252> {\n    fn into(self: FP16x16W) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP16x16WIntoI32 of Into<FP16x16W, i32> {\n    fn into(self: FP16x16W) -> i32 {\n        _i32_into_fp(self)\n    }\n}\n\nimpl FP16x16IntoFP16x16W of Into<FP16x16, FP16x16W> {\n    fn into(self: FP16x16) -> FP16x16W {\n        FP16x16W { mag: self.mag.into(), sign: self.sign }\n    }\n}\n\nimpl FP16x16WTryIntoFP16x16 of TryInto<FP16x16W, FP16x16> {\n    fn try_into(self: FP16x16W) -> Option<FP16x16> {\n        match self.mag.try_into() {\n            Option::Some(val) => { Option::Some(FP16x16 { mag: val, sign: self.sign }) },\n            Option::None => { Option::None(()) }\n        }\n    }\n}\n\nimpl FP16x16WTryIntoI8 of TryInto<FP16x16W, i8> {\n    fn try_into(self: FP16x16W) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\n\nimpl FP16x16WTryIntoU128 of TryInto<FP16x16W, u128> {\n    fn try_into(self: FP16x16W) -> Option<u128> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP16x16WTryIntoU64 of TryInto<FP16x16W, u64> {\n    fn try_into(self: FP16x16W) -> Option<u64> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP16x16WTryIntoU32 of TryInto<FP16x16W, u32> {\n    fn try_into(self: FP16x16W) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP16x16WTryIntoU16 of TryInto<FP16x16W, u16> {\n    fn try_into(self: FP16x16W) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP16x16WTryIntoU8 of TryInto<FP16x16W, u8> {\n    fn try_into(self: FP16x16W) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP16x16WPartialEq of PartialEq<FP16x16W> {\n    #[inline(always)]\n    fn eq(lhs: @FP16x16W, rhs: @FP16x16W) -> bool {\n        core_math::eq(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn ne(lhs: @FP16x16W, rhs: @FP16x16W) -> bool {\n        core_math::ne(lhs, rhs)\n    }\n}\n\nimpl FP16x16WAdd of Add<FP16x16W> {\n    fn add(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        core_math::add(lhs, rhs)\n    }\n}\n\nimpl FP16x16WAddEq of AddEq<FP16x16W> {\n    #[inline(always)]\n    fn add_eq(ref self: FP16x16W, other: FP16x16W) {\n        self = Add::add(self, other);\n    }\n}\n\nimpl FP16x16WSub of Sub<FP16x16W> {\n    fn sub(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        core_math::sub(lhs, rhs)\n    }\n}\n\nimpl FP16x16WSubEq of SubEq<FP16x16W> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP16x16W, other: FP16x16W) {\n        self = Sub::sub(self, other);\n    }\n}\n\nimpl FP16x16WMul of Mul<FP16x16W> {\n    fn mul(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        core_math::mul(lhs, rhs)\n    }\n}\n\nimpl FP16x16WMulEq of MulEq<FP16x16W> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP16x16W, other: FP16x16W) {\n        self = Mul::mul(self, other);\n    }\n}\n\nimpl FP16x16WDiv of Div<FP16x16W> {\n    fn div(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        core_math::div(lhs, rhs)\n    }\n}\n\nimpl FP16x16WDivEq of DivEq<FP16x16W> {\n    #[inline(always)]\n    fn div_eq(ref self: FP16x16W, other: FP16x16W) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl FP16x16WPartialOrd of PartialOrd<FP16x16W> {\n    #[inline(always)]\n    fn ge(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        core_math::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        core_math::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        core_math::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP16x16W, rhs: FP16x16W) -> bool {\n        core_math::lt(lhs, rhs)\n    }\n}\n\nimpl FP16x16WNeg of Neg<FP16x16W> {\n    #[inline(always)]\n    fn neg(a: FP16x16W) -> FP16x16W {\n        core_math::neg(a)\n    }\n}\n\nimpl FP16x16WRem of Rem<FP16x16W> {\n    #[inline(always)]\n    fn rem(lhs: FP16x16W, rhs: FP16x16W) -> FP16x16W {\n        core_math::rem(lhs, rhs)\n    }\n}\n\n/// INTERNAL\nfn _i32_into_fp(x: FP16x16W) -> i32 {\n    let number_felt: felt252 = (x.mag / ONE).into();\n    let number_i32: i32 = number_felt.try_into().unwrap();\n    if x.sign {\n        return number_i32 * -1_i32;\n    }\n\n    number_i32\n}\n\nfn _i8_try_from_fp(x: FP16x16W) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/helpers.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    HALF, ONE, TWO, FP16x16W, FP16x16WImpl, FP16x16WSub, FP16x16WDiv, FixedTrait, FP16x16WPrint\n};\n\nconst DEFAULT_PRECISION: u64 = 7; // 1e-4\n\n// To use `DEFAULT_PRECISION`, final arg is: `Option::None(())`.\n// To use `custom_precision` of 430_u32: `Option::Some(430_u32)`.\nfn assert_precise(\n    result: FP16x16W, expected: felt252, msg: felt252, custom_precision: Option<u64>\n) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = (result - FixedTrait::from_felt(expected)).mag;\n\n    if (diff > precision) {\n        result.print();\n        assert(diff <= precision, msg);\n    }\n}\n\nfn assert_relative(\n    result: FP16x16W, expected: felt252, msg: felt252, custom_precision: Option<u64>\n) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = result - FixedTrait::from_felt(expected);\n    let rel_diff = (diff / result).mag;\n\n    if (rel_diff > precision) {\n        result.print();\n        assert(rel_diff <= precision, msg);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math.cairo",
        "content": "mod core;\nmod comp;\nmod lut;\nmod trig;\nmod hyp;\nmod erf;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/comp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    FP16x16W, FixedTrait, FP16x16WImpl, FP16x16WPartialOrd, FP16x16WPartialEq\n};\n\nfn max(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    if a >= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn min(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    if a <= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn xor(a: FP16x16W, b: FP16x16W) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP16x16W, b: FP16x16W) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP16x16W, b: FP16x16W) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP16x16W, b: FP16x16W, c: FP16x16W) -> FP16x16W {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use super::{FixedTrait, max, min, bitwise_and, bitwise_xor, bitwise_or};\n\n    #[test]\n    fn test_max() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(max(a, a) == a, 'max(a, a)');\n        assert(max(a, b) == a, 'max(a, b)');\n        assert(max(a, c) == a, 'max(a, c)');\n\n        assert(max(b, a) == a, 'max(b, a)');\n        assert(max(b, b) == b, 'max(b, b)');\n        assert(max(b, c) == b, 'max(b, c)');\n\n        assert(max(c, a) == a, 'max(c, a)');\n        assert(max(c, b) == b, 'max(c, b)');\n        assert(max(c, c) == c, 'max(c, c)');\n    }\n\n    #[test]\n    fn test_min() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(min(a, a) == a, 'min(a, a)');\n        assert(min(a, b) == b, 'min(a, b)');\n        assert(min(a, c) == c, 'min(a, c)');\n\n        assert(min(b, a) == b, 'min(b, a)');\n        assert(min(b, b) == b, 'min(b, b)');\n        assert(min(b, c) == c, 'min(b, c)');\n\n        assert(min(c, a) == c, 'min(c, a)');\n        assert(min(c, b) == c, 'min(c, b)');\n        assert(min(c, c) == c, 'min(c, c)');\n    }\n\n    #[test]\n    fn test_bitwise_and() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(94208, false); // 1.4375\n\n        assert(bitwise_and(a, b) == c, 'bitwise_and(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_xor() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(4160880640, true);\n\n        assert(bitwise_xor(a, b) == c, 'bitwise_xor(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_or() {\n        let a = FixedTrait::new(225280, false); // 3.4375\n        let b = FixedTrait::new(4160843776, true); // -2046.5625\n        let c = FixedTrait::new(4160974848, true);\n\n        assert(bitwise_or(a, b) == c, 'bitwise_or(a,b)')\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/core.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    HALF, ONE, MAX, FP16x16W, FP16x16WImpl, FP16x16WAdd, FP16x16WAddEq, FP16x16WSub, FP16x16WMul,\n    FP16x16WMulEq, FP16x16WTryIntoU128, FP16x16WPartialEq, FP16x16WPartialOrd, FP16x16WSubEq,\n    FP16x16WNeg, FP16x16WDiv, FP16x16WIntoFelt252, FixedTrait\n};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::lut;\n\n// PUBLIC\nfn abs(a: FP16x16W) -> FP16x16W {\n    FixedTrait::new(a.mag, false)\n}\n\nfn add(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    if a.sign == b.sign {\n        return FixedTrait::new(a.mag + b.mag, a.sign);\n    }\n\n    if a.mag == b.mag {\n        return FixedTrait::ZERO();\n    }\n\n    if (a.mag > b.mag) {\n        FixedTrait::new(a.mag - b.mag, a.sign)\n    } else {\n        FixedTrait::new(b.mag - a.mag, b.sign)\n    }\n}\n\nfn ceil(a: FP16x16W) -> FP16x16W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div + 1, false)\n    } else if div == 0 {\n        FixedTrait::new_unscaled(0, false)\n    } else {\n        FixedTrait::new_unscaled(div, true)\n    }\n}\n\nfn div(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    let a_u64 = integer::u64_wide_mul(a.mag, ONE);\n    let res_u64 = a_u64 / b.mag.into();\n\n    // Re-apply sign\n    FixedTrait::new(res_u64.try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn eq(a: @FP16x16W, b: @FP16x16W) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n// Calculates the natural exponent of x: e^x\nfn exp(a: FP16x16W) -> FP16x16W {\n    exp2(FixedTrait::new(94548, false) * a) // log2(e) * 2^23 \u2248 12102203\n}\n\n// Calculates the binary exponent of x: 2^x\nfn exp2(a: FP16x16W) -> FP16x16W {\n    if (a.mag == 0) {\n        return FixedTrait::ONE();\n    }\n\n    let (int_part, frac_part) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n    let int_res = FixedTrait::new_unscaled(lut::exp2(int_part), false);\n    let mut res_u = int_res;\n\n    if frac_part != 0 {\n        let frac = FixedTrait::new(frac_part, false);\n        let r7 = FixedTrait::new(1, false) * frac;\n        let r6 = (r7 + FixedTrait::new(10, false)) * frac;\n        let r5 = (r6 + FixedTrait::new(87, false)) * frac;\n        let r4 = (r5 + FixedTrait::new(630, false)) * frac;\n        let r3 = (r4 + FixedTrait::new(3638, false)) * frac;\n        let r2 = (r3 + FixedTrait::new(15743, false)) * frac;\n        let r1 = (r2 + FixedTrait::new(45426, false)) * frac;\n        res_u = res_u * (r1 + FixedTrait::ONE());\n    }\n\n    if a.sign {\n        FixedTrait::ONE() / res_u\n    } else {\n        res_u\n    }\n}\n\nfn exp2_int(exp: u64) -> FP16x16W {\n    FixedTrait::new_unscaled(lut::exp2(exp), false)\n}\n\nfn floor(a: FP16x16W) -> FP16x16W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div, false)\n    } else {\n        FixedTrait::new_unscaled(div + 1, true)\n    }\n}\n\nfn ge(a: FP16x16W, b: FP16x16W) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn gt(a: FP16x16W, b: FP16x16W) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn le(a: FP16x16W, b: FP16x16W) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\n// Calculates the natural logarithm of x: ln(x)\n// self must be greater than zero\nfn ln(a: FP16x16W) -> FP16x16W {\n    FixedTrait::new(45426, false) * log2(a) // ln(2) = 0.693...\n}\n\n// Calculates the binary logarithm of x: log2(x)\n// self must be greather than zero\nfn log2(a: FP16x16W) -> FP16x16W {\n    assert(a.sign == false, 'must be positive');\n\n    if (a.mag == ONE) {\n        return FixedTrait::ZERO();\n    } else if (a.mag < ONE) {\n        // Compute true inverse binary log if 0 < x < 1\n        let div = FixedTrait::ONE() / a;\n        return -log2(div);\n    }\n\n    let whole = a.mag / ONE;\n    let (msb, div) = lut::msb(whole);\n\n    if a.mag == div * ONE {\n        FixedTrait::new_unscaled(msb, false)\n    } else {\n        let norm = a / FixedTrait::new_unscaled(div, false);\n        let r8 = FixedTrait::new(596, true) * norm;\n        let r7 = (r8 + FixedTrait::new(8116, false)) * norm;\n        let r6 = (r7 + FixedTrait::new(49044, true)) * norm;\n        let r5 = (r6 + FixedTrait::new(172935, false)) * norm;\n        let r4 = (r5 + FixedTrait::new(394096, true)) * norm;\n        let r3 = (r4 + FixedTrait::new(608566, false)) * norm;\n        let r2 = (r3 + FixedTrait::new(655828, true)) * norm;\n        let r1 = (r2 + FixedTrait::new(534433, false)) * norm;\n\n        r1 + FixedTrait::new(224487, true) + FixedTrait::new_unscaled(msb, false)\n    }\n}\n\n// Calculates the base 10 log of x: log10(x)\n// self must be greater than zero\nfn log10(a: FP16x16W) -> FP16x16W {\n    FixedTrait::new(19728, false) * log2(a) // log10(2) = 0.301...\n}\n\nfn lt(a: FP16x16W, b: FP16x16W) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\nfn mul(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    let prod_u128 = integer::u64_wide_mul(a.mag, b.mag);\n\n    // Re-apply sign\n    FixedTrait::new((prod_u128 / ONE.into()).try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn ne(a: @FP16x16W, b: @FP16x16W) -> bool {\n    (*a.mag != *b.mag) || (*a.sign != *b.sign)\n}\n\nfn neg(a: FP16x16W) -> FP16x16W {\n    if a.mag == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new(a.mag, !a.sign)\n    } else {\n        FixedTrait::new(a.mag, false)\n    }\n}\n\n// Calclates the value of x^y and checks for overflow before returning\n// self is a FP16x16W point value\n// b is a FP16x16W point value\nfn pow(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    let (_, rem) = integer::u64_safe_divmod(b.mag, integer::u64_as_non_zero(ONE));\n\n    // use the more performant integer pow when y is an int\n    if (rem == 0) {\n        return pow_int(a, b.mag / ONE, b.sign);\n    }\n\n    // x^y = exp(y*ln(x)) for x > 0 will error for x < 0\n    exp(b * ln(a))\n}\n\n// Calclates the value of a^b and checks for overflow before returning\nfn pow_int(a: FP16x16W, b: u64, sign: bool) -> FP16x16W {\n    let mut x = a;\n    let mut n = b;\n\n    if sign {\n        x = FixedTrait::ONE() / x;\n    }\n\n    if n == 0 {\n        return FixedTrait::ONE();\n    }\n\n    let mut y = FixedTrait::ONE();\n    let two = integer::u64_as_non_zero(2);\n\n    while n > 1 {\n        let (div, rem) = integer::u64_safe_divmod(n, two);\n\n        if rem == 1 {\n            y = x * y;\n        }\n\n        x = x * x;\n        n = div;\n    };\n\n    x * y\n}\n\nfn rem(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    a - floor(a / b) * b\n}\n\nfn round(a: FP16x16W) -> FP16x16W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if (HALF <= rem) {\n        FixedTrait::new_unscaled(div + 1, a.sign)\n    } else {\n        FixedTrait::new_unscaled(div, a.sign)\n    }\n}\n\n// Calculates the square root of a FP16x16W point value\n// x must be positive\nfn sqrt(a: FP16x16W) -> FP16x16W {\n    assert(a.sign == false, 'must be positive');\n\n    let root = integer::u64_sqrt(a.mag.into() * ONE.into());\n\n    FixedTrait::new(root.into(), false)\n}\n\nfn sub(a: FP16x16W, b: FP16x16W) -> FP16x16W {\n    add(a, -b)\n}\n\nfn sign(a: FP16x16W) -> FP16x16W {\n    if a.mag == 0 {\n        FixedTrait::new(0, false)\n    } else {\n        FixedTrait::new(ONE, a.sign)\n    }\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16wide::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp16x16wide::math::trig::{PI, HALF_PI};\n\n    use super::{\n        FixedTrait, ONE, FP16x16W, ceil, floor, sqrt, round, lut, pow, exp, exp2, exp2_int, ln,\n        log2, log10, eq, add, ne, HALF\n    };\n\n    #[test]\n    fn test_into() {\n        let a = FixedTrait::<FP16x16W>::new_unscaled(5, false);\n        assert(a.mag == 5 * ONE, 'invalid result');\n    }\n\n    #[test]\n    fn test_try_into_u128() {\n        // Positive unscaled\n        let a = FixedTrait::<FP16x16W>::new_unscaled(5, false);\n        assert(a.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Positive scaled\n        let b = FixedTrait::<FP16x16W>::new(5 * ONE, false);\n        assert(b.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Zero\n        let d = FixedTrait::<FP16x16W>::new_unscaled(0, false);\n        assert(d.try_into().unwrap() == 0_u128, 'invalid result');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_negative_try_into_u128() {\n        let a = FixedTrait::<FP16x16W>::new_unscaled(1, true);\n        let _a: u128 = a.try_into().unwrap();\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_acos() {\n        let a = FixedTrait::<FP16x16W>::ONE();\n        assert(a.acos().into() == 0, 'invalid one');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_asin() {\n        let a = FixedTrait::ONE();\n        assert_precise(a.asin(), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(a.atan(), 72558, 'invalid two', Option::None(()));\n    }\n\n    #[test]\n    fn test_ceil() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(ceil(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_floor() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(floor(a).mag == 2 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_round() {\n        let a = FixedTrait::new(190054, false); // 2.9\n        assert(round(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_sqrt_fail() {\n        let a = FixedTrait::new_unscaled(25, true);\n        sqrt(a);\n    }\n\n    #[test]\n    fn test_sqrt() {\n        let mut a = FixedTrait::new_unscaled(0, false);\n        assert(sqrt(a).mag == 0, 'invalid zero root');\n        a = FixedTrait::new_unscaled(25, false);\n        assert(sqrt(a).mag == 5 * ONE, 'invalid pos root');\n    }\n\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_msb() {\n        let a = FixedTrait::<FP16x16W>::new_unscaled(100, false);\n        let (msb, div) = lut::msb(a.mag / ONE);\n        assert(msb == 6, 'invalid msb');\n        assert(div == 64, 'invalid msb ceil');\n    }\n\n    #[test]\n    #[available_gas(600000)]\n    fn test_pow() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new_unscaled(4, false);\n        assert(pow(a, b).mag == 81 * ONE, 'invalid pos base power');\n    }\n\n    #[test]\n    #[available_gas(900000)]\n    fn test_pow_frac() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new(32768, false); // 0.5\n        assert_relative(\n            pow(a, b), 113512, 'invalid pos base power', Option::None(())\n        ); // 1.7320508075688772\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_exp() {\n        let a = FixedTrait::new_unscaled(2, false);\n        assert_relative(exp(a), 484249, 'invalid exp of 2', Option::None(())); // 7.389056098793725\n    }\n\n    #[test]\n    #[available_gas(400000)]\n    fn test_exp2() {\n        let a = FixedTrait::new_unscaled(5, false);\n        assert(exp2(a).mag == 2097152, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(20000)]\n    fn test_exp2_int() {\n        assert(exp2_int(5).into() == 2097152, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_ln() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        assert(ln(a).mag == 0, 'invalid ln of 1');\n\n        a = FixedTrait::new(178145, false);\n        assert_relative(ln(a), ONE.into(), 'invalid ln of 2.7...', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log2() {\n        let mut a = FixedTrait::new_unscaled(32, false);\n        assert(log2(a) == FixedTrait::new_unscaled(5, false), 'invalid log2 32');\n\n        a = FixedTrait::new_unscaled(10, false);\n        assert_relative(log2(a), 217706, 'invalid log2 10', Option::None(())); // 3.321928094887362\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log10() {\n        let a = FixedTrait::new_unscaled(100, false);\n        assert_relative(log10(a), 2 * ONE.into(), 'invalid log10', Option::None(()));\n    }\n\n    #[test]\n    fn test_eq() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = eq(@a, @b);\n        assert(c, 'invalid result');\n    }\n\n    #[test]\n    fn test_ne() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = ne(@a, @b);\n        assert(!c, 'invalid result');\n    }\n\n    #[test]\n    fn test_add() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        assert(add(a, b) == FixedTrait::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_add_eq() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a += b;\n        assert(a == FixedTrait::<FP16x16W>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_sub() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        let c = a - b;\n        assert(c == FixedTrait::<FP16x16W>::new_unscaled(3, false), 'false result invalid');\n    }\n\n    #[test]\n    fn test_sub_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a -= b;\n        assert(a == FixedTrait::<FP16x16W>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_mul_pos() {\n        let a = FP16x16W { mag: 190054, sign: false };\n        let b = FP16x16W { mag: 190054, sign: false };\n        let c = a * b;\n        assert(c.mag == 551155, 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_neg() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        let c = a * b;\n        assert(c == FixedTrait::<FP16x16W>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        a *= b;\n        assert(a == FixedTrait::<FP16x16W>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_div() {\n        let a = FixedTrait::new_unscaled(10, false);\n        let b = FixedTrait::<FP16x16W>::new(190054, false); // 2.9\n        let c = a / b;\n        assert(c.mag == 225986, 'invalid pos decimal'); // 3.4482758620689653\n    }\n\n    #[test]\n    fn test_le() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16W>::new_unscaled(1, true);\n\n        assert(a <= a, 'a <= a');\n        assert(!(a <= b), 'a <= b');\n        assert(!(a <= c), 'a <= c');\n\n        assert(b <= a, 'b <= a');\n        assert(b <= b, 'b <= b');\n        assert(!(b <= c), 'b <= c');\n\n        assert(c <= a, 'c <= a');\n        assert(c <= b, 'c <= b');\n        assert(c <= c, 'c <= c');\n    }\n\n    #[test]\n    fn test_lt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16W>::new_unscaled(1, true);\n\n        assert(!(a < a), 'a < a');\n        assert(!(a < b), 'a < b');\n        assert(!(a < c), 'a < c');\n\n        assert(b < a, 'b < a');\n        assert(!(b < b), 'b < b');\n        assert(!(b < c), 'b < c');\n\n        assert(c < a, 'c < a');\n        assert(c < b, 'c < b');\n        assert(!(c < c), 'c < c');\n    }\n\n    #[test]\n    fn test_ge() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16W>::new_unscaled(1, true);\n\n        assert(a >= a, 'a >= a');\n        assert(a >= b, 'a >= b');\n        assert(a >= c, 'a >= c');\n\n        assert(!(b >= a), 'b >= a');\n        assert(b >= b, 'b >= b');\n        assert(b >= c, 'b >= c');\n\n        assert(!(c >= a), 'c >= a');\n        assert(!(c >= b), 'c >= b');\n        assert(c >= c, 'c >= c');\n    }\n\n    #[test]\n    fn test_gt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP16x16W>::new_unscaled(1, true);\n\n        assert(!(a > a), 'a > a');\n        assert(a > b, 'a > b');\n        assert(a > c, 'a > c');\n\n        assert(!(b > a), 'b > a');\n        assert(!(b > b), 'b > b');\n        assert(b > c, 'b > c');\n\n        assert(!(c > a), 'c > a');\n        assert(!(c > b), 'c > b');\n        assert(!(c > c), 'c > c');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_cos() {\n        let a = FixedTrait::<FP16x16W>::new(HALF_PI, false);\n        assert(a.cos().into() == 0, 'invalid half pi');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(a.sin(), ONE.into(), 'invalid half pi', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_tan() {\n        let a = FixedTrait::<FP16x16W>::new(HALF_PI / 2, false);\n        assert(a.tan().mag == 65536, 'invalid quarter pi');\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_sign() {\n        let a = FixedTrait::<FP16x16W>::new(0, false);\n        assert(a.sign().mag == 0 && !a.sign().sign, 'invalid sign (0, true)');\n\n        let a = FixedTrait::<FP16x16W>::new(HALF, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (HALF, true)');\n\n        let a = FixedTrait::<FP16x16W>::new(HALF, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (HALF, false)');\n\n        let a = FixedTrait::<FP16x16W>::new(ONE, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (ONE, true)');\n\n        let a = FixedTrait::<FP16x16W>::new(ONE, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (ONE, false)');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(2000000)]\n    fn test_sign_fail() {\n        let a = FixedTrait::<FP16x16W>::new(HALF, true);\n        assert(a.sign().mag != ONE && !a.sign().sign, 'invalid sign (HALF, true)');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/erf.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16wide::core::{ONE, FP16x16W, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u64 = 100;\nconst ROUND_CHECK_NUMBER: u64 = 10;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u64 = 229376;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u64 = 131072;\n\nfn erf(x: FP16x16W) -> FP16x16W {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u64 = 0;\n\n    if x.mag < MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP16x16W { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/hyp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    HALF, ONE, TWO, FP16x16W, FP16x16WImpl, FP16x16WAdd, FP16x16WAddEq, FP16x16WSub, FP16x16WMul,\n    FP16x16WMulEq, FP16x16WTryIntoU128, FP16x16WPartialEq, FP16x16WPartialOrd, FP16x16WSubEq,\n    FP16x16WNeg, FP16x16WDiv, FP16x16WIntoFelt252, FixedTrait\n};\n\n// Calculates hyperbolic cosine of a (fixed point)\nfn cosh(a: FP16x16W) -> FP16x16W {\n    let ea = a.exp();\n\n    (ea + (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic sine of a (fixed point)\nfn sinh(a: FP16x16W) -> FP16x16W {\n    let ea = a.exp();\n\n    (ea - (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic tangent of a (fixed point)\nfn tanh(a: FP16x16W) -> FP16x16W {\n    let ea = a.exp();\n    let ea_i = FixedTrait::ONE() / ea;\n\n    (ea - ea_i) / (ea + ea_i)\n}\n\n// Calculates inverse hyperbolic cosine of a (fixed point)\nfn acosh(a: FP16x16W) -> FP16x16W {\n    let root = (a * a - FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic sine of a (fixed point)\nfn asinh(a: FP16x16W) -> FP16x16W {\n    let root = (a * a + FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic tangent of a (fixed point)\nfn atanh(a: FP16x16W) -> FP16x16W {\n    let one = FixedTrait::ONE();\n    let ln_arg = (one + a) / (one - a);\n\n    ln_arg.ln() / FixedTrait::new(TWO, false)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16wide::helpers::assert_precise;\n\n    use super::{FixedTrait, TWO, cosh, ONE, sinh, tanh, acosh, asinh, atanh, HALF};\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_cosh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(cosh(a), 246550, 'invalid two', Option::None(())); // 3.5954653836066\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 101127, 'invalid one', Option::None(())); // 1.42428174592510\n\n        let a = FixedTrait::ZERO();\n        assert_precise(cosh(a), ONE.into(), 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 101127, 'invalid neg one', Option::None(())); // 1.42428174592510\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(cosh(a), 246568, 'invalid neg two', Option::None(())); // 3.5954653836066\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_sinh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(sinh(a), 237681, 'invalid two', Option::None(())); // 3.48973469357602\n\n        let a = FixedTrait::ONE();\n        assert_precise(sinh(a), 77018, 'invalid one', Option::None(())); // 1.13687593250230\n\n        let a = FixedTrait::ZERO();\n        assert(sinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(sinh(a), -77018, 'invalid neg one', Option::None(())); // -1.13687593250230\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(sinh(a), -237699, 'invalid neg two', Option::None(())); // -3.48973469357602\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_tanh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(tanh(a), 63179, 'invalid two', Option::None(())); // 0.75314654693321\n\n        let a = FixedTrait::ONE();\n        assert_precise(tanh(a), 49912, 'invalid one', Option::None(())); // 0.59499543433175\n\n        let a = FixedTrait::ZERO();\n        assert(tanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(tanh(a), -49912, 'invalid neg one', Option::None(())); // -0.59499543433175\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(tanh(a), -63179, 'invalid neg two', Option::None(())); // 0.75314654693321\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_acosh() {\n        let a = FixedTrait::new(246559, false); // 3.5954653836066\n        assert_precise(acosh(a), 131072, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(101127, false); // 1.42428174592510\n        assert_precise(acosh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ONE(); // 1\n        assert(acosh(a).into() == 0, 'invalid zero');\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_asinh() {\n        let a = FixedTrait::new(237690, false); // 3.48973469357602\n        assert_precise(asinh(a), 131072, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(77018, false); // 1.13687593250230\n        assert_precise(asinh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(asinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(77018, true); // -1.13687593250230\n        assert_precise(asinh(a), -ONE.into(), 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(237690, true); // -3.48973469357602\n        assert_precise(asinh(a), -131017, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_atanh() {\n        let a = FixedTrait::new(58982, false); // 0.9\n        assert_precise(atanh(a), 96483, 'invalid 0.9', Option::None(())); // 1.36892147623689\n\n        let a = FixedTrait::new(HALF, false); // 0.5\n        assert_precise(atanh(a), 35999, 'invalid half', Option::None(())); // 0.42914542526098\n\n        let a = FixedTrait::ZERO();\n        assert(atanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(HALF, true); // 0.5\n        assert_precise(atanh(a), -35999, 'invalid neg half', Option::None(())); // 0.42914542526098\n\n        let a = FixedTrait::new(58982, true); // 0.9\n        assert_precise(atanh(a), -96483, 'invalid -0.9', Option::None(())); // 1.36892147623689\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::core::ONE;\n\n// Calculates the most significant bit\nfn msb(whole: u64) -> (u64, u64) {\n    if whole < 256 {\n        if whole < 2 {\n            return (0, 1);\n        }\n        if whole < 4 {\n            return (1, 2);\n        }\n        if whole < 8 {\n            return (2, 4);\n        }\n        if whole < 16 {\n            return (3, 8);\n        }\n        if whole < 32 {\n            return (4, 16);\n        }\n        if whole < 64 {\n            return (5, 32);\n        }\n        if whole < 128 {\n            return (6, 64);\n        }\n        if whole < 256 {\n            return (7, 128);\n        }\n    } else if whole < 65536 {\n        if whole < 512 {\n            return (8, 256);\n        }\n        if whole < 1024 {\n            return (9, 512);\n        }\n        if whole < 2048 {\n            return (10, 1024);\n        }\n        if whole < 4096 {\n            return (11, 2048);\n        }\n        if whole < 8192 {\n            return (12, 4096);\n        }\n        if whole < 16384 {\n            return (13, 8192);\n        }\n        if whole < 32768 {\n            return (14, 16384);\n        }\n        if whole < 65536 {\n            return (15, 32768);\n        }\n    }\n\n    (16, 65536)\n}\n\nfn exp2(exp: u64) -> u64 {\n    if exp <= 16 {\n        if exp == 0 {\n            return 1;\n        }\n        if exp == 1 {\n            return 2;\n        }\n        if exp == 2 {\n            return 4;\n        }\n        if exp == 3 {\n            return 8;\n        }\n        if exp == 4 {\n            return 16;\n        }\n        if exp == 5 {\n            return 32;\n        }\n        if exp == 6 {\n            return 64;\n        }\n        if exp == 7 {\n            return 128;\n        }\n        if exp == 8 {\n            return 256;\n        }\n        if exp == 9 {\n            return 512;\n        }\n        if exp == 10 {\n            return 1024;\n        }\n        if exp == 11 {\n            return 2048;\n        }\n        if exp == 12 {\n            return 4096;\n        }\n        if exp == 13 {\n            return 8192;\n        }\n        if exp == 14 {\n            return 16384;\n        }\n        if exp == 15 {\n            return 32768;\n        }\n        if exp == 16 {\n            return 65536;\n        }\n    }\n\n    65536\n}\n\nfn sin(a: u64) -> (u64, u64, u64) {\n    let slot = a / 402;\n\n    if slot < 128 {\n        if slot < 64 {\n            if slot < 32 {\n                if slot < 16 {\n                    if slot == 0 {\n                        return (0, 0, 402);\n                    }\n                    if slot == 1 {\n                        return (402, 402, 804);\n                    }\n                    if slot == 2 {\n                        return (804, 804, 1206);\n                    }\n                    if slot == 3 {\n                        return (1206, 1206, 1608);\n                    }\n                    if slot == 4 {\n                        return (1608, 1608, 2010);\n                    }\n                    if slot == 5 {\n                        return (2011, 2010, 2412);\n                    }\n                    if slot == 6 {\n                        return (2413, 2412, 2814);\n                    }\n                    if slot == 7 {\n                        return (2815, 2814, 3216);\n                    }\n                    if slot == 8 {\n                        return (3217, 3216, 3617);\n                    }\n                    if slot == 9 {\n                        return (3619, 3617, 4019);\n                    }\n                    if slot == 10 {\n                        return (4023, 4019, 4420);\n                    }\n                    if slot == 11 {\n                        return (4423, 4420, 4821);\n                    }\n                    if slot == 12 {\n                        return (4825, 4821, 5222);\n                    }\n                    if slot == 13 {\n                        return (5228, 5222, 5623);\n                    }\n                    if slot == 14 {\n                        return (5630, 5623, 6023);\n                    }\n                    if slot == 15 {\n                        return (6032, 6023, 6424);\n                    }\n                } else {\n                    if slot == 16 {\n                        return (6434, 6424, 6824);\n                    }\n                    if slot == 17 {\n                        return (6836, 6824, 7224);\n                    }\n                    if slot == 18 {\n                        return (7238, 7224, 7623);\n                    }\n                    if slot == 19 {\n                        return (7640, 7623, 8022);\n                    }\n                    if slot == 20 {\n                        return (8042, 8022, 8421);\n                    }\n                    if slot == 21 {\n                        return (8445, 8421, 8820);\n                    }\n                    if slot == 22 {\n                        return (8847, 8820, 9218);\n                    }\n                    if slot == 23 {\n                        return (9249, 9218, 9616);\n                    }\n                    if slot == 24 {\n                        return (9651, 9616, 10014);\n                    }\n                    if slot == 25 {\n                        return (10053, 10014, 10411);\n                    }\n                    if slot == 26 {\n                        return (10455, 10411, 10808);\n                    }\n                    if slot == 27 {\n                        return (10857, 10808, 11204);\n                    }\n                    if slot == 28 {\n                        return (11259, 11204, 11600);\n                    }\n                    if slot == 29 {\n                        return (11662, 11600, 11996);\n                    }\n                    if slot == 30 {\n                        return (12064, 11996, 12391);\n                    }\n                    if slot == 31 {\n                        return (12466, 12391, 12785);\n                    }\n                }\n            } else {\n                if slot < 48 {\n                    if slot == 32 {\n                        return (12868, 12785, 13180);\n                    }\n                    if slot == 33 {\n                        return (13270, 13180, 13573);\n                    }\n                    if slot == 34 {\n                        return (13672, 13573, 13966);\n                    }\n                    if slot == 35 {\n                        return (14074, 13966, 14359);\n                    }\n                    if slot == 36 {\n                        return (14476, 14359, 14751);\n                    }\n                    if slot == 37 {\n                        return (14879, 14751, 15143);\n                    }\n                    if slot == 38 {\n                        return (15281, 15143, 15534);\n                    }\n                    if slot == 39 {\n                        return (15683, 15534, 15924);\n                    }\n                    if slot == 40 {\n                        return (16081, 15924, 16314);\n                    }\n                    if slot == 41 {\n                        return (16487, 16314, 16703);\n                    }\n                    if slot == 42 {\n                        return (16889, 16703, 17091);\n                    }\n                    if slot == 43 {\n                        return (17291, 17091, 17479);\n                    }\n                    if slot == 44 {\n                        return (17693, 17479, 17867);\n                    }\n                    if slot == 45 {\n                        return (18096, 17867, 18253);\n                    }\n                    if slot == 46 {\n                        return (18498, 18253, 18639);\n                    }\n                    if slot == 47 {\n                        return (18900, 18639, 19024);\n                    }\n                } else {\n                    if slot == 48 {\n                        return (19302, 19024, 19409);\n                    }\n                    if slot == 49 {\n                        return (19704, 19409, 19792);\n                    }\n                    if slot == 50 {\n                        return (20113, 19792, 20175);\n                    }\n                    if slot == 51 {\n                        return (20508, 20175, 20557);\n                    }\n                    if slot == 52 {\n                        return (20910, 20557, 20939);\n                    }\n                    if slot == 53 {\n                        return (21313, 20939, 21320);\n                    }\n                    if slot == 54 {\n                        return (21715, 21320, 21699);\n                    }\n                    if slot == 55 {\n                        return (22117, 21699, 22078);\n                    }\n                    if slot == 56 {\n                        return (22519, 22078, 22457);\n                    }\n                    if slot == 57 {\n                        return (22921, 22457, 22834);\n                    }\n                    if slot == 58 {\n                        return (23323, 22834, 23210);\n                    }\n                    if slot == 59 {\n                        return (23725, 23210, 23586);\n                    }\n                    if slot == 60 {\n                        return (24127, 23586, 23961);\n                    }\n                    if slot == 61 {\n                        return (24530, 23961, 24335);\n                    }\n                    if slot == 62 {\n                        return (24932, 24335, 24708);\n                    }\n                    if slot == 63 {\n                        return (25334, 24708, 25080);\n                    }\n                }\n            }\n        } else {\n            if slot < 96 {\n                if slot < 80 {\n                    if slot == 64 {\n                        return (25736, 25080, 25451);\n                    }\n                    if slot == 65 {\n                        return (26138, 25451, 25821);\n                    }\n                    if slot == 66 {\n                        return (26540, 25821, 26190);\n                    }\n                    if slot == 67 {\n                        return (26942, 26190, 26558);\n                    }\n                    if slot == 68 {\n                        return (27344, 26558, 26925);\n                    }\n                    if slot == 69 {\n                        return (27747, 26925, 27291);\n                    }\n                    if slot == 70 {\n                        return (28149, 27291, 27656);\n                    }\n                    if slot == 71 {\n                        return (28551, 27656, 28020);\n                    }\n                    if slot == 72 {\n                        return (28953, 28020, 28383);\n                    }\n                    if slot == 73 {\n                        return (29355, 28383, 28745);\n                    }\n                    if slot == 74 {\n                        return (29757, 28745, 29106);\n                    }\n                    if slot == 75 {\n                        return (30159, 29106, 29466);\n                    }\n                    if slot == 76 {\n                        return (30561, 29466, 29824);\n                    }\n                    if slot == 77 {\n                        return (30964, 29824, 30182);\n                    }\n                    if slot == 78 {\n                        return (31366, 30182, 30538);\n                    }\n                    if slot == 79 {\n                        return (31768, 30538, 30893);\n                    }\n                } else {\n                    if slot == 80 {\n                        return (32171, 30893, 31248);\n                    }\n                    if slot == 81 {\n                        return (32572, 31248, 31600);\n                    }\n                    if slot == 82 {\n                        return (32974, 31600, 31952);\n                    }\n                    if slot == 83 {\n                        return (33376, 31952, 32303);\n                    }\n                    if slot == 84 {\n                        return (33778, 32303, 32652);\n                    }\n                    if slot == 85 {\n                        return (34181, 32652, 33000);\n                    }\n                    if slot == 86 {\n                        return (34583, 33000, 33347);\n                    }\n                    if slot == 87 {\n                        return (34985, 33347, 33692);\n                    }\n                    if slot == 88 {\n                        return (35387, 33692, 34037);\n                    }\n                    if slot == 89 {\n                        return (35789, 34037, 34380);\n                    }\n                    if slot == 90 {\n                        return (36194, 34380, 34721);\n                    }\n                    if slot == 91 {\n                        return (36593, 34721, 35062);\n                    }\n                    if slot == 92 {\n                        return (36995, 35062, 35401);\n                    }\n                    if slot == 93 {\n                        return (37398, 35401, 35738);\n                    }\n                    if slot == 94 {\n                        return (37800, 35738, 36075);\n                    }\n                    if slot == 95 {\n                        return (38202, 36075, 36410);\n                    }\n                }\n            } else {\n                if slot < 112 {\n                    if slot == 96 {\n                        return (38604, 36410, 36744);\n                    }\n                    if slot == 97 {\n                        return (39006, 36744, 37076);\n                    }\n                    if slot == 98 {\n                        return (39408, 37076, 37407);\n                    }\n                    if slot == 99 {\n                        return (39810, 37407, 37736);\n                    }\n                    if slot == 100 {\n                        return (40227, 37736, 38064);\n                    }\n                    if slot == 101 {\n                        return (40615, 38064, 38391);\n                    }\n                    if slot == 102 {\n                        return (41017, 38391, 38716);\n                    }\n                    if slot == 103 {\n                        return (41419, 38716, 39040);\n                    }\n                    if slot == 104 {\n                        return (41821, 39040, 39362);\n                    }\n                    if slot == 105 {\n                        return (42223, 39362, 39683);\n                    }\n                    if slot == 106 {\n                        return (42625, 39683, 40002);\n                    }\n                    if slot == 107 {\n                        return (43027, 40002, 40320);\n                    }\n                    if slot == 108 {\n                        return (43429, 40320, 40636);\n                    }\n                    if slot == 109 {\n                        return (43832, 40636, 40951);\n                    }\n                    if slot == 110 {\n                        return (44234, 40951, 41264);\n                    }\n                    if slot == 111 {\n                        return (44636, 41264, 41576);\n                    }\n                } else {\n                    if slot == 112 {\n                        return (45038, 41576, 41886);\n                    }\n                    if slot == 113 {\n                        return (45440, 41886, 42194);\n                    }\n                    if slot == 114 {\n                        return (45842, 42194, 42501);\n                    }\n                    if slot == 115 {\n                        return (46244, 42501, 42806);\n                    }\n                    if slot == 116 {\n                        return (46646, 42806, 43110);\n                    }\n                    if slot == 117 {\n                        return (47048, 43110, 43412);\n                    }\n                    if slot == 118 {\n                        return (47451, 43412, 43713);\n                    }\n                    if slot == 119 {\n                        return (47853, 43713, 44011);\n                    }\n                    if slot == 120 {\n                        return (48252, 44011, 44308);\n                    }\n                    if slot == 121 {\n                        return (48657, 44308, 44604);\n                    }\n                    if slot == 122 {\n                        return (49059, 44604, 44898);\n                    }\n                    if slot == 123 {\n                        return (49461, 44898, 45190);\n                    }\n                    if slot == 124 {\n                        return (49863, 45190, 45480);\n                    }\n                    if slot == 125 {\n                        return (50265, 45480, 45769);\n                    }\n                    if slot == 126 {\n                        return (50668, 45769, 46056);\n                    }\n                    if slot == 127 {\n                        return (51070, 46056, 46341);\n                    }\n                }\n            }\n        }\n    } else {\n        if slot < 192 {\n            if slot < 160 {\n                if slot < 144 {\n                    if slot == 128 {\n                        return (51472, 46341, 46624);\n                    }\n                    if slot == 129 {\n                        return (51874, 46624, 46906);\n                    }\n                    if slot == 130 {\n                        return (52285, 46906, 47186);\n                    }\n                    if slot == 131 {\n                        return (52678, 47186, 47464);\n                    }\n                    if slot == 132 {\n                        return (53080, 47464, 47741);\n                    }\n                    if slot == 133 {\n                        return (53482, 47741, 48015);\n                    }\n                    if slot == 134 {\n                        return (53885, 48015, 48288);\n                    }\n                    if slot == 135 {\n                        return (54287, 48288, 48559);\n                    }\n                    if slot == 136 {\n                        return (54689, 48559, 48828);\n                    }\n                    if slot == 137 {\n                        return (55091, 48828, 49095);\n                    }\n                    if slot == 138 {\n                        return (55493, 49095, 49361);\n                    }\n                    if slot == 139 {\n                        return (55895, 49361, 49624);\n                    }\n                    if slot == 140 {\n                        return (56297, 49624, 49886);\n                    }\n                    if slot == 141 {\n                        return (56699, 49886, 50146);\n                    }\n                    if slot == 142 {\n                        return (57102, 50146, 50404);\n                    }\n                    if slot == 143 {\n                        return (57504, 50404, 50660);\n                    }\n                } else {\n                    if slot == 144 {\n                        return (57906, 50660, 50914);\n                    }\n                    if slot == 145 {\n                        return (58308, 50914, 51166);\n                    }\n                    if slot == 146 {\n                        return (58710, 51166, 51417);\n                    }\n                    if slot == 147 {\n                        return (59112, 51417, 51665);\n                    }\n                    if slot == 148 {\n                        return (59514, 51665, 51911);\n                    }\n                    if slot == 149 {\n                        return (59916, 51911, 52156);\n                    }\n                    if slot == 150 {\n                        return (60320, 52156, 52398);\n                    }\n                    if slot == 151 {\n                        return (60721, 52398, 52639);\n                    }\n                    if slot == 152 {\n                        return (61123, 52639, 52878);\n                    }\n                    if slot == 153 {\n                        return (61525, 52878, 53114);\n                    }\n                    if slot == 154 {\n                        return (61927, 53114, 53349);\n                    }\n                    if slot == 155 {\n                        return (62329, 53349, 53581);\n                    }\n                    if slot == 156 {\n                        return (62731, 53581, 53812);\n                    }\n                    if slot == 157 {\n                        return (63133, 53812, 54040);\n                    }\n                    if slot == 158 {\n                        return (63536, 54040, 54267);\n                    }\n                    if slot == 159 {\n                        return (63938, 54267, 54491);\n                    }\n                    if slot == 160 {\n                        return (64343, 54491, 54714);\n                    }\n                }\n            } else {\n                if slot < 176 {\n                    if slot == 161 {\n                        return (64742, 54714, 54934);\n                    }\n                    if slot == 162 {\n                        return (65144, 54934, 55152);\n                    }\n                    if slot == 163 {\n                        return (65546, 55152, 55368);\n                    }\n                    if slot == 164 {\n                        return (65948, 55368, 55582);\n                    }\n                    if slot == 165 {\n                        return (66350, 55582, 55794);\n                    }\n                    if slot == 166 {\n                        return (66753, 55794, 56004);\n                    }\n                    if slot == 167 {\n                        return (67155, 56004, 56212);\n                    }\n                    if slot == 168 {\n                        return (67557, 56212, 56418);\n                    }\n                    if slot == 169 {\n                        return (67959, 56418, 56621);\n                    }\n                    if slot == 170 {\n                        return (68361, 56621, 56823);\n                    }\n                    if slot == 171 {\n                        return (68763, 56823, 57022);\n                    }\n                    if slot == 172 {\n                        return (69165, 57022, 57219);\n                    }\n                    if slot == 173 {\n                        return (69567, 57219, 57414);\n                    }\n                    if slot == 174 {\n                        return (69970, 57414, 57607);\n                    }\n                    if slot == 175 {\n                        return (70372, 57607, 57798);\n                    }\n                } else {\n                    if slot == 176 {\n                        return (70774, 57798, 57986);\n                    }\n                    if slot == 177 {\n                        return (71176, 57986, 58172);\n                    }\n                    if slot == 178 {\n                        return (71578, 58172, 58356);\n                    }\n                    if slot == 179 {\n                        return (71980, 58356, 58538);\n                    }\n                    if slot == 180 {\n                        return (72382, 58538, 58718);\n                    }\n                    if slot == 181 {\n                        return (72784, 58718, 58896);\n                    }\n                    if slot == 182 {\n                        return (73187, 58896, 59071);\n                    }\n                    if slot == 183 {\n                        return (73589, 59071, 59244);\n                    }\n                    if slot == 184 {\n                        return (73991, 59244, 59415);\n                    }\n                    if slot == 185 {\n                        return (74393, 59415, 59583);\n                    }\n                    if slot == 186 {\n                        return (74795, 59583, 59750);\n                    }\n                    if slot == 187 {\n                        return (75197, 59750, 59914);\n                    }\n                    if slot == 188 {\n                        return (75599, 59914, 60075);\n                    }\n                    if slot == 189 {\n                        return (76001, 60075, 60235);\n                    }\n                    if slot == 190 {\n                        return (76401, 60235, 60392);\n                    }\n                    if slot == 191 {\n                        return (76806, 60392, 60547);\n                    }\n                }\n            }\n        } else {\n            if slot < 224 {\n                if slot < 208 {\n                    if slot == 192 {\n                        return (77208, 60547, 60700);\n                    }\n                    if slot == 193 {\n                        return (77610, 60700, 60851);\n                    }\n                    if slot == 194 {\n                        return (78012, 60851, 60999);\n                    }\n                    if slot == 195 {\n                        return (78414, 60999, 61145);\n                    }\n                    if slot == 196 {\n                        return (78816, 61145, 61288);\n                    }\n                    if slot == 197 {\n                        return (79218, 61288, 61429);\n                    }\n                    if slot == 198 {\n                        return (79621, 61429, 61568);\n                    }\n                    if slot == 199 {\n                        return (80023, 61568, 61705);\n                    }\n                    if slot == 200 {\n                        return (80423, 61705, 61839);\n                    }\n                    if slot == 201 {\n                        return (80827, 61839, 61971);\n                    }\n                    if slot == 202 {\n                        return (81229, 61971, 62101);\n                    }\n                    if slot == 203 {\n                        return (81631, 62101, 62228);\n                    }\n                    if slot == 204 {\n                        return (82033, 62228, 62353);\n                    }\n                    if slot == 205 {\n                        return (82435, 62353, 62476);\n                    }\n                    if slot == 206 {\n                        return (82838, 62476, 62596);\n                    }\n                    if slot == 207 {\n                        return (83240, 62596, 62714);\n                    }\n                } else {\n                    if slot == 208 {\n                        return (83642, 62714, 62830);\n                    }\n                    if slot == 209 {\n                        return (84044, 62830, 62943);\n                    }\n                    if slot == 210 {\n                        return (84446, 62943, 63054);\n                    }\n                    if slot == 211 {\n                        return (84848, 63054, 63162);\n                    }\n                    if slot == 212 {\n                        return (85250, 63162, 63268);\n                    }\n                    if slot == 213 {\n                        return (85652, 63268, 63372);\n                    }\n                    if slot == 214 {\n                        return (86055, 63372, 63473);\n                    }\n                    if slot == 215 {\n                        return (86457, 63473, 63572);\n                    }\n                    if slot == 216 {\n                        return (86859, 63572, 63668);\n                    }\n                    if slot == 217 {\n                        return (87261, 63668, 63763);\n                    }\n                    if slot == 218 {\n                        return (87663, 63763, 63854);\n                    }\n                    if slot == 219 {\n                        return (88065, 63854, 63944);\n                    }\n                    if slot == 220 {\n                        return (88467, 63944, 64031);\n                    }\n                    if slot == 221 {\n                        return (88869, 64031, 64115);\n                    }\n                    if slot == 222 {\n                        return (89271, 64115, 64197);\n                    }\n                    if slot == 223 {\n                        return (89674, 64197, 64277);\n                    }\n                }\n            } else {\n                if slot < 240 {\n                    if slot == 224 {\n                        return (90076, 64277, 64354);\n                    }\n                    if slot == 225 {\n                        return (90478, 64354, 64429);\n                    }\n                    if slot == 226 {\n                        return (90880, 64429, 64501);\n                    }\n                    if slot == 227 {\n                        return (91282, 64501, 64571);\n                    }\n                    if slot == 228 {\n                        return (91684, 64571, 64639);\n                    }\n                    if slot == 229 {\n                        return (92086, 64639, 64704);\n                    }\n                    if slot == 230 {\n                        return (92491, 64704, 64766);\n                    }\n                    if slot == 231 {\n                        return (92891, 64766, 64827);\n                    }\n                    if slot == 232 {\n                        return (93293, 64827, 64884);\n                    }\n                    if slot == 233 {\n                        return (93695, 64884, 64940);\n                    }\n                    if slot == 234 {\n                        return (94097, 64940, 64993);\n                    }\n                    if slot == 235 {\n                        return (94499, 64993, 65043);\n                    }\n                    if slot == 236 {\n                        return (94901, 65043, 65091);\n                    }\n                    if slot == 237 {\n                        return (95303, 65091, 65137);\n                    }\n                    if slot == 238 {\n                        return (95705, 65137, 65180);\n                    }\n                    if slot == 239 {\n                        return (96108, 65180, 65220);\n                    }\n                } else {\n                    if slot == 240 {\n                        return (96514, 65220, 65259);\n                    }\n                    if slot == 241 {\n                        return (96912, 65259, 65294);\n                    }\n                    if slot == 242 {\n                        return (97314, 65294, 65328);\n                    }\n                    if slot == 243 {\n                        return (97716, 65328, 65358);\n                    }\n                    if slot == 244 {\n                        return (98118, 65358, 65387);\n                    }\n                    if slot == 245 {\n                        return (98520, 65387, 65413);\n                    }\n                    if slot == 246 {\n                        return (98922, 65413, 65436);\n                    }\n                    if slot == 247 {\n                        return (99325, 65436, 65457);\n                    }\n                    if slot == 248 {\n                        return (99727, 65457, 65476);\n                    }\n                    if slot == 249 {\n                        return (100129, 65476, 65492);\n                    }\n                    if slot == 250 {\n                        return (100531, 65492, 65505);\n                    }\n                    if slot == 251 {\n                        return (100933, 65505, 65516);\n                    }\n                    if slot == 252 {\n                        return (101335, 65516, 65525);\n                    }\n                    if slot == 253 {\n                        return (101737, 65525, 65531);\n                    }\n                    if slot == 254 {\n                        return (102139, 65531, 65535);\n                    }\n                }\n            }\n        }\n    }\n\n    (102542, 65535, 65536)\n}\n\nfn atan(a: u64) -> (u64, u64, u64) {\n    let slot = a / 459;\n\n    if slot == 0 {\n        return (0, 0, 459);\n    }\n    if slot == 1 {\n        return (459, 459, 917);\n    }\n    if slot == 2 {\n        return (918, 917, 1376);\n    }\n    if slot == 3 {\n        return (1376, 1376, 1835);\n    }\n    if slot == 4 {\n        return (1835, 1835, 2293);\n    }\n    if slot == 5 {\n        return (2294, 2293, 2751);\n    }\n    if slot == 6 {\n        return (2753, 2751, 3209);\n    }\n    if slot == 7 {\n        return (3211, 3209, 3666);\n    }\n    if slot == 8 {\n        return (3670, 3666, 4123);\n    }\n    if slot == 9 {\n        return (4129, 4123, 4580);\n    }\n    if slot == 10 {\n        return (4591, 4580, 5036);\n    }\n    if slot == 11 {\n        return (5046, 5036, 5492);\n    }\n    if slot == 12 {\n        return (5505, 5492, 5947);\n    }\n    if slot == 13 {\n        return (5964, 5947, 6402);\n    }\n    if slot == 14 {\n        return (6423, 6402, 6856);\n    }\n    if slot == 15 {\n        return (6881, 6856, 7310);\n    }\n    if slot == 16 {\n        return (7340, 7310, 7762);\n    }\n    if slot == 17 {\n        return (7799, 7762, 8214);\n    }\n    if slot == 18 {\n        return (8258, 8214, 8665);\n    }\n    if slot == 19 {\n        return (8716, 8665, 9116);\n    }\n    if slot == 20 {\n        return (9181, 9116, 9565);\n    }\n    if slot == 21 {\n        return (9634, 9565, 10014);\n    }\n    if slot == 22 {\n        return (10093, 10014, 10462);\n    }\n    if slot == 23 {\n        return (10551, 10462, 10908);\n    }\n    if slot == 24 {\n        return (11010, 10908, 11354);\n    }\n    if slot == 25 {\n        return (11469, 11354, 11798);\n    }\n    if slot == 26 {\n        return (11928, 11798, 12242);\n    }\n    if slot == 27 {\n        return (12386, 12242, 12684);\n    }\n    if slot == 28 {\n        return (12845, 12684, 13125);\n    }\n    if slot == 29 {\n        return (13304, 13125, 13565);\n    }\n    if slot == 30 {\n        return (13762, 13565, 14004);\n    }\n    if slot == 31 {\n        return (14221, 14004, 14442);\n    }\n    if slot == 32 {\n        return (14680, 14442, 14878);\n    }\n    if slot == 33 {\n        return (15139, 14878, 15313);\n    }\n    if slot == 34 {\n        return (15598, 15313, 15746);\n    }\n    if slot == 35 {\n        return (16056, 15746, 16178);\n    }\n    if slot == 36 {\n        return (16515, 16178, 16609);\n    }\n    if slot == 37 {\n        return (16974, 16609, 17038);\n    }\n    if slot == 38 {\n        return (17433, 17038, 17466);\n    }\n    if slot == 39 {\n        return (17891, 17466, 17892);\n    }\n    if slot == 40 {\n        return (18353, 17892, 18317);\n    }\n    if slot == 41 {\n        return (18809, 18317, 18740);\n    }\n    if slot == 42 {\n        return (19268, 18740, 19161);\n    }\n    if slot == 43 {\n        return (19726, 19161, 19581);\n    }\n    if slot == 44 {\n        return (20185, 19581, 19999);\n    }\n    if slot == 45 {\n        return (20644, 19999, 20416);\n    }\n    if slot == 46 {\n        return (21103, 20416, 20830);\n    }\n    if slot == 47 {\n        return (21561, 20830, 21243);\n    }\n    if slot == 48 {\n        return (22020, 21243, 21655);\n    }\n    if slot == 49 {\n        return (22479, 21655, 22064);\n    }\n    if slot == 50 {\n        return (22944, 22064, 22472);\n    }\n    if slot == 51 {\n        return (23396, 22472, 22878);\n    }\n    if slot == 52 {\n        return (23855, 22878, 23282);\n    }\n    if slot == 53 {\n        return (24314, 23282, 23685);\n    }\n    if slot == 54 {\n        return (24773, 23685, 24085);\n    }\n    if slot == 55 {\n        return (25231, 24085, 24484);\n    }\n    if slot == 56 {\n        return (25690, 24484, 24880);\n    }\n    if slot == 57 {\n        return (26149, 24880, 25275);\n    }\n    if slot == 58 {\n        return (26608, 25275, 25668);\n    }\n    if slot == 59 {\n        return (27066, 25668, 26059);\n    }\n    if slot == 60 {\n        return (27534, 26059, 26448);\n    }\n    if slot == 61 {\n        return (27984, 26448, 26835);\n    }\n    if slot == 62 {\n        return (28443, 26835, 27220);\n    }\n    if slot == 63 {\n        return (28901, 27220, 27603);\n    }\n    if slot == 64 {\n        return (29360, 27603, 27984);\n    }\n    if slot == 65 {\n        return (29819, 27984, 28363);\n    }\n    if slot == 66 {\n        return (30278, 28363, 28740);\n    }\n    if slot == 67 {\n        return (30736, 28740, 29115);\n    }\n    if slot == 68 {\n        return (31195, 29115, 29488);\n    }\n    if slot == 69 {\n        return (31654, 29488, 29859);\n    }\n    if slot == 70 {\n        return (32113, 29859, 30228);\n    }\n    if slot == 71 {\n        return (32571, 30228, 30595);\n    }\n    if slot == 72 {\n        return (33030, 30595, 30960);\n    }\n    if slot == 73 {\n        return (33489, 30960, 31323);\n    }\n    if slot == 74 {\n        return (33948, 31323, 31683);\n    }\n    if slot == 75 {\n        return (34406, 31683, 32042);\n    }\n    if slot == 76 {\n        return (34865, 32042, 32398);\n    }\n    if slot == 77 {\n        return (35324, 32398, 32753);\n    }\n    if slot == 78 {\n        return (35783, 32753, 33105);\n    }\n    if slot == 79 {\n        return (36241, 33105, 33455);\n    }\n    if slot == 80 {\n        return (36700, 33455, 33804);\n    }\n    if slot == 81 {\n        return (37159, 33804, 34150);\n    }\n    if slot == 82 {\n        return (37618, 34150, 34494);\n    }\n    if slot == 83 {\n        return (38076, 34494, 34836);\n    }\n    if slot == 84 {\n        return (38535, 34836, 35175);\n    }\n    if slot == 85 {\n        return (38994, 35175, 35513);\n    }\n    if slot == 86 {\n        return (39453, 35513, 35849);\n    }\n    if slot == 87 {\n        return (39911, 35849, 36183);\n    }\n    if slot == 88 {\n        return (40370, 36183, 36514);\n    }\n    if slot == 89 {\n        return (40829, 36514, 36843);\n    }\n    if slot == 90 {\n        return (41288, 36843, 37171);\n    }\n    if slot == 91 {\n        return (41746, 37171, 37496);\n    }\n    if slot == 92 {\n        return (42205, 37496, 37819);\n    }\n    if slot == 93 {\n        return (42664, 37819, 38141);\n    }\n    if slot == 94 {\n        return (43123, 38141, 38460);\n    }\n    if slot == 95 {\n        return (43581, 38460, 38777);\n    }\n    if slot == 96 {\n        return (44040, 38777, 39092);\n    }\n    if slot == 97 {\n        return (44499, 39092, 39405);\n    }\n    if slot == 98 {\n        return (44958, 39405, 39716);\n    }\n\n    (45416, 39716, 40025)\n}\n\nfn erf_lut(x: u64) -> u64 {\n    // Construct the erf lookup table\n    if x <= 5898 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 655 {\n            return 739;\n        }\n        if x <= 1310 {\n            return 1478;\n        }\n        if x <= 1966 {\n            return 2217;\n        }\n        if x <= 2621 {\n            return 2956;\n        }\n        if x <= 3276 {\n            return 3694;\n        }\n        if x <= 3932 {\n            return 4431;\n        }\n        if x <= 4587 {\n            return 5168;\n        }\n        if x <= 5242 {\n            return 5903;\n        }\n        if x <= 5898 {\n            return 6637;\n        }\n    }\n    if x <= 12451 {\n        if x <= 6553 {\n            return 7370;\n        }\n        if x <= 7208 {\n            return 8101;\n        }\n        if x <= 7864 {\n            return 8831;\n        }\n        if x <= 8519 {\n            return 9559;\n        }\n        if x <= 9175 {\n            return 10285;\n        }\n        if x <= 9830 {\n            return 11009;\n        }\n        if x <= 10485 {\n            return 11731;\n        }\n        if x <= 11141 {\n            return 12451;\n        }\n        if x <= 11796 {\n            return 13168;\n        }\n        if x <= 12451 {\n            return 13883;\n        }\n    }\n    if x <= 19005 {\n        if x <= 13107 {\n            return 14595;\n        }\n        if x <= 13762 {\n            return 15304;\n        }\n        if x <= 14417 {\n            return 16010;\n        }\n        if x <= 15073 {\n            return 16713;\n        }\n        if x <= 15728 {\n            return 17412;\n        }\n        if x <= 16384 {\n            return 18109;\n        }\n        if x <= 17039 {\n            return 18802;\n        }\n        if x <= 17694 {\n            return 19491;\n        }\n        if x <= 18350 {\n            return 20177;\n        }\n        if x <= 19005 {\n            return 20859;\n        }\n    }\n    if x <= 25559 {\n        if x <= 19660 {\n            return 21536;\n        }\n        if x <= 20316 {\n            return 22210;\n        }\n        if x <= 20971 {\n            return 22880;\n        }\n        if x <= 21626 {\n            return 23545;\n        }\n        if x <= 22282 {\n            return 24206;\n        }\n        if x <= 22937 {\n            return 24863;\n        }\n        if x <= 23592 {\n            return 25515;\n        }\n        if x <= 24248 {\n            return 26162;\n        }\n        if x <= 24903 {\n            return 26804;\n        }\n        if x <= 25559 {\n            return 27442;\n        }\n    }\n    if x <= 32112 {\n        if x <= 26214 {\n            return 28075;\n        }\n        if x <= 26869 {\n            return 28702;\n        }\n        if x <= 27525 {\n            return 29325;\n        }\n        if x <= 28180 {\n            return 29942;\n        }\n        if x <= 28835 {\n            return 30554;\n        }\n        if x <= 29491 {\n            return 31161;\n        }\n        if x <= 30146 {\n            return 31762;\n        }\n        if x <= 30801 {\n            return 32358;\n        }\n        if x <= 31457 {\n            return 32948;\n        }\n        if x <= 32112 {\n            return 33532;\n        }\n    }\n    if x <= 38666 {\n        if x <= 32768 {\n            return 34111;\n        }\n        if x <= 33423 {\n            return 34684;\n        }\n        if x <= 34078 {\n            return 35251;\n        }\n        if x <= 34734 {\n            return 35813;\n        }\n        if x <= 35389 {\n            return 36368;\n        }\n        if x <= 36044 {\n            return 36917;\n        }\n        if x <= 36700 {\n            return 37461;\n        }\n        if x <= 37355 {\n            return 37998;\n        }\n        if x <= 38010 {\n            return 38530;\n        }\n        if x <= 38666 {\n            return 39055;\n        }\n    }\n    if x <= 45219 {\n        if x <= 39321 {\n            return 39574;\n        }\n        if x <= 39976 {\n            return 40087;\n        }\n        if x <= 40632 {\n            return 40593;\n        }\n        if x <= 41287 {\n            return 41094;\n        }\n        if x <= 41943 {\n            return 41588;\n        }\n        if x <= 42598 {\n            return 42076;\n        }\n        if x <= 43253 {\n            return 42557;\n        }\n        if x <= 43909 {\n            return 43032;\n        }\n        if x <= 44564 {\n            return 43501;\n        }\n        if x <= 45219 {\n            return 43964;\n        }\n    }\n    if x <= 51773 {\n        if x <= 45875 {\n            return 44420;\n        }\n        if x <= 46530 {\n            return 44870;\n        }\n        if x <= 47185 {\n            return 45313;\n        }\n        if x <= 47841 {\n            return 45750;\n        }\n        if x <= 48496 {\n            return 46181;\n        }\n        if x <= 49152 {\n            return 46606;\n        }\n        if x <= 49807 {\n            return 47024;\n        }\n        if x <= 50462 {\n            return 47436;\n        }\n        if x <= 51118 {\n            return 47841;\n        }\n        if x <= 51773 {\n            return 48241;\n        }\n    }\n    if x <= 58327 {\n        if x <= 52428 {\n            return 48634;\n        }\n        if x <= 53084 {\n            return 49021;\n        }\n        if x <= 53739 {\n            return 49401;\n        }\n        if x <= 54394 {\n            return 49776;\n        }\n        if x <= 55050 {\n            return 50144;\n        }\n        if x <= 55705 {\n            return 50506;\n        }\n        if x <= 56360 {\n            return 50862;\n        }\n        if x <= 57016 {\n            return 51212;\n        }\n        if x <= 57671 {\n            return 51556;\n        }\n        if x <= 58327 {\n            return 51894;\n        }\n    }\n    if x <= 64880 {\n        if x <= 58982 {\n            return 52226;\n        }\n        if x <= 59637 {\n            return 52552;\n        }\n        if x <= 60293 {\n            return 52872;\n        }\n        if x <= 60948 {\n            return 53186;\n        }\n        if x <= 61603 {\n            return 53495;\n        }\n        if x <= 62259 {\n            return 53797;\n        }\n        if x <= 62914 {\n            return 54094;\n        }\n        if x <= 63569 {\n            return 54386;\n        }\n        if x <= 64225 {\n            return 54672;\n        }\n        if x <= 64880 {\n            return 54952;\n        }\n    }\n    if x <= 71434 {\n        if x <= 65536 {\n            return 55227;\n        }\n        if x <= 66191 {\n            return 55496;\n        }\n        if x <= 66846 {\n            return 55760;\n        }\n        if x <= 67502 {\n            return 56019;\n        }\n        if x <= 68157 {\n            return 56272;\n        }\n        if x <= 68812 {\n            return 56520;\n        }\n        if x <= 69468 {\n            return 56763;\n        }\n        if x <= 70123 {\n            return 57001;\n        }\n        if x <= 70778 {\n            return 57234;\n        }\n        if x <= 71434 {\n            return 57462;\n        }\n    }\n    if x <= 77987 {\n        if x <= 72089 {\n            return 57685;\n        }\n        if x <= 72744 {\n            return 57903;\n        }\n        if x <= 73400 {\n            return 58116;\n        }\n        if x <= 74055 {\n            return 58325;\n        }\n        if x <= 74711 {\n            return 58529;\n        }\n        if x <= 75366 {\n            return 58728;\n        }\n        if x <= 76021 {\n            return 58923;\n        }\n        if x <= 76677 {\n            return 59113;\n        }\n        if x <= 77332 {\n            return 59299;\n        }\n        if x <= 77987 {\n            return 59481;\n        }\n    }\n    if x <= 84541 {\n        if x <= 78643 {\n            return 59658;\n        }\n        if x <= 79298 {\n            return 59831;\n        }\n        if x <= 79953 {\n            return 60000;\n        }\n        if x <= 80609 {\n            return 60165;\n        }\n        if x <= 81264 {\n            return 60326;\n        }\n        if x <= 81920 {\n            return 60483;\n        }\n        if x <= 82575 {\n            return 60636;\n        }\n        if x <= 83230 {\n            return 60785;\n        }\n        if x <= 83886 {\n            return 60931;\n        }\n        if x <= 84541 {\n            return 61072;\n        }\n    }\n    if x <= 91095 {\n        if x <= 85196 {\n            return 61211;\n        }\n        if x <= 85852 {\n            return 61345;\n        }\n        if x <= 86507 {\n            return 61477;\n        }\n        if x <= 87162 {\n            return 61604;\n        }\n        if x <= 87818 {\n            return 61729;\n        }\n        if x <= 88473 {\n            return 61850;\n        }\n        if x <= 89128 {\n            return 61968;\n        }\n        if x <= 89784 {\n            return 62083;\n        }\n        if x <= 90439 {\n            return 62194;\n        }\n        if x <= 91095 {\n            return 62303;\n        }\n    }\n    if x <= 97648 {\n        if x <= 91750 {\n            return 62408;\n        }\n        if x <= 92405 {\n            return 62511;\n        }\n        if x <= 93061 {\n            return 62611;\n        }\n        if x <= 93716 {\n            return 62708;\n        }\n        if x <= 94371 {\n            return 62802;\n        }\n        if x <= 95027 {\n            return 62894;\n        }\n        if x <= 95682 {\n            return 62983;\n        }\n        if x <= 96337 {\n            return 63070;\n        }\n        if x <= 96993 {\n            return 63154;\n        }\n        if x <= 97648 {\n            return 63235;\n        }\n    }\n    if x <= 104202 {\n        if x <= 98304 {\n            return 63314;\n        }\n        if x <= 98959 {\n            return 63391;\n        }\n        if x <= 99614 {\n            return 63465;\n        }\n        if x <= 100270 {\n            return 63538;\n        }\n        if x <= 100925 {\n            return 63608;\n        }\n        if x <= 101580 {\n            return 63676;\n        }\n        if x <= 102236 {\n            return 63742;\n        }\n        if x <= 102891 {\n            return 63806;\n        }\n        if x <= 103546 {\n            return 63867;\n        }\n        if x <= 104202 {\n            return 63927;\n        }\n    }\n    if x <= 110755 {\n        if x <= 104857 {\n            return 63985;\n        }\n        if x <= 105512 {\n            return 64042;\n        }\n        if x <= 106168 {\n            return 64096;\n        }\n        if x <= 106823 {\n            return 64149;\n        }\n        if x <= 107479 {\n            return 64200;\n        }\n        if x <= 108134 {\n            return 64249;\n        }\n        if x <= 108789 {\n            return 64297;\n        }\n        if x <= 109445 {\n            return 64343;\n        }\n        if x <= 110100 {\n            return 64388;\n        }\n        if x <= 110755 {\n            return 64431;\n        }\n    }\n    if x <= 117309 {\n        if x <= 111411 {\n            return 64473;\n        }\n        if x <= 112066 {\n            return 64514;\n        }\n        if x <= 112721 {\n            return 64553;\n        }\n        if x <= 113377 {\n            return 64590;\n        }\n        if x <= 114032 {\n            return 64627;\n        }\n        if x <= 114688 {\n            return 64662;\n        }\n        if x <= 115343 {\n            return 64696;\n        }\n        if x <= 115998 {\n            return 64729;\n        }\n        if x <= 116654 {\n            return 64760;\n        }\n        if x <= 117309 {\n            return 64791;\n        }\n    }\n    if x <= 123863 {\n        if x <= 117964 {\n            return 64821;\n        }\n        if x <= 118620 {\n            return 64849;\n        }\n        if x <= 119275 {\n            return 64876;\n        }\n        if x <= 119930 {\n            return 64903;\n        }\n        if x <= 120586 {\n            return 64928;\n        }\n        if x <= 121241 {\n            return 64953;\n        }\n        if x <= 121896 {\n            return 64977;\n        }\n        if x <= 122552 {\n            return 64999;\n        }\n        if x <= 123207 {\n            return 65021;\n        }\n        if x <= 123863 {\n            return 65043;\n        }\n    }\n    if x <= 130416 {\n        if x <= 124518 {\n            return 65063;\n        }\n        if x <= 125173 {\n            return 65083;\n        }\n        if x <= 125829 {\n            return 65102;\n        }\n        if x <= 126484 {\n            return 65120;\n        }\n        if x <= 127139 {\n            return 65137;\n        }\n        if x <= 127795 {\n            return 65154;\n        }\n        if x <= 128450 {\n            return 65170;\n        }\n        if x <= 129105 {\n            return 65186;\n        }\n        if x <= 129761 {\n            return 65201;\n        }\n        if x <= 130416 {\n            return 65215;\n        }\n    }\n    if x <= 222822 {\n        if x <= 131072 {\n            return 65229;\n        }\n        if x <= 137625 {\n            return 65340;\n        }\n        if x <= 144179 {\n            return 65413;\n        }\n        if x <= 150732 {\n            return 65461;\n        }\n        if x <= 157286 {\n            return 65490;\n        }\n        if x <= 163840 {\n            return 65509;\n        }\n        if x <= 170393 {\n            return 65520;\n        }\n        if x <= 176947 {\n            return 65527;\n        }\n        if x <= 183500 {\n            return 65531;\n        }\n        if x <= 190054 {\n            return 65533;\n        }\n        if x <= 196608 {\n            return 65534;\n        }\n        if x <= 203161 {\n            return 65535;\n        }\n        if x <= 209715 {\n            return 65535;\n        }\n        if x <= 216268 {\n            return 65535;\n        }\n        if x <= 222822 {\n            return 65535;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp16x16wide/math/trig.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::lut;\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    HALF, ONE, TWO, FP16x16W, FP16x16WImpl, FP16x16WAdd, FP16x16WSub, FP16x16WMul, FP16x16WDiv,\n    FP16x16WIntoFelt252, FixedTrait\n};\n\n// CONSTANTS\nconst TWO_PI: u64 = 411775;\nconst PI: u64 = 205887;\nconst HALF_PI: u64 = 102944;\n\n// PUBLIC\n\n// Calculates arccos(a) for -1 <= a <= 1 (fixed point)\n// arccos(a) = arcsin(sqrt(1 - a^2)) - arctan identity has discontinuity at zero\nfn acos(a: FP16x16W) -> FP16x16W {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin(asin_arg);\n\n    if a.sign {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\nfn acos_fast(a: FP16x16W) -> FP16x16W {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin_fast(asin_arg);\n\n    if a.sign {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\n// Calculates arcsin(a) for -1 <= a <= 1 (fixed point)\n// arcsin(a) = arctan(a / sqrt(1 - a^2))\nfn asin(a: FP16x16W) -> FP16x16W {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan(a / div)\n}\n\nfn asin_fast(a: FP16x16W) -> FP16x16W {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan_fast(a / div)\n}\n\n// Calculates arctan(a) (fixed point)\n// See https://stackoverflow.com/a/50894477 for range adjustments\nfn atan(a: FP16x16W) -> FP16x16W {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 45875) {\n        let sqrt3_3 = FixedTrait::new(37837, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let r10 = FixedTrait::new(120, true) * at;\n    let r9 = (r10 + FixedTrait::new(3066, true)) * at;\n    let r8 = (r9 + FixedTrait::new(12727, false)) * at;\n    let r7 = (r8 + FixedTrait::new(17170, true)) * at;\n    let r6 = (r7 + FixedTrait::new(2865, false)) * at;\n    let r5 = (r6 + FixedTrait::new(12456, false)) * at;\n    let r4 = (r5 + FixedTrait::new(90, false)) * at;\n    let r3 = (r4 + FixedTrait::new(21852, true)) * at;\n    let r2 = r3 * at;\n    let mut res = (r2 + FixedTrait::new(65536, false)) * at;\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(34315, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\nfn atan_fast(a: FP16x16W) -> FP16x16W {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 45875) {\n        let sqrt3_3 = FixedTrait::new(37837, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let (start, low, high) = lut::atan(at.mag);\n    let partial_step = FixedTrait::new(at.mag - start, false) / FixedTrait::new(459, false);\n    let mut res = partial_step * FixedTrait::new(high - low, false) + FixedTrait::new(low, false);\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(34315, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::<FP16x16W>::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\n// Calculates cos(a) with a in radians (fixed point)\nfn cos(a: FP16x16W) -> FP16x16W {\n    sin(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn cos_fast(a: FP16x16W) -> FP16x16W {\n    sin_fast(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn sin(a: FP16x16W) -> FP16x16W {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, partial_rem) = integer::u64_safe_divmod(a1, integer::u64_as_non_zero(PI));\n    let a2 = FixedTrait::new(partial_rem, false);\n    let partial_sign = whole_rem == 1;\n\n    let loop_res = a2 * _sin_loop(a2, 7, FixedTrait::ONE());\n\n    FixedTrait::new(loop_res.mag, a.sign ^ partial_sign && loop_res.mag != 0)\n}\n\nfn sin_fast(a: FP16x16W) -> FP16x16W {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, mut partial_rem) = integer::u64_safe_divmod(a1, integer::u64_as_non_zero(PI));\n    let partial_sign = whole_rem == 1;\n\n    if partial_rem >= HALF_PI {\n        partial_rem = PI - partial_rem;\n    }\n\n    let (start, low, high) = lut::sin(partial_rem);\n    let partial_step = FixedTrait::new(partial_rem - start, false) / FixedTrait::new(402, false);\n    let res = partial_step * (FixedTrait::new(high, false) - FixedTrait::new(low, false))\n        + FixedTrait::<FP16x16W>::new(low, false);\n\n    FixedTrait::new(res.mag, a.sign ^ partial_sign && res.mag != 0)\n}\n\n// Calculates tan(a) with a in radians (fixed point)\nfn tan(a: FP16x16W) -> FP16x16W {\n    let sinx = sin(a);\n    let cosx = cos(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\nfn tan_fast(a: FP16x16W) -> FP16x16W {\n    let sinx = sin_fast(a);\n    let cosx = cos_fast(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\n// Helper function to calculate Taylor series for sin\nfn _sin_loop(a: FP16x16W, i: u64, acc: FP16x16W) -> FP16x16W {\n    let div = (2 * i + 2) * (2 * i + 3);\n    let term = a * a * acc / FixedTrait::new_unscaled(div, false);\n    let new_acc = FixedTrait::ONE() - term;\n\n    if (i == 0) {\n        return new_acc;\n    }\n\n    _sin_loop(a, i - 1, new_acc)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp16x16wide::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n        FP16x16WPartialEq, FP16x16WPrint\n    };\n\n    use super::{\n        FixedTrait, acos, HALF_PI, ONE, acos_fast, PI, atan_fast, atan, asin, cos, cos_fast, sin,\n        sin_fast, tan\n    };\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_acos() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos(a), 68629, 'invalid half', error); // 1.3687308642680\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos(a), 137258, 'invalid neg half', error); // 2.737461741902\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_acos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos_fast(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos_fast(a), 68629, 'invalid half', error); // 1.3687308642680\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos_fast(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos_fast(a), 137258, 'invalid neg half', error); // 2.737461741902\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos_fast(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(8000000)]\n    fn test_acos_fail() {\n        let a = FixedTrait::new(2 * ONE, true);\n        acos(a);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_atan_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan_fast(a), 72558, 'invalid two', error);\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan_fast(a), 51472, 'invalid one', error);\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan_fast(a), 30386, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert(atan_fast(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan_fast(a), -30386, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan_fast(a), -51472, 'invalid neg one', error);\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan_fast(a), -72558, 'invalid neg two', error);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan(a), 72558, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan(a), 51472, 'invalid one', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan(a), 30386, 'invalid half', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(atan(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan(a), -30386, 'invalid neg half', Option::None(()));\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan(a), -51472, 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan(a), -72558, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_asin() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert_relative(asin(a), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(asin(a), 34315, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert_precise(asin(a), 0, 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(asin(a), -34315, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(asin(a), -HALF_PI.into(), 'invalid neg one', Option::None(())); // -PI / 2\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(8000000)]\n    fn test_asin_fail() {\n        let a = FixedTrait::new(2 * ONE, false);\n        asin(a);\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_cos() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_relative(cos(a), 46341, 'invalid quarter pi', Option::None(())); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert_relative(cos(a), -1 * ONE.into(), 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_relative(cos(a), -18033, 'invalid 17', Option::None(())); // -0.21497123284870\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_relative(cos(a), -18033, 'invalid -17', Option::None(())); // -0.21497123284870\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_cos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos_fast(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(cos_fast(a), 46341, 'invalid quarter pi', error); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(cos_fast(a), -1 * ONE.into(), 'invalid pi', error);\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(cos_fast(a), -18033, 'invalid 17', error); // -0.21497123284870\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin(a), ONE.into(), 'invalid half pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin(a), 46341, 'invalid quarter pi', Option::None(())); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin(a), -ONE.into(), 'invalid neg half pi', Option::None(())\n        ); // 0.78124999999529\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin(a), -63006, 'invalid 17', Option::None(())); // -0.75109179053073\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin(a), 63006, 'invalid -17', Option::None(())); // 0.75109179053073\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_sin_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin_fast(a), ONE.into(), 'invalid half pi', error);\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin_fast(a), 46341, 'invalid quarter pi', error); // 0.55242717280199\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin_fast(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(sin_fast(a), -ONE.into(), 'invalid neg half pi', error); // 0.78124999999529\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin_fast(a), -63006, 'invalid 17', error); // -0.75109179053073\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin_fast(a), 63006, 'invalid -17', error); // 0.75109179053073\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_tan() {\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(tan(a), ONE.into(), 'invalid quarter pi', Option::None(()));\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(tan(a), 0, 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(tan(a), 228990, 'invalid 17', Option::None(())); // 3.3858731852805\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(tan(a), -228952, 'invalid -17', Option::None(())); // -3.3858731852805\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp32x32.cairo",
        "content": "mod core;\nmod comp;\nmod erf;\nmod lut;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp32x32/comp.cairo",
        "content": "use orion::numbers::{FP32x32, FP32x32Impl, FixedTrait};\n\nfn xor(a: FP32x32, b: FP32x32) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP32x32, b: FP32x32) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP32x32, b: FP32x32) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP32x32, b: FP32x32, c: FP32x32) -> FP32x32 {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP32x32, b: FP32x32) -> FP32x32 {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP32x32, b: FP32x32) -> FP32x32 {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP32x32, b: FP32x32) -> FP32x32 {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp32x32/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse cubit::f64 as fp32x32;\nuse cubit::f64::Fixed as FP32x32;\nuse cubit::f64::{ONE, HALF};\nuse cubit::f64::types::fixed;\n\nuse orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp32x32::erf;\nuse orion::numbers::fixed_point::utils;\n\nconst MAX: u64 = 9223372036854775808;\n\nimpl FP32x32Impl of FixedTrait<FP32x32, u64> {\n    fn ZERO() -> FP32x32 {\n        FP32x32 { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP32x32 {\n        FP32x32 { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP32x32 {\n        FP32x32 { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP32x32 {\n        FP32x32 { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u64, sign: bool) -> FP32x32 {\n        FP32x32 { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP32x32 {\n        FP32x32 { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP32x32 {\n        let mag = core::integer::u64_try_from_felt252(utils::felt_abs(val)).unwrap();\n\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::abs(self)\n    }\n\n    fn acos(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::acosh(self)\n    }\n\n    fn asin(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::asinh(self)\n    }\n\n    fn atan(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::atanh(self)\n    }\n\n    fn ceil(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::ceil(self)\n    }\n\n    fn cos(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::cosh(self)\n    }\n\n    fn floor(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP32x32, b: FP32x32) -> FP32x32 {\n        fp32x32::ops::pow(self, b)\n    }\n\n    fn round(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::round(self)\n    }\n\n    fn sin(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP32x32) -> FP32x32 {\n        fp32x32::ops::sqrt(self)\n    }\n\n    fn tan(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP32x32) -> FP32x32 {\n        fp32x32::trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP32x32) -> FP32x32 {\n        fp32x32::hyp::tanh(self)\n    }\n\n    fn sign(self: FP32x32) -> FP32x32 {\n        panic(array!['not supported!'])\n    }\n\n    fn NaN() -> FP32x32 {\n        FP32x32 { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP32x32) -> bool {\n        self == FP32x32 { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP32x32 {\n        FP32x32 { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP32x32 {\n        FP32x32 { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP32x32 {\n        FP32x32 { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP32x32) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP32x32) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP32x32) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP32x32) -> FP32x32 {\n        erf::erf(self)\n    }\n}\n\nimpl FP32x32Print of PrintTrait<FP32x32> {\n    fn print(self: FP32x32) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP32x32IntoFelt252 of Into<FP32x32, felt252> {\n    fn into(self: FP32x32) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP32x32TryIntoU64 of TryInto<FP32x32, u64> {\n    fn try_into(self: FP32x32) -> Option<u64> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP32x32TryIntoU16 of TryInto<FP32x32, u16> {\n    fn try_into(self: FP32x32) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP32x32TryIntoU32 of TryInto<FP32x32, u32> {\n    fn try_into(self: FP32x32) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP32x32TryIntoU8 of TryInto<FP32x32, u8> {\n    fn try_into(self: FP32x32) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP32x32TryIntoI8 of TryInto<FP32x32, i8> {\n    fn try_into(self: FP32x32) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\n// impl FP32x32PartialEq of PartialEq<FP32x32> {\n//     #[inline(always)]\n//     fn eq(lhs: @FP32x32, rhs: @FP32x32) -> bool {\n//         return fp32x32::ops::eq(lhs, rhs);\n//     }\n\n//     #[inline(always)]\n//     fn ne(lhs: @FP32x32, rhs: @FP32x32) -> bool {\n//         return fp32x32::ops::ne(lhs, rhs);\n//     }\n// }\n\nimpl FP32x32Add of Add<FP32x32> {\n    fn add(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        fp32x32::ops::add(lhs, rhs)\n    }\n}\n\nimpl FP32x32AddEq of AddEq<FP32x32> {\n    #[inline(always)]\n    fn add_eq(ref self: FP32x32, other: FP32x32) {\n        self = fp32x32::ops::add(self, other);\n    }\n}\n\nimpl FP32x32Sub of Sub<FP32x32> {\n    fn sub(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        fp32x32::ops::sub(lhs, rhs)\n    }\n}\n\nimpl FP32x32SubEq of SubEq<FP32x32> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP32x32, other: FP32x32) {\n        self = fp32x32::ops::sub(self, other);\n    }\n}\n\nimpl FP32x32Mul of Mul<FP32x32> {\n    fn mul(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        fp32x32::ops::mul(lhs, rhs)\n    }\n}\n\nimpl FP32x32MulEq of MulEq<FP32x32> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP32x32, other: FP32x32) {\n        self = fp32x32::ops::mul(self, other);\n    }\n}\n\nimpl FP32x32Div of Div<FP32x32> {\n    fn div(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        fp32x32::ops::div(lhs, rhs)\n    }\n}\n\nimpl FP32x32DivEq of DivEq<FP32x32> {\n    #[inline(always)]\n    fn div_eq(ref self: FP32x32, other: FP32x32) {\n        self = fp32x32::ops::div(self, other);\n    }\n}\n\nimpl FP32x32PartialOrd of PartialOrd<FP32x32> {\n    #[inline(always)]\n    fn ge(lhs: FP32x32, rhs: FP32x32) -> bool {\n        fp32x32::ops::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP32x32, rhs: FP32x32) -> bool {\n        fp32x32::ops::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP32x32, rhs: FP32x32) -> bool {\n        fp32x32::ops::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP32x32, rhs: FP32x32) -> bool {\n        fp32x32::ops::lt(lhs, rhs)\n    }\n}\n\nimpl FP32x32Neg of Neg<FP32x32> {\n    #[inline(always)]\n    fn neg(a: FP32x32) -> FP32x32 {\n        fp32x32::ops::neg(a)\n    }\n}\n\nimpl FP32x32Rem of Rem<FP32x32> {\n    #[inline(always)]\n    fn rem(lhs: FP32x32, rhs: FP32x32) -> FP32x32 {\n        fp32x32::ops::rem(lhs, rhs)\n    }\n}\n\nfn eq(a: @FP32x32, b: @FP32x32) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n/// INTERNAL\nfn _i8_try_from_fp(x: FP32x32) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp32x32/erf.cairo",
        "content": "use cubit::f64::ONE;\n\nuse orion::numbers::{FP32x32, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp32x32::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u64 = 100;\nconst ROUND_CHECK_NUMBER: u64 = 10;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u64 = 15032385536;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u64 = 8589934592;\n\nfn erf(x: FP32x32) -> FP32x32 {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u64 = 0_u64;\n\n    if x.mag < MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP32x32 { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp32x32/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp32x32::core::ONE;\n\nfn erf_lut(x: u64) -> u64 {\n    // Construct the erf lookup table\n    if x <= 386547056 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 42949672 {\n            return 48461900;\n        }\n        if x <= 85899345 {\n            return 96914110;\n        }\n        if x <= 128849018 {\n            return 145346943;\n        }\n        if x <= 171798691 {\n            return 193750725;\n        }\n        if x <= 214748364 {\n            return 242115801;\n        }\n        if x <= 257698037 {\n            return 290432536;\n        }\n        if x <= 300647710 {\n            return 338691327;\n        }\n        if x <= 343597383 {\n            return 386882604;\n        }\n        if x <= 386547056 {\n            return 434996838;\n        }\n    }\n    if x <= 816043786 {\n        if x <= 429496729 {\n            return 483024546;\n        }\n        if x <= 472446402 {\n            return 530956296;\n        }\n        if x <= 515396075 {\n            return 578782713;\n        }\n        if x <= 558345748 {\n            return 626494487;\n        }\n        if x <= 601295421 {\n            return 674082374;\n        }\n        if x <= 644245094 {\n            return 721537203;\n        }\n        if x <= 687194767 {\n            return 768849883;\n        }\n        if x <= 730144440 {\n            return 816011407;\n        }\n        if x <= 773094113 {\n            return 863012857;\n        }\n        if x <= 816043786 {\n            return 909845408;\n        }\n    }\n    if x <= 1245540515 {\n        if x <= 858993459 {\n            return 956500337;\n        }\n        if x <= 901943132 {\n            return 1002969022;\n        }\n        if x <= 944892805 {\n            return 1049242950;\n        }\n        if x <= 987842478 {\n            return 1095313724;\n        }\n        if x <= 1030792151 {\n            return 1141173063;\n        }\n        if x <= 1073741824 {\n            return 1186812808;\n        }\n        if x <= 1116691496 {\n            return 1232224928;\n        }\n        if x <= 1159641169 {\n            return 1277401521;\n        }\n        if x <= 1202590842 {\n            return 1322334823;\n        }\n        if x <= 1245540515 {\n            return 1367017205;\n        }\n    }\n    if x <= 1675037245 {\n        if x <= 1288490188 {\n            return 1411441184;\n        }\n        if x <= 1331439861 {\n            return 1455599421;\n        }\n        if x <= 1374389534 {\n            return 1499484729;\n        }\n        if x <= 1417339207 {\n            return 1543090073;\n        }\n        if x <= 1460288880 {\n            return 1586408573;\n        }\n        if x <= 1503238553 {\n            return 1629433512;\n        }\n        if x <= 1546188226 {\n            return 1672158333;\n        }\n        if x <= 1589137899 {\n            return 1714576645;\n        }\n        if x <= 1632087572 {\n            return 1756682226;\n        }\n        if x <= 1675037245 {\n            return 1798469022;\n        }\n    }\n    if x <= 2104533975 {\n        if x <= 1717986918 {\n            return 1839931154;\n        }\n        if x <= 1760936591 {\n            return 1881062918;\n        }\n        if x <= 1803886264 {\n            return 1921858787;\n        }\n        if x <= 1846835937 {\n            return 1962313411;\n        }\n        if x <= 1889785610 {\n            return 2002421622;\n        }\n        if x <= 1932735283 {\n            return 2042178436;\n        }\n        if x <= 1975684956 {\n            return 2081579049;\n        }\n        if x <= 2018634629 {\n            return 2120618846;\n        }\n        if x <= 2061584302 {\n            return 2159293393;\n        }\n        if x <= 2104533975 {\n            return 2197598448;\n        }\n    }\n    if x <= 2534030704 {\n        if x <= 2147483648 {\n            return 2235529952;\n        }\n        if x <= 2190433320 {\n            return 2273084038;\n        }\n        if x <= 2233382993 {\n            return 2310257026;\n        }\n        if x <= 2276332666 {\n            return 2347045424;\n        }\n        if x <= 2319282339 {\n            return 2383445931;\n        }\n        if x <= 2362232012 {\n            return 2419455435;\n        }\n        if x <= 2405181685 {\n            return 2455071011;\n        }\n        if x <= 2448131358 {\n            return 2490289925;\n        }\n        if x <= 2491081031 {\n            return 2525109629;\n        }\n        if x <= 2534030704 {\n            return 2559527765;\n        }\n    }\n    if x <= 2963527434 {\n        if x <= 2576980377 {\n            return 2593542161;\n        }\n        if x <= 2619930050 {\n            return 2627150830;\n        }\n        if x <= 2662879723 {\n            return 2660351971;\n        }\n        if x <= 2705829396 {\n            return 2693143967;\n        }\n        if x <= 2748779069 {\n            return 2725525382;\n        }\n        if x <= 2791728742 {\n            return 2757494964;\n        }\n        if x <= 2834678415 {\n            return 2789051637;\n        }\n        if x <= 2877628088 {\n            return 2820194507;\n        }\n        if x <= 2920577761 {\n            return 2850922852;\n        }\n        if x <= 2963527434 {\n            return 2881236128;\n        }\n    }\n    if x <= 3393024163 {\n        if x <= 3006477107 {\n            return 2911133960;\n        }\n        if x <= 3049426780 {\n            return 2940616146;\n        }\n        if x <= 3092376453 {\n            return 2969682651;\n        }\n        if x <= 3135326126 {\n            return 2998333604;\n        }\n        if x <= 3178275799 {\n            return 3026569298;\n        }\n        if x <= 3221225472 {\n            return 3054390188;\n        }\n        if x <= 3264175144 {\n            return 3081796886;\n        }\n        if x <= 3307124817 {\n            return 3108790160;\n        }\n        if x <= 3350074490 {\n            return 3135370928;\n        }\n        if x <= 3393024163 {\n            return 3161540260;\n        }\n    }\n    if x <= 3822520893 {\n        if x <= 3435973836 {\n            return 3187299373;\n        }\n        if x <= 3478923509 {\n            return 3212649627;\n        }\n        if x <= 3521873182 {\n            return 3237592522;\n        }\n        if x <= 3564822855 {\n            return 3262129696;\n        }\n        if x <= 3607772528 {\n            return 3286262922;\n        }\n        if x <= 3650722201 {\n            return 3309994103;\n        }\n        if x <= 3693671874 {\n            return 3333325270;\n        }\n        if x <= 3736621547 {\n            return 3356258580;\n        }\n        if x <= 3779571220 {\n            return 3378796308;\n        }\n        if x <= 3822520893 {\n            return 3400940848;\n        }\n    }\n    if x <= 4252017623 {\n        if x <= 3865470566 {\n            return 3422694710;\n        }\n        if x <= 3908420239 {\n            return 3444060511;\n        }\n        if x <= 3951369912 {\n            return 3465040979;\n        }\n        if x <= 3994319585 {\n            return 3485638942;\n        }\n        if x <= 4037269258 {\n            return 3505857331;\n        }\n        if x <= 4080218931 {\n            return 3525699170;\n        }\n        if x <= 4123168604 {\n            return 3545167580;\n        }\n        if x <= 4166118277 {\n            return 3564265768;\n        }\n        if x <= 4209067950 {\n            return 3582997028;\n        }\n        if x <= 4252017623 {\n            return 3601364736;\n        }\n    }\n    if x <= 4681514352 {\n        if x <= 4294967296 {\n            return 3619372346;\n        }\n        if x <= 4337916968 {\n            return 3637023387;\n        }\n        if x <= 4380866641 {\n            return 3654321460;\n        }\n        if x <= 4423816314 {\n            return 3671270233;\n        }\n        if x <= 4466765987 {\n            return 3687873439;\n        }\n        if x <= 4509715660 {\n            return 3704134870;\n        }\n        if x <= 4552665333 {\n            return 3720058378;\n        }\n        if x <= 4595615006 {\n            return 3735647866;\n        }\n        if x <= 4638564679 {\n            return 3750907289;\n        }\n        if x <= 4681514352 {\n            return 3765840647;\n        }\n    }\n    if x <= 5111011082 {\n        if x <= 4724464025 {\n            return 3780451987;\n        }\n        if x <= 4767413698 {\n            return 3794745393;\n        }\n        if x <= 4810363371 {\n            return 3808724986;\n        }\n        if x <= 4853313044 {\n            return 3822394923;\n        }\n        if x <= 4896262717 {\n            return 3835759389;\n        }\n        if x <= 4939212390 {\n            return 3848822598;\n        }\n        if x <= 4982162063 {\n            return 3861588787;\n        }\n        if x <= 5025111736 {\n            return 3874062214;\n        }\n        if x <= 5068061409 {\n            return 3886247156;\n        }\n        if x <= 5111011082 {\n            return 3898147905;\n        }\n    }\n    if x <= 5540507811 {\n        if x <= 5153960755 {\n            return 3909768765;\n        }\n        if x <= 5196910428 {\n            return 3921114049;\n        }\n        if x <= 5239860101 {\n            return 3932188077;\n        }\n        if x <= 5282809774 {\n            return 3942995173;\n        }\n        if x <= 5325759447 {\n            return 3953539662;\n        }\n        if x <= 5368709120 {\n            return 3963825868;\n        }\n        if x <= 5411658792 {\n            return 3973858111;\n        }\n        if x <= 5454608465 {\n            return 3983640704;\n        }\n        if x <= 5497558138 {\n            return 3993177952;\n        }\n        if x <= 5540507811 {\n            return 4002474150;\n        }\n    }\n    if x <= 5970004541 {\n        if x <= 5583457484 {\n            return 4011533577;\n        }\n        if x <= 5626407157 {\n            return 4020360499;\n        }\n        if x <= 5669356830 {\n            return 4028959162;\n        }\n        if x <= 5712306503 {\n            return 4037333795;\n        }\n        if x <= 5755256176 {\n            return 4045488602;\n        }\n        if x <= 5798205849 {\n            return 4053427767;\n        }\n        if x <= 5841155522 {\n            return 4061155446;\n        }\n        if x <= 5884105195 {\n            return 4068675768;\n        }\n        if x <= 5927054868 {\n            return 4075992834;\n        }\n        if x <= 5970004541 {\n            return 4083110714;\n        }\n    }\n    if x <= 6399501271 {\n        if x <= 6012954214 {\n            return 4090033445;\n        }\n        if x <= 6055903887 {\n            return 4096765032;\n        }\n        if x <= 6098853560 {\n            return 4103309442;\n        }\n        if x <= 6141803233 {\n            return 4109670609;\n        }\n        if x <= 6184752906 {\n            return 4115852426;\n        }\n        if x <= 6227702579 {\n            return 4121858749;\n        }\n        if x <= 6270652252 {\n            return 4127693393;\n        }\n        if x <= 6313601925 {\n            return 4133360131;\n        }\n        if x <= 6356551598 {\n            return 4138862695;\n        }\n        if x <= 6399501271 {\n            return 4144204773;\n        }\n    }\n    if x <= 6828998000 {\n        if x <= 6442450944 {\n            return 4149390008;\n        }\n        if x <= 6485400616 {\n            return 4154421999;\n        }\n        if x <= 6528350289 {\n            return 4159304298;\n        }\n        if x <= 6571299962 {\n            return 4164040410;\n        }\n        if x <= 6614249635 {\n            return 4168633795;\n        }\n        if x <= 6657199308 {\n            return 4173087863;\n        }\n        if x <= 6700148981 {\n            return 4177405975;\n        }\n        if x <= 6743098654 {\n            return 4181591444;\n        }\n        if x <= 6786048327 {\n            return 4185647533;\n        }\n        if x <= 6828998000 {\n            return 4189577456;\n        }\n    }\n    if x <= 7258494730 {\n        if x <= 6871947673 {\n            return 4193384375;\n        }\n        if x <= 6914897346 {\n            return 4197071404;\n        }\n        if x <= 6957847019 {\n            return 4200641603;\n        }\n        if x <= 7000796692 {\n            return 4204097984;\n        }\n        if x <= 7043746365 {\n            return 4207443505;\n        }\n        if x <= 7086696038 {\n            return 4210681075;\n        }\n        if x <= 7129645711 {\n            return 4213813550;\n        }\n        if x <= 7172595384 {\n            return 4216843737;\n        }\n        if x <= 7215545057 {\n            return 4219774388;\n        }\n        if x <= 7258494730 {\n            return 4222608207;\n        }\n    }\n    if x <= 7687991459 {\n        if x <= 7301444403 {\n            return 4225347845;\n        }\n        if x <= 7344394076 {\n            return 4227995903;\n        }\n        if x <= 7387343749 {\n            return 4230554929;\n        }\n        if x <= 7430293422 {\n            return 4233027424;\n        }\n        if x <= 7473243095 {\n            return 4235415834;\n        }\n        if x <= 7516192768 {\n            return 4237722559;\n        }\n        if x <= 7559142440 {\n            return 4239949947;\n        }\n        if x <= 7602092113 {\n            return 4242100295;\n        }\n        if x <= 7645041786 {\n            return 4244175854;\n        }\n        if x <= 7687991459 {\n            return 4246178824;\n        }\n    }\n    if x <= 8117488189 {\n        if x <= 7730941132 {\n            return 4248111357;\n        }\n        if x <= 7773890805 {\n            return 4249975557;\n        }\n        if x <= 7816840478 {\n            return 4251773482;\n        }\n        if x <= 7859790151 {\n            return 4253507139;\n        }\n        if x <= 7902739824 {\n            return 4255178493;\n        }\n        if x <= 7945689497 {\n            return 4256789460;\n        }\n        if x <= 7988639170 {\n            return 4258341912;\n        }\n        if x <= 8031588843 {\n            return 4259837674;\n        }\n        if x <= 8074538516 {\n            return 4261278529;\n        }\n        if x <= 8117488189 {\n            return 4262666214;\n        }\n    }\n    if x <= 8546984919 {\n        if x <= 8160437862 {\n            return 4264002425;\n        }\n        if x <= 8203387535 {\n            return 4265288813;\n        }\n        if x <= 8246337208 {\n            return 4266526989;\n        }\n        if x <= 8289286881 {\n            return 4267718520;\n        }\n        if x <= 8332236554 {\n            return 4268864936;\n        }\n        if x <= 8375186227 {\n            return 4269967724;\n        }\n        if x <= 8418135900 {\n            return 4271028331;\n        }\n        if x <= 8461085573 {\n            return 4272048167;\n        }\n        if x <= 8504035246 {\n            return 4273028604;\n        }\n        if x <= 8546984919 {\n            return 4273970975;\n        }\n    }\n    if x <= 14602888806 {\n        if x <= 8589934592 {\n            return 4274876577;\n        }\n        if x <= 9019431321 {\n            return 4282170584;\n        }\n        if x <= 9448928051 {\n            return 4286966432;\n        }\n        if x <= 9878424780 {\n            return 4290057389;\n        }\n        if x <= 10307921510 {\n            return 4292010151;\n        }\n        if x <= 10737418240 {\n            return 4293219450;\n        }\n        if x <= 11166914969 {\n            return 4293953535;\n        }\n        if x <= 11596411699 {\n            return 4294390341;\n        }\n        if x <= 12025908428 {\n            return 4294645116;\n        }\n        if x <= 12455405158 {\n            return 4294790781;\n        }\n        if x <= 12884901888 {\n            return 4294872418;\n        }\n        if x <= 13314398617 {\n            return 4294917265;\n        }\n        if x <= 13743895347 {\n            return 4294941415;\n        }\n        if x <= 14173392076 {\n            return 4294954163;\n        }\n        if x <= 14602888806 {\n            return 4294960759;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp64x64.cairo",
        "content": "mod core;\nmod comp;\nmod erf;\nmod lut;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp64x64/comp.cairo",
        "content": "use orion::numbers::{FP64x64, FixedTrait};\nuse orion::numbers::FP64x64Impl;\n\nfn xor(a: FP64x64, b: FP64x64) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP64x64, b: FP64x64) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP64x64, b: FP64x64) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP64x64, b: FP64x64, c: FP64x64) -> FP64x64 {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP64x64, b: FP64x64) -> FP64x64 {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP64x64, b: FP64x64) -> FP64x64 {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP64x64, b: FP64x64) -> FP64x64 {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp64x64/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse cubit::f128 as fp64x64;\nuse cubit::f128::types::Fixed as FP64x64;\nuse cubit::f128::ONE_u128 as ONE;\nuse cubit::f128::ops::MAX_u128 as MAX;\n\nuse orion::numbers::fixed_point::implementations::fp64x64::erf;\nuse orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::numbers::fixed_point::utils;\n\nconst HALF: u128 = 9223372036854775808_u128; // 2 ** 63\n\nimpl FP64x64Impl of FixedTrait<FP64x64, u128> {\n    fn ZERO() -> FP64x64 {\n        FP64x64 { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP64x64 {\n        FP64x64 { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP64x64 {\n        FP64x64 { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP64x64 {\n        FP64x64 { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u128, sign: bool) -> FP64x64 {\n        FP64x64 { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u128, sign: bool) -> FP64x64 {\n        FP64x64 { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP64x64 {\n        let mag = core::integer::u128_try_from_felt252(utils::felt_abs(val)).unwrap();\n\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::abs(self)\n    }\n\n    fn acos(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::acosh(self)\n    }\n\n    fn asin(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::asinh(self)\n    }\n\n    fn atan(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::atanh(self)\n    }\n\n    fn ceil(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::ceil(self)\n    }\n\n    fn cos(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::cosh(self)\n    }\n\n    fn floor(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP64x64, b: FP64x64) -> FP64x64 {\n        fp64x64::ops::pow(self, b)\n    }\n\n    fn round(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::round(self)\n    }\n\n    fn sin(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP64x64) -> FP64x64 {\n        fp64x64::ops::sqrt(self)\n    }\n\n    fn tan(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP64x64) -> FP64x64 {\n        fp64x64::trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP64x64) -> FP64x64 {\n        fp64x64::hyp::tanh(self)\n    }\n\n    fn sign(self: FP64x64) -> FP64x64 {\n        panic(array!['not supported!'])\n    }\n\n    fn NaN() -> FP64x64 {\n        FP64x64 { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP64x64) -> bool {\n        self == FP64x64 { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP64x64 {\n        FP64x64 { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP64x64 {\n        FP64x64 { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP64x64 {\n        FP64x64 { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP64x64) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP64x64) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP64x64) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP64x64) -> FP64x64 {\n        erf::erf(self)\n    }\n}\n\nimpl FP64x64Print of PrintTrait<FP64x64> {\n    fn print(self: FP64x64) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP64x64IntoFelt252 of Into<FP64x64, felt252> {\n    fn into(self: FP64x64) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP64x64TryIntoU128 of TryInto<FP64x64, u128> {\n    fn try_into(self: FP64x64) -> Option<u128> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP64x64TryIntoU16 of TryInto<FP64x64, u16> {\n    fn try_into(self: FP64x64) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP64x64TryIntoU32 of TryInto<FP64x64, u32> {\n    fn try_into(self: FP64x64) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP64x64TryIntoU8 of TryInto<FP64x64, u8> {\n    fn try_into(self: FP64x64) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP64x64TryIntoI8 of TryInto<FP64x64, i8> {\n    fn try_into(self: FP64x64) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\n// impl FP64x64PartialEq of PartialEq<FP64x64> {\n//     #[inline(always)]\n//     fn eq(lhs: @FP64x64, rhs: @FP64x64) -> bool {\n//         return fp64x64::ops::eq(lhs, rhs);\n//     }\n\n//     #[inline(always)]\n//     fn ne(lhs: @FP64x64, rhs: @FP64x64) -> bool {\n//         return fp64x64::ops::ne(lhs, rhs);\n//     }\n// }\n\nimpl FP64x64Add of Add<FP64x64> {\n    fn add(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        fp64x64::ops::add(lhs, rhs)\n    }\n}\n\nimpl FP64x64AddEq of AddEq<FP64x64> {\n    #[inline(always)]\n    fn add_eq(ref self: FP64x64, other: FP64x64) {\n        self = fp64x64::ops::add(self, other);\n    }\n}\n\nimpl FP64x64Sub of Sub<FP64x64> {\n    fn sub(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        fp64x64::ops::sub(lhs, rhs)\n    }\n}\n\nimpl FP64x64SubEq of SubEq<FP64x64> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP64x64, other: FP64x64) {\n        self = fp64x64::ops::sub(self, other);\n    }\n}\n\nimpl FP64x64Mul of Mul<FP64x64> {\n    fn mul(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        fp64x64::ops::mul(lhs, rhs)\n    }\n}\n\nimpl FP64x64MulEq of MulEq<FP64x64> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP64x64, other: FP64x64) {\n        self = fp64x64::ops::mul(self, other);\n    }\n}\n\nimpl FP64x64Div of Div<FP64x64> {\n    fn div(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        fp64x64::ops::div(lhs, rhs)\n    }\n}\n\nimpl FP64x64DivEq of DivEq<FP64x64> {\n    #[inline(always)]\n    fn div_eq(ref self: FP64x64, other: FP64x64) {\n        self = fp64x64::ops::div(self, other);\n    }\n}\n\nimpl FP64x64PartialOrd of PartialOrd<FP64x64> {\n    #[inline(always)]\n    fn ge(lhs: FP64x64, rhs: FP64x64) -> bool {\n        fp64x64::ops::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP64x64, rhs: FP64x64) -> bool {\n        fp64x64::ops::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP64x64, rhs: FP64x64) -> bool {\n        fp64x64::ops::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP64x64, rhs: FP64x64) -> bool {\n        fp64x64::ops::lt(lhs, rhs)\n    }\n}\n\nimpl FP64x64Neg of Neg<FP64x64> {\n    #[inline(always)]\n    fn neg(a: FP64x64) -> FP64x64 {\n        fp64x64::ops::neg(a)\n    }\n}\n\nimpl FP64x64Rem of Rem<FP64x64> {\n    #[inline(always)]\n    fn rem(lhs: FP64x64, rhs: FP64x64) -> FP64x64 {\n        fp64x64::ops::rem(lhs, rhs)\n    }\n}\n\nfn eq(a: @FP64x64, b: @FP64x64) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n/// INTERNAL\nfn _i8_try_from_fp(x: FP64x64) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp64x64/erf.cairo",
        "content": "use cubit::f128::ONE_u128 as ONE;\n\nuse orion::numbers::{FP64x64, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp64x64::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u128 = 100_u128;\nconst ROUND_CHECK_NUMBER: u128 = 10_u128;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u128 = 64563604257983430656_u128;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u128 = 36893488147419103232_u128;\n\nfn erf(x: FP64x64) -> FP64x64 {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u128 = 0_u128;\n\n    if x.mag <= MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP64x64 { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp64x64/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp64x64::core::ONE;\n\nfn erf_lut(x: u128) -> u128 {\n    // Construct the erf lookup table\n    if x <= 1660206966633859584 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 184467440737095520 {\n            return 208142279036071072;\n        }\n        if x <= 368934881474191040 {\n            return 416242934472567232;\n        }\n        if x <= 553402322211286528 {\n            return 624260367679495296;\n        }\n        if x <= 737869762948382080 {\n            return 832153029941062528;\n        }\n        if x <= 922337203685477632 {\n            return 1039879447350402944;\n        }\n        if x <= 1106804644422573056 {\n            return 1247398245629553408;\n        }\n        if x <= 1291272085159668736 {\n            return 1454668174849927424;\n        }\n        if x <= 1475739525896764160 {\n            return 1661648134028665088;\n        }\n        if x <= 1660206966633859584 {\n            return 1868297195576427008;\n        }\n    }\n    if x <= 3504881374004814848 {\n        if x <= 1844674407370955264 {\n            return 2074574629572391936;\n        }\n        if x <= 2029141848108050688 {\n            return 2280439927842463744;\n        }\n        if x <= 2213609288845146112 {\n            return 2485852827816977408;\n        }\n        if x <= 2398076729582241792 {\n            return 2690773336144481280;\n        }\n        if x <= 2582544170319337472 {\n            return 2895161752038532608;\n        }\n        if x <= 2767011611056432640 {\n            return 3098978690334796800;\n        }\n        if x <= 2951479051793528320 {\n            return 3302185104236156928;\n        }\n        if x <= 3135946492530624000 {\n            return 3504742307723958272;\n        }\n        if x <= 3320413933267719168 {\n            return 3706611997613982720;\n        }\n        if x <= 3504881374004814848 {\n            return 3907756275236240384;\n        }\n    }\n    if x <= 5349555781375769600 {\n        if x <= 3689348814741910528 {\n            return 4108137667718166528;\n        }\n        if x <= 3873816255479005696 {\n            return 4307719148851377152;\n        }\n        if x <= 4058283696216101376 {\n            return 4506464159522699776;\n        }\n        if x <= 4242751136953197056 {\n            return 4704336627690769408;\n        }\n        if x <= 4427218577690292224 {\n            return 4901300987890141184;\n        }\n        if x <= 4611686018427387904 {\n            return 5097322200245477376;\n        }\n        if x <= 4796153459164483584 {\n            return 5292365768979031040;\n        }\n        if x <= 4980620899901579264 {\n            return 5486397760395360256;\n        }\n        if x <= 5165088340638674944 {\n            return 5679384820327877632;\n        }\n        if x <= 5349555781375769600 {\n            return 5871294191032579072;\n        }\n    }\n    if x <= 7194230188746725376 {\n        if x <= 5534023222112865280 {\n            return 6062093727515032576;\n        }\n        if x <= 5718490662849960960 {\n            return 6251751913277435904;\n        }\n        if x <= 5902958103587056640 {\n            return 6440237875473368064;\n        }\n        if x <= 6087425544324152320 {\n            return 6627521399458594816;\n        }\n        if x <= 6271892985061248000 {\n            return 6813572942727099392;\n        }\n        if x <= 6456360425798342656 {\n            return 6998363648222307328;\n        }\n        if x <= 6640827866535438336 {\n            return 7181865357014296576;\n        }\n        if x <= 6825295307272534016 {\n            return 7364050620334585856;\n        }\n        if x <= 7009762748009629696 {\n            return 7544892710960923648;\n        }\n        if x <= 7194230188746725376 {\n            return 7724365633945352192;\n        }\n    }\n    if x <= 9038904596117680128 {\n        if x <= 7378697629483821056 {\n            return 7902444136679609344;\n        }\n        if x <= 7563165070220915712 {\n            return 8079103718292817920;\n        }\n        if x <= 7747632510958011392 {\n            return 8254320638377208832;\n        }\n        if x <= 7932099951695107072 {\n            return 8428071925038478336;\n        }\n        if x <= 8116567392432202752 {\n            return 8600335382268215296;\n        }\n        if x <= 8301034833169298432 {\n            return 8771089596636659712;\n        }\n        if x <= 8485502273906394112 {\n            return 8940313943304876032;\n        }\n        if x <= 8669969714643488768 {\n            return 9107988591356256256;\n        }\n        if x <= 8854437155380584448 {\n            return 9274094508448081920;\n        }\n        if x <= 9038904596117680128 {\n            return 9438613464784658432;\n        }\n    }\n    if x <= 10883579003488634880 {\n        if x <= 9223372036854775808 {\n            return 9601528036414361600;\n        }\n        if x <= 9407839477591871488 {\n            return 9762821607853701120;\n        }\n        if x <= 9592306918328967168 {\n            return 9922478374042292224;\n        }\n        if x <= 9776774359066062848 {\n            return 10080483341633368064;\n        }\n        if x <= 9961241799803158528 {\n            return 10236822329625237504;\n        }\n        if x <= 10145709240540254208 {\n            return 10391481969339820032;\n        }\n        if x <= 10330176681277349888 {\n            return 10544449703755059200;\n        }\n        if x <= 10514644122014443520 {\n            return 10695713786198818816;\n        }\n        if x <= 10699111562751539200 {\n            return 10845263278412423168;\n        }\n        if x <= 10883579003488634880 {\n            return 10993088047992748032;\n        }\n    }\n    if x <= 12728253410859589632 {\n        if x <= 11068046444225730560 {\n            return 11139178765222393856;\n        }\n        if x <= 11252513884962826240 {\n            return 11283526899298078720;\n        }\n        if x <= 11436981325699921920 {\n            return 11426124713968005120;\n        }\n        if x <= 11621448766437017600 {\n            return 11566965262589513728;\n        }\n        if x <= 11805916207174113280 {\n            return 11706042382618923008;\n        }\n        if x <= 11990383647911208960 {\n            return 11843350689545969664;\n        }\n        if x <= 12174851088648304640 {\n            return 11978885570285762560;\n        }\n        if x <= 12359318529385400320 {\n            return 12112643176041672704;\n        }\n        if x <= 12543785970122496000 {\n            return 12244620414653018112;\n        }\n        if x <= 12728253410859589632 {\n            return 12374814942441867264;\n        }\n    }\n    if x <= 14572927818230546432 {\n        if x <= 12912720851596685312 {\n            return 12503225155573657600;\n        }\n        if x <= 13097188292333780992 {\n            return 12629850180946728960;\n        }\n        if x <= 13281655733070876672 {\n            return 12754689866626244608;\n        }\n        if x <= 13466123173807972352 {\n            return 12877744771838261248;\n        }\n        if x <= 13650590614545068032 {\n            return 12999016156540069888;\n        }\n        if x <= 13835058055282163712 {\n            return 13118505970583140352;\n        }\n        if x <= 14019525496019259392 {\n            return 13236216842485327872;\n        }\n        if x <= 14203992936756355072 {\n            return 13352152067829151744;\n        }\n        if x <= 14388460377493450752 {\n            return 13466315597303212032;\n        }\n        if x <= 14572927818230546432 {\n            return 13578712024403965952;\n        }\n    }\n    if x <= 16417602225601501184 {\n        if x <= 14757395258967642112 {\n            return 13689346572815177728;\n        }\n        if x <= 14941862699704737792 {\n            return 13798225083482576896;\n        }\n        if x <= 15126330140441831424 {\n            return 13905354001401262080;\n        }\n        if x <= 15310797581178927104 {\n            return 14010740362133477376;\n        }\n        if x <= 15495265021916022784 {\n            return 14114391778074478592;\n        }\n        if x <= 15679732462653118464 {\n            return 14216316424484128768;\n        }\n        if x <= 15864199903390214144 {\n            return 14316523025301962752;\n        }\n        if x <= 16048667344127309824 {\n            return 14415020838763323392;\n        }\n        if x <= 16233134784864405504 {\n            return 14511819642834194432;\n        }\n        if x <= 16417602225601501184 {\n            return 14606929720482222080;\n        }\n    }\n    if x <= 18262276632972455936 {\n        if x <= 16602069666338596864 {\n            return 14700361844801351680;\n        }\n        if x <= 16786537107075692544 {\n            return 14792127264007346176;\n        }\n        if x <= 16971004547812788224 {\n            return 14882237686321330176;\n        }\n        if x <= 17155471988549883904 {\n            return 14970705264758325248;\n        }\n        if x <= 17339939429286977536 {\n            return 15057542581837537280;\n        }\n        if x <= 17524406870024073216 {\n            return 15142762634230988800;\n        }\n        if x <= 17708874310761168896 {\n            return 15226378817366812672;\n        }\n        if x <= 17893341751498264576 {\n            return 15308404910003300352;\n        }\n        if x <= 18077809192235360256 {\n            return 15388855058789533696;\n        }\n        if x <= 18262276632972455936 {\n            return 15467743762828154880;\n        }\n    }\n    if x <= 20106951040343412736 {\n        if x <= 18446744073709551616 {\n            return 15545085858255493120;\n        }\n        if x <= 18631211514446647296 {\n            return 15620896502854008832;\n        }\n        if x <= 18815678955183742976 {\n            return 15695191160711634944;\n        }\n        if x <= 19000146395920838656 {\n            return 15767985586942304256;\n        }\n        if x <= 19184613836657934336 {\n            return 15839295812481531904;\n        }\n        if x <= 19369081277395030016 {\n            return 15909138128970633216;\n        }\n        if x <= 19553548718132125696 {\n            return 15977529073742716928;\n        }\n        if x <= 19738016158869221376 {\n            return 16044485414923208704;\n        }\n        if x <= 19922483599606317056 {\n            return 16110024136657332224;\n        }\n        if x <= 20106951040343412736 {\n            return 16174162424476436480;\n        }\n    }\n    if x <= 21951625447714365440 {\n        if x <= 20291418481080508416 {\n            return 16236917650814795776;\n        }\n        if x <= 20475885921817604096 {\n            return 16298307360687947776;\n        }\n        if x <= 20660353362554699776 {\n            return 16358349257543309312;\n        }\n        if x <= 20844820803291791360 {\n            return 16417061189293291520;\n        }\n        if x <= 21029288244028887040 {\n            return 16474461134540791808;\n        }\n        if x <= 21213755684765982720 {\n            return 16530567189006364672;\n        }\n        if x <= 21398223125503078400 {\n            return 16585397552166088704;\n        }\n        if x <= 21582690566240174080 {\n            return 16638970514108524544;\n        }\n        if x <= 21767158006977269760 {\n            return 16691304442618875904;\n        }\n        if x <= 21951625447714365440 {\n            return 16742417770497863680;\n        }\n    }\n    if x <= 23796299855085322240 {\n        if x <= 22136092888451461120 {\n            return 16792328983122491392;\n        }\n        if x <= 22320560329188556800 {\n            return 16841056606255333376;\n        }\n        if x <= 22505027769925652480 {\n            return 16888619194108602368;\n        }\n        if x <= 22689495210662748160 {\n            return 16935035317668771840;\n        }\n        if x <= 22873962651399843840 {\n            return 16980323553287045120;\n        }\n        if x <= 23058430092136939520 {\n            return 17024502471540604928;\n        }\n        if x <= 23242897532874035200 {\n            return 17067590626369081344;\n        }\n        if x <= 23427364973611130880 {\n            return 17109606544490213376;\n        }\n        if x <= 23611832414348226560 {\n            return 17150568715098355712;\n        }\n        if x <= 23796299855085322240 {\n            return 17190495579848931328;\n        }\n    }\n    if x <= 25640974262456274944 {\n        if x <= 23980767295822417920 {\n            return 17229405523131617280;\n        }\n        if x <= 24165234736559513600 {\n            return 17267316862634573824;\n        }\n        if x <= 24349702177296609280 {\n            return 17304247840201650176;\n        }\n        if x <= 24534169618033704960 {\n            return 17340216612984107008;\n        }\n        if x <= 24718637058770800640 {\n            return 17375241244887996416;\n        }\n        if x <= 24903104499507896320 {\n            return 17409339698317971456;\n        }\n        if x <= 25087571940244992000 {\n            return 17442529826217906176;\n        }\n        if x <= 25272039380982087680 {\n            return 17474829364408369152;\n        }\n        if x <= 25456506821719179264 {\n            return 17506255924220641280;\n        }\n        if x <= 25640974262456274944 {\n            return 17536826985426591744;\n        }\n    }\n    if x <= 27485648669827231744 {\n        if x <= 25825441703193370624 {\n            return 17566559889463431168;\n        }\n        if x <= 26009909143930466304 {\n            return 17595471832952045568;\n        }\n        if x <= 26194376584667561984 {\n            return 17623579861507229696;\n        }\n        if x <= 26378844025404657664 {\n            return 17650900863837954048;\n        }\n        if x <= 26563311466141753344 {\n            return 17677451566135410688;\n        }\n        if x <= 26747778906878849024 {\n            return 17703248526746337280;\n        }\n        if x <= 26932246347615944704 {\n            return 17728308131128877056;\n        }\n        if x <= 27116713788353040384 {\n            return 17752646587087935488;\n        }\n        if x <= 27301181229090136064 {\n            return 17776279920286781440;\n        }\n        if x <= 27485648669827231744 {\n            return 17799223970031376384;\n        }\n    }\n    if x <= 29330323077198188544 {\n        if x <= 27670116110564327424 {\n            return 17821494385323737088;\n        }\n        if x <= 27854583551301423104 {\n            return 17843106621180358656;\n        }\n        if x <= 28039050992038518784 {\n            return 17864075935211624448;\n        }\n        if x <= 28223518432775614464 {\n            return 17884417384457840640;\n        }\n        if x <= 28407985873512710144 {\n            return 17904145822477408256;\n        }\n        if x <= 28592453314249805824 {\n            return 17923275896682506240;\n        }\n        if x <= 28776920754986901504 {\n            return 17941822045917437952;\n        }\n        if x <= 28961388195723997184 {\n            return 17959798498274711552;\n        }\n        if x <= 29145855636461092864 {\n            return 17977219269143760896;\n        }\n        if x <= 29330323077198188544 {\n            return 17994098159487121408;\n        }\n    }\n    if x <= 31174997484569141248 {\n        if x <= 29514790517935284224 {\n            return 18010448754338713600;\n        }\n        if x <= 29699257958672379904 {\n            return 18026284421518878720;\n        }\n        if x <= 29883725399409475584 {\n            return 18041618310560610304;\n        }\n        if x <= 30068192840146567168 {\n            return 18056463351841458176;\n        }\n        if x <= 30252660280883662848 {\n            return 18070832255915431936;\n        }\n        if x <= 30437127721620758528 {\n            return 18084737513039206400;\n        }\n        if x <= 30621595162357854208 {\n            return 18098191392886906880;\n        }\n        if x <= 30806062603094949888 {\n            return 18111205944447655936;\n        }\n        if x <= 30990530043832045568 {\n            return 18123792996100098048;\n        }\n        if x <= 31174997484569141248 {\n            return 18135964155858038784;\n        }\n    }\n    if x <= 33019671891940098048 {\n        if x <= 31359464925306236928 {\n            return 18147730811781371904;\n        }\n        if x <= 31543932366043332608 {\n            return 18159104132546453504;\n        }\n        if x <= 31728399806780428288 {\n            return 18170095068170047488;\n        }\n        if x <= 31912867247517523968 {\n            return 18180714350881038336;\n        }\n        if x <= 32097334688254619648 {\n            return 18190972496134107136;\n        }\n        if x <= 32281802128991715328 {\n            return 18200879803759552512;\n        }\n        if x <= 32466269569728811008 {\n            return 18210446359243550720;\n        }\n        if x <= 32650737010465906688 {\n            return 18219682035133120512;\n        }\n        if x <= 32835204451203002368 {\n            return 18228596492560154624;\n        }\n        if x <= 33019671891940098048 {\n            return 18237199182878894080;\n        }\n    }\n    if x <= 34864346299311050752 {\n        if x <= 33204139332677193728 {\n            return 18245499349411323904;\n        }\n        if x <= 33388606773414289408 {\n            return 18253506029294995456;\n        }\n        if x <= 33573074214151385088 {\n            return 18261228055427880960;\n        }\n        if x <= 33757541654888480768 {\n            return 18268674058504921088;\n        }\n        if x <= 33942009095625576448 {\n            return 18275852469141008384;\n        }\n        if x <= 34126476536362672128 {\n            return 18282771520075268096;\n        }\n        if x <= 34310943977099767808 {\n            return 18289439248451522560;\n        }\n        if x <= 34495411417836863488 {\n            return 18295863498169980928;\n        }\n        if x <= 34679878858573955072 {\n            return 18302051922305267712;\n        }\n        if x <= 34864346299311050752 {\n            return 18308011985585967104;\n        }\n    }\n    if x <= 36709020706682007552 {\n        if x <= 35048813740048146432 {\n            return 18313750966931048448;\n        }\n        if x <= 35233281180785242112 {\n            return 18319275962038544384;\n        }\n        if x <= 35417748621522337792 {\n            return 18324593886022047744;\n        }\n        if x <= 35602216062259433472 {\n            return 18329711476090615808;\n        }\n        if x <= 35786683502996529152 {\n            return 18334635294267887616;\n        }\n        if x <= 35971150943733624832 {\n            return 18339371730146226176;\n        }\n        if x <= 36155618384470720512 {\n            return 18343927003671875584;\n        }\n        if x <= 36340085825207816192 {\n            return 18348307167957243904;\n        }\n        if x <= 36524553265944911872 {\n            return 18352518112116494336;\n        }\n        if x <= 36709020706682007552 {\n            return 18356565564120772608;\n        }\n    }\n    if x <= 62718929850612473856 {\n        if x <= 36893488147419103232 {\n            return 18360455093669533696;\n        }\n        if x <= 38738162554790060032 {\n            return 18391782614824026112;\n        }\n        if x <= 40582836962161016832 {\n            return 18412380624802023424;\n        }\n        if x <= 42427511369531965440 {\n            return 18425656187587059712;\n        }\n        if x <= 44272185776902922240 {\n            return 18434043234066948096;\n        }\n        if x <= 46116860184273879040 {\n            return 18439237133993463808;\n        }\n        if x <= 47961534591644835840 {\n            return 18442390007235248128;\n        }\n        if x <= 49806208999015792640 {\n            return 18444266072035147776;\n        }\n        if x <= 51650883406386741248 {\n            return 18445360324505407488;\n        }\n        if x <= 53495557813757698048 {\n            return 18445985951670278144;\n        }\n        if x <= 55340232221128654848 {\n            return 18446336575964956672;\n        }\n        if x <= 57184906628499611648 {\n            return 18446529193908295680;\n        }\n        if x <= 59029581035870568448 {\n            return 18446632918035736576;\n        }\n        if x <= 60874255443241517056 {\n            return 18446687668919484416;\n        }\n        if x <= 62718929850612473856 {\n            return 18446715997887504384;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23.cairo",
        "content": "mod core;\nmod math;\nmod helpers;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp8x23::math::{core as core_math, trig, hyp, erf};\nuse orion::numbers::fixed_point::utils;\n\n/// A struct representing a fixed point number.\n#[derive(Serde, Copy, Drop)]\nstruct FP8x23 {\n    mag: u32,\n    sign: bool\n}\n\n// CONSTANTS\nconst TWO: u32 = 16777216; // 2 ** 24\nconst ONE: u32 = 8388608; // 2 ** 23\nconst HALF: u32 = 4194304; // 2 ** 22\nconst MAX: u32 = 2147483648; // 2 ** 31\n\n\nimpl FP8x23Impl of FixedTrait<FP8x23, u32> {\n    fn ZERO() -> FP8x23 {\n        FP8x23 { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP8x23 {\n        FP8x23 { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP8x23 {\n        FP8x23 { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP8x23 {\n        FP8x23 { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u32, sign: bool) -> FP8x23 {\n        FP8x23 { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u32, sign: bool) -> FP8x23 {\n        FP8x23 { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP8x23 {\n        let mag = core::integer::u32_try_from_felt252(utils::felt_abs(val)).unwrap();\n\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP8x23) -> FP8x23 {\n        core_math::abs(self)\n    }\n\n    fn acos(self: FP8x23) -> FP8x23 {\n        trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP8x23) -> FP8x23 {\n        trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP8x23) -> FP8x23 {\n        hyp::acosh(self)\n    }\n\n    fn asin(self: FP8x23) -> FP8x23 {\n        trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP8x23) -> FP8x23 {\n        trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP8x23) -> FP8x23 {\n        hyp::asinh(self)\n    }\n\n    fn atan(self: FP8x23) -> FP8x23 {\n        trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP8x23) -> FP8x23 {\n        trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP8x23) -> FP8x23 {\n        hyp::atanh(self)\n    }\n\n    fn ceil(self: FP8x23) -> FP8x23 {\n        core_math::ceil(self)\n    }\n\n    fn cos(self: FP8x23) -> FP8x23 {\n        trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP8x23) -> FP8x23 {\n        trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP8x23) -> FP8x23 {\n        hyp::cosh(self)\n    }\n\n    fn floor(self: FP8x23) -> FP8x23 {\n        core_math::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP8x23) -> FP8x23 {\n        core_math::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP8x23) -> FP8x23 {\n        core_math::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP8x23) -> FP8x23 {\n        core_math::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP8x23) -> FP8x23 {\n        core_math::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP8x23) -> FP8x23 {\n        core_math::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP8x23, b: FP8x23) -> FP8x23 {\n        core_math::pow(self, b)\n    }\n\n    fn round(self: FP8x23) -> FP8x23 {\n        core_math::round(self)\n    }\n\n    fn sin(self: FP8x23) -> FP8x23 {\n        trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP8x23) -> FP8x23 {\n        trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP8x23) -> FP8x23 {\n        hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP8x23) -> FP8x23 {\n        core_math::sqrt(self)\n    }\n\n    fn tan(self: FP8x23) -> FP8x23 {\n        trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP8x23) -> FP8x23 {\n        trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP8x23) -> FP8x23 {\n        hyp::tanh(self)\n    }\n\n    fn sign(self: FP8x23) -> FP8x23 {\n        core_math::sign(self)\n    }\n\n    fn NaN() -> FP8x23 {\n        FP8x23 { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP8x23) -> bool {\n        self == FP8x23 { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP8x23 {\n        FP8x23 { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP8x23 {\n        FP8x23 { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP8x23 {\n        FP8x23 { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP8x23) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP8x23) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP8x23) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP8x23) -> FP8x23 {\n        erf::erf(self)\n    }\n}\n\nimpl FP8x23Print of PrintTrait<FP8x23> {\n    fn print(self: FP8x23) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP8x23IntoFelt252 of Into<FP8x23, felt252> {\n    fn into(self: FP8x23) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP8x23TryIntoU128 of TryInto<FP8x23, u128> {\n    fn try_into(self: FP8x23) -> Option<u128> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP8x23TryIntoU64 of TryInto<FP8x23, u64> {\n    fn try_into(self: FP8x23) -> Option<u64> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP8x23TryIntoU32 of TryInto<FP8x23, u32> {\n    fn try_into(self: FP8x23) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some(self.mag / ONE)\n        }\n    }\n}\n\nimpl FP8x23TryIntoU16 of TryInto<FP8x23, u16> {\n    fn try_into(self: FP8x23) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP8x23TryIntoU8 of TryInto<FP8x23, u8> {\n    fn try_into(self: FP8x23) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP8x23IntoI32 of Into<FP8x23, i32> {\n    fn into(self: FP8x23) -> i32 {\n        _i32_into_fp(self)\n    }\n}\n\nimpl FP8x23TryIntoI8 of TryInto<FP8x23, i8> {\n    fn try_into(self: FP8x23) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\nimpl FP8x23PartialEq of PartialEq<FP8x23> {\n    #[inline(always)]\n    fn eq(lhs: @FP8x23, rhs: @FP8x23) -> bool {\n        core_math::eq(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn ne(lhs: @FP8x23, rhs: @FP8x23) -> bool {\n        core_math::ne(lhs, rhs)\n    }\n}\n\nimpl FP8x23Add of Add<FP8x23> {\n    fn add(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        core_math::add(lhs, rhs)\n    }\n}\n\nimpl FP8x23AddEq of AddEq<FP8x23> {\n    #[inline(always)]\n    fn add_eq(ref self: FP8x23, other: FP8x23) {\n        self = Add::add(self, other);\n    }\n}\n\nimpl FP8x23Sub of Sub<FP8x23> {\n    fn sub(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        core_math::sub(lhs, rhs)\n    }\n}\n\nimpl FP8x23SubEq of SubEq<FP8x23> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP8x23, other: FP8x23) {\n        self = Sub::sub(self, other);\n    }\n}\n\nimpl FP8x23Mul of Mul<FP8x23> {\n    fn mul(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        core_math::mul(lhs, rhs)\n    }\n}\n\nimpl FP8x23MulEq of MulEq<FP8x23> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP8x23, other: FP8x23) {\n        self = Mul::mul(self, other);\n    }\n}\n\nimpl FP8x23Div of Div<FP8x23> {\n    fn div(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        core_math::div(lhs, rhs)\n    }\n}\n\nimpl FP8x23DivEq of DivEq<FP8x23> {\n    #[inline(always)]\n    fn div_eq(ref self: FP8x23, other: FP8x23) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl FP8x23PartialOrd of PartialOrd<FP8x23> {\n    #[inline(always)]\n    fn ge(lhs: FP8x23, rhs: FP8x23) -> bool {\n        core_math::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP8x23, rhs: FP8x23) -> bool {\n        core_math::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP8x23, rhs: FP8x23) -> bool {\n        core_math::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP8x23, rhs: FP8x23) -> bool {\n        core_math::lt(lhs, rhs)\n    }\n}\n\nimpl FP8x23Neg of Neg<FP8x23> {\n    #[inline(always)]\n    fn neg(a: FP8x23) -> FP8x23 {\n        core_math::neg(a)\n    }\n}\n\nimpl FP8x23Rem of Rem<FP8x23> {\n    #[inline(always)]\n    fn rem(lhs: FP8x23, rhs: FP8x23) -> FP8x23 {\n        core_math::rem(lhs, rhs)\n    }\n}\n\n/// INTERNAL\nfn _i32_into_fp(x: FP8x23) -> i32 {\n    // i32 { mag: x.mag / ONE, sign: x.sign }\n    let number_felt: felt252 = (x.mag / ONE).into();\n    let number_i32: i32 = number_felt.try_into().unwrap();\n\n    if x.sign {\n        return number_i32 * -1_i32;\n    }\n\n    number_i32\n}\n\nfn _i8_try_from_fp(x: FP8x23) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n    // Option::Some(i8 { mag: unscaled_mag.unwrap(), sign: x.sign })\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/helpers.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{\n    HALF, ONE, TWO, FP8x23, FP8x23Sub, FP8x23Div, FixedTrait, FP8x23Print\n};\n\nconst DEFAULT_PRECISION: u32 = 8; // 1e-6\n\n// To use `DEFAULT_PRECISION`, final arg is: `Option::None(())`.\n// To use `custom_precision` of 430_u32: `Option::Some(430_u32)`.\nfn assert_precise(result: FP8x23, expected: felt252, msg: felt252, custom_precision: Option<u32>) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = (result - FixedTrait::from_felt(expected)).mag;\n\n    if (diff > precision) {\n        result.print();\n        assert(diff <= precision, msg);\n    }\n}\n\nfn assert_relative(result: FP8x23, expected: felt252, msg: felt252, custom_precision: Option<u32>) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = result - FixedTrait::from_felt(expected);\n    let rel_diff = (diff / result).mag;\n\n    if (rel_diff > precision) {\n        result.print();\n        assert(rel_diff <= precision, msg);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math.cairo",
        "content": "mod core;\nmod comp;\nmod lut;\nmod trig;\nmod hyp;\nmod erf;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/comp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23::core::{\n    FP8x23, FixedTrait, FP8x23PartialOrd, FP8x23PartialEq\n};\n\nfn max(a: FP8x23, b: FP8x23) -> FP8x23 {\n    if a >= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn min(a: FP8x23, b: FP8x23) -> FP8x23 {\n    if a <= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn xor(a: FP8x23, b: FP8x23) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP8x23, b: FP8x23) -> bool {\n    let zero = FixedTrait::new(0, false);\n\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP8x23, b: FP8x23) -> bool {\n    let zero = FixedTrait::new(0, false);\n\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP8x23, b: FP8x23, c: FP8x23) -> FP8x23 {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP8x23, b: FP8x23) -> FP8x23 {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP8x23, b: FP8x23) -> FP8x23 {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP8x23, b: FP8x23) -> FP8x23 {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use super::{FixedTrait, max, min, bitwise_and, bitwise_xor, bitwise_or};\n\n    #[test]\n    fn test_max() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(max(a, a) == a, 'max(a, a)');\n        assert(max(a, b) == a, 'max(a, b)');\n        assert(max(a, c) == a, 'max(a, c)');\n\n        assert(max(b, a) == a, 'max(b, a)');\n        assert(max(b, b) == b, 'max(b, b)');\n        assert(max(b, c) == b, 'max(b, c)');\n\n        assert(max(c, a) == a, 'max(c, a)');\n        assert(max(c, b) == b, 'max(c, b)');\n        assert(max(c, c) == c, 'max(c, c)');\n    }\n\n    #[test]\n    fn test_min() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(min(a, a) == a, 'min(a, a)');\n        assert(min(a, b) == b, 'min(a, b)');\n        assert(min(a, c) == c, 'min(a, c)');\n\n        assert(min(b, a) == b, 'min(b, a)');\n        assert(min(b, b) == b, 'min(b, b)');\n        assert(min(b, c) == c, 'min(b, c)');\n\n        assert(min(c, a) == c, 'min(c, a)');\n        assert(min(c, b) == c, 'min(c, b)');\n        assert(min(c, c) == c, 'min(c, c)');\n    }\n\n    #[test]\n    fn test_bitwise_and() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n\n        assert(bitwise_and(a, b) == a, 'bitwise_and(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_xor() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n        let c = FixedTrait::new(1610612736, true);\n\n        assert(bitwise_xor(a, b) == c, 'bitwise_xor(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_or() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n\n        assert(bitwise_or(a, b) == b, 'bitwise_or(a,b)')\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/core.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{\n    HALF, ONE, MAX, FP8x23, FP8x23Add, FP8x23Impl, FP8x23AddEq, FP8x23Sub, FP8x23Mul, FP8x23MulEq,\n    FP8x23TryIntoU128, FP8x23PartialEq, FP8x23PartialOrd, FP8x23SubEq, FP8x23Neg, FP8x23Div,\n    FP8x23IntoFelt252, FixedTrait\n};\nuse orion::numbers::fixed_point::implementations::fp8x23::math::lut;\n\n// PUBLIC\nfn abs(a: FP8x23) -> FP8x23 {\n    FixedTrait::new(a.mag, false)\n}\n\nfn add(a: FP8x23, b: FP8x23) -> FP8x23 {\n    if a.sign == b.sign {\n        return FixedTrait::new(a.mag + b.mag, a.sign);\n    }\n\n    if a.mag == b.mag {\n        return FixedTrait::ZERO();\n    }\n\n    if (a.mag > b.mag) {\n        FixedTrait::new(a.mag - b.mag, a.sign)\n    } else {\n        FixedTrait::new(b.mag - a.mag, b.sign)\n    }\n}\n\nfn ceil(a: FP8x23) -> FP8x23 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div + 1, false)\n    } else if div == 0 {\n        FixedTrait::new_unscaled(0, false)\n    } else {\n        FixedTrait::new_unscaled(div, true)\n    }\n}\n\nfn div(a: FP8x23, b: FP8x23) -> FP8x23 {\n    let a_u64 = integer::u32_wide_mul(a.mag, ONE);\n    let res_u64 = a_u64 / b.mag.into();\n\n    // Re-apply sign\n    FixedTrait::new(res_u64.try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn eq(a: @FP8x23, b: @FP8x23) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n// Calculates the natural exponent of x: e^x\nfn exp(a: FP8x23) -> FP8x23 {\n    exp2(FixedTrait::new(12102203, false) * a) // log2(e) * 2^23 \u2248 12102203\n}\n\n// Calculates the binary exponent of x: 2^x\nfn exp2(a: FP8x23) -> FP8x23 {\n    if (a.mag == 0) {\n        return FixedTrait::ONE();\n    }\n\n    let (int_part, frac_part) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n    let int_res = FixedTrait::new_unscaled(lut::exp2(int_part), false);\n    let mut res_u = int_res;\n\n    if frac_part != 0 {\n        let frac = FixedTrait::new(frac_part, false);\n        let r8 = FixedTrait::new(19, false) * frac;\n        let r7 = (r8 + FixedTrait::new(105, false)) * frac;\n        let r6 = (r7 + FixedTrait::new(1324, false)) * frac;\n        let r5 = (r6 + FixedTrait::new(11159, false)) * frac;\n        let r4 = (r5 + FixedTrait::new(80695, false)) * frac;\n        let r3 = (r4 + FixedTrait::new(465599, false)) * frac;\n        let r2 = (r3 + FixedTrait::new(2015166, false)) * frac;\n        let r1 = (r2 + FixedTrait::new(5814540, false)) * frac;\n        res_u = res_u * (r1 + FixedTrait::ONE());\n    }\n\n    if a.sign {\n        FixedTrait::ONE() / res_u\n    } else {\n        res_u\n    }\n}\n\nfn exp2_int(exp: u32) -> FP8x23 {\n    FixedTrait::new_unscaled(lut::exp2(exp), false)\n}\n\nfn floor(a: FP8x23) -> FP8x23 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if rem == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new_unscaled(div, false)\n    } else {\n        FixedTrait::new_unscaled(div + 1, true)\n    }\n}\n\nfn ge(a: FP8x23, b: FP8x23) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn gt(a: FP8x23, b: FP8x23) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn le(a: FP8x23, b: FP8x23) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\n// Calculates the natural logarithm of x: ln(x)\n// self must be greater than zero\nfn ln(a: FP8x23) -> FP8x23 {\n    FixedTrait::new(5814540, false) * log2(a) // ln(2) = 0.693...\n}\n\n// Calculates the binary logarithm of x: log2(x)\n// self must be greather than zero\nfn log2(a: FP8x23) -> FP8x23 {\n    assert(!a.sign, 'must be positive');\n\n    if (a.mag == ONE) {\n        return FixedTrait::ZERO();\n    } else if (a.mag < ONE) {\n        // Compute true inverse binary log if 0 < x < 1\n        let div = FixedTrait::ONE() / a;\n        return -log2(div);\n    }\n\n    let whole = a.mag / ONE;\n    let (msb, div) = lut::msb(whole);\n\n    if a.mag == div * ONE {\n        FixedTrait::new_unscaled(msb, false)\n    } else {\n        let norm = a / FixedTrait::new_unscaled(div, false);\n        let r8 = FixedTrait::new(76243, true) * norm;\n        let r7 = (r8 + FixedTrait::new(1038893, false)) * norm;\n        let r6 = (r7 + FixedTrait::new(6277679, true)) * norm;\n        let r5 = (r6 + FixedTrait::new(22135645, false)) * norm;\n        let r4 = (r5 + FixedTrait::new(50444339, true)) * norm;\n        let r3 = (r4 + FixedTrait::new(77896489, false)) * norm;\n        let r2 = (r3 + FixedTrait::new(83945943, true)) * norm;\n        let r1 = (r2 + FixedTrait::new(68407458, false)) * norm;\n\n        r1 + FixedTrait::new(28734280, true) + FixedTrait::new_unscaled(msb, false)\n    }\n}\n\n// Calculates the base 10 log of x: log10(x)\n// self must be greater than zero\nfn log10(a: FP8x23) -> FP8x23 {\n    FixedTrait::new(2525223, false) * log2(a) // log10(2) = 0.301...\n}\n\nfn lt(a: FP8x23, b: FP8x23) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\nfn mul(a: FP8x23, b: FP8x23) -> FP8x23 {\n    let prod_u128 = integer::u32_wide_mul(a.mag, b.mag);\n\n    // Re-apply sign\n    FixedTrait::new((prod_u128 / ONE.into()).try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn ne(a: @FP8x23, b: @FP8x23) -> bool {\n    (*a.mag != *b.mag) || (*a.sign != *b.sign)\n}\n\nfn neg(a: FP8x23) -> FP8x23 {\n    if a.mag == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new(a.mag, !a.sign)\n    } else {\n        FixedTrait::new(a.mag, false)\n    }\n}\n\n// Calclates the value of x^y and checks for overflow before returning\n// self is a FP8x23 point value\n// b is a FP8x23 point value\nfn pow(a: FP8x23, b: FP8x23) -> FP8x23 {\n    let (_, rem) = integer::u32_safe_divmod(b.mag, integer::u32_as_non_zero(ONE));\n\n    // use the more performant integer pow when y is an int\n    if (rem == 0) {\n        return pow_int(a, b.mag / ONE, b.sign);\n    }\n\n    // x^y = exp(y*ln(x)) for x > 0 will error for x < 0\n    exp(b * ln(a))\n}\n\n// Calclates the value of a^b and checks for overflow before returning\nfn pow_int(a: FP8x23, b: u32, sign: bool) -> FP8x23 {\n    let mut x = a;\n    let mut n = b;\n\n    if sign {\n        x = FixedTrait::ONE() / x;\n    }\n\n    if n == 0 {\n        return FixedTrait::ONE();\n    }\n\n    let mut y = FixedTrait::ONE();\n    let two = integer::u32_as_non_zero(2);\n\n    while n > 1 {\n        let (div, rem) = integer::u32_safe_divmod(n, two);\n\n        if rem == 1 {\n            y = x * y;\n        }\n\n        x = x * x;\n        n = div;\n    };\n\n    x * y\n}\n\nfn rem(a: FP8x23, b: FP8x23) -> FP8x23 {\n    a - floor(a / b) * b\n}\n\nfn round(a: FP8x23) -> FP8x23 {\n    let (div, rem) = integer::u32_safe_divmod(a.mag, integer::u32_as_non_zero(ONE));\n\n    if (HALF <= rem) {\n        FixedTrait::new_unscaled(div + 1, a.sign)\n    } else {\n        FixedTrait::new_unscaled(div, a.sign)\n    }\n}\n\n// Calculates the square root of a FP8x23 point value\n// x must be positive\nfn sqrt(a: FP8x23) -> FP8x23 {\n    assert(!(a.sign), 'must be positive');\n\n    let root = integer::u64_sqrt(a.mag.into() * ONE.into());\n\n    FixedTrait::new(root.into(), false)\n}\n\nfn sub(a: FP8x23, b: FP8x23) -> FP8x23 {\n    add(a, -b)\n}\n\nfn sign(a: FP8x23) -> FP8x23 {\n    if a.mag == 0 {\n        FixedTrait::new(0, false)\n    } else {\n        FixedTrait::new(ONE, a.sign)\n    }\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp8x23::math::trig::{PI, HALF_PI};\n\n    use super::{\n        FixedTrait, ONE, FP8x23, ceil, floor, sqrt, round, lut, pow, exp, exp2, exp2_int, ln, log2,\n        log10, eq, add, ne, HALF\n    };\n\n    #[test]\n    fn test_into() {\n        let a = FixedTrait::<FP8x23>::new_unscaled(5, false);\n        assert(a.mag == 5 * ONE, 'invalid result');\n    }\n\n    #[test]\n    fn test_try_into_u128() {\n        // Positive unscaled\n        let a = FixedTrait::<FP8x23>::new_unscaled(5, false);\n        assert(a.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Positive scaled\n        let b = FixedTrait::<FP8x23>::new(5 * ONE, false);\n        assert(b.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Zero\n        let d = FixedTrait::<FP8x23>::new_unscaled(0, false);\n        assert(d.try_into().unwrap() == 0_u128, 'invalid result');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_negative_try_into_u128() {\n        let a = FixedTrait::<FP8x23>::new_unscaled(1, true);\n        let _a: u128 = a.try_into().unwrap();\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_acos() {\n        let a = FixedTrait::<FP8x23>::ONE();\n        assert(a.acos().into() == 0, 'invalid one');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_asin() {\n        let a = FixedTrait::ONE();\n        assert_precise(a.asin(), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(a.atan(), 9287469, 'invalid two', Option::None(()));\n    }\n\n    #[test]\n    fn test_ceil() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(ceil(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_floor() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(floor(a).mag == 2 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_round() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(round(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_sqrt_fail() {\n        let a = FixedTrait::new_unscaled(25, true);\n        sqrt(a);\n    }\n\n    #[test]\n    fn test_sqrt() {\n        let mut a = FixedTrait::new_unscaled(0, false);\n        assert(sqrt(a).mag == 0, 'invalid zero root');\n        a = FixedTrait::new_unscaled(25, false);\n        assert(sqrt(a).mag == 5 * ONE, 'invalid pos root');\n    }\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_msb() {\n        let a = FixedTrait::<FP8x23>::new_unscaled(100, false);\n        let (msb, div) = lut::msb(a.mag / ONE);\n        assert(msb == 6, 'invalid msb');\n        assert(div == 64, 'invalid msb ceil');\n    }\n\n    #[test]\n    #[available_gas(600000)]\n    fn test_pow() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new_unscaled(4, false);\n        assert(pow(a, b).mag == 81 * ONE, 'invalid pos base power');\n    }\n\n    #[test]\n    #[available_gas(900000)]\n    fn test_pow_frac() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new(4194304, false); // 0.5\n        assert_relative(\n            pow(a, b), 14529495, 'invalid pos base power', Option::None(())\n        ); // 1.7320508075688772\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_exp() {\n        let a = FixedTrait::new_unscaled(2, false);\n        assert_relative(\n            exp(a), 61983895, 'invalid exp of 2', Option::None(())\n        ); // 7.389056098793725\n    }\n\n    #[test]\n    #[available_gas(400000)]\n    fn test_exp2() {\n        let a = FixedTrait::new_unscaled(5, false);\n        assert(exp2(a).mag == 268435456, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(20000)]\n    fn test_exp2_int() {\n        assert(exp2_int(5).into() == 268435456, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_ln() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        assert(ln(a).mag == 0, 'invalid ln of 1');\n\n        a = FixedTrait::new(22802601, false);\n        assert_relative(ln(a), ONE.into(), 'invalid ln of 2.7...', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log2() {\n        let mut a = FixedTrait::new_unscaled(32, false);\n        assert(log2(a) == FixedTrait::new_unscaled(5, false), 'invalid log2 32');\n\n        a = FixedTrait::new_unscaled(10, false);\n        assert_relative(\n            log2(a), 27866353, 'invalid log2 10', Option::None(())\n        ); // 3.321928094887362\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log10() {\n        let a = FixedTrait::new_unscaled(100, false);\n        assert_relative(log10(a), 2 * ONE.into(), 'invalid log10', Option::None(()));\n    }\n\n    #[test]\n    fn test_eq() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = eq(@a, @b);\n        assert(c, 'invalid result');\n    }\n\n    #[test]\n    fn test_ne() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = ne(@a, @b);\n        assert(!c, 'invalid result');\n    }\n\n    #[test]\n    fn test_add() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        assert(add(a, b) == FixedTrait::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_add_eq() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a += b;\n        assert(a == FixedTrait::<FP8x23>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_sub() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        let c = a - b;\n        assert(c == FixedTrait::<FP8x23>::new_unscaled(3, false), 'false result invalid');\n    }\n\n    #[test]\n    fn test_sub_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a -= b;\n        assert(a == FixedTrait::<FP8x23>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_mul_pos() {\n        let a = FP8x23 { mag: 24326963, sign: false };\n        let b = FP8x23 { mag: 24326963, sign: false };\n        let c = a * b;\n        assert(c.mag == 70548192, 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_neg() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        let c = a * b;\n        assert(c == FixedTrait::<FP8x23>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        a *= b;\n        assert(a == FixedTrait::<FP8x23>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_div() {\n        let a = FixedTrait::new_unscaled(10, false);\n        let b = FixedTrait::<FP8x23>::new(24326963, false); // 2.9\n        let c = a / b;\n        assert(c.mag == 28926234, 'invalid pos decimal'); // 3.4482758620689653\n    }\n\n    #[test]\n    fn test_le() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23>::new_unscaled(1, true);\n\n        assert(a <= a, 'a <= a');\n        assert(!(a <= b), 'a <= b');\n        assert(!(a <= c), 'a <= c');\n\n        assert(b <= a, 'b <= a');\n        assert(b <= b, 'b <= b');\n        assert(!(b <= c), 'b <= c');\n\n        assert(c <= a, 'c <= a');\n        assert(c <= b, 'c <= b');\n        assert(c <= c, 'c <= c');\n    }\n\n    #[test]\n    fn test_lt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23>::new_unscaled(1, true);\n\n        assert(!(a < a), 'a < a');\n        assert(!(a < b), 'a < b');\n        assert(!(a < c), 'a < c');\n\n        assert(b < a, 'b < a');\n        assert(!(b < b), 'b < b');\n        assert(!(b < c), 'b < c');\n\n        assert(c < a, 'c < a');\n        assert(c < b, 'c < b');\n        assert(!(c < c), 'c < c');\n    }\n\n    #[test]\n    fn test_ge() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23>::new_unscaled(1, true);\n\n        assert(a >= a, 'a >= a');\n        assert(a >= b, 'a >= b');\n        assert(a >= c, 'a >= c');\n\n        assert(!(b >= a), 'b >= a');\n        assert(b >= b, 'b >= b');\n        assert(b >= c, 'b >= c');\n\n        assert(!(c >= a), 'c >= a');\n        assert(!(c >= b), 'c >= b');\n        assert(c >= c, 'c >= c');\n    }\n\n    #[test]\n    fn test_gt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23>::new_unscaled(1, true);\n\n        assert(!(a > a), 'a > a');\n        assert(a > b, 'a > b');\n        assert(a > c, 'a > c');\n\n        assert(!(b > a), 'b > a');\n        assert(!(b > b), 'b > b');\n        assert(b > c, 'b > c');\n\n        assert(!(c > a), 'c > a');\n        assert(!(c > b), 'c > b');\n        assert(!(c > c), 'c > c');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_cos() {\n        let a = FixedTrait::<FP8x23>::new(HALF_PI, false);\n        assert(a.cos().into() == 0, 'invalid half pi');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(a.sin(), ONE.into(), 'invalid half pi', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_tan() {\n        let a = FixedTrait::<FP8x23>::new(HALF_PI / 2, false);\n        assert(a.tan().mag == 8388608, 'invalid quarter pi');\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_sign() {\n        let a = FixedTrait::<FP8x23>::new(0, false);\n        assert(a.sign().mag == 0 && !a.sign().sign, 'invalid sign (0, true)');\n\n        let a = FixedTrait::<FP8x23>::new(HALF, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (HALF, true)');\n\n        let a = FixedTrait::<FP8x23>::new(HALF, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (HALF, false)');\n\n        let a = FixedTrait::<FP8x23>::new(ONE, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (ONE, true)');\n\n        let a = FixedTrait::<FP8x23>::new(ONE, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (ONE, false)');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(2000000)]\n    fn test_sign_fail() {\n        let a = FixedTrait::<FP8x23>::new(HALF, true);\n        assert(a.sign().mag != ONE && !a.sign().sign, 'invalid sign (HALF, true)');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/erf.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23::core::{ONE, FP8x23, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp8x23::math::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u32 = 100;\nconst MAX_ERF_COMPUTATIONAL_ACCURACY: u32 = 10;\nconst ROUND_CHECK_NUMBER: u32 = 1;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u32 = 29360128;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u32 = 16777216;\n\nfn erf(x: FP8x23) -> FP8x23 {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u32 = 0;\n\n    if x.mag < MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP8x23 { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/hyp.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{\n    HALF, ONE, TWO, FP8x23, FP8x23Impl, FP8x23Add, FP8x23AddEq, FP8x23Sub, FP8x23Mul, FP8x23MulEq,\n    FP8x23TryIntoU128, FP8x23PartialEq, FP8x23PartialOrd, FP8x23SubEq, FP8x23Neg, FP8x23Div,\n    FP8x23IntoFelt252, FixedTrait\n};\n\n// Calculates hyperbolic cosine of a (fixed point)\nfn cosh(a: FP8x23) -> FP8x23 {\n    let ea = a.exp();\n\n    (ea + (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic sine of a (fixed point)\nfn sinh(a: FP8x23) -> FP8x23 {\n    let ea = a.exp();\n\n    (ea - (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic tangent of a (fixed point)\nfn tanh(a: FP8x23) -> FP8x23 {\n    let ea = a.exp();\n    let ea_i = FixedTrait::ONE() / ea;\n\n    (ea - ea_i) / (ea + ea_i)\n}\n\n// Calculates inverse hyperbolic cosine of a (fixed point)\nfn acosh(a: FP8x23) -> FP8x23 {\n    let root = (a * a - FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic sine of a (fixed point)\nfn asinh(a: FP8x23) -> FP8x23 {\n    let root = (a * a + FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic tangent of a (fixed point)\nfn atanh(a: FP8x23) -> FP8x23 {\n    let one = FixedTrait::ONE();\n    let ln_arg = (one + a) / (one - a);\n\n    ln_arg.ln() / FixedTrait::new(TWO, false)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23::helpers::assert_precise;\n\n    use super::{FixedTrait, TWO, cosh, ONE, sinh, tanh, acosh, asinh, atanh, HALF};\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_cosh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(cosh(a), 31559585, 'invalid two', Option::None(())); // 3.762195691016423\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 12944299, 'invalid one', Option::None(())); // 1.5430806347841253\n\n        let a = FixedTrait::ZERO();\n        assert_precise(cosh(a), ONE.into(), 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_precise(\n            cosh(a), 12944299, 'invalid neg one', Option::None(())\n        ); // 1.5430806347841253\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(cosh(a), 31559602, 'invalid neg two', Option::None(())); // 3.762195691016423\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_sinh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(sinh(a), 30424310, 'invalid two', Option::None(())); // 3.6268604077773023\n\n        let a = FixedTrait::ONE();\n        assert_precise(sinh(a), 9858302, 'invalid one', Option::None(())); // 1.1752011936029418\n\n        let a = FixedTrait::ZERO();\n        assert(sinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(\n            sinh(a), -9858302, 'invalid neg one', Option::None(())\n        ); // -1.1752011936029418\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(\n            sinh(a), -30424328, 'invalid neg two', Option::None(())\n        ); // -3.6268604077773023\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_tanh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(tanh(a), 8086849, 'invalid two', Option::None(())); // 0.9640275800745076\n\n        let a = FixedTrait::ONE();\n        assert_precise(tanh(a), 6388715, 'invalid one', Option::None(())); // 0.7615941559446443\n\n        let a = FixedTrait::ZERO();\n        assert(tanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(\n            tanh(a), -6388715, 'invalid neg one', Option::None(())\n        ); // -0.7615941559446443\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(\n            tanh(a), -8086849, 'invalid neg two', Option::None(())\n        ); // 0.9640275800745076\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_acosh() {\n        let a = FixedTrait::new(31559585, false); // 3.762195691016423\n        assert_precise(acosh(a), 16777257, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(12944299, false); // 1.5430806347841253\n        assert_precise(acosh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ONE(); // 1\n        assert(acosh(a).into() == 0, 'invalid zero');\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_asinh() {\n        let a = FixedTrait::new(30424310, false); // 3.6268604077773023\n        assert_precise(asinh(a), 16777257, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(9858302, false); // 1.1752011936029418\n        assert_precise(asinh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(asinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(9858302, true); // -1.1752011936029418\n        assert_precise(asinh(a), -ONE.into(), 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(30424310, true); // -3.6268604077773023\n        assert_precise(asinh(a), -16777238, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_atanh() {\n        let a = FixedTrait::new(7549747, false); // 0.9\n        assert_precise(atanh(a), 12349872, 'invalid 0.9', Option::None(())); // 1.4722194895832204\n\n        let a = FixedTrait::new(HALF, false); // 0.5\n        assert_precise(atanh(a), 4607914, 'invalid half', Option::None(())); // 0.5493061443340548\n\n        let a = FixedTrait::ZERO();\n        assert(atanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(HALF, true); // 0.5\n        assert_precise(\n            atanh(a), -4607914, 'invalid neg half', Option::None(())\n        ); // 0.5493061443340548\n\n        let a = FixedTrait::new(7549747, true); // 0.9\n        assert_precise(atanh(a), -12349872, 'invalid -0.9', Option::None(())); // 1.4722194895832204\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23::core::ONE;\n\n// Calculates the most significant bit\nfn msb(whole: u32) -> (u32, u32) {\n    if whole < 256 {\n        if whole < 2 {\n            return (0, 1);\n        }\n        if whole < 4 {\n            return (1, 2);\n        }\n        if whole < 8 {\n            return (2, 4);\n        }\n        if whole < 16 {\n            return (3, 8);\n        }\n        if whole < 32 {\n            return (4, 16);\n        }\n        if whole < 64 {\n            return (5, 32);\n        }\n        if whole < 128 {\n            return (6, 64);\n        }\n        if whole < 256 {\n            return (7, 128);\n        }\n    }\n\n    (8, 256)\n}\n\nfn exp2(exp: u32) -> u32 {\n    if exp <= 16 {\n        if exp == 0 {\n            return 1;\n        }\n        if exp == 1 {\n            return 2;\n        }\n        if exp == 2 {\n            return 4;\n        }\n        if exp == 3 {\n            return 8;\n        }\n        if exp == 4 {\n            return 16;\n        }\n        if exp == 5 {\n            return 32;\n        }\n        if exp == 6 {\n            return 64;\n        }\n        if exp == 7 {\n            return 128;\n        }\n        if exp == 8 {\n            return 256;\n        }\n        if exp == 9 {\n            return 512;\n        }\n        if exp == 10 {\n            return 1024;\n        }\n        if exp == 11 {\n            return 2048;\n        }\n        if exp == 12 {\n            return 4096;\n        }\n        if exp == 13 {\n            return 8192;\n        }\n        if exp == 14 {\n            return 16384;\n        }\n        if exp == 15 {\n            return 32768;\n        }\n        if exp == 16 {\n            return 65536;\n        }\n    } else if exp <= 32 {\n        if exp == 17 {\n            return 131072;\n        }\n        if exp == 18 {\n            return 262144;\n        }\n        if exp == 19 {\n            return 524288;\n        }\n        if exp == 20 {\n            return 1048576;\n        }\n        if exp == 21 {\n            return 2097152;\n        }\n        if exp == 22 {\n            return 4194304;\n        }\n    }\n\n    8388608\n}\n\nfn sin(a: u32) -> (u32, u32, u32) {\n    let slot = a / 51472;\n\n    if slot < 128 {\n        if slot < 64 {\n            if slot < 32 {\n                if slot < 16 {\n                    if slot == 0 {\n                        return (0, 0, 51472);\n                    }\n                    if slot == 1 {\n                        return (51472, 51472, 102941);\n                    }\n                    if slot == 2 {\n                        return (102944, 102941, 154407);\n                    }\n                    if slot == 3 {\n                        return (154416, 154407, 205867);\n                    }\n                    if slot == 4 {\n                        return (205887, 205867, 257319);\n                    }\n                    if slot == 5 {\n                        return (257359, 257319, 308761);\n                    }\n                    if slot == 6 {\n                        return (308831, 308761, 360192);\n                    }\n                    if slot == 7 {\n                        return (360303, 360192, 411609);\n                    }\n                    if slot == 8 {\n                        return (411775, 411609, 463011);\n                    }\n                    if slot == 9 {\n                        return (463247, 463011, 514396);\n                    }\n                    if slot == 10 {\n                        return (514723, 514396, 565761);\n                    }\n                    if slot == 11 {\n                        return (566190, 565761, 617104);\n                    }\n                    if slot == 12 {\n                        return (617662, 617104, 668425);\n                    }\n                    if slot == 13 {\n                        return (669134, 668425, 719720);\n                    }\n                    if slot == 14 {\n                        return (720606, 719720, 770988);\n                    }\n                    if slot == 15 {\n                        return (772078, 770988, 822227);\n                    }\n                } else {\n                    if slot == 16 {\n                        return (823550, 822227, 873436);\n                    }\n                    if slot == 17 {\n                        return (875022, 873436, 924611);\n                    }\n                    if slot == 18 {\n                        return (926493, 924611, 975751);\n                    }\n                    if slot == 19 {\n                        return (977965, 975751, 1026855);\n                    }\n                    if slot == 20 {\n                        return (1029437, 1026855, 1077920);\n                    }\n                    if slot == 21 {\n                        return (1080909, 1077920, 1128945);\n                    }\n                    if slot == 22 {\n                        return (1132381, 1128945, 1179927);\n                    }\n                    if slot == 23 {\n                        return (1183853, 1179927, 1230864);\n                    }\n                    if slot == 24 {\n                        return (1235324, 1230864, 1281756);\n                    }\n                    if slot == 25 {\n                        return (1286796, 1281756, 1332599);\n                    }\n                    if slot == 26 {\n                        return (1338268, 1332599, 1383392);\n                    }\n                    if slot == 27 {\n                        return (1389740, 1383392, 1434132);\n                    }\n                    if slot == 28 {\n                        return (1441212, 1434132, 1484819);\n                    }\n                    if slot == 29 {\n                        return (1492684, 1484819, 1535450);\n                    }\n                    if slot == 30 {\n                        return (1544156, 1535450, 1586023);\n                    }\n                    if slot == 31 {\n                        return (1595627, 1586023, 1636536);\n                    }\n                }\n            } else {\n                if slot < 48 {\n                    if slot == 32 {\n                        return (1647099, 1636536, 1686988);\n                    }\n                    if slot == 33 {\n                        return (1698571, 1686988, 1737376);\n                    }\n                    if slot == 34 {\n                        return (1750043, 1737376, 1787699);\n                    }\n                    if slot == 35 {\n                        return (1801515, 1787699, 1837954);\n                    }\n                    if slot == 36 {\n                        return (1852987, 1837954, 1888141);\n                    }\n                    if slot == 37 {\n                        return (1904459, 1888141, 1938256);\n                    }\n                    if slot == 38 {\n                        return (1955930, 1938256, 1988298);\n                    }\n                    if slot == 39 {\n                        return (2007402, 1988298, 2038265);\n                    }\n                    if slot == 40 {\n                        return (2058871, 2038265, 2088156);\n                    }\n                    if slot == 41 {\n                        return (2110346, 2088156, 2137968);\n                    }\n                    if slot == 42 {\n                        return (2161818, 2137968, 2187700);\n                    }\n                    if slot == 43 {\n                        return (2213290, 2187700, 2237349);\n                    }\n                    if slot == 44 {\n                        return (2264762, 2237349, 2286914);\n                    }\n                    if slot == 45 {\n                        return (2316233, 2286914, 2336392);\n                    }\n                    if slot == 46 {\n                        return (2367705, 2336392, 2385783);\n                    }\n                    if slot == 47 {\n                        return (2419177, 2385783, 2435084);\n                    }\n                } else {\n                    if slot == 48 {\n                        return (2470649, 2435084, 2484294);\n                    }\n                    if slot == 49 {\n                        return (2522121, 2484294, 2533410);\n                    }\n                    if slot == 50 {\n                        return (2573593, 2533410, 2582430);\n                    }\n                    if slot == 51 {\n                        return (2625065, 2582430, 2631353);\n                    }\n                    if slot == 52 {\n                        return (2676536, 2631353, 2680177);\n                    }\n                    if slot == 53 {\n                        return (2728008, 2680177, 2728901);\n                    }\n                    if slot == 54 {\n                        return (2779480, 2728901, 2777521);\n                    }\n                    if slot == 55 {\n                        return (2830952, 2777521, 2826037);\n                    }\n                    if slot == 56 {\n                        return (2882424, 2826037, 2874446);\n                    }\n                    if slot == 57 {\n                        return (2933896, 2874446, 2922748);\n                    }\n                    if slot == 58 {\n                        return (2985368, 2922748, 2970939);\n                    }\n                    if slot == 59 {\n                        return (3036839, 2970939, 3019018);\n                    }\n                    if slot == 60 {\n                        return (3088311, 3019018, 3066984);\n                    }\n                    if slot == 61 {\n                        return (3139783, 3066984, 3114834);\n                    }\n                    if slot == 62 {\n                        return (3191255, 3114834, 3162567);\n                    }\n                    if slot == 63 {\n                        return (3242727, 3162567, 3210181);\n                    }\n                }\n            }\n        } else {\n            if slot < 96 {\n                if slot < 80 {\n                    if slot == 64 {\n                        return (3294199, 3210181, 3257674);\n                    }\n                    if slot == 65 {\n                        return (3345671, 3257674, 3305045);\n                    }\n                    if slot == 66 {\n                        return (3397142, 3305045, 3352291);\n                    }\n                    if slot == 67 {\n                        return (3448614, 3352291, 3399411);\n                    }\n                    if slot == 68 {\n                        return (3500086, 3399411, 3446402);\n                    }\n                    if slot == 69 {\n                        return (3551558, 3446402, 3493264);\n                    }\n                    if slot == 70 {\n                        return (3603030, 3493264, 3539995);\n                    }\n                    if slot == 71 {\n                        return (3654502, 3539995, 3586592);\n                    }\n                    if slot == 72 {\n                        return (3705973, 3586592, 3633054);\n                    }\n                    if slot == 73 {\n                        return (3757445, 3633054, 3679380);\n                    }\n                    if slot == 74 {\n                        return (3808917, 3679380, 3725567);\n                    }\n                    if slot == 75 {\n                        return (3860389, 3725567, 3771613);\n                    }\n                    if slot == 76 {\n                        return (3911861, 3771613, 3817518);\n                    }\n                    if slot == 77 {\n                        return (3963333, 3817518, 3863279);\n                    }\n                    if slot == 78 {\n                        return (4014805, 3863279, 3908894);\n                    }\n                    if slot == 79 {\n                        return (4066276, 3908894, 3954362);\n                    }\n                } else {\n                    if slot == 80 {\n                        return (4117751, 3954362, 3999682);\n                    }\n                    if slot == 81 {\n                        return (4169220, 3999682, 4044851);\n                    }\n                    if slot == 82 {\n                        return (4220692, 4044851, 4089867);\n                    }\n                    if slot == 83 {\n                        return (4272164, 4089867, 4134730);\n                    }\n                    if slot == 84 {\n                        return (4323636, 4134730, 4179437);\n                    }\n                    if slot == 85 {\n                        return (4375108, 4179437, 4223986);\n                    }\n                    if slot == 86 {\n                        return (4426579, 4223986, 4268377);\n                    }\n                    if slot == 87 {\n                        return (4478051, 4268377, 4312606);\n                    }\n                    if slot == 88 {\n                        return (4529523, 4312606, 4356674);\n                    }\n                    if slot == 89 {\n                        return (4580995, 4356674, 4400577);\n                    }\n                    if slot == 90 {\n                        return (4632474, 4400577, 4444315);\n                    }\n                    if slot == 91 {\n                        return (4683939, 4444315, 4487885);\n                    }\n                    if slot == 92 {\n                        return (4735411, 4487885, 4531287);\n                    }\n                    if slot == 93 {\n                        return (4786882, 4531287, 4574518);\n                    }\n                    if slot == 94 {\n                        return (4838354, 4574518, 4617576);\n                    }\n                    if slot == 95 {\n                        return (4889826, 4617576, 4660461);\n                    }\n                }\n            } else {\n                if slot < 112 {\n                    if slot == 96 {\n                        return (4941298, 4660461, 4703170);\n                    }\n                    if slot == 97 {\n                        return (4992770, 4703170, 4745702);\n                    }\n                    if slot == 98 {\n                        return (5044242, 4745702, 4788056);\n                    }\n                    if slot == 99 {\n                        return (5095714, 4788056, 4830229);\n                    }\n                    if slot == 100 {\n                        return (5147227, 4830229, 4872221);\n                    }\n                    if slot == 101 {\n                        return (5198657, 4872221, 4914029);\n                    }\n                    if slot == 102 {\n                        return (5250129, 4914029, 4955652);\n                    }\n                    if slot == 103 {\n                        return (5301601, 4955652, 4997088);\n                    }\n                    if slot == 104 {\n                        return (5353073, 4997088, 5038336);\n                    }\n                    if slot == 105 {\n                        return (5404545, 5038336, 5079395);\n                    }\n                    if slot == 106 {\n                        return (5456017, 5079395, 5120262);\n                    }\n                    if slot == 107 {\n                        return (5507488, 5120262, 5160937);\n                    }\n                    if slot == 108 {\n                        return (5558960, 5160937, 5201417);\n                    }\n                    if slot == 109 {\n                        return (5610432, 5201417, 5241701);\n                    }\n                    if slot == 110 {\n                        return (5661904, 5241701, 5281788);\n                    }\n                    if slot == 111 {\n                        return (5713376, 5281788, 5321677);\n                    }\n                } else {\n                    if slot == 112 {\n                        return (5764848, 5321677, 5361364);\n                    }\n                    if slot == 113 {\n                        return (5816320, 5361364, 5400850);\n                    }\n                    if slot == 114 {\n                        return (5867791, 5400850, 5440133);\n                    }\n                    if slot == 115 {\n                        return (5919263, 5440133, 5479211);\n                    }\n                    if slot == 116 {\n                        return (5970735, 5479211, 5518082);\n                    }\n                    if slot == 117 {\n                        return (6022207, 5518082, 5556746);\n                    }\n                    if slot == 118 {\n                        return (6073679, 5556746, 5595201);\n                    }\n                    if slot == 119 {\n                        return (6125151, 5595201, 5633445);\n                    }\n                    if slot == 120 {\n                        return (6176622, 5633445, 5671477);\n                    }\n                    if slot == 121 {\n                        return (6228094, 5671477, 5709295);\n                    }\n                    if slot == 122 {\n                        return (6279566, 5709295, 5746898);\n                    }\n                    if slot == 123 {\n                        return (6331038, 5746898, 5784285);\n                    }\n                    if slot == 124 {\n                        return (6382510, 5784285, 5821455);\n                    }\n                    if slot == 125 {\n                        return (6433982, 5821455, 5858405);\n                    }\n                    if slot == 126 {\n                        return (6485454, 5858405, 5895134);\n                    }\n                    if slot == 127 {\n                        return (6536925, 5895134, 5931642);\n                    }\n                }\n            }\n        }\n    } else {\n        if slot < 192 {\n            if slot < 160 {\n                if slot < 144 {\n                    if slot == 128 {\n                        return (6588397, 5931642, 5967926);\n                    }\n                    if slot == 129 {\n                        return (6639869, 5967926, 6003985);\n                    }\n                    if slot == 130 {\n                        return (6691345, 6003985, 6039819);\n                    }\n                    if slot == 131 {\n                        return (6742813, 6039819, 6075425);\n                    }\n                    if slot == 132 {\n                        return (6794285, 6075425, 6110802);\n                    }\n                    if slot == 133 {\n                        return (6845757, 6110802, 6145949);\n                    }\n                    if slot == 134 {\n                        return (6897228, 6145949, 6180865);\n                    }\n                    if slot == 135 {\n                        return (6948700, 6180865, 6215549);\n                    }\n                    if slot == 136 {\n                        return (7000172, 6215549, 6249998);\n                    }\n                    if slot == 137 {\n                        return (7051644, 6249998, 6284212);\n                    }\n                    if slot == 138 {\n                        return (7103116, 6284212, 6318189);\n                    }\n                    if slot == 139 {\n                        return (7154588, 6318189, 6351928);\n                    }\n                    if slot == 140 {\n                        return (7206060, 6351928, 6385428);\n                    }\n                    if slot == 141 {\n                        return (7257531, 6385428, 6418688);\n                    }\n                    if slot == 142 {\n                        return (7309003, 6418688, 6451706);\n                    }\n                    if slot == 143 {\n                        return (7360475, 6451706, 6484482);\n                    }\n                } else {\n                    if slot == 144 {\n                        return (7411947, 6484482, 6517013);\n                    }\n                    if slot == 145 {\n                        return (7463419, 6517013, 6549299);\n                    }\n                    if slot == 146 {\n                        return (7514891, 6549299, 6581338);\n                    }\n                    if slot == 147 {\n                        return (7566363, 6581338, 6613129);\n                    }\n                    if slot == 148 {\n                        return (7617834, 6613129, 6644672);\n                    }\n                    if slot == 149 {\n                        return (7669306, 6644672, 6675964);\n                    }\n                    if slot == 150 {\n                        return (7720780, 6675964, 6707005);\n                    }\n                    if slot == 151 {\n                        return (7772250, 6707005, 6737793);\n                    }\n                    if slot == 152 {\n                        return (7823722, 6737793, 6768328);\n                    }\n                    if slot == 153 {\n                        return (7875194, 6768328, 6798608);\n                    }\n                    if slot == 154 {\n                        return (7926666, 6798608, 6828632);\n                    }\n                    if slot == 155 {\n                        return (7978137, 6828632, 6858399);\n                    }\n                    if slot == 156 {\n                        return (8029609, 6858399, 6887907);\n                    }\n                    if slot == 157 {\n                        return (8081081, 6887907, 6917156);\n                    }\n                    if slot == 158 {\n                        return (8132553, 6917156, 6946145);\n                    }\n                    if slot == 159 {\n                        return (8184025, 6946145, 6974873);\n                    }\n                    if slot == 160 {\n                        return (8235503, 6974873, 7003337);\n                    }\n                }\n            } else {\n                if slot < 176 {\n                    if slot == 161 {\n                        return (8286968, 7003337, 7031538);\n                    }\n                    if slot == 162 {\n                        return (8338440, 7031538, 7059475);\n                    }\n                    if slot == 163 {\n                        return (8389912, 7059475, 7087145);\n                    }\n                    if slot == 164 {\n                        return (8441384, 7087145, 7114549);\n                    }\n                    if slot == 165 {\n                        return (8492856, 7114549, 7141685);\n                    }\n                    if slot == 166 {\n                        return (8544328, 7141685, 7168552);\n                    }\n                    if slot == 167 {\n                        return (8595800, 7168552, 7195149);\n                    }\n                    if slot == 168 {\n                        return (8647271, 7195149, 7221475);\n                    }\n                    if slot == 169 {\n                        return (8698743, 7221475, 7247530);\n                    }\n                    if slot == 170 {\n                        return (8750215, 7247530, 7273311);\n                    }\n                    if slot == 171 {\n                        return (8801687, 7273311, 7298819);\n                    }\n                    if slot == 172 {\n                        return (8853159, 7298819, 7324052);\n                    }\n                    if slot == 173 {\n                        return (8904631, 7324052, 7349009);\n                    }\n                    if slot == 174 {\n                        return (8956103, 7349009, 7373689);\n                    }\n                    if slot == 175 {\n                        return (9007574, 7373689, 7398092);\n                    }\n                } else {\n                    if slot == 176 {\n                        return (9059046, 7398092, 7422216);\n                    }\n                    if slot == 177 {\n                        return (9110518, 7422216, 7446061);\n                    }\n                    if slot == 178 {\n                        return (9161990, 7446061, 7469625);\n                    }\n                    if slot == 179 {\n                        return (9213462, 7469625, 7492909);\n                    }\n                    if slot == 180 {\n                        return (9264934, 7492909, 7515910);\n                    }\n                    if slot == 181 {\n                        return (9316406, 7515910, 7538628);\n                    }\n                    if slot == 182 {\n                        return (9367877, 7538628, 7561062);\n                    }\n                    if slot == 183 {\n                        return (9419349, 7561062, 7583212);\n                    }\n                    if slot == 184 {\n                        return (9470821, 7583212, 7605076);\n                    }\n                    if slot == 185 {\n                        return (9522293, 7605076, 7626654);\n                    }\n                    if slot == 186 {\n                        return (9573765, 7626654, 7647945);\n                    }\n                    if slot == 187 {\n                        return (9625237, 7647945, 7668947);\n                    }\n                    if slot == 188 {\n                        return (9676709, 7668947, 7689661);\n                    }\n                    if slot == 189 {\n                        return (9728180, 7689661, 7710086);\n                    }\n                    if slot == 190 {\n                        return (9779651, 7710086, 7730220);\n                    }\n                    if slot == 191 {\n                        return (9831124, 7730220, 7750063);\n                    }\n                }\n            }\n        } else {\n            if slot < 224 {\n                if slot < 208 {\n                    if slot == 192 {\n                        return (9882596, 7750063, 7769615);\n                    }\n                    if slot == 193 {\n                        return (9934068, 7769615, 7788874);\n                    }\n                    if slot == 194 {\n                        return (9985540, 7788874, 7807839);\n                    }\n                    if slot == 195 {\n                        return (10037012, 7807839, 7826511);\n                    }\n                    if slot == 196 {\n                        return (10088483, 7826511, 7844888);\n                    }\n                    if slot == 197 {\n                        return (10139955, 7844888, 7862970);\n                    }\n                    if slot == 198 {\n                        return (10191427, 7862970, 7880755);\n                    }\n                    if slot == 199 {\n                        return (10242899, 7880755, 7898244);\n                    }\n                    if slot == 200 {\n                        return (10294373, 7898244, 7915436);\n                    }\n                    if slot == 201 {\n                        return (10345843, 7915436, 7932329);\n                    }\n                    if slot == 202 {\n                        return (10397315, 7932329, 7948924);\n                    }\n                    if slot == 203 {\n                        return (10448786, 7948924, 7965220);\n                    }\n                    if slot == 204 {\n                        return (10500258, 7965220, 7981215);\n                    }\n                    if slot == 205 {\n                        return (10551730, 7981215, 7996911);\n                    }\n                    if slot == 206 {\n                        return (10603202, 7996911, 8012305);\n                    }\n                    if slot == 207 {\n                        return (10654674, 8012305, 8027397);\n                    }\n                } else {\n                    if slot == 208 {\n                        return (10706146, 8027397, 8042188);\n                    }\n                    if slot == 209 {\n                        return (10757617, 8042188, 8056675);\n                    }\n                    if slot == 210 {\n                        return (10809089, 8056675, 8070859);\n                    }\n                    if slot == 211 {\n                        return (10860561, 8070859, 8084740);\n                    }\n                    if slot == 212 {\n                        return (10912033, 8084740, 8098316);\n                    }\n                    if slot == 213 {\n                        return (10963505, 8098316, 8111587);\n                    }\n                    if slot == 214 {\n                        return (11014977, 8111587, 8124552);\n                    }\n                    if slot == 215 {\n                        return (11066449, 8124552, 8137212);\n                    }\n                    if slot == 216 {\n                        return (11117920, 8137212, 8149565);\n                    }\n                    if slot == 217 {\n                        return (11169392, 8149565, 8161612);\n                    }\n                    if slot == 218 {\n                        return (11220864, 8161612, 8173351);\n                    }\n                    if slot == 219 {\n                        return (11272336, 8173351, 8184783);\n                    }\n                    if slot == 220 {\n                        return (11323808, 8184783, 8195906);\n                    }\n                    if slot == 221 {\n                        return (11375280, 8195906, 8206721);\n                    }\n                    if slot == 222 {\n                        return (11426752, 8206721, 8217227);\n                    }\n                    if slot == 223 {\n                        return (11478223, 8217227, 8227423);\n                    }\n                }\n            } else {\n                if slot < 240 {\n                    if slot == 224 {\n                        return (11529695, 8227423, 8237310);\n                    }\n                    if slot == 225 {\n                        return (11581167, 8237310, 8246887);\n                    }\n                    if slot == 226 {\n                        return (11632639, 8246887, 8256153);\n                    }\n                    if slot == 227 {\n                        return (11684111, 8256153, 8265108);\n                    }\n                    if slot == 228 {\n                        return (11735583, 8265108, 8273752);\n                    }\n                    if slot == 229 {\n                        return (11787055, 8273752, 8282085);\n                    }\n                    if slot == 230 {\n                        return (11838531, 8282085, 8290105);\n                    }\n                    if slot == 231 {\n                        return (11889998, 8290105, 8297814);\n                    }\n                    if slot == 232 {\n                        return (11941470, 8297814, 8305210);\n                    }\n                    if slot == 233 {\n                        return (11992942, 8305210, 8312294);\n                    }\n                    if slot == 234 {\n                        return (12044414, 8312294, 8319064);\n                    }\n                    if slot == 235 {\n                        return (12095886, 8319064, 8325522);\n                    }\n                    if slot == 236 {\n                        return (12147358, 8325522, 8331666);\n                    }\n                    if slot == 237 {\n                        return (12198829, 8331666, 8337496);\n                    }\n                    if slot == 238 {\n                        return (12250301, 8337496, 8343012);\n                    }\n                    if slot == 239 {\n                        return (12301773, 8343012, 8348215);\n                    }\n                } else {\n                    if slot == 240 {\n                        return (12353244, 8348215, 8353102);\n                    }\n                    if slot == 241 {\n                        return (12404717, 8353102, 8357676);\n                    }\n                    if slot == 242 {\n                        return (12456189, 8357676, 8361935);\n                    }\n                    if slot == 243 {\n                        return (12507661, 8361935, 8365879);\n                    }\n                    if slot == 244 {\n                        return (12559132, 8365879, 8369508);\n                    }\n                    if slot == 245 {\n                        return (12610604, 8369508, 8372822);\n                    }\n                    if slot == 246 {\n                        return (12662076, 8372822, 8375820);\n                    }\n                    if slot == 247 {\n                        return (12713548, 8375820, 8378504);\n                    }\n                    if slot == 248 {\n                        return (12765020, 8378504, 8380871);\n                    }\n                    if slot == 249 {\n                        return (12816492, 8380871, 8382924);\n                    }\n                    if slot == 250 {\n                        return (12867964, 8382924, 8384660);\n                    }\n                    if slot == 251 {\n                        return (12919435, 8384660, 8386082);\n                    }\n                    if slot == 252 {\n                        return (12970907, 8386082, 8387187);\n                    }\n                    if slot == 253 {\n                        return (13022379, 8387187, 8387976);\n                    }\n                    if slot == 254 {\n                        return (13073851, 8387976, 8388450);\n                    }\n                }\n            }\n        }\n    }\n\n    (13125323, 8388450, 8388608)\n}\n\nfn atan(a: u32) -> (u32, u32, u32) {\n    let slot = a / 58720;\n\n    if slot == 0 {\n        return (0, 0, 58719);\n    }\n    if slot == 1 {\n        return (58720, 58719, 117433);\n    }\n    if slot == 2 {\n        return (117441, 117433, 176135);\n    }\n    if slot == 3 {\n        return (176161, 176135, 234820);\n    }\n    if slot == 4 {\n        return (234881, 234820, 293481);\n    }\n    if slot == 5 {\n        return (293601, 293481, 352115);\n    }\n    if slot == 6 {\n        return (352322, 352115, 410713);\n    }\n    if slot == 7 {\n        return (411042, 410713, 469272);\n    }\n    if slot == 8 {\n        return (469762, 469272, 527785);\n    }\n    if slot == 9 {\n        return (528482, 527785, 586246);\n    }\n    if slot == 10 {\n        return (587201, 586246, 644651);\n    }\n    if slot == 11 {\n        return (645923, 644651, 702993);\n    }\n    if slot == 12 {\n        return (704643, 702993, 761267);\n    }\n    if slot == 13 {\n        return (763363, 761267, 819467);\n    }\n    if slot == 14 {\n        return (822084, 819467, 877588);\n    }\n    if slot == 15 {\n        return (880804, 877588, 935625);\n    }\n    if slot == 16 {\n        return (939524, 935625, 993572);\n    }\n    if slot == 17 {\n        return (998244, 993572, 1051424);\n    }\n    if slot == 18 {\n        return (1056965, 1051424, 1109175);\n    }\n    if slot == 19 {\n        return (1115685, 1109175, 1166821);\n    }\n    if slot == 20 {\n        return (1174411, 1166821, 1224357);\n    }\n    if slot == 21 {\n        return (1233125, 1224357, 1281776);\n    }\n    if slot == 22 {\n        return (1291846, 1281776, 1339075);\n    }\n    if slot == 23 {\n        return (1350566, 1339075, 1396248);\n    }\n    if slot == 24 {\n        return (1409286, 1396248, 1453290);\n    }\n    if slot == 25 {\n        return (1468006, 1453290, 1510197);\n    }\n    if slot == 26 {\n        return (1526727, 1510197, 1566964);\n    }\n    if slot == 27 {\n        return (1585447, 1566964, 1623585);\n    }\n    if slot == 28 {\n        return (1644167, 1623585, 1680058);\n    }\n    if slot == 29 {\n        return (1702887, 1680058, 1736376);\n    }\n    if slot == 30 {\n        return (1761612, 1736376, 1792537);\n    }\n    if slot == 31 {\n        return (1820328, 1792537, 1848534);\n    }\n    if slot == 32 {\n        return (1879048, 1848534, 1904364);\n    }\n    if slot == 33 {\n        return (1937768, 1904364, 1960024);\n    }\n    if slot == 34 {\n        return (1996489, 1960024, 2015508);\n    }\n    if slot == 35 {\n        return (2055209, 2015508, 2070813);\n    }\n    if slot == 36 {\n        return (2113929, 2070813, 2125935);\n    }\n    if slot == 37 {\n        return (2172649, 2125935, 2180869);\n    }\n    if slot == 38 {\n        return (2231370, 2180869, 2235613);\n    }\n    if slot == 39 {\n        return (2290090, 2235613, 2290163);\n    }\n    if slot == 40 {\n        return (2348813, 2290163, 2344515);\n    }\n    if slot == 41 {\n        return (2407530, 2344515, 2398665);\n    }\n    if slot == 42 {\n        return (2466251, 2398665, 2452611);\n    }\n    if slot == 43 {\n        return (2524971, 2452611, 2506348);\n    }\n    if slot == 44 {\n        return (2583691, 2506348, 2559875);\n    }\n    if slot == 45 {\n        return (2642412, 2559875, 2613187);\n    }\n    if slot == 46 {\n        return (2701132, 2613187, 2666281);\n    }\n    if slot == 47 {\n        return (2759852, 2666281, 2719156);\n    }\n    if slot == 48 {\n        return (2818572, 2719156, 2771807);\n    }\n    if slot == 49 {\n        return (2877293, 2771807, 2824233);\n    }\n    if slot == 50 {\n        return (2936014, 2824233, 2876431);\n    }\n    if slot == 51 {\n        return (2994733, 2876431, 2928397);\n    }\n    if slot == 52 {\n        return (3053453, 2928397, 2980130);\n    }\n    if slot == 53 {\n        return (3112174, 2980130, 3031628);\n    }\n    if slot == 54 {\n        return (3170894, 3031628, 3082888);\n    }\n    if slot == 55 {\n        return (3229614, 3082888, 3133907);\n    }\n    if slot == 56 {\n        return (3288334, 3133907, 3184685);\n    }\n    if slot == 57 {\n        return (3347055, 3184685, 3235218);\n    }\n    if slot == 58 {\n        return (3405775, 3235218, 3285506);\n    }\n    if slot == 59 {\n        return (3464495, 3285506, 3335545);\n    }\n    if slot == 60 {\n        return (3523224, 3335545, 3385336);\n    }\n    if slot == 61 {\n        return (3581936, 3385336, 3434875);\n    }\n    if slot == 62 {\n        return (3640656, 3434875, 3484161);\n    }\n    if slot == 63 {\n        return (3699376, 3484161, 3533193);\n    }\n    if slot == 64 {\n        return (3758096, 3533193, 3581970);\n    }\n    if slot == 65 {\n        return (3816817, 3581970, 3630491);\n    }\n    if slot == 66 {\n        return (3875537, 3630491, 3678753);\n    }\n    if slot == 67 {\n        return (3934257, 3678753, 3726756);\n    }\n    if slot == 68 {\n        return (3992977, 3726756, 3774499);\n    }\n    if slot == 69 {\n        return (4051698, 3774499, 3821981);\n    }\n    if slot == 70 {\n        return (4110418, 3821981, 3869201);\n    }\n    if slot == 71 {\n        return (4169138, 3869201, 3916159);\n    }\n    if slot == 72 {\n        return (4227858, 3916159, 3962853);\n    }\n    if slot == 73 {\n        return (4286579, 3962853, 4009282);\n    }\n    if slot == 74 {\n        return (4345299, 4009282, 4055447);\n    }\n    if slot == 75 {\n        return (4404019, 4055447, 4101347);\n    }\n    if slot == 76 {\n        return (4462739, 4101347, 4146981);\n    }\n    if slot == 77 {\n        return (4521460, 4146981, 4192350);\n    }\n    if slot == 78 {\n        return (4580180, 4192350, 4237451);\n    }\n    if slot == 79 {\n        return (4638900, 4237451, 4282286);\n    }\n    if slot == 80 {\n        return (4697620, 4282286, 4326855);\n    }\n    if slot == 81 {\n        return (4756341, 4326855, 4371156);\n    }\n    if slot == 82 {\n        return (4815061, 4371156, 4415191);\n    }\n    if slot == 83 {\n        return (4873781, 4415191, 4458958);\n    }\n    if slot == 84 {\n        return (4932502, 4458958, 4502459);\n    }\n    if slot == 85 {\n        return (4991222, 4502459, 4545693);\n    }\n    if slot == 86 {\n        return (5049942, 4545693, 4588660);\n    }\n    if slot == 87 {\n        return (5108662, 4588660, 4631361);\n    }\n    if slot == 88 {\n        return (5167383, 4631361, 4673795);\n    }\n    if slot == 89 {\n        return (5226103, 4673795, 4715964);\n    }\n    if slot == 90 {\n        return (5284823, 4715964, 4757868);\n    }\n    if slot == 91 {\n        return (5343543, 4757868, 4799506);\n    }\n    if slot == 92 {\n        return (5402264, 4799506, 4840880);\n    }\n    if slot == 93 {\n        return (5460984, 4840880, 4881990);\n    }\n    if slot == 94 {\n        return (5519704, 4881990, 4922837);\n    }\n    if slot == 95 {\n        return (5578424, 4922837, 4963420);\n    }\n    if slot == 96 {\n        return (5637145, 4963420, 5003742);\n    }\n    if slot == 97 {\n        return (5695865, 5003742, 5043802);\n    }\n    if slot == 98 {\n        return (5754585, 5043802, 5083601);\n    }\n\n    (5813305, 5083601, 5123141)\n}\n\nfn erf_lut(x: u32) -> u32 {\n    // Construct the erf lookup table\n    if x <= 754974 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 83886 {\n            return 94652;\n        }\n        if x <= 167772 {\n            return 189285;\n        }\n        if x <= 251658 {\n            return 283880;\n        }\n        if x <= 335544 {\n            return 378419;\n        }\n        if x <= 419430 {\n            return 472882;\n        }\n        if x <= 503316 {\n            return 567251;\n        }\n        if x <= 587202 {\n            return 661506;\n        }\n        if x <= 671088 {\n            return 755630;\n        }\n        if x <= 754974 {\n            return 849603;\n        }\n    }\n    if x <= 1593835 {\n        if x <= 838860 {\n            return 943407;\n        }\n        if x <= 922746 {\n            return 1037024;\n        }\n        if x <= 1006632 {\n            return 1130434;\n        }\n        if x <= 1090519 {\n            return 1223622;\n        }\n        if x <= 1174405 {\n            return 1316567;\n        }\n        if x <= 1258291 {\n            return 1409252;\n        }\n        if x <= 1342177 {\n            return 1501659;\n        }\n        if x <= 1426063 {\n            return 1593772;\n        }\n        if x <= 1509949 {\n            return 1685571;\n        }\n        if x <= 1593835 {\n            return 1777041;\n        }\n    }\n    if x <= 2432696 {\n        if x <= 1677721 {\n            return 1868164;\n        }\n        if x <= 1761607 {\n            return 1958923;\n        }\n        if x <= 1845493 {\n            return 2049302;\n        }\n        if x <= 1929379 {\n            return 2139284;\n        }\n        if x <= 2013265 {\n            return 2228853;\n        }\n        if x <= 2097152 {\n            return 2317993;\n        }\n        if x <= 2181038 {\n            return 2406689;\n        }\n        if x <= 2264924 {\n            return 2494924;\n        }\n        if x <= 2348810 {\n            return 2582685;\n        }\n        if x <= 2432696 {\n            return 2669955;\n        }\n    }\n    if x <= 3271557 {\n        if x <= 2516582 {\n            return 2756721;\n        }\n        if x <= 2600468 {\n            return 2842967;\n        }\n        if x <= 2684354 {\n            return 2928681;\n        }\n        if x <= 2768240 {\n            return 3013847;\n        }\n        if x <= 2852126 {\n            return 3098454;\n        }\n        if x <= 2936012 {\n            return 3182487;\n        }\n        if x <= 3019898 {\n            return 3265934;\n        }\n        if x <= 3103784 {\n            return 3348782;\n        }\n        if x <= 3187671 {\n            return 3431019;\n        }\n        if x <= 3271557 {\n            return 3512634;\n        }\n    }\n    if x <= 4110417 {\n        if x <= 3355443 {\n            return 3593615;\n        }\n        if x <= 3439329 {\n            return 3673951;\n        }\n        if x <= 3523215 {\n            return 3753630;\n        }\n        if x <= 3607101 {\n            return 3832643;\n        }\n        if x <= 3690987 {\n            return 3910979;\n        }\n        if x <= 3774873 {\n            return 3988629;\n        }\n        if x <= 3858759 {\n            return 4065584;\n        }\n        if x <= 3942645 {\n            return 4141833;\n        }\n        if x <= 4026531 {\n            return 4217369;\n        }\n        if x <= 4110417 {\n            return 4292184;\n        }\n    }\n    if x <= 4949278 {\n        if x <= 4194304 {\n            return 4366269;\n        }\n        if x <= 4278190 {\n            return 4439617;\n        }\n        if x <= 4362076 {\n            return 4512220;\n        }\n        if x <= 4445962 {\n            return 4584073;\n        }\n        if x <= 4529848 {\n            return 4655167;\n        }\n        if x <= 4613734 {\n            return 4725498;\n        }\n        if x <= 4697620 {\n            return 4795060;\n        }\n        if x <= 4781506 {\n            return 4863847;\n        }\n        if x <= 4865392 {\n            return 4931854;\n        }\n        if x <= 4949278 {\n            return 4999077;\n        }\n    }\n    if x <= 5788139 {\n        if x <= 5033164 {\n            return 5065512;\n        }\n        if x <= 5117050 {\n            return 5131153;\n        }\n        if x <= 5200936 {\n            return 5195999;\n        }\n        if x <= 5284823 {\n            return 5260046;\n        }\n        if x <= 5368709 {\n            return 5323291;\n        }\n        if x <= 5452595 {\n            return 5385732;\n        }\n        if x <= 5536481 {\n            return 5447366;\n        }\n        if x <= 5620367 {\n            return 5508192;\n        }\n        if x <= 5704253 {\n            return 5568208;\n        }\n        if x <= 5788139 {\n            return 5627414;\n        }\n    }\n    if x <= 6627000 {\n        if x <= 5872025 {\n            return 5685808;\n        }\n        if x <= 5955911 {\n            return 5743390;\n        }\n        if x <= 6039797 {\n            return 5800161;\n        }\n        if x <= 6123683 {\n            return 5856120;\n        }\n        if x <= 6207569 {\n            return 5911268;\n        }\n        if x <= 6291456 {\n            return 5965605;\n        }\n        if x <= 6375342 {\n            return 6019134;\n        }\n        if x <= 6459228 {\n            return 6071855;\n        }\n        if x <= 6543114 {\n            return 6123771;\n        }\n        if x <= 6627000 {\n            return 6174883;\n        }\n    }\n    if x <= 7465861 {\n        if x <= 6710886 {\n            return 6225194;\n        }\n        if x <= 6794772 {\n            return 6274706;\n        }\n        if x <= 6878658 {\n            return 6323422;\n        }\n        if x <= 6962544 {\n            return 6371347;\n        }\n        if x <= 7046430 {\n            return 6418482;\n        }\n        if x <= 7130316 {\n            return 6464832;\n        }\n        if x <= 7214202 {\n            return 6510400;\n        }\n        if x <= 7298088 {\n            return 6555192;\n        }\n        if x <= 7381975 {\n            return 6599211;\n        }\n        if x <= 7465861 {\n            return 6642462;\n        }\n    }\n    if x <= 8304721 {\n        if x <= 7549747 {\n            return 6684950;\n        }\n        if x <= 7633633 {\n            return 6726680;\n        }\n        if x <= 7717519 {\n            return 6767658;\n        }\n        if x <= 7801405 {\n            return 6807888;\n        }\n        if x <= 7885291 {\n            return 6847377;\n        }\n        if x <= 7969177 {\n            return 6886131;\n        }\n        if x <= 8053063 {\n            return 6924155;\n        }\n        if x <= 8136949 {\n            return 6961456;\n        }\n        if x <= 8220835 {\n            return 6998041;\n        }\n        if x <= 8304721 {\n            return 7033915;\n        }\n    }\n    if x <= 9143582 {\n        if x <= 8388608 {\n            return 7069086;\n        }\n        if x <= 8472494 {\n            return 7103561;\n        }\n        if x <= 8556380 {\n            return 7137346;\n        }\n        if x <= 8640266 {\n            return 7170449;\n        }\n        if x <= 8724152 {\n            return 7202877;\n        }\n        if x <= 8808038 {\n            return 7234638;\n        }\n        if x <= 8891924 {\n            return 7265739;\n        }\n        if x <= 8975810 {\n            return 7296187;\n        }\n        if x <= 9059696 {\n            return 7325990;\n        }\n        if x <= 9143582 {\n            return 7355157;\n        }\n    }\n    if x <= 9982443 {\n        if x <= 9227468 {\n            return 7383695;\n        }\n        if x <= 9311354 {\n            return 7411612;\n        }\n        if x <= 9395240 {\n            return 7438915;\n        }\n        if x <= 9479127 {\n            return 7465615;\n        }\n        if x <= 9563013 {\n            return 7491717;\n        }\n        if x <= 9646899 {\n            return 7517231;\n        }\n        if x <= 9730785 {\n            return 7542165;\n        }\n        if x <= 9814671 {\n            return 7566527;\n        }\n        if x <= 9898557 {\n            return 7590326;\n        }\n        if x <= 9982443 {\n            return 7613570;\n        }\n    }\n    if x <= 10821304 {\n        if x <= 10066329 {\n            return 7636267;\n        }\n        if x <= 10150215 {\n            return 7658425;\n        }\n        if x <= 10234101 {\n            return 7680054;\n        }\n        if x <= 10317987 {\n            return 7701162;\n        }\n        if x <= 10401873 {\n            return 7721757;\n        }\n        if x <= 10485760 {\n            return 7741847;\n        }\n        if x <= 10569646 {\n            return 7761441;\n        }\n        if x <= 10653532 {\n            return 7780548;\n        }\n        if x <= 10737418 {\n            return 7799175;\n        }\n        if x <= 10821304 {\n            return 7817332;\n        }\n    }\n    if x <= 11660165 {\n        if x <= 10905190 {\n            return 7835026;\n        }\n        if x <= 10989076 {\n            return 7852266;\n        }\n        if x <= 11072962 {\n            return 7869060;\n        }\n        if x <= 11156848 {\n            return 7885417;\n        }\n        if x <= 11240734 {\n            return 7901344;\n        }\n        if x <= 11324620 {\n            return 7916851;\n        }\n        if x <= 11408506 {\n            return 7931944;\n        }\n        if x <= 11492392 {\n            return 7946632;\n        }\n        if x <= 11576279 {\n            return 7960923;\n        }\n        if x <= 11660165 {\n            return 7974825;\n        }\n    }\n    if x <= 12499025 {\n        if x <= 11744051 {\n            return 7988346;\n        }\n        if x <= 11827937 {\n            return 8001494;\n        }\n        if x <= 11911823 {\n            return 8014276;\n        }\n        if x <= 11995709 {\n            return 8026700;\n        }\n        if x <= 12079595 {\n            return 8038774;\n        }\n        if x <= 12163481 {\n            return 8050505;\n        }\n        if x <= 12247367 {\n            return 8061901;\n        }\n        if x <= 12331253 {\n            return 8072969;\n        }\n        if x <= 12415139 {\n            return 8083716;\n        }\n        if x <= 12499025 {\n            return 8094149;\n        }\n    }\n    if x <= 13337886 {\n        if x <= 12582912 {\n            return 8104277;\n        }\n        if x <= 12666798 {\n            return 8114105;\n        }\n        if x <= 12750684 {\n            return 8123641;\n        }\n        if x <= 12834570 {\n            return 8132891;\n        }\n        if x <= 12918456 {\n            return 8141862;\n        }\n        if x <= 13002342 {\n            return 8150562;\n        }\n        if x <= 13086228 {\n            return 8158996;\n        }\n        if x <= 13170114 {\n            return 8167170;\n        }\n        if x <= 13254000 {\n            return 8175092;\n        }\n        if x <= 13337886 {\n            return 8182768;\n        }\n    }\n    if x <= 14176747 {\n        if x <= 13421772 {\n            return 8190203;\n        }\n        if x <= 13505658 {\n            return 8197405;\n        }\n        if x <= 13589544 {\n            return 8204378;\n        }\n        if x <= 13673431 {\n            return 8211128;\n        }\n        if x <= 13757317 {\n            return 8217663;\n        }\n        if x <= 13841203 {\n            return 8223986;\n        }\n        if x <= 13925089 {\n            return 8230104;\n        }\n        if x <= 14008975 {\n            return 8236022;\n        }\n        if x <= 14092861 {\n            return 8241746;\n        }\n        if x <= 14176747 {\n            return 8247281;\n        }\n    }\n    if x <= 15015608 {\n        if x <= 14260633 {\n            return 8252632;\n        }\n        if x <= 14344519 {\n            return 8257804;\n        }\n        if x <= 14428405 {\n            return 8262802;\n        }\n        if x <= 14512291 {\n            return 8267631;\n        }\n        if x <= 14596177 {\n            return 8272296;\n        }\n        if x <= 14680064 {\n            return 8276801;\n        }\n        if x <= 14763950 {\n            return 8281152;\n        }\n        if x <= 14847836 {\n            return 8285352;\n        }\n        if x <= 14931722 {\n            return 8289405;\n        }\n        if x <= 15015608 {\n            return 8293318;\n        }\n    }\n    if x <= 15854469 {\n        if x <= 15099494 {\n            return 8297092;\n        }\n        if x <= 15183380 {\n            return 8300733;\n        }\n        if x <= 15267266 {\n            return 8304245;\n        }\n        if x <= 15351152 {\n            return 8307631;\n        }\n        if x <= 15435038 {\n            return 8310895;\n        }\n        if x <= 15518924 {\n            return 8314041;\n        }\n        if x <= 15602810 {\n            return 8317074;\n        }\n        if x <= 15686696 {\n            return 8319995;\n        }\n        if x <= 15770583 {\n            return 8322809;\n        }\n        if x <= 15854469 {\n            return 8325519;\n        }\n    }\n    if x <= 16693329 {\n        if x <= 15938355 {\n            return 8328129;\n        }\n        if x <= 16022241 {\n            return 8330642;\n        }\n        if x <= 16106127 {\n            return 8333060;\n        }\n        if x <= 16190013 {\n            return 8335387;\n        }\n        if x <= 16273899 {\n            return 8337626;\n        }\n        if x <= 16357785 {\n            return 8339780;\n        }\n        if x <= 16441671 {\n            return 8341852;\n        }\n        if x <= 16525557 {\n            return 8343844;\n        }\n        if x <= 16609443 {\n            return 8345758;\n        }\n        if x <= 16693329 {\n            return 8347599;\n        }\n    }\n    if x <= 28521267 {\n        if x <= 16777216 {\n            return 8349368;\n        }\n        if x <= 17616076 {\n            return 8363614;\n        }\n        if x <= 18454937 {\n            return 8372981;\n        }\n        if x <= 19293798 {\n            return 8379018;\n        }\n        if x <= 20132659 {\n            return 8382832;\n        }\n        if x <= 20971520 {\n            return 8385194;\n        }\n        if x <= 21810380 {\n            return 8386627;\n        }\n        if x <= 22649241 {\n            return 8387481;\n        }\n        if x <= 23488102 {\n            return 8387978;\n        }\n        if x <= 24326963 {\n            return 8388263;\n        }\n        if x <= 25165824 {\n            return 8388422;\n        }\n        if x <= 26004684 {\n            return 8388510;\n        }\n        if x <= 26843545 {\n            return 8388557;\n        }\n        if x <= 27682406 {\n            return 8388582;\n        }\n        if x <= 28521267 {\n            return 8388595;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23/math/trig.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp8x23::math::lut;\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{\n    HALF, ONE, TWO, FP8x23, FP8x23Impl, FP8x23Add, FP8x23Sub, FP8x23Mul, FP8x23Div,\n    FP8x23IntoFelt252, FixedTrait\n};\n\n// CONSTANTS\nconst TWO_PI: u32 = 52707178;\nconst PI: u32 = 26353589;\nconst HALF_PI: u32 = 13176795;\n\n// PUBLIC\n\n// Calculates arccos(a) for -1 <= a <= 1 (fixed point)\n// arccos(a) = arcsin(sqrt(1 - a^2)) - arctan identity has discontinuity at zero\nfn acos(a: FP8x23) -> FP8x23 {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin(asin_arg);\n\n    if (a.sign) {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\nfn acos_fast(a: FP8x23) -> FP8x23 {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin_fast(asin_arg);\n\n    if (a.sign) {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\n// Calculates arcsin(a) for -1 <= a <= 1 (fixed point)\n// arcsin(a) = arctan(a / sqrt(1 - a^2))\nfn asin(a: FP8x23) -> FP8x23 {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan(a / div)\n}\n\nfn asin_fast(a: FP8x23) -> FP8x23 {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan_fast(a / div)\n}\n\n// Calculates arctan(a) (fixed point)\n// See https://stackoverflow.com/a/50894477 for range adjustments\nfn atan(a: FP8x23) -> FP8x23 {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 5872026) {\n        let sqrt3_3 = FixedTrait::new(4843165, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let r10 = FixedTrait::new(15363, true) * at;\n    let r9 = (r10 + FixedTrait::new(392482, true)) * at;\n    let r8 = (r9 + FixedTrait::new(1629064, false)) * at;\n    let r7 = (r8 + FixedTrait::new(2197820, true)) * at;\n    let r6 = (r7 + FixedTrait::new(366693, false)) * at;\n    let r5 = (r6 + FixedTrait::new(1594324, false)) * at;\n    let r4 = (r5 + FixedTrait::new(11519, false)) * at;\n    let r3 = (r4 + FixedTrait::new(2797104, true)) * at;\n    let r2 = (r3 + FixedTrait::new(34, false)) * at;\n    let mut res = (r2 + FixedTrait::new(8388608, false)) * at;\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(4392265, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\nfn atan_fast(a: FP8x23) -> FP8x23 {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 5872026) {\n        let sqrt3_3 = FixedTrait::new(4843165, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let (start, low, high) = lut::atan(at.mag);\n    let partial_step = FixedTrait::new(at.mag - start, false) / FixedTrait::new(58720, false);\n    let mut res = partial_step * FixedTrait::new(high - low, false) + FixedTrait::new(low, false);\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(4392265, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::<FP8x23>::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\n// Calculates cos(a) with a in radians (fixed point)\nfn cos(a: FP8x23) -> FP8x23 {\n    sin(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn cos_fast(a: FP8x23) -> FP8x23 {\n    sin_fast(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn sin(a: FP8x23) -> FP8x23 {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, partial_rem) = integer::u32_safe_divmod(a1, integer::u32_as_non_zero(PI));\n    let a2 = FixedTrait::new(partial_rem, false);\n    let partial_sign = whole_rem == 1;\n\n    let loop_res = a2 * _sin_loop(a2, 7, FixedTrait::ONE());\n\n    FixedTrait::new(loop_res.mag, a.sign ^ partial_sign && loop_res.mag != 0)\n}\n\nfn sin_fast(a: FP8x23) -> FP8x23 {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, mut partial_rem) = integer::u32_safe_divmod(a1, integer::u32_as_non_zero(PI));\n    let partial_sign = whole_rem == 1;\n\n    if partial_rem >= HALF_PI {\n        partial_rem = PI - partial_rem;\n    }\n\n    let (start, low, high) = lut::sin(partial_rem);\n    let partial_step = FixedTrait::new(partial_rem - start, false) / FixedTrait::new(51472, false);\n    let res = partial_step * (FixedTrait::new(high, false) - FixedTrait::new(low, false))\n        + FixedTrait::<FP8x23>::new(low, false);\n\n    FixedTrait::new(res.mag, a.sign ^ partial_sign && res.mag != 0)\n}\n\n// Calculates tan(a) with a in radians (fixed point)\nfn tan(a: FP8x23) -> FP8x23 {\n    let sinx = sin(a);\n    let cosx = cos(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\nfn tan_fast(a: FP8x23) -> FP8x23 {\n    let sinx = sin_fast(a);\n    let cosx = cos_fast(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\n// Helper function to calculate Taylor series for sin\nfn _sin_loop(a: FP8x23, i: u32, acc: FP8x23) -> FP8x23 {\n    let div = (2 * i + 2) * (2 * i + 3);\n    let term = a * a * acc / FixedTrait::new_unscaled(div, false);\n    let new_acc = FixedTrait::ONE() - term;\n\n    if (i == 0) {\n        return new_acc;\n    }\n\n    _sin_loop(a, i - 1, new_acc)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23::helpers::{\n        assert_precise, assert_relative\n    };\n\n    use super::{\n        FixedTrait, acos, HALF_PI, ONE, acos_fast, PI, atan_fast, atan, asin, cos, cos_fast, sin,\n        sin_fast, tan\n    };\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_acos() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos(a), 8784530, 'invalid half', error); // 1.0471975506263043\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos(a), 17569060, 'invalid neg half', error); // 2.094395102963489\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_acos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos_fast(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos_fast(a), 8784530, 'invalid half', error); // 1.0471975506263043\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos_fast(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos_fast(a), 17569060, 'invalid neg half', error); // 2.094395102963489\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos_fast(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(1000000)]\n    fn test_acos_fail() {\n        let a = FixedTrait::new(2 * ONE, true);\n        acos(a);\n    }\n\n    #[test]\n    #[available_gas(1400000)]\n    fn test_atan_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan_fast(a), 9287437, 'invalid two', error);\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan_fast(a), 6588397, 'invalid one', error);\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan_fast(a), 3889358, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert(atan_fast(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan_fast(a), -3889358, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan_fast(a), -6588397, 'invalid neg one', error);\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan_fast(a), -9287437, 'invalid neg two', error);\n    }\n\n    #[test]\n    #[available_gas(2600000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan(a), 9287437, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan(a), 6588397, 'invalid one', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan(a), 3889358, 'invalid half', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(atan(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan(a), -3889358, 'invalid neg half', Option::None(()));\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan(a), -6588397, 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan(a), -9287437, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_asin() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert_relative(asin(a), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(asin(a), 4392265, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert_precise(asin(a), 0, 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(asin(a), -4392265, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(asin(a), -HALF_PI.into(), 'invalid neg one', Option::None(())); // -PI / 2\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(1000000)]\n    fn test_asin_fail() {\n        let a = FixedTrait::new(2 * ONE, false);\n        asin(a);\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_cos() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_relative(\n            cos(a), 5931642, 'invalid quarter pi', Option::None(())\n        ); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert_relative(cos(a), -1 * ONE.into(), 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_relative(cos(a), -2308239, 'invalid 17', Option::None(())); // -0.2751631780463348\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_relative(cos(a), -2308236, 'invalid -17', Option::None(())); // -0.2751631780463348\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_cos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos_fast(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(cos_fast(a), 5931642, 'invalid quarter pi', error); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(cos_fast(a), -1 * ONE.into(), 'invalid pi', error);\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(cos_fast(a), -2308239, 'invalid 17', error); // -0.2751631780463348\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin(a), ONE.into(), 'invalid half pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(\n            sin(a), 5931642, 'invalid quarter pi', Option::None(())\n        ); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin(a), -ONE.into(), 'invalid neg half pi', Option::None(())\n        ); // 0.9999999999939766\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin(a), -8064787, 'invalid 17', Option::None(())); // -0.9613974918793389\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin(a), 8064787, 'invalid -17', Option::None(())); // 0.9613974918793389\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin_fast(a), ONE.into(), 'invalid half pi', error);\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin_fast(a), 5931642, 'invalid quarter pi', error); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin_fast(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin_fast(a), -ONE.into(), 'invalid neg half pi', error\n        ); // 0.9999999999939766\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin_fast(a), -8064787, 'invalid 17', error); // -0.9613974918793389\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin_fast(a), 8064787, 'invalid -17', error); // 0.9613974918793389\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_tan() {\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(tan(a), ONE.into(), 'invalid quarter pi', Option::None(()));\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(tan(a), 0, 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(tan(a), 29309069, 'invalid 17', Option::None(())); // 3.493917677159002\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(tan(a), -29309106, 'invalid -17', Option::None(())); // -3.493917677159002\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide.cairo",
        "content": "mod core;\nmod math;\nmod helpers;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/core.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::{fixed_point::core::{FixedTrait}, FP8x23};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::{\n    core as core_math, trig, hyp, erf\n};\nuse orion::numbers::fixed_point::utils;\n\n/// A struct representing a fixed point number.\n#[derive(Serde, Copy, Drop)]\nstruct FP8x23W {\n    mag: u64,\n    sign: bool\n}\n\n// CONSTANTS\nconst TWO: u64 = 16777216; // 2 ** 24\nconst ONE: u64 = 8388608; // 2 ** 23\nconst HALF: u64 = 4194304; // 2 ** 22\nconst MAX: u64 = 2147483648; // 2 ** 31\n\nimpl FP8x23WImpl of FixedTrait<FP8x23W, u64> {\n    fn ZERO() -> FP8x23W {\n        FP8x23W { mag: 0, sign: false }\n    }\n\n    fn HALF() -> FP8x23W {\n        FP8x23W { mag: HALF, sign: false }\n    }\n\n    fn ONE() -> FP8x23W {\n        FP8x23W { mag: ONE, sign: false }\n    }\n\n    fn MAX() -> FP8x23W {\n        FP8x23W { mag: MAX, sign: false }\n    }\n\n    fn new(mag: u64, sign: bool) -> FP8x23W {\n        FP8x23W { mag: mag, sign: sign }\n    }\n\n    fn new_unscaled(mag: u64, sign: bool) -> FP8x23W {\n        FP8x23W { mag: mag * ONE, sign: sign }\n    }\n\n    fn from_felt(val: felt252) -> FP8x23W {\n        let mag = core::integer::u64_try_from_felt252(utils::felt_abs(val)).unwrap();\n        FixedTrait::new(mag, utils::felt_sign(val))\n    }\n\n    fn abs(self: FP8x23W) -> FP8x23W {\n        core_math::abs(self)\n    }\n\n    fn acos(self: FP8x23W) -> FP8x23W {\n        trig::acos_fast(self)\n    }\n\n    fn acos_fast(self: FP8x23W) -> FP8x23W {\n        trig::acos_fast(self)\n    }\n\n    fn acosh(self: FP8x23W) -> FP8x23W {\n        hyp::acosh(self)\n    }\n\n    fn asin(self: FP8x23W) -> FP8x23W {\n        trig::asin_fast(self)\n    }\n\n    fn asin_fast(self: FP8x23W) -> FP8x23W {\n        trig::asin_fast(self)\n    }\n\n    fn asinh(self: FP8x23W) -> FP8x23W {\n        hyp::asinh(self)\n    }\n\n    fn atan(self: FP8x23W) -> FP8x23W {\n        trig::atan_fast(self)\n    }\n\n    fn atan_fast(self: FP8x23W) -> FP8x23W {\n        trig::atan_fast(self)\n    }\n\n    fn atanh(self: FP8x23W) -> FP8x23W {\n        hyp::atanh(self)\n    }\n\n    fn ceil(self: FP8x23W) -> FP8x23W {\n        core_math::ceil(self)\n    }\n\n    fn cos(self: FP8x23W) -> FP8x23W {\n        trig::cos_fast(self)\n    }\n\n    fn cos_fast(self: FP8x23W) -> FP8x23W {\n        trig::cos_fast(self)\n    }\n\n    fn cosh(self: FP8x23W) -> FP8x23W {\n        hyp::cosh(self)\n    }\n\n    fn floor(self: FP8x23W) -> FP8x23W {\n        core_math::floor(self)\n    }\n\n    // Calculates the natural exponent of x: e^x\n    fn exp(self: FP8x23W) -> FP8x23W {\n        core_math::exp(self)\n    }\n\n    // Calculates the binary exponent of x: 2^x\n    fn exp2(self: FP8x23W) -> FP8x23W {\n        core_math::exp2(self)\n    }\n\n    // Calculates the natural logarithm of x: ln(x)\n    // self must be greater than zero\n    fn ln(self: FP8x23W) -> FP8x23W {\n        core_math::ln(self)\n    }\n\n    // Calculates the binary logarithm of x: log2(x)\n    // self must be greather than zero\n    fn log2(self: FP8x23W) -> FP8x23W {\n        core_math::log2(self)\n    }\n\n    // Calculates the base 10 log of x: log10(x)\n    // self must be greater than zero\n    fn log10(self: FP8x23W) -> FP8x23W {\n        core_math::log10(self)\n    }\n\n    // Calclates the value of x^y and checks for overflow before returning\n    // self is a fixed point value\n    // b is a fixed point value\n    fn pow(self: FP8x23W, b: FP8x23W) -> FP8x23W {\n        core_math::pow(self, b)\n    }\n\n    fn round(self: FP8x23W) -> FP8x23W {\n        core_math::round(self)\n    }\n\n    fn sin(self: FP8x23W) -> FP8x23W {\n        trig::sin_fast(self)\n    }\n\n    fn sin_fast(self: FP8x23W) -> FP8x23W {\n        trig::sin_fast(self)\n    }\n\n    fn sinh(self: FP8x23W) -> FP8x23W {\n        hyp::sinh(self)\n    }\n\n    // Calculates the square root of a fixed point value\n    // x must be positive\n    fn sqrt(self: FP8x23W) -> FP8x23W {\n        core_math::sqrt(self)\n    }\n\n    fn tan(self: FP8x23W) -> FP8x23W {\n        trig::tan_fast(self)\n    }\n\n    fn tan_fast(self: FP8x23W) -> FP8x23W {\n        trig::tan_fast(self)\n    }\n\n    fn tanh(self: FP8x23W) -> FP8x23W {\n        hyp::tanh(self)\n    }\n\n    fn sign(self: FP8x23W) -> FP8x23W {\n        core_math::sign(self)\n    }\n\n    fn NaN() -> FP8x23W {\n        FP8x23W { mag: 0, sign: true }\n    }\n\n    fn is_nan(self: FP8x23W) -> bool {\n        self == FP8x23W { mag: 0, sign: true }\n    }\n\n    fn INF() -> FP8x23W {\n        FP8x23W { mag: 4294967295, sign: false }\n    }\n\n    fn POS_INF() -> FP8x23W {\n        FP8x23W { mag: 4294967295, sign: false }\n    }\n\n    fn NEG_INF() -> FP8x23W {\n        FP8x23W { mag: 4294967295, sign: true }\n    }\n\n    fn is_inf(self: FP8x23W) -> bool {\n        self.mag == 4294967295\n    }\n\n    fn is_pos_inf(self: FP8x23W) -> bool {\n        self.is_inf() && !self.sign\n    }\n\n    fn is_neg_inf(self: FP8x23W) -> bool {\n        self.is_inf() && self.sign\n    }\n\n    fn erf(self: FP8x23W) -> FP8x23W {\n        erf::erf(self)\n    }\n}\n\n\nimpl FP8x23WPrint of PrintTrait<FP8x23W> {\n    fn print(self: FP8x23W) {\n        self.sign.print();\n        self.mag.print();\n    }\n}\n\n// Into a raw felt without unscaling\nimpl FP8x23WIntoFelt252 of Into<FP8x23W, felt252> {\n    fn into(self: FP8x23W) -> felt252 {\n        let mag_felt = self.mag.into();\n\n        if self.sign {\n            mag_felt * -1\n        } else {\n            mag_felt * 1\n        }\n    }\n}\n\nimpl FP8x23IntoFP8x23W of Into<FP8x23, FP8x23W> {\n    fn into(self: FP8x23) -> FP8x23W {\n        FP8x23W { mag: self.mag.into(), sign: self.sign }\n    }\n}\n\nimpl FP8x23WTryIntoFP8x23 of TryInto<FP8x23W, FP8x23> {\n    fn try_into(self: FP8x23W) -> Option<FP8x23> {\n        match self.mag.try_into() {\n            Option::Some(val) => { Option::Some(FP8x23 { mag: val, sign: self.sign }) },\n            Option::None => { Option::None(()) }\n        }\n    }\n}\n\nimpl FP8x23WTryIntoU128 of TryInto<FP8x23W, u128> {\n    fn try_into(self: FP8x23W) -> Option<u128> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP8x23WTryIntoU64 of TryInto<FP8x23W, u64> {\n    fn try_into(self: FP8x23W) -> Option<u64> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            Option::Some((self.mag / ONE).into())\n        }\n    }\n}\n\nimpl FP8x23WTryIntoU32 of TryInto<FP8x23W, u32> {\n    fn try_into(self: FP8x23W) -> Option<u32> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP8x23WTryIntoU16 of TryInto<FP8x23W, u16> {\n    fn try_into(self: FP8x23W) -> Option<u16> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP8x23WTryIntoU8 of TryInto<FP8x23W, u8> {\n    fn try_into(self: FP8x23W) -> Option<u8> {\n        if self.sign {\n            Option::None(())\n        } else {\n            // Unscale the magnitude and round down\n            (self.mag / ONE).try_into()\n        }\n    }\n}\n\nimpl FP8x23WIntoI32 of Into<FP8x23W, i32> {\n    fn into(self: FP8x23W) -> i32 {\n        _i32_into_fp(self)\n    }\n}\n\nimpl FP8x23WTryIntoI8 of TryInto<FP8x23W, i8> {\n    fn try_into(self: FP8x23W) -> Option<i8> {\n        _i8_try_from_fp(self)\n    }\n}\n\nimpl FP8x23WPartialEq of PartialEq<FP8x23W> {\n    #[inline(always)]\n    fn eq(lhs: @FP8x23W, rhs: @FP8x23W) -> bool {\n        core_math::eq(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn ne(lhs: @FP8x23W, rhs: @FP8x23W) -> bool {\n        core_math::ne(lhs, rhs)\n    }\n}\n\nimpl FP8x23WAdd of Add<FP8x23W> {\n    fn add(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        core_math::add(lhs, rhs)\n    }\n}\n\nimpl FP8x23WAddEq of AddEq<FP8x23W> {\n    #[inline(always)]\n    fn add_eq(ref self: FP8x23W, other: FP8x23W) {\n        self = Add::add(self, other);\n    }\n}\n\nimpl FP8x23WSub of Sub<FP8x23W> {\n    fn sub(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        core_math::sub(lhs, rhs)\n    }\n}\n\nimpl FP8x23WSubEq of SubEq<FP8x23W> {\n    #[inline(always)]\n    fn sub_eq(ref self: FP8x23W, other: FP8x23W) {\n        self = Sub::sub(self, other);\n    }\n}\n\nimpl FP8x23WMul of Mul<FP8x23W> {\n    fn mul(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        core_math::mul(lhs, rhs)\n    }\n}\n\nimpl FP8x23WMulEq of MulEq<FP8x23W> {\n    #[inline(always)]\n    fn mul_eq(ref self: FP8x23W, other: FP8x23W) {\n        self = Mul::mul(self, other);\n    }\n}\n\nimpl FP8x23WDiv of Div<FP8x23W> {\n    fn div(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        core_math::div(lhs, rhs)\n    }\n}\n\nimpl FP8x23WDivEq of DivEq<FP8x23W> {\n    #[inline(always)]\n    fn div_eq(ref self: FP8x23W, other: FP8x23W) {\n        self = Div::div(self, other);\n    }\n}\n\nimpl FP8x23WPartialOrd of PartialOrd<FP8x23W> {\n    #[inline(always)]\n    fn ge(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        core_math::ge(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        core_math::gt(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn le(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        core_math::le(lhs, rhs)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: FP8x23W, rhs: FP8x23W) -> bool {\n        core_math::lt(lhs, rhs)\n    }\n}\n\nimpl FP8x23WNeg of Neg<FP8x23W> {\n    #[inline(always)]\n    fn neg(a: FP8x23W) -> FP8x23W {\n        core_math::neg(a)\n    }\n}\n\nimpl FP8x23WRem of Rem<FP8x23W> {\n    #[inline(always)]\n    fn rem(lhs: FP8x23W, rhs: FP8x23W) -> FP8x23W {\n        core_math::rem(lhs, rhs)\n    }\n}\n\n/// INTERNAL\n\nfn _i32_into_fp(x: FP8x23W) -> i32 {\n    let number_felt: felt252 = (x.mag / ONE).into();\n    let number_i32: i32 = number_felt.try_into().unwrap();\n\n    if x.sign {\n        return number_i32 * -1_i32;\n    }\n\n    number_i32\n}\n\nfn _i8_try_from_fp(x: FP8x23W) -> Option<i8> {\n    let unscaled_mag: Option<u8> = (x.mag / ONE).try_into();\n\n    match unscaled_mag {\n        Option::Some => {\n            let number_felt: felt252 = unscaled_mag.unwrap().into();\n            let mut number_i8: i8 = number_felt.try_into().unwrap();\n\n            if x.sign {\n                return Option::Some(number_i8 * -1_i8);\n            }\n\n            Option::Some(number_i8)\n        },\n        Option::None => Option::None(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/helpers.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    HALF, ONE, TWO, FP8x23W, FP8x23WSub, FP8x23WDiv, FixedTrait, FP8x23WPrint\n};\n\nconst DEFAULT_PRECISION: u64 = 8; // 1e-6\n\n// To use `DEFAULT_PRECISION`, final arg is: `Option::None(())`.\n// To use `custom_precision` of 430_u64: `Option::Some(430_u64)`.\nfn assert_precise(result: FP8x23W, expected: felt252, msg: felt252, custom_precision: Option<u64>) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = (result - FixedTrait::from_felt(expected)).mag;\n\n    if (diff > precision) {\n        result.print();\n        assert(diff <= precision, msg);\n    }\n}\n\nfn assert_relative(\n    result: FP8x23W, expected: felt252, msg: felt252, custom_precision: Option<u64>\n) {\n    let precision = match custom_precision {\n        Option::Some(val) => val,\n        Option::None => DEFAULT_PRECISION,\n    };\n\n    let diff = result - FixedTrait::from_felt(expected);\n    let rel_diff = (diff / result).mag;\n\n    if (rel_diff > precision) {\n        result.print();\n        assert(rel_diff <= precision, msg);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math.cairo",
        "content": "mod core;\nmod comp;\nmod lut;\nmod trig;\nmod hyp;\nmod erf;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/comp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    FP8x23W, FixedTrait, FP8x23WPartialOrd, FP8x23WPartialEq\n};\n\nfn max(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    if a >= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn min(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    if a <= b {\n        a\n    } else {\n        b\n    }\n}\n\nfn xor(a: FP8x23W, b: FP8x23W) -> bool {\n    if (a == FixedTrait::new(0, false) || b == FixedTrait::new(0, false)) && (a != b) {\n        true\n    } else {\n        false\n    }\n}\n\nfn or(a: FP8x23W, b: FP8x23W) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero && b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn and(a: FP8x23W, b: FP8x23W) -> bool {\n    let zero = FixedTrait::new(0, false);\n    if a == zero || b == zero {\n        false\n    } else {\n        true\n    }\n}\n\nfn where(a: FP8x23W, b: FP8x23W, c: FP8x23W) -> FP8x23W {\n    if a == FixedTrait::new(0, false) {\n        c\n    } else {\n        b\n    }\n}\n\nfn bitwise_and(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    FixedTrait::new(a.mag & b.mag, a.sign & b.sign)\n}\n\nfn bitwise_xor(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    FixedTrait::new(a.mag ^ b.mag, a.sign ^ b.sign)\n}\n\nfn bitwise_or(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    FixedTrait::new(a.mag | b.mag, a.sign | b.sign)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use super::{FixedTrait, max, min, bitwise_and, bitwise_xor, bitwise_or};\n\n    #[test]\n    fn test_max() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(max(a, a) == a, 'max(a, a)');\n        assert(max(a, b) == a, 'max(a, b)');\n        assert(max(a, c) == a, 'max(a, c)');\n\n        assert(max(b, a) == a, 'max(b, a)');\n        assert(max(b, b) == b, 'max(b, b)');\n        assert(max(b, c) == b, 'max(b, c)');\n\n        assert(max(c, a) == a, 'max(c, a)');\n        assert(max(c, b) == b, 'max(c, b)');\n        assert(max(c, c) == c, 'max(c, c)');\n    }\n\n    #[test]\n    fn test_min() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::new_unscaled(1, true);\n\n        assert(min(a, a) == a, 'min(a, a)');\n        assert(min(a, b) == b, 'min(a, b)');\n        assert(min(a, c) == c, 'min(a, c)');\n\n        assert(min(b, a) == b, 'min(b, a)');\n        assert(min(b, b) == b, 'min(b, b)');\n        assert(min(b, c) == c, 'min(b, c)');\n\n        assert(min(c, a) == c, 'min(c, a)');\n        assert(min(c, b) == c, 'min(c, b)');\n        assert(min(c, c) == c, 'min(c, c)');\n    }\n\n    #[test]\n    fn test_bitwise_and() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n\n        assert(bitwise_and(a, b) == a, 'bitwise_and(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_xor() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n        let c = FixedTrait::new(1610612736, true);\n\n        assert(bitwise_xor(a, b) == c, 'bitwise_xor(a,b)')\n    }\n\n    #[test]\n    fn test_bitwise_or() {\n        let a = FixedTrait::new(28835840, false); // 3.4375\n        let b = FixedTrait::new(1639448576, true); // -60.5625\n\n        assert(bitwise_or(a, b) == b, 'bitwise_or(a,b)')\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/core.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    HALF, ONE, MAX, FP8x23W, FP8x23WAdd, FP8x23WImpl, FP8x23WAddEq, FP8x23WSub, FP8x23WMul,\n    FP8x23WMulEq, FP8x23WTryIntoU128, FP8x23WPartialEq, FP8x23WPartialOrd, FP8x23WSubEq, FP8x23WNeg,\n    FP8x23WDiv, FP8x23WIntoFelt252, FixedTrait\n};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::lut;\n\n// PUBLIC\nfn abs(a: FP8x23W) -> FP8x23W {\n    FixedTrait::new(a.mag, false)\n}\n\nfn add(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    if a.sign == b.sign {\n        return FixedTrait::new(a.mag + b.mag, a.sign);\n    }\n\n    if a.mag == b.mag {\n        return FixedTrait::ZERO();\n    }\n\n    if (a.mag > b.mag) {\n        return FixedTrait::new(a.mag - b.mag, a.sign);\n    } else {\n        return FixedTrait::new(b.mag - a.mag, b.sign);\n    }\n}\n\nfn ceil(a: FP8x23W) -> FP8x23W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if rem == 0 {\n        return a;\n    } else if !a.sign {\n        return FixedTrait::new_unscaled(div + 1, false);\n    } else if div == 0 {\n        return FixedTrait::new_unscaled(0, false);\n    } else {\n        return FixedTrait::new_unscaled(div, true);\n    }\n}\n\nfn div(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    let a_u64 = integer::u64_wide_mul(a.mag, ONE);\n    let res_u64 = a_u64 / b.mag.into();\n\n    // Re-apply sign\n    FixedTrait::new(res_u64.try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn eq(a: @FP8x23W, b: @FP8x23W) -> bool {\n    (*a.mag == *b.mag) && (*a.sign == *b.sign)\n}\n\n// Calculates the natural exponent of x: e^x\nfn exp(a: FP8x23W) -> FP8x23W {\n    exp2(FixedTrait::new(12102203, false) * a) // log2(e) * 2^23 \u2248 12102203\n}\n\n// Calculates the binary exponent of x: 2^x\nfn exp2(a: FP8x23W) -> FP8x23W {\n    if (a.mag == 0) {\n        return FixedTrait::ONE();\n    }\n\n    let (int_part, frac_part) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n    let int_res = FixedTrait::new_unscaled(lut::exp2(int_part), false);\n    let mut res_u = int_res;\n\n    if frac_part != 0 {\n        let frac = FixedTrait::new(frac_part, false);\n        let r8 = FixedTrait::new(19, false) * frac;\n        let r7 = (r8 + FixedTrait::new(105, false)) * frac;\n        let r6 = (r7 + FixedTrait::new(1324, false)) * frac;\n        let r5 = (r6 + FixedTrait::new(11159, false)) * frac;\n        let r4 = (r5 + FixedTrait::new(80695, false)) * frac;\n        let r3 = (r4 + FixedTrait::new(465599, false)) * frac;\n        let r2 = (r3 + FixedTrait::new(2015166, false)) * frac;\n        let r1 = (r2 + FixedTrait::new(5814540, false)) * frac;\n        res_u = res_u * (r1 + FixedTrait::ONE());\n    }\n\n    if a.sign {\n        FixedTrait::ONE() / res_u\n    } else {\n        res_u\n    }\n}\n\nfn exp2_int(exp: u64) -> FP8x23W {\n    FixedTrait::new_unscaled(lut::exp2(exp), false)\n}\n\nfn floor(a: FP8x23W) -> FP8x23W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if rem == 0 {\n        return a;\n    } else if !a.sign {\n        return FixedTrait::new_unscaled(div, false);\n    } else {\n        return FixedTrait::new_unscaled(div + 1, true);\n    }\n}\n\nfn ge(a: FP8x23W, b: FP8x23W) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn gt(a: FP8x23W, b: FP8x23W) -> bool {\n    if a.sign != b.sign {\n        !a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag > b.mag) ^ a.sign)\n    }\n}\n\nfn le(a: FP8x23W, b: FP8x23W) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag == b.mag) || ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\n// Calculates the natural logarithm of x: ln(x)\n// self must be greater than zero\nfn ln(a: FP8x23W) -> FP8x23W {\n    FixedTrait::new(5814540, false) * log2(a) // ln(2) = 0.693...\n}\n\n// Calculates the binary logarithm of x: log2(x)\n// self must be greather than zero\nfn log2(a: FP8x23W) -> FP8x23W {\n    assert(!a.sign, 'must be positive');\n\n    if (a.mag == ONE) {\n        return FixedTrait::ZERO();\n    } else if (a.mag < ONE) {\n        // Compute true inverse binary log if 0 < x < 1\n        let div = FixedTrait::ONE() / a;\n        return -log2(div);\n    }\n\n    let whole = a.mag / ONE;\n    let (msb, div) = lut::msb(whole);\n\n    if a.mag == div * ONE {\n        FixedTrait::new_unscaled(msb, false)\n    } else {\n        let norm = a / FixedTrait::new_unscaled(div, false);\n        let r8 = FixedTrait::new(76243, true) * norm;\n        let r7 = (r8 + FixedTrait::new(1038893, false)) * norm;\n        let r6 = (r7 + FixedTrait::new(6277679, true)) * norm;\n        let r5 = (r6 + FixedTrait::new(22135645, false)) * norm;\n        let r4 = (r5 + FixedTrait::new(50444339, true)) * norm;\n        let r3 = (r4 + FixedTrait::new(77896489, false)) * norm;\n        let r2 = (r3 + FixedTrait::new(83945943, true)) * norm;\n        let r1 = (r2 + FixedTrait::new(68407458, false)) * norm;\n\n        r1 + FixedTrait::new(28734280, true) + FixedTrait::new_unscaled(msb, false)\n    }\n}\n\n// Calculates the base 10 log of x: log10(x)\n// self must be greater than zero\nfn log10(a: FP8x23W) -> FP8x23W {\n    FixedTrait::new(2525223, false) * log2(a) // log10(2) = 0.301...\n}\n\nfn lt(a: FP8x23W, b: FP8x23W) -> bool {\n    if a.sign != b.sign {\n        a.sign\n    } else {\n        (a.mag != b.mag) && ((a.mag < b.mag) ^ a.sign)\n    }\n}\n\nfn mul(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    let prod_u128 = integer::u64_wide_mul(a.mag, b.mag);\n\n    // Re-apply sign\n    FixedTrait::new((prod_u128 / ONE.into()).try_into().unwrap(), a.sign ^ b.sign)\n}\n\nfn ne(a: @FP8x23W, b: @FP8x23W) -> bool {\n    (*a.mag != *b.mag) || (*a.sign != *b.sign)\n}\n\nfn neg(a: FP8x23W) -> FP8x23W {\n    if a.mag == 0 {\n        a\n    } else if !a.sign {\n        FixedTrait::new(a.mag, !a.sign)\n    } else {\n        FixedTrait::new(a.mag, false)\n    }\n}\n\n// Calclates the value of x^y and checks for overflow before returning\n// self is a FP8x23W point value\n// b is a FP8x23W point value\nfn pow(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    let (_, rem) = integer::u64_safe_divmod(b.mag, integer::u64_as_non_zero(ONE));\n\n    // use the more performant integer pow when y is an int\n    if (rem == 0) {\n        return pow_int(a, b.mag / ONE, b.sign);\n    }\n\n    // x^y = exp(y*ln(x)) for x > 0 will error for x < 0\n    exp(b * ln(a))\n}\n\n// Calclates the value of a^b and checks for overflow before returning\nfn pow_int(a: FP8x23W, b: u64, sign: bool) -> FP8x23W {\n    let mut x = a;\n    let mut n = b;\n\n    if sign {\n        x = FixedTrait::ONE() / x;\n    }\n\n    if n == 0 {\n        return FixedTrait::ONE();\n    }\n\n    let mut y = FixedTrait::ONE();\n    let two = integer::u64_as_non_zero(2);\n\n    while n > 1 {\n        let (div, rem) = integer::u64_safe_divmod(n, two);\n\n        if rem == 1 {\n            y = x * y;\n        }\n\n        x = x * x;\n        n = div;\n    };\n\n    x * y\n}\n\nfn rem(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    a - floor(a / b) * b\n}\n\nfn round(a: FP8x23W) -> FP8x23W {\n    let (div, rem) = integer::u64_safe_divmod(a.mag, integer::u64_as_non_zero(ONE));\n\n    if (HALF <= rem) {\n        FixedTrait::new_unscaled(div + 1, a.sign)\n    } else {\n        FixedTrait::new_unscaled(div, a.sign)\n    }\n}\n\n// Calculates the square root of a FP8x23W point value\n// x must be positive\nfn sqrt(a: FP8x23W) -> FP8x23W {\n    assert(!a.sign, 'must be positive');\n\n    let root = integer::u64_sqrt(a.mag.into() * ONE.into());\n\n    FixedTrait::new(root.into(), false)\n}\n\nfn sub(a: FP8x23W, b: FP8x23W) -> FP8x23W {\n    add(a, -b)\n}\n\nfn sign(a: FP8x23W) -> FP8x23W {\n    if a.mag == 0 {\n        FixedTrait::new(0, false)\n    } else {\n        FixedTrait::new(ONE, a.sign)\n    }\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23wide::helpers::{\n        assert_precise, assert_relative\n    };\n    use orion::numbers::fixed_point::implementations::fp8x23wide::math::trig::{PI, HALF_PI};\n\n    use super::{\n        FixedTrait, ONE, FP8x23W, ceil, floor, sqrt, round, lut, pow, exp, exp2, exp2_int, ln, log2,\n        log10, eq, add, ne, HALF\n    };\n\n    #[test]\n    fn test_into() {\n        let a = FixedTrait::<FP8x23W>::new_unscaled(5, false);\n        assert(a.mag == 5 * ONE, 'invalid result');\n    }\n\n    #[test]\n    fn test_try_into_u128() {\n        // Positive unscaled\n        let a = FixedTrait::<FP8x23W>::new_unscaled(5, false);\n        assert(a.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Positive scaled\n        let b = FixedTrait::<FP8x23W>::new(5 * ONE, false);\n        assert(b.try_into().unwrap() == 5_u128, 'invalid result');\n\n        // Zero\n        let d = FixedTrait::<FP8x23W>::new_unscaled(0, false);\n        assert(d.try_into().unwrap() == 0_u128, 'invalid result');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_negative_try_into_u128() {\n        let a = FixedTrait::<FP8x23W>::new_unscaled(1, true);\n        let _a: u128 = a.try_into().unwrap();\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_acos() {\n        let a = FixedTrait::<FP8x23W>::ONE();\n        assert(a.acos().into() == 0, 'invalid one');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_asin() {\n        let a = FixedTrait::ONE();\n        assert_precise(a.asin(), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(a.atan(), 9287469, 'invalid two', Option::None(()));\n    }\n\n    #[test]\n    fn test_ceil() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(ceil(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_floor() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(floor(a).mag == 2 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    fn test_round() {\n        let a = FixedTrait::new(24326963, false); // 2.9\n        assert(round(a).mag == 3 * ONE, 'invalid pos decimal');\n    }\n\n    #[test]\n    #[should_panic]\n    fn test_sqrt_fail() {\n        let a = FixedTrait::new_unscaled(25, true);\n        sqrt(a);\n    }\n\n    #[test]\n    fn test_sqrt() {\n        let mut a = FixedTrait::new_unscaled(0, false);\n        assert(sqrt(a).mag == 0, 'invalid zero root');\n        a = FixedTrait::new_unscaled(25, false);\n        assert(sqrt(a).mag == 5 * ONE, 'invalid pos root');\n    }\n\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_msb() {\n        let a = FixedTrait::<FP8x23W>::new_unscaled(100, false);\n        let (msb, div) = lut::msb(a.mag / ONE);\n        assert(msb == 6, 'invalid msb');\n        assert(div == 64, 'invalid msb ceil');\n    }\n\n    #[test]\n    #[available_gas(600000)]\n    fn test_pow() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new_unscaled(4, false);\n        assert(pow(a, b).mag == 81 * ONE, 'invalid pos base power');\n    }\n\n    #[test]\n    #[available_gas(900000)]\n    fn test_pow_frac() {\n        let a = FixedTrait::new_unscaled(3, false);\n        let b = FixedTrait::new(4194304, false); // 0.5\n        assert_relative(\n            pow(a, b), 14529495, 'invalid pos base power', Option::None(())\n        ); // 1.7320508075688772\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_exp() {\n        let a = FixedTrait::new_unscaled(2, false);\n        assert_relative(\n            exp(a), 61983895, 'invalid exp of 2', Option::None(())\n        ); // 7.389056098793725\n    }\n\n    #[test]\n    #[available_gas(400000)]\n    fn test_exp2() {\n        let a = FixedTrait::new_unscaled(5, false);\n        assert(exp2(a).mag == 268435456, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(20000)]\n    fn test_exp2_int() {\n        assert(exp2_int(5).into() == 268435456, 'invalid exp2 of 2');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_ln() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        assert(ln(a).mag == 0, 'invalid ln of 1');\n\n        a = FixedTrait::new(22802601, false);\n        assert_relative(ln(a), ONE.into(), 'invalid ln of 2.7...', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log2() {\n        let mut a = FixedTrait::new_unscaled(32, false);\n        assert(log2(a) == FixedTrait::new_unscaled(5, false), 'invalid log2 32');\n\n        a = FixedTrait::new_unscaled(10, false);\n        assert_relative(\n            log2(a), 27866353, 'invalid log2 10', Option::None(())\n        ); // 3.321928094887362\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_log10() {\n        let a = FixedTrait::new_unscaled(100, false);\n        assert_relative(log10(a), 2 * ONE.into(), 'invalid log10', Option::None(()));\n    }\n\n    #[test]\n    fn test_eq() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = eq(@a, @b);\n        assert(c, 'invalid result');\n    }\n\n    #[test]\n    fn test_ne() {\n        let a = FixedTrait::new_unscaled(42, false);\n        let b = FixedTrait::new_unscaled(42, false);\n        let c = ne(@a, @b);\n        assert(!c, 'invalid result');\n    }\n\n    #[test]\n    fn test_add() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        assert(add(a, b) == FixedTrait::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_add_eq() {\n        let mut a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a += b;\n        assert(a == FixedTrait::<FP8x23W>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    fn test_sub() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        let c = a - b;\n        assert(c == FixedTrait::<FP8x23W>::new_unscaled(3, false), 'false result invalid');\n    }\n\n    #[test]\n    fn test_sub_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, false);\n        a -= b;\n        assert(a == FixedTrait::<FP8x23W>::new_unscaled(3, false), 'invalid result');\n    }\n\n    #[test]\n    #[available_gas(100000)]\n    fn test_mul_pos() {\n        let a = FP8x23W { mag: 24326963, sign: false };\n        let b = FP8x23W { mag: 24326963, sign: false };\n        let c = a * b;\n        assert(c.mag == 70548192, 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_neg() {\n        let a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        let c = a * b;\n        assert(c == FixedTrait::<FP8x23W>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_mul_eq() {\n        let mut a = FixedTrait::new_unscaled(5, false);\n        let b = FixedTrait::new_unscaled(2, true);\n        a *= b;\n        assert(a == FixedTrait::<FP8x23W>::new_unscaled(10, true), 'invalid result');\n    }\n\n    #[test]\n    fn test_div() {\n        let a = FixedTrait::new_unscaled(10, false);\n        let b = FixedTrait::<FP8x23W>::new(24326963, false); // 2.9\n        let c = a / b;\n        assert(c.mag == 28926234, 'invalid pos decimal'); // 3.4482758620689653\n    }\n\n    #[test]\n    fn test_le() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23W>::new_unscaled(1, true);\n\n        assert(a <= a, 'a <= a');\n        assert(!(a <= b), 'a <= b');\n        assert(!(a <= c), 'a <= c');\n\n        assert(b <= a, 'b <= a');\n        assert(b <= b, 'b <= b');\n        assert(!(b <= c), 'b <= c');\n\n        assert(c <= a, 'c <= a');\n        assert(c <= b, 'c <= b');\n        assert(c <= c, 'c <= c');\n    }\n\n    #[test]\n    fn test_lt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23W>::new_unscaled(1, true);\n\n        assert(!(a < a), 'a < a');\n        assert(!(a < b), 'a < b');\n        assert(!(a < c), 'a < c');\n\n        assert(b < a, 'b < a');\n        assert(!(b < b), 'b < b');\n        assert(!(b < c), 'b < c');\n\n        assert(c < a, 'c < a');\n        assert(c < b, 'c < b');\n        assert(!(c < c), 'c < c');\n    }\n\n    #[test]\n    fn test_ge() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23W>::new_unscaled(1, true);\n\n        assert(a >= a, 'a >= a');\n        assert(a >= b, 'a >= b');\n        assert(a >= c, 'a >= c');\n\n        assert(!(b >= a), 'b >= a');\n        assert(b >= b, 'b >= b');\n        assert(b >= c, 'b >= c');\n\n        assert(!(c >= a), 'c >= a');\n        assert(!(c >= b), 'c >= b');\n        assert(c >= c, 'c >= c');\n    }\n\n    #[test]\n    fn test_gt() {\n        let a = FixedTrait::new_unscaled(1, false);\n        let b = FixedTrait::new_unscaled(0, false);\n        let c = FixedTrait::<FP8x23W>::new_unscaled(1, true);\n\n        assert(!(a > a), 'a > a');\n        assert(a > b, 'a > b');\n        assert(a > c, 'a > c');\n\n        assert(!(b > a), 'b > a');\n        assert(!(b > b), 'b > b');\n        assert(b > c, 'b > c');\n\n        assert(!(c > a), 'c > a');\n        assert(!(c > b), 'c > b');\n        assert(!(c > c), 'c > c');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_cos() {\n        let a = FixedTrait::<FP8x23W>::new(HALF_PI, false);\n        assert(a.cos().into() == 0, 'invalid half pi');\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(a.sin(), ONE.into(), 'invalid half pi', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_tan() {\n        let a = FixedTrait::<FP8x23W>::new(HALF_PI / 2, false);\n        assert(a.tan().mag == 8388608, 'invalid quarter pi');\n    }\n\n    #[test]\n    #[available_gas(2000000)]\n    fn test_sign() {\n        let a = FixedTrait::<FP8x23W>::new(0, false);\n        assert(a.sign().mag == 0 && !a.sign().sign, 'invalid sign (0, true)');\n\n        let a = FixedTrait::<FP8x23W>::new(HALF, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (HALF, true)');\n\n        let a = FixedTrait::<FP8x23W>::new(HALF, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (HALF, false)');\n\n        let a = FixedTrait::<FP8x23W>::new(ONE, true);\n        assert(a.sign().mag == ONE && a.sign().sign, 'invalid sign (ONE, true)');\n\n        let a = FixedTrait::<FP8x23W>::new(ONE, false);\n        assert(a.sign().mag == ONE && !a.sign().sign, 'invalid sign (ONE, false)');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(2000000)]\n    fn test_sign_fail() {\n        let a = FixedTrait::<FP8x23W>::new(HALF, true);\n        assert(a.sign().mag != ONE && !a.sign().sign, 'invalid sign (HALF, true)');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/erf.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::core::{ONE, FP8x23W, FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::lut::erf_lut;\n\nconst ERF_COMPUTATIONAL_ACCURACY: u64 = 100;\nconst MAX_ERF_COMPUTATIONAL_ACCURACY: u64 = 10;\nconst ROUND_CHECK_NUMBER: u64 = 1;\n// Values > MAX_ERF_NUMBER return 1\nconst MAX_ERF_NUMBER: u64 = 29360128;\n// Values <= ERF_TRUNCATION_NUMBER -> two decimal places, and values > ERF_TRUNCATION_NUMBER -> one decimal place\nconst ERF_TRUNCATION_NUMBER: u64 = 16777216;\n\nfn erf(x: FP8x23W) -> FP8x23W {\n    // Lookup\n    // 1. if x.mag < 3.5 { lookup table }\n    // 2. else{ return 1}\n    let mut erf_value: u64 = 0;\n\n    if x.mag < MAX_ERF_NUMBER {\n        erf_value = erf_lut(x.mag);\n    } else {\n        erf_value = ONE;\n    }\n\n    FP8x23W { mag: erf_value, sign: x.sign }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/hyp.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    HALF, ONE, TWO, FP8x23W, FP8x23WImpl, FP8x23WAdd, FP8x23WAddEq, FP8x23WSub, FP8x23WMul,\n    FP8x23WMulEq, FP8x23WTryIntoU128, FP8x23WPartialEq, FP8x23WPartialOrd, FP8x23WSubEq, FP8x23WNeg,\n    FP8x23WDiv, FP8x23WIntoFelt252, FixedTrait\n};\n\n// Calculates hyperbolic cosine of a (fixed point)\nfn cosh(a: FP8x23W) -> FP8x23W {\n    let ea = a.exp();\n\n    (ea + (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic sine of a (fixed point)\nfn sinh(a: FP8x23W) -> FP8x23W {\n    let ea = a.exp();\n\n    (ea - (FixedTrait::ONE() / ea)) / FixedTrait::new(TWO, false)\n}\n\n// Calculates hyperbolic tangent of a (fixed point)\nfn tanh(a: FP8x23W) -> FP8x23W {\n    let ea = a.exp();\n    let ea_i = FixedTrait::ONE() / ea;\n\n    (ea - ea_i) / (ea + ea_i)\n}\n\n// Calculates inverse hyperbolic cosine of a (fixed point)\nfn acosh(a: FP8x23W) -> FP8x23W {\n    let root = (a * a - FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic sine of a (fixed point)\nfn asinh(a: FP8x23W) -> FP8x23W {\n    let root = (a * a + FixedTrait::ONE()).sqrt();\n\n    (a + root).ln()\n}\n\n// Calculates inverse hyperbolic tangent of a (fixed point)\nfn atanh(a: FP8x23W) -> FP8x23W {\n    let one = FixedTrait::ONE();\n    let ln_arg = (one + a) / (one - a);\n\n    ln_arg.ln() / FixedTrait::new(TWO, false)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23wide::helpers::assert_precise;\n\n    use super::{FixedTrait, TWO, cosh, ONE, sinh, tanh, acosh, asinh, atanh, HALF};\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_cosh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(cosh(a), 31559585, 'invalid two', Option::None(())); // 3.762195691016423\n\n        let a = FixedTrait::ONE();\n        assert_precise(cosh(a), 12944299, 'invalid one', Option::None(())); // 1.5430806347841253\n\n        let a = FixedTrait::ZERO();\n        assert_precise(cosh(a), ONE.into(), 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_precise(\n            cosh(a), 12944299, 'invalid neg one', Option::None(())\n        ); // 1.5430806347841253\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(cosh(a), 31559602, 'invalid neg two', Option::None(())); // 3.762195691016423\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_sinh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(sinh(a), 30424310, 'invalid two', Option::None(())); // 3.6268604077773023\n\n        let a = FixedTrait::ONE();\n        assert_precise(sinh(a), 9858302, 'invalid one', Option::None(())); // 1.1752011936029418\n\n        let a = FixedTrait::ZERO();\n        assert(sinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(\n            sinh(a), -9858302, 'invalid neg one', Option::None(())\n        ); // -1.1752011936029418\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(\n            sinh(a), -30424328, 'invalid neg two', Option::None(())\n        ); // -3.6268604077773023\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_tanh() {\n        let a = FixedTrait::new(TWO, false);\n        assert_precise(tanh(a), 8086849, 'invalid two', Option::None(())); // 0.9640275800745076\n\n        let a = FixedTrait::ONE();\n        assert_precise(tanh(a), 6388715, 'invalid one', Option::None(())); // 0.7615941559446443\n\n        let a = FixedTrait::ZERO();\n        assert(tanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE, true);\n        assert_precise(\n            tanh(a), -6388715, 'invalid neg one', Option::None(())\n        ); // -0.7615941559446443\n\n        let a = FixedTrait::new(TWO, true);\n        assert_precise(\n            tanh(a), -8086849, 'invalid neg two', Option::None(())\n        ); // 0.9640275800745076\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_acosh() {\n        let a = FixedTrait::new(31559585, false); // 3.762195691016423\n        assert_precise(acosh(a), 16777257, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(12944299, false); // 1.5430806347841253\n        assert_precise(acosh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ONE(); // 1\n        assert(acosh(a).into() == 0, 'invalid zero');\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_asinh() {\n        let a = FixedTrait::new(30424310, false); // 3.6268604077773023\n        assert_precise(asinh(a), 16777257, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::new(9858302, false); // 1.1752011936029418\n        assert_precise(asinh(a), ONE.into(), 'invalid one', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(asinh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(9858302, true); // -1.1752011936029418\n        assert_precise(asinh(a), -ONE.into(), 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(30424310, true); // -3.6268604077773023\n        assert_precise(asinh(a), -16777238, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(10000000)]\n    fn test_atanh() {\n        let a = FixedTrait::new(7549747, false); // 0.9\n        assert_precise(atanh(a), 12349872, 'invalid 0.9', Option::None(())); // 1.4722194895832204\n\n        let a = FixedTrait::new(HALF, false); // 0.5\n        assert_precise(atanh(a), 4607914, 'invalid half', Option::None(())); // 0.5493061443340548\n\n        let a = FixedTrait::ZERO();\n        assert(atanh(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(HALF, true); // 0.5\n        assert_precise(\n            atanh(a), -4607914, 'invalid neg half', Option::None(())\n        ); // 0.5493061443340548\n\n        let a = FixedTrait::new(7549747, true); // 0.9\n        assert_precise(atanh(a), -12349872, 'invalid -0.9', Option::None(())); // 1.4722194895832204\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/lut.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::core::ONE;\n\n// Calculates the most significant bit\nfn msb(whole: u64) -> (u64, u64) {\n    if whole < 256 {\n        if whole < 2 {\n            return (0, 1);\n        }\n        if whole < 4 {\n            return (1, 2);\n        }\n        if whole < 8 {\n            return (2, 4);\n        }\n        if whole < 16 {\n            return (3, 8);\n        }\n        if whole < 32 {\n            return (4, 16);\n        }\n        if whole < 64 {\n            return (5, 32);\n        }\n        if whole < 128 {\n            return (6, 64);\n        }\n        if whole < 256 {\n            return (7, 128);\n        }\n    }\n\n    (8, 256)\n}\n\nfn exp2(exp: u64) -> u64 {\n    if exp <= 16 {\n        if exp == 0 {\n            return 1;\n        }\n        if exp == 1 {\n            return 2;\n        }\n        if exp == 2 {\n            return 4;\n        }\n        if exp == 3 {\n            return 8;\n        }\n        if exp == 4 {\n            return 16;\n        }\n        if exp == 5 {\n            return 32;\n        }\n        if exp == 6 {\n            return 64;\n        }\n        if exp == 7 {\n            return 128;\n        }\n        if exp == 8 {\n            return 256;\n        }\n        if exp == 9 {\n            return 512;\n        }\n        if exp == 10 {\n            return 1024;\n        }\n        if exp == 11 {\n            return 2048;\n        }\n        if exp == 12 {\n            return 4096;\n        }\n        if exp == 13 {\n            return 8192;\n        }\n        if exp == 14 {\n            return 16384;\n        }\n        if exp == 15 {\n            return 32768;\n        }\n        if exp == 16 {\n            return 65536;\n        }\n    } else if exp <= 32 {\n        if exp == 17 {\n            return 131072;\n        }\n        if exp == 18 {\n            return 262144;\n        }\n        if exp == 19 {\n            return 524288;\n        }\n        if exp == 20 {\n            return 1048576;\n        }\n        if exp == 21 {\n            return 2097152;\n        }\n        if exp == 22 {\n            return 4194304;\n        }\n    }\n\n    8388608\n}\n\nfn sin(a: u64) -> (u64, u64, u64) {\n    let slot = a / 51472;\n\n    if slot < 128 {\n        if slot < 64 {\n            if slot < 32 {\n                if slot < 16 {\n                    if slot == 0 {\n                        return (0, 0, 51472);\n                    }\n                    if slot == 1 {\n                        return (51472, 51472, 102941);\n                    }\n                    if slot == 2 {\n                        return (102944, 102941, 154407);\n                    }\n                    if slot == 3 {\n                        return (154416, 154407, 205867);\n                    }\n                    if slot == 4 {\n                        return (205887, 205867, 257319);\n                    }\n                    if slot == 5 {\n                        return (257359, 257319, 308761);\n                    }\n                    if slot == 6 {\n                        return (308831, 308761, 360192);\n                    }\n                    if slot == 7 {\n                        return (360303, 360192, 411609);\n                    }\n                    if slot == 8 {\n                        return (411775, 411609, 463011);\n                    }\n                    if slot == 9 {\n                        return (463247, 463011, 514396);\n                    }\n                    if slot == 10 {\n                        return (514723, 514396, 565761);\n                    }\n                    if slot == 11 {\n                        return (566190, 565761, 617104);\n                    }\n                    if slot == 12 {\n                        return (617662, 617104, 668425);\n                    }\n                    if slot == 13 {\n                        return (669134, 668425, 719720);\n                    }\n                    if slot == 14 {\n                        return (720606, 719720, 770988);\n                    }\n                    if slot == 15 {\n                        return (772078, 770988, 822227);\n                    }\n                } else {\n                    if slot == 16 {\n                        return (823550, 822227, 873436);\n                    }\n                    if slot == 17 {\n                        return (875022, 873436, 924611);\n                    }\n                    if slot == 18 {\n                        return (926493, 924611, 975751);\n                    }\n                    if slot == 19 {\n                        return (977965, 975751, 1026855);\n                    }\n                    if slot == 20 {\n                        return (1029437, 1026855, 1077920);\n                    }\n                    if slot == 21 {\n                        return (1080909, 1077920, 1128945);\n                    }\n                    if slot == 22 {\n                        return (1132381, 1128945, 1179927);\n                    }\n                    if slot == 23 {\n                        return (1183853, 1179927, 1230864);\n                    }\n                    if slot == 24 {\n                        return (1235324, 1230864, 1281756);\n                    }\n                    if slot == 25 {\n                        return (1286796, 1281756, 1332599);\n                    }\n                    if slot == 26 {\n                        return (1338268, 1332599, 1383392);\n                    }\n                    if slot == 27 {\n                        return (1389740, 1383392, 1434132);\n                    }\n                    if slot == 28 {\n                        return (1441212, 1434132, 1484819);\n                    }\n                    if slot == 29 {\n                        return (1492684, 1484819, 1535450);\n                    }\n                    if slot == 30 {\n                        return (1544156, 1535450, 1586023);\n                    }\n                    if slot == 31 {\n                        return (1595627, 1586023, 1636536);\n                    }\n                }\n            } else {\n                if slot < 48 {\n                    if slot == 32 {\n                        return (1647099, 1636536, 1686988);\n                    }\n                    if slot == 33 {\n                        return (1698571, 1686988, 1737376);\n                    }\n                    if slot == 34 {\n                        return (1750043, 1737376, 1787699);\n                    }\n                    if slot == 35 {\n                        return (1801515, 1787699, 1837954);\n                    }\n                    if slot == 36 {\n                        return (1852987, 1837954, 1888141);\n                    }\n                    if slot == 37 {\n                        return (1904459, 1888141, 1938256);\n                    }\n                    if slot == 38 {\n                        return (1955930, 1938256, 1988298);\n                    }\n                    if slot == 39 {\n                        return (2007402, 1988298, 2038265);\n                    }\n                    if slot == 40 {\n                        return (2058871, 2038265, 2088156);\n                    }\n                    if slot == 41 {\n                        return (2110346, 2088156, 2137968);\n                    }\n                    if slot == 42 {\n                        return (2161818, 2137968, 2187700);\n                    }\n                    if slot == 43 {\n                        return (2213290, 2187700, 2237349);\n                    }\n                    if slot == 44 {\n                        return (2264762, 2237349, 2286914);\n                    }\n                    if slot == 45 {\n                        return (2316233, 2286914, 2336392);\n                    }\n                    if slot == 46 {\n                        return (2367705, 2336392, 2385783);\n                    }\n                    if slot == 47 {\n                        return (2419177, 2385783, 2435084);\n                    }\n                } else {\n                    if slot == 48 {\n                        return (2470649, 2435084, 2484294);\n                    }\n                    if slot == 49 {\n                        return (2522121, 2484294, 2533410);\n                    }\n                    if slot == 50 {\n                        return (2573593, 2533410, 2582430);\n                    }\n                    if slot == 51 {\n                        return (2625065, 2582430, 2631353);\n                    }\n                    if slot == 52 {\n                        return (2676536, 2631353, 2680177);\n                    }\n                    if slot == 53 {\n                        return (2728008, 2680177, 2728901);\n                    }\n                    if slot == 54 {\n                        return (2779480, 2728901, 2777521);\n                    }\n                    if slot == 55 {\n                        return (2830952, 2777521, 2826037);\n                    }\n                    if slot == 56 {\n                        return (2882424, 2826037, 2874446);\n                    }\n                    if slot == 57 {\n                        return (2933896, 2874446, 2922748);\n                    }\n                    if slot == 58 {\n                        return (2985368, 2922748, 2970939);\n                    }\n                    if slot == 59 {\n                        return (3036839, 2970939, 3019018);\n                    }\n                    if slot == 60 {\n                        return (3088311, 3019018, 3066984);\n                    }\n                    if slot == 61 {\n                        return (3139783, 3066984, 3114834);\n                    }\n                    if slot == 62 {\n                        return (3191255, 3114834, 3162567);\n                    }\n                    if slot == 63 {\n                        return (3242727, 3162567, 3210181);\n                    }\n                }\n            }\n        } else {\n            if slot < 96 {\n                if slot < 80 {\n                    if slot == 64 {\n                        return (3294199, 3210181, 3257674);\n                    }\n                    if slot == 65 {\n                        return (3345671, 3257674, 3305045);\n                    }\n                    if slot == 66 {\n                        return (3397142, 3305045, 3352291);\n                    }\n                    if slot == 67 {\n                        return (3448614, 3352291, 3399411);\n                    }\n                    if slot == 68 {\n                        return (3500086, 3399411, 3446402);\n                    }\n                    if slot == 69 {\n                        return (3551558, 3446402, 3493264);\n                    }\n                    if slot == 70 {\n                        return (3603030, 3493264, 3539995);\n                    }\n                    if slot == 71 {\n                        return (3654502, 3539995, 3586592);\n                    }\n                    if slot == 72 {\n                        return (3705973, 3586592, 3633054);\n                    }\n                    if slot == 73 {\n                        return (3757445, 3633054, 3679380);\n                    }\n                    if slot == 74 {\n                        return (3808917, 3679380, 3725567);\n                    }\n                    if slot == 75 {\n                        return (3860389, 3725567, 3771613);\n                    }\n                    if slot == 76 {\n                        return (3911861, 3771613, 3817518);\n                    }\n                    if slot == 77 {\n                        return (3963333, 3817518, 3863279);\n                    }\n                    if slot == 78 {\n                        return (4014805, 3863279, 3908894);\n                    }\n                    if slot == 79 {\n                        return (4066276, 3908894, 3954362);\n                    }\n                } else {\n                    if slot == 80 {\n                        return (4117751, 3954362, 3999682);\n                    }\n                    if slot == 81 {\n                        return (4169220, 3999682, 4044851);\n                    }\n                    if slot == 82 {\n                        return (4220692, 4044851, 4089867);\n                    }\n                    if slot == 83 {\n                        return (4272164, 4089867, 4134730);\n                    }\n                    if slot == 84 {\n                        return (4323636, 4134730, 4179437);\n                    }\n                    if slot == 85 {\n                        return (4375108, 4179437, 4223986);\n                    }\n                    if slot == 86 {\n                        return (4426579, 4223986, 4268377);\n                    }\n                    if slot == 87 {\n                        return (4478051, 4268377, 4312606);\n                    }\n                    if slot == 88 {\n                        return (4529523, 4312606, 4356674);\n                    }\n                    if slot == 89 {\n                        return (4580995, 4356674, 4400577);\n                    }\n                    if slot == 90 {\n                        return (4632474, 4400577, 4444315);\n                    }\n                    if slot == 91 {\n                        return (4683939, 4444315, 4487885);\n                    }\n                    if slot == 92 {\n                        return (4735411, 4487885, 4531287);\n                    }\n                    if slot == 93 {\n                        return (4786882, 4531287, 4574518);\n                    }\n                    if slot == 94 {\n                        return (4838354, 4574518, 4617576);\n                    }\n                    if slot == 95 {\n                        return (4889826, 4617576, 4660461);\n                    }\n                }\n            } else {\n                if slot < 112 {\n                    if slot == 96 {\n                        return (4941298, 4660461, 4703170);\n                    }\n                    if slot == 97 {\n                        return (4992770, 4703170, 4745702);\n                    }\n                    if slot == 98 {\n                        return (5044242, 4745702, 4788056);\n                    }\n                    if slot == 99 {\n                        return (5095714, 4788056, 4830229);\n                    }\n                    if slot == 100 {\n                        return (5147227, 4830229, 4872221);\n                    }\n                    if slot == 101 {\n                        return (5198657, 4872221, 4914029);\n                    }\n                    if slot == 102 {\n                        return (5250129, 4914029, 4955652);\n                    }\n                    if slot == 103 {\n                        return (5301601, 4955652, 4997088);\n                    }\n                    if slot == 104 {\n                        return (5353073, 4997088, 5038336);\n                    }\n                    if slot == 105 {\n                        return (5404545, 5038336, 5079395);\n                    }\n                    if slot == 106 {\n                        return (5456017, 5079395, 5120262);\n                    }\n                    if slot == 107 {\n                        return (5507488, 5120262, 5160937);\n                    }\n                    if slot == 108 {\n                        return (5558960, 5160937, 5201417);\n                    }\n                    if slot == 109 {\n                        return (5610432, 5201417, 5241701);\n                    }\n                    if slot == 110 {\n                        return (5661904, 5241701, 5281788);\n                    }\n                    if slot == 111 {\n                        return (5713376, 5281788, 5321677);\n                    }\n                } else {\n                    if slot == 112 {\n                        return (5764848, 5321677, 5361364);\n                    }\n                    if slot == 113 {\n                        return (5816320, 5361364, 5400850);\n                    }\n                    if slot == 114 {\n                        return (5867791, 5400850, 5440133);\n                    }\n                    if slot == 115 {\n                        return (5919263, 5440133, 5479211);\n                    }\n                    if slot == 116 {\n                        return (5970735, 5479211, 5518082);\n                    }\n                    if slot == 117 {\n                        return (6022207, 5518082, 5556746);\n                    }\n                    if slot == 118 {\n                        return (6073679, 5556746, 5595201);\n                    }\n                    if slot == 119 {\n                        return (6125151, 5595201, 5633445);\n                    }\n                    if slot == 120 {\n                        return (6176622, 5633445, 5671477);\n                    }\n                    if slot == 121 {\n                        return (6228094, 5671477, 5709295);\n                    }\n                    if slot == 122 {\n                        return (6279566, 5709295, 5746898);\n                    }\n                    if slot == 123 {\n                        return (6331038, 5746898, 5784285);\n                    }\n                    if slot == 124 {\n                        return (6382510, 5784285, 5821455);\n                    }\n                    if slot == 125 {\n                        return (6433982, 5821455, 5858405);\n                    }\n                    if slot == 126 {\n                        return (6485454, 5858405, 5895134);\n                    }\n                    if slot == 127 {\n                        return (6536925, 5895134, 5931642);\n                    }\n                }\n            }\n        }\n    } else {\n        if slot < 192 {\n            if slot < 160 {\n                if slot < 144 {\n                    if slot == 128 {\n                        return (6588397, 5931642, 5967926);\n                    }\n                    if slot == 129 {\n                        return (6639869, 5967926, 6003985);\n                    }\n                    if slot == 130 {\n                        return (6691345, 6003985, 6039819);\n                    }\n                    if slot == 131 {\n                        return (6742813, 6039819, 6075425);\n                    }\n                    if slot == 132 {\n                        return (6794285, 6075425, 6110802);\n                    }\n                    if slot == 133 {\n                        return (6845757, 6110802, 6145949);\n                    }\n                    if slot == 134 {\n                        return (6897228, 6145949, 6180865);\n                    }\n                    if slot == 135 {\n                        return (6948700, 6180865, 6215549);\n                    }\n                    if slot == 136 {\n                        return (7000172, 6215549, 6249998);\n                    }\n                    if slot == 137 {\n                        return (7051644, 6249998, 6284212);\n                    }\n                    if slot == 138 {\n                        return (7103116, 6284212, 6318189);\n                    }\n                    if slot == 139 {\n                        return (7154588, 6318189, 6351928);\n                    }\n                    if slot == 140 {\n                        return (7206060, 6351928, 6385428);\n                    }\n                    if slot == 141 {\n                        return (7257531, 6385428, 6418688);\n                    }\n                    if slot == 142 {\n                        return (7309003, 6418688, 6451706);\n                    }\n                    if slot == 143 {\n                        return (7360475, 6451706, 6484482);\n                    }\n                } else {\n                    if slot == 144 {\n                        return (7411947, 6484482, 6517013);\n                    }\n                    if slot == 145 {\n                        return (7463419, 6517013, 6549299);\n                    }\n                    if slot == 146 {\n                        return (7514891, 6549299, 6581338);\n                    }\n                    if slot == 147 {\n                        return (7566363, 6581338, 6613129);\n                    }\n                    if slot == 148 {\n                        return (7617834, 6613129, 6644672);\n                    }\n                    if slot == 149 {\n                        return (7669306, 6644672, 6675964);\n                    }\n                    if slot == 150 {\n                        return (7720780, 6675964, 6707005);\n                    }\n                    if slot == 151 {\n                        return (7772250, 6707005, 6737793);\n                    }\n                    if slot == 152 {\n                        return (7823722, 6737793, 6768328);\n                    }\n                    if slot == 153 {\n                        return (7875194, 6768328, 6798608);\n                    }\n                    if slot == 154 {\n                        return (7926666, 6798608, 6828632);\n                    }\n                    if slot == 155 {\n                        return (7978137, 6828632, 6858399);\n                    }\n                    if slot == 156 {\n                        return (8029609, 6858399, 6887907);\n                    }\n                    if slot == 157 {\n                        return (8081081, 6887907, 6917156);\n                    }\n                    if slot == 158 {\n                        return (8132553, 6917156, 6946145);\n                    }\n                    if slot == 159 {\n                        return (8184025, 6946145, 6974873);\n                    }\n                    if slot == 160 {\n                        return (8235503, 6974873, 7003337);\n                    }\n                }\n            } else {\n                if slot < 176 {\n                    if slot == 161 {\n                        return (8286968, 7003337, 7031538);\n                    }\n                    if slot == 162 {\n                        return (8338440, 7031538, 7059475);\n                    }\n                    if slot == 163 {\n                        return (8389912, 7059475, 7087145);\n                    }\n                    if slot == 164 {\n                        return (8441384, 7087145, 7114549);\n                    }\n                    if slot == 165 {\n                        return (8492856, 7114549, 7141685);\n                    }\n                    if slot == 166 {\n                        return (8544328, 7141685, 7168552);\n                    }\n                    if slot == 167 {\n                        return (8595800, 7168552, 7195149);\n                    }\n                    if slot == 168 {\n                        return (8647271, 7195149, 7221475);\n                    }\n                    if slot == 169 {\n                        return (8698743, 7221475, 7247530);\n                    }\n                    if slot == 170 {\n                        return (8750215, 7247530, 7273311);\n                    }\n                    if slot == 171 {\n                        return (8801687, 7273311, 7298819);\n                    }\n                    if slot == 172 {\n                        return (8853159, 7298819, 7324052);\n                    }\n                    if slot == 173 {\n                        return (8904631, 7324052, 7349009);\n                    }\n                    if slot == 174 {\n                        return (8956103, 7349009, 7373689);\n                    }\n                    if slot == 175 {\n                        return (9007574, 7373689, 7398092);\n                    }\n                } else {\n                    if slot == 176 {\n                        return (9059046, 7398092, 7422216);\n                    }\n                    if slot == 177 {\n                        return (9110518, 7422216, 7446061);\n                    }\n                    if slot == 178 {\n                        return (9161990, 7446061, 7469625);\n                    }\n                    if slot == 179 {\n                        return (9213462, 7469625, 7492909);\n                    }\n                    if slot == 180 {\n                        return (9264934, 7492909, 7515910);\n                    }\n                    if slot == 181 {\n                        return (9316406, 7515910, 7538628);\n                    }\n                    if slot == 182 {\n                        return (9367877, 7538628, 7561062);\n                    }\n                    if slot == 183 {\n                        return (9419349, 7561062, 7583212);\n                    }\n                    if slot == 184 {\n                        return (9470821, 7583212, 7605076);\n                    }\n                    if slot == 185 {\n                        return (9522293, 7605076, 7626654);\n                    }\n                    if slot == 186 {\n                        return (9573765, 7626654, 7647945);\n                    }\n                    if slot == 187 {\n                        return (9625237, 7647945, 7668947);\n                    }\n                    if slot == 188 {\n                        return (9676709, 7668947, 7689661);\n                    }\n                    if slot == 189 {\n                        return (9728180, 7689661, 7710086);\n                    }\n                    if slot == 190 {\n                        return (9779651, 7710086, 7730220);\n                    }\n                    if slot == 191 {\n                        return (9831124, 7730220, 7750063);\n                    }\n                }\n            }\n        } else {\n            if slot < 224 {\n                if slot < 208 {\n                    if slot == 192 {\n                        return (9882596, 7750063, 7769615);\n                    }\n                    if slot == 193 {\n                        return (9934068, 7769615, 7788874);\n                    }\n                    if slot == 194 {\n                        return (9985540, 7788874, 7807839);\n                    }\n                    if slot == 195 {\n                        return (10037012, 7807839, 7826511);\n                    }\n                    if slot == 196 {\n                        return (10088483, 7826511, 7844888);\n                    }\n                    if slot == 197 {\n                        return (10139955, 7844888, 7862970);\n                    }\n                    if slot == 198 {\n                        return (10191427, 7862970, 7880755);\n                    }\n                    if slot == 199 {\n                        return (10242899, 7880755, 7898244);\n                    }\n                    if slot == 200 {\n                        return (10294373, 7898244, 7915436);\n                    }\n                    if slot == 201 {\n                        return (10345843, 7915436, 7932329);\n                    }\n                    if slot == 202 {\n                        return (10397315, 7932329, 7948924);\n                    }\n                    if slot == 203 {\n                        return (10448786, 7948924, 7965220);\n                    }\n                    if slot == 204 {\n                        return (10500258, 7965220, 7981215);\n                    }\n                    if slot == 205 {\n                        return (10551730, 7981215, 7996911);\n                    }\n                    if slot == 206 {\n                        return (10603202, 7996911, 8012305);\n                    }\n                    if slot == 207 {\n                        return (10654674, 8012305, 8027397);\n                    }\n                } else {\n                    if slot == 208 {\n                        return (10706146, 8027397, 8042188);\n                    }\n                    if slot == 209 {\n                        return (10757617, 8042188, 8056675);\n                    }\n                    if slot == 210 {\n                        return (10809089, 8056675, 8070859);\n                    }\n                    if slot == 211 {\n                        return (10860561, 8070859, 8084740);\n                    }\n                    if slot == 212 {\n                        return (10912033, 8084740, 8098316);\n                    }\n                    if slot == 213 {\n                        return (10963505, 8098316, 8111587);\n                    }\n                    if slot == 214 {\n                        return (11014977, 8111587, 8124552);\n                    }\n                    if slot == 215 {\n                        return (11066449, 8124552, 8137212);\n                    }\n                    if slot == 216 {\n                        return (11117920, 8137212, 8149565);\n                    }\n                    if slot == 217 {\n                        return (11169392, 8149565, 8161612);\n                    }\n                    if slot == 218 {\n                        return (11220864, 8161612, 8173351);\n                    }\n                    if slot == 219 {\n                        return (11272336, 8173351, 8184783);\n                    }\n                    if slot == 220 {\n                        return (11323808, 8184783, 8195906);\n                    }\n                    if slot == 221 {\n                        return (11375280, 8195906, 8206721);\n                    }\n                    if slot == 222 {\n                        return (11426752, 8206721, 8217227);\n                    }\n                    if slot == 223 {\n                        return (11478223, 8217227, 8227423);\n                    }\n                }\n            } else {\n                if slot < 240 {\n                    if slot == 224 {\n                        return (11529695, 8227423, 8237310);\n                    }\n                    if slot == 225 {\n                        return (11581167, 8237310, 8246887);\n                    }\n                    if slot == 226 {\n                        return (11632639, 8246887, 8256153);\n                    }\n                    if slot == 227 {\n                        return (11684111, 8256153, 8265108);\n                    }\n                    if slot == 228 {\n                        return (11735583, 8265108, 8273752);\n                    }\n                    if slot == 229 {\n                        return (11787055, 8273752, 8282085);\n                    }\n                    if slot == 230 {\n                        return (11838531, 8282085, 8290105);\n                    }\n                    if slot == 231 {\n                        return (11889998, 8290105, 8297814);\n                    }\n                    if slot == 232 {\n                        return (11941470, 8297814, 8305210);\n                    }\n                    if slot == 233 {\n                        return (11992942, 8305210, 8312294);\n                    }\n                    if slot == 234 {\n                        return (12044414, 8312294, 8319064);\n                    }\n                    if slot == 235 {\n                        return (12095886, 8319064, 8325522);\n                    }\n                    if slot == 236 {\n                        return (12147358, 8325522, 8331666);\n                    }\n                    if slot == 237 {\n                        return (12198829, 8331666, 8337496);\n                    }\n                    if slot == 238 {\n                        return (12250301, 8337496, 8343012);\n                    }\n                    if slot == 239 {\n                        return (12301773, 8343012, 8348215);\n                    }\n                } else {\n                    if slot == 240 {\n                        return (12353244, 8348215, 8353102);\n                    }\n                    if slot == 241 {\n                        return (12404717, 8353102, 8357676);\n                    }\n                    if slot == 242 {\n                        return (12456189, 8357676, 8361935);\n                    }\n                    if slot == 243 {\n                        return (12507661, 8361935, 8365879);\n                    }\n                    if slot == 244 {\n                        return (12559132, 8365879, 8369508);\n                    }\n                    if slot == 245 {\n                        return (12610604, 8369508, 8372822);\n                    }\n                    if slot == 246 {\n                        return (12662076, 8372822, 8375820);\n                    }\n                    if slot == 247 {\n                        return (12713548, 8375820, 8378504);\n                    }\n                    if slot == 248 {\n                        return (12765020, 8378504, 8380871);\n                    }\n                    if slot == 249 {\n                        return (12816492, 8380871, 8382924);\n                    }\n                    if slot == 250 {\n                        return (12867964, 8382924, 8384660);\n                    }\n                    if slot == 251 {\n                        return (12919435, 8384660, 8386082);\n                    }\n                    if slot == 252 {\n                        return (12970907, 8386082, 8387187);\n                    }\n                    if slot == 253 {\n                        return (13022379, 8387187, 8387976);\n                    }\n                    if slot == 254 {\n                        return (13073851, 8387976, 8388450);\n                    }\n                }\n            }\n        }\n    }\n\n    (13125323, 8388450, 8388608)\n}\n\nfn atan(a: u64) -> (u64, u64, u64) {\n    let slot = a / 58720;\n\n    if slot == 0 {\n        return (0, 0, 58719);\n    }\n    if slot == 1 {\n        return (58720, 58719, 117433);\n    }\n    if slot == 2 {\n        return (117441, 117433, 176135);\n    }\n    if slot == 3 {\n        return (176161, 176135, 234820);\n    }\n    if slot == 4 {\n        return (234881, 234820, 293481);\n    }\n    if slot == 5 {\n        return (293601, 293481, 352115);\n    }\n    if slot == 6 {\n        return (352322, 352115, 410713);\n    }\n    if slot == 7 {\n        return (411042, 410713, 469272);\n    }\n    if slot == 8 {\n        return (469762, 469272, 527785);\n    }\n    if slot == 9 {\n        return (528482, 527785, 586246);\n    }\n    if slot == 10 {\n        return (587201, 586246, 644651);\n    }\n    if slot == 11 {\n        return (645923, 644651, 702993);\n    }\n    if slot == 12 {\n        return (704643, 702993, 761267);\n    }\n    if slot == 13 {\n        return (763363, 761267, 819467);\n    }\n    if slot == 14 {\n        return (822084, 819467, 877588);\n    }\n    if slot == 15 {\n        return (880804, 877588, 935625);\n    }\n    if slot == 16 {\n        return (939524, 935625, 993572);\n    }\n    if slot == 17 {\n        return (998244, 993572, 1051424);\n    }\n    if slot == 18 {\n        return (1056965, 1051424, 1109175);\n    }\n    if slot == 19 {\n        return (1115685, 1109175, 1166821);\n    }\n    if slot == 20 {\n        return (1174411, 1166821, 1224357);\n    }\n    if slot == 21 {\n        return (1233125, 1224357, 1281776);\n    }\n    if slot == 22 {\n        return (1291846, 1281776, 1339075);\n    }\n    if slot == 23 {\n        return (1350566, 1339075, 1396248);\n    }\n    if slot == 24 {\n        return (1409286, 1396248, 1453290);\n    }\n    if slot == 25 {\n        return (1468006, 1453290, 1510197);\n    }\n    if slot == 26 {\n        return (1526727, 1510197, 1566964);\n    }\n    if slot == 27 {\n        return (1585447, 1566964, 1623585);\n    }\n    if slot == 28 {\n        return (1644167, 1623585, 1680058);\n    }\n    if slot == 29 {\n        return (1702887, 1680058, 1736376);\n    }\n    if slot == 30 {\n        return (1761612, 1736376, 1792537);\n    }\n    if slot == 31 {\n        return (1820328, 1792537, 1848534);\n    }\n    if slot == 32 {\n        return (1879048, 1848534, 1904364);\n    }\n    if slot == 33 {\n        return (1937768, 1904364, 1960024);\n    }\n    if slot == 34 {\n        return (1996489, 1960024, 2015508);\n    }\n    if slot == 35 {\n        return (2055209, 2015508, 2070813);\n    }\n    if slot == 36 {\n        return (2113929, 2070813, 2125935);\n    }\n    if slot == 37 {\n        return (2172649, 2125935, 2180869);\n    }\n    if slot == 38 {\n        return (2231370, 2180869, 2235613);\n    }\n    if slot == 39 {\n        return (2290090, 2235613, 2290163);\n    }\n    if slot == 40 {\n        return (2348813, 2290163, 2344515);\n    }\n    if slot == 41 {\n        return (2407530, 2344515, 2398665);\n    }\n    if slot == 42 {\n        return (2466251, 2398665, 2452611);\n    }\n    if slot == 43 {\n        return (2524971, 2452611, 2506348);\n    }\n    if slot == 44 {\n        return (2583691, 2506348, 2559875);\n    }\n    if slot == 45 {\n        return (2642412, 2559875, 2613187);\n    }\n    if slot == 46 {\n        return (2701132, 2613187, 2666281);\n    }\n    if slot == 47 {\n        return (2759852, 2666281, 2719156);\n    }\n    if slot == 48 {\n        return (2818572, 2719156, 2771807);\n    }\n    if slot == 49 {\n        return (2877293, 2771807, 2824233);\n    }\n    if slot == 50 {\n        return (2936014, 2824233, 2876431);\n    }\n    if slot == 51 {\n        return (2994733, 2876431, 2928397);\n    }\n    if slot == 52 {\n        return (3053453, 2928397, 2980130);\n    }\n    if slot == 53 {\n        return (3112174, 2980130, 3031628);\n    }\n    if slot == 54 {\n        return (3170894, 3031628, 3082888);\n    }\n    if slot == 55 {\n        return (3229614, 3082888, 3133907);\n    }\n    if slot == 56 {\n        return (3288334, 3133907, 3184685);\n    }\n    if slot == 57 {\n        return (3347055, 3184685, 3235218);\n    }\n    if slot == 58 {\n        return (3405775, 3235218, 3285506);\n    }\n    if slot == 59 {\n        return (3464495, 3285506, 3335545);\n    }\n    if slot == 60 {\n        return (3523224, 3335545, 3385336);\n    }\n    if slot == 61 {\n        return (3581936, 3385336, 3434875);\n    }\n    if slot == 62 {\n        return (3640656, 3434875, 3484161);\n    }\n    if slot == 63 {\n        return (3699376, 3484161, 3533193);\n    }\n    if slot == 64 {\n        return (3758096, 3533193, 3581970);\n    }\n    if slot == 65 {\n        return (3816817, 3581970, 3630491);\n    }\n    if slot == 66 {\n        return (3875537, 3630491, 3678753);\n    }\n    if slot == 67 {\n        return (3934257, 3678753, 3726756);\n    }\n    if slot == 68 {\n        return (3992977, 3726756, 3774499);\n    }\n    if slot == 69 {\n        return (4051698, 3774499, 3821981);\n    }\n    if slot == 70 {\n        return (4110418, 3821981, 3869201);\n    }\n    if slot == 71 {\n        return (4169138, 3869201, 3916159);\n    }\n    if slot == 72 {\n        return (4227858, 3916159, 3962853);\n    }\n    if slot == 73 {\n        return (4286579, 3962853, 4009282);\n    }\n    if slot == 74 {\n        return (4345299, 4009282, 4055447);\n    }\n    if slot == 75 {\n        return (4404019, 4055447, 4101347);\n    }\n    if slot == 76 {\n        return (4462739, 4101347, 4146981);\n    }\n    if slot == 77 {\n        return (4521460, 4146981, 4192350);\n    }\n    if slot == 78 {\n        return (4580180, 4192350, 4237451);\n    }\n    if slot == 79 {\n        return (4638900, 4237451, 4282286);\n    }\n    if slot == 80 {\n        return (4697620, 4282286, 4326855);\n    }\n    if slot == 81 {\n        return (4756341, 4326855, 4371156);\n    }\n    if slot == 82 {\n        return (4815061, 4371156, 4415191);\n    }\n    if slot == 83 {\n        return (4873781, 4415191, 4458958);\n    }\n    if slot == 84 {\n        return (4932502, 4458958, 4502459);\n    }\n    if slot == 85 {\n        return (4991222, 4502459, 4545693);\n    }\n    if slot == 86 {\n        return (5049942, 4545693, 4588660);\n    }\n    if slot == 87 {\n        return (5108662, 4588660, 4631361);\n    }\n    if slot == 88 {\n        return (5167383, 4631361, 4673795);\n    }\n    if slot == 89 {\n        return (5226103, 4673795, 4715964);\n    }\n    if slot == 90 {\n        return (5284823, 4715964, 4757868);\n    }\n    if slot == 91 {\n        return (5343543, 4757868, 4799506);\n    }\n    if slot == 92 {\n        return (5402264, 4799506, 4840880);\n    }\n    if slot == 93 {\n        return (5460984, 4840880, 4881990);\n    }\n    if slot == 94 {\n        return (5519704, 4881990, 4922837);\n    }\n    if slot == 95 {\n        return (5578424, 4922837, 4963420);\n    }\n    if slot == 96 {\n        return (5637145, 4963420, 5003742);\n    }\n    if slot == 97 {\n        return (5695865, 5003742, 5043802);\n    }\n    if slot == 98 {\n        return (5754585, 5043802, 5083601);\n    }\n\n    (5813305, 5083601, 5123141)\n}\n\nfn erf_lut(x: u64) -> u64 {\n    // Construct the erf lookup table\n    if x <= 754974 {\n        if x <= 0 {\n            return 0;\n        }\n        if x <= 83886 {\n            return 94652;\n        }\n        if x <= 167772 {\n            return 189285;\n        }\n        if x <= 251658 {\n            return 283880;\n        }\n        if x <= 335544 {\n            return 378419;\n        }\n        if x <= 419430 {\n            return 472882;\n        }\n        if x <= 503316 {\n            return 567251;\n        }\n        if x <= 587202 {\n            return 661506;\n        }\n        if x <= 671088 {\n            return 755630;\n        }\n        if x <= 754974 {\n            return 849603;\n        }\n    }\n    if x <= 1593835 {\n        if x <= 838860 {\n            return 943407;\n        }\n        if x <= 922746 {\n            return 1037024;\n        }\n        if x <= 1006632 {\n            return 1130434;\n        }\n        if x <= 1090519 {\n            return 1223622;\n        }\n        if x <= 1174405 {\n            return 1316567;\n        }\n        if x <= 1258291 {\n            return 1409252;\n        }\n        if x <= 1342177 {\n            return 1501659;\n        }\n        if x <= 1426063 {\n            return 1593772;\n        }\n        if x <= 1509949 {\n            return 1685571;\n        }\n        if x <= 1593835 {\n            return 1777041;\n        }\n    }\n    if x <= 2432696 {\n        if x <= 1677721 {\n            return 1868164;\n        }\n        if x <= 1761607 {\n            return 1958923;\n        }\n        if x <= 1845493 {\n            return 2049302;\n        }\n        if x <= 1929379 {\n            return 2139284;\n        }\n        if x <= 2013265 {\n            return 2228853;\n        }\n        if x <= 2097152 {\n            return 2317993;\n        }\n        if x <= 2181038 {\n            return 2406689;\n        }\n        if x <= 2264924 {\n            return 2494924;\n        }\n        if x <= 2348810 {\n            return 2582685;\n        }\n        if x <= 2432696 {\n            return 2669955;\n        }\n    }\n    if x <= 3271557 {\n        if x <= 2516582 {\n            return 2756721;\n        }\n        if x <= 2600468 {\n            return 2842967;\n        }\n        if x <= 2684354 {\n            return 2928681;\n        }\n        if x <= 2768240 {\n            return 3013847;\n        }\n        if x <= 2852126 {\n            return 3098454;\n        }\n        if x <= 2936012 {\n            return 3182487;\n        }\n        if x <= 3019898 {\n            return 3265934;\n        }\n        if x <= 3103784 {\n            return 3348782;\n        }\n        if x <= 3187671 {\n            return 3431019;\n        }\n        if x <= 3271557 {\n            return 3512634;\n        }\n    }\n    if x <= 4110417 {\n        if x <= 3355443 {\n            return 3593615;\n        }\n        if x <= 3439329 {\n            return 3673951;\n        }\n        if x <= 3523215 {\n            return 3753630;\n        }\n        if x <= 3607101 {\n            return 3832643;\n        }\n        if x <= 3690987 {\n            return 3910979;\n        }\n        if x <= 3774873 {\n            return 3988629;\n        }\n        if x <= 3858759 {\n            return 4065584;\n        }\n        if x <= 3942645 {\n            return 4141833;\n        }\n        if x <= 4026531 {\n            return 4217369;\n        }\n        if x <= 4110417 {\n            return 4292184;\n        }\n    }\n    if x <= 4949278 {\n        if x <= 4194304 {\n            return 4366269;\n        }\n        if x <= 4278190 {\n            return 4439617;\n        }\n        if x <= 4362076 {\n            return 4512220;\n        }\n        if x <= 4445962 {\n            return 4584073;\n        }\n        if x <= 4529848 {\n            return 4655167;\n        }\n        if x <= 4613734 {\n            return 4725498;\n        }\n        if x <= 4697620 {\n            return 4795060;\n        }\n        if x <= 4781506 {\n            return 4863847;\n        }\n        if x <= 4865392 {\n            return 4931854;\n        }\n        if x <= 4949278 {\n            return 4999077;\n        }\n    }\n    if x <= 5788139 {\n        if x <= 5033164 {\n            return 5065512;\n        }\n        if x <= 5117050 {\n            return 5131153;\n        }\n        if x <= 5200936 {\n            return 5195999;\n        }\n        if x <= 5284823 {\n            return 5260046;\n        }\n        if x <= 5368709 {\n            return 5323291;\n        }\n        if x <= 5452595 {\n            return 5385732;\n        }\n        if x <= 5536481 {\n            return 5447366;\n        }\n        if x <= 5620367 {\n            return 5508192;\n        }\n        if x <= 5704253 {\n            return 5568208;\n        }\n        if x <= 5788139 {\n            return 5627414;\n        }\n    }\n    if x <= 6627000 {\n        if x <= 5872025 {\n            return 5685808;\n        }\n        if x <= 5955911 {\n            return 5743390;\n        }\n        if x <= 6039797 {\n            return 5800161;\n        }\n        if x <= 6123683 {\n            return 5856120;\n        }\n        if x <= 6207569 {\n            return 5911268;\n        }\n        if x <= 6291456 {\n            return 5965605;\n        }\n        if x <= 6375342 {\n            return 6019134;\n        }\n        if x <= 6459228 {\n            return 6071855;\n        }\n        if x <= 6543114 {\n            return 6123771;\n        }\n        if x <= 6627000 {\n            return 6174883;\n        }\n    }\n    if x <= 7465861 {\n        if x <= 6710886 {\n            return 6225194;\n        }\n        if x <= 6794772 {\n            return 6274706;\n        }\n        if x <= 6878658 {\n            return 6323422;\n        }\n        if x <= 6962544 {\n            return 6371347;\n        }\n        if x <= 7046430 {\n            return 6418482;\n        }\n        if x <= 7130316 {\n            return 6464832;\n        }\n        if x <= 7214202 {\n            return 6510400;\n        }\n        if x <= 7298088 {\n            return 6555192;\n        }\n        if x <= 7381975 {\n            return 6599211;\n        }\n        if x <= 7465861 {\n            return 6642462;\n        }\n    }\n    if x <= 8304721 {\n        if x <= 7549747 {\n            return 6684950;\n        }\n        if x <= 7633633 {\n            return 6726680;\n        }\n        if x <= 7717519 {\n            return 6767658;\n        }\n        if x <= 7801405 {\n            return 6807888;\n        }\n        if x <= 7885291 {\n            return 6847377;\n        }\n        if x <= 7969177 {\n            return 6886131;\n        }\n        if x <= 8053063 {\n            return 6924155;\n        }\n        if x <= 8136949 {\n            return 6961456;\n        }\n        if x <= 8220835 {\n            return 6998041;\n        }\n        if x <= 8304721 {\n            return 7033915;\n        }\n    }\n    if x <= 9143582 {\n        if x <= 8388608 {\n            return 7069086;\n        }\n        if x <= 8472494 {\n            return 7103561;\n        }\n        if x <= 8556380 {\n            return 7137346;\n        }\n        if x <= 8640266 {\n            return 7170449;\n        }\n        if x <= 8724152 {\n            return 7202877;\n        }\n        if x <= 8808038 {\n            return 7234638;\n        }\n        if x <= 8891924 {\n            return 7265739;\n        }\n        if x <= 8975810 {\n            return 7296187;\n        }\n        if x <= 9059696 {\n            return 7325990;\n        }\n        if x <= 9143582 {\n            return 7355157;\n        }\n    }\n    if x <= 9982443 {\n        if x <= 9227468 {\n            return 7383695;\n        }\n        if x <= 9311354 {\n            return 7411612;\n        }\n        if x <= 9395240 {\n            return 7438915;\n        }\n        if x <= 9479127 {\n            return 7465615;\n        }\n        if x <= 9563013 {\n            return 7491717;\n        }\n        if x <= 9646899 {\n            return 7517231;\n        }\n        if x <= 9730785 {\n            return 7542165;\n        }\n        if x <= 9814671 {\n            return 7566527;\n        }\n        if x <= 9898557 {\n            return 7590326;\n        }\n        if x <= 9982443 {\n            return 7613570;\n        }\n    }\n    if x <= 10821304 {\n        if x <= 10066329 {\n            return 7636267;\n        }\n        if x <= 10150215 {\n            return 7658425;\n        }\n        if x <= 10234101 {\n            return 7680054;\n        }\n        if x <= 10317987 {\n            return 7701162;\n        }\n        if x <= 10401873 {\n            return 7721757;\n        }\n        if x <= 10485760 {\n            return 7741847;\n        }\n        if x <= 10569646 {\n            return 7761441;\n        }\n        if x <= 10653532 {\n            return 7780548;\n        }\n        if x <= 10737418 {\n            return 7799175;\n        }\n        if x <= 10821304 {\n            return 7817332;\n        }\n    }\n    if x <= 11660165 {\n        if x <= 10905190 {\n            return 7835026;\n        }\n        if x <= 10989076 {\n            return 7852266;\n        }\n        if x <= 11072962 {\n            return 7869060;\n        }\n        if x <= 11156848 {\n            return 7885417;\n        }\n        if x <= 11240734 {\n            return 7901344;\n        }\n        if x <= 11324620 {\n            return 7916851;\n        }\n        if x <= 11408506 {\n            return 7931944;\n        }\n        if x <= 11492392 {\n            return 7946632;\n        }\n        if x <= 11576279 {\n            return 7960923;\n        }\n        if x <= 11660165 {\n            return 7974825;\n        }\n    }\n    if x <= 12499025 {\n        if x <= 11744051 {\n            return 7988346;\n        }\n        if x <= 11827937 {\n            return 8001494;\n        }\n        if x <= 11911823 {\n            return 8014276;\n        }\n        if x <= 11995709 {\n            return 8026700;\n        }\n        if x <= 12079595 {\n            return 8038774;\n        }\n        if x <= 12163481 {\n            return 8050505;\n        }\n        if x <= 12247367 {\n            return 8061901;\n        }\n        if x <= 12331253 {\n            return 8072969;\n        }\n        if x <= 12415139 {\n            return 8083716;\n        }\n        if x <= 12499025 {\n            return 8094149;\n        }\n    }\n    if x <= 13337886 {\n        if x <= 12582912 {\n            return 8104277;\n        }\n        if x <= 12666798 {\n            return 8114105;\n        }\n        if x <= 12750684 {\n            return 8123641;\n        }\n        if x <= 12834570 {\n            return 8132891;\n        }\n        if x <= 12918456 {\n            return 8141862;\n        }\n        if x <= 13002342 {\n            return 8150562;\n        }\n        if x <= 13086228 {\n            return 8158996;\n        }\n        if x <= 13170114 {\n            return 8167170;\n        }\n        if x <= 13254000 {\n            return 8175092;\n        }\n        if x <= 13337886 {\n            return 8182768;\n        }\n    }\n    if x <= 14176747 {\n        if x <= 13421772 {\n            return 8190203;\n        }\n        if x <= 13505658 {\n            return 8197405;\n        }\n        if x <= 13589544 {\n            return 8204378;\n        }\n        if x <= 13673431 {\n            return 8211128;\n        }\n        if x <= 13757317 {\n            return 8217663;\n        }\n        if x <= 13841203 {\n            return 8223986;\n        }\n        if x <= 13925089 {\n            return 8230104;\n        }\n        if x <= 14008975 {\n            return 8236022;\n        }\n        if x <= 14092861 {\n            return 8241746;\n        }\n        if x <= 14176747 {\n            return 8247281;\n        }\n    }\n    if x <= 15015608 {\n        if x <= 14260633 {\n            return 8252632;\n        }\n        if x <= 14344519 {\n            return 8257804;\n        }\n        if x <= 14428405 {\n            return 8262802;\n        }\n        if x <= 14512291 {\n            return 8267631;\n        }\n        if x <= 14596177 {\n            return 8272296;\n        }\n        if x <= 14680064 {\n            return 8276801;\n        }\n        if x <= 14763950 {\n            return 8281152;\n        }\n        if x <= 14847836 {\n            return 8285352;\n        }\n        if x <= 14931722 {\n            return 8289405;\n        }\n        if x <= 15015608 {\n            return 8293318;\n        }\n    }\n    if x <= 15854469 {\n        if x <= 15099494 {\n            return 8297092;\n        }\n        if x <= 15183380 {\n            return 8300733;\n        }\n        if x <= 15267266 {\n            return 8304245;\n        }\n        if x <= 15351152 {\n            return 8307631;\n        }\n        if x <= 15435038 {\n            return 8310895;\n        }\n        if x <= 15518924 {\n            return 8314041;\n        }\n        if x <= 15602810 {\n            return 8317074;\n        }\n        if x <= 15686696 {\n            return 8319995;\n        }\n        if x <= 15770583 {\n            return 8322809;\n        }\n        if x <= 15854469 {\n            return 8325519;\n        }\n    }\n    if x <= 16693329 {\n        if x <= 15938355 {\n            return 8328129;\n        }\n        if x <= 16022241 {\n            return 8330642;\n        }\n        if x <= 16106127 {\n            return 8333060;\n        }\n        if x <= 16190013 {\n            return 8335387;\n        }\n        if x <= 16273899 {\n            return 8337626;\n        }\n        if x <= 16357785 {\n            return 8339780;\n        }\n        if x <= 16441671 {\n            return 8341852;\n        }\n        if x <= 16525557 {\n            return 8343844;\n        }\n        if x <= 16609443 {\n            return 8345758;\n        }\n        if x <= 16693329 {\n            return 8347599;\n        }\n    }\n    if x <= 28521267 {\n        if x <= 16777216 {\n            return 8349368;\n        }\n        if x <= 17616076 {\n            return 8363614;\n        }\n        if x <= 18454937 {\n            return 8372981;\n        }\n        if x <= 19293798 {\n            return 8379018;\n        }\n        if x <= 20132659 {\n            return 8382832;\n        }\n        if x <= 20971520 {\n            return 8385194;\n        }\n        if x <= 21810380 {\n            return 8386627;\n        }\n        if x <= 22649241 {\n            return 8387481;\n        }\n        if x <= 23488102 {\n            return 8387978;\n        }\n        if x <= 24326963 {\n            return 8388263;\n        }\n        if x <= 25165824 {\n            return 8388422;\n        }\n        if x <= 26004684 {\n            return 8388510;\n        }\n        if x <= 26843545 {\n            return 8388557;\n        }\n        if x <= 27682406 {\n            return 8388582;\n        }\n        if x <= 28521267 {\n            return 8388595;\n        }\n    }\n\n    ONE\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/implementations/fp8x23wide/math/trig.cairo",
        "content": "use core::integer;\n\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::lut;\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    HALF, ONE, TWO, FP8x23W, FP8x23WImpl, FP8x23WAdd, FP8x23WSub, FP8x23WMul, FP8x23WDiv,\n    FP8x23WIntoFelt252, FixedTrait\n};\n\n// CONSTANTS\nconst TWO_PI: u64 = 52707178;\nconst PI: u64 = 26353589;\nconst HALF_PI: u64 = 13176795;\n\n// PUBLIC\n\n// Calculates arccos(a) for -1 <= a <= 1 (fixed point)\n// arccos(a) = arcsin(sqrt(1 - a^2)) - arctan identity has discontinuity at zero\nfn acos(a: FP8x23W) -> FP8x23W {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin(asin_arg);\n\n    if (a.sign) {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\nfn acos_fast(a: FP8x23W) -> FP8x23W {\n    let asin_arg = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n    let asin_res = asin_fast(asin_arg);\n\n    if (a.sign) {\n        FixedTrait::new(PI, false) - asin_res\n    } else {\n        asin_res\n    }\n}\n\n// Calculates arcsin(a) for -1 <= a <= 1 (fixed point)\n// arcsin(a) = arctan(a / sqrt(1 - a^2))\nfn asin(a: FP8x23W) -> FP8x23W {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan(a / div)\n}\n\nfn asin_fast(a: FP8x23W) -> FP8x23W {\n    if (a.mag == ONE) {\n        return FixedTrait::new(HALF_PI, a.sign);\n    }\n\n    let div = (FixedTrait::ONE() - a * a).sqrt(); // will fail if a > 1\n\n    atan_fast(a / div)\n}\n\n// Calculates arctan(a) (fixed point)\n// See https://stackoverflow.com/a/50894477 for range adjustments\nfn atan(a: FP8x23W) -> FP8x23W {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 5872026) {\n        let sqrt3_3 = FixedTrait::new(4843165, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let r10 = FixedTrait::new(15363, true) * at;\n    let r9 = (r10 + FixedTrait::new(392482, true)) * at;\n    let r8 = (r9 + FixedTrait::new(1629064, false)) * at;\n    let r7 = (r8 + FixedTrait::new(2197820, true)) * at;\n    let r6 = (r7 + FixedTrait::new(366693, false)) * at;\n    let r5 = (r6 + FixedTrait::new(1594324, false)) * at;\n    let r4 = (r5 + FixedTrait::new(11519, false)) * at;\n    let r3 = (r4 + FixedTrait::new(2797104, true)) * at;\n    let r2 = (r3 + FixedTrait::new(34, false)) * at;\n    let mut res = (r2 + FixedTrait::new(8388608, false)) * at;\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(4392265, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\nfn atan_fast(a: FP8x23W) -> FP8x23W {\n    let mut at = a.abs();\n    let mut shift = false;\n    let mut invert = false;\n\n    // Invert value when a > 1\n    if (at.mag > ONE) {\n        at = FixedTrait::ONE() / at;\n        invert = true;\n    }\n\n    // Account for lack of precision in polynomaial when a > 0.7\n    if (at.mag > 5872026) {\n        let sqrt3_3 = FixedTrait::new(4843165, false); // sqrt(3) / 3\n        at = (at - sqrt3_3) / (FixedTrait::ONE() + at * sqrt3_3);\n        shift = true;\n    }\n\n    let (start, low, high) = lut::atan(at.mag);\n    let partial_step = FixedTrait::new(at.mag - start, false) / FixedTrait::new(58720, false);\n    let mut res = partial_step * FixedTrait::new(high - low, false) + FixedTrait::new(low, false);\n\n    // Adjust for sign change, inversion, and shift\n    if (shift) {\n        res = res + FixedTrait::new(4392265, false); // pi / 6\n    }\n\n    if (invert) {\n        res = res - FixedTrait::<FP8x23W>::new(HALF_PI, false);\n    }\n\n    FixedTrait::new(res.mag, a.sign)\n}\n\n// Calculates cos(a) with a in radians (fixed point)\nfn cos(a: FP8x23W) -> FP8x23W {\n    sin(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn cos_fast(a: FP8x23W) -> FP8x23W {\n    sin_fast(FixedTrait::new(HALF_PI, false) - a)\n}\n\nfn sin(a: FP8x23W) -> FP8x23W {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, partial_rem) = integer::u64_safe_divmod(a1, integer::u64_as_non_zero(PI));\n    let a2 = FixedTrait::new(partial_rem, false);\n    let partial_sign = whole_rem == 1;\n\n    let loop_res = a2 * _sin_loop(a2, 7, FixedTrait::ONE());\n\n    FixedTrait::new(loop_res.mag, a.sign ^ partial_sign && loop_res.mag != 0)\n}\n\nfn sin_fast(a: FP8x23W) -> FP8x23W {\n    let a1 = a.mag % TWO_PI;\n    let (whole_rem, mut partial_rem) = integer::u64_safe_divmod(a1, integer::u64_as_non_zero(PI));\n    let partial_sign = whole_rem == 1;\n\n    if partial_rem >= HALF_PI {\n        partial_rem = PI - partial_rem;\n    }\n\n    let (start, low, high) = lut::sin(partial_rem);\n    let partial_step = FixedTrait::new(partial_rem - start, false) / FixedTrait::new(51472, false);\n    let res = partial_step * (FixedTrait::new(high, false) - FixedTrait::new(low, false))\n        + FixedTrait::<FP8x23W>::new(low, false);\n\n    FixedTrait::new(res.mag, a.sign ^ partial_sign && res.mag != 0)\n}\n\n// Calculates tan(a) with a in radians (fixed point)\nfn tan(a: FP8x23W) -> FP8x23W {\n    let sinx = sin(a);\n    let cosx = cos(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\nfn tan_fast(a: FP8x23W) -> FP8x23W {\n    let sinx = sin_fast(a);\n    let cosx = cos_fast(a);\n    assert(cosx.mag != 0, 'tan undefined');\n\n    sinx / cosx\n}\n\n// Helper function to calculate Taylor series for sin\nfn _sin_loop(a: FP8x23W, i: u64, acc: FP8x23W) -> FP8x23W {\n    let div = (2 * i + 2) * (2 * i + 3);\n    let term = a * a * acc / FixedTrait::new_unscaled(div, false);\n    let new_acc = FixedTrait::ONE() - term;\n\n    if (i == 0) {\n        return new_acc;\n    }\n\n    _sin_loop(a, i - 1, new_acc)\n}\n\n// Tests --------------------------------------------------------------------------------------------------------------\n\n#[cfg(test)]\nmod tests {\n    use orion::numbers::fixed_point::implementations::fp8x23wide::helpers::{\n        assert_precise, assert_relative\n    };\n\n    use super::{\n        FixedTrait, acos, HALF_PI, ONE, acos_fast, PI, atan_fast, atan, asin, cos, cos_fast, sin,\n        sin_fast, tan\n    };\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_acos() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos(a), 8784530, 'invalid half', error); // 1.0471975506263043\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos(a), 17569060, 'invalid neg half', error); // 2.094395102963489\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_acos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert(acos_fast(a).into() == 0, 'invalid one');\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(acos_fast(a), 8784530, 'invalid half', error); // 1.0471975506263043\n\n        let a = FixedTrait::ZERO();\n        assert_relative(acos_fast(a), HALF_PI.into(), 'invalid zero', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(acos_fast(a), 17569060, 'invalid neg half', error); // 2.094395102963489\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(acos_fast(a), PI.into(), 'invalid neg one', Option::None(())); // PI\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(1000000)]\n    fn test_acos_fail() {\n        let a = FixedTrait::new(2 * ONE, true);\n        acos(a);\n    }\n\n    #[test]\n    #[available_gas(1400000)]\n    fn test_atan_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan_fast(a), 9287437, 'invalid two', error);\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan_fast(a), 6588397, 'invalid one', error);\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan_fast(a), 3889358, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert(atan_fast(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan_fast(a), -3889358, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan_fast(a), -6588397, 'invalid neg one', error);\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan_fast(a), -9287437, 'invalid neg two', error);\n    }\n\n    #[test]\n    #[available_gas(2600000)]\n    fn test_atan() {\n        let a = FixedTrait::new(2 * ONE, false);\n        assert_relative(atan(a), 9287437, 'invalid two', Option::None(()));\n\n        let a = FixedTrait::ONE();\n        assert_relative(atan(a), 6588397, 'invalid one', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(atan(a), 3889358, 'invalid half', Option::None(()));\n\n        let a = FixedTrait::ZERO();\n        assert(atan(a).into() == 0, 'invalid zero');\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(atan(a), -3889358, 'invalid neg half', Option::None(()));\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(atan(a), -6588397, 'invalid neg one', Option::None(()));\n\n        let a = FixedTrait::new(2 * ONE, true);\n        assert_relative(atan(a), -9287437, 'invalid neg two', Option::None(()));\n    }\n\n    #[test]\n    #[available_gas(3000000)]\n    fn test_asin() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::ONE();\n        assert_relative(asin(a), HALF_PI.into(), 'invalid one', Option::None(())); // PI / 2\n\n        let a = FixedTrait::new(ONE / 2, false);\n        assert_relative(asin(a), 4392265, 'invalid half', error);\n\n        let a = FixedTrait::ZERO();\n        assert_precise(asin(a), 0, 'invalid zero', Option::None(()));\n\n        let a = FixedTrait::new(ONE / 2, true);\n        assert_relative(asin(a), -4392265, 'invalid neg half', error);\n\n        let a = FixedTrait::new(ONE, true);\n        assert_relative(asin(a), -HALF_PI.into(), 'invalid neg one', Option::None(())); // -PI / 2\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(1000000)]\n    fn test_asin_fail() {\n        let a = FixedTrait::new(2 * ONE, false);\n        asin(a);\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_cos() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_relative(\n            cos(a), 5931642, 'invalid quarter pi', Option::None(())\n        ); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert_relative(cos(a), -1 * ONE.into(), 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_relative(cos(a), -2308239, 'invalid 17', Option::None(())); // -0.2751631780463348\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_relative(cos(a), -2308236, 'invalid -17', Option::None(())); // -0.2751631780463348\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_cos_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert(cos_fast(a).into() == 0, 'invalid half pi');\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(cos_fast(a), 5931642, 'invalid quarter pi', error); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(cos_fast(a), -1 * ONE.into(), 'invalid pi', error);\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(cos(a), 0, 'invalid neg half pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(cos_fast(a), -2308239, 'invalid 17', error); // -0.2751631780463348\n    }\n\n    #[test]\n    #[available_gas(6000000)]\n    fn test_sin() {\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin(a), ONE.into(), 'invalid half pi', Option::None(()));\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(\n            sin(a), 5931642, 'invalid quarter pi', Option::None(())\n        ); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin(a), -ONE.into(), 'invalid neg half pi', Option::None(())\n        ); // 0.9999999999939766\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin(a), -8064787, 'invalid 17', Option::None(())); // -0.9613974918793389\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin(a), 8064787, 'invalid -17', Option::None(())); // 0.9613974918793389\n    }\n\n    #[test]\n    #[available_gas(1000000)]\n    fn test_sin_fast() {\n        let error = Option::Some(84); // 1e-5\n\n        let a = FixedTrait::new(HALF_PI, false);\n        assert_precise(sin_fast(a), ONE.into(), 'invalid half pi', error);\n\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(sin_fast(a), 5931642, 'invalid quarter pi', error); // 0.7071067811865475\n\n        let a = FixedTrait::new(PI, false);\n        assert(sin_fast(a).into() == 0, 'invalid pi');\n\n        let a = FixedTrait::new(HALF_PI, true);\n        assert_precise(\n            sin_fast(a), -ONE.into(), 'invalid neg half pi', error\n        ); // 0.9999999999939766\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(sin_fast(a), -8064787, 'invalid 17', error); // -0.9613974918793389\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(sin_fast(a), 8064787, 'invalid -17', error); // 0.9613974918793389\n    }\n\n    #[test]\n    #[available_gas(8000000)]\n    fn test_tan() {\n        let a = FixedTrait::new(HALF_PI / 2, false);\n        assert_precise(tan(a), ONE.into(), 'invalid quarter pi', Option::None(()));\n\n        let a = FixedTrait::new(PI, false);\n        assert_precise(tan(a), 0, 'invalid pi', Option::None(()));\n\n        let a = FixedTrait::new_unscaled(17, false);\n        assert_precise(tan(a), 29309069, 'invalid 17', Option::None(())); // 3.493917677159002\n\n        let a = FixedTrait::new_unscaled(17, true);\n        assert_precise(tan(a), -29309106, 'invalid -17', Option::None(())); // -3.493917677159002\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/numbers/fixed_point/utils.cairo",
        "content": "use core::integer;\n\nconst HALF_PRIME: felt252 =\n    1809251394333065606848661391547535052811553607665798349986546028067936010240;\n\n// Returns the sign of a signed `felt252` as with signed magnitude representation\n// true = negative\n// false = positive\nfn felt_sign(a: felt252) -> bool {\n    integer::u256_from_felt252(a) > integer::u256_from_felt252(HALF_PRIME)\n}\n\n// Returns the absolute value of a signed `felt252`\nfn felt_abs(a: felt252) -> felt252 {\n    let a_sign = felt_sign(a);\n\n    if a_sign {\n        return a * -1;\n    } else {\n        return a * 1;\n    }\n}\n\n\n#[cfg(test)]\nmod tests {\n    use super::{felt_sign, felt_abs};\n\n    #[test]\n    fn test_sign() {\n        let min = -1809251394333065606848661391547535052811553607665798349986546028067936010240;\n        let max = 1809251394333065606848661391547535052811553607665798349986546028067936010240;\n        assert(felt_sign(min), 'invalid result');\n        assert(felt_sign(-1), 'invalid result');\n        assert(!felt_sign(0), 'invalid result');\n        assert(!felt_sign(1), 'invalid result');\n        assert(!felt_sign(max), 'invalid result');\n    }\n\n    #[test]\n    fn test_abs() {\n        assert(felt_abs(5) == 5, 'abs of pos should be pos');\n        assert(felt_abs(-5) == 5, 'abs of neg should be pos');\n        assert(felt_abs(0) == 0, 'abs of 0 should be 0');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators.cairo",
        "content": "mod tensor;\nmod nn;\nmod ml;\nmod matrix;\nmod vec;\nmod sequence;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/matrix.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::vec::{VecTrait, NullableVec, NullableVecImpl};\n\nstruct MutMatrix<T> {\n    data: NullableVec<T>,\n    rows: usize,\n    cols: usize,\n}\n\nimpl MutMatrixDestruct<T, +Drop<T>> of Destruct<MutMatrix<T>> {\n    fn destruct(self: MutMatrix<T>) nopanic {\n        self.data.destruct()\n    }\n}\n\n#[generate_trait]\nimpl MutMatrixImpl<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +PartialOrd<T>\n> of MutMatrixTrait<T> {\n    /// Constructor for the Matrix\n    fn new(rows: usize, cols: usize) -> MutMatrix<T> {\n        MutMatrix { data: NullableVecImpl::new(), rows: rows, cols: cols }\n    }\n\n    /// Get the value at (row, col)\n    fn get(ref self: MutMatrix<T>, row: usize, col: usize) -> Option<T> {\n        if row >= self.rows || col >= self.cols {\n            Option::None\n        } else {\n            self.data.get(row * self.cols + col)\n        }\n    }\n\n    /// Get the value at (row, col)\n    fn at(ref self: MutMatrix<T>, row: usize, col: usize) -> T {\n        match self.get(row, col) {\n            Option::Some(val) => val,\n            Option::None => NumberTrait::zero(),\n        }\n    }\n\n    /// Performs the product between a m x n `MutMatrix<T>` and a n x 1 `NullableVec<T>`. \n    /// Returns the resulta as a `NullableVec<T>`.\n    fn matrix_vector_product<+Mul<T>, +Add<T>, +Div<T>, +AddEq<T>>(\n        ref self: MutMatrix<T>, ref vec: NullableVec<T>\n    ) -> NullableVec<T> {\n        assert(self.cols == vec.len, 'wrong matrix shape for dot');\n\n        let m = self.rows;\n        let n = self.cols;\n\n        let mut result_vec = VecTrait::new();\n\n        let mut i = 0_usize;\n        while i != m {\n            let mut sum: T = NumberTrait::zero();\n            let mut k = 0_usize;\n            while k != n {\n                sum += MutMatrixImpl::at(ref self, i, k) * VecTrait::at(ref vec, k);\n\n                k += 1;\n            };\n\n            VecTrait::set(ref result_vec, i, sum);\n            i += 1;\n        };\n\n        result_vec\n    }\n\n    /// Set the value at (row, col)\n    fn set(ref self: MutMatrix<T>, row: usize, col: usize, value: T) {\n        if row < self.rows && col < self.cols {\n            let index = row * self.cols + col;\n\n            self.data.set(index, value)\n        }\n    }\n\n    /// Returns the shape of the matrix as (rows, cols)\n    fn shape(self: MutMatrix<T>) -> (usize, usize) {\n        (self.rows, self.cols)\n    }\n\n    /// Returns the index of the maximum value along the specified axis\n    fn argmax(ref self: MutMatrix<T>, axis: usize) -> Span<usize> {\n        assert(axis < 2, 'Invalid axis');\n\n        let mut result: Array<usize> = ArrayTrait::new();\n\n        if axis == 0 {\n            let mut col: usize = 0;\n            while col != self.cols {\n                let mut max_value = self.get(0, col);\n                let mut max_value = match max_value {\n                    Option::Some => { max_value.unwrap() },\n                    Option::None => { NumberTrait::min_value() }\n                };\n                let mut max_index = 0;\n\n                let mut row: usize = 1;\n                while row != self.rows {\n                    let mut value = self.get(row, col);\n                    let mut value = match value {\n                        Option::Some => { value.unwrap() },\n                        Option::None => { NumberTrait::min_value() }\n                    };\n\n                    if value > max_value {\n                        max_value = value;\n                        max_index = row;\n                    }\n\n                    row += 1;\n                };\n\n                result.append(max_index);\n                col += 1;\n            };\n\n            return result.span();\n        }\n\n        let mut row: usize = 0;\n        while row != self.rows {\n            let mut max_value = self.get(row, 0);\n            let mut max_value = match max_value {\n                Option::Some => { max_value.unwrap() },\n                Option::None => { NumberTrait::min_value() }\n            };\n            let mut max_index = 0;\n\n            let mut col: usize = 1;\n            while col != self.cols {\n                let mut value = self.get(row, col);\n                let mut value = match value {\n                    Option::Some => { value.unwrap() },\n                    Option::None => { NumberTrait::min_value() }\n                };\n\n                if value > max_value {\n                    max_value = value;\n                    max_index = col;\n                }\n\n                col += 1;\n            };\n\n            result.append(max_index);\n            row += 1;\n        };\n\n        result.span()\n    }\n\n    /// Apply softmax to the matrix along the specified axis\n    fn softmax<+AddEq<T>, +Div<T>>(ref self: MutMatrix<T>, axis: usize) -> MutMatrix<T> {\n        assert(axis < 2, 'Invalid axis');\n\n        let mut result = MutMatrixImpl::new(self.rows, self.cols);\n\n        if axis == 0 {\n            let mut col: usize = 0;\n            while col != self.cols {\n                let mut sum_exp = NumberTrait::zero();\n                let mut row: usize = 0;\n                while row != self.rows {\n                    let value = self.get(row, col).unwrap().into();\n                    sum_exp += value.exp();\n\n                    row += 1;\n                };\n\n                row = 0;\n                while row != self.rows {\n                    let value = self.get(row, col).unwrap().into();\n                    let softmax_value = (value.exp() / sum_exp).into();\n                    result.set(row, col, softmax_value);\n\n                    row += 1;\n                };\n\n                col += 1;\n            };\n        } else {\n            let mut row: usize = 0;\n            while row != self.rows {\n                let mut sum_exp = NumberTrait::zero();\n                let mut col: usize = 0;\n                while col != self.cols {\n                    let value = self.get(row, col).unwrap().into();\n                    sum_exp += value.exp();\n\n                    col += 1;\n                };\n\n                col = 0;\n                while col != self.cols {\n                    let value = self.get(row, col).unwrap().into();\n                    let softmax_value = (value.exp() / sum_exp).into();\n                    result.set(row, col, softmax_value);\n\n                    col += 1;\n                };\n\n                row += 1;\n            };\n        }\n\n        result\n    }\n\n    /// Apply softmax to the matrix along the specified axis, treating zeros as neutral\n    fn softmax_zero<+AddEq<T>, +Div<T>, +PartialEq<T>>(\n        ref self: MutMatrix<T>, axis: usize\n    ) -> MutMatrix<T> {\n        assert(axis < 2, 'Invalid axis');\n\n        let mut result = MutMatrixImpl::new(self.rows, self.cols);\n\n        if axis == 0 {\n            let mut col: usize = 0;\n            while col != self.cols {\n                let mut sum_exp = NumberTrait::zero();\n                let mut row: usize = 0;\n                while row != self.rows {\n                    let value = self.get(row, col).unwrap().into();\n\n                    if value != NumberTrait::zero() {\n                        sum_exp += value.exp();\n                    }\n\n                    row += 1;\n                };\n\n                row = 0;\n                while row != self.rows {\n                    let value = self.get(row, col).unwrap().into();\n\n                    if value != NumberTrait::zero() {\n                        let softmax_value = (value.exp() / sum_exp).into();\n                        result.set(row, col, softmax_value);\n                    } else {\n                        result.set(row, col, NumberTrait::zero());\n                    }\n\n                    row += 1;\n                };\n\n                col += 1;\n            };\n        } else {\n            let mut row: usize = 0;\n            while row != self.rows {\n                let mut sum_exp = NumberTrait::zero();\n                let mut col: usize = 0;\n                while col != self.cols {\n                    let value = self.get(row, col).unwrap().into();\n                    if value != NumberTrait::zero() {\n                        sum_exp += value.exp();\n                    }\n\n                    col += 1;\n                };\n\n                col = 0;\n                while col != self.cols {\n                    let value = self.get(row, col).unwrap().into();\n\n                    if value != NumberTrait::zero() {\n                        let softmax_value = (value.exp() / sum_exp).into();\n                        result.set(row, col, softmax_value);\n                    } else {\n                        result.set(row, col, NumberTrait::zero());\n                    }\n\n                    col += 1;\n                };\n\n                row += 1;\n            };\n        }\n\n        result\n    }\n\n    /// Apply the sigmoid function to each element of the matrix\n    fn sigmoid<+Mul<T>, +Add<T>, +Div<T>>(ref self: MutMatrix<T>) -> MutMatrix<T> {\n        let mut result = MutMatrixImpl::new(self.rows, self.cols);\n\n        let mut row: usize = 0;\n        while row != self.rows {\n            let mut col: usize = 0;\n            while col != self.cols {\n                let value = self.get(row, col);\n\n                if value.is_some() {\n                    let value = NumberTrait::one()\n                        / (NumberTrait::one() + (value.unwrap() * NumberTrait::neg_one()).exp());\n\n                    result.set(row, col, value);\n                }\n\n                col += 1;\n            };\n\n            row += 1;\n        };\n\n        result\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml.cairo",
        "content": "mod tree_ensemble;\nmod linear;\nmod svm;\nmod normalizer;\n\nuse orion::operators::ml::tree_ensemble::core::{\n    TreeEnsemble, TreeEnsembleAttributes, TreeEnsembleImpl, NODE_MODES\n};\nuse orion::operators::ml::tree_ensemble::tree_ensemble_classifier::{\n    TreeEnsembleClassifier, TreeEnsembleClassifierImpl, TreeEnsembleClassifierTrait\n};\n\nuse orion::operators::ml::tree_ensemble::tree_ensemble_regressor::{\n    TreeEnsembleRegressor, TreeEnsembleRegressorImpl, TreeEnsembleRegressorTrait, AGGREGATE_FUNCTION\n};\n\nuse orion::operators::ml::linear::linear_regressor::{\n    LinearRegressorTrait, LinearRegressorImpl, LinearRegressor\n};\n\nuse orion::operators::ml::linear::linear_classifier::{\n    LinearClassifierTrait, LinearClassifierImpl, LinearClassifier\n};\n\nuse orion::operators::ml::normalizer::normalizer::{NormalizerTrait, NORM};\n\n#[derive(Copy, Drop)]\nenum POST_TRANSFORM {\n    NONE,\n    SOFTMAX,\n    LOGISTIC,\n    SOFTMAXZERO,\n    PROBIT,\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/linear.cairo",
        "content": "mod linear_regressor;\nmod linear_classifier;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/linear/linear_classifier.cairo",
        "content": "use core::array::ArrayTrait;\nuse core::array::SpanTrait;\nuse orion::numbers::FP16x16;\n\nuse orion::operators::tensor::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FP32x32, FP32x32Impl, FixedTrait};\nuse orion::operators::nn::{NNTrait, FP16x16NN};\nuse orion::operators::ml::POST_TRANSFORM;\n\n#[derive(Destruct)]\nstruct LinearClassifier<T> {\n    classlabels: Option<Span<usize>>,\n    coefficients: Span<T>,\n    intercepts: Option<Span<T>>,\n    multi_class: usize,\n    post_transform: POST_TRANSFORM,\n}\n\n/// Trait\n///\n/// predict - Performs the linear classification.\ntrait LinearClassifierTrait<T> {\n    /// # LinearClassifierTrait::predict\n    ///\n    /// ```rust \n    ///    fn predict(classifier: LinearClassifier<T>, X: Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Linear Classifier. Performs the linear classification.\n    /// \n    /// ## Args\n    ///\n    /// * `self`: LinearClassifier<T> - A LinearClassifier object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * Tensor<T> containing the linear classification evaluation of the input X.\n    ///\n    /// ## Type Constraints\n    ///\n    /// `LinearClassifier` and `X` must be fixed points\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\n    /// \n    /// use orion::operators::ml::linear::linear_classifier::{\n    ///     LinearClassifierTrait, POST_TRANSFORM, LinearClassifier\n    /// };\n    /// \n    /// fn linear_classifier_helper(\n    ///     post_transform: POST_TRANSFORM\n    /// ) -> (LinearClassifier<FP16x16>, Tensor<FP16x16>) {\n    /// \n    ///     let classlabels: Span<usize> = array![0, 1, 2].span();\n    ///     let classlabels = Option::Some(classlabels);\n    /// \n    ///     let classlabels_strings: Option<Span<FP16x16>> = Option::None;\n    /// \n    ///     let coefficients: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 38011, sign: true },\n    ///         FP16x16 { mag: 19005, sign: true },\n    ///         FP16x16 { mag: 5898, sign: true },\n    ///         FP16x16 { mag: 38011, sign: false },\n    ///         FP16x16 { mag: 19005, sign: false },\n    ///         FP16x16 { mag: 5898, sign: false }, \n    ///     ]\n    ///         .span();\n    /// \n    ///     let intercepts: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 176947, sign: false },\n    ///         FP16x16 { mag: 176947, sign: true },\n    ///         FP16x16 { mag: 32768, sign: false },\n    ///     ]\n    ///         .span();\n    ///     let intercepts = Option::Some(intercepts);\n    /// \n    ///     let multi_class: usize = 0;\n    /// \n    ///     let mut classifier: LinearClassifier<FP16x16> = LinearClassifier {\n    ///         classlabels,\n    ///         coefficients,\n    ///         intercepts,\n    ///         multi_class,\n    ///         post_transform\n    ///         };\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 2].span(),\n    ///         array![\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 65536, sign: false },\n    ///             FP16x16 { mag: 131072, sign: false },\n    ///             FP16x16 { mag: 196608, sign: false },\n    ///             FP16x16 { mag: 262144, sign: false },\n    ///             FP16x16 { mag: 327680, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     (classifier, X)\n    /// }\n    /// \n    /// fn linear_classifier_multi_softmax() -> (Span<usize>, Tensor<FP16x16>) {\n    ///     let (mut classifier, X) = linear_classifier_helper(POST_TRANSFORM::SOFTMAX);\n    /// \n    ///     let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n    /// \n    ///     (labels, scores)\n    /// }\n    /// \n    /// >>> \n    /// ([0, 2, 2],\n    ///  [\n    ///     [0.852656, 0.009192, 0.138152],\n    ///     [0.318722, 0.05216, 0.629118],\n    ///     [0.036323, 0.090237, 0.87344]\n    ///  ])\n    /// ```\n    fn predict(classifier: LinearClassifier<T>, X: Tensor<T>) -> (Span<usize>, Tensor<T>);\n}\n\nimpl LinearClassifierImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Add<Tensor<T>>,\n    +NNTrait<T>\n> of LinearClassifierTrait<T> {\n    fn predict(classifier: LinearClassifier<T>, X: Tensor<T>) -> (Span<usize>, Tensor<T>) {\n        let n: usize = classifier.coefficients.len() / *(X.shape).at(1);\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(n);\n        shape.append(*(X.shape).at(1));\n\n        let mut coefficients = TensorTrait::new(shape.span(), classifier.coefficients);\n        let coefficients = coefficients.transpose(array![1, 0].span());\n\n        let mut scores = X.matmul(@coefficients);\n        match classifier.intercepts {\n            Option::Some(intercepts) => {\n                let mut shape = ArrayTrait::<usize>::new();\n                shape.append(1);\n                shape.append(intercepts.len());\n                let intercepts = TensorTrait::new(shape.span(), intercepts);\n                scores = TensorTrait::add(scores, intercepts);\n            },\n            Option::None => {},\n        };\n\n        let (n_classes, classlabels) = match classifier.classlabels {\n            Option::Some(classlabels) => { (classlabels.len(), classlabels) },\n            Option::None => { (0, ArrayTrait::<usize>::new().span()) },\n        };\n        if *coefficients.shape.at(1) == 1 && n_classes == 2 {\n            let mut new_scores = array![];\n\n            loop {\n                match scores.data.pop_front() {\n                    Option::Some(item) => {\n                        new_scores.append(NumberTrait::neg(*item));\n                        new_scores.append(*item);\n                    },\n                    Option::None => { break; },\n                }\n            };\n\n            scores = TensorTrait::new(array![*scores.shape.at(0), 2].span(), new_scores.span());\n        }\n        // Post Transform\n        scores = match classifier.post_transform {\n            POST_TRANSFORM::NONE => { scores },\n            POST_TRANSFORM::SOFTMAX => { NNTrait::softmax(@scores, Option::Some(1)) },\n            POST_TRANSFORM::LOGISTIC => { NNTrait::sigmoid(@scores) },\n            POST_TRANSFORM::SOFTMAXZERO => { NNTrait::softmax_zero(@scores, 1) },\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n\n        // Labels\n        let mut labels_list = array![];\n        if *scores.shape.at(1) > 1 {\n            let mut labels = scores.argmax(1, Option::None, Option::None);\n            loop {\n                match labels.data.pop_front() {\n                    Option::Some(i) => {\n                        labels_list.append(*classlabels[(*i).try_into().unwrap()]);\n                    },\n                    Option::None => { break; }\n                };\n            };\n        } else {\n            let mut i = 0;\n            match classifier.post_transform {\n                POST_TRANSFORM::NONE => {\n                    while i != scores\n                        .data\n                        .len() {\n                            if *scores.data.at(i) >= NumberTrait::zero() {\n                                labels_list.append(*classlabels[0]);\n                            } else {\n                                labels_list.append(0);\n                            }\n\n                            i += 1;\n                        };\n                },\n                POST_TRANSFORM::SOFTMAX => {\n                    while i != scores\n                        .data\n                        .len() {\n                            if *scores.data.at(i) >= NumberTrait::half() {\n                                labels_list.append(*classlabels[0]);\n                            } else {\n                                labels_list.append(0);\n                            }\n\n                            i += 1;\n                        };\n                },\n                POST_TRANSFORM::LOGISTIC => {\n                    while i != scores\n                        .data\n                        .len() {\n                            if *scores.data.at(i) >= NumberTrait::half() {\n                                labels_list.append(*classlabels[0]);\n                            } else {\n                                labels_list.append(0);\n                            }\n\n                            i += 1;\n                        };\n                },\n                POST_TRANSFORM::SOFTMAXZERO => {\n                    while i != scores\n                        .data\n                        .len() {\n                            if *scores.data.at(i) >= NumberTrait::half() {\n                                labels_list.append(*classlabels[0]);\n                            } else {\n                                labels_list.append(0);\n                            }\n\n                            i += 1;\n                        };\n                },\n                POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n            };\n        }\n\n        (labels_list.span(), scores)\n    }\n}\n\nfn max(a: usize, b: usize) -> usize {\n    if a > b {\n        a\n    } else {\n        b\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/linear/linear_regressor.cairo",
        "content": "use core::array::ArrayTrait;\nuse core::clone::Clone;\nuse core::traits::Into;\nuse core::array::SpanTrait;\nuse core::dict::Felt252DictTrait;\nuse core::dict::Felt252DictEntryTrait;\nuse orion::numbers::FP16x16;\n\nuse orion::operators::tensor::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FP32x32, FP32x32Impl, FixedTrait};\n\nuse core::debug::PrintTrait;\nuse orion::operators::nn::{NNTrait, FP16x16NN};\nuse orion::operators::ml::POST_TRANSFORM;\n\n#[derive(Destruct)]\nstruct LinearRegressor<T> {\n    coefficients: Span<T>,\n    intercepts: Option<Span<T>>,\n    target: usize,\n    post_transform: POST_TRANSFORM,\n}\n\n\n/// Trait\n///\n/// predict - Performs the generalized linear regression evaluation.\ntrait LinearRegressorTrait<T> {\n    /// # LinearRegressorTrait::predict\n    ///\n    /// ```rust \n    ///    fn predict(regressor: LinearRegressor<T>, X: Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Linear Regressor. Performs the generalized linear regression evaluation.\n    /// \n    /// ## Args\n    ///\n    /// * `regressor`: LinearRegressor<T> - A LinearRegressor object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * Tensor<T> containing the generalized linear regression evaluation of the input X.\n    ///\n    /// ## Type Constraints\n    ///\n    /// `LinearRegressor` and `X` must be fixed points\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor, FP16x16TensorAdd};\n    /// use orion::operators::ml::linear::linear_regressor::{\n    ///     LinearRegressorTrait, POST_TRANSFORM, LinearRegressor\n    /// };\n    /// use orion::numbers::{FP16x16, FixedTrait};\n    /// use orion::operators::nn::{NNTrait, FP16x16NN};\n    /// \n    /// fn example_linear_regressor() -> Tensor<FP16x16> {\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 2].span(),\n    ///         array![\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 65536, sign: false },\n    ///             FP16x16 { mag: 131072, sign: false },\n    ///             FP16x16 { mag: 196608, sign: false },\n    ///             FP16x16 { mag: 262144, sign: false },\n    ///             FP16x16 { mag: 327680, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     let coefficients: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 19661, sign: false },\n    ///         FP16x16 { mag: 50463, sign: true },\n    /// \n    ///     ]\n    ///         .span();\n    /// \n    ///     let intercepts: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 32768, sign: false },\n    /// \n    ///     ]\n    ///         .span();\n    ///     let intercepts = Option::Some(intercepts);    \n    /// \n    ///     let target : usize = 1;\n    ///     let post_transform = POST_TRANSFORM::NONE;\n    /// \n    ///     let mut regressor: LinearRegressor<FP16x16> = LinearRegressor {\n    ///         coefficients,\n    ///         intercepts,\n    ///         target,\n    ///         post_transform\n    ///     };\n    /// \n    ///     let scores = LinearRegressorTrait::predict(regressor, X);\n    /// \n    ///     scores\n    /// }\n    /// \n    /// >>> \n    /// [[-0.27], [-1.21], [-2.15]]\n    /// \n    /// \n    /// \n    /// fn example_linear_regressor_2() -> Tensor<FP16x16> {\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 2].span(),\n    ///         array![\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 65536, sign: false },\n    ///             FP16x16 { mag: 131072, sign: false },\n    ///             FP16x16 { mag: 196608, sign: false },\n    ///             FP16x16 { mag: 262144, sign: false },\n    ///             FP16x16 { mag: 327680, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     let coefficients: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 19661, sign: false },\n    ///         FP16x16 { mag: 50463, sign: true },\n    ///         FP16x16 { mag: 19661, sign: false },\n    ///         FP16x16 { mag: 50463, sign: true },\n    /// \n    ///     ]\n    ///         .span();\n    /// \n    ///     let intercepts: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 32768, sign: false },\n    ///         FP16x16 { mag: 45875, sign: false },\n    /// \n    ///     ]\n    ///         .span();\n    ///     let intercepts = Option::Some(intercepts);  \n    /// \n    ///     let target = 2;\n    ///     let post_transform = POST_TRANSFORM::NONE;\n    /// \n    ///     let mut regressor: LinearRegressor<FP16x16> = LinearRegressor {\n    ///         coefficients,\n    ///         intercepts,\n    ///         target,\n    ///         post_transform\n    ///     };\n    /// \n    ///     let scores = LinearRegressorTrait::predict(regressor, X);\n    /// \n    ///     scores\n    /// }\n    /// \n    /// >>>\n    /// [[-0.27, -0.07], [-1.21, -1.01], [-2.15, -1.95]]   \n    /// ```\n    ///\n    ///\n\n    fn predict(regressor: LinearRegressor<T>, X: Tensor<T>) -> Tensor<T>;\n}\n\nimpl LinearRegressorImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Add<Tensor<T>>,\n    +NNTrait<T>,\n> of LinearRegressorTrait<T> {\n    fn predict(regressor: LinearRegressor<T>, X: Tensor<T>) -> Tensor<T> {\n        let n: usize = regressor.coefficients.len() / regressor.target;\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(regressor.target);\n        shape.append(n);\n        let mut coefficients = TensorTrait::new(shape.span(), regressor.coefficients);\n\n        let coefficients = coefficients.transpose(array![1, 0].span());\n        let mut score = X.matmul(@coefficients);\n\n        match regressor.intercepts {\n            Option::Some(intercepts) => {\n                let mut shape: Array<usize> = array![];\n                shape.append(1);\n                shape.append(intercepts.len());\n                let intercepts = TensorTrait::new(shape.span(), intercepts);\n                score = TensorTrait::add(score, intercepts);\n            },\n            Option::None => {},\n        };\n\n        // Post Transform\n        let score = match regressor.post_transform {\n            POST_TRANSFORM::NONE => score, // No action required\n            POST_TRANSFORM::SOFTMAX => NNTrait::softmax(@score, Option::Some(1)),\n            POST_TRANSFORM::LOGISTIC => NNTrait::sigmoid(@score),\n            POST_TRANSFORM::SOFTMAXZERO => NNTrait::softmax_zero(@score, 1),\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n\n        score\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/normalizer.cairo",
        "content": "mod normalizer;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/normalizer/normalizer.cairo",
        "content": "use core::array::ArrayTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n\n#[derive(Copy, Drop)]\nenum NORM {\n    MAX,\n    L1,\n    L2,\n}\n\n\n/// predict - Returns the normalization of the input, each row of the input is normalized independently.\ntrait NormalizerTrait<T> {\n    /// # Normalizer::predict\n    ///\n    /// ```rust \n    ///    fn predict(X: Tensor<T>, norm: NORM) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns the normalized input.\n    /// Tree different types of normalization can be performed and are defined as follow :\n    /// MAX: $Y = \\frac{X}{max(X)}$\n    /// L1: $Y = \\frac{X}{sum(X)}$\n    /// L2: $Y = \\frac{X}\\sqrt{{sum(X\u00b2)}}$\n    /// For batches, that is, [N,C] tensors, normalization is done along the C axis. In other words, each row of the batch is normalized independently.\n    ///     \n    /// ## Args\n    ///\n    /// * `X`(`@Tensor<T>`) - Input 2D tensor. \n    /// * `norm`(`NORM`) - NORM::MAX, NORM::L1 or NORM::L2\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// * Tensor<T> - output tensor \n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorDiv, FP16x16TensorPartialEq};\n    /// \n    /// use orion::operators::ml::normalizer::normalizer::{\n    ///     NormalizerTrait, NORM\n    /// };\n    /// \n    /// \n    /// \n    /// fn normalizer_max() ->  Tensor<FP16x16> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(3);\n    ///     shape.append(3);\n    ///\n    ///   let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 65536, sign: true });\n    ///     data.append(FP16x16 { mag: 52428, sign: true });\n    ///     data.append(FP16x16 { mag: 39321, sign: true });\n    ///     data.append(FP16x16 { mag: 26214, sign: true });\n    ///     data.append(FP16x16 { mag: 13107, sign: true });\n    ///     data.append(FP16x16 { mag: 0, sign: false });\n    ///     data.append(FP16x16 { mag: 13107, sign: false });\n    ///     data.append(FP16x16 { mag: 26214, sign: false });\n    ///     data.append(FP16x16 { mag: 39321, sign: false });\n    ///\n    ///   let X = TensorTrait::new(shape.span(), data.span());\n    ///\n    ///   return NormalizerTrait::predict(X, NORM::MAX);\n    /// }\n    /// >>> [[-1.        -0.8       -0.6      ]\n    ///      [-1.        -0.5        0.       ]\n    ///      [ 0.3333333  0.6666666  1.       ]]\n    ///\n    /// ```\n    ///\n    ///\n    fn predict(X: Tensor<T>, norm: NORM) -> Tensor<T>;\n}\n\n\nimpl NormalizerImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Div<Tensor<T>>,\n    +Mul<T>\n> of NormalizerTrait<T> {\n    fn predict(X: Tensor<T>, norm: NORM) -> Tensor<T> {\n        assert(X.shape.len() == 2, 'input should be 2D: NxC');\n\n        let normalized_tensor = match norm {\n            NORM::MAX => { norm_max(X) },\n            NORM::L1 => { norm_l1(X) },\n            NORM::L2 => { norm_l2(X) },\n        };\n\n        return normalized_tensor;\n    }\n}\n\n\nfn norm_max<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +Div<Tensor<T>>,\n>(\n    X: Tensor<T>\n) -> Tensor<T> {\n    let div_data = reduce_max_2D_axis_1(X.abs());\n\n    let div = TensorTrait::new(\n        array![*X.shape.at(0), (div_data.len() / *X.shape.at(0))].span(), div_data\n    );\n\n    let epsillon = TensorTrait::new(array![1, 1].span(), array![NumberTrait::from_felt(1)].span());\n    let safe_div = TensorTrait::max(tensors: array![div, epsillon].span());\n\n    return X / safe_div;\n}\n\nfn norm_l1<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +AddEq<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +Div<Tensor<T>>,\n>(\n    X: Tensor<T>\n) -> Tensor<T> {\n    let div_data = reduce_sum_2D_axis_1(X.abs());\n\n    let div = TensorTrait::new(\n        array![*X.shape.at(0), (div_data.len() / *X.shape.at(0))].span(), div_data\n    );\n\n    let epsillon = TensorTrait::new(array![1, 1].span(), array![NumberTrait::from_felt(1)].span());\n    let safe_div = TensorTrait::max(tensors: array![div, epsillon].span());\n\n    return X / safe_div;\n}\n\nfn norm_l2<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +AddEq<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +Div<Tensor<T>>,\n    +Mul<T>\n>(\n    X: Tensor<T>\n) -> Tensor<T> {\n    let div_data = reduce_sum_2D_axis_1(square(X));\n    let div = TensorTrait::new(\n        array![*X.shape.at(0), (div_data.len() / *X.shape.at(0))].span(), div_data\n    );\n\n    let epsillon = TensorTrait::new(array![1, 1].span(), array![NumberTrait::from_felt(1)].span());\n    let safe_div = TensorTrait::max(tensors: array![div.sqrt(), epsillon].span());\n\n    return X / safe_div;\n}\n\n\nfn reduce_max_2D_axis_1<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +PartialOrd<T>,\n>(\n    X: Tensor<T>\n) -> Span<T> {\n    let mut new_data = ArrayTrait::new();\n    let N = *X.shape.at(0);\n    let C = *X.shape.at(1);\n\n    let mut i = 0;\n    while i != N {\n        let max = max(SpanTrait::slice(X.data, i * C, C));\n        new_data.append(max);\n        i += 1;\n    };\n    return new_data.span();\n}\n\n\nfn max<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +PartialOrd<T>,>(\n    mut a: Span<T>\n) -> T {\n    assert(a.len() > 0, 'span cannot be empty');\n\n    let mut max = *a.at(0);\n    loop {\n        match a.pop_front() {\n            Option::Some(v) => { if *v > max {\n                max = *v;\n            }; },\n            Option::None => { break max; }\n        };\n    }\n}\n\nfn sum<T, MAG, +Drop<T>, +Copy<T>, +AddEq<T>, +NumberTrait<T, MAG>,>(mut a: Span<T>) -> T {\n    assert(a.len() > 0, 'span cannot be empty');\n\n    let mut sum = NumberTrait::zero();\n    loop {\n        match a.pop_front() {\n            Option::Some(v) => { sum += *v; },\n            Option::None => { break sum; }\n        };\n    }\n}\n\nfn square<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +AddEq<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +Mul<T>\n>(\n    mut a: Tensor<T>\n) -> Tensor<T> {\n    let mut arr = ArrayTrait::new();\n    loop {\n        match a.data.pop_front() {\n            Option::Some(v) => { arr.append(*v * *v); },\n            Option::None => { break TensorTrait::new(a.shape, arr.span()); }\n        };\n    }\n}\n\nfn reduce_sum_2D_axis_1<\n    T, MAG, +Drop<T>, +Copy<T>, +AddEq<T>, +NumberTrait<T, MAG>, +TensorTrait<T>,\n>(\n    X: Tensor<T>\n) -> Span<T> {\n    let mut new_data = ArrayTrait::new();\n    let N = *X.shape.at(0);\n    let C = *X.shape.at(1);\n\n    let mut i = 0;\n    while i != N {\n        let sum = sum(SpanTrait::slice(X.data, i * C, C));\n        new_data.append(sum);\n        i += 1;\n    };\n    return new_data.span();\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/svm.cairo",
        "content": "mod core;\nmod svm_regressor;\nmod svm_classifier;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/svm/core.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, BoolTensor\n};\nuse orion::utils::get_row;\n\n#[derive(Copy, Drop)]\nenum KERNEL_TYPE {\n    LINEAR,\n    POLY,\n    RBF,\n    SIGMOID,\n}\n\nfn kernel_dot<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n>(\n    kernel_params: Span<T>, pA: Span<T>, pB: Span<T>, kernel: KERNEL_TYPE\n) -> T {\n    let s = match kernel {\n        KERNEL_TYPE::LINEAR => sv_dot(pA, pB),\n        KERNEL_TYPE::POLY => {\n            let mut s = sv_dot(pA, pB);\n            s = s * *kernel_params.at(0) + *kernel_params.at(1);\n            s.pow(*kernel_params.at(2))\n        },\n        KERNEL_TYPE::RBF => {\n            let mut s = squared_diff(pA, pB);\n            NumberTrait::exp(-*kernel_params.at(0) * s)\n        },\n        KERNEL_TYPE::SIGMOID => {\n            let mut s = sv_dot(pA, pB);\n            s = s * *kernel_params.at(0) + *kernel_params.at(1);\n            NumberTrait::tanh(s)\n        },\n    };\n\n    s\n}\n\n\nfn sv_dot<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Add<T>, +TensorTrait<T>, +AddEq<T>, +Mul<T>,\n>(\n    pA: Span<T>, pB: Span<T>\n) -> T {\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != pA.len() {\n        sum = sum + *pA.at(i) * *pB.at(i);\n        i += 1;\n    };\n\n    sum\n}\n\nfn squared_diff<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    pA: Span<T>, pB: Span<T>\n) -> T {\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != pA.len() {\n        sum = sum + (*pA.at(i) - *pB.at(i)).pow(NumberTrait::one() + NumberTrait::one());\n        i += 1;\n    };\n\n    sum\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/svm/svm_classifier.cairo",
        "content": "use core::array::ArrayTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, BoolTensor\n};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\n\nuse orion::operators::vec::{VecTrait, NullableVec, NullableVecImpl};\nuse orion::operators::matrix::{MutMatrix, MutMatrixImpl};\n\nuse orion::numbers::{FP64x64, FP64x64Impl};\nuse orion::operators::tensor::implementations::tensor_fp64x64::{FP64x64Tensor};\nuse orion::operators::nn::{NNTrait, FP16x16NN, FP64x64NN};\nuse orion::utils::get_row;\n\nuse orion::operators::ml::svm::core::{kernel_dot, KERNEL_TYPE};\nuse orion::operators::ml::POST_TRANSFORM;\n\n\n#[derive(Copy, Drop, Destruct)]\nstruct SVMClassifier<T> {\n    classlabels: Span<usize>,\n    coefficients: Span<T>,\n    kernel_params: Span<T>,\n    kernel_type: KERNEL_TYPE,\n    post_transform: POST_TRANSFORM,\n    prob_a: Span<T>,\n    prob_b: Span<T>,\n    rho: Span<T>,\n    support_vectors: Span<T>,\n    vectors_per_class: Option<Span<usize>>,\n}\n\n#[derive(Copy, Drop)]\nenum MODE {\n    SVM_LINEAR,\n    SVM_SVC,\n}\n\n\n///\n/// predict - Returns the top class for each of N inputs.\ntrait SVMClassifierTrait<T> {\n    /// # SVMClassifierTrait::predict\n    ///\n    /// ```rust \n    ///    fn predict(ref self: SVMClassifier<T>, X: Tensor<T>) -> (Span<usize>, Tensor<T>);\n    /// ```\n    ///\n    /// Support Vector Machine classification.\n    /// \n    /// ## Args\n    ///\n    /// * `self`: SVMClassifier<T> - A SVMClassifier object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * N Top class for each point\n    /// * The class score Matrix for each class, for each point.  If prob_a and prob_b are provided they are probabilities for each class, otherwise they are raw scores.\n    ///\n    /// ## Type Constraints\n    ///\n    /// `SVMClassifier` and `X` must be fixed points\n    ///\n    /// ## Examples\n    /// \n    /// ```rust    \n    /// fn example_svm_classifier_noprob_linear_sv_none() -> (Span<usize>, Tensor<FP16x16>) {\n    ///     let coefficients: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 50226, sign: false },\n    ///         FP16x16 { mag: 5711, sign: false },\n    ///         FP16x16 { mag: 7236, sign: false },\n    ///         FP16x16 { mag: 63175, sign: true }\n    ///     ]\n    ///         .span();\n    ///     let kernel_params: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 8025, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 196608, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let kernel_type = KERNEL_TYPE::LINEAR;\n    ///     let prob_a: Span<FP16x16> = array![].span();\n    ///     let prob_b: Span<FP16x16> = array![].span();\n    ///     let rho: Span<FP16x16> = array![FP16x16 { mag: 146479, sign: false }].span();\n    /// \n    ///     let support_vectors: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 314572, sign: false },\n    ///         FP16x16 { mag: 222822, sign: false },\n    ///         FP16x16 { mag: 124518, sign: false },\n    ///         FP16x16 { mag: 327680, sign: false },\n    ///         FP16x16 { mag: 196608, sign: false },\n    ///         FP16x16 { mag: 104857, sign: false },\n    ///         FP16x16 { mag: 294912, sign: false },\n    ///         FP16x16 { mag: 150732, sign: false },\n    ///         FP16x16 { mag: 85196, sign: false },\n    ///         FP16x16 { mag: 334233, sign: false },\n    ///         FP16x16 { mag: 163840, sign: false },\n    ///         FP16x16 { mag: 196608, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let classlabels: Span<usize> = array![0, 1].span();\n    /// \n    ///     let vectors_per_class = Option::Some(array![3, 1].span());\n    /// \n    ///     let post_transform = POST_TRANSFORM::NONE;\n    /// \n    ///     let mut classifier: SVMClassifier<FP16x16> = SVMClassifier {\n    ///         classlabels,\n    ///         coefficients,\n    ///         kernel_params,\n    ///         kernel_type,\n    ///         post_transform,\n    ///         prob_a,\n    ///         prob_b,\n    ///         rho,\n    ///         support_vectors,\n    ///         vectors_per_class,\n    ///     };\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 3].span(),\n    ///         array![\n    ///             FP16x16 { mag: 65536, sign: true },\n    ///             FP16x16 { mag: 52428, sign: true },\n    ///             FP16x16 { mag: 39321, sign: true },\n    ///             FP16x16 { mag: 26214, sign: true },\n    ///             FP16x16 { mag: 13107, sign: true },\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 13107, sign: false },\n    ///             FP16x16 { mag: 26214, sign: false },\n    ///             FP16x16 { mag: 39321, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     return SVMClassifierTrait::predict(ref classifier, X);\n    /// \n    /// }\n    /// // >>> ([0, 0, 0],\n    /// //      [[-2.662655, 2.662655], \n    /// //       [-2.21481, 2.21481], \n    /// //       [-1.766964, 1.766964]])\n    /// \n    /// \n    /// fn example_svm_classifier_binary_softmax_fp64x64() -> (Span<usize>, Tensor<FP64x64>) {\n    ///     let coefficients: Span<FP64x64> = array![\n    ///         FP64x64 { mag: 18446744073709551616, sign: false },\n    ///         FP64x64 { mag: 18446744073709551616, sign: false },\n    ///         FP64x64 { mag: 18446744073709551616, sign: false },\n    ///         FP64x64 { mag: 18446744073709551616, sign: false },\n    ///         FP64x64 { mag: 18446744073709551616, sign: true },\n    ///         FP64x64 { mag: 18446744073709551616, sign: true },\n    ///         FP64x64 { mag: 18446744073709551616, sign: true },\n    ///         FP64x64 { mag: 18446744073709551616, sign: true }\n    ///     ]\n    ///         .span();\n    ///     let kernel_params: Span<FP64x64> = array![\n    ///         FP64x64 { mag: 7054933896252620800, sign: false },\n    ///         FP64x64 { mag: 0, sign: false },\n    ///         FP64x64 { mag: 55340232221128654848, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let kernel_type = KERNEL_TYPE::RBF;\n    ///     let prob_a: Span<FP64x64> = array![FP64x64 { mag: 94799998099962986496, sign: true }].span();\n    ///     let prob_b: Span<FP64x64> = array![FP64x64 { mag: 1180576833385529344, sign: false }].span();\n    ///     let rho: Span<FP64x64> = array![FP64x64 { mag: 3082192501545631744, sign: false }].span();\n    /// \n    ///     let support_vectors: Span<FP64x64> = array![\n    ///         FP64x64 { mag: 3528081300248330240, sign: false },\n    ///         FP64x64 { mag: 19594207602596118528, sign: true },\n    ///         FP64x64 { mag: 9235613999318433792, sign: false },\n    ///         FP64x64 { mag: 10869715877100519424, sign: true },\n    ///         FP64x64 { mag: 5897111318564962304, sign: true },\n    ///         FP64x64 { mag: 1816720038917308416, sign: false },\n    ///         FP64x64 { mag: 4564890528671334400, sign: false },\n    ///         FP64x64 { mag: 21278987070814027776, sign: true },\n    ///         FP64x64 { mag: 7581529597213147136, sign: false },\n    ///         FP64x64 { mag: 10953113834067329024, sign: true },\n    ///         FP64x64 { mag: 24318984989010034688, sign: true },\n    ///         FP64x64 { mag: 30296187483321270272, sign: true },\n    ///         FP64x64 { mag: 10305112258191032320, sign: false },\n    ///         FP64x64 { mag: 17005441559857987584, sign: true },\n    ///         FP64x64 { mag: 11555205301925838848, sign: false },\n    ///         FP64x64 { mag: 2962701975885447168, sign: true },\n    ///         FP64x64 { mag: 11741665981322231808, sign: true },\n    ///         FP64x64 { mag: 15376232508819505152, sign: false },\n    ///         FP64x64 { mag: 13908474645692022784, sign: false },\n    ///         FP64x64 { mag: 7323415394302033920, sign: true },\n    ///         FP64x64 { mag: 3284258824352956416, sign: true },\n    ///         FP64x64 { mag: 11374683084831064064, sign: true },\n    ///         FP64x64 { mag: 9087138148126818304, sign: false },\n    ///         FP64x64 { mag: 8247488946750095360, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let classlabels: Span<usize> = array![0, 1].span();\n    /// \n    ///     let vectors_per_class = Option::Some(array![4, 4].span());\n    ///     let post_transform = POST_TRANSFORM::SOFTMAX;\n    /// \n    ///     let mut classifier: SVMClassifier<FP64x64> = SVMClassifier {\n    ///         classlabels,\n    ///         coefficients,\n    ///         kernel_params,\n    ///         kernel_type,\n    ///         post_transform,\n    ///         prob_a,\n    ///         prob_b,\n    ///         rho,\n    ///         support_vectors,\n    ///         vectors_per_class,\n    ///     };\n    /// \n    ///     let mut X: Tensor<FP64x64> = TensorTrait::new(\n    ///         array![3, 3].span(),\n    ///         array![\n    ///             FP64x64 { mag: 18446744073709551616, sign: true },\n    ///             FP64x64 { mag: 14757395258967642112, sign: true },\n    ///             FP64x64 { mag: 11068046444225730560, sign: true },\n    ///             FP64x64 { mag: 7378697629483821056, sign: true },\n    ///             FP64x64 { mag: 3689348814741910528, sign: true },\n    ///             FP64x64 { mag: 0, sign: false },\n    ///             FP64x64 { mag: 3689348814741910528, sign: false },\n    ///             FP64x64 { mag: 7378697629483821056, sign: false },\n    ///             FP64x64 { mag: 11068046444225730560, sign: false }\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    /// \n    ///     return SVMClassifierTrait::predict(ref classifier, X);\n    /// \n    /// }\n    /// >>> ([0, 1, 1],\n    ///      [[0.728411, 0.271589], \n    ///       [0.484705, 0.515295], \n    ///       [0.274879, 0.725121]])\n    /// ```\n    fn predict(ref self: SVMClassifier<T>, X: Tensor<T>) -> (Span<usize>, Tensor<T>);\n}\n\nimpl SVMClassifierImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n    +NNTrait<T>,\n> of SVMClassifierTrait<T> {\n    fn predict(ref self: SVMClassifier<T>, X: Tensor<T>) -> (Span<usize>, Tensor<T>) {\n        let mut vector_count_ = 0;\n        let class_count_ = max(self.classlabels.len(), 1);\n        let mut starting_vector_: Array<usize> = array![];\n\n        let (vectors_per_class_, starting_vector_) = match self.vectors_per_class {\n            Option::Some(vectors_per_class) => {\n                let mut i = 0;\n                while i != vectors_per_class.len() {\n                    starting_vector_.append(vector_count_);\n                    vector_count_ += *vectors_per_class.at(i);\n                    i += 1;\n                };\n\n                (vectors_per_class, starting_vector_.span())\n            },\n            Option::None => { (array![].span(), array![].span()) },\n        };\n\n        let (mode, kernel_type_, sv, coefs) = if vector_count_ > 0 {\n            let mode = MODE::SVM_SVC;\n            let kernel_type_ = self.kernel_type;\n            let sv = TensorTrait::new(\n                array![vector_count_, self.support_vectors.len() / vector_count_].span(),\n                self.support_vectors\n            );\n            let coefs = TensorTrait::new(\n                array![self.coefficients.len() / vector_count_, vector_count_].span(),\n                self.coefficients\n            );\n            (mode, kernel_type_, sv, coefs)\n        } else {\n            let mode = MODE::SVM_LINEAR;\n            let kernel_type_ = KERNEL_TYPE::LINEAR;\n            let sv = TensorTrait::new(\n                array![self.support_vectors.len()].span(), self.support_vectors\n            );\n            let coefs = TensorTrait::new(\n                array![class_count_, self.coefficients.len() / class_count_].span(),\n                self.coefficients\n            );\n            (mode, kernel_type_, sv, coefs)\n        };\n\n        let weights_are_all_positive_ = (min(self.coefficients) >= NumberTrait::zero());\n\n        // SVM\n        let (res, votes) = match mode {\n            MODE::SVM_LINEAR => {\n                let mut res: Array<T> = array![];\n                let mut n = 0;\n                while n != *X.shape.at(0) {\n                    let mut x_n = get_row(@X, n);\n                    let scores = run_linear(ref self, x_n, coefs, class_count_, kernel_type_);\n                    let mut i = 0;\n                    while i != scores.len() {\n                        res.append(*scores.at(i));\n                        i += 1;\n                    };\n\n                    n += 1;\n                };\n\n                (\n                    TensorTrait::new(array![*X.shape.at(0), class_count_].span(), res.span()),\n                    Option::None\n                )\n            },\n            MODE::SVM_SVC => {\n                let mut res: Array<T> = array![];\n                let mut votes: Array<T> = array![];\n                let mut n = 0;\n                while n != *X.shape.at(0) {\n                    let mut x_n = get_row(@X, n);\n                    let (scores, mut vote) = run_svm(\n                        ref self,\n                        x_n,\n                        sv,\n                        vector_count_,\n                        kernel_type_,\n                        class_count_,\n                        starting_vector_,\n                        coefs,\n                        vectors_per_class_\n                    );\n                    let mut i = 0;\n                    while i != scores.len() {\n                        res.append(*scores.at(i));\n                        i += 1;\n                    };\n\n                    let mut i = 0;\n                    while i != vote.len() {\n                        votes.append(vote.at(i));\n                        i += 1;\n                    };\n\n                    n += 1;\n                };\n\n                (\n                    TensorTrait::new(\n                        array![*X.shape.at(0), class_count_ * (class_count_ - 1) / 2].span(),\n                        res.span()\n                    ),\n                    Option::Some(\n                        TensorTrait::new(array![*X.shape.at(0), class_count_].span(), votes.span())\n                    )\n                )\n            },\n        };\n\n        // Proba\n        let (scores, has_proba) = match mode {\n            MODE::SVM_LINEAR => { (res, false) },\n            MODE::SVM_SVC => {\n                let (scores, has_proba) = if self.prob_a.len() > 0 {\n                    let mut scores: Array<T> = array![];\n                    let mut n = 0;\n                    while n != *res.shape.at(0) {\n                        let res_n = get_row(@res, n);\n                        let mut s = probablities(ref self, res_n, class_count_);\n\n                        let mut i = 0;\n                        while i != s.len() {\n                            scores.append(s.at(i));\n                            i += 1;\n                        };\n\n                        n += 1;\n                    };\n                    (\n                        TensorTrait::new(\n                            array![*res.shape.at(0), scores.len() / *res.shape.at(0)].span(),\n                            scores.span()\n                        ),\n                        true\n                    )\n                } else {\n                    (res, false)\n                };\n\n                (scores, has_proba)\n            },\n        };\n\n        // Finalization \n        let mut labels: Array<usize> = array![];\n        let mut final_scores: Array<T> = array![];\n\n        let mut n = 0;\n        while n != *scores.shape.at(0) {\n            let mut scores_n = get_row(@scores, n);\n            match votes {\n                Option::Some(votes) => {\n                    let mut votes_n = get_row(@votes, n);\n                    let (label, new_scores) = compute_final_scores(\n                        ref self,\n                        votes_n,\n                        scores_n,\n                        weights_are_all_positive_,\n                        has_proba,\n                        self.classlabels\n                    );\n\n                    let mut i = 0;\n                    while i != new_scores.data.len() {\n                        final_scores.append(*new_scores.data.at(i));\n                        i += 1;\n                    };\n\n                    labels.append(label);\n                },\n                Option::None => {\n                    let (label, new_scores) = compute_final_scores(\n                        ref self,\n                        array![].span(),\n                        scores_n,\n                        weights_are_all_positive_,\n                        has_proba,\n                        self.classlabels\n                    );\n\n                    let mut i = 0;\n                    while i != new_scores.data.len() {\n                        final_scores.append(*new_scores.data.at(i));\n                        i += 1;\n                    };\n\n                    labels.append(label);\n                },\n            }\n\n            n += 1;\n        };\n\n        let labels = labels.span();\n\n        // Labels\n        if self.classlabels.len() > 0 {\n            let mut class_labels: Array<usize> = array![];\n            let mut i = 0;\n            while i != labels.len() {\n                class_labels.append(*self.classlabels.at(*labels.at(i)));\n                i += 1;\n            };\n\n            return (\n                class_labels.span(),\n                TensorTrait::new(\n                    array![*X.shape.at(0), final_scores.len() / *X.shape.at(0)].span(),\n                    final_scores.span()\n                )\n            );\n        }\n\n        (\n            labels,\n            TensorTrait::new(\n                array![*X.shape.at(0), final_scores.len() / *X.shape.at(0)].span(),\n                final_scores.span()\n            )\n        )\n    }\n}\n\nfn run_svm<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n    +PartialOrd<T>,\n>(\n    ref self: SVMClassifier<T>,\n    X: Span<T>,\n    sv: Tensor<T>,\n    vector_count_: usize,\n    kernel: KERNEL_TYPE,\n    class_count_: usize,\n    starting_vector_: Span<usize>,\n    coefs: Tensor<T>,\n    vectors_per_class_: Span<usize>\n) -> (Array<T>, NullableVec<T>) {\n    let mut evals = 0;\n    let mut kernels: Array<T> = array![];\n\n    let mut j = 0;\n    while j != vector_count_ {\n        let sv_j = get_row(@sv, j);\n        kernels.append(kernel_dot(self.kernel_params, X, sv_j, kernel));\n        j += 1;\n    };\n\n    let kernels = kernels.span();\n\n    let mut scores: Array<T> = array![];\n    let mut votes = VecTrait::new();\n    VecTrait::set(ref votes, class_count_ - 1, NumberTrait::zero());\n\n    let mut i = 0;\n    while i != class_count_ {\n        let si_i = *starting_vector_.at(i);\n        let class_i_sc = *vectors_per_class_.at(i);\n\n        let mut j = i + 1;\n        while j != class_count_ {\n            let si_j = *starting_vector_.at(j);\n            let class_j_sc = *vectors_per_class_.at(j);\n\n            let s1 = dot_start_end(\n                coefs.data,\n                kernels,\n                (j - 1) * *coefs.shape.at(0) + si_i,\n                (j - 1) * *coefs.shape.at(0) + si_i + class_i_sc,\n                si_i,\n                si_i + class_i_sc\n            );\n\n            let s2 = dot_start_end(\n                coefs.data,\n                kernels,\n                i * *coefs.shape.at(0) + si_j,\n                i * *coefs.shape.at(0) + si_j + class_j_sc,\n                si_j,\n                si_j + class_j_sc\n            );\n\n            let s = *self.rho.at(evals) + s1 + s2;\n            scores.append(s);\n\n            if s > NumberTrait::zero() {\n                VecTrait::set(ref votes, i, VecTrait::at(ref votes, i) + NumberTrait::one());\n            } else {\n                VecTrait::set(ref votes, j, VecTrait::at(ref votes, j) + NumberTrait::one());\n            }\n\n            evals += 1;\n            j += 1;\n        };\n\n        i += 1;\n    };\n\n    (scores, votes)\n}\n\nfn run_linear<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n>(\n    ref self: SVMClassifier<T>,\n    X: Span<T>,\n    coefs: Tensor<T>,\n    class_count_: usize,\n    kernel: KERNEL_TYPE\n) -> Array<T> {\n    let mut scores: Array<T> = array![];\n\n    let mut j = 0;\n    while j != class_count_ {\n        let coefs_j = get_row(@coefs, j);\n\n        let d = kernel_dot(self.kernel_params, X, coefs_j, kernel);\n\n        let score = *self.rho.at(0) + d;\n\n        scores.append(score);\n        j += 1;\n    };\n\n    scores\n}\n\nfn compute_final_scores<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +NNTrait<T>,\n    +Into<usize, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n    +Div<T>,\n    +PartialOrd<T>,\n>(\n    ref self: SVMClassifier<T>,\n    votes: Span<T>,\n    scores: Span<T>,\n    weights_are_all_positive_: bool,\n    has_proba: bool,\n    classlabels: Span<usize>\n) -> (usize, Tensor<T>) {\n    let (max_class, max_weight) = if votes.len() > 0 {\n        let max_class = argmax_span(votes);\n        let max_weight = *votes.at(max_class);\n        (max_class, max_weight)\n    } else {\n        let max_class = argmax_span(scores);\n        let max_weight = *scores.at(max_class);\n        (max_class, max_weight)\n    };\n\n    let (label, write_additional_scores) = if self.rho.len() == 1 {\n        let (label, write_additional_scores) = set_score_svm(\n            max_weight, max_class, weights_are_all_positive_, has_proba, classlabels, 1, 0\n        );\n        (label, write_additional_scores)\n    } else if classlabels.len() > 0 {\n        let label = *classlabels.at(max_class);\n        (label, 4)\n    } else {\n        (max_class, 4)\n    };\n\n    let new_scores = write_scores(\n        scores.len(),\n        TensorTrait::new(array![scores.len()].span(), scores),\n        self.post_transform,\n        write_additional_scores\n    );\n\n    (label, new_scores)\n}\n\nfn write_scores<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +NNTrait<T>,\n    +Neg<T>,\n    +Sub<T>,\n>(\n    n_classes: usize, scores: Tensor<T>, post_transform: POST_TRANSFORM, add_second_class: usize\n) -> Tensor<T> {\n    let new_scores = if n_classes >= 2 {\n        let new_scores = match post_transform {\n            POST_TRANSFORM::NONE => scores,\n            POST_TRANSFORM::SOFTMAX => NNTrait::softmax(@scores, Option::Some(0)),\n            POST_TRANSFORM::LOGISTIC => NNTrait::sigmoid(@scores),\n            POST_TRANSFORM::SOFTMAXZERO => NNTrait::softmax_zero(@scores, 0),\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n        new_scores\n    } else { //if n_classes == 1\n        let new_scores = match post_transform {\n            POST_TRANSFORM::NONE => {\n                let scores = if add_second_class == 0 || add_second_class == 1 {\n                    TensorTrait::new(\n                        array![2].span(),\n                        array![NumberTrait::one() - *scores.data.at(0), *scores.data.at(0)].span()\n                    )\n                } else if add_second_class == 2 || add_second_class == 3 {\n                    TensorTrait::new(\n                        array![2].span(), array![-*scores.data.at(0), *scores.data.at(0)].span()\n                    )\n                } else {\n                    TensorTrait::new(array![1].span(), array![*scores.data.at(0)].span())\n                };\n\n                scores\n            },\n            POST_TRANSFORM::SOFTMAX => {\n                let scores = if add_second_class == 0 || add_second_class == 1 {\n                    TensorTrait::new(\n                        array![2].span(),\n                        array![NumberTrait::one() - *scores.data.at(0), *scores.data.at(0)].span()\n                    )\n                } else if add_second_class == 2 || add_second_class == 3 {\n                    //\n                    NNTrait::softmax(\n                        @TensorTrait::new(\n                            array![2].span(), array![-*scores.data.at(0), *scores.data.at(0)].span()\n                        ),\n                        Option::Some(0)\n                    )\n                } else {\n                    TensorTrait::new(array![1].span(), array![*scores.data.at(0)].span())\n                };\n\n                scores\n            },\n            POST_TRANSFORM::LOGISTIC => {\n                let scores = if add_second_class == 0 || add_second_class == 1 {\n                    TensorTrait::new(\n                        array![2].span(),\n                        array![NumberTrait::one() - *scores.data.at(0), *scores.data.at(0)].span()\n                    )\n                } else if add_second_class == 2 || add_second_class == 3 {\n                    //\n                    NNTrait::sigmoid(\n                        @TensorTrait::new(\n                            array![2].span(), array![-*scores.data.at(0), *scores.data.at(0)].span()\n                        )\n                    )\n                } else {\n                    TensorTrait::new(array![1].span(), array![*scores.data.at(0)].span())\n                };\n\n                scores\n            },\n            POST_TRANSFORM::SOFTMAXZERO => {\n                let scores = if add_second_class == 0 || add_second_class == 1 {\n                    TensorTrait::new(\n                        array![2].span(),\n                        array![NumberTrait::one() - *scores.data.at(0), *scores.data.at(0)].span()\n                    )\n                } else if add_second_class == 2 || add_second_class == 3 {\n                    //\n                    NNTrait::softmax_zero(\n                        @TensorTrait::new(\n                            array![2].span(), array![-*scores.data.at(0), *scores.data.at(0)].span()\n                        ),\n                        0\n                    )\n                } else {\n                    TensorTrait::new(array![1].span(), array![*scores.data.at(0)].span())\n                };\n\n                scores\n            },\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not applicable here.'),\n        };\n        new_scores\n    };\n\n    new_scores\n}\n\nfn set_score_svm<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +PartialOrd<T>,\n>(\n    max_weight: T,\n    maxclass: usize,\n    weights_are_all_positive_: bool,\n    has_proba: bool,\n    classlabels: Span<usize>,\n    posclass: usize,\n    negclass: usize\n) -> (usize, usize) {\n    let mut write_additional_scores = 0;\n\n    if classlabels.len() == 2 {\n        write_additional_scores = 2;\n        if !has_proba {\n            if weights_are_all_positive_ && max_weight >= NumberTrait::half() {\n                return (*classlabels.at(1), write_additional_scores);\n            };\n        };\n\n        return (*classlabels.at(maxclass), write_additional_scores);\n    }\n    if max_weight >= NumberTrait::zero() {\n        return (posclass, write_additional_scores);\n    };\n\n    (negclass, write_additional_scores)\n}\n\nfn argmax_span<T, +Drop<T>, +Copy<T>, +PartialOrd<T>,>(span: Span<T>) -> usize {\n    let mut max = 0;\n    let mut i = 0;\n    while i != span.len() {\n        if *span.at(i) > *span.at(max) {\n            max = i;\n        }\n\n        i += 1;\n    };\n\n    max\n}\n\nfn probablities<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Into<usize, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n    +Div<T>,\n    +PartialOrd<T>,\n>(\n    ref self: SVMClassifier<T>, scores: Span<T>, class_count_: usize\n) -> NullableVec<T> {\n    let mut probsp2: MutMatrix<T> = MutMatrixImpl::new(class_count_, class_count_);\n    let mut index = 0;\n    let mut i = 0;\n    while i != class_count_ {\n        let mut j = i + 1;\n        while j != class_count_ {\n            let val1 = sigmoid_probability(\n                *scores.at(index), *self.prob_a.at(index), *self.prob_b.at(index)\n            );\n\n            let mut val2 = NumberTrait::min(\n                val1, NumberTrait::one()\n            ); // ONNX : min(val2, (1 - 1.0e-7))\n\n            probsp2.set(i, j, val2);\n            probsp2.set(j, i, NumberTrait::one() - val2);\n\n            j += 1;\n            index += 1;\n        };\n\n        i += 1;\n    };\n\n    multiclass_probability(class_count_, ref probsp2)\n}\n\nfn multiclass_probability<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +Add<T>,\n    +Mul<T>,\n    +Div<T>,\n    +Sub<T>,\n    +Neg<T>,\n    +AddEq<T>,\n    +Into<usize, MAG>,\n>(\n    k: usize, ref R: MutMatrix<T>\n) -> NullableVec<T> {\n    let max_iter = max(100, k);\n    let k_fp = NumberTrait::<T>::new_unscaled(k.into(), false);\n\n    let mut Q: MutMatrix<T> = MutMatrixImpl::new(k, k);\n    MutMatrixImpl::set(ref Q, k - 1, k - 1, NumberTrait::zero());\n\n    let mut P = VecTrait::new();\n    VecTrait::set(ref P, k - 1, NumberTrait::zero());\n\n    let a: usize = 100;\n    let eps = (NumberTrait::half() / NumberTrait::new_unscaled(a.into(), false)) / k_fp;\n    let mut t = 0;\n\n    while t != k {\n        VecTrait::set(ref P, t, NumberTrait::one() / k_fp);\n\n        let mut i = 0;\n        let mut acc1 = NumberTrait::zero();\n        while i != t {\n            let r_i = MutMatrixImpl::at(ref R, i, t);\n            acc1 += r_i * r_i;\n            i += 1;\n        };\n\n        MutMatrixImpl::set(ref Q, t, t, acc1);\n\n        let mut i = 0;\n        while i != t {\n            MutMatrixImpl::set(ref Q, t, i, MutMatrixImpl::at(ref Q, i, t));\n            i += 1;\n        };\n\n        let mut i = t + 1;\n        let mut acc2 = NumberTrait::zero();\n        while i != k {\n            let r_i = MutMatrixImpl::at(ref R, i, t);\n            acc2 += r_i * r_i;\n            i += 1;\n        };\n\n        MutMatrixImpl::set(ref Q, t, t, acc1 + acc2);\n\n        let mut i = t + 1;\n        let mut acc = NumberTrait::zero();\n        while i != k {\n            acc += -MutMatrixImpl::at(ref R, i, t) * MutMatrixImpl::at(ref R, t, i);\n            i += 1;\n        };\n\n        let mut i = t + 1;\n        while i != k {\n            MutMatrixImpl::set(ref Q, t, i, acc);\n            i += 1;\n        };\n\n        t += 1;\n    };\n\n    let mut i = 0;\n    while i != max_iter {\n        let mut Qp = MutMatrixImpl::matrix_vector_product(ref Q, ref P);\n        let mut pQp = dot(ref P, ref Qp);\n\n        let mut max_error = NumberTrait::zero();\n        let mut t = 0;\n        while t != k {\n            let error = NumberTrait::abs(Qp.at(t) - pQp);\n            if error > max_error {\n                max_error = error;\n            }\n\n            t += 1;\n        };\n\n        if max_error < eps {\n            break;\n        }\n\n        let mut t = 0;\n        while t != k {\n            let diff = (-VecTrait::at(ref Qp, t) + pQp) / MutMatrixImpl::at(ref Q, t, t);\n            VecTrait::set(ref P, t, VecTrait::at(ref P, t) + diff);\n\n            pQp =\n                (pQp\n                    + diff\n                        * (diff * MutMatrixImpl::at(ref Q, t, t)\n                            + (NumberTrait::one() + NumberTrait::one()) * VecTrait::at(ref Qp, t)))\n                / ((NumberTrait::one() + diff) * (NumberTrait::one() + diff));\n\n            div_element_wise(ref P, NumberTrait::one() + diff);\n\n            Qp_computation(ref Q, ref Qp, diff, t);\n\n            t += 1;\n        };\n\n        i += 1;\n    };\n\n    P\n}\n\n/// Computation of the matrix Qb in the multiclass_probability computation\n///\n/// Qp[:] = (Qp + diff * Q[t, :]) / (1 + diff)\n///\nfn Qp_computation<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +AddEq<T>\n>(\n    ref Q: MutMatrix<T>, ref Qp: NullableVec<T>, diff: T, t: usize\n) {\n    let m = Qp.len;\n\n    let mut i = 0_usize;\n    while i != m {\n        let elem = (VecTrait::at(ref Qp, i) + diff * MutMatrixImpl::at(ref Q, t, i))\n            / (NumberTrait::one() + diff);\n\n        VecTrait::set(ref Qp, i, elem);\n        i += 1;\n    };\n}\n\nfn sigmoid_probability<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +Add<T>,\n    +Mul<T>,\n    +Div<T>,\n    +Sub<T>,\n    +Neg<T>,\n>(\n    score: T, prob_a: T, prob_b: T\n) -> T {\n    let val = score * prob_a + prob_b;\n\n    let mut v = NumberTrait::one()\n        / (NumberTrait::one() + NumberTrait::exp(-NumberTrait::abs(val)));\n\n    v = if val < NumberTrait::zero() {\n        NumberTrait::one() - v\n    } else {\n        v\n    };\n\n    NumberTrait::one() - v\n}\n\nfn max(a: usize, b: usize) -> usize {\n    if a > b {\n        return a;\n    };\n\n    b\n}\n\nfn min<T, +Copy<T>, +Drop<T>, +PartialOrd<T>,>(a: Span<T>) -> T {\n    let mut min = *a.at(0);\n\n    let mut i = 0;\n    while i != a.len() {\n        if min > *a.at(i) {\n            min = *a.at(i);\n        }\n\n        i += 1;\n    };\n\n    min\n}\n\nfn dot_start_end<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Add<T>, +TensorTrait<T>, +AddEq<T>, +Mul<T>,\n>(\n    pA: Span<T>, pB: Span<T>, a_start: usize, a_end: usize, b_start: usize, b_end: usize\n) -> T {\n    let mut sum = NumberTrait::zero();\n    let mut index_a = a_start;\n    let mut index_b = b_start;\n    while index_a != a_end && index_b != b_end {\n        sum = sum + *pA.at(index_a) * *pB.at(index_b);\n        index_a += 1;\n        index_b += 1;\n    };\n\n    sum\n}\n\nfn sv_dot<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Add<T>, +TensorTrait<T>, +AddEq<T>, +Mul<T>,\n>(\n    pA: Span<T>, pB: Span<T>\n) -> T {\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != pA.len() {\n        sum = sum + *pA.at(i) * *pB.at(i);\n        i += 1;\n    };\n\n    sum\n}\n\nfn squared_diff<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +AddEq<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    pA: Span<T>, pB: Span<T>\n) -> T {\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != pA.len() {\n        sum = sum + (*pA.at(i) - *pB.at(i)).pow(NumberTrait::one() + NumberTrait::one());\n        i += 1;\n    };\n\n    sum\n}\n\nfn dot<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Mul<T>, +AddEq<T>, +Add<T>, +Div<T>>(\n    ref self: NullableVec<T>, ref vec: NullableVec<T>\n) -> T {\n    assert(self.len == vec.len, 'wrong vec len for dot prod');\n    let n = self.len;\n    let mut sum: T = NumberTrait::zero();\n    let mut i = 0_usize;\n    while i != n {\n        sum += self.at(i) * vec.at(i);\n        i += 1;\n    };\n\n    sum\n}\n\nfn div_element_wise<T, MAG, +Mul<T>, +Add<T>, +Div<T>, +NumberTrait<T, MAG>, +Drop<T>, +Copy<T>>(\n    ref self: NullableVec<T>, elem: T\n) {\n    let m = self.len;\n\n    let mut i = 0_usize;\n    while i != m {\n        VecTrait::set(ref self, i, VecTrait::at(ref self, i) / elem);\n        i += 1;\n    };\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/svm/svm_regressor.cairo",
        "content": "use core::traits::TryInto;\nuse core::array::ArrayTrait;\nuse core::array::SpanTrait;\nuse core::traits::Into;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, BoolTensor\n};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse core::debug::PrintTrait;\nuse orion::operators::nn::{NNTrait, FP16x16NN};\nuse orion::utils::get_row;\nuse orion::operators::ml::POST_TRANSFORM;\n\nuse orion::operators::ml::svm::core::{kernel_dot, KERNEL_TYPE};\n\n#[derive(Copy, Drop, Destruct)]\nstruct SVMRegressor<T> {\n    coefficients: Span<T>,\n    kernel_params: Span<T>,\n    kernel_type: KERNEL_TYPE,\n    n_supports: usize,\n    one_class: usize,\n    post_transform: POST_TRANSFORM,\n    rho: Span<T>,\n    support_vectors: Span<T>,\n}\n\n#[derive(Copy, Drop)]\nenum MODE {\n    SVM_LINEAR,\n    SVM_SVC,\n}\n\n/// Trait\n///\n/// predict - Returns the regressed values for each input in N.\ntrait SVMRegressorTrait<T> {\n    /// # SVMRegressorTrait::predict\n    ///\n    /// ```rust \n    ///    fn predict(ref self: SVMRegressor<T>, X: Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Support Vector Machine regression prediction and one-class SVM anomaly detection.\n    /// \n    /// ## Args\n    ///\n    /// * `self`: SVMRegressor<T> - A SVMRegressor object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * Tensor<T> containing the Support Vector Machine regression prediction and one-class SVM anomaly detection of the input X.\n    ///\n    /// ## Type Constraints\n    ///\n    /// `SVMRegressor` and `X` must be fixed points\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\n    /// use orion::operators::tensor::FP16x16TensorPartialEq;\n    /// \n    /// use orion::operators::ml::svm::svm_regressor::{SVMRegressorTrait, POST_TRANSFORM, SVMRegressor};\n    /// use orion::operators::ml::svm::core::{KERNEL_TYPE};\n    /// \n    /// fn example_svm_regressor_linear() -> Tensor<FP16x16> {\n    ///     let coefficients: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 65536, sign: false },\n    ///         FP16x16 { mag: 65536, sign: true },\n    ///         FP16x16 { mag: 54959, sign: false },\n    ///         FP16x16 { mag: 54959, sign: true },\n    ///         FP16x16 { mag: 29299, sign: false },\n    ///         FP16x16 { mag: 65536, sign: true },\n    ///         FP16x16 { mag: 36236, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let n_supports: usize = 7;\n    ///     let one_class: usize = 0;\n    ///     let rho: Span<FP16x16> = array![FP16x16 { mag: 35788, sign: false }].span();\n    ///     let support_vectors: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 8421, sign: true },\n    ///         FP16x16 { mag: 5842, sign: false },\n    ///         FP16x16 { mag: 4510, sign: false },\n    ///         FP16x16 { mag: 5202, sign: true },\n    ///         FP16x16 { mag: 14783, sign: true },\n    ///         FP16x16 { mag: 17380, sign: true },\n    ///         FP16x16 { mag: 60595, sign: false },\n    ///         FP16x16 { mag: 1674, sign: true },\n    ///         FP16x16 { mag: 38669, sign: true },\n    ///         FP16x16 { mag: 63803, sign: false },\n    ///         FP16x16 { mag: 87720, sign: true },\n    ///         FP16x16 { mag: 22236, sign: false },\n    ///         FP16x16 { mag: 61816, sign: false },\n    ///         FP16x16 { mag: 34267, sign: true },\n    ///         FP16x16 { mag: 36418, sign: false },\n    ///         FP16x16 { mag: 27471, sign: false },\n    ///         FP16x16 { mag: 28421, sign: false },\n    ///         FP16x16 { mag: 69270, sign: true },\n    ///         FP16x16 { mag: 152819, sign: false },\n    ///         FP16x16 { mag: 4065, sign: false },\n    ///         FP16x16 { mag: 62274, sign: true }\n    ///     ]\n    ///         .span();\n    ///     let post_transform = POST_TRANSFORM::NONE;\n    ///     let kernel_params: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 27812, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 196608, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let kernel_type = KERNEL_TYPE::LINEAR;\n    /// \n    ///     let mut regressor: SVMRegressor<FP16x16> = SVMRegressor {\n    ///         coefficients,\n    ///         kernel_params,\n    ///         kernel_type,\n    ///         n_supports,\n    ///         one_class,\n    ///         post_transform,\n    ///         rho,\n    ///         support_vectors,\n    ///     };\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 3].span(),\n    ///         array![\n    ///             FP16x16 { mag: 32768, sign: true },\n    ///             FP16x16 { mag: 26214, sign: true },\n    ///             FP16x16 { mag: 19660, sign: true },\n    ///             FP16x16 { mag: 13107, sign: true },\n    ///             FP16x16 { mag: 6553, sign: true },\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 6553, sign: false },\n    ///             FP16x16 { mag: 13107, sign: false },\n    ///             FP16x16 { mag: 19660, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     return SVMRegressorTrait::predict(ref regressor, X);\n    /// }\n    /// \n    /// >>> [[-0.468206], [0.227487], [0.92318]]\n    /// ```\n    ///\n    ///\n    fn predict(ref self: SVMRegressor<T>, X: Tensor<T>) -> Tensor<T>;\n}\n\nimpl SVMRegressorImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Neg<T>,\n    +Sub<T>,\n    +NNTrait<T>,\n> of SVMRegressorTrait<T> {\n    fn predict(ref self: SVMRegressor<T>, X: Tensor<T>) -> Tensor<T> {\n        let (mode_, kernel_type_, sv) = if self.n_supports > 0 {\n            let mode_ = MODE::SVM_SVC;\n            let kernel_type_ = self.kernel_type;\n            let sv = TensorTrait::new(\n                array![self.n_supports, self.support_vectors.len() / self.n_supports].span(),\n                self.support_vectors\n            ); //self.atts.support_vectors.reshape((self.atts.n_supports, -1))\n            (mode_, kernel_type_, sv)\n        } else {\n            let mode_ = MODE::SVM_LINEAR;\n            let kernel_type_ = KERNEL_TYPE::LINEAR;\n            let sv = TensorTrait::new(\n                array![self.support_vectors.len()].span(), self.support_vectors\n            );\n            (mode_, kernel_type_, sv)\n        };\n\n        let mut z: Array<T> = array![];\n        let mut n = 0;\n        while n != *X.shape.at(0) {\n            let mut s = NumberTrait::zero();\n            match mode_ {\n                MODE::SVM_LINEAR => {\n                    let mut x_n = get_row(@X, n);\n                    s = kernel_dot(self.kernel_params, x_n, self.coefficients, kernel_type_);\n                    s += *self.rho.at(0);\n                },\n                MODE::SVM_SVC => {\n                    let mut x_n = get_row(@X, n);\n                    let mut j = 0;\n                    while j != self.n_supports {\n                        let mut sv_j = get_row(@sv, j);\n                        let d = kernel_dot(self.kernel_params, x_n, sv_j, kernel_type_);\n                        s += *self.coefficients.at(j) * d;\n                        j += 1;\n                    };\n\n                    s += *self.rho.at(0);\n                },\n            }\n            if self.one_class == 1 {\n                let elem = if s > NumberTrait::zero() {\n                    NumberTrait::one()\n                } else {\n                    -NumberTrait::one()\n                };\n                z.append(elem);\n            } else {\n                z.append(s);\n            };\n\n            n += 1;\n        };\n\n        // Post Transform\n        let mut score = TensorTrait::new(array![*X.shape.at(0)].span(), z.span());\n\n        score = match self.post_transform {\n            POST_TRANSFORM::NONE => score,\n            POST_TRANSFORM::SOFTMAX => NNTrait::softmax(@score, Option::Some(1)),\n            POST_TRANSFORM::LOGISTIC => NNTrait::sigmoid(@score),\n            POST_TRANSFORM::SOFTMAXZERO => NNTrait::softmax_zero(@score, 1),\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n\n        score\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/tree_ensemble.cairo",
        "content": "mod core;\nmod tree_ensemble_classifier;\nmod tree_ensemble_regressor;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/tree_ensemble/core.cairo",
        "content": "use alexandria_data_structures::array_ext::SpanTraitExt;\nuse alexandria_merkle_tree::merkle_tree::{pedersen::PedersenHasherImpl};\nuse alexandria_data_structures::array_ext::ArrayTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, U32Tensor};\nuse orion::utils::get_row;\n\n#[derive(Copy, Drop, Destruct)]\nstruct TreeEnsembleAttributes<T> {\n    nodes_falsenodeids: Span<usize>,\n    nodes_featureids: Span<usize>,\n    nodes_missing_value_tracks_true: Span<usize>,\n    nodes_modes: Span<NODE_MODES>,\n    nodes_nodeids: Span<usize>,\n    nodes_treeids: Span<usize>,\n    nodes_truenodeids: Span<usize>,\n    nodes_values: Span<T>,\n}\n\n#[derive(Destruct)]\nstruct TreeEnsemble<T> {\n    atts: TreeEnsembleAttributes<T>,\n    tree_ids: Span<usize>,\n    root_index: Felt252Dict<usize>,\n    node_index: Felt252Dict<usize>, // index is pedersen hash of tree_id and nid.\n}\n\n#[derive(Copy, Drop)]\nenum NODE_MODES {\n    BRANCH_LEQ,\n    BRANCH_LT,\n    BRANCH_GTE,\n    BRANCH_GT,\n    BRANCH_EQ,\n    BRANCH_NEQ,\n    LEAF\n}\n\n#[generate_trait]\nimpl TreeEnsembleImpl<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +PartialOrd<T>, +PartialEq<T>\n> of TreeEnsembleTrait<T> {\n    fn leaf_index_tree(ref self: TreeEnsemble<T>, x: Span<T>, tree_id: usize) -> usize {\n        let mut index: usize = self.root_index.get(tree_id.into());\n\n        loop {\n            // Loop breaker\n            match *self.atts.nodes_modes.at(index) {\n                NODE_MODES::BRANCH_LEQ => {},\n                NODE_MODES::BRANCH_LT => {},\n                NODE_MODES::BRANCH_GTE => {},\n                NODE_MODES::BRANCH_GT => {},\n                NODE_MODES::BRANCH_EQ => {},\n                NODE_MODES::BRANCH_NEQ => {},\n                NODE_MODES::LEAF => { break; },\n            };\n\n            let x_value = *x.at(*(self.atts.nodes_featureids).at(index));\n            let r = if x_value.is_nan() {\n                *self.atts.nodes_missing_value_tracks_true.at(index) >= 1\n            } else {\n                match *self.atts.nodes_modes.at(index) {\n                    NODE_MODES::BRANCH_LEQ => x_value <= *self.atts.nodes_values[index],\n                    NODE_MODES::BRANCH_LT => x_value < *self.atts.nodes_values[index],\n                    NODE_MODES::BRANCH_GTE => x_value >= *self.atts.nodes_values[index],\n                    NODE_MODES::BRANCH_GT => x_value > *self.atts.nodes_values[index],\n                    NODE_MODES::BRANCH_EQ => x_value == *self.atts.nodes_values[index],\n                    NODE_MODES::BRANCH_NEQ => x_value != *self.atts.nodes_values[index],\n                    NODE_MODES::LEAF => {\n                        panic(array!['Unexpected rule for node index ', index.into()])\n                    },\n                }\n            };\n\n            let nid = if r {\n                *self.atts.nodes_truenodeids[index]\n            } else {\n                *self.atts.nodes_falsenodeids[index]\n            };\n\n            // key of TreeEnsemble.node_index is pedersen hash of tree_id and nid.\n            let mut key = PedersenHasherImpl::new();\n            let key: felt252 = key.hash(tree_id.into(), nid.into());\n\n            index = self.node_index.get(key);\n        };\n\n        index\n    }\n\n    fn leave_index_tree(ref self: TreeEnsemble<T>, x: Tensor<T>) -> Tensor<usize> {\n        let mut outputs: Array<usize> = array![];\n\n        let mut i: usize = 0;\n        let breaker: usize = *x.shape[0];\n        while i != breaker {\n            let row_data: Span<T> = get_row(@x, i);\n            let mut outs: Array<usize> = array![];\n            let mut tree_ids = self.tree_ids;\n            loop {\n                match tree_ids.pop_front() {\n                    Option::Some(tree_id) => {\n                        outs\n                            .append(\n                                TreeEnsembleImpl::<T>::leaf_index_tree(ref self, row_data, *tree_id)\n                            )\n                    },\n                    Option::None => { break; }\n                };\n            };\n\n            outputs.append_all(ref outs);\n            i += 1;\n        };\n\n        TensorTrait::new(array![*x.shape[0], self.tree_ids.len()].span(), outputs.span())\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/tree_ensemble/tree_ensemble_classifier.cairo",
        "content": "use core::array::ArrayTrait;\nuse core::clone::Clone;\nuse core::box::BoxTrait;\nuse core::traits::Into;\nuse core::option::OptionTrait;\nuse orion::operators::matrix::MutMatrixTrait;\nuse core::array::SpanTrait;\nuse core::nullable::NullableTrait;\nuse core::dict::Felt252DictTrait;\nuse core::dict::Felt252DictEntryTrait;\nuse core::nullable::{match_nullable, FromNullableResult};\n\nuse orion::operators::tensor::{Tensor, TensorTrait};\nuse orion::operators::ml::tree_ensemble::core::{TreeEnsemble, TreeEnsembleImpl, TreeEnsembleTrait};\nuse orion::numbers::NumberTrait;\nuse orion::utils::get_row;\n\nuse alexandria_merkle_tree::merkle_tree::{pedersen::PedersenHasherImpl};\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n\nuse orion::operators::matrix::{MutMatrix, MutMatrixImpl};\nuse orion::operators::vec::{VecTrait, NullableVec, NullableVecImpl};\nuse orion::operators::ml::POST_TRANSFORM;\n\nuse core::debug::PrintTrait;\n\n#[derive(Destruct)]\nstruct TreeEnsembleClassifier<T> {\n    ensemble: TreeEnsemble<T>,\n    class_ids: Span<usize>,\n    class_nodeids: Span<usize>,\n    class_treeids: Span<usize>,\n    class_weights: Span<T>,\n    classlabels: Span<usize>,\n    base_values: Option<Span<T>>,\n    post_transform: POST_TRANSFORM,\n}\n\n/// Trait\n///\n/// predict - Returns the top class for each of N inputs.\ntrait TreeEnsembleClassifierTrait<T> {\n    /// # TreeEnsembleClassifier::predict\n    ///\n    /// ```rust \n    ///    fn predict(classifier: TreeEnsembleClassifier<T>, X: Tensor<T>) -> (Span<usize>, MutMatrix::<T>);\n    /// ```\n    ///\n    /// Tree Ensemble classifier. Returns the top class for each of N inputs.\n    /// \n    /// ## Args\n    ///\n    /// * `self`: TreeEnsembleClassifier<T> - A TreeEnsembleClassifier object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * N Top class for each point\n    /// * The class score Matrix for each class, for each point.\n    ///\n    /// ## Type Constraints\n    ///\n    /// `TreeEnsembleClassifier` and `X` must be fixed points\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\n    /// use orion::operators::ml::{NODE_MODES, TreeEnsembleAttributes, TreeEnsemble};\n    /// use orion::operators::ml::{\n    ///     TreeEnsembleClassifier, POST_TRANSFORM, TreeEnsembleClassifierTrait\n    /// };\n    /// use orion::operators::matrix::{MutMatrix, MutMatrixImpl};\n    /// \n    /// fn tree_ensemble_classifier_helper(\n    ///    post_transform: POST_TRANSFORM\n    ///) -> (TreeEnsembleClassifier<FP16x16>, Tensor<FP16x16>) {\n    ///    let class_ids: Span<usize> = array![0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]\n    ///        .span();\n    ///\n    ///    let class_nodeids: Span<usize> = array![2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 1, 1, 3, 3, 3, 4, 4, 4]\n    ///        .span();\n    ///\n    ///    let class_treeids: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n    ///        .span();\n    ///\n    ///    let class_weights: Span<FP16x16> = array![\n    ///        FP16x16 { mag: 30583, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 2185, sign: false },\n    ///        FP16x16 { mag: 13107, sign: false },\n    ///        FP16x16 { mag: 15729, sign: false },\n    ///        FP16x16 { mag: 3932, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 32768, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 32768, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 29491, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 3277, sign: false },\n    ///        FP16x16 { mag: 6746, sign: false },\n    ///        FP16x16 { mag: 12529, sign: false },\n    ///        FP16x16 { mag: 13493, sign: false },\n    ///    ]\n    ///        .span();\n    ///\n    ///    let classlabels: Span<usize> = array![0, 1, 2].span();\n    ///\n    ///    let nodes_falsenodeids: Span<usize> = array![4, 3, 0, 0, 0, 2, 0, 4, 0, 0].span();\n    ///\n    ///    let nodes_featureids: Span<usize> = array![1, 0, 0, 0, 0, 1, 0, 0, 0, 0].span();\n    ///\n    ///    let nodes_missing_value_tracks_true: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 0].span();\n    ///\n    ///    let nodes_modes: Span<NODE_MODES> = array![\n    ///        NODE_MODES::BRANCH_LEQ,\n    ///        NODE_MODES::BRANCH_LEQ,\n    ///        NODE_MODES::LEAF,\n    ///        NODE_MODES::LEAF,\n    ///        NODE_MODES::LEAF,\n    ///        NODE_MODES::BRANCH_LEQ,\n    ///        NODE_MODES::LEAF,\n    ///        NODE_MODES::BRANCH_LEQ,\n    ///        NODE_MODES::LEAF,\n    ///        NODE_MODES::LEAF,\n    ///    ]\n    ///        .span();\n    ///\n    ///    let nodes_nodeids: Span<usize> = array![0, 1, 2, 3, 4, 0, 1, 2, 3, 4].span();\n    ///\n    ///    let nodes_treeids: Span<usize> = array![0, 0, 0, 0, 0, 1, 1, 1, 1, 1].span();\n    ///\n    ///    let nodes_truenodeids: Span<usize> = array![1, 2, 0, 0, 0, 1, 0, 3, 0, 0].span();\n    ///\n    ///    let nodes_values: Span<FP16x16> = array![\n    ///        FP16x16 { mag: 81892, sign: false },\n    ///        FP16x16 { mag: 19992, sign: true },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 110300, sign: true },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 44245, sign: true },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///        FP16x16 { mag: 0, sign: false },\n    ///    ]\n    ///        .span();\n    ///\n    ///    let tree_ids: Span<usize> = array![0, 1].span();\n    ///\n    ///    let mut root_index: Felt252Dict<usize> = Default::default();\n    ///    root_index.insert(0, 0);\n    ///    root_index.insert(1, 5);\n    ///\n    ///    let mut node_index: Felt252Dict<usize> = Default::default();\n    ///    node_index\n    ///        .insert(2089986280348253421170679821480865132823066470938446095505822317253594081284, 0);\n    ///    node_index\n    ///        .insert(2001140082530619239661729809084578298299223810202097622761632384561112390979, 1);\n    ///    node_index\n    ///        .insert(2592670241084192212354027440049085852792506518781954896144296316131790403900, 2);\n    ///    node_index\n    ///        .insert(2960591271376829378356567803618548672034867345123727178628869426548453833420, 3);\n    ///    node_index\n    ///        .insert(458933264452572171106695256465341160654132084710250671055261382009315664425, 4);\n    ///    node_index\n    ///        .insert(1089549915800264549621536909767699778745926517555586332772759280702396009108, 5);\n    ///    node_index\n    ///        .insert(1321142004022994845681377299801403567378503530250467610343381590909832171180, 6);\n    ///    node_index\n    ///        .insert(2592987851775965742543459319508348457290966253241455514226127639100457844774, 7);\n    ///    node_index\n    ///        .insert(2492755623019086109032247218615964389726368532160653497039005814484393419348, 8);\n    ///    node_index\n    ///        .insert(1323616023845704258113538348000047149470450086307731200728039607710316625916, 9);\n    ///\n    ///    let atts = TreeEnsembleAttributes {\n    ///        nodes_falsenodeids,\n    ///        nodes_featureids,\n    ///        nodes_missing_value_tracks_true,\n    ///        nodes_modes,\n    ///        nodes_nodeids,\n    ///        nodes_treeids,\n    ///        nodes_truenodeids,\n    ///        nodes_values\n    ///    };\n    ///\n    ///    let mut ensemble: TreeEnsemble<FP16x16> = TreeEnsemble {\n    ///        atts, tree_ids, root_index, node_index\n    ///    };\n    ///\n    ///    let base_values: Option<Span<FP16x16>> = Option::None;\n    ///\n    ///    let mut classifier: TreeEnsembleClassifier<FP16x16> = TreeEnsembleClassifier {\n    ///        ensemble,\n    ///        class_ids,\n    ///        class_nodeids,\n    ///        class_treeids,\n    ///        class_weights,\n    ///        classlabels,\n    ///        base_values,\n    ///        post_transform\n    ///    };\n    ///\n    ///    let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///        array![3, 3].span(),\n    ///        array![\n    ///            FP16x16 { mag: 65536, sign: true },\n    ///            FP16x16 { mag: 52429, sign: true },\n    ///            FP16x16 { mag: 39322, sign: true },\n    ///            FP16x16 { mag: 26214, sign: true },\n    ///            FP16x16 { mag: 13107, sign: true },\n    ///            FP16x16 { mag: 0, sign: false },\n    ///            FP16x16 { mag: 13107, sign: false },\n    ///            FP16x16 { mag: 26214, sign: false },\n    ///            FP16x16 { mag: 39322, sign: false },\n    ///        ]\n    ///            .span()\n    ///    );\n    ///\n    ///    (classifier, X)\n    /// }\n    ///\n    /// fn test_tree_ensemble_classifier_multi_pt_softmax() -> (Span<usize>, MutMatrix::<FP16x16>) {\n    ///     let (mut classifier, X) = tree_ensemble_classifier_helper(POST_TRANSFORM::SOFTMAX);\n    /// \n    ///     let (labels, scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n    ///     (labels, scores)\n    /// }   \n    ///\n    /// >>> \n    /// ([0, 0, 1],\n    ///  [\n    ///    [0.545123, 0.217967, 0.23691],\n    ///    [0.416047, 0.284965, 0.298988],\n    ///    [0.322535, 0.366664, 0.310801],\n    ///   ])      \n    /// ```\n    ///\n    fn predict(\n        classifier: TreeEnsembleClassifier<T>, X: Tensor<T>\n    ) -> (Span<usize>, MutMatrix::<T>);\n}\n\nimpl TreeEnsembleClassifierImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>\n> of TreeEnsembleClassifierTrait<T> {\n    fn predict(\n        classifier: TreeEnsembleClassifier<T>, X: Tensor<T>\n    ) -> (Span<usize>, MutMatrix::<T>) {\n        let mut classifier = classifier;\n        let leaves_index = classifier.ensemble.leave_index_tree(X);\n        let n_classes = classifier.classlabels.len();\n        let mut res: MutMatrix<T> = MutMatrixImpl::new(*leaves_index.shape.at(0), n_classes);\n\n        // Set base values\n        if classifier.base_values.is_some() {\n            let mut base_values = classifier.base_values.unwrap();\n            let mut row: usize = 0;\n            loop {\n                if row == res.rows {\n                    break;\n                }\n\n                let mut col: usize = 0;\n                loop {\n                    if col == res.cols {\n                        break;\n                    }\n\n                    let value = *base_values.pop_front().unwrap();\n                    res.set(row, col, value);\n\n                    col += 1\n                };\n\n                row += 1;\n            }\n        } else {\n            let mut row: usize = 0;\n            loop {\n                if row == res.rows {\n                    break;\n                }\n\n                let mut col: usize = 0;\n                loop {\n                    if col == res.cols {\n                        break;\n                    }\n\n                    res.set(row, col, NumberTrait::zero());\n\n                    col += 1\n                };\n\n                row += 1;\n            }\n        }\n\n        let mut class_index: Felt252Dict<Nullable<Span<usize>>> = Default::default();\n        let mut i: usize = 0;\n        loop {\n            if i == classifier.class_treeids.len() {\n                break;\n            }\n\n            let tid = *classifier.class_treeids[i];\n            let nid = *classifier.class_nodeids[i];\n\n            let mut key = PedersenHasherImpl::new();\n            let key: felt252 = key.hash(tid.into(), nid.into());\n            match match_nullable(class_index.get(key)) {\n                FromNullableResult::Null(()) => {\n                    class_index.insert(key, NullableTrait::new(array![i].span()));\n                },\n                FromNullableResult::NotNull(val) => {\n                    let mut new_val = val.unbox();\n                    let new_val = new_val.concat(array![i].span());\n                    class_index.insert(key, NullableTrait::new(new_val));\n                },\n            }\n\n            i += 1;\n        };\n        let mut i: usize = 0;\n        loop {\n            if i == res.rows {\n                break;\n            }\n\n            let mut indices = get_row(@leaves_index, i);\n            let mut t_index: Array<Span<core::integer::u32>> = ArrayTrait::new();\n            loop {\n                match indices.pop_front() {\n                    Option::Some(index) => {\n                        let mut key = PedersenHasherImpl::new();\n                        let key: felt252 = key\n                            .hash(\n                                (*classifier.ensemble.atts.nodes_treeids[*index]).into(),\n                                (*classifier.ensemble.atts.nodes_nodeids[*index]).into()\n                            );\n                        t_index.append(class_index.get(key).deref());\n                    },\n                    Option::None => { break; }\n                };\n            };\n            let mut t_index = t_index.span();\n            loop {\n                match t_index.pop_front() {\n                    Option::Some(its) => {\n                        let mut its = *its;\n                        loop {\n                            match its.pop_front() {\n                                Option::Some(it) => {\n                                    match res.get(i, *classifier.class_ids[*it]) {\n                                        Option::Some(val) => {\n                                            res\n                                                .set(\n                                                    i,\n                                                    *classifier.class_ids[*it],\n                                                    val + *classifier.class_weights[*it]\n                                                );\n                                        },\n                                        Option::None => {\n                                            res\n                                                .set(\n                                                    i,\n                                                    *classifier.class_ids[*it],\n                                                    *classifier.class_weights[*it]\n                                                );\n                                        },\n                                    };\n                                },\n                                Option::None => { break; }\n                            };\n                        };\n                    },\n                    Option::None => { break; }\n                };\n            };\n            i += 1;\n        };\n\n        // Binary class\n        let mut binary = false;\n        let mut i: usize = 0;\n        let mut class_ids = classifier.class_ids;\n        let mut class_id: usize = 0;\n        // Get first class_id in class_ids\n        match class_ids.pop_front() {\n            Option::Some(c_id) => { class_id = *c_id; },\n            Option::None => { class_id = 0; }\n        };\n        loop {\n            if i == classifier.class_ids.len() {\n                break;\n            }\n            match class_ids.pop_front() {\n                Option::Some(c_id) => {\n                    if *c_id == class_id {\n                        binary = true;\n                        continue;\n                    } else {\n                        binary = false;\n                        break;\n                    }\n                },\n                Option::None => { break; }\n            };\n        };\n\n        // Clone res\n        if binary {\n            let mut new_res: MutMatrix<T> = MutMatrixImpl::new(res.rows, res.cols);\n            let mut i: usize = 0;\n            loop {\n                if i == res.rows {\n                    break;\n                }\n                // Exchange\n                match res.get(i, 0) {\n                    Option::Some(res_0) => { new_res.set(i, 1, res_0); },\n                    Option::None => { new_res.set(i, 1, NumberTrait::zero()); },\n                };\n                i += 1;\n            };\n            match classifier.post_transform {\n                POST_TRANSFORM::NONE => {\n                    let mut i: usize = 0;\n                    loop {\n                        if i == res.rows {\n                            break;\n                        }\n                        // Exchange\n                        match new_res.get(i, 1) {\n                            Option::Some(res_1) => {\n                                let value = NumberTrait::sub(NumberTrait::one(), res_1);\n                                new_res.set(i, 0, value);\n                            },\n                            Option::None => { new_res.set(i, 0, NumberTrait::zero()); },\n                        };\n                        i += 1;\n                    };\n                },\n                POST_TRANSFORM::SOFTMAX => {\n                    let mut i: usize = 0;\n                    loop {\n                        if i == res.rows {\n                            break;\n                        }\n                        // Exchange\n                        match new_res.get(i, 1) {\n                            Option::Some(res_1) => { new_res.set(i, 0, res_1.neg()); },\n                            Option::None => { new_res.set(i, 0, NumberTrait::zero()); },\n                        };\n                        i += 1;\n                    };\n                },\n                POST_TRANSFORM::LOGISTIC => {\n                    let mut i: usize = 0;\n                    loop {\n                        if i == res.rows {\n                            break;\n                        }\n                        // Exchange\n                        match new_res.get(i, 1) {\n                            Option::Some(res_1) => { new_res.set(i, 0, res_1.neg()); },\n                            Option::None => { new_res.set(i, 0, NumberTrait::zero()); },\n                        };\n                        i += 1;\n                    };\n                },\n                POST_TRANSFORM::SOFTMAXZERO => {\n                    let mut i: usize = 0;\n                    loop {\n                        if i == res.rows {\n                            break;\n                        }\n                        // Exchange\n                        match new_res.get(i, 1) {\n                            Option::Some(res_1) => { new_res.set(i, 0, res_1.neg()); },\n                            Option::None => { new_res.set(i, 0, NumberTrait::zero()); },\n                        };\n                        i += 1;\n                    };\n                },\n                POST_TRANSFORM::PROBIT => {\n                    let mut i: usize = 0;\n                    loop {\n                        if i == res.rows {\n                            break;\n                        }\n                        // Exchange\n                        match new_res.get(i, 1) {\n                            Option::Some(res_1) => {\n                                let value = NumberTrait::sub(NumberTrait::one(), res_1);\n                                new_res.set(i, 0, value);\n                            },\n                            Option::None => { new_res.set(i, 0, NumberTrait::zero()); },\n                        };\n                        i += 1;\n                    };\n                },\n            };\n            res = new_res;\n        }\n\n        // Post Transform\n        let mut new_scores = match classifier.post_transform {\n            POST_TRANSFORM::NONE => res, // No action required\n            POST_TRANSFORM::SOFTMAX => res.softmax(1),\n            POST_TRANSFORM::LOGISTIC => res.sigmoid(),\n            POST_TRANSFORM::SOFTMAXZERO => res.softmax_zero(1),\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n\n        // Labels\n        let mut labels = new_scores.argmax(1);\n\n        let mut labels_list = ArrayTrait::new();\n        loop {\n            match labels.pop_front() {\n                Option::Some(i) => { labels_list.append(*classifier.classlabels[*i]); },\n                Option::None => { break; }\n            };\n        };\n\n        return (labels_list.span(), new_scores);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/ml/tree_ensemble/tree_ensemble_regressor.cairo",
        "content": "use core::array::ArrayTrait;\nuse core::clone::Clone;\nuse core::box::BoxTrait;\nuse core::traits::Into;\nuse core::option::OptionTrait;\nuse orion::operators::matrix::MutMatrixTrait;\nuse core::array::SpanTrait;\nuse core::nullable::NullableTrait;\nuse core::dict::Felt252DictTrait;\nuse core::dict::Felt252DictEntryTrait;\nuse core::nullable::{match_nullable, FromNullableResult};\n\n\nuse orion::operators::tensor::{Tensor, TensorTrait};\nuse orion::operators::ml::tree_ensemble::core::{TreeEnsemble, TreeEnsembleImpl, TreeEnsembleTrait};\nuse orion::numbers::NumberTrait;\nuse orion::utils::get_row;\n\nuse alexandria_merkle_tree::merkle_tree::{pedersen::PedersenHasherImpl};\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n\nuse orion::operators::matrix::{MutMatrix, MutMatrixImpl};\nuse orion::operators::vec::{VecTrait, NullableVec, NullableVecImpl};\nuse orion::operators::ml::POST_TRANSFORM;\n\nuse core::debug::PrintTrait;\n\n#[derive(Destruct)]\nstruct TreeEnsembleRegressor<T> {\n    ensemble: TreeEnsemble<T>,\n    target_ids: Span<usize>,\n    target_nodeids: Span<usize>,\n    target_treeids: Span<usize>,\n    target_weights: Span<T>,\n    base_values: Option<Span<T>>,\n    n_targets: usize,\n    aggregate_function: AGGREGATE_FUNCTION,\n    post_transform: POST_TRANSFORM,\n}\n\n#[derive(Copy, Drop)]\nenum AGGREGATE_FUNCTION {\n    SUM,\n    AVERAGE,\n    MIN,\n    MAX,\n}\n\n/// Trait\n///\n/// predict - Returns the regressed values for each input in N.\ntrait TreeEnsembleRegressorTrait<T> {\n    /// # TreeEnsembleRegressor::predict\n    ///\n    /// ```rust \n    ///    fn predict(regressor: TreeEnsembleRegressor<T>, X: Tensor<T>) -> (Span<usize>, MutMatrix::<T>);\n    /// ```\n    ///\n    /// Tree Ensemble regressor. Returns the regressed values for each input in N.\n    /// \n    /// ## Args\n    ///\n    /// * `self`: TreeEnsembleRegressor<T> - A TreeEnsembleRegressor object.\n    /// * `X`:  Input 2D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// * Regressed values for each input in N\n    ///\n    /// ## Type Constraints\n    ///\n    /// `TreeEnsembleRegressor` and `X` must be fixed points\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\n    /// use orion::operators::ml::{NODE_MODES, TreeEnsembleAttributes, TreeEnsemble};\n    /// use orion::operators::ml::tree_ensemble::tree_ensemble_regressor::{\n    ///     TreeEnsembleRegressor, POST_TRANSFORM, TreeEnsembleRegressorTrait, AGGREGATE_FUNCTION\n    /// };\n    /// use orion::operators::matrix::{MutMatrix, MutMatrixImpl};\n    /// \n    /// \n    /// fn tree_ensemble_regressor_helper(\n    ///     agg: AGGREGATE_FUNCTION\n    /// ) -> (TreeEnsembleRegressor<FP16x16>, Tensor<FP16x16>) {\n    ///     let n_targets: usize = 1;\n    ///     let aggregate_function = agg;\n    ///     let nodes_falsenodeids: Span<usize> = array![4, 3, 0, 0, 0, 2, 0, 4, 0, 0].span();\n    ///     let nodes_featureids: Span<usize> = array![0, 2, 0, 0, 0, 0, 0, 2, 0, 0].span();\n    ///     let nodes_missing_value_tracks_true: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 0].span();\n    ///     let nodes_modes: Span<NODE_MODES> = array![\n    ///         NODE_MODES::BRANCH_LEQ,\n    ///         NODE_MODES::BRANCH_LEQ,\n    ///         NODE_MODES::LEAF,\n    ///         NODE_MODES::LEAF,\n    ///         NODE_MODES::LEAF,\n    ///         NODE_MODES::BRANCH_LEQ,\n    ///         NODE_MODES::LEAF,\n    ///         NODE_MODES::BRANCH_LEQ,\n    ///         NODE_MODES::LEAF,\n    ///         NODE_MODES::LEAF\n    ///     ]\n    ///         .span();\n    ///     let nodes_nodeids: Span<usize> = array![0, 1, 2, 3, 4, 0, 1, 2, 3, 4].span();\n    ///     let nodes_treeids: Span<usize> = array![0, 0, 0, 0, 0, 1, 1, 1, 1, 1].span();\n    ///     let nodes_truenodeids: Span<usize> = array![1, 2, 0, 0, 0, 1, 0, 3, 0, 0].span();\n    ///     let nodes_values: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 17462, sign: false },\n    ///         FP16x16 { mag: 40726, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 47240, sign: true },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 36652, sign: true },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 0, sign: false }\n    ///     ]\n    ///         .span();\n    ///     let target_ids: Span<usize> = array![0, 0, 0, 0, 0, 0].span();\n    ///     let target_nodeids: Span<usize> = array![2, 3, 4, 1, 3, 4].span();\n    ///     let target_treeids: Span<usize> = array![0, 0, 0, 1, 1, 1].span();\n    ///     let target_weights: Span<FP16x16> = array![\n    ///         FP16x16 { mag: 5041, sign: false },\n    ///         FP16x16 { mag: 32768, sign: false },\n    ///         FP16x16 { mag: 32768, sign: false },\n    ///         FP16x16 { mag: 0, sign: false },\n    ///         FP16x16 { mag: 18724, sign: false },\n    ///         FP16x16 { mag: 32768, sign: false }\n    ///     ]\n    ///         .span();\n    /// \n    ///     let base_values: Option<Span<FP16x16>> = Option::None;\n    ///     let post_transform = POST_TRANSFORM::NONE;\n    /// \n    ///     let tree_ids: Span<usize> = array![0, 1].span();\n    /// \n    ///     let mut root_index: Felt252Dict<usize> = Default::default();\n    ///     root_index.insert(0, 0);\n    ///     root_index.insert(1, 5);\n    /// \n    ///     let mut node_index: Felt252Dict<usize> = Default::default();\n    ///     node_index\n    ///         .insert(2089986280348253421170679821480865132823066470938446095505822317253594081284, 0);\n    ///     node_index\n    ///         .insert(2001140082530619239661729809084578298299223810202097622761632384561112390979, 1);\n    ///     node_index\n    ///         .insert(2592670241084192212354027440049085852792506518781954896144296316131790403900, 2);\n    ///     node_index\n    ///         .insert(2960591271376829378356567803618548672034867345123727178628869426548453833420, 3);\n    ///     node_index\n    ///         .insert(458933264452572171106695256465341160654132084710250671055261382009315664425, 4);\n    ///     node_index\n    ///         .insert(1089549915800264549621536909767699778745926517555586332772759280702396009108, 5);\n    ///     node_index\n    ///         .insert(1321142004022994845681377299801403567378503530250467610343381590909832171180, 6);\n    ///     node_index\n    ///         .insert(2592987851775965742543459319508348457290966253241455514226127639100457844774, 7);\n    ///     node_index\n    ///         .insert(2492755623019086109032247218615964389726368532160653497039005814484393419348, 8);\n    ///     node_index\n    ///         .insert(1323616023845704258113538348000047149470450086307731200728039607710316625916, 9);\n    /// \n    ///     let atts = TreeEnsembleAttributes {\n    ///         nodes_falsenodeids,\n    ///         nodes_featureids,\n    ///         nodes_missing_value_tracks_true,\n    ///         nodes_modes,\n    ///         nodes_nodeids,\n    ///         nodes_treeids,\n    ///         nodes_truenodeids,\n    ///         nodes_values\n    ///     };\n    /// \n    ///     let mut ensemble: TreeEnsemble<FP16x16> = TreeEnsemble {\n    ///         atts, tree_ids, root_index, node_index\n    ///     };\n    /// \n    ///     let mut regressor: TreeEnsembleRegressor<FP16x16> = TreeEnsembleRegressor {\n    ///         ensemble,\n    ///         target_ids,\n    ///         target_nodeids,\n    ///         target_treeids,\n    ///         target_weights,\n    ///         base_values,\n    ///         n_targets,\n    ///         aggregate_function,\n    ///         post_transform\n    ///     };\n    /// \n    ///     let mut X: Tensor<FP16x16> = TensorTrait::new(\n    ///         array![3, 3].span(),\n    ///         array![\n    ///             FP16x16 { mag: 32768, sign: true },\n    ///             FP16x16 { mag: 26214, sign: true },\n    ///             FP16x16 { mag: 19660, sign: true },\n    ///             FP16x16 { mag: 13107, sign: true },\n    ///             FP16x16 { mag: 6553, sign: true },\n    ///             FP16x16 { mag: 0, sign: false },\n    ///             FP16x16 { mag: 6553, sign: false },\n    ///             FP16x16 { mag: 13107, sign: false },\n    ///             FP16x16 { mag: 19660, sign: false },\n    ///         ]\n    ///             .span()\n    ///     );\n    /// \n    ///     (regressor, X)\n    /// }\n    /// \n    /// fn test_tree_ensemble_regressor_SUM() -> MutMatrix::<FP16x16> {\n    ///     let (mut regressor, X) = tree_ensemble_regressor_helper(AGGREGATE_FUNCTION::SUM);\n    ///     let mut res = TreeEnsembleRegressorTrait::predict(regressor, X);\n    ///     res\n    /// }\n    /// >>> \n    ///\n    ///    [0.5769, 0.5769, 0.5769] \n    ///\n    /// ```\n    ///\n    fn predict(regressor: TreeEnsembleRegressor<T>, X: Tensor<T>) -> MutMatrix::<T>;\n}\n\nimpl TreeEnsembleRegressorImpl<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n> of TreeEnsembleRegressorTrait<T> {\n    fn predict(regressor: TreeEnsembleRegressor<T>, X: Tensor<T>) -> MutMatrix::<T> {\n        let mut regressor = regressor;\n        let leaves_index = regressor.ensemble.leave_index_tree(X);\n        let n_targets = regressor.n_targets;\n\n        let mut res: MutMatrix<T> = MutMatrixImpl::new(*leaves_index.shape.at(0), n_targets);\n        let n_trees = regressor.ensemble.tree_ids.len();\n\n        let mut target_index: Felt252Dict<Nullable<Span<usize>>> = Default::default();\n        let mut i: usize = 0;\n        loop {\n            if i == regressor.target_treeids.len() {\n                break;\n            }\n\n            let tid = *regressor.target_treeids[i];\n            let nid = *regressor.target_nodeids[i];\n\n            let mut key = PedersenHasherImpl::new();\n            let key: felt252 = key.hash(tid.into(), nid.into());\n            match match_nullable(target_index.get(key)) {\n                FromNullableResult::Null(()) => {\n                    target_index.insert(key, NullableTrait::new(array![i].span()));\n                },\n                FromNullableResult::NotNull(val) => {\n                    let mut new_val = val.unbox();\n                    let new_val = new_val.concat(array![i].span());\n                    target_index.insert(key, NullableTrait::new(new_val));\n                },\n            }\n\n            i += 1;\n        };\n\n        let mut i: usize = 0;\n        loop {\n            if i == res.rows {\n                break;\n            }\n\n            let mut indices = get_row(@leaves_index, i);\n            let mut t_index: Array<Span<core::integer::u32>> = ArrayTrait::new();\n            loop {\n                match indices.pop_front() {\n                    Option::Some(index) => {\n                        let mut key = PedersenHasherImpl::new();\n                        let key: felt252 = key\n                            .hash(\n                                (*regressor.ensemble.atts.nodes_treeids[*index]).into(),\n                                (*regressor.ensemble.atts.nodes_nodeids[*index]).into()\n                            );\n                        t_index.append(target_index.get(key).deref());\n                    },\n                    Option::None => { break; }\n                };\n            };\n            let mut t_index = t_index.span();\n\n            match regressor.aggregate_function {\n                AGGREGATE_FUNCTION::SUM => {\n                    compute_res_SUM(ref regressor, ref res, ref t_index, i);\n                },\n                AGGREGATE_FUNCTION::AVERAGE => {\n                    compute_res_AVERAGE(ref regressor, ref res, ref t_index, n_trees, i);\n                },\n                AGGREGATE_FUNCTION::MIN => {\n                    compute_res_MIN(ref regressor, ref res, ref t_index, i);\n                },\n                AGGREGATE_FUNCTION::MAX => {\n                    compute_res_MAX(ref regressor, ref res, ref t_index, i);\n                },\n            };\n            i += 1;\n        };\n\n        // Convention is to add base_values after aggregate function\n        if regressor.base_values.is_some() {\n            let mut base_values = regressor.base_values.unwrap();\n            let mut row: usize = 0;\n            loop {\n                if row == res.rows {\n                    break;\n                }\n\n                let mut col: usize = 0;\n                loop {\n                    if col == res.cols {\n                        break;\n                    }\n\n                    let value = *base_values.pop_front().unwrap();\n                    match res.get(row, col) {\n                        Option::Some(val) => { res.set(row, col, val + value); },\n                        Option::None => { res.set(row, col, value); },\n                    };\n\n                    col += 1\n                };\n\n                row += 1;\n            }\n        }\n\n        // Post Transform\n        let mut new_scores = match regressor.post_transform {\n            POST_TRANSFORM::NONE => res, // No action required\n            POST_TRANSFORM::SOFTMAX => res.softmax(1),\n            POST_TRANSFORM::LOGISTIC => res.sigmoid(),\n            POST_TRANSFORM::SOFTMAXZERO => res.softmax_zero(1),\n            POST_TRANSFORM::PROBIT => core::panic_with_felt252('Probit not supported yet'),\n        };\n\n        return new_scores;\n    }\n}\n\n\nfn compute_res_SUM<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n>(\n    ref self: TreeEnsembleRegressor<T>,\n    ref res: MutMatrix<T>,\n    ref t_index: Span<Span<core::integer::u32>>,\n    i: usize\n) {\n    loop {\n        match t_index.pop_front() {\n            Option::Some(its) => {\n                let mut its = *its;\n                loop {\n                    match its.pop_front() {\n                        Option::Some(it) => {\n                            match res.get(i, *self.target_ids[*it]) {\n                                Option::Some(val) => {\n                                    res\n                                        .set(\n                                            i,\n                                            *self.target_ids[*it],\n                                            val + *self.target_weights[*it]\n                                        );\n                                },\n                                Option::None => {\n                                    res.set(i, *self.target_ids[*it], *self.target_weights[*it]);\n                                },\n                            };\n                        },\n                        Option::None => { break; }\n                    };\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n}\n\nfn compute_res_AVERAGE<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>\n>(\n    ref self: TreeEnsembleRegressor<T>,\n    ref res: MutMatrix<T>,\n    ref t_index: Span<Span<core::integer::u32>>,\n    n_trees: usize,\n    i: usize\n) {\n    let n_trees_felt: felt252 = (n_trees * 65536).into();\n    let n_trees: T = NumberTrait::from_felt(n_trees_felt);\n    loop {\n        match t_index.pop_front() {\n            Option::Some(its) => {\n                let mut its = *its;\n                loop {\n                    match its.pop_front() {\n                        Option::Some(it) => {\n                            match res.get(i, *self.target_ids[*it]) {\n                                Option::Some(val) => {\n                                    res\n                                        .set(\n                                            i,\n                                            *self.target_ids[*it],\n                                            val + (*self.target_weights[*it]) / n_trees\n                                        );\n                                },\n                                Option::None => {\n                                    res\n                                        .set(\n                                            i,\n                                            *self.target_ids[*it],\n                                            *self.target_weights[*it] / n_trees\n                                        );\n                                },\n                            };\n                        },\n                        Option::None => { break; }\n                    };\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n}\n\nfn compute_res_MIN<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n>(\n    ref self: TreeEnsembleRegressor<T>,\n    ref res: MutMatrix<T>,\n    ref t_index: Span<Span<core::integer::u32>>,\n    i: usize\n) {\n    let mut j = 0;\n    loop {\n        if j == res.cols {\n            break;\n        }\n        res.set(i, j, NumberTrait::max_value());\n        j += 1;\n    };\n    loop {\n        match t_index.pop_front() {\n            Option::Some(its) => {\n                let mut its = *its;\n                loop {\n                    match its.pop_front() {\n                        Option::Some(it) => {\n                            match res.get(i, *self.target_ids[*it]) {\n                                Option::Some(val) => {\n                                    res\n                                        .set(\n                                            i,\n                                            *self.target_ids[*it],\n                                            NumberTrait::min(val, *self.target_weights[*it])\n                                        );\n                                },\n                                Option::None => {\n                                    res.set(i, *self.target_ids[*it], *self.target_weights[*it]);\n                                },\n                            };\n                        },\n                        Option::None => { break; }\n                    };\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n}\n\n\nfn compute_res_MAX<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +TensorTrait<usize>,\n    +TensorTrait<T>,\n    +PrintTrait<T>,\n    +AddEq<T>,\n    +Div<T>,\n    +Mul<T>,\n>(\n    ref self: TreeEnsembleRegressor<T>,\n    ref res: MutMatrix<T>,\n    ref t_index: Span<Span<core::integer::u32>>,\n    i: usize\n) {\n    let mut j = 0;\n    loop {\n        if j == res.cols {\n            break;\n        }\n        res.set(i, j, NumberTrait::min_value());\n        j += 1;\n    };\n    loop {\n        match t_index.pop_front() {\n            Option::Some(its) => {\n                let mut its = *its;\n                loop {\n                    match its.pop_front() {\n                        Option::Some(it) => {\n                            match res.get(i, *self.target_ids[*it]) {\n                                Option::Some(val) => {\n                                    res\n                                        .set(\n                                            i,\n                                            *self.target_ids[*it],\n                                            NumberTrait::max(val, *self.target_weights[*it])\n                                        );\n                                },\n                                Option::None => {\n                                    res.set(i, *self.target_ids[*it], *self.target_weights[*it]);\n                                },\n                            };\n                        },\n                        Option::None => { break; }\n                    };\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn.cairo",
        "content": "mod core;\nmod implementations;\nmod functional;\n\nuse orion::operators::nn::core::NNTrait;\n\nuse orion::operators::nn::implementations::nn_fp8x23::FP8x23NN;\nuse orion::operators::nn::implementations::nn_fp16x16::FP16x16NN;\nuse orion::operators::nn::implementations::nn_fp32x32::FP32x32NN;\nuse orion::operators::nn::implementations::nn_fp64x64::FP64x64NN;\nuse orion::operators::nn::implementations::nn_i8::I8NN;\nuse orion::operators::nn::implementations::nn_i32::I32NN;\nuse orion::operators::nn::implementations::nn_u32::U32NN;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/core.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\n\n/// Trait\n///\n/// relu - Applies the rectified linear unit function element-wise.\n/// leaky_relu - Applies the leaky rectified linear unit (Leaky ReLU) activation function element-wise.\n/// sigmoid - Applies the Sigmoid function to an n-dimensional input tensor.\n/// softmax - Computes softmax activations.\n/// softmax_zero - Computes softmax zero.\n/// logsoftmax - Applies the natural log to Softmax function to an n-dimensional input Tensor.\n/// softsign - Applies the Softsign function element-wise.\n/// softplus - Applies the Softplus function element-wise.\n/// linear - Performs a linear transformation of the input tensor using the provided weights and bias.\n/// hard_sigmoid - Applies the Hard Sigmoid function to an n-dimensional input tensor.\n/// thresholded_relu - Performs the thresholded relu activation function element-wise.\n/// gemm - Performs General Matrix multiplication.\n/// grid_sample - Computes the grid sample of the input tensor and input grid.\n/// col2im - Rearranges column blocks back into a multidimensional image\n/// conv_transpose - Performs the convolution transpose of the input data tensor and weight tensor.\n/// conv - Performs the convolution of the input data tensor and weight tensor.\ntrait NNTrait<T> {\n    /// # NNTrait::relu\n    ///\n    /// ```rust \n    ///    fn relu(tensor: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    /// \n    /// Applies the rectified linear unit function element-wise\n    /// \n    /// $$\n    /// ReLU(x)=(x)^+=max(0,x)\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    /// \n    /// A `Tensor<T>` with the same shape as the input tensor.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\n    /// use orion::operators::nn::{NNTrait, I32NN};\n    /// \n    /// fn relu_example() -> Tensor<i32> {\n    ///     let tensor = TensorTrait::<i32>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![1, 2, -1, -2].span(),\n    ///     );\n    /// \n    ///     return NNTrait::relu(@tensor);\n    /// }\n    /// >>> [[1,2],[0,0]]\n    /// ```\n    /// \n    fn relu(tensor: @Tensor<T>) -> Tensor<T>;\n    /// # NNTrait::softmax\n    ///\n    /// ```rust \n    ///    fn softmax(tensor: @Tensor<T>, axis: Option<i32>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range \\[0,1] and sum to 1.\n    /// \n    /// $$\n    /// \\text{softmax}(x_i) = \\frac{e^{x_i}}{\\sum_{j=1}^n e^{x_j}}\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`Option<i32>`) - Describes the dimension Softmax will be performed on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn softmax_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::softmax(@tensor, Option::Some(1));\n    /// }\n    /// >>> [[2255697,6132911],[2255697,6132911]]\n    ///     // The fixed point representation of\n    ///     // [[0.2689, 0.7311],[0.2689, 0.7311]]\n    /// ```\n    ///\n    fn softmax(tensor: @Tensor<T>, axis: Option<i32>) -> Tensor<T>;\n    /// # NNTrait::softmax_zero\n    ///\n    /// ```rust \n    ///    fn softmax_zero(tensor: @Tensor<T>, axis: usize) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the Softmax zero function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range \\[0,1] and sum to 1 while keeping the zero elements to zero.\n    /// \n    /// The softmax zero on the set $\\mathbf{x} = (x_1, ..., x_n)$ is given by :\n    /// \n    /// $$\n    /// \\text{softmax zero}(x_i) = \\begin{cases}\n    /// 0 & \\qquad x_i = 0 \\\\\n    /// \\frac{e^{x_i}}{ \\sum_{x \\in {S}} e^{x}} & \\qquad \\text{otherwise} \n    /// \\end{cases}\n    /// $$\n    /// where $S$ in a subset of $\\mathbf{x}$ given by \n    /// \n    /// $$\n    ///  \\  S = \\{ (x_1, \\ldots, x_k) \\mid 1 \\leq k \\leq n, x_j \\neq 0 \\text{ for } 1 \\leq j \\leq k \\}\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The axis along which to compute the softmax zero.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// use core::debug::PrintTrait;\n    /// \n    /// fn softmax_zero_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(8388608, false),\n    ///             FixedTrait::new(16777216, false),\n    ///             FixedTrait::new(25165824, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::softmax_zero(@tensor, 1);\n    /// }\n    /// >>> [[0,0x800000],[2256043,6132564]]\n    ///     // The fixed point representation of\n    ///     // [[0, 1],[0.2689, 0.7311]]\n    /// ```\n    ///\n    fn softmax_zero(tensor: @Tensor<T>, axis: usize) -> Tensor<T>;\n    /// # NNTrait::logsoftmax\n    ///\n    /// ```rust \n    ///    fn logsoftmax(tensor: @Tensor<T>, axis: usize) -> Tensor<T>\n    /// ```\n    ///\n    /// Applies the natural log to Softmax function to an n-dimensional input Tensor consisting of values in the range \\[0,1].\n    /// \n    /// $$\n    /// \\text{log softmax}(x_i) = \\log(frac{e^{x_i}}{\\sum_{j=1}^n e^{x_j}})\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The axis along which to compute the natural lof softmax outputs.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn logsoftmax_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::logsoftmax(@tensor, 1);\n    /// }\n    ///     This will first generate the softmax output tensor\n    /// >>> [[2255697,6132911],[2255697,6132911]]\n    ///     // The fixed point representation of\n    ///     // [[0.2689, 0.7311],[0.2689, 0.7311]]\n    ///     \n    ///     Applying the natural log to this tensor yields\n    /// >>> \n    ///     // The fixed point representation of:\n    ///     // [[-1.3134, -0.3132],[-1.3134, -0.3132]]\n    /// ```\n    ///\n    fn logsoftmax(tensor: @Tensor<T>, axis: usize) -> Tensor<T>;\n    /// # NNTrait::sigmoid\n    ///\n    /// ```rust \n    ///    fn sigmoid(tensor: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the Sigmoid function to an n-dimensional input tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range \\[0,1].\n    /// \n    /// $$\n    /// \\text{sigmoid}(x_i) = \\frac{1}{1 + e^{-x_i}}\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn sigmoid_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::sigmoid(@tensor);\n    /// }\n    /// >>> [[4194304,6132564],[7388661,7990771]]\n    ///     // The fixed point representation of\n    ///     // [[0.5, 0.7310586],[0.88079703, 0.95257413]]\n    /// ```\n    ///\n    fn sigmoid(tensor: @Tensor<T>) -> Tensor<T>;\n    /// # NNTrait::softsign\n    ///\n    /// ```rust \n    ///    fn softsign(tensor: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the Softsign function to an n-dimensional input Tensor such that the elements of the n-dimensional output Tensor lie in the range \\[-1,1]. \n    /// \n    /// $$\n    /// \\text{softsign}(x_i) = \\frac{x_i}{1 + |x_i|}\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn softsign_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::softsign(@tensor);\n    /// }\n    /// >>> [[0,4194304],[5592405,6291456]]\n    ///     // The fixed point representation of\n    ///     // [[0, 0.5],[0.67, 0.75]]\n    /// ```\n    ///\n    fn softsign(tensor: @Tensor<T>) -> Tensor<T>;\n    /// # NNTrait::softplus\n    ///\n    /// ```rust \n    ///    fn softplus(tensor: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the Softplus function to an n-dimensional input Tensor such that the elements of the n-dimensional output Tensor lie in the range \\[-1,1].\n    /// \n    /// $$\n    /// \\text{softplus}(x_i) = log({1 + e^{x_i}})\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn softplus_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return NNTrait::softplus(@tensor);\n    /// }\n    /// >>> [[5814540,11016447],[17841964,25573406]]\n    ///     // The fixed point representation of\n    ///     // [[0.6931452, 1.31326096],[2.12692796, 3.04858728]]\n    /// ```\n    ///\n    fn softplus(tensor: @Tensor<T>) -> Tensor<T>;\n    /// # NNTrait::linear\n    /// \n    /// ```rust\n    /// fn linear(inputs: Tensor<T>, weights: Tensor<T>, bias: Tensor<T>) -> Tensor<T>\n    /// ```\n    /// \n    /// Performs a linear transformation of the input tensor using the provided weights and bias.\n    ///\n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - A 1D tensor representing the input tensor.\n    /// * `weights`(`@Tensor<T>`) - A 2D tensor representing the weights.\n    /// * `bias`(`@Tensor<T>`) - A 1D tensor representing the bias.\n    ///\n    /// ## Panics\n    /// \n    /// * This function asserts that the input tensor `inputs` must be 1D, weights tensor must be 2D, and bias tensor must be 1D.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` representing the result of the linear transformation.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\n    /// use orion::operators::nn::{NNTrait, I32NN};\n    /// \n    /// fn linear_example() -> Tensor<i32> {\n    ///     // We instantiate inputs here.\n    ///     let inputs = TensorTrait::<i32>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             -71, 38, 62,\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     // We instantiate weights here.\n    ///     let weights = TensorTrait::<i32>::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![\n    ///             -8,\n    ///             64,\n    ///             40,\n    ///             -33,\n    ///             -34,\n    ///             -20,\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     // We instantiate bias here.\n    ///     let bias = TensorTrait::<i32>::new(\n    ///         shape: array![2].span(),\n    ///         data: array![61, -61].span(),\n    ///     );\n    /// \n    ///     return NNTrait::linear(inputs, weights, bias);\n    /// }\n    /// >>> [5541, -250]\n    /// ````\n    ///\n    fn linear(inputs: Tensor<T>, weights: Tensor<T>, bias: Tensor<T>) -> Tensor<T>;\n    /// # NNTrait::leaky_relu\n    /// \n    /// ```rust\n    ///  fn leaky_relu(inputs: @Tensor<T>, alpha: @T) -> Tensor<T>\n    /// ```\n    ///\n    /// Applies the leaky rectified linear unit (Leaky ReLU) activation function element-wise to a given tensor.\n    ///\n    /// The Leaky ReLU function is defined as f(x) = alpha * x if x < 0, f(x) = x otherwise, where x is the input element.\n    ///\n    /// ## Args\n    /// * `inputs`(`@Tensor<T>`) - A snapshot of a tensor to which the Leaky ReLU function will be applied.\n    /// * `alpha`(`@T`) - A snapshot of a fixed point scalar that defines the alpha value of the Leaky ReLU function.\n    ///\n    /// ## Returns\n    /// A new fixed point tensor with the same shape as the input tensor and the Leaky ReLU function applied element-wise.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn leaky_relu_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(1, true),\n    ///             FixedTrait::new(2, true),\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(0, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let alpha = FixedTrait::from_felt(838861); // 0.1\n    /// \n    ///     return NNTrait::leaky_relu(@tensor, @alpha);\n    /// }\n    /// >>> [[8388608, 16777216, 838861], [1677722, 0, 0]]\n    ///      // The fixed point representation of\n    ///     [[1, 2, 0.1], [0.2, 0, 0]]\n    /// ```\n    /// \n    fn leaky_relu(inputs: @Tensor<T>, alpha: @T) -> Tensor<T>;\n    /// # NNTrait::hard_sigmoid\n    ///\n    /// ```rust \n    ///    fn hard_sigmoid(tensor: @Tensor<T>, alpha: @T, beta: @T) -> Tensor<T>;\n    /// ```\n    ///\n    /// Applies the HardSigmoid function to an n-dimensional input tensor.\n    /// \n    /// $$\n    /// \\text{HardSigmoid}(x_i) = \\text{max}(0, \\text{min}(alpha * x + beta, 1))\n    /// $$\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor.\n    /// * `alpha`(`@T`) - value of alpha.\n    /// * `beta`(`@T`) - value of beta.\n    ///\n    /// ## Returns\n    ///\n    /// A Tensor of fixed point numbers with the same shape than the input Tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP16x16, FixedTrait};\n    /// \n    /// fn hard_sigmoid_example() -> Tensor<FP16x16> {\n    ///     let tensor = TensorTrait::<FP16x16>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(13107, false),\n    ///             FixedTrait::new(32768, false),\n    ///             FixedTrait::new(65536, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let alpha = FixedTrait::new(13107, false);\n    ///     let beta = FixedTrait::new(32768, false);\n    /// \n    ///     return NNTrait::hard_sigmoid(@tensor, @alpha, @beta);\n    /// }\n    /// >>> [[32768, 35389],[39321, 45875]]\n    /// ```\n    ///\n    fn hard_sigmoid(tensor: @Tensor<T>, alpha: @T, beta: @T) -> Tensor<T>;\n    /// # NNTrait::thresholded_relu\n    /// \n    /// ```rust\n    ///  fn thresholded_relu(tensor: @Tensor<T>, alpha: @T) -> Tensor<T>\n    /// ```\n    ///\n    /// Applies the thresholded rectified linear unit (Thresholded ReLU) activation function element-wise to a given tensor.\n    ///\n    /// The Thresholded ReLU function is defined as f(x) = x if x > alpha, f(x) = 0 otherwise, where x is the input element.\n    ///\n    /// ## Args\n    /// * `tensor`(`@Tensor<T>`) - A snapshot of a tensor to which the Leaky ReLU function will be applied.\n    /// * `alpha`(`@T`) - A snapshot of a fixed point scalar that defines the alpha value of the Thresholded ReLU function.\n    ///\n    /// ## Returns\n    /// A new fixed point tensor with the same shape as the input tensor and the Thresholded ReLU function applied element-wise.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23};\n    /// use orion::operators::nn::{NNTrait, FP8x23NN};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn thresholded_relu_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(256, false),\n    ///             FixedTrait::new(512, false),\n    ///             FixedTrait::new(257, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let alpha = FixedTrait::from_felt(256); // 1.0\n    /// \n    ///     return NNTrait::leaky_relu(@tensor, @alpha);\n    /// }\n    /// >>> [[0, 0], [512, 257]]\n    /// ```\n    /// \n    fn thresholded_relu(tensor: @Tensor<T>, alpha: @T) -> Tensor<T>;\n    /// # NNTrait::space_to_depth\n    /// \n    /// ```rust\n    ///     fn space_to_depth(tensor: @Tensor<T>, blocksize: usize) -> Tensor<T>;\n    /// ```\n    ///\n    /// SpaceToDepth rearranges blocks of spatial data into depth. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the depth dimension.\n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.\n    /// * `blocksize`(`usize`) - The size of the blocks to move along [blocksize, blocksize].\n    ///\n    /// ## Returns\n    /// \n    /// A `Tensor<T>` of [N, C * blocksize * blocksize, H/blocksize, W/blocksize].\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::operators::tensor::{I8Tensor, I8TensorAdd};\n    /// use orion::numbers::NumberTrait;\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::operators::nn::I8NN;\n    /// use orion::numbers::FixedTrait;\n    ///\n    /// fn space_to_depth_example() -> Tensor<i8> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(2);\n    ///     shape.append(2);\n    ///     shape.append(4);\n    ///\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(-3);\n    ///     data.append(0);\n    ///     data.append(0);\n    ///     data.append(0);\n    ///     data.append(-1);\n    ///     data.append(1);\n    ///     data.append(-2);\n    ///     data.append(-3);\n    ///     data.append(2);\n    ///     data.append(-2);\n    ///     data.append(-3);\n    ///     data.append(-3);\n    ///     data.append(-1);\n    ///     data.append(0);\n    ///     data.append(1);\n    ///     data.append(-3);\n    ///     let tensor = TensorTrait::new(shape.span(), data.span());\n    ///     return NNTrait::space_to_depth(@tensor, 2);\n    /// }\n    /// >>> [[[[-3, 0]], [[2, -3]], [[0, 0]], [[-2, -3]], [[-1, -2]], [[-1, 1]], [[1, -3]], [[0, -3]]]]\n    /// ```\n    ///\n    fn space_to_depth(tensor: @Tensor<T>, blocksize: usize) -> Tensor<T>;\n    /// # NNTrait::depth_to_space\n    /// \n    /// ```rust\n    ///     fn depth_to_space(tensor: @Tensor<T>, blocksize: usize) -> Tensor<T>;\n    /// ```\n    ///\n    /// DepthToSpace rearranges (permutes) data from depth into blocks of spatial data. This is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of the input tensor where values from the depth dimension are moved in spatial blocks to the height and width dimensions. By default, mode = DCR. In the DCR mode, elements along the depth dimension from the input tensor are rearranged in the following order: depth, column, and then row. \n    /// \n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.\n    /// * `blocksize`(`usize`) - The size of the blocks to move along [blocksize, blocksize].\n    /// * `mode`(felt252) - DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order.\n    ///\n    /// ## Returns\n    /// \n    /// A `Tensor<T>` of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::operators::tensor::{I8Tensor, I8TensorAdd};\n    /// use orion::numbers::NumberTrait;\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::operators::nn::I8NN;\n    /// use orion::numbers::FixedTrait;\n    ///\n    /// fn depth_to_space_example() -> Tensor<i8> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(4);\n    ///     shape.append(2);\n    ///     shape.append(2);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(-2);\n    ///     data.append(0);\n    ///     data.append(-1);\n    ///     data.append(0);\n    ///     data.append(0);\n    ///     data.append(-3);\n    ///     data.append(2);\n    ///     data.append(1);\n    ///     data.append(-2);\n    ///     data.append(-2);\n    ///     data.append(0);\n    ///     data.append(-2);\n    ///     data.append(-1);\n    ///     data.append(-1);\n    ///     data.append(2);\n    ///     data.append(2);\n    ///     let tensor = TensorTrait::new(shape.span(), data.span());\n    ///     return NNTrait::depth_to_space(@tensor, 2, 'DCR');\n    /// }\n    /// >>> [[[[-2, 0, 0, -3], [-2, -1, -2, -1], [-1, 2, 0, 1], [0, 2, -2, 2]]]]\n    /// ```\n    ///\n    fn depth_to_space(tensor: @Tensor<T>, blocksize: usize, mode: felt252) -> Tensor<T>;\n    /// # NNTrait::gemm\n    /// \n    /// ```rust\n    ///     fn gemm(\n    ///         A: Tensor<T>,\n    ///         B: Tensor<T>,\n    ///         C: Option<Tensor<T>>,\n    ///         alpha: Option<T>,\n    ///         beta: Option<T>,\n    ///         transA: bool,\n    ///         transB: bool\n    ///     ) -> Tensor<T>;\n    /// ```\n    /// \n    /// Performs General Matrix multiplication: https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n    ///\n    /// * A' = transpose(A) if transA else A\n    /// * B' = transpose(B) if transB else B\n    ///\n    /// Compute `Y = alpha * A' * B' + beta * C`, where input tensor A has shape (M, K) or (K, M), input tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N), and output tensor Y has shape (M, N).\n    /// `A` will be transposed before doing the computation if attribute `transA` is `true`, same for `B` and `transB`.\n    /// \n    /// ## Args\n    ///\n    /// * `A`(`Tensor<T>`) - Input tensor A. The shape of `A` should be (M, K) if `transA` is `false`, or (K, M) if `transA` is `true`.\n    /// * `B`(`Tensor<T>`) - Input tensor B. The shape of `B` should be (K, N) if `transB` is `false`, or (N, K) if `transB` is `true`.\n    /// * `C`(`Option<Tensor<T>>`) - Optional input tensor C. The shape of C should be unidirectional broadcastable to (M, N). \n    /// * `alpha`(`Option<T>`) - Optional scalar multiplier for the product of input tensors `A * B`.\n    /// * `beta`(`Option<T>`) - Optional scalar multiplier for input tensor `C`.\n    /// * `transA`(`bool`) - Whether `A` should be transposed.\n    /// * `transB`(`bool`) - Whether `B` should be transposed.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` of shape (M, N).\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    ///     mod input_0;\n    ///     mod input_1;\n    ///     mod input_2;\n    ///     \n    ///     use orion::operators::nn::NNTrait;\n    ///     use orion::numbers::FixedTrait;\n    ///     use orion::operators::nn::FP16x16NN;\n    ///     use orion::operators::tensor::FP16x16TensorPartialEq;\n    ///\n    ///   fn gemm_all_attributes_example() -> Tensor<FP16x16> {\n    ///       let input_0 = input_0::input_0(); // shape [4;3]\n    ///       let input_1 = input_1::input_1(); // shape [5;4]\n    ///       let input_2 = input_2::input_2(); // shape [1;5]\n    ///\n    ///       let y = NNTrait::gemm(\n    ///           input_0,\n    ///           input_1,\n    ///           Option::Some(input_2),\n    ///           Option::Some(FixedTrait::new(16384, false)), // 0.25\n    ///           Option::Some(FixedTrait::new(22938, false)), // 0.35\n    ///           true,\n    ///           true\n    ///       );\n    ///\n    ///       return y;\n    ///   } \n    ///  >>> tensor of shape [3;5]\n    /// ````\n    ///\n    fn gemm(\n        A: Tensor<T>,\n        B: Tensor<T>,\n        C: Option<Tensor<T>>,\n        alpha: Option<T>,\n        beta: Option<T>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<T>;\n    ///\n    /// # NNTrait::conv\n    /// \n    /// ```rust\n    ///     conv(\n    ///         X: @Tensor<T>,\n    ///         W: @Tensor<T>,\n    ///         B: Option<Span<T>>,\n    ///         auto_pad: Option<AUTO_PAD>,\n    ///         dilations: Option<Span<usize>>,\n    ///         group: Option<usize>,\n    ///         kernel_shape: Option<Span<usize>>,\n    ///         pads: Option<Span<usize>>,\n    ///         strides: Option<Span<usize>>,\n    ///     ) -> Tensor<T>\n    /// ```\n    /// \n    /// The convolution operator consumes an input tensor and a filter (input weight tensor), and computes the output.\n    ///\n    /// ## Args\n    ///\n    /// * `X`(`@Tensor<T>`) - Input data tensor, has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W if 2D, otherwise the size is (N x C x D1 x D2 ... x Dn).\n    /// * `W`(`@Tensor<T>`) - The weight tensor, has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps if 2D, for more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn).\n    /// * `B`(`Option<@Tensor<T>>`) - Optional 1D bias to be added to the convolution, has size of M.\n    /// * `auto_pad`(`Option<AUTO_PAD>`) - Default is NOTSET, auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. NOTSET means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that `output_shape[i] = ceil(input_shape[i] / strides[i])` for each axis `i`.\n    /// * `dilations`(`Option<Span<usize>>`) - Dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.\n    /// * `group`(`Option<usize>`) - Default is 1, number of groups input channels and output channels are divided into.\n    /// * `kernel_shape`(`Option<Span<usize>>`) - The shape of the convolution kernel. If not present, should be inferred from input W.\n    /// * `pads`(`Option<Span<usize>>`) - Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.\n    /// * `strides`(`Option<Span<usize>>`) - Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` that contains the result of the convolution.\n    ///\n    /// ## Examples\n    ///     \n    /// ```rust\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::numbers::FixedTrait;\n    /// use orion::operators::nn::FP16x16NN;\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\n    /// \n    /// \n    /// fn example_conv() -> Tensor<FP16x16> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(1);\n    ///     shape.append(3);\n    ///     shape.append(3);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     let W = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(1);\n    ///     shape.append(5);\n    ///     shape.append(5);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 0, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 131072, sign: false });\n    ///     data.append(FP16x16 { mag: 196608, sign: false });\n    ///     data.append(FP16x16 { mag: 262144, sign: false });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     data.append(FP16x16 { mag: 393216, sign: false });\n    ///     data.append(FP16x16 { mag: 458752, sign: false });\n    ///     data.append(FP16x16 { mag: 524288, sign: false });\n    ///     data.append(FP16x16 { mag: 589824, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 720896, sign: false });\n    ///     data.append(FP16x16 { mag: 786432, sign: false });\n    ///     data.append(FP16x16 { mag: 851968, sign: false });\n    ///     data.append(FP16x16 { mag: 917504, sign: false });\n    ///     data.append(FP16x16 { mag: 983040, sign: false });\n    ///     data.append(FP16x16 { mag: 1048576, sign: false });\n    ///     data.append(FP16x16 { mag: 1114112, sign: false });\n    ///     data.append(FP16x16 { mag: 1179648, sign: false });\n    ///     data.append(FP16x16 { mag: 1245184, sign: false });\n    ///     data.append(FP16x16 { mag: 1310720, sign: false });\n    ///     data.append(FP16x16 { mag: 1376256, sign: false });\n    ///     data.append(FP16x16 { mag: 1441792, sign: false });\n    ///     data.append(FP16x16 { mag: 1507328, sign: false });\n    ///     data.append(FP16x16 { mag: 1572864, sign: false });\n    ///     let mut X = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     return NNTrait::conv(\n    ///         @X,\n    ///         @W,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::Some(array![3, 3].span()),\n    ///         Option::Some(array![1, 1, 1, 1].span()),\n    ///         Option::None,\n    ///     );\n    /// }\n    ///\n    /// >>> [\n    ///         [\n    ///             [\n    ///                 [12.0, 21.0, 27.0, 33.0, 24.0],  \n    ///                 [33.0, 54.0, 63.0, 72.0, 51.0],\n    ///                 [63.0, 99.0, 108.0, 117.0, 81.0],\n    ///                 [93.0, 144.0, 153.0, 162.0, 111.0],\n    ///                 [72.0, 111.0, 117.0, 123.0, 84.0],\n    ///             ]\n    ///         ]\n    ///     ]\n    ///\n    /// ````\n    ///\n    fn conv(\n        X: @Tensor<T>,\n        W: @Tensor<T>,\n        B: Option<Span<T>>,\n        auto_pad: Option<orion::operators::nn::functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<T>;\n    /// # NNTrait::conv_transpose\n    /// \n    /// ```rust\n    ///     conv_transpose(\n    ///     X: @Tensor<T>,\n    ///     W: @Tensor<T>,\n    ///     B: Option<@Tensor<T>>,\n    ///     auto_pad: Option<AUTO_PAD>,\n    ///     dilations: Option<Span<usize>>,\n    ///     group: Option<usize>,\n    ///     kernel_shape: Option<Span<usize>>,\n    ///     output_padding: Option<Span<usize>>,\n    ///     output_shape: Option<Span<usize>>,\n    ///     pads: Option<Span<usize>>,\n    ///     strides: Option<Span<usize>>,\n    /// ) -> Tensor<T>\n    /// ```\n    /// \n    /// The convolution transpose operator consumes an input tensor and a input weight tensor, and computes the output.\n    ///\n    /// ## Args\n    ///\n    /// * `X`(`@Tensor<T>`) - Input data tensor, has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W if 2D, otherwise the size is (N x C x D1 x D2 ... x Dn).\n    /// * `W`(`@Tensor<T>`) - The weight tensor, has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps if 2D, for more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn).\n    /// * `B`(`Option<@Tensor<T>>`) - Optional 1D bias to be added to the convolution, has size of M.\n    /// * `auto_pad`(`Option<AUTO_PAD>`) - Default is NOTSET, auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. NOTSET means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that `output_shape[i] = input_shape[i] * strides[i]` for each axis `i`.\n    /// * `dilations`(`Option<Span<usize>>`) - Dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.\n    /// * `group`(`Option<usize>`) - Default is 1, number of groups input channels and output channels are divided into.\n    /// * `kernel_shape`(`Option<Span<usize>>`) - The shape of the convolution kernel. If not present, should be inferred from input W.\n    /// * `output_padding`(`Option<Span<usize>>`) - Additional elements added to the side with higher coordinate indices in the output. Each padding value in \"output_padding\" must be less than the corresponding stride/dilation dimension. By default, this attribute is a zero vector. \n    /// * `output_shape`(`Option<Span<usize>>`) - The shape of the output can be explicitly set which will cause pads values to be auto generated. If output_shape is specified pads values are ignored. See doc for details for equations to generate pads.\n    /// * `pads`(`Option<Span<usize>>`) - Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.\n    /// * `strides`(`Option<Span<usize>>`) - Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` that contains the result of the convolution transpose.\n    ///\n    /// ## Examples\n    ///     \n    /// ```rust\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::numbers::FixedTrait;\n    /// use orion::operators::nn::FP16x16NN;\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\n    /// \n    /// fn example_conv_transpose() -> Tensor<FP16x16> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(2);\n    ///     shape.append(3);\n    ///     shape.append(3);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     let W = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(1);\n    ///     shape.append(3);\n    ///     shape.append(3);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 0, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 131072, sign: false });\n    ///     data.append(FP16x16 { mag: 196608, sign: false });\n    ///     data.append(FP16x16 { mag: 262144, sign: false });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     data.append(FP16x16 { mag: 393216, sign: false });\n    ///     data.append(FP16x16 { mag: 458752, sign: false });\n    ///     data.append(FP16x16 { mag: 524288, sign: false });\n    ///     let mut X = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     return NNTrait::conv_transpose(\n    ///         @X,\n    ///         @W,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///     );\n    /// \n    /// }\n    /// >>> [\n    ///         [\n    ///             [\n    ///                 [0.0, 1.0, 3.0, 3.0, 2.0],  \n    ///                 [3.0, 8.0, 15.0, 12.0, 7.0],\n    ///                 [9.0, 21.0, 36.0, 27.0, 15.0],\n    ///                 [9.0, 20.0, 33.0, 24.0, 13.0],\n    ///                 [6.0, 13.0, 21.0, 15.0, 8.0],\n    ///             ],\n    ///             [\n    ///                 [0.0, 1.0, 3.0, 3.0, 2.0],\n    ///                 [3.0, 8.0, 15.0, 12.0, 7.0],\n    ///                 [9.0, 21.0, 36.0, 27.0, 15.0],\n    ///                 [9.0, 20.0, 33.0, 24.0, 13.0],\n    ///                 [6.0, 13.0, 21.0, 15.0, 8.0],\n    ///             ],\n    ///         ]\n    ///     ]\n    ///\n    /// ````\n    ///\n    fn conv_transpose(\n        X: @Tensor<T>,\n        W: @Tensor<T>,\n        B: Option<@Tensor<T>>,\n        auto_pad: Option<orion::operators::nn::functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<T>;\n    /// # NNTrait::col2im\n    /// \n    /// ```rust\n    ///     col2im(\n    ///     data: @Tensor<T>,\n    ///     image_shape: Span<usize>,\n    ///     block_shape: Span<usize>,\n    ///     dilations: Option<Span<usize>>,\n    ///     pads: Option<Span<usize>>,\n    ///     strides: Option<Span<usize>>,\n    /// )  -> Tensor<T>\n    /// ```\n    /// \n    /// The operator rearranges column blocks back into a multidimensional image\n    ///\n    /// Col2Im behaves similarly to PyTorch's fold https://pytorch.org/docs/stable/generated/torch.nn.Fold.html, but it only supports batched multi-dimensional image tensors. Another implementation in Python with N-dimension support can be found at https://github.com/f-dangel/unfoldNd/.\n    ///\n    /// ## Args\n    ///\n    /// * `data`(`@Tensor<T>`) - Input data tensor to be rearranged from column blocks back into an image. This is a 3-dimensional tensor containing [N, C * n-ary-product(block_shape), L], where N is batch dimension, C is image channel dimension and L is number of blocks.\n    /// * `image_shape`(`Span<usize>`) - The shape of the spatial dimensions of the image after rearranging the column blocks.This is a 1-dimensional tensor with size of at least 2, containing the value [H_img, W_img] for a 2-D image or [dim_i1, dim_i2, ..., dim_iN] for a N-D image.\n    /// * `block_shape`(`Span<usize>`) - The shape of the block to apply on the input.This is a 1-dimensional tensor of size of at least 2, containing the value [H_block, W_block] for a 2-D image or [dim_b1, dim_b2, ..., dim_bN] for a N-D block.This is the block-shape before dilation is applied to it.\n    /// * `dilations`(`Option<Span<usize>>`) - 1-dimensional tensor with dilation value along each spatial axis of the image. If not present, the dilation defaults to 1 along each spatial axis of the image.\n    /// * `pads`(`Option<Span<usize>>`) - 1-dimensional tensor with padding value for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin is the number of pixels added at the beginning of axis `i` and xi_end is the number of pixels added at the end of axis `i`. If not present, the padding defaults to 0 along start and end of each spatial axis.\n    /// * `strides`(`Option<Span<usize>>`) - 1-dimensional tensor with stride value along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` output tensor produced by rearranging blocks into an image.\n    ///\n    /// ## Examples\n    ///     \n    /// ```rust\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::numbers::FixedTrait;\n    /// use orion::operators::nn::FP16x16NN;\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\n    /// \n    /// fn example_col2im() -> Tensor<FP16x16> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(5);\n    ///     shape.append(5);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 393216, sign: false });\n    ///     data.append(FP16x16 { mag: 720896, sign: false });\n    ///     data.append(FP16x16 { mag: 1048576, sign: false });\n    ///     data.append(FP16x16 { mag: 1376256, sign: false });\n    ///     data.append(FP16x16 { mag: 131072, sign: false });\n    ///     data.append(FP16x16 { mag: 458752, sign: false });\n    ///     data.append(FP16x16 { mag: 786432, sign: false });\n    ///     data.append(FP16x16 { mag: 1114112, sign: false });\n    ///     data.append(FP16x16 { mag: 1441792, sign: false });\n    ///     data.append(FP16x16 { mag: 196608, sign: false });\n    ///     data.append(FP16x16 { mag: 524288, sign: false });\n    ///     data.append(FP16x16 { mag: 851968, sign: false });\n    ///     data.append(FP16x16 { mag: 1179648, sign: false });\n    ///     data.append(FP16x16 { mag: 1507328, sign: false });\n    ///     data.append(FP16x16 { mag: 262144, sign: false });\n    ///     data.append(FP16x16 { mag: 589824, sign: false });\n    ///     data.append(FP16x16 { mag: 917504, sign: false });\n    ///     data.append(FP16x16 { mag: 1245184, sign: false });\n    ///     data.append(FP16x16 { mag: 1572864, sign: false });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     data.append(FP16x16 { mag: 0, sign: false });\n    ///     data.append(FP16x16 { mag: 983040, sign: false });\n    ///     data.append(FP16x16 { mag: 1310720, sign: false });\n    ///     data.append(FP16x16 { mag: 1638400, sign: false });\n    ///     let mut X = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     let image_shape = array![5, 5].span();\n    ///     let block_shape = array![1, 5].span();\n    /// \n    ///     return NNTrait::col2im(\n    ///         @X, image_shape, block_shape, Option::None, Option::None, Option::None,\n    ///     );\n    /// \n    /// \n    /// }\n    /// >>> [\n    ///         [\n    ///             [\n    ///                 [1.0, 2.0, 3.0, 4.0, 5.0],  \n    ///                 [6.0, 7.0, 8.0, 9.0, 0.0],\n    ///                 [11.0, 12.0, 13.0, 14.0, 15.0],\n    ///                 [16.0, 17.0, 18.0, 19.0, 20.0],\n    ///                 [21.0, 22.0, 23.0, 24.0, 25.0],\n    ///             ]\n    ///         ]\n    ///     ]\n    ///\n    /// ````\n    ///\n    ///\n    fn col2im(\n        data: @Tensor<T>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<T>;\n    /// # NNTrait::grid_sample\n    /// \n    /// ```rust\n    ///     fn grid_sample(\n    ///     X: @Tensor<T>,\n    ///     grid: @Tensor<T>,\n    ///     align_corner: Option<usize>,\n    ///     mode: Option<MODE>,\n    ///     padding_mode: Option<PADDING_MODE>,\n    /// ) -> Tensor<T>;\n    /// ```\n    /// \n    /// Given an input X and a flow-field grid, computes the output Y using X values and pixel locations from the grid.\n    /// \n    /// ## Args\n    ///\n    /// * `X`(`@Tensor<T>`) - Input tensor of shape (N, C, D1, D2, ..., Dr), where N is the batch size, C is the number of channels, D1, D2, ..., Dr are the spatial dimensions.\n    /// * `grid`(`@Tensor<T>`) - Input offset of shape (N, D1_out, D2_out, ..., Dr_out, r), where D1_out, D2_out, ..., Dr_out are the spatial dimensions of the grid and output, and r is the number of spatial dimensions. Grid specifies the sampling locations normalized by the input spatial dimensions. \n    /// * `align_corners`(`Option<usize>`) - default is 0. If align_corners=1, the extrema are considered as referring to the center points of the input's corner pixels. If align_corners=0, they are instead considered as referring to the corner points of the input's corner pixels \n    /// * `mode`(`Option<MODE>`) - default is linear. Three interpolation modes: linear (default), nearest and cubic.\n    /// * `padding_mode`(`Option<PADDING_MODE>`) - default is zeros. Support padding modes for outside grid values: `zeros`(default), `border`, `reflection`.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` of shape (N, C, D1_out, D2_out, ..., Dr_out) of the sampled values.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use orion::operators::nn::NNTrait;\n    /// use orion::numbers::FixedTrait;\n    /// use orion::operators::nn::FP16x16NN;\n    /// use orion::numbers::FP16x16;\n    /// use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\n    ///\n    /// fn example_grid_sample() -> Tensor<FP16x16> {\n    /// \n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(2);\n    ///     shape.append(4);\n    ///     shape.append(2);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 655360, sign: true });\n    ///     data.append(FP16x16 { mag: 655360, sign: true });\n    ///     data.append(FP16x16 { mag: 327680, sign: true });\n    ///     data.append(FP16x16 { mag: 327680, sign: true });\n    ///     data.append(FP16x16 { mag: 13107, sign: true });\n    ///     data.append(FP16x16 { mag: 13107, sign: true });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 13107, sign: true });\n    ///     data.append(FP16x16 { mag: 13107, sign: true });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    ///     data.append(FP16x16 { mag: 655360, sign: false });\n    /// \n    ///     let mut grid = TensorTrait::new(shape.span(), data.span());\n    /// \n    /// \n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(1);\n    ///     shape.append(3);\n    ///     shape.append(2);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 0, sign: false });\n    ///     data.append(FP16x16 { mag: 65536, sign: false });\n    ///     data.append(FP16x16 { mag: 131072, sign: false });\n    ///     data.append(FP16x16 { mag: 196608, sign: false });\n    ///     data.append(FP16x16 { mag: 262144, sign: false });\n    ///     data.append(FP16x16 { mag: 327680, sign: false });\n    ///     let mut X = TensorTrait::new(shape.span(), data.span());\n    /// \n    /// \n    ///     return NNTrait::grid_sample(\n    ///         @X, @grid, Option::None, Option::None, Option::None,\n    ///     );\n    /// \n    /// }\n    /// \n    ///}\n    /// >>> [\n    ///         [\n    ///             [\n    ///                 [0.0000, 0.0000, 1.7000, 0.0000], \n    ///                 [0.0000, 1.7000, 0.0000, 0.0000]\n    ///             ]\n    ///         ]\n    ///     ]\n    ///\n    /// ````\n    fn grid_sample(\n        X: @Tensor<T>,\n        grid: @Tensor<T>,\n        align_corner: Option<usize>,\n        mode: Option<orion::operators::nn::functional::grid_sample::MODE>,\n        padding_mode: Option<orion::operators::nn::functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<T>;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional.cairo",
        "content": "mod relu;\nmod leaky_relu;\nmod sigmoid;\nmod softmax;\nmod softmax_zero;\nmod softsign;\nmod softplus;\nmod linear;\nmod logsoftmax;\nmod thresholded_relu;\nmod hard_sigmoid;\nmod gemm;\nmod grid_sample;\nmod col2im;\nmod conv_transpose;\nmod depth_to_space;\nmod space_to_depth;\nmod conv;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/col2im.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{stride};\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor,};\nuse orion::operators::vec::{NullableVec, NullableVecImpl};\n\nfn col2im<T, MAG, +TensorTrait<T>, +NumberTrait<T, MAG>, +Copy<T>, +Drop<T>, +Add<T>, +Mul<T>,>(\n    data: @Tensor<T>,\n    image_shape: Span<usize>,\n    block_shape: Span<usize>,\n    dilations: Option<Span<usize>>,\n    pads: Option<Span<usize>>,\n    strides: Option<Span<usize>>,\n) -> Tensor<T> {\n    let dilations = match dilations {\n        Option::Some(dilations) => dilations,\n        Option::None => {\n            let mut dilations: Array<usize> = array![];\n            let mut i = 0;\n            while i != image_shape.len() {\n                dilations.append(1);\n                i += 1;\n            };\n\n            dilations.span()\n        },\n    };\n\n    let pads = match pads {\n        Option::Some(pads) => pads,\n        Option::None => {\n            let mut pads: Array<usize> = array![];\n            let mut i = 0;\n            while i != image_shape.len() {\n                pads.append(0);\n                pads.append(0);\n                i += 1;\n            };\n\n            pads.span()\n        },\n    };\n    let strides = match strides {\n        Option::Some(strides) => strides,\n        Option::None => {\n            let mut strides: Array<usize> = array![];\n            let mut i = 0;\n            while i != image_shape.len() {\n                strides.append(1);\n                i += 1;\n            };\n\n            strides.span()\n        },\n    };\n\n    let bl = prod(block_shape, 0);\n    let C = *(*data).shape.at(1) / bl;\n\n    let mut new_shape: Array<i32> = array![\n        (*(*data).shape.at(0)).try_into().unwrap(), C.try_into().unwrap(), bl.try_into().unwrap()\n    ];\n    let mut i = 2;\n    while i != (*data)\n        .shape\n        .len() {\n            new_shape.append((*(*data).shape.at(i)).try_into().unwrap());\n            i += 1;\n        };\n\n    let data = data.reshape(new_shape.span(), false);\n\n    let mut res: Array<T> = array![];\n    let data_stride = stride(data.shape);\n\n    let mut n = 0;\n    while n != *data\n        .shape\n        .at(0) {\n            let mut c = 0;\n            while c != *data\n                .shape\n                .at(1) {\n                    let data_n_c = TensorTrait::new(\n                        SpanTrait::slice(data.shape, 2, data.shape.len() - 2),\n                        SpanTrait::slice(\n                            data.data,\n                            n * *data_stride.at(0) + c * *data_stride.at(1),\n                            *data_stride.at(1)\n                        )\n                    );\n                    let mut out = col2im_naive_implementation(\n                        @data_n_c, image_shape, block_shape, dilations, pads, strides\n                    );\n                    let mut i = 0;\n                    while i != out.len() {\n                        res.append(out.at(i));\n                        i += 1;\n                    };\n\n                    c += 1;\n                };\n\n            n += 1;\n        };\n\n    let mut new_shape = array![*data.shape.at(0), *data.shape.at(1)];\n    let mut i = 0;\n    while i != image_shape.len() {\n        new_shape.append(*image_shape.at(i));\n        i += 1;\n    };\n\n    TensorTrait::new(new_shape.span(), res.span())\n}\n\nfn get_image<T, +Drop<T>, +Copy<T>>(self: @Tensor<T>, row: usize) -> Span<T> {\n    assert((*self).shape.len() == 2, 'Expected a 2D tensor');\n\n    let row_length = *self.shape[1];\n    let start = row * row_length;\n\n    (*self).data.slice(start, row_length)\n}\n\nfn col2im_naive_implementation<\n    T, MAG, +TensorTrait<T>, +NumberTrait<T, MAG>, +Copy<T>, +Drop<T>, +Add<T>,\n>(\n    data: @Tensor<T>,\n    image_shape: Span<usize>,\n    kernel_shape: Span<usize>,\n    dilations: Span<usize>,\n    pads: Span<usize>,\n    strides: Span<usize>,\n) -> NullableVec<T> {\n    let n_dims = pads.len() / 2;\n\n    col2im_shape_check(data, image_shape, kernel_shape, dilations, pads, strides);\n\n    let mut dim_col: Array<usize> = array![];\n    let mut i = 0;\n    while i != n_dims {\n        dim_col\n            .append(\n                (*image_shape.at(i)\n                    + (*pads.at(i) + *pads.at(i + n_dims))\n                    - (*dilations.at(i) * (*kernel_shape.at(i) - 1) + 1))\n                    / *strides.at(i)\n                    + 1\n            );\n\n        i += 1;\n    };\n\n    let dim_col = dim_col.span();\n\n    let stride_img = stride(image_shape);\n\n    let mut data_im = NullableVecImpl::new();\n    data_im.set(*image_shape.at(0) * *stride_img.at(0) - 1, NumberTrait::zero());\n\n    let kernel_size = prod(kernel_shape, 0);\n    let col_size = prod(dim_col, 0);\n    let mut c_col = 0;\n    while c_col != kernel_size {\n        let offset = get_indices(c_col, kernel_shape).span();\n\n        let mut col = 0;\n        while col != col_size {\n            let ind_col = get_indices(col, dim_col).span();\n            let mut ind_im: Array<usize> = array![];\n            let mut i = 0;\n            while i != n_dims {\n                if (*ind_col.at(i) * *strides.at(i) + *offset.at(i) * *dilations.at(i)) < *pads\n                    .at(i) {\n                    let neg_index = *pads.at(i)\n                        - (*ind_col.at(i) * *strides.at(i) + *offset.at(i) * *dilations.at(i));\n                    ind_im.append(*image_shape.at(i) + neg_index);\n                } else {\n                    ind_im\n                        .append(\n                            *ind_col.at(i) * *strides.at(i)\n                                + *offset.at(i) * *dilations.at(i)\n                                - *pads.at(i)\n                        );\n                }\n\n                i += 1;\n            };\n\n            let ind_im = ind_im.span();\n            if !is_out(ind_im, image_shape) {\n                let mut index = 0;\n                let mut i = 0;\n                while i != image_shape.len() {\n                    index += *stride_img.at(i) * *ind_im.at(i);\n                    i += 1;\n                };\n\n                data_im.set(index, data_im.at(index) + *(*data).data.at(c_col * col_size + col));\n            }\n\n            col += 1;\n        };\n\n        c_col += 1;\n    };\n\n    data_im\n}\n\nfn col2im_shape_check<T, +TensorTrait<T>, +Copy<T>, +Drop<T>,>(\n    X: @Tensor<T>,\n    output_shape: Span<usize>,\n    kernel_shape: Span<usize>,\n    dilations: Span<usize>,\n    pads: Span<usize>,\n    strides: Span<usize>,\n) {\n    let n_input_plane = *(*X).shape.at(0);\n\n    let kernel_size = prod(kernel_shape, 0);\n\n    assert(n_input_plane % kernel_size == 0, 'wrong input dimension');\n\n    let input_length = *(*X).shape.at(1);\n    let n_dims = output_shape.len();\n    let mut n_blocks: Array<usize> = array![];\n\n    let mut i = 0;\n    while i != n_dims {\n        n_blocks\n            .append(\n                (*output_shape.at(i)\n                    + (*pads.at(i) + *pads.at(i + n_dims))\n                    - *dilations.at(i) * (*kernel_shape.at(i) - 1)\n                    - 1)\n                    / *strides.at(i)\n                    + 1\n            );\n        i += 1;\n    };\n\n    let block_size = prod(n_blocks.span(), 0);\n\n    assert(input_length == block_size, 'input_length != block_size');\n}\n\nfn get_indices(index: usize, shape: Span<usize>,) -> Array<usize> {\n    let mut i = index;\n    let mut res: Array<usize> = array![];\n    let mut k = shape.len() - 1;\n    while k != 0 {\n        let m = i % *shape.at(k);\n        res.append(m);\n        i -= m;\n        i /= *shape.at(k);\n        k -= 1;\n    };\n\n    let mut new_res: Array<usize> = array![];\n    new_res.append(i);\n    let mut i = shape.len() - 1;\n    while i != 0 {\n        new_res.append(*res.at(i - 1));\n        i -= 1;\n    };\n\n    new_res\n}\n\nfn is_out(ind: Span<usize>, shape: Span<usize>,) -> bool {\n    let mut n = 0;\n    let is_out = loop {\n        if n == ind.len() {\n            break false;\n        }\n        let s = *shape.at(n);\n        let i = *ind.at(n);\n        if i < 0 {\n            break true;\n        }\n        if i >= s {\n            break true;\n        }\n        n += 1;\n    };\n\n    is_out\n}\n\nfn prod<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +Mul<T>,>(\n    pA: Span<T>, start: usize\n) -> T {\n    let mut i = start;\n    let mut prod = NumberTrait::one();\n    while i != pA.len() {\n        prod = prod * (*pA.at(i));\n        i += 1;\n    };\n\n    prod\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/conv.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::NumberTrait;\nuse orion::numbers::{U32IntoI32, I32IntoU32, I32Div, I32Number};\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor,};\nuse orion::operators::vec::{NullableVec, NullableVecImpl};\nuse orion::operators::tensor::core::{stride};\n\n#[derive(Copy, Drop)]\nenum AUTO_PAD {\n    NOTSET,\n    SAME_UPPER,\n    SAME_LOWER,\n    VALID\n}\n\nfn conv<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +Copy<T>,\n    +Drop<T>,\n    +Add<T>,\n    +Mul<T>,\n    +AddEq<T>,\n    +PrintTrait<T>,\n>(\n    X: @Tensor<T>,\n    W: @Tensor<T>,\n    B: Option<Span<T>>,\n    auto_pad: Option<AUTO_PAD>,\n    dilations: Option<Span<usize>>,\n    group: Option<usize>,\n    kernel_shape: Option<Span<usize>>,\n    pads: Option<Span<usize>>,\n    strides: Option<Span<usize>>,\n) -> Tensor<T> {\n    let nd = (*X).shape.len() - 2;\n\n    assert((*X).shape.len() >= 3, 'X must have at least 3 dim');\n\n    let dilations = match dilations {\n        Option::Some(dilations) => dilations,\n        Option::None => {\n            let mut dilations: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                dilations.append(1);\n                i += 1;\n            };\n\n            dilations.span()\n        },\n    };\n    let kernel_shape = match kernel_shape {\n        Option::Some(kernel_shape) => kernel_shape,\n        Option::None => {\n            let mut kernel_shape: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*W).shape.len() {\n                kernel_shape.append(*(*W).shape.at(i));\n                i += 1;\n            };\n\n            kernel_shape.span()\n        },\n    };\n    let pads = match pads {\n        Option::Some(pads) => pads,\n        Option::None => {\n            let mut pads: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                pads.append(0);\n                pads.append(0);\n                i += 1;\n            };\n\n            pads.span()\n        },\n    };\n    let strides = match strides {\n        Option::Some(strides) => strides,\n        Option::None => {\n            let mut strides: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                strides.append(1);\n                i += 1;\n            };\n\n            strides.span()\n        },\n    };\n\n    let group = match group {\n        Option::Some(group) => group,\n        Option::None => { 1 },\n    };\n    let auto_pad = match auto_pad {\n        Option::Some(auto_pad) => auto_pad,\n        Option::None => { AUTO_PAD::NOTSET },\n    };\n\n    if group > 1 {\n        let sN = *(*X).shape.at(0);\n\n        let mut res_b: Array<usize> = array![];\n        let mut res_cv = array![];\n\n        let mut td = 0;\n        let mg = *(*W).shape.at(0) / group;\n        let dw = *(*W).shape.at(1);\n\n        let X_stride = stride((*X).shape);\n        let mut gx_shape = array![1, dw];\n        let mut i = 2;\n        while i != (*X).shape.len() {\n            gx_shape.append(*(*X).shape.at(i));\n            i += 1;\n        };\n\n        let gx_shape = gx_shape.span();\n\n        let W_stride = stride((*W).shape);\n        let mut gw_shape = array![mg];\n        let mut i = 1;\n        while i != (*W).shape.len() {\n            gw_shape.append(*(*W).shape.at(i));\n            i += 1;\n        };\n\n        let gw_shape = gw_shape.span();\n\n        let mut b = 0;\n        while b != sN {\n            let mut g = 0;\n            while g != group {\n                let gx = TensorTrait::new(\n                    gx_shape,\n                    SpanTrait::slice(\n                        (*X).data,\n                        b * *X_stride.at(0) + (g * dw) * *X_stride.at(1),\n                        *X_stride.at(1) * dw\n                    )\n                );\n                let gw = TensorTrait::new(\n                    gw_shape,\n                    SpanTrait::slice((*W).data, (g * mg) * *W_stride.at(0), *W_stride.at(0) * mg)\n                );\n                let cv = conv(\n                    @gx,\n                    @gw,\n                    Option::None,\n                    Option::Some(auto_pad),\n                    Option::Some(dilations),\n                    Option::Some(1),\n                    Option::Some(kernel_shape),\n                    Option::Some(pads),\n                    Option::Some(strides)\n                );\n\n                if b == 0 {\n                    td += *cv.shape.at(1);\n                }\n\n                res_b.append(b);\n                res_cv.append(cv);\n                g += 1;\n            };\n\n            b += 1;\n        };\n\n        let res_b = res_b.span();\n        let res_cv = res_cv.span();\n\n        let mut final_shape = array![sN, td];\n\n        let mut cv = *res_cv.at(0);\n\n        let mut i = 2;\n        while i != cv.shape.len() {\n            final_shape.append(*cv.shape.at(i));\n            i += 1;\n        };\n\n        let final_shape = final_shape.span();\n\n        let mut final: Array<T> = array![];\n\n        let mut p = 0;\n        let mut i = 0;\n\n        while i != res_b.len() {\n            let cv = *res_cv.at(i);\n\n            let mut n = 0;\n            while n != cv.data.len() {\n                final.append(*cv.data.at(n));\n                n += 1;\n            };\n\n            p += *cv.shape.at(1);\n            if p >= td {\n                p = 0;\n            }\n\n            i += 1;\n        };\n\n        let final = final.span();\n\n        let final = match B {\n            Option::Some(B) => {\n                let mut final_b: Array<T> = array![];\n                let final_stride = stride(final_shape);\n                let mut i = 0;\n                while i != *final_shape.at(0) {\n                    let mut j = 0;\n                    while j != B.len() {\n                        let mut k = 0;\n                        while k != *final_stride.at(1) {\n                            final_b\n                                .append(\n                                    *final.at(i * *final_stride.at(0) + j * *final_stride.at(1) + k)\n                                        + *B.at(j)\n                                );\n                            k += 1;\n                        };\n\n                        j += 1;\n                    };\n\n                    i += 1;\n                };\n\n                final_b.span()\n            },\n            Option::None => { final },\n        };\n\n        return TensorTrait::new(final_shape, final);\n    }\n\n    // group == 1\n    if *dilations.at(0) != 1 || min(dilations.clone()) != max(dilations.clone()) {\n        // computation of the dilated kernel\n        let nd = dilations.len();\n        let mut new_kernel_shape: Array<usize> = array![];\n        let mut new_shape: Array<usize> = array![];\n        new_shape.append_span(SpanTrait::slice((*W).shape, 0, (*W).shape.len() - nd));\n\n        let mut i = 0;\n        while i != dilations.len() {\n            let d = *dilations.at(i);\n            let di = (*W).shape.len() - nd + i;\n            new_shape.append(*(*W).shape.at(di) + (*(*W).shape.at(di) - 1) * (d - 1));\n            new_kernel_shape.append(*kernel_shape.at(i) + (*kernel_shape.at(i) - 1) * (d - 1));\n            i += 1;\n        };\n\n        let new_shape = new_shape.span();\n        let new_w_strides = stride(new_shape);\n\n        let mut new_w = NullableVecImpl::new();\n        new_w.set(*new_shape.at(0) * *new_w_strides.at(0) - 1, NumberTrait::zero());\n\n        let mut indices = array![];\n\n        indices.append(arange(0, *new_shape.at(0), 1));\n        indices.append(arange(0, *new_shape.at(1), 1));\n\n        let mut i = 0;\n        while i != dilations.len() {\n            let d = *dilations.at(i);\n            let di = (*W).shape.len() - nd + i;\n            indices.append(arange(0, *new_shape.at(di), d));\n            i += 1;\n        };\n\n        let set_of_all_indices = cartesian(indices.span());\n\n        let mut new_w_arr: Array<T> = array![];\n\n        let mut i = 0;\n        let mut prev = 0;\n        while i != (*W).data.len() {\n            let nd_index = *set_of_all_indices.at(i);\n            let mut flatten_index = 0;\n            let mut j = 0;\n            while j != nd_index.len() {\n                flatten_index += *nd_index.at(j) * *new_w_strides.at(j);\n                j += 1;\n            };\n\n            if flatten_index > prev + 1 {\n                let mut j = prev + 1;\n                while j != flatten_index {\n                    new_w_arr.append(NumberTrait::zero());\n                };\n\n                j += 1;\n            }\n\n            new_w_arr.append(*(*W).data.at(i));\n            new_w.set(flatten_index, *(*W).data.at(i));\n            prev = flatten_index;\n            i += 1;\n        };\n    }\n\n    let pads = match auto_pad {\n        AUTO_PAD::NOTSET => { pads },\n        AUTO_PAD::SAME_UPPER => {\n            let mut head: Array<usize> = array![];\n            let mut tail: Array<usize> = array![];\n            let mut i = 0;\n            while i != nd {\n                let d = *(*X).shape.at(i);\n                let target_size = (d + *strides.at(i) - 1) / *strides.at(i);\n                let pad_needed = (target_size - 1) * *strides.at(i) + *kernel_shape.at(i) - d;\n                let pad_head = pad_needed / 2;\n                let pad_tail = pad_needed - pad_head;\n                head.append(pad_head);\n                tail.append(pad_tail);\n                i += 1;\n            };\n\n            head.append_span(tail.span());\n            let pads = head.span();\n            pads\n        },\n        AUTO_PAD::SAME_LOWER => {\n            let mut head: Array<usize> = array![];\n            let mut tail: Array<usize> = array![];\n            let mut i = 0;\n            while i != nd {\n                let d = *(*X).shape.at(i);\n                let target_size = (d + *strides.at(i) - 1) / *strides.at(i);\n                let pad_needed = (target_size - 1) * *strides.at(i) + *kernel_shape.at(i) - d;\n                let pad_head = (pad_needed + 1) / 2;\n                let pad_tail = pad_needed - pad_head;\n                head.append(pad_head);\n                tail.append(pad_tail);\n                i += 1;\n            };\n\n            head.append_span(tail.span());\n            let pads = head.span();\n            pads\n        },\n        AUTO_PAD::VALID => {\n            let mut head: Array<usize> = array![];\n            let mut tail: Array<usize> = array![];\n            let mut i = 0;\n            while i != nd {\n                let d = *(*X).shape.at(i);\n                let target_size = (d + *strides.at(i) - 1) / *strides.at(i);\n                let pad_needed = (target_size - 1) * *strides.at(i) + *kernel_shape.at(i) - d;\n                let pad_head = pad_needed / 2;\n                let pad_tail = pad_needed - pad_head;\n                head.append(pad_head);\n                tail.append(pad_tail);\n                i += 1;\n            };\n\n            head.append_span(tail.span());\n            let pads = head.span();\n            pads\n        },\n    };\n\n    if (*X).shape.len() == 3 {\n        let sN = *(*X).shape.at(0);\n        let sC = *(*X).shape.at(1);\n        let sH = *(*X).shape.at(2);\n\n        let sM = *(*W).shape.at(0);\n\n        let kh = *kernel_shape.at(0);\n        let sth = *strides.at(0);\n\n        let h_out = ((sH - kh + *pads.at(0) + *pads.at(1)) / sth) + 1;\n\n        let h0 = *pads.at(0);\n        let oh: i32 = -1 * (kh % 2).into();\n        let bh: i32 = -h0.into();\n        let eh = h_out * sth;\n        let mut res = NullableVecImpl::new();\n\n        let res_shape = array![sN, sM, h_out].span();\n        let res_strides = stride(res_shape);\n        res.set(sN * *res_strides.at(0) - 1, NumberTrait::zero());\n\n        match B {\n            Option::Some(B) => {\n                let mut i = 0;\n                while i != sN {\n                    let mut j = 0;\n                    while j != sM {\n                        let b_j = *B.at(j);\n                        let mut k = 0;\n                        while k != h_out {\n                            res.set(i * *res_strides.at(0) + j * *res_strides.at(1) + k, b_j);\n                            k += 1;\n                        };\n\n                        j += 1;\n                    };\n\n                    i += 1;\n                };\n            },\n            Option::None => {},\n        }\n\n        let mut n = 0;\n        while n != sN {\n            let mut nw = 0;\n            while nw != sM {\n                let mut c = 0;\n                while c != sC {\n                    let w = SpanTrait::slice((*W).data, nw * sC * kh + c * kh, kh);\n\n                    let mut io = bh;\n                    while io < eh.into() {\n                        let hr = (io - bh) / sth.into();\n                        if hr < h_out.into() {\n                            let i = io + (kh % 2).into();\n\n                            let ih1 = I32Number::max(0, i + oh).into();\n                            let ih2 = I32Number::min(i + oh + kh.into(), sH.into()).into();\n                            let img = SpanTrait::slice((*X).data, n * sN + c * sC + ih1, ih2 - ih1);\n\n                            let s = if w.len() != img.len() {\n                                let jh1 = I32Number::max(0, -i - oh).into();\n                                let jh2 = I32Number::min(sH.into() - (i + oh), kh.into()).into();\n\n                                let w_ = SpanTrait::slice(w, jh1, jh2 - jh1);\n                                assert(w_.len() == img.len(), 'unexpected w and img len');\n                                dot(img, w_)\n                            } else {\n                                dot(img, w)\n                            };\n\n                            let hr = if hr < 0 {\n                                *res_strides.at(1) - hr.into()\n                            } else {\n                                hr.into()\n                            };\n\n                            res\n                                .set(\n                                    n * *res_strides.at(0) + nw * *res_strides.at(1) + hr,\n                                    res.at(n * *res_strides.at(0) + nw * *res_strides.at(1) + hr)\n                                        + s\n                                );\n                        }\n\n                        io += sth.into();\n                    };\n\n                    c += 1;\n                };\n\n                nw += 1;\n            };\n\n            n += 1;\n        };\n\n        let mut res_data: Array<T> = array![];\n        let mut i = 0;\n        while i != res.len() {\n            res_data.append(res.at(i));\n            i += 1;\n        };\n\n        return TensorTrait::new(res_shape, res_data.span());\n    }\n\n    if (*X).shape.len() == 4 {\n        let sN = *(*X).shape.at(0);\n        let sC = *(*X).shape.at(1);\n        let sH = *(*X).shape.at(2);\n        let sW = *(*X).shape.at(3);\n\n        let sM = *(*W).shape.at(0);\n\n        let kh = *kernel_shape.at(0);\n        let kw = *kernel_shape.at(1);\n\n        let sth = *strides.at(0);\n        let stw = *strides.at(1);\n\n        let h_out = ((sH - kh + *pads.at(0) + *pads.at(2)) / sth) + 1;\n        let w_out = ((sW - kw + *pads.at(1) + *pads.at(3)) / stw) + 1;\n\n        let h0 = *pads.at(0);\n        let w0 = *pads.at(1);\n\n        let oh: i32 = -1 * (kh % 2).into();\n        let ow: i32 = -1 * (kw % 2).into();\n        let bh: i32 = -h0.into();\n        let bw: i32 = -w0.into();\n        let eh = h_out * sth;\n        let ew = w_out * stw;\n\n        let mut res = NullableVecImpl::new();\n        let res_shape = array![sN, sM, h_out, w_out].span();\n        let res_strides = stride(res_shape);\n        res.set(sN * *res_strides.at(0) - 1, NumberTrait::zero());\n\n        match B {\n            Option::Some(B) => {\n                let mut i = 0;\n                while i != sN {\n                    let mut j = 0;\n                    while j != sM {\n                        let b_j = *B.at(j);\n                        let mut k = 0;\n                        while k != h_out {\n                            let mut l = 0;\n                            while l != w_out {\n                                res\n                                    .set(\n                                        i * *res_strides.at(0)\n                                            + j * *res_strides.at(1)\n                                            + k * *res_strides.at(2)\n                                            + l,\n                                        b_j\n                                    );\n                                l += 1;\n                            };\n\n                            k += 1;\n                        };\n\n                        j += 1;\n                    };\n\n                    i += 1;\n                };\n            },\n            Option::None => {},\n        }\n\n        let mut n = 0;\n        while n != sN {\n            let mut nw = 0;\n            while nw != sM {\n                let mut c = 0;\n                while c != sC {\n                    let w = SpanTrait::slice(\n                        (*W).data, nw * (sC * kh * kw) + c * (kh * kw), kh * kw\n                    );\n\n                    let mut io = bh;\n                    while io < eh.into() {\n                        let hr = (io - bh) / sth.into();\n                        if hr < h_out.into() {\n                            let i = io + (kh % 2).into();\n                            let ih1 = I32Number::max(0, i + oh).into();\n                            let ih2 = I32Number::min(i + oh + kh.into(), sH.into()).into();\n\n                            let mut jo = bw;\n                            while jo < ew.into() {\n                                let wr = (jo - bw) / stw.into();\n                                if wr < w_out.into() {\n                                    let j = jo + (kw % 2).into();\n                                    let iw1 = I32Number::max(0, j + ow).into();\n                                    let iw2 = I32Number::min(j + ow + kw.into(), sW.into()).into();\n\n                                    let mut img: Array<T> = array![];\n                                    let mut ihi = ih1;\n                                    while ihi != ih2 {\n                                        img\n                                            .append_span(\n                                                SpanTrait::slice(\n                                                    (*X).data,\n                                                    n * (sC * sH * sW)\n                                                        + c * (sH * sW)\n                                                        + ihi * sW\n                                                        + iw1,\n                                                    iw2 - iw1\n                                                )\n                                            );\n                                        ihi += 1;\n                                    };\n\n                                    let img = img.span();\n\n                                    let s = if w.len() != img.len() {\n                                        let jh1 = I32Number::max(0, -i - oh).into();\n                                        let jh2 = I32Number::min(sH.into() - (i + oh), kh.into())\n                                            .into();\n\n                                        let jw1 = I32Number::max(0, -j - ow).into();\n                                        let jw2 = I32Number::min(sW.into() - (j + ow), kw.into())\n                                            .into();\n\n                                        let mut w_: Array<T> = array![];\n                                        let mut jhj = jh1;\n                                        while jhj != jh2 {\n                                            w_\n                                                .append_span(\n                                                    SpanTrait::slice(w, jhj * kw + jw1, jw2 - jw1)\n                                                );\n                                            jhj += 1;\n                                        };\n\n                                        let w_ = w_.span();\n\n                                        assert(w_.len() == img.len(), 'unexpected w and img len');\n                                        dot(img, w_)\n                                    } else {\n                                        dot(img, w)\n                                    };\n\n                                    let hr = if hr < 0 {\n                                        h_out - hr.into()\n                                    } else {\n                                        hr.into()\n                                    };\n\n                                    let wr = if wr < 0 {\n                                        w_out - wr.into()\n                                    } else {\n                                        wr.into()\n                                    };\n\n                                    res\n                                        .set(\n                                            n * *res_strides.at(0)\n                                                + nw * *res_strides.at(1)\n                                                + hr * *res_strides.at(2)\n                                                + wr,\n                                            res\n                                                .at(\n                                                    n * *res_strides.at(0)\n                                                        + nw * *res_strides.at(1)\n                                                        + hr * *res_strides.at(2)\n                                                        + wr\n                                                )\n                                                + s\n                                        );\n                                }\n\n                                jo += stw.into();\n                            };\n                        }\n\n                        io += sth.into();\n                    };\n\n                    c += 1;\n                };\n\n                nw += 1;\n            };\n\n            n += 1;\n        };\n\n        let mut res_data: Array<T> = array![];\n        let mut i = 0;\n        while i != res.len() {\n            res_data.append(res.at(i));\n            i += 1;\n        };\n\n        return TensorTrait::new(res_shape, res_data.span());\n    }\n\n    if (*X).shape.len() == 5 {\n        let sN = *(*X).shape.at(0);\n        let sC = *(*X).shape.at(1);\n        let sH = *(*X).shape.at(2);\n        let sW = *(*X).shape.at(3);\n        let sZ = *(*X).shape.at(4);\n\n        let sM = *(*W).shape.at(0);\n\n        let kh = *kernel_shape.at(0);\n        let kw = *kernel_shape.at(1);\n        let kz = *kernel_shape.at(2);\n\n        let sth = *strides.at(0);\n        let stw = *strides.at(1);\n        let stz = *strides.at(2);\n\n        let h_out = ((sH - kh + *pads.at(0) + *pads.at(3)) / sth) + 1;\n        let w_out = ((sW - kw + *pads.at(1) + *pads.at(4)) / stw) + 1;\n        let z_out = ((sZ - kz + *pads.at(2) + *pads.at(5)) / stz) + 1;\n\n        let h0 = *pads.at(0);\n        let w0 = *pads.at(1);\n        let z0 = *pads.at(2);\n\n        let oh: i32 = -1 * (kh % 2).into();\n        let ow: i32 = -1 * (kw % 2).into();\n        let oz: i32 = -1 * (kz % 2).into();\n\n        let bh: i32 = -h0.into();\n        let bw: i32 = -w0.into();\n        let bz: i32 = -z0.into();\n\n        let eh = h_out * sth;\n        let ew = w_out * stw;\n        let ez = z_out * stz;\n\n        let mut res = NullableVecImpl::new();\n        let res_shape = array![sN, sM, h_out, w_out, z_out].span();\n        let res_strides = stride(res_shape);\n        res.set(sN * *res_strides.at(0) - 1, NumberTrait::zero());\n\n        match B {\n            Option::Some(B) => {\n                let mut i = 0;\n                while i != sN {\n                    let mut j = 0;\n                    while j != sM {\n                        let b_j = *B.at(j);\n                        let mut k = 0;\n                        while k != h_out {\n                            let mut l = 0;\n                            while l != w_out {\n                                let mut m = 0;\n                                while m != z_out {\n                                    res\n                                        .set(\n                                            i * *res_strides.at(0)\n                                                + j * *res_strides.at(1)\n                                                + k * *res_strides.at(2)\n                                                + l * *res_strides.at(3)\n                                                + m,\n                                            b_j\n                                        );\n                                    m += 1;\n                                };\n\n                                l += 1;\n                            };\n\n                            k += 1;\n                        };\n\n                        j += 1;\n                    };\n\n                    i += 1;\n                };\n            },\n            Option::None => {},\n        }\n\n        let mut n = 0;\n        while n != sN {\n            let mut nw = 0;\n            while nw != sM {\n                let mut c = 0;\n                while c != sC {\n                    let w = SpanTrait::slice(\n                        (*W).data, nw * (sC * kh * kw * kz) + c * (kh * kw * kz), kh * kw * kz\n                    );\n\n                    let mut io = bh;\n                    while io < eh.into() {\n                        let hr = (io - bh) / sth.into();\n                        if hr < h_out.into() {\n                            let i = io + (kh % 2).into();\n                            let ih1 = I32Number::max(0, i + oh).into();\n                            let ih2 = I32Number::min(i + oh + kh.into(), sH.into()).into();\n\n                            let mut jo = bw;\n                            while jo < ew.into() {\n                                let wr = (jo - bw) / stw.into();\n                                if wr < w_out.into() {\n                                    let j = jo + (kw % 2).into();\n                                    let iw1 = I32Number::max(0, j + ow).into();\n                                    let iw2 = I32Number::min(j + ow + kw.into(), sW.into()).into();\n\n                                    let mut zo = bz;\n                                    while zo < ez.into() {\n                                        let zr = (zo - bz) / stz.into();\n                                        if zr < z_out.into() {\n                                            let z = zo + (kz % 2).into();\n                                            let iz1 = I32Number::max(0, z + oz).into();\n                                            let iz2 = I32Number::min(z + oz + kz.into(), sW.into())\n                                                .into();\n\n                                            let mut img: Array<T> = array![];\n                                            let mut ihi = ih1;\n                                            while ihi != ih2 {\n                                                let mut iwi = iw1;\n                                                while iwi != iw2 {\n                                                    img\n                                                        .append_span(\n                                                            SpanTrait::slice(\n                                                                (*X).data,\n                                                                n * (sC * sH * sW * sZ)\n                                                                    + c * (sH * sW * sZ)\n                                                                    + ihi * (sW * sZ)\n                                                                    + iwi * sZ\n                                                                    + iz1,\n                                                                iz2 - iz1\n                                                            )\n                                                        );\n                                                    iwi += 1;\n                                                };\n\n                                                ihi += 1;\n                                            };\n\n                                            let img = img.span();\n\n                                            let s = if w.len() != img.len() {\n                                                let jh1 = I32Number::max(0, -i - oh).into();\n                                                let jh2 = I32Number::min(\n                                                    sH.into() - (i + oh), kh.into()\n                                                )\n                                                    .into();\n\n                                                let jw1 = I32Number::max(0, -j - ow).into();\n                                                let jw2 = I32Number::min(\n                                                    sW.into() - (j + ow), kw.into()\n                                                )\n                                                    .into();\n\n                                                let jz1 = I32Number::max(0, -z - oz).into();\n                                                let jz2 = I32Number::min(\n                                                    sZ.into() - (z + oz), kz.into()\n                                                )\n                                                    .into();\n\n                                                let mut w_: Array<T> = array![];\n                                                let mut jhj = jh1;\n                                                while jhj != jh2 {\n                                                    let mut jwj = jw1;\n                                                    while jwj != jw2 {\n                                                        w_\n                                                            .append_span(\n                                                                SpanTrait::slice(\n                                                                    w,\n                                                                    jhj * kw * kz + jwj * kz + jz1,\n                                                                    jz2 - jz1\n                                                                )\n                                                            );\n                                                        jwj += 1;\n                                                    };\n\n                                                    jhj += 1;\n                                                };\n\n                                                let w_ = w_.span();\n\n                                                assert(\n                                                    w_.len() == img.len(),\n                                                    'unexpected w and img len'\n                                                );\n                                                dot(img, w_)\n                                            } else {\n                                                dot(img, w)\n                                            };\n\n                                            let hr = if hr < 0 {\n                                                h_out - hr.into()\n                                            } else {\n                                                hr.into()\n                                            };\n\n                                            let wr = if wr < 0 {\n                                                w_out - wr.into()\n                                            } else {\n                                                wr.into()\n                                            };\n\n                                            let zr = if zr < 0 {\n                                                z_out - zr.into()\n                                            } else {\n                                                zr.into()\n                                            };\n\n                                            res\n                                                .set(\n                                                    n * *res_strides.at(0)\n                                                        + nw * *res_strides.at(1)\n                                                        + hr * *res_strides.at(2)\n                                                        + wr * *res_strides.at(3)\n                                                        + zr,\n                                                    res\n                                                        .at(\n                                                            n * *res_strides.at(0)\n                                                                + nw * *res_strides.at(1)\n                                                                + hr * *res_strides.at(2)\n                                                                + wr * *res_strides.at(3)\n                                                                + zr\n                                                        )\n                                                        + s\n                                                );\n                                        }\n\n                                        zo += stz.into();\n                                    };\n                                }\n\n                                jo += stw.into();\n                            };\n                        }\n\n                        io += sth.into();\n                    };\n\n                    c += 1;\n                };\n\n                nw += 1;\n            };\n\n            n += 1;\n        };\n\n        let mut res_data: Array<T> = array![];\n        let mut i = 0;\n        while i != res.len() {\n            res_data.append(res.at(i));\n            i += 1;\n        };\n\n        return TensorTrait::new(res_shape, res_data.span());\n    }\n\n    // if (*X).shape.len() > 5\n\n    let sN = *(*X).shape.at(0);\n    let sC = *(*X).shape.at(1);\n\n    let sM = *(*W).shape.at(0);\n\n    let w_stride = stride((*W).shape);\n    let x_stride = stride((*X).shape);\n\n    let mut shape_out: Array<usize> = array![];\n    let mut o_index: Array<i32> = array![];\n    let mut b_index: Array<i32> = array![];\n    let mut e_index: Array<usize> = array![];\n\n    let mut range_len: Array<usize> = array![];\n\n    let mut i = 0;\n    while i != nd {\n        shape_out\n            .append(\n                ((*(*X).shape.at(2 + i) - *kernel_shape.at(i) + *pads.at(i) + *pads.at(i + nd))\n                    / *strides.at(i))\n                    + 1\n            );\n        let k = *kernel_shape.at(i);\n        o_index.append(-1 * (k % 2).into());\n        b_index.append(-(*pads.at(i)).into());\n        e_index.append(*shape_out.at(i) * *strides.at(i));\n        range_len.append((((*e_index.at(i)).into() - *b_index.at(i)).into()) / *strides.at(i));\n        i += 1;\n    };\n\n    let o_index = o_index.span();\n    let b_index = b_index.span();\n\n    let shape_out = shape_out.span();\n\n    let range_len = range_len.span();\n    let range_stride = stride(range_len);\n\n    let mut res_shape = array![sN, sM];\n    res_shape.append_span(shape_out);\n    let res_shape = res_shape.span();\n\n    let res_strides = stride(res_shape);\n\n    let mut res = NullableVecImpl::new();\n    res.set(sN * *res_strides.at(0) - 1, NumberTrait::zero());\n\n    match B {\n        Option::Some(B) => {\n            let mut i = 0;\n            while i != sN {\n                let mut j = 0;\n                while j != sM {\n                    let b_j = *B.at(j);\n                    let mut k = 0;\n                    while k != *res_strides.at(1) {\n                        res.set(i * *res_strides.at(0) + j * *res_strides.at(1) + k, b_j);\n                        k += 1;\n                    };\n\n                    j += 1;\n                };\n\n                i += 1;\n            };\n        },\n        Option::None => {},\n    }\n\n    let mut n = 0;\n    while n != sN {\n        let mut nw = 0;\n        while nw != sM {\n            let mut c = 0;\n            while c != sC {\n                let w = SpanTrait::slice(\n                    (*W).data, nw * *w_stride.at(0) + c * *w_stride.at(1), *w_stride.at(1)\n                );\n                let mut i = 0;\n                while i != *range_len.at(0) * *range_stride.at(0) {\n                    let mut io_index: Array<i32> = array![];\n                    let mut r_index: Array<i32> = array![];\n                    let mut flatten_index = i;\n\n                    let mut nx = 0;\n                    while nx != nd {\n                        let (n_index, rem) = DivRem::div_rem(\n                            flatten_index, (*range_stride.at(nx)).try_into().unwrap()\n                        );\n\n                        flatten_index = rem;\n                        io_index\n                            .append(n_index.into() * (*strides.at(nx)).into() + *b_index.at(nx));\n                        r_index.append(n_index.into());\n                        nx += 1;\n                    };\n\n                    if r_index_check(r_index.span(), shape_out) {\n                        let mut indices: Array<i32> = array![];\n                        let mut i1_index: Array<usize> = array![];\n                        let mut i2_index: Array<usize> = array![];\n                        let mut idiff_index: Array<usize> = array![];\n\n                        let mut nx = 0;\n                        while nx != nd {\n                            indices.append(*io_index.at(nx) + (*kernel_shape.at(nx) % 2).into());\n                            i1_index\n                                .append(\n                                    I32Number::max(0, *indices.at(nx) + *o_index.at(nx)).into()\n                                );\n                            i2_index\n                                .append(\n                                    I32Number::min(\n                                        (*(*X).shape.at(nx + 2)).into(),\n                                        *indices.at(nx)\n                                            + *o_index.at(nx)\n                                            + (*kernel_shape.at(nx)).into()\n                                    )\n                                        .into()\n                                );\n\n                            if nx != nd - 1 {\n                                idiff_index.append(*i2_index.at(nx) - *i1_index.at(nx));\n                            }\n                            nx += 1;\n                        };\n\n                        let i1_index = i1_index.span();\n                        let mut img: Array<T> = array![];\n\n                        let img = if nx == 1 {\n                            let img = SpanTrait::slice(\n                                (*X).data,\n                                n * sN + c * sC + *i1_index.at(nd - 1),\n                                *i2_index.at(nd - 1) - *i1_index.at(nd - 1)\n                            );\n                            img\n                        } else {\n                            let i_stride = stride(idiff_index.span());\n\n                            let mut ii = 0;\n                            while ii != *i_stride.at(0) * *idiff_index.at(0) {\n                                let mut flatten_index = ii;\n                                let mut start = n * *x_stride.at(0) + c * *x_stride.at(1);\n\n                                let mut nx = 0;\n                                while nx != nd - 1 {\n                                    let (ii_index, rem) = DivRem::div_rem(\n                                        flatten_index, (*i_stride.at(nx)).try_into().unwrap()\n                                    );\n                                    flatten_index = rem;\n\n                                    start += (*i1_index.at(nx) + ii_index) * *x_stride.at(2 + nx);\n                                    nx += 1;\n                                };\n\n                                img\n                                    .append_span(\n                                        SpanTrait::slice(\n                                            (*X).data,\n                                            start + *i1_index.at(nd - 1),\n                                            *i2_index.at(nd - 1) - *i1_index.at(nd - 1)\n                                        )\n                                    );\n                                ii += 1;\n                            };\n\n                            img.span()\n                        };\n\n                        let s = if w.len() != img.len() {\n                            let mut j1_index: Array<usize> = array![];\n                            let mut j2_index: Array<usize> = array![];\n                            let mut jdiff_index: Array<usize> = array![];\n\n                            let mut nx = 0;\n                            while nx != nd {\n                                j1_index\n                                    .append(\n                                        I32Number::max(0, -*indices.at(nx) - *o_index.at(nx)).into()\n                                    );\n                                j2_index\n                                    .append(\n                                        I32Number::min(\n                                            (*(*X).shape.at(nx + 2)).into()\n                                                - *indices.at(nx)\n                                                - *o_index.at(nx),\n                                            (*kernel_shape.at(nx)).into()\n                                        )\n                                            .into()\n                                    );\n                                if nx != nd - 1 {\n                                    jdiff_index.append(*j2_index.at(nx) - *j1_index.at(nx));\n                                }\n                                nx += 1;\n                            };\n\n                            let j1_index = j1_index.span();\n\n                            let mut w_: Array<T> = array![];\n\n                            let w_ = if nx == 1 {\n                                let w_ = SpanTrait::slice(\n                                    w,\n                                    *j1_index.at(nd - 1),\n                                    *j2_index.at(nd - 1) - *j1_index.at(nd - 1)\n                                );\n                                w_\n                            } else {\n                                let j_stride = stride(jdiff_index.span());\n\n                                let mut jj = 0;\n                                while jj != *j_stride.at(0) * *jdiff_index.at(0) {\n                                    let mut flatten_index = jj;\n                                    let mut start = 0;\n\n                                    let mut nx = 0;\n                                    while nx != nd - 1 {\n                                        let (jj_index, rem) = DivRem::div_rem(\n                                            flatten_index, (*j_stride.at(nx)).try_into().unwrap()\n                                        );\n                                        flatten_index = rem;\n                                        start += (*j1_index.at(nx) + jj_index)\n                                            * *kernel_shape.at(nx);\n                                        nx += 1;\n                                    };\n                                    w_\n                                        .append_span(\n                                            SpanTrait::slice(\n                                                w,\n                                                start + *j1_index.at(nd - 1),\n                                                *j2_index.at(nd - 1) - *j1_index.at(nd - 1)\n                                            )\n                                        );\n                                    jj += 1;\n                                };\n\n                                w_.span()\n                            };\n\n                            dot(img, w_)\n                        } else {\n                            dot(img, w)\n                        };\n\n                        let mut res_index = n * *res_strides.at(0) + nw * *res_strides.at(1);\n\n                        let mut nx = 0;\n                        while nx != nd {\n                            res_index += (*r_index.at(nx)).into() * *res_strides.at(2 + nx);\n                            nx += 1;\n                        };\n\n                        res.set(res_index, res.at(res_index) + s);\n                    };\n\n                    i += 1\n                };\n\n                c += 1;\n            };\n\n            nw += 1;\n        };\n\n        n += 1;\n    };\n\n    let mut res_data: Array<T> = array![];\n    let mut i = 0;\n    while i != res.len() {\n        res_data.append(res.at(i));\n        i += 1;\n    };\n\n    TensorTrait::new(res_shape, res_data.span())\n}\n\nfn r_index_check(r_index: Span<i32>, shape_out: Span<usize>) -> bool {\n    let mut i = 0;\n    let flag = loop {\n        if i == r_index.len() {\n            break true;\n        }\n        if *r_index.at(i) >= (*shape_out.at(i)).into() {\n            break false;\n        }\n        i += 1;\n    };\n\n    flag\n}\n\nfn prod<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +Mul<T>,>(\n    pA: Span<T>, start: usize\n) -> T {\n    let mut i = start;\n    let mut prod = NumberTrait::one();\n    while i != pA.len() {\n        prod = prod * (*pA.at(i));\n        i += 1;\n    };\n\n    prod\n}\n\nfn min(mut a: Span<usize>) -> usize {\n    assert(a.len() > 0, 'span cannot be empty');\n\n    let mut min = *a.at(0);\n    loop {\n        match a.pop_front() {\n            Option::Some(v) => { if *v < min {\n                min = *v;\n            }; },\n            Option::None => { break min; }\n        };\n    }\n}\n\nfn max(mut a: Span<usize>) -> usize {\n    assert(a.len() > 0, 'span cannot be empty');\n\n    let mut max = *a.at(0);\n    loop {\n        match a.pop_front() {\n            Option::Some(v) => { if *v > max {\n                max = *v;\n            }; },\n            Option::None => { break max; }\n        };\n    }\n}\n\nfn arange(start: usize, end: usize, step: usize) -> Span<usize> {\n    assert((end - start) % step == 0, 'incompatible step value');\n\n    let mut arr: Array<usize> = array![];\n    let mut i = start;\n    while i < end {\n        arr.append(i);\n        i += step;\n    };\n\n    arr.span()\n}\n\n\nfn cartesian(mut arrays: Span<Span<usize>>,) -> Span<Span<usize>> {\n    let mut n = 1;\n    let mut i = arrays.len() - 1;\n    loop {\n        n = n * (*(arrays.at(i))).len();\n        if i == 0 {\n            break;\n        }\n        i -= 1;\n    };\n\n    let mut i = 0;\n    let mut size_arrays: Array<usize> = array![];\n    while i != arrays.len() {\n        size_arrays.append((*(arrays.at(i))).len());\n        i += 1;\n    };\n\n    let size_arrays = size_arrays.span();\n    let mut output_arrays = array![];\n    let mut m = n;\n\n    let mut i = 0;\n    while i != arrays.len() {\n        m = m / (*(arrays.at(i))).len();\n        let mut out = repeat(*(arrays.at(i)), m);\n        out = repeat_2(out, size_arrays, i);\n\n        output_arrays.append(out);\n        i += 1;\n    };\n\n    let output_arrays = output_arrays.span();\n\n    let mut i = 0;\n    let mut ret = ArrayTrait::new();\n    while i != n {\n        let mut j = 0;\n        let mut x: Array<usize> = array![];\n        while j != arrays.len() {\n            x.append(*(output_arrays.at(j)).at(i));\n            j += 1;\n        };\n\n        ret.append(x.span());\n        i += 1;\n    };\n\n    ret.span()\n}\n\nfn repeat_2(mut array: Array<usize>, size_array: Span<usize>, index: usize) -> Array<usize> {\n    let mut size = array.len();\n    let mut i = 0;\n    while i != index {\n        let mut j = 1;\n        while j != *size_array.at(index - 1 - i) {\n            let mut k = 0;\n            while k != size {\n                array.append(*array.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n\n        size = size * *size_array.at(index - 1 - i);\n        i += 1;\n    };\n\n    array\n}\n\nfn repeat(array: Span<usize>, m: usize,) -> Array<usize> {\n    let mut out: Array<usize> = array![];\n    let mut j = 0;\n    while j != array.len() {\n        let mut k = 0;\n        while k != m {\n            out.append(*array.at(j));\n            k += 1;\n        };\n\n        j += 1;\n    };\n\n    out\n}\n\nfn dot<\n    T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Add<T>, +TensorTrait<T>, +AddEq<T>, +Mul<T>,\n>(\n    a: Span<T>, b: Span<T>\n) -> T {\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != a.len() {\n        sum = sum + *a.at(i) * *b.at(i);\n        i += 1;\n    };\n\n    sum\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/conv_transpose.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{stride};\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor,};\nuse orion::operators::vec::{NullableVec, NullableVecImpl};\n\n#[derive(Copy, Drop)]\nenum AUTO_PAD {\n    NOTSET,\n    SAME_UPPER,\n    SAME_LOWER,\n    VALID\n}\n\nfn conv_transpose<\n    T, MAG, +TensorTrait<T>, +NumberTrait<T, MAG>, +Copy<T>, +Drop<T>, +Add<T>, +Mul<T>,\n>(\n    X: @Tensor<T>,\n    W: @Tensor<T>,\n    B: Option<@Tensor<T>>,\n    auto_pad: Option<AUTO_PAD>,\n    dilations: Option<Span<usize>>,\n    group: Option<usize>,\n    kernel_shape: Option<Span<usize>>,\n    output_padding: Option<Span<usize>>,\n    output_shape: Option<Span<usize>>,\n    pads: Option<Span<usize>>,\n    strides: Option<Span<usize>>,\n) -> Tensor<T> {\n    let auto_pad = match auto_pad {\n        Option::Some(auto_pad) => auto_pad,\n        Option::None => { AUTO_PAD::NOTSET },\n    };\n    let dilations = match dilations {\n        Option::Some(dilations) => dilations,\n        Option::None => {\n            let mut dilations: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                dilations.append(1);\n                i += 1;\n            };\n\n            dilations.span()\n        },\n    };\n    let kernel_shape = match kernel_shape {\n        Option::Some(kernel_shape) => kernel_shape,\n        Option::None => {\n            let mut kernel_shape: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*W).shape.len() {\n                kernel_shape.append(*(*W).shape.at(i));\n                i += 1;\n            };\n\n            kernel_shape.span()\n        },\n    };\n    let output_padding = match output_padding {\n        Option::Some(output_padding) => output_padding,\n        Option::None => {\n            let mut output_padding: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X)\n                .shape\n                .len() {\n                    output_padding.append(0);\n                    output_padding.append(0);\n                    i += 1;\n                };\n\n            output_padding.span()\n        },\n    };\n    let strides = match strides {\n        Option::Some(strides) => strides,\n        Option::None => {\n            let mut strides: Array<usize> = array![];\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                strides.append(1);\n                i += 1;\n            };\n\n            strides.span()\n        },\n    };\n    let (pads, _, output_shape) = match pads {\n        Option::Some(pads) => {\n            let n_dims = (*X).shape.len() - 2;\n\n            let output_shape = match output_shape {\n                Option::Some(output_shape) => output_shape,\n                Option::None => {\n                    let mut output_shape: Array<usize> = array![];\n                    let mut i = 0;\n                    while i != n_dims {\n                        output_shape\n                            .append(\n                                (*(*X).shape.at(i + 2) - 1) * *strides.at(i)\n                                    + *output_padding.at(i)\n                                    + ((*kernel_shape.at(i) - 1) * *dilations.at(i) + 1)\n                                    - (*pads.at(i) + *pads.at(i + n_dims))\n                            );\n                        i += 1;\n                    };\n\n                    output_shape.span()\n                },\n            };\n\n            (pads, n_dims, output_shape)\n        },\n        Option::None => {\n            let (pads, n_dims, output_shape) = match auto_pad {\n                AUTO_PAD::NOTSET => {\n                    let mut pads: Array<usize> = array![];\n                    let mut i = 0;\n                    while i != strides.len() * 2 {\n                        pads.append(0);\n                        i += 1;\n                    };\n\n                    let pads = pads.span();\n\n                    let n_dims = (*X).shape.len() - 2;\n\n                    let output_shape = match output_shape {\n                        Option::Some(output_shape) => output_shape,\n                        Option::None => {\n                            let mut output_shape: Array<usize> = array![];\n                            let mut i = 0;\n                            while i != n_dims {\n                                output_shape\n                                    .append(\n                                        (*(*X).shape.at(i + 2) - 1) * *strides.at(i)\n                                            + *output_padding.at(i)\n                                            + ((*kernel_shape.at(i) - 1) * *dilations.at(i) + 1)\n                                            - (*pads.at(i) + *pads.at(i + n_dims))\n                                    );\n                                i += 1;\n                            };\n\n                            output_shape.span()\n                        },\n                    };\n\n                    (pads, n_dims, output_shape)\n                },\n                AUTO_PAD::SAME_UPPER => {\n                    let output_shape = match output_shape {\n                        Option::Some(output_shape) => output_shape,\n                        Option::None => {\n                            let mut output_shape: Array<usize> = array![];\n                            let mut i = 0;\n                            while i != strides\n                                .len() {\n                                    output_shape.append(*(*X).shape.at(i + 2) * *strides.at(i));\n                                    i += 1;\n                                };\n\n                            output_shape.span()\n                        },\n                    };\n                    let mut total_padding: Array<usize> = array![];\n\n                    let mut i = 0;\n                    while i != output_shape\n                        .len() {\n                            total_padding\n                                .append(\n                                    (*(*X).shape.at(i + 2) - 1) * *strides.at(i)\n                                        + *output_padding.at(i)\n                                        + ((*kernel_shape.at(i) - 1) * *dilations.at(i) + 1)\n                                        - *output_shape.at(i)\n                                );\n                            i += 1;\n                        };\n\n                    let total_padding = total_padding.span();\n\n                    let mut pads: Array<usize> = array![];\n\n                    let mut i = 0;\n                    while i != output_shape.len() {\n                        pads.append(*total_padding.at(i) / 2);\n                        i += 1;\n                    };\n\n                    let mut i = 0;\n                    while i != output_shape\n                        .len() {\n                            pads.append(*total_padding.at(i) - (*total_padding.at(i) / 2));\n                            i += 1;\n                        };\n\n                    (pads.span(), pads.len() / 2, output_shape)\n                },\n                AUTO_PAD::SAME_LOWER => {\n                    let output_shape = match output_shape {\n                        Option::Some(output_shape) => output_shape,\n                        Option::None => {\n                            let mut output_shape: Array<usize> = array![];\n                            let mut i = 0;\n                            while i != strides\n                                .len() {\n                                    output_shape.append(*(*X).shape.at(i + 2) * *strides.at(i));\n                                    i += 1;\n                                };\n\n                            output_shape.span()\n                        },\n                    };\n                    let mut total_padding: Array<usize> = array![];\n\n                    let mut i = 0;\n                    while i != output_shape\n                        .len() {\n                            total_padding\n                                .append(\n                                    (*(*X).shape.at(i + 2) - 1) * *strides.at(i)\n                                        + *output_padding.at(i)\n                                        + ((*kernel_shape.at(i) - 1) * *dilations.at(i) + 1)\n                                        - *output_shape.at(i)\n                                );\n                            i += 1;\n                        };\n\n                    let total_padding = total_padding.span();\n\n                    let mut pads: Array<usize> = array![];\n\n                    let mut i = 0;\n                    while i != output_shape\n                        .len() {\n                            pads.append(*total_padding.at(i) - *total_padding.at(i) / 2);\n                            i += 1;\n                        };\n\n                    let mut i = 0;\n                    while i != output_shape.len() {\n                        pads.append(*total_padding.at(i) / 2);\n                        i += 1;\n                    };\n\n                    (pads.span(), pads.len() / 2, output_shape)\n                },\n                AUTO_PAD::VALID => {\n                    let mut pads: Array<usize> = array![];\n                    let mut i = 0;\n                    while i != strides.len() * 2 {\n                        pads.append(0);\n                        i += 1;\n                    };\n\n                    let pads = pads.span();\n\n                    let n_dims = (*X).shape.len() - 2;\n                    let output_shape = match output_shape {\n                        Option::Some(output_shape) => output_shape,\n                        Option::None => {\n                            let mut output_shape: Array<usize> = array![];\n                            let mut i = 0;\n                            while i != n_dims {\n                                output_shape\n                                    .append(\n                                        (*(*X).shape.at(i + 2) - 1) * *strides.at(i)\n                                            + *output_padding.at(i)\n                                            + ((*kernel_shape.at(i) - 1) * *dilations.at(i) + 1)\n                                            - (*pads.at(i) + *pads.at(i + n_dims))\n                                    );\n                                i += 1;\n                            };\n\n                            output_shape.span()\n                        },\n                    };\n\n                    (pads, n_dims, output_shape)\n                },\n            };\n\n            (pads, n_dims, output_shape)\n        },\n    };\n    let group = match group {\n        Option::Some(group) => group,\n        Option::None => { 1 },\n    };\n\n    let mut kernel_shape: Array<usize> = array![];\n    let mut i = 2;\n    while i != (*W).shape.len() {\n        kernel_shape.append(*(*W).shape.at(i));\n        i += 1;\n    };\n\n    let kernel_shape = kernel_shape.span();\n    let kernel_size = prod(kernel_shape, 0);\n\n    let mut num_output_channels = *(*W).shape.at(1) * group;\n    let mut kernel_dim = (num_output_channels / group) * kernel_size;\n\n    let C = *(*X).shape.at(1);\n    let m = kernel_dim;\n    let n = prod((*X).shape, 2);\n    let k = C / group;\n\n    let mut final: Array<T> = array![];\n\n    if group == 1 {\n        let mut image_id = 0;\n        while image_id != *(*X)\n            .shape\n            .at(0) {\n                let w_t = TensorTrait::new(array![k, m].span(), (*W).data)\n                    .transpose(array![1, 0].span());\n\n                let image = SpanTrait::slice((*X).data, image_id * k * n, k * n);\n                let gemm = w_t.matmul(@TensorTrait::new(array![k, n].span(), image));\n\n                let gemmc = gemm\n                    .reshape(\n                        array![\n                            num_output_channels.try_into().unwrap(),\n                            (m / num_output_channels).try_into().unwrap(),\n                            n.try_into().unwrap()\n                        ]\n                            .span(),\n                        false\n                    );\n                let mut c = 0;\n                while c != num_output_channels {\n                    let gemmc_c = TensorTrait::new(\n                        array![m / num_output_channels, n].span(),\n                        SpanTrait::slice(\n                            gemmc.data,\n                            (m / num_output_channels) * n * c,\n                            (m / num_output_channels) * n\n                        )\n                    );\n\n                    let mut res = col2im_naive_implementation(\n                        @gemmc_c, output_shape, kernel_shape, dilations, pads, strides\n                    );\n\n                    match B {\n                        Option::Some(B) => {\n                            let mut i = 0;\n                            while i != res\n                                .len() {\n                                    res.set(i, res.at(i) + *(*B).data.at(c));\n                                    i += 1;\n                                };\n                        },\n                        Option::None => {},\n                    }\n\n                    c += 1;\n\n                    let mut i = 0;\n                    while i != res.len() {\n                        final.append(res.at(i));\n                        i += 1;\n                    };\n                };\n\n                image_id += 1;\n            };\n    } else {\n        let mut output_array: Array<Span<T>> = array![];\n\n        let mut i = 0;\n        let mut output_size = 1;\n        while i != output_shape.len() {\n            output_size *= *output_shape.at(i);\n            i += 1;\n        };\n\n        // Computation of conv transposition per group\n        let mut group_id = 0;\n        while group_id != group {\n            let mut group_X: Array<T> = array![];\n            let mut group_W: Array<T> = array![];\n\n            let mut image_id = 0;\n            while image_id != *(*X)\n                .shape\n                .at(0) {\n                    let start = image_id * n * C + (group_id * C / group) * n;\n                    let end = image_id * n * C + ((group_id + 1) * C / group) * n;\n\n                    let mut i = start;\n                    while i != end {\n                        group_X.append(*(*X).data.at(i));\n                        i += 1;\n                    };\n\n                    image_id += 1;\n                };\n\n            let start = (group_id * C / group) * *(*W).shape.at(1) * kernel_size;\n            let end = (group_id + 1) * C / group * *(*W).shape.at(1) * kernel_size;\n            let mut i = start;\n            while i != end {\n                group_W.append(*(*W).data.at(i));\n                i += 1;\n            };\n\n            let mut shape_X: Array<usize> = array![];\n            shape_X.append(*(*X).shape.at(0));\n            shape_X.append(C / group);\n\n            let mut i = 2;\n            while i != (*X).shape.len() {\n                shape_X.append(*(*X).shape.at(i));\n                i += 1;\n            };\n\n            let mut shape_W: Array<usize> = array![];\n            shape_W.append(C / group);\n\n            let mut i = 1;\n            while i != (*W).shape.len() {\n                shape_W.append(*(*W).shape.at(i));\n                i += 1;\n            };\n\n            // group_X : N x (C / group) x X.shape[2:]\n            let group_X = TensorTrait::new(shape_X.span(), group_X.span());\n            // group_W : (C / group) x *(*W).shape.at(1) x W.shape[2:]\n            let group_W = TensorTrait::new(shape_W.span(), group_W.span());\n\n            // group output : N x (num_output_channels / group) x output_shape\n            let group_output = conv_transpose(\n                @group_X,\n                @group_W,\n                B,\n                Option::Some(auto_pad),\n                Option::Some(dilations),\n                Option::Some(1),\n                Option::Some(kernel_shape),\n                Option::Some(output_padding),\n                Option::Some(output_shape),\n                Option::Some(pads),\n                Option::Some(strides)\n            );\n\n            output_array.append(group_output.data);\n\n            group_id += 1;\n        };\n\n        let output_array = output_array.span();\n\n        // Sorting result per item of the batch\n        // output size : N (batch size) x num_output_channels x output_shape\n        let mut image_id = 0;\n        while image_id != *(*X)\n            .shape\n            .at(0) {\n                let mut group_id = 0;\n                while group_id != group {\n                    let group_output = *output_array.at(group_id);\n                    let mut i = image_id * output_size * (num_output_channels / group);\n\n                    while i != (image_id + 1)\n                        * output_size\n                        * (num_output_channels / group) {\n                            final.append(*group_output.at(i));\n                            i += 1;\n                        };\n\n                    group_id += 1;\n                };\n\n                image_id += 1;\n            };\n    }\n\n    let mut shape = array![*(*X).shape.at(0), num_output_channels];\n\n    let mut i = 0;\n    while i != output_shape.len() {\n        shape.append(*output_shape.at(i));\n        i += 1;\n    };\n\n    TensorTrait::new(shape.span(), final.span())\n}\n\nfn get_image<T, +Drop<T>, +Copy<T>>(self: @Tensor<T>, row: usize) -> Span<T> {\n    assert((*self).shape.len() == 2, 'Expected a 2D tensor');\n\n    let row_length = *self.shape[1];\n    let start = row * row_length;\n\n    (*self).data.slice(start, row_length)\n}\n\nfn col2im_naive_implementation<\n    T, MAG, +TensorTrait<T>, +NumberTrait<T, MAG>, +Copy<T>, +Drop<T>, +Add<T>,\n>(\n    data: @Tensor<T>,\n    image_shape: Span<usize>,\n    kernel_shape: Span<usize>,\n    dilations: Span<usize>,\n    pads: Span<usize>,\n    strides: Span<usize>,\n) -> NullableVec<T> {\n    let n_dims = pads.len() / 2;\n\n    col2im_shape_check(data, image_shape, kernel_shape, dilations, pads, strides);\n\n    let mut dim_col: Array<usize> = array![];\n    let mut i = 0;\n    while i != n_dims {\n        dim_col\n            .append(\n                (*image_shape.at(i)\n                    + (*pads.at(i) + *pads.at(i + n_dims))\n                    - (*dilations.at(i) * (*kernel_shape.at(i) - 1) + 1))\n                    / *strides.at(i)\n                    + 1\n            );\n\n        i += 1;\n    };\n\n    let dim_col = dim_col.span();\n\n    let stride_img = stride(image_shape);\n\n    let mut data_im = NullableVecImpl::new();\n    data_im.set(*image_shape.at(0) * *stride_img.at(0) - 1, NumberTrait::zero());\n\n    let kernel_size = prod(kernel_shape, 0);\n    let col_size = prod(dim_col, 0);\n    let mut c_col = 0;\n    while c_col != kernel_size {\n        let offset = get_indices(c_col, kernel_shape).span();\n\n        let mut col = 0;\n        while col != col_size {\n            let ind_col = get_indices(col, dim_col).span();\n            let mut ind_im: Array<usize> = array![];\n            let mut i = 0;\n            while i != n_dims {\n                if (*ind_col.at(i) * *strides.at(i) + *offset.at(i) * *dilations.at(i)) < *pads\n                    .at(i) {\n                    let neg_index = *pads.at(i)\n                        - (*ind_col.at(i) * *strides.at(i) + *offset.at(i) * *dilations.at(i));\n                    ind_im.append(*image_shape.at(i) + neg_index);\n                } else {\n                    ind_im\n                        .append(\n                            *ind_col.at(i) * *strides.at(i)\n                                + *offset.at(i) * *dilations.at(i)\n                                - *pads.at(i)\n                        );\n                }\n\n                i += 1;\n            };\n\n            let ind_im = ind_im.span();\n            if !is_out(ind_im, image_shape) {\n                let mut index = 0;\n                let mut i = 0;\n                while i != image_shape.len() {\n                    index += *stride_img.at(i) * *ind_im.at(i);\n                    i += 1;\n                };\n\n                data_im.set(index, data_im.at(index) + *(*data).data.at(c_col * col_size + col));\n            }\n\n            col += 1;\n        };\n\n        c_col += 1;\n    };\n\n    data_im\n}\n\nfn col2im_shape_check<T, +TensorTrait<T>, +Copy<T>, +Drop<T>,>(\n    X: @Tensor<T>,\n    output_shape: Span<usize>,\n    kernel_shape: Span<usize>,\n    dilations: Span<usize>,\n    pads: Span<usize>,\n    strides: Span<usize>,\n) {\n    let n_input_plane = *(*X).shape.at(0);\n\n    let kernel_size = prod(kernel_shape, 0);\n\n    assert(n_input_plane % kernel_size == 0, 'wrong input dimension');\n\n    let input_length = *(*X).shape.at(1);\n    let n_dims = output_shape.len();\n    let mut n_blocks: Array<usize> = array![];\n\n    let mut i = 0;\n    while i != n_dims {\n        n_blocks\n            .append(\n                (*output_shape.at(i)\n                    + (*pads.at(i) + *pads.at(i + n_dims))\n                    - *dilations.at(i) * (*kernel_shape.at(i) - 1)\n                    - 1)\n                    / *strides.at(i)\n                    + 1\n            );\n        i += 1;\n    };\n\n    let block_size = prod(n_blocks.span(), 0);\n\n    assert(input_length == block_size, 'input_length != block_size');\n}\n\n\nfn get_indices(index: usize, shape: Span<usize>,) -> Array<usize> {\n    let mut i = index;\n    let mut res: Array<usize> = array![];\n    let mut k = shape.len() - 1;\n    while k != 0 {\n        let m = i % *shape.at(k);\n        res.append(m);\n        i -= m;\n        i /= *shape.at(k);\n        k -= 1;\n    };\n\n    let mut new_res: Array<usize> = array![];\n    new_res.append(i);\n    let mut i = shape.len() - 1;\n    while i != 0 {\n        new_res.append(*res.at(i - 1));\n        i -= 1;\n    };\n\n    new_res\n}\n\nfn is_out(ind: Span<usize>, shape: Span<usize>,) -> bool {\n    let mut n = 0;\n    let is_out = loop {\n        if n == ind.len() {\n            break false;\n        }\n        let s = *shape.at(n);\n        let i = *ind.at(n);\n        if i < 0 {\n            break true;\n        }\n        if i >= s {\n            break true;\n        }\n        n += 1;\n    };\n\n    is_out\n}\n\nfn prod<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +Mul<T>,>(\n    pA: Span<T>, start: usize\n) -> T {\n    let mut i = start;\n    let mut prod = NumberTrait::one();\n    while i != pA.len() {\n        prod = prod * (*pA.at(i));\n        i += 1;\n    };\n\n    prod\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/depth_to_space.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\nuse orion::operators::tensor::math::{reduce_sum::accumulate_sum, arithmetic::div_downcast};\n\n/// Cf: NNTrait::depth_to_space docstring\nfn depth_to_space<\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl TAdd: Add<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    tensor: Tensor<T>, blocksize: usize, mode: felt252\n) -> Tensor<T> {\n    assert((tensor.shape).len() == 4, 'Unexpected shape 4.');\n\n    let blocksize_i32: i32 = blocksize.try_into().unwrap();\n\n    let b: i32 = (*(tensor.shape).at(0)).try_into().unwrap();\n    let C: u32 = (*(tensor.shape).at(1)).try_into().unwrap();\n    let H: i32 = (*(tensor.shape).at(2)).try_into().unwrap();\n    let W: i32 = (*(tensor.shape).at(3)).try_into().unwrap();\n    let finalshape: Array<i32> = array![\n        b,\n        (C / (blocksize * blocksize)).try_into().unwrap(),\n        (H * blocksize_i32),\n        (W * blocksize_i32)\n    ];\n\n    if mode == 'DCR' {\n        let tmpshape: Array<i32> = array![\n            b, blocksize_i32, blocksize_i32, (C / (blocksize * blocksize)).try_into().unwrap(), H, W\n        ];\n        let reshaped = (tensor).reshape(target_shape: tmpshape.span(), allowzero: false);\n        let transposed = reshaped.transpose(axes: array![0, 3, 4, 1, 5, 2].span());\n\n        transposed.reshape(target_shape: finalshape.span(), allowzero: false)\n    } else {\n        // assert mode == \"CRD\"\n        let tmpshape: Array<i32> = array![\n            b, (C / (blocksize * blocksize)).try_into().unwrap(), blocksize_i32, blocksize_i32, H, W\n        ];\n        let reshaped = (tensor).reshape(target_shape: tmpshape.span(), allowzero: false);\n        let transposed = reshaped.transpose(axes: array![0, 1, 4, 2, 5, 3].span());\n\n        transposed.reshape(target_shape: finalshape.span(), allowzero: false)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/gemm.cairo",
        "content": "use core::array::SpanTrait;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}, math::arithmetic::mul_by_scalar};\n\n/// Cf: NNTrait::gemm docstring\nfn gemm<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TAddTensor: Add<Tensor<T>>,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TMul: Mul<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    A: Tensor<T>,\n    B: Tensor<T>,\n    C: Option<Tensor<T>>,\n    alpha: Option<T>,\n    beta: Option<T>,\n    transA: bool,\n    transB: bool\n) -> Tensor<T> {\n    let mut A = A;\n    let mut B = B;\n\n    let alpha: T = if alpha.is_some() {\n        alpha.unwrap()\n    } else {\n        NumberTrait::one()\n    };\n\n    let beta: T = if beta.is_some() {\n        beta.unwrap()\n    } else {\n        NumberTrait::one()\n    };\n\n    if transA {\n        A = A.transpose(array![1, 0].span());\n    }\n\n    if transB {\n        B = B.transpose(array![1, 0].span());\n    }\n\n    match C {\n        Option::Some(c) => { mul_by_scalar(@A.matmul(@B), alpha) + mul_by_scalar(@c, beta) },\n        Option::None(_) => { mul_by_scalar(@A.matmul(@B), alpha) }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/grid_sample.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::FP16x16;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{stride};\nuse orion::operators::tensor::{FP16x16Tensor, TensorTrait, Tensor, U32Tensor,};\nuse orion::operators::vec::{NullableVec, NullableVecImpl};\n\n#[derive(Copy, Drop)]\nenum MODE {\n    NEAREST,\n    LINEAR,\n    CUBIC,\n}\n\n#[derive(Copy, Drop)]\nenum PADDING_MODE {\n    ZEROS,\n    BORDER,\n    REFLECTION,\n}\n\nfn grid_sample<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +Copy<T>,\n    +Drop<T>,\n    +Add<T>,\n    +Mul<T>,\n    +Sub<T>,\n    +Div<T>,\n    +AddEq<T>,\n    +PrintTrait<T>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +Rem<T>,\n    +Neg<T>,\n    +SubEq<T>,\n>(\n    X: @Tensor<T>,\n    grid: @Tensor<T>,\n    align_corner: Option<usize>,\n    mode: Option<MODE>,\n    padding_mode: Option<PADDING_MODE>,\n) -> Tensor<T> {\n    let align_corner = match align_corner {\n        Option::Some(align_corner) => align_corner,\n        Option::None => 0,\n    };\n\n    let mode = match mode {\n        Option::Some(mode) => mode,\n        Option::None => MODE::LINEAR,\n    };\n\n    let padding_mode = match padding_mode {\n        Option::Some(padding_mode) => padding_mode,\n        Option::None => PADDING_MODE::ZEROS,\n    };\n\n    let x_dims = (*X).shape;\n    let x_stride = stride((*X).shape);\n    let grid_dims = (*grid).shape;\n    let grid_stride = stride((*grid).shape);\n\n    let N = *x_dims.at(0);\n    let C = *x_dims.at(1);\n\n    let num_dims = x_dims.len() - 2;\n    let dims = SpanTrait::slice(x_dims, 2, num_dims);\n\n    let border = prepare_border(X, dims, align_corner);\n\n    let mut y_dims: Array<usize> = array![N, C];\n    y_dims.append_span(SpanTrait::slice(grid_dims, 1, grid_dims.len() - 2));\n    let y_dims = y_dims.span();\n\n    if prod(y_dims, 0) == 0 {\n        return TensorTrait::new(array![].span(), array![].span());\n    }\n\n    let mut Y: Array<T> = array![];\n\n    let mut n = 0;\n    while n != N {\n        let grid_data = SpanTrait::slice((*grid).data, n * *grid_stride.at(0), *grid_stride.at(0));\n        let grid_data_stride = SpanTrait::slice(grid_stride, 1, grid_stride.len() - 1);\n\n        let mut c = 0;\n        while c != C {\n            let X_data = SpanTrait::slice(\n                (*X).data, n * *x_stride.at(0) + c * *x_stride.at(1), *x_stride.at(1)\n            );\n            let X_data_stride = SpanTrait::slice(x_stride, 2, grid_stride.len() - 2);\n            let all_coords = get_all_coords(SpanTrait::slice(grid_dims, 1, grid_dims.len() - 2));\n\n            let mut ix = 0;\n            while ix != all_coords.len() {\n                let ox = *all_coords.at(ix);\n                let nx = get_sub(grid_data, grid_data_stride, ox);\n                let nx = reverse(nx);\n                let x = gs_denormalize_coordinates(nx, dims, align_corner);\n\n                let x = match mode {\n                    MODE::NEAREST => { rint(x) },\n                    MODE::LINEAR => { x },\n                    MODE::CUBIC => { x },\n                };\n\n                let mut new_x: Array<T> = array![];\n                let mut i = 0;\n                while i != x.len() {\n                    let v = *x.at(i);\n                    let mut x_min = *border.at(i);\n                    let mut x_max = *border.at(i + num_dims);\n                    let new_v = if v < x_min || v > x_max {\n                        let v = match padding_mode {\n                            PADDING_MODE::ZEROS => { v },\n                            PADDING_MODE::BORDER => {\n                                clamp(\n                                    v,\n                                    NumberTrait::zero(),\n                                    NumberTrait::new_unscaled((*dims.at(i)).into(), false)\n                                        - NumberTrait::one()\n                                )\n                            },\n                            PADDING_MODE::REFLECTION => { gs_reflect(v, x_min, x_max) },\n                        };\n                        v\n                    } else {\n                        v\n                    };\n\n                    new_x.append(new_v);\n                    i += 1;\n                };\n\n                let x = new_x.span();\n\n                let y = match mode {\n                    MODE::NEAREST => {\n                        pixel_at_ndarray(X_data, dims, X_data_stride, x, border, padding_mode)\n                    },\n                    MODE::LINEAR => {\n                        gs_linear_interpolation_nd_with_x(\n                            X_data, dims, X_data_stride, x, border, padding_mode\n                        )\n                    },\n                    MODE::CUBIC => {\n                        gs_cubic_interpolation_nd_with_x(\n                            X_data, dims, X_data_stride, x, border, padding_mode\n                        )\n                    },\n                };\n\n                Y.append(y);\n                ix += 1;\n            };\n\n            c += 1;\n        };\n\n        n += 1;\n    };\n\n    TensorTrait::new(y_dims, Y.span())\n}\n\nfn gs_cubic_interpolation_1d_with_x<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +AddEq<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>,\n>(\n    data: Span<T>, x: T, border: Span<T>, padding_mode: PADDING_MODE\n) -> T {\n    let x_0 = NumberTrait::floor(x);\n    let x_1 = x_0 + NumberTrait::one();\n    let x_2 = x_1 + NumberTrait::one();\n    let x_minus_1 = x_0 - NumberTrait::one();\n\n    let coeffs = gs_get_cubic_coeffs(x - x_0);\n\n    let v_0 = pixel_at_array(data, x_minus_1.try_into().unwrap(), border, padding_mode);\n    let v_1 = pixel_at_array(data, x_0.try_into().unwrap(), border, padding_mode);\n    let v_2 = pixel_at_array(data, x_1.try_into().unwrap(), border, padding_mode);\n    let v_3 = pixel_at_array(data, x_2.try_into().unwrap(), border, padding_mode);\n\n    let v: Span<T> = array![v_0, v_1, v_2, v_3].span();\n\n    dot(coeffs, v)\n}\n\nfn gs_get_cubic_coeffs<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    x: T\n) -> Span<T> {\n    let one = NumberTrait::one();\n    let two = one + NumberTrait::one();\n    let three = two + NumberTrait::one();\n    let four = three + NumberTrait::one();\n    let five = four + NumberTrait::one();\n    let eigth = four + four;\n\n    let A = NumberTrait::neg(three / four);\n    let x = NumberTrait::abs(x);\n\n    let mut coeffs: Array<T> = array![];\n\n    coeffs.append(((A * (x + one) - five * A) * (x + one) + eigth * A) * (x + one) - four * A);\n    coeffs.append(((A + two) * x - (A + three)) * x * x + one);\n    coeffs.append(((A + two) * (one - x) - (A + three)) * (one - x) * (one - x) + one);\n    coeffs\n        .append(\n            ((A * ((one - x) + one) - five * A) * ((one - x) + one) + eigth * A) * ((one - x) + one)\n                - four * A\n        );\n\n    coeffs.span()\n}\n\nfn gs_cubic_interpolation_nd_with_x<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +AddEq<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>,\n>(\n    data: Span<T>,\n    data_dims: Span<usize>,\n    data_stride: Span<usize>,\n    x: Span<T>,\n    border: Span<T>,\n    padding_mode: PADDING_MODE\n) -> T {\n    let num_dims = data_dims.len();\n\n    assert(num_dims == x.len(), 'pixel at nd array: wrong dim');\n    assert(num_dims == (border.len() / 2), 'pixel at nd array: wrong dim');\n\n    if num_dims == 1 {\n        let a = gs_cubic_interpolation_1d_with_x(data, *x.at(0), border, padding_mode);\n        return a;\n    }\n\n    let mut res1d: Array<T> = array![];\n\n    let mut i = 0;\n    while i != *data_dims.at(0) {\n        let sub_data = SpanTrait::slice(data, i * *data_stride.at(0), *data_stride.at(0));\n        let sub_x = SpanTrait::slice(x, 1, x.len() - 1);\n\n        let data_dims_sub = SpanTrait::slice(data_dims, 1, data_dims.len() - 1);\n        let data_stride_sub = SpanTrait::slice(data_stride, 1, data_stride.len() - 1);\n\n        let border1 = SpanTrait::slice(border, 1, num_dims - 1);\n        let border2 = SpanTrait::slice(border, num_dims + 1, num_dims - 1);\n        let mut border = ArrayTrait::new();\n        border.append_span(border1);\n        border.append_span(border2);\n\n        let r = gs_cubic_interpolation_nd_with_x(\n            sub_data, data_dims_sub, data_stride_sub, sub_x, border.span(), padding_mode\n        );\n\n        res1d.append(r);\n        i += 1;\n    };\n\n    gs_cubic_interpolation_1d_with_x(\n        res1d.span(), *x.at(0), array![*border.at(0), *border.at(num_dims)].span(), padding_mode\n    )\n}\n\nfn gs_get_linear_coeffs<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Sub<T>,>(\n    x: T\n) -> Span<T> {\n    let x = NumberTrait::abs(x);\n\n    array![NumberTrait::one() - x, x].span()\n}\n\nfn gs_linear_interpolation_1d_with_x<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>\n>(\n    data: Span<T>, x: T, border: Span<T>, padding_mode: PADDING_MODE\n) -> T {\n    let x_0 = NumberTrait::floor(x);\n    let x_1 = x_0 + NumberTrait::one();\n\n    let coeffs = gs_get_linear_coeffs(x - x_0);\n\n    let v_0 = pixel_at_array(data, x_0.try_into().unwrap(), border, padding_mode);\n    let v_1 = pixel_at_array(data, x_1.try_into().unwrap(), border, padding_mode);\n\n    let v: Span<T> = array![v_0, v_1].span();\n\n    dot(coeffs, v)\n}\n\nfn dot<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +Add<T>, +TensorTrait<T>, +Mul<T>,>(\n    a: Span<T>, b: Span<T>\n) -> T {\n    assert(a.len() == b.len(), 'dot: wrong len');\n\n    let mut i = 0;\n    let mut sum = NumberTrait::zero();\n    while i != a.len() {\n        sum = sum + *a.at(i) * *b.at(i);\n        i += 1;\n    };\n\n    sum\n}\n\nfn gs_linear_interpolation_nd_with_x<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>\n>(\n    data: Span<T>,\n    data_dims: Span<usize>,\n    data_stride: Span<usize>,\n    x: Span<T>,\n    border: Span<T>,\n    padding_mode: PADDING_MODE\n) -> T {\n    let num_dims = data_dims.len();\n\n    assert(num_dims == x.len(), 'pixel at nd array: wrong dim');\n    assert(num_dims == (border.len() / 2), 'pixel at nd array: wrong dim');\n\n    if num_dims == 1 {\n        let a = gs_linear_interpolation_1d_with_x(data, *x.at(0), border, padding_mode);\n        return a;\n    }\n\n    let mut res1d: Array<T> = array![];\n\n    let mut i = 0;\n    while i != *data_dims.at(0) {\n        let sub_data = SpanTrait::slice(data, i * *data_stride.at(0), *data_stride.at(0));\n        let sub_x = SpanTrait::slice(x, 1, x.len() - 1);\n\n        let data_dims_sub = SpanTrait::slice(data_dims, 1, data_dims.len() - 1);\n        let data_stride_sub = SpanTrait::slice(data_stride, 1, data_stride.len() - 1);\n\n        let border1 = SpanTrait::slice(border, 1, num_dims - 1);\n        let border2 = SpanTrait::slice(border, num_dims + 1, num_dims - 1);\n        let mut border = ArrayTrait::new();\n        border.append_span(border1);\n        border.append_span(border2);\n\n        let r = gs_linear_interpolation_nd_with_x(\n            sub_data, data_dims_sub, data_stride_sub, sub_x, border.span(), padding_mode\n        );\n\n        res1d.append(r);\n        i += 1;\n    };\n\n    gs_linear_interpolation_1d_with_x(\n        res1d.span(), *x.at(0), array![*border.at(0), *border.at(num_dims)].span(), padding_mode\n    )\n}\n\nfn pixel_at_ndarray<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>,\n>(\n    ndarray: Span<T>,\n    ndarray_dims: Span<usize>,\n    ndarray_stride: Span<usize>,\n    x: Span<T>,\n    border: Span<T>,\n    padding_mode: PADDING_MODE\n) -> T {\n    let num_dims = ndarray_dims.len();\n\n    assert(num_dims == x.len(), 'pixel at nd array: wrong dim');\n    assert(num_dims == (border.len() / 2), 'pixel at nd array: wrong dim');\n\n    let i = *x.at(0);\n\n    if num_dims == 1 {\n        return pixel_at_array(ndarray, *x.at(0), border, padding_mode);\n    }\n\n    let d = NumberTrait::new_unscaled((*ndarray_dims.at(0)).into(), false);\n\n    let ndarray = match padding_mode {\n        PADDING_MODE::ZEROS => {\n            let ndarray = if i >= NumberTrait::zero() && i < d {\n                SpanTrait::slice(\n                    ndarray, i.try_into().unwrap() * *ndarray_stride.at(0), *ndarray_stride.at(0)\n                )\n            } else {\n                let ndarray: Span<T> = zeros(*ndarray_stride.at(0));\n                ndarray\n            };\n            ndarray\n        },\n        PADDING_MODE::BORDER => {\n            let i = clamp(i, NumberTrait::zero(), d - NumberTrait::one());\n            SpanTrait::slice(\n                ndarray, i.try_into().unwrap() * *ndarray_stride.at(0), *ndarray_stride.at(0)\n            )\n        },\n        PADDING_MODE::REFLECTION => {\n            let i: usize = (gs_reflect(i, *border.at(0), *border.at(num_dims))).try_into().unwrap();\n            SpanTrait::slice(ndarray, i * *ndarray_stride.at(0), *ndarray_stride.at(0))\n        },\n    };\n\n    let x = SpanTrait::slice(x, 1, x.len() - 1);\n    let ndarray_dims = SpanTrait::slice(ndarray_dims, 1, ndarray_dims.len() - 1);\n    let ndarray_stride = SpanTrait::slice(ndarray_stride, 1, ndarray_stride.len() - 1);\n\n    let border1 = SpanTrait::slice(border, 1, num_dims - 1);\n    let border2 = SpanTrait::slice(border, num_dims + 1, num_dims - 1);\n    let mut border = ArrayTrait::new();\n    border.append_span(border1);\n    border.append_span(border2);\n\n    pixel_at_ndarray(ndarray, ndarray_dims, ndarray_stride, x, border.span(), padding_mode)\n}\n\nfn pixel_at_array<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Rem<T>,\n    +PrintTrait<T>,\n>(\n    array: Span<T>, i: T, border: Span<T>, padding_mode: PADDING_MODE\n) -> T {\n    let d = NumberTrait::new_unscaled(array.len().into(), false);\n\n    let pixel = match padding_mode {\n        PADDING_MODE::ZEROS => {\n            let pixel = if i >= NumberTrait::zero() && i < d {\n                *array.at(i.try_into().unwrap())\n            } else {\n                NumberTrait::zero()\n            };\n            pixel\n        },\n        PADDING_MODE::BORDER => {\n            let i = clamp(i, NumberTrait::zero(), d - NumberTrait::one());\n            let pixel = *array.at(i.try_into().unwrap());\n            pixel\n        },\n        PADDING_MODE::REFLECTION => {\n            let i: usize = (gs_reflect(i, *border.at(0), *border.at(1))).try_into().unwrap();\n            let pixel = *array.at(i);\n            pixel\n        },\n    };\n\n    pixel\n}\n\nfn zeros<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>>(n: usize) -> Span<T> {\n    let mut zeros: Array<T> = array![];\n    let mut i = 0;\n    while i != n {\n        zeros.append(NumberTrait::zero());\n        i += 1;\n    };\n\n    zeros.span()\n}\n\nfn rint<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +SubEq<T>,\n    +Rem<T>,\n    +PartialEq<T>,\n    +PartialOrd<T>,\n    +Add<T>,\n    +Sub<T>\n>(\n    data: Span<T>\n) -> Span<T> {\n    // round to nearest if ties rounds to the nearest even value. \n    let mut rint: Array<T> = array![];\n    let two: T = NumberTrait::one() + NumberTrait::one();\n\n    let mut i = 0;\n    while i != data.len() {\n        let x = *data.at(i);\n        let mut round = NumberTrait::round(x);\n\n        let diff = round - x;\n        if diff == NumberTrait::half() {\n            if round % two != NumberTrait::zero() {\n                round -= NumberTrait::one()\n            }\n        }\n\n        rint.append(round);\n        i += 1;\n    };\n\n    rint.span()\n}\n\nfn clamp<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +PartialOrd<T>>(\n    val: T, low: T, high: T\n) -> T {\n    if val < low {\n        return low;\n    }\n\n    if val > high {\n        return high;\n    }\n\n    val\n}\n\nfn gs_reflect<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Add<T>,\n    +Sub<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Rem<T>,\n    +PrintTrait<T>,\n>(\n    x: T, x_min: T, x_max: T\n) -> T {\n    let two: T = NumberTrait::one() + NumberTrait::one();\n    let mut fx = x;\n    let rng = x_max - x_min;\n\n    let fx = if fx < x_min {\n        let dx = x_min - fx;\n        let n = NumberTrait::floor(dx / rng);\n        let r = dx - n * rng;\n        let fx = if NumberTrait::round(n % two) == NumberTrait::zero() {\n            x_min + r\n        } else {\n            x_max - r\n        };\n        fx\n    } else if fx > x_max {\n        let dx = fx - x_max;\n        let n = NumberTrait::floor(dx / rng);\n        let r = dx - n * rng;\n\n        let fx = if NumberTrait::round(n % two) == NumberTrait::zero() {\n            x_max - r\n        } else {\n            x_min + r\n        };\n        fx\n    } else {\n        fx\n    };\n\n    fx\n}\n\nfn reverse<T, +Copy<T>, +Drop<T>,>(data: Span<T>) -> Span<T> {\n    let mut rev: Array<T> = array![];\n    let mut i = data.len();\n    while i != 0 {\n        rev.append(*data.at(i - 1));\n        i -= 1;\n    };\n\n    rev.span()\n}\n\nfn get_sub<T, +Copy<T>, +Drop<T>,>(\n    data: Span<T>, stride_data: Span<usize>, index: Span<usize>,\n) -> Span<T> {\n    let mut acc_indices = 0;\n    let mut i = 0;\n    while i != index.len() {\n        acc_indices += *index.at(i) * *stride_data.at(i);\n        i += 1;\n    };\n\n    SpanTrait::slice(data, acc_indices, *stride_data.at(index.len() - 1))\n}\n\nfn prod<T, MAG, +Drop<T>, +Copy<T>, +NumberTrait<T, MAG>, +TensorTrait<T>, +Mul<T>,>(\n    pA: Span<T>, start: usize\n) -> T {\n    let mut i = start;\n    let mut prod = NumberTrait::one();\n    while i != pA.len() {\n        prod = prod * (*pA.at(i));\n        i += 1;\n    };\n\n    prod\n}\n\nfn prepare_border<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +Into<usize, MAG>,\n    +Neg<T>\n>(\n    self: @Tensor<T>, dims: Span<usize>, align_corner: usize\n) -> Span<T> {\n    let num_dims = dims.len();\n\n    let mut borders1: Array<T> = array![];\n    let mut borders2: Array<T> = array![];\n\n    let mut i = 0;\n    while i != num_dims {\n        if align_corner == 0 {\n            borders1.append(-NumberTrait::half());\n            borders2\n                .append(\n                    NumberTrait::new_unscaled((*dims.at(i)).into(), false) - NumberTrait::half()\n                );\n        } else {\n            borders1.append(NumberTrait::zero());\n            borders2\n                .append(\n                    NumberTrait::new_unscaled((*dims.at(i)).into(), false) - NumberTrait::one()\n                );\n        }\n\n        i += 1;\n    };\n\n    borders1.append_span(borders2.span());\n\n    borders1.span()\n}\n\nfn arange(start: usize, end: usize, step: usize) -> Span<usize> {\n    assert((end - start) % step == 0, 'incompatible step value');\n    let mut arr: Array<usize> = array![];\n    let mut i = start;\n    while i != end {\n        arr.append(i);\n        i += step;\n    };\n\n    arr.span()\n}\n\nfn gs_denormalize_coordinates<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +Into<usize, MAG>\n>(\n    n: Span<T>, dims: Span<usize>, align_corner: usize\n) -> Span<T> {\n    let mut x: Array<T> = array![];\n\n    let mut i = 0;\n    while i != n.len() {\n        let v = *n.at(i);\n        let dim = *dims.at(i);\n        x.append(gs_denormalize(v, dim, align_corner));\n        i += 1;\n    };\n\n    x.span()\n}\n\nfn gs_denormalize<\n    T,\n    MAG,\n    +Drop<T>,\n    +Copy<T>,\n    +NumberTrait<T, MAG>,\n    +TensorTrait<T>,\n    +Mul<T>,\n    +Add<T>,\n    +Div<T>,\n    +Sub<T>,\n    +Into<usize, MAG>\n>(\n    n: T, length: usize, align_corner: usize\n) -> T {\n    let length = NumberTrait::new_unscaled(length.into(), false);\n    let two: T = NumberTrait::one() + NumberTrait::one();\n\n    let x = if align_corner == 0 {\n        ((n + NumberTrait::one()) * length - NumberTrait::one()) / two\n    } else {\n        (n + NumberTrait::one()) / two * (length - NumberTrait::one())\n    };\n\n    x\n}\n\nfn get_all_coords(shape: Span<usize>) -> Span<Span<usize>> {\n    let mut all_indices = array![];\n\n    let mut i = 0;\n    while i != shape.len() {\n        all_indices.append(arange(0, *shape.at(i), 1));\n        i += 1;\n    };\n\n    cartesian(all_indices.span())\n}\n\nfn cartesian(mut arrays: Span<Span<usize>>,) -> Span<Span<usize>> {\n    let mut n = 1;\n    let mut i = arrays.len() - 1;\n    loop {\n        n = n * (*(arrays.at(i))).len();\n        if i == 0 {\n            break;\n        }\n        i -= 1;\n    };\n\n    let mut i = 0;\n    let mut size_arrays: Array<usize> = array![];\n    while i != arrays.len() {\n        size_arrays.append((*(arrays.at(i))).len());\n        i += 1;\n    };\n\n    let size_arrays = size_arrays.span();\n    let mut output_arrays = ArrayTrait::<Array<usize>>::new();\n    let mut m = n;\n\n    let mut i = 0;\n    while i != arrays.len() {\n        m = m / (*(arrays.at(i))).len();\n        let mut out = repeat(*(arrays.at(i)), m);\n        out = repeat_2(out, size_arrays, i);\n\n        output_arrays.append(out);\n        i += 1;\n    };\n\n    let output_arrays = output_arrays.span();\n\n    let mut i = 0;\n    let mut ret = array![];\n    while i != n {\n        let mut j = 0;\n        let mut x = ArrayTrait::new();\n        while j != arrays.len() {\n            x.append(*(output_arrays.at(j)).at(i));\n            j += 1;\n        };\n\n        ret.append(x.span());\n        i += 1;\n    };\n\n    ret.span()\n}\n\nfn repeat_2(mut array: Array<usize>, size_array: Span<usize>, index: usize) -> Array<usize> {\n    let mut size = array.len();\n    let mut i = 0;\n    while i != index {\n        let mut j = 1;\n        while j != *size_array.at(index - 1 - i) {\n            let mut k = 0;\n            while k != size {\n                array.append(*array.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n\n        size = size * *size_array.at(index - 1 - i);\n        i += 1;\n    };\n\n    array\n}\n\nfn repeat(array: Span<usize>, m: usize,) -> Array<usize> {\n    let mut out: Array<usize> = array![];\n    let mut j = 0;\n    while j != array.len() {\n        let mut k = 0;\n        while k != m {\n            out.append(*array.at(j));\n            k += 1;\n        };\n\n        j += 1;\n    };\n\n    out\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/hard_sigmoid.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::hard_sigmoid docstring\nfn hard_sigmoid<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAdd: Add<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut x: Tensor<T>, alpha: @T, beta: @T\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match x.data.pop_front() {\n            Option::Some(item) => {\n                let temp = (*item) * (*alpha) + (*beta);\n                let result = temp.min(NumberTrait::one()).max(NumberTrait::zero());\n                data_result.append(result);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(x.shape, data_result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/leaky_relu.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::leaky_relu docstring\nfn leaky_relu<\n    T,\n    MAG,\n    impl FNumber: NumberTrait<T, MAG>,\n    impl FTensor: TensorTrait<T>,\n    impl FPartialOrd: PartialOrd<T>,\n    impl FMul: Mul<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    mut z: Tensor<T>, alpha: @T\n) -> Tensor<T> {\n    assert(*alpha < NumberTrait::one(), 'alpha must be less than 1');\n\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                if (*item >= NumberTrait::zero()) {\n                    data_result.append(*item);\n                } else {\n                    data_result.append(*item * *alpha);\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/linear.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::linear docstring\nfn linear<\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl TAddTensor: Add<Tensor<T>>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    z: Tensor<T>, weights: Tensor<T>, bias: Tensor<T>\n) -> Tensor<T> {\n    assert(z.shape.len() == 1, 'input tensor must be 1D');\n    assert(weights.shape.len() == 2, 'weights tensor must be 2D');\n    assert(bias.shape.len() == 1, 'bias tensor must be 1D');\n\n    let dot = weights.matmul(@z);\n    let sum = dot + bias;\n\n    sum\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/logsoftmax.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::math::{exp::exp_upcast, arithmetic::div_downcast};\n\n/// Cf: NNTrait::logsoftmax docstring\nfn logsoftmax<\n    T, impl TTensor: TensorTrait<T>, impl TDivTensor: Div<Tensor<T>>, impl TDrop: Drop<T>\n>(\n    z: @Tensor<T>, axis: usize\n) -> Tensor<T> {\n    let exp_tensor = z.exp();\n    let sum = exp_tensor\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(true),\n            Option::Some(false)\n        );\n    let softmax = exp_tensor / sum;\n    let logsoftmax = softmax.log();\n\n    logsoftmax\n}\n\n/// Cf: NNTrait::logsoftmax docstring\nfn logsoftmaxWide<\n    T,\n    TMAG,\n    W,\n    WMAG,\n    impl TTensor: TensorTrait<T>,\n    impl WTensor: TensorTrait<W>,\n    impl TDiv: Div<T>,\n    impl TIntoW: Into<T, W>,\n    impl WTryIntoT: TryInto<W, T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl WCopy: Copy<W>,\n    impl WDrop: Drop<W>,\n    impl TFixed: FixedTrait<T, TMAG>,\n    impl WFixed: FixedTrait<W, WMAG>,\n>(\n    z: @Tensor<T>, axis: usize\n) -> Tensor<T> {\n    let exp_tensor: Tensor<W> = exp_upcast(*z);\n    let sum = exp_tensor\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(true),\n            Option::Some(false)\n        );\n    let softmax = div_downcast(@exp_tensor, @sum);\n\n    softmax.log()\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/relu.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::relu docstring\nfn relu<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                if (*item) < NumberTrait::zero() {\n                    data_result.append(NumberTrait::zero());\n                } else {\n                    data_result.append(*item);\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/sigmoid.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::sigmoid docstring\nfn sigmoid<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAdd: Add<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                let result = NumberTrait::one()\n                    / (NumberTrait::one() + (*item * NumberTrait::neg_one()).exp());\n                data_result.append(result);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/softmax.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::math::{exp::exp_upcast, arithmetic::div_downcast};\n\n/// Cf: NNTrait::softmax docstring\nfn softmax<\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    z: @Tensor<T>, axis: Option<i32>\n) -> Tensor<T> {\n    let axis = match axis {\n        Option::Some(val) => val,\n        Option::None => -1\n    };\n\n    let exp_tensor = z.exp();\n    let sum = exp_tensor\n        .reduce_sum(Option::Some(array![axis].span()), Option::Some(true), Option::Some(false));\n\n    exp_tensor / sum\n}\n\n/// Cf: NNTrait::softmax docstring\nfn softmaxWide<\n    T,\n    TMAG,\n    W,\n    WMAG,\n    impl TTensor: TensorTrait<T>,\n    impl WTensor: TensorTrait<W>,\n    impl TDiv: Div<T>,\n    impl TIntoW: Into<T, W>,\n    impl WTryIntoT: TryInto<W, T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl WCopy: Copy<W>,\n    impl WDrop: Drop<W>,\n    impl TFixed: FixedTrait<T, TMAG>,\n    impl WFixed: FixedTrait<W, WMAG>,\n>(\n    z: @Tensor<T>, axis: Option<i32>\n) -> Tensor<T> {\n    let axis = match axis {\n        Option::Some(val) => val,\n        Option::None => -1\n    };\n\n    let exp_tensor: Tensor<W> = exp_upcast(*z);\n    let sum = exp_tensor\n        .reduce_sum(Option::Some(array![axis].span()), Option::Some(true), Option::Some(false));\n\n    div_downcast(@exp_tensor, @sum)\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/softmax_zero.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\nuse orion::operators::tensor::math::{reduce_sum::accumulate_sum, arithmetic::div_downcast};\n\n/// Cf: NNTrait::softmax_zero docstring\nfn softmax_zero<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialEq: PartialEq<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TAddEq: AddEq<T>,\n>(\n    z: @Tensor<T>, axis: usize\n) -> Tensor<T> {\n    let exp_tensor = exp_zero(*z);\n    let sum_no_zero = reduce_sum_no_zero(@exp_tensor, axis, true);\n\n    exp_tensor / sum_no_zero\n}\n\n/// Cf: NNTrait::softmax_zero docstring\nfn softmaxWide_zero<\n    T,\n    TMAG,\n    W,\n    WMAG,\n    impl TTensor: TensorTrait<T>,\n    impl WTensor: TensorTrait<W>,\n    impl TDiv: Div<T>,\n    impl TIntoW: Into<T, W>,\n    impl WTryIntoT: TryInto<W, T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl WCopy: Copy<W>,\n    impl WDrop: Drop<W>,\n    impl TNumber: NumberTrait<T, TMAG>,\n    impl WNumber: NumberTrait<W, WMAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl WPartialEq: PartialEq<W>,\n    impl TAddEq: AddEq<T>,\n    impl WAddEq: AddEq<W>,\n>(\n    z: @Tensor<T>, axis: usize\n) -> Tensor<T> {\n    let exp_tensor: Tensor<W> = exp_upcast_zero(*z);\n    let sum_no_zero = reduce_sum_no_zero(@exp_tensor, axis, true);\n\n    div_downcast(@exp_tensor, @sum_no_zero)\n}\n\n/// Helper function that compute the exponential of a tensor except if the value of an entry is zero, the value remains zero.\n///\n/// # Arguments\n/// * `z` - The input tensor.\n///\n/// # Returns\n/// * A Tensor<T> representing the exponential of the tensor except for the entries equal to zero in the input tensor, they remain zero.\nfn exp_zero<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl FTensor: TensorTrait<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                if *item == NumberTrait::zero() {\n                    result.append(NumberTrait::zero());\n                } else {\n                    result.append((*item).exp());\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, result.span())\n}\n\n/// Helper function that compute the exponential of a tensor except if the value of an entry is zero, the value remains zero.\n///\n/// # Arguments\n/// * `z` - The input tensor.\n///\n/// # Returns\n/// * A Tensor<T> representing the exponential of the tensor except for the entries equal to zero in the input tensor, they remain zero.\nfn exp_upcast_zero<\n    T,\n    TMAG,\n    W,\n    WMAG,\n    impl TNumber: NumberTrait<T, TMAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl WNumber: NumberTrait<W, WMAG>,\n    impl WTensor: TensorTrait<W>,\n    impl WCopy: Copy<W>,\n    impl WDrop: Drop<W>,\n    impl TIntoW: Into<T, W>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<W> {\n    let mut result: Array<W> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => {\n                if *item == NumberTrait::zero() {\n                    result.append(NumberTrait::zero());\n                } else {\n                    result.append((TIntoW::into(*item)).exp());\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n\n/// Helper function that compute the reduce sum making sure no none zero value are in the output tensor.\n///\n/// # Arguments\n/// * `z` - The input tensor.\n///\n/// # Returns\n/// * A Tensor<T> representing the ereduce sum with no entries equal to zero.\n\nfn reduce_sum_no_zero<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TPartialEq: PartialEq<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let mut output_data: Array<T> = array![];\n\n    if (*self.shape).len() == 1 {\n        assert(axis == 0, 'axis out of dimensions');\n\n        let current_sum = accumulate_sum::<T>(*self.data, *self.shape, *self.shape, axis);\n        output_data.append(current_sum);\n\n        let mut output_shape: Array<usize> = array![];\n        output_shape.append(1);\n\n        return TensorTrait::new(output_shape.span(), output_data.span());\n    } else {\n        assert(axis <= (*self.shape).len(), 'axis out of dimensions');\n\n        let output_shape = reduce_output_shape(*self.shape, axis, false);\n        let output_data_len = len_from_shape(output_shape);\n\n        let mut index: usize = 0;\n        while index != output_data_len {\n            let output_indices = unravel_index(index, output_shape);\n            let mut current_sum = accumulate_sum::<\n                T\n            >(*self.data, *self.shape, output_indices, axis);\n\n            if current_sum == NumberTrait::zero() {\n                current_sum = NumberTrait::one();\n            }\n\n            output_data.append(current_sum);\n            index += 1;\n        };\n\n        if keepdims {\n            let output_shape = reduce_output_shape(*self.shape, axis, true);\n            TensorTrait::<T>::new(output_shape, output_data.span())\n        } else {\n            TensorTrait::<T>::new(output_shape, output_data.span())\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/softplus.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\n\n/// Cf: NNTrait::softplus docstring\nfn softplus<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TFixed: FixedTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAdd: Add<T>,\n    impl TDiv: Div<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                let result = (FixedTrait::ONE() + (*item).exp()).ln();\n                data_result.append(result);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/softsign.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::softsign docstring\nfn softsign<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TFixed: FixedTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAdd: Add<T>,\n    impl TDiv: Div<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                let result = *item / (FixedTrait::ONE() + (*item).abs());\n                data_result.append(result);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/space_to_depth.cairo",
        "content": "use core::option::OptionTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\nuse orion::operators::tensor::math::{reduce_sum::accumulate_sum, arithmetic::div_downcast};\n\n/// Cf: NNTrait::space_to_depth docstring\nfn space_to_depth<\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl TAdd: Add<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    tensor: Tensor<T>, blocksize: usize\n) -> Tensor<T> {\n    assert((tensor.shape).len() == 4, 'Unexpected shape 4.');\n\n    let blocksize_i32: i32 = blocksize.try_into().unwrap();\n\n    let b: i32 = (*(tensor.shape).at(0)).try_into().unwrap();\n    let C: i32 = (*(tensor.shape).at(1)).try_into().unwrap();\n    let H: u32 = (*(tensor.shape).at(2));\n    let W: u32 = (*(tensor.shape).at(3));\n    let tmpshape = array![\n        b,\n        C,\n        (H / blocksize).try_into().unwrap(),\n        blocksize_i32,\n        (W / blocksize).try_into().unwrap(),\n        blocksize_i32\n    ];\n    let reshaped = (tensor).reshape(target_shape: tmpshape.span(), allowzero: false);\n    let transposed = reshaped.transpose(axes: array![0, 3, 5, 1, 2, 4].span());\n    let finalshape = array![\n        b,\n        C * blocksize_i32 * blocksize_i32,\n        (H / blocksize).try_into().unwrap(),\n        (W / blocksize).try_into().unwrap()\n    ];\n\n    transposed.reshape(target_shape: finalshape.span(), allowzero: false)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/functional/thresholded_relu.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: NNTrait::thresholded_relu docstring\nfn thresholded_relu<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut z: Tensor<T>, alpha: @T\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => {\n                if (*item) <= (*alpha) {\n                    data_result.append(NumberTrait::zero());\n                } else {\n                    data_result.append(*item);\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations.cairo",
        "content": "mod nn_i8;\nmod nn_i32;\nmod nn_u32;\nmod nn_fp8x23;\nmod nn_fp16x16;\nmod nn_fp64x64;\nmod nn_fp32x32;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_fp16x16.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\nuse orion::operators::tensor::implementations::tensor_fp16x16::{\n    FP16x16Tensor, FP16x16TensorDiv, FP16x16TensorAdd\n};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    FP16x16WImpl, FP16x16WTryIntoFP16x16, FP16x16W, FP16x16IntoFP16x16W\n};\nuse orion::operators::tensor::implementations::tensor_fp16x16wide::{\n    FP16x16WTensor, FP16x16WTensorDiv, FP16x16WTensorAdd\n};\n\nimpl FP16x16NN of NNTrait<FP16x16> {\n    fn relu(tensor: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        functional::sigmoid::sigmoid(*tensor)\n    }\n\n    fn softmax(tensor: @Tensor<FP16x16>, axis: Option<i32>) -> Tensor<FP16x16> {\n        functional::softmax::softmaxWide::<FP16x16, u32, FP16x16W, u64>(tensor, axis)\n    }\n\n    fn softmax_zero(tensor: @Tensor<FP16x16>, axis: usize) -> Tensor<FP16x16> {\n        functional::softmax_zero::softmaxWide_zero::<FP16x16, u32, FP16x16W, u64>(tensor, axis)\n    }\n\n    fn logsoftmax(tensor: @Tensor<FP16x16>, axis: usize) -> Tensor<FP16x16> {\n        functional::logsoftmax::logsoftmaxWide::<FP16x16, u32, FP16x16W, u64>(tensor, axis)\n    }\n\n    fn softsign(tensor: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        functional::softsign::softsign(*tensor)\n    }\n\n    fn softplus(tensor: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        functional::softplus::softplus(*tensor)\n    }\n\n    fn linear(\n        inputs: Tensor<FP16x16>, weights: Tensor<FP16x16>, bias: Tensor<FP16x16>\n    ) -> Tensor<FP16x16> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<FP16x16>, alpha: @FP16x16) -> Tensor<FP16x16> {\n        functional::leaky_relu::leaky_relu(*inputs, alpha)\n    }\n\n    fn thresholded_relu(tensor: @Tensor<FP16x16>, alpha: @FP16x16) -> Tensor<FP16x16> {\n        functional::thresholded_relu::thresholded_relu(*tensor, alpha)\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<FP16x16>, alpha: @FP16x16, beta: @FP16x16) -> Tensor<FP16x16> {\n        functional::hard_sigmoid::hard_sigmoid(*tensor, alpha, beta)\n    }\n\n    fn depth_to_space(\n        tensor: @Tensor<FP16x16>, blocksize: usize, mode: felt252\n    ) -> Tensor<FP16x16> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<FP16x16>, blocksize: usize) -> Tensor<FP16x16> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<FP16x16>,\n        B: Tensor<FP16x16>,\n        C: Option<Tensor<FP16x16>>,\n        alpha: Option<FP16x16>,\n        beta: Option<FP16x16>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<FP16x16> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<FP16x16>,\n        grid: @Tensor<FP16x16>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<FP16x16> {\n        functional::grid_sample::grid_sample(X, grid, align_corner, mode, padding_mode)\n    }\n\n    fn col2im(\n        data: @Tensor<FP16x16>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP16x16> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<FP16x16>,\n        W: @Tensor<FP16x16>,\n        B: Option<@Tensor<FP16x16>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP16x16> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<FP16x16>,\n        W: @Tensor<FP16x16>,\n        B: Option<Span<FP16x16>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP16x16> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_fp32x32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::numbers::fixed_point::implementations::fp32x32::core::{FP32x32, FP32x32Impl};\nuse orion::operators::tensor::implementations::tensor_fp32x32::{\n    FP32x32Tensor, FP32x32TensorDiv, FP32x32TensorAdd\n};\n\nimpl FP32x32NN of NNTrait<FP32x32> {\n    fn relu(tensor: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        functional::sigmoid::sigmoid(*tensor)\n    }\n\n    fn softmax(tensor: @Tensor<FP32x32>, axis: Option<i32>) -> Tensor<FP32x32> {\n        functional::softmax::softmax(tensor, axis)\n    }\n\n    fn softmax_zero(tensor: @Tensor<FP32x32>, axis: usize) -> Tensor<FP32x32> {\n        functional::softmax_zero::softmax_zero(tensor, axis)\n    }\n\n    fn logsoftmax(tensor: @Tensor<FP32x32>, axis: usize) -> Tensor<FP32x32> {\n        functional::logsoftmax::logsoftmax(tensor, axis)\n    }\n\n    fn softsign(tensor: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        functional::softsign::softsign(*tensor)\n    }\n\n    fn softplus(tensor: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        functional::softplus::softplus(*tensor)\n    }\n\n    fn linear(\n        inputs: Tensor<FP32x32>, weights: Tensor<FP32x32>, bias: Tensor<FP32x32>\n    ) -> Tensor<FP32x32> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<FP32x32>, alpha: @FP32x32) -> Tensor<FP32x32> {\n        functional::leaky_relu::leaky_relu(*inputs, alpha)\n    }\n\n    fn thresholded_relu(tensor: @Tensor<FP32x32>, alpha: @FP32x32) -> Tensor<FP32x32> {\n        functional::thresholded_relu::thresholded_relu(*tensor, alpha)\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<FP32x32>, alpha: @FP32x32, beta: @FP32x32) -> Tensor<FP32x32> {\n        functional::hard_sigmoid::hard_sigmoid(*tensor, alpha, beta)\n    }\n\n    fn depth_to_space(\n        tensor: @Tensor<FP32x32>, blocksize: usize, mode: felt252\n    ) -> Tensor<FP32x32> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<FP32x32>, blocksize: usize) -> Tensor<FP32x32> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<FP32x32>,\n        B: Tensor<FP32x32>,\n        C: Option<Tensor<FP32x32>>,\n        alpha: Option<FP32x32>,\n        beta: Option<FP32x32>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<FP32x32> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<FP32x32>,\n        grid: @Tensor<FP32x32>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<FP32x32> {\n        functional::grid_sample::grid_sample(X, grid, align_corner, mode, padding_mode)\n    }\n\n    fn col2im(\n        data: @Tensor<FP32x32>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP32x32> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<FP32x32>,\n        W: @Tensor<FP32x32>,\n        B: Option<@Tensor<FP32x32>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP32x32> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<FP32x32>,\n        W: @Tensor<FP32x32>,\n        B: Option<Span<FP32x32>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP32x32> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_fp64x64.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::numbers::fixed_point::implementations::fp64x64::core::{FP64x64, FP64x64Impl};\nuse orion::operators::tensor::implementations::tensor_fp64x64::{\n    FP64x64Tensor, FP64x64TensorDiv, FP64x64TensorAdd\n};\n\nimpl FP64x64NN of NNTrait<FP64x64> {\n    fn relu(tensor: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        functional::sigmoid::sigmoid(*tensor)\n    }\n\n    fn softmax(tensor: @Tensor<FP64x64>, axis: Option<i32>) -> Tensor<FP64x64> {\n        functional::softmax::softmax(tensor, axis)\n    }\n\n    fn softmax_zero(tensor: @Tensor<FP64x64>, axis: usize) -> Tensor<FP64x64> {\n        functional::softmax_zero::softmax_zero(tensor, axis)\n    }\n\n    fn logsoftmax(tensor: @Tensor<FP64x64>, axis: usize) -> Tensor<FP64x64> {\n        functional::logsoftmax::logsoftmax(tensor, axis)\n    }\n\n    fn softsign(tensor: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        functional::softsign::softsign(*tensor)\n    }\n\n    fn softplus(tensor: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        functional::softplus::softplus(*tensor)\n    }\n\n    fn linear(\n        inputs: Tensor<FP64x64>, weights: Tensor<FP64x64>, bias: Tensor<FP64x64>\n    ) -> Tensor<FP64x64> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<FP64x64>, alpha: @FP64x64) -> Tensor<FP64x64> {\n        functional::leaky_relu::leaky_relu(*inputs, alpha)\n    }\n\n    fn thresholded_relu(tensor: @Tensor<FP64x64>, alpha: @FP64x64) -> Tensor<FP64x64> {\n        functional::thresholded_relu::thresholded_relu(*tensor, alpha)\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<FP64x64>, alpha: @FP64x64, beta: @FP64x64) -> Tensor<FP64x64> {\n        functional::hard_sigmoid::hard_sigmoid(*tensor, alpha, beta)\n    }\n\n    fn depth_to_space(\n        tensor: @Tensor<FP64x64>, blocksize: usize, mode: felt252\n    ) -> Tensor<FP64x64> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<FP64x64>, blocksize: usize) -> Tensor<FP64x64> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<FP64x64>,\n        B: Tensor<FP64x64>,\n        C: Option<Tensor<FP64x64>>,\n        alpha: Option<FP64x64>,\n        beta: Option<FP64x64>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<FP64x64> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<FP64x64>,\n        grid: @Tensor<FP64x64>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<FP64x64> {\n        functional::grid_sample::grid_sample(X, grid, align_corner, mode, padding_mode)\n    }\n\n    fn col2im(\n        data: @Tensor<FP64x64>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP64x64> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<FP64x64>,\n        W: @Tensor<FP64x64>,\n        B: Option<@Tensor<FP64x64>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP64x64> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<FP64x64>,\n        W: @Tensor<FP64x64>,\n        B: Option<Span<FP64x64>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP64x64> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_fp8x23.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\nuse orion::operators::tensor::implementations::tensor_fp8x23::{\n    FP8x23Tensor, FP8x23TensorDiv, FP8x23TensorAdd\n};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{\n    FP8x23WImpl, FP8x23WTryIntoFP8x23, FP8x23W, FP8x23IntoFP8x23W\n};\nuse orion::operators::tensor::implementations::tensor_fp8x23wide::{FP8x23WTensor};\n\nimpl FP8x23NN of NNTrait<FP8x23> {\n    fn relu(tensor: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        functional::sigmoid::sigmoid(*tensor)\n    }\n\n    fn softmax(tensor: @Tensor<FP8x23>, axis: Option<i32>) -> Tensor<FP8x23> {\n        functional::softmax::softmaxWide::<FP8x23, u32, FP8x23W, u64>(tensor, axis)\n    }\n\n    fn softmax_zero(tensor: @Tensor<FP8x23>, axis: usize) -> Tensor<FP8x23> {\n        functional::softmax_zero::softmaxWide_zero::<FP8x23, u32, FP8x23W, u64>(tensor, axis)\n    }\n\n    fn logsoftmax(tensor: @Tensor<FP8x23>, axis: usize) -> Tensor<FP8x23> {\n        functional::logsoftmax::logsoftmaxWide::<FP8x23, u32, FP8x23W, u64>(tensor, axis)\n    }\n\n    fn softsign(tensor: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        functional::softsign::softsign(*tensor)\n    }\n\n    fn softplus(tensor: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        functional::softplus::softplus(*tensor)\n    }\n\n    fn linear(\n        inputs: Tensor<FP8x23>, weights: Tensor<FP8x23>, bias: Tensor<FP8x23>\n    ) -> Tensor<FP8x23> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<FP8x23>, alpha: @FP8x23) -> Tensor<FP8x23> {\n        functional::leaky_relu::leaky_relu(*inputs, alpha)\n    }\n\n    fn thresholded_relu(tensor: @Tensor<FP8x23>, alpha: @FP8x23) -> Tensor<FP8x23> {\n        functional::thresholded_relu::thresholded_relu(*tensor, alpha)\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<FP8x23>, alpha: @FP8x23, beta: @FP8x23) -> Tensor<FP8x23> {\n        functional::hard_sigmoid::hard_sigmoid(*tensor, alpha, beta)\n    }\n\n    fn depth_to_space(tensor: @Tensor<FP8x23>, blocksize: usize, mode: felt252) -> Tensor<FP8x23> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<FP8x23>, blocksize: usize) -> Tensor<FP8x23> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<FP8x23>,\n        B: Tensor<FP8x23>,\n        C: Option<Tensor<FP8x23>>,\n        alpha: Option<FP8x23>,\n        beta: Option<FP8x23>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<FP8x23> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<FP8x23>,\n        grid: @Tensor<FP8x23>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<FP8x23> {\n        functional::grid_sample::grid_sample(X, grid, align_corner, mode, padding_mode)\n    }\n\n    fn col2im(\n        data: @Tensor<FP8x23>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP8x23> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<FP8x23>,\n        W: @Tensor<FP8x23>,\n        B: Option<@Tensor<FP8x23>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP8x23> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<FP8x23>,\n        W: @Tensor<FP8x23>,\n        B: Option<Span<FP8x23>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<FP8x23> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_i32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::operators::tensor::implementations::tensor_i32::{I32Tensor, I32TensorAdd};\n\nimpl I32NN of NNTrait<i32> {\n    fn relu(tensor: @Tensor<i32>) -> Tensor<i32> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax(tensor: @Tensor<i32>, axis: Option<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax_zero(tensor: @Tensor<i32>, axis: usize) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn logsoftmax(tensor: @Tensor<i32>, axis: usize) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softsign(tensor: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softplus(tensor: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn linear(inputs: Tensor<i32>, weights: Tensor<i32>, bias: Tensor<i32>) -> Tensor<i32> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<i32>, alpha: @i32) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn thresholded_relu(tensor: @Tensor<i32>, alpha: @i32) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<i32>, alpha: @i32, beta: @i32) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn depth_to_space(tensor: @Tensor<i32>, blocksize: usize, mode: felt252) -> Tensor<i32> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<i32>, blocksize: usize) -> Tensor<i32> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<i32>,\n        B: Tensor<i32>,\n        C: Option<Tensor<i32>>,\n        alpha: Option<i32>,\n        beta: Option<i32>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<i32> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<i32>,\n        grid: @Tensor<i32>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn col2im(\n        data: @Tensor<i32>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i32> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<i32>,\n        W: @Tensor<i32>,\n        B: Option<@Tensor<i32>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i32> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<i32>,\n        W: @Tensor<i32>,\n        B: Option<Span<i32>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i32> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_i8.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::operators::tensor::implementations::tensor_i8::{I8Tensor, I8TensorAdd};\n\nimpl I8NN of NNTrait<i8> {\n    fn relu(tensor: @Tensor<i8>) -> Tensor<i8> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax(tensor: @Tensor<i8>, axis: Option<i32>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax_zero(tensor: @Tensor<i8>, axis: usize) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn logsoftmax(tensor: @Tensor<i8>, axis: usize) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn softsign(tensor: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn softplus(tensor: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn linear(inputs: Tensor<i8>, weights: Tensor<i8>, bias: Tensor<i8>) -> Tensor<i8> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<i8>, alpha: @i8) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn thresholded_relu(tensor: @Tensor<i8>, alpha: @i8) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<i8>, alpha: @i8, beta: @i8) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn depth_to_space(tensor: @Tensor<i8>, blocksize: usize, mode: felt252) -> Tensor<i8> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<i8>, blocksize: usize) -> Tensor<i8> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<i8>,\n        B: Tensor<i8>,\n        C: Option<Tensor<i8>>,\n        alpha: Option<i8>,\n        beta: Option<i8>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<i8> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<i8>,\n        grid: @Tensor<i8>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn col2im(\n        data: @Tensor<i8>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i8> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<i8>,\n        W: @Tensor<i8>,\n        B: Option<@Tensor<i8>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i8> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<i8>,\n        W: @Tensor<i8>,\n        B: Option<Span<i8>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<i8> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/nn/implementations/nn_u32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::nn::core::NNTrait;\nuse orion::operators::nn::functional;\nuse orion::operators::tensor::implementations::tensor_u32::{U32Tensor, U32TensorAdd};\n\nimpl U32NN of NNTrait<u32> {\n    fn relu(tensor: @Tensor<u32>) -> Tensor<u32> {\n        functional::relu::relu(*tensor)\n    }\n\n    fn sigmoid(tensor: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax(tensor: @Tensor<u32>, axis: Option<i32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softmax_zero(tensor: @Tensor<u32>, axis: usize) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn logsoftmax(tensor: @Tensor<u32>, axis: usize) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softsign(tensor: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn softplus(tensor: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn linear(inputs: Tensor<u32>, weights: Tensor<u32>, bias: Tensor<u32>) -> Tensor<u32> {\n        functional::linear::linear(inputs, weights, bias)\n    }\n\n    fn leaky_relu(inputs: @Tensor<u32>, alpha: @u32) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn thresholded_relu(tensor: @Tensor<u32>, alpha: @u32) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn hard_sigmoid(tensor: @Tensor<u32>, alpha: @u32, beta: @u32) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn depth_to_space(tensor: @Tensor<u32>, blocksize: usize, mode: felt252) -> Tensor<u32> {\n        functional::depth_to_space::depth_to_space(*tensor, blocksize, mode)\n    }\n\n    fn space_to_depth(tensor: @Tensor<u32>, blocksize: usize) -> Tensor<u32> {\n        functional::space_to_depth::space_to_depth(*tensor, blocksize)\n    }\n\n    fn gemm(\n        A: Tensor<u32>,\n        B: Tensor<u32>,\n        C: Option<Tensor<u32>>,\n        alpha: Option<u32>,\n        beta: Option<u32>,\n        transA: bool,\n        transB: bool\n    ) -> Tensor<u32> {\n        functional::gemm::gemm(A, B, C, alpha, beta, transA, transB)\n    }\n\n    fn grid_sample(\n        X: @Tensor<u32>,\n        grid: @Tensor<u32>,\n        align_corner: Option<usize>,\n        mode: Option<functional::grid_sample::MODE>,\n        padding_mode: Option<functional::grid_sample::PADDING_MODE>,\n    ) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn col2im(\n        data: @Tensor<u32>,\n        image_shape: Span<usize>,\n        block_shape: Span<usize>,\n        dilations: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<u32> {\n        functional::col2im::col2im(data, image_shape, block_shape, dilations, pads, strides,)\n    }\n\n    fn conv_transpose(\n        X: @Tensor<u32>,\n        W: @Tensor<u32>,\n        B: Option<@Tensor<u32>>,\n        auto_pad: Option<functional::conv_transpose::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        output_padding: Option<Span<usize>>,\n        output_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<u32> {\n        functional::conv_transpose::conv_transpose(\n            X,\n            W,\n            B,\n            auto_pad,\n            dilations,\n            group,\n            kernel_shape,\n            output_padding,\n            output_shape,\n            pads,\n            strides\n        )\n    }\n\n    fn conv(\n        X: @Tensor<u32>,\n        W: @Tensor<u32>,\n        B: Option<Span<u32>>,\n        auto_pad: Option<functional::conv::AUTO_PAD>,\n        dilations: Option<Span<usize>>,\n        group: Option<usize>,\n        kernel_shape: Option<Span<usize>>,\n        pads: Option<Span<usize>>,\n        strides: Option<Span<usize>>,\n    ) -> Tensor<u32> {\n        functional::conv::conv(X, W, B, auto_pad, dilations, group, kernel_shape, pads, strides)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence.cairo",
        "content": "mod core;\nmod implementations;\nmod functional;\n\nuse orion::operators::sequence::core::SequenceTrait;\n\nuse orion::operators::sequence::implementations::sequence_fp8x23::FP8x23Sequence;\nuse orion::operators::sequence::implementations::sequence_fp8x23wide::FP8x23WSequence;\nuse orion::operators::sequence::implementations::sequence_fp16x16::FP16x16Sequence;\nuse orion::operators::sequence::implementations::sequence_fp16x16wide::FP16x16WSequence;\nuse orion::operators::sequence::implementations::sequence_i8::I8Sequence;\nuse orion::operators::sequence::implementations::sequence_i32::I32Sequence;\nuse orion::operators::sequence::implementations::sequence_u32::U32Sequence;\nuse orion::operators::sequence::implementations::sequence_bool::BoolSequence;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/core.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\n\n/// Trait\n///\n/// sequence_construct - Constructs a tensor sequence containing the input tensors.\n/// sequence_empty - Returns an empty tensor sequence.\n/// sequence_length - Returns the length of the input sequence.\n/// sequence_insert - Insert a tensor into a sequence.\n/// sequence_at - Outputs the tensor at the specified position in the input sequence.\n/// sequence_erase \u2013 Outputs the tensor sequence with the erased tensor at the specified position.\n/// concat_from_sequence - Concatenate a sequence of tensors into a single tensor.\ntrait SequenceTrait<T> {\n    /// ## sequence.sequence_construct\n    ///\n    /// ```rust \n    ///    fn sequence_construct(tensors: Array<Tensor<T>>) -> Array<Tensor<T>>;\n    /// ```\n    ///\n    /// Constructs a tensor sequence containing the input tensors.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(`Array<Tensor<T>>`) - The array of input tensors.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if input tensor array is empty.\n    ///\n    /// ## Returns\n    ///\n    /// A tensor sequence `Array<Tensor<T>>` containing the input tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// use orion::operators::sequence::SequenceTrait;\n    ///\n    /// fn sequence_construct_example() -> Array<Tensor<usize>> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span());\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![4, 5, 6, 7].span());\n    ///     let result = SequenceTrait::sequence_construct(tensors: array![tensor1, tensor2]);\n    ///     return result;\n    /// }\n    /// >>> [[0, 1, 2, 3], [4, 5, 6, 7]]\n    /// ```\n    ///\n    fn sequence_construct(tensors: Array<Tensor<T>>) -> Array<Tensor<T>>;\n    /// ## sequence.sequence_empty\n    ///\n    /// ```rust\n    ///    fn sequence_empty() -> Array<Tensor<T>>;\n    /// ```\n    ///\n    /// Returns an empty tensor sequence.\n    ///\n    /// ## Args\n    ///\n    /// ## Returns\n    ///\n    /// An empty `Array<Tensor<T>>` instance.\n    ///\n    /// ## Examples\n    ///\n    /// Let's create a new empty sequence.\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    ///\n    /// use orion::operators::tensor::{\n    ///     TensorTrait, // we import the trait\n    ///     Tensor, // we import the type\n    ///     U32Tensor // we import the implementation. \n    /// };\n    /// use orion::operators::sequence::SequenceTrait;\n    ///\n    /// fn sequence_empty_example() -> Array<Tensor<u32>> {\n    ///     let sequence = SequenceTrait::sequence_empty();\n    ///\n    ///     return sequence;\n    /// }\n    ///\n    /// >>> []\n    /// ```\n    ///\n    fn sequence_empty() -> Array<Tensor<T>>;\n    /// # tensor.sequence_length\n    ///\n    /// ```rust\n    ///    fn sequence_length(self: Array<Tensor<T>>) -> Tensor<u32>;\n    /// ```\n    ///\n    /// Returns the length of the input sequence.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`Array<Tensor<T>>`) - The input sequence.\n    ///\n    /// ## Returns\n    ///\n    /// The length of the sequence as scalar, i.e. a tensor of shape [].\n    ///\n    /// ## Examples\n    ///\n    /// Let's create new u32 Tensor with constant 42.\n    ///\n    /// ```rust\n    /// let mut sequence = ArrayTrait::new();\n    ///\n    /// let mut shape = ArrayTrait::<usize>::new();\n    /// shape.append(1);\n    /// shape.append(2);\n    ///\n    /// let mut data = ArrayTrait::new();\n    /// data.append(3);\n    /// data.append(1);\n    ///\n    /// sequence.append(TensorTrait::new(shape.span(), data.span()));\n    ///\n    /// sequence.sequence_length()\n    /// >>> [1]\n    /// ```\n    ///\n    fn sequence_length(self: Array<Tensor<T>>) -> Tensor<u32>;\n    /// # tensor.sequence_insert\n    ///\n    /// ```rust \n    ///    fn sequence_insert(self: Array<Tensor<T>>, tensor: @Tensor<T>, position: Option<Tensor<i32>>) -> Array<Tensor<T>>;\n    /// ```\n    ///\n    /// Returns a tensor sequence that inserts 'tensor' into 'self' at 'position'.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`Array<Tensor<T>>`) - input sequence.\n    /// * `tensor` (`@Tensor<T>`) - the tensor to insert.\n    /// * `position` (`@Tensor<i32>`) - the index for insertion (default: -1).\n    ///\n    /// ## Returns\n    ///\n    /// Tensor sequence containing 'tensor' inserted into 'self' at 'position'.\n    ///\n    /// ## Examples\n    ///\n    /// Let's insert the tensor [2] into the sequence [[1], [3]] at position 1.\n    ///\n    /// ```rust\n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor, U32Tensor};\n    ///\n    /// fn sequence_insert_example() -> Array<Tensor<u32>> {\n    ///     // Prepare sequence\n    ///     let mut sequence = ArrayTrait::new();\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(1);\n    ///     sequence.append(TensorTrait::new(shape.span(), data.span()));\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(3);\n    ///\n    ///     sequence.append(TensorTrait::new(shape.span(), data.span()));\n    ///\n    ///     // Prepare input tensor\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(2);\n    ///     let tensor = TensorTrait::new(shape.span(), data.span());\n    ///\n    ///     // Prepare position\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     let mut data = ArrayTrait::<i32>::new();\n    ///     data.append(1);\n    ///     let position = TensorTrait::<i32>::new(shape.span(), data.span())\n    ///\n    ///     let sequence = self.sequence_insert(tensor, Option::Some(position));\n    ///\n    ///     return sequence;\n    /// }\n    ///\n    /// >>> [[1], [2], [3]]\n    /// ```\n    ///\n    fn sequence_insert(\n        self: Array<Tensor<T>>, tensor: @Tensor<T>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<T>>;\n    /// ## tensor.sequence_at\n    ///\n    /// ```rust \n    ///    fn sequence_at(sequence: Array<Tensor<T>>, position: Tensor<i32>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Outputs the tensor at the specified position in the input sequence.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(`Array<Tensor<T>>`) - The tensor sequence.\n    /// * `position`(`Tensor<i32>`) - The position tensor.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if position is not a scalar\n    /// * Panics if position is out of bounds [-n, n - 1]\n    ///\n    /// ## Returns\n    ///\n    /// The tensor `Tensor<T>` from the sequence at the specified position.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor, I32Tensor};\n    ///\n    /// fn sequence_at_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span());\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![4, 5, 6, 7].span());\n    ///     \n    ///     let mut sequence = ArrayTrait::new();\n    ///     sequence.append(tensor1);\n    ///     sequence.append(tensor2);\n    ///\n    ///     let position = TensorTrait::new(shape: array![].span(), data: array![IntegerTrait::new(1, false)].span());\n    ///\n    ///     let result = TensorTrait::sequence_at(sequence, position);\n    ///     return result;\n    /// }\n    /// >>> [4, 5, 6, 7]\n    /// ```\n    ///\n    fn sequence_at(sequence: Array<Tensor<T>>, position: Tensor<i32>) -> Tensor<T>;\n    /// ## tensor.sequence_erase\n    ///\n    /// ```rust \n    ///    fn sequence_erase(sequence: Array<Tensor<T>>, position: Option<Tensor<i32>>) -> Array<Tensor<T>>;\n    /// ```\n    ///\n    /// Outputs the tensor sequence with the erased tensor at the specified position.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(`Array<Tensor<T>>`) - The tensor sequence.\n    /// * `position`(`Option<Tensor<i32>>`) - The optional position tensor (by default erases the last tensor).\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if position is not a scalar\n    /// * Panics if position is out of bounds [-n, n - 1]\n    ///\n    /// ## Returns\n    ///\n    /// The tensor sequence `Array<Tensor<T>>` with the erased tensor at the specified position.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor, I32Tensor};\n    ///\n    /// fn sequence_erase_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span());\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![4, 5, 6, 7].span());\n    ///     let tensor3 = TensorTrait::new(shape: array![2, 2].span(), data: array![8, 9, 10, 11].span());\n    ///     \n    ///     let mut sequence = ArrayTrait::new();\n    ///     sequence.append(tensor1);\n    ///     sequence.append(tensor2);\n    ///     sequence.append(tensor3);\n    ///\n    ///     let position = TensorTrait::new(shape: array![].span(), data: array![IntegerTrait::new(1, false)].span());\n    ///\n    ///     let result = TensorTrait::sequence_erase(sequence, position);\n    ///     return result;\n    /// }\n    /// >>> [[0, 1, 2, 3], [8, 9, 10, 11]]\n    /// ```\n    ///\n    fn sequence_erase(\n        sequence: Array<Tensor<T>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<T>>;\n    /// # tensor.concat_from_sequence\n    ///\n    /// ```rust \n    ///    fn concat_from_sequence(sequence: Array<Tensor<T>>, axis: i32, new_axis: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Concatenate a sequence of tensors into a single tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `sequence`(`Array<Tensor<T>>`) - The input sequence.\n    /// * `axis`(`i32`) -  Axis to concat on.\n    /// * `new_axis`(`Option<usize>`) -  Optionally added new axis.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if new_axis not 0 or 1 (if value provided).\n    /// * Panics if axis not in accepted ranges.\n    /// * Panics if sequence length is not greater than 1.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` concatenated tensor from the input tensor sequence.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn concat_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///\n    ///     let mut sequence = ArrayTrait::new();\n    ///     sequence.append(tensor1);\n    ///     sequence.append(tensor2);\n    ///\n    ///     let result = TensorTrait::concat_from_sequence(sequence: sequence, axis: 0, new_axis: Option::Some(0));\n    ///     return result;\n    /// }\n    /// >>> [[0. 1.]\n    ///      [2. 3.],\n    ///      [0. 1.]\n    ///      [2. 3.]]\n    ///\n    ///     result.shape\n    /// >>> (4, 2)\n    ///\n    ///    let result = TensorTrait::concat_from_sequence(sequence: sequence, axis: 1, new_axis: Option::Some(0));\n    ///    return result;\n    /// }\n    /// >>> [[0. 1., 0., 1.]\n    ///      [2. 3., 2., 3.]]\n    ///\n    ///     result.shape\n    /// >>> (2, 4 ) \n    /// ```\n    ///\n    fn concat_from_sequence(\n        sequence: Array<Tensor<T>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<T>;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional.cairo",
        "content": "mod sequence_construct;\nmod sequence_empty;\nmod sequence_at;\nmod sequence_erase;\nmod sequence_insert;\nmod sequence_length;\nmod concat_from_sequence;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/concat_from_sequence.cairo",
        "content": "use orion::operators::tensor::helpers::replace_index;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::math::concat::concat;\nuse orion::numbers::{NumberTrait, I32IntoU32};\n\nfn concat_from_sequence<\n    T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,\n>(\n    sequence: Array<Tensor<T>>, axis: i32, new_axis: Option<usize>\n) -> Tensor<T> {\n    let new_axis: usize = match new_axis {\n        Option::Some(val) => {\n            assert(val == 0 || val == 1, 'new_axis must be 0 or 1');\n            val\n        },\n        Option::None => 0\n    };\n\n    let first_tensor = *sequence.at(0);\n    let r = first_tensor.shape.len();\n\n    if new_axis == 0 {\n        concat_without_new_axis(sequence, axis, r)\n    } else {\n        concat_with_new_axis(sequence, axis, r)\n    }\n}\n\nfn concat_without_new_axis<\n    T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,\n>(\n    sequence: Array<Tensor<T>>, axis: i32, r: usize\n) -> Tensor<T> {\n    let axis_is_negative: bool = axis < 0;\n    let mut axis_value: u32 = axis.into();\n\n    /// assert in range [-r, r - 1]\n    assert(\n        (!axis_is_negative && axis_value <= r - 1) || (axis_is_negative && axis_value <= r),\n        'Out of bounds for dimension'\n    );\n\n    if axis_is_negative {\n        axis_value = r - axis_value\n    }\n\n    concat(sequence.span(), axis_value)\n}\n\nfn concat_with_new_axis<\n    T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,\n>(\n    sequence: Array<Tensor<T>>, axis: i32, r: usize\n) -> Tensor<T> {\n    let axis_is_negative: bool = axis < 0;\n    let mut axis_value: u32 = axis.into();\n\n    /// assert in range [-r - 1, r]\n    assert(\n        (!axis_is_negative && axis_value <= r) || (axis_is_negative && axis_value <= r + 1),\n        'Out of bounds for dimension'\n    );\n\n    if axis_is_negative {\n        if axis_value > r {\n            axis_value = 0\n        } else {\n            axis_value = r - axis_value\n        }\n    }\n\n    let mut input_sequence_copy = sequence;\n    let mut reshaped_sequence: Array<Tensor<T>> = array![];\n    loop {\n        match input_sequence_copy.pop_front() {\n            Option::Some(input_sequence_value) => {\n                let mut reshaped_tensor = add_new_dimension(input_sequence_value, axis_value);\n                reshaped_sequence.append(reshaped_tensor);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    concat(reshaped_sequence.span(), axis_value)\n}\n\n\nfn add_new_dimension<\n    T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,\n>(\n    mut tensor: Tensor<T>, axis: usize\n) -> Tensor<T> {\n    let mut tensor_shape = tensor.shape;\n    let mut new_tensor_shape: Array<usize> = array![];\n    let mut tensor_shape_counter: usize = 0;\n    loop {\n        match tensor_shape.pop_front() {\n            Option::Some(tensor_shape_value) => {\n                if tensor_shape_counter == axis {\n                    new_tensor_shape.append(1);\n                }\n                new_tensor_shape.append(*tensor_shape_value);\n                tensor_shape_counter += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    if axis >= tensor.shape.len() {\n        new_tensor_shape.append(1);\n    }\n\n    TensorTrait::<T>::new(new_tensor_shape.span(), tensor.data)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_at.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::{NumberTrait, I32IntoU32, U32IntoI32};\n\n/// Cf: SequenceTrait::sequence_at docstring\nfn sequence_at<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    sequence: Array<Tensor<T>>, position: Tensor<i32>\n) -> Tensor<T> {\n    assert(\n        position.shape.len() == 0 && position.data.len().into() == 1, 'Position must be a scalar'\n    );\n\n    let position_value_i32: i32 = *position.data.at(0);\n    let is_negative: bool = position_value_i32 < 0;\n    let position_value: u32 = position_value_i32.into();\n\n    assert(\n        (!is_negative && position_value <= sequence.len() - 1)\n            || (is_negative && position_value <= sequence.len()),\n        'Position out of bounds'\n    );\n\n    if !is_negative {\n        *sequence.at(position_value)\n    } else {\n        let normalized_position_value = sequence.len() - position_value;\n\n        *sequence.at(normalized_position_value)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_construct.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: SequenceTrait::sequence_construct docstring\nfn sequence_construct<T, impl TDrop: Drop<T>>(tensors: Array<Tensor<T>>) -> Array<Tensor<T>> {\n    assert(tensors.len() >= 1, 'Input tensors must be >= 1');\n\n    tensors\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_empty.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: SequenceTrait::sequence_empty docstring\nfn sequence_empty<T, impl TTensorTrait: TensorTrait<T>, impl TDrop: Drop<T>>() -> Array<Tensor<T>> {\n    let mut sequence = array![];\n\n    let mut shape: Array<usize> = array![];\n    shape.append(0);\n\n    let mut data: Array<T> = array![];\n    let tensor = TensorTrait::new(shape.span(), data.span());\n\n    sequence.append(tensor);\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_erase.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::I32Tensor;\nuse orion::numbers::{NumberTrait, I32IntoU32};\n\n/// Cf: SequenceTrait::sequence_erase docstring\nfn sequence_erase<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    sequence: Array<Tensor<T>>, position: Option<Tensor<i32>>\n) -> Array<Tensor<T>> {\n    let position: Tensor<i32> = match position {\n        Option::Some(p) => p,\n        Option::None => {\n            let mut shape: Array<usize> = array![];\n            let mut data: Array<i32> = array![];\n            data.append(-1_i32);\n\n            TensorTrait::<i32>::new(shape.span(), data.span())\n        }\n    };\n\n    assert(position.shape.len() == 0 && position.data.len() == 1, 'Position must be a scalar');\n\n    let position_value_i32: i32 = *position.data.at(0);\n    let is_negative: bool = position_value_i32 < 0;\n    let mut position_value: u32 = position_value_i32.into();\n\n    assert(\n        (!is_negative && position_value <= sequence.len() - 1)\n            || (is_negative && position_value <= sequence.len()),\n        'Position out of bounds'\n    );\n\n    if is_negative {\n        position_value = sequence.len() - position_value;\n    }\n\n    let mut input_sequence_copy = sequence;\n    let mut output_sequence: Array<Tensor<T>> = array![];\n    let mut tensor_counter: usize = 0;\n    loop {\n        match input_sequence_copy.pop_front() {\n            Option::Some(input_sequence_value) => {\n                if tensor_counter == position_value {\n                    tensor_counter += 1;\n                    continue;\n                }\n\n                output_sequence.append(input_sequence_value);\n                tensor_counter += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_sequence\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_insert.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::I32Tensor;\nuse orion::numbers::{NumberTrait, I32IntoU32};\n\n/// Cf: SequenceTrait::sequence_insert docstring\nfn sequence_insert<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: Array<Tensor<T>>, tensor: @Tensor<T>, position: Option<Tensor<i32>>\n) -> Array<Tensor<T>> {\n    let position: Tensor<i32> = match position {\n        Option::Some(p) => p,\n        Option::None => {\n            let mut shape: Array<usize> = array![];\n            let mut data: Array<i32> = array![];\n            data.append(-1_i32);\n\n            TensorTrait::<i32>::new(shape.span(), data.span())\n        },\n    };\n\n    assert(position.shape.len() == 0 && position.data.len() == 1, 'Position must be a scalar');\n\n    let position_value_i32: i32 = *position.data.at(0);\n    let is_negative: bool = position_value_i32 < 0;\n    let mut position_value: u32 = position_value_i32.into();\n\n    assert(\n        (!is_negative && position_value <= self.len() - 1)\n            || (is_negative && position_value <= self.len()),\n        'Position out of bounds'\n    );\n\n    if is_negative {\n        position_value = self.len() - position_value;\n    }\n\n    let mut new_sequence: Array<Tensor<T>> = array![];\n    let mut inserted = false;\n    let mut self_copy = self;\n    loop {\n        match self_copy.pop_front() {\n            Option::Some(t) => {\n                if position_value == 0 && inserted == false {\n                    new_sequence.append(*tensor);\n                    inserted = true;\n                }\n                new_sequence.append(t);\n                if !inserted {\n                    position_value -= 1;\n                }\n            },\n            Option::None => { break; },\n        };\n    };\n\n    new_sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/functional/sequence_length.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: SequenceTrait::sequence_length docstring\nfn sequence_length<T, impl TDrop: Drop<T>>(self: Array<Tensor<T>>) -> Tensor<u32> {\n    let mut shape: Array<usize> = array![];\n    let mut result: Array<usize> = array![];\n    result.append(self.len());\n\n    Tensor::<u32> { shape: shape.span(), data: result.span(), }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations.cairo",
        "content": "mod sequence_bool;\nmod sequence_i8;\nmod sequence_i32;\nmod sequence_u32;\nmod sequence_fp8x23;\nmod sequence_fp8x23wide;\nmod sequence_fp16x16;\nmod sequence_fp16x16wide;\nmod sequence_fp32x32;\nmod sequence_fp64x64;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_bool.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::operators::tensor::implementations::tensor_bool::BoolTensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl BoolSequence of SequenceTrait<bool> {\n    fn sequence_construct(tensors: Array<Tensor<bool>>) -> Array<Tensor<bool>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<bool>> {\n        functional::sequence_empty::sequence_empty::<bool>()\n    }\n\n    fn sequence_length(self: Array<Tensor<bool>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<bool>>, position: Tensor<i32>) -> Tensor<bool> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<bool>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<bool>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<bool>>, tensor: @Tensor<bool>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<bool>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<bool>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<bool> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp16x16.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\nuse orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP16x16Sequence of SequenceTrait<FP16x16> {\n    fn sequence_construct(tensors: Array<Tensor<FP16x16>>) -> Array<Tensor<FP16x16>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP16x16>> {\n        functional::sequence_empty::sequence_empty::<FP16x16>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP16x16>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP16x16>>, position: Tensor<i32>) -> Tensor<FP16x16> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP16x16>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP16x16>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP16x16>>, tensor: @Tensor<FP16x16>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP16x16>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP16x16>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP16x16> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp16x16wide.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::FP16x16W;\nuse orion::operators::tensor::implementations::tensor_fp16x16wide::FP16x16WTensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP16x16WSequence of SequenceTrait<FP16x16W> {\n    fn sequence_construct(tensors: Array<Tensor<FP16x16W>>) -> Array<Tensor<FP16x16W>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP16x16W>> {\n        functional::sequence_empty::sequence_empty::<FP16x16W>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP16x16W>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP16x16W>>, position: Tensor<i32>) -> Tensor<FP16x16W> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP16x16W>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP16x16W>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP16x16W>>, tensor: @Tensor<FP16x16W>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP16x16W>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP16x16W>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp32x32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp32x32::core::FP32x32;\nuse orion::operators::tensor::implementations::tensor_fp32x32::FP32x32Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP32x32Sequence of SequenceTrait<FP32x32> {\n    fn sequence_construct(tensors: Array<Tensor<FP32x32>>) -> Array<Tensor<FP32x32>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP32x32>> {\n        functional::sequence_empty::sequence_empty::<FP32x32>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP32x32>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP32x32>>, position: Tensor<i32>) -> Tensor<FP32x32> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP32x32>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP32x32>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP32x32>>, tensor: @Tensor<FP32x32>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP32x32>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP32x32>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP32x32> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp64x64.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp64x64::core::FP64x64;\nuse orion::operators::tensor::implementations::tensor_fp64x64::FP64x64Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP64x64Sequence of SequenceTrait<FP64x64> {\n    fn sequence_construct(tensors: Array<Tensor<FP64x64>>) -> Array<Tensor<FP64x64>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP64x64>> {\n        functional::sequence_empty::sequence_empty::<FP64x64>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP64x64>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP64x64>>, position: Tensor<i32>) -> Tensor<FP64x64> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP64x64>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP64x64>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP64x64>>, tensor: @Tensor<FP64x64>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP64x64>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP64x64>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP64x64> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp8x23.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\nuse orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP8x23Sequence of SequenceTrait<FP8x23> {\n    fn sequence_construct(tensors: Array<Tensor<FP8x23>>) -> Array<Tensor<FP8x23>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP8x23>> {\n        functional::sequence_empty::sequence_empty::<FP8x23>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP8x23>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP8x23>>, position: Tensor<i32>) -> Tensor<FP8x23> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP8x23>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP8x23>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP8x23>>, tensor: @Tensor<FP8x23>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP8x23>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP8x23>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP8x23> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_fp8x23wide.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::FP8x23W;\nuse orion::operators::tensor::implementations::tensor_fp8x23wide::FP8x23WTensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl FP8x23WSequence of SequenceTrait<FP8x23W> {\n    fn sequence_construct(tensors: Array<Tensor<FP8x23W>>) -> Array<Tensor<FP8x23W>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<FP8x23W>> {\n        functional::sequence_empty::sequence_empty::<FP8x23W>()\n    }\n\n    fn sequence_length(self: Array<Tensor<FP8x23W>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<FP8x23W>>, position: Tensor<i32>) -> Tensor<FP8x23W> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<FP8x23W>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP8x23W>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<FP8x23W>>, tensor: @Tensor<FP8x23W>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<FP8x23W>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<FP8x23W>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_i32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl I32Sequence of SequenceTrait<i32> {\n    fn sequence_construct(tensors: Array<Tensor<i32>>) -> Array<Tensor<i32>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<i32>> {\n        functional::sequence_empty::sequence_empty::<i32>()\n    }\n\n    fn sequence_length(self: Array<Tensor<i32>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<i32>>, position: Tensor<i32>) -> Tensor<i32> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<i32>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<i32>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<i32>>, tensor: @Tensor<i32>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<i32>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<i32>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<i32> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_i8.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::operators::tensor::implementations::tensor_i8::I8Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl I8Sequence of SequenceTrait<i8> {\n    fn sequence_construct(tensors: Array<Tensor<i8>>) -> Array<Tensor<i8>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<i8>> {\n        functional::sequence_empty::sequence_empty::<i8>()\n    }\n\n    fn sequence_length(self: Array<Tensor<i8>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<i8>>, position: Tensor<i32>) -> Tensor<i8> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<i8>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<i8>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<i8>>, tensor: @Tensor<i8>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<i8>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<i8>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<i8> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/sequence/implementations/sequence_u32.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::operators::sequence::core::SequenceTrait;\nuse orion::operators::sequence::functional;\nuse orion::operators::tensor::implementations::tensor_u32::U32Tensor;\nuse orion::operators::tensor::implementations::tensor_i32::I32Tensor;\n\nimpl U32Sequence of SequenceTrait<u32> {\n    fn sequence_construct(tensors: Array<Tensor<u32>>) -> Array<Tensor<u32>> {\n        functional::sequence_construct::sequence_construct(tensors)\n    }\n\n    fn sequence_empty() -> Array<Tensor<u32>> {\n        functional::sequence_empty::sequence_empty::<u32>()\n    }\n\n    fn sequence_length(self: Array<Tensor<u32>>) -> Tensor<u32> {\n        functional::sequence_length::sequence_length(self)\n    }\n\n    fn sequence_at(sequence: Array<Tensor<u32>>, position: Tensor<i32>) -> Tensor<u32> {\n        functional::sequence_at::sequence_at(sequence, position)\n    }\n\n    fn sequence_erase(\n        sequence: Array<Tensor<u32>>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<u32>> {\n        functional::sequence_erase::sequence_erase(sequence, position)\n    }\n\n    fn sequence_insert(\n        self: Array<Tensor<u32>>, tensor: @Tensor<u32>, position: Option<Tensor<i32>>\n    ) -> Array<Tensor<u32>> {\n        functional::sequence_insert::sequence_insert(self, tensor, position)\n    }\n\n    fn concat_from_sequence(\n        sequence: Array<Tensor<u32>>, axis: i32, new_axis: Option<usize>\n    ) -> Tensor<u32> {\n        functional::concat_from_sequence::concat_from_sequence(sequence, axis, new_axis)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor.cairo",
        "content": "mod core;\nmod helpers;\nmod math;\nmod linalg;\nmod quantization;\nmod implementations;\nmod manipulation;\nmod ml;\n\nuse orion::operators::tensor::core::{Tensor, TensorSerde, TensorTrait};\n\nuse orion::operators::tensor::implementations::tensor_fp8x23::{\n    FP8x23Tensor, FP8x23TensorAdd, FP8x23TensorSub, FP8x23TensorMul, FP8x23TensorDiv,\n    FP8x23TensorPartialEq,\n};\n\nuse orion::operators::tensor::implementations::tensor_fp32x32::{\n    FP32x32Tensor, FP32x32TensorAdd, FP32x32TensorSub, FP32x32TensorMul, FP32x32TensorDiv,\n    FP32x32TensorPartialEq,\n};\n\nuse orion::operators::tensor::implementations::tensor_fp16x16::{\n    FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorSub, FP16x16TensorMul, FP16x16TensorDiv,\n    FP16x16TensorPartialEq,\n};\n\nuse orion::operators::tensor::implementations::tensor_i8::{\n    I8Tensor, I8TensorAdd, I8TensorSub, I8TensorMul, I8TensorDiv, I8TensorPartialEq,\n};\n\nuse orion::operators::tensor::implementations::tensor_i32::{\n    I32Tensor, I32TensorAdd, I32TensorSub, I32TensorMul, I32TensorDiv, I32TensorPartialEq,\n    TensorI8IntoTensorI32\n};\n\nuse orion::operators::tensor::implementations::tensor_u32::{\n    U32Tensor, U32TensorAdd, U32TensorSub, U32TensorMul, U32TensorDiv, U32TensorPartialEq\n};\n\nuse orion::operators::tensor::implementations::tensor_bool::{BoolTensor, BoolTensorPartialEq};\n\nuse orion::operators::tensor::implementations::tensor_complex64::{\n    Complex64Tensor, Complex64TensorAdd, Complex64TensorSub, Complex64TensorMul, Complex64TensorDiv,\n    Complex64TensorPartialEq,\n};\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/core.cairo",
        "content": "use alexandria_data_structures::array_ext::ArrayTraitExt;\nuse core::array::{ArrayTrait, SpanTrait};\nuse core::serde::Serde;\nuse core::option::OptionTrait;\n\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n//::resize::{MODE, NEAREST_MODE, KEEP_ASPECT_RATIO_POLICY, TRANSFORMATION_MODE};\n\nuse orion::operators::tensor::helpers::{len_from_shape, check_shape};\nuse orion::numbers::{NumberTrait, I32IntoU32, U32IntoI32};\n\n#[derive(Copy, Drop)]\nstruct Tensor<T> {\n    shape: Span<usize>,\n    data: Span<T>,\n}\n\n//Implement TensorSerde\nimpl TensorSerde<T, impl TSerde: Serde<T>, impl TDrop: Drop<T>> of Serde<Tensor<T>> {\n    fn serialize(self: @Tensor<T>, ref output: Array<felt252>) {\n        self.shape.serialize(ref output);\n        self.data.serialize(ref output);\n    }\n\n    fn deserialize(ref serialized: Span<felt252>) -> Option<Tensor<T>> {\n        let shape: Span<usize> = Serde::<Span<usize>>::deserialize(ref serialized)?;\n        let data: Span<T> = Serde::<Span<T>>::deserialize(ref serialized)?;\n\n        Option::Some(Tensor { shape, data })\n    }\n}\n\n/// Trait\n///\n/// new - Returns a new tensor with the given shape and data.\n/// reshape - Returns a new tensor with the specified target shape and the same data as the input tensor.\n/// flatten - Flattens the input tensor into a 2D tensor.\n/// constant_of_shape - Generate a tensor with given value and shape.\n/// transpose - Returns a new tensor with the axes rearranged according to the given permutation.\n/// at - Retrieves the value at the specified indices of a Tensor.\n/// ravel_index - Converts a multi-dimensional index to a one-dimensional index.\n/// unravel_index - Converts a one-dimensional index to a multi-dimensional index.\n/// equal - Check if two tensors are equal element-wise.\n/// greater - Check if each element of the first tensor is greater than the corresponding element of the second tensor.\n/// greater_equal - Check if each element of the first tensor is greater than or equal to the corresponding element of the second tensor.\n/// less - Check if each element of the first tensor is less than the corresponding element of the second tensor.\n/// less_equal - Check if each element of the first tensor is less than or equal to the corresponding element of the second tensor.\n/// or - Computes the logical OR of two tensors element-wise.\n/// xor - Computes the logical XOR of two tensors element-wise.\n/// stride - Computes the stride of each dimension in the tensor.\n/// onehot - Produces one-hot tensor based on input.\n/// max_in_tensor - Returns the maximum value in the tensor.\n/// min_in_tensor - Returns the minimum value in the tensor.\n/// min - Returns the minimum value in the tensor.\n/// max - Returns the maximum value in the tensor.\n/// reduce_sum - Reduces a tensor by summing its elements along a specified axis.\n/// reduce_prod - Reduces a tensor to its products along specified axis.\n/// argmax - Returns the index of the maximum value along the specified axis.\n/// argmin - Returns the index of the minimum value along the specified axis.\n/// cumsum - Performs cumulative sum of the input elements along the given axis.\n/// matmul - Performs matrix product of two tensors.\n/// exp - Computes the exponential of all elements of the input tensor.\n/// log - Computes the natural log of all elements of the input tensor.\n/// abs - Computes the absolute value of all elements in the input tensor.\n/// neg - Computes the negation of all elements in the input tensor.\n/// ceil - Rounds up the value of each element in the input tensor.\n/// sqrt - Computes the square root of all elements of the input tensor.\n/// sin - Computes the sine of all elements of the input tensor.\n/// cos - Computes the cosine of all elements of the input tensor.\n/// atan - Computes the arctangent (inverse of tangent) of all elements of the input tensor.\n/// asin - Computes the arcsine (inverse of sine) of all elements of the input tensor.\n/// acos - Computes the arccosine (inverse of cosine) of all elements of the input tensor.\n/// sinh - Computes the hyperbolic sine of all elements of the input tensor.\n/// tanh - Computes the hyperbolic tangent of all elements of the input tensor.\n/// cosh - Computes the hyperbolic cosine of all elements of the input tensor.\n/// asinh - Computes the inverse hyperbolic sine of all elements of the input tensor.\n/// acosh - Computes the inverse hyperbolic cosine of all elements of the input tensor.\n/// slice - Produces a slice of the input tensor along multiple axes. \n/// concat - Concatenate a list of tensors into a single tensor.\n/// quantize_linear - Quantizes a Tensor to i8 using linear quantization.\n/// dequantize_linear - Dequantizes an i8 Tensor using linear dequantization.\n/// qlinear_add - Performs the sum of two quantized i8 Tensors.\n/// qlinear_mul - Performs the element-wise multiplication of quantized Tensors.\n/// qlinear_matmul - Performs the product of two quantized i8 Tensors.\n/// qlinear_concat - Concatenate a list of tensors after dequantizing them with their respective scales and zero_points and returns the quantized result.\n/// qlinear_leakyrelu - Applies the Leaky Relu operator to a quantized Tensor\n/// gather - Gather entries of the axis dimension of data.\n/// nonzero - Produces indices of the elements that are non-zero (in row-major order - by dimension).\n/// squeeze - Removes dimensions of size 1 from the shape of a tensor.\n/// unsqueeze - Inserts single-dimensional entries to the shape of an input tensor.\n/// sign - Calculates the sign of the given input tensor element-wise.\n/// clip - Clip operator limits the given input within an interval.\n/// and - Computes the logical AND of two tensors element-wise. \n/// identity - Return a Tensor with the same shape and contents as input.\n/// where - Return elements chosen from x or y depending on condition.\n/// bitwise_and - Computes the bitwise AND of two tensors element-wise.\n/// bitwise_xor - Computes the bitwise XOR of two tensors element-wise.\n/// bitwise_or - Computes the bitwise OR of two tensors element-wise.\n/// resize - Resizes the input tensor.\n/// round - Computes the round value of all elements in the input tensor.\n/// reduce_l1 - Computes the L1 norm of the input tensor's elements along the provided axes.\n/// trilu - Returns the upper or lower triangular part of a tensor or a batch of 2D matrices.\n/// scatter - Produces a copy of input data, and updates value to values specified by updates at specific index positions specified by indices.\n/// reduce_sum_square - Computes the sum square of the input tensor's elements along the provided axes. \n/// reduce_l2 - Computes the L2 norm of the input tensor's elements along the provided axes.\n/// gather_elements - GatherElements is an indexing operation that produces its output by indexing into the input data tensor at index positions determined by elements of the indices tensor.\n/// reduce_min - Computes the min of the input tensor's elements along the provided axes.\n/// shrink \u2013 Shrinks the input tensor element-wise to the output tensor with the same datatype and shape based on a defined formula.\n/// reduce_mean - Computes the mean of the input tensor's elements along the provided axes.\n/// pow - Pow takes input data (Tensor) and exponent Tensor, and produces one output data (Tensor) where the function f(x) = x^exponent, is applied to the data tensor elementwise.\n/// binarizer - Maps the values of a tensor element-wise to 0 or 1 based on the comparison against a threshold value.\n/// array_feature_extractor - Selects elements of the input tensor based on the indices passed applied to the last tensor axis.\n/// reduce_min - Computes the min of the input tensor's elements along the provided axes.\n/// is_nan - Returns which elements of the input are NaN.\n/// is_inf - Maps infinity to true and other values to false.\n/// not - Computes the logical negation of all elements in the input tensor.\n/// gather_nd - Given data tensor of rank r >= 1, indices tensor of rank q >= 1, and batch_dims integer b, this operator gathers slices of data into an output tensor of rank q + r - indices_shape[-1] - 1 - b.\n/// reduce_log_sum - Computes the log sum of the input tensor's elements along the provided axes. \n/// erf - Computes the error function of the given input tensor element-wise.\n/// reduce_log_sum_exp - Computes the log sum of the exponentials of the input tensor's elements along the provided axes.\n/// layer_normalization - computes the layer normalization of the input tensor.\n/// split - Split a tensor into a list of tensors, along the specified \u2018axis\u2019. \n/// random_uniform_like - RandomUniformLike generates a tensor with random values using a uniform distribution, matching the shape of the input tensor.\n/// split_to_sequence - Split a tensor into a sequence of tensors, along the specified \u2018axis\u2019.\n/// range - Generate a tensor containing a sequence of numbers that begin at start and extends by increments of delta up to limit (exclusive).\n/// hann_window - Generates a Hann window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n/// hamming_window - Generates a Hamming window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n/// blackman_window - Generates a Blackman window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n/// reverse_sequence - Reverse batch of sequences having different lengths specified by sequence_lens.\n/// optional - Constructs an optional-type value containing either an empty optional of a certain type specified by the attribute, or a non-empty value containing the input element.\n/// dynamic_quantize_linear - Computes the Scale, Zero Point and FP32->8Bit conversion of FP32 Input data. \n/// scatter_nd - The output of the operation is produced by creating a copy of the input data, and then updating its value to values specified by updates at specific index positions specified by indices. Its output shape is the same as the shape of data\n/// label_encoder - Maps each element in the input tensor to another value.\ntrait TensorTrait<T> {\n    /// # tensor.new\n    ///\n    /// ```rust \n    ///    fn new(shape: Span<usize>, data: Span<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns a new tensor with the given shape and data.\n    /// \n    /// ## Args\n    /// \n    /// * `shape`(`Span<usize>`) - A span representing the shape of the tensor.\n    /// * `data` (`Span<T>`) - A span containing the array of elements.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shape and data length are incompatible.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance.\n    ///\n    /// ## Examples\n    /// \n    /// Let's create new u32 Tensors.\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{\n    ///     TensorTrait, // we import the trait\n    ///     Tensor, // we import the type\n    ///     U32Tensor // we import the implementation. \n    /// };\n    /// \n    /// // 1D TENSOR\n    /// fn tensor_1D() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::new(shape: array![3].span(), data: array![0, 1, 2].span());\n    /// \n    ///     return tensor;\n    /// }\n    /// \n    /// // 2D TENSOR\n    /// fn tensor_2D() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span());\n    /// \n    ///     return tensor;\n    /// }\n    /// \n    /// // 3D TENSOR\n    /// fn tensor_3D() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor;\n    /// }\n    /// ```\n    ///\n    fn new(shape: Span<usize>, data: Span<T>) -> Tensor<T>;\n    /// # tensor.at\n    ///\n    /// ```rust \n    ///    fn at(self: @Tensor<T>, indices: Span<usize>) -> T;\n    /// ```\n    ///\n    /// Retrieves the value at the specified indices of a Tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Span<usize>`) - The indices to access element of the Tensor.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the number of indices provided don't match the number of dimensions in the tensor.\n    ///\n    /// ## Returns\n    ///\n    /// The `T` value at the specified indices.\n    ///\n    /// # Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// \n    /// fn at_example() -> u32 {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `at` function as follows.\n    ///     return tensor.at(indices: array![0, 1, 1].span());\n    /// }\n    /// >>> 3\n    /// ```\n    /// \n    fn at(self: @Tensor<T>, indices: Span<usize>) -> T;\n    /// # tensor.min_in_tensor\n    ///\n    /// ```rust \n    ///    fn min_in_tensor(self: @Tensor<T>) -> T;\n    /// ```\n    ///\n    /// Returns the minimum value in the tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// The minimum `T` value in the tensor.\n    /// \n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn min_in_tensor_example() -> u32 {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![2, 2, 2].span(),\n    ///         data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `min_in_tensor` function as follows.\n    ///     return tensor.min_in_tensor();\n    /// }\n    /// >>> 0\n    /// ```\n    ///\n    fn min_in_tensor(self: @Tensor<T>) -> T;\n    fn add(lhs: Tensor<T>, rhs: Tensor<T>) -> Tensor<T>;\n    fn sub(lhs: Tensor<T>, rhs: Tensor<T>) -> Tensor<T>;\n    fn mul(lhs: Tensor<T>, rhs: Tensor<T>) -> Tensor<T>;\n    fn div(lhs: Tensor<T>, rhs: Tensor<T>) -> Tensor<T>;\n    /// # tensor.min\n    ///\n    /// ```rust \n    ///    fn min(tensors: Span<Tensor<T>>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns the element-wise minimum values from a list of input tensors\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(` Span<Tensor<T>>,`) - Array of the input tensors\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` containing the element-wise minimum values\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if tensor array is empty\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Process tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn min_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 3, 1, 2].span(),);\n    ///     let result = TensorTrait::min(tensors: array![tensor1, tensor2].span());\n    ///     return result;\n    /// }\n    /// >>> [0, 1, 1, 2]\n    ///\n    ///     result.shape\n    /// >>> (2, 2)\n    /// ```\n    /// \n    /// Case 2: Process tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn min_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![1, 2].span(), data: array![1, 4].span(),);\n    ///     let result = TensorTrait::min(tensors: array![tensor1, tensor2].span());\n    ///     return result;\n    /// }\n    /// >>> [0, 1, 1, 4]\n    ///\n    ///     result.shape\n    /// >>> (2, 2)\n    /// ```\n    ///\n    fn min(tensors: Span<Tensor<T>>) -> Tensor<T>;\n    /// # tensor.max_in_tensor\n    ///\n    /// ```rust \n    ///    fn max_in_tensor(self: @Tensor<T>) -> T;\n    /// ```\n    ///\n    /// Returns the maximum value in the tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// The maximum `T` value in the tensor.\n    ///\n    /// Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn max_in_tensor_example() -> u32 {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `max_in_tensor` function as follows.\n    ///     return tensor.max_in_tensor();\n    /// }\n    /// >>> 7\n    /// ```\n    /// \n    fn max_in_tensor(self: @Tensor<T>) -> T;\n    /// # tensor.max\n    ///\n    /// ```rust \n    ///    fn max(tensors: Span<Tensor<T>>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns the element-wise maximum values from a list of input tensors\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(` Span<Tensor<T>>,`) - Array of the input tensors\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` containing the element-wise maximum values\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if tensor array is empty\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Process tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn max_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 3, 1, 2].span(),);\n    ///     let result = TensorTrait::max(tensors: array![tensor1, tensor2].span());\n    ///     return result;\n    /// }\n    /// >>> [0, 3, 2, 3]\n    ///\n    ///     result.shape\n    /// >>> (2, 2)\n    /// ```\n    /// \n    /// Case 2: Process tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn max_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![1, 2].span(), data: array![1, 4].span(),);\n    ///     let result = TensorTrait::max(tensors: array![tensor1, tensor2].span());\n    ///     return result;\n    /// }\n    /// >>> [1, 4, 2, 4]\n    ///\n    ///     result.shape\n    /// >>> (2, 2)\n    /// ```\n    ///\n    fn max(tensors: Span<Tensor<T>>) -> Tensor<T>;\n    /// # tensor.stride\n    ///\n    /// ```rust \n    ///    fn stride(self: @Tensor<T>) -> Span<usize>;\n    /// ```\n    ///\n    /// Computes the stride of each dimension in the tensor.\n    ///\n    /// ## Args\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A span of usize representing the stride for each dimension of the tensor.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn stride_example() -> Span<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `stride` function as follows.\n    ///     return tensor.stride();\n    /// }\n    /// >>> [4,2,1]\n    /// ```\n    ///\n    fn stride(self: @Tensor<T>) -> Span<usize>;\n    /// # tensor.ravel_index\n    ///\n    /// ```rust \n    ///     fn ravel_index(self: @Tensor<T>, indices: Span<usize>) -> usize;\n    /// ```\n    ///\n    /// Converts a multi-dimensional index to a one-dimensional index.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Span<usize>`) - The indices of the Tensor to ravel.\n    ///\n    /// ## Panics \n    ///\n    /// * Panics if the indices are out of bounds of the Tensor shape.\n    ///\n    /// ## Returns\n    /// \n    /// The index corresponding to the given indices.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn ravel_index_example() -> usize {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `ravel_index` function as follows.\n    ///     return tensor.ravel_index(indices: array![1, 3, 0].span());\n    /// }\n    /// >>> 10 \n    /// // This means that the value of indices [1,3,0] \n    /// // of a multidimensional array can be found at index 10 of Tensor.data.\n    /// ```\n    ///    \n    fn ravel_index(self: @Tensor<T>, indices: Span<usize>) -> usize;\n    /// # tensor.unravel_index\n    ///\n    /// ```rust \n    ///    fn unravel_index(self: @Tensor<T>, index: usize) -> Span<usize>;\n    /// ```\n    ///\n    /// Converts a one-dimensional index to a multi-dimensional index.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Span<usize>`) - The index to unravel.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the index is out of bounds of the Tensor shape.\n    ///\n    /// ## Returns\n    ///\n    /// The unraveled indices corresponding to the given index.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn unravel_index_example() -> Span<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `unravel_index` function as follows.\n    ///     return tensor.unravel_index(3);\n    /// }\n    /// >>> [0,1,1] \n    /// // This means that the value of index 3 of Tensor.data\n    /// // can be found at indices [0,1,1] in multidimensional representation.\n    /// ```\n    ///\n    fn unravel_index(self: @Tensor<T>, index: usize) -> Span<usize>;\n    /// # tensor.reshape\n    ///\n    /// ```rust \n    ///    fn reshape(self: @Tensor<T>, target_shape: Span<i32>, allowzero: bool) -> Tensor<T>;\n    /// ```\n    ///\n    /// Reshape the input tensor similar to numpy.reshape. First input is the data tensor, second \n    /// input is a shape tensor which specifies the output shape. It outputs the reshaped tensor. \n    /// At most one dimension of the new shape can be -1. In this case, the value is inferred from \n    /// the size of the tensor and the remaining dimensions. A dimension could also be 0, in which case \n    /// the actual dimension value is unchanged (i.e. taken from the input tensor). If 'allowzero' is set,\n    /// and the new shape includes 0, the dimension will be set explicitly to zero (i.e. not taken from input tensor)\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `target_shape`(Span<i32>) - A span containing the target shape of the tensor.\n    /// * `allowzero`(`bool`) - Indicates that if any value in the 'shape' input is set to zero, the zero value is honored, similar to NumPy.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the target shape is incompatible with the input tensor's data.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the specified target shape and the same data.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reshape_tensor_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reshape` function as follows.\n    ///     return tensor.reshape(target_shape: array![2, 4].span(), false);\n    /// }\n    /// >>> [[0,1,2,3], [4,5,6,7]]\n    /// ```\n    ///\n    fn reshape(self: @Tensor<T>, target_shape: Span<i32>, allowzero: bool) -> Tensor<T>;\n    /// # tensor.transpose\n    ///\n    /// ```rust \n    ///    fn transpose(self: @Tensor<T>, axes: Span<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns a new tensor with the axes rearranged according to the given permutation.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axes`(`Span<usize>`) - The usize elements representing the axes to be transposed.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the length of the axes array is not equal to the rank of the input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` instance with the axes reordered according to the given permutation.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn transpose_tensor_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `transpose` function as follows.\n    ///     return tensor.transpose(axes: array![1, 2, 0].span());\n    /// }\n    /// >>> [[[0,4],[1,5]],[[2,6],[3,7]]]\n    /// ```\n    ///\n    fn transpose(self: @Tensor<T>, axes: Span<usize>) -> Tensor<T>;\n    /// ## tensor.reduce_sum\n    ///\n    /// ```rust \n    ///    fn reduce_sum(self: @Tensor<T>, axes: Option<Span<i32>>, keepdims: Option<bool>, noop_with_empty_axes: Option<bool>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Reduces a tensor by summing its elements along a specified axis.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axes`(`Option<Span<i32>>`) - Optional input list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor if 'noop_with_empty_axes' is false, else act as an Identity op when 'noop_with_empty_axes' is true.\n    /// * `keepdims`(`Option<bool>`) - Keep the reduced dimension or not, default 1 means keep reduced dimension.\n    /// * `noop_with_empty_axes`(`Option<bool>`) - Defines behavior if 'axes' is empty. Default behavior with 'false' is to reduce all axes. When axes is empty and this attribute is set to true, input tensor will not be reduced,and the output tensor would be equivalent to input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Reduced output tensor.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reduce_sum_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reduce_sum` function as follows.\n    ///     return tensor.reduce_sum(axes: Option::None, keepdims: false);\n    /// }\n    /// >>> [[4,6],[8,10]]\n    /// ```\n    ///\n    fn reduce_sum(\n        self: @Tensor<T>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<T>; \n    /// # tensor.argmax\n    ///\n    /// ```rust \n    ///    fn argmax(self: @Tensor<T>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>) -> Tensor<i32>;\n    /// ```\n    ///\n    /// Returns the index of the maximum value along the specified axis.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`i32`) - The axis along which to compute the argmax.\n    /// * `keepdims`(`Option<bool>`) - If true, retains reduced dimensions with length 1. Defaults to true.\n    /// * `select_last_index`(`Option<bool>`) - If true, the index of the last occurrence of the maximum value is returned. Defaults to false.   \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` instance containing the indices of the maximum values along the specified axis.\n    ///\n    /// ## Examples\n    /// \n    /// Case 1: argmax with default parameters\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmax_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmax` function as follows.\n    ///     return tensor.argmax(axis: 2, keepdims: Option::None(()), select_last_index: Option::None(()));\n    /// }\n    /// >>> [[[1,1],[0,0]]]\n    /// ```\n    /// Case 2: argmax with keepdims set to false\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmax_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmax` function as follows.\n    ///     return tensor\n    ///         .argmax(axis: 2, keepdims: Option::Some(false), select_last_index: Option::None(()));\n    /// }\n    /// >>> [[1,1],[0,0]]\n    /// ```\n    ///\n    /// Case 3: argmax with select_last_index set to true\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmax_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmax` function as follows.\n    ///     return tensor\n    ///         .argmax(axis: 2, keepdims: Option::None(()), select_last_index: Option::Some(true));\n    /// }\n    /// >>> [[[1,1],[1,1]]]\n    /// ```\n    ///\n    fn argmax(\n        self: @Tensor<T>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32>;\n    /// # tensor.argmin\n    ///\n    /// ```rust \n    ///    fn argmin(self: @Tensor<T>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Returns the index of the minimum value along the specified axis.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The axis along which to compute the argmin.\n    /// * `keepdims`(`Option<bool>`) - If true, retains reduced dimensions with length 1. Defaults to true.\n    /// * `select_last_index`(`Option<bool>`) - If true, the index of the last occurrence of the minimum value is returned. Defaults to false.   \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` instance containing the indices of the minimum values along the specified axis.\n    ///\n    /// ## Examples\n    /// \n    /// Case 1: argmin with default parameters\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmin_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmin` function as follows.\n    ///     return tensor.argmin(axis: 2, keepdims: Option::None(()), select_last_index: Option::None(()));\n    /// }\n    /// >>> [[[0,0],[0,0]]]\n    ///\n    /// ```\n    /// Case 2: argmin with keepdims set to false\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmin_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmin` function as follows.\n    ///     return tensor\n    ///         .argmin(axis: 2, keepdims: Option::Some(false), select_last_index: Option::None(()));\n    /// }\n    /// >>> [[0,0],[0,0]]\n    /// ```\n    ///\n    /// Case 3: argmin with select_last_index set to true\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn argmin_example() -> Tensor<usize> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 4, 5, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `argmin` function as follows.\n    ///     return tensor\n    ///         .argmin(axis: 2, keepdims: Option::None(()), select_last_index: Option::Some(true));\n    /// }\n    /// >>> [[[0,0],[1,1]]]\n    /// ```\n    ///\n    fn argmin(\n        self: @Tensor<T>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize>;\n    /// # tensor.matmul\n    ///\n    /// ```rust \n    ///    fn matmul(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Performs matrix product of two tensors.\n    /// The behavior depends on the dimensionality of the tensors as follows:\n    /// * If both tensors are 1-dimensional, the dot product is returned.\n    /// * If both arguments are 2-dimensional, the matrix-matrix product is returned.\n    /// * If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed.\n    /// * If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - the first tensor to be multiplied\n    /// * `other`(`@Tensor<T>`) - the second tensor to be multiplied\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the dimension of the tensors is higher than two.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` resulting from the matrix multiplication.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Dot product of two vectors (1D \\* 1D)\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn dot_product_example() -> Tensor<u32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `matmul` function as follows.\n    ///     return tensor_1.matmul(@tensor_2);\n    /// }\n    /// >>> [5]\n    /// ```\n    /// \n    /// Case 2: Matrix multiplication (2D \\* 2D)\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn matrix_mul_example() -> Tensor<u32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), data: array![244, 99, 109, 162].span()\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), data: array![151, 68, 121, 170].span()\n    ///     );\n    /// \n    ///     // We can call `matmul` function as follows.\n    ///     return tensor_1.matmul(@tensor_2);\n    /// }\n    /// >>> [[48823, 33422],[36061, 34952]]\n    /// ```\n    /// \n    /// Case 3: Matrix-Vector multiplication (2D x 1D)\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn matrix_vec_mul_example() -> Tensor<u32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `matmul` function as follows.\n    ///     return tensor_1.matmul(@tensor_2);\n    /// }\n    /// >>> [5,14,23]\n    /// ```\n    ///\n    fn matmul(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.exp\n    ///\n    /// ```rust \n    ///     fn exp(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the exponential of all elements of the input tensor.\n    /// $$\n    /// y_i=e^{x_i}\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the exponential of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn exp_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(), \n    ///         data: array![\n    ///                 FixedTrait::new_unscaled(0, false), \n    ///                 FixedTrait::new_unscaled(1, false), \n    ///                 FixedTrait::new_unscaled(2, false), \n    ///                 FixedTrait::new_unscaled(3, false), \n    ///             ]\n    ///     );\n    /// \n    ///     // We can call `exp` function as follows.\n    ///     return tensor.exp();\n    /// }\n    /// >>> [[8388608,22802594],[61983844,168489688]]\n    /// // The fixed point representation of\n    /// // [[1, 2.718281],[7.38905, 20.085536]]\n    /// ```\n    ///\n    fn exp(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.log\n    ///\n    /// ```rust \n    ///     fn log(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the natural log of all elements of the input tensor.\n    /// $$\n    /// y_i=log({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the natural log of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn log_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(), \n    ///         data: array![\n    ///                 FixedTrait::new_unscaled(0, false), \n    ///                 FixedTrait::new_unscaled(1, false), \n    ///                 FixedTrait::new_unscaled(2, false), \n    ///                 FixedTrait::new_unscaled(100, false), \n    ///             ]\n    ///     );\n    /// \n    ///     // We can call `log` function as follows.\n    ///     return tensor.log();\n    /// }\n    /// >>> [[0, 5814538, 9215825, 38630966]]\n    /// // The fixed point representation of\n    /// /// [[0, 0.693147, 1.098612, 4.605170]]\n    /// ```\n    ///\n    fn log(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.equal\n    ///\n    /// ```rust\n    ///     fn equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Check if two tensors are equal element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be equated\n    /// * `other`(`@Tensor<T>`) - The second tensor to be equated\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<usize>` of booleans (1 if equal, 0 otherwise) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn eq_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `equal` function as follows.\n    ///     return tensor_1.equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,1,1,0,0,0]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn eq_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `equal` function as follows.\n    ///     return tensor_1.equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,0,0,0,0,0,0]\n    /// ```\n    ///\n    fn equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// #tensor.greater\n    ///\n    /// ```rust\n    ///     fn greater(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Check if each element of the first tensor is greater than the corresponding element of the second tensor.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<usize>` of booleans (0 or 1) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn greater_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `greater` function as follows.\n    ///     return tensor_1.greater(@tensor_2);\n    /// }\n    /// >>> [0,0,0,0,0,0,0,1,1]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn greater_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `greater` function as follows.\n    ///     return tensor_1.greater(@tensor_2);\n    /// }\n    /// >>> [0,0,0,1,1,1,1,1,1]\n    /// ```\n    ///\n    fn greater(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// #tensor.greater_equal\n    ///\n    /// ```rust\n    ///     fn greater_equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Check if each element of the first tensor is greater than or equal to the corresponding element of the second tensor.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<usize>` of booleans (0 or 1) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn greater_equal_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `greater_equal` function as follows.\n    ///     return tensor_1.greater_equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,1,1,1,0,1,1]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn greater_equal_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `greater_equal` function as follows.\n    ///     return tensor_1.greater_equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,1,1,1,0,0,0]\n    /// ```\n    ///\n    fn greater_equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// #tensor.less\n    ///\n    /// ```rust\n    ///     fn less(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<i32>;\n    /// ```\n    ///\n    /// Check if each element of the first tensor is less than the corresponding element of the second tensor.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<bool>` of booleans with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn less_example() -> Tensor<i32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `less` function as follows.\n    ///     return tensor_1.less(@tensor_2);\n    /// }\n    /// >>> [0,0,0,0,0,0,1,0,0]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn less_example() -> Tensor<i32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `less` function as follows.\n    ///     return tensor_1.less(@tensor_2);\n    /// }\n    /// >>> [0,0,0,0,0,0,0,1,1]\n    /// ```\n    ///\n    fn less(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<i32>;\n    /// #tensor.less_equal\n    ///\n    /// ```rust\n    ///     fn less_equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<i32>;\n    /// ```\n    ///\n    /// Check if each element of the first tensor is less than or equal to the corresponding element of the second tensor.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<i32>` of booleans (0 or 1) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn less_equal_example() -> Tensor<i32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     // We can call `less_equal` function as follows.\n    ///     return tensor_1.less_equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,1,1,1,1,0,0]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn less_equal_example() -> Tensor<i32> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(shape: array![3].span(), data: array![0, 1, 2].span(),);\n    /// \n    ///     // We can call `less_equal` function as follows.\n    ///     return tensor_1.less_equal(@tensor_2);\n    /// }\n    /// >>> [1,1,1,0,0,0,1,1,1]\n    /// ```\n    ///\n    fn less_equal(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<i32>;\n    /// #tensor.abs\n    ///\n    /// ```rust\n    ///     fn abs(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the absolute value of all elements in the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the absolute value of all elements in the input tensor.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\n    /// \n    /// fn abs_example() -> Tensor<i32> {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             -1, -2, 3\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.abs();\n    /// }\n    /// >>> [1, 2, 3]\n    /// ```\n    ///\n    fn abs(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.neg\n    ///\n    /// ```rust\n    ///     fn neg(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the negation of all elements in the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the negation of all elements in the input tensor.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\n    /// \n    /// fn neg_example() -> Tensor<i32> {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             -1, -2, 3\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.neg();\n    /// }\n    /// >>> [1, 2, -3]\n    /// ```\n    ///\n    fn neg(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.ceil\n    ///\n    /// ```rust\n    ///     fn ceil(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Rounds up the value of each element in the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the rounded up value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn ceil_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new(29998, false), // 0.003576\n    ///             FixedTrait::new(100663252, false), // 11.9999947548\n    ///             FixedTrait::new(100663252, true) // -11.9999947548\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.ceil();\n    /// }\n    /// >>> [1,12,-11]\n    /// ```\n    ///\n    fn ceil(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.sin\n    ///\n    /// ```rust\n    ///     fn sin(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the sine of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the sine value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn sin_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.sin();\n    /// }\n    /// >>> [0,7058770,7627740]\n    /// // The fixed point representation of\n    /// // [0,0.8414...,0.9092...]\n    /// ```\n    ///\n    fn sin(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.cos\n    ///\n    /// ```rust\n    ///     fn cos(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the cosine of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the cosine value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn cos_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.cos();\n    /// }\n    /// >>> [8388608,4532384,-3490893]\n    /// // The fixed point representation of\n    /// // [1, 0.5403...,-0.4161]\n    /// ```\n    ///\n    fn cos(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.cumsum\n    ///\n    /// ```rust \n    ///    fn cumsum(self: @Tensor<T>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Performs cumulative sum of the input elements along the given axis.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The axis along which to compute the cumulative sum.\n    /// * `exclusive`(`Option<bool>`) - By default, it will do the sum inclusively meaning the first element is copied as is.\n    /// * `reverse`(`Option<bool>`) - If true, the cumulative sum is performed in the opposite direction. Defaults to false.   \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` instance containing the cumulative sum of the input tensor's elements along the given axis.\n    ///\n    /// ## Examples\n    /// \n    /// Case 1: cumsum with default parameters\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn cumsum_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor.cumsum(axis: 2, exclusive: Option::None(()), reverse: Option::None(()));\n    /// }\n    /// >>> [[[0,1],[2,5]],[[4,9],[6,13]]]\n    /// ```\n    ///\n    /// Case 2: cumsum with exclusive = true\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn cumsum_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor.cumsum(axis: 2, exclusive: Option::Some(true), reverse: Option::None(()));\n    /// }\n    /// >>> [[[0,0],[0,2]],[[0,4],[0,6]]]\n    /// ```\n    ///\n    /// Case 3: cumsum with exclusive = true and reverse = true\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn cumsum_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor.cumsum(axis: 2, exclusive: Option::Some(true), reverse: Option::Some(true));\n    /// }\n    /// >>> [[[1,0],[3,0]],[[5,0],[7,0]]]\n    /// ```\n    ///\n    fn cumsum(\n        self: @Tensor<T>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<T>;\n    /// # tensor.flatten\n    ///\n    /// ```rust \n    ///    fn flatten(self: @Tensor<T>, axis: usize) -> Tensor<T>;\n    /// ```\n    ///\n    /// Flattens the input tensor into a 2D tensor. \n    /// If input tensor has shape (1, 2, 3,...n) then the output will have shape\n    /// (1 * 2 * 3 * ... (axis-1), axis * (axis+1) * ... n).\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - Indicate up to which input dimensions (exclusive) should be flattened. \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` instance containing the flattened version of the input tensor.\n    ///\n    /// ## Examples\n    /// \n    /// Case 1: flatten with axis 0\n    ///\n    /// ```rust\n    /// fn flatten_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(),\n    ///         data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///         extra: Option::None(())\n    ///     );\n    /// \n    ///     return tensor.flatten(0); // equivalent to tensor.reshape(1,8)\n    /// }\n    /// >>> [[0,1,2,5,4,9,6,13]]\n    /// ```\n    /// \n    /// Case 2: flatten with axis 1\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn flatten_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor.flatten(1); // equivalent to tensor.reshape(2,4)\n    /// }\n    /// >>> [[0,1,2,3],[4,5,6,7]]\n    /// ```\n    ///\n    /// Case 3: flatten with axis 2\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn flatten_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     return tensor.flatten(2); // equivalent to tensor.reshape(4,2)\n    /// }\n    /// >>> [[0,1],[2,3],[4,5],[6,7]]\n    /// ```\n    ///\n    fn flatten(self: @Tensor<T>, axis: usize) -> Tensor<T>;\n    /// # tensor.sinh\n    ///\n    /// ```rust \n    ///     fn sinh(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the hyperbolic sine of all elements of the input tensor.\n    /// $$\n    /// y_i=sinh({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the hyperbolic sine of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn sinh_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.sinh();\n    /// }\n    /// >>> [[0,9858303],[30424311,84036026]]\n    /// // The fixed point representation of\n    /// // [[0, 1.175201],[3.62686, 10.0178749]]\n    /// ```\n    ///\n    fn sinh(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.tanh\n    ///\n    /// ```rust \n    ///     fn tanh(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the hyperbolic tangent of all elements of the input tensor.\n    /// $$\n    /// y_i=tanh({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the hyperbolic tangent of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn tanh_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.tanh();\n    /// }\n    /// >>> [[0,6388715],[8086850,8347125]]\n    /// // The fixed point representation of\n    /// // [[0, 0.761594],[0.96403, 0.9951]]\n    /// ```\n    ///\n    fn tanh(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.cosh\n    ///\n    /// ```rust \n    ///     fn cosh(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the hyperbolic cosine of all elements of the input tensor.\n    /// $$\n    /// y_i=cosh({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the hyperblic cosine of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn cosh_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.cosh();\n    /// }\n    /// >>> [[8388608,12944299],[31559585,84453670]]\n    /// // The fixed point representation of\n    /// // [[, 1.54308],[3.762196, 10.067662]]\n    /// ```\n    ///\n    fn cosh(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.asinh\n    ///\n    /// ```rust \n    ///     fn asinh(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the inverse hyperbolic sine of all elements of the input tensor.\n    /// $$\n    /// y_i=asinh({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the hyperblic sine of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn asinh_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.asinh();\n    /// }\n    /// >>> [[0,7393498],[12110093,15254235]]\n    /// // The fixed point representation of\n    /// // [[0, 0.8814],[1.44364, 1.8185]]\n    /// ```\n    ///\n    fn asinh(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.acosh\n    ///\n    /// ```rust \n    ///     fn acosh(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the inverse hyperbolic cosine of all elements of the input tensor.\n    /// $$\n    /// y_i=acosh({x_i})\n    /// $$\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// Returns a new tensor in `T` with the hyperblic cosine of the elements of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn acosh_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false),\n    ///             FixedTrait::new_unscaled(4, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.acosh();\n    /// }\n    /// >>> [[0,11047444],[14786996,17309365]]\n    /// // The fixed point representation of\n    /// // [[0, 1.31696],[1.76275, 2.06344]]\n    /// ```\n    ///\n    fn acosh(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.atan\n    ///\n    /// ```rust\n    ///     fn atan(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the arctangent (inverse of tangent) of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the arctangent (inverse of tangent) value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn atan_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.atan();\n    /// }\n    /// >>> [0,6588397,9287028]\n    /// // The fixed point representation of\n    /// // [0,0.7853...,1.1071...]\n    /// ```\n    ///    \n    fn atan(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.asin\n    ///\n    /// ```rust\n    ///     fn asin(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the arcsine (inverse of sine) of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the arcsine value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn asin_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2].span(),\n    ///         data: array![FixedTrait::new_unscaled(0, false), FixedTrait::new_unscaled(1, false),]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.asin();\n    /// }\n    /// >>> [0, 13176794]\n    /// // The fixed point representation of\n    /// // [0, 1.5707...]\n    /// ```\n    ///\n    fn asin(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.or\n    ///\n    /// ```rust\n    ///     fn or(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Computes the logical OR of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<usize>` of booleans (0 or 1) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn or_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     return tensor_1.or(@tensor_2);\n    /// }\n    /// >>> [0,1,1,1,1,1,1,1,1]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn or_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![1, 3].span(), data: array![0, 1, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.or(@tensor_2);\n    /// }\n    /// >>> [0,1,1,1,1,1,1,1,1]\n    /// ```\n    ///\n    fn or(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// #tensor.xor\n    ///\n    /// ```rust\n    ///     fn xor(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Computes the logical XOR of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<usize>` of booleans (0 or 1) with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn xor_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 9, 1, 5].span(),\n    ///     );\n    /// \n    ///     return tensor_1.xor(@tensor_2);\n    /// }\n    /// >>> [0,0,0,0,0,0,0,0,0]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn xor_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![1, 3].span(), data: array![0, 1, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.xor(@tensor_2);\n    /// }\n    /// >>> [0,0,0,1,0,0,1,0,0]\n    /// ```\n    ///\n    fn xor(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// #tensor.acos\n    ///\n    /// ```rust\n    ///     fn acos(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the arccosine (inverse of cosine) of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the arccosine value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn acos_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2].span(),\n    ///         data: array![FixedTrait::new_unscaled(0, false), FixedTrait::new_unscaled(1, false),]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.acos();\n    /// }\n    /// >>> [13176794, 0]\n    /// // The fixed point representation of\n    /// // [1.5707..., 0]\n    /// ```\n    ///\n    fn acos(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.onehot\n    ///\n    /// ```rust \n    ///    fn onehot(self: @Tensor<T>, depth: usize, axis: Option<usize>, values: Span<usize>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Produces one-hot tensor based on input.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `depth`(`usize`) - Scalar or Rank 1 tensor containing exactly one element, specifying the number of classes in one-hot tensor.\n    /// * `axis`(`Option<bool>`) - Axis along which one-hot representation in added. Default: axis=-1.\n    /// * `values`(`Span<usize>`) - Rank 1 tensor containing exactly two elements, in the format [off_value, on_value]   \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if values is not equal to 2.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` one-hot encode of the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FP8x23, FixedTrait};\n    /// \n    /// fn onehot_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2,2].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///             FixedTrait::new_unscaled(3, false),\n    ///         ]\n    ///             .span(),\n    ///     );    \n    /// \n    ///     return tensor.onehot(depth: 3, axis: Option::None(()), values: array![0, 1].span());\n    /// }\n    /// >>> [[1. 0. 0.]\n    ///      [0. 1. 0.]\n    ///      [0. 0. 1.]]\n    /// ```\n    ///\n    fn onehot(\n        self: @Tensor<T>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<T>;\n    /// #tensor.sqrt\n    ///\n    /// ```rust\n    ///     fn sqrt(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the square root of all elements of the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the arctangent (inverse of tangent) value of all elements in the input tensor.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn sqrt_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(0, false),\n    ///             FixedTrait::new_unscaled(1, false),\n    ///             FixedTrait::new_unscaled(2, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.sqrt();\n    /// }\n    /// >>> [0,8388608,11863169]\n    /// // The fixed point representation of\n    /// // [0,1,1.4142...]\n    /// ```\n    ///    \n    fn sqrt(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.concat\n    ///\n    /// ```rust \n    ///    fn concat(tensors: Span<Tensor<T>>, axis: usize,  ) -> Tensor<T>;\n    /// ```\n    ///\n    /// Concatenate a list of tensors into a single tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(` Span<Tensor<T>>,`) - Array of the input tensors.\n    /// * `axis`(`usize`) -  Axis to concat on.\n    ///\n    /// ## Panics\n    ///\n    /// * Panic if tensor length is not greater than 1.\n    /// * Panics if dimension is not greater than axis.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` concatenated tensor of the input tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn concat_example() -> Tensor<u32> {\n    ///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n    ///     let result = TensorTrait::concat(tensors: array![tensor1, tensor2].span(), axis: 0);\n    ///     return result;\n    /// }\n    /// >>> [[0. 1.]\n    ///      [2. 3.],\n    ///      [0. 1.]\n    ///      [2. 3.]]\n    ///\n    ///     result.shape\n    /// >>> (4, 2)\n    ///\n    ///    let result = TensorTrait::concat(tensors: array![tensor1, tensor2].span(), axis: 1);\n    ///    return result;\n    /// }\n    /// >>> [[0. 1., 0., 1.]\n    ///      [2. 3., 2., 3.]]\n    ///\n    ///     result.shape\n    /// >>> (2, 4 ) \n    /// ```\n    ///\n    fn concat(tensors: Span<Tensor<T>>, axis: usize,) -> Tensor<T>;\n    /// # tensor.quantize_linear\n    /// \n    /// ```rust\n    /// fn quantize_linear(self: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>) -> Tensor::<Q>;\n    /// ```\n    /// \n    /// Quantizes a Tensor using linear quantization.\n    ///\n    /// The linear quantization operator. It consumes a high precision tensor, a scale, and a zero point \n    /// to compute the low precision / quantized tensor. The scale factor and zero point must have same shape, \n    /// and can be either a scalar for per-tensor / per layer quantization, or a 1-D tensor for per-axis quantization.\n    /// The quantization formula is `y = saturate ((x / y_scale) + y_zero_point)`. For saturation, it saturates to `[-128, 127]`. \n    /// For (x / y_scale), it's rounding to the nearest even.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `y_scale`(`@Tensor<T>`) - Scale for doing quantization to get `y`.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for doing quantization to get `y`.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<Q>` with the same shape as the input tensor, containing the quantized values.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor};\n    /// \n    /// fn quantize_linear_example() -> Tensor<i8> {\n    ///     // We instantiate a 1D Tensor here.\n    ///     let x = TensorTrait::<i32>::new(\n    ///         shape: array![6].span(),\n    ///         data: array![0, 2, 3, 1, -254,-1000].span(),\n    ///     );\n    /// \n    ///     // We instantiate the y_scale here.\n    ///     let y_scale = TensorTrait::<i32>::new(\n    ///         shape: array![1].span(), data: array![2].span(),\n    ///     );\n    /// \n    ///     // We instantiate the y_zero_point here.\n    ///     let y_zero_point = TensorTrait::<i32>::new(\n    ///         shape: array![1].span(), data: array![1].span(),\n    ///     );\n    /// \n    ///     return x.quantize_linear(@y_scale, @y_zero_point);\n    /// }\n    /// >>> [1, 2, 2, 127, -126, -128]\n    /// ```\n    ///\n    fn quantize_linear(\n        self: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>\n    ) -> Tensor::<i8>;\n    /// # tensor.dequantize_linear\n    /// \n    /// ```rust\n    /// fn dequantize_linear(self: @Tensor<Q>, x_scale: @Tensor<T>, x_zero_point: @Tensor<T>) -> Tensor::<T>;\n    /// ```\n    /// \n    /// Dequantizes a Tensor using linear dequantization.\n    ///\n    /// The linear dequantization operator. It consumes a quantized tensor, a scale, and a zero point to compute \n    /// the full precision tensor. The dequantization formula is y = (x - x_zero_point) * x_scale. x_scale and \n    /// x_zero_point must have same shape, and can be either a scalar for per-tensor / per layer quantization, \n    /// or a 1-D tensor for per-axis quantization.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<Q>`) - The input tensor.\n    /// * `x_scale`(`@Tensor<T>`) - Scale for input `x`.\n    /// * `x_zero_point`(`@Tensor<T>`) - Zero point for input `x`.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the same shape as the input tensor, containing the dequantized values.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    ///  use core::array::{ArrayTrait, SpanTrait};\n    ///  \n    ///  use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor};\n    ///  \n    ///  fn dequantize_linear_example() -> Tensor<i32> {\n    ///      // We instantiate a 1D Tensor here.\n    ///      let x = TensorTrait::<i8>::new(\n    ///          shape: array![4].span(),\n    ///          data: array![0, 3, 125, 127].span(),\n    ///      );\n    ///  \n    ///      // We instantiate the x_scale here.\n    ///      let x_scale = TensorTrait::<i32>::new(\n    ///          shape: array![1].span(), data: array![2].span(),\n    ///      );\n    ///  \n    ///      // We instantiate the x_zero_point here.\n    ///      let x_zero_point = TensorTrait::<i32>::new(\n    ///          shape: array![1].span(), data: array![0].span(),\n    ///      );\n    ///  \n    ///      return x.dequantize_linear(@x_scale, @x_zero_point);\n    ///  }\n    /// >>> [0, 6, 250, 254]\n    /// ```\n    ///\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<T>, x_zero_point: @Tensor<T>\n    ) -> Tensor::<T>;\n    /// # tensor.qlinear_add\n    ///\n    /// ```rust\n    ///     fn qlinear_add(self: @Tensor<i8>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, b: @Tensor<i8>, b_scale: @Tensor<T>, b_zero_point: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>) -> Tensor::<i8>;\n    /// ```\n    /// \n    /// Performs the sum of quantized Tensors\n    ///\n    /// It consumes two quantized input tensors, their scales and zero points, scale and zero point of output, and computes the quantized output. \n    /// The quantization formula is y = saturate((x / y_scale) + y_zero_point).\n    /// It performs the addition of the two vectors once dequantized, then return the quantization of the result of the addition.\n    /// The broadcasting is supported\n    /// Scale and zero point must have same shape and the same type. They must be either scalar (per tensor) or N-D tensor (per row for 'a' and per column for 'b'). \n    /// Scalar refers to per tensor quantization whereas N-D refers to per row or per column quantization.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<i8>`) - The first tensor to be additionned (a).\n    /// * `a_scale`(`@Tensor<T>`) - Scale for input `a`.\n    /// * `a_zero_point`(`@Tensor<T>`) - Zero point for input `a`.\n    /// * `b`(`@Tensor<i8>`) - The second tensor to be additionned\n    /// * `b_scale`(`@Tensor<T>`) - Scale for input `b`.\n    /// * `b_zero_point`(`@Tensor<T>`) - Zero point for input `b`.    \n    /// * `y_scale`(`@Tensor<T>`) - Scale for outut.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for output.   \n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<i8>`, containing the quantized result of the addition of the dequantized inputs.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    ///  \n    /// ## Example\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// \n    /// fn qlinear_add_example() -> Tensor<i8> {    \n    ///     let a = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![6, 6, 6, 11, 11, 11].span(),\n    ///     );\n    /// \n    ///     // As the operator supports broadcasting shapes [1, 3] and [2, 3] are compatible\n    ///     let b = TensorTrait::<i8>::new(\n    ///         shape: array![1, 3].span(),\n    ///         data: array![40, 40, 40].span(),\n    ///     );\n    /// \n    ///     let a_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),);\n    ///     let a_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    ///     let b_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    ///     let b_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    /// \n    ///     let y_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),);\n    ///     let y_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, true)].span(),);\n    /// \n    ///     return a\n    ///         .qlinear_add(\n    ///             @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n    ///         );\n    /// }        \n    /// \n    /// >>> [[1, 1, 1], [2, 2, 2]]\n    /// ```\n    ///\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<T>,\n        a_zero_point: @Tensor<T>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<T>,\n        b_zero_point: @Tensor<T>,\n        y_scale: @Tensor<T>,\n        y_zero_point: @Tensor<T>\n    ) -> Tensor::<i8>;\n    /// # tensor.qlinear_mul\n    ///\n    /// ```rust\n    ///     fn qlinear_mul(self: @Tensor<i8>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, b: @Tensor<i8>, b_scale: @Tensor<T>, b_zero_point: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>) -> Tensor::<i8>;\n    /// ```\n    /// \n    /// Performs the element-wise multiplication of quantized Tensors\n    ///\n    /// It consumes two quantized input tensors, their scales and zero points, scale and zero point of output, and computes the quantized output. \n    /// The quantization formula is y = saturate((x / y_scale) + y_zero_point).\n    /// It performs the element-wise multiplication of the two vectors once dequantized, then return the quantization of the result of the multiplication.\n    /// The broadcasting is supported\n    /// Scale and zero point must have same shape and the same type. They must be either scalar (per tensor) or N-D tensor (per row for 'a' and per column for 'b'). \n    /// Scalar refers to per tensor quantization whereas N-D refers to per row or per column quantization.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<i8>`) - The first tensor to be multiplied (a).\n    /// * `a_scale`(`@Tensor<T>`) - Scale for input `a`.\n    /// * `a_zero_point`(`@Tensor<T>`) - Zero point for input `a`.\n    /// * `b`(`@Tensor<i8>`) - The second tensor to be multiplied\n    /// * `b_scale`(`@Tensor<T>`) - Scale for input `b`.\n    /// * `b_zero_point`(`@Tensor<T>`) - Zero point for input `b`.    \n    /// * `y_scale`(`@Tensor<T>`) - Scale for outut.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for output.   \n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<i8>`, containing the quantized result of the element-wise multiplication of the dequantized inputs.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    /// \n    /// ## Example \n    ///\n    ///\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// ```rust \n    /// #[test]\n    /// #[available_gas(200000000000)]\n    /// fn qlinear_mul_example() -> Tensor<i8>{\n    ///     let a = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![21, 21, 21, 41, 41, 41]\n    ///             .span(),\n    ///     );\n    ///     let b = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![1, 3].span(),\n    ///         data: array![4, 8, 12].span(),\n    ///     );\n    /// \n    ///     let a_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    ///     );\n    ///     let a_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    ///     let b_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    ///     let b_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    /// \n    ///     let y_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(393216, false)].span(),\n    ///     );\n    ///     let y_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),\n    ///     );\n    /// \n    ///     return = a\n    ///         .qlinear_mul(\n    ///             @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n    ///         );\n    /// \n    /// }\n    ///\n    /// >>> [[16, 23, 30], [23, 36, 50]]\n    /// ```\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<T>,\n        a_zero_point: @Tensor<T>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<T>,\n        b_zero_point: @Tensor<T>,\n        y_scale: @Tensor<T>,\n        y_zero_point: @Tensor<T>\n    ) -> Tensor::<i8>;\n    /// # tensor.qlinear_matmul\n    /// \n    /// ```rust\n    ///     fn qlinear_matmul(self: @Tensor<i8>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, b: @Tensor<i8>, b_scale: @Tensor<T>, b_zero_point: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>) -> Tensor::<i8>;\n    /// ```\n    /// \n    /// Multiplies quantized Tensors\n    ///\n    /// It consumes two quantized input tensors, their scales and zero points, scale and zero point of output, and computes the quantized output. \n    /// The quantization formula is y = saturate((x / y_scale) + y_zero_point).\n    /// It performs the multiplication of the two vectors once dequantized. If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes.\n    /// Then return the quantization of the result of the multiplication.\n    /// Scale and zero point must have same shape and the same type. They must be either scalar (per tensor) or N-D tensor (per row for 'a' and per column for 'b'). \n    /// Scalar refers to per tensor quantization whereas N-D refers to per row or per column quantization.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<i8>`) - The first tensor to be multiplied (a).\n    /// * `a_scale`(`@Tensor<T>`) - Scale for input `a`.\n    /// * `a_zero_point`(`@Tensor<T>`) - Zero point for input `a`.\n    /// * `b`(`@Tensor<i8>`) - The second tensor to be multiplied\n    /// * `b_scale`(`@Tensor<T>`) - Scale for input `b`.\n    /// * `b_zero_point`(`@Tensor<T>`) - Zero point for input `b`.    \n    /// * `y_scale`(`@Tensor<T>`) - Scale for output.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for output.   \n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<i8>`, containing the quantized result of the multiplication of the dequantized inputs.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    ///  \n    /// ## Example\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// fn qlinear_matmul_example() -> Tensor<i8> {    \n    ///     let a = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![\n    ///             3,\n    ///             4,\n    ///             5,\n    ///             2,\n    ///             4,\n    ///             3\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let b = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![3, 1].span(),\n    ///         data: array![\n    ///             4,\n    ///             8,\n    ///             4\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     let a_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),);\n    ///     let a_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    ///     let b_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    ///     let b_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    /// \n    ///     let y_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(393216, false)].span(),);\n    ///     let y_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),);\n    /// \n    ///     return a\n    ///         .qlinear_matmul(\n    ///             @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n    ///         );\n    /// }        \n    /// >>> [14, 13]\n    /// ```\n    ///\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<T>,\n        a_zero_point: @Tensor<T>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<T>,\n        b_zero_point: @Tensor<T>,\n        y_scale: @Tensor<T>,\n        y_zero_point: @Tensor<T>\n    ) -> Tensor::<i8>;\n    /// # tensor.qlinear_concat\n    ///\n    /// ```rust \n    ///   qlinear_concat(tensors: Span<Tensor<i8>>, scales: Span<Tensor<T>>, zero_points: Span<Tensor<T>>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>, axis: usize) -> Tensor::<i8>;\n    /// ```\n    ///\n    /// Concatenate a list of tensors after dequantizing them with their respective scales and zero_points and returns the quantized result.\n    ///\n    /// ## Args\n    ///\n    /// * `tensors`(` Span<Tensor<i8>>,`) - Array of the quantized input tensors.\n    /// * `scales`(` Span<Tensor<T>>,`) - Array of the scales of the quantized input tensors.\n    /// * `zero_points`(` Span<Tensor<T>>,`) - Arrayof the zero_points of the quantized input tensors.\n    /// * `y_scale`(`@Tensor<T>`) - Scale for output.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for output.   \n    /// * `axis`(`usize`) -  Axis to concat on.\n    ///\n    /// ## Panics\n    ///\n    /// * Panic if tensor length is not greater than 1.\n    /// * Panics if dimension is not greater than axis.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<i8>` concatenated quantized tensor of the dequantized input tensors.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    ///\n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// fn qlinear_concat_example() -> Tensor<i8> {\n    ///     let tensor1 = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             5,\n    ///             5,\n    ///             5,\n    ///             5,\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let tensor2 = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             1,\n    ///             1,\n    ///             1,\n    ///             1,\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     let tensors = array![tensor1, tensor2].span();\n    /// \n    ///     let tensor1_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),);\n    ///     let tensor2_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(262144, false)].span(),);\n    /// \n    ///     let scales = array![tensor1_scale, tensor2_scale].span();\n    /// \n    ///     let tensor1_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(327680, false)].span(),); \n    ///     let tensor2_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    /// \n    ///     let zero_points = array![tensor1_zero_point, tensor2_zero_point].span();\n    /// \n    ///     let y_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(262144, false)].span(),);\n    /// \n    ///     let y_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    /// \n    ///     return TensorTrait::qlinear_concat(tensors, scales, zero_points, @y_scale, @y_zero_point, 0);\n    /// }\n    /// \n    /// >>> [[1, 1, 1, 1], [2, 2, 2, 2]]  \n    /// ```\n    ///\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<T>>,\n        zero_points: Span<Tensor<T>>,\n        y_scale: @Tensor<T>,\n        y_zero_point: @Tensor<T>,\n        axis: usize\n    ) -> Tensor::<i8>;\n    /// # tensor.qlinear_leakyrelu\n    /// \n    /// ```rust\n    ///     fn qlinear_leakyrelu(self: @Tensor<i8>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, alpha: T) -> Tensor::<i8>;\n    /// ```\n    /// \n    /// Applies the Leaky Relu operator to a quantized Tensor\n    ///\n    /// QLinar LeakyRelu takes as input a quantized Tensor, its scale and zero point and an scalar alpha, and produces one output data (a quantized Tensor)\n    /// where the function `f(x) = alpha * x for x < 0, f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n    /// The quantization formula is y = saturate((x / y_scale) + y_zero_point).\n    /// Scale and zero point must have same shape and the same type. They must be either scalar (per tensor) or N-D tensor (per row for 'a' and per column for 'b'). \n    /// Scalar refers to per tensor quantization whereas N-D refers to per row or per column quantization.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<i8>`) - The first tensor to be multiplied (a).\n    /// * `a_scale`(`@Tensor<T>`) - Scale for input `a`.\n    /// * `a_zero_point`(`@Tensor<T>`) - Zero point for input `a`.\n    /// * `alpha`(`T`) - The factor multiplied to negative elements.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<i8>`, containing result of the Leaky Relu.\n    ///\n    /// ## Type Constraints\n    ///\n    /// u32 tensor, not supported.\n    /// fp8x23wide tensor, not supported.\n    /// fp16x16wide tensor, not supported.\n    /// bool tensor, not supported.\n    ///  \n    /// ## Example\n    /// \n    /// ```rust\n\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// \n    /// \n    /// fn qlinear_leakyrelu_example() -> Tensor<i8> {\n    ///     let a = TensorTrait::<\n    ///         i8\n    ///     >::new(\n    ///         shape: array![2, 3].span(),\n    ///         data: array![\n    ///             -10,\n    ///             -10,\n    ///             -10,\n    ///             10,\n    ///             10,\n    ///             10\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     \n    ///     let a_scale = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(327680, false)].span(),);\n    ///     let a_zero_point = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),);\n    /// \n    ///     let alpha = FixedTrait::<FP16x16>::new(655360, false);\n    /// \n    ///     return = a\n    ///         .qlinear_leakyrelu(\n    ///             @a_scale, @a_zero_point, alpha\n    ///         );\n    /// }\n    /// \n    /// >>> [[-118, -118, -118], [10, 10, 10]]\n    ///\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, alpha: T\n    ) -> Tensor::<i8>;\n    /// # tensor.slice\n    ///\n    /// ```rust \n    ///    fn slice(self: @Tensor<T>, starts: Span<usize>, ends: Span<usize>, axes: Option<Span<usize>>, steps: Option<Span<usize>>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Produces a slice of the input tensor along multiple axes.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Tensor of data to extract slices from.\n    /// * `starts`(Span<usize>) - 1-D tensor of starting indices of corresponding axis in `axes`\n    /// * `ends`(Span<usize>) - 1-D tensor of ending indices (exclusive) of corresponding axis in `axes`\n    /// * `axes`(Option<Span<usize>>) - 1-D tensor of axes that `starts` and `ends` apply to. \n    /// * `steps`(Option<Span<usize>>) - 1-D tensor of slice step of corresponding axis in `axes`.    \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the length of starts is not equal to the length of ends.\n    /// * Panics if the length of starts is not equal to the length of axes.\n    /// * Panics if the length of starts is not equal to the length of steps.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` slice of the input tensor.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn slice_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 4].span(), \n    ///         data: array![0, 1, 2, 3, 4, 5, 6, 7].span(), \n    ///     );\n    /// \n    ///     return tensor.slice(\n    ///         starts: array![0, 2].span(), \n    ///         ends: array![2, 4].span(), \n    ///         axis: Option::None(()), \n    ///         steps: Option::Some(array![1, 1].span())\n    ///     );\n    /// }\n    /// >>> [[2 3]\n    ///      [6 7]]\n    /// ```\n    ///\n    fn slice(\n        self: @Tensor<T>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<T>;\n    /// # tensor.nonzero\n    ///\n    /// ```rust \n    ///    fn nonzero(self: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Produces indices of the elements that are non-zero (in row-major order - by dimension).\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Tensor of data to calculate non-zero indices.  \n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<usize>` indices of the elements that are non-zero (in row-major order - by dimension).\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn nonzero_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 4].span(), \n    ///         data: array![0, 1, 2, 3, 4, 5, 6, 7].span(), \n    ///     );\n    /// \n    ///     return tensor.nonzero();\n    /// }\n    /// >>> [[0 0 0 1 1 1 1]\n    ///      [1 2 3 0 1 2 3]]\n    /// ```\n    ///\n    fn nonzero(self: @Tensor<T>) -> Tensor<usize>;\n    /// # tensor.gather\n    ///\n    /// ```rust \n    ///    fn gather(self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Gather entries of the axis dimension of data.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Tensor<i32>`) - Tensor of indices.\n    /// * `axis`(`Option<i32>`) - Axis to gather on. Default: axis=0.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if index values are not within bounds [-s, s-1] along axis of size s.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` .\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn gather_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 3].span(), \n    ///         data: array![[ 1, 2, 3],[4, 5, 6]].span(), \n    ///     );\n    ///     let indices = TensorTrait::<i32>::new(\n    ///         shape: array![1, 1].span(), \n    ///         data: array![1, 0].span(), \n    ///     );\n    /// \n    ///     return tensor.gather(\n    ///         indices: indices, \n    ///         axis: Option::None(()), \n    ///     );\n    /// }\n    /// >>> [[4. 5. 6.]\n    ///      [1. 2. 3.]]\n    /// ```\n    ///\n    fn gather(self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<T>;\n    /// # tensor.unsqueeze\n    ///\n    /// ```rust \n    ///    fn unsqueeze(self: @Tensor<T>, axes: Span<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Insert single-dimensional entries to the shape of an input tensor (data). Takes one required input axes -\n    /// which contains a list of dimension indices and this operator will insert a dimension of value 1 into the\n    /// corresponding index of the output tensor (expanded).\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Tensor of data to unsquezee.\n    /// * `axes`(`Span<usize>`) - List of integers indicating the dimensions to be inserted. \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the given axes have duplicate elements.\n    /// * Panics if one of the given axes is invalid.\n    ///\n    /// ## Returns \n    ///\n    /// Reshaped `Tensor<T>` with same data as input.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn unsqueeze_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 4].span(), \n    ///         data: array![0, 1, 2, 3, 4, 5, 6, 7].span(), \n    ///     );\n    /// \n    ///     return tensor.unsqueeze(\n    ///         axes: array![0, 3].span(), \n    ///     );\n    /// }\n    /// >>> [[[[0]\n    ///        [1]\n    ///        [2]\n    ///        [3]]\n    ///\n    ///       [[4]\n    ///        [5]\n    ///        [6]\n    ///        [7]]]]\n    /// ```\n    ///\n    fn unsqueeze(self: @Tensor<T>, axes: Span<usize>) -> Tensor<T>;\n    /// # tensor.squeeze\n    ///\n    /// ```rust \n    ///    fn squeeze(self: @Tensor<T>, axes: Option<Span<i32>>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Removes dimensions of size 1 from the shape of a tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Tensor of data to calculate non-zero indices.  \n    /// * `axes`(`Option<Span<i32>>`) - List of integers indicating the dimensions to squeeze.  \n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` Reshaped tensor with same data as input.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn squeeze_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![1, 2, 1, 2, 1].span(), \n    ///         data: array![1, 1, 1, 1].span(), \n    ///     );\n    /// \n    ///     return tensor.squeeze(axes: Option::None(());\n    /// }\n    /// >>> [[1 1]\n    ///      [1 1]]\n    /// ```\n    ///\n    fn squeeze(self: @Tensor<T>, axes: Option<Span<u32>>) -> Tensor<T>;\n    /// # tensor.clip\n    ///\n    /// ```rust \n    ///    fn clip(self: @Tensor<T>, min: T, max: T) -> Tensor<T>;\n    /// ```\n    ///\n    /// Clip operator limits the given input within an interval.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Input tensor whose elements to be clipped.\n    /// * `min`(`Option<T>`) - Minimum value, under which element is replaced by min.\n    /// * `max`(`Option<T>`) - Maximum value, above which element is replaced by max.\n    ///\n    /// ## Returns \n    ///\n    /// Output `Tensor<T>` with clipped input elements.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn clip_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 3].span(), \n    ///         data: array![[ 1, 2, 3],[4, 5, 6]].span(), \n    ///     );\n    /// \n    ///     return tensor.clip(\n    ///         min: Option::None(()), \n    ///         max: Option::Some(3),\n    ///     );\n    /// }\n    /// >>> [[1. 2. 3.]\n    ///      [3. 3. 3.]]\n    /// ```\n    ///\n    fn clip(self: @Tensor<T>, min: Option<T>, max: Option<T>) -> Tensor<T>;\n    /// # tensor.sign\n    ///\n    /// ```rust \n    ///    fn sign(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Calculates the sign of the given input tensor element-wise.\n    /// If input > 0, output 1. if input < 0, output -1. if input == 0, output 0.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Tensor of data to calculates the sign of the given input tensor element-wise.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with The sign of the input tensor computed element-wise.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\n    /// \n    /// fn sign_example() -> Tensor<i32> {\n    ///     let tensor = TensorTrait::<i32>::new(\n    ///         shape: array![11].span(), \n    ///         data: array![-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5].span(), \n    ///     );\n    /// \n    ///     return tensor.sign();\n    /// }\n    /// >>> [-1, -1, -1, -1, -1, 0, 1, 1, 1, 1, 1]\n    /// ```\n    ///\n    fn sign(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.identity\n    ///\n    /// ```rust \n    ///    fn identity(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Return a Tensor with the same shape and contents as input.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - Input tensor.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` to copy input into.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, i32Tensor};\n    /// \n    /// fn identity_example() -> Tensor<i32> {\n    ///     let tensor = TensorTrait::<i32>::new(\n    ///         shape: array![2, 2].span(), \n    ///         data: array![1, 2, 3, 4].span(), \n    ///     );\n    ///     let t_identity = tensor.identity();\n    ///     t_identity\n    /// }\n    /// >>> [[1 2] [3 4]] // A Tensor with the same shape and contents as input\n    /// ```\n    ///\n    fn identity(self: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.and\n    ///\n    /// ```rust\n    ///     fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool>;\n    /// ```\n    ///\n    /// Computes the logical AND of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<bool>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<bool>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<bool>` with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, BoolTensor};\n    /// \n    /// fn and_example() -> Tensor<bool> {\n    ///     let tensor_1 = TensorTrait::<bool>::new(\n    ///         shape: array![3, 3].span(), data: array![false, true, false, false, false, true, true, false, true, false, false, true].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<bool>::new(\n    ///         shape: array![3, 3].span(), data: array![false, false, true, true, false, true, false, true, false, true, false, true].span(),\n    ///     );\n    /// \n    ///     return tensor_1.and(@tensor_2);\n    /// }\n    /// >>> [false, false, false, false, false, true, false, false, false, false, false, true]\n    /// ```\n    ///\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool>;\n    /// #tensor.where\n    ///\n    /// ```rust\n    ///     fn where(self: @Tensor<T>, x: @Tensor<T>, y: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes a new tensor by selecting values from tensor x (resp. y) at\n    /// indices where the condition is 1 (resp. 0).\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The condition tensor\n    /// * `x`(`@Tensor<T>`) - The first input tensor\n    /// * `y`(`@Tensor<T>`) - The second input tensor\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// Return a new `Tensor<T>` of the same shape as the input with elements \n    /// chosen from x or y depending on the condition.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    ///\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn where_example() -> Tensor<u32> {\n    ///     let tensor_cond = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), data: array![0, 1, 0, 1].span(),\n    ///     );\n    ///\n    ///     let tensor_x = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), data: array![2, 4, 6, 8].span(),\n    ///     );\n    ///\n    ///     let tensor_y = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), data: array![1, 3, 5, 9].span(),\n    ///     );\n    ///\n    ///     return tensor_cond.where(@tensor_1, @tensor_2);\n    /// }\n    /// >>> [1,4,5,8]\n    /// ```\n    ///\n    fn where(self: @Tensor<T>, x: @Tensor<T>, y: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.resize\n    ///\n    /// ```rust\n    ///     fn resize(\n    ///         self: @Tensor<T>,\n    ///         roi: Option<Tensor<T>>,\n    ///         scales: Option<Span<T>>,\n    ///         sizes: Option<Span<usize>>,\n    ///         antialias: Option<usize>,\n    ///         axes: Option<Span<usize>>,\n    ///         coordinate_transformation_mode: Option<orion::operators::tensor::math::resize::TRANSFORMATION_MODE>,\n    ///         cubic_coeff_a: Option<T>,\n    ///         exclude_outside: Option<bool>,\n    ///         extrapolation_value: Option<T>,\n    ///         keep_aspect_ratio_policy: Option<orion::operators::tensor::math::resize::KEEP_ASPECT_RATIO_POLICY>,\n    ///         mode: Option<orion::operators::tensor::math::resize::MODE>,\n    ///         nearest_mode: Option<orion::operators::tensor::math::resize::NEAREST_MODE>,\n    ///     ) -> Tensor<T>;\n    /// ```\n    ///\n    /// Resizes the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood in the input tensor. \n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `roi` (`Option<Tensor<T>>`) (optional) - 1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X or the length of axes, if provided. It only takes effect when coordinate_transformation_mode is \"tf_crop_and_resize\"\n    /// * `scales` (`Option<Tensor<T>>`) (optional) - The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X' or the length of 'axes', if provided. One and only one of 'scales' and 'sizes' MUST be specified.\n    /// * `sizes` (`Option<Tensor<usize>>`) (optional) - Target size of the output tensor. Its interpretation depends on the 'keep_aspect_ratio_policy' value. The number of elements of 'sizes' should be the same as the rank of input 'X', or the length of 'axes', if provided. One and only one of 'scales' and 'sizes' MUST be specified.  \n    /// * `antialias` (`Option<usize>`) (default is 0) - If set to 1, \"linear\" and \"cubic\" interpolation modes will use an antialiasing filter when downscaling. Antialiasing is achieved by stretching the resampling filter by a factor max(1, 1 / scale).\n    /// * `axes`(`Option<Span<usize>>`) - If provided, it specifies a subset of axes that 'roi', 'scales' and 'sizes' refer to. If not provided, all axes are assumed [0, 1, ..., r-1], where r = rank(data). \n    /// * `coordinate_transformation_mode` (`Option<TRANSFORMATION_MODE>`) (default is half_pixel) - This attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. \n    /// * `cubic_coeff_a` (`Option<T>`) (default is -0.75) - The coefficient 'a' used in cubic interpolation.\n    /// * `exclude_outside` (`Option<bool>`) (default is false) - If set to true, the weight of sampling locations outside the tensor will be set to 0 and the weight will be renormalized so that their sum is 1.0. \n    /// * `extrapolation_value` (`Option<T>`) (default is 0.0) - When coordinate_transformation_mode is \"tf_crop_and_resize\" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. \n    /// * `keep_aspect_ratio_policy` (`Option<KEEP_ASPECT_RATIO_POLICY>`) (default is stretch) - This attribute describes how to interpret the `sizes` input with regard to keeping the original aspect ratio of the input, and it is not applicable when the `scales` input is used. \n    /// * `mode` (`Option<MODE>`) (default is nearest) - Three interpolation modes: \"nearest\", \"linear\" and \"cubic\".\n    /// * `nearest_mode` (`Option<NEAREST_MODE>`) (default is round_prefer_floor) - Four modes: \"round_prefer_floor\" (as known as round half down), \"round_prefer_ceil\" (as known as round half up), \"floor\", \"ceil\". Only used by nearest interpolation. \n    ///\n    /// ## Panics\n    ///\n    /// * Panics if both scales and sizes are `Option::None`.\n    /// * Panics if roi is `Option::None` for the coordinate_transformation_mode `tf_crop_and_resize`.\n    /// * Panics if antialias is not `Option::None` for mode `nearest`.\n    ///\n    /// ## Returns\n    ///\n    /// A new resized `Tensor<T>` of the dimension given by output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) is scale is specified, or output_size if size is specified (note that some value of the parameter `keep_aspect_ratio_policy` can change sizes and therefore the dimension of the output tensor) \n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP16x16Tensor, FP16x16TensorPartialEq};\n    /// use orion::operators::tensor::math::resize::{\n    ///     MODE, NEAREST_MODE, KEEP_ASPECT_RATIO_POLICY, TRANSFORMATION_MODE\n    /// };\n    /// use orion::numbers::{FP16x16, FP16x16Impl, FixedTrait};\n    /// use core::debug::PrintTrait;\n    /// \n    /// fn example_resize_downsample_scales_linear() -> Tensor<FP16x16>{\n    ///     let mut data = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1, 1, 2, 4].span(),\n    ///         data: array![\n    ///             FixedTrait::<FP16x16>::new(65536, false),   //1\n    ///             FixedTrait::<FP16x16>::new(131072, false),  //2\n    ///             FixedTrait::<FP16x16>::new(196608, false),  //3\n    ///             FixedTrait::<FP16x16>::new(262144, false),  //4\n    ///             FixedTrait::<FP16x16>::new(327680, false),  //5\n    ///             FixedTrait::<FP16x16>::new(393216, false),  //6\n    ///             FixedTrait::<FP16x16>::new(458752, false),  //7\n    ///             FixedTrait::<FP16x16>::new(524288, false),  //8\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let mut scales = array![\n    ///         FixedTrait::<FP16x16>::new(65536, false),  //1\n    ///         FixedTrait::<FP16x16>::new(65536, false),   \n    ///         FixedTrait::<FP16x16>::new(39322, false),  //0.6\n    ///         FixedTrait::<FP16x16>::new(39322, false)\n    ///     ]\n    ///         .span();\n    /// \n    ///     let scales = Option::Some(scales);\n    /// \n    ///     return data.resize(\n    ///         Option::None,\n    ///         scales,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::Some(MODE::LINEAR),\n    ///         Option::None,\n    ///     );\n    /// \n    /// }\n    /// >>> [[[[2.6666665 4.3333331]]]]\n    /// \n    /// \n    /// \n    /// fn example_resize_tf_crop_and_resize_extrapolation_value() -> Tensor<FP16x16> {\n    ///     let mut data = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1, 1, 4, 4].span(),\n    ///         data: array![\n    ///             FixedTrait::<FP16x16>::new(65536, false),\n    ///             FixedTrait::<FP16x16>::new(131072, false),\n    ///             FixedTrait::<FP16x16>::new(196608, false),\n    ///             FixedTrait::<FP16x16>::new(262144, false),\n    ///             FixedTrait::<FP16x16>::new(327680, false),\n    ///             FixedTrait::<FP16x16>::new(393216, false),\n    ///             FixedTrait::<FP16x16>::new(458752, false),\n    ///             FixedTrait::<FP16x16>::new(524288, false),\n    ///             FixedTrait::<FP16x16>::new(589824, false),\n    ///             FixedTrait::<FP16x16>::new(655360, false),\n    ///             FixedTrait::<FP16x16>::new(720896, false),\n    ///             FixedTrait::<FP16x16>::new(786432, false),\n    ///             FixedTrait::<FP16x16>::new(851968, false),\n    ///             FixedTrait::<FP16x16>::new(917504, false),\n    ///             FixedTrait::<FP16x16>::new(983040, false),\n    ///             FixedTrait::<FP16x16>::new(1048576, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     let mut roi = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![8].span(),\n    ///         data: array![\n    ///             FixedTrait::<FP16x16>::new(0, false),\n    ///             FixedTrait::<FP16x16>::new(0, false),\n    ///             FixedTrait::<FP16x16>::new(26214, false),\n    ///             FixedTrait::<FP16x16>::new(39322, false),\n    ///             FixedTrait::<FP16x16>::new(65536, false),\n    ///             FixedTrait::<FP16x16>::new(65536, false),\n    ///             FixedTrait::<FP16x16>::new(78643, false),\n    ///             FixedTrait::<FP16x16>::new(111411, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let roi = Option::Some(roi);\n    /// \n    ///     let mut sizes = array![1, 1, 3, 3].span();\n    ///     let sizes = Option::Some(sizes);\n    /// \n    ///     let extrapolation_value = Option::Some(FixedTrait::<FP16x16>::new(655360, false));\n    /// \n    ///     return data.resize(\n    ///         roi,\n    ///         Option::None,\n    ///         sizes,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::Some(TRANSFORMATION_MODE::TF_CROP_AND_RESIZE),\n    ///         Option::None,\n    ///         Option::None,\n    ///         extrapolation_value,\n    ///         Option::None,\n    ///         Option::Some(MODE::LINEAR),\n    ///         Option::None,\n    ///     );\n    /// \n    /// }\n    /// >>> [[[[ 7.6000004 10.        10.       ]\n    ///     [12.400001  10.        10.       ]\n    ///     [10.        10.        10.       ]]]]\n    /// \n    /// \n    /// \n    /// fn example_resize_downsample_sizes_cubic_antialias() -> Tensor<FP16x16> {\n    ///     let mut data = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![1, 1, 4, 4].span(),\n    ///         data: array![\n    ///             FixedTrait::<FP16x16>::new(65536, false),\n    ///             FixedTrait::<FP16x16>::new(131072, false),\n    ///             FixedTrait::<FP16x16>::new(196608, false),\n    ///             FixedTrait::<FP16x16>::new(262144, false),\n    ///             FixedTrait::<FP16x16>::new(327680, false),\n    ///             FixedTrait::<FP16x16>::new(393216, false),\n    ///             FixedTrait::<FP16x16>::new(458752, false),\n    ///             FixedTrait::<FP16x16>::new(524288, false),\n    ///             FixedTrait::<FP16x16>::new(589824, false),\n    ///             FixedTrait::<FP16x16>::new(655360, false),\n    ///             FixedTrait::<FP16x16>::new(720896, false),\n    ///             FixedTrait::<FP16x16>::new(786432, false),\n    ///             FixedTrait::<FP16x16>::new(851968, false),\n    ///             FixedTrait::<FP16x16>::new(917504, false),\n    ///             FixedTrait::<FP16x16>::new(983040, false),\n    ///             FixedTrait::<FP16x16>::new(1048576, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     let antialias = Option::Some(1);\n    /// \n    ///     let mut sizes = array![1, 1, 3, 3].span();\n    ///     let sizes = Option::Some(sizes);\n    /// \n    ///     return data.resize(\n    ///         Option::None,\n    ///         Option::None,\n    ///         sizes,\n    ///         antialias,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::None,\n    ///         Option::Some(MODE::CUBIC),\n    ///         Option::None,\n    ///     );\n    /// }\n    /// \n    /// >>> [[[[ 1.7750092  3.1200073  4.4650054]\n    ///     [ 7.1550016  8.5        9.844998 ]\n    ///     [12.534994  13.8799925 15.224991 ]]]]\n    /// \n    /// ```\n    ///\n    fn resize(\n        self: @Tensor<T>,\n        roi: Option<Tensor<T>>,\n        scales: Option<Span<T>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<\n            orion::operators::tensor::math::resize::TRANSFORMATION_MODE\n        >,\n        cubic_coeff_a: Option<T>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<T>,\n        keep_aspect_ratio_policy: Option<\n            orion::operators::tensor::math::resize::KEEP_ASPECT_RATIO_POLICY\n        >,\n        mode: Option<orion::operators::tensor::math::resize::MODE>,\n        nearest_mode: Option<orion::operators::tensor::math::resize::NEAREST_MODE>,\n    ) -> Tensor<T>;\n    /// #tensor.round\n    ///\n    /// ```rust\n    ///     fn round(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the round value of all elements in the input tensor.\n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the round value of all elements in the input tensor.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FixedTrait, FP16x16};\n    /// \n    /// fn round_example() -> Tensor<FP16x16> {\n    ///     let tensor = TensorTrait::<FP16x16>::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             FixedTrait::new(190054, false),  // 2.9\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.round();\n    /// }\n    /// >>> [3]\n    /// ```\n    ///\n    fn round(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.scatter\n    ///\n    /// ```rust \n    ///    fn scatter(self: @Tensor<T>, updates: Tensor<T>, indices: Tensor<usize>,  axis: Option<usize>, reduction: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Produces a copy of input data, and updates value to values specified by updates at specific index positions specified by indices.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `updates`(`Tensor<T>`) - The updates tensor.\n    /// * `indices`(`Tensor<T>`) - Tensor of indices.\n    /// * `axis`(`Option<usize>`) - Axis to scatter on. Default: axis=0.\n    /// * `reduction`(`Option<usize>`) - Reduction operation. Default: reduction='none'.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if index values are not within bounds [-s, s-1] along axis of size s.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` .\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn scatter_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![3, 5].span(), \n    ///         data: array![[ 0, 0, 0, 0, 0],\n    ///                      [ 0, 0, 0, 0, 0],\n    ///                      [ 0, 0, 0, 0, 0]].span(), \n    ///     );\n    ///     let updates = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), \n    ///         data: array![[ 1, 2, 3],\n    ///                      [ 4, 5, 6],\n    ///                      [ 7, 8, 9]].span(), \n    ///     );\n    ///     let indices = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), \n    ///         data: array![[ 0, 1, 2],\n    ///                      [ 2, 0, 1],\n    ///                      [ 1, 0, 1]].span(), \n    ///     );\n    /// \n    ///     return tensor.scatter(\n    ///         updates: updates\n    ///         indices: indices, \n    ///         axis: Option::None(()), \n    ///         reduction: Option::None(()), \n    ///     );\n    /// }\n    /// >>> [[ 1, 8, 0, 0, 0],\n    ///      [ 7, 2, 9, 0, 0],\n    ///      [ 4, 0, 3, 0, 0]]\n    /// ```\n    ///\n    fn scatter(\n        self: @Tensor<T>,\n        updates: Tensor<T>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<T>;\n    /// # tensor.trilu\n    ///\n    /// ```rust \n    ///    fn trilu(self: @Tensor<T>, upper: bool, k: i64) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns a new tensor with the uppper/lower triangular part of the tensor.\n    ///\n    /// ## Args\n    /// \n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `upper`(`bool`) - if true, returns the upper triangular part of the tensor, otherwise returns the lower part.\n    /// * `k`(`i64`) - value corresponding to the number diagonals above or below the main diagonal to exclude or include.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the dimension of the tensor is less than 2.\n    ///\n    /// ## Returns\n    ///\n    /// A `Tensor<T>` instance with the uppper/lower triangular part of the tensor.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn trilu_tensor_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 3, 3].span(), data: array![0, 4, 3, 2, 0, 9, 8, 2, 5, 2, 7, 2, 2, 6, 0, 2, 6 ,5].span(),\n    ///     );\n    /// \n    ///     // We can call `trilu` function as follows.\n    ///     return tensor.trilu(false, 0);\n    /// }\n    /// >>> [[[0, 0, 0],[2, 0, 0], [8, 2, 5]], [[2, 0, 0], [2, 6, 0], [2, 6, 5]]]\n    /// ```\n    ///\n    fn trilu(self: @Tensor<T>, upper: bool, k: i64) -> Tensor<T>;\n    /// #tensor.bitwise_and\n    ///\n    /// ```rust\n    ///     fn bitwise_and(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Computes the bitwise AND of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the same shape as the broadcasted inputs.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn and_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 0, 4, 5, 0, 6, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.bitwise_and(@tensor_2);\n    /// }\n    /// >>> [0,1,2,0,4,5,0,6,2]\n    /// ```\n    ///\n    fn bitwise_and(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.bitwise_or\n    ///\n    /// ```rust\n    ///     fn bitwise_or(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Computes the bitwise OR of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the same shape as the broadcasted inputs.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn or_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 0, 4, 5, 0, 6, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.bitwise_or(@tensor_2);\n    /// }\n    /// >>> [0,1,2,3,4,5,6,7,10]\n    /// ```\n    ///\n    fn bitwise_or(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// #tensor.bitwise_xor\n    ///\n    /// ```rust\n    ///     fn bitwise_xor(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<usize>;\n    /// ```\n    ///\n    /// Computes the bitwise XOR of two tensors element-wise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor to be compared\n    /// * `other`(`@Tensor<T>`) - The second tensor to be compared\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the same shape as the broadcasted inputs.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn xor_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 0, 4, 5, 0, 6, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.bitwise_xor(@tensor_2);\n    /// }\n    /// >>> [0,0,0,3,0,0,6,1,10]\n    /// ```\n    ///\n    fn bitwise_xor(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// ## tensor.reduce_l1\n    ///\n    /// ```rust \n    ///    fn reduce_l1(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the L1 norm of the input tensor's elements along the provided axes.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The dimension to reduce.\n    /// * `keepdims`(`bool`) - If true, retains reduced dimensions with length 1.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axis reduced by summing its elements.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reduce_l1_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reduce_l1` function as follows.\n    ///     return tensor.reduce_l1(axis: 1, keepdims: false);\n    /// }\n    /// >>> [[2,4],[10,12]]\n    /// ```\n    ///\n    fn reduce_l1(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ## tensor.reduce_l2\n    ///\n    /// ```rust \n    ///    fn reduce_l2(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the L2 norm of the input tensor's elements along the provided axes.\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The dimension to reduce.\n    /// * `keepdims`(`bool`) - If true, retains reduced dimensions with length 1.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axis reduced by summing its elements.\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn reduce_l2_example() -> Tensor<u32> {\n    ///\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(2);\n    ///     shape.append(2);\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FixedTrait::new_unscaled(1, false));\n    ///     data.append(FixedTrait::new_unscaled(2, false));\n    ///     data.append(FixedTrait::new_unscaled(3, false));\n    ///     data.append(FixedTrait::new_unscaled(5, false));\n    ///     let tensor = TensorTrait::<FP8x23>::new(shape.span(), data.span());\n    /// \n    ///     We can call `reduce_l2` function as follows.\n    ///     return tensor.reduce_l2(axis: 1, keepdims: true);\n    /// }\n    /// >>> [[0x11e3779, 0x2ea5ca1]]\n    /// ```\n    ///\n    fn reduce_l2(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ## tensor.reduce_sum_square\n    ///\n    /// ```rust \n    ///    fn reduce_sum_square(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the sum square of the input tensor's elements along the provided axes. \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The dimension to reduce.\n    /// * `keepdims`(`bool`) - If true, retains reduced dimensions with length 1.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axis reduced by summing its elements.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn reduce_sum_square_example() -> Tensor<u32> {\n    ///\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(2);\n    ///     shape.append(2);\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(1);\n    ///     data.append(2);\n    ///     data.append(3);\n    ///     data.append(4);\n    ///     let tensor = TensorTrait::<u32>::new(shape.span(), data.span());\n    /// \n    ///     We can call `reduce_sum_square` function as follows.\n    ///     return tensor.reduce_sum_square(axis: 1, keepdims: true);\n    /// }\n    /// >>> [[5, 25]]\n    /// ```\n    ///\n    fn reduce_sum_square(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// # tensor.constant_of_shape\n    ///\n    /// ```rust \n    ///    fn constant_of_shape(shape: Span<usize>, value: T) -> Tensor<T>;\n    /// ```\n    ///\n    /// Returns a new tensor with the given shape and constant value.\n    /// \n    /// ## Args\n    /// \n    /// * `shape`(`Span<usize>`) - A span representing the shape of the tensor.\n    /// * `value` (`T`) - the constant value.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance.\n    ///\n    /// ## Examples\n    /// \n    /// Let's create new u32 Tensor with constant 42.\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{\n    ///     TensorTrait, // we import the trait\n    ///     Tensor, // we import the type\n    ///     U32Tensor // we import the implementation. \n    /// };\n    /// \n    /// fn constant_of_shape_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::constant_of_shape(shape: array![3].span(), value: 42);\n    /// \n    ///     return tensor;\n    /// }\n    /// \n    /// >>> [42, 42, 42]\n    /// ```\n    ///\n    fn constant_of_shape(shape: Span<usize>, value: T) -> Tensor<T>;\n    /// # tensor.gather_elements\n    ///\n    /// ```rust \n    ///    fn gather_elements(self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<T>;\n    /// ```\n    ///\n    /// GatherElements is an indexing operation that produces its output by indexing into the input data tensor at index positions determined by elements of the indices tensor.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Tensor<i32>`) - Tensor of indices.\n    /// * `axis`(`Option<i32>`) - Axis to gather_elements on. Default: axis=0.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if index values are not within bounds [-s, s-1] along axis of size s.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` .\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn gather_elements_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), \n    ///         data: array![[ 1, 2, 3],[4, 5, 6], [7, 8, 9]].span(), \n    ///     );\n    ///     let indices = TensorTrait::<i32>::new(\n    ///         shape: array![1, 2, 0].span(), \n    ///         data: array![2, 0, 0].span(), \n    ///     );\n    /// \n    ///     return tensor.gather_elements(\n    ///         indices: indices, \n    ///         axis: Option::None(()), \n    ///     );\n    /// }\n    /// >>> [[4. 8. 3.]\n    ///      [7. 2. 3.]]\n    /// ```\n    ///\n    fn gather_elements(self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<T>;\n    /// # tensor.binarizer\n    /// \n    /// ```rust\n    ///  fn binarizer(self: @Tensor<T>, threshold: Option<T>) -> Tensor<T>\n    /// ```\n    ///\n    /// Maps the values of a tensor element-wise to 0 or 1 based on the comparison against a threshold value.\n    ///\n    /// ## Args\n    /// * `self`(`@Tensor<T>`) - The input tensor to be binarized.\n    /// * `threshold`(`Option<T>`) - The threshold for the binarization operation.\n    ///\n    /// ## Returns\n    /// A new `Tensor<T>` of the same shape as the input tensor with binarized values.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point numbers.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn binarizer_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(0, false),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false),\n    ///             FixedTrait::new(3, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let threshold = Option::Some(FixedTrait::new(1, false))\n    /// \n    ///     return tensor.binarizer(@tensor, threshold);\n    /// }\n    /// >>> [0, 0, 8388608, 8388608]\n    ///     // The fixed point representation of\n    ///     [0, 0, 1, 1]\n    /// ```\n    ///\n    fn binarizer(self: @Tensor<T>, threshold: Option<T>) -> Tensor<T>;\n    /// # tensor.array_feature_extractor\n    ///\n    /// ```rust\n    ///     fn array_feature_extractor(self: @Tensor<T>, indices: Tensor<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Selects elements of the input tensor based on the indices passed applied to the last tensor axis. \n    /// \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Tensor<usize>`) - Tensor of indices.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if indices tensor is not 1-dimensional.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with selected elements based on provided indices.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor, U32Tensor};\n    /// \n    /// fn array_feature_extractor_example() -> Tensor<i32> {\n    ///     let input_tensor = TensorTrait::new(\n    ///         shape: array![3, 4].span(),\n    ///         data: array![\n    ///             0, 1, 2, 3,\n    ///             4, 5, 6, 7,\n    ///             8, 9, 10, 11\n    ///         ].span(),\n    ///     );\n    ///     \n    ///     let indices = TensorTrait::<u32>::new(\n    ///         shape: array![2].span(), data: array![1, 3].span(),\n    ///     );\n    /// \n    ///     return tensor.array_feature_extractor(@input_tensor, @indices);\n    /// }\n    /// >>> [[1, 3]\n    ///      [5, 7]\n    ///      [9, 11]]\n    /// ```\n    ///\n    fn array_feature_extractor(self: @Tensor<T>, indices: Tensor<usize>) -> Tensor<T>;\n    /// # tensor.shrink\n    /// \n    /// ```rust\n    ///  fn shrink(self: @Tensor<T>, bias: Option<T>, lambd: Option<T>) -> Tensor<T>\n    /// ```\n    ///\n    /// Shrinks the input tensor element-wise to the output tensor with the same datatype and shape based on the following formula:\n    /// If x < -lambd: y = x + bias; If x > lambd: y = x - bias; Otherwise: y = 0.\n    ///\n    /// ## Args\n    /// * `self`(`@Tensor<T>`) - The input tensor to be shrinked.\n    /// * `bias`(`Option<T>`) - The bias value added to or subtracted from input tensor values.\n    /// * `lambd`(`Option<T>`) - The lambd value defining the shrink condition.\n    ///\n    /// ## Returns\n    /// A new `Tensor<T>` of the same datatype and shape as the input tensor with shrinked values.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point numbers.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    /// \n    /// fn shrink_example() -> Tensor<FP8x23> {\n    ///     let tensor = TensorTrait::<FP8x23>::new(\n    ///         shape: array![2, 2].span(),\n    ///         data: array![\n    ///             FixedTrait::new(2, true),\n    ///             FixedTrait::new(1, true),\n    ///             FixedTrait::new(1, false),\n    ///             FixedTrait::new(2, false)\n    ///         ]\n    ///             .span(),\n    ///     );\n    ///     let bias = Option::Some(FixedTrait::new(1, false))\n    ///     let lambd = Option::Some(FixedTrait::new(1, false))\n    /// \n    ///     return tensor.shrink(tensor, bias, lambd);\n    /// }\n    /// >>> [-8388608, 0, 0, 8388608]\n    ///     // The fixed point representation of\n    ///     [-1, 0, 0, 1]\n    /// ```\n    ///\n    fn shrink(self: Tensor<T>, bias: Option<T>, lambd: Option<T>) -> Tensor<T>;\n    /// ## tensor.reduce_mean\n    ///\n    /// ```rust \n    ///    fn reduce_mean(self: @Tensor<T>, axes: Option<Span<usize>>, keepdims: Option<bool>, noop_with_empty_axes: Option<bool>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the mean of the input tensor's elements along the provided axes.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axes`(`Option<Span<usize>>`) - Optional input list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor if 'noop_with_empty_axes' is false, else act as an Identity op when 'noop_with_empty_axes' is true.\n    /// * `keepdims`(`Option<bool>`) - Keep the reduced dimension or not, default true means keep reduced dimension.\n    /// * `noop_with_empty_axes`(`Option<bool>`) - Defines behavior if 'axes' is empty. Default behavior with 'false' is to reduce all axes. When axes is empty and this attribute is set to true, input tensor will not be reduced,and the output tensor would be equivalent to input tensor.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axes reduced by meaning its elements.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reduce_mean_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reduce_mean` function as follows.\n    ///     return tensor.reduce_mean(axes: array![1].span(), \n    ///         keepdims: Option::None(()), \n    ///         noop_with_empty_axes:  Option::None(()));\n    /// }\n    /// >>> [[1,2],[5,6]]\n    /// ```\n    ///\n    fn reduce_mean(\n        self: @Tensor<T>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<T>;\n    /// ## tensor.reduce_min\n    ///\n    /// ```rust \n    ///    fn reduce_min(self: @Tensor<T>, axes: Option<Span<usize>>, keepdims: Option<bool>, noop_with_empty_axes: Option<bool>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the min of the input tensor's elements along the provided axes.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axes`(`Option<Span<usize>>`) - Optional input list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor if 'noop_with_empty_axes' is false, else act as an Identity op when 'noop_with_empty_axes' is true.\n    /// * `keepdims`(`Option<bool>`) - Keep the reduced dimension or not, default true means keep reduced dimension.\n    /// * `noop_with_empty_axes`(`Option<bool>`) - Defines behavior if 'axes' is empty. Default behavior with 'false' is to reduce all axes. When axes is empty and this attribute is set to true, input tensor will not be reduced,and the output tensor would be equivalent to input tensor.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axes reduced by minimum of its elements.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reduce_min_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reduce_min` function as follows.\n    ///     return tensor.reduce_min(axes: array![1].span(), \n    ///         keepdims: Option::None(()), \n    ///         noop_with_empty_axes:  Option::None(()));\n    /// }\n    /// >>> [[0,1],[4,5]]\n    /// ```\n    ///\n    fn reduce_min(\n        self: @Tensor<T>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<T>;\n    /// #tensor.pow\n    ///\n    /// ```rust\n    ///     fn pow(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Pow takes input data (Tensor) and exponent Tensor, and produces one output data (Tensor) where the function f(x) = x^exponent, is applied to the data tensor elementwise.\n    /// The input tensors must have either:\n    /// * Exactly the same shape\n    /// * The same number of dimensions and the length of each dimension is either a common length or 1.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The first tensor, base of the exponent.\n    /// * `other`(`@Tensor<T>`) - The second tensor, power of the exponent.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the shapes are not equal or broadcastable\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` with the same shape as the broadcasted inputs.\n    ///\n    /// ## Examples\n    ///\n    /// Case 1: Compare tensors with same shape\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn pow_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 0, 1, 2, 0, 1, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.pow(@tensor_2);\n    /// }\n    /// >>> [0,1,4,0,4,25,0,7,64]\n    /// ```\n    ///\n    /// Case 2: Compare tensors with different shapes\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn pow_example() -> Tensor<usize> {\n    ///     let tensor_1 = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7, 8].span(),\n    ///     );\n    /// \n    ///     let tensor_2 = TensorTrait::<u32>::new(\n    ///         shape: array![1, 3].span(), data: array![0, 1, 2].span(),\n    ///     );\n    /// \n    ///     return tensor_1.pow(@tensor_2);\n    /// }\n    /// >>> [0,1,4,0,4,25,0,7,64]\n    /// ```\n    ///\n    fn pow(self: @Tensor<T>, other: @Tensor<T>) -> Tensor<T>;\n    /// ## tensor.reduce_prod\n    /// \n    /// ```rust \n    ///    fn reduce_prod(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ```\n    /// \n    /// Reduces a tensor by multiplying its elements along a specified axis.\n    /// \n    /// ## Args\n    /// \n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The dimension to reduce.\n    /// * `keepdims`(`bool`) - If true, retains reduced dimensions with length 1.\n    /// \n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    /// \n    /// ## Returns\n    /// \n    /// A new `Tensor<T>` instance with the specified axis reduced by multiplying its elements.\n    /// \n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn reduce_prod_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),\n    ///     );\n    /// \n    ///     // We can call `reduce_prod` function as follows.\n    ///     return tensor.reduce_prod(axis: 0, keepdims: false);\n    /// }\n    /// >>> [[0,5],[12,21]]\n    /// ```\n    ///\n    fn reduce_prod(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ## tensor.is_inf\n    ///\n    /// ```rust\n    ///    fn is_inf(self: @Tensor<T>, detect_negative: Option<u8>, detect_positive: Option<u8>) -> Tensor<bool>;\n    /// ```\n    ///\n    /// Maps infinity to true and other values to false.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `detect_negative`(`Option<u8>`) - Optional Whether map negative infinity to true. Default to 1 so that negative infinity induces true.\n    /// * `detect_positive`(`Option<u8>`) - Optional Whether map positive infinity to true. Default to 1 so that positive infinity induces true.\n    ///\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<bool>` instance with entries set to true iff the input tensors corresponding element was infinity.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};    \n    /// use orion::operators::tensor::{BoolTensor, TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn is_inf_example() -> Tensor<bool> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![6].span(), data: array![1, 0, NumberTrait::INF(), 8, NumberTrait::INF(), NumberTrait::INF()].span(),\n    ///     );\n    ///\n    ///     return tensor.is_inf(detect_negative: Option::None, detect_positive: Option::None);\n    /// }\n    /// >>> [false, false, true, false, true, true]\n    /// ```\n    ///\n    fn is_inf(\n        self: @Tensor<T>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool>;\n    /// ## tensor.is_nan\n    ///\n    /// ```rust\n    ///    fn is_nan(self: @Tensor<T>) -> Tensor<bool>;\n    /// ```\n    ///\n    /// Maps NaN to true and other values to false.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<bool>` instance with entries set to true iff the input tensors corresponding element was NaN.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{BoolTensor, TensorTrait, Tensor, FP8x23Tensor};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    ///\n    /// fn is_nan_example() -> Tensor<bool> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(4);\n    ///\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP8x23 { mag: 10066329, sign: true });\n    ///     data.append(FP8x23 { mag: 0, sign: false });\n    ///     data.append(FixedTrait::NaN());\n    ///     data.append(FP8x23 { mag: 23488102, sign: false });\n    ///     let tensor = TensorTrait::new(shape.span(), data.span())\n    ///\n    ///     return tensor.is_nan();\n    /// }\n    /// >>> [false, false, true, false]\n    /// ```\n    ///\n    fn is_nan(self: @Tensor<T>) -> Tensor<bool>;\n    /// #tensor.not\n    /// \n    /// ```rust\n    ///     fn not(self: @Tensor<bool>) -> Tensor<bool;\n    /// ```\n    /// \n    /// Computes the negation of the elements in the bool type input tensor.\n    /// \n    /// ## Args\n    /// \n    /// * `self`(`@Tensor<bool>`) - The input tensor.\n    /// \n    /// \n    /// ## Returns\n    /// \n    /// A new `Tensor<bool>` of the same shape as the input tensor with \n    /// the negation of all elements in the input tensor.\n    /// \n    /// ## Example\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, BoolTensor};\n    /// \n    /// fn not_example() -> Tensor<bool> {\n    ///     let tensor = TensorTrait::new(\n    ///         shape: array![3].span(),\n    ///         data: array![\n    ///             true, true, false\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.not();\n    /// }\n    /// >>> [true, true, false]\n    /// ```\n    ///\n    fn not(self: @Tensor<T>) -> Tensor<T>;\n    /// ## tensor.reduce_log_sum\n    ///\n    /// ```rust \n    ///    fn reduce_log_sum(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the log sum of the input tensor's elements along the provided axes.\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The dimension to reduce.\n    /// * `keepdims`(`bool`) - If true, retains reduced dimensions with length 1.\n    ///\n    /// ## Panics \n    /// \n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` instance with the specified axis reduced by summing its elements.\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FixedTrait, FP16x16};\n    ///\n    /// fn reduce_log_sum() -> Tensor<FP16x16> {\n    ///\n    ///    let mut sizes = ArrayTrait::new();\n    ///    sizes.append(2);\n    ///    sizes.append(2);\n    ///    sizes.append(2);\n    ///\n    ///    let mut data = ArrayTrait::new();\n    ///    data.append(FixedTrait::new_unscaled(1, false));\n    ///    data.append(FixedTrait::new_unscaled(2, false));\n    ///    data.append(FixedTrait::new_unscaled(3, false));\n    ///    data.append(FixedTrait::new_unscaled(4, false));\n    ///    data.append(FixedTrait::new_unscaled(5, false));\n    ///    data.append(FixedTrait::new_unscaled(6, false));\n    ///    data.append(FixedTrait::new_unscaled(7, false));\n    ///    data.append(FixedTrait::new_unscaled(8, false));\n    ///\n    ///    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n    /// \n    ///     We can call `reduce_log_sum` function as follows.\n    ///     return tensor.reduce_log_sum(axis: 2, keepdims: false);\n    /// }\n    /// >>> [[0x11938, 0x1f203], [0x265d9, 0x2b540]]\n    /// ```\n    ///\n    fn reduce_log_sum(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ## tensor.reduce_log_sum_exp \n    ///\n    /// ```rust \n    ///    fn reduce_log_sum_exp(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>; \n    /// ```\n    ///\n    /// Computes the log sum of the exponentials of the input tensor's elements along the provided axes. \n    /// \n    /// ## Args \n    /// * 'self'(`@Tensor<T>`) - The input tensor.\n    /// * 'axis'(`usize`) - The dimension to reduce.\n    /// * 'keepdims'(`bool`) - If true, retains reduced dimensions with length 1.\n    ///\n    /// ## Panics \n    ///\n    /// * Panics if axis is not in the range of the input tensor's dimensions.\n    ///\n    /// ## Returns \n    ///\n    /// Returns a new `Tensor<T>` instance with the specified axis reduced by summing its elements.\n    ///\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::operators::tensor::FP32x32Tensor;\n    /// use orion::numbers::{FixedTrait, FP32x32};\n    ///\n    /// fn reduce_log_sum_exp() -> Tensor<FP32x32> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(3);\n    ///     shape.append(2);\n    ///     shape.append(2);\n    ///\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP32x32 { mag: 4294967296, sign: false });\n    ///     data.append(FP32x32 { mag: 8589934592, sign: false });\n    ///     data.append(FP32x32 { mag: 12884901888, sign: false });\n    ///     data.append(FP32x32 { mag: 17179869184, sign: false });\n    ///     data.append(FP32x32 { mag: 21474836480, sign: false });\n    ///     data.append(FP32x32 { mag: 25769803776, sign: false });\n    ///     data.append(FP32x32 { mag: 30064771072, sign: false });\n    ///     data.append(FP32x32 { mag: 34359738368, sign: false });\n    ///     data.append(FP32x32 { mag: 38654705664, sign: false });\n    ///     data.append(FP32x32 { mag: 42949672960, sign: false });\n    ///     data.append(FP32x32 { mag: 47244640256, sign: false });\n    ///     data.append(FP32x32 { mag: 51539607552, sign: false });\n    ///     TensorTrait::new(shape.span(), data.span())\n    ///\n    ///     let tensor = TensorTrait::<FP32x32>::new(shape.span(), data.span());\n    ///\n    ///     return tensor.reduce_log_sum_exp(axis: 2, keepdims: false);\n    ///\n    ///  }   \n    ///  \n    ///    \n    /// >>> [[9215828, 16323477, 20115004], [22716772, 24699744, 26302432]]\n    /// ``` \n    ///\n    fn reduce_log_sum_exp(self: @Tensor<T>, axis: usize, keepdims: bool) -> Tensor<T>;\n    /// ## tensor.erf\n    ///\n    /// ```rust \n    ///    fn erf(self: @Tensor<T>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Computes the mean of the input tensor's elements along the provided axes.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` of the same shape as the input tensor with \n    /// the the error function of the input tensor computed element-wise.\n    ///\n    /// ## Type Constraints\n    ///\n    /// Constrain input and output types to fixed point tensors.\n    ///\n    /// ## Examples\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, FP16x16Tensor};\n    /// use orion::numbers::{FixedTrait, FP16x16};\n    /// \n    /// fn erf_example() -> Tensor<FP16x16> {\n    ///     // The erf inputs is [1.0, 0.134, 0.520, 2.0, 3.5, 5.164]\n    ///     let tensor = TensorTrait::<FP16x16>::new(\n    ///         shape: array![6].span(),\n    ///         data: array![\n    ///             FixedTrait::new_unscaled(65536, false),\n    ///             FixedTrait::new_unscaled(8832, false),\n    ///             FixedTrait::new_unscaled(34079, false),\n    ///             FixedTrait::new_unscaled(131072, false),\n    ///             FixedTrait::new_unscaled(229376, false),\n    ///             FixedTrait::new_unscaled(338428, false),\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return tensor.erf();\n    /// }\n    /// >>> [55227,9560,35252,65229,65536,65536]\n    /// ```\n    ///\n    fn erf(self: @Tensor<T>) -> Tensor<T>;\n    /// # tensor.unique\n    ///\n    /// ```rust\n    ///     fn unique(self: @Tensor<T>, axis: Option<usize>, sorted: Option<bool>) -> (Tensor<T>, Tensor<i32>, Tensor<i32>, Tensor<i32>);\n    /// ```\n    ///\n    /// Identifies the unique elements or subtensors of a tensor, with an optional axis parameter for subtensor slicing.\n    /// This function returns a tuple containing the tensor of unique elements or subtensors, and optionally,\n    /// tensors for indices, inverse indices, and counts of unique elements.\n    /// * `axis`(`Option<i32>`) - Specifies the dimension along which to find unique subtensors. A None value means the unique\n    ///                           elements of the tensor will be returned in a flattened form. A negative value indicates\n    ///                           dimension counting from the end.\n    /// * `sorted`(`Option<bool>`) - Determines if the unique elements should be returned in ascending order. Defaults to true.\n    ///\n    /// ## Returns\n    ///\n    /// A tuple containing:\n    /// * A Tensor<T> with unique values or subtensors from self.\n    /// * A Tensor<i32> with the first occurrence indices of unique elements in self. If axis is given, it returns indices\n    ///   along that axis; otherwise, it refers to the flattened tensor.\n    /// * A Tensor<i32> mapping each element of self to its index in the unique tensor. If axis is specified, it maps to\n    ///   the subtensor index; otherwise, it maps to the unique flattened tensor.\n    /// * A Tensor<i32> for the counts of each unique element or subtensor in self.\n    ///\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn unique_flat_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![1, 6].span(), \n    ///         data: array![[2, 1, 1, 3, 4, 3]].span(), \n    ///     );\n    ///\n    ///     return tensor.unique(\n    ///         axis: Option::None(())\n    ///         sorted: Option::Some(false) \n    ///     );\n    /// }\n    /// >>> (\n    ///         [2, 1, 3, 4],\n    ///         [0, 1, 3, 4],\n    ///         [0, 1, 1, 2, 3, 2],\n    ///         [1, 2, 2, 1]\n    ///     )\n    /// ```\n    ///\n    /// or\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn unique_axis_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![3, 3].span(), \n    ///         data: array![[ 1, 0, 0],\n    ///                      [ 1, 0, 0],\n    ///                      [ 2, 3, 4]].span(), \n    ///     );\n    ///\n    ///     return tensor.unique(\n    ///         axis: Option::Some(0)\n    ///         sorted: Option::Some(true) \n    ///     );\n    /// }\n    /// >>> (    \n    ///         [[ 1, 0, 0],\n    ///          [ 2, 3, 4]],\n    ///         [0, 2],\n    ///         [0, 0, 1],\n    ///         [2, 1]\n    ///     )\n    /// ```\n    /// \n    fn unique(\n        self: @Tensor<T>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<T>, Tensor<i32>, Tensor<i32>, Tensor<i32>);\n    /// # tensor.gather_nd\n    ///\n    /// ```rust \n    ///    fn gather_nd(self: @Tensor<T>, indices: Tensor<T>, batch_dims: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Given data tensor of rank r >= 1, indices tensor of rank q >= 1, and batch_dims integer b, this operator gathers slices of data into an output tensor of rank q + r - indices_shape[-1] - 1 - b.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `indices`(`Tensor<T>`) - Tensor of indices.\n    /// * `batch_dims`(`Option<usize>`) -  The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:].\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if index values are not within bounds [-s, s-1] along axis of size s.\n    /// * Panics if If indices_shape[-1] > r-b.\n    /// * Panics if first b dimensions of the shape of indices tensor and data tensor are not equal.\n    ///\n    /// ## Returns\n    /// A new `Tensor<T>`.\n    /// \n    /// ## Example\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn gather_nd_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![2, 2].span(), \n    ///         data: array![[0, 1], [2, 3]].span(), \n    ///     );\n    ///     let indices = TensorTrait::<u32>::new(\n    ///         shape: array![4, 1].span(), \n    ///         data: array![[0], [0], [1], [1]].span(), \n    ///     );\n    /// \n    ///     return tensor.gather_nd(\n    ///         indices: indices, \n    ///         axis: Option::Some((0)), \n    ///     );\n    /// }\n    /// >>> [[0, 1],\n    ///      [0, 1],\n    ///      [2, 3],\n    ///      [2, 3]]\n    /// ```\n    ///\n    fn gather_nd(self: @Tensor<T>, indices: Tensor<usize>, batch_dims: Option<usize>) -> Tensor<T>;\n    /// # tensor.compress\n    ///\n    /// ```rust \n    ///    fn compress(self: @Tensor<T>, condition: Tensor<T>, axis: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index. In case axis is not provided, input is flattened before elements are selected.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `condition`(`Tensor<T>`) - Rank 1 tensor of booleans to indicate which slices or data elements to be selected. Its length can be less than the input length along the axis or the flattened input size if axis is not specified. In such cases data slices or elements exceeding the condition length are discarded.\n    /// * `axis`(`Option<usize>`) - (Optional) Axis along which to take slices. If not specified, input is flattened before elements being selected. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if condition rank is not equal to 1.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` .\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    ///\n    /// fn compress_example() -> Tensor<u32> {\n    ///     let tensor = TensorTrait::<u32>::new(\n    ///         shape: array![3, 2].span(), \n    ///         data: array![[1, 2], [3, 4], [5, 6]].span(), \n    ///     );\n    ///     let condition = TensorTrait::<u32>::new(\n    ///         shape: array![3].span(), \n    ///         data: array![0, 1, 1].span(), \n    ///     );\n    /// \n    ///     return tensor.compress(\n    ///         condition: condition, \n    ///         axis: Option::Some((0)), \n    ///     );\n    /// }\n    /// >>> [[3, 4],\n    ///      [5, 6]]\n    /// ```\n    ///\n    fn compress(self: @Tensor<T>, condition: Tensor<usize>, axis: Option<usize>) -> Tensor<T>;\n    /// # tensor.layer_normalization\n    ///\n    /// ```rust \n    ///    fn layer_normalization(\n    ///     self: @Tensor<T>,\n    ///     scale: @Tensor<T>,\n    ///     B: Option<@Tensor<T>>,\n    ///     axis: Option<i32>,\n    ///     epsilon: Option<T>,\n    ///     stash_type: Option<usize>,\n    /// ) -> (Tensor<T>, Tensor<T>, Tensor<T>);\n    /// ```\n    ///\n    /// Layer normalization of the input, in two stages.\n    /// The first stage is standardization, which makes the normalized elements have zero mean and unit variances.\n    /// The second stage then scales and shifts the outcome of the first stage \n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `scale`(`@Tensor<T>,`) - Scale tensor.\n    /// * `B`(`Option<@Tensor<T>>`) - Bias tensor. \n    /// * `axis`(`Option<i32>`) (default is -1) - The first normalization dimension. If rank(X) is r, axis' allowed range is [-r, r). Negative value means counting dimensions from the back.\n    /// * `epsilon`(`Option<T>`) (default is 0) - The epsilon value to use to avoid division by zero.\n    /// * `stash_type`(`Option<usize>`) - Precise the computation precision - unused the precision is defined by the type of the tensor.\n    /// ## Panics\n    ///\n    /// * Panics if condition rank is not equal to 1.\n    ///\n    /// ## Returns \n    ///\n    /// A new normalized tensor`Tensor<T>`.\n    /// A tensor containing the mean `Tensor<T>`.\n    /// A tensor containing the inverse standard deviation `Tensor<T>`.\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::operators::tensor::FP16x16TensorPartialEq;\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::FP16x16Tensor;\n    /// use orion::numbers::{FixedTrait, FP16x16};\n    /// \n    /// fn layer_normalization_example() -> (Tensor<FP16x16>, Tensor<FP16x16>, Tensor<FP16x16>) {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(3);\n    ///     shape.append(4);\n    /// \n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 41143, sign: true });\n    ///     data.append(FP16x16 { mag: 51803, sign: false });\n    ///     data.append(FP16x16 { mag: 113556, sign: false });\n    ///     data.append(FP16x16 { mag: 64774, sign: false });\n    ///     data.append(FP16x16 { mag: 866, sign: false });\n    ///     data.append(FP16x16 { mag: 698, sign: true });\n    ///     data.append(FP16x16 { mag: 106500, sign: false });\n    ///     data.append(FP16x16 { mag: 98929, sign: false });\n    ///     data.append(FP16x16 { mag: 7551, sign: false });\n    ///     data.append(FP16x16 { mag: 30689, sign: true });\n    ///     data.append(FP16x16 { mag: 38325, sign: false });\n    ///     data.append(FP16x16 { mag: 48164, sign: false });\n    ///     let X = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     let shape = ArrayTrait::<usize>::new();\n    ///     shape.append(4);\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 49855, sign: false });\n    ///     data.append(FP16x16 { mag: 150787, sign: false });\n    ///     data.append(FP16x16 { mag: 83498, sign: true });\n    ///     data.append(FP16x16 { mag: 30346, sign: false });\n    ///     let scale = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///      \n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(4);\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP16x16 { mag: 54864, sign: true });\n    ///     data.append(FP16x16 { mag: 50952, sign: false });\n    ///     data.append(FP16x16 { mag: 8870, sign: true });\n    ///     data.append(FP16x16 { mag: 23216, sign: true });\n    ///     let bias = TensorTrait::new(shape.span(), data.span());\n    /// \n    ///     return X.layer_normalization(@scale,Option::Some(@bias),Option::None,Option::None,Option::None);\n    /// }\n    /// >>> [[-0.48926553  1.0185822  -0.02138367 -0.39223218]\n    ///      [-0.7945549   0.99696046  0.04332176 -0.412645  ]\n    ///      [-0.5664707   0.7491956  -0.7896356  -0.5320859 ]]\n    /// \n    /// ``` \n    ///\n    fn layer_normalization(\n        self: @Tensor<T>,\n        scale: @Tensor<T>,\n        B: Option<@Tensor<T>>,\n        axis: Option<i32>,\n        epsilon: Option<T>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<T>, Tensor<T>, Tensor<T>);\n    /// # tensor.split\n    ///\n    /// ```rust \n    ///    fn split(self: @Tensor<T>, axis: usize, num_outputs: Option<usize>, split: Option<Tensor<usize>>\n    ///    ) -> Array<Tensor<T>>;\n    /// ```\n    /// ## Args\n    /// Split a tensor into a list of tensors, along the specified \u2018axis\u2019\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `axis`(`usize`) - The axis along which to split on.\n    /// * `num_outputs `(Option<usize>) - Number of outputs to split parts of the tensor into. \n    /// * `split  `(Option<Tensor<usize>>) - Optional length of each output.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the 'axis' accepted range is not [-rank, rank-1] where r = rank(input).\n    /// * Panics if the 'split' values not >= 0. Sum of the values is not equal to the dim value at \u2018axis\u2019 specified.\n    /// * Panics if the input 'split' or the attribute 'num_outputs' both are specified or not.\n    ///\n    /// ## Returns\n    ///\n    /// One or more outputs forming list of tensors after splitting.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// use core::option::OptionTrait;\n    /// fn split_tensor_example() -> Array<Tensor<u32>> {\n    ///     let tensor: Tensor<u32> = TensorTrait::<u32>::new(\n    ///         shape: array![2,4].span(), \n    ///         data: array![\n    ///             0, 1, 2, 3, 4, 5, 6, 7\n    ///             ].span(),\n    ///     );\n    ///     let num_outputs = Option::Some(2);\n    ///     // split = Option::Some(array![1, 1].span());\n    ///     let split_num: Option<Tensor<usize>> = Option::None(());\n    ///     // We can call `split` function as follows.\n    ///     return tensor.split(1, num_outputs, split_num);\n    /// }\n    /// >>> [[0,1],[4,5]]\n    ///     [[2,3],[6,7]]\n    /// ```\n    ///\n    fn split(\n        self: @Tensor<T>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<T>>;\n    /// # tensor.reverse_sequence\n    ///\n    /// ```rust\n    ///    fn reverse_sequence(self: @Tensor<T>, sequence_lens: @Tensor<i32>, batch_axis: Option<usize>, time_axis: Option<usize>) -> \n    ///    Tensor<T>;\n    /// ```\n    ///\n    /// Reverse batch of sequences having different lengths specified by sequence_lens.\n    ///\n    /// * `self`(`@Array<Tensor<T>>`) - Tensor of rank r >= 2.\n    /// * `sequence_lens`(`@Tensor<T>`) - Tensor specifying lengths of the sequences in a batch. It has shape [batch_size].\n    /// * `batch_axis`(`Option<usize>`) - (Optional) Specify which axis is batch axis. Must be one of 1 (default), or 0.\n    /// * `time_axis`(`Option<usize>`) - (Optional) Specify which axis is time axis. Must be one of 0 (default), or 1.\n    ///\n    /// ## Panics\n    /// \n    /// * Panics if the 'batch_axis' == 'time_axis'.\n    /// * Panics if the 'batch_axis' and 'time_axis' are not 0 and 1.\n    /// * Panics if the 'sequence_len' exceeding the sequence range.\n    ///\n    /// ## Returns\n    ///\n    /// Tensor with same shape of input.\n    /// \n    /// ## Example\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// use core::option::OptionTrait;\n    /// fn reverse_sequence_example() -> Tensor<u32> {\n    ///     let tensor: Tensor<u32> = TensorTrait::<u32>::new(\n    ///         shape: array![4,4].span(), \n    ///         data: array![\n    ///             0, 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,16\n    ///             ].span(),\n    ///     );\n    ///     let sequence_lens = TensorTrait::<usize>::new(array![4].span(), array![1,2,3,4].span());\n    ///     let batch_axis = Option::Some(0);\n    ///     let time_axis = Option::Some(1);\n    ///     // We can call `split` function as follows.\n    ///     return tensor.reverse_sequence(sequence_lens, batch_axis, time_axis);\n    /// }\n    /// >>> [\n    ///         [0,1,2,3],\n    ///         [5,4,6,7],\n    ///         [10,9,8,11],\n    ///         [15,14,13,12]\n    ///     ] \n    /// ```\n    ///\n    fn reverse_sequence(\n        self: @Tensor<T>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<T>;\n    /// # tensor.scatter_nd\n    ///\n    /// ```rust \n    ///    fn scatter_nd(self: @Tensor<T>, updates: Tensor<T>, indices: Tensor<usize>,  reduction: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Produces a copy of input data, and updates value to values specified by updates at specific index positions specified by indices.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `updates`(`Tensor<T>`) - The updates tensor.\n    /// * `indices`(`Tensor<T>`) - Tensor of indices.\n    /// * `reduction`(`Option<usize>`) - Reduction operation. Default: reduction='none'.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if index values are not within bounds [-s, s-1] along axis of size s.\n    /// * Panics if indices last axis is greater than data rank.\n    ///\n    /// ## Returns \n    ///\n    /// A new `Tensor<T>` .\n    ///\n    /// ## Example\n    ///\n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn scatter_nd_example() -> Tensor<u32> {\n    ///    let tensor = TensorTrait::<u32>::new(\n    ///        shape: array![4, 4, 4].span(), \n    ///        data: array![1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6,\n    ///             7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4,\n    ///             5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8].span()\n    ///    );\n    ///\n    ///    let updates = TensorTrait::<u32>::new(\n    ///        shape: array![2, 4, 4].span(), \n    ///        data: array![5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 1, 1, 1, 1, 2, 2,\n    ///                    2, 2, 3, 3, 3, 3, 4, 4, 4, 4].span(), \n    ///    );\n    ///\n    ///    let indices = TensorTrait::<u32>::new(\n    ///        shape: array![2, 1].span(), \n    ///        data: array![0, 2].span(), \n    ///    );\n    /// \n    ///     return tensor.scatter_nd(\n    ///         updates: updates\n    ///         indices: indices, \n    ///         reduction: Option::Some('add'), \n    ///     );\n    /// }\n    /// >>> [[[ 6.,  7.,  8.,  9.],\n    ///        [11., 12., 13., 14.],\n    ///        [15., 14., 13., 12.],\n    ///        [12., 11., 10.,  9.]],\n    ///\n    ///    [[ 1.,  2.,  3.,  4.],\n    ///        [ 5.,  6.,  7.,  8.],\n    ///        [ 8.,  7.,  6.,  5.],\n    ///        [ 4.,  3.,  2.,  1.]],\n    ///\n    ///    [[ 9.,  8.,  7.,  6.],\n    ///        [ 6.,  5.,  4.,  3.],\n    ///        [ 4.,  5.,  6.,  7.],\n    ///        [ 9., 10., 11., 12.]],\n    ///\n    ///    [[ 8.,  7.,  6.,  5.],\n    ///        [ 4.,  3.,  2.,  1.],\n    ///        [ 1.,  2.,  3.,  4.],\n    ///        [ 5.,  6.,  7.,  8.]]]\n    /// ```\n    ///\n    fn scatter_nd(\n        self: @Tensor<T>, updates: Tensor<T>, indices: Tensor<usize>, reduction: Option<usize>\n    ) -> Tensor<T>;\n    /// # tensor.dynamic_quantize_linear\n    /// \n    /// ```rust\n    /// fn dynamic_quantize_linear(self: @Tensor<T>) -> (Tensor::<Q>, Tensor<T>, Tensor<T>);\n    /// ```\n    /// \n    /// Quantizes a Tensor using dynamic linear quantization.\n    ///\n    /// The dynamic linear quantization operator. It consumes a high precision tensor \n    /// to compute the low precision / quantized tensor dynamicly. \n    /// Right now only uint8 is supported, it saturates to [0, 255].\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<Q>` with the same shape as the input tensor, containing the quantized values.\n    /// * `y_scale`(`@Tensor<T>`) - Scale for doing quantization to get `y`.\n    /// * `y_zero_point`(`@Tensor<T>`) - Zero point for doing quantization to get `y`.\n    ///\n    /// ## Type Constraints\n    ///\n    /// * `T` in (`Tensor<FP>`, `Tensor<i8>`, `Tensor<i32>`, `tensor<u32>`)\n    /// * `Q` in (`Tensor<i32>`)- Constrain `y` to 8-bit unsigned integer tensor.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// \n    /// use orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor};\n    /// use orion::numbers::{u8, i32, IntegerTrait};\n    /// \n    /// fn dynamic_quantize_linear_example() -> (Tensor<u32>, Tensor<FP16x16>, Tensor<FP16x16>) {\n    ///     // We instantiate a 1D Tensor here.\n    ///     let x = TensorTrait::<FP16x16>::new(\n    ///         shape: array![6].span(),\n    ///         data: array![\n    ///             FP16x16 { mag: 10945, sign: false },\n    ///             FP16x16 { mag: 190054, sign: false },\n    ///             FP16x16 { mag: 196608, sign: false },\n    ///             FP16x16 { mag: 229376, sign: false },\n    ///             FP16x16 { mag: 196608, sign: true },\n    ///             FP16x16 { mag: 229376, sign: true },\n    ///         ]\n    ///             .span(),\n    ///     );\n    /// \n    ///     return x.dynamic_quantize_linear();\n    /// }\n    /// >>> ([133, 233, 236, 255, -18, -0], [0.02745], [128]\n    /// ```\n    ///\n    fn dynamic_quantize_linear(self: @Tensor<T>) -> (Tensor<u32>, Tensor<T>, Tensor<T>);\n    /// # tensor.optional\n    ///\n    /// ```rust \n    ///    fn optional(self: @Tensor<T>) -> Option<Tensor<T>>;\n    /// ```\n    ///\n    /// Constructs an optional-type value containing either an empty optional of a certain \n    /// type specified by the attribute, or a non-empty value containing the input element.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    ///\n    /// ## Returns\n    ///\n    /// The optional output enclosing the input element.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::option::OptionTrait;\n    /// fn optional_example() -> Option<Tensor<T>> {\n    ///     let a = TensorTrait::<\n    ///         FP16x16\n    ///     >::new(\n    ///         shape: array![4, 2].span(),\n    ///         data: array![\n    ///            1_i8,\n    ///            2_i8,\n    ///            3_i8,\n    ///            4_i8,\n    ///            5_i8,\n    ///            6_i8,\n    ///            7_i8,\n    ///            8_i8\n    ///         ].span(),\n    ///     );\n    ///     a.optional()\n    /// }\n    /// >>> Option[Tensor[1,2,3,4,5,6,7,8]]\n    ///     \n    /// ```\n    ///\n    fn optional(self: @Tensor<T>) -> Option<Tensor<T>>;\n    /// # tensor.split_to_sequence\n    ///\n    /// ```rust \n    ///    fn split_to_sequence(\n    ///        self: @Tensor<T>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ///    ) -> Array<Tensor<T>>;\n    /// ```\n    ///\n    /// Split a tensor into a sequence of tensors, along the specified \u2018axis\u2019\n    ///\n    ///\n    /// ## Args\n    /// * `self`(`@Tensor<T>`) - The input tensor to split.\n    /// * `axis`(`usize`) - The axis along which to split on.\n    /// * `keepdims  `(`usize`) - Keep the split dimension or not. If input \u2018split\u2019 is specified, this attribute is ignored.\n    /// * `split  `(`Option<Tensor<usize>>`) - Length of each output. It can be either a scalar(tensor of empty shape), or a 1-D tensor. All values must be >= 0.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the 'axis' accepted range is not [-rank, rank-1] where r = rank(input).\n    /// * Panics if the 'split' is not either a scalar (tensor of empty shape), or a 1-D tensor.\n    ///\n    /// ## Returns\n    ///\n    /// One or more outputs forming a sequence of tensors after splitting.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// use core::option::OptionTrait;\n    /// fn split_to_sequence_example() -> Array<Tensor<u32>> {\n    ///     let tensor: Tensor<u32> = TensorTrait::<u32>::new(\n    ///         shape: array![2,4].span(), \n    ///         data: array![\n    ///             0, 1, 2, 3, 4, 5, 6, 7\n    ///             ].span(),\n    ///     );\n    ///     let num_outputs = Option::Some(2);\n    ///     // let split = Option::Some(TensorTrait::new(array![1].span(), array![2].span()));\n    ///     let split: Option<Tensor<usize>> = Option::Some(TensorTrait::new(array![2].span(), array![2, 2].span()));\n    ///     // We can call `split_to_sequence` function as follows.\n    ///     return tensor.split_to_sequence(1, 1, split);\n    /// }\n    /// >>> [\n    ///         [[0,1],[4,5]],\n    ///         [[2,3],[6,7]]\n    ///     ]\n    /// ```\n    ///\n    fn split_to_sequence(\n        self: @Tensor<T>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<T>>;\n    /// # tensor.range\n    ///\n    /// ```rust \n    ///    fn range(start: T, end: T, step: T) -> Tensor<T>;\n    /// ```\n    ///\n    /// Generate a tensor containing a sequence of numbers that begin at start and extends by increments of delta up to limit (exclusive).\n    /// \n    ///\n    /// * `start`(`T`) - First entry for the range of output values.\n    /// * `end`(`T`) - Exclusive upper limit for the range of output values.\n    /// * `step `(`T`) - Value to step by.\n    ///\n    /// ## Returns\n    ///\n    /// A 1-D tensor with same type as the inputs containing generated range of values.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::I32TensorPartialEq;\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::operators::tensor::{I32Tensor, I32TensorAdd};\n    /// use orion::utils::{assert_eq, assert_seq_eq};\n    /// use orion::numbers::NumberTrait;\n    ///\n    ///\n    /// fn range_example() -> Tensor<i32> {\n    ///     return TensorTrait::range(21,2,-3);\n    /// }\n    /// >>> [21 18 15 12  9  6  3]\n    /// ```\n    /// \n    fn range(start: T, end: T, step: T) -> Tensor<T>;\n    /// # tensor.hann_window\n    ///\n    /// ```rust \n    ///    fn hann_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Generates a Hann window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n    /// \n    ///\n    /// * `size`(`T`) - A scalar value indicating the length of the window.\n    /// * `periodic`(Option<usize>) - If 1, returns a window to be used as periodic function. If 0, return a symmetric window. When 'periodic' is specified, hann computes a window of length size + 1 and returns the first size points. The default value is 1.\n    ///\n    /// ## Returns\n    ///\n    /// A Hann window with length: size. The output has the shape: [size].\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::FP8x23TensorPartialEq;\n    /// use orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::utils::{assert_eq, assert_seq_eq};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    ///\n    ///\n    /// fn hann_window_example() -> Tensor<FP8x23> {\n    ///     return TensorTrait::hann_window(FP8x23 { mag: 33554432, sign: false }, Option::Some(0));  // size: 4\n    /// }\n    /// >>> [0  6291455  6291456  0]\n    /// ```\n    /// \n    fn hann_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// # tensor.hamming_window\n    ///\n    /// ```rust \n    ///    fn hamming_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Generates a Hamming window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n    /// \n    ///\n    /// * `size`(`T`) - A scalar value indicating the length of the window.\n    /// * `periodic`(Option<usize>) - If 1, returns a window to be used as periodic function. If 0, return a symmetric window. When 'periodic' is specified, hann computes a window of length size + 1 and returns the first size points. The default value is 1.\n    ///\n    /// ## Returns\n    ///\n    /// A Hamming window with length: size. The output has the shape: [size].\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::FP8x23TensorPartialEq;\n    /// use orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::utils::{assert_eq, assert_seq_eq};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    ///\n    ///\n    /// fn hamming_window_example() -> Tensor<FP8x23> {\n    ///     return TensorTrait::hamming_window(FP8x23 { mag: 33554432, sign: false }, Option::Some(0));  // size: 4\n    /// }\n    /// >>> [729444  6473817  6473817  729444]\n    /// ```\n    /// \n    fn hamming_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// # tensor.blackman_window\n    ///\n    /// ```rust \n    ///    fn blackman_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// Generates a Blackman window as described in the paper https://ieeexplore.ieee.org/document/1455106.\n    /// \n    ///\n    /// * `size`(`T`) - A scalar value indicating the length of the window.\n    /// * `periodic`(Option<usize>) - If 1, returns a window to be used as periodic function. If 0, return a symmetric window. When 'periodic' is specified, hann computes a window of length size + 1 and returns the first size points. The default value is 1.\n    ///\n    /// ## Returns\n    ///\n    /// A Blackman window with length: size. The output has the shape: [size].\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::FP8x23TensorPartialEq;\n    /// use orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::utils::{assert_eq, assert_seq_eq};\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    ///\n    ///\n    /// fn blackman_window_example() -> Tensor<FP8x23> {\n    ///     return TensorTrait::blackman_window(FP8x23 { mag: 33554432, sign: false }, Option::Some(0));  // size: 4\n    /// }\n    /// >>> [0  0.36  0.36  0]\n    /// ```\n    /// \n    fn blackman_window(size: T, periodic: Option<usize>) -> Tensor<T>;\n    /// # TensorTrait::random_uniform_like\n    /// \n    /// ```rust\n    ///         fn random_uniform_like(tensor: @Tensor<T>, high: Option<T>, low: Option<T>, seed: Option<usize>) -> Tensor<T>;\n    /// ```\n    ///\n    /// RandomUniformLike generates a tensor with random values using a uniform distribution, matching the shape of the input tensor.\n    ///\n    /// This operation creates a new tensor with the same shape as the input tensor, where each element is initialized with a random value sampled from a uniform distribution.\n    ///\n    /// ## Args\n    ///\n    /// * `tensor`(`@Tensor<T>`) - The input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.\n    /// * `high`(Option<T>) - An optional parameter specifying the upper bound (exclusive) of the uniform distribution. If not provided, defaults to 1.0.\n    /// * `low`(Option<T>) - An optional parameter specifying the lower bound (inclusive) of the uniform distribution. If not provided, defaults to 0.0.\n    /// * `seed`(Option<usize>) - An optional parameter specifying the seed for the random number generator. If not provided, a random seed will be used.\n    ///\n    /// ## Returns\n    /// \n    /// * A `Tensor<T>` with the same shape as the input tensor, filled with random values from a uniform distribution within the specified range.\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\n    /// use core::array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::{TensorTrait, Tensor};\n    /// use orion::utils::{assert_eq, assert_seq_eq};\n    /// use orion::operators::tensor::FP8x23TensorPartialEq;\n    /// use orion::numbers::{FixedTrait, FP8x23};\n    ///\n    ///\n    /// fn example() -> Tensor<FP8x23> {\n    ///     let mut shape = ArrayTrait::<usize>::new();\n    ///     shape.append(1);\n    ///     shape.append(8);\n    ///     shape.append(1);\n    ///     shape.append(2);\n    ///\n    ///     let mut data = ArrayTrait::new();\n    ///     data.append(FP8x23 { mag: 70016, sign: true });\n    ///     data.append(FP8x23 { mag: 57536, sign: false });\n    ///     data.append(FP8x23 { mag: 116032, sign: false });\n    ///     data.append(FP8x23 { mag: 162944, sign: true });\n    ///     data.append(FP8x23 { mag: 43360, sign: false });\n    ///     data.append(FP8x23 { mag: 128960, sign: false });\n    ///     data.append(FP8x23 { mag: 151808, sign: true });\n    ///     data.append(FP8x23 { mag: 28368, sign: false });\n    ///     data.append(FP8x23 { mag: 21024, sign: false });\n    ///     data.append(FP8x23 { mag: 24992, sign: false });\n    ///     data.append(FP8x23 { mag: 125120, sign: true });\n    ///     data.append(FP8x23 { mag: 79168, sign: true });\n    ///     data.append(FP8x23 { mag: 136960, sign: true });\n    ///     data.append(FP8x23 { mag: 10104, sign: true });\n    ///     data.append(FP8x23 { mag: 136704, sign: false });\n    ///     data.append(FP8x23 { mag: 184960, sign: true });\n    ///     let tensor = TensorTrait::new(shape.span(), data.span());\n    ///     return TensorTrait::random_uniform_like(@tensor, Option::Some(FP8x23 { mag: 83886080, sign: false }),Option::Some(FP8x23 { mag: 8388608, sign: false }), Option::Some(354145));\n    /// }\n    /// >>> [[[[7299130, 4884492]], [[2339070, 1559536]], [[3448557, 984617]], [[5745934, 3670947]], [[4665989, 3079292]], [[3375288, 948254]], [[3749966, 4911069]], [[1358829, 4368105]]]]\n    /// ```\n    ///\n    fn random_uniform_like(\n        tensor: @Tensor<T>, high: Option<T>, low: Option<T>, seed: Option<usize>\n    ) -> Tensor<T>;\n    /// # tensor.label_encoder\n    /// \n    /// ```rust\n    /// fn label_encoder(self: @Tensor<T>, default_list: Option<Span<T>>, default_tensor: Option<Tensor<T>>, keys: Option<Span<T>>, keys_tensor: Option<Tensor<T>>, values: Option<Span<T>>, values_tensor: Option<Tensor<T>>) -> Tensor<T>;\n    /// ```\n    /// \n    /// Maps each element in the input tensor to another value.\n    ///\n    /// The mapping is determined by the two parallel attributes, 'keys_' and 'values_' attribute. \n    /// The i-th value in the specified 'keys_' attribute would be mapped to the i-th value in the specified 'values_' attribute.\n    ///  It implies that input's element type and the element type of the specified 'keys_' should be identical while the output type is identical to the specified 'values_' attribute.\n    ///\n    /// ## Args\n    ///\n    /// * `self`(`@Tensor<T>`) - The input tensor.\n    /// * `default_list`(`Option<Span<T>>`) - The default span.\n    /// * `default_tensor`(`Option<Tensor<T>>`) - The default tensor.\n    /// * `keys`(`Option<Span<T>>`) - The keys span.\n    /// * `keys_tensor`(`Option<Tensor<T>>`) - The keys tensor.\n    /// * `values`(` Option<Span<T>>`) - The values span.\n    /// * `values_tensor`(`Option<Tensor<T>>`) - The values tensor.\n    ///\n    /// One and only one of 'default_*'s should be set\n    /// One and only one of 'keys*'s should be set\n    ///  One and only one of 'values*'s should be set.\n    ///\n    /// ## Panics\n    ///\n    /// * Panics if the len/shape of keys and values are not the same.\n    ///\n    /// ## Returns\n    ///\n    /// A new `Tensor<T>` which maps each element in the input tensor to another value..\n    ///\n    /// ## Type Constraints\n    ///\n    /// * `T` in (`Tensor<FP>`, `Tensor<i8>`, `Tensor<i32>`, `tensor<u32>,`)\n    ///\n    /// ## Examples\n    /// \n    /// ```rust\n    /// use array::{ArrayTrait, SpanTrait};\n    /// use orion::operators::tensor::U32Tensor;\n    /// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n    /// \n    /// fn label_encoder_example() -> Tensor<T>,  {\n    ///    fn data() -> Tensor<u32> {\n    ///        let mut sizes = ArrayTrait::new();\n    ///        sizes.append(2);\n    ///        sizes.append(3);\n    ///        let mut data = ArrayTrait::new();\n    ///        data.append(1);\n    ///        data.append(2);\n    ///        data.append(3);\n    ///        data.append(1);\n    ///        data.append(4);\n    ///        data.append(5);\n    ///\n    ///        let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n    ///        return tensor;\n    ///    }\n    ///\n    ///    fn keys() -> Tensor<u32> {\n    ///        let mut sizes = ArrayTrait::new();\n    ///        sizes.append(3);\n    ///        sizes.append(1);\n    ///\n    ///        let mut data = ArrayTrait::new();\n    ///        data.append(1);\n    ///        data.append(2);\n    ///        data.append(1);\n    ///\n    ///        let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n    ///        return tensor;\n    ///    }\n    ///\n    ///    fn values() -> Tensor<u32> {\n    ///        let mut sizes = ArrayTrait::new();\n    ///        sizes.append(3);\n    ///        sizes.append(1);\n    ///\n    ///        let mut data = ArrayTrait::new();\n    ///        data.append(8);\n    ///        data.append(9);\n    ///        data.append(7);\n    ///\n    ///        let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n    ///        return tensor;\n    ///    }\n    ///\n    ///    fn default() -> Tensor<u32> {\n    ///        let mut sizes = ArrayTrait::new();\n    ///        sizes.append(1);\n    ///\n    ///        let mut data = ArrayTrait::new();\n    ///        data.append(999);\n    ///\n    ///        let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n    ///        return tensor;\n    ///    }\n    ///\n    ///    let data = data();\n    ///    let keys = keys();\n    ///    let values = values();\n    ///    let default = default();\n    ///    return data.label_encoder(default_list: Option::None, default_tensor: Option::Some(default),\n    ///         keys: Option::None, keys_tensor: Option::Some(keys),  \n    ///         values: Option::None, values_tensor: Option::Some(values));\n    /// >>> [7, 9, 999, 7, 999, 999],\n    /// ```\n    ///\n    fn label_encoder(\n        self: @Tensor<T>,\n        default_list: Option<Span<T>>,\n        default_tensor: Option<Tensor<T>>,\n        keys: Option<Span<T>>,\n        keys_tensor: Option<Tensor<T>>,\n        values: Option<Span<T>>,\n        values_tensor: Option<Tensor<T>>\n    ) -> Tensor<T>;\n}\n\n/// Cf: TensorTrait::new docstring\nfn new_tensor<T>(shape: Span<usize>, data: Span<T>) -> Tensor<T> {\n    check_shape::<T>(shape, data);\n    Tensor::<T> { shape, data }\n}\n\n/// Cf: TensorTrait::constant_of_shape docstring\nfn constant_of_shape<T, impl FCopy: Copy<T>, impl FDrop: Drop<T>,>(\n    shape: Span<usize>, value: T\n) -> Tensor<T> {\n    let mut data = ArrayTrait::new();\n\n    let mut length = len_from_shape(shape);\n\n    loop {\n        match length.into() {\n            0 => { break (); },\n            _ => {\n                data.append(value.clone());\n                length -= 1;\n            }\n        }\n    };\n\n    Tensor::<T> { shape, data: data.span() }\n}\n\n/// Cf: TensorTrait::ravel_index docstring\nfn ravel_index(mut shape: Span<usize>, mut indices: Span<usize>) -> usize {\n    assert(shape.len() == indices.len(), 'shape & indices length unequal');\n\n    let mut raveled_index: usize = 0;\n    let mut stride: usize = 1;\n\n    loop {\n        match shape.pop_back() {\n            Option::Some(i) => {\n                let index = *indices.pop_back().unwrap();\n                raveled_index += index * stride;\n\n                stride *= *i;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    raveled_index\n}\n\n/// Cf: TensorTrait::unravel_index docstring\nfn unravel_index(index: usize, mut shape: Span<usize>) -> Span<usize> {\n    assert(shape.len() > 0, 'shape cannot be empty');\n\n    let mut result = ArrayTrait::new();\n    let mut remainder = index;\n    let mut stride = len_from_shape(shape);\n\n    loop {\n        match shape.pop_front() {\n            Option::Some(i) => {\n                stride /= *i;\n\n                let coord = remainder / stride;\n                remainder = remainder % stride;\n\n                result.append(coord);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    return result.span();\n}\n\n/// Cf: TensorTrait::stride docstring\nfn stride(mut shape: Span<usize>) -> Span<usize> {\n    let mut strides = ArrayTrait::new();\n    let mut stride = 1;\n    loop {\n        match shape.pop_back() {\n            Option::Some(size) => {\n                strides.append(stride);\n                stride *= *size;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    strides.reverse().span()\n}\n\n\n/// Cf: TensorTrait::reshape docstring\nfn reshape<T, +Copy<Tensor<T>>>(\n    self: @Tensor<T>, target_shape: Span<i32>, allowzero: bool\n) -> Tensor<T> {\n    // Calculate the total number of elements in the original tensor\n    let mut total_elements = 1;\n    let mut shape = *self.shape;\n    loop {\n        match shape.pop_front() {\n            Option::Some(val) => total_elements *= *val,\n            Option::None => { break; }\n        };\n    };\n\n    // Calculate 'elements_so_far' and find 'inferred_index'\n    let mut elements_so_far = 1;\n    let mut inferred_index = Option::None;\n    let mut target_shape_clone = target_shape.clone();\n    let mut i: usize = 0;\n    loop {\n        match target_shape_clone.pop_front() {\n            Option::Some(dim) => {\n                if *dim == -1 {\n                    if inferred_index.is_none() {\n                        inferred_index = Option::Some(i);\n                    } else {\n                        panic!(\"Only one dimension can be inferred\");\n                    }\n                } else if *dim == 0 && allowzero == false {\n                    // When allowzero is not set, copy the dimension size from the original tensor\n                    if i >= (*self.shape).len() {\n                        panic!(\"Dimension out of bounds for using original dimension value\");\n                    }\n                    elements_so_far *= *(*self).shape.at(i);\n                } else if *dim >= 0 {\n                    elements_so_far *= (*dim).try_into().unwrap();\n                } else {\n                    panic!(\"Invalid dimension size\");\n                };\n            },\n            Option::None => { break; }\n        };\n        i += 1;\n    };\n\n    let mut target_shape_clone = target_shape.clone();\n    let mut inferred_shape = ArrayTrait::<u32>::new();\n    i = 0; // Reset the index for the next loop\n    loop {\n        match target_shape_clone.pop_front() {\n            Option::Some(dim) => {\n                if *dim == -1 {\n                    inferred_shape.append(total_elements / elements_so_far) // Inferred dimension\n                } else if *dim == 0 {\n                    if allowzero == true {\n                        inferred_shape\n                            .append(\n                                0\n                            ) // Explicitly set the dimension to zero when allowzero is enabled\n                    } else if i < (*self.shape).len() {\n                        inferred_shape\n                            .append(\n                                *(*self).shape.at(i)\n                            ) // Dimension unchanged from original when allowzero is not enabled\n                    } else {\n                        panic!(\"Dimension out of bounds for using original dimension value\");\n                    }\n                } else {\n                    inferred_shape\n                        .append((*dim).try_into().unwrap()) // Directly specified dimension\n                };\n            },\n            Option::None => { break; }\n        }\n        i += 1;\n    };\n\n    new_tensor(inferred_shape.span(), *self.data)\n}\n\n/// Cf: TensorTrait::at docstring\nfn at_tensor<T>(self: @Tensor<T>, indices: Span<usize>) -> @T {\n    assert(indices.len() == (*self.shape).len(), 'indices not match dimensions');\n    let data = *self.data;\n\n    return data.at(ravel_index(*self.shape, indices));\n}\n\n// Return true if two tensor are equal\nfn tensor_eq<T, impl TPartialEq: PartialEq<T>>(mut lhs: Tensor<T>, mut rhs: Tensor<T>,) -> bool {\n    let mut is_eq = true;\n\n    loop {\n        if lhs.shape.len() == 0 || !is_eq {\n            break;\n        }\n\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    loop {\n        if lhs.data.len() == 0 || !is_eq {\n            break;\n        }\n\n        is_eq = lhs.data.pop_front().unwrap() == rhs.data.pop_front().unwrap();\n    };\n\n    return is_eq;\n}\n\n/// Cf: TensorTrait::slice docstring\nfn slice<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: @Tensor<T>,\n    starts: Span<usize>,\n    ends: Span<usize>,\n    axes: Option<Span<usize>>,\n    steps: Option<Span<usize>>\n) -> Tensor<T> {\n    let axes = match axes {\n        Option::Some(axes) => axes,\n        Option::None => {\n            let mut ret: Array<usize> = ArrayTrait::new();\n            let mut i: usize = 0;\n            let stop_i = starts.len() - 1;\n            loop {\n                ret.append(i);\n                if i == stop_i {\n                    break ();\n                }\n                i += 1;\n            };\n            ret.span()\n        },\n    };\n    let steps = match steps {\n        Option::Some(steps) => steps,\n        Option::None => {\n            let mut ret: Array<usize> = ArrayTrait::new();\n            let mut i: usize = 0;\n            let stop_i = starts.len() - 1;\n            loop {\n                ret.append(1);\n                if i == stop_i {\n                    break ();\n                }\n                i += 1;\n            };\n            ret.span()\n        },\n    };\n    assert(starts.len() == ends.len(), 'Ends and starts len unequal');\n    assert(starts.len() == axes.len(), 'Axes and starts len unequal');\n    assert(starts.len() == steps.len(), 'Steps and starts len unequal');\n\n    let mut is_empty: bool = false;\n    let mut output_shape: Array<usize> = ArrayTrait::new();\n    let mut processed_starts: Array<usize> = ArrayTrait::new();\n    let mut processed_ends: Array<usize> = ArrayTrait::new();\n    let mut processed_steps: Array<usize> = ArrayTrait::new();\n\n    let mut shape = *self.shape;\n    let mut i: usize = 0;\n    loop {\n        match shape.pop_front() {\n            Option::Some(ele) => {\n                let (axis_index, is_found) = match axes.index_of(i) {\n                    Option::Some(axis_index) => (axis_index, true),\n                    Option::None => (0, false),\n                };\n\n                let mut processed_params = (0, 0, 0, 0);\n                if is_found {\n                    let mut start: usize = *ele;\n                    let mut end: usize = *ele;\n\n                    if *starts.at(axis_index) < *ele {\n                        start = *starts.at(axis_index);\n                    }\n\n                    if *ele > *ends.at(axis_index) {\n                        end = *ends.at(axis_index);\n                    };\n\n                    if start > *ele {\n                        start = *ele;\n                    };\n\n                    if end > *ele {\n                        end = *ele;\n                    };\n\n                    if start >= end {\n                        is_empty = true;\n                    } else {\n                        let dim = (end - start + (*steps.at(axis_index) - 1))\n                            / *steps.at(axis_index);\n\n                        if dim == 0 {\n                            is_empty = true;\n                        } else {\n                            processed_params = (start, end, *steps.at(axis_index), dim);\n                        };\n                    };\n                } else {\n                    processed_params = (0, *ele, 1, *ele);\n                }\n\n                let (start, end, step, shape) = processed_params;\n                processed_starts.append(start);\n                processed_ends.append(end);\n                processed_steps.append(step);\n                output_shape.append(shape);\n\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_data: Array<T> = ArrayTrait::new();\n\n    if is_empty {\n        return Tensor::<T> { shape: output_shape.span(), data: output_data.span() };\n    }\n\n    let mut data = *self.data;\n    let mut j: usize = 0;\n    loop {\n        match data.pop_front() {\n            Option::Some(ele) => {\n                let mut indices = unravel_index(j, *self.shape);\n                let mut is_included = false;\n\n                let mut shape = *self.shape;\n                let mut starts = processed_starts.span();\n                let mut ends = processed_ends.span();\n                let mut steps = processed_steps.span();\n                loop {\n                    match shape.pop_front() {\n                        Option::Some => {\n                            let start = *starts.pop_front().unwrap();\n                            let end = *ends.pop_front().unwrap();\n                            let step = *steps.pop_front().unwrap();\n                            let index = *indices.pop_front().unwrap();\n\n                            if index < start || index >= end {\n                                is_included = false;\n                                break ();\n                            }\n                            if (index - start) % step == 0 {\n                                is_included = true;\n                            } else {\n                                is_included = false;\n                                break ();\n                            }\n                        },\n                        Option::None => { break; }\n                    };\n                };\n\n                if is_included {\n                    output_data.append(*ele);\n                }\n\n                j += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    return TensorTrait::new(output_shape.span(), output_data.span());\n}\n\n/// Cf: TensorTrait::nonzero docstring\nfn nonzero<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TDrop: Drop<T>,\n    impl TCopy: Copy<T>,\n    impl TNumber: NumberTrait<T, MAG>\n>(\n    self: @Tensor<T>\n) -> Tensor<usize> {\n    let mut indexes_of_dimensions: Array<usize> = ArrayTrait::new();\n    let mut self_data_copy = *self.data;\n    let mut j: usize = 0;\n\n    loop {\n        match self_data_copy.pop_front() {\n            Option::Some(val) => {\n                if *val != NumberTrait::zero() {\n                    let indices = unravel_index(j, *self.shape);\n                    let mut i: usize = 0;\n\n                    let mut self_shape_copy = *self.shape;\n                    loop {\n                        match self_shape_copy.pop_front() {\n                            Option::Some => {\n                                indexes_of_dimensions.append(*indices.at(i));\n                                i += 1;\n                            },\n                            Option::None => { break (); }\n                        };\n                    };\n                }\n                j += 1;\n            },\n            Option::None => { break (); }\n        };\n    };\n\n    let indexes_of_dimensions_span = indexes_of_dimensions.span();\n    let mut output_data: Array<usize> = ArrayTrait::new();\n\n    if indexes_of_dimensions_span.len() == 0 {\n        return Tensor::<\n            usize\n        > { shape: array![(*self.shape).len(), 0].span(), data: output_data.span() };\n    }\n\n    let stop_k = (indexes_of_dimensions_span.len() / (*self.shape).len()) - 1;\n    let mut self_shape_copy = *self.shape;\n    let mut i: usize = 0;\n\n    loop {\n        match self_shape_copy.pop_front() {\n            Option::Some => {\n                let mut k: usize = 0;\n\n                loop {\n                    output_data.append(*indexes_of_dimensions_span.at((*self.shape).len() * k + i));\n\n                    if k == stop_k {\n                        break ();\n                    }\n                    k += 1;\n                };\n                i += 1;\n            },\n            Option::None => { break (); }\n        };\n    };\n\n    return Tensor::<\n        usize\n    > { shape: array![(*self.shape).len(), stop_k + 1].span(), data: output_data.span() };\n}\n\n/// Cf: TensorTrait::squeeze docstring\nfn squeeze<T>(self: @Tensor<T>, axes: Option<Span<u32>>) -> Tensor<T> {\n    let target_shape = match axes {\n        Option::Some(mut axes) => {\n            let mut axis_squeezed = 0;\n            let mut shape = *self.shape;\n            loop {\n                match axes.pop_front() {\n                    Option::Some(axis) => {\n                        let mut reshape: Array<usize> = ArrayTrait::new();\n                        let mut index = 0;\n                        let axis = if *axis < 0 {\n                            assert(\n                                *axis <= (*self.shape).len().into(), 'axis out of accepted range'\n                            );\n                            (*self.shape).len().into() - *axis\n                        } else {\n                            assert(\n                                *axis < (*self.shape).len().into(), 'axis out of accepted range'\n                            );\n                            *axis\n                        };\n\n                        loop {\n                            match shape.pop_front() {\n                                Option::Some(shape) => {\n                                    let squeezed = if axis >= axis_squeezed {\n                                        axis - axis_squeezed\n                                    } else {\n                                        axis\n                                    };\n                                    if index == squeezed {\n                                        assert(*shape == 1, 'shape entry not equal to one');\n                                        axis_squeezed += 1;\n                                    } else {\n                                        reshape.append(*shape);\n                                    }\n                                },\n                                Option::None => { break; },\n                            };\n                            index += 1;\n                        };\n                        shape = reshape.span();\n                    },\n                    Option::None => { break shape; },\n                };\n            }\n        },\n        Option::None => {\n            let mut reshape: Array<usize> = ArrayTrait::new();\n            let mut shape = *self.shape;\n            loop {\n                match shape.pop_front() {\n                    Option::Some(shape) => { if *shape != 1 {\n                        reshape.append(*shape);\n                    } },\n                    Option::None => { break reshape.span(); },\n                };\n            }\n        },\n    };\n\n    return Tensor::<T> { shape: target_shape, data: *self.data };\n}\n/// Cf: TensorTrait::unsqueeze docstring\nfn unsqueeze<T>(self: @Tensor<T>, axes: Span<usize>) -> Tensor<T> {\n    let dedupped_array = axes.dedup();\n    assert(dedupped_array.len() == axes.len(), 'Duplicated input axes');\n\n    let mut self_shape_copy = *self.shape;\n    let mut i: usize = 0;\n    let mut added_axes_count: usize = 0;\n    let mut output_shape: Array<usize> = ArrayTrait::new();\n    loop {\n        if axes.contains(i + added_axes_count) {\n            output_shape.append(1);\n            added_axes_count += 1;\n        } else {\n            match self_shape_copy.pop_front() {\n                Option::Some(val) => {\n                    output_shape.append(*val);\n                    i += 1;\n                },\n                Option::None => { break (); }\n            };\n        };\n    };\n\n    let mut j: usize = output_shape.len();\n    loop {\n        if axes.contains(j) {\n            output_shape.append(1);\n        } else {\n            break ();\n        }\n        j += 1;\n    };\n    assert(output_shape.len() == axes.len() + (*self.shape).len(), 'Invalid input axes');\n\n    return Tensor::<T> { shape: output_shape.span(), data: *self.data };\n}\n\n/// Cf: TensorTrait::sign docstring\nfn sign<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TDrop: Drop<T>,\n    impl TCopy: Copy<T>,\n>(\n    self: @Tensor<T>\n) -> Tensor<T> {\n    let mut sign_data_array: Array<T> = ArrayTrait::new();\n    let mut data = *self.data;\n\n    loop {\n        match data.pop_front() {\n            Option::Some(data) => {\n                let sign_data = if *data == NumberTrait::zero() {\n                    NumberTrait::zero()\n                } else if NumberTrait::is_neg(*data) {\n                    NumberTrait::neg_one()\n                } else {\n                    NumberTrait::one()\n                };\n                sign_data_array.append(sign_data);\n            },\n            Option::None => {\n                break Tensor::<T> { shape: *self.shape, data: sign_data_array.span() };\n            }\n        };\n    }\n}\n\n/// Cf: TensorTrait::clip docstring\nfn clip<\n    T,\n    MAG,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TTensor: TensorTrait<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>\n>(\n    self: @Tensor<T>, min: Option<T>, max: Option<T>\n) -> Tensor<T> {\n    let min = match min {\n        Option::Some(min) => min,\n        Option::None => { NumberTrait::min_value() },\n    };\n    let max = match max {\n        Option::Some(max) => max,\n        Option::None => { NumberTrait::max_value() },\n    };\n\n    let mut return_data: Array<T> = ArrayTrait::new();\n    let mut self_data_copy = *self.data;\n\n    loop {\n        match self_data_copy.pop_front() {\n            Option::Some(val) => {\n                if *val < min {\n                    return_data.append(min);\n                } else if *val > max {\n                    return_data.append(max);\n                } else {\n                    return_data.append(*val);\n                }\n            },\n            Option::None => { break (); }\n        };\n    };\n\n    return Tensor::<T> { shape: *self.shape, data: return_data.span() };\n}\n\n/// Cf: TensorTrait::identity docstring\nfn identity<T>(self: @Tensor<T>) -> Tensor<T> {\n    Tensor::<T> { shape: *self.shape, data: *self.data }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/helpers.cairo",
        "content": "use alexandria_data_structures::array_ext::ArrayTraitExt;\n\nuse orion::utils::u32_max;\nuse orion::operators::tensor::{core::{Tensor, TensorTrait, stride}, BoolTensor};\n\n/// Calculates the number of elements in a tensor given its shape.\n///\n/// # Arguments\n/// * `shape` - A span containing the shape of the tensor as usize elements.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize representing the number of elements in the tensor.\nfn len_from_shape(mut shape: Span<usize>) -> usize {\n    let mut result: usize = 1;\n\n    loop {\n        match shape.pop_front() {\n            Option::Some(item) => { result *= *item; },\n            Option::None => { break; }\n        };\n    };\n\n    result\n}\n\n/// Verifies if the shape and the data array of a tensor are compatible.\n///\n/// # Arguments\n/// * `shape` - A span containing the shape of the tensor as usize elements.\n/// * `data` -  A span containing the data elements of generic type T.\n///\n/// # Panics\n/// * Panics if the shape and data array are incompatible.\nfn check_shape<T>(shape: Span<usize>, data: Span<T>) {\n    assert(len_from_shape(shape) == data.len(), 'wrong tensor shape');\n}\n\n/// Checks if two tensor shapes are compatible for broadcasting.\n///\n/// # Arguments\n/// * `shape_1` - A span containing the first tensor's shape as usize elements.\n/// * `shape_2` - A span containing the second tensor's shape as usize elements.\n///\n/// # Panics\n/// * Panics if the shapes are not compatible for broadcasting.\nfn check_compatibility(mut shape_1: Span<usize>, mut shape_2: Span<usize>) {\n    // Start from the last dimension by getting the length of each shape\n    let mut iter_1 = shape_1.len();\n    let mut iter_2 = shape_2.len();\n\n    // Iterate while there are dimensions left in either shape\n    while iter_1 > 0 || iter_2 > 0 {\n        // Get the current dimension for each shape, defaulting to 1 if we've run out of dimensions\n        let dim_1 = if iter_1 > 0 {\n            *shape_1[iter_1 - 1]\n        } else {\n            1\n        };\n        let dim_2 = if iter_2 > 0 {\n            *shape_2[iter_2 - 1]\n        } else {\n            1\n        };\n\n        // Check the broadcasting rule for the current dimension\n        if dim_1 != dim_2 && dim_1 != 1 && dim_2 != 1 {\n            panic(array!['tensors shape must match']);\n        }\n\n        // Move to the next dimension\n        if iter_1 > 0 {\n            iter_1 -= 1;\n        }\n        if iter_2 > 0 {\n            iter_2 -= 1;\n        }\n    }\n}\n\n/// Computes the index in the broadcasted tensor corresponding to the given indices and shape.\n///\n/// # Arguments\n/// * `shape` - A span containing the shape of the tensor as usize elements.\n/// * `indices` - A span containing the indices as usize elements.\n///\n/// # Panics\n/// * Panics if shape and indices length are not equal.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize representing the index in the broadcasted tensor.\nfn broadcast_index_mapping(mut shape: Span<usize>, mut indices: Span<usize>) -> usize {\n    if shape.len() == indices.len() {\n        broadcast_index_mapping_equal_shape(shape, indices)\n    } else {\n        broadcast_index_mapping_non_equal_shape(shape, indices)\n    }\n}\n\n\nfn broadcast_index_mapping_equal_shape(mut shape: Span<usize>, mut indices: Span<usize>) -> usize {\n    let mut result = 0_usize;\n    let mut stride = stride(shape);\n\n    loop {\n        match shape.pop_front() {\n            Option::Some(shape_val) => {\n                let indices_val = *indices.pop_front().unwrap();\n                let stride_val = *stride.pop_front().unwrap();\n\n                let index = (indices_val % *shape_val) * stride_val;\n                result += index;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    result\n}\n\nfn broadcast_index_mapping_non_equal_shape(\n    mut shape: Span<usize>, mut indices: Span<usize>\n) -> usize {\n    let mut result = 0_usize;\n    let mut stride = stride(shape.clone());\n\n    // Calculate the offset to align indices with the rightmost dimensions of the shape\n    let mut offset = if shape.len() > indices.len() {\n        shape.len() - indices.len()\n    } else {\n        0\n    };\n\n    loop {\n        match shape.pop_back() {\n            Option::Some(_) => {\n                let stride_val = stride\n                    .pop_back()\n                    .unwrap_or(@1); // Default stride for non-existent dimensions is 1\n\n                // Calculate the index, using 0 for dimensions beyond the length of indices\n                let index_val = if offset > 0 {\n                    offset -= 1; // Decrement offset until we align indices with the shape\n                    0 // Use 0 for indices beyond the length of the indices span\n                } else {\n                    *indices\n                        .pop_back()\n                        .unwrap_or(@0) // Use actual index value or 0 if indices are exhausted\n                };\n\n                let index = index_val * *stride_val;\n                result += index;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    result\n}\n\n\n/// Generates the output shape after reducing a tensor along a specified axis.\n///\n/// # Arguments\n/// * `input_shape` - A span containing the input tensor's shape as usize elements.\n/// * `axis` - A usize representing the axis to reduce.\n///\n/// # Panics\n/// * Panics if input_shape is empty.\n/// * Panic if the axis is not in the valid range of the input_shape dimensions.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A Span of usize representing the output shape after reduction.\nfn reduce_output_shape(mut input_shape: Span<usize>, axis: usize, keepdims: bool) -> Span<usize> {\n    assert(axis < input_shape.len(), 'axis out of dimensions');\n\n    let mut output_shape: Array<u32> = array![];\n    let mut n: usize = 0;\n\n    loop {\n        match input_shape.pop_front() {\n            Option::Some(current_dim) => {\n                if n == axis {\n                    if keepdims {\n                        output_shape.append(1);\n                    }\n                } else {\n                    output_shape.append(*current_dim);\n                }\n\n                n += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_shape.span()\n}\n\n\n/// Helper function that computes the output shape of a tensor after applying the axes permutation.\n///\n/// # Arguments\n/// * `input_shape` - A span containing the input tensor's shape as usize elements.\n/// * `axes` -  A span containing the usize elements representing the axes permutation.\n///\n/// # Panics\n/// * Panics if shape and axes length are not equal.\n/// * Panic if the axis value in axes is not in the valid range of the input_shape dimensions.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A Span of usize representing the output shape after permutation.\nfn permutation_output_shape(input_shape: Span<usize>, mut axes: Span<usize>) -> Span<usize> {\n    let axes_len = axes.len();\n    assert(input_shape.len() == axes_len, 'input_shape/indices len unequal');\n\n    let mut output_shape: Array<u32> = array![];\n\n    loop {\n        match axes.pop_front() {\n            Option::Some(item) => { output_shape.append(*input_shape[*item]); },\n            Option::None => { break; }\n        };\n    };\n\n    output_shape.span()\n}\n\n/// Combines output indices with the current index of the specified axis.\n///\n/// # Arguments\n/// * `output_indices` - A span containing the output indices as usize elements.\n/// * `axis_index` - A usize representing the current index of the specified axis.\n/// * `axis` - A usize representing the specified axis.\n///\n/// # Panics\n/// * Panics if the axis value is not in the range of the output_indices length.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A Span of usize representing the combined indices.\nfn combine_indices(mut output_indices: Span<usize>, axis_index: usize, axis: usize) -> Span<usize> {\n    assert(axis <= output_indices.len(), 'axis value is out of range');\n\n    let mut result: Array<u32> = array![];\n    let mut n: usize = 0;\n\n    while n != output_indices.len() + 1 {\n        if n == axis {\n            result.append(axis_index);\n        } else if n > axis {\n            result.append(*output_indices[n - 1_usize]);\n        } else {\n            result.append(*output_indices[n]);\n        }\n\n        n += 1;\n    };\n\n    result.span()\n}\n\n\n/// Helper function that finds the index of a target axis in the given axes array.\n///\n/// # Arguments\n/// * `axes` - A span containing the usize elements representing the axes.\n/// * `target_axis` - A usize representing the target axis.\n///\n/// # Panics\n/// * Panics if the target_axis value is not in the range of the axes dimensions.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize representing the index of the target axis in the given axes array.\nfn find_axis(mut axes: Span<usize>, target_axis: usize) -> usize {\n    assert(target_axis < axes.len(), 'target_axis is out of range');\n    let mut axis: usize = 0;\n\n    loop {\n        match axes.pop_front() {\n            Option::Some(item) => {\n                if *item == target_axis {\n                    break ();\n                }\n                axis += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    axis\n}\n\n/// Computes the broadcasted shape of two tensors.\n///\n/// # Arguments\n/// * `shape1` - A span containing the shape of the first tensor as usize elements.\n/// * `shape2` - A span containing the shape of the second tensor as usize elements.\n///\n/// # Panics\n/// * Panics if the shapes of the tensors are not compatible.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A Span of usize representing the broadcasted shape.\nfn broadcast_shape(mut shape1: Span<usize>, mut shape2: Span<usize>) -> Span<usize> {\n    check_compatibility(shape1, shape2);\n    let mut result: Array<usize> = array![];\n\n    while !shape1.is_empty() || !shape2.is_empty() {\n        let dim1 = *shape1.pop_back().unwrap_or(@1);\n        let dim2 = *shape2.pop_back().unwrap_or(@1);\n\n        let broadcasted_dim = u32_max(dim1, dim2);\n        result.append(broadcasted_dim);\n    };\n\n    result.reverse().span()\n}\n\n/// Substitute a value in a shape at a given index\n/// \n/// # Arguments\n///\n/// * `shape` - The shape to modify\n/// * `index` - The index to modify\n/// * `value` - The value to insert\n///\n/// # Panics\n/// * Panics if the index is out of bounds\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * `Span<usize>` - The modified shape\nfn replace_index(mut shape: Span<usize>, index: usize, value: usize) -> Span<usize> {\n    let mut output: Array<u32> = array![];\n    let mut i = 0;\n\n    loop {\n        match shape.pop_front() {\n            Option::Some(item) => {\n                if i == index {\n                    output.append(value);\n                } else {\n                    output.append(*item);\n                };\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output.span()\n}\n\n/// Creates a list of all axes of given shape\n/// \n/// # Arguments\n///\n/// * `shape` - A span containing the input tensor's shape as usize elements.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * `Span<usize>` - A span containing the usize elements representing the axes.\nfn get_all_axes(shape: Span<usize>) -> Span<usize> {\n    let mut ret: Array<usize> = array![];\n    let mut i: usize = 0;\n    let stop_i = shape.len() - 1;\n    loop {\n        ret.append(i);\n        if i == stop_i {\n            break ();\n        }\n        i += 1;\n    };\n\n    ret.span()\n}\n\n/// Flatten a given array of tensors into an Array<T>.\nfn flatten_array_of_tensors<T, +Copy<T>, +Drop<T>,>(\n    tensors: Array<Tensor<T>>, axis: usize, new_shape: Span<usize>\n) -> Span<T> {\n    let mut new_stride = stride(new_shape);\n\n    let mut flattened: Array<T> = array![];\n\n    let stride_lim: usize = *new_stride.at(axis);\n    let max_row = (*(*tensors.at(0).shape).at(0));\n    let mut row = 0;\n    while row != max_row {\n        let mut tensors_span = tensors.span();\n        loop {\n            let mut i = 0;\n            match tensors_span.pop_front() {\n                Option::Some(mut t) => {\n                    let mut data = *t.data;\n                    while i != stride_lim {\n                        let idx = i + (row * stride_lim);\n                        flattened.append(*data.at(idx));\n                        i += 1;\n                    }\n                },\n                Option::None => { break; },\n            }\n        };\n\n        row += 1;\n    };\n\n    flattened.span()\n}\n\n/// Convert a Tensor to an array of tensors along a given axis.\nfn as_tensors_array<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    tensor: @Tensor<T>, axis: usize\n) -> Array<Tensor<T>> {\n    let shape = *tensor.shape;\n    let rank = shape.len();\n    let mut as_tensors: Array<Tensor<T>> = array![];\n\n    let mut axes: Array<usize> = array![];\n    let mut idx: usize = 0;\n    while idx != rank {\n        axes.append(idx);\n        idx += 1;\n    };\n\n    idx = 0;\n    let axis_len: usize = *shape.at(axis);\n    while idx != axis_len {\n        let mut starts: Array<usize> = array![];\n        let mut ends: Array<usize> = array![];\n        let mut i: usize = 0;\n        while i != rank {\n            starts.append(if i == axis {\n                idx\n            } else {\n                0\n            });\n            ends.append(if i == axis {\n                idx + 1\n            } else {\n                *shape.at(i)\n            });\n            i += 1;\n        };\n\n        let sub_tensor: Tensor<T> = tensor\n            .slice(\n                starts: starts.span(),\n                ends: ends.span(),\n                axes: Option::Some(axes.span()),\n                steps: Option::None(())\n            );\n\n        as_tensors.append(sub_tensor);\n\n        idx += 1;\n    };\n\n    as_tensors\n}\n\n/// Compares two Spans of generic type T.\n///\n/// # Returns\n/// an i8 type containing:\n/// * 1 if the left operand is greater than the right,\n/// * 0 if the left operand is equal to the right,\n/// * -1 if the left operand is lower than the right,\nfn span_cmp<T, +Drop<T>, +Copy<T>, +PartialEq<T>, +PartialOrd<T>>(\n    lhs: Span<T>, rhs: Span<T>\n) -> i8 {\n    let mut rhs = rhs;\n    let mut lhs = lhs;\n    let mut ret: i8 = 0;\n    loop {\n        match lhs.pop_front() {\n            Option::Some(l) => {\n                match rhs.pop_front() {\n                    Option::Some(r) => { if l != r {\n                        ret = if *l > *r {\n                            1\n                        } else {\n                            -1\n                        };\n                        break;\n                    } },\n                    Option::None => {\n                        ret = 1;\n                        break;\n                    },\n                }\n            },\n            Option::None => {\n                ret = -1;\n                break;\n            }\n        };\n    };\n\n    ret\n}\n\n/// Implements PartiaLOrd for two spans of generic type T.\nimpl SpanPartialOrd<T, +Drop<T>, +Copy<T>, +PartialEq<T>, +PartialOrd<T>> of PartialOrd<Span<T>> {\n    fn ge(lhs: Span<T>, rhs: Span<T>) -> bool {\n        span_cmp(lhs, rhs) >= 0\n    }\n\n    fn gt(lhs: Span<T>, rhs: Span<T>) -> bool {\n        span_cmp(lhs, rhs) > 0\n    }\n\n    fn le(lhs: Span<T>, rhs: Span<T>) -> bool {\n        span_cmp(lhs, rhs) <= 0\n    }\n\n    fn lt(lhs: Span<T>, rhs: Span<T>) -> bool {\n        span_cmp(lhs, rhs) < 0\n    }\n}\n\n/// Returns true if (1) the input is an optional-type and contains an element, \n/// or, (2) the input is a tensor type.\n/// If the input is not provided or is an empty optional-type, this op returns false.\n///\n/// # Arguments\n/// * `x` - The optional input.\n///\n/// # Returns\n/// * A scalar boolean tensor. \n/// If true, it indicates that optional-type input contains an element. Otherwise, it is empty.\nfn optional_has_element<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    x: Option<Tensor<T>>\n) -> Tensor<bool> {\n    match x {\n        Option::Some => {\n            let mut shape: Array<usize> = array![];\n            shape.append(1);\n            let mut data: Array<bool> = array![];\n            data.append(true);\n            TensorTrait::new(shape.span(), data.span())\n        },\n        Option::None => {\n            let mut shape: Array<usize> = array![];\n            shape.append(1);\n            let mut data: Array<bool> = array![];\n            data.append(false);\n            TensorTrait::new(shape.span(), data.span())\n        }\n    }\n}\n\n/// If the input is a tensor type, it returns the input.\n/// If the input is an optional type, it outputs the element in the input. \n///\n/// # Arguments\n/// * `x` - The optional input.\n///\n/// # Panics\n/// * Panics if the input is an empty optional-type (i.e. does not have an element) \n///   and the behavior is undefined in this case.\n///\n/// # Returns\n/// * Output element in the optional input.\nfn optional_get_element<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    x: Option<Tensor<T>>\n) -> Tensor<T> {\n    match x {\n        Option::Some(ele) => { ele },\n        Option::None => { panic(array!['The input is an empty', 'optional-type.']) }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations.cairo",
        "content": "mod tensor_bool;\nmod tensor_u32;\nmod tensor_i8;\nmod tensor_i32;\nmod tensor_fp8x23;\nmod tensor_fp16x16;\nmod tensor_fp64x64;\nmod tensor_fp32x32;\nmod tensor_fp16x16wide;\nmod tensor_fp8x23wide;\nmod tensor_complex64;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_bool.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{\n    constant_of_shape, new_tensor, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_ops, ml, manipulation};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::implementations::tensor_u32::U32Tensor;\n\nimpl BoolTensor of TensorTrait<bool> {\n    fn new(shape: Span<usize>, data: Span<bool>) -> Tensor<bool> {\n        new_tensor(shape, data)\n    }\n\n    fn at(self: @Tensor<bool>, indices: Span<usize>) -> bool {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<bool>, rhs: Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn sub(lhs: Tensor<bool>, rhs: Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn mul(lhs: Tensor<bool>, rhs: Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn div(lhs: Tensor<bool>, rhs: Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn min_in_tensor(self: @Tensor<bool>) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn min(tensors: Span<Tensor<bool>>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn max_in_tensor(self: @Tensor<bool>) -> bool {\n        panic(array!['not supported!'])\n    }\n\n    fn max(tensors: Span<Tensor<bool>>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn stride(self: @Tensor<bool>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<bool>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<bool>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<bool>, target_shape: Span<i32>, allowzero: bool) -> Tensor<bool> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<bool>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_prod(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn argmax(\n        self: @Tensor<bool>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn argmin(\n        self: @Tensor<bool>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn transpose(self: @Tensor<bool>, axes: Span<usize>) -> Tensor<bool> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn exp(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn log(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn equal(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn greater_equal(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn less(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn less_equal(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn abs(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn neg(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn cumsum(\n        self: @Tensor<bool>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn flatten(self: @Tensor<bool>, axis: usize) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn sinh(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn xor(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn or(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn onehot(\n        self: @Tensor<bool>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn concat(tensors: Span<Tensor<bool>>, axis: usize,) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn quantize_linear(\n        self: @Tensor<bool>, y_scale: @Tensor<bool>, y_zero_point: @Tensor<bool>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<bool>, x_zero_point: @Tensor<bool>\n    ) -> Tensor::<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn slice(\n        self: @Tensor<bool>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<bool> {\n        core_ops::slice::<bool>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(self: @Tensor<bool>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<bool> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<bool>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn squeeze(self: @Tensor<bool>, axes: Option<Span<usize>>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn unsqueeze(self: @Tensor<bool>, axes: Span<usize>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn sign(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn clip(self: @Tensor<bool>, min: Option<bool>, max: Option<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<bool>) -> Tensor<bool> {\n        core_ops::identity(self)\n    }\n\n    fn where(self: @Tensor<bool>, x: @Tensor<bool>, y: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<bool>,\n        a_zero_point: @Tensor<bool>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<bool>,\n        b_zero_point: @Tensor<bool>,\n        y_scale: @Tensor<bool>,\n        y_zero_point: @Tensor<bool>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn not(self: @Tensor<bool>) -> Tensor<bool> {\n        math::not::not(*self)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<bool>,\n        a_zero_point: @Tensor<bool>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<bool>,\n        b_zero_point: @Tensor<bool>,\n        y_scale: @Tensor<bool>,\n        y_zero_point: @Tensor<bool>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<bool>,\n        a_zero_point: @Tensor<bool>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<bool>,\n        b_zero_point: @Tensor<bool>,\n        y_scale: @Tensor<bool>,\n        y_zero_point: @Tensor<bool>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<bool>>,\n        zero_points: Span<Tensor<bool>>,\n        y_scale: @Tensor<bool>,\n        y_zero_point: @Tensor<bool>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<bool>, a_zero_point: @Tensor<bool>, alpha: bool,\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter(\n        self: @Tensor<bool>,\n        updates: Tensor<bool>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn trilu(self: @Tensor<bool>, upper: bool, k: i64) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_l1(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_l2(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_sum_square(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: bool) -> Tensor<bool> {\n        constant_of_shape(shape, value)\n    }\n\n    fn gather_elements(\n        self: @Tensor<bool>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<bool> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(self: Tensor<bool>, bias: Option<bool>, lambd: Option<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_mean(\n        self: @Tensor<bool>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn binarizer(self: @Tensor<bool>, threshold: Option<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn array_feature_extractor(self: @Tensor<bool>, indices: Tensor<usize>) -> Tensor<bool> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn reduce_min(\n        self: @Tensor<bool>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_inf(\n        self: @Tensor<bool>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<bool>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<bool>, axis: usize, keepdims: bool) -> Tensor<bool> {\n        panic(array!['not supported'])\n    }\n\n    fn unique(\n        self: @Tensor<bool>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<bool>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_nd(\n        self: @Tensor<bool>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<bool> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn compress(\n        self: @Tensor<bool>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<bool> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<bool>,\n        scale: @Tensor<bool>,\n        B: Option<@Tensor<bool>>,\n        axis: Option<i32>,\n        epsilon: Option<bool>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<bool>, Tensor<bool>, Tensor<bool>) {\n        panic(array!['not supported!'])\n    }\n\n    fn resize(\n        self: @Tensor<bool>,\n        roi: Option<Tensor<bool>>,\n        scales: Option<Span<bool>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<bool>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<bool>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<bool>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<bool>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<bool>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<bool>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<bool>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<bool> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<bool>) -> Option<Tensor<bool>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<bool>\n    ) -> (Tensor::<u32>, Tensor::<bool>, Tensor<bool>) {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter_nd(\n        self: @Tensor<bool>, updates: Tensor<bool>, indices: Tensor<usize>, reduction: Option<usize>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn range(start: bool, end: bool, step: bool) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn hann_window(size: bool, periodic: Option<usize>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: bool, periodic: Option<usize>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: bool, periodic: Option<usize>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<bool>, high: Option<bool>, low: Option<bool>, seed: Option<usize>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn label_encoder(\n        self: @Tensor<bool>,\n        default_list: Option<Span<bool>>,\n        default_tensor: Option<Tensor<bool>>,\n        keys: Option<Span<bool>>,\n        keys_tensor: Option<Tensor<bool>>,\n        values: Option<Span<bool>>,\n        values_tensor: Option<Tensor<bool>>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n}\n\n/// Implements partial equal for two `Tensor<bool>` using the `PartialEq` trait.\nimpl BoolTensorPartialEq of PartialEq<Tensor<bool>> {\n    fn eq(lhs: @Tensor<bool>, rhs: @Tensor<bool>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<bool>, rhs: @Tensor<bool>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl BoolTryIntobool of TryInto<bool, bool> {\n    fn try_into(self: bool) -> Option<bool> {\n        Option::Some(self)\n    }\n}\n\n// Internals\nfn tensor_eq(mut lhs: Tensor<bool>, mut rhs: Tensor<bool>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0\n        && is_eq {\n            is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n        };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0\n        && is_eq {\n            is_eq = lhs.data.pop_front().unwrap() == rhs.data.pop_front().unwrap();\n        };\n\n    is_eq\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_complex64.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP64x64, FP64x64Impl};\nuse orion::numbers::fixed_point::implementations::fp64x64::core::ONE;\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\nuse orion::numbers::complex_number::complex_trait::ComplexTrait;\nuse orion::numbers::complex_number::complex64::{Complex64Impl, complex64};\n\nimpl Complex64Tensor of TensorTrait<complex64> {\n    fn new(shape: Span<usize>, data: Span<complex64>) -> Tensor<complex64> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: complex64) -> Tensor<complex64> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<complex64>, indices: Span<usize>) -> complex64 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<complex64>) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn min(tensors: Span<Tensor<complex64>>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn max_in_tensor(self: @Tensor<complex64>) -> complex64 {\n        panic(array!['not supported!'])\n    }\n\n    fn max(tensors: Span<Tensor<complex64>>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn stride(self: @Tensor<complex64>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<complex64>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<complex64>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(\n        self: @Tensor<complex64>, target_shape: Span<i32>, allowzero: bool\n    ) -> Tensor<complex64> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<complex64>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<complex64> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<complex64>, axis: usize, keepdims: bool) -> Tensor<complex64> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<complex64>,\n        axis: i32,\n        keepdims: Option<bool>,\n        select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn argmin(\n        self: @Tensor<complex64>,\n        axis: usize,\n        keepdims: Option<bool>,\n        select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn transpose(self: @Tensor<complex64>, axes: Span<usize>) -> Tensor<complex64> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<complex64> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn greater_equal(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn less(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn less_equal(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn abs(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn ceil(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<complex64>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<complex64> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<complex64>, axis: usize) -> Tensor<complex64> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn or(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<usize> {\n        panic(array!['not supported!'])\n    }\n\n    fn acos(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<complex64>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<complex64>) -> Tensor<complex64> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<complex64>>, axis: usize,) -> Tensor<complex64> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<complex64>, y_scale: @Tensor<complex64>, y_zero_point: @Tensor<complex64>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<complex64>, x_zero_point: @Tensor<complex64>\n    ) -> Tensor::<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<complex64>,\n        a_zero_point: @Tensor<complex64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<complex64>,\n        b_zero_point: @Tensor<complex64>,\n        y_scale: @Tensor<complex64>,\n        y_zero_point: @Tensor<complex64>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<complex64>,\n        a_zero_point: @Tensor<complex64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<complex64>,\n        b_zero_point: @Tensor<complex64>,\n        y_scale: @Tensor<complex64>,\n        y_zero_point: @Tensor<complex64>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<complex64>,\n        a_zero_point: @Tensor<complex64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<complex64>,\n        b_zero_point: @Tensor<complex64>,\n        y_scale: @Tensor<complex64>,\n        y_zero_point: @Tensor<complex64>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<complex64>>,\n        zero_points: Span<Tensor<complex64>>,\n        y_scale: @Tensor<complex64>,\n        y_zero_point: @Tensor<complex64>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<complex64>,\n        a_zero_point: @Tensor<complex64>,\n        alpha: complex64\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn slice(\n        self: @Tensor<complex64>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<complex64> {\n        core_tensor::slice::<complex64>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<complex64>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<complex64> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn gather_nd(\n        self: @Tensor<complex64>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<complex64> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn nonzero(self: @Tensor<complex64>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<complex64>, axes: Option<Span<usize>>) -> Tensor<complex64> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<complex64>, axes: Span<usize>) -> Tensor<complex64> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn clip(\n        self: @Tensor<complex64>, min: Option<complex64>, max: Option<complex64>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<complex64>) -> Tensor<complex64> {\n        core_tensor::identity(self)\n    }\n\n    fn where(\n        self: @Tensor<complex64>, x: @Tensor<complex64>, y: @Tensor<complex64>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_and(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_xor(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn bitwise_or(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn round(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_l1(self: @Tensor<complex64>, axis: usize, keepdims: bool) -> Tensor<complex64> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn array_feature_extractor(\n        self: @Tensor<complex64>, indices: Tensor<usize>\n    ) -> Tensor<complex64> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<complex64>, threshold: Option<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_sum_square(\n        self: @Tensor<complex64>, axis: usize, keepdims: bool\n    ) -> Tensor<complex64> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<complex64>, axis: usize, keepdims: bool) -> Tensor<complex64> {\n        math::reduce_l2::reduce_l2_complex(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<complex64>, upper: bool, k: i64) -> Tensor<complex64> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<complex64>,\n        updates: Tensor<complex64>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn not(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n\n    fn gather_elements(\n        self: @Tensor<complex64>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<complex64> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<complex64>, bias: Option<complex64>, lambd: Option<complex64>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_mean(\n        self: @Tensor<complex64>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<complex64> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<complex64>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn pow(self: @Tensor<complex64>, other: @Tensor<complex64>) -> Tensor<complex64> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<complex64>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_nan(self: @Tensor<complex64>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum(self: @Tensor<complex64>, axis: usize, keepdims: bool) -> Tensor<complex64> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn erf(self: @Tensor<complex64>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn unique(\n        self: @Tensor<complex64>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<complex64>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn compress(\n        self: @Tensor<complex64>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<complex64> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn reduce_log_sum_exp(\n        self: @Tensor<complex64>, axis: usize, keepdims: bool\n    ) -> Tensor<complex64> {\n        math::reduce_log_sum_exp::reduce_log_sum_exp(self, axis, keepdims)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<complex64>,\n        scale: @Tensor<complex64>,\n        B: Option<@Tensor<complex64>>,\n        axis: Option<i32>,\n        epsilon: Option<complex64>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<complex64>, Tensor<complex64>, Tensor<complex64>) {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<complex64>,\n        axis: usize,\n        num_outputs: Option<usize>,\n        spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<complex64>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<complex64>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<complex64> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn resize(\n        self: @Tensor<complex64>,\n        roi: Option<Tensor<complex64>>,\n        scales: Option<Span<complex64>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<complex64>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<complex64>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<complex64>,\n        high: Option<complex64>,\n        low: Option<complex64>,\n        seed: Option<usize>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn range(start: complex64, end: complex64, step: complex64) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn hann_window(size: complex64, periodic: Option<usize>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: complex64, periodic: Option<usize>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: complex64, periodic: Option<usize>) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<complex64>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<complex64>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn optional(self: @Tensor<complex64>) -> Option<Tensor<complex64>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<complex64>\n    ) -> (Tensor::<u32>, Tensor::<complex64>, Tensor<complex64>) {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter_nd(\n        self: @Tensor<complex64>,\n        updates: Tensor<complex64>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n\n    fn label_encoder(\n        self: @Tensor<complex64>,\n        default_list: Option<Span<complex64>>,\n        default_tensor: Option<Tensor<complex64>>,\n        keys: Option<Span<complex64>>,\n        keys_tensor: Option<Tensor<complex64>>,\n        values: Option<Span<complex64>>,\n        values_tensor: Option<Tensor<complex64>>\n    ) -> Tensor<complex64> {\n        panic(array!['not supported!'])\n    }\n}\n\n/// Implements addition for `Tensor<complex64>` using the `Add` trait.\nimpl Complex64TensorAdd of Add<Tensor<complex64>> {\n    /// Adds two `Tensor<complex64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<complex64>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<complex64>` using the `Sub` trait.\nimpl Complex64TensorSub of Sub<Tensor<complex64>> {\n    /// Subtracts two `Tensor<complex64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<complex64>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<complex64>` using the `Mul` trait.\nimpl Complex64TensorMul of Mul<Tensor<complex64>> {\n    /// Multiplies two `Tensor<complex64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<complex64>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<complex64>` using the `Div` trait.\nimpl Complex64TensorDiv of Div<Tensor<complex64>> {\n    /// Divides two `Tensor<complex64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<complex64>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<complex64>, rhs: Tensor<complex64>) -> Tensor<complex64> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<complex64>` using the `complex64` trait.\nimpl Complex64TensorPartialEq of PartialEq<Tensor<complex64>> {\n    fn eq(lhs: @Tensor<complex64>, rhs: @Tensor<complex64>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<complex64>, rhs: @Tensor<complex64>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\n// Internals\nfn eq(lhs: @complex64, rhs: @complex64) -> bool {\n    let eq = (*lhs.real == *rhs.real) && (*lhs.img == *rhs.img);\n\n    eq\n}\n\nfn tensor_eq(mut lhs: Tensor<complex64>, mut rhs: Tensor<complex64>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0\n        && is_eq {\n            is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n        };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0\n        && is_eq {\n            is_eq = eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n        };\n\n    is_eq\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp16x16.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP16x16, I8IntoFP16x16};\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\nuse orion::numbers::fixed_point::implementations::fp16x16::math::trig::PI;\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::FP16x16W;\n\n\nimpl FP16x16Tensor of TensorTrait<FP16x16> {\n    fn new(shape: Span<usize>, data: Span<FP16x16>) -> Tensor<FP16x16> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP16x16) -> Tensor<FP16x16> {\n        constant_of_shape(shape, value)\n    }\n\n    fn add(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn at(self: @Tensor<FP16x16>, indices: Span<usize>) -> FP16x16 {\n        *at_tensor(self, indices)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP16x16>) -> FP16x16 {\n        math::min_in_tensor::min_in_tensor::<FP16x16, u32>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP16x16>>) -> Tensor<FP16x16> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP16x16>) -> FP16x16 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP16x16>>) -> Tensor<FP16x16> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP16x16>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP16x16>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP16x16>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP16x16>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP16x16> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP16x16>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP16x16>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP16x16>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP16x16>, axes: Span<usize>) -> Tensor<FP16x16> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP16x16>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP16x16> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP16x16>, axis: usize) -> Tensor<FP16x16> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP16x16>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP16x16> {\n        math::onehot::onehot(self, depth, axis, values)\n    }\n\n    fn sqrt(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP16x16>>, axis: usize,) -> Tensor<FP16x16> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP16x16>, y_scale: @Tensor<FP16x16>, y_zero_point: @Tensor<FP16x16>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP16x16>, x_zero_point: @Tensor<FP16x16>\n    ) -> Tensor::<FP16x16> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16>,\n        a_zero_point: @Tensor<FP16x16>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16>,\n        b_zero_point: @Tensor<FP16x16>,\n        y_scale: @Tensor<FP16x16>,\n        y_zero_point: @Tensor<FP16x16>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16>,\n        a_zero_point: @Tensor<FP16x16>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16>,\n        b_zero_point: @Tensor<FP16x16>,\n        y_scale: @Tensor<FP16x16>,\n        y_zero_point: @Tensor<FP16x16>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16>,\n        a_zero_point: @Tensor<FP16x16>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16>,\n        b_zero_point: @Tensor<FP16x16>,\n        y_scale: @Tensor<FP16x16>,\n        y_zero_point: @Tensor<FP16x16>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP16x16>>,\n        zero_points: Span<Tensor<FP16x16>>,\n        y_scale: @Tensor<FP16x16>,\n        y_zero_point: @Tensor<FP16x16>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<FP16x16>, a_zero_point: @Tensor<FP16x16>, alpha: FP16x16\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<FP16x16>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP16x16> {\n        core_tensor::slice::<FP16x16>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<FP16x16>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP16x16> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP16x16>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP16x16>, axes: Option<Span<usize>>) -> Tensor<FP16x16> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP16x16>, axes: Span<usize>) -> Tensor<FP16x16> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<FP16x16>, min: Option<FP16x16>, max: Option<FP16x16>) -> Tensor<FP16x16> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<FP16x16>, x: @Tensor<FP16x16>, y: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn array_feature_extractor(self: @Tensor<FP16x16>, indices: Tensor<usize>) -> Tensor<FP16x16> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<FP16x16>, threshold: Option<FP16x16>) -> Tensor<FP16x16> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<FP16x16>, upper: bool, k: i64) -> Tensor<FP16x16> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<FP16x16>,\n        updates: Tensor<FP16x16>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP16x16> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn not(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP16x16>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP16x16> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<FP16x16>, bias: Option<FP16x16>, lambd: Option<FP16x16>\n    ) -> Tensor<FP16x16> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP16x16>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP16x16>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP16x16>, other: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP16x16>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP16x16>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP16x16>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP16x16> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<FP16x16>, axis: usize, keepdims: bool) -> Tensor<FP16x16> {\n        panic(array!['not supported!'])\n    }\n\n\n    fn erf(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP16x16>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP16x16>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP16x16>,\n        scale: @Tensor<FP16x16>,\n        B: Option<@Tensor<FP16x16>>,\n        axis: Option<i32>,\n        epsilon: Option<FP16x16>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP16x16>, Tensor<FP16x16>, Tensor<FP16x16>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP16x16>,\n        roi: Option<Tensor<FP16x16>>,\n        scales: Option<Span<FP16x16>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP16x16>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP16x16>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP16x16> {\n        math::resize::resize(\n            self,\n            roi,\n            scales,\n            sizes,\n            antialias,\n            axes,\n            coordinate_transformation_mode,\n            cubic_coeff_a,\n            exclude_outside,\n            extrapolation_value,\n            keep_aspect_ratio_policy,\n            mode,\n            nearest_mode\n        )\n    }\n\n    fn compress(\n        self: @Tensor<FP16x16>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP16x16> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn split(\n        self: @Tensor<FP16x16>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP16x16>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP16x16>, high: Option<FP16x16>, low: Option<FP16x16>, seed: Option<usize>\n    ) -> Tensor<FP16x16> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP16x16, end: FP16x16, step: FP16x16) -> Tensor<FP16x16> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP16x16, periodic: Option<usize>) -> Tensor<FP16x16> {\n        math::hann_window::hann_window(size, FP16x16 { mag: PI, sign: false }, periodic)\n    }\n\n    fn hamming_window(size: FP16x16, periodic: Option<usize>) -> Tensor<FP16x16> {\n        math::hamming_window::hamming_window(size, FP16x16 { mag: PI, sign: false }, periodic)\n    }\n\n    fn blackman_window(size: FP16x16, periodic: Option<usize>) -> Tensor<FP16x16> {\n        math::blackman_window::blackman_window(size, FP16x16 { mag: PI, sign: false }, periodic)\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP16x16>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP16x16>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP16x16>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP16x16> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP16x16>) -> Option<Tensor<FP16x16>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP16x16>\n    ) -> (Tensor::<u32>, Tensor::<FP16x16>, Tensor<FP16x16>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP16x16>,\n        updates: Tensor<FP16x16>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP16x16> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP16x16>,\n        default_list: Option<Span<FP16x16>>,\n        default_tensor: Option<Tensor<FP16x16>>,\n        keys: Option<Span<FP16x16>>,\n        keys_tensor: Option<Tensor<FP16x16>>,\n        values: Option<Span<FP16x16>>,\n        values_tensor: Option<Tensor<FP16x16>>\n    ) -> Tensor<FP16x16> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP16x16>` using the `Add` trait.\nimpl FP16x16TensorAdd of Add<Tensor<FP16x16>> {\n    /// Adds two `Tensor<FP16x16>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP16x16>` using the `Sub` trait.\nimpl FP16x16TensorSub of Sub<Tensor<FP16x16>> {\n    /// Subtracts two `Tensor<FP16x16>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP16x16>` using the `Mul` trait.\nimpl FP16x16TensorMul of Mul<Tensor<FP16x16>> {\n    /// Multiplies two `Tensor<FP16x16>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP16x16>` using the `Div` trait.\nimpl FP16x16TensorDiv of Div<Tensor<FP16x16>> {\n    /// Divides two `Tensor<FP16x16>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP16x16>` using the `PartialEq` trait.\nimpl FP16x16TensorPartialEq of PartialEq<Tensor<FP16x16>> {\n    fn eq(lhs: @Tensor<FP16x16>, rhs: @Tensor<FP16x16>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP16x16>, rhs: @Tensor<FP16x16>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl TensorI8IntoTensorFP16x16 of Into<Tensor<i8>, Tensor<FP16x16>> {\n    fn into(self: Tensor<i8>) -> Tensor<FP16x16> {\n        tensor_i8_to_tensor_fp16x16(@self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP16x16>` using `PartialOrd` trait.\nimpl FP16x16TensorPartialOrd of PartialOrd<Tensor<FP16x16>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP16x16>, rhs: Tensor<FP16x16>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nconst PRECISION: u32 = 589; // 0.009\n\nfn relative_eq(lhs: @FP16x16, rhs: @FP16x16) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\n\nfn tensor_eq(mut lhs: Tensor<FP16x16>, mut rhs: Tensor<FP16x16>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n    };\n\n    is_eq\n}\n\nfn tensor_i8_to_tensor_fp16x16(x: @Tensor<i8>) -> Tensor<FP16x16> {\n    let mut result_data = ArrayTrait::<FP16x16>::new();\n    let mut data = *x.data;\n\n    while data.len() != 0 {\n        result_data.append((*data.pop_front().unwrap()).into());\n    };\n\n    TensorTrait::new(*x.shape, result_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp16x16wide.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP16x16W};\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\nuse orion::numbers::fixed_point::implementations::fp16x16wide::math::trig::PI;\n\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{\n    FP16x16WImpl, FP16x16WTryIntoFP16x16, FP16x16IntoFP16x16W\n};\n\nuse orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\n\n\nimpl FP16x16WTensor of TensorTrait<FP16x16W> {\n    fn new(shape: Span<usize>, data: Span<FP16x16W>) -> Tensor<FP16x16W> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP16x16W) -> Tensor<FP16x16W> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<FP16x16W>, indices: Span<usize>) -> FP16x16W {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP16x16W>) -> FP16x16W {\n        math::min_in_tensor::min_in_tensor::<FP16x16W, u64>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP16x16W>>) -> Tensor<FP16x16W> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP16x16W>) -> FP16x16W {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP16x16W>>) -> Tensor<FP16x16W> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP16x16W>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP16x16W>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP16x16W>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP16x16W>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP16x16W> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP16x16W>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16W> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP16x16W>, axis: usize, keepdims: bool) -> Tensor<FP16x16W> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP16x16W>,\n        axis: i32,\n        keepdims: Option<bool>,\n        select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP16x16W>,\n        axis: usize,\n        keepdims: Option<bool>,\n        select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP16x16W>, axes: Span<usize>) -> Tensor<FP16x16W> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP16x16W>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP16x16W> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP16x16W>, axis: usize) -> Tensor<FP16x16W> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP16x16W>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP16x16W> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP16x16W>>, axis: usize,) -> Tensor<FP16x16W> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP16x16W>, y_scale: @Tensor<FP16x16W>, y_zero_point: @Tensor<FP16x16W>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP16x16W>, x_zero_point: @Tensor<FP16x16W>\n    ) -> Tensor::<FP16x16W> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16W>,\n        a_zero_point: @Tensor<FP16x16W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16W>,\n        b_zero_point: @Tensor<FP16x16W>,\n        y_scale: @Tensor<FP16x16W>,\n        y_zero_point: @Tensor<FP16x16W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16W>,\n        a_zero_point: @Tensor<FP16x16W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16W>,\n        b_zero_point: @Tensor<FP16x16W>,\n        y_scale: @Tensor<FP16x16W>,\n        y_zero_point: @Tensor<FP16x16W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16W>,\n        a_zero_point: @Tensor<FP16x16W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP16x16W>,\n        b_zero_point: @Tensor<FP16x16W>,\n        y_scale: @Tensor<FP16x16W>,\n        y_zero_point: @Tensor<FP16x16W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP16x16W>>,\n        zero_points: Span<Tensor<FP16x16W>>,\n        y_scale: @Tensor<FP16x16W>,\n        y_zero_point: @Tensor<FP16x16W>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP16x16W>,\n        a_zero_point: @Tensor<FP16x16W>,\n        alpha: FP16x16W\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn slice(\n        self: @Tensor<FP16x16W>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP16x16W> {\n        core_tensor::slice::<FP16x16W>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<FP16x16W>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP16x16W> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP16x16W>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP16x16W>, axes: Option<Span<usize>>) -> Tensor<FP16x16W> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP16x16W>, axes: Span<usize>) -> Tensor<FP16x16W> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(\n        self: @Tensor<FP16x16W>, min: Option<FP16x16W>, max: Option<FP16x16W>\n    ) -> Tensor<FP16x16W> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        core_tensor::identity(self)\n    }\n\n    fn where(\n        self: @Tensor<FP16x16W>, x: @Tensor<FP16x16W>, y: @Tensor<FP16x16W>\n    ) -> Tensor<FP16x16W> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<FP16x16W>, axis: usize, keepdims: bool) -> Tensor<FP16x16W> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<FP16x16W>, upper: bool, k: i64) -> Tensor<FP16x16W> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<FP16x16W>,\n        updates: Tensor<FP16x16W>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn array_feature_extractor(\n        self: @Tensor<FP16x16W>, indices: Tensor<usize>\n    ) -> Tensor<FP16x16W> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<FP16x16W>, threshold: Option<FP16x16W>) -> Tensor<FP16x16W> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP16x16W>, axis: usize, keepdims: bool) -> Tensor<FP16x16W> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP16x16W>, axis: usize, keepdims: bool) -> Tensor<FP16x16W> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn not(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP16x16W>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP16x16W> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<FP16x16W>, bias: Option<FP16x16W>, lambd: Option<FP16x16W>\n    ) -> Tensor<FP16x16W> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP16x16W>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16W> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP16x16W>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP16x16W> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP16x16W>, other: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP16x16W>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP16x16W>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP16x16W>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP16x16W>, axis: usize, keepdims: bool) -> Tensor<FP16x16W> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(\n        self: @Tensor<FP16x16W>, axis: usize, keepdims: bool\n    ) -> Tensor<FP16x16W> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP16x16W>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP16x16W>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn compress(\n        self: @Tensor<FP16x16W>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP16x16W>,\n        scale: @Tensor<FP16x16W>,\n        B: Option<@Tensor<FP16x16W>>,\n        axis: Option<i32>,\n        epsilon: Option<FP16x16W>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP16x16W>, Tensor<FP16x16W>, Tensor<FP16x16W>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP16x16W>,\n        roi: Option<Tensor<FP16x16W>>,\n        scales: Option<Span<FP16x16W>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP16x16W>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP16x16W>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP16x16W> {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<FP16x16W>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP16x16W>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP16x16W>,\n        high: Option<FP16x16W>,\n        low: Option<FP16x16W>,\n        seed: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP16x16W, end: FP16x16W, step: FP16x16W) -> Tensor<FP16x16W> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP16x16W, periodic: Option<usize>) -> Tensor<FP16x16W> {\n        math::hann_window::hann_window(size, FP16x16W { mag: PI, sign: false }, periodic)\n    }\n\n    fn hamming_window(size: FP16x16W, periodic: Option<usize>) -> Tensor<FP16x16W> {\n        math::hamming_window::hamming_window(size, FP16x16W { mag: PI, sign: false }, periodic)\n    }\n\n    fn blackman_window(size: FP16x16W, periodic: Option<usize>) -> Tensor<FP16x16W> {\n        math::blackman_window::blackman_window(size, FP16x16W { mag: PI, sign: false }, periodic)\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP16x16W>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP16x16W>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP16x16W>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP16x16W>) -> Option<Tensor<FP16x16W>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP16x16W>\n    ) -> (Tensor::<u32>, Tensor::<FP16x16W>, Tensor<FP16x16W>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP16x16W>,\n        updates: Tensor<FP16x16W>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP16x16W> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP16x16W>,\n        default_list: Option<Span<FP16x16W>>,\n        default_tensor: Option<Tensor<FP16x16W>>,\n        keys: Option<Span<FP16x16W>>,\n        keys_tensor: Option<Tensor<FP16x16W>>,\n        values: Option<Span<FP16x16W>>,\n        values_tensor: Option<Tensor<FP16x16W>>\n    ) -> Tensor<FP16x16W> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP16x16W>` using the `Add` trait.\nimpl FP16x16WTensorAdd of Add<Tensor<FP16x16W>> {\n    /// Adds two `Tensor<FP16x16W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16W>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP16x16W>` using the `Sub` trait.\nimpl FP16x16WTensorSub of Sub<Tensor<FP16x16W>> {\n    /// Subtracts two `Tensor<FP16x16W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16W>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP16x16W>` using the `Mul` trait.\nimpl FP16x16WTensorMul of Mul<Tensor<FP16x16W>> {\n    /// Multiplies two `Tensor<FP16x16W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16W>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP16x16W>` using the `Div` trait.\nimpl FP16x16WTensorDiv of Div<Tensor<FP16x16W>> {\n    /// Divides two `Tensor<FP16x16W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP16x16W>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> Tensor<FP16x16W> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP16x16W>` using the `PartialEq` trait.\nimpl FP16x16WTensorPartialEq of PartialEq<Tensor<FP16x16W>> {\n    fn eq(lhs: @Tensor<FP16x16W>, rhs: @Tensor<FP16x16W>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP16x16W>, rhs: @Tensor<FP16x16W>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl U32TryIntoU32 of TryInto<u32, u32> {\n    fn try_into(self: u32) -> Option<u32> {\n        Option::Some(self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP16x16W>` using `PartialOrd` trait.\nimpl FP16x16WTensorPartialOrd of PartialOrd<Tensor<FP16x16W>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP16x16W>, rhs: Tensor<FP16x16W>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nconst PRECISION: u64 = 589; // 0.009\n\nfn relative_eq(lhs: @FP16x16W, rhs: @FP16x16W) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\nfn tensor_eq(mut lhs: Tensor<FP16x16W>, mut rhs: Tensor<FP16x16W>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n    };\n\n    is_eq\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp32x32.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP32x32, FP32x32Impl, I8IntoFP32x32};\nuse orion::numbers::fixed_point::implementations::fp32x32::core::ONE;\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\n\nimpl FP32x32Tensor of TensorTrait<FP32x32> {\n    fn new(shape: Span<usize>, data: Span<FP32x32>) -> Tensor<FP32x32> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP32x32) -> Tensor<FP32x32> {\n        constant_of_shape(shape, value)\n    }\n\n    fn add(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn at(self: @Tensor<FP32x32>, indices: Span<usize>) -> FP32x32 {\n        *at_tensor(self, indices)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP32x32>) -> FP32x32 {\n        math::min_in_tensor::min_in_tensor::<FP32x32, u64>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP32x32>>) -> Tensor<FP32x32> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP32x32>) -> FP32x32 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP32x32>>) -> Tensor<FP32x32> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP32x32>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP32x32>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP32x32>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP32x32>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP32x32> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP32x32>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP32x32> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP32x32>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP32x32>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP32x32>, axes: Span<usize>) -> Tensor<FP32x32> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP32x32>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP32x32> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP32x32>, axis: usize) -> Tensor<FP32x32> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP32x32>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP32x32> {\n        math::onehot::onehot(self, depth, axis, values)\n    }\n\n    fn sqrt(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP32x32>>, axis: usize,) -> Tensor<FP32x32> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP32x32>, y_scale: @Tensor<FP32x32>, y_zero_point: @Tensor<FP32x32>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP32x32>, x_zero_point: @Tensor<FP32x32>\n    ) -> Tensor::<FP32x32> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP32x32>,\n        a_zero_point: @Tensor<FP32x32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP32x32>,\n        b_zero_point: @Tensor<FP32x32>,\n        y_scale: @Tensor<FP32x32>,\n        y_zero_point: @Tensor<FP32x32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP32x32>,\n        a_zero_point: @Tensor<FP32x32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP32x32>,\n        b_zero_point: @Tensor<FP32x32>,\n        y_scale: @Tensor<FP32x32>,\n        y_zero_point: @Tensor<FP32x32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP32x32>,\n        a_zero_point: @Tensor<FP32x32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP32x32>,\n        b_zero_point: @Tensor<FP32x32>,\n        y_scale: @Tensor<FP32x32>,\n        y_zero_point: @Tensor<FP32x32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP32x32>>,\n        zero_points: Span<Tensor<FP32x32>>,\n        y_scale: @Tensor<FP32x32>,\n        y_zero_point: @Tensor<FP32x32>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<FP32x32>, a_zero_point: @Tensor<FP32x32>, alpha: FP32x32\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<FP32x32>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP32x32> {\n        core_tensor::slice::<FP32x32>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<FP32x32>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP32x32> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP32x32>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP32x32>, axes: Option<Span<usize>>) -> Tensor<FP32x32> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP32x32>, axes: Span<usize>) -> Tensor<FP32x32> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<FP32x32>, min: Option<FP32x32>, max: Option<FP32x32>) -> Tensor<FP32x32> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<FP32x32>, x: @Tensor<FP32x32>, y: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::round::round(*self)\n    }\n\n    fn trilu(self: @Tensor<FP32x32>, upper: bool, k: i64) -> Tensor<FP32x32> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn reduce_l1(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn scatter(\n        self: @Tensor<FP32x32>,\n        updates: Tensor<FP32x32>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP32x32> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn array_feature_extractor(self: @Tensor<FP32x32>, indices: Tensor<usize>) -> Tensor<FP32x32> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<FP32x32>, threshold: Option<FP32x32>) -> Tensor<FP32x32> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn not(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP32x32>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP32x32> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<FP32x32>, bias: Option<FP32x32>, lambd: Option<FP32x32>\n    ) -> Tensor<FP32x32> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP32x32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP32x32> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP32x32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP32x32> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP32x32>, other: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP32x32>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP32x32>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP32x32>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP32x32> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<FP32x32>, axis: usize, keepdims: bool) -> Tensor<FP32x32> {\n        math::reduce_log_sum_exp::reduce_log_sum_exp(self, axis, keepdims)\n    }\n\n    fn erf(self: @Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP32x32>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP32x32>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP32x32>,\n        scale: @Tensor<FP32x32>,\n        B: Option<@Tensor<FP32x32>>,\n        axis: Option<i32>,\n        epsilon: Option<FP32x32>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP32x32>, Tensor<FP32x32>, Tensor<FP32x32>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP32x32>,\n        roi: Option<Tensor<FP32x32>>,\n        scales: Option<Span<FP32x32>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP32x32>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP32x32>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP32x32> {\n        math::resize::resize(\n            self,\n            roi,\n            scales,\n            sizes,\n            antialias,\n            axes,\n            coordinate_transformation_mode,\n            cubic_coeff_a,\n            exclude_outside,\n            extrapolation_value,\n            keep_aspect_ratio_policy,\n            mode,\n            nearest_mode\n        )\n    }\n\n    fn compress(\n        self: @Tensor<FP32x32>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP32x32> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn split(\n        self: @Tensor<FP32x32>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP32x32>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP32x32>, high: Option<FP32x32>, low: Option<FP32x32>, seed: Option<usize>\n    ) -> Tensor<FP32x32> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP32x32, end: FP32x32, step: FP32x32) -> Tensor<FP32x32> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP32x32, periodic: Option<usize>) -> Tensor<FP32x32> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: FP32x32, periodic: Option<usize>) -> Tensor<FP32x32> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: FP32x32, periodic: Option<usize>) -> Tensor<FP32x32> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP32x32>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP32x32>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP32x32>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP32x32> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP32x32>) -> Option<Tensor<FP32x32>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP32x32>\n    ) -> (Tensor::<u32>, Tensor::<FP32x32>, Tensor<FP32x32>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP32x32>,\n        updates: Tensor<FP32x32>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP32x32> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP32x32>,\n        default_list: Option<Span<FP32x32>>,\n        default_tensor: Option<Tensor<FP32x32>>,\n        keys: Option<Span<FP32x32>>,\n        keys_tensor: Option<Tensor<FP32x32>>,\n        values: Option<Span<FP32x32>>,\n        values_tensor: Option<Tensor<FP32x32>>\n    ) -> Tensor<FP32x32> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP32x32>` using the `Add` trait.\nimpl FP32x32TensorAdd of Add<Tensor<FP32x32>> {\n    /// Adds two `Tensor<FP32x32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP32x32>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP32x32>` using the `Sub` trait.\nimpl FP32x32TensorSub of Sub<Tensor<FP32x32>> {\n    /// Subtracts two `Tensor<FP32x32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP32x32>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP32x32>` using the `Mul` trait.\nimpl FP32x32TensorMul of Mul<Tensor<FP32x32>> {\n    /// Multiplies two `Tensor<FP32x32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP32x32>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP32x32>` using the `Div` trait.\nimpl FP32x32TensorDiv of Div<Tensor<FP32x32>> {\n    /// Divides two `Tensor<FP32x32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP32x32>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> Tensor<FP32x32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP32x32>` using the `PartialEq` trait.\nimpl FP32x32TensorPartialEq of PartialEq<Tensor<FP32x32>> {\n    fn eq(lhs: @Tensor<FP32x32>, rhs: @Tensor<FP32x32>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP32x32>, rhs: @Tensor<FP32x32>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl FP32x32TryIntoI8 of TryInto<FP32x32, i8> {\n    fn try_into(self: FP32x32) -> Option<i8> {\n        let number_felt: felt252 = (self.mag / ONE).into();\n        let number_i8: i8 = number_felt.try_into().unwrap();\n        if self.sign {\n            return Option::Some(number_i8 * -1_i8);\n        }\n        Option::Some(number_i8)\n    }\n}\n\nimpl TensorI8IntoTensorFP32x32 of Into<Tensor<i8>, Tensor<FP32x32>> {\n    fn into(self: Tensor<i8>) -> Tensor<FP32x32> {\n        tensor_i8_to_tensor_fp32x32(@self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP32x32>` using `PartialOrd` trait.\nimpl FP32x32TensorPartialOrd of PartialOrd<Tensor<FP32x32>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> bool {\n        return SpanPartialOrd::ge(lhs.data, rhs.data);\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> bool {\n        return SpanPartialOrd::gt(lhs.data, rhs.data);\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> bool {\n        return SpanPartialOrd::le(lhs.data, rhs.data);\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP32x32>, rhs: Tensor<FP32x32>) -> bool {\n        return SpanPartialOrd::lt(lhs.data, rhs.data);\n    }\n}\n\n// Internals\nconst PRECISION: u64 = 75497; // 0.009\n\nfn relative_eq(lhs: @FP32x32, rhs: @FP32x32) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\nfn tensor_eq(mut lhs: Tensor<FP32x32>, mut rhs: Tensor<FP32x32>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n    };\n\n    is_eq\n}\n\nfn tensor_i8_to_tensor_fp32x32(x: @Tensor<i8>) -> Tensor<FP32x32> {\n    let mut result_data = ArrayTrait::<FP32x32>::new();\n    let mut data = *x.data;\n\n    while data.len() != 0 {\n        result_data.append((*data.pop_front().unwrap()).into());\n    };\n\n    TensorTrait::new(*x.shape, result_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp64x64.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP64x64, FP64x64Impl, I8IntoFP64x64};\nuse orion::numbers::fixed_point::implementations::fp64x64::core::ONE;\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\n\nimpl FP64x64Tensor of TensorTrait<FP64x64> {\n    fn new(shape: Span<usize>, data: Span<FP64x64>) -> Tensor<FP64x64> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP64x64) -> Tensor<FP64x64> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<FP64x64>, indices: Span<usize>) -> FP64x64 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP64x64>) -> FP64x64 {\n        math::min_in_tensor::min_in_tensor::<FP64x64, u128>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP64x64>>) -> Tensor<FP64x64> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP64x64>) -> FP64x64 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP64x64>>) -> Tensor<FP64x64> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP64x64>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP64x64>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP64x64>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP64x64>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP64x64> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP64x64>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP64x64> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP64x64>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP64x64>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP64x64>, axes: Span<usize>) -> Tensor<FP64x64> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP64x64>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP64x64> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP64x64>, axis: usize) -> Tensor<FP64x64> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP64x64>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP64x64> {\n        math::onehot::onehot(self, depth, axis, values)\n    }\n\n    fn sqrt(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP64x64>>, axis: usize,) -> Tensor<FP64x64> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP64x64>, y_scale: @Tensor<FP64x64>, y_zero_point: @Tensor<FP64x64>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP64x64>, x_zero_point: @Tensor<FP64x64>\n    ) -> Tensor::<FP64x64> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP64x64>,\n        a_zero_point: @Tensor<FP64x64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP64x64>,\n        b_zero_point: @Tensor<FP64x64>,\n        y_scale: @Tensor<FP64x64>,\n        y_zero_point: @Tensor<FP64x64>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP64x64>,\n        a_zero_point: @Tensor<FP64x64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP64x64>,\n        b_zero_point: @Tensor<FP64x64>,\n        y_scale: @Tensor<FP64x64>,\n        y_zero_point: @Tensor<FP64x64>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP64x64>,\n        a_zero_point: @Tensor<FP64x64>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP64x64>,\n        b_zero_point: @Tensor<FP64x64>,\n        y_scale: @Tensor<FP64x64>,\n        y_zero_point: @Tensor<FP64x64>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP64x64>>,\n        zero_points: Span<Tensor<FP64x64>>,\n        y_scale: @Tensor<FP64x64>,\n        y_zero_point: @Tensor<FP64x64>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<FP64x64>, a_zero_point: @Tensor<FP64x64>, alpha: FP64x64\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<FP64x64>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP64x64> {\n        core_tensor::slice::<FP64x64>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<FP64x64>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP64x64> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP64x64>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP64x64>, axes: Option<Span<usize>>) -> Tensor<FP64x64> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP64x64>, axes: Span<usize>) -> Tensor<FP64x64> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<FP64x64>, min: Option<FP64x64>, max: Option<FP64x64>) -> Tensor<FP64x64> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<FP64x64>, x: @Tensor<FP64x64>, y: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn array_feature_extractor(self: @Tensor<FP64x64>, indices: Tensor<usize>) -> Tensor<FP64x64> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<FP64x64>, threshold: Option<FP64x64>) -> Tensor<FP64x64> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<FP64x64>, upper: bool, k: i64) -> Tensor<FP64x64> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<FP64x64>,\n        updates: Tensor<FP64x64>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP64x64> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn not(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP64x64>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP64x64> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<FP64x64>, bias: Option<FP64x64>, lambd: Option<FP64x64>\n    ) -> Tensor<FP64x64> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP64x64>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP64x64> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP64x64>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP64x64> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP64x64>, other: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP64x64>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP64x64>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP64x64>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP64x64> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<FP64x64>, axis: usize, keepdims: bool) -> Tensor<FP64x64> {\n        math::reduce_log_sum_exp::reduce_log_sum_exp(self, axis, keepdims)\n    }\n\n    fn erf(self: @Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP64x64>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP64x64>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP64x64>,\n        scale: @Tensor<FP64x64>,\n        B: Option<@Tensor<FP64x64>>,\n        axis: Option<i32>,\n        epsilon: Option<FP64x64>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP64x64>, Tensor<FP64x64>, Tensor<FP64x64>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP64x64>,\n        roi: Option<Tensor<FP64x64>>,\n        scales: Option<Span<FP64x64>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP64x64>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP64x64>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP64x64> {\n        math::resize::resize(\n            self,\n            roi,\n            scales,\n            sizes,\n            antialias,\n            axes,\n            coordinate_transformation_mode,\n            cubic_coeff_a,\n            exclude_outside,\n            extrapolation_value,\n            keep_aspect_ratio_policy,\n            mode,\n            nearest_mode\n        )\n    }\n\n    fn compress(\n        self: @Tensor<FP64x64>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP64x64> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn split(\n        self: @Tensor<FP64x64>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP64x64>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP64x64>, high: Option<FP64x64>, low: Option<FP64x64>, seed: Option<usize>\n    ) -> Tensor<FP64x64> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP64x64, end: FP64x64, step: FP64x64) -> Tensor<FP64x64> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP64x64, periodic: Option<usize>) -> Tensor<FP64x64> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: FP64x64, periodic: Option<usize>) -> Tensor<FP64x64> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: FP64x64, periodic: Option<usize>) -> Tensor<FP64x64> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP64x64>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP64x64>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP64x64>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP64x64> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP64x64>) -> Option<Tensor<FP64x64>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP64x64>\n    ) -> (Tensor::<u32>, Tensor::<FP64x64>, Tensor<FP64x64>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP64x64>,\n        updates: Tensor<FP64x64>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP64x64> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP64x64>,\n        default_list: Option<Span<FP64x64>>,\n        default_tensor: Option<Tensor<FP64x64>>,\n        keys: Option<Span<FP64x64>>,\n        keys_tensor: Option<Tensor<FP64x64>>,\n        values: Option<Span<FP64x64>>,\n        values_tensor: Option<Tensor<FP64x64>>\n    ) -> Tensor<FP64x64> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP64x64>` using the `Add` trait.\nimpl FP64x64TensorAdd of Add<Tensor<FP64x64>> {\n    /// Adds two `Tensor<FP64x64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP64x64>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP64x64>` using the `Sub` trait.\nimpl FP64x64TensorSub of Sub<Tensor<FP64x64>> {\n    /// Subtracts two `Tensor<FP64x64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP64x64>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP64x64>` using the `Mul` trait.\nimpl FP64x64TensorMul of Mul<Tensor<FP64x64>> {\n    /// Multiplies two `Tensor<FP64x64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP64x64>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP64x64>` using the `Div` trait.\nimpl FP64x64TensorDiv of Div<Tensor<FP64x64>> {\n    /// Divides two `Tensor<FP64x64>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP64x64>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> Tensor<FP64x64> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP64x64>` using the `PartialEq` trait.\nimpl FP64x64TensorPartialEq of PartialEq<Tensor<FP64x64>> {\n    fn eq(lhs: @Tensor<FP64x64>, rhs: @Tensor<FP64x64>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP64x64>, rhs: @Tensor<FP64x64>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl FP64x64TryIntoI8 of TryInto<FP64x64, i8> {\n    fn try_into(self: FP64x64) -> Option<i8> {\n        let number_felt: felt252 = (self.mag / ONE).into();\n        let number_i8: i8 = number_felt.try_into().unwrap();\n        if self.sign {\n            return Option::Some(number_i8 * -1_i8);\n        }\n        Option::Some(number_i8)\n    }\n}\n\nimpl TensorI8IntoTensorFP64x64 of Into<Tensor<i8>, Tensor<FP64x64>> {\n    fn into(self: Tensor<i8>) -> Tensor<FP64x64> {\n        tensor_i8_to_tensor_fp64x64(@self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP64x64>` using `PartialOrd` trait.\nimpl FP64x64TensorPartialOrd of PartialOrd<Tensor<FP64x64>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP64x64>, rhs: Tensor<FP64x64>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nconst PRECISION: u128 = 1660000000000000; // 9e-05\n\nfn relative_eq(lhs: @FP64x64, rhs: @FP64x64) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\nfn tensor_eq(mut lhs: Tensor<FP64x64>, mut rhs: Tensor<FP64x64>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n    };\n\n    is_eq\n}\n\nfn tensor_i8_to_tensor_fp64x64(x: @Tensor<i8>) -> Tensor<FP64x64> {\n    let mut result_data = ArrayTrait::<FP64x64>::new();\n    let mut data = *x.data;\n\n    while data.len() != 0 {\n        result_data.append((*data.pop_front().unwrap()).into());\n    };\n\n    TensorTrait::new(*x.shape, result_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp8x23.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_ops, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP8x23, I8IntoFP8x23};\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\nuse orion::numbers::fixed_point::implementations::fp8x23::math::trig::PI;\n\nimpl FP8x23Tensor of TensorTrait<FP8x23> {\n    fn new(shape: Span<usize>, data: Span<FP8x23>) -> Tensor<FP8x23> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP8x23) -> Tensor<FP8x23> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<FP8x23>, indices: Span<usize>) -> FP8x23 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP8x23>) -> FP8x23 {\n        math::min_in_tensor::min_in_tensor::<FP8x23, u32>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP8x23>>) -> Tensor<FP8x23> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP8x23>) -> FP8x23 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP8x23>>) -> Tensor<FP8x23> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP8x23>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP8x23>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP8x23>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP8x23>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP8x23> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP8x23>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP8x23>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP8x23>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP8x23>, axes: Span<usize>) -> Tensor<FP8x23> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP8x23>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP8x23> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP8x23>, axis: usize) -> Tensor<FP8x23> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP8x23>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP8x23> {\n        math::onehot::onehot(self, depth, axis, values)\n    }\n\n    fn sqrt(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP8x23>>, axis: usize,) -> Tensor<FP8x23> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP8x23>, y_scale: @Tensor<FP8x23>, y_zero_point: @Tensor<FP8x23>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP8x23>, x_zero_point: @Tensor<FP8x23>\n    ) -> Tensor::<FP8x23> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23>,\n        a_zero_point: @Tensor<FP8x23>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23>,\n        b_zero_point: @Tensor<FP8x23>,\n        y_scale: @Tensor<FP8x23>,\n        y_zero_point: @Tensor<FP8x23>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23>,\n        a_zero_point: @Tensor<FP8x23>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23>,\n        b_zero_point: @Tensor<FP8x23>,\n        y_scale: @Tensor<FP8x23>,\n        y_zero_point: @Tensor<FP8x23>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23>,\n        a_zero_point: @Tensor<FP8x23>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23>,\n        b_zero_point: @Tensor<FP8x23>,\n        y_scale: @Tensor<FP8x23>,\n        y_zero_point: @Tensor<FP8x23>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP8x23>>,\n        zero_points: Span<Tensor<FP8x23>>,\n        y_scale: @Tensor<FP8x23>,\n        y_zero_point: @Tensor<FP8x23>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<FP8x23>, a_zero_point: @Tensor<FP8x23>, alpha: FP8x23\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<FP8x23>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP8x23> {\n        core_ops::slice::<FP8x23>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(self: @Tensor<FP8x23>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<FP8x23> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP8x23>) -> Tensor<usize> {\n        core_ops::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP8x23>, axes: Option<Span<usize>>) -> Tensor<FP8x23> {\n        core_ops::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP8x23>, axes: Span<usize>) -> Tensor<FP8x23> {\n        core_ops::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<FP8x23>, min: Option<FP8x23>, max: Option<FP8x23>) -> Tensor<FP8x23> {\n        core_ops::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        core_ops::identity(self)\n    }\n\n    fn where(self: @Tensor<FP8x23>, x: @Tensor<FP8x23>, y: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<FP8x23>, upper: bool, k: i64) -> Tensor<FP8x23> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<FP8x23>,\n        updates: Tensor<FP8x23>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP8x23> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP8x23>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP8x23> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(self: Tensor<FP8x23>, bias: Option<FP8x23>, lambd: Option<FP8x23>) -> Tensor<FP8x23> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP8x23>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn binarizer(self: @Tensor<FP8x23>, threshold: Option<FP8x23>) -> Tensor<FP8x23> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn array_feature_extractor(self: @Tensor<FP8x23>, indices: Tensor<usize>) -> Tensor<FP8x23> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn not(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP8x23>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP8x23>, other: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP8x23>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP8x23>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP8x23>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP8x23> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<FP8x23>, axis: usize, keepdims: bool) -> Tensor<FP8x23> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP8x23>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP8x23>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP8x23>,\n        scale: @Tensor<FP8x23>,\n        B: Option<@Tensor<FP8x23>>,\n        axis: Option<i32>,\n        epsilon: Option<FP8x23>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP8x23>, Tensor<FP8x23>, Tensor<FP8x23>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP8x23>,\n        roi: Option<Tensor<FP8x23>>,\n        scales: Option<Span<FP8x23>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP8x23>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP8x23>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP8x23> {\n        math::resize::resize(\n            self,\n            roi,\n            scales,\n            sizes,\n            antialias,\n            axes,\n            coordinate_transformation_mode,\n            cubic_coeff_a,\n            exclude_outside,\n            extrapolation_value,\n            keep_aspect_ratio_policy,\n            mode,\n            nearest_mode\n        )\n    }\n\n    fn compress(\n        self: @Tensor<FP8x23>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP8x23> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn split(\n        self: @Tensor<FP8x23>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP8x23>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP8x23>, high: Option<FP8x23>, low: Option<FP8x23>, seed: Option<usize>\n    ) -> Tensor<FP8x23> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP8x23, end: FP8x23, step: FP8x23) -> Tensor<FP8x23> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP8x23, periodic: Option<usize>) -> Tensor<FP8x23> {\n        math::hann_window::hann_window(size, FP8x23 { mag: PI, sign: false }, periodic)\n    }\n\n    fn hamming_window(size: FP8x23, periodic: Option<usize>) -> Tensor<FP8x23> {\n        math::hamming_window::hamming_window(size, FP8x23 { mag: PI, sign: false }, periodic)\n    }\n\n    fn blackman_window(size: FP8x23, periodic: Option<usize>) -> Tensor<FP8x23> {\n        math::blackman_window::blackman_window(size, FP8x23 { mag: PI, sign: false }, periodic)\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP8x23>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP8x23>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP8x23>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP8x23> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP8x23>) -> Option<Tensor<FP8x23>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP8x23>\n    ) -> (Tensor::<u32>, Tensor::<FP8x23>, Tensor<FP8x23>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP8x23>,\n        updates: Tensor<FP8x23>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP8x23> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP8x23>,\n        default_list: Option<Span<FP8x23>>,\n        default_tensor: Option<Tensor<FP8x23>>,\n        keys: Option<Span<FP8x23>>,\n        keys_tensor: Option<Tensor<FP8x23>>,\n        values: Option<Span<FP8x23>>,\n        values_tensor: Option<Tensor<FP8x23>>\n    ) -> Tensor<FP8x23> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP8x23>` using the `Add` trait.\nimpl FP8x23TensorAdd<\n    FP8x23,\n    impl FP8x23Tensor: TensorTrait<FP8x23>,\n    impl TAdd: Add<FP8x23>,\n    impl TCopy: Copy<FP8x23>,\n    impl TDrop: Drop<FP8x23>\n> of Add<Tensor<FP8x23>> {\n    /// Adds two `Tensor<FP8x23>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP8x23>` using the `Sub` trait.\nimpl FP8x23TensorSub<\n    FP8x23,\n    impl FP8x23Tensor: TensorTrait<FP8x23>,\n    impl TSub: Sub<FP8x23>,\n    impl TCopy: Copy<FP8x23>,\n    impl TDrop: Drop<FP8x23>\n> of Sub<Tensor<FP8x23>> {\n    /// Subtracts two `Tensor<FP8x23>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP8x23>` using the `Mul` trait.\nimpl FP8x23TensorMul<\n    FP8x23,\n    impl FP8x23Tensor: TensorTrait<FP8x23>,\n    impl TMul: Mul<FP8x23>,\n    impl TCopy: Copy<FP8x23>,\n    impl TDrop: Drop<FP8x23>\n> of Mul<Tensor<FP8x23>> {\n    /// Multiplies two `Tensor<FP8x23>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP8x23>` using the `Div` trait.\nimpl FP8x23TensorDiv<\n    FP8x23,\n    impl FP8x23Tensor: TensorTrait<FP8x23>,\n    impl TDiv: Div<FP8x23>,\n    impl TCopy: Copy<FP8x23>,\n    impl TDrop: Drop<FP8x23>\n> of Div<Tensor<FP8x23>> {\n    /// Divides two `Tensor<FP8x23>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> Tensor<FP8x23> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP8x23>` using the `PartialEq` trait.\nimpl FP8x23TensorPartialEq of PartialEq<Tensor<FP8x23>> {\n    fn eq(lhs: @Tensor<FP8x23>, rhs: @Tensor<FP8x23>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP8x23>, rhs: @Tensor<FP8x23>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl TensorI8IntoTensorFP8x23 of Into<Tensor<i8>, Tensor<FP8x23>> {\n    fn into(self: Tensor<i8>) -> Tensor<FP8x23> {\n        tensor_i8_to_tensor_fp8x23(@self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP8x23>` using `PartialOrd` trait.\nimpl FP8x23TensorPartialOrd of PartialOrd<Tensor<FP8x23>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP8x23>, rhs: Tensor<FP8x23>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nconst PRECISION: u32 = 75497; // 0.009\n\nfn relative_eq(lhs: @FP8x23, rhs: @FP8x23) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\nfn tensor_eq(mut lhs: Tensor<FP8x23>, mut rhs: Tensor<FP8x23>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0\n        && is_eq {\n            is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n        };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0\n        && is_eq {\n            is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n        };\n\n    is_eq\n}\n\nfn tensor_i8_to_tensor_fp8x23(x: @Tensor<i8>) -> Tensor<FP8x23> {\n    let mut result_data = ArrayTrait::<FP8x23>::new();\n    let mut data = *x.data;\n\n    while data.len() != 0 {\n        result_data.append((*data.pop_front().unwrap()).into());\n    };\n\n    TensorTrait::new(*x.shape, result_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_fp8x23wide.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait, FP8x23W};\nuse orion::operators::tensor::implementations::{\n    tensor_i8::I8Tensor, tensor_u32::U32Tensor, tensor_bool::BoolTensor\n};\nuse orion::numbers::fixed_point::implementations::fp8x23wide::math::trig::PI;\n\nuse orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\n\n\nimpl FP8x23WTensor of TensorTrait<FP8x23W> {\n    fn new(shape: Span<usize>, data: Span<FP8x23W>) -> Tensor<FP8x23W> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: FP8x23W) -> Tensor<FP8x23W> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<FP8x23W>, indices: Span<usize>) -> FP8x23W {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<FP8x23W>) -> FP8x23W {\n        math::min_in_tensor::min_in_tensor::<FP8x23W, u64>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<FP8x23W>>) -> Tensor<FP8x23W> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<FP8x23W>) -> FP8x23W {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<FP8x23W>>) -> Tensor<FP8x23W> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<FP8x23W>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<FP8x23W>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<FP8x23W>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<FP8x23W>, target_shape: Span<i32>, allowzero: bool) -> Tensor<FP8x23W> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<FP8x23W>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23W> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<FP8x23W>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<FP8x23W>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<FP8x23W>, axes: Span<usize>) -> Tensor<FP8x23W> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::exp::exp(*self)\n    }\n\n    fn log(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::log::log(*self)\n    }\n\n    fn equal(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::ceil::ceil(*self)\n    }\n\n    fn sin(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::sin::sin(*self)\n    }\n\n    fn cos(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::cos::cos(*self)\n    }\n\n    fn asin(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::asin::asin(*self)\n    }\n\n    fn cumsum(\n        self: @Tensor<FP8x23W>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<FP8x23W> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<FP8x23W>, axis: usize) -> Tensor<FP8x23W> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::sinh::sinh(*self)\n    }\n\n    fn tanh(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::tanh::tanh(*self)\n    }\n\n    fn cosh(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::cosh::cosh(*self)\n    }\n\n    fn acosh(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::acosh::acosh(*self)\n    }\n\n    fn asinh(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::asinh::asinh(*self)\n    }\n\n    fn atan(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::atan::atan(*self)\n    }\n\n    fn xor(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::acos::acos(*self)\n    }\n\n    fn onehot(\n        self: @Tensor<FP8x23W>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<FP8x23W> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::sqrt::sqrt(*self)\n    }\n\n    fn concat(tensors: Span<Tensor<FP8x23W>>, axis: usize,) -> Tensor<FP8x23W> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<FP8x23W>, y_scale: @Tensor<FP8x23W>, y_zero_point: @Tensor<FP8x23W>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<FP8x23W>, x_zero_point: @Tensor<FP8x23W>\n    ) -> Tensor::<FP8x23W> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23W>,\n        a_zero_point: @Tensor<FP8x23W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23W>,\n        b_zero_point: @Tensor<FP8x23W>,\n        y_scale: @Tensor<FP8x23W>,\n        y_zero_point: @Tensor<FP8x23W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23W>,\n        a_zero_point: @Tensor<FP8x23W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23W>,\n        b_zero_point: @Tensor<FP8x23W>,\n        y_scale: @Tensor<FP8x23W>,\n        y_zero_point: @Tensor<FP8x23W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<FP8x23W>,\n        a_zero_point: @Tensor<FP8x23W>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<FP8x23W>,\n        b_zero_point: @Tensor<FP8x23W>,\n        y_scale: @Tensor<FP8x23W>,\n        y_zero_point: @Tensor<FP8x23W>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<FP8x23W>>,\n        zero_points: Span<Tensor<FP8x23W>>,\n        y_scale: @Tensor<FP8x23W>,\n        y_zero_point: @Tensor<FP8x23W>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<FP8x23W>, a_zero_point: @Tensor<FP8x23W>, alpha: FP8x23W\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn slice(\n        self: @Tensor<FP8x23W>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<FP8x23W> {\n        core_tensor::slice::<FP8x23W>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(\n        self: @Tensor<FP8x23W>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP8x23W> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<FP8x23W>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<FP8x23W>, axes: Option<Span<usize>>) -> Tensor<FP8x23W> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<FP8x23W>, axes: Span<usize>) -> Tensor<FP8x23W> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<FP8x23W>, min: Option<FP8x23W>, max: Option<FP8x23W>) -> Tensor<FP8x23W> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<FP8x23W>, x: @Tensor<FP8x23W>, y: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn array_feature_extractor(self: @Tensor<FP8x23W>, indices: Tensor<usize>) -> Tensor<FP8x23W> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n\n    fn binarizer(self: @Tensor<FP8x23W>, threshold: Option<FP8x23W>) -> Tensor<FP8x23W> {\n        math::binarizer::binarizer(*self, threshold)\n    }\n\n    fn reduce_sum_square(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        math::reduce_l2::reduce_l2(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<FP8x23W>, upper: bool, k: i64) -> Tensor<FP8x23W> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<FP8x23W>,\n        updates: Tensor<FP8x23W>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn not(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<FP8x23W>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<FP8x23W> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(\n        self: Tensor<FP8x23W>, bias: Option<FP8x23W>, lambd: Option<FP8x23W>\n    ) -> Tensor<FP8x23W> {\n        math::shrink::shrink(self, bias, lambd)\n    }\n\n    fn reduce_mean(\n        self: @Tensor<FP8x23W>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23W> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<FP8x23W>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<FP8x23W> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<FP8x23W>, other: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::pow::pow(self, other)\n    }\n\n    fn is_inf(\n        self: @Tensor<FP8x23W>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<FP8x23W>) -> Tensor<bool> {\n        math::is_nan::is_nan(self)\n    }\n\n    fn gather_nd(\n        self: @Tensor<FP8x23W>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        math::reduce_log_sum::reduce_log_sum(self, axis, keepdims)\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<FP8x23W>, axis: usize, keepdims: bool) -> Tensor<FP8x23W> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::erf::erf(*self)\n    }\n\n    fn unique(\n        self: @Tensor<FP8x23W>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<FP8x23W>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<FP8x23W>,\n        scale: @Tensor<FP8x23W>,\n        B: Option<@Tensor<FP8x23W>>,\n        axis: Option<i32>,\n        epsilon: Option<FP8x23W>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<FP8x23W>, Tensor<FP8x23W>, Tensor<FP8x23W>) {\n        math::layer_normalization::layer_normalization(self, scale, B, axis, epsilon, stash_type)\n    }\n\n    fn resize(\n        self: @Tensor<FP8x23W>,\n        roi: Option<Tensor<FP8x23W>>,\n        scales: Option<Span<FP8x23W>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<FP8x23W>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<FP8x23W>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<FP8x23W> {\n        panic(array!['not supported!'])\n    }\n\n    fn compress(\n        self: @Tensor<FP8x23W>, condition: Tensor<usize>, axis: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn split(\n        self: @Tensor<FP8x23W>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP8x23W>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<FP8x23W>, high: Option<FP8x23W>, low: Option<FP8x23W>, seed: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        math::random_uniform_like::random_uniform_like(*tensor, high, low, seed)\n    }\n\n    fn range(start: FP8x23W, end: FP8x23W, step: FP8x23W) -> Tensor<FP8x23W> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: FP8x23W, periodic: Option<usize>) -> Tensor<FP8x23W> {\n        math::hann_window::hann_window(size, FP8x23W { mag: PI, sign: false }, periodic)\n    }\n\n    fn hamming_window(size: FP8x23W, periodic: Option<usize>) -> Tensor<FP8x23W> {\n        math::hamming_window::hamming_window(size, FP8x23W { mag: PI, sign: false }, periodic)\n    }\n\n    fn blackman_window(size: FP8x23W, periodic: Option<usize>) -> Tensor<FP8x23W> {\n        math::blackman_window::blackman_window(size, FP8x23W { mag: PI, sign: false }, periodic)\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<FP8x23W>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<FP8x23W>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<FP8x23W>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<FP8x23W>) -> Option<Tensor<FP8x23W>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(\n        self: @Tensor<FP8x23W>\n    ) -> (Tensor::<u32>, Tensor::<FP8x23W>, Tensor<FP8x23W>) {\n        quantization::dynamic_quantize_linear::dynamic_quantize_linear(\n            self,\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(255, false),\n            NumberTrait::new_unscaled(0, false),\n            NumberTrait::new_unscaled(1, false),\n        )\n    }\n\n    fn scatter_nd(\n        self: @Tensor<FP8x23W>,\n        updates: Tensor<FP8x23W>,\n        indices: Tensor<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<FP8x23W> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<FP8x23W>,\n        default_list: Option<Span<FP8x23W>>,\n        default_tensor: Option<Tensor<FP8x23W>>,\n        keys: Option<Span<FP8x23W>>,\n        keys_tensor: Option<Tensor<FP8x23W>>,\n        values: Option<Span<FP8x23W>>,\n        values_tensor: Option<Tensor<FP8x23W>>\n    ) -> Tensor<FP8x23W> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<FP8x23W>` using the `Add` trait.\nimpl FP8x23WTensorAdd<\n    FP8x23W,\n    impl FP8x23WTensor: TensorTrait<FP8x23W>,\n    impl TAdd: Add<FP8x23W>,\n    impl TCopy: Copy<FP8x23W>,\n    impl TDrop: Drop<FP8x23W>\n> of Add<Tensor<FP8x23W>> {\n    /// Adds two `Tensor<FP8x23W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23W>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<FP8x23W>` using the `Sub` trait.\nimpl FP8x23WTensorSub<\n    FP8x23W,\n    impl FP8x23WTensor: TensorTrait<FP8x23W>,\n    impl TSub: Sub<FP8x23W>,\n    impl TCopy: Copy<FP8x23W>,\n    impl TDrop: Drop<FP8x23W>\n> of Sub<Tensor<FP8x23W>> {\n    /// Subtracts two `Tensor<FP8x23W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23W>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<FP8x23W>` using the `Mul` trait.\nimpl FP8x23WTensorMul<\n    FP8x23W,\n    impl FP8x23WTensor: TensorTrait<FP8x23W>,\n    impl TMul: Mul<FP8x23W>,\n    impl TCopy: Copy<FP8x23W>,\n    impl TDrop: Drop<FP8x23W>\n> of Mul<Tensor<FP8x23W>> {\n    /// Multiplies two `Tensor<FP8x23W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23W>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<FP8x23W>` using the `Div` trait.\nimpl FP8x23WTensorDiv<\n    FP8x23W,\n    impl FP8x23WTensor: TensorTrait<FP8x23W>,\n    impl TDiv: Div<FP8x23W>,\n    impl TCopy: Copy<FP8x23W>,\n    impl TDrop: Drop<FP8x23W>\n> of Div<Tensor<FP8x23W>> {\n    /// Divides two `Tensor<FP8x23W>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<FP8x23W>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> Tensor<FP8x23W> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<FP8x23W>` using the `PartialEq` trait.\nimpl FP8x23WTensorPartialEq of PartialEq<Tensor<FP8x23W>> {\n    fn eq(lhs: @Tensor<FP8x23W>, rhs: @Tensor<FP8x23W>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<FP8x23W>, rhs: @Tensor<FP8x23W>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl U32TryIntoU32 of TryInto<u64, u64> {\n    fn try_into(self: u64) -> Option<u64> {\n        Option::Some(self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<FP8x23W>` using `PartialOrd` trait.\nimpl FP8x23WTensorPartialOrd of PartialOrd<Tensor<FP8x23W>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<FP8x23W>, rhs: Tensor<FP8x23W>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nconst PRECISION: u64 = 75497; // 0.009\n\nfn relative_eq(lhs: @FP8x23W, rhs: @FP8x23W) -> bool {\n    let diff = *lhs - *rhs;\n\n    let rel_diff = if *lhs.mag != 0 {\n        (diff / *lhs).mag\n    } else {\n        diff.mag\n    };\n\n    rel_diff <= PRECISION\n}\n\nfn tensor_eq(mut lhs: Tensor<FP8x23W>, mut rhs: Tensor<FP8x23W>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = relative_eq(lhs.data.pop_front().unwrap(), rhs.data.pop_front().unwrap());\n    };\n\n    is_eq\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_i32.cairo",
        "content": "use orion::numbers::{I32Div, I32DivEq};\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::implementations::{\n    tensor_u32::U32Tensor, tensor_i8::I8Tensor, tensor_bool::BoolTensor\n};\n\nimpl I32Tensor of TensorTrait<i32> {\n    fn new(shape: Span<usize>, data: Span<i32>) -> Tensor<i32> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: i32) -> Tensor<i32> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<i32>, indices: Span<usize>) -> i32 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<i32>) -> i32 {\n        math::min_in_tensor::min_in_tensor::<i32>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<i32>>) -> Tensor<i32> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<i32>) -> i32 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<i32>>) -> Tensor<i32> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<i32>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<i32>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<i32>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<i32>, target_shape: Span<i32>, allowzero: bool) -> Tensor<i32> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<i32>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i32> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n\n    fn reduce_prod(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<i32>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<i32>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<i32>, axes: Span<usize>) -> Tensor<i32> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn log(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn equal(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<i32>) -> Tensor<i32> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<i32>) -> Tensor<i32> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cumsum(\n        self: @Tensor<i32>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<i32> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<i32>, axis: usize) -> Tensor<i32> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn xor(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn onehot(\n        self: @Tensor<i32>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn concat(tensors: Span<Tensor<i32>>, axis: usize,) -> Tensor<i32> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<i32>, y_scale: @Tensor<i32>, y_zero_point: @Tensor<i32>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(self, y_scale, y_zero_point, -127, 127)\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<i32>, x_zero_point: @Tensor<i32>\n    ) -> Tensor::<i32> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i32>,\n        a_zero_point: @Tensor<i32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i32>,\n        b_zero_point: @Tensor<i32>,\n        y_scale: @Tensor<i32>,\n        y_zero_point: @Tensor<i32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i32>,\n        a_zero_point: @Tensor<i32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i32>,\n        b_zero_point: @Tensor<i32>,\n        y_scale: @Tensor<i32>,\n        y_zero_point: @Tensor<i32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i32>,\n        a_zero_point: @Tensor<i32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i32>,\n        b_zero_point: @Tensor<i32>,\n        y_scale: @Tensor<i32>,\n        y_zero_point: @Tensor<i32>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<i32>>,\n        zero_points: Span<Tensor<i32>>,\n        y_scale: @Tensor<i32>,\n        y_zero_point: @Tensor<i32>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<i32>, a_zero_point: @Tensor<i32>, alpha: i32\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(128, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<i32>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<i32> {\n        core_tensor::slice::<i32>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(self: @Tensor<i32>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<i32> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<i32>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<i32>, axes: Option<Span<usize>>) -> Tensor<i32> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<i32>, axes: Span<usize>) -> Tensor<i32> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<i32>) -> Tensor<i32> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<i32>, min: Option<i32>, max: Option<i32>) -> Tensor<i32> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<i32>) -> Tensor<i32> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<i32>, x: @Tensor<i32>, y: @Tensor<i32>) -> Tensor<i32> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<i32>) -> Tensor<i32> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<i32>, upper: bool, k: i64) -> Tensor<i32> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<i32>,\n        updates: Tensor<i32>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<i32> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn array_feature_extractor(self: @Tensor<i32>, indices: Tensor<usize>) -> Tensor<i32> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<i32>, threshold: Option<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_sum_square(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn not(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<i32>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<i32> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(self: Tensor<i32>, bias: Option<i32>, lambd: Option<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_mean(\n        self: @Tensor<i32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i32> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<i32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i32> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<i32>, other: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_inf(\n        self: @Tensor<i32>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<i32>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_nd(\n        self: @Tensor<i32>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<i32> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<i32>, axis: usize, keepdims: bool) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<i32>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn unique(\n        self: @Tensor<i32>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<i32>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn resize(\n        self: @Tensor<i32>,\n        roi: Option<Tensor<i32>>,\n        scales: Option<Span<i32>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<i32>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<i32>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn compress(self: @Tensor<i32>, condition: Tensor<usize>, axis: Option<usize>) -> Tensor<i32> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<i32>,\n        scale: @Tensor<i32>,\n        B: Option<@Tensor<i32>>,\n        axis: Option<i32>,\n        epsilon: Option<i32>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<i32>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<i32>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<i32>, high: Option<i32>, low: Option<i32>, seed: Option<usize>\n    ) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn range(start: i32, end: i32, step: i32) -> Tensor<i32> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: i32, periodic: Option<usize>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: i32, periodic: Option<usize>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: i32, periodic: Option<usize>) -> Tensor<i32> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<i32>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<i32>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<i32>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<i32> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<i32>) -> Option<Tensor<i32>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(self: @Tensor<i32>) -> (Tensor::<u32>, Tensor::<i32>, Tensor<i32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter_nd(\n        self: @Tensor<i32>, updates: Tensor<i32>, indices: Tensor<usize>, reduction: Option<usize>\n    ) -> Tensor<i32> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<i32>,\n        default_list: Option<Span<i32>>,\n        default_tensor: Option<Tensor<i32>>,\n        keys: Option<Span<i32>>,\n        keys_tensor: Option<Tensor<i32>>,\n        values: Option<Span<i32>>,\n        values_tensor: Option<Tensor<i32>>\n    ) -> Tensor<i32> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<i32>` using the `Add` trait.\nimpl I32TensorAdd of Add<Tensor<i32>> {\n    /// Adds two `Tensor<i32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i32>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<i32>` using the `Sub` trait.\nimpl I32TensorSub of Sub<Tensor<i32>> {\n    /// Subtracts two `Tensor<i32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i32>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<i32>` using the `Mul` trait.\nimpl I32TensorMul of Mul<Tensor<i32>> {\n    /// Multiplies two `Tensor<i32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i32>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<i32>` using the `Div` trait.\nimpl I32TensorDiv of Div<Tensor<i32>> {\n    /// Divides two `Tensor<i32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i32>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<i32>, rhs: Tensor<i32>) -> Tensor<i32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<i32>` using the `PartialEq` trait.\nimpl I32TensorPartialEq of PartialEq<Tensor<i32>> {\n    fn eq(lhs: @Tensor<i32>, rhs: @Tensor<i32>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<i32>, rhs: @Tensor<i32>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\nimpl I8TryIntoI8 of TryInto<i32, i32> {\n    fn try_into(self: i32) -> Option<i32> {\n        Option::Some(self)\n    }\n}\n\nimpl TensorI8IntoTensorI32 of Into<Tensor<i8>, Tensor<i32>> {\n    fn into(self: Tensor<i8>) -> Tensor<i32> {\n        tensor_i8_to_tensor_i32(@self)\n    }\n}\n\n/// Implements partial ord for two `Tensor<i32>` using `PartialOrd` trait.\nimpl I32TensorPartialOrd of PartialOrd<Tensor<i32>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<i32>, rhs: Tensor<i32>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<i32>, rhs: Tensor<i32>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<i32>, rhs: Tensor<i32>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<i32>, rhs: Tensor<i32>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nfn tensor_eq(mut lhs: Tensor<i32>, mut rhs: Tensor<i32>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = lhs.data.pop_front().unwrap() == rhs.data.pop_front().unwrap();\n    };\n\n    is_eq\n}\n\nfn tensor_i8_to_tensor_i32(x: @Tensor<i8>) -> Tensor<i32> {\n    let mut result_data = ArrayTrait::<i32>::new();\n    let mut data = *x.data;\n\n    while data.len() != 0 {\n        result_data.append((*data.pop_front().unwrap()).into());\n    };\n\n    TensorTrait::new(*x.shape, result_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_i8.cairo",
        "content": "use orion::numbers::{I8Div, I8DivEq};\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::implementations::{tensor_u32::U32Tensor, tensor_bool::BoolTensor};\n\nimpl I8Tensor of TensorTrait<i8> {\n    fn new(shape: Span<usize>, data: Span<i8>) -> Tensor<i8> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: i8) -> Tensor<i8> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<i8>, indices: Span<usize>) -> i8 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<i8>) -> i8 {\n        math::min_in_tensor::min_in_tensor::<i8>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<i8>>) -> Tensor<i8> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<i8>) -> i8 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<i8>>) -> Tensor<i8> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<i8>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<i8>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<i8>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<i8>, target_shape: Span<i32>, allowzero: bool) -> Tensor<i8> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<i8>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i8> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<i8>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<i8>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<i8>, axes: Span<usize>) -> Tensor<i8> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i8> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn log(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn equal(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<i8>) -> Tensor<i8> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<i8>) -> Tensor<i8> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn cumsum(\n        self: @Tensor<i8>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<i8> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<i8>, axis: usize) -> Tensor<i8> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn xor(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn onehot(\n        self: @Tensor<i8>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn concat(tensors: Span<Tensor<i8>>, axis: usize,) -> Tensor<i8> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<i8>, y_scale: @Tensor<i8>, y_zero_point: @Tensor<i8>\n    ) -> Tensor::<i8> {\n        quantization::quantize_linear::quantize_linear(\n            self,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<i8>, x_zero_point: @Tensor<i8>\n    ) -> Tensor::<i8> {\n        quantization::dequantize_linear::dequantize_linear(self, x_scale, x_zero_point)\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i8>,\n        a_zero_point: @Tensor<i8>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i8>,\n        b_zero_point: @Tensor<i8>,\n        y_scale: @Tensor<i8>,\n        y_zero_point: @Tensor<i8>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_add::qlinear_add(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i8>,\n        a_zero_point: @Tensor<i8>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i8>,\n        b_zero_point: @Tensor<i8>,\n        y_scale: @Tensor<i8>,\n        y_zero_point: @Tensor<i8>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_mul::qlinear_mul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<i8>,\n        a_zero_point: @Tensor<i8>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<i8>,\n        b_zero_point: @Tensor<i8>,\n        y_scale: @Tensor<i8>,\n        y_zero_point: @Tensor<i8>\n    ) -> Tensor::<i8> {\n        quantization::qlinear_matmul::qlinear_matmul(\n            self,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            y_scale,\n            y_zero_point,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<i8>>,\n        zero_points: Span<Tensor<i8>>,\n        y_scale: @Tensor<i8>,\n        y_zero_point: @Tensor<i8>,\n        axis: usize\n    ) -> Tensor::<i8> {\n        quantization::qlinear_concat::qlinear_concat(\n            tensors,\n            scales,\n            zero_points,\n            y_scale,\n            y_zero_point,\n            axis,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<i8>, a_zero_point: @Tensor<i8>, alpha: i8\n    ) -> Tensor::<i8> {\n        quantization::qlinear_leakyrelu::qlinear_leakyrelu(\n            self,\n            a_scale,\n            a_zero_point,\n            alpha,\n            NumberTrait::new_unscaled(-127, true),\n            NumberTrait::new_unscaled(127, false)\n        )\n    }\n\n    fn slice(\n        self: @Tensor<i8>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<i8> {\n        core_tensor::slice::<i8>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(self: @Tensor<i8>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<i8> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<i8>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<i8>, axes: Option<Span<usize>>) -> Tensor<i8> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<i8>, axes: Span<usize>) -> Tensor<i8> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<i8>) -> Tensor<i8> {\n        math::sign::sign(*self)\n    }\n\n    fn clip(self: @Tensor<i8>, min: Option<i8>, max: Option<i8>) -> Tensor<i8> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<i8>) -> Tensor<i8> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<i8>, x: @Tensor<i8>, y: @Tensor<i8>) -> Tensor<i8> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i8> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i8> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i8> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<i8>) -> Tensor<i8> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<i8>, upper: bool, k: i64) -> Tensor<i8> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<i8>,\n        updates: Tensor<i8>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<i8> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn array_feature_extractor(self: @Tensor<i8>, indices: Tensor<usize>) -> Tensor<i8> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<i8>, threshold: Option<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_sum_square(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn not(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<i8>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<i8> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(self: Tensor<i8>, bias: Option<i8>, lambd: Option<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_mean(\n        self: @Tensor<i8>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i8> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<i8>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<i8> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<i8>, other: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_inf(\n        self: @Tensor<i8>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<i8>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_nd(\n        self: @Tensor<i8>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<i8> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<i8>, axis: usize, keepdims: bool) -> Tensor<i8> {\n        panic(array!['not supported'])\n    }\n\n    fn erf(self: @Tensor<i8>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn unique(\n        self: @Tensor<i8>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<i8>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn resize(\n        self: @Tensor<i8>,\n        roi: Option<Tensor<i8>>,\n        scales: Option<Span<i8>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<i8>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<i8>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn compress(self: @Tensor<i8>, condition: Tensor<usize>, axis: Option<usize>) -> Tensor<i8> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<i8>,\n        scale: @Tensor<i8>,\n        B: Option<@Tensor<i8>>,\n        axis: Option<i32>,\n        epsilon: Option<i8>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<i8>, Tensor<i8>, Tensor<i8>) {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<i8>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<i8>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<i8>, high: Option<i8>, low: Option<i8>, seed: Option<usize>\n    ) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn range(start: i8, end: i8, step: i8) -> Tensor<i8> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: i8, periodic: Option<usize>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: i8, periodic: Option<usize>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: i8, periodic: Option<usize>) -> Tensor<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<i8>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<i8>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<i8>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<i8> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<i8>) -> Option<Tensor<i8>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(self: @Tensor<i8>) -> (Tensor::<u32>, Tensor::<i8>, Tensor<i8>) {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter_nd(\n        self: @Tensor<i8>, updates: Tensor<i8>, indices: Tensor<usize>, reduction: Option<usize>\n    ) -> Tensor<i8> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<i8>,\n        default_list: Option<Span<i8>>,\n        default_tensor: Option<Tensor<i8>>,\n        keys: Option<Span<i8>>,\n        keys_tensor: Option<Tensor<i8>>,\n        values: Option<Span<i8>>,\n        values_tensor: Option<Tensor<i8>>\n    ) -> Tensor<i8> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<i8>` using the `Add` trait.\nimpl I8TensorAdd of Add<Tensor<i8>> {\n    /// Adds two `Tensor<i8>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i8>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<i8>` using the `Sub` trait.\nimpl I8TensorSub of Sub<Tensor<i8>> {\n    /// Subtracts two `Tensor<i8>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i8>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<i8>` using the `Mul` trait.\nimpl I8TensorMul of Mul<Tensor<i8>> {\n    /// Multiplies two `Tensor<i8>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i8>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<i8>` using the `Div` trait.\nimpl I8TensorDiv of Div<Tensor<i8>> {\n    /// Divides two `Tensor<i8>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<i8>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<i8>, rhs: Tensor<i8>) -> Tensor<i8> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<i8>` using the `PartialEq` trait.\nimpl I8TensorPartialEq of PartialEq<Tensor<i8>> {\n    fn eq(lhs: @Tensor<i8>, rhs: @Tensor<i8>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<i8>, rhs: @Tensor<i8>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\n/// Implements partial ord for two `Tensor<i8>` using `PartialOrd` trait.\nimpl I8TensorPartialOrd of PartialOrd<Tensor<i8>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<i8>, rhs: Tensor<i8>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<i8>, rhs: Tensor<i8>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<i8>, rhs: Tensor<i8>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<i8>, rhs: Tensor<i8>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\nfn tensor_eq(mut lhs: Tensor<i8>, mut rhs: Tensor<i8>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() == 0 && !is_eq {\n        is_eq = lhs.data.pop_front().unwrap() == rhs.data.pop_front().unwrap();\n    };\n\n    is_eq\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/implementations/tensor_u32.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::helpers::SpanPartialOrd;\nuse orion::operators::tensor::core::{\n    new_tensor, constant_of_shape, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape,\n    at_tensor,\n};\nuse orion::operators::tensor::{math, linalg, quantization, core as core_tensor, ml, manipulation};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::implementations::{tensor_i8::I8Tensor, tensor_bool::BoolTensor};\n\nimpl U32Tensor of TensorTrait<u32> {\n    fn new(shape: Span<usize>, data: Span<u32>) -> Tensor<u32> {\n        new_tensor(shape, data)\n    }\n\n    fn constant_of_shape(shape: Span<usize>, value: u32) -> Tensor<u32> {\n        constant_of_shape(shape, value)\n    }\n\n    fn at(self: @Tensor<u32>, indices: Span<usize>) -> u32 {\n        *at_tensor(self, indices)\n    }\n\n    fn add(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n\n    fn sub(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n\n    fn mul(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n\n    fn div(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n\n    fn min_in_tensor(self: @Tensor<u32>) -> u32 {\n        math::min_in_tensor::min_in_tensor::<u32, u32>(*self.data)\n    }\n\n    fn min(tensors: Span<Tensor<u32>>) -> Tensor<u32> {\n        math::min::min(tensors)\n    }\n\n    fn max_in_tensor(self: @Tensor<u32>) -> u32 {\n        math::max_in_tensor::max_in_tensor(*self.data)\n    }\n\n    fn max(tensors: Span<Tensor<u32>>) -> Tensor<u32> {\n        math::max::max(tensors)\n    }\n\n    fn stride(self: @Tensor<u32>) -> Span<usize> {\n        stride(*self.shape)\n    }\n\n    fn ravel_index(self: @Tensor<u32>, indices: Span<usize>) -> usize {\n        ravel_index(*self.shape, indices)\n    }\n\n    fn unravel_index(self: @Tensor<u32>, index: usize) -> Span<usize> {\n        unravel_index(index, *self.shape)\n    }\n\n    fn reshape(self: @Tensor<u32>, target_shape: Span<i32>, allowzero: bool) -> Tensor<u32> {\n        reshape(self, target_shape, allowzero)\n    }\n\n    fn reduce_sum(\n        self: @Tensor<u32>,\n        axes: Option<Span<i32>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<u32> {\n        math::reduce_sum::reduce_sum(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_prod(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        math::reduce_prod::reduce_prod(self, axis, keepdims)\n    }\n\n    fn argmax(\n        self: @Tensor<u32>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<i32> {\n        math::argmax::argmax(self, axis, keepdims, select_last_index)\n    }\n\n    fn argmin(\n        self: @Tensor<u32>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n    ) -> Tensor<usize> {\n        math::argmin::argmin(self, axis, keepdims, select_last_index)\n    }\n\n    fn transpose(self: @Tensor<u32>, axes: Span<usize>) -> Tensor<u32> {\n        linalg::transpose::transpose(self, axes)\n    }\n\n    fn matmul(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<u32> {\n        linalg::matmul::matmul(self, other)\n    }\n\n    fn exp(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn log(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn equal(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<usize> {\n        math::equal::equal(self, other)\n    }\n\n    fn greater(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<usize> {\n        math::greater::greater(self, other)\n    }\n\n    fn greater_equal(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<usize> {\n        math::greater_equal::greater_equal(self, other)\n    }\n\n    fn less(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<i32> {\n        math::less::less(self, other)\n    }\n\n    fn less_equal(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<i32> {\n        math::less_equal::less_equal(self, other)\n    }\n\n    fn abs(self: @Tensor<u32>) -> Tensor<u32> {\n        math::abs::abs(*self)\n    }\n\n    fn neg(self: @Tensor<u32>) -> Tensor<u32> {\n        math::neg::neg(*self)\n    }\n\n    fn ceil(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn sin(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cos(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn asin(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cumsum(\n        self: @Tensor<u32>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n    ) -> Tensor<u32> {\n        math::cumsum::cumsum(self, axis, exclusive, reverse)\n    }\n\n    fn flatten(self: @Tensor<u32>, axis: usize) -> Tensor<u32> {\n        math::flatten::flatten(self, axis)\n    }\n\n    fn sinh(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn tanh(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn cosh(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn acosh(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn asinh(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn atan(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn xor(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<usize> {\n        math::xor::xor(self, other)\n    }\n\n    fn or(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<usize> {\n        math::or::or(self, other)\n    }\n\n    fn acos(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn onehot(\n        self: @Tensor<u32>, depth: usize, axis: Option<usize>, values: Span<usize>\n    ) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn sqrt(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn concat(tensors: Span<Tensor<u32>>, axis: usize,) -> Tensor<u32> {\n        math::concat::concat(tensors, axis)\n    }\n\n    fn quantize_linear(\n        self: @Tensor<u32>, y_scale: @Tensor<u32>, y_zero_point: @Tensor<u32>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn dequantize_linear(\n        self: @Tensor<i8>, x_scale: @Tensor<u32>, x_zero_point: @Tensor<u32>\n    ) -> Tensor::<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_add(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<u32>,\n        a_zero_point: @Tensor<u32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<u32>,\n        b_zero_point: @Tensor<u32>,\n        y_scale: @Tensor<u32>,\n        y_zero_point: @Tensor<u32>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_mul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<u32>,\n        a_zero_point: @Tensor<u32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<u32>,\n        b_zero_point: @Tensor<u32>,\n        y_scale: @Tensor<u32>,\n        y_zero_point: @Tensor<u32>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_matmul(\n        self: @Tensor<i8>,\n        a_scale: @Tensor<u32>,\n        a_zero_point: @Tensor<u32>,\n        b: @Tensor<i8>,\n        b_scale: @Tensor<u32>,\n        b_zero_point: @Tensor<u32>,\n        y_scale: @Tensor<u32>,\n        y_zero_point: @Tensor<u32>\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_concat(\n        tensors: Span<Tensor<i8>>,\n        scales: Span<Tensor<u32>>,\n        zero_points: Span<Tensor<u32>>,\n        y_scale: @Tensor<u32>,\n        y_zero_point: @Tensor<u32>,\n        axis: usize,\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn qlinear_leakyrelu(\n        self: @Tensor<i8>, a_scale: @Tensor<u32>, a_zero_point: @Tensor<u32>, alpha: u32\n    ) -> Tensor::<i8> {\n        panic(array!['not supported!'])\n    }\n\n    fn slice(\n        self: @Tensor<u32>,\n        starts: Span<usize>,\n        ends: Span<usize>,\n        axes: Option<Span<usize>>,\n        steps: Option<Span<usize>>\n    ) -> Tensor<u32> {\n        core_tensor::slice::<u32>(self, starts, ends, axes, steps)\n    }\n\n    fn gather(self: @Tensor<u32>, indices: Tensor<i32>, axis: Option<i32>) -> Tensor<u32> {\n        math::gather::gather(self, indices, axis)\n    }\n\n    fn nonzero(self: @Tensor<u32>) -> Tensor<usize> {\n        core_tensor::nonzero(self)\n    }\n\n    fn squeeze(self: @Tensor<u32>, axes: Option<Span<usize>>) -> Tensor<u32> {\n        core_tensor::squeeze(self, axes)\n    }\n\n    fn unsqueeze(self: @Tensor<u32>, axes: Span<usize>) -> Tensor<u32> {\n        core_tensor::unsqueeze(self, axes)\n    }\n\n    fn sign(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn clip(self: @Tensor<u32>, min: Option<u32>, max: Option<u32>) -> Tensor<u32> {\n        core_tensor::clip(self, min, max)\n    }\n\n    fn and(self: @Tensor<bool>, other: @Tensor<bool>) -> Tensor<bool> {\n        math::and::and(self, other)\n    }\n\n    fn identity(self: @Tensor<u32>) -> Tensor<u32> {\n        core_tensor::identity(self)\n    }\n\n    fn where(self: @Tensor<u32>, x: @Tensor<u32>, y: @Tensor<u32>) -> Tensor<u32> {\n        math::where::where(self, x, y)\n    }\n\n    fn bitwise_and(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<u32> {\n        math::bitwise_and::bitwise_and(self, other)\n    }\n\n    fn bitwise_xor(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<u32> {\n        math::bitwise_xor::bitwise_xor(self, other)\n    }\n\n    fn bitwise_or(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<u32> {\n        math::bitwise_or::bitwise_or(self, other)\n    }\n\n    fn round(self: @Tensor<u32>) -> Tensor<u32> {\n        math::round::round(*self)\n    }\n\n    fn reduce_l1(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        math::reduce_l1::reduce_l1(self, axis, keepdims)\n    }\n\n    fn trilu(self: @Tensor<u32>, upper: bool, k: i64) -> Tensor<u32> {\n        linalg::trilu::trilu(self, upper, k)\n    }\n\n    fn scatter(\n        self: @Tensor<u32>,\n        updates: Tensor<u32>,\n        indices: Tensor<usize>,\n        axis: Option<usize>,\n        reduction: Option<usize>\n    ) -> Tensor<u32> {\n        math::scatter::scatter(self, updates, indices, axis, reduction)\n    }\n\n    fn array_feature_extractor(self: @Tensor<u32>, indices: Tensor<usize>) -> Tensor<u32> {\n        ml::array_feature_extractor::array_feature_extractor(*self, indices)\n    }\n\n    fn binarizer(self: @Tensor<u32>, threshold: Option<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_sum_square(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        math::reduce_sum_square::reduce_sum_square(self, axis, keepdims)\n    }\n\n    fn reduce_l2(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn not(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_elements(\n        self: @Tensor<u32>, indices: Tensor<i32>, axis: Option<i32>\n    ) -> Tensor<u32> {\n        math::gather_elements::gather_elements(self, indices, axis)\n    }\n\n    fn shrink(self: Tensor<u32>, bias: Option<u32>, lambd: Option<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_mean(\n        self: @Tensor<u32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<u32> {\n        math::reduce_mean::reduce_mean(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn reduce_min(\n        self: @Tensor<u32>,\n        axes: Option<Span<usize>>,\n        keepdims: Option<bool>,\n        noop_with_empty_axes: Option<bool>\n    ) -> Tensor<u32> {\n        math::reduce_min::reduce_min(self, axes, keepdims, noop_with_empty_axes)\n    }\n\n    fn pow(self: @Tensor<u32>, other: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn is_inf(\n        self: @Tensor<u32>, detect_negative: Option<u8>, detect_positive: Option<u8>\n    ) -> Tensor<bool> {\n        math::is_inf::is_inf(self, detect_negative, detect_positive)\n    }\n\n    fn is_nan(self: @Tensor<u32>) -> Tensor<bool> {\n        panic(array!['not supported!'])\n    }\n\n    fn gather_nd(\n        self: @Tensor<u32>, indices: Tensor<usize>, batch_dims: Option<usize>\n    ) -> Tensor<u32> {\n        math::gather_nd::gather_nd(self, indices, batch_dims)\n    }\n\n    fn reduce_log_sum(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn reduce_log_sum_exp(self: @Tensor<u32>, axis: usize, keepdims: bool) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn erf(self: @Tensor<u32>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn unique(\n        self: @Tensor<u32>, axis: Option<usize>, sorted: Option<bool>\n    ) -> (Tensor<u32>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n        manipulation::unique::unique(self, axis, sorted)\n    }\n\n    fn resize(\n        self: @Tensor<u32>,\n        roi: Option<Tensor<u32>>,\n        scales: Option<Span<u32>>,\n        sizes: Option<Span<usize>>,\n        antialias: Option<usize>,\n        axes: Option<Span<usize>>,\n        coordinate_transformation_mode: Option<math::resize::TRANSFORMATION_MODE>,\n        cubic_coeff_a: Option<u32>,\n        exclude_outside: Option<bool>,\n        extrapolation_value: Option<u32>,\n        keep_aspect_ratio_policy: Option<math::resize::KEEP_ASPECT_RATIO_POLICY>,\n        mode: Option<math::resize::MODE>,\n        nearest_mode: Option<math::resize::NEAREST_MODE>,\n    ) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn compress(self: @Tensor<u32>, condition: Tensor<usize>, axis: Option<usize>) -> Tensor<u32> {\n        math::compress::compress(self, condition, axis)\n    }\n\n    fn layer_normalization(\n        self: @Tensor<u32>,\n        scale: @Tensor<u32>,\n        B: Option<@Tensor<u32>>,\n        axis: Option<i32>,\n        epsilon: Option<u32>,\n        stash_type: Option<usize>,\n    ) -> (Tensor<u32>, Tensor<u32>, Tensor<u32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn split(\n        self: @Tensor<u32>, axis: usize, num_outputs: Option<usize>, spl: Option<Tensor<usize>>\n    ) -> Array<Tensor<u32>> {\n        manipulation::split::split(self, axis, num_outputs, spl)\n    }\n\n    fn random_uniform_like(\n        tensor: @Tensor<u32>, high: Option<u32>, low: Option<u32>, seed: Option<usize>\n    ) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn range(start: u32, end: u32, step: u32) -> Tensor<u32> {\n        math::range::range(start, end, step)\n    }\n\n    fn hann_window(size: u32, periodic: Option<usize>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn hamming_window(size: u32, periodic: Option<usize>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn blackman_window(size: u32, periodic: Option<usize>) -> Tensor<u32> {\n        panic(array!['not supported!'])\n    }\n\n    fn split_to_sequence(\n        self: @Tensor<u32>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n    ) -> Array<Tensor<u32>> {\n        manipulation::split_to_sequence::split_to_sequence(self, axis, keepdims, split)\n    }\n\n    fn reverse_sequence(\n        self: @Tensor<u32>,\n        sequence_lens: Tensor<usize>,\n        batch_axis: Option<usize>,\n        time_axis: Option<usize>\n    ) -> Tensor<u32> {\n        manipulation::reverse_sequence::reverse_sequence(self, sequence_lens, batch_axis, time_axis)\n    }\n\n    fn optional(self: @Tensor<u32>) -> Option<Tensor<u32>> {\n        manipulation::optional::optional(self)\n    }\n\n    fn dynamic_quantize_linear(self: @Tensor<u32>) -> (Tensor::<u32>, Tensor::<u32>, Tensor<u32>) {\n        panic(array!['not supported!'])\n    }\n\n    fn scatter_nd(\n        self: @Tensor<u32>, updates: Tensor<u32>, indices: Tensor<usize>, reduction: Option<usize>\n    ) -> Tensor<u32> {\n        math::scatter_nd::scatter_nd(self, updates, indices, reduction)\n    }\n\n    fn label_encoder(\n        self: @Tensor<u32>,\n        default_list: Option<Span<u32>>,\n        default_tensor: Option<Tensor<u32>>,\n        keys: Option<Span<u32>>,\n        keys_tensor: Option<Tensor<u32>>,\n        values: Option<Span<u32>>,\n        values_tensor: Option<Tensor<u32>>\n    ) -> Tensor<u32> {\n        ml::label_encoder::label_encoder(\n            self, default_list, default_tensor, keys, keys_tensor, values, values_tensor\n        )\n    }\n}\n\n/// Implements addition for `Tensor<u32>` using the `Add` trait.\nimpl U32TensorAdd of Add<Tensor<u32>> {\n    /// Adds two `Tensor<u32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<u32>` instance representing the result of the element-wise addition.\n    fn add(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::add(@lhs, @rhs)\n    }\n}\n\n/// Implements subtraction for `Tensor<u32>` using the `Sub` trait.\nimpl U32TensorSub of Sub<Tensor<u32>> {\n    /// Subtracts two `Tensor<u32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<u32>` instance representing the result of the element-wise subtraction.\n    fn sub(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::sub(@lhs, @rhs)\n    }\n}\n\n/// Implements multiplication for `Tensor<u32>` using the `Mul` trait.\nimpl U32TensorMul of Mul<Tensor<u32>> {\n    /// Multiplies two `Tensor<u32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<u32>` instance representing the result of the element-wise multiplication.\n    fn mul(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::mul(@lhs, @rhs)\n    }\n}\n\n/// Implements division for `Tensor<u32>` using the `Div` trait.\nimpl U32TensorDiv of Div<Tensor<u32>> {\n    /// Divides two `Tensor<u32>` instances element-wise.\n    ///\n    /// # Arguments\n    /// * `lhs` - The first tensor.\n    /// * `rhs` - The second tensor.\n    ///\n    /// # Returns\n    /// * A `Tensor<u32>` instance representing the result of the element-wise division.\n    fn div(lhs: Tensor<u32>, rhs: Tensor<u32>) -> Tensor<u32> {\n        math::arithmetic::div(@lhs, @rhs)\n    }\n}\n\n/// Implements partial equal for two `Tensor<u32>` using the `PartialEq` trait.\nimpl U32TensorPartialEq of PartialEq<Tensor<u32>> {\n    fn eq(lhs: @Tensor<u32>, rhs: @Tensor<u32>) -> bool {\n        tensor_eq(*lhs, *rhs)\n    }\n\n    fn ne(lhs: @Tensor<u32>, rhs: @Tensor<u32>) -> bool {\n        !tensor_eq(*lhs, *rhs)\n    }\n}\n\n\nimpl U32TryIntoI8 of TryInto<u32, i8> {\n    fn try_into(self: u32) -> Option<i8> {\n        let number_felt: felt252 = self.into();\n        let number_i8: i8 = number_felt.try_into().unwrap();\n        Option::Some(number_i8)\n    }\n}\n\n/// Implements partial ord for two `Tensor<u32>` using `PartialOrd` trait.\nimpl U32TensorPartialOrd of PartialOrd<Tensor<u32>> {\n    #[inline(always)]\n    fn ge(lhs: Tensor<u32>, rhs: Tensor<u32>) -> bool {\n        SpanPartialOrd::ge(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn gt(lhs: Tensor<u32>, rhs: Tensor<u32>) -> bool {\n        SpanPartialOrd::gt(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn le(lhs: Tensor<u32>, rhs: Tensor<u32>) -> bool {\n        SpanPartialOrd::le(lhs.data, rhs.data)\n    }\n\n    #[inline(always)]\n    fn lt(lhs: Tensor<u32>, rhs: Tensor<u32>) -> bool {\n        SpanPartialOrd::lt(lhs.data, rhs.data)\n    }\n}\n\n// Internals\n\nfn tensor_eq(mut lhs: Tensor<u32>, mut rhs: Tensor<u32>,) -> bool {\n    let mut is_eq = true;\n\n    while lhs.shape.len() != 0 && is_eq {\n        is_eq = lhs.shape.pop_front().unwrap() == rhs.shape.pop_front().unwrap();\n    };\n\n    if !is_eq {\n        return false;\n    }\n\n    while lhs.data.len() != 0 && is_eq {\n        is_eq = lhs.data.pop_front().unwrap() == rhs.data.pop_front().unwrap();\n    };\n\n    is_eq\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/linalg.cairo",
        "content": "mod matmul;\nmod transpose;\nmod trilu;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/linalg/matmul.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::matmul docstring\nfn matmul<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<T> {\n    let self_shape = *self.shape;\n    let other_shape = *other.shape;\n    let self_ndim = (self_shape).len();\n    let other_ndim = (other_shape).len();\n\n    assert(self_ndim <= 2 || other_ndim <= 2, 'supports only 1D and 2D matmul');\n\n    //! Case: Both tensors are 1-dimensional\n    if self_ndim == 1 && other_ndim == 1 {\n        let dot = dot_product((*self).data, (*other).data);\n        let mut result_shape = ArrayTrait::new();\n        let mut result_data = ArrayTrait::new();\n        result_shape.append(1);\n        result_data.append(dot);\n\n        return TensorTrait::new(result_shape.span(), result_data.span());\n    }\n\n    let self_shape = prepare_shape_for_matmul(self_shape, true);\n    let other_shape = prepare_shape_for_matmul(other_shape, false);\n\n    let result = matrix_multiply(*self.data, self_shape, *other.data, other_shape);\n\n    let result_shape = adjust_output_shape_after_matmul(result.shape, self_ndim, other_ndim);\n\n    TensorTrait::new(result_shape, result.data)\n}\n\n/// Computes the dot product of two 1-dimensional i32 tensors.\n///\n/// # Arguments\n/// * `vec1` - A span containing the data elements of the first vector as i32 elements.\n/// * `vec2` - A span containing the data elements of the second vector as i32 elements.\n///\n/// # Panics\n/// * Panics if the lengths of the vectors do not match.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * An i32 representing the dot product of the two vectors.\nfn dot_product<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut vec1: Span<T>, mut vec2: Span<T>\n) -> T {\n    assert(vec1.len() == vec2.len(), 'vector lengths do not match');\n\n    let mut result: T = NumberTrait::zero();\n\n    loop {\n        match vec1.pop_front() {\n            Option::Some(vec1_item) => {\n                let element_product = *vec1_item * *vec2.pop_front().unwrap();\n                result += element_product;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    result\n}\n\n\n/// Computes the matrix multiplication of two 2-dimensional i32 tensors.\n///\n/// # Arguments\n/// * `mat1` - A Span containing the data elements of the first matrix as i32 elements.\n/// * `mat1_shape` - A Span containing the shape of the first matrix as usize elements.\n/// * `mat2` - A Span containing the data elements of the second matrix as i32 elements.\n/// * `mat2_shape` - A Span containing the shape of the second matrix as usize elements.\n///\n/// # Panics\n/// * Panics if the inner dimensions of the matrices do not match.\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * Returns the restulting i32 tensor.\nfn matrix_multiply<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mat1: Span<T>, mat1_shape: Span<usize>, mat2: Span<T>, mat2_shape: Span<usize>\n) -> Tensor<T> {\n    let m = *mat1_shape[0];\n    let n = *mat1_shape[1];\n    let p = *mat2_shape[1];\n\n    let mut result_data: Array<T> = array![];\n    let mut result_shape: Array<usize> = array![m, p];\n\n    let mut i = 0_usize;\n    while i != m {\n        let mut j = 0_usize;\n        while j != p {\n            let mut sum: T = NumberTrait::zero();\n            let mut k = 0_usize;\n            while k != n {\n                let mat1_index = i * n + k;\n                let mat2_index = k * p + j;\n                sum += *mat1[mat1_index] * *mat2[mat2_index];\n\n                k += 1;\n            };\n\n            result_data.append(sum);\n            j += 1;\n        };\n\n        i += 1;\n    };\n\n    TensorTrait::new(result_shape.span(), result_data.span())\n}\n\n/// Prepares the shape of a tensor for matrix multiplication.\n///\n/// # Arguments\n/// * `shape` - A mutable span representing the shape of the tensor.\n/// * `is_first_tensor` - A boolean indicating whether the input tensor is the first (left) \n///   tensor in the matrix multiplication operation.\n///\n/// # Behavior\n/// This function adjusts the shapes of the tensors based on their dimensionality:\n/// * If the first tensor is 1-dimensional, a 1 is prepended to its shape.\n/// * If the second tensor is 1-dimensional, a 1 is appended to its shape.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A span representing the adjusted shape of the tensor.\nfn prepare_shape_for_matmul(mut shape: Span<usize>, is_first_tensor: bool) -> Span<usize> {\n    let ndim = shape.len();\n\n    if ndim == 1 && is_first_tensor {\n        // Prepend 1 to shape if it's 1-dimensional\n        let mut shape_adjusted = ArrayTrait::new();\n        shape_adjusted.append(1);\n\n        loop {\n            match shape.pop_front() {\n                Option::Some(item) => { shape_adjusted.append(*item); },\n                Option::None => { break; }\n            };\n        };\n\n        return shape_adjusted.span();\n    } else if ndim == 1 && !is_first_tensor {\n        // Append 1 to shape if it's 1-dimensional\n        let mut shape_adjusted = ArrayTrait::new();\n\n        loop {\n            match shape.pop_front() {\n                Option::Some(item) => { shape_adjusted.append(*item) },\n                Option::None => { break; }\n            };\n        };\n\n        shape_adjusted.append(1);\n\n        return shape_adjusted.span();\n    }\n\n    shape\n}\n\n/// Adjusts the output shape of the matrix multiplication result based on the\n/// original dimensionality of the input tensors.\n///\n/// # Arguments\n/// * `output_shape` - A mutable span representing the shape of the matrix multiplication result.\n/// * `self_dim` - A usize representing the dimensionality of the first input tensor.\n/// * `other_dim` - A usize representing the dimensionality of the second input tensor.\n///\n/// # Behavior\n/// This function adjusts the output shape based on the dimensionality of the input tensors:\n/// * If the first input tensor was 1-dimensional, the prepended 1 is removed from the output shape.\n/// * If the second input tensor was 1-dimensional, the appended 1 is removed from the output shape.\n///\n/// # Returns\n/// * A span representing the adjusted output shape of the matrix multiplication result.\nfn adjust_output_shape_after_matmul(\n    mut output_shape: Span<usize>, self_dim: usize, other_dim: usize\n) -> Span<usize> {\n    // If self_shape was 1-dimensional, remove the prepended 1 from the output_shape.\n    if self_dim == 1 {\n        let _ = output_shape.pop_front().unwrap();\n    }\n\n    // If other_shape was 1-dimensional, remove the appended 1 from the output_shape.\n    if other_dim == 1 {\n        let _ = output_shape.pop_back().unwrap();\n    }\n\n    output_shape\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/linalg/transpose.cairo",
        "content": "use orion::operators::tensor::core::{\n    new_tensor, stride, Tensor, TensorTrait, ravel_index, unravel_index, reshape\n};\nuse orion::operators::tensor::helpers::{len_from_shape, find_axis, permutation_output_shape};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::transpose docstring\nfn transpose<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: @Tensor<T>, axes: Span<usize>\n) -> Tensor<T> {\n    if (*self.shape).len() == 1 {\n        return self.identity();\n    }\n\n    assert(axes.len() == (*self.shape).len(), 'shape and axes length unequal');\n\n    if (*self.shape).len() == 2 {\n        return transpose2D(@(*self));\n    }\n\n    let output_shape = permutation_output_shape(*self.shape, axes);\n    let output_data_len = len_from_shape(output_shape);\n\n    let mut output_data: Array<T> = array![];\n\n    let mut output_index: usize = 0;\n    while output_index != output_data_len {\n        let output_indices = unravel_index(output_index, output_shape);\n        let mut input_indices: Array<u32> = array![];\n\n        let mut output_axis: usize = 0;\n        while output_axis != axes.len() {\n            let input_axis = find_axis(axes, output_axis);\n            input_indices.append(*output_indices[input_axis]);\n\n            output_axis += 1;\n        };\n\n        let input_index = ravel_index(*self.shape, input_indices.span());\n        output_data.append(*(*self.data)[input_index]);\n\n        output_index += 1;\n    };\n\n    TensorTrait::new(output_shape, output_data.span())\n}\n\nfn transpose2D<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: @Tensor<T>\n) -> Tensor<T> {\n    assert((*self.shape).len() == 2, 'transpose a 2D tensor');\n\n    let mut output_data: Array<T> = array![];\n\n    let n = *self.shape[0];\n    let m = *self.shape[1];\n\n    let mut output_shape: Array<u32> = array![m, n];\n\n    let mut j: usize = 0;\n    while j != m {\n        let mut i = 0;\n        while i != n {\n            output_data.append(*(*self.data)[i * m + j]);\n\n            i += 1;\n        };\n\n        j += 1;\n    };\n\n    TensorTrait::new(output_shape.span(), output_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/linalg/trilu.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::trilu docstring\nfn trilu<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, upper: bool, k: i64\n) -> Tensor<T> {\n    assert((*self.shape).len() >= 2, 'must have at least 2 dimensions');\n\n    let shape_len = (*self.shape).len();\n    let mut output_data: Array<T> = array![];\n    let mut output_size: Array<u32> = array![];\n\n    let mut batch_size = 1;\n    let mut n: u32 = 0;\n    let mut m: u32 = 0;\n\n    let mut self_shape = *self.shape;\n    let mut i = 0;\n    loop {\n        match self_shape.pop_front() {\n            Option::Some(val) => {\n                if i == shape_len - 2 {\n                    n = *val;\n                } else if i == shape_len - 1 {\n                    m = *val;\n                } else {\n                    batch_size *= *val;\n                }\n                i += 1;\n                output_size.append(*val);\n            },\n            Option::None => { break; }\n        }\n    };\n\n    let mut self_data = *self.data;\n    let mut b = 0;\n    loop {\n        if b == batch_size {\n            break ();\n        }\n\n        let mut i = 0;\n        loop {\n            if i == n {\n                break ();\n            }\n            let mut j = 0;\n            loop {\n                if j == m {\n                    break ();\n                }\n\n                let ii: felt252 = i.into();\n                let jj: felt252 = j.into();\n\n                let iii: i64 = ii.try_into().unwrap();\n                let jjj: i64 = jj.try_into().unwrap();\n\n                let result = match self_data.pop_front() {\n                    Option::Some(val) => {\n                        if (upper && (iii + k <= jjj)) || (!upper && (iii + k >= jjj)) {\n                            *val\n                        } else {\n                            NumberTrait::zero()\n                        }\n                    },\n                    Option::None => { break; }\n                };\n\n                output_data.append(result);\n\n                j += 1;\n            };\n\n            i += 1;\n        };\n\n        b += 1;\n    };\n\n    TensorTrait::new(*self.shape, output_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation.cairo",
        "content": "mod unique;\nmod split;\nmod split_to_sequence;\nmod reverse_sequence;\nmod optional;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation/optional.cairo",
        "content": "use orion::operators::tensor::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::optional docstring\nfn optional<T, +Copy<T>, +Drop<T>, impl TOption: OptionTrait<T>>(\n    self: @Tensor<T>\n) -> Option<Tensor<T>> {\n    Option::Some(*self)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation/reverse_sequence.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: TensorTrait::reverse_sequence docstring\nfn reverse_sequence<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: @Tensor<T>,\n    sequence_lens: Tensor<usize>,\n    batch_axis: Option<usize>,\n    time_axis: Option<usize>\n) -> Tensor<T> {\n    let shape = *self.shape;\n    let mut data: Array<T> = array![];\n\n    let has_batch_axis: usize = match batch_axis {\n        Option::Some(value) => {\n            assert!((value != 0) || (value != 1), \"batch_axis must be one of 1 or 0.\");\n            value\n        },\n        Option::None => 0,\n    };\n\n    let has_time_axis: usize = match time_axis {\n        Option::Some(value) => {\n            assert!((value != 0) || (value != 1), \"time_axis must be one of 1 or 0.\");\n            value\n        },\n        Option::None => 1,\n    };\n\n    assert!(has_batch_axis != has_time_axis, \"batch_axis and time_axis cannot be equal\");\n    assert((*self.data).len() >= 2, 'Tensor of rank r >= 2');\n    let control: bool = if has_batch_axis == 0 && has_time_axis == 1 {\n        true\n    } else {\n        false\n    };\n\n    let mut index: Array<usize> = reverse_index(*self.shape, sequence_lens, control);\n    loop {\n        match index.pop_front() {\n            Option::Some(ele) => { data.append(*((*self).data).at(ele)); },\n            Option::None => { break; }\n        }\n    };\n\n    TensorTrait::<T>::new(shape, data.span())\n}\n\n\nfn reverse_index(shape: Span<usize>, sequence_lens: Tensor<usize>, control: bool) -> Array<usize> {\n    let x: usize = *shape.at(0);\n    let y: usize = *shape.at(1);\n    let mut result: Array<usize> = array![];\n\n    if control {\n        // [i, slice]\n        assert!(\n            sequence_lens.data.len() <= x, \"The length of sequence_lens cannot exceed batch_axis\"\n        );\n        let mut i: usize = 0;\n        while i != x {\n            let reverse: usize = (*sequence_lens.data.at(i));\n            assert!(\n                reverse <= y && reverse >= 1,\n                \"sequence_lens must be greater than one and less than batch_size\"\n            );\n            let mut j: usize = reverse - 1;\n            loop {\n                if j == 0 {\n                    result.append(i * y + j);\n                    break;\n                }\n\n                result.append(i * y + j);\n                j -= 1;\n            };\n            let current_index_len: usize = (i + 1) * y - 1;\n            let mut j: usize = result.len();\n            while j != current_index_len + 1 {\n                result.append(j);\n                j += 1;\n            };\n\n            i += 1;\n        };\n    } else {\n        // [slice, i]\n        assert!(\n            sequence_lens.data.len() <= y, \"The length of sequence_lens cannot exceed time_axis\"\n        );\n        let mut tmp = ArrayTrait::<usize>::new();\n        let mut i: usize = 0;\n        while i != y {\n            let reverse: usize = *sequence_lens.data.at(i);\n            assert!(\n                reverse <= x && reverse >= 1,\n                \"sequence_lens must be greater than one and less than batch_size\"\n            );\n\n            let mut j: usize = reverse - 1;\n            loop {\n                if j == 0 {\n                    tmp.append(j * y + i);\n                    break;\n                }\n                tmp.append(j * y + i);\n                j -= 1;\n            };\n            let mut j: usize = reverse;\n            while j != x {\n                tmp.append(j * y + i);\n                j += 1;\n            };\n\n            i += 1;\n        };\n\n        let tmp = tmp.span();\n        let mut i: usize = 0;\n        while i != x {\n            let mut j: usize = 0;\n            while j != y {\n                result.append((*tmp.at(j * x + i)));\n                j += 1;\n            };\n\n            i += 1;\n        };\n    }\n\n    result\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation/split.cairo",
        "content": "use orion::operators::tensor::{Tensor, TensorTrait, U32Tensor};\nuse orion::operators::matrix::{MutMatrixTrait, MutMatrix, MutMatrixImpl};\n\n/// Cf: TensorTrait::split docstring\nfn split<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    self: @Tensor<T>, axis: usize, num_outputs: Option<usize>, split: Option<Tensor<usize>>\n) -> Array<Tensor<T>> {\n    let has_num_outputs = match num_outputs {\n        Option::Some => true,\n        Option::None => false,\n    };\n    let has_split = match split {\n        Option::Some => true,\n        Option::None => false,\n    };\n    assert(!(has_num_outputs && has_split), 'split or num_outputs not both.');\n    assert(has_num_outputs || has_split, 'split or num_outputs not both.');\n\n    let mut splited_t: Array<Tensor<T>> = array![];\n\n    let rank = (*self).shape.len();\n    // assert(axis < rank && axis > -rank, 'axis out of dimensions');\n    assert(axis < rank, 'axis out of dimensions');\n\n    if (has_num_outputs) {\n        splited_t = split_num_outputs(self, axis, num_outputs.unwrap());\n    } else {\n        splited_t = split_has_split(self, axis, split.unwrap());\n    }\n\n    splited_t\n}\n\n/// Subfunction split for tensors (wth num_outputs).\n/// Cf: TensorTrait::split docstring\nfn split_num_outputs<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    t: @Tensor<T>, mut axis: usize, num_outputs: usize\n) -> Array<Tensor<T>> {\n    let mut splited_t: Array<Tensor<T>> = array![];\n    let mut div: usize = 0;\n    // consturct split array\n    let mut split: Array<usize> = array![];\n    // if axis==0 {\n    //     axis = 1;\n    // }\n    if (*(*t).shape.at(axis) % num_outputs == 0) {\n        div = *(*t).shape.at(axis) / num_outputs;\n        let mut i = 0;\n        while i != num_outputs {\n            split.append(div);\n            i += 1;\n        };\n    } else {\n        div = *(*t).shape.at(axis) / num_outputs + 1;\n        let mut i = 0;\n        while i != num_outputs {\n            split.append(div);\n            i += 1;\n        };\n\n        match split.pop_front() {\n            Option::Some(split_last_one) => {\n                split.append(split_last_one + *(*t).shape.at(axis) - div * (num_outputs - 1));\n            },\n            Option::None => { assert(false, 'split is none array'); }\n        }\n    }\n\n    let mut sli: MutMatrix<usize> = MutMatrixImpl::new((*t).shape.len(), 2);\n    let mut pos: usize = 0;\n    let mut i = 0;\n    while i != (*t).shape.len() {\n        let s: usize = *(*t).shape.at(i);\n        sli.set(i, 0, 0);\n        sli.set(i, 1, s);\n        i += 1;\n    };\n\n    let mut i: usize = 0;\n    while i != split.len() {\n        let spl = *split.at(i);\n        sli.set(axis, 0, pos);\n        pos += spl;\n        sli.set(axis, 1, pos);\n\n        let end_ele_0 = match sli.get(axis, 0) {\n            Option::Some(res) => res,\n            Option::None => {\n                assert(false, 'Get end_ele_0 is failed');\n                0\n            },\n        };\n        let end_ele_1 = match sli.get(axis, 1) {\n            Option::Some(res) => res,\n            Option::None => {\n                assert(false, 'Get end_ele_0 is failed');\n                0\n            },\n        };\n        let starts: Span<usize> = array![sli.get(0, 0).unwrap(), end_ele_0].span();\n        let ends: Span<usize> = array![sli.get(0, 1).unwrap(), end_ele_1].span();\n        let axes: Option<Span<usize>> = Option::None(());\n        let steps: Option<Span<usize>> = Option::None(());\n        let sub_t: Tensor<T> = t.slice(starts, ends, axes, steps);\n        splited_t.append(sub_t);\n        i += 1;\n    };\n\n    splited_t\n}\n\n/// Subfunction split for tensors (wth split).\n/// Cf: TensorTrait::split docstring\nfn split_has_split<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    t: @Tensor<T>, axis: usize, split: Tensor<u32>\n) -> Array<Tensor<T>> {\n    let mut splited_t: Array<Tensor<T>> = array![];\n    let mut sli: MutMatrix<usize> = MutMatrixImpl::new((*t).shape.len(), 2);\n    let mut pos: usize = 0;\n    let mut i = 0;\n    while i != (*t).shape.len() {\n        let s: usize = *(*t).shape.at(i);\n        sli.set(i, 0, 0);\n        sli.set(i, 1, s);\n        i += 1;\n    };\n\n    let mut i: usize = 0;\n    while i != split.data.len() {\n        let spl: usize = split.at(indices: array![i].span());\n        sli.set(axis, 0, pos);\n        pos += spl;\n        sli.set(axis, 1, pos);\n\n        let end_ele_0 = match sli.get(axis, 0) {\n            Option::Some(res) => res,\n            Option::None => {\n                assert(false, 'Get end_ele_0 is failed');\n                0\n            },\n        };\n        let end_ele_1 = match sli.get(axis, 1) {\n            Option::Some(res) => res,\n            Option::None => {\n                assert(false, 'Get end_ele_0 is failed');\n                0\n            },\n        };\n        let starts: Span<usize> = array![sli.get(0, 0).unwrap(), end_ele_0].span();\n        let ends: Span<usize> = array![sli.get(0, 1).unwrap(), end_ele_1].span();\n        let axes: Option<Span<usize>> = Option::None(());\n        let steps: Option<Span<usize>> = Option::None(());\n        let sub_t: Tensor<T> = t.slice(starts, ends, axes, steps);\n        splited_t.append(sub_t);\n        i += 1;\n    };\n\n    splited_t\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation/split_to_sequence.cairo",
        "content": "use core::option::OptionTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, U32Tensor};\nuse orion::operators::matrix::{MutMatrixTrait, MutMatrix, MutMatrixImpl};\n\n/// Cf: NNTrait::split docstring\nfn split_to_sequence<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    self: @Tensor<T>, axis: usize, keepdims: usize, split: Option<Tensor<usize>>\n) -> Array<Tensor<T>> {\n    let has_split = match split {\n        Option::Some => true,\n        Option::None => false,\n    };\n    let mut has_num_outputs = false;\n    let mut split_unwrap: Tensor<usize> = TensorTrait::new(array![1].span(), array![1].span());\n\n    if (!has_split) {\n        let split_length = *(*self.shape).at(axis);\n        let mut split_data: Array<usize> = array![];\n        let mut i = 0;\n        while i != split_length {\n            split_data.append(1);\n            i += 1;\n        };\n\n        split_unwrap = TensorTrait::new(array![split_length].span(), split_data.span());\n    } else if (split.unwrap().data.len() == 1 && *(split.unwrap().shape.at(0)) == 1) {\n        // A scalar\n        has_num_outputs = true;\n        split_unwrap = split.unwrap();\n    } else {\n        split_unwrap = split.unwrap();\n    }\n\n    let mut splited_t: Array<Tensor<T>> = array![];\n\n    let rank = (*self).shape.len();\n    // assert(axis < rank && axis > -rank, 'axis out of dimensions');\n    assert(axis < rank, 'axis out of dimensions');\n\n    if (has_num_outputs) {\n        splited_t = split_num_outputs(self, axis, *(split_unwrap.data).at(0));\n    } else {\n        splited_t = split_has_split(self, axis, split_unwrap);\n    }\n\n    if (keepdims == 0 && !has_split) {\n        let mut splited_t_temp: Array<Tensor<T>> = array![];\n        let mut i = 0;\n        while i != splited_t\n            .len() {\n                let mut shape: Array<i32> = array![];\n                let mut j = 0;\n                let shape_in_splited: Span<usize> = *splited_t.at(i).shape;\n                while j != shape_in_splited\n                    .len() {\n                        if (j != axis) {\n                            shape.append((*shape_in_splited.at(j)).try_into().unwrap())\n                        }\n\n                        j += 1;\n                    };\n\n                splited_t_temp.append(splited_t[i].reshape(shape.span(), false));\n                i += 1;\n            };\n\n        return splited_t_temp;\n    }\n    splited_t\n}\n\n\n/// Subfunction split for tensors (wth num_outputs).\n/// Cf: TensorTrait::split docstring\nfn split_num_outputs<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    t: @Tensor<T>, mut axis: usize, num_outputs: usize\n) -> Array<Tensor<T>> {\n    let mut splited_t: Array<Tensor<T>> = array![];\n    let mut div: usize = 0;\n    // consturct split array\n    let mut split: Array<usize> = array![];\n    // if axis==0 {\n    //     axis = 1;\n    // }\n    if (*(*t).shape.at(axis) % num_outputs == 0) {\n        div = *(*t).shape.at(axis) / num_outputs;\n        let mut i = 0;\n        while i != num_outputs {\n            split.append(div);\n            i += 1;\n        };\n    } else {\n        div = *(*t).shape.at(axis) / num_outputs + 1;\n        let mut i = 0;\n        while i != num_outputs {\n            split.append(div);\n            i += 1;\n        };\n\n        match split.pop_front() {\n            Option::Some(split_last_one) => {\n                split.append(split_last_one + *(*t).shape.at(axis) - div * (num_outputs - 1));\n            },\n            Option::None => { assert(false, 'split is none array'); }\n        }\n    }\n\n    let mut sli: MutMatrix<usize> = MutMatrixImpl::new((*t).shape.len(), 2);\n    let mut pos: usize = 0;\n    let mut i = 0;\n    while i != (*t)\n        .shape\n        .len() {\n            let s: usize = *(*t).shape.at(i);\n            sli.set(i, 0, 0);\n            sli.set(i, 1, s);\n            i += 1;\n        };\n\n    let mut i: usize = 0;\n    while i != split\n        .len() {\n            let spl = *split.at(i);\n            sli.set(axis, 0, pos);\n            pos += spl;\n            sli.set(axis, 1, pos);\n\n            let end_ele_0 = match sli.get(axis, 0) {\n                Option::Some(res) => res,\n                Option::None => {\n                    assert(false, 'Get end_ele_0 is failed');\n                    0\n                },\n            };\n            let end_ele_1 = match sli.get(axis, 1) {\n                Option::Some(res) => res,\n                Option::None => {\n                    assert(false, 'Get end_ele_0 is failed');\n                    0\n                },\n            };\n            let starts: Span<usize> = array![sli.get(0, 0).unwrap(), end_ele_0].span();\n            let ends: Span<usize> = array![sli.get(0, 1).unwrap(), end_ele_1].span();\n            let axes: Option<Span<usize>> = Option::None(());\n            let steps: Option<Span<usize>> = Option::None(());\n            let sub_t: Tensor<T> = t.slice(starts, ends, axes, steps);\n            splited_t.append(sub_t);\n            i += 1;\n        };\n\n    splited_t\n}\n\n/// Subfunction split for tensors (wth split).\n/// Cf: TensorTrait::split docstring\nfn split_has_split<T, +Copy<T>, +Drop<T>, +TensorTrait<T>,>(\n    t: @Tensor<T>, axis: usize, split: Tensor<u32>\n) -> Array<Tensor<T>> {\n    let mut splited_t: Array<Tensor<T>> = array![];\n    let mut sli: MutMatrix<usize> = MutMatrixImpl::new((*t).shape.len(), 2);\n    let mut pos: usize = 0;\n    let mut i = 0;\n    while i != (*t)\n        .shape\n        .len() {\n            let s: usize = *(*t).shape.at(i);\n            sli.set(i, 0, 0);\n            sli.set(i, 1, s);\n            i += 1;\n        };\n\n    let mut i: usize = 0;\n    while i != split\n        .data\n        .len() {\n            let spl: usize = split.at(indices: array![i].span());\n            sli.set(axis, 0, pos);\n            pos += spl;\n            sli.set(axis, 1, pos);\n\n            let end_ele_0 = match sli.get(axis, 0) {\n                Option::Some(res) => { res },\n                Option::None => {\n                    assert(false, 'Get end_ele_0 is failed');\n                    0\n                },\n            };\n            let end_ele_1 = match sli.get(axis, 1) {\n                Option::Some(res) => { res },\n                Option::None => {\n                    assert(false, 'Get end_ele_0 is failed');\n                    0\n                },\n            };\n            let starts: Span<usize> = array![sli.get(0, 0).unwrap(), end_ele_0].span();\n            let ends: Span<usize> = array![sli.get(0, 1).unwrap(), end_ele_1].span();\n            let axes: Option<Span<usize>> = Option::None(());\n            let steps: Option<Span<usize>> = Option::None(());\n            let sub_t: Tensor<T> = t.slice(starts, ends, axes, steps);\n            splited_t.append(sub_t);\n            i += 1;\n        };\n\n    splited_t\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/manipulation/unique.cairo",
        "content": "use alexandria_data_structures::array_ext::{SpanTraitExt, ArrayTraitExt};\nuse alexandria_sorting::merge_sort::merge;\n\nuse orion::numbers::{NumberTrait, U32IntoI32};\nuse orion::operators::tensor::core::{Tensor, TensorTrait, stride};\nuse orion::operators::tensor::helpers::{as_tensors_array, flatten_array_of_tensors};\n\n\n/// Cf: TensorTrait::unique docstring\nfn unique<\n    T,\n    +Copy<T>,\n    +Drop<T>,\n    +TensorTrait<T>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +PartialEq<Tensor<T>>,\n    +PartialOrd<Tensor<T>>\n>(\n    self: @Tensor<T>, axis: Option<usize>, sorted: Option<bool>\n) -> (Tensor<T>, Tensor<i32>, Tensor<i32>, Tensor<i32>) {\n    let sorted = match sorted {\n        Option::Some(sorted) => sorted,\n        Option::None => true,\n    };\n\n    let (unique_elements, new_shape, indices, inverse_indices, count) = if axis.is_none() {\n        unique_flatten(self, sorted)\n    } else {\n        unique_along_axis(self, axis.unwrap(), sorted)\n    };\n\n    let unique_elements = Tensor::<T> { shape: new_shape, data: unique_elements };\n    let indices = Tensor::<i32> { shape: array![indices.len()].span(), data: indices };\n    let inverse_indices = Tensor::<\n        i32\n    > { shape: array![inverse_indices.len()].span(), data: inverse_indices };\n    let count = Tensor::<i32> { shape: array![count.len()].span(), data: count };\n\n    (unique_elements, indices, inverse_indices, count)\n}\n\n/// Subfunction unique for flatten tensors (no axis).\n/// Cf: TensorTrait::unique docstring\nfn unique_flatten<T, +Copy<T>, +Drop<T>, +PartialOrd<T>, +PartialEq<T>,>(\n    t: @Tensor<T>, sorted: bool\n) -> (Span<T>, Span<usize>, Span<i32>, Span<i32>, Span<i32>) {\n    let mut indices: Array<i32> = array![];\n    let mut inverse_indices: Array<i32> = array![];\n    let mut count: Array<i32> = array![];\n\n    let mut unique_elements = (*t.data).unique();\n    let mut new_shape: Array<usize> = array![unique_elements.len()];\n\n    if (sorted) {\n        unique_elements = merge(unique_elements);\n    }\n\n    let mut unique_elements_span = unique_elements.span();\n    let mut data_cpy = *(t.data);\n    loop {\n        match unique_elements_span.pop_front() {\n            Option::Some(value) => {\n                let occurences = data_cpy.occurrences_of(*value);\n                count.append(occurences.into());\n                let idx_in_data = data_cpy.index_of(*value).unwrap();\n                indices.append(idx_in_data.into());\n            },\n            Option::None => { break; }\n        }\n    };\n    unique_elements_span = unique_elements.span();\n    loop {\n        match data_cpy.pop_front() {\n            Option::Some(value) => {\n                let idx_in_uniques = unique_elements_span.index_of(*value).unwrap();\n                inverse_indices.append(idx_in_uniques.into());\n            },\n            Option::None => { break; }\n        }\n    };\n\n    (unique_elements.span(), new_shape.span(), indices.span(), inverse_indices.span(), count.span())\n}\n\n/// Subfunction unique for tensors (wth axis).\n/// Cf: TensorTrait::unique docstring\nfn unique_along_axis<\n    T,\n    +Copy<T>,\n    +Drop<T>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +TensorTrait<T>,\n    +PartialEq<Tensor<T>>,\n    +PartialOrd<Tensor<T>>\n>(\n    t: @Tensor<T>, axis: usize, sorted: bool\n) -> (Span<T>, Span<usize>, Span<i32>, Span<i32>, Span<i32>) {\n    let mut new_shape: Array<usize> = array![];\n    let mut indices: Array<i32> = array![];\n    let mut inverse_indices: Array<i32> = array![];\n    let mut count: Array<i32> = array![];\n\n    let rank = (*t).shape.len();\n    assert(axis < rank, 'axis out of dimensions');\n\n    let all_tensors = as_tensors_array(t, axis);\n    let mut unique_tensors = all_tensors.unique();\n    let mut unique_tensors_len = unique_tensors.len();\n\n    let mut i = 0;\n    while i != rank {\n        new_shape.append(if axis == i {\n            unique_tensors_len\n        } else {\n            *(*t).shape.at(i)\n        });\n        i += 1;\n    };\n\n    if (sorted) {\n        unique_tensors = merge(unique_tensors);\n    }\n\n    let mut all_tensors_span = all_tensors.span();\n    let mut unique_tensors_span = unique_tensors.span();\n    loop {\n        match unique_tensors_span.pop_front() {\n            Option::Some(t) => {\n                let occurences = all_tensors_span.occurrences_of(*t);\n                count.append(occurences.into());\n                let idx_in_all = all_tensors_span.index_of(*t).unwrap();\n                indices.append(idx_in_all.into());\n            },\n            Option::None => { break; }\n        }\n    };\n    unique_tensors_span = unique_tensors.span();\n    loop {\n        match all_tensors_span.pop_front() {\n            Option::Some(t) => {\n                let idx_in_uniques = unique_tensors_span.index_of(*t).unwrap();\n                inverse_indices.append(idx_in_uniques.into());\n            },\n            Option::None => { break; }\n        }\n    };\n\n    let new_shape_span = new_shape.span();\n    let unique_elements = flatten_array_of_tensors(unique_tensors, axis, new_shape_span);\n\n    (unique_elements, new_shape_span, indices.span(), inverse_indices.span(), count.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math.cairo",
        "content": "mod min_in_tensor;\nmod min;\nmod max_in_tensor;\nmod max;\nmod reduce_sum;\nmod reduce_prod;\nmod argmax;\nmod argmin;\nmod exp;\nmod log;\nmod arithmetic;\nmod equal;\nmod greater;\nmod greater_equal;\nmod less;\nmod less_equal;\nmod abs;\nmod ceil;\nmod sin;\nmod cos;\nmod asin;\nmod cumsum;\nmod flatten;\nmod sinh;\nmod tanh;\nmod cosh;\nmod acosh;\nmod asinh;\nmod atan;\nmod xor;\nmod or;\nmod acos;\nmod onehot;\nmod sqrt;\nmod concat;\nmod gather;\nmod sign;\nmod and;\nmod neg;\nmod where;\nmod not;\nmod round;\nmod scatter;\nmod binarizer;\nmod reduce_l2;\nmod reduce_l1;\nmod reduce_sum_square;\nmod bitwise_and;\nmod bitwise_xor;\nmod bitwise_or;\nmod gather_elements;\nmod reduce_min;\nmod shrink;\nmod reduce_mean;\nmod pow;\nmod is_nan;\nmod is_inf;\nmod gather_nd;\nmod reduce_log_sum;\nmod erf;\nmod reduce_log_sum_exp;\nmod layer_normalization;\nmod resize;\nmod compress;\nmod random_uniform_like;\nmod range;\nmod hann_window;\nmod hamming_window;\nmod blackman_window;\nmod scatter_nd;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/abs.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::abs docstring\nfn abs<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => { data_result.append((*item).abs()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/acos.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::acos docstring\nfn acos<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).acos()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(self.shape, result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/acosh.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::acosh docstring\nfn acosh<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).acosh()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/and.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::{core::{Tensor, TensorTrait, unravel_index}, BoolTensor};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::and docstring\nfn and(y: @Tensor<bool>, z: @Tensor<bool>) -> Tensor<bool> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<bool> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        result.append(*(*y.data)[indices_self] && *(*z.data)[indices_other]);\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/argmax.cairo",
        "content": "use core::option::OptionTrait;\nuse core::traits::TryInto;\nuse orion::operators::tensor::{core::{Tensor, TensorTrait, ravel_index, unravel_index}, I32Tensor};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::argmax docstring\nfn argmax<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: i32, keepdims: Option<bool>, select_last_index: Option<bool>\n) -> Tensor<i32> {\n    let keepdims = keepdims.unwrap_or(true);\n    let select_last_index = select_last_index.unwrap_or(false);\n\n    // Convert negative axis to positive\n    let axis = if axis < 0 {\n        ((*self.shape).len().try_into().unwrap() + axis).try_into().unwrap()\n    } else {\n        axis.try_into().unwrap()\n    };\n\n    assert(axis <= (*self.shape).len(), 'axis out of dimensions');\n\n    if (*self.shape).len() == 1 {\n        return find_argmax_1D::<T>(*self, axis, true, select_last_index);\n    }\n\n    let mut output_data: Array<i32> = array![];\n\n    let output_shape = reduce_output_shape(*self.shape, axis, false);\n    let output_data_len = len_from_shape(output_shape);\n\n    let MIN = NumberTrait::min_value();\n\n    let mut index: usize = 0;\n    while index != output_data_len {\n        let output_indices = unravel_index(index, output_shape);\n        let current_argmax = find_argmax(self, output_indices, axis, 0, MIN, 0, select_last_index);\n\n        output_data.append(current_argmax);\n\n        index += 1;\n    };\n\n    TensorTrait::<i32>::new(reduce_output_shape(*self.shape, axis, keepdims), output_data.span())\n}\n\n/// Helper function that finds the index of the maximum value in a flat tensor.\n///\n/// # Arguments\n/// * `input` - The input tensor.\n/// * `axis` - The axis along which to find the maximum value.\n/// * `keepdims` - Whether to keep the reduced dimension or not.\n/// * `select_last_index` - Whether to sel\u0192ect last occurrence of the max value along the axis.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize value representing the index of the maximum value along the specified axis.\nfn find_argmax_1D<\n    T,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut input: Tensor<T>, axis: usize, keepdims: bool, select_last_index: bool\n) -> Tensor<i32> {\n    let mut output_data = ArrayTrait::<i32>::new();\n\n    let mut max = match input.data.pop_front() {\n        Option::Some(item) => *item,\n        Option::None => {\n            return TensorTrait::<\n                i32\n            >::new(reduce_output_shape(input.shape, axis, keepdims), output_data.span());\n        }\n    };\n    let mut max_index = 0;\n    let mut count = 0;\n\n    loop {\n        match input.data.pop_front() {\n            Option::Some(item) => {\n                count += 1;\n\n                if *item > max {\n                    max = *item;\n                    max_index = count;\n                } else {\n                    if select_last_index && item == @max {\n                        max_index = count;\n                    }\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_data.append(max_index);\n\n    return TensorTrait::<\n        i32\n    >::new(reduce_output_shape(input.shape, axis, keepdims), output_data.span());\n}\n\n\n/// Recursive helper function that finds the index of the maximum value along a specific axis.\n///\n/// # Arguments\n/// * `input` - The input tensor.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to find the maximum value.\n/// * `axis_index` - The current index along the specified axis.\n/// * `max_value` - The current maximum value found along the axis.\n/// * `argmax` - The current index of the maximum value along the axis.\n/// * `select_last_index` - Whether to select last occurrence of the max value along the axis.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize value representing the index of the maximum value along the specified axis.\nfn find_argmax<\n    T,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    input: @Tensor<T>,\n    output_indices: Span<usize>,\n    axis: usize,\n    axis_index: usize,\n    max_value: T,\n    argmax: usize,\n    select_last_index: bool\n) -> i32 {\n    if axis_index == *(*input.shape)[axis] {\n        return argmax.try_into().unwrap();\n    }\n\n    let input_indices = combine_indices(output_indices, axis_index, axis);\n    let input_index = ravel_index(*input.shape, input_indices);\n    let ele = *(*input.data)[input_index];\n\n    let (new_max_value, new_argmax) = if ele > max_value {\n        (ele, axis_index)\n    } else {\n        if select_last_index && ele == max_value {\n            (ele, axis_index)\n        } else {\n            (max_value, argmax)\n        }\n    };\n\n    return find_argmax(\n        input,\n        output_indices,\n        axis,\n        axis_index + 1_usize,\n        new_max_value,\n        new_argmax,\n        select_last_index\n    );\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/argmin.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{reduce_output_shape, combine_indices, len_from_shape};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::argmin docstring\nfn argmin<\n    T,\n    MAG,\n    impl UsizeTensor: TensorTrait<usize>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: Option<bool>, select_last_index: Option<bool>\n) -> Tensor<usize> {\n    let keepdims = match keepdims {\n        Option::Some(val) => val,\n        Option::None => true,\n    };\n\n    let select_last_index = match select_last_index {\n        Option::Some(val) => val,\n        Option::None => false,\n    };\n\n    assert(axis <= (*self.shape).len(), 'axis out of dimensions');\n\n    if (*self.shape).len() == 1 {\n        return find_argmin_1D(*self, axis, true, select_last_index);\n    }\n\n    let mut output_data: Array<u32> = array![];\n\n    let output_shape = reduce_output_shape(*self.shape, axis, false);\n    let output_data_len = len_from_shape(output_shape);\n\n    let MAX = NumberTrait::max_value();\n\n    let mut index: usize = 0;\n    while index != output_data_len {\n        let output_indices = unravel_index(index, output_shape);\n        let current_argmin = find_argmin(self, output_indices, axis, 0, MAX, 0, select_last_index);\n\n        output_data.append(current_argmin);\n\n        index += 1;\n    };\n\n    TensorTrait::<usize>::new(reduce_output_shape(*self.shape, axis, keepdims), output_data.span())\n}\n\n\n/// Helper function that finds the index of the minimum value in a flat tensor.\n///\n/// # Arguments\n/// * `input` - The input tensor.\n/// * `axis` - The axis along which to find the minimum value.\n/// * `keepdims` - Whether to keep the reduced dimension or not.\n/// * `select_last_index` - Whether to select last occurrence of the min value along the axis.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize value representing the index of the minimum value along the specified axis.\nfn find_argmin_1D<\n    T,\n    impl UsizeTensor: TensorTrait<usize>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut input: Tensor<T>, axis: usize, keepdims: bool, select_last_index: bool\n) -> Tensor<usize> {\n    let mut output_data = ArrayTrait::<usize>::new();\n\n    let mut min = match input.data.pop_front() {\n        Option::Some(item) => *item,\n        Option::None => {\n            return TensorTrait::<\n                usize\n            >::new(reduce_output_shape(input.shape, axis, keepdims), output_data.span());\n        }\n    };\n    let mut min_index = 0;\n    let mut count = 0;\n\n    loop {\n        match input.data.pop_front() {\n            Option::Some(item) => {\n                count += 1;\n\n                if *item < min {\n                    min = *item;\n                    min_index = count;\n                } else {\n                    if select_last_index && item == @min {\n                        min_index = count;\n                    }\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_data.append(min_index);\n\n    return TensorTrait::<\n        usize\n    >::new(reduce_output_shape(input.shape, axis, keepdims), output_data.span());\n}\n\n\n/// Recursive helper function that finds the index of the minimum value along a specific axis.\n///\n/// # Arguments\n/// * `input` - The input tensor.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to find the minimum value.\n/// * `axis_index` - The current index along the specified axis.\n/// * `min_value` - The current minimum value found along the axis.\n/// * `argmin` - The current index of the minimum value along the axis.\n/// * `select_last_index` - Whether to select last occurrence of the min value along the axis.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A usize value representing the index of the minimum value along the specified axis.\nfn find_argmin<\n    T,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    input: @Tensor<T>,\n    output_indices: Span<usize>,\n    axis: usize,\n    axis_index: usize,\n    min_value: T,\n    argmin: usize,\n    select_last_index: bool\n) -> usize {\n    if axis_index == *(*input.shape)[axis] {\n        return argmin;\n    }\n\n    let input_indices = combine_indices(output_indices, axis_index, axis);\n    let input_index = ravel_index(*input.shape, input_indices);\n    let ele = *(*input.data)[input_index];\n\n    let (new_min_value, new_argmin) = if ele < min_value {\n        (ele, axis_index)\n    } else {\n        if select_last_index && ele == min_value {\n            (ele, axis_index)\n        } else {\n            (min_value, argmin)\n        }\n    };\n\n    return find_argmin(\n        input,\n        output_indices,\n        axis,\n        axis_index + 1_usize,\n        new_min_value,\n        new_argmin,\n        select_last_index\n    );\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/arithmetic.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index,};\nuse orion::operators::tensor::helpers::{broadcast_shape, broadcast_index_mapping, len_from_shape,};\nuse orion::utils::saturate;\n\nfn add<\n    T, impl TTensor: TensorTrait<T>, impl TAdd: Add<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result.append(*(*self.data)[indices_self] + *(*other.data)[indices_other]);\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n\nfn add_by_scalar<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TAdd: Add<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, val: T\n) -> Tensor<T> {\n    if val == NumberTrait::zero() {\n        return *self;\n    }\n\n    let mut input_data = *self.data;\n    let mut data_result = array![];\n    loop {\n        match input_data.pop_front() {\n            Option::Some(ele) => { data_result.append(*ele + val); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(*self.shape, data_result.span())\n}\n\nfn saturated_add<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TAdd: Add<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QDrop: Drop<Q>,\n>(\n    self: @Tensor<T>, other: @Tensor<T>, min_saturation: T, max_saturation: T\n) -> Tensor<Q> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result\n            .append(\n                saturate(\n                    min_saturation,\n                    max_saturation,\n                    *(*self.data)[indices_self] + *(*other.data)[indices_other]\n                )\n                    .try_into()\n                    .unwrap()\n            );\n\n        n += 1;\n    };\n\n    TensorTrait::<Q>::new(broadcasted_shape, result.span())\n}\n\nfn sub<\n    T, impl TTensor: TensorTrait<T>, impl TSub: Sub<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result.append(*(*self.data)[indices_self] - *(*other.data)[indices_other]);\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n\nfn sub_by_scalar<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TSub: Sub<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, val: T\n) -> Tensor<T> {\n    if val == NumberTrait::zero() {\n        return *self;\n    }\n\n    let mut input_data = *self.data;\n    let mut data_result = array![];\n    loop {\n        match input_data.pop_front() {\n            Option::Some(ele) => { data_result.append(*ele - val); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(*self.shape, data_result.span())\n}\n\nfn saturated_sub<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TSub: Sub<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QDrop: Drop<Q>,\n>(\n    self: @Tensor<T>, other: @Tensor<T>, min_saturation: T, max_saturation: T\n) -> Tensor<Q> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result\n            .append(\n                saturate(\n                    min_saturation,\n                    max_saturation,\n                    *(*self.data)[indices_self] - *(*other.data)[indices_other]\n                )\n                    .try_into()\n                    .unwrap()\n            );\n\n        n += 1;\n    };\n\n    TensorTrait::<Q>::new(broadcasted_shape, result.span())\n}\n\nfn mul<\n    T, impl TTensor: TensorTrait<T>, impl TMul: Mul<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result.append(*(*self.data)[indices_self] * *(*other.data)[indices_other]);\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n\nfn mul_by_scalar<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TMul: Mul<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, val: T\n) -> Tensor<T> {\n    if val == NumberTrait::one() {\n        return *self;\n    }\n\n    let mut input_data = *self.data;\n    let mut data_result = array![];\n    loop {\n        match input_data.pop_front() {\n            Option::Some(ele) => { data_result.append(*ele * val); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(*self.shape, data_result.span())\n}\n\nfn saturated_mul<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TMul: Mul<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QDrop: Drop<Q>,\n>(\n    self: @Tensor<T>, other: @Tensor<T>, min_saturation: T, max_saturation: T\n) -> Tensor<Q> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result\n            .append(\n                saturate(\n                    min_saturation,\n                    max_saturation,\n                    *(*self.data)[indices_self] * *(*other.data)[indices_other]\n                )\n                    .try_into()\n                    .unwrap()\n            );\n\n        n += 1;\n    };\n\n    TensorTrait::<Q>::new(broadcasted_shape, result.span())\n}\n\nfn div<\n    T, impl TTensor: TensorTrait<T>, impl TMul: Div<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result.append(*(*self.data)[indices_self] / *(*other.data)[indices_other]);\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n\nfn div_by_scalar<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TDiv: Div<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, val: T\n) -> Tensor<T> {\n    if val == NumberTrait::one() {\n        return *self;\n    }\n\n    let mut input_data = *self.data;\n    let mut data_result = array![];\n    loop {\n        match input_data.pop_front() {\n            Option::Some(ele) => { data_result.append(*ele / val); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(*self.shape, data_result.span())\n}\n\nfn saturated_div<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TDiv: Div<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QDrop: Drop<Q>,\n>(\n    self: @Tensor<T>, other: @Tensor<T>, min_saturation: T, max_saturation: T\n) -> Tensor<Q> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result\n            .append(\n                saturate(\n                    min_saturation,\n                    max_saturation,\n                    *(*self.data)[indices_self] / *(*other.data)[indices_other]\n                )\n                    .try_into()\n                    .unwrap()\n            );\n\n        n += 1;\n    };\n\n    TensorTrait::<Q>::new(broadcasted_shape, result.span())\n}\n\nfn div_downcast<\n    T,\n    D,\n    impl TTensor: TensorTrait<T>,\n    impl DTensor: TensorTrait<D>,\n    impl DDiv: Div<D>,\n    impl TTryIntoD: TryInto<T, D>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl DCopy: Copy<D>,\n    impl DDrop: Drop<D>\n>(\n    self: @Tensor<T>, other: @Tensor<T>\n) -> Tensor<D> {\n    let broadcasted_shape = broadcast_shape(*self.shape, *other.shape);\n    let mut result = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*other.shape, indices_broadcasted);\n\n        result\n            .append(\n                (*(*self.data)[indices_self]).try_into().unwrap()\n                    / (*(*other.data)[indices_other]).try_into().unwrap()\n            );\n\n        n += 1;\n    };\n\n    TensorTrait::<D>::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/asin.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::asin docstring\nfn asin<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).asin()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/asinh.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::asinh docstring\nfn asinh<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).asinh()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/atan.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn atan<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).atan()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/binarizer.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::binarizer docstring\nfn binarizer<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut self: Tensor<T>, threshold: Option<T>\n) -> Tensor<T> {\n    let threshold: T = if threshold.is_some() {\n        threshold.unwrap()\n    } else {\n        NumberTrait::zero()\n    };\n\n    let mut binarized_data: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => {\n                if (*item) > threshold {\n                    binarized_data.append(NumberTrait::one());\n                } else {\n                    binarized_data.append(NumberTrait::zero());\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, binarized_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/bitwise_and.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::and docstring\nfn bitwise_and<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<T> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        let lhs = *(*y.data)[indices_self];\n        let rhs = *(*z.data)[indices_other];\n\n        result.append(NumberTrait::bitwise_and(lhs, rhs));\n        // let res = *(*y.data).at(n) ^ *(*z.data).at(n)\n        // result.append(res);\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/bitwise_or.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::and docstring\nfn bitwise_or<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<T> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        let lhs = *(*y.data)[indices_self];\n        let rhs = *(*z.data)[indices_other];\n\n        result.append(NumberTrait::bitwise_or(lhs, rhs));\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/bitwise_xor.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::and docstring\nfn bitwise_xor<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<T> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        let lhs = *(*y.data)[indices_self];\n        let rhs = *(*z.data)[indices_other];\n\n        result.append(NumberTrait::bitwise_xor(lhs, rhs));\n\n        n += 1;\n    };\n\n    TensorTrait::<T>::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/blackman_window.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn blackman_window<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    size: T, PI: T, periodic: Option<usize>\n) -> Tensor<T> {\n    let start: T = NumberTrait::zero();\n    let one_step: T = NumberTrait::one();\n    let two: T = one_step + one_step;\n    let three: T = two + one_step;\n    let n25: T = three.pow(three) - two;\n    let alpha: T = (n25 - two * two) / (n25 * two);\n    let beta: T = two / n25;\n    let n_0_5: T = (one_step - two) / two;\n\n    let ni = TensorTrait::range(start, size, one_step);\n    assert((ni.shape).len() == 1, 'Unexpected shape 1.');\n    let mut N_1 = size;\n\n    if periodic != Option::Some(1) {\n        N_1 = N_1 - one_step;\n    };\n\n    let len = *(ni.shape).at(0);\n    let mut arr1: Array<T> = array![];\n    let mut i: usize = 0;\n    while i != len {\n        let v = *(ni.data).at(i);\n        let r = (v * (PI * two)) / N_1;\n        arr1.append(r);\n        i += 1;\n    };\n\n    let window_cos = TensorTrait::<T>::new(ni.shape, arr1.span()).cos();\n    i = 0;\n    let mut a1: Array<T> = array![];\n    while i != len {\n        let v = *(window_cos.data).at(i);\n        let r = v * n_0_5;\n        a1.append(r);\n        i += 1;\n    };\n\n    let window1 = TensorTrait::<T>::new(ni.shape, a1.span());\n\n    let mut arr2: Array<T> = array![];\n    i = 0;\n    while i != len {\n        let v = *(ni.data).at(i);\n        let r = v * (PI * two * two) / N_1;\n        arr2.append(r);\n        i += 1;\n    };\n\n    let window_cos_2 = TensorTrait::<T>::new(ni.shape, arr2.span()).cos();\n\n    let mut a2: Array<T> = array![];\n    i = 0;\n    while i != len {\n        let v = *(window_cos_2.data).at(i);\n        let r = v * beta + alpha;\n        a2.append(r);\n        i += 1;\n    };\n\n    let window2 = TensorTrait::<T>::new(ni.shape, a2.span());\n\n    let mut arr: Array<T> = array![];\n    i = 0;\n    while i != len {\n        let v1 = *(window1.data).at(i);\n        let v2 = *(window2.data).at(i);\n        let r = v1 + v2;\n        arr.append(r);\n        i += 1;\n    };\n\n    TensorTrait::<T>::new(ni.shape, arr.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/ceil.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::ceil docstring\nfn ceil<\n    T,\n    MAG,\n    impl FFixedTrait: FixedTrait<T, MAG>,\n    impl FTensor: TensorTrait<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => { data_result.append((*item).ceil()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/compress.cairo",
        "content": "use alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n\n/// Cf: TensorTrait::compare docstring\nfn compress<T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    self: @Tensor<T>, condition: Tensor<usize>, axis: Option<usize>\n) -> Tensor<T> {\n    let axis = match axis {\n        Option::Some(val) => val,\n        Option::None => 999\n    };\n\n    let data_rank = (*self.shape).len();\n    let condition_rank = (condition.shape).len();\n    assert((data_rank >= 1), 'data rank must > 1');\n    assert((condition_rank == 1), 'condition rank must be 1');\n\n    let mut data_shape = *self.shape;\n\n    if (axis != 999) {\n        assert(*data_shape.at(axis) >= condition.data.len(), 'index out of bound');\n    }\n\n    let mut output_shape = array![];\n    let mut index_data = array![];\n    let mut output_data = array![];\n\n    let mut condition_data = condition.data;\n\n    let mut ind = 0;\n    let mut condition_data_clone = condition_data.clone();\n    let mut output = 0;\n    loop {\n        match condition_data_clone.pop_front() {\n            Option::Some(val) => {\n                if (*val != 0) {\n                    output += 1;\n                }\n                ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    if (axis == 999) {\n        output_shape.append(output);\n\n        let mut total_shape = 1;\n        loop {\n            match data_shape.pop_front() {\n                Option::Some(val) => { total_shape *= *val; },\n                Option::None => { break; }\n            };\n        };\n\n        let mut ind = 0;\n        loop {\n            match condition_data.pop_front() {\n                Option::Some(val) => {\n                    if (ind == total_shape) {\n                        break;\n                    }\n                    if (*val != 0) {\n                        output_data.append(*self.data[ind]);\n                    }\n                    ind += 1;\n                },\n                Option::None => { break; }\n            };\n        };\n    } else {\n        let mut ind = 0;\n        let mut loop_breaker = 1;\n        let mut other_loop_breaker = 1;\n        let mut multiplier = 1;\n\n        let mut data_shape_clone = data_shape.clone();\n        loop {\n            match data_shape_clone.pop_front() {\n                Option::Some(val) => {\n                    if (ind == axis) {\n                        output_shape.append(output);\n                    } else {\n                        output_shape.append(*val);\n                        if (ind > axis) {\n                            loop_breaker *= *val;\n                        }\n                        if (ind >= axis) {\n                            multiplier *= *val;\n                        }\n                        if (ind < axis) {\n                            other_loop_breaker *= *val;\n                        }\n                    }\n                    ind += 1;\n                },\n                Option::None => { break; }\n            };\n        };\n\n        let mut ind = 0;\n\n        let mut inner_index: usize = 0;\n\n        loop {\n            if (ind == other_loop_breaker) {\n                break;\n            }\n            let mut condition_data_clone = condition_data.clone();\n            inner_index = *data_shape.at(axis) * ind;\n            loop {\n                match condition_data_clone.pop_front() {\n                    Option::Some(val) => {\n                        if (*val != 0) {\n                            let result = inner_index * loop_breaker;\n\n                            let mut data_ind: usize = result;\n                            loop {\n                                if data_ind == result + loop_breaker {\n                                    break;\n                                }\n                                index_data.append(data_ind);\n                                data_ind += 1;\n                            };\n                        }\n                        inner_index += 1;\n                    },\n                    Option::None => { break; }\n                };\n            };\n\n            ind += 1;\n        };\n\n        loop {\n            match index_data.pop_front() {\n                Option::Some(val) => { output_data.append(*self.data[val]); },\n                Option::None => { break; }\n            };\n        };\n    }\n\n    let mut output_tensor = TensorTrait::<T>::new(output_shape.span(), output_data.span());\n\n    output_tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/concat.cairo",
        "content": "use orion::operators::tensor::helpers::replace_index;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\nfn concat<T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    mut tensors: Span<Tensor<T>>, axis: usize\n) -> Tensor<T> {\n    assert(tensors.len() >= 2, 'Input tensors must be > 1');\n    let base_tensor = *tensors.at(0);\n    let base_shape = base_tensor.shape;\n    let dimension = base_shape.len();\n    assert(dimension > axis, 'Out of bounds for dimension');\n\n    // Validate shapes of tensors\n    validate_shapes(tensors, base_shape, axis);\n\n    // Calculate output size\n    let output_size = compute_output_size(base_shape, tensors, axis);\n\n    // Concatenate tensor data\n    let output_data: Array<T> = concatenate_data(tensors, axis, base_shape);\n\n    TensorTrait::<T>::new(output_size.span(), output_data.span())\n}\n\nfn validate_shapes<T>(mut tensors: Span<Tensor<T>>, mut base_shape: Span<usize>, axis: usize) {\n    loop {\n        match tensors.pop_front() {\n            Option::Some(tensor) => {\n                assert(base_shape.len() == (*tensor.shape).len(), 'Dimension not the same');\n\n                let mut axis_index = 0;\n                let mut tensor_shape = *tensor.shape;\n                let mut base_shape_copy = base_shape;\n                loop {\n                    match tensor_shape.pop_front() {\n                        Option::Some(tensor_shape_i) => {\n                            let base_shape_i = base_shape_copy.pop_front().unwrap();\n                            if axis_index != axis {\n                                assert(base_shape_i == tensor_shape_i, 'Shape is not the same');\n                            }\n                            axis_index += 1;\n                        },\n                        Option::None => { break; }\n                    };\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n}\n\nfn compute_output_size<T>(\n    mut base_shape: Span<usize>, mut tensors: Span<Tensor<T>>, axis: usize\n) -> Array<u32> {\n    let mut output_size: Array<usize> = array![];\n\n    let mut axis_size = 0;\n    loop {\n        match tensors.pop_front() {\n            Option::Some(tensor) => { axis_size += *(*tensor.shape).at(axis); },\n            Option::None => { break; }\n        };\n    };\n\n    let mut shape_index = 0;\n    loop {\n        match base_shape.pop_front() {\n            Option::Some(item) => {\n                if shape_index == axis {\n                    output_size.append(axis_size);\n                } else {\n                    output_size.append(*item);\n                }\n                shape_index += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_size\n}\n\nfn concatenate_data<T, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    mut tensors: Span<Tensor<T>>, axis: usize, base_shape: Span<usize>\n) -> Array<T> {\n    let mut output_data: Array<T> = array![];\n\n    let total_loops = product_upto(base_shape, axis);\n\n    let mut outer_loop_index = 0;\n    while outer_loop_index != total_loops {\n        let mut tensors_copy = tensors;\n        loop {\n            match tensors_copy.pop_front() {\n                Option::Some(tensor) => {\n                    let slice_len = (*tensor.data).len() / total_loops;\n\n                    let mut inner_index = 0;\n                    while inner_index != slice_len {\n                        output_data\n                            .append(*(*tensor.data).at(slice_len * outer_loop_index + inner_index));\n                        inner_index += 1;\n                    };\n                },\n                Option::None => { break; }\n            };\n        };\n\n        outer_loop_index += 1;\n    };\n\n    output_data\n}\n\nfn product_upto(mut shape: Span<usize>, upto: usize) -> usize {\n    let mut total = 1;\n    let mut index = 0;\n\n    loop {\n        match shape.pop_front() {\n            Option::Some(val) => {\n                if index == upto {\n                    break;\n                }\n\n                total *= *val;\n                index += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    total\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/cos.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::cos docstring\nfn cos<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).cos()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/cosh.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::cosh docstring\nfn cosh<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).cosh()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/cumsum.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::helpers::replace_index;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\n\n/// Cf: TensorTrait::cumsum docstring\nfn cumsum<\n    T,\n    MAG,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAddEq: AddEq<T>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, exclusive: Option<bool>, reverse: Option<bool>\n) -> Tensor<T> {\n    let reverse = match reverse {\n        Option::Some(val) => val,\n        Option::None => false\n    };\n\n    if reverse {\n        cumsum_reverse::<T>(self, axis, exclusive, NumberTrait::zero())\n    } else {\n        cumsum_forward::<T>(self, axis, exclusive, NumberTrait::zero())\n    }\n}\n\n/// Cf: TensorTrait::cumsum docstring\nfn cumsum_forward<\n    T,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TAdd: Add<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, exclusive: Option<bool>, zero: T,\n) -> Tensor<T> {\n    let exclusive = match exclusive {\n        Option::Some(val) => val,\n        Option::None => false,\n    };\n\n    assert(axis < (*self.shape).len(), 'axis out of dimensions');\n\n    let data = *self.data;\n\n    let mut output_data = array![];\n\n    let mut index: usize = 0;\n\n    while index != data.len() {\n        let current_indices = unravel_index(index, *self.shape);\n        let axis_value = *current_indices[axis];\n\n        if axis_value == 0 {\n            if exclusive {\n                output_data.append(zero);\n            } else {\n                output_data.append(*(data)[index]);\n            }\n        } else {\n            let previous_axis_element_indices = replace_index(\n                current_indices, axis, axis_value - 1\n            );\n            let previous_axis_element_index = ravel_index(\n                *self.shape, previous_axis_element_indices\n            );\n\n            if exclusive {\n                output_data\n                    .append(\n                        *output_data[previous_axis_element_index]\n                            + *(data)[previous_axis_element_index]\n                    );\n            } else {\n                output_data.append(*output_data[previous_axis_element_index] + *(data)[index]);\n            };\n        }\n\n        index += 1;\n    };\n\n    TensorTrait::<T>::new(*self.shape, output_data.span())\n}\n\n/// Cf: TensorTrait::cumsum docstring\nfn cumsum_reverse<\n    T,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TAddEq: AddEq<T>,\n    impl TSub: Sub<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, exclusive: Option<bool>, zero: T,\n) -> Tensor<T> {\n    let exclusive = match exclusive {\n        Option::Some(val) => val,\n        Option::None => false,\n    };\n\n    assert(axis < (*self.shape).len(), 'axis out of dimensions');\n    let data = *self.data;\n    let mut output_data = array![];\n    let mut index: usize = 0;\n    while index != data.len() {\n        let current_indices = unravel_index(index, *self.shape);\n        let mut axis_value = *current_indices[axis];\n\n        if axis_value == 0 {\n            // If the axis value is 0, we need to sum all the elements\n            // in the axis.\n            let mut sum = *(data)[index];\n            if exclusive {\n                sum = zero;\n            }\n\n            let end_index = *(*self.shape)[axis] - 1;\n\n            loop {\n                axis_value += 1;\n                if axis_value > end_index {\n                    break ();\n                }\n\n                let next_axis_element_indices = replace_index(current_indices, axis, axis_value);\n                let next_axis_element_index = ravel_index(*self.shape, next_axis_element_indices);\n                sum += *data[next_axis_element_index];\n            };\n\n            output_data.append(sum);\n        } else {\n            // If the axis value is not 0, we only need to do a subtraction\n            let previous_axis_element_indices = replace_index(\n                current_indices, axis, axis_value - 1\n            );\n            let previous_axis_element_index = ravel_index(\n                *self.shape, previous_axis_element_indices\n            );\n\n            if exclusive {\n                output_data.append(*output_data[previous_axis_element_index] - *(data)[index]);\n            } else {\n                output_data\n                    .append(\n                        *output_data[previous_axis_element_index]\n                            - *(data)[previous_axis_element_index]\n                    );\n            }\n        }\n\n        index += 1;\n    };\n\n    TensorTrait::<T>::new(*self.shape, output_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/equal.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::equal docstring\nfn equal<\n    T,\n    impl UsizeFTensor: TensorTrait<usize>,\n    impl TPartialEq: PartialEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<usize> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<usize> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if *(*y.data)[indices_self] == *(*z.data)[indices_other] {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/erf.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::erf docstring\nfn erf<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TFixed: FixedTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => { data_result.append((*item).erf()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/exp.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::exp docstring\nfn exp<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).exp()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n\n/// Cf: TensorTrait::exp docstring\nfn exp_upcast<\n    T,\n    TMAG,\n    W,\n    WMAG,\n    impl TFixedTrait: FixedTrait<T, TMAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl WFixedTrait: FixedTrait<W, WMAG>,\n    impl WTensor: TensorTrait<W>,\n    impl WCopy: Copy<W>,\n    impl WDrop: Drop<W>,\n    impl TIntoW: Into<T, W>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<W> {\n    let mut result = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((TIntoW::into(*item)).exp()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/flatten.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::flatten docstring\nfn flatten<T, impl TTensorTrait: TensorTrait<T>>(self: @Tensor<T>, axis: usize) -> Tensor<T> {\n    let mut shape = *self.shape;\n    assert(axis < shape.len(), 'axis out of dimensions');\n\n    let mut new_shape_first_axis = 1;\n    let mut index = 0;\n    loop {\n        match shape.pop_front() {\n            Option::Some(val) => {\n                if index == axis {\n                    break;\n                }\n\n                new_shape_first_axis *= *val;\n                index += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let new_shape_second_axis = (*self.data).len() / new_shape_first_axis;\n\n    self\n        .reshape(\n            array![\n                new_shape_first_axis.try_into().unwrap(), new_shape_second_axis.try_into().unwrap()\n            ]\n                .span(),\n            false\n        )\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/gather.cairo",
        "content": "use core::option::OptionTrait;\nuse core::traits::TryInto;\nuse alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: TensorTrait::gather docstring\nfn gather<T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>\n) -> Tensor<T> {\n    let axis: usize = match axis {\n        Option::Some(val) => {\n            if val < 0 {\n                (((*self.shape).len()).try_into().unwrap() + val).try_into().unwrap()\n            } else {\n                val.try_into().unwrap()\n            }\n        },\n        Option::None => 0\n    };\n    assert(axis < (*self.shape).len(), 'axis out of dimensions');\n\n    let axis_shape = *(*self.shape).at(axis);\n\n    // Adjust indices that are negative\n    let mut adjusted_indices = array![];\n    let mut indices_data = indices.data.clone();\n    loop {\n        match indices_data.pop_front() {\n            Option::Some(index) => {\n                let adjusted_index: usize = if *index < 0 {\n                    let val: u32 = (axis_shape.try_into().unwrap() + *index).try_into().unwrap();\n                    val\n                } else {\n                    let val: u32 = (*index).try_into().unwrap();\n                    val\n                };\n                assert(adjusted_index >= 0 && adjusted_index < axis_shape, 'Index out of bounds');\n                adjusted_indices.append(adjusted_index);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_data = array![];\n    let mut output_size = array![];\n    let mut self_shape = *self.shape;\n    let mut i: usize = 0;\n    loop {\n        match self_shape.pop_front() {\n            Option::Some(val) => {\n                if i == axis {\n                    let mut indices_shape = indices.shape;\n                    loop {\n                        match indices_shape.pop_front() {\n                            Option::Some(item) => { output_size.append(*item); },\n                            Option::None => { break; }\n                        };\n                    };\n                } else {\n                    output_size.append(*val);\n                }\n\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut outer_loop_break = 1;\n    let mut divisor = (*self.data).len();\n\n    let mut self_shape = *self.shape;\n    let mut i: usize = 0;\n    loop {\n        match self_shape.pop_front() {\n            Option::Some(val) => {\n                if i == axis {\n                    divisor /= *val;\n                    break ();\n                };\n\n                outer_loop_break *= *val;\n                divisor /= *val;\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut break_loop: usize = 1;\n    let mut self_shape = *self.shape;\n    loop {\n        match self_shape.pop_back() {\n            Option::Some(val) => {\n                if self_shape.len() + 1 == axis {\n                    break;\n                }\n                break_loop *= *val;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut outer_loop: usize = 0;\n    let axis_index = *self.shape[axis];\n    while outer_loop != outer_loop_break {\n        let mut adjusted_indices_iter = adjusted_indices.clone();\n        loop {\n            match adjusted_indices_iter.pop_front() {\n                Option::Some(indice) => {\n                    let mut inner_loop = 0;\n                    while inner_loop != break_loop {\n                        let new_val = inner_loop / divisor % axis_index;\n                        if indice == new_val {\n                            output_data.append(*self.data[break_loop * outer_loop + inner_loop]);\n                        }\n\n                        inner_loop += 1;\n                    }\n                },\n                Option::None => { break; },\n            };\n        };\n\n        outer_loop += 1;\n    };\n\n    let mut output_tensor = TensorTrait::<T>::new(output_size.span(), output_data.span());\n\n    output_tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/gather_elements.cairo",
        "content": "use alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: TensorTrait::gather_elements docstring\nfn gather_elements<T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    self: @Tensor<T>, indices: Tensor<i32>, axis: Option<i32>\n) -> Tensor<T> {\n    let axis: usize = match axis {\n        Option::Some(val) => {\n            if val < 0 {\n                (((*self.shape).len()).try_into().unwrap() + val).try_into().unwrap()\n            } else {\n                val.try_into().unwrap()\n            }\n        },\n        Option::None => 0\n    };\n    assert(axis < (*self.shape).len(), 'axis out of dimensions');\n\n    let axis_shape = *(*self.shape).at(axis);\n\n    // Adjust indices that are negative\n    let mut adjusted_indices = array![];\n    let mut indices_data = indices.data.clone();\n    loop {\n        match indices_data.pop_front() {\n            Option::Some(index) => {\n                let adjusted_index: usize = if *index < 0 {\n                    let val: u32 = (axis_shape.try_into().unwrap() + *index).try_into().unwrap();\n                    val\n                } else {\n                    let val: u32 = (*index).try_into().unwrap();\n                    val\n                };\n                assert(adjusted_index >= 0 && adjusted_index < axis_shape, 'Index out of bounds');\n                adjusted_indices.append(adjusted_index);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_data = array![];\n    let mut data_shape_clone = (*self.shape).clone();\n    let mut multiplier = 1;\n    let mut looper = 1;\n    let mut ind = 0;\n    loop {\n        match data_shape_clone.pop_front() {\n            Option::Some(val) => {\n                if ind >= axis {\n                    multiplier *= *val;\n                }\n                if ind > axis {\n                    looper *= *val;\n                }\n                ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let inner_loop = multiplier / axis_shape;\n    let mut adjusted_indices_iter = adjusted_indices.clone();\n\n    let mut i: usize = 0;\n    loop {\n        match adjusted_indices_iter.pop_front() {\n            Option::Some(indice) => {\n                let value = if axis == 0 {\n                    indice * inner_loop + (i % inner_loop)\n                } else if axis == (*self.shape).len() - 1 {\n                    indice + axis_shape * (i / axis_shape)\n                } else {\n                    indice * looper\n                        + (i % looper)\n                        + (multiplier / axis_shape) * (i / (multiplier / axis_shape))\n                };\n\n                output_data.append(*self.data[value]);\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(indices.shape, output_data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/gather_nd.cairo",
        "content": "use alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n\n/// Cf: TensorTrait::gather_nd docstring\nfn gather_nd<T, impl TTensorTrait: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>,>(\n    self: @Tensor<T>, indices: Tensor<usize>, batch_dims: Option<usize>\n) -> Tensor<T> {\n    let batch_dims = match batch_dims {\n        Option::Some(val) => val,\n        Option::None => 0\n    };\n\n    let data_rank = (*self.shape).len();\n    let indices_rank = (indices.shape).len();\n    assert((data_rank >= 1) & (indices_rank >= 1), 'rank must > 1');\n\n    let mut data_shape = *self.shape;\n    let mut indices_shape = indices.shape;\n    let mut data_shape_clone = data_shape.clone();\n    let mut indices_shape_clone = indices_shape.clone();\n\n    let indices_shape_last = indices_shape_clone.pop_back().unwrap();\n    assert(\n        (*indices_shape_last >= 1) & (*indices_shape_last <= data_rank - batch_dims),\n        'check indices'\n    );\n\n    let mut batch_dims_shape = array![];\n    let mut output_shape = array![];\n    let mut index_data = array![];\n    let mut output_data = array![];\n\n    let mut batch_dims_size = batch_dims;\n    let mut total_data_len = 1;\n    let mut multiple_data_len = array![];\n\n    let mut ind = 0;\n    while ind != batch_dims {\n        match indices_shape_clone.pop_front() {\n            Option::Some(val) => {\n                batch_dims_size *= *val;\n                batch_dims_shape.append(*val);\n                ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    loop {\n        match indices_shape_clone.pop_front() {\n            Option::Some(val) => { batch_dims_shape.append(*val); },\n            Option::None => { break; }\n        };\n    };\n\n    if (*indices_shape_last == data_rank - batch_dims) {\n        output_shape = batch_dims_shape;\n    } else {\n        let mut ind = 0;\n        output_shape = batch_dims_shape;\n        loop {\n            match data_shape_clone.pop_front() {\n                Option::Some(val) => {\n                    if (ind >= (batch_dims + *indices_shape_last)) {\n                        output_shape.append(*val);\n                    }\n\n                    ind += 1;\n                },\n                Option::None => { break; }\n            };\n        };\n    }\n\n    let mut ind = 0;\n    let mut multiple = 1;\n    let mut incrementer = 1;\n    let mut data_shape_clone = data_shape.clone();\n    loop {\n        match data_shape_clone.pop_front() {\n            Option::Some(val) => {\n                if (ind >= batch_dims) {\n                    multiple *= *val;\n                    multiple_data_len.append(multiple);\n                }\n\n                if (ind >= batch_dims + *indices_shape_last) {\n                    incrementer *= *val;\n                }\n\n                ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut ind = 0;\n    let mut indices_shape_clone = indices_shape.clone();\n    let mut breaker = 1;\n    loop {\n        match indices_shape_clone.pop_front() {\n            Option::Some(val) => {\n                if (ind >= batch_dims) {\n                    breaker *= *val;\n                }\n\n                ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    total_data_len = *multiple_data_len.at(multiple_data_len.len() - 1);\n    let mut data_indices = indices.data;\n    let mut ind = 0;\n    let mut result = 0;\n    loop {\n        match data_indices.pop_front() {\n            Option::Some(val) => {\n                let index = ind % *indices_shape_last;\n                let incr = total_data_len * (ind / breaker);\n                result += (*val * total_data_len / *multiple_data_len.at(index));\n                ind += 1;\n\n                if (index == *indices_shape_last - 1) {\n                    let mut data_ind: usize = result;\n                    while data_ind != result + incrementer {\n                        index_data.append(data_ind + incr);\n                        data_ind += 1;\n                    };\n\n                    result = 0;\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    loop {\n        match index_data.pop_front() {\n            Option::Some(val) => { output_data.append(*self.data[val]); },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_tensor = TensorTrait::<T>::new(output_shape.span(), output_data.span());\n\n    output_tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/greater.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::greater docstring\nfn greater<\n    T,\n    impl UsizeFTensor: TensorTrait<usize>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<usize> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<usize> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if *(*y.data)[indices_self] > *(*z.data)[indices_other] {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/greater_equal.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::greater_equal docstring\nfn greater_equal<\n    T,\n    impl UsizeFTensor: TensorTrait<usize>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<usize> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<usize> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if *(*y.data)[indices_self] >= *(*z.data)[indices_other] {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/hamming_window.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn hamming_window<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    size: T, PI: T, periodic: Option<usize>\n) -> Tensor<T> {\n    let start: T = NumberTrait::zero();\n    let one_step: T = NumberTrait::one();\n    let two: T = one_step + one_step;\n    let three: T = two + one_step;\n    let n25: T = three.pow(three) - two;\n    let n46: T = n25 * two - two * two;\n    let alpha: T = n25 / n46;\n\n    let beta: T = one_step - alpha;\n    let ni = TensorTrait::range(start, size, one_step);\n    assert((ni.shape).len() == 1, 'Unexpected shape 1.');\n    let mut N_1 = size;\n\n    if periodic != Option::Some(1) {\n        N_1 = N_1 - one_step;\n    };\n\n    let len = *(ni.shape).at(0);\n    let mut arr: Array<T> = array![];\n    let mut i: usize = 0;\n    while i != len {\n        let v = *(ni.data).at(i);\n        let r = v * PI * two / N_1;\n        arr.append(r);\n        i += 1;\n    };\n\n    let window = TensorTrait::<T>::new(ni.shape, arr.span());\n    let window_cos = window.cos();\n    let len2 = *(ni.shape).at(0);\n    let mut arr2: Array<T> = array![];\n    let mut j: usize = 0;\n    while j != len2 {\n        let v = *(window_cos.data).at(j);\n        let v_2 = alpha - v * beta;\n        arr2.append(v_2);\n        j += 1;\n    };\n\n    let window_cos_2 = TensorTrait::<T>::new(ni.shape, arr2.span());\n\n    window_cos_2\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/hann_window.cairo",
        "content": "use orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn hann_window<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    size: T, PI: T, periodic: Option<usize>\n) -> Tensor<T> {\n    let start: T = NumberTrait::zero();\n    let one_step: T = NumberTrait::one();\n    let ni = TensorTrait::range(start, size, one_step);\n    assert((ni.shape).len() == 1, 'Unexpected shape 1.');\n    let mut N_1 = size;\n\n    if periodic != Option::Some(1) {\n        N_1 = N_1 - one_step;\n    };\n\n    let len = *(ni.shape).at(0);\n    let mut arr: Array<T> = array![];\n    let mut i: usize = 0;\n    while i != len {\n        let v = *(ni.data).at(i);\n        let r = v * PI / N_1;\n        arr.append(r);\n        i += 1;\n    };\n\n    let window = TensorTrait::<T>::new(ni.shape, arr.span());\n    let window_sin = window.sin();\n    let len2 = *(ni.shape).at(0);\n    let mut arr2: Array<T> = array![];\n    let mut j: usize = 0;\n    while j != len2 {\n        let v = *(window_sin.data).at(j);\n        let v_2 = v * v;\n        arr2.append(v_2);\n        j += 1;\n    };\n\n    let window_sin_2 = TensorTrait::<T>::new(ni.shape, arr2.span());\n\n    window_sin_2\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/is_inf.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::implementations::tensor_bool::BoolTensor;\n\n/// Cf: TensorTrait::is_inf docstring\nfn is_inf<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    x: @Tensor<T>, detect_negative: Option<u8>, detect_positive: Option<u8>\n) -> Tensor<bool> {\n    let neg_opt = match detect_negative {\n        Option::Some(val) => { if val == 0 {\n            0\n        } else {\n            1\n        } },\n        Option::None => 1,\n    };\n\n    let pos_opt = match detect_positive {\n        Option::Some(val) => { if val == 0 {\n            0\n        } else {\n            1\n        } },\n        Option::None => 1,\n    };\n\n    if neg_opt == 0 && pos_opt == 0 {\n        return TensorTrait::new(*x.shape, ArrayTrait::<bool>::new().span());\n    }\n\n    if neg_opt == 0 && pos_opt == 1 {\n        return is_pos_inf(x);\n    }\n\n    if neg_opt == 1 && pos_opt == 0 {\n        return is_neg_inf(x);\n    }\n\n    let mut data_result: Array<bool> = array![];\n    let mut y: Span<T> = *x.data;\n    loop {\n        match y.pop_front() {\n            Option::Some(item) => { data_result.append((*item).is_inf()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(*x.shape, data_result.span())\n}\n\n/// Cf: TensorTrait::is_pos_inf docstring\nfn is_pos_inf<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    x: @Tensor<T>\n) -> Tensor<bool> {\n    let mut data_result: Array<bool> = array![];\n    let mut y: Span<T> = *x.data;\n    loop {\n        match y.pop_front() {\n            Option::Some(item) => { data_result.append((*item).is_pos_inf()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(*x.shape, data_result.span())\n}\n\n/// Cf: TensorTrait::is_neg_inf docstring\nfn is_neg_inf<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    x: @Tensor<T>\n) -> Tensor<bool> {\n    let mut data_result: Array<bool> = array![];\n    let mut y: Span<T> = *x.data;\n    loop {\n        match y.pop_front() {\n            Option::Some(item) => { data_result.append((*item).is_neg_inf()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(*x.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/is_nan.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::implementations::tensor_bool::BoolTensor;\n\n/// Cf: TensorTrait::is_nan docstring\nfn is_nan<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    x: @Tensor<T>\n) -> Tensor<bool> {\n    let mut data_result: Array<bool> = array![];\n    let mut y: Span<T> = *x.data;\n    loop {\n        match y.pop_front() {\n            Option::Some(item) => { data_result.append((*item).is_nan()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(*x.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/layer_normalization.cairo",
        "content": "use core::option::OptionTrait;\nuse core::traits::TryInto;\nuse orion::numbers::{NumberTrait, I32IntoU32};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, BoolTensor\n};\nuse orion::operators::vec::{VecTrait, NullableVec, NullableVecImpl};\n\n/// Cf: TensorTrait::layer_normalization docstring\nfn layer_normalization<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +Div<Tensor<T>>,\n    +Sub<Tensor<T>>,\n    +Add<Tensor<T>>,\n    +Mul<Tensor<T>>,\n    +Into<usize, MAG>,\n>(\n    self: @Tensor<T>,\n    scale: @Tensor<T>,\n    B: Option<@Tensor<T>>,\n    axis: Option<i32>,\n    epsilon: Option<T>,\n    stash_type: Option<usize>,\n) -> (Tensor<T>, Tensor<T>, Tensor<T>) {\n    let X_rank = (*self).shape.len();\n\n    let mut axis = match axis {\n        Option::Some(axis) => axis,\n        Option::None => -1,\n    };\n    let epsilon = match epsilon {\n        Option::Some(epsilon) => epsilon,\n        Option::None => NumberTrait::zero(), // default of onnx is 1e-05 \n    };\n\n    let axis = if axis < 0 {\n        X_rank - axis.into()\n    } else {\n        axis.into()\n    };\n\n    let unsqueezed_rank = X_rank - axis;\n    let mut reduction_shape = array![];\n    let mut i = 0;\n    while i != axis {\n        reduction_shape.append(*(*self).shape.at(i));\n        i += 1;\n    };\n\n    let mut i = 0;\n    while i != unsqueezed_rank {\n        reduction_shape.append(1);\n        i += 1;\n    };\n\n    let mut row_number = 1;\n    let mut col_number = 1;\n    let mut i = 0;\n    while i != X_rank {\n        if i < axis {\n            row_number *= *(*self).shape.at(i);\n        } else {\n            col_number *= *(*self).shape.at(i);\n        }\n\n        i += 1;\n    };\n\n    let mut shape_matrix = array![];\n    shape_matrix.append(row_number.try_into().unwrap());\n    shape_matrix.append(col_number.try_into().unwrap());\n\n    // Shape [1, 1] to mutiply one element tensors with 2D matrices\n    let mut shape_one = array![];\n    shape_one.append(1);\n    shape_one.append(1);\n\n    let mut col_number_tensor = array![];\n    col_number_tensor.append(NumberTrait::new_unscaled(col_number.into(), false));\n\n    let mut epsilon_tensor = array![];\n    epsilon_tensor.append(epsilon);\n\n    let mut one_tensor = array![];\n    one_tensor.append(NumberTrait::one());\n\n    let x_mat = self.reshape(shape_matrix.span(), false);\n    let x_mean = x_mat\n        .reduce_sum(Option::Some(array![1].span()), Option::Some(true), Option::Some(false))\n        / TensorTrait::new(shape_one.span(), col_number_tensor.span());\n\n    let x_diff = x_mat - x_mean;\n    let x_squared_diff = x_diff * x_diff;\n\n    let variance = x_squared_diff.reduce_sum(Option::Some(array![1].span()), Option::Some(true), Option::Some(false))\n        / TensorTrait::new(shape_one.span(), col_number_tensor.span());\n    let variance_eps = variance + TensorTrait::new(shape_one.span(), epsilon_tensor.span());\n\n    let std_dev = variance_eps.sqrt();\n\n    let inv_std_dev = TensorTrait::new(shape_one.span(), one_tensor.span()) / std_dev;\n\n    let y_mat = x_diff * inv_std_dev;\n\n    let scale = if (*scale).shape.len() < (*self).shape.len() {\n        // Append 1 in scale shape to make sure scale has a dimension compatible with Y for multiplication\n        let mut shape = array![];\n        let mut i = 0;\n        while i != (*self).shape.len() - (*scale).shape.len() {\n            shape.append(1);\n            i += 1;\n        };\n\n        let mut i = 0;\n        while i != (*scale).shape.len() {\n            shape.append(*(*scale).shape.at(i));\n            i += 1;\n        };\n\n        TensorTrait::new(shape.span(), (*scale).data)\n    } else {\n        *scale\n    };\n\n    let mut i = 0;\n    let mut target_shape: Array<i32> = array![];\n    while i < (*self)\n        .shape\n        .len() {\n            target_shape.append((*(*self).shape.at(i)).try_into().unwrap());\n            i += 1;\n        };\n    let Y = y_mat.reshape(target_shape.span(), false) * scale;\n\n    let Y = match B {\n        Option::Some(B) => {\n            let B = if (*B).shape.len() < (*self).shape.len() {\n                // Append 1 in B shape to make sure scale has a dimension compatible with Y for multiplication\n                let mut shape = array![];\n                let mut i = 0;\n                while i != (*self).shape.len() - (*B).shape.len() {\n                    shape.append(1);\n                    i += 1;\n                };\n\n                let mut i = 0;\n                while i != (*B).shape.len() {\n                    shape.append(*(*B).shape.at(i));\n                    i += 1;\n                };\n\n                TensorTrait::new(shape.span(), (*B).data)\n            } else {\n                *B\n            };\n            Y + B\n        },\n        Option::None => Y,\n    };\n\n    let X_mean = TensorTrait::new(reduction_shape.span(), x_mean.data);\n    let X_inv_std_dev = TensorTrait::new(reduction_shape.span(), inv_std_dev.data);\n\n    (Y, X_mean, X_inv_std_dev)\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/less.cairo",
        "content": "use orion::operators::tensor::{core::{Tensor, TensorTrait, unravel_index}, I32Tensor};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::less docstring\nfn less<T, impl TPartialOrd: PartialOrd<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<i32> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<i32> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if *(*y.data)[indices_self] < *(*z.data)[indices_other] {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/less_equal.cairo",
        "content": "use orion::operators::tensor::{core::{Tensor, TensorTrait, unravel_index}, I32Tensor};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::less_equal docstring\nfn less_equal<\n    T,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<i32> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<i32> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if *(*y.data)[indices_self] <= *(*z.data)[indices_other] {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/log.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::log docstring\nfn log<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).ln()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/max.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::max docstring\nfn max<\n    T,\n    MAG,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    tensors: Span<Tensor<T>>\n) -> Tensor<T> {\n    assert(tensors.len() >= 1, 'Input tensors must be >= 1');\n\n    let first_tensor = *tensors.at(0);\n\n    if tensors.len() == 1 {\n        return first_tensor;\n    }\n\n    let mut max_shape: Span<usize> = first_tensor.shape;\n    let mut max_data: Span<T> = first_tensor.data;\n\n    let mut tensor_counter: usize = 1;\n\n    while tensor_counter != tensors.len() {\n        let mut new_max_data: Array<T> = array![];\n\n        let mut current_tensor = *tensors.at(tensor_counter);\n\n        let mut broadcasted_shape = broadcast_shape(max_shape, current_tensor.shape);\n\n        let num_elements = len_from_shape(broadcasted_shape);\n        let mut n: usize = 0;\n        while n != num_elements {\n            let mut indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n            let mut indices_self = broadcast_index_mapping(max_shape, indices_broadcasted);\n            let mut indices_other = broadcast_index_mapping(\n                current_tensor.shape, indices_broadcasted\n            );\n\n            let mut max_value = NumberTrait::max(\n                *(max_data)[indices_self], *(current_tensor.data)[indices_other]\n            );\n            new_max_data.append(max_value);\n\n            n += 1;\n        };\n\n        max_shape = broadcasted_shape;\n        max_data = new_max_data.span();\n        tensor_counter += 1;\n    };\n\n    TensorTrait::<T>::new(max_shape, max_data)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/max_in_tensor.cairo",
        "content": "use orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::max_in_tensor docstring\nfn max_in_tensor<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut vec: Span::<T>\n) -> T {\n    let mut max_value: T = NumberTrait::min_value();\n\n    loop {\n        match vec.pop_front() {\n            Option::Some(item) => {\n                let check_max = max_value.max(*item);\n                if (max_value < check_max) {\n                    max_value = check_max;\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    max_value\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/min.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::min docstring\nfn min<\n    T,\n    MAG,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    tensors: Span<Tensor<T>>\n) -> Tensor<T> {\n    assert(tensors.len() >= 1, 'Input tensors must be >= 1');\n\n    let first_tensor = *tensors.at(0);\n\n    if tensors.len() == 1 {\n        return first_tensor;\n    }\n\n    let mut min_shape: Span<usize> = first_tensor.shape;\n    let mut min_data: Span<T> = first_tensor.data;\n\n    let mut tensor_counter: usize = 1;\n\n    while tensor_counter != tensors.len() {\n        let mut new_min_data: Array<T> = array![];\n\n        let mut current_tensor = *tensors.at(tensor_counter);\n\n        let mut broadcasted_shape = broadcast_shape(min_shape, current_tensor.shape);\n\n        let num_elements = len_from_shape(broadcasted_shape);\n        let mut n: usize = 0;\n        while n != num_elements {\n            let mut indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n            let mut indices_self = broadcast_index_mapping(min_shape, indices_broadcasted);\n            let mut indices_other = broadcast_index_mapping(\n                current_tensor.shape, indices_broadcasted\n            );\n\n            let mut min_value = NumberTrait::min(\n                *(min_data)[indices_self], *(current_tensor.data)[indices_other]\n            );\n            new_min_data.append(min_value);\n\n            n += 1;\n        };\n\n        min_shape = broadcasted_shape;\n        min_data = new_min_data.span();\n        tensor_counter += 1;\n    };\n\n    TensorTrait::<T>::new(min_shape, min_data)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/min_in_tensor.cairo",
        "content": "use orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::min_in_tensor docstring\nfn min_in_tensor<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut vec: Span::<T>\n) -> T {\n    let mut min_value: T = NumberTrait::max_value();\n\n    loop {\n        match vec.pop_front() {\n            Option::Some(item) => {\n                let check_min = min_value.min(*item);\n                if (min_value > check_min) {\n                    min_value = check_min;\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    min_value\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/neg.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::neg docstring\nfn neg<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut z: Tensor<T>\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => { data_result.append((*item).neg()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::<T>::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/not.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::implementations::{tensor_bool::BoolTensor};\n\n// Cf TensorTrait::not docstring\nfn not(mut z: Tensor<bool>) -> Tensor<bool> {\n    let mut data_result: Array<bool> = array![];\n\n    loop {\n        match z.data.pop_front() {\n            Option::Some(item) => { data_result.append((!*item)); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/onehot.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: TensorTrait::onehot docstring\nfn onehot_encode<\n    T,\n    MAG,\n    impl FFixed: FixedTrait<T, MAG>,\n    impl FTensorTrait: TensorTrait<T>,\n    impl FNumber: NumberTrait<T, MAG>,\n    impl U32TryIntoMAG: TryInto<u32, MAG>,\n    impl FPartialEq: PartialEq<T>,\n    impl FAdd: Add<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    self: @Tensor<T>, depth: usize, axis: Option<usize>, values: Tensor<T>\n) -> Tensor<T> {\n    let mut data = *self.data;\n    let mut shape = *self.shape;\n    let rank = shape.len();\n\n    // using 999 to denote -1, innermost dimension\n    let axis = match axis {\n        Option::Some(val) => val,\n        Option::None => 999\n    };\n\n    assert(((axis == 999) | (axis.into() <= rank)), 'axis out of dimensions');\n\n    let mut output_data = array![];\n    let mut output_size: Array<usize> = array![];\n\n    // New shape for output data\n    loop {\n        match shape.pop_front() {\n            Option::Some(size) => { output_size.append(*size); },\n            Option::None => { break; }\n        };\n    };\n    output_size.append(depth.into());\n\n    // OneHot enocde loop\n    loop {\n        match data.pop_front() {\n            Option::Some(outer_index) => {\n                let mut fixed_number = *outer_index;\n\n                if fixed_number.is_neg() {\n                    fixed_number =\n                        FixedTrait::<T, MAG>::new_unscaled(depth.try_into().unwrap(), false)\n                        + fixed_number\n                }\n\n                let mut inner_index = 0;\n                while inner_index != depth {\n                    let ind = FixedTrait::<\n                        T, MAG\n                    >::new_unscaled(inner_index.try_into().unwrap(), false);\n\n                    if fixed_number == ind {\n                        output_data.append(*values.data.at(1));\n                    } else {\n                        output_data.append(*values.data.at(0));\n                    };\n\n                    inner_index += 1;\n                };\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_tensor = TensorTrait::new(output_size.span(), output_data.span());\n    let mut tranpose_axes = array![];\n    // Get New shape is axis is not last dimension\n    if (axis != 999) & (axis.into() != rank) {\n        let mut index: usize = 0;\n        loop {\n            let max_dim = output_size.len() - 1;\n            if index.into() == max_dim {\n                break ();\n            };\n\n            if axis == index {\n                tranpose_axes.append(max_dim.into())\n            }\n            tranpose_axes.append(index.into());\n            index += 1;\n        };\n\n        output_tensor = output_tensor.transpose(tranpose_axes.span());\n    }\n\n    output_tensor\n}\n\nfn onehot<\n    T,\n    MAG,\n    impl FFixed: FixedTrait<T, MAG>,\n    impl FTensorTrait: TensorTrait<T>,\n    impl FNumber: NumberTrait<T, MAG>,\n    impl U32TryIntoMAG: TryInto<u32, MAG>,\n    impl FPartialEq: PartialEq<T>,\n    impl FAdd: Add<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    self: @Tensor<T>, depth: usize, axis: Option<usize>, mut values: Span<usize>,\n) -> Tensor<T> {\n    assert(values.len() == 2, 'Wrong values dimensions');\n\n    let mut sizes = array![];\n    sizes.append(2);\n\n    let mut first = *values.pop_front().unwrap();\n    let mut second = *values.pop_front().unwrap();\n\n    let mut data = array![];\n    data.append(FixedTrait::<T, MAG>::new_unscaled(first.try_into().unwrap(), false));\n    data.append(FixedTrait::<T, MAG>::new_unscaled(second.try_into().unwrap(), false));\n\n    let values = TensorTrait::new(sizes.span(), data.span());\n\n    onehot_encode(self, depth, axis, values)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/optional_get_element.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::optional_get_element docstring\nfn optional_get_element<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut z: Tensor<T>, index: usize\n) -> Tensor<T> {\n    let mut data_result: Array<T> = array![];\n\n    // use of match to get element within and out the array bound\n    match z.data.get(index) {\n        Option::Some(item) => { data_result.append((*item.unbox())); },\n        Option::None => {}\n    };\n\n    TensorTrait::<T>::new(z.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/or.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::or docstring\nfn or<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl UsizeFTensor: TensorTrait<usize>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<usize> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<usize> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if NumberTrait::or(*(*y.data)[indices_self], *(*z.data)[indices_other]) {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/pow.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{broadcast_shape, broadcast_index_mapping, len_from_shape};\n\n/// Cf: TensorTrait::pow docstring\nfn pow<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<T> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<T> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        result.append(NumberTrait::pow(*(*y.data)[indices_self], *(*z.data)[indices_other]));\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/random_uniform_like.cairo",
        "content": "use core::integer;\n\nuse alexandria_merkle_tree::merkle_tree::{pedersen::PedersenHasherImpl};\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\nuse orion::operators::tensor::math::{reduce_sum::accumulate_sum, arithmetic::div_downcast};\n\n/// Cf: TensorTrait::random_uniform_like docstring\nfn random_uniform_like<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TRem: Rem<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    tensor: Tensor<T>, high: Option<T>, low: Option<T>, seed: Option<usize>\n) -> Tensor<T> {\n    let mut seed: usize = match seed {\n        Option::Some(seed) => seed,\n        Option::None => NumberTrait::max_value(),\n    };\n    let mut high = match high {\n        Option::Some(high) => high,\n        Option::None => NumberTrait::one(),\n    };\n    let mut low = match low {\n        Option::Some(low) => low,\n        Option::None => NumberTrait::zero(),\n    };\n    assert!(high > low, \"high must be larger than low\");\n    let res = tensor_get_state(tensor, seed, high, low);\n\n    res\n}\n\nfn tensor_get_state<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TRem: Rem<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    tensor: Tensor<T>, mut seed: usize, high: T, low: T\n) -> Tensor<T> {\n    let mut data = array![];\n    let mut count = (tensor.data).len();\n    let mut i = 0;\n\n    while count != i {\n        let mut v = NumberTrait::one();\n        v = hash_random_range(seed, low, high);\n        let a: u64 = 1664525;\n        let c: u64 = 1013904223;\n        let m: u64 = 4294967295;\n        let s: u64 = (a * seed.try_into().unwrap() + c) % m;\n        seed = s.try_into().unwrap();\n        data.append(v);\n        i += 1;\n    };\n\n    TensorTrait::new(tensor.shape, data.span())\n}\n\n// High level random in a range\n// Only one random number per hash might be inefficient.\nfn hash_random_range<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDiv: Div<T>,\n    impl TRem: Rem<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    seed: usize, min: T, max: T\n) -> T {\n    let mut key = PedersenHasherImpl::new();\n    let hash: felt252 = key.hash(seed.into(), 1);\n    let a: u128 = 4294967295;\n    let b: u128 = match integer::u128s_from_felt252(hash) {\n        integer::U128sFromFelt252Result::Narrow(x) => x,\n        integer::U128sFromFelt252Result::Wide((x, _)) => x,\n    } % a;\n    let c: felt252 = b.into();\n    let rnd: T = NumberTrait::from_felt(c);\n    let range = max - min + NumberTrait::one(); // + 1 to include max\n\n    min + rnd % range\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/range.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn range<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut start: T, end: T, step: T\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n    let zero: T = NumberTrait::zero();\n    while !(step >= zero && start >= end) && !(step <= zero && start <= end) {\n        let v = start;\n        result.append(v);\n        start += step;\n    };\n\n    let shape = array![result.len()];\n\n    TensorTrait::<T>::new(shape.span(), result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_l1.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\n\n/// Cf: TensorTrait::reduce_sum docstring\nfn reduce_l1<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let data_abs = self.abs();\n\n    data_abs.reduce_sum(Option::Some(array![axis.try_into().unwrap()].span()), Option::Some(keepdims), Option::Some(false))\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_l2.cairo",
        "content": "use core::debug::PrintTrait;\n\nuse orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\n\nfn square<\n    T,\n    MAG,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>\n) -> Tensor<T> {\n    let mut data = *self.data;\n    let mut output_data = array![];\n\n    loop {\n        match data.pop_front() {\n            Option::Some(item) => {\n                let ele = *item;\n                output_data.append(ele * ele);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let tensor_square = TensorTrait::new(*self.shape, output_data.span());\n\n    tensor_square\n}\n\n/// Cf: TensorTrait::reduce_l2 docstring\nfn reduce_l2<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let tensor_square = square(self);\n    let tensor_square_sum = tensor_square\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(keepdims),\n            Option::Some(false)\n        );\n\n    tensor_square_sum.sqrt()\n}\n\nfn reduce_l2_complex<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TPrint: PrintTrait<T>\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let mut tensor_square = square(@self.abs());\n    let mut tensor_square_sum = tensor_square\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(keepdims),\n            Option::Some(false)\n        );\n\n    tensor_square_sum.sqrt()\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_log_sum.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\n\n/// Cf: TensorTrait::reduce_sum_square docstring\nfn reduce_log_sum<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let tensor_square_sum = self\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(keepdims),\n            Option::Some(false)\n        );\n    let tensor_square_sum_log = tensor_square_sum.log();\n\n    tensor_square_sum_log\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_log_sum_exp.cairo",
        "content": "use core::option::OptionTrait;\nuse core::array::ArrayTrait;\nuse core::array::SpanTrait;\nuse core::debug::PrintTrait;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::math::{exp::exp_upcast, arithmetic::div_downcast};\n\n/// Cf: TensorTrait::reduce_log_sum_exp docstring\n// fn reduce_log_sum_exp_wide<\n//     T,\n//     TMAG,\n//     W,\n//     WMAG,\n//     impl TIntoW: Into<T, W>,\n//     impl WTryIntoT: TryInto<W, T>,\n//     impl WCopy: Copy<W>,\n//     impl WDrop: Drop<W>,\n//     impl TCopy: Copy<T>,\n//     impl TDrop: Drop<T>,\n//     impl TDiv: Div<T>,\n//     impl TTensor: TensorTrait<T>,\n//     impl WTensor: TensorTrait<W>,\n//     impl TFixed: FixedTrait<T, TMAG>,\n//     impl WFixed: FixedTrait<W, WMAG>\n// >(\n//     self: @Tensor<T>, axis: usize, keepdims: bool\n// ) -> Tensor<W> {\n//     let tensor_exp: Tensor<W> = exp_upcast(*self);\n//     let tensor_exp_log_sum = tensor_exp.reduce_log_sum(axis, keepdims);\n\n//     return tensor_exp_log_sum;\n// }\n\nfn reduce_log_sum_exp<\n    T,\n    MAG,\n    impl Tensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let tensor_exp = self.exp();\n    let tensor_exp_log_sum = tensor_exp.reduce_log_sum(axis: axis, keepdims: keepdims);\n    return tensor_exp_log_sum;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_mean.cairo",
        "content": "use alexandria_sorting::bubble_sort;\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{\n    reduce_output_shape, len_from_shape, combine_indices, get_all_axes\n};\n\n/// Cf: TensorTrait::reduce_mean docstring\nfn reduce_mean<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TDiv: Div<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>,\n    axes: Option<Span<usize>>,\n    keepdims: Option<bool>,\n    noop_with_empty_axes: Option<bool>\n) -> Tensor<T> {\n    let noop_with_empty_axes = match noop_with_empty_axes {\n        Option::Some(noop_with_empty_axes) => noop_with_empty_axes,\n        Option::None => false,\n    };\n    let axes = match axes {\n        Option::Some(axes) => {\n            if (axes.len() == 0) {\n                get_all_axes(*self.shape)\n            } else {\n                assert(axes.len() == axes.unique().len(), 'duplicated axis.');\n                let mut axes_arr = array![];\n                let mut copy_axes = axes;\n                loop {\n                    match copy_axes.pop_front() {\n                        Option::Some(axis) => { axes_arr.append(*axis); },\n                        Option::None => { break; }\n                    };\n                };\n                let sorted_axes = bubble_sort::bubble_sort_elements(axes_arr, true).span();\n                sorted_axes\n            }\n        },\n        Option::None => {\n            if noop_with_empty_axes {\n                return *self;\n            }\n            get_all_axes(*self.shape)\n        },\n    };\n    let keepdims = match keepdims {\n        Option::Some(keepdims) => keepdims,\n        Option::None => true,\n    };\n\n    let mut axis_c = 0;\n    let mut copy_axes = axes;\n    let mut shape = *self.shape;\n    let mut data = *self.data;\n    loop {\n        match copy_axes.pop_front() {\n            Option::Some(axis) => {\n                if (shape.len() == 1) {\n                    let current_mean = accumulate_mean::<T>(data, shape, shape, 0);\n                    shape = array![].span();\n                    data = array![current_mean].span();\n                    break ();\n                }\n                let mut temp_data = array![];\n                let mut temp_shape = reduce_output_shape(shape, *axis - axis_c, false);\n                let data_len = len_from_shape(temp_shape);\n                let mut index: usize = 0;\n                while index != data_len {\n                    let indices = unravel_index(index, temp_shape);\n                    let current_mean = accumulate_mean::<T>(data, shape, indices, *axis - axis_c);\n\n                    temp_data.append(current_mean);\n\n                    index += 1;\n                };\n\n                shape = temp_shape;\n                data = temp_data.span();\n                axis_c += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut axes_copy = axes;\n    if keepdims {\n        shape = *self.shape;\n        loop {\n            match axes_copy.pop_front() {\n                Option::Some(axis) => { shape = reduce_output_shape(shape, *axis, true); },\n                Option::None => { break; }\n            };\n        };\n\n        TensorTrait::<T>::new(shape, data)\n    } else {\n        TensorTrait::<T>::new(shape, data)\n    }\n}\n\n/// Helper function that accumulates the mean of elements along a specific axis.\n///\n/// # Arguments\n/// * `input_data` - The input's data.\n/// * `input_shape` - The input's shape.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to accumulate the mean.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A value representing the accumulated mean along the specified axis.\nfn accumulate_mean<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TDiv: Div<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut input_data: Span<T>, input_shape: Span<usize>, output_indices: Span<usize>, axis: usize\n) -> T {\n    let axis_len = *(input_shape)[axis];\n    let mut acc: T = NumberTrait::zero();\n\n    let mut axis_index: T = NumberTrait::zero();\n    let mut axis_indexu32 = 0;\n\n    if (input_shape).len() > 1 {\n        while axis_indexu32 != axis_len {\n            let input_indices = combine_indices(output_indices, axis_indexu32, axis);\n            let input_index = ravel_index(input_shape, input_indices);\n            let ele = *(input_data)[input_index];\n            acc += ele;\n            axis_index += NumberTrait::one();\n            axis_indexu32 += 1;\n        };\n    } else {\n        loop {\n            match input_data.pop_front() {\n                Option::Some(item) => {\n                    acc += *item;\n                    axis_index += NumberTrait::one();\n                    axis_indexu32 += 1;\n                },\n                Option::None => { break; }\n            };\n        };\n    }\n    // let axis_index: T = NumberTrait::<T, MAG>::new(axis_index.try_into().unwrap(), false); \n    acc / axis_index\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_min.cairo",
        "content": "use alexandria_sorting::bubble_sort;\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{\n    reduce_output_shape, len_from_shape, combine_indices, get_all_axes\n};\n\n/// Cf: TensorTrait::reduce_min docstring\nfn reduce_min<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>,\n    axes: Option<Span<usize>>,\n    keepdims: Option<bool>,\n    noop_with_empty_axes: Option<bool>\n) -> Tensor<T> {\n    let noop_with_empty_axes = match noop_with_empty_axes {\n        Option::Some(noop_with_empty_axes) => noop_with_empty_axes,\n        Option::None => false,\n    };\n    let axes = match axes {\n        Option::Some(axes) => {\n            if (axes.len() == 0) {\n                get_all_axes(*self.shape)\n            } else {\n                assert(axes.len() == axes.unique().len(), 'duplicated axis.');\n                let mut axes_arr: Array<usize> = array![];\n                let mut copy_axes = axes;\n                loop {\n                    match copy_axes.pop_front() {\n                        Option::Some(axis) => { axes_arr.append(*axis); },\n                        Option::None => { break; }\n                    };\n                };\n                let sorted_axes = bubble_sort::bubble_sort_elements(axes_arr, true).span();\n                sorted_axes\n            }\n        },\n        Option::None => {\n            if noop_with_empty_axes {\n                return *self;\n            }\n            get_all_axes(*self.shape)\n        },\n    };\n    let keepdims = match keepdims {\n        Option::Some(keepdims) => keepdims,\n        Option::None => true,\n    };\n\n    let mut axis_c = 0;\n    let mut copy_axes = axes;\n    let mut shape = *self.shape;\n    let mut data = *self.data;\n    loop {\n        match copy_axes.pop_front() {\n            Option::Some(axis) => {\n                if (shape.len() == 1) {\n                    let current_min = accumulate_min::<T>(data, shape, shape, 0);\n                    shape = array![].span();\n                    data = array![current_min].span();\n                    break ();\n                }\n                let mut temp_data = array![];\n                let mut temp_shape = reduce_output_shape(shape, *axis - axis_c, false);\n                let data_len = len_from_shape(temp_shape);\n                let mut index: usize = 0;\n                while index != data_len {\n                    let indices = unravel_index(index, temp_shape);\n                    let current_min = accumulate_min::<T>(data, shape, indices, *axis - axis_c);\n\n                    temp_data.append(current_min);\n\n                    index += 1;\n                };\n\n                shape = temp_shape;\n                data = temp_data.span();\n                axis_c += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut axes_copy = axes;\n    if keepdims {\n        shape = *self.shape;\n        loop {\n            match axes_copy.pop_front() {\n                Option::Some(axis) => { shape = reduce_output_shape(shape, *axis, true); },\n                Option::None => { break; }\n            };\n        };\n\n        TensorTrait::<T>::new(shape, data)\n    } else {\n        TensorTrait::<T>::new(shape, data)\n    }\n}\n\n/// Helper function that accumulates the minimum of elements along a specific axis.\n///\n/// # Arguments\n/// * `input_data` - The input's data.\n/// * `input_shape` - The input's shape.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to accumulate the minimum.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A value representing the accumulated minimum along the specified axis.\nfn accumulate_min<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut input_data: Span<T>, input_shape: Span<usize>, output_indices: Span<usize>, axis: usize\n) -> T {\n    let axis_len = *(input_shape)[axis];\n    let mut min: T = NumberTrait::max_value();\n\n    let mut axis_index = 0;\n\n    if (input_shape).len() > 1 {\n        while axis_index != axis_len {\n            let input_indices = combine_indices(output_indices, axis_index, axis);\n            let input_index = ravel_index(input_shape, input_indices);\n            let ele = *(input_data)[input_index];\n            if (ele < min) {\n                min = ele;\n            }\n\n            axis_index += 1;\n        };\n    } else {\n        loop {\n            match input_data.pop_front() {\n                Option::Some(item) => { if (*item < min) {\n                    min = *item;\n                } },\n                Option::None => { break; }\n            };\n        };\n    }\n\n    min\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_prod.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{reduce_output_shape, len_from_shape, combine_indices};\n\n/// reduce_prod - Reduces a tensor to its products along specified axis.\nfn reduce_prod<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAddEq: AddEq<T>,\n    impl TMulEq: MulEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    /// Performs the reduction operation akin to ONNX's 'reduce_prod' on the given tensor for Orion Runtime.\n    ///\n    /// Given a tensor `self`, this function computes the product of elements along the specified axis.\n    /// If the tensor is one-dimensional, the axis must be 0. For multi-dimensional tensors,\n    /// the axis determines the dimension along which the reduction is performed.\n    ///\n    /// Arguments:\n    /// - `self`: A reference to the input tensor on which the reduction operation is applied.\n    /// - `axis`: The axis along which the reduction operation is performed.\n    /// - `keepdims`: A boolean flag indicating whether to keep the reduced dimension in the output shape.\n    ///\n    /// Returns:\n    /// - A new tensor resulting from the reduction operation.\n    ///   If `keepdims` is `true`, the output tensor retains reduced dimensions;\n    ///   otherwise, the reduced dimensions are eliminated from the output shape.\n    ///\n    /// # Panics\n    /// - Panics if the specified axis is out of the tensor's dimensions.\n    ///\n    /// # Examples\n    /// ```rust\n    /// // Create a tensor\n    /// let tensor_1 = TensorTrait::new(\n    ///     shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),);\n    ///\n    /// // Reduce along axis 1 while keeping the dimension\n    /// let reduced = reduce_prod(@tensor_1, 1, true);\n    ///\n    /// // Verify the shape of the reduced tensor\n    /// assert(reduced.shape == array![2,1,2].span() , 'the tensors shapes are not equal');\n    /// ```\n    ///\n    /// # Notes\n    /// - This function utilizes accumulation of products along the specified axis to perform the reduction.\n    /// - For one-dimensional tensors, the axis must be 0 to compute the product of all elements.\n    ///\n    /// # See Also\n    /// - ONNX's 'reduce_prod' operation: https://github.com/onnx/onnx/blob/main/docs/Operators.md#ReduceProd \n    ///\n    /// # References\n    /// - Orion: https://orion.gizatech.xyz/\n    /// - ONNX: Open Neural Network Exchange: https://onnx.ai/\n    ///\n    /// ```\n    let mut output_data = array![];\n\n    if (*self.shape).len() == 1 {\n        assert(axis == 0, 'axis out of dimensions');\n        let current_prod = accumulate_production::<T>(*self.data, *self.shape, *self.shape, axis);\n        output_data.append(current_prod);\n\n        let mut output_shape = array![];\n        output_shape.append(1);\n\n        return TensorTrait::new(output_shape.span(), output_data.span());\n    } else {\n        assert(axis <= (*self.shape).len(), 'axis out of dimensions');\n        let output_shape = reduce_output_shape(*self.shape, axis, false);\n        let output_data_len = len_from_shape(output_shape);\n        let mut index: usize = 0;\n        while index != output_data_len {\n            let output_indices = unravel_index(index, output_shape);\n            let current_sum = accumulate_production::<\n                T\n            >(*self.data, *self.shape, output_indices, axis);\n\n            output_data.append(current_sum);\n\n            index += 1;\n        };\n\n        if keepdims {\n            let output_shape = reduce_output_shape(*self.shape, axis, true);\n\n            TensorTrait::<T>::new(output_shape, output_data.span())\n        } else {\n            TensorTrait::<T>::new(output_shape, output_data.span())\n        }\n    }\n}\n\n\n/// Helper function that accumulates the product of elements along a specific axis.\n///\n/// # Arguments\n/// * `input_data` - The input's data.\n/// * `input_shape` - The input's shape.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to accumulate the product.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * An i32 value representing the accumulated product along the specified axis.\nfn accumulate_production<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TAddEq: AddEq<T>,\n    impl TMulEq: MulEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut input_data: Span<T>, input_shape: Span<usize>, output_indices: Span<usize>, axis: usize\n) -> T {\n    let axis_len = *(input_shape)[axis];\n    let mut acc: T = NumberTrait::one();\n\n    let mut axis_index: usize = 0;\n\n    if (input_shape).len() > 1 {\n        loop {\n            if axis_index == axis_len {\n                break ();\n            }\n\n            let input_indices = combine_indices(output_indices, axis_index, axis);\n            let input_index = ravel_index(input_shape, input_indices);\n            let ele = *(input_data)[input_index];\n            acc *= ele;\n            axis_index += 1;\n        };\n    } else {\n        loop {\n            match input_data.pop_front() {\n                Option::Some(item) => { acc *= *item; },\n                Option::None => { break; }\n            };\n        };\n    }\n\n    return acc;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_sum.cairo",
        "content": "use core::option::OptionTrait;\nuse core::traits::TryInto;\nuse alexandria_sorting::bubble_sort;\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\n\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::operators::tensor::helpers::{\n    reduce_output_shape, len_from_shape, combine_indices, get_all_axes\n};\n\n/// Cf: TensorTrait::reduce_sum docstring\nfn reduce_sum<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>,\n    axes: Option<Span<i32>>,\n    keepdims: Option<bool>,\n    noop_with_empty_axes: Option<bool>\n) -> Tensor<T> {\n    let noop_with_empty_axes = match noop_with_empty_axes {\n        Option::Some(noop_with_empty_axes) => noop_with_empty_axes,\n        Option::None => false,\n    };\n    let axes = match axes {\n        Option::Some(axes) => {\n            if (axes.len() == 0) {\n                get_all_axes(*self.shape)\n            } else {\n                assert(axes.len() == axes.unique().len(), 'duplicated axis.');\n                let mut axes_arr: Array<usize> = array![];\n                let mut copy_axes = axes.clone();\n                loop {\n                    match copy_axes.pop_front() {\n                        Option::Some(axis) => {\n                            // Adjust negative axes to positive\n                            let adjusted_axis = if *axis < 0 {\n                                ((*self.shape).len().try_into().unwrap() + *axis)\n                                    .try_into()\n                                    .unwrap()\n                            } else {\n                                (*axis).try_into().unwrap()\n                            };\n                            axes_arr.append(adjusted_axis);\n                        },\n                        Option::None => { break; }\n                    };\n                };\n                let sorted_axes = bubble_sort::bubble_sort_elements(axes_arr, true).span();\n                sorted_axes\n            }\n        },\n        Option::None => {\n            if noop_with_empty_axes {\n                return *self;\n            }\n            get_all_axes(*self.shape)\n        },\n    };\n    let keepdims = match keepdims {\n        Option::Some(keepdims) => keepdims,\n        Option::None => true,\n    };\n\n    let mut axis_c = 0;\n    let mut copy_axes = axes.clone();\n    let mut shape = *self.shape;\n    let mut data = *self.data;\n    loop {\n        match copy_axes.pop_front() {\n            Option::Some(axis) => {\n                if (shape.len() == 1) {\n                    let current_sum = accumulate_sum::<T>(data, shape, shape, 0);\n                    shape = array![].span();\n                    data = array![current_sum].span();\n                    break ();\n                }\n                let mut temp_data = array![];\n                let mut temp_shape = reduce_output_shape(shape, *axis - axis_c, false);\n                let data_len = len_from_shape(temp_shape);\n                let mut index: usize = 0;\n                while index != data_len {\n                    let indices = unravel_index(index, temp_shape);\n                    let current_sum = accumulate_sum::<T>(data, shape, indices, *axis - axis_c);\n\n                    temp_data.append(current_sum);\n\n                    index += 1;\n                };\n\n                shape = temp_shape;\n                data = temp_data.span();\n                axis_c += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut axes_copy = axes.clone();\n    if keepdims {\n        shape = *self.shape;\n        loop {\n            match axes_copy.pop_front() {\n                Option::Some(axis) => { shape = reduce_output_shape(shape, *axis, true); },\n                Option::None => { break; }\n            };\n        };\n\n        TensorTrait::<T>::new(shape, data)\n    } else {\n        TensorTrait::<T>::new(shape, data)\n    }\n}\n\n/// Helper function that accumulates the sum of elements along a specific axis.\n///\n/// # Arguments\n/// * `input_data` - The input's data.\n/// * `input_shape` - The input's shape.\n/// * `output_indices` - A span of output indices.\n/// * `axis` - The axis along which to accumulate the sum.\n///\n/// # Panics\n/// * Panics if gas limit is exceeded during execution.\n///\n/// # Returns\n/// * A value representing the accumulated sum along the specified axis.\nfn accumulate_sum<\n    T, MAG, impl TNumber: NumberTrait<T, MAG>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    mut input_data: Span<T>, input_shape: Span<usize>, output_indices: Span<usize>, axis: usize\n) -> T {\n    let axis_len = *(input_shape)[axis];\n    let mut sum: T = NumberTrait::zero();\n\n    let mut axis_index = 0;\n\n    if (input_shape).len() > 1 {\n        while axis_index != axis_len {\n            let input_indices = combine_indices(output_indices, axis_index, axis);\n            let input_index = ravel_index(input_shape, input_indices);\n            let ele = *(input_data)[input_index];\n            sum = NumberTrait::add(sum, ele);\n\n            axis_index += 1;\n        };\n    } else {\n        loop {\n            match input_data.pop_front() {\n                Option::Some(item) => sum = NumberTrait::add(sum, *item),\n                Option::None => { break; }\n            };\n        };\n    }\n\n    sum\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/reduce_sum_square.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, ravel_index, unravel_index};\nuse orion::numbers::fixed_point::core::FixedTrait;\n\nfn square<\n    T,\n    MAG,\n    impl FTensorTrait: TensorTrait<T>,\n    impl FNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    self: @Tensor<T>\n) -> Tensor<T> {\n    let mut data = *self.data;\n    let mut output_data = array![];\n\n    loop {\n        match data.pop_front() {\n            Option::Some(item) => {\n                let ele = *item;\n                output_data.append(ele * ele);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let tensor_square = TensorTrait::new(*self.shape, output_data.span());\n\n    tensor_square\n}\n\n/// Cf: TensorTrait::reduce_sum_square docstring\nfn reduce_sum_square<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    self: @Tensor<T>, axis: usize, keepdims: bool\n) -> Tensor<T> {\n    let tensor_square = square(self);\n    let tensor_square_sum = tensor_square\n        .reduce_sum(\n            Option::Some(array![axis.try_into().unwrap()].span()),\n            Option::Some(keepdims),\n            Option::Some(false)\n        );\n\n    tensor_square_sum\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/resize.cairo",
        "content": "use alexandria_sorting::bubble_sort;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, BoolTensor\n};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\n\n#[derive(Copy, Drop)]\nenum MODE {\n    NEAREST,\n    LINEAR,\n    CUBIC,\n}\n\n#[derive(Copy, Drop)]\nenum NEAREST_MODE {\n    ROUND_PREFER_FLOOR,\n    ROUND_PREFER_CEIL,\n    FLOOR,\n    CEIL\n}\n\n#[derive(Copy, Drop)]\nenum KEEP_ASPECT_RATIO_POLICY {\n    STRETCH,\n    NOT_LARGER,\n    NOT_SMALLER\n}\n\n#[derive(Copy, Drop)]\nenum TRANSFORMATION_MODE {\n    HALF_PIXEL,\n    ALIGN_CORNERS,\n    ASYMMETRIC,\n    TF_CROP_AND_RESIZE,\n    PYTORCH_HALF_PIXEL,\n    HALF_PIXEL_SYMMETRIC\n}\n\n/// Cf: TensorTrait::resize docstring\nfn resize<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    self: @Tensor<T>,\n    roi: Option<Tensor<T>>,\n    scales: Option<Span<T>>,\n    sizes: Option<Span<usize>>,\n    antialias: Option<usize>,\n    axes: Option<Span<usize>>,\n    coordinate_transformation_mode: Option<TRANSFORMATION_MODE>,\n    cubic_coeff_a: Option<T>,\n    exclude_outside: Option<bool>,\n    extrapolation_value: Option<T>,\n    keep_aspect_ratio_policy: Option<KEEP_ASPECT_RATIO_POLICY>,\n    mode: Option<MODE>,\n    nearest_mode: Option<NEAREST_MODE>,\n) -> Tensor<T> {\n    let output = interpolate_nd(\n        self,\n        antialias,\n        mode,\n        nearest_mode,\n        scales,\n        sizes,\n        roi,\n        keep_aspect_ratio_policy,\n        exclude_outside,\n        coordinate_transformation_mode,\n        extrapolation_value,\n        axes,\n        cubic_coeff_a\n    );\n\n    output\n}\n\nfn interpolate_nd<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    data: @Tensor<T>,\n    antialias: Option<usize>,\n    mode: Option<MODE>,\n    nearest_mode: Option<NEAREST_MODE>,\n    scale_factors: Option<Span<T>>,\n    output_size: Option<Span<usize>>,\n    roi: Option<Tensor<T>>,\n    keep_aspect_ratio_policy: Option<KEEP_ASPECT_RATIO_POLICY>,\n    exclude_outside: Option<bool>,\n    coordinate_transformation_mode: Option<TRANSFORMATION_MODE>,\n    extrapolation_value: Option<T>,\n    axes: Option<Span<usize>>,\n    cubic_coeff_a: Option<T>,\n) -> Tensor<T> {\n    let mode = match mode {\n        Option::Some(mode) => mode,\n        Option::None => { MODE::NEAREST },\n    };\n\n    let keep_aspect_ratio_policy = match keep_aspect_ratio_policy {\n        Option::Some(keep_aspect_ratio_policy) => keep_aspect_ratio_policy,\n        Option::None => { KEEP_ASPECT_RATIO_POLICY::STRETCH },\n    };\n\n    let exclude_outside = match exclude_outside {\n        Option::Some(exclude_outside) => exclude_outside,\n        Option::None => { false },\n    };\n\n    let extrapolation_value = match extrapolation_value {\n        Option::Some(extrapolation_value) => extrapolation_value,\n        Option::None => { NumberTrait::zero() },\n    };\n\n    if output_size.is_none() && scale_factors.is_none() {\n        core::panic_with_felt252('size and scale are None');\n    }\n\n    let r = (*data).shape.len();\n\n    let (axes, scale_factors, output_size, roi) = match axes {\n        Option::Some(axes) => {\n            let mut scale_factors = match scale_factors {\n                Option::Some(scale_factors) => {\n                    let mut new_scale_factors = ArrayTrait::<T>::new();\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break NumberTrait::one();\n                            }\n\n                            if *axes.at(i) == d {\n                                break *scale_factors.at(i);\n                            }\n\n                            i += 1;\n                        };\n                        new_scale_factors.append(item);\n                        d += 1;\n                    };\n\n                    Option::Some(new_scale_factors.span())\n                },\n                Option::None => { Option::None },\n            };\n\n            let mut output_size = match output_size {\n                Option::Some(output_size) => {\n                    let mut new_output_size = array![];\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break *(*data).shape.at(d);\n                            }\n\n                            if *axes.at(i) == d {\n                                break *output_size.at(i);\n                            }\n\n                            i += 1;\n                        };\n                        new_output_size.append(item);\n                        d += 1;\n                    };\n\n                    Option::Some(new_output_size.span())\n                },\n                Option::None => { Option::None },\n            };\n\n            let mut roi = match roi {\n                Option::Some(roi) => {\n                    let mut new_roi_data = array![];\n                    let naxes = axes.len();\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break NumberTrait::zero();\n                            }\n\n                            if *axes.at(i) == d {\n                                break *roi.data.at(i);\n                            }\n\n                            i += 1;\n                        };\n\n                        new_roi_data.append(item);\n                        d += 1;\n                    };\n\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break NumberTrait::one();\n                            }\n\n                            if *axes.at(i) == d {\n                                break *roi.data.at(i + naxes);\n                            }\n\n                            i += 1;\n                        };\n\n                        new_roi_data.append(item);\n                        d += 1;\n                    };\n\n                    let mut shape = ArrayTrait::new();\n                    shape.append(r * 2);\n                    Option::Some(TensorTrait::new(shape.span(), new_roi_data.span()))\n                },\n                Option::None => { Option::None },\n            };\n\n            (axes, scale_factors, output_size, roi)\n        },\n        Option::None => {\n            let mut axes = array![];\n            let mut i = 0;\n            while i != r {\n                axes.append(i);\n                i += 1;\n            };\n\n            (axes.span(), scale_factors, output_size, roi)\n        }\n    };\n    let (mut output_size, mut scale_factors) = match output_size {\n        Option::Some(output_size) => {\n            let mut scale_factors: Array<T> = array![];\n            let mut i = 0;\n            while i != r {\n                let output_size_i: T = NumberTrait::new_unscaled(\n                    (*output_size.at(i)).into(), false\n                );\n                let data_shape_i: T = NumberTrait::new_unscaled(\n                    (*(*data).shape.at(i)).into(), false\n                );\n\n                scale_factors.append(output_size_i / data_shape_i);\n                i += 1;\n            };\n\n            let (mut output_size, mut scale_factors) = match keep_aspect_ratio_policy {\n                KEEP_ASPECT_RATIO_POLICY::STRETCH => { (output_size, scale_factors.span()) },\n                KEEP_ASPECT_RATIO_POLICY::NOT_LARGER => {\n                    let mut scale = *scale_factors.at(*axes.at(0));\n                    let mut i = 1;\n                    while i != axes.len() {\n                        if scale > *scale_factors.at(*axes.at(i)) {\n                            scale = *scale_factors.at(*axes.at(i));\n                        }\n\n                        i += 1;\n                    };\n\n                    let mut scale_factors: Array<T> = array![];\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break NumberTrait::one();\n                            }\n\n                            if *axes.at(i) == d {\n                                break scale;\n                            }\n\n                            i += 1;\n                        };\n                        scale_factors.append(item);\n                        d += 1;\n                    };\n\n                    let mut output_size = array![];\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break *(*data).shape.at(d);\n                            }\n\n                            if *axes.at(i) == d {\n                                break NumberTrait::round(\n                                    scale\n                                        * NumberTrait::new_unscaled(\n                                            (*(*data).shape.at(d)).into(), false\n                                        )\n                                )\n                                    .try_into()\n                                    .unwrap();\n                            }\n\n                            i += 1;\n                        };\n                        output_size.append(item);\n                        d += 1;\n                    };\n\n                    (output_size.span(), scale_factors.span())\n                },\n                KEEP_ASPECT_RATIO_POLICY::NOT_SMALLER => {\n                    let mut scale = *scale_factors.at(*axes.at(0));\n                    let mut i = 1;\n                    while i != axes.len() {\n                        if scale < *scale_factors.at(*axes.at(i)) {\n                            scale = *scale_factors.at(*axes.at(i));\n                        }\n\n                        i += 1;\n                    };\n\n                    let mut scale_factors: Array<T> = array![];\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break NumberTrait::one();\n                            }\n\n                            if *axes.at(i) == d {\n                                break scale;\n                            }\n\n                            i += 1;\n                        };\n                        scale_factors.append(item);\n                        d += 1;\n                    };\n\n                    let mut output_size = array![];\n                    let mut d = 0;\n                    while d != r {\n                        let mut i = 0;\n                        let item = loop {\n                            if i == axes.len() {\n                                break *(*data).shape.at(d);\n                            }\n\n                            if *axes.at(i) == d {\n                                break NumberTrait::round(\n                                    scale\n                                        * NumberTrait::new_unscaled(\n                                            (*(*data).shape.at(d)).into(), false\n                                        )\n                                )\n                                    .try_into()\n                                    .unwrap();\n                            }\n\n                            i += 1;\n                        };\n                        output_size.append(item);\n                        d += 1;\n                    };\n\n                    (output_size.span(), scale_factors.span())\n                },\n            };\n\n            (output_size, scale_factors)\n        },\n        Option::None => {\n            let mut output_size: Array<usize> = array![];\n\n            let scale_factors = match scale_factors {\n                Option::Some(scale_factors) => scale_factors,\n                Option::None => { core::panic_with_felt252('size and scale None') },\n            };\n\n            let mut i = 0;\n            while i != scale_factors.len() {\n                let item = *scale_factors.at(i)\n                    * NumberTrait::new_unscaled((*(*(data).shape).at(i)).into(), false);\n                output_size.append(item.try_into().unwrap());\n                i += 1;\n            };\n\n            (output_size.span(), scale_factors)\n        },\n    };\n\n    let mut ret: Array<Span<usize>> = array![];\n    let mut i = 0;\n    while i != output_size.len() {\n        let mut temp = ArrayTrait::<usize>::new();\n        let mut j = 0;\n        while j != *output_size.at(i) {\n            temp.append(j);\n            j += 1;\n        };\n\n        ret.append(temp.span());\n        i += 1;\n    };\n\n    let mut ret = cartesian(ret.span());\n    let mut ret_data = array![];\n\n    loop {\n        match ret.pop_front() {\n            Option::Some(X) => {\n                let mut x: Array<T> = array![];\n                let mut i = 0;\n                while i != X.len() {\n                    x.append(NumberTrait::new_unscaled((*X.at(i)).into(), false));\n                    i += 1;\n                };\n\n                let mut x = x.span();\n                let item = interpolate_nd_with_x(\n                    data,\n                    (*data).shape.len(),\n                    scale_factors,\n                    output_size,\n                    x,\n                    antialias,\n                    mode,\n                    nearest_mode,\n                    roi,\n                    extrapolation_value,\n                    coordinate_transformation_mode,\n                    exclude_outside,\n                    cubic_coeff_a\n                );\n\n                ret_data.append(*item.data.at(0));\n            },\n            Option::None => { break; }\n        }\n    };\n\n    let mut shape = array![];\n    shape.append(ret_data.len());\n\n    TensorTrait::new(output_size, ret_data.span())\n}\n\nfn cartesian(mut arrays: Span<Span<usize>>,) -> Array<Array<usize>> {\n    let mut n = 1;\n    let mut i = arrays.len() - 1;\n    loop {\n        n = n * (*(arrays.at(i))).len();\n        if i == 0 {\n            break;\n        }\n        i -= 1;\n    };\n\n    let mut i = 0;\n    let mut size_arrays = array![];\n    while i != arrays.len() {\n        size_arrays.append((*(arrays.at(i))).len());\n        i += 1;\n    };\n\n    let size_arrays = size_arrays.span();\n    let mut output_arrays = array![];\n    let mut m = n;\n\n    let mut i = 0;\n    while i != arrays.len() {\n        m = m / (*(arrays.at(i))).len();\n        let mut out = repeat(*(arrays.at(i)), m);\n        out = repeat_2(out, size_arrays, i);\n\n        output_arrays.append(out);\n        i += 1;\n    };\n\n    let output_arrays = output_arrays.span();\n\n    let mut i = 0;\n    let mut ret = array![];\n    while i != n {\n        let mut j = 0;\n        let mut x = array![];\n        while j != arrays.len() {\n            x.append(*(output_arrays.at(j)).at(i));\n            j += 1;\n        };\n\n        ret.append(x);\n        i += 1;\n    };\n\n    ret\n}\n\nfn repeat_2(mut array: Array<usize>, size_array: Span<usize>, index: usize) -> Array<usize> {\n    let mut size = array.len();\n    let mut i = 0;\n    while i != index {\n        let mut j = 1;\n        while j != *size_array.at(index - 1 - i) {\n            let mut k = 0;\n            while k != size {\n                array.append(*array.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n\n        size = size * *size_array.at(index - 1 - i);\n        i += 1;\n    };\n\n    array\n}\n\nfn repeat(array: Span<usize>, m: usize,) -> Array<usize> {\n    let mut out = array![];\n    let mut j = 0;\n    while j != array.len() {\n        let mut k = 0;\n        while k != m {\n            out.append(*array.at(j));\n            k += 1;\n        };\n\n        j += 1;\n    };\n\n    out\n}\n\nfn interpolate_nd_with_x<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    data: @Tensor<T>,\n    n: usize,\n    mut scale_factor: Span<T>,\n    mut output_size: Span<usize>,\n    mut x: Span<T>,\n    antialias: Option<usize>,\n    mode: MODE,\n    nearest_mode: Option<NEAREST_MODE>,\n    roi: Option<Tensor<T>>,\n    extrapolation_value: T,\n    coordinate_transformation_mode: Option<TRANSFORMATION_MODE>,\n    exclude_outside: bool,\n    cubic_coeff_a: Option<T>,\n) -> Tensor<T> {\n    if n == 1 {\n        return interpolate_1d_with_x(\n            data,\n            *scale_factor.at(0),\n            *output_size.at(0),\n            *x.at(0),\n            antialias,\n            mode,\n            nearest_mode,\n            roi,\n            extrapolation_value,\n            coordinate_transformation_mode,\n            exclude_outside,\n            cubic_coeff_a\n        );\n    }\n\n    let mut res1d = array![];\n\n    let scale_factor_zero = match scale_factor.pop_front() {\n        Option::Some(item) => { *item },\n        Option::None => core::panic_with_felt252('scale factor empty')\n    };\n    let output_size_zero = match output_size.pop_front() {\n        Option::Some(item) => { *item },\n        Option::None => core::panic_with_felt252('output_size empty')\n    };\n    let x_zero = match x.pop_front() {\n        Option::Some(item) => { *item },\n        Option::None => core::panic_with_felt252('x empty')\n    };\n\n    let reduced_roi = match roi {\n        Option::Some(roi) => {\n            let mut reduced_roi = ArrayTrait::new();\n            let mut reduced_roi_shape = ArrayTrait::new();\n            reduced_roi_shape.append(roi.data.len() - 2);\n\n            let mut i = 1;\n            while i != 2 * n {\n                if i != n {\n                    reduced_roi.append(*roi.data.at(i));\n                }\n\n                i += 1;\n            };\n            Option::Some(TensorTrait::new(reduced_roi_shape.span(), reduced_roi.span()))\n        },\n        Option::None => { Option::None }\n    };\n\n    let mut i = 0;\n    while i != *(*data).shape.at(0) {\n        let data = get_row_n(data, i);\n\n        let mut r = interpolate_nd_with_x(\n            @data,\n            n - 1,\n            scale_factor,\n            output_size,\n            x,\n            antialias,\n            mode,\n            nearest_mode,\n            reduced_roi,\n            extrapolation_value,\n            coordinate_transformation_mode,\n            exclude_outside,\n            cubic_coeff_a\n        );\n\n        loop {\n            match r.data.pop_front() {\n                Option::Some(item) => { res1d.append(*item); },\n                Option::None => { break; }\n            }\n        };\n\n        i += 1;\n    };\n\n    let mut shape = array![];\n    shape.append(res1d.len());\n\n    let res1d = TensorTrait::new(shape.span(), res1d.span());\n\n    let reduced_roi = match roi {\n        Option::Some(roi) => {\n            let mut reduced_roi = array![];\n            let mut reduced_roi_shape = array![];\n\n            reduced_roi_shape.append(2);\n            reduced_roi.append(*roi.data.at(0));\n            reduced_roi.append(*roi.data.at(n));\n\n            Option::Some(TensorTrait::new(reduced_roi_shape.span(), reduced_roi.span()))\n        },\n        Option::None => { Option::None }\n    };\n\n    let a = interpolate_1d_with_x(\n        @res1d,\n        scale_factor_zero,\n        output_size_zero,\n        x_zero,\n        antialias,\n        mode,\n        nearest_mode,\n        reduced_roi,\n        extrapolation_value,\n        coordinate_transformation_mode,\n        exclude_outside,\n        cubic_coeff_a\n    );\n\n    //let mut ret = array![];\n    //let mut shape = array![];\n    //shape.append(2);\n    //ret.append(NumberTrait::zero());\n\n    a\n}\n\nfn get_row_n<T, +TensorTrait<T>, +Copy<T>, +Drop<T>,>(\n    data: @Tensor<T>, index: usize,\n) -> Tensor<T> {\n    let mut output_data = array![];\n    let mut output_shape = array![];\n    let mut stride_output = 1;\n\n    let mut i = 0;\n    while i != (*data).shape.len() {\n        if i != 0 {\n            output_shape.append(*(*data).shape.at(i));\n            stride_output = stride_output * *(*data).shape.at(i);\n        }\n\n        i += 1;\n    };\n\n    let mut i = 0;\n    while i != stride_output {\n        output_data.append(*(*data).data.at(index * stride_output + i));\n        i += 1;\n    };\n\n    TensorTrait::new(output_shape.span(), output_data.span())\n}\n\nfn interpolate_1d_with_x<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    data: @Tensor<T>,\n    scale_factor: T,\n    output_width_int: usize,\n    x: T,\n    antialias: Option<usize>,\n    mode: MODE,\n    nearest_mode: Option<NEAREST_MODE>,\n    roi: Option<Tensor<T>>,\n    extrapolation_value: T,\n    coordinate_transformation_mode: Option<TRANSFORMATION_MODE>,\n    exclude_outside: bool,\n    cubic_coeff_a: Option<T>,\n) -> Tensor<T> {\n    let coordinate_transformation_mode = match coordinate_transformation_mode {\n        Option::Some(coordinate_transformation_mode) => coordinate_transformation_mode,\n        Option::None => { TRANSFORMATION_MODE::HALF_PIXEL },\n    };\n\n    let input_width = (*data).data.len();\n    let output_width = (scale_factor * NumberTrait::new_unscaled((input_width).into(), false));\n\n    let x_ori: T = match coordinate_transformation_mode {\n        TRANSFORMATION_MODE::HALF_PIXEL => {\n            (x + NumberTrait::half()) / scale_factor - NumberTrait::half()\n        },\n        TRANSFORMATION_MODE::ALIGN_CORNERS => {\n            let mut x_ori = NumberTrait::zero();\n            if output_width != NumberTrait::one() {\n                x_ori = x\n                    * (NumberTrait::new_unscaled(input_width.into(), false) - NumberTrait::one())\n                    / (output_width - NumberTrait::one());\n            }\n            x_ori\n        },\n        TRANSFORMATION_MODE::ASYMMETRIC => { x / scale_factor },\n        TRANSFORMATION_MODE::TF_CROP_AND_RESIZE => {\n            let x_ori = match roi {\n                Option::Some(roi) => {\n                    let mut x_ori = if output_width == NumberTrait::one() {\n                        (*roi.data.at(1) - *roi.data.at(0))\n                            * (NumberTrait::new_unscaled(input_width.into(), false)\n                                - NumberTrait::one())\n                            / (NumberTrait::one() + NumberTrait::one())\n                    } else {\n                        x\n                            * (*roi.data.at(1) - *roi.data.at(0))\n                            * (NumberTrait::new_unscaled(input_width.into(), false)\n                                - NumberTrait::one())\n                            / (output_width - NumberTrait::one())\n                    };\n\n                    x_ori = x_ori\n                        + *roi.data.at(0)\n                            * (NumberTrait::new_unscaled(input_width.into(), false)\n                                - NumberTrait::one());\n\n                    if x_ori < NumberTrait::zero()\n                        || x_ori > (NumberTrait::new_unscaled(input_width.into(), false)\n                            - NumberTrait::one()) {\n                        let mut ret = ArrayTrait::new();\n                        let mut shape = ArrayTrait::new();\n                        shape.append(1);\n                        ret.append(extrapolation_value);\n                        return TensorTrait::new(shape.span(), ret.span());\n                    };\n                    x_ori\n                },\n                Option::None => { core::panic_with_felt252('roi cannot be None.') },\n            };\n            x_ori\n        },\n        TRANSFORMATION_MODE::PYTORCH_HALF_PIXEL => {\n            if output_width == NumberTrait::one() {\n                NumberTrait::neg(NumberTrait::<T>::half())\n            } else {\n                (x + NumberTrait::half()) / scale_factor - NumberTrait::half()\n            }\n        },\n        TRANSFORMATION_MODE::HALF_PIXEL_SYMMETRIC => {\n            let adjustement: T = NumberTrait::new_unscaled(output_width_int.into(), false)\n                / output_width;\n            let center: T = NumberTrait::new_unscaled(input_width.into(), false)\n                / (NumberTrait::one() + NumberTrait::one());\n            let offset = center * (NumberTrait::one() - adjustement);\n            offset + (x + NumberTrait::half()) / scale_factor - NumberTrait::half()\n        },\n    };\n\n    let x_ori_int = x_ori.floor();\n\n    let ratio = if x_ori_int.try_into().unwrap() == x_ori {\n        NumberTrait::one()\n    } else {\n        x_ori - x_ori_int.try_into().unwrap()\n    };\n\n    let mut coeffs = match mode {\n        MODE::NEAREST => {\n            let coeffs = match antialias {\n                Option::Some => core::panic_with_felt252('antialias not for mode NEAREST'),\n                Option::None => { nearest_coeffs(ratio, nearest_mode) },\n            };\n            coeffs\n        },\n        MODE::LINEAR => {\n            let coeffs = match antialias {\n                Option::Some(antialias) => {\n                    let coeffs = if antialias == 0 {\n                        linear_coeffs(ratio)\n                    } else {\n                        linear_coeffs_antialias(ratio, scale_factor)\n                    };\n                    coeffs\n                },\n                Option::None => { linear_coeffs(ratio) },\n            };\n            coeffs\n        },\n        MODE::CUBIC => {\n            let coeffs = match antialias {\n                Option::Some => { cubic_coeffs_antialias(ratio, scale_factor, cubic_coeff_a) },\n                Option::None => { cubic_coeffs(ratio, cubic_coeff_a) },\n            };\n            coeffs\n        },\n    };\n\n    let n = coeffs.data.len();\n\n    let (idxes, points) = get_neighbor(x_ori, n, data);\n\n    if exclude_outside {\n        let mut coeffs_exclude_outside: Array<T> = array![];\n        let mut sum = NumberTrait::zero();\n        let mut i = 0;\n        while i != idxes.data.len() {\n            if *idxes.data.at(i) {\n                coeffs_exclude_outside.append(NumberTrait::zero());\n                sum += NumberTrait::zero();\n            } else {\n                coeffs_exclude_outside.append(*coeffs.data.at(i));\n                sum += *coeffs.data.at(i);\n            }\n\n            i += 1;\n        };\n\n        let mut coeff_div: Array<T> = array![];\n        let mut i = 0;\n        while i != n {\n            coeff_div.append(*coeffs_exclude_outside.at(i) / sum);\n            i += 1;\n        };\n\n        coeffs = TensorTrait::new(coeffs.shape, coeff_div.span());\n    }\n\n    TensorTrait::matmul(@coeffs, @points)\n}\n\nfn get_neighbor<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut x: T, n: usize, data: @Tensor<T>,\n) -> (Tensor<bool>, Tensor<T>) {\n    let pad_width: usize = NumberTrait::ceil(\n        NumberTrait::new_unscaled(n.into(), false)\n            / (NumberTrait::<T>::one() + NumberTrait::<T>::one())\n    )\n        .try_into()\n        .unwrap();\n    let mut padded = array![];\n\n    let mut i = 0;\n    while i != pad_width {\n        padded.append(*(*data).data.at(0));\n        i += 1;\n    };\n\n    let mut i = 0;\n    while i != (*data).data.len() {\n        padded.append(*(*data).data.at(i));\n        i += 1;\n    };\n\n    let mut i = 0;\n    while i != pad_width {\n        padded.append(*(*data).data.at((*data).data.len() - 1));\n        i += 1;\n    };\n\n    x = x + NumberTrait::new_unscaled(pad_width.into(), false);\n\n    let mut idxes = get_neighbor_idxes(x, n, padded.len());\n\n    let mut idxes_centered = array![];\n    let mut ret = array![];\n    let mut i = 0;\n    while i != idxes.data.len() {\n        ret.append(*padded.at(*idxes.data.at(i)));\n\n        if *idxes.data.at(i) >= pad_width {\n            if (*idxes.data.at(i) - pad_width) >= (*data).data.len() {\n                idxes_centered.append(true);\n            } else {\n                idxes_centered.append(false);\n            }\n        } else {\n            idxes_centered.append(true);\n        }\n\n        i += 1;\n    };\n\n    let mut shape = array![];\n    shape.append(idxes.data.len());\n\n    (\n        TensorTrait::new(shape.span(), idxes_centered.span()),\n        TensorTrait::new(shape.span(), ret.span())\n    )\n}\n\nfn get_neighbor_idxes<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut x: T, n: usize, limit: usize,\n) -> Tensor<usize> {\n    let _pad_width: usize = NumberTrait::<\n        T\n    >::ceil(\n        NumberTrait::new_unscaled(n.into(), false)\n            / (NumberTrait::<T>::one() + NumberTrait::<T>::one())\n    )\n        .try_into()\n        .unwrap();\n    let mut idxes = array![];\n\n    if n % 2 == 0 {\n        let (mut i_low, mut i_high) = if x < NumberTrait::zero() {\n            (0, 1)\n        } else {\n            (NumberTrait::floor(x).try_into().unwrap(), NumberTrait::ceil(x).try_into().unwrap())\n        };\n\n        if i_high >= limit {\n            i_low = limit - 2;\n            i_high = limit - 1;\n        }\n\n        if i_low == i_high {\n            if i_low == 0 {\n                i_high = i_high + 1;\n            } else {\n                i_low = i_low - 1;\n            }\n        }\n\n        let mut i = 0;\n        while i != n / 2 {\n            if i_low - i < 0 {\n                idxes.append(i_high + i);\n                i_high += 1;\n            } else {\n                idxes.append(i_low - i);\n            }\n            if i_high + i >= limit {\n                i_low -= 1;\n                idxes.append(i_low - i);\n            } else {\n                idxes.append(i_high + i);\n            }\n\n            i += 1;\n        }\n    } else {\n        core::panic_with_felt252('MUST BE EVEN');\n    }\n\n    idxes = bubble_sort::bubble_sort_elements(idxes, true);\n\n    let mut shape = array![];\n    shape.append(n);\n\n    TensorTrait::new(shape.span(), idxes.span())\n}\n\nfn linear_coeffs<\n    T,\n    MAG,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +TensorTrait<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +Sub<T>\n>(\n    mut ratio: T\n) -> Tensor<T> {\n    let mut ret = array![];\n    let mut shape = array![];\n    shape.append(2);\n    ret.append(NumberTrait::one() - ratio);\n    ret.append(ratio);\n\n    TensorTrait::new(shape.span(), ret.span())\n}\n\nfn linear_coeffs_antialias<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut ratio: T, scale: T\n) -> Tensor<T> {\n    let scale = NumberTrait::min(scale, NumberTrait::one());\n    let start = (NumberTrait::floor(NumberTrait::neg(NumberTrait::one()) / scale)\n        + NumberTrait::one());\n    let footprint = (NumberTrait::one() + NumberTrait::one())\n        - (NumberTrait::one() + NumberTrait::one()) * start;\n\n    let mut coeffs: Array<T> = array![];\n    let mut sum = NumberTrait::zero();\n\n    // arange and clip + compute sum\n    let mut i = start;\n    while i != start + footprint {\n        let value = NumberTrait::one() - NumberTrait::abs((i - ratio) * scale);\n\n        if value < NumberTrait::zero() {\n            coeffs.append(NumberTrait::zero());\n        } else if value > NumberTrait::one() {\n            coeffs.append(NumberTrait::one());\n            sum += NumberTrait::one();\n        } else {\n            coeffs.append(value);\n            sum += value;\n        }\n\n        i += NumberTrait::one();\n    };\n\n    let n = coeffs.len();\n\n    let mut coeff_div: Array<T> = array![];\n    let mut i = 0;\n    while i != n {\n        coeff_div.append(*coeffs.at(i) / sum);\n        i += 1;\n    };\n\n    let mut shape = array![];\n    shape.append(n);\n\n    TensorTrait::new(shape.span(), coeff_div.span())\n}\n\nfn cubic_coeffs<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut ratio: T, A: Option<T>\n) -> Tensor<T> {\n    let one = NumberTrait::one();\n    let two = one + NumberTrait::one();\n    let three = two + NumberTrait::one();\n    let four = three + NumberTrait::one();\n    let five = four + NumberTrait::one();\n    let eigth = four + four;\n\n    let A = match A {\n        Option::Some(A) => A,\n        Option::None => { NumberTrait::neg(three / four) },\n    };\n\n    let mut coeffs = array![];\n    let mut shape = array![];\n\n    coeffs\n        .append(\n            ((A * (ratio + one) - five * A) * (ratio + one) + eigth * A) * (ratio + one) - four * A\n        );\n    coeffs.append(((A + two) * ratio - (A + three)) * ratio * ratio + one);\n    coeffs.append(((A + two) * (one - ratio) - (A + three)) * (one - ratio) * (one - ratio) + one);\n    coeffs\n        .append(\n            ((A * ((one - ratio) + one) - five * A) * ((one - ratio) + one) + eigth * A)\n                * ((one - ratio) + one)\n                - four * A\n        );\n\n    shape.append(4);\n\n    TensorTrait::new(shape.span(), coeffs.span())\n}\n\nfn cubic_coeffs_antialias<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +TryInto<T, usize>,\n    +Into<usize, MAG>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut ratio: T, scale: T, A: Option<T>\n) -> Tensor<T> {\n    let one = NumberTrait::one();\n    let two = one + NumberTrait::one();\n    let three = two + NumberTrait::one();\n    let four = three + NumberTrait::one();\n\n    let scale = NumberTrait::min(scale, NumberTrait::one());\n\n    let i_start = NumberTrait::floor(NumberTrait::neg(two) / scale) + NumberTrait::one();\n    let i_end = two - i_start;\n    assert(i_end > i_start, 'i_end must be greater');\n\n    let A = match A {\n        Option::Some(A) => A,\n        Option::None => { NumberTrait::neg(three / four) },\n    };\n\n    let mut coeffs = array![];\n    let mut sum = NumberTrait::zero();\n\n    let mut i = i_start;\n    while i != i_end {\n        let value = compute_coeff(scale * (i - ratio), A);\n        coeffs.append(value);\n        sum += value;\n\n        i += NumberTrait::one();\n    };\n\n    let n = coeffs.len();\n\n    let mut coeff_div: Array<T> = array![];\n    let mut i = 0;\n    while i != n {\n        coeff_div.append(*coeffs.at(i) / sum);\n        i += 1;\n    };\n\n    let mut shape = array![];\n    shape.append(n);\n\n    TensorTrait::new(shape.span(), coeff_div.span())\n}\n\nfn compute_coeff<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut x: T, A: T\n) -> T {\n    let one = NumberTrait::one();\n    let two = one + NumberTrait::one();\n    let three = two + NumberTrait::one();\n    let four = three + NumberTrait::one();\n    let five = four + NumberTrait::one();\n    let eigth = four + four;\n\n    x = x.abs();\n    let mut x_2 = x * x;\n    let mut x_3 = x * x_2;\n    if x <= one {\n        return (A + two) * x_3 - (A + three) * x_2 + one;\n    }\n    if x < two {\n        return A * x_3 - five * A * x_2 + eigth * A * x - four * A;\n    }\n\n    NumberTrait::zero()\n}\n\nfn nearest_coeffs<\n    T,\n    MAG,\n    +TensorTrait<T>,\n    +NumberTrait<T, MAG>,\n    +PartialOrd<T>,\n    +PartialEq<T>,\n    +Copy<T>,\n    +Drop<T>,\n    +AddEq<T>,\n    +Add<T>,\n    +Div<T>,\n    +Mul<T>,\n    +Sub<T>,\n>(\n    mut ratio: T, nearest_mode: Option<NEAREST_MODE>\n) -> Tensor<T> {\n    let nearest_mode = match nearest_mode {\n        Option::Some(nearest_mode) => { nearest_mode },\n        Option::None => { NEAREST_MODE::ROUND_PREFER_FLOOR },\n    };\n\n    let mut ret = array![];\n    let mut shape = array![];\n    shape.append(2);\n\n    // CHECK SI C'EST UNE CONDITION ASSEZ GENERALE\n    if ratio == NumberTrait::one() {\n        ret.append(NumberTrait::zero());\n        ret.append(NumberTrait::one());\n        return TensorTrait::new(shape.span(), ret.span());\n    }\n\n    match nearest_mode {\n        NEAREST_MODE::ROUND_PREFER_FLOOR => {\n            if ratio <= NumberTrait::half() {\n                ret.append(NumberTrait::one());\n                ret.append(NumberTrait::zero());\n                return TensorTrait::new(shape.span(), ret.span());\n            } else {\n                ret.append(NumberTrait::zero());\n                ret.append(NumberTrait::one());\n                return TensorTrait::new(shape.span(), ret.span());\n            }\n        },\n        NEAREST_MODE::ROUND_PREFER_CEIL => {\n            if ratio < NumberTrait::half() {\n                ret.append(NumberTrait::one());\n                ret.append(NumberTrait::zero());\n                return TensorTrait::new(shape.span(), ret.span());\n            } else {\n                ret.append(NumberTrait::zero());\n                ret.append(NumberTrait::one());\n                return TensorTrait::new(shape.span(), ret.span());\n            }\n        },\n        NEAREST_MODE::FLOOR => {\n            ret.append(NumberTrait::one());\n            ret.append(NumberTrait::zero());\n            return TensorTrait::new(shape.span(), ret.span());\n        },\n        NEAREST_MODE::CEIL => {\n            ret.append(NumberTrait::zero());\n            ret.append(NumberTrait::one());\n            return TensorTrait::new(shape.span(), ret.span());\n        },\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/round.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn round<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl FTensor: TensorTrait<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).round()); },\n            Option::None => { break; }\n        };\n    };\n\n    return TensorTrait::new(self.shape, result.span());\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/scatter.cairo",
        "content": "use alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\nuse core::dict::Felt252DictTrait;\nuse core::nullable::{nullable_from_box, match_nullable, FromNullableResult};\n\n/// Cf: TensorTrait::scatter docstring\nfn scatter<\n    T,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TAddEq: AddEq<T>,\n    impl TMulEq: MulEq<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n>(\n    self: @Tensor<T>,\n    updates: Tensor<T>,\n    indices: Tensor<usize>,\n    axis: Option<usize>,\n    reduction: Option<usize>\n) -> Tensor<T> {\n    let mut axis = match axis {\n        Option::Some(val) => val,\n        Option::None => 0\n    };\n\n    let reduction = match reduction {\n        Option::Some(val) => val,\n        Option::None => 'none'\n    };\n\n    let data_rank = (*self.shape).len();\n    let indices_rank = (indices.shape).len();\n    let updates_rank = (updates.shape).len();\n\n    assert((data_rank == updates_rank) & (updates_rank == indices_rank), 'must be same rank');\n    let data_shape = *self.shape;\n    let ind_max = indices.data.max().unwrap();\n    assert(ind_max < *data_shape.at(axis), 'index is out of bound');\n\n    let data_shape = *self.shape;\n    let mut indices_shape = indices.shape;\n    let updates_shape = updates.shape;\n    assert(\n        (*indices_shape[0] == *updates_shape[0]) & (*indices_shape[1] == *updates_shape[1]),\n        'shape must be same'\n    );\n\n    let mut output_data = array![];\n    let mut data_indices = indices.data;\n    let mut data_updates = updates.data;\n    let mut indices_updates: Felt252Dict<usize> = Default::default();\n    let mut indices_updates_reduction: Felt252Dict<Nullable<Span<usize>>> = Default::default();\n\n    let mut data_shape_copy = data_shape;\n    let mut indices_shape_copy = indices_shape;\n    *data_shape_copy.pop_front().unwrap();\n    *indices_shape_copy.pop_front().unwrap();\n\n    let mut indices_loop: usize = 1;\n    let mut data_loop: usize = 1;\n\n    if (axis == 0) {\n        loop {\n            match indices_shape_copy.pop_front() {\n                Option::Some(val) => { indices_loop *= *val; },\n                Option::None => { break; }\n            };\n        };\n\n        loop {\n            match data_shape_copy.pop_front() {\n                Option::Some(val) => { data_loop *= *val; },\n                Option::None => { break; }\n            };\n        };\n    }\n\n    let mut transpose = false;\n    if ((data_rank > 2) & (axis == 1)) {\n        let index = indices.transpose(axes: array![0, 2, 1].span());\n        let update = updates.transpose(axes: array![0, 2, 1].span());\n        data_indices = index.data;\n        data_updates = update.data;\n        indices_shape = index.shape;\n        axis = 2;\n        transpose = true;\n    }\n\n    if (axis == (data_rank - 1)) {\n        data_loop = *data_shape_copy.pop_back().unwrap();\n        indices_loop = *indices_shape_copy.pop_back().unwrap();\n    }\n\n    let mut total_count: usize = 0;\n    let mut shift = 0;\n\n    loop {\n        let mut result: usize = 0;\n\n        match data_indices.pop_front() {\n            Option::Some(val) => {\n                let value = total_count + 1;\n\n                if (axis == 0) {\n                    let column = total_count % indices_loop;\n                    result = (*val * data_loop) + (column);\n                    if ((result % *data_shape.at(data_rank - 1)) != total_count % *indices_shape\n                        .at(data_rank - 1)) {\n                        result +=\n                            (*data_shape.at(data_rank - 1) - *indices_shape.at(data_rank - 1));\n                    }\n                }\n\n                if (axis == (data_rank - 1)) {\n                    let mut row = total_count / indices_loop;\n                    if ((data_rank > 2) & (row % *data_shape.at(1) >= *indices_shape.at(1))) {\n                        shift = (*data_shape.at(1) - *indices_shape.at(1));\n                    }\n\n                    result = *val + (data_loop * (row + shift));\n                }\n\n                if (reduction == 'none') {\n                    indices_updates.insert(result.into(), value.into());\n                } else {\n                    let mut arr = array![];\n\n                    let val = indices_updates_reduction.get(result.into());\n                    let mut a = ArrayTrait::new();\n                    let mut span = match match_nullable(val) {\n                        FromNullableResult::Null(()) => a.span(),\n                        FromNullableResult::NotNull(val) => val.unbox(),\n                    };\n\n                    loop {\n                        match span.pop_front() {\n                            Option::Some(val) => { arr.append(*val); },\n                            Option::None => { break; }\n                        };\n                    };\n\n                    arr.append(total_count);\n                    indices_updates_reduction\n                        .insert(result.into(), nullable_from_box(BoxTrait::new(arr.span())));\n                }\n\n                total_count += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut data = *self.data;\n    let mut i: usize = 0;\n    loop {\n        match data.pop_front() {\n            Option::Some(val) => {\n                if (reduction == 'none') {\n                    let value = indices_updates.get(i.into());\n                    if (value == 0) {\n                        output_data.append(*val);\n                    } else {\n                        let data_value = data_updates[value - 1];\n                        output_data.append(*data_value);\n                    }\n                } else {\n                    let value = indices_updates_reduction.get(i.into());\n                    let mut a = array![];\n                    let mut span = match match_nullable(value) {\n                        FromNullableResult::Null(()) => a.span(),\n                        FromNullableResult::NotNull(value) => value.unbox(),\n                    };\n\n                    if (span.len() == 0) {\n                        output_data.append(*val);\n                    } else {\n                        // let mut result = *data_updates.at(*span.pop_front().unwrap());\n                        let mut result = *val;\n\n                        if (reduction == 'add') {\n                            loop {\n                                match span.pop_front() {\n                                    Option::Some(val) => { result += *data_updates[*val]; },\n                                    Option::None => { break; }\n                                };\n                            };\n\n                            output_data.append(result);\n                        }\n\n                        if (reduction == 'mul') {\n                            loop {\n                                match span.pop_front() {\n                                    Option::Some(val) => { result *= *data_updates[*val]; },\n                                    Option::None => { break; }\n                                };\n                            };\n\n                            output_data.append(result);\n                        }\n\n                        if (reduction == 'max') {\n                            loop {\n                                match span.pop_front() {\n                                    Option::Some(val) => {\n                                        let holder = *data_updates[*val];\n                                        if (holder > result) {\n                                            result = holder;\n                                        }\n                                    },\n                                    Option::None => { break; }\n                                };\n                            };\n\n                            output_data.append(result);\n                        }\n\n                        if (reduction == 'min') {\n                            loop {\n                                match span.pop_front() {\n                                    Option::Some(val) => {\n                                        let holder = *data_updates[*val];\n                                        if (holder < result) {\n                                            result = holder;\n                                        }\n                                    },\n                                    Option::None => { break; }\n                                };\n                            };\n\n                            output_data.append(result);\n                        }\n                    }\n                }\n\n                i += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_tensor = TensorTrait::<T>::new(*self.shape, output_data.span());\n\n    if transpose {\n        output_tensor = output_tensor.transpose(axes: array![0, 2, 1].span())\n    }\n\n    output_tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/scatter_nd.cairo",
        "content": "use core::nullable::{nullable_from_box, match_nullable, FromNullableResult};\n\nuse alexandria_data_structures::array_ext::SpanTraitExt;\n\nuse orion::numbers::NumberTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n\n/// Cf: TensorTrait::scatter_nd docstring\nfn scatter_nd<\n    T,\n    impl TTensorTrait: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TAdd: Add<T>,\n    impl TMul: Mul<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n>(\n    self: @Tensor<T>, updates: Tensor<T>, indices: Tensor<usize>, reduction: Option<usize>\n) -> Tensor<T> {\n    let reduction = match reduction {\n        Option::Some(val) => val,\n        Option::None => 'none'\n    };\n\n    let data_rank = (*self.shape).len();\n    let mut data_shape = *self.shape;\n    let mut indices_shape = indices.shape;\n    let updates_shape = updates.shape;\n\n    let indices_last_axis = indices_shape.pop_back().unwrap();\n    assert(*indices_last_axis <= data_rank, 'must be <= data rank');\n\n    let ind_max = indices.data.max().unwrap();\n    if (data_rank > 1) {\n        assert(ind_max < data_rank, 'index is out of bound');\n    }\n\n    let mut batch_dims_shape = array![];\n    let mut ind: usize = 0;\n\n    loop {\n        match indices_shape.pop_front() {\n            Option::Some(val) => { batch_dims_shape.append(*val); },\n            Option::None => { break; }\n        };\n    };\n\n    let mut data_shape_clone = data_shape.clone();\n    loop {\n        match data_shape_clone.pop_front() {\n            Option::Some(val) => {\n                if (ind >= *indices_last_axis) {\n                    batch_dims_shape.append(*val);\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut ind: usize = 0;\n    loop {\n        match batch_dims_shape.pop_front() {\n            Option::Some(val) => { assert(val == *updates_shape[ind], 'must be same'); },\n            Option::None => { break; }\n        };\n    };\n\n    let mut data_indices = indices.data;\n    let mut data_updates = updates.data;\n\n    let mut data_shape_clone = data_shape.clone();\n    let mut indexer = 1;\n    let data_shape_first = data_shape_clone.pop_front();\n    if data_rank >= 1 {\n        loop {\n            match data_shape_clone.pop_front() {\n                Option::Some(val) => { indexer *= *val; },\n                Option::None => { break; }\n            };\n        }\n    }\n\n    let mut updates_index_dict: Felt252Dict<u32> = Default::default();\n    let mut dict_ind: usize = 1;\n    loop {\n        match data_indices.pop_front() {\n            Option::Some(val) => {\n                updates_index_dict.insert((*val).into(), dict_ind);\n                dict_ind += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_data: Array<T> = array![];\n    let mut data = *self.data;\n    let mut index: usize = 0;\n    let mut inner_index: usize = 0;\n    let num = *data_shape_first.unwrap();\n    while index != num {\n        let comp_index = updates_index_dict.get(index.into());\n\n        if comp_index == 0 {\n            loop {\n                if (inner_index == indexer) {\n                    inner_index = 0;\n                    break;\n                }\n                let val = *data.at((index * indexer) + inner_index);\n                output_data.append(val);\n                inner_index += 1;\n            };\n        } else {\n            loop {\n                if (inner_index == indexer) {\n                    inner_index = 0;\n                    break;\n                }\n                if (reduction == 'none') {\n                    let val = data_updates.at(((comp_index - 1) * indexer) + inner_index);\n                    output_data.append(*val);\n                }\n                if (reduction == 'add') {\n                    let val = data_updates.at(((comp_index - 1) * indexer) + inner_index);\n                    let data_val = *data.at((index * indexer) + inner_index);\n                    output_data.append(*val + data_val);\n                }\n                if (reduction == 'mul') {\n                    let val = data_updates.at(((comp_index - 1) * indexer) + inner_index);\n                    let data_val = *data.at((index * indexer) + inner_index);\n                    output_data.append((*val) * data_val);\n                }\n                if (reduction == 'max') {\n                    let val = data_updates.at(((comp_index - 1) * indexer) + inner_index);\n                    let data_val = *data.at((index * indexer) + inner_index);\n                    if (*val > data_val) {\n                        output_data.append(*val);\n                    } else {\n                        output_data.append(data_val);\n                    }\n                }\n                if (reduction == 'min') {\n                    let val = data_updates.at(((comp_index - 1) * indexer) + inner_index);\n                    let data_val = *data.at((index * indexer) + inner_index);\n                    if (*val > data_val) {\n                        output_data.append(data_val);\n                    } else {\n                        output_data.append(*val);\n                    }\n                }\n                inner_index += 1;\n            }\n        }\n        index += 1;\n    };\n\n    let mut output_tensor = TensorTrait::<T>::new(*self.shape, output_data.span());\n\n    output_tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/shrink.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::shrink docstring\nfn shrink<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mut self: Tensor<T>, bias: Option<T>, lambd: Option<T>\n) -> Tensor<T> {\n    let bias: T = if bias.is_some() {\n        bias.unwrap()\n    } else {\n        NumberTrait::zero()\n    };\n\n    let lambd: T = if lambd.is_some() {\n        lambd.unwrap()\n    } else {\n        NumberTrait::half()\n    };\n\n    let mut data_result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => {\n                if (*item) < lambd.neg() {\n                    let mut y = NumberTrait::add(*item, bias);\n                    data_result.append(y);\n                } else if (*item) > lambd {\n                    let mut y = NumberTrait::sub(*item, bias);\n                    data_result.append(y);\n                } else {\n                    data_result.append(NumberTrait::zero());\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, data_result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/sign.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn sign<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl FTensor: TensorTrait<T>,\n    impl FCopy: Copy<T>,\n    impl FDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).sign()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/sin.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::sin docstring\nfn sin<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).sin()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/sinh.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::sinh docstring\nfn sinh<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).sinh()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/sqrt.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\nfn sqrt<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).sqrt()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/tanh.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::numbers::fixed_point::core::FixedTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\n\n/// Cf: TensorTrait::tanh docstring\nfn tanh<\n    T,\n    MAG,\n    impl TNumberTrait: NumberTrait<T, MAG>,\n    impl TTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n>(\n    mut self: Tensor<T>\n) -> Tensor<T> {\n    let mut result: Array<T> = array![];\n\n    loop {\n        match self.data.pop_front() {\n            Option::Some(item) => { result.append((*item).tanh()); },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(self.shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/where.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::where docstring\nfn where<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TFTensor: TensorTrait<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    self: @Tensor<T>, x: @Tensor<T>, y: @Tensor<T>\n) -> Tensor<T> {\n    let xy_shape = broadcast_shape(*x.shape, *y.shape);\n    let broadcasted_shape = broadcast_shape(*self.shape, xy_shape);\n    let mut result: Array<T> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_cond = broadcast_index_mapping(*self.shape, indices_broadcasted);\n        let indices_x = broadcast_index_mapping(*x.shape, indices_broadcasted);\n        let indices_y = broadcast_index_mapping(*y.shape, indices_broadcasted);\n\n        let res = NumberTrait::where(\n            *(*self.data)[indices_cond], *(*x.data)[indices_x], *(*y.data)[indices_y]\n        );\n        result.append(res);\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/math/xor.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::core::{Tensor, TensorTrait, unravel_index};\nuse orion::operators::tensor::helpers::{\n    broadcast_shape, broadcast_index_mapping, len_from_shape, check_compatibility\n};\n\n/// Cf: TensorTrait::xor docstring\nfn xor<\n    T,\n    MAG,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl UsizeFTensor: TensorTrait<usize>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    y: @Tensor<T>, z: @Tensor<T>\n) -> Tensor<usize> {\n    let broadcasted_shape = broadcast_shape(*y.shape, *z.shape);\n    let mut result: Array<usize> = array![];\n\n    let num_elements = len_from_shape(broadcasted_shape);\n\n    let mut n: usize = 0;\n    while n != num_elements {\n        let indices_broadcasted = unravel_index(n, broadcasted_shape);\n\n        let indices_self = broadcast_index_mapping(*y.shape, indices_broadcasted);\n        let indices_other = broadcast_index_mapping(*z.shape, indices_broadcasted);\n\n        if NumberTrait::xor(*(*y.data)[indices_self], *(*z.data)[indices_other]) {\n            result.append(1);\n        } else {\n            result.append(0);\n        }\n\n        n += 1;\n    };\n\n    TensorTrait::new(broadcasted_shape, result.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/ml.cairo",
        "content": "mod array_feature_extractor;\nmod label_encoder;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/ml/array_feature_extractor.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\n\n/// Cf: TensorTrait::array_feature_extractor docstring\nfn array_feature_extractor<\n    T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    self: Tensor<T>, indices: Tensor<usize>\n) -> Tensor<T> {\n    assert(indices.shape.len() == 1, 'Indices must be a 1D tensor');\n\n    if self.shape.len() == 1 {\n        return process_1D_tensor(self, indices);\n    }\n\n    let (output_shape, total_elements) = calculate_output_shape::<T>(self.shape, indices);\n\n    let output_data = calculate_output_data::<T>(self, indices, total_elements);\n\n    TensorTrait::new(output_shape.span(), output_data.span())\n}\n\n\nfn process_1D_tensor<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: Tensor<T>, indices: Tensor<usize>\n) -> Tensor<T> {\n    let mut output_data: Array<T> = array![];\n\n    let mut indices_values: Span<usize> = indices.data;\n    let self_len = *self.shape.at(0);\n    loop {\n        match indices_values.pop_front() {\n            Option::Some(current_indices_value) => {\n                assert(*current_indices_value < self_len, 'Indices out of range');\n                let mut current_data_value = *self.data.at(*current_indices_value);\n                output_data.append(current_data_value);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(indices.shape, output_data.span())\n}\n\n\nfn calculate_output_shape<\n    T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>\n>(\n    input_shape: Span<usize>, indices: Tensor<usize>\n) -> (Array<usize>, usize) {\n    let mut total_elements: usize = 1;\n    let mut output_shape: Array<usize> = array![];\n\n    let mut input_shape_copy = input_shape;\n    let mut input_shape_counter: usize = 0;\n    let breaker = input_shape.len() - 2;\n    loop {\n        match input_shape_copy.pop_front() {\n            Option::Some(current_shape_value) => {\n                if input_shape_counter > breaker {\n                    break;\n                }\n                output_shape.append(*current_shape_value);\n                total_elements = total_elements * *current_shape_value;\n\n                input_shape_counter += 1;\n            },\n            Option::None => { break; }\n        };\n    };\n\n    output_shape.append(indices.data.len());\n\n    (output_shape, total_elements)\n}\n\n\nfn calculate_output_data<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    self: Tensor<T>, indices: Tensor<usize>, total_elements: usize\n) -> Array<T> {\n    let last_tensor_axis: usize = *self.shape.at(self.shape.len() - 1);\n\n    let mut output_data: Array<T> = array![];\n\n    let strides: Span<usize> = TensorTrait::stride(@self);\n\n    let mut element_counter: usize = 0;\n    let mut stride_l2 = *strides.at(strides.len() - 2);\n    let mut stride_l1 = *strides.at(strides.len() - 1);\n    while element_counter != total_elements {\n        let mut base_index = if strides.len() > 1 {\n            element_counter * stride_l2\n        } else {\n            0\n        };\n\n        let mut indices_values = indices.data;\n        loop {\n            match indices_values.pop_front() {\n                Option::Some(current_indices_value) => {\n                    assert(*current_indices_value < last_tensor_axis, 'Indices out of range');\n                    let mut flat_index = base_index + *current_indices_value * (stride_l1);\n\n                    let mut current_data_value = *self.data.at(flat_index);\n                    output_data.append(current_data_value);\n                },\n                Option::None => { break; }\n            };\n        };\n\n        element_counter += 1;\n    };\n\n    output_data\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/ml/label_encoder.cairo",
        "content": "use core::array::ArrayTrait;\nuse core::option::OptionTrait;\nuse core::array::SpanTrait;\n\nuse orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::numbers::NumberTrait;\n\nuse core::dict::Felt252DictTrait;\nuse core::nullable::{nullable_from_box, match_nullable, FromNullableResult};\nuse core::debug::PrintTrait;\n\nuse core::traits::Into;\nuse core::traits::TryInto;\n/// Cf: TensorTrait::label_encoder docstring\nfn label_encoder<\n    T, +Drop<T>, +Copy<T>, +AddEq<T>, +TensorTrait<T>, +PartialOrd<T>, +Into<T, felt252>,\n>(\n    // self: @Tensor<T>, default: T, keys: Array<T>, values: Array<T>\n    self: @Tensor<T>,\n    default_list: Option<Span<T>>,\n    default_tensor: Option<Tensor<T>>,\n    keys: Option<Span<T>>,\n    keys_tensor: Option<Tensor<T>>,\n    values: Option<Span<T>>,\n    values_tensor: Option<Tensor<T>>,\n) -> Tensor<T> {\n    let mut default = match default_list {\n        Option::Some(value) => value,\n        Option::None => {\n            match default_tensor {\n                Option::Some(value) => value.data,\n                Option::None => { core::panic_with_felt252('None') },\n            }\n        }\n    };\n\n    let default = match default.pop_front() {\n        Option::Some(value) => *value,\n        Option::None => { core::panic_with_felt252('None') }\n    };\n\n    let mut keys = match keys {\n        Option::Some(value) => { value },\n        Option::None => {\n            match keys_tensor {\n                Option::Some(value) => { value.data },\n                Option::None => { core::panic_with_felt252('None') },\n            }\n        }\n    };\n\n    let mut values = match values {\n        Option::Some(value) => { value },\n        Option::None => {\n            match values_tensor {\n                Option::Some(value) => { value.data },\n                Option::None => { core::panic_with_felt252('None') },\n            }\n        }\n    };\n\n    assert(keys.len() == values.len(), 'keys must be eq to values');\n    let mut key_value_dict: Felt252Dict<Nullable<T>> = Default::default();\n    let mut output_data = ArrayTrait::<T>::new();\n\n    loop {\n        let key = match keys.pop_front() {\n            Option::Some(key) => key,\n            Option::None => { break; }\n        };\n        let value = match values.pop_front() {\n            Option::Some(value) => value,\n            Option::None => { break; }\n        };\n\n        key_value_dict.insert((*key).into(), nullable_from_box(BoxTrait::new(*value)));\n    };\n\n    let mut data = *self.data;\n    loop {\n        match data.pop_front() {\n            Option::Some(val) => {\n                let value = *val;\n                let res = key_value_dict.get(value.into());\n\n                let mut span = match match_nullable(res) {\n                    FromNullableResult::Null => default,\n                    FromNullableResult::NotNull(res) => res.unbox(),\n                };\n                output_data.append(span);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    let mut output_tensor = TensorTrait::<T>::new(*self.shape, output_data.span());\n    return output_tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization.cairo",
        "content": "mod quantize_linear;\nmod dynamic_quantize_linear;\nmod dequantize_linear;\nmod qlinear_matmul;\nmod qlinear_concat;\nmod qlinear_add;\nmod qlinear_mul;\nmod qlinear_leakyrelu;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/dequantize_linear.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::helpers::check_compatibility;\nuse orion::utils::saturate;\n\n/// Cf: PerfomanceTrait::dequantize_linear docstring\nfn dequantize_linear<\n    Q,\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl QIntoT: Into<Q, T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TDrop: Drop<T>,\n    impl TCopy: Copy<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>\n>(\n    x: @Tensor<Q>, x_scale: @Tensor<T>, x_zero_point: @Tensor<T>\n) -> Tensor::<T> {\n    if (*x_scale.data).len() == 1 && (*x_zero_point.data).len() == 1 {\n        dequantize_element_wise(*x, *x_scale.data[0], *x_zero_point.data[0])\n    } else {\n        check_compatibility(*x.shape, *x_scale.shape);\n        check_compatibility(*x.shape, *x_zero_point.shape);\n        check_compatibility(*x_scale.shape, *x_zero_point.shape);\n\n        dequantize_per_axis(@(*x).into(), x_scale, x_zero_point)\n    }\n}\n\nfn dequantize_per_axis<\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    x: @Tensor<T>, x_scale: @Tensor<T>, x_zero_point: @Tensor<T>\n) -> Tensor::<T> {\n    (*x - *x_zero_point) * *x_scale\n}\n\nfn dequantize_element_wise<\n    Q,\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl QIntoT: Into<Q, T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TDrop: Drop<T>,\n    impl TCopy: Copy<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>\n>(\n    mut x: Tensor::<Q>, x_scale: T, x_zero_point: T\n) -> Tensor::<T> {\n    let mut result_data: Array<T> = array![];\n\n    loop {\n        match x.data.pop_front() {\n            Option::Some(item) => {\n                let dequantized = dequantize(*item, x_scale, x_zero_point);\n                result_data.append(dequantized);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(x.shape, result_data.span())\n}\n\nfn dequantize<\n    Q, T, impl QIntoT: Into<Q, T>, impl TSub: Sub<T>, impl TMul: Mul<T>, impl TDrop: Drop<T>\n>(\n    x: Q, x_scale: T, x_zero_point: T\n) -> T {\n    (x.into() - x_zero_point) * x_scale\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/dynamic_quantize_linear.cairo",
        "content": "use orion::numbers::NumberTrait;\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::saturate;\n\nfn dynamic_quantize_linear<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TPartialEq: PartialEq<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    x: @Tensor<T>, min: T, max: T, zero: T, one: T\n) -> (Tensor<Q>, Tensor<T>, Tensor<T>) {\n    // y_scale = (maximum(0, max(x)) - minimum(0, min(x))) / (qmax - qmin)\n    let mut x_max: T = x.max_in_tensor();\n    let mut x_min: T = x.min_in_tensor();\n    if x_max < zero {\n        x_max = zero;\n    }\n    if x_min > zero {\n        x_min = zero\n    }\n\n    // scale = max == min ? 1.0f : (max - min) / float(qmax - qmin);\n    let mut y_scale_values = ArrayTrait::new();\n    let y_scale_value: T = (x_max - x_min) / (max - min);\n    if x_max == x_min {\n        y_scale_values.append(one);\n    } else {\n        y_scale_values.append(y_scale_value);\n    }\n\n    let mut y_scale_tensor_shape: Array<u32> = array![];\n    y_scale_tensor_shape.append(y_scale_values.len());\n\n    let y_scale = TensorTrait::<\n        T\n    >::new(shape: y_scale_tensor_shape.span(), data: y_scale_values.span(),);\n\n    // intermediate_zero_point = qmin - min(x)/y_scale\n    let intermediate_zero_point: T = min - x_min / y_scale_value;\n\n    // y_zero_point = cast(round(saturate(itermediate_zero_point)))\n    let mut y_zero_point_value: T = saturate(min, max, intermediate_zero_point);\n    let mut y_zero_point_values: Array<T> = array![];\n    y_zero_point_values.append(y_zero_point_value);\n\n    let mut y_zero_point_tensor_shape: Array<u32> = array![];\n    y_zero_point_tensor_shape.append(y_zero_point_values.len());\n\n    let mut y_zero_point_values: Array<T> = array![];\n    y_zero_point_values.append(y_zero_point_value);\n    let mut y_zero_point = TensorTrait::<\n        T\n    >::new(shape: y_zero_point_tensor_shape.span(), data: y_zero_point_values.span(),);\n    // y_zero_point = y_zero_point.round(); // tensor<FP> only supported!\n\n    // y = saturate (round (x / y_scale) + y_zero_point)\n\n    (quantize_linear(x, @y_scale, @y_zero_point, min, max), y_scale, y_zero_point)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/qlinear_add.cairo",
        "content": "use orion::numbers::{NumberTrait};\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\nfn qlinear_add<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    a: @Tensor<Q>,\n    a_scale: @Tensor<T>,\n    a_zero_point: @Tensor<T>,\n    b: @Tensor<Q>,\n    b_scale: @Tensor<T>,\n    b_zero_point: @Tensor<T>,\n    y_scale: @Tensor<T>,\n    y_zero_point: @Tensor<T>,\n    min: T,\n    max: T\n) -> Tensor<Q> {\n    let mut dequantized_a = dequantize_linear(@(*a), a_scale, a_zero_point);\n    let mut dequantized_b = dequantize_linear(@(*b), b_scale, b_zero_point);\n\n    let mut x = (dequantized_a + dequantized_b).into();\n\n    quantize_linear(@x, y_scale, y_zero_point, min, max)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/qlinear_concat.cairo",
        "content": "use orion::numbers::{NumberTrait};\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::math::concat::{\n    validate_shapes, compute_output_size, concatenate_data\n};\n\nfn qlinear_concat<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    tensors: Span<Tensor<Q>>,\n    scales: Span<Tensor<T>>,\n    zero_points: Span<Tensor<T>>,\n    y_scale: @Tensor<T>,\n    y_zero_point: @Tensor<T>,\n    axis: usize,\n    min: T,\n    max: T\n) -> Tensor<Q> {\n    assert(tensors.len() == scales.len(), 'Each Tensors must have a scale');\n    assert(tensors.len() == zero_points.len(), 'Each Tensors must have a scale');\n\n    //let mut x = TensorTrait::concat(tensors: array![dequantized_a, dequantized_b].span(), axis: axis);\n    let mut x = concat_dequantize(tensors, scales, zero_points, axis, min, max);\n\n    quantize_linear(@x, y_scale, y_zero_point, min, max)\n}\n\n\nfn concat_dequantize<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    tensors: Span<Tensor<Q>>,\n    scales: Span<Tensor<T>>,\n    zero_points: Span<Tensor<T>>,\n    axis: usize,\n    min: T,\n    max: T\n) -> Tensor<T> {\n    assert(tensors.len() >= 2, 'Input tensors must be > 1');\n    let base_tensor = *tensors.at(0);\n    let base_shape = base_tensor.shape;\n    let dimension = base_shape.len();\n    assert(dimension > axis, 'Out of bounds for dimension');\n\n    // Validate shapes of tensors\n    validate_shapes(tensors, base_shape, axis);\n\n    // Calculate output size\n    let output_size = compute_output_size(base_shape, tensors, axis);\n\n    // Dequantize tensors\n    let tensors = dequantize_tensors(tensors, scales, zero_points, min, max);\n\n    // Concatenate tensor data\n    let output_data: Array<T> = concatenate_data(tensors, axis, base_shape);\n\n    TensorTrait::<T>::new(output_size.span(), output_data.span())\n}\n\nfn dequantize_tensors<\n    Q,\n    T,\n    impl TTensor: TensorTrait<T>,\n    impl QIntoT: Into<Q, T>,\n    impl TSub: Sub<T>,\n    impl TMul: Mul<T>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TDrop: Drop<T>,\n    impl TCopy: Copy<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>\n//MAybe numberTRait\n>(\n    mut tensors: Span<Tensor<Q>>,\n    scales: Span<Tensor<T>>,\n    zero_points: Span<Tensor<T>>,\n    min: T,\n    max: T\n) -> Span<Tensor<T>> {\n    let mut array: Array<Tensor<T>> = array![];\n    let mut i = 0;\n    loop {\n        match tensors.pop_front() {\n            Option::Some(tensor) => {\n                array\n                    .append(dequantize_linear(@(*tensor), @(*scales.at(i)), @(*zero_points.at(i))));\n            },\n            Option::None => { break; }\n        };\n\n        i += 1;\n    };\n\n    array.span()\n}\n/// # tensor.concat\n///\n/// ```rust \n///    fn concat(tensors: Span<Tensor<T>>, axis: usize,  ) -> Tensor<T>;\n/// ```\n///\n/// Concatenate a list of tensors into a single tensor.\n///\n/// ## Args\n///\n/// * `tensors`(` Span<Tensor<T>>,`) - Array of the input tensors.\n/// * `axis`(`usize`) -  Axis to concat on.\n///\n/// ## Panics\n///\n/// * Panic if tensor length is not greater than 1.\n/// * Panics if dimension is not greater than axis.\n///\n/// ## Returns \n///\n/// A new `Tensor<T>` concatenated tensor of the input tensors.\n///\n/// ## Example\n///\n/// ```rust\n/// use core::array::{ArrayTrait, SpanTrait};\n/// \n/// use orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\n/// \n/// fn concat_example() -> Tensor<u32> {\n///     let tensor1 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n///     let tensor2 = TensorTrait::new(shape: array![2, 2].span(), data: array![0, 1, 2, 3].span(),);\n///     let result = TensorTrait::concat(tensors: array![tensor1, tensor2].span(), axis: 0);\n///     return result;\n/// }\n/// >>> [[0. 1.]\n///      [2. 3.],\n///      [0. 1.]\n///      [2. 3.]]\n///\n///     result.shape\n/// >>> (4, 2)\n///\n///    let result = TensorTrait::concat(tensors: array![tensor1, tensor2].span(), axis: 1);\n///    return result;\n/// }\n/// >>> [[0. 1., 0., 1.]\n///      [2. 3., 2., 3.]]\n///\n///     result.shape\n/// >>> (2, 4 ) \n/// ```\n///\n///fn concat(tensors: Span<Tensor<T>>, axis: usize,) -> Tensor<T>;\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/qlinear_leakyrelu.cairo",
        "content": "use orion::numbers::{NumberTrait};\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\nfn qlinear_leakyrelu<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>\n>(\n    a: @Tensor<Q>, a_scale: @Tensor<T>, a_zero_point: @Tensor<T>, alpha: T, min: T, max: T\n) -> Tensor<Q> {\n    let mut dequantized_a = dequantize_linear(@(*a), a_scale, a_zero_point);\n\n    let mut result_data: Array<T> = array![];\n    loop {\n        match dequantized_a.data.pop_front() {\n            Option::Some(elem) => {\n                if *elem < NumberTrait::zero() {\n                    result_data.append(*elem * alpha);\n                } else {\n                    result_data.append(*elem);\n                }\n            },\n            Option::None => { break; }\n        };\n    };\n\n    quantize_linear(\n        @TensorTrait::new(dequantized_a.shape, result_data.span()), a_scale, a_zero_point, min, max\n    )\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/qlinear_matmul.cairo",
        "content": "use orion::numbers::{NumberTrait};\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n/// Cf: TensorTrait::qlinear_matmul docstring\nfn qlinear_matmul<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TMul: Mul<T>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    //impl TTensorTryInto: TryInto<Tensor<T>, Tensor<Q>>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    a: @Tensor<Q>,\n    a_scale: @Tensor<T>,\n    a_zero_point: @Tensor<T>,\n    b: @Tensor<Q>,\n    b_scale: @Tensor<T>,\n    b_zero_point: @Tensor<T>,\n    y_scale: @Tensor<T>,\n    y_zero_point: @Tensor<T>,\n    min: T,\n    max: T\n) -> Tensor<Q> {\n    let a_shape = *a.shape;\n    let b_shape = *b.shape;\n\n    let a_ndim = (a_shape).len();\n    let b_ndim = (b_shape).len();\n\n    //! Case: Both tensors are max 2-dimensional\n    if a_ndim <= 2 && b_ndim <= 2 {\n        let mut dequantized_a = dequantize_linear(@(*a), a_scale, a_zero_point);\n        let mut dequantized_b = dequantize_linear(@(*b), b_scale, b_zero_point);\n\n        let mut x = dequantized_a.matmul(@dequantized_b);\n\n        return quantize_linear(@x, y_scale, y_zero_point, min, max);\n    }\n\n    // (D1, D2, M, K) * (D1, D2, K, N) -> (D1, D2, M, N)\n    assert(a_ndim == b_ndim, 'dim missmatch');\n    let mut dequantized_a = dequantize_linear(@(*a), a_scale, a_zero_point);\n    let mut dequantized_b = dequantize_linear(@(*b), b_scale, b_zero_point);\n    let mut x_shape: Array<usize> = array![];\n    let mut x_data: Array<T> = array![];\n\n    assert(a_shape[a_ndim - 1] == b_shape[b_ndim - 2], 'incompatible dim for matmul');\n\n    let m = *a_shape[a_ndim - 2];\n    let k = *a_shape[a_ndim - 1];\n    let n = *b_shape[b_ndim - 1];\n\n    let mut a_shape_reduced: Array<usize> = array![];\n    a_shape_reduced.append(m);\n    a_shape_reduced.append(k);\n\n    let mut b_shape_reduced: Array<usize> = array![];\n    b_shape_reduced.append(k);\n    b_shape_reduced.append(n);\n\n    let mut i = 0;\n    while i != stride(a_shape) / (m * k) {\n        result_updates(\n            @subtensor(@dequantized_a, i * (m * k), a_shape_reduced.span()),\n            @subtensor(@dequantized_b, i * (k * n), b_shape_reduced.span()),\n            ref x_data\n        );\n        i += 1;\n    };\n\n    x_shape(ref x_shape, a_shape, m, n);\n    let x = TensorTrait::new(x_shape.span(), x_data.span());\n\n    quantize_linear(@x, y_scale, y_zero_point, min, max)\n}\n\nfn x_shape(ref x_data: Array<usize>, mut shape: Span<usize>, m: usize, n: usize) {\n    while shape.len() != 2 {\n        match shape.pop_front() {\n            Option::Some(elem) => { x_data.append(*elem); },\n            Option::None => { break; }\n        };\n    };\n\n    x_data.append(m);\n    x_data.append(n);\n}\n\nfn stride(mut shape: Span<usize>) -> usize {\n    let shape_len = shape.len();\n    assert(shape_len > 0, 'shape cannot be empty');\n\n    let mut accumulated: usize = 1;\n    loop {\n        match shape.pop_back() {\n            Option::Some(i) => { accumulated *= *i; },\n            Option::None => { break; }\n        };\n    };\n\n    accumulated\n}\n\nfn subtensor<T, impl TTensor: TensorTrait<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    x: @Tensor<T>, start: usize, shape: Span<usize>\n) -> Tensor::<T> {\n    let mut data = ArrayTrait::<T>::new();\n    let mut stride = stride(shape);\n    let mut i = 0;\n\n    while i != stride {\n        data.append(*x.data[start + i]);\n        i += 1;\n    };\n\n    TensorTrait::new(shape, data.span())\n}\n\n\nfn result_updates<\n    T,\n    MAG,\n    impl TTensor: TensorTrait<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TMul: Mul<T>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>\n>(\n    mat1: @Tensor<T>, mat2: @Tensor<T>, ref result_data: Array<T>\n) {\n    let m = *mat1.shape[0];\n    let n = *mat1.shape[1];\n    let p = *mat2.shape[1];\n\n    let mat1 = *mat1.data;\n    let mat2 = *mat2.data;\n\n    let mut result_shape: Array<usize> = array![];\n    result_shape.append(m);\n    result_shape.append(p);\n\n    let mut i = 0_usize;\n    while i != m {\n        let mut j = 0_usize;\n        while j != p {\n            let mut sum: T = NumberTrait::zero();\n            let mut k = 0_usize;\n            while k != n {\n                let mat1_index = i * n + k;\n                let mat2_index = k * p + j;\n                sum += *mat1[mat1_index] * *mat2[mat2_index];\n\n                k += 1;\n            };\n\n            result_data.append(sum);\n            j += 1;\n        };\n\n        i += 1;\n    };\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/qlinear_mul.cairo",
        "content": "use orion::numbers::{NumberTrait};\nuse orion::operators::tensor::quantization::dequantize_linear::dequantize_linear;\nuse orion::operators::tensor::quantization::quantize_linear::quantize_linear;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n\nfn qlinear_mul<\n    T,\n    MAG,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl QIntoT: Into<Q, T>,\n    impl QTensorIntoTTensor: Into<Tensor<Q>, Tensor<T>>,\n    impl TAdd: Add<T>,\n    impl TSub: Sub<T>,\n    impl TDiv: Div<T>,\n    impl TMul: Mul<T>,\n    impl TTensorAdd: Add<Tensor<T>>,\n    impl TTensorSub: Sub<Tensor<T>>,\n    impl TTensorMul: Mul<Tensor<T>>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TNumber: NumberTrait<T, MAG>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TAddEq: AddEq<T>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    a: @Tensor<Q>,\n    a_scale: @Tensor<T>,\n    a_zero_point: @Tensor<T>,\n    b: @Tensor<Q>,\n    b_scale: @Tensor<T>,\n    b_zero_point: @Tensor<T>,\n    y_scale: @Tensor<T>,\n    y_zero_point: @Tensor<T>,\n    min: T,\n    max: T\n) -> Tensor<Q> {\n    let mut dequantized_a = dequantize_linear(@(*a), a_scale, a_zero_point);\n    let mut dequantized_b = dequantize_linear(@(*b), b_scale, b_zero_point);\n\n    let mut x = (dequantized_a * dequantized_b).into();\n\n    quantize_linear(@x, y_scale, y_zero_point, min, max)\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/tensor/quantization/quantize_linear.cairo",
        "content": "use orion::operators::tensor::core::{Tensor, TensorTrait};\nuse orion::operators::tensor::helpers::check_compatibility;\nuse orion::operators::tensor::math::arithmetic::saturated_add;\nuse orion::utils::saturate;\n\n/// Cf: TensorTrait::quantize_linear docstring\nfn quantize_linear<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TAdd: Add<T>,\n    impl TDiv: Div<T>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n>(\n    x: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>, min: T, max: T\n) -> Tensor::<Q> {\n    if (*y_scale.data).len() == 1 && (*y_zero_point.data).len() == 1 {\n        quantize_element_wise(*x, *y_scale.data[0], *y_zero_point.data[0], min, max)\n    } else {\n        check_compatibility(*x.shape, *y_scale.shape);\n        check_compatibility(*x.shape, *y_zero_point.shape);\n        check_compatibility(*y_scale.shape, *y_zero_point.shape);\n\n        quantize_per_axis(x, y_scale, y_zero_point, min, max)\n    }\n}\n\nfn quantize_per_axis<\n    T,\n    Q,\n    impl TTensor: TensorTrait<T>,\n    impl QTensor: TensorTrait<Q>,\n    impl TAdd: Add<T>,\n    impl TTensorDiv: Div<Tensor<T>>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TTryInto: TryInto<T, Q>,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QDrop: Drop<Q>,\n>(\n    x: @Tensor<T>, y_scale: @Tensor<T>, y_zero_point: @Tensor<T>, min: T, max: T\n) -> Tensor::<Q> {\n    saturated_add(@(*x / *y_scale), y_zero_point, min, max)\n}\n\nfn quantize_element_wise<\n    T,\n    Q,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl QCopy: Copy<Q>,\n    impl QDrop: Drop<Q>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TDiv: Div<T>,\n    impl TAdd: Add<T>,\n    impl TTryIntoQ: TryInto<T, Q>,\n    impl QTensor: TensorTrait<Q>\n>(\n    mut x: Tensor::<T>, y_scale: T, y_zero_point: T, min: T, max: T\n) -> Tensor::<Q> {\n    let mut result_data: Array<Q> = array![];\n\n    loop {\n        match x.data.pop_front() {\n            Option::Some(item) => {\n                let quantized = quantize(*item, y_scale, y_zero_point, min, max);\n                result_data.append(quantized);\n            },\n            Option::None => { break; }\n        };\n    };\n\n    TensorTrait::new(x.shape, result_data.span())\n}\n\nfn quantize<\n    T,\n    Q,\n    impl TCopy: Copy<T>,\n    impl TDrop: Drop<T>,\n    impl TPartialOrd: PartialOrd<T>,\n    impl TDiv: Div<T>,\n    impl TAdd: Add<T>,\n    impl TTryIntoQ: TryInto<T, Q>\n>(\n    x: T, y_scale: T, y_zero_point: T, min: T, max: T\n) -> Q {\n    saturate(min, max, ((x / y_scale) + y_zero_point)).try_into().unwrap()\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/operators/vec.cairo",
        "content": "use core::box::BoxTrait;\nuse core::traits::Into;\nuse core::nullable::{Nullable, match_nullable, FromNullableResult, nullable_from_box};\nuse alexandria_data_structures::vec::{VecTrait};\nuse orion::numbers::NumberTrait;\n\nstruct NullableVec<T> {\n    items: Felt252Dict<Nullable<T>>,\n    len: usize,\n}\n\nimpl DestructNullableVec<T, impl TDrop: Drop<T>> of Destruct<NullableVec<T>> {\n    fn destruct(self: NullableVec<T>) nopanic {\n        self.items.squash();\n    }\n}\n\nimpl NullableVecImpl<\n    T, MAG, impl TDrop: Drop<T>, impl TCopy: Copy<T>, +NumberTrait<T, MAG>\n> of VecTrait<NullableVec<T>, T> {\n    fn new() -> NullableVec<T> {\n        NullableVec { items: Default::default(), len: 0 }\n    }\n\n    fn get(ref self: NullableVec<T>, index: usize) -> Option<T> {\n        if (index < self.len()) {\n            return match match_nullable(self.items.get(index.into())) {\n                FromNullableResult::Null(()) => { Option::Some(NumberTrait::zero()) },\n                FromNullableResult::NotNull(val) => { Option::Some(val.unbox()) },\n            };\n        } else {\n            Option::<T>::None\n        }\n    }\n\n    fn at(ref self: NullableVec<T>, index: usize) -> T {\n        assert(index < self.len(), 'Index out of bounds');\n\n        return match self.get(index) {\n            Option::Some(val) => val,\n            Option::None => NumberTrait::zero(),\n        };\n    }\n\n    fn push(ref self: NullableVec<T>, value: T) -> () {\n        self.items.insert(self.len.into(), nullable_from_box(BoxTrait::new(value)));\n        self.len = core::integer::u32_wrapping_add(self.len, 1_usize);\n    }\n\n    fn set(ref self: NullableVec<T>, index: usize, value: T) {\n        if index >= self.len() {\n            self.len = index + 1;\n        }\n        self.items.insert(index.into(), nullable_from_box(BoxTrait::new(value)));\n    }\n\n    fn len(self: @NullableVec<T>) -> usize {\n        *self.len\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper.cairo",
        "content": "mod tensor;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor.cairo",
        "content": "mod fixed_point;\nmod i32;\nmod i8;\nmod u32;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/fixed_point.cairo",
        "content": "mod fp8x23;\nmod fp16x16;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/fixed_point/fp16x16.cairo",
        "content": "use orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\nuse orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n// 1D\nfn fp_tensor_1x3_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_1x3_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 2D\nfn fp_tensor_2x2_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x2_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x1_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x1_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x3_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x3_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 3D\nfn fp_tensor_2x2x2_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x2x2_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2x2_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false),\n        FixedTrait::new_unscaled(9, false),\n        FixedTrait::new_unscaled(10, false),\n        FixedTrait::new_unscaled(11, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2x2_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true),\n        FixedTrait::new_unscaled(9, true),\n        FixedTrait::new_unscaled(10, true),\n        FixedTrait::new_unscaled(11, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n\nfn fp_tensor_3x3x3_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false),\n        FixedTrait::new_unscaled(9, false),\n        FixedTrait::new_unscaled(10, false),\n        FixedTrait::new_unscaled(11, false),\n        FixedTrait::new_unscaled(12, false),\n        FixedTrait::new_unscaled(13, false),\n        FixedTrait::new_unscaled(14, false),\n        FixedTrait::new_unscaled(15, false),\n        FixedTrait::new_unscaled(16, false),\n        FixedTrait::new_unscaled(17, false),\n        FixedTrait::new_unscaled(18, false),\n        FixedTrait::new_unscaled(19, false),\n        FixedTrait::new_unscaled(20, false),\n        FixedTrait::new_unscaled(21, false),\n        FixedTrait::new_unscaled(22, false),\n        FixedTrait::new_unscaled(23, false),\n        FixedTrait::new_unscaled(24, false),\n        FixedTrait::new_unscaled(25, false),\n        FixedTrait::new_unscaled(26, false)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3x3_neg_helper() -> Tensor<FP16x16> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true),\n        FixedTrait::new_unscaled(9, true),\n        FixedTrait::new_unscaled(10, true),\n        FixedTrait::new_unscaled(11, true),\n        FixedTrait::new_unscaled(12, true),\n        FixedTrait::new_unscaled(13, true),\n        FixedTrait::new_unscaled(14, true),\n        FixedTrait::new_unscaled(15, true),\n        FixedTrait::new_unscaled(16, true),\n        FixedTrait::new_unscaled(17, true),\n        FixedTrait::new_unscaled(18, true),\n        FixedTrait::new_unscaled(19, true),\n        FixedTrait::new_unscaled(20, true),\n        FixedTrait::new_unscaled(21, true),\n        FixedTrait::new_unscaled(22, true),\n        FixedTrait::new_unscaled(23, true),\n        FixedTrait::new_unscaled(24, true),\n        FixedTrait::new_unscaled(25, true),\n        FixedTrait::new_unscaled(26, true)\n    ];\n\n    let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/fixed_point/fp8x23.cairo",
        "content": "use orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\nuse orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n// 1D\nfn fp_tensor_1x3_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_1x3_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 2D\nfn fp_tensor_2x2_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x2_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x1_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x1_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x3_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x3_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 3D\nfn fp_tensor_2x2x2_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_2x2x2_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2x2_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false),\n        FixedTrait::new_unscaled(9, false),\n        FixedTrait::new_unscaled(10, false),\n        FixedTrait::new_unscaled(11, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x2x2_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true),\n        FixedTrait::new_unscaled(9, true),\n        FixedTrait::new_unscaled(10, true),\n        FixedTrait::new_unscaled(11, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n\nfn fp_tensor_3x3x3_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, false),\n        FixedTrait::new_unscaled(2, false),\n        FixedTrait::new_unscaled(3, false),\n        FixedTrait::new_unscaled(4, false),\n        FixedTrait::new_unscaled(5, false),\n        FixedTrait::new_unscaled(6, false),\n        FixedTrait::new_unscaled(7, false),\n        FixedTrait::new_unscaled(8, false),\n        FixedTrait::new_unscaled(9, false),\n        FixedTrait::new_unscaled(10, false),\n        FixedTrait::new_unscaled(11, false),\n        FixedTrait::new_unscaled(12, false),\n        FixedTrait::new_unscaled(13, false),\n        FixedTrait::new_unscaled(14, false),\n        FixedTrait::new_unscaled(15, false),\n        FixedTrait::new_unscaled(16, false),\n        FixedTrait::new_unscaled(17, false),\n        FixedTrait::new_unscaled(18, false),\n        FixedTrait::new_unscaled(19, false),\n        FixedTrait::new_unscaled(20, false),\n        FixedTrait::new_unscaled(21, false),\n        FixedTrait::new_unscaled(22, false),\n        FixedTrait::new_unscaled(23, false),\n        FixedTrait::new_unscaled(24, false),\n        FixedTrait::new_unscaled(25, false),\n        FixedTrait::new_unscaled(26, false)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn fp_tensor_3x3x3_neg_helper() -> Tensor<FP8x23> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data = array![\n        FixedTrait::new_unscaled(0, false),\n        FixedTrait::new_unscaled(1, true),\n        FixedTrait::new_unscaled(2, true),\n        FixedTrait::new_unscaled(3, true),\n        FixedTrait::new_unscaled(4, true),\n        FixedTrait::new_unscaled(5, true),\n        FixedTrait::new_unscaled(6, true),\n        FixedTrait::new_unscaled(7, true),\n        FixedTrait::new_unscaled(8, true),\n        FixedTrait::new_unscaled(9, true),\n        FixedTrait::new_unscaled(10, true),\n        FixedTrait::new_unscaled(11, true),\n        FixedTrait::new_unscaled(12, true),\n        FixedTrait::new_unscaled(13, true),\n        FixedTrait::new_unscaled(14, true),\n        FixedTrait::new_unscaled(15, true),\n        FixedTrait::new_unscaled(16, true),\n        FixedTrait::new_unscaled(17, true),\n        FixedTrait::new_unscaled(18, true),\n        FixedTrait::new_unscaled(19, true),\n        FixedTrait::new_unscaled(20, true),\n        FixedTrait::new_unscaled(21, true),\n        FixedTrait::new_unscaled(22, true),\n        FixedTrait::new_unscaled(23, true),\n        FixedTrait::new_unscaled(24, true),\n        FixedTrait::new_unscaled(25, true),\n        FixedTrait::new_unscaled(26, true)\n    ];\n\n    let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/i32.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32Tensor;\n\n// 1D\nfn i32_tensor_1x3_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data: Array<i32> = array![0, 1, 2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_1x3_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data: Array<i32> = array![0, -1, -2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 2D\nfn i32_tensor_2x2_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data: Array<i32> = array![0, 1, 2, 3];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_2x2_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data: Array<i32> = array![0, -1, -2, -3];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x3_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data: Array<i32> = array![0, 1, 2, 3, 4, 5, 6, 7, 8];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x3_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data: Array<i32> = array![0, -1, -2, -3, -4, -5, -6, -7, -8];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x2_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data: Array<i32> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x2_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data: Array<i32> = array![0, -1, -2, -3, -4, -5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x1_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data: Array<i32> = array![0, 1, 2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x1_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data: Array<i32> = array![0, -1, -2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_2x3_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data: Array<i32> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_2x3_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data: Array<i32> = array![0, -1, -2, -3, -4, -5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 3D\nfn i32_tensor_2x2x2_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data: Array<i32> = array![0, 1, 2, 3, 4, 5, 6, 7];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_2x2x2_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data: Array<i32> = array![0, -1, -2, -3, -4, -5, -6, -7];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x2x2_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data: Array<i32> = array![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x2x2_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data: Array<i32> = array![0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x3x3_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data: Array<i32> = array![\n        0,\n        1,\n        2,\n        3,\n        4,\n        5,\n        6,\n        7,\n        8,\n        9,\n        10,\n        11,\n        12,\n        13,\n        14,\n        15,\n        16,\n        17,\n        18,\n        19,\n        20,\n        21,\n        22,\n        23,\n        24,\n        25,\n        26\n    ];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i32_tensor_3x3x3_neg_helper() -> Tensor<i32> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data: Array<i32> = array![\n        0,\n        -1,\n        -2,\n        -3,\n        -4,\n        -5,\n        -6,\n        -7,\n        -8,\n        -9,\n        -10,\n        -11,\n        -12,\n        -13,\n        -14,\n        -15,\n        -16,\n        -17,\n        -18,\n        -19,\n        -20,\n        -21,\n        -22,\n        -23,\n        -24,\n        -25,\n        -26\n    ];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/i8.cairo",
        "content": "use orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8Tensor;\n\n// 1D\nfn i8_tensor_1x3_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data: Array<i8> = array![0, 1, 2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_1x3_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data: Array<i8> = array![0, -1, 2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 2D\nfn i8_tensor_2x2_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data: Array<i8> = array![0, 1, 2, 3];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_2x2_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data: Array<i8> = array![0, -1, -2, -3];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x3_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data: Array<i8> = array![0, 1, 2, 3, 4, 5, 6, 7, 8];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x3_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data: Array<i8> = array![0, -1, -2, -3, -4, -5, -6, -7, -8];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x2_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data: Array<i8> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x2_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data: Array<i8> = array![0, -1, -2, -3, -4, -5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    return tensor;\n}\n\nfn i8_tensor_3x1_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data: Array<i8> = array![0, 1, 2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x1_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data: Array<i8> = array![0, -1, -2];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_2x3_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data: Array<i8> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_2x3_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data: Array<i8> = array![0, -1, -2, -3, -4, -5];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 3D\n\nfn i8_tensor_2x2x2_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data: Array<i8> = array![0, 1, 2, 3, 4, 5, 6, 7];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_2x2x2_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data: Array<i8> = array![0, -1, -2, -3, -4, -5, -6, -7];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x2x2_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data: Array<i8> = array![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x2x2_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data: Array<i8> = array![0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x3x3_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data: Array<i8> = array![\n        0,\n        1,\n        2,\n        3,\n        4,\n        5,\n        6,\n        7,\n        8,\n        9,\n        10,\n        11,\n        12,\n        13,\n        14,\n        15,\n        16,\n        17,\n        18,\n        19,\n        20,\n        21,\n        22,\n        23,\n        24,\n        25,\n        26\n    ];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn i8_tensor_3x3x3_neg_helper() -> Tensor<i8> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data: Array<i8> = array![\n        0,\n        -1,\n        -2,\n        -3,\n        -4,\n        -5,\n        -6,\n        -7,\n        -8,\n        -9,\n        -10,\n        -11,\n        -12,\n        -13,\n        -14,\n        -15,\n        -16,\n        -17,\n        -18,\n        -19,\n        -20,\n        -21,\n        -22,\n        -23,\n        -24,\n        -25,\n        -26\n    ];\n\n    let tensor = TensorTrait::new(sizes.span(), data.span());\n\n    tensor\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/test_helper/tensor/u32.cairo",
        "content": "use orion::operators::tensor::U32Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n// 1D\nfn u32_tensor_1x3_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3];\n    let mut data: Array<u32> = array![0, 1, 2];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 2D\nfn u32_tensor_2x2_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![2, 2];\n    let mut data: Array<u32> = array![0, 1, 2, 3];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_3x3_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3, 3];\n    let mut data: Array<u32> = array![0, 1, 2, 3, 4, 5, 6, 7, 8];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_3x2_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3, 2];\n    let mut data: Array<u32> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_3x1_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3, 1];\n    let mut data: Array<u32> = array![0, 1, 2];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_2x3_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![2, 3];\n    let mut data: Array<u32> = array![0, 1, 2, 3, 4, 5];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n// 3D\nfn u32_tensor_2x2x2_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![2, 2, 2];\n    let mut data: Array<u32> = array![0, 1, 2, 3, 4, 5, 6, 7];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_3x2x2_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3, 2, 2];\n    let mut data: Array<u32> = array![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\nfn u32_tensor_3x3x3_helper() -> Tensor<u32> {\n    let mut sizes: Array<u32> = array![3, 3, 3];\n    let mut data: Array<u32> = array![\n        0,\n        1,\n        2,\n        3,\n        4,\n        5,\n        6,\n        7,\n        8,\n        9,\n        10,\n        11,\n        12,\n        13,\n        14,\n        15,\n        16,\n        17,\n        18,\n        19,\n        20,\n        21,\n        22,\n        23,\n        24,\n        25,\n        26\n    ];\n\n    let tensor = TensorTrait::<u32>::new(sizes.span(), data.span());\n\n    tensor\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "src/utils.cairo",
        "content": "use orion::operators::tensor::{Tensor, TensorTrait};\n\nfn u32_max(a: u32, b: u32) -> u32 {\n    if a > b {\n        a\n    } else {\n        b\n    }\n}\n\nfn saturate<T, impl TCopy: Copy<T>, impl TDrop: Drop<T>, impl PartialOrdT: PartialOrd<T>>(\n    min: T, max: T, x: T\n) -> T {\n    if x < min {\n        min\n    } else if x > max {\n        max\n    } else {\n        x\n    }\n}\n\nfn assert_eq<T, impl TPartialEq: PartialEq<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    lhs: T, rhs: T\n) {\n    assert(lhs == rhs, 'should be equal');\n}\n\nfn assert_seq_eq<T, impl TPartialEq: PartialEq<T>, impl TCopy: Copy<T>, impl TDrop: Drop<T>>(\n    lhs: Array<T>, rhs: Array<T>\n) {\n    assert(lhs.len() == rhs.len(), 'should be equal');\n\n    let mut i = 0;\n    while i != lhs.len() {\n        assert_eq(lhs[i], rhs[i]);\n        i += 1;\n    }\n}\n\nfn get_row<T, +Drop<T>, +Copy<T>>(self: @Tensor<T>, row: usize) -> Span<T> {\n    assert((*self).shape.len() == 2, 'Expected a 2D tensor');\n\n    let row_length = *self.shape[1];\n    let start = row * row_length;\n\n    (*self).data.slice(start, row_length)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/lib.cairo",
        "content": "mod numbers;\nmod performance;\nmod tensor_core;\nmod nodes;\nmod ml;\nmod operators;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml.cairo",
        "content": "mod tree_ensemble_classifier;\nmod tree_ensemble_regressor;\nmod linear_regressor_test;\nmod linear_classifier_test;\nmod svm_regressor_test;\nmod svm_classifier_test;\nmod normalizer_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/linear_classifier_test.cairo",
        "content": "use orion::numbers::FP16x16;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\n\nuse orion::operators::ml::linear::linear_classifier::{\n    LinearClassifierTrait, POST_TRANSFORM, LinearClassifier\n};\nuse core::debug::PrintTrait;\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_multi_none() {\n    let (mut classifier, X) = linear_classifier_helper(POST_TRANSFORM::NONE);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 2, 'labels[1]');\n    assert(*labels[2] == 2, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 157942, sign: false }, '*scores[0] == 2.41');\n    assert(*scores.data[1] == FP16x16 { mag: 138936, sign: true }, '*scores[1] == -2.12');\n    assert(*scores.data[2] == FP16x16 { mag: 38666, sign: false }, '*scores[2] == 0.59');\n    assert(*scores.data[3] == FP16x16 { mag: 43910, sign: false }, '*scores[3] == 0.67');\n    assert(*scores.data[4] == FP16x16 { mag: 74710, sign: true }, '*scores[4] == -1.14');\n    assert(*scores.data[5] == FP16x16 { mag: 88472, sign: false }, '*scores[5] == 1.35');\n    assert(*scores.data[6] == FP16x16 { mag: 70122, sign: true }, '*scores[6] == -1.07');\n    assert(*scores.data[7] == FP16x16 { mag: 10484, sign: true }, '*scores[7] == -0.16');\n    assert(*scores.data[8] == FP16x16 { mag: 138278, sign: false }, '*scores[8] == 2.11');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_multi_softmax() {\n    let (mut classifier, X) = linear_classifier_helper(POST_TRANSFORM::SOFTMAX);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 2, 'labels[1]');\n    assert(*labels[2] == 2, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 55879, sign: false }, '*scores[0] == 0.852656');\n    assert(*scores.data[1] == FP16x16 { mag: 602, sign: false }, '*scores[1] == 0.009192');\n    assert(*scores.data[2] == FP16x16 { mag: 9053, sign: false }, '*scores[2] == 0.138152');\n    assert(*scores.data[3] == FP16x16 { mag: 20888, sign: false }, '*scores[3] == 0.318722');\n    assert(*scores.data[4] == FP16x16 { mag: 3418, sign: false }, '*scores[4] == 0.05216');\n    assert(*scores.data[5] == FP16x16 { mag: 41229, sign: false }, '*scores[5] == 0.629118');\n    assert(*scores.data[6] == FP16x16 { mag: 2380, sign: false }, '*scores[6] == 0.036323');\n    assert(*scores.data[7] == FP16x16 { mag: 5914, sign: false }, '*scores[7] == 0.090237');\n    assert(*scores.data[8] == FP16x16 { mag: 57241, sign: false }, '*scores[8] == 0.87344');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_multi_softmax_zero() {\n    let (mut classifier, X) = linear_classifier_helper(POST_TRANSFORM::SOFTMAXZERO);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 2, 'labels[1]');\n    assert(*labels[2] == 2, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 55879, sign: false }, '*scores[0] == 0.852656');\n    assert(*scores.data[1] == FP16x16 { mag: 602, sign: false }, '*scores[1] == 0.009192');\n    assert(*scores.data[2] == FP16x16 { mag: 9053, sign: false }, '*scores[2] == 0.138152');\n    assert(*scores.data[3] == FP16x16 { mag: 20888, sign: false }, '*scores[3] == 0.318722');\n    assert(*scores.data[4] == FP16x16 { mag: 3418, sign: false }, '*scores[4] == 0.05216');\n    assert(*scores.data[5] == FP16x16 { mag: 41229, sign: false }, '*scores[5] == 0.629118');\n    assert(*scores.data[6] == FP16x16 { mag: 2380, sign: false }, '*scores[6] == 0.036323');\n    assert(*scores.data[7] == FP16x16 { mag: 5914, sign: false }, '*scores[7] == 0.090237');\n    assert(*scores.data[8] == FP16x16 { mag: 57241, sign: false }, '*scores[8] == 0.87344');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_multi_logistic() {\n    let (mut classifier, X) = linear_classifier_helper(POST_TRANSFORM::LOGISTIC);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0] == 0');\n    assert(*labels[1] == 2, 'labels[1] == 2');\n    assert(*labels[2] == 2, 'labels[2] == 2');\n    assert(labels.len() == 3, 'len(labels) == 3');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 60135, sign: false }, '*scores[0] == 0.917587');\n    assert(*scores.data[1] == FP16x16 { mag: 7023, sign: false }, '*scores[1] == 0.107168');\n    assert(*scores.data[2] == FP16x16 { mag: 42163, sign: false }, '*scores[2] == 0.643365');\n    assert(*scores.data[3] == FP16x16 { mag: 43351, sign: false }, '*scores[3] == 0.661503');\n    assert(*scores.data[4] == FP16x16 { mag: 15881, sign: false }, '*scores[4] == 0.24232');\n    assert(*scores.data[5] == FP16x16 { mag: 52043, sign: false }, '*scores[5] == 0.79413');\n    assert(*scores.data[6] == FP16x16 { mag: 16738, sign: false }, '*scores[6] == 0.255403');\n    assert(*scores.data[7] == FP16x16 { mag: 30152, sign: false }, '*scores[7] == 0.460085');\n    assert(*scores.data[8] == FP16x16 { mag: 58450, sign: false }, '*scores[8] == 0.891871');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_binary_none() {\n    let (mut classifier, X) = linear_classifier_helper_binary(POST_TRANSFORM::NONE);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 624559, sign: true }, '*scores[0] == -9.53');\n    assert(*scores.data[1] == FP16x16 { mag: 624559, sign: false }, '*scores[1] == 9.53');\n    assert(*scores.data[2] == FP16x16 { mag: 435817, sign: true }, '*scores[2] == -6.65');\n    assert(*scores.data[3] == FP16x16 { mag: 435817, sign: false }, '*scores[3] == 6.65');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_binary_logistic() {\n    let (mut classifier, X) = linear_classifier_helper_binary(POST_TRANSFORM::LOGISTIC);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 4, sign: false }, '*scores[0] == 7.263436e-05');\n    assert(*scores.data[1] == FP16x16 { mag: 65532, sign: false }, '*scores[1] == 9.999274e-01');\n    assert(*scores.data[2] == FP16x16 { mag: 84, sign: false }, '*scores[2] == 1.292350e-03');\n    assert(*scores.data[3] == FP16x16 { mag: 65452, sign: false }, '*scores[3] == 9.999983e-01');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_binary_softmax() {\n    let (mut classifier, X) = linear_classifier_helper_binary(POST_TRANSFORM::SOFTMAX);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 0, sign: false }, '*scores[0] == 5.276517e-09');\n    assert(*scores.data[1] == FP16x16 { mag: 65535, sign: false }, '*scores[1] == 1.000000');\n    assert(*scores.data[2] == FP16x16 { mag: 0, sign: false }, '*scores[2] == 1.674492e-06');\n    assert(*scores.data[3] == FP16x16 { mag: 65535, sign: false }, '*scores[3] ==  9.999983e-01');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_binary_softmax_zero() {\n    let (mut classifier, X) = linear_classifier_helper_binary(POST_TRANSFORM::SOFTMAXZERO);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 0, sign: false }, '*scores[0] == 5.276517e-09');\n    assert(*scores.data[1] == FP16x16 { mag: 65535, sign: false }, '*scores[1] == 1.000000');\n    assert(*scores.data[2] == FP16x16 { mag: 0, sign: false }, '*scores[2] == 1.674492e-06');\n    assert(*scores.data[3] == FP16x16 { mag: 65535, sign: false }, '*scores[3] ==  9.999983e-01');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_unary_none() {\n    let (mut classifier, X) = linear_classifier_helper_unary(POST_TRANSFORM::NONE);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 146146, sign: false }, '*scores[0] == 2.23');\n    assert(*scores.data[1] == FP16x16 { mag: 42596, sign: true }, '*scores[1] == -0.65');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_unary_logistic() {\n    let (mut classifier, X) = linear_classifier_helper_unary(POST_TRANSFORM::LOGISTIC);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 59173, sign: false }, '*scores[0] == 0.902911');\n    assert(*scores.data[1] == FP16x16 { mag: 22479, sign: false }, '*scores[1] == 0.34299');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_unary_softmax() {\n    let (mut classifier, X) = linear_classifier_helper_unary(POST_TRANSFORM::SOFTMAX);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 65536, sign: false }, '*scores[0] == 1');\n    assert(*scores.data[1] == FP16x16 { mag: 65536, sign: false }, '*scores[1] == 1');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_classifier_unary_softmax_zero() {\n    let (mut classifier, X) = linear_classifier_helper_unary(POST_TRANSFORM::SOFTMAXZERO);\n\n    let (labels, mut scores) = LinearClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(labels.len() == 2, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(*scores.data[0] == FP16x16 { mag: 65536, sign: false }, '*scores[0] == 1');\n    assert(*scores.data[1] == FP16x16 { mag: 65536, sign: false }, '*scores[1] == 1');\n}\n\n\n// ============ HELPER ============ //\n\nfn linear_classifier_helper(\n    post_transform: POST_TRANSFORM\n) -> (LinearClassifier<FP16x16>, Tensor<FP16x16>) {\n    let classlabels: Span<usize> = array![0, 1, 2].span();\n    let classlabels = Option::Some(classlabels);\n\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 38011, sign: true },\n        FP16x16 { mag: 19005, sign: true },\n        FP16x16 { mag: 5898, sign: true },\n        FP16x16 { mag: 38011, sign: false },\n        FP16x16 { mag: 19005, sign: false },\n        FP16x16 { mag: 5898, sign: false },\n    ]\n        .span();\n\n    let intercepts: Span<FP16x16> = array![\n        FP16x16 { mag: 176947, sign: false },\n        FP16x16 { mag: 176947, sign: true },\n        FP16x16 { mag: 32768, sign: false },\n    ]\n        .span();\n    let intercepts = Option::Some(intercepts);\n\n    let multi_class: usize = 0;\n\n    let mut classifier: LinearClassifier<FP16x16> = LinearClassifier {\n        classlabels, coefficients, intercepts, multi_class, post_transform\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 131072, sign: false },\n            FP16x16 { mag: 196608, sign: false },\n            FP16x16 { mag: 262144, sign: false },\n            FP16x16 { mag: 327680, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n\nfn linear_classifier_helper_binary(\n    post_transform: POST_TRANSFORM\n) -> (LinearClassifier<FP16x16>, Tensor<FP16x16>) {\n    let classlabels: Span<usize> = array![0, 1].span();\n    let classlabels = Option::Some(classlabels);\n\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 38011, sign: true },\n        FP16x16 { mag: 19005, sign: true },\n        FP16x16 { mag: 5898, sign: true },\n    ]\n        .span();\n\n    let intercepts: Span<FP16x16> = array![FP16x16 { mag: 655360, sign: false },].span();\n    let intercepts = Option::Some(intercepts);\n\n    let multi_class: usize = 0;\n\n    let mut classifier: LinearClassifier<FP16x16> = LinearClassifier {\n        classlabels, coefficients, intercepts, multi_class, post_transform\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![2, 3].span(),\n        array![\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 131072, sign: false },\n            FP16x16 { mag: 196608, sign: false },\n            FP16x16 { mag: 262144, sign: false },\n            FP16x16 { mag: 327680, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\nfn linear_classifier_helper_unary(\n    post_transform: POST_TRANSFORM\n) -> (LinearClassifier<FP16x16>, Tensor<FP16x16>) {\n    let classlabels: Span<usize> = array![1].span();\n    let classlabels = Option::Some(classlabels);\n\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 38011, sign: true },\n        FP16x16 { mag: 19005, sign: true },\n        FP16x16 { mag: 5898, sign: true },\n    ]\n        .span();\n\n    let intercepts: Span<FP16x16> = array![FP16x16 { mag: 176947, sign: false },].span();\n    let intercepts = Option::Some(intercepts);\n\n    let multi_class: usize = 0;\n\n    let mut classifier: LinearClassifier<FP16x16> = LinearClassifier {\n        classlabels, coefficients, intercepts, multi_class, post_transform\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![2, 3].span(),\n        array![\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 131072, sign: false },\n            FP16x16 { mag: 196608, sign: false },\n            FP16x16 { mag: 262144, sign: false },\n            FP16x16 { mag: 327680, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/linear_regressor_test.cairo",
        "content": "use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor, FP16x16TensorAdd};\nuse orion::operators::ml::linear::linear_regressor::{\n    LinearRegressorTrait, POST_TRANSFORM, LinearRegressor\n};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nuse core::debug::PrintTrait;\n\nuse orion::operators::nn::{NNTrait, FP16x16NN};\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_regressor() {\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 131072, sign: false },\n            FP16x16 { mag: 196608, sign: false },\n            FP16x16 { mag: 262144, sign: false },\n            FP16x16 { mag: 327680, sign: false },\n        ]\n            .span()\n    );\n\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 19661, sign: false }, FP16x16 { mag: 50463, sign: true },\n    ]\n        .span();\n\n    let intercepts: Span<FP16x16> = array![FP16x16 { mag: 32768, sign: false },].span();\n    let intercepts = Option::Some(intercepts);\n\n    let target: usize = 1;\n    let post_transform = POST_TRANSFORM::NONE;\n\n    let mut regressor: LinearRegressor<FP16x16> = LinearRegressor {\n        coefficients, intercepts, target, post_transform\n    };\n\n    let scores = LinearRegressorTrait::predict(regressor, X);\n\n    assert(*scores.data[0] == FP16x16 { mag: 17695, sign: true }, '*scores[0] == -0.27');\n    assert(*scores.data[1] == FP16x16 { mag: 79299, sign: true }, '*scores[1] == -1.21');\n    assert(*scores.data[2] == FP16x16 { mag: 140903, sign: true }, '*scores[2] == -2.15');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_linear_regressor_2() {\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 131072, sign: false },\n            FP16x16 { mag: 196608, sign: false },\n            FP16x16 { mag: 262144, sign: false },\n            FP16x16 { mag: 327680, sign: false },\n        ]\n            .span()\n    );\n\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 19661, sign: false },\n        FP16x16 { mag: 50463, sign: true },\n        FP16x16 { mag: 19661, sign: false },\n        FP16x16 { mag: 50463, sign: true },\n    ]\n        .span();\n\n    let intercepts: Span<FP16x16> = array![\n        FP16x16 { mag: 32768, sign: false }, FP16x16 { mag: 45875, sign: false },\n    ]\n        .span();\n    let intercepts = Option::Some(intercepts);\n\n    let target = 2;\n    let post_transform = POST_TRANSFORM::NONE;\n\n    let mut regressor: LinearRegressor<FP16x16> = LinearRegressor {\n        coefficients, intercepts, target, post_transform\n    };\n\n    let scores = LinearRegressorTrait::predict(regressor, X);\n\n    assert(*scores.data[0] == FP16x16 { mag: 17695, sign: true }, '*scores[0] == -0.27');\n    assert(*scores.data[1] == FP16x16 { mag: 4588, sign: true }, '*scores[1] == -0.07');\n    assert(*scores.data[2] == FP16x16 { mag: 79299, sign: true }, '*scores[2] == -1.21');\n    assert(*scores.data[3] == FP16x16 { mag: 66192, sign: true }, '*scores[3] == -1.01');\n    assert(*scores.data[4] == FP16x16 { mag: 140903, sign: true }, '*scores[4] == -2.15');\n    assert(*scores.data[5] == FP16x16 { mag: 127796, sign: true }, '*scores[5] == -1.95');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/normalizer_test.cairo",
        "content": "use orion::operators::ml::normalizer::normalizer::{NormalizerTrait, NORM};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\nuse orion::numbers::FP16x16;\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorDiv, FP16x16TensorPartialEq\n};\n\n#[test]\n#[available_gas(200000000000)]\nfn test_normalizer_max() {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 52428, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 26214, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 26214, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    let X = TensorTrait::new(shape.span(), data.span());\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 52428, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 21845, sign: false });\n    data.append(FP16x16 { mag: 43690, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    let expected_output = TensorTrait::new(shape.span(), data.span());\n\n    let actual_output = NormalizerTrait::predict(X, NORM::MAX);\n\n    assert_eq(actual_output, expected_output);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_normalizer_l1() {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 52428, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 26214, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 26214, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    let X = TensorTrait::new(shape.span(), data.span());\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 27306, sign: true });\n    data.append(FP16x16 { mag: 21845, sign: true });\n    data.append(FP16x16 { mag: 16384, sign: true });\n    data.append(FP16x16 { mag: 43690, sign: true });\n    data.append(FP16x16 { mag: 21845, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 10922, sign: false });\n    data.append(FP16x16 { mag: 21845, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    let expected_output = TensorTrait::new(shape.span(), data.span());\n\n    let actual_output = NormalizerTrait::predict(X, NORM::L1);\n\n    assert_eq(actual_output, expected_output);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_normalizer_l2() {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 52428, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 26214, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 26214, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    let X = TensorTrait::new(shape.span(), data.span());\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 46340, sign: true });\n    data.append(FP16x16 { mag: 37072, sign: true });\n    data.append(FP16x16 { mag: 27804, sign: true });\n    data.append(FP16x16 { mag: 58617, sign: true });\n    data.append(FP16x16 { mag: 29308, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 17515, sign: false });\n    data.append(FP16x16 { mag: 35030, sign: false });\n    data.append(FP16x16 { mag: 52545, sign: false });\n    let expected_output = TensorTrait::new(shape.span(), data.span());\n\n    let actual_output = NormalizerTrait::predict(X, NORM::L2);\n\n    assert_eq(actual_output, expected_output);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_normalizer_max_avoid_div_zero() {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    let X = TensorTrait::new(shape.span(), data.span());\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    let expected_output = TensorTrait::new(shape.span(), data.span());\n\n    let actual_output = NormalizerTrait::predict(X, NORM::MAX);\n\n    assert_eq(actual_output, expected_output);\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/svm_classifier_test.cairo",
        "content": "use orion::numbers::FP16x16;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\nuse orion::numbers::FP64x64;\nuse orion::operators::tensor::implementations::tensor_fp64x64::{\n    FP64x64Tensor, FP64x64TensorPartialEq\n};\n\nuse orion::operators::ml::svm::svm_classifier::{SVMClassifierTrait, POST_TRANSFORM, SVMClassifier};\nuse orion::operators::ml::svm::core::{KERNEL_TYPE};\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_sv_none() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let (mut classifier, X) = svm_classifier_binary_noprob_linear_sv(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 174499, sign: true },\n            FP16x16 { mag: 174499, sign: false },\n            FP16x16 { mag: 145149, sign: true },\n            FP16x16 { mag: 145149, sign: false },\n            FP16x16 { mag: 115799, sign: true },\n            FP16x16 { mag: 115799, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_sv_logistic() {\n    let post_transform = POST_TRANSFORM::LOGISTIC;\n    let (mut classifier, X) = svm_classifier_binary_noprob_linear_sv(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 4273, sign: false },\n            FP16x16 { mag: 61262, sign: false },\n            FP16x16 { mag: 6450, sign: false },\n            FP16x16 { mag: 59085, sign: false },\n            FP16x16 { mag: 9563, sign: false },\n            FP16x16 { mag: 55972, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_sv_softmax() {\n    let post_transform = POST_TRANSFORM::SOFTMAX;\n    let (mut classifier, X) = svm_classifier_binary_noprob_linear_sv(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 317, sign: false },\n            FP16x16 { mag: 65218, sign: false },\n            FP16x16 { mag: 771, sign: false },\n            FP16x16 { mag: 64764, sign: false },\n            FP16x16 { mag: 1858, sign: false },\n            FP16x16 { mag: 63677, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_sv_softmax_zero() {\n    let post_transform = POST_TRANSFORM::SOFTMAXZERO;\n    let (mut classifier, X) = svm_classifier_binary_noprob_linear_sv(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP16x16 { mag: 317, sign: false },\n            FP16x16 { mag: 65218, sign: false },\n            FP16x16 { mag: 771, sign: false },\n            FP16x16 { mag: 64764, sign: false },\n            FP16x16 { mag: 1858, sign: false },\n            FP16x16 { mag: 63677, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_none() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let (mut classifier, X) = svm_classifier_helper_noprob_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 7738, sign: true },\n            FP16x16 { mag: 29929, sign: true },\n            FP16x16 { mag: 27248, sign: false },\n            FP16x16 { mag: 21922, sign: false },\n            FP16x16 { mag: 4021, sign: true },\n            FP16x16 { mag: 15167, sign: true },\n            FP16x16 { mag: 4843, sign: false },\n            FP16x16 { mag: 5979, sign: false },\n            FP16x16 { mag: 304, sign: true },\n            FP16x16 { mag: 406, sign: true },\n            FP16x16 { mag: 17562, sign: true },\n            FP16x16 { mag: 9962, sign: true },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_logistic() {\n    let post_transform = POST_TRANSFORM::LOGISTIC;\n    let (mut classifier, X) = svm_classifier_helper_noprob_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 30835, sign: false },\n            FP16x16 { mag: 25413, sign: false },\n            FP16x16 { mag: 39483, sign: false },\n            FP16x16 { mag: 38197, sign: false },\n            FP16x16 { mag: 31762, sign: false },\n            FP16x16 { mag: 28992, sign: false },\n            FP16x16 { mag: 33978, sign: false },\n            FP16x16 { mag: 34261, sign: false },\n            FP16x16 { mag: 32691, sign: false },\n            FP16x16 { mag: 32666, sign: false },\n            FP16x16 { mag: 28403, sign: false },\n            FP16x16 { mag: 30282, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_softmax() {\n    let post_transform = POST_TRANSFORM::SOFTMAX;\n    let (mut classifier, X) = svm_classifier_helper_noprob_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 13131, sign: false },\n            FP16x16 { mag: 9359, sign: false },\n            FP16x16 { mag: 22396, sign: false },\n            FP16x16 { mag: 20648, sign: false },\n            FP16x16 { mag: 15779, sign: false },\n            FP16x16 { mag: 13311, sign: false },\n            FP16x16 { mag: 18064, sign: false },\n            FP16x16 { mag: 18380, sign: false },\n            FP16x16 { mag: 18054, sign: false },\n            FP16x16 { mag: 18026, sign: false },\n            FP16x16 { mag: 13874, sign: false },\n            FP16x16 { mag: 15580, sign: false },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_noprob_linear_softmax_zero() {\n    let post_transform = POST_TRANSFORM::SOFTMAXZERO;\n    let (mut classifier, X) = svm_classifier_helper_noprob_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 13131, sign: false },\n            FP16x16 { mag: 9359, sign: false },\n            FP16x16 { mag: 22396, sign: false },\n            FP16x16 { mag: 20648, sign: false },\n            FP16x16 { mag: 15779, sign: false },\n            FP16x16 { mag: 13311, sign: false },\n            FP16x16 { mag: 18064, sign: false },\n            FP16x16 { mag: 18380, sign: false },\n            FP16x16 { mag: 18054, sign: false },\n            FP16x16 { mag: 18026, sign: false },\n            FP16x16 { mag: 13874, sign: false },\n            FP16x16 { mag: 15580, sign: false },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_linear_none() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let (mut classifier, X) = svm_classifier_helper_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 7738, sign: true },\n            FP16x16 { mag: 29929, sign: true },\n            FP16x16 { mag: 27248, sign: false },\n            FP16x16 { mag: 21922, sign: false },\n            FP16x16 { mag: 4021, sign: true },\n            FP16x16 { mag: 15167, sign: true },\n            FP16x16 { mag: 4843, sign: false },\n            FP16x16 { mag: 5979, sign: false },\n            FP16x16 { mag: 304, sign: true },\n            FP16x16 { mag: 406, sign: true },\n            FP16x16 { mag: 17562, sign: true },\n            FP16x16 { mag: 9962, sign: true },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_linear_logistic() {\n    let post_transform = POST_TRANSFORM::LOGISTIC;\n    let (mut classifier, X) = svm_classifier_helper_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 30835, sign: false },\n            FP16x16 { mag: 25413, sign: false },\n            FP16x16 { mag: 39483, sign: false },\n            FP16x16 { mag: 38197, sign: false },\n            FP16x16 { mag: 31762, sign: false },\n            FP16x16 { mag: 28992, sign: false },\n            FP16x16 { mag: 33978, sign: false },\n            FP16x16 { mag: 34261, sign: false },\n            FP16x16 { mag: 32691, sign: false },\n            FP16x16 { mag: 32666, sign: false },\n            FP16x16 { mag: 28403, sign: false },\n            FP16x16 { mag: 30282, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_linear_softmax() {\n    let post_transform = POST_TRANSFORM::SOFTMAX;\n    let (mut classifier, X) = svm_classifier_helper_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 13131, sign: false },\n            FP16x16 { mag: 9359, sign: false },\n            FP16x16 { mag: 22396, sign: false },\n            FP16x16 { mag: 20648, sign: false },\n            FP16x16 { mag: 15779, sign: false },\n            FP16x16 { mag: 13311, sign: false },\n            FP16x16 { mag: 18064, sign: false },\n            FP16x16 { mag: 18380, sign: false },\n            FP16x16 { mag: 18054, sign: false },\n            FP16x16 { mag: 18026, sign: false },\n            FP16x16 { mag: 13874, sign: false },\n            FP16x16 { mag: 15580, sign: false },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_linear_softmax_zero() {\n    let post_transform = POST_TRANSFORM::SOFTMAXZERO;\n    let (mut classifier, X) = svm_classifier_helper_linear(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 2, 'labels[0]');\n    assert(*labels[1] == 3, 'labels[1]');\n    assert(*labels[2] == 0, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 4].span(),\n        array![\n            FP16x16 { mag: 13131, sign: false },\n            FP16x16 { mag: 9359, sign: false },\n            FP16x16 { mag: 22396, sign: false },\n            FP16x16 { mag: 20648, sign: false },\n            FP16x16 { mag: 15779, sign: false },\n            FP16x16 { mag: 13311, sign: false },\n            FP16x16 { mag: 18064, sign: false },\n            FP16x16 { mag: 18380, sign: false },\n            FP16x16 { mag: 18054, sign: false },\n            FP16x16 { mag: 18026, sign: false },\n            FP16x16 { mag: 13874, sign: false },\n            FP16x16 { mag: 15580, sign: false },\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_binary_none_fp64x64() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let (mut classifier, X) = svm_classifier_helper_fp64x64(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP64x64> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP64x64 { mag: 18322911080742739968, sign: false },\n            FP64x64 { mag: 123832992966812224, sign: false },\n            FP64x64 { mag: 8658920114943337472, sign: false },\n            FP64x64 { mag: 9787823958766215168, sign: false },\n            FP64x64 { mag: 276645820873422144, sign: false },\n            FP64x64 { mag: 18170098252836128768, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_binary_logistic_fp64x64() {\n    let post_transform = POST_TRANSFORM::LOGISTIC;\n    let (mut classifier, X) = svm_classifier_helper_fp64x64(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP64x64> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP64x64 { mag: 13461271680116586496, sign: false },\n            FP64x64 { mag: 9254325673410459648, sign: false },\n            FP64x64 { mag: 11349211717397211136, sign: false },\n            FP64x64 { mag: 11614494343921229824, sign: false },\n            FP64x64 { mag: 9292528880387112960, sign: false },\n            FP64x64 { mag: 13431074360067923968, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_binary_softmax_fp64x64() {\n    let post_transform = POST_TRANSFORM::SOFTMAX;\n    let (mut classifier, X) = svm_classifier_helper_fp64x64(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP64x64> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP64x64 { mag: 13436811297474848768, sign: false },\n            FP64x64 { mag: 5009932776234703872, sign: false },\n            FP64x64 { mag: 8941229086247388160, sign: false },\n            FP64x64 { mag: 9505514987462162432, sign: false },\n            FP64x64 { mag: 5070622564237207552, sign: false },\n            FP64x64 { mag: 13376121509472344064, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_classifier_binary_softmax_zero_fp64x64() {\n    let post_transform = POST_TRANSFORM::SOFTMAXZERO;\n    let (mut classifier, X) = svm_classifier_helper_fp64x64(post_transform);\n\n    let (labels, scores) = SVMClassifierTrait::predict(ref classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 1, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    let mut expected_scores: Tensor<FP64x64> = TensorTrait::new(\n        array![3, 2].span(),\n        array![\n            FP64x64 { mag: 13436811297474848768, sign: false },\n            FP64x64 { mag: 5009932776234703872, sign: false },\n            FP64x64 { mag: 8941229086247388160, sign: false },\n            FP64x64 { mag: 9505514987462162432, sign: false },\n            FP64x64 { mag: 5070622564237207552, sign: false },\n            FP64x64 { mag: 13376121509472344064, sign: false }\n        ]\n            .span()\n    );\n\n    assert_eq(scores, expected_scores);\n}\n\n\n// ============ HELPER ============ //\n\nfn svm_classifier_helper_linear(\n    post_transform: POST_TRANSFORM\n) -> (SVMClassifier<FP16x16>, Tensor<FP16x16>) {\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 10169, sign: true },\n        FP16x16 { mag: 15905, sign: false },\n        FP16x16 { mag: 459, sign: false },\n        FP16x16 { mag: 26713, sign: false },\n        FP16x16 { mag: 2129, sign: true },\n        FP16x16 { mag: 18, sign: false },\n        FP16x16 { mag: 12830, sign: true },\n        FP16x16 { mag: 23097, sign: true },\n        FP16x16 { mag: 1415, sign: true },\n        FP16x16 { mag: 28717, sign: true },\n        FP16x16 { mag: 2994, sign: false },\n        FP16x16 { mag: 847, sign: true }\n    ]\n        .span();\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 65, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::LINEAR;\n    let prob_a: Span<FP16x16> = array![FP16x16 { mag: 336797, sign: true }].span();\n    let prob_b: Span<FP16x16> = array![FP16x16 { mag: 4194, sign: false }].span();\n    let rho: Span<FP16x16> = array![\n        FP16x16 { mag: 4908, sign: true },\n        FP16x16 { mag: 11563, sign: true },\n        FP16x16 { mag: 13872, sign: true },\n        FP16x16 { mag: 33829, sign: true }\n    ]\n        .span();\n\n    let support_vectors: Span<FP16x16> = array![].span();\n    let classlabels: Span<usize> = array![0, 1, 2, 3].span();\n\n    let vectors_per_class = Option::None;\n\n    let mut classifier: SVMClassifier<FP16x16> = SVMClassifier {\n        classlabels,\n        coefficients,\n        kernel_params,\n        kernel_type,\n        post_transform,\n        prob_a,\n        prob_b,\n        rho,\n        support_vectors,\n        vectors_per_class,\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 65536, sign: true },\n            FP16x16 { mag: 52428, sign: true },\n            FP16x16 { mag: 39321, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 26214, sign: false },\n            FP16x16 { mag: 39321, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n\nfn svm_classifier_binary_noprob_linear_sv(\n    post_transform: POST_TRANSFORM\n) -> (SVMClassifier<FP16x16>, Tensor<FP16x16>) {\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 50226, sign: false },\n        FP16x16 { mag: 5711, sign: false },\n        FP16x16 { mag: 7236, sign: false },\n        FP16x16 { mag: 63175, sign: true }\n    ]\n        .span();\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 8025, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::LINEAR;\n    let prob_a: Span<FP16x16> = array![].span();\n    let prob_b: Span<FP16x16> = array![].span();\n    let rho: Span<FP16x16> = array![FP16x16 { mag: 146479, sign: false }].span();\n\n    let support_vectors: Span<FP16x16> = array![\n        FP16x16 { mag: 314572, sign: false },\n        FP16x16 { mag: 222822, sign: false },\n        FP16x16 { mag: 124518, sign: false },\n        FP16x16 { mag: 327680, sign: false },\n        FP16x16 { mag: 196608, sign: false },\n        FP16x16 { mag: 104857, sign: false },\n        FP16x16 { mag: 294912, sign: false },\n        FP16x16 { mag: 150732, sign: false },\n        FP16x16 { mag: 85196, sign: false },\n        FP16x16 { mag: 334233, sign: false },\n        FP16x16 { mag: 163840, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let classlabels: Span<usize> = array![0, 1].span();\n\n    let vectors_per_class = Option::Some(array![3, 1].span());\n\n    let mut classifier: SVMClassifier<FP16x16> = SVMClassifier {\n        classlabels,\n        coefficients,\n        kernel_params,\n        kernel_type,\n        post_transform,\n        prob_a,\n        prob_b,\n        rho,\n        support_vectors,\n        vectors_per_class,\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 65536, sign: true },\n            FP16x16 { mag: 52428, sign: true },\n            FP16x16 { mag: 39321, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 26214, sign: false },\n            FP16x16 { mag: 39321, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n\nfn svm_classifier_helper_noprob_linear(\n    post_transform: POST_TRANSFORM\n) -> (SVMClassifier<FP16x16>, Tensor<FP16x16>) {\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 10169, sign: true },\n        FP16x16 { mag: 15905, sign: false },\n        FP16x16 { mag: 459, sign: false },\n        FP16x16 { mag: 26713, sign: false },\n        FP16x16 { mag: 2129, sign: true },\n        FP16x16 { mag: 18, sign: false },\n        FP16x16 { mag: 12830, sign: true },\n        FP16x16 { mag: 23097, sign: true },\n        FP16x16 { mag: 1415, sign: true },\n        FP16x16 { mag: 28717, sign: true },\n        FP16x16 { mag: 2994, sign: false },\n        FP16x16 { mag: 847, sign: true }\n    ]\n        .span();\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 65, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::LINEAR;\n    let prob_a: Span<FP16x16> = array![].span();\n    let prob_b: Span<FP16x16> = array![].span();\n    let rho: Span<FP16x16> = array![\n        FP16x16 { mag: 4908, sign: true },\n        FP16x16 { mag: 11563, sign: true },\n        FP16x16 { mag: 13872, sign: true },\n        FP16x16 { mag: 33829, sign: true }\n    ]\n        .span();\n\n    let support_vectors: Span<FP16x16> = array![].span();\n    let classlabels: Span<usize> = array![0, 1, 2, 3].span();\n\n    let vectors_per_class = Option::None;\n\n    let mut classifier: SVMClassifier<FP16x16> = SVMClassifier {\n        classlabels,\n        coefficients,\n        kernel_params,\n        kernel_type,\n        post_transform,\n        prob_a,\n        prob_b,\n        rho,\n        support_vectors,\n        vectors_per_class,\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 65536, sign: true },\n            FP16x16 { mag: 52428, sign: true },\n            FP16x16 { mag: 39321, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 26214, sign: false },\n            FP16x16 { mag: 39321, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n\nfn svm_classifier_helper_fp64x64(\n    post_transform: POST_TRANSFORM\n) -> (SVMClassifier<FP64x64>, Tensor<FP64x64>) {\n    let coefficients: Span<FP64x64> = array![\n        FP64x64 { mag: 18446744073709551616, sign: false },\n        FP64x64 { mag: 18446744073709551616, sign: false },\n        FP64x64 { mag: 18446744073709551616, sign: false },\n        FP64x64 { mag: 18446744073709551616, sign: false },\n        FP64x64 { mag: 18446744073709551616, sign: true },\n        FP64x64 { mag: 18446744073709551616, sign: true },\n        FP64x64 { mag: 18446744073709551616, sign: true },\n        FP64x64 { mag: 18446744073709551616, sign: true }\n    ]\n        .span();\n    let kernel_params: Span<FP64x64> = array![\n        FP64x64 { mag: 7054933896252620800, sign: false },\n        FP64x64 { mag: 0, sign: false },\n        FP64x64 { mag: 55340232221128654848, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::RBF;\n    let prob_a: Span<FP64x64> = array![FP64x64 { mag: 94799998099962986496, sign: true }].span();\n    let prob_b: Span<FP64x64> = array![FP64x64 { mag: 1180576833385529344, sign: false }].span();\n    let rho: Span<FP64x64> = array![FP64x64 { mag: 3082192501545631744, sign: false }].span();\n\n    let support_vectors: Span<FP64x64> = array![\n        FP64x64 { mag: 3528081300248330240, sign: false },\n        FP64x64 { mag: 19594207602596118528, sign: true },\n        FP64x64 { mag: 9235613999318433792, sign: false },\n        FP64x64 { mag: 10869715877100519424, sign: true },\n        FP64x64 { mag: 5897111318564962304, sign: true },\n        FP64x64 { mag: 1816720038917308416, sign: false },\n        FP64x64 { mag: 4564890528671334400, sign: false },\n        FP64x64 { mag: 21278987070814027776, sign: true },\n        FP64x64 { mag: 7581529597213147136, sign: false },\n        FP64x64 { mag: 10953113834067329024, sign: true },\n        FP64x64 { mag: 24318984989010034688, sign: true },\n        FP64x64 { mag: 30296187483321270272, sign: true },\n        FP64x64 { mag: 10305112258191032320, sign: false },\n        FP64x64 { mag: 17005441559857987584, sign: true },\n        FP64x64 { mag: 11555205301925838848, sign: false },\n        FP64x64 { mag: 2962701975885447168, sign: true },\n        FP64x64 { mag: 11741665981322231808, sign: true },\n        FP64x64 { mag: 15376232508819505152, sign: false },\n        FP64x64 { mag: 13908474645692022784, sign: false },\n        FP64x64 { mag: 7323415394302033920, sign: true },\n        FP64x64 { mag: 3284258824352956416, sign: true },\n        FP64x64 { mag: 11374683084831064064, sign: true },\n        FP64x64 { mag: 9087138148126818304, sign: false },\n        FP64x64 { mag: 8247488946750095360, sign: false }\n    ]\n        .span();\n    let classlabels: Span<usize> = array![0, 1].span();\n\n    let vectors_per_class = Option::Some(array![4, 4].span());\n\n    let mut classifier: SVMClassifier<FP64x64> = SVMClassifier {\n        classlabels,\n        coefficients,\n        kernel_params,\n        kernel_type,\n        post_transform,\n        prob_a,\n        prob_b,\n        rho,\n        support_vectors,\n        vectors_per_class,\n    };\n\n    let mut X: Tensor<FP64x64> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP64x64 { mag: 18446744073709551616, sign: true },\n            FP64x64 { mag: 14757395258967642112, sign: true },\n            FP64x64 { mag: 11068046444225730560, sign: true },\n            FP64x64 { mag: 7378697629483821056, sign: true },\n            FP64x64 { mag: 3689348814741910528, sign: true },\n            FP64x64 { mag: 0, sign: false },\n            FP64x64 { mag: 3689348814741910528, sign: false },\n            FP64x64 { mag: 7378697629483821056, sign: false },\n            FP64x64 { mag: 11068046444225730560, sign: false }\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/svm_regressor_test.cairo",
        "content": "use orion::numbers::FP16x16;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\nuse orion::operators::ml::svm::svm_regressor::{SVMRegressorTrait, POST_TRANSFORM, SVMRegressor};\nuse orion::operators::ml::svm::core::{KERNEL_TYPE};\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_linear() {\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 27812, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::LINEAR;\n    let (mut regressor, X) = svm_regressor_helper(kernel_type, kernel_params);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 30684, sign: true },\n            FP16x16 { mag: 14908, sign: false },\n            FP16x16 { mag: 60501, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_poly() {\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 22456, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n\n    let kernel_type = KERNEL_TYPE::POLY;\n    let (mut regressor, X) = svm_regressor_helper(kernel_type, kernel_params);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 34542, sign: false },\n            FP16x16 { mag: 35623, sign: false },\n            FP16x16 { mag: 35815, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_rbf() {\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 19848, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::RBF;\n    let (mut regressor, X) = svm_regressor_helper(kernel_type, kernel_params);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 19376, sign: false },\n            FP16x16 { mag: 31318, sign: false },\n            FP16x16 { mag: 45566, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_sigmoid() {\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 20108, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::SIGMOID;\n    let (mut regressor, X) = svm_regressor_helper(kernel_type, kernel_params);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 15683, sign: false },\n            FP16x16 { mag: 29421, sign: false },\n            FP16x16 { mag: 43364, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_linear_one_class_0() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let one_class = 0;\n    let (mut regressor, X) = svm_regressor_linear_helper(post_transform, one_class);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 63484, sign: false },\n            FP16x16 { mag: 74218, sign: false },\n            FP16x16 { mag: 84953, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_svm_regressor_linear_one_class_1() {\n    let post_transform = POST_TRANSFORM::NONE;\n    let one_class = 1;\n    let (mut regressor, X) = svm_regressor_linear_helper(post_transform, one_class);\n\n    let scores = SVMRegressorTrait::predict(ref regressor, X);\n\n    let mut expected_scores: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 1].span(),\n        array![\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n        ]\n            .span()\n    );\n    assert_eq(scores, expected_scores);\n}\n\n\n// ============ HELPER ============ //\n\nfn svm_regressor_helper(\n    kernel_type: KERNEL_TYPE, kernel_params: Span<FP16x16>\n) -> (SVMRegressor<FP16x16>, Tensor<FP16x16>) {\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: true },\n        FP16x16 { mag: 54959, sign: false },\n        FP16x16 { mag: 54959, sign: true },\n        FP16x16 { mag: 29299, sign: false },\n        FP16x16 { mag: 65536, sign: true },\n        FP16x16 { mag: 36236, sign: false }\n    ]\n        .span();\n\n    let n_supports: usize = 7;\n    let one_class: usize = 0;\n    let rho: Span<FP16x16> = array![FP16x16 { mag: 35788, sign: false }].span();\n\n    let support_vectors: Span<FP16x16> = array![\n        FP16x16 { mag: 8421, sign: true },\n        FP16x16 { mag: 5842, sign: false },\n        FP16x16 { mag: 4510, sign: false },\n        FP16x16 { mag: 5202, sign: true },\n        FP16x16 { mag: 14783, sign: true },\n        FP16x16 { mag: 17380, sign: true },\n        FP16x16 { mag: 60595, sign: false },\n        FP16x16 { mag: 1674, sign: true },\n        FP16x16 { mag: 38669, sign: true },\n        FP16x16 { mag: 63803, sign: false },\n        FP16x16 { mag: 87720, sign: true },\n        FP16x16 { mag: 22236, sign: false },\n        FP16x16 { mag: 61816, sign: false },\n        FP16x16 { mag: 34267, sign: true },\n        FP16x16 { mag: 36418, sign: false },\n        FP16x16 { mag: 27471, sign: false },\n        FP16x16 { mag: 28421, sign: false },\n        FP16x16 { mag: 69270, sign: true },\n        FP16x16 { mag: 152819, sign: false },\n        FP16x16 { mag: 4065, sign: false },\n        FP16x16 { mag: 62274, sign: true }\n    ]\n        .span();\n\n    let post_transform = POST_TRANSFORM::NONE;\n\n    let mut regressor: SVMRegressor<FP16x16> = SVMRegressor {\n        coefficients,\n        kernel_params,\n        kernel_type,\n        n_supports,\n        one_class,\n        post_transform,\n        rho,\n        support_vectors,\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 32768, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 19660, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 6553, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 6553, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 19660, sign: false },\n        ]\n            .span()\n    );\n\n    (regressor, X)\n}\n\nfn svm_regressor_linear_helper(\n    post_transform: POST_TRANSFORM, one_class: usize\n) -> (SVMRegressor<FP16x16>, Tensor<FP16x16>) {\n    let coefficients: Span<FP16x16> = array![\n        FP16x16 { mag: 18540, sign: false },\n        FP16x16 { mag: 1746, sign: true },\n        FP16x16 { mag: 1097, sign: false }\n    ]\n        .span();\n    let kernel_params: Span<FP16x16> = array![\n        FP16x16 { mag: 65, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 196608, sign: false }\n    ]\n        .span();\n    let kernel_type = KERNEL_TYPE::LINEAR;\n    let n_supports: usize = 0;\n    let rho: Span<FP16x16> = array![FP16x16 { mag: 81285, sign: false }].span();\n\n    let support_vectors: Span<FP16x16> = array![].span();\n\n    let mut regressor: SVMRegressor<FP16x16> = SVMRegressor {\n        coefficients,\n        kernel_params,\n        kernel_type,\n        n_supports,\n        one_class,\n        post_transform,\n        rho,\n        support_vectors,\n    };\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 65536, sign: true },\n            FP16x16 { mag: 52428, sign: true },\n            FP16x16 { mag: 39321, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 26214, sign: false },\n            FP16x16 { mag: 39321, sign: false },\n        ]\n            .span()\n    );\n\n    (regressor, X)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/tree_ensemble_classifier.cairo",
        "content": "use orion::numbers::FP16x16;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\nuse orion::operators::ml::tree_ensemble::core::{NODE_MODES, TreeEnsembleAttributes, TreeEnsemble};\nuse orion::operators::ml::tree_ensemble::tree_ensemble_classifier::{\n    TreeEnsembleClassifier, POST_TRANSFORM, TreeEnsembleClassifierTrait\n};\nuse orion::operators::tensor::implementations::tensor_fp16x16::relative_eq;\nuse orion::operators::matrix::{MutMatrix, MutMatrixImpl};\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_multi_pt_none() {\n    let (mut classifier, X) = tree_ensemble_classifier_helper(POST_TRANSFORM::NONE);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 60075, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 0, sign: false }) == true,\n        'score[0, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 2).unwrap(), @FP16x16 { mag: 5461, sign: false }) == true,\n        'score[0, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 0).unwrap(), @FP16x16 { mag: 37329, sign: false }) == true,\n        'score[1, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 1).unwrap(), @FP16x16 { mag: 12528, sign: false }) == true,\n        'score[1, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 2).unwrap(), @FP16x16 { mag: 15677, sign: false }) == true,\n        'score[1, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 0).unwrap(), @FP16x16 { mag: 19853, sign: false }) == true,\n        'score[2, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 1).unwrap(), @FP16x16 { mag: 28257, sign: false }) == true,\n        'score[2, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 2).unwrap(), @FP16x16 { mag: 17424, sign: false }) == true,\n        'score[2, 2]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_multi_pt_softmax() {\n    let (mut classifier, X) = tree_ensemble_classifier_helper(POST_TRANSFORM::SOFTMAX);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0]');\n    assert(*labels[1] == 0, 'labels[1]');\n    assert(*labels[2] == 1, 'labels[2]');\n    assert(labels.len() == 3, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 35725, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 14284, sign: false }) == true,\n        'score[0, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 2).unwrap(), @FP16x16 { mag: 15526, sign: false }) == true,\n        'score[0, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 0).unwrap(), @FP16x16 { mag: 27266, sign: false }) == true,\n        'score[1, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 1).unwrap(), @FP16x16 { mag: 18675, sign: false }) == true,\n        'score[1, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 2).unwrap(), @FP16x16 { mag: 19594, sign: false }) == true,\n        'score[1, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 0).unwrap(), @FP16x16 { mag: 21137, sign: false }) == true,\n        'score[2, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 1).unwrap(), @FP16x16 { mag: 24029, sign: false }) == true,\n        'score[2, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 2).unwrap(), @FP16x16 { mag: 20368, sign: false }) == true,\n        'score[2, 2]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_multi_pt_softmax_zero() {\n    let (mut classifier, X) = tree_ensemble_classifier_helper(POST_TRANSFORM::SOFTMAXZERO);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0] == 0');\n    assert(*labels[1] == 0, 'labels[1] == 0');\n    assert(*labels[2] == 1, 'labels[2] == 1');\n    assert(labels.len() == 3, 'len(labels) == 3');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 45682, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 0, sign: false }) == true,\n        'score[0, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 2).unwrap(), @FP16x16 { mag: 19853, sign: false }) == true,\n        'score[0, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 0).unwrap(), @FP16x16 { mag: 27266, sign: false }) == true,\n        'score[1, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 1).unwrap(), @FP16x16 { mag: 18675, sign: false }) == true,\n        'score[1, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 2).unwrap(), @FP16x16 { mag: 19594, sign: false }) == true,\n        'score[1, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 0).unwrap(), @FP16x16 { mag: 21137, sign: false }) == true,\n        'score[2, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 1).unwrap(), @FP16x16 { mag: 24029, sign: false }) == true,\n        'score[2, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 2).unwrap(), @FP16x16 { mag: 20368, sign: false }) == true,\n        'score[2, 2]'\n    );\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_multi_pt_logistic() {\n    let (mut classifier, X) = tree_ensemble_classifier_helper(POST_TRANSFORM::LOGISTIC);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 0, 'labels[0] == 0');\n    assert(*labels[1] == 0, 'labels[1] == 0');\n    assert(*labels[2] == 1, 'labels[2] == 1');\n    assert(labels.len() == 3, 'len(labels) == 3');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 46816, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 32768, sign: false }) == true,\n        'score[0, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 2).unwrap(), @FP16x16 { mag: 34132, sign: false }) == true,\n        'score[0, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 0).unwrap(), @FP16x16 { mag: 41856, sign: false }) == true,\n        'score[1, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 1).unwrap(), @FP16x16 { mag: 35890, sign: false }) == true,\n        'score[1, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(1, 2).unwrap(), @FP16x16 { mag: 36668, sign: false }) == true,\n        'score[1, 2]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 0).unwrap(), @FP16x16 { mag: 37693, sign: false }) == true,\n        'score[2, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 1).unwrap(), @FP16x16 { mag: 39724, sign: false }) == true,\n        'score[2, 1]'\n    );\n    assert(\n        relative_eq(@scores.get(2, 2).unwrap(), @FP16x16 { mag: 37098, sign: false }) == true,\n        'score[2, 2]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_binary_none() {\n    let (mut classifier, X) = tree_ensemble_classifier_binary_class_helper(POST_TRANSFORM::NONE);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(labels.len() == 1, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 0, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 65536, sign: false }) == true,\n        'score[0, 1]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_binary_logistic() {\n    let (mut classifier, X) = tree_ensemble_classifier_binary_class_helper(\n        POST_TRANSFORM::LOGISTIC\n    );\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(labels.len() == 1, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 17625, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 47910, sign: false }) == true,\n        'score[0, 1]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_binary_softmax() {\n    let (mut classifier, X) = tree_ensemble_classifier_binary_class_helper(POST_TRANSFORM::SOFTMAX);\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(labels.len() == 1, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 7812, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 57723, sign: false }) == true,\n        'score[0, 1]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_classifier_binary_softmax_zero() {\n    let (mut classifier, X) = tree_ensemble_classifier_binary_class_helper(\n        POST_TRANSFORM::SOFTMAXZERO\n    );\n\n    let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n    // ASSERT LABELS\n    assert(*labels[0] == 1, 'labels[0]');\n    assert(labels.len() == 1, 'len(labels)');\n\n    // ASSERT SCORES\n    assert(\n        relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 7812, sign: false }) == true,\n        'score[0, 0]'\n    );\n    assert(\n        relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 57723, sign: false }) == true,\n        'score[0, 1]'\n    );\n}\n\n// #[test]\n// #[available_gas(200000000000)]\n// fn test_tree_ensemble_classifier_binary_probit() {\n//     let (mut classifier, X) = tree_ensemble_classifier_binary_class_helper(POST_TRANSFORM::PROBIT);\n\n//     let (labels, mut scores) = TreeEnsembleClassifierTrait::predict(classifier, X);\n\n//     // ASSERT LABELS\n//     assert(*labels[0] == 1, 'labels[0]');\n//     assert(labels.len() == 1, 'len(labels)');\n\n//     // ASSERT SCORES\n//     assert(\n//         relative_eq(@scores.get(0, 0).unwrap(), @FP16x16 { mag: 0, sign: false }) == true,\n//         'score[0, 0]'\n//     );\n//     assert(\n//         relative_eq(@scores.get(0, 1).unwrap(), @FP16x16 { mag: 65536, sign: false }) == true,\n//         'score[0, 1]'\n//     );\n// }\n\n// ============ HELPER ============ //\n\nfn tree_ensemble_classifier_helper(\n    post_transform: POST_TRANSFORM\n) -> (TreeEnsembleClassifier<FP16x16>, Tensor<FP16x16>) {\n    let class_ids: Span<usize> = array![0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]\n        .span();\n\n    let class_nodeids: Span<usize> = array![2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 1, 1, 3, 3, 3, 4, 4, 4]\n        .span();\n\n    let class_treeids: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n        .span();\n\n    let class_weights: Span<FP16x16> = array![\n        FP16x16 { mag: 30583, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 2185, sign: false },\n        FP16x16 { mag: 13107, sign: false },\n        FP16x16 { mag: 15729, sign: false },\n        FP16x16 { mag: 3932, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 3277, sign: false },\n        FP16x16 { mag: 6746, sign: false },\n        FP16x16 { mag: 12529, sign: false },\n        FP16x16 { mag: 13493, sign: false },\n    ]\n        .span();\n\n    let classlabels: Span<usize> = array![0, 1, 2].span();\n\n    let nodes_falsenodeids: Span<usize> = array![4, 3, 0, 0, 0, 2, 0, 4, 0, 0].span();\n\n    let nodes_featureids: Span<usize> = array![1, 0, 0, 0, 0, 1, 0, 0, 0, 0].span();\n\n    let nodes_missing_value_tracks_true: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 0].span();\n\n    let nodes_modes: Span<NODE_MODES> = array![\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n    ]\n        .span();\n\n    let nodes_nodeids: Span<usize> = array![0, 1, 2, 3, 4, 0, 1, 2, 3, 4].span();\n\n    let nodes_treeids: Span<usize> = array![0, 0, 0, 0, 0, 1, 1, 1, 1, 1].span();\n\n    let nodes_truenodeids: Span<usize> = array![1, 2, 0, 0, 0, 1, 0, 3, 0, 0].span();\n\n    let nodes_values: Span<FP16x16> = array![\n        FP16x16 { mag: 81892, sign: false },\n        FP16x16 { mag: 19992, sign: true },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 110300, sign: true },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 44245, sign: true },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n    ]\n        .span();\n\n    let tree_ids: Span<usize> = array![0, 1].span();\n\n    let mut root_index: Felt252Dict<usize> = Default::default();\n    root_index.insert(0, 0);\n    root_index.insert(1, 5);\n\n    let mut node_index: Felt252Dict<usize> = Default::default();\n    node_index\n        .insert(2089986280348253421170679821480865132823066470938446095505822317253594081284, 0);\n    node_index\n        .insert(2001140082530619239661729809084578298299223810202097622761632384561112390979, 1);\n    node_index\n        .insert(2592670241084192212354027440049085852792506518781954896144296316131790403900, 2);\n    node_index\n        .insert(2960591271376829378356567803618548672034867345123727178628869426548453833420, 3);\n    node_index\n        .insert(458933264452572171106695256465341160654132084710250671055261382009315664425, 4);\n    node_index\n        .insert(1089549915800264549621536909767699778745926517555586332772759280702396009108, 5);\n    node_index\n        .insert(1321142004022994845681377299801403567378503530250467610343381590909832171180, 6);\n    node_index\n        .insert(2592987851775965742543459319508348457290966253241455514226127639100457844774, 7);\n    node_index\n        .insert(2492755623019086109032247218615964389726368532160653497039005814484393419348, 8);\n    node_index\n        .insert(1323616023845704258113538348000047149470450086307731200728039607710316625916, 9);\n\n    let atts = TreeEnsembleAttributes {\n        nodes_falsenodeids,\n        nodes_featureids,\n        nodes_missing_value_tracks_true,\n        nodes_modes,\n        nodes_nodeids,\n        nodes_treeids,\n        nodes_truenodeids,\n        nodes_values\n    };\n\n    let mut ensemble: TreeEnsemble<FP16x16> = TreeEnsemble {\n        atts, tree_ids, root_index, node_index\n    };\n\n    let base_values: Option<Span<FP16x16>> = Option::None;\n\n    let mut classifier: TreeEnsembleClassifier<FP16x16> = TreeEnsembleClassifier {\n        ensemble,\n        class_ids,\n        class_nodeids,\n        class_treeids,\n        class_weights,\n        classlabels,\n        base_values,\n        post_transform\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 65536, sign: true },\n            FP16x16 { mag: 52429, sign: true },\n            FP16x16 { mag: 39322, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 26214, sign: false },\n            FP16x16 { mag: 39322, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n\n// ============ BINARY CLASS HELPER ============ //\n\nfn tree_ensemble_classifier_binary_class_helper(\n    post_transform: POST_TRANSFORM\n) -> (TreeEnsembleClassifier<FP16x16>, Tensor<FP16x16>) {\n    let class_ids: Span<usize> = array![\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let class_nodeids: Span<usize> = array![\n        4,\n        5,\n        7,\n        10,\n        12,\n        13,\n        15,\n        17,\n        19,\n        20,\n        24,\n        26,\n        29,\n        31,\n        32,\n        33,\n        37,\n        38,\n        39,\n        40,\n        46,\n        49,\n        50,\n        52,\n        56,\n        57,\n        58,\n        59,\n        62,\n        64,\n        66,\n        67,\n        68,\n        73,\n        74,\n        75,\n        76,\n        81,\n        82,\n        83,\n        84,\n        88,\n        89,\n        91,\n        93,\n        94,\n        95,\n        98,\n        99,\n        101,\n        104,\n        106,\n        107,\n        108,\n        112,\n        113,\n        114,\n        115,\n        119,\n        121,\n        124,\n        125,\n        127,\n        128,\n        130,\n        131,\n        138,\n        140,\n        141,\n        142,\n        143,\n        148,\n        149,\n        150,\n        151,\n        152,\n        153,\n        154\n    ]\n        .span();\n    let class_treeids: Span<usize> = array![\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let class_weights: Span<FP16x16> = array![\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 43690, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 65536, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 65536, sign: false }\n    ]\n        .span();\n    let classlabels: Span<usize> = array![0, 1].span();\n    let nodes_falsenodeids: Span<usize> = array![\n        116,\n        21,\n        6,\n        5,\n        0,\n        0,\n        8,\n        0,\n        14,\n        11,\n        0,\n        13,\n        0,\n        0,\n        16,\n        0,\n        18,\n        0,\n        20,\n        0,\n        0,\n        41,\n        34,\n        25,\n        0,\n        27,\n        0,\n        33,\n        30,\n        0,\n        32,\n        0,\n        0,\n        0,\n        40,\n        39,\n        38,\n        0,\n        0,\n        0,\n        0,\n        109,\n        96,\n        69,\n        60,\n        47,\n        0,\n        51,\n        50,\n        0,\n        0,\n        53,\n        0,\n        59,\n        58,\n        57,\n        0,\n        0,\n        0,\n        0,\n        68,\n        63,\n        0,\n        65,\n        0,\n        67,\n        0,\n        0,\n        0,\n        77,\n        76,\n        75,\n        74,\n        0,\n        0,\n        0,\n        0,\n        85,\n        84,\n        83,\n        82,\n        0,\n        0,\n        0,\n        0,\n        95,\n        90,\n        89,\n        0,\n        0,\n        92,\n        0,\n        94,\n        0,\n        0,\n        0,\n        100,\n        99,\n        0,\n        0,\n        102,\n        0,\n        108,\n        105,\n        0,\n        107,\n        0,\n        0,\n        0,\n        115,\n        114,\n        113,\n        0,\n        0,\n        0,\n        0,\n        132,\n        129,\n        120,\n        0,\n        122,\n        0,\n        126,\n        125,\n        0,\n        0,\n        128,\n        0,\n        0,\n        131,\n        0,\n        0,\n        154,\n        153,\n        144,\n        143,\n        142,\n        139,\n        0,\n        141,\n        0,\n        0,\n        0,\n        0,\n        152,\n        151,\n        150,\n        149,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let nodes_featureids: Span<usize> = array![\n        3,\n        2,\n        4,\n        8,\n        0,\n        0,\n        1,\n        0,\n        2,\n        7,\n        0,\n        0,\n        0,\n        0,\n        7,\n        0,\n        0,\n        0,\n        6,\n        0,\n        0,\n        8,\n        0,\n        2,\n        0,\n        7,\n        0,\n        7,\n        2,\n        0,\n        2,\n        0,\n        0,\n        0,\n        2,\n        6,\n        7,\n        0,\n        0,\n        0,\n        0,\n        7,\n        7,\n        0,\n        7,\n        1,\n        0,\n        0,\n        2,\n        0,\n        0,\n        2,\n        0,\n        2,\n        2,\n        6,\n        0,\n        0,\n        0,\n        0,\n        2,\n        0,\n        0,\n        1,\n        0,\n        6,\n        0,\n        0,\n        0,\n        0,\n        2,\n        6,\n        7,\n        0,\n        0,\n        0,\n        0,\n        6,\n        7,\n        2,\n        0,\n        0,\n        0,\n        0,\n        0,\n        2,\n        2,\n        7,\n        0,\n        0,\n        2,\n        0,\n        0,\n        0,\n        0,\n        0,\n        6,\n        1,\n        0,\n        0,\n        4,\n        0,\n        2,\n        2,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        1,\n        2,\n        0,\n        0,\n        0,\n        0,\n        6,\n        0,\n        7,\n        0,\n        0,\n        0,\n        1,\n        3,\n        0,\n        0,\n        2,\n        0,\n        0,\n        8,\n        0,\n        0,\n        2,\n        2,\n        2,\n        4,\n        7,\n        3,\n        0,\n        1,\n        0,\n        0,\n        0,\n        0,\n        4,\n        3,\n        7,\n        8,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let nodes_missing_value_tracks_true: Span<usize> = array![\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let nodes_modes: Span<NODE_MODES> = array![\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF\n    ]\n        .span();\n    let nodes_nodeids: Span<usize> = array![\n        0,\n        1,\n        2,\n        3,\n        4,\n        5,\n        6,\n        7,\n        8,\n        9,\n        10,\n        11,\n        12,\n        13,\n        14,\n        15,\n        16,\n        17,\n        18,\n        19,\n        20,\n        21,\n        22,\n        23,\n        24,\n        25,\n        26,\n        27,\n        28,\n        29,\n        30,\n        31,\n        32,\n        33,\n        34,\n        35,\n        36,\n        37,\n        38,\n        39,\n        40,\n        41,\n        42,\n        43,\n        44,\n        45,\n        46,\n        47,\n        48,\n        49,\n        50,\n        51,\n        52,\n        53,\n        54,\n        55,\n        56,\n        57,\n        58,\n        59,\n        60,\n        61,\n        62,\n        63,\n        64,\n        65,\n        66,\n        67,\n        68,\n        69,\n        70,\n        71,\n        72,\n        73,\n        74,\n        75,\n        76,\n        77,\n        78,\n        79,\n        80,\n        81,\n        82,\n        83,\n        84,\n        85,\n        86,\n        87,\n        88,\n        89,\n        90,\n        91,\n        92,\n        93,\n        94,\n        95,\n        96,\n        97,\n        98,\n        99,\n        100,\n        101,\n        102,\n        103,\n        104,\n        105,\n        106,\n        107,\n        108,\n        109,\n        110,\n        111,\n        112,\n        113,\n        114,\n        115,\n        116,\n        117,\n        118,\n        119,\n        120,\n        121,\n        122,\n        123,\n        124,\n        125,\n        126,\n        127,\n        128,\n        129,\n        130,\n        131,\n        132,\n        133,\n        134,\n        135,\n        136,\n        137,\n        138,\n        139,\n        140,\n        141,\n        142,\n        143,\n        144,\n        145,\n        146,\n        147,\n        148,\n        149,\n        150,\n        151,\n        152,\n        153,\n        154\n    ]\n        .span();\n    let nodes_treeids: Span<usize> = array![\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let nodes_truenodeids: Span<usize> = array![\n        1,\n        2,\n        3,\n        4,\n        0,\n        0,\n        7,\n        0,\n        9,\n        10,\n        0,\n        12,\n        0,\n        0,\n        15,\n        0,\n        17,\n        0,\n        19,\n        0,\n        0,\n        22,\n        23,\n        24,\n        0,\n        26,\n        0,\n        28,\n        29,\n        0,\n        31,\n        0,\n        0,\n        0,\n        35,\n        36,\n        37,\n        0,\n        0,\n        0,\n        0,\n        42,\n        43,\n        44,\n        45,\n        46,\n        0,\n        48,\n        49,\n        0,\n        0,\n        52,\n        0,\n        54,\n        55,\n        56,\n        0,\n        0,\n        0,\n        0,\n        61,\n        62,\n        0,\n        64,\n        0,\n        66,\n        0,\n        0,\n        0,\n        70,\n        71,\n        72,\n        73,\n        0,\n        0,\n        0,\n        0,\n        78,\n        79,\n        80,\n        81,\n        0,\n        0,\n        0,\n        0,\n        86,\n        87,\n        88,\n        0,\n        0,\n        91,\n        0,\n        93,\n        0,\n        0,\n        0,\n        97,\n        98,\n        0,\n        0,\n        101,\n        0,\n        103,\n        104,\n        0,\n        106,\n        0,\n        0,\n        0,\n        110,\n        111,\n        112,\n        0,\n        0,\n        0,\n        0,\n        117,\n        118,\n        119,\n        0,\n        121,\n        0,\n        123,\n        124,\n        0,\n        0,\n        127,\n        0,\n        0,\n        130,\n        0,\n        0,\n        133,\n        134,\n        135,\n        136,\n        137,\n        138,\n        0,\n        140,\n        0,\n        0,\n        0,\n        0,\n        145,\n        146,\n        147,\n        148,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0\n    ]\n        .span();\n    let nodes_values: Span<FP16x16> = array![\n        FP16x16 { mag: 4096, sign: false },\n        FP16x16 { mag: 22937, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 16384, sign: false },\n        FP16x16 { mag: 57344, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 19660, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 24576, sign: false },\n        FP16x16 { mag: 42598, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 62259, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 62259, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 40960, sign: false },\n        FP16x16 { mag: 24576, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 19660, sign: false },\n        FP16x16 { mag: 45875, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 42598, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 36044, sign: false },\n        FP16x16 { mag: 19660, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 45875, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 36044, sign: false },\n        FP16x16 { mag: 58982, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 58982, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 45875, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 58982, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 42598, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 45875, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 29491, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 45875, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 36044, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 58982, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 36044, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 16384, sign: false },\n        FP16x16 { mag: 20480, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 49152, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 8192, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false }\n    ]\n        .span();\n    let base_values: Option<Span<FP16x16>> = Option::None;\n\n    let tree_ids: Span<usize> = array![0].span();\n    let mut root_index: Felt252Dict<usize> = Default::default();\n    root_index.insert(0, 0);\n    let mut node_index: Felt252Dict<usize> = Default::default();\n    node_index\n        .insert(2089986280348253421170679821480865132823066470938446095505822317253594081284, 0);\n    node_index\n        .insert(2001140082530619239661729809084578298299223810202097622761632384561112390979, 1);\n    node_index\n        .insert(2592670241084192212354027440049085852792506518781954896144296316131790403900, 2);\n    node_index\n        .insert(2960591271376829378356567803618548672034867345123727178628869426548453833420, 3);\n    node_index\n        .insert(458933264452572171106695256465341160654132084710250671055261382009315664425, 4);\n    node_index\n        .insert(3344223123784052057366048933846905716067140384361791026153972616805110454637, 5);\n    node_index\n        .insert(658476905110174425295568215706634733332002869979287079110965040248935650599, 6);\n    node_index\n        .insert(2836212335642438363012490794290757623813171043187182819737087983331902926990, 7);\n    node_index\n        .insert(3496601277869056110810900082189273917786762659443522403285387602989271154262, 8);\n    node_index\n        .insert(1249294489531540970169611621067106471309281870082955806338234725206665112557, 9);\n    node_index\n        .insert(2161697998033672097816961828039488190903838124365465380011173778905747857792, 10);\n    node_index\n        .insert(1129815197211541481934112806673325772687763881719835256646064516195041515616, 11);\n    node_index\n        .insert(2592593088135949192377729543480191336537305484235681164569491942155715064163, 12);\n    node_index\n        .insert(578223957014284909949571568465953382377214912750427143720957054706073492593, 13);\n    node_index\n        .insert(1645617302026197421098102802983206579163506957138012501615708926120228167528, 14);\n    node_index\n        .insert(2809438816810155970395166036110536928593305127049404137239671320081144123490, 15);\n    node_index\n        .insert(2496308528011391755709310159103918074725328650411689040761791240500618770096, 16);\n    node_index\n        .insert(2003594778587446957576114348312422277631766150749194167061999666337236425714, 17);\n    node_index\n        .insert(2215681478480673835576618830034726157921200517935329010004363713426342305479, 18);\n    node_index\n        .insert(3185925835074464079989752015681272863271067691852543168049845807561733691707, 19);\n    node_index\n        .insert(1207265836470221457484062512091666004839070622130697586496866096347024057755, 20);\n    node_index\n        .insert(1870230949202979679764944800468118671928852128047695497376875566624821494262, 21);\n    node_index\n        .insert(618060852536781954395603948693216564334274573299243914053414488061601327758, 22);\n    node_index\n        .insert(232760707548494477255512699093366059519467428168757247456690480397246371463, 23);\n    node_index\n        .insert(1617386247965480308136742715422077429967341022950306068917456849194882895900, 24);\n    node_index\n        .insert(654822874782506608656472905579051041410086644071534146326024101025575400153, 25);\n    node_index\n        .insert(525638101901638132526332140778087078272370083489998903571807698910013602668, 26);\n    node_index\n        .insert(3091640181556387972179279087539287892670640556085669903494551919685982442095, 27);\n    node_index\n        .insert(1425411460578159050163131982087304445715005458700346341117759372943452688022, 28);\n    node_index\n        .insert(1722933265299553894839124723076027659619615015638971980461286818493531809034, 29);\n    node_index\n        .insert(3325117385742592388671007840076299062858228097051060057749225651290693960897, 30);\n    node_index\n        .insert(1869273998012404873272699831805499731567895666937555882116307079956228100456, 31);\n    node_index\n        .insert(257262395234910825879033951801423835835630270967846664413154594520703929530, 32);\n    node_index\n        .insert(2891500475385583315757684141371327604925143655360011721762142660942782195029, 33);\n    node_index\n        .insert(1257459981124043271342269816753070228024611695909553991758648317372015085782, 34);\n    node_index\n        .insert(3573101724490615587655146760489247477770015274618159524231872921394794809579, 35);\n    node_index\n        .insert(2951401777594449283985541406642940553317465718696638438535370997641527993378, 36);\n    node_index\n        .insert(2436860863451320452900512817385686838091627966322316039332239784330434600829, 37);\n    node_index\n        .insert(3257977356974702770994741663931928753019715185508521958836925918758890988390, 38);\n    node_index\n        .insert(2741853283805093821434776875305720302351684616683152528499335618682018880592, 39);\n    node_index\n        .insert(514567459251558911686762246500770717674979116530125263461114578537254680672, 40);\n    node_index\n        .insert(2119374930171040799805795099091470687208894498354655018353474015395489390434, 41);\n    node_index\n        .insert(3338470191188327918255138125570464269857839379813971679216902484398948556964, 42);\n    node_index\n        .insert(2892272281879752543368066497063301979597320550780387266511926397533716561161, 43);\n    node_index\n        .insert(2855312300216814846973137837923466865382642814675378398541743368270404441020, 44);\n    node_index\n        .insert(3483159989811162048659069774034779954374540681397531094699912464364012442948, 45);\n    node_index\n        .insert(2987290998320166766043911843685118029159841654368226419198314196237253901671, 46);\n    node_index\n        .insert(2925128850088180758852255336587985612621894021863350117875677692518888637440, 47);\n    node_index\n        .insert(2816470536741550741568042622139415760794090671576940833850781679568928363263, 48);\n    node_index\n        .insert(117504025904364990582663097556885493352655695615775952177872159762046032741, 49);\n    node_index\n        .insert(2143228410294149239354901612797540167003066966910132278060626241695943498248, 50);\n    node_index\n        .insert(419311759585766455354017006957403420381614228026953716552023555428752798694, 51);\n    node_index\n        .insert(3050064038480880151202753004776919876287903442365303272956696507808448797287, 52);\n    node_index\n        .insert(1385347512411195789080079656286641766866442255046855963092069449745407366357, 53);\n    node_index\n        .insert(3070310993421490198115289431281422702215620142859327949152517372324361472619, 54);\n    node_index\n        .insert(2913742884576958969164113782587195202828846527657900496424141449477472273564, 55);\n    node_index\n        .insert(2093568472535973986606438755824580633177115509557931302974988564932601955239, 56);\n    node_index\n        .insert(3560543329106347446823281318204312198881533222464682017397248462954529220234, 57);\n    node_index\n        .insert(2258329791422139736262782239641765930569031761627249090322755566443202104242, 58);\n    node_index\n        .insert(780147230530856456622774510057100334628735431063744145772648079601317149643, 59);\n    node_index\n        .insert(2316329094783634722527635915976455864728431870713378530935487247638854220445, 60);\n    node_index\n        .insert(595942459003356191117553450912822964169058193996898486073017533717706655996, 61);\n    node_index\n        .insert(468061318535033931711585815055033307297228787991312757359512916260570188285, 62);\n    node_index\n        .insert(2052204235688624923559873131063770183910134013049526186717275231865702195614, 63);\n    node_index\n        .insert(1699955311620840869165542755053722387608345658646185648087789689690825797785, 64);\n    node_index\n        .insert(3374282522812564185678772854203408947562394461702303390331208821006329361123, 65);\n    node_index\n        .insert(2973169188135795465401576355486514117723575153845438471619715618155257254587, 66);\n    node_index\n        .insert(1933845760462748501896196912926633344425020928596291295340561855718789280752, 67);\n    node_index\n        .insert(1400206374308839959676708676217334569580738052049798766556848516900888958934, 68);\n    node_index\n        .insert(1440488595273849761788031183901254714714513692476890759699232177835922420051, 69);\n    node_index\n        .insert(1765607197782429306903827944694032984087223086461400721152786273443512274576, 70);\n    node_index\n        .insert(1081728107764482028110815183657783965582618309560569428049406599883158895762, 71);\n    node_index\n        .insert(2062101824085365476835789898002802715794623271831111740147610520210138854237, 72);\n    node_index\n        .insert(2074740322618091900768870458741540994849904300182495465356314088191301853065, 73);\n    node_index\n        .insert(3258451235037745323160669027918885172565773098482160366154412360890640013860, 74);\n    node_index\n        .insert(525053653813541387331907730505904505067816165493211829943994988775279102044, 75);\n    node_index\n        .insert(1899573658331441767985549642643113663505618738939032010935036740376062596854, 76);\n    node_index\n        .insert(350484224543766923071449868701665032398970313961410080649918872017849315812, 77);\n    node_index\n        .insert(1950842492180490337143378914485176805944281696420768035114335939818602766139, 78);\n    node_index\n        .insert(1404824782481446239312837894341789608778585592445990662138109764117920511709, 79);\n    node_index\n        .insert(362836422984951199752185473435750713386745407518736982952373985921347236081, 80);\n    node_index\n        .insert(946623025367211063265176586824604502073515634531788667777364911179858705558, 81);\n    node_index\n        .insert(2633163324000277496191816132521100721217797223993064604664039067710591734562, 82);\n    node_index\n        .insert(1801986104078933931671502775029170829560335045042499367678597186639133610708, 83);\n    node_index\n        .insert(1420697278439090953165809531316265389371075037014378922361911811337560296928, 84);\n    node_index\n        .insert(2818913779862691152404893285048164649343019708946413114150419613972391643833, 85);\n    node_index\n        .insert(2117995436013652728497840885480545729833030913486848118093758726746902541269, 86);\n    node_index\n        .insert(127751852951361188238686395231851222850913859197429858579312845246901369178, 87);\n    node_index\n        .insert(2698811633001158191033663638617437313508153976714307643233173949778419312517, 88);\n    node_index\n        .insert(658388282521842455588914251287531837029259203197178137902217792556456503561, 89);\n    node_index\n        .insert(1181527093320872098458354979612125149419384756607076935731557552577945926179, 90);\n    node_index\n        .insert(749436134732178646256740138670151907037714564259781780243747781475007506978, 91);\n    node_index\n        .insert(139527053159256821789882596124320673637475746672994443968014105962305658551, 92);\n    node_index\n        .insert(2256264752321707533173578319742847366660740117899562657584919346001438808295, 93);\n    node_index\n        .insert(1471349294215639651865069312281269029496180149092207674923855978537861742949, 94);\n    node_index\n        .insert(1599527610774916650758786135513735847459194869088601099692148267264507139422, 95);\n    node_index\n        .insert(1348925567371118538973078195838174941892601233016661969987842843098656775084, 96);\n    node_index\n        .insert(3255130909854220350850821724488067913492420563978595271106701962634473840914, 97);\n    node_index\n        .insert(1098499015810170842401428216621470177488952811780672364884710297364076372943, 98);\n    node_index\n        .insert(2666902303639302012507119689908308317608522901613536135678723310999647515155, 99);\n    node_index\n        .insert(907997515879651052705985194221621380802961721264372722705825219340461809200, 100);\n    node_index\n        .insert(2124360554325144308113106422635485756539471211141315552843423768396084888273, 101);\n    node_index\n        .insert(3598736440043009208771817410113758019876931018927260161846683440123219507147, 102);\n    node_index\n        .insert(1237113034722832488580561245188430373504295256910735188987019984096012001931, 103);\n    node_index\n        .insert(884558344049768836371555446021588200903052780339208951904957349404044037185, 104);\n    node_index\n        .insert(784280321344489256066716285882203121428790637989919760379274813665427427262, 105);\n    node_index\n        .insert(3472551952588748711709398308465335743810517871695257916614928877311914574241, 106);\n    node_index\n        .insert(1579363348100943961344032004617708767155021524242506190674861550786419896732, 107);\n    node_index\n        .insert(653576968777651719072715499492112313607520878545254037043893560183879857489, 108);\n    node_index\n        .insert(2633327961579170199842757290989312779085828750765842327985383652720803061926, 109);\n    node_index\n        .insert(3101204920253220343970782457572784926765600523633379722044614528209389590915, 110);\n    node_index\n        .insert(2537565394330405662800880050062241097694806466900452037378113841155978555645, 111);\n    node_index\n        .insert(306955559655552244989220345789093187601563118591829582730637833945761653350, 112);\n    node_index\n        .insert(1144065212212058748489308207801098564095305699242880891977316839573431241916, 113);\n    node_index\n        .insert(3478181491851418723342103101321490659650934149094649769124337426850038155270, 114);\n    node_index\n        .insert(3419621624676637660673415219086314486713019053519954317586073983685881930356, 115);\n    node_index\n        .insert(2426908011370291613447136873176769136554489197972200481728552402228021778402, 116);\n    node_index\n        .insert(1916122042123370178944690083048900704842269230325086549679099089416174875473, 117);\n    node_index\n        .insert(2057207652658215393591191155928140567561900227203223756539551876829334137660, 118);\n    node_index\n        .insert(2722034389703601317070746005702467061064354401688341549606678773616189196490, 119);\n    node_index\n        .insert(1171026027377763359814377926117880688616494219551682642535759838199732407496, 120);\n    node_index\n        .insert(3507234282031533800397666430789917374211847440333243952151005899337152633413, 121);\n    node_index\n        .insert(591003147462937848375161803108517142253138969543815135207326321181858185919, 122);\n    node_index\n        .insert(182069734527202013451813026473135702900640769187641767871411473365447302169, 123);\n    node_index\n        .insert(1195243682249232878341146428166676460720423167409013083888435705219134747702, 124);\n    node_index\n        .insert(1793425644853312386902998134061844248823841892125424765064687913085130719534, 125);\n    node_index\n        .insert(1983622665815164792580256365519803214027269990384198703315493315153573288434, 126);\n    node_index\n        .insert(3615973154491344159350153395208055142342062736505558158666764642048838175685, 127);\n    node_index\n        .insert(2751715913626909804252433699602081411293721754810298670422380863932998088133, 128);\n    node_index\n        .insert(186918881712189523740089713555196200069231794627360499557319265374750577226, 129);\n    node_index\n        .insert(696585542544434929491503209053317581175146475161262066468664234437983008675, 130);\n    node_index\n        .insert(4359830495913805154545225899592517767672472055784183911796827820518038513, 131);\n    node_index\n        .insert(2954335207058000607751727656601539819316106074875304820535376873121805433820, 132);\n    node_index\n        .insert(2510390039949230255082316953804013731253145558531652907601250263563528226672, 133);\n    node_index\n        .insert(3226995230854300551967642178527450300960499043510855212238369890580256668532, 134);\n    node_index\n        .insert(1620924075233065517364532267959798304439946408626316544761884056227131075831, 135);\n    node_index\n        .insert(1610900122192929153657761847202689179268074338802437933866337242354758101660, 136);\n    node_index\n        .insert(2565949095169598991903537465065584077778440646580025930326495506484329892725, 137);\n    node_index\n        .insert(1012362975819634411571869839734809106575285344002573666983595104659295812607, 138);\n    node_index\n        .insert(242312010918799555845832460483650516749990744287009628468613253461264531026, 139);\n    node_index\n        .insert(1104776796569046483584574115975216172161469015460244982207905888870418040487, 140);\n    node_index\n        .insert(3289555912992777681578950209252840071327866822704829766247386311885634446673, 141);\n    node_index\n        .insert(3133389957643610781371406448279843175887428913359743769920083259111437722268, 142);\n    node_index\n        .insert(1169918710119352022244140656086831769713178729571654411898266328562003734517, 143);\n    node_index\n        .insert(3592039235252149652556167686570045881877115549259769455422056097903987237819, 144);\n    node_index\n        .insert(2048175709145840597887667330964815895803568760936075562647625937161113445908, 145);\n    node_index\n        .insert(602222645962845554276438041138511866776339653340605661136009451417275008940, 146);\n    node_index\n        .insert(3318742320906017551291978242369663702298606650330380959683585594592748661010, 147);\n    node_index\n        .insert(564160996724923690963741657975239836484028160385417016805513722318839327322, 148);\n    node_index\n        .insert(656294390376267384135628810815504467149264887388377312825033341338166573620, 149);\n    node_index\n        .insert(1201592236750942207412694706123654466634588634474700675083122904145559965915, 150);\n    node_index\n        .insert(2141408926815137181004274624388915700231991905288681935478972043994347966006, 151);\n    node_index\n        .insert(1440847977042239464860406726605567303568767649154338464116083965986084755262, 152);\n    node_index\n        .insert(950585553138591375958592507876257987416844837045084288783892644487908218679, 153);\n    node_index\n        .insert(257643451533833048856069434258149588745628261389615631070776723485957908127, 154);\n\n    let atts = TreeEnsembleAttributes {\n        nodes_falsenodeids,\n        nodes_featureids,\n        nodes_missing_value_tracks_true,\n        nodes_modes,\n        nodes_nodeids,\n        nodes_treeids,\n        nodes_truenodeids,\n        nodes_values\n    };\n\n    let mut ensemble: TreeEnsemble<FP16x16> = TreeEnsemble {\n        atts, tree_ids, root_index, node_index\n    };\n\n    let mut classifier: TreeEnsembleClassifier<FP16x16> = TreeEnsembleClassifier {\n        ensemble,\n        class_ids,\n        class_nodeids,\n        class_treeids,\n        class_weights,\n        classlabels,\n        base_values,\n        post_transform\n    };\n\n    let mut X = TensorTrait::new(\n        array![1, 9].span(),\n        array![\n            FP16x16 { mag: 39321, sign: false },\n            FP16x16 { mag: 32768, sign: false },\n            FP16x16 { mag: 52428, sign: false },\n            FP16x16 { mag: 16384, sign: false },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 65536, sign: false },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 16384, sign: false },\n            FP16x16 { mag: 0, sign: false },\n        ]\n            .span()\n    );\n\n    (classifier, X)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/ml/tree_ensemble_regressor.cairo",
        "content": "use orion::numbers::FP16x16;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor, U32Tensor};\nuse orion::operators::ml::tree_ensemble::core::{NODE_MODES, TreeEnsembleAttributes, TreeEnsemble};\nuse orion::operators::ml::tree_ensemble::tree_ensemble_regressor::{\n    TreeEnsembleRegressor, POST_TRANSFORM, TreeEnsembleRegressorTrait, AGGREGATE_FUNCTION\n};\nuse orion::operators::matrix::{MutMatrix, MutMatrixImpl};\nuse orion::operators::tensor::implementations::tensor_fp16x16::relative_eq;\nuse core::debug::PrintTrait;\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_regressor_SUM() {\n    let (mut regressor, X) = tree_ensemble_regressor_helper(AGGREGATE_FUNCTION::SUM);\n\n    let mut res = TreeEnsembleRegressorTrait::predict(regressor, X);\n\n    // ASSERT RES\n    assert(\n        relative_eq(@res.get(0, 0).unwrap(), @FP16x16 { mag: 37809, sign: false }) == true,\n        'res[0, 0] = 37809'\n    );\n    assert(\n        relative_eq(@res.get(1, 0).unwrap(), @FP16x16 { mag: 37809, sign: false }) == true,\n        'res[1, 0] = 37809'\n    );\n    assert(\n        relative_eq(@res.get(2, 0).unwrap(), @FP16x16 { mag: 37809, sign: false }) == true,\n        'res[2, 0] = 37809'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_regressor_AVERAGE() {\n    let (mut regressor, X) = tree_ensemble_regressor_helper(AGGREGATE_FUNCTION::AVERAGE);\n\n    let mut res = TreeEnsembleRegressorTrait::predict(regressor, X);\n\n    // ASSERT RES\n    assert(\n        relative_eq(@res.get(0, 0).unwrap(), @FP16x16 { mag: 18904, sign: false }) == true,\n        'res[0, 0] = 18904'\n    );\n    assert(\n        relative_eq(@res.get(1, 0).unwrap(), @FP16x16 { mag: 18904, sign: false }) == true,\n        'res[1, 0] = 18904'\n    );\n    assert(\n        relative_eq(@res.get(2, 0).unwrap(), @FP16x16 { mag: 18904, sign: false }) == true,\n        'res[2, 0] = 18904'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_regressor_MIN() {\n    let (mut regressor, X) = tree_ensemble_regressor_helper(AGGREGATE_FUNCTION::MIN);\n\n    let mut res = TreeEnsembleRegressorTrait::predict(regressor, X);\n\n    // ASSERT RES\n    assert(\n        relative_eq(@res.get(0, 0).unwrap(), @FP16x16 { mag: 5041, sign: false }) == true,\n        'res[0, 0] = 5041'\n    );\n    assert(\n        relative_eq(@res.get(1, 0).unwrap(), @FP16x16 { mag: 5041, sign: false }) == true,\n        'res[1, 0] = 5041'\n    );\n    assert(\n        relative_eq(@res.get(2, 0).unwrap(), @FP16x16 { mag: 5041, sign: false }) == true,\n        'res[2, 0] = 5041'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn test_tree_ensemble_regressor_MAX() {\n    let (mut regressor, X) = tree_ensemble_regressor_helper(AGGREGATE_FUNCTION::MAX);\n\n    let mut res = TreeEnsembleRegressorTrait::predict(regressor, X);\n\n    // ASSERT RES\n    assert(\n        relative_eq(@res.get(0, 0).unwrap(), @FP16x16 { mag: 32768, sign: false }) == true,\n        'res[0, 0] = 32768'\n    );\n    assert(\n        relative_eq(@res.get(1, 0).unwrap(), @FP16x16 { mag: 32768, sign: false }) == true,\n        'res[1, 0] = 32768'\n    );\n    assert(\n        relative_eq(@res.get(2, 0).unwrap(), @FP16x16 { mag: 32768, sign: false }) == true,\n        'res[2, 0] = 32768'\n    );\n}\n\n\n// ============ HELPER ============ //\n\nfn tree_ensemble_regressor_helper(\n    agg: AGGREGATE_FUNCTION\n) -> (TreeEnsembleRegressor<FP16x16>, Tensor<FP16x16>) {\n    let n_targets: usize = 1;\n    let aggregate_function = agg;\n    let nodes_falsenodeids: Span<usize> = array![4, 3, 0, 0, 0, 2, 0, 4, 0, 0].span();\n    let nodes_featureids: Span<usize> = array![0, 2, 0, 0, 0, 0, 0, 2, 0, 0].span();\n    let nodes_missing_value_tracks_true: Span<usize> = array![0, 0, 0, 0, 0, 0, 0, 0, 0, 0].span();\n    let nodes_modes: Span<NODE_MODES> = array![\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::BRANCH_LEQ,\n        NODE_MODES::LEAF,\n        NODE_MODES::LEAF\n    ]\n        .span();\n    let nodes_nodeids: Span<usize> = array![0, 1, 2, 3, 4, 0, 1, 2, 3, 4].span();\n    let nodes_treeids: Span<usize> = array![0, 0, 0, 0, 0, 1, 1, 1, 1, 1].span();\n    let nodes_truenodeids: Span<usize> = array![1, 2, 0, 0, 0, 1, 0, 3, 0, 0].span();\n    let nodes_values: Span<FP16x16> = array![\n        FP16x16 { mag: 17462, sign: false },\n        FP16x16 { mag: 40726, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 47240, sign: true },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 36652, sign: true },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 0, sign: false }\n    ]\n        .span();\n    let target_ids: Span<usize> = array![0, 0, 0, 0, 0, 0].span();\n    let target_nodeids: Span<usize> = array![2, 3, 4, 1, 3, 4].span();\n    let target_treeids: Span<usize> = array![0, 0, 0, 1, 1, 1].span();\n    let target_weights: Span<FP16x16> = array![\n        FP16x16 { mag: 5041, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 32768, sign: false },\n        FP16x16 { mag: 0, sign: false },\n        FP16x16 { mag: 18724, sign: false },\n        FP16x16 { mag: 32768, sign: false }\n    ]\n        .span();\n\n    let base_values: Option<Span<FP16x16>> = Option::None;\n    let post_transform = POST_TRANSFORM::NONE;\n\n    let tree_ids: Span<usize> = array![0, 1].span();\n\n    let mut root_index: Felt252Dict<usize> = Default::default();\n    root_index.insert(0, 0);\n    root_index.insert(1, 5);\n\n    let mut node_index: Felt252Dict<usize> = Default::default();\n    node_index\n        .insert(2089986280348253421170679821480865132823066470938446095505822317253594081284, 0);\n    node_index\n        .insert(2001140082530619239661729809084578298299223810202097622761632384561112390979, 1);\n    node_index\n        .insert(2592670241084192212354027440049085852792506518781954896144296316131790403900, 2);\n    node_index\n        .insert(2960591271376829378356567803618548672034867345123727178628869426548453833420, 3);\n    node_index\n        .insert(458933264452572171106695256465341160654132084710250671055261382009315664425, 4);\n    node_index\n        .insert(1089549915800264549621536909767699778745926517555586332772759280702396009108, 5);\n    node_index\n        .insert(1321142004022994845681377299801403567378503530250467610343381590909832171180, 6);\n    node_index\n        .insert(2592987851775965742543459319508348457290966253241455514226127639100457844774, 7);\n    node_index\n        .insert(2492755623019086109032247218615964389726368532160653497039005814484393419348, 8);\n    node_index\n        .insert(1323616023845704258113538348000047149470450086307731200728039607710316625916, 9);\n\n    let atts = TreeEnsembleAttributes {\n        nodes_falsenodeids,\n        nodes_featureids,\n        nodes_missing_value_tracks_true,\n        nodes_modes,\n        nodes_nodeids,\n        nodes_treeids,\n        nodes_truenodeids,\n        nodes_values\n    };\n\n    let mut ensemble: TreeEnsemble<FP16x16> = TreeEnsemble {\n        atts, tree_ids, root_index, node_index\n    };\n\n    let mut regressor: TreeEnsembleRegressor<FP16x16> = TreeEnsembleRegressor {\n        ensemble,\n        target_ids,\n        target_nodeids,\n        target_treeids,\n        target_weights,\n        base_values,\n        n_targets,\n        aggregate_function,\n        post_transform\n    };\n\n    let mut X: Tensor<FP16x16> = TensorTrait::new(\n        array![3, 3].span(),\n        array![\n            FP16x16 { mag: 32768, sign: true },\n            FP16x16 { mag: 26214, sign: true },\n            FP16x16 { mag: 19660, sign: true },\n            FP16x16 { mag: 13107, sign: true },\n            FP16x16 { mag: 6553, sign: true },\n            FP16x16 { mag: 0, sign: false },\n            FP16x16 { mag: 6553, sign: false },\n            FP16x16 { mag: 13107, sign: false },\n            FP16x16 { mag: 19660, sign: false },\n        ]\n            .span()\n    );\n\n    (regressor, X)\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes.cairo",
        "content": "mod abs_fp16x16;\nmod abs_fp8x23;\nmod abs_i32;\nmod abs_i8;\nmod acos_fp16x16;\nmod acos_fp8x23;\nmod acosh_fp16x16;\nmod acosh_fp8x23;\nmod add_fp16x16;\nmod add_fp16x16_broadcast;\nmod add_fp8x23;\nmod add_fp8x23_broadcast;\nmod add_i32;\nmod add_i32_broadcast;\nmod add_i8;\nmod add_i8_broadcast;\nmod add_u32;\nmod add_u32_broadcast;\nmod argmin_fp16x16_1D_default;\nmod argmin_fp16x16_1D_keepdims_false;\nmod argmin_fp16x16_1D_last_index;\nmod argmin_fp16x16_2D_default;\nmod argmin_fp16x16_2D_keepdims_false;\nmod argmin_fp16x16_2D_last_index;\nmod argmin_fp16x16_3D_default;\nmod argmin_fp16x16_3D_keepdims_false;\nmod argmin_fp16x16_3D_last_index;\nmod argmin_fp8x23_1D_default;\nmod argmin_fp8x23_1D_keepdims_false;\nmod argmin_fp8x23_1D_last_index;\nmod argmin_fp8x23_2D_default;\nmod argmin_fp8x23_2D_keepdims_false;\nmod argmin_fp8x23_2D_last_index;\nmod argmin_fp8x23_3D_default;\nmod argmin_fp8x23_3D_keepdims_false;\nmod argmin_fp8x23_3D_last_index;\nmod argmin_i32_1D_default;\nmod argmin_i32_1D_keepdims_false;\nmod argmin_i32_1D_last_index;\nmod argmin_i32_2D_default;\nmod argmin_i32_2D_keepdims_false;\nmod argmin_i32_2D_last_index;\nmod argmin_i32_3D_default;\nmod argmin_i32_3D_keepdims_false;\nmod argmin_i32_3D_last_index;\nmod argmin_i8_1D_default;\nmod argmin_i8_1D_keepdims_false;\nmod argmin_i8_1D_last_index;\nmod argmin_i8_2D_default;\nmod argmin_i8_2D_keepdims_false;\nmod argmin_i8_2D_last_index;\nmod argmin_i8_3D_default;\nmod argmin_i8_3D_keepdims_false;\nmod argmin_i8_3D_last_index;\nmod argmin_u32_1D_default;\nmod argmin_u32_1D_keepdims_false;\nmod argmin_u32_1D_last_index;\nmod argmin_u32_2D_default;\nmod argmin_u32_2D_keepdims_false;\nmod argmin_u32_2D_last_index;\nmod argmin_u32_3D_default;\nmod argmin_u32_3D_keepdims_false;\nmod argmin_u32_3D_last_index;\nmod asin_fp16x16;\nmod asin_fp8x23;\nmod asinh_fp16x16;\nmod asinh_fp8x23;\nmod atan_fp16x16;\nmod atan_fp8x23;\nmod ceil_fp16x16;\nmod ceil_fp8x23;\nmod concat_fp16x16_1d;\nmod concat_fp16x16_2d;\nmod concat_fp16x16_3d_default;\nmod concat_fp16x16_3d_axis_1;\nmod concat_fp16x16_3d_axis_2;\nmod concat_fp16x16_3d_three_tensors_axis_1;\nmod concat_fp16x16_3d_three_tensors_axis_2;\nmod concat_fp8x23_1d;\nmod concat_fp8x23_2d;\nmod concat_fp8x23_3d_default;\nmod concat_fp8x23_3d_axis_1;\nmod concat_fp8x23_3d_axis_2;\nmod concat_fp8x23_3d_three_tensors_axis_1;\nmod concat_fp8x23_3d_three_tensors_axis_2;\nmod concat_i32_1d;\nmod concat_i32_2d;\nmod concat_i32_3d_default;\nmod concat_i32_3d_axis_1;\nmod concat_i32_3d_axis_2;\nmod concat_i32_3d_three_tensors_axis_1;\nmod concat_i32_3d_three_tensors_axis_2;\nmod concat_i8_1d;\nmod concat_i8_2d;\nmod concat_i8_3d_default;\nmod concat_i8_3d_axis_1;\nmod concat_i8_3d_axis_2;\nmod concat_i8_3d_three_tensors_axis_1;\nmod concat_i8_3d_three_tensors_axis_2;\nmod concat_u32_1d;\nmod concat_u32_2d;\nmod concat_u32_3d_default;\nmod concat_u32_3d_axis_1;\nmod concat_u32_3d_axis_2;\nmod concat_u32_3d_three_tensors_axis_1;\nmod concat_u32_3d_three_tensors_axis_2;\nmod cos_fp16x16;\nmod cos_fp8x23;\nmod cosh_fp16x16;\nmod cosh_fp8x23;\nmod cumsum_fp16x16_1d_default;\nmod cumsum_fp16x16_1d_exclusive;\nmod cumsum_fp16x16_1d_reverse;\nmod cumsum_fp16x16_1d_reverse_exclusive;\nmod cumsum_fp16x16_2d_axis_0;\nmod cumsum_fp16x16_2d_axis_1;\nmod cumsum_fp8x23_1d_default;\nmod cumsum_fp8x23_1d_exclusive;\nmod cumsum_fp8x23_1d_reverse;\nmod cumsum_fp8x23_1d_reverse_exclusive;\nmod cumsum_fp8x23_2d_axis_0;\nmod cumsum_fp8x23_2d_axis_1;\nmod cumsum_i32_1d_default;\nmod cumsum_i32_1d_exclusive;\nmod cumsum_i32_1d_reverse;\nmod cumsum_i32_1d_reverse_exclusive;\nmod cumsum_i32_2d_axis_0;\nmod cumsum_i32_2d_axis_1;\nmod cumsum_i8_1d_default;\nmod cumsum_i8_1d_exclusive;\nmod cumsum_i8_1d_reverse;\nmod cumsum_i8_1d_reverse_exclusive;\nmod cumsum_i8_2d_axis_0;\nmod cumsum_i8_2d_axis_1;\nmod cumsum_u32_1d_default;\nmod cumsum_u32_1d_exclusive;\nmod cumsum_u32_1d_reverse;\nmod cumsum_u32_1d_reverse_exclusive;\nmod cumsum_u32_2d_axis_0;\nmod cumsum_u32_2d_axis_1;\nmod div_fp16x16;\nmod div_fp16x16_broadcast;\nmod div_fp8x23;\nmod div_fp8x23_broadcast;\nmod div_i32;\nmod div_i32_broadcast;\nmod div_i8;\nmod div_i8_broadcast;\nmod div_u32;\nmod div_u32_broadcast;\nmod equal_fp16x16;\nmod equal_fp16x16_broadcast;\nmod equal_fp8x23;\nmod equal_fp8x23_broadcast;\nmod equal_i32;\nmod equal_i32_broadcast;\nmod equal_i8;\nmod equal_i8_broadcast;\nmod equal_u32;\nmod equal_u32_broadcast;\nmod exp_fp16x16;\nmod exp_fp8x23;\nmod less_equal_fp16x16;\nmod less_equal_fp16x16_broadcast;\nmod less_equal_fp8x23;\nmod less_equal_fp8x23_broadcast;\nmod less_equal_i32;\nmod less_equal_i32_broadcast;\nmod less_equal_i8;\nmod less_equal_i8_broadcast;\nmod less_equal_u32;\nmod less_equal_u32_broadcast;\nmod greater_fp16x16;\nmod greater_fp16x16_broadcast;\nmod greater_fp8x23;\nmod greater_fp8x23_broadcast;\nmod greater_i32;\nmod greater_i32_broadcast;\nmod greater_i8;\nmod greater_i8_broadcast;\nmod greater_u32;\nmod greater_u32_broadcast;\nmod leaky_relu_fp16x16;\nmod leaky_relu_fp8x23;\nmod linear_fp16x16;\nmod linear_fp8x23;\nmod linear_i32;\nmod linear_i8;\nmod linear_u32;\nmod log_fp16x16;\nmod log_fp8x23;\nmod logsoftmax_fp16x16_axis_0;\nmod logsoftmax_fp16x16_axis_1;\nmod logsoftmax_fp8x23_axis_0;\nmod logsoftmax_fp8x23_axis_1;\nmod matmul_fp16x16_1d;\nmod matmul_fp16x16_2x2;\nmod matmul_fp16x16_2x1;\nmod matmul_fp16x16_1x2;\nmod matmul_fp8x23_1d;\nmod matmul_fp8x23_2x2;\nmod matmul_fp8x23_2x1;\nmod matmul_fp8x23_1x2;\nmod matmul_i32_1d;\nmod matmul_i32_2x2;\nmod matmul_i32_2x1;\nmod matmul_i32_1x2;\nmod matmul_i8_1d;\nmod matmul_i8_2x2;\nmod matmul_i8_2x1;\nmod matmul_i8_1x2;\nmod matmul_u32_1d;\nmod matmul_u32_2x2;\nmod matmul_u32_2x1;\nmod matmul_u32_1x2;\nmod mul_fp16x16;\nmod mul_fp16x16_broadcast;\nmod mul_fp8x23;\nmod mul_fp8x23_broadcast;\nmod mul_i32;\nmod mul_i32_broadcast;\nmod mul_i8;\nmod mul_i8_broadcast;\nmod mul_u32;\nmod mul_u32_broadcast;\nmod or_fp16x16;\nmod or_fp16x16_broadcast;\nmod or_fp8x23;\nmod or_fp8x23_broadcast;\nmod or_i32;\nmod or_i32_broadcast;\nmod or_i8;\nmod or_i8_broadcast;\nmod or_u32;\nmod or_u32_broadcast;\nmod relu_fp16x16;\nmod relu_fp8x23;\nmod relu_i32;\nmod relu_i8;\nmod sigmoid_fp16x16;\nmod sigmoid_fp8x23;\nmod sin_fp16x16;\nmod sin_fp8x23;\nmod sinh_fp16x16;\nmod sinh_fp8x23;\nmod softplus_fp8x23;\nmod softplus_fp16x16;\nmod softsign_fp8x23;\nmod softsign_fp16x16;\nmod sqrt_fp16x16;\nmod sqrt_fp8x23;\nmod sub_fp16x16;\nmod sub_fp16x16_broadcast;\nmod sub_fp8x23;\nmod sub_fp8x23_broadcast;\nmod sub_i32;\nmod sub_i32_broadcast;\nmod sub_i8;\nmod sub_i8_broadcast;\nmod sub_u32;\nmod sub_u32_broadcast;\nmod tanh_fp16x16;\nmod tanh_fp8x23;\nmod transpose_fp16x16_2d;\nmod transpose_fp16x16_3d;\nmod transpose_fp8x23_2d;\nmod transpose_fp8x23_3d;\nmod transpose_i32_2d;\nmod transpose_i32_3d;\nmod transpose_i8_2d;\nmod transpose_i8_3d;\nmod transpose_u32_2d;\nmod transpose_u32_3d;\nmod xor_fp16x16;\nmod xor_fp16x16_broadcast;\nmod xor_fp8x23;\nmod xor_fp8x23_broadcast;\nmod xor_i32;\nmod xor_i32_broadcast;\nmod xor_i8;\nmod xor_i8_broadcast;\nmod xor_u32;\nmod xor_u32_broadcast;\nmod greater_equal_fp16x16;\nmod greater_equal_fp16x16_broadcast;\nmod greater_equal_fp8x23;\nmod greater_equal_fp8x23_broadcast;\nmod greater_equal_i32;\nmod greater_equal_i32_broadcast;\nmod greater_equal_i8;\nmod greater_equal_i8_broadcast;\nmod greater_equal_u32;\nmod greater_equal_u32_broadcast;\nmod slice_fp16x16_2d;\nmod slice_fp16x16_3d;\nmod slice_fp8x23_2d;\nmod slice_fp8x23_3d;\nmod slice_i32_2d;\nmod slice_i32_3d;\nmod slice_i8_2d;\nmod slice_i8_3d;\nmod slice_u32_2d;\nmod slice_u32_3d;\nmod nonzero_fp16x16_2d;\nmod nonzero_fp16x16_3d;\nmod nonzero_fp8x23_2d;\nmod nonzero_fp8x23_3d;\nmod nonzero_i32_2d;\nmod nonzero_i32_3d;\nmod nonzero_i8_2d;\nmod nonzero_i8_3d;\nmod nonzero_u32_2d;\nmod nonzero_u32_3d;\nmod squeeze_fP16x16;\nmod squeeze_fP8x23;\nmod squeeze_i32;\nmod squeeze_i8;\nmod squeeze_u32;\nmod unsqueeze_fp16x16_2d;\nmod unsqueeze_fp16x16_3d;\nmod unsqueeze_fp8x23_2d;\nmod unsqueeze_fp8x23_3d;\nmod unsqueeze_i32_2d;\nmod unsqueeze_i32_3d;\nmod unsqueeze_i8_2d;\nmod unsqueeze_i8_3d;\nmod unsqueeze_u32_2d;\nmod unsqueeze_u32_3d;\nmod sign_fP16x16;\nmod sign_fP8x23;\nmod sign_fail;\nmod sign_i32;\nmod sign_i8;\nmod clip_fp16x16_2d;\nmod clip_fp16x16_3d;\nmod clip_fp8x23_2d;\nmod clip_fp8x23_3d;\nmod clip_i32_2d;\nmod clip_i32_3d;\nmod clip_i8_2d;\nmod clip_i8_3d;\nmod clip_u32_2d;\nmod clip_u32_3d;\nmod identity_fP16x16;\nmod identity_fP8x23;\nmod identity_i32;\nmod identity_i8;\nmod identity_u32;\nmod thresholded_relu_fp16x16;\nmod thresholded_relu_fp8x23;\nmod hard_sigmoid_fp8x23;\nmod hard_sigmoid_fp16x16;\nmod neg_fp16x16;\nmod neg_fp8x23;\nmod neg_i32;\nmod neg_i8;\nmod gemm_all_attributes;\nmod gemm_alpha;\nmod gemm_beta;\nmod gemm_default_matrix_bias;\nmod gemm_default_vector_bias;\nmod gemm_default_no_bias;\nmod gemm_transposeA;\nmod gemm_transposeB;\nmod min_fp16x16_three_tensors;\nmod min_fp16x16_broadcast_three_tensors;\nmod min_fp16x16_two_tensors;\nmod min_fp16x16_broadcast_two_tensors;\nmod min_fp8x23_three_tensors;\nmod min_fp8x23_broadcast_three_tensors;\nmod min_fp8x23_two_tensors;\nmod min_fp8x23_broadcast_two_tensors;\nmod min_i32_three_tensors;\nmod min_i32_broadcast_three_tensors;\nmod min_i32_two_tensors;\nmod min_i32_broadcast_two_tensors;\nmod min_i8_three_tensors;\nmod min_i8_broadcast_three_tensors;\nmod min_i8_two_tensors;\nmod min_i8_broadcast_two_tensors;\nmod min_u32_three_tensors;\nmod min_u32_broadcast_three_tensors;\nmod min_u32_two_tensors;\nmod min_u32_broadcast_two_tensors;\nmod where_fp16x16;\nmod where_fp16x16_broadcast;\nmod where_fp8x23;\nmod where_fp8x23_broadcast;\nmod where_i32;\nmod where_i32_broadcast;\nmod where_i8;\nmod where_i8_broadcast;\nmod where_u32;\nmod where_u32_broadcast;\nmod not_bool;\nmod round_fp16x16;\nmod round_fp8x23;\nmod max_fp16x16_three_tensors;\nmod max_fp16x16_broadcast_three_tensors;\nmod max_fp16x16_two_tensors;\nmod max_fp16x16_broadcast_two_tensors;\nmod max_fp8x23_three_tensors;\nmod max_fp8x23_broadcast_three_tensors;\nmod max_fp8x23_two_tensors;\nmod max_fp8x23_broadcast_two_tensors;\nmod max_i32_three_tensors;\nmod max_i32_broadcast_three_tensors;\nmod max_i32_two_tensors;\nmod max_i32_broadcast_two_tensors;\nmod max_i8_three_tensors;\nmod max_i8_broadcast_three_tensors;\nmod max_i8_two_tensors;\nmod max_i8_broadcast_two_tensors;\nmod max_u32_three_tensors;\nmod max_u32_broadcast_three_tensors;\nmod max_u32_two_tensors;\nmod max_u32_broadcast_two_tensors;\nmod scatter_fp16x16_3d_default;\nmod scatter_fp16x16_3d_axis1;\nmod scatter_fp16x16_3d_axis1_add;\nmod scatter_fp8x23_default;\nmod scatter_fp8x23_axis1;\nmod scatter_fp8x23_mul;\nmod scatter_i8_default;\nmod scatter_i8_axis1;\nmod scatter_i8_axis1_max;\nmod scatter_u32_default;\nmod scatter_u32_axis1;\nmod scatter_u32_add;\nmod array_feature_extractor_1D_i32;\nmod array_feature_extractor_1D_fp8x23;\nmod array_feature_extractor_1D_fp16x16;\nmod array_feature_extractor_2D_i32;\nmod array_feature_extractor_2D_fp8x23;\nmod array_feature_extractor_2D_fp16x16;\nmod array_feature_extractor_3D_i32;\nmod array_feature_extractor_3D_fp8x23;\nmod array_feature_extractor_3D_fp16x16;\nmod binarizer_fp16x16;\nmod binarizer_fp8x23;\nmod tril_fp16x16;\nmod tril_fp16x16_neg;\nmod tril_fp16x16_one_row;\nmod tril_fp16x16_out_neg;\nmod tril_fp16x16_out_pos;\nmod tril_fp16x16_pos;\nmod tril_fp16x16_square;\nmod tril_fp16x16_square_neg;\nmod tril_fp16x16_zero;\nmod triu_fp16x16;\nmod triu_fp16x16_neg;\nmod triu_fp16x16_one_row;\nmod triu_fp16x16_out_neg;\nmod triu_fp16x16_out_pos;\nmod triu_fp16x16_pos;\nmod triu_fp16x16_square;\nmod triu_fp16x16_square_neg;\nmod triu_fp16x16_zero;\nmod tril_fp8x23;\nmod tril_fp8x23_neg;\nmod tril_fp8x23_one_row;\nmod tril_fp8x23_out_neg;\nmod tril_fp8x23_out_pos;\nmod tril_fp8x23_pos;\nmod tril_fp8x23_square;\nmod tril_fp8x23_square_neg;\nmod tril_fp8x23_zero;\nmod triu_fp8x23;\nmod triu_fp8x23_neg;\nmod triu_fp8x23_one_row;\nmod triu_fp8x23_out_neg;\nmod triu_fp8x23_out_pos;\nmod triu_fp8x23_pos;\nmod triu_fp8x23_square;\nmod triu_fp8x23_square_neg;\nmod triu_fp8x23_zero;\nmod tril_i32;\nmod tril_neg_i32;\nmod tril_i32_one_row;\nmod tril_i32_out_neg;\nmod tril_i32_out_pos;\nmod tril_i32_pos;\nmod tril_i32_square;\nmod tril_i32_square_neg;\nmod tril_i32_zero;\nmod triu_i32;\nmod triu_i32_neg;\nmod triu_i32_one_row;\nmod triu_i32_out_neg;\nmod triu_i32_out_pos;\nmod triu_i32_pos;\nmod triu_i32_square;\nmod triu_i32_square_neg;\nmod triu_i32_zero;\nmod tril_i8;\nmod tril_i8_neg;\nmod tril_i8_one_row;\nmod tril_i8_out_neg;\nmod tril_i8_out_pos;\nmod tril_i8_pos;\nmod tril_i8_square;\nmod tril_i8_square_neg;\nmod tril_i8_zero;\nmod triu_i8;\nmod triu_i8_neg;\nmod triu_i8_one_row;\nmod triu_i8_out_neg;\nmod triu_i8_out_pos;\nmod triu_i8_pos;\nmod triu_i8_square;\nmod triu_i8_square_neg;\nmod triu_i8_zero;\nmod tril_u32;\nmod tril_u32_neg;\nmod tril_u32_one_row;\nmod tril_u32_out_neg;\nmod tril_u32_out_pos;\nmod tril_u32_pos;\nmod tril_u32_square;\nmod tril_u32_square_neg;\nmod tril_u32_zero;\nmod triu_u32;\nmod triu_u32_neg;\nmod triu_u32_one_row;\nmod triu_u32_out_neg;\nmod triu_u32_out_pos;\nmod triu_u32_pos;\nmod triu_u32_square;\nmod triu_u32_square_neg;\nmod triu_u32_zero;\nmod reduce_sum_square_fp16x16_export_do_not_keepdims;\nmod reduce_sum_square_fp16x16_export_keepdims;\nmod reduce_sum_square_fp16x16_export_negative_axes_keepdims;\nmod reduce_sum_square_fp8x23_export_do_not_keepdims;\nmod reduce_sum_square_fp8x23_export_keepdims;\nmod reduce_sum_square_fp8x23_export_negative_axes_keepdims;\nmod reduce_sum_square_i32_export_do_not_keepdims;\nmod reduce_sum_square_i32_export_keepdims;\nmod reduce_sum_square_i32_export_negative_axes_keepdims;\nmod reduce_sum_square_i8_export_do_not_keepdims;\nmod reduce_sum_square_i8_export_keepdims;\nmod reduce_sum_square_i8_export_negative_axes_keepdims;\nmod reduce_sum_square_u32_export_do_not_keepdims;\nmod reduce_sum_square_u32_export_keepdims;\nmod reduce_sum_square_u32_export_negative_axes_keepdims;\nmod reduce_l2_fp16x16_export_do_not_keepdims;\nmod reduce_l2_fp16x16_export_keepdims;\nmod reduce_l2_fp16x16_export_negative_axes_keepdims;\nmod reduce_l2_fp8x23_export_do_not_keepdims;\nmod reduce_l2_fp8x23_export_keepdims;\nmod reduce_l2_fp8x23_export_negative_axes_keepdims;\nmod reduce_l1_fp16x16_export_do_not_keepdims;\nmod reduce_l1_fp16x16_export_keepdims;\nmod reduce_l1_fp16x16_export_negative_axes_keepdims;\nmod reduce_l1_fp8x23_export_do_not_keepdims;\nmod reduce_l1_fp8x23_export_keepdims;\nmod reduce_l1_fp8x23_export_negative_axes_keepdims;\nmod reduce_l1_i32_export_do_not_keepdims;\nmod reduce_l1_i32_export_keepdims;\nmod reduce_l1_i32_export_negative_axes_keepdims;\nmod reduce_l1_i8_export_do_not_keepdims;\nmod reduce_l1_i8_export_keepdims;\nmod reduce_l1_i8_export_negative_axes_keepdims;\nmod reduce_l1_u32_export_do_not_keepdims;\nmod reduce_l1_u32_export_keepdims;\nmod reduce_l1_u32_export_negative_axes_keepdims;\nmod reduce_prod_fp16x16_1D;\nmod reduce_prod_fp16x16_2D_default;\nmod reduce_prod_fp16x16_2D_keepdims;\nmod reduce_prod_fp16x16_2D_axis_1;\nmod reduce_prod_fp8x23_1D;\nmod reduce_prod_fp8x23_2D_default;\nmod reduce_prod_fp8x23_2D_keepdims;\nmod reduce_prod_fp8x23_2D_axis_1;\nmod reduce_prod_i32_1D;\nmod reduce_prod_i32_2D_default;\nmod reduce_prod_i32_2D_keepdims;\nmod reduce_prod_i32_2D_axis_1;\nmod reduce_prod_i8_1D;\nmod reduce_prod_i8_2D_default;\nmod reduce_prod_i8_2D_keepdims;\nmod reduce_prod_i8_2D_axis_1;\nmod reduce_prod_u32_1D;\nmod reduce_prod_u32_2D_default;\nmod reduce_prod_u32_2D_keepdims;\nmod reduce_prod_u32_2D_axis_1;\nmod sequence_length_fp16x16;\nmod sequence_length_fp16x16_broadcast;\nmod sequence_length_fp8x23;\nmod sequence_length_fp8x23_broadcast;\nmod sequence_length_i32;\nmod sequence_length_i32_broadcast;\nmod sequence_length_i8;\nmod sequence_length_i8_broadcast;\nmod sequence_length_u32;\nmod sequence_length_u32_broadcast;\nmod sequence_at_u32_positive;\nmod sequence_at_u32_negative;\nmod sequence_at_fp16x16_positive;\nmod sequence_at_fp16x16_negative;\nmod sequence_at_fp8x23_positive;\nmod sequence_at_fp8x23_negative;\nmod sequence_at_i32_positive;\nmod sequence_at_i32_negative;\nmod sequence_at_i8_positive;\nmod sequence_at_i8_negative;\nmod reduce_min_fp16x16_1D;\nmod reduce_min_fp16x16_2D_default;\nmod reduce_min_fp16x16_2D_keepdims;\nmod reduce_min_fp16x16_2D_axis_1;\nmod reduce_min_fp8x23_1D;\nmod reduce_min_fp8x23_2D_default;\nmod reduce_min_fp8x23_2D_keepdims;\nmod reduce_min_fp8x23_2D_axis_1;\nmod reduce_min_i32_1D;\nmod reduce_min_i32_2D_default;\nmod reduce_min_i32_2D_keepdims;\nmod reduce_min_i32_2D_axis_1;\nmod reduce_min_i8_1D;\nmod reduce_min_i8_2D_default;\nmod reduce_min_i8_2D_keepdims;\nmod reduce_min_i8_2D_axis_1;\nmod reduce_min_u32_1D;\nmod reduce_min_u32_2D_default;\nmod reduce_min_u32_2D_keepdims;\nmod reduce_min_u32_2D_axis_1;\nmod sequence_construct_fp16x16;\nmod sequence_construct_fp8x23;\nmod sequence_construct_i32;\nmod sequence_construct_i8;\nmod sequence_construct_u32;\nmod shrink_hard_fp16x16;\nmod shrink_soft_fp16x16;\nmod shrink_hard_fp8x23;\nmod shrink_soft_fp8x23;\nmod sequence_empty_fp16x16;\nmod sequence_empty_fp8x23;\nmod sequence_empty_i32;\nmod sequence_empty_i8;\nmod sequence_empty_u32;\nmod reduce_mean_fp16x16_1D;\nmod reduce_mean_fp16x16_2D_default;\nmod reduce_mean_fp16x16_2D_keepdims;\nmod reduce_mean_fp16x16_2D_axis_1;\nmod reduce_mean_fp8x23_1D;\nmod reduce_mean_fp8x23_2D_default;\nmod reduce_mean_fp8x23_2D_keepdims;\nmod reduce_mean_fp8x23_2D_axis_1;\nmod reduce_mean_i32_1D;\nmod reduce_mean_i32_2D_default;\nmod reduce_mean_i32_2D_keepdims;\nmod reduce_mean_i32_2D_axis_1;\nmod reduce_mean_i8_1D;\nmod reduce_mean_i8_2D_default;\nmod reduce_mean_i8_2D_keepdims;\nmod reduce_mean_i8_2D_axis_1;\nmod reduce_mean_u32_1D;\nmod reduce_mean_u32_2D_default;\nmod reduce_mean_u32_2D_keepdims;\nmod reduce_mean_u32_2D_axis_1;\nmod pow_fp16x16;\nmod pow_fp16x16_broadcast;\nmod pow_fp8x23;\nmod pow_fp8x23_broadcast;\nmod sequence_erase_u32_positive;\nmod sequence_erase_u32_negative;\nmod sequence_erase_u32_empty;\nmod sequence_erase_fp16x16_positive;\nmod sequence_erase_fp16x16_negative;\nmod sequence_erase_fp16x16_empty;\nmod sequence_erase_fp8x23_positive;\nmod sequence_erase_fp8x23_negative;\nmod sequence_erase_fp8x23_empty;\nmod sequence_erase_i32_positive;\nmod sequence_erase_i32_negative;\nmod sequence_erase_i32_empty;\nmod sequence_erase_i8_positive;\nmod sequence_erase_i8_negative;\nmod sequence_erase_i8_empty;\nmod sequence_insert_fp16x16;\nmod sequence_insert_fp8x23;\nmod sequence_insert_i32;\nmod sequence_insert_i8;\nmod sequence_insert_u32;\nmod concat_from_sequence_fp8x23_new_axis_zero;\nmod concat_from_sequence_fp8x23_new_axis_one;\nmod concat_from_sequence_fp8x23_new_axis_default;\nmod concat_from_sequence_fp16x16_new_axis_zero;\nmod concat_from_sequence_fp16x16_new_axis_one;\nmod concat_from_sequence_fp16x16_new_axis_default;\nmod concat_from_sequence_i32_new_axis_zero;\nmod concat_from_sequence_i32_new_axis_one;\nmod concat_from_sequence_i32_new_axis_default;\nmod concat_from_sequence_i8_new_axis_zero;\nmod concat_from_sequence_i8_new_axis_one;\nmod concat_from_sequence_i8_new_axis_default;\nmod concat_from_sequence_u32_new_axis_zero;\nmod concat_from_sequence_u32_new_axis_one;\nmod concat_from_sequence_u32_new_axis_default;\nmod is_nan_fp16x16;\nmod is_nan_fp8x23;\nmod is_inf_fp16x16;\nmod is_inf_fp8x23;\nmod is_inf_i32;\nmod is_inf_i8;\nmod is_inf_u32;\nmod is_pos_inf_fp16x16;\nmod is_neg_inf_fp16x16;\nmod is_pos_inf_fp8x23;\nmod is_neg_inf_fp8x23;\nmod is_pos_inf_i32;\nmod is_neg_inf_i32;\nmod is_pos_inf_i8;\nmod is_neg_inf_i8;\nmod reduce_log_sum_fp8x23_export_do_not_keepdims;\nmod reduce_log_sum_fp8x23_export_keepdims;\nmod reduce_log_sum_fp8x23_export_negative_axes_keepdims;\nmod reduce_log_sum_fp16x16_export_do_not_keepdims;\nmod reduce_log_sum_fp16x16_export_keepdims;\nmod reduce_log_sum_fp16x16_export_negative_axes_keepdims;\nmod and_bool;\nmod erf_fp16x16;\nmod erf_fp8x23;\nmod unique_fp16x16_without_axis_sorted;\nmod unique_fp16x16_with_axis_zero_sorted;\nmod unique_u32_without_axis_sorted;\nmod unique_u32_without_axis_not_sorted;\nmod unique_u32_with_axis_zero_sorted;\nmod unique_u32_with_axis_zero_not_sorted;\nmod unique_u32_with_axis_one_sorted;\nmod unique_u32_with_axis_one_not_sorted;\nmod gather_nd_fp16x16_3d_default;\nmod gather_nd_fp16x16_3d_batch_dims1;\nmod gather_nd_fp16x16_3d_batch_dims2;\nmod gather_nd_fp8x23_3d_default;\nmod gather_nd_fp8x23_3d_batch_dims1;\nmod gather_nd_fp8x23_3d_batch_dims2;\nmod gather_nd_i32_3d_default;\nmod gather_nd_i32_3d_batch_dims1;\nmod gather_nd_i32_3d_batch_dims2;\nmod gather_nd_i8_3d_default;\nmod gather_nd_i8_3d_batch_dims1;\nmod gather_nd_u32_default;\nmod gather_nd_u32_batch_dims1;\nmod gather_nd_u32_batch_dims2;\nmod resize_upsample_scales_nearest;\nmod resize_downsample_scales_cubic;\nmod resize_downsample_scales_cubic_A_n0p5_exclude_outside;\nmod resize_downsample_scales_cubic_align_corners;\nmod resize_upsample_scales_linear;\nmod resize_downsample_scales_linear_align_corners;\nmod resize_downsample_scales_nearest;\nmod resize_upsample_scales_cubic;\nmod resize_upsample_scales_cubic_A_n0p5_exclude_outside;\nmod resize_upsample_scales_cubic_align_corners;\nmod resize_upsample_scales_cubic_asymmetric;\nmod resize_upsample_scales_linear_align_corners;\nmod resize_upsample_sizes_nearest;\nmod resize_upsample_sizes_cubic;\nmod resize_downsample_sizes_cubic;\nmod resize_downsample_sizes_nearest;\nmod resize_upsample_scales_linear_half_pixel_symmetric;\nmod resize_downsample_scales_cubic_antialias;\nmod resize_downsample_scales_linear_antialias;\nmod resize_downsample_sizes_cubic_antialias;\nmod resize_downsample_sizes_linear_pytorch_half_pixel;\nmod resize_tf_crop_and_resize;\nmod resize_tf_crop_and_resize_extrapolation_value;\nmod resize_upsample_scales_nearest_axes_2_3;\nmod resize_upsample_scales_nearest_axes_3_2;\nmod resize_upsample_sizes_nearest_axes_2_3;\nmod resize_upsample_sizes_nearest_ceil_half_pixel;\nmod resize_upsample_sizes_nearest_floor_align_corners;\nmod resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric;\nmod resize_downsample_scales_linear_half_pixel_symmetric;\nmod resize_downsample_sizes_nearest_not_larger;\nmod resize_downsample_sizes_nearest_not_smaller;\nmod resize_tf_crop_and_resize_axes_2_3;\nmod resize_tf_crop_and_resize_axes_3_2;\nmod resize_upsample_sizes_nearest_axes_3_2;\nmod resize_upsample_sizes_nearest_not_larger;\nmod resize_upsample_sizes_nearest_not_smaller;\nmod compress_fp16x16_3d_default;\nmod compress_fp16x16_3d_axis1;\nmod compress_fp16x16_3d_axis2;\nmod compress_fp16x16_3d_axis3;\nmod compress_fp16x16_3d_noaxis;\nmod compress_fp8x23_3d_default;\nmod compress_fp8x23_3d_axis1;\nmod compress_fp8x23_3d_axis2;\nmod compress_i32_3d_default;\nmod compress_i32_3d_axis1;\nmod compress_i32_3d_axis2;\nmod compress_i8_3d_default;\nmod compress_i8_3d_axis1;\nmod compress_i8_3d_axis2;\nmod compress_u32_3d_default;\nmod compress_u32_3d_axis1;\nmod compress_u32_3d_axis2;\nmod compress_u32_3d_axis2_2;\nmod compress_u32_3d_axis3;\nmod reduce_log_sum_exp_fp32x32_export_do_not_keepdims;\nmod reduce_log_sum_exp_fp32x32_export_keepdims;\nmod reduce_log_sum_exp_fp32x32_export_negative_axes_keepdims;\nmod layer_normalization_default_axis;\nmod layer_normalization_4d_axis0;\nmod layer_normalization_4d_axis1;\nmod layer_normalization_4d_axis2;\nmod layer_normalization_4d_axis3;\nmod layer_normalization_3d_axis0_epsilon;\nmod layer_normalization_3d_axis_negative_3_epsilon;\nmod layer_normalization_3d_axis1_epsilon;\nmod layer_normalization_3d_axis2_epsilon;\nmod layer_normalization_4d_axis_negative_4;\nmod layer_normalization_4d_axis_negative_3;\nmod layer_normalization_4d_axis_negative_2;\nmod layer_normalization_4d_axis_negative_1;\nmod layer_normalization_3d_axis_negative_2_epsilon;\nmod layer_normalization_3d_axis_negative_1_epsilon;\nmod layer_normalization_test;\nmod split_u32_1d_equal_parts;\nmod split_u32_2d_equal_parts;\nmod split_u32_zero_size;\nmod split_u32_1d_variable_parts;\nmod split_u32_2d_variable_parts;\nmod split_u32_1d_uneven;\nmod split_u32_2d_uneven;\nmod split_fp16x16_1d_equal_parts;\nmod split_fp16x16_1d_variable_parts;\nmod split_fp16x16_2d_equal_parts;\nmod split_fp16x16_2d_variable_parts;\nmod split_fp16x16_zero_size;\nmod split_fp16x16_1d_uneven;\nmod split_fp16x16_2d_uneven;\nmod grid_sample;\nmod grid_sample_cubic;\nmod grid_sample_aligncorners;\nmod grid_sample_nearest;\nmod grid_sample_nearest_aligncorner;\nmod grid_sample_padding_border;\nmod grid_sample_padding_reflection;\nmod grid_sample_padding_zeros;\nmod col2im;\nmod col2im_5D;\nmod col2im_dilations;\nmod col2im_pads;\nmod col2im_strides;\nmod random_uniform_like_fp16x16;\nmod random_uniform_like_fp8x23;\nmod range_fp8x23;\nmod range_fp16x16;\nmod range_i32;\nmod range_i8;\nmod range_u32;\nmod hann_window_fp8x23;\nmod hann_window_fp16x16;\nmod hamming_window_fp16x16;\nmod hamming_window_fp8x23;\nmod blackman_window_fp16x16;\nmod blackman_window_fp8x23;\nmod split_to_sequence_fp16x16_1d_equal_parts;\nmod split_to_sequence_fp16x16_1d_variable_parts;\nmod split_to_sequence_fp16x16_2d_equal_parts;\nmod split_to_sequence_fp16x16_2d_variable_parts;\nmod split_to_sequence_fp16x16_zero_size;\nmod split_to_sequence_fp16x16_1d_uneven;\nmod split_to_sequence_fp16x16_2d_uneven;\nmod split_to_sequence_u32_1d_equal_parts;\nmod split_to_sequence_u32_1d_variable_parts;\nmod split_to_sequence_u32_2d_equal_parts;\nmod split_to_sequence_u32_2d_variable_parts;\nmod split_to_sequence_u32_zero_size;\nmod split_to_sequence_u32_1d_uneven;\nmod split_to_sequence_u32_2d_uneven;\nmod split_to_sequence_2d_scalar;\nmod split_to_sequence_2d_nokeepdims;\nmod split_to_sequence_1d_nokeepdims;\nmod reverse_sequence_fp16x16_batch_equal_parts;\nmod reverse_sequence_fp16x16_time_equal_parts;\nmod reverse_sequence_i32_batch_equal_parts;\nmod reverse_sequence_i32_time_equal_parts;\nmod reverse_sequence_i8_batch_equal_parts;\nmod reverse_sequence_i8_time_equal_parts;\nmod reverse_sequence_u32_4x4_batch;\nmod reverse_sequence_u32_4x4_time;\nmod reverse_sequence_u32_3x3_batch;\nmod reverse_sequence_u32_3x3_time;\nmod reverse_sequence_different_dimensions_4_5;\nmod reverse_sequence_different_dimensions_2_4;\nmod reverse_sequence_different_dimensions_1_6;\nmod reverse_sequence_different_dimensions_3x9_batch;\nmod reverse_sequence_different_dimensions_3x9_time;\nmod conv_transpose;\nmod conv_transpose_1d;\nmod conv_transpose_3d;\nmod conv_transpose_attributes;\nmod conv_transpose_autopad_same;\nmod conv_transpose_dilations;\nmod conv_transpose_pads;\nmod conv_transpose_group_2;\nmod conv_transpose_group_2_image_3;\nmod depth_to_space_fp16x16;\nmod depth_to_space_fp8x23;\nmod depth_to_space_i32;\nmod depth_to_space_i8;\nmod depth_to_space_u32;\nmod space_to_depth_fp16x16;\nmod space_to_depth_fp8x23;\nmod space_to_depth_i32;\nmod space_to_depth_i8;\nmod space_to_depth_u32;\nmod scatter_nd_fp16x16_3d_default;\nmod scatter_nd_fp16x16_3d_add;\nmod scatter_nd_fp16x16_3d_mul;\nmod scatter_nd_fp16x16_3d_max;\nmod scatter_nd_fp16x16_3d_min;\nmod scatter_nd_fp8x23_3d_default;\nmod scatter_nd_fp8x23_3d_add;\nmod scatter_nd_fp8x23_3d_mul;\nmod scatter_nd_fp8x23_3d_max;\nmod scatter_nd_fp8x23_3d_min;\nmod scatter_nd_u32_default;\nmod scatter_nd_u32_add;\nmod scatter_nd_u32_mul;\nmod scatter_nd_u32_max;\nmod scatter_nd_u32_min;\nmod conv_2D_with_padding;\nmod conv_1D_no_padding;\nmod conv_1D_with_padding;\nmod conv_3D_no_padding;\nmod conv_3D_with_padding;\nmod conv_4D_no_padding;\nmod conv_2D_with_2_groups;\nmod conv_2D_with_autopad_same;\nmod conv_2D_with_strides_asymmetric_padding;\nmod conv_2D_with_strides_with_padding;\nmod conv_4D_with_padding;\nmod label_encoder_fp16x16_3d_default;\nmod label_encoder_fp8x23_default;\nmod label_encoder_i8_default;\nmod label_encoder_i32_default;\nmod label_encoder_u32_default;\nmod gather_fp16x16_3d_default;\nmod gather_fp16x16_3d_axis1;\nmod gather_fp16x16_3d_axis2;\nmod gather_negative_indices;\nmod gather_negative_axis;\nmod less_fp16x16;\nmod less_fp16x16_broadcast;\nmod less_fp8x23;\nmod less_fp8x23_broadcast;\nmod less_i32;\nmod less_i32_broadcast;\nmod less_i8;\nmod less_i8_broadcast;\nmod less_u32;\nmod less_u32_broadcast;\nmod reshape_extended_dims;\nmod reshape_negative_dim;\nmod reshape_negative_extended_dims;\nmod reshape_one_dim;\nmod reshape_reduced_dims;\nmod reshape_reordered_all_dims;\nmod reshape_reordered_last_dims;\nmod reshape_zero_and_negative_dim;\nmod reshape_zero_dim;\nmod reduce_sum_default_axes_keepdims;\nmod reduce_sum_empty_axes_input_noop;\nmod reduce_sum_keep_dims;\nmod reduce_sum_negative_axes_keepdims;\nmod reduce_sum_no_keep_dims;\nmod gather_elements_default;\nmod gather_elements_axis1;\nmod gather_elements_axis2;\nmod gather_elements_negative_indices;\nmod softmax_axis_0;\nmod softmax_axis_1;\nmod softmax_axis_2;\nmod softmax_axis_minus_1;\nmod argmax_default_axes_keepdims;\nmod argmax_default_axes_keepdims_select_last_index;\nmod argmax_keepdims;\nmod argmax_keepdims_select_last_index;\nmod argmax_negative_axis_keepdims;\nmod argmax_negative_axis_keepdims_select_last_index;\nmod argmax_no_keepdims;\nmod argmax_no_keepdims_select_last_index;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_abs_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.abs();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_abs_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.abs();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32Tensor;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_abs_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.abs();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32Tensor;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-35);\n    data.append(106);\n    data.append(91);\n    data.append(-12);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32Tensor;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(35);\n    data.append(106);\n    data.append(91);\n    data.append(12);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I8Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_abs_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.abs();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8Tensor;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-85);\n    data.append(100);\n    data.append(-90);\n    data.append(-40);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/abs_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8Tensor;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(85);\n    data.append(100);\n    data.append(90);\n    data.append(40);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acos_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.acos();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 51202, sign: true });\n    data.append(FP16x16 { mag: 49944, sign: false });\n    data.append(FP16x16 { mag: 18761, sign: false });\n    data.append(FP16x16 { mag: 64655, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 161711, sign: false });\n    data.append(FP16x16 { mag: 46154, sign: false });\n    data.append(FP16x16 { mag: 83915, sign: false });\n    data.append(FP16x16 { mag: 195133, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acos_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.acos();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3764690, sign: false });\n    data.append(FP8x23 { mag: 556457, sign: true });\n    data.append(FP8x23 { mag: 529360, sign: false });\n    data.append(FP8x23 { mag: 2252561, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acos_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 9272682, sign: false });\n    data.append(FP8x23 { mag: 13733660, sign: false });\n    data.append(FP8x23 { mag: 12647081, sign: false });\n    data.append(FP8x23 { mag: 15457344, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acosh_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.acosh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 278211, sign: false });\n    data.append(FP16x16 { mag: 184787, sign: false });\n    data.append(FP16x16 { mag: 83173, sign: false });\n    data.append(FP16x16 { mag: 258400, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 139248, sign: false });\n    data.append(FP16x16 { mag: 111195, sign: false });\n    data.append(FP16x16 { mag: 47062, sign: false });\n    data.append(FP16x16 { mag: 134255, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acosh_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.acosh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 11868883, sign: false });\n    data.append(FP8x23 { mag: 28161016, sign: false });\n    data.append(FP8x23 { mag: 27794185, sign: false });\n    data.append(FP8x23 { mag: 28651727, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/acosh_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 7399094, sign: false });\n    data.append(FP8x23 { mag: 15781079, sign: false });\n    data.append(FP8x23 { mag: 15665784, sign: false });\n    data.append(FP8x23 { mag: 15932759, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(-2);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(-3);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(-4);\n    data.append(0);\n    data.append(-3);\n    data.append(-6);\n    data.append(-1);\n    data.append(0);\n    data.append(-3);\n    data.append(3);\n    data.append(2);\n    data.append(-2);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(-2);\n    data.append(3);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(-4);\n    data.append(2);\n    data.append(-3);\n    data.append(4);\n    data.append(-1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-3);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(-2);\n    data.append(-2);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(-2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(3);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-4);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(-6);\n    data.append(-2);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(-5);\n    data.append(0);\n    data.append(-3);\n    data.append(-4);\n    data.append(-3);\n    data.append(-3);\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(-4);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-1);\n    data.append(-4);\n    data.append(-4);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 + input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/add_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_and_bool() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = BoolTensor::and(@input_0, @input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn input_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn input_1() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_and_bool_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = BoolTensor::and(@input_0, @input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn input_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn input_1() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/and_bool_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(true);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_default_axes_keepdims() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(0, Option::Some(true), Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims_select_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_default_axes_keepdims_select_last_index() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims_select_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_default_axes_keepdims_select_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_keepdims() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(1, Option::Some(true), Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims_select_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_keepdims_select_last_index() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(1, Option::Some(true), Option::Some(true));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims_select_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_keepdims_select_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_negative_axis_keepdims() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(-1, Option::Some(true), Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims_select_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_negative_axis_keepdims_select_last_index() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(-1, Option::Some(true), Option::Some(true));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims_select_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_negative_axis_keepdims_select_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_no_keepdims() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(1, Option::Some(false), Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims_select_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmax_no_keepdims_select_last_index() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.argmax(1, Option::Some(false), Option::Some(true));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims_select_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 10, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmax_no_keepdims_select_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_1D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_1D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_1D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_1D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_2D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_2D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_2D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_2D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_3D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_3D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp16x16_3D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp16x16_3D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_1D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_1D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_1D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_1D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_2D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_2D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_2D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_2D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_3D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_3D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_fp8x23_3D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_fp8x23_3D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_1D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-34);\n    data.append(-47);\n    data.append(-23);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_1D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(73);\n    data.append(75);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_1D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(165);\n    data.append(215);\n    data.append(188);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_1D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_2D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(77);\n    data.append(3);\n    data.append(99);\n    data.append(-44);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_2D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(97);\n    data.append(-75);\n    data.append(27);\n    data.append(36);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_2D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-46);\n    data.append(39);\n    data.append(-26);\n    data.append(56);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_2D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_3D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-71);\n    data.append(99);\n    data.append(106);\n    data.append(-4);\n    data.append(-110);\n    data.append(56);\n    data.append(-77);\n    data.append(-6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_3D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-24);\n    data.append(-16);\n    data.append(-113);\n    data.append(-11);\n    data.append(-67);\n    data.append(53);\n    data.append(65);\n    data.append(29);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i32_3D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-120);\n    data.append(122);\n    data.append(-75);\n    data.append(123);\n    data.append(-48);\n    data.append(-96);\n    data.append(-113);\n    data.append(59);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i32_3D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_1D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-122);\n    data.append(48);\n    data.append(12);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_1D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-102);\n    data.append(94);\n    data.append(122);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_1D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-126);\n    data.append(-114);\n    data.append(-119);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_1D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_2D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-5);\n    data.append(96);\n    data.append(-59);\n    data.append(-110);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_2D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-91);\n    data.append(-120);\n    data.append(62);\n    data.append(-4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_2D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(90);\n    data.append(-107);\n    data.append(11);\n    data.append(77);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_2D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_3D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(104);\n    data.append(91);\n    data.append(-75);\n    data.append(51);\n    data.append(-57);\n    data.append(-22);\n    data.append(-13);\n    data.append(72);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_3D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-7);\n    data.append(-74);\n    data.append(93);\n    data.append(-43);\n    data.append(77);\n    data.append(-8);\n    data.append(39);\n    data.append(-121);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_i8_3D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-73);\n    data.append(-96);\n    data.append(-90);\n    data.append(9);\n    data.append(-99);\n    data.append(-18);\n    data.append(-49);\n    data.append(-30);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_i8_3D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_1D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(247);\n    data.append(56);\n    data.append(43);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_1D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(48);\n    data.append(249);\n    data.append(180);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_1D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(196);\n    data.append(188);\n    data.append(28);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_1D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_2D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(85);\n    data.append(201);\n    data.append(161);\n    data.append(249);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_2D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(242);\n    data.append(21);\n    data.append(196);\n    data.append(65);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_2D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(95);\n    data.append(155);\n    data.append(175);\n    data.append(231);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_2D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_3D_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(132);\n    data.append(217);\n    data.append(50);\n    data.append(22);\n    data.append(79);\n    data.append(215);\n    data.append(166);\n    data.append(125);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_keepdims_false.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_3D_keepdims_false() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::Some(false), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_keepdims_false/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(133);\n    data.append(237);\n    data.append(19);\n    data.append(140);\n    data.append(162);\n    data.append(214);\n    data.append(247);\n    data.append(234);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_keepdims_false/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_last_index.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_argmin_u32_3D_last_index() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.argmin(0, Option::None(()), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_last_index/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(21);\n    data.append(206);\n    data.append(245);\n    data.append(180);\n    data.append(229);\n    data.append(107);\n    data.append(167);\n    data.append(193);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/argmin_u32_3D_last_index/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_1D_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_1D_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_1D_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_1D_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_2D_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_2D_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_2D_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_2D_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(1);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_3D_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_3D_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_array_feature_extractor_3D_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::array_feature_extractor(@input_0, input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(1);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/array_feature_extractor_3D_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(-2);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asin_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.asin();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7855, sign: false });\n    data.append(FP16x16 { mag: 57259, sign: false });\n    data.append(FP16x16 { mag: 44465, sign: true });\n    data.append(FP16x16 { mag: 23854, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7874, sign: false });\n    data.append(FP16x16 { mag: 69649, sign: false });\n    data.append(FP16x16 { mag: 48870, sign: true });\n    data.append(FP16x16 { mag: 24414, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asin_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.asin();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4179211, sign: false });\n    data.append(FP8x23 { mag: 3678986, sign: true });\n    data.append(FP8x23 { mag: 755318, sign: true });\n    data.append(FP8x23 { mag: 4357027, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asin_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4374848, sign: false });\n    data.append(FP8x23 { mag: 3808479, sign: true });\n    data.append(FP8x23 { mag: 756342, sign: true });\n    data.append(FP8x23 { mag: 4581408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asinh_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.asinh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 169913, sign: false });\n    data.append(FP16x16 { mag: 256877, sign: false });\n    data.append(FP16x16 { mag: 257385, sign: false });\n    data.append(FP16x16 { mag: 187249, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 110173, sign: false });\n    data.append(FP16x16 { mag: 135989, sign: false });\n    data.append(FP16x16 { mag: 136114, sign: false });\n    data.append(FP16x16 { mag: 116149, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asinh_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.asinh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 20018460, sign: false });\n    data.append(FP8x23 { mag: 27476659, sign: false });\n    data.append(FP8x23 { mag: 29261793, sign: false });\n    data.append(FP8x23 { mag: 27170230, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/asinh_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 13456914, sign: false });\n    data.append(FP8x23 { mag: 15956279, sign: false });\n    data.append(FP8x23 { mag: 16462601, sign: false });\n    data.append(FP8x23 { mag: 15866344, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_atan_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.atan();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 4877388, sign: false });\n    data.append(FP16x16 { mag: 314010, sign: true });\n    data.append(FP16x16 { mag: 78417, sign: true });\n    data.append(FP16x16 { mag: 504882, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 102063, sign: false });\n    data.append(FP16x16 { mag: 89459, sign: true });\n    data.append(FP16x16 { mag: 57320, sign: true });\n    data.append(FP16x16 { mag: 94484, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_atan_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.atan();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 82419129, sign: false });\n    data.append(FP8x23 { mag: 513495334, sign: false });\n    data.append(FP8x23 { mag: 84734076, sign: false });\n    data.append(FP8x23 { mag: 594378282, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/atan_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 12325933, sign: false });\n    data.append(FP8x23 { mag: 13039768, sign: false });\n    data.append(FP8x23 { mag: 12349026, sign: false });\n    data.append(FP8x23 { mag: 13058411, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::TensorTrait;\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::assert_eq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_binarizer_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::binarizer(@input_0, Option::Some(FixedTrait::new(65536, false)));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::FixedTrait;\nuse orion::numbers::FP16x16;\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 116651, sign: true });\n    data.append(FP16x16 { mag: 45255, sign: false });\n    data.append(FP16x16 { mag: 132067, sign: true });\n    data.append(FP16x16 { mag: 83631, sign: true });\n    data.append(FP16x16 { mag: 151971, sign: false });\n    data.append(FP16x16 { mag: 46816, sign: true });\n    data.append(FP16x16 { mag: 4353, sign: false });\n    data.append(FP16x16 { mag: 188531, sign: false });\n    data.append(FP16x16 { mag: 104593, sign: false });\n    data.append(FP16x16 { mag: 41997, sign: true });\n    data.append(FP16x16 { mag: 127090, sign: false });\n    data.append(FP16x16 { mag: 79053, sign: false });\n    data.append(FP16x16 { mag: 139184, sign: true });\n    data.append(FP16x16 { mag: 439, sign: false });\n    data.append(FP16x16 { mag: 115688, sign: false });\n    data.append(FP16x16 { mag: 184428, sign: true });\n    data.append(FP16x16 { mag: 161855, sign: true });\n    data.append(FP16x16 { mag: 42551, sign: true });\n    data.append(FP16x16 { mag: 40207, sign: false });\n    data.append(FP16x16 { mag: 72062, sign: false });\n    data.append(FP16x16 { mag: 195673, sign: false });\n    data.append(FP16x16 { mag: 27413, sign: true });\n    data.append(FP16x16 { mag: 173891, sign: true });\n    data.append(FP16x16 { mag: 69697, sign: true });\n    data.append(FP16x16 { mag: 162632, sign: false });\n    data.append(FP16x16 { mag: 53852, sign: true });\n    data.append(FP16x16 { mag: 93775, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::FixedTrait;\nuse orion::numbers::FP16x16;\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::TensorTrait;\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::assert_eq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_binarizer_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::binarizer(@input_0, Option::Some(FixedTrait::new(8388608, false)));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::FixedTrait;\nuse orion::numbers::FP8x23;\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 19910639, sign: true });\n    data.append(FP8x23 { mag: 16200109, sign: false });\n    data.append(FP8x23 { mag: 7318221, sign: false });\n    data.append(FP8x23 { mag: 3839710, sign: true });\n    data.append(FP8x23 { mag: 5198439, sign: true });\n    data.append(FP8x23 { mag: 13440550, sign: false });\n    data.append(FP8x23 { mag: 3475736, sign: false });\n    data.append(FP8x23 { mag: 12659448, sign: false });\n    data.append(FP8x23 { mag: 22040361, sign: true });\n    data.append(FP8x23 { mag: 16960032, sign: true });\n    data.append(FP8x23 { mag: 20980250, sign: false });\n    data.append(FP8x23 { mag: 19528339, sign: true });\n    data.append(FP8x23 { mag: 24567413, sign: true });\n    data.append(FP8x23 { mag: 3374986, sign: true });\n    data.append(FP8x23 { mag: 5428617, sign: false });\n    data.append(FP8x23 { mag: 16499249, sign: true });\n    data.append(FP8x23 { mag: 14111693, sign: false });\n    data.append(FP8x23 { mag: 22806062, sign: false });\n    data.append(FP8x23 { mag: 5020958, sign: false });\n    data.append(FP8x23 { mag: 20749322, sign: false });\n    data.append(FP8x23 { mag: 7503709, sign: true });\n    data.append(FP8x23 { mag: 24435895, sign: false });\n    data.append(FP8x23 { mag: 12933406, sign: true });\n    data.append(FP8x23 { mag: 11401085, sign: true });\n    data.append(FP8x23 { mag: 97331, sign: false });\n    data.append(FP8x23 { mag: 21216642, sign: true });\n    data.append(FP8x23 { mag: 2018862, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/binarizer_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::FixedTrait;\nuse orion::numbers::FP8x23;\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/blackman_window_fp16x16.cairo",
        "content": "mod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_blackman_window_fp16x16() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::blackman_window(FP16x16 { mag: 196608, sign: false }, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/blackman_window_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1, sign: true });\n    data.append(FP16x16 { mag: 41288, sign: false });\n    data.append(FP16x16 { mag: 41288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/blackman_window_fp8x23.cairo",
        "content": "mod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_blackman_window_fp8x23() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::blackman_window(FP8x23 { mag: 25165824, sign: false }, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/blackman_window_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1, sign: true });\n    data.append(FP8x23 { mag: 8388605, sign: false });\n    data.append(FP8x23 { mag: 1, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_ceil_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.ceil();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 32172, sign: false });\n    data.append(FP16x16 { mag: 3356, sign: false });\n    data.append(FP16x16 { mag: 42435, sign: true });\n    data.append(FP16x16 { mag: 31055, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_ceil_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.ceil();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3513846, sign: false });\n    data.append(FP8x23 { mag: 5898636, sign: true });\n    data.append(FP8x23 { mag: 1928949, sign: true });\n    data.append(FP8x23 { mag: 3104735, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/ceil_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_fp16x16_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0\n        .clip(\n            Option::Some(FP16x16 { mag: 655360, sign: true }),\n            Option::Some(FP16x16 { mag: 1310720, sign: false })\n        );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_fp16x16_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0\n        .clip(\n            Option::Some(FP16x16 { mag: 655360, sign: true }),\n            Option::Some(FP16x16 { mag: 1310720, sign: false })\n        );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 3211264, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 5636096, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 1769472, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 3211264, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 8257536, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 8257536, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp16x16_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::numbers::{FixedTrait, FP8x23};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_fp8x23_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0\n        .clip(\n            Option::Some(FP8x23 { mag: 83886080, sign: true }),\n            Option::Some(FP8x23 { mag: 167772160, sign: false })\n        );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::numbers::{FixedTrait, FP8x23};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_fp8x23_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0\n        .clip(\n            Option::Some(FP8x23 { mag: 83886080, sign: true }),\n            Option::Some(FP8x23 { mag: 167772160, sign: false })\n        );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 771751936, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 788529152, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 771751936, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 1048576000, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: true });\n    data.append(FP8x23 { mag: 293601280, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 1048576000, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: true });\n    data.append(FP8x23 { mag: 788529152, sign: true });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 503316480, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 184549376, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 260046848, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: true });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_fp8x23_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_i32_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(-10_i32), Option::Some(20_i32));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-72);\n    data.append(41);\n    data.append(8);\n    data.append(-66);\n    data.append(62);\n    data.append(-57);\n    data.append(1);\n    data.append(-34);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-10);\n    data.append(20);\n    data.append(8);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(1);\n    data.append(-10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_i32_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(-10_i32), Option::Some(20_i32));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(52);\n    data.append(-112);\n    data.append(-115);\n    data.append(-114);\n    data.append(103);\n    data.append(111);\n    data.append(-96);\n    data.append(34);\n    data.append(79);\n    data.append(-25);\n    data.append(-24);\n    data.append(70);\n    data.append(69);\n    data.append(-89);\n    data.append(71);\n    data.append(-18);\n    data.append(-116);\n    data.append(-73);\n    data.append(-44);\n    data.append(-14);\n    data.append(-65);\n    data.append(-97);\n    data.append(125);\n    data.append(-124);\n    data.append(112);\n    data.append(91);\n    data.append(-90);\n    data.append(107);\n    data.append(-74);\n    data.append(82);\n    data.append(17);\n    data.append(-83);\n    data.append(-115);\n    data.append(116);\n    data.append(79);\n    data.append(-5);\n    data.append(-93);\n    data.append(-74);\n    data.append(33);\n    data.append(-61);\n    data.append(-111);\n    data.append(-101);\n    data.append(-54);\n    data.append(-71);\n    data.append(-20);\n    data.append(70);\n    data.append(28);\n    data.append(49);\n    data.append(-64);\n    data.append(26);\n    data.append(64);\n    data.append(-66);\n    data.append(98);\n    data.append(-11);\n    data.append(23);\n    data.append(96);\n    data.append(74);\n    data.append(4);\n    data.append(-72);\n    data.append(-71);\n    data.append(-104);\n    data.append(7);\n    data.append(-59);\n    data.append(10);\n    data.append(-62);\n    data.append(-5);\n    data.append(30);\n    data.append(-47);\n    data.append(-85);\n    data.append(35);\n    data.append(-123);\n    data.append(-93);\n    data.append(-50);\n    data.append(2);\n    data.append(22);\n    data.append(-115);\n    data.append(-70);\n    data.append(-82);\n    data.append(-21);\n    data.append(119);\n    data.append(73);\n    data.append(75);\n    data.append(83);\n    data.append(-127);\n    data.append(82);\n    data.append(60);\n    data.append(-2);\n    data.append(-2);\n    data.append(50);\n    data.append(123);\n    data.append(-69);\n    data.append(58);\n    data.append(112);\n    data.append(33);\n    data.append(101);\n    data.append(16);\n    data.append(4);\n    data.append(123);\n    data.append(71);\n    data.append(40);\n    data.append(-29);\n    data.append(64);\n    data.append(-124);\n    data.append(-50);\n    data.append(-116);\n    data.append(0);\n    data.append(125);\n    data.append(-70);\n    data.append(-49);\n    data.append(47);\n    data.append(-18);\n    data.append(-58);\n    data.append(-71);\n    data.append(-45);\n    data.append(54);\n    data.append(28);\n    data.append(54);\n    data.append(-49);\n    data.append(74);\n    data.append(82);\n    data.append(-43);\n    data.append(107);\n    data.append(-46);\n    data.append(-41);\n    data.append(-19);\n    data.append(106);\n    data.append(40);\n    data.append(-70);\n    data.append(-32);\n    data.append(-111);\n    data.append(97);\n    data.append(79);\n    data.append(-95);\n    data.append(-12);\n    data.append(87);\n    data.append(86);\n    data.append(78);\n    data.append(11);\n    data.append(43);\n    data.append(-14);\n    data.append(-85);\n    data.append(0);\n    data.append(119);\n    data.append(60);\n    data.append(-101);\n    data.append(-81);\n    data.append(5);\n    data.append(106);\n    data.append(114);\n    data.append(-25);\n    data.append(-43);\n    data.append(37);\n    data.append(-10);\n    data.append(-122);\n    data.append(29);\n    data.append(82);\n    data.append(-25);\n    data.append(-18);\n    data.append(11);\n    data.append(-88);\n    data.append(71);\n    data.append(-83);\n    data.append(121);\n    data.append(-39);\n    data.append(11);\n    data.append(-40);\n    data.append(-18);\n    data.append(-35);\n    data.append(-108);\n    data.append(26);\n    data.append(-19);\n    data.append(-58);\n    data.append(-105);\n    data.append(29);\n    data.append(-11);\n    data.append(1);\n    data.append(-17);\n    data.append(-1);\n    data.append(-12);\n    data.append(-29);\n    data.append(-104);\n    data.append(-51);\n    data.append(-78);\n    data.append(16);\n    data.append(-43);\n    data.append(66);\n    data.append(62);\n    data.append(68);\n    data.append(-31);\n    data.append(-81);\n    data.append(-26);\n    data.append(-101);\n    data.append(126);\n    data.append(94);\n    data.append(87);\n    data.append(-30);\n    data.append(-41);\n    data.append(117);\n    data.append(75);\n    data.append(75);\n    data.append(-69);\n    data.append(50);\n    data.append(-42);\n    data.append(-104);\n    data.append(-36);\n    data.append(121);\n    data.append(8);\n    data.append(33);\n    data.append(84);\n    data.append(-108);\n    data.append(-55);\n    data.append(12);\n    data.append(-48);\n    data.append(62);\n    data.append(-122);\n    data.append(50);\n    data.append(121);\n    data.append(-67);\n    data.append(53);\n    data.append(-20);\n    data.append(99);\n    data.append(103);\n    data.append(-41);\n    data.append(-6);\n    data.append(110);\n    data.append(38);\n    data.append(-40);\n    data.append(52);\n    data.append(-23);\n    data.append(-26);\n    data.append(31);\n    data.append(-108);\n    data.append(29);\n    data.append(38);\n    data.append(111);\n    data.append(12);\n    data.append(30);\n    data.append(81);\n    data.append(-15);\n    data.append(118);\n    data.append(-10);\n    data.append(39);\n    data.append(63);\n    data.append(37);\n    data.append(22);\n    data.append(77);\n    data.append(119);\n    data.append(-49);\n    data.append(-106);\n    data.append(-108);\n    data.append(77);\n    data.append(-127);\n    data.append(-96);\n    data.append(-43);\n    data.append(-96);\n    data.append(75);\n    data.append(-54);\n    data.append(-66);\n    data.append(42);\n    data.append(17);\n    data.append(-106);\n    data.append(12);\n    data.append(88);\n    data.append(122);\n    data.append(-94);\n    data.append(60);\n    data.append(-67);\n    data.append(74);\n    data.append(-7);\n    data.append(78);\n    data.append(113);\n    data.append(-91);\n    data.append(14);\n    data.append(-38);\n    data.append(54);\n    data.append(77);\n    data.append(-39);\n    data.append(-86);\n    data.append(-25);\n    data.append(37);\n    data.append(7);\n    data.append(-44);\n    data.append(76);\n    data.append(43);\n    data.append(74);\n    data.append(32);\n    data.append(-52);\n    data.append(105);\n    data.append(-112);\n    data.append(-13);\n    data.append(-81);\n    data.append(-4);\n    data.append(92);\n    data.append(-39);\n    data.append(59);\n    data.append(-117);\n    data.append(3);\n    data.append(54);\n    data.append(-14);\n    data.append(-16);\n    data.append(39);\n    data.append(-44);\n    data.append(-24);\n    data.append(-29);\n    data.append(22);\n    data.append(-114);\n    data.append(-15);\n    data.append(-5);\n    data.append(-45);\n    data.append(49);\n    data.append(115);\n    data.append(-71);\n    data.append(74);\n    data.append(-20);\n    data.append(66);\n    data.append(22);\n    data.append(-93);\n    data.append(-124);\n    data.append(23);\n    data.append(-26);\n    data.append(-42);\n    data.append(54);\n    data.append(94);\n    data.append(-22);\n    data.append(100);\n    data.append(21);\n    data.append(-34);\n    data.append(31);\n    data.append(93);\n    data.append(6);\n    data.append(23);\n    data.append(57);\n    data.append(93);\n    data.append(122);\n    data.append(-32);\n    data.append(21);\n    data.append(50);\n    data.append(58);\n    data.append(-110);\n    data.append(-61);\n    data.append(86);\n    data.append(-77);\n    data.append(32);\n    data.append(6);\n    data.append(-33);\n    data.append(84);\n    data.append(44);\n    data.append(126);\n    data.append(-103);\n    data.append(-46);\n    data.append(5);\n    data.append(-81);\n    data.append(-23);\n    data.append(11);\n    data.append(-120);\n    data.append(-91);\n    data.append(-39);\n    data.append(-37);\n    data.append(-71);\n    data.append(-25);\n    data.append(-75);\n    data.append(117);\n    data.append(62);\n    data.append(-47);\n    data.append(-39);\n    data.append(3);\n    data.append(50);\n    data.append(13);\n    data.append(-6);\n    data.append(-91);\n    data.append(-28);\n    data.append(35);\n    data.append(96);\n    data.append(102);\n    data.append(90);\n    data.append(96);\n    data.append(-22);\n    data.append(98);\n    data.append(-8);\n    data.append(65);\n    data.append(115);\n    data.append(-75);\n    data.append(-101);\n    data.append(-31);\n    data.append(-93);\n    data.append(24);\n    data.append(117);\n    data.append(-81);\n    data.append(59);\n    data.append(32);\n    data.append(-93);\n    data.append(73);\n    data.append(2);\n    data.append(-49);\n    data.append(-102);\n    data.append(-121);\n    data.append(-75);\n    data.append(-61);\n    data.append(34);\n    data.append(96);\n    data.append(28);\n    data.append(28);\n    data.append(95);\n    data.append(-73);\n    data.append(53);\n    data.append(72);\n    data.append(-119);\n    data.append(77);\n    data.append(108);\n    data.append(0);\n    data.append(10);\n    data.append(94);\n    data.append(1);\n    data.append(-27);\n    data.append(19);\n    data.append(-56);\n    data.append(-109);\n    data.append(34);\n    data.append(106);\n    data.append(58);\n    data.append(-61);\n    data.append(81);\n    data.append(117);\n    data.append(14);\n    data.append(-18);\n    data.append(0);\n    data.append(41);\n    data.append(-103);\n    data.append(111);\n    data.append(118);\n    data.append(-106);\n    data.append(-114);\n    data.append(100);\n    data.append(35);\n    data.append(115);\n    data.append(-29);\n    data.append(-98);\n    data.append(72);\n    data.append(45);\n    data.append(18);\n    data.append(64);\n    data.append(-3);\n    data.append(-94);\n    data.append(21);\n    data.append(-75);\n    data.append(6);\n    data.append(111);\n    data.append(-61);\n    data.append(-28);\n    data.append(6);\n    data.append(-104);\n    data.append(113);\n    data.append(-55);\n    data.append(-37);\n    data.append(123);\n    data.append(-63);\n    data.append(-32);\n    data.append(65);\n    data.append(-23);\n    data.append(-117);\n    data.append(89);\n    data.append(90);\n    data.append(-97);\n    data.append(-36);\n    data.append(123);\n    data.append(30);\n    data.append(104);\n    data.append(-25);\n    data.append(5);\n    data.append(54);\n    data.append(-53);\n    data.append(3);\n    data.append(-69);\n    data.append(40);\n    data.append(101);\n    data.append(106);\n    data.append(4);\n    data.append(8);\n    data.append(19);\n    data.append(45);\n    data.append(96);\n    data.append(49);\n    data.append(-28);\n    data.append(67);\n    data.append(-113);\n    data.append(-106);\n    data.append(12);\n    data.append(6);\n    data.append(28);\n    data.append(87);\n    data.append(-57);\n    data.append(28);\n    data.append(75);\n    data.append(-118);\n    data.append(110);\n    data.append(-75);\n    data.append(-32);\n    data.append(49);\n    data.append(-5);\n    data.append(-115);\n    data.append(-68);\n    data.append(-29);\n    data.append(-122);\n    data.append(-96);\n    data.append(-34);\n    data.append(-98);\n    data.append(9);\n    data.append(-101);\n    data.append(7);\n    data.append(117);\n    data.append(-2);\n    data.append(-53);\n    data.append(-119);\n    data.append(-106);\n    data.append(117);\n    data.append(27);\n    data.append(73);\n    data.append(94);\n    data.append(126);\n    data.append(-105);\n    data.append(105);\n    data.append(61);\n    data.append(32);\n    data.append(-46);\n    data.append(-87);\n    data.append(8);\n    data.append(-112);\n    data.append(-60);\n    data.append(75);\n    data.append(94);\n    data.append(6);\n    data.append(64);\n    data.append(36);\n    data.append(-5);\n    data.append(-26);\n    data.append(60);\n    data.append(-85);\n    data.append(29);\n    data.append(-100);\n    data.append(-97);\n    data.append(-27);\n    data.append(56);\n    data.append(54);\n    data.append(60);\n    data.append(8);\n    data.append(-55);\n    data.append(-103);\n    data.append(-99);\n    data.append(104);\n    data.append(-53);\n    data.append(111);\n    data.append(-65);\n    data.append(48);\n    data.append(-28);\n    data.append(-73);\n    data.append(-59);\n    data.append(-56);\n    data.append(-34);\n    data.append(-108);\n    data.append(-85);\n    data.append(-95);\n    data.append(-97);\n    data.append(64);\n    data.append(-49);\n    data.append(-114);\n    data.append(-64);\n    data.append(7);\n    data.append(70);\n    data.append(97);\n    data.append(15);\n    data.append(-110);\n    data.append(-63);\n    data.append(95);\n    data.append(-110);\n    data.append(-53);\n    data.append(-118);\n    data.append(48);\n    data.append(121);\n    data.append(-113);\n    data.append(-116);\n    data.append(58);\n    data.append(-83);\n    data.append(-87);\n    data.append(-55);\n    data.append(-99);\n    data.append(-113);\n    data.append(121);\n    data.append(13);\n    data.append(-117);\n    data.append(13);\n    data.append(-94);\n    data.append(91);\n    data.append(5);\n    data.append(67);\n    data.append(55);\n    data.append(121);\n    data.append(121);\n    data.append(120);\n    data.append(44);\n    data.append(-50);\n    data.append(-101);\n    data.append(5);\n    data.append(-9);\n    data.append(45);\n    data.append(71);\n    data.append(-39);\n    data.append(90);\n    data.append(-59);\n    data.append(104);\n    data.append(-61);\n    data.append(37);\n    data.append(102);\n    data.append(113);\n    data.append(76);\n    data.append(-27);\n    data.append(27);\n    data.append(56);\n    data.append(1);\n    data.append(95);\n    data.append(122);\n    data.append(-102);\n    data.append(-21);\n    data.append(-35);\n    data.append(-97);\n    data.append(-119);\n    data.append(5);\n    data.append(25);\n    data.append(-122);\n    data.append(125);\n    data.append(8);\n    data.append(42);\n    data.append(-62);\n    data.append(59);\n    data.append(96);\n    data.append(-89);\n    data.append(122);\n    data.append(125);\n    data.append(-71);\n    data.append(-43);\n    data.append(-112);\n    data.append(-76);\n    data.append(72);\n    data.append(-26);\n    data.append(-9);\n    data.append(98);\n    data.append(-93);\n    data.append(-107);\n    data.append(-113);\n    data.append(-29);\n    data.append(-120);\n    data.append(49);\n    data.append(94);\n    data.append(-102);\n    data.append(124);\n    data.append(-77);\n    data.append(95);\n    data.append(-71);\n    data.append(38);\n    data.append(-109);\n    data.append(101);\n    data.append(-107);\n    data.append(22);\n    data.append(88);\n    data.append(118);\n    data.append(-28);\n    data.append(-84);\n    data.append(-124);\n    data.append(-8);\n    data.append(72);\n    data.append(12);\n    data.append(113);\n    data.append(94);\n    data.append(19);\n    data.append(107);\n    data.append(14);\n    data.append(-86);\n    data.append(-88);\n    data.append(75);\n    data.append(-25);\n    data.append(1);\n    data.append(55);\n    data.append(99);\n    data.append(-69);\n    data.append(115);\n    data.append(52);\n    data.append(106);\n    data.append(110);\n    data.append(-59);\n    data.append(64);\n    data.append(-10);\n    data.append(-119);\n    data.append(-78);\n    data.append(53);\n    data.append(116);\n    data.append(7);\n    data.append(100);\n    data.append(0);\n    data.append(-70);\n    data.append(-64);\n    data.append(88);\n    data.append(-76);\n    data.append(-91);\n    data.append(-35);\n    data.append(-6);\n    data.append(6);\n    data.append(-103);\n    data.append(-51);\n    data.append(115);\n    data.append(-98);\n    data.append(122);\n    data.append(-38);\n    data.append(20);\n    data.append(-34);\n    data.append(62);\n    data.append(6);\n    data.append(-99);\n    data.append(0);\n    data.append(-117);\n    data.append(-3);\n    data.append(-114);\n    data.append(-96);\n    data.append(-52);\n    data.append(-7);\n    data.append(62);\n    data.append(93);\n    data.append(-87);\n    data.append(12);\n    data.append(-99);\n    data.append(49);\n    data.append(0);\n    data.append(-98);\n    data.append(-46);\n    data.append(-11);\n    data.append(-5);\n    data.append(-120);\n    data.append(-37);\n    data.append(-29);\n    data.append(-77);\n    data.append(-83);\n    data.append(-90);\n    data.append(-86);\n    data.append(-61);\n    data.append(-91);\n    data.append(-45);\n    data.append(-91);\n    data.append(-79);\n    data.append(117);\n    data.append(76);\n    data.append(-39);\n    data.append(31);\n    data.append(-55);\n    data.append(13);\n    data.append(-12);\n    data.append(18);\n    data.append(85);\n    data.append(-7);\n    data.append(-40);\n    data.append(-80);\n    data.append(-25);\n    data.append(-63);\n    data.append(24);\n    data.append(-17);\n    data.append(-25);\n    data.append(77);\n    data.append(-115);\n    data.append(108);\n    data.append(2);\n    data.append(-115);\n    data.append(98);\n    data.append(-31);\n    data.append(-55);\n    data.append(-83);\n    data.append(-67);\n    data.append(76);\n    data.append(76);\n    data.append(17);\n    data.append(-31);\n    data.append(110);\n    data.append(21);\n    data.append(-86);\n    data.append(-8);\n    data.append(47);\n    data.append(-21);\n    data.append(-28);\n    data.append(-58);\n    data.append(83);\n    data.append(74);\n    data.append(-44);\n    data.append(17);\n    data.append(-19);\n    data.append(-37);\n    data.append(-1);\n    data.append(-36);\n    data.append(16);\n    data.append(-3);\n    data.append(82);\n    data.append(8);\n    data.append(41);\n    data.append(105);\n    data.append(-116);\n    data.append(-118);\n    data.append(97);\n    data.append(31);\n    data.append(-47);\n    data.append(-81);\n    data.append(-83);\n    data.append(-121);\n    data.append(-111);\n    data.append(-115);\n    data.append(-80);\n    data.append(-37);\n    data.append(-23);\n    data.append(120);\n    data.append(-35);\n    data.append(-122);\n    data.append(79);\n    data.append(-84);\n    data.append(53);\n    data.append(-37);\n    data.append(42);\n    data.append(-49);\n    data.append(-38);\n    data.append(15);\n    data.append(-29);\n    data.append(98);\n    data.append(-33);\n    data.append(-50);\n    data.append(99);\n    data.append(-21);\n    data.append(67);\n    data.append(73);\n    data.append(43);\n    data.append(103);\n    data.append(73);\n    data.append(-2);\n    data.append(-89);\n    data.append(89);\n    data.append(-65);\n    data.append(-102);\n    data.append(-88);\n    data.append(-22);\n    data.append(67);\n    data.append(-64);\n    data.append(-77);\n    data.append(-49);\n    data.append(95);\n    data.append(-35);\n    data.append(15);\n    data.append(40);\n    data.append(18);\n    data.append(99);\n    data.append(-24);\n    data.append(-93);\n    data.append(82);\n    data.append(-5);\n    data.append(70);\n    data.append(27);\n    data.append(0);\n    data.append(-86);\n    data.append(110);\n    data.append(65);\n    data.append(-47);\n    data.append(-124);\n    data.append(90);\n    data.append(31);\n    data.append(-23);\n    data.append(39);\n    data.append(116);\n    data.append(-116);\n    data.append(-5);\n    data.append(116);\n    data.append(-87);\n    data.append(96);\n    data.append(63);\n    data.append(96);\n    data.append(-74);\n    data.append(-39);\n    data.append(119);\n    data.append(-74);\n    data.append(100);\n    data.append(-34);\n    data.append(78);\n    data.append(-78);\n    data.append(94);\n    data.append(-45);\n    data.append(-49);\n    data.append(-84);\n    data.append(-124);\n    data.append(-5);\n    data.append(43);\n    data.append(-74);\n    data.append(-57);\n    data.append(53);\n    data.append(-40);\n    data.append(82);\n    data.append(79);\n    data.append(53);\n    data.append(59);\n    data.append(-77);\n    data.append(-87);\n    data.append(-118);\n    data.append(-109);\n    data.append(-108);\n    data.append(94);\n    data.append(17);\n    data.append(-83);\n    data.append(86);\n    data.append(3);\n    data.append(9);\n    data.append(-101);\n    data.append(6);\n    data.append(-47);\n    data.append(-46);\n    data.append(-34);\n    data.append(-41);\n    data.append(-76);\n    data.append(-13);\n    data.append(27);\n    data.append(-85);\n    data.append(-58);\n    data.append(33);\n    data.append(49);\n    data.append(9);\n    data.append(8);\n    data.append(-82);\n    data.append(-17);\n    data.append(49);\n    data.append(22);\n    data.append(38);\n    data.append(-97);\n    data.append(34);\n    data.append(-72);\n    data.append(-107);\n    data.append(-126);\n    data.append(86);\n    data.append(-40);\n    data.append(114);\n    data.append(93);\n    data.append(-77);\n    data.append(-9);\n    data.append(72);\n    data.append(72);\n    data.append(77);\n    data.append(20);\n    data.append(-85);\n    data.append(-47);\n    data.append(96);\n    data.append(22);\n    data.append(-55);\n    data.append(48);\n    data.append(119);\n    data.append(17);\n    data.append(-18);\n    data.append(89);\n    data.append(-28);\n    data.append(86);\n    data.append(5);\n    data.append(-121);\n    data.append(48);\n    data.append(28);\n    data.append(60);\n    data.append(-115);\n    data.append(-47);\n    data.append(68);\n    data.append(-81);\n    data.append(6);\n    data.append(-123);\n    data.append(-43);\n    data.append(-81);\n    data.append(-91);\n    data.append(-17);\n    data.append(-117);\n    data.append(-8);\n    data.append(56);\n    data.append(121);\n    data.append(-78);\n    data.append(76);\n    data.append(121);\n    data.append(-92);\n    data.append(-90);\n    data.append(5);\n    data.append(36);\n    data.append(78);\n    data.append(120);\n    data.append(106);\n    data.append(-8);\n    data.append(79);\n    data.append(119);\n    data.append(12);\n    data.append(-73);\n    data.append(52);\n    data.append(71);\n    data.append(111);\n    data.append(78);\n    data.append(4);\n    data.append(-115);\n    data.append(117);\n    data.append(34);\n    data.append(109);\n    data.append(37);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i32_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-5);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(4);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(7);\n    data.append(-10);\n    data.append(10);\n    data.append(-10);\n    data.append(-5);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(2);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-2);\n    data.append(-2);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(16);\n    data.append(4);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(0);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(11);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(0);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(11);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(11);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(1);\n    data.append(-10);\n    data.append(-1);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(16);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(8);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(12);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-6);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-7);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(14);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(7);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-4);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(3);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-5);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(6);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(6);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(-10);\n    data.append(-10);\n    data.append(11);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(3);\n    data.append(20);\n    data.append(13);\n    data.append(-6);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-8);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(2);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(0);\n    data.append(10);\n    data.append(20);\n    data.append(1);\n    data.append(-10);\n    data.append(19);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(14);\n    data.append(-10);\n    data.append(0);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(20);\n    data.append(-3);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(6);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(6);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(5);\n    data.append(20);\n    data.append(-10);\n    data.append(3);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(4);\n    data.append(8);\n    data.append(19);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(12);\n    data.append(6);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-5);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(9);\n    data.append(-10);\n    data.append(7);\n    data.append(20);\n    data.append(-2);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(8);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(6);\n    data.append(20);\n    data.append(20);\n    data.append(-5);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(8);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(7);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(13);\n    data.append(-10);\n    data.append(13);\n    data.append(-10);\n    data.append(20);\n    data.append(5);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(-9);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(1);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(8);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-9);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-8);\n    data.append(20);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(19);\n    data.append(20);\n    data.append(14);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(1);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(7);\n    data.append(20);\n    data.append(0);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-6);\n    data.append(6);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(6);\n    data.append(-10);\n    data.append(0);\n    data.append(-10);\n    data.append(-3);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-7);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(12);\n    data.append(-10);\n    data.append(20);\n    data.append(0);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-5);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(13);\n    data.append(-10);\n    data.append(18);\n    data.append(20);\n    data.append(-7);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(2);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-8);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(17);\n    data.append(-10);\n    data.append(-10);\n    data.append(-1);\n    data.append(-10);\n    data.append(16);\n    data.append(-3);\n    data.append(20);\n    data.append(8);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(15);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-2);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(15);\n    data.append(20);\n    data.append(18);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-5);\n    data.append(20);\n    data.append(20);\n    data.append(0);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-5);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-5);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(20);\n    data.append(3);\n    data.append(9);\n    data.append(-10);\n    data.append(6);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(9);\n    data.append(8);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-9);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(5);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(6);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-8);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-8);\n    data.append(20);\n    data.append(20);\n    data.append(12);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(4);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_i8_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(-10_i8), Option::Some(20_i8));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-29);\n    data.append(82);\n    data.append(121);\n    data.append(-89);\n    data.append(-87);\n    data.append(69);\n    data.append(71);\n    data.append(-25);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_i8_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(-10_i8), Option::Some(20_i8));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(50);\n    data.append(83);\n    data.append(22);\n    data.append(-104);\n    data.append(-81);\n    data.append(20);\n    data.append(-84);\n    data.append(-73);\n    data.append(84);\n    data.append(36);\n    data.append(-57);\n    data.append(-35);\n    data.append(71);\n    data.append(84);\n    data.append(30);\n    data.append(54);\n    data.append(6);\n    data.append(102);\n    data.append(55);\n    data.append(-61);\n    data.append(51);\n    data.append(105);\n    data.append(68);\n    data.append(-56);\n    data.append(41);\n    data.append(-37);\n    data.append(49);\n    data.append(-63);\n    data.append(-115);\n    data.append(119);\n    data.append(124);\n    data.append(-84);\n    data.append(-52);\n    data.append(68);\n    data.append(-21);\n    data.append(-20);\n    data.append(-122);\n    data.append(-125);\n    data.append(-83);\n    data.append(-31);\n    data.append(-10);\n    data.append(85);\n    data.append(-8);\n    data.append(104);\n    data.append(-12);\n    data.append(-55);\n    data.append(-101);\n    data.append(-116);\n    data.append(-76);\n    data.append(-28);\n    data.append(-25);\n    data.append(96);\n    data.append(-59);\n    data.append(-54);\n    data.append(2);\n    data.append(-78);\n    data.append(-43);\n    data.append(74);\n    data.append(57);\n    data.append(-94);\n    data.append(-45);\n    data.append(59);\n    data.append(46);\n    data.append(-25);\n    data.append(-72);\n    data.append(81);\n    data.append(32);\n    data.append(-94);\n    data.append(-76);\n    data.append(-112);\n    data.append(-39);\n    data.append(78);\n    data.append(18);\n    data.append(7);\n    data.append(86);\n    data.append(-23);\n    data.append(121);\n    data.append(-66);\n    data.append(-124);\n    data.append(-79);\n    data.append(-22);\n    data.append(-95);\n    data.append(61);\n    data.append(-10);\n    data.append(-96);\n    data.append(21);\n    data.append(-4);\n    data.append(40);\n    data.append(54);\n    data.append(-54);\n    data.append(-63);\n    data.append(109);\n    data.append(-97);\n    data.append(-61);\n    data.append(-53);\n    data.append(-104);\n    data.append(-38);\n    data.append(-86);\n    data.append(-82);\n    data.append(-8);\n    data.append(-20);\n    data.append(38);\n    data.append(114);\n    data.append(100);\n    data.append(76);\n    data.append(15);\n    data.append(17);\n    data.append(-93);\n    data.append(-107);\n    data.append(22);\n    data.append(-122);\n    data.append(79);\n    data.append(6);\n    data.append(-85);\n    data.append(28);\n    data.append(103);\n    data.append(42);\n    data.append(-88);\n    data.append(46);\n    data.append(24);\n    data.append(8);\n    data.append(-71);\n    data.append(72);\n    data.append(46);\n    data.append(-30);\n    data.append(-89);\n    data.append(-20);\n    data.append(-100);\n    data.append(20);\n    data.append(126);\n    data.append(-71);\n    data.append(-118);\n    data.append(7);\n    data.append(78);\n    data.append(89);\n    data.append(-105);\n    data.append(-98);\n    data.append(-67);\n    data.append(-125);\n    data.append(-71);\n    data.append(14);\n    data.append(49);\n    data.append(54);\n    data.append(77);\n    data.append(85);\n    data.append(26);\n    data.append(59);\n    data.append(-126);\n    data.append(-120);\n    data.append(9);\n    data.append(111);\n    data.append(-49);\n    data.append(100);\n    data.append(-18);\n    data.append(93);\n    data.append(91);\n    data.append(-126);\n    data.append(26);\n    data.append(92);\n    data.append(-52);\n    data.append(-100);\n    data.append(88);\n    data.append(-111);\n    data.append(94);\n    data.append(-24);\n    data.append(10);\n    data.append(-36);\n    data.append(70);\n    data.append(121);\n    data.append(78);\n    data.append(-5);\n    data.append(-22);\n    data.append(-46);\n    data.append(45);\n    data.append(10);\n    data.append(-86);\n    data.append(-114);\n    data.append(38);\n    data.append(12);\n    data.append(109);\n    data.append(76);\n    data.append(57);\n    data.append(-91);\n    data.append(-118);\n    data.append(115);\n    data.append(-80);\n    data.append(86);\n    data.append(11);\n    data.append(-99);\n    data.append(71);\n    data.append(86);\n    data.append(-98);\n    data.append(64);\n    data.append(-39);\n    data.append(71);\n    data.append(101);\n    data.append(-29);\n    data.append(-12);\n    data.append(-119);\n    data.append(-16);\n    data.append(67);\n    data.append(38);\n    data.append(93);\n    data.append(-105);\n    data.append(-72);\n    data.append(14);\n    data.append(95);\n    data.append(57);\n    data.append(30);\n    data.append(-117);\n    data.append(2);\n    data.append(-120);\n    data.append(-14);\n    data.append(-70);\n    data.append(41);\n    data.append(-56);\n    data.append(-102);\n    data.append(117);\n    data.append(72);\n    data.append(-59);\n    data.append(55);\n    data.append(61);\n    data.append(-86);\n    data.append(-26);\n    data.append(-16);\n    data.append(122);\n    data.append(-9);\n    data.append(-68);\n    data.append(102);\n    data.append(-87);\n    data.append(13);\n    data.append(-84);\n    data.append(-51);\n    data.append(12);\n    data.append(110);\n    data.append(-35);\n    data.append(-70);\n    data.append(6);\n    data.append(124);\n    data.append(-83);\n    data.append(-123);\n    data.append(86);\n    data.append(-16);\n    data.append(-14);\n    data.append(90);\n    data.append(-79);\n    data.append(62);\n    data.append(89);\n    data.append(0);\n    data.append(90);\n    data.append(4);\n    data.append(124);\n    data.append(124);\n    data.append(63);\n    data.append(-83);\n    data.append(-50);\n    data.append(-27);\n    data.append(-31);\n    data.append(105);\n    data.append(77);\n    data.append(55);\n    data.append(56);\n    data.append(-56);\n    data.append(-110);\n    data.append(24);\n    data.append(96);\n    data.append(-89);\n    data.append(-96);\n    data.append(120);\n    data.append(7);\n    data.append(1);\n    data.append(11);\n    data.append(-9);\n    data.append(51);\n    data.append(-12);\n    data.append(3);\n    data.append(8);\n    data.append(78);\n    data.append(-89);\n    data.append(82);\n    data.append(-42);\n    data.append(20);\n    data.append(-77);\n    data.append(96);\n    data.append(117);\n    data.append(-53);\n    data.append(-10);\n    data.append(-118);\n    data.append(-40);\n    data.append(111);\n    data.append(58);\n    data.append(65);\n    data.append(109);\n    data.append(-30);\n    data.append(12);\n    data.append(-83);\n    data.append(-11);\n    data.append(-7);\n    data.append(-89);\n    data.append(-59);\n    data.append(54);\n    data.append(-32);\n    data.append(81);\n    data.append(-24);\n    data.append(-85);\n    data.append(40);\n    data.append(-8);\n    data.append(-80);\n    data.append(-37);\n    data.append(120);\n    data.append(92);\n    data.append(43);\n    data.append(-32);\n    data.append(45);\n    data.append(-105);\n    data.append(-2);\n    data.append(38);\n    data.append(14);\n    data.append(-41);\n    data.append(-75);\n    data.append(-37);\n    data.append(110);\n    data.append(-55);\n    data.append(61);\n    data.append(49);\n    data.append(-3);\n    data.append(16);\n    data.append(47);\n    data.append(-47);\n    data.append(62);\n    data.append(-114);\n    data.append(-99);\n    data.append(113);\n    data.append(-115);\n    data.append(46);\n    data.append(-20);\n    data.append(13);\n    data.append(11);\n    data.append(-53);\n    data.append(-42);\n    data.append(-102);\n    data.append(92);\n    data.append(37);\n    data.append(18);\n    data.append(-35);\n    data.append(-97);\n    data.append(26);\n    data.append(-126);\n    data.append(19);\n    data.append(59);\n    data.append(-46);\n    data.append(101);\n    data.append(101);\n    data.append(11);\n    data.append(92);\n    data.append(-43);\n    data.append(-97);\n    data.append(-97);\n    data.append(46);\n    data.append(32);\n    data.append(-108);\n    data.append(126);\n    data.append(7);\n    data.append(63);\n    data.append(80);\n    data.append(63);\n    data.append(-48);\n    data.append(-27);\n    data.append(-127);\n    data.append(-44);\n    data.append(82);\n    data.append(114);\n    data.append(-93);\n    data.append(-125);\n    data.append(13);\n    data.append(-105);\n    data.append(97);\n    data.append(-41);\n    data.append(24);\n    data.append(54);\n    data.append(-56);\n    data.append(-70);\n    data.append(22);\n    data.append(38);\n    data.append(104);\n    data.append(-121);\n    data.append(-116);\n    data.append(63);\n    data.append(93);\n    data.append(53);\n    data.append(-6);\n    data.append(-46);\n    data.append(-17);\n    data.append(-37);\n    data.append(16);\n    data.append(113);\n    data.append(-117);\n    data.append(40);\n    data.append(125);\n    data.append(-89);\n    data.append(1);\n    data.append(-64);\n    data.append(67);\n    data.append(97);\n    data.append(-79);\n    data.append(-54);\n    data.append(-14);\n    data.append(58);\n    data.append(-102);\n    data.append(-25);\n    data.append(73);\n    data.append(117);\n    data.append(-68);\n    data.append(-81);\n    data.append(55);\n    data.append(90);\n    data.append(-11);\n    data.append(30);\n    data.append(107);\n    data.append(-33);\n    data.append(-85);\n    data.append(61);\n    data.append(113);\n    data.append(48);\n    data.append(-69);\n    data.append(-29);\n    data.append(26);\n    data.append(-63);\n    data.append(-72);\n    data.append(-106);\n    data.append(-100);\n    data.append(36);\n    data.append(-35);\n    data.append(61);\n    data.append(108);\n    data.append(-67);\n    data.append(96);\n    data.append(122);\n    data.append(58);\n    data.append(26);\n    data.append(111);\n    data.append(47);\n    data.append(-98);\n    data.append(-63);\n    data.append(0);\n    data.append(-28);\n    data.append(-121);\n    data.append(6);\n    data.append(64);\n    data.append(61);\n    data.append(-17);\n    data.append(85);\n    data.append(-58);\n    data.append(29);\n    data.append(-111);\n    data.append(24);\n    data.append(7);\n    data.append(-76);\n    data.append(8);\n    data.append(62);\n    data.append(79);\n    data.append(124);\n    data.append(6);\n    data.append(-126);\n    data.append(74);\n    data.append(6);\n    data.append(-81);\n    data.append(11);\n    data.append(-7);\n    data.append(86);\n    data.append(1);\n    data.append(-32);\n    data.append(105);\n    data.append(114);\n    data.append(8);\n    data.append(-29);\n    data.append(83);\n    data.append(-94);\n    data.append(44);\n    data.append(-30);\n    data.append(-63);\n    data.append(45);\n    data.append(-104);\n    data.append(-83);\n    data.append(56);\n    data.append(-24);\n    data.append(68);\n    data.append(-17);\n    data.append(24);\n    data.append(-32);\n    data.append(-118);\n    data.append(3);\n    data.append(-56);\n    data.append(4);\n    data.append(65);\n    data.append(120);\n    data.append(65);\n    data.append(-109);\n    data.append(-117);\n    data.append(-10);\n    data.append(99);\n    data.append(103);\n    data.append(91);\n    data.append(-19);\n    data.append(43);\n    data.append(53);\n    data.append(40);\n    data.append(35);\n    data.append(-70);\n    data.append(-21);\n    data.append(-97);\n    data.append(-93);\n    data.append(89);\n    data.append(-117);\n    data.append(-110);\n    data.append(58);\n    data.append(-67);\n    data.append(-12);\n    data.append(18);\n    data.append(12);\n    data.append(-12);\n    data.append(12);\n    data.append(-46);\n    data.append(92);\n    data.append(-97);\n    data.append(-83);\n    data.append(34);\n    data.append(-57);\n    data.append(31);\n    data.append(-45);\n    data.append(60);\n    data.append(123);\n    data.append(81);\n    data.append(83);\n    data.append(-37);\n    data.append(-82);\n    data.append(61);\n    data.append(-2);\n    data.append(6);\n    data.append(-98);\n    data.append(83);\n    data.append(-60);\n    data.append(38);\n    data.append(52);\n    data.append(46);\n    data.append(-7);\n    data.append(10);\n    data.append(-77);\n    data.append(30);\n    data.append(41);\n    data.append(123);\n    data.append(-82);\n    data.append(43);\n    data.append(-60);\n    data.append(-78);\n    data.append(-107);\n    data.append(31);\n    data.append(-77);\n    data.append(-127);\n    data.append(-107);\n    data.append(2);\n    data.append(93);\n    data.append(117);\n    data.append(18);\n    data.append(-87);\n    data.append(-59);\n    data.append(-85);\n    data.append(-87);\n    data.append(-59);\n    data.append(87);\n    data.append(49);\n    data.append(60);\n    data.append(114);\n    data.append(84);\n    data.append(84);\n    data.append(18);\n    data.append(122);\n    data.append(29);\n    data.append(59);\n    data.append(97);\n    data.append(-49);\n    data.append(62);\n    data.append(109);\n    data.append(46);\n    data.append(30);\n    data.append(123);\n    data.append(-7);\n    data.append(-8);\n    data.append(123);\n    data.append(7);\n    data.append(111);\n    data.append(35);\n    data.append(72);\n    data.append(47);\n    data.append(73);\n    data.append(-21);\n    data.append(-123);\n    data.append(62);\n    data.append(-113);\n    data.append(74);\n    data.append(-67);\n    data.append(-58);\n    data.append(-82);\n    data.append(-85);\n    data.append(14);\n    data.append(66);\n    data.append(85);\n    data.append(55);\n    data.append(95);\n    data.append(-93);\n    data.append(91);\n    data.append(-29);\n    data.append(-88);\n    data.append(-117);\n    data.append(-41);\n    data.append(13);\n    data.append(124);\n    data.append(-17);\n    data.append(-59);\n    data.append(-24);\n    data.append(26);\n    data.append(-24);\n    data.append(-30);\n    data.append(1);\n    data.append(-60);\n    data.append(116);\n    data.append(123);\n    data.append(-12);\n    data.append(117);\n    data.append(85);\n    data.append(38);\n    data.append(99);\n    data.append(74);\n    data.append(15);\n    data.append(-22);\n    data.append(102);\n    data.append(9);\n    data.append(62);\n    data.append(-10);\n    data.append(86);\n    data.append(-76);\n    data.append(-94);\n    data.append(-4);\n    data.append(27);\n    data.append(35);\n    data.append(5);\n    data.append(39);\n    data.append(-15);\n    data.append(-12);\n    data.append(52);\n    data.append(-9);\n    data.append(35);\n    data.append(77);\n    data.append(61);\n    data.append(101);\n    data.append(53);\n    data.append(124);\n    data.append(111);\n    data.append(63);\n    data.append(112);\n    data.append(-118);\n    data.append(-25);\n    data.append(85);\n    data.append(-22);\n    data.append(102);\n    data.append(5);\n    data.append(45);\n    data.append(-25);\n    data.append(56);\n    data.append(-84);\n    data.append(24);\n    data.append(114);\n    data.append(17);\n    data.append(32);\n    data.append(72);\n    data.append(-97);\n    data.append(-38);\n    data.append(69);\n    data.append(-107);\n    data.append(-3);\n    data.append(89);\n    data.append(-36);\n    data.append(6);\n    data.append(-67);\n    data.append(-120);\n    data.append(-6);\n    data.append(-46);\n    data.append(-28);\n    data.append(-80);\n    data.append(-34);\n    data.append(116);\n    data.append(-55);\n    data.append(106);\n    data.append(74);\n    data.append(50);\n    data.append(-87);\n    data.append(-97);\n    data.append(-16);\n    data.append(89);\n    data.append(81);\n    data.append(-84);\n    data.append(-111);\n    data.append(-17);\n    data.append(50);\n    data.append(64);\n    data.append(-68);\n    data.append(23);\n    data.append(-8);\n    data.append(79);\n    data.append(86);\n    data.append(-58);\n    data.append(-77);\n    data.append(-57);\n    data.append(125);\n    data.append(71);\n    data.append(-73);\n    data.append(-7);\n    data.append(-65);\n    data.append(126);\n    data.append(-38);\n    data.append(-46);\n    data.append(95);\n    data.append(54);\n    data.append(15);\n    data.append(-18);\n    data.append(22);\n    data.append(2);\n    data.append(-86);\n    data.append(1);\n    data.append(67);\n    data.append(49);\n    data.append(-35);\n    data.append(34);\n    data.append(-40);\n    data.append(49);\n    data.append(17);\n    data.append(-118);\n    data.append(-69);\n    data.append(47);\n    data.append(84);\n    data.append(123);\n    data.append(50);\n    data.append(2);\n    data.append(71);\n    data.append(-61);\n    data.append(32);\n    data.append(-45);\n    data.append(59);\n    data.append(73);\n    data.append(-12);\n    data.append(-98);\n    data.append(124);\n    data.append(104);\n    data.append(21);\n    data.append(-37);\n    data.append(46);\n    data.append(-91);\n    data.append(18);\n    data.append(20);\n    data.append(-66);\n    data.append(-67);\n    data.append(-15);\n    data.append(9);\n    data.append(-60);\n    data.append(-12);\n    data.append(10);\n    data.append(45);\n    data.append(77);\n    data.append(27);\n    data.append(92);\n    data.append(-125);\n    data.append(-4);\n    data.append(46);\n    data.append(10);\n    data.append(-85);\n    data.append(51);\n    data.append(-40);\n    data.append(-42);\n    data.append(112);\n    data.append(98);\n    data.append(98);\n    data.append(-107);\n    data.append(-34);\n    data.append(101);\n    data.append(39);\n    data.append(-101);\n    data.append(-36);\n    data.append(-12);\n    data.append(16);\n    data.append(24);\n    data.append(-32);\n    data.append(-35);\n    data.append(53);\n    data.append(50);\n    data.append(66);\n    data.append(-16);\n    data.append(64);\n    data.append(-36);\n    data.append(7);\n    data.append(-37);\n    data.append(-117);\n    data.append(109);\n    data.append(61);\n    data.append(-58);\n    data.append(-63);\n    data.append(37);\n    data.append(37);\n    data.append(-72);\n    data.append(20);\n    data.append(31);\n    data.append(74);\n    data.append(94);\n    data.append(-73);\n    data.append(-68);\n    data.append(57);\n    data.append(112);\n    data.append(100);\n    data.append(66);\n    data.append(110);\n    data.append(-122);\n    data.append(-64);\n    data.append(-26);\n    data.append(-43);\n    data.append(43);\n    data.append(-108);\n    data.append(-90);\n    data.append(20);\n    data.append(44);\n    data.append(-45);\n    data.append(-18);\n    data.append(10);\n    data.append(-86);\n    data.append(-51);\n    data.append(96);\n    data.append(-77);\n    data.append(-116);\n    data.append(-29);\n    data.append(4);\n    data.append(93);\n    data.append(82);\n    data.append(-50);\n    data.append(36);\n    data.append(-45);\n    data.append(-12);\n    data.append(77);\n    data.append(89);\n    data.append(-125);\n    data.append(12);\n    data.append(96);\n    data.append(-64);\n    data.append(23);\n    data.append(117);\n    data.append(119);\n    data.append(80);\n    data.append(124);\n    data.append(53);\n    data.append(-84);\n    data.append(-13);\n    data.append(126);\n    data.append(-37);\n    data.append(-10);\n    data.append(126);\n    data.append(45);\n    data.append(98);\n    data.append(120);\n    data.append(-86);\n    data.append(66);\n    data.append(-101);\n    data.append(-88);\n    data.append(-68);\n    data.append(86);\n    data.append(64);\n    data.append(-43);\n    data.append(-27);\n    data.append(-20);\n    data.append(32);\n    data.append(-35);\n    data.append(69);\n    data.append(76);\n    data.append(-70);\n    data.append(78);\n    data.append(-50);\n    data.append(-54);\n    data.append(25);\n    data.append(10);\n    data.append(47);\n    data.append(-68);\n    data.append(-120);\n    data.append(76);\n    data.append(31);\n    data.append(-91);\n    data.append(55);\n    data.append(63);\n    data.append(107);\n    data.append(-115);\n    data.append(53);\n    data.append(-3);\n    data.append(8);\n    data.append(62);\n    data.append(-122);\n    data.append(-59);\n    data.append(11);\n    data.append(-62);\n    data.append(36);\n    data.append(-70);\n    data.append(-27);\n    data.append(-81);\n    data.append(-86);\n    data.append(-96);\n    data.append(-60);\n    data.append(-108);\n    data.append(-40);\n    data.append(49);\n    data.append(0);\n    data.append(38);\n    data.append(-116);\n    data.append(46);\n    data.append(96);\n    data.append(-88);\n    data.append(67);\n    data.append(-24);\n    data.append(-4);\n    data.append(-126);\n    data.append(-114);\n    data.append(-96);\n    data.append(5);\n    data.append(-87);\n    data.append(-5);\n    data.append(3);\n    data.append(-13);\n    data.append(-71);\n    data.append(119);\n    data.append(29);\n    data.append(-29);\n    data.append(32);\n    data.append(62);\n    data.append(47);\n    data.append(7);\n    data.append(-123);\n    data.append(86);\n    data.append(-121);\n    data.append(-96);\n    data.append(-38);\n    data.append(-42);\n    data.append(-57);\n    data.append(34);\n    data.append(-11);\n    data.append(86);\n    data.append(119);\n    data.append(-27);\n    data.append(-92);\n    data.append(62);\n    data.append(120);\n    data.append(2);\n    data.append(34);\n    data.append(-31);\n    data.append(-59);\n    data.append(45);\n    data.append(-14);\n    data.append(-92);\n    data.append(-54);\n    data.append(121);\n    data.append(38);\n    data.append(-99);\n    data.append(-73);\n    data.append(-89);\n    data.append(111);\n    data.append(-103);\n    data.append(-37);\n    data.append(22);\n    data.append(113);\n    data.append(-9);\n    data.append(-70);\n    data.append(-102);\n    data.append(85);\n    data.append(-78);\n    data.append(-19);\n    data.append(126);\n    data.append(16);\n    data.append(-15);\n    data.append(-4);\n    data.append(112);\n    data.append(-115);\n    data.append(57);\n    data.append(54);\n    data.append(81);\n    data.append(38);\n    data.append(7);\n    data.append(-102);\n    data.append(111);\n    data.append(-40);\n    data.append(-101);\n    data.append(42);\n    data.append(88);\n    data.append(120);\n    data.append(44);\n    data.append(64);\n    data.append(99);\n    data.append(-24);\n    data.append(-6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_i8_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(6);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-8);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(2);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(18);\n    data.append(7);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-4);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-8);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(17);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(6);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(8);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(7);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(14);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(9);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-5);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(11);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(14);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(2);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-9);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(13);\n    data.append(-10);\n    data.append(-10);\n    data.append(12);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(6);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(0);\n    data.append(20);\n    data.append(4);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(7);\n    data.append(1);\n    data.append(11);\n    data.append(-9);\n    data.append(20);\n    data.append(-10);\n    data.append(3);\n    data.append(8);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(12);\n    data.append(-10);\n    data.append(-10);\n    data.append(-7);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-8);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-2);\n    data.append(20);\n    data.append(14);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-3);\n    data.append(16);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(13);\n    data.append(11);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(19);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(11);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(7);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(13);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-6);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(16);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(1);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(0);\n    data.append(-10);\n    data.append(-10);\n    data.append(6);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(7);\n    data.append(-10);\n    data.append(8);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(6);\n    data.append(-10);\n    data.append(20);\n    data.append(6);\n    data.append(-10);\n    data.append(11);\n    data.append(-7);\n    data.append(20);\n    data.append(1);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(8);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(3);\n    data.append(-10);\n    data.append(4);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(18);\n    data.append(12);\n    data.append(-10);\n    data.append(12);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-2);\n    data.append(6);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-7);\n    data.append(10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(2);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-7);\n    data.append(-8);\n    data.append(20);\n    data.append(7);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(14);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(13);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(1);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(-10);\n    data.append(20);\n    data.append(9);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-4);\n    data.append(20);\n    data.append(20);\n    data.append(5);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-9);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(5);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(17);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-3);\n    data.append(20);\n    data.append(-10);\n    data.append(6);\n    data.append(-10);\n    data.append(-10);\n    data.append(-6);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-8);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-7);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(-10);\n    data.append(20);\n    data.append(2);\n    data.append(-10);\n    data.append(1);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(17);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(2);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(18);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(9);\n    data.append(-10);\n    data.append(-10);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-4);\n    data.append(20);\n    data.append(10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(16);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(7);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(4);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(12);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-3);\n    data.append(8);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(11);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(0);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-4);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(5);\n    data.append(-10);\n    data.append(-5);\n    data.append(3);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(7);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(2);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(-9);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(16);\n    data.append(-10);\n    data.append(-4);\n    data.append(20);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(7);\n    data.append(-10);\n    data.append(20);\n    data.append(-10);\n    data.append(-10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(-10);\n    data.append(-6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_u32_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(10_u32), Option::Some(20_u32));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(102);\n    data.append(105);\n    data.append(111);\n    data.append(39);\n    data.append(165);\n    data.append(3);\n    data.append(165);\n    data.append(196);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_clip_u32_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.clip(Option::Some(10_u32), Option::Some(20_u32));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(135);\n    data.append(235);\n    data.append(21);\n    data.append(46);\n    data.append(138);\n    data.append(25);\n    data.append(138);\n    data.append(155);\n    data.append(127);\n    data.append(193);\n    data.append(119);\n    data.append(237);\n    data.append(226);\n    data.append(82);\n    data.append(74);\n    data.append(93);\n    data.append(65);\n    data.append(23);\n    data.append(121);\n    data.append(147);\n    data.append(31);\n    data.append(204);\n    data.append(127);\n    data.append(170);\n    data.append(32);\n    data.append(133);\n    data.append(254);\n    data.append(98);\n    data.append(162);\n    data.append(3);\n    data.append(239);\n    data.append(104);\n    data.append(44);\n    data.append(254);\n    data.append(60);\n    data.append(163);\n    data.append(50);\n    data.append(213);\n    data.append(208);\n    data.append(181);\n    data.append(62);\n    data.append(236);\n    data.append(154);\n    data.append(99);\n    data.append(61);\n    data.append(204);\n    data.append(36);\n    data.append(49);\n    data.append(160);\n    data.append(136);\n    data.append(67);\n    data.append(149);\n    data.append(56);\n    data.append(13);\n    data.append(141);\n    data.append(133);\n    data.append(77);\n    data.append(97);\n    data.append(204);\n    data.append(254);\n    data.append(119);\n    data.append(216);\n    data.append(221);\n    data.append(80);\n    data.append(80);\n    data.append(52);\n    data.append(172);\n    data.append(135);\n    data.append(206);\n    data.append(1);\n    data.append(213);\n    data.append(156);\n    data.append(151);\n    data.append(153);\n    data.append(9);\n    data.append(114);\n    data.append(12);\n    data.append(41);\n    data.append(60);\n    data.append(157);\n    data.append(2);\n    data.append(80);\n    data.append(60);\n    data.append(45);\n    data.append(41);\n    data.append(15);\n    data.append(24);\n    data.append(53);\n    data.append(182);\n    data.append(67);\n    data.append(7);\n    data.append(55);\n    data.append(15);\n    data.append(237);\n    data.append(1);\n    data.append(23);\n    data.append(174);\n    data.append(55);\n    data.append(172);\n    data.append(8);\n    data.append(50);\n    data.append(209);\n    data.append(130);\n    data.append(185);\n    data.append(123);\n    data.append(173);\n    data.append(65);\n    data.append(148);\n    data.append(85);\n    data.append(111);\n    data.append(122);\n    data.append(28);\n    data.append(40);\n    data.append(115);\n    data.append(180);\n    data.append(43);\n    data.append(189);\n    data.append(62);\n    data.append(192);\n    data.append(48);\n    data.append(150);\n    data.append(74);\n    data.append(178);\n    data.append(88);\n    data.append(92);\n    data.append(97);\n    data.append(157);\n    data.append(91);\n    data.append(90);\n    data.append(102);\n    data.append(143);\n    data.append(32);\n    data.append(130);\n    data.append(155);\n    data.append(198);\n    data.append(215);\n    data.append(74);\n    data.append(86);\n    data.append(136);\n    data.append(96);\n    data.append(23);\n    data.append(234);\n    data.append(215);\n    data.append(42);\n    data.append(88);\n    data.append(104);\n    data.append(66);\n    data.append(45);\n    data.append(117);\n    data.append(201);\n    data.append(61);\n    data.append(73);\n    data.append(28);\n    data.append(79);\n    data.append(196);\n    data.append(171);\n    data.append(44);\n    data.append(50);\n    data.append(191);\n    data.append(229);\n    data.append(108);\n    data.append(173);\n    data.append(162);\n    data.append(106);\n    data.append(193);\n    data.append(4);\n    data.append(41);\n    data.append(200);\n    data.append(57);\n    data.append(33);\n    data.append(42);\n    data.append(68);\n    data.append(152);\n    data.append(147);\n    data.append(140);\n    data.append(108);\n    data.append(20);\n    data.append(52);\n    data.append(175);\n    data.append(99);\n    data.append(204);\n    data.append(81);\n    data.append(3);\n    data.append(15);\n    data.append(159);\n    data.append(81);\n    data.append(61);\n    data.append(31);\n    data.append(105);\n    data.append(111);\n    data.append(87);\n    data.append(6);\n    data.append(138);\n    data.append(28);\n    data.append(107);\n    data.append(204);\n    data.append(147);\n    data.append(136);\n    data.append(207);\n    data.append(162);\n    data.append(169);\n    data.append(233);\n    data.append(213);\n    data.append(90);\n    data.append(162);\n    data.append(3);\n    data.append(112);\n    data.append(97);\n    data.append(139);\n    data.append(28);\n    data.append(212);\n    data.append(32);\n    data.append(18);\n    data.append(217);\n    data.append(221);\n    data.append(207);\n    data.append(24);\n    data.append(187);\n    data.append(243);\n    data.append(229);\n    data.append(55);\n    data.append(97);\n    data.append(158);\n    data.append(241);\n    data.append(78);\n    data.append(151);\n    data.append(186);\n    data.append(211);\n    data.append(133);\n    data.append(30);\n    data.append(67);\n    data.append(73);\n    data.append(74);\n    data.append(7);\n    data.append(164);\n    data.append(73);\n    data.append(65);\n    data.append(41);\n    data.append(74);\n    data.append(6);\n    data.append(39);\n    data.append(203);\n    data.append(250);\n    data.append(224);\n    data.append(66);\n    data.append(58);\n    data.append(151);\n    data.append(162);\n    data.append(154);\n    data.append(214);\n    data.append(247);\n    data.append(57);\n    data.append(60);\n    data.append(72);\n    data.append(152);\n    data.append(37);\n    data.append(110);\n    data.append(196);\n    data.append(128);\n    data.append(7);\n    data.append(46);\n    data.append(177);\n    data.append(212);\n    data.append(61);\n    data.append(120);\n    data.append(141);\n    data.append(201);\n    data.append(74);\n    data.append(29);\n    data.append(113);\n    data.append(139);\n    data.append(20);\n    data.append(201);\n    data.append(240);\n    data.append(194);\n    data.append(36);\n    data.append(241);\n    data.append(170);\n    data.append(152);\n    data.append(237);\n    data.append(2);\n    data.append(66);\n    data.append(33);\n    data.append(26);\n    data.append(10);\n    data.append(237);\n    data.append(85);\n    data.append(68);\n    data.append(63);\n    data.append(167);\n    data.append(194);\n    data.append(213);\n    data.append(162);\n    data.append(102);\n    data.append(158);\n    data.append(37);\n    data.append(115);\n    data.append(212);\n    data.append(83);\n    data.append(82);\n    data.append(51);\n    data.append(65);\n    data.append(140);\n    data.append(5);\n    data.append(225);\n    data.append(70);\n    data.append(66);\n    data.append(62);\n    data.append(47);\n    data.append(210);\n    data.append(61);\n    data.append(145);\n    data.append(22);\n    data.append(124);\n    data.append(154);\n    data.append(138);\n    data.append(173);\n    data.append(29);\n    data.append(41);\n    data.append(208);\n    data.append(191);\n    data.append(133);\n    data.append(68);\n    data.append(13);\n    data.append(144);\n    data.append(139);\n    data.append(69);\n    data.append(214);\n    data.append(157);\n    data.append(139);\n    data.append(123);\n    data.append(86);\n    data.append(199);\n    data.append(45);\n    data.append(7);\n    data.append(138);\n    data.append(184);\n    data.append(89);\n    data.append(73);\n    data.append(107);\n    data.append(109);\n    data.append(187);\n    data.append(79);\n    data.append(41);\n    data.append(247);\n    data.append(106);\n    data.append(181);\n    data.append(59);\n    data.append(63);\n    data.append(35);\n    data.append(185);\n    data.append(127);\n    data.append(221);\n    data.append(62);\n    data.append(191);\n    data.append(4);\n    data.append(103);\n    data.append(219);\n    data.append(217);\n    data.append(12);\n    data.append(4);\n    data.append(227);\n    data.append(201);\n    data.append(219);\n    data.append(60);\n    data.append(210);\n    data.append(190);\n    data.append(193);\n    data.append(23);\n    data.append(85);\n    data.append(223);\n    data.append(254);\n    data.append(224);\n    data.append(40);\n    data.append(2);\n    data.append(173);\n    data.append(85);\n    data.append(39);\n    data.append(13);\n    data.append(172);\n    data.append(224);\n    data.append(66);\n    data.append(253);\n    data.append(198);\n    data.append(51);\n    data.append(153);\n    data.append(57);\n    data.append(138);\n    data.append(217);\n    data.append(126);\n    data.append(149);\n    data.append(47);\n    data.append(142);\n    data.append(230);\n    data.append(6);\n    data.append(102);\n    data.append(68);\n    data.append(180);\n    data.append(123);\n    data.append(241);\n    data.append(176);\n    data.append(110);\n    data.append(8);\n    data.append(248);\n    data.append(155);\n    data.append(136);\n    data.append(47);\n    data.append(217);\n    data.append(25);\n    data.append(134);\n    data.append(2);\n    data.append(254);\n    data.append(162);\n    data.append(234);\n    data.append(111);\n    data.append(164);\n    data.append(248);\n    data.append(106);\n    data.append(227);\n    data.append(207);\n    data.append(242);\n    data.append(39);\n    data.append(47);\n    data.append(130);\n    data.append(117);\n    data.append(61);\n    data.append(24);\n    data.append(233);\n    data.append(207);\n    data.append(12);\n    data.append(73);\n    data.append(98);\n    data.append(184);\n    data.append(253);\n    data.append(79);\n    data.append(243);\n    data.append(23);\n    data.append(62);\n    data.append(92);\n    data.append(213);\n    data.append(161);\n    data.append(89);\n    data.append(124);\n    data.append(245);\n    data.append(159);\n    data.append(233);\n    data.append(59);\n    data.append(124);\n    data.append(194);\n    data.append(239);\n    data.append(115);\n    data.append(175);\n    data.append(40);\n    data.append(120);\n    data.append(103);\n    data.append(33);\n    data.append(240);\n    data.append(219);\n    data.append(36);\n    data.append(60);\n    data.append(142);\n    data.append(133);\n    data.append(19);\n    data.append(73);\n    data.append(29);\n    data.append(74);\n    data.append(14);\n    data.append(50);\n    data.append(107);\n    data.append(229);\n    data.append(177);\n    data.append(31);\n    data.append(105);\n    data.append(233);\n    data.append(38);\n    data.append(213);\n    data.append(156);\n    data.append(188);\n    data.append(173);\n    data.append(88);\n    data.append(226);\n    data.append(234);\n    data.append(31);\n    data.append(44);\n    data.append(16);\n    data.append(240);\n    data.append(191);\n    data.append(173);\n    data.append(208);\n    data.append(9);\n    data.append(61);\n    data.append(217);\n    data.append(111);\n    data.append(230);\n    data.append(91);\n    data.append(57);\n    data.append(51);\n    data.append(102);\n    data.append(52);\n    data.append(174);\n    data.append(19);\n    data.append(149);\n    data.append(226);\n    data.append(84);\n    data.append(159);\n    data.append(76);\n    data.append(34);\n    data.append(93);\n    data.append(34);\n    data.append(228);\n    data.append(227);\n    data.append(126);\n    data.append(111);\n    data.append(112);\n    data.append(136);\n    data.append(51);\n    data.append(254);\n    data.append(241);\n    data.append(36);\n    data.append(18);\n    data.append(126);\n    data.append(90);\n    data.append(250);\n    data.append(15);\n    data.append(185);\n    data.append(184);\n    data.append(47);\n    data.append(153);\n    data.append(101);\n    data.append(81);\n    data.append(209);\n    data.append(82);\n    data.append(225);\n    data.append(156);\n    data.append(85);\n    data.append(128);\n    data.append(102);\n    data.append(65);\n    data.append(30);\n    data.append(25);\n    data.append(10);\n    data.append(233);\n    data.append(209);\n    data.append(206);\n    data.append(123);\n    data.append(158);\n    data.append(204);\n    data.append(82);\n    data.append(246);\n    data.append(190);\n    data.append(177);\n    data.append(102);\n    data.append(238);\n    data.append(191);\n    data.append(249);\n    data.append(194);\n    data.append(157);\n    data.append(107);\n    data.append(191);\n    data.append(27);\n    data.append(188);\n    data.append(56);\n    data.append(159);\n    data.append(243);\n    data.append(241);\n    data.append(122);\n    data.append(28);\n    data.append(183);\n    data.append(154);\n    data.append(53);\n    data.append(74);\n    data.append(138);\n    data.append(134);\n    data.append(37);\n    data.append(212);\n    data.append(27);\n    data.append(173);\n    data.append(109);\n    data.append(32);\n    data.append(61);\n    data.append(56);\n    data.append(107);\n    data.append(26);\n    data.append(240);\n    data.append(167);\n    data.append(66);\n    data.append(143);\n    data.append(92);\n    data.append(160);\n    data.append(150);\n    data.append(90);\n    data.append(244);\n    data.append(72);\n    data.append(190);\n    data.append(96);\n    data.append(240);\n    data.append(253);\n    data.append(62);\n    data.append(48);\n    data.append(22);\n    data.append(46);\n    data.append(164);\n    data.append(172);\n    data.append(84);\n    data.append(6);\n    data.append(233);\n    data.append(196);\n    data.append(63);\n    data.append(162);\n    data.append(138);\n    data.append(160);\n    data.append(216);\n    data.append(191);\n    data.append(122);\n    data.append(27);\n    data.append(90);\n    data.append(37);\n    data.append(246);\n    data.append(252);\n    data.append(95);\n    data.append(241);\n    data.append(183);\n    data.append(183);\n    data.append(163);\n    data.append(197);\n    data.append(232);\n    data.append(208);\n    data.append(191);\n    data.append(226);\n    data.append(178);\n    data.append(93);\n    data.append(249);\n    data.append(93);\n    data.append(116);\n    data.append(129);\n    data.append(134);\n    data.append(101);\n    data.append(100);\n    data.append(156);\n    data.append(26);\n    data.append(187);\n    data.append(247);\n    data.append(50);\n    data.append(43);\n    data.append(227);\n    data.append(188);\n    data.append(237);\n    data.append(23);\n    data.append(192);\n    data.append(224);\n    data.append(253);\n    data.append(164);\n    data.append(224);\n    data.append(75);\n    data.append(172);\n    data.append(96);\n    data.append(248);\n    data.append(112);\n    data.append(0);\n    data.append(20);\n    data.append(84);\n    data.append(52);\n    data.append(124);\n    data.append(217);\n    data.append(231);\n    data.append(65);\n    data.append(209);\n    data.append(85);\n    data.append(180);\n    data.append(51);\n    data.append(248);\n    data.append(246);\n    data.append(31);\n    data.append(194);\n    data.append(89);\n    data.append(155);\n    data.append(151);\n    data.append(154);\n    data.append(180);\n    data.append(29);\n    data.append(115);\n    data.append(35);\n    data.append(207);\n    data.append(100);\n    data.append(113);\n    data.append(237);\n    data.append(216);\n    data.append(186);\n    data.append(155);\n    data.append(183);\n    data.append(130);\n    data.append(113);\n    data.append(63);\n    data.append(254);\n    data.append(246);\n    data.append(254);\n    data.append(67);\n    data.append(192);\n    data.append(110);\n    data.append(35);\n    data.append(91);\n    data.append(76);\n    data.append(171);\n    data.append(157);\n    data.append(109);\n    data.append(177);\n    data.append(240);\n    data.append(69);\n    data.append(165);\n    data.append(97);\n    data.append(25);\n    data.append(160);\n    data.append(5);\n    data.append(205);\n    data.append(217);\n    data.append(141);\n    data.append(185);\n    data.append(235);\n    data.append(174);\n    data.append(106);\n    data.append(166);\n    data.append(237);\n    data.append(47);\n    data.append(221);\n    data.append(68);\n    data.append(101);\n    data.append(161);\n    data.append(37);\n    data.append(30);\n    data.append(23);\n    data.append(23);\n    data.append(122);\n    data.append(7);\n    data.append(53);\n    data.append(66);\n    data.append(28);\n    data.append(254);\n    data.append(155);\n    data.append(215);\n    data.append(199);\n    data.append(43);\n    data.append(211);\n    data.append(65);\n    data.append(243);\n    data.append(210);\n    data.append(156);\n    data.append(202);\n    data.append(199);\n    data.append(239);\n    data.append(33);\n    data.append(117);\n    data.append(151);\n    data.append(78);\n    data.append(63);\n    data.append(234);\n    data.append(105);\n    data.append(108);\n    data.append(97);\n    data.append(121);\n    data.append(30);\n    data.append(20);\n    data.append(76);\n    data.append(235);\n    data.append(215);\n    data.append(116);\n    data.append(106);\n    data.append(127);\n    data.append(63);\n    data.append(97);\n    data.append(84);\n    data.append(151);\n    data.append(140);\n    data.append(169);\n    data.append(16);\n    data.append(227);\n    data.append(104);\n    data.append(148);\n    data.append(149);\n    data.append(175);\n    data.append(71);\n    data.append(89);\n    data.append(224);\n    data.append(239);\n    data.append(97);\n    data.append(71);\n    data.append(204);\n    data.append(3);\n    data.append(10);\n    data.append(18);\n    data.append(62);\n    data.append(126);\n    data.append(17);\n    data.append(7);\n    data.append(216);\n    data.append(191);\n    data.append(179);\n    data.append(193);\n    data.append(103);\n    data.append(106);\n    data.append(98);\n    data.append(2);\n    data.append(201);\n    data.append(94);\n    data.append(151);\n    data.append(42);\n    data.append(156);\n    data.append(4);\n    data.append(110);\n    data.append(90);\n    data.append(109);\n    data.append(200);\n    data.append(162);\n    data.append(155);\n    data.append(217);\n    data.append(39);\n    data.append(199);\n    data.append(235);\n    data.append(212);\n    data.append(204);\n    data.append(166);\n    data.append(210);\n    data.append(143);\n    data.append(91);\n    data.append(124);\n    data.append(191);\n    data.append(51);\n    data.append(110);\n    data.append(13);\n    data.append(136);\n    data.append(4);\n    data.append(121);\n    data.append(163);\n    data.append(193);\n    data.append(194);\n    data.append(168);\n    data.append(124);\n    data.append(236);\n    data.append(133);\n    data.append(16);\n    data.append(61);\n    data.append(163);\n    data.append(26);\n    data.append(82);\n    data.append(198);\n    data.append(103);\n    data.append(254);\n    data.append(194);\n    data.append(136);\n    data.append(193);\n    data.append(191);\n    data.append(58);\n    data.append(155);\n    data.append(132);\n    data.append(58);\n    data.append(184);\n    data.append(66);\n    data.append(153);\n    data.append(224);\n    data.append(1);\n    data.append(77);\n    data.append(217);\n    data.append(113);\n    data.append(25);\n    data.append(93);\n    data.append(243);\n    data.append(244);\n    data.append(238);\n    data.append(57);\n    data.append(116);\n    data.append(254);\n    data.append(34);\n    data.append(197);\n    data.append(109);\n    data.append(243);\n    data.append(198);\n    data.append(93);\n    data.append(244);\n    data.append(51);\n    data.append(214);\n    data.append(101);\n    data.append(88);\n    data.append(51);\n    data.append(222);\n    data.append(79);\n    data.append(149);\n    data.append(32);\n    data.append(46);\n    data.append(62);\n    data.append(122);\n    data.append(145);\n    data.append(5);\n    data.append(98);\n    data.append(91);\n    data.append(36);\n    data.append(172);\n    data.append(213);\n    data.append(94);\n    data.append(102);\n    data.append(117);\n    data.append(81);\n    data.append(26);\n    data.append(17);\n    data.append(123);\n    data.append(93);\n    data.append(184);\n    data.append(65);\n    data.append(13);\n    data.append(25);\n    data.append(31);\n    data.append(95);\n    data.append(66);\n    data.append(9);\n    data.append(221);\n    data.append(195);\n    data.append(30);\n    data.append(1);\n    data.append(235);\n    data.append(247);\n    data.append(147);\n    data.append(253);\n    data.append(32);\n    data.append(38);\n    data.append(86);\n    data.append(30);\n    data.append(85);\n    data.append(170);\n    data.append(32);\n    data.append(156);\n    data.append(182);\n    data.append(153);\n    data.append(114);\n    data.append(237);\n    data.append(174);\n    data.append(157);\n    data.append(151);\n    data.append(207);\n    data.append(147);\n    data.append(73);\n    data.append(248);\n    data.append(52);\n    data.append(165);\n    data.append(46);\n    data.append(49);\n    data.append(127);\n    data.append(183);\n    data.append(64);\n    data.append(11);\n    data.append(151);\n    data.append(234);\n    data.append(239);\n    data.append(239);\n    data.append(141);\n    data.append(170);\n    data.append(112);\n    data.append(137);\n    data.append(78);\n    data.append(13);\n    data.append(144);\n    data.append(125);\n    data.append(76);\n    data.append(91);\n    data.append(171);\n    data.append(78);\n    data.append(41);\n    data.append(159);\n    data.append(162);\n    data.append(101);\n    data.append(149);\n    data.append(173);\n    data.append(149);\n    data.append(137);\n    data.append(195);\n    data.append(79);\n    data.append(121);\n    data.append(14);\n    data.append(151);\n    data.append(22);\n    data.append(209);\n    data.append(159);\n    data.append(62);\n    data.append(68);\n    data.append(151);\n    data.append(211);\n    data.append(82);\n    data.append(60);\n    data.append(129);\n    data.append(6);\n    data.append(94);\n    data.append(71);\n    data.append(115);\n    data.append(58);\n    data.append(204);\n    data.append(139);\n    data.append(23);\n    data.append(193);\n    data.append(229);\n    data.append(188);\n    data.append(147);\n    data.append(201);\n    data.append(231);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/clip_u32_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(15);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(15);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(12);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(12);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(19);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(14);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(16);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(19);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(18);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(15);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(16);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(10);\n    data.append(18);\n    data.append(20);\n    data.append(20);\n    data.append(17);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(16);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(17);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(11);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(13);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(14);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(10);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    data.append(20);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_col2im() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::col2im(\n        @input_0, array![5, 5].span(), array![1, 5].span(), Option::None, Option::None, Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_5D.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_col2im_5D() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::col2im(\n        @input_0,\n        array![3, 4, 5].span(),\n        array![1, 1, 5].span(),\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_5D/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(10);\n    shape.append(12);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_5D/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_dilations.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_col2im_dilations() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::col2im(\n        @input_0,\n        array![6, 6].span(),\n        array![2, 2].span(),\n        Option::Some(array![1, 5].span()),\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_dilations/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_dilations/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(6);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_pads.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_col2im_pads() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::col2im(\n        @input_0,\n        array![5, 5].span(),\n        array![1, 5].span(),\n        Option::None,\n        Option::Some(array![0, 1, 0, 1].span()),\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_pads/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_pads/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 13172736, sign: false });\n    data.append(FP16x16 { mag: 13369344, sign: false });\n    data.append(FP16x16 { mag: 13565952, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_strides.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_col2im_strides() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::col2im(\n        @input_0,\n        array![5, 5].span(),\n        array![3, 3].span(),\n        Option::None,\n        Option::None,\n        Option::Some(array![2, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_strides/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(9);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/col2im_strides/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp16x16_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 8323072, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 8519680, sign: false });\n    data.append(FP16x16 { mag: 8585216, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 8716288, sign: false });\n    data.append(FP16x16 { mag: 8781824, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 8912896, sign: false });\n    data.append(FP16x16 { mag: 8978432, sign: false });\n    data.append(FP16x16 { mag: 9043968, sign: false });\n    data.append(FP16x16 { mag: 9109504, sign: false });\n    data.append(FP16x16 { mag: 9175040, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 9306112, sign: false });\n    data.append(FP16x16 { mag: 9371648, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 9502720, sign: false });\n    data.append(FP16x16 { mag: 9568256, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 9764864, sign: false });\n    data.append(FP16x16 { mag: 9830400, sign: false });\n    data.append(FP16x16 { mag: 9895936, sign: false });\n    data.append(FP16x16 { mag: 9961472, sign: false });\n    data.append(FP16x16 { mag: 10027008, sign: false });\n    data.append(FP16x16 { mag: 10092544, sign: false });\n    data.append(FP16x16 { mag: 10158080, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 10289152, sign: false });\n    data.append(FP16x16 { mag: 10354688, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 10485760, sign: false });\n    data.append(FP16x16 { mag: 10551296, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 10682368, sign: false });\n    data.append(FP16x16 { mag: 10747904, sign: false });\n    data.append(FP16x16 { mag: 10813440, sign: false });\n    data.append(FP16x16 { mag: 10878976, sign: false });\n    data.append(FP16x16 { mag: 10944512, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 11075584, sign: false });\n    data.append(FP16x16 { mag: 11141120, sign: false });\n    data.append(FP16x16 { mag: 11206656, sign: false });\n    data.append(FP16x16 { mag: 11272192, sign: false });\n    data.append(FP16x16 { mag: 11337728, sign: false });\n    data.append(FP16x16 { mag: 11403264, sign: false });\n    data.append(FP16x16 { mag: 11468800, sign: false });\n    data.append(FP16x16 { mag: 11534336, sign: false });\n    data.append(FP16x16 { mag: 11599872, sign: false });\n    data.append(FP16x16 { mag: 11665408, sign: false });\n    data.append(FP16x16 { mag: 11730944, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 8323072, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 8519680, sign: false });\n    data.append(FP16x16 { mag: 8585216, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 8716288, sign: false });\n    data.append(FP16x16 { mag: 8781824, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 8912896, sign: false });\n    data.append(FP16x16 { mag: 8978432, sign: false });\n    data.append(FP16x16 { mag: 9043968, sign: false });\n    data.append(FP16x16 { mag: 9109504, sign: false });\n    data.append(FP16x16 { mag: 9175040, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 9306112, sign: false });\n    data.append(FP16x16 { mag: 9371648, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 9502720, sign: false });\n    data.append(FP16x16 { mag: 9568256, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 9764864, sign: false });\n    data.append(FP16x16 { mag: 9830400, sign: false });\n    data.append(FP16x16 { mag: 9895936, sign: false });\n    data.append(FP16x16 { mag: 9961472, sign: false });\n    data.append(FP16x16 { mag: 10027008, sign: false });\n    data.append(FP16x16 { mag: 10092544, sign: false });\n    data.append(FP16x16 { mag: 10158080, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 10289152, sign: false });\n    data.append(FP16x16 { mag: 10354688, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 10485760, sign: false });\n    data.append(FP16x16 { mag: 10551296, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 10682368, sign: false });\n    data.append(FP16x16 { mag: 10747904, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp16x16_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis3.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp16x16_3d_axis3() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(3));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_axis3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n    shape.append(4);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp16x16_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_noaxis.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp16x16_3d_noaxis() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_noaxis/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_noaxis/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp16x16_3d_noaxis/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(7);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp8x23_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp8x23_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_fp8x23_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_fp8x23_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i32_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i32_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(7);\n    data.append(8);\n    data.append(10);\n    data.append(11);\n    data.append(13);\n    data.append(14);\n    data.append(16);\n    data.append(17);\n    data.append(19);\n    data.append(20);\n    data.append(22);\n    data.append(23);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i32_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i32_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i8_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i8_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(7);\n    data.append(8);\n    data.append(10);\n    data.append(11);\n    data.append(13);\n    data.append(14);\n    data.append(16);\n    data.append(17);\n    data.append(19);\n    data.append(20);\n    data.append(22);\n    data.append(23);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_i8_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_i8_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_u32_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_u32_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(6);\n    data.append(9);\n    data.append(10);\n    data.append(13);\n    data.append(14);\n    data.append(17);\n    data.append(18);\n    data.append(21);\n    data.append(22);\n    data.append(25);\n    data.append(26);\n    data.append(29);\n    data.append(30);\n    data.append(33);\n    data.append(34);\n    data.append(37);\n    data.append(38);\n    data.append(41);\n    data.append(42);\n    data.append(45);\n    data.append(46);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_u32_3d_axis2_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis2_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(6);\n    data.append(7);\n    data.append(11);\n    data.append(12);\n    data.append(16);\n    data.append(17);\n    data.append(21);\n    data.append(22);\n    data.append(26);\n    data.append(27);\n    data.append(31);\n    data.append(32);\n    data.append(36);\n    data.append(37);\n    data.append(41);\n    data.append(42);\n    data.append(46);\n    data.append(47);\n    data.append(51);\n    data.append(52);\n    data.append(56);\n    data.append(57);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis3.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_u32_3d_axis3() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(3));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(5);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(82);\n    data.append(83);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(88);\n    data.append(89);\n    data.append(90);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(94);\n    data.append(95);\n    data.append(96);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(100);\n    data.append(101);\n    data.append(102);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(106);\n    data.append(107);\n    data.append(108);\n    data.append(109);\n    data.append(110);\n    data.append(111);\n    data.append(112);\n    data.append(113);\n    data.append(114);\n    data.append(115);\n    data.append(116);\n    data.append(117);\n    data.append(118);\n    data.append(119);\n    data.append(120);\n    data.append(121);\n    data.append(122);\n    data.append(123);\n    data.append(124);\n    data.append(125);\n    data.append(126);\n    data.append(127);\n    data.append(128);\n    data.append(129);\n    data.append(130);\n    data.append(131);\n    data.append(132);\n    data.append(133);\n    data.append(134);\n    data.append(135);\n    data.append(136);\n    data.append(137);\n    data.append(138);\n    data.append(139);\n    data.append(140);\n    data.append(141);\n    data.append(142);\n    data.append(143);\n    data.append(144);\n    data.append(145);\n    data.append(146);\n    data.append(147);\n    data.append(148);\n    data.append(149);\n    data.append(150);\n    data.append(151);\n    data.append(152);\n    data.append(153);\n    data.append(154);\n    data.append(155);\n    data.append(156);\n    data.append(157);\n    data.append(158);\n    data.append(159);\n    data.append(160);\n    data.append(161);\n    data.append(162);\n    data.append(163);\n    data.append(164);\n    data.append(165);\n    data.append(166);\n    data.append(167);\n    data.append(168);\n    data.append(169);\n    data.append(170);\n    data.append(171);\n    data.append(172);\n    data.append(173);\n    data.append(174);\n    data.append(175);\n    data.append(176);\n    data.append(177);\n    data.append(178);\n    data.append(179);\n    data.append(180);\n    data.append(181);\n    data.append(182);\n    data.append(183);\n    data.append(184);\n    data.append(185);\n    data.append(186);\n    data.append(187);\n    data.append(188);\n    data.append(189);\n    data.append(190);\n    data.append(191);\n    data.append(192);\n    data.append(193);\n    data.append(194);\n    data.append(195);\n    data.append(196);\n    data.append(197);\n    data.append(198);\n    data.append(199);\n    data.append(200);\n    data.append(201);\n    data.append(202);\n    data.append(203);\n    data.append(204);\n    data.append(205);\n    data.append(206);\n    data.append(207);\n    data.append(208);\n    data.append(209);\n    data.append(210);\n    data.append(211);\n    data.append(212);\n    data.append(213);\n    data.append(214);\n    data.append(215);\n    data.append(216);\n    data.append(217);\n    data.append(218);\n    data.append(219);\n    data.append(220);\n    data.append(221);\n    data.append(222);\n    data.append(223);\n    data.append(224);\n    data.append(225);\n    data.append(226);\n    data.append(227);\n    data.append(228);\n    data.append(229);\n    data.append(230);\n    data.append(231);\n    data.append(232);\n    data.append(233);\n    data.append(234);\n    data.append(235);\n    data.append(236);\n    data.append(237);\n    data.append(238);\n    data.append(239);\n    data.append(240);\n    data.append(241);\n    data.append(242);\n    data.append(243);\n    data.append(244);\n    data.append(245);\n    data.append(246);\n    data.append(247);\n    data.append(248);\n    data.append(249);\n    data.append(250);\n    data.append(251);\n    data.append(252);\n    data.append(253);\n    data.append(254);\n    data.append(255);\n    data.append(256);\n    data.append(257);\n    data.append(258);\n    data.append(259);\n    data.append(260);\n    data.append(261);\n    data.append(262);\n    data.append(263);\n    data.append(264);\n    data.append(265);\n    data.append(266);\n    data.append(267);\n    data.append(268);\n    data.append(269);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_axis3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(5);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(11);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(17);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(23);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(29);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(35);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(41);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(47);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(53);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(59);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(65);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(71);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(77);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(83);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(89);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(95);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(101);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(107);\n    data.append(109);\n    data.append(110);\n    data.append(111);\n    data.append(113);\n    data.append(115);\n    data.append(116);\n    data.append(117);\n    data.append(119);\n    data.append(121);\n    data.append(122);\n    data.append(123);\n    data.append(125);\n    data.append(127);\n    data.append(128);\n    data.append(129);\n    data.append(131);\n    data.append(133);\n    data.append(134);\n    data.append(135);\n    data.append(137);\n    data.append(139);\n    data.append(140);\n    data.append(141);\n    data.append(143);\n    data.append(145);\n    data.append(146);\n    data.append(147);\n    data.append(149);\n    data.append(151);\n    data.append(152);\n    data.append(153);\n    data.append(155);\n    data.append(157);\n    data.append(158);\n    data.append(159);\n    data.append(161);\n    data.append(163);\n    data.append(164);\n    data.append(165);\n    data.append(167);\n    data.append(169);\n    data.append(170);\n    data.append(171);\n    data.append(173);\n    data.append(175);\n    data.append(176);\n    data.append(177);\n    data.append(179);\n    data.append(181);\n    data.append(182);\n    data.append(183);\n    data.append(185);\n    data.append(187);\n    data.append(188);\n    data.append(189);\n    data.append(191);\n    data.append(193);\n    data.append(194);\n    data.append(195);\n    data.append(197);\n    data.append(199);\n    data.append(200);\n    data.append(201);\n    data.append(203);\n    data.append(205);\n    data.append(206);\n    data.append(207);\n    data.append(209);\n    data.append(211);\n    data.append(212);\n    data.append(213);\n    data.append(215);\n    data.append(217);\n    data.append(218);\n    data.append(219);\n    data.append(221);\n    data.append(223);\n    data.append(224);\n    data.append(225);\n    data.append(227);\n    data.append(229);\n    data.append(230);\n    data.append(231);\n    data.append(233);\n    data.append(235);\n    data.append(236);\n    data.append(237);\n    data.append(239);\n    data.append(241);\n    data.append(242);\n    data.append(243);\n    data.append(245);\n    data.append(247);\n    data.append(248);\n    data.append(249);\n    data.append(251);\n    data.append(253);\n    data.append(254);\n    data.append(255);\n    data.append(257);\n    data.append(259);\n    data.append(260);\n    data.append(261);\n    data.append(263);\n    data.append(265);\n    data.append(266);\n    data.append(267);\n    data.append(269);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_compress_u32_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.compress(condition: input_1, axis: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/compress_u32_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_2d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_2d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_2d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_3d_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_3d_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_3d_three_tensors_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(9);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp16x16_3d_three_tensors_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp16x16_3d_three_tensors_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_2d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_2d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_2d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_3d_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_3d_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_3d_three_tensors_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(9);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_fp8x23_3d_three_tensors_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_fp8x23_3d_three_tensors_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::sequence::FP16x16Sequence;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp16x16_new_axis_default() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Array<Tensor<FP16x16>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_one.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::sequence::FP16x16Sequence;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp16x16_new_axis_one() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_one/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Array<Tensor<FP16x16>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_one/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(5);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_zero.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::sequence::FP16x16Sequence;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp16x16_new_axis_zero() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_zero/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Array<Tensor<FP16x16>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp16x16_new_axis_zero/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::FP8x23Sequence;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp8x23_new_axis_default() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Array<Tensor<FP8x23>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(10);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_one.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::FP8x23Sequence;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp8x23_new_axis_one() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_one/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Array<Tensor<FP8x23>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_one/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_zero.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::FP8x23Sequence;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_fp8x23_new_axis_zero() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_zero/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Array<Tensor<FP8x23>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_fp8x23_new_axis_zero/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I32Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i32_new_axis_default() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(-3);\n    data.append(-2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(-2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(-3);\n    data.append(1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(4);\n    data.append(-6);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-6);\n    data.append(2);\n    data.append(5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(-3);\n    data.append(-2);\n    data.append(4);\n    data.append(5);\n    data.append(-2);\n    data.append(4);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(4);\n    data.append(-6);\n    data.append(-6);\n    data.append(2);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_one.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I32Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i32_new_axis_one() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_one/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(1);\n    data.append(3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-4);\n    data.append(4);\n    data.append(-1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-6);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_one/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(-4);\n    data.append(4);\n    data.append(-1);\n    data.append(-1);\n    data.append(-6);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_zero.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I32Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i32_new_axis_zero() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_zero/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-4);\n    data.append(-5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-6);\n    data.append(-3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i32_new_axis_zero/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(10);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(-4);\n    data.append(-5);\n    data.append(-6);\n    data.append(-3);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I8Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i8_new_axis_default() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i8>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(-1);\n    data.append(3);\n    data.append(-1);\n    data.append(5);\n    data.append(5);\n    data.append(-1);\n    data.append(-1);\n    data.append(-6);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-5);\n    data.append(3);\n    data.append(5);\n    data.append(-5);\n    data.append(-1);\n    data.append(3);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(-4);\n    data.append(-2);\n    data.append(0);\n    data.append(-6);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-6);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(-1);\n    data.append(-2);\n    data.append(-6);\n    data.append(-4);\n    data.append(-5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-2);\n    data.append(-2);\n    data.append(3);\n    data.append(-1);\n    data.append(2);\n    data.append(5);\n    data.append(-2);\n    data.append(-5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(-1);\n    data.append(3);\n    data.append(-5);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(-4);\n    data.append(-2);\n    data.append(-6);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(5);\n    data.append(5);\n    data.append(-5);\n    data.append(-1);\n    data.append(3);\n    data.append(0);\n    data.append(-6);\n    data.append(2);\n    data.append(5);\n    data.append(-1);\n    data.append(-2);\n    data.append(3);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    data.append(-1);\n    data.append(-6);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(-6);\n    data.append(-4);\n    data.append(-5);\n    data.append(5);\n    data.append(-2);\n    data.append(-5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_one.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I8Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i8_new_axis_one() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_one/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i8>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-4);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-5);\n    data.append(-5);\n    data.append(5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-5);\n    data.append(-3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-6);\n    data.append(1);\n    data.append(3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(0);\n    data.append(-4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_one/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-5);\n    data.append(-2);\n    data.append(-6);\n    data.append(3);\n    data.append(-4);\n    data.append(-5);\n    data.append(-5);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(-3);\n    data.append(3);\n    data.append(-4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_zero.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::I8Sequence;\nuse orion::operators::sequence::SequenceTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_i8_new_axis_zero() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_zero/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<i8>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(-6);\n    data.append(-1);\n    data.append(4);\n    data.append(-6);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-5);\n    data.append(-2);\n    data.append(4);\n    data.append(1);\n    data.append(-2);\n    data.append(-5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(5);\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-5);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_i8_new_axis_zero/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(-6);\n    data.append(-5);\n    data.append(-2);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(-2);\n    data.append(-5);\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(4);\n    data.append(-6);\n    data.append(1);\n    data.append(-2);\n    data.append(-5);\n    data.append(-3);\n    data.append(5);\n    data.append(2);\n    data.append(-2);\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::SequenceTrait;\nuse orion::operators::sequence::U32Sequence;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_u32_new_axis_default() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::None(()));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<u32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_one.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::SequenceTrait;\nuse orion::operators::sequence::U32Sequence;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_u32_new_axis_one() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_one/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<u32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_one/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_zero.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::sequence::SequenceTrait;\nuse orion::operators::sequence::U32Sequence;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_from_sequence_u32_new_axis_zero() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = SequenceTrait::concat_from_sequence(input_0, 1_i32, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_zero/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Array<Tensor<u32>> {\n    let mut sequence = ArrayTrait::new();\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n\n    sequence.append(TensorTrait::new(shape.span(), data.span()));\n\n    sequence\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_from_sequence_u32_new_axis_zero/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(15);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_2d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_2d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_2d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_3d_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_3d_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_3d_three_tensors_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(9);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i32_3d_three_tensors_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i32_3d_three_tensors_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_2d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_2d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_2d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_3d_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_3d_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_3d_three_tensors_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 54, sign: false });\n    data.append(FP8x23 { mag: 55, sign: false });\n    data.append(FP8x23 { mag: 56, sign: false });\n    data.append(FP8x23 { mag: 57, sign: false });\n    data.append(FP8x23 { mag: 58, sign: false });\n    data.append(FP8x23 { mag: 59, sign: false });\n    data.append(FP8x23 { mag: 60, sign: false });\n    data.append(FP8x23 { mag: 61, sign: false });\n    data.append(FP8x23 { mag: 62, sign: false });\n    data.append(FP8x23 { mag: 63, sign: false });\n    data.append(FP8x23 { mag: 64, sign: false });\n    data.append(FP8x23 { mag: 65, sign: false });\n    data.append(FP8x23 { mag: 66, sign: false });\n    data.append(FP8x23 { mag: 67, sign: false });\n    data.append(FP8x23 { mag: 68, sign: false });\n    data.append(FP8x23 { mag: 69, sign: false });\n    data.append(FP8x23 { mag: 70, sign: false });\n    data.append(FP8x23 { mag: 71, sign: false });\n    data.append(FP8x23 { mag: 72, sign: false });\n    data.append(FP8x23 { mag: 73, sign: false });\n    data.append(FP8x23 { mag: 74, sign: false });\n    data.append(FP8x23 { mag: 75, sign: false });\n    data.append(FP8x23 { mag: 76, sign: false });\n    data.append(FP8x23 { mag: 77, sign: false });\n    data.append(FP8x23 { mag: 78, sign: false });\n    data.append(FP8x23 { mag: 79, sign: false });\n    data.append(FP8x23 { mag: 80, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(9);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 54, sign: false });\n    data.append(FP8x23 { mag: 55, sign: false });\n    data.append(FP8x23 { mag: 56, sign: false });\n    data.append(FP8x23 { mag: 57, sign: false });\n    data.append(FP8x23 { mag: 58, sign: false });\n    data.append(FP8x23 { mag: 59, sign: false });\n    data.append(FP8x23 { mag: 60, sign: false });\n    data.append(FP8x23 { mag: 61, sign: false });\n    data.append(FP8x23 { mag: 62, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 63, sign: false });\n    data.append(FP8x23 { mag: 64, sign: false });\n    data.append(FP8x23 { mag: 65, sign: false });\n    data.append(FP8x23 { mag: 66, sign: false });\n    data.append(FP8x23 { mag: 67, sign: false });\n    data.append(FP8x23 { mag: 68, sign: false });\n    data.append(FP8x23 { mag: 69, sign: false });\n    data.append(FP8x23 { mag: 70, sign: false });\n    data.append(FP8x23 { mag: 71, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    data.append(FP8x23 { mag: 72, sign: false });\n    data.append(FP8x23 { mag: 73, sign: false });\n    data.append(FP8x23 { mag: 74, sign: false });\n    data.append(FP8x23 { mag: 75, sign: false });\n    data.append(FP8x23 { mag: 76, sign: false });\n    data.append(FP8x23 { mag: 77, sign: false });\n    data.append(FP8x23 { mag: 78, sign: false });\n    data.append(FP8x23 { mag: 79, sign: false });\n    data.append(FP8x23 { mag: 80, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_i8_3d_three_tensors_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 54, sign: false });\n    data.append(FP8x23 { mag: 55, sign: false });\n    data.append(FP8x23 { mag: 56, sign: false });\n    data.append(FP8x23 { mag: 57, sign: false });\n    data.append(FP8x23 { mag: 58, sign: false });\n    data.append(FP8x23 { mag: 59, sign: false });\n    data.append(FP8x23 { mag: 60, sign: false });\n    data.append(FP8x23 { mag: 61, sign: false });\n    data.append(FP8x23 { mag: 62, sign: false });\n    data.append(FP8x23 { mag: 63, sign: false });\n    data.append(FP8x23 { mag: 64, sign: false });\n    data.append(FP8x23 { mag: 65, sign: false });\n    data.append(FP8x23 { mag: 66, sign: false });\n    data.append(FP8x23 { mag: 67, sign: false });\n    data.append(FP8x23 { mag: 68, sign: false });\n    data.append(FP8x23 { mag: 69, sign: false });\n    data.append(FP8x23 { mag: 70, sign: false });\n    data.append(FP8x23 { mag: 71, sign: false });\n    data.append(FP8x23 { mag: 72, sign: false });\n    data.append(FP8x23 { mag: 73, sign: false });\n    data.append(FP8x23 { mag: 74, sign: false });\n    data.append(FP8x23 { mag: 75, sign: false });\n    data.append(FP8x23 { mag: 76, sign: false });\n    data.append(FP8x23 { mag: 77, sign: false });\n    data.append(FP8x23 { mag: 78, sign: false });\n    data.append(FP8x23 { mag: 79, sign: false });\n    data.append(FP8x23 { mag: 80, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_i8_3d_three_tensors_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 27, sign: false });\n    data.append(FP8x23 { mag: 28, sign: false });\n    data.append(FP8x23 { mag: 29, sign: false });\n    data.append(FP8x23 { mag: 54, sign: false });\n    data.append(FP8x23 { mag: 55, sign: false });\n    data.append(FP8x23 { mag: 56, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    data.append(FP8x23 { mag: 5, sign: false });\n    data.append(FP8x23 { mag: 30, sign: false });\n    data.append(FP8x23 { mag: 31, sign: false });\n    data.append(FP8x23 { mag: 32, sign: false });\n    data.append(FP8x23 { mag: 57, sign: false });\n    data.append(FP8x23 { mag: 58, sign: false });\n    data.append(FP8x23 { mag: 59, sign: false });\n    data.append(FP8x23 { mag: 6, sign: false });\n    data.append(FP8x23 { mag: 7, sign: false });\n    data.append(FP8x23 { mag: 8, sign: false });\n    data.append(FP8x23 { mag: 33, sign: false });\n    data.append(FP8x23 { mag: 34, sign: false });\n    data.append(FP8x23 { mag: 35, sign: false });\n    data.append(FP8x23 { mag: 60, sign: false });\n    data.append(FP8x23 { mag: 61, sign: false });\n    data.append(FP8x23 { mag: 62, sign: false });\n    data.append(FP8x23 { mag: 9, sign: false });\n    data.append(FP8x23 { mag: 10, sign: false });\n    data.append(FP8x23 { mag: 11, sign: false });\n    data.append(FP8x23 { mag: 36, sign: false });\n    data.append(FP8x23 { mag: 37, sign: false });\n    data.append(FP8x23 { mag: 38, sign: false });\n    data.append(FP8x23 { mag: 63, sign: false });\n    data.append(FP8x23 { mag: 64, sign: false });\n    data.append(FP8x23 { mag: 65, sign: false });\n    data.append(FP8x23 { mag: 12, sign: false });\n    data.append(FP8x23 { mag: 13, sign: false });\n    data.append(FP8x23 { mag: 14, sign: false });\n    data.append(FP8x23 { mag: 39, sign: false });\n    data.append(FP8x23 { mag: 40, sign: false });\n    data.append(FP8x23 { mag: 41, sign: false });\n    data.append(FP8x23 { mag: 66, sign: false });\n    data.append(FP8x23 { mag: 67, sign: false });\n    data.append(FP8x23 { mag: 68, sign: false });\n    data.append(FP8x23 { mag: 15, sign: false });\n    data.append(FP8x23 { mag: 16, sign: false });\n    data.append(FP8x23 { mag: 17, sign: false });\n    data.append(FP8x23 { mag: 42, sign: false });\n    data.append(FP8x23 { mag: 43, sign: false });\n    data.append(FP8x23 { mag: 44, sign: false });\n    data.append(FP8x23 { mag: 69, sign: false });\n    data.append(FP8x23 { mag: 70, sign: false });\n    data.append(FP8x23 { mag: 71, sign: false });\n    data.append(FP8x23 { mag: 18, sign: false });\n    data.append(FP8x23 { mag: 19, sign: false });\n    data.append(FP8x23 { mag: 20, sign: false });\n    data.append(FP8x23 { mag: 45, sign: false });\n    data.append(FP8x23 { mag: 46, sign: false });\n    data.append(FP8x23 { mag: 47, sign: false });\n    data.append(FP8x23 { mag: 72, sign: false });\n    data.append(FP8x23 { mag: 73, sign: false });\n    data.append(FP8x23 { mag: 74, sign: false });\n    data.append(FP8x23 { mag: 21, sign: false });\n    data.append(FP8x23 { mag: 22, sign: false });\n    data.append(FP8x23 { mag: 23, sign: false });\n    data.append(FP8x23 { mag: 48, sign: false });\n    data.append(FP8x23 { mag: 49, sign: false });\n    data.append(FP8x23 { mag: 50, sign: false });\n    data.append(FP8x23 { mag: 75, sign: false });\n    data.append(FP8x23 { mag: 76, sign: false });\n    data.append(FP8x23 { mag: 77, sign: false });\n    data.append(FP8x23 { mag: 24, sign: false });\n    data.append(FP8x23 { mag: 25, sign: false });\n    data.append(FP8x23 { mag: 26, sign: false });\n    data.append(FP8x23 { mag: 51, sign: false });\n    data.append(FP8x23 { mag: 52, sign: false });\n    data.append(FP8x23 { mag: 53, sign: false });\n    data.append(FP8x23 { mag: 78, sign: false });\n    data.append(FP8x23 { mag: 79, sign: false });\n    data.append(FP8x23 { mag: 80, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_2d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_2d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_2d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_3d_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_3d_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1].span(), 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_3d_three_tensors_axis_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(9);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_concat_u32_3d_three_tensors_axis_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::concat(array![input_0, input_1, input_2].span(), 2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/concat_u32_3d_three_tensors_axis_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_no_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_1D_no_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_no_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_no_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_no_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_with_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_1D_with_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![1, 1].span()),\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_with_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_with_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_1D_with_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_2_groups.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_2D_with_2_groups() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(2),\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_2_groups/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_2_groups/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_2_groups/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_autopad_same.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\nuse orion::operators::nn::functional::conv::AUTO_PAD;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_2D_with_autopad_same() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::Some(AUTO_PAD::SAME_LOWER),\n        Option::None,\n        Option::None,\n        Option::Some(array![3, 3].span()),\n        Option::None,\n        Option::Some(array![2, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_autopad_same/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_autopad_same/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_autopad_same/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_2D_with_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 10027008, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_asymmetric_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_2D_with_strides_asymmetric_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![3, 3].span()),\n        Option::Some(array![1, 0, 1, 0].span()),\n        Option::Some(array![2, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_asymmetric_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(7);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_asymmetric_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_asymmetric_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 12386304, sign: false });\n    data.append(FP16x16 { mag: 13565952, sign: false });\n    data.append(FP16x16 { mag: 11206656, sign: false });\n    data.append(FP16x16 { mag: 11993088, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_with_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_2D_with_strides_with_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![3, 3].span()),\n        Option::Some(array![1, 1, 1, 1].span()),\n        Option::Some(array![2, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_with_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(7);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_with_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_2D_with_strides_with_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 11599872, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_no_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_3D_no_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_no_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_no_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_no_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 54853632, sign: false });\n    data.append(FP16x16 { mag: 56623104, sign: false });\n    data.append(FP16x16 { mag: 58392576, sign: false });\n    data.append(FP16x16 { mag: 63700992, sign: false });\n    data.append(FP16x16 { mag: 65470464, sign: false });\n    data.append(FP16x16 { mag: 67239936, sign: false });\n    data.append(FP16x16 { mag: 72548352, sign: false });\n    data.append(FP16x16 { mag: 74317824, sign: false });\n    data.append(FP16x16 { mag: 76087296, sign: false });\n    data.append(FP16x16 { mag: 99090432, sign: false });\n    data.append(FP16x16 { mag: 100859904, sign: false });\n    data.append(FP16x16 { mag: 102629376, sign: false });\n    data.append(FP16x16 { mag: 107937792, sign: false });\n    data.append(FP16x16 { mag: 109707264, sign: false });\n    data.append(FP16x16 { mag: 111476736, sign: false });\n    data.append(FP16x16 { mag: 116785152, sign: false });\n    data.append(FP16x16 { mag: 118554624, sign: false });\n    data.append(FP16x16 { mag: 120324096, sign: false });\n    data.append(FP16x16 { mag: 143327232, sign: false });\n    data.append(FP16x16 { mag: 145096704, sign: false });\n    data.append(FP16x16 { mag: 146866176, sign: false });\n    data.append(FP16x16 { mag: 152174592, sign: false });\n    data.append(FP16x16 { mag: 153944064, sign: false });\n    data.append(FP16x16 { mag: 155713536, sign: false });\n    data.append(FP16x16 { mag: 161021952, sign: false });\n    data.append(FP16x16 { mag: 162791424, sign: false });\n    data.append(FP16x16 { mag: 164560896, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_with_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_3D_with_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![1, 1, 1, 1, 1, 1].span()),\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_with_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_with_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_3D_with_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 12582912, sign: false });\n    data.append(FP16x16 { mag: 13369344, sign: false });\n    data.append(FP16x16 { mag: 14155776, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 14155776, sign: false });\n    data.append(FP16x16 { mag: 21823488, sign: false });\n    data.append(FP16x16 { mag: 23003136, sign: false });\n    data.append(FP16x16 { mag: 24182784, sign: false });\n    data.append(FP16x16 { mag: 16515072, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 27721728, sign: false });\n    data.append(FP16x16 { mag: 28901376, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 20447232, sign: false });\n    data.append(FP16x16 { mag: 22020096, sign: false });\n    data.append(FP16x16 { mag: 33619968, sign: false });\n    data.append(FP16x16 { mag: 34799616, sign: false });\n    data.append(FP16x16 { mag: 35979264, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 15990784, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 25165824, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 17563648, sign: false });\n    data.append(FP16x16 { mag: 22020096, sign: false });\n    data.append(FP16x16 { mag: 33619968, sign: false });\n    data.append(FP16x16 { mag: 34799616, sign: false });\n    data.append(FP16x16 { mag: 35979264, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 35979264, sign: false });\n    data.append(FP16x16 { mag: 54853632, sign: false });\n    data.append(FP16x16 { mag: 56623104, sign: false });\n    data.append(FP16x16 { mag: 58392576, sign: false });\n    data.append(FP16x16 { mag: 39518208, sign: false });\n    data.append(FP16x16 { mag: 41877504, sign: false });\n    data.append(FP16x16 { mag: 63700992, sign: false });\n    data.append(FP16x16 { mag: 65470464, sign: false });\n    data.append(FP16x16 { mag: 67239936, sign: false });\n    data.append(FP16x16 { mag: 45416448, sign: false });\n    data.append(FP16x16 { mag: 47775744, sign: false });\n    data.append(FP16x16 { mag: 72548352, sign: false });\n    data.append(FP16x16 { mag: 74317824, sign: false });\n    data.append(FP16x16 { mag: 76087296, sign: false });\n    data.append(FP16x16 { mag: 51314688, sign: false });\n    data.append(FP16x16 { mag: 33816576, sign: false });\n    data.append(FP16x16 { mag: 51314688, sign: false });\n    data.append(FP16x16 { mag: 52494336, sign: false });\n    data.append(FP16x16 { mag: 53673984, sign: false });\n    data.append(FP16x16 { mag: 36175872, sign: false });\n    data.append(FP16x16 { mag: 41680896, sign: false });\n    data.append(FP16x16 { mag: 63111168, sign: false });\n    data.append(FP16x16 { mag: 64290816, sign: false });\n    data.append(FP16x16 { mag: 65470464, sign: false });\n    data.append(FP16x16 { mag: 44040192, sign: false });\n    data.append(FP16x16 { mag: 65470464, sign: false });\n    data.append(FP16x16 { mag: 99090432, sign: false });\n    data.append(FP16x16 { mag: 100859904, sign: false });\n    data.append(FP16x16 { mag: 102629376, sign: false });\n    data.append(FP16x16 { mag: 69009408, sign: false });\n    data.append(FP16x16 { mag: 71368704, sign: false });\n    data.append(FP16x16 { mag: 107937792, sign: false });\n    data.append(FP16x16 { mag: 109707264, sign: false });\n    data.append(FP16x16 { mag: 111476736, sign: false });\n    data.append(FP16x16 { mag: 74907648, sign: false });\n    data.append(FP16x16 { mag: 77266944, sign: false });\n    data.append(FP16x16 { mag: 116785152, sign: false });\n    data.append(FP16x16 { mag: 118554624, sign: false });\n    data.append(FP16x16 { mag: 120324096, sign: false });\n    data.append(FP16x16 { mag: 80805888, sign: false });\n    data.append(FP16x16 { mag: 53477376, sign: false });\n    data.append(FP16x16 { mag: 80805888, sign: false });\n    data.append(FP16x16 { mag: 81985536, sign: false });\n    data.append(FP16x16 { mag: 83165184, sign: false });\n    data.append(FP16x16 { mag: 55836672, sign: false });\n    data.append(FP16x16 { mag: 61341696, sign: false });\n    data.append(FP16x16 { mag: 92602368, sign: false });\n    data.append(FP16x16 { mag: 93782016, sign: false });\n    data.append(FP16x16 { mag: 94961664, sign: false });\n    data.append(FP16x16 { mag: 63700992, sign: false });\n    data.append(FP16x16 { mag: 94961664, sign: false });\n    data.append(FP16x16 { mag: 143327232, sign: false });\n    data.append(FP16x16 { mag: 145096704, sign: false });\n    data.append(FP16x16 { mag: 146866176, sign: false });\n    data.append(FP16x16 { mag: 98500608, sign: false });\n    data.append(FP16x16 { mag: 100859904, sign: false });\n    data.append(FP16x16 { mag: 152174592, sign: false });\n    data.append(FP16x16 { mag: 153944064, sign: false });\n    data.append(FP16x16 { mag: 155713536, sign: false });\n    data.append(FP16x16 { mag: 104398848, sign: false });\n    data.append(FP16x16 { mag: 106758144, sign: false });\n    data.append(FP16x16 { mag: 161021952, sign: false });\n    data.append(FP16x16 { mag: 162791424, sign: false });\n    data.append(FP16x16 { mag: 164560896, sign: false });\n    data.append(FP16x16 { mag: 110297088, sign: false });\n    data.append(FP16x16 { mag: 73138176, sign: false });\n    data.append(FP16x16 { mag: 110297088, sign: false });\n    data.append(FP16x16 { mag: 111476736, sign: false });\n    data.append(FP16x16 { mag: 112656384, sign: false });\n    data.append(FP16x16 { mag: 75497472, sign: false });\n    data.append(FP16x16 { mag: 47448064, sign: false });\n    data.append(FP16x16 { mag: 71565312, sign: false });\n    data.append(FP16x16 { mag: 72351744, sign: false });\n    data.append(FP16x16 { mag: 73138176, sign: false });\n    data.append(FP16x16 { mag: 49020928, sign: false });\n    data.append(FP16x16 { mag: 73138176, sign: false });\n    data.append(FP16x16 { mag: 110297088, sign: false });\n    data.append(FP16x16 { mag: 111476736, sign: false });\n    data.append(FP16x16 { mag: 112656384, sign: false });\n    data.append(FP16x16 { mag: 75497472, sign: false });\n    data.append(FP16x16 { mag: 77070336, sign: false });\n    data.append(FP16x16 { mag: 116195328, sign: false });\n    data.append(FP16x16 { mag: 117374976, sign: false });\n    data.append(FP16x16 { mag: 118554624, sign: false });\n    data.append(FP16x16 { mag: 79429632, sign: false });\n    data.append(FP16x16 { mag: 81002496, sign: false });\n    data.append(FP16x16 { mag: 122093568, sign: false });\n    data.append(FP16x16 { mag: 123273216, sign: false });\n    data.append(FP16x16 { mag: 124452864, sign: false });\n    data.append(FP16x16 { mag: 83361792, sign: false });\n    data.append(FP16x16 { mag: 55312384, sign: false });\n    data.append(FP16x16 { mag: 83361792, sign: false });\n    data.append(FP16x16 { mag: 84148224, sign: false });\n    data.append(FP16x16 { mag: 84934656, sign: false });\n    data.append(FP16x16 { mag: 56885248, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_no_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_4D_no_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_no_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_no_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_no_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 20971520, sign: false });\n    data.append(FP16x16 { mag: 22020096, sign: false });\n    data.append(FP16x16 { mag: 24117248, sign: false });\n    data.append(FP16x16 { mag: 25165824, sign: false });\n    data.append(FP16x16 { mag: 30408704, sign: false });\n    data.append(FP16x16 { mag: 31457280, sign: false });\n    data.append(FP16x16 { mag: 33554432, sign: false });\n    data.append(FP16x16 { mag: 34603008, sign: false });\n    data.append(FP16x16 { mag: 49283072, sign: false });\n    data.append(FP16x16 { mag: 50331648, sign: false });\n    data.append(FP16x16 { mag: 52428800, sign: false });\n    data.append(FP16x16 { mag: 53477376, sign: false });\n    data.append(FP16x16 { mag: 58720256, sign: false });\n    data.append(FP16x16 { mag: 59768832, sign: false });\n    data.append(FP16x16 { mag: 61865984, sign: false });\n    data.append(FP16x16 { mag: 62914560, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_with_padding.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_4D_with_padding() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![1, 1, 1, 1, 1, 1, 1, 1].span()),\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_with_padding/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_with_padding/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_4D_with_padding/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 9699328, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 20971520, sign: false });\n    data.append(FP16x16 { mag: 22020096, sign: false });\n    data.append(FP16x16 { mag: 11272192, sign: false });\n    data.append(FP16x16 { mag: 11796480, sign: false });\n    data.append(FP16x16 { mag: 24117248, sign: false });\n    data.append(FP16x16 { mag: 25165824, sign: false });\n    data.append(FP16x16 { mag: 12845056, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 12845056, sign: false });\n    data.append(FP16x16 { mag: 13369344, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 14417920, sign: false });\n    data.append(FP16x16 { mag: 14942208, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 14942208, sign: false });\n    data.append(FP16x16 { mag: 30408704, sign: false });\n    data.append(FP16x16 { mag: 31457280, sign: false });\n    data.append(FP16x16 { mag: 15990784, sign: false });\n    data.append(FP16x16 { mag: 16515072, sign: false });\n    data.append(FP16x16 { mag: 33554432, sign: false });\n    data.append(FP16x16 { mag: 34603008, sign: false });\n    data.append(FP16x16 { mag: 17563648, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 17563648, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 9175040, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 8650752, sign: false });\n    data.append(FP16x16 { mag: 17563648, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 9175040, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 19136512, sign: false });\n    data.append(FP16x16 { mag: 19660800, sign: false });\n    data.append(FP16x16 { mag: 9961472, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 9961472, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 10747904, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 22282240, sign: false });\n    data.append(FP16x16 { mag: 22806528, sign: false });\n    data.append(FP16x16 { mag: 11534336, sign: false });\n    data.append(FP16x16 { mag: 11796480, sign: false });\n    data.append(FP16x16 { mag: 23855104, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 12320768, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 12320768, sign: false });\n    data.append(FP16x16 { mag: 12582912, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 11796480, sign: false });\n    data.append(FP16x16 { mag: 23855104, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 12320768, sign: false });\n    data.append(FP16x16 { mag: 24379392, sign: false });\n    data.append(FP16x16 { mag: 49283072, sign: false });\n    data.append(FP16x16 { mag: 50331648, sign: false });\n    data.append(FP16x16 { mag: 25427968, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 52428800, sign: false });\n    data.append(FP16x16 { mag: 53477376, sign: false });\n    data.append(FP16x16 { mag: 27000832, sign: false });\n    data.append(FP16x16 { mag: 13369344, sign: false });\n    data.append(FP16x16 { mag: 27000832, sign: false });\n    data.append(FP16x16 { mag: 27525120, sign: false });\n    data.append(FP16x16 { mag: 13893632, sign: false });\n    data.append(FP16x16 { mag: 14155776, sign: false });\n    data.append(FP16x16 { mag: 28573696, sign: false });\n    data.append(FP16x16 { mag: 29097984, sign: false });\n    data.append(FP16x16 { mag: 14680064, sign: false });\n    data.append(FP16x16 { mag: 29097984, sign: false });\n    data.append(FP16x16 { mag: 58720256, sign: false });\n    data.append(FP16x16 { mag: 59768832, sign: false });\n    data.append(FP16x16 { mag: 30146560, sign: false });\n    data.append(FP16x16 { mag: 30670848, sign: false });\n    data.append(FP16x16 { mag: 61865984, sign: false });\n    data.append(FP16x16 { mag: 62914560, sign: false });\n    data.append(FP16x16 { mag: 31719424, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 31719424, sign: false });\n    data.append(FP16x16 { mag: 32243712, sign: false });\n    data.append(FP16x16 { mag: 16252928, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 15466496, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 31719424, sign: false });\n    data.append(FP16x16 { mag: 32243712, sign: false });\n    data.append(FP16x16 { mag: 16252928, sign: false });\n    data.append(FP16x16 { mag: 16515072, sign: false });\n    data.append(FP16x16 { mag: 33292288, sign: false });\n    data.append(FP16x16 { mag: 33816576, sign: false });\n    data.append(FP16x16 { mag: 17039360, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 17039360, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 8716288, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 14680064, sign: false });\n    data.append(FP16x16 { mag: 14942208, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 15466496, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 15466496, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 31719424, sign: false });\n    data.append(FP16x16 { mag: 32243712, sign: false });\n    data.append(FP16x16 { mag: 16252928, sign: false });\n    data.append(FP16x16 { mag: 16515072, sign: false });\n    data.append(FP16x16 { mag: 33292288, sign: false });\n    data.append(FP16x16 { mag: 33816576, sign: false });\n    data.append(FP16x16 { mag: 17039360, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 17039360, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 8716288, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 17825792, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 9109504, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 36438016, sign: false });\n    data.append(FP16x16 { mag: 36962304, sign: false });\n    data.append(FP16x16 { mag: 18612224, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 38010880, sign: false });\n    data.append(FP16x16 { mag: 38535168, sign: false });\n    data.append(FP16x16 { mag: 19398656, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 19398656, sign: false });\n    data.append(FP16x16 { mag: 19660800, sign: false });\n    data.append(FP16x16 { mag: 9895936, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 9502720, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 19398656, sign: false });\n    data.append(FP16x16 { mag: 19660800, sign: false });\n    data.append(FP16x16 { mag: 9895936, sign: false });\n    data.append(FP16x16 { mag: 10027008, sign: false });\n    data.append(FP16x16 { mag: 20185088, sign: false });\n    data.append(FP16x16 { mag: 20447232, sign: false });\n    data.append(FP16x16 { mag: 10289152, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 10289152, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_3d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_3d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_3d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(5);\n    shape.append(6);\n    shape.append(7);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 11403264, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 21233664, sign: false });\n    data.append(FP16x16 { mag: 14548992, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 16121856, sign: false });\n    data.append(FP16x16 { mag: 24772608, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 12058624, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 19267584, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 13631488, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 12386304, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 13565952, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 27721728, sign: false });\n    data.append(FP16x16 { mag: 28901376, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 20447232, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 14745600, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 46006272, sign: false });\n    data.append(FP16x16 { mag: 47775744, sign: false });\n    data.append(FP16x16 { mag: 49545216, sign: false });\n    data.append(FP16x16 { mag: 33619968, sign: false });\n    data.append(FP16x16 { mag: 17104896, sign: false });\n    data.append(FP16x16 { mag: 17694720, sign: false });\n    data.append(FP16x16 { mag: 35979264, sign: false });\n    data.append(FP16x16 { mag: 54853632, sign: false });\n    data.append(FP16x16 { mag: 56623104, sign: false });\n    data.append(FP16x16 { mag: 58392576, sign: false });\n    data.append(FP16x16 { mag: 39518208, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 12779520, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 39518208, sign: false });\n    data.append(FP16x16 { mag: 40697856, sign: false });\n    data.append(FP16x16 { mag: 41877504, sign: false });\n    data.append(FP16x16 { mag: 28311552, sign: false });\n    data.append(FP16x16 { mag: 14352384, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 13959168, sign: false });\n    data.append(FP16x16 { mag: 21233664, sign: false });\n    data.append(FP16x16 { mag: 21823488, sign: false });\n    data.append(FP16x16 { mag: 22413312, sign: false });\n    data.append(FP16x16 { mag: 15138816, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 12582912, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 8781824, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 8519680, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 26345472, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 27918336, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 9568256, sign: false });\n    data.append(FP16x16 { mag: 13762560, sign: false });\n    data.append(FP16x16 { mag: 27918336, sign: false });\n    data.append(FP16x16 { mag: 42467328, sign: false });\n    data.append(FP16x16 { mag: 43646976, sign: false });\n    data.append(FP16x16 { mag: 44826624, sign: false });\n    data.append(FP16x16 { mag: 30277632, sign: false });\n    data.append(FP16x16 { mag: 15335424, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 31850496, sign: false });\n    data.append(FP16x16 { mag: 48365568, sign: false });\n    data.append(FP16x16 { mag: 49545216, sign: false });\n    data.append(FP16x16 { mag: 50724864, sign: false });\n    data.append(FP16x16 { mag: 34209792, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 11141120, sign: false });\n    data.append(FP16x16 { mag: 22544384, sign: false });\n    data.append(FP16x16 { mag: 34209792, sign: false });\n    data.append(FP16x16 { mag: 34996224, sign: false });\n    data.append(FP16x16 { mag: 35782656, sign: false });\n    data.append(FP16x16 { mag: 24117248, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 11927552, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 12713984, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 11272192, sign: false });\n    data.append(FP16x16 { mag: 17104896, sign: false });\n    data.append(FP16x16 { mag: 17498112, sign: false });\n    data.append(FP16x16 { mag: 17891328, sign: false });\n    data.append(FP16x16 { mag: 12058624, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 17891328, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 27721728, sign: false });\n    data.append(FP16x16 { mag: 28311552, sign: false });\n    data.append(FP16x16 { mag: 19070976, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 9830400, sign: false });\n    data.append(FP16x16 { mag: 19857408, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 30670848, sign: false });\n    data.append(FP16x16 { mag: 31260672, sign: false });\n    data.append(FP16x16 { mag: 21037056, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 13893632, sign: false });\n    data.append(FP16x16 { mag: 21037056, sign: false });\n    data.append(FP16x16 { mag: 21430272, sign: false });\n    data.append(FP16x16 { mag: 21823488, sign: false });\n    data.append(FP16x16 { mag: 14680064, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 11206656, sign: false });\n    data.append(FP16x16 { mag: 11403264, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 11403264, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 8388608, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 21233664, sign: false });\n    data.append(FP16x16 { mag: 14548992, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 16121856, sign: false });\n    data.append(FP16x16 { mag: 24772608, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 9437184, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 12058624, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 19267584, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 13631488, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 10223616, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 12386304, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 13565952, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 27721728, sign: false });\n    data.append(FP16x16 { mag: 28901376, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 20447232, sign: false });\n    data.append(FP16x16 { mag: 10420224, sign: false });\n    data.append(FP16x16 { mag: 14745600, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 46006272, sign: false });\n    data.append(FP16x16 { mag: 47775744, sign: false });\n    data.append(FP16x16 { mag: 49545216, sign: false });\n    data.append(FP16x16 { mag: 33619968, sign: false });\n    data.append(FP16x16 { mag: 17104896, sign: false });\n    data.append(FP16x16 { mag: 17694720, sign: false });\n    data.append(FP16x16 { mag: 35979264, sign: false });\n    data.append(FP16x16 { mag: 54853632, sign: false });\n    data.append(FP16x16 { mag: 56623104, sign: false });\n    data.append(FP16x16 { mag: 58392576, sign: false });\n    data.append(FP16x16 { mag: 39518208, sign: false });\n    data.append(FP16x16 { mag: 20054016, sign: false });\n    data.append(FP16x16 { mag: 12779520, sign: false });\n    data.append(FP16x16 { mag: 25952256, sign: false });\n    data.append(FP16x16 { mag: 39518208, sign: false });\n    data.append(FP16x16 { mag: 40697856, sign: false });\n    data.append(FP16x16 { mag: 41877504, sign: false });\n    data.append(FP16x16 { mag: 28311552, sign: false });\n    data.append(FP16x16 { mag: 14352384, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 13959168, sign: false });\n    data.append(FP16x16 { mag: 21233664, sign: false });\n    data.append(FP16x16 { mag: 21823488, sign: false });\n    data.append(FP16x16 { mag: 22413312, sign: false });\n    data.append(FP16x16 { mag: 15138816, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 12582912, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 8781824, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 8519680, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 26345472, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 27918336, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 9568256, sign: false });\n    data.append(FP16x16 { mag: 13762560, sign: false });\n    data.append(FP16x16 { mag: 27918336, sign: false });\n    data.append(FP16x16 { mag: 42467328, sign: false });\n    data.append(FP16x16 { mag: 43646976, sign: false });\n    data.append(FP16x16 { mag: 44826624, sign: false });\n    data.append(FP16x16 { mag: 30277632, sign: false });\n    data.append(FP16x16 { mag: 15335424, sign: false });\n    data.append(FP16x16 { mag: 15728640, sign: false });\n    data.append(FP16x16 { mag: 31850496, sign: false });\n    data.append(FP16x16 { mag: 48365568, sign: false });\n    data.append(FP16x16 { mag: 49545216, sign: false });\n    data.append(FP16x16 { mag: 50724864, sign: false });\n    data.append(FP16x16 { mag: 34209792, sign: false });\n    data.append(FP16x16 { mag: 17301504, sign: false });\n    data.append(FP16x16 { mag: 11141120, sign: false });\n    data.append(FP16x16 { mag: 22544384, sign: false });\n    data.append(FP16x16 { mag: 34209792, sign: false });\n    data.append(FP16x16 { mag: 34996224, sign: false });\n    data.append(FP16x16 { mag: 35782656, sign: false });\n    data.append(FP16x16 { mag: 24117248, sign: false });\n    data.append(FP16x16 { mag: 12189696, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 11927552, sign: false });\n    data.append(FP16x16 { mag: 18087936, sign: false });\n    data.append(FP16x16 { mag: 18481152, sign: false });\n    data.append(FP16x16 { mag: 18874368, sign: false });\n    data.append(FP16x16 { mag: 12713984, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: false });\n    data.append(FP16x16 { mag: 11272192, sign: false });\n    data.append(FP16x16 { mag: 17104896, sign: false });\n    data.append(FP16x16 { mag: 17498112, sign: false });\n    data.append(FP16x16 { mag: 17891328, sign: false });\n    data.append(FP16x16 { mag: 12058624, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 17891328, sign: false });\n    data.append(FP16x16 { mag: 27131904, sign: false });\n    data.append(FP16x16 { mag: 27721728, sign: false });\n    data.append(FP16x16 { mag: 28311552, sign: false });\n    data.append(FP16x16 { mag: 19070976, sign: false });\n    data.append(FP16x16 { mag: 9633792, sign: false });\n    data.append(FP16x16 { mag: 9830400, sign: false });\n    data.append(FP16x16 { mag: 19857408, sign: false });\n    data.append(FP16x16 { mag: 30081024, sign: false });\n    data.append(FP16x16 { mag: 30670848, sign: false });\n    data.append(FP16x16 { mag: 31260672, sign: false });\n    data.append(FP16x16 { mag: 21037056, sign: false });\n    data.append(FP16x16 { mag: 10616832, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 13893632, sign: false });\n    data.append(FP16x16 { mag: 21037056, sign: false });\n    data.append(FP16x16 { mag: 21430272, sign: false });\n    data.append(FP16x16 { mag: 21823488, sign: false });\n    data.append(FP16x16 { mag: 14680064, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 11010048, sign: false });\n    data.append(FP16x16 { mag: 11206656, sign: false });\n    data.append(FP16x16 { mag: 11403264, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_attributes.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_attributes() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_attributes/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_attributes/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_attributes/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_autopad_same.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\nuse orion::operators::nn::functional::conv_transpose::AUTO_PAD;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_autopad_same() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::Some(AUTO_PAD::SAME_UPPER),\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![2, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_autopad_same/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_autopad_same/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_autopad_same/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(6);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_dilations.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_dilations() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::Some(array![2, 2].span()),\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_dilations/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_dilations/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_dilations/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_group_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(2),\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2_image_3.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_group_2_image_3() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(2),\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2_image_3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2_image_3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_group_2_image_3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(5);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 8454144, sign: false });\n    data.append(FP16x16 { mag: 12976128, sign: false });\n    data.append(FP16x16 { mag: 8847360, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 9240576, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_pads.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conv_transpose_pads() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::conv_transpose(\n        @input_0,\n        @input_1,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::None,\n        Option::Some(array![3, 3].span()),\n        Option::Some(array![1, 1].span()),\n        Option::Some(array![10, 8].span()),\n        Option::None,\n        Option::Some(array![3, 2].span())\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_pads/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_pads/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/conv_transpose_pads/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(10);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cos_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cos();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1913830, sign: false });\n    data.append(FP16x16 { mag: 4049104, sign: false });\n    data.append(FP16x16 { mag: 2278925, sign: false });\n    data.append(FP16x16 { mag: 6595486, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 39263, sign: true });\n    data.append(FP16x16 { mag: 32755, sign: false });\n    data.append(FP16x16 { mag: 64011, sign: true });\n    data.append(FP16x16 { mag: 65152, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cos_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cos();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 867902390, sign: false });\n    data.append(FP8x23 { mag: 179014618, sign: false });\n    data.append(FP8x23 { mag: 1037532703, sign: false });\n    data.append(FP8x23 { mag: 37869648, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cos_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8203389, sign: true });\n    data.append(FP8x23 { mag: 6673244, sign: true });\n    data.append(FP8x23 { mag: 3338956, sign: true });\n    data.append(FP8x23 { mag: 1649907, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cosh_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cosh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 111792, sign: false });\n    data.append(FP16x16 { mag: 177968, sign: true });\n    data.append(FP16x16 { mag: 144397, sign: false });\n    data.append(FP16x16 { mag: 151621, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 186369, sign: false });\n    data.append(FP16x16 { mag: 497406, sign: false });\n    data.append(FP16x16 { mag: 300338, sign: false });\n    data.append(FP16x16 { mag: 334535, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cosh_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cosh();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 6347776, sign: false });\n    data.append(FP8x23 { mag: 12366572, sign: false });\n    data.append(FP8x23 { mag: 8513073, sign: true });\n    data.append(FP8x23 { mag: 20925683, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cosh_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 10907148, sign: false });\n    data.append(FP8x23 { mag: 19279307, sign: false });\n    data.append(FP8x23 { mag: 13092000, sign: false });\n    data.append(FP8x23 { mag: 51164820, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_1d_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_1d_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_1d_reverse() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(false), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_1d_reverse_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_1d_reverse_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_2d_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp16x16_2d_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(1, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp16x16_2d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_1d_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_1d_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_1d_reverse() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(false), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_1d_reverse_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_1d_reverse_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_2d_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_fp8x23_2d_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(1, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_fp8x23_2d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_1d_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_1d_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_1d_reverse() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(false), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(15);\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_1d_reverse_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_1d_reverse_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_2d_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(7);\n    data.append(9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i32_2d_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(1, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i32_2d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(4);\n    data.append(9);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_1d_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_1d_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_1d_reverse() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(false), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(15);\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_1d_reverse_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_1d_reverse_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_2d_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(7);\n    data.append(9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_i8_2d_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(1, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_i8_2d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(4);\n    data.append(9);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_default.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_1d_default() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_1d_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_1d_reverse() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(false), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(15);\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse_exclusive.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_1d_reverse_exclusive() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::Some(true), Option::Some(true));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse_exclusive/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_1d_reverse_exclusive/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(14);\n    data.append(12);\n    data.append(9);\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_2d_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(0, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(7);\n    data.append(9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cumsum_u32_2d_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.cumsum(1, Option::None(()), Option::None(()));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/cumsum_u32_2d_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(6);\n    data.append(4);\n    data.append(9);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_depth_to_space_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::depth_to_space(@input_0, 2, 'DCR');\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 172672, sign: false });\n    data.append(FP16x16 { mag: 110976, sign: true });\n    data.append(FP16x16 { mag: 102912, sign: true });\n    data.append(FP16x16 { mag: 146944, sign: true });\n    data.append(FP16x16 { mag: 159232, sign: false });\n    data.append(FP16x16 { mag: 130112, sign: false });\n    data.append(FP16x16 { mag: 106304, sign: false });\n    data.append(FP16x16 { mag: 26832, sign: false });\n    data.append(FP16x16 { mag: 26800, sign: false });\n    data.append(FP16x16 { mag: 172928, sign: true });\n    data.append(FP16x16 { mag: 177280, sign: true });\n    data.append(FP16x16 { mag: 102208, sign: false });\n    data.append(FP16x16 { mag: 11808, sign: true });\n    data.append(FP16x16 { mag: 111488, sign: true });\n    data.append(FP16x16 { mag: 53120, sign: true });\n    data.append(FP16x16 { mag: 165888, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 172672, sign: false });\n    data.append(FP16x16 { mag: 159232, sign: false });\n    data.append(FP16x16 { mag: 110976, sign: true });\n    data.append(FP16x16 { mag: 130112, sign: false });\n    data.append(FP16x16 { mag: 26800, sign: false });\n    data.append(FP16x16 { mag: 11808, sign: true });\n    data.append(FP16x16 { mag: 172928, sign: true });\n    data.append(FP16x16 { mag: 111488, sign: true });\n    data.append(FP16x16 { mag: 102912, sign: true });\n    data.append(FP16x16 { mag: 106304, sign: false });\n    data.append(FP16x16 { mag: 146944, sign: true });\n    data.append(FP16x16 { mag: 26832, sign: false });\n    data.append(FP16x16 { mag: 177280, sign: true });\n    data.append(FP16x16 { mag: 53120, sign: true });\n    data.append(FP16x16 { mag: 102208, sign: false });\n    data.append(FP16x16 { mag: 165888, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::FP8x23NN;\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_depth_to_space_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::depth_to_space(@input_0, 2, 'DCR');\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 2107888, sign: true });\n    data.append(FP8x23 { mag: 18609267, sign: false });\n    data.append(FP8x23 { mag: 21110896, sign: false });\n    data.append(FP8x23 { mag: 20658169, sign: true });\n    data.append(FP8x23 { mag: 15019497, sign: false });\n    data.append(FP8x23 { mag: 18600854, sign: false });\n    data.append(FP8x23 { mag: 17219045, sign: false });\n    data.append(FP8x23 { mag: 5826906, sign: false });\n    data.append(FP8x23 { mag: 1835376, sign: false });\n    data.append(FP8x23 { mag: 3485937, sign: false });\n    data.append(FP8x23 { mag: 23249935, sign: true });\n    data.append(FP8x23 { mag: 428809, sign: false });\n    data.append(FP8x23 { mag: 20996700, sign: false });\n    data.append(FP8x23 { mag: 7565588, sign: true });\n    data.append(FP8x23 { mag: 15581476, sign: true });\n    data.append(FP8x23 { mag: 7136954, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 2107888, sign: true });\n    data.append(FP8x23 { mag: 15019497, sign: false });\n    data.append(FP8x23 { mag: 18609267, sign: false });\n    data.append(FP8x23 { mag: 18600854, sign: false });\n    data.append(FP8x23 { mag: 1835376, sign: false });\n    data.append(FP8x23 { mag: 20996700, sign: false });\n    data.append(FP8x23 { mag: 3485937, sign: false });\n    data.append(FP8x23 { mag: 7565588, sign: true });\n    data.append(FP8x23 { mag: 21110896, sign: false });\n    data.append(FP8x23 { mag: 17219045, sign: false });\n    data.append(FP8x23 { mag: 20658169, sign: true });\n    data.append(FP8x23 { mag: 5826906, sign: false });\n    data.append(FP8x23 { mag: 23249935, sign: true });\n    data.append(FP8x23 { mag: 15581476, sign: true });\n    data.append(FP8x23 { mag: 428809, sign: false });\n    data.append(FP8x23 { mag: 7136954, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::I32NN;\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_depth_to_space_i32() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::depth_to_space(@input_0, 2, 'CRD');\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(2);\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::nn::I8NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_depth_to_space_i8() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::depth_to_space(@input_0, 2, 'DCR');\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-3);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(-1);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_u32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::nn::U32NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_depth_to_space_u32() {\n    let input_0 = input_0::input_0();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::depth_to_space(@input_0, 2, 'CRD');\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4294967293);\n    data.append(4294967294);\n    data.append(2);\n    data.append(4294967293);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(4294967295);\n    data.append(4294967293);\n    data.append(4294967293);\n    data.append(0);\n    data.append(0);\n    data.append(4294967294);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/depth_to_space_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(4294967293);\n    data.append(2);\n    data.append(4294967294);\n    data.append(2);\n    data.append(4294967295);\n    data.append(0);\n    data.append(4294967293);\n    data.append(4294967294);\n    data.append(2);\n    data.append(2);\n    data.append(4294967293);\n    data.append(2);\n    data.append(4294967293);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 4194304, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 / input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/div_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-3);\n    data.append(-3);\n    data.append(-2);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_equal_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/equal_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16Tensor;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_erf_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.erf();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7864, sign: false });\n    data.append(FP16x16 { mag: 108789, sign: true });\n    data.append(FP16x16 { mag: 222822, sign: false });\n    data.append(FP16x16 { mag: 314572, sign: false });\n    data.append(FP16x16 { mag: 176947, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 8831, sign: false });\n    data.append(FP16x16 { mag: 64297, sign: true });\n    data.append(FP16x16 { mag: 65535, sign: false });\n    data.append(FP16x16 { mag: 65535, sign: false });\n    data.append(FP16x16 { mag: 65527, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::FP8x23Tensor;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_erf_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.erf();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1006632, sign: false });\n    data.append(FP8x23 { mag: 13925089, sign: true });\n    data.append(FP8x23 { mag: 28521267, sign: false });\n    data.append(FP8x23 { mag: 40265318, sign: false });\n    data.append(FP8x23 { mag: 22649241, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/erf_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23Tensor;\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1130434, sign: false });\n    data.append(FP8x23 { mag: 8230104, sign: true });\n    data.append(FP8x23 { mag: 8388595, sign: false });\n    data.append(FP8x23 { mag: 8388607, sign: false });\n    data.append(FP8x23 { mag: 8387481, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_exp_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.exp();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 143305, sign: true });\n    data.append(FP16x16 { mag: 34228, sign: false });\n    data.append(FP16x16 { mag: 81407, sign: false });\n    data.append(FP16x16 { mag: 119049, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7359, sign: false });\n    data.append(FP16x16 { mag: 110485, sign: false });\n    data.append(FP16x16 { mag: 226963, sign: false });\n    data.append(FP16x16 { mag: 10655, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_exp_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.exp();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1192320, sign: true });\n    data.append(FP8x23 { mag: 3640877, sign: true });\n    data.append(FP8x23 { mag: 21840452, sign: false });\n    data.append(FP8x23 { mag: 8498896, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/exp_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 7277146, sign: false });\n    data.append(FP8x23 { mag: 5434938, sign: false });\n    data.append(FP8x23 { mag: 113347630, sign: false });\n    data.append(FP8x23 { mag: 23104375, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_elements_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_elements(indices:input_1, axis:Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_elements_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_elements(indices:input_1, axis:Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_elements_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_elements(indices:input_1, axis:Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_negative_indices.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_elements_negative_indices() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_elements(indices:input_1, axis:Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_negative_indices/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_negative_indices/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(-2);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_elements_negative_indices/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_fp16x16_3d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather(indices:input_1, axis:Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_fp16x16_3d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather(indices:input_1, axis:Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_fp16x16_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather(indices:input_1, axis:Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_fp16x16_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp16x16_3d_batch_dims1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp16x16_3d_batch_dims2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_batch_dims2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp16x16_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp16x16_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp8x23_3d_batch_dims1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp8x23_3d_batch_dims2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_batch_dims2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_fp8x23_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_fp8x23_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_i32_3d_batch_dims1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(82);\n    data.append(83);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(88);\n    data.append(89);\n    data.append(90);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(94);\n    data.append(95);\n    data.append(96);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(100);\n    data.append(101);\n    data.append(102);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(106);\n    data.append(107);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(6);\n    data.append(21);\n    data.append(29);\n    data.append(37);\n    data.append(64);\n    data.append(54);\n    data.append(96);\n    data.append(84);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_i32_3d_batch_dims2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_batch_dims2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(9);\n    data.append(15);\n    data.append(19);\n    data.append(25);\n    data.append(31);\n    data.append(36);\n    data.append(45);\n    data.append(50);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_i32_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i32_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_batch_dims1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_i8_3d_batch_dims1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_batch_dims1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_batch_dims1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_batch_dims1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(3);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_i8_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_i8_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_u32_batch_dims1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(82);\n    data.append(83);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(88);\n    data.append(89);\n    data.append(90);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(94);\n    data.append(95);\n    data.append(96);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(100);\n    data.append(101);\n    data.append(102);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(106);\n    data.append(107);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_u32_batch_dims2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(2));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(82);\n    data.append(83);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(88);\n    data.append(89);\n    data.append(90);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(94);\n    data.append(95);\n    data.append(96);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(100);\n    data.append(101);\n    data.append(102);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(106);\n    data.append(107);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_batch_dims2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(15);\n    data.append(24);\n    data.append(40);\n    data.append(51);\n    data.append(61);\n    data.append(75);\n    data.append(84);\n    data.append(100);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_nd_u32_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather_nd(indices: input_1, batch_dims: Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(24);\n    data.append(25);\n    data.append(26);\n    data.append(27);\n    data.append(28);\n    data.append(29);\n    data.append(30);\n    data.append(31);\n    data.append(32);\n    data.append(33);\n    data.append(34);\n    data.append(35);\n    data.append(36);\n    data.append(37);\n    data.append(38);\n    data.append(39);\n    data.append(40);\n    data.append(41);\n    data.append(42);\n    data.append(43);\n    data.append(44);\n    data.append(45);\n    data.append(46);\n    data.append(47);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(60);\n    data.append(61);\n    data.append(62);\n    data.append(63);\n    data.append(64);\n    data.append(65);\n    data.append(66);\n    data.append(67);\n    data.append(68);\n    data.append(69);\n    data.append(70);\n    data.append(71);\n    data.append(72);\n    data.append(73);\n    data.append(74);\n    data.append(75);\n    data.append(76);\n    data.append(77);\n    data.append(78);\n    data.append(79);\n    data.append(80);\n    data.append(81);\n    data.append(82);\n    data.append(83);\n    data.append(84);\n    data.append(85);\n    data.append(86);\n    data.append(87);\n    data.append(88);\n    data.append(89);\n    data.append(90);\n    data.append(91);\n    data.append(92);\n    data.append(93);\n    data.append(94);\n    data.append(95);\n    data.append(96);\n    data.append(97);\n    data.append(98);\n    data.append(99);\n    data.append(100);\n    data.append(101);\n    data.append(102);\n    data.append(103);\n    data.append(104);\n    data.append(105);\n    data.append(106);\n    data.append(107);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32Tensor;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32Tensor;\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_nd_u32_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32Tensor;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    data.append(8);\n    data.append(9);\n    data.append(10);\n    data.append(11);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(12);\n    data.append(13);\n    data.append(14);\n    data.append(15);\n    data.append(16);\n    data.append(17);\n    data.append(18);\n    data.append(19);\n    data.append(20);\n    data.append(21);\n    data.append(22);\n    data.append(23);\n    data.append(48);\n    data.append(49);\n    data.append(50);\n    data.append(51);\n    data.append(52);\n    data.append(53);\n    data.append(54);\n    data.append(55);\n    data.append(56);\n    data.append(57);\n    data.append(58);\n    data.append(59);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_axis.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_negative_axis() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather(indices:input_1, axis:Option::Some(-1));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_axis/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_axis/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_axis/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_indices.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gather_negative_indices() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.gather(indices:input_1, axis:Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_indices/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_indices/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(-9);\n    data.append(-10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gather_negative_indices/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_all_attributes.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_all_attributes() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0,\n        input_1,\n        Option::Some(input_2),\n        Option::Some(FixedTrait::new(16384, false)),\n        Option::Some(FixedTrait::new(22938, false)),\n        true,\n        true\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_all_attributes/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6181, sign: false });\n    data.append(FP16x16 { mag: 64225, sign: false });\n    data.append(FP16x16 { mag: 49893, sign: false });\n    data.append(FP16x16 { mag: 27262, sign: false });\n    data.append(FP16x16 { mag: 59085, sign: false });\n    data.append(FP16x16 { mag: 11503, sign: false });\n    data.append(FP16x16 { mag: 27421, sign: false });\n    data.append(FP16x16 { mag: 1528, sign: false });\n    data.append(FP16x16 { mag: 3846, sign: false });\n    data.append(FP16x16 { mag: 45763, sign: false });\n    data.append(FP16x16 { mag: 23273, sign: false });\n    data.append(FP16x16 { mag: 2087, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_all_attributes/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 23725, sign: false });\n    data.append(FP16x16 { mag: 17645, sign: false });\n    data.append(FP16x16 { mag: 43346, sign: false });\n    data.append(FP16x16 { mag: 23010, sign: false });\n    data.append(FP16x16 { mag: 58499, sign: false });\n    data.append(FP16x16 { mag: 53494, sign: false });\n    data.append(FP16x16 { mag: 8855, sign: false });\n    data.append(FP16x16 { mag: 52549, sign: false });\n    data.append(FP16x16 { mag: 33829, sign: false });\n    data.append(FP16x16 { mag: 64693, sign: false });\n    data.append(FP16x16 { mag: 23894, sign: false });\n    data.append(FP16x16 { mag: 27926, sign: false });\n    data.append(FP16x16 { mag: 3015, sign: false });\n    data.append(FP16x16 { mag: 63591, sign: false });\n    data.append(FP16x16 { mag: 31838, sign: false });\n    data.append(FP16x16 { mag: 6987, sign: false });\n    data.append(FP16x16 { mag: 63224, sign: false });\n    data.append(FP16x16 { mag: 63842, sign: false });\n    data.append(FP16x16 { mag: 27830, sign: false });\n    data.append(FP16x16 { mag: 56137, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_all_attributes/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 39653, sign: false });\n    data.append(FP16x16 { mag: 1049, sign: false });\n    data.append(FP16x16 { mag: 50921, sign: false });\n    data.append(FP16x16 { mag: 49433, sign: false });\n    data.append(FP16x16 { mag: 42267, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_all_attributes/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 24824, sign: false });\n    data.append(FP16x16 { mag: 17409, sign: false });\n    data.append(FP16x16 { mag: 32722, sign: false });\n    data.append(FP16x16 { mag: 28536, sign: false });\n    data.append(FP16x16 { mag: 35635, sign: false });\n    data.append(FP16x16 { mag: 25964, sign: false });\n    data.append(FP16x16 { mag: 31473, sign: false });\n    data.append(FP16x16 { mag: 43310, sign: false });\n    data.append(FP16x16 { mag: 33179, sign: false });\n    data.append(FP16x16 { mag: 49819, sign: false });\n    data.append(FP16x16 { mag: 19988, sign: false });\n    data.append(FP16x16 { mag: 14397, sign: false });\n    data.append(FP16x16 { mag: 27673, sign: false });\n    data.append(FP16x16 { mag: 21189, sign: false });\n    data.append(FP16x16 { mag: 30484, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_alpha.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_alpha() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0,\n        input_1,\n        Option::None(()),\n        Option::Some(FixedTrait::new(32768, false)),\n        Option::None(()),\n        false,\n        false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_alpha/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 56236, sign: false });\n    data.append(FP16x16 { mag: 61356, sign: false });\n    data.append(FP16x16 { mag: 59267, sign: false });\n    data.append(FP16x16 { mag: 7019, sign: false });\n    data.append(FP16x16 { mag: 27265, sign: false });\n    data.append(FP16x16 { mag: 35843, sign: false });\n    data.append(FP16x16 { mag: 12233, sign: false });\n    data.append(FP16x16 { mag: 47311, sign: false });\n    data.append(FP16x16 { mag: 14312, sign: false });\n    data.append(FP16x16 { mag: 3477, sign: false });\n    data.append(FP16x16 { mag: 39621, sign: false });\n    data.append(FP16x16 { mag: 44543, sign: false });\n    data.append(FP16x16 { mag: 56785, sign: false });\n    data.append(FP16x16 { mag: 29674, sign: false });\n    data.append(FP16x16 { mag: 39650, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_alpha/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 13522, sign: false });\n    data.append(FP16x16 { mag: 12888, sign: false });\n    data.append(FP16x16 { mag: 53048, sign: false });\n    data.append(FP16x16 { mag: 29185, sign: false });\n    data.append(FP16x16 { mag: 17013, sign: false });\n    data.append(FP16x16 { mag: 54418, sign: false });\n    data.append(FP16x16 { mag: 48187, sign: false });\n    data.append(FP16x16 { mag: 45789, sign: false });\n    data.append(FP16x16 { mag: 20854, sign: false });\n    data.append(FP16x16 { mag: 49110, sign: false });\n    data.append(FP16x16 { mag: 48981, sign: false });\n    data.append(FP16x16 { mag: 9983, sign: false });\n    data.append(FP16x16 { mag: 4283, sign: false });\n    data.append(FP16x16 { mag: 14740, sign: false });\n    data.append(FP16x16 { mag: 39006, sign: false });\n    data.append(FP16x16 { mag: 38039, sign: false });\n    data.append(FP16x16 { mag: 39666, sign: false });\n    data.append(FP16x16 { mag: 3808, sign: false });\n    data.append(FP16x16 { mag: 34989, sign: false });\n    data.append(FP16x16 { mag: 49693, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_alpha/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 31676, sign: false });\n    data.append(FP16x16 { mag: 54792, sign: false });\n    data.append(FP16x16 { mag: 76833, sign: false });\n    data.append(FP16x16 { mag: 50845, sign: false });\n    data.append(FP16x16 { mag: 14333, sign: false });\n    data.append(FP16x16 { mag: 28040, sign: false });\n    data.append(FP16x16 { mag: 41871, sign: false });\n    data.append(FP16x16 { mag: 21330, sign: false });\n    data.append(FP16x16 { mag: 31873, sign: false });\n    data.append(FP16x16 { mag: 48155, sign: false });\n    data.append(FP16x16 { mag: 73048, sign: false });\n    data.append(FP16x16 { mag: 52353, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_beta.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_beta() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0,\n        input_1,\n        Option::Some(input_2),\n        Option::None(()),\n        Option::Some(FixedTrait::new(32768, false)),\n        false,\n        false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_beta/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(7);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 24460, sign: false });\n    data.append(FP16x16 { mag: 18819, sign: false });\n    data.append(FP16x16 { mag: 5981, sign: false });\n    data.append(FP16x16 { mag: 57425, sign: false });\n    data.append(FP16x16 { mag: 3433, sign: false });\n    data.append(FP16x16 { mag: 51302, sign: false });\n    data.append(FP16x16 { mag: 30317, sign: false });\n    data.append(FP16x16 { mag: 51496, sign: false });\n    data.append(FP16x16 { mag: 49111, sign: false });\n    data.append(FP16x16 { mag: 60422, sign: false });\n    data.append(FP16x16 { mag: 62691, sign: false });\n    data.append(FP16x16 { mag: 49763, sign: false });\n    data.append(FP16x16 { mag: 54999, sign: false });\n    data.append(FP16x16 { mag: 31795, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_beta/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(7);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 61572, sign: false });\n    data.append(FP16x16 { mag: 45985, sign: false });\n    data.append(FP16x16 { mag: 19404, sign: false });\n    data.append(FP16x16 { mag: 4011, sign: false });\n    data.append(FP16x16 { mag: 4824, sign: false });\n    data.append(FP16x16 { mag: 17368, sign: false });\n    data.append(FP16x16 { mag: 26865, sign: false });\n    data.append(FP16x16 { mag: 19036, sign: false });\n    data.append(FP16x16 { mag: 29179, sign: false });\n    data.append(FP16x16 { mag: 27268, sign: false });\n    data.append(FP16x16 { mag: 11806, sign: false });\n    data.append(FP16x16 { mag: 41521, sign: false });\n    data.append(FP16x16 { mag: 51714, sign: false });\n    data.append(FP16x16 { mag: 9380, sign: false });\n    data.append(FP16x16 { mag: 637, sign: false });\n    data.append(FP16x16 { mag: 34737, sign: false });\n    data.append(FP16x16 { mag: 6709, sign: false });\n    data.append(FP16x16 { mag: 51346, sign: false });\n    data.append(FP16x16 { mag: 24730, sign: false });\n    data.append(FP16x16 { mag: 2358, sign: false });\n    data.append(FP16x16 { mag: 12807, sign: false });\n    data.append(FP16x16 { mag: 41228, sign: false });\n    data.append(FP16x16 { mag: 60913, sign: false });\n    data.append(FP16x16 { mag: 15947, sign: false });\n    data.append(FP16x16 { mag: 45496, sign: false });\n    data.append(FP16x16 { mag: 60217, sign: false });\n    data.append(FP16x16 { mag: 51117, sign: false });\n    data.append(FP16x16 { mag: 52177, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_beta/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 30641, sign: false });\n    data.append(FP16x16 { mag: 53716, sign: false });\n    data.append(FP16x16 { mag: 41, sign: false });\n    data.append(FP16x16 { mag: 47279, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_beta/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 119090, sign: false });\n    data.append(FP16x16 { mag: 122540, sign: false });\n    data.append(FP16x16 { mag: 89241, sign: false });\n    data.append(FP16x16 { mag: 101578, sign: false });\n    data.append(FP16x16 { mag: 181607, sign: false });\n    data.append(FP16x16 { mag: 212926, sign: false });\n    data.append(FP16x16 { mag: 141595, sign: false });\n    data.append(FP16x16 { mag: 153059, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_matrix_bias.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_default_matrix_bias() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0, input_1, Option::Some(input_2), Option::None(()), Option::None(()), false, false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_matrix_bias/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 24313, sign: false });\n    data.append(FP16x16 { mag: 15462, sign: false });\n    data.append(FP16x16 { mag: 40752, sign: false });\n    data.append(FP16x16 { mag: 22033, sign: false });\n    data.append(FP16x16 { mag: 30592, sign: false });\n    data.append(FP16x16 { mag: 46888, sign: false });\n    data.append(FP16x16 { mag: 16081, sign: false });\n    data.append(FP16x16 { mag: 12404, sign: false });\n    data.append(FP16x16 { mag: 27033, sign: false });\n    data.append(FP16x16 { mag: 10395, sign: false });\n    data.append(FP16x16 { mag: 12042, sign: false });\n    data.append(FP16x16 { mag: 35690, sign: false });\n    data.append(FP16x16 { mag: 7033, sign: false });\n    data.append(FP16x16 { mag: 606, sign: false });\n    data.append(FP16x16 { mag: 2994, sign: false });\n    data.append(FP16x16 { mag: 20651, sign: false });\n    data.append(FP16x16 { mag: 46099, sign: false });\n    data.append(FP16x16 { mag: 5768, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_matrix_bias/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 60818, sign: false });\n    data.append(FP16x16 { mag: 59979, sign: false });\n    data.append(FP16x16 { mag: 36912, sign: false });\n    data.append(FP16x16 { mag: 46433, sign: false });\n    data.append(FP16x16 { mag: 3745, sign: false });\n    data.append(FP16x16 { mag: 29174, sign: false });\n    data.append(FP16x16 { mag: 3555, sign: false });\n    data.append(FP16x16 { mag: 3092, sign: false });\n    data.append(FP16x16 { mag: 60956, sign: false });\n    data.append(FP16x16 { mag: 37111, sign: false });\n    data.append(FP16x16 { mag: 28077, sign: false });\n    data.append(FP16x16 { mag: 9904, sign: false });\n    data.append(FP16x16 { mag: 17752, sign: false });\n    data.append(FP16x16 { mag: 51564, sign: false });\n    data.append(FP16x16 { mag: 16512, sign: false });\n    data.append(FP16x16 { mag: 18193, sign: false });\n    data.append(FP16x16 { mag: 62859, sign: false });\n    data.append(FP16x16 { mag: 28772, sign: false });\n    data.append(FP16x16 { mag: 42434, sign: false });\n    data.append(FP16x16 { mag: 12591, sign: false });\n    data.append(FP16x16 { mag: 24303, sign: false });\n    data.append(FP16x16 { mag: 19725, sign: false });\n    data.append(FP16x16 { mag: 14636, sign: false });\n    data.append(FP16x16 { mag: 57618, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_matrix_bias/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 62000, sign: false });\n    data.append(FP16x16 { mag: 64560, sign: false });\n    data.append(FP16x16 { mag: 23724, sign: false });\n    data.append(FP16x16 { mag: 53487, sign: false });\n    data.append(FP16x16 { mag: 44710, sign: false });\n    data.append(FP16x16 { mag: 54528, sign: false });\n    data.append(FP16x16 { mag: 39071, sign: false });\n    data.append(FP16x16 { mag: 3222, sign: false });\n    data.append(FP16x16 { mag: 22465, sign: false });\n    data.append(FP16x16 { mag: 56410, sign: false });\n    data.append(FP16x16 { mag: 11578, sign: false });\n    data.append(FP16x16 { mag: 57495, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_matrix_bias/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176052, sign: false });\n    data.append(FP16x16 { mag: 161653, sign: false });\n    data.append(FP16x16 { mag: 91548, sign: false });\n    data.append(FP16x16 { mag: 130822, sign: false });\n    data.append(FP16x16 { mag: 113090, sign: false });\n    data.append(FP16x16 { mag: 114286, sign: false });\n    data.append(FP16x16 { mag: 78771, sign: false });\n    data.append(FP16x16 { mag: 55867, sign: false });\n    data.append(FP16x16 { mag: 83763, sign: false });\n    data.append(FP16x16 { mag: 103037, sign: false });\n    data.append(FP16x16 { mag: 53197, sign: false });\n    data.append(FP16x16 { mag: 82622, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_no_bias.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_default_no_bias() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0, input_1, Option::None(()), Option::None(()), Option::None(()), false, false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_no_bias/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 22549, sign: false });\n    data.append(FP16x16 { mag: 29927, sign: false });\n    data.append(FP16x16 { mag: 5624, sign: false });\n    data.append(FP16x16 { mag: 43955, sign: false });\n    data.append(FP16x16 { mag: 38785, sign: false });\n    data.append(FP16x16 { mag: 14854, sign: false });\n    data.append(FP16x16 { mag: 4727, sign: false });\n    data.append(FP16x16 { mag: 24506, sign: false });\n    data.append(FP16x16 { mag: 29042, sign: false });\n    data.append(FP16x16 { mag: 35461, sign: false });\n    data.append(FP16x16 { mag: 53031, sign: false });\n    data.append(FP16x16 { mag: 2059, sign: false });\n    data.append(FP16x16 { mag: 45485, sign: false });\n    data.append(FP16x16 { mag: 54450, sign: false });\n    data.append(FP16x16 { mag: 13645, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_no_bias/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 21264, sign: false });\n    data.append(FP16x16 { mag: 40785, sign: false });\n    data.append(FP16x16 { mag: 3120, sign: false });\n    data.append(FP16x16 { mag: 5275, sign: false });\n    data.append(FP16x16 { mag: 38611, sign: false });\n    data.append(FP16x16 { mag: 30792, sign: false });\n    data.append(FP16x16 { mag: 9186, sign: false });\n    data.append(FP16x16 { mag: 7839, sign: false });\n    data.append(FP16x16 { mag: 61914, sign: false });\n    data.append(FP16x16 { mag: 53606, sign: false });\n    data.append(FP16x16 { mag: 5497, sign: false });\n    data.append(FP16x16 { mag: 49410, sign: false });\n    data.append(FP16x16 { mag: 33114, sign: false });\n    data.append(FP16x16 { mag: 20996, sign: false });\n    data.append(FP16x16 { mag: 11300, sign: false });\n    data.append(FP16x16 { mag: 19630, sign: false });\n    data.append(FP16x16 { mag: 14015, sign: false });\n    data.append(FP16x16 { mag: 25247, sign: false });\n    data.append(FP16x16 { mag: 1692, sign: false });\n    data.append(FP16x16 { mag: 43693, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_no_bias/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 60767, sign: false });\n    data.append(FP16x16 { mag: 61719, sign: false });\n    data.append(FP16x16 { mag: 14321, sign: false });\n    data.append(FP16x16 { mag: 48660, sign: false });\n    data.append(FP16x16 { mag: 53016, sign: false });\n    data.append(FP16x16 { mag: 54477, sign: false });\n    data.append(FP16x16 { mag: 9349, sign: false });\n    data.append(FP16x16 { mag: 52579, sign: false });\n    data.append(FP16x16 { mag: 91823, sign: false });\n    data.append(FP16x16 { mag: 93878, sign: false });\n    data.append(FP16x16 { mag: 16370, sign: false });\n    data.append(FP16x16 { mag: 64215, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_vector_bias.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_default_vector_bias() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0, input_1, Option::Some(input_2), Option::None(()), Option::None(()), false, false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_vector_bias/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(7);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 26141, sign: false });\n    data.append(FP16x16 { mag: 65210, sign: false });\n    data.append(FP16x16 { mag: 44238, sign: false });\n    data.append(FP16x16 { mag: 15740, sign: false });\n    data.append(FP16x16 { mag: 27732, sign: false });\n    data.append(FP16x16 { mag: 54749, sign: false });\n    data.append(FP16x16 { mag: 23531, sign: false });\n    data.append(FP16x16 { mag: 12333, sign: false });\n    data.append(FP16x16 { mag: 3048, sign: false });\n    data.append(FP16x16 { mag: 50642, sign: false });\n    data.append(FP16x16 { mag: 50567, sign: false });\n    data.append(FP16x16 { mag: 20553, sign: false });\n    data.append(FP16x16 { mag: 14789, sign: false });\n    data.append(FP16x16 { mag: 48807, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_vector_bias/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(7);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 2655, sign: false });\n    data.append(FP16x16 { mag: 27005, sign: false });\n    data.append(FP16x16 { mag: 28670, sign: false });\n    data.append(FP16x16 { mag: 49392, sign: false });\n    data.append(FP16x16 { mag: 39855, sign: false });\n    data.append(FP16x16 { mag: 37109, sign: false });\n    data.append(FP16x16 { mag: 58515, sign: false });\n    data.append(FP16x16 { mag: 40588, sign: false });\n    data.append(FP16x16 { mag: 59543, sign: false });\n    data.append(FP16x16 { mag: 58423, sign: false });\n    data.append(FP16x16 { mag: 200, sign: false });\n    data.append(FP16x16 { mag: 57208, sign: false });\n    data.append(FP16x16 { mag: 10967, sign: false });\n    data.append(FP16x16 { mag: 21516, sign: false });\n    data.append(FP16x16 { mag: 4197, sign: false });\n    data.append(FP16x16 { mag: 2419, sign: false });\n    data.append(FP16x16 { mag: 15655, sign: false });\n    data.append(FP16x16 { mag: 33193, sign: false });\n    data.append(FP16x16 { mag: 40116, sign: false });\n    data.append(FP16x16 { mag: 14725, sign: false });\n    data.append(FP16x16 { mag: 37526, sign: false });\n    data.append(FP16x16 { mag: 4098, sign: false });\n    data.append(FP16x16 { mag: 45267, sign: false });\n    data.append(FP16x16 { mag: 11802, sign: false });\n    data.append(FP16x16 { mag: 53114, sign: false });\n    data.append(FP16x16 { mag: 53602, sign: false });\n    data.append(FP16x16 { mag: 23812, sign: false });\n    data.append(FP16x16 { mag: 50714, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_vector_bias/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 43991, sign: false });\n    data.append(FP16x16 { mag: 30927, sign: false });\n    data.append(FP16x16 { mag: 35649, sign: false });\n    data.append(FP16x16 { mag: 3973, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_default_vector_bias/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 184581, sign: false });\n    data.append(FP16x16 { mag: 159946, sign: false });\n    data.append(FP16x16 { mag: 169795, sign: false });\n    data.append(FP16x16 { mag: 137561, sign: false });\n    data.append(FP16x16 { mag: 153754, sign: false });\n    data.append(FP16x16 { mag: 150739, sign: false });\n    data.append(FP16x16 { mag: 87691, sign: false });\n    data.append(FP16x16 { mag: 106281, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeA.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_transposeA() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0, input_1, Option::None(()), Option::None(()), Option::None(()), true, false\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeA/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 25712, sign: false });\n    data.append(FP16x16 { mag: 33518, sign: false });\n    data.append(FP16x16 { mag: 55900, sign: false });\n    data.append(FP16x16 { mag: 17835, sign: false });\n    data.append(FP16x16 { mag: 55991, sign: false });\n    data.append(FP16x16 { mag: 49824, sign: false });\n    data.append(FP16x16 { mag: 10885, sign: false });\n    data.append(FP16x16 { mag: 46382, sign: false });\n    data.append(FP16x16 { mag: 12037, sign: false });\n    data.append(FP16x16 { mag: 54001, sign: false });\n    data.append(FP16x16 { mag: 28270, sign: false });\n    data.append(FP16x16 { mag: 53624, sign: false });\n    data.append(FP16x16 { mag: 8973, sign: false });\n    data.append(FP16x16 { mag: 57376, sign: false });\n    data.append(FP16x16 { mag: 59443, sign: false });\n    data.append(FP16x16 { mag: 20787, sign: false });\n    data.append(FP16x16 { mag: 21410, sign: false });\n    data.append(FP16x16 { mag: 30468, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeA/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 38056, sign: false });\n    data.append(FP16x16 { mag: 35209, sign: false });\n    data.append(FP16x16 { mag: 55369, sign: false });\n    data.append(FP16x16 { mag: 64248, sign: false });\n    data.append(FP16x16 { mag: 16398, sign: false });\n    data.append(FP16x16 { mag: 58129, sign: false });\n    data.append(FP16x16 { mag: 46239, sign: false });\n    data.append(FP16x16 { mag: 56435, sign: false });\n    data.append(FP16x16 { mag: 25984, sign: false });\n    data.append(FP16x16 { mag: 64809, sign: false });\n    data.append(FP16x16 { mag: 65020, sign: false });\n    data.append(FP16x16 { mag: 8759, sign: false });\n    data.append(FP16x16 { mag: 50946, sign: false });\n    data.append(FP16x16 { mag: 29640, sign: false });\n    data.append(FP16x16 { mag: 12257, sign: false });\n    data.append(FP16x16 { mag: 26776, sign: false });\n    data.append(FP16x16 { mag: 20618, sign: false });\n    data.append(FP16x16 { mag: 15242, sign: false });\n    data.append(FP16x16 { mag: 5560, sign: false });\n    data.append(FP16x16 { mag: 3669, sign: false });\n    data.append(FP16x16 { mag: 64019, sign: false });\n    data.append(FP16x16 { mag: 9851, sign: false });\n    data.append(FP16x16 { mag: 26388, sign: false });\n    data.append(FP16x16 { mag: 62343, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeA/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 88819, sign: false });\n    data.append(FP16x16 { mag: 70034, sign: false });\n    data.append(FP16x16 { mag: 64340, sign: false });\n    data.append(FP16x16 { mag: 84362, sign: false });\n    data.append(FP16x16 { mag: 112807, sign: false });\n    data.append(FP16x16 { mag: 142888, sign: false });\n    data.append(FP16x16 { mag: 132618, sign: false });\n    data.append(FP16x16 { mag: 122405, sign: false });\n    data.append(FP16x16 { mag: 139852, sign: false });\n    data.append(FP16x16 { mag: 128789, sign: false });\n    data.append(FP16x16 { mag: 121667, sign: false });\n    data.append(FP16x16 { mag: 153539, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeB.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_gemm_transposeB() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = NNTrait::gemm(\n        input_0, input_1, Option::None(()), Option::None(()), Option::None(()), false, true\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeB/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 43014, sign: false });\n    data.append(FP16x16 { mag: 16802, sign: false });\n    data.append(FP16x16 { mag: 52318, sign: false });\n    data.append(FP16x16 { mag: 40979, sign: false });\n    data.append(FP16x16 { mag: 277, sign: false });\n    data.append(FP16x16 { mag: 29333, sign: false });\n    data.append(FP16x16 { mag: 26593, sign: false });\n    data.append(FP16x16 { mag: 41294, sign: false });\n    data.append(FP16x16 { mag: 47646, sign: false });\n    data.append(FP16x16 { mag: 2148, sign: false });\n    data.append(FP16x16 { mag: 24564, sign: false });\n    data.append(FP16x16 { mag: 18370, sign: false });\n    data.append(FP16x16 { mag: 63747, sign: false });\n    data.append(FP16x16 { mag: 10833, sign: false });\n    data.append(FP16x16 { mag: 29301, sign: false });\n    data.append(FP16x16 { mag: 20991, sign: false });\n    data.append(FP16x16 { mag: 28040, sign: false });\n    data.append(FP16x16 { mag: 133, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeB/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 9020, sign: false });\n    data.append(FP16x16 { mag: 1508, sign: false });\n    data.append(FP16x16 { mag: 17596, sign: false });\n    data.append(FP16x16 { mag: 15725, sign: false });\n    data.append(FP16x16 { mag: 17557, sign: false });\n    data.append(FP16x16 { mag: 6286, sign: false });\n    data.append(FP16x16 { mag: 33993, sign: false });\n    data.append(FP16x16 { mag: 24966, sign: false });\n    data.append(FP16x16 { mag: 18648, sign: false });\n    data.append(FP16x16 { mag: 1482, sign: false });\n    data.append(FP16x16 { mag: 56402, sign: false });\n    data.append(FP16x16 { mag: 11205, sign: false });\n    data.append(FP16x16 { mag: 59749, sign: false });\n    data.append(FP16x16 { mag: 32628, sign: false });\n    data.append(FP16x16 { mag: 51145, sign: false });\n    data.append(FP16x16 { mag: 37477, sign: false });\n    data.append(FP16x16 { mag: 14287, sign: false });\n    data.append(FP16x16 { mag: 18084, sign: false });\n    data.append(FP16x16 { mag: 13969, sign: false });\n    data.append(FP16x16 { mag: 52688, sign: false });\n    data.append(FP16x16 { mag: 40536, sign: false });\n    data.append(FP16x16 { mag: 36430, sign: false });\n    data.append(FP16x16 { mag: 17009, sign: false });\n    data.append(FP16x16 { mag: 50657, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/gemm_transposeB/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 33076, sign: false });\n    data.append(FP16x16 { mag: 49782, sign: false });\n    data.append(FP16x16 { mag: 120002, sign: false });\n    data.append(FP16x16 { mag: 100565, sign: false });\n    data.append(FP16x16 { mag: 26262, sign: false });\n    data.append(FP16x16 { mag: 67414, sign: false });\n    data.append(FP16x16 { mag: 93642, sign: false });\n    data.append(FP16x16 { mag: 90109, sign: false });\n    data.append(FP16x16 { mag: 29452, sign: false });\n    data.append(FP16x16 { mag: 70161, sign: false });\n    data.append(FP16x16 { mag: 104534, sign: false });\n    data.append(FP16x16 { mag: 59471, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-2);\n    data.append(-1);\n    data.append(0);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(2);\n    data.append(-3);\n    data.append(2);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(-3);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-2);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(-1);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_equal_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater_equal(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_equal_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(-3);\n    data.append(-1);\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(-2);\n    data.append(-1);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(0);\n    data.append(-3);\n    data.append(1);\n    data.append(0);\n    data.append(-2);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(2);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-3);\n    data.append(-3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_greater_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.greater(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/greater_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(@input_0, @input_1, Option::None, Option::None, Option::None);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(4);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(6);\n    shape.append(6);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(6);\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 9830, sign: false });\n    data.append(FP16x16 { mag: 36044, sign: false });\n    data.append(FP16x16 { mag: 62259, sign: false });\n    data.append(FP16x16 { mag: 88473, sign: false });\n    data.append(FP16x16 { mag: 49152, sign: false });\n    data.append(FP16x16 { mag: 39321, sign: false });\n    data.append(FP16x16 { mag: 98303, sign: false });\n    data.append(FP16x16 { mag: 150732, sign: false });\n    data.append(FP16x16 { mag: 203161, sign: false });\n    data.append(FP16x16 { mag: 255590, sign: false });\n    data.append(FP16x16 { mag: 137625, sign: false });\n    data.append(FP16x16 { mag: 144179, sign: false });\n    data.append(FP16x16 { mag: 308019, sign: false });\n    data.append(FP16x16 { mag: 360448, sign: false });\n    data.append(FP16x16 { mag: 412876, sign: false });\n    data.append(FP16x16 { mag: 465305, sign: false });\n    data.append(FP16x16 { mag: 242483, sign: false });\n    data.append(FP16x16 { mag: 249036, sign: false });\n    data.append(FP16x16 { mag: 517734, sign: false });\n    data.append(FP16x16 { mag: 570163, sign: false });\n    data.append(FP16x16 { mag: 622592, sign: false });\n    data.append(FP16x16 { mag: 675020, sign: false });\n    data.append(FP16x16 { mag: 347340, sign: false });\n    data.append(FP16x16 { mag: 353894, sign: false });\n    data.append(FP16x16 { mag: 727449, sign: false });\n    data.append(FP16x16 { mag: 779878, sign: false });\n    data.append(FP16x16 { mag: 832307, sign: false });\n    data.append(FP16x16 { mag: 884736, sign: false });\n    data.append(FP16x16 { mag: 452198, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 403046, sign: false });\n    data.append(FP16x16 { mag: 429260, sign: false });\n    data.append(FP16x16 { mag: 455475, sign: false });\n    data.append(FP16x16 { mag: 481689, sign: false });\n    data.append(FP16x16 { mag: 245760, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_aligncorners.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_aligncorners() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(@input_0, @input_1, Option::Some(1), Option::None, Option::None);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_aligncorners/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_aligncorners/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_aligncorners/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 81920, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 163840, sign: false });\n    data.append(FP16x16 { mag: 163840, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 245760, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_cubic.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_cubic() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(\n        @input_0, @input_1, Option::Some(0), Option::Some(MODE::CUBIC), Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_cubic/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_cubic/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_cubic/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 9216, sign: true });\n    data.append(FP16x16 { mag: 25088, sign: false });\n    data.append(FP16x16 { mag: 115051, sign: false });\n    data.append(FP16x16 { mag: 194560, sign: false });\n    data.append(FP16x16 { mag: 194560, sign: false });\n    data.append(FP16x16 { mag: 115051, sign: false });\n    data.append(FP16x16 { mag: 337152, sign: false });\n    data.append(FP16x16 { mag: 91136, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_nearest() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(\n        @input_0, @input_1, Option::Some(0), Option::Some(MODE::NEAREST), Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest_aligncorner.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_nearest_aligncorner() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(\n        @input_0, @input_1, Option::Some(1), Option::Some(MODE::NEAREST), Option::None\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest_aligncorner/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest_aligncorner/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 32768, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_nearest_aligncorner/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_border.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::PADDING_MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_padding_border() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(\n        @input_0, @input_1, Option::None, Option::None, Option::Some(PADDING_MODE::BORDER)\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_border/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_border/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_border/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_reflection.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::PADDING_MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_padding_reflection() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(\n        @input_0, @input_1, Option::None, Option::None, Option::Some(PADDING_MODE::REFLECTION)\n    );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_reflection/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_reflection/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_reflection/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 163840, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 163840, sign: false });\n    data.append(FP16x16 { mag: 163840, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 163840, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_zeros.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::functional::grid_sample::PADDING_MODE;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_grid_sample_padding_zeros() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = NNTrait::grid_sample(@input_0, @input_1, Option::None, Option::None, Option::None);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_zeros/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(3);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_zeros/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 13107, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/grid_sample_padding_zeros/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 111411, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hamming_window_fp16x16.cairo",
        "content": "mod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hamming_window_fp16x16() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::hamming_window(FP16x16 { mag: 655360, sign: false }, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hamming_window_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 5696, sign: false });\n    data.append(FP16x16 { mag: 12688, sign: false });\n    data.append(FP16x16 { mag: 30400, sign: false });\n    data.append(FP16x16 { mag: 50560, sign: false });\n    data.append(FP16x16 { mag: 63712, sign: false });\n    data.append(FP16x16 { mag: 63744, sign: false });\n    data.append(FP16x16 { mag: 50624, sign: false });\n    data.append(FP16x16 { mag: 30432, sign: false });\n    data.append(FP16x16 { mag: 12752, sign: false });\n    data.append(FP16x16 { mag: 5696, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hamming_window_fp8x23.cairo",
        "content": "mod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::numbers::{FixedTrait, FP8x23};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hamming_window_fp8x23() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::hamming_window(FP8x23 { mag: 33554432, sign: false }, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hamming_window_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 729444, sign: false });\n    data.append(FP8x23 { mag: 6473817, sign: false });\n    data.append(FP8x23 { mag: 6473817, sign: false });\n    data.append(FP8x23 { mag: 729444, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hann_window_fp16x16.cairo",
        "content": "mod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hann_window_fp16x16() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::hann_window(FP16x16 { mag: 655360, sign: false }, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hann_window_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7656, sign: false });\n    data.append(FP16x16 { mag: 27056, sign: false });\n    data.append(FP16x16 { mag: 49120, sign: false });\n    data.append(FP16x16 { mag: 63552, sign: false });\n    data.append(FP16x16 { mag: 63552, sign: false });\n    data.append(FP16x16 { mag: 49184, sign: false });\n    data.append(FP16x16 { mag: 27104, sign: false });\n    data.append(FP16x16 { mag: 7732, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hann_window_fp8x23.cairo",
        "content": "mod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::{FixedTrait, FP8x23};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hann_window_fp8x23() {\n    let z_0 = output_0::output_0();\n\n    let y_0 = TensorTrait::hann_window(FP8x23 { mag: 33554432, sign: false }, Option::Some(0));\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hann_window_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 6291455, sign: false });\n    data.append(FP8x23 { mag: 6291456, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hard_sigmoid_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::hard_sigmoid(\n        @input_0, @FixedTrait::new(13107, false), @FixedTrait::new(32768, false)\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 163137, sign: false });\n    data.append(FP16x16 { mag: 109300, sign: true });\n    data.append(FP16x16 { mag: 28237, sign: false });\n    data.append(FP16x16 { mag: 20376, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65395, sign: false });\n    data.append(FP16x16 { mag: 10907, sign: false });\n    data.append(FP16x16 { mag: 38415, sign: false });\n    data.append(FP16x16 { mag: 28692, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::nn::FP8x23NN;\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_hard_sigmoid_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::hard_sigmoid(\n        @input_0, @FixedTrait::new(1677721, false), @FixedTrait::new(4194304, false)\n    );\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1488696, sign: true });\n    data.append(FP8x23 { mag: 14193978, sign: true });\n    data.append(FP8x23 { mag: 23668532, sign: true });\n    data.append(FP8x23 { mag: 19142362, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/hard_sigmoid_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3896564, sign: false });\n    data.append(FP8x23 { mag: 1355508, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8022776, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_identity_fP16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.identity();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 4, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 3, sign: false });\n    data.append(FP16x16 { mag: 4, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_identity_fP8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.identity();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_fP8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 3, sign: false });\n    data.append(FP8x23 { mag: 4, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_identity_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.identity();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_identity_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.identity();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_u32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_identity_u32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.identity();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/identity_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_inf_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::None, Option::None);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 78643, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FixedTrait::NEG_INF());\n    data.append(FP16x16 { mag: 183500, sign: false });\n    data.append(FixedTrait::POS_INF());\n    data.append(FixedTrait::NEG_INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_inf_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::None, Option::None);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 10066329, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FixedTrait::NEG_INF());\n    data.append(FP8x23 { mag: 23488102, sign: false });\n    data.append(FixedTrait::POS_INF());\n    data.append(FixedTrait::NEG_INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_inf_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::None, Option::None);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_inf_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::None, Option::None);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_u32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_inf_u32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::None, Option::None);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF());\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_inf_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::BoolTensor;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_nan_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_nan(@input_0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 78643, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FixedTrait::NaN());\n    data.append(FP16x16 { mag: 183500, sign: false });\n    data.append(FixedTrait::NaN());\n    data.append(FixedTrait::NaN());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_nan_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_nan(@input_0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 10066329, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FixedTrait::NaN());\n    data.append(FP8x23 { mag: 23488102, sign: false });\n    data.append(FixedTrait::NaN());\n    data.append(FixedTrait::NaN());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_nan_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(true);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_neg_inf_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FixedTrait::POS_INF());\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FixedTrait::NEG_INF());\n    data.append(FixedTrait::POS_INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_neg_inf_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FixedTrait::POS_INF());\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FixedTrait::NEG_INF());\n    data.append(FixedTrait::POS_INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_neg_inf_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_neg_inf_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(1), Option::Some(0));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_neg_inf_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_pos_inf_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 4294967295, sign: false });\n    data.append(FP16x16 { mag: 2, sign: false });\n    data.append(FP16x16 { mag: 4294967295, sign: true });\n    data.append(FP16x16 { mag: 4294967295, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_pos_inf_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 4294967295, sign: false });\n    data.append(FP8x23 { mag: 2, sign: false });\n    data.append(FP8x23 { mag: 4294967295, sign: true });\n    data.append(FP8x23 { mag: 4294967295, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_pos_inf_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_is_pos_inf_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::is_inf(@input_0, Option::Some(0), Option::Some(1));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::{NumberTrait};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(NumberTrait::INF());\n    data.append(8);\n    data.append(NumberTrait::INF() * -1);\n    data.append(NumberTrait::INF());\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/is_pos_inf_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    data.append(false);\n    data.append(false);\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod input_3;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_label_encoder_fp16x16_3d_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let input_3 = input_3::input_3();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0\n        .label_encoder(\n            default_list: Option::None,\n            default_tensor: Option::Some(input_1),\n            keys: Option::None,\n            keys_tensor: Option::Some(input_2),\n            values: Option::None,\n            values_tensor: Option::Some(input_3)\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default/input_3.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_3() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp16x16_3d_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(9);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod input_3;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_label_encoder_fp8x23_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let input_3 = input_3::input_3();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0\n        .label_encoder(\n            default_list: Option::None,\n            default_tensor: Option::Some(input_1),\n            keys: Option::None,\n            keys_tensor: Option::Some(input_2),\n            values: Option::None,\n            values_tensor: Option::Some(input_3)\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default/input_3.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_3() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_fp8x23_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod input_3;\nmod output_0;\n\n\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_label_encoder_i32_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let input_3 = input_3::input_3();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0\n        .label_encoder(\n            default_list: Option::None,\n            default_tensor: Option::Some(input_1),\n            keys: Option::None,\n            keys_tensor: Option::Some(input_2),\n            values: Option::None,\n            values_tensor: Option::Some(input_3)\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n\n    let mut data = ArrayTrait::new();\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default/input_3.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_3() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(55);\n    data.append(66);\n    data.append(77);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i32_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(99);\n    data.append(55);\n    data.append(66);\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(77);\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod input_3;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_label_encoder_i8_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let input_3 = input_3::input_3();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0\n        .label_encoder(\n            default_list: Option::None,\n            default_tensor: Option::Some(input_1),\n            keys: Option::None,\n            keys_tensor: Option::Some(input_2),\n            values: Option::None,\n            values_tensor: Option::Some(input_3)\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n\n    let mut data = ArrayTrait::new();\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default/input_3.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_3() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(55);\n    data.append(66);\n    data.append(77);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_i8_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(99);\n    data.append(55);\n    data.append(66);\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(77);\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod input_3;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_label_encoder_u32_default() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let input_3 = input_3::input_3();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0\n        .label_encoder(\n            default_list: Option::None,\n            default_tensor: Option::Some(input_1),\n            keys: Option::None,\n            keys_tensor: Option::Some(input_2),\n            values: Option::None,\n            values_tensor: Option::Some(input_3)\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(7);\n    data.append(8);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n\n    let mut data = ArrayTrait::new();\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(6);\n    data.append(7);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default/input_3.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_3() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(55);\n    data.append(66);\n    data.append(77);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/label_encoder_u32_default/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(11);\n\n    let mut data = ArrayTrait::new();\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(99);\n    data.append(55);\n    data.append(66);\n    data.append(11);\n    data.append(22);\n    data.append(99);\n    data.append(77);\n    data.append(99);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis0_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis0_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(0),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis0_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis0_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 41116, sign: true });\n    data.append(FP16x16 { mag: 33345, sign: false });\n    data.append(FP16x16 { mag: 16035, sign: true });\n    data.append(FP16x16 { mag: 66324, sign: true });\n    data.append(FP16x16 { mag: 65521, sign: false });\n    data.append(FP16x16 { mag: 44567, sign: false });\n    data.append(FP16x16 { mag: 12343, sign: true });\n    data.append(FP16x16 { mag: 22182, sign: false });\n    data.append(FP16x16 { mag: 68006, sign: false });\n    data.append(FP16x16 { mag: 18564, sign: true });\n    data.append(FP16x16 { mag: 159060, sign: true });\n    data.append(FP16x16 { mag: 41449, sign: false });\n    data.append(FP16x16 { mag: 21502, sign: true });\n    data.append(FP16x16 { mag: 23583, sign: true });\n    data.append(FP16x16 { mag: 10004, sign: true });\n    data.append(FP16x16 { mag: 111077, sign: true });\n    data.append(FP16x16 { mag: 51023, sign: true });\n    data.append(FP16x16 { mag: 27845, sign: false });\n    data.append(FP16x16 { mag: 548, sign: false });\n    data.append(FP16x16 { mag: 51940, sign: true });\n    data.append(FP16x16 { mag: 4135, sign: false });\n    data.append(FP16x16 { mag: 77167, sign: false });\n    data.append(FP16x16 { mag: 27642, sign: true });\n    data.append(FP16x16 { mag: 50063, sign: true });\n    data.append(FP16x16 { mag: 60555, sign: true });\n    data.append(FP16x16 { mag: 34923, sign: true });\n    data.append(FP16x16 { mag: 66185, sign: false });\n    data.append(FP16x16 { mag: 1845, sign: true });\n    data.append(FP16x16 { mag: 63811, sign: true });\n    data.append(FP16x16 { mag: 30524, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis0_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 53067, sign: false });\n    data.append(FP16x16 { mag: 12598, sign: false });\n    data.append(FP16x16 { mag: 22071, sign: true });\n    data.append(FP16x16 { mag: 185160, sign: true });\n    data.append(FP16x16 { mag: 71946, sign: true });\n    data.append(FP16x16 { mag: 109757, sign: false });\n    data.append(FP16x16 { mag: 53829, sign: true });\n    data.append(FP16x16 { mag: 61215, sign: true });\n    data.append(FP16x16 { mag: 112863, sign: false });\n    data.append(FP16x16 { mag: 64576, sign: true });\n    data.append(FP16x16 { mag: 14400, sign: true });\n    data.append(FP16x16 { mag: 47376, sign: false });\n    data.append(FP16x16 { mag: 42132, sign: false });\n    data.append(FP16x16 { mag: 15521, sign: true });\n    data.append(FP16x16 { mag: 19564, sign: false });\n    data.append(FP16x16 { mag: 17481, sign: true });\n    data.append(FP16x16 { mag: 1740, sign: true });\n    data.append(FP16x16 { mag: 111657, sign: false });\n    data.append(FP16x16 { mag: 112934, sign: false });\n    data.append(FP16x16 { mag: 19870, sign: true });\n    data.append(FP16x16 { mag: 122950, sign: true });\n    data.append(FP16x16 { mag: 92754, sign: false });\n    data.append(FP16x16 { mag: 3247, sign: false });\n    data.append(FP16x16 { mag: 74346, sign: true });\n    data.append(FP16x16 { mag: 98767, sign: false });\n    data.append(FP16x16 { mag: 8702, sign: true });\n    data.append(FP16x16 { mag: 40643, sign: true });\n    data.append(FP16x16 { mag: 138135, sign: true });\n    data.append(FP16x16 { mag: 22240, sign: false });\n    data.append(FP16x16 { mag: 1595, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis0_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 142574, sign: false });\n    data.append(FP16x16 { mag: 81046, sign: false });\n    data.append(FP16x16 { mag: 23127, sign: true });\n    data.append(FP16x16 { mag: 168203, sign: true });\n    data.append(FP16x16 { mag: 63557, sign: true });\n    data.append(FP16x16 { mag: 59277, sign: false });\n    data.append(FP16x16 { mag: 42308, sign: true });\n    data.append(FP16x16 { mag: 44993, sign: true });\n    data.append(FP16x16 { mag: 55077, sign: false });\n    data.append(FP16x16 { mag: 76461, sign: true });\n    data.append(FP16x16 { mag: 108813, sign: false });\n    data.append(FP16x16 { mag: 50883, sign: false });\n    data.append(FP16x16 { mag: 27205, sign: false });\n    data.append(FP16x16 { mag: 7326, sign: false });\n    data.append(FP16x16 { mag: 23613, sign: false });\n    data.append(FP16x16 { mag: 27157, sign: false });\n    data.append(FP16x16 { mag: 5637, sign: true });\n    data.append(FP16x16 { mag: 90697, sign: false });\n    data.append(FP16x16 { mag: 112821, sign: false });\n    data.append(FP16x16 { mag: 91044, sign: true });\n    data.append(FP16x16 { mag: 123095, sign: true });\n    data.append(FP16x16 { mag: 204883, sign: false });\n    data.append(FP16x16 { mag: 9454, sign: false });\n    data.append(FP16x16 { mag: 55780, sign: true });\n    data.append(FP16x16 { mag: 159695, sign: false });\n    data.append(FP16x16 { mag: 6840, sign: true });\n    data.append(FP16x16 { mag: 119261, sign: false });\n    data.append(FP16x16 { mag: 139557, sign: true });\n    data.append(FP16x16 { mag: 38352, sign: false });\n    data.append(FP16x16 { mag: 8088, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis1_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis1_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(1),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis1_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis1_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 19493, sign: true });\n    data.append(FP16x16 { mag: 6259, sign: true });\n    data.append(FP16x16 { mag: 35118, sign: true });\n    data.append(FP16x16 { mag: 2823, sign: false });\n    data.append(FP16x16 { mag: 34210, sign: false });\n    data.append(FP16x16 { mag: 7012, sign: false });\n    data.append(FP16x16 { mag: 52120, sign: true });\n    data.append(FP16x16 { mag: 51293, sign: true });\n    data.append(FP16x16 { mag: 23181, sign: false });\n    data.append(FP16x16 { mag: 54682, sign: false });\n    data.append(FP16x16 { mag: 34168, sign: false });\n    data.append(FP16x16 { mag: 54896, sign: false });\n    data.append(FP16x16 { mag: 94902, sign: false });\n    data.append(FP16x16 { mag: 35974, sign: true });\n    data.append(FP16x16 { mag: 96972, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis1_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 37910, sign: true });\n    data.append(FP16x16 { mag: 18888, sign: true });\n    data.append(FP16x16 { mag: 42890, sign: false });\n    data.append(FP16x16 { mag: 47165, sign: false });\n    data.append(FP16x16 { mag: 63877, sign: true });\n    data.append(FP16x16 { mag: 88993, sign: true });\n    data.append(FP16x16 { mag: 41540, sign: true });\n    data.append(FP16x16 { mag: 68862, sign: true });\n    data.append(FP16x16 { mag: 21940, sign: false });\n    data.append(FP16x16 { mag: 5420, sign: true });\n    data.append(FP16x16 { mag: 101888, sign: true });\n    data.append(FP16x16 { mag: 13856, sign: false });\n    data.append(FP16x16 { mag: 55772, sign: false });\n    data.append(FP16x16 { mag: 21988, sign: false });\n    data.append(FP16x16 { mag: 63379, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis1_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 251, sign: true });\n    data.append(FP16x16 { mag: 32754, sign: true });\n    data.append(FP16x16 { mag: 33505, sign: false });\n    data.append(FP16x16 { mag: 47029, sign: false });\n    data.append(FP16x16 { mag: 52651, sign: true });\n    data.append(FP16x16 { mag: 95360, sign: true });\n    data.append(FP16x16 { mag: 4402, sign: true });\n    data.append(FP16x16 { mag: 116033, sign: true });\n    data.append(FP16x16 { mag: 7323, sign: false });\n    data.append(FP16x16 { mag: 39982, sign: false });\n    data.append(FP16x16 { mag: 120917, sign: true });\n    data.append(FP16x16 { mag: 29534, sign: false });\n    data.append(FP16x16 { mag: 139597, sign: false });\n    data.append(FP16x16 { mag: 48872, sign: false });\n    data.append(FP16x16 { mag: 44543, sign: false });\n    data.append(FP16x16 { mag: 25225, sign: true });\n    data.append(FP16x16 { mag: 18016, sign: true });\n    data.append(FP16x16 { mag: 78919, sign: false });\n    data.append(FP16x16 { mag: 45917, sign: false });\n    data.append(FP16x16 { mag: 21307, sign: true });\n    data.append(FP16x16 { mag: 90805, sign: true });\n    data.append(FP16x16 { mag: 111010, sign: true });\n    data.append(FP16x16 { mag: 45210, sign: true });\n    data.append(FP16x16 { mag: 7624, sign: false });\n    data.append(FP16x16 { mag: 76340, sign: true });\n    data.append(FP16x16 { mag: 111388, sign: true });\n    data.append(FP16x16 { mag: 143559, sign: false });\n    data.append(FP16x16 { mag: 112995, sign: false });\n    data.append(FP16x16 { mag: 39651, sign: false });\n    data.append(FP16x16 { mag: 74850, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis2_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis2_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(2),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis2_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis2_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 39349, sign: true });\n    data.append(FP16x16 { mag: 89048, sign: false });\n    data.append(FP16x16 { mag: 26497, sign: false });\n    data.append(FP16x16 { mag: 76393, sign: false });\n    data.append(FP16x16 { mag: 89741, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis2_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7433, sign: true });\n    data.append(FP16x16 { mag: 119887, sign: true });\n    data.append(FP16x16 { mag: 18199, sign: true });\n    data.append(FP16x16 { mag: 19666, sign: true });\n    data.append(FP16x16 { mag: 12164, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis2_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 53879, sign: false });\n    data.append(FP16x16 { mag: 15631, sign: false });\n    data.append(FP16x16 { mag: 16210, sign: true });\n    data.append(FP16x16 { mag: 31819, sign: true });\n    data.append(FP16x16 { mag: 1365, sign: false });\n    data.append(FP16x16 { mag: 30042, sign: false });\n    data.append(FP16x16 { mag: 184179, sign: true });\n    data.append(FP16x16 { mag: 13663, sign: false });\n    data.append(FP16x16 { mag: 67432, sign: true });\n    data.append(FP16x16 { mag: 86296, sign: true });\n    data.append(FP16x16 { mag: 22179, sign: false });\n    data.append(FP16x16 { mag: 71910, sign: true });\n    data.append(FP16x16 { mag: 20350, sign: false });\n    data.append(FP16x16 { mag: 99451, sign: true });\n    data.append(FP16x16 { mag: 29814, sign: false });\n    data.append(FP16x16 { mag: 13673, sign: false });\n    data.append(FP16x16 { mag: 113125, sign: true });\n    data.append(FP16x16 { mag: 44314, sign: true });\n    data.append(FP16x16 { mag: 41557, sign: true });\n    data.append(FP16x16 { mag: 143319, sign: true });\n    data.append(FP16x16 { mag: 7507, sign: true });\n    data.append(FP16x16 { mag: 34257, sign: false });\n    data.append(FP16x16 { mag: 23982, sign: true });\n    data.append(FP16x16 { mag: 49325, sign: true });\n    data.append(FP16x16 { mag: 113251, sign: false });\n    data.append(FP16x16 { mag: 19969, sign: false });\n    data.append(FP16x16 { mag: 39099, sign: false });\n    data.append(FP16x16 { mag: 14713, sign: true });\n    data.append(FP16x16 { mag: 88159, sign: true });\n    data.append(FP16x16 { mag: 41236, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_1_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis_negative_1_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(-1),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_1_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_1_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 95136, sign: true });\n    data.append(FP16x16 { mag: 46210, sign: false });\n    data.append(FP16x16 { mag: 95007, sign: false });\n    data.append(FP16x16 { mag: 13976, sign: false });\n    data.append(FP16x16 { mag: 59189, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_1_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 55378, sign: false });\n    data.append(FP16x16 { mag: 119900, sign: false });\n    data.append(FP16x16 { mag: 48314, sign: true });\n    data.append(FP16x16 { mag: 9945, sign: false });\n    data.append(FP16x16 { mag: 75929, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_1_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 203617, sign: false });\n    data.append(FP16x16 { mag: 190225, sign: false });\n    data.append(FP16x16 { mag: 41182, sign: true });\n    data.append(FP16x16 { mag: 7721, sign: false });\n    data.append(FP16x16 { mag: 83051, sign: false });\n    data.append(FP16x16 { mag: 145985, sign: false });\n    data.append(FP16x16 { mag: 86537, sign: false });\n    data.append(FP16x16 { mag: 65930, sign: false });\n    data.append(FP16x16 { mag: 1205, sign: false });\n    data.append(FP16x16 { mag: 140868, sign: false });\n    data.append(FP16x16 { mag: 126973, sign: false });\n    data.append(FP16x16 { mag: 144796, sign: false });\n    data.append(FP16x16 { mag: 89906, sign: false });\n    data.append(FP16x16 { mag: 4652, sign: true });\n    data.append(FP16x16 { mag: 64288, sign: false });\n    data.append(FP16x16 { mag: 106407, sign: false });\n    data.append(FP16x16 { mag: 123409, sign: false });\n    data.append(FP16x16 { mag: 141950, sign: true });\n    data.append(FP16x16 { mag: 5939, sign: false });\n    data.append(FP16x16 { mag: 178478, sign: false });\n    data.append(FP16x16 { mag: 55197, sign: false });\n    data.append(FP16x16 { mag: 199890, sign: false });\n    data.append(FP16x16 { mag: 69050, sign: true });\n    data.append(FP16x16 { mag: 4518, sign: false });\n    data.append(FP16x16 { mag: 9257, sign: false });\n    data.append(FP16x16 { mag: 121631, sign: false });\n    data.append(FP16x16 { mag: 202403, sign: false });\n    data.append(FP16x16 { mag: 35816, sign: true });\n    data.append(FP16x16 { mag: 2586, sign: true });\n    data.append(FP16x16 { mag: 56755, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_2_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis_negative_2_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(-2),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_2_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_2_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 69151, sign: false });\n    data.append(FP16x16 { mag: 49647, sign: true });\n    data.append(FP16x16 { mag: 25308, sign: false });\n    data.append(FP16x16 { mag: 49767, sign: true });\n    data.append(FP16x16 { mag: 17913, sign: false });\n    data.append(FP16x16 { mag: 10090, sign: false });\n    data.append(FP16x16 { mag: 4364, sign: true });\n    data.append(FP16x16 { mag: 41827, sign: false });\n    data.append(FP16x16 { mag: 12848, sign: true });\n    data.append(FP16x16 { mag: 137417, sign: false });\n    data.append(FP16x16 { mag: 70720, sign: true });\n    data.append(FP16x16 { mag: 76109, sign: false });\n    data.append(FP16x16 { mag: 66590, sign: true });\n    data.append(FP16x16 { mag: 50658, sign: false });\n    data.append(FP16x16 { mag: 107949, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_2_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 18752, sign: false });\n    data.append(FP16x16 { mag: 19935, sign: false });\n    data.append(FP16x16 { mag: 20182, sign: true });\n    data.append(FP16x16 { mag: 65500, sign: false });\n    data.append(FP16x16 { mag: 3405, sign: true });\n    data.append(FP16x16 { mag: 43973, sign: true });\n    data.append(FP16x16 { mag: 45323, sign: true });\n    data.append(FP16x16 { mag: 24495, sign: false });\n    data.append(FP16x16 { mag: 27923, sign: true });\n    data.append(FP16x16 { mag: 149149, sign: false });\n    data.append(FP16x16 { mag: 3341, sign: true });\n    data.append(FP16x16 { mag: 17501, sign: false });\n    data.append(FP16x16 { mag: 38949, sign: true });\n    data.append(FP16x16 { mag: 85674, sign: false });\n    data.append(FP16x16 { mag: 3401, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_2_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 114840, sign: true });\n    data.append(FP16x16 { mag: 90046, sign: true });\n    data.append(FP16x16 { mag: 13419, sign: true });\n    data.append(FP16x16 { mag: 67891, sign: false });\n    data.append(FP16x16 { mag: 2473, sign: false });\n    data.append(FP16x16 { mag: 53134, sign: true });\n    data.append(FP16x16 { mag: 42214, sign: true });\n    data.append(FP16x16 { mag: 62961, sign: false });\n    data.append(FP16x16 { mag: 19822, sign: true });\n    data.append(FP16x16 { mag: 263248, sign: false });\n    data.append(FP16x16 { mag: 36043, sign: false });\n    data.append(FP16x16 { mag: 39237, sign: false });\n    data.append(FP16x16 { mag: 97766, sign: true });\n    data.append(FP16x16 { mag: 47816, sign: false });\n    data.append(FP16x16 { mag: 17567, sign: true });\n    data.append(FP16x16 { mag: 26247, sign: true });\n    data.append(FP16x16 { mag: 26852, sign: false });\n    data.append(FP16x16 { mag: 46147, sign: true });\n    data.append(FP16x16 { mag: 87501, sign: false });\n    data.append(FP16x16 { mag: 18885, sign: false });\n    data.append(FP16x16 { mag: 46581, sign: true });\n    data.append(FP16x16 { mag: 51141, sign: true });\n    data.append(FP16x16 { mag: 5208, sign: false });\n    data.append(FP16x16 { mag: 19988, sign: true });\n    data.append(FP16x16 { mag: 29072, sign: true });\n    data.append(FP16x16 { mag: 16318, sign: false });\n    data.append(FP16x16 { mag: 197324, sign: false });\n    data.append(FP16x16 { mag: 79100, sign: true });\n    data.append(FP16x16 { mag: 60801, sign: false });\n    data.append(FP16x16 { mag: 16170, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_3_epsilon.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_3d_axis_negative_3_epsilon() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1,\n            Option::Some(@input_2),\n            Option::Some(-3),\n            Option::Some(FixedTrait::new(6554, false)),\n            Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_3_epsilon/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 176084, sign: true });\n    data.append(FP16x16 { mag: 134870, sign: false });\n    data.append(FP16x16 { mag: 11194, sign: true });\n    data.append(FP16x16 { mag: 34834, sign: true });\n    data.append(FP16x16 { mag: 6625, sign: true });\n    data.append(FP16x16 { mag: 99311, sign: true });\n    data.append(FP16x16 { mag: 84659, sign: true });\n    data.append(FP16x16 { mag: 37723, sign: false });\n    data.append(FP16x16 { mag: 78508, sign: true });\n    data.append(FP16x16 { mag: 31024, sign: false });\n    data.append(FP16x16 { mag: 72988, sign: true });\n    data.append(FP16x16 { mag: 9818, sign: true });\n    data.append(FP16x16 { mag: 34996, sign: false });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 45795, sign: true });\n    data.append(FP16x16 { mag: 45583, sign: true });\n    data.append(FP16x16 { mag: 10423, sign: true });\n    data.append(FP16x16 { mag: 71376, sign: true });\n    data.append(FP16x16 { mag: 31238, sign: true });\n    data.append(FP16x16 { mag: 84702, sign: false });\n    data.append(FP16x16 { mag: 18617, sign: true });\n    data.append(FP16x16 { mag: 90788, sign: false });\n    data.append(FP16x16 { mag: 32546, sign: true });\n    data.append(FP16x16 { mag: 43302, sign: true });\n    data.append(FP16x16 { mag: 90009, sign: true });\n    data.append(FP16x16 { mag: 19958, sign: true });\n    data.append(FP16x16 { mag: 161585, sign: false });\n    data.append(FP16x16 { mag: 40607, sign: false });\n    data.append(FP16x16 { mag: 34601, sign: true });\n    data.append(FP16x16 { mag: 7286, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_3_epsilon/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1396, sign: true });\n    data.append(FP16x16 { mag: 91738, sign: false });\n    data.append(FP16x16 { mag: 22354, sign: false });\n    data.append(FP16x16 { mag: 40925, sign: true });\n    data.append(FP16x16 { mag: 70890, sign: false });\n    data.append(FP16x16 { mag: 64955, sign: false });\n    data.append(FP16x16 { mag: 25324, sign: false });\n    data.append(FP16x16 { mag: 25230, sign: false });\n    data.append(FP16x16 { mag: 142906, sign: true });\n    data.append(FP16x16 { mag: 68962, sign: true });\n    data.append(FP16x16 { mag: 20940, sign: false });\n    data.append(FP16x16 { mag: 107327, sign: true });\n    data.append(FP16x16 { mag: 52698, sign: false });\n    data.append(FP16x16 { mag: 17542, sign: true });\n    data.append(FP16x16 { mag: 125557, sign: false });\n    data.append(FP16x16 { mag: 3282, sign: false });\n    data.append(FP16x16 { mag: 32752, sign: false });\n    data.append(FP16x16 { mag: 38674, sign: false });\n    data.append(FP16x16 { mag: 16699, sign: false });\n    data.append(FP16x16 { mag: 20489, sign: false });\n    data.append(FP16x16 { mag: 24738, sign: true });\n    data.append(FP16x16 { mag: 21702, sign: false });\n    data.append(FP16x16 { mag: 32990, sign: true });\n    data.append(FP16x16 { mag: 73557, sign: false });\n    data.append(FP16x16 { mag: 24845, sign: false });\n    data.append(FP16x16 { mag: 48972, sign: false });\n    data.append(FP16x16 { mag: 23684, sign: false });\n    data.append(FP16x16 { mag: 168361, sign: false });\n    data.append(FP16x16 { mag: 32800, sign: false });\n    data.append(FP16x16 { mag: 66808, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_3_epsilon/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 47175, sign: false });\n    data.append(FP16x16 { mag: 48068, sign: false });\n    data.append(FP16x16 { mag: 72715, sign: true });\n    data.append(FP16x16 { mag: 40805, sign: true });\n    data.append(FP16x16 { mag: 97387, sign: true });\n    data.append(FP16x16 { mag: 52917, sign: false });\n    data.append(FP16x16 { mag: 16842, sign: false });\n    data.append(FP16x16 { mag: 48741, sign: false });\n    data.append(FP16x16 { mag: 114144, sign: false });\n    data.append(FP16x16 { mag: 5783, sign: false });\n    data.append(FP16x16 { mag: 24320, sign: true });\n    data.append(FP16x16 { mag: 1477, sign: true });\n    data.append(FP16x16 { mag: 101470, sign: false });\n    data.append(FP16x16 { mag: 126422, sign: true });\n    data.append(FP16x16 { mag: 5733, sign: true });\n    data.append(FP16x16 { mag: 97314, sign: true });\n    data.append(FP16x16 { mag: 65247, sign: false });\n    data.append(FP16x16 { mag: 3443, sign: true });\n    data.append(FP16x16 { mag: 16494, sign: true });\n    data.append(FP16x16 { mag: 107377, sign: true });\n    data.append(FP16x16 { mag: 63019, sign: false });\n    data.append(FP16x16 { mag: 2523, sign: false });\n    data.append(FP16x16 { mag: 111859, sign: true });\n    data.append(FP16x16 { mag: 26857, sign: true });\n    data.append(FP16x16 { mag: 19691, sign: true });\n    data.append(FP16x16 { mag: 83436, sign: true });\n    data.append(FP16x16 { mag: 176674, sign: true });\n    data.append(FP16x16 { mag: 21073, sign: true });\n    data.append(FP16x16 { mag: 114640, sign: false });\n    data.append(FP16x16 { mag: 26239, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_3d_axis_negative_3_epsilon/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 50215, sign: false });\n    data.append(FP16x16 { mag: 236376, sign: false });\n    data.append(FP16x16 { mag: 71242, sign: true });\n    data.append(FP16x16 { mag: 30342, sign: true });\n    data.append(FP16x16 { mag: 88310, sign: true });\n    data.append(FP16x16 { mag: 20655, sign: true });\n    data.append(FP16x16 { mag: 6794, sign: true });\n    data.append(FP16x16 { mag: 67191, sign: false });\n    data.append(FP16x16 { mag: 235574, sign: false });\n    data.append(FP16x16 { mag: 38362, sign: true });\n    data.append(FP16x16 { mag: 40541, sign: true });\n    data.append(FP16x16 { mag: 10558, sign: true });\n    data.append(FP16x16 { mag: 138052, sign: false });\n    data.append(FP16x16 { mag: 109426, sign: true });\n    data.append(FP16x16 { mag: 56553, sign: true });\n    data.append(FP16x16 { mag: 98633, sign: true });\n    data.append(FP16x16 { mag: 67749, sign: false });\n    data.append(FP16x16 { mag: 32554, sign: true });\n    data.append(FP16x16 { mag: 19947, sign: true });\n    data.append(FP16x16 { mag: 79300, sign: true });\n    data.append(FP16x16 { mag: 63887, sign: false });\n    data.append(FP16x16 { mag: 34057, sign: false });\n    data.append(FP16x16 { mag: 104451, sign: true });\n    data.append(FP16x16 { mag: 54136, sign: true });\n    data.append(FP16x16 { mag: 44689, sign: true });\n    data.append(FP16x16 { mag: 86047, sign: true });\n    data.append(FP16x16 { mag: 119451, sign: true });\n    data.append(FP16x16 { mag: 108647, sign: false });\n    data.append(FP16x16 { mag: 106358, sign: false });\n    data.append(FP16x16 { mag: 47435, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 50439, sign: true });\n    data.append(FP16x16 { mag: 80584, sign: false });\n    data.append(FP16x16 { mag: 108804, sign: false });\n    data.append(FP16x16 { mag: 64736, sign: true });\n    data.append(FP16x16 { mag: 35989, sign: false });\n    data.append(FP16x16 { mag: 83918, sign: false });\n    data.append(FP16x16 { mag: 80462, sign: true });\n    data.append(FP16x16 { mag: 43318, sign: false });\n    data.append(FP16x16 { mag: 65651, sign: true });\n    data.append(FP16x16 { mag: 11331, sign: true });\n    data.append(FP16x16 { mag: 25254, sign: true });\n    data.append(FP16x16 { mag: 62677, sign: false });\n    data.append(FP16x16 { mag: 8412, sign: false });\n    data.append(FP16x16 { mag: 64067, sign: true });\n    data.append(FP16x16 { mag: 11592, sign: true });\n    data.append(FP16x16 { mag: 10557, sign: false });\n    data.append(FP16x16 { mag: 33540, sign: true });\n    data.append(FP16x16 { mag: 50007, sign: true });\n    data.append(FP16x16 { mag: 66942, sign: true });\n    data.append(FP16x16 { mag: 24781, sign: true });\n    data.append(FP16x16 { mag: 70618, sign: true });\n    data.append(FP16x16 { mag: 91944, sign: false });\n    data.append(FP16x16 { mag: 25130, sign: false });\n    data.append(FP16x16 { mag: 70069, sign: true });\n    data.append(FP16x16 { mag: 19429, sign: false });\n    data.append(FP16x16 { mag: 17607, sign: true });\n    data.append(FP16x16 { mag: 20059, sign: true });\n    data.append(FP16x16 { mag: 30637, sign: false });\n    data.append(FP16x16 { mag: 110305, sign: true });\n    data.append(FP16x16 { mag: 47227, sign: true });\n    data.append(FP16x16 { mag: 52701, sign: false });\n    data.append(FP16x16 { mag: 113586, sign: true });\n    data.append(FP16x16 { mag: 28893, sign: false });\n    data.append(FP16x16 { mag: 19309, sign: true });\n    data.append(FP16x16 { mag: 9704, sign: true });\n    data.append(FP16x16 { mag: 56793, sign: false });\n    data.append(FP16x16 { mag: 44072, sign: false });\n    data.append(FP16x16 { mag: 2660, sign: true });\n    data.append(FP16x16 { mag: 29401, sign: true });\n    data.append(FP16x16 { mag: 36736, sign: true });\n    data.append(FP16x16 { mag: 86250, sign: false });\n    data.append(FP16x16 { mag: 38971, sign: true });\n    data.append(FP16x16 { mag: 138249, sign: true });\n    data.append(FP16x16 { mag: 36048, sign: false });\n    data.append(FP16x16 { mag: 37452, sign: false });\n    data.append(FP16x16 { mag: 23181, sign: true });\n    data.append(FP16x16 { mag: 35955, sign: true });\n    data.append(FP16x16 { mag: 51748, sign: true });\n    data.append(FP16x16 { mag: 57097, sign: true });\n    data.append(FP16x16 { mag: 91645, sign: true });\n    data.append(FP16x16 { mag: 727, sign: true });\n    data.append(FP16x16 { mag: 26384, sign: true });\n    data.append(FP16x16 { mag: 1331, sign: false });\n    data.append(FP16x16 { mag: 98672, sign: false });\n    data.append(FP16x16 { mag: 82596, sign: false });\n    data.append(FP16x16 { mag: 100984, sign: true });\n    data.append(FP16x16 { mag: 88934, sign: true });\n    data.append(FP16x16 { mag: 110736, sign: false });\n    data.append(FP16x16 { mag: 106050, sign: true });\n    data.append(FP16x16 { mag: 43286, sign: true });\n    data.append(FP16x16 { mag: 114427, sign: false });\n    data.append(FP16x16 { mag: 26160, sign: false });\n    data.append(FP16x16 { mag: 19914, sign: true });\n    data.append(FP16x16 { mag: 168031, sign: false });\n    data.append(FP16x16 { mag: 70834, sign: true });\n    data.append(FP16x16 { mag: 62785, sign: false });\n    data.append(FP16x16 { mag: 20711, sign: true });\n    data.append(FP16x16 { mag: 150814, sign: true });\n    data.append(FP16x16 { mag: 19909, sign: true });\n    data.append(FP16x16 { mag: 4360, sign: true });\n    data.append(FP16x16 { mag: 38550, sign: false });\n    data.append(FP16x16 { mag: 155210, sign: false });\n    data.append(FP16x16 { mag: 49387, sign: true });\n    data.append(FP16x16 { mag: 48606, sign: false });\n    data.append(FP16x16 { mag: 26297, sign: false });\n    data.append(FP16x16 { mag: 5832, sign: true });\n    data.append(FP16x16 { mag: 67019, sign: false });\n    data.append(FP16x16 { mag: 108552, sign: false });\n    data.append(FP16x16 { mag: 38302, sign: true });\n    data.append(FP16x16 { mag: 67467, sign: false });\n    data.append(FP16x16 { mag: 123524, sign: false });\n    data.append(FP16x16 { mag: 38110, sign: true });\n    data.append(FP16x16 { mag: 49459, sign: true });\n    data.append(FP16x16 { mag: 89977, sign: false });\n    data.append(FP16x16 { mag: 3116, sign: false });\n    data.append(FP16x16 { mag: 139868, sign: true });\n    data.append(FP16x16 { mag: 3777, sign: false });\n    data.append(FP16x16 { mag: 93508, sign: false });\n    data.append(FP16x16 { mag: 18473, sign: true });\n    data.append(FP16x16 { mag: 9749, sign: false });\n    data.append(FP16x16 { mag: 69280, sign: false });\n    data.append(FP16x16 { mag: 31261, sign: true });\n    data.append(FP16x16 { mag: 70810, sign: true });\n    data.append(FP16x16 { mag: 53719, sign: true });\n    data.append(FP16x16 { mag: 25490, sign: false });\n    data.append(FP16x16 { mag: 76561, sign: true });\n    data.append(FP16x16 { mag: 87810, sign: true });\n    data.append(FP16x16 { mag: 54546, sign: true });\n    data.append(FP16x16 { mag: 11956, sign: false });\n    data.append(FP16x16 { mag: 53981, sign: true });\n    data.append(FP16x16 { mag: 48734, sign: false });\n    data.append(FP16x16 { mag: 81861, sign: true });\n    data.append(FP16x16 { mag: 91276, sign: false });\n    data.append(FP16x16 { mag: 104233, sign: false });\n    data.append(FP16x16 { mag: 52396, sign: false });\n    data.append(FP16x16 { mag: 37016, sign: false });\n    data.append(FP16x16 { mag: 39784, sign: false });\n    data.append(FP16x16 { mag: 16087, sign: true });\n    data.append(FP16x16 { mag: 22464, sign: true });\n    data.append(FP16x16 { mag: 98432, sign: true });\n    data.append(FP16x16 { mag: 120832, sign: true });\n    data.append(FP16x16 { mag: 25665, sign: true });\n    data.append(FP16x16 { mag: 23338, sign: true });\n    data.append(FP16x16 { mag: 18801, sign: false });\n    data.append(FP16x16 { mag: 22675, sign: false });\n    data.append(FP16x16 { mag: 79634, sign: true });\n    data.append(FP16x16 { mag: 95608, sign: true });\n    data.append(FP16x16 { mag: 73767, sign: false });\n    data.append(FP16x16 { mag: 20235, sign: false });\n    data.append(FP16x16 { mag: 19535, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 4256, sign: true });\n    data.append(FP16x16 { mag: 12347, sign: true });\n    data.append(FP16x16 { mag: 12223, sign: true });\n    data.append(FP16x16 { mag: 35664, sign: false });\n    data.append(FP16x16 { mag: 47729, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 31681, sign: true });\n    data.append(FP16x16 { mag: 39712, sign: false });\n    data.append(FP16x16 { mag: 111813, sign: true });\n    data.append(FP16x16 { mag: 73292, sign: false });\n    data.append(FP16x16 { mag: 69974, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 27222, sign: true });\n    data.append(FP16x16 { mag: 29264, sign: false });\n    data.append(FP16x16 { mag: 127142, sign: true });\n    data.append(FP16x16 { mag: 28560, sign: false });\n    data.append(FP16x16 { mag: 60351, sign: true });\n    data.append(FP16x16 { mag: 37788, sign: true });\n    data.append(FP16x16 { mag: 54370, sign: false });\n    data.append(FP16x16 { mag: 121438, sign: true });\n    data.append(FP16x16 { mag: 39380, sign: false });\n    data.append(FP16x16 { mag: 74002, sign: true });\n    data.append(FP16x16 { mag: 29712, sign: true });\n    data.append(FP16x16 { mag: 19392, sign: false });\n    data.append(FP16x16 { mag: 116026, sign: true });\n    data.append(FP16x16 { mag: 23611, sign: false });\n    data.append(FP16x16 { mag: 76413, sign: true });\n    data.append(FP16x16 { mag: 38774, sign: true });\n    data.append(FP16x16 { mag: 39995, sign: false });\n    data.append(FP16x16 { mag: 103821, sign: true });\n    data.append(FP16x16 { mag: 26838, sign: false });\n    data.append(FP16x16 { mag: 55050, sign: true });\n    data.append(FP16x16 { mag: 26907, sign: true });\n    data.append(FP16x16 { mag: 21300, sign: false });\n    data.append(FP16x16 { mag: 116914, sign: true });\n    data.append(FP16x16 { mag: 33608, sign: false });\n    data.append(FP16x16 { mag: 54427, sign: true });\n    data.append(FP16x16 { mag: 33093, sign: true });\n    data.append(FP16x16 { mag: 36271, sign: false });\n    data.append(FP16x16 { mag: 128658, sign: true });\n    data.append(FP16x16 { mag: 13438, sign: false });\n    data.append(FP16x16 { mag: 84790, sign: true });\n    data.append(FP16x16 { mag: 36528, sign: true });\n    data.append(FP16x16 { mag: 61679, sign: false });\n    data.append(FP16x16 { mag: 120628, sign: true });\n    data.append(FP16x16 { mag: 68843, sign: false });\n    data.append(FP16x16 { mag: 67883, sign: true });\n    data.append(FP16x16 { mag: 37338, sign: true });\n    data.append(FP16x16 { mag: 27445, sign: false });\n    data.append(FP16x16 { mag: 108887, sign: true });\n    data.append(FP16x16 { mag: 39593, sign: false });\n    data.append(FP16x16 { mag: 124310, sign: true });\n    data.append(FP16x16 { mag: 36554, sign: true });\n    data.append(FP16x16 { mag: 45301, sign: false });\n    data.append(FP16x16 { mag: 90795, sign: true });\n    data.append(FP16x16 { mag: 91286, sign: false });\n    data.append(FP16x16 { mag: 45037, sign: true });\n    data.append(FP16x16 { mag: 36959, sign: true });\n    data.append(FP16x16 { mag: 31204, sign: false });\n    data.append(FP16x16 { mag: 111906, sign: true });\n    data.append(FP16x16 { mag: 65334, sign: false });\n    data.append(FP16x16 { mag: 151771, sign: true });\n    data.append(FP16x16 { mag: 28963, sign: true });\n    data.append(FP16x16 { mag: 53952, sign: false });\n    data.append(FP16x16 { mag: 104513, sign: true });\n    data.append(FP16x16 { mag: 121643, sign: false });\n    data.append(FP16x16 { mag: 20658, sign: true });\n    data.append(FP16x16 { mag: 28787, sign: true });\n    data.append(FP16x16 { mag: 46278, sign: false });\n    data.append(FP16x16 { mag: 135335, sign: true });\n    data.append(FP16x16 { mag: 46819, sign: false });\n    data.append(FP16x16 { mag: 68555, sign: true });\n    data.append(FP16x16 { mag: 35143, sign: true });\n    data.append(FP16x16 { mag: 42180, sign: false });\n    data.append(FP16x16 { mag: 102903, sign: true });\n    data.append(FP16x16 { mag: 124252, sign: false });\n    data.append(FP16x16 { mag: 132667, sign: true });\n    data.append(FP16x16 { mag: 37173, sign: true });\n    data.append(FP16x16 { mag: 38662, sign: false });\n    data.append(FP16x16 { mag: 89894, sign: true });\n    data.append(FP16x16 { mag: 76738, sign: false });\n    data.append(FP16x16 { mag: 54649, sign: true });\n    data.append(FP16x16 { mag: 31336, sign: true });\n    data.append(FP16x16 { mag: 18722, sign: false });\n    data.append(FP16x16 { mag: 94412, sign: true });\n    data.append(FP16x16 { mag: 75879, sign: false });\n    data.append(FP16x16 { mag: 82768, sign: true });\n    data.append(FP16x16 { mag: 28065, sign: true });\n    data.append(FP16x16 { mag: 33448, sign: false });\n    data.append(FP16x16 { mag: 127469, sign: true });\n    data.append(FP16x16 { mag: 21429, sign: false });\n    data.append(FP16x16 { mag: 45363, sign: true });\n    data.append(FP16x16 { mag: 37692, sign: true });\n    data.append(FP16x16 { mag: 51120, sign: false });\n    data.append(FP16x16 { mag: 98514, sign: true });\n    data.append(FP16x16 { mag: 106370, sign: false });\n    data.append(FP16x16 { mag: 85630, sign: true });\n    data.append(FP16x16 { mag: 24340, sign: true });\n    data.append(FP16x16 { mag: 37405, sign: false });\n    data.append(FP16x16 { mag: 128694, sign: true });\n    data.append(FP16x16 { mag: 69394, sign: false });\n    data.append(FP16x16 { mag: 57263, sign: true });\n    data.append(FP16x16 { mag: 38335, sign: true });\n    data.append(FP16x16 { mag: 44227, sign: false });\n    data.append(FP16x16 { mag: 98068, sign: true });\n    data.append(FP16x16 { mag: 44884, sign: false });\n    data.append(FP16x16 { mag: 35454, sign: true });\n    data.append(FP16x16 { mag: 28683, sign: true });\n    data.append(FP16x16 { mag: 52423, sign: false });\n    data.append(FP16x16 { mag: 110980, sign: true });\n    data.append(FP16x16 { mag: 139406, sign: false });\n    data.append(FP16x16 { mag: 72447, sign: true });\n    data.append(FP16x16 { mag: 32053, sign: true });\n    data.append(FP16x16 { mag: 63056, sign: false });\n    data.append(FP16x16 { mag: 120760, sign: true });\n    data.append(FP16x16 { mag: 106395, sign: false });\n    data.append(FP16x16 { mag: 63149, sign: true });\n    data.append(FP16x16 { mag: 35826, sign: true });\n    data.append(FP16x16 { mag: 27007, sign: false });\n    data.append(FP16x16 { mag: 110829, sign: true });\n    data.append(FP16x16 { mag: 65907, sign: false });\n    data.append(FP16x16 { mag: 151855, sign: true });\n    data.append(FP16x16 { mag: 23850, sign: true });\n    data.append(FP16x16 { mag: 39710, sign: false });\n    data.append(FP16x16 { mag: 112364, sign: true });\n    data.append(FP16x16 { mag: 103957, sign: false });\n    data.append(FP16x16 { mag: 25360, sign: true });\n    data.append(FP16x16 { mag: 27646, sign: true });\n    data.append(FP16x16 { mag: 54560, sign: false });\n    data.append(FP16x16 { mag: 130110, sign: true });\n    data.append(FP16x16 { mag: 96250, sign: false });\n    data.append(FP16x16 { mag: 69503, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 50439, sign: true });\n    data.append(FP16x16 { mag: 80584, sign: false });\n    data.append(FP16x16 { mag: 108804, sign: false });\n    data.append(FP16x16 { mag: 64736, sign: true });\n    data.append(FP16x16 { mag: 35989, sign: false });\n    data.append(FP16x16 { mag: 83918, sign: false });\n    data.append(FP16x16 { mag: 80462, sign: true });\n    data.append(FP16x16 { mag: 43318, sign: false });\n    data.append(FP16x16 { mag: 65651, sign: true });\n    data.append(FP16x16 { mag: 11331, sign: true });\n    data.append(FP16x16 { mag: 25254, sign: true });\n    data.append(FP16x16 { mag: 62677, sign: false });\n    data.append(FP16x16 { mag: 8412, sign: false });\n    data.append(FP16x16 { mag: 64067, sign: true });\n    data.append(FP16x16 { mag: 11592, sign: true });\n    data.append(FP16x16 { mag: 10557, sign: false });\n    data.append(FP16x16 { mag: 33540, sign: true });\n    data.append(FP16x16 { mag: 50007, sign: true });\n    data.append(FP16x16 { mag: 66942, sign: true });\n    data.append(FP16x16 { mag: 24781, sign: true });\n    data.append(FP16x16 { mag: 70618, sign: true });\n    data.append(FP16x16 { mag: 91944, sign: false });\n    data.append(FP16x16 { mag: 25130, sign: false });\n    data.append(FP16x16 { mag: 70069, sign: true });\n    data.append(FP16x16 { mag: 19429, sign: false });\n    data.append(FP16x16 { mag: 17607, sign: true });\n    data.append(FP16x16 { mag: 20059, sign: true });\n    data.append(FP16x16 { mag: 30637, sign: false });\n    data.append(FP16x16 { mag: 110305, sign: true });\n    data.append(FP16x16 { mag: 47227, sign: true });\n    data.append(FP16x16 { mag: 52701, sign: false });\n    data.append(FP16x16 { mag: 113586, sign: true });\n    data.append(FP16x16 { mag: 28893, sign: false });\n    data.append(FP16x16 { mag: 19309, sign: true });\n    data.append(FP16x16 { mag: 9704, sign: true });\n    data.append(FP16x16 { mag: 56793, sign: false });\n    data.append(FP16x16 { mag: 44072, sign: false });\n    data.append(FP16x16 { mag: 2660, sign: true });\n    data.append(FP16x16 { mag: 29401, sign: true });\n    data.append(FP16x16 { mag: 36736, sign: true });\n    data.append(FP16x16 { mag: 86250, sign: false });\n    data.append(FP16x16 { mag: 38971, sign: true });\n    data.append(FP16x16 { mag: 138249, sign: true });\n    data.append(FP16x16 { mag: 36048, sign: false });\n    data.append(FP16x16 { mag: 37452, sign: false });\n    data.append(FP16x16 { mag: 23181, sign: true });\n    data.append(FP16x16 { mag: 35955, sign: true });\n    data.append(FP16x16 { mag: 51748, sign: true });\n    data.append(FP16x16 { mag: 57097, sign: true });\n    data.append(FP16x16 { mag: 91645, sign: true });\n    data.append(FP16x16 { mag: 727, sign: true });\n    data.append(FP16x16 { mag: 26384, sign: true });\n    data.append(FP16x16 { mag: 1331, sign: false });\n    data.append(FP16x16 { mag: 98672, sign: false });\n    data.append(FP16x16 { mag: 82596, sign: false });\n    data.append(FP16x16 { mag: 100984, sign: true });\n    data.append(FP16x16 { mag: 88934, sign: true });\n    data.append(FP16x16 { mag: 110736, sign: false });\n    data.append(FP16x16 { mag: 106050, sign: true });\n    data.append(FP16x16 { mag: 43286, sign: true });\n    data.append(FP16x16 { mag: 114427, sign: false });\n    data.append(FP16x16 { mag: 26160, sign: false });\n    data.append(FP16x16 { mag: 19914, sign: true });\n    data.append(FP16x16 { mag: 168031, sign: false });\n    data.append(FP16x16 { mag: 70834, sign: true });\n    data.append(FP16x16 { mag: 62785, sign: false });\n    data.append(FP16x16 { mag: 20711, sign: true });\n    data.append(FP16x16 { mag: 150814, sign: true });\n    data.append(FP16x16 { mag: 19909, sign: true });\n    data.append(FP16x16 { mag: 4360, sign: true });\n    data.append(FP16x16 { mag: 38550, sign: false });\n    data.append(FP16x16 { mag: 155210, sign: false });\n    data.append(FP16x16 { mag: 49387, sign: true });\n    data.append(FP16x16 { mag: 48606, sign: false });\n    data.append(FP16x16 { mag: 26297, sign: false });\n    data.append(FP16x16 { mag: 5832, sign: true });\n    data.append(FP16x16 { mag: 67019, sign: false });\n    data.append(FP16x16 { mag: 108552, sign: false });\n    data.append(FP16x16 { mag: 38302, sign: true });\n    data.append(FP16x16 { mag: 67467, sign: false });\n    data.append(FP16x16 { mag: 123524, sign: false });\n    data.append(FP16x16 { mag: 38110, sign: true });\n    data.append(FP16x16 { mag: 49459, sign: true });\n    data.append(FP16x16 { mag: 89977, sign: false });\n    data.append(FP16x16 { mag: 3116, sign: false });\n    data.append(FP16x16 { mag: 139868, sign: true });\n    data.append(FP16x16 { mag: 3777, sign: false });\n    data.append(FP16x16 { mag: 93508, sign: false });\n    data.append(FP16x16 { mag: 18473, sign: true });\n    data.append(FP16x16 { mag: 9749, sign: false });\n    data.append(FP16x16 { mag: 69280, sign: false });\n    data.append(FP16x16 { mag: 31261, sign: true });\n    data.append(FP16x16 { mag: 70810, sign: true });\n    data.append(FP16x16 { mag: 53719, sign: true });\n    data.append(FP16x16 { mag: 25490, sign: false });\n    data.append(FP16x16 { mag: 76561, sign: true });\n    data.append(FP16x16 { mag: 87810, sign: true });\n    data.append(FP16x16 { mag: 54546, sign: true });\n    data.append(FP16x16 { mag: 11956, sign: false });\n    data.append(FP16x16 { mag: 53981, sign: true });\n    data.append(FP16x16 { mag: 48734, sign: false });\n    data.append(FP16x16 { mag: 81861, sign: true });\n    data.append(FP16x16 { mag: 91276, sign: false });\n    data.append(FP16x16 { mag: 104233, sign: false });\n    data.append(FP16x16 { mag: 52396, sign: false });\n    data.append(FP16x16 { mag: 37016, sign: false });\n    data.append(FP16x16 { mag: 39784, sign: false });\n    data.append(FP16x16 { mag: 16087, sign: true });\n    data.append(FP16x16 { mag: 22464, sign: true });\n    data.append(FP16x16 { mag: 98432, sign: true });\n    data.append(FP16x16 { mag: 120832, sign: true });\n    data.append(FP16x16 { mag: 25665, sign: true });\n    data.append(FP16x16 { mag: 23338, sign: true });\n    data.append(FP16x16 { mag: 18801, sign: false });\n    data.append(FP16x16 { mag: 22675, sign: false });\n    data.append(FP16x16 { mag: 79634, sign: true });\n    data.append(FP16x16 { mag: 95608, sign: true });\n    data.append(FP16x16 { mag: 73767, sign: false });\n    data.append(FP16x16 { mag: 20235, sign: false });\n    data.append(FP16x16 { mag: 19535, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 12195, sign: false });\n    data.append(FP16x16 { mag: 25593, sign: false });\n    data.append(FP16x16 { mag: 14094, sign: true });\n    data.append(FP16x16 { mag: 99626, sign: true });\n    data.append(FP16x16 { mag: 48676, sign: true });\n    data.append(FP16x16 { mag: 58459, sign: false });\n    data.append(FP16x16 { mag: 96699, sign: true });\n    data.append(FP16x16 { mag: 14935, sign: true });\n    data.append(FP16x16 { mag: 2362, sign: true });\n    data.append(FP16x16 { mag: 150235, sign: false });\n    data.append(FP16x16 { mag: 65730, sign: true });\n    data.append(FP16x16 { mag: 56267, sign: false });\n    data.append(FP16x16 { mag: 83617, sign: true });\n    data.append(FP16x16 { mag: 34940, sign: false });\n    data.append(FP16x16 { mag: 14826, sign: false });\n    data.append(FP16x16 { mag: 67759, sign: true });\n    data.append(FP16x16 { mag: 88099, sign: true });\n    data.append(FP16x16 { mag: 103290, sign: true });\n    data.append(FP16x16 { mag: 50684, sign: true });\n    data.append(FP16x16 { mag: 29161, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 44676, sign: false });\n    data.append(FP16x16 { mag: 53361, sign: true });\n    data.append(FP16x16 { mag: 33378, sign: true });\n    data.append(FP16x16 { mag: 43061, sign: false });\n    data.append(FP16x16 { mag: 24801, sign: false });\n    data.append(FP16x16 { mag: 33406, sign: false });\n    data.append(FP16x16 { mag: 54529, sign: true });\n    data.append(FP16x16 { mag: 133687, sign: false });\n    data.append(FP16x16 { mag: 44032, sign: true });\n    data.append(FP16x16 { mag: 38747, sign: true });\n    data.append(FP16x16 { mag: 34054, sign: true });\n    data.append(FP16x16 { mag: 45436, sign: false });\n    data.append(FP16x16 { mag: 80815, sign: false });\n    data.append(FP16x16 { mag: 79372, sign: true });\n    data.append(FP16x16 { mag: 17958, sign: true });\n    data.append(FP16x16 { mag: 49483, sign: false });\n    data.append(FP16x16 { mag: 46695, sign: true });\n    data.append(FP16x16 { mag: 1816, sign: true });\n    data.append(FP16x16 { mag: 43264, sign: true });\n    data.append(FP16x16 { mag: 59187, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 34980, sign: false });\n    data.append(FP16x16 { mag: 14079, sign: true });\n    data.append(FP16x16 { mag: 62083, sign: true });\n    data.append(FP16x16 { mag: 147603, sign: false });\n    data.append(FP16x16 { mag: 11308, sign: true });\n    data.append(FP16x16 { mag: 126598, sign: false });\n    data.append(FP16x16 { mag: 73983, sign: false });\n    data.append(FP16x16 { mag: 120660, sign: false });\n    data.append(FP16x16 { mag: 41515, sign: true });\n    data.append(FP16x16 { mag: 53720, sign: true });\n    data.append(FP16x16 { mag: 11229, sign: true });\n    data.append(FP16x16 { mag: 113880, sign: false });\n    data.append(FP16x16 { mag: 59791, sign: false });\n    data.append(FP16x16 { mag: 115620, sign: true });\n    data.append(FP16x16 { mag: 19505, sign: true });\n    data.append(FP16x16 { mag: 29861, sign: false });\n    data.append(FP16x16 { mag: 3122, sign: true });\n    data.append(FP16x16 { mag: 79516, sign: false });\n    data.append(FP16x16 { mag: 11908, sign: false });\n    data.append(FP16x16 { mag: 49306, sign: true });\n    data.append(FP16x16 { mag: 30901, sign: false });\n    data.append(FP16x16 { mag: 4892, sign: true });\n    data.append(FP16x16 { mag: 42556, sign: true });\n    data.append(FP16x16 { mag: 154572, sign: false });\n    data.append(FP16x16 { mag: 1734, sign: true });\n    data.append(FP16x16 { mag: 25009, sign: false });\n    data.append(FP16x16 { mag: 36229, sign: true });\n    data.append(FP16x16 { mag: 122431, sign: false });\n    data.append(FP16x16 { mag: 39621, sign: true });\n    data.append(FP16x16 { mag: 143085, sign: true });\n    data.append(FP16x16 { mag: 110561, sign: true });\n    data.append(FP16x16 { mag: 63080, sign: true });\n    data.append(FP16x16 { mag: 20513, sign: false });\n    data.append(FP16x16 { mag: 85496, sign: true });\n    data.append(FP16x16 { mag: 17909, sign: true });\n    data.append(FP16x16 { mag: 34541, sign: true });\n    data.append(FP16x16 { mag: 135099, sign: true });\n    data.append(FP16x16 { mag: 15693, sign: true });\n    data.append(FP16x16 { mag: 24867, sign: true });\n    data.append(FP16x16 { mag: 44624, sign: true });\n    data.append(FP16x16 { mag: 62432, sign: false });\n    data.append(FP16x16 { mag: 61070, sign: true });\n    data.append(FP16x16 { mag: 9497, sign: true });\n    data.append(FP16x16 { mag: 31812, sign: true });\n    data.append(FP16x16 { mag: 12740, sign: true });\n    data.append(FP16x16 { mag: 28750, sign: false });\n    data.append(FP16x16 { mag: 29494, sign: true });\n    data.append(FP16x16 { mag: 140863, sign: false });\n    data.append(FP16x16 { mag: 42720, sign: true });\n    data.append(FP16x16 { mag: 195054, sign: true });\n    data.append(FP16x16 { mag: 49531, sign: true });\n    data.append(FP16x16 { mag: 38426, sign: false });\n    data.append(FP16x16 { mag: 58711, sign: false });\n    data.append(FP16x16 { mag: 22407, sign: true });\n    data.append(FP16x16 { mag: 2868, sign: false });\n    data.append(FP16x16 { mag: 128861, sign: false });\n    data.append(FP16x16 { mag: 41612, sign: false });\n    data.append(FP16x16 { mag: 187704, sign: true });\n    data.append(FP16x16 { mag: 19714, sign: false });\n    data.append(FP16x16 { mag: 48637, sign: true });\n    data.append(FP16x16 { mag: 58990, sign: false });\n    data.append(FP16x16 { mag: 53022, sign: true });\n    data.append(FP16x16 { mag: 25027, sign: true });\n    data.append(FP16x16 { mag: 144085, sign: true });\n    data.append(FP16x16 { mag: 86230, sign: false });\n    data.append(FP16x16 { mag: 62331, sign: false });\n    data.append(FP16x16 { mag: 3779, sign: false });\n    data.append(FP16x16 { mag: 168240, sign: false });\n    data.append(FP16x16 { mag: 42633, sign: true });\n    data.append(FP16x16 { mag: 97041, sign: true });\n    data.append(FP16x16 { mag: 45633, sign: true });\n    data.append(FP16x16 { mag: 141649, sign: false });\n    data.append(FP16x16 { mag: 162760, sign: false });\n    data.append(FP16x16 { mag: 68597, sign: true });\n    data.append(FP16x16 { mag: 17735, sign: true });\n    data.append(FP16x16 { mag: 77086, sign: false });\n    data.append(FP16x16 { mag: 95189, sign: true });\n    data.append(FP16x16 { mag: 115074, sign: true });\n    data.append(FP16x16 { mag: 980, sign: true });\n    data.append(FP16x16 { mag: 75411, sign: true });\n    data.append(FP16x16 { mag: 69778, sign: false });\n    data.append(FP16x16 { mag: 63413, sign: true });\n    data.append(FP16x16 { mag: 25417, sign: true });\n    data.append(FP16x16 { mag: 111323, sign: true });\n    data.append(FP16x16 { mag: 13487, sign: false });\n    data.append(FP16x16 { mag: 79762, sign: true });\n    data.append(FP16x16 { mag: 77975, sign: true });\n    data.append(FP16x16 { mag: 109742, sign: false });\n    data.append(FP16x16 { mag: 43808, sign: true });\n    data.append(FP16x16 { mag: 11284, sign: false });\n    data.append(FP16x16 { mag: 115283, sign: true });\n    data.append(FP16x16 { mag: 29181, sign: false });\n    data.append(FP16x16 { mag: 155120, sign: false });\n    data.append(FP16x16 { mag: 101365, sign: true });\n    data.append(FP16x16 { mag: 9482, sign: true });\n    data.append(FP16x16 { mag: 115606, sign: false });\n    data.append(FP16x16 { mag: 54304, sign: false });\n    data.append(FP16x16 { mag: 64495, sign: false });\n    data.append(FP16x16 { mag: 61839, sign: true });\n    data.append(FP16x16 { mag: 40715, sign: true });\n    data.append(FP16x16 { mag: 54635, sign: false });\n    data.append(FP16x16 { mag: 84491, sign: true });\n    data.append(FP16x16 { mag: 54222, sign: true });\n    data.append(FP16x16 { mag: 124370, sign: true });\n    data.append(FP16x16 { mag: 17725, sign: true });\n    data.append(FP16x16 { mag: 70484, sign: false });\n    data.append(FP16x16 { mag: 120027, sign: true });\n    data.append(FP16x16 { mag: 136560, sign: false });\n    data.append(FP16x16 { mag: 43343, sign: true });\n    data.append(FP16x16 { mag: 260233, sign: true });\n    data.append(FP16x16 { mag: 85770, sign: false });\n    data.append(FP16x16 { mag: 26220, sign: false });\n    data.append(FP16x16 { mag: 106343, sign: false });\n    data.append(FP16x16 { mag: 67118, sign: true });\n    data.append(FP16x16 { mag: 11865, sign: true });\n    data.append(FP16x16 { mag: 129550, sign: false });\n    data.append(FP16x16 { mag: 79314, sign: false });\n    data.append(FP16x16 { mag: 126419, sign: true });\n    data.append(FP16x16 { mag: 62170, sign: true });\n    data.append(FP16x16 { mag: 52010, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 50439, sign: true });\n    data.append(FP16x16 { mag: 80584, sign: false });\n    data.append(FP16x16 { mag: 108804, sign: false });\n    data.append(FP16x16 { mag: 64736, sign: true });\n    data.append(FP16x16 { mag: 35989, sign: false });\n    data.append(FP16x16 { mag: 83918, sign: false });\n    data.append(FP16x16 { mag: 80462, sign: true });\n    data.append(FP16x16 { mag: 43318, sign: false });\n    data.append(FP16x16 { mag: 65651, sign: true });\n    data.append(FP16x16 { mag: 11331, sign: true });\n    data.append(FP16x16 { mag: 25254, sign: true });\n    data.append(FP16x16 { mag: 62677, sign: false });\n    data.append(FP16x16 { mag: 8412, sign: false });\n    data.append(FP16x16 { mag: 64067, sign: true });\n    data.append(FP16x16 { mag: 11592, sign: true });\n    data.append(FP16x16 { mag: 10557, sign: false });\n    data.append(FP16x16 { mag: 33540, sign: true });\n    data.append(FP16x16 { mag: 50007, sign: true });\n    data.append(FP16x16 { mag: 66942, sign: true });\n    data.append(FP16x16 { mag: 24781, sign: true });\n    data.append(FP16x16 { mag: 70618, sign: true });\n    data.append(FP16x16 { mag: 91944, sign: false });\n    data.append(FP16x16 { mag: 25130, sign: false });\n    data.append(FP16x16 { mag: 70069, sign: true });\n    data.append(FP16x16 { mag: 19429, sign: false });\n    data.append(FP16x16 { mag: 17607, sign: true });\n    data.append(FP16x16 { mag: 20059, sign: true });\n    data.append(FP16x16 { mag: 30637, sign: false });\n    data.append(FP16x16 { mag: 110305, sign: true });\n    data.append(FP16x16 { mag: 47227, sign: true });\n    data.append(FP16x16 { mag: 52701, sign: false });\n    data.append(FP16x16 { mag: 113586, sign: true });\n    data.append(FP16x16 { mag: 28893, sign: false });\n    data.append(FP16x16 { mag: 19309, sign: true });\n    data.append(FP16x16 { mag: 9704, sign: true });\n    data.append(FP16x16 { mag: 56793, sign: false });\n    data.append(FP16x16 { mag: 44072, sign: false });\n    data.append(FP16x16 { mag: 2660, sign: true });\n    data.append(FP16x16 { mag: 29401, sign: true });\n    data.append(FP16x16 { mag: 36736, sign: true });\n    data.append(FP16x16 { mag: 86250, sign: false });\n    data.append(FP16x16 { mag: 38971, sign: true });\n    data.append(FP16x16 { mag: 138249, sign: true });\n    data.append(FP16x16 { mag: 36048, sign: false });\n    data.append(FP16x16 { mag: 37452, sign: false });\n    data.append(FP16x16 { mag: 23181, sign: true });\n    data.append(FP16x16 { mag: 35955, sign: true });\n    data.append(FP16x16 { mag: 51748, sign: true });\n    data.append(FP16x16 { mag: 57097, sign: true });\n    data.append(FP16x16 { mag: 91645, sign: true });\n    data.append(FP16x16 { mag: 727, sign: true });\n    data.append(FP16x16 { mag: 26384, sign: true });\n    data.append(FP16x16 { mag: 1331, sign: false });\n    data.append(FP16x16 { mag: 98672, sign: false });\n    data.append(FP16x16 { mag: 82596, sign: false });\n    data.append(FP16x16 { mag: 100984, sign: true });\n    data.append(FP16x16 { mag: 88934, sign: true });\n    data.append(FP16x16 { mag: 110736, sign: false });\n    data.append(FP16x16 { mag: 106050, sign: true });\n    data.append(FP16x16 { mag: 43286, sign: true });\n    data.append(FP16x16 { mag: 114427, sign: false });\n    data.append(FP16x16 { mag: 26160, sign: false });\n    data.append(FP16x16 { mag: 19914, sign: true });\n    data.append(FP16x16 { mag: 168031, sign: false });\n    data.append(FP16x16 { mag: 70834, sign: true });\n    data.append(FP16x16 { mag: 62785, sign: false });\n    data.append(FP16x16 { mag: 20711, sign: true });\n    data.append(FP16x16 { mag: 150814, sign: true });\n    data.append(FP16x16 { mag: 19909, sign: true });\n    data.append(FP16x16 { mag: 4360, sign: true });\n    data.append(FP16x16 { mag: 38550, sign: false });\n    data.append(FP16x16 { mag: 155210, sign: false });\n    data.append(FP16x16 { mag: 49387, sign: true });\n    data.append(FP16x16 { mag: 48606, sign: false });\n    data.append(FP16x16 { mag: 26297, sign: false });\n    data.append(FP16x16 { mag: 5832, sign: true });\n    data.append(FP16x16 { mag: 67019, sign: false });\n    data.append(FP16x16 { mag: 108552, sign: false });\n    data.append(FP16x16 { mag: 38302, sign: true });\n    data.append(FP16x16 { mag: 67467, sign: false });\n    data.append(FP16x16 { mag: 123524, sign: false });\n    data.append(FP16x16 { mag: 38110, sign: true });\n    data.append(FP16x16 { mag: 49459, sign: true });\n    data.append(FP16x16 { mag: 89977, sign: false });\n    data.append(FP16x16 { mag: 3116, sign: false });\n    data.append(FP16x16 { mag: 139868, sign: true });\n    data.append(FP16x16 { mag: 3777, sign: false });\n    data.append(FP16x16 { mag: 93508, sign: false });\n    data.append(FP16x16 { mag: 18473, sign: true });\n    data.append(FP16x16 { mag: 9749, sign: false });\n    data.append(FP16x16 { mag: 69280, sign: false });\n    data.append(FP16x16 { mag: 31261, sign: true });\n    data.append(FP16x16 { mag: 70810, sign: true });\n    data.append(FP16x16 { mag: 53719, sign: true });\n    data.append(FP16x16 { mag: 25490, sign: false });\n    data.append(FP16x16 { mag: 76561, sign: true });\n    data.append(FP16x16 { mag: 87810, sign: true });\n    data.append(FP16x16 { mag: 54546, sign: true });\n    data.append(FP16x16 { mag: 11956, sign: false });\n    data.append(FP16x16 { mag: 53981, sign: true });\n    data.append(FP16x16 { mag: 48734, sign: false });\n    data.append(FP16x16 { mag: 81861, sign: true });\n    data.append(FP16x16 { mag: 91276, sign: false });\n    data.append(FP16x16 { mag: 104233, sign: false });\n    data.append(FP16x16 { mag: 52396, sign: false });\n    data.append(FP16x16 { mag: 37016, sign: false });\n    data.append(FP16x16 { mag: 39784, sign: false });\n    data.append(FP16x16 { mag: 16087, sign: true });\n    data.append(FP16x16 { mag: 22464, sign: true });\n    data.append(FP16x16 { mag: 98432, sign: true });\n    data.append(FP16x16 { mag: 120832, sign: true });\n    data.append(FP16x16 { mag: 25665, sign: true });\n    data.append(FP16x16 { mag: 23338, sign: true });\n    data.append(FP16x16 { mag: 18801, sign: false });\n    data.append(FP16x16 { mag: 22675, sign: false });\n    data.append(FP16x16 { mag: 79634, sign: true });\n    data.append(FP16x16 { mag: 95608, sign: true });\n    data.append(FP16x16 { mag: 73767, sign: false });\n    data.append(FP16x16 { mag: 20235, sign: false });\n    data.append(FP16x16 { mag: 19535, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 72546, sign: true });\n    data.append(FP16x16 { mag: 1934, sign: true });\n    data.append(FP16x16 { mag: 26602, sign: false });\n    data.append(FP16x16 { mag: 64666, sign: false });\n    data.append(FP16x16 { mag: 113155, sign: false });\n    data.append(FP16x16 { mag: 140657, sign: true });\n    data.append(FP16x16 { mag: 8029, sign: false });\n    data.append(FP16x16 { mag: 1972, sign: true });\n    data.append(FP16x16 { mag: 13859, sign: true });\n    data.append(FP16x16 { mag: 30242, sign: true });\n    data.append(FP16x16 { mag: 5299, sign: false });\n    data.append(FP16x16 { mag: 164784, sign: false });\n    data.append(FP16x16 { mag: 46610, sign: false });\n    data.append(FP16x16 { mag: 8040, sign: true });\n    data.append(FP16x16 { mag: 2005, sign: false });\n    data.append(FP16x16 { mag: 43621, sign: true });\n    data.append(FP16x16 { mag: 23042, sign: false });\n    data.append(FP16x16 { mag: 12823, sign: true });\n    data.append(FP16x16 { mag: 93996, sign: true });\n    data.append(FP16x16 { mag: 32415, sign: true });\n    data.append(FP16x16 { mag: 78956, sign: true });\n    data.append(FP16x16 { mag: 74322, sign: true });\n    data.append(FP16x16 { mag: 3724, sign: true });\n    data.append(FP16x16 { mag: 5105, sign: true });\n    data.append(FP16x16 { mag: 54473, sign: false });\n    data.append(FP16x16 { mag: 38101, sign: false });\n    data.append(FP16x16 { mag: 12378, sign: false });\n    data.append(FP16x16 { mag: 36960, sign: true });\n    data.append(FP16x16 { mag: 87265, sign: true });\n    data.append(FP16x16 { mag: 34339, sign: true });\n    data.append(FP16x16 { mag: 109979, sign: false });\n    data.append(FP16x16 { mag: 138917, sign: true });\n    data.append(FP16x16 { mag: 93741, sign: false });\n    data.append(FP16x16 { mag: 139243, sign: false });\n    data.append(FP16x16 { mag: 42853, sign: true });\n    data.append(FP16x16 { mag: 33084, sign: false });\n    data.append(FP16x16 { mag: 23897, sign: true });\n    data.append(FP16x16 { mag: 52766, sign: true });\n    data.append(FP16x16 { mag: 38574, sign: true });\n    data.append(FP16x16 { mag: 10485, sign: true });\n    data.append(FP16x16 { mag: 60984, sign: true });\n    data.append(FP16x16 { mag: 20096, sign: false });\n    data.append(FP16x16 { mag: 24418, sign: false });\n    data.append(FP16x16 { mag: 29015, sign: false });\n    data.append(FP16x16 { mag: 49773, sign: false });\n    data.append(FP16x16 { mag: 104302, sign: false });\n    data.append(FP16x16 { mag: 39141, sign: false });\n    data.append(FP16x16 { mag: 23473, sign: true });\n    data.append(FP16x16 { mag: 33895, sign: false });\n    data.append(FP16x16 { mag: 12032, sign: true });\n    data.append(FP16x16 { mag: 60207, sign: false });\n    data.append(FP16x16 { mag: 64204, sign: false });\n    data.append(FP16x16 { mag: 34732, sign: true });\n    data.append(FP16x16 { mag: 31629, sign: false });\n    data.append(FP16x16 { mag: 3538, sign: true });\n    data.append(FP16x16 { mag: 13382, sign: false });\n    data.append(FP16x16 { mag: 29195, sign: true });\n    data.append(FP16x16 { mag: 5944, sign: true });\n    data.append(FP16x16 { mag: 103840, sign: true });\n    data.append(FP16x16 { mag: 38426, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-3/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 140567, sign: false });\n    data.append(FP16x16 { mag: 40459, sign: true });\n    data.append(FP16x16 { mag: 24644, sign: false });\n    data.append(FP16x16 { mag: 111555, sign: false });\n    data.append(FP16x16 { mag: 8570, sign: false });\n    data.append(FP16x16 { mag: 10992, sign: true });\n    data.append(FP16x16 { mag: 212035, sign: false });\n    data.append(FP16x16 { mag: 11465, sign: false });\n    data.append(FP16x16 { mag: 73223, sign: false });\n    data.append(FP16x16 { mag: 105723, sign: true });\n    data.append(FP16x16 { mag: 75766, sign: true });\n    data.append(FP16x16 { mag: 102598, sign: true });\n    data.append(FP16x16 { mag: 94019, sign: true });\n    data.append(FP16x16 { mag: 35770, sign: false });\n    data.append(FP16x16 { mag: 78502, sign: false });\n    data.append(FP16x16 { mag: 41664, sign: true });\n    data.append(FP16x16 { mag: 29280, sign: true });\n    data.append(FP16x16 { mag: 124649, sign: false });\n    data.append(FP16x16 { mag: 99019, sign: true });\n    data.append(FP16x16 { mag: 66970, sign: true });\n    data.append(FP16x16 { mag: 8747, sign: true });\n    data.append(FP16x16 { mag: 79443, sign: true });\n    data.append(FP16x16 { mag: 68471, sign: false });\n    data.append(FP16x16 { mag: 11126, sign: true });\n    data.append(FP16x16 { mag: 24010, sign: true });\n    data.append(FP16x16 { mag: 4088, sign: false });\n    data.append(FP16x16 { mag: 49743, sign: false });\n    data.append(FP16x16 { mag: 8246, sign: false });\n    data.append(FP16x16 { mag: 84164, sign: false });\n    data.append(FP16x16 { mag: 86259, sign: false });\n    data.append(FP16x16 { mag: 42086, sign: false });\n    data.append(FP16x16 { mag: 5197, sign: false });\n    data.append(FP16x16 { mag: 1592, sign: false });\n    data.append(FP16x16 { mag: 41261, sign: true });\n    data.append(FP16x16 { mag: 52531, sign: false });\n    data.append(FP16x16 { mag: 9495, sign: true });\n    data.append(FP16x16 { mag: 18817, sign: true });\n    data.append(FP16x16 { mag: 2626, sign: false });\n    data.append(FP16x16 { mag: 7622, sign: true });\n    data.append(FP16x16 { mag: 34140, sign: true });\n    data.append(FP16x16 { mag: 29535, sign: true });\n    data.append(FP16x16 { mag: 43504, sign: true });\n    data.append(FP16x16 { mag: 71292, sign: true });\n    data.append(FP16x16 { mag: 30928, sign: false });\n    data.append(FP16x16 { mag: 113967, sign: false });\n    data.append(FP16x16 { mag: 38791, sign: false });\n    data.append(FP16x16 { mag: 89439, sign: true });\n    data.append(FP16x16 { mag: 73665, sign: true });\n    data.append(FP16x16 { mag: 103501, sign: false });\n    data.append(FP16x16 { mag: 27579, sign: false });\n    data.append(FP16x16 { mag: 81207, sign: false });\n    data.append(FP16x16 { mag: 8128, sign: true });\n    data.append(FP16x16 { mag: 7160, sign: true });\n    data.append(FP16x16 { mag: 159276, sign: true });\n    data.append(FP16x16 { mag: 93395, sign: false });\n    data.append(FP16x16 { mag: 6090, sign: false });\n    data.append(FP16x16 { mag: 29949, sign: false });\n    data.append(FP16x16 { mag: 24359, sign: true });\n    data.append(FP16x16 { mag: 44435, sign: false });\n    data.append(FP16x16 { mag: 57014, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 187342, sign: false });\n    data.append(FP16x16 { mag: 43360, sign: true });\n    data.append(FP16x16 { mag: 76815, sign: false });\n    data.append(FP16x16 { mag: 54732, sign: false });\n    data.append(FP16x16 { mag: 95653, sign: false });\n    data.append(FP16x16 { mag: 229562, sign: true });\n    data.append(FP16x16 { mag: 202912, sign: false });\n    data.append(FP16x16 { mag: 9710, sign: false });\n    data.append(FP16x16 { mag: 85609, sign: false });\n    data.append(FP16x16 { mag: 105578, sign: true });\n    data.append(FP16x16 { mag: 76999, sign: true });\n    data.append(FP16x16 { mag: 96182, sign: false });\n    data.append(FP16x16 { mag: 79183, sign: true });\n    data.append(FP16x16 { mag: 42747, sign: false });\n    data.append(FP16x16 { mag: 78484, sign: false });\n    data.append(FP16x16 { mag: 57080, sign: true });\n    data.append(FP16x16 { mag: 37764, sign: true });\n    data.append(FP16x16 { mag: 132826, sign: false });\n    data.append(FP16x16 { mag: 13030, sign: true });\n    data.append(FP16x16 { mag: 59680, sign: true });\n    data.append(FP16x16 { mag: 68231, sign: false });\n    data.append(FP16x16 { mag: 204694, sign: true });\n    data.append(FP16x16 { mag: 66266, sign: false });\n    data.append(FP16x16 { mag: 6194, sign: true });\n    data.append(FP16x16 { mag: 3149, sign: false });\n    data.append(FP16x16 { mag: 6, sign: true });\n    data.append(FP16x16 { mag: 47916, sign: false });\n    data.append(FP16x16 { mag: 16960, sign: true });\n    data.append(FP16x16 { mag: 225919, sign: false });\n    data.append(FP16x16 { mag: 106594, sign: false });\n    data.append(FP16x16 { mag: 156803, sign: false });\n    data.append(FP16x16 { mag: 238316, sign: false });\n    data.append(FP16x16 { mag: 62849, sign: false });\n    data.append(FP16x16 { mag: 60107, sign: true });\n    data.append(FP16x16 { mag: 51595, sign: false });\n    data.append(FP16x16 { mag: 27228, sign: false });\n    data.append(FP16x16 { mag: 40369, sign: true });\n    data.append(FP16x16 { mag: 4608, sign: true });\n    data.append(FP16x16 { mag: 3968, sign: false });\n    data.append(FP16x16 { mag: 29731, sign: true });\n    data.append(FP16x16 { mag: 126627, sign: true });\n    data.append(FP16x16 { mag: 52689, sign: true });\n    data.append(FP16x16 { mag: 122123, sign: true });\n    data.append(FP16x16 { mag: 53286, sign: false });\n    data.append(FP16x16 { mag: 153464, sign: false });\n    data.append(FP16x16 { mag: 18067, sign: false });\n    data.append(FP16x16 { mag: 105399, sign: true });\n    data.append(FP16x16 { mag: 58027, sign: true });\n    data.append(FP16x16 { mag: 77954, sign: false });\n    data.append(FP16x16 { mag: 43451, sign: false });\n    data.append(FP16x16 { mag: 91367, sign: false });\n    data.append(FP16x16 { mag: 24251, sign: true });\n    data.append(FP16x16 { mag: 14192, sign: true });\n    data.append(FP16x16 { mag: 102491, sign: true });\n    data.append(FP16x16 { mag: 87973, sign: false });\n    data.append(FP16x16 { mag: 13606, sign: true });\n    data.append(FP16x16 { mag: 67163, sign: false });\n    data.append(FP16x16 { mag: 36206, sign: true });\n    data.append(FP16x16 { mag: 205884, sign: false });\n    data.append(FP16x16 { mag: 36735, sign: true });\n    data.append(FP16x16 { mag: 26425, sign: false });\n    data.append(FP16x16 { mag: 41090, sign: true });\n    data.append(FP16x16 { mag: 16004, sign: false });\n    data.append(FP16x16 { mag: 262275, sign: false });\n    data.append(FP16x16 { mag: 109588, sign: true });\n    data.append(FP16x16 { mag: 129666, sign: true });\n    data.append(FP16x16 { mag: 209336, sign: false });\n    data.append(FP16x16 { mag: 15754, sign: false });\n    data.append(FP16x16 { mag: 77723, sign: false });\n    data.append(FP16x16 { mag: 102547, sign: true });\n    data.append(FP16x16 { mag: 73109, sign: true });\n    data.append(FP16x16 { mag: 251621, sign: false });\n    data.append(FP16x16 { mag: 128567, sign: true });\n    data.append(FP16x16 { mag: 30597, sign: false });\n    data.append(FP16x16 { mag: 79160, sign: false });\n    data.append(FP16x16 { mag: 36176, sign: true });\n    data.append(FP16x16 { mag: 8461, sign: true });\n    data.append(FP16x16 { mag: 105536, sign: false });\n    data.append(FP16x16 { mag: 44072, sign: true });\n    data.append(FP16x16 { mag: 96463, sign: true });\n    data.append(FP16x16 { mag: 143124, sign: true });\n    data.append(FP16x16 { mag: 36197, sign: true });\n    data.append(FP16x16 { mag: 71235, sign: false });\n    data.append(FP16x16 { mag: 17395, sign: true });\n    data.append(FP16x16 { mag: 23976, sign: true });\n    data.append(FP16x16 { mag: 72861, sign: true });\n    data.append(FP16x16 { mag: 49866, sign: false });\n    data.append(FP16x16 { mag: 38981, sign: true });\n    data.append(FP16x16 { mag: 110729, sign: false });\n    data.append(FP16x16 { mag: 83018, sign: false });\n    data.append(FP16x16 { mag: 144969, sign: false });\n    data.append(FP16x16 { mag: 72585, sign: false });\n    data.append(FP16x16 { mag: 96262, sign: true });\n    data.append(FP16x16 { mag: 152991, sign: true });\n    data.append(FP16x16 { mag: 38957, sign: false });\n    data.append(FP16x16 { mag: 46719, sign: true });\n    data.append(FP16x16 { mag: 11869, sign: false });\n    data.append(FP16x16 { mag: 45582, sign: false });\n    data.append(FP16x16 { mag: 12464, sign: true });\n    data.append(FP16x16 { mag: 25688, sign: true });\n    data.append(FP16x16 { mag: 68881, sign: true });\n    data.append(FP16x16 { mag: 67620, sign: true });\n    data.append(FP16x16 { mag: 40860, sign: true });\n    data.append(FP16x16 { mag: 72401, sign: false });\n    data.append(FP16x16 { mag: 148655, sign: false });\n    data.append(FP16x16 { mag: 88817, sign: false });\n    data.append(FP16x16 { mag: 69136, sign: true });\n    data.append(FP16x16 { mag: 67311, sign: true });\n    data.append(FP16x16 { mag: 91271, sign: false });\n    data.append(FP16x16 { mag: 44836, sign: false });\n    data.append(FP16x16 { mag: 24194, sign: true });\n    data.append(FP16x16 { mag: 34197, sign: true });\n    data.append(FP16x16 { mag: 5799, sign: false });\n    data.append(FP16x16 { mag: 152246, sign: true });\n    data.append(FP16x16 { mag: 92415, sign: false });\n    data.append(FP16x16 { mag: 9547, sign: true });\n    data.append(FP16x16 { mag: 70654, sign: false });\n    data.append(FP16x16 { mag: 30297, sign: true });\n    data.append(FP16x16 { mag: 19252, sign: false });\n    data.append(FP16x16 { mag: 44739, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-4/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 50439, sign: true });\n    data.append(FP16x16 { mag: 80584, sign: false });\n    data.append(FP16x16 { mag: 108804, sign: false });\n    data.append(FP16x16 { mag: 64736, sign: true });\n    data.append(FP16x16 { mag: 35989, sign: false });\n    data.append(FP16x16 { mag: 83918, sign: false });\n    data.append(FP16x16 { mag: 80462, sign: true });\n    data.append(FP16x16 { mag: 43318, sign: false });\n    data.append(FP16x16 { mag: 65651, sign: true });\n    data.append(FP16x16 { mag: 11331, sign: true });\n    data.append(FP16x16 { mag: 25254, sign: true });\n    data.append(FP16x16 { mag: 62677, sign: false });\n    data.append(FP16x16 { mag: 8412, sign: false });\n    data.append(FP16x16 { mag: 64067, sign: true });\n    data.append(FP16x16 { mag: 11592, sign: true });\n    data.append(FP16x16 { mag: 10557, sign: false });\n    data.append(FP16x16 { mag: 33540, sign: true });\n    data.append(FP16x16 { mag: 50007, sign: true });\n    data.append(FP16x16 { mag: 66942, sign: true });\n    data.append(FP16x16 { mag: 24781, sign: true });\n    data.append(FP16x16 { mag: 70618, sign: true });\n    data.append(FP16x16 { mag: 91944, sign: false });\n    data.append(FP16x16 { mag: 25130, sign: false });\n    data.append(FP16x16 { mag: 70069, sign: true });\n    data.append(FP16x16 { mag: 19429, sign: false });\n    data.append(FP16x16 { mag: 17607, sign: true });\n    data.append(FP16x16 { mag: 20059, sign: true });\n    data.append(FP16x16 { mag: 30637, sign: false });\n    data.append(FP16x16 { mag: 110305, sign: true });\n    data.append(FP16x16 { mag: 47227, sign: true });\n    data.append(FP16x16 { mag: 52701, sign: false });\n    data.append(FP16x16 { mag: 113586, sign: true });\n    data.append(FP16x16 { mag: 28893, sign: false });\n    data.append(FP16x16 { mag: 19309, sign: true });\n    data.append(FP16x16 { mag: 9704, sign: true });\n    data.append(FP16x16 { mag: 56793, sign: false });\n    data.append(FP16x16 { mag: 44072, sign: false });\n    data.append(FP16x16 { mag: 2660, sign: true });\n    data.append(FP16x16 { mag: 29401, sign: true });\n    data.append(FP16x16 { mag: 36736, sign: true });\n    data.append(FP16x16 { mag: 86250, sign: false });\n    data.append(FP16x16 { mag: 38971, sign: true });\n    data.append(FP16x16 { mag: 138249, sign: true });\n    data.append(FP16x16 { mag: 36048, sign: false });\n    data.append(FP16x16 { mag: 37452, sign: false });\n    data.append(FP16x16 { mag: 23181, sign: true });\n    data.append(FP16x16 { mag: 35955, sign: true });\n    data.append(FP16x16 { mag: 51748, sign: true });\n    data.append(FP16x16 { mag: 57097, sign: true });\n    data.append(FP16x16 { mag: 91645, sign: true });\n    data.append(FP16x16 { mag: 727, sign: true });\n    data.append(FP16x16 { mag: 26384, sign: true });\n    data.append(FP16x16 { mag: 1331, sign: false });\n    data.append(FP16x16 { mag: 98672, sign: false });\n    data.append(FP16x16 { mag: 82596, sign: false });\n    data.append(FP16x16 { mag: 100984, sign: true });\n    data.append(FP16x16 { mag: 88934, sign: true });\n    data.append(FP16x16 { mag: 110736, sign: false });\n    data.append(FP16x16 { mag: 106050, sign: true });\n    data.append(FP16x16 { mag: 43286, sign: true });\n    data.append(FP16x16 { mag: 114427, sign: false });\n    data.append(FP16x16 { mag: 26160, sign: false });\n    data.append(FP16x16 { mag: 19914, sign: true });\n    data.append(FP16x16 { mag: 168031, sign: false });\n    data.append(FP16x16 { mag: 70834, sign: true });\n    data.append(FP16x16 { mag: 62785, sign: false });\n    data.append(FP16x16 { mag: 20711, sign: true });\n    data.append(FP16x16 { mag: 150814, sign: true });\n    data.append(FP16x16 { mag: 19909, sign: true });\n    data.append(FP16x16 { mag: 4360, sign: true });\n    data.append(FP16x16 { mag: 38550, sign: false });\n    data.append(FP16x16 { mag: 155210, sign: false });\n    data.append(FP16x16 { mag: 49387, sign: true });\n    data.append(FP16x16 { mag: 48606, sign: false });\n    data.append(FP16x16 { mag: 26297, sign: false });\n    data.append(FP16x16 { mag: 5832, sign: true });\n    data.append(FP16x16 { mag: 67019, sign: false });\n    data.append(FP16x16 { mag: 108552, sign: false });\n    data.append(FP16x16 { mag: 38302, sign: true });\n    data.append(FP16x16 { mag: 67467, sign: false });\n    data.append(FP16x16 { mag: 123524, sign: false });\n    data.append(FP16x16 { mag: 38110, sign: true });\n    data.append(FP16x16 { mag: 49459, sign: true });\n    data.append(FP16x16 { mag: 89977, sign: false });\n    data.append(FP16x16 { mag: 3116, sign: false });\n    data.append(FP16x16 { mag: 139868, sign: true });\n    data.append(FP16x16 { mag: 3777, sign: false });\n    data.append(FP16x16 { mag: 93508, sign: false });\n    data.append(FP16x16 { mag: 18473, sign: true });\n    data.append(FP16x16 { mag: 9749, sign: false });\n    data.append(FP16x16 { mag: 69280, sign: false });\n    data.append(FP16x16 { mag: 31261, sign: true });\n    data.append(FP16x16 { mag: 70810, sign: true });\n    data.append(FP16x16 { mag: 53719, sign: true });\n    data.append(FP16x16 { mag: 25490, sign: false });\n    data.append(FP16x16 { mag: 76561, sign: true });\n    data.append(FP16x16 { mag: 87810, sign: true });\n    data.append(FP16x16 { mag: 54546, sign: true });\n    data.append(FP16x16 { mag: 11956, sign: false });\n    data.append(FP16x16 { mag: 53981, sign: true });\n    data.append(FP16x16 { mag: 48734, sign: false });\n    data.append(FP16x16 { mag: 81861, sign: true });\n    data.append(FP16x16 { mag: 91276, sign: false });\n    data.append(FP16x16 { mag: 104233, sign: false });\n    data.append(FP16x16 { mag: 52396, sign: false });\n    data.append(FP16x16 { mag: 37016, sign: false });\n    data.append(FP16x16 { mag: 39784, sign: false });\n    data.append(FP16x16 { mag: 16087, sign: true });\n    data.append(FP16x16 { mag: 22464, sign: true });\n    data.append(FP16x16 { mag: 98432, sign: true });\n    data.append(FP16x16 { mag: 120832, sign: true });\n    data.append(FP16x16 { mag: 25665, sign: true });\n    data.append(FP16x16 { mag: 23338, sign: true });\n    data.append(FP16x16 { mag: 18801, sign: false });\n    data.append(FP16x16 { mag: 22675, sign: false });\n    data.append(FP16x16 { mag: 79634, sign: true });\n    data.append(FP16x16 { mag: 95608, sign: true });\n    data.append(FP16x16 { mag: 73767, sign: false });\n    data.append(FP16x16 { mag: 20235, sign: false });\n    data.append(FP16x16 { mag: 19535, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-4/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 9950, sign: true });\n    data.append(FP16x16 { mag: 28981, sign: true });\n    data.append(FP16x16 { mag: 12325, sign: false });\n    data.append(FP16x16 { mag: 111567, sign: true });\n    data.append(FP16x16 { mag: 87492, sign: true });\n    data.append(FP16x16 { mag: 2266, sign: false });\n    data.append(FP16x16 { mag: 91808, sign: false });\n    data.append(FP16x16 { mag: 99181, sign: false });\n    data.append(FP16x16 { mag: 54619, sign: false });\n    data.append(FP16x16 { mag: 56530, sign: true });\n    data.append(FP16x16 { mag: 58746, sign: false });\n    data.append(FP16x16 { mag: 11025, sign: true });\n    data.append(FP16x16 { mag: 63919, sign: false });\n    data.append(FP16x16 { mag: 16987, sign: true });\n    data.append(FP16x16 { mag: 14843, sign: true });\n    data.append(FP16x16 { mag: 9629, sign: false });\n    data.append(FP16x16 { mag: 27461, sign: false });\n    data.append(FP16x16 { mag: 34324, sign: false });\n    data.append(FP16x16 { mag: 102809, sign: true });\n    data.append(FP16x16 { mag: 75888, sign: false });\n    data.append(FP16x16 { mag: 65510, sign: true });\n    data.append(FP16x16 { mag: 54723, sign: true });\n    data.append(FP16x16 { mag: 52244, sign: true });\n    data.append(FP16x16 { mag: 54119, sign: false });\n    data.append(FP16x16 { mag: 28309, sign: false });\n    data.append(FP16x16 { mag: 30690, sign: false });\n    data.append(FP16x16 { mag: 5155, sign: false });\n    data.append(FP16x16 { mag: 1463, sign: false });\n    data.append(FP16x16 { mag: 72974, sign: true });\n    data.append(FP16x16 { mag: 62563, sign: true });\n    data.append(FP16x16 { mag: 115530, sign: true });\n    data.append(FP16x16 { mag: 3885, sign: true });\n    data.append(FP16x16 { mag: 1274, sign: false });\n    data.append(FP16x16 { mag: 20319, sign: true });\n    data.append(FP16x16 { mag: 13396, sign: true });\n    data.append(FP16x16 { mag: 12923, sign: false });\n    data.append(FP16x16 { mag: 13623, sign: false });\n    data.append(FP16x16 { mag: 95497, sign: true });\n    data.append(FP16x16 { mag: 78541, sign: false });\n    data.append(FP16x16 { mag: 61124, sign: false });\n    data.append(FP16x16 { mag: 12527, sign: true });\n    data.append(FP16x16 { mag: 128370, sign: true });\n    data.append(FP16x16 { mag: 81782, sign: false });\n    data.append(FP16x16 { mag: 47494, sign: true });\n    data.append(FP16x16 { mag: 15027, sign: false });\n    data.append(FP16x16 { mag: 76936, sign: false });\n    data.append(FP16x16 { mag: 95112, sign: true });\n    data.append(FP16x16 { mag: 37987, sign: false });\n    data.append(FP16x16 { mag: 11759, sign: false });\n    data.append(FP16x16 { mag: 128485, sign: true });\n    data.append(FP16x16 { mag: 12506, sign: false });\n    data.append(FP16x16 { mag: 16778, sign: false });\n    data.append(FP16x16 { mag: 49483, sign: false });\n    data.append(FP16x16 { mag: 11346, sign: false });\n    data.append(FP16x16 { mag: 58647, sign: true });\n    data.append(FP16x16 { mag: 71599, sign: false });\n    data.append(FP16x16 { mag: 22777, sign: false });\n    data.append(FP16x16 { mag: 17125, sign: true });\n    data.append(FP16x16 { mag: 122340, sign: true });\n    data.append(FP16x16 { mag: 14001, sign: true });\n    data.append(FP16x16 { mag: 43279, sign: false });\n    data.append(FP16x16 { mag: 74703, sign: false });\n    data.append(FP16x16 { mag: 95648, sign: false });\n    data.append(FP16x16 { mag: 9808, sign: true });\n    data.append(FP16x16 { mag: 41586, sign: false });\n    data.append(FP16x16 { mag: 55055, sign: false });\n    data.append(FP16x16 { mag: 29114, sign: false });\n    data.append(FP16x16 { mag: 80337, sign: true });\n    data.append(FP16x16 { mag: 45090, sign: false });\n    data.append(FP16x16 { mag: 21497, sign: true });\n    data.append(FP16x16 { mag: 66453, sign: true });\n    data.append(FP16x16 { mag: 41129, sign: true });\n    data.append(FP16x16 { mag: 28771, sign: false });\n    data.append(FP16x16 { mag: 38619, sign: true });\n    data.append(FP16x16 { mag: 12052, sign: true });\n    data.append(FP16x16 { mag: 71742, sign: true });\n    data.append(FP16x16 { mag: 3122, sign: true });\n    data.append(FP16x16 { mag: 7658, sign: false });\n    data.append(FP16x16 { mag: 72650, sign: false });\n    data.append(FP16x16 { mag: 125101, sign: true });\n    data.append(FP16x16 { mag: 123350, sign: true });\n    data.append(FP16x16 { mag: 17299, sign: true });\n    data.append(FP16x16 { mag: 133664, sign: false });\n    data.append(FP16x16 { mag: 95871, sign: false });\n    data.append(FP16x16 { mag: 68174, sign: true });\n    data.append(FP16x16 { mag: 11742, sign: true });\n    data.append(FP16x16 { mag: 39757, sign: false });\n    data.append(FP16x16 { mag: 107969, sign: true });\n    data.append(FP16x16 { mag: 47625, sign: false });\n    data.append(FP16x16 { mag: 25381, sign: false });\n    data.append(FP16x16 { mag: 86657, sign: false });\n    data.append(FP16x16 { mag: 124296, sign: true });\n    data.append(FP16x16 { mag: 84481, sign: true });\n    data.append(FP16x16 { mag: 39857, sign: false });\n    data.append(FP16x16 { mag: 62123, sign: false });\n    data.append(FP16x16 { mag: 51178, sign: true });\n    data.append(FP16x16 { mag: 1008, sign: true });\n    data.append(FP16x16 { mag: 58152, sign: false });\n    data.append(FP16x16 { mag: 23649, sign: false });\n    data.append(FP16x16 { mag: 21472, sign: true });\n    data.append(FP16x16 { mag: 42397, sign: true });\n    data.append(FP16x16 { mag: 9088, sign: true });\n    data.append(FP16x16 { mag: 174345, sign: false });\n    data.append(FP16x16 { mag: 36378, sign: true });\n    data.append(FP16x16 { mag: 57507, sign: false });\n    data.append(FP16x16 { mag: 9867, sign: false });\n    data.append(FP16x16 { mag: 103912, sign: false });\n    data.append(FP16x16 { mag: 14015, sign: false });\n    data.append(FP16x16 { mag: 18604, sign: true });\n    data.append(FP16x16 { mag: 5497, sign: false });\n    data.append(FP16x16 { mag: 47155, sign: false });\n    data.append(FP16x16 { mag: 46396, sign: true });\n    data.append(FP16x16 { mag: 57120, sign: false });\n    data.append(FP16x16 { mag: 74433, sign: true });\n    data.append(FP16x16 { mag: 8714, sign: false });\n    data.append(FP16x16 { mag: 52414, sign: true });\n    data.append(FP16x16 { mag: 29603, sign: false });\n    data.append(FP16x16 { mag: 34762, sign: false });\n    data.append(FP16x16 { mag: 30832, sign: false });\n    data.append(FP16x16 { mag: 71610, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-4/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 74987, sign: false });\n    data.append(FP16x16 { mag: 102257, sign: true });\n    data.append(FP16x16 { mag: 78717, sign: false });\n    data.append(FP16x16 { mag: 59379, sign: true });\n    data.append(FP16x16 { mag: 11211, sign: true });\n    data.append(FP16x16 { mag: 26255, sign: false });\n    data.append(FP16x16 { mag: 30689, sign: false });\n    data.append(FP16x16 { mag: 80491, sign: true });\n    data.append(FP16x16 { mag: 14461, sign: true });\n    data.append(FP16x16 { mag: 42696, sign: false });\n    data.append(FP16x16 { mag: 56317, sign: false });\n    data.append(FP16x16 { mag: 88135, sign: false });\n    data.append(FP16x16 { mag: 45393, sign: false });\n    data.append(FP16x16 { mag: 18363, sign: true });\n    data.append(FP16x16 { mag: 20773, sign: false });\n    data.append(FP16x16 { mag: 66375, sign: false });\n    data.append(FP16x16 { mag: 35314, sign: true });\n    data.append(FP16x16 { mag: 52902, sign: false });\n    data.append(FP16x16 { mag: 86324, sign: true });\n    data.append(FP16x16 { mag: 40151, sign: true });\n    data.append(FP16x16 { mag: 22446, sign: false });\n    data.append(FP16x16 { mag: 33948, sign: true });\n    data.append(FP16x16 { mag: 30607, sign: false });\n    data.append(FP16x16 { mag: 8106, sign: false });\n    data.append(FP16x16 { mag: 42198, sign: false });\n    data.append(FP16x16 { mag: 128853, sign: true });\n    data.append(FP16x16 { mag: 17078, sign: true });\n    data.append(FP16x16 { mag: 200766, sign: false });\n    data.append(FP16x16 { mag: 8367, sign: false });\n    data.append(FP16x16 { mag: 91621, sign: true });\n    data.append(FP16x16 { mag: 34264, sign: false });\n    data.append(FP16x16 { mag: 46301, sign: false });\n    data.append(FP16x16 { mag: 106288, sign: false });\n    data.append(FP16x16 { mag: 130170, sign: false });\n    data.append(FP16x16 { mag: 5525, sign: false });\n    data.append(FP16x16 { mag: 111843, sign: true });\n    data.append(FP16x16 { mag: 1844, sign: true });\n    data.append(FP16x16 { mag: 73523, sign: true });\n    data.append(FP16x16 { mag: 33663, sign: false });\n    data.append(FP16x16 { mag: 9757, sign: false });\n    data.append(FP16x16 { mag: 16424, sign: true });\n    data.append(FP16x16 { mag: 67890, sign: false });\n    data.append(FP16x16 { mag: 103692, sign: true });\n    data.append(FP16x16 { mag: 37978, sign: false });\n    data.append(FP16x16 { mag: 52354, sign: true });\n    data.append(FP16x16 { mag: 62808, sign: false });\n    data.append(FP16x16 { mag: 73374, sign: true });\n    data.append(FP16x16 { mag: 42169, sign: false });\n    data.append(FP16x16 { mag: 42576, sign: false });\n    data.append(FP16x16 { mag: 76141, sign: false });\n    data.append(FP16x16 { mag: 12231, sign: false });\n    data.append(FP16x16 { mag: 42136, sign: false });\n    data.append(FP16x16 { mag: 47496, sign: true });\n    data.append(FP16x16 { mag: 81264, sign: false });\n    data.append(FP16x16 { mag: 15196, sign: true });\n    data.append(FP16x16 { mag: 70791, sign: true });\n    data.append(FP16x16 { mag: 7825, sign: true });\n    data.append(FP16x16 { mag: 40333, sign: true });\n    data.append(FP16x16 { mag: 30221, sign: false });\n    data.append(FP16x16 { mag: 98040, sign: true });\n    data.append(FP16x16 { mag: 39486, sign: true });\n    data.append(FP16x16 { mag: 6407, sign: false });\n    data.append(FP16x16 { mag: 24512, sign: true });\n    data.append(FP16x16 { mag: 7948, sign: true });\n    data.append(FP16x16 { mag: 11193, sign: true });\n    data.append(FP16x16 { mag: 3711, sign: true });\n    data.append(FP16x16 { mag: 35698, sign: true });\n    data.append(FP16x16 { mag: 3213, sign: false });\n    data.append(FP16x16 { mag: 38235, sign: false });\n    data.append(FP16x16 { mag: 82210, sign: true });\n    data.append(FP16x16 { mag: 6567, sign: true });\n    data.append(FP16x16 { mag: 5350, sign: false });\n    data.append(FP16x16 { mag: 5068, sign: true });\n    data.append(FP16x16 { mag: 27441, sign: true });\n    data.append(FP16x16 { mag: 17130, sign: false });\n    data.append(FP16x16 { mag: 89900, sign: true });\n    data.append(FP16x16 { mag: 77188, sign: false });\n    data.append(FP16x16 { mag: 34983, sign: true });\n    data.append(FP16x16 { mag: 5966, sign: false });\n    data.append(FP16x16 { mag: 16995, sign: true });\n    data.append(FP16x16 { mag: 34228, sign: true });\n    data.append(FP16x16 { mag: 29003, sign: false });\n    data.append(FP16x16 { mag: 9617, sign: false });\n    data.append(FP16x16 { mag: 70272, sign: true });\n    data.append(FP16x16 { mag: 82673, sign: true });\n    data.append(FP16x16 { mag: 12155, sign: false });\n    data.append(FP16x16 { mag: 25123, sign: true });\n    data.append(FP16x16 { mag: 137966, sign: true });\n    data.append(FP16x16 { mag: 69397, sign: true });\n    data.append(FP16x16 { mag: 61271, sign: false });\n    data.append(FP16x16 { mag: 12363, sign: false });\n    data.append(FP16x16 { mag: 13484, sign: true });\n    data.append(FP16x16 { mag: 85721, sign: false });\n    data.append(FP16x16 { mag: 81931, sign: false });\n    data.append(FP16x16 { mag: 15988, sign: false });\n    data.append(FP16x16 { mag: 82208, sign: false });\n    data.append(FP16x16 { mag: 94093, sign: true });\n    data.append(FP16x16 { mag: 111240, sign: true });\n    data.append(FP16x16 { mag: 95369, sign: false });\n    data.append(FP16x16 { mag: 29800, sign: false });\n    data.append(FP16x16 { mag: 18974, sign: false });\n    data.append(FP16x16 { mag: 41527, sign: true });\n    data.append(FP16x16 { mag: 12256, sign: false });\n    data.append(FP16x16 { mag: 28697, sign: false });\n    data.append(FP16x16 { mag: 92475, sign: true });\n    data.append(FP16x16 { mag: 90746, sign: true });\n    data.append(FP16x16 { mag: 4496, sign: true });\n    data.append(FP16x16 { mag: 6464, sign: false });\n    data.append(FP16x16 { mag: 45570, sign: true });\n    data.append(FP16x16 { mag: 28209, sign: true });\n    data.append(FP16x16 { mag: 33084, sign: false });\n    data.append(FP16x16 { mag: 131340, sign: false });\n    data.append(FP16x16 { mag: 15928, sign: true });\n    data.append(FP16x16 { mag: 13786, sign: true });\n    data.append(FP16x16 { mag: 89832, sign: false });\n    data.append(FP16x16 { mag: 59414, sign: true });\n    data.append(FP16x16 { mag: 27186, sign: true });\n    data.append(FP16x16 { mag: 57062, sign: false });\n    data.append(FP16x16 { mag: 8290, sign: false });\n    data.append(FP16x16 { mag: 23747, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis-4/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 81938, sign: false });\n    data.append(FP16x16 { mag: 139115, sign: true });\n    data.append(FP16x16 { mag: 99625, sign: false });\n    data.append(FP16x16 { mag: 42553, sign: false });\n    data.append(FP16x16 { mag: 63807, sign: true });\n    data.append(FP16x16 { mag: 29251, sign: false });\n    data.append(FP16x16 { mag: 74903, sign: true });\n    data.append(FP16x16 { mag: 9937, sign: true });\n    data.append(FP16x16 { mag: 65116, sign: true });\n    data.append(FP16x16 { mag: 48943, sign: false });\n    data.append(FP16x16 { mag: 37524, sign: false });\n    data.append(FP16x16 { mag: 77082, sign: false });\n    data.append(FP16x16 { mag: 57309, sign: false });\n    data.append(FP16x16 { mag: 3013, sign: true });\n    data.append(FP16x16 { mag: 22472, sign: false });\n    data.append(FP16x16 { mag: 68481, sign: false });\n    data.append(FP16x16 { mag: 47521, sign: true });\n    data.append(FP16x16 { mag: 29144, sign: false });\n    data.append(FP16x16 { mag: 11016, sign: false });\n    data.append(FP16x16 { mag: 63886, sign: true });\n    data.append(FP16x16 { mag: 88094, sign: false });\n    data.append(FP16x16 { mag: 112894, sign: true });\n    data.append(FP16x16 { mag: 7732, sign: false });\n    data.append(FP16x16 { mag: 45680, sign: true });\n    data.append(FP16x16 { mag: 52166, sign: false });\n    data.append(FP16x16 { mag: 135141, sign: true });\n    data.append(FP16x16 { mag: 18324, sign: true });\n    data.append(FP16x16 { mag: 201528, sign: false });\n    data.append(FP16x16 { mag: 125050, sign: false });\n    data.append(FP16x16 { mag: 50933, sign: true });\n    data.append(FP16x16 { mag: 64223, sign: true });\n    data.append(FP16x16 { mag: 52706, sign: false });\n    data.append(FP16x16 { mag: 106918, sign: false });\n    data.append(FP16x16 { mag: 134854, sign: false });\n    data.append(FP16x16 { mag: 6678, sign: false });\n    data.append(FP16x16 { mag: 100030, sign: true });\n    data.append(FP16x16 { mag: 8001, sign: false });\n    data.append(FP16x16 { mag: 75425, sign: true });\n    data.append(FP16x16 { mag: 3641, sign: false });\n    data.append(FP16x16 { mag: 20349, sign: true });\n    data.append(FP16x16 { mag: 33423, sign: true });\n    data.append(FP16x16 { mag: 135434, sign: false });\n    data.append(FP16x16 { mag: 268826, sign: true });\n    data.append(FP16x16 { mag: 9384, sign: false });\n    data.append(FP16x16 { mag: 42989, sign: true });\n    data.append(FP16x16 { mag: 40596, sign: false });\n    data.append(FP16x16 { mag: 27643, sign: true });\n    data.append(FP16x16 { mag: 14881, sign: false });\n    data.append(FP16x16 { mag: 33184, sign: false });\n    data.append(FP16x16 { mag: 245527, sign: false });\n    data.append(FP16x16 { mag: 12844, sign: false });\n    data.append(FP16x16 { mag: 36484, sign: false });\n    data.append(FP16x16 { mag: 43540, sign: true });\n    data.append(FP16x16 { mag: 98782, sign: false });\n    data.append(FP16x16 { mag: 91559, sign: true });\n    data.append(FP16x16 { mag: 175239, sign: true });\n    data.append(FP16x16 { mag: 36924, sign: true });\n    data.append(FP16x16 { mag: 69880, sign: true });\n    data.append(FP16x16 { mag: 218008, sign: false });\n    data.append(FP16x16 { mag: 89765, sign: true });\n    data.append(FP16x16 { mag: 37583, sign: false });\n    data.append(FP16x16 { mag: 40273, sign: false });\n    data.append(FP16x16 { mag: 47428, sign: true });\n    data.append(FP16x16 { mag: 33322, sign: true });\n    data.append(FP16x16 { mag: 53002, sign: true });\n    data.append(FP16x16 { mag: 51571, sign: false });\n    data.append(FP16x16 { mag: 43023, sign: true });\n    data.append(FP16x16 { mag: 180611, sign: false });\n    data.append(FP16x16 { mag: 27436, sign: false });\n    data.append(FP16x16 { mag: 82088, sign: true });\n    data.append(FP16x16 { mag: 49075, sign: true });\n    data.append(FP16x16 { mag: 93116, sign: true });\n    data.append(FP16x16 { mag: 24713, sign: true });\n    data.append(FP16x16 { mag: 57986, sign: true });\n    data.append(FP16x16 { mag: 11641, sign: false });\n    data.append(FP16x16 { mag: 87906, sign: true });\n    data.append(FP16x16 { mag: 73854, sign: false });\n    data.append(FP16x16 { mag: 22022, sign: true });\n    data.append(FP16x16 { mag: 31528, sign: true });\n    data.append(FP16x16 { mag: 151422, sign: true });\n    data.append(FP16x16 { mag: 270761, sign: true });\n    data.append(FP16x16 { mag: 37881, sign: false });\n    data.append(FP16x16 { mag: 81795, sign: true });\n    data.append(FP16x16 { mag: 65199, sign: false });\n    data.append(FP16x16 { mag: 89952, sign: true });\n    data.append(FP16x16 { mag: 36152, sign: false });\n    data.append(FP16x16 { mag: 20482, sign: true });\n    data.append(FP16x16 { mag: 296268, sign: true });\n    data.append(FP16x16 { mag: 79775, sign: true });\n    data.append(FP16x16 { mag: 66513, sign: false });\n    data.append(FP16x16 { mag: 107842, sign: false });\n    data.append(FP16x16 { mag: 37504, sign: false });\n    data.append(FP16x16 { mag: 170624, sign: false });\n    data.append(FP16x16 { mag: 52118, sign: false });\n    data.append(FP16x16 { mag: 43525, sign: false });\n    data.append(FP16x16 { mag: 138068, sign: false });\n    data.append(FP16x16 { mag: 92822, sign: true });\n    data.append(FP16x16 { mag: 155459, sign: true });\n    data.append(FP16x16 { mag: 101038, sign: false });\n    data.append(FP16x16 { mag: 45944, sign: false });\n    data.append(FP16x16 { mag: 14639, sign: true });\n    data.append(FP16x16 { mag: 30883, sign: true });\n    data.append(FP16x16 { mag: 262024, sign: false });\n    data.append(FP16x16 { mag: 30507, sign: true });\n    data.append(FP16x16 { mag: 43715, sign: true });\n    data.append(FP16x16 { mag: 84662, sign: true });\n    data.append(FP16x16 { mag: 63901, sign: false });\n    data.append(FP16x16 { mag: 3913, sign: false });\n    data.append(FP16x16 { mag: 40400, sign: true });\n    data.append(FP16x16 { mag: 36018, sign: true });\n    data.append(FP16x16 { mag: 49780, sign: true });\n    data.append(FP16x16 { mag: 146468, sign: false });\n    data.append(FP16x16 { mag: 32554, sign: true });\n    data.append(FP16x16 { mag: 39291, sign: true });\n    data.append(FP16x16 { mag: 93325, sign: false });\n    data.append(FP16x16 { mag: 216, sign: false });\n    data.append(FP16x16 { mag: 67978, sign: true });\n    data.append(FP16x16 { mag: 97710, sign: false });\n    data.append(FP16x16 { mag: 19520, sign: false });\n    data.append(FP16x16 { mag: 6998, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis0.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis0() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(0), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis0/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4232019, sign: false });\n    data.append(FP8x23 { mag: 9414959, sign: false });\n    data.append(FP8x23 { mag: 5324792, sign: true });\n    data.append(FP8x23 { mag: 128763, sign: true });\n    data.append(FP8x23 { mag: 11769934, sign: true });\n    data.append(FP8x23 { mag: 5782115, sign: true });\n    data.append(FP8x23 { mag: 5288267, sign: false });\n    data.append(FP8x23 { mag: 2114632, sign: true });\n    data.append(FP8x23 { mag: 17281796, sign: true });\n    data.append(FP8x23 { mag: 4231838, sign: false });\n    data.append(FP8x23 { mag: 8315803, sign: true });\n    data.append(FP8x23 { mag: 3959008, sign: true });\n    data.append(FP8x23 { mag: 8316806, sign: false });\n    data.append(FP8x23 { mag: 10504447, sign: false });\n    data.append(FP8x23 { mag: 11309414, sign: false });\n    data.append(FP8x23 { mag: 4354704, sign: false });\n    data.append(FP8x23 { mag: 11441280, sign: false });\n    data.append(FP8x23 { mag: 1670098, sign: false });\n    data.append(FP8x23 { mag: 5359432, sign: false });\n    data.append(FP8x23 { mag: 9566567, sign: false });\n    data.append(FP8x23 { mag: 862169, sign: false });\n    data.append(FP8x23 { mag: 3592849, sign: true });\n    data.append(FP8x23 { mag: 6354821, sign: false });\n    data.append(FP8x23 { mag: 15286515, sign: true });\n    data.append(FP8x23 { mag: 6568954, sign: false });\n    data.append(FP8x23 { mag: 8783522, sign: true });\n    data.append(FP8x23 { mag: 13773893, sign: true });\n    data.append(FP8x23 { mag: 492845, sign: true });\n    data.append(FP8x23 { mag: 4346782, sign: true });\n    data.append(FP8x23 { mag: 13743203, sign: false });\n    data.append(FP8x23 { mag: 18494036, sign: true });\n    data.append(FP8x23 { mag: 698252, sign: false });\n    data.append(FP8x23 { mag: 1015292, sign: false });\n    data.append(FP8x23 { mag: 24111832, sign: true });\n    data.append(FP8x23 { mag: 9435828, sign: false });\n    data.append(FP8x23 { mag: 314313, sign: true });\n    data.append(FP8x23 { mag: 1064978, sign: false });\n    data.append(FP8x23 { mag: 5250829, sign: true });\n    data.append(FP8x23 { mag: 12141758, sign: false });\n    data.append(FP8x23 { mag: 10504567, sign: false });\n    data.append(FP8x23 { mag: 3704533, sign: true });\n    data.append(FP8x23 { mag: 2768767, sign: false });\n    data.append(FP8x23 { mag: 2231142, sign: true });\n    data.append(FP8x23 { mag: 463985, sign: true });\n    data.append(FP8x23 { mag: 3370932, sign: false });\n    data.append(FP8x23 { mag: 7362219, sign: true });\n    data.append(FP8x23 { mag: 764387, sign: false });\n    data.append(FP8x23 { mag: 1457716, sign: false });\n    data.append(FP8x23 { mag: 126049, sign: true });\n    data.append(FP8x23 { mag: 3918899, sign: true });\n    data.append(FP8x23 { mag: 270524, sign: true });\n    data.append(FP8x23 { mag: 11137441, sign: true });\n    data.append(FP8x23 { mag: 1444337, sign: true });\n    data.append(FP8x23 { mag: 8488962, sign: true });\n    data.append(FP8x23 { mag: 7123331, sign: false });\n    data.append(FP8x23 { mag: 8201855, sign: false });\n    data.append(FP8x23 { mag: 6222805, sign: true });\n    data.append(FP8x23 { mag: 6386507, sign: true });\n    data.append(FP8x23 { mag: 290309, sign: true });\n    data.append(FP8x23 { mag: 11420835, sign: true });\n    data.append(FP8x23 { mag: 13222036, sign: true });\n    data.append(FP8x23 { mag: 9057537, sign: true });\n    data.append(FP8x23 { mag: 8642815, sign: true });\n    data.append(FP8x23 { mag: 4838046, sign: false });\n    data.append(FP8x23 { mag: 1764850, sign: false });\n    data.append(FP8x23 { mag: 3928761, sign: true });\n    data.append(FP8x23 { mag: 7064763, sign: true });\n    data.append(FP8x23 { mag: 892586, sign: false });\n    data.append(FP8x23 { mag: 1449, sign: true });\n    data.append(FP8x23 { mag: 3997728, sign: true });\n    data.append(FP8x23 { mag: 1617748, sign: true });\n    data.append(FP8x23 { mag: 6798862, sign: true });\n    data.append(FP8x23 { mag: 5931349, sign: true });\n    data.append(FP8x23 { mag: 3729811, sign: false });\n    data.append(FP8x23 { mag: 855198, sign: false });\n    data.append(FP8x23 { mag: 8389855, sign: false });\n    data.append(FP8x23 { mag: 26774346, sign: false });\n    data.append(FP8x23 { mag: 2663191, sign: true });\n    data.append(FP8x23 { mag: 478906, sign: true });\n    data.append(FP8x23 { mag: 3544579, sign: true });\n    data.append(FP8x23 { mag: 4402933, sign: true });\n    data.append(FP8x23 { mag: 1577028, sign: false });\n    data.append(FP8x23 { mag: 7590409, sign: true });\n    data.append(FP8x23 { mag: 5962040, sign: false });\n    data.append(FP8x23 { mag: 3561389, sign: true });\n    data.append(FP8x23 { mag: 2575361, sign: true });\n    data.append(FP8x23 { mag: 12645527, sign: false });\n    data.append(FP8x23 { mag: 1847218, sign: false });\n    data.append(FP8x23 { mag: 2636782, sign: false });\n    data.append(FP8x23 { mag: 4503268, sign: true });\n    data.append(FP8x23 { mag: 10772561, sign: false });\n    data.append(FP8x23 { mag: 2286333, sign: false });\n    data.append(FP8x23 { mag: 5685346, sign: true });\n    data.append(FP8x23 { mag: 2568535, sign: false });\n    data.append(FP8x23 { mag: 2808778, sign: false });\n    data.append(FP8x23 { mag: 6059521, sign: true });\n    data.append(FP8x23 { mag: 5806019, sign: false });\n    data.append(FP8x23 { mag: 3326381, sign: false });\n    data.append(FP8x23 { mag: 11284680, sign: true });\n    data.append(FP8x23 { mag: 3394, sign: true });\n    data.append(FP8x23 { mag: 6295530, sign: false });\n    data.append(FP8x23 { mag: 676486, sign: false });\n    data.append(FP8x23 { mag: 3288573, sign: false });\n    data.append(FP8x23 { mag: 9587575, sign: false });\n    data.append(FP8x23 { mag: 5976725, sign: false });\n    data.append(FP8x23 { mag: 3165322, sign: false });\n    data.append(FP8x23 { mag: 14451783, sign: false });\n    data.append(FP8x23 { mag: 957597, sign: true });\n    data.append(FP8x23 { mag: 9305994, sign: true });\n    data.append(FP8x23 { mag: 9337821, sign: false });\n    data.append(FP8x23 { mag: 11604104, sign: true });\n    data.append(FP8x23 { mag: 12009648, sign: false });\n    data.append(FP8x23 { mag: 11962518, sign: false });\n    data.append(FP8x23 { mag: 9762105, sign: false });\n    data.append(FP8x23 { mag: 16290091, sign: false });\n    data.append(FP8x23 { mag: 2582084, sign: true });\n    data.append(FP8x23 { mag: 11396864, sign: false });\n    data.append(FP8x23 { mag: 2647521, sign: true });\n    data.append(FP8x23 { mag: 5459088, sign: true });\n    data.append(FP8x23 { mag: 6242592, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis0/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 182533, sign: false });\n    data.append(FP8x23 { mag: 4606354, sign: false });\n    data.append(FP8x23 { mag: 2606279, sign: false });\n    data.append(FP8x23 { mag: 1836291, sign: true });\n    data.append(FP8x23 { mag: 776462, sign: true });\n    data.append(FP8x23 { mag: 4201430, sign: true });\n    data.append(FP8x23 { mag: 8864747, sign: true });\n    data.append(FP8x23 { mag: 21878440, sign: false });\n    data.append(FP8x23 { mag: 19190702, sign: false });\n    data.append(FP8x23 { mag: 11081136, sign: true });\n    data.append(FP8x23 { mag: 1846544, sign: true });\n    data.append(FP8x23 { mag: 2650079, sign: false });\n    data.append(FP8x23 { mag: 10380200, sign: true });\n    data.append(FP8x23 { mag: 16036666, sign: false });\n    data.append(FP8x23 { mag: 1787011, sign: true });\n    data.append(FP8x23 { mag: 5182057, sign: true });\n    data.append(FP8x23 { mag: 4948965, sign: false });\n    data.append(FP8x23 { mag: 1044138, sign: true });\n    data.append(FP8x23 { mag: 8227229, sign: false });\n    data.append(FP8x23 { mag: 6051373, sign: false });\n    data.append(FP8x23 { mag: 11195256, sign: true });\n    data.append(FP8x23 { mag: 5163053, sign: true });\n    data.append(FP8x23 { mag: 6205135, sign: true });\n    data.append(FP8x23 { mag: 1407165, sign: true });\n    data.append(FP8x23 { mag: 9476520, sign: true });\n    data.append(FP8x23 { mag: 4988598, sign: false });\n    data.append(FP8x23 { mag: 2193447, sign: false });\n    data.append(FP8x23 { mag: 1745083, sign: true });\n    data.append(FP8x23 { mag: 1212564, sign: true });\n    data.append(FP8x23 { mag: 4135245, sign: false });\n    data.append(FP8x23 { mag: 17634618, sign: true });\n    data.append(FP8x23 { mag: 10822064, sign: true });\n    data.append(FP8x23 { mag: 1364135, sign: true });\n    data.append(FP8x23 { mag: 3398124, sign: false });\n    data.append(FP8x23 { mag: 6510555, sign: false });\n    data.append(FP8x23 { mag: 2305050, sign: true });\n    data.append(FP8x23 { mag: 5031243, sign: true });\n    data.append(FP8x23 { mag: 7136078, sign: false });\n    data.append(FP8x23 { mag: 13141474, sign: false });\n    data.append(FP8x23 { mag: 4393622, sign: true });\n    data.append(FP8x23 { mag: 19109898, sign: true });\n    data.append(FP8x23 { mag: 1560166, sign: false });\n    data.append(FP8x23 { mag: 19533432, sign: true });\n    data.append(FP8x23 { mag: 3037078, sign: false });\n    data.append(FP8x23 { mag: 3096676, sign: false });\n    data.append(FP8x23 { mag: 738457, sign: true });\n    data.append(FP8x23 { mag: 3674711, sign: false });\n    data.append(FP8x23 { mag: 5430008, sign: false });\n    data.append(FP8x23 { mag: 736298, sign: true });\n    data.append(FP8x23 { mag: 2054313, sign: false });\n    data.append(FP8x23 { mag: 12914497, sign: false });\n    data.append(FP8x23 { mag: 13798454, sign: false });\n    data.append(FP8x23 { mag: 5461689, sign: false });\n    data.append(FP8x23 { mag: 4431607, sign: true });\n    data.append(FP8x23 { mag: 3866629, sign: false });\n    data.append(FP8x23 { mag: 7574228, sign: false });\n    data.append(FP8x23 { mag: 5892835, sign: true });\n    data.append(FP8x23 { mag: 5213653, sign: false });\n    data.append(FP8x23 { mag: 13585100, sign: true });\n    data.append(FP8x23 { mag: 5868984, sign: true });\n    data.append(FP8x23 { mag: 10449856, sign: true });\n    data.append(FP8x23 { mag: 21849164, sign: true });\n    data.append(FP8x23 { mag: 794675, sign: false });\n    data.append(FP8x23 { mag: 1398016, sign: true });\n    data.append(FP8x23 { mag: 3721883, sign: true });\n    data.append(FP8x23 { mag: 8554286, sign: false });\n    data.append(FP8x23 { mag: 8999503, sign: true });\n    data.append(FP8x23 { mag: 1477321, sign: true });\n    data.append(FP8x23 { mag: 1134818, sign: true });\n    data.append(FP8x23 { mag: 16218611, sign: true });\n    data.append(FP8x23 { mag: 3781667, sign: true });\n    data.append(FP8x23 { mag: 6030933, sign: true });\n    data.append(FP8x23 { mag: 7143546, sign: false });\n    data.append(FP8x23 { mag: 2401444, sign: false });\n    data.append(FP8x23 { mag: 9745432, sign: true });\n    data.append(FP8x23 { mag: 8637640, sign: true });\n    data.append(FP8x23 { mag: 3338635, sign: true });\n    data.append(FP8x23 { mag: 5511234, sign: true });\n    data.append(FP8x23 { mag: 8132204, sign: false });\n    data.append(FP8x23 { mag: 11108457, sign: false });\n    data.append(FP8x23 { mag: 8013075, sign: true });\n    data.append(FP8x23 { mag: 5479938, sign: true });\n    data.append(FP8x23 { mag: 135261, sign: true });\n    data.append(FP8x23 { mag: 4611320, sign: false });\n    data.append(FP8x23 { mag: 14790095, sign: false });\n    data.append(FP8x23 { mag: 524231, sign: false });\n    data.append(FP8x23 { mag: 6893361, sign: false });\n    data.append(FP8x23 { mag: 7042414, sign: true });\n    data.append(FP8x23 { mag: 3401594, sign: true });\n    data.append(FP8x23 { mag: 8037410, sign: true });\n    data.append(FP8x23 { mag: 18738864, sign: true });\n    data.append(FP8x23 { mag: 4145636, sign: true });\n    data.append(FP8x23 { mag: 15480272, sign: false });\n    data.append(FP8x23 { mag: 1088523, sign: false });\n    data.append(FP8x23 { mag: 13142920, sign: true });\n    data.append(FP8x23 { mag: 16094435, sign: true });\n    data.append(FP8x23 { mag: 9691265, sign: true });\n    data.append(FP8x23 { mag: 2069802, sign: false });\n    data.append(FP8x23 { mag: 3346902, sign: true });\n    data.append(FP8x23 { mag: 6260557, sign: false });\n    data.append(FP8x23 { mag: 2084721, sign: false });\n    data.append(FP8x23 { mag: 5605861, sign: true });\n    data.append(FP8x23 { mag: 7801239, sign: true });\n    data.append(FP8x23 { mag: 14879763, sign: false });\n    data.append(FP8x23 { mag: 11315182, sign: false });\n    data.append(FP8x23 { mag: 21418632, sign: true });\n    data.append(FP8x23 { mag: 2158442, sign: true });\n    data.append(FP8x23 { mag: 12606992, sign: false });\n    data.append(FP8x23 { mag: 11320753, sign: true });\n    data.append(FP8x23 { mag: 5226692, sign: true });\n    data.append(FP8x23 { mag: 13332767, sign: true });\n    data.append(FP8x23 { mag: 10821589, sign: true });\n    data.append(FP8x23 { mag: 17468832, sign: true });\n    data.append(FP8x23 { mag: 4250356, sign: false });\n    data.append(FP8x23 { mag: 2191593, sign: false });\n    data.append(FP8x23 { mag: 11413254, sign: false });\n    data.append(FP8x23 { mag: 3410953, sign: false });\n    data.append(FP8x23 { mag: 7124555, sign: true });\n    data.append(FP8x23 { mag: 5373506, sign: false });\n    data.append(FP8x23 { mag: 1372494, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 7037577, sign: true });\n    data.append(FP8x23 { mag: 14724418, sign: true });\n    data.append(FP8x23 { mag: 3022586, sign: false });\n    data.append(FP8x23 { mag: 1787971, sign: true });\n    data.append(FP8x23 { mag: 17806604, sign: true });\n    data.append(FP8x23 { mag: 10204453, sign: true });\n    data.append(FP8x23 { mag: 7120407, sign: true });\n    data.append(FP8x23 { mag: 24452990, sign: false });\n    data.append(FP8x23 { mag: 26784136, sign: false });\n    data.append(FP8x23 { mag: 14295083, sign: true });\n    data.append(FP8x23 { mag: 5218924, sign: false });\n    data.append(FP8x23 { mag: 2070471, sign: true });\n    data.append(FP8x23 { mag: 8872511, sign: true });\n    data.append(FP8x23 { mag: 5973684, sign: false });\n    data.append(FP8x23 { mag: 6132282, sign: false });\n    data.append(FP8x23 { mag: 225177, sign: false });\n    data.append(FP8x23 { mag: 64604, sign: true });\n    data.append(FP8x23 { mag: 1153317, sign: false });\n    data.append(FP8x23 { mag: 5677642, sign: false });\n    data.append(FP8x23 { mag: 7078033, sign: true });\n    data.append(FP8x23 { mag: 11042504, sign: true });\n    data.append(FP8x23 { mag: 4603322, sign: true });\n    data.append(FP8x23 { mag: 6567126, sign: true });\n    data.append(FP8x23 { mag: 12650194, sign: false });\n    data.append(FP8x23 { mag: 11303708, sign: true });\n    data.append(FP8x23 { mag: 8870792, sign: false });\n    data.append(FP8x23 { mag: 10416405, sign: true });\n    data.append(FP8x23 { mag: 1456034, sign: true });\n    data.append(FP8x23 { mag: 2767, sign: false });\n    data.append(FP8x23 { mag: 8707088, sign: true });\n    data.append(FP8x23 { mag: 22040482, sign: false });\n    data.append(FP8x23 { mag: 10160538, sign: true });\n    data.append(FP8x23 { mag: 3218779, sign: true });\n    data.append(FP8x23 { mag: 47819348, sign: true });\n    data.append(FP8x23 { mag: 12301572, sign: false });\n    data.append(FP8x23 { mag: 2039057, sign: true });\n    data.append(FP8x23 { mag: 3248913, sign: true });\n    data.append(FP8x23 { mag: 1237417, sign: false });\n    data.append(FP8x23 { mag: 31046658, sign: false });\n    data.append(FP8x23 { mag: 17809218, sign: true });\n    data.append(FP8x23 { mag: 20730340, sign: true });\n    data.append(FP8x23 { mag: 5032377, sign: true });\n    data.append(FP8x23 { mag: 20401240, sign: true });\n    data.append(FP8x23 { mag: 3165594, sign: false });\n    data.append(FP8x23 { mag: 280886, sign: true });\n    data.append(FP8x23 { mag: 3396857, sign: false });\n    data.append(FP8x23 { mag: 4682179, sign: false });\n    data.append(FP8x23 { mag: 4616465, sign: false });\n    data.append(FP8x23 { mag: 745478, sign: true });\n    data.append(FP8x23 { mag: 1001749, sign: false });\n    data.append(FP8x23 { mag: 12734723, sign: false });\n    data.append(FP8x23 { mag: 3225686, sign: false });\n    data.append(FP8x23 { mag: 5270924, sign: false });\n    data.append(FP8x23 { mag: 10999454, sign: true });\n    data.append(FP8x23 { mag: 6343230, sign: false });\n    data.append(FP8x23 { mag: 10666792, sign: false });\n    data.append(FP8x23 { mag: 12757594, sign: true });\n    data.append(FP8x23 { mag: 7665874, sign: false });\n    data.append(FP8x23 { mag: 14022398, sign: true });\n    data.append(FP8x23 { mag: 8373909, sign: true });\n    data.append(FP8x23 { mag: 13868518, sign: true });\n    data.append(FP8x23 { mag: 2214998, sign: true });\n    data.append(FP8x23 { mag: 18125466, sign: true });\n    data.append(FP8x23 { mag: 5735991, sign: true });\n    data.append(FP8x23 { mag: 22940, sign: false });\n    data.append(FP8x23 { mag: 18790208, sign: false });\n    data.append(FP8x23 { mag: 15120878, sign: true });\n    data.append(FP8x23 { mag: 1545451, sign: true });\n    data.append(FP8x23 { mag: 1134904, sign: true });\n    data.append(FP8x23 { mag: 17024186, sign: true });\n    data.append(FP8x23 { mag: 4435868, sign: true });\n    data.append(FP8x23 { mag: 1831345, sign: true });\n    data.append(FP8x23 { mag: 12326800, sign: false });\n    data.append(FP8x23 { mag: 2081182, sign: false });\n    data.append(FP8x23 { mag: 10111056, sign: true });\n    data.append(FP8x23 { mag: 11797644, sign: true });\n    data.append(FP8x23 { mag: 13957666, sign: true });\n    data.append(FP8x23 { mag: 9751228, sign: true });\n    data.append(FP8x23 { mag: 8166369, sign: false });\n    data.append(FP8x23 { mag: 14472534, sign: false });\n    data.append(FP8x23 { mag: 5787050, sign: true });\n    data.append(FP8x23 { mag: 5167903, sign: true });\n    data.append(FP8x23 { mag: 2354272, sign: false });\n    data.append(FP8x23 { mag: 3538191, sign: true });\n    data.append(FP8x23 { mag: 16882428, sign: false });\n    data.append(FP8x23 { mag: 3591225, sign: false });\n    data.append(FP8x23 { mag: 26898508, sign: false });\n    data.append(FP8x23 { mag: 10517529, sign: true });\n    data.append(FP8x23 { mag: 2174513, sign: false });\n    data.append(FP8x23 { mag: 8749099, sign: true });\n    data.append(FP8x23 { mag: 24184572, sign: true });\n    data.append(FP8x23 { mag: 2126525, sign: true });\n    data.append(FP8x23 { mag: 23430856, sign: false });\n    data.append(FP8x23 { mag: 4520174, sign: false });\n    data.append(FP8x23 { mag: 13652877, sign: true });\n    data.append(FP8x23 { mag: 12283456, sign: true });\n    data.append(FP8x23 { mag: 10740277, sign: true });\n    data.append(FP8x23 { mag: 4411417, sign: false });\n    data.append(FP8x23 { mag: 10658245, sign: true });\n    data.append(FP8x23 { mag: 6258550, sign: false });\n    data.append(FP8x23 { mag: 597025, sign: true });\n    data.append(FP8x23 { mag: 5697438, sign: true });\n    data.append(FP8x23 { mag: 9281796, sign: true });\n    data.append(FP8x23 { mag: 15249477, sign: false });\n    data.append(FP8x23 { mag: 18532372, sign: false });\n    data.append(FP8x23 { mag: 16837466, sign: true });\n    data.append(FP8x23 { mag: 1797340, sign: false });\n    data.append(FP8x23 { mag: 12228078, sign: false });\n    data.append(FP8x23 { mag: 6983374, sign: true });\n    data.append(FP8x23 { mag: 8255684, sign: true });\n    data.append(FP8x23 { mag: 21276412, sign: true });\n    data.append(FP8x23 { mag: 19283468, sign: true });\n    data.append(FP8x23 { mag: 15394488, sign: true });\n    data.append(FP8x23 { mag: 6857165, sign: false });\n    data.append(FP8x23 { mag: 1110300, sign: true });\n    data.append(FP8x23 { mag: 11658292, sign: false });\n    data.append(FP8x23 { mag: 718357, sign: true });\n    data.append(FP8x23 { mag: 11227997, sign: true });\n    data.append(FP8x23 { mag: 4305150, sign: false });\n    data.append(FP8x23 { mag: 780804, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(1), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 2649509, sign: false });\n    data.append(FP8x23 { mag: 7144735, sign: false });\n    data.append(FP8x23 { mag: 3358040, sign: true });\n    data.append(FP8x23 { mag: 9386912, sign: true });\n    data.append(FP8x23 { mag: 13500097, sign: true });\n    data.append(FP8x23 { mag: 5270301, sign: false });\n    data.append(FP8x23 { mag: 110414, sign: true });\n    data.append(FP8x23 { mag: 9924386, sign: true });\n    data.append(FP8x23 { mag: 15635640, sign: false });\n    data.append(FP8x23 { mag: 1427528, sign: false });\n    data.append(FP8x23 { mag: 2846589, sign: false });\n    data.append(FP8x23 { mag: 1541675, sign: true });\n    data.append(FP8x23 { mag: 12896779, sign: false });\n    data.append(FP8x23 { mag: 8095688, sign: false });\n    data.append(FP8x23 { mag: 15709178, sign: true });\n    data.append(FP8x23 { mag: 3272469, sign: false });\n    data.append(FP8x23 { mag: 3726665, sign: false });\n    data.append(FP8x23 { mag: 18764, sign: true });\n    data.append(FP8x23 { mag: 1073322, sign: false });\n    data.append(FP8x23 { mag: 6797195, sign: false });\n    data.append(FP8x23 { mag: 5732947, sign: false });\n    data.append(FP8x23 { mag: 4820546, sign: false });\n    data.append(FP8x23 { mag: 3081034, sign: false });\n    data.append(FP8x23 { mag: 14074043, sign: true });\n    data.append(FP8x23 { mag: 6461992, sign: false });\n    data.append(FP8x23 { mag: 13566343, sign: true });\n    data.append(FP8x23 { mag: 491369, sign: false });\n    data.append(FP8x23 { mag: 288012, sign: false });\n    data.append(FP8x23 { mag: 10414907, sign: false });\n    data.append(FP8x23 { mag: 11528715, sign: false });\n    data.append(FP8x23 { mag: 3682921, sign: false });\n    data.append(FP8x23 { mag: 12963271, sign: false });\n    data.append(FP8x23 { mag: 263060, sign: true });\n    data.append(FP8x23 { mag: 5531121, sign: false });\n    data.append(FP8x23 { mag: 19149566, sign: false });\n    data.append(FP8x23 { mag: 2802384, sign: true });\n    data.append(FP8x23 { mag: 8137323, sign: true });\n    data.append(FP8x23 { mag: 2070264, sign: false });\n    data.append(FP8x23 { mag: 2892212, sign: false });\n    data.append(FP8x23 { mag: 2728473, sign: true });\n    data.append(FP8x23 { mag: 3360785, sign: false });\n    data.append(FP8x23 { mag: 1874124, sign: false });\n    data.append(FP8x23 { mag: 1551380, sign: false });\n    data.append(FP8x23 { mag: 4138289, sign: true });\n    data.append(FP8x23 { mag: 18117802, sign: true });\n    data.append(FP8x23 { mag: 1020022, sign: true });\n    data.append(FP8x23 { mag: 5212319, sign: true });\n    data.append(FP8x23 { mag: 705204, sign: false });\n    data.append(FP8x23 { mag: 3437416, sign: false });\n    data.append(FP8x23 { mag: 11732816, sign: false });\n    data.append(FP8x23 { mag: 13791144, sign: true });\n    data.append(FP8x23 { mag: 98925, sign: true });\n    data.append(FP8x23 { mag: 7643209, sign: false });\n    data.append(FP8x23 { mag: 101893, sign: true });\n    data.append(FP8x23 { mag: 3594931, sign: true });\n    data.append(FP8x23 { mag: 12445462, sign: false });\n    data.append(FP8x23 { mag: 6342234, sign: true });\n    data.append(FP8x23 { mag: 12620105, sign: false });\n    data.append(FP8x23 { mag: 5220821, sign: true });\n    data.append(FP8x23 { mag: 8501779, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1141568, sign: false });\n    data.append(FP8x23 { mag: 3539686, sign: false });\n    data.append(FP8x23 { mag: 19183412, sign: true });\n    data.append(FP8x23 { mag: 6702357, sign: true });\n    data.append(FP8x23 { mag: 18341166, sign: true });\n    data.append(FP8x23 { mag: 2085003, sign: false });\n    data.append(FP8x23 { mag: 5754160, sign: true });\n    data.append(FP8x23 { mag: 6418104, sign: false });\n    data.append(FP8x23 { mag: 5327939, sign: false });\n    data.append(FP8x23 { mag: 1071055, sign: true });\n    data.append(FP8x23 { mag: 8731756, sign: true });\n    data.append(FP8x23 { mag: 6458415, sign: false });\n    data.append(FP8x23 { mag: 285981, sign: true });\n    data.append(FP8x23 { mag: 10557919, sign: false });\n    data.append(FP8x23 { mag: 1513612, sign: true });\n    data.append(FP8x23 { mag: 15288170, sign: true });\n    data.append(FP8x23 { mag: 3484741, sign: false });\n    data.append(FP8x23 { mag: 9718607, sign: false });\n    data.append(FP8x23 { mag: 12358125, sign: true });\n    data.append(FP8x23 { mag: 15954180, sign: false });\n    data.append(FP8x23 { mag: 262601, sign: false });\n    data.append(FP8x23 { mag: 5672420, sign: false });\n    data.append(FP8x23 { mag: 4338296, sign: true });\n    data.append(FP8x23 { mag: 1830635, sign: false });\n    data.append(FP8x23 { mag: 6483353, sign: false });\n    data.append(FP8x23 { mag: 6624924, sign: false });\n    data.append(FP8x23 { mag: 24104034, sign: false });\n    data.append(FP8x23 { mag: 10195068, sign: true });\n    data.append(FP8x23 { mag: 9134898, sign: false });\n    data.append(FP8x23 { mag: 16650777, sign: true });\n    data.append(FP8x23 { mag: 623710, sign: true });\n    data.append(FP8x23 { mag: 10605975, sign: true });\n    data.append(FP8x23 { mag: 6924507, sign: false });\n    data.append(FP8x23 { mag: 6210575, sign: true });\n    data.append(FP8x23 { mag: 17054160, sign: false });\n    data.append(FP8x23 { mag: 6280133, sign: true });\n    data.append(FP8x23 { mag: 9148351, sign: true });\n    data.append(FP8x23 { mag: 7262568, sign: false });\n    data.append(FP8x23 { mag: 6099670, sign: false });\n    data.append(FP8x23 { mag: 2873259, sign: true });\n    data.append(FP8x23 { mag: 1290482, sign: true });\n    data.append(FP8x23 { mag: 7829370, sign: true });\n    data.append(FP8x23 { mag: 12044643, sign: false });\n    data.append(FP8x23 { mag: 3011473, sign: true });\n    data.append(FP8x23 { mag: 6080298, sign: true });\n    data.append(FP8x23 { mag: 2388015, sign: true });\n    data.append(FP8x23 { mag: 9140926, sign: true });\n    data.append(FP8x23 { mag: 6684113, sign: true });\n    data.append(FP8x23 { mag: 43961, sign: false });\n    data.append(FP8x23 { mag: 9137080, sign: false });\n    data.append(FP8x23 { mag: 7920313, sign: false });\n    data.append(FP8x23 { mag: 8783942, sign: true });\n    data.append(FP8x23 { mag: 2190876, sign: true });\n    data.append(FP8x23 { mag: 9310159, sign: true });\n    data.append(FP8x23 { mag: 12063621, sign: true });\n    data.append(FP8x23 { mag: 1418983, sign: true });\n    data.append(FP8x23 { mag: 14507015, sign: true });\n    data.append(FP8x23 { mag: 10873077, sign: true });\n    data.append(FP8x23 { mag: 4798862, sign: true });\n    data.append(FP8x23 { mag: 1492661, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3244081, sign: true });\n    data.append(FP8x23 { mag: 10706794, sign: true });\n    data.append(FP8x23 { mag: 18958928, sign: true });\n    data.append(FP8x23 { mag: 3353777, sign: true });\n    data.append(FP8x23 { mag: 37528560, sign: true });\n    data.append(FP8x23 { mag: 7473744, sign: false });\n    data.append(FP8x23 { mag: 5790740, sign: true });\n    data.append(FP8x23 { mag: 18114384, sign: false });\n    data.append(FP8x23 { mag: 1228071, sign: true });\n    data.append(FP8x23 { mag: 2115461, sign: true });\n    data.append(FP8x23 { mag: 11064842, sign: true });\n    data.append(FP8x23 { mag: 4650204, sign: false });\n    data.append(FP8x23 { mag: 2117008, sign: false });\n    data.append(FP8x23 { mag: 3066889, sign: false });\n    data.append(FP8x23 { mag: 12395364, sign: true });\n    data.append(FP8x23 { mag: 11292374, sign: true });\n    data.append(FP8x23 { mag: 1926478, sign: false });\n    data.append(FP8x23 { mag: 9694338, sign: false });\n    data.append(FP8x23 { mag: 12846217, sign: true });\n    data.append(FP8x23 { mag: 6915843, sign: false });\n    data.append(FP8x23 { mag: 1307795, sign: false });\n    data.append(FP8x23 { mag: 4985127, sign: false });\n    data.append(FP8x23 { mag: 4480469, sign: true });\n    data.append(FP8x23 { mag: 14326418, sign: false });\n    data.append(FP8x23 { mag: 4790479, sign: false });\n    data.append(FP8x23 { mag: 12347656, sign: false });\n    data.append(FP8x23 { mag: 24547608, sign: false });\n    data.append(FP8x23 { mag: 10357171, sign: true });\n    data.append(FP8x23 { mag: 6391847, sign: false });\n    data.append(FP8x23 { mag: 27053802, sign: true });\n    data.append(FP8x23 { mag: 8298346, sign: true });\n    data.append(FP8x23 { mag: 1500052, sign: false });\n    data.append(FP8x23 { mag: 7390910, sign: false });\n    data.append(FP8x23 { mag: 5305790, sign: false });\n    data.append(FP8x23 { mag: 28702554, sign: false });\n    data.append(FP8x23 { mag: 3992515, sign: true });\n    data.append(FP8x23 { mag: 22513472, sign: true });\n    data.append(FP8x23 { mag: 9551410, sign: false });\n    data.append(FP8x23 { mag: 10288647, sign: false });\n    data.append(FP8x23 { mag: 501099, sign: false });\n    data.append(FP8x23 { mag: 175674, sign: false });\n    data.append(FP8x23 { mag: 12165864, sign: true });\n    data.append(FP8x23 { mag: 12648068, sign: false });\n    data.append(FP8x23 { mag: 1932084, sign: true });\n    data.append(FP8x23 { mag: 11462044, sign: false });\n    data.append(FP8x23 { mag: 1838592, sign: true });\n    data.append(FP8x23 { mag: 15893444, sign: true });\n    data.append(FP8x23 { mag: 7061486, sign: true });\n    data.append(FP8x23 { mag: 320677, sign: false });\n    data.append(FP8x23 { mag: 12322688, sign: false });\n    data.append(FP8x23 { mag: 1152384, sign: true });\n    data.append(FP8x23 { mag: 8876509, sign: true });\n    data.append(FP8x23 { mag: 1133718, sign: true });\n    data.append(FP8x23 { mag: 9388043, sign: true });\n    data.append(FP8x23 { mag: 13317113, sign: true });\n    data.append(FP8x23 { mag: 3277348, sign: false });\n    data.append(FP8x23 { mag: 21393756, sign: true });\n    data.append(FP8x23 { mag: 15482224, sign: true });\n    data.append(FP8x23 { mag: 12521701, sign: true });\n    data.append(FP8x23 { mag: 3392381, sign: true });\n    data.append(FP8x23 { mag: 1818300, sign: false });\n    data.append(FP8x23 { mag: 12425486, sign: true });\n    data.append(FP8x23 { mag: 26694168, sign: true });\n    data.append(FP8x23 { mag: 2028386, sign: false });\n    data.append(FP8x23 { mag: 47604776, sign: true });\n    data.append(FP8x23 { mag: 12058849, sign: true });\n    data.append(FP8x23 { mag: 5851246, sign: true });\n    data.append(FP8x23 { mag: 7294009, sign: false });\n    data.append(FP8x23 { mag: 6121678, sign: false });\n    data.append(FP8x23 { mag: 790016, sign: true });\n    data.append(FP8x23 { mag: 7578667, sign: true });\n    data.append(FP8x23 { mag: 7450989, sign: false });\n    data.append(FP8x23 { mag: 11979960, sign: true });\n    data.append(FP8x23 { mag: 9764177, sign: false });\n    data.append(FP8x23 { mag: 5534756, sign: false });\n    data.append(FP8x23 { mag: 16585565, sign: true });\n    data.append(FP8x23 { mag: 1930917, sign: false });\n    data.append(FP8x23 { mag: 9688134, sign: false });\n    data.append(FP8x23 { mag: 12447360, sign: true });\n    data.append(FP8x23 { mag: 9266335, sign: false });\n    data.append(FP8x23 { mag: 2768829, sign: true });\n    data.append(FP8x23 { mag: 6603410, sign: false });\n    data.append(FP8x23 { mag: 5405931, sign: true });\n    data.append(FP8x23 { mag: 21713060, sign: false });\n    data.append(FP8x23 { mag: 2523116, sign: false });\n    data.append(FP8x23 { mag: 23339766, sign: false });\n    data.append(FP8x23 { mag: 24896902, sign: false });\n    data.append(FP8x23 { mag: 10753976, sign: true });\n    data.append(FP8x23 { mag: 31634404, sign: false });\n    data.append(FP8x23 { mag: 14895410, sign: true });\n    data.append(FP8x23 { mag: 2570909, sign: true });\n    data.append(FP8x23 { mag: 1013971, sign: false });\n    data.append(FP8x23 { mag: 7304647, sign: false });\n    data.append(FP8x23 { mag: 1318246, sign: false });\n    data.append(FP8x23 { mag: 13296067, sign: false });\n    data.append(FP8x23 { mag: 4443571, sign: true });\n    data.append(FP8x23 { mag: 7558768, sign: true });\n    data.append(FP8x23 { mag: 8737636, sign: false });\n    data.append(FP8x23 { mag: 7994008, sign: false });\n    data.append(FP8x23 { mag: 4502029, sign: true });\n    data.append(FP8x23 { mag: 2793031, sign: true });\n    data.append(FP8x23 { mag: 8108336, sign: true });\n    data.append(FP8x23 { mag: 11312462, sign: false });\n    data.append(FP8x23 { mag: 3134164, sign: true });\n    data.append(FP8x23 { mag: 28352826, sign: true });\n    data.append(FP8x23 { mag: 3892915, sign: true });\n    data.append(FP8x23 { mag: 10553366, sign: true });\n    data.append(FP8x23 { mag: 6404744, sign: true });\n    data.append(FP8x23 { mag: 1634334, sign: true });\n    data.append(FP8x23 { mag: 5114852, sign: false });\n    data.append(FP8x23 { mag: 1631376, sign: true });\n    data.append(FP8x23 { mag: 8711429, sign: true });\n    data.append(FP8x23 { mag: 906596, sign: true });\n    data.append(FP8x23 { mag: 9337071, sign: true });\n    data.append(FP8x23 { mag: 11280144, sign: true });\n    data.append(FP8x23 { mag: 2754582, sign: true });\n    data.append(FP8x23 { mag: 12085832, sign: true });\n    data.append(FP8x23 { mag: 9075175, sign: false });\n    data.append(FP8x23 { mag: 5795584, sign: true });\n    data.append(FP8x23 { mag: 581302, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(2), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 2055097, sign: false });\n    data.append(FP8x23 { mag: 4681757, sign: true });\n    data.append(FP8x23 { mag: 9467429, sign: true });\n    data.append(FP8x23 { mag: 10714904, sign: true });\n    data.append(FP8x23 { mag: 4545937, sign: true });\n    data.append(FP8x23 { mag: 6802699, sign: true });\n    data.append(FP8x23 { mag: 8448431, sign: false });\n    data.append(FP8x23 { mag: 1309417, sign: false });\n    data.append(FP8x23 { mag: 1427043, sign: true });\n    data.append(FP8x23 { mag: 16194403, sign: true });\n    data.append(FP8x23 { mag: 10729787, sign: false });\n    data.append(FP8x23 { mag: 11312058, sign: false });\n    data.append(FP8x23 { mag: 4344780, sign: true });\n    data.append(FP8x23 { mag: 2117222, sign: true });\n    data.append(FP8x23 { mag: 4305543, sign: true });\n    data.append(FP8x23 { mag: 19256026, sign: false });\n    data.append(FP8x23 { mag: 6015612, sign: true });\n    data.append(FP8x23 { mag: 3912062, sign: true });\n    data.append(FP8x23 { mag: 6010057, sign: true });\n    data.append(FP8x23 { mag: 5751897, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1759247, sign: false });\n    data.append(FP8x23 { mag: 3714086, sign: true });\n    data.append(FP8x23 { mag: 1622474, sign: true });\n    data.append(FP8x23 { mag: 8081111, sign: false });\n    data.append(FP8x23 { mag: 15897326, sign: true });\n    data.append(FP8x23 { mag: 758940, sign: true });\n    data.append(FP8x23 { mag: 12821375, sign: true });\n    data.append(FP8x23 { mag: 5124450, sign: true });\n    data.append(FP8x23 { mag: 23434418, sign: false });\n    data.append(FP8x23 { mag: 3803789, sign: true });\n    data.append(FP8x23 { mag: 1614523, sign: true });\n    data.append(FP8x23 { mag: 5084428, sign: true });\n    data.append(FP8x23 { mag: 1234480, sign: true });\n    data.append(FP8x23 { mag: 16545990, sign: false });\n    data.append(FP8x23 { mag: 281637, sign: true });\n    data.append(FP8x23 { mag: 2667010, sign: false });\n    data.append(FP8x23 { mag: 10535491, sign: false });\n    data.append(FP8x23 { mag: 4933426, sign: true });\n    data.append(FP8x23 { mag: 327930, sign: true });\n    data.append(FP8x23 { mag: 4062404, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1302729, sign: true });\n    data.append(FP8x23 { mag: 4831539, sign: false });\n    data.append(FP8x23 { mag: 2405890, sign: true });\n    data.append(FP8x23 { mag: 10269737, sign: false });\n    data.append(FP8x23 { mag: 22971448, sign: true });\n    data.append(FP8x23 { mag: 8658816, sign: true });\n    data.append(FP8x23 { mag: 8791916, sign: true });\n    data.append(FP8x23 { mag: 6457350, sign: true });\n    data.append(FP8x23 { mag: 23814312, sign: false });\n    data.append(FP8x23 { mag: 5515081, sign: false });\n    data.append(FP8x23 { mag: 8723604, sign: true });\n    data.append(FP8x23 { mag: 9736747, sign: false });\n    data.append(FP8x23 { mag: 2683101, sign: true });\n    data.append(FP8x23 { mag: 18170350, sign: false });\n    data.append(FP8x23 { mag: 3875810, sign: true });\n    data.append(FP8x23 { mag: 28814384, sign: false });\n    data.append(FP8x23 { mag: 12130002, sign: false });\n    data.append(FP8x23 { mag: 10525460, sign: true });\n    data.append(FP8x23 { mag: 1482957, sign: false });\n    data.append(FP8x23 { mag: 10778394, sign: true });\n    data.append(FP8x23 { mag: 2144567, sign: false });\n    data.append(FP8x23 { mag: 3213963, sign: true });\n    data.append(FP8x23 { mag: 1438178, sign: true });\n    data.append(FP8x23 { mag: 16459940, sign: false });\n    data.append(FP8x23 { mag: 14920009, sign: true });\n    data.append(FP8x23 { mag: 1688695, sign: false });\n    data.append(FP8x23 { mag: 5723649, sign: true });\n    data.append(FP8x23 { mag: 5762840, sign: true });\n    data.append(FP8x23 { mag: 23743028, sign: false });\n    data.append(FP8x23 { mag: 9072578, sign: false });\n    data.append(FP8x23 { mag: 21630128, sign: true });\n    data.append(FP8x23 { mag: 4738203, sign: false });\n    data.append(FP8x23 { mag: 5646856, sign: false });\n    data.append(FP8x23 { mag: 12505231, sign: false });\n    data.append(FP8x23 { mag: 2750364, sign: true });\n    data.append(FP8x23 { mag: 11142692, sign: true });\n    data.append(FP8x23 { mag: 1450514, sign: false });\n    data.append(FP8x23 { mag: 8938924, sign: true });\n    data.append(FP8x23 { mag: 8347829, sign: true });\n    data.append(FP8x23 { mag: 10378059, sign: true });\n    data.append(FP8x23 { mag: 2397369, sign: false });\n    data.append(FP8x23 { mag: 10139759, sign: false });\n    data.append(FP8x23 { mag: 4029842, sign: true });\n    data.append(FP8x23 { mag: 13634148, sign: false });\n    data.append(FP8x23 { mag: 9718088, sign: true });\n    data.append(FP8x23 { mag: 5013421, sign: false });\n    data.append(FP8x23 { mag: 1567635, sign: true });\n    data.append(FP8x23 { mag: 6230074, sign: true });\n    data.append(FP8x23 { mag: 23594884, sign: false });\n    data.append(FP8x23 { mag: 5660413, sign: true });\n    data.append(FP8x23 { mag: 4544134, sign: false });\n    data.append(FP8x23 { mag: 5145321, sign: false });\n    data.append(FP8x23 { mag: 1044552, sign: true });\n    data.append(FP8x23 { mag: 15062652, sign: false });\n    data.append(FP8x23 { mag: 1170275, sign: true });\n    data.append(FP8x23 { mag: 7297682, sign: false });\n    data.append(FP8x23 { mag: 4021705, sign: false });\n    data.append(FP8x23 { mag: 2420450, sign: true });\n    data.append(FP8x23 { mag: 9646560, sign: true });\n    data.append(FP8x23 { mag: 3731646, sign: true });\n    data.append(FP8x23 { mag: 2374416, sign: false });\n    data.append(FP8x23 { mag: 4568049, sign: false });\n    data.append(FP8x23 { mag: 20037666, sign: true });\n    data.append(FP8x23 { mag: 15425628, sign: false });\n    data.append(FP8x23 { mag: 24479156, sign: true });\n    data.append(FP8x23 { mag: 13813299, sign: false });\n    data.append(FP8x23 { mag: 5914193, sign: true });\n    data.append(FP8x23 { mag: 5106312, sign: true });\n    data.append(FP8x23 { mag: 23249850, sign: false });\n    data.append(FP8x23 { mag: 7863789, sign: true });\n    data.append(FP8x23 { mag: 2931223, sign: false });\n    data.append(FP8x23 { mag: 10148270, sign: true });\n    data.append(FP8x23 { mag: 1659329, sign: false });\n    data.append(FP8x23 { mag: 16533875, sign: false });\n    data.append(FP8x23 { mag: 947778, sign: false });\n    data.append(FP8x23 { mag: 1996097, sign: true });\n    data.append(FP8x23 { mag: 12094645, sign: false });\n    data.append(FP8x23 { mag: 10551688, sign: true });\n    data.append(FP8x23 { mag: 436736, sign: true });\n    data.append(FP8x23 { mag: 8262162, sign: true });\n    data.append(FP8x23 { mag: 800841, sign: false });\n    data.append(FP8x23 { mag: 4740033, sign: true });\n    data.append(FP8x23 { mag: 1154255, sign: false });\n    data.append(FP8x23 { mag: 22071580, sign: false });\n    data.append(FP8x23 { mag: 13414370, sign: true });\n    data.append(FP8x23 { mag: 6956623, sign: false });\n    data.append(FP8x23 { mag: 425380, sign: false });\n    data.append(FP8x23 { mag: 7490499, sign: true });\n    data.append(FP8x23 { mag: 20456024, sign: false });\n    data.append(FP8x23 { mag: 6724115, sign: true });\n    data.append(FP8x23 { mag: 6617779, sign: true });\n    data.append(FP8x23 { mag: 4948384, sign: false });\n    data.append(FP8x23 { mag: 4572023, sign: false });\n    data.append(FP8x23 { mag: 13733747, sign: false });\n    data.append(FP8x23 { mag: 366789, sign: false });\n    data.append(FP8x23 { mag: 8627705, sign: true });\n    data.append(FP8x23 { mag: 11436292, sign: false });\n    data.append(FP8x23 { mag: 7720046, sign: true });\n    data.append(FP8x23 { mag: 4280700, sign: true });\n    data.append(FP8x23 { mag: 596352, sign: true });\n    data.append(FP8x23 { mag: 135641, sign: true });\n    data.append(FP8x23 { mag: 1580582, sign: true });\n    data.append(FP8x23 { mag: 7475112, sign: false });\n    data.append(FP8x23 { mag: 9973263, sign: false });\n    data.append(FP8x23 { mag: 23622258, sign: true });\n    data.append(FP8x23 { mag: 14936001, sign: true });\n    data.append(FP8x23 { mag: 11125128, sign: true });\n    data.append(FP8x23 { mag: 4605262, sign: true });\n    data.append(FP8x23 { mag: 24842062, sign: false });\n    data.append(FP8x23 { mag: 8487889, sign: false });\n    data.append(FP8x23 { mag: 7613585, sign: false });\n    data.append(FP8x23 { mag: 20572216, sign: true });\n    data.append(FP8x23 { mag: 1407370, sign: true });\n    data.append(FP8x23 { mag: 16143629, sign: false });\n    data.append(FP8x23 { mag: 2145556, sign: false });\n    data.append(FP8x23 { mag: 4857438, sign: true });\n    data.append(FP8x23 { mag: 15467646, sign: false });\n    data.append(FP8x23 { mag: 13730522, sign: true });\n    data.append(FP8x23 { mag: 782145, sign: true });\n    data.append(FP8x23 { mag: 6308927, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis3.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis3() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(3), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 3788502, sign: false });\n    data.append(FP8x23 { mag: 4378064, sign: true });\n    data.append(FP8x23 { mag: 686928, sign: true });\n    data.append(FP8x23 { mag: 8276067, sign: true });\n    data.append(FP8x23 { mag: 2591624, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis3/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14176189, sign: false });\n    data.append(FP8x23 { mag: 13256247, sign: false });\n    data.append(FP8x23 { mag: 7459632, sign: true });\n    data.append(FP8x23 { mag: 2183266, sign: false });\n    data.append(FP8x23 { mag: 3222205, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 10687401, sign: false });\n    data.append(FP8x23 { mag: 18501866, sign: false });\n    data.append(FP8x23 { mag: 7720244, sign: true });\n    data.append(FP8x23 { mag: 1007289, sign: false });\n    data.append(FP8x23 { mag: 918086, sign: true });\n    data.append(FP8x23 { mag: 20068066, sign: false });\n    data.append(FP8x23 { mag: 10312502, sign: false });\n    data.append(FP8x23 { mag: 6596813, sign: true });\n    data.append(FP8x23 { mag: 4552789, sign: false });\n    data.append(FP8x23 { mag: 4998041, sign: false });\n    data.append(FP8x23 { mag: 10128268, sign: false });\n    data.append(FP8x23 { mag: 7354607, sign: false });\n    data.append(FP8x23 { mag: 7563708, sign: true });\n    data.append(FP8x23 { mag: 12087002, sign: false });\n    data.append(FP8x23 { mag: 1237964, sign: false });\n    data.append(FP8x23 { mag: 18442268, sign: false });\n    data.append(FP8x23 { mag: 15300608, sign: false });\n    data.append(FP8x23 { mag: 8281400, sign: true });\n    data.append(FP8x23 { mag: 6342275, sign: false });\n    data.append(FP8x23 { mag: 6728317, sign: false });\n    data.append(FP8x23 { mag: 18537474, sign: false });\n    data.append(FP8x23 { mag: 12175616, sign: false });\n    data.append(FP8x23 { mag: 7813574, sign: true });\n    data.append(FP8x23 { mag: 17309800, sign: false });\n    data.append(FP8x23 { mag: 3443862, sign: false });\n    data.append(FP8x23 { mag: 13112224, sign: false });\n    data.append(FP8x23 { mag: 5033589, sign: false });\n    data.append(FP8x23 { mag: 7108840, sign: true });\n    data.append(FP8x23 { mag: 2370007, sign: false });\n    data.append(FP8x23 { mag: 5979892, sign: false });\n    data.append(FP8x23 { mag: 9399040, sign: false });\n    data.append(FP8x23 { mag: 10599692, sign: false });\n    data.append(FP8x23 { mag: 6725607, sign: true });\n    data.append(FP8x23 { mag: 8720121, sign: true });\n    data.append(FP8x23 { mag: 2171889, sign: false });\n    data.append(FP8x23 { mag: 10271292, sign: false });\n    data.append(FP8x23 { mag: 8856792, sign: false });\n    data.append(FP8x23 { mag: 7844595, sign: true });\n    data.append(FP8x23 { mag: 4803428, sign: true });\n    data.append(FP8x23 { mag: 6795485, sign: false });\n    data.append(FP8x23 { mag: 17807714, sign: false });\n    data.append(FP8x23 { mag: 20838886, sign: false });\n    data.append(FP8x23 { mag: 8086314, sign: true });\n    data.append(FP8x23 { mag: 105801, sign: true });\n    data.append(FP8x23 { mag: 4298992, sign: false });\n    data.append(FP8x23 { mag: 10501791, sign: false });\n    data.append(FP8x23 { mag: 5582881, sign: false });\n    data.append(FP8x23 { mag: 6796975, sign: true });\n    data.append(FP8x23 { mag: 2603986, sign: false });\n    data.append(FP8x23 { mag: 2619135, sign: false });\n    data.append(FP8x23 { mag: 15345391, sign: false });\n    data.append(FP8x23 { mag: 7680755, sign: false });\n    data.append(FP8x23 { mag: 6432286, sign: true });\n    data.append(FP8x23 { mag: 3431878, sign: true });\n    data.append(FP8x23 { mag: 5204896, sign: false });\n    data.append(FP8x23 { mag: 13113800, sign: false });\n    data.append(FP8x23 { mag: 9725064, sign: false });\n    data.append(FP8x23 { mag: 6484407, sign: true });\n    data.append(FP8x23 { mag: 9486773, sign: true });\n    data.append(FP8x23 { mag: 4560893, sign: false });\n    data.append(FP8x23 { mag: 14081383, sign: false });\n    data.append(FP8x23 { mag: 19622632, sign: false });\n    data.append(FP8x23 { mag: 8223578, sign: true });\n    data.append(FP8x23 { mag: 8021712, sign: false });\n    data.append(FP8x23 { mag: 442630, sign: false });\n    data.append(FP8x23 { mag: 6884316, sign: false });\n    data.append(FP8x23 { mag: 8932191, sign: false });\n    data.append(FP8x23 { mag: 7594812, sign: true });\n    data.append(FP8x23 { mag: 385854, sign: true });\n    data.append(FP8x23 { mag: 2108179, sign: false });\n    data.append(FP8x23 { mag: 20355344, sign: false });\n    data.append(FP8x23 { mag: 16189169, sign: false });\n    data.append(FP8x23 { mag: 6603276, sign: true });\n    data.append(FP8x23 { mag: 2181112, sign: true });\n    data.append(FP8x23 { mag: 3848914, sign: false });\n    data.append(FP8x23 { mag: 12701286, sign: false });\n    data.append(FP8x23 { mag: 15061858, sign: false });\n    data.append(FP8x23 { mag: 8757626, sign: true });\n    data.append(FP8x23 { mag: 2480438, sign: false });\n    data.append(FP8x23 { mag: 5948392, sign: false });\n    data.append(FP8x23 { mag: 14269568, sign: false });\n    data.append(FP8x23 { mag: 7047774, sign: false });\n    data.append(FP8x23 { mag: 7718220, sign: true });\n    data.append(FP8x23 { mag: 16099773, sign: false });\n    data.append(FP8x23 { mag: 3578917, sign: false });\n    data.append(FP8x23 { mag: 10858196, sign: false });\n    data.append(FP8x23 { mag: 9199796, sign: false });\n    data.append(FP8x23 { mag: 6549769, sign: true });\n    data.append(FP8x23 { mag: 8350657, sign: true });\n    data.append(FP8x23 { mag: 3219648, sign: false });\n    data.append(FP8x23 { mag: 12119373, sign: false });\n    data.append(FP8x23 { mag: 9431783, sign: false });\n    data.append(FP8x23 { mag: 6461031, sign: true });\n    data.append(FP8x23 { mag: 8869742, sign: true });\n    data.append(FP8x23 { mag: 3772824, sign: false });\n    data.append(FP8x23 { mag: 8127924, sign: false });\n    data.append(FP8x23 { mag: 16584150, sign: false });\n    data.append(FP8x23 { mag: 8071290, sign: true });\n    data.append(FP8x23 { mag: 4320410, sign: true });\n    data.append(FP8x23 { mag: 1459009, sign: false });\n    data.append(FP8x23 { mag: 11231873, sign: false });\n    data.append(FP8x23 { mag: 14567803, sign: false });\n    data.append(FP8x23 { mag: 6898410, sign: true });\n    data.append(FP8x23 { mag: 2296813, sign: false });\n    data.append(FP8x23 { mag: 1721236, sign: true });\n    data.append(FP8x23 { mag: 20783392, sign: false });\n    data.append(FP8x23 { mag: 13201518, sign: false });\n    data.append(FP8x23 { mag: 7591836, sign: true });\n    data.append(FP8x23 { mag: 11113338, sign: false });\n    data.append(FP8x23 { mag: 5476785, sign: false });\n    data.append(FP8x23 { mag: 19358212, sign: false });\n    data.append(FP8x23 { mag: 20245408, sign: false });\n    data.append(FP8x23 { mag: 7649984, sign: true });\n    data.append(FP8x23 { mag: 1763582, sign: true });\n    data.append(FP8x23 { mag: 4583921, sign: false });\n    data.append(FP8x23 { mag: 12314612, sign: false });\n    data.append(FP8x23 { mag: 17131904, sign: false });\n    data.append(FP8x23 { mag: 8786219, sign: true });\n    data.append(FP8x23 { mag: 2707669, sign: false });\n    data.append(FP8x23 { mag: 4495219, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis_negative_1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(-1), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 11768025, sign: false });\n    data.append(FP8x23 { mag: 16293154, sign: false });\n    data.append(FP8x23 { mag: 1357895, sign: true });\n    data.append(FP8x23 { mag: 10771229, sign: true });\n    data.append(FP8x23 { mag: 1256579, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_1/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14856029, sign: true });\n    data.append(FP8x23 { mag: 11603919, sign: false });\n    data.append(FP8x23 { mag: 2672200, sign: false });\n    data.append(FP8x23 { mag: 513076, sign: false });\n    data.append(FP8x23 { mag: 16056013, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25693068, sign: true });\n    data.append(FP8x23 { mag: 7917877, sign: true });\n    data.append(FP8x23 { mag: 2157031, sign: false });\n    data.append(FP8x23 { mag: 1017447, sign: true });\n    data.append(FP8x23 { mag: 14048544, sign: true });\n    data.append(FP8x23 { mag: 3445597, sign: false });\n    data.append(FP8x23 { mag: 22559194, sign: false });\n    data.append(FP8x23 { mag: 4377790, sign: false });\n    data.append(FP8x23 { mag: 3596989, sign: false });\n    data.append(FP8x23 { mag: 16917048, sign: true });\n    data.append(FP8x23 { mag: 27429874, sign: true });\n    data.append(FP8x23 { mag: 33567124, sign: false });\n    data.append(FP8x23 { mag: 2466467, sign: false });\n    data.append(FP8x23 { mag: 13402702, sign: false });\n    data.append(FP8x23 { mag: 15093930, sign: true });\n    data.append(FP8x23 { mag: 1604535, sign: true });\n    data.append(FP8x23 { mag: 3995742, sign: false });\n    data.append(FP8x23 { mag: 1047758, sign: false });\n    data.append(FP8x23 { mag: 5925989, sign: false });\n    data.append(FP8x23 { mag: 17755992, sign: true });\n    data.append(FP8x23 { mag: 1308801, sign: true });\n    data.append(FP8x23 { mag: 15625532, sign: false });\n    data.append(FP8x23 { mag: 1972539, sign: false });\n    data.append(FP8x23 { mag: 20200126, sign: false });\n    data.append(FP8x23 { mag: 16163486, sign: true });\n    data.append(FP8x23 { mag: 18160966, sign: true });\n    data.append(FP8x23 { mag: 42204896, sign: false });\n    data.append(FP8x23 { mag: 3365634, sign: false });\n    data.append(FP8x23 { mag: 756118, sign: false });\n    data.append(FP8x23 { mag: 17393110, sign: true });\n    data.append(FP8x23 { mag: 29695036, sign: true });\n    data.append(FP8x23 { mag: 21490404, sign: false });\n    data.append(FP8x23 { mag: 4123195, sign: false });\n    data.append(FP8x23 { mag: 13677586, sign: true });\n    data.append(FP8x23 { mag: 15546755, sign: true });\n    data.append(FP8x23 { mag: 26985604, sign: true });\n    data.append(FP8x23 { mag: 27976678, sign: false });\n    data.append(FP8x23 { mag: 1911217, sign: false });\n    data.append(FP8x23 { mag: 8580043, sign: true });\n    data.append(FP8x23 { mag: 17788560, sign: true });\n    data.append(FP8x23 { mag: 3575616, sign: true });\n    data.append(FP8x23 { mag: 16615201, sign: true });\n    data.append(FP8x23 { mag: 1433398, sign: false });\n    data.append(FP8x23 { mag: 2466125, sign: true });\n    data.append(FP8x23 { mag: 16578106, sign: true });\n    data.append(FP8x23 { mag: 26269618, sign: true });\n    data.append(FP8x23 { mag: 40160680, sign: false });\n    data.append(FP8x23 { mag: 3982118, sign: false });\n    data.append(FP8x23 { mag: 1060640, sign: false });\n    data.append(FP8x23 { mag: 15763607, sign: true });\n    data.append(FP8x23 { mag: 11224197, sign: true });\n    data.append(FP8x23 { mag: 32353352, sign: false });\n    data.append(FP8x23 { mag: 4703022, sign: false });\n    data.append(FP8x23 { mag: 6794984, sign: true });\n    data.append(FP8x23 { mag: 17017344, sign: true });\n    data.append(FP8x23 { mag: 18156072, sign: true });\n    data.append(FP8x23 { mag: 24745368, sign: false });\n    data.append(FP8x23 { mag: 4599990, sign: false });\n    data.append(FP8x23 { mag: 14675376, sign: true });\n    data.append(FP8x23 { mag: 16705092, sign: true });\n    data.append(FP8x23 { mag: 15150520, sign: true });\n    data.append(FP8x23 { mag: 12088855, sign: true });\n    data.append(FP8x23 { mag: 1162058, sign: false });\n    data.append(FP8x23 { mag: 8111762, sign: false });\n    data.append(FP8x23 { mag: 14708304, sign: true });\n    data.append(FP8x23 { mag: 37506388, sign: true });\n    data.append(FP8x23 { mag: 27696080, sign: false });\n    data.append(FP8x23 { mag: 2404980, sign: false });\n    data.append(FP8x23 { mag: 2830611, sign: true });\n    data.append(FP8x23 { mag: 15515864, sign: true });\n    data.append(FP8x23 { mag: 4337955, sign: false });\n    data.append(FP8x23 { mag: 688924, sign: false });\n    data.append(FP8x23 { mag: 4365013, sign: false });\n    data.append(FP8x23 { mag: 5167124, sign: true });\n    data.append(FP8x23 { mag: 16359880, sign: true });\n    data.append(FP8x23 { mag: 19437442, sign: true });\n    data.append(FP8x23 { mag: 4884262, sign: false });\n    data.append(FP8x23 { mag: 106371, sign: false });\n    data.append(FP8x23 { mag: 899843, sign: false });\n    data.append(FP8x23 { mag: 17377838, sign: true });\n    data.append(FP8x23 { mag: 14565970, sign: true });\n    data.append(FP8x23 { mag: 34709016, sign: false });\n    data.append(FP8x23 { mag: 2161031, sign: false });\n    data.append(FP8x23 { mag: 18625288, sign: false });\n    data.append(FP8x23 { mag: 16228969, sign: true });\n    data.append(FP8x23 { mag: 25162534, sign: true });\n    data.append(FP8x23 { mag: 26700174, sign: false });\n    data.append(FP8x23 { mag: 4470785, sign: false });\n    data.append(FP8x23 { mag: 13196732, sign: true });\n    data.append(FP8x23 { mag: 16054773, sign: true });\n    data.append(FP8x23 { mag: 21245010, sign: true });\n    data.append(FP8x23 { mag: 25836828, sign: false });\n    data.append(FP8x23 { mag: 4646199, sign: false });\n    data.append(FP8x23 { mag: 13872315, sign: true });\n    data.append(FP8x23 { mag: 16322987, sign: true });\n    data.append(FP8x23 { mag: 33643436, sign: true });\n    data.append(FP8x23 { mag: 781014, sign: true });\n    data.append(FP8x23 { mag: 1463096, sign: false });\n    data.append(FP8x23 { mag: 7951401, sign: true });\n    data.append(FP8x23 { mag: 15201107, sign: true });\n    data.append(FP8x23 { mag: 24001804, sign: true });\n    data.append(FP8x23 { mag: 6722907, sign: false });\n    data.append(FP8x23 { mag: 3781605, sign: false });\n    data.append(FP8x23 { mag: 660857, sign: false });\n    data.append(FP8x23 { mag: 13659127, sign: true });\n    data.append(FP8x23 { mag: 5667579, sign: false });\n    data.append(FP8x23 { mag: 11807596, sign: false });\n    data.append(FP8x23 { mag: 2410864, sign: false });\n    data.append(FP8x23 { mag: 12135487, sign: false });\n    data.append(FP8x23 { mag: 17149172, sign: true });\n    data.append(FP8x23 { mag: 1240615, sign: false });\n    data.append(FP8x23 { mag: 14406547, sign: true });\n    data.append(FP8x23 { mag: 2295918, sign: false });\n    data.append(FP8x23 { mag: 4623713, sign: true });\n    data.append(FP8x23 { mag: 16716257, sign: true });\n    data.append(FP8x23 { mag: 20638546, sign: true });\n    data.append(FP8x23 { mag: 2819504, sign: true });\n    data.append(FP8x23 { mag: 49850, sign: false });\n    data.append(FP8x23 { mag: 1195583, sign: false });\n    data.append(FP8x23 { mag: 16673249, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis_negative_2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(2), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8254028, sign: false });\n    data.append(FP8x23 { mag: 15690628, sign: false });\n    data.append(FP8x23 { mag: 5515815, sign: false });\n    data.append(FP8x23 { mag: 5436207, sign: false });\n    data.append(FP8x23 { mag: 4444335, sign: false });\n    data.append(FP8x23 { mag: 1122784, sign: false });\n    data.append(FP8x23 { mag: 12881007, sign: false });\n    data.append(FP8x23 { mag: 2781310, sign: true });\n    data.append(FP8x23 { mag: 582197, sign: false });\n    data.append(FP8x23 { mag: 2891656, sign: false });\n    data.append(FP8x23 { mag: 1856695, sign: true });\n    data.append(FP8x23 { mag: 2058841, sign: false });\n    data.append(FP8x23 { mag: 1014957, sign: true });\n    data.append(FP8x23 { mag: 9724722, sign: true });\n    data.append(FP8x23 { mag: 22497248, sign: true });\n    data.append(FP8x23 { mag: 12912647, sign: false });\n    data.append(FP8x23 { mag: 10905704, sign: true });\n    data.append(FP8x23 { mag: 3390802, sign: false });\n    data.append(FP8x23 { mag: 14589767, sign: true });\n    data.append(FP8x23 { mag: 8773874, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_2/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8789918, sign: true });\n    data.append(FP8x23 { mag: 14437992, sign: false });\n    data.append(FP8x23 { mag: 86356, sign: true });\n    data.append(FP8x23 { mag: 3036480, sign: true });\n    data.append(FP8x23 { mag: 6736255, sign: true });\n    data.append(FP8x23 { mag: 5972939, sign: false });\n    data.append(FP8x23 { mag: 2010263, sign: false });\n    data.append(FP8x23 { mag: 6592165, sign: false });\n    data.append(FP8x23 { mag: 764864, sign: false });\n    data.append(FP8x23 { mag: 6630163, sign: true });\n    data.append(FP8x23 { mag: 13792561, sign: true });\n    data.append(FP8x23 { mag: 7577680, sign: true });\n    data.append(FP8x23 { mag: 12301127, sign: false });\n    data.append(FP8x23 { mag: 2468466, sign: false });\n    data.append(FP8x23 { mag: 766822, sign: true });\n    data.append(FP8x23 { mag: 9420083, sign: false });\n    data.append(FP8x23 { mag: 2868397, sign: false });\n    data.append(FP8x23 { mag: 9292738, sign: true });\n    data.append(FP8x23 { mag: 6785176, sign: false });\n    data.append(FP8x23 { mag: 18482062, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 21087944, sign: true });\n    data.append(FP8x23 { mag: 14202160, sign: true });\n    data.append(FP8x23 { mag: 370069, sign: false });\n    data.append(FP8x23 { mag: 4146880, sign: true });\n    data.append(FP8x23 { mag: 179760, sign: false });\n    data.append(FP8x23 { mag: 7276812, sign: false });\n    data.append(FP8x23 { mag: 8153829, sign: false });\n    data.append(FP8x23 { mag: 9423354, sign: false });\n    data.append(FP8x23 { mag: 609877, sign: false });\n    data.append(FP8x23 { mag: 8294132, sign: true });\n    data.append(FP8x23 { mag: 12562397, sign: true });\n    data.append(FP8x23 { mag: 4880166, sign: true });\n    data.append(FP8x23 { mag: 11962724, sign: false });\n    data.append(FP8x23 { mag: 9929396, sign: false });\n    data.append(FP8x23 { mag: 19547024, sign: true });\n    data.append(FP8x23 { mag: 26953908, sign: false });\n    data.append(FP8x23 { mag: 5759087, sign: false });\n    data.append(FP8x23 { mag: 4445810, sign: true });\n    data.append(FP8x23 { mag: 11181212, sign: false });\n    data.append(FP8x23 { mag: 28726552, sign: true });\n    data.append(FP8x23 { mag: 7242334, sign: true });\n    data.append(FP8x23 { mag: 12761861, sign: false });\n    data.append(FP8x23 { mag: 193729, sign: true });\n    data.append(FP8x23 { mag: 7287480, sign: true });\n    data.append(FP8x23 { mag: 7691729, sign: true });\n    data.append(FP8x23 { mag: 5568957, sign: false });\n    data.append(FP8x23 { mag: 12831901, sign: false });\n    data.append(FP8x23 { mag: 7948158, sign: false });\n    data.append(FP8x23 { mag: 638959, sign: false });\n    data.append(FP8x23 { mag: 8929355, sign: true });\n    data.append(FP8x23 { mag: 10329036, sign: true });\n    data.append(FP8x23 { mag: 5789921, sign: true });\n    data.append(FP8x23 { mag: 13908634, sign: false });\n    data.append(FP8x23 { mag: 16091354, sign: true });\n    data.append(FP8x23 { mag: 13666367, sign: true });\n    data.append(FP8x23 { mag: 159615, sign: false });\n    data.append(FP8x23 { mag: 13601758, sign: true });\n    data.append(FP8x23 { mag: 5820949, sign: true });\n    data.append(FP8x23 { mag: 12683600, sign: true });\n    data.append(FP8x23 { mag: 28115886, sign: true });\n    data.append(FP8x23 { mag: 6226987, sign: true });\n    data.append(FP8x23 { mag: 31992340, sign: true });\n    data.append(FP8x23 { mag: 1316199, sign: false });\n    data.append(FP8x23 { mag: 5853814, sign: true });\n    data.append(FP8x23 { mag: 12777388, sign: true });\n    data.append(FP8x23 { mag: 5020211, sign: false });\n    data.append(FP8x23 { mag: 19168420, sign: false });\n    data.append(FP8x23 { mag: 8940602, sign: false });\n    data.append(FP8x23 { mag: 699398, sign: false });\n    data.append(FP8x23 { mag: 6298646, sign: true });\n    data.append(FP8x23 { mag: 14858262, sign: true });\n    data.append(FP8x23 { mag: 5715824, sign: true });\n    data.append(FP8x23 { mag: 12345495, sign: false });\n    data.append(FP8x23 { mag: 4344728, sign: true });\n    data.append(FP8x23 { mag: 5410113, sign: true });\n    data.append(FP8x23 { mag: 12525305, sign: false });\n    data.append(FP8x23 { mag: 8940445, sign: true });\n    data.append(FP8x23 { mag: 11470874, sign: true });\n    data.append(FP8x23 { mag: 15836346, sign: true });\n    data.append(FP8x23 { mag: 17977528, sign: true });\n    data.append(FP8x23 { mag: 6319176, sign: true });\n    data.append(FP8x23 { mag: 13319088, sign: true });\n    data.append(FP8x23 { mag: 10642511, sign: false });\n    data.append(FP8x23 { mag: 6762721, sign: true });\n    data.append(FP8x23 { mag: 1653770, sign: false });\n    data.append(FP8x23 { mag: 3567792, sign: false });\n    data.append(FP8x23 { mag: 12541384, sign: false });\n    data.append(FP8x23 { mag: 6553638, sign: false });\n    data.append(FP8x23 { mag: 840163, sign: false });\n    data.append(FP8x23 { mag: 5905214, sign: true });\n    data.append(FP8x23 { mag: 14579163, sign: true });\n    data.append(FP8x23 { mag: 8499320, sign: true });\n    data.append(FP8x23 { mag: 12977132, sign: false });\n    data.append(FP8x23 { mag: 2412819, sign: false });\n    data.append(FP8x23 { mag: 5657099, sign: false });\n    data.append(FP8x23 { mag: 6293111, sign: false });\n    data.append(FP8x23 { mag: 5694987, sign: false });\n    data.append(FP8x23 { mag: 4423076, sign: true });\n    data.append(FP8x23 { mag: 6521042, sign: false });\n    data.append(FP8x23 { mag: 24888322, sign: true });\n    data.append(FP8x23 { mag: 12639230, sign: true });\n    data.append(FP8x23 { mag: 17876392, sign: false });\n    data.append(FP8x23 { mag: 1704105, sign: true });\n    data.append(FP8x23 { mag: 10134546, sign: true });\n    data.append(FP8x23 { mag: 9163717, sign: true });\n    data.append(FP8x23 { mag: 4699486, sign: false });\n    data.append(FP8x23 { mag: 22207096, sign: false });\n    data.append(FP8x23 { mag: 11617848, sign: false });\n    data.append(FP8x23 { mag: 1979972, sign: false });\n    data.append(FP8x23 { mag: 6108713, sign: true });\n    data.append(FP8x23 { mag: 12926792, sign: true });\n    data.append(FP8x23 { mag: 5751667, sign: true });\n    data.append(FP8x23 { mag: 13657549, sign: false });\n    data.append(FP8x23 { mag: 10448591, sign: true });\n    data.append(FP8x23 { mag: 2621331, sign: false });\n    data.append(FP8x23 { mag: 1846107, sign: false });\n    data.append(FP8x23 { mag: 4501459, sign: false });\n    data.append(FP8x23 { mag: 6877419, sign: true });\n    data.append(FP8x23 { mag: 2810404, sign: true });\n    data.append(FP8x23 { mag: 13194988, sign: true });\n    data.append(FP8x23 { mag: 16400489, sign: true });\n    data.append(FP8x23 { mag: 7287681, sign: false });\n    data.append(FP8x23 { mag: 5386697, sign: true });\n    data.append(FP8x23 { mag: 3996463, sign: true });\n    data.append(FP8x23 { mag: 816025, sign: false });\n    data.append(FP8x23 { mag: 8312861, sign: false });\n    data.append(FP8x23 { mag: 4596467, sign: false });\n    data.append(FP8x23 { mag: 5489366, sign: false });\n    data.append(FP8x23 { mag: 190582, sign: false });\n    data.append(FP8x23 { mag: 8824953, sign: true });\n    data.append(FP8x23 { mag: 15389404, sign: true });\n    data.append(FP8x23 { mag: 10396522, sign: true });\n    data.append(FP8x23 { mag: 12260739, sign: false });\n    data.append(FP8x23 { mag: 620359, sign: false });\n    data.append(FP8x23 { mag: 11915708, sign: false });\n    data.append(FP8x23 { mag: 4374361, sign: false });\n    data.append(FP8x23 { mag: 11809902, sign: false });\n    data.append(FP8x23 { mag: 1667804, sign: true });\n    data.append(FP8x23 { mag: 5682543, sign: false });\n    data.append(FP8x23 { mag: 21908880, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_3.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis_negative_3() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(-3), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_3/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_3/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4015916, sign: false });\n    data.append(FP8x23 { mag: 9874032, sign: true });\n    data.append(FP8x23 { mag: 8467489, sign: false });\n    data.append(FP8x23 { mag: 4415316, sign: true });\n    data.append(FP8x23 { mag: 263255, sign: true });\n    data.append(FP8x23 { mag: 14018546, sign: true });\n    data.append(FP8x23 { mag: 831957, sign: true });\n    data.append(FP8x23 { mag: 2773992, sign: false });\n    data.append(FP8x23 { mag: 7052111, sign: false });\n    data.append(FP8x23 { mag: 10508586, sign: false });\n    data.append(FP8x23 { mag: 9333348, sign: false });\n    data.append(FP8x23 { mag: 6120022, sign: true });\n    data.append(FP8x23 { mag: 2919362, sign: false });\n    data.append(FP8x23 { mag: 6599845, sign: false });\n    data.append(FP8x23 { mag: 5617565, sign: true });\n    data.append(FP8x23 { mag: 1982437, sign: false });\n    data.append(FP8x23 { mag: 2318222, sign: true });\n    data.append(FP8x23 { mag: 6877898, sign: true });\n    data.append(FP8x23 { mag: 4843686, sign: true });\n    data.append(FP8x23 { mag: 4281547, sign: true });\n    data.append(FP8x23 { mag: 9020321, sign: false });\n    data.append(FP8x23 { mag: 7121201, sign: true });\n    data.append(FP8x23 { mag: 1936677, sign: true });\n    data.append(FP8x23 { mag: 3342963, sign: false });\n    data.append(FP8x23 { mag: 298643, sign: true });\n    data.append(FP8x23 { mag: 5599239, sign: false });\n    data.append(FP8x23 { mag: 9816171, sign: true });\n    data.append(FP8x23 { mag: 2305190, sign: true });\n    data.append(FP8x23 { mag: 7276842, sign: true });\n    data.append(FP8x23 { mag: 13293301, sign: false });\n    data.append(FP8x23 { mag: 4150123, sign: false });\n    data.append(FP8x23 { mag: 6761773, sign: false });\n    data.append(FP8x23 { mag: 19059686, sign: true });\n    data.append(FP8x23 { mag: 9122647, sign: false });\n    data.append(FP8x23 { mag: 2738195, sign: false });\n    data.append(FP8x23 { mag: 3539305, sign: true });\n    data.append(FP8x23 { mag: 3442799, sign: true });\n    data.append(FP8x23 { mag: 7286815, sign: false });\n    data.append(FP8x23 { mag: 3449812, sign: true });\n    data.append(FP8x23 { mag: 6301439, sign: true });\n    data.append(FP8x23 { mag: 27827, sign: false });\n    data.append(FP8x23 { mag: 16922668, sign: false });\n    data.append(FP8x23 { mag: 6773437, sign: false });\n    data.append(FP8x23 { mag: 8139997, sign: false });\n    data.append(FP8x23 { mag: 6658577, sign: true });\n    data.append(FP8x23 { mag: 6401045, sign: true });\n    data.append(FP8x23 { mag: 13884754, sign: true });\n    data.append(FP8x23 { mag: 1770918, sign: true });\n    data.append(FP8x23 { mag: 6725222, sign: true });\n    data.append(FP8x23 { mag: 15731397, sign: true });\n    data.append(FP8x23 { mag: 2697259, sign: false });\n    data.append(FP8x23 { mag: 5132627, sign: true });\n    data.append(FP8x23 { mag: 7225220, sign: true });\n    data.append(FP8x23 { mag: 19265056, sign: false });\n    data.append(FP8x23 { mag: 2468254, sign: true });\n    data.append(FP8x23 { mag: 9273583, sign: false });\n    data.append(FP8x23 { mag: 10740621, sign: true });\n    data.append(FP8x23 { mag: 9934493, sign: false });\n    data.append(FP8x23 { mag: 11214323, sign: false });\n    data.append(FP8x23 { mag: 2580905, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_3/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 5269800, sign: false });\n    data.append(FP8x23 { mag: 26437698, sign: false });\n    data.append(FP8x23 { mag: 7881796, sign: true });\n    data.append(FP8x23 { mag: 496681, sign: true });\n    data.append(FP8x23 { mag: 3823099, sign: true });\n    data.append(FP8x23 { mag: 7108821, sign: true });\n    data.append(FP8x23 { mag: 5930229, sign: false });\n    data.append(FP8x23 { mag: 11642453, sign: false });\n    data.append(FP8x23 { mag: 142364, sign: true });\n    data.append(FP8x23 { mag: 15029132, sign: false });\n    data.append(FP8x23 { mag: 6182555, sign: true });\n    data.append(FP8x23 { mag: 6906046, sign: false });\n    data.append(FP8x23 { mag: 13535761, sign: false });\n    data.append(FP8x23 { mag: 15033282, sign: true });\n    data.append(FP8x23 { mag: 7360644, sign: true });\n    data.append(FP8x23 { mag: 12940572, sign: true });\n    data.append(FP8x23 { mag: 2081043, sign: true });\n    data.append(FP8x23 { mag: 7708528, sign: false });\n    data.append(FP8x23 { mag: 4226297, sign: true });\n    data.append(FP8x23 { mag: 5764964, sign: true });\n    data.append(FP8x23 { mag: 2288960, sign: true });\n    data.append(FP8x23 { mag: 821999, sign: false });\n    data.append(FP8x23 { mag: 207150, sign: false });\n    data.append(FP8x23 { mag: 15723386, sign: true });\n    data.append(FP8x23 { mag: 15068840, sign: false });\n    data.append(FP8x23 { mag: 8499812, sign: true });\n    data.append(FP8x23 { mag: 6200952, sign: false });\n    data.append(FP8x23 { mag: 2097368, sign: false });\n    data.append(FP8x23 { mag: 2254739, sign: true });\n    data.append(FP8x23 { mag: 3738338, sign: true });\n    data.append(FP8x23 { mag: 3717253, sign: true });\n    data.append(FP8x23 { mag: 2772971, sign: true });\n    data.append(FP8x23 { mag: 1447187, sign: true });\n    data.append(FP8x23 { mag: 6541738, sign: true });\n    data.append(FP8x23 { mag: 12934512, sign: false });\n    data.append(FP8x23 { mag: 4182447, sign: true });\n    data.append(FP8x23 { mag: 2751003, sign: false });\n    data.append(FP8x23 { mag: 5609383, sign: false });\n    data.append(FP8x23 { mag: 17567880, sign: false });\n    data.append(FP8x23 { mag: 57541, sign: true });\n    data.append(FP8x23 { mag: 7380573, sign: true });\n    data.append(FP8x23 { mag: 10171347, sign: true });\n    data.append(FP8x23 { mag: 4604353, sign: false });\n    data.append(FP8x23 { mag: 7985652, sign: false });\n    data.append(FP8x23 { mag: 10874691, sign: false });\n    data.append(FP8x23 { mag: 5158722, sign: true });\n    data.append(FP8x23 { mag: 3391219, sign: true });\n    data.append(FP8x23 { mag: 7147749, sign: false });\n    data.append(FP8x23 { mag: 8060486, sign: false });\n    data.append(FP8x23 { mag: 338831, sign: false });\n    data.append(FP8x23 { mag: 3054272, sign: false });\n    data.append(FP8x23 { mag: 7731630, sign: true });\n    data.append(FP8x23 { mag: 3137681, sign: true });\n    data.append(FP8x23 { mag: 2613931, sign: true });\n    data.append(FP8x23 { mag: 2182738, sign: false });\n    data.append(FP8x23 { mag: 10013805, sign: false });\n    data.append(FP8x23 { mag: 6079653, sign: true });\n    data.append(FP8x23 { mag: 5500669, sign: true });\n    data.append(FP8x23 { mag: 3497484, sign: false });\n    data.append(FP8x23 { mag: 1959672, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_3/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1377619, sign: true });\n    data.append(FP8x23 { mag: 46126352, sign: false });\n    data.append(FP8x23 { mag: 8447846, sign: true });\n    data.append(FP8x23 { mag: 1078388, sign: false });\n    data.append(FP8x23 { mag: 4197258, sign: true });\n    data.append(FP8x23 { mag: 21442406, sign: true });\n    data.append(FP8x23 { mag: 5654608, sign: false });\n    data.append(FP8x23 { mag: 8373193, sign: false });\n    data.append(FP8x23 { mag: 3099309, sign: true });\n    data.append(FP8x23 { mag: 7340858, sign: false });\n    data.append(FP8x23 { mag: 13832236, sign: true });\n    data.append(FP8x23 { mag: 272050, sign: true });\n    data.append(FP8x23 { mag: 14079711, sign: false });\n    data.append(FP8x23 { mag: 21140192, sign: true });\n    data.append(FP8x23 { mag: 11251934, sign: true });\n    data.append(FP8x23 { mag: 10519948, sign: true });\n    data.append(FP8x23 { mag: 1111704, sign: true });\n    data.append(FP8x23 { mag: 1186678, sign: true });\n    data.append(FP8x23 { mag: 2023637, sign: true });\n    data.append(FP8x23 { mag: 71723, sign: true });\n    data.append(FP8x23 { mag: 644434, sign: true });\n    data.append(FP8x23 { mag: 1837309, sign: false });\n    data.append(FP8x23 { mag: 296517, sign: false });\n    data.append(FP8x23 { mag: 18691470, sign: true });\n    data.append(FP8x23 { mag: 15147077, sign: false });\n    data.append(FP8x23 { mag: 10861756, sign: true });\n    data.append(FP8x23 { mag: 2660419, sign: true });\n    data.append(FP8x23 { mag: 3394808, sign: false });\n    data.append(FP8x23 { mag: 338183, sign: true });\n    data.append(FP8x23 { mag: 15733650, sign: true });\n    data.append(FP8x23 { mag: 12365466, sign: true });\n    data.append(FP8x23 { mag: 3541655, sign: false });\n    data.append(FP8x23 { mag: 32345368, sign: false });\n    data.append(FP8x23 { mag: 12452552, sign: false });\n    data.append(FP8x23 { mag: 14600115, sign: false });\n    data.append(FP8x23 { mag: 1293272, sign: true });\n    data.append(FP8x23 { mag: 2903611, sign: true });\n    data.append(FP8x23 { mag: 13665540, sign: false });\n    data.append(FP8x23 { mag: 12571296, sign: false });\n    data.append(FP8x23 { mag: 7735577, sign: false });\n    data.append(FP8x23 { mag: 7368433, sign: true });\n    data.append(FP8x23 { mag: 49328312, sign: true });\n    data.append(FP8x23 { mag: 7238951, sign: false });\n    data.append(FP8x23 { mag: 5862499, sign: false });\n    data.append(FP8x23 { mag: 17321778, sign: false });\n    data.append(FP8x23 { mag: 1710870, sign: true });\n    data.append(FP8x23 { mag: 21378808, sign: true });\n    data.append(FP8x23 { mag: 8095413, sign: false });\n    data.append(FP8x23 { mag: 7519097, sign: false });\n    data.append(FP8x23 { mag: 3932442, sign: true });\n    data.append(FP8x23 { mag: 4828702, sign: false });\n    data.append(FP8x23 { mag: 12534346, sign: true });\n    data.append(FP8x23 { mag: 4137026, sign: true });\n    data.append(FP8x23 { mag: 12111757, sign: false });\n    data.append(FP8x23 { mag: 1322099, sign: false });\n    data.append(FP8x23 { mag: 13513219, sign: false });\n    data.append(FP8x23 { mag: 17742402, sign: true });\n    data.append(FP8x23 { mag: 9128971, sign: true });\n    data.append(FP8x23 { mag: 20086140, sign: false });\n    data.append(FP8x23 { mag: 1382969, sign: false });\n    data.append(FP8x23 { mag: 6295538, sign: false });\n    data.append(FP8x23 { mag: 48501584, sign: false });\n    data.append(FP8x23 { mag: 11057000, sign: false });\n    data.append(FP8x23 { mag: 3609993, sign: false });\n    data.append(FP8x23 { mag: 4393747, sign: true });\n    data.append(FP8x23 { mag: 30512606, sign: false });\n    data.append(FP8x23 { mag: 5198704, sign: false });\n    data.append(FP8x23 { mag: 11397626, sign: false });\n    data.append(FP8x23 { mag: 215633, sign: false });\n    data.append(FP8x23 { mag: 17097970, sign: false });\n    data.append(FP8x23 { mag: 2401828, sign: true });\n    data.append(FP8x23 { mag: 10846288, sign: false });\n    data.append(FP8x23 { mag: 10888669, sign: false });\n    data.append(FP8x23 { mag: 15680364, sign: true });\n    data.append(FP8x23 { mag: 4840164, sign: true });\n    data.append(FP8x23 { mag: 13726524, sign: true });\n    data.append(FP8x23 { mag: 1114465, sign: true });\n    data.append(FP8x23 { mag: 3460715, sign: true });\n    data.append(FP8x23 { mag: 3823596, sign: true });\n    data.append(FP8x23 { mag: 1552296, sign: true });\n    data.append(FP8x23 { mag: 7058666, sign: true });\n    data.append(FP8x23 { mag: 553315, sign: true });\n    data.append(FP8x23 { mag: 878244, sign: false });\n    data.append(FP8x23 { mag: 20445996, sign: true });\n    data.append(FP8x23 { mag: 15251864, sign: false });\n    data.append(FP8x23 { mag: 15398532, sign: true });\n    data.append(FP8x23 { mag: 9638320, sign: true });\n    data.append(FP8x23 { mag: 6570754, sign: false });\n    data.append(FP8x23 { mag: 17975028, sign: true });\n    data.append(FP8x23 { mag: 1714295, sign: true });\n    data.append(FP8x23 { mag: 5911468, sign: true });\n    data.append(FP8x23 { mag: 3288110, sign: false });\n    data.append(FP8x23 { mag: 26095284, sign: false });\n    data.append(FP8x23 { mag: 5875775, sign: false });\n    data.append(FP8x23 { mag: 12397143, sign: false });\n    data.append(FP8x23 { mag: 1862939, sign: true });\n    data.append(FP8x23 { mag: 3423535, sign: false });\n    data.append(FP8x23 { mag: 10801258, sign: false });\n    data.append(FP8x23 { mag: 15308325, sign: false });\n    data.append(FP8x23 { mag: 3819202, sign: true });\n    data.append(FP8x23 { mag: 7393014, sign: true });\n    data.append(FP8x23 { mag: 12690310, sign: true });\n    data.append(FP8x23 { mag: 1407596, sign: false });\n    data.append(FP8x23 { mag: 8226985, sign: false });\n    data.append(FP8x23 { mag: 2689187, sign: false });\n    data.append(FP8x23 { mag: 14602564, sign: true });\n    data.append(FP8x23 { mag: 7153725, sign: true });\n    data.append(FP8x23 { mag: 6446196, sign: false });\n    data.append(FP8x23 { mag: 11344032, sign: false });\n    data.append(FP8x23 { mag: 5731847, sign: false });\n    data.append(FP8x23 { mag: 4922383, sign: false });\n    data.append(FP8x23 { mag: 3969367, sign: true });\n    data.append(FP8x23 { mag: 4351727, sign: true });\n    data.append(FP8x23 { mag: 2474283, sign: false });\n    data.append(FP8x23 { mag: 2720667, sign: false });\n    data.append(FP8x23 { mag: 9018600, sign: false });\n    data.append(FP8x23 { mag: 1979362, sign: true });\n    data.append(FP8x23 { mag: 10202510, sign: false });\n    data.append(FP8x23 { mag: 5638443, sign: false });\n    data.append(FP8x23 { mag: 2236335, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_4.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP8x23};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_4d_axis_negative_4() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::Some(-4), Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_4/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14135088, sign: true });\n    data.append(FP8x23 { mag: 16974250, sign: true });\n    data.append(FP8x23 { mag: 820692, sign: true });\n    data.append(FP8x23 { mag: 3250506, sign: true });\n    data.append(FP8x23 { mag: 11653046, sign: false });\n    data.append(FP8x23 { mag: 8310194, sign: false });\n    data.append(FP8x23 { mag: 2516595, sign: false });\n    data.append(FP8x23 { mag: 10139063, sign: true });\n    data.append(FP8x23 { mag: 3774983, sign: true });\n    data.append(FP8x23 { mag: 6392895, sign: true });\n    data.append(FP8x23 { mag: 7130434, sign: true });\n    data.append(FP8x23 { mag: 9570993, sign: false });\n    data.append(FP8x23 { mag: 1301459, sign: false });\n    data.append(FP8x23 { mag: 8016460, sign: true });\n    data.append(FP8x23 { mag: 5545983, sign: false });\n    data.append(FP8x23 { mag: 9974566, sign: false });\n    data.append(FP8x23 { mag: 3765257, sign: true });\n    data.append(FP8x23 { mag: 10580338, sign: false });\n    data.append(FP8x23 { mag: 4072127, sign: true });\n    data.append(FP8x23 { mag: 11406249, sign: true });\n    data.append(FP8x23 { mag: 1267835, sign: false });\n    data.append(FP8x23 { mag: 1455441, sign: true });\n    data.append(FP8x23 { mag: 647138, sign: true });\n    data.append(FP8x23 { mag: 7702541, sign: true });\n    data.append(FP8x23 { mag: 2456257, sign: true });\n    data.append(FP8x23 { mag: 3796222, sign: true });\n    data.append(FP8x23 { mag: 7306505, sign: false });\n    data.append(FP8x23 { mag: 4978121, sign: true });\n    data.append(FP8x23 { mag: 2468020, sign: true });\n    data.append(FP8x23 { mag: 7824061, sign: true });\n    data.append(FP8x23 { mag: 17727482, sign: true });\n    data.append(FP8x23 { mag: 7567520, sign: false });\n    data.append(FP8x23 { mag: 15121815, sign: true });\n    data.append(FP8x23 { mag: 17192194, sign: false });\n    data.append(FP8x23 { mag: 4838400, sign: false });\n    data.append(FP8x23 { mag: 7102806, sign: true });\n    data.append(FP8x23 { mag: 13506918, sign: false });\n    data.append(FP8x23 { mag: 9006810, sign: false });\n    data.append(FP8x23 { mag: 11880085, sign: false });\n    data.append(FP8x23 { mag: 10626748, sign: true });\n    data.append(FP8x23 { mag: 3396410, sign: false });\n    data.append(FP8x23 { mag: 19655650, sign: true });\n    data.append(FP8x23 { mag: 2999983, sign: false });\n    data.append(FP8x23 { mag: 2446665, sign: true });\n    data.append(FP8x23 { mag: 8376280, sign: true });\n    data.append(FP8x23 { mag: 4775309, sign: true });\n    data.append(FP8x23 { mag: 10598686, sign: false });\n    data.append(FP8x23 { mag: 4745864, sign: true });\n    data.append(FP8x23 { mag: 414428, sign: false });\n    data.append(FP8x23 { mag: 2015518, sign: false });\n    data.append(FP8x23 { mag: 5253980, sign: false });\n    data.append(FP8x23 { mag: 7583038, sign: false });\n    data.append(FP8x23 { mag: 899019, sign: false });\n    data.append(FP8x23 { mag: 6146756, sign: false });\n    data.append(FP8x23 { mag: 2662374, sign: false });\n    data.append(FP8x23 { mag: 2902689, sign: false });\n    data.append(FP8x23 { mag: 8841467, sign: false });\n    data.append(FP8x23 { mag: 3321704, sign: true });\n    data.append(FP8x23 { mag: 12138878, sign: false });\n    data.append(FP8x23 { mag: 1612645, sign: false });\n    data.append(FP8x23 { mag: 1933493, sign: false });\n    data.append(FP8x23 { mag: 17910888, sign: true });\n    data.append(FP8x23 { mag: 17723454, sign: false });\n    data.append(FP8x23 { mag: 7514799, sign: true });\n    data.append(FP8x23 { mag: 17173626, sign: false });\n    data.append(FP8x23 { mag: 21490536, sign: true });\n    data.append(FP8x23 { mag: 6905543, sign: false });\n    data.append(FP8x23 { mag: 805526, sign: true });\n    data.append(FP8x23 { mag: 302451, sign: false });\n    data.append(FP8x23 { mag: 1466887, sign: false });\n    data.append(FP8x23 { mag: 3126242, sign: false });\n    data.append(FP8x23 { mag: 5233297, sign: true });\n    data.append(FP8x23 { mag: 7328616, sign: true });\n    data.append(FP8x23 { mag: 883529, sign: true });\n    data.append(FP8x23 { mag: 3677998, sign: true });\n    data.append(FP8x23 { mag: 3261808, sign: true });\n    data.append(FP8x23 { mag: 3425112, sign: true });\n    data.append(FP8x23 { mag: 12840248, sign: false });\n    data.append(FP8x23 { mag: 764734, sign: true });\n    data.append(FP8x23 { mag: 7943693, sign: true });\n    data.append(FP8x23 { mag: 4316337, sign: true });\n    data.append(FP8x23 { mag: 1437067, sign: false });\n    data.append(FP8x23 { mag: 2863806, sign: true });\n    data.append(FP8x23 { mag: 11361048, sign: true });\n    data.append(FP8x23 { mag: 4986414, sign: true });\n    data.append(FP8x23 { mag: 9921546, sign: true });\n    data.append(FP8x23 { mag: 12757816, sign: false });\n    data.append(FP8x23 { mag: 15568051, sign: true });\n    data.append(FP8x23 { mag: 17115114, sign: false });\n    data.append(FP8x23 { mag: 1111349, sign: false });\n    data.append(FP8x23 { mag: 4315836, sign: true });\n    data.append(FP8x23 { mag: 7041772, sign: false });\n    data.append(FP8x23 { mag: 11618970, sign: true });\n    data.append(FP8x23 { mag: 10746123, sign: false });\n    data.append(FP8x23 { mag: 1666196, sign: true });\n    data.append(FP8x23 { mag: 5325180, sign: true });\n    data.append(FP8x23 { mag: 1658984, sign: true });\n    data.append(FP8x23 { mag: 5576354, sign: false });\n    data.append(FP8x23 { mag: 5117903, sign: false });\n    data.append(FP8x23 { mag: 4655447, sign: false });\n    data.append(FP8x23 { mag: 3665281, sign: true });\n    data.append(FP8x23 { mag: 1288444, sign: true });\n    data.append(FP8x23 { mag: 3863506, sign: true });\n    data.append(FP8x23 { mag: 134155, sign: false });\n    data.append(FP8x23 { mag: 9695251, sign: false });\n    data.append(FP8x23 { mag: 11656149, sign: false });\n    data.append(FP8x23 { mag: 2057527, sign: false });\n    data.append(FP8x23 { mag: 3055111, sign: false });\n    data.append(FP8x23 { mag: 3993322, sign: true });\n    data.append(FP8x23 { mag: 2834319, sign: true });\n    data.append(FP8x23 { mag: 5417702, sign: false });\n    data.append(FP8x23 { mag: 5944049, sign: true });\n    data.append(FP8x23 { mag: 1237020, sign: false });\n    data.append(FP8x23 { mag: 2002815, sign: false });\n    data.append(FP8x23 { mag: 1839059, sign: true });\n    data.append(FP8x23 { mag: 957417, sign: true });\n    data.append(FP8x23 { mag: 3144637, sign: true });\n    data.append(FP8x23 { mag: 12495473, sign: false });\n    data.append(FP8x23 { mag: 1419401, sign: false });\n    data.append(FP8x23 { mag: 956462, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_4/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 4525518, sign: false });\n    data.append(FP8x23 { mag: 5259039, sign: true });\n    data.append(FP8x23 { mag: 4902294, sign: true });\n    data.append(FP8x23 { mag: 7215282, sign: false });\n    data.append(FP8x23 { mag: 6105136, sign: true });\n    data.append(FP8x23 { mag: 11225632, sign: false });\n    data.append(FP8x23 { mag: 8302024, sign: false });\n    data.append(FP8x23 { mag: 16591307, sign: true });\n    data.append(FP8x23 { mag: 1674214, sign: true });\n    data.append(FP8x23 { mag: 6789284, sign: false });\n    data.append(FP8x23 { mag: 4502548, sign: true });\n    data.append(FP8x23 { mag: 7462902, sign: true });\n    data.append(FP8x23 { mag: 4320235, sign: true });\n    data.append(FP8x23 { mag: 3190392, sign: true });\n    data.append(FP8x23 { mag: 1740484, sign: false });\n    data.append(FP8x23 { mag: 1557919, sign: false });\n    data.append(FP8x23 { mag: 1374899, sign: false });\n    data.append(FP8x23 { mag: 9363886, sign: true });\n    data.append(FP8x23 { mag: 12480922, sign: false });\n    data.append(FP8x23 { mag: 20130672, sign: true });\n    data.append(FP8x23 { mag: 3971236, sign: true });\n    data.append(FP8x23 { mag: 7092766, sign: true });\n    data.append(FP8x23 { mag: 4235542, sign: false });\n    data.append(FP8x23 { mag: 6999284, sign: true });\n    data.append(FP8x23 { mag: 4524231, sign: false });\n    data.append(FP8x23 { mag: 1031761, sign: false });\n    data.append(FP8x23 { mag: 14527510, sign: true });\n    data.append(FP8x23 { mag: 15157414, sign: true });\n    data.append(FP8x23 { mag: 13849730, sign: true });\n    data.append(FP8x23 { mag: 7325780, sign: true });\n    data.append(FP8x23 { mag: 19150614, sign: true });\n    data.append(FP8x23 { mag: 3085445, sign: false });\n    data.append(FP8x23 { mag: 10552206, sign: true });\n    data.append(FP8x23 { mag: 7890319, sign: true });\n    data.append(FP8x23 { mag: 1390200, sign: false });\n    data.append(FP8x23 { mag: 7338448, sign: false });\n    data.append(FP8x23 { mag: 9865018, sign: false });\n    data.append(FP8x23 { mag: 5836528, sign: true });\n    data.append(FP8x23 { mag: 257489, sign: true });\n    data.append(FP8x23 { mag: 3419194, sign: false });\n    data.append(FP8x23 { mag: 4815813, sign: true });\n    data.append(FP8x23 { mag: 5451730, sign: true });\n    data.append(FP8x23 { mag: 5357836, sign: true });\n    data.append(FP8x23 { mag: 13437259, sign: true });\n    data.append(FP8x23 { mag: 12776456, sign: false });\n    data.append(FP8x23 { mag: 1040500, sign: false });\n    data.append(FP8x23 { mag: 6347629, sign: false });\n    data.append(FP8x23 { mag: 768580, sign: true });\n    data.append(FP8x23 { mag: 1856652, sign: false });\n    data.append(FP8x23 { mag: 9727590, sign: true });\n    data.append(FP8x23 { mag: 1163720, sign: true });\n    data.append(FP8x23 { mag: 19893312, sign: false });\n    data.append(FP8x23 { mag: 6670710, sign: false });\n    data.append(FP8x23 { mag: 12627989, sign: true });\n    data.append(FP8x23 { mag: 5925065, sign: true });\n    data.append(FP8x23 { mag: 2064145, sign: true });\n    data.append(FP8x23 { mag: 2921622, sign: true });\n    data.append(FP8x23 { mag: 6036185, sign: false });\n    data.append(FP8x23 { mag: 6012981, sign: true });\n    data.append(FP8x23 { mag: 8142272, sign: true });\n    data.append(FP8x23 { mag: 22916826, sign: false });\n    data.append(FP8x23 { mag: 9351772, sign: true });\n    data.append(FP8x23 { mag: 16524275, sign: true });\n    data.append(FP8x23 { mag: 2438246, sign: false });\n    data.append(FP8x23 { mag: 20169540, sign: true });\n    data.append(FP8x23 { mag: 134078, sign: true });\n    data.append(FP8x23 { mag: 2713766, sign: false });\n    data.append(FP8x23 { mag: 16188388, sign: false });\n    data.append(FP8x23 { mag: 3589682, sign: true });\n    data.append(FP8x23 { mag: 1063762, sign: true });\n    data.append(FP8x23 { mag: 7815083, sign: true });\n    data.append(FP8x23 { mag: 6348636, sign: false });\n    data.append(FP8x23 { mag: 4530695, sign: true });\n    data.append(FP8x23 { mag: 7469298, sign: false });\n    data.append(FP8x23 { mag: 7325134, sign: true });\n    data.append(FP8x23 { mag: 2692019, sign: false });\n    data.append(FP8x23 { mag: 874681, sign: true });\n    data.append(FP8x23 { mag: 6650540, sign: false });\n    data.append(FP8x23 { mag: 10089647, sign: false });\n    data.append(FP8x23 { mag: 4923024, sign: true });\n    data.append(FP8x23 { mag: 3315151, sign: false });\n    data.append(FP8x23 { mag: 1457470, sign: false });\n    data.append(FP8x23 { mag: 5470786, sign: false });\n    data.append(FP8x23 { mag: 2868822, sign: true });\n    data.append(FP8x23 { mag: 4246805, sign: true });\n    data.append(FP8x23 { mag: 18505256, sign: true });\n    data.append(FP8x23 { mag: 3936190, sign: true });\n    data.append(FP8x23 { mag: 8093713, sign: true });\n    data.append(FP8x23 { mag: 16349175, sign: false });\n    data.append(FP8x23 { mag: 11068122, sign: false });\n    data.append(FP8x23 { mag: 3749413, sign: false });\n    data.append(FP8x23 { mag: 17441864, sign: true });\n    data.append(FP8x23 { mag: 1883478, sign: false });\n    data.append(FP8x23 { mag: 9263616, sign: false });\n    data.append(FP8x23 { mag: 7243952, sign: true });\n    data.append(FP8x23 { mag: 405480, sign: false });\n    data.append(FP8x23 { mag: 7575996, sign: false });\n    data.append(FP8x23 { mag: 10759260, sign: false });\n    data.append(FP8x23 { mag: 2551835, sign: true });\n    data.append(FP8x23 { mag: 856625, sign: true });\n    data.append(FP8x23 { mag: 7553555, sign: false });\n    data.append(FP8x23 { mag: 1352994, sign: false });\n    data.append(FP8x23 { mag: 208875, sign: true });\n    data.append(FP8x23 { mag: 8348104, sign: true });\n    data.append(FP8x23 { mag: 491335, sign: true });\n    data.append(FP8x23 { mag: 11149267, sign: true });\n    data.append(FP8x23 { mag: 5898778, sign: false });\n    data.append(FP8x23 { mag: 4338052, sign: false });\n    data.append(FP8x23 { mag: 11249455, sign: true });\n    data.append(FP8x23 { mag: 756821, sign: true });\n    data.append(FP8x23 { mag: 3970259, sign: false });\n    data.append(FP8x23 { mag: 5989580, sign: true });\n    data.append(FP8x23 { mag: 11286085, sign: true });\n    data.append(FP8x23 { mag: 3635279, sign: false });\n    data.append(FP8x23 { mag: 3133278, sign: true });\n    data.append(FP8x23 { mag: 20313782, sign: false });\n    data.append(FP8x23 { mag: 13736921, sign: true });\n    data.append(FP8x23 { mag: 6854841, sign: true });\n    data.append(FP8x23 { mag: 14518657, sign: false });\n    data.append(FP8x23 { mag: 16244271, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_4/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 9356669, sign: false });\n    data.append(FP8x23 { mag: 4321566, sign: false });\n    data.append(FP8x23 { mag: 12889196, sign: false });\n    data.append(FP8x23 { mag: 12649253, sign: true });\n    data.append(FP8x23 { mag: 9137760, sign: true });\n    data.append(FP8x23 { mag: 655513, sign: false });\n    data.append(FP8x23 { mag: 1740834, sign: true });\n    data.append(FP8x23 { mag: 21648278, sign: true });\n    data.append(FP8x23 { mag: 664188, sign: true });\n    data.append(FP8x23 { mag: 10367219, sign: false });\n    data.append(FP8x23 { mag: 477453, sign: true });\n    data.append(FP8x23 { mag: 10536956, sign: false });\n    data.append(FP8x23 { mag: 9226832, sign: false });\n    data.append(FP8x23 { mag: 10996161, sign: true });\n    data.append(FP8x23 { mag: 5104221, sign: true });\n    data.append(FP8x23 { mag: 9511266, sign: true });\n    data.append(FP8x23 { mag: 974460, sign: false });\n    data.append(FP8x23 { mag: 4847155, sign: false });\n    data.append(FP8x23 { mag: 8103556, sign: false });\n    data.append(FP8x23 { mag: 3244957, sign: true });\n    data.append(FP8x23 { mag: 2802236, sign: false });\n    data.append(FP8x23 { mag: 1587211, sign: true });\n    data.append(FP8x23 { mag: 2695125, sign: false });\n    data.append(FP8x23 { mag: 2733983, sign: false });\n    data.append(FP8x23 { mag: 9818284, sign: false });\n    data.append(FP8x23 { mag: 13530923, sign: true });\n    data.append(FP8x23 { mag: 2639953, sign: true });\n    data.append(FP8x23 { mag: 2824861, sign: true });\n    data.append(FP8x23 { mag: 321756, sign: true });\n    data.append(FP8x23 { mag: 9810377, sign: false });\n    data.append(FP8x23 { mag: 19373754, sign: true });\n    data.append(FP8x23 { mag: 6743712, sign: true });\n    data.append(FP8x23 { mag: 15551278, sign: true });\n    data.append(FP8x23 { mag: 1501830, sign: false });\n    data.append(FP8x23 { mag: 5746712, sign: false });\n    data.append(FP8x23 { mag: 2844757, sign: false });\n    data.append(FP8x23 { mag: 1073141, sign: true });\n    data.append(FP8x23 { mag: 129722, sign: true });\n    data.append(FP8x23 { mag: 1379474, sign: true });\n    data.append(FP8x23 { mag: 6218418, sign: true });\n    data.append(FP8x23 { mag: 4615243, sign: false });\n    data.append(FP8x23 { mag: 9323116, sign: false });\n    data.append(FP8x23 { mag: 15992441, sign: false });\n    data.append(FP8x23 { mag: 14940432, sign: false });\n    data.append(FP8x23 { mag: 938580, sign: true });\n    data.append(FP8x23 { mag: 5536288, sign: true });\n    data.append(FP8x23 { mag: 10426515, sign: false });\n    data.append(FP8x23 { mag: 9866679, sign: false });\n    data.append(FP8x23 { mag: 12881712, sign: true });\n    data.append(FP8x23 { mag: 1205361, sign: false });\n    data.append(FP8x23 { mag: 2116248, sign: true });\n    data.append(FP8x23 { mag: 2551278, sign: true });\n    data.append(FP8x23 { mag: 12211160, sign: true });\n    data.append(FP8x23 { mag: 12214886, sign: true });\n    data.append(FP8x23 { mag: 1060373, sign: false });\n    data.append(FP8x23 { mag: 1544064, sign: true });\n    data.append(FP8x23 { mag: 9528255, sign: true });\n    data.append(FP8x23 { mag: 1485134, sign: true });\n    data.append(FP8x23 { mag: 2533885, sign: false });\n    data.append(FP8x23 { mag: 11694236, sign: true });\n    data.append(FP8x23 { mag: 8034937, sign: false });\n    data.append(FP8x23 { mag: 5450222, sign: true });\n    data.append(FP8x23 { mag: 9130253, sign: false });\n    data.append(FP8x23 { mag: 1643301, sign: false });\n    data.append(FP8x23 { mag: 330497, sign: true });\n    data.append(FP8x23 { mag: 18730094, sign: true });\n    data.append(FP8x23 { mag: 9596369, sign: true });\n    data.append(FP8x23 { mag: 1349540, sign: false });\n    data.append(FP8x23 { mag: 825993, sign: true });\n    data.append(FP8x23 { mag: 2628970, sign: true });\n    data.append(FP8x23 { mag: 5667817, sign: true });\n    data.append(FP8x23 { mag: 18206424, sign: false });\n    data.append(FP8x23 { mag: 1710864, sign: true });\n    data.append(FP8x23 { mag: 8111602, sign: false });\n    data.append(FP8x23 { mag: 8977911, sign: true });\n    data.append(FP8x23 { mag: 1211268, sign: true });\n    data.append(FP8x23 { mag: 2455632, sign: true });\n    data.append(FP8x23 { mag: 1977709, sign: false });\n    data.append(FP8x23 { mag: 11296273, sign: true });\n    data.append(FP8x23 { mag: 16922314, sign: true });\n    data.append(FP8x23 { mag: 9726242, sign: false });\n    data.append(FP8x23 { mag: 795335, sign: true });\n    data.append(FP8x23 { mag: 566574, sign: false });\n    data.append(FP8x23 { mag: 10365729, sign: false });\n    data.append(FP8x23 { mag: 8084625, sign: true });\n    data.append(FP8x23 { mag: 8689213, sign: false });\n    data.append(FP8x23 { mag: 4856601, sign: true });\n    data.append(FP8x23 { mag: 11550873, sign: true });\n    data.append(FP8x23 { mag: 4699438, sign: false });\n    data.append(FP8x23 { mag: 275684, sign: true });\n    data.append(FP8x23 { mag: 8704336, sign: true });\n    data.append(FP8x23 { mag: 379253, sign: false });\n    data.append(FP8x23 { mag: 4344884, sign: true });\n    data.append(FP8x23 { mag: 22511138, sign: true });\n    data.append(FP8x23 { mag: 9166379, sign: false });\n    data.append(FP8x23 { mag: 2883054, sign: true });\n    data.append(FP8x23 { mag: 5212371, sign: true });\n    data.append(FP8x23 { mag: 11557156, sign: false });\n    data.append(FP8x23 { mag: 1653742, sign: true });\n    data.append(FP8x23 { mag: 17620446, sign: true });\n    data.append(FP8x23 { mag: 2869877, sign: true });\n    data.append(FP8x23 { mag: 12529882, sign: true });\n    data.append(FP8x23 { mag: 6358051, sign: false });\n    data.append(FP8x23 { mag: 3299874, sign: false });\n    data.append(FP8x23 { mag: 2066510, sign: false });\n    data.append(FP8x23 { mag: 6576978, sign: false });\n    data.append(FP8x23 { mag: 5426550, sign: false });\n    data.append(FP8x23 { mag: 14043765, sign: true });\n    data.append(FP8x23 { mag: 101030, sign: false });\n    data.append(FP8x23 { mag: 2547235, sign: true });\n    data.append(FP8x23 { mag: 10267325, sign: false });\n    data.append(FP8x23 { mag: 5464667, sign: true });\n    data.append(FP8x23 { mag: 3669542, sign: false });\n    data.append(FP8x23 { mag: 9605139, sign: false });\n    data.append(FP8x23 { mag: 8012144, sign: false });\n    data.append(FP8x23 { mag: 3023674, sign: false });\n    data.append(FP8x23 { mag: 12049591, sign: true });\n    data.append(FP8x23 { mag: 13005965, sign: false });\n    data.append(FP8x23 { mag: 5010748, sign: true });\n    data.append(FP8x23 { mag: 4764491, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_4d_axis_negative_4/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 1635828, sign: false });\n    data.append(FP8x23 { mag: 15119412, sign: false });\n    data.append(FP8x23 { mag: 13272471, sign: false });\n    data.append(FP8x23 { mag: 15356888, sign: true });\n    data.append(FP8x23 { mag: 17971400, sign: true });\n    data.append(FP8x23 { mag: 12310023, sign: false });\n    data.append(FP8x23 { mag: 997595, sign: false });\n    data.append(FP8x23 { mag: 1448470, sign: true });\n    data.append(FP8x23 { mag: 71442, sign: false });\n    data.append(FP8x23 { mag: 5210973, sign: false });\n    data.append(FP8x23 { mag: 3348107, sign: false });\n    data.append(FP8x23 { mag: 1638514, sign: false });\n    data.append(FP8x23 { mag: 8443650, sign: false });\n    data.append(FP8x23 { mag: 7939849, sign: true });\n    data.append(FP8x23 { mag: 3885465, sign: true });\n    data.append(FP8x23 { mag: 7576798, sign: true });\n    data.append(FP8x23 { mag: 371979, sign: false });\n    data.append(FP8x23 { mag: 7473513, sign: true });\n    data.append(FP8x23 { mag: 2166138, sign: false });\n    data.append(FP8x23 { mag: 24382900, sign: false });\n    data.append(FP8x23 { mag: 2098648, sign: false });\n    data.append(FP8x23 { mag: 482226, sign: true });\n    data.append(FP8x23 { mag: 2453855, sign: false });\n    data.append(FP8x23 { mag: 9170470, sign: false });\n    data.append(FP8x23 { mag: 8559846, sign: false });\n    data.append(FP8x23 { mag: 13986947, sign: true });\n    data.append(FP8x23 { mag: 15939734, sign: true });\n    data.append(FP8x23 { mag: 6064824, sign: false });\n    data.append(FP8x23 { mag: 3550536, sign: false });\n    data.append(FP8x23 { mag: 16655951, sign: false });\n    data.append(FP8x23 { mag: 21709898, sign: false });\n    data.append(FP8x23 { mag: 3820554, sign: true });\n    data.append(FP8x23 { mag: 3724540, sign: false });\n    data.append(FP8x23 { mag: 15258496, sign: true });\n    data.append(FP8x23 { mag: 6599915, sign: false });\n    data.append(FP8x23 { mag: 3365518, sign: true });\n    data.append(FP8x23 { mag: 15436782, sign: false });\n    data.append(FP8x23 { mag: 6686343, sign: true });\n    data.append(FP8x23 { mag: 1759188, sign: true });\n    data.append(FP8x23 { mag: 10585142, sign: true });\n    data.append(FP8x23 { mag: 2508703, sign: false });\n    data.append(FP8x23 { mag: 22303900, sign: false });\n    data.append(FP8x23 { mag: 13908498, sign: false });\n    data.append(FP8x23 { mag: 18662316, sign: false });\n    data.append(FP8x23 { mag: 13740165, sign: true });\n    data.append(FP8x23 { mag: 6120731, sign: true });\n    data.append(FP8x23 { mag: 18792740, sign: false });\n    data.append(FP8x23 { mag: 10295619, sign: false });\n    data.append(FP8x23 { mag: 12746493, sign: true });\n    data.append(FP8x23 { mag: 1407339, sign: true });\n    data.append(FP8x23 { mag: 2889584, sign: true });\n    data.append(FP8x23 { mag: 16333434, sign: false });\n    data.append(FP8x23 { mag: 11330107, sign: true });\n    data.append(FP8x23 { mag: 21985066, sign: true });\n    data.append(FP8x23 { mag: 999620, sign: true });\n    data.append(FP8x23 { mag: 2322364, sign: true });\n    data.append(FP8x23 { mag: 12751276, sign: true });\n    data.append(FP8x23 { mag: 3802842, sign: true });\n    data.append(FP8x23 { mag: 6523586, sign: true });\n    data.append(FP8x23 { mag: 13480076, sign: true });\n    data.append(FP8x23 { mag: 13960264, sign: false });\n    data.append(FP8x23 { mag: 14821762, sign: false });\n    data.append(FP8x23 { mag: 27043336, sign: true });\n    data.append(FP8x23 { mag: 542922, sign: true });\n    data.append(FP8x23 { mag: 43128104, sign: true });\n    data.append(FP8x23 { mag: 18380770, sign: true });\n    data.append(FP8x23 { mag: 7244983, sign: true });\n    data.append(FP8x23 { mag: 113904, sign: false });\n    data.append(FP8x23 { mag: 1038282, sign: true });\n    data.append(FP8x23 { mag: 2843327, sign: true });\n    data.append(FP8x23 { mag: 8828154, sign: true });\n    data.append(FP8x23 { mag: 14284936, sign: false });\n    data.append(FP8x23 { mag: 2248393, sign: false });\n    data.append(FP8x23 { mag: 7470248, sign: false });\n    data.append(FP8x23 { mag: 5846187, sign: true });\n    data.append(FP8x23 { mag: 2225206, sign: true });\n    data.append(FP8x23 { mag: 2108722, sign: true });\n    data.append(FP8x23 { mag: 12565851, sign: false });\n    data.append(FP8x23 { mag: 12016079, sign: true });\n    data.append(FP8x23 { mag: 12249987, sign: true });\n    data.append(FP8x23 { mag: 8050175, sign: false });\n    data.append(FP8x23 { mag: 506957, sign: true });\n    data.append(FP8x23 { mag: 1227756, sign: true });\n    data.append(FP8x23 { mag: 14287121, sign: false });\n    data.append(FP8x23 { mag: 5589607, sign: true });\n    data.append(FP8x23 { mag: 30727100, sign: false });\n    data.append(FP8x23 { mag: 11083630, sign: true });\n    data.append(FP8x23 { mag: 3675577, sign: false });\n    data.append(FP8x23 { mag: 39273680, sign: false });\n    data.append(FP8x23 { mag: 1473504, sign: false });\n    data.append(FP8x23 { mag: 10599726, sign: true });\n    data.append(FP8x23 { mag: 15024036, sign: true });\n    data.append(FP8x23 { mag: 6978806, sign: true });\n    data.append(FP8x23 { mag: 10134630, sign: true });\n    data.append(FP8x23 { mag: 10481579, sign: false });\n    data.append(FP8x23 { mag: 3138070, sign: true });\n    data.append(FP8x23 { mag: 6581176, sign: true });\n    data.append(FP8x23 { mag: 19131162, sign: false });\n    data.append(FP8x23 { mag: 3307076, sign: true });\n    data.append(FP8x23 { mag: 18127018, sign: true });\n    data.append(FP8x23 { mag: 6087514, sign: true });\n    data.append(FP8x23 { mag: 12713040, sign: true });\n    data.append(FP8x23 { mag: 6452089, sign: false });\n    data.append(FP8x23 { mag: 2977957, sign: false });\n    data.append(FP8x23 { mag: 1473198, sign: false });\n    data.append(FP8x23 { mag: 9559340, sign: true });\n    data.append(FP8x23 { mag: 7041180, sign: false });\n    data.append(FP8x23 { mag: 12327230, sign: true });\n    data.append(FP8x23 { mag: 5344226, sign: false });\n    data.append(FP8x23 { mag: 2301738, sign: true });\n    data.append(FP8x23 { mag: 12985185, sign: false });\n    data.append(FP8x23 { mag: 1244468, sign: true });\n    data.append(FP8x23 { mag: 1712494, sign: false });\n    data.append(FP8x23 { mag: 10575880, sign: false });\n    data.append(FP8x23 { mag: 8647239, sign: false });\n    data.append(FP8x23 { mag: 1095909, sign: false });\n    data.append(FP8x23 { mag: 7072431, sign: true });\n    data.append(FP8x23 { mag: 2381521, sign: false });\n    data.append(FP8x23 { mag: 2169412, sign: true });\n    data.append(FP8x23 { mag: 3224816, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_default_axis.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_default_axis() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::None, Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_default_axis/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 64602, sign: false });\n    data.append(FP16x16 { mag: 26167, sign: false });\n    data.append(FP16x16 { mag: 88402, sign: true });\n    data.append(FP16x16 { mag: 30731, sign: false });\n    data.append(FP16x16 { mag: 20146, sign: false });\n    data.append(FP16x16 { mag: 26491, sign: false });\n    data.append(FP16x16 { mag: 57414, sign: false });\n    data.append(FP16x16 { mag: 19431, sign: true });\n    data.append(FP16x16 { mag: 8560, sign: false });\n    data.append(FP16x16 { mag: 28768, sign: true });\n    data.append(FP16x16 { mag: 117108, sign: true });\n    data.append(FP16x16 { mag: 161076, sign: true });\n    data.append(FP16x16 { mag: 60002, sign: false });\n    data.append(FP16x16 { mag: 25748, sign: false });\n    data.append(FP16x16 { mag: 45775, sign: true });\n    data.append(FP16x16 { mag: 8379, sign: true });\n    data.append(FP16x16 { mag: 4860, sign: true });\n    data.append(FP16x16 { mag: 19966, sign: false });\n    data.append(FP16x16 { mag: 123117, sign: false });\n    data.append(FP16x16 { mag: 39789, sign: false });\n    data.append(FP16x16 { mag: 156001, sign: true });\n    data.append(FP16x16 { mag: 26549, sign: false });\n    data.append(FP16x16 { mag: 191014, sign: false });\n    data.append(FP16x16 { mag: 62627, sign: true });\n    data.append(FP16x16 { mag: 59690, sign: true });\n    data.append(FP16x16 { mag: 68003, sign: true });\n    data.append(FP16x16 { mag: 133782, sign: true });\n    data.append(FP16x16 { mag: 20370, sign: false });\n    data.append(FP16x16 { mag: 78702, sign: false });\n    data.append(FP16x16 { mag: 2397, sign: false });\n    data.append(FP16x16 { mag: 37450, sign: false });\n    data.append(FP16x16 { mag: 64629, sign: false });\n    data.append(FP16x16 { mag: 39733, sign: false });\n    data.append(FP16x16 { mag: 104565, sign: false });\n    data.append(FP16x16 { mag: 56385, sign: false });\n    data.append(FP16x16 { mag: 11447, sign: false });\n    data.append(FP16x16 { mag: 135879, sign: false });\n    data.append(FP16x16 { mag: 67891, sign: true });\n    data.append(FP16x16 { mag: 121976, sign: true });\n    data.append(FP16x16 { mag: 5320, sign: false });\n    data.append(FP16x16 { mag: 53119, sign: true });\n    data.append(FP16x16 { mag: 84, sign: false });\n    data.append(FP16x16 { mag: 21896, sign: false });\n    data.append(FP16x16 { mag: 34587, sign: true });\n    data.append(FP16x16 { mag: 83500, sign: true });\n    data.append(FP16x16 { mag: 7325, sign: false });\n    data.append(FP16x16 { mag: 85656, sign: true });\n    data.append(FP16x16 { mag: 87252, sign: false });\n    data.append(FP16x16 { mag: 7076, sign: true });\n    data.append(FP16x16 { mag: 23654, sign: true });\n    data.append(FP16x16 { mag: 67732, sign: false });\n    data.append(FP16x16 { mag: 37838, sign: true });\n    data.append(FP16x16 { mag: 18205, sign: true });\n    data.append(FP16x16 { mag: 39334, sign: true });\n    data.append(FP16x16 { mag: 2652, sign: true });\n    data.append(FP16x16 { mag: 11349, sign: true });\n    data.append(FP16x16 { mag: 109949, sign: false });\n    data.append(FP16x16 { mag: 16940, sign: true });\n    data.append(FP16x16 { mag: 128278, sign: true });\n    data.append(FP16x16 { mag: 67936, sign: true });\n    data.append(FP16x16 { mag: 14710, sign: false });\n    data.append(FP16x16 { mag: 28567, sign: true });\n    data.append(FP16x16 { mag: 68311, sign: false });\n    data.append(FP16x16 { mag: 55974, sign: false });\n    data.append(FP16x16 { mag: 63420, sign: false });\n    data.append(FP16x16 { mag: 75349, sign: true });\n    data.append(FP16x16 { mag: 3746, sign: true });\n    data.append(FP16x16 { mag: 998, sign: false });\n    data.append(FP16x16 { mag: 119081, sign: true });\n    data.append(FP16x16 { mag: 25450, sign: false });\n    data.append(FP16x16 { mag: 81231, sign: false });\n    data.append(FP16x16 { mag: 65013, sign: true });\n    data.append(FP16x16 { mag: 16931, sign: false });\n    data.append(FP16x16 { mag: 14035, sign: true });\n    data.append(FP16x16 { mag: 7760, sign: false });\n    data.append(FP16x16 { mag: 28307, sign: false });\n    data.append(FP16x16 { mag: 4283, sign: false });\n    data.append(FP16x16 { mag: 13410, sign: true });\n    data.append(FP16x16 { mag: 22979, sign: true });\n    data.append(FP16x16 { mag: 17571, sign: true });\n    data.append(FP16x16 { mag: 2523, sign: false });\n    data.append(FP16x16 { mag: 38005, sign: false });\n    data.append(FP16x16 { mag: 86948, sign: false });\n    data.append(FP16x16 { mag: 4605, sign: true });\n    data.append(FP16x16 { mag: 34628, sign: false });\n    data.append(FP16x16 { mag: 11983, sign: false });\n    data.append(FP16x16 { mag: 3697, sign: false });\n    data.append(FP16x16 { mag: 24864, sign: false });\n    data.append(FP16x16 { mag: 21188, sign: true });\n    data.append(FP16x16 { mag: 73912, sign: false });\n    data.append(FP16x16 { mag: 77630, sign: true });\n    data.append(FP16x16 { mag: 45833, sign: true });\n    data.append(FP16x16 { mag: 87681, sign: true });\n    data.append(FP16x16 { mag: 3396, sign: false });\n    data.append(FP16x16 { mag: 3239, sign: false });\n    data.append(FP16x16 { mag: 68960, sign: true });\n    data.append(FP16x16 { mag: 11032, sign: false });\n    data.append(FP16x16 { mag: 51110, sign: false });\n    data.append(FP16x16 { mag: 21945, sign: true });\n    data.append(FP16x16 { mag: 63090, sign: false });\n    data.append(FP16x16 { mag: 5950, sign: true });\n    data.append(FP16x16 { mag: 117950, sign: false });\n    data.append(FP16x16 { mag: 68215, sign: false });\n    data.append(FP16x16 { mag: 62288, sign: true });\n    data.append(FP16x16 { mag: 47333, sign: false });\n    data.append(FP16x16 { mag: 133116, sign: true });\n    data.append(FP16x16 { mag: 63795, sign: false });\n    data.append(FP16x16 { mag: 23343, sign: false });\n    data.append(FP16x16 { mag: 74308, sign: true });\n    data.append(FP16x16 { mag: 54548, sign: true });\n    data.append(FP16x16 { mag: 12541, sign: true });\n    data.append(FP16x16 { mag: 26795, sign: true });\n    data.append(FP16x16 { mag: 2291, sign: false });\n    data.append(FP16x16 { mag: 88058, sign: true });\n    data.append(FP16x16 { mag: 14460, sign: true });\n    data.append(FP16x16 { mag: 173994, sign: false });\n    data.append(FP16x16 { mag: 138436, sign: true });\n    data.append(FP16x16 { mag: 33664, sign: false });\n    data.append(FP16x16 { mag: 53676, sign: true });\n    data.append(FP16x16 { mag: 61132, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_default_axis/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 35508, sign: false });\n    data.append(FP16x16 { mag: 113098, sign: false });\n    data.append(FP16x16 { mag: 98425, sign: true });\n    data.append(FP16x16 { mag: 17510, sign: true });\n    data.append(FP16x16 { mag: 105804, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_default_axis/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 111176, sign: false });\n    data.append(FP16x16 { mag: 17239, sign: false });\n    data.append(FP16x16 { mag: 61606, sign: false });\n    data.append(FP16x16 { mag: 56902, sign: false });\n    data.append(FP16x16 { mag: 5890, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_default_axis/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n    shape.append(4);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 148105, sign: false });\n    data.append(FP16x16 { mag: 51069, sign: false });\n    data.append(FP16x16 { mag: 249530, sign: false });\n    data.append(FP16x16 { mag: 50124, sign: false });\n    data.append(FP16x16 { mag: 25260, sign: false });\n    data.append(FP16x16 { mag: 131213, sign: false });\n    data.append(FP16x16 { mag: 192949, sign: false });\n    data.append(FP16x16 { mag: 150671, sign: false });\n    data.append(FP16x16 { mag: 57066, sign: false });\n    data.append(FP16x16 { mag: 121458, sign: true });\n    data.append(FP16x16 { mag: 81554, sign: false });\n    data.append(FP16x16 { mag: 136827, sign: true });\n    data.append(FP16x16 { mag: 65628, sign: true });\n    data.append(FP16x16 { mag: 41469, sign: false });\n    data.append(FP16x16 { mag: 8262, sign: false });\n    data.append(FP16x16 { mag: 79823, sign: false });\n    data.append(FP16x16 { mag: 74314, sign: true });\n    data.append(FP16x16 { mag: 90284, sign: false });\n    data.append(FP16x16 { mag: 24306, sign: false });\n    data.append(FP16x16 { mag: 18836, sign: false });\n    data.append(FP16x16 { mag: 67465, sign: false });\n    data.append(FP16x16 { mag: 54695, sign: false });\n    data.append(FP16x16 { mag: 109517, sign: true });\n    data.append(FP16x16 { mag: 64466, sign: false });\n    data.append(FP16x16 { mag: 37152, sign: true });\n    data.append(FP16x16 { mag: 88064, sign: false });\n    data.append(FP16x16 { mag: 157380, sign: true });\n    data.append(FP16x16 { mag: 7574, sign: false });\n    data.append(FP16x16 { mag: 33421, sign: false });\n    data.append(FP16x16 { mag: 38156, sign: false });\n    data.append(FP16x16 { mag: 77338, sign: false });\n    data.append(FP16x16 { mag: 36257, sign: false });\n    data.append(FP16x16 { mag: 146134, sign: false });\n    data.append(FP16x16 { mag: 25111, sign: false });\n    data.append(FP16x16 { mag: 12299, sign: true });\n    data.append(FP16x16 { mag: 118888, sign: false });\n    data.append(FP16x16 { mag: 203585, sign: false });\n    data.append(FP16x16 { mag: 130002, sign: false });\n    data.append(FP16x16 { mag: 79958, sign: false });\n    data.append(FP16x16 { mag: 21416, sign: false });\n    data.append(FP16x16 { mag: 89115, sign: false });\n    data.append(FP16x16 { mag: 107601, sign: false });\n    data.append(FP16x16 { mag: 74343, sign: true });\n    data.append(FP16x16 { mag: 59119, sign: false });\n    data.append(FP16x16 { mag: 145656, sign: true });\n    data.append(FP16x16 { mag: 118625, sign: false });\n    data.append(FP16x16 { mag: 147797, sign: true });\n    data.append(FP16x16 { mag: 100250, sign: true });\n    data.append(FP16x16 { mag: 57755, sign: false });\n    data.append(FP16x16 { mag: 30748, sign: true });\n    data.append(FP16x16 { mag: 177852, sign: false });\n    data.append(FP16x16 { mag: 74217, sign: true });\n    data.append(FP16x16 { mag: 92027, sign: false });\n    data.append(FP16x16 { mag: 71729, sign: false });\n    data.append(FP16x16 { mag: 15065, sign: false });\n    data.append(FP16x16 { mag: 116394, sign: false });\n    data.append(FP16x16 { mag: 208223, sign: false });\n    data.append(FP16x16 { mag: 54137, sign: false });\n    data.append(FP16x16 { mag: 80353, sign: false });\n    data.append(FP16x16 { mag: 54658, sign: true });\n    data.append(FP16x16 { mag: 91876, sign: false });\n    data.append(FP16x16 { mag: 176865, sign: true });\n    data.append(FP16x16 { mag: 27849, sign: true });\n    data.append(FP16x16 { mag: 46841, sign: false });\n    data.append(FP16x16 { mag: 88031, sign: false });\n    data.append(FP16x16 { mag: 84253, sign: false });\n    data.append(FP16x16 { mag: 81232, sign: false });\n    data.append(FP16x16 { mag: 2720, sign: true });\n    data.append(FP16x16 { mag: 84339, sign: false });\n    data.append(FP16x16 { mag: 122880, sign: false });\n    data.append(FP16x16 { mag: 168024, sign: false });\n    data.append(FP16x16 { mag: 150776, sign: true });\n    data.append(FP16x16 { mag: 37600, sign: false });\n    data.append(FP16x16 { mag: 64076, sign: false });\n    data.append(FP16x16 { mag: 11218, sign: false });\n    data.append(FP16x16 { mag: 173101, sign: false });\n    data.append(FP16x16 { mag: 69045, sign: false });\n    data.append(FP16x16 { mag: 109739, sign: false });\n    data.append(FP16x16 { mag: 74434, sign: false });\n    data.append(FP16x16 { mag: 69416, sign: true });\n    data.append(FP16x16 { mag: 79483, sign: false });\n    data.append(FP16x16 { mag: 39901, sign: false });\n    data.append(FP16x16 { mag: 106494, sign: true });\n    data.append(FP16x16 { mag: 76376, sign: false });\n    data.append(FP16x16 { mag: 16086, sign: false });\n    data.append(FP16x16 { mag: 103647, sign: false });\n    data.append(FP16x16 { mag: 36533, sign: true });\n    data.append(FP16x16 { mag: 42174, sign: false });\n    data.append(FP16x16 { mag: 79080, sign: false });\n    data.append(FP16x16 { mag: 191746, sign: false });\n    data.append(FP16x16 { mag: 77441, sign: false });\n    data.append(FP16x16 { mag: 2812, sign: false });\n    data.append(FP16x16 { mag: 180705, sign: false });\n    data.append(FP16x16 { mag: 36837, sign: false });\n    data.append(FP16x16 { mag: 126699, sign: false });\n    data.append(FP16x16 { mag: 55555, sign: false });\n    data.append(FP16x16 { mag: 26973, sign: false });\n    data.append(FP16x16 { mag: 28356, sign: true });\n    data.append(FP16x16 { mag: 67324, sign: false });\n    data.append(FP16x16 { mag: 128783, sign: false });\n    data.append(FP16x16 { mag: 88862, sign: false });\n    data.append(FP16x16 { mag: 171949, sign: false });\n    data.append(FP16x16 { mag: 5842, sign: false });\n    data.append(FP16x16 { mag: 83802, sign: false });\n    data.append(FP16x16 { mag: 30236, sign: false });\n    data.append(FP16x16 { mag: 61609, sign: false });\n    data.append(FP16x16 { mag: 176100, sign: false });\n    data.append(FP16x16 { mag: 20018, sign: true });\n    data.append(FP16x16 { mag: 66700, sign: false });\n    data.append(FP16x16 { mag: 23575, sign: true });\n    data.append(FP16x16 { mag: 128526, sign: false });\n    data.append(FP16x16 { mag: 21255, sign: false });\n    data.append(FP16x16 { mag: 32892, sign: true });\n    data.append(FP16x16 { mag: 90380, sign: false });\n    data.append(FP16x16 { mag: 51132, sign: false });\n    data.append(FP16x16 { mag: 164403, sign: false });\n    data.append(FP16x16 { mag: 147072, sign: true });\n    data.append(FP16x16 { mag: 44562, sign: false });\n    data.append(FP16x16 { mag: 68319, sign: false });\n    data.append(FP16x16 { mag: 51670, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_test.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_layer_normalization_test() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z_0 = output_0::output_0();\n\n    let (y_0, _, _) = input_0\n        .layer_normalization(\n            @input_1, Option::Some(@input_2), Option::None, Option::None, Option::None\n        );\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_test/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 60552, sign: false });\n    data.append(FP16x16 { mag: 32131, sign: true });\n    data.append(FP16x16 { mag: 17263, sign: false });\n    data.append(FP16x16 { mag: 17309, sign: false });\n    data.append(FP16x16 { mag: 75079, sign: true });\n    data.append(FP16x16 { mag: 132412, sign: true });\n    data.append(FP16x16 { mag: 72947, sign: false });\n    data.append(FP16x16 { mag: 89468, sign: false });\n    data.append(FP16x16 { mag: 9763, sign: false });\n    data.append(FP16x16 { mag: 43535, sign: true });\n    data.append(FP16x16 { mag: 137407, sign: false });\n    data.append(FP16x16 { mag: 45433, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_test/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 60302, sign: false });\n    data.append(FP16x16 { mag: 171263, sign: false });\n    data.append(FP16x16 { mag: 38170, sign: true });\n    data.append(FP16x16 { mag: 102181, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_test/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 15701, sign: true });\n    data.append(FP16x16 { mag: 15386, sign: false });\n    data.append(FP16x16 { mag: 38358, sign: false });\n    data.append(FP16x16 { mag: 48407, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/layer_normalization_test/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 66655, sign: false });\n    data.append(FP16x16 { mag: 234574, sign: true });\n    data.append(FP16x16 { mag: 36595, sign: false });\n    data.append(FP16x16 { mag: 43544, sign: false });\n    data.append(FP16x16 { mag: 56268, sign: true });\n    data.append(FP16x16 { mag: 203346, sign: true });\n    data.append(FP16x16 { mag: 4468, sign: false });\n    data.append(FP16x16 { mag: 60114, sign: true });\n    data.append(FP16x16 { mag: 19585, sign: true });\n    data.append(FP16x16 { mag: 118482, sign: true });\n    data.append(FP16x16 { mag: 24747, sign: true });\n    data.append(FP16x16 { mag: 130887, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::FP16x16NN;\nuse orion::operators::nn::NNTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_leaky_relu_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::leaky_relu(@input_0, @FixedTrait::new(6554, false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 262956, sign: true });\n    data.append(FP16x16 { mag: 93265, sign: false });\n    data.append(FP16x16 { mag: 218381, sign: true });\n    data.append(FP16x16 { mag: 244376, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 26295, sign: true });\n    data.append(FP16x16 { mag: 93265, sign: false });\n    data.append(FP16x16 { mag: 21838, sign: true });\n    data.append(FP16x16 { mag: 24437, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::nn::FP8x23NN;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::nn::NNTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_leaky_relu_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::leaky_relu(@input_0, @FixedTrait::new(838861, false));\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14080598, sign: false });\n    data.append(FP8x23 { mag: 57593374, sign: false });\n    data.append(FP8x23 { mag: 23686131, sign: false });\n    data.append(FP8x23 { mag: 26702392, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/leaky_relu_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 14080599, sign: false });\n    data.append(FP8x23 { mag: 57593376, sign: false });\n    data.append(FP8x23 { mag: 23686132, sign: false });\n    data.append(FP8x23 { mag: 2670239, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_equal_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less_equal(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_equal_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorAdd};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorAdd};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    data.append(0);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(-2);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-3);\n    data.append(0);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(-3);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-3);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    data.append(1);\n    data.append(-1);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(-1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_less_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z_0 = output_0::output_0();\n\n    let y_0 = input_0.less(@input_1);\n\n    assert_eq(y_0, z_0);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/less_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorAdd};\nuse orion::numbers::NumberTrait;\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::FP16x16NN;\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_linear_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::linear(input_0, input_1, input_2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 185755, sign: false });\n    data.append(FP16x16 { mag: 99924, sign: true });\n    data.append(FP16x16 { mag: 46055, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 429406, sign: false });\n    data.append(FP16x16 { mag: 288523, sign: false });\n    data.append(FP16x16 { mag: 414929, sign: false });\n    data.append(FP16x16 { mag: 259811, sign: true });\n    data.append(FP16x16 { mag: 394274, sign: false });\n    data.append(FP16x16 { mag: 314398, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp16x16/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 18363, sign: true });\n    data.append(FP16x16 { mag: 80823, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 467238, sign: false });\n    data.append(FP16x16 { mag: 1035802, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::FP8x23NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_linear_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::linear(input_0, input_1, input_2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 55312980, sign: false });\n    data.append(FP8x23 { mag: 3192975, sign: true });\n    data.append(FP8x23 { mag: 30534236, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 53179762, sign: false });\n    data.append(FP8x23 { mag: 34716255, sign: false });\n    data.append(FP8x23 { mag: 6923297, sign: false });\n    data.append(FP8x23 { mag: 2365083, sign: true });\n    data.append(FP8x23 { mag: 35449593, sign: true });\n    data.append(FP8x23 { mag: 46253431, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp8x23/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 57085261, sign: false });\n    data.append(FP8x23 { mag: 10010743, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 419729535, sign: false });\n    data.append(FP8x23 { mag: 176269923, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::I32NN;\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::numbers::FixedTrait;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_linear_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::linear(input_0, input_1, input_2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(-1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(6);\n    data.append(6);\n    data.append(5);\n    data.append(-3);\n    data.append(6);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i32/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(36);\n    data.append(-9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::I8NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_linear_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::linear(input_0, input_1, input_2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i8/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::nn::NNTrait;\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::U32NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_linear_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = NNTrait::linear(input_0, input_1, input_2);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_u32/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/linear_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(17);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_log_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.log();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 1614287, sign: false });\n    data.append(FP16x16 { mag: 3665868, sign: false });\n    data.append(FP16x16 { mag: 4581929, sign: false });\n    data.append(FP16x16 { mag: 1000635, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 209980, sign: false });\n    data.append(FP16x16 { mag: 263731, sign: false });\n    data.append(FP16x16 { mag: 278349, sign: false });\n    data.append(FP16x16 { mag: 178637, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_log_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.log();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 339939403, sign: false });\n    data.append(FP8x23 { mag: 689657480, sign: false });\n    data.append(FP8x23 { mag: 360525458, sign: false });\n    data.append(FP8x23 { mag: 745926917, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/log_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 31053727, sign: false });\n    data.append(FP8x23 { mag: 36988061, sign: false });\n    data.append(FP8x23 { mag: 31546937, sign: false });\n    data.append(FP8x23 { mag: 37646001, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_logsoftmax_fp16x16_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::logsoftmax(@input_0, 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 71864, sign: true });\n    data.append(FP16x16 { mag: 148859, sign: true });\n    data.append(FP16x16 { mag: 72361, sign: true });\n    data.append(FP16x16 { mag: 31682, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 45178, sign: true });\n    data.append(FP16x16 { mag: 127314, sign: true });\n    data.append(FP16x16 { mag: 45674, sign: true });\n    data.append(FP16x16 { mag: 10137, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::nn::NNTrait;\nuse orion::operators::nn::FP16x16NN;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_logsoftmax_fp16x16_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::logsoftmax(@input_0, 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 55516, sign: true });\n    data.append(FP16x16 { mag: 94686, sign: false });\n    data.append(FP16x16 { mag: 154182, sign: false });\n    data.append(FP16x16 { mag: 54374, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp16x16_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 156513, sign: true });\n    data.append(FP16x16 { mag: 6310, sign: true });\n    data.append(FP16x16 { mag: 2664, sign: true });\n    data.append(FP16x16 { mag: 211221, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_0.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::FP8x23NN;\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_logsoftmax_fp8x23_axis_0() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::logsoftmax(@input_0, 0);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_0/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 21668022, sign: true });\n    data.append(FP8x23 { mag: 1186402, sign: false });\n    data.append(FP8x23 { mag: 16768523, sign: true });\n    data.append(FP8x23 { mag: 20022676, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_0/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8617021, sign: true });\n    data.append(FP8x23 { mag: 19680507, sign: true });\n    data.append(FP8x23 { mag: 3717522, sign: true });\n    data.append(FP8x23 { mag: 844233, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_1.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::numbers::FixedTrait;\nuse orion::operators::nn::FP8x23NN;\nuse orion::operators::nn::NNTrait;\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_logsoftmax_fp8x23_axis_1() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = NNTrait::logsoftmax(@input_0, 1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 13710717, sign: true });\n    data.append(FP8x23 { mag: 10127369, sign: true });\n    data.append(FP8x23 { mag: 16322929, sign: true });\n    data.append(FP8x23 { mag: 5550537, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/logsoftmax_fp8x23_axis_1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 7796112, sign: true });\n    data.append(FP8x23 { mag: 4212765, sign: true });\n    data.append(FP8x23 { mag: 12822736, sign: true });\n    data.append(FP8x23 { mag: 2050343, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp16x16_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 458752, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp16x16_1x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_1x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 458752, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp16x16_2x1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp16x16_2x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp16x16_2x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp8x23_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp8x23_1x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_1x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp8x23_2x1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_fp8x23_2x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_fp8x23_2x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorDiv};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i32_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-96);\n    data.append(50);\n    data.append(16);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(23);\n    data.append(89);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2338);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i32_1x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-86);\n    data.append(43);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(125);\n    data.append(-59);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_1x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-13287);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i32_2x1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(115);\n    data.append(-24);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-103);\n    data.append(-90);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-11845);\n    data.append(-10350);\n    data.append(2472);\n    data.append(2160);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i32_2x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(74);\n    data.append(-16);\n    data.append(61);\n    data.append(-21);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(33);\n    data.append(119);\n    data.append(15);\n    data.append(113);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i32_2x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorDiv};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2202);\n    data.append(6998);\n    data.append(1698);\n    data.append(4886);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i8_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-1);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(10);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i8_1x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_1x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-17);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i8_2x1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_i8_2x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(3);\n    data.append(-3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(2);\n    data.append(-4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_i8_2x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorDiv};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(-14);\n    data.append(11);\n    data.append(-13);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1d.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_u32_1d() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(184);\n    data.append(244);\n    data.append(49);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1d/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(45);\n    data.append(178);\n    data.append(105);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(56857);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_u32_1x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(204);\n    data.append(167);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(179);\n    data.append(76);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_1x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(49208);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x1.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_u32_2x1() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x1/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(104);\n    data.append(169);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x1/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(118);\n    data.append(37);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x1/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(12272);\n    data.append(3848);\n    data.append(19942);\n    data.append(6253);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x2.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_matmul_u32_2x2() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.matmul(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x2/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(162);\n    data.append(101);\n    data.append(130);\n    data.append(82);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x2/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(149);\n    data.append(196);\n    data.append(137);\n    data.append(132);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/matmul_u32_2x2/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorDiv};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(37975);\n    data.append(45084);\n    data.append(30604);\n    data.append(36304);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp16x16_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp16x16_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp16x16_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp16x16_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp16x16_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp8x23_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp8x23_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp8x23_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_fp8x23_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_fp8x23_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i32_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i32_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i32_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i32_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i32_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i8_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i8_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i8_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_i8_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_i8_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_u32_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_u32_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_u32_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_max_u32_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::max(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/max_u32_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp16x16_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp16x16_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp16x16_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_2() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp16x16_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp16x16_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp8x23_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp8x23_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp8x23_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_2() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_fp8x23_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_fp8x23_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i32_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i32_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i32_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_2() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i32_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i32_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i8_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i8_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i8_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(4);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_2() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I8TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_i8_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(5);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_i8_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_u32_broadcast_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_u32_broadcast_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_broadcast_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_three_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod input_2;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_u32_three_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let input_2 = input_2::input_2();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1, input_2].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_three_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(1);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(1);\n    data.append(5);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_three_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(5);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_three_tensors/input_2.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_2() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(1);\n    data.append(0);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_three_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(3);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_two_tensors.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_min_u32_two_tensors() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = TensorTrait::min(array![input_0, input_1].span());\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_two_tensors/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(5);\n    data.append(2);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_two_tensors/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    data.append(2);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(1);\n    data.append(4);\n    data.append(4);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/min_u32_two_tensors/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(4);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(4);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(3);\n    data.append(2);\n    data.append(1);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(4);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(-3);\n    data.append(0);\n    data.append(0);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(-2);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(-2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(-6);\n    data.append(-3);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(9);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(6);\n    data.append(-2);\n    data.append(0);\n    data.append(0);\n    data.append(6);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(-2);\n    data.append(0);\n    data.append(3);\n    data.append(3);\n    data.append(-1);\n    data.append(-6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(-3);\n    data.append(2);\n    data.append(1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-2);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(-3);\n    data.append(-6);\n    data.append(1);\n    data.append(2);\n    data.append(-2);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(-6);\n    data.append(9);\n    data.append(-1);\n    data.append(3);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(-3);\n    data.append(6);\n    data.append(6);\n    data.append(0);\n    data.append(1);\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-2);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(-1);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(-3);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(2);\n    data.append(-1);\n    data.append(-3);\n    data.append(-4);\n    data.append(0);\n    data.append(6);\n    data.append(-2);\n    data.append(3);\n    data.append(-4);\n    data.append(-1);\n    data.append(1);\n    data.append(-6);\n    data.append(0);\n    data.append(-4);\n    data.append(6);\n    data.append(0);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(2);\n    data.append(-2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(-1);\n    data.append(3);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(0);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(2);\n    data.append(2);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(10);\n    data.append(10);\n    data.append(6);\n    data.append(5);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(6);\n    data.append(10);\n    data.append(0);\n    data.append(0);\n    data.append(10);\n    data.append(0);\n    data.append(10);\n    data.append(8);\n    data.append(0);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(6);\n    data.append(10);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0 * input_1;\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(3);\n    data.append(5);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/mul_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(5);\n    data.append(6);\n    data.append(8);\n    data.append(8);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(3);\n    data.append(5);\n    data.append(8);\n    data.append(8);\n    data.append(10);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(3);\n    data.append(5);\n    data.append(3);\n    data.append(6);\n    data.append(8);\n    data.append(6);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp16x16.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_neg_fp16x16() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.neg();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6684672, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp8x23.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_neg_fp8x23() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.neg();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn output_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i32.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_neg_i32() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.neg();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-17);\n    data.append(116);\n    data.append(-66);\n    data.append(18);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn output_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(17);\n    data.append(-116);\n    data.append(66);\n    data.append(-18);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i8.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_neg_i8() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.neg();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(83);\n    data.append(51);\n    data.append(20);\n    data.append(15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/neg_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn output_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-83);\n    data.append(-51);\n    data.append(-20);\n    data.append(-15);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_fp16x16_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_fp16x16_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 5439488, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 6225920, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 5046272, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: true });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: true });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: true });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 1769472, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 4194304, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 5439488, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: true });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: true });\n    data.append(FP16x16 { mag: 6946816, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: true });\n    data.append(FP16x16 { mag: 8257536, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 7864320, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 5505024, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 5505024, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: true });\n    data.append(FP16x16 { mag: 7405568, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 589824, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: true });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: false });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: false });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 5636096, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: true });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: true });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 4128768, sign: true });\n    data.append(FP16x16 { mag: 6291456, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 7340032, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 6553600, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 720896, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: true });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 6356992, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 2686976, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: false });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 6684672, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 7340032, sign: false });\n    data.append(FP16x16 { mag: 2359296, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3276800, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 4784128, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 5570560, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 786432, sign: false });\n    data.append(FP16x16 { mag: 7208960, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: false });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 4915200, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 655360, sign: true });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 7471104, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 2424832, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: true });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 1310720, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 4128768, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: true });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 7864320, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: false });\n    data.append(FP16x16 { mag: 2883584, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: true });\n    data.append(FP16x16 { mag: 327680, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 4259840, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 4980736, sign: true });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 917504, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 6946816, sign: true });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 720896, sign: false });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: true });\n    data.append(FP16x16 { mag: 8060928, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 6094848, sign: true });\n    data.append(FP16x16 { mag: 5832704, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: true });\n    data.append(FP16x16 { mag: 2555904, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 1507328, sign: true });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 7602176, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 6225920, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 2555904, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 4653056, sign: false });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: false });\n    data.append(FP16x16 { mag: 5636096, sign: true });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 1572864, sign: true });\n    data.append(FP16x16 { mag: 3866624, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 2818048, sign: true });\n    data.append(FP16x16 { mag: 7995392, sign: false });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: true });\n    data.append(FP16x16 { mag: 1966080, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 3211264, sign: false });\n    data.append(FP16x16 { mag: 8060928, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 5636096, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 5111808, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: true });\n    data.append(FP16x16 { mag: 2293760, sign: true });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 4063232, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 6291456, sign: true });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 8257536, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 7077888, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 4063232, sign: true });\n    data.append(FP16x16 { mag: 4784128, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 4194304, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: true });\n    data.append(FP16x16 { mag: 3604480, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: true });\n    data.append(FP16x16 { mag: 5046272, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: true });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 4456448, sign: true });\n    data.append(FP16x16 { mag: 1179648, sign: false });\n    data.append(FP16x16 { mag: 3670016, sign: false });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 3145728, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: false });\n    data.append(FP16x16 { mag: 3997696, sign: false });\n    data.append(FP16x16 { mag: 655360, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 4653056, sign: true });\n    data.append(FP16x16 { mag: 6094848, sign: false });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: true });\n    data.append(FP16x16 { mag: 4980736, sign: false });\n    data.append(FP16x16 { mag: 3932160, sign: true });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 6422528, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 4325376, sign: true });\n    data.append(FP16x16 { mag: 3932160, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 3538944, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 3407872, sign: false });\n    data.append(FP16x16 { mag: 6750208, sign: true });\n    data.append(FP16x16 { mag: 5767168, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 6422528, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: true });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 6815744, sign: false });\n    data.append(FP16x16 { mag: 1966080, sign: true });\n    data.append(FP16x16 { mag: 2162688, sign: false });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 2490368, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: true });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 1638400, sign: false });\n    data.append(FP16x16 { mag: 8323072, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 262144, sign: true });\n    data.append(FP16x16 { mag: 5242880, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: false });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 4718592, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 4849664, sign: false });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 3801088, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 4587520, sign: true });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 6553600, sign: true });\n    data.append(FP16x16 { mag: 5308416, sign: false });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 3473408, sign: false });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 7733248, sign: false });\n    data.append(FP16x16 { mag: 7602176, sign: true });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 393216, sign: true });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 1638400, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: false });\n    data.append(FP16x16 { mag: 5898240, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 7208960, sign: true });\n    data.append(FP16x16 { mag: 2949120, sign: true });\n    data.append(FP16x16 { mag: 1048576, sign: false });\n    data.append(FP16x16 { mag: 4390912, sign: false });\n    data.append(FP16x16 { mag: 8192000, sign: true });\n    data.append(FP16x16 { mag: 3014656, sign: true });\n    data.append(FP16x16 { mag: 6553600, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 5701632, sign: false });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 5111808, sign: false });\n    data.append(FP16x16 { mag: 1114112, sign: true });\n    data.append(FP16x16 { mag: 7929856, sign: true });\n    data.append(FP16x16 { mag: 1245184, sign: true });\n    data.append(FP16x16 { mag: 3407872, sign: true });\n    data.append(FP16x16 { mag: 6029312, sign: false });\n    data.append(FP16x16 { mag: 6225920, sign: false });\n    data.append(FP16x16 { mag: 7929856, sign: false });\n    data.append(FP16x16 { mag: 2228224, sign: false });\n    data.append(FP16x16 { mag: 7536640, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    data.append(FP16x16 { mag: 3342336, sign: true });\n    data.append(FP16x16 { mag: 6750208, sign: false });\n    data.append(FP16x16 { mag: 7667712, sign: false });\n    data.append(FP16x16 { mag: 3080192, sign: false });\n    data.append(FP16x16 { mag: 1835008, sign: true });\n    data.append(FP16x16 { mag: 4587520, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: true });\n    data.append(FP16x16 { mag: 6881280, sign: true });\n    data.append(FP16x16 { mag: 5177344, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 7471104, sign: false });\n    data.append(FP16x16 { mag: 2752512, sign: true });\n    data.append(FP16x16 { mag: 6619136, sign: true });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2097152, sign: false });\n    data.append(FP16x16 { mag: 7798784, sign: false });\n    data.append(FP16x16 { mag: 7143424, sign: false });\n    data.append(FP16x16 { mag: 6488064, sign: false });\n    data.append(FP16x16 { mag: 2293760, sign: false });\n    data.append(FP16x16 { mag: 2031616, sign: true });\n    data.append(FP16x16 { mag: 458752, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: true });\n    data.append(FP16x16 { mag: 4849664, sign: true });\n    data.append(FP16x16 { mag: 3342336, sign: false });\n    data.append(FP16x16 { mag: 6160384, sign: true });\n    data.append(FP16x16 { mag: 3735552, sign: true });\n    data.append(FP16x16 { mag: 8126464, sign: true });\n    data.append(FP16x16 { mag: 5373952, sign: true });\n    data.append(FP16x16 { mag: 1703936, sign: false });\n    data.append(FP16x16 { mag: 3145728, sign: false });\n    data.append(FP16x16 { mag: 2621440, sign: false });\n    data.append(FP16x16 { mag: 7274496, sign: true });\n    data.append(FP16x16 { mag: 4521984, sign: false });\n    data.append(FP16x16 { mag: 1376256, sign: true });\n    data.append(FP16x16 { mag: 851968, sign: true });\n    data.append(FP16x16 { mag: 5963776, sign: false });\n    data.append(FP16x16 { mag: 786432, sign: true });\n    data.append(FP16x16 { mag: 4259840, sign: false });\n    data.append(FP16x16 { mag: 983040, sign: false });\n    data.append(FP16x16 { mag: 1441792, sign: false });\n    data.append(FP16x16 { mag: 5177344, sign: true });\n    data.append(FP16x16 { mag: 4390912, sign: true });\n    data.append(FP16x16 { mag: 2818048, sign: false });\n    data.append(FP16x16 { mag: 524288, sign: true });\n    data.append(FP16x16 { mag: 1900544, sign: false });\n    data.append(FP16x16 { mag: 7012352, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp16x16_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(998);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_fp8x23_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_fp8x23_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: false });\n    data.append(FP8x23 { mag: 746586112, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 746586112, sign: false });\n    data.append(FP8x23 { mag: 889192448, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 176160768, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 595591168, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: true });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 260046848, sign: true });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 998244352, sign: true });\n    data.append(FP8x23 { mag: 201326592, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 1015021568, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 293601280, sign: false });\n    data.append(FP8x23 { mag: 1015021568, sign: false });\n    data.append(FP8x23 { mag: 293601280, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 578813952, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 469762048, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 872415232, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 486539264, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 805306368, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 310378496, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 1015021568, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 469762048, sign: true });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 511705088, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 587202560, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: true });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: true });\n    data.append(FP8x23 { mag: 587202560, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: true });\n    data.append(FP8x23 { mag: 159383552, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 243269632, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: false });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 989855744, sign: false });\n    data.append(FP8x23 { mag: 260046848, sign: false });\n    data.append(FP8x23 { mag: 192937984, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 402653184, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 58720256, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 184549376, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: false });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: false });\n    data.append(FP8x23 { mag: 855638016, sign: false });\n    data.append(FP8x23 { mag: 369098752, sign: true });\n    data.append(FP8x23 { mag: 973078528, sign: true });\n    data.append(FP8x23 { mag: 813694976, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 771751936, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 301989888, sign: false });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 150994944, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 1023410176, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: false });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 956301312, sign: false });\n    data.append(FP8x23 { mag: 553648128, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 989855744, sign: true });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 369098752, sign: false });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 125829120, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 620756992, sign: true });\n    data.append(FP8x23 { mag: 142606336, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 696254464, sign: true });\n    data.append(FP8x23 { mag: 889192448, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 50331648, sign: true });\n    data.append(FP8x23 { mag: 125829120, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 545259520, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: false });\n    data.append(FP8x23 { mag: 218103808, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: true });\n    data.append(FP8x23 { mag: 922746880, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: true });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 662700032, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: false });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 494927872, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 880803840, sign: false });\n    data.append(FP8x23 { mag: 973078528, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 276824064, sign: true });\n    data.append(FP8x23 { mag: 343932928, sign: true });\n    data.append(FP8x23 { mag: 553648128, sign: true });\n    data.append(FP8x23 { mag: 570425344, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 671088640, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 1056964608, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: false });\n    data.append(FP8x23 { mag: 419430400, sign: true });\n    data.append(FP8x23 { mag: 671088640, sign: true });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: false });\n    data.append(FP8x23 { mag: 654311424, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: false });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 486539264, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 620756992, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 721420288, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 662700032, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 771751936, sign: false });\n    data.append(FP8x23 { mag: 679477248, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 805306368, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 947912704, sign: true });\n    data.append(FP8x23 { mag: 788529152, sign: true });\n    data.append(FP8x23 { mag: 981467136, sign: true });\n    data.append(FP8x23 { mag: 318767104, sign: true });\n    data.append(FP8x23 { mag: 1048576000, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 1040187392, sign: true });\n    data.append(FP8x23 { mag: 243269632, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: true });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 209715200, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: true });\n    data.append(FP8x23 { mag: 411041792, sign: false });\n    data.append(FP8x23 { mag: 922746880, sign: true });\n    data.append(FP8x23 { mag: 562036736, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 427819008, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 788529152, sign: false });\n    data.append(FP8x23 { mag: 570425344, sign: false });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 713031680, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: false });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 822083584, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: false });\n    data.append(FP8x23 { mag: 251658240, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 1006632960, sign: false });\n    data.append(FP8x23 { mag: 83886080, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 100663296, sign: false });\n    data.append(FP8x23 { mag: 520093696, sign: true });\n    data.append(FP8x23 { mag: 67108864, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: false });\n    data.append(FP8x23 { mag: 721420288, sign: true });\n    data.append(FP8x23 { mag: 310378496, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 494927872, sign: true });\n    data.append(FP8x23 { mag: 864026624, sign: true });\n    data.append(FP8x23 { mag: 335544320, sign: true });\n    data.append(FP8x23 { mag: 931135488, sign: false });\n    data.append(FP8x23 { mag: 872415232, sign: true });\n    data.append(FP8x23 { mag: 1015021568, sign: true });\n    data.append(FP8x23 { mag: 998244352, sign: true });\n    data.append(FP8x23 { mag: 461373440, sign: false });\n    data.append(FP8x23 { mag: 385875968, sign: false });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 318767104, sign: false });\n    data.append(FP8x23 { mag: 897581056, sign: true });\n    data.append(FP8x23 { mag: 939524096, sign: false });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 629145600, sign: true });\n    data.append(FP8x23 { mag: 75497472, sign: false });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 41943040, sign: true });\n    data.append(FP8x23 { mag: 654311424, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: true });\n    data.append(FP8x23 { mag: 738197504, sign: true });\n    data.append(FP8x23 { mag: 704643072, sign: true });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 436207616, sign: true });\n    data.append(FP8x23 { mag: 1040187392, sign: false });\n    data.append(FP8x23 { mag: 50331648, sign: false });\n    data.append(FP8x23 { mag: 914358272, sign: false });\n    data.append(FP8x23 { mag: 503316480, sign: true });\n    data.append(FP8x23 { mag: 268435456, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 511705088, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 360710144, sign: true });\n    data.append(FP8x23 { mag: 780140544, sign: false });\n    data.append(FP8x23 { mag: 352321536, sign: false });\n    data.append(FP8x23 { mag: 964689920, sign: false });\n    data.append(FP8x23 { mag: 117440512, sign: true });\n    data.append(FP8x23 { mag: 176160768, sign: true });\n    data.append(FP8x23 { mag: 327155712, sign: true });\n    data.append(FP8x23 { mag: 385875968, sign: true });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 838860800, sign: false });\n    data.append(FP8x23 { mag: 478150656, sign: true });\n    data.append(FP8x23 { mag: 872415232, sign: false });\n    data.append(FP8x23 { mag: 687865856, sign: true });\n    data.append(FP8x23 { mag: 251658240, sign: false });\n    data.append(FP8x23 { mag: 729808896, sign: false });\n    data.append(FP8x23 { mag: 645922816, sign: true });\n    data.append(FP8x23 { mag: 679477248, sign: true });\n    data.append(FP8x23 { mag: 503316480, sign: false });\n    data.append(FP8x23 { mag: 159383552, sign: true });\n    data.append(FP8x23 { mag: 352321536, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: false });\n    data.append(FP8x23 { mag: 285212672, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 343932928, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: false });\n    data.append(FP8x23 { mag: 226492416, sign: true });\n    data.append(FP8x23 { mag: 1031798784, sign: true });\n    data.append(FP8x23 { mag: 92274688, sign: false });\n    data.append(FP8x23 { mag: 134217728, sign: true });\n    data.append(FP8x23 { mag: 830472192, sign: false });\n    data.append(FP8x23 { mag: 981467136, sign: false });\n    data.append(FP8x23 { mag: 268435456, sign: true });\n    data.append(FP8x23 { mag: 578813952, sign: false });\n    data.append(FP8x23 { mag: 394264576, sign: true });\n    data.append(FP8x23 { mag: 603979776, sign: true });\n    data.append(FP8x23 { mag: 528482304, sign: false });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 150994944, sign: false });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 234881024, sign: false });\n    data.append(FP8x23 { mag: 813694976, sign: true });\n    data.append(FP8x23 { mag: 201326592, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: true });\n    data.append(FP8x23 { mag: 645922816, sign: false });\n    data.append(FP8x23 { mag: 58720256, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 687865856, sign: false });\n    data.append(FP8x23 { mag: 905969664, sign: true });\n    data.append(FP8x23 { mag: 33554432, sign: false });\n    data.append(FP8x23 { mag: 452984832, sign: false });\n    data.append(FP8x23 { mag: 595591168, sign: true });\n    data.append(FP8x23 { mag: 377487360, sign: true });\n    data.append(FP8x23 { mag: 109051904, sign: true });\n    data.append(FP8x23 { mag: 796917760, sign: false });\n    data.append(FP8x23 { mag: 637534208, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 754974720, sign: false });\n    data.append(FP8x23 { mag: 536870912, sign: true });\n    data.append(FP8x23 { mag: 1023410176, sign: false });\n    data.append(FP8x23 { mag: 838860800, sign: true });\n    data.append(FP8x23 { mag: 167772160, sign: false });\n    data.append(FP8x23 { mag: 1056964608, sign: true });\n    data.append(FP8x23 { mag: 444596224, sign: false });\n    data.append(FP8x23 { mag: 209715200, sign: true });\n    data.append(FP8x23 { mag: 360710144, sign: false });\n    data.append(FP8x23 { mag: 612368384, sign: false });\n    data.append(FP8x23 { mag: 763363328, sign: true });\n    data.append(FP8x23 { mag: 847249408, sign: true });\n    data.append(FP8x23 { mag: 746586112, sign: true });\n    data.append(FP8x23 { mag: 520093696, sign: false });\n    data.append(FP8x23 { mag: 1065353216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_fp8x23_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(997);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_i32_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(-70);\n    data.append(71);\n    data.append(121);\n    data.append(106);\n    data.append(-89);\n    data.append(11);\n    data.append(-69);\n    data.append(-78);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::I32TensorPartialEq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_i32_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorSub};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(78);\n    data.append(-73);\n    data.append(-120);\n    data.append(37);\n    data.append(69);\n    data.append(59);\n    data.append(-57);\n    data.append(-36);\n    data.append(-5);\n    data.append(98);\n    data.append(98);\n    data.append(-91);\n    data.append(-64);\n    data.append(49);\n    data.append(90);\n    data.append(104);\n    data.append(-87);\n    data.append(78);\n    data.append(120);\n    data.append(124);\n    data.append(56);\n    data.append(-100);\n    data.append(-72);\n    data.append(70);\n    data.append(-3);\n    data.append(95);\n    data.append(42);\n    data.append(-7);\n    data.append(113);\n    data.append(-33);\n    data.append(18);\n    data.append(18);\n    data.append(-103);\n    data.append(-117);\n    data.append(-108);\n    data.append(-84);\n    data.append(-64);\n    data.append(96);\n    data.append(1);\n    data.append(117);\n    data.append(115);\n    data.append(-56);\n    data.append(74);\n    data.append(-75);\n    data.append(62);\n    data.append(-51);\n    data.append(-26);\n    data.append(94);\n    data.append(-87);\n    data.append(-51);\n    data.append(-48);\n    data.append(-124);\n    data.append(7);\n    data.append(84);\n    data.append(21);\n    data.append(122);\n    data.append(-95);\n    data.append(-118);\n    data.append(-68);\n    data.append(-100);\n    data.append(-107);\n    data.append(-116);\n    data.append(-2);\n    data.append(-100);\n    data.append(114);\n    data.append(123);\n    data.append(56);\n    data.append(-104);\n    data.append(-112);\n    data.append(-102);\n    data.append(37);\n    data.append(-110);\n    data.append(-89);\n    data.append(9);\n    data.append(47);\n    data.append(-111);\n    data.append(-69);\n    data.append(-121);\n    data.append(9);\n    data.append(-92);\n    data.append(60);\n    data.append(123);\n    data.append(44);\n    data.append(0);\n    data.append(-116);\n    data.append(-1);\n    data.append(-126);\n    data.append(18);\n    data.append(51);\n    data.append(40);\n    data.append(32);\n    data.append(30);\n    data.append(-64);\n    data.append(-112);\n    data.append(-117);\n    data.append(-40);\n    data.append(75);\n    data.append(-30);\n    data.append(-42);\n    data.append(-5);\n    data.append(120);\n    data.append(86);\n    data.append(-25);\n    data.append(-18);\n    data.append(26);\n    data.append(1);\n    data.append(77);\n    data.append(113);\n    data.append(-88);\n    data.append(50);\n    data.append(-82);\n    data.append(23);\n    data.append(-10);\n    data.append(-4);\n    data.append(-80);\n    data.append(-71);\n    data.append(-46);\n    data.append(16);\n    data.append(-45);\n    data.append(-21);\n    data.append(-104);\n    data.append(4);\n    data.append(-97);\n    data.append(77);\n    data.append(120);\n    data.append(58);\n    data.append(86);\n    data.append(-47);\n    data.append(6);\n    data.append(-8);\n    data.append(37);\n    data.append(-102);\n    data.append(-58);\n    data.append(40);\n    data.append(-77);\n    data.append(-93);\n    data.append(99);\n    data.append(14);\n    data.append(-117);\n    data.append(-121);\n    data.append(-29);\n    data.append(28);\n    data.append(62);\n    data.append(116);\n    data.append(-24);\n    data.append(-33);\n    data.append(120);\n    data.append(-77);\n    data.append(54);\n    data.append(-84);\n    data.append(19);\n    data.append(96);\n    data.append(76);\n    data.append(119);\n    data.append(-99);\n    data.append(-71);\n    data.append(16);\n    data.append(110);\n    data.append(-99);\n    data.append(89);\n    data.append(-22);\n    data.append(-35);\n    data.append(24);\n    data.append(-41);\n    data.append(12);\n    data.append(72);\n    data.append(-80);\n    data.append(22);\n    data.append(113);\n    data.append(6);\n    data.append(73);\n    data.append(-60);\n    data.append(-52);\n    data.append(66);\n    data.append(-2);\n    data.append(96);\n    data.append(-11);\n    data.append(97);\n    data.append(9);\n    data.append(-60);\n    data.append(107);\n    data.append(-61);\n    data.append(-114);\n    data.append(-106);\n    data.append(102);\n    data.append(53);\n    data.append(-50);\n    data.append(33);\n    data.append(55);\n    data.append(-103);\n    data.append(-20);\n    data.append(-62);\n    data.append(102);\n    data.append(82);\n    data.append(-46);\n    data.append(-26);\n    data.append(36);\n    data.append(14);\n    data.append(8);\n    data.append(46);\n    data.append(-50);\n    data.append(-79);\n    data.append(83);\n    data.append(15);\n    data.append(68);\n    data.append(-18);\n    data.append(75);\n    data.append(47);\n    data.append(38);\n    data.append(98);\n    data.append(-87);\n    data.append(-92);\n    data.append(5);\n    data.append(36);\n    data.append(55);\n    data.append(-101);\n    data.append(2);\n    data.append(-117);\n    data.append(-57);\n    data.append(-82);\n    data.append(67);\n    data.append(52);\n    data.append(53);\n    data.append(104);\n    data.append(-75);\n    data.append(53);\n    data.append(1);\n    data.append(-98);\n    data.append(-82);\n    data.append(33);\n    data.append(114);\n    data.append(-110);\n    data.append(77);\n    data.append(-31);\n    data.append(72);\n    data.append(-34);\n    data.append(123);\n    data.append(-61);\n    data.append(120);\n    data.append(-30);\n    data.append(43);\n    data.append(-37);\n    data.append(71);\n    data.append(6);\n    data.append(-22);\n    data.append(45);\n    data.append(-48);\n    data.append(-45);\n    data.append(11);\n    data.append(-62);\n    data.append(123);\n    data.append(-82);\n    data.append(114);\n    data.append(87);\n    data.append(90);\n    data.append(121);\n    data.append(106);\n    data.append(-113);\n    data.append(-122);\n    data.append(118);\n    data.append(2);\n    data.append(96);\n    data.append(-39);\n    data.append(-99);\n    data.append(-55);\n    data.append(87);\n    data.append(-45);\n    data.append(96);\n    data.append(46);\n    data.append(-95);\n    data.append(100);\n    data.append(20);\n    data.append(-27);\n    data.append(94);\n    data.append(-61);\n    data.append(60);\n    data.append(-107);\n    data.append(85);\n    data.append(51);\n    data.append(-84);\n    data.append(-48);\n    data.append(-59);\n    data.append(-50);\n    data.append(-65);\n    data.append(101);\n    data.append(-28);\n    data.append(94);\n    data.append(70);\n    data.append(-99);\n    data.append(-50);\n    data.append(120);\n    data.append(-103);\n    data.append(-38);\n    data.append(2);\n    data.append(-7);\n    data.append(12);\n    data.append(89);\n    data.append(70);\n    data.append(49);\n    data.append(107);\n    data.append(56);\n    data.append(29);\n    data.append(-37);\n    data.append(-29);\n    data.append(-85);\n    data.append(116);\n    data.append(125);\n    data.append(-3);\n    data.append(-94);\n    data.append(-100);\n    data.append(-82);\n    data.append(-9);\n    data.append(-17);\n    data.append(-74);\n    data.append(-113);\n    data.append(-32);\n    data.append(-115);\n    data.append(114);\n    data.append(-51);\n    data.append(8);\n    data.append(38);\n    data.append(-75);\n    data.append(-40);\n    data.append(-31);\n    data.append(36);\n    data.append(84);\n    data.append(12);\n    data.append(-80);\n    data.append(12);\n    data.append(-92);\n    data.append(126);\n    data.append(111);\n    data.append(62);\n    data.append(104);\n    data.append(51);\n    data.append(75);\n    data.append(-95);\n    data.append(-54);\n    data.append(106);\n    data.append(6);\n    data.append(-76);\n    data.append(118);\n    data.append(-110);\n    data.append(-60);\n    data.append(-16);\n    data.append(25);\n    data.append(3);\n    data.append(-105);\n    data.append(-124);\n    data.append(-78);\n    data.append(-85);\n    data.append(-24);\n    data.append(66);\n    data.append(50);\n    data.append(54);\n    data.append(-12);\n    data.append(-10);\n    data.append(-60);\n    data.append(-11);\n    data.append(46);\n    data.append(31);\n    data.append(-76);\n    data.append(-23);\n    data.append(23);\n    data.append(-92);\n    data.append(-15);\n    data.append(-52);\n    data.append(-31);\n    data.append(68);\n    data.append(94);\n    data.append(42);\n    data.append(-68);\n    data.append(108);\n    data.append(51);\n    data.append(-68);\n    data.append(-4);\n    data.append(44);\n    data.append(66);\n    data.append(105);\n    data.append(16);\n    data.append(-21);\n    data.append(-113);\n    data.append(-41);\n    data.append(44);\n    data.append(-17);\n    data.append(37);\n    data.append(-103);\n    data.append(-117);\n    data.append(65);\n    data.append(125);\n    data.append(103);\n    data.append(-40);\n    data.append(-72);\n    data.append(-127);\n    data.append(47);\n    data.append(-3);\n    data.append(2);\n    data.append(-111);\n    data.append(107);\n    data.append(42);\n    data.append(-34);\n    data.append(37);\n    data.append(81);\n    data.append(-46);\n    data.append(4);\n    data.append(-95);\n    data.append(-80);\n    data.append(92);\n    data.append(-72);\n    data.append(-43);\n    data.append(-26);\n    data.append(-113);\n    data.append(-117);\n    data.append(-11);\n    data.append(-21);\n    data.append(99);\n    data.append(63);\n    data.append(-36);\n    data.append(14);\n    data.append(-124);\n    data.append(-18);\n    data.append(91);\n    data.append(121);\n    data.append(-4);\n    data.append(-74);\n    data.append(103);\n    data.append(-61);\n    data.append(108);\n    data.append(58);\n    data.append(83);\n    data.append(-73);\n    data.append(72);\n    data.append(92);\n    data.append(-31);\n    data.append(-12);\n    data.append(-30);\n    data.append(50);\n    data.append(-105);\n    data.append(16);\n    data.append(-93);\n    data.append(68);\n    data.append(-103);\n    data.append(-60);\n    data.append(121);\n    data.append(80);\n    data.append(-90);\n    data.append(0);\n    data.append(49);\n    data.append(7);\n    data.append(11);\n    data.append(-89);\n    data.append(-37);\n    data.append(-96);\n    data.append(102);\n    data.append(38);\n    data.append(-30);\n    data.append(-127);\n    data.append(4);\n    data.append(31);\n    data.append(-66);\n    data.append(23);\n    data.append(20);\n    data.append(91);\n    data.append(-116);\n    data.append(-40);\n    data.append(41);\n    data.append(35);\n    data.append(-120);\n    data.append(-79);\n    data.append(-12);\n    data.append(-77);\n    data.append(-103);\n    data.append(93);\n    data.append(-65);\n    data.append(103);\n    data.append(47);\n    data.append(24);\n    data.append(-77);\n    data.append(-42);\n    data.append(-25);\n    data.append(96);\n    data.append(105);\n    data.append(15);\n    data.append(-107);\n    data.append(114);\n    data.append(-123);\n    data.append(-101);\n    data.append(57);\n    data.append(102);\n    data.append(94);\n    data.append(-64);\n    data.append(37);\n    data.append(-90);\n    data.append(16);\n    data.append(81);\n    data.append(-92);\n    data.append(14);\n    data.append(-84);\n    data.append(78);\n    data.append(-115);\n    data.append(99);\n    data.append(-97);\n    data.append(-81);\n    data.append(85);\n    data.append(90);\n    data.append(53);\n    data.append(8);\n    data.append(-34);\n    data.append(-58);\n    data.append(-60);\n    data.append(43);\n    data.append(-67);\n    data.append(-6);\n    data.append(-8);\n    data.append(25);\n    data.append(-93);\n    data.append(-8);\n    data.append(11);\n    data.append(6);\n    data.append(52);\n    data.append(106);\n    data.append(-113);\n    data.append(-101);\n    data.append(43);\n    data.append(-119);\n    data.append(-102);\n    data.append(89);\n    data.append(106);\n    data.append(-47);\n    data.append(-109);\n    data.append(-117);\n    data.append(92);\n    data.append(-79);\n    data.append(82);\n    data.append(-124);\n    data.append(63);\n    data.append(120);\n    data.append(-6);\n    data.append(-58);\n    data.append(-101);\n    data.append(-58);\n    data.append(29);\n    data.append(-118);\n    data.append(42);\n    data.append(50);\n    data.append(114);\n    data.append(-110);\n    data.append(-63);\n    data.append(86);\n    data.append(-105);\n    data.append(-124);\n    data.append(-13);\n    data.append(109);\n    data.append(7);\n    data.append(-19);\n    data.append(85);\n    data.append(-14);\n    data.append(117);\n    data.append(96);\n    data.append(97);\n    data.append(82);\n    data.append(-35);\n    data.append(42);\n    data.append(-88);\n    data.append(90);\n    data.append(-84);\n    data.append(114);\n    data.append(-26);\n    data.append(101);\n    data.append(-72);\n    data.append(-6);\n    data.append(-50);\n    data.append(13);\n    data.append(-18);\n    data.append(-117);\n    data.append(39);\n    data.append(112);\n    data.append(103);\n    data.append(57);\n    data.append(-55);\n    data.append(111);\n    data.append(125);\n    data.append(-18);\n    data.append(118);\n    data.append(84);\n    data.append(53);\n    data.append(-32);\n    data.append(18);\n    data.append(61);\n    data.append(110);\n    data.append(-23);\n    data.append(60);\n    data.append(-52);\n    data.append(31);\n    data.append(-114);\n    data.append(-89);\n    data.append(76);\n    data.append(77);\n    data.append(-87);\n    data.append(42);\n    data.append(81);\n    data.append(28);\n    data.append(-47);\n    data.append(34);\n    data.append(125);\n    data.append(-99);\n    data.append(70);\n    data.append(47);\n    data.append(-69);\n    data.append(-54);\n    data.append(46);\n    data.append(-39);\n    data.append(-12);\n    data.append(-29);\n    data.append(-72);\n    data.append(1);\n    data.append(-41);\n    data.append(1);\n    data.append(-78);\n    data.append(47);\n    data.append(13);\n    data.append(-101);\n    data.append(-2);\n    data.append(110);\n    data.append(-66);\n    data.append(96);\n    data.append(-77);\n    data.append(-96);\n    data.append(-111);\n    data.append(62);\n    data.append(-75);\n    data.append(71);\n    data.append(11);\n    data.append(-80);\n    data.append(100);\n    data.append(89);\n    data.append(-3);\n    data.append(77);\n    data.append(1);\n    data.append(14);\n    data.append(46);\n    data.append(26);\n    data.append(47);\n    data.append(37);\n    data.append(108);\n    data.append(-20);\n    data.append(18);\n    data.append(-84);\n    data.append(-124);\n    data.append(-111);\n    data.append(-103);\n    data.append(-58);\n    data.append(123);\n    data.append(36);\n    data.append(-49);\n    data.append(86);\n    data.append(-114);\n    data.append(-80);\n    data.append(-76);\n    data.append(126);\n    data.append(-8);\n    data.append(114);\n    data.append(-8);\n    data.append(52);\n    data.append(-30);\n    data.append(18);\n    data.append(82);\n    data.append(-66);\n    data.append(-108);\n    data.append(62);\n    data.append(-108);\n    data.append(30);\n    data.append(34);\n    data.append(81);\n    data.append(-73);\n    data.append(-84);\n    data.append(-46);\n    data.append(-29);\n    data.append(61);\n    data.append(-9);\n    data.append(-45);\n    data.append(-10);\n    data.append(73);\n    data.append(125);\n    data.append(-4);\n    data.append(70);\n    data.append(4);\n    data.append(99);\n    data.append(-54);\n    data.append(-105);\n    data.append(-101);\n    data.append(-6);\n    data.append(2);\n    data.append(-1);\n    data.append(-58);\n    data.append(-109);\n    data.append(-122);\n    data.append(-60);\n    data.append(-87);\n    data.append(87);\n    data.append(13);\n    data.append(-28);\n    data.append(110);\n    data.append(42);\n    data.append(-37);\n    data.append(-108);\n    data.append(-25);\n    data.append(-90);\n    data.append(104);\n    data.append(71);\n    data.append(-85);\n    data.append(122);\n    data.append(-109);\n    data.append(-120);\n    data.append(62);\n    data.append(-125);\n    data.append(-33);\n    data.append(-65);\n    data.append(-89);\n    data.append(110);\n    data.append(-92);\n    data.append(55);\n    data.append(80);\n    data.append(-20);\n    data.append(92);\n    data.append(-118);\n    data.append(79);\n    data.append(27);\n    data.append(-125);\n    data.append(16);\n    data.append(-100);\n    data.append(14);\n    data.append(58);\n    data.append(27);\n    data.append(-6);\n    data.append(10);\n    data.append(94);\n    data.append(88);\n    data.append(-109);\n    data.append(-29);\n    data.append(-127);\n    data.append(101);\n    data.append(11);\n    data.append(-71);\n    data.append(116);\n    data.append(24);\n    data.append(18);\n    data.append(1);\n    data.append(50);\n    data.append(-71);\n    data.append(100);\n    data.append(-96);\n    data.append(99);\n    data.append(67);\n    data.append(-22);\n    data.append(-99);\n    data.append(58);\n    data.append(74);\n    data.append(50);\n    data.append(-8);\n    data.append(-118);\n    data.append(-98);\n    data.append(-126);\n    data.append(-52);\n    data.append(35);\n    data.append(-4);\n    data.append(-37);\n    data.append(81);\n    data.append(56);\n    data.append(100);\n    data.append(101);\n    data.append(-119);\n    data.append(52);\n    data.append(-23);\n    data.append(97);\n    data.append(38);\n    data.append(80);\n    data.append(23);\n    data.append(-19);\n    data.append(54);\n    data.append(-3);\n    data.append(34);\n    data.append(-5);\n    data.append(25);\n    data.append(-42);\n    data.append(91);\n    data.append(59);\n    data.append(53);\n    data.append(-108);\n    data.append(-57);\n    data.append(-74);\n    data.append(-96);\n    data.append(7);\n    data.append(95);\n    data.append(-7);\n    data.append(-93);\n    data.append(-93);\n    data.append(-111);\n    data.append(102);\n    data.append(90);\n    data.append(-95);\n    data.append(24);\n    data.append(-64);\n    data.append(46);\n    data.append(-60);\n    data.append(-89);\n    data.append(26);\n    data.append(-47);\n    data.append(-60);\n    data.append(15);\n    data.append(-92);\n    data.append(15);\n    data.append(-113);\n    data.append(32);\n    data.append(-39);\n    data.append(40);\n    data.append(-94);\n    data.append(-108);\n    data.append(52);\n    data.append(118);\n    data.append(86);\n    data.append(46);\n    data.append(84);\n    data.append(-47);\n    data.append(93);\n    data.append(-101);\n    data.append(15);\n    data.append(119);\n    data.append(-50);\n    data.append(-10);\n    data.append(-124);\n    data.append(124);\n    data.append(-58);\n    data.append(-122);\n    data.append(-6);\n    data.append(2);\n    data.append(-101);\n    data.append(43);\n    data.append(7);\n    data.append(-25);\n    data.append(55);\n    data.append(-27);\n    data.append(-84);\n    data.append(98);\n    data.append(91);\n    data.append(-26);\n    data.append(-98);\n    data.append(121);\n    data.append(-92);\n    data.append(117);\n    data.append(-71);\n    data.append(-26);\n    data.append(97);\n    data.append(76);\n    data.append(-89);\n    data.append(52);\n    data.append(81);\n    data.append(-48);\n    data.append(-48);\n    data.append(-29);\n    data.append(122);\n    data.append(125);\n    data.append(-69);\n    data.append(118);\n    data.append(114);\n    data.append(41);\n    data.append(47);\n    data.append(38);\n    data.append(38);\n    data.append(-10);\n    data.append(123);\n    data.append(-74);\n    data.append(89);\n    data.append(-59);\n    data.append(-29);\n    data.append(-39);\n    data.append(-127);\n    data.append(-70);\n    data.append(-32);\n    data.append(90);\n    data.append(-10);\n    data.append(-33);\n    data.append(-56);\n    data.append(-81);\n    data.append(21);\n    data.append(-95);\n    data.append(13);\n    data.append(26);\n    data.append(-121);\n    data.append(20);\n    data.append(80);\n    data.append(-49);\n    data.append(71);\n    data.append(-119);\n    data.append(-23);\n    data.append(65);\n    data.append(-24);\n    data.append(79);\n    data.append(-53);\n    data.append(48);\n    data.append(-27);\n    data.append(-6);\n    data.append(-9);\n    data.append(64);\n    data.append(9);\n    data.append(-58);\n    data.append(-52);\n    data.append(-43);\n    data.append(-97);\n    data.append(-102);\n    data.append(104);\n    data.append(108);\n    data.append(-7);\n    data.append(-51);\n    data.append(-102);\n    data.append(46);\n    data.append(15);\n    data.append(30);\n    data.append(-45);\n    data.append(-18);\n    data.append(22);\n    data.append(-61);\n    data.append(91);\n    data.append(9);\n    data.append(30);\n    data.append(90);\n    data.append(14);\n    data.append(25);\n    data.append(18);\n    data.append(-4);\n    data.append(-38);\n    data.append(124);\n    data.append(-115);\n    data.append(-12);\n    data.append(65);\n    data.append(48);\n    data.append(106);\n    data.append(30);\n    data.append(-77);\n    data.append(-26);\n    data.append(66);\n    data.append(-3);\n    data.append(-40);\n    data.append(-105);\n    data.append(-27);\n    data.append(-74);\n    data.append(123);\n    data.append(13);\n    data.append(-46);\n    data.append(15);\n    data.append(-73);\n    data.append(74);\n    data.append(-75);\n    data.append(18);\n    data.append(72);\n    data.append(22);\n    data.append(-124);\n    data.append(-79);\n    data.append(-94);\n    data.append(-50);\n    data.append(-95);\n    data.append(-18);\n    data.append(-5);\n    data.append(-127);\n    data.append(-99);\n    data.append(10);\n    data.append(101);\n    data.append(-69);\n    data.append(-109);\n    data.append(-92);\n    data.append(22);\n    data.append(45);\n    data.append(-13);\n    data.append(27);\n    data.append(77);\n    data.append(76);\n    data.append(76);\n    data.append(5);\n    data.append(121);\n    data.append(-16);\n    data.append(-94);\n    data.append(-59);\n    data.append(-71);\n    data.append(-52);\n    data.append(-41);\n    data.append(13);\n    data.append(13);\n    data.append(-21);\n    data.append(75);\n    data.append(-79);\n    data.append(52);\n    data.append(96);\n    data.append(-99);\n    data.append(25);\n    data.append(2);\n    data.append(-48);\n    data.append(36);\n    data.append(118);\n    data.append(-75);\n    data.append(-87);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i32_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(998);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_i8_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(123);\n    data.append(12);\n    data.append(-91);\n    data.append(122);\n    data.append(66);\n    data.append(42);\n    data.append(12);\n    data.append(18);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_i8_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorSub};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(-104);\n    data.append(-10);\n    data.append(-42);\n    data.append(54);\n    data.append(90);\n    data.append(94);\n    data.append(-6);\n    data.append(37);\n    data.append(125);\n    data.append(-14);\n    data.append(-16);\n    data.append(103);\n    data.append(74);\n    data.append(92);\n    data.append(17);\n    data.append(59);\n    data.append(79);\n    data.append(117);\n    data.append(29);\n    data.append(15);\n    data.append(-38);\n    data.append(-111);\n    data.append(-31);\n    data.append(71);\n    data.append(92);\n    data.append(122);\n    data.append(109);\n    data.append(-120);\n    data.append(-52);\n    data.append(-122);\n    data.append(88);\n    data.append(78);\n    data.append(99);\n    data.append(21);\n    data.append(-67);\n    data.append(-36);\n    data.append(21);\n    data.append(-62);\n    data.append(66);\n    data.append(64);\n    data.append(-70);\n    data.append(-44);\n    data.append(-58);\n    data.append(-27);\n    data.append(45);\n    data.append(104);\n    data.append(-103);\n    data.append(-36);\n    data.append(-44);\n    data.append(73);\n    data.append(-88);\n    data.append(-12);\n    data.append(-88);\n    data.append(37);\n    data.append(-127);\n    data.append(-9);\n    data.append(124);\n    data.append(-52);\n    data.append(126);\n    data.append(-15);\n    data.append(-81);\n    data.append(-60);\n    data.append(86);\n    data.append(-109);\n    data.append(89);\n    data.append(7);\n    data.append(33);\n    data.append(-113);\n    data.append(61);\n    data.append(-82);\n    data.append(18);\n    data.append(-107);\n    data.append(31);\n    data.append(83);\n    data.append(10);\n    data.append(3);\n    data.append(-18);\n    data.append(-2);\n    data.append(-47);\n    data.append(30);\n    data.append(-1);\n    data.append(-60);\n    data.append(-28);\n    data.append(31);\n    data.append(-101);\n    data.append(-49);\n    data.append(53);\n    data.append(-27);\n    data.append(-110);\n    data.append(28);\n    data.append(-83);\n    data.append(-30);\n    data.append(-27);\n    data.append(49);\n    data.append(22);\n    data.append(94);\n    data.append(84);\n    data.append(-41);\n    data.append(75);\n    data.append(93);\n    data.append(58);\n    data.append(-77);\n    data.append(16);\n    data.append(52);\n    data.append(-56);\n    data.append(75);\n    data.append(94);\n    data.append(88);\n    data.append(-33);\n    data.append(-83);\n    data.append(-20);\n    data.append(-125);\n    data.append(16);\n    data.append(-7);\n    data.append(-74);\n    data.append(-57);\n    data.append(37);\n    data.append(-46);\n    data.append(35);\n    data.append(8);\n    data.append(96);\n    data.append(42);\n    data.append(-76);\n    data.append(-103);\n    data.append(-50);\n    data.append(-24);\n    data.append(26);\n    data.append(33);\n    data.append(98);\n    data.append(30);\n    data.append(35);\n    data.append(110);\n    data.append(31);\n    data.append(-6);\n    data.append(-48);\n    data.append(-38);\n    data.append(105);\n    data.append(124);\n    data.append(65);\n    data.append(-119);\n    data.append(-34);\n    data.append(-24);\n    data.append(-54);\n    data.append(17);\n    data.append(48);\n    data.append(104);\n    data.append(24);\n    data.append(23);\n    data.append(116);\n    data.append(-69);\n    data.append(7);\n    data.append(-11);\n    data.append(-27);\n    data.append(-17);\n    data.append(41);\n    data.append(19);\n    data.append(20);\n    data.append(26);\n    data.append(-102);\n    data.append(0);\n    data.append(45);\n    data.append(-35);\n    data.append(41);\n    data.append(77);\n    data.append(-43);\n    data.append(89);\n    data.append(85);\n    data.append(-5);\n    data.append(97);\n    data.append(112);\n    data.append(93);\n    data.append(-33);\n    data.append(-74);\n    data.append(94);\n    data.append(95);\n    data.append(28);\n    data.append(95);\n    data.append(-48);\n    data.append(43);\n    data.append(-29);\n    data.append(65);\n    data.append(121);\n    data.append(-72);\n    data.append(17);\n    data.append(-116);\n    data.append(31);\n    data.append(105);\n    data.append(-85);\n    data.append(-24);\n    data.append(-38);\n    data.append(-9);\n    data.append(-88);\n    data.append(-126);\n    data.append(-119);\n    data.append(57);\n    data.append(89);\n    data.append(7);\n    data.append(5);\n    data.append(112);\n    data.append(-83);\n    data.append(25);\n    data.append(-33);\n    data.append(38);\n    data.append(-51);\n    data.append(50);\n    data.append(49);\n    data.append(71);\n    data.append(108);\n    data.append(-89);\n    data.append(-83);\n    data.append(-1);\n    data.append(-42);\n    data.append(-100);\n    data.append(74);\n    data.append(3);\n    data.append(-96);\n    data.append(-28);\n    data.append(-33);\n    data.append(-124);\n    data.append(70);\n    data.append(16);\n    data.append(-60);\n    data.append(-56);\n    data.append(-76);\n    data.append(113);\n    data.append(61);\n    data.append(-64);\n    data.append(78);\n    data.append(117);\n    data.append(37);\n    data.append(-94);\n    data.append(-45);\n    data.append(72);\n    data.append(8);\n    data.append(-53);\n    data.append(-120);\n    data.append(-125);\n    data.append(-96);\n    data.append(-65);\n    data.append(61);\n    data.append(-76);\n    data.append(93);\n    data.append(-89);\n    data.append(-22);\n    data.append(-5);\n    data.append(35);\n    data.append(42);\n    data.append(66);\n    data.append(53);\n    data.append(115);\n    data.append(-47);\n    data.append(-70);\n    data.append(-29);\n    data.append(52);\n    data.append(87);\n    data.append(91);\n    data.append(70);\n    data.append(-35);\n    data.append(-25);\n    data.append(-107);\n    data.append(34);\n    data.append(105);\n    data.append(-44);\n    data.append(-1);\n    data.append(95);\n    data.append(-36);\n    data.append(-54);\n    data.append(-114);\n    data.append(-108);\n    data.append(-48);\n    data.append(-49);\n    data.append(-106);\n    data.append(-115);\n    data.append(24);\n    data.append(-65);\n    data.append(-69);\n    data.append(75);\n    data.append(-57);\n    data.append(-4);\n    data.append(0);\n    data.append(116);\n    data.append(-24);\n    data.append(110);\n    data.append(10);\n    data.append(19);\n    data.append(-58);\n    data.append(38);\n    data.append(-71);\n    data.append(0);\n    data.append(76);\n    data.append(69);\n    data.append(33);\n    data.append(53);\n    data.append(-100);\n    data.append(99);\n    data.append(-23);\n    data.append(81);\n    data.append(48);\n    data.append(6);\n    data.append(-16);\n    data.append(-48);\n    data.append(25);\n    data.append(-73);\n    data.append(56);\n    data.append(23);\n    data.append(-85);\n    data.append(32);\n    data.append(-3);\n    data.append(-94);\n    data.append(-2);\n    data.append(119);\n    data.append(69);\n    data.append(40);\n    data.append(-87);\n    data.append(-113);\n    data.append(71);\n    data.append(15);\n    data.append(-105);\n    data.append(48);\n    data.append(24);\n    data.append(-72);\n    data.append(74);\n    data.append(-125);\n    data.append(-28);\n    data.append(-125);\n    data.append(-119);\n    data.append(87);\n    data.append(95);\n    data.append(-44);\n    data.append(-37);\n    data.append(17);\n    data.append(86);\n    data.append(-114);\n    data.append(-84);\n    data.append(-1);\n    data.append(-105);\n    data.append(-110);\n    data.append(-96);\n    data.append(99);\n    data.append(-127);\n    data.append(-50);\n    data.append(-47);\n    data.append(-26);\n    data.append(-70);\n    data.append(-13);\n    data.append(-70);\n    data.append(-104);\n    data.append(94);\n    data.append(83);\n    data.append(-56);\n    data.append(67);\n    data.append(5);\n    data.append(93);\n    data.append(60);\n    data.append(109);\n    data.append(42);\n    data.append(6);\n    data.append(84);\n    data.append(-115);\n    data.append(-47);\n    data.append(-90);\n    data.append(2);\n    data.append(37);\n    data.append(68);\n    data.append(122);\n    data.append(99);\n    data.append(-42);\n    data.append(-54);\n    data.append(-24);\n    data.append(-77);\n    data.append(-76);\n    data.append(-123);\n    data.append(-51);\n    data.append(86);\n    data.append(-111);\n    data.append(-45);\n    data.append(6);\n    data.append(-80);\n    data.append(73);\n    data.append(-76);\n    data.append(67);\n    data.append(104);\n    data.append(52);\n    data.append(-91);\n    data.append(-73);\n    data.append(-127);\n    data.append(-21);\n    data.append(-105);\n    data.append(35);\n    data.append(-41);\n    data.append(-82);\n    data.append(-23);\n    data.append(19);\n    data.append(-80);\n    data.append(-1);\n    data.append(-119);\n    data.append(-58);\n    data.append(105);\n    data.append(109);\n    data.append(65);\n    data.append(-74);\n    data.append(29);\n    data.append(-82);\n    data.append(-9);\n    data.append(37);\n    data.append(-63);\n    data.append(24);\n    data.append(-47);\n    data.append(-35);\n    data.append(-112);\n    data.append(-41);\n    data.append(36);\n    data.append(9);\n    data.append(45);\n    data.append(9);\n    data.append(-46);\n    data.append(121);\n    data.append(83);\n    data.append(-31);\n    data.append(-91);\n    data.append(51);\n    data.append(57);\n    data.append(12);\n    data.append(-65);\n    data.append(-70);\n    data.append(-40);\n    data.append(-54);\n    data.append(29);\n    data.append(12);\n    data.append(57);\n    data.append(41);\n    data.append(-86);\n    data.append(-40);\n    data.append(119);\n    data.append(-122);\n    data.append(-46);\n    data.append(46);\n    data.append(117);\n    data.append(-112);\n    data.append(88);\n    data.append(-66);\n    data.append(39);\n    data.append(99);\n    data.append(-66);\n    data.append(86);\n    data.append(-19);\n    data.append(88);\n    data.append(-80);\n    data.append(85);\n    data.append(-9);\n    data.append(23);\n    data.append(-111);\n    data.append(-1);\n    data.append(80);\n    data.append(-16);\n    data.append(-72);\n    data.append(5);\n    data.append(-92);\n    data.append(-71);\n    data.append(-20);\n    data.append(-82);\n    data.append(-77);\n    data.append(-124);\n    data.append(-58);\n    data.append(-74);\n    data.append(122);\n    data.append(41);\n    data.append(-101);\n    data.append(8);\n    data.append(-11);\n    data.append(41);\n    data.append(-61);\n    data.append(89);\n    data.append(-82);\n    data.append(-97);\n    data.append(-46);\n    data.append(-55);\n    data.append(10);\n    data.append(95);\n    data.append(85);\n    data.append(-29);\n    data.append(10);\n    data.append(-25);\n    data.append(-9);\n    data.append(-24);\n    data.append(-67);\n    data.append(16);\n    data.append(78);\n    data.append(-77);\n    data.append(33);\n    data.append(87);\n    data.append(-93);\n    data.append(-19);\n    data.append(-80);\n    data.append(-24);\n    data.append(-93);\n    data.append(47);\n    data.append(27);\n    data.append(-1);\n    data.append(72);\n    data.append(-25);\n    data.append(42);\n    data.append(-45);\n    data.append(101);\n    data.append(-36);\n    data.append(-2);\n    data.append(-125);\n    data.append(-89);\n    data.append(56);\n    data.append(8);\n    data.append(-109);\n    data.append(-91);\n    data.append(75);\n    data.append(118);\n    data.append(102);\n    data.append(-100);\n    data.append(-51);\n    data.append(-89);\n    data.append(103);\n    data.append(-47);\n    data.append(114);\n    data.append(0);\n    data.append(-97);\n    data.append(-75);\n    data.append(-127);\n    data.append(-15);\n    data.append(-109);\n    data.append(94);\n    data.append(33);\n    data.append(-13);\n    data.append(77);\n    data.append(-48);\n    data.append(69);\n    data.append(84);\n    data.append(47);\n    data.append(4);\n    data.append(-78);\n    data.append(-25);\n    data.append(-55);\n    data.append(119);\n    data.append(73);\n    data.append(0);\n    data.append(89);\n    data.append(34);\n    data.append(48);\n    data.append(49);\n    data.append(29);\n    data.append(-110);\n    data.append(11);\n    data.append(-88);\n    data.append(67);\n    data.append(-12);\n    data.append(-67);\n    data.append(6);\n    data.append(-4);\n    data.append(6);\n    data.append(9);\n    data.append(-38);\n    data.append(114);\n    data.append(110);\n    data.append(93);\n    data.append(8);\n    data.append(126);\n    data.append(96);\n    data.append(-51);\n    data.append(16);\n    data.append(87);\n    data.append(-35);\n    data.append(29);\n    data.append(67);\n    data.append(-64);\n    data.append(-2);\n    data.append(-113);\n    data.append(38);\n    data.append(3);\n    data.append(-82);\n    data.append(9);\n    data.append(-101);\n    data.append(9);\n    data.append(27);\n    data.append(51);\n    data.append(-6);\n    data.append(32);\n    data.append(-19);\n    data.append(35);\n    data.append(62);\n    data.append(-66);\n    data.append(-107);\n    data.append(-4);\n    data.append(80);\n    data.append(104);\n    data.append(7);\n    data.append(-69);\n    data.append(68);\n    data.append(28);\n    data.append(114);\n    data.append(91);\n    data.append(75);\n    data.append(-60);\n    data.append(-31);\n    data.append(121);\n    data.append(76);\n    data.append(-59);\n    data.append(50);\n    data.append(-70);\n    data.append(112);\n    data.append(16);\n    data.append(-73);\n    data.append(106);\n    data.append(117);\n    data.append(38);\n    data.append(14);\n    data.append(-124);\n    data.append(89);\n    data.append(-11);\n    data.append(-90);\n    data.append(69);\n    data.append(-56);\n    data.append(60);\n    data.append(-57);\n    data.append(65);\n    data.append(48);\n    data.append(106);\n    data.append(-103);\n    data.append(79);\n    data.append(-52);\n    data.append(-101);\n    data.append(-28);\n    data.append(-94);\n    data.append(4);\n    data.append(-106);\n    data.append(-99);\n    data.append(-25);\n    data.append(-26);\n    data.append(-75);\n    data.append(-18);\n    data.append(75);\n    data.append(-42);\n    data.append(68);\n    data.append(-58);\n    data.append(53);\n    data.append(64);\n    data.append(77);\n    data.append(-81);\n    data.append(85);\n    data.append(103);\n    data.append(114);\n    data.append(78);\n    data.append(-54);\n    data.append(-122);\n    data.append(-2);\n    data.append(-59);\n    data.append(-78);\n    data.append(-2);\n    data.append(-56);\n    data.append(-11);\n    data.append(38);\n    data.append(48);\n    data.append(86);\n    data.append(-21);\n    data.append(50);\n    data.append(-106);\n    data.append(4);\n    data.append(-97);\n    data.append(-89);\n    data.append(-42);\n    data.append(72);\n    data.append(27);\n    data.append(-80);\n    data.append(66);\n    data.append(53);\n    data.append(114);\n    data.append(98);\n    data.append(-25);\n    data.append(-15);\n    data.append(106);\n    data.append(-9);\n    data.append(-67);\n    data.append(-110);\n    data.append(36);\n    data.append(-94);\n    data.append(110);\n    data.append(-127);\n    data.append(-71);\n    data.append(82);\n    data.append(100);\n    data.append(82);\n    data.append(-93);\n    data.append(-29);\n    data.append(-87);\n    data.append(94);\n    data.append(-101);\n    data.append(-84);\n    data.append(-58);\n    data.append(25);\n    data.append(-15);\n    data.append(85);\n    data.append(-97);\n    data.append(-86);\n    data.append(-43);\n    data.append(23);\n    data.append(-118);\n    data.append(-68);\n    data.append(-98);\n    data.append(66);\n    data.append(-18);\n    data.append(124);\n    data.append(-119);\n    data.append(-107);\n    data.append(17);\n    data.append(-59);\n    data.append(58);\n    data.append(14);\n    data.append(32);\n    data.append(52);\n    data.append(43);\n    data.append(-80);\n    data.append(24);\n    data.append(-117);\n    data.append(-2);\n    data.append(3);\n    data.append(113);\n    data.append(-74);\n    data.append(105);\n    data.append(-9);\n    data.append(41);\n    data.append(-29);\n    data.append(97);\n    data.append(-8);\n    data.append(-97);\n    data.append(-22);\n    data.append(111);\n    data.append(21);\n    data.append(111);\n    data.append(-5);\n    data.append(42);\n    data.append(-45);\n    data.append(106);\n    data.append(-79);\n    data.append(-48);\n    data.append(-75);\n    data.append(-19);\n    data.append(93);\n    data.append(48);\n    data.append(-92);\n    data.append(-37);\n    data.append(114);\n    data.append(40);\n    data.append(110);\n    data.append(-93);\n    data.append(-56);\n    data.append(-61);\n    data.append(50);\n    data.append(-37);\n    data.append(-48);\n    data.append(68);\n    data.append(69);\n    data.append(-54);\n    data.append(-71);\n    data.append(-82);\n    data.append(-22);\n    data.append(-3);\n    data.append(7);\n    data.append(-81);\n    data.append(78);\n    data.append(7);\n    data.append(102);\n    data.append(41);\n    data.append(40);\n    data.append(-14);\n    data.append(-17);\n    data.append(-86);\n    data.append(-123);\n    data.append(5);\n    data.append(-1);\n    data.append(98);\n    data.append(-36);\n    data.append(36);\n    data.append(-65);\n    data.append(-122);\n    data.append(-123);\n    data.append(40);\n    data.append(-90);\n    data.append(-57);\n    data.append(92);\n    data.append(-38);\n    data.append(114);\n    data.append(-68);\n    data.append(101);\n    data.append(-38);\n    data.append(-2);\n    data.append(-124);\n    data.append(-1);\n    data.append(-122);\n    data.append(98);\n    data.append(-29);\n    data.append(-27);\n    data.append(-25);\n    data.append(-89);\n    data.append(-112);\n    data.append(-32);\n    data.append(115);\n    data.append(59);\n    data.append(118);\n    data.append(-96);\n    data.append(72);\n    data.append(-82);\n    data.append(30);\n    data.append(112);\n    data.append(72);\n    data.append(113);\n    data.append(106);\n    data.append(55);\n    data.append(18);\n    data.append(62);\n    data.append(-70);\n    data.append(31);\n    data.append(24);\n    data.append(29);\n    data.append(-72);\n    data.append(-87);\n    data.append(89);\n    data.append(-55);\n    data.append(-88);\n    data.append(6);\n    data.append(40);\n    data.append(89);\n    data.append(-25);\n    data.append(7);\n    data.append(-127);\n    data.append(71);\n    data.append(79);\n    data.append(-82);\n    data.append(-43);\n    data.append(-33);\n    data.append(-1);\n    data.append(-40);\n    data.append(-44);\n    data.append(104);\n    data.append(-70);\n    data.append(57);\n    data.append(13);\n    data.append(-109);\n    data.append(110);\n    data.append(-35);\n    data.append(104);\n    data.append(-37);\n    data.append(-116);\n    data.append(39);\n    data.append(9);\n    data.append(-68);\n    data.append(64);\n    data.append(-89);\n    data.append(86);\n    data.append(126);\n    data.append(65);\n    data.append(-56);\n    data.append(-123);\n    data.append(110);\n    data.append(-45);\n    data.append(-38);\n    data.append(-9);\n    data.append(-103);\n    data.append(-60);\n    data.append(-54);\n    data.append(-105);\n    data.append(98);\n    data.append(86);\n    data.append(-12);\n    data.append(-75);\n    data.append(-73);\n    data.append(-114);\n    data.append(-72);\n    data.append(46);\n    data.append(-126);\n    data.append(-69);\n    data.append(-26);\n    data.append(44);\n    data.append(-74);\n    data.append(116);\n    data.append(-30);\n    data.append(5);\n    data.append(-125);\n    data.append(-115);\n    data.append(-81);\n    data.append(102);\n    data.append(-18);\n    data.append(103);\n    data.append(-73);\n    data.append(-46);\n    data.append(-89);\n    data.append(-33);\n    data.append(-64);\n    data.append(-53);\n    data.append(-86);\n    data.append(-24);\n    data.append(23);\n    data.append(108);\n    data.append(105);\n    data.append(3);\n    data.append(-121);\n    data.append(-112);\n    data.append(67);\n    data.append(-62);\n    data.append(94);\n    data.append(98);\n    data.append(-81);\n    data.append(73);\n    data.append(33);\n    data.append(-97);\n    data.append(-30);\n    data.append(30);\n    data.append(-11);\n    data.append(-89);\n    data.append(113);\n    data.append(-30);\n    data.append(95);\n    data.append(46);\n    data.append(-118);\n    data.append(1);\n    data.append(-104);\n    data.append(112);\n    data.append(10);\n    data.append(5);\n    data.append(-61);\n    data.append(96);\n    data.append(-20);\n    data.append(-112);\n    data.append(-36);\n    data.append(-12);\n    data.append(-111);\n    data.append(60);\n    data.append(-36);\n    data.append(102);\n    data.append(-81);\n    data.append(-109);\n    data.append(61);\n    data.append(-64);\n    data.append(19);\n    data.append(-107);\n    data.append(-7);\n    data.append(9);\n    data.append(-122);\n    data.append(-80);\n    data.append(-118);\n    data.append(34);\n    data.append(-71);\n    data.append(-42);\n    data.append(-9);\n    data.append(48);\n    data.append(-25);\n    data.append(7);\n    data.append(-127);\n    data.append(-79);\n    data.append(-105);\n    data.append(90);\n    data.append(-33);\n    data.append(68);\n    data.append(-3);\n    data.append(-23);\n    data.append(6);\n    data.append(107);\n    data.append(66);\n    data.append(51);\n    data.append(-12);\n    data.append(55);\n    data.append(-31);\n    data.append(-93);\n    data.append(119);\n    data.append(-45);\n    data.append(84);\n    data.append(-92);\n    data.append(52);\n    data.append(-90);\n    data.append(-12);\n    data.append(19);\n    data.append(-104);\n    data.append(67);\n    data.append(-108);\n    data.append(-40);\n    data.append(-115);\n    data.append(87);\n    data.append(3);\n    data.append(-15);\n    data.append(-109);\n    data.append(68);\n    data.append(-42);\n    data.append(-93);\n    data.append(-98);\n    data.append(-22);\n    data.append(-89);\n    data.append(-110);\n    data.append(-110);\n    data.append(-4);\n    data.append(-26);\n    data.append(90);\n    data.append(55);\n    data.append(-34);\n    data.append(31);\n    data.append(-102);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_i8_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(995);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_2d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_u32_2d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_2d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(4);\n\n    let mut data = ArrayTrait::new();\n    data.append(75);\n    data.append(210);\n    data.append(169);\n    data.append(35);\n    data.append(213);\n    data.append(12);\n    data.append(32);\n    data.append(9);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_2d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(8);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_3d.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_nonzero_u32_3d() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.nonzero();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_3d/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(20);\n    shape.append(10);\n    shape.append(5);\n\n    let mut data = ArrayTrait::new();\n    data.append(217);\n    data.append(153);\n    data.append(64);\n    data.append(56);\n    data.append(242);\n    data.append(184);\n    data.append(154);\n    data.append(10);\n    data.append(204);\n    data.append(131);\n    data.append(162);\n    data.append(226);\n    data.append(127);\n    data.append(196);\n    data.append(72);\n    data.append(76);\n    data.append(158);\n    data.append(222);\n    data.append(133);\n    data.append(187);\n    data.append(29);\n    data.append(207);\n    data.append(34);\n    data.append(54);\n    data.append(98);\n    data.append(70);\n    data.append(182);\n    data.append(48);\n    data.append(212);\n    data.append(151);\n    data.append(108);\n    data.append(126);\n    data.append(139);\n    data.append(13);\n    data.append(133);\n    data.append(150);\n    data.append(30);\n    data.append(235);\n    data.append(198);\n    data.append(186);\n    data.append(59);\n    data.append(233);\n    data.append(37);\n    data.append(247);\n    data.append(21);\n    data.append(30);\n    data.append(9);\n    data.append(26);\n    data.append(4);\n    data.append(157);\n    data.append(158);\n    data.append(170);\n    data.append(232);\n    data.append(27);\n    data.append(181);\n    data.append(27);\n    data.append(134);\n    data.append(23);\n    data.append(123);\n    data.append(27);\n    data.append(72);\n    data.append(39);\n    data.append(52);\n    data.append(129);\n    data.append(202);\n    data.append(163);\n    data.append(95);\n    data.append(243);\n    data.append(198);\n    data.append(230);\n    data.append(21);\n    data.append(254);\n    data.append(7);\n    data.append(250);\n    data.append(181);\n    data.append(187);\n    data.append(41);\n    data.append(51);\n    data.append(139);\n    data.append(12);\n    data.append(161);\n    data.append(64);\n    data.append(133);\n    data.append(66);\n    data.append(133);\n    data.append(87);\n    data.append(5);\n    data.append(56);\n    data.append(160);\n    data.append(143);\n    data.append(200);\n    data.append(180);\n    data.append(153);\n    data.append(211);\n    data.append(207);\n    data.append(51);\n    data.append(248);\n    data.append(149);\n    data.append(195);\n    data.append(39);\n    data.append(31);\n    data.append(61);\n    data.append(69);\n    data.append(105);\n    data.append(225);\n    data.append(149);\n    data.append(58);\n    data.append(18);\n    data.append(141);\n    data.append(209);\n    data.append(99);\n    data.append(10);\n    data.append(37);\n    data.append(21);\n    data.append(193);\n    data.append(232);\n    data.append(82);\n    data.append(6);\n    data.append(213);\n    data.append(38);\n    data.append(66);\n    data.append(157);\n    data.append(217);\n    data.append(222);\n    data.append(216);\n    data.append(200);\n    data.append(226);\n    data.append(142);\n    data.append(70);\n    data.append(39);\n    data.append(219);\n    data.append(55);\n    data.append(79);\n    data.append(82);\n    data.append(212);\n    data.append(27);\n    data.append(163);\n    data.append(180);\n    data.append(39);\n    data.append(102);\n    data.append(73);\n    data.append(205);\n    data.append(51);\n    data.append(182);\n    data.append(186);\n    data.append(104);\n    data.append(169);\n    data.append(122);\n    data.append(201);\n    data.append(226);\n    data.append(205);\n    data.append(248);\n    data.append(230);\n    data.append(22);\n    data.append(1);\n    data.append(3);\n    data.append(151);\n    data.append(204);\n    data.append(222);\n    data.append(180);\n    data.append(58);\n    data.append(85);\n    data.append(153);\n    data.append(116);\n    data.append(235);\n    data.append(87);\n    data.append(47);\n    data.append(142);\n    data.append(231);\n    data.append(41);\n    data.append(72);\n    data.append(42);\n    data.append(242);\n    data.append(86);\n    data.append(164);\n    data.append(23);\n    data.append(207);\n    data.append(53);\n    data.append(23);\n    data.append(66);\n    data.append(138);\n    data.append(148);\n    data.append(9);\n    data.append(143);\n    data.append(195);\n    data.append(140);\n    data.append(62);\n    data.append(5);\n    data.append(222);\n    data.append(100);\n    data.append(226);\n    data.append(240);\n    data.append(66);\n    data.append(120);\n    data.append(217);\n    data.append(95);\n    data.append(168);\n    data.append(189);\n    data.append(196);\n    data.append(250);\n    data.append(5);\n    data.append(11);\n    data.append(1);\n    data.append(98);\n    data.append(198);\n    data.append(82);\n    data.append(120);\n    data.append(110);\n    data.append(32);\n    data.append(144);\n    data.append(240);\n    data.append(209);\n    data.append(63);\n    data.append(212);\n    data.append(21);\n    data.append(185);\n    data.append(109);\n    data.append(252);\n    data.append(83);\n    data.append(162);\n    data.append(35);\n    data.append(149);\n    data.append(5);\n    data.append(193);\n    data.append(18);\n    data.append(185);\n    data.append(222);\n    data.append(252);\n    data.append(22);\n    data.append(160);\n    data.append(58);\n    data.append(18);\n    data.append(109);\n    data.append(253);\n    data.append(56);\n    data.append(217);\n    data.append(9);\n    data.append(21);\n    data.append(168);\n    data.append(89);\n    data.append(191);\n    data.append(202);\n    data.append(91);\n    data.append(138);\n    data.append(42);\n    data.append(62);\n    data.append(214);\n    data.append(25);\n    data.append(225);\n    data.append(158);\n    data.append(136);\n    data.append(224);\n    data.append(62);\n    data.append(162);\n    data.append(155);\n    data.append(239);\n    data.append(202);\n    data.append(101);\n    data.append(176);\n    data.append(176);\n    data.append(15);\n    data.append(208);\n    data.append(247);\n    data.append(108);\n    data.append(1);\n    data.append(222);\n    data.append(20);\n    data.append(127);\n    data.append(108);\n    data.append(224);\n    data.append(22);\n    data.append(76);\n    data.append(113);\n    data.append(37);\n    data.append(192);\n    data.append(88);\n    data.append(167);\n    data.append(62);\n    data.append(172);\n    data.append(108);\n    data.append(197);\n    data.append(75);\n    data.append(143);\n    data.append(149);\n    data.append(205);\n    data.append(119);\n    data.append(4);\n    data.append(108);\n    data.append(208);\n    data.append(105);\n    data.append(22);\n    data.append(170);\n    data.append(212);\n    data.append(218);\n    data.append(62);\n    data.append(25);\n    data.append(48);\n    data.append(152);\n    data.append(91);\n    data.append(201);\n    data.append(190);\n    data.append(104);\n    data.append(86);\n    data.append(149);\n    data.append(145);\n    data.append(210);\n    data.append(165);\n    data.append(25);\n    data.append(224);\n    data.append(128);\n    data.append(69);\n    data.append(52);\n    data.append(202);\n    data.append(218);\n    data.append(86);\n    data.append(44);\n    data.append(15);\n    data.append(202);\n    data.append(170);\n    data.append(46);\n    data.append(132);\n    data.append(248);\n    data.append(4);\n    data.append(89);\n    data.append(229);\n    data.append(236);\n    data.append(73);\n    data.append(188);\n    data.append(113);\n    data.append(164);\n    data.append(115);\n    data.append(109);\n    data.append(92);\n    data.append(25);\n    data.append(206);\n    data.append(24);\n    data.append(83);\n    data.append(159);\n    data.append(197);\n    data.append(154);\n    data.append(213);\n    data.append(41);\n    data.append(80);\n    data.append(128);\n    data.append(15);\n    data.append(11);\n    data.append(127);\n    data.append(40);\n    data.append(16);\n    data.append(235);\n    data.append(94);\n    data.append(55);\n    data.append(234);\n    data.append(163);\n    data.append(168);\n    data.append(36);\n    data.append(181);\n    data.append(162);\n    data.append(53);\n    data.append(64);\n    data.append(159);\n    data.append(41);\n    data.append(216);\n    data.append(188);\n    data.append(219);\n    data.append(141);\n    data.append(121);\n    data.append(38);\n    data.append(78);\n    data.append(239);\n    data.append(167);\n    data.append(238);\n    data.append(41);\n    data.append(212);\n    data.append(214);\n    data.append(85);\n    data.append(166);\n    data.append(156);\n    data.append(37);\n    data.append(226);\n    data.append(80);\n    data.append(197);\n    data.append(164);\n    data.append(127);\n    data.append(213);\n    data.append(13);\n    data.append(169);\n    data.append(224);\n    data.append(33);\n    data.append(199);\n    data.append(247);\n    data.append(223);\n    data.append(106);\n    data.append(224);\n    data.append(181);\n    data.append(48);\n    data.append(245);\n    data.append(2);\n    data.append(252);\n    data.append(63);\n    data.append(3);\n    data.append(14);\n    data.append(121);\n    data.append(226);\n    data.append(217);\n    data.append(231);\n    data.append(101);\n    data.append(89);\n    data.append(166);\n    data.append(221);\n    data.append(119);\n    data.append(49);\n    data.append(4);\n    data.append(196);\n    data.append(56);\n    data.append(231);\n    data.append(69);\n    data.append(20);\n    data.append(165);\n    data.append(81);\n    data.append(15);\n    data.append(208);\n    data.append(118);\n    data.append(216);\n    data.append(133);\n    data.append(118);\n    data.append(68);\n    data.append(102);\n    data.append(116);\n    data.append(135);\n    data.append(64);\n    data.append(7);\n    data.append(103);\n    data.append(173);\n    data.append(149);\n    data.append(208);\n    data.append(191);\n    data.append(83);\n    data.append(213);\n    data.append(166);\n    data.append(166);\n    data.append(177);\n    data.append(88);\n    data.append(97);\n    data.append(227);\n    data.append(181);\n    data.append(70);\n    data.append(83);\n    data.append(188);\n    data.append(54);\n    data.append(148);\n    data.append(155);\n    data.append(172);\n    data.append(74);\n    data.append(250);\n    data.append(19);\n    data.append(25);\n    data.append(170);\n    data.append(215);\n    data.append(188);\n    data.append(129);\n    data.append(73);\n    data.append(71);\n    data.append(144);\n    data.append(241);\n    data.append(217);\n    data.append(197);\n    data.append(10);\n    data.append(39);\n    data.append(187);\n    data.append(101);\n    data.append(75);\n    data.append(1);\n    data.append(221);\n    data.append(140);\n    data.append(199);\n    data.append(24);\n    data.append(251);\n    data.append(114);\n    data.append(175);\n    data.append(157);\n    data.append(166);\n    data.append(204);\n    data.append(235);\n    data.append(89);\n    data.append(90);\n    data.append(188);\n    data.append(179);\n    data.append(118);\n    data.append(53);\n    data.append(94);\n    data.append(67);\n    data.append(127);\n    data.append(207);\n    data.append(177);\n    data.append(141);\n    data.append(193);\n    data.append(113);\n    data.append(213);\n    data.append(15);\n    data.append(92);\n    data.append(52);\n    data.append(186);\n    data.append(40);\n    data.append(192);\n    data.append(240);\n    data.append(60);\n    data.append(183);\n    data.append(94);\n    data.append(103);\n    data.append(181);\n    data.append(235);\n    data.append(95);\n    data.append(73);\n    data.append(232);\n    data.append(208);\n    data.append(12);\n    data.append(199);\n    data.append(13);\n    data.append(180);\n    data.append(125);\n    data.append(144);\n    data.append(46);\n    data.append(7);\n    data.append(149);\n    data.append(51);\n    data.append(27);\n    data.append(202);\n    data.append(169);\n    data.append(114);\n    data.append(131);\n    data.append(167);\n    data.append(105);\n    data.append(234);\n    data.append(245);\n    data.append(69);\n    data.append(240);\n    data.append(168);\n    data.append(224);\n    data.append(117);\n    data.append(211);\n    data.append(208);\n    data.append(227);\n    data.append(196);\n    data.append(157);\n    data.append(189);\n    data.append(43);\n    data.append(244);\n    data.append(25);\n    data.append(120);\n    data.append(74);\n    data.append(13);\n    data.append(206);\n    data.append(30);\n    data.append(100);\n    data.append(130);\n    data.append(214);\n    data.append(184);\n    data.append(133);\n    data.append(200);\n    data.append(115);\n    data.append(94);\n    data.append(114);\n    data.append(173);\n    data.append(110);\n    data.append(51);\n    data.append(126);\n    data.append(97);\n    data.append(137);\n    data.append(77);\n    data.append(19);\n    data.append(241);\n    data.append(58);\n    data.append(175);\n    data.append(53);\n    data.append(9);\n    data.append(75);\n    data.append(165);\n    data.append(186);\n    data.append(57);\n    data.append(81);\n    data.append(249);\n    data.append(251);\n    data.append(220);\n    data.append(226);\n    data.append(43);\n    data.append(15);\n    data.append(90);\n    data.append(104);\n    data.append(89);\n    data.append(10);\n    data.append(184);\n    data.append(171);\n    data.append(13);\n    data.append(151);\n    data.append(28);\n    data.append(207);\n    data.append(94);\n    data.append(87);\n    data.append(174);\n    data.append(139);\n    data.append(49);\n    data.append(74);\n    data.append(239);\n    data.append(56);\n    data.append(96);\n    data.append(12);\n    data.append(223);\n    data.append(140);\n    data.append(156);\n    data.append(161);\n    data.append(122);\n    data.append(252);\n    data.append(51);\n    data.append(219);\n    data.append(79);\n    data.append(212);\n    data.append(139);\n    data.append(240);\n    data.append(31);\n    data.append(143);\n    data.append(42);\n    data.append(153);\n    data.append(61);\n    data.append(106);\n    data.append(63);\n    data.append(82);\n    data.append(181);\n    data.append(5);\n    data.append(232);\n    data.append(191);\n    data.append(131);\n    data.append(145);\n    data.append(136);\n    data.append(14);\n    data.append(165);\n    data.append(131);\n    data.append(84);\n    data.append(62);\n    data.append(117);\n    data.append(103);\n    data.append(253);\n    data.append(195);\n    data.append(58);\n    data.append(12);\n    data.append(175);\n    data.append(11);\n    data.append(155);\n    data.append(236);\n    data.append(213);\n    data.append(240);\n    data.append(1);\n    data.append(93);\n    data.append(43);\n    data.append(208);\n    data.append(215);\n    data.append(36);\n    data.append(157);\n    data.append(160);\n    data.append(117);\n    data.append(121);\n    data.append(223);\n    data.append(231);\n    data.append(5);\n    data.append(0);\n    data.append(56);\n    data.append(31);\n    data.append(143);\n    data.append(42);\n    data.append(153);\n    data.append(23);\n    data.append(219);\n    data.append(28);\n    data.append(225);\n    data.append(188);\n    data.append(160);\n    data.append(149);\n    data.append(239);\n    data.append(85);\n    data.append(141);\n    data.append(31);\n    data.append(173);\n    data.append(202);\n    data.append(169);\n    data.append(39);\n    data.append(85);\n    data.append(77);\n    data.append(85);\n    data.append(94);\n    data.append(47);\n    data.append(89);\n    data.append(116);\n    data.append(72);\n    data.append(77);\n    data.append(254);\n    data.append(25);\n    data.append(114);\n    data.append(130);\n    data.append(144);\n    data.append(139);\n    data.append(150);\n    data.append(202);\n    data.append(117);\n    data.append(218);\n    data.append(123);\n    data.append(243);\n    data.append(163);\n    data.append(5);\n    data.append(158);\n    data.append(172);\n    data.append(42);\n    data.append(111);\n    data.append(177);\n    data.append(152);\n    data.append(199);\n    data.append(0);\n    data.append(104);\n    data.append(242);\n    data.append(238);\n    data.append(204);\n    data.append(186);\n    data.append(246);\n    data.append(163);\n    data.append(205);\n    data.append(59);\n    data.append(179);\n    data.append(2);\n    data.append(23);\n    data.append(231);\n    data.append(176);\n    data.append(237);\n    data.append(213);\n    data.append(39);\n    data.append(99);\n    data.append(130);\n    data.append(236);\n    data.append(174);\n    data.append(206);\n    data.append(8);\n    data.append(114);\n    data.append(44);\n    data.append(100);\n    data.append(69);\n    data.append(51);\n    data.append(245);\n    data.append(248);\n    data.append(188);\n    data.append(46);\n    data.append(15);\n    data.append(127);\n    data.append(96);\n    data.append(226);\n    data.append(37);\n    data.append(173);\n    data.append(96);\n    data.append(19);\n    data.append(108);\n    data.append(128);\n    data.append(225);\n    data.append(165);\n    data.append(81);\n    data.append(188);\n    data.append(18);\n    data.append(90);\n    data.append(201);\n    data.append(238);\n    data.append(47);\n    data.append(7);\n    data.append(223);\n    data.append(212);\n    data.append(33);\n    data.append(118);\n    data.append(169);\n    data.append(41);\n    data.append(244);\n    data.append(104);\n    data.append(92);\n    data.append(138);\n    data.append(44);\n    data.append(48);\n    data.append(182);\n    data.append(212);\n    data.append(215);\n    data.append(18);\n    data.append(184);\n    data.append(175);\n    data.append(90);\n    data.append(251);\n    data.append(47);\n    data.append(111);\n    data.append(54);\n    data.append(245);\n    data.append(214);\n    data.append(14);\n    data.append(121);\n    data.append(220);\n    data.append(219);\n    data.append(88);\n    data.append(34);\n    data.append(163);\n    data.append(23);\n    data.append(134);\n    data.append(117);\n    data.append(67);\n    data.append(27);\n    data.append(157);\n    data.append(151);\n    data.append(220);\n    data.append(30);\n    data.append(133);\n    data.append(28);\n    data.append(140);\n    data.append(179);\n    data.append(132);\n    data.append(79);\n    data.append(121);\n    data.append(96);\n    data.append(167);\n    data.append(185);\n    data.append(138);\n    data.append(125);\n    data.append(48);\n    data.append(147);\n    data.append(35);\n    data.append(132);\n    data.append(105);\n    data.append(74);\n    data.append(249);\n    data.append(208);\n    data.append(37);\n    data.append(189);\n    data.append(153);\n    data.append(73);\n    data.append(142);\n    data.append(202);\n    data.append(152);\n    data.append(253);\n    data.append(45);\n    data.append(58);\n    data.append(45);\n    data.append(174);\n    data.append(187);\n    data.append(88);\n    data.append(127);\n    data.append(188);\n    data.append(158);\n    data.append(133);\n    data.append(192);\n    data.append(40);\n    data.append(70);\n    data.append(224);\n    data.append(216);\n    data.append(106);\n    data.append(30);\n    data.append(2);\n    data.append(87);\n    data.append(89);\n    data.append(233);\n    data.append(191);\n    data.append(76);\n    data.append(100);\n    data.append(105);\n    data.append(0);\n    data.append(26);\n    data.append(146);\n    data.append(182);\n    data.append(30);\n    data.append(56);\n    data.append(234);\n    data.append(88);\n    data.append(124);\n    data.append(61);\n    data.append(229);\n    data.append(94);\n    data.append(201);\n    data.append(109);\n    data.append(196);\n    data.append(155);\n    data.append(149);\n    data.append(105);\n    data.append(217);\n    data.append(100);\n    data.append(51);\n    data.append(149);\n    data.append(153);\n    data.append(102);\n    data.append(3);\n    data.append(82);\n    data.append(73);\n    data.append(60);\n    data.append(165);\n    data.append(160);\n    data.append(32);\n    data.append(146);\n    data.append(181);\n    data.append(46);\n    data.append(85);\n    data.append(55);\n    data.append(151);\n    data.append(203);\n    data.append(200);\n    data.append(89);\n    data.append(26);\n    data.append(109);\n    data.append(10);\n    data.append(5);\n    data.append(23);\n    data.append(15);\n    data.append(174);\n    data.append(67);\n    data.append(218);\n    data.append(214);\n    data.append(207);\n    data.append(237);\n    data.append(210);\n    data.append(72);\n    data.append(112);\n    data.append(37);\n    data.append(97);\n    data.append(206);\n    data.append(201);\n    data.append(93);\n    data.append(10);\n    data.append(149);\n    data.append(110);\n    data.append(99);\n    data.append(203);\n    data.append(107);\n    data.append(211);\n    data.append(225);\n    data.append(26);\n    data.append(99);\n    data.append(218);\n    data.append(85);\n    data.append(174);\n    data.append(138);\n    data.append(10);\n    data.append(133);\n    data.append(242);\n    data.append(96);\n    data.append(174);\n    data.append(161);\n    data.append(92);\n    data.append(156);\n    data.append(235);\n    data.append(174);\n    data.append(13);\n    data.append(223);\n    data.append(70);\n    data.append(50);\n    data.append(152);\n    data.append(247);\n    data.append(80);\n    data.append(30);\n    data.append(72);\n    data.append(77);\n    data.append(141);\n    data.append(161);\n    data.append(219);\n    data.append(94);\n    data.append(121);\n    data.append(251);\n    data.append(234);\n    data.append(239);\n    data.append(109);\n    data.append(201);\n    data.append(7);\n    data.append(152);\n    data.append(213);\n    data.append(93);\n    data.append(254);\n    data.append(82);\n    data.append(137);\n    data.append(83);\n    data.append(214);\n    data.append(172);\n    data.append(208);\n    data.append(236);\n    data.append(215);\n    data.append(164);\n    data.append(15);\n    data.append(102);\n    data.append(26);\n    data.append(220);\n    data.append(12);\n    data.append(77);\n    data.append(25);\n    data.append(99);\n    data.append(62);\n    data.append(144);\n    data.append(95);\n    data.append(45);\n    data.append(57);\n    data.append(125);\n    data.append(155);\n    data.append(204);\n    data.append(125);\n    data.append(163);\n    data.append(239);\n    data.append(70);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/nonzero_u32_3d/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorSub};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(997);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(10);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(11);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(12);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(13);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(14);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(15);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(16);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(17);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(18);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(19);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(3);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(4);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(5);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(6);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(7);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(8);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(9);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    data.append(0);\n    data.append(1);\n    data.append(2);\n    data.append(3);\n    data.append(4);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/not_bool.cairo",
        "content": "mod input_0;\nmod output_0;\n\n\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::TensorTrait;\nuse orion::operators::tensor::BoolTensor;\nuse orion::operators::tensor::BoolTensorPartialEq;\nuse orion::utils::assert_eq;\n\n#[test]\n#[available_gas(2000000000)]\nfn test_not_bool() {\n    let input_0 = input_0::input_0();\n    let z = output_0::output_0();\n\n    let y = input_0.not();\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/not_bool/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn input_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(true);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/not_bool/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::BoolTensor;\n\nfn output_0() -> Tensor<bool> {\n    let mut shape = ArrayTrait::new();\n    shape.append(1);\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(false);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 0, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 196608, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: true });\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorMul};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: true });\n    data.append(FP16x16 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 16777216, sign: false });\n    data.append(FP8x23 { mag: 8388608, sign: false });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_fp8x23_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_0() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 16777216, sign: true });\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    data.append(FP8x23 { mag: 25165824, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorMul};\nuse orion::numbers::{FixedTrait, FP8x23};\n\nfn input_1() -> Tensor<FP8x23> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP8x23 { mag: 8388608, sign: true });\n    data.append(FP8x23 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_fp8x23_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_i32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(0);\n    data.append(-2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(-2);\n    data.append(-3);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(-3);\n    data.append(-2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    data.append(-1);\n    data.append(0);\n    data.append(0);\n    data.append(-2);\n    data.append(-2);\n    data.append(2);\n    data.append(-2);\n    data.append(-2);\n    data.append(-1);\n    data.append(-3);\n    data.append(-3);\n    data.append(2);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::I32TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_i32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_0() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I32Tensor, I32TensorMul};\n\nfn input_1() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_i8() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(-1);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(-2);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(0);\n    data.append(2);\n    data.append(1);\n    data.append(2);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-2);\n    data.append(-1);\n    data.append(-1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(-3);\n    data.append(1);\n    data.append(-1);\n    data.append(0);\n    data.append(-1);\n    data.append(0);\n    data.append(-3);\n    data.append(2);\n    data.append(-2);\n    data.append(-2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(2);\n    data.append(-1);\n    data.append(2);\n    data.append(-3);\n    data.append(-1);\n    data.append(-1);\n    data.append(-3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse orion::operators::tensor::I8TensorPartialEq;\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_i8_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_0() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-1);\n    data.append(-2);\n    data.append(2);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{I8Tensor, I8TensorMul};\n\nfn input_1() -> Tensor<i8> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(-3);\n    data.append(-1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_i8_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_u32() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(5);\n    data.append(5);\n    data.append(0);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(0);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(3);\n    data.append(1);\n    data.append(0);\n    data.append(1);\n    data.append(5);\n    data.append(0);\n    data.append(5);\n    data.append(2);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(5);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(4);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(3);\n    data.append(0);\n    data.append(0);\n    data.append(4);\n    data.append(4);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(5);\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(5);\n    data.append(4);\n    data.append(3);\n    data.append(4);\n    data.append(2);\n    data.append(4);\n    data.append(5);\n    data.append(4);\n    data.append(2);\n    data.append(1);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n    shape.append(3);\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(0);\n    data.append(0);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::U32TensorPartialEq;\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::utils::{assert_eq, assert_seq_eq};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_or_u32_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.or(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(3);\n    data.append(2);\n    data.append(2);\n    data.append(3);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn input_1() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(0);\n    data.append(5);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/or_u32_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{U32Tensor, U32TensorMul};\n\nfn output_0() -> Tensor<u32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(2);\n    shape.append(2);\n\n    let mut data = ArrayTrait::new();\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    data.append(1);\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_pow_fp16x16() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.pow(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 1769472, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16_broadcast.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::operators::tensor::FP16x16TensorPartialEq;\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_pow_fp16x16_broadcast() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.pow(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16_broadcast/input_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 131072, sign: false });\n    data.append(FP16x16 { mag: 196608, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16_broadcast/input_1.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn input_1() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 131072, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp16x16_broadcast/output_0.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorSub};\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn output_0() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(3);\n\n    let mut data = ArrayTrait::new();\n    data.append(FP16x16 { mag: 65536, sign: false });\n    data.append(FP16x16 { mag: 262144, sign: false });\n    data.append(FP16x16 { mag: 589824, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/nodes/pow_fp8x23.cairo",
        "content": "mod input_0;\nmod input_1;\nmod output_0;\n\n\nuse orion::utils::{assert_eq, assert_seq_eq};\nuse core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP8x23TensorPartialEq;\nuse orion::operators::tensor::{FP8x23Tensor, FP8x23TensorSub};\n\n#[test]\n#[available_gas(2000000000)]\nfn test_pow_fp8x23() {\n    let input_0 = input_0::input_0();\n    let input_1 = input_1::input_1();\n    let z = output_0::output_0();\n\n    let y = input_0.pow(@input_1);\n\n    assert_eq(y, z);\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers.cairo",
        "content": "// mod fixed_point;\nmod complex_number_test;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/complex_number_test.cairo",
        "content": "//use cubit::f128::types::fixed::FixedTrait;\nuse orion::numbers::complex_number::complex_trait::ComplexTrait;\nuse orion::numbers::complex_number::complex64::{TWO, complex64};\nuse orion::numbers::{FP64x64, FP64x64Impl, FixedTrait};\nuse core::debug::PrintTrait;\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_add() {\n    // Test addition of two complex numbers\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(36893488147419103232, false),\n        FixedTrait::<FP64x64>::new(239807672958224171008, false)\n    );\n    let result = a + b;\n    assert(result.real == FixedTrait::<FP64x64>::new(110680464442257309696, false), '4 + 2 = 6');\n    assert(\n        result.img == FixedTrait::<FP64x64>::new(1014570924054025338880, false),\n        '42i + 13i = 55i, b = 55'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_sub() {\n    // Test substraction of two complex numbers\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(36893488147419103232, false),\n        FixedTrait::<FP64x64>::new(239807672958224171008, false)\n    );\n    let result = a - b;\n    assert(result.real == FixedTrait::<FP64x64>::new(36893488147419103232, false), '4 - 2 = 2');\n    assert(\n        result.img == FixedTrait::<FP64x64>::new(534955578137576996864, false),\n        '42i - 13i = 29i, b = 29'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mul() {\n    // Test multiplication of positive integers\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(36893488147419103232, false),\n        FixedTrait::<FP64x64>::new(239807672958224171008, false)\n    );\n    let result = a * b;\n    assert(\n        result.real == FixedTrait::<FP64x64>::new(9924348311655738769408, true),\n        '4*2 - 42*13 = -538'\n    );\n    assert(\n        result.img == FixedTrait::<FP64x64>::new(2508757194024499019776, false),\n        '(4*13 + 2*42)i = 136i, b = 136'\n    );\n\n    // Test multiplication with a pure imaginary number\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(0, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(36893488147419103232, false),\n        FixedTrait::<FP64x64>::new(239807672958224171008, false)\n    );\n    let result = a * b;\n    assert(\n        result.real == FixedTrait::<FP64x64>::new(10071922264245415182336, true),\n        '0*2 - 42*13 = 546'\n    );\n    assert(\n        result.img == FixedTrait::<FP64x64>::new(1549526502191602335744, false),\n        '(0*13 + 2*42)i = 84, b = 84'\n    );\n\n    // Test multiplication by zero\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(FixedTrait::<FP64x64>::new(0, false), FixedTrait::<FP64x64>::new(0, false));\n    let result = a * b;\n    assert(result.real == FixedTrait::<FP64x64>::new(0, false), '0');\n    assert(result.img == FixedTrait::<FP64x64>::new(0, false), '0');\n\n    // Test i * i = -1\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(0, false),\n        FixedTrait::<FP64x64>::new(18446744073709551616, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(0, false),\n        FixedTrait::<FP64x64>::new(18446744073709551616, false)\n    );\n    let result = a * b;\n    assert(result.real == FixedTrait::<FP64x64>::new(18446744073709551616, true), 'i * i = -1');\n    assert(result.img == FixedTrait::<FP64x64>::new(0, false), 'i * i = -1 + 0i');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_div_no_rem() {\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(36893488147419103232, false),\n        FixedTrait::<FP64x64>::new(239807672958224171008, false)\n    );\n    let result = a / b;\n    assert(\n        result.real == FixedTrait::<FP64x64>::new(59072232467254864688, false),\n        'real = 3.2023121387283235'\n    );\n    assert(\n        result.img == FixedTrait::<FP64x64>::new(3412114510743963284, false),\n        'img = 0.18497109826589594j'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_zero() {\n    // Test multiplication by zero\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let b = ComplexTrait::zero();\n    let result = a * b;\n    assert(result.real == FixedTrait::<FP64x64>::new(0, false), 'should be 0');\n    assert(result.img == FixedTrait::<FP64x64>::new(0, false), 'should be 0');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_conjugate() {\n    // Test conjugate of a complex number\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let conjugate = a.conjugate();\n    assert(\n        conjugate.real == FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        'conjugate.real = 4'\n    );\n    assert(\n        conjugate.img == FixedTrait::<FP64x64>::new(774763251095801167872, true),\n        'conjugate.img = -42'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_mag() {\n    // Test mag of a complex number\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    );\n    let mag = a.mag();\n    assert(mag == FixedTrait::new(0x2a30a6de7900000000, false), 'mag = 42.190046219457976');\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_arg() {\n    // Test arg of a complex number\n    let a = ComplexTrait::<\n        complex64\n    >::new(\n        FixedTrait::<FP64x64>::new(73786976294838206464, false),\n        FixedTrait::<FP64x64>::new(774763251095801167872, false)\n    );\n    let arg = a.arg();\n    assert(\n        arg == FixedTrait::<FP64x64>::new(27224496882576083824, false), 'arg = 1.4758446204521403'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_exp() {\n    // Test exp of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    ); // 4 + 42i\n\n    let _z = ComplexTrait::exp(a);\n\n    let _z_expected: complex64 = ComplexTrait::new(\n        FixedTrait::new(402848450095324460000, true), FixedTrait::new(923082101320478400000, true)\n    );\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_exp2() {\n    // Test exp2 of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    ); // 4 + 42i\n\n    let exp2 = a.exp2();\n    assert(\n        exp2.real == FixedTrait::new(197471674372309809080, true), 'exp2.real = -10.70502356986'\n    );\n    assert(exp2.img == FixedTrait::new(219354605088992285353, true), 'exp2.img = -11.89127707');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_sqrt() {\n    // Test square root of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    );\n    let sqrt = a.sqrt();\n    assert(sqrt.real == FixedTrait::new(88650037379463118848, false), 'real = 4.80572815603723');\n    assert(sqrt.img == FixedTrait::new(80608310115317055488, false), 'img = 4.369785247552674');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_ln() {\n    // Test ln of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    );\n    let ln = a.ln();\n    assert(ln.real == FixedTrait::new(69031116512113681970, false), 'ln.real = 3.7421843216430655');\n    assert(ln.img == FixedTrait::new(27224496882576083824, false), 'ln.img = 1.4758446204521403');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_log2() {\n    // Test log2 of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let log2 = a.log2();\n    assert(log2.real == FixedTrait::new(34130530934667840346, false), 'log2.real = 1.85021986');\n    assert(log2.img == FixedTrait::new(26154904847122126193, false), 'log2.img = 1.41787163');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_log10() {\n    // Test log10 of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let log10 = a.log10();\n    assert(\n        log10.real == FixedTrait::new(10274314139629458970, false),\n        'log10.real = 0.5569716761534184'\n    );\n    assert(\n        log10.img == FixedTrait::new(7873411322133748801, false), 'log10.img = 0.42682189085546657'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acos() {\n    // Test acos of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let acos = a.acos();\n    assert(\n        acos.real == FixedTrait::new(18449430688981877061, false), 'acos.real = 1.000143542473797'\n    );\n    assert(acos.img == FixedTrait::new(36587032881711954470, true), 'acos.img = -1.98338702991653');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asin() {\n    // Test asin of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let asin = a.asin();\n    assert(asin.real == FixedTrait::new(10526647143326614308, false), 'asin.real = 0.57065278432');\n    assert(asin.img == FixedTrait::new(36587032881711954470, false), 'asin.img = 1.9833870299');\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_atan() {\n    // Test atan of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let atan = a.atan();\n    assert(atan.real == FixedTrait::new(26008453796191787243, false), 'atan.real = 1.40992104959');\n    assert(atan.img == FixedTrait::new(4225645162986888119, false), 'atan.img = 0.229072682968538');\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cos() {\n    // Test cos of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let cos = a.cos();\n    assert(\n        cos.real == FixedTrait::new(77284883172661882094, true), 'cos.real = -4.189625690968807'\n    );\n    assert(cos.img == FixedTrait::new(168035443352962049425, true), 'cos.img = -9.109227893755337');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_sin() {\n    // Test sin of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let sin = a.sin();\n    assert(\n        sin.real == FixedTrait::new(168870549816927860082, false), 'sin.real = 9.15449914691143'\n    );\n    assert(sin.img == FixedTrait::new(76902690389051588309, true), 'sin.img = -4.168906959966565');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_tan() {\n    // Test tan of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n\n    let tan = a.tan();\n    assert(tan.real == FixedTrait::new(69433898428143694, true), 'tan.real = -0.003764025641');\n    assert(tan.img == FixedTrait::new(18506486100303669886, false), 'tan.img = 1.00323862735361');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_acosh() {\n    // Test acosh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let acosh = a.acosh();\n    assert(acosh.real == FixedTrait::new(36587032878947915965, false), 'acosh.real = 1.9833870');\n    assert(acosh.img == FixedTrait::new(18449360714192945790, false), 'acosh.img = 1.0001435424');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_asinh() {\n    // Test asinh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let asinh = a.asinh();\n    assert(\n        asinh.real == FixedTrait::new(36314960239770126586, false), 'asinh.real = 1.96863792579'\n    );\n    assert(asinh.img == FixedTrait::new(17794714057579789616, false), 'asinh.img = 0.96465850440');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_atanh() {\n    // Test atanh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let atanh = a.atanh();\n    assert(\n        atanh.real == FixedTrait::new(2710687792925618924, false), 'atanh.real = 0.146946666225'\n    );\n    assert(atanh.img == FixedTrait::new(24699666646262346226, false), 'atanh.img = 1.3389725222');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_cosh() {\n    // Test cosh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let cosh = a.cosh();\n    assert(cosh.real == FixedTrait::new(68705646899632870392, true), 'cosh.real = -3.72454550491');\n    assert(cosh.img == FixedTrait::new(9441447324287988702, false), 'cosh.img = 0.511822569987');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_sinh() {\n    // Test sinh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let sinh = a.sinh();\n    assert(sinh.real == FixedTrait::new(66234138518106676624, true), 'sinh.real = -3.59056458998');\n    assert(sinh.img == FixedTrait::new(9793752294470951790, false), 'sinh.img = 0.530921086');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_tanh() {\n    // Test tanh of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(55340232221128654848, false)\n    );\n    let tanh = a.tanh();\n    assert(tanh.real == FixedTrait::new(17808227710002974080, false), 'tanh.real = 0.96538587902');\n    assert(tanh.img == FixedTrait::new(182334107030204896, true), 'tanh.img = 0.009884375');\n}\n\n\n#[test]\n#[available_gas(2000000000)]\nfn test_pow() {\n    // Test pow with exp = 2\n    let two = ComplexTrait::new(FP64x64Impl::new(TWO, false), FP64x64Impl::new(0, false));\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    );\n\n    let pow = a.pow(two);\n    assert(pow.real == FixedTrait::new(32244908640844296224768, true), 'pow.real = -1748');\n    assert(pow.img == FixedTrait::new(6198106008766409342976, false), 'pow.img = 336');\n\n    // Test pow with exp = n, int\n    let three: complex64 = ComplexTrait::new(\n        FP64x64Impl::new(55340232221128654848, false), FP64x64Impl::new(0, false)\n    );\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    );\n\n    let pow = a.pow(three);\n    assert(pow.real == FixedTrait::new(389305023520047451076807, true), 'pow.real = -21104');\n    assert(pow.img == FixedTrait::new(1329485652886846033475029, true), 'pow.img = 72072');\n\n    // Test pow with exp = w, complex\n    let w: complex64 = ComplexTrait::new(\n        FixedTrait::new(36893488147419103232, false), FixedTrait::new(18446744073709551616, false)\n    ); // 2 + i\n\n    let pow = a.pow(w);\n    assert(\n        pow.real == FixedTrait::new(6881545343236111419203, false), 'pow.real = 373.0485407816205'\n    );\n    assert(\n        pow.img == FixedTrait::new(2996539405459717736042, false), 'pow.img = 162.4438823807959'\n    );\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_to_polar() {\n    // Test to polar coordinates of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    ); // 4 + 42i\n    let (mag, arg) = a.to_polar();\n\n    assert(mag == FixedTrait::new(778268985067028086784, false), 'mag = 42.190046219457976');\n    assert(arg == FixedTrait::new(27224496882576083824, false), 'arg = 1.4758446204521403');\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_from_polar() {\n    // Test from polar coordiantes of a complex number\n    let mag: FP64x64 = FixedTrait::new(778268985067028086784, false); // 42.190046219457976\n    let arg: FP64x64 = FixedTrait::new(27224496882576083824, false); //1.4758446204521403\n    let z_actual: complex64 = ComplexTrait::from_polar(mag, arg);\n\n    let z_expected: complex64 = ComplexTrait::new(\n        FixedTrait::new(73787936714814843012, false), FixedTrait::new(774759489569697723777, false)\n    );\n\n    assert(z_actual == z_expected, 'wrong number');\n}\n\n#[test]\n#[available_gas(2000000000)]\nfn test_reciprocal() {\n    // Test from polar coordiantes of a complex number\n    let a: complex64 = ComplexTrait::new(\n        FixedTrait::new(73786976294838206464, false), FixedTrait::new(774763251095801167872, false)\n    ); // 4 + 42i\n\n    let z_actual = a.reciprocal();\n\n    let z_expected: complex64 = ComplexTrait::new(\n        FixedTrait::new(41453357469010228, false), FixedTrait::new(435260253424607397, true)\n    );\n    assert(z_actual == z_expected, '0.002247191011 - 0.0235955056 i');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test.cairo",
        "content": "mod erf_fp16x16_test;\nmod erf_fp16x16wide_test;\nmod erf_fp8x23_test;\nmod erf_fp8x23wide_test;\nmod erf_fp32x32_test;\nmod erf_fp64x64_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp16x16_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16::math::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{ONE, FP16x16, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP16x16 = FP16x16 { mag: 65536, sign: false };\n    // 0.134\n    let f2: FP16x16 = FP16x16 { mag: 8832, sign: false };\n    // 0.520\n    let f3: FP16x16 = FP16x16 { mag: 34078, sign: false };\n    // 2.0\n    let f4: FP16x16 = FP16x16 { mag: 131072, sign: false };\n    // 3.5\n    let f5: FP16x16 = FP16x16 { mag: 229376, sign: false };\n    // 5.164\n    let f6: FP16x16 = FP16x16 { mag: 338428, sign: false };\n\n    let f1_erf: FP16x16 = erf(f1);\n    let f2_erf: FP16x16 = erf(f2);\n    let f3_erf: FP16x16 = erf(f3);\n    let f4_erf: FP16x16 = erf(f4);\n    let f5_erf: FP16x16 = erf(f5);\n    let f6_erf: FP16x16 = erf(f6);\n\n    assert(f1_erf.mag == 55227, 'f1_erf it works!');\n    assert(f2_erf.mag == 10285, 'f2_erf it works!');\n    assert(f3_erf.mag == 35251, 'f3_erf it works!');\n    assert(f4_erf.mag == 65229, 'f4_erf it works!');\n    assert(f5_erf.mag == 65536, 'f5_erf it works!');\n    assert(f6_erf.mag == 65536, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp16x16wide_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp16x16wide::math::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp16x16wide::core::{ONE, FP16x16W, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP16x16W = FP16x16W { mag: 65536, sign: false };\n    // 0.134\n    let f2: FP16x16W = FP16x16W { mag: 8832, sign: false };\n    // 0.520\n    let f3: FP16x16W = FP16x16W { mag: 34078, sign: false };\n    // 2.0\n    let f4: FP16x16W = FP16x16W { mag: 131072, sign: false };\n    // 3.5\n    let f5: FP16x16W = FP16x16W { mag: 229376, sign: false };\n    // 5.164\n    let f6: FP16x16W = FP16x16W { mag: 338428, sign: false };\n\n    let f1_erf: FP16x16W = erf(f1);\n    let f2_erf: FP16x16W = erf(f2);\n    let f3_erf: FP16x16W = erf(f3);\n    let f4_erf: FP16x16W = erf(f4);\n    let f5_erf: FP16x16W = erf(f5);\n    let f6_erf: FP16x16W = erf(f6);\n\n    assert(f1_erf.mag == 55227, 'f1_erf it works!');\n    assert(f2_erf.mag == 10285, 'f2_erf it works!');\n    assert(f3_erf.mag == 35251, 'f3_erf it works!');\n    assert(f4_erf.mag == 65229, 'f4_erf it works!');\n    assert(f5_erf.mag == 65536, 'f5_erf it works!');\n    assert(f6_erf.mag == 65536, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp32x32_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp32x32::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp32x32::core::{ONE, FP32x32, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP32x32 = FP32x32 { mag: 4294967296, sign: false };\n    // 0.134\n    let f2: FP32x32 = FP32x32 { mag: 575525618, sign: false };\n    // 0.520\n    let f3: FP32x32 = FP32x32 { mag: 2233382993, sign: false };\n    // 2.0\n    let f4: FP32x32 = FP32x32 { mag: 8589934592, sign: false };\n    // 3.5\n    let f5: FP32x32 = FP32x32 { mag: 15032385536, sign: false };\n    // 5.164\n    let f6: FP32x32 = FP32x32 { mag: 22179211117, sign: false };\n\n    let f1_erf: FP32x32 = erf(f1);\n    let f2_erf: FP32x32 = erf(f2);\n    let f3_erf: FP32x32 = erf(f3);\n    let f4_erf: FP32x32 = erf(f4);\n    let f5_erf: FP32x32 = erf(f5);\n    let f6_erf: FP32x32 = erf(f6);\n    assert(f1_erf.mag == 3619372346, 'f1_erf it works!');\n    assert(f2_erf.mag == 674082374, 'f2_erf it works!');\n    assert(f3_erf.mag == 2310257026, 'f3_erf it works!');\n    assert(f4_erf.mag == 4274876577, 'f4_erf it works!');\n    assert(f5_erf.mag == 4294967296, 'f5_erf it works!');\n    assert(f6_erf.mag == 4294967296, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp64x64_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp64x64::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp64x64::core::{ONE, FP64x64, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP64x64 = FP64x64 { mag: 18446744073709551616_u128, sign: false };\n    // 0.134\n    let f2: FP64x64 = FP64x64 { mag: 2471863705877080064_u128, sign: false };\n    // 0.520\n    let f3: FP64x64 = FP64x64 { mag: 9592306918328967168_u128, sign: false };\n    // 2.0\n    let f4: FP64x64 = FP64x64 { mag: 36893488147419103232_u128, sign: false };\n    // 3.5\n    let f5: FP64x64 = FP64x64 { mag: 64563604257983430656_u128, sign: false };\n    // 5.164\n    let f6: FP64x64 = FP64x64 { mag: 95258986396636119040_u128, sign: false };\n\n    let f1_erf: FP64x64 = erf(f1);\n    let f2_erf: FP64x64 = erf(f2);\n    let f3_erf: FP64x64 = erf(f3);\n    let f4_erf: FP64x64 = erf(f4);\n    let f5_erf: FP64x64 = erf(f5);\n    let f6_erf: FP64x64 = erf(f6);\n    assert(f1_erf.mag == 15545085858255493120_u128, 'f1_erf it works!');\n    assert(f2_erf.mag == 2895161752038532608_u128, 'f2_erf it works!');\n    assert(f3_erf.mag == 9922478374042292224_u128, 'f3_erf it works!');\n    assert(f4_erf.mag == 18360455093669533696_u128, 'f4_erf it works!');\n    assert(f5_erf.mag == 18446744073709551616_u128, 'f5_erf it works!');\n    assert(f6_erf.mag == 18446744073709551616_u128, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp8x23_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23::math::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp8x23::core::{ONE, FP8x23, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP8x23 = FP8x23 { mag: 8388608, sign: false };\n    // 0.134\n    let f2: FP8x23 = FP8x23 { mag: 1124073, sign: false };\n    // 0.520\n    let f3: FP8x23 = FP8x23 { mag: 4362076, sign: false };\n    // 2.0\n    let f4: FP8x23 = FP8x23 { mag: 16777216, sign: false };\n    // 3.5\n    let f5: FP8x23 = FP8x23 { mag: 29360128, sign: false };\n    // 5.164\n    let f6: FP8x23 = FP8x23 { mag: 43318772, sign: false };\n\n    let f1_erf: FP8x23 = erf(f1);\n    let f2_erf: FP8x23 = erf(f2);\n    let f3_erf: FP8x23 = erf(f3);\n    let f4_erf: FP8x23 = erf(f4);\n    let f5_erf: FP8x23 = erf(f5);\n    let f6_erf: FP8x23 = erf(f6);\n\n    assert(f1_erf.mag == 7069086, 'f1_erf it works!');\n    assert(f2_erf.mag == 1316567, 'f2_erf it works!');\n    assert(f3_erf.mag == 4512220, 'f3_erf it works!');\n    assert(f4_erf.mag == 8349368, 'f4_erf it works!');\n    assert(f5_erf.mag == 8388608, 'f5_erf it works!');\n    assert(f6_erf.mag == 8388608, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/numbers/fixed_point_test/erf_fp8x23wide_test.cairo",
        "content": "use orion::numbers::fixed_point::implementations::fp8x23wide::math::erf::erf;\nuse orion::numbers::fixed_point::implementations::fp8x23wide::core::{ONE, FP8x23W, FixedTrait};\nuse core::debug::PrintTrait;\n#[test]\n#[available_gas(1000000000)]\nfn test_erf() {\n    // 1.0\n    let f1: FP8x23W = FP8x23W { mag: 8388608, sign: false };\n    // 0.134\n    let f2: FP8x23W = FP8x23W { mag: 1124073, sign: false };\n    // 0.520\n    let f3: FP8x23W = FP8x23W { mag: 4362076, sign: false };\n    // 2.0\n    let f4: FP8x23W = FP8x23W { mag: 16777216, sign: false };\n    // 3.5\n    let f5: FP8x23W = FP8x23W { mag: 29360128, sign: false };\n    // 5.164\n    let f6: FP8x23W = FP8x23W { mag: 43318772, sign: false };\n\n    let f1_erf: FP8x23W = erf(f1);\n    let f2_erf: FP8x23W = erf(f2);\n    let f3_erf: FP8x23W = erf(f3);\n    let f4_erf: FP8x23W = erf(f4);\n    let f5_erf: FP8x23W = erf(f5);\n    let f6_erf: FP8x23W = erf(f6);\n\n    assert(f1_erf.mag == 7069086, 'f1_erf it works!');\n    assert(f2_erf.mag == 1316567, 'f2_erf it works!');\n    assert(f3_erf.mag == 4512220, 'f3_erf it works!');\n    assert(f4_erf.mag == 8349368, 'f4_erf it works!');\n    assert(f5_erf.mag == 8388608, 'f5_erf it works!');\n    assert(f6_erf.mag == 8388608, 'f6_erf it works!');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators.cairo",
        "content": "mod transpose_test;\nmod qlinear_matmul_test;\nmod qlinear_concat_test;\nmod qlinear_add_test;\nmod constant_of_shape_test;\nmod qlinear_leakyrelu_test;\nmod optional;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/constant_of_shape_test.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\nuse core::debug::PrintTrait;\n\n\n#[test]\n#[available_gas(200000000000)]\nfn constant_of_shape_test() {\n    let tensor = TensorTrait::<u32>::constant_of_shape(shape: array![4, 2].span(), value: 20);\n\n    assert(tensor.shape == array![4, 2].span(), 'wrong dim');\n    assert(tensor.data == array![20, 20, 20, 20, 20, 20, 20, 20].span(), 'wrong values');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/optional.cairo",
        "content": "mod optional_test;\nmod optional_has_element_test;\nmod optional_get_element_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/optional/optional_get_element_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse core::option::OptionTrait;\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::helpers::{optional_has_element, optional_get_element};\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_get_element_i8_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let ele = optional_get_element(a.optional());\n\n    assert(*(ele.data).at(0) == *(a.data).at(0), 'ele[0] == a[0]');\n    assert(*(ele.data).at(1) == *(a.data).at(1), 'ele[1] == a[1]');\n    assert(*(ele.data).at(2) == *(a.data).at(2), 'ele[2] == a[2]');\n    assert(*(ele.data).at(3) == *(a.data).at(3), 'ele[3] == a[3]');\n    assert(*(ele.data).at(4) == *(a.data).at(4), 'ele[4] == a[4]');\n    assert(*(ele.data).at(5) == *(a.data).at(5), 'ele[5] == a[5]');\n    assert(*(ele.data).at(6) == *(a.data).at(6), 'ele[6] == a[6]');\n    assert(*(ele.data).at(7) == *(a.data).at(7), 'ele[7] == a[7]');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_get_element_fp16x16_test() {\n    let a = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![\n            FixedTrait::<FP16x16>::new_unscaled(1, false),\n            FixedTrait::<FP16x16>::new_unscaled(2, false),\n            FixedTrait::<FP16x16>::new_unscaled(3, false),\n            FixedTrait::<FP16x16>::new_unscaled(4, false),\n            FixedTrait::<FP16x16>::new_unscaled(5, false),\n            FixedTrait::<FP16x16>::new_unscaled(6, false),\n            FixedTrait::<FP16x16>::new_unscaled(7, false),\n            FixedTrait::<FP16x16>::new_unscaled(8, false)\n        ]\n            .span(),\n    );\n    let ele = optional_get_element(a.optional());\n\n    assert(*(ele.data).at(0) == *(a.data).at(0), 'ele[0] == a[0]');\n    assert(*(ele.data).at(1) == *(a.data).at(1), 'ele[1] == a[1]');\n    assert(*(ele.data).at(2) == *(a.data).at(2), 'ele[2] == a[2]');\n    assert(*(ele.data).at(3) == *(a.data).at(3), 'ele[3] == a[3]');\n    assert(*(ele.data).at(4) == *(a.data).at(4), 'ele[4] == a[4]');\n    assert(*(ele.data).at(5) == *(a.data).at(5), 'ele[5] == a[5]');\n    assert(*(ele.data).at(6) == *(a.data).at(6), 'ele[6] == a[6]');\n    assert(*(ele.data).at(7) == *(a.data).at(7), 'ele[7] == a[7]');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/optional/optional_has_element_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse core::option::OptionTrait;\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::helpers::{optional_has_element, optional_get_element};\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_has_element_i8_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let a_optional = a.optional();\n    let has_ele = optional_has_element(a_optional);\n\n    assert(*(has_ele.data).at(0) == true, 'has_ele[0] == true');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_has_element_fp16x16_test() {\n    let a = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![\n            FixedTrait::<FP16x16>::new_unscaled(1, false),\n            FixedTrait::<FP16x16>::new_unscaled(2, false),\n            FixedTrait::<FP16x16>::new_unscaled(3, false),\n            FixedTrait::<FP16x16>::new_unscaled(4, false),\n            FixedTrait::<FP16x16>::new_unscaled(5, false),\n            FixedTrait::<FP16x16>::new_unscaled(6, false),\n            FixedTrait::<FP16x16>::new_unscaled(7, false),\n            FixedTrait::<FP16x16>::new_unscaled(8, false)\n        ]\n            .span(),\n    );\n    let a_optional = a.optional();\n    let has_ele = optional_has_element(a_optional);\n\n    assert(*(has_ele.data).at(0) == true, 'has_ele[0] == true');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_has_element_none_test() {\n    let a: Option<Tensor<u32>> = Option::None(());\n    let has_ele = optional_has_element(a);\n\n    assert(*(has_ele.data).at(0) == false, 'has_ele[0] == false');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/optional/optional_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\nuse core::option::OptionTrait;\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\nuse orion::operators::tensor::helpers::{optional_has_element, optional_get_element};\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_i8_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let a_optional = a.optional();\n\n    assert(\n        *(optional_get_element(a_optional).data).at(0) == *(a.data).at(0),\n        'a_optional[0] == Option(a)[0]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(1) == *(a.data).at(1),\n        'a_optional[1] == Option(a)[1]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(2) == *(a.data).at(2),\n        'a_optional[2] == Option(a)[2]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(3) == *(a.data).at(3),\n        'a_optional[3] == Option(a)[3]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(4) == *(a.data).at(4),\n        'a_optional[4] == Option(a)[4]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(5) == *(a.data).at(5),\n        'a_optional[5] == Option(a)[5]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(6) == *(a.data).at(6),\n        'a_optional[6] == Option(a)[6]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(7) == *(a.data).at(7),\n        'a_optional[7] == Option(a)[7]'\n    );\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn optional_fp16x16_test() {\n    let a = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![\n            FixedTrait::<FP16x16>::new_unscaled(1, false),\n            FixedTrait::<FP16x16>::new_unscaled(2, false),\n            FixedTrait::<FP16x16>::new_unscaled(3, false),\n            FixedTrait::<FP16x16>::new_unscaled(4, false),\n            FixedTrait::<FP16x16>::new_unscaled(5, false),\n            FixedTrait::<FP16x16>::new_unscaled(6, false),\n            FixedTrait::<FP16x16>::new_unscaled(7, false),\n            FixedTrait::<FP16x16>::new_unscaled(8, false)\n        ]\n            .span(),\n    );\n    let a_optional = a.optional();\n\n    assert(\n        *(optional_get_element(a_optional).data).at(0) == *(a.data).at(0),\n        'a_optional[0] == Option(a)[0]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(1) == *(a.data).at(1),\n        'a_optional[1] == Option(a)[1]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(2) == *(a.data).at(2),\n        'a_optional[2] == Option(a)[2]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(3) == *(a.data).at(3),\n        'a_optional[3] == Option(a)[3]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(4) == *(a.data).at(4),\n        'a_optional[4] == Option(a)[4]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(5) == *(a.data).at(5),\n        'a_optional[5] == Option(a)[5]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(6) == *(a.data).at(6),\n        'a_optional[6] == Option(a)[6]'\n    );\n    assert(\n        *(optional_get_element(a_optional).data).at(7) == *(a.data).at(7),\n        'a_optional[7] == Option(a)[7]'\n    );\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/qlinear_add_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinearadd_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 2].span(),\n        data: array![2_i8, 4_i8, 6_i8, 8_i8, 10_i8, 12_i8, 14_i8, 16_i8].span(),\n    );\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(20000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(25000, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(30000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_add(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n\n    assert((*actual_output.data[0]).into() == 2, '*result[0] == 2');\n    assert((*actual_output.data[1]).into() == 4, '*result[1] == 4');\n    assert((*actual_output.data[2]).into() == 7, '*result[2] == 7');\n    assert((*actual_output.data[3]).into() == 9, '*result[3] == 9');\n    assert((*actual_output.data[4]).into() == 11, '*result[4] == 11');\n    assert((*actual_output.data[5]).into() == 14, '*result[5] == 14');\n    assert((*actual_output.data[6]).into() == 16, '*result[6] == 16');\n    assert((*actual_output.data[7]).into() == 18, '*result[7] == 18');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinearadd_broadcast_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 4].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(shape: array![1, 4].span(), data: array![2_i8, 4_i8, 6_i8, 8_i8,].span(),);\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(20000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(25000, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(30000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_add(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n\n    assert((*actual_output.data[0]).into() == 2, '*result[0] == 2');\n    assert((*actual_output.data[1]).into() == 4, '*result[1] == 4');\n    assert((*actual_output.data[2]).into() == 7, '*result[2] == 7');\n    assert((*actual_output.data[3]).into() == 9, '*result[3] == 9');\n    assert((*actual_output.data[4]).into() == 5, '*result[4] == 5');\n    assert((*actual_output.data[5]).into() == 7, '*result[5] == 7');\n    assert((*actual_output.data[6]).into() == 9, '*result[6] == 9');\n    assert((*actual_output.data[7]).into() == 12, '*result[7] == 12');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_example_doc() {\n    let a = TensorTrait::<\n        i8\n    >::new(shape: array![2, 3].span(), data: array![6_i8, 6_i8, 6_i8, 11_i8, 11_i8, 11_i8].span(),);\n    let b = TensorTrait::<\n        i8\n    >::new(shape: array![1, 3].span(), data: array![40_i8, 40_i8, 40_i8].span(),);\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),\n    );\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, true)].span(),);\n\n    let actual_output = a\n        .qlinear_add(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n    assert((*actual_output.data[0]).into() == 1, '*result[0] == 1');\n    assert((*actual_output.data[1]).into() == 1, '*result[1] == 1');\n    assert((*actual_output.data[2]).into() == 1, '*result[2] == 1');\n    assert((*actual_output.data[3]).into() == 2, '*result[3] == 2');\n    assert((*actual_output.data[4]).into() == 2, '*result[4] == 2');\n    assert((*actual_output.data[5]).into() == 2, '*result[5] == 2');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/qlinear_concat_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\nfn print_span(mut span: Span<i8>) {\n    loop {\n        match span.pop_front() {\n            Option::Some(i) => { (*i).print(); },\n            Option::None => { break; }\n        };\n    };\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinear_concat_test() {\n    let tensor1 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![10_i8, 20_i8, 30_i8, 40_i8,].span(),);\n    let tensor2 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![20_i8, 40_i8, 60_i8, 80_i8,].span(),);\n\n    let tensors = array![tensor1, tensor2].span();\n\n    let tensor1_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(20000, false)].span(),);\n    let tensor2_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(25000, false)].span(),);\n\n    let scales = array![tensor1_scale, tensor2_scale].span();\n\n    let tensor1_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let tensor2_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let zero_points = array![tensor1_zero_point, tensor2_zero_point].span();\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = TensorTrait::qlinear_concat(\n        tensors, scales, zero_points, @y_scale, @y_zero_point, 0\n    );\n\n    assert((*actual_output.data[0]).into() == 3, '*result[0] == 3');\n    assert((*actual_output.data[1]).into() == 6, '*result[1] == 6');\n    assert((*actual_output.data[2]).into() == 9, '*result[2] == 9');\n    assert((*actual_output.data[3]).into() == 12, '*result[3] == 12');\n    assert((*actual_output.data[4]).into() == 7, '*result[4] == 8');\n    assert((*actual_output.data[5]).into() == 15, '*result[5] == 15');\n    assert((*actual_output.data[6]).into() == 22, '*result[6] == 22');\n    assert((*actual_output.data[7]).into() == 30, '*result[7] == 30');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinear_concat_test_shape() {\n    let tensor1 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![2_i8, 2_i8, 2_i8, 2_i8,].span(),);\n    let tensor2 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![8_i8, 8_i8, 8_i8, 8_i8,].span(),);\n    let tensor3 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![10_i8, 10_i8, 10_i8, 10_i8,].span(),);\n\n    let tensors = array![tensor1, tensor2, tensor3].span();\n\n    let tensor1_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let tensor2_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(262144, false)].span(),\n    );\n    let tensor3_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n\n    let scales = array![tensor1_scale, tensor2_scale, tensor3_scale].span();\n\n    let tensor1_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    let tensor2_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    let tensor3_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n\n    let zero_points = array![tensor1_zero_point, tensor2_zero_point, tensor3_zero_point].span();\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(30000, false)].span(),);\n\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = TensorTrait::qlinear_concat(\n        tensors, scales, zero_points, @y_scale, @y_zero_point, 0\n    );\n\n    assert((*actual_output.shape[0]).into() == 6, '*result.shape[0] == 6');\n    assert((*actual_output.shape[1]).into() == 2, '*result.shape[1] == 2');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinear_concat_example_doc() {\n    let tensor1 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![5_i8, 5_i8, 5_i8, 5_i8,].span(),);\n    let tensor2 = TensorTrait::<\n        i8\n    >::new(shape: array![2, 2].span(), data: array![1_i8, 1_i8, 1_i8, 1_i8,].span(),);\n\n    let tensors = array![tensor1, tensor2].span();\n\n    let tensor1_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let tensor2_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(262144, false)].span(),\n    );\n\n    let scales = array![tensor1_scale, tensor2_scale].span();\n\n    let tensor1_zero_point = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(327680, false)].span(),\n    );\n    let tensor2_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let zero_points = array![tensor1_zero_point, tensor2_zero_point].span();\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(262144, false)].span(),\n    );\n\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n\n    let actual_output = TensorTrait::qlinear_concat(\n        tensors, scales, zero_points, @y_scale, @y_zero_point, 0\n    );\n\n    assert((*actual_output.data[0]).into() == 1, '*result[0] == 1');\n    assert((*actual_output.data[1]).into() == 1, '*result[1] == 1');\n    assert((*actual_output.data[2]).into() == 1, '*result[2] == 1');\n    assert((*actual_output.data[3]).into() == 1, '*result[3] == 1');\n    assert((*actual_output.data[4]).into() == 2, '*result[4] == 2');\n    assert((*actual_output.data[5]).into() == 2, '*result[5] == 2');\n    assert((*actual_output.data[6]).into() == 2, '*result[4] == 2');\n    assert((*actual_output.data[7]).into() == 2, '*result[5] == 2');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/qlinear_leakyrelu_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\n\nuse orion::operators::tensor::{TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinear_leakyrelu_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 3].span(),\n        data: array![-10_i8, -10_i8, -10_i8, 10_i8, 10_i8, 10_i8].span(),\n    );\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n\n    let alpha = FixedTrait::<FP16x16>::new(655360, false);\n\n    let actual_output = a.qlinear_leakyrelu(@a_scale, @a_zero_point, alpha);\n\n    assert((*actual_output.data[0]).abs().into() == 118, '*result[0] == 118');\n    assert((*actual_output.data[1]).abs().into() == 118, '*result[1] == 118');\n    assert((*actual_output.data[2]).abs().into() == 118, '*result[2] == 118');\n    assert((*actual_output.data[3]).into() == 10, '*result[3] == 10');\n    assert((*actual_output.data[4]).into() == 10, '*result[4] == 10');\n    assert((*actual_output.data[5]).into() == 10, '*result[5] == 10');\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/qlinear_matmul_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\n\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, FP32x32Tensor\n};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinearmatmul_2D_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 4].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 3].span(),\n        data: array![2_i8, 4_i8, 6_i8, 8_i8, 10_i8, 12_i8, 14_i8, 16_i8, 18_i8, 20_i8, 22_i8, 24_i8]\n            .span(),\n    );\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(2000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(2500, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(3000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_matmul(\n            @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n        );\n\n    assert((*actual_output.data[0]).into() == 3, '*result[0] == 3');\n    assert((*actual_output.data[1]).into() == 4, '*result[1] == 4');\n    assert((*actual_output.data[2]).into() == 4, '*result[2] == 4');\n    assert((*actual_output.data[3]).into() == 8, '*result[3] == 8');\n    assert((*actual_output.data[4]).into() == 9, '*result[4] == 9');\n    assert((*actual_output.data[5]).into() == 10, '*result[5] == 10');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinearmatmul_3D_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 2, 3].span(),\n        data: array![\n            -1_i8, -2_i8, -2_i8, -3_i8, -4_i8, -4_i8, -5_i8, -6_i8, -6_i8, -7_i8, -8_i8, -8_i8\n        ]\n            .span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 3, 2].span(),\n        data: array![\n            -2_i8, -4_i8, -6_i8, -8_i8, -10_i8, -12_i8, -2_i8, -4_i8, -6_i8, -8_i8, -10_i8, -12_i8\n        ]\n            .span(),\n    );\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(20000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(25000, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(30000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_matmul(\n            @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n        );\n\n    assert((*actual_output.data[0]).into() == 8, '*result[0] == 8');\n    assert((*actual_output.data[1]).into() == 11, '*result[1] == 11');\n    assert((*actual_output.data[2]).into() == 17, '*result[2] == 17');\n    assert((*actual_output.data[3]).into() == 23, '*result[3] == 23');\n    assert((*actual_output.data[4]).into() == 26, '*result[4] == 26');\n    assert((*actual_output.data[5]).into() == 35, '*result[5] == 35');\n    assert((*actual_output.data[6]).into() == 36, '*result[6] == 36');\n    assert((*actual_output.data[7]).into() == 47, '*result[7] == 47');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_example_doc() {\n    let a = TensorTrait::<\n        i8\n    >::new(shape: array![2, 3].span(), data: array![3_i8, 4_i8, 5_i8, 2_i8, 4_i8, 3_i8].span(),);\n    let b = TensorTrait::<\n        i8\n    >::new(shape: array![3, 1].span(), data: array![4_i8, 8_i8, 4_i8].span(),);\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(393216, false)].span(),\n    );\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),\n    );\n\n    let actual_output = a\n        .qlinear_matmul(\n            @a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point\n        );\n\n    assert((*actual_output.data[0]).into() == 14, '*result[0] == 14');\n    assert((*actual_output.data[1]).into() == 13, '*result[1] == 13');\n}\n\nfn print_span(mut span: Span<i8>) {\n    loop {\n        match span.pop_front() {\n            Option::Some(i) => { (*i).print(); },\n            Option::None => { break; }\n        };\n    };\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/qlinear_mul_test.cairo",
        "content": "use core::debug::PrintTrait;\nuse core::array::{ArrayTrait, SpanTrait};\n\nuse orion::operators::tensor::{\n    TensorTrait, Tensor, I8Tensor, I32Tensor, U32Tensor, FP16x16Tensor, FP32x32Tensor\n};\nuse orion::numbers::{FP16x16, FP16x16Impl, FP32x32, FP32x32Impl, FixedTrait};\nuse orion::numbers::{NumberTrait};\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinearmul_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 3].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8, 9_i8, 10_i8, 11_i8, 12_i8]\n            .span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(\n        shape: array![4, 3].span(),\n        data: array![2_i8, 4_i8, 6_i8, 8_i8, 10_i8, 12_i8, 14_i8, 16_i8, 18_i8, 20_i8, 22_i8, 24_i8]\n            .span(),\n    );\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(2000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(2500, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(3000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_mul(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n\n    assert((*actual_output.data[0]).into() == 0, '*result[0] == 0');\n    assert((*actual_output.data[1]).into() == 0, '*result[1] == 0');\n    assert((*actual_output.data[2]).into() == 0, '*result[2] == 0');\n    assert((*actual_output.data[3]).into() == 0, '*result[3] == 0');\n    assert((*actual_output.data[4]).into() == 1, '*result[4] == 1');\n    assert((*actual_output.data[5]).into() == 1, '*result[5] == 1');\n    assert((*actual_output.data[6]).into() == 2, '*result[6] == 2');\n    assert((*actual_output.data[7]).into() == 3, '*result[7] == 3');\n    assert((*actual_output.data[8]).into() == 4, '*result[8] == 4');\n    assert((*actual_output.data[9]).into() == 5, '*result[9] == 5');\n    assert((*actual_output.data[10]).into() == 6, '*result[10] == 6');\n    assert((*actual_output.data[11]).into() == 7, '*result[11] == 7');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn qlinear_mul_broadcast_test() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 4].span(),\n        data: array![1_i8, 2_i8, 3_i8, 4_i8, 5_i8, 6_i8, 7_i8, 8_i8].span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(shape: array![1, 4].span(), data: array![2_i8, 4_i8, 6_i8, 8_i8,].span(),);\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(20000, false)].span(),);\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(25000, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(30000, false)].span(),);\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let actual_output = a\n        .qlinear_mul(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n\n    assert((*actual_output.data[0]).into() == 0, '*result[0] == 0');\n    assert((*actual_output.data[1]).into() == 2, '*result[1] == 2');\n    assert((*actual_output.data[2]).into() == 4, '*result[2] == 4');\n    assert((*actual_output.data[3]).into() == 8, '*result[3] == 8');\n    assert((*actual_output.data[4]).into() == 2, '*result[4] == 2');\n    assert((*actual_output.data[5]).into() == 6, '*result[5] == 6');\n    assert((*actual_output.data[6]).into() == 10, '*result[6] == 10');\n    assert((*actual_output.data[7]).into() == 16, '*result[7] == 16');\n}\n\n\n#[test]\n#[available_gas(200000000000)]\nfn test_example_doc() {\n    let a = TensorTrait::<\n        i8\n    >::new(\n        shape: array![2, 3].span(), data: array![21_i8, 21_i8, 21_i8, 41_i8, 41_i8, 41_i8].span(),\n    );\n    let b = TensorTrait::<\n        i8\n    >::new(shape: array![1, 3].span(), data: array![4_i8, 8_i8, 12_i8].span(),);\n\n    let a_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(131072, false)].span(),\n    );\n    let a_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(65536, false)].span(),);\n    let b_scale = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(16384, false)].span(),);\n    let b_zero_point = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(0, false)].span(),);\n\n    let y_scale = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(393216, false)].span(),\n    );\n    let y_zero_point = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![1].span(), data: array![FixedTrait::<FP16x16>::new(655360, false)].span(),\n    );\n\n    let actual_output = a\n        .qlinear_mul(@a_scale, @a_zero_point, @b, @b_scale, @b_zero_point, @y_scale, @y_zero_point);\n\n    assert((*actual_output.data[0]).into() == 16, '*result[0] == 16');\n    assert((*actual_output.data[1]).into() == 23, '*result[1] == 23');\n    assert((*actual_output.data[2]).into() == 30, '*result[2] == 30');\n    assert((*actual_output.data[3]).into() == 23, '*result[3] == 23');\n    assert((*actual_output.data[4]).into() == 36, '*result[4] == 36');\n    assert((*actual_output.data[5]).into() == 50, '*result[5] == 50');\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/tensor/math.cairo",
        "content": "mod argmax;\nmod argmin;\nmod max;\nmod min;\nmod reduce_sum;\nmod exp;\nmod equal;\nmod greater;\nmod greater_equal;\nmod less;\nmod less_equal;\nmod abs;\nmod ceil;\nmod ln;\nmod arithmetic;\nmod sin;\nmod cos;\nmod asin;\nmod cumsum;\nmod flatten;\nmod sinh;\nmod tanh;\nmod cosh;\nmod acosh;\nmod asinh;\nmod atan;\nmod xor;\nmod or;\nmod acos;\nmod onehot;\nmod sqrt;\nmod concat;\nmod gather;\nmod where;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/operators/transpose_test.cairo",
        "content": "use core::array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor, U32Tensor};\nuse core::debug::PrintTrait;\n\n\n#[test]\n#[available_gas(200000000000)]\nfn transpose_test_shape() {\n    let tensor = TensorTrait::<\n        u32\n    >::new(shape: array![4, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),);\n\n    let result = tensor.transpose(axes: array![1, 0].span());\n    assert(result.shape == array![2, 4].span(), 'wrong dim');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn transpose_test_values() {\n    let tensor = TensorTrait::<\n        u32\n    >::new(shape: array![4, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),);\n\n    let result = tensor.transpose(axes: array![1, 0].span());\n    assert(result.data == array![0, 2, 4, 6, 1, 3, 5, 7].span(), 'wrong data');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn transpose_test_1D() {\n    let tensor = TensorTrait::<u32>::new(shape: array![4].span(), data: array![0, 1, 2, 3].span(),);\n\n    let result = tensor.transpose(axes: array![0].span());\n\n    assert(result.shape == array![4].span(), 'wrong shape');\n    assert(result.data == array![0, 1, 2, 3].span(), 'wrong data');\n}\n\n#[test]\n#[available_gas(200000000000)]\nfn transpose_test_3D() {\n    let tensor = TensorTrait::<\n        u32\n    >::new(shape: array![2, 2, 2].span(), data: array![0, 1, 2, 3, 4, 5, 6, 7].span(),);\n\n    let result = tensor.transpose(axes: array![1, 2, 0].span());\n\n    assert(result.shape == array![2, 2, 2].span(), 'wrong shape');\n    assert(result.data == array![0, 4, 1, 5, 2, 6, 3, 7].span(), 'wrong data');\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance.cairo",
        "content": "mod quantize_linear_test;\nmod dequantize_linear_test;\nmod dynamic_quantize_linear_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dequantize_linear_test.cairo",
        "content": "mod dequantize_linear_i32_test;\nmod dequantize_linear_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dequantize_linear_test/dequantize_linear_fp_test.cairo",
        "content": "mod fp_i8_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dequantize_linear_test/dequantize_linear_fp_test/fp_i8_test.cairo",
        "content": "#[cfg(test)]\nmod fp8x23 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp8x23::core::{FP8x23Impl, FP8x23PartialEq};\n    use orion::operators::tensor::I8Tensor;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP8x23;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn dequantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(4);\n        let mut data = ArrayTrait::<i8>::new();\n        data.append(0);\n        data.append(3);\n        data.append(125);\n        data.append(127);\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // XSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n\n        let x_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n\n        let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<FP8x23> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n        assert(\n            (*y.data[0]).into() == FixedTrait::<FP8x23, u32>::new_unscaled(0, false),\n            '*result[0] == 0'\n        );\n        assert(\n            (*y.data[1]).into() == FixedTrait::<FP8x23, u32>::new_unscaled(6, false),\n            '*result[1] == 6'\n        );\n        assert(\n            (*y.data[2]).into() == FixedTrait::<FP8x23, u32>::new_unscaled(250, false),\n            '*result[2] == 250'\n        );\n        assert(\n            (*y.data[3]).into() == FixedTrait::<FP8x23, u32>::new_unscaled(254, false),\n            '*result[3] == 254'\n        );\n    }\n// TODO: fix it when move performance tests in nodes.\n// #[test]\n// #[available_gas(20000000)]\n// fn per_axis() {\n//     // X\n//     let mut shape = ArrayTrait::<usize>::new();\n//     shape.append(1);\n//     shape.append(3);\n//     shape.append(3);\n//     shape.append(2);\n//     let mut data = ArrayTrait::<i8>::new();\n//     data.append(IntegerTrait::new(3, false));\n//     data.append(IntegerTrait::new(89, false));\n//     data.append(IntegerTrait::new(34, false));\n//     data.append(IntegerTrait::new(127, false));\n//     data.append(IntegerTrait::new(74, false));\n//     data.append(IntegerTrait::new(59, false));\n//     data.append(IntegerTrait::new(5, false));\n//     data.append(IntegerTrait::new(24, false));\n//     data.append(IntegerTrait::new(24, false));\n//     data.append(IntegerTrait::new(87, false));\n//     data.append(IntegerTrait::new(32, false));\n//     data.append(IntegerTrait::new(13, false));\n//     data.append(IntegerTrait::new(127, false));\n//     data.append(IntegerTrait::new(99, false));\n//     data.append(IntegerTrait::new(4, false));\n//     data.append(IntegerTrait::new(127, false));\n//     data.append(IntegerTrait::new(121, false));\n//     data.append(IntegerTrait::new(102, false));\n//     \n//     let x = TensorTrait::new(shape.span(), data.span());\n\n//     // XSCALE\n//     let mut shape = ArrayTrait::<usize>::new();\n//     shape.append(1);\n//     shape.append(3);\n//     shape.append(1);\n//     shape.append(1);\n//     let mut data = ArrayTrait::<FixedType>::new();\n//     data.append(FixedTrait::new_unscaled(2, false));\n//     data.append(FixedTrait::new_unscaled(4, false));\n//     data.append(FixedTrait::new_unscaled(5, false));\n//     \n//     let x_scale = TensorTrait::new(shape.span(), data.span());\n\n//     // ZEROPOINT\n//     let mut shape = ArrayTrait::<usize>::new();\n//     shape.append(1);\n//     shape.append(3);\n//     shape.append(1);\n//     shape.append(1);\n//     let mut data = ArrayTrait::<FixedType>::new();\n//     data.append(FixedTrait::new_unscaled(1, false));\n//     data.append(FixedTrait::new_unscaled(2, false));\n//     data.append(FixedTrait::new_unscaled(3, false));\n//     \n//     let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n//     let y: Tensor<FixedType> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n//     assert((*y.data[0]).into() == FixedTrait::new_unscaled(4, false), '*result[0] == 162');\n//     assert((*y.data[1]).into() == FixedTrait::new_unscaled(176, false), '*result[1] == 10');\n//     assert((*y.data[2]).into() == FixedTrait::new_unscaled(66, false), '*result[2] == 100');\n//     assert((*y.data[3]).into() == FixedTrait::new_unscaled(252, false), '*result[3] == 232');\n//     assert((*y.data[4]).into() == FixedTrait::new_unscaled(146, false), '*result[4] == 20');\n//     assert((*y.data[5]).into() == FixedTrait::new_unscaled(116, false), '*result[5] == 50');\n//     assert((*y.data[6]).into() == FixedTrait::new_unscaled(12, false), '*result[6] == 76');\n//     assert((*y.data[7]).into() == FixedTrait::new_unscaled(88, false), '*result[7] == 0');\n//     assert((*y.data[8]).into() == FixedTrait::new_unscaled(88, false), '*result[8] == 0');\n//     assert((*y.data[9]).into() == FixedTrait::new_unscaled(340, false), '*result[9] == 252');\n//     assert((*y.data[10]).into() == FixedTrait::new_unscaled(120, false), '*result[10] == 32');\n//     assert((*y.data[11]).into() == FixedTrait::new_unscaled(44, false), '*result[11] == 44');\n//     assert((*y.data[12]).into() == FixedTrait::new_unscaled(620, false), '*result[12] == 245');\n//     assert((*y.data[13]).into() == FixedTrait::new_unscaled(480, false), '*result[13] == 485');\n//     assert((*y.data[14]).into() == FixedTrait::new_unscaled(5, false), '*result[14] == 960');\n//     assert((*y.data[15]).into() == FixedTrait::new_unscaled(620, false), '*result[15] == 270');\n//     assert((*y.data[16]).into() == FixedTrait::new_unscaled(590, false), '*result[16] == 375');\n//     assert((*y.data[17]).into() == FixedTrait::new_unscaled(495, false), '*result[17] == 470');\n// }\n}\n\n#[cfg(test)]\nmod fp16x16 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16Impl, FP16x16PartialEq\n    };\n    use orion::operators::tensor::I8Tensor;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP16x16;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn dequantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(4);\n        let mut data = ArrayTrait::<i8>::new();\n        data.append(0);\n        data.append(3);\n        data.append(125);\n        data.append(127);\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // XSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n\n        let x_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n\n        let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<FP16x16> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n        assert(\n            (*y.data[0]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(0, false),\n            '*result[0] == 0'\n        );\n        assert(\n            (*y.data[1]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(6, false),\n            '*result[1] == 6'\n        );\n        assert(\n            (*y.data[2]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(250, false),\n            '*result[2] == 250'\n        );\n        assert(\n            (*y.data[3]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(254, false),\n            '*result[3] == 254'\n        );\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn per_axis() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(3);\n        shape.append(2);\n        let mut data = ArrayTrait::<i8>::new();\n        data.append(3);\n        data.append(89);\n        data.append(34);\n        data.append(127);\n        data.append(74);\n        data.append(59);\n        data.append(5);\n        data.append(24);\n        data.append(24);\n        data.append(87);\n        data.append(32);\n        data.append(13);\n        data.append(127);\n        data.append(99);\n        data.append(4);\n        data.append(127);\n        data.append(121);\n        data.append(102);\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // XSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(4, false));\n        data.append(FixedTrait::new_unscaled(5, false));\n\n        let x_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n\n        let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<FP16x16> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n        assert(\n            (*y.data[0]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(4, false),\n            '*result[0] == 162'\n        );\n        assert(\n            (*y.data[1]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(176, false),\n            '*result[1] == 10'\n        );\n        assert(\n            (*y.data[2]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(66, false),\n            '*result[2] == 100'\n        );\n        assert(\n            (*y.data[3]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(252, false),\n            '*result[3] == 232'\n        );\n        assert(\n            (*y.data[4]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(146, false),\n            '*result[4] == 20'\n        );\n        assert(\n            (*y.data[5]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(116, false),\n            '*result[5] == 50'\n        );\n        assert(\n            (*y.data[6]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(12, false),\n            '*result[6] == 76'\n        );\n        assert(\n            (*y.data[7]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(88, false),\n            '*result[7] == 0'\n        );\n        assert(\n            (*y.data[8]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(88, false),\n            '*result[8] == 0'\n        );\n        assert(\n            (*y.data[9]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(340, false),\n            '*result[9] == 252'\n        );\n        assert(\n            (*y.data[10]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(120, false),\n            '*result[10] == 32'\n        );\n        assert(\n            (*y.data[11]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(44, false),\n            '*result[11] == 44'\n        );\n        assert(\n            (*y.data[12]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(620, false),\n            '*result[12] == 245'\n        );\n        assert(\n            (*y.data[13]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(480, false),\n            '*result[13] == 485'\n        );\n        assert(\n            (*y.data[14]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(5, false),\n            '*result[14] == 960'\n        );\n        assert(\n            (*y.data[15]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(620, false),\n            '*result[15] == 270'\n        );\n        assert(\n            (*y.data[16]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(590, false),\n            '*result[16] == 375'\n        );\n        assert(\n            (*y.data[17]).into() == FixedTrait::<FP16x16, u32>::new_unscaled(495, false),\n            '*result[17] == 470'\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dequantize_linear_test/dequantize_linear_i32_test.cairo",
        "content": "use core::debug::{PrintTrait};\nuse core::array::ArrayTrait;\nuse core::array::SpanTrait;\nuse core::traits::Into;\n\nuse orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::operators::tensor::I8Tensor;\nuse orion::operators::tensor::I32Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000)]\nfn dequantize_linear() {\n    // X\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(4);\n    let mut data = ArrayTrait::<i8>::new();\n    data.append(0);\n    data.append(3);\n    data.append(125);\n    data.append(127);\n\n    let x = TensorTrait::new(shape.span(), data.span());\n\n    // XSCALE\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(2);\n\n    let x_scale = TensorTrait::new(shape.span(), data.span());\n\n    // ZEROPOINT\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(0);\n\n    let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n    let y: Tensor<i32> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n    assert((*y.data[0]).into() == 0, '*result[0] == 0');\n    assert((*y.data[1]).into() == 6, '*result[1] == 6');\n    assert((*y.data[2]).into() == 250, '*result[2] == 250');\n    assert((*y.data[3]).into() == 254, '*result[3] == 254');\n}\n\n#[test]\n#[available_gas(20000000)]\nfn per_axis() {\n    // X\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n    let mut data = ArrayTrait::<i8>::new();\n    data.append(3);\n    data.append(89);\n    data.append(34);\n    data.append(127);\n    data.append(74);\n    data.append(59);\n    data.append(5);\n    data.append(24);\n    data.append(24);\n    data.append(87);\n    data.append(32);\n    data.append(13);\n    data.append(127);\n    data.append(99);\n    data.append(4);\n    data.append(127);\n    data.append(121);\n    data.append(102);\n\n    let x = TensorTrait::new(shape.span(), data.span());\n\n    // XSCALE\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(2);\n    data.append(4);\n    data.append(5);\n\n    let x_scale = TensorTrait::new(shape.span(), data.span());\n\n    // ZEROPOINT\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(1);\n    data.append(2);\n    data.append(3);\n\n    let x_zero_point = TensorTrait::new(shape.span(), data.span());\n\n    let y: Tensor<i32> = x.dequantize_linear(@x_scale, @x_zero_point);\n\n    assert((*y.data[0]).into() == 4, '*result[0] == 162');\n    assert((*y.data[1]).into() == 176, '*result[1] == 10');\n    assert((*y.data[2]).into() == 66, '*result[2] == 100');\n    assert((*y.data[3]).into() == 252, '*result[3] == 232');\n    assert((*y.data[4]).into() == 146, '*result[4] == 20');\n    assert((*y.data[5]).into() == 116, '*result[5] == 50');\n    assert((*y.data[6]).into() == 12, '*result[6] == 76');\n    assert((*y.data[7]).into() == 88, '*result[7] == 0');\n    assert((*y.data[8]).into() == 88, '*result[8] == 0');\n    assert((*y.data[9]).into() == 340, '*result[9] == 252');\n    assert((*y.data[10]).into() == 120, '*result[10] == 32');\n    assert((*y.data[11]).into() == 44, '*result[11] == 44');\n    assert((*y.data[12]).into() == 620, '*result[12] == 245');\n    assert((*y.data[13]).into() == 480, '*result[13] == 485');\n    assert((*y.data[14]).into() == 5, '*result[14] == 960');\n    assert((*y.data[15]).into() == 620, '*result[15] == 270');\n    assert((*y.data[16]).into() == 590, '*result[16] == 375');\n    assert((*y.data[17]).into() == 495, '*result[17] == 470');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dynamic_quantize_linear_test.cairo",
        "content": "mod dynamic_quantize_linear_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/dynamic_quantize_linear_test/dynamic_quantize_linear_fp_test.cairo",
        "content": "#[cfg(test)]\nmod fp8x23 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23Impl;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP8x23;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn dynamic_quantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(6);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new(0, false));\n        data.append(FixedTrait::new(587203, false)); // 0.07\n        data.append(FixedTrait::new(838861, false)); // 0.1\n        data.append(FixedTrait::new(1677722, false)); // 0.2\n        data.append(FixedTrait::new(4194304, false)); // 0.5\n        data.append(FixedTrait::new(7549747, false)); // 0.9\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        let (y, y_scale, y_zero_point) = x.dynamic_quantize_linear();\n\n        assert((*(y_scale.data).at(0)).into() == 29606, '*y_scale[0].mag == 0.00353');\n        assert((*(y_zero_point.data).at(0)).into() == 0, '*y_zero_point[0].mag == 0');\n        assert((*(y.data).at(0)).into() == 0, '*result[0] == 0');\n        assert((*(y.data).at(1)).into() == 19, '*result[1] == 19');\n        assert((*(y.data).at(2)).into() == 28, '*result[2] == 28');\n        assert((*(y.data).at(3)).into() == 56, '*result[3] == 56');\n        assert((*(y.data).at(4)).into() == 141, '*result[4] == 141');\n        assert((*(y.data).at(5)).into() == 255, '*result[5] == 255');\n    }\n}\n\n\n#[cfg(test)]\nmod fp16x16 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP16x16;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn dynamic_quantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(6);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new(10945, false)); // 0.167\n        data.append(FixedTrait::new(190054, false)); // 2.9\n        data.append(FixedTrait::new_unscaled(3, false)); // 3.0\n        data.append(FixedTrait::new(229376, false)); // 3.5\n        data.append(FixedTrait::new_unscaled(3, true)); // -3.0\n        data.append(FixedTrait::new(229376, true)); // -3.5\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        let (y, y_scale, y_zero_point) = x.dynamic_quantize_linear();\n\n        assert((*(y_scale.data).at(0)).into() == 1799, '*y_scale[0].mag == 0.02745');\n        assert((*(y_zero_point.data).at(0)).into() == 8355967, '*y_zero_point[0].mag == 128');\n        assert((*(y.data).at(0)).into() == 133, '*result[0] == 134');\n        assert((*(y.data).at(1)).into() == 233, '*result[1] == 233');\n        assert((*(y.data).at(2)).into() == 236, '*result[2] == 237');\n        assert((*(y.data).at(3)).into() == 255, '*result[3] == 255');\n        assert((*(y.data).at(4)).into() == 18, '*result[4] == -18');\n        assert((*(y.data).at(5)).into() == 0, '*result[5] == -0');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/quantize_linear_test.cairo",
        "content": "mod quantize_linear_i32_test;\nmod quantize_linear_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/quantize_linear_test/quantize_linear_fp_test.cairo",
        "content": "mod fp_i8_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/quantize_linear_test/quantize_linear_fp_test/fp_i8_test.cairo",
        "content": "#[cfg(test)]\nmod fp8x23 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23Impl;\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP8x23;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn quantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(6);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(200, false));\n        data.append(FixedTrait::new_unscaled(250, true));\n        data.append(FixedTrait::new_unscaled(100, true));\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // YSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n\n        let y_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(1, false));\n\n        let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n        assert((*y.data[0]).into() == 1, '*result[0] == 1');\n        assert((*y.data[1]).into() == 2, '*result[1] == 2');\n        assert((*y.data[2]).into() == 2, '*result[2] == 2');\n        assert((*y.data[3]).into() == 101, '*result[3] == 101');\n        assert((*y.data[4]).into() == -124, '*result[4] == -124');\n        assert((*y.data[5]).into() == -49, '*result[5] == -49');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn per_axis() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(3);\n        shape.append(2);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(162, true));\n        data.append(FixedTrait::new_unscaled(10, false));\n        data.append(FixedTrait::new_unscaled(100, true));\n        data.append(FixedTrait::new_unscaled(232, false));\n        data.append(FixedTrait::new_unscaled(20, true));\n        data.append(FixedTrait::new_unscaled(50, true));\n        data.append(FixedTrait::new_unscaled(76, true));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(252, false));\n        data.append(FixedTrait::new_unscaled(32, false));\n        data.append(FixedTrait::new_unscaled(44, true));\n        data.append(FixedTrait::new_unscaled(245, false));\n        data.append(FixedTrait::new_unscaled(220, true));\n        data.append(FixedTrait::new_unscaled(210, true));\n        data.append(FixedTrait::new_unscaled(210, true));\n        data.append(FixedTrait::new_unscaled(200, true));\n        data.append(FixedTrait::new_unscaled(120, true));\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // YSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(4, false));\n        data.append(FixedTrait::new_unscaled(5, false));\n\n        let y_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP8x23>::new();\n        data.append(FixedTrait::new_unscaled(84, false));\n        data.append(FixedTrait::new_unscaled(24, false));\n        data.append(FixedTrait::new_unscaled(196, false));\n\n        let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n        assert((*y.data[0]).into() == 3, '*result[0] == 3');\n        assert((*y.data[1]).into() == 89, '*result[1] == 89');\n        assert((*y.data[2]).into() == 34, '*result[2] == 34');\n        assert((*y.data[3]).into() == 127, '*result[3] == 127');\n        assert((*y.data[4]).into() == 74, '*result[4] == 74');\n        assert((*y.data[5]).into() == 59, '*result[5] == 59');\n        assert((*y.data[6]).into() == 5, '*result[6] == 5');\n        assert((*y.data[7]).into() == 24, '*result[7] == 24');\n        assert((*y.data[8]).into() == 24, '*result[8] == 24');\n        assert((*y.data[9]).into() == 87, '*result[9] == 87');\n        assert((*y.data[10]).into() == 32, '*result[10] == 32');\n        assert((*y.data[11]).into() == 13, '*result[11] == 13');\n        assert((*y.data[12]).into() == 127, '*result[12] == 127');\n        assert((*y.data[13]).into() == 127, '*result[13] == 127');\n        assert((*y.data[14]).into() == 127, '*result[14] == 127');\n        assert((*y.data[15]).into() == 127, '*result[15] == 127');\n        assert((*y.data[16]).into() == 127, '*result[16] == 127');\n        assert((*y.data[17]).into() == 127, '*result[17] == 127');\n    }\n}\n\n\n#[cfg(test)]\nmod fp16x16 {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n    use core::traits::Into;\n    use core::debug::PrintTrait;\n\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::{TensorTrait, Tensor};\n    use orion::numbers::FP16x16;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn quantize_linear() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(6);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(1000, false));\n        data.append(FixedTrait::new_unscaled(254, true));\n        data.append(FixedTrait::new_unscaled(1000, true));\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // YSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n\n        let y_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(1, false));\n\n        let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n        assert((*y.data[0]).into() == 1, '*result[0] == 1');\n        assert((*y.data[1]).into() == 2, '*result[1] == 2');\n        assert((*y.data[2]).into() == 2, '*result[2] == 2');\n        assert((*y.data[3]).into() == 127, '*result[3] == 127');\n        assert((*y.data[4]).into() == -126, '*result[4] == -126');\n        assert((*y.data[5]).into() == -127, '*result[5] == -127');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn per_axis() {\n        // X\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(3);\n        shape.append(2);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(162, true));\n        data.append(FixedTrait::new_unscaled(10, false));\n        data.append(FixedTrait::new_unscaled(100, true));\n        data.append(FixedTrait::new_unscaled(232, false));\n        data.append(FixedTrait::new_unscaled(20, true));\n        data.append(FixedTrait::new_unscaled(50, true));\n        data.append(FixedTrait::new_unscaled(76, true));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(252, false));\n        data.append(FixedTrait::new_unscaled(32, false));\n        data.append(FixedTrait::new_unscaled(44, true));\n        data.append(FixedTrait::new_unscaled(245, false));\n        data.append(FixedTrait::new_unscaled(485, true));\n        data.append(FixedTrait::new_unscaled(960, true));\n        data.append(FixedTrait::new_unscaled(270, true));\n        data.append(FixedTrait::new_unscaled(375, true));\n        data.append(FixedTrait::new_unscaled(470, true));\n\n        let x = TensorTrait::new(shape.span(), data.span());\n\n        // YSCALE\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(4, false));\n        data.append(FixedTrait::new_unscaled(5, false));\n\n        let y_scale = TensorTrait::new(shape.span(), data.span());\n\n        // ZEROPOINT\n        let mut shape = ArrayTrait::<usize>::new();\n        shape.append(1);\n        shape.append(3);\n        shape.append(1);\n        shape.append(1);\n        let mut data = ArrayTrait::<FP16x16>::new();\n        data.append(FixedTrait::new_unscaled(84, false));\n        data.append(FixedTrait::new_unscaled(24, false));\n        data.append(FixedTrait::new_unscaled(196, false));\n\n        let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n        let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n        assert((*y.data[0]).into() == 3, '*result[0] == 3');\n        assert((*y.data[1]).into() == 89, '*result[1] == 89');\n        assert((*y.data[2]).into() == 34, '*result[2] == 34');\n        assert((*y.data[3]).into() == 127, '*result[3] == 127');\n        assert((*y.data[4]).into() == 74, '*result[4] == 74');\n        assert((*y.data[5]).into() == 59, '*result[5] == 59');\n        assert((*y.data[6]).into() == 5, '*result[6] == 5');\n        assert((*y.data[7]).into() == 24, '*result[7] == 24');\n        assert((*y.data[8]).into() == 24, '*result[8] == 24');\n        assert((*y.data[9]).into() == 87, '*result[9] == 87');\n        assert((*y.data[10]).into() == 32, '*result[10] == 32');\n        assert((*y.data[11]).into() == 13, '*result[11] == 13');\n        assert((*y.data[12]).into() == 127, '*result[12] == 127');\n        assert((*y.data[13]).into() == 99, '*result[13] == 99');\n        assert((*y.data[14]).into() == 4, '*result[14] == 4');\n        assert((*y.data[15]).into() == 127, '*result[15] == 127');\n        assert((*y.data[16]).into() == 121, '*result[16] == 121');\n        assert((*y.data[17]).into() == 102, '*result[17] == 102');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/performance/quantize_linear_test/quantize_linear_i32_test.cairo",
        "content": "use core::debug::{PrintTrait};\nuse core::array::ArrayTrait;\nuse core::array::SpanTrait;\nuse core::traits::Into;\n\nuse orion::numbers::fixed_point::core::{FixedTrait};\nuse orion::operators::tensor::I32Tensor;\nuse orion::operators::tensor::{TensorTrait, Tensor};\n\n#[test]\n#[available_gas(2000000)]\nfn quantize_linear() {\n    // X\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(6);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(0);\n    data.append(2);\n    data.append(3);\n    data.append(1000);\n    data.append(-254);\n    data.append(-1000);\n\n    let x = TensorTrait::new(shape.span(), data.span());\n\n    // YSCALE\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(2);\n\n    let y_scale = TensorTrait::new(shape.span(), data.span());\n\n    // ZEROPOINT\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(1);\n\n    let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n    let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n    assert((*y.data[0]).into() == 1, '*result[0] == 1');\n    assert((*y.data[1]).into() == 2, '*result[1] == 2');\n    assert((*y.data[2]).into() == 2, '*result[2] == 2');\n    assert((*y.data[3]).into() == 127, '*result[3] == 127');\n    assert((*y.data[4]).into() == -126, '*result[4] == -126');\n    assert((*y.data[5]).into() == -127, '*result[5] == -127');\n}\n\n\n#[test]\n#[available_gas(20000000)]\nfn per_axis() {\n    // X\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(3);\n    shape.append(2);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(-162);\n    data.append(10);\n    data.append(-100);\n    data.append(232);\n    data.append(-20);\n    data.append(-50);\n    data.append(-76);\n    data.append(0);\n    data.append(0);\n    data.append(252);\n    data.append(32);\n    data.append(-44);\n    data.append(245);\n    data.append(-485);\n    data.append(-960);\n    data.append(-270);\n    data.append(-375);\n    data.append(-470);\n\n    let x = TensorTrait::new(shape.span(), data.span());\n\n    // YSCALE\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(2);\n    data.append(4);\n    data.append(5);\n\n    let y_scale = TensorTrait::new(shape.span(), data.span());\n\n    // ZEROPOINT\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(1);\n    shape.append(3);\n    shape.append(1);\n    shape.append(1);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(84);\n    data.append(24);\n    data.append(196);\n\n    let y_zero_point = TensorTrait::new(shape.span(), data.span());\n\n    let y: Tensor<i8> = x.quantize_linear(@y_scale, @y_zero_point);\n\n    assert((*y.data[0]).into() == 3, '*result[0] == 3');\n    assert((*y.data[1]).into() == 89, '*result[1] == 89');\n    assert((*y.data[2]).into() == 34, '*result[2] == 34');\n    assert((*y.data[3]).into() == 127, '*result[3] == 127');\n    assert((*y.data[4]).into() == 74, '*result[4] == 74');\n    assert((*y.data[5]).into() == 59, '*result[5] == 59');\n    assert((*y.data[6]).into() == 5, '*result[6] == 5');\n    assert((*y.data[7]).into() == 24, '*result[7] == 24');\n    assert((*y.data[8]).into() == 24, '*result[8] == 24');\n    assert((*y.data[9]).into() == 87, '*result[9] == 87');\n    assert((*y.data[10]).into() == 32, '*result[10] == 32');\n    assert((*y.data[11]).into() == 13, '*result[11] == 13');\n    assert((*y.data[12]).into() == 127, '*result[12] == 127');\n    assert((*y.data[13]).into() == 99, '*result[13] == 99');\n    assert((*y.data[14]).into() == 4, '*result[14] == 4');\n    assert((*y.data[15]).into() == 127, '*result[15] == 127');\n    assert((*y.data[16]).into() == 121, '*result[16] == 121');\n    assert((*y.data[17]).into() == 102, '*result[17] == 102');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core.cairo",
        "content": "mod at;\nmod flatten;\nmod max;\nmod min;\nmod stride;\nmod onehot;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at.cairo",
        "content": "mod at_u32_test;\nmod at_i32_test;\nmod at_fp_test;\nmod at_bool_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_bool_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::BoolTensor;\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(3);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(true);\n        data.append(false);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == true, 'result[2] = true');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::{BoolTensor};\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(true);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == true, 'result[4] = true');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::{BoolTensor};\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(true);\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(false);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let mut indices = ArrayTrait::new();\n        indices.append(0);\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == true, 'result[3] = true');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_fp_test.cairo",
        "content": "mod at_fp8x23_test;\nmod at_fp16x16_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_fp_test/at_fp16x16_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16Impl, FP16x16PartialEq\n    };\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_1x3_helper();\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(1, false), 'result[2] = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16Impl, FP16x16PartialEq\n    };\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(3, false), 'result[4] = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16Impl, FP16x16PartialEq\n    };\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(0);\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(3, false), 'result[3] = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_fp_test/at_fp8x23_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::{FP8x23Impl, FP8x23PartialEq};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_1x3_helper();\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(1, false), 'result[2] = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::{FP8x23Impl, FP8x23PartialEq};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(3, false), 'result[4] = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::core::FixedTrait;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::{FP8x23Impl, FP8x23PartialEq};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(0);\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == FixedTrait::new_unscaled(3, false), 'result[3] = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_i32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = i32_tensor_1x3_helper();\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 1, 'result[2] = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = i32_tensor_2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 3, 'result[4] = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = i32_tensor_2x2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(0);\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 3, 'result[3] = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/at/at_u32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = u32_tensor_1x3_helper();\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 1, 'result[2] = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = u32_tensor_2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 3, 'result[4] = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = u32_tensor_2x2x2_helper();\n\n        let mut indices = ArrayTrait::new();\n        indices.append(0);\n        indices.append(1);\n        indices.append(1);\n\n        let result = tensor.at(indices.span());\n\n        assert(result == 3, 'result[3] = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten.cairo",
        "content": "mod flatten_i32_test;\nmod flatten_u32_test;\nmod flatten_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten/flatten_fp_test.cairo",
        "content": "mod flatten_fp8x23_test;\nmod flatten_fp16x16_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten/flatten_fp_test/flatten_fp16x16_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_1x3_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_1x3_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 3, 'result[1] = 3');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2x2_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 8, 'result[1] = 8');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_2() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(2);\n        assert((*result.shape[0]).into() == 4, 'result[0] = 4');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten/flatten_fp_test/flatten_fp8x23_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_1x3_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_1x3_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 3, 'result[1] = 3');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::traits::Into;\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2x2_helper;\n    use orion::operators::tensor::core::TensorTrait;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 8, 'result[1] = 8');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_2() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.flatten(2);\n        assert((*result.shape[0]).into() == 4, 'result[0] = 4');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten/flatten_i32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = i32_tensor_1x3_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 3, 'result[1] = 3');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = i32_tensor_2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = i32_tensor_2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = i32_tensor_2x2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 8, 'result[1] = 8');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = i32_tensor_2x2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_2() {\n        let tensor = i32_tensor_2x2x2_helper();\n        let result = tensor.flatten(2);\n        assert((*result.shape[0]).into() == 4, 'result[0] = 4');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/flatten/flatten_u32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = u32_tensor_1x3_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 3, 'result[1] = 3');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = u32_tensor_2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = u32_tensor_2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_0() {\n        let tensor = u32_tensor_2x2x2_helper();\n        let result = tensor.flatten(0);\n        assert((*result.shape[0]).into() == 1, 'result[0] = 1');\n        assert((*result.shape[1]).into() == 8, 'result[1] = 8');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_1() {\n        let tensor = u32_tensor_2x2x2_helper();\n        let result = tensor.flatten(1);\n        assert((*result.shape[0]).into() == 2, 'result[0] = 2');\n        assert((*result.shape[1]).into() == 4, 'result[1] = 4');\n    }\n\n    #[test]\n    #[available_gas(200000)]\n    fn axis_2() {\n        let tensor = u32_tensor_2x2x2_helper();\n        let result = tensor.flatten(2);\n        assert((*result.shape[0]).into() == 4, 'result[0] = 4');\n        assert((*result.shape[1]).into() == 2, 'result[1] = 2');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max.cairo",
        "content": "mod max_u32_test;\nmod max_i32_test;\nmod max_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max/max_fp_test.cairo",
        "content": "mod max_fp8x23_test;\nmod max_fp16x16_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max/max_fp_test/max_fp16x16_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP16x16>::new_unscaled(2, false).mag, 'tensor.max = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP16x16>::new_unscaled(3, false).mag, 'tensor.max = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP16x16>::new_unscaled(7, false).mag, 'tensor.max = 7');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max/max_fp_test/max_fp8x23_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP8x23>::new_unscaled(2, false).mag, 'tensor.max = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP8x23>::new_unscaled(3, false).mag, 'tensor.max = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let result = tensor.max_in_tensor().mag;\n        assert(result == FixedTrait::<FP8x23>::new_unscaled(7, false).mag, 'tensor.max = 7');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max/max_i32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = i32_tensor_1x3_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 2, 'tensor.max = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = i32_tensor_2x2_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 3, 'tensor.max = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_2x2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = i32_tensor_2x2x2_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 7, 'tensor.max = 7');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/max/max_u32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = u32_tensor_1x3_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 2, 'tensor.max = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = u32_tensor_2x2_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 3, 'tensor.max = 3');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_2x2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_max() {\n        let tensor = u32_tensor_2x2x2_helper();\n\n        let result = tensor.max_in_tensor();\n        assert(result == 7, 'tensor.max = 7');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min.cairo",
        "content": "mod min_u32_test;\nmod min_i32_test;\nmod min_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min/min_fp_test.cairo",
        "content": "mod min_fp8x23_test;\nmod min_fp16x16_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min/min_fp_test/min_fp16x16_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min/min_fp_test/min_fp8x23_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_1x3_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2x2_helper;\n    use orion::numbers::fixed_point::implementations::fp8x23::core::FP8x23Impl;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = fp_tensor_2x2x2_helper();\n\n        let result = tensor.min_in_tensor().mag;\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min/min_i32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = i32_tensor_1x3_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = i32_tensor_2x2_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::i32::i32_tensor_2x2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = i32_tensor_2x2x2_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/min/min_u32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_1x3_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = u32_tensor_1x3_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = u32_tensor_2x2_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::u32::u32_tensor_2x2x2_helper;\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_min() {\n        let tensor = u32_tensor_2x2x2_helper();\n\n        let result = tensor.min_in_tensor();\n        assert(result == 0, 'tensor.min = 0');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/onehot.cairo",
        "content": "mod onehot_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/onehot/onehot_fp_test.cairo",
        "content": "mod onehot_fp8x23_test;\nmod onehot_fp16x16_test;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/onehot/onehot_fp_test/onehot_fp16x16_test.cairo",
        "content": "use core::serde::Serde;\nuse core::option::OptionTrait;\nuse core::clone::Clone;\n// ===== 1D ===== //\nuse orion::numbers::fixed_point::core::FixedTrait;\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FP16x16PartialEq};\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::test_helper::tensor::fixed_point::fp16x16::{\n        fp_tensor_1x3_helper, fp_tensor_2x2_helper, fp_tensor_3x2x2_neg_helper,\n        fp_tensor_1x3_neg_helper, fp_tensor_2x2x2_helper\n    };\n    use orion::operators::tensor::core::TensorTrait;\n    use core::debug::PrintTrait;\n    use core::clone::Clone;\n    use core::option::OptionTrait;\n    use core::serde::Serde;\n\n    // use orion::numbers::fixed_point::implementations::fp16x16::core::FP16x16Impl;\n    // use orion::operators::tensor::implementations::impl_tensor_fp::Tensor_fp;\n    use orion::operators::tensor::core::{Tensor};\n\n    fn fp_tensor_3x2x2_new() -> Tensor<FP16x16> {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(3);\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n\n        let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n        return tensor;\n    }\n\n    fn fp_tensor_2x2_pos_neg_new() -> Tensor<FP16x16> {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, true));\n        data.append(FixedTrait::new_unscaled(1, true));\n\n        let tensor = TensorTrait::<FP16x16>::new(sizes.span(), data.span());\n\n        return tensor;\n    }\n\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_last_axis() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_neg_last_axis() {\n        let tensor = fp_tensor_1x3_neg_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(1, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_2x2_post_neg_last_axis() {\n        let tensor = fp_tensor_2x2_pos_neg_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(1, false), 'result[7] = 1');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(0, false), 'result[10] = 0');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(1, false), 'result[11] = 0');\n    }\n\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_1x3_fail() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(3);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_Zero_axis() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_axis_one() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_last_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(1)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(2)) == 4, 'shape[0] = 4');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_2x2_fail() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(3);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_first_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(1)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(2)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_second_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(1, false), 'result[3] = 1');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(0, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(1, false), 'result[12] = 1');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(1)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(2)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_last_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::None(());\n        // let axis: Option<usize> = Option::Some(3);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(1, false), 'result[21] = 1');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(1, false), 'result[26] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(1, false), 'result[37] = 1');\n        assert((*result.data[42]) == FixedTrait::new_unscaled(1, false), 'result[42] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 2, 'shape[1] = 2');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 2');\n        assert((*result.shape.at(3)) == 4, 'shape[0] = 4');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_3x2x2_fail() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(4);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_first_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(2);\n        values.append(5);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(5, false), 'result[0] = 5');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(2, false), 'result[1] = 2');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(2, false), 'result[2] = 2');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(2, false), 'result[3] = 2');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(5, false), 'result[4] = 5');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(2, false), 'result[5] = 2');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(2, false), 'result[6] = 2');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(2, false), 'result[7] = 2');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(5, false), 'result[8] = 5');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(2, false), 'result[9] = 2');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(2, false), 'result[10] = 2');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(2, false), 'result[11] = 2');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(2, false), 'result[12] = 2');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(5, false), 'result[13] = 5');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(2, false), 'result[14] = 2');\n        assert((*result.data[17]) == FixedTrait::new_unscaled(5, false), 'result[17] = 5');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(5, false), 'result[21] = 5');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(5, false), 'result[26] = 5');\n        assert((*result.data[30]) == FixedTrait::new_unscaled(5, false), 'result[30] = 5');\n        assert((*result.data[34]) == FixedTrait::new_unscaled(5, false), 'result[34] = 5');\n        assert((*result.data[39]) == FixedTrait::new_unscaled(5, false), 'result[39] = 5');\n        assert((*result.data[43]) == FixedTrait::new_unscaled(5, false), 'result[43] = 5');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(2, false), 'result[46] = 2');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(5, false), 'result[47] = 5');\n\n        assert((*result.shape.at(0)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(1)) == 3, 'shape[1] = 3');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 3');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_second_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(1, false), 'result[21] = 1');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(1, false), 'result[26] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(1, false), 'result[37] = 1');\n        assert((*result.data[42]) == FixedTrait::new_unscaled(1, false), 'result[42] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 4, 'shape[1] = 4');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 3');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_third_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(2);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(1, false), 'result[3] = 1');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(1, false), 'result[12] = 1');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[19]) == FixedTrait::new_unscaled(1, false), 'result[19] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(0, false), 'result[21] = 0');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(0, false), 'result[26] = 0');\n        assert((*result.data[28]) == FixedTrait::new_unscaled(1, false), 'result[28] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[35]) == FixedTrait::new_unscaled(1, false), 'result[35] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(0, false), 'result[37] = 0');\n        assert((*result.data[44]) == FixedTrait::new_unscaled(1, false), 'result[44] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 2, 'shape[1] = 2');\n        assert((*result.shape.at(2)) == 4, 'shape[2] = 4');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/onehot/onehot_fp_test/onehot_fp8x23_test.cairo",
        "content": "use core::serde::Serde;\nuse core::option::OptionTrait;\nuse core::clone::Clone;\n// ===== 1D ===== //\nuse orion::numbers::fixed_point::core::FixedTrait;\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::{ArrayTrait, SpanTrait};\n    use core::traits::Into;\n    use orion::numbers::fixed_point::core::{FixedTrait};\n    use orion::numbers::fixed_point::implementations::fp8x23::core::{FP8x23, FP8x23PartialEq};\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::TensorTrait;\n    use orion::test_helper::tensor::fixed_point::fp8x23::{\n        fp_tensor_1x3_helper, fp_tensor_2x2_helper, fp_tensor_3x2x2_neg_helper,\n        fp_tensor_1x3_neg_helper, fp_tensor_2x2x2_helper\n    };\n    use core::debug::PrintTrait;\n    use core::clone::Clone;\n    use core::option::OptionTrait;\n    use core::serde::Serde;\n\n    use orion::operators::tensor::core::{Tensor};\n\n    fn fp_tensor_3x2x2_new() -> Tensor<FP8x23> {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(3);\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, false));\n        data.append(FixedTrait::new_unscaled(3, false));\n\n        let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n        return tensor;\n    }\n\n    fn fp_tensor_2x2_pos_neg_new() -> Tensor<FP8x23> {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(FixedTrait::new_unscaled(0, false));\n        data.append(FixedTrait::new_unscaled(1, false));\n        data.append(FixedTrait::new_unscaled(2, true));\n        data.append(FixedTrait::new_unscaled(1, true));\n\n        let tensor = TensorTrait::<FP8x23>::new(sizes.span(), data.span());\n\n        return tensor;\n    }\n\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_last_axis() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_neg_last_axis() {\n        let tensor = fp_tensor_1x3_neg_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(1, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_2x2_post_neg_last_axis() {\n        let tensor = fp_tensor_2x2_pos_neg_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(1, false), 'result[7] = 1');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(0, false), 'result[10] = 0');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(1, false), 'result[11] = 0');\n    }\n\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_1x3_fail() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(3);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_Zero_axis() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn tensor_onehot_1x3_axis_one() {\n        let tensor = fp_tensor_1x3_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 3;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(1, false), 'result[4] = 1');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(1, false), 'result[8] = 1');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_last_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::None(());\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(1)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(2)) == 4, 'shape[0] = 4');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_2x2_fail() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(3);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_first_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(1)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(2)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_2x2_helper_second_axis() {\n        let tensor = fp_tensor_2x2_helper();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(1, false), 'result[3] = 1');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(0, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(1, false), 'result[12] = 1');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n\n        assert((*result.shape.at(0)) == 2, 'shape[0] = 2');\n        assert((*result.shape.at(1)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(2)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_last_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::None(());\n        // let axis: Option<usize> = Option::Some(3);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(1, false), 'result[21] = 1');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(1, false), 'result[26] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(1, false), 'result[37] = 1');\n        assert((*result.data[42]) == FixedTrait::new_unscaled(1, false), 'result[42] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 2, 'shape[1] = 2');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 2');\n        assert((*result.shape.at(3)) == 4, 'shape[0] = 4');\n    }\n\n    #[test]\n    #[should_panic]\n    #[available_gas(20000000)]\n    fn tensor_onehot_tensor_3x2x2_fail() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(4);\n\n        let _result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_first_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(2);\n        values.append(5);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(0);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(5, false), 'result[0] = 5');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(2, false), 'result[1] = 2');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(2, false), 'result[2] = 2');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(2, false), 'result[3] = 2');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(5, false), 'result[4] = 5');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(2, false), 'result[5] = 2');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(2, false), 'result[6] = 2');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(2, false), 'result[7] = 2');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(5, false), 'result[8] = 5');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(2, false), 'result[9] = 2');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(2, false), 'result[10] = 2');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(2, false), 'result[11] = 2');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(2, false), 'result[12] = 2');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(5, false), 'result[13] = 5');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(2, false), 'result[14] = 2');\n        assert((*result.data[17]) == FixedTrait::new_unscaled(5, false), 'result[17] = 5');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(5, false), 'result[21] = 5');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(5, false), 'result[26] = 5');\n        assert((*result.data[30]) == FixedTrait::new_unscaled(5, false), 'result[30] = 5');\n        assert((*result.data[34]) == FixedTrait::new_unscaled(5, false), 'result[34] = 5');\n        assert((*result.data[39]) == FixedTrait::new_unscaled(5, false), 'result[39] = 5');\n        assert((*result.data[43]) == FixedTrait::new_unscaled(5, false), 'result[43] = 5');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(2, false), 'result[46] = 2');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(5, false), 'result[47] = 5');\n\n        assert((*result.shape.at(0)) == 4, 'shape[0] = 4');\n        assert((*result.shape.at(1)) == 3, 'shape[1] = 3');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 3');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_second_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(1);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(0, false), 'result[3] = 0');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(1, false), 'result[5] = 1');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[7]) == FixedTrait::new_unscaled(0, false), 'result[7] = 0');\n        assert((*result.data[8]) == FixedTrait::new_unscaled(0, false), 'result[8] = 0');\n        assert((*result.data[9]) == FixedTrait::new_unscaled(0, false), 'result[9] = 0');\n        assert((*result.data[10]) == FixedTrait::new_unscaled(1, false), 'result[10] = 1');\n        assert((*result.data[11]) == FixedTrait::new_unscaled(0, false), 'result[11] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(0, false), 'result[12] = 0');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(1, false), 'result[21] = 1');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(1, false), 'result[26] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(1, false), 'result[37] = 1');\n        assert((*result.data[42]) == FixedTrait::new_unscaled(1, false), 'result[42] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 4, 'shape[1] = 4');\n        assert((*result.shape.at(2)) == 2, 'shape[2] = 3');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n\n    #[test]\n    #[available_gas(20000000)]\n    fn fp_tensor_onehot_3x2x2_new_third_axis() {\n        let tensor = fp_tensor_3x2x2_new();\n\n        let mut values = ArrayTrait::new();\n        values.append(0);\n        values.append(1);\n        let depth = 4;\n        let axis: Option<usize> = Option::Some(2);\n\n        let result = tensor.onehot(depth: depth, axis: axis, values: values.span());\n\n        assert((*result.data[0]) == FixedTrait::new_unscaled(1, false), 'result[0] = 1');\n        assert((*result.data[1]) == FixedTrait::new_unscaled(0, false), 'result[1] = 0');\n        assert((*result.data[2]) == FixedTrait::new_unscaled(0, false), 'result[2] = 0');\n        assert((*result.data[3]) == FixedTrait::new_unscaled(1, false), 'result[3] = 1');\n        assert((*result.data[4]) == FixedTrait::new_unscaled(0, false), 'result[4] = 0');\n        assert((*result.data[5]) == FixedTrait::new_unscaled(0, false), 'result[5] = 0');\n        assert((*result.data[6]) == FixedTrait::new_unscaled(0, false), 'result[6] = 0');\n        assert((*result.data[12]) == FixedTrait::new_unscaled(1, false), 'result[12] = 1');\n        assert((*result.data[13]) == FixedTrait::new_unscaled(0, false), 'result[13] = 0');\n        assert((*result.data[14]) == FixedTrait::new_unscaled(0, false), 'result[14] = 0');\n        assert((*result.data[15]) == FixedTrait::new_unscaled(1, false), 'result[15] = 1');\n        assert((*result.data[16]) == FixedTrait::new_unscaled(1, false), 'result[16] = 1');\n        assert((*result.data[19]) == FixedTrait::new_unscaled(1, false), 'result[19] = 1');\n        assert((*result.data[21]) == FixedTrait::new_unscaled(0, false), 'result[21] = 0');\n        assert((*result.data[26]) == FixedTrait::new_unscaled(0, false), 'result[26] = 0');\n        assert((*result.data[28]) == FixedTrait::new_unscaled(1, false), 'result[28] = 1');\n        assert((*result.data[31]) == FixedTrait::new_unscaled(1, false), 'result[31] = 1');\n        assert((*result.data[32]) == FixedTrait::new_unscaled(1, false), 'result[32] = 1');\n        assert((*result.data[35]) == FixedTrait::new_unscaled(1, false), 'result[35] = 1');\n        assert((*result.data[37]) == FixedTrait::new_unscaled(0, false), 'result[37] = 0');\n        assert((*result.data[44]) == FixedTrait::new_unscaled(1, false), 'result[44] = 1');\n        assert((*result.data[46]) == FixedTrait::new_unscaled(0, false), 'result[46] = 0');\n        assert((*result.data[47]) == FixedTrait::new_unscaled(1, false), 'result[47] = 1');\n\n        assert((*result.shape.at(0)) == 3, 'shape[0] = 3');\n        assert((*result.shape.at(1)) == 2, 'shape[1] = 2');\n        assert((*result.shape.at(2)) == 4, 'shape[2] = 4');\n        assert((*result.shape.at(3)) == 2, 'shape[0] = 2');\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/ravel_index.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::core::{ravel_index};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_ravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(5);\n        let mut indices = ArrayTrait::new();\n        indices.append(2);\n        let result = ravel_index(shape.span(), indices.span());\n        assert(result == 2, 'result = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::core::{ravel_index};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_ravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(2);\n        shape.append(4);\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(2);\n        let result = ravel_index(shape.span(), indices.span());\n        assert(result == 6, 'result = 6');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::core::{ravel_index};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_ravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(2);\n        shape.append(4);\n        shape.append(6);\n        let mut indices = ArrayTrait::new();\n        indices.append(1);\n        indices.append(3);\n        indices.append(0);\n        let result = ravel_index(shape.span(), indices.span());\n        assert(result == 42, 'result = 42');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride.cairo",
        "content": "mod stride_u32_test;\nmod stride_i32_test;\nmod stride_bool_test;\nmod stride_fp_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_bool_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::{BoolTensor};\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(3);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(true);\n        data.append(false);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let result = tensor.stride();\n\n        assert(*result[0] == 1, 'stride x = 1');\n        assert(result.len() == 1, 'len = 1');\n    }\n}\n\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::{BoolTensor};\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(true);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let result = tensor.stride();\n\n        assert(*result[0] == 2, 'stride x = 2');\n        assert(*result[1] == 1, 'stride y = 1');\n        assert(result.len() == 2, 'len = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use orion::operators::tensor::{BoolTensor};\n    use orion::operators::tensor::core::{TensorTrait};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let mut sizes = ArrayTrait::new();\n        sizes.append(2);\n        sizes.append(2);\n        sizes.append(2);\n\n        let mut data = ArrayTrait::new();\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(true);\n        data.append(false);\n        data.append(false);\n        data.append(false);\n        data.append(false);\n\n        let tensor = TensorTrait::<bool>::new(sizes.span(), data.span());\n\n        let result = tensor.stride();\n\n        assert(*result[0] == 4, 'stride x = 4');\n        assert(*result[1] == 2, 'stride y = 2');\n        assert(*result[2] == 1, 'stride z = 1');\n        assert(result.len() == 3, 'len = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_fp_test.cairo",
        "content": "mod stride_fp8x23_test;\nmod stride_fp16x16_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_fp_test/stride_fp16x16_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_1x3_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 1, 'stride x = 1');\n        assert(result.len() == 1, 'len = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 2, 'stride x = 2');\n        assert(*result[1] == 1, 'stride y = 1');\n        assert(result.len() == 2, 'len = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp16x16::FP16x16Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp16x16::fp_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 4, 'stride x = 4');\n        assert(*result[1] == 2, 'stride y = 2');\n        assert(*result[2] == 1, 'stride z = 1');\n        assert(result.len() == 3, 'len = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_fp_test/stride_fp8x23_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_1x3_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 1, 'stride x = 1');\n        assert(result.len() == 1, 'len = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 2, 'stride x = 2');\n        assert(*result[1] == 1, 'stride y = 1');\n        assert(result.len() == 2, 'len = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::implementations::tensor_fp8x23::FP8x23Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::fixed_point::fp8x23::fp_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = fp_tensor_2x2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 4, 'stride x = 4');\n        assert(*result[1] == 2, 'stride y = 2');\n        assert(*result[2] == 1, 'stride z = 1');\n        assert(result.len() == 3, 'len = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_i32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = i32_tensor_1x3_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 1, 'stride x = 1');\n        assert(result.len() == 1, 'len = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = i32_tensor_2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 2, 'stride x = 2');\n        assert(*result[1] == 1, 'stride y = 1');\n        assert(result.len() == 2, 'len = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::I32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::i32::i32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = i32_tensor_2x2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 4, 'stride x = 4');\n        assert(*result[1] == 2, 'stride y = 2');\n        assert(*result[2] == 1, 'stride z = 1');\n        assert(result.len() == 3, 'len = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/stride/stride_u32_test.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_1x3_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_stride() {\n        let tensor = u32_tensor_1x3_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 1, 'stride x = 1');\n        assert(result.len() == 1, 'len = 1');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = u32_tensor_2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 2, 'stride x = 2');\n        assert(*result[1] == 1, 'stride y = 1');\n        assert(result.len() == 2, 'len = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::U32Tensor;\n    use orion::operators::tensor::core::{TensorTrait};\n    use orion::test_helper::tensor::u32::u32_tensor_2x2x2_helper;\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_at() {\n        let tensor = u32_tensor_2x2x2_helper();\n        let result = tensor.stride();\n        assert(*result[0] == 4, 'stride x = 4');\n        assert(*result[1] == 2, 'stride y = 2');\n        assert(*result[2] == 1, 'stride z = 1');\n        assert(result.len() == 3, 'len = 3');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/orion",
        "file_path": "tests/tensor_core/unravel_index.cairo",
        "content": "// ===== 1D ===== //\n\n#[cfg(test)]\nmod tensor_1D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::core::{unravel_index};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_unravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(5);\n        let result = unravel_index(2, shape.span());\n        assert(*result[0] == 2, 'result[0] = 2');\n    }\n}\n\n// ===== 2D ===== //\n\n#[cfg(test)]\nmod tensor_2D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::core::{unravel_index};\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_unravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(2);\n        shape.append(4);\n        let result = unravel_index(6, shape.span());\n        assert(*result[0] == 1, 'result[0] = 1');\n        assert(*result[1] == 2, 'result[1] = 2');\n    }\n}\n\n// ===== 3D ===== //\n\n#[cfg(test)]\nmod tensor_3D {\n    use core::array::ArrayTrait;\n    use core::array::SpanTrait;\n\n    use orion::operators::tensor::core::{unravel_index};\n\n\n    #[test]\n    #[available_gas(2000000)]\n    fn tensor_unravel_index() {\n        let mut shape = ArrayTrait::new();\n        shape.append(2);\n        shape.append(4);\n        shape.append(6);\n        let result = unravel_index(42, shape.span());\n        assert(*result[0] == 1, 'result[0] = 1');\n        assert(*result[1] == 3, 'result[1] = 3');\n        assert(*result[2] == 0, 'result[2] = 0');\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/action_agent.py",
        "content": "import argparse\nimport os\nimport pprint\n\nimport numpy as np\nfrom addresses import ADDRESSES\nfrom dotenv import find_dotenv, load_dotenv\nfrom giza_actions.action import action\nfrom giza_actions.agent import AgentResult, GizaAgent\nfrom giza_actions.task import task\nfrom lp_tools import get_tick_range\nfrom prefect import get_run_logger\nfrom uni_helpers import (\n    approve_token,\n    check_allowance,\n    close_position,\n    get_all_user_positions,\n    get_mint_params,\n)\n\nload_dotenv(find_dotenv())\n\nos.environ[\"DEV_PASSPHRASE\"] = os.environ.get(\"DEV_PASSPHRASE\")\nsepolia_rpc_url = os.environ.get(\"SEPOLIA_RPC_URL\")\n\n\n@task(name=\"Data processing\")\ndef process_data(realized_vol: float, dec_price_change: float):\n    pct_change_sq = (100 * dec_price_change) ** 2\n    X = np.array([[realized_vol, pct_change_sq]])\n    return X\n\n\n@task(name=\"Get volatility and price change data\")\ndef get_data():\n    # TODO: implement fetching onchain or from some other source\n    # hardcoding the values for now\n    realized_vol = 4.20\n    dec_price_change = 0.1\n    return realized_vol, dec_price_change\n\n\n@task(name=\"Create a Giza agent for the Volatility prediction model\")\ndef create_agent(\n    model_id: int, version_id: int, chain: str, contracts: dict, account: str\n):\n    \"\"\"\n    Create a Giza agent for the volatility prediction model\n    \"\"\"\n    agent = GizaAgent(\n        contracts=contracts,\n        id=model_id,\n        version_id=version_id,\n        chain=chain,\n        account=account,\n    )\n    return agent\n\n\n@task(name=\"Run the volatility prediction model\")\ndef predict(agent: GizaAgent, X: np.ndarray):\n    \"\"\"\n    Predict the next day volatility.\n\n    Args:\n        X (np.ndarray): Input to the model.\n\n    Returns:\n        int: Predicted value.\n    \"\"\"\n    prediction = agent.predict(input_feed={\"val\": X}, verifiable=True, job_size=\"XL\")\n    return prediction\n\n\n@task(name=\"Verify the inference proof and return the predicted value\")\ndef get_pred_val(prediction: AgentResult):\n    \"\"\"\n    Get the value from the prediction.\n\n    Args:\n        prediction (dict): Prediction from the model.\n\n    Returns:\n        int: Predicted value.\n    \"\"\"\n    # This will block the executon until the prediction has generated the proof\n    # and the proof has been verified\n    return prediction.value[0][0]\n\n\n# Create Action\n@action(log_prints=True)\ndef rebalance_lp(\n    tokenA_amount: int,\n    tokenB_amount: int,\n    pred_model_id: int,\n    pred_version_id: int,\n    account=\"dev\",\n    chain=f\"ethereum:sepolia:{sepolia_rpc_url}\",\n    nft_id=None,\n):\n    logger = get_run_logger()\n    nft_manager_address = ADDRESSES[\"NonfungiblePositionManager\"][11155111]\n    tokenA_address = ADDRESSES[\"UNI\"][11155111]\n    tokenB_address = ADDRESSES[\"WETH\"][11155111]\n    pool_address = \"0x287B0e934ed0439E2a7b1d5F0FC25eA2c24b64f7\"\n    user_address = \"0xCBB090699E0664f0F6A4EFbC616f402233718152\"\n    pool_fee = 3000\n    logger.info(\"Fetching input data\")\n    realized_vol, dec_price_change = get_data()\n    logger.info(f\"Input data: {realized_vol}, {dec_price_change}\")\n    X = process_data(realized_vol, dec_price_change)\n    contracts = {\n        \"nft_manager\": nft_manager_address,\n        \"tokenA\": tokenA_address,\n        \"tokenB\": tokenB_address,\n        \"pool\": pool_address,\n    }\n    agent = create_agent(\n        model_id=pred_model_id,\n        version_id=pred_version_id,\n        chain=chain,\n        contracts=contracts,\n        account=account,\n    )\n    result = predict(agent, X)\n    predicted_value = get_pred_val(result)\n    logger.info(f\"Result: {result}\")\n    with agent.execute() as contracts:\n        logger.info(\"Executing contract\")\n        if nft_id is None:\n            positions = [\n                max(get_all_user_positions(contracts.nft_manager, user_address))\n            ]\n        else:\n            positions = [nft_id]\n        logger.info(f\"Closing the following positions {positions}\")\n        for nft_id in positions:\n            close_position(user_address, contracts.nft_manager, nft_id)\n        logger.info(\"Calculating mint params...\")\n        _, curr_tick, _, _, _, _, _ = contracts.pool.slot0()\n        if not check_allowance(\n            contracts.tokenA, nft_manager_address, account, tokenA_amount\n        ):\n            approve_token(contracts.tokenA, nft_manager_address, tokenA_amount)\n        if not check_allowance(\n            contracts.tokenB, nft_manager_address, account, tokenB_amount\n        ):\n            approve_token(contracts.tokenB, nft_manager_address, tokenB_amount)\n        tokenA_decimals = contracts.tokenA.decimals()\n        tokenB_decimals = contracts.tokenB.decimals()\n        predicted_value = predicted_value / 100 * 1.96  # convert to decimal %\n        lower_tick, upper_tick = get_tick_range(\n            curr_tick, predicted_value, tokenA_decimals, tokenB_decimals, pool_fee\n        )\n        mint_params = get_mint_params(\n            user_address,\n            contracts.tokenA.address,\n            contracts.tokenB.address,\n            tokenA_amount,\n            tokenB_amount,\n            pool_fee,\n            lower_tick,\n            upper_tick,\n        )\n        # step 5: mint new position\n        logger.info(\"Minting new position...\")\n        contract_result = contracts.nft_manager.mint(mint_params)\n        logger.info(\"SUCCESSFULLY MINTED A POSITION\")\n        logger.info(\"Contract executed\")\n\n    logger.info(f\"Contract result: {contract_result}\")\n    pprint.pprint(contract_result.__dict__)\n    logger.info(\"Finished\")\n\n\nif __name__ == \"__main__\":\n    # Create the parser\n    parser = argparse.ArgumentParser()\n\n    # Add arguments\n    parser.add_argument(\"--model-id\", metavar=\"M\", type=int, help=\"model-id\")\n    parser.add_argument(\"--version-id\", metavar=\"V\", type=int, help=\"version-id\")\n    parser.add_argument(\"--tokenA-amount\", metavar=\"A\", type=int, help=\"tokenA-amount\")\n    parser.add_argument(\"--tokenB-amount\", metavar=\"B\", type=int, help=\"tokenB-amount\")\n\n    # Parse arguments\n    args = parser.parse_args()\n\n    MODEL_ID = args.model_id\n    VERSION_ID = args.version_id\n    tokenA_amount = args.tokenA_amount\n    tokenB_amount = args.tokenB_amount\n\n    rebalance_lp(tokenA_amount, tokenB_amount, MODEL_ID, VERSION_ID)\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/addresses.py",
        "content": "# source: https://docs.uniswap.org/contracts/v3/reference/deployments\nADDRESSES = {\n    \"WETH\": {\n        1: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\",\n        11155111: \"0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14\",\n        5: \"0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6\",\n        42161: \"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1\",\n    },\n    \"UNI\": {\n        1: \"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984\",\n        11155111: \"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984\",\n        5: \"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984\",\n        42161: \"0xFa7F8980b0f1E64A2062791cc3b0871572f1F7f0\",\n    },\n    \"USDC\": {\n        1: \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\",\n        11155111: \"0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238\",\n        5: \"\",\n        42161: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n    },\n    \"NonfungiblePositionManager\": {\n        1: \"0xC36442b4a4522E871399CD717aBDD847Ab11FE88\",\n        11155111: \"0x1238536071E1c677A632429e3655c799b22cDA52\",\n        5: \"0xC36442b4a4522E871399CD717aBDD847Ab11FE88\",\n        42161: \"0xC36442b4a4522E871399CD717aBDD847Ab11FE88\",\n    },\n    \"PoolFactory\": {\n        1: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\",\n        11155111: \"0x0227628f3F023bb0B980b67D528571c95c6DaC1c\",\n        5: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\",\n        42161: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\",\n    },\n    \"Router\": {\n        1: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n        11155111: \"0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E\",\n        5: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n        42161: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n    },\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/get_tokens.py",
        "content": "import os\n\nfrom addresses import ADDRESSES\nfrom ape import Contract, accounts, chain, networks\nfrom dotenv import find_dotenv, load_dotenv\n\nload_dotenv(find_dotenv())\n\ndev_passphrase = os.environ.get(\"DEV_PASSPHRASE\")\nsepolia_rpc_url = os.environ.get(\"SEPOLIA_RPC_URL\")\n\nif __name__ == \"__main__\":\n    networks.parse_network_choice(f\"ethereum:sepolia:{sepolia_rpc_url}\").__enter__()\n    chain_id = chain.chain_id\n    weth_mint_amount = 0.0001\n    pool_fee = 3000\n    uni = Contract(ADDRESSES[\"UNI\"][chain_id])\n    weth = Contract(ADDRESSES[\"WETH\"][chain_id])\n    weth_decimals = weth.decimals()\n    uni_decimals = uni.decimals()\n    weth_mint_amount = int(weth_mint_amount * 10**weth_decimals)\n    uni_mint_amount = int(0.5 * weth_mint_amount)\n\n    pool_factory = Contract(ADDRESSES[\"PoolFactory\"][chain_id])\n    pool_address = \"0x287B0e934ed0439E2a7b1d5F0FC25eA2c24b64f7\"\n    pool = Contract(pool_address)\n    swap_router = Contract(ADDRESSES[\"Router\"][chain_id])\n    wallet = accounts.load(\"dev\")\n    wallet.set_autosign(True, passphrase=dev_passphrase)\n    with accounts.use_sender(\"dev\"):\n        print(f\"Minting {weth_mint_amount/10**weth_decimals} WETH\")\n        weth.deposit(value=weth_mint_amount)\n        print(\"Approving WETH for swap\")\n        weth.approve(swap_router.address, weth_mint_amount)\n        swap_params = {\n            \"tokenIn\": weth.address,\n            \"tokenOut\": uni.address,\n            \"fee\": pool_fee,\n            \"recipient\": wallet.address,\n            \"amountIn\": weth_mint_amount,\n            \"amountOutMinimum\": 0,\n            \"sqrtPriceLimitX96\": 0,\n        }\n        swap_params = tuple(swap_params.values())\n        print(\"Swapping WETH for UNI\")\n        amountOut = swap_router.exactInputSingle(swap_params)\n        print(f\"Successfully minted {uni_mint_amount/10**uni_decimals} UNI\")\n\n    print(f\"Your WETH balance: {weth.balanceOf(wallet.address)/10**weth_decimals}\")\n    print(f\"Your UNI balance: {uni.balanceOf(wallet.address)/10**uni_decimals}\")\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/lp_tools.py",
        "content": "import math\n\nMIN_TICK = -887272\nMAX_TICK = -MIN_TICK\nTICKS_Q = 1.0001\nQ96 = 2**96\nMAX_UINT_128 = 2 ** (128) - 1\n_tick_spacing = {100: 1, 500: 10, 3_000: 60, 10_000: 200}\n\n# https://ethereum.stackexchange.com/questions/150280/calculate-amount-of-eth-and-usdc-after-minting-a-position-in-uniswap-v3\n\n\ndef price_to_tick(price):\n    sqrtPriceX96 = int(price * 2**96)\n    tick = math.floor(math.log((sqrtPriceX96 / Q96) ** 2) / math.log(TICKS_Q))\n    return tick\n\n\ndef tick_to_price(tick, decimals0, decimals1, invert=False):\n    if invert:\n        return 1 / (TICKS_Q**tick / 10 ** (decimals1 - decimals0))\n    else:\n        return TICKS_Q**tick / 10 ** (decimals1 - decimals0)\n\n\ndef get_min_tick(fee: int):\n    min_tick_spacing: int = _tick_spacing[fee]\n    return -(MIN_TICK // -min_tick_spacing) * min_tick_spacing\n\n\ndef get_max_tick(fee: int):\n    max_tick_spacing: int = _tick_spacing[fee]\n    return (MAX_TICK // max_tick_spacing) * max_tick_spacing\n\n\ndef default_tick_range(fee: int):\n    min_tick = get_min_tick(fee)\n    max_tick = get_max_tick(fee)\n    return min_tick, max_tick\n\n\ndef nearest_tick(tick: int, fee: int):\n    min_tick, max_tick = default_tick_range(fee)\n    assert (\n        min_tick <= tick <= max_tick\n    ), f\"Provided tick is out of bounds: {(min_tick, max_tick)}\"\n    tick_spacing = _tick_spacing[fee]\n    rounded_tick_spacing = round(tick / tick_spacing) * tick_spacing\n    if rounded_tick_spacing < min_tick:\n        return rounded_tick_spacing + tick_spacing\n    elif rounded_tick_spacing > max_tick:\n        return rounded_tick_spacing - tick_spacing\n    else:\n        return rounded_tick_spacing\n\n\ndef get_tick_range(curr_tick, pct_dev, tokenA_decimals, tokenB_decimals, fee):\n    curr_price = tick_to_price(curr_tick, tokenA_decimals, tokenB_decimals)\n    upper_price = curr_price * (1 + pct_dev)\n    lower_price = curr_price * (1 - pct_dev)\n    lower_tick = price_to_tick(lower_price)\n    upper_tick = price_to_tick(upper_price)\n    lower_tick = nearest_tick(lower_tick, fee)\n    upper_tick = nearest_tick(upper_tick, fee)\n    return lower_tick, upper_tick\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/model_training.py",
        "content": "import datetime\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport yfinance as yf\nfrom sklearn.metrics import mean_squared_error as mse\n\n\ndef download_data():\n    uni_ticker = \"UNI-USD\"\n    eth_ticker = \"ETH-USD\"\n    start = datetime.datetime(2019, 1, 1)\n    end = datetime.datetime(2024, 4, 1)\n    uni = yf.download(uni_ticker, start=start, end=end, interval=\"1d\")\n    eth = yf.download(eth_ticker, start=start, end=end, interval=\"1d\")\n    uni = uni.reset_index()\n    uni.to_csv(\"uni.csv\", index=False)\n    eth = eth.reset_index()\n    eth.to_csv(\"eth.csv\", index=False)\n    return uni, eth\n\n\ndef process_data(uni: pd.DataFrame, eth: pd.DataFrame):\n    uni = uni[uni[\"Open\"] < 0.30]\n    uni = uni[[\"Date\", \"Open\"]]\n    eth = eth[[\"Date\", \"Open\"]]\n\n    uni.rename(columns={\"Open\": \"UNI\"}, inplace=True)\n    eth.rename(columns={\"Open\": \"ETH\"}, inplace=True)\n\n    df = pd.merge(uni, eth, on=\"Date\")\n    df.dropna(inplace=True)\n    df[\"price\"] = df[\"ETH\"] / df[\"UNI\"]\n    ret = 100 * (df[\"price\"].pct_change()[1:])\n    realized_vol = ret.rolling(5).std()\n    realized_vol = pd.DataFrame(realized_vol)\n    realized_vol.reset_index(drop=True, inplace=True)\n    returns_svm = ret**2  # returns squared\n    returns_svm = returns_svm.reset_index()\n    X = pd.concat([realized_vol, returns_svm], axis=1, ignore_index=True)\n    X = X[4:].copy()\n    X = X.reset_index()\n    X.drop(\"index\", axis=1, inplace=True)\n    X.drop(1, axis=1, inplace=True)\n    X.rename(columns={0: \"realized_vol\", 2: \"returns_squared\"}, inplace=True)\n    X[\"target\"] = X[\"realized_vol\"].shift(-5)\n    X.dropna(inplace=True)\n    Y = X[\"target\"]\n    X.drop(\"target\", axis=1, inplace=True)\n    n = 252\n    X_train = X.iloc[:-n]\n    X_test = X.iloc[-n:]\n    Y_train = Y.iloc[:-n]\n    Y_test = Y.iloc[-n:]\n    return X_train, X_test, Y_train, Y_test\n\n\ndef train_model(\n    X_train: pd.DataFrame,\n    X_test: pd.DataFrame,\n    Y_train: pd.DataFrame,\n    Y_test: pd.DataFrame,\n):\n    model = nn.Sequential(\n        nn.Linear(X_train.shape[1], 128),\n        nn.ReLU(),\n        nn.Linear(128, 64),\n        nn.ReLU(),\n        nn.Linear(64, 1),\n    )\n\n    # Loss and optimizer\n    criterion = nn.MSELoss()\n    optimizer = optim.RMSprop(model.parameters())\n\n    # Convert data to PyTorch tensors\n    X_tensor = torch.tensor(X_train.values, dtype=torch.float32)\n    y_tensor = torch.tensor(Y_train.values.reshape(-1, 1), dtype=torch.float32)\n    X_test_tensor = torch.tensor(X_test.values, dtype=torch.float32)\n\n    # Training loop\n    epochs_trial = np.arange(100, 400, 4)\n    batch_trial = np.arange(100, 400, 4)\n    DL_pred = []\n    DL_RMSE = []\n\n    for i, j, k in zip(range(4), epochs_trial, batch_trial):\n        for epoch in range(j):\n            optimizer.zero_grad()\n            outputs = model(X_tensor)\n            loss = criterion(outputs, y_tensor)\n            loss.backward()\n            optimizer.step()\n\n        with torch.no_grad():\n            DL_predict = model(X_test_tensor).numpy()\n            DL_RMSE.append(\n                np.sqrt(mse(Y_test.values / 100, DL_predict.flatten() / 100))\n            )\n            DL_pred.append(DL_predict)\n            print(\"DL_RMSE_{}:{:.6f}\".format(i + 1, DL_RMSE[i]))\n\n    return model\n\n\ndef serialize_to_onnx(\n    model: nn.Module, X_train: pd.DataFrame, save_path=\"torch_vol_model\"\n):\n    # Ensure the model is in evaluation mode\n    model.eval()\n\n    # Dummy input matching the input size\n    sample_input = torch.randn(\n        1, X_train.shape[1]\n    )  # Replace 1 with the batch size you'd like to use\n\n    # Specify the path to save the ONNX model\n    onnx_file_path = save_path + \".onnx\"\n\n    torch.onnx.export(\n        model,\n        sample_input,\n        onnx_file_path,\n        export_params=True,\n        opset_version=10,\n        do_constant_folding=True,\n        input_names=[\"input\"],\n        output_names=[\"output\"],\n        dynamic_axes={\n            \"input\": {0: \"batch_size\"},\n            \"output\": {0: \"batch_size\"},\n        },\n    )\n    print(f\"Saved serialized ONNX model to {onnx_file_path}.\")\n\n\ndef main():\n    uni, eth = download_data()\n    X_train, X_test, Y_train, Y_test = process_data(uni, eth)\n    model = train_model(X_train, X_test, Y_train, Y_test)\n    serialize_to_onnx(model, X_train)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-giza-agents/uni-v3-lp-agent/uni_helpers.py",
        "content": "import os\nimport time\n\nfrom ape.contracts.base import ContractInstance\nfrom dotenv import find_dotenv, load_dotenv\nfrom giza_actions.task import task\nfrom lp_tools import MAX_UINT_128\n\nload_dotenv(find_dotenv())\n\ndev_passphrase = os.environ.get(\"DEV_PASSPHRASE\")\nsepolia_rpc_url = os.environ.get(\"SEPOLIA_RPC_URL\")\n\n\n@task(name=\"Check allowance\")\ndef check_allowance(token: ContractInstance, spender: str, account: str, amount: int):\n    return token.allowance(account, spender) >= amount\n\n\n@task(name=\"Approve token spend\")\ndef approve_token(token: ContractInstance, spender: str, amount: int):\n    return token.approve(spender, amount)\n\n\n@task(name=\"Get mint parameters\")\ndef get_mint_params(\n    user_address: str,\n    tokenA_address: str,\n    tokenB_address: str,\n    amount0: int,\n    amount1: int,\n    pool_fee: int,\n    lower_tick: int,\n    upper_tick: int,\n    deadline=None,\n    slippage_tolerance=0.01,\n):\n    if deadline is None:\n        deadline = int(time.time()) + 60\n    mint_params = {\n        \"token0\": tokenA_address,\n        \"token1\": tokenB_address,\n        \"fee\": pool_fee,\n        \"tickLower\": lower_tick,\n        \"tickUpper\": upper_tick,\n        \"amount0Desired\": amount0,\n        \"amount1Desired\": amount1,\n        \"amount0Min\": 0,  # int(amount0 * (1 - slippage_tolerance)),\n        \"amount1Min\": 0,  # int(amount1 * (1 - slippage_tolerance)),\n        \"recipient\": user_address,\n        \"deadline\": deadline,\n    }\n    return tuple(mint_params.values())\n\n\n@task(name=\"Get all user LP positions\")\ndef get_all_user_positions(nft_manager: ContractInstance, user_address: str):\n    n_positions = nft_manager.balanceOf(user_address)\n    positions = []\n    for n in range(n_positions):\n        position = nft_manager.tokenOfOwnerByIndex(user_address, n)\n        positions.append(position)\n    return positions\n\n\ndef get_pos_liquidity(nft_manager: ContractInstance, nft_id: int):\n    (\n        nonce,\n        operator,\n        token0,\n        token1,\n        fee,\n        tickLower,\n        tickUpper,\n        liquidity,\n        feeGrowthInside0LastX128,\n        feeGrowthInside1LastX128,\n        tokensOwed0,\n        tokensOwed1,\n    ) = nft_manager.positions(nft_id)\n    return liquidity\n\n\n@task(name=\"Close the position\")\ndef close_position(user_address: str, nft_manager: ContractInstance, nft_id: int):\n    liq = get_pos_liquidity(nft_manager, nft_id)\n    if liq > 0:\n        nft_manager.decreaseLiquidity((nft_id, liq, 0, 0, int(time.time() + 60)))\n        nft_manager.collect((nft_id, user_address, MAX_UINT_128, MAX_UINT_128))\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/QAT_MNIST_MLP.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"04w3OowXkaQh\"\n      },\n      \"source\": [\n        \"# Build Your Neural Network In Cairo 1.0 with Orion\\n\",\n        \"\\n\",\n        \"Orion is a dedicated Cairo-based library designed specifically to build machine learning models for ValidityML. Its purpose is to facilitate verifiable inference. For better performance we will operate with an 8-bit quantized model. In this tutorial, you will be guided on how to train your model using Quantized Aware Training using MNIST dataset, how to convert your pre-trained model to Cairo 1, and how to perform inference with Orion.\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"## Install Dependecies, Rust, Cairo and Scarb\\n\",\n        \"Let's start by installing all dependecies.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 1,\n      \"metadata\": {\n        \"id\": \"1Sfci39Llvii\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Requirement already satisfied: numpy in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (1.24.3)\\n\",\n            \"Requirement already satisfied: tensorflow in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (2.13.0rc1)\\n\",\n            \"Requirement already satisfied: tensorflow_model_optimization in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (0.7.5)\\n\",\n            \"Requirement already satisfied: matplotlib in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (3.7.1)\\n\",\n            \"Requirement already satisfied: scipy in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (1.10.1)\\n\",\n            \"Requirement already satisfied: tensorflow-macos==2.13.0-rc1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow) (2.13.0rc1)\\n\",\n            \"Requirement already satisfied: six>=1.12.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (1.16.0)\\n\",\n            \"Requirement already satisfied: google-pasta>=0.1.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (0.2.0)\\n\",\n            \"Requirement already satisfied: typing-extensions>=3.6.6 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (4.6.3)\\n\",\n            \"Requirement already satisfied: keras<2.14,>=2.13.1rc0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (2.13.1rc0)\\n\",\n            \"Requirement already satisfied: gast<=0.4.0,>=0.2.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (0.4.0)\\n\",\n            \"Requirement already satisfied: grpcio<2.0,>=1.24.3 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (1.54.2)\\n\",\n            \"Requirement already satisfied: tensorflow-estimator<2.14,>=2.13.0rc0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (2.13.0rc0)\\n\",\n            \"Requirement already satisfied: flatbuffers>=23.1.21 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (23.5.26)\\n\",\n            \"Requirement already satisfied: opt-einsum>=2.3.2 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (3.3.0)\\n\",\n            \"Requirement already satisfied: libclang>=13.0.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (16.0.0)\\n\",\n            \"Requirement already satisfied: tensorboard<2.14,>=2.13 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (2.13.0)\\n\",\n            \"Requirement already satisfied: termcolor>=1.1.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (2.3.0)\\n\",\n            \"Requirement already satisfied: packaging in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (23.1)\\n\",\n            \"Requirement already satisfied: setuptools in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (67.8.0)\\n\",\n            \"Requirement already satisfied: h5py>=2.9.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (3.8.0)\\n\",\n            \"Requirement already satisfied: wrapt>=1.11.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (1.15.0)\\n\",\n            \"Requirement already satisfied: astunparse>=1.6.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (1.6.3)\\n\",\n            \"Requirement already satisfied: absl-py>=1.0.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (1.4.0)\\n\",\n            \"Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow-macos==2.13.0-rc1->tensorflow) (4.23.2)\\n\",\n            \"Requirement already satisfied: dm-tree~=0.1.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorflow_model_optimization) (0.1.8)\\n\",\n            \"Requirement already satisfied: contourpy>=1.0.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (1.0.7)\\n\",\n            \"Requirement already satisfied: pyparsing>=2.3.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (3.0.9)\\n\",\n            \"Requirement already satisfied: pillow>=6.2.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (9.5.0)\\n\",\n            \"Requirement already satisfied: kiwisolver>=1.0.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (1.4.4)\\n\",\n            \"Requirement already satisfied: fonttools>=4.22.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (4.39.4)\\n\",\n            \"Requirement already satisfied: python-dateutil>=2.7 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (2.8.2)\\n\",\n            \"Requirement already satisfied: cycler>=0.10 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from matplotlib) (0.11.0)\\n\",\n            \"Requirement already satisfied: wheel<1.0,>=0.23.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from astunparse>=1.6.0->tensorflow-macos==2.13.0-rc1->tensorflow) (0.38.4)\\n\",\n            \"Requirement already satisfied: markdown>=2.6.8 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (3.4.3)\\n\",\n            \"Requirement already satisfied: google-auth-oauthlib<1.1,>=0.5 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (1.0.0)\\n\",\n            \"Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (0.7.0)\\n\",\n            \"Requirement already satisfied: requests<3,>=2.21.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (2.31.0)\\n\",\n            \"Requirement already satisfied: werkzeug>=1.0.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (2.3.5)\\n\",\n            \"Requirement already satisfied: google-auth<3,>=1.6.3 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (2.19.1)\\n\",\n            \"Requirement already satisfied: urllib3<2.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (1.26.16)\\n\",\n            \"Requirement already satisfied: pyasn1-modules>=0.2.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (0.3.0)\\n\",\n            \"Requirement already satisfied: rsa<5,>=3.1.4 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (4.9)\\n\",\n            \"Requirement already satisfied: cachetools<6.0,>=2.0.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (5.3.1)\\n\",\n            \"Requirement already satisfied: requests-oauthlib>=0.7.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from google-auth-oauthlib<1.1,>=0.5->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (1.3.1)\\n\",\n            \"Requirement already satisfied: charset-normalizer<4,>=2 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from requests<3,>=2.21.0->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (3.1.0)\\n\",\n            \"Requirement already satisfied: certifi>=2017.4.17 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from requests<3,>=2.21.0->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (2023.5.7)\\n\",\n            \"Requirement already satisfied: idna<4,>=2.5 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from requests<3,>=2.21.0->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (3.4)\\n\",\n            \"Requirement already satisfied: MarkupSafe>=2.1.1 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from werkzeug>=1.0.1->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (2.1.3)\\n\",\n            \"Requirement already satisfied: pyasn1<0.6.0,>=0.4.6 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (0.5.0)\\n\",\n            \"Requirement already satisfied: oauthlib>=3.0.0 in /Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<1.1,>=0.5->tensorboard<2.14,>=2.13->tensorflow-macos==2.13.0-rc1->tensorflow) (3.2.2)\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"import sys\\n\",\n        \"!{sys.executable} -m pip install numpy tensorflow tensorflow_model_optimization matplotlib scipy\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"GwTsquVDEe4p\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"!curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"uBsZQCRBExEc\",\n        \"outputId\": \"54cbbc65-854e-4afa-b809-d2fc838f6ecf\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Create .cairo folder if it doesn't exist yet\\n\",\n        \"! mkdir $HOME/.cairo\\n\",\n        \"\\n\",\n        \"! source \\\"$HOME/.cargo/env\\\"\\n\",\n        \"\\n\",\n        \"# Clone the Cairo compiler in $CAIRO_ROOT (default root)\\n\",\n        \"! cd $HOME/.cairo && git clone https://github.com/starkware-libs/cairo.git .\\n\",\n        \"\\n\",\n        \"# OPTIONAL/RECOMMENDED: If you want to install a specific version of the compiler\\n\",\n        \"# Fetch all tags (versions)\\n\",\n        \"! git fetch --all --tags\\n\",\n        \"# View tags (you can also do this in the cairo compiler repository)\\n\",\n        \"! git describe --tags `git rev-list --tags`\\n\",\n        \"# Checkout the version you want\\n\",\n        \"! git checkout tags/v1.1.0\\n\",\n        \"\\n\",\n        \"# Generate release binaries\\n\",\n        \"! cd $HOME/.cairo && $HOME/.cargo/bin/cargo build --all --release\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# Install Scarb\\n\",\n        \"! curl --proto '=https' --tlsv1.2 -sSf https://docs.swmansion.com/scarb/install.sh | sh\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"## Train and Test your Neural Network with Tensorflow\\n\",\n        \"In this section we will use Tensorflow to train and test a feedforward neural network with MNIST dataset.\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"nKiq8oKxklon\"\n      },\n      \"source\": [\n        \"### Dataset Preparation\\n\",\n        \"Import the required libraries and load the dataset.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 2,\n      \"metadata\": {\n        \"id\": \"4po2PWTAkWOR\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from tensorflow import keras\\n\",\n        \"from keras.datasets import mnist\\n\",\n        \"from scipy.ndimage import zoom\\n\",\n        \"import numpy as np\\n\",\n        \"\\n\",\n        \"(x_train, y_train), (x_test, y_test) = mnist.load_data()\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"NXigQHM_k0ux\"\n      },\n      \"source\": [\n        \"We have a total of 70,000 grayscale images, each with a dimension of 28 x 28 pixels. 60,000 images are for training and the remaining 10,000 are for testing. \\n\",\n        \"\\n\",\n        \"We now need to pre-process our data. For the purposes of this tutorial and performance, we'll resize the images to 14 x 14 pixels. You'll see later that the neural network's input layer supports a 1D tensor. We, therefore, need to flatten and normalize our data.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 3,\n      \"metadata\": {\n        \"id\": \"6AwxawnnkaA5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from scipy.ndimage import zoom\\n\",\n        \"\\n\",\n        \"# Resizing function\\n\",\n        \"def resize_images(images):\\n\",\n        \"    return np.array([zoom(image, 0.5) for image in images])\\n\",\n        \"\\n\",\n        \"# Resize\\n\",\n        \"x_train = resize_images(x_train)\\n\",\n        \"x_test = resize_images(x_test)\\n\",\n        \"\\n\",\n        \"# Then reshape\\n\",\n        \"x_train = x_train.reshape(60000, 14*14)\\n\",\n        \"x_test = x_test.reshape(10000, 14*14)\\n\",\n        \"x_train = x_train.astype('float32')\\n\",\n        \"x_test = x_test.astype('float32')\\n\",\n        \"\\n\",\n        \"# normalize to range [0, 1]\\n\",\n        \"x_train /= 255\\n\",\n        \"x_test /= 255\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"ix3qnUgElDlB\"\n      },\n      \"source\": [\n        \"### Model Definition and Training\\n\",\n        \"We will design a straightforward feedforward neural network.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 4,\n      \"metadata\": {\n        \"id\": \"7gilDCS6k9-u\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from tensorflow.keras import layers\\n\",\n        \"\\n\",\n        \"num_classes = 10\\n\",\n        \"\\n\",\n        \"model = keras.Sequential([\\n\",\n        \"    keras.layers.InputLayer(input_shape=(14*14,)),\\n\",\n        \"    keras.layers.Dense(10, activation='relu'), \\n\",\n        \"    keras.layers.Dense(10, activation='softmax')\\n\",\n        \"])\\n\",\n        \"\\n\",\n        \"model.compile(optimizer='adam', \\n\",\n        \"              loss='sparse_categorical_crossentropy', \\n\",\n        \"              metrics=['accuracy'])\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"BFUZZOudlQmP\"\n      },\n      \"source\": [\n        \"Now let's train this model on our training data.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 5,\n      \"metadata\": {\n        \"id\": \"jjkH102GlOd2\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Epoch 1/10\\n\",\n            \"1500/1500 [==============================] - 1s 449us/step - loss: 0.8094 - accuracy: 0.7795 - val_loss: 0.3885 - val_accuracy: 0.8953\\n\",\n            \"Epoch 2/10\\n\",\n            \"1500/1500 [==============================] - 1s 399us/step - loss: 0.3693 - accuracy: 0.8961 - val_loss: 0.3152 - val_accuracy: 0.9122\\n\",\n            \"Epoch 3/10\\n\",\n            \"1500/1500 [==============================] - 1s 402us/step - loss: 0.3239 - accuracy: 0.9072 - val_loss: 0.2905 - val_accuracy: 0.9185\\n\",\n            \"Epoch 4/10\\n\",\n            \"1500/1500 [==============================] - 1s 403us/step - loss: 0.3041 - accuracy: 0.9130 - val_loss: 0.2842 - val_accuracy: 0.9192\\n\",\n            \"Epoch 5/10\\n\",\n            \"1500/1500 [==============================] - 1s 428us/step - loss: 0.2931 - accuracy: 0.9162 - val_loss: 0.2716 - val_accuracy: 0.9237\\n\",\n            \"Epoch 6/10\\n\",\n            \"1500/1500 [==============================] - 1s 406us/step - loss: 0.2849 - accuracy: 0.9193 - val_loss: 0.2689 - val_accuracy: 0.9228\\n\",\n            \"Epoch 7/10\\n\",\n            \"1500/1500 [==============================] - 1s 407us/step - loss: 0.2791 - accuracy: 0.9202 - val_loss: 0.2645 - val_accuracy: 0.9259\\n\",\n            \"Epoch 8/10\\n\",\n            \"1500/1500 [==============================] - 1s 401us/step - loss: 0.2747 - accuracy: 0.9215 - val_loss: 0.2608 - val_accuracy: 0.9269\\n\",\n            \"Epoch 9/10\\n\",\n            \"1500/1500 [==============================] - 1s 401us/step - loss: 0.2705 - accuracy: 0.9226 - val_loss: 0.2585 - val_accuracy: 0.9283\\n\",\n            \"Epoch 10/10\\n\",\n            \"1500/1500 [==============================] - 1s 401us/step - loss: 0.2674 - accuracy: 0.9236 - val_loss: 0.2582 - val_accuracy: 0.9283\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"batch_size = 256\\n\",\n        \"epochs = 10\\n\",\n        \"history = model.fit(x_train, y_train,\\n\",\n        \"                    epochs=epochs,\\n\",\n        \"                    validation_split=0.2)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"uNRdKGpflar4\"\n      },\n      \"source\": [\n        \"At this point, we have trained a regular model.\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"7Bu55FCqlbj4\"\n      },\n      \"source\": [\n        \"### Making the Model Quantization Aware\\n\",\n        \"Now, let's transform our model into a quantization aware model. We use the TensorFlow Model Optimization Toolkit for this.\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 6,\n      \"metadata\": {\n        \"id\": \"iAZYo9vKlTHK\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Model: \\\"sequential\\\"\\n\",\n            \"_________________________________________________________________\\n\",\n            \" Layer (type)                Output Shape              Param #   \\n\",\n            \"=================================================================\\n\",\n            \" quantize_layer (QuantizeLa  (None, 196)               3         \\n\",\n            \" yer)                                                            \\n\",\n            \"                                                                 \\n\",\n            \" quant_dense (QuantizeWrapp  (None, 10)                1975      \\n\",\n            \" erV2)                                                           \\n\",\n            \"                                                                 \\n\",\n            \" quant_dense_1 (QuantizeWra  (None, 10)                115       \\n\",\n            \" pperV2)                                                         \\n\",\n            \"                                                                 \\n\",\n            \"=================================================================\\n\",\n            \"Total params: 2093 (8.18 KB)\\n\",\n            \"Trainable params: 2080 (8.12 KB)\\n\",\n            \"Non-trainable params: 13 (52.00 Byte)\\n\",\n            \"_________________________________________________________________\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"import tensorflow_model_optimization as tfmot\\n\",\n        \"\\n\",\n        \"# Apply quantization to the layers\\n\",\n        \"quantize_model = tfmot.quantization.keras.quantize_model\\n\",\n        \"\\n\",\n        \"# q_aware stands for 'quantization aware'\\n\",\n        \"q_aware_model = quantize_model(model)\\n\",\n        \"\\n\",\n        \"# 'quantize_model' requires a recompile\\n\",\n        \"q_aware_model.compile(optimizer='adam',\\n\",\n        \"                      loss='sparse_categorical_crossentropy',\\n\",\n        \"                      metrics=['accuracy'])\\n\",\n        \"\\n\",\n        \"q_aware_model.summary()\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"eYPUWWwTl_np\"\n      },\n      \"source\": [\n        \"We have now created a new model, q_aware_model, which is a quantization aware version of our original model. Now we can train this model exactly like our original model.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 7,\n      \"metadata\": {\n        \"id\": \"U-t5MPhGlqoI\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Epoch 1/10\\n\",\n            \"1500/1500 [==============================] - 1s 526us/step - loss: 0.2671 - accuracy: 0.9236 - val_loss: 0.2581 - val_accuracy: 0.9283\\n\",\n            \"Epoch 2/10\\n\",\n            \"1500/1500 [==============================] - 1s 478us/step - loss: 0.2625 - accuracy: 0.9235 - val_loss: 0.2538 - val_accuracy: 0.9293\\n\",\n            \"Epoch 3/10\\n\",\n            \"1500/1500 [==============================] - 1s 491us/step - loss: 0.2602 - accuracy: 0.9246 - val_loss: 0.2521 - val_accuracy: 0.9308\\n\",\n            \"Epoch 4/10\\n\",\n            \"1500/1500 [==============================] - 1s 481us/step - loss: 0.2579 - accuracy: 0.9265 - val_loss: 0.2541 - val_accuracy: 0.9296\\n\",\n            \"Epoch 5/10\\n\",\n            \"1500/1500 [==============================] - 1s 481us/step - loss: 0.2557 - accuracy: 0.9271 - val_loss: 0.2490 - val_accuracy: 0.9317\\n\",\n            \"Epoch 6/10\\n\",\n            \"1500/1500 [==============================] - 1s 482us/step - loss: 0.2540 - accuracy: 0.9274 - val_loss: 0.2492 - val_accuracy: 0.9313\\n\",\n            \"Epoch 7/10\\n\",\n            \"1500/1500 [==============================] - 1s 497us/step - loss: 0.2522 - accuracy: 0.9277 - val_loss: 0.2495 - val_accuracy: 0.9296\\n\",\n            \"Epoch 8/10\\n\",\n            \"1500/1500 [==============================] - 1s 491us/step - loss: 0.2505 - accuracy: 0.9277 - val_loss: 0.2472 - val_accuracy: 0.9306\\n\",\n            \"Epoch 9/10\\n\",\n            \"1500/1500 [==============================] - 1s 479us/step - loss: 0.2491 - accuracy: 0.9288 - val_loss: 0.2461 - val_accuracy: 0.9337\\n\",\n            \"Epoch 10/10\\n\",\n            \"1500/1500 [==============================] - 1s 483us/step - loss: 0.2477 - accuracy: 0.9285 - val_loss: 0.2444 - val_accuracy: 0.9325\\n\",\n            \"Test loss: 0.25082069635391235\\n\",\n            \"Test accuracy: 0.9277999997138977\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"batch_size = 256\\n\",\n        \"epochs = 10\\n\",\n        \"history = q_aware_model.fit(x_train, y_train,\\n\",\n        \"                            epochs=epochs,\\n\",\n        \"                            validation_split=0.2)\\n\",\n        \"\\n\",\n        \"scores, acc = q_aware_model.evaluate(x_test, y_test, verbose=0)\\n\",\n        \"print('Test loss:', scores)\\n\",\n        \"print('Test accuracy:', acc)\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"XhbweTQEmWN-\"\n      },\n      \"source\": [\n        \"### Converting to TFLite Format\\n\",\n        \"Now, we will convert our model to TFLite format, which is a format optimized for on-device machine learning.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 8,\n      \"metadata\": {\n        \"id\": \"uOwZiCRWmHDT\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"INFO:tensorflow:Assets written to: /var/folders/s3/6c0gmns50x36dt6vvfhv6jhc0000gn/T/tmpwwestso3/assets\\n\"\n          ]\n        },\n        {\n          \"name\": \"stderr\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"INFO:tensorflow:Assets written to: /var/folders/s3/6c0gmns50x36dt6vvfhv6jhc0000gn/T/tmpwwestso3/assets\\n\",\n            \"/Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/.conda/lib/python3.10/site-packages/tensorflow/lite/python/convert.py:887: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.\\n\",\n            \"  warnings.warn(\\n\",\n            \"2023-09-08 08:57:11.760815: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:364] Ignored output_format.\\n\",\n            \"2023-09-08 08:57:11.760826: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:367] Ignored drop_control_dependency.\\n\",\n            \"2023-09-08 08:57:11.761006: I tensorflow/cc/saved_model/reader.cc:45] Reading SavedModel from: /var/folders/s3/6c0gmns50x36dt6vvfhv6jhc0000gn/T/tmpwwestso3\\n\",\n            \"2023-09-08 08:57:11.761945: I tensorflow/cc/saved_model/reader.cc:91] Reading meta graph with tags { serve }\\n\",\n            \"2023-09-08 08:57:11.761951: I tensorflow/cc/saved_model/reader.cc:132] Reading SavedModel debug info (if present) from: /var/folders/s3/6c0gmns50x36dt6vvfhv6jhc0000gn/T/tmpwwestso3\\n\",\n            \"2023-09-08 08:57:11.764080: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:375] MLIR V1 optimization pass is not enabled\\n\",\n            \"2023-09-08 08:57:11.765054: I tensorflow/cc/saved_model/loader.cc:231] Restoring SavedModel bundle.\\n\",\n            \"2023-09-08 08:57:11.795103: I tensorflow/cc/saved_model/loader.cc:215] Running initialization op on SavedModel bundle at path: /var/folders/s3/6c0gmns50x36dt6vvfhv6jhc0000gn/T/tmpwwestso3\\n\",\n            \"2023-09-08 08:57:11.804542: I tensorflow/cc/saved_model/loader.cc:314] SavedModel load for tags { serve }; Status: success: OK. Took 43536 microseconds.\\n\",\n            \"2023-09-08 08:57:11.814757: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:255] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.\\n\",\n            \"fully_quantize: 0, inference_type: 6, input_inference_type: INT8, output_inference_type: INT8\\n\"\n          ]\n        },\n        {\n          \"data\": {\n            \"text/plain\": [\n              \"4312\"\n            ]\n          },\n          \"execution_count\": 8,\n          \"metadata\": {},\n          \"output_type\": \"execute_result\"\n        }\n      ],\n      \"source\": [\n        \"import tensorflow as tf\\n\",\n        \"\\n\",\n        \"# Create a converter\\n\",\n        \"converter = tf.lite.TFLiteConverter.from_keras_model(q_aware_model)\\n\",\n        \"\\n\",\n        \"# Indicate that you want to perform default optimizations,\\n\",\n        \"# which include quantization\\n\",\n        \"converter.optimizations = [tf.lite.Optimize.DEFAULT]\\n\",\n        \"\\n\",\n        \"# Define a generator function that provides your test data's numpy arrays\\n\",\n        \"def representative_data_gen():\\n\",\n        \"  for i in range(500):\\n\",\n        \"    yield [x_test[i:i+1]]\\n\",\n        \"\\n\",\n        \"# Use the generator function to guide the quantization process\\n\",\n        \"converter.representative_dataset = representative_data_gen\\n\",\n        \"\\n\",\n        \"# Ensure that if any ops can't be quantized, the converter throws an error\\n\",\n        \"converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\\n\",\n        \"\\n\",\n        \"# Set the input and output tensors to int8\\n\",\n        \"converter.inference_input_type = tf.int8\\n\",\n        \"converter.inference_output_type = tf.int8\\n\",\n        \"\\n\",\n        \"# Convert the model\\n\",\n        \"tflite_model = converter.convert()\\n\",\n        \"\\n\",\n        \"# Save the model to disk\\n\",\n        \"open(\\\"q_aware_model.tflite\\\", \\\"wb\\\").write(tflite_model)\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"zxGWitSs3MAH\"\n      },\n      \"source\": [\n        \"### Testing the Quantized Model\\n\",\n        \"Now that we have trained a quantization-aware model and converted it to the TFLite format, we can now perform inference using the TensorFlow Lite interpreter.\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"8qbfjJFa3Zy7\"\n      },\n      \"source\": [\n        \"We first load the TFLite model and allocate the required tensors. The Interpreter class provides methods for loading a model and running inferences.\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 9,\n      \"metadata\": {\n        \"id\": \"sXEM3WEv3SSt\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stderr\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"INFO: Created TensorFlow Lite XNNPACK delegate for CPU.\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"# Load the TFLite model and allocate tensors.\\n\",\n        \"interpreter = tf.lite.Interpreter(model_path=\\\"q_aware_model.tflite\\\")\\n\",\n        \"interpreter.allocate_tensors()\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"mP6WRo1L3dZp\"\n      },\n      \"source\": [\n        \"Next, we get the details of the input and output tensors. Each tensor in a TensorFlow Lite model has a name, index, shape, data type, and quantization parameters. These can be accessed via the input_details and output_details methods.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 10,\n      \"metadata\": {\n        \"id\": \"T7r8JFTC3Xxe\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Get input and output tensors.\\n\",\n        \"input_details = interpreter.get_input_details()\\n\",\n        \"output_details = interpreter.get_output_details()\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"ofFMDXq13ix7\"\n      },\n      \"source\": [\n        \"Before performing the inference, we need to normalize the input to match the data type of our model's input tensor, which in our case is int8. Then, we use the set_tensor method to provide the input data to the model. We perform the inference using the invoke method.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 11,\n      \"metadata\": {\n        \"id\": \"-1yOJjl83b9i\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Normalize the input value to int8\\n\",\n        \"input_shape = input_details[0]['shape']\\n\",\n        \"input_data = np.array(x_test[0:1], dtype=np.int8)\\n\",\n        \"interpreter.set_tensor(input_details[0]['index'], input_data)\\n\",\n        \"\\n\",\n        \"# Perform the inference\\n\",\n        \"interpreter.invoke()\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"ge-Y3K1J3oWs\"\n      },\n      \"source\": [\n        \"After the inference, we get the output data from the model's output tensor.\\n\",\n        \"\\n\",\n        \"Now, we are going to run the inference for the entire test set:\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 12,\n      \"metadata\": {\n        \"id\": \"MtfTBPCl3iKm\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"[[-122 -128  -22  -67 -128  -47 -128 -127 -128 -128]]\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"# Get the result\\n\",\n        \"output_data = interpreter.get_tensor(output_details[0]['index'])\\n\",\n        \"print(output_data)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"JO9fwtAF3sRP\"\n      },\n      \"source\": [\n        \"We normalize the entire test set and initialize an array to store the predictions.\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 13,\n      \"metadata\": {\n        \"id\": \"B5fDA1Vt3num\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"(_, _), (x_test_image, y_test_label) = mnist.load_data()\\n\",\n        \"\\n\",\n        \"# Resize and Normalize x_test_image to int8\\n\",\n        \"x_test_image = resize_images(x_test_image)\\n\",\n        \"x_test_image_norm = (x_test_image / 255.0 * 255 - 128).astype(np.int8)\\n\",\n        \"\\n\",\n        \"# Initialize an array to store the predictions\\n\",\n        \"predictions = []\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"l1PzXSuj3uy9\"\n      },\n      \"source\": [\n        \"We then iterate over the test set, making predictions for each image. For each image, we flatten the image, normalize it, and then expand its dimensions to match the shape of our model's input tensor.\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 14,\n      \"metadata\": {\n        \"id\": \"z1Clh4Kt3fuF\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Iterate over the test data and make predictions\\n\",\n        \"for i in range(len(x_test_image_norm)):\\n\",\n        \"    test_image = np.expand_dims(x_test_image_norm[i].flatten(), axis=0)\\n\",\n        \"    \\n\",\n        \"    # Set the value for the input tensor\\n\",\n        \"    interpreter.set_tensor(input_details[0]['index'], test_image)\\n\",\n        \"    \\n\",\n        \"    # Run the inference\\n\",\n        \"    interpreter.invoke()\\n\",\n        \"\\n\",\n        \"    output = interpreter.get_tensor(output_details[0]['index'])\\n\",\n        \"    predictions.append(output)\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"Finally, we use a function to plot the test images along with their predicted labels. This will give us a visual representation of how well our model is performing.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 15,\n      \"metadata\": {\n        \"id\": \"5wWyve_E3uL8\"\n      },\n      \"outputs\": [\n        {\n          \"data\": {\n            \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAA7YAAARDCAYAAABcAr28AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAABojklEQVR4nO3de5zWZZ0//vc9M8AMRw8gBx1Rc1VQWfFMhodvKboe083MdhNT1MrALHNb/RXFZpCatlZWax7WSMlyRdu1TVPI46a2wiIeWUiJPCHKiBxnPr8/Nmc9YPu5YG5uLu7n8/GYx0OcF+/7um+u677v13yGoVIURREAAACQqYZaLwAAAADWh2ILAABA1hRbAAAAsqbYAgAAkDXFFgAAgKwptgAAAGRNsQUAACBrii0AAABZU2wBAADIWt0X24MPPjjOOeecUtkZM2ZEpVKJV199db1uc7vttovLL798vWZAV3EGqGf2P/XOGaCe2f+blrovtrmZOHFiVCqVd3306tWr1kuDDWLGjBlx7LHHxuDBg6NXr16xxx57xNSpU2u9LNggVqxYEWPHjo3dd989mpqa4rjjjqv1kmCDmz17dowePTqam5ujtbU1vvnNb9Z6SbDBPfPMM9GnT5/YbLPNar2UjYZim5kvfOEL8cc//vFtH8OHD4+PfOQjtV4abBD3339/jBgxIn7+85/H7Nmz49RTT41PfOIT8Ytf/KLWS4Oqa29vj5aWlhg/fnx86EMfqvVyYINbunRpHHbYYTF06NB45JFH4uKLL46JEyfGD3/4w1ovDTaY1atXx8c+9rEYPXp0rZeyUVFs3+L666+PvffeO/r06RODBg2Kk08+OV588cV35e67774YMWJENDc3x/777x9z5sx52+fvvffeGD16dLS0tERra2uMHz8+li1b1iVr7N27dwwaNKjz44UXXoi5c+fGaaed1iXzqW85nIG///u/j0mTJsX73//+eN/73hcTJkyIww8/PG6++eYumU/9ymH/9+rVK6688soYN25cDBo0qEtmwptyOANTp06NVatWxdVXXx277rprnHTSSTF+/Pj41re+1SXzqV857P83XXjhhbHLLrvEiSee2KVzc6fYvsXq1atj0qRJMWvWrLjllltiwYIFMXbs2HflzjvvvLj00kvjoYceigEDBsTRRx8dq1evjoiIefPmxeGHHx4nnHBCzJ49O6ZNmxb33ntvnH322e95u0cccUT07t37PT923XXX9/y9V111Vey0006+YkOXyPEMRES89tprscUWW6zXfYdc9z90lRzOwAMPPBAHHnhgdO/evfP/jRkzJp588slYsmRJ1z0Y1J0c9n9ExF133RU33XRTfPe73+3S+79JKOrcQQcdVEyYMGGtn3vooYeKiCja2tqKoiiKu+++u4iI4sYbb+zMLF68uGhpaSmmTZtWFEVRnHbaacUZZ5zxtjn33HNP0dDQUCxfvrwoiqIYOnRocdlll3V+fuHChcXTTz/9nh8LFixY6/qWL19ebL755sWUKVPW9e5D1megKIpi2rRpRffu3Ys5c+asy92nzuW8/0855ZTi2GOPXcd7Dv8jtzNw6KGHvmv+Y489VkREMXfu3HV+HKhPue3/l19+uWhtbS1mzpxZFEVRXHPNNUW/fv3W92HYZDTVqE9vlB555JGYOHFizJo1K5YsWRIdHR0REfHss8/G8OHDO3OjRo3q/O8tttgidt5553j88ccjImLWrFkxe/bst/0wm6IooqOjI+bPnx/Dhg171+1uvfXW67Tef/mXf4m2trY45ZRT1un3wzvldgbuvvvuOPXUU+Of/umfXNViveW2/6GrOQPUsxz2/7hx4+Lkk0+OAw88MPn+1QPF9k+WLVsWY8aMiTFjxsTUqVNjwIAB8eyzz8aYMWNi1apVpee8/vrrceaZZ8b48ePf9bltt912rb/niCOOiHvuuec9Zw4dOjQee+yxd/3/q666Ko466qgYOHBg6fXBe8ntDMycOTOOPvrouOyyy+ITn/hE6fXB2uS2/6Gr5XIG3vz5Im/15q/9vXPWVS77/6677opbb701Lrnkkoj439Lc1NQUP/zhD+OTn/xk6bVuihTbP3niiSdi8eLFMXny5GhtbY2IiIcffnit2QcffLBzcy5ZsiSeeuqpzq/A7LnnnjF37tzYcccdS9/2VVddFcuXL3/Pz3fr1u1d/2/+/Plx9913x6233lr6duDPyekMzJgxI4466qiYMmVKnHHGGaVvB95LTvsfqiGXMzBq1Ki44IILYvXq1Z3//4477oidd945Nt9889K3CW+Vy/5/4IEHor29vfPX06dPjylTpsT999/vOx9Cse207bbbRvfu3eOKK66Is846K+bMmROTJk1aa/ZrX/tabLnlljFw4MC44IILon///p3/luD5558f+++/f5x99tlx+umnR69evWLu3Llxxx13xHe+8521zluXjXj11VfH4MGD44gjjkj+vbA2uZyBu+++O4466qiYMGFCnHDCCfH8889HRET37t39ACnWWS77PyJi7ty5sWrVqnjllVeira0tHn300YiI2GOPPZLmwFvlcgZOPvnk+OpXvxqnnXZanH/++TFnzpz49re/HZdddlnyfYY35bL/3/mtzA8//HA0NDTEbrvtVnrGpsxPRf6TAQMGxLXXXhs33XRTDB8+PCZPntx5mf+dJk+eHBMmTIi99tornn/++bjttts6fzrfiBEjYubMmfHUU0/F6NGjY+TIkfHlL385hgwZ0mVr7ejoiGuvvTbGjh0bjY2NXTaX+pbLGbjuuuvijTfeiG984xsxePDgzo/jjz++S+ZTn3LZ/xERf/VXfxUjR46M2267LWbMmBEjR46MkSNHdtl86lMuZ6Bfv37xq1/9KubPnx977bVXfP7zn48vf/nLvnuH9ZLL/ufPqxRFUdR6EQAAALCuXLEFAAAga4otAAAAWVNsAQAAyJpiCwAAQNYUWwAAALKm2AIAAJC1pjKhjo6OWLRoUfTp0ycqlUq11wRvUxRFtLW1xZAhQ6KhYcN/Lcb+p9acAeqZ/U+9cwaoZyn7v1SxXbRoUbS2tnbJ4mBdPffcc7HNNtts8Nu1/9lYOAPUM/ufeucMUM/K7P9SxbZPnz6dA/v27bv+K4MES5cujdbW1s59uKHZ/9SaM0A9s/+pd84A9Sxl/5cqtm9+20Hfvn1taGqmVt/+Yv+zsXAGqGf2P/XOGaCeldn/fngUAAAAWVNsAQAAyJpiCwAAQNYUWwAAALKm2AIAAJA1xRYAAICsKbYAAABkrdS/Ywts+lavXp2UX7VqVels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RpNn9+vVLXU52rr322qR8ytk69dRTE1fDxubmm28unf3e976XNNvzNBu7I488snR2/vz5SbN///vfpy6ntKuvvrpqs1k3Ke+ne/funTR7+fLlpbNvvPFG0uyiKEpne/XqlTR72LBhpbM9e/ZMmp2y7pQ/m42BK7YAAABkTbEFAAAga4otAAAAWVNsAQAAyJpiCwAAQNYUWwAAALKm2AIAAJA1xRYAAICsKbYAAABkTbEFAAAga4otAAAAWWuq9QI2Ju3t7Un5iy++uHR21KhRSbOPOOKIpDysTe/evUtnp02bljQ7NZ+iX79+pbOvvfZa1dax8847J+X333//0tlTTz01dTmsg46OjtLZBQsWVG0dAwcOrNps8tbQUP4aw2677Va1dVQqlaR89+7dS2dT7mNERHNzc+nsrFmzkmbDe+nZs2etl9Cpqal8Rdthhx2SZqe8LjY2NibNrjVXbAEAAMiaYgsAAEDWFFsAAACyptgCAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWmmq9gGrr6Ogonf3jH/+YNPtLX/pS6ezKlSuTZkNXaGtrK51dtmxZ0uyUs7V48eKk2b169SqdbWlpSZrdu3fvpDx5K4qidHbWrFlJsy+77LLS2ZTzEhHR0ODrzqy/lH33d3/3d0mzv/Wtb5XOfv/730+a/bd/+7els84Km6I5c+aUzu64445JszflM7Pp3jMAAADqgmILAABA1hRbAAAAsqbYAgAAkDXFFgAAgKwptgAAAGRNsQUAACBrii0AAABZU2wBAADImmILAABA1hRbAAAAstZU6wVUW0ND+e7+qU99qmrraGra5B9qMterV6+qze7du3fVZlcqlarNJn+NjY2lsx/+8IeruBLY8FKeH6dMmZI0OzUPlLdq1arS2W7dulVxJXlxxRYAAICsKbYAAABkTbEFAAAga4otAAAAWVNsAQAAyJpiCwAAQNYUWwAAALKm2AIAAJA1xRYAAICsKbYAAABkranWC9iY3HbbbbVeAmySKpVKrZcAAJCFbt261XoJWXLFFgAAgKwptgAAAGRNsQUAACBrii0AAABZU2wBAADImmILAABA1hRbAAAAsqb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3++23x8c//vG44oor4rDDDovHH388xo0bFy0tLXH22WfXenlQdd4HUc/a29ujpaUlxo8fHz//+c9rvZyNjiu2b3H99dfH3nvvHX369IlBgwbFySefHC+++OK7cvfdd1+MGDEimpubY//99485c+a87fP33ntvjB49OlpaWqK1tTXGjx8fy5Yt65I1Tp06NVatWhVXX3117LrrrnHSSSfF+PHj41vf+laXzKe+5XAGHn/88bjyyitj+vTpccwxx8T2228fe+21Vxx66KFdMp/6lcP+v/766+O4446Ls846K3bYYYc48sgj40tf+lJMmTIliqLoktugfuVwBrwPolpy2P+9evWKK6+8MsaNGxeDBg3qkpmbEsX2LVavXh2TJk2KWbNmxS233BILFiyIsWPHvit33nnnxaWXXhoPPfRQDBgwII4++uhYvXp1RETMmzcvDj/88DjhhBNi9uzZMW3atLj33nv/7FfSjzjiiOjdu/d7fuy6666d2QceeCAOPPDA6N69e+f/GzNmTDz55JOxZMmSrnswqEs5nIHbbrstdthhh/jFL34R22+/fWy33XZx+umnu2LLesth/69cuTKam5vf9vtbWlpi4cKF8fvf/75rHgjqVg5nwPsgqiWH/c//oahzBx10UDFhwoS1fu6hhx4qIqJoa2sriqIo7r777iIiihtvvLEzs3jx4qKlpaWYNm1aURRFcdpppxVnnHHG2+bcc889RUNDQ7F8+fKiKIpi6NChxWWXXdb5+YULFxZPP/30e34sWLCgM3vooYe+a/5jjz1WREQxd+7cdX4cqF+5nYEzzzyz6NGjR7HffvsVv/nNb4q777672GOPPYpDDjmkKx4O6kxu+/8HP/hB0bNnz+LOO+8s2tvbiyeffLLYZZddiogo7r///q54SKgzuZ0B74PoSrnt/7c65ZRTimOPPXYd7/mmyd+xfYtHHnkkJk6cGLNmzYolS5ZER0dHREQ8++yzMXz48M7cqFGjOv97iy22iJ133jkef/zxiIiYNWtWzJ49O6ZOndqZKYoiOjo6Yv78+TFs2LB33e7WW29drbsESXI4Ax0dHbFy5cr453/+59hpp50iIuJHP/pR7LXXXvHkk0/GzjvvnHan4U9y2P/jxo2LefPmxV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iuuSMpTP1L2XUTEmWeeWaWVsK5csQUAACBrii0AAABZU2wBAADImmILAABA1hRbAAAAsqbYAgAAkDXFFgAAgKwptgAAAGRNsQUAACBrii0AAABZa6r1AiIiGhrK9+uddtopafYFF1xQOjtu3Lik2Sm22267pPztt99eOnvwwQenLYa6cd5555XOnn322Umz29raSmd79OiRNLtfv36ls0VRJM2G95K6l+bPn1+llUQMGjSoarOpH8cff3zp7AsvvJA0e8iQIaWzJ510UtLsyy67rHT2Jz/5SdLs7t27J+WpHytXrkzKP//886Wzy5cvT5rd3NyclOd/uGILAABA1hRbAAAAsqbYAgAAkDXFFgAAgKwptgAAAGRNsQUAACBrii0AAABZU2wBAADImmILAABA1hRbAAAAsqbYAgAAkLWmWi8gVaVSScqffvrpVcnCpqalpSUp39zcXDqbem5TVHM29aWjoyMpP3/+/NLZAw88MHU5sEF96lOfSsqfccYZpbMrV65Mmn3xxReXzjY2NibNhvfSo0ePpPyqVatKZ4uiSF0O68AVWwAAALKm2AIAAJA1xRYAAICsKbYAAABkTbEFAAAga4otAAAAWVNsAQAAyJpiCwAAQNYUWwAAALKm2AIAAJC1plovAMhTpVKp9RKgSzU2NiblP/jBD1YlCzlIOS89e/as4kpg4+c904bhii0AAABZU2wBAADImmILAABA1hRbAAAAsqbYAgAAkDXFFgAAgKwptgAAAGRNsQUAACBrii0AAABZU2wBAADIWlOZUFEUERGxdOnSqi4G1ubNfffmPtzQ7H9qzRmgntn/1DtngHqWsv9LFdu2traIiGhtbV2PZcH6aWtri379+tXkdiPsf2rPGaCe2f/UO2eAelZm/1eKEvW3o6MjFi1aFH369IlKpdJlC4QyiqKItra2GDJkSDQ0bPjvnrf/qTVngHpm/1PvnAHqWcr+L1VsAQAAYGPlh0cBAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWFFsAAACyptgCAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWFFsAAACyptgCAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWFFsAAACyptgCAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWFFsAAACyptgCAACQNcUWAACArCm2AAAAZE2xBQAAIGuKLQAAAFlTbAEAAMiaYgsAAEDWFFsAAACyptgCAACQtbovtgcffHCcc845pbIzZsyISqUSr7766nrd5nbbbReXX375es2AruIMUM/sf+qdM0A9s/83LXVfbHOzYMGCqFQq7/p48MEHa7002GB++tOfxh577BE9e/aMoUOHxsUXX1zrJcEGMXHixLW+BvTq1avWS4MN4sknn4xDDjkkBg4cGM3NzbHDDjvEhRdeGKtXr6710mCDeuaZZ6JPnz6x2Wab1XopG42mWi+AdXPnnXfGrrvu2vnrLbfcsoargQ3n9ttvj49//ONxxRVXxGGHHRaPP/54jBs3LlpaWuLss8+u9fKgqr7whS/EWWed9bb/98EPfjD22WefGq0INqxu3brFJz7xidhzzz1js802i1mzZsW4ceOio6MjLrroolovDzaI1atXx8c+9rEYPXp03H///bVezkbDFdu3uP7662PvvfeOPn36xKBBg+Lkk0+OF1988V25++67L0aMGBHNzc2x//77x5w5c972+XvvvTdGjx4dLS0t0draGuPHj49ly5Z16Vq33HLLGDRoUOdHt27dunQ+9SmHM3D99dfHcccdF2eddVbssMMOceSRR8aXvvSlmDJlShRF0SW3QX3KYf/37t37bc/9L7zwQsydOzdOO+20LplPfcvhDOywww5x6qmnxl/+5V/G0KFD45hjjomPf/zjcc8993TJfOpXDvv/TRdeeGHssssuceKJJ3bp3Nwptm+xevXqmDRpUsyaNStuueWWWLBgQYwdO/ZdufPOOy8uvfTSeOihh2LAgAFx9NFHd34LzLx58+Lwww+PE044IWbPnh3Tpk2Le++9989eSTriiCOid+/e7/nx1iuzbzrmmGNiq622ig984ANx6623dtljQH3L4QysXLkympub3/b7W1paYuHChfH73/++ax4I6lIO+/+drrrqqthpp51i9OjR633/Iccz8Mwzz8Qvf/nLOOigg9b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0Ca22+/PT7+8Y/HFVdcEYcddlg8/vjjMW7cuGhpaYmzzz671suDDWLChAnxq1/9Ki655JLYfffd45VXXolXXnml1suCDcL+h4g777wzdt11185fb7nlljVcDWxYq1evjo997GMxevTouP/++2u9nI2GK7Zvcf3118fee+8dffr0iUGDBsXJJ58cL7744rty9913X4wYMSKam5tj//33jzlz5rzt8/fee2+MHj06WlpaorW1NcaPHx/Lli3rsjUed9xxcdZZZ8UOO+wQRx55ZHzpS1+KKVOmRFEUXXIb1K8czsDjjz8eV155ZUyfPj2OOeaY2H777WOvvfaKQw89tEvmU7/sf+pdDmfgTVtuuWUMGjSo86Nbt25dOp/6k9P+v/DCC2OXXXaJE088sUvn5k6xfYvVq1fHpEmTYtasWXHLLbfEggULYuzYse/KnXfeeXHppZfGQw89FAMGDIijjz46Vq9eHRER8+bNi8MPPzxOOOGEmD17dkybNi3uvffeP3s19YgjjojevXu/58dbvyK5cuXKaG5uftvvb2lpiYULF8bvf//7rnkgqFs5nIHbbrstdthhh/jFL34R22+/fWy33XZx+umnu2LFerP/qXc5nIE3HXPMMbHVVlvFBz7wgbj11lu77DGgfuWy/++666646aab4rvf/W6X3v9NQlHnDjrooGLChAlr/dxDDz1URETR1tZWFEVR3H333UVEFDfeeGNnZvHixUVLS0sxbdq0oiiK4rTTTivOOOOMt8255557ioaGhmL58uVFURTF0KFDi8suu6zz8wsXLiyefvrp9/xYsGBBZ/YHP/hB0bNnz+LOO+8s2tvbiyeffLLYZZddiogo7r///q54SKgzuZ2BM888s+jRo0ex3377Fb/5zW+Ku+++u9hjjz2KQw45pCseDuqM/U+9y+0MvPTSS8Wll15aPPjgg8Vvf/vb4vzzzy8qlUoxffr0rng4qDO57f+XX365aG1tLWbOnFkURVFcc801Rb9+/db3Ydhk+Du2b/HII4/ExIkTY9asWbFkyZLo6OiIiIhnn302hg8f3pkbNWpU539vscUWsfPOO8fjjz8eERGzZs2K2bNnx9SpUzszRVFER0dHzJ8/P4YNG/au2916661Lr3HcuHExb968OOqoo2L16tXRt2/fmDBhQkycODEaGlyAZ/3kcAY6Ojpi5cqV8c///M+x0047RUTEj370o9hrr73iySefjJ133jntTsOf2P/UuxzOQP/+/ePcc8/t/PU+++wTixYtiosvvjiOOeaY8ncW3iGH/T9u3Lg4+eST48ADD0y+f/VAsf2TZcuWxZgxY2LMmDExderUGDBgQDz77LMxZsyYWLVqVek5r7/+epx55pkxfvz4d31u2223XevvOeKII+Kee+55z5lDhw6Nxx57LCIiKpVKTJkyJS666KJ4/vnnY8CAAfHrX/86IiJ22GGH0uuEd8rlDAwePDiampo639RHROcLxbPPPuuNPevE/qfe5XIG1ma//faLO+64o/Qa4Z1y2f933XVX3HrrrXHJJZdExP+W5qampvjhD38Yn/zkJ0uvdVOk2P7JE088EYsXL47JkydHa2trREQ8/PDDa80++OCDnZtzyZIl8dRTT3W+sdhzzz1j7ty5seOOO5a+7auuuiqWL1/+np9f2w9EaGxs7PwKzw033BCjRo2KAQMGlL5NeKdczsABBxwQa9asiXnz5sX73ve+iIh46qmnIuJ/nvxhXdj/1LtczsDaPProozF48ODStwfvlMv+f+CBB6K9vb3z19OnT48pU6bE/fffn3Tld1Ol2P7JtttuG927d48rrrgizjrrrJgzZ05MmjRprdmvfe1rseWWW8bAgQPjggsuiP79+8dxxx0XERHnn39+7L///nH22WfH6aefHr169Yq5c+fGHXfcEd/5znfWOi9lI7788svxs5/9LA4++OBYsWJFXHPNNXHTTTfFzJkzk+8zvFUuZ+BDH/pQ7LnnnvHJT34yLr/88ujo6IjPfOYzceihh77tKhaksP+pd7mcgeuuuy66d+8eI0eOjIiIm2++Oa6++uq46qqr0u4wvEUu+/+d38r88MMPR0NDQ+y2226lZ2zK/KXMPxkwYEBce+21cdNNN8Xw4cNj8uTJnZf532ny5MkxYcKE2GuvveL555+P2267Lbp37x4RESNGjIiZM2fGU089FaNHj46RI0fGl7/85RgyZEiXrfW6666LvffeOw444IB47LHHYsaMGbHvvvt22XzqUy5noKGhIW677bbo379/HHjggXHkk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1hRbAAAAsqbYAgAAkDXFFgAAgKz9/4FOtpbaPnAJAAAAAElFTkSuQmCC\",\n            \"text/plain\": [\n              \"<Figure size 1200x1400 with 25 Axes>\"\n            ]\n          },\n          \"metadata\": {},\n          \"output_type\": \"display_data\"\n        }\n      ],\n      \"source\": [\n        \"import matplotlib.pyplot as plt\\n\",\n        \"\\n\",\n        \"def plot_images_labels_prediction(images,labels,idx,num=10):\\n\",\n        \"    fig=plt.gcf()\\n\",\n        \"    fig.set_size_inches(12, 14)\\n\",\n        \"    if num > 25: num=25\\n\",\n        \"    for i in range(0, num):\\n\",\n        \"        ax=plt.subplot(5, 5, i+1)\\n\",\n        \"        ax.imshow(images[idx], cmap='binary')\\n\",\n        \"        title=\\\"label=\\\" + str(labels[idx])\\n\",\n        \"        ax.set_title(title, fontsize=10)\\n\",\n        \"        ax.set_xticks([]);\\n\",\n        \"        ax.set_yticks([]);\\n\",\n        \"        idx += 1\\n\",\n        \"    plt.show()\\n\",\n        \"\\n\",\n        \"plot_images_labels_prediction(x_test_image, y_test_label, 0, 25)\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"VOHKHUMp30j8\"\n      },\n      \"source\": [\n        \"That's it! We have successfully trained a quantization-aware model, converted it to the TFLite format, and performed inference using the TensorFlow Lite interpreter.\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"ywhXM1mA-a7F\"\n      },\n      \"source\": [\n        \"## Convert your model to Orion's Cairo code\\n\",\n        \"In this section you will generate Cairo files for each bias and weight of the model. \"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 19,\n      \"metadata\": {\n        \"id\": \"wP_kVSuEKA1U\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import numpy as np\\n\",\n        \"import tensorflow as tf\\n\",\n        \"import os\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# Load the TFLite model and allocate tensors.\\n\",\n        \"interpreter = tf.lite.Interpreter(model_path=\\\"q_aware_model.tflite\\\")\\n\",\n        \"interpreter.allocate_tensors()\\n\",\n        \"\\n\",\n        \"# Create an object with all tensors (an input + all weights and biases)\\n\",\n        \"tensors = {\\n\",\n        \"    \\\"input\\\": x_test_image[0].flatten(), #7\\n\",\n        \"    \\\"fc1_weights\\\": interpreter.get_tensor(1), \\n\",\n        \"    \\\"fc1_bias\\\": interpreter.get_tensor(2), \\n\",\n        \"    \\\"fc2_weights\\\": interpreter.get_tensor(4), \\n\",\n        \"    \\\"fc2_bias\\\": interpreter.get_tensor(5)\\n\",\n        \"}\\n\",\n        \"\\n\",\n        \"# Create the directory if it doesn't exist\\n\",\n        \"os.makedirs('src/generated', exist_ok=True)\\n\",\n        \"\\n\",\n        \"for tensor_name, tensor in tensors.items():\\n\",\n        \"    with open(os.path.join('src', 'generated', f\\\"{tensor_name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n        \"        f.write(\\n\",\n        \"            \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n        \"            \\\"use orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\\\\n\\\" +\\n\",\n        \"            \\\"use orion::numbers::i32;\\\\n\\\\n\\\" +\\n\",\n        \"            \\\"\\\\nfn {0}() -> Tensor<i32> \\\".format(tensor_name) + \\\"{\\\\n\\\" +\\n\",\n        \"            \\\"    let mut shape = ArrayTrait::<usize>::new();\\\\n\\\"\\n\",\n        \"        )\\n\",\n        \"        for dim in tensor.shape:\\n\",\n        \"            f.write(\\\"    shape.append({0});\\\\n\\\".format(dim))\\n\",\n        \"        f.write(\\n\",\n        \"            \\\"    let mut data = ArrayTrait::<i32>::new();\\\\n\\\"\\n\",\n        \"        )\\n\",\n        \"        for val in np.nditer(tensor.flatten()):\\n\",\n        \"            f.write(\\\"    data.append(i32 {{ mag: {0}, sign: {1} }});\\\\n\\\".format(abs(int(val)), str(val < 0).lower()))\\n\",\n        \"        f.write(\\n\",\n        \"            \\\"    TensorTrait::new(shape.span(), data.span())\\\\n\\\" +\\n\",\n        \"            \\\"}\\\\n\\\"\\n\",\n        \"        )\\n\",\n        \"      \\n\",\n        \"with open(os.path.join('src', 'generated.cairo'), 'w') as f:\\n\",\n        \"    for param_name in tensors.keys():\\n\",\n        \"        f.write(f\\\"mod {param_name};\\\\n\\\")\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"iobaWNzdW4Jq\"\n      },\n      \"source\": [\n        \"## Build your NN with Cairo and Orion\\n\",\n        \"In this section you will perform inference with Cairo and Orion.\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"Create the `nn.cairo` file in which we'll build the neural network functions.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 17,\n      \"metadata\": {\n        \"id\": \"x2slaqnnUWlB\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"! touch src/nn.cairo\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"Let's create the two dense layer functions of the neural network: `fc1` and `fc2`.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 20,\n      \"metadata\": {\n        \"id\": \"UMF0u2gcUko9\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Overwriting src/nn.cairo\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"%%writefile src/nn.cairo\\n\",\n        \"use orion::operators::tensor::core::Tensor;\\n\",\n        \"use orion::numbers::signed_integer::{integer_trait::IntegerTrait, i32::i32};\\n\",\n        \"use orion::operators::nn::{NNTrait, I32NN};\\n\",\n        \"\\n\",\n        \"fn fc1(i: Tensor<i32>, w: Tensor<i32>, b: Tensor<i32>) -> Tensor<i32> {\\n\",\n        \"    let x = NNTrait::linear(i, w, b);\\n\",\n        \"    NNTrait::relu(@x)\\n\",\n        \"}\\n\",\n        \"\\n\",\n        \"fn fc2(i: Tensor<i32>, w: Tensor<i32>, b: Tensor<i32>) -> Tensor<i32> {\\n\",\n        \"    NNTrait::linear(i, w, b)\\n\",\n        \"}\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"We will make predictions in a test. First, create the testing file.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 21,\n      \"metadata\": {\n        \"id\": \"OF8ANN0IU0BL\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"! touch src/test.cairo\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"Let's now define the input data and parameters generated earlier, and set the neural network.\\n\",\n        \"The input data represents the number 7. The probability at index 7 must therefore be close to 1.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 22,\n      \"metadata\": {\n        \"id\": \"FsWjlfyeWJF8\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"Overwriting src/test.cairo\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"%%writefile src/test.cairo\\n\",\n        \"use core::array::SpanTrait;\\n\",\n        \"\\n\",\n        \"use mnist_nn::nn::fc1;\\n\",\n        \"use mnist_nn::nn::fc2;\\n\",\n        \"use mnist_nn::generated::input::input;\\n\",\n        \"use mnist_nn::generated::fc1_bias::fc1_bias;\\n\",\n        \"use mnist_nn::generated::fc1_weights::fc1_weights;\\n\",\n        \"use mnist_nn::generated::fc2_bias::fc2_bias;\\n\",\n        \"use mnist_nn::generated::fc2_weights::fc2_weights;\\n\",\n        \"\\n\",\n        \"use orion::operators::tensor::I32Tensor;\\n\",\n        \"\\n\",\n        \"#[test]\\n\",\n        \"#[available_gas(99999999999999999)]\\n\",\n        \"fn mnist_nn_test() {\\n\",\n        \"    let input = input();\\n\",\n        \"    let fc1_bias = fc1_bias();\\n\",\n        \"    let fc1_weights = fc1_weights();\\n\",\n        \"    let fc2_bias = fc2_bias();\\n\",\n        \"    let fc2_weights = fc2_weights();\\n\",\n        \"\\n\",\n        \"    let x = fc1(input, fc1_weights, fc1_bias);\\n\",\n        \"    let x = fc2(x, fc2_weights, fc2_bias);\\n\",\n        \"\\n\",\n        \"    let x = *x.argmax(0, Option::None(()), Option::None(())).data.at(0);\\n\",\n        \"\\n\",\n        \"    assert(x == 7, 'should predict 7');\\n\",\n        \"}\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"attachments\": {},\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"Run the following cell to test your file.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"lkep4mVkWMtS\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"! scarb run test\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": []\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.10.11\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated.cairo",
        "content": "mod input;\nmod fc1_weights;\nmod fc1_bias;\nmod fc2_weights;\nmod fc2_bias;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated/fc1_bias.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\nuse orion::numbers::i32;\n\n\nfn fc1_bias() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(i32 { mag: 1287, sign: false });\n    data.append(i32 { mag: 3667, sign: true });\n    data.append(i32 { mag: 2954, sign: false });\n    data.append(i32 { mag: 7938, sign: false });\n    data.append(i32 { mag: 3959, sign: false });\n    data.append(i32 { mag: 5862, sign: true });\n    data.append(i32 { mag: 4886, sign: false });\n    data.append(i32 { mag: 4992, sign: false });\n    data.append(i32 { mag: 10126, sign: false });\n    data.append(i32 { mag: 2237, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated/fc1_weights.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\nuse orion::numbers::i32;\n\n\nfn fc1_weights() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n    shape.append(196);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 55, sign: false });\n    data.append(i32 { mag: 46, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 42, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 53, sign: false });\n    data.append(i32 { mag: 51, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 75, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 57, sign: true });\n    data.append(i32 { mag: 44, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 45, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 53, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 46, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 50, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 61, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 71, sign: true });\n    data.append(i32 { mag: 78, sign: true });\n    data.append(i32 { mag: 63, sign: true });\n    data.append(i32 { mag: 74, sign: true });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 54, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 31, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 49, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 65, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 41, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 53, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 41, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 44, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 55, sign: false });\n    data.append(i32 { mag: 97, sign: false });\n    data.append(i32 { mag: 125, sign: false });\n    data.append(i32 { mag: 68, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 47, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 46, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 50, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 54, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 43, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 56, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 80, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 68, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 46, sign: true });\n    data.append(i32 { mag: 60, sign: true });\n    data.append(i32 { mag: 84, sign: true });\n    data.append(i32 { mag: 84, sign: true });\n    data.append(i32 { mag: 95, sign: true });\n    data.append(i32 { mag: 70, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 39, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 63, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 33, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 66, sign: false });\n    data.append(i32 { mag: 121, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 43, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 33, sign: false });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 127, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 54, sign: false });\n    data.append(i32 { mag: 47, sign: false });\n    data.append(i32 { mag: 55, sign: false });\n    data.append(i32 { mag: 62, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 51, sign: false });\n    data.append(i32 { mag: 67, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 41, sign: true });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 83, sign: true });\n    data.append(i32 { mag: 71, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 33, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 60, sign: true });\n    data.append(i32 { mag: 65, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 46, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 42, sign: true });\n    data.append(i32 { mag: 43, sign: true });\n    data.append(i32 { mag: 55, sign: true });\n    data.append(i32 { mag: 44, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 52, sign: true });\n    data.append(i32 { mag: 55, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 53, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 66, sign: true });\n    data.append(i32 { mag: 70, sign: true });\n    data.append(i32 { mag: 58, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 45, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 89, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 50, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 33, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 45, sign: true });\n    data.append(i32 { mag: 84, sign: true });\n    data.append(i32 { mag: 71, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 53, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 78, sign: true });\n    data.append(i32 { mag: 39, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 31, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 46, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 73, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 80, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 84, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 47, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 39, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 74, sign: true });\n    data.append(i32 { mag: 48, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 40, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 65, sign: false });\n    data.append(i32 { mag: 104, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 55, sign: true });\n    data.append(i32 { mag: 42, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 43, sign: true });\n    data.append(i32 { mag: 85, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 53, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 71, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 48, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 44, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 52, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 40, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 43, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 24, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 48, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 50, sign: true });\n    data.append(i32 { mag: 95, sign: true });\n    data.append(i32 { mag: 60, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 78, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 53, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 33, sign: true });\n    data.append(i32 { mag: 39, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 49, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 65, sign: true });\n    data.append(i32 { mag: 56, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 57, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 79, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 39, sign: true });\n    data.append(i32 { mag: 34, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 93, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 22, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 109, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 48, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 52, sign: false });\n    data.append(i32 { mag: 52, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 47, sign: false });\n    data.append(i32 { mag: 63, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 54, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 61, sign: true });\n    data.append(i32 { mag: 25, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 46, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 32, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 50, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 37, sign: true });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 49, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 54, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 14, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 26, sign: true });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 30, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 68, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 40, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 57, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 44, sign: false });\n    data.append(i32 { mag: 69, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 73, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 7, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 34, sign: false });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 74, sign: true });\n    data.append(i32 { mag: 89, sign: true });\n    data.append(i32 { mag: 60, sign: true });\n    data.append(i32 { mag: 68, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 15, sign: true });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 8, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 29, sign: true });\n    data.append(i32 { mag: 45, sign: true });\n    data.append(i32 { mag: 53, sign: true });\n    data.append(i32 { mag: 42, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 23, sign: true });\n    data.append(i32 { mag: 20, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 74, sign: false });\n    data.append(i32 { mag: 37, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 18, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 6, sign: true });\n    data.append(i32 { mag: 11, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 49, sign: false });\n    data.append(i32 { mag: 56, sign: false });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 58, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 25, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 10, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 33, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 36, sign: false });\n    data.append(i32 { mag: 38, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 17, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 18, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 23, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 8, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 40, sign: true });\n    data.append(i32 { mag: 59, sign: true });\n    data.append(i32 { mag: 16, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 4, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 4, sign: false });\n    data.append(i32 { mag: 9, sign: true });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 7, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated/fc2_bias.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\nuse orion::numbers::i32;\n\n\nfn fc2_bias() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(i32 { mag: 313, sign: true });\n    data.append(i32 { mag: 1064, sign: false });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 184, sign: true });\n    data.append(i32 { mag: 1012, sign: true });\n    data.append(i32 { mag: 1885, sign: false });\n    data.append(i32 { mag: 787, sign: true });\n    data.append(i32 { mag: 835, sign: false });\n    data.append(i32 { mag: 1819, sign: true });\n    data.append(i32 { mag: 208, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated/fc2_weights.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\nuse orion::numbers::i32;\n\n\nfn fc2_weights() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(10);\n    shape.append(10);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(i32 { mag: 42, sign: true });\n    data.append(i32 { mag: 41, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 27, sign: true });\n    data.append(i32 { mag: 58, sign: true });\n    data.append(i32 { mag: 71, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 50, sign: true });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 67, sign: true });\n    data.append(i32 { mag: 35, sign: true });\n    data.append(i32 { mag: 112, sign: true });\n    data.append(i32 { mag: 95, sign: false });\n    data.append(i32 { mag: 78, sign: false });\n    data.append(i32 { mag: 15, sign: false });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 64, sign: false });\n    data.append(i32 { mag: 49, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 69, sign: true });\n    data.append(i32 { mag: 53, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 62, sign: true });\n    data.append(i32 { mag: 47, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 70, sign: true });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 48, sign: false });\n    data.append(i32 { mag: 69, sign: true });\n    data.append(i32 { mag: 21, sign: true });\n    data.append(i32 { mag: 35, sign: false });\n    data.append(i32 { mag: 38, sign: true });\n    data.append(i32 { mag: 100, sign: true });\n    data.append(i32 { mag: 41, sign: true });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 78, sign: false });\n    data.append(i32 { mag: 12, sign: true });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 59, sign: false });\n    data.append(i32 { mag: 49, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 19, sign: true });\n    data.append(i32 { mag: 99, sign: true });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 11, sign: false });\n    data.append(i32 { mag: 29, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 2, sign: true });\n    data.append(i32 { mag: 127, sign: true });\n    data.append(i32 { mag: 117, sign: true });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 39, sign: false });\n    data.append(i32 { mag: 17, sign: true });\n    data.append(i32 { mag: 67, sign: false });\n    data.append(i32 { mag: 9, sign: false });\n    data.append(i32 { mag: 42, sign: false });\n    data.append(i32 { mag: 112, sign: true });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 10, sign: true });\n    data.append(i32 { mag: 1, sign: true });\n    data.append(i32 { mag: 73, sign: true });\n    data.append(i32 { mag: 21, sign: false });\n    data.append(i32 { mag: 65, sign: true });\n    data.append(i32 { mag: 76, sign: true });\n    data.append(i32 { mag: 5, sign: true });\n    data.append(i32 { mag: 90, sign: true });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 75, sign: true });\n    data.append(i32 { mag: 36, sign: true });\n    data.append(i32 { mag: 71, sign: false });\n    data.append(i32 { mag: 45, sign: true });\n    data.append(i32 { mag: 82, sign: false });\n    data.append(i32 { mag: 13, sign: false });\n    data.append(i32 { mag: 5, sign: false });\n    data.append(i32 { mag: 81, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 13, sign: true });\n    data.append(i32 { mag: 22, sign: false });\n    data.append(i32 { mag: 28, sign: true });\n    data.append(i32 { mag: 46, sign: true });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 110, sign: true });\n    data.append(i32 { mag: 3, sign: true });\n    data.append(i32 { mag: 82, sign: true });\n    data.append(i32 { mag: 16, sign: false });\n    data.append(i32 { mag: 32, sign: false });\n    data.append(i32 { mag: 12, sign: false });\n    data.append(i32 { mag: 31, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 45, sign: false });\n    data.append(i32 { mag: 30, sign: true });\n    data.append(i32 { mag: 87, sign: true });\n    data.append(i32 { mag: 125, sign: true });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/generated/input.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{TensorTrait, Tensor, I32Tensor};\nuse orion::numbers::i32;\n\n\nfn input() -> Tensor<i32> {\n    let mut shape = ArrayTrait::<usize>::new();\n    shape.append(196);\n    let mut data = ArrayTrait::<i32>::new();\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 14, sign: false });\n    data.append(i32 { mag: 24, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 220, sign: false });\n    data.append(i32 { mag: 216, sign: false });\n    data.append(i32 { mag: 255, sign: false });\n    data.append(i32 { mag: 240, sign: false });\n    data.append(i32 { mag: 246, sign: false });\n    data.append(i32 { mag: 245, sign: false });\n    data.append(i32 { mag: 237, sign: false });\n    data.append(i32 { mag: 114, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 27, sign: false });\n    data.append(i32 { mag: 26, sign: false });\n    data.append(i32 { mag: 171, sign: false });\n    data.append(i32 { mag: 108, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 19, sign: false });\n    data.append(i32 { mag: 255, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 207, sign: false });\n    data.append(i32 { mag: 72, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 1, sign: false });\n    data.append(i32 { mag: 20, sign: false });\n    data.append(i32 { mag: 255, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 244, sign: false });\n    data.append(i32 { mag: 73, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 3, sign: false });\n    data.append(i32 { mag: 120, sign: false });\n    data.append(i32 { mag: 187, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 28, sign: false });\n    data.append(i32 { mag: 255, sign: false });\n    data.append(i32 { mag: 6, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 179, sign: false });\n    data.append(i32 { mag: 255, sign: false });\n    data.append(i32 { mag: 2, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    data.append(i32 { mag: 0, sign: false });\n    TensorTrait::new(shape.span(), data.span())\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/inference.cairo",
        "content": "// use orion::operators::tensor::core::TensorTrait;\n\n// use core::array::{SpanTrait, ArrayTrait};\n\n// use mnist_nn::nn::fc1;\n// use mnist_nn::nn::fc2;\n// use mnist_nn::generated::input::input;\n// use mnist_nn::generated::fc1_bias::fc1_bias;\n// use mnist_nn::generated::fc1_weights::fc1_weights;\n// use mnist_nn::generated::fc2_bias::fc2_bias;\n// use mnist_nn::generated::fc2_weights::fc2_weights;\n\n// use orion::operators::tensor::implementations::impl_tensor_fp::Tensor_fp;\n\n// fn main() -> u32 {\n//     let input = input();\n//     let fc1_bias = fc1_bias();\n//     let fc1_weights = fc1_weights();\n//     let fc2_bias = fc2_bias();\n//     let fc2_weights = fc2_weights();\n\n//     let x = fc1(input, fc1_weights, fc1_bias);\n//     let x = fc2(x, fc2_weights, fc2_bias);\n    \n//     let x = *x.argmax(0, Option::None(()), Option::None(())).data.at(0);\n\n//     x\n// }"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/lib.cairo",
        "content": "mod generated;\nmod nn;\nmod test;\nmod inference;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/nn.cairo",
        "content": "use orion::operators::tensor::core::Tensor;\nuse orion::numbers::signed_integer::{integer_trait::IntegerTrait, i32::i32};\nuse orion::operators::nn::{NNTrait, I32NN};\n\nfn fc1(i: Tensor<i32>, w: Tensor<i32>, b: Tensor<i32>) -> Tensor<i32> {\n    let x = NNTrait::linear(i, w, b);\n    NNTrait::relu(@x)\n}\n\nfn fc2(i: Tensor<i32>, w: Tensor<i32>, b: Tensor<i32>) -> Tensor<i32> {\n    NNTrait::linear(i, w, b)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/mnist_nn/src/test.cairo",
        "content": "use core::array::SpanTrait;\n\nuse mnist_nn::nn::fc1;\nuse mnist_nn::nn::fc2;\nuse mnist_nn::generated::input::input;\nuse mnist_nn::generated::fc1_bias::fc1_bias;\nuse mnist_nn::generated::fc1_weights::fc1_weights;\nuse mnist_nn::generated::fc2_bias::fc2_bias;\nuse mnist_nn::generated::fc2_weights::fc2_weights;\n\nuse orion::operators::tensor::{I32Tensor, Tensor};\nuse orion::numbers::i32;\n\n#[test]\n#[available_gas(99999999999999999)]\nfn mnist_nn_test() {\n    let input = input();\n    let fc1_bias = fc1_bias();\n    let fc1_weights = fc1_weights();\n    let fc2_bias = fc2_bias();\n    let fc2_weights = fc2_weights();\n\n    let x = fc1(input, fc1_weights, fc1_bias);\n    let x = fc2(x, fc2_weights, fc2_bias);\n\n    let x = *x.argmax(0, Option::None(()), Option::None(())).data.at(0);\n\n    assert(x == 7, 'should predict 7');\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/notebooks/fp16x16 to decimal converter.ipynb",
        "content": "{\r\n \"cells\": [\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": 7,\r\n   \"id\": \"c7d8c871\",\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"def fp16x16_to_decimal(fp_number):\\n\",\r\n    \"    whole_number = (fp_number >> 16) & 0xFFFF\\n\",\r\n    \"    fractional_part = fp_number & 0xFFFF\\n\",\r\n    \"    decimal_value = whole_number + (fractional_part / 65536)  # Divide by 2^16\\n\",\r\n    \"    return decimal_value\\n\",\r\n    \"\\n\",\r\n    \"def decimal_to_fp16x16(decimal_number):\\n\",\r\n    \"    whole_number = int(decimal_number)\\n\",\r\n    \"    fractional_part = int((decimal_number - whole_number) * 65536)  # Multiply by 2^16\\n\",\r\n    \"    fp_number = (whole_number << 16) + fractional_part\\n\",\r\n    \"    return fp_number\\n\",\r\n    \"\\n\",\r\n    \"def hex_to_decimal(hex_string):\\n\",\r\n    \"    try:\\n\",\r\n    \"        decimal_number = int(hex_string, 16)\\n\",\r\n    \"        return decimal_number\\n\",\r\n    \"    except ValueError:\\n\",\r\n    \"        return \\\"Invalid hexadecimal input\\\"\\n\",\r\n    \"    \\n\",\r\n    \"def fp16x16_hex_to_decimal(hex_string):\\n\",\r\n    \"    hex_to_decimal_variable = hex_to_decimal(hex_string)\\n\",\r\n    \"    decimal_value = fp16x16_to_decimal(hex_to_decimal_variable)\\n\",\r\n    \"    return decimal_value\\n\",\r\n    \"\\n\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": 9,\r\n   \"id\": \"b0d907a8\",\r\n   \"metadata\": {},\r\n   \"outputs\": [\r\n    {\r\n     \"data\": {\r\n      \"text/plain\": [\r\n       \"38.45289611816406\"\r\n      ]\r\n     },\r\n     \"execution_count\": 9,\r\n     \"metadata\": {},\r\n     \"output_type\": \"execute_result\"\r\n    }\r\n   ],\r\n   \"source\": [\r\n    \"felt_to_number(\\\"0x2673f1\\\")\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"id\": \"9fe1872d\",\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": []\r\n  }\r\n ],\r\n \"metadata\": {\r\n  \"kernelspec\": {\r\n   \"display_name\": \"Python 3 (ipykernel)\",\r\n   \"language\": \"python\",\r\n   \"name\": \"python3\"\r\n  },\r\n  \"language_info\": {\r\n   \"codemirror_mode\": {\r\n    \"name\": \"ipython\",\r\n    \"version\": 3\r\n   },\r\n   \"file_extension\": \".py\",\r\n   \"mimetype\": \"text/x-python\",\r\n   \"name\": \"python\",\r\n   \"nbconvert_exporter\": \"python\",\r\n   \"pygments_lexer\": \"ipython3\",\r\n   \"version\": \"3.9.13\"\r\n  }\r\n },\r\n \"nbformat\": 4,\r\n \"nbformat_minor\": 5\r\n}\r\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/notebooks/verifiable_simple_linear_regression_model.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4a28cde5\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Verifiable Simple Linear Regression model\\n\",\n    \"\\n\",\n    \"Simple Linear Regression model is a foundational technique used to determine the linear relationship between an independent variables (predictors) and a dependent variable (outcome) . By identifying the line of best fit, we can make informed predictions based on new data points or decipher how changes in one variable may lead to changes in another. \\n\",\n    \"\\n\",\n    \"The following is a small run through of the implementation of a Simple Linear Regression model using <b>Ordinary Least Squares</b> (OLS) in python, which we will in later stages convert it to Cairo  to turn it into a  <b>\\\"Verifiable Linear Regression model\\\" </b>. By utilysing the <b>Orion's</b> library we will be able to add an extra layer of transparency and robustness enabling us to make <b>verifiable inferences</b>  which  can be easily <b>proved</b> using the LambdaClass STARK Prover.\\n\",\n    \"\\n\",\n    \"In this particular exercise, we'll replicate the entire linear regression model in Cairo. This approach will not only enable us to validate each individual inference made to the model but also allow us to verify all the steps executed during the model's construction phase also. This is to provide an opportunity to get familiar with Orion's main functions and operators along the process. \\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2d479a73\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Generate a synthetic dataset\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 58,\n   \"id\": \"f60750c4\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"X values =  [-0.5        -0.49328859 -0.48657718 -0.47986577 -0.47315436 -0.46644295\\n\",\n      \" -0.45973154 -0.45302013 -0.44630872 -0.43959732 -0.43288591 -0.4261745\\n\",\n      \" -0.41946309 -0.41275168 -0.40604027 -0.39932886 -0.39261745 -0.38590604\\n\",\n      \" -0.37919463 -0.37248322 -0.36577181 -0.3590604  -0.35234899 -0.34563758\\n\",\n      \" -0.33892617 -0.33221477 -0.32550336 -0.31879195 -0.31208054 -0.30536913\\n\",\n      \" -0.29865772 -0.29194631 -0.2852349  -0.27852349 -0.27181208 -0.26510067\\n\",\n      \" -0.25838926 -0.25167785 -0.24496644 -0.23825503 -0.23154362 -0.22483221\\n\",\n      \" -0.21812081 -0.2114094  -0.20469799 -0.19798658 -0.19127517 -0.18456376\\n\",\n      \" -0.17785235 -0.17114094 -0.16442953 -0.15771812 -0.15100671 -0.1442953\\n\",\n      \" -0.13758389 -0.13087248 -0.12416107 -0.11744966 -0.11073826 -0.10402685\\n\",\n      \" -0.09731544 -0.09060403 -0.08389262 -0.07718121 -0.0704698  -0.06375839\\n\",\n      \" -0.05704698 -0.05033557 -0.04362416 -0.03691275 -0.03020134 -0.02348993\\n\",\n      \" -0.01677852 -0.01006711 -0.0033557   0.0033557   0.01006711  0.01677852\\n\",\n      \"  0.02348993  0.03020134  0.03691275  0.04362416  0.05033557  0.05704698\\n\",\n      \"  0.06375839  0.0704698   0.07718121  0.08389262  0.09060403  0.09731544\\n\",\n      \"  0.10402685  0.11073826  0.11744966  0.12416107  0.13087248  0.13758389\\n\",\n      \"  0.1442953   0.15100671  0.15771812  0.16442953  0.17114094  0.17785235\\n\",\n      \"  0.18456376  0.19127517  0.19798658  0.20469799  0.2114094   0.21812081\\n\",\n      \"  0.22483221  0.23154362  0.23825503  0.24496644  0.25167785  0.25838926\\n\",\n      \"  0.26510067  0.27181208  0.27852349  0.2852349   0.29194631  0.29865772\\n\",\n      \"  0.30536913  0.31208054  0.31879195  0.32550336  0.33221477  0.33892617\\n\",\n      \"  0.34563758  0.35234899  0.3590604   0.36577181  0.37248322  0.37919463\\n\",\n      \"  0.38590604  0.39261745  0.39932886  0.40604027  0.41275168  0.41946309\\n\",\n      \"  0.4261745   0.43288591  0.43959732  0.44630872  0.45302013  0.45973154\\n\",\n      \"  0.46644295  0.47315436  0.47986577  0.48657718  0.49328859  0.5       ]\\n\",\n      \"y values =  [4.04967142 3.99959639 4.09161449 4.19257144 4.03027594 4.0437004\\n\",\n      \" 4.23845819 4.1707032  4.06043511 4.17506137 4.08788642 4.10107803\\n\",\n      \" 4.18527005 3.98316862 4.01542768 4.14511353 4.11348199 4.25961265\\n\",\n      \" 4.15080833 4.11380319 4.41502125 4.25930156 4.30205483 4.16625001\\n\",\n      \" 4.26770938 4.34666273 4.23389393 4.39998591 4.31577506 4.36009237\\n\",\n      \" 4.3425139  4.6013352  4.42818048 4.33718193 4.53863033 4.34771429\\n\",\n      \" 4.50410784 4.30067728 4.37724851 4.54317606 4.61075941 4.5674724\\n\",\n      \" 4.55219356 4.54707084 4.44275183 4.53204242 4.57138579 4.73658471\\n\",\n      \" 4.67865713 4.48141411 4.70354934 4.64605553 4.63029438 4.77257702\\n\",\n      \" 4.82793217 4.83138305 4.6677561  4.73417943 4.81164983 4.88950082\\n\",\n      \" 4.7574517  4.80022605 4.72158127 4.72601692 4.94031298 5.00810722\\n\",\n      \" 4.87870503 4.99968215 4.94891528 4.86166252 4.97573688 5.10682379\\n\",\n      \" 4.96286035 5.13633014 4.73131408 5.08890166 5.02883894 5.00365631\\n\",\n      \" 5.05615594 4.86164579 5.05185831 5.12295958 5.24846055 5.06226694\\n\",\n      \" 5.04666742 5.09076389 5.24590263 5.20066035 5.12823203 5.24595762\\n\",\n      \" 5.21776145 5.31834101 5.16469402 5.21555593 5.22253415 5.12881629\\n\",\n      \" 5.31820263 5.32811895 5.31594759 5.30540035 5.2007448  5.31364017\\n\",\n      \" 5.33485607 5.30232261 5.37984458 5.44980106 5.61143738 5.45369939\\n\",\n      \" 5.47541947 5.45564266 5.28463295 5.4872815  5.50937873 5.76310273\\n\",\n      \" 5.51096525 5.5737789  5.5535758  5.45360199 5.6981749  5.67250874\\n\",\n      \" 5.68984145 5.53322233 5.77786332 5.51082161 5.72311524 5.89689791\\n\",\n      \" 5.59222154 5.64806821 5.72808594 5.68119606 5.5899001  5.76524556\\n\",\n      \" 5.66558171 5.83259414 5.70671529 5.96707398 5.74717803 5.80672002\\n\",\n      \" 5.93370072 5.74268538 5.90194062 6.02333173 5.74529195 5.93792647\\n\",\n      \" 5.95887419 6.02449101 5.83603647 5.8411087  6.03877134 6.02969847]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import os\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"# Constants for reproducibility\\n\",\n    \"SEED = 42\\n\",\n    \"np.random.seed(SEED)\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"X = np.linspace(-0.5, 0.5, 150).astype('float64')\\n\",\n    \"noise = np.random.normal(0, 0.1, len(X)).astype('float64')\\n\",\n    \"y = 2 * X + 5 + noise # y=2x+5 + error\\n\",\n    \"\\n\",\n    \"print('X values = ',X)\\n\",\n    \"print('y values = ', y)\\n\",\n    \"   \\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 59,\n   \"id\": \"fa6fc5c0\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"Text(0, 0.5, 'y values')\"\n      ]\n     },\n     \"execution_count\": 59,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAjcAAAGwCAYAAABVdURTAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAAC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vz4MPu9deP6asHJg1Vfp51MGQ+Y8aFhXHtd+Npn5vbbrtNa9as0b/+9S/b90ybNk0vvPCCNmzY0PjaJZdcov3792vFihUtrq+rq1NdXV3j9zU1NerRowd9bgAArYZZ/SSpSaKwGW40L9V2cr3ZC6d0Y5WWle/U3trDjdd71efG0+CmsLBQ5557rr744gu99tpr6t69u37+859rypQplvecffbZGjp0qO65557G1x577DHdeOONqq6ubnH9zJkzNWvWrBavE9wAAFoTN/vcWAUrsRzFkDTBTVbWsa2sm2++WT/60Y/09ttva+rUqXrwwQd1xRVXBL3npJNO0lVXXaXp06c3vvbiiy9q/PjxOnTokNq1a9fkenZuAADJzM2Awc0OxfGWNB2KGxoadPrpp+vOO++UJJ166qnasGFDyODGqczMTGVmZrryLAAA4imS3ZNQ2qT5NKJP55DXJFJAEylPg5v8/HwVFhY2ea1///565plnLO/x+/3atWtXk9d27dql3NzcFrs2AAAkK6vZTbEcaeB2MOUVT6ulRo4cqU8++aTJa59++ql69uxpec+IESP08ssvN3mttLRUI0aMiMkaAQCIN6ddhd3gdERDIvM0uLnpppv0xhtv6M4779TmzZu1aNEiPfzww7ruuusar5k+fbouv/zyxu9/9rOf6bPPPtOvfvUrffzxx7r//vv15JNP6qabbvLiVwAAwHVOuwpH6/DRBv166Ya4BlOx5Glw81//9V9aunSpFi9erAEDBmj27Nm65557VFJS0nhNZWWltm3b1vh979699cILL6i0tFSDBw/W3XffrUcffVTnnnuuF78CAACuc9pVuL7BUFnFHi0v36Gyij2OgpAVGyo1fM7KJiXczXkxHyoanubcSNIFF1ygCy64wPLnwboPf+c739F7770Xw1UBAOAdJ12Fo8mTscrrsRLP+VDR8Hz8AgAAaMpul+B9tYcjzpMJlddjJZ7zoaJBcAMAQIJpk+bTjAuPVRM3D3DM728f31+zX4g86ThcXk/z94z3fKhoENwAAJCAxg3I1wOThsrfbHaTPy9LD0waqo7ZmVElHTs9Yor3fKhoeJ5zAwAAghs3IF9jC/1Bm+otL99h6xlrNn8VtCGf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kOHDlV6errS09P12muv6Y9//KPS09NVX1/f4h6/369du3Y1eW3Xrl3y+/3xWrYls+eN5F434WjYPSb7zfj+BDYAgJTiWXDz3e9+V+vXr1d5eXnj1+mnn66SkhKVl5erTZs2Le4ZMWKEXn755SavlZaWasSIEfFadkhWPW/8Lpd222H3mMyf1y7GKwEAIL48O5bKycnRgAEDmryWnZ2tzp07N75++eWXq3v37pozZ44kaerUqRo9erTuvvtujR8/XkuWLNE777yjhx9+OO7rtzJuQH5ckoXDSbRjMgAA4sXzUvBQtm3bpsrKysbvzzzzTC1atEgPP/ywBg8erKefflrLli1rESR5LZpuwm6uIZGOyQAAiBefYRitqud+TU2N8vLyVF1drdzcXK+XE3MMywQApAInf78973OD2EqUYzIAAOKF4KYViHVPHQAAEklC59wAAAA4RXADAABSCsENAABIKQQ3AAAgpRDcAACAlEJwAwAAUgrBDQAASCkENwAAIKUQ3AAAgJTS6joUm6O0ampqPF4JAACwy/y7bWckZqsLbg4cOCBJ6tGjh8crAQAATh04cEB5eXkhr2l1U8EbGhq0c+dO5eTkyOdjeGRNTY169Oih7du3t4op6V7hc44PPuf44HOOHz7r/zAMQwcOHFC3bt2UlhY6q6bV7dykpaXpW9/6ltfLSDi5ubmt/v9w4oHPOT74nOODzzl++KyPCbdjYyKhGAAApBSCGwAAkFIIblq5zMxMzZgxQ5mZmV4vJaXxOccHn3N88DnHD591ZFpdQjEAAEht7NwAAICUQnADAABSCsENAABIKQQ3AAAgpRDctEJ79+5VSUmJcnNz1aFDB02ePFkHDx60da9hGDrvvPPk8/m0bNmy2C40yTn9nPfu3asbbrhB/fr1U7t27XTiiSfqF7/4haqrq+O46sR33333qVevXsrKytKwYcP01ltvhbz+qaee0sknn6ysrCwNHDhQL774YpxWmtycfM6PPPKIzjrrLHXs2FEdO3ZUUVFR2P9d8B9O/502LVmyRD6fTxMnToztApMQwU0rVFJSog8//FClpaV6/vnn9frrr+uaa66xde8999zD2AqbnH7OO3fu1M6dO3XXXXdpw4YNWrhw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ZeJ/0gvsxE13feeafxtX/84x8hE10rKyuN9evXN/mSZCxYsMD47LPP4rX0pBLJ52wYhlFdXW0MHz7cGD16tFFbWxuPpSaVM844w7j++usbv6+vrze6d+8eMqH4ggsuaPLaiBEjSCgOw+nnbBiGMW/ePCM3N9coKyuLxxJThpPP+uuvv27x3+IJEyYYY8aMMdavX2/U1dXFc+kJjeCmFRo3bpxx6qmnGm+++aaxevVqo6CgwCguLm78+RdffGH069fPePPNNy2fIaqlwnL6OVdXVxvDhg0zBg4caGzevNmorKxs/Dp69KhXv0ZCWbJkiZGZmWksXLjQ2Lhxo3HNNdcYHTp0MKqqqgzDMIzLLrvMuO222xqvX7NmjZGenm7cddddxkcffWTMmDHDyMjIMNavX+/Vr5AUnH7Oc+fONdq2bWs8/fTTTf69PXDggFe/QtJw+lk3R7VUcAQ3rdCePXuM4uJi47jjjjNyc3ONq666qsl/hLZs2WJIMl555RXLZxDchOf0c37llVcMSUG/tmzZ4s0vkYD+9Kc/GSeeeKLRtm1b44wzzjDeeOONxp+NHj3auOKKK5pc/+STTxonnXSS0bZtW+OUU04xXnjhhTivODk5+Zx79uwZ9N/bGTNmxH/hScjpv9OBCG6C8xmGYcT7KAwAACBWqJYCAAApheAGAACkFIIbAACQUghuAABASiG4AQAAKYXgBgAApBSCGwAAkFIIbgAAQEohuAGQsnw+n5YtW+b1MgDEGcENgJipr6/XmWeeqR/84AdNXq+urlaPHj30P//zPx6tDEAqI7gBEDNt2rTRwoULtWLFCj3xxBONr99www3q1KmTZsyY4eHqAKQqghsAMXXSSSdp7ty5uuGGG1RZWanly5dryZIl+utf/6q2bdsGvefXv/61hg0b1uL1wYMH64477pAkvf322xo7dqy6dOmivLw8jR49WuvWrbNcx6uvviqfz6f9+/c3vlZeXi6fz6etW7c2vrZ69WqdddZZateunXr06KFf/OIXqq2tbfz5/fffr4KCAmVlZalr16767//+b4efCIBYI7gBEHM33HCDBg8erMsuu0zXXHON/t//+38aPHiw5fUlJSV66623VFFR0fjahx9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bZ2RmZhrt27c3Dhw40ORn69atM04//XQjKyvLKCgoMJ566imjZ8+exvz58xuvUUBCsWEYxurVq42BAwcaWVlZxllnnWU89dRTTRKKDcMw3nrrLWPs2LHGcccdZ2RnZxuDBg0yfve73xmGcSy5ePTo0UbHjh2Ndu3aGYMGDTL+/ve/R/bhAIgZn2GEOfgGAABIIhxLAQCAlEJwAwAAUgrBDQAASCkENwAAIKUQ3AAAgJRCcAMAAFIKwQ0AAEgpBDcAACClENwAAICUQnADAABSCsENAABIKf8fMj+pJAWpTtEAAAAASUVORK5CYII=\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"plt.scatter(X,y)\\n\",\n    \"plt.xlabel('X values')\\n\",\n    \"plt.ylabel('y values')\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"68a91d93\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Equation of a straight line \\n\",\n    \"\\n\",\n    \"<br>\\n\",\n    \"\\n\",\n    \"<img src=\\\"line_equation.gif\\\" width=\\\"200px\\\" height=\\\"200px\\\" align=\\\"left\\\">   <br><br>\\n\",\n    \"\\n\",\n    \"**y:** y values  \\n\",\n    \"**x:** x values  \\n\",\n    \"**b:** gradient  \\n\",\n    \"**a:** y intercept  \\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4999fbae\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Calculating the gradient of the line of best fit\\n\",\n    \"<br>\\n\",\n    \"\\n\",\n    \"<img src=\\\"gradient.png\\\" width=\\\"230px\\\" height=\\\"230px\\\" align=\\\"left\\\">\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 60,\n   \"id\": \"7fe2a45b\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"The slope of regression line: 2.0133337976122685\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"numerator = sum((X - X.mean()) * (y - y.mean()))\\n\",\n    \"denominator = sum((X - X.mean())**2)\\n\",\n    \"\\n\",\n    \"beta = numerator / denominator\\n\",\n    \"print('The slope of regression line:', beta)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"5d126c20\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Calculating the y intercept\\n\",\n    \"\\n\",\n    \"<br>\\n\",\n    \"\\n\",\n    \"<img src=\\\"intercept.png\\\" width=\\\"150px\\\" height=\\\"150px\\\" align=\\\"left\\\">\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 61,\n   \"id\": \"4f3979d7\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"The y intercept of our regression line: 4.991767313284746\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"intercept = y.mean() - beta * X.mean()\\n\",\n    \"print('The y intercept of our regression line:', intercept)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 62,\n   \"id\": \"88c5f347\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Given x=0.17 , our model predicts the corresponing y value shoud be 5.3340340588788315\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# making new predictions using our model\\n\",\n    \"predicted_y_value = beta * 0.17 + intercept \\n\",\n    \"print(f'Given x=0.17 , our model predicts the corresponing y value shoud be {predicted_y_value}')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 63,\n   \"id\": \"d73113cf\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAjcAAAHHCAYAAABDUnkqAAAAOXR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mDQMGDGDEiBFERESwZMkSTp48yYEDB/QjCmvWrMHb25u3334bb29v9uzZw4cffkhsbCxz5swxuPeDBw/o1KkTPXv25JVXXqF06dI29//q1asA+Pv764/t2bOHTp060ahRIyZNmoSTkxOrV6+mTZs2/P777/oRnpMnTxIaGkpgYCBTpkxBrVYzdepUSpYsafRee/bs4fvvv2fYsGGUKFGCihUrcufOHZo2baoPHEqWLMm2bdsYOHAgsbGxjBo1CtBOJ40YMYIXX3yRkSNHkpSUxOnTpzly5Ai9e/cG4M033+THH39k2LBhhISE8ODBA/744w8uXLhAw4YNjfZJURSee+459u7dy8CBA6lfvz47duxg3Lhx3Lp1i/nz5xu0/+OPP9iwYQNvvfUWPj4+LFq0iBdeeIHr169TvHhxm5+/EPmKIoTIN1avXq0AyrFjx0y2iYiIUABl9erV+mP9+vVTAGXq1KkGbRs0aKA0atRI//r3339XAOWbb74xaLd9+/ZMxxMTEzPde/DgwYqnp6eSlJSkP9aqVSsFUJYvX27VZ5w0aZICKBcvXlTu3bunXL16VVm1apVSpEgRpWTJkkpCQoKiKIqi0WiUqlWrKh07dlQ0Go1BvypVqqS0b99ef6xr166Kp6encuvWLf2xS5cuKS4uLkrGfwYBxcnJSTl37pzB8YEDByqBgYHK/fv3DY737NlTKVq0qP55dOvWTalVq5bZz1i0aFFl6NChZtv069dPqVChgv71pk2bFECZPn26QbsXX3xRUalUyuXLlw0+g5ubm8GxU6dOKYCyePFis/cVoiCQaSkhCpE333zT4HXLli35559/9K9/+OEHihYtSvv27bl//77+V6NGjfD29mbv3r36tkWKFNH/Pi4ujvv379OyZUsSExP566+/DO7j7u7OgAEDbOpr9erVKVmyJBUrVuS1116jSpUqbNu2Tb9WJzw8nEuXLtG7d28ePHig72tCQgJt27Zl//79aDQa1Go1u3btonv37pQpU0Z//SpVqtCpUyej927VqhUhISH614qi8NNPP9G1a1cURTF4Nh07diQmJkY/peTn58fNmzc5duyYyc/m5+fHkSNHuH37ttXPY+vWrTg7OzNixAiD42PGjE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dTZ8+ffD19cXPz4+BAwcSHx9v1bmKotCpUydUKhWbNm3K3Y7mc7Y+5+joaIYPH0716tUpUqQI5cuXZ8SIEcTExNix13nfp59+SsWKFfHw8ODJJ5/k6NGjZtv/8MMP1KhRAw8PD+rUqcPWrVvt1NP8zZbnvGLFClq2bIm/vz/+/v60a9fO4p+L+I+t32mddevWoVKp6N69e+52MB+S4KYQ6tOnD+fOnSMsLIwtW7awf/9+3njjDavOXbBggZStsJKtz/n27dvcvn2buXPncvbsWdasWcP27dsZOHCgHXudt61fv563336bSZMmceLECerVq0fHjh25e/eu0fYHDx6kV69eDBw4kJMnT9K9e3e6d+/O2bNn7dzz/MXW57xv3z569erF3r17OXToEEFBQXTo0IFbt27Zuef5j63PWufq1auMHTuWli1b2qmn+YwiCpXz588rgHLs2DH9sW3btikqlUq5deuW2XNPnjyplC1bVomMjFQAZePGjbnc2/wrO885ve+//15xc3NTUlNTc6Ob+U6TJk2UoUOH6l+r1WqlTJkyyowZM4y2f+mll5QuXboYHHvyySeVwYMH52o/8ztbn3NGaWlpio+Pj7J27drc6mKBkZVnnZaWpjRv3lxZuXKl0q9fP6Vbt2526Gn+IiM3hcyhQ4fw8/OjcePG+mPt2rXDycmJI0eOmDwvMTGR3r178+mnnxIQEGCPruZrWX3OGcXExODr64uLS6ErA5dJSkoKx48fp127dvpjTk5OtGvXjkOHDhk959ChQwbtATp27Giyvcjac84oMTGR1NRUihUrllvdLBCy+qynTp1KqVKlZFTXDPkXs5CJioqiVKlSBsdcXFwoVqwYUVFRJs8bPXo0zZs3p1u3brndxQIhq885vfv37zNt2jSrpwwLuvv376NWqyldurTB8dKlS/PXX38ZPScqKspoe2v/DAqjrDznjCZMmECZMmUyBZbCUFae9R9//MEXX3xBeHi4HXqYf8nITQHxzjvvoFKpzP6y9h+mjDZv3syePXtYsGBBznY6H8rN55xebGwsXbp0ISQkhMmTJ2e/40LYycyZM1m3bh0bN27Ew8PD0d0pUOLi4nj11VdZsWIFJUqUcHR38jQZ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Rw+OHTtGvXr1HN01IYSdSXAjhCgQFEWhTZs2ODs7c+bMGYYPH87777/v6G4JIRxAghshRIHx119/UbNmTerUqcOJEydwcXFxdJeEEA4gC4qFEAXGqlWr8PT0JCIigps3bzq6O0IIB5GRGyFEgXDw4EFatWrFzp07mT59OgC7du1CpVI5uGdCCHuTkRshRL6XmJhI//79GTJkCM888wxffPEFR48eZfny5Y7umhDCAWTkRgiR740cOZKtW7dy6tQpPD09Afjss88YO3YsZ86coWLFio7toBDCriS4EULka7/99htt27Zl3759PPXUUwbvdezYkbS0NJmeEqKQkeBGCCGEEAWKrLkRQgghRIEiwY0QQgghChQJboQQQghRoEhwI4QQQogCRYIbIYQQQhQoEtwIIYQQokCR4EYIIYQQBYoEN0IIIYQoUCS4EUIIIUSBIsGNEEIIIQoUCW6EEEIIUaBIcCOEEEKIAuX/C6Xw6OcfJXcAAAAASUVORK5CYII=\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Calculated beta: 2.0133337976122685\\n\",\n      \"Calculated intercept: 4.991767313284746\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"plt.scatter(X, y, label='Data Points')\\n\",\n    \"plt.plot(X, beta * X + intercept, color='red', label='Regression Line')\\n\",\n    \"plt.scatter(0.17,predicted_y_value, color='green', label='pred for x = 0.17 ')\\n\",\n    \"plt.xlabel('X')\\n\",\n    \"plt.ylabel('y')\\n\",\n    \"plt.title('Linear Regression')\\n\",\n    \"plt.legend()\\n\",\n    \"plt.grid(True)\\n\",\n    \"plt.show()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"print(f\\\"Calculated beta: {beta}\\\")\\n\",\n    \"print(f\\\"Calculated intercept: {intercept}\\\")\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"07ce1abf\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Calculating the accuracy of our linear regression model\\n\",\n    \"\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 64,\n   \"id\": \"e4a526a3\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Mean Squared Error (MSE): 0.008805873341370826\\n\",\n      \"R-squared (R^2): 0.974921526753728\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"y_pred = beta * X + intercept\\n\",\n    \"\\n\",\n    \"mse = np.mean((y - y_pred)**2)\\n\",\n    \"y_mean = np.mean(y)\\n\",\n    \"r_squared = 1 - np.sum((y - y_pred)**2) / np.sum((y - y_mean)**2)\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"print(\\\"Mean Squared Error (MSE):\\\", mse)\\n\",\n    \"print(\\\"R-squared (R^2):\\\", r_squared)\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f0e27741\",\n   \"metadata\": {},\n   \"source\": [\n    \"#  Replicating the linear regression model using the Orion library\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"da10af23\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Create a scarb project \\n\",\n    \"Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation <a src='https://github.com/gizatechxyz/orion/blob/develop/docs/framework/get-started.md#installations'>here</a>\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 65,\n   \"id\": \"a07f433b\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"\\u001b[31merror\\u001b[0m: destination `verifiable_linear_regression` already exists\\n\",\n      \"help: use `scarb init` to initialize the directory\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"! scarb new verifiable_linear_regression\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b27b16d7\",\n   \"metadata\": {},\n   \"source\": [\n    \"A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"06745de8\",\n   \"metadata\": {},\n   \"source\": [\n    \"```tom\\n\",\n    \"[package]\\n\",\n    \"name = \\\"verifiable_linear_regression\\\"\\n\",\n    \"version = \\\"0.1.0\\\"\\n\",\n    \"\\n\",\n    \"[dependencies]\\n\",\n    \"orion = { git = \\\"https://github.com/gizatechxyz/orion.git\\\", branch = \\\"develop\\\"   }\\n\",\n    \"\\n\",\n    \"[scripts]\\n\",\n    \"test = \\\"scarb cairo-test -f linear_regression_test\\\"\\n\",\n    \"\\n\",\n    \"```\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"1d2536ce\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Generate the x and y values in cairo and importing the neccessary libs\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 68,\n   \"id\": \"c1b1057f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tensor_name =['X_values', 'Y_values']\\n\",\n    \"\\n\",\n    \"base_path = os.path.expanduser(\\\"~/verifiable_linear_regression/src\\\")\\n\",\n    \"\\n\",\n    \"def generate_cairo_files(data, name):\\n\",\n    \"    generated_path = os.path.join(base_path, 'generated')\\n\",\n    \"    os.makedirs(generated_path, exist_ok=True)\\n\",\n    \"\\n\",\n    \"    with open(os.path.join(generated_path, f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n    \"                \\\"use orion::operators::tensor::{{FP16x16Tensor, TensorTrait, Tensor}};\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::{{FixedTrait, FP16x16, FP16x16Impl}};\\\\n\\\"\\n\",\n    \"                \\\"\\\\nfn {0}() -> Tensor<FixedType>  \\\".format(name) + \\\"{{\\\\n\\\" +\\n\",\n    \"                \\\"    let mut shape = ArrayTrait::new();\\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"            for dim in data.shape:\\n\",\n    \"                f.write(\\\"    shape.append({0});\\\\n\\\".format(dim))\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"    let mut data = ArrayTrait::new();\\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"            for val in np.nditer(data.flatten()):\\n\",\n    \"                f.write(\\\"    data.append(FixedTrait::new({0}, {1} ));\\\\n\\\".format(abs(int(val * 2**16)), str(val < 0).lower()))\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"let tensor = TensorTrait::<FixedType>::new(shape.span(), data.span()); \\\\n \\\\n\\\" +\\n\",\n    \"                \\\"return tensor;\\\\n\\\\n\\\"+\\n\",\n    \"                \\\"}\\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"    with open(os.path.join(base_path, 'generated.cairo'), 'w') as f:\\n\",\n    \"        for param_name in tensor_name:\\n\",\n    \"            f.write(f\\\"mod {param_name};\\\\n\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 69,\n   \"id\": \"e1f168e7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(X, 'X_values')\\n\",\n    \"generate_cairo_files(y, 'Y_values')\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"31671139\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Building our OLS functions in cairo using Orion lib\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 75,\n   \"id\": \"c7204a1b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch verifiable_linear_regression/src/lin_reg_func.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 76,\n   \"id\": \"4c0b8e16\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting verifiable_linear_regression/src/lin_reg_func.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile verifiable_linear_regression/src/lin_reg_func.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"\\n\",\n    \"/// Calculates the mean of a given 1D tensor.\\n\",\n    \"fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\\n\",\n    \"\\n\",\n    \"    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\\n\",\n    \"    let mean = *sum_result / tensor_size;\\n\",\n    \"\\n\",\n    \"    return mean;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"/// Calculates the deviation of each element from the mean of the provided 1D tensor.\\n\",\n    \"fn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mean_value = calculate_mean(tensor_data);\\n\",\n    \"\\n\",\n    \"    let mut tensor_shape = array::ArrayTrait::new();\\n\",\n    \"    tensor_shape.append(tensor_data.data.len());\\n\",\n    \"\\n\",\n    \"    let mut deviation_values = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= tensor_data.data.len() {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let distance_from_mean = *tensor_data.data.at(i) - mean_value;\\n\",\n    \"        deviation_values.append(distance_from_mean);\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let distance_from_mean_tensor = TensorTrait::<FP16x16>::new(\\n\",\n    \"        tensor_shape.span(), deviation_values.span()\\n\",\n    \"    );\\n\",\n    \"\\n\",\n    \"    return distance_from_mean_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"/// Calculates the beta value for linear regression.\\n\",\n    \"fn compute_beta(x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let x_deviation = deviation_from_mean(x_values);\\n\",\n    \"    let y_deviation = deviation_from_mean(y_values);\\n\",\n    \"\\n\",\n    \"    let x_y_covariance = x_deviation.matmul(@y_deviation);\\n\",\n    \"    let x_variance = x_deviation.matmul(@x_deviation);\\n\",\n    \"\\n\",\n    \"    let beta_value = *x_y_covariance.data.at(0) / *x_variance.data.at(0);\\n\",\n    \"\\n\",\n    \"    return beta_value;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"/// Calculates the intercept for linear regression.\\n\",\n    \"fn compute_intercept(\\n\",\n    \"    beta_value: FP16x16, x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>\\n\",\n    \") -> FP16x16 {\\n\",\n    \"    let x_mean = calculate_mean(x_values);\\n\",\n    \"    let y_mean = calculate_mean(y_values);\\n\",\n    \"\\n\",\n    \"    let mx = beta_value * x_mean;\\n\",\n    \"    let intercept = y_mean - mx;\\n\",\n    \"\\n\",\n    \"    return intercept;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"/// Predicts the y values using the provided x values and computed beta and intercept.\\n\",\n    \"fn predict_y_values(\\n\",\n    \"    beta_value: FP16x16, x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let beta = compute_beta(x_values, y_values);\\n\",\n    \"    let intercept = compute_intercept(beta_value, x_values, y_values);\\n\",\n    \"\\n\",\n    \"    //create a tensor to hold all the y_pred values\\n\",\n    \"    let mut y_pred_shape = array::ArrayTrait::new();\\n\",\n    \"    y_pred_shape.append(y_values.data.len());\\n\",\n    \"\\n\",\n    \"    let mut y_pred_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= y_values.data.len() {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        // (*x_values.data.at(i)).print();\\n\",\n    \"        let predicted_value = beta * *x_values.data.at(i) + intercept;\\n\",\n    \"        y_pred_vals.append(predicted_value);\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let y_pred_tensor = TensorTrait::<FP16x16>::new(y_pred_shape.span(), y_pred_vals.span());\\n\",\n    \"\\n\",\n    \"    return y_pred_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"/// Calculates the mean squared error between the true y values and the predicted y values.\\n\",\n    \"fn compute_mse(y_values: Tensor<FP16x16>, y_pred_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let mut squared_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_diff_shape.append(y_values.data.len());\\n\",\n    \"\\n\",\n    \"    let mut squared_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= y_values.data.len() {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let diff = *y_values.data.at(i) - *y_pred_values.data.at(i);\\n\",\n    \"        let squared_diff = diff * diff;\\n\",\n    \"        squared_diff_vals.append(squared_diff);\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let squared_diff_tensor = TensorTrait::<FP16x16>::new(\\n\",\n    \"        squared_diff_shape.span(), squared_diff_vals.span()\\n\",\n    \"    );\\n\",\n    \"\\n\",\n    \"    let mse = calculate_mean(squared_diff_tensor);\\n\",\n    \"\\n\",\n    \"    return mse;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"/// Calculates the R squared score.\\n\",\n    \"fn calculate_r_score(y_values: Tensor<FP16x16>, y_pred_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let mean_y_value = calculate_mean(y_values);\\n\",\n    \"\\n\",\n    \"    // creating the appropriate tensor shapes and empty arrays to populate values into\\n\",\n    \"    let mut squared_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_diff_shape.append(y_values.data.len());\\n\",\n    \"    let mut squared_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut squared_mean_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_mean_diff_shape.append(y_values.data.len());\\n\",\n    \"    let mut squared_mean_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= y_values.data.len() {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let diff_pred = *y_values.data.at(i) - *y_pred_values.data.at(i);\\n\",\n    \"        let squared_diff = diff_pred * diff_pred;\\n\",\n    \"        squared_diff_vals.append(squared_diff);\\n\",\n    \"\\n\",\n    \"        let diff_mean = *y_values.data.at(i) - mean_y_value;\\n\",\n    \"        let squared_mean_diff = diff_mean * diff_mean;\\n\",\n    \"        squared_mean_diff_vals.append(squared_mean_diff);\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let squared_diff_tensor = TensorTrait::<FP16x16>::new(\\n\",\n    \"        squared_diff_shape.span(), squared_diff_vals.span()\\n\",\n    \"    );\\n\",\n    \"    let squared_mean_diff_tensor = TensorTrait::<FP16x16>::new(\\n\",\n    \"        squared_mean_diff_shape.span(), squared_mean_diff_vals.span()\\n\",\n    \"    );\\n\",\n    \"\\n\",\n    \"    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_squared_mean_diff = squared_mean_diff_tensor\\n\",\n    \"        .cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"\\n\",\n    \"    let r_score = FixedTrait::new_unscaled(1, false)\\n\",\n    \"        - *sum_squared_diff.data.at(y_values.data.len() - 1)\\n\",\n    \"            / *sum_squared_mean_diff.data.at(y_values.data.len() - 1);\\n\",\n    \"\\n\",\n    \"    return r_score;\\n\",\n    \"}\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"cdc968d1\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Running test on our model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 77,\n   \"id\": \"cd53bcfb\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Writing verifiable_linear_regression/src/test.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile verifiable_linear_regression/src/test.cairo\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"\\n\",\n    \"use verifiable_linear_regression::generated::X_values::X_values;\\n\",\n    \"use verifiable_linear_regression::generated::Y_values::Y_values;\\n\",\n    \"use verifiable_linear_regression::lin_reg_func::{\\n\",\n    \"    calculate_mean, deviation_from_mean, compute_beta, compute_intercept, predict_y_values,\\n\",\n    \"    compute_mse, calculate_r_score\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"#[test]\\n\",\n    \"#[available_gas(99999999999999999)]\\n\",\n    \"fn linear_regression_test() {\\n\",\n    \"    // Fetching the x and y values\\n\",\n    \"    let y_values = Y_values();\\n\",\n    \"    let x_values = X_values();\\n\",\n    \"\\n\",\n    \"    // (*x_values.data.at(18)).print();\\n\",\n    \"\\n\",\n    \"    let beta_value = compute_beta(x_values, y_values);\\n\",\n    \"    // beta_value.print();    // calculated gradient value\\n\",\n    \"\\n\",\n    \"    let intercept_value = compute_intercept(beta_value, x_values, y_values);\\n\",\n    \"    // intercept_value.print();   // calculated intercept value\\n\",\n    \"\\n\",\n    \"    let y_pred = predict_y_values(beta_value, x_values, y_values);\\n\",\n    \"\\n\",\n    \"    let mse = compute_mse(y_values, y_pred);\\n\",\n    \"    // mse.print();       // mean squared error ouput\\n\",\n    \"\\n\",\n    \"    let r_score = calculate_r_score(y_values, y_pred);\\n\",\n    \"    r_score.print(); // accuracy of model around 0.97494506835\\n\",\n    \"\\n\",\n    \"    assert(beta_value.mag > 0, 'x & y not positively correlated');\\n\",\n    \"    assert(r_score.mag > 0, 'R-Squared needs to be above 0');\\n\",\n    \"    assert(\\n\",\n    \"        r_score.mag < 65536, 'R-Squared has to be below 65536'\\n\",\n    \"    ); // 65536 represents ONE in fp16x16.\\n\",\n    \"    assert(r_score.mag > 32768, 'Accuracy below 50% ');\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 78,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting verifiable_linear_regression/src/lib.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile verifiable_linear_regression/src/lib.cairo\\n\",\n    \"\\n\",\n    \"mod generated;\\n\",\n    \"mod lin_reg_func;\\n\",\n    \"mod test;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Run test\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 81,\n   \"id\": \"ae8a18aa\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"\\u001b[2K\\u001b[32m\\u001b[1m   Compiling\\u001b[0m test(verifiable_linear_regression_unittest) verifiable_linear_regression v0.1.0 (/Users/raphaeldoukhan/Desktop/Orion-Giza/Academy/Tutorials/orion_tutorials/basic/verifiable_linear_regression_model/Scarb.toml)e --recurse-submodules /Users/ 0s\\n\",\n      \"\\u001b[32m\\u001b[1m    Finished\\u001b[0m release target(s) in 7 seconds\\n\",\n      \"testing verifiable_linear_regression ...\\n\",\n      \"running 1 tests\\n\",\n      \"[DEBUG]\\tfalse                          \\t(raw: 0x66616c7365\\n\",\n      \"\\n\",\n      \"[DEBUG]\\t                               \\t(raw: 0xf996 \\n\",\n      \"\\n\",\n      \"test verifiable_linear_regression::test::linear_regression_test ... \\u001b[92mok\\u001b[0m (gas usage est.: 273795540)\\n\",\n      \"test result: \\u001b[92mok\\u001b[0m. 1 passed; 0 failed; 0 ignored; 0 filtered out;\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"! cd verifiable_linear_regression\\n\",\n    \"! scarb cairo-test -f linear_regression_test\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cfbcc71c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.11\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/generated.cairo",
        "content": "mod X_values;\r\nmod Y_values;\r\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/generated/X_values.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{FP16x16Tensor, TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn X_values() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(150);\n    let mut data = ArrayTrait::new();\n    data.append(FixedTrait::new(32768, true));\n    data.append(FixedTrait::new(32328, true));\n    data.append(FixedTrait::new(31888, true));\n    data.append(FixedTrait::new(31448, true));\n    data.append(FixedTrait::new(31008, true));\n    data.append(FixedTrait::new(30568, true));\n    data.append(FixedTrait::new(30128, true));\n    data.append(FixedTrait::new(29689, true));\n    data.append(FixedTrait::new(29249, true));\n    data.append(FixedTrait::new(28809, true));\n    data.append(FixedTrait::new(28369, true));\n    data.append(FixedTrait::new(27929, true));\n    data.append(FixedTrait::new(27489, true));\n    data.append(FixedTrait::new(27050, true));\n    data.append(FixedTrait::new(26610, true));\n    data.append(FixedTrait::new(26170, true));\n    data.append(FixedTrait::new(25730, true));\n    data.append(FixedTrait::new(25290, true));\n    data.append(FixedTrait::new(24850, true));\n    data.append(FixedTrait::new(24411, true));\n    data.append(FixedTrait::new(23971, true));\n    data.append(FixedTrait::new(23531, true));\n    data.append(FixedTrait::new(23091, true));\n    data.append(FixedTrait::new(22651, true));\n    data.append(FixedTrait::new(22211, true));\n    data.append(FixedTrait::new(21772, true));\n    data.append(FixedTrait::new(21332, true));\n    data.append(FixedTrait::new(20892, true));\n    data.append(FixedTrait::new(20452, true));\n    data.append(FixedTrait::new(20012, true));\n    data.append(FixedTrait::new(19572, true));\n    data.append(FixedTrait::new(19132, true));\n    data.append(FixedTrait::new(18693, true));\n    data.append(FixedTrait::new(18253, true));\n    data.append(FixedTrait::new(17813, true));\n    data.append(FixedTrait::new(17373, true));\n    data.append(FixedTrait::new(16933, true));\n    data.append(FixedTrait::new(16493, true));\n    data.append(FixedTrait::new(16054, true));\n    data.append(FixedTrait::new(15614, true));\n    data.append(FixedTrait::new(15174, true));\n    data.append(FixedTrait::new(14734, true));\n    data.append(FixedTrait::new(14294, true));\n    data.append(FixedTrait::new(13854, true));\n    data.append(FixedTrait::new(13415, true));\n    data.append(FixedTrait::new(12975, true));\n    data.append(FixedTrait::new(12535, true));\n    data.append(FixedTrait::new(12095, true));\n    data.append(FixedTrait::new(11655, true));\n    data.append(FixedTrait::new(11215, true));\n    data.append(FixedTrait::new(10776, true));\n    data.append(FixedTrait::new(10336, true));\n    data.append(FixedTrait::new(9896, true));\n    data.append(FixedTrait::new(9456, true));\n    data.append(FixedTrait::new(9016, true));\n    data.append(FixedTrait::new(8576, true));\n    data.append(FixedTrait::new(8137, true));\n    data.append(FixedTrait::new(7697, true));\n    data.append(FixedTrait::new(7257, true));\n    data.append(FixedTrait::new(6817, true));\n    data.append(FixedTrait::new(6377, true));\n    data.append(FixedTrait::new(5937, true));\n    data.append(FixedTrait::new(5497, true));\n    data.append(FixedTrait::new(5058, true));\n    data.append(FixedTrait::new(4618, true));\n    data.append(FixedTrait::new(4178, true));\n    data.append(FixedTrait::new(3738, true));\n    data.append(FixedTrait::new(3298, true));\n    data.append(FixedTrait::new(2858, true));\n    data.append(FixedTrait::new(2419, true));\n    data.append(FixedTrait::new(1979, true));\n    data.append(FixedTrait::new(1539, true));\n    data.append(FixedTrait::new(1099, true));\n    data.append(FixedTrait::new(659, true));\n    data.append(FixedTrait::new(219, true));\n    data.append(FixedTrait::new(219, false));\n    data.append(FixedTrait::new(659, false));\n    data.append(FixedTrait::new(1099, false));\n    data.append(FixedTrait::new(1539, false));\n    data.append(FixedTrait::new(1979, false));\n    data.append(FixedTrait::new(2419, false));\n    data.append(FixedTrait::new(2858, false));\n    data.append(FixedTrait::new(3298, false));\n    data.append(FixedTrait::new(3738, false));\n    data.append(FixedTrait::new(4178, false));\n    data.append(FixedTrait::new(4618, false));\n    data.append(FixedTrait::new(5058, false));\n    data.append(FixedTrait::new(5497, false));\n    data.append(FixedTrait::new(5937, false));\n    data.append(FixedTrait::new(6377, false));\n    data.append(FixedTrait::new(6817, false));\n    data.append(FixedTrait::new(7257, false));\n    data.append(FixedTrait::new(7697, false));\n    data.append(FixedTrait::new(8137, false));\n    data.append(FixedTrait::new(8576, false));\n    data.append(FixedTrait::new(9016, false));\n    data.append(FixedTrait::new(9456, false));\n    data.append(FixedTrait::new(9896, false));\n    data.append(FixedTrait::new(10336, false));\n    data.append(FixedTrait::new(10776, false));\n    data.append(FixedTrait::new(11215, false));\n    data.append(FixedTrait::new(11655, false));\n    data.append(FixedTrait::new(12095, false));\n    data.append(FixedTrait::new(12535, false));\n    data.append(FixedTrait::new(12975, false));\n    data.append(FixedTrait::new(13415, false));\n    data.append(FixedTrait::new(13854, false));\n    data.append(FixedTrait::new(14294, false));\n    data.append(FixedTrait::new(14734, false));\n    data.append(FixedTrait::new(15174, false));\n    data.append(FixedTrait::new(15614, false));\n    data.append(FixedTrait::new(16054, false));\n    data.append(FixedTrait::new(16493, false));\n    data.append(FixedTrait::new(16933, false));\n    data.append(FixedTrait::new(17373, false));\n    data.append(FixedTrait::new(17813, false));\n    data.append(FixedTrait::new(18253, false));\n    data.append(FixedTrait::new(18693, false));\n    data.append(FixedTrait::new(19132, false));\n    data.append(FixedTrait::new(19572, false));\n    data.append(FixedTrait::new(20012, false));\n    data.append(FixedTrait::new(20452, false));\n    data.append(FixedTrait::new(20892, false));\n    data.append(FixedTrait::new(21332, false));\n    data.append(FixedTrait::new(21772, false));\n    data.append(FixedTrait::new(22211, false));\n    data.append(FixedTrait::new(22651, false));\n    data.append(FixedTrait::new(23091, false));\n    data.append(FixedTrait::new(23531, false));\n    data.append(FixedTrait::new(23971, false));\n    data.append(FixedTrait::new(24411, false));\n    data.append(FixedTrait::new(24850, false));\n    data.append(FixedTrait::new(25290, false));\n    data.append(FixedTrait::new(25730, false));\n    data.append(FixedTrait::new(26170, false));\n    data.append(FixedTrait::new(26610, false));\n    data.append(FixedTrait::new(27050, false));\n    data.append(FixedTrait::new(27489, false));\n    data.append(FixedTrait::new(27929, false));\n    data.append(FixedTrait::new(28369, false));\n    data.append(FixedTrait::new(28809, false));\n    data.append(FixedTrait::new(29249, false));\n    data.append(FixedTrait::new(29689, false));\n    data.append(FixedTrait::new(30128, false));\n    data.append(FixedTrait::new(30568, false));\n    data.append(FixedTrait::new(31008, false));\n    data.append(FixedTrait::new(31448, false));\n    data.append(FixedTrait::new(31888, false));\n    data.append(FixedTrait::new(32328, false));\n    data.append(FixedTrait::new(32768, false));\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/generated/Y_values.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{FP16x16Tensor, TensorTrait, Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn Y_values() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(150);\n    let mut data = ArrayTrait::new();\n    data.append(FixedTrait::new(265399, false));\n    data.append(FixedTrait::new(262117, false));\n    data.append(FixedTrait::new(268148, false));\n    data.append(FixedTrait::new(274764, false));\n    data.append(FixedTrait::new(264128, false));\n    data.append(FixedTrait::new(265007, false));\n    data.append(FixedTrait::new(277771, false));\n    data.append(FixedTrait::new(273331, false));\n    data.append(FixedTrait::new(266104, false));\n    data.append(FixedTrait::new(273616, false));\n    data.append(FixedTrait::new(267903, false));\n    data.append(FixedTrait::new(268768, false));\n    data.append(FixedTrait::new(274285, false));\n    data.append(FixedTrait::new(261040, false));\n    data.append(FixedTrait::new(263155, false));\n    data.append(FixedTrait::new(271654, false));\n    data.append(FixedTrait::new(269581, false));\n    data.append(FixedTrait::new(279157, false));\n    data.append(FixedTrait::new(272027, false));\n    data.append(FixedTrait::new(269602, false));\n    data.append(FixedTrait::new(289342, false));\n    data.append(FixedTrait::new(279137, false));\n    data.append(FixedTrait::new(281939, false));\n    data.append(FixedTrait::new(273039, false));\n    data.append(FixedTrait::new(279688, false));\n    data.append(FixedTrait::new(284862, false));\n    data.append(FixedTrait::new(277472, false));\n    data.append(FixedTrait::new(288357, false));\n    data.append(FixedTrait::new(282838, false));\n    data.append(FixedTrait::new(285743, false));\n    data.append(FixedTrait::new(284590, false));\n    data.append(FixedTrait::new(301553, false));\n    data.append(FixedTrait::new(290205, false));\n    data.append(FixedTrait::new(284241, false));\n    data.append(FixedTrait::new(297443, false));\n    data.append(FixedTrait::new(284931, false));\n    data.append(FixedTrait::new(295181, false));\n    data.append(FixedTrait::new(281849, false));\n    data.append(FixedTrait::new(286867, false));\n    data.append(FixedTrait::new(297741, false));\n    data.append(FixedTrait::new(302170, false));\n    data.append(FixedTrait::new(299333, false));\n    data.append(FixedTrait::new(298332, false));\n    data.append(FixedTrait::new(297996, false));\n    data.append(FixedTrait::new(291160, false));\n    data.append(FixedTrait::new(297011, false));\n    data.append(FixedTrait::new(299590, false));\n    data.append(FixedTrait::new(310416, false));\n    data.append(FixedTrait::new(306620, false));\n    data.append(FixedTrait::new(293693, false));\n    data.append(FixedTrait::new(308251, false));\n    data.append(FixedTrait::new(304483, false));\n    data.append(FixedTrait::new(303450, false));\n    data.append(FixedTrait::new(312775, false));\n    data.append(FixedTrait::new(316403, false));\n    data.append(FixedTrait::new(316629, false));\n    data.append(FixedTrait::new(305906, false));\n    data.append(FixedTrait::new(310259, false));\n    data.append(FixedTrait::new(315336, false));\n    data.append(FixedTrait::new(320438, false));\n    data.append(FixedTrait::new(311784, false));\n    data.append(FixedTrait::new(314587, false));\n    data.append(FixedTrait::new(309433, false));\n    data.append(FixedTrait::new(309724, false));\n    data.append(FixedTrait::new(323768, false));\n    data.append(FixedTrait::new(328211, false));\n    data.append(FixedTrait::new(319730, false));\n    data.append(FixedTrait::new(327659, false));\n    data.append(FixedTrait::new(324332, false));\n    data.append(FixedTrait::new(318613, false));\n    data.append(FixedTrait::new(326089, false));\n    data.append(FixedTrait::new(334680, false));\n    data.append(FixedTrait::new(325246, false));\n    data.append(FixedTrait::new(336614, false));\n    data.append(FixedTrait::new(310071, false));\n    data.append(FixedTrait::new(333506, false));\n    data.append(FixedTrait::new(329569, false));\n    data.append(FixedTrait::new(327919, false));\n    data.append(FixedTrait::new(331360, false));\n    data.append(FixedTrait::new(318612, false));\n    data.append(FixedTrait::new(331078, false));\n    data.append(FixedTrait::new(335738, false));\n    data.append(FixedTrait::new(343963, false));\n    data.append(FixedTrait::new(331760, false));\n    data.append(FixedTrait::new(330738, false));\n    data.append(FixedTrait::new(333628, false));\n    data.append(FixedTrait::new(343795, false));\n    data.append(FixedTrait::new(340830, false));\n    data.append(FixedTrait::new(336083, false));\n    data.append(FixedTrait::new(343799, false));\n    data.append(FixedTrait::new(341951, false));\n    data.append(FixedTrait::new(348542, false));\n    data.append(FixedTrait::new(338473, false));\n    data.append(FixedTrait::new(341806, false));\n    data.append(FixedTrait::new(342263, false));\n    data.append(FixedTrait::new(336122, false));\n    data.append(FixedTrait::new(348533, false));\n    data.append(FixedTrait::new(349183, false));\n    data.append(FixedTrait::new(348385, false));\n    data.append(FixedTrait::new(347694, false));\n    data.append(FixedTrait::new(340836, false));\n    data.append(FixedTrait::new(348234, false));\n    data.append(FixedTrait::new(349625, false));\n    data.append(FixedTrait::new(347493, false));\n    data.append(FixedTrait::new(352573, false));\n    data.append(FixedTrait::new(357158, false));\n    data.append(FixedTrait::new(367751, false));\n    data.append(FixedTrait::new(357413, false));\n    data.append(FixedTrait::new(358837, false));\n    data.append(FixedTrait::new(357540, false));\n    data.append(FixedTrait::new(346333, false));\n    data.append(FixedTrait::new(359614, false));\n    data.append(FixedTrait::new(361062, false));\n    data.append(FixedTrait::new(377690, false));\n    data.append(FixedTrait::new(361166, false));\n    data.append(FixedTrait::new(365283, false));\n    data.append(FixedTrait::new(363959, false));\n    data.append(FixedTrait::new(357407, false));\n    data.append(FixedTrait::new(373435, false));\n    data.append(FixedTrait::new(371753, false));\n    data.append(FixedTrait::new(372889, false));\n    data.append(FixedTrait::new(362625, false));\n    data.append(FixedTrait::new(378658, false));\n    data.append(FixedTrait::new(361157, false));\n    data.append(FixedTrait::new(375070, false));\n    data.append(FixedTrait::new(386459, false));\n    data.append(FixedTrait::new(366491, false));\n    data.append(FixedTrait::new(370151, false));\n    data.append(FixedTrait::new(375395, false));\n    data.append(FixedTrait::new(372322, false));\n    data.append(FixedTrait::new(366339, false));\n    data.append(FixedTrait::new(377831, false));\n    data.append(FixedTrait::new(371299, false));\n    data.append(FixedTrait::new(382244, false));\n    data.append(FixedTrait::new(373995, false));\n    data.append(FixedTrait::new(391058, false));\n    data.append(FixedTrait::new(376647, false));\n    data.append(FixedTrait::new(380549, false));\n    data.append(FixedTrait::new(388871, false));\n    data.append(FixedTrait::new(376352, false));\n    data.append(FixedTrait::new(386789, false));\n    data.append(FixedTrait::new(394745, false));\n    data.append(FixedTrait::new(376523, false));\n    data.append(FixedTrait::new(389147, false));\n    data.append(FixedTrait::new(390520, false));\n    data.append(FixedTrait::new(394821, false));\n    data.append(FixedTrait::new(382470, false));\n    data.append(FixedTrait::new(382802, false));\n    data.append(FixedTrait::new(395756, false));\n    data.append(FixedTrait::new(395162, false));\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/lib.cairo",
        "content": "mod generated;\r\nmod test;\r\nmod lin_reg_func;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/lin_reg_func.cairo",
        "content": "use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\r\nuse orion::numbers::{FP16x16, FixedTrait};\r\n\r\n/// Calculates the mean of a given 1D tensor.\r\nfn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\r\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\r\n\r\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\r\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\r\n    let mean = *sum_result / tensor_size;\r\n\r\n    return mean;\r\n}\r\n\r\n/// Calculates the deviation of each element from the mean of the provided 1D tensor.\r\nfn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\r\n    let mean_value = calculate_mean(tensor_data);\r\n\r\n    let mut tensor_shape = array::ArrayTrait::new();\r\n    tensor_shape.append(tensor_data.data.len());\r\n\r\n    let mut deviation_values = array::ArrayTrait::new();\r\n\r\n    let mut i: u32 = 0;\r\n    loop {\r\n        if i >= tensor_data.data.len() {\r\n            break ();\r\n        }\r\n        let distance_from_mean = *tensor_data.data.at(i) - mean_value;\r\n        deviation_values.append(distance_from_mean);\r\n        i += 1;\r\n    };\r\n\r\n    let distance_from_mean_tensor = TensorTrait::<FP16x16>::new(\r\n        tensor_shape.span(), deviation_values.span()\r\n    );\r\n\r\n    return distance_from_mean_tensor;\r\n}\r\n\r\n\r\n/// Calculates the beta value for linear regression.\r\nfn compute_beta(x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>) -> FP16x16 {\r\n    let x_deviation = deviation_from_mean(x_values);\r\n    let y_deviation = deviation_from_mean(y_values);\r\n\r\n    let x_y_covariance = x_deviation.matmul(@y_deviation);\r\n    let x_variance = x_deviation.matmul(@x_deviation);\r\n\r\n    let beta_value = *x_y_covariance.data.at(0) / *x_variance.data.at(0);\r\n\r\n    return beta_value;\r\n}\r\n\r\n/// Calculates the intercept for linear regression.\r\nfn compute_intercept(\r\n    beta_value: FP16x16, x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>\r\n) -> FP16x16 {\r\n    let x_mean = calculate_mean(x_values);\r\n    let y_mean = calculate_mean(y_values);\r\n\r\n    let mx = beta_value * x_mean;\r\n    let intercept = y_mean - mx;\r\n\r\n    return intercept;\r\n}\r\n\r\n/// Predicts the y values using the provided x values and computed beta and intercept.\r\nfn predict_y_values(\r\n    beta_value: FP16x16, x_values: Tensor<FP16x16>, y_values: Tensor<FP16x16>\r\n) -> Tensor<FP16x16> {\r\n    let beta = compute_beta(x_values, y_values);\r\n    let intercept = compute_intercept(beta_value, x_values, y_values);\r\n\r\n    //create a tensor to hold all the y_pred values\r\n    let mut y_pred_shape = array::ArrayTrait::new();\r\n    y_pred_shape.append(y_values.data.len());\r\n\r\n    let mut y_pred_vals = array::ArrayTrait::new();\r\n\r\n    let mut i: u32 = 0;\r\n    loop {\r\n        if i >= y_values.data.len() {\r\n            break ();\r\n        }\r\n        // (*x_values.data.at(i)).print();\r\n        let predicted_value = beta * *x_values.data.at(i) + intercept;\r\n        y_pred_vals.append(predicted_value);\r\n        i += 1;\r\n    };\r\n\r\n    let y_pred_tensor = TensorTrait::<FP16x16>::new(y_pred_shape.span(), y_pred_vals.span());\r\n\r\n    return y_pred_tensor;\r\n}\r\n\r\n\r\n/// Calculates the mean squared error between the true y values and the predicted y values.\r\nfn compute_mse(y_values: Tensor<FP16x16>, y_pred_values: Tensor<FP16x16>) -> FP16x16 {\r\n    let mut squared_diff_shape = array::ArrayTrait::new();\r\n    squared_diff_shape.append(y_values.data.len());\r\n\r\n    let mut squared_diff_vals = array::ArrayTrait::new();\r\n\r\n    let mut i: u32 = 0;\r\n    loop {\r\n        if i >= y_values.data.len() {\r\n            break ();\r\n        }\r\n        let diff = *y_values.data.at(i) - *y_pred_values.data.at(i);\r\n        let squared_diff = diff * diff;\r\n        squared_diff_vals.append(squared_diff);\r\n        i += 1;\r\n    };\r\n\r\n    let squared_diff_tensor = TensorTrait::<FP16x16>::new(\r\n        squared_diff_shape.span(), squared_diff_vals.span()\r\n    );\r\n\r\n    let mse = calculate_mean(squared_diff_tensor);\r\n\r\n    return mse;\r\n}\r\n\r\n/// Calculates the R squared score.\r\nfn calculate_r_score(y_values: Tensor<FP16x16>, y_pred_values: Tensor<FP16x16>) -> FP16x16 {\r\n    let mean_y_value = calculate_mean(y_values);\r\n\r\n    // creating the appropriate tensor shapes and empty arrays to populate values into\r\n    let mut squared_diff_shape = array::ArrayTrait::new();\r\n    squared_diff_shape.append(y_values.data.len());\r\n    let mut squared_diff_vals = array::ArrayTrait::new();\r\n\r\n    let mut squared_mean_diff_shape = array::ArrayTrait::new();\r\n    squared_mean_diff_shape.append(y_values.data.len());\r\n    let mut squared_mean_diff_vals = array::ArrayTrait::new();\r\n\r\n    let mut i: u32 = 0;\r\n    loop {\r\n        if i >= y_values.data.len() {\r\n            break ();\r\n        }\r\n        let diff_pred = *y_values.data.at(i) - *y_pred_values.data.at(i);\r\n        let squared_diff = diff_pred * diff_pred;\r\n        squared_diff_vals.append(squared_diff);\r\n\r\n        let diff_mean = *y_values.data.at(i) - mean_y_value;\r\n        let squared_mean_diff = diff_mean * diff_mean;\r\n        squared_mean_diff_vals.append(squared_mean_diff);\r\n        i += 1;\r\n    };\r\n\r\n    let squared_diff_tensor = TensorTrait::<FP16x16>::new(\r\n        squared_diff_shape.span(), squared_diff_vals.span()\r\n    );\r\n    let squared_mean_diff_tensor = TensorTrait::<FP16x16>::new(\r\n        squared_mean_diff_shape.span(), squared_mean_diff_vals.span()\r\n    );\r\n\r\n    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\r\n    let sum_squared_mean_diff = squared_mean_diff_tensor\r\n        .cumsum(0, Option::None(()), Option::None(()));\r\n\r\n    let r_score = FixedTrait::new_unscaled(1, false)\r\n        - *sum_squared_diff.data.at(y_values.data.len() - 1)\r\n            / *sum_squared_mean_diff.data.at(y_values.data.len() - 1);\r\n\r\n    return r_score;\r\n}\r\n\r\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_linear_regression_model/src/test.cairo",
        "content": "use debug::PrintTrait;\r\n\r\nuse verifiable_linear_regression::generated::X_values::X_values;\r\nuse verifiable_linear_regression::generated::Y_values::Y_values;\r\nuse verifiable_linear_regression::lin_reg_func::{\r\n    calculate_mean, deviation_from_mean, compute_beta, compute_intercept, predict_y_values,\r\n    compute_mse, calculate_r_score\r\n};\r\n\r\n\r\n#[test]\r\n#[available_gas(99999999999999999)]\r\nfn linear_regression_test() {\r\n    // Fetching the x and y values\r\n    let y_values = Y_values();\r\n    let x_values = X_values();\r\n\r\n    // (*x_values.data.at(18)).print();\r\n\r\n    let beta_value = compute_beta(x_values, y_values);\r\n    // beta_value.print();    // calculated gradient value\r\n\r\n    let intercept_value = compute_intercept(beta_value, x_values, y_values);\r\n    // intercept_value.print();   // calculated intercept value\r\n\r\n    let y_pred = predict_y_values(beta_value, x_values, y_values);\r\n\r\n    let mse = compute_mse(y_values, y_pred);\r\n    // mse.print();       // mean squared error ouput\r\n\r\n    let r_score = calculate_r_score(y_values, y_pred);\r\n    r_score.print(); // accuracy of model around 0.97494506835\r\n\r\n    assert(beta_value.mag > 0, 'x & y not positively correlated');\r\n    assert(r_score.mag > 0, 'R-Squared needs to be above 0');\r\n    assert(\r\n        r_score.mag < 65536, 'R-Squared has to be below 65536'\r\n    ); // 65536 represents ONE in fp16x16.\r\n    assert(r_score.mag > 32768, 'Accuracy below 50% ');\r\n}\r\n\r\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/notebooks/pca_iris.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# <span style='color:Black'> **Verifiable Principal Components Analysis**  </span> \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"\\n\",\n    \"The Principal Component Analysis (PCA) method is an unsupervised learning algorithm that aims to reduce the dimensionality of a dataset consisting of a large number of interrelated variables, while at the same time preserving as much of the variation present in the original dataset as possible. This is achieved by transforming to a new set of variables, the principal components (PC), which are uncorrelated and are ordered in such a way that the first ones retain most of the variation present in all the original variables. More formally, with PCA, given \\n\",\n    \"$n$ observations of $p$ variables, it seeks the possibility of adequately representing this information with a smaller number of variables, constructed as linear combinations of the original variables.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Below, we provide a brief review of the implementation of a Principal Component Analysis (PCA) in Python, which we will then convert to Cairo to transform it into a verifiable ZKML (Principal Component Analysis), using the Orion library. This provides an opportunity to become familiar with the main functions and operators that the framework offers for the implementation of PCA.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Used DataSet**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For the purposes of this tutorial, we will use the iris dataset from sklearn.datasets.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import math\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import pandas as pd\\n\",\n    \"from sklearn.datasets import load_iris\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Cargar datos de Iris\\n\",\n    \"data = load_iris()\\n\",\n    \"X = data['data']\\n\",\n    \"\\n\",\n    \"y = data['target']\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For the purposes of this tutorial, we will not take into account the total number of records in the original dataset. In this sense, we will only focus on the first 105 individuals and the first 3 variables, in order to have comparable results between the python and cairo implementations, taking into consideration the same number of iterations in both programs to achieve orthogonality between the components at the computational level. Therefore, we will have the total number of individuals of the species versicolor and virginica, partially the individuals of the species setosa and with the exclusion of the variable petal width.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X, y = X[:105,0:3], y[:105]\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Before applying PCA, it is important to standardize the data. This ensures that each feature has an equal weight in the calculation of principal components.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"mu = np.mean(X, axis=0)\\n\",\n    \"sigma = np.std(X, axis=0)\\n\",\n    \"X_std = (X - mu)/sigma\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We print the first 20 rows\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[-0.62902748,  0.86993347, -1.04142584],\\n\",\n       \"       [-0.93199944, -0.19965686, -1.04142584],\\n\",\n       \"       [-1.23497139,  0.22817927, -1.10670925],\\n\",\n       \"       [-1.38645737,  0.0142612 , -0.97614243],\\n\",\n       \"       [-0.78051346,  1.08385154, -1.04142584],\\n\",\n       \"       [-0.17456955,  1.72560573, -0.84557561],\\n\",\n       \"       [-1.38645737,  0.6560154 , -1.04142584],\\n\",\n       \"       [-0.78051346,  0.6560154 , -0.97614243],\\n\",\n       \"       [-1.68942932, -0.41357493, -1.04142584],\\n\",\n       \"       [-0.93199944,  0.0142612 , -0.97614243],\\n\",\n       \"       [-0.17456955,  1.2977696 , -0.97614243],\\n\",\n       \"       [-1.08348542,  0.6560154 , -0.91085902],\\n\",\n       \"       [-1.08348542, -0.19965686, -1.04142584],\\n\",\n       \"       [-1.8409153 , -0.19965686, -1.23727607],\\n\",\n       \"       [ 0.43137435,  1.9395238 , -1.17199266],\\n\",\n       \"       [ 0.27988838,  2.79519606, -0.97614243],\\n\",\n       \"       [-0.17456955,  1.72560573, -1.10670925],\\n\",\n       \"       [-0.62902748,  0.86993347, -1.04142584],\\n\",\n       \"       [ 0.27988838,  1.51168767, -0.84557561],\\n\",\n       \"       [-0.62902748,  1.51168767, -0.97614243]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_std[0:20,:]\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Implementation of the Jacobi algorithm**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The Jacobi algorithm is an iterative method for finding the eigenvalues and eigenvectors of a symmetric matrix, which in our case is the correlation matrix over $\\\\mathbf{X_{std}}$. With this method, the aim is to identify pairs of elements off the main diagonal of the matrix and \\\"rotate\\\" them to zero using orthogonal transformations. The idea is that, after enough rotations, the matrix will converge to a diagonal matrix whose diagonal elements will be the eigenvalues of the original matrix. The eigenvectors, on the other hand, are constructed from the rotation matrices applied during the process.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def extract_diagonal(matrix):\\n\",\n    \"    return [matrix[i][i] for i in range(len(matrix))]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def find_max_off_diag(A):\\n\",\n    \"    n = A.shape[0]\\n\",\n    \"    p, q = 0, 1\\n\",\n    \"    max_val = abs(A[p, q])\\n\",\n    \"    for i in range(n-1):\\n\",\n    \"        for j in range(i+1, n):\\n\",\n    \"            if abs(A[i, j]) > max_val:\\n\",\n    \"                max_val = abs(A[i, j])\\n\",\n    \"                p, q = i, j\\n\",\n    \"    return p, q\\n\",\n    \"\\n\",\n    \"def jacobi_eigensystem(A, tol=1e-2, max_iter=500): \\n\",\n    \"    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:\\n\",\n    \"        raise ValueError(\\\"A must be a square matrix\\\")\\n\",\n    \"    \\n\",\n    \"    n = A.shape[0]\\n\",\n    \"    V = np.eye(n)\\n\",\n    \"\\n\",\n    \"    for _ in range(max_iter):\\n\",\n    \"        p, q = find_max_off_diag(A)\\n\",\n    \"        \\n\",\n    \"        if abs(A[p, q]) < tol:\\n\",\n    \"            break\\n\",\n    \"        \\n\",\n    \"        if A[p, p] == A[q, q]:\\n\",\n    \"            theta = math.pi/4\\n\",\n    \"        else:\\n\",\n    \"            theta = 0.5 * math.atan(2 * A[p, q] / (A[p, p] - A[q, q]))\\n\",\n    \"        \\n\",\n    \"        J = np.eye(n)\\n\",\n    \"        J[p, p], J[q, q] = math.cos(theta), math.cos(theta)\\n\",\n    \"        J[p, q], J[q, p] = math.sin(theta), -math.sin(theta)\\n\",\n    \"        \\n\",\n    \"        A = np.matmul(np.matmul(J.T,A),J)\\n\",\n    \"        V = np.matmul(V,J)\\n\",\n    \"\\n\",\n    \"    return extract_diagonal(A), V\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Correlation Matrix**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"At this point, we determine the correlation matrix, based on the calculations of the variance and covariance matrix for **$\\\\mathbf{X_{std}}$** :\\n\",\n    \"\\n\",\n    \"We compute the covariance matrix\\n\",\n    \"\\n\",\n    \" $\\\\mathbf{S}$ = $\\\\mathbf{X}^{T}$ $\\\\mathbf{X}$ $/\\\\mathbf{n-1}$ \\n\",\n    \"\\n\",\n    \"Then, we determine the correlation matrix :\\n\",\n    \"\\n\",\n    \"$\\\\mathbf{r}$  =  $\\\\mathbf{Cov(X,Y)}$ $/\\\\mathbf{S_{X} S_{Y}}$,\\n\",\n    \"\\n\",\n    \"where $\\\\mathbf{S_{X} S_{Y}}$ are the standard deviations of X and Y respectively. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"n = (X_std.shape[0]-1) \\n\",\n    \"cov_matrix = np.dot(X_std.T,X_std)/n \\n\",\n    \"stddevs = np.sqrt(extract_diagonal(cov_matrix))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[ 1.00961538, -0.20656485,  0.83469099],\\n\",\n       \"       [-0.20656485,  1.00961538, -0.57369635],\\n\",\n       \"       [ 0.83469099, -0.57369635,  1.00961538]])\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"cov_matrix\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"corr_matrix = cov_matrix / np.matmul(stddevs.reshape(-1, 1),stddevs.reshape(1, -1))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[ 1.        , -0.20459756,  0.82674155],\\n\",\n       \"       [-0.20459756,  1.        , -0.56823258],\\n\",\n       \"       [ 0.82674155, -0.56823258,  1.        ]])\"\n      ]\n     },\n     \"execution_count\": 11,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"corr_matrix\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"evalu, evec = jacobi_eigensystem(corr_matrix)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"At this point, we have the eigenvalues and eigenvectors associated with the correlation matrix. Now, we sort the eigenvalues in decreasing order, as the largest of these will be associated with the component that explains the most variability in the data. Consequently, the principal components will be sorted in the same order as the eigenvalues and eigenvectors.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"idx = np.argsort(evalu)[::-1]\\n\",\n    \"evec = evec[:,idx]\\n\",\n    \"evalu = np.sort(evalu)[::-1]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(array([2.10545934, 0.81005256, 0.0844881 ]),\\n\",\n       \" array([[-0.58699831,  0.55819468, -0.58638867],\\n\",\n       \"        [ 0.45714577,  0.82631669,  0.32896575],\\n\",\n       \"        [-0.66816968,  0.07496276,  0.74022284]]))\"\n      ]\n     },\n     \"execution_count\": 14,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"evalu, evec\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Loadings PCA**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Once the aforementioned order is established, we find the loadings which are represented by the discovered eigenvectors (evec). These loadings represent the coefficients of each variable in each of the principal components.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>PC1</th>\\n\",\n       \"      <th>PC2</th>\\n\",\n       \"      <th>PC3</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>sepal length (cm)</th>\\n\",\n       \"      <td>-0.586998</td>\\n\",\n       \"      <td>0.558195</td>\\n\",\n       \"      <td>-0.586389</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>sepal width (cm)</th>\\n\",\n       \"      <td>0.457146</td>\\n\",\n       \"      <td>0.826317</td>\\n\",\n       \"      <td>0.328966</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>petal length (cm)</th>\\n\",\n       \"      <td>-0.668170</td>\\n\",\n       \"      <td>0.074963</td>\\n\",\n       \"      <td>0.740223</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"                        PC1       PC2       PC3\\n\",\n       \"sepal length (cm) -0.586998  0.558195 -0.586389\\n\",\n       \"sepal width (cm)   0.457146  0.826317  0.328966\\n\",\n       \"petal length (cm) -0.668170  0.074963  0.740223\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"loadings = pd.DataFrame(evec,columns=['PC1','PC2','PC3'], index = data['feature_names'][:3])\\n\",\n    \"loadings\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **New axis, Principal Components**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Next, we identify the new axes or principal components, which are obtained as a linear combination of the standardized original variables.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"$\\\\mathbf{PC_{i}}$ =  $\\\\mathbf{a_{i1}X_1}   +  \\\\mathbf{a_{i2}X_2}  +  \\\\mathbf{...}  +  \\\\mathbf{a_{in}X_n}$,\\n\",\n    \"\\n\",\n    \"Where,\\n\",\n    \"\\n\",\n    \"$\\\\mathbf{X_1}, \\\\mathbf{X_2}, \\\\mathbf{...} + \\\\mathbf{X_n}$  are the standardized original variables.\\n\",\n    \"\\n\",\n    \"$\\\\mathbf{a_{i1}}, \\\\mathbf{a_{i2}}, \\\\mathbf{...} + \\\\mathbf{a_{in}}$ are the coefficients or loadings of the $\\\\mathbf{i-th}$ eigenvector.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>principal component 1</th>\\n\",\n       \"      <th>principal component 2</th>\\n\",\n       \"      <th>principal component 3</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.462774</td>\\n\",\n       \"      <td>0.289653</td>\\n\",\n       \"      <td>-0.115854</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>1.151659</td>\\n\",\n       \"      <td>-0.763285</td>\\n\",\n       \"      <td>-0.290054</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>1.568707</td>\\n\",\n       \"      <td>-0.583768</td>\\n\",\n       \"      <td>-0.019975</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>1.472596</td>\\n\",\n       \"      <td>-0.835303</td>\\n\",\n       \"      <td>0.095131</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>1.649487</td>\\n\",\n       \"      <td>0.381858</td>\\n\",\n       \"      <td>0.043347</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>100</th>\\n\",\n       \"      <td>-1.806412</td>\\n\",\n       \"      <td>1.175944</td>\\n\",\n       \"      <td>0.900363</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>101</th>\\n\",\n       \"      <td>-1.555969</td>\\n\",\n       \"      <td>-0.351478</td>\\n\",\n       \"      <td>0.487362</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>102</th>\\n\",\n       \"      <td>-2.767543</td>\\n\",\n       \"      <td>1.317228</td>\\n\",\n       \"      <td>-0.069714</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>103</th>\\n\",\n       \"      <td>-2.023098</td>\\n\",\n       \"      <td>0.449313</td>\\n\",\n       \"      <td>0.425579</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>104</th>\\n\",\n       \"      <td>-2.190391</td>\\n\",\n       \"      <td>0.804982</td>\\n\",\n       \"      <td>0.414940</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"<p>105 rows \u00d7 3 columns</p>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"     principal component 1  principal component 2  principal component 3\\n\",\n       \"0                 1.462774               0.289653              -0.115854\\n\",\n       \"1                 1.151659              -0.763285              -0.290054\\n\",\n       \"2                 1.568707              -0.583768              -0.019975\\n\",\n       \"3                 1.472596              -0.835303               0.095131\\n\",\n       \"4                 1.649487               0.381858               0.043347\\n\",\n       \"..                     ...                    ...                    ...\\n\",\n       \"100              -1.806412               1.175944               0.900363\\n\",\n       \"101              -1.555969              -0.351478               0.487362\\n\",\n       \"102              -2.767543               1.317228              -0.069714\\n\",\n       \"103              -2.023098               0.449313               0.425579\\n\",\n       \"104              -2.190391               0.804982               0.414940\\n\",\n       \"\\n\",\n       \"[105 rows x 3 columns]\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"principalDf = pd.DataFrame(np.dot(X_std,loadings))\\n\",\n    \"principalDf.columns = [\\\"principal component {}\\\".format(i+1) for i in range(principalDf.shape[1])]\\n\",\n    \"principalDf\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Next, we validate the orthogonality between the principal components, as we observe the lack of correlation between these new variables (Principal Components).\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"n = principalDf.shape[0] - 1\\n\",\n    \"cov_new = np.dot(np.array(principalDf).T,np.array(principalDf))/n \\n\",\n    \"stddevs = np.sqrt(extract_diagonal(cov_new))\\n\",\n    \"corr_new = cov_new / np.matmul(stddevs.reshape(-1, 1),stddevs.reshape(1, -1))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[ 1.        , -0.002632  , -0.01975951],\\n\",\n       \"       [-0.002632  ,  1.        ,  0.0200618 ],\\n\",\n       \"       [-0.01975951,  0.0200618 ,  1.        ]])\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"corr_new\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"     0    1    2\\n\",\n       \"0  1.0  0.0  0.0\\n\",\n       \"1  0.0  1.0  0.0\\n\",\n       \"2  0.0  0.0  1.0\"\n      ]\n     },\n     \"execution_count\": 19,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"new_corr = round(abs(pd.DataFrame(corr_new)))\\n\",\n    \"new_corr\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The implementation of Jacobi in Python is carried out considering 500 iterations, in order to optimize its implementation at the Cairo level. That is why rounding is applied when checking for orthogonality.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Selection of the number of components to be retained**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Each principal component accounts for a proportion of the total variance, and such proportion can be determined by the ratio of each eigenvalue to the total sum of all eigenvalues. Thus, the percentage of variance explained by the i-th component is given by:\\n\",\n    \"\\n\",\n    \"$\\\\frac{\\\\lambda_i}{\\\\sum_{j=1}^{p} \\\\lambda_j}$\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAkAAAAGwCAYAAABB4NqyAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXM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6Whw8eFAcOnRItG7dWgwdOlS/ja+++kr4+/uLDRs2iPPnz4sNGzYIT09PsXLlSoOfh1atWomffvpJnDp1Sjz11FMiKChIVFRUiLKyMrFgwQLh5uYmMjIyREZGhigsLBQHDx4UcrlcrF69Wly4cEEkJyeLhQsX1vCTSWQ5WAARWaBu3bqJrl27Giy77777xBtvvCGEMK4A+uWXX/RtEhISBABx7tw5/bIXXnhBxMTEGDx369athU6n0y974403ROvWrYUQQly8eFHI5XJx5coVg3w9e/YU8fHxQoibH+oARGpqao39fPPNN0VISIjBcy1dulS4uLgIrVYrhBDigw8+EEFBQTVuJzY2VjzwwAPVPlZUVCQcHBzE119/rV9WXl4uAgICxNy5c4UQ9fdanT59WgAQe/bs0T+em5srnJycxPr164UQf79WZ8+eNXgNfH199febNWsmVq9ebdCvt956S3Tu3FkI8ffPw2effaZ//Pjx4wKAOHHihP551Gq1wTY2bNgg3NzchEajqfa1I7JkPARGZKFCQ0MN7vv7+yM7O/uutuPr6wuVSoWmTZsaLPv3du+//37IZDL9/c6dO+PMmTPQarU4evQotFotWrZsCRcXF/1t165dOHfunH4dhUJRpQ//duLECXTu3NnguR544AEUFRXh8uXLte5jamoqevbsWe1j586dQ0VFBR544AH9MgcHB0RGRuLEiRMGbU39Wp04cQL29vaIiorSP96gQQOEhIQYPLdKpUKzZs309//5XhcXF+PcuXMYNWqUwev99ttvG7ze/87v7+8PADX+zDzyyCMICgpC06ZNMWzYMHz99ddVDocSWSoOgiayUA4ODgb3ZTIZdDodAOgHE4t/jDWpqKi443ZkMlmN262NoqIiyOVyHDp0CHK53OAxFxcX/fdOTk4GhUF9cnJyMsl2TP1a1eV5bz3Prfe2qKgIAPDpp58aFFIAqrz+/84PoMa8rq6uSE5Oxs6dO7F161ZMmzYNM2bMwMGDB3nGGFk87gEiskLe3t4AYDBQ1pTz4+zfv9/g/u+//44WLVpALpcjIiICWq0W2dnZaN68ucHNz8/PqOdp3bo19u3bZ1DI7dmzB66urmjUqFGttxMaGoqkpKRqH2vWrBkUCgX27NmjX1ZRUYGDBw+iTZs2RuWtTk2vVevWrVFZWWnQJi8vD6dOnar1c/v6+iIgIADnz5+v8no3adKk1jkVCgW0Wm2V5fb29oiOjsbcuXNx5MgRXLhwAdu3b6/1donMFfcAEVkhJycn3H///ZgzZw6aNGmC7OxsTJkyxWTbT09PR1xcHF544QUkJydj8eLFmDdvHgCgZcuWeOaZZzB8+HDMmzcPERERyMnJQVJSEkJDQ9GvX79aP89///tfLFiwAC+//DLGjRuHU6dOYfr06YiLizPqlPn4+Hi0b98e//3vf/Hiiy9CoVBgx44dGDRoELy8vDB27Fi8/vrr8PT0ROPGjTF37lyUlJRg1KhRRr82/1bTa9WiRQsMGDAAY8aMwccffwxXV1dMnjwZDRs2xIABA2r9HDNnzsT48eOhVqvRu3dvlJWV4Y8//sD169cRFxdXq20EBwejqKgISUlJCAsLg0qlwvbt23H+/Hk89NBD8PDwwObNm6HT6RASElKn14LInLAAIrJSK1aswKhRo9CxY0eEhIRg7ty56NWrl0m2PXz4cNy4cQORkZGQy+WYMGECnn/+ef3jn3/+Od5++228+uqruHLlCry8vHD//ffj0UcfNep5GjZsiM2bN+P1119HWFgYPD09MWrUKKOLuZYtW2Lr1q148803ERkZCScnJ0RFRSE2NhYAMGfOHOh0OgwbNgyFhYXo1KkTtmzZAg8PD6Oepzq1ea0mTJiARx99FOXl5XjooYewefPmKoe9ajJ69GioVCq89957eP311+Hs7Iz27dsbNWN3ly5d8OKLL2Lw4MHIy8vD9OnTER0djY0bN2LGjBkoLS1FixYtsGbNGrRt29aYl4DILMnEP/ctExGRyXTv3h3h4eFYsGCB1FGI6F84BoiIiIhsDgsgIiIisjk8BEZEREQ2h3uAiIiIyOawACIiIiKbwwKIiIiIbA4LICIiIrI5LICIiIjI5rAAIiIiIpvDAoiIiIhsDgsgIiIisjn/D6zWbaza6e6zAAAAAElFTkSuQmCC\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"plt.plot(np.cumsum(evalu)/np.sum(evalu))\\n\",\n    \"plt.xlabel('number of components')\\n\",\n    \"plt.ylabel('cumulative explained variance');\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"97.0\"\n      ]\n     },\n     \"execution_count\": 21,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"select_pc = round(((evalu)/np.sum(evalu))[:2].sum(),2)*100\\n\",\n    \"select_pc\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"As observed in the previous graph, we decided to keep the **first 2 components**, which explain **97%** of the total variability of the data.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAArcAAALLCAYAAADjfarNAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAACpVklEQVR4nOzdeViU9fo/8PcsLKM4Km6Iu2loRWqRaSNoddyPIRyz0k6lHn8HwSywo/mttDqV1VFoBSpTKzUtCxHXzPTEkJZrRzO13HBBMjVHdIRh5vn98TQjMCvDrM+8X9fFBcx8ZuaGh+Weez7PfcsEQRBARERERCQBcn8HQERERETkKUxuiYiIiEgymNwSERERkWQwuSUiIiIiyWByS0RERESSweSWiIiIiCSDyS0RERERSQaTWyIiIiKSDCa3RERERCQZTG4pZC1evBgymQwymQzHjx/3dzhERF5z/vx5PPXUU+jZsydUKpXlb98bb7zh79CIPI7JLQW9rVu3Wv5Qu/K2ePFif4d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odd95Bnz59sGfPHkyePBmNGzfGo48+ih9++AF9+/bF119/jZtvvhnh4eEAgDfffBPz58/He++9hz59+mDhwoW477778NNPP6F79+546623sHr1anz22Wfo2LEjTp48iZMnT1piksvleOutt9ClSxccPXoU6enpmDFjRq3EmoiIiKghmNx6U3Y2oFBYJ7Y1KRRATo5Xktvq6mqkpqaiU6dOAID4+HgAwJw5czB//nykpqYCECu1Bw4cwHvvvYdHH30UrVq1AgC0aNECMTExlvucN28eZs6ciQcffBAA8Nprr2HLli1444038O6776K0tBTdu3fHgAEDIJPJLI9r9uSTT1o+7ty5M1566SWkpaUxuSUiIiKPYXLrLXo9UFh4fSuCPdXVQEGBuF6l8tjD9+rVC/feey/i4+MxdOhQDBkyBGPGjEF4eDiOHDmCSZMmYfLkyTXCqEbTpk3t3p9Op8OZM2egqZOEazQa/PjjjwCAxx57DIMHD0ZcXByGDRuGv/71rxgyZIhl7ddff425c+fi4MGD0Ol0qK6uxrVr13D16lVOfyMiIiKP4J5bb9HpnCe2ZiaTuN6DFAoFNm3ahPXr1+Omm27C22+/jbi4OOzfvx8A8MEHH2Dv3r2Wt/3792P79u0NeszbbrsNx44dw7///W/o9XqMHTsWY8aMASB2YPjrX/+KW2+9FV988QV27dqFd999F4C4V5eIiIjIE1i59Ra1GpDLXUtw5XJxvYfJZDJoNBpoNBrMnj0bnTp1QklJCWJjY3H06FGMHz/e5u3Me2yNRqPlMrVajdjYWJSUlGDgwIGWy0tKStC3b99a6x544AE88MADGDNmDIYNG4YLFy5g165dMJlMmD9/vmWU8Weffebxr5mIiIhCG5Nbb1GpgORksSuCoz23SqW4zoNbEgDg+++/x+bNmzFkyBC0bt0a33//Pc6dO4eePXvihRdewLRp09C0aVMMGzYMlZWV2LlzJy5evIisrCy0bt0aKpUKGzZsQPv27REZGYmmTZviX//6F+bMmYMbbrgBvXv3xqJFi7B3714sXboUgNgNoW3btujTpw/kcjk+//xzxMTEoFmzZujWrRsMBgPefvttjBo1CiUlJcj3YqcIIiK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5mZmWjZsiWGDh3aoO8jERERBRcmt16kLdUiY10GBAioNtWeI11tqoYAAelr071Swb3//vtx/vx5bNmyxXLZhQsXsGHDBowfPx7FxcV45JFH8MQTT+DAgQN47733sHjxYrz88su17uf5559HSkoK9u3bh4kTJ+K5557DgQMHsH79evz888/Iy8uzuw3h9OnTSEpKQkREBL755hvs2rULEydOtCSjb775JubPn4958+bhf//7H4YOHYr77rsPv/zyi937GzFiBO644w78+OOPyMvLw4cffoiXXnqp1rrly5cjPDwcJSUlyM/3zpMHIiIiCkyB8/qxBGVvy4ZCrrBKbGtSyBXI2Z4DTUfPbiJv3rw5hg8fjmXLluHee+8FAKxcuRItW7bE3XffjSFDhuDpp5/Go48+CgDo2rUr/v3vf2PGjBmYM2eO5X7GjRuHCRMmWD4vLS1Fnz59kJCQAADo3Lmz3RjeffddNG3aFMuXL0dYWBgA4MYbb7RcP2/ePMycORMPPvggAOC1117Dli1b8MYbb+Ddd9+1ur/c3Fx06NAB77zzDmQyGXr06IEzZ85g5syZmD17NuR/nnXatWtXvPbaa5bPiYiIKHTwv7+X6A16FB4qdJjYAmIFt+BgAfQGvcdjGD9+PL744gtUVlYCAJYuXYoHH3wQcrkcP/74I1588UVERUVZ3iZPnoyysjJcvXrVch/mJNZsypQpWL58OXr37o0ZM2bgu+++s/v4e/fuRWJioiWxrUmn0+HMmTPQ1DkzVKPR4Oeff7Z5fz///DP69+8PmUxWa31FRQVOnTpluax37972vylEREQkaUxuvURXqbPssXXGJJigq9R5PIZRo0ZBEASsXbsWJ0+eRHFxMcaPHw8AqKiowAsvvIC9e/da3vbt24dffvkFkZGRlvto3LhxrfscPnw4Tpw4gczMTJw5cwb33nsvnnrqKZuPr/LTGaCNGjXyy+MSERGR/zG59RJ1hBpymWvfXrlMDnWE2uMxREZGIjU1FUuXLsWnn36KuLg43HbbbQCA2267DYcOHUK3bt2s3py9nN+qVSs8+uijWLJkCd544w28//77NtfdeuutKC4uttllQa1WIzY2FiUltfcbl5SU4KabbrJ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iIhIMpjcEhEREZFkMLklIiIiIslgcktEREREksHkloiIiIgkg8ktEREREUkGk1siIiIikgwmt0REREQkGUGd3B4/fhyTJk1Cly5doFKpcMMNN2DOnDmoqqryd2hERERE5AdBPX734MGDMJlMeO+999CtWzfs378fkydPxpUrVzBv3jx/h0dEREREPhbUye2wYcMwbNgwy+ddu3bFoUOHkJeXx+SWiIiIKAQFdXJry6VLlxAdHe1wTWVlJSorKy2f63Q6y8cGg8FrsZH3mY8fj2Nw43GUBh5HaeBxlAYpHEdXY5cJgiB4ORaf+fXXX3H77bdj3rx5mDx5st11zz//PF544QWry5ctW4ZGjRp5M0QiIiIicsPVq1cxbtw4XLp0CWq12u66gExun376abz22msO1/z888/o0aOH5fPTp09j4MCBGDRoEBYsWODwtrYqtx06dMCyZcuQnJyMsLCwhn0B5DcGgwGbNm3C4MGDeRyDGI+jNPA4SgOPozRI4TjqdDq0bNnSaXIbkNsSpk+fjscee8zhmq5du1o+PnPmDO6++27cddddeP/9953ef0REBCIiImxeFxYWFrQHna7jcZQGHkdp4HGUBh5HaQjm4+hq3AGZ3LZq1QqtWrVyae3p06dx99134/bbb8eiRYsglwd1dzMiIiIiaoCATG5ddfr0aQwaNAidOnXCvHnzcO7cOct1MTExfoyMiIiIiPwhqJPbTZs24ddff8Wvv/6K9u3b17ouALcSExEREZGXBfVr+I899hgEQbD5RkREREShJ6iTWyIiIiKimpjcEhEREZFkMLklIiIiIslgcktEREREksHkloiIiIgkg8ktEREREUkGk1siIiIikgwmt0REREQkGUxuiYiIiEgymNwSERERkWQwuSUiIiIiyWByS0RERESSweSWiIiIiCSDyS0RERERSQaTWyIiIiKSDCa3RERERCQZTG6JiIiISDKY3BIRERGRZDC5JSIiIiLJYHJLRERERJLB5JaIiIiIJIPJLRERERFJBpNbIiIiIpIMJrdEREREJBlMbomIiIhIMpjcEhEREZFkMLklIiIiIslgcktEREREksHklogkT2/Qo7yiHHrD/2/v3sOiuO43gL+zXBeWRRC53wKRRuu1QhHBKKI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nFl8ioi5GkiT4+Pjo/eqc2o/HlYgeFbxyS0RERESywXBLRERERLLBcEtEREREssE5t0REREQkG7xyS0RERESywXBLRERERLLBcEtEREREssFwS0RERESywXBLRERERLLBcEtEREREssFwS0RERESywXBLRERERLLxf3h3lIj59hzSAAAAAElFTkSuQmCC\",\n      \"text/plain\": [\n       \"<Figure size 800x800 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"fig = plt.figure(figsize = (8,8))\\n\",\n    \"ax = fig.add_subplot(1,1,1) \\n\",\n    \"ax.set_xlabel('Principal Component 1', fontsize = 15)\\n\",\n    \"ax.set_ylabel('Principal Component 2', fontsize = 15)\\n\",\n    \"ax.set_title('First two Components of PCA', fontsize = 20)\\n\",\n    \"\\n\",\n    \"targets = [0, 1, 2]\\n\",\n    \"names = ['setosa', 'versicolor','virginica']\\n\",\n    \"colors = ['r', 'g', 'b'] \\n\",\n    \"for target, color, name in zip(targets, colors, names):\\n\",\n    \"    indicesToKeep = y == target\\n\",\n    \"    ax.scatter(principalDf.loc[indicesToKeep, 'principal component 1']\\n\",\n    \"               , principalDf.loc[indicesToKeep, 'principal component 2']\\n\",\n    \"               , c = color\\n\",\n    \"               , s = 50)\\n\",\n    \"ax.legend(names)\\n\",\n    \"ax.grid()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Based on what is observed in the graph of the first 2 principal components, we notice how the setosa species differentiates from the versicolor and virginica species in principal component 1, which is attributed to the variables petal length (cm), and sepal length (cm).\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Among its other applications, here we were able to use PCA to describe a dataset in a dimension smaller than that of the original dataset. As previously discussed, we noticed how we can describe interesting aspects of the original data without the need to address separately all the dimensions of such data.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## <span style='color:Black'> **Convert your model to Cairo**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### <span style='color:Black'> **Generating Cairo files**  </span>\\n\",\n    \"\\n\",\n    \"Now let's generate Cairo files for each tensor in the object.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def decimal_to_fp16x16(num):\\n\",\n    \"\\n\",\n    \"    whole_num = int(num)\\n\",\n    \"    fractional_part = int((num - whole_num) * 65536)\\n\",\n    \"    fp_number = (whole_num << 16) + fractional_part\\n\",\n    \"    return fp_number\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import os\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 25,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"current_directory = os.getcwd()\\n\",\n    \"parent_directory = os.path.dirname(current_directory)\\n\",\n    \"new_directory_path = os.path.join(parent_directory, \\\"src/generated\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 26,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"os.makedirs('src/generated', exist_ok=True) \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 27,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tensor_name = [\\\"X\\\",\\\"X_std\\\",\\\"y\\\"]\\n\",\n    \"\\n\",\n    \"def generate_cairo_files(data, name):\\n\",\n    \"\\n\",\n    \"    with open(os.path.join('src', 'generated', f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"        f.write(\\n\",\n    \"            \\\"use array::{ArrayTrait, SpanTrait};\\\\n\\\" +\\n\",\n    \"            \\\"use orion::operators::tensor::{core::{Tensor, TensorTrait}};\\\\n\\\" +\\n\",\n    \"            \\\"use orion::operators::tensor::FP16x16Tensor;\\\\n\\\" +\\n\",\n    \"            \\\"use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\\\\n\\\" +\\n\",\n    \"            \\\"\\\\n\\\" + f\\\"fn {name}() -> Tensor<FP16x16>\\\" + \\\"{\\\\n\\\\n\\\" + \\n\",\n    \"            \\\"let mut shape = ArrayTrait::new();\\\\n\\\"\\n\",\n    \"        )\\n\",\n    \"        for dim in data.shape:\\n\",\n    \"            f.write(f\\\"shape.append({dim});\\\\n\\\")\\n\",\n    \"    \\n\",\n    \"        f.write(\\\"let mut data = ArrayTrait::new();\\\\n\\\")\\n\",\n    \"        for val in np.nditer(data.flatten()):\\n\",\n    \"            f.write(f\\\"data.append(FixedTrait::new({abs(int(decimal_to_fp16x16(val)))}, {str(val < 0).lower()}));\\\\n\\\")\\n\",\n    \"        f.write(\\n\",\n    \"            \\\"let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\\\\n\\\" +\\n\",\n    \"            \\\"return tensor;\\\\n}\\\"\\n\",\n    \"        )\\n\",\n    \"\\n\",\n    \"with open(f\\\"src/generated.cairo\\\", \\\"w\\\") as f:\\n\",\n    \"    for n in tensor_name:\\n\",\n    \"        f.write(f\\\"mod {n};\\\\n\\\")\\n\",\n    \"\\n\",\n    \"generate_cairo_files(X, \\\"X\\\")\\n\",\n    \"generate_cairo_files(X_std, \\\"X_std\\\")\\n\",\n    \"generate_cairo_files(y, \\\"y\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"<span style='color:Black'> **Convert some hyperparameters to FP16x16**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 28,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tol=1e-2\\n\",\n    \"max_iter=500\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 29,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"655\\n\",\n      \"32768000\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"print(decimal_to_fp16x16(tol))\\n\",\n    \"print(decimal_to_fp16x16(max_iter))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"<span style='color:Black'> **Get an estimate for the first two values of eigenvalus and first eigenvector in FP16x16**  </span>\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 30,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"First Eigenvalue: 137983\\n\",\n      \"Second Eigenvalue: 53087\\n\",\n      \"First Eigenvector: [-38469  36581 -38429]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"evec_1 = np.array([decimal_to_fp16x16(evec[0][0]),\\n\",\n    \"              decimal_to_fp16x16(evec[0][1]),\\n\",\n    \"              decimal_to_fp16x16(evec[0][2])])\\n\",\n    \"\\n\",\n    \"print(\\\"First Eigenvalue: {}\\\".format(decimal_to_fp16x16(evalu[0])))\\n\",\n    \"print(\\\"Second Eigenvalue: {}\\\".format(decimal_to_fp16x16(evalu[1])))\\n\",\n    \"\\n\",\n    \"print(\\\"First Eigenvector: {}\\\".format(evec_1))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For the implementation of PCA in Cairo with Orion, please visit the Convert your model section within the **Verifiable Principal Componentes Analysis tutorial**\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.12\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated.cairo",
        "content": "mod X_std;\nmod X;\nmod y;\nmod evalu_sort;\nmod evec_sort;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated/X.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\n\nfn X() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(105);\n    shape.append(3);\n    let mut data = ArrayTrait::new();\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(235929, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(255590, false));\n    data.append(FixedTrait::new(111411, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(242483, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(281804, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(72089, false));\n    data.append(FixedTrait::new(380108, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(78643, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(255590, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(249036, false));\n    data.append(FixedTrait::new(111411, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(249036, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(111411, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(242483, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(235929, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(111411, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(124518, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(340787, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(340787, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(340787, false));\n    data.append(FixedTrait::new(268697, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(275251, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(78643, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(235929, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(150732, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(85196, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(249036, false));\n    data.append(FixedTrait::new(124518, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(249036, false));\n    data.append(FixedTrait::new(104857, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(347340, false));\n    data.append(FixedTrait::new(242483, false));\n    data.append(FixedTrait::new(98304, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(91750, false));\n    data.append(FixedTrait::new(458752, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(419430, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(452198, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(150732, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(425984, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(412876, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(157286, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(432537, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(340787, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(255590, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(131072, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(386662, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(275251, false));\n    data.append(FixedTrait::new(393216, false));\n    data.append(FixedTrait::new(144179, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(399769, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(235929, false));\n    data.append(FixedTrait::new(439091, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(380108, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(268697, false));\n    data.append(FixedTrait::new(406323, false));\n    data.append(FixedTrait::new(144179, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(163840, false));\n    data.append(FixedTrait::new(255590, false));\n    data.append(FixedTrait::new(386662, false));\n    data.append(FixedTrait::new(209715, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(399769, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(412876, false));\n    data.append(FixedTrait::new(163840, false));\n    data.append(FixedTrait::new(321126, false));\n    data.append(FixedTrait::new(399769, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(419430, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(281804, false));\n    data.append(FixedTrait::new(432537, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(445644, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(314572, false));\n    data.append(FixedTrait::new(439091, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(393216, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(170393, false));\n    data.append(FixedTrait::new(229376, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(157286, false));\n    data.append(FixedTrait::new(249036, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(157286, false));\n    data.append(FixedTrait::new(242483, false));\n    data.append(FixedTrait::new(380108, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(255590, false));\n    data.append(FixedTrait::new(393216, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(353894, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(393216, false));\n    data.append(FixedTrait::new(222822, false));\n    data.append(FixedTrait::new(294912, false));\n    data.append(FixedTrait::new(439091, false));\n    data.append(FixedTrait::new(203161, false));\n    data.append(FixedTrait::new(308019, false));\n    data.append(FixedTrait::new(412876, false));\n    data.append(FixedTrait::new(150732, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(268697, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(163840, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(360448, false));\n    data.append(FixedTrait::new(170393, false));\n    data.append(FixedTrait::new(288358, false));\n    data.append(FixedTrait::new(399769, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(301465, false));\n    data.append(FixedTrait::new(380108, false));\n    data.append(FixedTrait::new(170393, false));\n    data.append(FixedTrait::new(262144, false));\n    data.append(FixedTrait::new(327680, false));\n    data.append(FixedTrait::new(150732, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(275251, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(275251, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(275251, false));\n    data.append(FixedTrait::new(406323, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(281804, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(163840, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(373555, false));\n    data.append(FixedTrait::new(183500, false));\n    data.append(FixedTrait::new(268697, false));\n    data.append(FixedTrait::new(412876, false));\n    data.append(FixedTrait::new(216268, false));\n    data.append(FixedTrait::new(393216, false));\n    data.append(FixedTrait::new(380108, false));\n    data.append(FixedTrait::new(176947, false));\n    data.append(FixedTrait::new(334233, false));\n    data.append(FixedTrait::new(465305, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(386662, false));\n    data.append(FixedTrait::new(412876, false));\n    data.append(FixedTrait::new(190054, false));\n    data.append(FixedTrait::new(367001, false));\n    data.append(FixedTrait::new(425984, false));\n    data.append(FixedTrait::new(196608, false));\n    data.append(FixedTrait::new(380108, false));\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated/X_std.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\n\nfn X_std() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(105);\n    shape.append(3);\n    let mut data = ArrayTrait::new();\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(61079, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(80935, true));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(90862, true));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(71031, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(113089, false));\n    data.append(FixedTrait::new(55415, true));\n    data.append(FixedTrait::new(90862, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(110718, true));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(61079, true));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(85050, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(71007, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(71007, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(120646, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(81086, true));\n    data.append(FixedTrait::new(28270, false));\n    data.append(FixedTrait::new(127108, false));\n    data.append(FixedTrait::new(76807, true));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(183185, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(113089, false));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(99069, false));\n    data.append(FixedTrait::new(55415, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(99069, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(55415, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(85050, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(90862, true));\n    data.append(FixedTrait::new(71031, false));\n    data.append(FixedTrait::new(85364, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(28973, false));\n    data.append(FixedTrait::new(55415, true));\n    data.append(FixedTrait::new(71007, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(46858, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(31296, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(31296, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(80935, true));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(71007, true));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(31296, true));\n    data.append(FixedTrait::new(141127, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(155147, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(61079, true));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(76807, true));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(61079, true));\n    data.append(FixedTrait::new(71031, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(110718, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(100790, true));\n    data.append(FixedTrait::new(111220, true));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(110718, true));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(72529, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(57011, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(99069, false));\n    data.append(FixedTrait::new(46858, true));\n    data.append(FixedTrait::new(71007, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(99069, false));\n    data.append(FixedTrait::new(59694, true));\n    data.append(FixedTrait::new(90862, true));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(21368, true));\n    data.append(FixedTrait::new(85050, false));\n    data.append(FixedTrait::new(63972, true));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(28973, false));\n    data.append(FixedTrait::new(68250, true));\n    data.append(FixedTrait::new(147403, false));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(72936, false));\n    data.append(FixedTrait::new(87837, false));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(137476, false));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(81493, false));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(111220, true));\n    data.append(FixedTrait::new(42987, false));\n    data.append(FixedTrait::new(97765, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(68658, false));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(77909, false));\n    data.append(FixedTrait::new(28973, false));\n    data.append(FixedTrait::new(72936, false));\n    data.append(FixedTrait::new(61079, true));\n    data.append(FixedTrait::new(97200, true));\n    data.append(FixedTrait::new(13038, false));\n    data.append(FixedTrait::new(107692, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(68658, false));\n    data.append(FixedTrait::new(31296, true));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(38709, false));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(153278, true));\n    data.append(FixedTrait::new(21595, false));\n    data.append(FixedTrait::new(38198, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(51544, false));\n    data.append(FixedTrait::new(48126, false));\n    data.append(FixedTrait::new(125239, true));\n    data.append(FixedTrait::new(42987, false));\n    data.append(FixedTrait::new(58053, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(72936, false));\n    data.append(FixedTrait::new(8414, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(25874, false));\n    data.append(FixedTrait::new(117620, false));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(60101, false));\n    data.append(FixedTrait::new(8414, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(28270, false));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(47266, false));\n    data.append(FixedTrait::new(67981, false));\n    data.append(FixedTrait::new(125239, true));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(8414, false));\n    data.append(FixedTrait::new(83181, true));\n    data.append(FixedTrait::new(38709, false));\n    data.append(FixedTrait::new(38198, false));\n    data.append(FixedTrait::new(14953, false));\n    data.append(FixedTrait::new(77215, false));\n    data.append(FixedTrait::new(58053, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(42987, false));\n    data.append(FixedTrait::new(77909, false));\n    data.append(FixedTrait::new(83181, true));\n    data.append(FixedTrait::new(81493, false));\n    data.append(FixedTrait::new(58053, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(72936, false));\n    data.append(FixedTrait::new(87837, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(55823, false));\n    data.append(FixedTrait::new(107692, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(60101, false));\n    data.append(FixedTrait::new(127548, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(77215, false));\n    data.append(FixedTrait::new(117620, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(85772, false));\n    data.append(FixedTrait::new(48126, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(69162, true));\n    data.append(FixedTrait::new(21595, false));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(97200, true));\n    data.append(FixedTrait::new(34431, false));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(97200, true));\n    data.append(FixedTrait::new(30152, false));\n    data.append(FixedTrait::new(28270, false));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(38709, false));\n    data.append(FixedTrait::new(48126, false));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(90050, false));\n    data.append(FixedTrait::new(11440, true));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(48126, false));\n    data.append(FixedTrait::new(42992, false));\n    data.append(FixedTrait::new(64379, false));\n    data.append(FixedTrait::new(117620, false));\n    data.append(FixedTrait::new(934, false));\n    data.append(FixedTrait::new(72936, false));\n    data.append(FixedTrait::new(77909, false));\n    data.append(FixedTrait::new(111220, true));\n    data.append(FixedTrait::new(60101, false));\n    data.append(FixedTrait::new(8414, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(47266, false));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(83181, true));\n    data.append(FixedTrait::new(42987, false));\n    data.append(FixedTrait::new(1512, true));\n    data.append(FixedTrait::new(69162, true));\n    data.append(FixedTrait::new(60101, false));\n    data.append(FixedTrait::new(58053, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(68658, false));\n    data.append(FixedTrait::new(28270, false));\n    data.append(FixedTrait::new(69162, true));\n    data.append(FixedTrait::new(42987, false));\n    data.append(FixedTrait::new(51151, true));\n    data.append(FixedTrait::new(111220, true));\n    data.append(FixedTrait::new(13038, false));\n    data.append(FixedTrait::new(8414, false));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(51544, false));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(51544, false));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(51544, false));\n    data.append(FixedTrait::new(67981, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(55823, false));\n    data.append(FixedTrait::new(41223, true));\n    data.append(FixedTrait::new(83181, true));\n    data.append(FixedTrait::new(203, false));\n    data.append(FixedTrait::new(18342, false));\n    data.append(FixedTrait::new(41123, true));\n    data.append(FixedTrait::new(47266, false));\n    data.append(FixedTrait::new(77909, false));\n    data.append(FixedTrait::new(28973, false));\n    data.append(FixedTrait::new(128556, false));\n    data.append(FixedTrait::new(28270, false));\n    data.append(FixedTrait::new(55142, true));\n    data.append(FixedTrait::new(90050, false));\n    data.append(FixedTrait::new(157331, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(124277, false));\n    data.append(FixedTrait::new(77909, false));\n    data.append(FixedTrait::new(27104, true));\n    data.append(FixedTrait::new(111442, false));\n    data.append(FixedTrait::new(97765, false));\n    data.append(FixedTrait::new(13084, true));\n    data.append(FixedTrait::new(119999, false));\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated/evalu_sort.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\n\nfn evalu_sort() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(3);\n    let mut data = ArrayTrait::new();\n\n    // evalu Original [ 52513 137534   5393]\n    // evalu Sorted   [137534  52513   5393]\n\n    data.append(FixedTrait::new(137534, false));\n    data.append(FixedTrait::new(52513, false));\n    data.append(FixedTrait::new(5393, false));\n\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated/evec_sort.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\n\nfn evec_sort() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(3);\n    shape.append(3);\n\n    // evec Original\n    // [[ 36422 -38024 -38467]\n    // [ 53777  30012  21440]\n    // [  5195 -43789  48143]]\n\n    // evec Sorted\n    // [[-38024  36422 -38467]\n    // [ 30012  53777  21440]\n    // [-43789   5195  48143]]\n\n    let mut data = ArrayTrait::new();\n\n    data.append(FixedTrait::new(38024, true));\n    data.append(FixedTrait::new(36422, false));\n    data.append(FixedTrait::new(38467, true));\n\n    data.append(FixedTrait::new(30012, false));\n    data.append(FixedTrait::new(53777, false));\n    data.append(FixedTrait::new(21440, false));\n\n    data.append(FixedTrait::new(43789, true));\n    data.append(FixedTrait::new(5195, false));\n    data.append(FixedTrait::new(48143, false));\n\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/generated/y.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{core::{Tensor, TensorTrait}};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16, FixedTrait};\n\nfn y() -> Tensor<FP16x16> {\n    let mut shape = ArrayTrait::new();\n    shape.append(105);\n    let mut data = ArrayTrait::new();\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(0, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(65536, false));\n    data.append(FixedTrait::new(131072, false));\n    data.append(FixedTrait::new(131072, false));\n    data.append(FixedTrait::new(131072, false));\n    data.append(FixedTrait::new(131072, false));\n    data.append(FixedTrait::new(131072, false));\n    let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/helper.cairo",
        "content": "use traits::TryInto;\nuse alexandria_data_structures::array_ext::{SpanTraitExt};\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{Tensor, TensorTrait};\nuse orion::numbers::fixed_point::{core::{FixedTrait}};\n\nuse orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    FP16x16, FP16x16Impl, FP16x16Add, FP16x16AddEq, FP16x16Sub, FP16x16Mul, FP16x16MulEq,\n    FP16x16TryIntoU128, FP16x16PartialEq, FP16x16PartialOrd, FP16x16SubEq, FP16x16Neg, FP16x16Div,\n    FP16x16IntoFelt252, FP16x16Print, HALF\n};\n\nuse orion::numbers::fixed_point::implementations::fp16x16::math::trig;\n\n#[derive(Copy, Drop)]\nstruct EigenValues<FP16x16> {\n    p_index: usize,\n    q_index: usize,\n    theta: FP16x16,\n}\n\nfn div_by_scalar(self: @Tensor<FP16x16>, divisor: u32) -> Tensor<FP16x16> {\n    let mut data = (*self).data;\n    let mut data_array = ArrayTrait::new();\n\n    loop {\n        match data.pop_front() {\n            Option::Some(elem) => {\n                data_array.append(FixedTrait::new(*elem.mag / divisor, *elem.sign));\n            },\n            Option::None(_) => {\n                break TensorTrait::<FP16x16>::new((*self).shape, data_array.span());\n            }\n        };\n    }\n}\n\nfn div_by_fp(self: @Tensor<FP16x16>, divisor: FP16x16) -> Tensor<FP16x16> {\n    let mut data = (*self).data;\n    let mut data_array = ArrayTrait::new();\n\n    loop {\n        match data.pop_front() {\n            Option::Some(elem) => { data_array.append(FP16x16Div::div(*elem, divisor)); },\n            Option::None(_) => {\n                break TensorTrait::<FP16x16>::new((*self).shape, data_array.span());\n            }\n        };\n    }\n}\n\n// find_max_off_diag: Finds the maximum off-diagonal element in a square Tensor.\nfn find_max_off_diag(a: @Tensor<FP16x16>) -> (usize, usize) {\n    let mut data = *a.data;\n    let mut shape = *a.shape;\n\n    let n = *(*a).shape.at(0);\n\n    let mut i = 0_usize;\n    let mut j = 0_usize;\n    let mut p = 0_usize;\n    let mut q = 1_usize;\n\n    let mut max_val = FixedTrait::abs((*a).at(indices: array![p, q].span()));\n\n    loop {\n        if i == n {\n            break (p, q);\n        };\n\n        j = i + 1;\n\n        loop {\n            if j == n {\n                break;\n            };\n            if FixedTrait::abs((a).at(indices: array![i, j].span())) > max_val {\n                max_val = FixedTrait::abs((a).at(indices: array![i, j].span()));\n                p = i;\n                q = j;\n            };\n            j += 1;\n        };\n        i += 1;\n    }\n}\n\n// jacobi_eigensystem: Implements the Jacobi eigenvalue algorithm to compute the eigenvalues and eigenvectors of a symmetric Tensor.\nfn jacobi_eigensystem(\n    mut a: Tensor<FP16x16>, tol: FP16x16, max_iter: usize\n) -> (Tensor<FP16x16>, Tensor<FP16x16>) {\n    assert(\n        !((a).shape.len() != 2_usize || ((a).shape.at(0_usize) != (a).shape.at(1_usize))),\n        'a must be a square matrix'\n    );\n\n    // let two = FixedTrait::new(ONE, false) + FixedTrait::new(ONE, false);\n    let two = FixedTrait::ONE() + FixedTrait::ONE();\n    let four = two * two;\n    let half = FixedTrait::<FP16x16>::new(HALF, false);\n    let pi = FixedTrait::<FP16x16>::new(trig::PI, false);\n\n    let mut data = a.data;\n    let mut shape = a.shape;\n    let numRows = *((shape).at(0));\n    let mut v = eye(numRows: numRows);\n\n    let mut i: usize = 0;\n\n    loop {\n        let (p, q) = find_max_off_diag(@a);\n\n        if i == max_iter || FixedTrait::abs((a).at(indices: array![p, q].span())) < tol {\n            break (extract_diagonal(@a), v);\n        };\n\n        let theta = if (a)\n            .at(indices: array![p, p].span()) == (a)\n            .at(indices: array![q, q].span()) {\n            FP16x16Div::div(pi, four)\n        } else {\n            half\n                * trig::atan(\n                    FP16x16Div::div(\n                        two * (a).at(indices: array![p, q].span()),\n                        (FP16x16Sub::sub(\n                            (a).at(indices: array![p, p].span()),\n                            (a).at(indices: array![q, q].span())\n                        ))\n                    )\n                )\n        };\n\n        let eigensystem = EigenValues { p_index: p, q_index: q, theta: theta };\n\n        let j_eye = eye(numRows: numRows);\n\n        let j = update_eigen_values(self: @j_eye, eigensystem: eigensystem);\n\n        let transpose_j = j.transpose(axes: array![1, 0].span());\n        a = transpose_j.matmul(@a).matmul(@j);\n\n        v = v.matmul(@j);\n\n        i += 1;\n    }\n}\n\n// eye: Generates an identity Tensor of the specified size\nfn eye(numRows: usize) -> Tensor<FP16x16> {\n    let mut data_array = ArrayTrait::new();\n\n    let mut x: usize = 0;\n\n    loop {\n        if x == numRows {\n            break;\n        };\n\n        let mut y: usize = 0;\n\n        loop {\n            if y == numRows {\n                break;\n            };\n\n            if x == y {\n                data_array.append(FixedTrait::ONE());\n            } else {\n                data_array.append(FixedTrait::ZERO());\n            };\n\n            y += 1;\n        };\n        x += 1;\n    };\n\n    Tensor::<FP16x16> { shape: array![numRows, numRows].span(), data: data_array.span() }\n}\n\n// extract_diagonal: Extracts the diagonal elements from a square tensor\nfn extract_diagonal(self: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut data = (*self).data;\n    let mut data_array = ArrayTrait::new();\n\n    let dims = (*self).shape.at(0);\n\n    let mut x: usize = 0;\n\n    loop {\n        if x == *dims {\n            break;\n        };\n\n        let mut y: usize = 0;\n\n        loop {\n            if y == *dims {\n                break;\n            };\n\n            match data.pop_front() {\n                Option::Some(elem) => { if x == y {\n                    data_array.append(*elem);\n                }; },\n                Option::None(_) => { break; }\n            };\n            y += 1;\n        };\n        x += 1;\n    };\n\n    Tensor::<FP16x16> { shape: array![*dims].span(), data: data_array.span() }\n}\n\n// update_eigen_values: Updates the eigenvalues of a symmetric tensor\nfn update_eigen_values(\n    self: @Tensor<FP16x16>, eigensystem: EigenValues<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut data = (*self).data;\n    let mut data_array = ArrayTrait::new();\n\n    let mut x: usize = 0;\n    let mut y: usize = 0;\n    let mut index: usize = 0;\n    let dims = (*self).shape.at(0);\n    let items = *dims * *dims;\n    let dims_y = (*self).shape.at(1);\n\n    loop {\n        if index == items {\n            break;\n        };\n\n        if y == *dims_y {\n            x += 1;\n            y = 0;\n        };\n\n        match data.pop_front() {\n            Option::Some(elem) => {\n                let eigen_values = eigensystem;\n\n                let value = if (eigen_values.p_index, eigen_values.p_index) == (x, y) {\n                    trig::cos(eigen_values.theta)\n                } else if (eigen_values.q_index, eigen_values.q_index) == (x, y) {\n                    trig::cos(eigen_values.theta)\n                } else if (eigen_values.p_index, eigen_values.q_index) == (x, y) {\n                    trig::sin(eigen_values.theta)\n                } else if (eigen_values.q_index, eigen_values.p_index) == (x, y) {\n                    trig::sin(-eigen_values.theta)\n                } else {\n                    *elem\n                };\n\n                data_array.append(value);\n                y += 1;\n                index += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n\n    Tensor::<FP16x16> { shape: *self.shape, data: data_array.span() }\n}\n\n// check_unit_diagonal_tensor: Checks whether a square tensor has a unit diagonal\nfn check_unit_diagonal_tensor(self: @Tensor<FP16x16>) -> bool {\n    let mut x: usize = 0;\n    let mut valid: bool = true;\n    let dim_x = (*self).shape.at(0);\n    let dim_y = (*self).shape.at(1);\n\n    loop {\n        if x == *dim_x || !valid {\n            break valid;\n        };\n\n        let mut y: usize = 0;\n\n        loop {\n            if y == *dim_y {\n                break;\n            };\n\n            if x == y {\n                if (self).at(indices: array![x, y].span()) != FixedTrait::ONE() {\n                    valid = false;\n                    break;\n                }\n            } else {\n                if (self).at(indices: array![x, y].span()) != FixedTrait::ZERO() {\n                    valid = false;\n                    break;\n                }\n            };\n\n            y += 1;\n        };\n        x += 1;\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/lib.cairo",
        "content": "mod generated;\nmod helper;\nmod test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_principal_component_analysis/src/test.cairo",
        "content": "#[cfg(test)]\nmod tests {\n    use traits::TryInto;\n    use alexandria_data_structures::array_ext::{SpanTraitExt};\n    use array::{ArrayTrait, SpanTrait};\n    use orion::operators::tensor::{Tensor, TensorTrait};\n    use orion::numbers::fixed_point::{core::{FixedTrait}};\n\n    use orion::operators::tensor::{FP16x16Tensor, FP16x16TensorDiv, FP16x16TensorSub};\n\n    use orion::numbers::fixed_point::implementations::fp16x16::core::{\n        FP16x16, FP16x16Impl, FP16x16Add, FP16x16AddEq, FP16x16Sub, FP16x16Mul, FP16x16MulEq,\n        FP16x16TryIntoU128, FP16x16PartialEq, FP16x16PartialOrd, FP16x16SubEq, FP16x16Neg,\n        FP16x16Div, FP16x16IntoFelt252, FP16x16Print\n    };\n\n    use pca::{\n        helper::{\n            EigenValues, extract_diagonal, eye, find_max_off_diag, jacobi_eigensystem,\n            update_eigen_values, check_unit_diagonal_tensor, div_by_scalar, div_by_fp\n        }\n    };\n\n    use pca::{generated::{X_std::X_std, X::X, y::y, evalu_sort::evalu_sort, evec_sort::evec_sort}};\n\n    #[test]\n    #[available_gas(99999999999999999)]\n    fn pca_test() {\n        let tol = FixedTrait::<FP16x16>::new(655, false); // 655 is 0.01 = 1e-2\n        let max_iter = 500_usize;\n\n        let X_std = X_std();\n        let X = X();\n        let y = y();\n\n        let mut n: usize = *((X_std).shape.at(0)) - 1;\n        let size = *(X_std.shape.at(1));\n\n        let X_std_transpose = X_std.transpose(axes: array![1, 0].span());\n        let mut cov_matrix = div_by_scalar(@(X_std_transpose.matmul(@X_std)), n);\n\n        let mut stddevs = extract_diagonal(@cov_matrix).sqrt();\n\n        let mut stddevs_left = stddevs.reshape(array![size, 1].span());\n        let mut stddevs_right = stddevs.reshape(array![1, size].span());\n        let corr_matrix = cov_matrix / stddevs_left.matmul(@stddevs_right);\n\n        let (evalu, evec) = jacobi_eigensystem(a: corr_matrix, tol: tol, max_iter: max_iter);\n\n        let (evalu, evec) = (evalu_sort(), evec_sort());\n\n        let loadings = evec;\n\n        let principal_component = X_std.matmul(@loadings);\n\n        n = *((principal_component).shape.at(0)) - 1;\n\n        let principal_component_transpose = principal_component\n            .transpose(axes: array![1, 0].span());\n\n        let cov_new = div_by_scalar(\n            @(principal_component_transpose.matmul(@principal_component)), n\n        );\n\n        stddevs = extract_diagonal(@cov_new).sqrt();\n        stddevs_left = stddevs.reshape(array![size, 1].span());\n        stddevs_right = stddevs.reshape(array![1, size].span());\n        let corr_new = cov_new / stddevs_left.matmul(@stddevs_right);\n\n        let new_corr = (@corr_new.abs()).round();\n\n        // The orthogonality of the tensor is validated.\n        assert(check_unit_diagonal_tensor(@new_corr), 'orthogonality is invalid');\n\n        let evalu_cumsum = evalu.cumsum(0, Option::None(()), Option::None(()));\n        let sum = evalu_cumsum.data.at(evalu_cumsum.data.len() - 1);\n        let evalu_div_sum = div_by_fp(@evalu, *sum);\n        let pc = (*evalu_div_sum.data.at(0) + *evalu_div_sum.data.at(1))\n            * FixedTrait::<FP16x16>::new_unscaled(100, false);\n\n        assert(\n            FixedTrait::round(pc).mag == 0x610000, 'no match with notebook version'\n        ); //  0x610000 == 97\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/notebooks/svm.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# **Verifiable Support Vector Machine**\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The Support Vector Machines (SVM) model is a supervised learning technique used for classification and regression. It is employed to solve binary classification problems where it identifies the hyperplane that best divides a data set into classes. This hyperplane results from maximizing the margin between the two classes. By determining this optimal hyperplane, predictions can be made for new data points and understand how the input attributes influence classification.\\n\",\n    \"\\n\",\n    \"Below, we provide a brief review of implementing an SVM model using the Gradient Descent method for the linear kernel in Python, which we will later convert to Cairo to transform it into a verifiable ZKML (support vector machine model), using Orion's library. This allows an opportunity to familiarize oneself with the main functions and operators that the framework offers for the implementation of the SVM.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"###  **DataSet Generate**  \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For the purposes of this tutorial, we generated linearly separable data using make_blobs from Scikit-learn\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"(100, 3) (100,) (50, 3) (50,)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"from sklearn.datasets import make_blobs\\n\",\n    \"\\n\",\n    \"X, y = make_blobs(n_samples=150, centers=2,\\n\",\n    \"                  random_state=0, cluster_std=0.60)\\n\",\n    \"y[y == 0] = -1\\n\",\n    \"\\n\",\n    \"X = np.hstack((X, np.ones((X.shape[0], 1))))\\n\",\n    \"\\n\",\n    \"X_train, y_train = X[:100, :], y[:100]\\n\",\n    \"X_test, y_test = X[100:, :], y[100:]\\n\",\n    \"\\n\",\n    \"print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Now we will visualize the training data using a scatter plot, where the points are colored based on their class labels, which in our case will be 1 and -1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<matplotlib.collections.PathCollection at 0x145c39360>\"\n      ]\n     },\n     \"execution_count\": 3,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAhYAAAGdCAYAAABO2DpVAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy88F64QAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA9iUlEQVR4nO3deXhU9dn/8fdkIWFJAiggS2QRRUVFBBUQVxBFa8HWulQRqtZHi1r11ypqraLWaJ8+Lq0tKqJW24pWRHGjorJZRAVBcEOqIMgOhSQEHJLJ+f1xZ5gMmUAmOTNn5szndV1zkXOYzLk5c5hzz3e5vwHHcRxEREREXJDldQAiIiLiH0osRERExDVKLERERMQ1SixERETENUosRERExDVKLERERMQ1SixERETENUosRERExDU5yT5gdXU1a9eupaCggEAgkOzDi4iISCM4jkN5eTmdOnUiK6v+domkJxZr166luLg42YcVERERF6xevZouXbrU+/dJTywKCgoAC6ywsDDZhxcREZFGKCsro7i4ePd9vD5JTyzC3R+FhYVKLERERNLMvoYxaPCmiIiIuEaJhYiIiLhGiYWIiIi4RomFiIiIuEaJhYiIiLhGiYWIiIi4RomFiIiIuEaJhYiIiLhGiYWIiIi4RomFiIiIuCbpJb0ToqIC3nzT/jzlFOja1euIYtu5E777Djp1gpYtvY5GRETEdenfYrF5M/TtCz/5CYwZA4cdBrNnex1VXS+/DPvvD4ccAvvtB3/7m9cRiYiIuC79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z+eefO9dff73TsmVLZ+XKlY7jOM64ceOcUaNG7X7+N99847Ro0cK54YYbnM8//9yZNGmSk5ub67z44ote/ROaLN5z8OCDDzpTp051vvrqK+fTTz91xo0b5wDOlClTvPonNEl5ebmzaNEiZ9GiRQ7gPPDAA86iRYucb7/91nGczLgG4j0HfrsGrr76aqeoqMiZNWuWs27dut2PHTt27H6O36+DxpwDP10Ht9xyizNnzhxnxYoVzpIlS5xbb73VycrKct566y3Hcfz//jtO/OcgUe9/2icWjuM4f/7zn52uXbs6zZo1c4455pio6VWjR492Tj755Kjnz5o1y+nbt6/TrFkzp1u3bs6ECROSHLH74jkH999/v3PQQQc5+fn5Tps2bZzBgwc7r7/+ugdRuyM8ZWrPx+jRox3HyYxrIN5z4LdrINa/HXCeeuqp3c/x+3XQmHPgp+vgsssu2/0Z2K5dO2fIkCG7b6iO4//333HiPweJev+1bLqIiIi4Jq3HWIiIiEhqUWIhIiIirlFiISIiIq5RYiEiIiKuUWIhIiIirlFiISIiIq5RYiEiIiKuUWIhIiIirlFiISIiIq5RYiEiIiKuUWIhIiIirlFiISIiIq75/yzIgsuRw7uPAAAAAElFTkSuQmCC\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, s=10, cmap='autumn')\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### **Loss function, gradient and Weight init** \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We will start by generating the key functions for SVM.\\n\",\n    \"\\n\",\n    \"Next, we'll define the loss functions and its gradient, with $\\\\mathbf{L2}$ regularization, both necessary to train our SVM.\\n\",\n    \"\\n\",\n    \"In the case of the loss function in SVM, the Hinge Loss ($\\\\max(0, 1 - y_i \\\\times (\\\\mathbf{w} \\\\cdot \\\\mathbf{x}_i))$) is used, which measures how far a sample is on the \\\"wrong side\\\" of the margin. If the sample is on the correct side of the margin, the loss is 0.\\n\",\n    \"\\n\",\n    \"$\\\\text{Loss Function}$  = $ \\\\frac{1}{N} \\\\sum_{i=1}^{N} \\\\max(0, 1 - y_i \\\\times (\\\\mathbf{w} \\\\cdot \\\\mathbf{x}_i)) + C \\\\times \\\\frac{1}{2} \\\\times \\\\mathbf{w} \\\\cdot \\\\mathbf{w}$\\n\",\n    \"\\n\",\n    \"$\\\\text{Gradient}$  =  $\\\\frac{1}{N} \\\\sum_{i=1}^{N} \\\\left( -y_i \\\\times \\\\mathbf{x}_i \\\\text{ (si } y_i \\\\times (\\\\mathbf{w} \\\\cdot \\\\mathbf{x}_i) < 1 \\\\text{) } \\\\right) + C \\\\times \\\\mathbf{w}$\\n\",\n    \"\\n\",\n    \"For the purposes of this tutorial, we initialize $\\\\mathbf{w}$ as an array of $\\\\mathbf{0's}$\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def loss_function(w, X, y, C):  \\n\",\n    \"    hinge_loss = np.maximum(0, 1 - y * np.dot(X, w)) \\n\",\n    \"    regularization_term = 0.5 * np.dot(w, w)  # Regularizaci\u00f3n L2 ###\\n\",\n    \"    total_loss = np.mean(hinge_loss) + C * regularization_term ###\\n\",\n    \"    return total_loss\\n\",\n    \"\\n\",\n    \"def loss_gradient(w, X, y, C):     \\n\",\n    \"    mask = (y * (np.dot(X, w))) < 1    #<1\\n\",\n    \"    gradient = (-np.dot(mask * y, X) / len(y)) +  C*w\\n\",\n    \"    return gradient\\n\",\n    \"\\n\",\n    \"# Gradiente descendente\\n\",\n    \"losses = []\\n\",\n    \"w = np.zeros(3)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"###  **Initial hyperparameters** \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Now, we declare the hyperparameters: learning rate (learning_rate), the number of epochs (num_epochs), and the regularization parameter (C). Then, we will use gradient descent to adjust the weights of the SVM model. For the purposes of this tutorial, we stick with the following hyperparameters; however, the hyperplane acquisition could be improved with their adjustment.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"learning_rate = 0.01\\n\",\n    \"num_epochs = 100\\n\",\n    \"C = 1\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### **Training** \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 0, Loss: 1.0000\\n\",\n      \"Epoch 25, Loss: 0.5300\\n\",\n      \"Epoch 50, Loss: 0.4594\\n\",\n      \"Epoch 75, Loss: 0.4238\\n\",\n      \"Epoch 99, Loss: 0.4092\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"for epoch in range(num_epochs):\\n\",\n    \"    loss = loss_function(w,X_train, y_train, C)\\n\",\n    \"    losses.append(loss)\\n\",\n    \"\\n\",\n    \"    if epoch % 25 == 0 or epoch  == 99:\\n\",\n    \"        print(f\\\"Epoch {epoch}, Loss: {loss:.4f}\\\")\\n\",\n    \"\\n\",\n    \"    gradient_w = loss_gradient(w, X_train, y_train,C)\\n\",\n    \"    w -= learning_rate * gradient_w\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<matplotlib.lines.Line2D at 0x145d7edd0>]\"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAiMAAAGdCAYAAADAAnMpAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy88F64QAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA7wklEQVR4nO3deXicdb3//9fMJDNZmkySptnTJAVKQ0O3pC3dKJvhFESqfrWiUlHwa/2JUKoerfXoseqJ56h8K2qrCMWDcKRHQEStSEAoLQVK06R0owtdkmZpmjSZJE0yk8zcvz+SDA1N20y2O5N5Pq7rvprcc9+Zdz6Uzuv6bLfFMAxDAAAAJrGaXQAAAAhthBEAAGAqwggAADAVYQQAAJiKMAIAAExFGAEAAKYijAAAAFMRRgAAgKnCzC6gP3w+n6qqqhQTEyOLxWJ2OQAAoB8Mw1Bzc7PS0tJktV64/yMowkhVVZUyMzPNLgMAAAxARUWFMjIyLvh6UISRmJgYSV2/TGxsrMnVAACA/mhqalJmZqb/c/xCgiKM9AzNxMbGEkYAAAgyl5piwQRWAABgKsIIAAAwFWEEAACYijACAABMRRgBAACmIowAAABTEUYAAICpCCMAAMBUhBEAAGCqgMPIa6+9pttuu01paWmyWCx67rnnLnnPli1blJ+fr4iICE2aNEm//vWvB1IrAAAYgwIOI2fPntX06dP1y1/+sl/XHzt2TLfccosWLVqk0tJSffvb39Z9992nZ555JuBiAQDA2BPws2mWLFmiJUuW9Pv6X//615o4caLWrVsnScrNzdXOnTv105/+VB//+McDfXsAADDGDPuckTfeeEOFhYW9zt18883auXOnOjo6+rzH7Xarqamp1zEcnt9dpX99erd2VzQOy88HAACXNuxhpKamRsnJyb3OJScnq7OzU3V1dX3eU1RUJKfT6T8yMzOHpba/76nW/+48qTeO1g/LzwcAAJc2IqtpPvjoYMMw+jzfY/Xq1XK5XP6joqJiWOqalhEnSXrnZOOw/HwAAHBpAc8ZCVRKSopqamp6nautrVVYWJjGjx/f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YmCibzXZeL0htbe15vSWS1NzcrJ07d6q0tFT33nuvJMnn88kwDIWFhenFF1/UDTfccN59DodDDocjkNIAAECQCqhnxG63Kz8/X8XFxb3OFxcXa/78+eddHxsbqz179qisrMx/rFixQldeeaXKyso0d+7cwVUPAACCXsD7jKxatUp33nmnCgoKNG/ePD388MMqLy/XihUrJHUNsVRWVurxxx+X1WpVXl5er/uTkpIUERFx3nkAABCaAg4jy5YtU319vdauXavq6mrl5eVp8+bNysrKkiRVV1dfcs8RAACAHgHvM2IG9hkBACD4DMs+IwAAAEONMAIAAExFGAEAAKYa0FN7R1rPtBa2hQcAIHj0fG5fanpqUISR5uZmSWJbeAAAglBzc7OcTucFXw+K1TQ+n09VVVWKiYnpc9v5gWpqalJmZqYqKipYpTPMaOuRRXuPHNp65NDWI2eo2towDDU3NystLU1W64VnhgRFz4jValVGRsaw/fzY2Fj+Yo8Q2npk0d4jh7YeObT1yBmKtr5Yj0gPJrACAABTEUYAAICpQjqMOBwOfe973+MJwSOAth5ZtPfIoa1HDm09cka6rYNiAisAABi7QrpnBAAAmI8wAgAATEUYAQAApiKMAAAAU4V0GFm/fr1ycnIUERGh/Px8bd261eySgl5RUZFmz56tmJgYJSUlaenSpTp48GCvawzD0L//+78rLS1NkZGRuu6667Rv3z6TKh4bioqKZLFYtHLlSv852nloVVZW6rOf/azGjx+vqKgozZgxQyUlJf7Xae+h0dnZqe985zvKyclRZGSkJk2apLVr18rn8/mvoa0H5rXXXtNtt92mtLQ0WSwWPffcc71e70+7ut1uffWrX1ViYqKio6P1kY98RCdPnhx8cUaIeuqpp4zw8HDjt7/9rbF//37j/vvvN6Kjo40TJ06YXVpQu/nmm43HHnvM2Lt3r1FWVmbceuutxsSJE42Wlhb/NT/+8Y+NmJgY45lnnjH27NljLFu2zEhNTTWamppMrDx47dixw8jOzjamTZtm3H///f7ztPPQOXPmjJGVlWXcddddxltvvWUcO3bMeOmll4wjR474r6G9h8YPf/hDY/z48cZf//pX49ixY8Yf//hHY9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GAYhu699149++yz+uc//6mcnJxer+fk5CglJaVX23s8Hm3ZsoW2D8CNN96oPXv2qKyszH8UFBToM5/5jMrKyjRp0iTaeQgtWLDgvCXqhw4dUlZWliT+Xg+l1tZWWa29P5psNpt/aS9tPTz60675+fkKDw/vdU11dbX27t07+LYf1PTXINaztPfRRx819u/fb6xcudKIjo42jh8/bnZpQe3LX/6y4XQ6jVdffdWorq72H62trf5rfvzjHxtOp9N49tlnjT179hh33HEHy/KGwLmraQyDdh5KO3bsMMLCwowf/ehHxuHDh40nn3zSiIqKMp544gn/NbT30Pjc5z5npKen+5f2Pvvss0ZiYqLxr//6r/5raOuBaW5uNkpLS43S0lJDkvHggw8apaWl/i0t+tOuK1asMDIyMoyXXnrJ2LVrl3HDDTewtHewfvWrXxlZWVmG3W43Zs2a5V9+ioGT1Ofx2GOP+a/x+XzG9773PSMlJcVwOBzGtddea+zZs8e8oseID4YR2nlo/eUvfzHy8vIMh8NhTJkyxXj44Yd7vU57D42mpibj/vvvNyZOnGhEREQYkyZNMtasWWO43W7/NbT1wLzyyit9/vv8uc99zjCM/rVrW1ubce+99xoJCQlGZGSk8eEPf9goLy8fdG0WwzCMwfWtAAAADFxIzhkBAACjB2EEAACYijACAABMRRgBAACmIowAAABTEUYAAICpCCMAAMBUhBEAAGAqwggAADAVYQQAAJiKMAIAAExFGAEAAKb6/wHJRzXQob1GqQAAAABJRU5ErkJggg==\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"plt.plot(losses)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"After training the model and observing the decrease of the loss function, we evaluate its performance on both the training and test data. We will calculate the accuracy and display the final loss on the training data. In our case, the weights $\\\\mathbf{w}$ and the accuracies will be the values against which we compare the SVM implementation in Cairo with Orion.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"###  **Evaluate model on training data** \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Accuracy: 0.99\\n\",\n      \"Final loss: 0.4089273002134721\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"def predict(X, w):\\n\",\n    \"    return np.sign(np.dot(X, w))\\n\",\n    \"\\n\",\n    \"predictions = predict(X_train, w)\\n\",\n    \"final_loss = loss_function(w, X_train, y_train,C)\\n\",\n    \"\\n\",\n    \"print(\\\"Accuracy: {}\\\".format((predictions == y_train).mean()))\\n\",\n    \"print(\\\"Final loss: {}\\\".format(final_loss))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"###  **Evaluate model on test data**\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Accuracy: 0.98\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"predictions = predict(X_test, w)\\n\",\n    \"\\n\",\n    \"print(\\\"Accuracy: {}\\\".format((predictions == y_test).mean()))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.36715632, -0.35873007,  0.12536368])\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"w\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Next, we will visualize the obtained hyperplane, determined by $\\\\mathbf{w} = (0.367, -0.358, 0.125)$ and the way it separates the classes in the test data.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<matplotlib.lines.Line2D at 0x145e11cf0>]\"\n      ]\n     },\n     \"execution_count\": 11,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAiIAAAGdCAYAAAAvwBgXAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy88F64QAAAACXBIWXMAAA9hAAAPYQGoP6dpAABanklEQVR4nO3dd3hU1dbH8e8kgdBDR5EIKLYkdJByKRYEuV7FdlW8lpvQBaRcREVfC4pRUaT3JICIoCBVegcDSO8ioBRFmmACCIFMzvvHJvQkkzJzZia/z/PMI5k5OWdlhDkra++9tsOyLAsRERERGwTYHYCIiIjkXkpERERExDZKRERERMQ2SkRERETENkpERERExDZKRERERMQ2SkRERETENkpERERExDZBdgeQnpSUFA4dOkThwoVxOBx2hyMiIiIusCyLU6dOUbZsWQIC0q95eHUicujQIUJDQ+0OQ0RERLLg4MGDlCtXLt1jvDoRKVy4MGB+kCJFitgcjYiIiLgiMTGR0NDQS/fx9Hh1IpI6HFOkSBElIiIiIj7GlWkVmqwqIiIitlEiIiIiIrZRIiIiIiK2USIiIiIitlEiIiIiIrZRIiIiIiK2USIiIiIitvHqPiIifuPCBTh6FPLkgVKlQFsWiIgAqoiIuNfvv8P//gclS0K5clCmDNx1FwwaBOfP2x2diIjtVBERcZft26FxY/jrL3A6Lz+/Zw906QLffQezZ0P+/LaFKCJiN1VERNzh/Hlo3vz6JATAssxj+XJTLRERycWUiIi4w7RpcPDg9UnIlVJSICYGTp70WFgiIt5GiYiIO3zzDQS48M/r/HmYOdP98YiIeCnNERFxh2PHTMUjIwEB8Oef7o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vRpNWcLCDBt64cM8WxcItkwdepUOnTowJEjRwgICKBr16588MEHFHClQV8u5xWJyKlTp9i/f/9Vz0VGRnL33Xfz+uuvE+HCbpxKRER8gKu76wYFwe+/Q+nS7o9JJBuOHTtG586dmTRpEgB33303cXFx1K1b1+bIfIdX7L5buHDh65KNggULUqJECZeSEBG/lpQE331nqghnzpg9ViIjwReXuI8bd3WTsrSkpJg5JK++6pm4RDLJsiy++eYbOnXqxPHjxwkMDKRnz56888475MuXz+7w/JY6q4p42sqV8OSTpjNoYKC5QQcGQv/+0KIFjB/vW8t1f/vNdH/NSGCgOVbECx0+fJhXXnmFqVOnAlC5cmXi4uKoWbOmzZH5P48mIkuXLvXk5US8z8aN8NBDZudduDynIrWaMGsWPPGE2V8mgzlUXqNwYdf2d0lJMceKeBHLsvjqq6/o0qULJ06cICgoiLfeeotevXqRV5OrPUKb3ol4Uq9eZplrWstZnU6zqducOZ6NKztatMh4WAbMz9aihfvjEXHR77//zmOPPcaLL77IiRMnqF69OuvWreO9995TEuJBSkREPGX/frOnSlorS1IFBsLQoZ6JKSc0awa33ZZ+BScoCBo08M05MOJ3LMsiNjaW8PBwZs2aRd68efnwww9Zs2bNpXYT4jmaIyLiKTt2uDaXwumEzZvdH09OCQiAadOgUSM4ffr66khgIJQp4/ruuiJudODAAdq2bcu8efMAqF27NnFxcYSHh9scWe6lioiIp2RmzoevzA9JVbkyrFsHLVtevVNw/vzQtq15TZ2SxUaWZTFixAgiIiKYN28ewcHBfPLJJ8THxysJsZkqIiKeUqOGuUlfuJD+cUFBprrga26/3Szl7d8fdu0ylZKwME1QFdv9+uuvtG7dmsWLFwNQv359YmNjueuuu2yOTEAVERHPKVkSnn3WJBrpSU42O/P6quLFzYZ+deooCRFbpaSkMGjQICIiIli8eDH58+enf//+LF++XEmIF1FFRMSToqNhwQL488+0V5q0b29u5CKSZbt37yYqKoqVK1cC0LhxY2JiYrj99tttjkyupYqIiCeVKwerV0P9+ubrgAAzXONwQIEC8O672o9FJB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IjY2loYNG9ocmdhFFREREfGI6dOnExYWxrhx43A4HHTr1o3NmzcrCcnlVBERERG3On78OJ07d2bixIkA3H333cTGxlKvXj2bIxNvoIqIiIi4zbfffktYWBgTJ04kICCAN954g40bNyoJkUtUERERkRx35MgROnbsyJQpUwCIiIggLi6OWrVq2RyZeBtVREREJMdYlsVXX31FWFgYU6ZMISgoiHfeeYd169YpCZEbUkVERERyxKFDh2jfvj0zZ84EoFq1asTFxVGtWjV7AxOvpoqIiIhki2VZxMXFERYWxsyZM8mTJw+9e/fmxx9/VBIiGVJFREREsuzAgQO0bduWefPmAVC7dm1iY2OJiIiwOTLxFaqIiIhIplmWxciRI4mIiGDevHkEBwfzySefEB8fryREMkUVERERyZRff/2V1q1bs3jxYgDq1atHbGwsd999t82RiS9SRURERFySkpLC4MGDqVy5MosXLyZ//vx88cUXrFixQkmIZJkqIiIikqHdu3fTqlUrVqxYAUCjRo2IiYmhUqVKNkcmvk4VERERSZPT6aRfv35UrVqVFStWULBgQQYPHsySJUuUhEiOUEVERERuaOfOnURFRbF69WoAmjRpwqhRo6hQoYK9gYlfUUVERESukpyczMcff0z16tVZvXo1hQsXZuTIkcyfP19JiOQ4tyYiw4YNo0qVKhQpUoQiRYpQr1495syZ485LiohINmzdupW6devy5ptvkpSUxMMPP8z27dtp06YNDofD7vDED7k1ESlXrhwff/wx69atY926dTzwwAO0aNGC7du3u/OyIiKSSRcuXKB3797UrFmT9evXU7RoUcaMGcPs2bMJDQ21OzzxYw7LsixPXrB48eL07duXVq1aZXhsYmIiISEhJCQkUKRIEQ9EJyKS+2zcuJHIyEg2b94MwGOPPcawYcMoW7aszZGJr8rM/dtjk1WdTifffvstZ86coV69ejc8JikpiaSkpEtfJyYmeio8EZFcJykpiQ8//JDo6GicTifFixdn0KBBtGzZUsMw4jFuT0S2bt1KvXr1OHfuHIUKFWLq1KmEhYXd8Njo6Gjef/99d4ckIpLr/fjjj0RFRV0aKn/66acZPHgwZcqUsTkyyW3cPjRz/vx5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X3+lTZs2LFq0CIB69eoRGxvL3XffbXNkIiLir1QREVJSUhgyZAiVK1dm0aJF5M+fn379+rFixQolISIi4laqiORye/bsoVWrVixfvhyARo0aERMTQ6VKlWyOTEREcgNVRHIpp9NJv379qFKlCsuXL6dgwYIMGjSIJUuWKAkRERGPUUUkF9q5cydRUVGsXr0agAcffJBRo0ZRsWJFmyMTEZHcRhWRXCQ5OZlPPvmE6tWrs3r1agoXLszIkSNZsGCBkhAREbGFKiK5xLZt24iMjGTdunUAPPzww4wcOZLQ0FCbIxMRkdxMFRE/d+HCBT744ANq1KjBunXrKFq0KGPGjGH27NlKQkRExHaqiPixjRs3EhkZyebNmwFo0aIFw4YN4+abb7Y5MhEREUMVET+UlJTE//3f/3HvvfeyefNmSpQowVdffcXUqVOVhIiIiFdRRcTPrF27lsjISLZv3w7A008/zeDBgylTpozNkYmIiFxPFRE/ce7cOd544w3q1q3L9u3bKV26NN9++y3ffvutkhAREfFaqoj4gfj4eKKioti1axcAzz//PAMGDKBkyZI2RyYiIpI+VUR82N9//0337t1p0KABu3bt4uabb2b69Ol89dVXSkJERMQnqCLio5YtW0arVq3Yu3cvAP/973/p168fxYoVszkyERER16ki4mNOnz5Np06duO+++9i7dy/lypVj9uzZxMXFKQkRERGfo4qID1m0aBGtW7dm3759ALRt25ZPP/2UkJAQewMTERHJIiUiPiAhIYGePXsycuRIACpUqMDo0aN58MEHbY5MRNzPAs5hCtjBNscikvM0NOPl5syZQ0RExKUkpGPHjmzdulVJiIjfSwA+BSoABYB8QHUgFrhgX1giOUwVES918uRJunXrxtixYwG4/fbbiYmJoXHjxjZHJiLu9zvQGPgVSLni+S1AK+BrYAaQ3/OhieQwVUS80IwZMwgPD2fs2LE4HA66devGli1blISI5AoW8Ciwn6uTEK74ejHQxZNBibiNEhEvcvz4cZ5//nlatGjBH3/8wV133cXKlSvp168fBQoUsDs8EfGIZcBGIDmdY1KAOOCoRyIScSclIl5i8uTJhIWF8fXXXxMQEEDPnj3ZuHEj9ev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ATJ05w4MABnE7npUpCpUqVKFSokDsvnWPWrVtHZGQk27ZtA+Cpp55iyJAhlClTxubIREREfJ9bE5F33nmHsWPHXvo6dYfZJUuWcN9997nz0tl27tw53n//ffr27YvT6aRUqVIMHTqUp59+2u7QRERE/IbDsizL7iDSkpiYSEhICAkJCRQpUiTjb8ghq1atIioqip9++gmAli1bMnDgwFw3JCUiIpIVmbl/e9XyXbv9/fff/O9//+Mf//gHP/30EzfddBNTp05lwoQJSkJERETcQLvvXrRixQqioqLYs2cPAC+//DJffPEFxYoVszkyERER/5XrKyKnT5+mc+fONGrUiD179lCuXDm+//57xowZoyRERETEzXJ1RWTRokW0bt2affv2AdC6dWs+++wzQkJC7A1MREQkl8iVFZGEhATatWtHkyZN2LdvH+XLl2fBggWMGjVKSYiIiIgH5cpEZMyYMYwcORKAV155ha1bt9KkSROboxIREcl9cuXQTMeOHYmPj6dDhw5e389ERETEn+XKRCQoKIhJkybZHYaIiEiulyuHZkRERMQ7KBERERER2ygREREREdsoERERERHbKBERERER2ygREREREdsoERERERHbKBERERER2ygREREREdsoERERERHbKBERERER2ygREREREdsoERERERHbePXuu5ZlAZCYmGhzJCIiIuKq1Pt26n08PV6diJw6dQqA0NBQmyMRERGRzDp16hQhISHpHuOwXElXbJKSksKhQ4coXLgwDofD7nBsk5iYSGhoKAcPHqRIkSJ2h+Mz9L5ljd63rNH7ljV637LG2983y7I4deoUZcuWJSAg/VkgXl0RCQgIoFy5cnaH4TWKFCnilX/hvJ3et6zR+5Y1et+yRu9b1njz+5ZRJSSVJquKiIiIbZSIiIiIiG2UiPiA4OBg3n33XYKDg+0OxafofcsavW9Zo/cta/S+ZY0/vW9ePVlVRERE/JsqIiIiImIbJSIiIiJiGyUiIiIiYhslIiIiImIbJSI+pk+fPtSvX58CBQpQtGhRu8PxWkOHDqVixYrky5ePmjVrsmLFCrtD8nrLly/n0UcfpWzZsjgcDqZNm2Z3SF4vOjqa2rVrU7hwYUqXLs3jjz/Orl277A7LJwwbNowqVapcashVr1495syZY3dYPiU6OhqHw0HXrl3tDiVblIj4mPPnz/Pvf/+bDh062B2K15o0aRJdu3blrbfeYuPGjTRs2JDmzZtz4MABu0PzamfOnKFq1aoMHjzY7lB8xrJly+jYsSOrV69mwYIFJCcn07RpU86cOWN3aF6vXLlyfPzxx6xbt45169bxwAMP0KJFC7Zv3253aD5h7dq1jBw5kipVqtgdSrZp+a6PGjNmDF27duWvv/6yOxSvU6dOHWrUqMGwYcMuPXfPPffw+OOPEx0dbWNkvsPhcDB16lQef/xxu0PxKceOHaN06dIsW7aMRo0a2R2OzylevDh9+/alVatWdofi1U6fPk2NGjUYOnQoH374IdWqVaN///52h5VlqoiIXzl//jzr16+nadOmVz3ftGlT4uPjbYpKcouEhATA3FDFdU6nk4kTJ3LmzBnq1atndzher2PHjjzyyCM0adLE7lByhFdveieSWcePH8fpdFKmTJmrni9TpgyHDx+2KSrJDSzLonv37jRo0ICIiAi7w/EJW7dupV69epw7d45ChQoxdepUwsLC7A7Lq02cOJENGzawdu1au0PJMaqIeIH33nsPh8OR7mPdunV2h+lTHA7HVV9blnXdcyI5qVOnTmzZsoWvv/7a7lB8xl133cWmTZtYvXo1HTp04OWXX2bHjh12h+W1Dh48SJcuXRg/fjz58uWzO5wco4qIF+jUqRPPPfdcusdUqFDBM8H4uJIlSxIYGHhd9ePo0aPXVUlEckrnzp2ZMWMGy5cvp1y5cnaH4zPy5s1LpUqVAKhVqxZr165lwIABjBgxwubIvNP69es5evQoNWvWvPSc0+lk+fLlDB48mKSkJAIDA22MMGuUiHiBkiVLUrJkSbvD8At58+alZs2aLFiwgCeeeOLS8wsWLKBFixY2Rib+yLIsOnfuzNSpU1m6dCkVK1a0OySfZlkWSUlJdofhtR588EG2bt161XORkZHcfffdvP766z6ZhIASEZ9z4MABTpw4wYEDB3A6nWzatAmASpUqUahQIXuD8xLdu3fnxRdfpFatWtSrV4+RI0dy4MAB2rdvb3doXu306dPs2bPn0te//vormzZtonjx4tx66602Rua9OnbsyIQJE5g+fTqFCxe+VIkLCQkhf/78Nkfn3Xr16kXz5s0JDQ3l1KlTTJw4kaVLlzJ37ly7Q/NahQsXvm7+UcGCBSlRooRvz0uyxKe8/PLLFnDdY8mSJXaH5lWGDBlilS9f3sqbN69Vo0YNa9myZXaH5PWWLFlyw79bL7/8st2hea0bvV+AFRcXZ3doXi8qKurSv9FSpUpZDz74oDV//ny7w/I5jRs3trp06WJ3GNmiPiIiIiJiG62aEREREdsoERERERHbKBERERER2ygREREREdsoERERERHbKBERERER2ygREREREdsoERERERHbKBERERER2ygREREREdsoERERERHbKBERERER2/w/oW/GyjU/nhcAAAAASUVORK5CYII=\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, s=50, cmap='autumn')\\n\",\n    \"\\n\",\n    \"x_plot = np.linspace(X_test[:, 0].min() - 1, X_test[:, 0].max() + 1, 100)\\n\",\n    \"y_plot = (-w[0] / w[1]) * x_plot - (w[2]/w[1]) #\\n\",\n    \"plt.plot(x_plot, y_plot, 'k-')\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The equation of the line obtained is $\\\\mathbf{Y} = 1.023\\\\mathbf{X} + 0.349$\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## **Convert your model to Cairo**\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### **Generating Cairo files**\\n\",\n    \"\\n\",\n    \"Now let's generate Cairo files for each tensor in the object.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def decimal_to_fp16x16(num):\\n\",\n    \"\\n\",\n    \"    whole_num = int(num)\\n\",\n    \"    fractional_part = int((num - whole_num) * 65536)\\n\",\n    \"    fp_number = (whole_num << 16) + fractional_part\\n\",\n    \"    return fp_number\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import os\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"os.makedirs(\\\"src/generated\\\", exist_ok=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tensor_name = [\\\"X_train\\\", \\\"Y_train\\\", \\\"X_test\\\", \\\"Y_test\\\"]\\n\",\n    \"\\n\",\n    \"def generate_cairo_files(data, name):\\n\",\n    \"\\n\",\n    \"    with open(os.path.join('src', 'generated', f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"        f.write(\\n\",\n    \"            \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n    \"            \\\"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\\\n\\\" +\\n\",\n    \"            \\\"use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\\\\n\\\" +\\n\",\n    \"            \\\"\\\\n\\\" + f\\\"fn {name}() -> Tensor<FP16x16>\\\" + \\\"{\\\\n\\\\n\\\" + \\n\",\n    \"            \\\"let mut shape = ArrayTrait::new();\\\\n\\\"\\n\",\n    \"        )\\n\",\n    \"        for dim in data.shape:\\n\",\n    \"            f.write(f\\\"shape.append({dim});\\\\n\\\")\\n\",\n    \"    \\n\",\n    \"        f.write(\\\"let mut data = ArrayTrait::new();\\\")\\n\",\n    \"        for val in np.nditer(data.flatten()):\\n\",\n    \"            f.write(f\\\"data.append(FixedTrait::new({abs(int(decimal_to_fp16x16(val)))}, {str(val < 0).lower()}));\\\\n\\\")\\n\",\n    \"        f.write(\\n\",\n    \"            \\\"let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\\\\n\\\" +\\n\",\n    \"            \\\"return tensor;\\\\n}\\\"\\n\",\n    \"        )\\n\",\n    \"\\n\",\n    \"with open(f\\\"src/generated.cairo\\\", \\\"w\\\") as f:\\n\",\n    \"    for n in tensor_name:\\n\",\n    \"        f.write(f\\\"mod {n};\\\\n\\\")\\n\",\n    \"\\n\",\n    \"generate_cairo_files(X_train, \\\"X_train\\\")\\n\",\n    \"generate_cairo_files(X_test, \\\"X_test\\\")\\n\",\n    \"generate_cairo_files(y_train, \\\"Y_train\\\")\\n\",\n    \"generate_cairo_files(y_test, \\\"Y_test\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \" **Convert hyperparameters to FP16x16**\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"655\\n\",\n      \"65536\\n\",\n      \"6553600\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"print(decimal_to_fp16x16(learning_rate))\\n\",\n    \"print(decimal_to_fp16x16(C))\\n\",\n    \"print(decimal_to_fp16x16(num_epochs))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \" **Get an estimate for the initial and final loss value, and final weights in FP16x16**  \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Initial loss: 65536\\n\",\n      \"Final loss: 26799\\n\",\n      \"Weights: [ 24061 -23509   8215]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"w = np.array([decimal_to_fp16x16(w[0]),\\n\",\n    \"decimal_to_fp16x16(w[1]),\\n\",\n    \"decimal_to_fp16x16(w[2])])\\n\",\n    \"\\n\",\n    \"print(\\\"Initial loss: {}\\\".format(decimal_to_fp16x16(losses[0])))\\n\",\n    \"print(\\\"Final loss: {}\\\".format(decimal_to_fp16x16(final_loss)))\\n\",\n    \"print(\\\"Weights: {}\\\".format(w))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For the implementation of SVM in Cairo with Orion, please visit the Convert your model section within the [Verifiable Support Vector Machine tutorial][def]\\n\",\n    \"\\n\",\n    \"[def]: ../tutorial/VerifiableSupportVectorMachineTutorial.md\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"cairo\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.9\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/generated.cairo",
        "content": "mod X_train;\nmod Y_train;\nmod X_test;\nmod Y_test;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/generated/X_test.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn X_test() -> Tensor<FP16x16>{\n\nlet mut shape = ArrayTrait::new();\nshape.append(50);\nshape.append(3);\nlet mut data = ArrayTrait::new();data.append(FixedTrait::new(87946, false));\ndata.append(FixedTrait::new(38900, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(34695, false));\ndata.append(FixedTrait::new(249556, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(159279, false));\ndata.append(FixedTrait::new(4166, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(83319, false));\ndata.append(FixedTrait::new(124029, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(154108, false));\ndata.append(FixedTrait::new(54263, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(81434, false));\ndata.append(FixedTrait::new(295173, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(101339, false));\ndata.append(FixedTrait::new(276101, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(51730, false));\ndata.append(FixedTrait::new(284261, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(130047, false));\ndata.append(FixedTrait::new(32083, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(112357, false));\ndata.append(FixedTrait::new(329332, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(103102, false));\ndata.append(FixedTrait::new(31715, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(111245, false));\ndata.append(FixedTrait::new(56762, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(77993, false));\ndata.append(FixedTrait::new(309836, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(180005, false));\ndata.append(FixedTrait::new(101281, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(62872, false));\ndata.append(FixedTrait::new(298895, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(36406, true));\ndata.append(FixedTrait::new(307754, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(150385, false));\ndata.append(FixedTrait::new(50193, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(106162, false));\ndata.append(FixedTrait::new(4433, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(79801, false));\ndata.append(FixedTrait::new(255125, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(95363, false));\ndata.append(FixedTrait::new(1913, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(121, true));\ndata.append(FixedTrait::new(300250, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(14718, false));\ndata.append(FixedTrait::new(312625, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(89573, false));\ndata.append(FixedTrait::new(41613, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(30116, false));\ndata.append(FixedTrait::new(357159, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(159865, false));\ndata.append(FixedTrait::new(4752, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(61297, false));\ndata.append(FixedTrait::new(349424, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(116464, false));\ndata.append(FixedTrait::new(77761, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(70534, false));\ndata.append(FixedTrait::new(307023, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(155183, false));\ndata.append(FixedTrait::new(36188, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(133737, false));\ndata.append(FixedTrait::new(29808, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(145701, false));\ndata.append(FixedTrait::new(54969, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(105613, false));\ndata.append(FixedTrait::new(119503, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(138536, false));\ndata.append(FixedTrait::new(81751, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(89231, false));\ndata.append(FixedTrait::new(89547, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(37538, false));\ndata.append(FixedTrait::new(267914, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(211603, false));\ndata.append(FixedTrait::new(74168, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(157689, false));\ndata.append(FixedTrait::new(319191, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(145953, false));\ndata.append(FixedTrait::new(82769, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(69644, false));\ndata.append(FixedTrait::new(339237, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(108783, false));\ndata.append(FixedTrait::new(233497, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(120774, false));\ndata.append(FixedTrait::new(4764, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(38978, false));\ndata.append(FixedTrait::new(308651, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(122543, false));\ndata.append(FixedTrait::new(7073, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(111206, false));\ndata.append(FixedTrait::new(49473, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(130347, false));\ndata.append(FixedTrait::new(98944, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(161886, false));\ndata.append(FixedTrait::new(86147, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(86653, false));\ndata.append(FixedTrait::new(273862, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(86507, false));\ndata.append(FixedTrait::new(92030, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(124252, false));\ndata.append(FixedTrait::new(339830, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(113347, false));\ndata.append(FixedTrait::new(75189, false));\ndata.append(FixedTrait::new(65536, false));\nlet tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\nreturn tensor;\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/generated/X_train.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn X_train() -> Tensor<FP16x16>{\n\nlet mut shape = ArrayTrait::new();\nshape.append(100);\nshape.append(3);\nlet mut data = ArrayTrait::new();\ndata.append(FixedTrait::new(165613, false));\ndata.append(FixedTrait::new(40488, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(101228, false));\ndata.append(FixedTrait::new(275957, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65780, false));\ndata.append(FixedTrait::new(274692, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(82291, false));\ndata.append(FixedTrait::new(221645, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(122469, false));\ndata.append(FixedTrait::new(62659, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(83856, false));\ndata.append(FixedTrait::new(69330, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(70073, false));\ndata.append(FixedTrait::new(296922, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(70957, false));\ndata.append(FixedTrait::new(266254, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(193459, false));\ndata.append(FixedTrait::new(22565, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(50300, false));\ndata.append(FixedTrait::new(288200, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(29071, false));\ndata.append(FixedTrait::new(204164, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(140848, false));\ndata.append(FixedTrait::new(67959, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(165042, false));\ndata.append(FixedTrait::new(91210, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(133149, false));\ndata.append(FixedTrait::new(12897, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(172026, false));\ndata.append(FixedTrait::new(62271, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(519, false));\ndata.append(FixedTrait::new(273687, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(3112, true));\ndata.append(FixedTrait::new(358760, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(130822, false));\ndata.append(FixedTrait::new(32740, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(78697, false));\ndata.append(FixedTrait::new(39431, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(155270, false));\ndata.append(FixedTrait::new(52083, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(122730, false));\ndata.append(FixedTrait::new(273985, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(59922, false));\ndata.append(FixedTrait::new(298198, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(39038, false));\ndata.append(FixedTrait::new(267789, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(109040, false));\ndata.append(FixedTrait::new(43456, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(109628, false));\ndata.append(FixedTrait::new(43207, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(18165, false));\ndata.append(FixedTrait::new(317474, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(161818, false));\ndata.append(FixedTrait::new(110019, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(151455, false));\ndata.append(FixedTrait::new(85446, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(54844, false));\ndata.append(FixedTrait::new(140008, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(129348, false));\ndata.append(FixedTrait::new(103533, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(134024, false));\ndata.append(FixedTrait::new(73738, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(37464, false));\ndata.append(FixedTrait::new(283304, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(43940, false));\ndata.append(FixedTrait::new(264827, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(109385, false));\ndata.append(FixedTrait::new(28598, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(219755, false));\ndata.append(FixedTrait::new(111383, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(120177, false));\ndata.append(FixedTrait::new(49416, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(66596, false));\ndata.append(FixedTrait::new(293946, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(91267, false));\ndata.append(FixedTrait::new(60880, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(72170, false));\ndata.append(FixedTrait::new(320456, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(223533, false));\ndata.append(FixedTrait::new(57167, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(138029, false));\ndata.append(FixedTrait::new(229056, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(102711, false));\ndata.append(FixedTrait::new(1167, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(58556, false));\ndata.append(FixedTrait::new(66252, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(94025, false));\ndata.append(FixedTrait::new(85630, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(5342, false));\ndata.append(FixedTrait::new(299330, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(97971, false));\ndata.append(FixedTrait::new(252869, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(46869, false));\ndata.append(FixedTrait::new(354769, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(137416, false));\ndata.append(FixedTrait::new(243624, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(139593, false));\ndata.append(FixedTrait::new(340269, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(110332, false));\ndata.append(FixedTrait::new(274978, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(48127, false));\ndata.append(FixedTrait::new(330121, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(17851, false));\ndata.append(FixedTrait::new(358479, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(155294, false));\ndata.append(FixedTrait::new(62306, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(97104, false));\ndata.append(FixedTrait::new(45224, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(28769, false));\ndata.append(FixedTrait::new(297266, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(47716, false));\ndata.append(FixedTrait::new(252661, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(107481, false));\ndata.append(FixedTrait::new(119242, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(28304, false));\ndata.append(FixedTrait::new(284095, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(36669, false));\ndata.append(FixedTrait::new(276169, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(93592, false));\ndata.append(FixedTrait::new(106453, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(140275, false));\ndata.append(FixedTrait::new(46272, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(170483, false));\ndata.append(FixedTrait::new(71302, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(32006, false));\ndata.append(FixedTrait::new(214172, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(129468, false));\ndata.append(FixedTrait::new(47119, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(178995, false));\ndata.append(FixedTrait::new(16364, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(64393, false));\ndata.append(FixedTrait::new(352276, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(137416, false));\ndata.append(FixedTrait::new(317680, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(76291, false));\ndata.append(FixedTrait::new(248468, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(22750, false));\ndata.append(FixedTrait::new(226215, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(92649, false));\ndata.append(FixedTrait::new(287124, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(74107, false));\ndata.append(FixedTrait::new(61316, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(53442, false));\ndata.append(FixedTrait::new(313606, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(14023, false));\ndata.append(FixedTrait::new(320171, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(170903, false));\ndata.append(FixedTrait::new(71362, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(29739, false));\ndata.append(FixedTrait::new(259291, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(122501, false));\ndata.append(FixedTrait::new(356602, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(118987, false));\ndata.append(FixedTrait::new(73380, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(116781, false));\ndata.append(FixedTrait::new(59516, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(43895, false));\ndata.append(FixedTrait::new(235628, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(33706, false));\ndata.append(FixedTrait::new(303257, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(168385, false));\ndata.append(FixedTrait::new(33229, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(48750, false));\ndata.append(FixedTrait::new(270165, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(93906, false));\ndata.append(FixedTrait::new(286837, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(78782, false));\ndata.append(FixedTrait::new(238822, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(72450, false));\ndata.append(FixedTrait::new(82830, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(181409, false));\ndata.append(FixedTrait::new(71291, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(177934, false));\ndata.append(FixedTrait::new(84595, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(225287, false));\ndata.append(FixedTrait::new(17147, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(88127, false));\ndata.append(FixedTrait::new(318315, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(153231, false));\ndata.append(FixedTrait::new(224865, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(79552, false));\ndata.append(FixedTrait::new(239072, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(21877, false));\ndata.append(FixedTrait::new(323515, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(75708, false));\ndata.append(FixedTrait::new(334208, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(68971, false));\ndata.append(FixedTrait::new(297859, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(97556, false));\ndata.append(FixedTrait::new(42705, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(109996, false));\ndata.append(FixedTrait::new(39914, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(28087, false));\ndata.append(FixedTrait::new(325975, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(12237, false));\ndata.append(FixedTrait::new(263902, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(90416, false));\ndata.append(FixedTrait::new(298075, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(115110, false));\ndata.append(FixedTrait::new(134701, false));\ndata.append(FixedTrait::new(65536, false));\nlet tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\nreturn tensor;\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/generated/Y_test.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn Y_test() -> Tensor<FP16x16>{\n\nlet mut shape = ArrayTrait::new();\nshape.append(50);\nlet mut data = ArrayTrait::new();data.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\nlet tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\nreturn tensor;\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/generated/Y_train.cairo",
        "content": "use array::ArrayTrait;\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\n\nfn Y_train() -> Tensor<FP16x16>{\n\nlet mut shape = ArrayTrait::new();\nshape.append(100);\nlet mut data = ArrayTrait::new();data.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, false));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, true));\ndata.append(FixedTrait::new(65536, false));\nlet tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span());\nreturn tensor;\n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/helper.cairo",
        "content": "use debug::PrintTrait;\nuse traits::TryInto;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub,\n    FP16x16TensorDiv\n};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16Print, FP16x16IntoI32, FP16x16PartialOrd,\n    FP16x16PartialEq\n};\n\n// Calculates the machine learning model's loss.\nfn calculate_loss(\n    w: @Tensor<FP16x16>,\n    x_train: @Tensor<FP16x16>,\n    y_train: @Tensor<FP16x16>,\n    c: @Tensor<FP16x16>,\n    one_tensor: @Tensor<FP16x16>,\n    half_tensor: @Tensor<FP16x16>,\n    y_train_len: u32\n) -> FP16x16 {\n    let tensor_size = FixedTrait::new_unscaled(y_train_len, false);\n\n    let pre_cumsum = *one_tensor - *y_train * x_train.matmul(w);\n    let cumsum = pre_cumsum.cumsum(0, Option::None(()), Option::None(()));\n    let sum = cumsum.data[pre_cumsum.data.len() - 1];\n    let mean = FP16x16Div::div(*sum, tensor_size);\n\n    let mean_tensor = TensorTrait::new(\n        shape: array![1].span(), data: array![mean].span(),\n    );\n\n    let regularization_term = *half_tensor * (w.matmul(w));\n    let loss_tensor = mean_tensor + *c * regularization_term;\n\n    loss_tensor.at(array![0].span())\n}\n\n// Calculates the gradient for the machine learning model\nfn calculate_gradient(\n    w: @Tensor<FP16x16>,\n    x_train: @Tensor<FP16x16>,\n    y_train: @Tensor<FP16x16>,\n    c: Tensor<FP16x16>,\n    one_tensor: @Tensor<FP16x16>,\n    neg_one_tensor: @Tensor<FP16x16>,\n    y_train_len: u32\n) -> Tensor<FP16x16> {\n    let tensor_size = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FixedTrait::new_unscaled(y_train_len, false)].span(),\n    );\n\n    let mask = (*y_train * x_train.matmul(w));\n    let mask = less(@mask, one_tensor);\n\n    let gradient = (((mask * *y_train).matmul(x_train) / tensor_size) * *neg_one_tensor) + (c * *w);\n\n    gradient\n}\n\n// Calculates the accuracy of the machine learning model's predictions.\nfn accuracy(y: @Tensor<FP16x16>, z: @Tensor<FP16x16>) -> FP16x16 {\n    let (mut left, mut right) = (y, z);\n\n    let mut right_data = *right.data;\n    let mut left_data = *left.data;\n    let mut counter = 0;\n\n    loop {\n        match right_data.pop_front() {\n            Option::Some(item) => {\n                let right_current_index = item;\n                let left_current_index = left_data.pop_front();\n                let (y_value, z_value) = (left_current_index.unwrap(), right_current_index);\n\n                if *y_value == *z_value {\n                    counter += 1;\n                };\n            },\n            Option::None(_) => {\n                break;\n            }\n        };\n    };\n\n    (FixedTrait::new_unscaled(counter, false) / FixedTrait::new_unscaled((*y.data).len(), false))\n        * FixedTrait::new_unscaled(100, false)\n}\n\n// Returns the truth value of (x < y) element-wise.\nfn less(y: @Tensor<FP16x16>, z: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut data_result = ArrayTrait::<FP16x16>::new();\n    let mut data_result2 = ArrayTrait::<FP16x16>::new();\n    let (mut smaller, mut bigger, retains_input_order) = if (*y.data).len() < (*z.data).len() {\n        (y, z, true)\n    } else {\n        (z, y, false)\n    };\n\n    let mut bigger_data = *bigger.data;\n    let mut smaller_data = *smaller.data;\n    let mut smaller_index = 0;\n\n    loop {\n        match bigger_data.pop_front() {\n            Option::Some(item) => {\n                let bigger_current_index = item;\n                let smaller_current_index = smaller_data[smaller_index];\n\n                let (y_value, z_value) = if retains_input_order {\n                    (smaller_current_index, bigger_current_index)\n                } else {\n                    (bigger_current_index, smaller_current_index)\n                };\n\n                if *y_value < *z_value {\n                    data_result.append(FixedTrait::ONE());\n                } else {\n                    data_result.append(FixedTrait::ZERO());\n                };\n\n                smaller_index = (1 + smaller_index) % smaller_data.len();\n            },\n            Option::None(_) => {\n                break;\n            }\n        };\n    };\n\n    return TensorTrait::<FP16x16>::new(*bigger.shape, data_result.span());\n}\n\n\n// Returns an element-wise indication of the sign of a number.\nfn sign(z: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut data_result = ArrayTrait::<FP16x16>::new();\n    let mut z_data = *z.data;\n\n    loop {\n        match z_data.pop_front() {\n            Option::Some(item) => {\n                let result = if *item.sign {\n                    FixedTrait::new(ONE, true)\n                } else {\n                    FixedTrait::new(ONE, false)\n                };\n                data_result.append(result);\n            },\n            Option::None(_) => {\n                break;\n            }\n        };\n    };\n\n    TensorTrait::<FP16x16>::new(*z.shape, data_result.span())\n}\n\n// Returns predictions using the machine learning model.\nfn pred(x: @Tensor<FP16x16>, w: @Tensor<FP16x16>) -> Tensor<FP16x16> {\n    sign(@(x.matmul(w)))\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/lib.cairo",
        "content": "mod generated;\nmod train;\nmod test;\nmod helper;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/test.cairo",
        "content": "use traits::TryInto;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub,\n    FP16x16TensorDiv\n};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16IntoI32, FP16x16PartialOrd,\n    FP16x16PartialEq\n};\n\nuse verifiable_support_vector_machine::{\n    generated::{X_train::X_train, Y_train::Y_train, X_test::X_test, Y_test::Y_test}, train::{train}\n};\n\nuse verifiable_support_vector_machine::{helper::{pred, accuracy}};\n\n#[test]\n#[available_gas(99999999999999999)]\nfn svm_test() {\n    let x_train = X_train();\n    let x_test = X_test();\n    let y_train = Y_train();\n    let y_test = Y_test();\n\n    let feature_size = *x_train.shape[1];\n\n    let mut zero_array = ArrayTrait::new();\n\n    let learning_rate = FixedTrait::new(655, false); // 655 is 0.01\n\n    // 50 %\n    let average_compare = FixedTrait::new_unscaled(50, false);\n\n    let mut i = 0_u32;\n    loop {\n        if i >= feature_size {\n            break ();\n        }\n        zero_array.append(FP16x16Impl::ZERO());\n        i += 1;\n    };\n\n    let initial_w = TensorTrait::new(\n        shape: array![feature_size].span(), data: zero_array.span()\n    );\n\n    let y_train_len = y_train.data.len();\n    let (final_w, initial_loss, final_loss) = train(\n        @x_train, @y_train, @initial_w, learning_rate, y_train_len, 100_u32\n    );\n\n    let final_y_pred = pred(@x_test, @final_w);\n    let average_pred = accuracy(@final_y_pred, @y_test);\n\n    let train_y_pred = pred(@x_train, @final_w);\n    let average_train = accuracy(@train_y_pred, @y_train);\n\n    assert(final_loss < initial_loss, 'No decrease in training loss');\n    assert(average_pred > average_compare, 'It is better to flip a coin');\n    assert(average_train > average_compare, 'It was not a good training');\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/basic/verifiable_support_vector_machine/src/train.cairo",
        "content": "use debug::PrintTrait;\nuse traits::TryInto;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub,\n    FP16x16TensorDiv\n};\nuse orion::numbers::{FixedTrait, FP16x16, FP16x16Impl};\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{\n    HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16Print, FP16x16IntoI32, FP16x16PartialOrd,\n    FP16x16PartialEq\n};\n\nuse verifiable_support_vector_machine::{helper::{calculate_loss, calculate_gradient}};\n\n// Performs a training step for each iteration during model training\nfn train_step(\n    x: @Tensor<FP16x16>,\n    y: @Tensor<FP16x16>,\n    w: @Tensor<FP16x16>,\n    learning_rate: FP16x16,\n    one_tensor: @Tensor<FP16x16>,\n    half_tensor: @Tensor<FP16x16>,\n    neg_one_tensor: @Tensor<FP16x16>,\n    y_train_len: u32,\n    iterations: u32,\n    index: u32\n) -> Tensor<FP16x16> {\n    let learning_rate_tensor = TensorTrait::new(\n        shape: array![1].span(), data: array![learning_rate].span()\n    );\n\n    let c = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FP16x16Impl::ONE()].span(),\n    );\n\n    let mut w_recursive = *w;\n\n    let gradient = calculate_gradient(\n        @w_recursive, x, y, c, one_tensor, neg_one_tensor, y_train_len\n    );\n\n    w_recursive = w_recursive - (learning_rate_tensor * gradient);\n\n    if index == iterations {\n        return w_recursive;\n    }\n\n    train_step(\n        x,\n        y,\n        @w_recursive,\n        learning_rate,\n        one_tensor,\n        half_tensor,\n        neg_one_tensor,\n        y_train_len,\n        iterations,\n        index + 1\n    )\n}\n\n// Trains the machine learning model.\nfn train(\n    x: @Tensor<FP16x16>,\n    y: @Tensor<FP16x16>,\n    init_w: @Tensor<FP16x16>,\n    learning_rate: FP16x16,\n    y_train_len: u32,\n    iterations: u32\n) -> (Tensor<FP16x16>, FP16x16, FP16x16) {\n    let iter_w = init_w;\n\n    'Iterations'.print();\n    iterations.print();\n\n    let c = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FP16x16Impl::ONE()].span(),\n    );\n\n    let one_tensor = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FP16x16Impl::ONE()].span(),\n    );\n\n    let half_tensor = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FixedTrait::new(HALF, false)].span(),\n    );\n\n    let neg_one_tensor = TensorTrait::new(\n        shape: array![1].span(),\n        data: array![FixedTrait::new(ONE, true)].span(),\n    );\n\n    let initial_loss = FixedTrait::<FP16x16>::ZERO();\n    let final_loss = FixedTrait::<FP16x16>::ZERO();\n\n    let initial_loss = calculate_loss(init_w, x, y, @c, @one_tensor, @half_tensor, y_train_len);\n\n    let iter_w = train_step(\n        x,\n        y,\n        init_w,\n        learning_rate,\n        @one_tensor,\n        @half_tensor,\n        @neg_one_tensor,\n        y_train_len,\n        iterations,\n        1\n    );\n\n    let final_loss = calculate_loss(@iter_w, x, y, @c, @one_tensor, @half_tensor, y_train_len);\n\n    (iter_w, initial_loss, final_loss)\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/Provable Linear Regression Solver (Linear Regression).ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"c4619365\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Provable Linear Regression Solver\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"4d401fa3\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<matplotlib.collections.PathCollection at 0x7f63f2d5ca10>\"\n      ]\n     },\n     \"execution_count\": 1,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAigAAAGdCAYAAAA44ojeAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAxY0lEQVR4nO3de3SU9b3v8c8kQhJoMhpSMhMNmE3RvWPYaHCjoFVQw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pSSMvAqk7gcQUlJSdFZZ50V625ETFZWVsz/R4Pg+G6si+/GuvhurMkq38tgIyc+LJIFAACWQ0ABAACWQ0CJobS0NFVWViotLS3WXcEp+G6si+/GuvhurClev5e4XCQLAAASGyMoAADAcggoAADAcggoAADAcggoAADAcggoFnHgwAHdeeedKigoUEZGhiZNmqTKykodP3481l1LesuXL9fMmTM1ZswYnX766bHuTlJ7/vnnVVBQoPT0dE2bNk2///3vY90lSNqyZYvKysqUl5cnm82mDRs2xLpLkFRTU6N/+Zd/UWZmpsaPH68bbrhBn3zySay7FTYCikX85S9/UU9Pj1544QXt2bNHzz77rH7xi1/okUceiXXXkt7x48d18803a+nSpbHuSlJ7/fXXVV5erkcffVQfffSRvv3tb6u0tFQHDx6MddeS3tGjRzV16lStXLky1l1BH5s3b9YPf/hDffjhh6qrq9PJkyc1b948HT16NNZdCwvbjC3s6aef1qpVq/Q///M/se4KJK1evVrl5eX68ssvY92VpHTRRRepuLhYq1at8l/7p3/6J91www2qqamJYc/Ql81m0/r163XDDTfEuis4xRdffKHx48dr8+bNuuyyy2LdnUExgmJhbrdb2dnZse4GEHPHjx/X7t27NW/evIDr8+bN07Zt22LUKyC+uN1uSYqb3xUCikXt379fP/vZz/SDH/wg1l0BYu5vf/ubvF6vcnNzA67n5uaqtbU1Rr0C4odhGFq2bJkuvfRSFRUVxbo7YSGgRFlVVZVsNtuAj127dgW8pqWlRSUlJbr55pt11113xajniW0o3wtiz2azBTw3DKPfNQD93XvvvfrTn/6k1157LdZdCdtpse5Aorv33nu1YMGCAducffbZ/n9uaWnR7NmzNWPGDP3yl7+Mcu+Sl9nvBbGVk5Oj1NTUfqMlbW1t/UZVAAS677779Jvf/EZbtmzRWWedFevuhI2AEmU5OTnKyckJq+3nn3+u2bNna9q0aXr55ZeVksIAV7SY+V4Qe6NHj9a0adNUV1enG2+80X+9rq5O119/fQx7BliXYRi67777tH79en3wwQcqKCiIdZdMIaBYREtLi2bNmqUJEyboP//zP/XFF1/47zkcjhj2DAcPHlR7e7sOHjwor9erhoYGSdK3vvUtfeMb34ht55LIsmXLdNttt+nCCy/0jzAePHiQdVoW0NnZqX379vmfNzc3q6GhQdnZ2ZowYUIMe5bcfvjDH2rt2rV68803lZmZ6R+BtNvtysjIiHHvwmDAEl5++WVDUtAHYmvx4sVBv5f3338/1l1LOj//+c+NiRMnGqNHjzaKi4uNzZs3x7pLMAzj/fffD/r/kcWLF8e6a0kt1G/Kyy+/HOuuhYU6KAAAwHJY5AAAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACyHgAIAACzn/wO5eISFlP4QaQAAAABJRU5ErkJggg==\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import matplotlib.pylab as plt\\n\",\n    \"from sklearn.metrics import r2_score\\n\",\n    \"import os\\n\",\n    \"\\n\",\n    \"N = 50\\n\",\n    \"noise = np.random.randn(N)+100\\n\",\n    \"x = np.random.randn(N)\\n\",\n    \"y = 8* x + noise\\n\",\n    \"np.random.seed(1)\\n\",\n    \"plt.scatter(x, y)\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ed9e4ef7\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Gradient and bias calculation\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"9e4e7430\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Gradient: 8.326885863832231\\n\",\n      \"bias: 100.05814848422345\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<matplotlib.legend.Legend at 0x7f63f2d967d0>\"\n      ]\n     },\n     \"execution_count\": 2,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAigAAAGxCAYAAABIjE2TAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAABds0lEQVR4nO3deViU5cIG8HsYWRVGAWFA2SI0ETc099wXNMk1U7SDSx6PZeVxK08ZUC65Zmmaxy+1VNQ2Law0NdfjvpAimkugmBCuwyLrzPv9QTMyzDswAwMzzNy/65rrap73mXeeAXNun1UiCIIAIiIiIgtiZ+4GEBEREZXFgEJEREQWhwGFiIiILA4DChEREVkcBhQiIiKyOAwoREREZHEYUIiIiMjiMKAQERGRxWFAISIiIovDgEJkATZu3AiJRKJ51KlTB40bN8b48ePx559/1kgbAgMDMW7cOM3zgwcPQiKR4ODBg0bd59ixY4iNjcWjR49M2j4AGDduHAIDA01+X0t9XyJbxoBCZEE2bNiA48ePY+/evZg0aRK2bt2K5557Drm5uTXelvDwcBw/fhzh4eFGve7YsWOIi4urloBCRLajjrkbQERPhIWFoV27dgCAnj17QqlU4oMPPsDOnTsxZswY0dc8fvwYLi4uJm+Lm5sbOnbsaPL7EhEZgj0oRBZMHRBu3rwJoGSooV69erh48SL69esHV1dX9O7dGwBQWFiIefPm4ZlnnoGjoyMaNmyI8ePH4+7du1r3LCoqwuzZsyGXy+Hi4oKuXbvi1KlTOu+tb4jn5MmTiIyMhIeHB5ycnBAcHIxp06YBAGJjYzFr1iwAQFBQkGbIqvQ9tm/fjk6dOqFu3bqoV68e+vfvj/Pnz+u8/8aNG9G0aVM4OjqiWbNm+PLLLw36mQ0ZMgQBAQFQqVQ61zp06KDVI/Tpp5+iW7du8PLyQt26ddGiRQssXrwYRUVF5b5HamoqJBIJNm7cqHNNIpEgNjZWq+zatWuIioqCl5eX5vN8+umnWnVUKhXmzZuH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/311/HDDz/g8OHDaNy4sbmbYzAGlGrm6ekJT09Pg+r++eef6NmzJ9q2bYsNGzbAzo4dXNXFmN8LmZ+DgwPatm2LvXv3YujQoZryvXv3YvDgwWZsGZHlEgQBr7/+Onbs2IGDBw8iKCjI3E0yCgOKhbhz5w569OgBf39/LF26FHfv3tVck8vlZmwZ3bp1Cw8ePMCtW7egVCqRmJgIAHj66adRr1498zbOhkyfPh0vv/wy2rVrp+lhvHXrFudpWYCcnBxcv35d8zwlJQWJiYlwd3eHv7+/GVtm21577TXEx8fj+++/h6urq6YHUiaTwdnZ2cytM4BAFmHDhg0CANEHmVd0dLTo7+XAgQPmbprN+fTTT4WAgADBwcFBCA8PFw4dOmTuJpEgCAcOHBD9fyQ6OtrcTbNp+r5TNmzYYO6mGYT7oBAREZHF4SQHIiIisjgMKERERGRxGFCIiIjI4jCgEBERkcVhQCEiIiKLw4BCREREFocBhYiIiCwOAwoRERFZHAYUIiIisjgMKERERGRxGFCIiIjI4vw/VnmmG8d8dZcAAAAASUVORK5CYII=\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"numerator = sum((x - x.mean()) * (y - y.mean()))\\n\",\n    \"denominator = sum((x - x.mean())**2) \\n\",\n    \"\\n\",\n    \"w = numerator / denominator\\n\",\n    \"b = y.mean() - w * x.mean()\\n\",\n    \"\\n\",\n    \"print(\\\"Gradient:\\\", w) \\n\",\n    \"print(\\\"bias:\\\",b)\\n\",\n    \"plt.scatter(x, y)\\n\",\n    \"plt.title(\\\"Predicted values\\\")\\n\",\n    \"plt.plot(x,(w * x)+b, color='orange')\\n\",\n    \"plt.legend([\\\"Actual values\\\", \\\"Predicted value\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"03421570\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Accuracy of model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"92aab9c4\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"R^2 score : 0.9808663599761945\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"predictions = w*x +b\\n\",\n    \"accuracy = r2_score(y, predictions)\\n\",\n    \"print(\\\"R^2 score :\\\", accuracy) \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"9641c98b\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Transition to Cairo\\n\",\n    \"## Create a scarb project\\n\",\n    \"\\n\",\n    \"Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"id\": \"1e527c7f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Created `linear_regression` package.\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"! scarb new linear_regression\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"5b75bcd0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!echo -n > linear_regression/src/lib.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b84409f8\",\n   \"metadata\": {},\n   \"source\": [\n    \"A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\\n\",\n    \"```toml\\n\",\n    \"[package]\\n\",\n    \"name = \\\"linear_regresion\\\"\\n\",\n    \"version = \\\"0.1.0\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"[dependencies]\\n\",\n    \"orion = { git = \\\"https://github.com/gizatechxyz/onnx-cairo\\\" }\\n\",\n    \"\\n\",\n    \"[scripts]\\n\",\n    \"test = \\\"scarb cairo-test -f linear_regression_test\\\"\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"0bd602a0\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"ename\": \"SyntaxError\",\n     \"evalue\": \"invalid syntax (3814475083.py, line 3)\",\n     \"output_type\": \"error\",\n     \"traceback\": [\n      \"\\u001b[0;36m  Cell \\u001b[0;32mIn [6], line 3\\u001b[0;36m\\u001b[0m\\n\\u001b[0;31m    mod test;\\u001b[0m\\n\\u001b[0m        ^\\u001b[0m\\n\\u001b[0;31mSyntaxError\\u001b[0m\\u001b[0;31m:\\u001b[0m invalid syntax\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# add reference modules to help our code compile at the end\\n\",\n    \"%%writefile linear_regression/src/lib.cairo\\n\",\n    \"mod test;\\n\",\n    \"mod data_preprocessing;\\n\",\n    \"mod helper_functions;\\n\",\n    \"mod datasets;\\n\",\n    \"mod model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"1d2ad43c\",\n   \"metadata\": {},\n   \"source\": [\n    \"\\n\",\n    \"## Generate Cairo files\\n\",\n    \"\\n\",\n    \"Now, we will transition our model to cairo. We will start by converting the the x features and y labels to FP16x16 tensors numbers. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"id\": \"e8dcc4e4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"\\n\",\n    \"def generate_cairo_files(data, name, folder_name):\\n\",\n    \"    \\n\",\n    \"    os.makedirs(f'linear_regression/src/datasets/{folder_name}', exist_ok=True)\\n\",\n    \"    with open(os.path.join('linear_regression/src/datasets', f'{folder_name}', f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\\\n\\\" +\\n\",\n    \"                \\\"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::{FP16x16, FixedTrait};\\\\n\\\\n\\\" +\\n\",\n    \"                \\\"fn {0}() ->  Tensor<FP16x16>  \\\".format(name) + \\\"{\\\\n\\\" +\\n\",\n    \"                \\\"    let tensor = TensorTrait::<FP16x16>::new( \\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"            \\n\",\n    \"            if len(data.shape)>1:\\n\",\n    \"                f.write(\\\"    shape: array![{0},\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\\"{0}].span(),\\\\n\\\".format(data.shape[1]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            if len(data.shape)==1:\\n\",\n    \"                f.write(\\\"    shape: array![{0}].span(),\\\\n\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            for val in np.nditer(data.flatten()):\\n\",\n    \"                f.write(\\\"    FixedTrait::new({0}, {1} ),\\\\n\\\".format(abs(int(val * 2**16)), str(val < 0).lower()))\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"].span() \\\\n \\\\n\\\" +\\n\",\n    \"                \\\");\\\\n\\\\n\\\"+\\n\",\n    \"                \\\"return tensor; \\\\n\\\"+\\n\",\n    \"                \\\"}\\\"\\n\",\n    \"            )\\n\",\n    \"    with open(os.path.join('linear_regression/src/datasets', f'{folder_name}.cairo'), 'a') as f:\\n\",\n    \"        f.write(f\\\"mod {name};\\\\n\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"id\": \"130007b6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(x, 'x_feature_data', 'linear_data')\\n\",\n    \"generate_cairo_files(y, 'y_label_data', 'linear_data')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"id\": \"0e56a0d7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# add reference modules to help our code compile\\n\",\n    \"! touch linear_regression/src/datasets.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"id\": \"398e349b\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/datasets.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/datasets.cairo\\n\",\n    \"mod linear_data;\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"id\": \"753ad297\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/datasets/linear_data.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"id\": \"1baa1a26\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/datasets/linear_data.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/datasets/linear_data.cairo\\n\",\n    \"mod x_feature_data;\\n\",\n    \"mod y_label_data;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ce0a391b\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Helper functions \\n\",\n    \"\\n\",\n    \"We add some helper functions that we may need during our linear regression model construction and testing\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"id\": \"e944127f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/helper_functions.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"id\": \"649d0a52\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/helper_functions.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/helper_functions.cairo\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"\\n\",\n    \"// retrieves row data by index in a 2D tensor\\n\",\n    \"fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\\n\",\n    \"    let column_len = *tensor_data.shape.at(1); //13\\n\",\n    \"    // crete new array\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // loop through the x values and append values \\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= column_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        result.append(tensor_data.at(indices: array![row_index, i].span()));\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    let resultant_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(array![column_len].span(), data: result.span());\\n\",\n    \"    return resultant_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// transposes tensor\\n\",\n    \"fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    return tensor_transposed;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\\n\",\n    \"    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\\n\",\n    \"    let mean = *sum_result / tensor_size;\\n\",\n    \"    return mean;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// Calculates the R-Squared score between two tensors.\\n\",\n    \"fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let mut Y_values_ = Y_values;\\n\",\n    \"    let mean_y_value = calculate_mean(Y_values);\\n\",\n    \"    // creating the appropriate tensor shapes and empty arrays to populate values into\\n\",\n    \"    let mut squared_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_diff_vals = array::ArrayTrait::new();\\n\",\n    \"    let mut squared_mean_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_mean_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_mean_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match Y_values_.data.pop_front() {\\n\",\n    \"            Option::Some(y_value) => {\\n\",\n    \"                let diff_pred = *y_value - *Y_pred_values.data.at(i);\\n\",\n    \"                let squared_diff = diff_pred * diff_pred;\\n\",\n    \"                squared_diff_vals.append(squared_diff);\\n\",\n    \"\\n\",\n    \"                let diff_mean = *y_value - mean_y_value;\\n\",\n    \"                let squared_mean_diff = diff_mean * diff_mean;\\n\",\n    \"                squared_mean_diff_vals.append(squared_mean_diff);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        }\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let squared_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_diff_shape.span(), squared_diff_vals.span());\\n\",\n    \"    let squared_mean_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\\n\",\n    \"    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_squared_mean_diff = squared_mean_diff_tensor\\n\",\n    \"        .cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let r_score = FixedTrait::new_unscaled(1, false)\\n\",\n    \"        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\\n\",\n    \"            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\\n\",\n    \"\\n\",\n    \"    return r_score;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\\n\",\n    \"fn normalize_user_x_inputs(\\n\",\n    \"    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_inputs_normalized = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut x_min = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() > 1 {\\n\",\n    \"        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\\n\",\n    \"        let data_len = *transposed_tensor.shape.at(0); //13\\n\",\n    \"        // loop through each row calculating the min, max and range row values for each feature columns\\n\",\n    \"        let mut i: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            if i >= data_len {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"            x_min.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"            x_max.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"            x_range\\n\",\n    \"                .append(\\n\",\n    \"                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\\n\",\n    \"                );\\n\",\n    \"            i += 1;\\n\",\n    \"        };\\n\",\n    \"        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::new(\\n\",\n    \"            shape: array![data_len].span(), data: x_range.span()\\n\",\n    \"        );\\n\",\n    \"\\n\",\n    \"        // for normalizing 2D user inputed feature vals\\n\",\n    \"        if x_inputs.shape.len() > 1 {\\n\",\n    \"            let mut j: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if j >= *x_inputs.shape.at(0) {\\n\",\n    \"                    break ();\\n\",\n    \"                };\\n\",\n    \"                let mut row_data = get_tensor_data_by_row(x_inputs, j);\\n\",\n    \"                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\\n\",\n    \"                let mut k: u32 = 0;\\n\",\n    \"\\n\",\n    \"                loop {\\n\",\n    \"                    if k >= norm_row_data.data.len() {\\n\",\n    \"                        break ();\\n\",\n    \"                    };\\n\",\n    \"                    result.append(*norm_row_data.data.at(k));\\n\",\n    \"                    k += 1;\\n\",\n    \"                };\\n\",\n    \"                j += 1;\\n\",\n    \"            };\\n\",\n    \"            x_inputs_normalized =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(\\n\",\n    \"                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\\n\",\n    \"                );\\n\",\n    \"        };\\n\",\n    \"\\n\",\n    \"        // for normalizing 1D feature input\\n\",\n    \"        if x_inputs.shape.len() == 1 {\\n\",\n    \"            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\\n\",\n    \"        };\\n\",\n    \"    }\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() == 1 {\\n\",\n    \"        let mut x_min_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(\\n\",\n    \"            shape: array![1].span(),\\n\",\n    \"            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\\n\",\n    \"                .span()\\n\",\n    \"        );\\n\",\n    \"        let mut diff = ((x_inputs - x_min_tensor));\\n\",\n    \"        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\\n\",\n    \"    };\\n\",\n    \"    return x_inputs_normalized;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// rescales model predictions to standard format\\n\",\n    \"fn rescale_predictions(\\n\",\n    \"    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut rescale_predictions = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut y_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    let mut y_max = y_values.max_in_tensor();\\n\",\n    \"    let mut y_min = y_values.min_in_tensor();\\n\",\n    \"    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\\n\",\n    \"    // convert to tensor format for ease of math operations\\n\",\n    \"    let y_min_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_min].span());\\n\",\n    \"    let y_max_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_max].span());\\n\",\n    \"    let y_range_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_range].span());\\n\",\n    \"\\n\",\n    \"    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\\n\",\n    \"\\n\",\n    \"    return rescale_predictions;\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"079198a6\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Data-preprocessing functions\\n\",\n    \"\\n\",\n    \"We can normalize our data but for this tutorial we will not as we are working with a relitively small and simple dataset. However, it is recommended to normalize data before passing it to the  linear regression model since we will be working with 16x16 fixed point numbers in cairo. This is to prevent  from having overflow issues as we compute the feature gradient values (some calculations involve squaring x values which can lead to relatively large if not normalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"id\": \"e2f82c96\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/data_preprocessing.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"id\": \"089f888f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/data_preprocessing.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"\\n\",\n    \"%%writefile linear_regression/src/data_preprocessing.cairo\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct Dataset {\\n\",\n    \"    x_values: Tensor<FP16x16>,\\n\",\n    \"    y_values: Tensor<FP16x16>,\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl DataPreprocessing of DatasetTrait {\\n\",\n    \"    fn normalize_dataset(ref self: Dataset) -> Dataset {\\n\",\n    \"        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        // used for multiple_linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() > 1 {\\n\",\n    \"            x_values = normalize_feature_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"        // used for linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() == 1 {\\n\",\n    \"            x_values = normalize_label_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        return Dataset { x_values, y_values };\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 2D Tensor\\n\",\n    \"fn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // transpose to change rows to be columns\\n\",\n    \"    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    let tensor_shape = transposed_tensor.shape;\\n\",\n    \"    let tensor_row_len = *tensor_shape.at(0); // 13 \\n\",\n    \"    let tensor_column_len = *tensor_shape.at(1); //50\\n\",\n    \"    // loop and append max and min row values to corresponding  array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= tensor_row_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"        x_max_array.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"        x_min_array.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"        x_range_array\\n\",\n    \"            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    // convert array to tensor format for ease of math operation\\n\",\n    \"    let mut x_min = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\\n\",\n    \"    let mut x_range = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\\n\",\n    \"    let normalized_tensor = (tensor_data - x_min) / x_range;\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 1D tensor\\n\",\n    \"fn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut tensor_data_ = tensor_data;\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\\n\",\n    \"    // loop through tensor values normalizing and appending to new array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match tensor_data_.data.pop_front() {\\n\",\n    \"            Option::Some(tensor_val) => {\\n\",\n    \"                let mut diff = *tensor_val - tensor_data.min_in_tensor();\\n\",\n    \"                normalized_array.append(diff / range);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        };\\n\",\n    \"    };\\n\",\n    \"    // convert normalized array values to tensor format\\n\",\n    \"    let mut normalized_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d2c1d5bf\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Linear Regression Model\\n\",\n    \"\\n\",\n    \"Implement the Linear Regression functions\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"id\": \"ba6e1b1a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"os.makedirs(f'linear_regression/src/model/', exist_ok=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"id\": \"f310112c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/model/linear_regression_model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"id\": \"7703f49a\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/model/linear_regression_model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/model/linear_regression_model.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct LinearRegressionModel {\\n\",\n    \"    gradient: Tensor<FP16x16>,\\n\",\n    \"    bias: Tensor<FP16x16>\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl RegressionOperation of LinearRegressionModelTrait {\\n\",\n    \"    fn predict(ref self: LinearRegressionModel, x_input: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"        let gradient = self.gradient;\\n\",\n    \"        let bias = self.bias;\\n\",\n    \"        let mut prediction = (gradient * x_input) + bias;\\n\",\n    \"        return prediction;\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn LinearRegression(dataset: Dataset) -> LinearRegressionModel {\\n\",\n    \"    let gradient = compute_gradient(dataset);\\n\",\n    \"    let bias = compute_bias(dataset);\\n\",\n    \"    return LinearRegressionModel { gradient, bias };\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// computes the mean of a given 1D tensor and outputs result as tensor\\n\",\n    \"fn compute_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\\n\",\n    \"    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\\n\",\n    \"    let mean = *sum_result / tensor_size;\\n\",\n    \"    let mut result_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![mean].span());\\n\",\n    \"    return result_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"/// Calculates the deviation of each element from the mean of the provided 1D tensor.\\n\",\n    \"fn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut tensor_data_ = tensor_data;\\n\",\n    \"    let mean_value = calculate_mean(tensor_data);\\n\",\n    \"    let mut tensor_shape = array::ArrayTrait::new();\\n\",\n    \"    tensor_shape.append(tensor_data.data.len());\\n\",\n    \"    let mut deviation_values = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match tensor_data_.data.pop_front() {\\n\",\n    \"            Option::Some(tensor_val) => {\\n\",\n    \"                let distance_from_mean = *tensor_val - mean_value;\\n\",\n    \"                deviation_values.append(distance_from_mean);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        };\\n\",\n    \"    };\\n\",\n    \"    let distance_from_mean_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(tensor_shape.span(), deviation_values.span());\\n\",\n    \"\\n\",\n    \"    return distance_from_mean_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"/// Calculates the beta value for linear regression.\\n\",\n    \"fn compute_gradient(dataset: Dataset) -> Tensor<FP16x16> {\\n\",\n    \"    let x_deviation = deviation_from_mean(dataset.x_values);\\n\",\n    \"    let y_deviation = deviation_from_mean(dataset.y_values);\\n\",\n    \"\\n\",\n    \"    let x_y_covariance = x_deviation.matmul(@y_deviation);\\n\",\n    \"    let x_variance = x_deviation.matmul(@x_deviation);\\n\",\n    \"\\n\",\n    \"    let beta_value = x_y_covariance / x_variance;\\n\",\n    \"\\n\",\n    \"    return beta_value;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"/// Calculates the intercept for linear regression.\\n\",\n    \"fn compute_bias(dataset: Dataset) -> Tensor<FP16x16> {\\n\",\n    \"    let x_mean = compute_mean(dataset.x_values);\\n\",\n    \"    let y_mean = compute_mean(dataset.y_values);\\n\",\n    \"    let gradient = compute_gradient(dataset);\\n\",\n    \"    let mx = gradient * x_mean;\\n\",\n    \"    let intercept = y_mean - mx;\\n\",\n    \"    return intercept;\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"id\": \"8be0b0e6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"id\": \"4fecca6e\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/model.cairo\\n\",\n    \"mod linear_regression_model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"e9321f85\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Running tests on model\\n\",\n    \"\\n\",\n    \"Running some checks to ensure the model is performing as expected. Some of the checks involve:\\n\",\n    \"- tensor shape/dimension check\\n\",\n    \"- gradient and bias value and dimension checks  \\n\",\n    \"- model accuracy deviance checks\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"id\": \"f32a96db\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch linear_regression/src/test.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"id\": \"619cff0f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting linear_regression/src/test.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile linear_regression/src/test.cairo\\n\",\n    \"// use traits::Into;\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use linear_regresion::datasets::linear_data::x_feature_data::x_feature_data;\\n\",\n    \"use linear_regresion::datasets::linear_data::y_label_data::y_label_data;\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16,  FixedTrait};\\n\",\n    \"use linear_regresion::model::linear_regression_model::{\\n\",\n    \"     LinearRegressionModel, compute_mean, LinearRegression, LinearRegressionModelTrait\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"use linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \\n\",\n    \"calculate_r_score, normalize_user_x_inputs, rescale_predictions};\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \\n\",\n    \"    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\\n\",\n    \"\\n\",\n    \"#[test]\\n\",\n    \"#[available_gas(99999999999999999)]\\n\",\n    \"fn multiple_linear_regression_test() {\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// // ----------------------------------------------------------------Simple Linear regression tests---------------------------------------------------------------------------------\\n\",\n    \"\\n\",\n    \"let mut main_x_vals = x_feature_data();\\n\",\n    \"let mut main_y_vals = y_label_data();\\n\",\n    \"let dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\\n\",\n    \"let mut model = LinearRegression(dataset);\\n\",\n    \"let gradient = model.gradient;\\n\",\n    \"let mut reconstructed_ys = model.predict(main_x_vals);\\n\",\n    \"let mut r_squared_score = calculate_r_score(main_y_vals,reconstructed_ys);\\n\",\n    \"r_squared_score.print(); \\n\",\n    \"\\n\",\n    \"// performing checks on shape on coefficient values (gradient vals + bias) \\n\",\n    \"assert(model.gradient.data.len() == 1,  'gradient data shape mismatch');\\n\",\n    \"assert(model.bias.data.len() == 1,  'bias data shape mismatch');\\n\",\n    \"// model accuracy deviance checks\\n\",\n    \"assert(r_squared_score >= FixedTrait::new(62259, false), 'Linear model acc. less than 95%');\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// linear regression model new input predictions\\n\",\n    \"let mut user_value =   TensorTrait::<FP16x16>::new(shape: array![2].span(), data: array![FixedTrait::new(65536, false), FixedTrait::new(65536, true)].span());\\n\",\n    \"let mut prediction_results = model.predict(user_value);\\n\",\n    \"(*prediction_results.data.at(0)).print(); \\n\",\n    \"(*prediction_results.data.at(1)).print();\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a3ac443e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.4\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/Provable Multiple Linear Regression (Boston Housing Value Estimation).ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"97bdc270\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import necessary libs & prepare dataset\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"ae4ed5fb\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import pandas as pd\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import pandas as pd\\n\",\n    \"import os\\n\",\n    \"from sklearn.metrics import r2_score\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"4768aa34\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>CRIM</th>\\n\",\n       \"      <th>ZN</th>\\n\",\n       \"      <th>INDUS</th>\\n\",\n       \"      <th>CHAS</th>\\n\",\n       \"      <th>NOX</th>\\n\",\n       \"      <th>RM</th>\\n\",\n       \"      <th>AGE</th>\\n\",\n       \"      <th>DIS</th>\\n\",\n       \"      <th>RAD</th>\\n\",\n       \"      <th>TAX</th>\\n\",\n       \"      <th>PTRATIO</th>\\n\",\n       \"      <th>MEDV</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>0.40771</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>6.20</td>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>0.507</td>\\n\",\n       \"      <td>6.164</td>\\n\",\n       \"      <td>91.3</td>\\n\",\n       \"      <td>3.0480</td>\\n\",\n       \"      <td>8</td>\\n\",\n       \"      <td>307</td>\\n\",\n       \"      <td>17.4</td>\\n\",\n       \"      <td>21.7</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>0.26838</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>9.69</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0.585</td>\\n\",\n       \"      <td>5.794</td>\\n\",\n       \"      <td>70.6</td>\\n\",\n       \"      <td>2.8927</td>\\n\",\n       \"      <td>6</td>\\n\",\n       \"      <td>391</td>\\n\",\n       \"      <td>19.2</td>\\n\",\n       \"      <td>18.3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>0.05360</td>\\n\",\n       \"      <td>21.0</td>\\n\",\n       \"      <td>5.64</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0.439</td>\\n\",\n       \"      <td>6.511</td>\\n\",\n       \"      <td>21.1</td>\\n\",\n       \"      <td>6.8147</td>\\n\",\n       \"      <td>4</td>\\n\",\n       \"      <td>243</td>\\n\",\n       \"      <td>16.8</td>\\n\",\n       \"      <td>25.0</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>11.16040</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>18.10</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0.740</td>\\n\",\n       \"      <td>6.629</td>\\n\",\n       \"      <td>94.6</td>\\n\",\n       \"      <td>2.1247</td>\\n\",\n       \"      <td>24</td>\\n\",\n       \"      <td>666</td>\\n\",\n       \"      <td>20.2</td>\\n\",\n       \"      <td>13.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>2.31390</td>\\n\",\n       \"      <td>0.0</td>\\n\",\n       \"      <td>19.58</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0.605</td>\\n\",\n       \"      <td>5.880</td>\\n\",\n       \"      <td>97.3</td>\\n\",\n       \"      <td>2.3887</td>\\n\",\n       \"      <td>5</td>\\n\",\n       \"      <td>403</td>\\n\",\n       \"      <td>14.7</td>\\n\",\n       \"      <td>19.1</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"       CRIM    ZN  INDUS  CHAS    NOX     RM   AGE     DIS  RAD  TAX  PTRATIO  \\\\\\n\",\n       \"0   0.40771   0.0   6.20     1  0.507  6.164  91.3  3.0480    8  307     17.4   \\n\",\n       \"1   0.26838   0.0   9.69     0  0.585  5.794  70.6  2.8927    6  391     19.2   \\n\",\n       \"2   0.05360  21.0   5.64     0  0.439  6.511  21.1  6.8147    4  243     16.8   \\n\",\n       \"3  11.16040   0.0  18.10     0  0.740  6.629  94.6  2.1247   24  666     20.2   \\n\",\n       \"4   2.31390   0.0  19.58     0  0.605  5.880  97.3  2.3887    5  403     14.7   \\n\",\n       \"\\n\",\n       \"   MEDV  \\n\",\n       \"0  21.7  \\n\",\n       \"1  18.3  \\n\",\n       \"2  25.0  \\n\",\n       \"3  13.4  \\n\",\n       \"4  19.1  \"\n      ]\n     },\n     \"execution_count\": 2,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"df = pd.read_csv(\\\"boston_dataset.csv\\\")\\n\",\n    \"df.drop('Unnamed: 0', axis=1, inplace=True)\\n\",\n    \"\\n\",\n    \"df.head()\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"c88f769e\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"(50, 12)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"print(df.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"66a093ca\",\n   \"metadata\": {},\n   \"source\": [\n    \"##### Column features\\n\",\n    \"\u2022 CRIM per capita crime rate by town <br>\\n\",\n    \"\u2022 ZN proportion of residential land zoned for lots over 25,000 sq.ft. <br>\\n\",\n    \"\u2022 INDUS proportion of non-retail business acres per town <br>\\n\",\n    \"\u2022 CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)<br>\\n\",\n    \"\u2022 NOX nitric oxides concentration (parts per 10 million) <br>\\n\",\n    \"\u2022 RM average number of rooms per dwelling <br>\\n\",\n    \"\u2022 AGE proportion of owner-occupied units built prior to 1940 <br>\\n\",\n    \"\u2022 DIS weighted distances to five Boston employment centres <br>\\n\",\n    \"\u2022 RAD index of accessibility to radial highways <br>\\n\",\n    \"\u2022 TAX full-value property-tax rate per 10,000 dollars <br>\\n\",\n    \"\u2022 PTRATIO pupil-teacher ratio by town <br>\\n\",\n    \"\u2022 MEDV Median value of owner-occupied homes in $1000's <br>\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"a3d9d8b1\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"(50, 11)\\n\",\n      \"(50,)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"features = df.drop(['MEDV',], axis=1)\\n\",\n    \"target = df['MEDV']\\n\",\n    \"\\n\",\n    \"#convert to numpy\\n\",\n    \"X_original = features.to_numpy()\\n\",\n    \"Y_original = target.to_numpy()\\n\",\n    \"\\n\",\n    \"print(X_original.shape)\\n\",\n    \"print(Y_original.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"fc086887\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Normalize the dataset\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"id\": \"587dcfb9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Normalize the data \\n\",\n    \"\\n\",\n    \"def normalize_data(original_data):\\n\",\n    \"    data_min = np.min(original_data, axis=0)\\n\",\n    \"    data_max = np.max(original_data, axis=0)\\n\",\n    \"    data_range = data_max - data_min\\n\",\n    \"    data_normalized =  (original_data - data_min) / data_range\\n\",\n    \"    \\n\",\n    \"    return data_normalized\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"fd6c797f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_normalized= normalize_data(X_original)\\n\",\n    \"y_normalized= normalize_data(Y_original)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"e2bddf32\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Main Multiple Linear Regression algorythm\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"id\": \"c1fb0d79\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def transpose_and_add_bias(feature_data):\\n\",\n    \"    #transpose the data\\n\",\n    \"    transposed_data= feature_data.T\\n\",\n    \"    #add bias term\\n\",\n    \"    transposed_data_with_bias = np.vstack((transposed_data, np.ones(transposed_data.shape[1])))\\n\",\n    \"    \\n\",\n    \"    return transposed_data_with_bias\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"id\": \"feeab27f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def decorrelate_features(feature_data):\\n\",\n    \"\\n\",\n    \"    # Make copy of input matrix\\n\",\n    \"    x_temp = feature_data.copy()\\n\",\n    \"    \\n\",\n    \"    # Get number of features\\n\",\n    \"    feature_rows = feature_data.shape[0]\\n\",\n    \"    \\n\",\n    \"    # Decorrelate features\\n\",\n    \"    for i in range(feature_rows):\\n\",\n    \"        feature_squared = np.sum(x_temp[i]**2)\\n\",\n    \"        for j in range(i+1, feature_rows):\\n\",\n    \"            feature_cross_prod = np.sum(x_temp[i] * x_temp[j])\\n\",\n    \"            if feature_squared == 0:\\n\",\n    \"                print('Warning, division by zero encountered and handled')\\n\",\n    \"                feature_squared = 1e-8 \\n\",\n    \"            feature_grad = feature_cross_prod / feature_squared\\n\",\n    \"            x_temp[j] -= feature_grad * x_temp[i]\\n\",\n    \"            \\n\",\n    \"    decorelated_x_vals = x_temp\\n\",\n    \"\\n\",\n    \"    return decorelated_x_vals\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"id\": \"617f3d11\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def calculate_gradients(decorelated_x_vals, y_values, original_x_features):\\n\",\n    \"  \\n\",\n    \"    # Initialize gradients array\\n\",\n    \"    feature_rows = decorelated_x_vals.shape[0]\\n\",\n    \"    gradients = np.zeros(feature_rows)\\n\",\n    \"\\n\",\n    \"    # Calculate gradients\\n\",\n    \"    for i in range(feature_rows-1, -1, -1):\\n\",\n    \"        prod = np.sum(y_values * decorelated_x_vals[i])\\n\",\n    \"        squared = np.sum(decorelated_x_vals[i] * decorelated_x_vals[i])\\n\",\n    \"        if squared == 0:\\n\",\n    \"            print('Warning, division by zero encountered and handled')\\n\",\n    \"            squared = 1e-8\\n\",\n    \"\\n\",\n    \"        gradients[i] = prod / squared\\n\",\n    \"        y_values -= gradients[i] * original_x_features[i]\\n\",\n    \"    \\n\",\n    \"\\n\",\n    \"    return gradients\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"id\": \"f07ae5a1\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Training data shapes:\\n\",\n      \"X_normalized: (12, 50)\\n\",\n      \"y_normalized: (50,)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"X_normalized_transposed_with_bias = transpose_and_add_bias(X_normalized)\\n\",\n    \"\\n\",\n    \"print(\\\"Training data shapes:\\\")\\n\",\n    \"print(\\\"X_normalized:\\\", X_normalized_transposed_with_bias.shape)\\n\",\n    \"print(\\\"y_normalized:\\\", y_normalized.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"id\": \"e3a13196\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"decorrelate_X_features = decorrelate_features(X_normalized_transposed_with_bias)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"id\": \"21864d6b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"decorrelate_X_features = decorrelate_features(X_normalized_transposed_with_bias)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"id\": \"8090dcd8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"gradient_values = calculate_gradients(decorrelate_X_features, y_normalized, X_normalized_transposed_with_bias )\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"id\": \"11b052e5\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.43365324, -0.18175555, -0.42523263,  0.13711559, -0.19621044,\\n\",\n       \"       -0.06995875,  0.62886834, -0.08972977, -0.0081258 ,  0.00121573,\\n\",\n       \"        0.0482544 ,  0.13295955])\"\n      ]\n     },\n     \"execution_count\": 14,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"real_gradient_values_reversed = np.flip(gradient_values)\\n\",\n    \"real_gradient_values_reversed\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"id\": \"b27055f3\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.13295955,  0.0482544 ,  0.00121573, -0.0081258 , -0.08972977,\\n\",\n       \"        0.62886834, -0.06995875, -0.19621044,  0.13711559, -0.42523263,\\n\",\n       \"       -0.18175555,  0.43365324])\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"gradient_values\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4f970ffa\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Reconstructing the y labels using the calculated gradients and X feature data\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"id\": \"7dab4a56\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def denormalize_data(original_data,normalized_data):\\n\",\n    \"    \\n\",\n    \"    data_min = np.min(original_data)\\n\",\n    \"    data_max = np.max(original_data)\\n\",\n    \"    data_range = data_max - data_min\\n\",\n    \"    \\n\",\n    \"    denormalize_data = ( normalized_data * data_range) + data_min\\n\",\n    \"    return denormalize_data\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"id\": \"f3a73a20\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"R^2 score (denormalized): 0.8497719822024984\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAh8AAAGxCAYAAADCo9TSAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAADa9UlEQVR4nOydd5gb5bn27xl1aYu2F++6d1ww2BRTbIoxGAjEIRC6aSEQCA7hw8cQgiEJLcCBHE5yUsAGQk0IKfRqQ2g27r2u6/a+qzaSZr4/3vcdjbTqq7p+f9e11+6ORtJII83c85T7ERRFUcDhcDgcDoeTIcRsbwCHw+FwOJyjCy4+OBwOh8PhZBQuPjgcDofD4WQULj44HA6Hw+FkFC4+OBwOh8PhZBQuPjgcDofD4WQULj44HA6Hw+FkFC4+OBwOh8PhZBQuPjgcDofD4WQULj44Q5oVK1ZAEAT1x2w2o7q6GmeccQYefvhhtLa2ZnsTc45ly5ZBEISgZXPnzsXcuXMzvi2CIGDZsmVR19m/f3/QPhZFEWVlZViwYAG++uqrjGznokWLMHLkyKBl8Wx7KI2NjVi2bBk2bNgw4LZw+4XDyVf02d4ADicTLF++HBMnToTX60Vrayv+85//4NFHH8Xjjz+O1157DWeffXa2NzGn+d3vfpftTYjJ7bffjiuuuAJ+vx9bt27FAw88gDPOOANfffUVZsyYkfHt+eqrr1BXV5fQfRobG/HAAw9g5MiROPbYY4Nuu/HGG3HuueemcAs5nOzBxQfnqGDKlCmYOXOm+v/3vvc9/PSnP8Wpp56KhQsXYvfu3aiqqsriFkbG6XTCarVmdRsmT56c1eePh+HDh+Okk04CAJxyyikYO3YszjrrLPzud7/Dn/70p7D3c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fj3vvvReSJMV8XC033ngjXn31VbhcLixfvhyXXXZZVBv8E044AWPGjFHv8+abb+Kqq65Sb3/iiSfw3//937j77rvxySefYMOGDZg/f37U7RIEYcD7oa1dkWUZxx9/PDZs2BD0s2vXLlxxxRUAgOXLl+Orr77C7Nmz8dprr2H8+PH4+uuvE3ovkiEh8XHXXXdh1apVaGhowDfffINLLrkEvb29uPbaayEIAhYvXoyHHnoIb775JrZs2YJFixbBarWqL5LD0aIoikZ88MgHhzMUGDt2LIxGI/7zn/+oy7xeL7799ltMmjQp7scpLi5GVVWVmtoASHRg/fr1g9q+L774AiNGjMC9996LmTNnYty4cUkVWC5YsAA2mw2///3v8e6770ZMuWi54oor8NJLL+Hf//43RFHE+eefr972+eef46KLLsJVV12F6dOnY/To0di9e3fUx6uoqEBTU5P6/+7du4MmIB933HHYvXs3KisrMXbs2KCf4uJidb0ZM2Zg6dKl+PLLLzFlypSg9FC6SEh8HD58GJdffjkmTJiAhQsXwmg04uuvv8aIESMAkOKhxYsX49Zbb8XMmTNx5MgRfPDBB9zjgxMWj08GE+1cfHA4QwObzYZbbrkF/+///T+899572LZtG2666SY4nU612DJebr/9djz88MP45z//iZ07d+KOO+5AV1fXoAoix44di4MHD+LVV1/F3r178dvf/hZvvvlmwo+j0+mwaNEiLF26FGPHjsXJJ58c8z5XXnkl1q1bh1//+te45JJLgoayjR07Fh9++CG+/PJLbN++HTfffLPayBGJM888E8888wzWrVuHb7/9Fj/60Y+Coj5XXnklysvLcdFFF+Hzzz9HQ0MDVq1ahTvuuAOHDx9GQ0MDli5diq+++goHDhzABx98gF27diUkEpMloZqPV199NertgiBg2bJlWLZs2WC2iXOUoK3z8Hh52oXDGSo88sgjkGUZV199Nfr6+jBz5ky8//77an1DvCxZsgTNzc245pproNPp8MMf/hDz588PMrdMlIsuugg//elPcdttt8Hj8eD888/Hfffdl9R564YbblDbeuNh3LhxmDVrFtasWYOnnnoq6Lb77rsPDQ0NmD9/PqxWK374wx/i4osvRk9PT8THe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whz+Ma665BgCd71owMjKCm2++GYlEAm1tbXjhhRewceNG4wJM57q6PPvss3jrrbdw8ODBOffR87u63HjjjfjhD3+Iq666ChcvXsQ3vvEN7Ny5E8eOHav5uW568SFRFCXv94yxObcRtYPOf/W5//77cfToUfzyl7+ccx+d7+qxfv16HDlyBDMzM3juuedw991348CBA8b9dK6rx+joKB544AG8/PLL8Hq98z6Oznl12LNnj/H95s2bcfPNN2Pt2rV45plncNNNNwGo3blu+rbL8uXLoWnanCrHxMTEHEVHVB/pnKbzX12++tWv4qWXXsIrr7yCoaEh43Y639XH4/HgyiuvxHXXXYfHHnsMW7duxV//9V/Tua4Bhw4dwsTEBHbs2AGXywWXy4UDBw7gb/7mb+ByuYzzSue8NgQCAWzevBnvv/9+zZ/fTS8+PB4PduzYgf379+fdvn//fuzcudOmo2odhoeH0d/fn3f+U6kUDhw4QOe/AhhjuP/++/H888/j5z//OYaHh/Pup/NdexhjSCaTdK5rwO23346RkREcOXLE+HXdddfh85//PI4cOYI1a9bQOa8hyWQSx48fx8DAQO2f30u2rDYAzz77LHO73ex73/see/fdd9nevXtZIBBgH3zwgd2H1hSEw2F2+PBhdvjwYQaAPfnkk+zw4cPszJkzjDHGHn/8cdbR0cGef/55NjIywn7/93+fDQwMsFAoZPORNx5f+cpXWEdHB3v11VfZ2NiY8SsWixmPofNdPR566CH22muvsdOnT7OjR4+yP//zP2eqqrKXX36ZMUbnuh5Yp10Yo3NeTb7+9a+zV199lZ06dYq98cYb7M4772TBYNB4b6zluW4J8cEYY3/7t3/LrrjiCubxeNj27duN0URi6bzyyisMwJxfd999N2OMj2w98sgjrL+/n+m6zm655RY2MjJi70E3KMXOMwD2/e9/33gMne/q8cUvftG4bvT09LDbb7/dEB6M0bmuB4Xig8559fjMZz7DBgYGmNvtZoODg+yuu+5ix44dM+6v5blWGGNs6fUTgiAIgiCI0mh6zwdBEARBEM6CxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHWFxAdBEARBEHXl/wMFeswfW2ZRoQAAAABJRU5ErkJggg==\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"y_pred_norm = gradient_values @ X_normalized_transposed_with_bias #prediction#\\n\",\n    \"\\n\",\n    \"reconstructed_y = denormalize_data(Y_original,y_pred_norm)\\n\",\n    \"\\n\",\n    \"# Plot the denormalized y values\\n\",\n    \"plt.figure(2)\\n\",\n    \"plt.title(\\\"Denormalized Prediction\\\")\\n\",\n    \"plt.plot(Y_original)\\n\",\n    \"plt.plot(reconstructed_y)\\n\",\n    \"plt.legend([\\\"original y values\\\", \\\"reconstructed ys\\\"])\\n\",\n    \"\\n\",\n    \"# Calculate R^2 score for denormalized prediction\\n\",\n    \"accuracy_denormalized = r2_score(Y_original, reconstructed_y)\\n\",\n    \"print(\\\"R^2 score (denormalized):\\\", accuracy_denormalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"302d8725\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Estimating value of a new property\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"id\": \"2bfac80e\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([  0.40771,   0.     ,   6.2    ,   1.     ,   0.507  ,   6.164  ,\\n\",\n       \"        91.3    ,   3.048  ,   8.     , 307.     ,  17.4    ])\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# 63.61759948730469  --->0.3379058837890625      #6.1999969482421875, 1, 0.506988525390625\\n\",\n    \"X_original[0]  #0.015472412109375 0.4076995849609375\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"id\": \"2fbe2acc\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"0.3628772191870112\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# user_input_feature_values = np.array([9.0771e-01, 5.0000e-01, 1.9500e+01, 1.3200e+00, 9.9000e-01,\\n\",\n    \"#        1.2164e+01, 9.1300e+01, 1.1000e+00, 6.0000e+00, 5.0600e+02,\\n\",\n    \"#        2.1000e+01])\\n\",\n    \"\\n\",\n    \"user_input_feature_values = X_original[0]\\n\",\n    \"\\n\",\n    \"X_min = np.min(X_original, axis=0)\\n\",\n    \"X_max = np.max(X_original, axis=0)\\n\",\n    \"X_range = X_max - X_min\\n\",\n    \"# normalize the feature vals\\n\",\n    \"normalized_vals = (user_input_feature_values - X_min) / X_range\\n\",\n    \"# add bias term \\n\",\n    \"user_input_feature_values_normalized_with_bias = np.append(normalized_vals, 1)\\n\",\n    \"\\n\",\n    \"# get normalized prediction\\n\",\n    \"prediction_normalized = gradient_values @ user_input_feature_values_normalized_with_bias\\n\",\n    \"print(prediction_normalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"id\": \"535f23d1\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"24.32395193323655\"\n      ]\n     },\n     \"execution_count\": 20,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"#denormalize forecast\\n\",\n    \"Y_min = np.min(Y_original, axis=0)\\n\",\n    \"Y_max = np.max(Y_original, axis=0)\\n\",\n    \"Y_range = Y_max - Y_min\\n\",\n    \"# rescale prediction\\n\",\n    \"denormlized_house_value_estimation =  (prediction_normalized * Y_range) + Y_min\\n\",\n    \"denormlized_house_value_estimation\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ea617854\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Transition to Cairo\\n\",\n    \"## Create a scarb project\\n\",\n    \"\\n\",\n    \"Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"id\": \"35d4e483\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Created `multiple_linear_regression` package.\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"! scarb new multiple_linear_regression\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"id\": \"e4211294\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! echo -n > multiple_linear_regression/src/lib.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"72afd4c8\",\n   \"metadata\": {},\n   \"source\": [\n    \"A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\\n\",\n    \"```toml\\n\",\n    \"[package]\\n\",\n    \"name = \\\"multiple_linear_regresion\\\"\\n\",\n    \"version = \\\"0.1.0\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"[dependencies]\\n\",\n    \"orion = { git = \\\"https://github.com/gizatechxyz/onnx-cairo\\\" }\\n\",\n    \"\\n\",\n    \"[scripts]\\n\",\n    \"test = \\\"scarb cairo-test -f multiple_linear_regression_test\\\"\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2aab745d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# add reference modules to help our code compile at the end\\n\",\n    \"%%writefile -a multiple_linear_regression/src/lib.cairo\\n\",\n    \"mod test;\\n\",\n    \"mod data_preprocessing;\\n\",\n    \"mod helper_functions;\\n\",\n    \"mod datasets;\\n\",\n    \"mod model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2ecade3b\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Generate Cairo files\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"id\": \"4192fdf0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Convert the original data to Cairo \\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def generate_cairo_files(data, name, folder_name):\\n\",\n    \"    \\n\",\n    \"    os.makedirs(f'multiple_linear_regression/src/datasets/{folder_name}', exist_ok=True)\\n\",\n    \"    with open(os.path.join('multiple_linear_regression/src/datasets', f'{folder_name}', f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\\\n\\\" +\\n\",\n    \"                \\\"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::{FP16x16, FixedTrait};\\\\n\\\\n\\\" +\\n\",\n    \"                \\\"fn {0}() ->  Tensor<FP16x16>  \\\".format(name) + \\\"{\\\\n\\\" +\\n\",\n    \"                \\\"    let tensor = TensorTrait::<FP16x16>::new( \\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"            \\n\",\n    \"            if len(data.shape)>1:\\n\",\n    \"                f.write(\\\"    shape: array![{0},\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\\"{0}].span(),\\\\n\\\".format(data.shape[1]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            if len(data.shape)==1:\\n\",\n    \"                f.write(\\\"    shape: array![{0}].span(),\\\\n\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            for val in np.nditer(data.flatten()):\\n\",\n    \"                f.write(\\\"    FixedTrait::new({0}, {1} ),\\\\n\\\".format(abs(int(val * 2**16)), str(val < 0).lower()))\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"].span() \\\\n \\\\n\\\" +\\n\",\n    \"                \\\");\\\\n\\\\n\\\"+\\n\",\n    \"                \\\"return tensor; \\\\n\\\"+\\n\",\n    \"                \\\"}\\\"\\n\",\n    \"            )\\n\",\n    \"    with open(os.path.join('multiple_linear_regression/src/datasets', f'{folder_name}.cairo'), 'a') as f:\\n\",\n    \"        f.write(f\\\"mod {name};\\\\n\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"id\": \"b05daac1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(X_original, 'boston_x_features', 'boston_data')\\n\",\n    \"generate_cairo_files(Y_original, 'boston_y_labels', 'boston_data') \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 25,\n   \"id\": \"30fe7dca\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(user_input_feature_values, 'user_inputs_boston_data', 'user_inputs_data')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 26,\n   \"id\": \"02e8a2d0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# add reference modules to help our code compile\\n\",\n    \"! touch multiple_linear_regression/src/datasets.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 27,\n   \"id\": \"f8cdb5fa\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/datasets.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/datasets.cairo\\n\",\n    \"mod boston_data;\\n\",\n    \"mod user_inputs_data;\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 28,\n   \"id\": \"cd1ca29f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/datasets/boston_data.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 29,\n   \"id\": \"4350c425\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/datasets/boston_data.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/datasets/boston_data.cairo\\n\",\n    \"mod boston_x_features;\\n\",\n    \"mod boston_y_labels;\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 30,\n   \"id\": \"f034a5e0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/datasets/user_inputs_data.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 31,\n   \"id\": \"d3235299\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/datasets/user_inputs_data.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/datasets/user_inputs_data.cairo\\n\",\n    \"mod user_inputs_boston_data;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ea3dd5d9\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Helper functions \\n\",\n    \"\\n\",\n    \"We add some helper functions to make it easier to construct our MLR model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 32,\n   \"id\": \"24ae59be\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/helper_functions.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 33,\n   \"id\": \"a51190ec\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/helper_functions.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/helper_functions.cairo\\n\",\n    \"\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"\\n\",\n    \"// retrieves row data by index in a 2D tensor\\n\",\n    \"fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\\n\",\n    \"    let column_len = *tensor_data.shape.at(1); //13\\n\",\n    \"    // crete new array\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // loop through the x values and append values \\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= column_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        result.append(tensor_data.at(indices: array![row_index, i].span()));\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    let resultant_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(array![column_len].span(), data: result.span());\\n\",\n    \"    return resultant_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// transposes tensor\\n\",\n    \"fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    return tensor_transposed;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\\n\",\n    \"    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\\n\",\n    \"    let mean = *sum_result / tensor_size;\\n\",\n    \"    return mean;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// Calculates the R-Squared score between two tensors.\\n\",\n    \"fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let mut Y_values_ = Y_values;\\n\",\n    \"    let mean_y_value = calculate_mean(Y_values);\\n\",\n    \"    // creating the appropriate tensor shapes and empty arrays to populate values into\\n\",\n    \"    let mut squared_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_diff_vals = array::ArrayTrait::new();\\n\",\n    \"    let mut squared_mean_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_mean_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_mean_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match Y_values_.data.pop_front() {\\n\",\n    \"            Option::Some(y_value) => {\\n\",\n    \"                let diff_pred = *y_value - *Y_pred_values.data.at(i);\\n\",\n    \"                let squared_diff = diff_pred * diff_pred;\\n\",\n    \"                squared_diff_vals.append(squared_diff);\\n\",\n    \"\\n\",\n    \"                let diff_mean = *y_value - mean_y_value;\\n\",\n    \"                let squared_mean_diff = diff_mean * diff_mean;\\n\",\n    \"                squared_mean_diff_vals.append(squared_mean_diff);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        }\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let squared_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_diff_shape.span(), squared_diff_vals.span());\\n\",\n    \"    let squared_mean_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\\n\",\n    \"    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_squared_mean_diff = squared_mean_diff_tensor\\n\",\n    \"        .cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let r_score = FixedTrait::new_unscaled(1, false)\\n\",\n    \"        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\\n\",\n    \"            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\\n\",\n    \"\\n\",\n    \"    return r_score;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\\n\",\n    \"fn normalize_user_x_inputs(\\n\",\n    \"    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_inputs_normalized = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut x_min = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() > 1 {\\n\",\n    \"        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\\n\",\n    \"        let data_len = *transposed_tensor.shape.at(0); //13\\n\",\n    \"        // loop through each row calculating the min, max and range row values for each feature columns\\n\",\n    \"        let mut i: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            if i >= data_len {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"            x_min.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"            x_max.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"            x_range\\n\",\n    \"                .append(\\n\",\n    \"                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\\n\",\n    \"                );\\n\",\n    \"            i += 1;\\n\",\n    \"        };\\n\",\n    \"        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::new(\\n\",\n    \"            shape: array![data_len].span(), data: x_range.span()\\n\",\n    \"        );\\n\",\n    \"\\n\",\n    \"        // for normalizing 2D user inputed feature vals\\n\",\n    \"        if x_inputs.shape.len() > 1 {\\n\",\n    \"            let mut j: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if j >= *x_inputs.shape.at(0) {\\n\",\n    \"                    break ();\\n\",\n    \"                };\\n\",\n    \"                let mut row_data = get_tensor_data_by_row(x_inputs, j);\\n\",\n    \"                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\\n\",\n    \"                let mut k: u32 = 0;\\n\",\n    \"\\n\",\n    \"                loop {\\n\",\n    \"                    if k >= norm_row_data.data.len() {\\n\",\n    \"                        break ();\\n\",\n    \"                    };\\n\",\n    \"                    result.append(*norm_row_data.data.at(k));\\n\",\n    \"                    k += 1;\\n\",\n    \"                };\\n\",\n    \"                j += 1;\\n\",\n    \"            };\\n\",\n    \"            x_inputs_normalized =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(\\n\",\n    \"                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\\n\",\n    \"                );\\n\",\n    \"        };\\n\",\n    \"\\n\",\n    \"        // for normalizing 1D feature input\\n\",\n    \"        if x_inputs.shape.len() == 1 {\\n\",\n    \"            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\\n\",\n    \"        };\\n\",\n    \"    }\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() == 1 {\\n\",\n    \"        let mut x_min_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(\\n\",\n    \"            shape: array![1].span(),\\n\",\n    \"            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\\n\",\n    \"                .span()\\n\",\n    \"        );\\n\",\n    \"        let mut diff = ((x_inputs - x_min_tensor));\\n\",\n    \"        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\\n\",\n    \"    };\\n\",\n    \"    return x_inputs_normalized;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// rescales model predictions to standard format\\n\",\n    \"fn rescale_predictions(\\n\",\n    \"    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut rescale_predictions = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut y_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    let mut y_max = y_values.max_in_tensor();\\n\",\n    \"    let mut y_min = y_values.min_in_tensor();\\n\",\n    \"    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\\n\",\n    \"    // convert to tensor format for ease of math operations\\n\",\n    \"    let y_min_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_min].span());\\n\",\n    \"    let y_max_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_max].span());\\n\",\n    \"    let y_range_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_range].span());\\n\",\n    \"\\n\",\n    \"    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\\n\",\n    \"\\n\",\n    \"    return rescale_predictions;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f728e6b9\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Data-preprocessing functions\\n\",\n    \"\\n\",\n    \"It is <b>recommended</b> to normalize data before passing it to the multiple linear regression model since we will be working with 16x16 fixed point numbers in cairo. This will prevent from having overflow issues as we compute the feature gradient values (some of the calculations involve squaring x values which can be relatively large if not normalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 34,\n   \"id\": \"9d23a514\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/data_preprocessing.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 35,\n   \"id\": \"71453638\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/data_preprocessing.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"\\n\",\n    \"%%writefile multiple_linear_regression/src/data_preprocessing.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct Dataset {\\n\",\n    \"    x_values: Tensor<FP16x16>,\\n\",\n    \"    y_values: Tensor<FP16x16>,\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl DataPreprocessing of DatasetTrait {\\n\",\n    \"    fn normalize_dataset(ref self: Dataset) -> Dataset {\\n\",\n    \"        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        // used for multiple_linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() > 1 {\\n\",\n    \"            x_values = normalize_feature_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"        // used for linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() == 1 {\\n\",\n    \"            x_values = normalize_label_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        return Dataset { x_values, y_values };\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 2D Tensor\\n\",\n    \"fn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // transpose to change rows to be columns\\n\",\n    \"    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    let tensor_shape = transposed_tensor.shape;\\n\",\n    \"    let tensor_row_len = *tensor_shape.at(0); // 13 \\n\",\n    \"    let tensor_column_len = *tensor_shape.at(1); //50\\n\",\n    \"    // loop and append max and min row values to corresponding  array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= tensor_row_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"        x_max_array.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"        x_min_array.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"        x_range_array\\n\",\n    \"            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    // convert array to tensor format for ease of math operation\\n\",\n    \"    let mut x_min = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\\n\",\n    \"    let mut x_range = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\\n\",\n    \"    let normalized_tensor = (tensor_data - x_min) / x_range;\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 1D tensor\\n\",\n    \"fn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut tensor_data_ = tensor_data;\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\\n\",\n    \"    // loop through tensor values normalizing and appending to new array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match tensor_data_.data.pop_front() {\\n\",\n    \"            Option::Some(tensor_val) => {\\n\",\n    \"                let mut diff = *tensor_val - tensor_data.min_in_tensor();\\n\",\n    \"                normalized_array.append(diff / range);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        };\\n\",\n    \"    };\\n\",\n    \"    // convert normalized array values to tensor format\\n\",\n    \"    let mut normalized_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"97a3109b\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Multiple Linear Regression Model\\n\",\n    \"\\n\",\n    \"Implement the Multiple Linear Regression functions\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 36,\n   \"id\": \"253241d2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"os.makedirs(f'multiple_linear_regression/src/model/', exist_ok=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 37,\n   \"id\": \"820b7925\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/model/multiple_linear_regression_model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 38,\n   \"id\": \"9fe7721f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/model/multiple_linear_regression_model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/model/multiple_linear_regression_model.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct MultipleLinearRegressionModel {\\n\",\n    \"    coefficients: Tensor<FP16x16>\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl RegressionOperation of MultipleLinearRegressionModelTrait {\\n\",\n    \"    // reconstruct the y values using the computed gradients and x values\\n\",\n    \"    fn predict(\\n\",\n    \"        ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\\n\",\n    \"    ) -> Tensor<FP16x16> {\\n\",\n    \"        // random tensor value that we will replace\\n\",\n    \"        let mut prediction_result = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"        let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"        // for multiple predictions\\n\",\n    \"        if feature_inputs.shape.len() > 1 {\\n\",\n    \"            let feature_values = add_bias_term(feature_inputs, 1);\\n\",\n    \"            let mut data_len: u32 = *feature_values.shape.at(0);\\n\",\n    \"            let mut i: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if i >= data_len {\\n\",\n    \"                    break ();\\n\",\n    \"                }\\n\",\n    \"                let feature_row_values = get_tensor_data_by_row(feature_values, i);\\n\",\n    \"                let predicted_values = feature_row_values.matmul(@self.coefficients);\\n\",\n    \"                result.append(*predicted_values.data.at(0));\\n\",\n    \"                i += 1;\\n\",\n    \"            };\\n\",\n    \"            prediction_result =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![result.len()].span(), data: result.span());\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        // for single predictions \\n\",\n    \"        if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\\n\",\n    \"            let feature_values = add_bias_term(feature_inputs, 1);\\n\",\n    \"            prediction_result = feature_values.matmul(@self.coefficients);\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        return prediction_result;\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\\n\",\n    \"    let x_values_tranposed = transpose_tensor(dataset.x_values);\\n\",\n    \"    let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\\n\",\n    \"    let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\\n\",\n    \"    let coefficients = compute_gradients(\\n\",\n    \"        decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\\n\",\n    \"    );\\n\",\n    \"    return MultipleLinearRegressionModel { coefficients };\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"//Adds bias term to features based on axis\\n\",\n    \"fn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_feature_ = x_feature;\\n\",\n    \"    let mut tensor_with_bias = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // check if feature data has multiple rows and columns\\n\",\n    \"    if x_feature.shape.len() > 1 {\\n\",\n    \"        let mut index: u32 = 0;\\n\",\n    \"        if axis == 1 {\\n\",\n    \"            index = 0;\\n\",\n    \"        } else {\\n\",\n    \"            index = 1;\\n\",\n    \"        }\\n\",\n    \"        let data_len = *x_feature.shape.at(index); // 50\\n\",\n    \"        let mut i: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            if i >= data_len {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            result\\n\",\n    \"                .append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \\n\",\n    \"            i += 1;\\n\",\n    \"        };\\n\",\n    \"        if axis == 0 {\\n\",\n    \"            let res_tensor = TensorTrait::new(\\n\",\n    \"                shape: array![1, data_len].span(), data: result.span()\\n\",\n    \"            );\\n\",\n    \"            tensor_with_bias =\\n\",\n    \"                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\\n\",\n    \"        } else {\\n\",\n    \"            let res_tensor = TensorTrait::new(\\n\",\n    \"                shape: array![data_len, 1].span(), data: result.span()\\n\",\n    \"            );\\n\",\n    \"            tensor_with_bias =\\n\",\n    \"                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\\n\",\n    \"        }\\n\",\n    \"    }\\n\",\n    \"    // check if feature data is 1D\\n\",\n    \"    if x_feature.shape.len() == 1 {\\n\",\n    \"        let mut j: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            match x_feature_.data.pop_front() {\\n\",\n    \"                Option::Some(x_val) => {\\n\",\n    \"                    result.append(*x_val);\\n\",\n    \"                    j += 1;\\n\",\n    \"                },\\n\",\n    \"                Option::None(_) => { break; }\\n\",\n    \"            };\\n\",\n    \"        };\\n\",\n    \"        result.append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \\n\",\n    \"        tensor_with_bias =\\n\",\n    \"            TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\\n\",\n    \"    }\\n\",\n    \"    return tensor_with_bias;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// decorrelates the feature data (*only the last tensor row of the decorelated feature data will be fully orthogonal)\\n\",\n    \"fn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut input_tensor = x_feature_data;\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= *x_feature_data.shape.at(0) {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let mut placeholder = ArrayTrait::<FP16x16>::new();\\n\",\n    \"        let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\\n\",\n    \"        let mut feature_squared = feature_row_values.matmul(@feature_row_values);\\n\",\n    \"        // avoiding division by zero errors\\n\",\n    \"        if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\\n\",\n    \"            feature_squared =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"        }\\n\",\n    \"        // loop throgh remaining tensor data and remove the individual tensor factors from one another \\n\",\n    \"        let mut j: u32 = i + 1;\\n\",\n    \"        loop {\\n\",\n    \"            if j >= *x_feature_data.shape.at(0) {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\\n\",\n    \"            let feature_cross_product = feature_row_values.matmul(@remaining_tensor_values);\\n\",\n    \"            let feature_gradients = feature_cross_product / feature_squared;\\n\",\n    \"            remaining_tensor_values = remaining_tensor_values\\n\",\n    \"                - (feature_row_values\\n\",\n    \"                    * feature_gradients); //remove the feature factors from one another\\n\",\n    \"            // loop and append the modifieed remaining_tensor_values (after the corelated factor has been removed) to placeholder array\\n\",\n    \"            let mut k: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if k >= remaining_tensor_values.data.len() {\\n\",\n    \"                    break ();\\n\",\n    \"                }\\n\",\n    \"                placeholder.append(*remaining_tensor_values.data.at(k));\\n\",\n    \"                k += 1;\\n\",\n    \"            };\\n\",\n    \"\\n\",\n    \"            j += 1;\\n\",\n    \"        };\\n\",\n    \"        // convert placeholder array to tensor format and update the original tensor with the new modified decorrelated tensor row values\\n\",\n    \"        let mut decorrelated_tensor = TensorTrait::new(\\n\",\n    \"            shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\\n\",\n    \"            data: placeholder.span()\\n\",\n    \"        );\\n\",\n    \"        let mut original_tensor = input_tensor\\n\",\n    \"            .slice(\\n\",\n    \"                starts: array![0, 0].span(),\\n\",\n    \"                ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\\n\",\n    \"                axes: Option::None(()),\\n\",\n    \"                steps: Option::Some(array![1, 1].span())\\n\",\n    \"            );\\n\",\n    \"        input_tensor =\\n\",\n    \"            TensorTrait::concat(\\n\",\n    \"                tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\\n\",\n    \"            );\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    return input_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// computes the corresponding MLR gradient using decorrelated feature\\n\",\n    \"fn compute_gradients(\\n\",\n    \"    decorrelated_x_features: Tensor<FP16x16>,\\n\",\n    \"    y_values: Tensor<FP16x16>,\\n\",\n    \"    original_x_tensor_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut gradient_values_flipped = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut tensor_y_vals = y_values;\\n\",\n    \"    let mut i: u32 = *decorrelated_x_features.shape.at(0);\\n\",\n    \"    // loop through Decorrelated_x_features starting from the fully orthogonlised last tensor row value\\n\",\n    \"    loop {\\n\",\n    \"        if i <= 0 {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let index_val = i - 1;\\n\",\n    \"        let mut decorelated_feature_row_values = get_tensor_data_by_row(\\n\",\n    \"            decorrelated_x_features, index_val\\n\",\n    \"        ); // 50 vals\\n\",\n    \"        let mut decorelated_features_squared = decorelated_feature_row_values\\n\",\n    \"            .matmul(@decorelated_feature_row_values);\\n\",\n    \"        let mut feature_label_cross_product = tensor_y_vals\\n\",\n    \"            .matmul(@decorelated_feature_row_values); // multiply the tensors\\n\",\n    \"        // avoiding division by zero errors\\n\",\n    \"        if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\\n\",\n    \"            decorelated_features_squared =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"        }\\n\",\n    \"        // computing the feature gradient values using the y values and decorrelated x features and appending to array\\n\",\n    \"        let mut single_gradient_value = feature_label_cross_product\\n\",\n    \"            / decorelated_features_squared; // devide the summed value by each other\\n\",\n    \"        result.append(*single_gradient_value.data.at(0));\\n\",\n    \"        // remove the assosciated feature gradient value away from y values\\n\",\n    \"        let mut original_x_tensor_row_values = get_tensor_data_by_row(\\n\",\n    \"            original_x_tensor_values, index_val\\n\",\n    \"        );\\n\",\n    \"        tensor_y_vals = tensor_y_vals\\n\",\n    \"            - (original_x_tensor_row_values\\n\",\n    \"                * single_gradient_value); //remove the first feature from second feature values\\n\",\n    \"        i -= 1;\\n\",\n    \"    };\\n\",\n    \"    // convert the gradient array to tensor format\\n\",\n    \"    let final_gradients = TensorTrait::new(\\n\",\n    \"        shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\\n\",\n    \"    );\\n\",\n    \"\\n\",\n    \"    let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut data_len: u32 = final_gradients.data.len();\\n\",\n    \"    loop {\\n\",\n    \"        if data_len <= 0 {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let temp_val = data_len - 1;\\n\",\n    \"        reverse_grad_array.append(*final_gradients.data.at(temp_val));\\n\",\n    \"        data_len -= 1;\\n\",\n    \"    };\\n\",\n    \"    // convert gradient values to tensor format\\n\",\n    \"    let gradient_values_flipped = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\\n\",\n    \"\\n\",\n    \"    return gradient_values_flipped;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \" \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 39,\n   \"id\": \"d269825b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 40,\n   \"id\": \"b762a212\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/model.cairo\\n\",\n    \"mod multiple_linear_regression_model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f700ee3a\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Running tests on model\\n\",\n    \"\\n\",\n    \"Running some checks to ensure the model is performing as expected. Some of the checks involve:\\n\",\n    \"- data normalizations checks\\n\",\n    \"- tensor shape/dimension check\\n\",\n    \"- coefficient value and dimension checks  \\n\",\n    \"- model accuracy deviance checks\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 41,\n   \"id\": \"6df3b8c5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression/src/test.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 42,\n   \"id\": \"6ccda27e\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression/src/test.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression/src/test.cairo\\n\",\n    \"\\n\",\n    \"// use traits::Into;\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use multiple_linear_regresion::datasets::boston_data::boston_x_features::boston_x_features;\\n\",\n    \"use multiple_linear_regresion::datasets::boston_data::boston_y_labels::boston_y_labels;\\n\",\n    \"use multiple_linear_regresion::datasets::user_inputs_data::user_inputs_boston_data::user_inputs_boston_data;\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16,  FixedTrait};\\n\",\n    \"\\n\",\n    \"use multiple_linear_regresion::model::multiple_linear_regression_model::{\\n\",\n    \"     MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\\n\",\n    \"};\\n\",\n    \"use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \\n\",\n    \"calculate_r_score, normalize_user_x_inputs, rescale_predictions};\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \\n\",\n    \"    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\\n\",\n    \"\\n\",\n    \"#[test]\\n\",\n    \"#[available_gas(99999999999999999)]\\n\",\n    \"fn multiple_linear_regression_test() {\\n\",\n    \"\\n\",\n    \"// -------------------------------------------------------------------Boston dataset tests---------------------------------------------------------------------------------------------\\n\",\n    \"\\n\",\n    \"let mut main_x_vals = boston_x_features();\\n\",\n    \"let mut main_y_vals = boston_y_labels();\\n\",\n    \"let mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\\n\",\n    \"let mut normalized_dataset = dataset.normalize_dataset();\\n\",\n    \"let mut model  = MultipleLinearRegression(normalized_dataset);\\n\",\n    \"let mut model_coefficients = model.coefficients;\\n\",\n    \"let mut reconstructed_ys = model.predict (normalized_dataset.x_values);\\n\",\n    \"let mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\\n\",\n    \"r_squared_score.print(); \\n\",\n    \"\\n\",\n    \"// checking if data has been normalized correctly\\n\",\n    \"assert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\\n\",\n    \"assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\\n\",\n    \"assert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\\n\",\n    \"assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\\n\",\n    \"// performing checks on the shape of normalized data\\n\",\n    \"assert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \\n\",\n    \"normalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\\n\",\n    \"// performing checks on shape on coefficient values (gradient vals + bias)\\n\",\n    \"assert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\\n\",\n    \"// model accuracy deviance checks\\n\",\n    \"assert(r_squared_score >= FixedTrait::new(55699, false), 'Boston model acc. less than 84%');\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// boston user inputed house valuation predictions\\n\",\n    \"let user_input = user_inputs_boston_data();\\n\",\n    \"let mut normalized_user_x_inputs = normalize_user_x_inputs(user_input, main_x_vals) ;\\n\",\n    \"let mut prediction_result  = model.predict (normalized_user_x_inputs); \\n\",\n    \"let mut rescale_prediction  = rescale_predictions(prediction_result, main_y_vals);\\n\",\n    \"(*rescale_prediction.data.at(0)).print(); \\n\",\n    \"\\n\",\n    \"\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"52ccc81e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3a36b2e6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.4\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/Provable Multiple Linear Regression Solver (Forecasting AAVE Business metrics).ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"151a8d2d\",\n   \"metadata\": {},\n   \"source\": [\n    \" # Provable  Multiple Linear Regression Solver\\n\",\n    \" \\n\",\n    \"For this particular tutorial, we will build a Multiple Linear Regression algorithm from scratch and use it to <b>forecast the projected the 7-day lifetime repayments for  AAVE's WETH Pool</b>. Toward the end of the tutorial, we will convert the data & model to Cairo enabling us to make the entire Multiple Regression Solver as well as the AAVE's forecasts to be <b>fully Provable and Verifiable. </b>\\n\",\n    \"### Overview & methodology\\n\",\n    \"In many financial business applications, a vast number of problems can be modeled using <b>Multiple Linear Regression.</b> As we step into the on-chain ProvableML domain, these traditional algorithms may still be essential in addressing forecasting and prediction-related business problems. Interestingly, these may prove to be actually advantageous in on-chain environments as they are relatively interpretable, lightweight and cost-efficient.\\n\",\n    \"\\n\",\n    \"The most common method for computing MLR includes the use of pseudo-inverse or  SVD (Singular value decomposition), which can be far more complex to implement than the problem being worked on often times. Hence, the next common approach often preferred are gradient-based methods.  These are perfect for large datasets, but they too can be excessive due to the intensive iterative approach they take to approximate gradients; which in the context of on-chain environments can be fairly expensive. \\n\",\n    \"\\n\",\n    \"<b>This repo presents an intuitive a closed-form (non gradient based) approach to computing MLR gradients to allow builders and end-users to interact with MLR systems with ease and transparency. </b>\\n\",\n    \"\\n\",\n    \"The Multiple Linear regression Solver works in three components:\\n\",\n    \"1. Decorrelates x features from one another (most intensive part)\\n\",\n    \"2. Computes the exact gradients between each decorrelated x feature and target y variables in one step\\n\",\n    \"3. Performs predictions and forecasts using the computed gradients\\n\",\n    \"\\n\",\n    \"#### Provability and Verifiability\\n\",\n    \"<b>The key benefit of this Multiple Linear Regression Solver lies in its commitment to <u>Provability and Verifiability</u>. By integrating it into Cairo using the Orion Framework, we allow the entire MLR system to become inherently provable through STARKs, ensuring unparalleled transparency and trustworthiness. This enables every inference of the model construction, execution and prediction to be easily proved using LambdaClass STARK Prover. </b>\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"90182f06\",\n   \"metadata\": {},\n   \"source\": [\n    \"##  Import necessary libs & prepare dataset\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"f09afc09\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import pandas as pd\\n\",\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import os\\n\",\n    \"from sklearn.metrics import r2_score\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"1f1a3299\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# dataset pulled from https://app.aavescan.com/  \\n\",\n    \"df_main= pd.read_csv('AAVE-V3-weth.csv')\\n\",\n    \"df_main.drop('Unnamed: 0', axis=1, inplace=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"bb21fa7d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# reverse order as the row 1 illustrates the most recent datapoint in terms of date\\n\",\n    \"df_main= df_main.iloc[::-1]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"1d292060\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>accruedToTreasury</th>\\n\",\n       \"      <th>availableLiquidity</th>\\n\",\n       \"      <th>lifetimeFlashLoans</th>\\n\",\n       \"      <th>lifetimeLiquidity</th>\\n\",\n       \"      <th>lifetimeReserveFactorAccrued</th>\\n\",\n       \"      <th>totalLiquidityAsCollateral</th>\\n\",\n       \"      <th>totalScaledVariableDebt</th>\\n\",\n       \"      <th>lifetimeRepayments</th>\\n\",\n       \"      <th>variableBorrowRate</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>30</th>\\n\",\n       \"      <td>9.330000e+18</td>\\n\",\n       \"      <td>7.400000e+22</td>\\n\",\n       \"      <td>1.240000e+23</td>\\n\",\n       \"      <td>2.040000e+24</td>\\n\",\n       \"      <td>5.500000e+20</td>\\n\",\n       \"      <td>1.190000e+24</td>\\n\",\n       \"      <td>2.870000e+23</td>\\n\",\n       \"      <td>7.640000e+23</td>\\n\",\n       \"      <td>3.370000e+25</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>29</th>\\n\",\n       \"      <td>1.340000e+19</td>\\n\",\n       \"      <td>7.450000e+22</td>\\n\",\n       \"      <td>1.240000e+23</td>\\n\",\n       \"      <td>2.050000e+24</td>\\n\",\n       \"      <td>5.500000e+20</td>\\n\",\n       \"      <td>1.190000e+24</td>\\n\",\n       \"      <td>2.870000e+23</td>\\n\",\n       \"      <td>7.640000e+23</td>\\n\",\n       \"      <td>3.370000e+25</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>28</th>\\n\",\n       \"      <td>1.740000e+19</td>\\n\",\n       \"      <td>8.020000e+22</td>\\n\",\n       \"      <td>1.240000e+23</td>\\n\",\n       \"      <td>2.070000e+24</td>\\n\",\n       \"      <td>5.500000e+20</td>\\n\",\n       \"      <td>1.190000e+24</td>\\n\",\n       \"      <td>2.880000e+23</td>\\n\",\n       \"      <td>7.650000e+23</td>\\n\",\n       \"      <td>3.320000e+25</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>27</th>\\n\",\n       \"      <td>2.120000e+19</td>\\n\",\n       \"      <td>9.590000e+22</td>\\n\",\n       \"      <td>1.280000e+23</td>\\n\",\n       \"      <td>2.120000e+24</td>\\n\",\n       \"      <td>5.500000e+20</td>\\n\",\n       \"      <td>1.240000e+24</td>\\n\",\n       \"      <td>2.860000e+23</td>\\n\",\n       \"      <td>7.700000e+23</td>\\n\",\n       \"      <td>3.180000e+25</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>26</th>\\n\",\n       \"      <td>1.660000e+17</td>\\n\",\n       \"      <td>1.000000e+23</td>\\n\",\n       \"      <td>1.410000e+23</td>\\n\",\n       \"      <td>2.150000e+24</td>\\n\",\n       \"      <td>5.750000e+20</td>\\n\",\n       \"      <td>1.280000e+24</td>\\n\",\n       \"      <td>2.870000e+23</td>\\n\",\n       \"      <td>7.730000e+23</td>\\n\",\n       \"      <td>3.150000e+25</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"    accruedToTreasury  availableLiquidity  lifetimeFlashLoans  \\\\\\n\",\n       \"30       9.330000e+18        7.400000e+22        1.240000e+23   \\n\",\n       \"29       1.340000e+19        7.450000e+22        1.240000e+23   \\n\",\n       \"28       1.740000e+19        8.020000e+22        1.240000e+23   \\n\",\n       \"27       2.120000e+19        9.590000e+22        1.280000e+23   \\n\",\n       \"26       1.660000e+17        1.000000e+23        1.410000e+23   \\n\",\n       \"\\n\",\n       \"    lifetimeLiquidity  lifetimeReserveFactorAccrued  \\\\\\n\",\n       \"30       2.040000e+24                  5.500000e+20   \\n\",\n       \"29       2.050000e+24                  5.500000e+20   \\n\",\n       \"28       2.070000e+24                  5.500000e+20   \\n\",\n       \"27       2.120000e+24                  5.500000e+20   \\n\",\n       \"26       2.150000e+24                  5.750000e+20   \\n\",\n       \"\\n\",\n       \"    totalLiquidityAsCollateral  totalScaledVariableDebt  lifetimeRepayments  \\\\\\n\",\n       \"30                1.190000e+24             2.870000e+23        7.640000e+23   \\n\",\n       \"29                1.190000e+24             2.870000e+23        7.640000e+23   \\n\",\n       \"28                1.190000e+24             2.880000e+23        7.650000e+23   \\n\",\n       \"27                1.240000e+24             2.860000e+23        7.700000e+23   \\n\",\n       \"26                1.280000e+24             2.870000e+23        7.730000e+23   \\n\",\n       \"\\n\",\n       \"    variableBorrowRate  \\n\",\n       \"30        3.370000e+25  \\n\",\n       \"29        3.370000e+25  \\n\",\n       \"28        3.320000e+25  \\n\",\n       \"27        3.180000e+25  \\n\",\n       \"26        3.150000e+25  \"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"df_main.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4d06feb5\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Preparing the Features and Labels\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"0eec3df8\",\n   \"metadata\": {},\n   \"source\": [\n    \"Now that we have prepared our AAVE dataset, we will use the features to forecast the <b>lifetime Repayments 7 days in advance</b>. In order to achieve this, we take the lifetime Repayments column and replicate it into a new column whilst shifting the column data upwards by 7 spots. This, will allow us to use this shifted column as our y label and the rest of the data as our X features.\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"id\": \"3a6dc4ba\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#Since Most of the df values are in wei we devide all values by a fixed factor to make the data easy to work with.\\n\",\n    \"# Hence, we devide by 1e+22 to have values in thousands of ETH. \\n\",\n    \"# This will also prevent overflow as we work with 16x16 fixed point numbers in orion as we transition to cairo in later stages \\n\",\n    \"factor = 1e+22\\n\",\n    \"df_main = df_main/factor\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"6b94e8bd\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df= df_main.copy()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"id\": \"629ee65a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"days_to_forecast = -7\\n\",\n    \"df['lifetimeRepayments_7day_forecast'] = df[['lifetimeRepayments']].shift(days_to_forecast) \\n\",\n    \"df = df[0:days_to_forecast]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"id\": \"1a8ac4af\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>accruedToTreasury</th>\\n\",\n       \"      <th>availableLiquidity</th>\\n\",\n       \"      <th>lifetimeFlashLoans</th>\\n\",\n       \"      <th>lifetimeLiquidity</th>\\n\",\n       \"      <th>lifetimeReserveFactorAccrued</th>\\n\",\n       \"      <th>totalLiquidityAsCollateral</th>\\n\",\n       \"      <th>totalScaledVariableDebt</th>\\n\",\n       \"      <th>lifetimeRepayments</th>\\n\",\n       \"      <th>variableBorrowRate</th>\\n\",\n       \"      <th>lifetimeRepayments_7day_forecast</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>30</th>\\n\",\n       \"      <td>0.000933</td>\\n\",\n       \"      <td>7.40</td>\\n\",\n       \"      <td>12.4</td>\\n\",\n       \"      <td>204.0</td>\\n\",\n       \"      <td>0.0550</td>\\n\",\n       \"      <td>119.0</td>\\n\",\n       \"      <td>28.7</td>\\n\",\n       \"      <td>76.4</td>\\n\",\n       \"      <td>3370.0</td>\\n\",\n       \"      <td>77.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>29</th>\\n\",\n       \"      <td>0.001340</td>\\n\",\n       \"      <td>7.45</td>\\n\",\n       \"      <td>12.4</td>\\n\",\n       \"      <td>205.0</td>\\n\",\n       \"      <td>0.0550</td>\\n\",\n       \"      <td>119.0</td>\\n\",\n       \"      <td>28.7</td>\\n\",\n       \"      <td>76.4</td>\\n\",\n       \"      <td>3370.0</td>\\n\",\n       \"      <td>77.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>28</th>\\n\",\n       \"      <td>0.001740</td>\\n\",\n       \"      <td>8.02</td>\\n\",\n       \"      <td>12.4</td>\\n\",\n       \"      <td>207.0</td>\\n\",\n       \"      <td>0.0550</td>\\n\",\n       \"      <td>119.0</td>\\n\",\n       \"      <td>28.8</td>\\n\",\n       \"      <td>76.5</td>\\n\",\n       \"      <td>3320.0</td>\\n\",\n       \"      <td>77.5</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>27</th>\\n\",\n       \"      <td>0.002120</td>\\n\",\n       \"      <td>9.59</td>\\n\",\n       \"      <td>12.8</td>\\n\",\n       \"      <td>212.0</td>\\n\",\n       \"      <td>0.0550</td>\\n\",\n       \"      <td>124.0</td>\\n\",\n       \"      <td>28.6</td>\\n\",\n       \"      <td>77.0</td>\\n\",\n       \"      <td>3180.0</td>\\n\",\n       \"      <td>77.6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>26</th>\\n\",\n       \"      <td>0.000017</td>\\n\",\n       \"      <td>10.00</td>\\n\",\n       \"      <td>14.1</td>\\n\",\n       \"      <td>215.0</td>\\n\",\n       \"      <td>0.0575</td>\\n\",\n       \"      <td>128.0</td>\\n\",\n       \"      <td>28.7</td>\\n\",\n       \"      <td>77.3</td>\\n\",\n       \"      <td>3150.0</td>\\n\",\n       \"      <td>78.0</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"    accruedToTreasury  availableLiquidity  lifetimeFlashLoans  \\\\\\n\",\n       \"30           0.000933                7.40                12.4   \\n\",\n       \"29           0.001340                7.45                12.4   \\n\",\n       \"28           0.001740                8.02                12.4   \\n\",\n       \"27           0.002120                9.59                12.8   \\n\",\n       \"26           0.000017               10.00                14.1   \\n\",\n       \"\\n\",\n       \"    lifetimeLiquidity  lifetimeReserveFactorAccrued  \\\\\\n\",\n       \"30              204.0                        0.0550   \\n\",\n       \"29              205.0                        0.0550   \\n\",\n       \"28              207.0                        0.0550   \\n\",\n       \"27              212.0                        0.0550   \\n\",\n       \"26              215.0                        0.0575   \\n\",\n       \"\\n\",\n       \"    totalLiquidityAsCollateral  totalScaledVariableDebt  lifetimeRepayments  \\\\\\n\",\n       \"30                       119.0                     28.7                76.4   \\n\",\n       \"29                       119.0                     28.7                76.4   \\n\",\n       \"28                       119.0                     28.8                76.5   \\n\",\n       \"27                       124.0                     28.6                77.0   \\n\",\n       \"26                       128.0                     28.7                77.3   \\n\",\n       \"\\n\",\n       \"    variableBorrowRate  lifetimeRepayments_7day_forecast  \\n\",\n       \"30              3370.0                              77.4  \\n\",\n       \"29              3370.0                              77.4  \\n\",\n       \"28              3320.0                              77.5  \\n\",\n       \"27              3180.0                              77.6  \\n\",\n       \"26              3150.0                              78.0  \"\n      ]\n     },\n     \"execution_count\": 8,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"df.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"id\": \"cf992ac6\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"(24, 9)\\n\",\n      \"(24,)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#Drop the y label from dataframe\\n\",\n    \"features = df.drop(['lifetimeRepayments_7day_forecast'], axis=1)\\n\",\n    \"#setting our y label\\n\",\n    \"target = df['lifetimeRepayments_7day_forecast']\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"# convert data to numpy format\\n\",\n    \"X_original = features.to_numpy()\\n\",\n    \"Y_original = target.to_numpy()\\n\",\n    \"\\n\",\n    \"print(X_original.shape)\\n\",\n    \"print(Y_original.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d5c31a01\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Normalize the data\\n\",\n    \"Normalize the data so that all the features values are between 0-1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"id\": \"e4551bc6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def normalize_data(original_data):\\n\",\n    \"    data_min = np.min(original_data, axis=0)\\n\",\n    \"    data_max = np.max(original_data, axis=0)\\n\",\n    \"    data_range = data_max - data_min\\n\",\n    \"    data_normalized =  (original_data - data_min) / data_range\\n\",\n    \"    \\n\",\n    \"    return data_normalized\\n\",\n    \"    \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"id\": \"9a50f392\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Features max value: 1.0\\n\",\n      \"Features min value: 0.0\\n\",\n      \"Labels max value: 1.0\\n\",\n      \"Labels min value: 0.0\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# normalize the data \\n\",\n    \"X_normalized= normalize_data(X_original)\\n\",\n    \"y_normalized= normalize_data(Y_original)\\n\",\n    \"\\n\",\n    \"print('Features max value:', X_normalized.max())\\n\",\n    \"print('Features min value:', X_normalized.min())\\n\",\n    \"print('Labels max value:', y_normalized.max())\\n\",\n    \"print('Labels min value:', y_normalized.min())\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"310c1a0a\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Main Multiple Linear Regression algorythm\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"id\": \"8a5a52b6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def transpose_and_add_bias(feature_data):\\n\",\n    \"    #transpose the data\\n\",\n    \"    transposed_data= feature_data.T\\n\",\n    \"    #add bias term\\n\",\n    \"    transposed_data_with_bias = np.vstack((transposed_data, np.ones(transposed_data.shape[1])))\\n\",\n    \"    \\n\",\n    \"    return transposed_data_with_bias\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"c8d6ed24\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### Decorelate the x features\\n\",\n    \"It's <b>very important</b> to notice that as we decorrelate the X features, only the last feature row will be fully <b>orthogonal</b>. The rest of the features are  decorrelated from one another but <b>are not fully orthogonal to each other</b>. This is done to save on computational cost and make the algorythm more efficient. This will enable us to calculate the following feature gradients much easier and quicker, than if we were to fully orthogonalize all the features and then compute the gradients.\\n\",\n    \"\\n\",\n    \"Later when we compute the gradients we will start from the last fully orthogonalised feature values and walk backwards to calculate the correponding gradinets, whilst removing their component from the y variable. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"id\": \"e3c5b44c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def decorrelate_features(feature_data):\\n\",\n    \"\\n\",\n    \"    # Make copy of input matrix\\n\",\n    \"    x_temp = feature_data.copy()\\n\",\n    \"    \\n\",\n    \"    # Get number of features\\n\",\n    \"    feature_rows = feature_data.shape[0]\\n\",\n    \"    \\n\",\n    \"    # Decorrelate features\\n\",\n    \"    for i in range(feature_rows):\\n\",\n    \"        feature_squared = np.sum(x_temp[i]**2)\\n\",\n    \"        for j in range(i+1, feature_rows):\\n\",\n    \"            feature_cross_prod = np.sum(x_temp[i] * x_temp[j])\\n\",\n    \"            if feature_squared == 0:\\n\",\n    \"                print('Warning, division by zero encountered and handled')\\n\",\n    \"                feature_squared = 1e-8 \\n\",\n    \"            feature_grad = feature_cross_prod / feature_squared\\n\",\n    \"            x_temp[j] -= feature_grad * x_temp[i]\\n\",\n    \"            \\n\",\n    \"    decorelated_x_vals = x_temp\\n\",\n    \"\\n\",\n    \"    return decorelated_x_vals\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"74fa9460\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### Calculating Gradients\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"id\": \"42de0d6e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def calculate_gradients(decorelated_x_vals, y_values, original_x_features):\\n\",\n    \"  \\n\",\n    \"    # Initialize gradients array\\n\",\n    \"    # Make copy of input matrix\\n\",\n    \"    y_temp = y_values.copy()\\n\",\n    \"    feature_rows = decorelated_x_vals.shape[0]\\n\",\n    \"    gradients = np.zeros(feature_rows)\\n\",\n    \"\\n\",\n    \"    # Calculate gradients\\n\",\n    \"    for i in range(feature_rows-1, -1, -1):\\n\",\n    \"        prod = np.sum(y_temp * decorelated_x_vals[i])\\n\",\n    \"        squared = np.sum(decorelated_x_vals[i] * decorelated_x_vals[i])\\n\",\n    \"        if squared == 0:\\n\",\n    \"            print('Warning, division by zero encountered and handled')\\n\",\n    \"            squared = 1e-8\\n\",\n    \"\\n\",\n    \"        gradients[i] = prod / squared\\n\",\n    \"        y_temp -= gradients[i] * original_x_features[i]\\n\",\n    \"    \\n\",\n    \"\\n\",\n    \"    return gradients\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"id\": \"3c7c3fc3\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Training data shapes:\\n\",\n      \"X_normalized: (10, 24)\\n\",\n      \"y_normalized: (24,)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"X_normalized_transposed_with_bias = transpose_and_add_bias(X_normalized)\\n\",\n    \"\\n\",\n    \"print(\\\"Training data shapes:\\\")\\n\",\n    \"print(\\\"X_normalized:\\\", X_normalized_transposed_with_bias.shape)\\n\",\n    \"print(\\\"y_normalized:\\\", y_normalized.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"id\": \"f96a6e15\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"decorrelated_X_features = decorrelate_features(X_normalized_transposed_with_bias)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"id\": \"8815700e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"gradient_values = calculate_gradients(decorrelated_X_features, y_normalized, X_normalized_transposed_with_bias )\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"id\": \"169a41b4\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"All regression coefficient:  [-1.27062243  1.15931271  0.173401   -0.31112069  1.09338439  0.93959362\\n\",\n      \" -1.12956438 -0.08371113  1.18734043  0.3425375 ]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"real_gradient_values_reversed = np.flip(gradient_values)\\n\",\n    \"print('All regression coefficient: ', real_gradient_values_reversed )\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d6134a53\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Reconstructing the y labels using the calculated gradients and X feature data\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"id\": \"a1bda8ed\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def denormalize_data(original_data,normalized_data):\\n\",\n    \"    data_min = np.min(original_data)\\n\",\n    \"    data_max = np.max(original_data)\\n\",\n    \"    data_range = data_max - data_min\\n\",\n    \"    \\n\",\n    \"    denormalize_data = ( normalized_data * data_range) + data_min\\n\",\n    \"    return denormalize_data\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"id\": \"17b37869\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"R^2 score (denormalized): 0.9968099033369738\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAkAAAAHFCAYAAAAaD0bAAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAACSm0lEQVR4nOzdd3hT1RvA8W/SvaGFLkZbNoVCQTbIUPaQJUOQKYIbRKY/9hRQZIiiiCB7iAiKbJlSlmWD7FJWKat7J+f3RyQSW6CBltD2/TxPHppz7z33vWlI3t6zNEophRBCCCFEHqK1dABCCCGEEM+bJEBCCCGEyHMkARJCCCFEniMJkBBCCCHyHEmAhBBCCJHnSAIkhBBCiDxHEiAhhBBC5DmSAAkhhBAiz5EESAghhBB5jiRAIs8KCwtDo9Hw+eefP3Y/f39/evbsaVJ25MgR6tWrh5ubGxqNhhkzZmT6vAkJCYwZM4adO3em27Zw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Q/qyKgJ7N69e7z33nsUKlQIW1tbihUrxv/+9z+Sk5NN9tNoNHzwwQcsXryYsmXL4ujoSMWKFfntt99M9rt9+zZ9+/alSJEixtehdu3abNu2LXMvush15A6QEGZ40ERVs2ZNXn/9dT755BPjtoiICKpVq4ZWq2XUqFEUL16ckJAQJkyYQFhYGAsWLMDHx4dNmzbRtGlT3nrrLfr06QPwxLs+ERER9OrViyFDhlC4cGFmz55N7969uXr1Kj/99BOffvopbm5ujBs3jjZt2nDp0iV8fX0BQ7NLrVq1KFq0KF988QXe3t5s3ryZjz76iDt37jB69OjHnvvy5csAlCpVyqxrfdhXX32Fn58fM2bMQK/XM3XqVJo1a8auXbuoWbMmADdu3MDDw4PPPvuMggULcu/ePX788UeqV6/OkSNHKF26NM7OzvTu3ZvvvvuOqVOn4ubmZjzH119/ja2tLb179zY5d58+fWjXrh0rVqzgyJEjfPrpp6SlpXH27FnatWtH37592bZtG1OmTMHX15eBAwcCoNfrad26NXv27GHIkCHUqlWLK1euMHr0aOrXr8/hw4dxcHAwnufYsWN88sknDBs2DC8vL77//nveeustSpQoQd26dWnRogWTJk3i008/Zc6cOVSuXBmA4sWLP/b1z8iFCxcA0/dNSkoKr732Gv369WPYsGGkpaWZdQ1vv/02ixYtYtCgQTRq1IiTJ0/Srl07YmNjnxjP5s2badWqFWXLlmX69OkULVqUsLAwY9+xPn36cO/ePWbPns3PP/9sbOJ91J2fpKQkGjRowMWLFxk7diwVKlRgz549TJ48maNHj7JhwwaT/Tds2MChQ4cYN24czs7OTJ06lbZt23L27FmKFSsGQLdu3QgNDWXixImUKlWKqKgoQkNDuXv3rpmvvsg1lBB51OXLlxWgpk2b9tj9/Pz8VI8ePUzKAPX++++blPXr1085OzurK1eumJR//vnnClCnTp1SSil1+/ZtBajRo0enO9eCBQsUoC5fvmwsq1evngLU4cOHjWV3795VVlZWysHBQV2/ft1YfvToUQWoWbNmGcuaNGmiChcurKKjo03O9cEHHyh7e3t17949k9djypQpKjU1VSUlJamj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c8jIiLSXZgegLZs2UJFRQWzZs3qdP9bb72FYRj88pe/7HR/RUUFdru9/f7x48d58MEHqa6uJjg4mBEjRrB9+3ZGjx7dJfVfSRv3VPLY23tobvUyMqY/f8xKo39QgNlliYiI9DjdZhF0d+LrzwEyDIOXt39F7ua/AzA50c1z01N89pUWIiIiPcFVtwjaylq9Bos3lvLGZ21fCTLrhjievP1fuuQrLERERKSNApCJTjW38shbn1P0vzXYbPAft/+M2ePjzC5LRESkx1MAMsnRhiZmF+5iz5HjBPSy8/z0FCYnhZtdloiIiCUoAJng4NFGsl/7GxXHTtKvjz9/zEojLTbE7LJEREQsQwHIx3Yf/o45hTv57uQZokJ6UzBzNEMHneMzfkRERKRLKAD5UHFZLXPf2E1Ti5frBgfzavYoBjl98AnUIiIi0oECkA/FDQgiyNGL8df0Y8V9I+gToF+/iIiIGfQK7EOxA4NYO28cUf1708vPfuEHiIiISJdQAPKxuIH6ji0RERGzaRpCRERELEcBSERERCxHAUhEREQsRwFIRERELEcBSERERCxHAUhEREQsRwFIRERELEcBSERERCxHAUhEREQsRwFIRERELEcBSERERCxHAUhEREQsRwFIRERELEffBt8JwzAA8Hg8JlciIiIiF+uH1+0fXsfPRwGoE/X19QBERUWZXImIiIhcqvr6eoKDg897jM24mJhkMV6vl8rKSpxOJzab7Yq27fF4iIqK4siRI7hcrivatlw89UP3oH7oHtQP3YP64fIZhkF9fT0RERHY7edf5aMZoE7Y7XYGDx7cpc/hcrn0B94NqB+6B/VD96B+6B7UD5fnQjM/P9AiaBEREbEcBSARERGxHAUgH3M4HCxatAiHw2F2KZamfuge1A/dg/qhe1A/+JYWQYuIiIjlaAZIRERELEcBSERERCxHAUhEREQsRwFIRERELEcByIdefPFF4uLiCAwMZOTIkezYscPskixl8eLF2Gy2Dje32212WZawfft2pkyZQkREBDabjfXr13fYbxgGixcvJiIigt69e3PzzTdTWlpqTrE92IX6YcaMGWeNkTFjxphTbA+Vm5vLqFGjcDqdhIaGMnXqVMrKyjoco/HgG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Z3fY73K5mD59Oq+88gpr1qxh7dq1HDt2zFenJCJdRGuAROSq1NTURHV1Na2trdTU1PDhhx+Sm5vLHXfcQVZWFvv27aOlpYUVK1YwZcoU/vKXv/DSSy+d1U7//v3JzMxk4cKFZGRkMHjw4PZ9zz33HOHh4aSkpGC323nnnXdwu93069fPh2cqIl1BM0AiclX68MMPCQ8PJzY2lkmTJlFcXExeXh4bNmzAz8+PlJQUli9fzrPPPktiYiKrV68+5yXss2fPprm5mVmzZnXY3rdvX5599lnS0tIYNWoUhw4d4oMPPsBu13+dIlc7m2EYhtlFiIiYafXq1Tz66KNUVlYSEBBgdjki4gN6C0xELOvkyZMcPHiQ3Nxcfv3rXyv8iFiI5nFFxLKWLl1KSkoKYWFh/O53vzO7HBHxIb0FJiIiIpajGSARERGxHAUgERERsRwFIBEREbEcBSARERGxHAUgERERsRwFIBEREbEcBSARERGxHAUgERERsRwFIBEREbGc/wN63R3OPTyAhwAAAABJRU5ErkJggg==\",\n      \"text/plain\": [\n       \"<Figure size 640x480 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"y_pred_norm = gradient_values @ X_normalized_transposed_with_bias #prediction#\\n\",\n    \"reconstructed_y = denormalize_data(Y_original,y_pred_norm) \\n\",\n    \"# Plot the denormalized y values\\n\",\n    \"plt.figure(2)\\n\",\n    \"plt.title(\\\" LifetimeRepayment Predictions\\\")\\n\",\n    \"plt.plot(reconstructed_y )\\n\",\n    \"plt.plot(Y_original)\\n\",\n    \"plt.legend([\\\" Actual y values\\\", \\\"reconstructed ys (predictions)\\\"])\\n\",\n    \"plt.xlabel('Days')\\n\",\n    \"plt.ylabel('Lifetime Repayment (thousands ETH)')\\n\",\n    \"\\n\",\n    \"# Calculate R^2 score for denormalized prediction\\n\",\n    \"accuracy_denormalized = r2_score(Y_original, reconstructed_y)\\n\",\n    \"print(\\\"R^2 score (denormalized):\\\", accuracy_denormalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b8296c8b\",\n   \"metadata\": {},\n   \"source\": [\n    \"# The upcoming 7 day Total lifetime repayments forecasts for AAVE's WETH Pool\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"id\": \"bb721ff0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df_forecast = df_main[-7:]\\n\",\n    \"df_forecast_data = df_forecast.to_numpy()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"id\": \"5ba45802\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_min = np.min(X_original, axis=0)\\n\",\n    \"X_max = np.max(X_original, axis=0)\\n\",\n    \"X_range = X_max - X_min\\n\",\n    \"df_forecast_data_normalized =    (df_forecast_data - X_min) / X_range\\n\",\n    \"# print(df_forecast_data_normalized.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"id\": \"c8d18eb5\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Training data shapes:\\n\",\n      \"X_normalized: (9, 7)\\n\",\n      \"y_normalized: (10, 7)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# tranpose the matrix and add ones \\n\",\n    \"df_forecast_data_normalized_transposed= df_forecast_data_normalized.T\\n\",\n    \"df_forecast_data_normalized_transposed_with_bias = np.vstack((df_forecast_data_normalized_transposed, np.ones(df_forecast_data_normalized_transposed.shape[1])))\\n\",\n    \"print(\\\"Training data shapes:\\\")\\n\",\n    \"print(\\\"X_normalized:\\\", df_forecast_data_normalized_transposed.shape)\\n\",\n    \"print(\\\"y_normalized:\\\", df_forecast_data_normalized_transposed_with_bias.shape)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"id\": \"5df80bde\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"0 1.0782944838728898\\n\",\n      \"1 1.1357059848525208\\n\",\n      \"2 1.1665048712468642\\n\",\n      \"3 1.193423550976403\\n\",\n      \"4 1.2455779743568984\\n\",\n      \"5 1.3032904853814864\\n\",\n      \"6 1.3668000624508785\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"forecast_normalized = gradient_values @ df_forecast_data_normalized_transposed_with_bias\\n\",\n    \"for i in range(len(forecast_normalized)):\\n\",\n    \"    print(i,forecast_normalized[i])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 25,\n   \"id\": \"84ea2dd4\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Tomorrow's Lifetime Repayment from Weth pool Forecast:  95.62317677745183\\n\",\n      \"Day 2 Lifetime Repayment from Weth pool Forecast 96.5934311440076\\n\",\n      \"Day 3 Lifetime Repayment from Weth pool Forecast 97.113932324072\\n\",\n      \"Day 4 Lifetime Repayment from Weth pool Forecast 97.5688580115012\\n\",\n      \"Day 5 Lifetime Repayment from Weth pool Forecast 98.45026776663158\\n\",\n      \"Day 6 Lifetime Repayment from Weth pool Forecast 99.42560920294711\\n\",\n      \"Day 7 Lifetime Repayment from Weth pool Forecast 100.49892105541984\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#denormalize forecast\\n\",\n    \"Y_min = np.min(Y_original, axis=0)\\n\",\n    \"Y_max = np.max(Y_original, axis=0)\\n\",\n    \"Y_range = Y_max - Y_min\\n\",\n    \"\\n\",\n    \"forecast_pred =  (forecast_normalized * Y_range) + Y_min\\n\",\n    \"# # print(forecast_pred)\\n\",\n    \"for i in range(len(forecast_pred)):\\n\",\n    \"    if i==0:\\n\",\n    \"        print(\\\"Tomorrow's Lifetime Repayment from Weth pool Forecast: \\\",forecast_pred[i])\\n\",\n    \"    else:\\n\",\n    \"        print('Day',i+1,'Lifetime Repayment from Weth pool Forecast',forecast_pred[i])\\n\",\n    \"        \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 26,\n   \"id\": \"01f96e7f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAA1IAAAHUCAYAAAAwUBnrAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAAC/qklEQVR4nOzdd3iT5frA8W+SZnVvOiht2XvJEJClKHs5QOHIFAciooDiUbSIoqAMJ3pQhojihKOyBFmigExFQGaZbSmU7jZNkzy/P/prDqEttNAF3J/ryiV55/2+aWLuPM9zPxqllEIIIYQQQgghRLFpKzoAIYQQQgghhLjRSCIlhBBCCCGEECUkiZQQQgghhBBClJAkUkIIIYQQQghRQpJICSGEEEIIIUQJSSIlhBBCCCGEECUkiZQQQgghhBBClJAkUkIIIYQQQghRQpJICSGEEEIIIUQJSSIlRAVbuHAhGo2myMebb755xf03btzosr3BYCAoKIh27drx4osvcvLkyXK6koKKuqbAwMAKi6m8xMXFERMTw969e0u032effUZQUBDp6ekF1uXm5hISEoJGo+Hbb7+96rEuXLiA0WhEo9Gwc+dO5/Lz589jMBh48MEHi9w3LS0Nd3d3+vTpA1z973Tjxo3OfaOiooiJiSn+RRfhwIEDxMTEcOLEiWs+xsqVK687lmHDhhEVFXXFbcaMGYNGoyEhIcFl+cWLF9Fqtej1ejIyMlzWnTlzBo1Gw7PPPgvAiRMnrniPY2JiCrzfr/SA/71ul77+l+rVq9dVr62oexAVFcWwYcNclu3Zs4eOHTvi4+ODRqNhzpw5Vz12vqysLOc1Xi7/Oq7nb+FaXf66aLVa/Pz8uOuuu/j555/LPZ6b0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DVr1iy1bt069dVXX6kRI0aogwcPKqWUSklJUcOGDVOLFy9W69evV6tXr1YTJkxQWq1WLVq0yHms33//XWk0GvXggw+qlStXqvXr16sFCxaohx9+WCmlVGpqqlqwYIEC1EsvvaS2bt2qtm7dqk6fPl3kvTp9+rQC1Icffljo+tdff10BasWKFcrhcKjIyEgVHR3tvJeXGzVqlALU/v37VVpamnJ3d1edOnVy2eall15SgNq7d6/L8okTJyrAeV+UUs7r2bZtW4HX02azFXldSin12GOPKXd3dzVr1iy1YcMG9dNPP6k333xTvffee0Xuk5iYqKZNm6YA9cEHHzjvYWJiolJKOdc99NBDasWKFeqzzz5T1atXVz4+Purw4cNKKaWOHj2q7r//fgU499+6dauyWCxKqby/77lz56rVq1er9evXq9mzZ6vAwEA1fPhwl1iGDh2qIiMjr3iNSin19NNPK0DFxcUppZS6cOGC0mg0as2aNWrVqlVKp9Op1NRUpZRSp06dUoCaOHGic//8v/Pp06cXuMe5ublFnjcyMlL17Nmz0HVXet1yc3NVjx49inVthd2DyMhINXToUKVU3uu1detWBaj777/fea+VUio+Pl5FRESoyMhI9fHHH6t169apqVOnKqPRqIYNG6aUUspisajVq1crQI0cOdK5/9GjR12uIzY21nn+jh07qoCAAFWnTh316aefqjVr1qhevXopQE2ZMkU1atRIffnll2rlypXq9ttvV0ajUZ09e9a5//79+5WPj49q1KiR+uyzz9TPP/+sxo8fr7RarYqJiSnwurz11lsu1//3338rQD311FPOZcW51kuPGRERoe644w713XffqW+++Ua1bNlS6fV69fvvvzu3Le3P6/x7GR0drcaPH69+/vlnNX36dKXT6dRDDz2kmjdvrl577TW1du1a9fzzzytAzZw503k8u92uunXrpjw8PNSUKVPU2rVr1SeffKLCw8NV/fr1VVZWlsvfSNWqVVX9+vXVZ599ptasWaMeeOABBahNmzY5/3au9F5XSqlz584pQL377rtKiMpEEikhKpmDBw8qQD322GPF2r44iVTr1q2V2Wwucr3NZlNWq1XVqlVLPfPMM87lx44dU1qtVs2ePdu5LDs7WwUEBBT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QCnFvHnzruv68hOpKVOmoNVqXV6z/H/nz5V0tb/vm0WvXr1YuXIlNWrUKHTOsnwlfc9cD3d3dzp37syePXto3LixszWmJAYPHswnn3zCvHnzmDhxIpGRkcW+1nzff/89b731lrMlOj09nR9//JH27ds7u/FWls/rfL169WLp0qXY7XZat25dKse82mtvs9k4ffq083NLiMpCEikhKon88tYDBw4s1v+AL3fkyBG2bduGw+FwTsj76aefkpaWxmeffeby5bxXr14sXLiQunXr0rhxY3bt2sVbb71VZNe3f/3rX7zwwgts3ryZl1566Zq+dBTmmWee4bPPPqNnz568+uqrREZGsmLFCj788EOeeOIJateufdVjfPzxx3Tv3p2uXbsybNgwwsPDuXjxIgcPHmT37t188803ALz66qusWrWKDh068O9//5tGjRqRkpLC6tWrefbZZ6lbty69evXi+++/Z/To0dx///2cPn2aqVOnEhoa6tIN7eWXX+bMmTPcddddVK1alZSUFN555x30er2zK1eNGjUwm80sWbKEevXq4enpSVhYWJG/vrdu3Rqz2cy2bdvo06ePc/mnn36Kn58fEyZMKLTb35AhQ5g1axZ//vknDRo04LPPPqNevXpFjrHr3bs3P/zwA+fPn3eWmx45ciQffPABs2bNom7durRt27bI+/3333+7lHHOV6NGjSLn+WndujW9evWicePG+Pn5cfDgQRYvXkybNm2KTKIgb84qgP/85z94eXlhMpmIjo4mICCAyZMn8+9//5shQ4bw0EMPkZSUxJQpUzCZTLzyyivOY+TPnTZ9+nS6d++OTqejcePG3H333RgMBh566CGee+45LBYLc+fOJTk5uch4iqNDhw7odDqWLVtWoOuer68vTZo0YdmyZej1etq1a1foMU6dOlVgfA7ktarWqFHjuuKrCK+++ipr166lbdu2jB07ljp16mCxWDhx4gQrV67ko48+omrVqnh5eREZGcl///tf7rrrLvz9/QkMDCyzVoh33nmHO+64g/bt2/PEE08QFRVFeno6R48e5ccffywwRrMw06dPp3Xr1kydOpVPPvmk2NeaT6fTcffdd/Pss8/icDiYPn06aWlpzmQbKs/ndb4HH3yQJUuW0KNHD55++mlatWqFXq/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31153rn3/+eWrXro27uzvVq1dn8uTJ5Obmlvian3rqKWbNmkViYmKR21itVp577jnCw8Px8PCgdevWbNy4EeCK96IwGo2GkJAQQkNDadGiBc888wwnT57k0KFDzm1+//13OnTogNlsJiIigrFjx5KZmQnACy+8wO23317guI0bN+aVV15xPl+wYAH16tXDZDJRt25dPvzwQ+e6/Na477//ns6dO+Pu7k6TJk3YunWrc5vCukbOmTOHqKgol2VXOo8QQgghxK1C5pEqoexcO/VfXlMh5z7walfcDWX7kg0ePJhmzZoxd+5cdDode/fuRa/X07ZtW+bMmcPLL7/sTAA8PT2BvG6ER44c4YcffsDb25vnn3+eHj16cODAAfR6PQBZWVm88cYbfPLJJwQEBBTaCvbCCy8wb948Zs+ezR133EF8fDz//POPc72XlxcLFy4kLCyMffv2MWrUKLy8vHjuuedKdI0PPfQQa9eu5dVXX+X9998vdJvhw4dz4sQJli5dSlhYGMuWLaNbt27s27fvivfialJSUvjiiy8AnPdm3759dO3alalTp/Lpp59y/vx5xowZw5gxY1iwYAGDBw/mzTff5NixY9SoUQOA/fv3s2/fPr799lsA5s2bxyuvvML7779Ps2bN2LNnD6NGjcLDw4OhQ4c6z//iiy/y9ttvU6tWLV588UUeeughjh49iptb8f6uinseIYQQQojicigHF7MvopQiyCOoosMpNkmkbmI//fRTgS/4drv9ivucOnWKiRMnUrduXQBq1arlXOfj4+NsXcmXn0D99ttvtG3bFoAlS5YQERHB8uXLeeCBBwDIzc3lww8/pEmTJoWeNz09nXfeeYf333/f+YW8Ro0a3HHHHc5tXnrpJee/o6KiGD9+PF999VWJEymNRsObb75J7969eeaZZ5zJSb5jx47x5ZdfcubMGcLCwgCYMGECq1evZsGCBUybNq3Qe1GU1NRUPD0981ozs7IA6NOnj/Mev/XWWwwaNIhx48YBeff83XffpWPHjsydO5eGDRvSuHFjvvjiCyZPngzk3eOWLVtSu3ZtAKZOncrMmTO59957AYiOjubAgQN8/PHHLgnOhAkT6NmzJwBTpkyhQYMGHD161BnL1RT3PEIII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Pjjz+SlpbGyJEjefLJJ53Jwdy5c3n22Wd588036d69O6mpqfz2229A3putX79+eHh4sGnTJmw2G6NHj2bgwIFs3LjReY5jx46xatUqVq9ezbFjx7j//vuJjY2ldu3abNq0id9//50RI0Zw1113cfvttxcZ64svvsjbb79NrVq1ePHFF3nooYc4evQobm5u/Pbbbzz++ONMnz6dPn36sG7dOiZPnlyie/HDDz9w4cIFhg0bdsXthg0bxunTp1m/fj0Gg4GxY8eSmJjoso1Wq+Xdd98lKiqK2NhYRo8ezXPPPceHH36Ih4cHDz74IAsWLOD+++937pP/3MvLq8A533nnHWrUqMF//vMfduzYgU6XV2b0ueee47vvvmPRokVERkYyY8YMunbtytGjR/H393fu/9xzz/H2229TvXp1fH19eemll/j++++ZO3cutWrVYvPmzfzrX/8iKCiIjh07cvbsWTp06ECnTp1Yv3493t7e/Pbbb9hsNgDS09MZOnQo7777LgAzZ86kR48eHDlyBC8vL7799ltmz57N0qVLadCgAQkJCfz5558AfP/99zRp0oRHH32UUaNGleg1EkIIIUTZyLHlkJiZyPms8+i1+nJthdLmpoHOWC7nKi2SSAksFguLFi2iatWqALz33nv07NmTmTNnEhISwmuvvcb48eN5+umnnfu0bNkSgHXr1vHXX38RGxtLREQEAIsXL6ZBgwbs2LHDuZ3D4WD+/Pl4eXlRv359OnfuzKFDh1i5ciVarZY6deowffp0Nm7ceMVEasKECfTs2ROAKVOm0KBBA44ePUrdunV577336N69OxMmTACgdu3a/P777/z000/FvheffvopXbt2dV5LYQ4fPsyqVavYtm0brVu3du5Xr149l+0uHaMWHR3N1KlTeeKJJ/jwww8BeOSRR2jbti1xcXGEhYVx4cIFfvrpJ9auXVvoeX18fPDy8kKn0zm7PWZmZjJ37lwWLlzoHE82b9481q5dy6effsrEiROd+7/66qvcfffdzv1mzZrF+vXradOmDQDVq1dny5YtfPzxx3Ts2JEPPvgAHx8fli5dil6vd97TfHfeeadLfB9//DF+fn5s2rSJXr16cerUKUJCQujSpQt6vZ5q1arRqlUrAPz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Mrl27yM7OpmbNmmzZsoXdu3czduzYYsWzYsUK7r33Xnr27MmePXucCUC+YcOGsXPnTn744Qe2bt2KUooePXqQm/u/VrisrCzefvttFi9ezObNmzl16hQTJkwAYMKECc5Wtfj4+AJJTb6JEyeyYcMGli1bxs8//8zGjRvZtWuXyzbDhw/nt99+Y+nSpfz111888MADdOvWzSWxu1IsAHPnzuXJJ5/k0UcfZd++ffzwww/UrJk3GFMpRc+ePUlISGDlypXs2rWL5s2bc9ddd3Hx4sVi3c98L774IjNnzmTnzp24ubkxYsQIAAYOHMj48eNp0KCB834MHDiw2Oc+evQoX3/9Nd999x179+7l/vvv58KFC2zYsMG5TXJyMmvWrGHw4MFA3pxwPXr0YN26dezZs4euXbvSu3dvTp06VaJrEkIIIW5FSilSLakcv3ic02mn0Wv1BJgDyqUbny47jsA9YwnZeh/G1D9xuHmSXGcSce1/JjukK5RTQYsbkXTtuwl5eXnRpk0bpk6dSr169ahSpQpffvkl27dvp1atWs7tunfvzgMPPEBkZCSxsbFMnjyZO++8k127dmE0GunatSv/+te/aNmyJWazmUWLFuHh4cETTzzBwoULmTt3Lu+99x6BgYH85z//oUGDBoXG8/rrr/Pggw8yZcoU57ImTZoAcOTIEX744Qd+++032rZtC8CSJUuIiIhg+fLlPPDAA0BeF7OPPvqIGjVqADBmzBheffVVADw9PfH19QUosgtcRkYGn376KZ999hl33303AIsWLaJq1arObY4dO8aXX37JmTNnCAsLA/KStNWrV7NgwQKmTZt21VgAXnvtNcaPH8/TTz/tXNayZUsANmzYwL59+0hMTHR2PXz77bdZvnw53377LY8++mih8Rd1Xzt27AjApEmT6NmzJxaLBbPZjKenJ25ubi73Y/369cU6t9VqZfHixQQFBTn37datG1988QV33XUXAN988w3+/v7O502aNHG+pvn3YNmyZfzwww8urXFCCCGEcJWdm+2sxqfT6sqtG5/Gno33sY/wPv4xWocFhYaMqgNIqTMehzG4zM9/M5BE6ia1ePFiRowYQXh4ODqdjubNmzNo0CB2797t3GbgwIHOfzds2JA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Pb1ditrrnHPO4YEHHqBXr14MHjyYZcuWMWvWLKZMmQJAfX0906dP58ILL6SwsJDNmzdz5513kpOTw/nnn9+utYmIdDXRmMnyKg9bPI0AFKcl8+HaKh5fsIGYCcUZKTx8yQjGlGUluFIREZHEi2s46e67725ubx4Khbj//vv3C1OzZs1qs+Ief/xx7rrrLm688UaqqqooKipi6tSp3H333UDT6NSqVat45plnqKuro7CwkAkTJvDyyy/jcrnarA4Rka6uMRzl44paagNhAIpTHcx4cy0ryusAOP/YYu49dzDu5LZdCysiItJZtbpr36mnnnrYxcSGYbBgwYI2Kexoam1nDhGRrqi6McTH22sJRmPYLQYNvjD3vrmGhlAUV7KNB84fyneHFyW6TBERkaOizbv2vfvuu21Rl4iIdCCb6hpYvtODCThtVt5esp23llUAMLZ3Fr+9eATFGSmJLVJERKQDar9OESIi0mHFTJMVO71s8jQAkITBfa+sZntdI3arwf9MHMD1J/fGalFbcxERkQNRkBIR6WYCkSj/railurFpPdSOXQ38798+B6BPrpNHLz2WIcXt20xIRESks1OQEhHpJqIxk02eBtZV1xOMxrAAf1u8nX+t3gnAVSeUcMeZx5CSZE1soSIiIp2AgpSISBcXM0027wlQjZGmffiikRi/+ds6KmobyUlL4qGLhnHawPwEVyoiItJ5KEiJiHRRMdOk3NvI2t2+5gAVCkf55Itq3lqynWjM5PSBeTx40TBy0hwJrlZERKRz+UZB6v333+f//u//2LhxI6+++irFxcU8++yzlJWVcdJJJ7V1jSIi0grhaIxNu/18Vulju7eRNJedtJSmfZ+8DWH+vbKSj77YTSRqkmy3cO93B3PF8b0Ou7WFiIiI7C/uIPXaa6/x/e9/nyuuuIJly5YRDAYB8Pl8zJgxg7fffrvNixQRkX1M06TSG+DzSh/r9jw+2+Hly11++he7mHRsEUV5TZun+wMRFqzayYbtXnrnpnHtiWUMLHQxtnc2helqay4iIvJNtXpD3r2OPfZYbrnlFq666ipcLhcrVqygd+/eLF++nEmTJlFZWdletbYbbcgrIh2VLxDmi52+5tC096NnT8e9v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iIiIiIhInBSkREREREZE4KUiJiIiIiIjESUFKREREREQkTgpSIiIiIiIicVKQEhERERERiZOClIiIiIiISJwUpEREREREROKkICUiIiIiIhInBSkREREREZE4KUiJiIiIiIjESUFKREREREQkTgpSIiIiIiIicbIluoCOwDRNALxeb4IrERERERGRRNqbCfZmhINRkAJ8Ph8APXv2THAlIiIiIiLSEfh8PtLT0w/6vGEeLmp1A7FYjIqKClwuF4ZhJLQWr9dLz549KS8vx+12J7QWaTu6rl2PrmnXo2vaNem6dj26pl1TR7qupmni8/koKirCYjn4SiiNSAEWi4UePXokuowW3G53wv8nkran69r16Jp2PbqmXZOua9eja9o1dZTreqiRqL3UbEJERERERCROClIiIiIiIiJxUpDqYBwOB/fccw8OhyPRpUgb0nXtenRNux5d065J17Xr0TXtmjrjdVWzCRERERERkThpREpERERERCROClIiIiIiIiJxUpASERERERGJk4KUiIiIiIhInBSkOpjf//73lJWVkZyczHHHHcf777+f6JLkG5o+fTqGYbR4FBQUJLosidN//vMfzjnnHIqKijAMgzfffLPF86ZpMn36dIqKikhJSeHUU09lzZo1iSlWWuVw1/Tqq6/e794dO3ZsYoqVVpk5cyajR4/G5XKRl5fHeeedx7p161qco3u1c2nNNdW92vn84Q9/YNiwYc2b7p5wwgn84x//aH6+s92nClIdyMsvv8zNN9/ML37xC5YtW8bJJ5/MmWeeydatWxNdmnxDgwcPZseOHc2PVatWJbokiZPf72f48OH87ne/O+DzDz30ELNmzeJ3v/sdixcvpqCggDPOOAOfz3eUK5XWOtw1BZg0aVKLe/ftt98+ihVKvN577z1+9KMf8fHHHzN//nwikQgTJ07E7/c3n6N7tXNpzTUF3audTY8ePfj1r3/NkiVLWLJkCaeddhrnnntuc1jqdPepKR3GmDFjzBtuuKHFsYEDB5o///nPE1SRHIl77rnHHD58eKLLkDYEmG+88Ubz17FYzCwoKDB//etfNx8LBAJmenq6OXv27ARUKPH6+jU1TdOcPHmyee655yakHmkbVVVVJmC+9957pmnqXu0Kvn5NTVP3aleRmZlp/vnPf+6U96lGpDqIUCjEp59+ysSJE1scnzhxIh9++GGCqpIjtX79eoqKiigrK+PSSy/lyy+/THRJ0oY2bdpEZWVli/vW4XBwyimn6L7t5N59913y8vLo378/119/PVVVVYkuSeLg8XgAyMrKAnSvdgVfv6Z76V7tvKLRKC+99BJ+v58TTjihU96nClIdxO7du4lGo+Tn57c4np+fT2VlZYKqkiNx/PHH88wzz/DPf/6TP/3pT1RWVjJu3Diqq6sTXZq0kb33pu7bruXMM8/k+eefZ8GCBfz2t79l8eLFnHbaaQSDwUSXJq1gmia33norJ510EkOGDAF0r3Z2B7qmoHu1s1q1ahVpaWk4HA5uuOEG3njjDQYNGtQp71NboguQlgzDaPG1aZr7HZPO4cwzz2z+fOjQoZxwwgn06dOHp59+mltvvTWBlUlb033btVxyySXNnw8ZMoRRo0ZRUlLC3//+dy644IIEViatcdNNN7Fy5UoWLVq033O6Vzung11T3aud04ABA1i+fDl1dXW89tprTJ48mffee6/5+c50n2pEqoPIycnBarXul7irqqr2S+bSOTmdToYOHcr69esTXYq0kb1dGHXfdm2FhYWUlJTo3u0EfvzjHzN37lwWLlxIjx49mo/rXu28DnZND0T3aueQlJRE3759GTVqFDNnzmT48OE8+uijnfI+VZDqIJKSkjjuuOOYP39+i+Pz589n3LhxCapK2lIwGOSzzz6jsLAw0aVIGykrK6OgoKDFfRsKhXjvvfd033Yh1dXVlJeX697twEzT5KabbuL1119nwYIFlJWVtXhe92rnc7hreiC6Vzsn0zQJBoOd8j7V1L4O5NZbb+X73/8+o0aN4oQTTuCPf/wjW7du5YYbbkh0afIN3HbbbZxzzjn06tWLqqoq7r//frxeL5MnT050aRKH+vp6NmzY0Pz1pk2bWL58OVlZWfTq1Yubb76ZGTNm0K9fP/r168eMGTNITU3l8ssvT2DVciiHuqZZWVlMnz6dCy+8kMLCQjZv3sydd95JTk4O559/fgKrlkP50Y9+xAsvvMBbb72Fy+Vq/o12eno6KSkpGIahe7WTOdw1ra+v173aCd15552ceeaZ9OzZE5/Px0svvcS7777LO++80znv04T1C5QDeuKJJ8ySkhIzKSnJHDlyZIs2n9K5XHLJJWZhYaFpt9vNoqIi84ILLjDXrFmT6LIkTgsXLjSB/R6TJ082TbOprfI999xjFhQUmA6Hwxw/fry5atWqxBYth3Soa9rQ0GBOnDjRzM3NNe12u9mrVy9z8uTJ5tatWxNdthzCga4nYM6ZM6f5HN2rncvhrqnu1c5pypQpzT/n5ubmmqeffro5b9685uc7231qmKZpHs3gJiIiIiIi0tlpjZSIiIiIiEicFKRERERERETipCAlIiIiIiISJwUpERERERGROClIiYiIiIiIxElBSkREREREJE4KUiIiIiIiInFSkBIREREREYmTgpSIiIiIiEicFKRERKTLuPrqqzEMA8MwsNvt5Ofnc8YZZ/Dkk08Si8USXZ6IiHQhClIiItKlTJo0iR07drB582b+8Y9/MGHCBKZNm8Z3vvMdIpFIossTEZEuQkFKRES6FIfDQUFBAcXFxYwcOZI777yTt956i3/84x889dRTAMyaNYuhQ4fidDrp2bMnN954I/X19QD4/X7cbjevvvpqi/f961//itPpxOfzEQqFuOmmmygsLCQ5OZnS0lJmzpx5tL9VERFJIAUpERHp8k477TSGDx/O66+/DoDFYuGxxx5j9erVPP300yxYsIDbb78dAKfTyaWXXsqcOXNavMecOXO46KKLcLlcPPbYY8ydO5e//OUvrFu3jueee47S0tKj/W2JiEgC2RJdgIiIyNEwcOBAVq5cCcDNN9/cfLysrIxf/epX/PCHP+T3v/89ANdddx3jxo2joqKCoqIidu/ezd/+9jfmz58PwNatW+nXrx8nnXQShmFQUlJy1L8fERFJLI1IiYhIt2CaJoZhALBw4ULOOOMMiouLcblcXHXVVVRXV+P3+wEYM2YMgwcP5plnngHg2WefpVevXowfPx5oamqxfPlyBgwYwE9+8hPmzZuXmG9KREQSRkFKRES6hc8++4yysjK2bNnCWWedxZAhQ3jttdf49NNPeeKJJwAIh8PN51933XXN0/vmzJnDNddc0xzERo4cyaZNm/jVr35FY2MjF198MRdddNHR/6ZERCRhFKRERKTLW7BgAatWreLCCy9kyZIlRCIRfvvb3zJ27Fj69+9PRUXFfq+58sor2bp1K4899hhr1qxh8uTJLZ53u91ccskl/OlPf+Lll1/mtddeo6am5mh9SyIikmBaIyUiIl1KMBiksrKSaDTKzp07eeedd5g5cybf+c53uOqqq1i1ahWRSITHH3+cc845hw8++IDZs2fv9z6ZmZlccMEF/PSnP2XixIn06NGj+bmHH36YwsJCRowYgcVi4ZVXXqGgoICMjIyj+J2KiEgiaURKRES6lHfeeYfCwkJKS0uZNGkSCxcu5LHHHuOtt97CarUyYsQIZs2axYMPPsiQIUN4/vnnD9q6/NprryUUCjFlypQWx9PS0njwwQcZNWoUo0ePZvPmzbz99ttYLPpnVUSkuzBM0zQTXYSIiEhH9PzzzzNt2jQqKipISkpKdDkiItKBaGqfiIjI1zQ0NLBp0yZmzpzJ1KlTFaJERGQ/moMgIiLyNQ899BAjRowgPz+fO+64I9HliIhIB6SpfSIiIiIiInHSiJSIiIiIiEicFKRERERERETipCAlIiIiIiISJwUpERERERGROClIiYiIiIiIxElBSkREREREJE4KUiIiIiIiInFSkBIREREREYnT/we1mC6bTb13xgAAAABJRU5ErkJggg==\",\n      \"text/plain\": [\n       \"<Figure size 1000x500 with 1 Axes>\"\n      ]\n     },\n     \"metadata\": {},\n     \"output_type\": \"display_data\"\n    }\n   ],\n   \"source\": [\n    \"forecast_plot_data = np.insert(forecast_pred, 0, Y_original[-1])\\n\",\n    \"\\n\",\n    \"# Calculate expanding confidence intervals\\n\",\n    \"residual = Y_original - reconstructed_y\\n\",\n    \"stderr = np.std(residual)\\n\",\n    \"z_score = 1.96 # z-score for 95% CI\\n\",\n    \"intervals = z_score *stderr * np.sqrt(np.arange(len(forecast_plot_data)))\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"# Creating the plot\\n\",\n    \"plt.figure(figsize=(10, 5))\\n\",\n    \"plt.plot(Y_original , label='Historical lifetime repayments')\\n\",\n    \"plt.plot(len(Y_original)-1 + np.arange(len(forecast_plot_data)), forecast_plot_data , color='orange', label='Upcoming 7 day forecast')\\n\",\n    \"plt.fill_between(len(Y_original)-1 + np.arange(len(forecast_plot_data)),  \\n\",\n    \"                 (forecast_plot_data - intervals),\\n\",\n    \"                 (forecast_plot_data + intervals),\\n\",\n    \"                 alpha=0.12,\\n\",\n    \"                color='green',\\n\",\n    \"                label='95% confidence interval')\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"plt.plot(reconstructed_y ,  label=\\\"Model's Predictions\\\", color='lightblue')\\n\",\n    \"# Adding labels and title\\n\",\n    \"plt.xlabel('Days')\\n\",\n    \"plt.ylabel('Lifetime Repayment (thousands ETH)')\\n\",\n    \"plt.title(\\\" 7 Day Forecast (AAVE's total WETH lifetimeRepayment)\\\")\\n\",\n    \"plt.legend()\\n\",\n    \"\\n\",\n    \"# Display the plot\\n\",\n    \"plt.show()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8af06223\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Transition to Cairo\\n\",\n    \"## Create a scarb project\\n\",\n    \"\\n\",\n    \"Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 27,\n   \"id\": \"9d3cb826\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Created `multiple_linear_regression_aave` package.\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"! scarb new multiple_linear_regression_aave\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 28,\n   \"id\": \"df9e40c3\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!echo -n > multiple_linear_regression_aave/src/lib.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"38ac62e4\",\n   \"metadata\": {},\n   \"source\": [\n    \"A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\\n\",\n    \"```toml\\n\",\n    \"[package]\\n\",\n    \"name = \\\"multiple_linear_regresion\\\"\\n\",\n    \"version = \\\"0.1.0\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"[dependencies]\\n\",\n    \"orion = { git = \\\"https://github.com/gizatechxyz/onnx-cairo\\\" }\\n\",\n    \"\\n\",\n    \"[scripts]\\n\",\n    \"test = \\\"scarb cairo-test -f multiple_linear_regression_test\\\"\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 29,\n   \"id\": \"e366fe1f\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"ename\": \"SyntaxError\",\n     \"evalue\": \"invalid syntax (252576425.py, line 3)\",\n     \"output_type\": \"error\",\n     \"traceback\": [\n      \"\\u001b[0;36m  Cell \\u001b[0;32mIn [29], line 3\\u001b[0;36m\\u001b[0m\\n\\u001b[0;31m    mod test;\\u001b[0m\\n\\u001b[0m        ^\\u001b[0m\\n\\u001b[0;31mSyntaxError\\u001b[0m\\u001b[0;31m:\\u001b[0m invalid syntax\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# add reference modules to help our code compile at the end\\n\",\n    \"%%writefile -a src/lib.cairo \\n\",\n    \"mod test;\\n\",\n    \"mod data_preprocessing;\\n\",\n    \"mod helper_functions;\\n\",\n    \"mod datasets;\\n\",\n    \"mod model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"c0340f15\",\n   \"metadata\": {},\n   \"source\": [\n    \"\\n\",\n    \"## Generate Cairo files\\n\",\n    \"\\n\",\n    \"Now, we will transition our model to cairo. We will start by converting the the X features and Y labels to FP16x16 tensors numbers. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 30,\n   \"id\": \"39b6b561\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Convert the original data to Cairo \\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def generate_cairo_files(data, name, folder_name):\\n\",\n    \"    \\n\",\n    \"    os.makedirs(f'multiple_linear_regression_aave/src/datasets/{folder_name}', exist_ok=True)\\n\",\n    \"    with open(os.path.join('multiple_linear_regression_aave/src/datasets', f'{folder_name}', f\\\"{name}.cairo\\\"), \\\"w\\\") as f:\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"use array::ArrayTrait;\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\\\n\\\" +\\n\",\n    \"                \\\"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\\\n\\\" +\\n\",\n    \"                \\\"use orion::numbers::{FP16x16, FixedTrait};\\\\n\\\\n\\\" +\\n\",\n    \"                \\\"fn {0}() ->  Tensor<FP16x16>  \\\".format(name) + \\\"{\\\\n\\\" +\\n\",\n    \"                \\\"    let tensor = TensorTrait::<FP16x16>::new( \\\\n\\\"\\n\",\n    \"            )\\n\",\n    \"            \\n\",\n    \"            if len(data.shape)>1:\\n\",\n    \"                f.write(\\\"    shape: array![{0},\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\\"{0}].span(),\\\\n\\\".format(data.shape[1]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            if len(data.shape)==1:\\n\",\n    \"                f.write(\\\"    shape: array![{0}].span(),\\\\n\\\".format(data.shape[0]))\\n\",\n    \"                f.write(\\n\",\n    \"                    \\\"    data: array![ \\\\n\\\"\\n\",\n    \"                )\\n\",\n    \"            for val in np.nditer(data.flatten()):\\n\",\n    \"                f.write(\\\"    FixedTrait::new({0}, {1} ),\\\\n\\\".format(abs(int(val * 2**16)), str(val < 0).lower()))\\n\",\n    \"            f.write(\\n\",\n    \"                \\\"].span() \\\\n \\\\n\\\" +\\n\",\n    \"                \\\");\\\\n\\\\n\\\"+\\n\",\n    \"                \\\"return tensor; \\\\n\\\"+\\n\",\n    \"                \\\"}\\\"\\n\",\n    \"            )\\n\",\n    \"    with open(os.path.join('multiple_linear_regression_aave/src/datasets', f'{folder_name}.cairo'), 'a') as f:\\n\",\n    \"        f.write(f\\\"mod {name};\\\\n\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 31,\n   \"id\": \"1a0e7a71\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(X_original, 'aave_x_features', 'aave_data')\\n\",\n    \"generate_cairo_files(Y_original, 'aave_y_labels', 'aave_data')\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 32,\n   \"id\": \"b8c2b804\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"generate_cairo_files(df_forecast_data, 'aave_weth_revenue_data_input', 'user_inputs_data')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 33,\n   \"id\": \"fb316caf\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# add reference modules to help our code compile\\n\",\n    \"! touch multiple_linear_regression_aave/src/datasets.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 34,\n   \"id\": \"fa5fb2be\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/datasets.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/datasets.cairo\\n\",\n    \"mod aave_data;\\n\",\n    \"mod user_inputs_data;\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 35,\n   \"id\": \"b9af5716\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/datasets/aave_data.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 36,\n   \"id\": \"230ac6ed\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/datasets/aave_data.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/datasets/aave_data.cairo\\n\",\n    \"mod aave_x_features;\\n\",\n    \"mod aave_y_labels;\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 37,\n   \"id\": \"4d57b462\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 38,\n   \"id\": \"fe4d136a\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo\\n\",\n    \"mod aave_weth_revenue_data_input;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8cb7f589\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Helper functions \\n\",\n    \"\\n\",\n    \"We add some helper functions to make it easier to construct our MLR model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 39,\n   \"id\": \"cd34a054\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/helper_functions.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 40,\n   \"id\": \"a9d33776\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/helper_functions.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/helper_functions.cairo\\n\",\n    \"\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"\\n\",\n    \"// retrieves row data by index in a 2D tensor\\n\",\n    \"fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\\n\",\n    \"    let column_len = *tensor_data.shape.at(1); //13\\n\",\n    \"    // crete new array\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // loop through the x values and append values \\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= column_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        result.append(tensor_data.at(indices: array![row_index, i].span()));\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    let resultant_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(array![column_len].span(), data: result.span());\\n\",\n    \"    return resultant_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// transposes tensor\\n\",\n    \"fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    return tensor_transposed;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\\n\",\n    \"    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\\n\",\n    \"    let mean = *sum_result / tensor_size;\\n\",\n    \"    return mean;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// Calculates the R-Squared score between two tensors.\\n\",\n    \"fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\\n\",\n    \"    let mut Y_values_ = Y_values;\\n\",\n    \"    let mean_y_value = calculate_mean(Y_values);\\n\",\n    \"    // creating the appropriate tensor shapes and empty arrays to populate values into\\n\",\n    \"    let mut squared_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_diff_vals = array::ArrayTrait::new();\\n\",\n    \"    let mut squared_mean_diff_shape = array::ArrayTrait::new();\\n\",\n    \"    squared_mean_diff_shape.append(Y_values.data.len());\\n\",\n    \"    let mut squared_mean_diff_vals = array::ArrayTrait::new();\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match Y_values_.data.pop_front() {\\n\",\n    \"            Option::Some(y_value) => {\\n\",\n    \"                let diff_pred = *y_value - *Y_pred_values.data.at(i);\\n\",\n    \"                let squared_diff = diff_pred * diff_pred;\\n\",\n    \"                squared_diff_vals.append(squared_diff);\\n\",\n    \"\\n\",\n    \"                let diff_mean = *y_value - mean_y_value;\\n\",\n    \"                let squared_mean_diff = diff_mean * diff_mean;\\n\",\n    \"                squared_mean_diff_vals.append(squared_mean_diff);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        }\\n\",\n    \"    };\\n\",\n    \"\\n\",\n    \"    let squared_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_diff_shape.span(), squared_diff_vals.span());\\n\",\n    \"    let squared_mean_diff_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\\n\",\n    \"    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let sum_squared_mean_diff = squared_mean_diff_tensor\\n\",\n    \"        .cumsum(0, Option::None(()), Option::None(()));\\n\",\n    \"    let r_score = FixedTrait::new_unscaled(1, false)\\n\",\n    \"        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\\n\",\n    \"            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\\n\",\n    \"\\n\",\n    \"    return r_score;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\\n\",\n    \"fn normalize_user_x_inputs(\\n\",\n    \"    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_inputs_normalized = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut x_min = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() > 1 {\\n\",\n    \"        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\\n\",\n    \"        let data_len = *transposed_tensor.shape.at(0); //13\\n\",\n    \"        // loop through each row calculating the min, max and range row values for each feature columns\\n\",\n    \"        let mut i: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            if i >= data_len {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"            x_min.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"            x_max.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"            x_range\\n\",\n    \"                .append(\\n\",\n    \"                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\\n\",\n    \"                );\\n\",\n    \"            i += 1;\\n\",\n    \"        };\\n\",\n    \"        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::new(\\n\",\n    \"            shape: array![data_len].span(), data: x_range.span()\\n\",\n    \"        );\\n\",\n    \"\\n\",\n    \"        // for normalizing 2D user inputed feature vals\\n\",\n    \"        if x_inputs.shape.len() > 1 {\\n\",\n    \"            let mut j: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if j >= *x_inputs.shape.at(0) {\\n\",\n    \"                    break ();\\n\",\n    \"                };\\n\",\n    \"                let mut row_data = get_tensor_data_by_row(x_inputs, j);\\n\",\n    \"                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\\n\",\n    \"                let mut k: u32 = 0;\\n\",\n    \"\\n\",\n    \"                loop {\\n\",\n    \"                    if k >= norm_row_data.data.len() {\\n\",\n    \"                        break ();\\n\",\n    \"                    };\\n\",\n    \"                    result.append(*norm_row_data.data.at(k));\\n\",\n    \"                    k += 1;\\n\",\n    \"                };\\n\",\n    \"                j += 1;\\n\",\n    \"            };\\n\",\n    \"            x_inputs_normalized =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(\\n\",\n    \"                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\\n\",\n    \"                );\\n\",\n    \"        };\\n\",\n    \"\\n\",\n    \"        // for normalizing 1D feature input\\n\",\n    \"        if x_inputs.shape.len() == 1 {\\n\",\n    \"            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\\n\",\n    \"        };\\n\",\n    \"    }\\n\",\n    \"\\n\",\n    \"    if original_x_values.shape.len() == 1 {\\n\",\n    \"        let mut x_min_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\\n\",\n    \"        let mut x_max_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\\n\",\n    \"        let mut x_range_tensor = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(\\n\",\n    \"            shape: array![1].span(),\\n\",\n    \"            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\\n\",\n    \"                .span()\\n\",\n    \"        );\\n\",\n    \"        let mut diff = ((x_inputs - x_min_tensor));\\n\",\n    \"        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\\n\",\n    \"    };\\n\",\n    \"    return x_inputs_normalized;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// rescales model predictions to standard format\\n\",\n    \"fn rescale_predictions(\\n\",\n    \"    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut rescale_predictions = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut y_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut y_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"\\n\",\n    \"    let mut y_max = y_values.max_in_tensor();\\n\",\n    \"    let mut y_min = y_values.min_in_tensor();\\n\",\n    \"    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\\n\",\n    \"    // convert to tensor format for ease of math operations\\n\",\n    \"    let y_min_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_min].span());\\n\",\n    \"    let y_max_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_max].span());\\n\",\n    \"    let y_range_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![y_range].span());\\n\",\n    \"\\n\",\n    \"    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\\n\",\n    \"\\n\",\n    \"    return rescale_predictions;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"22a08abf\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Data-preprocessing functions\\n\",\n    \"\\n\",\n    \"It is <b>recommended</b> to normalize data before passing it to the multiple linear regression model since we will be working with 16x16 fixed point numbers in cairo. This will prevent from having overflow issues as we compute the feature gradient values (some of the calculations involve squaring x values which can be relatively large if not normalized)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 41,\n   \"id\": \"9995e498\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/data_preprocessing.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 42,\n   \"id\": \"f559dab1\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/data_preprocessing.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"\\n\",\n    \"%%writefile multiple_linear_regression_aave/src/data_preprocessing.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct Dataset {\\n\",\n    \"    x_values: Tensor<FP16x16>,\\n\",\n    \"    y_values: Tensor<FP16x16>,\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl DataPreprocessing of DatasetTrait {\\n\",\n    \"    fn normalize_dataset(ref self: Dataset) -> Dataset {\\n\",\n    \"        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\\n\",\n    \"        // used for multiple_linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() > 1 {\\n\",\n    \"            x_values = normalize_feature_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"        // used for linear_regression_models\\n\",\n    \"        if self.x_values.shape.len() == 1 {\\n\",\n    \"            x_values = normalize_label_data(self.x_values);\\n\",\n    \"            y_values = normalize_label_data(self.y_values);\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        return Dataset { x_values, y_values };\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 2D Tensor\\n\",\n    \"fn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_min_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_max_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut x_range_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // transpose to change rows to be columns\\n\",\n    \"    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\\n\",\n    \"    let tensor_shape = transposed_tensor.shape;\\n\",\n    \"    let tensor_row_len = *tensor_shape.at(0); // 13 \\n\",\n    \"    let tensor_column_len = *tensor_shape.at(1); //50\\n\",\n    \"    // loop and append max and min row values to corresponding  array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= tensor_row_len {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\\n\",\n    \"        x_max_array.append(transposed_tensor_row.max_in_tensor());\\n\",\n    \"        x_min_array.append(transposed_tensor_row.min_in_tensor());\\n\",\n    \"        x_range_array\\n\",\n    \"            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    // convert array to tensor format for ease of math operation\\n\",\n    \"    let mut x_min = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\\n\",\n    \"    let mut x_range = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\\n\",\n    \"    let normalized_tensor = (tensor_data - x_min) / x_range;\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// normalizes 1D tensor\\n\",\n    \"fn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut tensor_data_ = tensor_data;\\n\",\n    \"    let mut normalized_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\\n\",\n    \"    // loop through tensor values normalizing and appending to new array\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"\\n\",\n    \"    loop {\\n\",\n    \"        match tensor_data_.data.pop_front() {\\n\",\n    \"            Option::Some(tensor_val) => {\\n\",\n    \"                let mut diff = *tensor_val - tensor_data.min_in_tensor();\\n\",\n    \"                normalized_array.append(diff / range);\\n\",\n    \"                i += 1;\\n\",\n    \"            },\\n\",\n    \"            Option::None(_) => { break; }\\n\",\n    \"        };\\n\",\n    \"    };\\n\",\n    \"    // convert normalized array values to tensor format\\n\",\n    \"    let mut normalized_tensor = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\\n\",\n    \"    return normalized_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"12784736\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Multiple Linear Regression Model\\n\",\n    \"\\n\",\n    \"Implement the Multiple Linear Regression functions\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 43,\n   \"id\": \"ea7c8acc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"os.makedirs(f'multiple_linear_regression_aave/src/model/', exist_ok=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 44,\n   \"id\": \"543d3c63\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/model/multiple_linear_regression_model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 45,\n   \"id\": \"24d21d37\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/model/multiple_linear_regression_model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/model/multiple_linear_regression_model.cairo\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\\n\",\n    \"    FP16x16TensorDiv, FP16x16TensorMul\\n\",\n    \"};\\n\",\n    \"use orion::numbers::{FP16x16, FixedTrait};\\n\",\n    \"use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{\\n\",\n    \"    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\\n\",\n    \"    normalize_user_x_inputs, rescale_predictions\\n\",\n    \"};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"#[derive(Copy, Drop)]\\n\",\n    \"struct MultipleLinearRegressionModel {\\n\",\n    \"    coefficients: Tensor<FP16x16>\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"#[generate_trait]\\n\",\n    \"impl RegressionOperation of MultipleLinearRegressionModelTrait {\\n\",\n    \"    // reconstruct the y values using the computed gradients and x values\\n\",\n    \"    fn predict(\\n\",\n    \"        ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\\n\",\n    \"    ) -> Tensor<FP16x16> {\\n\",\n    \"        // random tensor value that we will replace\\n\",\n    \"        let mut prediction_result = TensorTrait::<\\n\",\n    \"            FP16x16\\n\",\n    \"        >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"        let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"        // for multiple predictions\\n\",\n    \"        if feature_inputs.shape.len() > 1 {\\n\",\n    \"            let feature_values = add_bias_term(feature_inputs, 1);\\n\",\n    \"            let mut data_len: u32 = *feature_values.shape.at(0);\\n\",\n    \"            let mut i: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if i >= data_len {\\n\",\n    \"                    break ();\\n\",\n    \"                }\\n\",\n    \"                let feature_row_values = get_tensor_data_by_row(feature_values, i);\\n\",\n    \"                let predicted_values = feature_row_values.matmul(@self.coefficients);\\n\",\n    \"                result.append(*predicted_values.data.at(0));\\n\",\n    \"                i += 1;\\n\",\n    \"            };\\n\",\n    \"            prediction_result =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![result.len()].span(), data: result.span());\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        // for single predictions \\n\",\n    \"        if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\\n\",\n    \"            let feature_values = add_bias_term(feature_inputs, 1);\\n\",\n    \"            prediction_result = feature_values.matmul(@self.coefficients);\\n\",\n    \"        }\\n\",\n    \"\\n\",\n    \"        return prediction_result;\\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"fn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\\n\",\n    \"    let x_values_tranposed = transpose_tensor(dataset.x_values);\\n\",\n    \"    let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\\n\",\n    \"    let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\\n\",\n    \"    let coefficients = compute_gradients(\\n\",\n    \"        decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\\n\",\n    \"    );\\n\",\n    \"    return MultipleLinearRegressionModel { coefficients };\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"//Adds bias term to features based on axis\\n\",\n    \"fn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\\n\",\n    \"    let mut x_feature_ = x_feature;\\n\",\n    \"    let mut tensor_with_bias = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    // check if feature data has multiple rows and columns\\n\",\n    \"    if x_feature.shape.len() > 1 {\\n\",\n    \"        let mut index: u32 = 0;\\n\",\n    \"        if axis == 1 {\\n\",\n    \"            index = 0;\\n\",\n    \"        } else {\\n\",\n    \"            index = 1;\\n\",\n    \"        }\\n\",\n    \"        let data_len = *x_feature.shape.at(index); // 50\\n\",\n    \"        let mut i: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            if i >= data_len {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            result\\n\",\n    \"                .append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \\n\",\n    \"            i += 1;\\n\",\n    \"        };\\n\",\n    \"        if axis == 0 {\\n\",\n    \"            let res_tensor = TensorTrait::new(\\n\",\n    \"                shape: array![1, data_len].span(), data: result.span()\\n\",\n    \"            );\\n\",\n    \"            tensor_with_bias =\\n\",\n    \"                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\\n\",\n    \"        } else {\\n\",\n    \"            let res_tensor = TensorTrait::new(\\n\",\n    \"                shape: array![data_len, 1].span(), data: result.span()\\n\",\n    \"            );\\n\",\n    \"            tensor_with_bias =\\n\",\n    \"                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\\n\",\n    \"        }\\n\",\n    \"    }\\n\",\n    \"    // check if feature data is 1D\\n\",\n    \"    if x_feature.shape.len() == 1 {\\n\",\n    \"        let mut j: u32 = 0;\\n\",\n    \"        loop {\\n\",\n    \"            match x_feature_.data.pop_front() {\\n\",\n    \"                Option::Some(x_val) => {\\n\",\n    \"                    result.append(*x_val);\\n\",\n    \"                    j += 1;\\n\",\n    \"                },\\n\",\n    \"                Option::None(_) => { break; }\\n\",\n    \"            };\\n\",\n    \"        };\\n\",\n    \"        result.append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \\n\",\n    \"        tensor_with_bias =\\n\",\n    \"            TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\\n\",\n    \"    }\\n\",\n    \"    return tensor_with_bias;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// decorrelates the feature data (*only the last tensor row of the decorelated feature data will be fully orthogonal)\\n\",\n    \"fn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\\n\",\n    \"    let mut input_tensor = x_feature_data;\\n\",\n    \"\\n\",\n    \"    let mut i: u32 = 0;\\n\",\n    \"    loop {\\n\",\n    \"        if i >= *x_feature_data.shape.at(0) {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let mut placeholder = ArrayTrait::<FP16x16>::new();\\n\",\n    \"        let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\\n\",\n    \"        let mut feature_squared = feature_row_values.matmul(@feature_row_values);\\n\",\n    \"        // avoiding division by zero errors\\n\",\n    \"        if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\\n\",\n    \"            feature_squared =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"        }\\n\",\n    \"        // loop throgh remaining tensor data and remove the individual tensor factors from one another \\n\",\n    \"        let mut j: u32 = i + 1;\\n\",\n    \"        loop {\\n\",\n    \"            if j >= *x_feature_data.shape.at(0) {\\n\",\n    \"                break ();\\n\",\n    \"            }\\n\",\n    \"            let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\\n\",\n    \"            let feature_cross_product = feature_row_values.matmul(@remaining_tensor_values);\\n\",\n    \"            let feature_gradients = feature_cross_product / feature_squared;\\n\",\n    \"            remaining_tensor_values = remaining_tensor_values\\n\",\n    \"                - (feature_row_values\\n\",\n    \"                    * feature_gradients); //remove the feature factors from one another\\n\",\n    \"            // loop and append the modifieed remaining_tensor_values (after the corelated factor has been removed) to placeholder array\\n\",\n    \"            let mut k: u32 = 0;\\n\",\n    \"            loop {\\n\",\n    \"                if k >= remaining_tensor_values.data.len() {\\n\",\n    \"                    break ();\\n\",\n    \"                }\\n\",\n    \"                placeholder.append(*remaining_tensor_values.data.at(k));\\n\",\n    \"                k += 1;\\n\",\n    \"            };\\n\",\n    \"\\n\",\n    \"            j += 1;\\n\",\n    \"        };\\n\",\n    \"        // convert placeholder array to tensor format and update the original tensor with the new modified decorrelated tensor row values\\n\",\n    \"        let mut decorrelated_tensor = TensorTrait::new(\\n\",\n    \"            shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\\n\",\n    \"            data: placeholder.span()\\n\",\n    \"        );\\n\",\n    \"        let mut original_tensor = input_tensor\\n\",\n    \"            .slice(\\n\",\n    \"                starts: array![0, 0].span(),\\n\",\n    \"                ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\\n\",\n    \"                axes: Option::None(()),\\n\",\n    \"                steps: Option::Some(array![1, 1].span())\\n\",\n    \"            );\\n\",\n    \"        input_tensor =\\n\",\n    \"            TensorTrait::concat(\\n\",\n    \"                tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\\n\",\n    \"            );\\n\",\n    \"        i += 1;\\n\",\n    \"    };\\n\",\n    \"    return input_tensor;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"// computes the corresponding MLR gradient using decorrelated feature\\n\",\n    \"fn compute_gradients(\\n\",\n    \"    decorrelated_x_features: Tensor<FP16x16>,\\n\",\n    \"    y_values: Tensor<FP16x16>,\\n\",\n    \"    original_x_tensor_values: Tensor<FP16x16>\\n\",\n    \") -> Tensor<FP16x16> {\\n\",\n    \"    let mut gradient_values_flipped = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"\\n\",\n    \"    let mut result = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut tensor_y_vals = y_values;\\n\",\n    \"    let mut i: u32 = *decorrelated_x_features.shape.at(0);\\n\",\n    \"    // loop through Decorrelated_x_features starting from the fully orthogonlised last tensor row value\\n\",\n    \"    loop {\\n\",\n    \"        if i <= 0 {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let index_val = i - 1;\\n\",\n    \"        let mut decorelated_feature_row_values = get_tensor_data_by_row(\\n\",\n    \"            decorrelated_x_features, index_val\\n\",\n    \"        ); // 50 vals\\n\",\n    \"        let mut decorelated_features_squared = decorelated_feature_row_values\\n\",\n    \"            .matmul(@decorelated_feature_row_values);\\n\",\n    \"        let mut feature_label_cross_product = tensor_y_vals\\n\",\n    \"            .matmul(@decorelated_feature_row_values); // multiply the tensors\\n\",\n    \"        // avoiding division by zero errors\\n\",\n    \"        if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\\n\",\n    \"            decorelated_features_squared =\\n\",\n    \"                TensorTrait::<\\n\",\n    \"                    FP16x16\\n\",\n    \"                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\\n\",\n    \"        }\\n\",\n    \"        // computing the feature gradient values using the y values and decorrelated x features and appending to array\\n\",\n    \"        let mut single_gradient_value = feature_label_cross_product\\n\",\n    \"            / decorelated_features_squared; // devide the summed value by each other\\n\",\n    \"        result.append(*single_gradient_value.data.at(0));\\n\",\n    \"        // remove the assosciated feature gradient value away from y values\\n\",\n    \"        let mut original_x_tensor_row_values = get_tensor_data_by_row(\\n\",\n    \"            original_x_tensor_values, index_val\\n\",\n    \"        );\\n\",\n    \"        tensor_y_vals = tensor_y_vals\\n\",\n    \"            - (original_x_tensor_row_values\\n\",\n    \"                * single_gradient_value); //remove the first feature from second feature values\\n\",\n    \"        i -= 1;\\n\",\n    \"    };\\n\",\n    \"    // convert the gradient array to tensor format\\n\",\n    \"    let final_gradients = TensorTrait::new(\\n\",\n    \"        shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\\n\",\n    \"    );\\n\",\n    \"\\n\",\n    \"    let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\\n\",\n    \"    let mut data_len: u32 = final_gradients.data.len();\\n\",\n    \"    loop {\\n\",\n    \"        if data_len <= 0 {\\n\",\n    \"            break ();\\n\",\n    \"        }\\n\",\n    \"        let temp_val = data_len - 1;\\n\",\n    \"        reverse_grad_array.append(*final_gradients.data.at(temp_val));\\n\",\n    \"        data_len -= 1;\\n\",\n    \"    };\\n\",\n    \"    // convert gradient values to tensor format\\n\",\n    \"    let gradient_values_flipped = TensorTrait::<\\n\",\n    \"        FP16x16\\n\",\n    \"    >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\\n\",\n    \"\\n\",\n    \"    return gradient_values_flipped;\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 46,\n   \"id\": \"6b37fbe5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/model.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 47,\n   \"id\": \"22f961a5\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/model.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/model.cairo\\n\",\n    \"mod multiple_linear_regression_model;\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8c1f41c6\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Running tests on model\\n\",\n    \"\\n\",\n    \"Running some checks to ensure the model is performing as expected. Some of the checks involve:\\n\",\n    \"- data normalizations checks\\n\",\n    \"- tensor shape/dimension check\\n\",\n    \"- coefficient value and dimension checks  \\n\",\n    \"- model accuracy deviance checks\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 48,\n   \"id\": \"dfb70ccd\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! touch multiple_linear_regression_aave/src/test.cairo\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 49,\n   \"id\": \"4dd10050\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Overwriting multiple_linear_regression_aave/src/test.cairo\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"%%writefile multiple_linear_regression_aave/src/test.cairo\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// use traits::Into;\\n\",\n    \"use debug::PrintTrait;\\n\",\n    \"use array::{ArrayTrait, SpanTrait};\\n\",\n    \"\\n\",\n    \"use multiple_linear_regresion::datasets::aave_data::aave_x_features::aave_x_features;\\n\",\n    \"use multiple_linear_regresion::datasets::aave_data::aave_y_labels::aave_y_labels; \\n\",\n    \"use multiple_linear_regresion::datasets::user_inputs_data::aave_weth_revenue_data_input::{aave_weth_revenue_data_input };  \\n\",\n    \"\\n\",\n    \"use multiple_linear_regresion::model::multiple_linear_regression_model::{\\n\",\n    \"     MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\\n\",\n    \"};\\n\",\n    \"use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\\n\",\n    \"use multiple_linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \\n\",\n    \"calculate_r_score, normalize_user_x_inputs, rescale_predictions};\\n\",\n    \"\\n\",\n    \"use orion::numbers::{FP16x16,  FixedTrait};\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"use orion::operators::tensor::{\\n\",\n    \"    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \\n\",\n    \"    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\\n\",\n    \"\\n\",\n    \"#[test]\\n\",\n    \"#[available_gas(99999999999999999)]\\n\",\n    \"fn multiple_linear_regression_test() {\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"// -------------------------------------------------------------------AAVE dataset tests---------------------------------------------------------------------------------------------\\n\",\n    \"\\n\",\n    \"let mut main_x_vals = aave_x_features();\\n\",\n    \"let mut main_y_vals = aave_y_labels();\\n\",\n    \"let mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\\n\",\n    \"let mut normalized_dataset = dataset.normalize_dataset();\\n\",\n    \"let mut model = MultipleLinearRegression(normalized_dataset);\\n\",\n    \"let mut model_coefficients = model.coefficients;\\n\",\n    \"let mut reconstructed_ys = model.predict (normalized_dataset.x_values);\\n\",\n    \"let mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\\n\",\n    \"r_squared_score.print(); \\n\",\n    \"\\n\",\n    \"// checking if data has been normalized correctly\\n\",\n    \"assert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\\n\",\n    \"assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\\n\",\n    \"assert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\\n\",\n    \"assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\\n\",\n    \"// performing checks on the shape of normalized data\\n\",\n    \"assert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \\n\",\n    \"normalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\\n\",\n    \"// performing checks on shape on coefficient values (gradient vals + bias)\\n\",\n    \"assert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\\n\",\n    \"// model accuracy deviance checks\\n\",\n    \"assert(r_squared_score >= FixedTrait::new(62259, false), 'AAVE model acc. less than 95%');\\n\",\n    \"\\n\",\n    \"// using model to forecast aave's 7 day WETH lifetime repayments forecast \\n\",\n    \"let last_7_days_aave_data = aave_weth_revenue_data_input();\\n\",\n    \"let last_7_days_aave_data_normalized = normalize_user_x_inputs(last_7_days_aave_data, main_x_vals );\\n\",\n    \"let mut forecast_results  = model.predict (last_7_days_aave_data_normalized); \\n\",\n    \"let mut rescale_forecasts = rescale_predictions(forecast_results, main_y_vals);  // PS. ** the rescaled forecasted ouputs are in denominated thousands of ETH\\n\",\n    \"(*rescale_forecasts.data.at(0)).print(); \\n\",\n    \"(*rescale_forecasts.data.at(1)).print(); \\n\",\n    \"(*rescale_forecasts.data.at(2)).print(); \\n\",\n    \"(*rescale_forecasts.data.at(5)).print(); \\n\",\n    \"(*rescale_forecasts.data.at(6)).print(); \\n\",\n    \"}\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4ae8fd10\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.4\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/data_preprocessing.cairo",
        "content": "\n\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct Dataset {\n    x_values: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n}\n\n#[generate_trait]\nimpl DataPreprocessing of DatasetTrait {\n    fn normalize_dataset(ref self: Dataset) -> Dataset {\n        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        // used for multiple_linear_regression_models\n        if self.x_values.shape.len() > 1 {\n            x_values = normalize_feature_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n        // used for linear_regression_models\n        if self.x_values.shape.len() == 1 {\n            x_values = normalize_label_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n\n        return Dataset { x_values, y_values };\n    }\n}\n\n// normalizes 2D Tensor\nfn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut x_min_array = ArrayTrait::<FP16x16>::new();\n    let mut x_max_array = ArrayTrait::<FP16x16>::new();\n    let mut x_range_array = ArrayTrait::<FP16x16>::new();\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    // transpose to change rows to be columns\n    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n    let tensor_shape = transposed_tensor.shape;\n    let tensor_row_len = *tensor_shape.at(0); // 13 \n    let tensor_column_len = *tensor_shape.at(1); //50\n    // loop and append max and min row values to corresponding  array\n    let mut i: u32 = 0;\n    loop {\n        if i >= tensor_row_len {\n            break ();\n        }\n        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n        x_max_array.append(transposed_tensor_row.max_in_tensor());\n        x_min_array.append(transposed_tensor_row.min_in_tensor());\n        x_range_array\n            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n        i += 1;\n    };\n    // convert array to tensor format for ease of math operation\n    let mut x_min = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n    let mut x_range = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n    let normalized_tensor = (tensor_data - x_min) / x_range;\n    return normalized_tensor;\n}\n\n// normalizes 1D tensor\nfn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n    // loop through tensor values normalizing and appending to new array\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let mut diff = *tensor_val - tensor_data.min_in_tensor();\n                normalized_array.append(diff / range);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    // convert normalized array values to tensor format\n    let mut normalized_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n    return normalized_tensor;\n}\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/datasets.cairo",
        "content": "mod linear_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/datasets/linear_data.cairo",
        "content": "mod x_feature_data;\nmod y_label_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/datasets/linear_data/x_feature_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn x_feature_data() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![50].span(),\n    data: array![ \n    FixedTrait::new(90639, false ),\n    FixedTrait::new(12581, true ),\n    FixedTrait::new(33595, false ),\n    FixedTrait::new(92893, false ),\n    FixedTrait::new(64841, false ),\n    FixedTrait::new(21784, false ),\n    FixedTrait::new(93600, false ),\n    FixedTrait::new(139107, false ),\n    FixedTrait::new(46680, true ),\n    FixedTrait::new(148678, true ),\n    FixedTrait::new(55700, false ),\n    FixedTrait::new(63442, false ),\n    FixedTrait::new(16625, false ),\n    FixedTrait::new(15088, false ),\n    FixedTrait::new(109945, false ),\n    FixedTrait::new(22098, false ),\n    FixedTrait::new(28923, false ),\n    FixedTrait::new(55032, true ),\n    FixedTrait::new(29968, false ),\n    FixedTrait::new(17353, false ),\n    FixedTrait::new(126, true ),\n    FixedTrait::new(6705, true ),\n    FixedTrait::new(81234, true ),\n    FixedTrait::new(38498, true ),\n    FixedTrait::new(75536, true ),\n    FixedTrait::new(984, true ),\n    FixedTrait::new(45491, true ),\n    FixedTrait::new(88496, false ),\n    FixedTrait::new(8992, false ),\n    FixedTrait::new(28549, false ),\n    FixedTrait::new(61676, true ),\n    FixedTrait::new(54096, true ),\n    FixedTrait::new(91046, false ),\n    FixedTrait::new(53660, false ),\n    FixedTrait::new(6145, true ),\n    FixedTrait::new(26994, false ),\n    FixedTrait::new(90657, false ),\n    FixedTrait::new(21638, true ),\n    FixedTrait::new(50848, false ),\n    FixedTrait::new(4550, true ),\n    FixedTrait::new(7560, true ),\n    FixedTrait::new(41550, false ),\n    FixedTrait::new(200, false ),\n    FixedTrait::new(102341, false ),\n    FixedTrait::new(25789, false ),\n    FixedTrait::new(9158, false ),\n    FixedTrait::new(102276, true ),\n    FixedTrait::new(76823, true ),\n    FixedTrait::new(69440, true ),\n    FixedTrait::new(17547, true ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/datasets/linear_data/y_label_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn y_label_data() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![50].span(),\n    data: array![ \n    FixedTrait::new(7282724, false ),\n    FixedTrait::new(6435011, false ),\n    FixedTrait::new(6662231, false ),\n    FixedTrait::new(7271410, false ),\n    FixedTrait::new(7099095, false ),\n    FixedTrait::new(6751687, false ),\n    FixedTrait::new(7403695, false ),\n    FixedTrait::new(7831893, false ),\n    FixedTrait::new(6135683, false ),\n    FixedTrait::new(5448106, false ),\n    FixedTrait::new(6992113, false ),\n    FixedTrait::new(7129256, false ),\n    FixedTrait::new(6678313, false ),\n    FixedTrait::new(6524452, false ),\n    FixedTrait::new(7538849, false ),\n    FixedTrait::new(6685568, false ),\n    FixedTrait::new(6749158, false ),\n    FixedTrait::new(6149931, false ),\n    FixedTrait::new(6876758, false ),\n    FixedTrait::new(6623147, false ),\n    FixedTrait::new(6679189, false ),\n    FixedTrait::new(6578635, false ),\n    FixedTrait::new(5894520, false ),\n    FixedTrait::new(6161430, false ),\n    FixedTrait::new(5887716, false ),\n    FixedTrait::new(6440009, false ),\n    FixedTrait::new(6209384, false ),\n    FixedTrait::new(7208597, false ),\n    FixedTrait::new(6679473, false ),\n    FixedTrait::new(6809111, false ),\n    FixedTrait::new(6068970, false ),\n    FixedTrait::new(6089744, false ),\n    FixedTrait::new(7360056, false ),\n    FixedTrait::new(6971060, false ),\n    FixedTrait::new(6419231, false ),\n    FixedTrait::new(6780044, false ),\n    FixedTrait::new(7279453, false ),\n    FixedTrait::new(6350620, false ),\n    FixedTrait::new(7023820, false ),\n    FixedTrait::new(6568475, false ),\n    FixedTrait::new(6528424, false ),\n    FixedTrait::new(6936953, false ),\n    FixedTrait::new(6511689, false ),\n    FixedTrait::new(7367935, false ),\n    FixedTrait::new(6860285, false ),\n    FixedTrait::new(6800462, false ),\n    FixedTrait::new(5650037, false ),\n    FixedTrait::new(5915425, false ),\n    FixedTrait::new(5913912, false ),\n    FixedTrait::new(6491295, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/helper_functions.cairo",
        "content": "\n\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\n\nuse orion::numbers::{FP16x16, FixedTrait};\n\n// retrieves row data by index in a 2D tensor\nfn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n    let column_len = *tensor_data.shape.at(1); //13\n    // crete new array\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // loop through the x values and append values \n    let mut i: u32 = 0;\n    loop {\n        if i >= column_len {\n            break ();\n        }\n        result.append(tensor_data.at(indices: array![row_index, i].span()));\n        i += 1;\n    };\n    let resultant_tensor = TensorTrait::<\n        FP16x16\n    >::new(array![column_len].span(), data: result.span());\n    return resultant_tensor;\n}\n\n\n// transposes tensor\nfn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n    return tensor_transposed;\n}\n\nfn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    return mean;\n}\n\n// Calculates the R-Squared score between two tensors.\nfn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n    let mut Y_values_ = Y_values;\n    let mean_y_value = calculate_mean(Y_values);\n    // creating the appropriate tensor shapes and empty arrays to populate values into\n    let mut squared_diff_shape = array::ArrayTrait::new();\n    squared_diff_shape.append(Y_values.data.len());\n    let mut squared_diff_vals = array::ArrayTrait::new();\n    let mut squared_mean_diff_shape = array::ArrayTrait::new();\n    squared_mean_diff_shape.append(Y_values.data.len());\n    let mut squared_mean_diff_vals = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match Y_values_.data.pop_front() {\n            Option::Some(y_value) => {\n                let diff_pred = *y_value - *Y_pred_values.data.at(i);\n                let squared_diff = diff_pred * diff_pred;\n                squared_diff_vals.append(squared_diff);\n\n                let diff_mean = *y_value - mean_y_value;\n                let squared_mean_diff = diff_mean * diff_mean;\n                squared_mean_diff_vals.append(squared_mean_diff);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        }\n    };\n\n    let squared_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_diff_shape.span(), squared_diff_vals.span());\n    let squared_mean_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n    let sum_squared_mean_diff = squared_mean_diff_tensor\n        .cumsum(0, Option::None(()), Option::None(()));\n    let r_score = FixedTrait::new_unscaled(1, false)\n        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n\n    return r_score;\n}\n\n\n// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\nfn normalize_user_x_inputs(\n    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut x_inputs_normalized = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut x_min = ArrayTrait::<FP16x16>::new();\n    let mut x_max = ArrayTrait::<FP16x16>::new();\n    let mut x_range = ArrayTrait::<FP16x16>::new();\n    let mut result = ArrayTrait::<FP16x16>::new();\n\n    if original_x_values.shape.len() > 1 {\n        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n        let data_len = *transposed_tensor.shape.at(0); //13\n        // loop through each row calculating the min, max and range row values for each feature columns\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n            x_min.append(transposed_tensor_row.min_in_tensor());\n            x_max.append(transposed_tensor_row.max_in_tensor());\n            x_range\n                .append(\n                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n                );\n            i += 1;\n        };\n        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n        let mut x_range_tensor = TensorTrait::new(\n            shape: array![data_len].span(), data: x_range.span()\n        );\n\n        // for normalizing 2D user inputed feature vals\n        if x_inputs.shape.len() > 1 {\n            let mut j: u32 = 0;\n            loop {\n                if j >= *x_inputs.shape.at(0) {\n                    break ();\n                };\n                let mut row_data = get_tensor_data_by_row(x_inputs, j);\n                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n                let mut k: u32 = 0;\n\n                loop {\n                    if k >= norm_row_data.data.len() {\n                        break ();\n                    };\n                    result.append(*norm_row_data.data.at(k));\n                    k += 1;\n                };\n                j += 1;\n            };\n            x_inputs_normalized =\n                TensorTrait::<\n                    FP16x16\n                >::new(\n                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n                );\n        };\n\n        // for normalizing 1D feature input\n        if x_inputs.shape.len() == 1 {\n            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n        };\n    }\n\n    if original_x_values.shape.len() == 1 {\n        let mut x_min_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n        let mut x_max_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n        let mut x_range_tensor = TensorTrait::<\n            FP16x16\n        >::new(\n            shape: array![1].span(),\n            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n                .span()\n        );\n        let mut diff = ((x_inputs - x_min_tensor));\n        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n    };\n    return x_inputs_normalized;\n}\n\n\n// rescales model predictions to standard format\nfn rescale_predictions(\n    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut rescale_predictions = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut y_min_array = ArrayTrait::<FP16x16>::new();\n    let mut y_max_array = ArrayTrait::<FP16x16>::new();\n    let mut y_range_array = ArrayTrait::<FP16x16>::new();\n\n    let mut y_max = y_values.max_in_tensor();\n    let mut y_min = y_values.min_in_tensor();\n    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n    // convert to tensor format for ease of math operations\n    let y_min_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_min].span());\n    let y_max_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_max].span());\n    let y_range_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_range].span());\n\n    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n\n    return rescale_predictions;\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/lib.cairo",
        "content": "mod test;\nmod data_preprocessing;\nmod helper_functions;\nmod datasets;\nmod model;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/model.cairo",
        "content": "mod linear_regression_model;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/model/linear_regression_model.cairo",
        "content": "\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct LinearRegressionModel {\n    gradient: Tensor<FP16x16>,\n    bias: Tensor<FP16x16>\n}\n\n#[generate_trait]\nimpl RegressionOperation of LinearRegressionModelTrait {\n    fn predict(ref self: LinearRegressionModel, x_input: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        let gradient = self.gradient;\n        let bias = self.bias;\n        let mut prediction = (gradient * x_input) + bias;\n        return prediction;\n    }\n}\n\nfn LinearRegression(dataset: Dataset) -> LinearRegressionModel {\n    let gradient = compute_gradient(dataset);\n    let bias = compute_bias(dataset);\n    return LinearRegressionModel { gradient, bias };\n}\n\n// computes the mean of a given 1D tensor and outputs result as tensor\nfn compute_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    let mut result_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![mean].span());\n    return result_tensor;\n}\n\n\n/// Calculates the deviation of each element from the mean of the provided 1D tensor.\nfn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mean_value = calculate_mean(tensor_data);\n    let mut tensor_shape = array::ArrayTrait::new();\n    tensor_shape.append(tensor_data.data.len());\n    let mut deviation_values = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let distance_from_mean = *tensor_val - mean_value;\n                deviation_values.append(distance_from_mean);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    let distance_from_mean_tensor = TensorTrait::<\n        FP16x16\n    >::new(tensor_shape.span(), deviation_values.span());\n\n    return distance_from_mean_tensor;\n}\n\n/// Calculates the beta value for linear regression.\nfn compute_gradient(dataset: Dataset) -> Tensor<FP16x16> {\n    let x_deviation = deviation_from_mean(dataset.x_values);\n    let y_deviation = deviation_from_mean(dataset.y_values);\n\n    let x_y_covariance = x_deviation.matmul(@y_deviation);\n    let x_variance = x_deviation.matmul(@x_deviation);\n\n    let beta_value = x_y_covariance / x_variance;\n\n    return beta_value;\n}\n\n\n/// Calculates the intercept for linear regression.\nfn compute_bias(dataset: Dataset) -> Tensor<FP16x16> {\n    let x_mean = compute_mean(dataset.x_values);\n    let y_mean = compute_mean(dataset.y_values);\n    let gradient = compute_gradient(dataset);\n    let mx = gradient * x_mean;\n    let intercept = y_mean - mx;\n    return intercept;\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/linear_regression/src/test.cairo",
        "content": "// use traits::Into;\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\n\n\nuse linear_regresion::datasets::linear_data::x_feature_data::x_feature_data;\nuse linear_regresion::datasets::linear_data::y_label_data::y_label_data;\n\n\nuse orion::numbers::{FP16x16,  FixedTrait};\nuse linear_regresion::model::linear_regression_model::{\n     LinearRegressionModel, compute_mean, LinearRegression, LinearRegressionModelTrait\n};\n\nuse linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \ncalculate_r_score, normalize_user_x_inputs, rescale_predictions};\n\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \n    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\n\n#[test]\n#[available_gas(99999999999999999)]\nfn multiple_linear_regression_test() {\n\n\n// // ----------------------------------------------------------------Simple Linear regression tests---------------------------------------------------------------------------------\n\nlet mut main_x_vals = x_feature_data();\nlet mut main_y_vals = y_label_data();\nlet dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\nlet mut model = LinearRegression(dataset);\nlet gradient = model.gradient;\nlet mut reconstructed_ys = model.predict(main_x_vals);\nlet mut r_squared_score = calculate_r_score(main_y_vals,reconstructed_ys);\nr_squared_score.print(); \n\n// performing checks on shape on coefficient values (gradient vals + bias) \nassert(model.gradient.data.len() == 1,  'gradient data shape mismatch');\nassert(model.bias.data.len() == 1,  'bias data shape mismatch');\n// model accuracy deviance checks\nassert(r_squared_score >= FixedTrait::new(62259, false), 'Linear model acc. less than 95%');\n\n\n// linear regression model new input predictions\nlet mut user_value =   TensorTrait::<FP16x16>::new(shape: array![2].span(), data: array![FixedTrait::new(65536, false), FixedTrait::new(65536, true)].span());\nlet mut prediction_results = model.predict(user_value);\n(*prediction_results.data.at(0)).print(); \n(*prediction_results.data.at(1)).print();\n\n\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/data_preprocessing.cairo",
        "content": "\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct Dataset {\n    x_values: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n}\n\n#[generate_trait]\nimpl DataPreprocessing of DatasetTrait {\n    fn normalize_dataset(ref self: Dataset) -> Dataset {\n        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        // used for multiple_linear_regression_models\n        if self.x_values.shape.len() > 1 {\n            x_values = normalize_feature_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n        // used for linear_regression_models\n        if self.x_values.shape.len() == 1 {\n            x_values = normalize_label_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n\n        return Dataset { x_values, y_values };\n    }\n}\n\n// normalizes 2D Tensor\nfn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut x_min_array = ArrayTrait::<FP16x16>::new();\n    let mut x_max_array = ArrayTrait::<FP16x16>::new();\n    let mut x_range_array = ArrayTrait::<FP16x16>::new();\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    // transpose to change rows to be columns\n    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n    let tensor_shape = transposed_tensor.shape;\n    let tensor_row_len = *tensor_shape.at(0); // 13 \n    let tensor_column_len = *tensor_shape.at(1); //50\n    // loop and append max and min row values to corresponding  array\n    let mut i: u32 = 0;\n    loop {\n        if i >= tensor_row_len {\n            break ();\n        }\n        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n        x_max_array.append(transposed_tensor_row.max_in_tensor());\n        x_min_array.append(transposed_tensor_row.min_in_tensor());\n        x_range_array\n            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n        i += 1;\n    };\n    // convert array to tensor format for ease of math operation\n    let mut x_min = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n    let mut x_range = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n    let normalized_tensor = (tensor_data - x_min) / x_range;\n    return normalized_tensor;\n}\n\n// normalizes 1D tensor\nfn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n    // loop through tensor values normalizing and appending to new array\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let mut diff = *tensor_val - tensor_data.min_in_tensor();\n                normalized_array.append(diff / range);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    // convert normalized array values to tensor format\n    let mut normalized_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n    return normalized_tensor;\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets.cairo",
        "content": "mod aave_data;\nmod user_inputs_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets/aave_data.cairo",
        "content": "mod aave_x_features;\nmod aave_y_labels;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets/aave_data/aave_x_features.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_x_features() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![24,9].span(),\n    data: array![ \n    FixedTrait::new(61, false ),\n    FixedTrait::new(484966, false ),\n    FixedTrait::new(812646, false ),\n    FixedTrait::new(13369344, false ),\n    FixedTrait::new(3604, false ),\n    FixedTrait::new(7798784, false ),\n    FixedTrait::new(1880883, false ),\n    FixedTrait::new(5006950, false ),\n    FixedTrait::new(220856320, false ),\n    FixedTrait::new(87, false ),\n    FixedTrait::new(488243, false ),\n    FixedTrait::new(812646, false ),\n    FixedTrait::new(13434880, false ),\n    FixedTrait::new(3604, false ),\n    FixedTrait::new(7798784, false ),\n    FixedTrait::new(1880883, false ),\n    FixedTrait::new(5006950, false ),\n    FixedTrait::new(220856320, false ),\n    FixedTrait::new(114, false ),\n    FixedTrait::new(525598, false ),\n    FixedTrait::new(812646, false ),\n    FixedTrait::new(13565952, false ),\n    FixedTrait::new(3604, false ),\n    FixedTrait::new(7798784, false ),\n    FixedTrait::new(1887436, false ),\n    FixedTrait::new(5013504, false ),\n    FixedTrait::new(217579519, false ),\n    FixedTrait::new(138, false ),\n    FixedTrait::new(628490, false ),\n    FixedTrait::new(838860, false ),\n    FixedTrait::new(13893632, false ),\n    FixedTrait::new(3604, false ),\n    FixedTrait::new(8126463, false ),\n    FixedTrait::new(1874329, false ),\n    FixedTrait::new(5046272, false ),\n    FixedTrait::new(208404480, false ),\n    FixedTrait::new(1, false ),\n    FixedTrait::new(655360, false ),\n    FixedTrait::new(924057, false ),\n    FixedTrait::new(14090240, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8388608, false ),\n    FixedTrait::new(1880883, false ),\n    FixedTrait::new(5065932, false ),\n    FixedTrait::new(206438400, false ),\n    FixedTrait::new(25, false ),\n    FixedTrait::new(688128, false ),\n    FixedTrait::new(924057, false ),\n    FixedTrait::new(14155776, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8454144, false ),\n    FixedTrait::new(1893990, false ),\n    FixedTrait::new(5065932, false ),\n    FixedTrait::new(204472320, false ),\n    FixedTrait::new(50, false ),\n    FixedTrait::new(681574, false ),\n    FixedTrait::new(924057, false ),\n    FixedTrait::new(14286848, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8585216, false ),\n    FixedTrait::new(1900544, false ),\n    FixedTrait::new(5072486, false ),\n    FixedTrait::new(205127680, false ),\n    FixedTrait::new(76, false ),\n    FixedTrait::new(640942, false ),\n    FixedTrait::new(924057, false ),\n    FixedTrait::new(14352384, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8650752, false ),\n    FixedTrait::new(1933312, false ),\n    FixedTrait::new(5072486, false ),\n    FixedTrait::new(209059840, false ),\n    FixedTrait::new(100, false ),\n    FixedTrait::new(747110, false ),\n    FixedTrait::new(924057, false ),\n    FixedTrait::new(14483456, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8716288, false ),\n    FixedTrait::new(1939865, false ),\n    FixedTrait::new(5072486, false ),\n    FixedTrait::new(201195519, false ),\n    FixedTrait::new(126, false ),\n    FixedTrait::new(650117, false ),\n    FixedTrait::new(989593, false ),\n    FixedTrait::new(14614528, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8781824, false ),\n    FixedTrait::new(1966080, false ),\n    FixedTrait::new(5079040, false ),\n    FixedTrait::new(209059840, false ),\n    FixedTrait::new(152, false ),\n    FixedTrait::new(645529, false ),\n    FixedTrait::new(989593, false ),\n    FixedTrait::new(14876672, false ),\n    FixedTrait::new(3768, false ),\n    FixedTrait::new(8978432, false ),\n    FixedTrait::new(1979187, false ),\n    FixedTrait::new(5085593, false ),\n    FixedTrait::new(209715200, false ),\n    FixedTrait::new(1, false ),\n    FixedTrait::new(653393, false ),\n    FixedTrait::new(1002700, false ),\n    FixedTrait::new(14876672, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(8978432, false ),\n    FixedTrait::new(1959526, false ),\n    FixedTrait::new(5111808, false ),\n    FixedTrait::new(209059840, false ),\n    FixedTrait::new(26, false ),\n    FixedTrait::new(614072, false ),\n    FixedTrait::new(1009254, false ),\n    FixedTrait::new(15007744, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9043968, false ),\n    FixedTrait::new(1926758, false ),\n    FixedTrait::new(5157683, false ),\n    FixedTrait::new(211025919, false ),\n    FixedTrait::new(54, false ),\n    FixedTrait::new(523632, false ),\n    FixedTrait::new(1009254, false ),\n    FixedTrait::new(15073280, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9043968, false ),\n    FixedTrait::new(2011955, false ),\n    FixedTrait::new(5203558, false ),\n    FixedTrait::new(220856320, false ),\n    FixedTrait::new(78, false ),\n    FixedTrait::new(688128, false ),\n    FixedTrait::new(1009254, false ),\n    FixedTrait::new(15138816, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9109504, false ),\n    FixedTrait::new(1861222, false ),\n    FixedTrait::new(5360844, false ),\n    FixedTrait::new(203816960, false ),\n    FixedTrait::new(102, false ),\n    FixedTrait::new(688128, false ),\n    FixedTrait::new(1028915, false ),\n    FixedTrait::new(15204352, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9109504, false ),\n    FixedTrait::new(1861222, false ),\n    FixedTrait::new(5367398, false ),\n    FixedTrait::new(203816960, false ),\n    FixedTrait::new(126, false ),\n    FixedTrait::new(694681, false ),\n    FixedTrait::new(1028915, false ),\n    FixedTrait::new(15204352, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9109504, false ),\n    FixedTrait::new(1861222, false ),\n    FixedTrait::new(5367398, false ),\n    FixedTrait::new(203161600, false ),\n    FixedTrait::new(151, false ),\n    FixedTrait::new(681574, false ),\n    FixedTrait::new(1028915, false ),\n    FixedTrait::new(15466496, false ),\n    FixedTrait::new(3951, false ),\n    FixedTrait::new(9371648, false ),\n    FixedTrait::new(1848115, false ),\n    FixedTrait::new(5452595, false ),\n    FixedTrait::new(203161600, false ),\n    FixedTrait::new(1, false ),\n    FixedTrait::new(591790, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(15663104, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(9568256, false ),\n    FixedTrait::new(1985740, false ),\n    FixedTrait::new(5485363, false ),\n    FixedTrait::new(214302719, false ),\n    FixedTrait::new(29, false ),\n    FixedTrait::new(565575, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(15859712, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(9764864, false ),\n    FixedTrait::new(2025062, false ),\n    FixedTrait::new(5505024, false ),\n    FixedTrait::new(217579519, false ),\n    FixedTrait::new(57, false ),\n    FixedTrait::new(681574, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(16187392, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(9961472, false ),\n    FixedTrait::new(1979187, false ),\n    FixedTrait::new(5583667, false ),\n    FixedTrait::new(207093760, false ),\n    FixedTrait::new(83, false ),\n    FixedTrait::new(547225, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(16580607, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10223616, false ),\n    FixedTrait::new(1998848, false ),\n    FixedTrait::new(5681971, false ),\n    FixedTrait::new(218234879, false ),\n    FixedTrait::new(110, false ),\n    FixedTrait::new(753664, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(16777216, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10289152, false ),\n    FixedTrait::new(1966080, false ),\n    FixedTrait::new(5754060, false ),\n    FixedTrait::new(201195519, false ),\n    FixedTrait::new(135, false ),\n    FixedTrait::new(747110, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(16842752, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10289152, false ),\n    FixedTrait::new(1992294, false ),\n    FixedTrait::new(5780275, false ),\n    FixedTrait::new(202506239, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets/aave_data/aave_y_labels.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_y_labels() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![24].span(),\n    data: array![ \n    FixedTrait::new(5072486, false ),\n    FixedTrait::new(5072486, false ),\n    FixedTrait::new(5079040, false ),\n    FixedTrait::new(5085593, false ),\n    FixedTrait::new(5111808, false ),\n    FixedTrait::new(5157683, false ),\n    FixedTrait::new(5203558, false ),\n    FixedTrait::new(5360844, false ),\n    FixedTrait::new(5367398, false ),\n    FixedTrait::new(5367398, false ),\n    FixedTrait::new(5452595, false ),\n    FixedTrait::new(5485363, false ),\n    FixedTrait::new(5505024, false ),\n    FixedTrait::new(5583667, false ),\n    FixedTrait::new(5681971, false ),\n    FixedTrait::new(5754060, false ),\n    FixedTrait::new(5780275, false ),\n    FixedTrait::new(5852364, false ),\n    FixedTrait::new(5891686, false ),\n    FixedTrait::new(5963776, false ),\n    FixedTrait::new(6035865, false ),\n    FixedTrait::new(6134169, false ),\n    FixedTrait::new(6153830, false ),\n    FixedTrait::new(6180044, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo",
        "content": "mod aave_weth_revenue_data_input;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/datasets/user_inputs_data/aave_weth_revenue_data_input.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_weth_revenue_data_input() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![7,9].span(),\n    data: array![ \n    FixedTrait::new(160, false ),\n    FixedTrait::new(786432, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(16973824, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10354688, false ),\n    FixedTrait::new(1952972, false ),\n    FixedTrait::new(5852364, false ),\n    FixedTrait::new(198574079, false ),\n    FixedTrait::new(185, false ),\n    FixedTrait::new(681574, false ),\n    FixedTrait::new(1048576, false ),\n    FixedTrait::new(17170432, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1959526, false ),\n    FixedTrait::new(5891686, false ),\n    FixedTrait::new(207093760, false ),\n    FixedTrait::new(211, false ),\n    FixedTrait::new(688128, false ),\n    FixedTrait::new(1055129, false ),\n    FixedTrait::new(17301504, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1952972, false ),\n    FixedTrait::new(5963776, false ),\n    FixedTrait::new(206438400, false ),\n    FixedTrait::new(236, false ),\n    FixedTrait::new(707788, false ),\n    FixedTrait::new(1055129, false ),\n    FixedTrait::new(17367040, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1907097, false ),\n    FixedTrait::new(6035865, false ),\n    FixedTrait::new(203161600, false ),\n    FixedTrait::new(261, false ),\n    FixedTrait::new(792985, false ),\n    FixedTrait::new(1061683, false ),\n    FixedTrait::new(17432576, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1880883, false ),\n    FixedTrait::new(6134169, false ),\n    FixedTrait::new(195952639, false ),\n    FixedTrait::new(285, false ),\n    FixedTrait::new(792985, false ),\n    FixedTrait::new(1061683, false ),\n    FixedTrait::new(17432576, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1880883, false ),\n    FixedTrait::new(6153830, false ),\n    FixedTrait::new(195952639, false ),\n    FixedTrait::new(308, false ),\n    FixedTrait::new(792985, false ),\n    FixedTrait::new(1061683, false ),\n    FixedTrait::new(17498112, false ),\n    FixedTrait::new(4128, false ),\n    FixedTrait::new(10420224, false ),\n    FixedTrait::new(1887436, false ),\n    FixedTrait::new(6180044, false ),\n    FixedTrait::new(196607999, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/helper_functions.cairo",
        "content": "\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\n\nuse orion::numbers::{FP16x16, FixedTrait};\n\n// retrieves row data by index in a 2D tensor\nfn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n    let column_len = *tensor_data.shape.at(1); //13\n    // crete new array\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // loop through the x values and append values \n    let mut i: u32 = 0;\n    loop {\n        if i >= column_len {\n            break ();\n        }\n        result.append(tensor_data.at(indices: array![row_index, i].span()));\n        i += 1;\n    };\n    let resultant_tensor = TensorTrait::<\n        FP16x16\n    >::new(array![column_len].span(), data: result.span());\n    return resultant_tensor;\n}\n\n\n// transposes tensor\nfn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n    return tensor_transposed;\n}\n\nfn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    return mean;\n}\n\n// Calculates the R-Squared score between two tensors.\nfn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n    let mut Y_values_ = Y_values;\n    let mean_y_value = calculate_mean(Y_values);\n    // creating the appropriate tensor shapes and empty arrays to populate values into\n    let mut squared_diff_shape = array::ArrayTrait::new();\n    squared_diff_shape.append(Y_values.data.len());\n    let mut squared_diff_vals = array::ArrayTrait::new();\n    let mut squared_mean_diff_shape = array::ArrayTrait::new();\n    squared_mean_diff_shape.append(Y_values.data.len());\n    let mut squared_mean_diff_vals = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match Y_values_.data.pop_front() {\n            Option::Some(y_value) => {\n                let diff_pred = *y_value - *Y_pred_values.data.at(i);\n                let squared_diff = diff_pred * diff_pred;\n                squared_diff_vals.append(squared_diff);\n\n                let diff_mean = *y_value - mean_y_value;\n                let squared_mean_diff = diff_mean * diff_mean;\n                squared_mean_diff_vals.append(squared_mean_diff);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        }\n    };\n\n    let squared_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_diff_shape.span(), squared_diff_vals.span());\n    let squared_mean_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n    let sum_squared_mean_diff = squared_mean_diff_tensor\n        .cumsum(0, Option::None(()), Option::None(()));\n    let r_score = FixedTrait::new_unscaled(1, false)\n        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n\n    return r_score;\n}\n\n\n// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\nfn normalize_user_x_inputs(\n    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut x_inputs_normalized = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut x_min = ArrayTrait::<FP16x16>::new();\n    let mut x_max = ArrayTrait::<FP16x16>::new();\n    let mut x_range = ArrayTrait::<FP16x16>::new();\n    let mut result = ArrayTrait::<FP16x16>::new();\n\n    if original_x_values.shape.len() > 1 {\n        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n        let data_len = *transposed_tensor.shape.at(0); //13\n        // loop through each row calculating the min, max and range row values for each feature columns\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n            x_min.append(transposed_tensor_row.min_in_tensor());\n            x_max.append(transposed_tensor_row.max_in_tensor());\n            x_range\n                .append(\n                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n                );\n            i += 1;\n        };\n        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n        let mut x_range_tensor = TensorTrait::new(\n            shape: array![data_len].span(), data: x_range.span()\n        );\n\n        // for normalizing 2D user inputed feature vals\n        if x_inputs.shape.len() > 1 {\n            let mut j: u32 = 0;\n            loop {\n                if j >= *x_inputs.shape.at(0) {\n                    break ();\n                };\n                let mut row_data = get_tensor_data_by_row(x_inputs, j);\n                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n                let mut k: u32 = 0;\n\n                loop {\n                    if k >= norm_row_data.data.len() {\n                        break ();\n                    };\n                    result.append(*norm_row_data.data.at(k));\n                    k += 1;\n                };\n                j += 1;\n            };\n            x_inputs_normalized =\n                TensorTrait::<\n                    FP16x16\n                >::new(\n                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n                );\n        };\n\n        // for normalizing 1D feature input\n        if x_inputs.shape.len() == 1 {\n            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n        };\n    }\n\n    if original_x_values.shape.len() == 1 {\n        let mut x_min_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n        let mut x_max_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n        let mut x_range_tensor = TensorTrait::<\n            FP16x16\n        >::new(\n            shape: array![1].span(),\n            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n                .span()\n        );\n        let mut diff = ((x_inputs - x_min_tensor));\n        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n    };\n    return x_inputs_normalized;\n}\n\n\n// rescales model predictions to standard format\nfn rescale_predictions(\n    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut rescale_predictions = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut y_min_array = ArrayTrait::<FP16x16>::new();\n    let mut y_max_array = ArrayTrait::<FP16x16>::new();\n    let mut y_range_array = ArrayTrait::<FP16x16>::new();\n\n    let mut y_max = y_values.max_in_tensor();\n    let mut y_min = y_values.min_in_tensor();\n    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n    // convert to tensor format for ease of math operations\n    let y_min_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_min].span());\n    let y_max_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_max].span());\n    let y_range_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_range].span());\n\n    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n\n    return rescale_predictions;\n}\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/lib.cairo",
        "content": "mod test;\nmod data_preprocessing;\nmod helper_functions;\nmod datasets;\nmod model;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/model.cairo",
        "content": "mod multiple_linear_regression_model;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/model/multiple_linear_regression_model.cairo",
        "content": "\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n\n#[derive(Copy, Drop)]\nstruct MultipleLinearRegressionModel {\n    coefficients: Tensor<FP16x16>\n}\n\n#[generate_trait]\nimpl RegressionOperation of MultipleLinearRegressionModelTrait {\n    // reconstruct the y values using the computed gradients and x values\n    fn predict(\n        ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\n    ) -> Tensor<FP16x16> {\n        // random tensor value that we will replace\n        let mut prediction_result = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n        let mut result = ArrayTrait::<FP16x16>::new();\n        // for multiple predictions\n        if feature_inputs.shape.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            let mut data_len: u32 = *feature_values.shape.at(0);\n            let mut i: u32 = 0;\n            loop {\n                if i >= data_len {\n                    break ();\n                }\n                let feature_row_values = get_tensor_data_by_row(feature_values, i);\n                let predicted_values = feature_row_values.matmul(@self.coefficients);\n                result.append(*predicted_values.data.at(0));\n                i += 1;\n            };\n            prediction_result =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![result.len()].span(), data: result.span());\n        }\n\n        // for single predictions \n        if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            prediction_result = feature_values.matmul(@self.coefficients);\n        }\n\n        return prediction_result;\n    }\n}\n\nfn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\n    let x_values_tranposed = transpose_tensor(dataset.x_values);\n    let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\n    let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\n    let coefficients = compute_gradients(\n        decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\n    );\n    return MultipleLinearRegressionModel { coefficients };\n}\n\n//Adds bias term to features based on axis\nfn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\n    let mut x_feature_ = x_feature;\n    let mut tensor_with_bias = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // check if feature data has multiple rows and columns\n    if x_feature.shape.len() > 1 {\n        let mut index: u32 = 0;\n        if axis == 1 {\n            index = 0;\n        } else {\n            index = 1;\n        }\n        let data_len = *x_feature.shape.at(index); // 50\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            result\n                .append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n            i += 1;\n        };\n        if axis == 0 {\n            let res_tensor = TensorTrait::new(\n                shape: array![1, data_len].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        } else {\n            let res_tensor = TensorTrait::new(\n                shape: array![data_len, 1].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        }\n    }\n    // check if feature data is 1D\n    if x_feature.shape.len() == 1 {\n        let mut j: u32 = 0;\n        loop {\n            match x_feature_.data.pop_front() {\n                Option::Some(x_val) => {\n                    result.append(*x_val);\n                    j += 1;\n                },\n                Option::None(_) => { break; }\n            };\n        };\n        result.append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n        tensor_with_bias =\n            TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\n    }\n    return tensor_with_bias;\n}\n\n// decorrelates the feature data (*only the last tensor row of the decorelated feature data will be fully orthogonal)\nfn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut input_tensor = x_feature_data;\n\n    let mut i: u32 = 0;\n    loop {\n        if i >= *x_feature_data.shape.at(0) {\n            break ();\n        }\n        let mut placeholder = ArrayTrait::<FP16x16>::new();\n        let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\n        let mut feature_squared = feature_row_values.matmul(@feature_row_values);\n        // avoiding division by zero errors\n        if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\n            feature_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // loop throgh remaining tensor data and remove the individual tensor factors from one another \n        let mut j: u32 = i + 1;\n        loop {\n            if j >= *x_feature_data.shape.at(0) {\n                break ();\n            }\n            let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\n            let feature_cross_product = feature_row_values.matmul(@remaining_tensor_values);\n            let feature_gradients = feature_cross_product / feature_squared;\n            remaining_tensor_values = remaining_tensor_values\n                - (feature_row_values\n                    * feature_gradients); //remove the feature factors from one another\n            // loop and append the modifieed remaining_tensor_values (after the corelated factor has been removed) to placeholder array\n            let mut k: u32 = 0;\n            loop {\n                if k >= remaining_tensor_values.data.len() {\n                    break ();\n                }\n                placeholder.append(*remaining_tensor_values.data.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n        // convert placeholder array to tensor format and update the original tensor with the new modified decorrelated tensor row values\n        let mut decorrelated_tensor = TensorTrait::new(\n            shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\n            data: placeholder.span()\n        );\n        let mut original_tensor = input_tensor\n            .slice(\n                starts: array![0, 0].span(),\n                ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\n                axes: Option::None(()),\n                steps: Option::Some(array![1, 1].span())\n            );\n        input_tensor =\n            TensorTrait::concat(\n                tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\n            );\n        i += 1;\n    };\n    return input_tensor;\n}\n\n// computes the corresponding MLR gradient using decorrelated feature\nfn compute_gradients(\n    decorrelated_x_features: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n    original_x_tensor_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut result = ArrayTrait::<FP16x16>::new();\n    let mut tensor_y_vals = y_values;\n    let mut i: u32 = *decorrelated_x_features.shape.at(0);\n    // loop through Decorrelated_x_features starting from the fully orthogonlised last tensor row value\n    loop {\n        if i <= 0 {\n            break ();\n        }\n        let index_val = i - 1;\n        let mut decorelated_feature_row_values = get_tensor_data_by_row(\n            decorrelated_x_features, index_val\n        ); // 50 vals\n        let mut decorelated_features_squared = decorelated_feature_row_values\n            .matmul(@decorelated_feature_row_values);\n        let mut feature_label_cross_product = tensor_y_vals\n            .matmul(@decorelated_feature_row_values); // multiply the tensors\n        // avoiding division by zero errors\n        if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\n            decorelated_features_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // computing the feature gradient values using the y values and decorrelated x features and appending to array\n        let mut single_gradient_value = feature_label_cross_product\n            / decorelated_features_squared; // devide the summed value by each other\n        result.append(*single_gradient_value.data.at(0));\n        // remove the assosciated feature gradient value away from y values\n        let mut original_x_tensor_row_values = get_tensor_data_by_row(\n            original_x_tensor_values, index_val\n        );\n        tensor_y_vals = tensor_y_vals\n            - (original_x_tensor_row_values\n                * single_gradient_value); //remove the first feature from second feature values\n        i -= 1;\n    };\n    // convert the gradient array to tensor format\n    let final_gradients = TensorTrait::new(\n        shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\n    );\n\n    let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\n    let mut data_len: u32 = final_gradients.data.len();\n    loop {\n        if data_len <= 0 {\n            break ();\n        }\n        let temp_val = data_len - 1;\n        reverse_grad_array.append(*final_gradients.data.at(temp_val));\n        data_len -= 1;\n    };\n    // convert gradient values to tensor format\n    let gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\n\n    return gradient_values_flipped;\n}\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_aave/src/test.cairo",
        "content": "\n\n\n// use traits::Into;\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\n\nuse multiple_linear_regresion::datasets::aave_data::aave_x_features::aave_x_features;\nuse multiple_linear_regresion::datasets::aave_data::aave_y_labels::aave_y_labels; \nuse multiple_linear_regresion::datasets::user_inputs_data::aave_weth_revenue_data_input::{aave_weth_revenue_data_input };  \n\nuse multiple_linear_regresion::model::multiple_linear_regression_model::{\n     MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\n};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \ncalculate_r_score, normalize_user_x_inputs, rescale_predictions};\n\nuse orion::numbers::{FP16x16,  FixedTrait};\n\n\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \n    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\n\n#[test]\n#[available_gas(99999999999999999)]\nfn multiple_linear_regression_test() {\n\n\n// -------------------------------------------------------------------AAVE dataset tests---------------------------------------------------------------------------------------------\n\nlet mut main_x_vals = aave_x_features();\nlet mut main_y_vals = aave_y_labels();\nlet mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\nlet mut normalized_dataset = dataset.normalize_dataset();\nlet mut model = MultipleLinearRegression(normalized_dataset);\nlet mut model_coefficients = model.coefficients;\nlet mut reconstructed_ys = model.predict (normalized_dataset.x_values);\nlet mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\nr_squared_score.print(); \n\n// checking if data has been normalized correctly\nassert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\nassert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\nassert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\nassert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\n// performing checks on the shape of normalized data\nassert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \nnormalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\n// performing checks on shape on coefficient values (gradient vals + bias)\nassert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\n// model accuracy deviance checks\nassert(r_squared_score >= FixedTrait::new(62259, false), 'AAVE model acc. less than 95%');\n\n// using model to forecast aave's 7 day WETH net lifetime repayments forecast \nlet last_7_days_aave_data = aave_weth_revenue_data_input();\nlet last_7_days_aave_data_normalized = normalize_user_x_inputs(last_7_days_aave_data, main_x_vals );\nlet mut forecast_results  = model.predict (last_7_days_aave_data_normalized); \nlet mut rescale_forecasts = rescale_predictions(forecast_results, main_y_vals);  // PS. ** the rescaled forecasted ouputs are in denominated thousands of ETH\n(*rescale_forecasts.data.at(0)).print(); \n(*rescale_forecasts.data.at(1)).print(); \n(*rescale_forecasts.data.at(2)).print(); \n(*rescale_forecasts.data.at(5)).print(); \n(*rescale_forecasts.data.at(6)).print(); \n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/data_preprocessing.cairo",
        "content": "\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct Dataset {\n    x_values: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n}\n\n#[generate_trait]\nimpl DataPreprocessing of DatasetTrait {\n    fn normalize_dataset(ref self: Dataset) -> Dataset {\n        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        // used for multiple_linear_regression_models\n        if self.x_values.shape.len() > 1 {\n            x_values = normalize_feature_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n        // used for linear_regression_models\n        if self.x_values.shape.len() == 1 {\n            x_values = normalize_label_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n\n        return Dataset { x_values, y_values };\n    }\n}\n\n// normalizes 2D Tensor\nfn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut x_min_array = ArrayTrait::<FP16x16>::new();\n    let mut x_max_array = ArrayTrait::<FP16x16>::new();\n    let mut x_range_array = ArrayTrait::<FP16x16>::new();\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    // transpose to change rows to be columns\n    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n    let tensor_shape = transposed_tensor.shape;\n    let tensor_row_len = *tensor_shape.at(0); // 13 \n    let tensor_column_len = *tensor_shape.at(1); //50\n    // loop and append max and min row values to corresponding  array\n    let mut i: u32 = 0;\n    loop {\n        if i >= tensor_row_len {\n            break ();\n        }\n        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n        x_max_array.append(transposed_tensor_row.max_in_tensor());\n        x_min_array.append(transposed_tensor_row.min_in_tensor());\n        x_range_array\n            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n        i += 1;\n    };\n    // convert array to tensor format for ease of math operation\n    let mut x_min = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n    let mut x_range = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n    let normalized_tensor = (tensor_data - x_min) / x_range;\n    return normalized_tensor;\n}\n\n// normalizes 1D tensor\nfn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n    // loop through tensor values normalizing and appending to new array\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let mut diff = *tensor_val - tensor_data.min_in_tensor();\n                normalized_array.append(diff / range);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    // convert normalized array values to tensor format\n    let mut normalized_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n    return normalized_tensor;\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets.cairo",
        "content": "mod boston_data;\nmod user_inputs_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets/boston_data.cairo",
        "content": "mod boston_x_features;\nmod boston_y_labels;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets/boston_data/boston_x_features.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn boston_x_features() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![50,11].span(),\n    data: array![ \n    FixedTrait::new(26719, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(406323, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(33226, false ),\n    FixedTrait::new(403963, false ),\n    FixedTrait::new(5983436, false ),\n    FixedTrait::new(199753, false ),\n    FixedTrait::new(524288, false ),\n    FixedTrait::new(20119552, false ),\n    FixedTrait::new(1140326, false ),\n    FixedTrait::new(17588, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(635043, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(38338, false ),\n    FixedTrait::new(379715, false ),\n    FixedTrait::new(4626841, false ),\n    FixedTrait::new(189575, false ),\n    FixedTrait::new(393216, false ),\n    FixedTrait::new(25624576, false ),\n    FixedTrait::new(1258291, false ),\n    FixedTrait::new(3512, false ),\n    FixedTrait::new(1376256, false ),\n    FixedTrait::new(369623, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(28770, false ),\n    FixedTrait::new(426704, false ),\n    FixedTrait::new(1382809, false ),\n    FixedTrait::new(446608, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(15925248, false ),\n    FixedTrait::new(1101004, false ),\n    FixedTrait::new(731407, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(48496, false ),\n    FixedTrait::new(434438, false ),\n    FixedTrait::new(6199705, false ),\n    FixedTrait::new(139244, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(151643, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1283194, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(39649, false ),\n    FixedTrait::new(385351, false ),\n    FixedTrait::new(6376652, false ),\n    FixedTrait::new(156545, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(26411008, false ),\n    FixedTrait::new(963379, false ),\n    FixedTrait::new(637283, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(48496, false ),\n    FixedTrait::new(419823, false ),\n    FixedTrait::new(6370099, false ),\n    FixedTrait::new(135338, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(6860, false ),\n    FixedTrait::new(2621440, false ),\n    FixedTrait::new(420085, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(29294, false ),\n    FixedTrait::new(476250, false ),\n    FixedTrait::new(3211264, false ),\n    FixedTrait::new(313733, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(16646144, false ),\n    FixedTrait::new(1153433, false ),\n    FixedTrait::new(1598672, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(45875, false ),\n    FixedTrait::new(304873, false ),\n    FixedTrait::new(6553600, false ),\n    FixedTrait::new(96154, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(264661, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(34865, false ),\n    FixedTrait::new(408223, false ),\n    FixedTrait::new(5944115, false ),\n    FixedTrait::new(203115, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(10624, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(456130, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(30408, false ),\n    FixedTrait::new(408944, false ),\n    FixedTrait::new(1068236, false ),\n    FixedTrait::new(290258, false ),\n    FixedTrait::new(196608, false ),\n    FixedTrait::new(14614528, false ),\n    FixedTrait::new(1218969, false ),\n    FixedTrait::new(6768, false ),\n    FixedTrait::new(1638400, false ),\n    FixedTrait::new(336199, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(29687, false ),\n    FixedTrait::new(388431, false ),\n    FixedTrait::new(3093299, false ),\n    FixedTrait::new(454295, false ),\n    FixedTrait::new(524288, false ),\n    FixedTrait::new(18612224, false ),\n    FixedTrait::new(1291059, false ),\n    FixedTrait::new(40077, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(260177, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(42401, false ),\n    FixedTrait::new(570425, false ),\n    FixedTrait::new(5695078, false ),\n    FixedTrait::new(118030, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(17301504, false ),\n    FixedTrait::new(851968, false ),\n    FixedTrait::new(527944, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(38273, false ),\n    FixedTrait::new(355663, false ),\n    FixedTrait::new(6252134, false ),\n    FixedTrait::new(159239, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(14030, false ),\n    FixedTrait::new(1441792, false ),\n    FixedTrait::new(384040, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(28246, false ),\n    FixedTrait::new(421920, false ),\n    FixedTrait::new(583270, false ),\n    FixedTrait::new(484750, false ),\n    FixedTrait::new(458752, false ),\n    FixedTrait::new(21626880, false ),\n    FixedTrait::new(1251737, false ),\n    FixedTrait::new(22353, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(483655, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(32309, false ),\n    FixedTrait::new(420413, false ),\n    FixedTrait::new(2627993, false ),\n    FixedTrait::new(309402, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(18808832, false ),\n    FixedTrait::new(1284505, false ),\n    FixedTrait::new(51800, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(648806, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35651, false ),\n    FixedTrait::new(401211, false ),\n    FixedTrait::new(3460300, false ),\n    FixedTrait::new(173034, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(19922944, false ),\n    FixedTrait::new(1205862, false ),\n    FixedTrait::new(1998, false ),\n    FixedTrait::new(3604480, false ),\n    FixedTrait::new(247726, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(31719, false ),\n    FixedTrait::new(450494, false ),\n    FixedTrait::new(1841561, false ),\n    FixedTrait::new(423716, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(24248320, false ),\n    FixedTrait::new(1153433, false ),\n    FixedTrait::new(22898, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(648806, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35651, false ),\n    FixedTrait::new(391380, false ),\n    FixedTrait::new(5026611, false ),\n    FixedTrait::new(203325, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(19922944, false ),\n    FixedTrait::new(1205862, false ),\n    FixedTrait::new(24195, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(648806, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35651, false ),\n    FixedTrait::new(430374, false ),\n    FixedTrait::new(5721292, false ),\n    FixedTrait::new(236080, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(19922944, false ),\n    FixedTrait::new(1205862, false ),\n    FixedTrait::new(623485, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(46727, false ),\n    FixedTrait::new(440926, false ),\n    FixedTrait::new(6166937, false ),\n    FixedTrait::new(163584, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(52606, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(533463, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35258, false ),\n    FixedTrait::new(357564, false ),\n    FixedTrait::new(2398617, false ),\n    FixedTrait::new(248807, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(20119552, false ),\n    FixedTrait::new(1376256, false ),\n    FixedTrait::new(3709, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(223477, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(32047, false ),\n    FixedTrait::new(459210, false ),\n    FixedTrait::new(5655756, false ),\n    FixedTrait::new(224244, false ),\n    FixedTrait::new(131072, false ),\n    FixedTrait::new(17694720, false ),\n    FixedTrait::new(1166540, false ),\n    FixedTrait::new(28554, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(694026, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(32047, false ),\n    FixedTrait::new(350224, false ),\n    FixedTrait::new(6553600, false ),\n    FixedTrait::new(253952, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(18153472, false ),\n    FixedTrait::new(1218969, false ),\n    FixedTrait::new(34087, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(260177, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(42401, false ),\n    FixedTrait::new(550371, false ),\n    FixedTrait::new(5996544, false ),\n    FixedTrait::new(149979, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(17301504, false ),\n    FixedTrait::new(851968, false ),\n    FixedTrait::new(802632, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(38273, false ),\n    FixedTrait::new(382533, false ),\n    FixedTrait::new(3912499, false ),\n    FixedTrait::new(130914, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(17654, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(648806, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35651, false ),\n    FixedTrait::new(410648, false ),\n    FixedTrait::new(5426380, false ),\n    FixedTrait::new(213830, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(19922944, false ),\n    FixedTrait::new(1205862, false ),\n    FixedTrait::new(2988, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(910295, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(36044, false ),\n    FixedTrait::new(385875, false ),\n    FixedTrait::new(3670016, false ),\n    FixedTrait::new(203954, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(18087936, false ),\n    FixedTrait::new(1074790, false ),\n    FixedTrait::new(3787, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(161218, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(31981, false ),\n    FixedTrait::new(457441, false ),\n    FixedTrait::new(3827302, false ),\n    FixedTrait::new(185401, false ),\n    FixedTrait::new(196608, false ),\n    FixedTrait::new(12648448, false ),\n    FixedTrait::new(1166540, false ),\n    FixedTrait::new(54084, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(260177, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(42401, false ),\n    FixedTrait::new(480182, false ),\n    FixedTrait::new(6193152, false ),\n    FixedTrait::new(136236, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(17301504, false ),\n    FixedTrait::new(851968, false ),\n    FixedTrait::new(227690, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(47054, false ),\n    FixedTrait::new(575406, false ),\n    FixedTrait::new(5432934, false ),\n    FixedTrait::new(124826, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(35685, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1434583, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(40894, false ),\n    FixedTrait::new(403111, false ),\n    FixedTrait::new(6415974, false ),\n    FixedTrait::new(109359, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(28639232, false ),\n    FixedTrait::new(1389363, false ),\n    FixedTrait::new(9209, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(694026, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(32047, false ),\n    FixedTrait::new(417792, false ),\n    FixedTrait::new(2116812, false ),\n    FixedTrait::new(258565, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(18153472, false ),\n    FixedTrait::new(1218969, false ),\n    FixedTrait::new(3069, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(223477, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(32047, false ),\n    FixedTrait::new(420544, false ),\n    FixedTrait::new(4331929, false ),\n    FixedTrait::new(202656, false ),\n    FixedTrait::new(131072, false ),\n    FixedTrait::new(17694720, false ),\n    FixedTrait::new(1166540, false ),\n    FixedTrait::new(4016, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(218234, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(29025, false ),\n    FixedTrait::new(501022, false ),\n    FixedTrait::new(3257139, false ),\n    FixedTrait::new(341567, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(14155776, false ),\n    FixedTrait::new(976486, false ),\n    FixedTrait::new(63974, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1434583, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(40894, false ),\n    FixedTrait::new(377290, false ),\n    FixedTrait::new(6448742, false ),\n    FixedTrait::new(153747, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(28639232, false ),\n    FixedTrait::new(1389363, false ),\n    FixedTrait::new(14556, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(656015, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35848, false ),\n    FixedTrait::new(399245, false ),\n    FixedTrait::new(6252134, false ),\n    FixedTrait::new(166985, false ),\n    FixedTrait::new(393216, false ),\n    FixedTrait::new(28311552, false ),\n    FixedTrait::new(1166540, false ),\n    FixedTrait::new(11358, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(635043, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(38338, false ),\n    FixedTrait::new(374013, false ),\n    FixedTrait::new(3538944, false ),\n    FixedTrait::new(156087, false ),\n    FixedTrait::new(393216, false ),\n    FixedTrait::new(25624576, false ),\n    FixedTrait::new(1258291, false ),\n    FixedTrait::new(3758, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(294256, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(29425, false ),\n    FixedTrait::new(434503, false ),\n    FixedTrait::new(3676569, false ),\n    FixedTrait::new(290829, false ),\n    FixedTrait::new(196608, false ),\n    FixedTrait::new(16187392, false ),\n    FixedTrait::new(1212416, false ),\n    FixedTrait::new(11143, false ),\n    FixedTrait::new(819200, false ),\n    FixedTrait::new(515768, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(34340, false ),\n    FixedTrait::new(393478, false ),\n    FixedTrait::new(5629542, false ),\n    FixedTrait::new(432019, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(20381696, false ),\n    FixedTrait::new(996147, false ),\n    FixedTrait::new(2121, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(142868, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(30015, false ),\n    FixedTrait::new(458620, false ),\n    FixedTrait::new(3001548, false ),\n    FixedTrait::new(397292, false ),\n    FixedTrait::new(196608, false ),\n    FixedTrait::new(14548992, false ),\n    FixedTrait::new(1225523, false ),\n    FixedTrait::new(10443, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(452853, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(29360, false ),\n    FixedTrait::new(407044, false ),\n    FixedTrait::new(425984, false ),\n    FixedTrait::new(374924, false ),\n    FixedTrait::new(196608, false ),\n    FixedTrait::new(15269888, false ),\n    FixedTrait::new(1173094, false ),\n    FixedTrait::new(3057, false ),\n    FixedTrait::new(5242880, false ),\n    FixedTrait::new(99614, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(26476, false ),\n    FixedTrait::new(465764, false ),\n    FixedTrait::new(2398617, false ),\n    FixedTrait::new(479002, false ),\n    FixedTrait::new(131072, false ),\n    FixedTrait::new(21561344, false ),\n    FixedTrait::new(825753, false ),\n    FixedTrait::new(2325, false ),\n    FixedTrait::new(5242880, false ),\n    FixedTrait::new(238551, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(25690, false ),\n    FixedTrait::new(385089, false ),\n    FixedTrait::new(1251737, false ),\n    FixedTrait::new(604261, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(20643840, false ),\n    FixedTrait::new(1074790, false ),\n    FixedTrait::new(4601, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(265420, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(33423, false ),\n    FixedTrait::new(394526, false ),\n    FixedTrait::new(3093299, false ),\n    FixedTrait::new(232973, false ),\n    FixedTrait::new(327680, false ),\n    FixedTrait::new(19398656, false ),\n    FixedTrait::new(1087897, false ),\n    FixedTrait::new(2816, false ),\n    FixedTrait::new(3440640, false ),\n    FixedTrait::new(348651, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(26542, false ),\n    FixedTrait::new(430243, false ),\n    FixedTrait::new(1500774, false ),\n    FixedTrait::new(479540, false ),\n    FixedTrait::new(393216, false ),\n    FixedTrait::new(19202048, false ),\n    FixedTrait::new(1087897, false ),\n    FixedTrait::new(90963, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(533463, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(35258, false ),\n    FixedTrait::new(389939, false ),\n    FixedTrait::new(5373952, false ),\n    FixedTrait::new(261488, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(20119552, false ),\n    FixedTrait::new(1376256, false ),\n    FixedTrait::new(12499, false ),\n    FixedTrait::new(1441792, false ),\n    FixedTrait::new(384040, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(28246, false ),\n    FixedTrait::new(440270, false ),\n    FixedTrait::new(1146880, false ),\n    FixedTrait::new(512917, false ),\n    FixedTrait::new(458752, false ),\n    FixedTrait::new(21626880, false ),\n    FixedTrait::new(1251737, false ),\n    FixedTrait::new(12805, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(708444, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(27066, false ),\n    FixedTrait::new(409272, false ),\n    FixedTrait::new(406323, false ),\n    FixedTrait::new(346508, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(19988480, false ),\n    FixedTrait::new(1258291, false ),\n    FixedTrait::new(758769, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(1186201, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(45875, false ),\n    FixedTrait::new(330039, false ),\n    FixedTrait::new(6356992, false ),\n    FixedTrait::new(115998, false ),\n    FixedTrait::new(1572864, false ),\n    FixedTrait::new(43646976, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(2369, false ),\n    FixedTrait::new(5242880, false ),\n    FixedTrait::new(324403, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(26935, false ),\n    FixedTrait::new(434503, false ),\n    FixedTrait::new(1533542, false ),\n    FixedTrait::new(335328, false ),\n    FixedTrait::new(262144, false ),\n    FixedTrait::new(16056320, false ),\n    FixedTrait::new(1258291, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets/boston_data/boston_y_labels.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn boston_y_labels() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![50].span(),\n    data: array![ \n    FixedTrait::new(1422131, false ),\n    FixedTrait::new(1199308, false ),\n    FixedTrait::new(1638400, false ),\n    FixedTrait::new(878182, false ),\n    FixedTrait::new(1251737, false ),\n    FixedTrait::new(1120665, false ),\n    FixedTrait::new(2175795, false ),\n    FixedTrait::new(688128, false ),\n    FixedTrait::new(1284505, false ),\n    FixedTrait::new(1651507, false ),\n    FixedTrait::new(1284505, false ),\n    FixedTrait::new(3276800, false ),\n    FixedTrait::new(904396, false ),\n    FixedTrait::new(1625292, false ),\n    FixedTrait::new(1638400, false ),\n    FixedTrait::new(1448345, false ),\n    FixedTrait::new(2044723, false ),\n    FixedTrait::new(1330380, false ),\n    FixedTrait::new(1559756, false ),\n    FixedTrait::new(976486, false ),\n    FixedTrait::new(1323827, false ),\n    FixedTrait::new(1546649, false ),\n    FixedTrait::new(1310720, false ),\n    FixedTrait::new(3198156, false ),\n    FixedTrait::new(668467, false ),\n    FixedTrait::new(1415577, false ),\n    FixedTrait::new(1526988, false ),\n    FixedTrait::new(2437939, false ),\n    FixedTrait::new(2031616, false ),\n    FixedTrait::new(1435238, false ),\n    FixedTrait::new(1166540, false ),\n    FixedTrait::new(1841561, false ),\n    FixedTrait::new(1481113, false ),\n    FixedTrait::new(3014656, false ),\n    FixedTrait::new(1022361, false ),\n    FixedTrait::new(1225523, false ),\n    FixedTrait::new(1428684, false ),\n    FixedTrait::new(1743257, false ),\n    FixedTrait::new(1238630, false ),\n    FixedTrait::new(2188902, false ),\n    FixedTrait::new(1618739, false ),\n    FixedTrait::new(1985740, false ),\n    FixedTrait::new(1369702, false ),\n    FixedTrait::new(1520435, false ),\n    FixedTrait::new(1625292, false ),\n    FixedTrait::new(865075, false ),\n    FixedTrait::new(1717043, false ),\n    FixedTrait::new(1533542, false ),\n    FixedTrait::new(635699, false ),\n    FixedTrait::new(1828454, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets/user_inputs_data.cairo",
        "content": "mod user_inputs_boston_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/datasets/user_inputs_data/user_inputs_boston_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn user_inputs_boston_data() ->  Tensor<FP16x16>  {\n    let tensor = TensorTrait::<FP16x16>::new( \n    shape: array![11].span(),\n    data: array![ \n    FixedTrait::new(26719, false ),\n    FixedTrait::new(0, false ),\n    FixedTrait::new(406323, false ),\n    FixedTrait::new(65536, false ),\n    FixedTrait::new(33226, false ),\n    FixedTrait::new(403963, false ),\n    FixedTrait::new(5983436, false ),\n    FixedTrait::new(199753, false ),\n    FixedTrait::new(524288, false ),\n    FixedTrait::new(20119552, false ),\n    FixedTrait::new(1140326, false ),\n].span() \n \n);\n\nreturn tensor; \n}"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/helper_functions.cairo",
        "content": "\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\n\nuse orion::numbers::{FP16x16, FixedTrait};\n\n// retrieves row data by index in a 2D tensor\nfn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n    let column_len = *tensor_data.shape.at(1); //13\n    // crete new array\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // loop through the x values and append values \n    let mut i: u32 = 0;\n    loop {\n        if i >= column_len {\n            break ();\n        }\n        result.append(tensor_data.at(indices: array![row_index, i].span()));\n        i += 1;\n    };\n    let resultant_tensor = TensorTrait::<\n        FP16x16\n    >::new(array![column_len].span(), data: result.span());\n    return resultant_tensor;\n}\n\n\n// transposes tensor\nfn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n    return tensor_transposed;\n}\n\nfn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    return mean;\n}\n\n// Calculates the R-Squared score between two tensors.\nfn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n    let mut Y_values_ = Y_values;\n    let mean_y_value = calculate_mean(Y_values);\n    // creating the appropriate tensor shapes and empty arrays to populate values into\n    let mut squared_diff_shape = array::ArrayTrait::new();\n    squared_diff_shape.append(Y_values.data.len());\n    let mut squared_diff_vals = array::ArrayTrait::new();\n    let mut squared_mean_diff_shape = array::ArrayTrait::new();\n    squared_mean_diff_shape.append(Y_values.data.len());\n    let mut squared_mean_diff_vals = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match Y_values_.data.pop_front() {\n            Option::Some(y_value) => {\n                let diff_pred = *y_value - *Y_pred_values.data.at(i);\n                let squared_diff = diff_pred * diff_pred;\n                squared_diff_vals.append(squared_diff);\n\n                let diff_mean = *y_value - mean_y_value;\n                let squared_mean_diff = diff_mean * diff_mean;\n                squared_mean_diff_vals.append(squared_mean_diff);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        }\n    };\n\n    let squared_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_diff_shape.span(), squared_diff_vals.span());\n    let squared_mean_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n    let sum_squared_mean_diff = squared_mean_diff_tensor\n        .cumsum(0, Option::None(()), Option::None(()));\n    let r_score = FixedTrait::new_unscaled(1, false)\n        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n\n    return r_score;\n}\n\n\n// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\nfn normalize_user_x_inputs(\n    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut x_inputs_normalized = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut x_min = ArrayTrait::<FP16x16>::new();\n    let mut x_max = ArrayTrait::<FP16x16>::new();\n    let mut x_range = ArrayTrait::<FP16x16>::new();\n    let mut result = ArrayTrait::<FP16x16>::new();\n\n    if original_x_values.shape.len() > 1 {\n        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n        let data_len = *transposed_tensor.shape.at(0); //13\n        // loop through each row calculating the min, max and range row values for each feature columns\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n            x_min.append(transposed_tensor_row.min_in_tensor());\n            x_max.append(transposed_tensor_row.max_in_tensor());\n            x_range\n                .append(\n                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n                );\n            i += 1;\n        };\n        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n        let mut x_range_tensor = TensorTrait::new(\n            shape: array![data_len].span(), data: x_range.span()\n        );\n\n        // for normalizing 2D user inputed feature vals\n        if x_inputs.shape.len() > 1 {\n            let mut j: u32 = 0;\n            loop {\n                if j >= *x_inputs.shape.at(0) {\n                    break ();\n                };\n                let mut row_data = get_tensor_data_by_row(x_inputs, j);\n                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n                let mut k: u32 = 0;\n\n                loop {\n                    if k >= norm_row_data.data.len() {\n                        break ();\n                    };\n                    result.append(*norm_row_data.data.at(k));\n                    k += 1;\n                };\n                j += 1;\n            };\n            x_inputs_normalized =\n                TensorTrait::<\n                    FP16x16\n                >::new(\n                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n                );\n        };\n\n        // for normalizing 1D feature input\n        if x_inputs.shape.len() == 1 {\n            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n        };\n    }\n\n    if original_x_values.shape.len() == 1 {\n        let mut x_min_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n        let mut x_max_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n        let mut x_range_tensor = TensorTrait::<\n            FP16x16\n        >::new(\n            shape: array![1].span(),\n            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n                .span()\n        );\n        let mut diff = ((x_inputs - x_min_tensor));\n        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n    };\n    return x_inputs_normalized;\n}\n\n\n// rescales model predictions to standard format\nfn rescale_predictions(\n    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut rescale_predictions = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut y_min_array = ArrayTrait::<FP16x16>::new();\n    let mut y_max_array = ArrayTrait::<FP16x16>::new();\n    let mut y_range_array = ArrayTrait::<FP16x16>::new();\n\n    let mut y_max = y_values.max_in_tensor();\n    let mut y_min = y_values.min_in_tensor();\n    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n    // convert to tensor format for ease of math operations\n    let y_min_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_min].span());\n    let y_max_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_max].span());\n    let y_range_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_range].span());\n\n    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n\n    return rescale_predictions;\n}\n\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/lib.cairo",
        "content": "mod test;\nmod data_preprocessing;\nmod helper_functions;\nmod datasets;\nmod model;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/model.cairo",
        "content": "mod multiple_linear_regression_model;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/model/multiple_linear_regression_model.cairo",
        "content": "\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n\n#[derive(Copy, Drop)]\nstruct MultipleLinearRegressionModel {\n    coefficients: Tensor<FP16x16>\n}\n\n#[generate_trait]\nimpl RegressionOperation of MultipleLinearRegressionModelTrait {\n    // reconstruct the y values using the computed gradients and x values\n    fn predict(\n        ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\n    ) -> Tensor<FP16x16> {\n        // random tensor value that we will replace\n        let mut prediction_result = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n        let mut result = ArrayTrait::<FP16x16>::new();\n        // for multiple predictions\n        if feature_inputs.shape.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            let mut data_len: u32 = *feature_values.shape.at(0);\n            let mut i: u32 = 0;\n            loop {\n                if i >= data_len {\n                    break ();\n                }\n                let feature_row_values = get_tensor_data_by_row(feature_values, i);\n                let predicted_values = feature_row_values.matmul(@self.coefficients);\n                result.append(*predicted_values.data.at(0));\n                i += 1;\n            };\n            prediction_result =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![result.len()].span(), data: result.span());\n        }\n\n        // for single predictions \n        if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            prediction_result = feature_values.matmul(@self.coefficients);\n        }\n\n        return prediction_result;\n    }\n}\n\nfn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\n    let x_values_tranposed = transpose_tensor(dataset.x_values);\n    let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\n    let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\n    let coefficients = compute_gradients(\n        decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\n    );\n    return MultipleLinearRegressionModel { coefficients };\n}\n\n//Adds bias term to features based on axis\nfn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\n    let mut x_feature_ = x_feature;\n    let mut tensor_with_bias = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // check if feature data has multiple rows and columns\n    if x_feature.shape.len() > 1 {\n        let mut index: u32 = 0;\n        if axis == 1 {\n            index = 0;\n        } else {\n            index = 1;\n        }\n        let data_len = *x_feature.shape.at(index); // 50\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            result\n                .append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n            i += 1;\n        };\n        if axis == 0 {\n            let res_tensor = TensorTrait::new(\n                shape: array![1, data_len].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        } else {\n            let res_tensor = TensorTrait::new(\n                shape: array![data_len, 1].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        }\n    }\n    // check if feature data is 1D\n    if x_feature.shape.len() == 1 {\n        let mut j: u32 = 0;\n        loop {\n            match x_feature_.data.pop_front() {\n                Option::Some(x_val) => {\n                    result.append(*x_val);\n                    j += 1;\n                },\n                Option::None(_) => { break; }\n            };\n        };\n        result.append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n        tensor_with_bias =\n            TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\n    }\n    return tensor_with_bias;\n}\n\n// decorrelates the feature data (*only the last tensor row of the decorelated feature data will be fully orthogonal)\nfn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut input_tensor = x_feature_data;\n\n    let mut i: u32 = 0;\n    loop {\n        if i >= *x_feature_data.shape.at(0) {\n            break ();\n        }\n        let mut placeholder = ArrayTrait::<FP16x16>::new();\n        let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\n        let mut feature_squared = feature_row_values.matmul(@feature_row_values);\n        // avoiding division by zero errors\n        if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\n            feature_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // loop throgh remaining tensor data and remove the individual tensor factors from one another \n        let mut j: u32 = i + 1;\n        loop {\n            if j >= *x_feature_data.shape.at(0) {\n                break ();\n            }\n            let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\n            let feature_cross_product = feature_row_values.matmul(@remaining_tensor_values);\n            let feature_gradients = feature_cross_product / feature_squared;\n            remaining_tensor_values = remaining_tensor_values\n                - (feature_row_values\n                    * feature_gradients); //remove the feature factors from one another\n            // loop and append the modifieed remaining_tensor_values (after the corelated factor has been removed) to placeholder array\n            let mut k: u32 = 0;\n            loop {\n                if k >= remaining_tensor_values.data.len() {\n                    break ();\n                }\n                placeholder.append(*remaining_tensor_values.data.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n        // convert placeholder array to tensor format and update the original tensor with the new modified decorrelated tensor row values\n        let mut decorrelated_tensor = TensorTrait::new(\n            shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\n            data: placeholder.span()\n        );\n        let mut original_tensor = input_tensor\n            .slice(\n                starts: array![0, 0].span(),\n                ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\n                axes: Option::None(()),\n                steps: Option::Some(array![1, 1].span())\n            );\n        input_tensor =\n            TensorTrait::concat(\n                tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\n            );\n        i += 1;\n    };\n    return input_tensor;\n}\n\n// computes the corresponding MLR gradient using decorrelated feature\nfn compute_gradients(\n    decorrelated_x_features: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n    original_x_tensor_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut result = ArrayTrait::<FP16x16>::new();\n    let mut tensor_y_vals = y_values;\n    let mut i: u32 = *decorrelated_x_features.shape.at(0);\n    // loop through Decorrelated_x_features starting from the fully orthogonlised last tensor row value\n    loop {\n        if i <= 0 {\n            break ();\n        }\n        let index_val = i - 1;\n        let mut decorelated_feature_row_values = get_tensor_data_by_row(\n            decorrelated_x_features, index_val\n        ); // 50 vals\n        let mut decorelated_features_squared = decorelated_feature_row_values\n            .matmul(@decorelated_feature_row_values);\n        let mut feature_label_cross_product = tensor_y_vals\n            .matmul(@decorelated_feature_row_values); // multiply the tensors\n        // avoiding division by zero errors\n        if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\n            decorelated_features_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // computing the feature gradient values using the y values and decorrelated x features and appending to array\n        let mut single_gradient_value = feature_label_cross_product\n            / decorelated_features_squared; // devide the summed value by each other\n        result.append(*single_gradient_value.data.at(0));\n        // remove the assosciated feature gradient value away from y values\n        let mut original_x_tensor_row_values = get_tensor_data_by_row(\n            original_x_tensor_values, index_val\n        );\n        tensor_y_vals = tensor_y_vals\n            - (original_x_tensor_row_values\n                * single_gradient_value); //remove the first feature from second feature values\n        i -= 1;\n    };\n    // convert the gradient array to tensor format\n    let final_gradients = TensorTrait::new(\n        shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\n    );\n\n    let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\n    let mut data_len: u32 = final_gradients.data.len();\n    loop {\n        if data_len <= 0 {\n            break ();\n        }\n        let temp_val = data_len - 1;\n        reverse_grad_array.append(*final_gradients.data.at(temp_val));\n        data_len -= 1;\n    };\n    // convert gradient values to tensor format\n    let gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\n\n    return gradient_values_flipped;\n}\n\n\n\n\n\n\n \n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/notebook_tutorials/multiple_linear_regression_boston/src/test.cairo",
        "content": "\n// use traits::Into;\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\n\n\nuse multiple_linear_regresion::datasets::boston_data::boston_x_features::boston_x_features;\nuse multiple_linear_regresion::datasets::boston_data::boston_y_labels::boston_y_labels;\nuse multiple_linear_regresion::datasets::user_inputs_data::user_inputs_boston_data::user_inputs_boston_data;\n\nuse orion::numbers::{FP16x16,  FixedTrait};\n\nuse multiple_linear_regresion::model::multiple_linear_regression_model::{\n     MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\n};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \ncalculate_r_score, normalize_user_x_inputs, rescale_predictions};\n\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \n    FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\n\n#[test]\n#[available_gas(99999999999999999)]\nfn multiple_linear_regression_test() {\n\n// -------------------------------------------------------------------Boston dataset tests---------------------------------------------------------------------------------------------\n\nlet mut main_x_vals = boston_x_features();\nlet mut main_y_vals = boston_y_labels();\nlet mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\nlet mut normalized_dataset = dataset.normalize_dataset();\nlet mut model  = MultipleLinearRegression(normalized_dataset);\nlet mut model_coefficients = model.coefficients;\nlet mut reconstructed_ys = model.predict (normalized_dataset.x_values);\nlet mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\nr_squared_score.print(); \n\n// checking if data has been normalized correctly\nassert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\nassert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\nassert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\nassert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\n// performing checks on the shape of normalized data\nassert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \nnormalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\n// performing checks on shape on coefficient values (gradient vals + bias)\nassert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\n// model accuracy deviance checks\nassert(r_squared_score >= FixedTrait::new(55699, false), 'Boston model acc. less than 84%');\n\n\n// boston user inputed house valuation predictions\nlet user_input = user_inputs_boston_data();\nlet mut normalized_user_x_inputs = normalize_user_x_inputs(user_input, main_x_vals) ;\nlet mut prediction_result  = model.predict (normalized_user_x_inputs); \nlet mut rescale_prediction  = rescale_predictions(prediction_result, main_y_vals);\n(*rescale_prediction.data.at(0)).print(); \n\n\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/data_preprocessing.cairo",
        "content": "use orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct Dataset {\n    x_values: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n}\n\n#[generate_trait]\nimpl DataPreprocessing of DatasetTrait {\n    fn normalize_dataset(ref self: Dataset) -> Dataset {\n        let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n        // used for multiple_linear_regression_models\n        if self.x_values.shape.len() > 1 {\n            x_values = normalize_feature_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n        // used for linear_regression_models\n        if self.x_values.shape.len() == 1 {\n            x_values = normalize_label_data(self.x_values);\n            y_values = normalize_label_data(self.y_values);\n        }\n\n        return Dataset { x_values, y_values };\n    }\n}\n\n// normalizes 2D Tensor\nfn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut x_min_array = ArrayTrait::<FP16x16>::new();\n    let mut x_max_array = ArrayTrait::<FP16x16>::new();\n    let mut x_range_array = ArrayTrait::<FP16x16>::new();\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    // transpose to change rows to be columns\n    let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n    let tensor_shape = transposed_tensor.shape;\n    let tensor_row_len = *tensor_shape.at(0); // 13 \n    let tensor_column_len = *tensor_shape.at(1); //50\n    // loop and append max and min row values to corresponding  array\n    let mut i: u32 = 0;\n    loop {\n        if i >= tensor_row_len {\n            break ();\n        }\n        let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n        x_max_array.append(transposed_tensor_row.max_in_tensor());\n        x_min_array.append(transposed_tensor_row.min_in_tensor());\n        x_range_array\n            .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n        i += 1;\n    };\n    // convert array to tensor format for ease of math operation\n    let mut x_min = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n    let mut x_range = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n    let normalized_tensor = (tensor_data - x_min) / x_range;\n    return normalized_tensor;\n}\n\n// normalizes 1D tensor\nfn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mut normalized_array = ArrayTrait::<FP16x16>::new();\n    let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n    // loop through tensor values normalizing and appending to new array\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let mut diff = *tensor_val - tensor_data.min_in_tensor();\n                normalized_array.append(diff / range);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    // convert normalized array values to tensor format\n    let mut normalized_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n    return normalized_tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets.cairo",
        "content": "mod aave_data;\nmod boston_data;\nmod linear_data;\nmod user_inputs_data;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/aave_data.cairo",
        "content": "mod aave_x_features;\nmod aave_y_labels;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/aave_data/aave_x_features.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_x_features() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![24, 9].span(),\n        data: array![\n            FixedTrait::new(61, false),\n            FixedTrait::new(484966, false),\n            FixedTrait::new(812646, false),\n            FixedTrait::new(13369344, false),\n            FixedTrait::new(3604, false),\n            FixedTrait::new(7798784, false),\n            FixedTrait::new(1880883, false),\n            FixedTrait::new(5006950, false),\n            FixedTrait::new(220856320, false),\n            FixedTrait::new(87, false),\n            FixedTrait::new(488243, false),\n            FixedTrait::new(812646, false),\n            FixedTrait::new(13434880, false),\n            FixedTrait::new(3604, false),\n            FixedTrait::new(7798784, false),\n            FixedTrait::new(1880883, false),\n            FixedTrait::new(5006950, false),\n            FixedTrait::new(220856320, false),\n            FixedTrait::new(114, false),\n            FixedTrait::new(525598, false),\n            FixedTrait::new(812646, false),\n            FixedTrait::new(13565952, false),\n            FixedTrait::new(3604, false),\n            FixedTrait::new(7798784, false),\n            FixedTrait::new(1887436, false),\n            FixedTrait::new(5013504, false),\n            FixedTrait::new(217579519, false),\n            FixedTrait::new(138, false),\n            FixedTrait::new(628490, false),\n            FixedTrait::new(838860, false),\n            FixedTrait::new(13893632, false),\n            FixedTrait::new(3604, false),\n            FixedTrait::new(8126463, false),\n            FixedTrait::new(1874329, false),\n            FixedTrait::new(5046272, false),\n            FixedTrait::new(208404480, false),\n            FixedTrait::new(1, false),\n            FixedTrait::new(655360, false),\n            FixedTrait::new(924057, false),\n            FixedTrait::new(14090240, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8388608, false),\n            FixedTrait::new(1880883, false),\n            FixedTrait::new(5065932, false),\n            FixedTrait::new(206438400, false),\n            FixedTrait::new(25, false),\n            FixedTrait::new(688128, false),\n            FixedTrait::new(924057, false),\n            FixedTrait::new(14155776, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8454144, false),\n            FixedTrait::new(1893990, false),\n            FixedTrait::new(5065932, false),\n            FixedTrait::new(204472320, false),\n            FixedTrait::new(50, false),\n            FixedTrait::new(681574, false),\n            FixedTrait::new(924057, false),\n            FixedTrait::new(14286848, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8585216, false),\n            FixedTrait::new(1900544, false),\n            FixedTrait::new(5072486, false),\n            FixedTrait::new(205127680, false),\n            FixedTrait::new(76, false),\n            FixedTrait::new(640942, false),\n            FixedTrait::new(924057, false),\n            FixedTrait::new(14352384, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8650752, false),\n            FixedTrait::new(1933312, false),\n            FixedTrait::new(5072486, false),\n            FixedTrait::new(209059840, false),\n            FixedTrait::new(100, false),\n            FixedTrait::new(747110, false),\n            FixedTrait::new(924057, false),\n            FixedTrait::new(14483456, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8716288, false),\n            FixedTrait::new(1939865, false),\n            FixedTrait::new(5072486, false),\n            FixedTrait::new(201195519, false),\n            FixedTrait::new(126, false),\n            FixedTrait::new(650117, false),\n            FixedTrait::new(989593, false),\n            FixedTrait::new(14614528, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8781824, false),\n            FixedTrait::new(1966080, false),\n            FixedTrait::new(5079040, false),\n            FixedTrait::new(209059840, false),\n            FixedTrait::new(152, false),\n            FixedTrait::new(645529, false),\n            FixedTrait::new(989593, false),\n            FixedTrait::new(14876672, false),\n            FixedTrait::new(3768, false),\n            FixedTrait::new(8978432, false),\n            FixedTrait::new(1979187, false),\n            FixedTrait::new(5085593, false),\n            FixedTrait::new(209715200, false),\n            FixedTrait::new(1, false),\n            FixedTrait::new(653393, false),\n            FixedTrait::new(1002700, false),\n            FixedTrait::new(14876672, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(8978432, false),\n            FixedTrait::new(1959526, false),\n            FixedTrait::new(5111808, false),\n            FixedTrait::new(209059840, false),\n            FixedTrait::new(26, false),\n            FixedTrait::new(614072, false),\n            FixedTrait::new(1009254, false),\n            FixedTrait::new(15007744, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9043968, false),\n            FixedTrait::new(1926758, false),\n            FixedTrait::new(5157683, false),\n            FixedTrait::new(211025919, false),\n            FixedTrait::new(54, false),\n            FixedTrait::new(523632, false),\n            FixedTrait::new(1009254, false),\n            FixedTrait::new(15073280, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9043968, false),\n            FixedTrait::new(2011955, false),\n            FixedTrait::new(5203558, false),\n            FixedTrait::new(220856320, false),\n            FixedTrait::new(78, false),\n            FixedTrait::new(688128, false),\n            FixedTrait::new(1009254, false),\n            FixedTrait::new(15138816, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9109504, false),\n            FixedTrait::new(1861222, false),\n            FixedTrait::new(5360844, false),\n            FixedTrait::new(203816960, false),\n            FixedTrait::new(102, false),\n            FixedTrait::new(688128, false),\n            FixedTrait::new(1028915, false),\n            FixedTrait::new(15204352, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9109504, false),\n            FixedTrait::new(1861222, false),\n            FixedTrait::new(5367398, false),\n            FixedTrait::new(203816960, false),\n            FixedTrait::new(126, false),\n            FixedTrait::new(694681, false),\n            FixedTrait::new(1028915, false),\n            FixedTrait::new(15204352, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9109504, false),\n            FixedTrait::new(1861222, false),\n            FixedTrait::new(5367398, false),\n            FixedTrait::new(203161600, false),\n            FixedTrait::new(151, false),\n            FixedTrait::new(681574, false),\n            FixedTrait::new(1028915, false),\n            FixedTrait::new(15466496, false),\n            FixedTrait::new(3951, false),\n            FixedTrait::new(9371648, false),\n            FixedTrait::new(1848115, false),\n            FixedTrait::new(5452595, false),\n            FixedTrait::new(203161600, false),\n            FixedTrait::new(1, false),\n            FixedTrait::new(591790, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(15663104, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(9568256, false),\n            FixedTrait::new(1985740, false),\n            FixedTrait::new(5485363, false),\n            FixedTrait::new(214302719, false),\n            FixedTrait::new(29, false),\n            FixedTrait::new(565575, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(15859712, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(9764864, false),\n            FixedTrait::new(2025062, false),\n            FixedTrait::new(5505024, false),\n            FixedTrait::new(217579519, false),\n            FixedTrait::new(57, false),\n            FixedTrait::new(681574, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(16187392, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(9961472, false),\n            FixedTrait::new(1979187, false),\n            FixedTrait::new(5583667, false),\n            FixedTrait::new(207093760, false),\n            FixedTrait::new(83, false),\n            FixedTrait::new(547225, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(16580607, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10223616, false),\n            FixedTrait::new(1998848, false),\n            FixedTrait::new(5681971, false),\n            FixedTrait::new(218234879, false),\n            FixedTrait::new(110, false),\n            FixedTrait::new(753664, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(16777216, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10289152, false),\n            FixedTrait::new(1966080, false),\n            FixedTrait::new(5754060, false),\n            FixedTrait::new(201195519, false),\n            FixedTrait::new(135, false),\n            FixedTrait::new(747110, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(16842752, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10289152, false),\n            FixedTrait::new(1992294, false),\n            FixedTrait::new(5780275, false),\n            FixedTrait::new(202506239, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/aave_data/aave_y_labels.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_y_labels() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![24].span(),\n        data: array![\n            FixedTrait::new(5072486, false),\n            FixedTrait::new(5072486, false),\n            FixedTrait::new(5079040, false),\n            FixedTrait::new(5085593, false),\n            FixedTrait::new(5111808, false),\n            FixedTrait::new(5157683, false),\n            FixedTrait::new(5203558, false),\n            FixedTrait::new(5360844, false),\n            FixedTrait::new(5367398, false),\n            FixedTrait::new(5367398, false),\n            FixedTrait::new(5452595, false),\n            FixedTrait::new(5485363, false),\n            FixedTrait::new(5505024, false),\n            FixedTrait::new(5583667, false),\n            FixedTrait::new(5681971, false),\n            FixedTrait::new(5754060, false),\n            FixedTrait::new(5780275, false),\n            FixedTrait::new(5852364, false),\n            FixedTrait::new(5891686, false),\n            FixedTrait::new(5963776, false),\n            FixedTrait::new(6035865, false),\n            FixedTrait::new(6134169, false),\n            FixedTrait::new(6153830, false),\n            FixedTrait::new(6180044, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/boston_data.cairo",
        "content": "mod boston_x_features;\nmod boston_y_labels;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/boston_data/boston_x_features.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn boston_x_features() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![50, 11].span(),\n        data: array![\n            FixedTrait::new(26719, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(406323, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(33226, false),\n            FixedTrait::new(403963, false),\n            FixedTrait::new(5983436, false),\n            FixedTrait::new(199753, false),\n            FixedTrait::new(524288, false),\n            FixedTrait::new(20119552, false),\n            FixedTrait::new(1140326, false),\n            FixedTrait::new(17588, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(635043, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(38338, false),\n            FixedTrait::new(379715, false),\n            FixedTrait::new(4626841, false),\n            FixedTrait::new(189575, false),\n            FixedTrait::new(393216, false),\n            FixedTrait::new(25624576, false),\n            FixedTrait::new(1258291, false),\n            FixedTrait::new(3512, false),\n            FixedTrait::new(1376256, false),\n            FixedTrait::new(369623, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(28770, false),\n            FixedTrait::new(426704, false),\n            FixedTrait::new(1382809, false),\n            FixedTrait::new(446608, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(15925248, false),\n            FixedTrait::new(1101004, false),\n            FixedTrait::new(731407, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(48496, false),\n            FixedTrait::new(434438, false),\n            FixedTrait::new(6199705, false),\n            FixedTrait::new(139244, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(151643, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1283194, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(39649, false),\n            FixedTrait::new(385351, false),\n            FixedTrait::new(6376652, false),\n            FixedTrait::new(156545, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(26411008, false),\n            FixedTrait::new(963379, false),\n            FixedTrait::new(637283, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(48496, false),\n            FixedTrait::new(419823, false),\n            FixedTrait::new(6370099, false),\n            FixedTrait::new(135338, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(6860, false),\n            FixedTrait::new(2621440, false),\n            FixedTrait::new(420085, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(29294, false),\n            FixedTrait::new(476250, false),\n            FixedTrait::new(3211264, false),\n            FixedTrait::new(313733, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(16646144, false),\n            FixedTrait::new(1153433, false),\n            FixedTrait::new(1598672, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(45875, false),\n            FixedTrait::new(304873, false),\n            FixedTrait::new(6553600, false),\n            FixedTrait::new(96154, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(264661, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(34865, false),\n            FixedTrait::new(408223, false),\n            FixedTrait::new(5944115, false),\n            FixedTrait::new(203115, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(10624, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(456130, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(30408, false),\n            FixedTrait::new(408944, false),\n            FixedTrait::new(1068236, false),\n            FixedTrait::new(290258, false),\n            FixedTrait::new(196608, false),\n            FixedTrait::new(14614528, false),\n            FixedTrait::new(1218969, false),\n            FixedTrait::new(6768, false),\n            FixedTrait::new(1638400, false),\n            FixedTrait::new(336199, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(29687, false),\n            FixedTrait::new(388431, false),\n            FixedTrait::new(3093299, false),\n            FixedTrait::new(454295, false),\n            FixedTrait::new(524288, false),\n            FixedTrait::new(18612224, false),\n            FixedTrait::new(1291059, false),\n            FixedTrait::new(40077, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(260177, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(42401, false),\n            FixedTrait::new(570425, false),\n            FixedTrait::new(5695078, false),\n            FixedTrait::new(118030, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(17301504, false),\n            FixedTrait::new(851968, false),\n            FixedTrait::new(527944, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(38273, false),\n            FixedTrait::new(355663, false),\n            FixedTrait::new(6252134, false),\n            FixedTrait::new(159239, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(14030, false),\n            FixedTrait::new(1441792, false),\n            FixedTrait::new(384040, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(28246, false),\n            FixedTrait::new(421920, false),\n            FixedTrait::new(583270, false),\n            FixedTrait::new(484750, false),\n            FixedTrait::new(458752, false),\n            FixedTrait::new(21626880, false),\n            FixedTrait::new(1251737, false),\n            FixedTrait::new(22353, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(483655, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(32309, false),\n            FixedTrait::new(420413, false),\n            FixedTrait::new(2627993, false),\n            FixedTrait::new(309402, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(18808832, false),\n            FixedTrait::new(1284505, false),\n            FixedTrait::new(51800, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(648806, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35651, false),\n            FixedTrait::new(401211, false),\n            FixedTrait::new(3460300, false),\n            FixedTrait::new(173034, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(19922944, false),\n            FixedTrait::new(1205862, false),\n            FixedTrait::new(1998, false),\n            FixedTrait::new(3604480, false),\n            FixedTrait::new(247726, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(31719, false),\n            FixedTrait::new(450494, false),\n            FixedTrait::new(1841561, false),\n            FixedTrait::new(423716, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(24248320, false),\n            FixedTrait::new(1153433, false),\n            FixedTrait::new(22898, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(648806, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35651, false),\n            FixedTrait::new(391380, false),\n            FixedTrait::new(5026611, false),\n            FixedTrait::new(203325, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(19922944, false),\n            FixedTrait::new(1205862, false),\n            FixedTrait::new(24195, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(648806, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35651, false),\n            FixedTrait::new(430374, false),\n            FixedTrait::new(5721292, false),\n            FixedTrait::new(236080, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(19922944, false),\n            FixedTrait::new(1205862, false),\n            FixedTrait::new(623485, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(46727, false),\n            FixedTrait::new(440926, false),\n            FixedTrait::new(6166937, false),\n            FixedTrait::new(163584, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(52606, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(533463, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35258, false),\n            FixedTrait::new(357564, false),\n            FixedTrait::new(2398617, false),\n            FixedTrait::new(248807, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(20119552, false),\n            FixedTrait::new(1376256, false),\n            FixedTrait::new(3709, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(223477, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(32047, false),\n            FixedTrait::new(459210, false),\n            FixedTrait::new(5655756, false),\n            FixedTrait::new(224244, false),\n            FixedTrait::new(131072, false),\n            FixedTrait::new(17694720, false),\n            FixedTrait::new(1166540, false),\n            FixedTrait::new(28554, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(694026, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(32047, false),\n            FixedTrait::new(350224, false),\n            FixedTrait::new(6553600, false),\n            FixedTrait::new(253952, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(18153472, false),\n            FixedTrait::new(1218969, false),\n            FixedTrait::new(34087, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(260177, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(42401, false),\n            FixedTrait::new(550371, false),\n            FixedTrait::new(5996544, false),\n            FixedTrait::new(149979, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(17301504, false),\n            FixedTrait::new(851968, false),\n            FixedTrait::new(802632, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(38273, false),\n            FixedTrait::new(382533, false),\n            FixedTrait::new(3912499, false),\n            FixedTrait::new(130914, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(17654, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(648806, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35651, false),\n            FixedTrait::new(410648, false),\n            FixedTrait::new(5426380, false),\n            FixedTrait::new(213830, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(19922944, false),\n            FixedTrait::new(1205862, false),\n            FixedTrait::new(2988, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(910295, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(36044, false),\n            FixedTrait::new(385875, false),\n            FixedTrait::new(3670016, false),\n            FixedTrait::new(203954, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(18087936, false),\n            FixedTrait::new(1074790, false),\n            FixedTrait::new(3787, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(161218, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(31981, false),\n            FixedTrait::new(457441, false),\n            FixedTrait::new(3827302, false),\n            FixedTrait::new(185401, false),\n            FixedTrait::new(196608, false),\n            FixedTrait::new(12648448, false),\n            FixedTrait::new(1166540, false),\n            FixedTrait::new(54084, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(260177, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(42401, false),\n            FixedTrait::new(480182, false),\n            FixedTrait::new(6193152, false),\n            FixedTrait::new(136236, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(17301504, false),\n            FixedTrait::new(851968, false),\n            FixedTrait::new(227690, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(47054, false),\n            FixedTrait::new(575406, false),\n            FixedTrait::new(5432934, false),\n            FixedTrait::new(124826, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(35685, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1434583, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(40894, false),\n            FixedTrait::new(403111, false),\n            FixedTrait::new(6415974, false),\n            FixedTrait::new(109359, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(28639232, false),\n            FixedTrait::new(1389363, false),\n            FixedTrait::new(9209, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(694026, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(32047, false),\n            FixedTrait::new(417792, false),\n            FixedTrait::new(2116812, false),\n            FixedTrait::new(258565, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(18153472, false),\n            FixedTrait::new(1218969, false),\n            FixedTrait::new(3069, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(223477, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(32047, false),\n            FixedTrait::new(420544, false),\n            FixedTrait::new(4331929, false),\n            FixedTrait::new(202656, false),\n            FixedTrait::new(131072, false),\n            FixedTrait::new(17694720, false),\n            FixedTrait::new(1166540, false),\n            FixedTrait::new(4016, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(218234, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(29025, false),\n            FixedTrait::new(501022, false),\n            FixedTrait::new(3257139, false),\n            FixedTrait::new(341567, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(14155776, false),\n            FixedTrait::new(976486, false),\n            FixedTrait::new(63974, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1434583, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(40894, false),\n            FixedTrait::new(377290, false),\n            FixedTrait::new(6448742, false),\n            FixedTrait::new(153747, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(28639232, false),\n            FixedTrait::new(1389363, false),\n            FixedTrait::new(14556, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(656015, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35848, false),\n            FixedTrait::new(399245, false),\n            FixedTrait::new(6252134, false),\n            FixedTrait::new(166985, false),\n            FixedTrait::new(393216, false),\n            FixedTrait::new(28311552, false),\n            FixedTrait::new(1166540, false),\n            FixedTrait::new(11358, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(635043, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(38338, false),\n            FixedTrait::new(374013, false),\n            FixedTrait::new(3538944, false),\n            FixedTrait::new(156087, false),\n            FixedTrait::new(393216, false),\n            FixedTrait::new(25624576, false),\n            FixedTrait::new(1258291, false),\n            FixedTrait::new(3758, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(294256, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(29425, false),\n            FixedTrait::new(434503, false),\n            FixedTrait::new(3676569, false),\n            FixedTrait::new(290829, false),\n            FixedTrait::new(196608, false),\n            FixedTrait::new(16187392, false),\n            FixedTrait::new(1212416, false),\n            FixedTrait::new(11143, false),\n            FixedTrait::new(819200, false),\n            FixedTrait::new(515768, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(34340, false),\n            FixedTrait::new(393478, false),\n            FixedTrait::new(5629542, false),\n            FixedTrait::new(432019, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(20381696, false),\n            FixedTrait::new(996147, false),\n            FixedTrait::new(2121, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(142868, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(30015, false),\n            FixedTrait::new(458620, false),\n            FixedTrait::new(3001548, false),\n            FixedTrait::new(397292, false),\n            FixedTrait::new(196608, false),\n            FixedTrait::new(14548992, false),\n            FixedTrait::new(1225523, false),\n            FixedTrait::new(10443, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(452853, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(29360, false),\n            FixedTrait::new(407044, false),\n            FixedTrait::new(425984, false),\n            FixedTrait::new(374924, false),\n            FixedTrait::new(196608, false),\n            FixedTrait::new(15269888, false),\n            FixedTrait::new(1173094, false),\n            FixedTrait::new(3057, false),\n            FixedTrait::new(5242880, false),\n            FixedTrait::new(99614, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(26476, false),\n            FixedTrait::new(465764, false),\n            FixedTrait::new(2398617, false),\n            FixedTrait::new(479002, false),\n            FixedTrait::new(131072, false),\n            FixedTrait::new(21561344, false),\n            FixedTrait::new(825753, false),\n            FixedTrait::new(2325, false),\n            FixedTrait::new(5242880, false),\n            FixedTrait::new(238551, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(25690, false),\n            FixedTrait::new(385089, false),\n            FixedTrait::new(1251737, false),\n            FixedTrait::new(604261, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(20643840, false),\n            FixedTrait::new(1074790, false),\n            FixedTrait::new(4601, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(265420, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(33423, false),\n            FixedTrait::new(394526, false),\n            FixedTrait::new(3093299, false),\n            FixedTrait::new(232973, false),\n            FixedTrait::new(327680, false),\n            FixedTrait::new(19398656, false),\n            FixedTrait::new(1087897, false),\n            FixedTrait::new(2816, false),\n            FixedTrait::new(3440640, false),\n            FixedTrait::new(348651, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(26542, false),\n            FixedTrait::new(430243, false),\n            FixedTrait::new(1500774, false),\n            FixedTrait::new(479540, false),\n            FixedTrait::new(393216, false),\n            FixedTrait::new(19202048, false),\n            FixedTrait::new(1087897, false),\n            FixedTrait::new(90963, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(533463, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(35258, false),\n            FixedTrait::new(389939, false),\n            FixedTrait::new(5373952, false),\n            FixedTrait::new(261488, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(20119552, false),\n            FixedTrait::new(1376256, false),\n            FixedTrait::new(12499, false),\n            FixedTrait::new(1441792, false),\n            FixedTrait::new(384040, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(28246, false),\n            FixedTrait::new(440270, false),\n            FixedTrait::new(1146880, false),\n            FixedTrait::new(512917, false),\n            FixedTrait::new(458752, false),\n            FixedTrait::new(21626880, false),\n            FixedTrait::new(1251737, false),\n            FixedTrait::new(12805, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(708444, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(27066, false),\n            FixedTrait::new(409272, false),\n            FixedTrait::new(406323, false),\n            FixedTrait::new(346508, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(19988480, false),\n            FixedTrait::new(1258291, false),\n            FixedTrait::new(758769, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(1186201, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(45875, false),\n            FixedTrait::new(330039, false),\n            FixedTrait::new(6356992, false),\n            FixedTrait::new(115998, false),\n            FixedTrait::new(1572864, false),\n            FixedTrait::new(43646976, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(2369, false),\n            FixedTrait::new(5242880, false),\n            FixedTrait::new(324403, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(26935, false),\n            FixedTrait::new(434503, false),\n            FixedTrait::new(1533542, false),\n            FixedTrait::new(335328, false),\n            FixedTrait::new(262144, false),\n            FixedTrait::new(16056320, false),\n            FixedTrait::new(1258291, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/boston_data/boston_y_labels.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn boston_y_labels() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![50].span(),\n        data: array![\n            FixedTrait::new(1422131, false),\n            FixedTrait::new(1199308, false),\n            FixedTrait::new(1638400, false),\n            FixedTrait::new(878182, false),\n            FixedTrait::new(1251737, false),\n            FixedTrait::new(1120665, false),\n            FixedTrait::new(2175795, false),\n            FixedTrait::new(688128, false),\n            FixedTrait::new(1284505, false),\n            FixedTrait::new(1651507, false),\n            FixedTrait::new(1284505, false),\n            FixedTrait::new(3276800, false),\n            FixedTrait::new(904396, false),\n            FixedTrait::new(1625292, false),\n            FixedTrait::new(1638400, false),\n            FixedTrait::new(1448345, false),\n            FixedTrait::new(2044723, false),\n            FixedTrait::new(1330380, false),\n            FixedTrait::new(1559756, false),\n            FixedTrait::new(976486, false),\n            FixedTrait::new(1323827, false),\n            FixedTrait::new(1546649, false),\n            FixedTrait::new(1310720, false),\n            FixedTrait::new(3198156, false),\n            FixedTrait::new(668467, false),\n            FixedTrait::new(1415577, false),\n            FixedTrait::new(1526988, false),\n            FixedTrait::new(2437939, false),\n            FixedTrait::new(2031616, false),\n            FixedTrait::new(1435238, false),\n            FixedTrait::new(1166540, false),\n            FixedTrait::new(1841561, false),\n            FixedTrait::new(1481113, false),\n            FixedTrait::new(3014656, false),\n            FixedTrait::new(1022361, false),\n            FixedTrait::new(1225523, false),\n            FixedTrait::new(1428684, false),\n            FixedTrait::new(1743257, false),\n            FixedTrait::new(1238630, false),\n            FixedTrait::new(2188902, false),\n            FixedTrait::new(1618739, false),\n            FixedTrait::new(1985740, false),\n            FixedTrait::new(1369702, false),\n            FixedTrait::new(1520435, false),\n            FixedTrait::new(1625292, false),\n            FixedTrait::new(865075, false),\n            FixedTrait::new(1717043, false),\n            FixedTrait::new(1533542, false),\n            FixedTrait::new(635699, false),\n            FixedTrait::new(1828454, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/linear_data.cairo",
        "content": "mod feature_data;\nmod label_data;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/linear_data/feature_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn x_feature_data() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![50].span(),\n        data: array![\n            FixedTrait::new(19671, false),\n            FixedTrait::new(23085, true),\n            FixedTrait::new(74876, true),\n            FixedTrait::new(22894, true),\n            FixedTrait::new(13690, true),\n            FixedTrait::new(38444, false),\n            FixedTrait::new(54983, false),\n            FixedTrait::new(61020, false),\n            FixedTrait::new(18716, false),\n            FixedTrait::new(58008, false),\n            FixedTrait::new(49440, true),\n            FixedTrait::new(82107, false),\n            FixedTrait::new(33615, false),\n            FixedTrait::new(19535, true),\n            FixedTrait::new(32015, false),\n            FixedTrait::new(4952, true),\n            FixedTrait::new(74162, false),\n            FixedTrait::new(99602, false),\n            FixedTrait::new(143233, false),\n            FixedTrait::new(91520, true),\n            FixedTrait::new(94641, true),\n            FixedTrait::new(33060, true),\n            FixedTrait::new(10488, false),\n            FixedTrait::new(57420, false),\n            FixedTrait::new(20685, false),\n            FixedTrait::new(132526, true),\n            FixedTrait::new(20067, true),\n            FixedTrait::new(54262, false),\n            FixedTrait::new(15079, false),\n            FixedTrait::new(49939, false),\n            FixedTrait::new(14570, true),\n            FixedTrait::new(13156, true),\n            FixedTrait::new(12226, false),\n            FixedTrait::new(26873, false),\n            FixedTrait::new(12995, false),\n            FixedTrait::new(7799, false),\n            FixedTrait::new(43952, true),\n            FixedTrait::new(24744, false),\n            FixedTrait::new(7983, false),\n            FixedTrait::new(74021, false),\n            FixedTrait::new(78572, false),\n            FixedTrait::new(12134, false),\n            FixedTrait::new(24594, true),\n            FixedTrait::new(41859, true),\n            FixedTrait::new(27754, false),\n            FixedTrait::new(5068, false),\n            FixedTrait::new(22534, true),\n            FixedTrait::new(2857, false),\n            FixedTrait::new(40632, true),\n            FixedTrait::new(45746, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/linear_data/label_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn y_label_data() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![50].span(),\n        data: array![\n            FixedTrait::new(6817428, false),\n            FixedTrait::new(6328827, false),\n            FixedTrait::new(5919977, false),\n            FixedTrait::new(6300125, false),\n            FixedTrait::new(6500794, false),\n            FixedTrait::new(6710325, false),\n            FixedTrait::new(7107816, false),\n            FixedTrait::new(6991879, false),\n            FixedTrait::new(6724238, false),\n            FixedTrait::new(7001326, false),\n            FixedTrait::new(6253898, false),\n            FixedTrait::new(7075450, false),\n            FixedTrait::new(6801393, false),\n            FixedTrait::new(6372144, false),\n            FixedTrait::new(6884026, false),\n            FixedTrait::new(6441896, false),\n            FixedTrait::new(7135599, false),\n            FixedTrait::new(7292890, false),\n            FixedTrait::new(7702237, false),\n            FixedTrait::new(5859629, false),\n            FixedTrait::new(5724338, false),\n            FixedTrait::new(6364135, false),\n            FixedTrait::new(6696592, false),\n            FixedTrait::new(7045896, false),\n            FixedTrait::new(6778122, false),\n            FixedTrait::new(5448575, false),\n            FixedTrait::new(6385007, false),\n            FixedTrait::new(6926370, false),\n            FixedTrait::new(6656679, false),\n            FixedTrait::new(6987870, false),\n            FixedTrait::new(6391707, false),\n            FixedTrait::new(6422343, false),\n            FixedTrait::new(6606377, false),\n            FixedTrait::new(6713193, false),\n            FixedTrait::new(6613575, false),\n            FixedTrait::new(6615164, false),\n            FixedTrait::new(6128755, false),\n            FixedTrait::new(6766914, false),\n            FixedTrait::new(6726246, false),\n            FixedTrait::new(7194405, false),\n            FixedTrait::new(7169606, false),\n            FixedTrait::new(6592503, false),\n            FixedTrait::new(6307876, false),\n            FixedTrait::new(6329638, false),\n            FixedTrait::new(6778962, false),\n            FixedTrait::new(6552402, false),\n            FixedTrait::new(6385833, false),\n            FixedTrait::new(6714099, false),\n            FixedTrait::new(6236415, false),\n            FixedTrait::new(6960018, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/user_inputs_data.cairo",
        "content": "mod user_inputs_boston_data;\nmod aave_weth_revenue_data_input;\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/user_inputs_data/aave_weth_revenue_data_input.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\nfn aave_weth_revenue_data_input() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![7, 9].span(),\n        data: array![\n            FixedTrait::new(160, false),\n            FixedTrait::new(786432, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(16973824, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10354688, false),\n            FixedTrait::new(1952972, false),\n            FixedTrait::new(5852364, false),\n            FixedTrait::new(198574079, false),\n            FixedTrait::new(185, false),\n            FixedTrait::new(681574, false),\n            FixedTrait::new(1048576, false),\n            FixedTrait::new(17170432, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1959526, false),\n            FixedTrait::new(5891686, false),\n            FixedTrait::new(207093760, false),\n            FixedTrait::new(211, false),\n            FixedTrait::new(688128, false),\n            FixedTrait::new(1055129, false),\n            FixedTrait::new(17301504, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1952972, false),\n            FixedTrait::new(5963776, false),\n            FixedTrait::new(206438400, false),\n            FixedTrait::new(236, false),\n            FixedTrait::new(707788, false),\n            FixedTrait::new(1055129, false),\n            FixedTrait::new(17367040, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1907097, false),\n            FixedTrait::new(6035865, false),\n            FixedTrait::new(203161600, false),\n            FixedTrait::new(261, false),\n            FixedTrait::new(792985, false),\n            FixedTrait::new(1061683, false),\n            FixedTrait::new(17432576, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1880883, false),\n            FixedTrait::new(6134169, false),\n            FixedTrait::new(195952639, false),\n            FixedTrait::new(285, false),\n            FixedTrait::new(792985, false),\n            FixedTrait::new(1061683, false),\n            FixedTrait::new(17432576, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1880883, false),\n            FixedTrait::new(6153830, false),\n            FixedTrait::new(195952639, false),\n            FixedTrait::new(308, false),\n            FixedTrait::new(792985, false),\n            FixedTrait::new(1061683, false),\n            FixedTrait::new(17498112, false),\n            FixedTrait::new(4128, false),\n            FixedTrait::new(10420224, false),\n            FixedTrait::new(1887436, false),\n            FixedTrait::new(6180044, false),\n            FixedTrait::new(196607999, false),\n        ]\n            .span()\n    );\n\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/datasets/user_inputs_data/user_inputs_boston_data.cairo",
        "content": "use array::ArrayTrait;\nuse orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq};\nuse orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\nuse orion::numbers::{FP16x16, FixedTrait};\n\n\nfn user_input_boston_housing() -> Tensor<FP16x16> {\n    let tensor = TensorTrait::<\n        FP16x16\n    >::new(\n        shape: array![11].span(),\n        data: array![\n            FixedTrait::new(26719, false),\n            FixedTrait::new(0, false),\n            FixedTrait::new(406323, false),\n            FixedTrait::new(65536, false),\n            FixedTrait::new(33226, false),\n            FixedTrait::new(403963, false),\n            FixedTrait::new(5983436, false),\n            FixedTrait::new(199753, false),\n            FixedTrait::new(524288, false),\n            FixedTrait::new(20119552, false),\n            FixedTrait::new(1140326, false),\n        ]\n            .span()\n    );\n    return tensor;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/helper_functions.cairo",
        "content": "use debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\n\nuse orion::numbers::{FP16x16, FixedTrait};\n\n// retrieves row data by index in a 2D tensor\nfn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n    let column_len = *tensor_data.shape.at(1); //13\n    // crete new array\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // loop through the x values and append values \n    let mut i: u32 = 0;\n    loop {\n        if i >= column_len {\n            break ();\n        }\n        result.append(tensor_data.at(indices: array![row_index, i].span()));\n        i += 1;\n    };\n    let resultant_tensor = TensorTrait::<\n        FP16x16\n    >::new(array![column_len].span(), data: result.span());\n    return resultant_tensor;\n}\n\n\n// transposes tensor\nfn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n    return tensor_transposed;\n}\n\nfn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    return mean;\n}\n\n// Calculates the R-Squared score between two tensors.\nfn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n    let mut Y_values_ = Y_values;\n    let mean_y_value = calculate_mean(Y_values);\n    // creating the appropriate tensor shapes and empty arrays to populate values into\n    let mut squared_diff_shape = array::ArrayTrait::new();\n    squared_diff_shape.append(Y_values.data.len());\n    let mut squared_diff_vals = array::ArrayTrait::new();\n    let mut squared_mean_diff_shape = array::ArrayTrait::new();\n    squared_mean_diff_shape.append(Y_values.data.len());\n    let mut squared_mean_diff_vals = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match Y_values_.data.pop_front() {\n            Option::Some(y_value) => {\n                let diff_pred = *y_value - *Y_pred_values.data.at(i);\n                let squared_diff = diff_pred * diff_pred;\n                squared_diff_vals.append(squared_diff);\n\n                let diff_mean = *y_value - mean_y_value;\n                let squared_mean_diff = diff_mean * diff_mean;\n                squared_mean_diff_vals.append(squared_mean_diff);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        }\n    };\n\n    let squared_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_diff_shape.span(), squared_diff_vals.span());\n    let squared_mean_diff_tensor = TensorTrait::<\n        FP16x16\n    >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n    let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n    let sum_squared_mean_diff = squared_mean_diff_tensor\n        .cumsum(0, Option::None(()), Option::None(()));\n    let r_score = FixedTrait::new_unscaled(1, false)\n        - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n            / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n\n    return r_score;\n}\n\n\n// computes the x_min, x_max and x_range. Used for helping in normalizing and denormalizing user inputed values operations\nfn normalize_user_x_inputs(\n    x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut x_inputs_normalized = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut x_min = ArrayTrait::<FP16x16>::new();\n    let mut x_max = ArrayTrait::<FP16x16>::new();\n    let mut x_range = ArrayTrait::<FP16x16>::new();\n    let mut result = ArrayTrait::<FP16x16>::new();\n\n    if original_x_values.shape.len() > 1 {\n        let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n        let data_len = *transposed_tensor.shape.at(0); //13\n        // loop through each row calculating the min, max and range row values for each feature columns\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n            x_min.append(transposed_tensor_row.min_in_tensor());\n            x_max.append(transposed_tensor_row.max_in_tensor());\n            x_range\n                .append(\n                    transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n                );\n            i += 1;\n        };\n        let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n        let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n        let mut x_range_tensor = TensorTrait::new(\n            shape: array![data_len].span(), data: x_range.span()\n        );\n\n        // for normalizing 2D user inputed feature vals\n        if x_inputs.shape.len() > 1 {\n            let mut j: u32 = 0;\n            loop {\n                if j >= *x_inputs.shape.at(0) {\n                    break ();\n                };\n                let mut row_data = get_tensor_data_by_row(x_inputs, j);\n                let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n                let mut k: u32 = 0;\n\n                loop {\n                    if k >= norm_row_data.data.len() {\n                        break ();\n                    };\n                    result.append(*norm_row_data.data.at(k));\n                    k += 1;\n                };\n                j += 1;\n            };\n            x_inputs_normalized =\n                TensorTrait::<\n                    FP16x16\n                >::new(\n                    array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n                );\n        };\n\n        // for normalizing 1D feature input\n        if x_inputs.shape.len() == 1 {\n            x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n        };\n    }\n\n    if original_x_values.shape.len() == 1 {\n        let mut x_min_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n        let mut x_max_tensor = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n        let mut x_range_tensor = TensorTrait::<\n            FP16x16\n        >::new(\n            shape: array![1].span(),\n            data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n                .span()\n        );\n        let mut diff = ((x_inputs - x_min_tensor));\n        x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n    };\n    return x_inputs_normalized;\n}\n\n\n// rescales model predictions to standard format\nfn rescale_predictions(\n    prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut rescale_predictions = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut y_min_array = ArrayTrait::<FP16x16>::new();\n    let mut y_max_array = ArrayTrait::<FP16x16>::new();\n    let mut y_range_array = ArrayTrait::<FP16x16>::new();\n\n    let mut y_max = y_values.max_in_tensor();\n    let mut y_min = y_values.min_in_tensor();\n    let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n    // convert to tensor format for ease of math operations\n    let y_min_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_min].span());\n    let y_max_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_max].span());\n    let y_range_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![y_range].span());\n\n    rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n\n    return rescale_predictions;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/lib.cairo",
        "content": "mod test;\nmod data_preprocessing;\nmod helper_functions;\nmod datasets;\nmod model;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/model.cairo",
        "content": "mod linear_regression_model;\nmod multiple_linear_regression_model;\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/model/linear_regression_model.cairo",
        "content": "use orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n#[derive(Copy, Drop)]\nstruct LinearRegressionModel {\n    gradient: Tensor<FP16x16>,\n    bias: Tensor<FP16x16>\n}\n\n#[generate_trait]\nimpl RegressionOperation of LinearRegressionModelTrait {\n    fn predict(ref self: LinearRegressionModel, x_input: Tensor<FP16x16>) -> Tensor<FP16x16> {\n        let gradient = self.gradient;\n        let bias = self.bias;\n        let mut prediction = (gradient * x_input) + bias;\n        return prediction;\n    }\n}\n\nfn LinearRegression(dataset: Dataset) -> LinearRegressionModel {\n    let gradient = compute_gradient(dataset);\n    let bias = compute_bias(dataset);\n    return LinearRegressionModel { gradient, bias };\n}\n\n// computes the mean of a given 1D tensor and outputs result as tensor\nfn compute_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n    let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n    let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n    let mean = *sum_result / tensor_size;\n    let mut result_tensor = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![mean].span());\n    return result_tensor;\n}\n\n\n/// Calculates the deviation of each element from the mean of the provided 1D tensor.\nfn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut tensor_data_ = tensor_data;\n    let mean_value = calculate_mean(tensor_data);\n    let mut tensor_shape = array::ArrayTrait::new();\n    tensor_shape.append(tensor_data.data.len());\n    let mut deviation_values = array::ArrayTrait::new();\n\n    let mut i: u32 = 0;\n\n    loop {\n        match tensor_data_.data.pop_front() {\n            Option::Some(tensor_val) => {\n                let distance_from_mean = *tensor_val - mean_value;\n                deviation_values.append(distance_from_mean);\n                i += 1;\n            },\n            Option::None(_) => { break; }\n        };\n    };\n    let distance_from_mean_tensor = TensorTrait::<\n        FP16x16\n    >::new(tensor_shape.span(), deviation_values.span());\n\n    return distance_from_mean_tensor;\n}\n\n/// Calculates the beta value for linear regression.\nfn compute_gradient(dataset: Dataset) -> Tensor<FP16x16> {\n    let x_deviation = deviation_from_mean(dataset.x_values);\n    let y_deviation = deviation_from_mean(dataset.y_values);\n\n    let x_y_covariance = x_deviation.matmul(@y_deviation);\n    let x_variance = x_deviation.matmul(@x_deviation);\n\n    let beta_value = x_y_covariance / x_variance;\n\n    return beta_value;\n}\n\n\n/// Calculates the intercept for linear regression.\nfn compute_bias(dataset: Dataset) -> Tensor<FP16x16> {\n    let x_mean = compute_mean(dataset.x_values);\n    let y_mean = compute_mean(dataset.y_values);\n    let gradient = compute_gradient(dataset);\n    let mx = gradient * x_mean;\n    let intercept = y_mean - mx;\n    return intercept;\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/model/multiple_linear_regression_model.cairo",
        "content": "use orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\n\n#[derive(Copy, Drop)]\nstruct MultipleLinearRegressionModel {\n    coefficients: Tensor<FP16x16>\n}\n\n#[generate_trait]\nimpl RegressionOperation of MultipleLinearRegressionModelTrait {\n    // reconstruct the y values using the computed gradients and x values\n    fn predict(\n        ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\n    ) -> Tensor<FP16x16> {\n        // random tensor value that we will replace\n        let mut prediction_result = TensorTrait::<\n            FP16x16\n        >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n        let mut result = ArrayTrait::<FP16x16>::new();\n        // for multiple predictions\n        if feature_inputs.shape.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            let mut data_len: u32 = *feature_values.shape.at(0);\n            let mut i: u32 = 0;\n            loop {\n                if i >= data_len {\n                    break ();\n                }\n                let feature_row_values = get_tensor_data_by_row(feature_values, i);\n                let predicted_values = feature_row_values.matmul(@self.coefficients);\n                result.append(*predicted_values.data.at(0));\n                i += 1;\n            };\n            prediction_result =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![result.len()].span(), data: result.span());\n        }\n\n        // for single predictions \n        if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\n            let feature_values = add_bias_term(feature_inputs, 1);\n            prediction_result = feature_values.matmul(@self.coefficients);\n        }\n\n        return prediction_result;\n    }\n}\n\nfn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\n    let x_values_tranposed = transpose_tensor(dataset.x_values);\n    let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\n    let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\n    let coefficients = compute_gradients(\n        decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\n    );\n    return MultipleLinearRegressionModel { coefficients };\n}\n\n//Adds bias term to features based on axis\nfn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\n    let mut x_feature_ = x_feature;\n    let mut tensor_with_bias = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n    let mut result = ArrayTrait::<FP16x16>::new();\n    // check if feature data has multiple rows and columns\n    if x_feature.shape.len() > 1 {\n        let mut index: u32 = 0;\n        if axis == 1 {\n            index = 0;\n        } else {\n            index = 1;\n        }\n        let data_len = *x_feature.shape.at(index); // 50\n        let mut i: u32 = 0;\n        loop {\n            if i >= data_len {\n                break ();\n            }\n            result\n                .append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n            i += 1;\n        };\n        if axis == 0 {\n            let res_tensor = TensorTrait::new(\n                shape: array![1, data_len].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        } else {\n            let res_tensor = TensorTrait::new(\n                shape: array![data_len, 1].span(), data: result.span()\n            );\n            tensor_with_bias =\n                TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n        }\n    }\n    // check if feature data is 1D\n    if x_feature.shape.len() == 1 {\n        let mut j: u32 = 0;\n        loop {\n            match x_feature_.data.pop_front() {\n                Option::Some(x_val) => {\n                    result.append(*x_val);\n                    j += 1;\n                },\n                Option::None(_) => { break; }\n            };\n        };\n        result.append(FixedTrait::new(65536, false)); //65536=ONE in FP16x16, change accordingly  \n        tensor_with_bias =\n            TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\n    }\n    return tensor_with_bias;\n}\n\n// decorrelates the feature data (*only the last tensor row of the decorelated feature data will be fully orthogonal)\nfn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n    let mut input_tensor = x_feature_data;\n\n    let mut i: u32 = 0;\n    loop {\n        if i >= *x_feature_data.shape.at(0) {\n            break ();\n        }\n        let mut placeholder = ArrayTrait::<FP16x16>::new();\n        let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\n        let mut feature_squared = feature_row_values.matmul(@feature_row_values);\n        // avoiding division by zero errors\n        if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\n            feature_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // loop throgh remaining tensor data and remove the individual tensor factors from one another \n        let mut j: u32 = i + 1;\n        loop {\n            if j >= *x_feature_data.shape.at(0) {\n                break ();\n            }\n            let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\n            let feature_cross_product = feature_row_values.matmul(@remaining_tensor_values);\n            let feature_gradients = feature_cross_product / feature_squared;\n            remaining_tensor_values = remaining_tensor_values\n                - (feature_row_values\n                    * feature_gradients); //remove the feature factors from one another\n            // loop and append the modifieed remaining_tensor_values (after the corelated factor has been removed) to placeholder array\n            let mut k: u32 = 0;\n            loop {\n                if k >= remaining_tensor_values.data.len() {\n                    break ();\n                }\n                placeholder.append(*remaining_tensor_values.data.at(k));\n                k += 1;\n            };\n\n            j += 1;\n        };\n        // convert placeholder array to tensor format and update the original tensor with the new modified decorrelated tensor row values\n        let mut decorrelated_tensor = TensorTrait::new(\n            shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\n            data: placeholder.span()\n        );\n        let mut original_tensor = input_tensor\n            .slice(\n                starts: array![0, 0].span(),\n                ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\n                axes: Option::None(()),\n                steps: Option::Some(array![1, 1].span())\n            );\n        input_tensor =\n            TensorTrait::concat(\n                tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\n            );\n        i += 1;\n    };\n    return input_tensor;\n}\n\n// computes the corresponding MLR gradient using decorrelated feature\nfn compute_gradients(\n    decorrelated_x_features: Tensor<FP16x16>,\n    y_values: Tensor<FP16x16>,\n    original_x_tensor_values: Tensor<FP16x16>\n) -> Tensor<FP16x16> {\n    let mut gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n\n    let mut result = ArrayTrait::<FP16x16>::new();\n    let mut tensor_y_vals = y_values;\n    let mut i: u32 = *decorrelated_x_features.shape.at(0);\n    // loop through Decorrelated_x_features starting from the fully orthogonlised last tensor row value\n    loop {\n        if i <= 0 {\n            break ();\n        }\n        let index_val = i - 1;\n        let mut decorelated_feature_row_values = get_tensor_data_by_row(\n            decorrelated_x_features, index_val\n        ); // 50 vals\n        let mut decorelated_features_squared = decorelated_feature_row_values\n            .matmul(@decorelated_feature_row_values);\n        let mut feature_label_cross_product = tensor_y_vals\n            .matmul(@decorelated_feature_row_values); // multiply the tensors\n        // avoiding division by zero errors\n        if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\n            decorelated_features_squared =\n                TensorTrait::<\n                    FP16x16\n                >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n        }\n        // computing the feature gradient values using the y values and decorrelated x features and appending to array\n        let mut single_gradient_value = feature_label_cross_product\n            / decorelated_features_squared; // devide the summed value by each other\n        result.append(*single_gradient_value.data.at(0));\n        // remove the assosciated feature gradient value away from y values\n        let mut original_x_tensor_row_values = get_tensor_data_by_row(\n            original_x_tensor_values, index_val\n        );\n        tensor_y_vals = tensor_y_vals\n            - (original_x_tensor_row_values\n                * single_gradient_value); //remove the first feature from second feature values\n        i -= 1;\n    };\n    // convert the gradient array to tensor format\n    let final_gradients = TensorTrait::new(\n        shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\n    );\n\n    let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\n    let mut data_len: u32 = final_gradients.data.len();\n    loop {\n        if data_len <= 0 {\n            break ();\n        }\n        let temp_val = data_len - 1;\n        reverse_grad_array.append(*final_gradients.data.at(temp_val));\n        data_len -= 1;\n    };\n    // convert gradient values to tensor format\n    let gradient_values_flipped = TensorTrait::<\n        FP16x16\n    >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\n\n    return gradient_values_flipped;\n}\n\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/finance/provable_multiple_linear_regression_solver/src/test.cairo",
        "content": "// use traits::Into;\nuse debug::PrintTrait;\nuse array::{ArrayTrait, SpanTrait};\n\nuse multiple_linear_regresion::datasets::aave_data::aave_x_features::aave_x_features;\nuse multiple_linear_regresion::datasets::aave_data::aave_y_labels::aave_y_labels;\nuse multiple_linear_regresion::datasets::boston_data::boston_x_features::boston_x_features;\nuse multiple_linear_regresion::datasets::boston_data::boston_y_labels::boston_y_labels;\nuse multiple_linear_regresion::datasets::linear_data::feature_data::x_feature_data;\nuse multiple_linear_regresion::datasets::linear_data::label_data::y_label_data;\nuse multiple_linear_regresion::datasets::user_inputs_data::user_inputs_boston_data::user_input_boston_housing;\nuse multiple_linear_regresion::datasets::user_inputs_data::aave_weth_revenue_data_input::{\n    aave_weth_revenue_data_input\n};\n\nuse orion::numbers::{FP16x16, FixedTrait};\nuse multiple_linear_regresion::model::linear_regression_model::{\n    LinearRegressionModel, compute_mean, LinearRegression, LinearRegressionModelTrait\n};\nuse multiple_linear_regresion::model::multiple_linear_regression_model::{\n    MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\n};\nuse multiple_linear_regresion::data_preprocessing::{\n    Dataset, DatasetTrait, normalize_feature_data, normalize_label_data\n};\nuse multiple_linear_regresion::helper_functions::{\n    get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n    normalize_user_x_inputs, rescale_predictions\n};\n\nuse orion::operators::tensor::{\n    Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n    FP16x16TensorDiv, FP16x16TensorMul\n};\n\n#[test]\n#[available_gas(99999999999999999)]\nfn multiple_linear_regression_test() {\n    // -------------------------------------------------------------------AAVE dataset tests---------------------------------------------------------------------------------------------\n\n    let mut main_x_vals = aave_x_features();\n    let mut main_y_vals = aave_y_labels();\n    let mut dataset = Dataset { x_values: main_x_vals, y_values: main_y_vals };\n    let mut normalized_dataset = dataset.normalize_dataset();\n    let mut model = MultipleLinearRegression(normalized_dataset);\n    let mut model_coefficients = model.coefficients;\n    let mut reconstructed_ys = model.predict(normalized_dataset.x_values);\n    let mut r_squared_score = calculate_r_score(normalized_dataset.y_values, reconstructed_ys);\n    r_squared_score.print();\n\n    // checking if data has been normalized correctly\n    assert(\n        normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false),\n        'normalized x not between 0-1'\n    );\n    assert(\n        normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false),\n        'normalized x not between 0-1'\n    );\n    assert(\n        normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false),\n        'normalized y not between 0-1'\n    );\n    assert(\n        normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false),\n        'normalized y not between 0-1'\n    );\n    // performing checks on the shape of normalized data\n    assert(\n        normalized_dataset.x_values.data.len() == main_x_vals.data.len()\n            && normalized_dataset.y_values.data.len() == main_y_vals.data.len(),\n        'normalized data shape mismatch'\n    );\n    // performing checks on shape on coefficient values (gradient vals + bias)\n    assert(\n        model.coefficients.data.len() == *main_x_vals.shape.at(1) + 1,\n        'coefficient data shape mismatch'\n    );\n    // model accuracy deviance checks\n    assert(r_squared_score >= FixedTrait::new(62259, false), 'AAVE model acc. less than 95%');\n\n    // using model to forecast aave's 7 day WETH lifetime repayments forecast \n    let last_7_days_aave_data = aave_weth_revenue_data_input();\n    let last_7_days_aave_data_normalized = normalize_user_x_inputs(\n        last_7_days_aave_data, main_x_vals\n    );\n    let mut forecast_results = model.predict(last_7_days_aave_data_normalized);\n    let mut rescale_forecasts = rescale_predictions(\n        forecast_results, main_y_vals\n    ); // PS. ** the rescaled forecasted ouputs are in denominated thousands of ETH\n    (*rescale_forecasts.data.at(0)).print();\n    (*rescale_forecasts.data.at(1)).print();\n    (*rescale_forecasts.data.at(2)).print();\n    (*rescale_forecasts.data.at(5)).print();\n    (*rescale_forecasts.data.at(6)).print();\n// -------------------------------------------------------------------Boston dataset tests---------------------------------------------------------------------------------------------\n\n// let mut main_x_vals = boston_x_features();\n// let mut main_y_vals = boston_y_labels();\n// let mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\n// let mut normalized_dataset = dataset.normalize_dataset();\n// let mut model  = MultipleLinearRegression(normalized_dataset);\n// let mut model_coefficients = model.coefficients;\n// let mut reconstructed_ys = model.predict (normalized_dataset.x_values);\n// let mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\n// r_squared_score.print(); \n\n// // checking if data has been normalized correctly\n// assert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\n// assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\n// assert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\n// assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\n// // performing checks on the shape of normalized data\n// assert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \n// normalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\n// // performing checks on shape on coefficient values (gradient vals + bias)\n// assert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\n// // model accuracy deviance checks\n// assert(r_squared_score >= FixedTrait::new(55699, false), 'Boston model acc. less than 84%');\n\n// // boston user inputed house valuation predictions\n// let user_input = user_input_boston_housing();\n// let mut normalized_user_x_inputs = normalize_user_x_inputs(user_input, main_x_vals) ;\n// let mut prediction_result  = model.predict (normalized_user_x_inputs); \n// let mut rescale_prediction  = rescale_predictions(prediction_result, main_y_vals);\n// (*rescale_prediction.data.at(0)).print(); \n\n// // ----------------------------------------------------------------Simple Linear regression tests---------------------------------------------------------------------------------\n\n// let mut main_x_vals = x_feature_data();\n// let mut main_y_vals = y_label_data();\n// let dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\n// let mut model = LinearRegression(dataset);\n// let gradient = model.gradient;\n// let mut reconstructed_ys = model.predict(main_x_vals);\n// let mut r_squared_score = calculate_r_score(main_y_vals,reconstructed_ys);\n// r_squared_score.print(); \n\n// // // performing checks on shape on coefficient values (gradient vals + bias) \n// // assert(model.gradient.data.len() == 1,  'gradient data shape mismatch');\n// // assert(model.bias.data.len() == 1,  'bias data shape mismatch');\n// // // model accuracy deviance checks\n// // assert(r_squared_score >= FixedTrait::new(62259, false), 'Linear model acc. less than 95%');\n\n// // linear regression model new input predictions\n// let mut user_value =   TensorTrait::<FP16x16>::new(shape: array![2].span(), data: array![FixedTrait::new(65536, false), FixedTrait::new(65536, true)].span());\n// let mut prediction_results = model.predict(user_value);\n// (*prediction_results.data.at(0)).print(); \n// (*prediction_results.data.at(1)).print();\n\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Importing required moduless\\n\",\n    \"import numpy as np \\n\",\n    \"import pandas as pd \\n\",\n    \"import pprint,random\\n\",\n    \"\\n\",\n    \"from scipy.ndimage.interpolation import shift\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"from keras.models import Sequential\\n\",\n    \"from keras.layers import Dense,Dropout\\n\",\n    \"from keras.optimizers import SGD\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Creating a Tic Tac Toe Game\\n\",\n    \"In order for a program to learn how to play Tic-Tac-Toe, we first need to create the Tic-Tac-Toe game\\n\",\n    \"\\n\",\n    \"Below, we create a simple tic tac toe game using Numpy\\n\",\n    \"\\n\",\n    \"Below are the details of the Numpy Tic Tac Toe Game:\\n\",\n    \"\\n\",\n    \"* The game board is a 3 * 3 numpy array\\n\",\n    \"* The below is the denotation used:\\n\",\n    \"    * 2: placeholder/empty cell\\n\",\n    \"    * 0: 'O'\\n\",\n    \"    * 1: 'X'\\n\",\n    \"* By default, the array is filled with the number 2 as placeholder\\n\",\n    \"* The number 0 denotes an 'O' and the number 1 denotes an 'X'\\n\",\n    \"* Players take turns in choosing the coordinates of the numpy array where they will place 0 or 1 respectively\\n\",\n    \"* The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game\\n\",\n    \"* For simplicity, the program always plays with the mark 1 and the opponent plays with 0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"class tic_tac_toe_game(object):\\n\",\n    \"    def __init__(self):\\n\",\n    \"        self.board=np.full((3,3),2)\\n\",\n    \"\\n\",\n    \"    def toss(self):\\n\",\n    \"        \\\"\\\"\\\"Function to simulate a toss and decide which player goes first\\n\",\n    \"\\n\",\n    \"        Args:\\n\",\n    \"\\n\",\n    \"        Returns:\\n\",\n    \"        Returns 1 if player assigned mark 1 has won, or 0 if his opponent won\\n\",\n    \"\\n\",\n    \"        \\\"\\\"\\\"\\n\",\n    \"        turn=np.random.randint(0,2,size=1)\\n\",\n    \"        if turn.mean()==0:\\n\",\n    \"            self.turn_monitor=0\\n\",\n    \"        elif turn.mean()==1:\\n\",\n    \"            self.turn_monitor=1\\n\",\n    \"        return self.turn_monitor\\n\",\n    \"\\n\",\n    \"    def move(self,player,coord):\\n\",\n    \"        \\\"\\\"\\\"Function to perform the action of placing a mark on the tic tac toe board\\n\",\n    \"        After performing the action, this function flips the value of the turn_monitor to \\n\",\n    \"        the next player\\n\",\n    \"\\n\",\n    \"        Args:\\n\",\n    \"        player: 1 if player who is assigned the mark 1 is performing the action, \\n\",\n    \"        0 if his opponent is performing the action\\n\",\n    \"        coord: The coordinate where the 1 or 0 is to be placed on the \\n\",\n    \"        tic-tac-toe board (numpy array)\\n\",\n    \"\\n\",\n    \"        Returns:\\n\",\n    \"        game_status(): Calls the game status function and returns its value\\n\",\n    \"        board: Returns the new board state after making the move\\n\",\n    \"\\n\",\n    \"        \\\"\\\"\\\"\\n\",\n    \"        if self.board[coord]!=2 or self.game_status()!=\\\"In Progress\\\" or self.turn_monitor!=player:\\n\",\n    \"            raise ValueError(\\\"Invalid move\\\")\\n\",\n    \"        self.board[coord]=player\\n\",\n    \"        self.turn_monitor=1-player\\n\",\n    \"        return self.game_status(),self.board\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"    def game_status(self):\\n\",\n    \"        \\\"\\\"\\\"Function to check the current status of the game, \\n\",\n    \"        whether the game has been won, drawn or is in progress\\n\",\n    \"\\n\",\n    \"        Args:\\n\",\n    \"\\n\",\n    \"        Returns:\\n\",\n    \"        \\\"Won\\\" if the game has been won, \\\"Drawn\\\" if the \\n\",\n    \"        game has been drawn, or \\\"In Progress\\\", if the game is still in progress\\n\",\n    \"\\n\",\n    \"        \\\"\\\"\\\"\\n\",\n    \"        #check for a win along rows\\n\",\n    \"        for i in range(self.board.shape[0]):\\n\",\n    \"            if 2 not in self.board[i,:] and len(set(self.board[i,:]))==1:\\n\",\n    \"                return \\\"Won\\\"\\n\",\n    \"        #check for a win along columns\\n\",\n    \"        for j in range(self.board.shape[1]):\\n\",\n    \"            if 2 not in self.board[:,j] and len(set(self.board[:,j]))==1:\\n\",\n    \"                return \\\"Won\\\"\\n\",\n    \"        # check for a win along diagonals\\n\",\n    \"        if 2 not in np.diag(self.board) and len(set(np.diag(self.board)))==1:\\n\",\n    \"            return \\\"Won\\\"\\n\",\n    \"        if 2 not in np.diag(np.fliplr(self.board)) and len(set(np.diag(np.fliplr(self.board))))==1:\\n\",\n    \"            return \\\"Won\\\"\\n\",\n    \"        # check for a Draw\\n\",\n    \"        if not 2 in self.board:\\n\",\n    \"            return \\\"Drawn\\\"\\n\",\n    \"        else:\\n\",\n    \"            return \\\"In Progress\\\"\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Testing the Tic Tac Toe game\\n\",\n    \"\\n\",\n    \"To simply test the tic-tac-toe game created above, let us play a dummy game. We make the moves for both the players.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# create an object of the class tick_tac_toe_game\\n\",\n    \"game=tic_tac_toe_game()\\n\",\n    \"# toss to decide which player goes first\\n\",\n    \"game.toss()\\n\",\n    \"print(\\\"Player \\\",game.turn_monitor,\\\" has won the toss\\\")\\n\",\n    \"# make the first move\\n\",\n    \"print(\\\"Initial board state \\\\n\\\",game.board)\\n\",\n    \"print(\\\"Let first player place their mark on 0,0\\\")\\n\",\n    \"game_status,board=game.move(game.turn_monitor,(0,0))\\n\",\n    \"print(\\\"New Board State: \\\\n\\\",board)\\n\",\n    \"print(\\\"Let second player place their mark on 0,1\\\")\\n\",\n    \"game_status,board=game.move(game.turn_monitor,(0,1))\\n\",\n    \"print(\\\"New Board State: \\\\n\\\",board)\\n\",\n    \"print(\\\"Let first player place their mark on 1,1\\\")\\n\",\n    \"game_status,board=game.move(game.turn_monitor,(1,1))\\n\",\n    \"print(\\\"New Board State: \\\\n\\\",board)\\n\",\n    \"print(\\\"Let second player place their mark on 0,2\\\")\\n\",\n    \"game_status,board=game.move(game.turn_monitor,(0,2))\\n\",\n    \"print(\\\"New Board State: \\\\n\\\",board)\\n\",\n    \"print(\\\"Let first player place their mark on 2,2\\\")\\n\",\n    \"game_status,board=game.move(game.turn_monitor,(2,2))\\n\",\n    \"print(\\\"New Board State: \\\\n\\\",board)\\n\",\n    \"print(\\\"Player \\\",1-game.turn_monitor,\\\" Has \\\",game_status)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Creating the Legal Moves Generator\\n\",\n    \"\\n\",\n    \"The legal moves genator accepts the board state and player as input, and provides the set of all possible legal moves as output.\\n\",\n    \"\\n\",\n    \"Basically, for a given board state and player, it tells us where all the player can place his mark legally (the player can only place the mark where there is no opponent's mark)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def legal_moves_generator(current_board_state,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function that returns the set of all possible legal moves and resulting board states, \\n\",\n    \"    for a given input board state and player\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    current_board_state: The current board state\\n\",\n    \"    turn_monitor: 1 if it's the player who places the mark 1's turn to play, 0 if its his opponent's turn\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    legal_moves_dict: A dictionary of a list of possible next coordinate-resulting board state pairs\\n\",\n    \"    The resulting board state is flattened to 1 d array\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    legal_moves_dict={}\\n\",\n    \"    for i in range(current_board_state.shape[0]):\\n\",\n    \"        for j in range(current_board_state.shape[1]):\\n\",\n    \"            if current_board_state[i,j]==2:\\n\",\n    \"                board_state_copy=current_board_state.copy()\\n\",\n    \"                board_state_copy[i,j]=turn_monitor\\n\",\n    \"                legal_moves_dict[(i,j)]=board_state_copy.flatten()\\n\",\n    \"    return legal_moves_dict\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Testing the Legal Moves Generator\\n\",\n    \"\\n\",\n    \"Let us test the above created Legal Moves Generator.\\n\",\n    \"\\n\",\n    \"We start a dummy game, and do the toss. We then pass the current board state and toss winner to the Legal Moves Generator. It returns the dictionary of legal moves that it returns the dictionary is of the form \\\"possible next legal move coordinate\\\":\\\"flattened resulting board state\\\"\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"game=tic_tac_toe_game()\\n\",\n    \"game.toss()\\n\",\n    \"print(\\\"Player \\\",game.turn_monitor,\\\" has won the toss\\\")\\n\",\n    \"print(\\\"Current board state \\\\n\\\",game.board)\\n\",\n    \"legal_moves_dict=legal_moves_generator(game.board,game.turn_monitor)\\n\",\n    \"print(\\\"Dictionary of Possible Next Legal Moves:\\\")\\n\",\n    \"pprint.pprint(legal_moves_dict)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"You can observe above that the Legal Moves Generator returns a dictionary with all the possible legal coordinates and their resulting flattened numpy board states\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Creating the Evaluator (Neural Network Model)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"As defined previously, the Evaluator function maps board states to scores.\\n\",\n    \"\\n\",\n    \"It is expected that after training, the Evaluator learns to assign higher scores to board states that are favourable to the program.\\n\",\n    \"In our kernel, we use a neural network as an Evaluator Function.\\n\",\n    \"\\n\",\n    \"Below, we create the neural network. The weights of the neural network are intialized randomly.\\n\",\n    \"The neural network takes the flattened tic-tac-toe board numpy array as input and outputs a score.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model = Sequential()\\n\",\n    \"model.add(Dense(18, input_dim=9,kernel_initializer='normal', activation='relu'))\\n\",\n    \"model.add(Dropout(0.1))\\n\",\n    \"model.add(Dense(9, kernel_initializer='normal',activation='relu'))\\n\",\n    \"model.add(Dropout(0.1))\\n\",\n    \"model.add(Dense(1,kernel_initializer='normal'))\\n\",\n    \"\\n\",\n    \"learning_rate = 0.001\\n\",\n    \"momentum = 0.8\\n\",\n    \"\\n\",\n    \"sgd = SGD(lr=learning_rate, momentum=momentum,nesterov=False)\\n\",\n    \"model.compile(loss='mean_squared_error', optimizer=sgd)\\n\",\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Creating the Program Move Selector\\n\",\n    \"\\n\",\n    \"The Program Move Selector selects the next move for a player given the current board state using the following approach:\\n\",\n    \"* Use the Legal Moves Generator to get all the possible next legal board states.\\n\",\n    \"* Use the Evaluator (model) to score each possible next board state.\\n\",\n    \"* The next board state that is assigned the highest score is selected as the next board state.\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def move_selector(model,current_board_state,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function that selects the next move to make from a set of possible legal moves\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    model: The Evaluator function to use to evaluate each possible next board state\\n\",\n    \"    turn_monitor: 1 if it's the player who places the mark 1's turn to play, 0 if its his opponent's turn\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The numpy array coordinates where the player should place thier mark\\n\",\n    \"    new_board_state: The flattened new board state resulting from performing above selected move\\n\",\n    \"    score: The score that was assigned to the above selected_move by the Evaluator (model)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    tracker={}\\n\",\n    \"    legal_moves_dict=legal_moves_generator(current_board_state,turn_monitor)\\n\",\n    \"    for legal_move_coord in legal_moves_dict:\\n\",\n    \"        score=model.predict(legal_moves_dict[legal_move_coord].reshape(1,9))\\n\",\n    \"        tracker[legal_move_coord]=score\\n\",\n    \"    selected_move=max(tracker, key=tracker.get)\\n\",\n    \"    new_board_state=legal_moves_dict[selected_move]\\n\",\n    \"    score=tracker[selected_move]\\n\",\n    \"    return selected_move,new_board_state,score\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Testing the Program Move Selector\\n\",\n    \"\\n\",\n    \"Let us play a dummy game and use the above created Program Move Selector function to select the next move\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# new game\\n\",\n    \"game=tic_tac_toe_game()\\n\",\n    \"# toss\\n\",\n    \"game.toss()\\n\",\n    \"# choose the first move\\n\",\n    \"print(\\\"Player assigned mark 1\\\",game.turn_monitor,\\\" won the toss\\\")\\n\",\n    \"print(\\\"Initial board state:\\\")\\n\",\n    \"print(game.board)\\n\",\n    \"selected_move,new_board_state,score=move_selector(model,game.board,game.turn_monitor)\\n\",\n    \"print(\\\"Selected move: \\\",selected_move)\\n\",\n    \"print(\\\"Resulting new board state: \\\",new_board_state)\\n\",\n    \"print(\\\"Score assigned to above board state by Evaluator(model): \\\", score)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Please note that since the Evaluator (model) has not yet been trained and has been assigned random weights, hence the score above is a random number\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Creating the opponent (The Opponent Move Selector)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For our program to self learn, it needs to play several games of tic-tac-toe.\\n\",\n    \"\\n\",\n    \"But with who will it play with?\\n\",\n    \"\\n\",\n    \"The program learns by playing games against a coded opponent.\\n\",\n    \"\\n\",\n    \"The opponent is coded to do the following:\\n\",\n    \"\\n\",\n    \"1. If playing in \\\"Easy\\\" mode:\\n\",\n    \"\\n\",\n    \"    * When it is your turn, use the Legal Moves Generator to get all possible legal next moves\\n\",\n    \"    * Pick a legal move at random\\n\",\n    \"    * Repeat above until the end of the game\\n\",\n    \"\\n\",\n    \"2. If playing in \\\"Hard\\\" mode:\\n\",\n    \"\\n\",\n    \"    * When it is your turn, use the Legal Moves Generator to get all possible legal next moves\\n\",\n    \"    * Of the above legal moves, if any legal move makes you win (along row/column/diagonal), pick that legal move\\n\",\n    \"    * Else, if any legal move prevents your opponent (program) from winning when it is one move away from a win, pick that move\\n\",\n    \"    * Else, if any legal move leads to a row/diagonal/column having two 0's and no 1's (program's mark) , pick that legal move\\n\",\n    \"    * If none of the above conditions exist, pick a legal move at random\\n\",\n    \"\\n\",\n    \"The Program is trained by repeatedly playing games against the above opponent and updating the weights of the model at the end of each game.\\n\",\n    \"\\n\",\n    \"Each game is played at either \\\"Easy\\\" or \\\"Hard\\\" mode, which is picked at random at the start of each game.\\n\",\n    \"\\n\",\n    \"The \\\"Easy\\\" mode helps the Program explore the tic-tac-toe space. The \\\"Hard\\\" mode helps the Program learn how to play with a real opponent.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def row_winning_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan rowwise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a winning board state\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to win for the opponent\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        #check for a win along rows\\n\",\n    \"        for i in range(current_board_state_copy.shape[0]):\\n\",\n    \"            if 2 not in current_board_state_copy[i,:] and len(set(current_board_state_copy[i,:]))==1:\\n\",\n    \"                selected_move=legal_move_coord\\n\",\n    \"                return selected_move\\n\",\n    \"            \\n\",\n    \"def column_winning_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan column wise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a winning board state\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to win for the opponent\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        for j in range(current_board_state_copy.shape[1]):\\n\",\n    \"                    if 2 not in current_board_state_copy[:,j] and len(set(current_board_state_copy[:,j]))==1:\\n\",\n    \"                        selected_move=legal_move_coord\\n\",\n    \"                        return selected_move\\n\",\n    \"\\n\",\n    \"def diag1_winning_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan diagonal and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a winning board state\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to win for the opponent\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        if 2 not in np.diag(current_board_state_copy) and len(set(np.diag(current_board_state_copy)))==1:\\n\",\n    \"            selected_move=legal_move_coord\\n\",\n    \"            return selected_move\\n\",\n    \"            \\n\",\n    \"def diag2_winning_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan second diagonal and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a winning board state\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to win for the opponent\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        if 2 not in np.diag(np.fliplr(current_board_state_copy)) and len(set(np.diag(np.fliplr(current_board_state_copy))))==1:\\n\",\n    \"            selected_move=legal_move_coord\\n\",\n    \"            return selected_move\\n\",\n    \"            \\n\",\n    \"#------------#\\n\",\n    \"\\n\",\n    \"def row_block_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan rowwise and identify coordinate amongst the legal coordinates \\n\",\n    \"    that will prevent the program \\n\",\n    \"    from winning\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will block 1 from winning\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        for i in range(current_board_state_copy.shape[0]):\\n\",\n    \"            if 2 not in current_board_state_copy[i,:] and (current_board_state_copy[i,:]==1).sum()==2:\\n\",\n    \"                if not (2 not in current_board_state[i,:] and (current_board_state[i,:]==1).sum()==2):\\n\",\n    \"                    selected_move=legal_move_coord\\n\",\n    \"                    return selected_move\\n\",\n    \"            \\n\",\n    \"def column_block_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan column wise and identify coordinate amongst the legal coordinates that will prevent 1 \\n\",\n    \"    from winning\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will block 1 from winning\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        \\n\",\n    \"        for j in range(current_board_state_copy.shape[1]):\\n\",\n    \"                    if 2 not in current_board_state_copy[:,j] and (current_board_state_copy[:,j]==1).sum()==2:\\n\",\n    \"                        if not (2 not in current_board_state[:,j] and (current_board_state[:,j]==1).sum()==2):\\n\",\n    \"                            selected_move=legal_move_coord\\n\",\n    \"                            return selected_move\\n\",\n    \"\\n\",\n    \"def diag1_block_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan diagonal 1 and identify coordinate amongst the legal coordinates that will prevent 1 \\n\",\n    \"    from winning\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will block 1 from winning\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor    \\n\",\n    \"        if 2 not in np.diag(current_board_state_copy) and (np.diag(current_board_state_copy)==1).sum()==2:\\n\",\n    \"                if not (2 not in np.diag(current_board_state) and (np.diag(current_board_state)==1).sum()==2):\\n\",\n    \"                    selected_move=legal_move_coord\\n\",\n    \"                    return selected_move\\n\",\n    \"            \\n\",\n    \"def diag2_block_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan second diagonal wise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a column having only 0s\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to two 0s being there (and no 1s)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        if 2 not in np.diag(np.fliplr(current_board_state_copy)) and (np.diag(np.fliplr(current_board_state_copy))==1).sum()==2:\\n\",\n    \"            if not (2 not in np.diag(np.fliplr(current_board_state)) and (np.diag(np.fliplr(current_board_state))==1).sum()==2):\\n\",\n    \"                selected_move=legal_move_coord\\n\",\n    \"                return selected_move\\n\",\n    \"\\n\",\n    \"#---------------#\\n\",\n    \"def row_second_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan rowwise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a row having two 0s and no 1s\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to two 0s being there (and no 1s)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        \\n\",\n    \"        for i in range(current_board_state_copy.shape[0]):\\n\",\n    \"            if 1 not in current_board_state_copy[i,:] and (current_board_state_copy[i,:]==0).sum()==2:\\n\",\n    \"                if not (1 not in current_board_state[i,:] and (current_board_state[i,:]==0).sum()==2):\\n\",\n    \"                    selected_move=legal_move_coord\\n\",\n    \"                    return selected_move\\n\",\n    \"            \\n\",\n    \"def column_second_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan column wise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a column having two 0s and no 1s\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to two 0s being there (and no 1s)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        \\n\",\n    \"        for j in range(current_board_state_copy.shape[1]):\\n\",\n    \"                    if 1 not in current_board_state_copy[:,j] and (current_board_state_copy[:,j]==0).sum()==2:\\n\",\n    \"                        if not (1 not in current_board_state[:,j] and (current_board_state[:,j]==0).sum()==2):\\n\",\n    \"                            selected_move=legal_move_coord\\n\",\n    \"                            return selected_move\\n\",\n    \"\\n\",\n    \"def diag1_second_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan diagonal wise and identify coordinate amongst the legal coordinates that will\\n\",\n    \"    result in a column having two 0s and no 1s\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to two 0s being there (and no 1s)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        if 1 not in np.diag(current_board_state_copy) and (np.diag(current_board_state_copy)==0).sum()==2:\\n\",\n    \"            if not (1 not in np.diag(current_board_state) and (np.diag(current_board_state)==0).sum()==2):\\n\",\n    \"                selected_move=legal_move_coord\\n\",\n    \"                return selected_move\\n\",\n    \"            \\n\",\n    \"def diag2_second_move_check(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"    \\\"\\\"\\\"Function to scan second diagonal wise and identify coordinate amongst \\n\",\n    \"    the legal coordinates that will result in a column having two 0s and no 1s\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    legal_moves_dict: Dictionary of legal next moves\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    \\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where opponent places their mark\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_move_coords =  list(legal_moves_dict.keys())\\n\",\n    \"    random.shuffle(legal_move_coords)\\n\",\n    \"    for legal_move_coord in legal_move_coords:\\n\",\n    \"        current_board_state_copy=current_board_state.copy()\\n\",\n    \"        current_board_state_copy[legal_move_coord]=turn_monitor\\n\",\n    \"        if 1 not in np.diag(np.fliplr(current_board_state_copy)) and (np.diag(np.fliplr(current_board_state_copy))==0).sum()==2:\\n\",\n    \"            if not (1 not in np.diag(np.fliplr(current_board_state)) and (np.diag(np.fliplr(current_board_state))==0).sum()==2):\\n\",\n    \"                selected_move=legal_move_coord\\n\",\n    \"                return selected_move\\n\",\n    \"    \\n\",\n    \"def opponent_move_selector(current_board_state,turn_monitor,mode):\\n\",\n    \"    \\\"\\\"\\\"Function that picks a legal move for the opponent\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    current_board_state: Current board state\\n\",\n    \"    turn_monitor: whose turn it is to move\\n\",\n    \"    mode: whether hard or easy mode\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    selected_move: The coordinates of numpy array where placing the 0 will lead to two 0s being there (and no 1s)\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    legal_moves_dict=legal_moves_generator(current_board_state,turn_monitor)\\n\",\n    \"    \\n\",\n    \"    winning_move_checks=[row_winning_move_check,column_winning_move_check,diag1_winning_move_check,diag2_winning_move_check]\\n\",\n    \"    block_move_checks=[row_block_move_check,column_block_move_check,diag1_block_move_check,diag2_block_move_check]\\n\",\n    \"    second_move_checks=[row_second_move_check,column_second_move_check,diag1_second_move_check,diag2_second_move_check]\\n\",\n    \"\\n\",\n    \"    if mode==\\\"Hard\\\":\\n\",\n    \"        random.shuffle(winning_move_checks)\\n\",\n    \"        random.shuffle(block_move_checks)\\n\",\n    \"        random.shuffle(second_move_checks)        \\n\",\n    \"        \\n\",\n    \"        for fn in winning_move_checks:\\n\",\n    \"            if fn(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"                return fn(current_board_state,legal_moves_dict,turn_monitor)\\n\",\n    \"            \\n\",\n    \"        for fn in block_move_checks:\\n\",\n    \"            if fn(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"                return fn(current_board_state,legal_moves_dict,turn_monitor)\\n\",\n    \"            \\n\",\n    \"        for fn in second_move_checks:\\n\",\n    \"            if fn(current_board_state,legal_moves_dict,turn_monitor):\\n\",\n    \"                return fn(current_board_state,legal_moves_dict,turn_monitor)\\n\",\n    \"            \\n\",\n    \"        selected_move=random.choice(list(legal_moves_dict.keys()))\\n\",\n    \"        return selected_move\\n\",\n    \"    \\n\",\n    \"    elif mode==\\\"Easy\\\":\\n\",\n    \"        legal_moves_dict=legal_moves_generator(current_board_state,turn_monitor)\\n\",\n    \"        selected_move=random.choice(list(legal_moves_dict.keys()))\\n\",\n    \"        return selected_move\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Training the Program\\n\",\n    \"\\n\",\n    \"Training the progam is essentially training the Evaluator(model) to assign higher scores to board states favourable to the program, and lower scores to board states unfavourable to the program.\\n\",\n    \"\\n\",\n    \"The progam is expected to learn by playing games against the Opponent.\\n\",\n    \"\\n\",\n    \"The Evaluator (model) is trained in the following way:\\n\",\n    \"\\n\",\n    \"* At first the weights of the model are randomly assigned\\n\",\n    \"* Using this model, the Move Selector function selects the next move to make for the program\\n\",\n    \"* The program and the opponent make thier moves until the game ends\\n\",\n    \"* After the game is completed, the scores are corrected as follows:\\n\",\n    \"    * If the game was Won by the program, assign the score 1 to the final board state, or assign -1 if lost or 0 if drawn\\n\",\n    \"    * Shift the remaining scores so that they become the scores of the previous board states\\n\",\n    \"    * Update the weights of the model using the board state and corrected score\\n\",\n    \"* The above process is repeated over 100s of thousands of games\\n\",\n    \"* It is expected that eventually, the Evaluator (model) learns to assign higher scores to more favourable board states and lower scores to less favourable board states\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def train(model,mode,print_progress=False):\\n\",\n    \"    \\\"\\\"\\\"Function trains the Evaluator (model) by playing a game against an opponent \\n\",\n    \"    playing random moves, and updates the weights of the model after the game\\n\",\n    \"    \\n\",\n    \"    Note that the model weights are updated using SGD with a batch size of 1\\n\",\n    \"\\n\",\n    \"    Args:\\n\",\n    \"    model: The Evaluator function being trained\\n\",\n    \"\\n\",\n    \"    Returns:\\n\",\n    \"    model: The model updated using SGD\\n\",\n    \"    y: The corrected scores\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\" \\n\",\n    \"    # start the game\\n\",\n    \"    if print_progress==True:\\n\",\n    \"        print(\\\"___________________________________________________________________\\\")\\n\",\n    \"        print(\\\"Starting a new game\\\")\\n\",\n    \"    game=tic_tac_toe_game()\\n\",\n    \"    game.toss()\\n\",\n    \"    scores_list=[]\\n\",\n    \"    corrected_scores_list=[]\\n\",\n    \"    new_board_states_list=[]\\n\",\n    \"    \\n\",\n    \"    while(1):\\n\",\n    \"        if game.game_status()==\\\"In Progress\\\" and game.turn_monitor==1:\\n\",\n    \"            # If its the program's turn, use the Move Selector function to select the next move\\n\",\n    \"            selected_move,new_board_state,score=move_selector(model,game.board,game.turn_monitor)\\n\",\n    \"            scores_list.append(score[0][0])\\n\",\n    \"            new_board_states_list.append(new_board_state)\\n\",\n    \"            # Make the next move\\n\",\n    \"            game_status,board=game.move(game.turn_monitor,selected_move)\\n\",\n    \"            if print_progress==True:\\n\",\n    \"                print(\\\"Program's Move\\\")\\n\",\n    \"                print(board)\\n\",\n    \"                print(\\\"\\\\n\\\")\\n\",\n    \"        elif game.game_status()==\\\"In Progress\\\" and game.turn_monitor==0:\\n\",\n    \"            selected_move=opponent_move_selector(game.board,game.turn_monitor,mode=mode)\\n\",\n    \"        \\n\",\n    \"            # Make the next move\\n\",\n    \"            game_status,board=game.move(game.turn_monitor,selected_move)\\n\",\n    \"            if print_progress==True:\\n\",\n    \"                print(\\\"Opponent's Move\\\")\\n\",\n    \"                print(board)\\n\",\n    \"                print(\\\"\\\\n\\\")\\n\",\n    \"        else:\\n\",\n    \"            break\\n\",\n    \"\\n\",\n    \"    \\n\",\n    \"    # Correct the scores, assigning 1/0/-1 to the winning/drawn/losing final board state, \\n\",\n    \"    # and assigning the other previous board states the score of their next board state\\n\",\n    \"    new_board_states_list=tuple(new_board_states_list)\\n\",\n    \"    new_board_states_list=np.vstack(new_board_states_list)\\n\",\n    \"    if game_status==\\\"Won\\\" and (1-game.turn_monitor)==1: \\n\",\n    \"        corrected_scores_list=shift(scores_list,-1,cval=1.0)\\n\",\n    \"        result=\\\"Won\\\"\\n\",\n    \"    if game_status==\\\"Won\\\" and (1-game.turn_monitor)!=1:\\n\",\n    \"        corrected_scores_list=shift(scores_list,-1,cval=-1.0)\\n\",\n    \"        result=\\\"Lost\\\"\\n\",\n    \"    if game_status==\\\"Drawn\\\":\\n\",\n    \"        corrected_scores_list=shift(scores_list,-1,cval=0.0)\\n\",\n    \"        result=\\\"Drawn\\\"\\n\",\n    \"    if print_progress==True:\\n\",\n    \"        print(\\\"Program has \\\",result)\\n\",\n    \"        print(\\\"\\\\n Correcting the Scores and Updating the model weights:\\\")\\n\",\n    \"        print(\\\"___________________________________________________________________\\\\n\\\")\\n\",\n    \"        \\n\",\n    \"    x=new_board_states_list\\n\",\n    \"    y=corrected_scores_list\\n\",\n    \"    \\n\",\n    \"    def unison_shuffled_copies(a, b):\\n\",\n    \"        assert len(a) == len(b)\\n\",\n    \"        p = np.random.permutation(len(a))\\n\",\n    \"        return a[p], b[p]\\n\",\n    \"    \\n\",\n    \"    # shuffle x and y in unison\\n\",\n    \"    x,y=unison_shuffled_copies(x,y)\\n\",\n    \"    x=x.reshape(-1,9) \\n\",\n    \"    \\n\",\n    \"    # update the weights of the model, one record at a time\\n\",\n    \"    model.fit(x,y,epochs=1,batch_size=1,verbose=0)\\n\",\n    \"    return model,y,result\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### A sample single training game\\n\",\n    \"\\n\",\n    \"Note that the program will always play the mark '1' and the opponent will always play mark '0'.\\n\",\n    \"\\n\",\n    \"below, we run a single iteration of training, or in other words, a single game of tic-tac-toe between the program and opponent.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"updated_model,y,result=train(model,mode=\\\"Hard\\\",print_progress=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Training by playing a large number of games\\n\",\n    \"\\n\",\n    \"We play 200,000 games of tic-tac-toe between the program and the opponent. We record the result of each game and plot the distribution of wins/losses/draws by the program over fixed intervals of games\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"game_counter=1\\n\",\n    \"data_for_graph=pd.DataFrame()\\n\",\n    \"\\n\",\n    \"mode_list=[\\\"Easy\\\",\\\"Hard\\\"]\\n\",\n    \"\\n\",\n    \"while(game_counter<=200000):\\n\",\n    \"    mode_selected=np.random.choice(mode_list, 1, p=[0.5,0.5])\\n\",\n    \"    model,y,result=train(model,mode=mode_selected[0],print_progress=False)\\n\",\n    \"    # data_for_graph=data_for_graph.append({\\\"game_counter\\\":game_counter,\\\"result\\\":result},ignore_index=True)\\n\",\n    \"    if game_counter % 10000 == 0:\\n\",\n    \"        print(\\\"Game#: \\\",game_counter)\\n\",\n    \"        print(\\\"Mode: \\\",mode_selected[0])\\n\",\n    \"    game_counter+=1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.save('model/ttt.h5')  # creates a HDF5 file 'ttt.h5'\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Play Against AI\\n\",\n    \"Below you can play against AI agent\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def play_with_model(model):\\n\",\n    \"    # Start a new game\\n\",\n    \"    game = tic_tac_toe_game()\\n\",\n    \"    game.toss()\\n\",\n    \"    current_player = \\\"Human\\\" if game.turn_monitor == 0 else \\\"Model\\\"\\n\",\n    \"\\n\",\n    \"    print(f\\\"{current_player} won the toss\\\")\\n\",\n    \"\\n\",\n    \"    # Game loop\\n\",\n    \"    while game.game_status() == \\\"In Progress\\\":\\n\",\n    \"        print(\\\"Current board state:\\\")\\n\",\n    \"        print(game.board)\\n\",\n    \"        \\n\",\n    \"        if game.turn_monitor == 0:  # Human's turn\\n\",\n    \"            valid_move = False\\n\",\n    \"            while not valid_move:\\n\",\n    \"                try:\\n\",\n    \"                    move_row = int(input(\\\"Enter the row where you want to place your mark (0, 1, 2): \\\"))\\n\",\n    \"                    move_col = int(input(\\\"Enter the column where you want to place your mark (0, 1, 2): \\\"))\\n\",\n    \"                    game_status, board = game.move(0, (move_row, move_col))\\n\",\n    \"                    valid_move = True\\n\",\n    \"                except ValueError as e:\\n\",\n    \"                    print(e)\\n\",\n    \"                    print(\\\"Try again.\\\")\\n\",\n    \"        else:  # Model's turn\\n\",\n    \"            selected_move, new_board_state, score = move_selector(model, game.board, game.turn_monitor)\\n\",\n    \"            game_status, board = game.move(1, selected_move)\\n\",\n    \"            print(f\\\"Model places at {selected_move}\\\")\\n\",\n    \"\\n\",\n    \"    print(f\\\"Game Over! Status: {game_status}\\\")\\n\",\n    \"    print(\\\"Final board state:\\\")\\n\",\n    \"    print(game.board)\\n\",\n    \"\\n\",\n    \"model = load_model('ttt.h5')\\n\",\n    \"play_with_model(model)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Convert to ONNX\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"! pip install onnx\\n\",\n    \"! pip install keras2onnx\\n\",\n    \"! pip install tensorflow\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.python.keras.models import load_model\\n\",\n    \"import os\\n\",\n    \"os.environ['TF_KERAS'] = '1'\\n\",\n    \"import onnxmltools\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"model = load_model('model/ttt.h5')\\n\",\n    \"onnx_model = onnxmltools.convert_keras(model) \\n\",\n    \"\\n\",\n    \"onnxmltools.utils.save_model(onnx_model, 'model/ttt.onnx')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import onnx\\n\",\n    \"\\n\",\n    \"# Load the ONNX model and check the model structure\\n\",\n    \"onnx_model = onnx.load('model/ttt.onnx')\\n\",\n    \"onnx.checker.check_model(onnx_model)\\n\",\n    \"\\n\",\n    \"# You can print the ONNX model's graph to inspect its structure\\n\",\n    \"print(onnx_model.graph)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.9\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_1_biasadd_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n    Tensor {\n        shape: array![18,].span(),\n        data: array![\n            FP16x16 { mag: 77099, sign: true },\n            FP16x16 { mag: 140625, sign: true },\n            FP16x16 { mag: 59258, sign: true },\n            FP16x16 { mag: 40408, sign: false },\n            FP16x16 { mag: 66634, sign: true },\n            FP16x16 { mag: 27092, sign: false },\n            FP16x16 { mag: 3196, sign: true },\n            FP16x16 { mag: 392, sign: true },\n            FP16x16 { mag: 81839, sign: true },\n            FP16x16 { mag: 39890, sign: true },\n            FP16x16 { mag: 16196, sign: false },\n            FP16x16 { mag: 59646, sign: false },\n            FP16x16 { mag: 55690, sign: false },\n            FP16x16 { mag: 181170, sign: true },\n            FP16x16 { mag: 22719, sign: true },\n            FP16x16 { mag: 91746, sign: false },\n            FP16x16 { mag: 141435, sign: true },\n            FP16x16 { mag: 123843, sign: true },\n        ]\n            .span()\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_1_matmul_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n    Tensor {\n        shape: array![9, 18,].span(),\n        data: array![\n            FP16x16 { mag: 3955, sign: false },\n            FP16x16 { mag: 31098, sign: true },\n            FP16x16 { mag: 56097, sign: false },\n            FP16x16 { mag: 5925, sign: true },\n            FP16x16 { mag: 11807, sign: false },\n            FP16x16 { mag: 14772, sign: true },\n            FP16x16 { mag: 62093, sign: true },\n            FP16x16 { mag: 2509, sign: true },\n            FP16x16 { mag: 78328, sign: false },\n            FP16x16 { mag: 112161, sign: true },\n            FP16x16 { mag: 39446, sign: true },\n            FP16x16 { mag: 75575, sign: true },\n            FP16x16 { mag: 2793, sign: true },\n            FP16x16 { mag: 86022, sign: false },\n            FP16x16 { mag: 2420, sign: true },\n            FP16x16 { mag: 64022, sign: true },\n            FP16x16 { mag: 13386, sign: false },\n            FP16x16 { mag: 36355, sign: true },\n            FP16x16 { mag: 60754, sign: false },\n            FP16x16 { mag: 6195, sign: true },\n            FP16x16 { mag: 32924, sign: false },\n            FP16x16 { mag: 18469, sign: false },\n            FP16x16 { mag: 77241, sign: true },\n            FP16x16 { mag: 41273, sign: false },\n            FP16x16 { mag: 1430, sign: true },\n            FP16x16 { mag: 892, sign: true },\n            FP16x16 { mag: 32289, sign: false },\n            FP16x16 { mag: 21674, sign: false },\n            FP16x16 { mag: 88897, sign: true },\n            FP16x16 { mag: 74800, sign: true },\n            FP16x16 { mag: 56068, sign: true },\n            FP16x16 { mag: 16620, sign: false },\n            FP16x16 { mag: 21513, sign: true },\n            FP16x16 { mag: 19496, sign: false },\n            FP16x16 { mag: 61824, sign: false },\n            FP16x16 { mag: 26766, sign: true },\n            FP16x16 { mag: 16100, sign: true },\n            FP16x16 { mag: 33159, sign: false },\n            FP16x16 { mag: 45269, sign: true },\n            FP16x16 { mag: 41714, sign: true },\n            FP16x16 { mag: 4038, sign: true },\n            FP16x16 { mag: 12259, sign: true },\n            FP16x16 { mag: 23497, sign: true },\n            FP16x16 { mag: 2852, sign: true },\n            FP16x16 { mag: 16666, sign: false },\n            FP16x16 { mag: 90011, sign: true },\n            FP16x16 { mag: 89479, sign: true },\n            FP16x16 { mag: 47499, sign: true },\n            FP16x16 { mag: 2231, sign: false },\n            FP16x16 { mag: 42105, sign: true },\n            FP16x16 { mag: 27305, sign: true },\n            FP16x16 { mag: 54180, sign: true },\n            FP16x16 { mag: 24296, sign: true },\n            FP16x16 { mag: 53924, sign: false },\n            FP16x16 { mag: 7000, sign: false },\n            FP16x16 { mag: 4234, sign: true },\n            FP16x16 { mag: 41393, sign: false },\n            FP16x16 { mag: 24115, sign: false },\n            FP16x16 { mag: 18438, sign: false },\n            FP16x16 { mag: 13772, sign: false },\n            FP16x16 { mag: 30782, sign: false },\n            FP16x16 { mag: 1532, sign: false },\n            FP16x16 { mag: 14289, sign: false },\n            FP16x16 { mag: 19607, sign: false },\n            FP16x16 { mag: 44319, sign: false },\n            FP16x16 { mag: 20825, sign: true },\n            FP16x16 { mag: 206, sign: false },\n            FP16x16 { mag: 85743, sign: false },\n            FP16x16 { mag: 5984, sign: false },\n            FP16x16 { mag: 28843, sign: true },\n            FP16x16 { mag: 33272, sign: true },\n            FP16x16 { mag: 4101, sign: true },\n            FP16x16 { mag: 10691, sign: true },\n            FP16x16 { mag: 66566, sign: false },\n            FP16x16 { mag: 1461, sign: true },\n            FP16x16 { mag: 64292, sign: true },\n            FP16x16 { mag: 9889, sign: false },\n            FP16x16 { mag: 1602, sign: true },\n            FP16x16 { mag: 79586, sign: false },\n            FP16x16 { mag: 860, sign: true },\n            FP16x16 { mag: 16922, sign: true },\n            FP16x16 { mag: 13655, sign: false },\n            FP16x16 { mag: 3763, sign: false },\n            FP16x16 { mag: 13831, sign: false },\n            FP16x16 { mag: 16606, sign: true },\n            FP16x16 { mag: 31081, sign: true },\n            FP16x16 { mag: 1148, sign: true },\n            FP16x16 { mag: 7401, sign: true },\n            FP16x16 { mag: 5918, sign: false },\n            FP16x16 { mag: 172902, sign: true },\n            FP16x16 { mag: 16803, sign: true },\n            FP16x16 { mag: 2761, sign: false },\n            FP16x16 { mag: 60016, sign: true },\n            FP16x16 { mag: 57641, sign: true },\n            FP16x16 { mag: 25229, sign: true },\n            FP16x16 { mag: 409, sign: true },\n            FP16x16 { mag: 4561, sign: false },\n            FP16x16 { mag: 2739, sign: true },\n            FP16x16 { mag: 33103, sign: false },\n            FP16x16 { mag: 15444, sign: true },\n            FP16x16 { mag: 2938, sign: true },\n            FP16x16 { mag: 9677, sign: false },\n            FP16x16 { mag: 1959, sign: false },\n            FP16x16 { mag: 48004, sign: true },\n            FP16x16 { mag: 21527, sign: true },\n            FP16x16 { mag: 13099, sign: true },\n            FP16x16 { mag: 4516, sign: true },\n            FP16x16 { mag: 61344, sign: false },\n            FP16x16 { mag: 24844, sign: true },\n            FP16x16 { mag: 20932, sign: false },\n            FP16x16 { mag: 32461, sign: false },\n            FP16x16 { mag: 21037, sign: false },\n            FP16x16 { mag: 3844, sign: true },\n            FP16x16 { mag: 63076, sign: true },\n            FP16x16 { mag: 116403, sign: true },\n            FP16x16 { mag: 47, sign: true },\n            FP16x16 { mag: 167757, sign: true },\n            FP16x16 { mag: 33293, sign: false },\n            FP16x16 { mag: 8474, sign: false },\n            FP16x16 { mag: 36467, sign: true },\n            FP16x16 { mag: 5361, sign: false },\n            FP16x16 { mag: 94574, sign: false },\n            FP16x16 { mag: 3961, sign: true },\n            FP16x16 { mag: 20948, sign: false },\n            FP16x16 { mag: 8617, sign: false },\n            FP16x16 { mag: 9743, sign: true },\n            FP16x16 { mag: 67822, sign: false },\n            FP16x16 { mag: 7211, sign: true },\n            FP16x16 { mag: 32215, sign: true },\n            FP16x16 { mag: 18519, sign: false },\n            FP16x16 { mag: 58230, sign: false },\n            FP16x16 { mag: 41745, sign: true },\n            FP16x16 { mag: 8810, sign: true },\n            FP16x16 { mag: 4189, sign: true },\n            FP16x16 { mag: 7625, sign: false },\n            FP16x16 { mag: 17757, sign: false },\n            FP16x16 { mag: 6851, sign: false },\n            FP16x16 { mag: 15698, sign: false },\n            FP16x16 { mag: 68976, sign: true },\n            FP16x16 { mag: 8665, sign: false },\n            FP16x16 { mag: 144, sign: false },\n            FP16x16 { mag: 72523, sign: true },\n            FP16x16 { mag: 70719, sign: false },\n            FP16x16 { mag: 21577, sign: true },\n            FP16x16 { mag: 28121, sign: true },\n            FP16x16 { mag: 20052, sign: false },\n            FP16x16 { mag: 46946, sign: true },\n            FP16x16 { mag: 87657, sign: true },\n            FP16x16 { mag: 33678, sign: true },\n            FP16x16 { mag: 48832, sign: true },\n            FP16x16 { mag: 4698, sign: true },\n            FP16x16 { mag: 878, sign: true },\n            FP16x16 { mag: 41781, sign: true },\n            FP16x16 { mag: 12867, sign: true },\n            FP16x16 { mag: 1281, sign: true },\n            FP16x16 { mag: 12234, sign: false },\n            FP16x16 { mag: 5716, sign: true },\n            FP16x16 { mag: 48745, sign: true },\n            FP16x16 { mag: 11140, sign: false },\n            FP16x16 { mag: 22035, sign: true },\n            FP16x16 { mag: 9363, sign: true },\n            FP16x16 { mag: 67049, sign: false },\n        ]\n            .span()\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_2_biasadd_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n\n   Tensor {\n       shape: array![9,].span(),\n       data: array![\nFP16x16 {mag: 1241, sign: true}, FP16x16 {mag: 32808, sign: true}, FP16x16 {mag: 5666, sign: false}, FP16x16 {mag: 896, sign: false}, FP16x16 {mag: 12018, sign: false}, FP16x16 {mag: 11826, sign: false}, FP16x16 {mag: 3795, sign: false}, FP16x16 {mag: 13949, sign: false}, FP16x16 {mag: 3218, sign: true}, ].span()\n   }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_2_matmul_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n\n   Tensor {\n       shape: array![18,9,].span(),\n       data: array![\nFP16x16 {mag: 2465, sign: false}, FP16x16 {mag: 2340, sign: false}, FP16x16 {mag: 32664, sign: true}, FP16x16 {mag: 16005, sign: false}, FP16x16 {mag: 40259, sign: true}, FP16x16 {mag: 37822, sign: true}, FP16x16 {mag: 2872, sign: true}, FP16x16 {mag: 39356, sign: true}, FP16x16 {mag: 1725, sign: true}, FP16x16 {mag: 11180, sign: true}, FP16x16 {mag: 34264, sign: false}, FP16x16 {mag: 6638, sign: false}, FP16x16 {mag: 3478, sign: false}, FP16x16 {mag: 14102, sign: true}, FP16x16 {mag: 12535, sign: true}, FP16x16 {mag: 12001, sign: true}, FP16x16 {mag: 18569, sign: true}, FP16x16 {mag: 22851, sign: true}, FP16x16 {mag: 12523, sign: false}, FP16x16 {mag: 26931, sign: false}, FP16x16 {mag: 3529, sign: true}, FP16x16 {mag: 13909, sign: true}, FP16x16 {mag: 23747, sign: false}, FP16x16 {mag: 29669, sign: false}, FP16x16 {mag: 14539, sign: false}, FP16x16 {mag: 27740, sign: false}, FP16x16 {mag: 18385, sign: false}, FP16x16 {mag: 30201, sign: true}, FP16x16 {mag: 13759, sign: true}, FP16x16 {mag: 11985, sign: true}, FP16x16 {mag: 71619, sign: false}, FP16x16 {mag: 19944, sign: false}, FP16x16 {mag: 4239, sign: false}, FP16x16 {mag: 33485, sign: true}, FP16x16 {mag: 6481, sign: true}, FP16x16 {mag: 33629, sign: true}, FP16x16 {mag: 2260, sign: false}, FP16x16 {mag: 6532, sign: true}, FP16x16 {mag: 5292, sign: true}, FP16x16 {mag: 24375, sign: false}, FP16x16 {mag: 13574, sign: false}, FP16x16 {mag: 8645, sign: false}, FP16x16 {mag: 7671, sign: false}, FP16x16 {mag: 14861, sign: false}, FP16x16 {mag: 12084, sign: false}, FP16x16 {mag: 7675, sign: true}, FP16x16 {mag: 4015, sign: true}, FP16x16 {mag: 22250, sign: true}, FP16x16 {mag: 15436, sign: true}, FP16x16 {mag: 28003, sign: false}, FP16x16 {mag: 18767, sign: false}, FP16x16 {mag: 6382, sign: true}, FP16x16 {mag: 31147, sign: false}, FP16x16 {mag: 5390, sign: false}, FP16x16 {mag: 17990, sign: false}, FP16x16 {mag: 39474, sign: false}, FP16x16 {mag: 9985, sign: false}, FP16x16 {mag: 33327, sign: true}, FP16x16 {mag: 29900, sign: true}, FP16x16 {mag: 23978, sign: true}, FP16x16 {mag: 9985, sign: false}, FP16x16 {mag: 12197, sign: true}, FP16x16 {mag: 7435, sign: true}, FP16x16 {mag: 639, sign: false}, FP16x16 {mag: 2532, sign: true}, FP16x16 {mag: 5910, sign: false}, FP16x16 {mag: 2848, sign: false}, FP16x16 {mag: 4306, sign: false}, FP16x16 {mag: 1856, sign: true}, FP16x16 {mag: 1251, sign: true}, FP16x16 {mag: 1589, sign: true}, FP16x16 {mag: 2191, sign: true}, FP16x16 {mag: 1067, sign: false}, FP16x16 {mag: 37203, sign: true}, FP16x16 {mag: 4686, sign: false}, FP16x16 {mag: 40127, sign: true}, FP16x16 {mag: 33823, sign: true}, FP16x16 {mag: 23325, sign: true}, FP16x16 {mag: 35514, sign: false}, FP16x16 {mag: 2639, sign: true}, FP16x16 {mag: 46695, sign: false}, FP16x16 {mag: 49480, sign: false}, FP16x16 {mag: 24483, sign: true}, FP16x16 {mag: 2421, sign: true}, FP16x16 {mag: 22600, sign: true}, FP16x16 {mag: 10720, sign: false}, FP16x16 {mag: 5655, sign: false}, FP16x16 {mag: 36440, sign: false}, FP16x16 {mag: 7469, sign: false}, FP16x16 {mag: 37046, sign: false}, FP16x16 {mag: 32540, sign: true}, FP16x16 {mag: 23355, sign: true}, FP16x16 {mag: 18911, sign: true}, FP16x16 {mag: 19967, sign: false}, FP16x16 {mag: 7995, sign: false}, FP16x16 {mag: 2876, sign: false}, FP16x16 {mag: 28494, sign: true}, FP16x16 {mag: 3640, sign: false}, FP16x16 {mag: 55301, sign: true}, FP16x16 {mag: 19263, sign: true}, FP16x16 {mag: 28503, sign: true}, FP16x16 {mag: 20567, sign: true}, FP16x16 {mag: 19075, sign: false}, FP16x16 {mag: 12334, sign: false}, FP16x16 {mag: 9320, sign: false}, FP16x16 {mag: 302, sign: true}, FP16x16 {mag: 8293, sign: false}, FP16x16 {mag: 48929, sign: true}, FP16x16 {mag: 9371, sign: true}, FP16x16 {mag: 7195, sign: false}, FP16x16 {mag: 9507, sign: true}, FP16x16 {mag: 27072, sign: true}, FP16x16 {mag: 31023, sign: false}, FP16x16 {mag: 28161, sign: false}, FP16x16 {mag: 15273, sign: true}, FP16x16 {mag: 27178, sign: false}, FP16x16 {mag: 7702, sign: true}, FP16x16 {mag: 11518, sign: false}, FP16x16 {mag: 10741, sign: false}, FP16x16 {mag: 20454, sign: false}, FP16x16 {mag: 26801, sign: true}, FP16x16 {mag: 27046, sign: true}, FP16x16 {mag: 24313, sign: true}, FP16x16 {mag: 14909, sign: false}, FP16x16 {mag: 28354, sign: true}, FP16x16 {mag: 17081, sign: false}, FP16x16 {mag: 7418, sign: false}, FP16x16 {mag: 25151, sign: false}, FP16x16 {mag: 8309, sign: false}, FP16x16 {mag: 4019, sign: false}, FP16x16 {mag: 16244, sign: true}, FP16x16 {mag: 981, sign: true}, FP16x16 {mag: 306, sign: true}, FP16x16 {mag: 3737, sign: false}, FP16x16 {mag: 6126, sign: false}, FP16x16 {mag: 12213, sign: true}, FP16x16 {mag: 38450, sign: true}, FP16x16 {mag: 22926, sign: true}, FP16x16 {mag: 5183, sign: true}, FP16x16 {mag: 32450, sign: true}, FP16x16 {mag: 30705, sign: true}, FP16x16 {mag: 43870, sign: true}, FP16x16 {mag: 26190, sign: true}, FP16x16 {mag: 54292, sign: true}, FP16x16 {mag: 3506, sign: true}, FP16x16 {mag: 12819, sign: false}, FP16x16 {mag: 46049, sign: true}, FP16x16 {mag: 241, sign: true}, FP16x16 {mag: 64050, sign: true}, FP16x16 {mag: 50948, sign: true}, FP16x16 {mag: 1238, sign: true}, FP16x16 {mag: 52562, sign: true}, FP16x16 {mag: 2508, sign: false}, FP16x16 {mag: 46211, sign: false}, FP16x16 {mag: 7648, sign: true}, FP16x16 {mag: 43005, sign: false}, FP16x16 {mag: 24333, sign: true}, FP16x16 {mag: 20222, sign: true}, FP16x16 {mag: 18892, sign: true}, FP16x16 {mag: 34596, sign: false}, FP16x16 {mag: 16295, sign: true}, FP16x16 {mag: 5455, sign: true}, ].span()\n   }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_3_biasadd_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n\n   Tensor {\n       shape: array![1,].span(),\n       data: array![\nFP16x16 {mag: 17046, sign: false}, ].span()\n   }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/crates/sequential_1_dense_3_matmul_readvariableop_0/src/lib.cairo",
        "content": "use array::{ArrayTrait, SpanTrait};\nuse orion::operators::tensor::{TensorTrait, Tensor};\nuse orion::operators::tensor::FP16x16Tensor;\nuse orion::numbers::{FixedTrait, FP16x16};\n\nfn tensor() -> Tensor<FP16x16> {\n\n   Tensor {\n       shape: array![9,1,].span(),\n       data: array![\nFP16x16 {mag: 15010, sign: true}, FP16x16 {mag: 27195, sign: true}, FP16x16 {mag: 36261, sign: true}, FP16x16 {mag: 26590, sign: false}, FP16x16 {mag: 23070, sign: false}, FP16x16 {mag: 29654, sign: false}, FP16x16 {mag: 25429, sign: true}, FP16x16 {mag: 28541, sign: false}, FP16x16 {mag: 27150, sign: true}, ].span()\n   }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/src/inference.cairo",
        "content": "#[starknet::contract]\nmod OrionRunner {\n    use core::array::SpanTrait;\n    use orion::operators::tensor::{TensorTrait, FP16x16Tensor, Tensor, FP16x16TensorAdd};\n    use orion::operators::nn::{NNTrait, FP16x16NN};\n    use orion::numbers::{FP16x16, FixedTrait};\n\n    use sequential_1_dense_1_matmul_readvariableop_0::tensor as t1;\n    use sequential_1_dense_1_biasadd_readvariableop_0::tensor as t2;\n    use sequential_1_dense_2_matmul_readvariableop_0::tensor as t3;\n    use sequential_1_dense_2_biasadd_readvariableop_0::tensor as t4;\n    use sequential_1_dense_3_matmul_readvariableop_0::tensor as t5;\n    use sequential_1_dense_3_biasadd_readvariableop_0::tensor as t6;\n\n    #[storage]\n    struct Storage {\n        id: u8,\n    }\n\n    #[external(v0)]\n    fn predict(self: @ContractState, mut x: Tensor<FP16x16>) -> FP16x16 {\n        // let two = FixedTrait::<FP16x16>::new_unscaled(2, false);\n        // let mut x = Tensor {\n        //     shape: array![9].span(),\n        //     data: array![two, two, two, two, two, two, two, two, two].span()\n        // };\n\n        // DENSE 1\n        x = TensorTrait::matmul(@x, @t1());\n        x = x + t2();\n        x = NNTrait::relu(@x);\n\n        // DENSE 2\n        x = TensorTrait::matmul(@x, @t3());\n        x = x + t4();\n        x = NNTrait::relu(@x);\n\n        // DENSE 3\n        x = TensorTrait::matmul(@x, @t5());\n        x = x + t6();\n\n        return *x.data.at(0);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/src/lib.cairo",
        "content": "mod inference;\nmod test;"
    },
    {
        "repo": "https://github.com/gizatechxyz/Giza-Hub",
        "file_path": "awesome-orion/gaming/tic_tac_toe/tic_tac_toe_orion/src/test.cairo",
        "content": "#[cfg(test)]\nmod tests {\n    use core::array::SpanTrait;\n    use orion::operators::tensor::{TensorTrait, FP16x16Tensor, Tensor, FP16x16TensorAdd};\n    use orion::operators::nn::{NNTrait, FP16x16NN};\n    use orion::numbers::{FP16x16, FixedTrait};\n\n    use sequential_1_dense_1_matmul_readvariableop_0::tensor as _sequential_1_dense_1_matmul_readvariableop_0;\n    use sequential_1_dense_1_biasadd_readvariableop_0::tensor as _sequential_1_dense_1_biasadd_readvariableop_0;\n    use sequential_1_dense_2_matmul_readvariableop_0::tensor as _sequential_1_dense_2_matmul_readvariableop_0;\n    use sequential_1_dense_2_biasadd_readvariableop_0::tensor as _sequential_1_dense_2_biasadd_readvariableop_0;\n    use sequential_1_dense_3_matmul_readvariableop_0::tensor as _sequential_1_dense_3_matmul_readvariableop_0;\n    use sequential_1_dense_3_biasadd_readvariableop_0::tensor as _sequential_1_dense_3_biasadd_readvariableop_0;\n\n    use debug::PrintTrait;\n\n    #[test]\n    #[available_gas(2000000000000)]\n    fn _main() {\n        let two = FixedTrait::<FP16x16>::new_unscaled(2, false);\n\n        let mut x = Tensor {\n            shape: array![9].span(),\n            data: array![two, two, two, two, two, two, two, two, two].span()\n        };\n\n        // DENSE 1\n        x = TensorTrait::matmul(@x, @_sequential_1_dense_1_matmul_readvariableop_0());\n        x = x + _sequential_1_dense_1_biasadd_readvariableop_0();\n        x = NNTrait::relu(@x);\n\n        // DENSE 2\n        x = TensorTrait::matmul(@x, @_sequential_1_dense_2_matmul_readvariableop_0());\n        x = x + _sequential_1_dense_2_biasadd_readvariableop_0();\n        x = NNTrait::relu(@x);\n\n        // DENSE 3\n        x = TensorTrait::matmul(@x, @_sequential_1_dense_3_matmul_readvariableop_0());\n        x = x + _sequential_1_dense_3_biasadd_readvariableop_0();\n\n        (*x.data.at(0)).print();\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_conv.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_keys;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::srs::gen_srs;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\nstatic mut KERNEL_HEIGHT: usize = 2;\nstatic mut KERNEL_WIDTH: usize = 2;\nstatic mut OUT_CHANNELS: usize = 1;\nstatic mut IMAGE_HEIGHT: usize = 2;\nstatic mut IMAGE_WIDTH: usize = 2;\nstatic mut IN_CHANNELS: usize = 1;\n\nconst K: usize = 17;\n\n#[derive(Clone, Debug)]\nstruct MyCircuit {\n    image: ValTensor<Fr>,\n    kernel: ValTensor<Fr>,\n    bias: ValTensor<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = 10;\n\n        let a = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let b = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let output = VarTensor::new_advice(cs, K, 1, (len + 1) * len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(\n                        &mut region,\n                        &[self.image.clone(), self.kernel.clone(), self.bias.clone()],\n                        Box::new(PolyOp::Conv {\n                            padding: vec![(0, 0)],\n                            stride: vec![1; 2],\n                        }),\n                    )\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runcnvrl(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_conv\");\n\n    let params = gen_srs::<KZGCommitmentScheme<_>>(K as u32);\n\n    for size in [1, 2, 4].iter() {\n        unsafe {\n            KERNEL_HEIGHT = size * 2;\n            KERNEL_WIDTH = size * 2;\n            IMAGE_HEIGHT = size * 4;\n            IMAGE_WIDTH = size * 4;\n            IN_CHANNELS = 1;\n            OUT_CHANNELS = 1;\n\n            let mut image = Tensor::from(\n                (0..IN_CHANNELS * IMAGE_HEIGHT * IMAGE_WIDTH)\n                    .map(|_| Value::known(Fr::random(OsRng))),\n            );\n            image\n                .reshape(&[1, IN_CHANNELS, IMAGE_HEIGHT, IMAGE_WIDTH])\n                .unwrap();\n            let mut kernel = Tensor::from(\n                (0..{ OUT_CHANNELS * IN_CHANNELS * KERNEL_HEIGHT * KERNEL_WIDTH })\n                    .map(|_| Fr::random(OsRng)),\n            );\n            kernel\n                .reshape(&[OUT_CHANNELS, IN_CHANNELS, KERNEL_HEIGHT, KERNEL_WIDTH])\n                .unwrap();\n            kernel.set_visibility(&ezkl::graph::Visibility::Private);\n\n            let mut bias = Tensor::from((0..{ OUT_CHANNELS }).map(|_| Fr::random(OsRng)));\n            bias.set_visibility(&ezkl::graph::Visibility::Private);\n\n            let circuit = MyCircuit {\n                image: ValTensor::from(image),\n                kernel: ValTensor::try_from(kernel).unwrap(),\n                bias: ValTensor::try_from(bias).unwrap(),\n            };\n\n            group.throughput(Throughput::Elements(*size as u64));\n            group.bench_with_input(BenchmarkId::new(\"pk\", size), &size, |b, &_| {\n                b.iter(|| {\n                    create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                        .unwrap();\n                });\n            });\n\n            let pk = create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                .unwrap();\n\n            group.throughput(Throughput::Elements(*size as u64));\n            group.bench_with_input(BenchmarkId::new(\"prove\", size), &size, |b, &_| {\n                b.iter(|| {\n                    let prover = create_proof_circuit::<\n                        KZGCommitmentScheme<_>,\n                        MyCircuit,\n                        ProverSHPLONK<_>,\n                        VerifierSHPLONK<_>,\n                        SingleStrategy<_>,\n                        _,\n                        EvmTranscript<_, _, _, _>,\n                        EvmTranscript<_, _, _, _>,\n                    >(\n                        circuit.clone(),\n                        vec![],\n                        &params,\n                        &pk,\n                        CheckMode::UNSAFE,\n                        ezkl::Commitments::KZG,\n                        TranscriptType::EVM,\n                        None,\n                        None,\n                    );\n                    prover.unwrap();\n                });\n            });\n        }\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runcnvrl\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_dot.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 2],\n    _marker: PhantomData<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len);\n        let b = VarTensor::new_advice(cs, K, 1, len);\n        let output = VarTensor::new_advice(cs, K, 1, len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(\n                        &mut region,\n                        &self.inputs,\n                        Box::new(PolyOp::Einsum {\n                            equation: \"i,i->\".to_string(),\n                        }),\n                    )\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn rundot(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_dot\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [16, 512].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        // parameters\n        let a = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let b = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = rundot\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_einsum_matmul.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 2],\n    _marker: PhantomData<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let b = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let output = VarTensor::new_advice(cs, K, 1, (len + 1) * len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(\n                        &mut region,\n                        &self.inputs,\n                        Box::new(PolyOp::Einsum {\n                            equation: \"ab,bc->ac\".to_string(),\n                        }),\n                    )\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runmatmul(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_einsum_matmul\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [4, 32].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        let mut a = Tensor::from((0..len * len).map(|_| Value::known(Fr::random(OsRng))));\n        a.reshape(&[len, len]).unwrap();\n\n        // parameters\n        let mut b = Tensor::from((0..len * len).map(|_| Value::known(Fr::random(OsRng))));\n        b.reshape(&[len, len]).unwrap();\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runmatmul\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_matmul_relu.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::table::Range;\nuse ezkl::circuit::*;\n\nuse ezkl::circuit::lookup::LookupOp;\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nconst BITS: Range = (-32768, 32768);\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 2],\n    _marker: PhantomData<Fr>,\n}\n\n// A columnar ReLu MLP\n#[derive(Clone)]\nstruct MyConfig {\n    base_config: BaseConfig<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = MyConfig;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len);\n        let b = VarTensor::new_advice(cs, K, 1, len);\n        let output = VarTensor::new_advice(cs, K, 1, len);\n\n        let mut base_config =\n            BaseConfig::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::UNSAFE);\n\n        // sets up a new relu table\n        base_config\n            .configure_lookup(cs, &b, &output, &a, BITS, K, &LookupOp::ReLU)\n            .unwrap();\n\n        MyConfig { base_config }\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        config.base_config.layout_tables(&mut layouter).unwrap();\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let op = PolyOp::Einsum {\n                    equation: \"ij,jk->ik\".to_string(),\n                };\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                let output = config\n                    .base_config\n                    .layout(&mut region, &self.inputs, Box::new(op))\n                    .unwrap();\n                let _output = config\n                    .base_config\n                    .layout(&mut region, &[output.unwrap()], Box::new(LookupOp::ReLU))\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n\n        Ok(())\n    }\n}\n\nfn runmatmul(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_matmul\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [4, 32].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        let mut a = Tensor::from((0..len * len).map(|_| Value::known(Fr::from(1))));\n        a.reshape(&[len, len]).unwrap();\n\n        // parameters\n        let mut b = Tensor::from((0..len).map(|_| Value::known(Fr::from(1))));\n        b.reshape(&[len, 1]).unwrap();\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runmatmul\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_matmul_relu_overflow.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::*;\n\nuse ezkl::circuit::lookup::LookupOp;\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::table::Range;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nconst BITS: Range = (-8180, 8180);\nstatic mut LEN: usize = 4;\nstatic mut K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 2],\n    _marker: PhantomData<Fr>,\n}\n\n// A columnar ReLu MLP\n#[derive(Clone)]\nstruct MyConfig {\n    base_config: BaseConfig<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = MyConfig;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n        let k = unsafe { K };\n\n        let a = VarTensor::new_advice(cs, k, 1, len);\n        let b = VarTensor::new_advice(cs, k, 1, len);\n        let output = VarTensor::new_advice(cs, k, 1, len);\n\n        let mut base_config =\n            BaseConfig::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::UNSAFE);\n\n        // sets up a new relu table\n        base_config\n            .configure_lookup(cs, &b, &output, &a, BITS, k, &LookupOp::ReLU)\n            .unwrap();\n\n        MyConfig { base_config }\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        config.base_config.layout_tables(&mut layouter).unwrap();\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let op = PolyOp::Einsum {\n                    equation: \"ij,jk->ik\".to_string(),\n                };\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                let output = config\n                    .base_config\n                    .layout(&mut region, &self.inputs, Box::new(op))\n                    .unwrap();\n                let _output = config\n                    .base_config\n                    .layout(&mut region, &[output.unwrap()], Box::new(LookupOp::ReLU))\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n\n        Ok(())\n    }\n}\n\nfn runmatmul(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_matmul\");\n\n    for &k in [8, 10, 11, 12, 13, 14].iter() {\n        let len = unsafe { LEN };\n        unsafe {\n            K = k;\n        };\n        let params = gen_srs::<KZGCommitmentScheme<_>>(k as u32);\n\n        let mut a = Tensor::from((0..len * len).map(|_| Value::known(Fr::from(1))));\n        a.reshape(&[len, len]).unwrap();\n\n        // parameters\n        let mut b = Tensor::from((0..len).map(|_| Value::known(Fr::from(1))));\n        b.reshape(&[len, 1]).unwrap();\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(k as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", k), &k, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(k as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", k), &k, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots().sample_size(10);\n  targets = runmatmul\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_sum.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 1],\n    _marker: PhantomData<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len);\n        let b = VarTensor::new_advice(cs, K, 1, len);\n        let output = VarTensor::new_advice(cs, K, 1, len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(\n                        &mut region,\n                        &self.inputs,\n                        Box::new(PolyOp::Sum { axes: vec![0] }),\n                    )\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runsum(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_sum\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [16, 512].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        // parameters\n        let a = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runsum\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/accum_sumpool.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::hybrid::HybridOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_keys;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::srs::gen_srs;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\nstatic mut IMAGE_HEIGHT: usize = 2;\nstatic mut IMAGE_WIDTH: usize = 2;\nstatic mut IN_CHANNELS: usize = 3;\n\nconst K: usize = 17;\n\n#[derive(Clone, Debug)]\nstruct MyCircuit {\n    image: ValTensor<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = 10;\n\n        let a = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let b = VarTensor::new_advice(cs, K, 1, len * len);\n\n        let output = VarTensor::new_advice(cs, K, 1, (len + 1) * len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(\n                        &mut region,\n                        &[self.image.clone()],\n                        Box::new(HybridOp::SumPool {\n                            padding: vec![(0, 0); 2],\n                            stride: vec![1, 1],\n                            kernel_shape: vec![2, 2],\n                            normalized: false,\n                        }),\n                    )\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runsumpool(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"accum_sumpool\");\n\n    let params = gen_srs::<KZGCommitmentScheme<_>>(K as u32);\n\n    for size in [1, 2].iter() {\n        unsafe {\n            IMAGE_HEIGHT = size * 4;\n            IMAGE_WIDTH = size * 4;\n\n            let mut image = Tensor::from(\n                (0..IN_CHANNELS * IMAGE_HEIGHT * IMAGE_WIDTH)\n                    .map(|_| Value::known(Fr::random(OsRng))),\n            );\n            image\n                .reshape(&[1, IN_CHANNELS, IMAGE_HEIGHT, IMAGE_WIDTH])\n                .unwrap();\n\n            let circuit = MyCircuit {\n                image: ValTensor::from(image),\n            };\n\n            group.throughput(Throughput::Elements(*size as u64));\n            group.bench_with_input(BenchmarkId::new(\"pk\", size), &size, |b, &_| {\n                b.iter(|| {\n                    create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                        .unwrap();\n                });\n            });\n\n            let pk = create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                .unwrap();\n\n            group.throughput(Throughput::Elements(*size as u64));\n            group.bench_with_input(BenchmarkId::new(\"prove\", size), &size, |b, &_| {\n                b.iter(|| {\n                    let prover = create_proof_circuit::<\n                        KZGCommitmentScheme<_>,\n                        MyCircuit,\n                        ProverSHPLONK<_>,\n                        VerifierSHPLONK<_>,\n                        SingleStrategy<_>,\n                        _,\n                        EvmTranscript<_, _, _, _>,\n                        EvmTranscript<_, _, _, _>,\n                    >(\n                        circuit.clone(),\n                        vec![],\n                        &params,\n                        &pk,\n                        CheckMode::UNSAFE,\n                        ezkl::Commitments::KZG,\n                        TranscriptType::EVM,\n                        None,\n                        None,\n                    );\n                    prover.unwrap();\n                });\n            });\n        }\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runsumpool\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/pairwise_add.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 2],\n    _marker: PhantomData<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len);\n        let b = VarTensor::new_advice(cs, K, 1, len);\n        let output = VarTensor::new_advice(cs, K, 1, len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::UNSAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = region::RegionCtx::new(region, 0, 1);\n                config\n                    .layout(&mut region, &self.inputs, Box::new(PolyOp::Add))\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runadd(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"pairwise_add\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [16, 512].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        // parameters\n        let a = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let b = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runadd\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/pairwise_pow.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::poly::PolyOp;\nuse ezkl::circuit::region::RegionCtx;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::marker::PhantomData;\n\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct MyCircuit {\n    inputs: [ValTensor<Fr>; 1],\n    _marker: PhantomData<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = BaseConfig<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        let len = unsafe { LEN };\n\n        let a = VarTensor::new_advice(cs, K, 1, len);\n        let b = VarTensor::new_advice(cs, K, 1, len);\n        let output = VarTensor::new_advice(cs, K, 1, len);\n\n        Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = RegionCtx::new(region, 0, 1);\n                config\n                    .layout(&mut region, &self.inputs, Box::new(PolyOp::Pow(4)))\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runpow(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"pairwise_pow\");\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [16, 512].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        // parameters\n        let a = Tensor::from((0..len).map(|_| Value::known(Fr::random(OsRng))));\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runpow\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/poseidon.rs",
        "content": "use std::collections::HashMap;\n\nuse criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};\nuse ezkl::circuit::modules::poseidon::{PoseidonChip, PoseidonConfig};\nuse ezkl::circuit::modules::Module;\nuse ezkl::circuit::*;\nuse ezkl::pfsys::create_keys;\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::srs::gen_srs;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::tensor::*;\nuse halo2_proofs::circuit::Value;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK};\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{Layouter, SimpleFloorPlanner},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::rngs::OsRng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\nconst L: usize = 10;\n\n#[derive(Clone, Debug)]\nstruct MyCircuit {\n    image: ValTensor<Fr>,\n}\n\nimpl Circuit<Fr> for MyCircuit {\n    type Config = PoseidonConfig<POSEIDON_WIDTH, POSEIDON_RATE>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, 10>::configure(cs, ())\n    }\n\n    fn synthesize(\n        &self,\n        config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), Error> {\n        let chip: PoseidonChip<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, L> =\n            PoseidonChip::new(config);\n        chip.layout(&mut layouter, &[self.image.clone()], 0, &mut HashMap::new())?;\n        Ok(())\n    }\n}\n\nfn runposeidon(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"poseidon\");\n\n    for size in [64, 784, 2352, 12288].iter() {\n        let k = (PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, L>::num_rows(*size)\n            as f32)\n            .log2()\n            .ceil() as u32;\n        let params = gen_srs::<KZGCommitmentScheme<_>>(k);\n\n        let message = (0..*size).map(|_| Fr::random(OsRng)).collect::<Vec<_>>();\n        let _output =\n            PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, L>::run(message.to_vec())\n                .unwrap();\n\n        let mut image = Tensor::from(message.into_iter().map(Value::known));\n        image.reshape(&[1, *size]).unwrap();\n\n        let circuit = MyCircuit {\n            image: ValTensor::from(image),\n        };\n\n        group.throughput(Throughput::Elements(*size as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", size), &size, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, MyCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(*size as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", size), &size, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    MyCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots().sample_size(10);\n  targets = runposeidon\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "benches/relu.rs",
        "content": "use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};\nuse ezkl::circuit::region::RegionCtx;\nuse ezkl::circuit::table::Range;\nuse ezkl::circuit::{ops::lookup::LookupOp, BaseConfig as Config, CheckMode};\nuse ezkl::pfsys::create_proof_circuit;\nuse ezkl::pfsys::TranscriptType;\nuse ezkl::pfsys::{create_keys, srs::gen_srs};\nuse ezkl::tensor::*;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK};\nuse halo2_proofs::poly::kzg::strategy::SingleStrategy;\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::{Bn256, Fr};\nuse rand::Rng;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\nconst BITS: Range = (-32768, 32768);\nstatic mut LEN: usize = 4;\nconst K: usize = 16;\n\n#[derive(Clone)]\nstruct NLCircuit {\n    pub input: ValTensor<Fr>,\n}\n\nimpl Circuit<Fr> for NLCircuit {\n    type Config = Config<Fr>;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n        unsafe {\n            let advices = (0..3)\n                .map(|_| VarTensor::new_advice(cs, K, 1, LEN))\n                .collect::<Vec<_>>();\n\n            let nl = LookupOp::ReLU;\n\n            let mut config = Config::default();\n\n            config\n                .configure_lookup(cs, &advices[0], &advices[1], &advices[2], BITS, K, &nl)\n                .unwrap();\n\n            config\n        }\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<Fr>, // layouter is our 'write buffer' for the circuit\n    ) -> Result<(), Error> {\n        config.layout_tables(&mut layouter).unwrap();\n        layouter.assign_region(\n            || \"\",\n            |region| {\n                let mut region = RegionCtx::new(region, 0, 1);\n                config\n                    .layout(&mut region, &[self.input.clone()], Box::new(LookupOp::ReLU))\n                    .unwrap();\n                Ok(())\n            },\n        )?;\n        Ok(())\n    }\n}\n\nfn runrelu(c: &mut Criterion) {\n    let mut group = c.benchmark_group(\"relu\");\n\n    let mut rng = rand::thread_rng();\n    let params = gen_srs::<KZGCommitmentScheme<_>>(17);\n    for &len in [4, 8].iter() {\n        unsafe {\n            LEN = len;\n        };\n\n        let input: Tensor<Value<Fr>> =\n            Tensor::<i32>::from((0..len).map(|_| rng.gen_range(0..10))).into();\n\n        let circuit = NLCircuit {\n            input: ValTensor::from(input.clone()),\n        };\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"pk\", len), &len, |b, &_| {\n            b.iter(|| {\n                create_keys::<KZGCommitmentScheme<Bn256>, NLCircuit>(&circuit, &params, true)\n                    .unwrap();\n            });\n        });\n\n        let pk =\n            create_keys::<KZGCommitmentScheme<Bn256>, NLCircuit>(&circuit, &params, true).unwrap();\n\n        group.throughput(Throughput::Elements(len as u64));\n        group.bench_with_input(BenchmarkId::new(\"prove\", len), &len, |b, &_| {\n            b.iter(|| {\n                let prover = create_proof_circuit::<\n                    KZGCommitmentScheme<_>,\n                    NLCircuit,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    SingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit.clone(),\n                    vec![],\n                    &params,\n                    &pk,\n                    CheckMode::UNSAFE,\n                    ezkl::Commitments::KZG,\n                    TranscriptType::EVM,\n                    None,\n                    None,\n                );\n                prover.unwrap();\n            });\n        });\n    }\n    group.finish();\n}\n\ncriterion_group! {\n  name = benches;\n  config = Criterion::default().with_plots();\n  targets = runrelu\n}\ncriterion_main!(benches);\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "contracts/AttestData.sol",
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\nimport './LoadInstances.sol';\n\n// This contract serves as a Data Attestation Verifier for the EZKL model.\n// It is designed to read and attest to instances of proofs generated from a specified circuit.\n// It is particularly constructed to read only int256 data from specified on-chain contracts' view functions.\n\n// Overview of the contract functionality:\n// 1. Initialization: Through the constructor, it sets up the contract calls that the EZKL model will read from.\n// 2. Data Quantization: Quantizes the returned data into a scaled fixed-point representation. See the `quantizeData` method for details.\n// 3. Static Calls: Makes static calls to fetch data from other contracts. See the `staticCall` method.\n// 4. Field Element Conversion: The fixed-point representation is then converted into a field element modulo P using the `toFieldElement` method.\n// 5. Data Attestation: The `attestData` method validates that the public instances match the data fetched and processed by the contract.\n// 6. Proof Verification: The `verifyWithDataAttestation` method parses the instances out of the encoded calldata and calls the `attestData` method to validate the public instances,\n//  then calls the `verifyProof` method to verify the proof on the verifier.\n\ncontract DataAttestation is LoadInstances {\n    /**\n     * @notice Struct used to make view only calls to accounts to fetch the data that EZKL reads from.\n     * @param the address of the account to make calls to\n     * @param the abi encoded function calls to make to the `contractAddress`\n     */\n    struct AccountCall {\n        address contractAddress;\n        mapping(uint256 => bytes) callData;\n        mapping(uint256 => uint256) decimals;\n        uint callCount;\n    }\n    AccountCall[] public accountCalls;\n\n    uint[] public scales;\n\n    address public admin;\n\n    /**\n     * @notice EZKL P value \n     * @dev In order to prevent the verifier from accepting two version of the same pubInput, n and the quantity (n + P),  where n + P <= 2^256, we require that all instances are stricly less than P. a\n     * @dev The reason for this is that the assmebly code of the verifier performs all arithmetic operations modulo P and as a consequence can't distinguish between n and n + P.\n     */\n    uint256 constant ORDER = uint256(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001); \n\n    uint256 constant INPUT_CALLS = 0;\n\n    uint256 constant OUTPUT_CALLS = 0;\n\n    uint8 public instanceOffset;\n\n    /**\n     * @dev Initialize the contract with account calls the EZKL model will read from.\n     * @param _contractAddresses - The calls to all the contracts EZKL reads storage from.\n     * @param _callData - The abi encoded function calls to make to the `contractAddress` that EZKL reads storage from.\n     */\n    constructor(\n        address[] memory _contractAddresses,\n        bytes[][] memory _callData,\n        uint256[][] memory _decimals,\n        uint[] memory _scales,\n        uint8 _instanceOffset,\n        address _admin\n    ) {\n        admin = _admin;\n        for (uint i; i < _scales.length; i++) {\n            scales.push(1 << _scales[i]);\n        }\n        populateAccountCalls(_contractAddresses, _callData, _decimals);\n        instanceOffset = _instanceOffset;\n    }\n\n    function updateAdmin(address _admin) external {\n        require(msg.sender == admin, \"Only admin can update admin\");\n        if(_admin == address(0)) {\n            revert();\n        }\n        admin = _admin;\n    }\n\n    function updateAccountCalls(\n        address[] memory _contractAddresses,\n        bytes[][] memory _callData,\n        uint256[][] memory _decimals\n    ) external {\n        require(msg.sender == admin, \"Only admin can update instanceOffset\");\n        populateAccountCalls(_contractAddresses, _callData, _decimals);\n    }\n\n    function populateAccountCalls(\n        address[] memory _contractAddresses,\n        bytes[][] memory _callData,\n        uint256[][] memory _decimals\n    ) internal {\n        require(\n            _contractAddresses.length == _callData.length &&\n                accountCalls.length == _contractAddresses.length,\n            \"Invalid input length\"\n        );\n        require(\n            _decimals.length == _contractAddresses.length,\n            \"Invalid number of decimals\"\n        );\n        // fill in the accountCalls storage array\n        uint counter = 0;\n        for (uint256 i = 0; i < _contractAddresses.length; i++) {\n            AccountCall storage accountCall = accountCalls[i];\n            accountCall.contractAddress = _contractAddresses[i];\n            accountCall.callCount = _callData[i].length;\n            for (uint256 j = 0; j < _callData[i].length; j++) {\n                accountCall.callData[j] = _callData[i][j];\n                accountCall.decimals[j] = 10 ** _decimals[i][j];\n            }\n            // count the total number of storage reads across all of the accounts\n            counter += _callData[i].length;\n        }\n        require(counter == INPUT_CALLS + OUTPUT_CALLS, \"Invalid number of calls\");\n    }\n\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            uint256 prod0;\n            uint256 prod1;\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            if (prod1 == 0) {\n                return prod0 / denominator;\n            }\n\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            uint256 remainder;\n            assembly {\n                remainder := mulmod(x, y, denominator)\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                denominator := div(denominator, twos)\n                prod0 := div(prod0, twos)\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            prod0 |= prod1 * twos;\n\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            inverse *= 2 - denominator * inverse;\n            inverse *= 2 - denominator * inverse;\n            inverse *= 2 - denominator * inverse;\n            inverse *= 2 - denominator * inverse;\n            inverse *= 2 - denominator * inverse;\n            inverse *= 2 - denominator * inverse;\n\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n    /**\n     * @dev Quantize the data returned from the account calls to the scale used by the EZKL model.\n     * @param data - The data returned from the account calls.\n     * @param decimals - The number of decimals the data returned from the account calls has (for floating point representation).\n     * @param scale - The scale used to convert the floating point value into a fixed point value. \n     */\n    function quantizeData(\n        bytes memory data,\n        uint256 decimals,\n        uint256 scale\n    ) internal pure returns (int256 quantized_data) {\n        int x = abi.decode(data, (int256));\n        bool neg = x < 0;\n        if (neg) x = -x;\n        uint output = mulDiv(uint256(x), scale, decimals);\n        if (mulmod(uint256(x), scale, decimals) * 2 >= decimals) {\n            output += 1;\n        }\n        quantized_data = neg ? -int256(output): int256(output);\n    }\n    /**\n     * @dev Make a static call to the account to fetch the data that EZKL reads from.\n     * @param target - The address of the account to make calls to.\n     * @param data  - The abi encoded function calls to make to the `contractAddress` that EZKL reads storage from.\n     * @return The data returned from the account calls. (Must come from either a view or pure function. Will throw an error otherwise)\n     */\n    function staticCall(\n        address target,\n        bytes memory data\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        if (success) {\n            if (returndata.length == 0) {\n                require(\n                    target.code.length > 0,\n                    \"Address: call to non-contract\"\n                );\n            }\n            return returndata;\n        } else {\n            revert(\"Address: low-level call failed\");\n        }\n    }\n    /**\n     * @dev Convert the fixed point quantized data into a field element.\n     * @param x - The quantized data.\n     * @return field_element - The field element.\n     */\n    function toFieldElement(int256 x) internal pure returns (uint256 field_element) {\n        // The casting down to uint256 is safe because the order is about 2^254, and the value\n        // of x ranges of -2^127 to 2^127, so x + int(ORDER) is always positive.\n        return uint256(x + int(ORDER)) % ORDER;\n    }\n\n    /**\n     * @dev Make the account calls to fetch the data that EZKL reads from and attest to the data.\n     * @param instances - The public instances to the proof (the data in the proof that publicly accessible to the verifier).\n     */\n    function attestData(uint256[] memory instances) internal view {\n        require(\n            instances.length >= INPUT_CALLS + OUTPUT_CALLS,\n            \"Invalid public inputs length\"\n        );\n        uint256 _accountCount = accountCalls.length;\n        uint counter = 0;\n        for (uint8 i = 0; i < _accountCount; ++i) {\n            address account = accountCalls[i].contractAddress;\n            for (uint8 j = 0; j < accountCalls[i].callCount; j++) {\n                bytes memory returnData = staticCall(\n                    account,\n                    accountCalls[i].callData[j]\n                );\n                uint256 scale = scales[counter];\n                int256 quantized_data = quantizeData(\n                    returnData,\n                    accountCalls[i].decimals[j],\n                    scale\n                );\n                uint256 field_element = toFieldElement(quantized_data);\n                require(\n                    field_element == instances[counter + instanceOffset],\n                    \"Public input does not match\"\n                );\n                counter++;\n            }\n        }\n    }\n\n\n    function verifyWithDataAttestation(\n        address verifier,\n        bytes calldata encoded\n    ) public view returns (bool) {\n        require(verifier.code.length > 0,\"Address: call to non-contract\");\n        attestData(getInstancesCalldata(encoded));\n        // static call the verifier contract to verify the proof\n        (bool success, bytes memory returndata) = verifier.staticcall(encoded);\n\n        if (success) {\n            return abi.decode(returndata, (bool));\n        } else {\n            revert(\"low-level call to verifier failed\");\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "contracts/LoadInstances.sol",
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\ncontract LoadInstances {\n    /**\n     * @dev Parse the instances array from the Halo2Verifier encoded calldata. \n     * @notice must pass encoded bytes from memory\n     * @param encoded - verifier calldata\n     */\n    function getInstancesMemory(\n        bytes memory encoded\n    ) internal pure returns (uint256[] memory instances) {\n        bytes4 funcSig;\n        uint256 instances_offset;\n        uint256 instances_length;\n        assembly {\n            // fetch function sig. Either `verifyProof(bytes,uint256[])` or `verifyProof(address,bytes,uint256[])`\n            funcSig := mload(add(encoded, 0x20))\n\n            // Fetch instances offset which is 4 + 32 + 32 bytes away from\n            // start of encoded for `verifyProof(bytes,uint256[])`,\n            // and 4 + 32 + 32 +32 away for `verifyProof(address,bytes,uint256[])`\n\n            instances_offset := mload(\n                add(encoded, add(0x44, mul(0x20, eq(funcSig, 0xaf83a18d))))\n            )\n\n            instances_length := mload(add(add(encoded, 0x24), instances_offset))\n        }\n        instances = new uint256[](instances_length); // Allocate memory for the instances array.\n        assembly {\n            // Now instances points to the start of the array data\n            // (right after the length field).\n            for {\n                let i := 0x20\n            } lt(i, add(mul(instances_length, 0x20), 0x20)) {\n                i := add(i, 0x20)\n            } {\n                mstore(\n                    add(instances, i),\n                    mload(add(add(encoded, add(i, 0x24)), instances_offset))\n                )\n            }\n        }\n    }\n    /**\n     * @dev Parse the instances array from the Halo2Verifier encoded calldata. \n     * @notice must pass encoded bytes from calldata\n     * @param encoded - verifier calldata\n     */\n    function getInstancesCalldata(\n        bytes calldata encoded\n    ) internal pure returns (uint256[] memory instances) {\n        bytes4 funcSig;\n        uint256 instances_offset;\n        uint256 instances_length;\n        assembly {\n            // fetch function sig. Either `verifyProof(bytes,uint256[])` or `verifyProof(address,bytes,uint256[])`\n            funcSig := calldataload(encoded.offset)\n\n            // Fetch instances offset which is 4 + 32 + 32 bytes away from\n            // start of encoded for `verifyProof(bytes,uint256[])`,\n            // and 4 + 32 + 32 +32 away for `verifyProof(address,bytes,uint256[])`\n\n            instances_offset := calldataload(\n                add(\n                    encoded.offset,\n                    add(0x24, mul(0x20, eq(funcSig, 0xaf83a18d)))\n                )\n            )\n\n            instances_length := calldataload(add(add(encoded.offset, 0x04), instances_offset))\n        }\n        instances = new uint256[](instances_length); // Allocate memory for the instances array.\n        assembly{\n            // Now instances points to the start of the array data\n            // (right after the length field).\n\n            for {\n                let i := 0x20\n            } lt(i, add(mul(instances_length, 0x20), 0x20)) {\n                i := add(i, 0x20)\n            } {\n                mstore(\n                    add(instances, i),\n                    calldataload(\n                        add(add(encoded.offset, add(i, 0x04)), instances_offset)\n                    )\n                )\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "contracts/QuantizeData.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract QuantizeData {\n    /**\n     * @notice EZKL P value\n     * @dev In order to prevent the verifier from accepting two version of the same instance, n and the quantity (n + P),  where n + P <= 2^256, we require that all instances are stricly less than P. a\n     * @dev The reason for this is that the assmebly code of the verifier performs all arithmetic operations modulo P and as a consequence can't distinguish between n and n + P.\n     */\n    uint256 constant ORDER =\n        uint256(\n            0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\n        );\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    function quantize_data(\n        bytes[] memory data,\n        uint256[] memory decimals,\n        uint256[] memory scales\n    ) external pure returns (int256[] memory quantized_data) {\n        quantized_data = new int256[](data.length);\n        for (uint i; i < data.length; i++) {\n            int x = abi.decode(data[i], (int256));\n            bool neg = x < 0;\n            if (neg) x = -x;\n            uint denom = 10 ** decimals[i];\n            uint scale = 1 << scales[i];\n            uint output = mulDiv(uint256(x), scale, denom);\n            if (mulmod(uint256(x), scale, denom) * 2 >= denom) {\n                output += 1;\n            }\n\n            quantized_data[i] = neg ? -int256(output) : int256(output);\n        }\n    }\n\n    function to_field_element(\n        int128[] memory quantized_data\n    ) public pure returns (uint256[] memory output) {\n        output = new uint256[](quantized_data.length);\n        for (uint i; i < quantized_data.length; i++) {\n            output[i] = uint256(quantized_data[i] + int(ORDER)) % ORDER;\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "contracts/TestReads.sol",
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.17;\n\ncontract TestReads {\n    int[] public arr;\n\n    constructor(int256[] memory _numbers) {\n        for (uint256 i = 0; i < _numbers.length; i++) {\n            arr.push(_numbers[i]);\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "docs/python/src/conf.py",
        "content": "import ezkl\n\nproject = 'ezkl'\nrelease = '0.0.0'\nversion = release\n\n\nextensions = [\n    'sphinx.ext.autodoc',\n    'sphinx.ext.autosummary',\n    'sphinx.ext.intersphinx',\n    'sphinx.ext.todo',\n    'sphinx.ext.inheritance_diagram',\n    'sphinx.ext.autosectionlabel',\n    'sphinx.ext.napoleon',\n    'sphinx_rtd_theme',\n]\n\nautosummary_generate = True\nautosummary_imported_members = True\n\ntemplates_path = ['_templates']\nexclude_patterns = []\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'sphinx_rtd_theme'\nhtml_static_path = ['_static']"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/conv2d_mnist/main.rs",
        "content": "use ezkl::circuit::region::RegionCtx;\nuse ezkl::circuit::{\n    ops::lookup::LookupOp, ops::poly::PolyOp, BaseConfig as PolyConfig, CheckMode,\n};\nuse ezkl::fieldutils;\nuse ezkl::fieldutils::i32_to_felt;\nuse ezkl::tensor::*;\nuse halo2_proofs::dev::MockProver;\nuse halo2_proofs::poly::commitment::Params;\nuse halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK};\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{\n        create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, Column, ConstraintSystem, Error,\n        Instance,\n    },\n    poly::{\n        commitment::ParamsProver,\n        kzg::{\n            commitment::{KZGCommitmentScheme, ParamsKZG},\n            strategy::SingleStrategy,\n        },\n    },\n    transcript::{\n        Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,\n    },\n};\nuse halo2curves::bn256::Bn256;\nuse halo2curves::bn256::Fr as F;\n\nuse instant::Instant;\nuse mnist::*;\nuse rand::rngs::OsRng;\nuse std::marker::PhantomData;\n\nmod params;\n\nconst K: usize = 20;\nconst NUM_INNER_COLS: usize = 1;\n\n#[derive(Clone)]\nstruct Config<\n    const LEN: usize, //LEN = CHOUT x OH x OW flattened //not supported yet in rust stable\n    const CLASSES: usize,\n    const LOOKUP_MIN: i128,\n    const LOOKUP_MAX: i128,\n    // Convolution\n    const KERNEL_HEIGHT: usize,\n    const KERNEL_WIDTH: usize,\n    const OUT_CHANNELS: usize,\n    const STRIDE: usize,\n    const IMAGE_HEIGHT: usize,\n    const IMAGE_WIDTH: usize,\n    const IN_CHANNELS: usize,\n    const PADDING: usize,\n> where\n    Value<F>: TensorType,\n{\n    // this will be a conv layer\n    layer_config: PolyConfig<F>,\n    // this will be an affine layer\n    public_output: Column<Instance>,\n}\n\n#[derive(Clone)]\nstruct MyCircuit<\n    const LEN: usize, //LEN = CHOUT x OH x OW flattened\n    const CLASSES: usize,\n    const LOOKUP_MIN: i128,\n    const LOOKUP_MAX: i128,\n    // Convolution\n    const KERNEL_HEIGHT: usize,\n    const KERNEL_WIDTH: usize,\n    const OUT_CHANNELS: usize,\n    const STRIDE: usize,\n    const IMAGE_HEIGHT: usize,\n    const IMAGE_WIDTH: usize,\n    const IN_CHANNELS: usize,\n    const PADDING: usize,\n> where\n    Value<F>: TensorType,\n{\n    // Given the stateless ConvConfig type information, a DNN trace is determined by its input and the parameters of its layers.\n    // Computing the trace still requires a forward pass. The intermediate activations are stored only by the layouter.\n    input: ValTensor<F>,\n    l0_params: [ValTensor<F>; 2],\n    l2_params: [ValTensor<F>; 2],\n}\n\nimpl<\n        const LEN: usize,\n        const CLASSES: usize,\n        const LOOKUP_MIN: i128,\n        const LOOKUP_MAX: i128,\n        // Convolution\n        const KERNEL_HEIGHT: usize,\n        const KERNEL_WIDTH: usize,\n        const OUT_CHANNELS: usize,\n        const STRIDE: usize,\n        const IMAGE_HEIGHT: usize,\n        const IMAGE_WIDTH: usize,\n        const IN_CHANNELS: usize,\n        const PADDING: usize,\n    > Circuit<F>\n    for MyCircuit<\n        LEN,\n        CLASSES,\n        LOOKUP_MIN,\n        LOOKUP_MAX,\n        KERNEL_HEIGHT,\n        KERNEL_WIDTH,\n        OUT_CHANNELS,\n        STRIDE,\n        IMAGE_HEIGHT,\n        IMAGE_WIDTH,\n        IN_CHANNELS,\n        PADDING,\n    >\nwhere\n    Value<F>: TensorType,\n{\n    type Config = Config<\n        LEN,\n        CLASSES,\n        LOOKUP_MIN,\n        LOOKUP_MAX,\n        KERNEL_HEIGHT,\n        KERNEL_WIDTH,\n        OUT_CHANNELS,\n        STRIDE,\n        IMAGE_HEIGHT,\n        IMAGE_WIDTH,\n        IN_CHANNELS,\n        PADDING,\n    >;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = PhantomData<F>;\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    // Here we wire together the layers by using the output advice in each layer as input advice in the next (not with copying / equality).\n    // This can be automated but we will sometimes want skip connections, etc. so we need the flexibility.\n    fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n        let input = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n        let params = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n        let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n\n        println!(\"INPUT COL {:#?}\", input);\n\n        let mut layer_config = PolyConfig::configure(\n            cs,\n            &[input.clone(), params.clone()],\n            &output,\n            CheckMode::SAFE,\n        );\n\n        layer_config\n            .configure_lookup(\n                cs,\n                &input,\n                &output,\n                &params,\n                (LOOKUP_MIN, LOOKUP_MAX),\n                K,\n                &LookupOp::ReLU,\n            )\n            .unwrap();\n\n        layer_config\n            .configure_lookup(\n                cs,\n                &input,\n                &output,\n                &params,\n                (LOOKUP_MIN, LOOKUP_MAX),\n                K,\n                &LookupOp::Div { denom: 32.0.into() },\n            )\n            .unwrap();\n\n        let public_output: Column<Instance> = cs.instance_column();\n        cs.enable_equality(public_output);\n\n        Config {\n            layer_config,\n            public_output,\n        }\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<F>,\n    ) -> Result<(), Error> {\n        config.layer_config.layout_tables(&mut layouter).unwrap();\n\n        let x = layouter\n            .assign_region(\n                || \"mlp_4d\",\n                |region| {\n                    let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS);\n\n                    let op = PolyOp::Conv {\n                        padding: vec![(PADDING, PADDING); 2],\n                        stride: vec![STRIDE; 2],\n                    };\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[\n                                self.input.clone(),\n                                self.l0_params[0].clone(),\n                                self.l0_params[1].clone(),\n                            ],\n                            Box::new(op),\n                        )\n                        .unwrap();\n\n                    let x = config\n                        .layer_config\n                        .layout(&mut region, &[x.unwrap()], Box::new(LookupOp::ReLU))\n                        .unwrap();\n\n                    let mut x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[x.unwrap()],\n                            Box::new(LookupOp::Div { denom: 32.0.into() }),\n                        )\n                        .unwrap()\n                        .unwrap();\n\n                    x.flatten();\n                    // multiply by weights\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[self.l2_params[0].clone(), x],\n                            Box::new(PolyOp::Einsum {\n                                equation: \"ij,j->ik\".to_string(),\n                            }),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    // add bias\n                    let x: ValTensor<F> = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[x, self.l2_params[1].clone()],\n                            Box::new(PolyOp::Add),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    Ok(x)\n                },\n            )\n            .unwrap();\n\n        match x {\n            ValTensor::Value {\n                inner: v, dims: _, ..\n            } => v\n                .enum_map(|i, x| match x {\n                    ValType::PrevAssigned(v) => {\n                        layouter.constrain_instance(v.cell(), config.public_output, i)\n                    }\n                    _ => panic!(),\n                })\n                .unwrap(),\n            _ => panic!(\"Should be assigned\"),\n        };\n\n        Ok(())\n    }\n}\n\npub fn runconv() {\n    #[cfg(not(target_arch = \"wasm32\"))]\n    env_logger::init();\n\n    const KERNEL_HEIGHT: usize = 5;\n    const KERNEL_WIDTH: usize = 5;\n    const OUT_CHANNELS: usize = 4;\n    const STRIDE: usize = 2;\n    const IMAGE_HEIGHT: usize = 28;\n    const IMAGE_WIDTH: usize = 28;\n    const IN_CHANNELS: usize = 1;\n    const PADDING: usize = 0;\n    const CLASSES: usize = 10;\n    const LEN: usize = {\n        OUT_CHANNELS\n            * ((IMAGE_HEIGHT + 2 * PADDING - KERNEL_HEIGHT) / STRIDE + 1)\n            * ((IMAGE_WIDTH + 2 * PADDING - KERNEL_WIDTH) / STRIDE + 1)\n    };\n\n    // Load the parameters and preimage from somewhere\n\n    let Mnist {\n        trn_img,\n        trn_lbl,\n        tst_img: _,\n        tst_lbl: _,\n        ..\n    } = MnistBuilder::new()\n        .base_path(\"examples/data\")\n        .label_format_digit()\n        .training_set_length(50_000)\n        .validation_set_length(10_000)\n        .test_set_length(10_000)\n        .finalize();\n\n    let mut train_data = Tensor::from(trn_img.iter().map(|x| i32_to_felt::<F>(*x as i32 / 16)));\n    train_data.reshape(&[50_000, 28, 28]).unwrap();\n\n    let mut train_labels = Tensor::from(trn_lbl.iter().map(|x| *x as f32));\n    train_labels.reshape(&[50_000, 1]).unwrap();\n\n    println!(\"The first digit is a {:?}\", train_labels[0]);\n\n    let mut input: ValTensor<F> = train_data\n        .get_slice(&[0..1, 0..28, 0..28])\n        .unwrap()\n        .map(Value::known)\n        .into();\n\n    input.reshape(&[1, 1, 28, 28]).unwrap();\n\n    let myparams = params::Params::new();\n    let mut l0_kernels = Tensor::<F>::from(\n        myparams\n            .kernels\n            .clone()\n            .into_iter()\n            .flatten()\n            .flatten()\n            .flatten()\n            .map(|fl| {\n                let dx = fl * 32_f32;\n                let rounded = dx.round();\n                let integral: i32 = unsafe { rounded.to_int_unchecked() };\n                fieldutils::i32_to_felt(integral)\n            }),\n    );\n\n    l0_kernels\n        .reshape(&[OUT_CHANNELS, IN_CHANNELS, KERNEL_HEIGHT, KERNEL_WIDTH])\n        .unwrap();\n    l0_kernels.set_visibility(&ezkl::graph::Visibility::Private);\n\n    let l0_kernels = l0_kernels.try_into().unwrap();\n\n    let mut l0_bias = Tensor::<F>::from((0..OUT_CHANNELS).map(|_| fieldutils::i32_to_felt(0)));\n    l0_bias.set_visibility(&ezkl::graph::Visibility::Private);\n\n    let l0_bias = l0_bias.try_into().unwrap();\n\n    let mut l2_biases = Tensor::<F>::from(myparams.biases.into_iter().map(|fl| {\n        let dx = fl * 32_f32;\n        let rounded = dx.round();\n        let integral: i32 = unsafe { rounded.to_int_unchecked() };\n        fieldutils::i32_to_felt(integral)\n    }));\n    l2_biases.set_visibility(&ezkl::graph::Visibility::Private);\n    l2_biases.reshape(&[l2_biases.len(), 1]).unwrap();\n\n    let l2_biases = l2_biases.try_into().unwrap();\n\n    let mut l2_weights = Tensor::<F>::from(myparams.weights.into_iter().flatten().map(|fl| {\n        let dx = fl * 32_f32;\n        let rounded = dx.round();\n        let integral: i32 = unsafe { rounded.to_int_unchecked() };\n        fieldutils::i32_to_felt(integral)\n    }));\n    l2_weights.set_visibility(&ezkl::graph::Visibility::Private);\n    l2_weights.reshape(&[CLASSES, LEN]).unwrap();\n\n    let l2_weights = l2_weights.try_into().unwrap();\n\n    let circuit = MyCircuit::<\n        LEN,\n        10,\n        -32768,\n        32768,\n        KERNEL_HEIGHT,\n        KERNEL_WIDTH,\n        OUT_CHANNELS,\n        STRIDE,\n        IMAGE_HEIGHT,\n        IMAGE_WIDTH,\n        IN_CHANNELS,\n        PADDING,\n    > {\n        input,\n        l0_params: [l0_kernels, l0_bias],\n        l2_params: [l2_weights, l2_biases],\n    };\n\n    let public_input: Tensor<i32> = vec![\n        -25124i32, -19304, -16668, -4399, -6209, -4548, -2317, -8349, -6117, -23461,\n    ]\n    .into_iter()\n    .into();\n\n    let pi_inner: Tensor<F> = public_input.map(i32_to_felt::<F>);\n\n    println!(\"MOCK PROVING\");\n    let now = Instant::now();\n    let prover = MockProver::run(\n        K as u32,\n        &circuit,\n        vec![pi_inner.clone().into_iter().collect()],\n    )\n    .unwrap();\n    prover.assert_satisfied();\n    let elapsed = now.elapsed();\n    println!(\n        \"MOCK PROVING took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    let pi_for_real_prover: &[&[&[F]]] = &[&[&pi_inner]];\n\n    //\tReal proof\n    println!(\"SRS GENERATION\");\n    let now = Instant::now();\n    let params: ParamsKZG<Bn256> = ParamsKZG::new(K as u32);\n    let elapsed = now.elapsed();\n    println!(\n        \"SRS GENERATION took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    let empty_circuit = circuit.without_witnesses();\n\n    // Initialize the proving key\n    println!(\"VK GENERATION\");\n    let now = Instant::now();\n    let vk = keygen_vk(&params, &empty_circuit).expect(\"keygen_vk should not fail\");\n    let elapsed = now.elapsed();\n    println!(\n        \"VK GENERATION took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    println!(\"PK GENERATION\");\n    let now = Instant::now();\n    let pk = keygen_pk(&params, vk, &empty_circuit).expect(\"keygen_pk should not fail\");\n    let elapsed = now.elapsed();\n    println!(\n        \"PK GENERATION took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    println!(\"PROOF GENERATION\");\n    let now = Instant::now();\n    let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]);\n    let mut rng = OsRng;\n    create_proof::<KZGCommitmentScheme<_>, ProverSHPLONK<_>, _, _, _, _>(\n        &params,\n        &pk,\n        &[circuit],\n        pi_for_real_prover,\n        &mut rng,\n        &mut transcript,\n    )\n    .expect(\"proof generation should not fail\");\n    let proof = transcript.finalize();\n    let elapsed = now.elapsed();\n    println!(\n        \"PROOF GENERATION took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    let now = Instant::now();\n    let strategy = SingleStrategy::new(&params);\n    let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]);\n    let verify = verify_proof::<_, VerifierSHPLONK<_>, _, _, _>(\n        &params,\n        pk.get_vk(),\n        strategy,\n        pi_for_real_prover,\n        &mut transcript,\n        params.n(),\n    );\n    assert!(verify.is_ok());\n\n    let elapsed = now.elapsed();\n    println!(\n        \"Verify took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n}\n\nfn main() {\n    runconv()\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/conv2d_mnist/params.rs",
        "content": "pub struct Params {\n    pub kernels: Vec<Vec<Vec<Vec<f32>>>>,\n    pub weights: Vec<Vec<f32>>,\n    pub biases: Vec<f32>,\n}\nimpl Params {\n    pub fn new() -> Params {\n        let kernels: Vec<Vec<Vec<Vec<f32>>>> = vec![\n            vec![\n                vec![vec![\n                    -0.109_487_005,\n                    0.909_935_65,\n                    0.328_405_1,\n                    0.155_579_06,\n                ]],\n                vec![vec![\n                    -0.471_988_14,\n                    0.322_556_82,\n                    0.157_859_01,\n                    -0.081_366_19,\n                ]],\n                vec![vec![\n                    -0.321_307_9,\n                    -0.709_357_5,\n                    -0.236_524_24,\n                    0.018_392_317,\n                ]],\n                vec![vec![\n                    -0.960_573_43,\n                    -0.846_240_9,\n                    -0.198_723_21,\n                    0.338_416_52,\n                ]],\n                vec![vec![\n                    0.166_024_16,\n                    0.430_398_14,\n                    0.047_989_722,\n                    0.390_401_57,\n                ]],\n            ],\n            vec![\n                vec![vec![0.179_814_12, 0.948_680_9, 0.071_443_19, 0.617_541_6]],\n                vec![vec![-0.697_547_9, -0.965_234_34, 0.536_243_9, 0.735_313_3]],\n                vec![vec![-0.856_151_64, -1.370_123, 0.471_787_6, 0.621_356_9]],\n                vec![vec![\n                    -1.038_033_6,\n                    -0.314_346_02,\n                    0.054_190_256,\n                    0.157_560_56,\n                ]],\n                vec![vec![\n                    -1.257_821_7,\n                    0.592_307_27,\n                    -0.602_756_1,\n                    -0.045_588_925,\n                ]],\n            ],\n            vec![\n                vec![vec![\n                    0.768_956_36,\n                    -0.270_884_07,\n                    0.018_818_572,\n                    0.856_514_2,\n                ]],\n                vec![vec![0.106_152_184, -1.894_055_7, 0.410_578_52, 1.128_321_6]],\n                vec![vec![0.258_462_85, -0.788_394_3, 0.439_590_57, 0.347_620_25]],\n                vec![vec![\n                    -0.285_630_46,\n                    0.344_891_73,\n                    -0.158_083_84,\n                    0.046_936_575,\n                ]],\n                vec![vec![-1.207_216_4, 0.972_309_4, -1.463_360_5, 0.158_549_34]],\n            ],\n            vec![\n                vec![vec![\n                    0.481_335_2,\n                    -0.999_390_1,\n                    -0.342_961_97,\n                    -0.462_902_43,\n                ]],\n                vec![vec![0.770_321_5, -0.693_961_4, 0.349_121_36, -0.411_381_07]],\n                vec![vec![0.576_287_75, 0.283_153_83, 1.110_488_4, 0.188_614_32]],\n                vec![vec![0.697_886_77, 0.836_453_6, -0.077_697_74, 0.236_429_83]],\n                vec![vec![0.525_762_26, 0.838_75, -1.107_396_1, 0.395_158_26]],\n            ],\n            vec![\n                vec![vec![0.165_011_53, -0.900_041_6, 0.047_026_41, -1.977_776]],\n                vec![vec![\n                    0.307_094_28,\n                    -0.446_277_47,\n                    0.300_544_77,\n                    -1.988_659_1,\n                ]],\n                vec![vec![0.406_012_42, 0.884_344_8, 0.952_605_9, -0.506_538]],\n                vec![vec![0.980_571_8, 0.721_017_2, 0.290_006_73, -0.175_620_02]],\n                vec![vec![0.928_422_87, 0.359_928_97, -0.923_574_2, 0.063_738_97]],\n            ],\n        ];\n\n        let w: Vec<Vec<f32>> = vec![\n            vec![\n                0.205_270_19,\n                -0.103_883_29,\n                -0.899_116_8,\n                0.729_005_6,\n                -0.240_855_54,\n                0.212_849_54,\n                -0.417_299_66,\n                -1.158_180_5,\n                -1.631_655_5,\n                -0.357_596_07,\n            ],\n            vec![\n                0.554_331_5,\n                -0.113_753_23,\n                -0.998_434_54,\n                0.527_284_1,\n                -0.702_836_16,\n                0.852_934_1,\n                -0.762_695,\n                -1.032_534_8,\n                -1.304_348_8,\n                -0.461_081_1,\n            ],\n            vec![\n                0.235_476_17,\n                0.933_593,\n                -0.580_496_9,\n                0.104_375_89,\n                -0.041_980_47,\n                -0.653_047_9,\n                -0.642_941_1,\n                -0.055_830_125,\n                -0.506_560_2,\n                -0.054_289_315,\n            ],\n            vec![\n                0.531_130_25,\n                -0.422_383_3,\n                -0.913_531_6,\n                0.379_514_9,\n                -0.694_251_5,\n                0.636_398_9,\n                -0.583_917_3,\n                -1.094_018_2,\n                -0.767_574_3,\n                -0.250_628_44,\n            ],\n            vec![\n                0.210_465_77,\n                -0.651_549_34,\n                0.430_768_22,\n                0.073_381_59,\n                -0.726_815_46,\n                -0.955_648_3,\n                0.060_921_72,\n                -1.645_878_4,\n                -0.245_945_47,\n                -1.102_198_2,\n            ],\n            vec![\n                -0.720_487_3,\n                -0.537_216_1,\n                0.213_335_25,\n                0.261_519,\n                -0.752_857_7,\n                -0.974_760_83,\n                0.801_267_15,\n                -1.639_844_2,\n                -0.296_582_34,\n                -0.877_851_4,\n            ],\n            vec![\n                0.286_137_55,\n                -0.717_753_95,\n                0.174_010_41,\n                -0.781_800_03,\n                -0.391_660_15,\n                0.916_126_9,\n                -0.611_720_1,\n                -0.838_970_3,\n                -1.248_522_9,\n                -0.266_078_17,\n            ],\n            vec![\n                0.786_667_5,\n                -1.937_995_7,\n                1.488_519_2,\n                -1.075_065,\n                -0.816_913_96,\n                -0.082_726_15,\n                0.544_172_8,\n                -0.647_251_5,\n                0.042_277_988,\n                -0.101_091_36,\n            ],\n            vec![\n                -0.081_334_39,\n                -0.410_865_6,\n                4.723_240_3e-5,\n                0.167_322_04,\n                -0.229_562_98,\n                -0.362_416_1,\n                0.258_705_38,\n                -1.749_157_9,\n                0.071_778_66,\n                -2.777_862_5,\n            ],\n            vec![\n                -0.085_456_52,\n                -1.244_134_9,\n                0.120_452_59,\n                0.158_306_17,\n                -0.578_419_6,\n                -0.349_570_4,\n                0.537_034,\n                -1.344_408,\n                -0.028_031_735,\n                -2.276_252,\n            ],\n            vec![\n                -1.502_647_6,\n                0.309_662_8,\n                0.248_574_35,\n                -0.207_915_56,\n                -1.259_506_8,\n                -1.270_181_1,\n                1.259_249_8,\n                -1.636_723,\n                0.053_503_122,\n                -0.590_245_2,\n            ],\n            vec![\n                0.065_632_41,\n                -0.254_215_4,\n                -0.589_417_6,\n                1.104_314_7,\n                -1.895_038_4,\n                -0.648_805_4,\n                1.669_961_3,\n                -1.083_259_8,\n                -0.401_768_77,\n                -1.511_640_2,\n            ],\n            vec![\n                0.249_498_64,\n                -0.175_782_26,\n                -0.258_627_98,\n                0.194_892_62,\n                -0.560_735_17,\n                -0.160_784_18,\n                0.161_112_1,\n                -3.568_600_4,\n                0.172_535_03,\n                -0.239_725_56,\n            ],\n            vec![\n                0.248_165_12,\n                -0.169_096_62,\n                0.112_139_55,\n                -0.364_031_9,\n                -1.327_239_8,\n                -0.027_334_109,\n                0.536_611_86,\n                -3.214_496_4,\n                0.130_880_97,\n                -0.526_202_7,\n            ],\n            vec![\n                -0.799_813_03,\n                1.452_860_1,\n                -0.319_819_72,\n                -0.184_792_74,\n                0.140_319_36,\n                -0.867_999_26,\n                0.693_308_35,\n                -1.197_729_1,\n                -0.766_039_6,\n                -1.556_379_1,\n            ],\n            vec![\n                -0.845_276_3,\n                0.304_203_3,\n                0.944_849_8,\n                0.124_821_134,\n                -0.922_336_76,\n                -0.491_067_53,\n                -0.184_880_93,\n                -2.557_060_7,\n                -1.775_722_1,\n                0.558_45,\n            ],\n            vec![\n                0.143_072_8,\n                -0.264_300_5,\n                -0.081_971_504,\n                0.048_953_265,\n                -0.542_625,\n                0.011_722_911,\n                -0.333_903_73,\n                -0.390_692_65,\n                0.272_231_76,\n                0.156_067_22,\n            ],\n            vec![\n                -0.387_689_44,\n                0.191_336_14,\n                -0.097_416_42,\n                0.035_105_634,\n                -0.395_439_33,\n                -0.242_016_94,\n                0.365_376_65,\n                -0.286_892_18,\n                -0.460_546_08,\n                0.274_879_22,\n            ],\n            vec![\n                -0.286_709_82,\n                0.791_482_3,\n                0.646_904_4,\n                -0.833_426_06,\n                -0.655_702_65,\n                -0.107_309_21,\n                0.858_584_76,\n                -1.800_347_8,\n                -1.091_450_2,\n                -3.117_647,\n            ],\n            vec![\n                -0.311_940_76,\n                0.585_462_15,\n                0.278_351_4,\n                -0.195_842_67,\n                -0.772_845_7,\n                0.177_592_13,\n                -0.098_054_45,\n                -1.845_965_5,\n                -1.022_349_2,\n                -0.907_678_4,\n            ],\n            vec![\n                0.272_821_28,\n                -0.067_864_05,\n                -0.138_505_9,\n                -0.081_492_29,\n                -0.387_334_82,\n                -0.016_360_57,\n                -0.215_009_03,\n                -0.167_551_83,\n                0.102_085_34,\n                0.173_719_73,\n            ],\n            vec![\n                -0.090_551_52,\n                0.208_982_07,\n                -0.150_085_8,\n                -0.553_895_7,\n                -0.287_771_4,\n                -0.334_054_1,\n                0.267_900_44,\n                -0.272_997_17,\n                -0.337_444_4,\n                -0.042_845_86,\n            ],\n            vec![\n                -0.356_198_94,\n                0.072_102_97,\n                0.102_510_154,\n                -0.196_657_39,\n                -0.191_161_19,\n                -0.281_018_23,\n                0.778_014_7,\n                -1.820_609_9,\n                -0.116_903_074,\n                -1.093_936_6,\n            ],\n            vec![\n                -1.026_930_8,\n                1.145_142_8,\n                -0.365_834_41,\n                0.112_254_17,\n                -0.342_273_4,\n                -1.065_313_3,\n                0.572_839_44,\n                -2.689_278_1,\n                -0.829_139_9,\n                -1.090_214_4,\n            ],\n            vec![\n                0.049_006_45,\n                -0.238_958_63,\n                0.072_469_26,\n                0.021_633_074,\n                -0.253_975_12,\n                0.073_988_98,\n                -0.179_797_55,\n                -0.204_893_05,\n                0.084_148_675,\n                0.454_873_56,\n            ],\n            vec![\n                -0.472_980_65,\n                0.094_130_29,\n                0.010_865_513,\n                -0.072_856_374,\n                -0.130_805_84,\n                0.288_349_66,\n                0.133_428_38,\n                -1.906_852,\n                -0.256_083_5,\n                0.130_116_46,\n            ],\n            vec![\n                0.310_519_2,\n                0.158_036_98,\n                -0.088_624_336,\n                -0.378_656_36,\n                -0.505_495_8,\n                -0.353_957_36,\n                0.128_528_24,\n                -0.121_506_3,\n                0.106_705_7,\n                0.053_275_537,\n            ],\n            vec![\n                0.404_991_5,\n                -0.886_301_64,\n                1.029_255_2,\n                0.946_611_64,\n                -1.078_323_2,\n                -0.478_881_12,\n                0.080_937_55,\n                -0.968_548_6,\n                -0.184_279_47,\n                -3.533_551_5,\n            ],\n            vec![\n                0.011_388_913,\n                -0.327_091_72,\n                0.107_985_206,\n                0.054_274_764,\n                -0.060_456_365,\n                -0.059_907_958,\n                -0.374_292_46,\n                -0.328_351_89,\n                0.065_400_75,\n                0.415_573_6,\n            ],\n            vec![\n                0.106_242_32,\n                0.290_615_23,\n                -0.515_454_4,\n                -0.672_065,\n                -0.247_548_16,\n                0.608_504_4,\n                -0.016_324_794,\n                -4.148_192_4,\n                -0.212_008_9,\n                -0.432_835_8,\n            ],\n            vec![\n                -0.526_448_97,\n                0.205_754_35,\n                0.076_098_82,\n                -0.069_695_31,\n                -0.191_621_91,\n                0.291_678_22,\n                -0.152_594_2,\n                0.101_625_93,\n                0.214_410_33,\n                -0.125_688_2,\n            ],\n            vec![\n                -1.190_686_7,\n                -0.957_843_84,\n                0.998_908_6,\n                1.184_374_7,\n                -1.852_929_7,\n                0.349_038_24,\n                0.564_113_3,\n                -1.171_722_8,\n                -0.685_080_77,\n                -1.525_082_7,\n            ],\n            vec![\n                -0.121_344_47,\n                0.014_777_94,\n                0.092_460_57,\n                0.227_560_82,\n                -0.133_595_06,\n                -0.061_949_328,\n                -0.229_687_59,\n                -1.204_043_5,\n                -0.117_137_89,\n                0.066_422_805,\n            ],\n            vec![\n                -0.713_826_5,\n                0.662_813_8,\n                -0.893_180_2,\n                -0.241_316_48,\n                -0.155_127_45,\n                0.235_396_18,\n                0.434_296,\n                -4.804_617,\n                -0.143_494_13,\n                -0.871_146_5,\n            ],\n            vec![\n                -0.257_979_33,\n                0.148_611_19,\n                -0.216_227,\n                0.063_711_99,\n                -0.247_472_02,\n                0.096_262_21,\n                0.213_341_3,\n                -0.876_289_25,\n                0.040_421_054,\n                -0.139_267_49,\n            ],\n            vec![\n                -0.095_453_01,\n                -1.067_049_1,\n                -0.109_649_43,\n                -0.193_885_3,\n                -1.734_969_9,\n                -0.106_661_83,\n                1.129_675_5,\n                -1.453_956_5,\n                0.904_227_4,\n                -1.171_946_4,\n            ],\n            vec![\n                -0.039_940_894,\n                0.063_756_41,\n                -0.203_613_64,\n                0.329_066_4,\n                -0.183_243_96,\n                0.100_813_02,\n                -0.053_472_206,\n                0.535_816_67,\n                -0.316_393_52,\n                -0.144_898_12,\n            ],\n            vec![\n                0.113_168_314,\n                -0.833_849_9,\n                -0.303_433_6,\n                -0.302_232_6,\n                0.228_052_87,\n                -0.354_127_2,\n                0.388_441_03,\n                0.625_805_4,\n                0.004_380_497_6,\n                -2.595_726,\n            ],\n            vec![\n                0.143_565_1,\n                0.182_829_17,\n                -0.528_689_74,\n                -0.110_325_485,\n                -0.503_309_8,\n                0.299_748_33,\n                0.095_951_79,\n                -2.118_308_3,\n                -0.408_070_4,\n                0.146_073_6,\n            ],\n            vec![\n                0.103_533_98,\n                0.597_761_1,\n                -1.624_569_9,\n                -1.605_465,\n                -1.133_732_3,\n                0.041_046_087,\n                0.620_659_6,\n                -1.410_499_7,\n                0.648_047_27,\n                -0.474_848_9,\n            ],\n            vec![\n                0.221_853_54,\n                -0.451_183_77,\n                -0.257_857_44,\n                0.264_325_53,\n                -0.355_948_24,\n                0.014_300_789,\n                -0.059_305_04,\n                0.556_209,\n                -0.052_184_805,\n                -0.290_411_74,\n            ],\n            vec![\n                0.123_746_41,\n                0.146_830_04,\n                0.365_464_8,\n                -2.524_588_8,\n                -0.209_791_47,\n                -0.002_517_690_6,\n                0.155_493_72,\n                -3.591_966_6,\n                -0.447_013_94,\n                -1.130_127,\n            ],\n            vec![\n                0.217_829_11,\n                0.214_957_76,\n                0.282_495_92,\n                0.167_459_32,\n                -0.208_813_38,\n                -0.567_943_75,\n                0.198_498_55,\n                0.576_863_3,\n                -0.373_066_4,\n                -0.126_371_68,\n            ],\n            vec![\n                -1.161_503_4,\n                -0.850_141_2,\n                0.323_090_46,\n                -1.075_380_4,\n                -0.876_660_05,\n                1.076_255_4,\n                -0.314_113_7,\n                -0.304_621_55,\n                -1.264_679_4,\n                -0.264_382_12,\n            ],\n            vec![\n                0.149_401_25,\n                -0.976_069_4,\n                0.511_743_55,\n                0.000_535_424_04,\n                -0.117_031_43,\n                -0.107_678_935,\n                -0.069_459_68,\n                0.306_292_47,\n                0.125_225_45,\n                -2.442_781,\n            ],\n            vec![\n                -1.668_387_7,\n                -1.762_069_5,\n                -0.121_069_3,\n                -1.923_070_9,\n                0.618_881_46,\n                -0.254_279_52,\n                -0.053_265_8,\n                -1.291_394_6,\n                -0.296_294_72,\n                -0.343_077_6,\n            ],\n            vec![\n                0.011_316_772,\n                -0.560_516_9,\n                0.481_444_72,\n                -0.479_095_2,\n                0.200_686_35,\n                -0.106_225_66,\n                -0.037_240_833,\n                0.214_261_46,\n                -0.261_465_5,\n                -1.978_262_7,\n            ],\n            vec![\n                -0.720_068_8,\n                -0.210_179_06,\n                -0.971_435_2,\n                -0.758_882_5,\n                -0.857_823_85,\n                -0.485_705_32,\n                1.141_667_8,\n                -0.028_217_256,\n                -0.530_086_4,\n                -0.159_677_88,\n            ],\n            vec![\n                0.177_069_29,\n                -0.121_254_206,\n                0.224_838_26,\n                0.371_999_23,\n                -0.589_339_85,\n                -0.052_119_676,\n                -0.246_520_33,\n                -0.337_158_02,\n                -0.360_983_88,\n                -1.255_084_3,\n            ],\n            vec![\n                -0.642_535_27,\n                0.163_133,\n                0.069_549_456,\n                0.491_649_72,\n                -0.022_372_723,\n                0.203_867_21,\n                -0.479_860_75,\n                -0.587_429_9,\n                -0.627_623_2,\n                -1.301_936_3,\n            ],\n            vec![\n                0.147_011_62,\n                0.614_845_7,\n                -0.894_145_9,\n                -0.523_223_1,\n                -0.561_377_64,\n                0.613_864_54,\n                -0.745_141_27,\n                0.978_213_97,\n                -1.130_499_4,\n                -1.302_783_1,\n            ],\n            vec![\n                0.695_418_36,\n                0.025_962_515,\n                -0.275_048_73,\n                0.853_301_6,\n                -0.425_614_98,\n                0.232_753_16,\n                -0.370_581_36,\n                -0.891_797_36,\n                -0.212_364_4,\n                -0.441_128_16,\n            ],\n            vec![\n                0.467_095_23,\n                0.164_520_4,\n                -0.320_856_18,\n                -0.053_149_23,\n                0.166_585_9,\n                0.201_401_62,\n                -0.586_135_57,\n                -0.012_367_41,\n                -0.328_987_12,\n                -0.114_124_13,\n            ],\n            vec![\n                0.236_447_05,\n                0.298_628_18,\n                -0.193_423_94,\n                0.009_453_123,\n                -0.490_039_44,\n                -0.417_519_3,\n                -0.036_829_55,\n                0.104_782_78,\n                -0.154_328_51,\n                -0.428_794_86,\n            ],\n            vec![\n                0.521_462_1,\n                -1.067_498_9,\n                -0.352_910_64,\n                -0.706_459_64,\n                -0.156_912_03,\n                0.753_26,\n                -0.110_429_8,\n                0.179_951_94,\n                -1.210_509_1,\n                -0.272_030_9,\n            ],\n            vec![\n                0.229_667_75,\n                0.585_958_8,\n                0.063_965_224,\n                -0.108_399_93,\n                -0.930_658_34,\n                -0.778_497_16,\n                -0.088_825_43,\n                0.233_678_62,\n                -0.337_286_65,\n                0.182_365_06,\n            ],\n            vec![\n                0.048_408_65,\n                -0.036_042_29,\n                0.416_218_55,\n                -0.182_036_67,\n                -0.523_173_2,\n                -0.128_682_4,\n                -0.118_689_634,\n                -0.138_312_35,\n                -0.105_193_26,\n                0.449_392_4,\n            ],\n            vec![\n                -0.074_198_395,\n                -0.436_481_77,\n                0.101_361_58,\n                0.039_507_54,\n                -0.011_397_873,\n                -0.430_790_33,\n                0.255_392_58,\n                -0.574_166_9,\n                0.086_148_12,\n                0.122_888_364,\n            ],\n            vec![\n                -0.855_785_55,\n                0.457_752_32,\n                -1.275_530_5,\n                0.259_120_94,\n                -0.464_194_15,\n                0.188_488_56,\n                1.413_801_8,\n                -0.357_694_63,\n                -1.278_620_5,\n                -1.631_098_6,\n            ],\n            vec![\n                -0.805_655_2,\n                -0.265_815_73,\n                0.124_419_026,\n                -0.461_629_48,\n                -0.314_236_97,\n                0.268_423_3,\n                0.274_402_47,\n                0.998_315_93,\n                0.380_863_43,\n                -0.614_466_97,\n            ],\n            vec![\n                -0.233_871_01,\n                -0.302_981_8,\n                0.258_206_84,\n                -0.005_351_850_8,\n                -0.144_955_49,\n                -0.253_221_06,\n                -0.228_432_7,\n                0.090_228_595,\n                0.008_581_011,\n                0.184_043_18,\n            ],\n            vec![\n                -0.209_811_84,\n                0.012_808_64,\n                -0.203_015_6,\n                -0.114_540_905,\n                -0.157_946_11,\n                -0.070_131_48,\n                0.271_216_4,\n                -0.113_623_81,\n                0.058_057_647,\n                0.014_067_203,\n            ],\n            vec![\n                -0.972_353_8,\n                1.463_821_9,\n                -0.622_333,\n                -0.397_985_52,\n                1.035_312_5,\n                -0.610_709_37,\n                0.239_632_68,\n                -0.255_446_08,\n                0.016_936_108,\n                -1.764_247_2,\n            ],\n            vec![\n                -0.260_985_3,\n                1.254_787_1,\n                0.186_725_72,\n                -0.455_625_27,\n                -0.066_667_27,\n                0.593_635_2,\n                0.162_254_18,\n                0.099_562_53,\n                -1.217_950_8,\n                -1.794_823_9,\n            ],\n            vec![\n                0.041_862_838,\n                0.140_515_88,\n                0.050_972_044,\n                0.157_721_89,\n                -0.544_736_7,\n                -0.090_700_32,\n                -0.086_753_72,\n                0.072_839_975,\n                0.126_270_53,\n                -0.009_919_372,\n            ],\n            vec![\n                -0.191_297_02,\n                0.391_595_66,\n                -0.347_080_17,\n                0.007_070_528,\n                0.079_755_33,\n                0.077_444_814,\n                0.275_881_83,\n                -0.337_502_7,\n                0.132_838_65,\n                -0.203_929_53,\n            ],\n            vec![\n                0.353_786_1,\n                1.386_378_4,\n                -0.448_180_6,\n                -0.091_514_84,\n                0.470_257_67,\n                -0.466_944_75,\n                0.277_010_8,\n                -0.946_052_85,\n                -0.480_009_35,\n                -1.484_195_4,\n            ],\n            vec![\n                -0.756_496_9,\n                -0.673_428_5,\n                0.142_579_26,\n                0.279_415_43,\n                1.044_289,\n                0.074_700_67,\n                -0.329_739_03,\n                1.033_776,\n                -0.044_540_51,\n                -1.185_075_5,\n            ],\n            vec![\n                0.016_420_702,\n                -0.481_048_32,\n                0.133_203_77,\n                0.279_789_4,\n                -0.584_399,\n                0.082_969_56,\n                -0.625_780_2,\n                0.033_153_057,\n                0.104_334_9,\n                0.392_508_8,\n            ],\n            vec![\n                -0.214_637_23,\n                0.187_661_42,\n                -0.509_873_2,\n                -0.175_593_53,\n                0.585_934_34,\n                -0.163_800_21,\n                0.677_062_8,\n                -0.294_775_52,\n                0.273_286_88,\n                -0.762_537_36,\n            ],\n            vec![\n                -0.274_889_4,\n                0.610_465_76,\n                0.456_998_2,\n                -0.148_116_63,\n                0.434_490_23,\n                -0.446_525_13,\n                0.168_362_99,\n                -0.592_147_05,\n                -0.428_666_38,\n                0.017_922_09,\n            ],\n            vec![\n                -0.867_463_77,\n                0.263_241_74,\n                0.439_303_04,\n                0.250_574_17,\n                0.456_202_2,\n                -0.278_351_84,\n                -0.850_352_35,\n                -0.670_502_54,\n                0.253_216_77,\n                -3.358_240_8,\n            ],\n            vec![\n                0.170_602_65,\n                -0.221_394_14,\n                -0.018_658_5,\n                0.224_552_65,\n                -0.444_447_9,\n                0.027_889_86,\n                -0.072_897_17,\n                0.025_849_128,\n                0.000_449_741_7,\n                0.120_267_78,\n            ],\n            vec![\n                0.094_457_65,\n                0.749_140_1,\n                -0.441_342_3,\n                -0.247_712_64,\n                0.380_680_47,\n                -0.539_401_77,\n                0.374_145_78,\n                -0.637_63,\n                -0.102_575_146,\n                -0.444_776_6,\n            ],\n            vec![\n                0.092_296_37,\n                0.324_160_07,\n                0.053_874_45,\n                -0.419_170_38,\n                0.080_262_61,\n                0.034_971_14,\n                0.339_625_27,\n                -0.456_453_14,\n                0.155_008_8,\n                -0.545_077_7,\n            ],\n            vec![\n                -0.144_919_11,\n                -0.484_287_77,\n                0.351_345_36,\n                1.020_092_8,\n                -0.322_258_44,\n                -0.290_137_68,\n                -0.837_886,\n                0.588_037_5,\n                -0.001_021_652_7,\n                -3.884_543_2,\n            ],\n            vec![\n                0.115_526_795,\n                -0.034_962_557,\n                -0.139_396_6,\n                0.033_680_24,\n                -0.342_877_4,\n                0.083_684_86,\n                -0.122_894_36,\n                0.324_849_55,\n                -0.114_528_82,\n                0.123_401_18,\n            ],\n            vec![\n                -0.137_530_28,\n                0.318_438_35,\n                -0.206_170_47,\n                -0.477_281_78,\n                0.460_907_3,\n                0.056_528_006,\n                0.050_785_955,\n                -0.574_258_3,\n                -0.024_915_818,\n                -0.404_091_6,\n            ],\n            vec![\n                -0.202_853_07,\n                -0.103_542_28,\n                -0.116_601_42,\n                0.144_897_67,\n                -0.017_747_866,\n                0.235_582_32,\n                0.170_953_4,\n                -0.053_962_417,\n                -0.127_650_17,\n                -0.203_697_12,\n            ],\n            vec![\n                0.152_913_54,\n                -0.516_011_83,\n                0.483_596_56,\n                0.244_190_16,\n                -0.029_850_394,\n                -0.097_673_82,\n                -0.312_583_42,\n                -1.341_605_7,\n                -0.423_485_9,\n                -0.279_781_43,\n            ],\n            vec![\n                0.068_590_745,\n                -0.149_233_73,\n                -0.073_714_636,\n                0.042_948_257,\n                -0.197_927_46,\n                -0.022_572_309,\n                -0.224_327_13,\n                0.327_125_85,\n                0.043_589_164,\n                -0.018_358_223,\n            ],\n            vec![\n                -0.294_240_27,\n                0.677_863_1,\n                -0.482_854_16,\n                -0.791_775_4,\n                0.785_504_2,\n                -0.272_481_23,\n                0.286_275_3,\n                -1.218_818_8,\n                -0.021_499_386,\n                -0.722_086_67,\n            ],\n            vec![\n                -0.177_391_37,\n                0.223_915_52,\n                -0.092_343_53,\n                -0.066_849_515,\n                0.131_875_72,\n                0.368_566_87,\n                -0.151_181_6,\n                -0.401_858_78,\n                -0.131_481_93,\n                -0.093_791_075,\n            ],\n            vec![\n                0.508_870_1,\n                -0.971_894_44,\n                0.366_849_9,\n                0.131_068_99,\n                -0.605_050_1,\n                -0.326_536_66,\n                0.050_295_74,\n                -2.077_97,\n                0.215_176_37,\n                -1.826_045_4,\n            ],\n            vec![\n                0.156_527_64,\n                -0.116_625_85,\n                0.154_377_33,\n                0.154_419_14,\n                -0.241_974_06,\n                -0.418_938_8,\n                -0.295_733_45,\n                0.149_280_2,\n                0.067_916_89,\n                0.028_793_553,\n            ],\n            vec![\n                -0.158_543_56,\n                0.413_012_92,\n                -0.627_065_3,\n                -1.317_622,\n                0.208_255_17,\n                0.317_041_13,\n                -0.227_730_59,\n                0.398_595_12,\n                -0.352_214_3,\n                -0.824_505_45,\n            ],\n            vec![\n                -0.161_441_8,\n                0.121_852_77,\n                -0.270_927_64,\n                -0.047_329_85,\n                -0.524_744_7,\n                0.105_052_55,\n                0.023_019_264,\n                0.050_272_036,\n                0.119_445_64,\n                0.246_476_17,\n            ],\n            vec![\n                -0.147_019_95,\n                -1.217_400_7,\n                0.256_482_8,\n                -0.399_383_75,\n                -1.991_811_2,\n                0.190_690_77,\n                -0.004_192_297,\n                0.097_936_116,\n                0.379_179_87,\n                -0.968_338_3,\n            ],\n            vec![\n                0.106_748_596,\n                0.093_080_916,\n                0.073_558_204,\n                0.456_351_52,\n                -0.196_805_95,\n                -0.407_231_93,\n                -0.167_090_68,\n                -0.462_795_7,\n                -0.056_798_77,\n                0.363_880_04,\n            ],\n            vec![\n                0.067_087_81,\n                0.700_592_1,\n                -2.085_968_3,\n                -1.309_445_1,\n                0.235_306_9,\n                0.437_614_35,\n                -0.111_600_46,\n                -0.668_872_65,\n                0.131_418_2,\n                -1.099_951,\n            ],\n            vec![\n                0.120_559_655,\n                -0.173_647_66,\n                0.087_945_215,\n                0.011_596_556,\n                0.138_631_33,\n                -0.457_137_44,\n                -0.219_191_34,\n                0.418_845_4,\n                0.058_534_283,\n                -0.049_473_75,\n            ],\n            vec![\n                -1.158_622_6,\n                -0.606_912_6,\n                -0.061_822_26,\n                -1.256_837_7,\n                -0.777_147_77,\n                0.427_778_1,\n                -0.644_817_6,\n                -2.014_167,\n                0.601_345_54,\n                -2.429_726,\n            ],\n            vec![\n                0.324_109_85,\n                0.111_482_88,\n                0.177_295_82,\n                0.801_780_64,\n                -0.232_152_54,\n                0.068_763_666,\n                -0.246_951_58,\n                -1.317_435_4,\n                -0.205_863_16,\n                -0.434_466_93,\n            ],\n            vec![\n                -1.748_575_2,\n                -2.571_439,\n                0.583_557_6,\n                -2.421_854_5,\n                -0.827_151,\n                0.664_516,\n                0.625_516_6,\n                -2.512_756_6,\n                0.469_817_76,\n                -2.431_587_2,\n            ],\n            vec![\n                -0.067_664_62,\n                -0.206_810_13,\n                -0.029_682_456,\n                0.605_365_75,\n                -0.336_148_23,\n                -0.151_250_17,\n                -0.282_517_22,\n                -0.148_410_19,\n                0.169_121_22,\n                -0.164_390_13,\n            ],\n            vec![\n                -1.392_889,\n                -1.023_818_9,\n                -1.862_098_8,\n                -1.219_547_2,\n                -0.623_446_46,\n                0.318_364_47,\n                -0.479_301_15,\n                -2.804_167_7,\n                0.677_353_2,\n                -1.441_338_1,\n            ],\n            vec![\n                -0.861_262_9,\n                0.004_425_101,\n                -0.071_183_55,\n                -0.184_647_08,\n                0.031_291_18,\n                -1.227_623_5,\n                -0.386_703_46,\n                0.281_736_55,\n                -0.005_909_541_6,\n                -0.399_945_47,\n            ],\n            vec![\n                -0.701_130_03,\n                -0.117_758_64,\n                0.368_344_07,\n                0.331_284_97,\n                -0.256_022_66,\n                -0.660_268,\n                0.039_130_14,\n                -0.481_968_08,\n                -0.089_253_89,\n                -0.579_329_7,\n            ],\n            vec![\n                0.670_172_63,\n                -0.580_271_24,\n                -0.649_096_13,\n                -0.474_525_66,\n                -0.377_117_63,\n                1.405_239_2,\n                -1.221_097_2,\n                1.200_569_9,\n                -0.086_327_35,\n                -2.255_320_3,\n            ],\n            vec![\n                -1.358_025_8,\n                -0.342_335_22,\n                0.295_178_5,\n                0.075_462_48,\n                -0.263_600_26,\n                -0.065_306_99,\n                -0.355_591_6,\n                -0.309_273_7,\n                0.027_559_858,\n                -0.708_983_06,\n            ],\n            vec![\n                -0.110_825_61,\n                -0.441_783_8,\n                0.510_953,\n                -0.017_491_657,\n                -0.361_264_1,\n                -0.658_499_2,\n                -1.168_359,\n                -0.183_945_58,\n                -0.018_839_432,\n                0.259_778_83,\n            ],\n            vec![\n                0.177_515_95,\n                -0.075_632_31,\n                0.013_366_969,\n                -0.259_934_54,\n                -0.146_670_1,\n                0.083_243_91,\n                -0.245_393_48,\n                -0.015_866_693,\n                -0.118_829_71,\n                -0.008_721_328,\n            ],\n            vec![\n                -0.550_502_36,\n                0.540_914_7,\n                -0.971_661_1,\n                -0.326_274_57,\n                0.005_312_611_3,\n                -1.068_250_4,\n                0.266_432_85,\n                0.465_531_14,\n                -0.377_819_33,\n                -2.766_870_7,\n            ],\n            vec![\n                0.389_952,\n                0.049_188_2,\n                -0.070_362_93,\n                -0.158_295_77,\n                -0.054_504_406,\n                -0.162_878_42,\n                -0.329_468_82,\n                0.147_300_17,\n                -0.285_775_2,\n                -0.423_477_32,\n            ],\n            vec![\n                -0.437_943_52,\n                -0.068_380_67,\n                0.194_627_26,\n                0.281_447_74,\n                -0.220_649_88,\n                -0.678_889,\n                -0.277_028_77,\n                0.230_105_79,\n                -0.006_377_558_7,\n                -0.206_830_32,\n            ],\n            vec![\n                -0.009_224_954,\n                -0.378_657,\n                -0.085_123_174,\n                -0.156_714_63,\n                -0.343_136_5,\n                0.055_030_156,\n                0.559_048_8,\n                -0.327_488_06,\n                0.169_883_4,\n                0.034_172_5,\n            ],\n            vec![\n                -0.688_926_8,\n                -0.104_911_59,\n                -0.976_121_96,\n                -0.522_905_95,\n                0.565_652_97,\n                0.191_607_74,\n                0.928_987_7,\n                0.271_104_07,\n                -0.397_580_33,\n                -1.708_864_6,\n            ],\n            vec![\n                0.012_301_554,\n                0.117_295_76,\n                -0.027_031_401,\n                0.264_092_45,\n                -0.886_667_85,\n                -0.591_631_6,\n                0.270_088_85,\n                0.682_763,\n                -0.278_033_26,\n                -0.395_845_86,\n            ],\n            vec![\n                -0.342_501_8,\n                0.562_693_6,\n                0.067_982_31,\n                0.326_943_3,\n                -0.336_273_97,\n                -0.601_590_1,\n                -0.685_105_3,\n                0.369_405_27,\n                -0.058_104_467,\n                -0.033_579_066,\n            ],\n            vec![\n                0.064_386_68,\n                -0.400_555_73,\n                -0.182_303_9,\n                -0.218_738_72,\n                0.216_905_34,\n                0.030_601_45,\n                0.094_936_07,\n                -0.009_266_577,\n                0.087_377_72,\n                0.053_116_817,\n            ],\n            vec![\n                0.239_458_02,\n                -0.553_885_1,\n                -0.751_549_4,\n                -0.327_702_13,\n                0.808_595_7,\n                0.551_519_1,\n                0.284_371_67,\n                0.547_793_6,\n                -0.059_032_235,\n                -1.324_021_5,\n            ],\n            vec![\n                -0.452_034_92,\n                0.261_517_6,\n                -0.252_394_05,\n                0.092_079_16,\n                0.429_929_17,\n                -0.167_667_57,\n                -0.211_615_74,\n                0.671_054_8,\n                0.349_666_24,\n                -2.117_855,\n            ],\n            vec![\n                -0.528_661_1,\n                -0.472_939_22,\n                0.182_015_09,\n                0.317_773_28,\n                -0.124_089_79,\n                0.045_638_64,\n                -0.724_232_9,\n                0.204_953_31,\n                -0.398_932_28,\n                0.107_951_67,\n            ],\n            vec![\n                -0.052_959_226,\n                0.135_726_82,\n                -0.136_894_15,\n                -0.566_229_05,\n                0.380_288_6,\n                0.140_286_85,\n                0.135_775_07,\n                -0.249_593_62,\n                -0.017_248_28,\n                -0.027_598_498,\n            ],\n            vec![\n                -0.220_504_76,\n                -0.046_495_143,\n                0.180_323_42,\n                -0.790_958_3,\n                1.322_335_2,\n                -0.108_043_14,\n                0.217_102_74,\n                0.825_262_4,\n                -0.492_108_76,\n                -0.700_494_5,\n            ],\n            vec![\n                -0.352_748_78,\n                0.213_851_73,\n                -0.163_977_56,\n                0.404_177_84,\n                -0.249_681_82,\n                -0.216_996_63,\n                -0.862_111_8,\n                0.325_164_74,\n                -0.162_396_8,\n                -0.256_683_9,\n            ],\n            vec![\n                -0.436_135_6,\n                -0.409_798_77,\n                -0.208_920_99,\n                0.172_075_72,\n                -0.236_797_62,\n                0.082_351_59,\n                -0.514_797_4,\n                0.356_074_42,\n                0.015_723_99,\n                -0.081_596_93,\n            ],\n            vec![\n                -0.451_420_16,\n                0.285_002_02,\n                -0.344_098_42,\n                -0.568_649_4,\n                0.139_230_56,\n                0.200_250_37,\n                0.495_893_72,\n                -0.290_844_05,\n                -0.022_031_482,\n                0.050_763_61,\n            ],\n            vec![\n                -0.173_756_91,\n                0.419_162_12,\n                -0.180_732_7,\n                -0.057_678_43,\n                0.963_222_5,\n                -0.542_589_25,\n                -0.015_682_373,\n                0.089_011_23,\n                0.035_791_16,\n                -0.455_887_17,\n            ],\n            vec![\n                -1.004_596_5,\n                -0.236_272_17,\n                0.173_167_3,\n                0.228_756_13,\n                0.258_503_44,\n                -0.065_365_806,\n                -0.879_822_5,\n                0.722_794_3,\n                -0.097_331_2,\n                -0.077_870_905,\n            ],\n            vec![\n                0.234_086_29,\n                -0.009_919_475,\n                -0.074_891_225,\n                -0.144_583_54,\n                -0.535_934_6,\n                0.124_304_32,\n                -0.782_060_27,\n                0.254_513_5,\n                0.055_683_39,\n                0.069_254_84,\n            ],\n            vec![\n                -0.390_705_17,\n                0.384_156_38,\n                -0.186_229_33,\n                -0.584_244_1,\n                0.531_919_96,\n                -0.069_686_66,\n                0.149_591_43,\n                -0.778_742_8,\n                -0.081_920_885,\n                -0.154_186_23,\n            ],\n            vec![\n                -0.041_898_686,\n                0.129_092_99,\n                -0.216_378_45,\n                0.181_084_84,\n                0.883_805_04,\n                -0.262_621,\n                -0.308_502_35,\n                0.180_086_1,\n                -0.291_687_16,\n                -0.113_592_334,\n            ],\n            vec![\n                -0.206_446_33,\n                0.171_964_9,\n                0.293_709_2,\n                0.253_592_46,\n                -1.241_981_9,\n                -0.466_809_84,\n                -0.528_306_25,\n                0.566_160_56,\n                -0.294_850_35,\n                0.329_751_46,\n            ],\n            vec![\n                0.028_156_348,\n                -0.089_827_4,\n                -0.039_944_68,\n                0.003_904_477_2,\n                -0.143_147_95,\n                -0.087_608_19,\n                -0.271_006_9,\n                0.135_168_46,\n                -0.169_262_14,\n                0.179_181,\n            ],\n            vec![\n                -0.158_213_47,\n                0.260_261_42,\n                -0.499_890_12,\n                -0.617_226_6,\n                0.677_156,\n                -0.141_557_51,\n                -0.015_163_827,\n                -0.268_581_3,\n                -0.383_393_73,\n                -0.079_002_6,\n            ],\n            vec![\n                0.025_213_772,\n                0.040_827_68,\n                -0.178_087_09,\n                0.116_391_845,\n                0.563_567_34,\n                -0.275_989_44,\n                -0.174_380_75,\n                -0.001_827_002_7,\n                0.125_746_6,\n                -0.340_517_07,\n            ],\n            vec![\n                0.019_749_146,\n                -0.783_887_57,\n                0.526_380_2,\n                -0.228_184_16,\n                -0.979_208_3,\n                0.045_181_397,\n                -0.290_830_22,\n                0.281_862_97,\n                0.212_756_75,\n                0.077_207_305,\n            ],\n            vec![\n                0.017_906_101,\n                -0.163_613_9,\n                0.087_164_72,\n                -0.046_330_657,\n                -0.222_235_14,\n                0.046_974_953,\n                -0.568_875_7,\n                0.137_390_6,\n                0.149_732_47,\n                0.054_858_174,\n            ],\n            vec![\n                -0.142_019_9,\n                0.449_144_24,\n                -0.686_669_5,\n                -1.090_786_9,\n                0.604_686_6,\n                0.076_722_49,\n                0.245_582_54,\n                -0.829_804_2,\n                -0.165_203_63,\n                -0.149_007_14,\n            ],\n            vec![\n                0.320_993_96,\n                0.119_689_37,\n                -0.150_012_6,\n                0.191_727_18,\n                0.082_919_58,\n                -0.527_837_1,\n                -0.071_530_03,\n                -0.021_497_987,\n                0.270_940_7,\n                -0.278_216_78,\n            ],\n            vec![\n                0.283_085_38,\n                -1.443_256_5,\n                0.252_147_61,\n                -0.163_902_98,\n                -1.414_779_3,\n                0.236_899_23,\n                -0.015_835_924,\n                -0.211_199_78,\n                0.192_544_15,\n                0.535_805_1,\n            ],\n            vec![\n                -0.031_128_181,\n                0.098_440_4,\n                -0.250_576_62,\n                0.001_446_956_2,\n                -0.166_310_09,\n                0.114_397_4,\n                -0.101_888_314,\n                0.048_192_31,\n                0.161_405_6,\n                0.090_395_294,\n            ],\n            vec![\n                -0.724_360_1,\n                0.207_801_43,\n                -1.503_290_2,\n                -1.666_891_3,\n                0.339_504,\n                0.795_809_75,\n                0.389_212_52,\n                0.054_467_775,\n                -0.033_395_73,\n                -0.436_388_46,\n            ],\n            vec![\n                0.075_730_63,\n                0.098_023_93,\n                -0.263_772_16,\n                -0.093_434_33,\n                0.315_961_48,\n                -0.366_490_3,\n                -0.232_862_79,\n                -0.119_057_89,\n                0.091_956_18,\n                -0.089_295_94,\n            ],\n            vec![\n                -0.308_372_44,\n                -0.820_044_16,\n                -0.298_285_63,\n                -0.393_244_65,\n                -0.718_027_65,\n                0.584_613_74,\n                0.539_996_6,\n                -1.438_904_9,\n                0.176_980_63,\n                0.054_312_26,\n            ],\n            vec![\n                0.174_080_85,\n                -0.216_159_63,\n                -0.026_459_76,\n                -0.357_671_2,\n                -0.113_939_73,\n                0.013_583_492_5,\n                -0.351_176_86,\n                0.252_733_47,\n                -0.039_529_853,\n                0.268_498_1,\n            ],\n            vec![\n                -1.993_145,\n                0.287_121_62,\n                -0.888_011_2,\n                -0.614_505_9,\n                0.438_744_78,\n                0.506_205_6,\n                0.087_504_11,\n                -0.068_988_88,\n                -0.123_064_6,\n                -1.331_926,\n            ],\n            vec![\n                0.215_632_22,\n                0.129_511_37,\n                0.274_990_14,\n                0.122_623_39,\n                0.047_715_563,\n                -0.734_401_6,\n                -0.375_344_1,\n                -0.003_185_275_7,\n                0.057_150_718,\n                -0.352_097_4,\n            ],\n            vec![\n                -0.425_337_6,\n                -0.582_686,\n                -1.584_758_6,\n                -0.888_137_8,\n                -0.990_626_6,\n                0.632_610_14,\n                0.343_601_02,\n                -0.343_171_48,\n                0.222_747_77,\n                0.065_007_046,\n            ],\n            vec![\n                0.751_865_74,\n                0.084_619_09,\n                -0.242_130_18,\n                -0.014_619_584,\n                -0.288_201_75,\n                -0.035_856_392,\n                -0.978_297_7,\n                -0.108_465_13,\n                0.110_781_03,\n                0.192_797_72,\n            ],\n            vec![\n                0.273_850_1,\n                -0.150_658_67,\n                0.348_599_05,\n                -1.558_001_3,\n                0.530_314_56,\n                0.911_728_44,\n                -0.471_142_77,\n                -1.818_102_1,\n                -0.112_300_32,\n                -4.107_308_4,\n            ],\n            vec![\n                0.576_481_4,\n                0.174_494_85,\n                0.100_200_04,\n                0.411_519_68,\n                0.186_069_13,\n                -0.563_864_1,\n                -0.216_897_5,\n                -0.346_323_73,\n                -0.215_137_65,\n                -0.052_019_272,\n            ],\n            vec![\n                -0.467_293_86,\n                -0.549_939_3,\n                -1.342_918_4,\n                -1.506_654_6,\n                0.483_067_24,\n                0.573_365,\n                0.154_416_11,\n                -1.015_882_1,\n                0.205_112_19,\n                -2.852_063_4,\n            ],\n            vec![\n                0.213_581_4,\n                -1.916_046_5,\n                -0.781_541_6,\n                0.128_297_82,\n                0.124_022_01,\n                0.193_614_44,\n                -1.000_155_4,\n                0.545_728,\n                -0.012_136_586,\n                -0.500_476_4,\n            ],\n            vec![\n                -0.691_628_8,\n                -0.228_353_02,\n                0.110_913_61,\n                0.106_528_59,\n                -0.173_485_19,\n                -0.040_805_902,\n                0.203_944_06,\n                -0.366_668_88,\n                0.147_183_84,\n                -0.490_145_03,\n            ],\n            vec![\n                0.456_025_42,\n                -0.025_084_412,\n                -0.650_509_3,\n                0.048_621_442,\n                0.065_681_994,\n                -0.435_010_22,\n                -0.478_657_13,\n                0.297_409_1,\n                -2.209_085_7,\n                -2.428_078,\n            ],\n            vec![\n                -0.779_053_87,\n                -0.167_990_27,\n                0.034_315_918,\n                0.144_756_27,\n                -0.375_923_57,\n                -0.178_410_22,\n                0.417_126_63,\n                -0.057_014_92,\n                0.045_673_035,\n                -0.833_929_9,\n            ],\n            vec![\n                -0.359_902_32,\n                -0.453_145_5,\n                0.376_054_2,\n                0.005_921_751,\n                -0.402_688_4,\n                -0.281_222_13,\n                -0.328_012,\n                0.300_563_34,\n                -0.322_811_7,\n                -0.074_488_41,\n            ],\n            vec![\n                0.155_242_74,\n                -0.326_161_83,\n                -0.004_502_223,\n                0.111_678_13,\n                -0.222_018,\n                0.012_103_265,\n                -0.348_285_56,\n                -0.313_547_67,\n                -0.090_373_31,\n                0.160_877_32,\n            ],\n            vec![\n                -0.779_235_84,\n                0.474_958_9,\n                0.174_592_91,\n                -0.627_929_2,\n                0.143_707_56,\n                0.655_198_63,\n                0.920_332_2,\n                -1.552_636_5,\n                -1.044_534_9,\n                -0.399_366_97,\n            ],\n            vec![\n                0.396_845_64,\n                -0.116_464_78,\n                -0.188_253_75,\n                0.055_635_884,\n                -0.439_850_36,\n                -0.115_104_504,\n                -0.056_754_448,\n                0.037_380_192,\n                0.050_991_777,\n                0.002_617_539_4,\n            ],\n            vec![\n                -0.062_194_28,\n                -0.033_647_98,\n                0.563_151_8,\n                0.341_664_5,\n                -0.104_682_36,\n                -1.025_237_4,\n                -0.539_365_8,\n                -0.000_981_343_2,\n                -0.223_044_22,\n                -0.168_867_19,\n            ],\n            vec![\n                0.034_815_1,\n                -0.044_562_746,\n                0.251_306_33,\n                -0.103_972_74,\n                -0.293_429,\n                -0.159_355_21,\n                0.462_565_1,\n                -0.656_678_1,\n                -0.184_929_68,\n                0.138_410_73,\n            ],\n            vec![\n                -0.174_431,\n                -1.836_079_8,\n                -0.516_358_14,\n                -0.740_650_9,\n                0.628_450_63,\n                0.170_128_93,\n                0.793_973_86,\n                0.020_685_973,\n                0.408_096_08,\n                -0.257_820_37,\n            ],\n            vec![\n                0.114_661_67,\n                -0.360_247,\n                -0.330_312_13,\n                0.139_972_79,\n                0.192_194_07,\n                0.278_673_35,\n                0.177_378_13,\n                0.021_838_47,\n                -0.169_735_85,\n                -0.255_217_5,\n            ],\n            vec![\n                0.028_787_855,\n                0.378_440_35,\n                0.000_291_143_08,\n                0.002_877_849_9,\n                -0.058_781_974,\n                -0.380_325_88,\n                -0.472_144_9,\n                0.718_679_3,\n                -0.138_149_2,\n                -0.280_253_98,\n            ],\n            vec![\n                -0.207_616_76,\n                -0.588_388_74,\n                0.261_936_13,\n                0.095_424_83,\n                0.073_274_486,\n                -0.358_869_7,\n                0.323_256_52,\n                -0.497_251_27,\n                0.098_571_09,\n                0.244_916_02,\n            ],\n            vec![\n                -0.053_375_665,\n                -0.907_372,\n                -0.727_244_5,\n                -0.735_421_36,\n                1.110_396_5,\n                -0.135_271_1,\n                0.323_004_5,\n                -0.285_868_73,\n                0.309_256_9,\n                0.093_485_77,\n            ],\n            vec![\n                0.084_668_264,\n                -0.228_887_29,\n                -0.118_540_026,\n                -0.044_351_313,\n                -0.233_455_63,\n                0.082_216_516,\n                -0.374_227_14,\n                -0.009_539_394,\n                0.398_557_2,\n                -0.049_398_433,\n            ],\n            vec![\n                -0.263_275_8,\n                -0.310_658_13,\n                -0.045_278_024,\n                0.538_273_16,\n                -0.228_020_5,\n                -0.319_284_53,\n                -0.379_847_7,\n                0.403_462,\n                0.080_615_55,\n                -0.393_287,\n            ],\n            vec![\n                0.068_945_13,\n                -0.858_146_67,\n                0.032_959_49,\n                -0.034_787_893,\n                0.424_780_7,\n                -0.216_492_3,\n                0.112_251_35,\n                -0.547_673_2,\n                0.084_244_326,\n                0.356_082_77,\n            ],\n            vec![\n                0.270_711_66,\n                -0.755_480_23,\n                -0.261_522_35,\n                -0.893_010_74,\n                0.546_178_9,\n                0.567_656_6,\n                0.107_416_8,\n                0.016_729_54,\n                0.054_772_306,\n                -0.339_417_46,\n            ],\n            vec![\n                -0.102_297_716,\n                -0.127_307_89,\n                0.000_735_883_37,\n                0.086_636_01,\n                -0.433_231_8,\n                -0.243_996_05,\n                -0.712_842_9,\n                0.360_887_5,\n                0.110_613_66,\n                0.189_828_68,\n            ],\n            vec![\n                -0.059_796_482,\n                -0.650_247_5,\n                0.098_926_224,\n                -0.024_830_63,\n                -0.814_044_24,\n                -0.161_119_15,\n                -0.094_905_17,\n                0.543_763_4,\n                0.024_063_092,\n                0.069_586_42,\n            ],\n            vec![\n                -0.213_605_99,\n                -0.365_503_8,\n                -0.127_580_96,\n                -0.113_292_836,\n                0.228_936_3,\n                -0.064_502_29,\n                0.331_887_63,\n                -0.558_377,\n                -0.105_677_84,\n                0.444_680_2,\n            ],\n            vec![\n                0.092_395_35,\n                -0.757_139_86,\n                -0.181_506_59,\n                -0.323_408_84,\n                0.503_436_9,\n                0.635_710_5,\n                0.275_355_67,\n                -0.271_641_22,\n                -0.356_673_75,\n                -0.198_984_77,\n            ],\n            vec![\n                -0.320_055_9,\n                -0.051_496_968,\n                0.210_841_16,\n                0.095_058_99,\n                -0.900_580_4,\n                -0.156_174_99,\n                -0.703_600_94,\n                0.193_674_56,\n                0.199_007_3,\n                0.074_151_62,\n            ],\n            vec![\n                -0.013_607_603_5,\n                -0.190_512_06,\n                -0.122_698_225,\n                -0.009_026_426,\n                -0.540_006_04,\n                0.150_625_72,\n                -0.424_062_43,\n                0.269_272_54,\n                0.120_677_96,\n                -0.155_426_44,\n            ],\n            vec![\n                -0.143_616_9,\n                0.148_102_3,\n                -0.157_922_39,\n                -0.248_577_13,\n                0.257_107_26,\n                -0.471_419,\n                0.425_645_65,\n                0.091_029_1,\n                -0.133_166_4,\n                -0.123_961_67,\n            ],\n            vec![\n                0.433_771_67,\n                0.247_506_9,\n                0.264_603_5,\n                -0.381_750_3,\n                0.335_878_8,\n                -0.245_618_85,\n                -0.068_682_83,\n                -0.399_691_46,\n                0.022_163_01,\n                -0.154_636_74,\n            ],\n            vec![\n                -0.236_952_07,\n                -0.070_704_85,\n                0.307_582,\n                0.150_636_15,\n                -1.261_24,\n                -0.333_410_05,\n                -0.273_555_9,\n                0.428_589_14,\n                0.090_926_83,\n                0.019_844_66,\n            ],\n            vec![\n                0.111_911_74,\n                -0.250_866_5,\n                -0.040_530_857,\n                -0.009_811_868,\n                -0.376_664_34,\n                0.104_442_65,\n                0.236_929_12,\n                0.013_377_204,\n                -0.148_502_3,\n                -0.034_420_002,\n            ],\n            vec![\n                -0.591_157_1,\n                0.354_086_85,\n                -0.014_166_484,\n                -0.011_582_683,\n                0.490_577_4,\n                -1.111_166_6,\n                -0.253_583_64,\n                0.226_966_57,\n                -0.246_680_5,\n                -0.316_616_7,\n            ],\n            vec![\n                0.504_683_3,\n                0.082_675_785,\n                0.287_152_26,\n                -0.142_236_1,\n                0.190_242_7,\n                -0.515_907_8,\n                -0.559_472_44,\n                0.154_153_21,\n                -0.010_323_325,\n                -0.047_526_196,\n            ],\n            vec![\n                0.040_378_43,\n                -0.571_260_6,\n                0.326_861_7,\n                -0.038_053_866,\n                -0.517_120_9,\n                -0.016_231_31,\n                0.090_821_356,\n                0.315_481_07,\n                -0.096_167_43,\n                0.083_659_82,\n            ],\n            vec![\n                0.171_835_9,\n                -0.296_782_73,\n                -0.215_916_13,\n                -0.310_014_22,\n                -0.178_923_47,\n                0.281_085_5,\n                0.054_179_72,\n                0.038_410_88,\n                0.157_684_07,\n                0.010_856_905,\n            ],\n            vec![\n                -0.762_344_84,\n                -0.197_173_1,\n                -0.075_202_31,\n                0.061_614_38,\n                0.914_948_6,\n                -0.605_976,\n                -0.187_276_05,\n                0.057_749_826,\n                -0.446_927_88,\n                -0.033_777_487,\n            ],\n            vec![\n                0.233_660_5,\n                0.015_873_462,\n                -0.005_255_001,\n                -0.047_930_67,\n                0.257_369_7,\n                -0.254_187_23,\n                -0.628_627_66,\n                0.188_018_29,\n                0.055_216_342,\n                0.058_550_056,\n            ],\n            vec![\n                0.334_796_16,\n                -1.575_294_3,\n                -0.049_017_817,\n                0.073_439_24,\n                -1.058_597_1,\n                0.562_272_2,\n                0.137_210_01,\n                -0.083_788_86,\n                -0.103_471_24,\n                0.205_879_26,\n            ],\n            vec![\n                0.152_744_38,\n                -0.078_858_71,\n                -0.300_489_6,\n                -0.508_556_37,\n                -0.266_207_28,\n                0.130_250_9,\n                -0.039_310_664,\n                0.147_595_6,\n                -0.039_225_88,\n                0.196_362_9,\n            ],\n            vec![\n                -0.866_875_9,\n                -0.032_697_26,\n                -0.008_656_468,\n                0.190_088_78,\n                0.596_259_3,\n                -0.330_446_96,\n                -0.226_081_36,\n                0.625_718_9,\n                -0.563_011_1,\n                -0.301_735_8,\n            ],\n            vec![\n                0.189_101_77,\n                0.056_929_618,\n                0.103_171_59,\n                0.099_822_3,\n                -0.248_609_11,\n                -0.085_192_98,\n                -0.267_723_77,\n                0.317_740_5,\n                -0.030_244_146,\n                -0.082_437_694,\n            ],\n            vec![\n                0.031_138_998,\n                -1.029_084_6,\n                -0.341_533_42,\n                -0.254_793_05,\n                -1.071_284_2,\n                0.558_588_2,\n                0.475_417_94,\n                -0.036_093_22,\n                0.231_615_5,\n                -0.322_770_45,\n            ],\n            vec![\n                0.206_510_78,\n                -0.975_108_86,\n                -0.343_907_36,\n                -0.275_595_87,\n                0.108_924_91,\n                -0.082_869_17,\n                0.311_547_16,\n                0.140_963_84,\n                0.180_081_08,\n                0.021_928_212,\n            ],\n            vec![\n                -1.792_503,\n                0.350_376_55,\n                -0.283_779_7,\n                0.281_561_2,\n                0.248_667_24,\n                0.750_453_65,\n                -0.240_568_13,\n                0.259_737_46,\n                -0.099_345_72,\n                -1.129_956_1,\n            ],\n            vec![\n                0.298_311,\n                0.325_646_67,\n                0.058_641_44,\n                0.327_485_47,\n                -0.216_788_63,\n                -0.641_922_06,\n                -0.490_922_72,\n                0.229_161_78,\n                -0.169_965_76,\n                0.082_617_49,\n            ],\n            vec![\n                -0.676_340_46,\n                -0.086_615_1,\n                -0.990_129_9,\n                -0.964_055_06,\n                -0.247_590_47,\n                0.553_486_35,\n                0.752_743_9,\n                -0.568_961_1,\n                0.076_329_686,\n                0.269_663_78,\n            ],\n            vec![\n                0.300_149_08,\n                0.034_903_92,\n                -0.273_156_73,\n                0.056_118_354,\n                -0.397_347_72,\n                0.280_960_4,\n                -0.701_381_3,\n                0.309_347_1,\n                -0.070_615_38,\n                -0.147_566_08,\n            ],\n            vec![\n                -1.512_842_3,\n                0.122_137_405,\n                -0.179_424_73,\n                -0.621_348_2,\n                0.242_645_67,\n                0.254_495_02,\n                0.367_945_88,\n                1.093_051_2,\n                -0.087_014_63,\n                -1.320_766_2,\n            ],\n            vec![\n                0.542_720_8,\n                0.077_151_79,\n                -0.531_274_4,\n                -0.059_125_736,\n                0.000_248_613_5,\n                -0.136_497_18,\n                -0.709_108_35,\n                -0.274_145_84,\n                0.022_545_459,\n                0.260_933_85,\n            ],\n            vec![\n                -0.764_393_57,\n                -0.922_812_3,\n                -0.821_932_6,\n                -0.524_062_63,\n                0.694_806_46,\n                0.568_482_94,\n                0.471_779_05,\n                -0.350_464_94,\n                -0.237_650_19,\n                -0.299_388_14,\n            ],\n            vec![\n                0.166_719_18,\n                -0.987_571_95,\n                -0.263_751_92,\n                -0.581_680_95,\n                -0.483_688_56,\n                -0.518_314,\n                -1.389_688_4,\n                0.515_866_94,\n                0.115_079_865,\n                -0.318_235_1,\n            ],\n            vec![\n                -0.271_017_07,\n                0.027_525_388,\n                -0.597_32,\n                -0.095_019_13,\n                -0.346_175_88,\n                0.580_207_8,\n                0.300_787_75,\n                0.043_705_73,\n                0.192_469_06,\n                -0.462_464,\n            ],\n            vec![\n                -0.096_515_015,\n                0.289_297_34,\n                -0.863_468_95,\n                1.005_157_8,\n                0.689_947_84,\n                -1.832_172_2,\n                -0.294_198_7,\n                -0.983_701_9,\n                -2.073_236_5,\n                0.231_339_78,\n            ],\n            vec![\n                -0.207_874_55,\n                0.057_534_594,\n                0.094_972_5,\n                -0.265_003_83,\n                -0.204_895_66,\n                0.182_718_59,\n                0.165_258_41,\n                -0.206_470_95,\n                0.043_471_36,\n                -0.343_006_22,\n            ],\n            vec![\n                -0.508_934_4,\n                0.487_504_9,\n                0.623_735_13,\n                0.645_485_3,\n                0.305_668_68,\n                -1.129_35,\n                0.055_277_206,\n                -0.114_775_866,\n                0.181_829_91,\n                -0.267_725_83,\n            ],\n            vec![\n                0.226_889_83,\n                -0.029_484_963,\n                0.074_473_15,\n                -0.288_940_55,\n                -0.178_996_61,\n                -0.191_890_85,\n                -0.276_085_3,\n                -0.236_703_66,\n                0.093_048_16,\n                0.225_298_88,\n            ],\n            vec![\n                0.153_564_24,\n                0.594_082_36,\n                -1.309_799_2,\n                -0.612_569_87,\n                -0.765_506_86,\n                -0.534_287_15,\n                0.528_604_87,\n                -1.124_329_4,\n                0.193_627_3,\n                0.739_874_84,\n            ],\n            vec![\n                0.515_318_45,\n                -0.407_639_27,\n                0.022_146_78,\n                -0.034_811_374,\n                -0.463_529_68,\n                0.219_874_3,\n                -0.065_351_21,\n                -0.027_115_954,\n                -0.071_082_34,\n                -0.167_560_82,\n            ],\n            vec![\n                -0.603_041_3,\n                0.173_094_06,\n                0.762_386_4,\n                0.372_296_84,\n                0.222_196_31,\n                -0.495_753_3,\n                -0.050_564_97,\n                0.188_722_49,\n                -0.672_652_3,\n                -0.178_792_94,\n            ],\n            vec![\n                -0.007_911_94,\n                -0.482_079_4,\n                -0.032_675_47,\n                0.100_052_4,\n                0.052_513_74,\n                -0.225_124_18,\n                0.350_639_73,\n                -0.364_823_76,\n                -0.068_803_236,\n                0.187_773_08,\n            ],\n            vec![\n                -0.062_913_46,\n                -0.409_758,\n                -0.320_442_44,\n                -0.662_729_5,\n                0.509_824_34,\n                -0.360_478_6,\n                0.261_233_48,\n                -0.390_644_28,\n                0.279_211_82,\n                0.240_606_68,\n            ],\n            vec![\n                0.160_814_46,\n                -0.166_563_53,\n                -0.262_935_88,\n                -0.128_298,\n                0.155_533_05,\n                0.059_555_724,\n                0.234_794_65,\n                -0.034_388_43,\n                -0.145_194_62,\n                -0.093_202_814,\n            ],\n            vec![\n                -0.473_849_77,\n                0.157_912_72,\n                0.307_175_3,\n                -0.267_877_85,\n                -0.035_855_27,\n                -0.207_699_18,\n                -0.755_759_1,\n                0.950_489_8,\n                -0.056_404_267,\n                -0.497_116_45,\n            ],\n            vec![\n                -0.107_620_25,\n                -0.324_108_27,\n                0.029_556_079,\n                0.184_373_11,\n                0.007_395_293,\n                -0.526_876_57,\n                0.440_726_82,\n                -0.351_558_86,\n                -0.289_385_68,\n                0.304_280_7,\n            ],\n            vec![\n                0.286_830_5,\n                -0.225_128_16,\n                -0.789_902_45,\n                -0.810_649_3,\n                0.174_392_4,\n                0.465_826_45,\n                0.181_955_62,\n                -0.288_959_44,\n                0.213_181_47,\n                0.089_912,\n            ],\n            vec![\n                -0.127_923_15,\n                0.353_413_67,\n                -0.127_158_69,\n                0.096_508_25,\n                -0.535_945_6,\n                -0.188_380_03,\n                -0.068_326_57,\n                -0.082_721_69,\n                0.070_878_4,\n                0.082_282_38,\n            ],\n            vec![\n                -0.180_664_45,\n                -0.405_656_93,\n                -0.136_641_98,\n                0.076_221_325,\n                0.185_186_62,\n                -0.130_355_78,\n                -0.347_225_52,\n                0.435_685_66,\n                -0.321_748_17,\n                -0.309_609_06,\n            ],\n            vec![\n                -0.100_575_75,\n                -0.154_703_74,\n                -0.374_440_88,\n                0.506_969_3,\n                0.237_276_14,\n                -0.406_840_98,\n                0.281_832_3,\n                -0.290_095_18,\n                -0.199_270_83,\n                0.243_440_67,\n            ],\n            vec![\n                0.221_755_46,\n                -0.790_980_94,\n                -0.791_633_2,\n                -0.824_782_43,\n                0.527_411_8,\n                0.514_031_65,\n                -0.120_601_065,\n                0.260_423_42,\n                0.167_460_32,\n                0.026_457_088,\n            ],\n            vec![\n                0.109_922_58,\n                0.160_769_25,\n                -0.222_593_46,\n                -0.154_723_23,\n                -0.093_943_31,\n                0.204_556_7,\n                -0.885_124_86,\n                0.142_079_01,\n                -0.057_717_92,\n                0.302_287_22,\n            ],\n            vec![\n                -0.424_106_03,\n                -0.129_682_73,\n                -0.087_105_61,\n                0.066_099_56,\n                -0.148_481_16,\n                -0.041_067_887,\n                -0.416_681_7,\n                0.047_628_727,\n                0.078_313_41,\n                0.058_919_758,\n            ],\n            vec![\n                0.083_984_82,\n                -0.395_945_52,\n                -0.220_289_78,\n                0.432_484_95,\n                0.357_147_13,\n                -0.226_951_78,\n                0.522_340_24,\n                -0.679_507_1,\n                -0.194_740_58,\n                0.244_101_08,\n            ],\n            vec![\n                0.102_482_185,\n                -0.045_399_34,\n                -0.080_852_3,\n                -1.222_988,\n                0.312_472_9,\n                0.321_611_9,\n                -0.034_010_515,\n                0.186_449_16,\n                0.316_959_83,\n                -0.126_345_13,\n            ],\n            vec![\n                -0.429_622_08,\n                0.161_493_81,\n                0.117_336_29,\n                0.354_605_3,\n                -0.120_046_5,\n                -0.057_381_7,\n                -0.986_256_5,\n                -0.148_423_24,\n                0.157_069_16,\n                -0.052_750_13,\n            ],\n            vec![\n                -0.529_666_66,\n                -0.341_064_48,\n                -0.274_165_27,\n                -0.241_169_75,\n                -0.250_266_55,\n                0.153_471_22,\n                0.504_053_7,\n                0.009_148_11,\n                0.325_742_24,\n                -0.271_160_96,\n            ],\n            vec![\n                -0.219_010_8,\n                0.314_067_42,\n                -0.029_913_263,\n                0.225_025_37,\n                0.235_776_56,\n                -0.426_587_97,\n                0.019_475_369,\n                -0.328_953_74,\n                -0.212_118_6,\n                -0.039_429_653,\n            ],\n            vec![\n                0.143_026_13,\n                0.481_122_58,\n                0.000_815_544_16,\n                -0.512_762_4,\n                0.290_940_82,\n                -0.322_919_73,\n                -0.410_684_62,\n                0.214_782_43,\n                0.438_849_93,\n                -0.633_576_15,\n            ],\n            vec![\n                -0.262_988_4,\n                0.058_395_483,\n                0.047_117_49,\n                0.129_354_98,\n                -0.311_606_05,\n                -0.030_636_294,\n                -0.587_008_95,\n                0.526_908_46,\n                -0.221_597_34,\n                -0.057_889_156,\n            ],\n            vec![\n                -0.420_213_37,\n                0.063_557_32,\n                -0.267_797_08,\n                -0.124_470_5,\n                -0.566_938_64,\n                0.322_641_5,\n                0.286_732_58,\n                -0.067_444_466,\n                0.005_744_403,\n                -0.038_390_506,\n            ],\n            vec![\n                -0.308_161_3,\n                0.022_639_94,\n                -0.040_295_47,\n                -0.061_031_915,\n                0.307_230_35,\n                -1.548_439_5,\n                -0.172_096_15,\n                0.440_008_9,\n                -0.280_834_56,\n                0.058_319_97,\n            ],\n            vec![\n                0.458_224_1,\n                0.032_741_494,\n                0.055_647_448,\n                -0.113_833_08,\n                0.055_677_84,\n                -0.582_109_33,\n                -0.714_378_95,\n                0.259_702_7,\n                0.250_479_64,\n                -0.138_732_57,\n            ],\n            vec![\n                -0.168_027_2,\n                -0.447_512,\n                0.073_285_77,\n                -0.102_245_696,\n                0.211_200_82,\n                0.355_911_34,\n                -0.286_303_85,\n                0.156_530_63,\n                -0.162_364_41,\n                0.003_130_642_5,\n            ],\n            vec![\n                0.185_978_83,\n                -0.570_623_6,\n                0.027_612_407,\n                -0.266_153_25,\n                0.065_444_656,\n                0.182_009_19,\n                0.460_085_06,\n                0.042_860_564,\n                -0.435_943_75,\n                -0.122_467_645,\n            ],\n            vec![\n                -0.295_862_8,\n                -0.726_465_9,\n                0.146_314_5,\n                0.105_163_55,\n                0.482_668_34,\n                -1.920_136_9,\n                -0.409_983_5,\n                0.098_039_93,\n                0.039_303_19,\n                0.032_061_82,\n            ],\n            vec![\n                0.452_977_72,\n                -0.052_895_073,\n                -0.147_236_78,\n                0.137_071_73,\n                0.388_998_57,\n                -0.387_540_73,\n                -1.293_666_4,\n                0.330_499_02,\n                -0.035_247_9,\n                -0.099_417_49,\n            ],\n            vec![\n                -0.183_451_46,\n                -1.082_602_7,\n                0.062_292_03,\n                0.275_495_1,\n                -0.361_221_02,\n                0.438_744_07,\n                -0.066_024_98,\n                0.169_357_73,\n                -0.069_054_18,\n                0.049_622_405,\n            ],\n            vec![\n                -0.193_424_6,\n                0.136_046_48,\n                -0.034_462_936,\n                -0.628_403_3,\n                -0.393_009_78,\n                0.316_833_26,\n                0.231_041_85,\n                0.009_123_952,\n                -0.018_631_496,\n                0.106_618_166,\n            ],\n            vec![\n                -0.034_093_65,\n                0.055_894_96,\n                0.231_049_24,\n                0.157_845_62,\n                0.202_304_78,\n                -0.788_765_5,\n                -0.634_623_7,\n                0.049_663_093,\n                0.184_820_65,\n                -0.288_572_73,\n            ],\n            vec![\n                0.628_891_6,\n                0.168_256_74,\n                0.297_308_53,\n                -0.028_807_169,\n                0.164_852_84,\n                -0.840_128,\n                -0.878_446_5,\n                0.055_374_74,\n                0.087_389_93,\n                -0.110_066_74,\n            ],\n            vec![\n                -0.396_640_54,\n                -0.432_740_78,\n                -0.332_767_5,\n                0.127_875_18,\n                -0.812_790_04,\n                0.703_349_65,\n                0.588_560_9,\n                -0.182_696_03,\n                0.048_864_517,\n                -0.205_589_47,\n            ],\n            vec![\n                0.322_684_76,\n                0.360_689_85,\n                -0.641_543_6,\n                -0.576_271_9,\n                -0.008_394_989,\n                -0.197_300_12,\n                0.157_365_19,\n                -0.066_966_61,\n                -0.090_489_98,\n                0.292_275_55,\n            ],\n            vec![\n                -0.272_229_2,\n                0.315_918_8,\n                0.124_067_43,\n                0.765_923_2,\n                0.052_089_103,\n                -1.410_848_4,\n                -0.537_994_5,\n                0.172_129_54,\n                0.392_988_62,\n                -0.357_418_63,\n            ],\n            vec![\n                0.452_900_53,\n                0.376_274_23,\n                -0.004_683_544,\n                0.227_762_8,\n                0.130_249_32,\n                -0.535_433_2,\n                -0.777_915,\n                0.194_872_07,\n                -0.117_443_47,\n                0.141_114_46,\n            ],\n            vec![\n                -0.245_853_66,\n                -0.098_773_584,\n                -0.266_520_92,\n                -0.224_863_57,\n                0.072_216_59,\n                0.338_712_57,\n                0.346_051_6,\n                -0.182_631_73,\n                0.372_764_44,\n                -0.743_095_1,\n            ],\n            vec![\n                -0.024_514_986,\n                -0.186_378_88,\n                -0.195_197_45,\n                -0.539_516_1,\n                0.022_574_846,\n                -0.175_003_86,\n                -0.087_664_865,\n                -0.077_440_86,\n                -0.164_217_31,\n                0.861_473_14,\n            ],\n            vec![\n                -1.176_825_3,\n                0.600_365_4,\n                0.404_460_37,\n                -0.293_111_56,\n                -0.260_110_77,\n                -0.525_379_7,\n                -0.275_370_5,\n                0.106_287_07,\n                0.424_896_2,\n                -0.136_489_18,\n            ],\n            vec![\n                0.222_941_64,\n                0.029_136_565,\n                0.116_637_25,\n                -0.101_515_725,\n                -0.630_471_9,\n                -0.480_908,\n                -0.131_508_16,\n                -0.083_099_48,\n                0.181_400_16,\n                0.018_836_357,\n            ],\n            vec![\n                -0.698_895_8,\n                0.397_754_07,\n                -0.329_033_97,\n                -0.829_641_5,\n                -0.215_803_35,\n                0.786_333_6,\n                -0.887_877_46,\n                -0.488_177_72,\n                0.073_410_35,\n                -0.162_985_18,\n            ],\n            vec![\n                -0.612_169_5,\n                0.394_888_82,\n                0.265_389_77,\n                -0.136_720_23,\n                -0.158_774_88,\n                -0.750_894,\n                -1.383_749_1,\n                0.339_417_8,\n                -0.662_179_9,\n                0.269_224_73,\n            ],\n            vec![\n                -0.072_811_88,\n                0.551_298_3,\n                -0.895_189_5,\n                -0.493_569_1,\n                -0.362_095_6,\n                -0.150_884_27,\n                0.169_696_85,\n                0.268_407_05,\n                -0.066_993_49,\n                0.132_940_23,\n            ],\n            vec![\n                -0.269_540_67,\n                0.507_770_36,\n                -1.427_464_2,\n                -0.734_724_04,\n                0.670_633_8,\n                -0.069_052_58,\n                -0.740_904_9,\n                0.356_450_95,\n                -1.593_374_7,\n                -0.755_425_75,\n            ],\n            vec![\n                0.279_056_88,\n                0.221_050_87,\n                -0.755_368_77,\n                -0.364_125_76,\n                -0.068_900_07,\n                -0.011_887_714,\n                -0.325_549_84,\n                0.097_667_33,\n                -0.171_342_55,\n                -0.043_467_447,\n            ],\n            vec![\n                -0.267_086_36,\n                -0.003_381_063_2,\n                1.405_259_5,\n                0.756_799_3,\n                -0.517_645_36,\n                -0.933_590_9,\n                -0.861_024_8,\n                -0.150_117_44,\n                0.463_376_55,\n                -0.722_872,\n            ],\n            vec![\n                0.139_099_29,\n                0.409_524_17,\n                -0.086_981_5,\n                -0.271_768_42,\n                0.187_499_46,\n                -0.228_399_5,\n                0.182_433_95,\n                -0.265_324_68,\n                -0.142_243_36,\n                0.101_598_375,\n            ],\n            vec![\n                0.300_135_97,\n                0.836_247_44,\n                -0.041_253_883,\n                0.630_782_84,\n                -0.605_257_15,\n                -1.116_649_7,\n                -0.420_335_23,\n                -0.816_147_4,\n                -1.019_898_3,\n                0.425_557_2,\n            ],\n            vec![\n                0.274_344_47,\n                -0.073_296_27,\n                -0.139_558_94,\n                -0.127_952_72,\n                -0.147_588_34,\n                -0.144_747_42,\n                0.132_950_99,\n                0.321_829_9,\n                -0.121_689_826,\n                0.006_479_399,\n            ],\n            vec![\n                -0.303_101_42,\n                -0.762_328_3,\n                1.457_457_9,\n                0.527_697_86,\n                -0.100_971_86,\n                -0.107_270_725,\n                -0.913_583_7,\n                -0.301_846_62,\n                -0.585_341_2,\n                -0.335_157_7,\n            ],\n            vec![\n                0.114_905_74,\n                -0.830_199_8,\n                0.112_558_655,\n                0.260_842_4,\n                -0.028_218_849,\n                -0.104_110_68,\n                0.330_357_46,\n                -0.289_884_24,\n                -0.151_965_86,\n                0.032_366_27,\n            ],\n            vec![\n                0.478_458,\n                -0.387_130_95,\n                -0.257_576_47,\n                -0.438_277_48,\n                0.059_315_678,\n                0.175_215_1,\n                0.827_331_6,\n                -0.895_138_6,\n                -0.217_182_8,\n                -0.067_494_41,\n            ],\n            vec![\n                -0.119_126_08,\n                -0.331_597_45,\n                -0.124_621_876,\n                0.422_070_12,\n                -0.404_816_3,\n                0.149_707_75,\n                -0.334_017_57,\n                -0.044_708_37,\n                -0.099_329_48,\n                0.051_153_32,\n            ],\n            vec![\n                -0.040_725_574,\n                0.289_044_26,\n                0.314_958_24,\n                -0.140_709_3,\n                0.047_588_103,\n                -0.066_910_43,\n                -0.671_796_2,\n                0.405_210_1,\n                -0.104_440_644,\n                -0.356_477_62,\n            ],\n            vec![\n                0.354_324_8,\n                0.119_619_39,\n                -0.241_285_52,\n                0.639_350_9,\n                -0.132_232_64,\n                -0.158_766_76,\n                0.331_828_2,\n                -0.224_304_81,\n                -0.384_496_63,\n                -0.419_428_74,\n            ],\n            vec![\n                0.177_356_42,\n                0.066_063_36,\n                -1.193_538_1,\n                -0.978_156_1,\n                0.130_779_65,\n                0.120_268_09,\n                7.424_281e-5,\n                -0.342_935_6,\n                0.447_567_02,\n                0.269_017_25,\n            ],\n            vec![\n                -0.120_202_97,\n                -0.495_071_47,\n                -0.274_519_18,\n                0.217_942_33,\n                -0.305_900_04,\n                0.293_836_6,\n                -0.254_543_84,\n                -0.036_753_487,\n                0.248_177_4,\n                0.110_505_62,\n            ],\n            vec![\n                -0.557_222_7,\n                -0.440_128_18,\n                0.688_790_44,\n                -0.358_640_04,\n                -0.019_008_324,\n                -0.128_100_08,\n                -0.436_285_23,\n                0.567_290_5,\n                -0.040_509_716,\n                -0.144_320_6,\n            ],\n            vec![\n                0.178_449_63,\n                -0.038_515_09,\n                -0.128_087_36,\n                0.622_190_7,\n                -0.044_439_893,\n                -0.059_167_873,\n                0.016_673_934,\n                0.057_158_887,\n                -0.473_533_18,\n                -0.514_728_07,\n            ],\n            vec![\n                0.201_881_47,\n                -0.331_614_8,\n                -1.440_653_1,\n                -1.318_789_6,\n                0.294_876_52,\n                0.125_336_42,\n                0.064_994_34,\n                0.061_897_79,\n                0.447_803_8,\n                0.315_823_6,\n            ],\n            vec![\n                0.185_746_1,\n                0.026_766_932,\n                -0.182_838_05,\n                -0.193_032_18,\n                -0.191_380_25,\n                0.368_004_92,\n                -0.685_593_2,\n                -0.157_489_08,\n                0.131_066_74,\n                0.104_366_794,\n            ],\n            vec![\n                -0.263_003_98,\n                -0.657_123_57,\n                0.488_098_4,\n                0.217_409_31,\n                -0.087_866_21,\n                0.232_031_39,\n                -0.269_720_44,\n                -0.295_114_82,\n                0.061_767_95,\n                -0.128_803_58,\n            ],\n            vec![\n                -0.310_965_54,\n                -0.075_754_36,\n                -0.154_235_14,\n                0.432_455_93,\n                -0.477_501_12,\n                -0.202_793_76,\n                0.262_324_48,\n                0.195_774_76,\n                -0.491_202_83,\n                -0.246_570_48,\n            ],\n            vec![\n                0.627_617_9,\n                0.130_057_8,\n                -0.699_788_63,\n                -0.849_566_5,\n                -0.067_410_79,\n                0.087_328_6,\n                -0.217_621_52,\n                0.255_800_58,\n                0.420_218,\n                -0.264_121_9,\n            ],\n            vec![\n                -0.538_376_87,\n                0.208_895,\n                0.156_969_23,\n                0.196_063_2,\n                0.298_645_4,\n                -0.041_912_43,\n                -0.819_426_4,\n                -0.240_417_4,\n                -0.098_353_334,\n                0.238_580_81,\n            ],\n            vec![\n                -0.552_053_33,\n                -0.496_717_3,\n                0.062_322_896,\n                0.024_250_77,\n                -0.391_012_04,\n                0.376_012_15,\n                0.596_021_83,\n                -0.888_136_6,\n                0.164_711_6,\n                -0.238_519_71,\n            ],\n            vec![\n                -0.372_523_64,\n                0.355_542_48,\n                -0.066_765_964,\n                0.190_823_06,\n                -0.305_456_5,\n                -0.475_693_26,\n                0.038_526,\n                0.092_013_51,\n                -0.336_231,\n                -0.025_312_696,\n            ],\n            vec![\n                0.769_496_56,\n                0.406_899_72,\n                -0.332_427_3,\n                -0.445_128_35,\n                -0.627_195_9,\n                -0.021_385_033,\n                -0.173_525_02,\n                0.440_466_17,\n                0.014_422_986,\n                -0.515_037_36,\n            ],\n            vec![\n                -0.475_403_67,\n                0.171_622_47,\n                -0.163_997_93,\n                0.218_631_22,\n                0.053_364_147,\n                -0.018_264_074,\n                -0.638_809,\n                0.136_716_44,\n                -0.230_133_73,\n                0.381_585_48,\n            ],\n            vec![\n                -1.587_163_6,\n                -0.057_017_2,\n                -0.228_662_16,\n                0.127_203_36,\n                -0.037_028_76,\n                0.185_854_69,\n                0.693_080_66,\n                -0.228_369_34,\n                -0.386_401_03,\n                -0.211_039_62,\n            ],\n            vec![\n                -0.197_697_91,\n                -0.439_417_15,\n                0.216_187_72,\n                -0.003_696_140_1,\n                -0.160_376_13,\n                -0.774_046_4,\n                -0.031_133_998,\n                0.276_498_97,\n                0.028_302_014,\n                -0.084_735_41,\n            ],\n            vec![\n                0.090_599_21,\n                0.285_985_1,\n                -0.131_176_73,\n                -0.362_053_6,\n                0.210_222_94,\n                0.005_901_443_3,\n                -0.687_696_1,\n                -0.021_012_772,\n                -0.088_486_426,\n                0.272_508_86,\n            ],\n            vec![\n                -0.192_863_09,\n                -0.651_285_77,\n                -0.431_206_1,\n                0.247_956_42,\n                -0.883_735_1,\n                0.068_415_62,\n                0.074_062_16,\n                0.190_670_46,\n                -0.138_411_24,\n                0.383_481_26,\n            ],\n            vec![\n                -0.262_158_33,\n                -0.356_746_85,\n                0.023_556_845,\n                -0.193_073_73,\n                -0.044_097_982,\n                0.221_795_44,\n                0.191_991_46,\n                0.201_811_48,\n                0.030_214_434,\n                -0.043_852_43,\n            ],\n            vec![\n                -0.123_064_674,\n                -0.007_795_926,\n                0.224_337_09,\n                -0.068_207_6,\n                0.218_500_39,\n                -1.402_807_7,\n                -0.185_828_67,\n                -0.275_227_55,\n                0.153_196_45,\n                -0.167_605_76,\n            ],\n            vec![\n                0.465_332_27,\n                0.239_009_44,\n                0.239_487_83,\n                -0.049_675_647,\n                0.322_712_87,\n                -0.361_904_1,\n                -0.783_763_95,\n                -0.214_422_43,\n                -0.097_743_59,\n                0.090_962_596,\n            ],\n            vec![\n                0.043_396_69,\n                -1.521_370_5,\n                -0.508_483_9,\n                0.592_855_33,\n                -0.660_342,\n                0.312_460_4,\n                0.362_794_82,\n                -0.059_432_253,\n                0.339_404_9,\n                -0.327_934_7,\n            ],\n            vec![\n                -0.104_387_17,\n                0.009_338_523,\n                -0.232_447_45,\n                -0.035_054_065,\n                -0.268_270_7,\n                0.478_249_04,\n                0.269_224_76,\n                -0.012_519_61,\n                -0.189_450_31,\n                -0.016_516_596,\n            ],\n            vec![\n                0.107_782_304,\n                0.049_322_58,\n                0.437_887_46,\n                0.041_052_792,\n                0.288_527_52,\n                -2.289_670_2,\n                -0.452_973_34,\n                -0.328_008_35,\n                0.655_561_1,\n                -0.149_166_33,\n            ],\n            vec![\n                0.265_693_13,\n                0.528_191_15,\n                0.106_833_115,\n                -0.031_265_777,\n                -0.066_381_5,\n                -0.430_439_44,\n                -0.698_310_3,\n                0.241_947_83,\n                -0.188_879_47,\n                0.252_632_14,\n            ],\n            vec![\n                -0.216_927_25,\n                0.121_004_46,\n                -0.445_989_88,\n                0.430_346_04,\n                -0.351_781_46,\n                0.152_730_35,\n                -0.425_484_9,\n                -0.088_983_38,\n                0.422_131_7,\n                -0.464_601_13,\n            ],\n            vec![\n                -0.360_672_53,\n                0.272_008_96,\n                -0.080_057_725,\n                0.201_231_36,\n                0.255_325_1,\n                0.169_969_59,\n                -0.024_861_794,\n                -0.017_412_573,\n                -0.317_985_1,\n                -0.423_185_65,\n            ],\n            vec![\n                0.121_128_2,\n                -0.288_258_37,\n                0.299_752_38,\n                0.867_127_4,\n                -0.493_007_18,\n                -1.506_429_4,\n                -0.199_151_4,\n                0.115_783_59,\n                0.173_776_28,\n                -0.029_131_787,\n            ],\n            vec![\n                0.606_763_3,\n                0.342_573_73,\n                -0.273_926_44,\n                -0.550_023_85,\n                -0.069_819_674,\n                -0.349_484_98,\n                -0.321_020_07,\n                0.041_649_144,\n                -0.116_718_37,\n                0.200_557_54,\n            ],\n            vec![\n                -0.276_791_4,\n                0.079_295_136,\n                -0.143_560_71,\n                0.106_754_03,\n                -0.082_330_11,\n                0.400_106_37,\n                0.196_720_81,\n                -0.285_766_4,\n                0.135_733_26,\n                -0.657_691_24,\n            ],\n            vec![\n                -0.193_547_56,\n                -0.307_601_33,\n                -0.076_231_666,\n                -0.365_790_6,\n                0.473_794_88,\n                -0.260_530_92,\n                0.097_811_81,\n                0.323_311_3,\n                -0.560_959_7,\n                -0.132_552,\n            ],\n            vec![\n                -0.556_238_5,\n                0.743_008_6,\n                0.481_494_16,\n                0.769_308_3,\n                -0.494_354_67,\n                -1.742_812_3,\n                -0.691_182_9,\n                0.270_070_43,\n                0.570_542_63,\n                -0.470_118_34,\n            ],\n            vec![\n                0.221_604_51,\n                0.072_595_246,\n                -0.703_638_85,\n                -0.193_811_58,\n                -0.599_087_06,\n                -0.332_261_5,\n                0.276_940_14,\n                0.066_991_21,\n                -0.039_732_546,\n                0.321_589_65,\n            ],\n            vec![\n                -0.809_401_5,\n                -0.330_654_8,\n                0.653_460_8,\n                -0.424_901_87,\n                -0.184_362_64,\n                0.578_688_2,\n                -0.596_104_8,\n                -0.250_692_34,\n                -0.054_308_05,\n                -0.653_985_6,\n            ],\n            vec![\n                -0.757_264_26,\n                0.429_740_1,\n                0.716_024_1,\n                0.120_151_47,\n                -0.597_643_4,\n                0.180_705_19,\n                -0.806_157_6,\n                0.257_461_58,\n                -0.015_053_513,\n                -1.014_189_7,\n            ],\n            vec![\n                -0.394_121_2,\n                0.859_029_7,\n                0.112_626_344,\n                -0.747_587_4,\n                0.334_439_93,\n                -0.228_314_1,\n                -0.685_789_64,\n                -0.002_370_33,\n                -0.350_976_56,\n                0.267_583_22,\n            ],\n            vec![\n                -0.533_223_7,\n                1.192_899_5,\n                0.018_847_07,\n                1.299_052_2,\n                -0.959_604_1,\n                -1.109_045_9,\n                -0.371_553_8,\n                1.284_699,\n                -1.822_740_6,\n                -1.447_136_5,\n            ],\n            vec![\n                -0.346_053_45,\n                0.541_713_8,\n                -0.737_071_9,\n                -0.844_016_97,\n                -0.144_290_58,\n                0.096_683_5,\n                -0.726_433_8,\n                0.502_831_04,\n                -0.315_663_22,\n                0.241_362_14,\n            ],\n            vec![\n                -0.237_618_37,\n                -0.054_344_088,\n                0.382_082_6,\n                0.053_052_82,\n                -0.476_174_8,\n                0.161_550_98,\n                0.060_836_162,\n                0.176_722_03,\n                -0.145_660_25,\n                -0.643_206_1,\n            ],\n            vec![\n                0.313_486_46,\n                -0.040_602_36,\n                -0.581_557_5,\n                -0.075_771_7,\n                -0.297_903_95,\n                -0.003_757_668_7,\n                0.189_653_56,\n                0.180_933_73,\n                -0.196_731_37,\n                -0.133_598_33,\n            ],\n            vec![\n                1.344_613_9,\n                1.172_998_8,\n                -0.202_547_77,\n                0.198_246_9,\n                -1.576_345_1,\n                -0.293_439_12,\n                -0.972_407_04,\n                -0.068_904_13,\n                -0.607_898_7,\n                0.297_143_25,\n            ],\n            vec![\n                0.117_273_1,\n                -0.561_625_5,\n                -0.528_112,\n                -0.637_099_2,\n                0.209_079_3,\n                -0.027_501_42,\n                0.148_175_52,\n                0.340_330_1,\n                -0.197_580_55,\n                0.090_481_9,\n            ],\n            vec![\n                -0.729_872_47,\n                0.592_992_07,\n                0.346_012_18,\n                0.104_230_6,\n                0.083_044_88,\n                0.357_109_3,\n                -0.601_610_66,\n                0.086_607_635,\n                -0.173_702_08,\n                -0.626_230_9,\n            ],\n            vec![\n                0.122_043,\n                -0.018_491_197,\n                0.319_558_86,\n                -0.254_409_13,\n                -0.078_237_48,\n                -0.070_578_46,\n                0.239_353_3,\n                0.064_942_785,\n                -0.123_233_385,\n                -0.340_646,\n            ],\n            vec![\n                0.582_297_4,\n                0.158_174_6,\n                -0.713_005_66,\n                -0.572_291_8,\n                -0.609_091_6,\n                0.350_477_34,\n                0.675_527_16,\n                -0.521_912_7,\n                -0.052_122_705,\n                0.171_072_05,\n            ],\n            vec![\n                0.105_577_48,\n                0.187_516_94,\n                -0.722_696_54,\n                -0.129_852_52,\n                -0.061_905_567,\n                0.474_712_94,\n                -0.111_769_19,\n                0.223_120_48,\n                0.017_446_205,\n                -0.148_053_33,\n            ],\n            vec![\n                -1.101_677_7,\n                0.066_154_94,\n                0.204_744_26,\n                0.431_297_1,\n                -0.281_498_5,\n                0.113_914_3,\n                -1.118_692_2,\n                0.674_603_04,\n                -0.015_837_92,\n                -0.210_914_73,\n            ],\n            vec![\n                0.392_721_44,\n                -0.259_683_13,\n                0.303_213_18,\n                -0.002_489_187,\n                -0.032_669_59,\n                -0.399_611_35,\n                0.225_581_81,\n                0.264_008_67,\n                -0.450_054_56,\n                -0.351_068_35,\n            ],\n            vec![\n                0.466_883_63,\n                -0.599_088_3,\n                -1.143_738,\n                -0.515_279_65,\n                0.090_717_19,\n                0.015_569_723,\n                0.412_253_83,\n                -0.076_723_94,\n                -0.476_769_86,\n                0.326_240_87,\n            ],\n            vec![\n                -0.205_071_79,\n                0.077_396_1,\n                -0.564_069_6,\n                -0.010_824_216,\n                0.148_514_58,\n                0.648_877_9,\n                -0.107_025_71,\n                -0.133_371_64,\n                -0.317_537_13,\n                0.053_802_9,\n            ],\n            vec![\n                -0.002_588_406_4,\n                -0.628_745,\n                0.242_333_65,\n                -0.274_682_16,\n                0.005_985_648,\n                -0.230_738_85,\n                -0.661_476_2,\n                0.266_736_95,\n                0.011_729_551,\n                -0.106_212_83,\n            ],\n            vec![\n                0.473_162_8,\n                0.263_148_2,\n                0.284_964_68,\n                0.150_511_85,\n                -0.234_422_31,\n                -0.414_224_8,\n                0.007_981_45,\n                0.192_275_82,\n                -0.492_831_2,\n                -0.820_278_8,\n            ],\n            vec![\n                0.448_108_9,\n                0.074_436_07,\n                -0.762_030_7,\n                -0.900_243,\n                -0.169_277_79,\n                0.501_497_5,\n                0.002_328_606_3,\n                0.056_543_965,\n                0.018_135_436,\n                0.052_846_033,\n            ],\n            vec![\n                -0.012_141_257_5,\n                -0.190_645_49,\n                -0.550_309_24,\n                0.019_054_85,\n                0.281_741_7,\n                0.040_815_17,\n                -0.135_266_07,\n                0.038_118_172,\n                -0.057_037_137,\n                0.162_227_14,\n            ],\n            vec![\n                -0.052_483_853,\n                -1.643_899_3,\n                0.285_089_28,\n                0.156_052_72,\n                0.180_602_33,\n                0.416_198_43,\n                0.111_903_85,\n                -0.716_806_7,\n                0.020_466_35,\n                -0.168_626_58,\n            ],\n            vec![\n                -0.290_455_64,\n                0.152_129_28,\n                0.204_712_85,\n                0.267_162_02,\n                -0.640_323,\n                -0.111_096_29,\n                -0.082_332_194,\n                0.179_990_7,\n                -0.276_141_3,\n                -0.579_719_07,\n            ],\n            vec![\n                0.411_667_73,\n                -0.181_603_67,\n                -0.617_817_9,\n                -0.463_887_9,\n                0.234_000_09,\n                0.517_197_8,\n                0.250_540_02,\n                -0.753_978_97,\n                0.009_809_169,\n                -0.214_948_12,\n            ],\n            vec![\n                -0.391_700_7,\n                0.399_570_94,\n                -0.365_930_32,\n                -0.166_463_48,\n                0.427_735_72,\n                0.122_039_06,\n                -1.010_15,\n                -0.181_935_43,\n                0.056_771_737,\n                0.396_852,\n            ],\n            vec![\n                -0.350_486_04,\n                -0.601_626_8,\n                0.281_698_82,\n                0.233_527_91,\n                -0.144_274_12,\n                0.168_160_99,\n                0.442_113_46,\n                -0.959_784_03,\n                -0.128_670_66,\n                -0.297_427_24,\n            ],\n            vec![\n                -0.352_210_25,\n                0.495_663_37,\n                0.424_403_73,\n                -0.108_114_14,\n                -0.879_724_26,\n                -0.030_185_6,\n                0.297_537_15,\n                0.167_476_2,\n                -0.380_549_04,\n                -0.517_068_5,\n            ],\n            vec![\n                -0.371_702_82,\n                0.131_365_8,\n                -0.030_542_398,\n                -0.460_730_94,\n                0.151_406_96,\n                0.211_525,\n                -0.245_326_33,\n                -0.119_136_095,\n                0.192_782_01,\n                0.041_209_22,\n            ],\n            vec![\n                -1.033_863_7,\n                0.136_977_34,\n                -0.492_126_97,\n                0.453_187,\n                0.086_104_54,\n                0.129_965_51,\n                -0.221_679_52,\n                -0.755_657,\n                0.053_589_15,\n                0.655_690_8,\n            ],\n            vec![\n                -0.544_424_5,\n                -0.237_751_4,\n                0.348_604_2,\n                -0.028_291_645,\n                -0.068_502_12,\n                0.086_517_86,\n                0.268_235_68,\n                -0.182_507_92,\n                -0.429_467_47,\n                -0.250_924_17,\n            ],\n            vec![\n                -0.011_818_108,\n                0.797_707_86,\n                0.208_938_8,\n                -0.604_700_74,\n                -0.220_071_33,\n                -0.039_925_22,\n                0.163_447_38,\n                0.073_279_925,\n                -0.220_862_34,\n                -0.289_076_3,\n            ],\n            vec![\n                0.129_709_68,\n                0.210_747_32,\n                -0.126_102_95,\n                -0.023_825_37,\n                0.344_960_84,\n                -0.135_978_13,\n                -0.421_447_52,\n                -0.209_916_95,\n                -0.252_269_18,\n                0.330_932_3,\n            ],\n            vec![\n                -0.487_710_3,\n                -0.460_413_96,\n                -0.365_575_58,\n                0.197_697_94,\n                -0.364_175_53,\n                0.058_523_543,\n                0.196_115_24,\n                -0.393_850_65,\n                0.207_997_77,\n                0.395_273,\n            ],\n            vec![\n                -0.198_588_37,\n                0.019_333_296,\n                -0.446_362_64,\n                -0.038_646_203,\n                0.071_068_4,\n                -0.048_991_922,\n                0.210_087_58,\n                0.239_180_73,\n                -0.022_882_91,\n                -0.188_380_54,\n            ],\n            vec![\n                -0.261_959_97,\n                0.333_264_44,\n                0.400_236_37,\n                -0.264_737_37,\n                0.274_795_5,\n                -0.317_504_9,\n                -0.618_102_55,\n                0.205_943_23,\n                -0.636_521_04,\n                0.152_472_51,\n            ],\n            vec![\n                0.022_477_72,\n                0.134_431_12,\n                -0.213_510_2,\n                0.248_061_33,\n                0.422_189_4,\n                -0.283_444_37,\n                -0.269_078_14,\n                0.057_764_01,\n                -0.206_792_04,\n                0.123_093_69,\n            ],\n            vec![\n                -0.233_692_9,\n                -1.017_291_4,\n                -0.150_414_63,\n                0.274_501_23,\n                0.148_620_25,\n                0.027_794_993,\n                -0.129_495_64,\n                0.074_302_66,\n                0.300_377_1,\n                -0.246_190_31,\n            ],\n            vec![\n                -0.150_708_17,\n                0.183_886_8,\n                -0.078_481_37,\n                0.087_658_904,\n                0.048_013_024,\n                0.170_886_93,\n                -0.114_284_694,\n                0.142_811_27,\n                -0.177_535_88,\n                -0.140_055_18,\n            ],\n            vec![\n                0.028_543_837,\n                0.518_874_6,\n                0.242_091_75,\n                -0.347_047_03,\n                0.124_305_62,\n                -0.714_907_77,\n                -0.905_192_4,\n                0.157_255_22,\n                -0.434_522_57,\n                0.489_530_83,\n            ],\n            vec![\n                0.217_295_18,\n                0.318_683_62,\n                -0.133_674_95,\n                -0.190_113_72,\n                -0.045_825_38,\n                -0.325_925_32,\n                -0.011_337_722,\n                0.141_903_42,\n                -0.049_026_8,\n                0.293_223_83,\n            ],\n            vec![\n                0.123_400_32,\n                -0.106_249_37,\n                -0.084_128_685,\n                0.015_276_704,\n                0.481_030_76,\n                -0.324_463_07,\n                -0.327_308_92,\n                -0.216_746_37,\n                0.306_427_78,\n                -0.215_458_57,\n            ],\n            vec![\n                -0.394_248_04,\n                0.267_972_32,\n                -0.323_327_48,\n                0.007_495_794,\n                0.274_354_7,\n                0.036_519_47,\n                0.021_192_394,\n                0.167_988_94,\n                0.037_339_807,\n                -0.287_706_64,\n            ],\n            vec![\n                0.476_326_35,\n                -0.171_908_97,\n                0.187_209_59,\n                -0.184_707_57,\n                0.266_605_26,\n                -0.379_704_62,\n                -0.725_388_94,\n                -0.382_156_3,\n                0.052_183_09,\n                -0.189_024_15,\n            ],\n            vec![\n                -0.068_175_21,\n                -0.936_696,\n                -0.284_851_34,\n                -0.312_424_24,\n                0.416_920_48,\n                -0.375_246_1,\n                0.166_914_12,\n                -0.062_018_942,\n                0.123_319_04,\n                0.251_326_02,\n            ],\n            vec![\n                -0.092_383_966,\n                -0.046_410_43,\n                -0.046_993_304,\n                -0.388_989_8,\n                0.106_352_895,\n                0.124_601_215,\n                0.077_070_52,\n                -0.494_940_2,\n                0.246_576_04,\n                -0.217_108_47,\n            ],\n            vec![\n                0.096_871_64,\n                0.016_262_09,\n                0.141_645_5,\n                0.007_451_025_3,\n                0.072_534_49,\n                0.056_562_357,\n                0.168_611_02,\n                -0.162_456_27,\n                -0.328_261_7,\n                -0.372_881_1,\n            ],\n            vec![\n                0.243_483_26,\n                1.041_714_3,\n                0.791_361_9,\n                0.188_247_03,\n                -0.280_531_8,\n                -1.232_775,\n                -0.546_552_8,\n                -0.402_143_33,\n                -0.092_386_58,\n                -0.397_024_24,\n            ],\n            vec![\n                0.179_208_04,\n                -0.010_297_535,\n                -0.525_091_9,\n                0.028_228_113,\n                -0.497_619_2,\n                0.147_705_4,\n                0.225_470_04,\n                0.150_027_7,\n                -0.438_805_9,\n                -0.228_523_7,\n            ],\n            vec![\n                -0.409_310_8,\n                0.074_870_44,\n                1.139_456_7,\n                -0.908_665_6,\n                0.320_797_95,\n                -0.477_966_25,\n                -0.522_859_04,\n                -0.480_945_1,\n                0.096_658_655,\n                -0.717_741_85,\n            ],\n            vec![\n                0.134_947_06,\n                -1.164_856_6,\n                0.246_233_84,\n                -0.609_766_54,\n                -0.025_210_831,\n                0.393_831_34,\n                0.685_161_7,\n                -0.135_826_19,\n                -0.096_989_535,\n                -1.079_150_1,\n            ],\n            vec![\n                -0.049_614_098,\n                -0.048_862_495,\n                -0.094_735_25,\n                -0.314_993_68,\n                0.411_675_1,\n                -0.036_843_784,\n                -0.471_937_2,\n                -0.006_239_565,\n                -0.048_200_63,\n                -0.049_639_5,\n            ],\n            vec![\n                -0.453_031_18,\n                1.981_460_9,\n                -0.534_942_5,\n                1.134_923_5,\n                -1.180_825,\n                -0.436_842_23,\n                -0.440_320_67,\n                -0.145_491_84,\n                -1.055_054_4,\n                -1.082_154_6,\n            ],\n            vec![\n                0.034_054_637,\n                0.987_097_86,\n                -0.180_340_56,\n                -0.405_921_8,\n                0.348_030_4,\n                -0.096_445_14,\n                -0.402_231_4,\n                0.393_197_66,\n                -0.034_837_45,\n                0.040_728_43,\n            ],\n            vec![\n                -0.927_784_8,\n                -0.331_701_96,\n                0.043_690_126,\n                0.348_231,\n                -0.148_379_56,\n                0.751_553_5,\n                -0.743_430_8,\n                -0.633_260_6,\n                0.104_607_72,\n                -1.347_444_8,\n            ],\n            vec![\n                0.294_677_2,\n                -0.262_028_93,\n                0.090_968_82,\n                -0.851_627_65,\n                -0.251_495_75,\n                -0.048_707_057,\n                0.087_642_65,\n                0.418_791_4,\n                -0.020_625_126,\n                -0.118_388_51,\n            ],\n            vec![\n                1.411_125_4,\n                1.265_975_8,\n                -0.123_655_915,\n                -0.262_882_35,\n                -0.469_494_76,\n                -0.835_732,\n                0.179_724_92,\n                -0.081_000_865,\n                0.255_376_25,\n                -0.679_300_84,\n            ],\n            vec![\n                0.239_018_35,\n                -0.071_063_62,\n                -0.550_355_73,\n                -0.908_293_96,\n                0.655_489_9,\n                -0.153_276_28,\n                -0.025_848_849,\n                -0.045_441_143,\n                0.145_653_16,\n                -0.070_270_97,\n            ],\n            vec![\n                -0.897_942,\n                -0.021_246_374,\n                0.240_951_28,\n                0.323_842_38,\n                -0.729_248_46,\n                0.805_137_04,\n                -0.773_077,\n                -0.093_318_924,\n                -0.176_274_8,\n                -0.478_634_36,\n            ],\n            vec![\n                0.251_268_6,\n                -0.085_224_04,\n                0.239_970_9,\n                -0.587_481_9,\n                -0.303_148_87,\n                -0.313_885_15,\n                0.300_267_34,\n                0.437_304_08,\n                0.087_836_996,\n                -0.311_975_42,\n            ],\n            vec![\n                0.068_631_664,\n                -1.392_326_2,\n                -0.099_468_19,\n                -0.284_783_1,\n                -0.793_635_5,\n                -0.480_267_6,\n                0.925_394_9,\n                0.271_452_1,\n                0.133_807_76,\n                -0.084_477_43,\n            ],\n            vec![\n                0.343_252_6,\n                -0.774_502_7,\n                -0.502_526_34,\n                -0.191_540_2,\n                0.355_186_13,\n                -0.262_243_15,\n                0.226_072_86,\n                -0.442_591_1,\n                -0.060_238_685,\n                0.115_893_52,\n            ],\n            vec![\n                -0.657_791_6,\n                -0.128_316_4,\n                -0.296_290_46,\n                0.371_296_1,\n                0.013_583_544,\n                0.408_244_16,\n                -0.542_473_1,\n                0.314_351_05,\n                -0.361_760_5,\n                -0.321_493_12,\n            ],\n            vec![\n                -0.003_390_869_6,\n                -0.328_679_44,\n                0.424_497_7,\n                -0.643_421_35,\n                -0.429_855_6,\n                -0.255_417_76,\n                0.101_383_574,\n                0.742_305_46,\n                0.214_543_4,\n                -0.402_187_14,\n            ],\n            vec![\n                0.561_219_3,\n                -1.216_058_3,\n                -0.270_737_44,\n                -0.528_367_9,\n                -0.021_387_836,\n                -0.619_280_5,\n                0.504_366,\n                0.262_697_73,\n                0.132_761_42,\n                -0.220_773_73,\n            ],\n            vec![\n                0.288_668_9,\n                0.052_324_463,\n                2.730_375_9e-6,\n                -0.561_678_7,\n                0.170_008_32,\n                -0.008_383_047,\n                0.310_118_82,\n                -0.481_119_4,\n                -0.014_314_591,\n                -0.155_750_17,\n            ],\n            vec![\n                -0.162_936_06,\n                -0.757_794_5,\n                -0.428_959_85,\n                0.198_041_78,\n                0.044_626_14,\n                0.308_839_4,\n                -0.573_860_47,\n                0.142_511_28,\n                -0.463_218_15,\n                0.459_949_67,\n            ],\n            vec![\n                -0.108_998_46,\n                0.143_664_78,\n                0.287_137_18,\n                -0.579_912_4,\n                -0.686_672_4,\n                -0.728_061_9,\n                0.073_713_4,\n                0.220_625_89,\n                0.278_465_2,\n                -1.068_123_3,\n            ],\n            vec![\n                0.418_938_52,\n                -0.238_915_4,\n                -0.297_480_58,\n                -0.299_199_64,\n                -0.162_441_09,\n                0.114_193_65,\n                0.343_621_76,\n                -0.145_716_18,\n                0.115_891_285,\n                -0.330_101_67,\n            ],\n            vec![\n                -0.529_461_15,\n                0.026_722_493,\n                -0.540_848_5,\n                0.035_596_557,\n                0.177_273_08,\n                0.194_150_37,\n                -0.056_900_654,\n                -0.362_647_8,\n                0.054_201_64,\n                0.224_758_28,\n            ],\n            vec![\n                -0.039_142_657,\n                -1.410_656_8,\n                0.004_147_059_7,\n                0.122_750_55,\n                0.601_991_5,\n                -0.190_151_87,\n                -0.217_774_1,\n                -0.161_282_72,\n                -0.107_949_33,\n                0.053_716_59,\n            ],\n            vec![\n                0.112_159_1,\n                0.046_277_083,\n                0.275_921_76,\n                -0.232_220_19,\n                -0.514_986_8,\n                -0.385_808_1,\n                0.475_410_9,\n                -0.089_640_72,\n                0.377_189,\n                -0.587_000_6,\n            ],\n            vec![\n                0.422_242_9,\n                0.303_726_17,\n                -0.226_179_72,\n                -0.223_675_2,\n                -0.390_193_07,\n                0.241_592_42,\n                0.510_321_9,\n                -0.769_924_46,\n                -0.186_996_15,\n                -0.151_660_49,\n            ],\n            vec![\n                -0.384_535_1,\n                0.537_968_6,\n                -0.524_274_23,\n                -0.155_019_48,\n                -0.126_955_48,\n                0.009_772_035,\n                -0.516_424_9,\n                -0.234_940_9,\n                0.141_023_25,\n                0.588_008_3,\n            ],\n            vec![\n                0.190_469_76,\n                -0.174_279_08,\n                -0.032_924_425,\n                0.020_208_841,\n                -0.119_237_93,\n                0.320_741_65,\n                0.307_459_98,\n                -0.463_212_76,\n                -0.407_833_8,\n                -0.337_217_8,\n            ],\n            vec![\n                0.027_527_304,\n                0.197_919_01,\n                0.425_531_77,\n                -0.485_134_8,\n                -0.014_653_06,\n                -0.029_860_709,\n                -0.220_132_3,\n                0.131_642_21,\n                -0.104_282_19,\n                -0.386_906_83,\n            ],\n            vec![\n                -0.430_011_15,\n                0.425_528_88,\n                -0.203_507_21,\n                0.393_514_2,\n                -0.351_871_97,\n                -0.370_563_15,\n                -0.020_044_824,\n                -0.261_879_5,\n                -0.169_493_78,\n                0.200_067_86,\n            ],\n            vec![\n                -0.567_681_25,\n                0.480_915_58,\n                -0.412_805_86,\n                0.302_825_93,\n                0.206_955_4,\n                -0.122_011_974,\n                -0.448_144_94,\n                -0.255_924_28,\n                -0.053_469_803,\n                0.390_555_17,\n            ],\n            vec![\n                -0.619_630_6,\n                -0.184_751_24,\n                0.014_298_667,\n                -0.047_660_213,\n                -0.404_390_66,\n                0.110_633_64,\n                0.399_682_85,\n                0.151_165_56,\n                -0.159_483_1,\n                -0.407_734_16,\n            ],\n            vec![\n                0.208_748_55,\n                0.558_834_97,\n                0.362_687_92,\n                -0.338_483_3,\n                -0.221_743_66,\n                0.158_116_89,\n                -0.274_581_67,\n                0.068_234_116,\n                -0.376_377_3,\n                -0.102_255_44,\n            ],\n            vec![\n                0.337_487_16,\n                0.171_616,\n                -0.152_372_08,\n                -0.012_385_000_5,\n                -0.132_557_57,\n                -0.028_043_98,\n                -0.117_279_43,\n                -0.153_480_23,\n                0.006_574_648_4,\n                0.038_567_707,\n            ],\n            vec![\n                -0.712_001_6,\n                -0.511_211,\n                -0.150_782_73,\n                0.340_937_82,\n                0.254_123_18,\n                -0.259_644_8,\n                -0.165_634_53,\n                -0.125_767_35,\n                0.116_586_65,\n                0.397_081_2,\n            ],\n            vec![\n                -0.124_941_25,\n                -0.073_137_37,\n                -0.225_942_08,\n                0.021_587_688,\n                -0.310_861_4,\n                0.265_024,\n                0.437_512_52,\n                0.267_344_92,\n                0.350_228_64,\n                -0.933_803_86,\n            ],\n            vec![\n                0.338_834_3,\n                -0.087_845_86,\n                0.272_357_1,\n                -0.358_795_73,\n                -0.271_767_88,\n                -0.295_830_1,\n                -0.059_075_07,\n                0.070_103_78,\n                -0.507_834_4,\n                0.156_935_7,\n            ],\n            vec![\n                -0.171_727_24,\n                -0.071_319_28,\n                -0.174_659_65,\n                -0.190_311_45,\n                -0.024_922_764,\n                -0.155_949_18,\n                0.055_906_9,\n                0.300_718_64,\n                -0.061_120_763,\n                0.048_273_016,\n            ],\n            vec![\n                0.000_543_689_76,\n                -0.869_367_8,\n                -0.138_599_25,\n                0.174_714_95,\n                -0.186_816_26,\n                0.022_358_809,\n                0.002_629_159_7,\n                -0.115_649_6,\n                0.283_790_8,\n                0.002_904_132_5,\n            ],\n            vec![\n                -0.068_747_63,\n                0.092_202_19,\n                0.011_669_183,\n                -0.379_747_6,\n                0.117_012_89,\n                0.107_468_17,\n                -0.269_050_3,\n                -0.006_621_833_4,\n                0.417_878_3,\n                -0.313_864_7,\n            ],\n            vec![\n                -0.112_997_69,\n                -0.889_295_4,\n                -0.023_633_067,\n                -0.089_614_69,\n                -0.415_933_13,\n                -0.074_443_22,\n                0.258_668_63,\n                0.419_528_16,\n                -0.490_358_4,\n                0.197_501_69,\n            ],\n            vec![\n                0.019_912_645,\n                -0.075_473_6,\n                -0.420_859_46,\n                -0.192_252_4,\n                0.229_218_27,\n                -0.212_090_2,\n                0.296_866_33,\n                0.250_561_54,\n                -0.184_706_94,\n                0.165_873_05,\n            ],\n            vec![\n                0.230_182_22,\n                -0.870_116_8,\n                0.038_269_054,\n                -0.076_351_45,\n                0.106_413_856,\n                -0.440_263_87,\n                0.128_705_7,\n                0.447_829_48,\n                0.203_339_47,\n                -0.447_020_9,\n            ],\n            vec![\n                -0.457_046_75,\n                -0.235_179_57,\n                0.229_851_17,\n                -0.228_986_76,\n                0.471_583_55,\n                0.118_459_63,\n                -0.331_542_28,\n                -0.029_790_87,\n                0.048_763_033,\n                -0.408_412_78,\n            ],\n            vec![\n                -0.091_034_68,\n                0.269_622_06,\n                -0.811_667_6,\n                0.296_985_98,\n                0.857_716_3,\n                -0.322_717_55,\n                -0.288_414_87,\n                0.545_152_7,\n                -0.844_064_9,\n                0.156_081_7,\n            ],\n            vec![\n                -0.044_334_59,\n                -0.443_265_35,\n                -0.400_787_65,\n                0.110_924_87,\n                0.339_526_06,\n                -0.231_262_07,\n                -0.021_097_727,\n                0.399_813_53,\n                -0.274_332_88,\n                -0.021_325_925,\n            ],\n            vec![\n                0.025_087_234,\n                0.216_655_64,\n                0.621_734_44,\n                -0.760_260_46,\n                -0.129_668_74,\n                -0.154_173_79,\n                0.086_462_654,\n                -0.375_934_66,\n                -0.049_108_52,\n                -0.459_173_02,\n            ],\n            vec![\n                -0.095_576_91,\n                -0.020_821_411,\n                0.080_915_31,\n                0.013_726_328_5,\n                -0.059_133_276,\n                0.063_827_924,\n                0.112_209_514,\n                0.007_046_244_6,\n                -0.146_494_31,\n                -0.216_906_01,\n            ],\n            vec![\n                0.049_646_854,\n                0.052_594_967,\n                0.154_725_54,\n                -1.005_775_5,\n                0.319_017_6,\n                -1.194_001_3,\n                -0.009_135_441,\n                0.154_628_23,\n                -0.284_685_82,\n                0.506_814_8,\n            ],\n            vec![\n                0.152_965_72,\n                -0.356_905_73,\n                -0.571_670_65,\n                0.213_715_2,\n                -0.072_330_84,\n                0.214_608_12,\n                0.078_163_56,\n                0.217_828_07,\n                -0.173_689_4,\n                -0.658_648_5,\n            ],\n            vec![\n                -0.376_370_76,\n                -0.150_108_67,\n                1.302_906_6,\n                -0.957_640_2,\n                -0.188_971_88,\n                -0.377_166_48,\n                -0.026_720_16,\n                -0.298_091_2,\n                -0.841_070_23,\n                -0.638_804_4,\n            ],\n            vec![\n                0.240_924_88,\n                0.182_269_63,\n                0.259_873_6,\n                -0.018_908_517,\n                0.249_969_38,\n                0.004_253_394_4,\n                0.937_601_6,\n                -0.470_375_4,\n                -0.213_874_68,\n                -1.540_429_6,\n            ],\n            vec![\n                0.308_340_9,\n                -0.562_844,\n                -0.056_334_414,\n                -0.376_736_97,\n                0.149_921_98,\n                -0.111_814_16,\n                0.267_282_43,\n                0.267_317,\n                0.036_327_82,\n                -0.108_395_79,\n            ],\n            vec![\n                -0.230_489_94,\n                0.410_497_9,\n                -0.547_524_63,\n                0.039_614_655,\n                -0.988_154_4,\n                0.321_934_58,\n                -0.602_366_27,\n                1.047_812_8,\n                -1.289_899_1,\n                -1.083_098,\n            ],\n            vec![\n                0.123_964_37,\n                -0.602_205_9,\n                0.236_914_6,\n                -0.170_817_54,\n                0.318_853_38,\n                -0.315_294_36,\n                0.268_049_06,\n                -0.053_268_034,\n                0.330_402_97,\n                -0.339_753_27,\n            ],\n            vec![\n                -1.076_121_9,\n                0.164_622_11,\n                -0.085_991_43,\n                0.311_612_9,\n                0.092_236_77,\n                0.700_294_7,\n                -0.707_306_2,\n                0.388_372_15,\n                -0.459_460_05,\n                -0.878_541_9,\n            ],\n            vec![\n                0.054_824_94,\n                -0.208_323_96,\n                0.255_419_28,\n                -0.643_839_1,\n                -0.036_447_406,\n                0.071_171_485,\n                0.106_985_23,\n                0.008_280_316,\n                0.163_153_02,\n                -0.149_317_26,\n            ],\n            vec![\n                0.509_663_3,\n                -0.604_420_36,\n                0.096_587_76,\n                0.317_167_55,\n                -0.619_287_67,\n                -0.598_932_6,\n                0.624_861_54,\n                -0.523_107_9,\n                -0.194_404_69,\n                0.189_819_41,\n            ],\n            vec![\n                0.118_258_34,\n                0.198_966_8,\n                0.067_972_64,\n                -0.302_075_48,\n                0.396_576_85,\n                -0.190_334_44,\n                0.101_252_384,\n                0.113_482_1,\n                -0.184_157_92,\n                -0.121_548_79,\n            ],\n            vec![\n                -1.145_558_1,\n                0.348_045_68,\n                -0.423_409_37,\n                0.440_486_2,\n                0.072_455_76,\n                0.763_049_54,\n                -1.268_408_3,\n                0.250_111_82,\n                -0.516_340_8,\n                -0.221_704_6,\n            ],\n            vec![\n                -0.262_807_97,\n                0.276_520_13,\n                0.106_213_8,\n                -0.840_162_6,\n                0.052_412_167,\n                -0.070_005_19,\n                0.178_391_87,\n                0.462_775_5,\n                0.266_045_6,\n                -0.749_436_86,\n            ],\n            vec![\n                -0.202_437_94,\n                -2.144_087_3,\n                -0.066_604_58,\n                0.145_307_91,\n                -0.324_613_12,\n                -0.216_517_84,\n                0.162_818_63,\n                0.020_858_074,\n                0.214_596_1,\n                -0.151_569_08,\n            ],\n            vec![\n                0.260_816_72,\n                0.047_080_51,\n                0.223_103_91,\n                -0.463_461_3,\n                0.378_594_96,\n                -0.177_486_64,\n                -0.119_682_61,\n                -0.136_843_38,\n                -0.316_811_6,\n                -0.301_904_92,\n            ],\n            vec![\n                -0.050_370_42,\n                -0.113_588_64,\n                -0.635_774_6,\n                0.286_719_14,\n                0.100_364_72,\n                0.363_518_63,\n                -0.715_137_06,\n                -0.032_084_25,\n                -0.612_420_6,\n                0.366_159_14,\n            ],\n            vec![\n                0.074_133_57,\n                -0.351_425_38,\n                0.301_147_34,\n                -0.591_415_8,\n                -0.691_740_3,\n                -0.058_086_09,\n                -0.023_912_637,\n                0.035_622_265,\n                0.253_961_95,\n                -0.318_256_23,\n            ],\n            vec![\n                0.253_794_28,\n                -1.398_279_4,\n                0.025_405_943,\n                -0.100_225_77,\n                0.264_267_9,\n                -0.325_903_53,\n                0.353_900_52,\n                -0.329_170_82,\n                0.209_164_6,\n                -0.406_238_32,\n            ],\n            vec![\n                0.052_275_31,\n                -0.042_211_66,\n                0.013_816_439,\n                -0.162_884_19,\n                0.066_365_06,\n                0.099_114_14,\n                -0.112_847_95,\n                -0.683_042_2,\n                0.152_652_59,\n                0.247_954_49,\n            ],\n            vec![\n                -0.169_138_82,\n                0.063_316_345,\n                -0.076_943_83,\n                0.330_167_4,\n                -0.332_760_45,\n                0.434_988_68,\n                -0.467_590_93,\n                -0.163_963_1,\n                -1.147_984_3,\n                0.389_239_9,\n            ],\n            vec![\n                0.396_338_05,\n                -0.439_943_28,\n                0.338_350_42,\n                -0.212_763_92,\n                -0.067_297_46,\n                -0.154_291_87,\n                -0.127_878_6,\n                0.205_634_64,\n                0.341_983_68,\n                -0.700_542_45,\n            ],\n            vec![\n                0.459_232_57,\n                -0.363_285_15,\n                0.151_907_15,\n                -0.270_820_17,\n                0.009_670_896,\n                -0.742_408_9,\n                0.592_906_8,\n                -0.601_926_5,\n                0.274_525_64,\n                -0.695_935_1,\n            ],\n            vec![\n                0.355_251_46,\n                -0.182_071_31,\n                -0.383_383_57,\n                0.006_683_327_3,\n                -0.227_649_12,\n                -0.277_776_72,\n                0.543_340_56,\n                -0.651_580_8,\n                -0.098_558_836,\n                0.477_418_54,\n            ],\n            vec![\n                0.293_424_58,\n                -0.607_008_34,\n                -0.075_632_825,\n                0.467_701_73,\n                0.293_549_72,\n                0.043_996_7,\n                -0.236_586_54,\n                -0.435_596_67,\n                -0.384_609_1,\n                -0.038_321_488,\n            ],\n            vec![\n                0.709_046_07,\n                -0.007_807_638_5,\n                0.201_393_7,\n                -0.629_413_4,\n                -0.310_686_8,\n                -0.164_051_59,\n                0.216_480_8,\n                0.212_010_01,\n                0.288_591_68,\n                -0.234_935_46,\n            ],\n            vec![\n                0.248_700_96,\n                0.463_258_9,\n                0.213_166_83,\n                -0.493_549_7,\n                -0.500_947_36,\n                -0.233_916_37,\n                -0.170_004_2,\n                -0.395_093_44,\n                0.287_036_15,\n                -0.080_354_17,\n            ],\n            vec![\n                0.061_269_62,\n                0.258_783_22,\n                -0.153_121_84,\n                0.113_186_5,\n                0.024_635_103,\n                -0.002_860_725_6,\n                -0.411_487_85,\n                -0.585_028_9,\n                0.044_166_09,\n                0.228_433_37,\n            ],\n            vec![\n                0.132_530_67,\n                -0.180_983_57,\n                0.134_121_52,\n                0.275_544_58,\n                -0.566_425_5,\n                0.038_025_07,\n                0.315_159_92,\n                -0.802_072_64,\n                0.077_547_364,\n                -0.816_164_1,\n            ],\n            vec![\n                0.253_262_8,\n                -0.189_946,\n                0.331_578_8,\n                -0.404_263_38,\n                -0.151_000_84,\n                0.073_550_07,\n                0.053_775_515,\n                -0.105_317_04,\n                0.135_138_12,\n                0.010_357_873,\n            ],\n            vec![\n                -0.262_911_5,\n                0.242_837_41,\n                0.207_556_83,\n                -0.334_707_74,\n                0.097_789_675,\n                -0.122_015_78,\n                -0.137_531_04,\n                -0.221_596_08,\n                0.078_258_86,\n                0.196_424_14,\n            ],\n            vec![\n                -0.473_952_86,\n                0.088_429_66,\n                0.038_478_95,\n                0.179_662_59,\n                0.068_714_57,\n                -0.325_091_87,\n                -0.105_515_07,\n                -0.208_877_01,\n                -0.020_721_51,\n                0.331_142_9,\n            ],\n            vec![\n                -0.213_202_6,\n                0.111_628_61,\n                0.141_606_03,\n                -0.075_352_96,\n                -0.104_872_68,\n                0.249_525_04,\n                0.052_972_06,\n                -0.699_384_57,\n                0.108_099_86,\n                -0.880_204_74,\n            ],\n            vec![\n                -0.012_819_135,\n                -0.188_733_34,\n                0.122_128_38,\n                -0.165_244_4,\n                -0.388_994_16,\n                0.040_872_46,\n                -0.008_985_156,\n                -0.082_336_16,\n                -0.231_696_62,\n                0.065_530_87,\n            ],\n            vec![\n                -0.180_819_06,\n                0.083_178_22,\n                0.006_874_827,\n                -0.014_614_635,\n                -0.196_168_27,\n                -0.009_432_043,\n                0.327_855_74,\n                -0.241_962_02,\n                0.248_983_44,\n                0.071_856_335,\n            ],\n            vec![\n                0.193_247_78,\n                -0.291_666_98,\n                0.176_878_88,\n                0.231_443_12,\n                -0.066_874_83,\n                -0.252_131_64,\n                -0.190_652_65,\n                -0.171_646_98,\n                0.055_850_454,\n                0.101_139_7,\n            ],\n            vec![\n                0.109_673_426,\n                0.237_693_83,\n                0.214_820_58,\n                -0.169_411_7,\n                -0.470_538_05,\n                0.039_358_5,\n                -0.303_813_25,\n                -0.118_628_58,\n                0.180_367_75,\n                -0.518_705_84,\n            ],\n            vec![\n                0.140_499_17,\n                -0.128_086_85,\n                -0.378_094_9,\n                -0.231_051_09,\n                -0.440_477_82,\n                0.065_958_3,\n                0.249_295_49,\n                -0.348_497_84,\n                -0.145_569_32,\n                0.148_800_55,\n            ],\n            vec![\n                -0.146_809_82,\n                -0.013_122_066,\n                -0.358_625,\n                -0.225_462_26,\n                -0.013_221_264,\n                0.116_620_995,\n                0.297_690_93,\n                -0.297_707_77,\n                0.305_377_8,\n                -0.088_207_8,\n            ],\n            vec![\n                0.288_419_66,\n                -0.858_799_6,\n                0.276_324_63,\n                0.323_865_12,\n                -0.234_156_06,\n                -0.215_353_5,\n                0.236_237,\n                -0.344_054_8,\n                -0.057_662_178,\n                -0.177_651_82,\n            ],\n            vec![\n                -0.080_386_27,\n                0.239_525_81,\n                0.180_896_65,\n                -0.285_275_5,\n                -0.050_495_982,\n                -0.374_826_3,\n                -0.278_306_45,\n                0.112_782_456,\n                -0.104_671_53,\n                0.304_652_18,\n            ],\n            vec![\n                0.032_451_022,\n                -1.064_182_9,\n                -0.152_482_1,\n                0.093_027_7,\n                -0.703_669_3,\n                0.141_962_16,\n                -0.124_975_15,\n                -0.171_874_43,\n                -0.039_661_873,\n                0.445_249_56,\n            ],\n            vec![\n                0.046_288_554,\n                -0.153_212_88,\n                -0.320_360_78,\n                0.280_627_1,\n                0.090_613_514,\n                -0.055_976_465,\n                -0.014_144_503_5,\n                -0.011_305_857,\n                -0.018_035_34,\n                0.011_035_047,\n            ],\n            vec![\n                -0.086_249_456,\n                0.088_105_045,\n                0.368_546_1,\n                -0.155_759_65,\n                0.382_325,\n                -0.536_992_13,\n                0.188_152_09,\n                -0.136_534_48,\n                -0.361_743_2,\n                -0.208_948_1,\n            ],\n            vec![\n                -0.910_889_7,\n                0.272_101_04,\n                0.135_209_81,\n                -0.349_540_56,\n                0.126_585_16,\n                -0.089_697_324,\n                -0.131_358_15,\n                0.545_545_9,\n                -0.205_144_06,\n                0.253_362_5,\n            ],\n            vec![\n                -0.184_916_23,\n                -0.374_353_44,\n                -0.891_287_57,\n                -0.267_861_46,\n                -0.051_716_913,\n                -0.515_604_73,\n                0.253_273_43,\n                0.429_561_23,\n                0.509_542_35,\n                -0.086_592_466,\n            ],\n            vec![\n                -0.081_433_564,\n                0.198_853_52,\n                -0.033_626_94,\n                0.073_289_62,\n                0.193_763_61,\n                -0.048_186_395,\n                0.127_340_51,\n                -0.342_430_5,\n                -0.154_588_85,\n                -0.207_824_74,\n            ],\n            vec![\n                0.271_959_33,\n                -0.041_163_232,\n                0.437_336_15,\n                -0.443_907_1,\n                0.084_922_336,\n                -0.000_430_476_33,\n                -0.098_115_13,\n                -0.343_641_52,\n                -0.244_402_11,\n                -0.175_968_54,\n            ],\n            vec![\n                -0.190_617_32,\n                0.230_641_68,\n                -0.188_811_4,\n                0.177_157_28,\n                0.048_706_33,\n                -0.090_728_484,\n                0.153_938_11,\n                0.037_883_04,\n                -0.355_102_63,\n                0.116_667_435,\n            ],\n            vec![\n                0.402_895_78,\n                -0.317_966_88,\n                0.258_100_3,\n                -0.026_641_415,\n                -0.338_13,\n                0.090_999_93,\n                -0.261_858_8,\n                0.191_292_58,\n                -1.057_412,\n                0.382_777_07,\n            ],\n            vec![\n                -0.309_803_16,\n                -0.035_574_716,\n                -0.368_250_88,\n                0.588_673_35,\n                -0.211_507_75,\n                0.018_968_955,\n                0.195_586_1,\n                -0.303_870_17,\n                -0.038_711_112,\n                -0.266_695_6,\n            ],\n            vec![\n                0.029_523_142,\n                -0.132_643_09,\n                0.603_934_1,\n                -0.538_810_8,\n                -0.303_734_24,\n                -0.611_127_6,\n                0.207_553_15,\n                -0.042_333_387,\n                -0.207_477_15,\n                -0.986_770_5,\n            ],\n            vec![\n                -1.344_093_9,\n                0.169_231_64,\n                0.061_742_768,\n                -0.253_307_07,\n                -1.425_251_2,\n                -0.079_412_21,\n                -0.527_068_44,\n                0.048_233_565,\n                0.255_186_32,\n                -0.558_624_4,\n            ],\n            vec![\n                0.361_004_3,\n                0.166_129_93,\n                0.344_421_86,\n                -0.383_434_74,\n                -0.492_711_96,\n                -0.684_580_45,\n                0.575_839_94,\n                -0.431_959_2,\n                0.416_690_38,\n                -0.076_345_67,\n            ],\n            vec![\n                0.300_126_25,\n                0.690_369_1,\n                -1.068_929_3,\n                0.779_963_97,\n                -1.161_616_9,\n                -0.320_421_67,\n                -0.699_888_4,\n                1.190_991_5,\n                -1.227_549_9,\n                -1.279_037_4,\n            ],\n            vec![\n                0.094_041_63,\n                0.374_507_96,\n                0.558_502_3,\n                -0.320_508_27,\n                -0.070_787_884,\n                -0.315_834_9,\n                0.404_205_9,\n                -0.396_628_05,\n                0.213_888_62,\n                -0.808_717_4,\n            ],\n            vec![\n                -2.094_858_6,\n                0.892_611_4,\n                -0.239_027_08,\n                0.395_698_2,\n                -0.483_642_64,\n                0.949_595_7,\n                -1.154_229_9,\n                -0.320_442_9,\n                -0.665_861_96,\n                -0.597_626_86,\n            ],\n            vec![\n                -0.177_534_52,\n                0.252_983_5,\n                0.116_914_53,\n                -0.560_802_1,\n                0.087_838_47,\n                -0.090_237_91,\n                0.053_532_7,\n                -0.182_902_56,\n                0.084_240_03,\n                -0.088_681_21,\n            ],\n            vec![\n                -0.538_007,\n                -0.922_660_95,\n                0.273_737_94,\n                0.454_611_18,\n                -0.405_907_57,\n                0.346_772_2,\n                0.337_938_85,\n                -0.476_058_45,\n                -2.544_968,\n                -0.027_647_516,\n            ],\n            vec![\n                0.253_208_6,\n                -0.398_181_68,\n                0.117_977_105,\n                -0.118_475_36,\n                0.316_321_02,\n                -0.069_564_12,\n                -0.162_117_57,\n                -0.532_771_77,\n                -0.053_623_687,\n                -0.046_250_254,\n            ],\n            vec![\n                -1.595_345,\n                0.359_475_85,\n                -1.132_169,\n                0.432_727_55,\n                0.061_862_98,\n                0.488_555_88,\n                -1.566_254_6,\n                -0.057_182_09,\n                -0.608_943_34,\n                0.738_639_4,\n            ],\n            vec![\n                0.142_813_28,\n                0.105_241_664,\n                0.111_599_65,\n                -0.381_024_63,\n                0.080_321_72,\n                -0.142_857_43,\n                -0.264_929_5,\n                -0.184_825_7,\n                0.159_262_42,\n                -0.245_617_99,\n            ],\n            vec![\n                0.655_968,\n                -1.573_916,\n                0.432_372_96,\n                -0.298_297_8,\n                0.502_385_26,\n                -0.046_713_434,\n                -1.533_887,\n                -0.506_285_85,\n                -0.146_341_43,\n                0.242_697_31,\n            ],\n            vec![\n                -0.024_878_51,\n                -0.016_973_916,\n                -0.008_455_125,\n                0.239_947_11,\n                0.124_730_94,\n                -0.347_739_07,\n                0.378_534_85,\n                -0.622_885_4,\n                -0.110_197_38,\n                0.128_122_76,\n            ],\n            vec![\n                -0.218_680_77,\n                0.007_973_12,\n                -0.552_104_8,\n                0.386_266_47,\n                -0.118_366_756,\n                0.403_684_44,\n                -1.525_699_7,\n                -0.182_769_82,\n                -0.480_417_88,\n                0.622_442_54,\n            ],\n            vec![\n                -0.303_771_9,\n                -0.042_189_557,\n                0.092_569_9,\n                -0.574_998_4,\n                0.298_017_68,\n                0.167_696_8,\n                -0.202_827_51,\n                -0.142_146,\n                -0.028_678_67,\n                0.029_778_654,\n            ],\n            vec![\n                0.486_929_45,\n                -0.567_170_5,\n                0.417_988_18,\n                -0.692_029_06,\n                0.041_134_74,\n                -0.792_387_4,\n                0.482_731_85,\n                -0.081_591_256,\n                0.193_019_3,\n                -0.081_880_37,\n            ],\n            vec![\n                -0.295_165_42,\n                0.512_547_5,\n                0.021_734_945,\n                0.172_966_55,\n                0.024_421_481,\n                -0.130_438_34,\n                0.182_010_81,\n                -1.150_716_8,\n                -0.215_264_6,\n                0.355_813_6,\n            ],\n            vec![\n                -0.072_581_3,\n                -0.071_467_33,\n                -0.358_769_15,\n                0.369_515_5,\n                -0.309_179_04,\n                0.183_673_81,\n                -0.194_713_83,\n                -0.686_681_75,\n                -0.520_779_43,\n                0.190_687_49,\n            ],\n            vec![\n                -0.304_834_3,\n                -0.003_794_444,\n                -0.041_297_033,\n                -0.344_114_3,\n                0.262_485_65,\n                0.134_406_94,\n                -0.385_703_86,\n                0.163_270_4,\n                -0.027_921_52,\n                -0.225_358_17,\n            ],\n            vec![\n                0.152_046_65,\n                0.351_264_2,\n                -0.055_531_275,\n                -0.621_087_25,\n                0.161_118_24,\n                -0.318_924_28,\n                0.309_624_1,\n                -0.128_448_31,\n                0.275_008_44,\n                -0.246_409_85,\n            ],\n            vec![\n                -0.123_393_57,\n                0.319_738_15,\n                -0.188_316_5,\n                -0.068_521_924,\n                0.008_892_386,\n                -0.022_754_567,\n                -0.047_962_56,\n                -0.411_065_5,\n                -0.109_584_08,\n                0.294_392_1,\n            ],\n            vec![\n                0.223_933_8,\n                -0.908_405_07,\n                -0.109_861_635,\n                0.140_895_23,\n                -0.903_743_2,\n                0.259_576_98,\n                -0.231_276_26,\n                -0.505_061_3,\n                -0.055_671_822,\n                -0.141_510_58,\n            ],\n            vec![\n                0.027_742_716,\n                -0.232_495_8,\n                -0.149_456_53,\n                -0.133_731_6,\n                0.017_137_157,\n                -0.092_800_43,\n                -0.595_613_24,\n                0.376_796_96,\n                -0.213_737_58,\n                0.137_654_66,\n            ],\n            vec![\n                -0.183_406_59,\n                0.552_172_5,\n                -0.378_588_3,\n                -1.007_870_4,\n                -0.015_809_247,\n                -0.196_884_62,\n                0.240_182_82,\n                0.050_163_735,\n                0.068_832_89,\n                0.203_356_61,\n            ],\n            vec![\n                0.287_887_1,\n                0.079_854_11,\n                -0.084_014_416,\n                -0.248_976_04,\n                -0.271_918_54,\n                -0.002_412_714_8,\n                0.216_199_38,\n                -0.569_119_1,\n                -0.112_770_88,\n                0.540_719_6,\n            ],\n            vec![\n                0.222_881_64,\n                -0.026_424_6,\n                0.048_772_09,\n                -0.146_413_06,\n                -1.901_193_9,\n                0.080_811_17,\n                0.147_072_54,\n                -0.397_790_46,\n                0.009_769_149,\n                -0.488_872_17,\n            ],\n            vec![\n                0.138_054_16,\n                -0.538_929_9,\n                -0.023_378_126,\n                -0.111_065_865,\n                0.276_592_94,\n                0.011_875_795,\n                -0.575_297_5,\n                0.184_301_76,\n                -0.287_715_35,\n                0.065_143_935,\n            ],\n            vec![\n                -0.552_735_4,\n                0.170_184_34,\n                0.113_717_236,\n                -0.240_356_07,\n                -0.123_588_435,\n                -0.058_988_72,\n                0.245_473_03,\n                -0.165_541_07,\n                0.144_339,\n                0.003_233_700_5,\n            ],\n            vec![\n                -0.029_856_594,\n                -0.252_960_12,\n                -0.012_215_844,\n                0.236_105_9,\n                0.287_288,\n                -0.408_385_34,\n                0.423_000_07,\n                0.157_817_66,\n                -0.016_059_026,\n                -0.278_439_52,\n            ],\n            vec![\n                -0.218_601_96,\n                0.037_431_795,\n                0.068_911_664,\n                -0.052_260_6,\n                -0.701_169_43,\n                0.143_489_64,\n                -0.029_043_015,\n                0.117_241_71,\n                0.118_014_246,\n                -0.401_062_9,\n            ],\n            vec![\n                0.184_052_65,\n                -0.694_549_14,\n                -0.227_834_02,\n                -0.068_688_065,\n                0.418_908,\n                -0.010_074_062,\n                -0.385_147_06,\n                -0.237_238_53,\n                -0.169_812_08,\n                0.140_497_3,\n            ],\n            vec![\n                -0.372_383_03,\n                0.067_174_725,\n                -0.166_325_8,\n                -0.080_401_81,\n                0.290_444_9,\n                -0.188_639_22,\n                0.151_756_58,\n                -0.076_491_4,\n                -0.021_862_388,\n                0.104_889_02,\n            ],\n            vec![\n                -0.342_421_56,\n                -0.158_555_61,\n                0.302_041_56,\n                0.164_577_9,\n                -0.032_191_727,\n                -0.149_581_67,\n                0.314_295_02,\n                -0.236_396_77,\n                0.062_216_03,\n                -0.242_104_13,\n            ],\n            vec![\n                -0.063_866_61,\n                0.546_288_43,\n                0.592_044_6,\n                -0.048_455_39,\n                -0.035_933_536,\n                -0.263_329_68,\n                -0.395_228_48,\n                0.051_577_035,\n                -0.290_856_4,\n                -0.260_335_45,\n            ],\n            vec![\n                -0.204_643_31,\n                -0.790_377_5,\n                -0.423_973_1,\n                0.394_549_4,\n                0.158_310_1,\n                0.520_480_2,\n                -0.384_039_85,\n                -0.470_651_3,\n                -0.134_060_95,\n                0.067_312_695,\n            ],\n            vec![\n                -0.243_832_14,\n                -0.189_681_66,\n                -0.170_536_52,\n                0.070_982_26,\n                0.210_219_16,\n                -0.105_663_456,\n                0.070_937_06,\n                0.024_109_1,\n                -0.006_263_296,\n                0.018_320_573,\n            ],\n            vec![\n                -0.172_563_31,\n                0.441_392_72,\n                0.372_488_38,\n                0.003_720_252_3,\n                0.030_075_574,\n                -0.216_040_12,\n                0.399_601_82,\n                -0.655_864_2,\n                -0.083_364_85,\n                -0.593_644_4,\n            ],\n            vec![\n                0.027_736_979,\n                0.826_652,\n                0.822_206_2,\n                -0.582_489_25,\n                -0.044_828_773,\n                -0.581_488_4,\n                -0.285_438_2,\n                -0.379_783_5,\n                -0.286_307_07,\n                -0.102_620_09,\n            ],\n            vec![\n                0.314_700_75,\n                -1.524_852_9,\n                -0.763_385_1,\n                0.722_350_4,\n                -0.472_515_5,\n                0.452_854_22,\n                -0.346_417_13,\n                -0.517_595_9,\n                0.155_832_47,\n                -0.666_454_5,\n            ],\n            vec![\n                -0.354_128_63,\n                -0.150_265_6,\n                -0.146_090_08,\n                -0.002_240_108_3,\n                0.097_634_58,\n                -0.092_596_22,\n                -0.077_518_13,\n                0.098_131_66,\n                0.043_073_647,\n                -0.048_724_25,\n            ],\n            vec![\n                0.001_564_541_6,\n                0.075_788_16,\n                0.233_583_33,\n                -0.104_224_06,\n                0.431_796_37,\n                -0.373_122_75,\n                -0.392_585_9,\n                -0.093_903_34,\n                -0.185_715_38,\n                0.058_544_405,\n            ],\n            vec![\n                -0.332_656_68,\n                -0.189_840_85,\n                1.300_733_4,\n                -0.580_438_3,\n                0.223_974_1,\n                -0.057_784_215,\n                -0.214_602_26,\n                -0.656_930_6,\n                -0.157_153_49,\n                -0.080_237_42,\n            ],\n            vec![\n                -0.374_737_6,\n                -0.203_834_73,\n                -0.517_297_3,\n                0.412_784_2,\n                -0.970_973_4,\n                0.525_642_45,\n                -0.345_279_6,\n                0.196_275_2,\n                0.068_473_96,\n                0.057_966_32,\n            ],\n            vec![\n                -0.206_786_44,\n                -0.166_731_15,\n                -0.277_479_2,\n                -0.079_962_75,\n                0.274_603_55,\n                -0.076_264_1,\n                0.065_194_56,\n                -0.000_790_951_2,\n                -0.014_463_453,\n                -0.020_161_366,\n            ],\n            vec![\n                -0.224_463_95,\n                0.101_412_96,\n                0.638_434_3,\n                -0.380_875_7,\n                -0.374_144_4,\n                0.106_621_68,\n                -0.224_464_5,\n                -0.106_371_82,\n                0.118_541_16,\n                -0.550_626_7,\n            ],\n            vec![\n                -0.060_894_59,\n                -0.489_318_3,\n                0.193_886_74,\n                0.104_497_54,\n                0.006_548_385,\n                0.149_242_77,\n                -0.532_321_8,\n                -0.391_359_06,\n                -0.056_789_97,\n                -0.072_821_505,\n            ],\n            vec![\n                0.861_896_63,\n                -0.556_303_86,\n                -0.339_215_52,\n                0.181_062_86,\n                -0.155_863_08,\n                -0.141_478_06,\n                -0.199_623_57,\n                -0.031_703_413,\n                -0.105_384_51,\n                -0.291_078_45,\n            ],\n            vec![\n                -0.534_867_2,\n                0.166_174_89,\n                0.194_590_84,\n                0.211_057_96,\n                -0.093_018_58,\n                0.144_604_07,\n                -0.602_165_34,\n                -0.621_696_2,\n                -0.136_288_7,\n                0.323_563_2,\n            ],\n            vec![\n                -0.417_162_4,\n                0.509_713_53,\n                0.629_261_9,\n                -0.350_670_7,\n                -0.785_039_4,\n                -0.556_359_23,\n                0.179_918_44,\n                -0.642_441_5,\n                -0.009_600_11,\n                0.252_771_4,\n            ],\n            vec![\n                0.469_258_84,\n                -0.855_024_6,\n                -1.139_494_7,\n                1.120_604_8,\n                -1.778_672_9,\n                -0.088_683_52,\n                0.548_659_4,\n                -0.079_584_97,\n                -1.412_795_8,\n                -0.117_211_64,\n            ],\n            vec![\n                0.313_460_44,\n                0.023_192_618,\n                -0.490_629_1,\n                -0.061_270_583,\n                -1.280_864_6,\n                0.074_842_51,\n                0.243_480_1,\n                -0.302_316_2,\n                0.313_274_35,\n                0.010_305_379_5,\n            ],\n            vec![\n                -0.136_217_18,\n                0.827_996_9,\n                0.006_726_798_6,\n                0.114_384_174,\n                -0.416_126_25,\n                0.454_064_16,\n                -0.044_973_407,\n                -0.230_108_25,\n                -1.075_043_3,\n                -1.211_537_5,\n            ],\n            vec![\n                0.254_804_46,\n                0.112_977_27,\n                0.636_671_5,\n                -0.396_636_04,\n                -1.013_891_3,\n                0.006_650_318_4,\n                0.412_682_83,\n                -1.177_916,\n                0.152_523_96,\n                -0.469_226_6,\n            ],\n            vec![\n                -0.594_725_97,\n                -0.624_621_57,\n                -2.020_615_3,\n                -0.064_352_76,\n                0.183_114_38,\n                0.490_432_3,\n                -0.265_091_1,\n                0.644_683,\n                -1.330_572_6,\n                0.489_623_07,\n            ],\n            vec![\n                -0.011_184_594,\n                0.156_875_71,\n                0.236_530_6,\n                -0.397_889_2,\n                -0.212_858_21,\n                0.044_737_875,\n                -0.590_274_63,\n                -0.066_678_21,\n                -0.027_576_448,\n                -0.136_117_09,\n            ],\n            vec![\n                -0.233_180_85,\n                -1.124_434_8,\n                1.129_748_3,\n                -0.175_548_2,\n                -0.861_948_2,\n                -0.498_053_7,\n                -0.195_488_96,\n                -2.249_580_1,\n                -0.512_081_56,\n                0.198_302_9,\n            ],\n            vec![\n                0.278_029_53,\n                0.142_057_5,\n                0.483_636_14,\n                -0.578_241_65,\n                -0.051_348_41,\n                -0.099_346_526,\n                0.280_694_54,\n                -0.555_599_03,\n                0.172_815_83,\n                -0.128_702_34,\n            ],\n            vec![\n                -1.064_693_6,\n                -0.205_767_29,\n                -1.183_542_7,\n                0.752_033_2,\n                -1.288_635_6,\n                0.470_424_12,\n                -2.355_776,\n                -0.134_253_84,\n                -0.579_577_7,\n                -0.122_758_45,\n            ],\n            vec![\n                -0.560_981_3,\n                0.278_608_56,\n                0.130_296_14,\n                -0.442_299_7,\n                0.532_096_6,\n                0.267_559_92,\n                -0.334_101_8,\n                0.205_616_82,\n                -0.378_532_62,\n                -0.133_773_39,\n            ],\n            vec![\n                0.549_214_2,\n                -0.024_388_539,\n                0.221_822_26,\n                -0.573_709_13,\n                0.681_470_1,\n                0.060_962_49,\n                -1.178_789_9,\n                -0.125_538_24,\n                0.163_888_47,\n                -0.991_272_03,\n            ],\n            vec![\n                0.172_073_77,\n                0.232_600_36,\n                0.378_192_66,\n                -0.214_604_97,\n                -0.105_139_2,\n                -0.473_140_27,\n                0.211_957_08,\n                -0.384_924_02,\n                0.264_930_34,\n                -0.299_187_33,\n            ],\n            vec![\n                0.043_230_236,\n                -0.610_978_4,\n                -1.192_533,\n                0.493_039_85,\n                -0.891_411_5,\n                0.410_983_65,\n                -0.368_046_3,\n                -0.696_914_6,\n                -0.306_526_72,\n                0.249_337_05,\n            ],\n            vec![\n                -0.347_867_16,\n                0.606_439_4,\n                0.021_995_341,\n                -0.689_578_65,\n                -0.003_900_446_7,\n                0.073_512_33,\n                -0.281_876_86,\n                0.166_069_42,\n                -0.458_259_58,\n                0.150_449_93,\n            ],\n            vec![\n                0.249_344_18,\n                -0.189_730_76,\n                0.321_47,\n                0.108_508_72,\n                0.313_829_78,\n                -0.866_597_06,\n                0.130_970_21,\n                0.236_043_48,\n                0.072_720_06,\n                -0.472_748_46,\n            ],\n            vec![\n                0.102_692_31,\n                0.008_673_394,\n                0.090_486_83,\n                0.002_421_351,\n                -0.293_571_5,\n                -0.083_851_23,\n                0.272_985_58,\n                -0.916_719_73,\n                0.312_562_76,\n                -0.216_144_65,\n            ],\n            vec![\n                0.513_089_36,\n                -0.760_970_3,\n                -0.109_253_26,\n                0.324_638_43,\n                -1.610_134_4,\n                0.365_245_13,\n                0.145_767_99,\n                -1.275_347_6,\n                0.061_278_246,\n                -0.201_693_62,\n            ],\n            vec![\n                -0.686_574_7,\n                -0.011_772_094,\n                -0.212_761_97,\n                -0.197_130_05,\n                0.448_876_14,\n                0.030_639_209,\n                -0.433_391_57,\n                0.089_604_154,\n                -0.522_763_25,\n                0.204_889_92,\n            ],\n            vec![\n                -0.169_049_92,\n                0.735_562_7,\n                -0.368_875_9,\n                -0.741_709_23,\n                0.085_351_005,\n                -0.667_998_8,\n                0.182_068_91,\n                0.249_736_53,\n                0.024_728_911,\n                0.147_767_14,\n            ],\n            vec![\n                0.269_879_73,\n                -0.061_343_107,\n                0.189_085_74,\n                0.057_410_844,\n                -0.413_874_86,\n                0.016_049_583,\n                0.354_817_8,\n                -0.213_496_49,\n                -0.016_339_261,\n                -0.195_600_63,\n            ],\n            vec![\n                0.612_416_45,\n                -0.652_237,\n                -0.290_922_4,\n                0.100_256_38,\n                -0.763_017_95,\n                0.134_294_51,\n                -0.346_889_47,\n                -1.198_402_4,\n                0.058_237_143,\n                -0.291_215_63,\n            ],\n            vec![\n                -1.451_199_5,\n                -0.261_634_74,\n                -0.290_876_92,\n                -0.112_408_124,\n                0.474_783_4,\n                0.259_347_14,\n                -1.402_955_7,\n                0.158_754_13,\n                -0.393_066_23,\n                0.170_342_42,\n            ],\n            vec![\n                -0.025_236_953,\n                0.091_647_916,\n                -0.063_152_87,\n                -0.691_322_1,\n                0.113_248_47,\n                -0.495_438_43,\n                0.110_764_95,\n                0.190_719_05,\n                0.092_877_21,\n                0.021_988_474,\n            ],\n            vec![\n                0.371_424_4,\n                -0.271_200_48,\n                0.052_355_736,\n                0.076_789_506,\n                -0.086_218_92,\n                -0.109_440_014,\n                0.269_172_04,\n                -0.321_849_58,\n                0.032_248_903,\n                -0.261_390_84,\n            ],\n            vec![\n                -0.372_055_23,\n                0.092_231_646,\n                -0.044_099_193,\n                0.178_492_75,\n                -0.317_144_16,\n                -0.081_630_535,\n                0.196_395_25,\n                -0.639_333_2,\n                0.134_729_04,\n                -0.032_898_054,\n            ],\n            vec![\n                -1.602_207_1,\n                -0.513_332_7,\n                -0.603_366_73,\n                -0.072_191_55,\n                0.333_521_63,\n                0.358_542_08,\n                -1.165_994_6,\n                0.183_343_26,\n                -0.066_384_84,\n                0.211_841_17,\n            ],\n            vec![\n                -0.620_023_2,\n                0.150_212_59,\n                -0.350_462_08,\n                0.064_612_39,\n                0.208_557_87,\n                -0.146_651_24,\n                -0.185_354_29,\n                0.116_813_12,\n                0.138_185_2,\n                -0.143_217_43,\n            ],\n            vec![\n                0.143_314_14,\n                -0.002_241_282,\n                0.001_118_428_3,\n                -0.144_721_54,\n                -0.174_310_04,\n                -0.140_035_72,\n                0.442_062_68,\n                -0.175_482_47,\n                0.057_133_213,\n                -0.229_593_01,\n            ],\n            vec![\n                -0.168_592_27,\n                0.249_408_66,\n                0.407_433_4,\n                -0.255_238_06,\n                0.346_984_45,\n                -0.251_691_88,\n                0.265_445_8,\n                0.098_686_33,\n                -0.421_546_55,\n                -0.193_290_73,\n            ],\n            vec![\n                -0.849_656_5,\n                -0.866_653_5,\n                -0.433_286_1,\n                0.437_252_34,\n                -0.031_424_575,\n                0.433_979_57,\n                0.068_777_926,\n                0.105_180_53,\n                0.273_456_1,\n                -0.106_595_99,\n            ],\n            vec![\n                -0.698_027_73,\n                0.245_267_1,\n                -0.051_311_884,\n                -0.057_796_728,\n                0.265_975_77,\n                -0.204_770_73,\n                0.498_724_46,\n                0.112_041_235,\n                -0.230_303_29,\n                -0.035_942_525,\n            ],\n            vec![\n                -0.123_949_625,\n                0.083_198_01,\n                -0.194_088_24,\n                0.043_361_794,\n                -0.143_197_5,\n                -0.183_903_63,\n                0.085_556_96,\n                -0.147_593_33,\n                0.188_463_91,\n                -0.067_946_32,\n            ],\n            vec![\n                -0.776_119,\n                0.319_575_22,\n                1.368_732_1,\n                -0.927_126_9,\n                0.283_870_94,\n                -0.463_118_76,\n                -0.611_538_3,\n                -0.392_389_03,\n                -0.181_314_23,\n                0.006_984_539_3,\n            ],\n            vec![\n                -0.218_999_68,\n                -0.384_511_35,\n                -0.574_313_7,\n                0.440_100_37,\n                -0.661_546_3,\n                0.322_600_1,\n                -0.286_143_45,\n                -0.646_361_35,\n                0.550_332_67,\n                0.120_832_48,\n            ],\n            vec![\n                -0.643_277_35,\n                0.128_418_03,\n                0.179_817_42,\n                0.268_390_8,\n                0.079_269_51,\n                0.124_471_985,\n                0.022_212_533,\n                -0.147_600_32,\n                -0.362_296_16,\n                0.123_608_25,\n            ],\n            vec![\n                -0.324_855_24,\n                0.066_592_135,\n                0.193_869_59,\n                0.056_280_106,\n                0.271_695_05,\n                -0.099_054_07,\n                -0.005_476_542_3,\n                -0.385_905_03,\n                0.016_091_432,\n                -0.064_823_22,\n            ],\n            vec![\n                -1.457_897_3,\n                0.392_666_1,\n                0.960_027_4,\n                -0.722_546_34,\n                0.349_659_6,\n                -0.715_940_2,\n                -1.805_410_7,\n                -0.064_484_65,\n                -0.303_603_83,\n                0.187_947_15,\n            ],\n            vec![\n                -0.428_292_3,\n                -0.341_486_84,\n                0.063_829_09,\n                0.292_772_02,\n                -1.050_140_6,\n                0.833_778_8,\n                0.437_908_62,\n                -0.802_109_2,\n                0.054_910_87,\n                -0.565_300_17,\n            ],\n            vec![\n                -0.597_262_8,\n                0.632_949_4,\n                -0.113_871_31,\n                -0.112_093_67,\n                -0.103_812_83,\n                0.209_886_74,\n                0.210_339_28,\n                0.207_727_49,\n                -0.110_167_1,\n                -0.125_435_67,\n            ],\n            vec![\n                -0.292_568_92,\n                0.100_869_8,\n                0.438_270_96,\n                0.036_628_58,\n                -0.052_523_613,\n                -0.189_247_85,\n                0.261_727,\n                -0.448_417_7,\n                -0.199_650_7,\n                -0.101_448_305,\n            ],\n            vec![\n                -2.346_928_1,\n                0.048_702_62,\n                0.665_279,\n                -0.397_370_37,\n                0.319_130_24,\n                -0.522_832_45,\n                -0.322_557_06,\n                -0.543_567_6,\n                -0.149_809_76,\n                0.490_307_48,\n            ],\n            vec![\n                -0.720_502_44,\n                -0.760_683_5,\n                -0.351_185_62,\n                0.345_522_28,\n                -0.426_943_75,\n                0.661_918_8,\n                0.549_301_8,\n                -0.639_204_26,\n                0.143_307_1,\n                -0.156_587_24,\n            ],\n            vec![\n                -0.139_704_15,\n                -0.131_308_82,\n                -0.543_173_4,\n                0.084_604_315,\n                0.257_846_68,\n                0.065_236_166,\n                0.061_439_02,\n                0.024_350_03,\n                -0.102_217_88,\n                -0.025_649_419,\n            ],\n            vec![\n                -0.323_183_75,\n                0.248_389_05,\n                -0.073_156_14,\n                -0.352_312_33,\n                0.437_357_43,\n                0.139_078_17,\n                0.033_624_098,\n                -0.242_638_07,\n                0.037_701_286,\n                -0.078_643_18,\n            ],\n            vec![\n                -0.542_560_5,\n                -0.480_773_27,\n                -0.276_509_3,\n                -0.396_356_76,\n                -0.420_418_44,\n                -0.085_941_86,\n                0.309_436_44,\n                -0.039_505_947,\n                0.120_491_13,\n                0.613_434_26,\n            ],\n            vec![\n                -0.318_124_32,\n                -0.063_282_974,\n                -0.583_637_7,\n                0.000_650_908_8,\n                0.251_998_1,\n                0.487_572_88,\n                0.294_763_92,\n                -0.502_559_4,\n                0.000_329_407_22,\n                -0.515_829_4,\n            ],\n            vec![\n                -0.654_853_94,\n                0.223_553_2,\n                -0.074_558_02,\n                0.135_706_9,\n                -0.106_060_155,\n                0.582_190_45,\n                -0.645_618_5,\n                -0.815_949_6,\n                -0.367_248_62,\n                0.525_076_2,\n            ],\n            vec![\n                -0.405_058_68,\n                0.018_883_748,\n                0.482_653_83,\n                -0.405_313_67,\n                -0.172_249_38,\n                0.247_358_53,\n                -0.383_800_8,\n                -1.180_208_6,\n                -0.285_524_87,\n                0.199_742_36,\n            ],\n            vec![\n                0.072_124_42,\n                0.089_611_27,\n                -0.648_444_3,\n                -1.149_063_5,\n                0.871_572_9,\n                -0.603_575_7,\n                -0.042_532_567,\n                -0.787_138_94,\n                -1.449_770_2,\n                0.068_524_61,\n            ],\n            vec![\n                -0.217_419_65,\n                -0.849_716_6,\n                -0.416_967_5,\n                0.302_742_72,\n                0.338_067_8,\n                0.029_692_076,\n                -1.289_909_8,\n                0.719_712_14,\n                -0.298_428_7,\n                -0.182_162_28,\n            ],\n            vec![\n                0.505_294_5,\n                0.315_604_78,\n                0.276_869_18,\n                0.805_631_34,\n                -0.602_539_1,\n                -0.478_464_57,\n                -0.269_422_98,\n                -0.784_946_2,\n                -0.468_819_7,\n                -1.085_707_2,\n            ],\n            vec![\n                -0.618_747_9,\n                -0.302_277_77,\n                0.243_801_47,\n                0.056_581_102,\n                0.284_645_62,\n                0.136_963_01,\n                -1.226_688_1,\n                0.336_242_38,\n                -0.480_236_17,\n                -0.364_608_62,\n            ],\n            vec![\n                -2.138_444_4,\n                -1.581_727_5,\n                -1.148_180_4,\n                0.170_667_14,\n                0.835_107_5,\n                -0.155_976_41,\n                0.211_119_86,\n                -1.193_190_1,\n                -2.671_164_3,\n                0.546_684_74,\n            ],\n            vec![\n                0.554_155_05,\n                -0.523_339_7,\n                0.123_114_61,\n                -0.190_302_52,\n                0.401_426_97,\n                -0.999_298_63,\n                -1.785_986_7,\n                -0.028_864_663,\n                0.075_423_63,\n                0.134_472_58,\n            ],\n            vec![\n                -0.999_845_8,\n                -1.265_773_9,\n                0.185_654_45,\n                0.022_434_83,\n                -1.064_128_4,\n                0.605_494_6,\n                -0.609_147_25,\n                0.160_562_52,\n                -0.393_894_2,\n                -1.073_601_5,\n            ],\n            vec![\n                0.589_565_5,\n                -0.083_658_06,\n                -0.233_503_48,\n                0.051_685_516,\n                -0.211_244_93,\n                -0.181_601_88,\n                -1.890_412_8,\n                -0.066_304_71,\n                0.160_530_27,\n                -0.527_078_8,\n            ],\n            vec![\n                -1.982_653_1,\n                -0.369_682_7,\n                -1.941_524_6,\n                1.238_792_3,\n                -0.395_362_47,\n                0.042_821_903,\n                -0.935_377_36,\n                -0.980_699_8,\n                -2.589_027_2,\n                -0.042_432_9,\n            ],\n            vec![\n                -1.365_509,\n                0.537_696_9,\n                -0.111_231_65,\n                0.185_135_45,\n                -0.308_016_84,\n                -0.549_564_96,\n                -0.944_409,\n                0.357_071_43,\n                -0.624_963_94,\n                0.194_620_94,\n            ],\n            vec![\n                -0.426_039_52,\n                0.343_039_57,\n                -0.558_455_35,\n                -0.165_530_98,\n                0.514_893_83,\n                0.328_566_43,\n                -1.802_753_6,\n                0.838_755_55,\n                -0.659_958_24,\n                0.466_113_2,\n            ],\n            vec![\n                0.304_619_76,\n                -0.197_458_82,\n                0.049_138_226,\n                -0.042_370_863,\n                -1.139_023,\n                -0.249_606_34,\n                0.102_472_335,\n                0.178_228_1,\n                0.087_729_655,\n                0.095_381_156,\n            ],\n            vec![\n                -0.000_232_155_61,\n                -1.015_105_8,\n                -1.281_301,\n                1.485_128_3,\n                -1.868_158_5,\n                0.041_754_503,\n                0.610_743_17,\n                -0.685_658_4,\n                0.142_848_21,\n                -0.769_454_1,\n            ],\n            vec![\n                -1.585_783_4,\n                0.190_147_06,\n                -1.414_753_4,\n                0.538_763_4,\n                0.484_258_77,\n                -0.715_786_04,\n                -0.592_829_2,\n                0.496_048_06,\n                -0.829_651,\n                0.413_377_2,\n            ],\n            vec![\n                0.566_932_6,\n                -0.068_602_435,\n                0.267_610_67,\n                0.261_273_3,\n                0.178_361_62,\n                -1.203_597_5,\n                -0.964_891_6,\n                0.010_196_564,\n                -0.457_586_7,\n                0.418_362_9,\n            ],\n            vec![\n                -0.004_002_593_5,\n                0.190_587_67,\n                0.128_683_66,\n                0.157_295_91,\n                -0.403_145_2,\n                -0.076_014_586,\n                -0.078_582_12,\n                -0.206_771_54,\n                0.113_126_98,\n                0.009_636_784,\n            ],\n            vec![\n                0.461_833_72,\n                -0.031_744_67,\n                0.328_814_74,\n                0.616_160_75,\n                -2.074_591_6,\n                0.830_497_9,\n                0.879_883_1,\n                -1.641_873_4,\n                0.203_190_55,\n                -1.673_336_3,\n            ],\n            vec![\n                -1.070_805_5,\n                0.108_797_63,\n                -0.310_216_9,\n                0.107_166_18,\n                0.215_771_24,\n                -0.338_961_36,\n                0.306_101_77,\n                0.367_811_7,\n                -0.262_294_98,\n                0.070_901_744,\n            ],\n            vec![\n                0.427_335_7,\n                0.006_227_863,\n                -0.298_522_56,\n                -0.016_469_207,\n                0.535_206_2,\n                -0.475_492_95,\n                0.123_835_57,\n                0.370_917_1,\n                -0.309_676_53,\n                -0.045_802_142,\n            ],\n            vec![\n                0.086_003_184,\n                -0.269_960_2,\n                0.322_433_23,\n                0.229_070_89,\n                0.097_541_71,\n                0.173_907_13,\n                -0.128_568_14,\n                -0.531_032_86,\n                0.125_477_95,\n                -0.333_153_04,\n            ],\n            vec![\n                -0.719_683_6,\n                0.179_478_72,\n                -0.887_378,\n                0.833_087_8,\n                -0.613_835_93,\n                0.758_620_7,\n                1.292_799_4,\n                -0.829_363_1,\n                -0.098_033_76,\n                -0.475_673_14,\n            ],\n            vec![\n                -1.122_670_9,\n                -0.525_466_6,\n                -0.975_395_2,\n                0.673_286_26,\n                0.065_977_84,\n                -0.214_926_73,\n                -0.724_994_36,\n                0.497_947_07,\n                -0.526_081_3,\n                0.304_432,\n            ],\n            vec![\n                -0.147_321_76,\n                -0.445_857_97,\n                -0.303_215_4,\n                0.430_011_36,\n                -0.002_681_413,\n                -0.563_261,\n                -0.488_504_3,\n                0.215_144_81,\n                0.119_377_89,\n                0.374_618_44,\n            ],\n            vec![\n                -0.031_042_775,\n                0.001_905_601_9,\n                0.375_899_1,\n                0.136_461_18,\n                -0.425_136_74,\n                0.113_508_43,\n                -0.165_993_11,\n                -0.183_742_42,\n                -0.017_969_275,\n                -0.226_747_04,\n            ],\n            vec![\n                -1.277_52,\n                0.530_681_13,\n                -0.608_959_73,\n                -0.105_554_65,\n                0.247_067_32,\n                0.958_920_1,\n                -1.320_192_1,\n                -0.159_428_92,\n                -1.006_717_9,\n                0.172_789_87,\n            ],\n            vec![\n                -1.090_040_2,\n                -0.868_742_4,\n                -1.176_520_7,\n                0.466_612_85,\n                -0.067_542_53,\n                0.456_095_34,\n                -0.771_310_5,\n                0.420_788_8,\n                -0.194_251_57,\n                0.181_740_39,\n            ],\n            vec![\n                -0.280_148_2,\n                0.261_400_22,\n                -0.844_498_6,\n                0.090_790_07,\n                -0.232_529_8,\n                -0.234_734_86,\n                -0.303_635_95,\n                0.205_579_67,\n                0.050_524_14,\n                0.188_166_6,\n            ],\n            vec![\n                0.278_557_15,\n                -0.290_673_97,\n                0.072_780_56,\n                -0.044_078_395,\n                -0.013_295_747,\n                0.023_838_982,\n                0.100_808_12,\n                -0.004_029_975_3,\n                0.087_681_495,\n                -0.250_307_1,\n            ],\n            vec![\n                -2.931_820_2,\n                0.643_360_8,\n                0.109_410_7,\n                -2.668_557,\n                0.839_273_6,\n                -0.091_143_765,\n                -1.141_751_9,\n                -0.111_864_276,\n                -1.236_231_3,\n                0.594_588,\n            ],\n            vec![\n                -1.329_099_8,\n                -0.404_363_07,\n                -0.786_461_3,\n                0.495_720_8,\n                0.523_596_5,\n                0.574_914_6,\n                -0.349_026_74,\n                0.074_060_86,\n                -0.291_518_78,\n                0.065_660_05,\n            ],\n            vec![\n                -0.420_664_07,\n                -0.189_287_14,\n                -0.090_219_02,\n                -0.098_952_18,\n                -0.586_029_95,\n                -0.280_429_72,\n                -0.034_379,\n                0.042_699_914,\n                0.310_710_94,\n                0.195_342_48,\n            ],\n            vec![\n                0.334_666_97,\n                -0.363_745_8,\n                -0.112_467_24,\n                0.109_010_57,\n                -0.239_026_34,\n                0.198_633_1,\n                0.201_740_61,\n                -0.145_083_79,\n                0.266_873_12,\n                -0.337_569,\n            ],\n            vec![\n                -3.973_189_8,\n                0.039_358_37,\n                0.481_752_46,\n                -0.109_007_26,\n                -0.161_161_2,\n                -0.505_807_7,\n                0.562_568,\n                -0.586_035_4,\n                0.455_849,\n                0.309_762_92,\n            ],\n            vec![\n                -1.230_398_8,\n                -0.176_831_8,\n                -0.535_786_6,\n                0.263_067_04,\n                0.242_315_7,\n                0.691_649_7,\n                -0.489_253_16,\n                0.264_390_2,\n                -0.131_665_13,\n                0.031_665_89,\n            ],\n            vec![\n                -0.141_270_65,\n                -0.159_680_43,\n                -0.210_704_6,\n                0.241_845_88,\n                -0.110_234_6,\n                0.023_166_748,\n                0.041_836_73,\n                -0.242_392_54,\n                -0.177_036_39,\n                0.219_812_54,\n            ],\n            vec![\n                0.345_195_98,\n                -0.085_443_124,\n                -0.370_670_35,\n                -0.047_733_57,\n                -0.272_001_9,\n                0.178_620_87,\n                0.240_321_86,\n                -0.216_357_14,\n                0.171_298_64,\n                -0.256_854_74,\n            ],\n            vec![\n                -0.667_514_15,\n                0.622_525_93,\n                0.954_174_04,\n                -0.909_746_17,\n                -0.424_728_42,\n                -1.346_686_4,\n                -2.209_663_4,\n                0.350_954_62,\n                -0.477_263_96,\n                0.115_298_78,\n            ],\n            vec![\n                0.060_172_78,\n                -0.029_796_772,\n                -0.057_546_39,\n                -0.003_541_321_5,\n                -0.026_794_007,\n                0.593_517_7,\n                -0.559_868_8,\n                0.041_287_13,\n                -0.123_922_66,\n                -0.467_462_5,\n            ],\n            vec![\n                -0.411_580_92,\n                0.064_860_13,\n                -0.498_746_1,\n                0.045_083_48,\n                -0.922_313_45,\n                0.362_882_3,\n                0.297_462_37,\n                0.046_287_77,\n                0.075_106_24,\n                0.453_751_1,\n            ],\n            vec![\n                0.100_418_225,\n                0.225_428_66,\n                -0.455_045_07,\n                0.093_468_67,\n                0.071_465_28,\n                -0.029_081_427,\n                0.174_563_81,\n                -0.214_674_04,\n                0.116_524_21,\n                -0.203_626_14,\n            ],\n            vec![\n                -1.225_284,\n                0.685_221_2,\n                -0.462_594_12,\n                -0.456_986_4,\n                -0.884_543_8,\n                -0.459_243_54,\n                -0.738_546,\n                0.063_575_98,\n                0.103_217_766,\n                0.969_997_4,\n            ],\n            vec![\n                -0.639_592_35,\n                0.264_141_44,\n                0.111_988_79,\n                -0.000_706_114_8,\n                0.445_127_3,\n                0.142_151_58,\n                -0.451_865_67,\n                -0.048_067_592,\n                -0.009_025_919,\n                -0.649_651_3,\n            ],\n            vec![\n                -0.619_525_8,\n                -0.363_677_14,\n                -0.403_265_83,\n                -0.067_008_51,\n                0.190_474_76,\n                0.069_310_8,\n                -0.245_115_25,\n                -0.092_971_34,\n                -0.374_226_12,\n                0.427_289_2,\n            ],\n            vec![\n                -0.509_418_8,\n                -0.371_609_36,\n                -0.328_480_66,\n                -0.018_435_072,\n                0.365_649_88,\n                0.175_797_33,\n                -0.477_345_17,\n                -0.215_904_94,\n                0.033_447_467,\n                -0.252_660_96,\n            ],\n            vec![\n                -2.052_151_7,\n                -1.064_796_9,\n                0.051_642_984,\n                -0.304_278_58,\n                0.236_843_05,\n                0.399_494_26,\n                -0.907_562_14,\n                0.199_219_11,\n                -1.396_473_3,\n                0.661_582_3,\n            ],\n            vec![\n                0.880_664_6,\n                -0.540_139_73,\n                0.181_769_37,\n                -0.051_451_266,\n                0.240_898_71,\n                -0.586_332_5,\n                0.075_078_525,\n                -0.629_870_06,\n                0.415_950_15,\n                -1.175_883_3,\n            ],\n            vec![\n                -0.346_670_18,\n                -1.826_483_8,\n                -0.156_105_98,\n                -0.106_954_85,\n                0.030_861_156,\n                0.661_358_24,\n                -1.081_977_8,\n                -0.420_936_08,\n                0.022_964_55,\n                0.151_142_18,\n            ],\n            vec![\n                -0.514_707_57,\n                -0.862_410_37,\n                -0.573_349_2,\n                -0.158_140_11,\n                -0.196_890_74,\n                0.588_682_23,\n                -1.308_61,\n                -1.008_766,\n                0.346_195_6,\n                0.537_148_7,\n            ],\n        ];\n\n        let b: Vec<f32> = vec![\n            -0.058_054_72,\n            0.477_797_06,\n            0.450_016_6,\n            -0.400_980_47,\n            -0.805_899_5,\n            1.038_068_2,\n            -0.427_971_72,\n            0.401_235_6,\n            -0.670_984_9,\n            -0.061_168_972,\n        ];\n        Params {\n            kernels,\n            weights: w,\n            biases: b,\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/mlp_4d_einsum.rs",
        "content": "use ezkl::circuit::region::RegionCtx;\nuse ezkl::circuit::{\n    ops::lookup::LookupOp, ops::poly::PolyOp, BaseConfig as PolyConfig, CheckMode,\n};\nuse ezkl::fieldutils::i32_to_felt;\nuse ezkl::tensor::*;\nuse halo2_proofs::dev::MockProver;\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, Column, ConstraintSystem, Error, Instance},\n};\nuse halo2curves::bn256::Fr as F;\nuse std::marker::PhantomData;\n\nconst K: usize = 15;\n// A columnar ReLu MLP\n#[derive(Clone)]\nstruct MyConfig {\n    layer_config: PolyConfig<F>,\n    public_output: Column<Instance>,\n}\n\n#[derive(Clone)]\nstruct MyCircuit<\n    const LEN: usize, //LEN = CHOUT x OH x OW flattened\n    const LOOKUP_MIN: i128,\n    const LOOKUP_MAX: i128,\n> {\n    // Given the stateless MyConfig type information, a DNN trace is determined by its input and the parameters of its layers.\n    // Computing the trace still requires a forward pass. The intermediate activations are stored only by the layouter.\n    input: ValTensor<F>,\n    l0_params: [Tensor<F>; 2],\n    l2_params: [Tensor<F>; 2],\n    _marker: PhantomData<F>,\n}\n\nimpl<const LEN: usize, const LOOKUP_MIN: i128, const LOOKUP_MAX: i128> Circuit<F>\n    for MyCircuit<LEN, LOOKUP_MIN, LOOKUP_MAX>\n{\n    type Config = MyConfig;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = PhantomData<F>;\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    // Here we wire together the layers by using the output advice in each layer as input advice in the next (not with copying / equality).\n    // This can be automated but we will sometimes want skip connections, etc. so we need the flexibility.\n    fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n        let input = VarTensor::new_advice(cs, K, 1, LEN);\n        let params = VarTensor::new_advice(cs, K, 1, LEN * LEN);\n        let output = VarTensor::new_advice(cs, K, 1, LEN);\n        // tells the config layer to add an affine op to the circuit gate\n\n        let mut layer_config = PolyConfig::<F>::configure(\n            cs,\n            &[input.clone(), params.clone()],\n            &output,\n            CheckMode::SAFE,\n        );\n\n        // sets up a new ReLU table and resuses it for l1 and l3 non linearities\n        layer_config\n            .configure_lookup(\n                cs,\n                &input,\n                &output,\n                &params,\n                (LOOKUP_MIN, LOOKUP_MAX),\n                K,\n                &LookupOp::ReLU,\n            )\n            .unwrap();\n\n        // sets up a new ReLU table and resuses it for l1 and l3 non linearities\n        layer_config\n            .configure_lookup(\n                cs,\n                &input,\n                &output,\n                &params,\n                (LOOKUP_MIN, LOOKUP_MAX),\n                K,\n                &LookupOp::Div {\n                    denom: ezkl::circuit::utils::F32::from(128.),\n                },\n            )\n            .unwrap();\n\n        let public_output: Column<Instance> = cs.instance_column();\n        cs.enable_equality(public_output);\n\n        MyConfig {\n            layer_config,\n            public_output,\n        }\n    }\n\n    fn synthesize(\n        &self,\n        mut config: Self::Config,\n        mut layouter: impl Layouter<F>,\n    ) -> Result<(), Error> {\n        config.layer_config.layout_tables(&mut layouter).unwrap();\n\n        let x = layouter\n            .assign_region(\n                || \"mlp_4d\",\n                |region| {\n                    let mut region = RegionCtx::new(region, 0, 1);\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[\n                                self.l0_params[0].clone().try_into().unwrap(),\n                                self.input.clone(),\n                            ],\n                            Box::new(PolyOp::Einsum {\n                                equation: \"ab,bc->ac\".to_string(),\n                            }),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    println!(\"1\");\n                    println!(\"offset: {}\", region.row());\n                    println!(\"x shape: {:?}\", x.dims());\n\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[x, self.l0_params[1].clone().try_into().unwrap()],\n                            Box::new(PolyOp::Add),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    println!(\"2\");\n                    println!(\"offset: {}\", region.row());\n                    println!(\"x shape: {:?}\", x.dims());\n                    let mut x = config\n                        .layer_config\n                        .layout(&mut region, &[x], Box::new(LookupOp::ReLU))\n                        .unwrap()\n                        .unwrap();\n                    println!(\"3\");\n                    println!(\"offset: {}\", region.row());\n                    println!(\"x shape: {:?}\", x.dims());\n                    x.reshape(&[x.dims()[0], 1]).unwrap();\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[self.l2_params[0].clone().try_into().unwrap(), x],\n                            Box::new(PolyOp::Einsum {\n                                equation: \"ab,bc->ac\".to_string(),\n                            }),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    println!(\"4\");\n                    println!(\"offset: {}\", region.row());\n                    println!(\"x shape: {:?}\", x.dims());\n\n                    let x = config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[x, self.l2_params[1].clone().try_into().unwrap()],\n                            Box::new(PolyOp::Add),\n                        )\n                        .unwrap()\n                        .unwrap();\n                    println!(\"5\");\n                    println!(\"offset: {}\", region.row());\n                    println!(\"x shape: {:?}\", x.dims());\n                    let x = config\n                        .layer_config\n                        .layout(&mut region, &[x], Box::new(LookupOp::ReLU))\n                        .unwrap();\n                    println!(\"6\");\n                    println!(\"offset: {}\", region.row());\n                    Ok(config\n                        .layer_config\n                        .layout(\n                            &mut region,\n                            &[x.unwrap()],\n                            Box::new(LookupOp::Div {\n                                denom: ezkl::circuit::utils::F32::from(128.),\n                            }),\n                        )\n                        .unwrap())\n                },\n            )\n            .unwrap();\n        match x.unwrap() {\n            ValTensor::Value {\n                inner: v, dims: _, ..\n            } => v\n                .enum_map(|i, x| match x {\n                    ValType::PrevAssigned(v) => {\n                        layouter.constrain_instance(v.cell(), config.public_output, i)\n                    }\n                    _ => panic!(),\n                })\n                .unwrap(),\n            _ => panic!(\"Should be assigned\"),\n        };\n        Ok(())\n    }\n}\n\npub fn runmlp() {\n    #[cfg(not(target_arch = \"wasm32\"))]\n    env_logger::init();\n    // parameters\n    let mut l0_kernel: Tensor<F> = Tensor::<i32>::new(\n        Some(&[10, 0, 0, -1, 0, 10, 1, 0, 0, 1, 10, 0, 1, 0, 0, 10]),\n        &[4, 4],\n    )\n    .unwrap()\n    .map(i32_to_felt);\n    l0_kernel.set_visibility(&ezkl::graph::Visibility::Private);\n\n    let mut l0_bias: Tensor<F> = Tensor::<i32>::new(Some(&[0, 0, 0, 1]), &[4, 1])\n        .unwrap()\n        .map(i32_to_felt);\n    l0_bias.set_visibility(&ezkl::graph::Visibility::Private);\n\n    let mut l2_kernel: Tensor<F> = Tensor::<i32>::new(\n        Some(&[0, 3, 10, -1, 0, 10, 1, 0, 0, 1, 0, 12, 1, -2, 32, 0]),\n        &[4, 4],\n    )\n    .unwrap()\n    .map(i32_to_felt);\n    l2_kernel.set_visibility(&ezkl::graph::Visibility::Private);\n    // input data, with 1 padding to allow for bias\n    let input: Tensor<Value<F>> = Tensor::<i32>::new(Some(&[-30, -21, 11, 40]), &[4, 1])\n        .unwrap()\n        .into();\n    let mut l2_bias: Tensor<F> = Tensor::<i32>::new(Some(&[0, 0, 0, 1]), &[4, 1])\n        .unwrap()\n        .map(i32_to_felt);\n    l2_bias.set_visibility(&ezkl::graph::Visibility::Private);\n\n    let circuit = MyCircuit::<4, -8192, 8192> {\n        input: input.into(),\n        l0_params: [l0_kernel, l0_bias],\n        l2_params: [l2_kernel, l2_bias],\n        _marker: PhantomData,\n    };\n\n    let public_input: Vec<i32> = unsafe {\n        vec![\n            (531f32 / 128f32).round().to_int_unchecked::<i32>(),\n            (103f32 / 128f32).round().to_int_unchecked::<i32>(),\n            (4469f32 / 128f32).round().to_int_unchecked::<i32>(),\n            (2849f32 / 128f32).to_int_unchecked::<i32>(),\n        ]\n    };\n\n    println!(\"public input {:?}\", public_input);\n\n    let prover = MockProver::run(\n        K as u32,\n        &circuit,\n        vec![public_input.iter().map(|x| i32_to_felt::<F>(*x)).collect()],\n    )\n    .unwrap();\n    prover.assert_satisfied();\n}\n\npub fn main() {\n    runmlp()\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/data_attest.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# data-attest-ezkl\\n\",\n                \"\\n\",\n                \"Here's an example leveraging EZKL whereby the inputs to the model are read and attested to from an on-chain source.\\n\",\n                \"\\n\",\n                \"In this setup:\\n\",\n                \"- the inputs and outputs are publicly known to the prover and verifier\\n\",\n                \"- the on chain inputs will be fetched and then fed directly into the circuit\\n\",\n                \"- the quantization of the on-chain inputs happens within the evm and is replicated at proving time \\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"logging.basicConfig(format=FORMAT)\\n\",\n                \"logging.getLogger().setLevel(logging.DEBUG)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we define our model. It is a very simple PyTorch model that has just one layer, an average pooling 2D layer. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"        self.layer = nn.AvgPool2d(2, 1, (1, 1))\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        return self.layer(x)[0]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# this is where you'd train your model\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \\n\",\n                \"Now we export the model to onnx and create a corresponding (randomly generated) input. This input data will eventually be stored on chain and read from according to the call_data field in the graph input.\\n\",\n                \"\\n\",\n                \"You can replace the random `x` with real data if you so wish. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = 0.1*torch.rand(1,*[3, 2, 2], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now define a function that will create a new anvil instance which we will deploy our test contract too. This contract will contain in its storage the data that we will read from and attest to. In production you would not need to set up a local anvil instance. Instead you would replace RPC_URL with the actual RPC endpoint of the chain you are deploying your verifiers too, reading from the data on said chain.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import subprocess\\n\",\n                \"import time\\n\",\n                \"import threading\\n\",\n                \"\\n\",\n                \"# make sure anvil is running locally\\n\",\n                \"# $ anvil -p 3030\\n\",\n                \"\\n\",\n                \"RPC_URL = \\\"http://localhost:3030\\\"\\n\",\n                \"\\n\",\n                \"# Save process globally\\n\",\n                \"anvil_process = None\\n\",\n                \"\\n\",\n                \"def start_anvil():\\n\",\n                \"    global anvil_process\\n\",\n                \"    if anvil_process is None:\\n\",\n                \"        anvil_process = subprocess.Popen([\\\"anvil\\\", \\\"-p\\\", \\\"3030\\\", \\\"--code-size-limit=41943040\\\"])\\n\",\n                \"        if anvil_process.returncode is not None:\\n\",\n                \"            raise Exception(\\\"failed to start anvil process\\\")\\n\",\n                \"        time.sleep(3)\\n\",\n                \"\\n\",\n                \"def stop_anvil():\\n\",\n                \"    global anvil_process\\n\",\n                \"    if anvil_process is not None:\\n\",\n                \"        anvil_process.terminate()\\n\",\n                \"        anvil_process = None\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n                \"- `input_visibility` defines the visibility of the model inputs\\n\",\n                \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n                \"- `output_visibility` defines the visibility of the model outputs\\n\",\n                \"\\n\",\n                \"Here we create the following setup:\\n\",\n                \"- `input_visibility`: \\\"public\\\"\\n\",\n                \"- `param_visibility`: \\\"private\\\"\\n\",\n                \"- `output_visibility`: public\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"srs_path = os.path.join('kzg.srs')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"public\\\"\\n\",\n                \"run_args.param_visibility = \\\"private\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.num_inner_cols = 1\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [(0.1*torch.rand(2, *[3, 2, 2])).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('val_data.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"The graph input for on chain data sources is formatted completely differently compared to file based data sources.\\n\",\n                \"\\n\",\n                \"- For file data sources, the raw floating point values that eventually get quantized, converted into field elements and stored in `witness.json` to be consumed by the circuit are stored. The output data contains the expected floating point values returned as outputs from running your vanilla pytorch model on the given inputs.\\n\",\n                \"- For on chain data sources, the input_data field contains all the data necessary to read and format the on chain data into something digestable by EZKL (aka field elements :-D). \\n\",\n                \"Here is what the schema for an on-chain data source graph input file should look like:\\n\",\n                \"    \\n\",\n                \"```json\\n\",\n                \"{\\n\",\n                \"  \\\"input_data\\\": {\\n\",\n                \"    \\\"rpc\\\": \\\"http://localhost:3030\\\", // The rpc endpoint of the chain you are deploying your verifier to\\n\",\n                \"    \\\"calls\\\": [\\n\",\n                \"      {\\n\",\n                \"        \\\"call_data\\\": [\\n\",\n                \"          [\\n\",\n                \"            \\\"71e5ee5f0000000000000000000000000000000000000000000000000000000000000000\\\", // The abi encoded call data to a view function that returns a single on-chain data point (we only support uint256 returns for now)\\n\",\n                \"            7 // The number of decimal places of the large uint256 value. This is our way of representing large wei values as floating points on chain, since the evm only natively supports integer values.\\n\",\n                \"          ],\\n\",\n                \"          [\\n\",\n                \"            \\\"71e5ee5f0000000000000000000000000000000000000000000000000000000000000001\\\",\\n\",\n                \"            5\\n\",\n                \"          ],\\n\",\n                \"          [\\n\",\n                \"            \\\"71e5ee5f0000000000000000000000000000000000000000000000000000000000000002\\\",\\n\",\n                \"            5\\n\",\n                \"          ]\\n\",\n                \"        ],\\n\",\n                \"        \\\"address\\\": \\\"5fbdb2315678afecb367f032d93f642f64180aa3\\\" // The address of the contract that we are calling to get the data. \\n\",\n                \"      }\\n\",\n                \"    ]\\n\",\n                \"  }\\n\",\n                \"}\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.setup_test_evm_witness(\\n\",\n                \"    data_path,\\n\",\n                \"    compiled_model_path,\\n\",\n                \"    # we write the call data to the same file as the input data\\n\",\n                \"    data_path,\\n\",\n                \"    input_source=ezkl.PyTestDataSource.OnChain,\\n\",\n                \"    output_source=ezkl.PyTestDataSource.File,\\n\",\n                \"    rpc_url=RPC_URL)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.get_srs( settings_path)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now need to generate the circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!export RUST_BACKTRACE=1\\n\",\n                \"\\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a full proof. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"And verify it as a sanity check. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We can now create and then deploy a vanilla evm verifier.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier(\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"addr_path_verifier = \\\"addr_verifier.txt\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_evm(\\n\",\n                \"    addr_path_verifier,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    'http://127.0.0.1:3030'\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"With the vanilla verifier deployed, we can now create the data attestation contract, which will read in the instances from the calldata to the verifier, attest to them, call the verifier and then return the result. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"input_path = 'input.json'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_data_attestation(\\n\",\n                \"        input_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we can deploy the data attest verifier contract. For security reasons, this binding will only deploy to a local anvil instance, using accounts generated by anvil. \\n\",\n                \"So should only be used for testing purposes.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"addr_path_da = \\\"addr_da.txt\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_da_evm(\\n\",\n                \"        addr_path_da,\\n\",\n                \"        input_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        RPC_URL,\\n\",\n                \"    )\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Call the view only verify method on the contract to verify the proof. Since it is a view function this is safe to use in production since you don't have to pass your private key.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# read the verifier address\\n\",\n                \"addr_verifier = None\\n\",\n                \"with open(addr_path_verifier, 'r') as f:\\n\",\n                \"    addr = f.read()\\n\",\n                \"#read the data attestation address\\n\",\n                \"addr_da = None\\n\",\n                \"with open(addr_path_da, 'r') as f:\\n\",\n                \"    addr_da = f.read()\\n\",\n                \"\\n\",\n                \"res = ezkl.verify_evm(\\n\",\n                \"    addr,\\n\",\n                \"    proof_path,\\n\",\n                \"    RPC_URL,\\n\",\n                \"    addr_da,\\n\",\n                \")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/data_attest_hashed.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# data-attest-ezkl hashed\\n\",\n                \"\\n\",\n                \"Here's an example leveraging EZKL whereby the hashes of the outputs to the model are read and attested to from an on-chain source.\\n\",\n                \"\\n\",\n                \"In this setup:\\n\",\n                \"- the hashes of outputs are publicly known to the prover and verifier\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.DEBUG)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we define our model. It is a very simple PyTorch model that has just one layer, an average pooling 2D layer. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"        self.layer = nn.AvgPool2d(2, 1, (1, 1))\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        return self.layer(x)[0]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# this is where you'd train your model\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \\n\",\n                \"Now we export the model to onnx and create a corresponding (randomly generated) input. This input data will eventually be stored on chain and read from according to the call_data field in the graph input.\\n\",\n                \"\\n\",\n                \"You can replace the random `x` with real data if you so wish. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = 0.1*torch.rand(1,*[3, 2, 2], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now define a function that will create a new anvil instance which we will deploy our test contract too. This contract will contain in its storage the data that we will read from and attest to. In production you would not need to set up a local anvil instance. Instead you would replace RPC_URL with the actual RPC endpoint of the chain you are deploying your verifiers too, reading from the data on said chain.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import subprocess\\n\",\n                \"import time\\n\",\n                \"import threading\\n\",\n                \"\\n\",\n                \"# make sure anvil is running locally\\n\",\n                \"# $ anvil -p 3030\\n\",\n                \"\\n\",\n                \"RPC_URL = \\\"http://localhost:3030\\\"\\n\",\n                \"\\n\",\n                \"# Save process globally\\n\",\n                \"anvil_process = None\\n\",\n                \"\\n\",\n                \"def start_anvil():\\n\",\n                \"    global anvil_process\\n\",\n                \"    if anvil_process is None:\\n\",\n                \"        anvil_process = subprocess.Popen([\\\"anvil\\\", \\\"-p\\\", \\\"3030\\\", \\\"--code-size-limit=41943040\\\"])\\n\",\n                \"        if anvil_process.returncode is not None:\\n\",\n                \"            raise Exception(\\\"failed to start anvil process\\\")\\n\",\n                \"        time.sleep(3)\\n\",\n                \"\\n\",\n                \"def stop_anvil():\\n\",\n                \"    global anvil_process\\n\",\n                \"    if anvil_process is not None:\\n\",\n                \"        anvil_process.terminate()\\n\",\n                \"        anvil_process = None\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n                \"- `input_visibility` defines the visibility of the model inputs\\n\",\n                \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n                \"- `output_visibility` defines the visibility of the model outputs\\n\",\n                \"\\n\",\n                \"Here we create the following setup:\\n\",\n                \"- `input_visibility`: \\\"private\\\"\\n\",\n                \"- `param_visibility`: \\\"private\\\"\\n\",\n                \"- `output_visibility`: hashed\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"srs_path = os.path.join('kzg.srs')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"private\\\"\\n\",\n                \"run_args.param_visibility = \\\"private\\\"\\n\",\n                \"run_args.output_visibility = \\\"hashed\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [(0.1*torch.rand(2, *[3, 2, 2])).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('val_data.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.get_srs( settings_path)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now need to generate the circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!export RUST_BACKTRACE=1\\n\",\n                \"\\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"print(ezkl.felt_to_big_endian(res['processed_outputs']['poseidon_hash'][0]))\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now post the hashes of the outputs to the chain. This is the data that will be read from and attested to.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"from web3 import Web3, HTTPProvider\\n\",\n                \"from solcx import compile_standard\\n\",\n                \"from decimal import Decimal\\n\",\n                \"import json\\n\",\n                \"import os\\n\",\n                \"import torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# setup web3 instance\\n\",\n                \"w3 = Web3(HTTPProvider(RPC_URL))\\n\",\n                \"\\n\",\n                \"def test_on_chain_data(res):\\n\",\n                \"    # Step 0: Convert the tensor to a flat list\\n\",\n                \"    data = [int(ezkl.felt_to_big_endian(res['processed_outputs']['poseidon_hash'][0]), 0)]\\n\",\n                \"\\n\",\n                \"    # Step 1: Prepare the data\\n\",\n                \"    # Step 2: Prepare and compile the contract.\\n\",\n                \"    # We are using a test contract here but in production you would\\n\",\n                \"    # use whatever contract you are fetching data from.\\n\",\n                \"    contract_source_code = '''\\n\",\n                \"    // SPDX-License-Identifier: UNLICENSED\\n\",\n                \"    pragma solidity ^0.8.17;\\n\",\n                \"\\n\",\n                \"    contract TestReads {\\n\",\n                \"\\n\",\n                \"        uint[] public arr;\\n\",\n                \"        constructor(uint256[] memory _numbers) {\\n\",\n                \"            for(uint256 i = 0; i < _numbers.length; i++) {\\n\",\n                \"                arr.push(_numbers[i]);\\n\",\n                \"            }\\n\",\n                \"        }\\n\",\n                \"    }\\n\",\n                \"    '''\\n\",\n                \"\\n\",\n                \"    compiled_sol = compile_standard({\\n\",\n                \"        \\\"language\\\": \\\"Solidity\\\",\\n\",\n                \"        \\\"sources\\\": {\\\"testreads.sol\\\": {\\\"content\\\": contract_source_code}},\\n\",\n                \"        \\\"settings\\\": {\\\"outputSelection\\\": {\\\"*\\\": {\\\"*\\\": [\\\"metadata\\\", \\\"evm.bytecode\\\", \\\"abi\\\"]}}}\\n\",\n                \"    })\\n\",\n                \"\\n\",\n                \"    # Get bytecode\\n\",\n                \"    bytecode = compiled_sol['contracts']['testreads.sol']['TestReads']['evm']['bytecode']['object']\\n\",\n                \"\\n\",\n                \"    # Get ABI\\n\",\n                \"    # In production if you are reading from really large contracts you can just use\\n\",\n                \"    # a stripped down version of the ABI of the contract you are calling, containing only the view functions you will fetch data from.\\n\",\n                \"    abi = json.loads(compiled_sol['contracts']['testreads.sol']['TestReads']['metadata'])['output']['abi']\\n\",\n                \"\\n\",\n                \"    # Step 3: Deploy the contract\\n\",\n                \"    TestReads = w3.eth.contract(abi=abi, bytecode=bytecode)\\n\",\n                \"    tx_hash = TestReads.constructor(data).transact()\\n\",\n                \"    tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)\\n\",\n                \"    # If you are deploying to production you can skip the 3 lines of code above and just instantiate the contract like this,\\n\",\n                \"    # passing the address and abi of the contract you are fetching data from.\\n\",\n                \"    contract = w3.eth.contract(address=tx_receipt['contractAddress'], abi=abi)\\n\",\n                \"\\n\",\n                \"    # Step 4: Interact with the contract\\n\",\n                \"    calldata = []\\n\",\n                \"    for i, _ in enumerate(data):\\n\",\n                \"        call = contract.functions.arr(i).build_transaction()\\n\",\n                \"        calldata.append((call['data'][2:], 0))\\n\",\n                \"\\n\",\n                \"    # Prepare the calls_to_account object\\n\",\n                \"    # If you were calling view functions across multiple contracts,\\n\",\n                \"    # you would have multiple entries in the calls_to_account array,\\n\",\n                \"    # one for each contract.\\n\",\n                \"    calls_to_account = [{\\n\",\n                \"        'call_data': calldata,\\n\",\n                \"        'address': contract.address[2:], # remove the '0x' prefix\\n\",\n                \"    }]\\n\",\n                \"\\n\",\n                \"    print(f'calls_to_account: {calls_to_account}')\\n\",\n                \"\\n\",\n                \"    return calls_to_account\\n\",\n                \"\\n\",\n                \"# Now let's start the Anvil process. You don't need to do this if you are deploying to a non-local chain.\\n\",\n                \"start_anvil()\\n\",\n                \"\\n\",\n                \"# Now let's call our function, passing in the same input tensor we used to export the model 2 cells above.\\n\",\n                \"calls_to_account = test_on_chain_data(res)\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array], output_data =  {'rpc': RPC_URL, 'calls': calls_to_account })\\n\",\n                \"\\n\",\n                \"# Serialize on-chain data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a full proof. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"And verify it as a sanity check. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We can now create and then deploy a vanilla evm verifier.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier(\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"addr_path_verifier = \\\"addr_verifier.txt\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_evm(\\n\",\n                \"    addr_path_verifier,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    'http://127.0.0.1:3030'\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"With the vanilla verifier deployed, we can now create the data attestation contract, which will read in the instances from the calldata to the verifier, attest to them, call the verifier and then return the result. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"input_path = 'input.json'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_data_attestation(\\n\",\n                \"        input_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we can deploy the data attest verifier contract. For security reasons, this binding will only deploy to a local anvil instance, using accounts generated by anvil. \\n\",\n                \"So should only be used for testing purposes.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"addr_path_da = \\\"addr_da.txt\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_da_evm(\\n\",\n                \"        addr_path_da,\\n\",\n                \"        input_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        RPC_URL,\\n\",\n                \"    )\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Call the view only verify method on the contract to verify the proof. Since it is a view function this is safe to use in production since you don't have to pass your private key.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# read the verifier address\\n\",\n                \"addr_verifier = None\\n\",\n                \"with open(addr_path_verifier, 'r') as f:\\n\",\n                \"    addr = f.read()\\n\",\n                \"#read the data attestation address\\n\",\n                \"addr_da = None\\n\",\n                \"with open(addr_path_da, 'r') as f:\\n\",\n                \"    addr_da = f.read()\\n\",\n                \"\\n\",\n                \"res = ezkl.verify_evm(\\n\",\n                \"    addr,\\n\",\n                \"    proof_path,\\n\",\n                \"    RPC_URL,\\n\",\n                \"    addr_da,\\n\",\n                \")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/decision_tree.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {\n                \"image-2.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAA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uTfozW+Zs6dSpBYtJyqV3whz/8wR577LHULuYqBBAIhABBYiCqiUwiED4Btfrt2rWrrpVI48oefvhhO/PMM11h1f08c+ZMt02cJpk8+OCDNnfuXLfe4qxZs9zizwosH3jgAbcby5e+9CW3tt9tt91mN954Y/jAAlKifv36uXrTTi6vvfaaa92944473JJDaoHUZyVtB6jW3z/96U9uxxfVtdZq1MLeak3WDiwkBBDIrwBBYn79eToCjQponF6YB+QPGjTIVqxYcVz5tabiX/7yF3dMwYa6L3/4wx+aPt90000uSDzttNPcAsoKNjRmTcHm008/bT/72c9cF+itt9563D35IzsC48ePP26JnCeeeMItxK3hAwr2tQfztGnT7MILL3TnaakaBY5eUkuytwbj0KFD7be//a299957NmPGDHfNPffc453KOwII5EmAiSt5guexCDQnoAWCwzwLV0GDt2VeQxYKIDUebfr06TZ58mTr0aOHO23t2rVWVlZmF110kQs+FCCSci+g8YhaLN17qbVXi6Yr8FOAqKSWRLUMNpdeeeUVd4oCxAkTJtjYsWObu4TvEUAgBwIEiTlA5hEIIBAvoEkqak2MTQqKvWOatHDVVVe5fZY3bNhQd9rixYvthhtucAso6/srr7yy7js+5E5g2bJl9ve//73upXUVGwr8Y9cwbNHiX//Kif18zTXXmOpbLcn6XSjwJCGAQP4F/vW/2PznhRwggECEBJYsWWL9+/d3rYResc877zz7xCc+4f4cN26cPfnkk/bMM8+4bde8VseJEyda9+7dTd2bmlHrtTqpZYut2TzJ/Lzv2bPHPXjYsGHufcyYMXVL2GgfaA0P0GLmSqNHj3bv+ofq+qGHHnLjU1XPBIl1NHxAIK8CjEnMKz8PRyC6AtpK7fvf/75dd911dumll7qu9d27d9tdd93lUNSNfO2119o555zjxi56y60o2NBxb79ejX9TUve0Agxdr+9J2RVQd/+5555b95Af//jH9u6777pJJ/LXtn6bN2+2rVu3unNUXy+99JKbaLRlyxY3rtS7+NFHH7Xbb7/dVLdr1qzxDvOOAAJ5Fig4NrbnaJ7zwOMRQKABAbWyaRyeZvQGNSlIaNu2resybq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ECGQEnMTOlIgQIECBAgACBn4CT+LOURIAAAQIECBDICDiJmSkVIUCAAAECBAj8BJzEn6UkAgQIECBAgEBGwEnMTKkIAQIECBAgQOAn4CT+LCURIECAAAECBDICTmJmSkUIECBAgAABAj8BJ/FnKYkAAQIECBAgkBFwEjNTKkKAAAECBAgQ+Ak4iT9LSQQIECBAgACBjICTmJlSEQIECBAgQIDAT8BJ/FlKIkCAAAECBAhkBJzEzJSKECBAgAABAgR+Ak7iz1ISAQIECBAgQCAjMOcXwdcGhnZMAAAAAElFTkSuQmCC\"\n                },\n                \"image.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAUAAAAEbCAYAAACr2V2eAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/PGzLySIb4h7mNFNU/8RBzRWnS9hUvGGvvK4KUPF8yFOeoD9IeQRgEmshAxhRzimEAM41D+2Uk0djIog2MDFlagowiHtlOkcBjkJmKGHBmiiBBL5Cch7t369w2bWrkKJN+AQKWpaYfA2S7FvG9qI0dA7w5wes1VS/25rFAL2stxyedwGuh8dN3XUSC0D9Qrrvtedd36Mfk/ABfmJ+uTZFvl1hD0AAAAVmVYSWZNTQAqAAAACAABh2kABAAAAAEAAAAaAAAAAAADkoYABwAAABIAAABEoAIABAAAAAEAAAFAoAMABAAAAAEAAAEbAAAAAEFTQ0lJAAAAU2NyZWVuc2hvdP5iyG4AAAHWaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGE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4/p96QMswsPB1BXtDK2aoJp15WzaFVGk1CXJfk+GpswkwUiTstX1IBFMyztBkrI1dU52oEAIYJFOlAjqo5pgvj7BIrN2JpkET6PEaqomGSQ4GqxQf2DUQZFyl6dStpa73L7nhwCW+AQEtcESsyF5iQQ0IKLaIAECcQjQBxiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgE/gcCHHjHKxBaJwAAAABJRU5ErkJggg==\"\n                }\n            },\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Decision Tree\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image.png](attachment:image.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image-2.png](attachment:image-2.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `hummingbird-ml` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from sklearn.tree import DecisionTreeClassifier as De\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = De()\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"circuit = convert(clr, \\\"torch\\\", X_test[:1]).model\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=True)\\n\",\n                \"torch_out = circuit(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [(torch.rand(20, *shape)).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('val_data.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/ezkl_demo.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"n8QlFzjPRIGN\"\n      },\n      \"source\": [\n        \"# EZKL DEMO\\n\",\n        \"\\n\",\n        \"**Learning Objectives**\\n\",\n        \"1. Learn some basic AI/ML techniques by training a toy model in pytorch to perform classification\\n\",\n        \"2. Convert the toy model into zk circuit with ezkl to do provable inference\\n\",\n        \"3. Create a solidity verifier and deploy it on Remix (you can deploy it however you like but we will use Remix as it's quite easy to setup)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"**Important Note**: You might want to avoid calling \\\"Run All\\\". There's some file locking issue with Colab which can cause weird bugs. To mitigate this issue you should run cell by cell on Colab.\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"dx81GOIySIpa\"\n      },\n      \"source\": [\n        \"# Step 1: Training a toy model\\n\",\n        \"\\n\",\n        \"For this demo we will use a toy data set called the Iris dataset to demonstrate how training can be performed. The Iris dataset is a collection of Iris flowers and is one of the earliest dataset used to validate classification methodologies.\\n\",\n        \"\\n\",\n        \"[More info in the dataset](https://archive.ics.uci.edu/dataset/53/iris)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"JhHE2WMvS9NP\"\n      },\n      \"source\": [\n        \"First, we will need to import all the various dependencies required to train the model\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"gvQ5HL1bTDWF\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import pandas as pd\\n\",\n        \"from sklearn.datasets import load_iris\\n\",\n        \"from sklearn.model_selection import train_test_split\\n\",\n        \"from sklearn.metrics import accuracy_score, precision_score, recall_score\\n\",\n        \"import numpy as np\\n\",\n        \"import torch\\n\",\n        \"import torch.nn as nn\\n\",\n        \"import torch.nn.functional as F\\n\",\n        \"from torch.autograd import Variable\\n\",\n        \"import tqdm\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"Op9SHfZHUkaR\"\n      },\n      \"source\": [\n        \"Inspect the dataset. Note that for the Iris dataset we have 3 targets.\\n\",\n        \"\\n\",\n        \"0 = Iris-setosa\\n\",\n        \"\\n\",\n        \"1 = Iris-versicolor\\n\",\n        \"\\n\",\n        \"2 = Iris-virginica\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 424\n        },\n        \"id\": \"C4XXA1hoU30c\",\n        \"outputId\": \"4fbd47ec-88d1-4ef7-baee-3e3894cc29db\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"iris = load_iris()\\n\",\n        \"dataset = pd.DataFrame(\\n\",\n        \"    data= np.c_[iris['data'], iris['target']],\\n\",\n        \"    columns= iris['feature_names'] + ['target'])\\n\",\n        \"dataset\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"I8RargmGTWN2\"\n      },\n      \"source\": [\n        \"Next, we can begin defining the neural net model. For this dataset we will use a small fully connected neural net.\\n\",\n        \"\\n\",\n        \"<br />\\n\",\n        \"\\n\",\n        \"**Note:**\\n\",\n        \"For the 1st layer we use 4x20, because there are 4 features we want as inputs. After which we add a ReLU.\\n\",\n        \"\\n\",\n        \"For the 2nd layer we use 20x20, then add a ReLU.\\n\",\n        \"\\n\",\n        \"And for the last layer we use 20x3, because there are 3 classes we want to classify, then add a ReLU.\\n\",\n        \"\\n\",\n        \"The last ReLU function gives us an array of 3 elements where the position of the largest value gives us the target that we want to classify.\\n\",\n        \"\\n\",\n        \"For example, if we get [0, 0.001, 0.002] as the output of the last ReLU. As, 0.002 is the largest value, the inferred value is 2.\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcMAAAENCAIAAAD8BplNAAAMPWlDQ1BJQ0MgUHJvZmlsZQAASImVVwdYU8kWnltSIbQAAlJCb4J0AkgJoQWQXgQbIQkQSoyBoGJHFxVcu1jAhq6KKHZA7IidRbD3xYKAsi4W7MqbFNB1X/ne+b6597//nPnPmXPnlgFA/RRXLM5FNQDIExVI4kIDGWNSUhmkLkAEZIAAe6DD5eWLWTExkQDa4Pnv9u4m9IR2zUGm9c/+/2qafEE+DwAkBuJ0fj4vD+JDAOCVPLGkAACijDefUiCWYdiAtgQmCPFCGc5U4EoZTlfgfXKfhDg2xM0Ak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uyy5ex5YSHr3PtPbPSNppmdwD+Om0cM4kAWmijxUKz6shLbST1tJ8yCPLz9tiWDrggHWLXPRywPX64GFpNfrz6Xtih4AkQOCADQtiMlPt3oTAJExQW2Sw9kKL3p54AV4YCHpC3DyGuLZHgCF4eAeStYTs+KSWAWAwl9QOxD87GGWxPLAzXjg/wCrWlHADFCeBgAAAABJRU5ErkJggg==)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"dIdQ9U3yTKtP\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"class Model(nn.Module):\\n\",\n        \"    # define nn\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(Model, self).__init__()\\n\",\n        \"        self.fc1 = nn.Linear(4, 20)\\n\",\n        \"        self.fc2 = nn.Linear(20, 20)\\n\",\n        \"        self.fc3 = nn.Linear(20, 3)\\n\",\n        \"        self.relu = nn.ReLU()\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        x = self.fc1(x)\\n\",\n        \"        x = self.relu(x)\\n\",\n        \"        x = self.fc2(x)\\n\",\n        \"        x = self.relu(x)\\n\",\n        \"        x = self.fc3(x)\\n\",\n        \"        x = self.relu(x)\\n\",\n        \"\\n\",\n        \"        return x\\n\",\n        \"\\n\",\n        \"# Initialize Model\\n\",\n        \"model = Model()\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"SfC03XLNXDPZ\"\n      },\n      \"source\": [\n        \"We will now need to split the dataset into a training set and testing set for ML. This is done fairly easily with the `train_test_split` helper function from sklearn.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"agmbEdmfUO1-\",\n        \"outputId\": \"87766edd-50db-48af-aa5d-3f4fc164f8b7\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"train_X, test_X, train_y, test_y = train_test_split(\\n\",\n        \"    dataset[dataset.columns[0:4]].values, # use columns 0-4 as X\\n\",\n        \"    dataset.target, # use target as y\\n\",\n        \"    test_size=0.2 # use 20% of data for testing\\n\",\n        \")\\n\",\n        \"\\n\",\n        \"# Uncomment for sanity checks\\n\",\n        \"# print(\\\"train_X: \\\", train_X)\\n\",\n        \"# print(\\\"test_X: \\\", test_X)\\n\",\n        \"print(\\\"train_y: \\\", train_y)\\n\",\n        \"print(\\\"test_y: \\\", test_y)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"_FrQXhAGZGS3\"\n      },\n      \"source\": [\n        \"We can now define the parameters for training, we will use the [Cross Entropy Loss](https://machinelearningmastery.com/cross-entropy-for-machine-learning/) and [Stochastic Gradient Descent Optimizer](https://en.wikipedia.org/wiki/Stochastic_gradient_descent).\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"9PjADXnuXbdk\",\n        \"outputId\": \"81602926-c386-4f68-a9ee-ae2d5837fe47\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# our loss function\\n\",\n        \"loss_fn = nn.CrossEntropyLoss()\\n\",\n        \"\\n\",\n        \"# our optimizer\\n\",\n        \"optimizer = torch.optim.SGD(model.parameters(), lr=0.01)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# use 800 EPOCHS\\n\",\n        \"EPOCHS = 800\\n\",\n        \"\\n\",\n        \"# Convert training data to pytorch variables\\n\",\n        \"train_X = Variable(torch.Tensor(train_X).float())\\n\",\n        \"test_X = Variable(torch.Tensor(test_X).float())\\n\",\n        \"train_y = Variable(torch.Tensor(train_y.values).long())\\n\",\n        \"test_y = Variable(torch.Tensor(test_y.values).long())\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"loss_list     = np.zeros((EPOCHS,))\\n\",\n        \"accuracy_list = np.zeros((EPOCHS,))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# we use tqdm for nice loading bars\\n\",\n        \"for epoch in tqdm.trange(EPOCHS):\\n\",\n        \"\\n\",\n        \"    # To train, we get a prediction from the current network\\n\",\n        \"    predicted_y = model(train_X)\\n\",\n        \"\\n\",\n        \"    # Compute the loss to see how bad or good we are doing\\n\",\n        \"    loss = loss_fn(predicted_y, train_y)\\n\",\n        \"\\n\",\n        \"    # Append the loss to keep track of our performance\\n\",\n        \"    loss_list[epoch] = loss.item()\\n\",\n        \"\\n\",\n        \"    # Afterwards, we will need to zero the gradients to reset\\n\",\n        \"    optimizer.zero_grad()\\n\",\n        \"    loss.backward()\\n\",\n        \"    optimizer.step()\\n\",\n        \"\\n\",\n        \"    # Calculate the accuracy, call torch.no_grad() to prevent updating gradients\\n\",\n        \"    # while calculating accuracy\\n\",\n        \"    with torch.no_grad():\\n\",\n        \"        y_pred = model(test_X)\\n\",\n        \"        correct = (torch.argmax(y_pred, dim=1) == test_y).type(torch.FloatTensor)\\n\",\n        \"        accuracy_list[epoch] = correct.mean()\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 546\n        },\n        \"id\": \"2fHJAgvwboCe\",\n        \"outputId\": \"513c73b7-2663-4bb3-f7b4-cae208940070\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Plot the Accuracy and Loss\\n\",\n        \"\\n\",\n        \"# import matplotlib\\n\",\n        \"import matplotlib.pyplot as plt\\n\",\n        \"\\n\",\n        \"plt.style.use('ggplot')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"fig, (ax1, ax2) = plt.subplots(2, figsize=(12, 6), sharex=True)\\n\",\n        \"\\n\",\n        \"ax1.plot(accuracy_list)\\n\",\n        \"ax1.set_ylabel(\\\"Accuracy\\\")\\n\",\n        \"ax2.plot(loss_list)\\n\",\n        \"ax2.set_ylabel(\\\"Loss\\\")\\n\",\n        \"ax2.set_xlabel(\\\"epochs\\\");\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"djB-UtvgYbF2\"\n      },\n      \"source\": [\n        \"## Congratulations! You've just trained a neural network\\n\",\n        \"\\n\",\n        \"**Exercise:** The model provided is very simplistic, what are other ways the model can be improved upon?\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"JgtwrbMZcgla\"\n      },\n      \"source\": [\n        \"# Step 2: ZK the Neural Network\\n\",\n        \"\\n\",\n        \"Now that we have the Neural Network trained, we can use ezkl to easily ZK our model.\\n\",\n        \"\\n\",\n        \"To proceed we will now need to install `ezkl`\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"C_YiqknhdDwN\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"import os\\n\",\n        \"import json\\n\",\n        \"import ezkl\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"-b_z_d2FdVTB\"\n      },\n      \"source\": [\n        \"Next, we will need to export the neural network to a `.onnx` file. ezkl reads this `.onnx` file and converts it into a circuit which then allows you to generate proofs as well as verify proofs\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"YeKWP0tFeCpq\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Specify all the files we need\\n\",\n        \"\\n\",\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.ezkl')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\\n\",\n        \"cal_data_path = os.path.join('cal_data.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"cQeNw_qndQ8g\",\n        \"outputId\": \"2d40f14e-7fbb-4377-e9ee-0e7678edb2ce\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n        \"\\n\",\n        \"# create a random input\\n\",\n        \"x = test_X[0].reshape(1, 4)\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"model.eval()\\n\",\n        \"\\n\",\n        \"# Export the model\\n\",\n        \"torch.onnx.export(model,                     # model being run\\n\",\n        \"                  x,                         # model input (or a tuple for multiple inputs)\\n\",\n        \"                  model_path,                # where to save the model (can be a file or file-like object)\\n\",\n        \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n        \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                  input_names = ['input'],   # the model's input names\\n\",\n        \"                  output_names = ['output'], # the model's output names\\n\",\n        \"                  dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array])\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump(data, open(data_path, 'w'))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"9P4x79hIeiLO\"\n      },\n      \"source\": [\n        \"After which we can proceed to generate the settings file for `ezkl` and run calibrate settings to find the optimal settings for `ezkl`\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"cY25BIyreIX8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"!RUST_LOG=trace\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n        \"assert res == True\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# use the test set to calibrate the circuit\\n\",\n        \"cal_data = dict(input_data = test_X.flatten().tolist())\\n\",\n        \"\\n\",\n        \"# Serialize calibration data into file:\\n\",\n        \"json.dump(data, open(cal_data_path, 'w'))\\n\",\n        \"\\n\",\n        \"# Optimize for resources, we cap logrows at 12 to reduce setup and proving time, at the expense of accuracy\\n\",\n        \"# You may want to increase the max logrows if accuracy is a concern\\n\",\n        \"res = ezkl.calibrate_settings(cal_data_path, model_path, settings_path, \\\"resources\\\", max_logrows = 12, scales = [2])\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"MFmPMBQ1jYao\"\n      },\n      \"source\": [\n        \"Next, we will compile the model. The compilation step allow us to generate proofs faster.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"De5XtpGUerkZ\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"UbkuSVKljmhA\"\n      },\n      \"source\": [\n        \"Before we can setup the circuit params, we need a SRS (Structured Reference String). The SRS is used to generate the proofs.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"amaTcWG6f2GI\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"Y92p3GhVj1Jd\"\n      },\n      \"source\": [\n        \"Now run setup, this will generate a proving key (pk) and verification key (vk). The proving key is used for proving while the verification key is used for verificaton.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"fdsteit9jzfK\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"QYlqpP3jkExm\"\n      },\n      \"source\": [\n        \"Now, we can generate a proof and verify the proof as a sanity check. We will use the \\\"evm\\\" transcript. This will allow us to provide proofs to the EVM.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"yoz5Vks5kaHI\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Generate the Witness for the proof\\n\",\n        \"\\n\",\n        \"# now generate the witness file\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"eKkFBZX1kBdE\",\n        \"outputId\": \"48c67e19-a491-4515-f09c-a560df8c3834\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Generate the proof\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('proof.json')\\n\",\n        \"\\n\",\n        \"proof = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(proof)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"DuuH-qcOkQf1\",\n        \"outputId\": \"375fdd63-1c0b-4c3c-eddd-f890a752923c\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# verify our proof\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"TOSRigalkwH-\"\n      },\n      \"source\": [\n        \"## Congratulations! You have just turned your Neural Network into a Halo2 Circuit!\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"flrg3NOGwsJh\"\n      },\n      \"source\": [\n        \"\\n\",\n        \"# Part 3: Deploying the Verifier\\n\",\n        \"Now that we have the circuit setup, we can proceed to deploy the verifier onchain.\\n\",\n        \"\\n\",\n        \"We will need to setup `solc=0.8.20` for this.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"CVqMeMYqktvl\",\n        \"outputId\": \"60ef81a5-867e-4a27-a0a1-0a492244e7f7\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"solc-select\\\"])\\n\",\n        \"    !solc-select install 0.8.20\\n\",\n        \"    !solc-select use 0.8.20\\n\",\n        \"    !solc --version\\n\",\n        \"\\n\",\n        \"# rely on local installation if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"HRHvkMjVlfWU\"\n      },\n      \"source\": [\n        \"With solc in our environment we can now create the evm verifier.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"gYlw20VZkva7\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"sol_code_path = os.path.join('Verifier.sol')\\n\",\n        \"abi_path = os.path.join('Verifier.abi')\\n\",\n        \"\\n\",\n        \"res = ezkl.create_evm_verifier(\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"        settings_path,\\n\",\n        \"        sol_code_path,\\n\",\n        \"        abi_path\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(sol_code_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"jQSAVMvxrBQD\",\n        \"outputId\": \"691484fa-ef21-4b40-e179-9d2d90abd3d0\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"onchain_input_array = []\\n\",\n        \"\\n\",\n        \"# using a loop\\n\",\n        \"# avoiding printing last comma\\n\",\n        \"formatted_output = \\\"[\\\"\\n\",\n        \"for i, value in enumerate(proof[\\\"instances\\\"]):\\n\",\n        \"    for j, field_element in enumerate(value):\\n\",\n        \"        onchain_input_array.append(ezkl.felt_to_big_endian(field_element))\\n\",\n        \"        formatted_output += '\\\"' + str(onchain_input_array[-1]) + '\\\"'\\n\",\n        \"        if j != len(value) - 1:\\n\",\n        \"            formatted_output += \\\", \\\"\\n\",\n        \"    if i != len(proof[\\\"instances\\\"]) - 1:\\n\",\n        \"        formatted_output += \\\", \\\"\\n\",\n        \"formatted_output += \\\"]\\\"\\n\",\n        \"\\n\",\n        \"# This will be the values you use onchain\\n\",\n        \"# copy them over to remix and see if they verify\\n\",\n        \"# What happens when you change a value?\\n\",\n        \"print(\\\"pubInputs: \\\", formatted_output)\\n\",\n        \"print(\\\"proof: \\\", proof[\\\"proof\\\"])\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"zrzPxPvZmX9b\"\n      },\n      \"source\": [\n        \"We will exit colab for the next steps. At the left of colab you can see a folder icon. Click on that.\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"You should see a `Verifier.sol`. Right-click and save it locally.\\n\",\n        \"\\n\",\n        \"Now go to [https://remix.ethereum.org](https://remix.ethereum.org).\\n\",\n        \"\\n\",\n        \"Create a new file within remix and copy the verifier code over.\\n\",\n        \"\\n\",\n        \"Finally, compile the code and deploy. For the demo you can deploy to the test environment within remix.\\n\",\n        \"\\n\",\n        \"If everything works, you would have deployed your verifer onchain! Copy the values in the cell above to the respective fields to test if the verifier is working.\\n\",\n        \"\\n\",\n        \"**Note that right now this setup accepts random values!**\\n\",\n        \"\\n\",\n        \"This might not be great for some applications. For that we will want to use a data attested verifier instead. [See this tutorial.](https://github.com/zkonduit/ezkl/blob/main/examples/notebooks/data_attest.ipynb)\\n\",\n        \"\\n\",\n        \"## Congratulations for making it this far!\\n\",\n        \"\\n\",\n        \"If you have followed the whole tutorial, you would have deployed a neural network inference model onchain! That's no mean feat!\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/gcn.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"5fe9feb6-2b35-414a-be9d-771eabdbb0dc\",\n      \"metadata\": {\n        \"id\": \"5fe9feb6-2b35-414a-be9d-771eabdbb0dc\"\n      },\n      \"source\": [\n        \"## EZKL GCN Notebook\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"nGcl_1sltpRq\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"nGcl_1sltpRq\",\n        \"outputId\": \"642693ac-970f-4ad9-80f5-e58c69f04ee9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"!pip install torch-scatter torch-sparse torch-geometric\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"1005303a-cd48-4766-9c43-2116f94ed381\",\n      \"metadata\": {\n        \"id\": \"1005303a-cd48-4766-9c43-2116f94ed381\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import numpy as np\\n\",\n        \"\\n\",\n        \"import torch\\n\",\n        \"from torch import nn\\n\",\n        \"import torch.nn.functional as F\\n\",\n        \"\\n\",\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    for e in [\\\"ezkl\\\", \\\"onnx\\\", \\\"torch\\\", \\\"torchvision\\\", \\\"torch-scatter\\\", \\\"torch-sparse\\\", \\\"torch-geometric\\\"]:\\n\",\n        \"        subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", e])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"89e5732e-a97b-445e-9174-69689e37e72c\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"89e5732e-a97b-445e-9174-69689e37e72c\",\n        \"outputId\": \"24049b0a-439b-4327-a829-4b4045490f0f\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import torch\\n\",\n        \"from torch_geometric.data import Data\\n\",\n        \"\\n\",\n        \"edge_index = torch.tensor([[2, 1, 3],\\n\",\n        \"                           [0, 0, 2]], dtype=torch.long)\\n\",\n        \"x = torch.tensor([[1], [1], [1]], dtype=torch.float)\\n\",\n        \"\\n\",\n        \"data = Data(x=x, edge_index=edge_index)\\n\",\n        \"data\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"73b34e81-63cb-44b0-9f95-f8490e844676\",\n      \"metadata\": {\n        \"id\": \"73b34e81-63cb-44b0-9f95-f8490e844676\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import torch\\n\",\n        \"import math\\n\",\n        \"from torch_geometric.nn import MessagePassing\\n\",\n        \"from torch.nn.modules.module import Module\\n\",\n        \"\\n\",\n        \"def glorot(tensor):\\n\",\n        \"    if tensor is not None:\\n\",\n        \"        stdv = math.sqrt(6.0 / (tensor.size(-2) + tensor.size(-1)))\\n\",\n        \"        tensor.data.uniform_(-stdv, stdv)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def zeros(tensor):\\n\",\n        \"    if tensor is not None:\\n\",\n        \"        tensor.data.fill_(0)\\n\",\n        \"\\n\",\n        \"class GCNConv(Module):\\n\",\n        \"    def __init__(self, in_channels, out_channels):\\n\",\n        \"        super(GCNConv, self).__init__()  # \\\"Add\\\" aggregation.\\n\",\n        \"        self.lin = torch.nn.Linear(in_channels, out_channels)\\n\",\n        \"\\n\",\n        \"        self.reset_parameters()\\n\",\n        \"\\n\",\n        \"    def reset_parameters(self):\\n\",\n        \"        glorot(self.lin.weight)\\n\",\n        \"        zeros(self.lin.bias)\\n\",\n        \"\\n\",\n        \"    def forward(self, x, adj_t, deg):\\n\",\n        \"        x = self.lin(x)\\n\",\n        \"        adj_t = self.normalize_adj(adj_t, deg)\\n\",\n        \"        x = adj_t @ x\\n\",\n        \"\\n\",\n        \"        return x\\n\",\n        \"\\n\",\n        \"    def normalize_adj(self, adj_t, deg):\\n\",\n        \"        deg.masked_fill_(deg == 0, 1.)\\n\",\n        \"        deg_inv_sqrt = deg.pow_(-0.5)\\n\",\n        \"        deg_inv_sqrt.masked_fill_(deg_inv_sqrt == 1, 0.)\\n\",\n        \"        adj_t = adj_t *  deg_inv_sqrt.view(-1, 1) # N, 1\\n\",\n        \"        adj_t = adj_t *  deg_inv_sqrt.view(1, -1) # 1, N\\n\",\n        \"\\n\",\n        \"        return adj_t\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"ae70bc34-def7-40fd-9558-2500c6f29323\",\n      \"metadata\": {\n        \"id\": \"ae70bc34-def7-40fd-9558-2500c6f29323\"\n      },\n      \"source\": [\n        \"## Train Pipeline\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"7ca117a1-7473-42a6-be95-dc314eb3e251\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"7ca117a1-7473-42a6-be95-dc314eb3e251\",\n        \"outputId\": \"edacee52-8a88-4c02-9a71-fd094e89c7b9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import os\\n\",\n        \"import os.path as osp\\n\",\n        \"import torch\\n\",\n        \"import torch.nn.functional as F\\n\",\n        \"from torch_geometric.datasets import Planetoid\\n\",\n        \"import torch_geometric.transforms as T\\n\",\n        \"\\n\",\n        \"path = osp.join(os.getcwd(), 'data', 'Cora')\\n\",\n        \"dataset = Planetoid(path, 'Cora')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"807f4d87-6acc-4cbb-80e4-8eb09feb994c\",\n      \"metadata\": {\n        \"id\": \"807f4d87-6acc-4cbb-80e4-8eb09feb994c\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import time\\n\",\n        \"\\n\",\n        \"from torch import tensor\\n\",\n        \"from torch.optim import Adam\\n\",\n        \"\\n\",\n        \"# define num feat to use for training here\\n\",\n        \"num_feat = 10\\n\",\n        \"\\n\",\n        \"def run(dataset, model, runs, epochs, lr, weight_decay, early_stopping):\\n\",\n        \"\\n\",\n        \"    val_losses, accs, durations = [], [], []\\n\",\n        \"    for _ in range(runs):\\n\",\n        \"        data = dataset[0]\\n\",\n        \"        data = data.to(device)\\n\",\n        \"\\n\",\n        \"        model.to(device).reset_parameters()\\n\",\n        \"        optimizer = Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\\n\",\n        \"\\n\",\n        \"        if torch.cuda.is_available():\\n\",\n        \"            torch.cuda.synchronize()\\n\",\n        \"\\n\",\n        \"        t_start = time.perf_counter()\\n\",\n        \"\\n\",\n        \"        best_val_loss = float('inf')\\n\",\n        \"        test_acc = 0\\n\",\n        \"        val_loss_history = []\\n\",\n        \"\\n\",\n        \"        for epoch in range(1, epochs + 1):\\n\",\n        \"            train(model, optimizer, data)\\n\",\n        \"            eval_info = evaluate(model, data)\\n\",\n        \"            eval_info['epoch'] = epoch\\n\",\n        \"\\n\",\n        \"            if eval_info['val_loss'] < best_val_loss:\\n\",\n        \"                best_val_loss = eval_info['val_loss']\\n\",\n        \"                test_acc = eval_info['test_acc']\\n\",\n        \"\\n\",\n        \"            val_loss_history.append(eval_info['val_loss'])\\n\",\n        \"            if early_stopping > 0 and epoch > epochs // 2:\\n\",\n        \"                tmp = tensor(val_loss_history[-(early_stopping + 1):-1])\\n\",\n        \"                if eval_info['val_loss'] > tmp.mean().item():\\n\",\n        \"                    break\\n\",\n        \"\\n\",\n        \"        if torch.cuda.is_available():\\n\",\n        \"            torch.cuda.synchronize()\\n\",\n        \"\\n\",\n        \"        t_end = time.perf_counter()\\n\",\n        \"\\n\",\n        \"        val_losses.append(best_val_loss)\\n\",\n        \"        accs.append(test_acc)\\n\",\n        \"        durations.append(t_end - t_start)\\n\",\n        \"\\n\",\n        \"    loss, acc, duration = tensor(val_losses), tensor(accs), tensor(durations)\\n\",\n        \"\\n\",\n        \"    print('Val Loss: {:.4f}, Test Accuracy: {:.3f} \u00b1 {:.3f}, Duration: {:.3f}'.\\n\",\n        \"          format(loss.mean().item(),\\n\",\n        \"                 acc.mean().item(),\\n\",\n        \"                 acc.std().item(),\\n\",\n        \"                 duration.mean().item()))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def train(model, optimizer, data):\\n\",\n        \"    model.train()\\n\",\n        \"    optimizer.zero_grad()\\n\",\n        \"\\n\",\n        \"    E = data.edge_index.size(1)\\n\",\n        \"    N = data.x.size(0)\\n\",\n        \"    x = data.x[:, :num_feat]\\n\",\n        \"    adj_t = torch.sparse_coo_tensor(data.edge_index, torch.ones(E), size=(N, N)).to_dense().T\\n\",\n        \"    deg = torch.sum(adj_t, dim=1)\\n\",\n        \"    out = model(x, adj_t, deg)\\n\",\n        \"    loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])\\n\",\n        \"    loss.backward()\\n\",\n        \"    optimizer.step()\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def evaluate(model, data):\\n\",\n        \"    model.eval()\\n\",\n        \"\\n\",\n        \"    with torch.no_grad():\\n\",\n        \"\\n\",\n        \"        E = data.edge_index.size(1)\\n\",\n        \"        N = data.x.size(0)\\n\",\n        \"        x = data.x[:, :num_feat]\\n\",\n        \"        adj_t = torch.sparse_coo_tensor(data.edge_index, torch.ones(E), size=(N, N)).to_dense().T\\n\",\n        \"        deg = torch.sum(adj_t, dim=1)\\n\",\n        \"        logits = model(x, adj_t, deg)\\n\",\n        \"\\n\",\n        \"    outs = {}\\n\",\n        \"    for key in ['train', 'val', 'test']:\\n\",\n        \"        mask = data['{}_mask'.format(key)]\\n\",\n        \"        loss = F.nll_loss(logits[mask], data.y[mask]).item()\\n\",\n        \"        pred = logits[mask].max(1)[1]\\n\",\n        \"        acc = pred.eq(data.y[mask]).sum().item() / mask.sum().item()\\n\",\n        \"\\n\",\n        \"        outs['{}_loss'.format(key)] = loss\\n\",\n        \"        outs['{}_acc'.format(key)] = acc\\n\",\n        \"\\n\",\n        \"    return outs\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"28b3605e-e6fd-45ff-ae4b-607065f4849c\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"28b3605e-e6fd-45ff-ae4b-607065f4849c\",\n        \"outputId\": \"b3ea504c-b57c-46d4-b382-aa54c9a4786f\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"runs = 1\\n\",\n        \"epochs = 200\\n\",\n        \"lr = 0.01\\n\",\n        \"weight_decay = 0.0005\\n\",\n        \"early_stopping = 10\\n\",\n        \"hidden = 16\\n\",\n        \"dropout = 0.5\\n\",\n        \"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class Net(torch.nn.Module):\\n\",\n        \"    def __init__(self, dataset, num_feat):\\n\",\n        \"        super(Net, self).__init__()\\n\",\n        \"        # self.conv1 = GCNConv(dataset.num_features, hidden)\\n\",\n        \"        self.conv1 = GCNConv(num_feat, hidden)\\n\",\n        \"        self.conv2 = GCNConv(hidden, dataset.num_classes)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    def reset_parameters(self):\\n\",\n        \"        self.conv1.reset_parameters()\\n\",\n        \"        self.conv2.reset_parameters()\\n\",\n        \"\\n\",\n        \"    def forward(self, x, adj_t, deg):\\n\",\n        \"        x = F.relu(self.conv1(x, adj_t, deg))\\n\",\n        \"        x = F.dropout(x, p=dropout, training=self.training)\\n\",\n        \"        x = self.conv2(x, adj_t, deg)\\n\",\n        \"        return F.log_softmax(x, dim=1)\\n\",\n        \"\\n\",\n        \"model = Net(dataset, num_feat)\\n\",\n        \"run(dataset, model, runs, epochs, lr, weight_decay, early_stopping)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"4cc3ffed-74c2-48e3-86bc-a5e51f44a09a\",\n      \"metadata\": {\n        \"id\": \"4cc3ffed-74c2-48e3-86bc-a5e51f44a09a\"\n      },\n      \"source\": [\n        \"## EZKL Setup\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"92585631-ff39-402e-bd1c-aaebdce682e5\",\n      \"metadata\": {\n        \"id\": \"92585631-ff39-402e-bd1c-aaebdce682e5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import os\\n\",\n        \"import ezkl\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"d80d3169-cc70-4aee-bdc2-df9a435b3116\",\n      \"metadata\": {\n        \"id\": \"d80d3169-cc70-4aee-bdc2-df9a435b3116\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Downsample graph\\n\",\n        \"num_node = 5\\n\",\n        \"\\n\",\n        \"# filter edges so that we only bring adjacencies among downsampled node\\n\",\n        \"filter_row = []\\n\",\n        \"filter_col = []\\n\",\n        \"row, col = dataset[0].edge_index\\n\",\n        \"for idx in range(row.size(0)):\\n\",\n        \"    if row[idx] < num_node and col[idx] < num_node:\\n\",\n        \"        filter_row.append(row[idx])\\n\",\n        \"        filter_col.append(col[idx])\\n\",\n        \"filter_edge_index = torch.stack([torch.tensor(filter_row), torch.tensor(filter_col)])\\n\",\n        \"num_edge = len(filter_row)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"x = dataset[0].x[:num_node, :num_feat]\\n\",\n        \"edge_index = filter_edge_index\\n\",\n        \"\\n\",\n        \"adj_t = torch.sparse_coo_tensor(edge_index, torch.ones(num_edge), size=(num_node, num_node)).to_dense().T\\n\",\n        \"deg = torch.sum(adj_t, dim=1)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"46367b2f-951d-403b-9346-e689de0bee3f\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"46367b2f-951d-403b-9346-e689de0bee3f\",\n        \"outputId\": \"f063bf1b-e518-4fdb-b8ad-507c521acaa3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import json\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"model.eval()\\n\",\n        \"model.to('cpu')\\n\",\n        \"\\n\",\n        \"# No dynamic axis for GNN batch\\n\",\n        \"torch.onnx.export(model,               # model being run\\n\",\n        \"                      (x, adj_t, deg),               # model input (or a tuple for multiple inputs)\\n\",\n        \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=11,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['x', 'edge_index'],   # the model's input names\\n\",\n        \"                      output_names = ['output']) # the model's output names\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"9e6da242-540e-48dc-bc20-d08fcd192af4\",\n      \"metadata\": {\n        \"id\": \"9e6da242-540e-48dc-bc20-d08fcd192af4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"torch_out = model(x, adj_t, deg)\\n\",\n        \"x_shape = x.shape\\n\",\n        \"adj_t_shape=adj_t.shape\\n\",\n        \"deg_shape=deg.shape\\n\",\n        \"\\n\",\n        \"x = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"adj_t = ((adj_t).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"deg = ((deg).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_shapes=[x_shape, adj_t_shape, deg_shape],\\n\",\n        \"            input_data=[x, adj_t, deg],\\n\",\n        \"            output_data=[((torch_out).detach().numpy()).reshape([-1]).tolist()])\\n\",\n        \"json.dump(data, open(data_path, 'w'))\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"3393a884-7a14-435e-bb9e-4fa4fcbdc76b\",\n      \"metadata\": {\n        \"id\": \"3393a884-7a14-435e-bb9e-4fa4fcbdc76b\",\n        \"tags\": []\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"!RUST_LOG=trace\\n\",\n        \"import ezkl\\n\",\n        \"\\n\",\n        \"run_args = ezkl.PyRunArgs()\\n\",\n        \"run_args.input_scale = 5\\n\",\n        \"run_args.param_scale = 5\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n        \"assert res == True\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"8f86fceb\",\n      \"metadata\": {\n        \"id\": \"8f86fceb\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"3b55c925\",\n      \"metadata\": {\n        \"id\": \"3b55c925\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"d6478bab\",\n      \"metadata\": {\n        \"id\": \"d6478bab\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate the witness file\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b500c1ba\",\n      \"metadata\": {\n        \"id\": \"b500c1ba\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n        \"# WE GOT KEYS\\n\",\n        \"# WE GOT CIRCUIT PARAMETERS\\n\",\n        \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"ae152a64\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"ae152a64\",\n        \"outputId\": \"599cc9b8-ee85-407e-f0da-b2360634d2a8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"a2548b00\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"a2548b00\",\n        \"outputId\": \"e2972113-c079-4cb2-bfc5-6f7ad2842195\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# VERIFY IT\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3.11.4 ('.env': venv)\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    },\n    \"vscode\": {\n      \"interpreter\": {\n        \"hash\": \"af2b032f4d5a009ff33cd3ba5ac25dedfd7d71c9736fbe82aa90983ec2fc3628\"\n      }\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/generalized_inverse.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n      \"metadata\": {\n        \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\"\n      },\n      \"source\": [\n        \"\\n\",\n        \"## Generalized Inverse\\n\",\n        \"\\n\",\n        \"We show how to use EZKL to prove that we know matrices $A$ and its generalized inverse $B$. Since these are large we deal with the KZG commitments, with $a$ the polycommit of $A$, $b$ the polycommit of $B$, and $ABA = A$.\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"95613ee9\",\n      \"metadata\": {\n        \"id\": \"95613ee9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# here we create and (potentially train a model)\\n\",\n        \"\\n\",\n        \"# make sure you have the dependencies required here already installed\\n\",\n        \"from torch import nn\\n\",\n        \"import ezkl\\n\",\n        \"import os\\n\",\n        \"import json\\n\",\n        \"import torch\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"9LgqGF56Qcdz\",\n      \"metadata\": {\n        \"id\": \"9LgqGF56Qcdz\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"class GeneralizedInverseProof(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(GeneralizedInverseProof, self).__init__()\\n\",\n        \"        self.relu = nn.ReLU()\\n\",\n        \"\\n\",\n        \"    def forward(self,A,B):\\n\",\n        \"        # some expression of tolerance to error in the inference\\n\",\n        \"        return torch.sum(torch.abs(A@B@A - A)) < 0.1\\n\",\n        \"\\n\",\n        \"circuit = GeneralizedInverseProof()\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"YRQLvvsXVs9s\",\n      \"metadata\": {\n        \"id\": \"YRQLvvsXVs9s\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"gip_run_args = ezkl.PyRunArgs()\\n\",\n        \"gip_run_args.input_visibility = \\\"polycommit\\\"  # matrix and generalized inverse commitments\\n\",\n        \"gip_run_args.output_visibility = \\\"fixed\\\"   # no parameters used\\n\",\n        \"gip_run_args.param_visibility = \\\"fixed\\\" # should be Tensor(True)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b37637c4\",\n      \"metadata\": {\n        \"id\": \"b37637c4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"82db373a\",\n      \"metadata\": {\n        \"id\": \"82db373a\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n        \"shape = [10, 10]\\n\",\n        \"\\n\",\n        \"A = 0.1*torch.rand(1,*shape, requires_grad=True)\\n\",\n        \"B = A.inverse()\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"circuit.eval()\\n\",\n        \"\\n\",\n        \"    # Export the model\\n\",\n        \"torch.onnx.export(circuit,               # model being run\\n\",\n        \"                      (A,B),                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input1', 'input2'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input1' : {0 : 'batch_size'},\\n\",\n        \"                                    'input2' : {0 : 'batch_size'},\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"d0 = ((A).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"d1 = ((B).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(\\n\",\n        \"    input_data=[d0, d1],\\n\",\n        \")\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path, 'w' ))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"HOLcdGx4eQ9n\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"HOLcdGx4eQ9n\",\n        \"outputId\": \"cd0a4f10-251e-492e-9f05-d8af0d79c86a\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"circuit.forward(A,B)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"d5e374a2\",\n      \"metadata\": {\n        \"colab\": {\n          \"background_save\": true,\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"d5e374a2\",\n        \"outputId\": \"11ae5963-02d4-4939-9c98-d126071a9ba0\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=gip_run_args)\\n\",\n        \"\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n        \"\\n\",\n        \"data_array = (0.1*torch.rand(20,*shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array])\\n\",\n        \"\\n\",\n        \"# Serialize data into file:\\n\",\n        \"json.dump(data, open(cal_path, 'w'))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n        \"assert res == True\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"3aa4f090\",\n      \"metadata\": {\n        \"id\": \"3aa4f090\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"8b74dcee\",\n      \"metadata\": {\n        \"id\": \"8b74dcee\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"18c8b7c7\",\n      \"metadata\": {\n        \"id\": \"18c8b7c7\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate the witness file\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b1c561a8\",\n      \"metadata\": {\n        \"id\": \"b1c561a8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"# we pass the witness file to the setup function so as to prepopulate the \\\"fixed\\\" columns of the circuit. \\n\",\n        \"# in this case we want to force the output to be 0 meaning that the difference between the two matrices is 0\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        \\n\",\n        \"        witness_path = witness_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"c384cbc8\",\n      \"metadata\": {\n        \"id\": \"c384cbc8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"76f00d41\",\n      \"metadata\": {\n        \"id\": \"76f00d41\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# VERIFY IT\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3 (ipykernel)\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 5\n}"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/gradient_boosted_trees.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {\n                \"image-2.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANS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vsMrv//vuTfozW+Zs6dSpBYtJyqV3whz/8wR577LHULuYqBBAIhABBYiCqiUwiED4Btfrt2rWrrpVI48oefvhhO/PMM11h1f08c+ZMt02cJpk8+OCDNnfuXLfe4qxZs9zizwosH3jgAbcby5e+9CW3tt9tt91mN954Y/jAAlKifv36uXrTTi6vvfaaa92944473JJDaoHUZyVtB6jW3z/96U9uxxfVtdZq1MLeak3WDiwkBBDIrwBBYn79eToCjQponF6YB+QPGjTIVqxYcVz5tabiX/7yF3dMwYa6L3/4wx+aPt90000uSDzttNPcAsoKNjRmTcHm008/bT/72c9cF+itt9563D35IzsC48ePP26JnCeeeMItxK3hAwr2tQfztGnT7MILL3TnaakaBY5eUkuytwbj0KFD7be//a299957NmPGDHfNPffc453KOwII5EmAiSt5guexCDQnoAWCwzwLV0GDt2VeQxYKIDUebfr06TZ58mTr0aOHO23t2rVWVlZmF110kQs+FCCSci+g8YhaLN17qbVXi6Yr8FOAqKSWRLUMNpdeeeUVd4oCxAkTJtjYsWObu4TvEUAgBwIEiTlA5hEIIBAvoEkqak2MTQqKvWOatHDVVVe5fZY3bNhQd9rixYvthhtucAso6/srr7yy7js+5E5g2bJl9ve//73upXUVGwr8Y9cwbNHiX//Kif18zTXXmOpbLcn6XSjwJCGAQP4F/vW/2PznhRwggECEBJYsWWL9+/d3rYResc877zz7xCc+4f4cN26cPfnkk/bMM8+4bde8VseJEyda9+7dTd2bmlHrtTqpZYut2TzJ/Lzv2bPHPXjYsGHufcyYMXVL2GgfaA0P0GLmSqNHj3bv+ofq+qGHHnLjU1XPBIl1NHxAIK8CjEnMKz8PRyC6AtpK7fvf/75dd911dumll7qu9d27d9tdd93lUNSNfO2119o555zjxi56y60o2NBxb79ejX9TUve0Agxdr+9J2RVQd/+5555b95Af//jH9u6777pJJ/LXtn6bN2+2rVu3unNUXy+99JKbaLRlyxY3rtS7+NFHH7Xbb7/dVLdr1qzxDvOOAAJ5Fig4NrbnaJ7zwOMRQKABAbWyaRyeZvQGNSlI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ggQIECAAAECGQEnMTOlIgQIECBAgACBn4CT+LOURIAAAQIECBDICDiJmSkVIUCAAAECBAj8BJzEn6UkAgQIECBAgEBGwEnMTKkIAQIECBAgQOAn4CT+LCURIECAAAECBDICTmJmSkUIECBAgAABAj8BJ/FnKYkAAQIECBAgkBFwEjNTKkKAAAECBAgQ+Ak4iT9LSQQIECBAgACBjICTmJlSEQIECBAgQIDAT8BJ/FlKIkCAAAECBAhkBJzEzJSKECBAgAABAgR+Ak7iz1ISAQIECBAgQCAjMOcXwdcGhnZMAAAAAElFTkSuQmCC\"\n                },\n                \"image.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAUAAAAEbCAYAAACr2V2eAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/PGzLySIb4h7mNFNU/8RBzRWnS9hUvGGvvK4KUPF8yFOeoD9IeQRgEmshAxhRzimEAM41D+2Uk0djIog2MDFlagowiHtlOkcBjkJmKGHBmiiBBL5Cch7t369w2bWrkKJN+AQKWpaYfA2S7FvG9qI0dA7w5wes1VS/25rFAL2stxyedwGuh8dN3XUSC0D9Qrrvtedd36Mfk/ABfmJ+uTZFvl1hD0AAAAVmVYSWZNTQAqAAAACAABh2kABAAAAAEAAAAaAAAAAAADkoYABwAAABIAAABEoAIABAAAAAEAAAFAoAMABAAAAAEAAAEbAAAAAEFTQ0lJAAAAU2NyZWVuc2hvdP5iyG4AAAHWaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5z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7K1mrZ4/p96QMswsPB1BXtDK2aoJp15WzaFVGk1CXJfk+GpswkwUiTstX1IBFMyztBkrI1dU52oEAIYJFOlAjqo5pgvj7BIrN2JpkET6PEaqomGSQ4GqxQf2DUQZFyl6dStpa73L7nhwCW+AQEtcESsyF5iQQ0IKLaIAECcQjQBxiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgE/gcCHHjHKxBaJwAAAABJRU5ErkJggg==\"\n                }\n            },\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Gradient Boosted Trees\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image.png](attachment:image.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image-2.png](attachment:image-2.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `hummingbird-ml` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from sklearn.ensemble import GradientBoostingClassifier as Gbc\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"from torch import nn\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"NUM_CLASSES = 3\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = Gbc()\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"torch_gbt = convert(clr, \\\"torch\\\", X_test[:1])\\n\",\n                \"# assert predictions from torch are = to sklearn\\n\",\n                \"diffs = []\\n\",\n                \"\\n\",\n                \"for i in range(len(X_test)):\\n\",\n                \"    torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\\n\",\n                \"    sk_pred = clr.predict(X_test[i].reshape(1, -1))\\n\",\n                \"    diffs.append(torch_pred != sk_pred[0])\\n\",\n                \"\\n\",\n                \"print(\\\"num diff: \\\", sum(diffs))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# !!!!!!!!!!!!!!!!! This cell will flash a warning about onnx runtime compat but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=False)\\n\",\n                \"torch_out = torch_gbt.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(torch_gbt.model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=18,          # the ONNX version to export the model to\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[o.reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20,*shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 10,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/hashed_vis.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# hashed-ezkl\\n\",\n                \"\\n\",\n                \"Here's an example leveraging EZKL whereby the inputs to the model, and the model params themselves, are hashed inside a circuit.\\n\",\n                \"\\n\",\n                \"In this setup:\\n\",\n                \"- the hashes are publicly known to the prover and verifier\\n\",\n                \"- the hashes serve as \\\"public inputs\\\" (a.k.a instances) to the circuit\\n\",\n                \"\\n\",\n                \"We leave the outputs of the model as public as well (known to the  verifier and prover). \\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": []\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"logging.basicConfig(format=FORMAT)\\n\",\n                \"logging.getLogger().setLevel(logging.INFO)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we define our model. It is a humble model with but a conv layer and a $ReLU$ non-linearity, but it is a model nonetheless\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, \\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5, stride=4)\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        return x\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# this is where you'd train your model\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \\n\",\n                \"Now we export the model to onnx and create a corresponding (randomly generated) input file.\\n\",\n                \"\\n\",\n                \"You can replace the random `x` with real data if you so wish. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"shape = [3, 8, 8]\\n\",\n                \"x = torch.rand(1,*shape, requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(\\\"input.json\\\", 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n                \"- `input_visibility` defines the visibility of the model inputs\\n\",\n                \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n                \"- `output_visibility` defines the visibility of the model outputs\\n\",\n                \"\\n\",\n                \"There are currently 6 visibility settings:\\n\",\n                \"- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \\n\",\n                \"- `private`: known only to the prover\\n\",\n                \"- `fixed`: known to the prover and verifier (as a commit), but not modifiable by the prover.\\n\",\n                \"- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \\n\",\n                \"- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypted element, the public key used to encrypt, and the hash of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\\n\",\n                \"- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be inserted directly within the proof bytes.  \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Here we create the following setup:\\n\",\n                \"- `input_visibility`: \\\"hashed\\\"\\n\",\n                \"- `param_visibility`: \\\"hashed\\\"\\n\",\n                \"- `output_visibility`: public\\n\",\n                \"\\n\",\n                \"We encourage you to play around with other setups :) \\n\",\n                \"\\n\",\n                \"Shoutouts: \\n\",\n                \"\\n\",\n                \"- [summa-solvency](https://github.com/summa-dev/summa-solvency) for their help with the poseidon hashing chip. \\n\",\n                \"- [timeofey](https://github.com/timoftime) for providing inspiration in our developement of the el-gamal encryption circuit in Halo2. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"hashed\\\"\\n\",\n                \"run_args.param_visibility = \\\"hashed\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [torch.cat((x, torch.rand(10, *[3, 8, 8]))).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('val_data.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.get_srs( settings_path)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now need to generate the (partial) circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!export RUST_BACKTRACE=1\\n\",\n                \"\\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As a sanity check you can \\\"mock prove\\\" (i.e check that all the constraints of the circuit match without generate a full proof). \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.mock(witness_path, compiled_model_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a full proof. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"And verify it as a sanity check. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We can now create an EVM / `.sol` verifier that can be deployed on chain to verify submitted proofs using a view function.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier(\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Verify on the evm\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Make sure anvil is running locally first\\n\",\n                \"# run with $ anvil -p 3030\\n\",\n                \"# we use the default anvil node here\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"address_path = os.path.join(\\\"address.json\\\")\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_evm(\\n\",\n                \"    address_path,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    'http://127.0.0.1:3030'\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"with open(address_path, 'r') as file:\\n\",\n                \"    addr = file.read().rstrip()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# make sure anvil is running locally\\n\",\n                \"# $ anvil -p 3030\\n\",\n                \"\\n\",\n                \"res = ezkl.verify_evm(\\n\",\n                \"    addr,\\n\",\n                \"    proof_path,\\n\",\n                \"    \\\"http://127.0.0.1:3030\\\"\\n\",\n                \")\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": []\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.13\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/keras_simple_demo.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL Jupyter Notebook Demo with Keras\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"a27b0cd9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"tf2onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"from keras.models import Sequential\\n\",\n                \"from keras.layers import Dense, Dropout, Activation, Flatten\\n\",\n                \"from keras.layers import Convolution2D, MaxPooling2D\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.DEBUG)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers, max pooling layers etc... \\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"model = Sequential()\\n\",\n                \"model.add(Convolution2D(2, (3,3), activation='relu', input_shape=(28,28,1)))\\n\",\n                \"model.add(Convolution2D(2, (3,3), activation='relu'))\\n\",\n                \"model.add(MaxPooling2D(pool_size=(2,2)))\\n\",\n                \"model.add(Dropout(0.25))\\n\",\n                \"model.add(Flatten())\\n\",\n                \"model.add(Dense(128, activation='relu'))\\n\",\n                \"model.add(Dropout(0.5))\\n\",\n                \"model.add(Dense(10, activation='softmax'))\\n\",\n                \"model.output_names=['output']\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Train the model as you like here (skipped for brevity)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import numpy as np\\n\",\n                \"import tf2onnx\\n\",\n                \"import tensorflow as tf\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"shape = [1, 28, 28]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*np.random.rand(1,*shape)\\n\",\n                \"\\n\",\n                \"spec = tf.TensorSpec([1, 28, 28, 1], tf.float32, name='input_0')\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"tf2onnx.convert.from_keras(model, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\\n\",\n                \"\\n\",\n                \"data_array = x.reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (0.1*np.random.rand(20,*shape)).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b6e051d5\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs(settings_path = settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.13\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/kmeans.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## K-means\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"sk2torch\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.cluster import KMeans\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Create a dataset of two Gaussians. There will be some overlap\\n\",\n                \"# between the two classes, which adds some uncertainty to the model.\\n\",\n                \"xs = np.concatenate(\\n\",\n                \"    [\\n\",\n                \"        np.random.random(size=(256, 2)) + [1, 0],\\n\",\n                \"        np.random.random(size=(256, 2)) + [-1, 0],\\n\",\n                \"    ],\\n\",\n                \"    axis=0,\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"# Train an SVM on the data and wrap it in PyTorch.\\n\",\n                \"sk_model = KMeans()\\n\",\n                \"sk_model.fit(xs)\\n\",\n                \"model = convert(sk_model, backend=\\\"pytorch\\\").model\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"# Create a coordinate grid to compute a vector field on.\\n\",\n                \"spaced = np.linspace(-2, 2, num=25)\\n\",\n                \"grid_xs = torch.tensor([[x, y] for x in spaced for y in spaced], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = xs.shape[1:]\\n\",\n                \"x = grid_xs[0:1]\\n\",\n                \"torch_out = model(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[o.reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (grid_xs[0:20].detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.13\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/kzg_vis.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# kzg-ezkl\\n\",\n                \"\\n\",\n                \"Here's an example leveraging EZKL whereby the inputs to the model, and the model params themselves, are committed to using kzg-commitments inside a circuit.\\n\",\n                \"\\n\",\n                \"In this setup:\\n\",\n                \"- the commitments are publicly known to the prover and verifier\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"We leave the outputs of the model as public as well (known to the  verifier and prover). \\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"logging.basicConfig(format=FORMAT)\\n\",\n                \"logging.getLogger().setLevel(logging.INFO)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we define our model. It is a humble model with but a conv layer and a $ReLU$ non-linearity, but it is a model nonetheless\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, \\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5, stride=4)\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        return x\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# this is where you'd train your model\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \\n\",\n                \"Now we export the model to onnx and create a corresponding (randomly generated) input file.\\n\",\n                \"\\n\",\n                \"You can replace the random `x` with real data if you so wish. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = torch.rand(1,*[3, 8, 8], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(\\\"input.json\\\", 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n                \"- `input_visibility` defines the visibility of the model inputs\\n\",\n                \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n                \"- `output_visibility` defines the visibility of the model outputs\\n\",\n                \"\\n\",\n                \"There are currently 6 visibility settings:\\n\",\n                \"- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \\n\",\n                \"- `private`: known only to the prover\\n\",\n                \"- `fixed`: known to the prover and verifier (as a commit), but not modifiable by the prover.\\n\",\n                \"- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \\n\",\n                \"- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypted element, the public key used to encrypt, and the hash of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\\n\",\n                \"- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be modified directly within the proof bytes.  \\n\",\n                \"\\n\",\n                \"Here we create the following setup:\\n\",\n                \"- `input_visibility`: \\\"polycommit\\\"\\n\",\n                \"- `param_visibility`: \\\"polycommit\\\"\\n\",\n                \"- `output_visibility`: public\\n\",\n                \"\\n\",\n                \"We encourage you to play around with other setups :) \\n\",\n                \"\\n\",\n                \"Shoutouts: \\n\",\n                \"\\n\",\n                \"- [summa-solvency](https://github.com/summa-dev/summa-solvency) for their help with the poseidon hashing chip. \\n\",\n                \"- [timeofey](https://github.com/timoftime) for providing inspiration in our development of the el-gamal encryption circuit in Halo2. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.param_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [torch.cat((x, torch.rand(10, *[3, 8, 8]))).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('val_data.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.get_srs( settings_path)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now need to generate the (partial) circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!export RUST_BACKTRACE=1\\n\",\n                \"\\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path, vk_path)\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As a sanity check you can \\\"mock prove\\\" (i.e check that all the constraints of the circuit match without generate a full proof). \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"res = ezkl.mock(witness_path, compiled_model_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a full proof. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we need to swap out the public commitments inside the corresponding proof bytes\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.swap_proof_commitments(proof_path, witness_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"And verify it as a sanity check. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We can now create an EVM / `.sol` verifier that can be deployed on chain to verify submitted proofs using a view function.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier(\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Verify on the evm\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Make sure anvil is running locally first\\n\",\n                \"# run with $ anvil -p 3030\\n\",\n                \"# we use the default anvil node here\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"address_path = os.path.join(\\\"address.json\\\")\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_evm(\\n\",\n                \"    address_path,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    'http://127.0.0.1:3030'\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"with open(address_path, 'r') as file:\\n\",\n                \"    addr = file.read().rstrip()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# make sure anvil is running locally\\n\",\n                \"# $ anvil -p 3030\\n\",\n                \"\\n\",\n                \"res = ezkl.verify_evm(\\n\",\n                \"    addr,\\n\",\n                \"    proof_path,\\n\",\n                \"    \\\"http://127.0.0.1:3030\\\"\\n\",\n                \")\\n\",\n                \"assert res == True\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.13\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/lightgbm.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {\n                \"image-3.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAyw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S0R+Vvf/ubXHnllVJdXS179uyRiy66SG655Ra5+eab5X/+539EA8tNN91kgkrjwKJBRYPJvHnzTA+Jej777LPy0ksvmV4c3ezxxRdfFA04GlCOOeYYmTVrltkE0ldg0aCkZdIhZC+//LIJSA8//HCTIWQEFqf/5lI/BBBAAIHmBAgszenwGQII2ErAX2DRHpbPPvtM7r//fnnwwQdNr8jOnTtND4tuyqi71d9xxx0mzOgGjdddd50JLPfcc485/7jjjpOsrCxZv3696Vl56623pHPnzmb41l133SUzZswwq5PpUC99X4eZ6dAynceiPTOLFi0yPSr/+Mc/5Be/+IWsXr3avH766adFy6aBRefM/O53v5NHHnmEwGKr3zoKiwACCCAQagECS6iFuT8CCIRNoLnAokPCxo4da3pCFixYYELJkSNHTDjQXpKf//znZnhWWVnZ0SFh06ZNM3u66LwVnYvyzjvvmKFj2pOiPSOPP/64/OQnPzHLDetQMP1c57lce+21JgT17t3b9Ljotffdd9/R93TomM6nIbCE7VeDByGAAAII2FiAwGLjxqPoCCDQUMBXYGl4RsNXOvFee0W8R2xsrBkq5n2t3xufo+81Pk+XUda9UnTolvdISUmRoqKiBu/5upf3/Oa+MySsOR0+QwABBBBwugCBxektTP0QcJFAsIHFLjQEFru0FOVEAAEEEAiFAIElFKrcEwEEIiJAYIkIOw9FAAEEEEAgpAIElpDycnMEEAinwIEDB8wQLKftdK/DzXTejM6J4UAAAQQQQMBtAgQWt7U49UXAwQLewBIdHe2oWuqQMAKLo5qUyiCAAAIIBCFAYAkCi1MRQMDaArpjvIYVJwYWXRygR48e1m4ASocAAggggEAIBAgsIUDllgggEBkBAktk3HkqAggggAACoRQgsIRSl3sjgEBYBcIRWDp06CDl5eVmiJa3crqEcWFhofdlu3/XIWH0sLQ7KzdEAAEEELCJAIHFJg1FMRFAoGWBcASW008/XZYsWWL2YjnllFNk6dKlMnr0aFm7dq3oppOhOAgsoVDlnggggAACdhEgsNilpSgnAgi0KOArsCQmJsrJJ58sFRUV8vXXX8vQoUMlLy9PdGf64u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Qz8/PN9frPigc/gV0vpH2tOgKZhwIIIAAAgi0VoDA0lo5rkMAgRYFNBjoql4aDqx0aC+LDk/r0qXL0V6SQMunw670Wp03wtG8gDofPnzY9GZpbwsHAggggAACrREgsLRGjWsQQCAgAe2JKCsrs1xg0cJruTSweFfXCqhCnpO010DnwrRlSFmgz3LCeTk5OWaxhISEBCdUhzoggAACCERAgMASAXQeiYBbBLQ3Qud6WPGPVe396d69uxmyFEx7FBQUmLkZVus1CqYO4TxXe1h0Hgs9LOFU51kIIICAswQILM5qT2qDgKUEmgssY8eONXNBNm3aFFCZzz//fFmwYIEJQHpBt27d5Nhjj5XPP/88oOsbn2S3wPLTn/5U/vWvf0lFRUXjqjR5rYsBTJ48Wd5///2jn6mVzr9p7eaSQ4cONUsn6ypkixYtEl3AQO950kknyapVq/zel8BytAn4AQEEEECglQIEllbCcRkCCLQs0Fxguffee0V7K2bMmGFupHus6NwQ7bnQYVcaSHRIma7opec999xz5g/wd955x5z/m9/8Rrp27Sp/+MMfTA+O7vauE/x1c0mdX6L30H/V194dLUfjo70Diw4T0yFm+ge6zt3w9ippvXRYlB76s36mf+xrz5PWTV9rCNFeiMLCQvNZ47Lqder13nvvydKlS4/eS3+oqqoy16uF1lnDit7zqaeeMjZ79uwx58+cOVPmzp1rQp+uaqZLROsmk1puXRBBjbQ86qftUP9Q2wsuuEBeeeUVGT16tOzevduU3/veNddcI3PmzDHzlepfpz8TWBqL8BoBBBBAIFgBAkuwYpyPAAIBC/gLLAMHDpQTTzxRevbsKc8884z5g/uWW24xfzQvX75czjjjDPOHroYX/UP8oYcekunTp5vnPvroo6J/cF9//fXm+9///ne5+eabZfv27TJkyBBz7pVXXmn+1X/MmDGmB0b/wG58tGdg0WB0ww03mD1isrKy5B//+Iccf/zxMmLECPPHvbee9913n3z77bcyYMAA+fDDD03AuOSSS+TNN9+Uc889V15++WW58cYb5cknn5SzzjrLBLDvvvtOzj77bPn+++/NexpE9Lj//vtFP1uxYoX84he/kI0bN8qgQ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Hz44YcycuRIs0eL9roUFBTI6tWrZfr06fLoo4+awKJDxFatWiX33HOP/PWvfzUw2gOjgeXWW2+Vxx9/3NxL76mBZcqUKfLyyy/7BCSw+GThTQQQQAABBCwrQGCxbNNQMAScI+ArsERHR8vUqVPNnBWdWP/CCy+Y5YavvfZa+f77783wrj/+8Y/Ss2dPufTSS00A0eFh+/btM5tPLlu2TL799lu5/PLLTdjR+TAHDx6Ujz76yISdjz/+WNavX98EkcDShIQ3EEAAAQQQsLQAgcXSzUPhEHCGgE6Q10n1vjaO1OWFdSK999DgoV96vvfQ17qPi3deS+PPdSiZTtavf3ivqf+e/pyTkyNpaWlmgn7jz3iNAAIIIIAAAtYTILBYr00oEQKOEygrKzMrdnXu3LlNdRs2bJiZdN/am3h3utdyaA8PBwIIIIAAAghYX4DAYv02ooQIOEJAly7WOSqpqakRq09ubq5Z/jiSZYhY5XkwAggggAACNhUgsNi04Sg2AnYTqKioEO9cFi27hpdwHTrkTHtXEhISzP4u4Xouz0EAAQQQQACBtgsQWNpuyB0QQCAIAd2xXsNLfHx8EFe17VSdz6JzZTSwcCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBP4/LTSuZ2kLvQEAAAAASUVORK5CYII=\"\n                },\n                \"image.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAUAAAAEbCAYAAACr2V2eAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/PGzLySIb4h7mNFNU/8RBzRWnS9hUvGGvvK4KUPF8yFOeoD9IeQRgEmshAxhRzimEAM41D+2Uk0djIog2MDFlagowiHtlOkcBjkJmKGHBmiiBBL5Cch7t369w2bWrkKJN+AQKWpaYfA2S7FvG9qI0dA7w5wes1VS/25rFAL2stxyedwGuh8dN3XUSC0D9Qrrvtedd36Mfk/ABfmJ+uTZFvl1hD0AAAAVmVYSWZNTQAqAAAACAABh2kABAAAAAEAAAAaAAAAAAADkoYABwAAABIAAABEoAIABAAAAAEAAAFAoAMABAAAAAEAAAEbAAAAAEFTQ0lJAAAAU2NyZWVuc2hvdP5iyG4AAAHWaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA2LjAuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICA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cESsyF5iQQ0IKLaIAECcQjQBxiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgE/gcCHHjHKxBaJwAAAABJRU5ErkJggg==\"\n                }\n            },\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## LightBGM models\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"LightBGM based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image.png](attachment:image.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image-3.png](attachment:image-3.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `hummingbird` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"a60b90d6\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!python -m pip install hummingbird_ml\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"lightgbm\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from lightgbm import LGBMClassifier as Gbc\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"from torch import nn\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"NUM_CLASSES = 3\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = Gbc(n_estimators=12)\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"# convert to torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"torch_gbt = convert(clr, 'torch', X_test[:1])\\n\",\n                \"\\n\",\n                \"print(torch_gbt)\\n\",\n                \"# assert predictions from torch are = to sklearn\\n\",\n                \"diffs = []\\n\",\n                \"\\n\",\n                \"for i in range(len(X_test)):\\n\",\n                \"    torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\\n\",\n                \"    sk_pred = clr.predict(X_test[i].reshape(1, -1))\\n\",\n                \"    diffs.append(torch_pred != sk_pred[0])\\n\",\n                \"\\n\",\n                \"print(\\\"num diff: \\\", sum(diffs))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# !!!!!!!!!!!!!!!!! This cell will flash a warning about onnx runtime compat but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=False)\\n\",\n                \"torch_out = torch_gbt.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(torch_gbt.model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=18,          # the ONNX version to export the model to\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[(o).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.randn(20, *shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"1f50a8d0\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/linear_regression.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Linear Regression\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format. \\n\",\n                \"This notebook showcases how to do so using the `hummingbird-ml` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"import os\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import json\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.linear_model import LinearRegression\\n\",\n                \"X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])\\n\",\n                \"# y = 1 * x_0 + 2 * x_1 + 3\\n\",\n                \"y = np.dot(X, np.array([1, 2])) + 3\\n\",\n                \"reg = LinearRegression().fit(X, y)\\n\",\n                \"reg.score(X, y)\\n\",\n                \"\\n\",\n                \"circuit = convert(reg, \\\"torch\\\", X[:1]).model\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=True)\\n\",\n                \"torch_out = circuit(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.randn(20, *shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/little_transformer.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"d0a82619\",\n            \"metadata\": {},\n            \"source\": [\n                \"Credits to [geohot](https://github.com/geohot/ai-notebooks/blob/master/mnist_gan.ipynb) for most of this code\\n\",\n                \"\\n\",\n                \"## Model Architecture and training\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c22afe46\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"%pip install pytorch_lightning\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"12fb79a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import random\\n\",\n                \"import math\\n\",\n                \"import numpy as np\\n\",\n                \"\\n\",\n                \"import torch\\n\",\n                \"from torch import nn\\n\",\n                \"import torch.nn.functional as F\\n\",\n                \"\\n\",\n                \"import pytorch_lightning as pl\\n\",\n                \"\\n\",\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# import logging\\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.DEBUG)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8638e94e\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"class BaseDataModule(pl.LightningDataModule):\\n\",\n                \"  def __init__(self, batch_size=32, split=0.8, *args, **kwargs):\\n\",\n                \"    super().__init__()\\n\",\n                \"    self.ds_X, self.ds_Y = self.get_dataset(*args, **kwargs)\\n\",\n                \"    self.split = int(self.ds_X.shape[0]*split)\\n\",\n                \"    self.batch_size = batch_size\\n\",\n                \"\\n\",\n                \"  def train_dataloader(self):\\n\",\n                \"    ds_X_train, ds_Y_train = self.ds_X[0:self.split], self.ds_Y[0:self.split]\\n\",\n                \"    return torch.utils.data.DataLoader(list(zip(ds_X_train, ds_Y_train)), batch_size=self.batch_size)\\n\",\n                \"\\n\",\n                \"  def val_dataloader(self):\\n\",\n                \"    ds_X_test, ds_Y_test = self.ds_X[self.split:], self.ds_Y[self.split:]\\n\",\n                \"    return torch.utils.data.DataLoader(list(zip(ds_X_test, ds_Y_test)), batch_size=self.batch_size)\\n\",\n                \"\\n\",\n                \"class ReverseDataModule(BaseDataModule):\\n\",\n                \"  def get_dataset(self, cnt=10000, seq_len=6):\\n\",\n                \"    ds = np.random.randint(0, 10, size=(cnt, seq_len))\\n\",\n                \"    return ds, ds[:, ::-1].ravel().reshape(cnt, seq_len)\\n\",\n                \"  \\n\",\n                \"# dataset idea from https://github.com/karpathy/minGPT/blob/master/play_math.ipynb\\n\",\n                \"class AdditionDataModule(BaseDataModule):\\n\",\n                \"  def get_dataset(self):\\n\",\n                \"    ret = []\\n\",\n                \"    for i in range(100):\\n\",\n                \"      for j in range(100):\\n\",\n                \"        s = i+j\\n\",\n                \"        ret.append([i//10, i%10, j//10, j%10, s//100, (s//10)%10, s%10])\\n\",\n                \"    ds = np.array(ret)\\n\",\n                \"    return ds[:, 0:6], np.copy(ds[:, 1:])    \\n\",\n                \"\\n\",\n                \"# this is the hardest to learn and requires 4 layers\\n\",\n                \"class ParityDataModule(BaseDataModule):\\n\",\n                \"  def get_dataset(self, seq_len=10):\\n\",\n                \"    ds_X, ds_Y = [], []\\n\",\n                \"    for i in range(2**seq_len):\\n\",\n                \"      x = [int(x) for x in list(bin(i)[2:].rjust(seq_len, '0'))]\\n\",\n                \"      ds_X.append(x)\\n\",\n                \"      ds_Y.append((np.cumsum(x)%2).tolist())\\n\",\n                \"    return np.array(ds_X), np.array(ds_Y)\\n\",\n                \"  \\n\",\n                \"class WikipediaDataModule(BaseDataModule):\\n\",\n                \"  def get_dataset(self, seq_len=50):\\n\",\n                \"    global enwik8\\n\",\n                \"    if 'enwik8' not in globals():\\n\",\n                \"      import requests\\n\",\n                \"      enwik8_zipped = requests.get(\\\"https://data.deepai.org/enwik8.zip\\\").content\\n\",\n                \"      from zipfile import ZipFile\\n\",\n                \"      import io\\n\",\n                \"      enwik8 = ZipFile(io.BytesIO(enwik8_zipped)).read('enwik8')\\n\",\n                \"    en = np.frombuffer(enwik8, dtype=np.uint8).astype(np.int)\\n\",\n                \"    en = en[0:-seq_len+1]\\n\",\n                \"    en[en>127] = 127\\n\",\n                \"    return en[0:-1].reshape(-1, seq_len), en[1:].reshape(-1, seq_len)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"323554ca\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"def attention(queries, keys, values):\\n\",\n                \"  d = queries.shape[-1]\\n\",\n                \"  scores = torch.matmul(queries, keys.transpose(-2,-1))/math.sqrt(d)\\n\",\n                \"  attention_weights = F.softmax(scores, dim=-1)\\n\",\n                \"  return torch.matmul(attention_weights, values)\\n\",\n                \"\\n\",\n                \"class MultiHeadAttention(nn.Module):\\n\",\n                \"  def __init__(self, embed_dim, num_heads):\\n\",\n                \"    super(MultiHeadAttention, self).__init__()\\n\",\n                \"    self.embed_dim, self.num_heads = embed_dim, num_heads\\n\",\n                \"    assert embed_dim % num_heads == 0\\n\",\n                \"    self.projection_dim = embed_dim // num_heads\\n\",\n                \"    \\n\",\n                \"    self.W_q = nn.Linear(embed_dim, embed_dim)\\n\",\n                \"    self.W_k = nn.Linear(embed_dim, embed_dim)\\n\",\n                \"    self.W_v = nn.Linear(embed_dim, embed_dim)\\n\",\n                \"    self.W_o = nn.Linear(embed_dim, embed_dim)\\n\",\n                \"\\n\",\n                \"  def transpose(self, x):\\n\",\n                \"    x = x.reshape(x.shape[0], x.shape[1], self.num_heads, self.projection_dim)\\n\",\n                \"    return x.permute(0, 2, 1, 3)\\n\",\n                \"  \\n\",\n                \"  def transpose_output(self, x):\\n\",\n                \"    x = x.permute(0, 2, 1, 3)\\n\",\n                \"    return x.reshape(x.shape[0], x.shape[1], self.embed_dim)\\n\",\n                \"    \\n\",\n                \"  def forward(self, q, k, v):\\n\",\n                \"    q = self.transpose(self.W_q(q))\\n\",\n                \"    k = self.transpose(self.W_k(k))\\n\",\n                \"    v = self.transpose(self.W_v(v))\\n\",\n                \"    output = attention(q, k, v)\\n\",\n                \"    return self.W_o(self.transpose_output(output))\\n\",\n                \"  \\n\",\n                \"class TransformerBlock(nn.Module):\\n\",\n                \"  def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):\\n\",\n                \"    super(TransformerBlock, self).__init__()\\n\",\n                \"    self.att = MultiHeadAttention(embed_dim, num_heads)\\n\",\n                \"    self.ffn = nn.Sequential(\\n\",\n                \"      nn.Linear(embed_dim, ff_dim), nn.ReLU(), nn.Linear(ff_dim, embed_dim)\\n\",\n                \"    )\\n\",\n                \"    self.layernorm1 = nn.LayerNorm(embed_dim)\\n\",\n                \"    self.layernorm2 = nn.LayerNorm(embed_dim)\\n\",\n                \"    self.dropout = nn.Dropout(rate)\\n\",\n                \"    \\n\",\n                \"  def forward(self, x):\\n\",\n                \"    x = self.layernorm1(x + self.dropout(self.att(x, x, x)))\\n\",\n                \"    x = self.layernorm2(x + self.dropout(self.ffn(x)))\\n\",\n                \"    return x\\n\",\n                \"  \\n\",\n                \"class TokenAndPositionEmbedding(nn.Module):\\n\",\n                \"  def __init__(self, maxlen, vocab_size, embed_dim):\\n\",\n                \"    super(TokenAndPositionEmbedding, self).__init__()\\n\",\n                \"    self.token_emb = nn.Embedding(vocab_size, embed_dim)\\n\",\n                \"    self.pos_emb = nn.Embedding(maxlen, embed_dim)\\n\",\n                \"  def forward(self, x):\\n\",\n                \"    pos = torch.arange(0, x.size(1), dtype=torch.int32, device=x.device)\\n\",\n                \"    return self.token_emb(x) + self.pos_emb(pos).view(1, x.size(1), -1)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"167e42e3\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"class LittleTransformer(pl.LightningModule):\\n\",\n                \"  def __init__(self, seq_len=6, max_value=10, layer_count=2, embed_dim=128, num_heads=4, ff_dim=32):\\n\",\n                \"    super().__init__()\\n\",\n                \"    self.max_value = max_value\\n\",\n                \"    self.model = nn.Sequential(\\n\",\n                \"      TokenAndPositionEmbedding(seq_len, max_value, embed_dim),\\n\",\n                \"      *[TransformerBlock(embed_dim, num_heads, ff_dim) for x in range(layer_count)],\\n\",\n                \"      nn.Linear(embed_dim, max_value),\\n\",\n                \"      nn.LogSoftmax(dim=-1))\\n\",\n                \"    \\n\",\n                \"  def forward(self, x):\\n\",\n                \"    return self.model(x)\\n\",\n                \"  \\n\",\n                \"  def training_step(self, batch, batch_idx):\\n\",\n                \"    x, y = batch\\n\",\n                \"    output = self.model(x)\\n\",\n                \"    loss = F.nll_loss(output.view(-1, self.max_value), y.view(-1))\\n\",\n                \"    self.log(\\\"train_loss\\\", loss)\\n\",\n                \"    return loss\\n\",\n                \"  \\n\",\n                \"  def validation_step(self, val_batch, batch_idx):\\n\",\n                \"    x, y = val_batch\\n\",\n                \"    pred = self.model(x).argmax(dim=2)\\n\",\n                \"    val_accuracy = (pred == y).type(torch.float).mean()\\n\",\n                \"    self.log(\\\"val_accuracy\\\", val_accuracy, prog_bar=True)\\n\",\n                \"  \\n\",\n                \"  def configure_optimizers(self):\\n\",\n                \"    if self.device.type == 'cuda':\\n\",\n                \"      import apex\\n\",\n                \"      return apex.optimizers.FusedAdam(self.parameters(), lr=3e-4)\\n\",\n                \"    else:\\n\",\n                \"      return torch.optim.Adam(self.parameters(), lr=3e-4)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"a2f48c98\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model = LittleTransformer(seq_len=6)\\n\",\n                \"trainer = pl.Trainer(enable_progress_bar=True, max_epochs=0)\\n\",\n                \"data = AdditionDataModule(batch_size=64)\\n\",\n                \"#data = ReverseDataModule(cnt=1000, seq_len=20)\\n\",\n                \"#data = ParityDataModule(seq_len=14)\\n\",\n                \"trainer.fit(model, data)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"fa7d277e\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"6f339a28\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import os \\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"27ce542b\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"shape = [1, 6]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = torch.zeros(shape, dtype=torch.long)\\n\",\n                \"x = x.reshape(shape)\\n\",\n                \"\\n\",\n                \"print(x)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"model.eval()\\n\",\n                \"model.to('cpu')\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(model,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data_json = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"print(data_json)\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data_json, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"36ddc6f9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl \\n\",\n                \"\\n\",\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"2fe6d972\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.randn(20, *shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"0990f5a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"1b80dc01\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"54cbde29\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"witness_path = \\\"gan_witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"28760638\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"5e595112\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d37adaef\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"5b58acd5\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/lstm.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"d0a82619\",\n            \"metadata\": {},\n            \"source\": [\n                \"\\n\",\n                \"## Model Architecture and training\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"12fb79a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import numpy as np\\n\",\n                \"\\n\",\n                \"import torch\\n\",\n                \"from torch import nn\\n\",\n                \"import torch.nn.functional as F\\n\",\n                \"\\n\",\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"a2f48c98\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model = nn.LSTM(3, 3)  # Input dim is 3, output dim is 3\\n\",\n                \"x = torch.randn(1, 3)\\n\",\n                \"\\n\",\n                \"# this is where you'd train the model\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"fa7d277e\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"6f339a28\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import os \\n\",\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"27ce542b\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import json \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"model.eval()\\n\",\n                \"model.to('cpu')\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(model,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"SEQ_LEN = 10\\n\",\n                \"shape = (SEQ_LEN, 3)\\n\",\n                \"# sequence of length 10\\n\",\n                \"x = torch.randn(*shape)\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data_json = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"print(data_json)\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data_json, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"2fe6d972\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", SEQ_LEN)]\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.randn(10, *shape).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"0990f5a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"1b80dc01\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"54cbde29\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"witness_path = \\\"lstmwitness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"28760638\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"5e595112\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d37adaef\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"5b58acd5\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/mean_postgres.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"## Mean of ERC20 transfer amounts\\n\",\n        \"\\n\",\n        \"This notebook shows how to calculate the mean of ERC20 transfer amounts, pulling data in from a Postgres database. First we install and get the necessary libraries running. \\n\",\n        \"The first of which is [shovel](https://indexsupply.com/shovel/docs/#getting-started), which is a library that allows us to pull data from the Ethereum blockchain into a Postgres database.\\n\",\n        \"\\n\",\n        \"Make sure you install postgres if needed https://indexsupply.com/shovel/docs/#getting-started. \\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"import os\\n\",\n        \"import getpass\\n\",\n        \"import json\\n\",\n        \"import time\\n\",\n        \"import subprocess\\n\",\n        \"\\n\",\n        \"# swap out for the relevant linux/amd64, darwin/arm64, darwin/amd64, windows/amd64\\n\",\n        \"os.system(\\\"curl -LO https://indexsupply.net/bin/1.0/linux/amd64/shovel\\\")\\n\",\n        \"os.system(\\\"chmod +x shovel\\\")\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"os.environ[\\\"PG_URL\\\"] = \\\"postgres://\\\" + getpass.getuser() + \\\":@localhost:5432/shovel\\\"\\n\",\n        \"\\n\",\n        \"# create a config.json file with the following contents\\n\",\n        \"config = {\\n\",\n        \"  \\\"pg_url\\\": \\\"$PG_URL\\\",\\n\",\n        \"  \\\"eth_sources\\\": [\\n\",\n        \"    {\\\"name\\\": \\\"mainnet\\\", \\\"chain_id\\\": 1, \\\"url\\\": \\\"https://ethereum-rpc.publicnode.com\\\"},\\n\",\n        \"    {\\\"name\\\": \\\"base\\\", \\\"chain_id\\\": 8453, \\\"url\\\": \\\"https://base-rpc.publicnode.com\\\"}\\n\",\n        \"  ],\\n\",\n        \"  \\\"integrations\\\": [{\\n\",\n        \"    \\\"name\\\": \\\"usdc_transfer\\\",\\n\",\n        \"    \\\"enabled\\\": True,\\n\",\n        \"    \\\"sources\\\": [{\\\"name\\\": \\\"mainnet\\\"}, {\\\"name\\\": \\\"base\\\"}],\\n\",\n        \"    \\\"table\\\": {\\n\",\n        \"      \\\"name\\\": \\\"usdc\\\",\\n\",\n        \"      \\\"columns\\\": [\\n\",\n        \"        {\\\"name\\\": \\\"log_addr\\\",  \\\"type\\\": \\\"bytea\\\"},\\n\",\n        \"        {\\\"name\\\": \\\"block_num\\\", \\\"type\\\": \\\"numeric\\\"},\\n\",\n        \"        {\\\"name\\\": \\\"f\\\",         \\\"type\\\": \\\"bytea\\\"},\\n\",\n        \"        {\\\"name\\\": \\\"t\\\",         \\\"type\\\": \\\"bytea\\\"},\\n\",\n        \"        {\\\"name\\\": \\\"v\\\",         \\\"type\\\": \\\"numeric\\\"}\\n\",\n        \"      ]\\n\",\n        \"    },\\n\",\n        \"    \\\"block\\\": [\\n\",\n        \"      {\\\"name\\\": \\\"block_num\\\", \\\"column\\\": \\\"block_num\\\"},\\n\",\n        \"      {\\n\",\n        \"        \\\"name\\\": \\\"log_addr\\\",\\n\",\n        \"        \\\"column\\\": \\\"log_addr\\\",\\n\",\n        \"        \\\"filter_op\\\": \\\"contains\\\",\\n\",\n        \"        \\\"filter_arg\\\": [\\n\",\n        \"          \\\"a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\\\",\\n\",\n        \"          \\\"833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\\\"\\n\",\n        \"        ]\\n\",\n        \"      }\\n\",\n        \"    ],\\n\",\n        \"    \\\"event\\\": {\\n\",\n        \"      \\\"name\\\": \\\"Transfer\\\",\\n\",\n        \"      \\\"type\\\": \\\"event\\\",\\n\",\n        \"      \\\"anonymous\\\": False,\\n\",\n        \"      \\\"inputs\\\": [\\n\",\n        \"        {\\\"indexed\\\": True,  \\\"name\\\": \\\"from\\\",  \\\"type\\\": \\\"address\\\", \\\"column\\\": \\\"f\\\"},\\n\",\n        \"        {\\\"indexed\\\": True,  \\\"name\\\": \\\"to\\\",    \\\"type\\\": \\\"address\\\", \\\"column\\\": \\\"t\\\"},\\n\",\n        \"        {\\\"indexed\\\": False, \\\"name\\\": \\\"value\\\", \\\"type\\\": \\\"uint256\\\", \\\"column\\\": \\\"v\\\"}\\n\",\n        \"      ]\\n\",\n        \"    }\\n\",\n        \"  }]\\n\",\n        \"}\\n\",\n        \"\\n\",\n        \"# write the config to a file\\n\",\n        \"with open(\\\"config.json\\\", \\\"w\\\") as f:\\n\",\n        \"  f.write(json.dumps(config))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# print the two env variables\\n\",\n        \"os.system(\\\"echo $PG_URL\\\")\\n\",\n        \"\\n\",\n        \"os.system(\\\"createdb -h localhost -p 5432 shovel\\\")\\n\",\n        \"\\n\",\n        \"os.system(\\\"echo shovel is now installed. starting:\\\")\\n\",\n        \"\\n\",\n        \"command = [\\\"./shovel\\\", \\\"-config\\\", \\\"config.json\\\"]\\n\",\n        \"subprocess.Popen(command)\\n\",\n        \"\\n\",\n        \"os.system(\\\"echo shovel started.\\\")\\n\",\n        \"\\n\",\n        \"time.sleep(5)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"2wIAHwqH2_mo\"\n      },\n      \"source\": [\n        \"**Import Dependencies**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"9Byiv2Nc2MsK\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"import ezkl\\n\",\n        \"import torch\\n\",\n        \"import datetime\\n\",\n        \"import pandas as pd\\n\",\n        \"import requests\\n\",\n        \"import json\\n\",\n        \"import os\\n\",\n        \"\\n\",\n        \"import logging\\n\",\n        \"# # uncomment for more descriptive logging \\n\",\n        \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n        \"logging.basicConfig(format=FORMAT)\\n\",\n        \"logging.getLogger().setLevel(logging.DEBUG)\\n\",\n        \"\\n\",\n        \"print(\\\"ezkl version: \\\", ezkl.__version__)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"osjj-0Ta3E8O\"\n      },\n      \"source\": [\n        \"**Create Computational Graph**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"x1vl9ZXF3EEW\",\n        \"outputId\": \"bda21d02-fe5f-4fb2-8106-f51a8e2e67aa\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from torch import nn\\n\",\n        \"import torch\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class Model(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(Model, self).__init__()\\n\",\n        \"\\n\",\n        \"    # x is a time series \\n\",\n        \"    def forward(self, x):\\n\",\n        \"        return [torch.mean(x)]\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"circuit = Model()\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"x = 0.1*torch.rand(1,*[1,5], requires_grad=True)\\n\",\n        \"\\n\",\n        \"# # print(torch.__version__)\\n\",\n        \"device = torch.device(\\\"cuda:0\\\" if torch.cuda.is_available() else \\\"cpu\\\")\\n\",\n        \"\\n\",\n        \"print(device)\\n\",\n        \"\\n\",\n        \"circuit.to(device)\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"circuit.eval()\\n\",\n        \"\\n\",\n        \"# Export the model\\n\",\n        \"torch.onnx.export(circuit,               # model being run\\n\",\n        \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      \\\"lol.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=11,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"# export(circuit, input_shape=[1, 20])\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"E3qCeX-X5xqd\"\n      },\n      \"source\": [\n        \"**Set Data Source and Get Data**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"6RAMplxk5xPk\",\n        \"outputId\": \"bd2158fe-0c00-44fd-e632-6a3f70cdb7c9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import getpass\\n\",\n        \"# make an input.json file from the df above\\n\",\n        \"input_filename = os.path.join('input.json')\\n\",\n        \"\\n\",\n        \"pg_input_file = dict(input_data = {\\n\",\n        \"  \\\"host\\\": \\\"localhost\\\",\\n\",\n        \"  # make sure you replace this with your own username\\n\",\n        \"  \\\"user\\\": getpass.getuser(),\\n\",\n        \"  \\\"dbname\\\": \\\"shovel\\\",\\n\",\n        \"  \\\"password\\\": \\\"\\\",\\n\",\n        \"  \\\"query\\\": \\\"SELECT v FROM usdc ORDER BY block_num DESC LIMIT 5\\\",\\n\",\n        \"  \\\"port\\\": \\\"5432\\\",\\n\",\n        \"})\\n\",\n        \"\\n\",\n        \"json_formatted_str = json.dumps(pg_input_file, indent=2)\\n\",\n        \"print(json_formatted_str)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump(pg_input_file, open(input_filename, 'w' ))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# this corresponds to 4 batches\\n\",\n        \"calibration_filename = os.path.join('calibration.json')\\n\",\n        \"\\n\",\n        \"pg_cal_file = dict(input_data = {\\n\",\n        \"  \\\"host\\\": \\\"localhost\\\",\\n\",\n        \"  # make sure you replace this with your own username\\n\",\n        \"  \\\"user\\\": getpass.getuser(),\\n\",\n        \"  \\\"dbname\\\": \\\"shovel\\\",\\n\",\n        \"  \\\"password\\\": \\\"\\\",\\n\",\n        \"  \\\"query\\\": \\\"SELECT v FROM usdc ORDER BY block_num DESC LIMIT 20\\\",\\n\",\n        \"  \\\"port\\\": \\\"5432\\\",\\n\",\n        \"})\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( pg_cal_file, open(calibration_filename, 'w' ))\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"eLJ7oirQ_HQR\"\n      },\n      \"source\": [\n        \"**EZKL Workflow**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"rNw0C9QL6W88\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import subprocess\\n\",\n        \"import os\\n\",\n        \"\\n\",\n        \"onnx_filename = os.path.join('lol.onnx')\\n\",\n        \"compiled_filename = os.path.join('lol.compiled')\\n\",\n        \"settings_filename = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"# Generate settings using ezkl\\n\",\n        \"res = ezkl.gen_settings(onnx_filename, settings_filename)\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"res = ezkl.calibrate_settings(input_filename, onnx_filename, settings_filename, \\\"resources\\\")\\n\",\n        \"\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"ezkl.compile_circuit(onnx_filename, compiled_filename, settings_filename)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"4MmE9SX66_Il\",\n        \"outputId\": \"16403639-66a4-4280-ac7f-6966b75de5a3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# generate settings\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# show the settings.json\\n\",\n        \"with open(\\\"settings.json\\\") as f:\\n\",\n        \"  data = json.load(f)\\n\",\n        \"  json_formatted_str = json.dumps(data, indent=2)\\n\",\n        \"\\n\",\n        \"  print(json_formatted_str)\\n\",\n        \"\\n\",\n        \"assert os.path.exists(\\\"settings.json\\\")\\n\",\n        \"assert os.path.exists(\\\"input.json\\\")\\n\",\n        \"assert os.path.exists(\\\"lol.onnx\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"fULvvnK7_CMb\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# setup the proof\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_filename,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_filename)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"witness_path = \\\"witness.json\\\"\\n\",\n        \"\\n\",\n        \"# generate the witness\\n\",\n        \"res = ezkl.gen_witness(\\n\",\n        \"        input_filename,\\n\",\n        \"        compiled_filename,\\n\",\n        \"        witness_path\\n\",\n        \"    )\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"Oog3j6Kd-Wed\",\n        \"outputId\": \"5839d0c1-5b43-476e-c2f8-6707de562260\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# prove the zk circuit\\n\",\n        \"# GENERATE A PROOF\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_filename,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\\"single\\\"\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"print(\\\"proved\\\")\\n\",\n        \"\\n\",\n        \"assert os.path.isfile(proof_path)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# kill all shovel process \\n\",\n        \"os.system(\\\"pkill -f shovel\\\")\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.12.2\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/mnist_classifier.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"6ypZa6jg0rZy\"\n      },\n      \"source\": [\n        \"## Mnist Clan-ssifier ;)\\n\",\n        \"\\n\",\n        \"Here we demonstrate how to use the EZKL package to build an MNIST classifier for on-chain handrawn digit recognition.\\n\",\n        \"The proofs get submitted to a contract that assigns the users account to a digit clan (0-9). The contract keeps track of the member count of each clan. The clan with the most members is the winner!\\n\",\n        \"\\n\",\n        \"![zk-gaming-diagram-transformed](https://file.notion.so/f/f/f9535faf-4480-4499-9059-a48ba240eaa9/cd13414a-ecd8-4b8f-90a1-8a2311baa278/Untitled.png?id=365d66ee-e653-4ec3-8eb6-6d2b6306455a&table=block&spaceId=f9535faf-4480-4499-9059-a48ba240eaa9&expirationTimestamp=1701568800000&signature=VJ9p3YsOjYjeLxmkVEWOJw_3VmM6IBkTYxMwQUFKeus&downloadName=Untitled.png)\\n\",\n        \"> **A typical ZK application flow**. For all the image classifictiton hackers out there \u2014 this is an fairly straight forward example. A user computes a ZKML-proof that they have calculated a valid classification of a hand drawn digit from a MNIST trained lenet model. They submit this proof to a verifier contract which governs a set of clans, along with the output values of the model (length 10 tensor whereby the index with the max value represented the prediction), and the clan count updates according the lenets model's prediction. \"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"Fm2DMmXW0rZ0\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"torch\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"torchvision\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"tf2onnx\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"# make sure you have the dependencies required here already installed\\n\",\n        \"import ezkl\\n\",\n        \"import os\\n\",\n        \"import json\\n\",\n        \"import time\\n\",\n        \"import random\\n\",\n        \"import logging\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# uncomment for more descriptive logging\\n\",\n        \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n        \"logging.basicConfig(format=FORMAT)\\n\",\n        \"logging.getLogger().setLevel(logging.INFO)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"jbRkAJLz0rZ1\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import torch\\n\",\n        \"import torch.nn as nn\\n\",\n        \"import torch.nn.functional as F\\n\",\n        \"\\n\",\n        \"class LeNet(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(LeNet, self).__init__()\\n\",\n        \"        # Convolutional encoder\\n\",\n        \"        self.conv1 = nn.Conv2d(1, 6, 5)  # 1 input channel, 6 output channels, 5x5 kernel\\n\",\n        \"        self.conv2 = nn.Conv2d(6, 16, 5) # 6 input channels, 16 output channels, 5x5 kernel\\n\",\n        \"\\n\",\n        \"        # Fully connected layers / Dense block\\n\",\n        \"        self.fc1 = nn.Linear(16 * 4 * 4, 120) \\n\",\n        \"        self.fc2 = nn.Linear(120, 84)         # 120 inputs, 84 outputs\\n\",\n        \"        self.fc3 = nn.Linear(84, 10)          # 84 inputs, 10 outputs (number of classes)\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        # Convolutional block\\n\",\n        \"        x = F.avg_pool2d(F.sigmoid(self.conv1(x)), (2, 2)) # Convolution -> Sigmoid -> Avg Pool\\n\",\n        \"        x = F.avg_pool2d(F.sigmoid(self.conv2(x)), (2, 2)) # Convolution -> Sigmoid -> Avg Pool\\n\",\n        \"\\n\",\n        \"        # Flattening\\n\",\n        \"        x = x.view(x.size(0), -1)\\n\",\n        \"\\n\",\n        \"        # Fully connected layers\\n\",\n        \"        x = F.sigmoid(self.fc1(x))\\n\",\n        \"        x = F.sigmoid(self.fc2(x))\\n\",\n        \"        x = self.fc3(x)  # No activation function here, will use CrossEntropyLoss later\\n\",\n        \"        return x\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"8yYNrvus0rZ2\",\n        \"outputId\": \"d3ae2380-fa03-4368-9bea-46c38a65ddca\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import numpy as np\\n\",\n        \"import os\\n\",\n        \"import torch\\n\",\n        \"from torchvision.datasets import mnist\\n\",\n        \"from torch.nn import CrossEntropyLoss\\n\",\n        \"from torch.optim import Adam  # Import Adam\\n\",\n        \"from torch.utils.data import DataLoader\\n\",\n        \"from torchvision.transforms import ToTensor\\n\",\n        \"\\n\",\n        \"def normalize_img(image, label):\\n\",\n        \"  return torch.round(image), label\\n\",\n        \"\\n\",\n        \"device = 'cuda' if torch.cuda.is_available() else 'cpu'\\n\",\n        \"batch_size = 256\\n\",\n        \"train_dataset = mnist.MNIST(root='./train', train=True, transform=ToTensor(), download=True)\\n\",\n        \"test_dataset = mnist.MNIST(root='./test', train=False, transform=ToTensor(), download=True)\\n\",\n        \"train_loader = DataLoader(train_dataset, batch_size=batch_size)\\n\",\n        \"test_loader = DataLoader(test_dataset, batch_size=batch_size)\\n\",\n        \"model = LeNet().to(device)\\n\",\n        \"adam = Adam(model.parameters())  # Using Adam with a learning rate of 1e-3\\n\",\n        \"loss_fn = CrossEntropyLoss()\\n\",\n        \"all_epoch = 25\\n\",\n        \"prev_acc = 0\\n\",\n        \"for current_epoch in range(all_epoch):\\n\",\n        \"    model.train()\\n\",\n        \"    for idx, (train_x, train_label) in enumerate(train_loader):\\n\",\n        \"        train_x = train_x.to(device)\\n\",\n        \"        # normalize the image to 0 or 1 to reflect the inputs from the drawing board\\n\",\n        \"        train_x = train_x.round()\\n\",\n        \"        train_label = train_label.to(device)\\n\",\n        \"        adam.zero_grad()  # Use adam optimizer\\n\",\n        \"        predict_y = model(train_x.float())\\n\",\n        \"        loss = loss_fn(predict_y, train_label.long())\\n\",\n        \"        loss.backward()\\n\",\n        \"        adam.step()  # Use adam optimizer\\n\",\n        \"    all_correct_num = 0\\n\",\n        \"    all_sample_num = 0\\n\",\n        \"    model.eval()\\n\",\n        \"\\n\",\n        \"    for idx, (test_x, test_label) in enumerate(test_loader):\\n\",\n        \"        test_x = test_x.to(device)\\n\",\n        \"         # normalize the image to 0 or 1 to reflect the inputs from the drawing board\\n\",\n        \"        test_x = test_x.round()\\n\",\n        \"        test_label = test_label.to(device)\\n\",\n        \"        predict_y = model(test_x.float()).detach()\\n\",\n        \"        predict_y = torch.argmax(predict_y, dim=-1)\\n\",\n        \"        current_correct_num = predict_y == test_label\\n\",\n        \"        all_correct_num += np.sum(current_correct_num.to('cpu').numpy(), axis=-1)\\n\",\n        \"        all_sample_num += current_correct_num.shape[0]\\n\",\n        \"    acc = all_correct_num / all_sample_num\\n\",\n        \"    print('test accuracy: {:.3f}'.format(acc), flush=True)\\n\",\n        \"    if not os.path.isdir(\\\"models\\\"):\\n\",\n        \"        os.mkdir(\\\"models\\\")\\n\",\n        \"    torch.save(model, 'models/mnist_{:.3f}.pkl'.format(acc))\\n\",\n        \"    prev_acc = acc\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"import matplotlib.pyplot as plt\\n\",\n        \"import numpy as np\\n\",\n        \"from matplotlib import colors\\n\",\n        \"from scipy import stats\\n\",\n        \"n_bins = 100\\n\",\n        \"# whats the smallest parameter in this model ?\\n\",\n        \"minimum_abs_val = 100000\\n\",\n        \"params_abs = []\\n\",\n        \"for param in model.parameters():\\n\",\n        \"  if param.abs().min() < minimum_abs_val:\\n\",\n        \"    minimum_abs_val = param.abs().min()\\n\",\n        \"  params_abs.extend(param.abs().detach().numpy().flatten().tolist())\\n\",\n        \"\\n\",\n        \"print(minimum_abs_val)\\n\",\n        \"\\n\",\n        \"xx = np.linspace(0, 0.2, 1000)\\n\",\n        \"\\n\",\n        \"kde = stats.gaussian_kde(params_abs)\\n\",\n        \"fig, ax = plt.subplots(figsize = (6,4))\\n\",\n        \"\\n\",\n        \"ax.set_xlim(0, 0.2)\\n\",\n        \"\\n\",\n        \"# N is the count in each bin, bins is the lower-limit of the bin\\n\",\n        \"N, bins, patches = ax.hist(params_abs, bins=n_bins, density = True, alpha =0.65)\\n\",\n        \"ax.plot(xx, kde(xx))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"ax.set_ylim(0, 14)\\n\",\n        \"ax.set_yticklabels([])\\n\",\n        \"ax.set_ylabel(\\\"\\\")\\n\",\n        \"plt.style.use(\\\"bmh\\\")\\n\",\n        \"ax.set_xticks([1.0/128.0, 1.0/32.0, 1.0/16.0])\\n\",\n        \"ax.set_xticklabels([\\\"1/2^7\\\", \\\"1/2^6\\\", \\\"1/2^5\\\"])\\n\",\n        \"ax.grid(False)\\n\",\n        \"# Calculate percentiles\\n\",\n        \"quant_5, quant_25, quant_50, quant_75, quant_95 = np.quantile(params_abs, 0.05), np.quantile(params_abs, 0.25), np.quantile(params_abs, 0.5), np.quantile(params_abs, 0.75), np.quantile(params_abs, 0.95)\\n\",\n        \"\\n\",\n        \"# [quantile, opacity, length]\\n\",\n        \"quants = [[quant_5, 0.6, 0.16], [quant_25, 0.8, 0.26], [quant_50, 1, 0.36],  [quant_75, 0.8, 0.46], [quant_95, 0.6, 0.56]]\\n\",\n        \"\\n\",\n        \"# Plot the lines with a loop\\n\",\n        \"for i in quants:\\n\",\n        \"    ax.axvline(i[0], alpha = i[1], ymax = i[2], linestyle = \\\":\\\")\\n\",\n        \"\\n\",\n        \"# Annotations\\n\",\n        \"ax.text(quant_5, 14 * 0.17, \\\"5th\\\", size = 10, alpha = 0.8)\\n\",\n        \"ax.text(quant_25, 14 * 0.27, \\\"25th\\\", size = 10, alpha = 0.85)\\n\",\n        \"ax.text(quant_50, 14 * 0.37, \\\"50th\\\", size = 10, alpha = 1)\\n\",\n        \"ax.text(quant_75, 14 * 0.47, \\\"75th\\\", size = 10, alpha = 0.85)\\n\",\n        \"ax.text(quant_95, 14 * 0.57, \\\"95th Percentile\\\", size = 10, alpha =.8)\\n\",\n        \"\\n\",\n        \"ax.set_title(\\\"Absolute value of parameters\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"tmGo25eb0rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import os\\n\",\n        \"\\n\",\n        \"model_path = os.path.join('network_lenet.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('key.pk')\\n\",\n        \"vk_path = os.path.join('key.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"RfFjaXrM0rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import torch\\n\",\n        \"import json\\n\",\n        \"\\n\",\n        \"model.eval()  # Set the model to evaluation mode\\n\",\n        \"\\n\",\n        \"# # Fetch a single data point from the train_dataset\\n\",\n        \"# # Ensure train_dataset is already loaded and accessible\\n\",\n        \"train_data_point, _ = next(iter(train_dataset))\\n\",\n        \"train_data_point = train_data_point.unsqueeze(0)  # Add a batch dimension\\n\",\n        \"\\n\",\n        \"# Verify the device (CPU or CUDA) and transfer the data point to the same device as the model\\n\",\n        \"device = 'cuda' if torch.cuda.is_available() else 'cpu'\\n\",\n        \"train_data_point = train_data_point.to(device)\\n\",\n        \"\\n\",\n        \"# # Export the model to ONNX format\\n\",\n        \"torch.onnx.export(model, train_data_point, model_path, export_params=True, opset_version=12, do_constant_folding=True, input_names=['input_0'], output_names=['output'])\\n\",\n        \"\\n\",\n        \"# Convert the tensor to numpy array and reshape it for JSON serialization\\n\",\n        \"x = train_data_point.cpu().detach().numpy().reshape([-1]).tolist()\\n\",\n        \"data = {'input_data': [x]}\\n\",\n        \"with open('input.json', 'w') as f:\\n\",\n        \"    json.dump(data, f)\\n\",\n        \"\\n\",\n        \"print(f\\\"Model exported to {model_path} and input data saved to input.json\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"dS-yXte30rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import ezkl\\n\",\n        \"\\n\",\n        \"run_args = ezkl.PyRunArgs()\\n\",\n        \"run_args.input_visibility = \\\"private\\\"\\n\",\n        \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n        \"run_args.output_visibility = \\\"public\\\"\\n\",\n        \"run_args.num_inner_cols = 2\\n\",\n        \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n        \"\\n\",\n        \"# Capture set of data points\\n\",\n        \"num_data_points = 8\\n\",\n        \"\\n\",\n        \"# Fetch 30 data points from the train_dataset\\n\",\n        \"data_points = []\\n\",\n        \"for i, (data_point, _) in enumerate(train_dataset):\\n\",\n        \"    if i >= num_data_points:\\n\",\n        \"        break\\n\",\n        \"    data_points.append(data_point)\\n\",\n        \"\\n\",\n        \"# Stack the data points to create a batch\\n\",\n        \"train_data_batch = torch.stack(data_points)\\n\",\n        \"\\n\",\n        \"# Add a batch dimension if not already present\\n\",\n        \"if train_data_batch.dim() == 3:\\n\",\n        \"    train_data_batch = train_data_batch.unsqueeze(0)\\n\",\n        \"\\n\",\n        \"x = train_data_batch.cpu().detach().numpy().reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [x])\\n\",\n        \"\\n\",\n        \"cal_path = os.path.join('cal_data.json')\\n\",\n        \"\\n\",\n        \"# Serialize data into file:\\n\",\n        \"json.dump( data, open(cal_path, 'w' ))\\n\",\n        \"\\n\",\n        \"!RUST_LOG=trace\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\", scales=[2,7])\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"pGb1nj720rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"umpLxVAI0rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"syLy2Kt90rZ3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate the witness file\\n\",\n        \"witness_path = \\\"witness.json\\\"\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"65u_ObBQ0rZ4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"c8GIoMD40rZ4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n        \"# WE GOT KEYS\\n\",\n        \"# WE GOT CIRCUIT PARAMETERS\\n\",\n        \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n        \"\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"vkIutAhR0rZ4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"KmpQBZUT0rZ4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# VERIFY IT\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"CZ2CYQdm0rZ4\"\n      },\n      \"source\": [\n        \"We can now create an EVM / `.sol` verifier that can be deployed on chain to verify submitted proofs using a view function.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"jASymUWQ0rZ4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"abi_path = 'test.abi'\\n\",\n        \"sol_code_path = 'test_1.sol'\\n\",\n        \"\\n\",\n        \"res = ezkl.create_evm_verifier(\\n\",\n        \"        vk_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        sol_code_path,\\n\",\n        \"        abi_path,\\n\",\n        \"    )\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"-icN2yw60rZ5\"\n      },\n      \"source\": [\n        \"## Verify on the evm\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"sTLsLwaC0rZ5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Make sure anvil is running locally first\\n\",\n        \"# run with $ anvil -p 3030\\n\",\n        \"# we use the default anvil node here\\n\",\n        \"import json\\n\",\n        \"\\n\",\n        \"address_path = os.path.join(\\\"address.json\\\")\\n\",\n        \"\\n\",\n        \"res = ezkl.deploy_evm(\\n\",\n        \"    address_path,\\n\",\n        \"    sol_code_path,\\n\",\n        \"    'http://127.0.0.1:3030'\\n\",\n        \")\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"with open(address_path, 'r') as file:\\n\",\n        \"    addr = file.read().rstrip()\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"PrSyQK4B0rZ5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# make sure anvil is running locally\\n\",\n        \"# $ anvil -p 3030\\n\",\n        \"\\n\",\n        \"res = ezkl.verify_evm(\\n\",\n        \"    addr,\\n\",\n        \"    proof_path,\\n\",\n        \"    \\\"http://127.0.0.1:3030\\\"\\n\",\n        \")\\n\",\n        \"assert res == True\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/mnist_gan.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"\\n\",\n                \"Credits to [geohot](https://github.com/geohot/ai-notebooks/blob/master/mnist_gan.ipynb) for most of this code\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"tf2onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import time\\n\",\n                \"import random\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"import tensorflow as tf\\n\",\n                \"from tensorflow.keras.optimizers import Adam\\n\",\n                \"from tensorflow.keras.layers import *\\n\",\n                \"from tensorflow.keras.models import Model\\n\",\n                \"from tensorflow.keras.datasets import mnist\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.INFO)\\n\",\n                \"\\n\",\n                \"# Can we build a simple GAN that can produce all 10 mnist digits?\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"(x_train, y_train), (x_test, y_test) = mnist.load_data()\\n\",\n                \"x_train, x_test = [x/255.0 for x in [x_train, x_test]]\\n\",\n                \"y_train, y_test = [tf.keras.utils.to_categorical(x) for x in [y_train, y_test]]\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {\n                \"scrolled\": false\n            },\n            \"outputs\": [],\n            \"source\": [\n                \"ZDIM = 100\\n\",\n                \"\\n\",\n                \"opt = Adam()\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# discriminator\\n\",\n                \"# 0 if it's fake, 1 if it's real\\n\",\n                \"x = in1 = Input((28,28))\\n\",\n                \"x = Reshape((28,28,1))(x)\\n\",\n                \"\\n\",\n                \"x = Conv2D(64, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Conv2D(128, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Flatten()(x)\\n\",\n                \"x = Dense(128)(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"x = Dense(1, activation='sigmoid')(x)\\n\",\n                \"dm = Model(in1, x)\\n\",\n                \"dm.compile(opt, 'binary_crossentropy')\\n\",\n                \"dm.summary()\\n\",\n                \"\\n\",\n                \"# generator, output digits\\n\",\n                \"x = in1 = Input((ZDIM,))\\n\",\n                \"\\n\",\n                \"x = Dense(7*7*64)(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"x = Reshape((7,7,64))(x)\\n\",\n                \"\\n\",\n                \"x = Conv2DTranspose(128, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Conv2DTranspose(1, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"x = Activation('sigmoid')(x)\\n\",\n                \"x = Reshape((28,28))(x)\\n\",\n                \"\\n\",\n                \"gm = Model(in1, x)\\n\",\n                \"gm.compile('adam', 'mse')\\n\",\n                \"gm.output_names=['output']\\n\",\n                \"gm.summary()\\n\",\n                \"\\n\",\n                \"opt = Adam()\\n\",\n                \"\\n\",\n                \"# GAN\\n\",\n                \"dm.trainable = False\\n\",\n                \"x = dm(gm.output)\\n\",\n                \"tm = Model(gm.input, x)\\n\",\n                \"tm.compile(opt, 'binary_crossentropy')\\n\",\n                \"\\n\",\n                \"dlosses, glosses = [], []\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {\n                \"scrolled\": false\n            },\n            \"outputs\": [],\n            \"source\": [\n                \"import numpy as np\\n\",\n                \"from matplotlib.pyplot import figure, imshow, show\\n\",\n                \"\\n\",\n                \"BS = 256\\n\",\n                \"\\n\",\n                \"# GAN training loop\\n\",\n                \"# make larger if you want it to look better\\n\",\n                \"for i in range(1):\\n\",\n                \"  # train discriminator\\n\",\n                \"  dm.trainable = True\\n\",\n                \"  real_i = x_train[np.random.choice(x_train.shape[0], BS)]\\n\",\n                \"  fake_i = gm.predict_on_batch(np.random.normal(0,1,size=(BS,ZDIM)))\\n\",\n                \"  dloss_r = dm.train_on_batch(real_i, np.ones(BS))\\n\",\n                \"  dloss_f = dm.train_on_batch(fake_i, np.zeros(BS))\\n\",\n                \"  dloss = (dloss_r + dloss_f)/2\\n\",\n                \"\\n\",\n                \"  # train generator\\n\",\n                \"  dm.trainable = False\\n\",\n                \"  gloss_0 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\\n\",\n                \"  gloss_1 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\\n\",\n                \"  gloss = (gloss_0 + gloss_1)/2\\n\",\n                \"\\n\",\n                \"  if i%50 == 0:\\n\",\n                \"    print(\\\"%4d: dloss:%8.4f   gloss:%8.4f\\\" % (i, dloss, gloss))\\n\",\n                \"  dlosses.append(dloss)\\n\",\n                \"  glosses.append(gloss)\\n\",\n                \"    \\n\",\n                \"  if i%250 == 0:\\n\",\n                \"    \\n\",\n                \"    figure(figsize=(16,16))\\n\",\n                \"    imshow(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\\n\",\n                \"    show()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"from matplotlib.pyplot import plot, legend\\n\",\n                \"figure(figsize=(8,8))\\n\",\n                \"plot(dlosses[100:], label=\\\"Discriminator Loss\\\")\\n\",\n                \"plot(glosses[100:], label=\\\"Generator Loss\\\")\\n\",\n                \"legend()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = []\\n\",\n                \"for i in range(10):\\n\",\n                \"  x.append(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\\n\",\n                \"imshow(np.concatenate(x, axis=0))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os \\n\",\n                \"\\n\",\n                \"model_path = os.path.join('gan.onnx')\\n\",\n                \"compiled_model_path = os.path.join('gan.compiled')\\n\",\n                \"pk_path = os.path.join('gan.pk')\\n\",\n                \"vk_path = os.path.join('gan.vk')\\n\",\n                \"settings_path = os.path.join('gan_settings.json')\\n\",\n                \"srs_path = os.path.join('gan_kzg.srs')\\n\",\n                \"witness_path = os.path.join('gan_witness.json')\\n\",\n                \"data_path = os.path.join('gan_input.json')\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we export the _generator_ to onnx\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import numpy as np\\n\",\n                \"import tf2onnx\\n\",\n                \"import tensorflow as tf\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"shape = [1, ZDIM]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*np.random.rand(1,*shape)\\n\",\n                \"\\n\",\n                \"spec = tf.TensorSpec(shape, tf.float32, name='input_0')\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"tf2onnx.convert.from_keras(gm, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\\n\",\n                \"\\n\",\n                \"data_array = x.reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"private\\\"\\n\",\n                \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (0.2 * np.random.rand(20, *shape)).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\", scales=[0,6])\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"witness_path = \\\"gan_witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# uncomment to mock prove\\n\",\n                \"# res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n                \"# assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.12.2\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/mnist_gan_proof_splitting.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Proof splitting\\n\",\n                \"\\n\",\n                \"Here we showcase how to split a larger circuit into multiple smaller proofs. This is useful if you want to prove over multiple machines, or if you want to split a proof into multiple parts to reduce the memory requirements.\\n\",\n                \"\\n\",\n                \"We showcase how to do this in the case where:\\n\",\n                \"- intermediate calculations need to be kept secret (but not blinded !) and we need to use the low overhead kzg commitment scheme detailed [here](https://blog.ezkl.xyz/post/commits/) to stitch the circuits together.\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 1,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"tf2onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import time\\n\",\n                \"import random\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"import tensorflow as tf\\n\",\n                \"from tensorflow.keras.optimizers import Adam\\n\",\n                \"from tensorflow.keras.layers import *\\n\",\n                \"from tensorflow.keras.models import Model\\n\",\n                \"from tensorflow.keras.datasets import mnist\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.INFO)\\n\",\n                \"\\n\",\n                \"# Can we build a simple GAN that can produce all 10 mnist digits?\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 2,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"(x_train, y_train), (x_test, y_test) = mnist.load_data()\\n\",\n                \"x_train, x_test = [x/255.0 for x in [x_train, x_test]]\\n\",\n                \"y_train, y_test = [tf.keras.utils.to_categorical(x) for x in [y_train, y_test]]\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 3,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\">Model: \\\"functional_1\\\"</span>\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1mModel: \\\"functional_1\\\"\\u001b[0m\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\">\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503<span style=\\\"font-weight: bold\\\"> Layer (type)                    </span>\u2503<span style=\\\"font-weight: bold\\\"> Output Shape           </span>\u2503<span style=\\\"font-weight: bold\\\">       Param # </span>\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 input_layer (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">InputLayer</span>)        \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>)         \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Reshape</span>)               \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)      \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2D</span>)                 \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">64</span>)     \u2502         <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1,664</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization             \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">64</span>)     \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">256</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                       \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">64</span>)     \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2D</span>)               \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)      \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">204,928</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_1           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)      \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">512</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)      \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 flatten (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Flatten</span>)               \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">6272</span>)           \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Dense</span>)                   \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)            \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">802,944</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_2           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)            \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">512</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_2 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)            \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Dense</span>)                 \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)              \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">129</span> \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503\\u001b[1m \\u001b[0m\\u001b[1mLayer (type)                   \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1mOutput Shape          \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1m      Param #\\u001b[0m\\u001b[1m \\u001b[0m\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 input_layer (\\u001b[38;5;33mInputLayer\\u001b[0m)        \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m)         \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape (\\u001b[38;5;33mReshape\\u001b[0m)               \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)      \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d (\\u001b[38;5;33mConv2D\\u001b[0m)                 \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m64\\u001b[0m)     \u2502         \\u001b[38;5;34m1,664\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization             \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m64\\u001b[0m)     \u2502           \\u001b[38;5;34m256\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu (\\u001b[38;5;33mELU\\u001b[0m)                       \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m64\\u001b[0m)     \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_1 (\\u001b[38;5;33mConv2D\\u001b[0m)               \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)      \u2502       \\u001b[38;5;34m204,928\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_1           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)      \u2502           \\u001b[38;5;34m512\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_1 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)      \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 flatten (\\u001b[38;5;33mFlatten\\u001b[0m)               \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m6272\\u001b[0m)           \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense (\\u001b[38;5;33mDense\\u001b[0m)                   \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)            \u2502       \\u001b[38;5;34m802,944\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_2           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)            \u2502           \\u001b[38;5;34m512\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_2 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)            \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense_1 (\\u001b[38;5;33mDense\\u001b[0m)                 \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)              \u2502           \\u001b[38;5;34m129\\u001b[0m \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Total params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1,010,945</span> (3.86 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Total params: \\u001b[0m\\u001b[38;5;34m1,010,945\\u001b[0m (3.86 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1,010,305</span> (3.85 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Trainable params: \\u001b[0m\\u001b[38;5;34m1,010,305\\u001b[0m (3.85 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Non-trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">640</span> (2.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Non-trainable params: \\u001b[0m\\u001b[38;5;34m640\\u001b[0m (2.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\">Model: \\\"functional_3\\\"</span>\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1mModel: \\\"functional_3\\\"\\u001b[0m\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\">\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503<span style=\\\"font-weight: bold\\\"> Layer (type)                    </span>\u2503<span style=\\\"font-weight: bold\\\"> Output Shape           </span>\u2503<span style=\\\"font-weight: bold\\\">       Param # </span>\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 input_layer_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">InputLayer</span>)      \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">100</span>)            \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense_2 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Dense</span>)                 \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">316,736</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_3           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502        <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">12,544</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_3 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Reshape</span>)             \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">64</span>)       \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose                \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">204,928</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2DTranspose</span>)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_4           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">512</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_4 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose_1              \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)      \u2502         <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3,201</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2DTranspose</span>)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 activation (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Activation</span>)         \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)      \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_2 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Reshape</span>)             \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>)         \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503\\u001b[1m \\u001b[0m\\u001b[1mLayer (type)                   \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1mOutput Shape          \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1m      Param #\\u001b[0m\\u001b[1m \\u001b[0m\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 input_layer_1 (\\u001b[38;5;33mInputLayer\\u001b[0m)      \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m100\\u001b[0m)            \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 dense_2 (\\u001b[38;5;33mDense\\u001b[0m)                 \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502       \\u001b[38;5;34m316,736\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_3           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502        \\u001b[38;5;34m12,544\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_3 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_1 (\\u001b[38;5;33mReshape\\u001b[0m)             \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m64\\u001b[0m)       \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose                \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502       \\u001b[38;5;34m204,928\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mConv2DTranspose\\u001b[0m)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_4           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502           \\u001b[38;5;34m512\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_4 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose_1              \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)      \u2502         \\u001b[38;5;34m3,201\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mConv2DTranspose\\u001b[0m)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 activation (\\u001b[38;5;33mActivation\\u001b[0m)         \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)      \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_2 (\\u001b[38;5;33mReshape\\u001b[0m)             \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m)         \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Total params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">537,921</span> (2.05 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Total params: \\u001b[0m\\u001b[38;5;34m537,921\\u001b[0m (2.05 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">531,393</span> (2.03 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Trainable params: \\u001b[0m\\u001b[38;5;34m531,393\\u001b[0m (2.03 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Non-trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">6,528</span> (25.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Non-trainable params: \\u001b[0m\\u001b[38;5;34m6,528\\u001b[0m (25.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                }\n            ],\n            \"source\": [\n                \"opt = Adam()\\n\",\n                \"ZDIM = 100\\n\",\n                \"\\n\",\n                \"# discriminator\\n\",\n                \"# 0 if it's fake, 1 if it's real\\n\",\n                \"x = in1 = Input((28,28))\\n\",\n                \"x = Reshape((28,28,1))(x)\\n\",\n                \"\\n\",\n                \"x = Conv2D(64, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Conv2D(128, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Flatten()(x)\\n\",\n                \"x = Dense(128)(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"x = Dense(1, activation='sigmoid')(x)\\n\",\n                \"dm = Model(in1, x)\\n\",\n                \"dm.compile(opt, 'binary_crossentropy')\\n\",\n                \"dm.summary()\\n\",\n                \"\\n\",\n                \"# generator, output digits\\n\",\n                \"x = in1 = Input((ZDIM,))\\n\",\n                \"\\n\",\n                \"x = Dense(7*7*64)(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"x = Reshape((7,7,64))(x)\\n\",\n                \"\\n\",\n                \"x = Conv2DTranspose(128, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"x = BatchNormalization()(x)\\n\",\n                \"x = ELU()(x)\\n\",\n                \"\\n\",\n                \"x = Conv2DTranspose(1, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"x = Activation('sigmoid')(x)\\n\",\n                \"x = Reshape((28,28))(x)\\n\",\n                \"\\n\",\n                \"gm = Model(in1, x)\\n\",\n                \"gm.compile('adam', 'mse')\\n\",\n                \"gm.summary()\\n\",\n                \"\\n\",\n                \"opt = Adam()\\n\",\n                \"\\n\",\n                \"# GAN\\n\",\n                \"dm.trainable = False\\n\",\n                \"x = dm(gm.output)\\n\",\n                \"tm = Model(gm.input, x)\\n\",\n                \"tm.compile(opt, 'binary_crossentropy')\\n\",\n                \"\\n\",\n                \"dlosses, glosses = [], []\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 4,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"name\": \"stdout\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"   0: dloss:  0.8063   gloss:  0.6461\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 42ms/step\\n\"\n                    ]\n                },\n                {\n                    \"data\": {\n                        \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAABQcAAACrCAYAAADb2yoEAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/H5lhTAAAACXBIWXMAAA9hAAAPYQGoP6dpAACNcklEQVR4nO39eZRlV3Xmi87TN3Ga6LuMyL5TKqWUlJJSCUIIK5EAGyPA1xhzjUxx8SsscQtwCzZQ+NnWe9S71wyXKXNHjbrGHlXYmLoGjGzAs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huiMiz/9icGlpSQYHByUYvLCq4KvuteJgMHj+iWbg314TzWQyNGhCXkG45gh5ZeGaI+SVh+uOkFcWrjlCXnm47kg2m105kzAgCSGEEEIIIYQQQgghqxY+HCSEEEIIIYQQQgghZJXyqn44GIvF5FOf+pTEYrFL3RRCVgVcc4S8snDNEfLKw3VHyCsL1xwhrzxcd+Sl8qoLSEIIIYQQQgghhBBCCHlleFX/cpAQQgghhBBCCCGEEPKTgw8HCSGEEEIIIYQQQghZpfDhICGEEEIIIYQQQgghqxQ+HCSEEEIIIYQQQgghZJXyqn04+LnPfU7Wr18v8Xhc9uzZI9///vcvdZMI+ZngP/7H/yiBQED92759+/nvy+Wy3HnnndLV1SWpVEre+c53ytTU1CVsMSE/fTz44IPy1re+VQYHByUQCMhXv/pV9X2r1ZJPfvKTMjAwIIlEQvbt2yfHjx9Xeebn5+U973mPZDIZaW9vl/e///2yvLz8CvaCkJ8eVlpzv/7rv272vje96U0qD9ccIRfP3XffLdddd52k02np7e2V22+/XY4eParyXMyZcmRkRH7+539eksmk9Pb2yu/8zu9IvV5/JbtCyE8NF7Pubr75ZrPf/ft//+9VHq474vGqfDj4pS99ST760Y/Kpz71KXniiSdk165dctttt8n09PSlbhohPxNcfvnlMjExcf7fQw89dP67j3zkI/L1r39dvvzlL8sDDzwg4+Pj8o53vOMStpaQnz4KhYLs2rVLPve5z7nff+Yzn5E///M/l89//vNy4MABaWtrk9tuu03K5fL5PO95z3vk0KFDcu+998o999wjDz74oPzGb/zGK9UFQn6qWGnNiYi86U1vUnvf3/7t36rvueYIuXgeeOABufPOO+WRRx6Re++9V2q1mtx6661SKBTO51npTNloNOTnf/7npVqtysMPPyx//dd/LV/4whfkk5/85KXoEiGvei5m3YmIfOADH1D73Wc+85nz33HdkRel9Srk+uuvb915553n041GozU4ONi6++67L2GrCPnZ4FOf+lRr165d7neLi4utSCTS+vKXv3z+s8OHD7dEpLV///5XqIWE/GwhIq2vfOUr59PNZrPV39/f+k//6T+d/2xxcbE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1Nm/e3Pqd3/mdVi6XU+Vw3RGPQKvVar2SDyMJIYQQQgghhBBCCCGvDl51moOEEEIIIYQQQgghhJBXBj4cJIQQQgghhBBCCCFklcKHg4QQQgghhBBCCCGErFL4cJAQQgghhBBCCCGEkFUKHw4SQgghhBBCCCGEELJK4cNBQgghhBBCCCGEEEJWKXw4SAghhBBCCCGEEELIKoUPBwkhhBBCCCGEEEIIWaXw4SAhhBBCCCGEEEIIIasUPhwkhBBCCCGEEEIIIWSVwoeDhBBCCCGEEEIIIYSsUvhwkBBCCCGEEEIIIYSQVcr/H9NxerZQIBl2AAAAAElFTkSuQmCC\",\n                        \"text/plain\": [\n                            \"<Figure size 1600x1600 with 1 Axes>\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                }\n            ],\n            \"source\": [\n                \"import numpy as np\\n\",\n                \"from matplotlib.pyplot import figure, imshow, show\\n\",\n                \"\\n\",\n                \"BS = 256\\n\",\n                \"\\n\",\n                \"# GAN training loop\\n\",\n                \"# make larger if you want it to look better\\n\",\n                \"for i in range(1):\\n\",\n                \"  # train discriminator\\n\",\n                \"  dm.trainable = True\\n\",\n                \"  real_i = x_train[np.random.choice(x_train.shape[0], BS)]\\n\",\n                \"  fake_i = gm.predict_on_batch(np.random.normal(0,1,size=(BS,ZDIM)))\\n\",\n                \"  dloss_r = dm.train_on_batch(real_i, np.ones(BS))\\n\",\n                \"  dloss_f = dm.train_on_batch(fake_i, np.zeros(BS))\\n\",\n                \"  dloss = (dloss_r + dloss_f)/2\\n\",\n                \"\\n\",\n                \"  # train generator\\n\",\n                \"  dm.trainable = False\\n\",\n                \"  gloss_0 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\\n\",\n                \"  gloss_1 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\\n\",\n                \"  gloss = (gloss_0 + gloss_1)/2\\n\",\n                \"\\n\",\n                \"  if i%50 == 0:\\n\",\n                \"    print(\\\"%4d: dloss:%8.4f   gloss:%8.4f\\\" % (i, dloss, gloss))\\n\",\n                \"  dlosses.append(dloss)\\n\",\n                \"  glosses.append(gloss)\\n\",\n                \"    \\n\",\n                \"  if i%250 == 0:\\n\",\n                \"    \\n\",\n                \"    figure(figsize=(16,16))\\n\",\n                \"    imshow(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\\n\",\n                \"    show()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 5,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"data\": {\n                        \"text/plain\": [\n                            \"<matplotlib.legend.Legend at 0x34f625160>\"\n                        ]\n                    },\n                    \"execution_count\": 5,\n                    \"metadata\": {},\n                    \"output_type\": \"execute_result\"\n                },\n                {\n                    \"data\": {\n                        \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAArMAAAKTCAYAAAAKS4AtAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/H5lhTAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA6CElEQVR4nO3de3RW5Z3o8V8CJKCSRG4JaADvICIoN5GuwUoUqlbxMiLHCzhOmY53UatYBKvTYr1UvFQde9p6tLVSr22p4iCotZKighcU8DgdFBUDWiQoKGCyzx8e3poKCMhreODzWetdrOz97Hc/OzvUbzf73SnIsiwLAABIUGFjTwAAADaXmAUAIFliFgCAZIlZAACSJWYBAEiWmAUAIFliFgCAZDVt7Ak0hvr6+li0aFG0bNkyCgoKGns6AAD8gyzL4sMPP4wOHTpEYeH6r79ulzG7aNGiqKysbOxpAADwJd56663Ydddd17t+u4zZli1bRsRn35ySkpJGng0AAP9o+fLlUVlZmeu29dkuY3btrQUlJSViFgBgK/Zlt4T6ABgAAMkSswAAJEvMAgCQrO3ynlkA2JbU1dXFmjVrGnsasEmaNWsWTZo0+crvI2YBIFFZlkVNTU0sW7assacCm6WsrCwqKiq+0nP/xSwAJGptyLZr1y522GEHvwiIZGRZFitXrowlS5ZERET79u03+73ELAAkqK6uLheyrVu3buzpwCZr0aJFREQsWbIk2rVrt9m3HPgAGAAkaO09sjvssEMjzwQ239qf369yz7eYBYCEubWAlG2Jn18xCwBAssQsAADJErMAwFapoKAgHn744by9/8iRI2Po0KFf6T2efPLJKCgo8Hi0RiRmAYCvzciRI6OgoCAKCgqiWbNmUV5eHocddlj84he/iPr6+gZj33333fjWt76Vt7nceOONceedd36l9zj44IPj3XffjdLS0i0zqf8v3yF/yCGHxPnnn5+39/86iVkA4Gs1ZMiQePfdd+ONN96IRx99NL75zW/GeeedF0cddVR8+umnuXEVFRVRXFy8xfdfV1cX9fX1UVpaGmVlZV/pvYqKir7yQ//zaXv4zXBiFgC2AVmWxcrVnzbKK8uyTZprcXFxVFRUxC677BIHHnhgXHbZZfG73/0uHn300QZXSj9/dXL16tVx9tlnR/v27aN58+bRqVOnmDBhQm7ssmXL4t/+7d+ivLw8mjdvHvvtt19Mnjw5IiLuvPPOKCsri9///vex7777RnFxcSxcuPALtxkccsghcc4558T5558fO++8c5SXl8fPfvazWLFiRZx++unRsmXL2HPPPePRRx/NbfOPtxms3ddjjz0WXbt2jZ122ikX72s999xzcdhhh0WbNm2itLQ0Bg4cGLNnz86t79y5c0REHHvssVFQUJD7OiLitttuiz322COKiopin332ibvvvrvB97agoCBuu+22OProo2PHHXeMH/7wh5t0btZ64IEHolu3blFcXBydO3eO66+/vsH6W2+9Nfbaa69o3rx5lJeXxwknnJBbd//990f37t2jRYsW0bp166iqqooVK1Zs1jw2hl+aAADbgI/X1MW+4x5rlH3PvXJw7FD01ZLi0EMPjR49esSDDz4Y//qv//qF9TfddFP8/ve/j9/+9rfRsWPHeOutt+Ktt96KiIj6+vr41re+FR9++GH86le/ij322CPmzp3b4CH8K1eujB//+Mfxv//3/47WrVtHu3bt1jmP//N//k9873vfi2effTYmTZoU//7v/x4PPfRQHHvssXHZZZfFDTfcEKeeemosXLhwvc/4XblyZVx33XVx9913R2FhYZxyyilx0UUXxa9//euIiPjwww9jxIgRcfPNN0eWZXH99dfHEUccEa+//nq0bNkynnvuuWjXrl388pe/jCFDhuSO46GHHorzzjsvJk6cGFVVVTF58uQ4/fTTY9ddd41vfvObuf1fccUVcfXVV8fEiROjadNNPy+zZs2KE088Ma644ooYNmxYzJgxI84888xo3bp1jBw5Mp5//vk499xz4+67746DDz44li5dGk8//XREfHZryPDhw+Oaa66JY489Nj788MN4+umnN/n/8GwKMQsAbBW6dOkSL7/88jrXLVy4MPbaa6/4xje+EQUFBdGpU6fcuscffzyeffbZmDdvXuy9994REbH77rs32H7NmjVx6623Ro8ePTY4hx49esTYsWMjImLMmDFx9dVXR5s2beI73/lORESMGzcubrvttnj55ZfjoIMOWud7rFmzJm6//fbYY489IiLi7LPPjiuvvDK3/tBDD20w/o477oiysrJ46qmn4qijjoq2bdtGRERZWVlUVFTkxl133XUxcuTIOPPMMyMiYvTo0fGXv/wlrrvuugYx+7/+1/+K008/fYPHuSE/+clPYtCgQXH55ZdHRMTee+8dc+fOjWuvvTZGjhwZCxcujB133DGOOuqoaNmyZXTq1CkOOOCAiPgsZj/99NM47rjjcueoe/fumz2XjSFmAWAb0KJZk5h75eBG2/eWkGXZeu89HTlyZBx22GGxzz77xJAhQ+Koo46Kww8/PCIiXnzxxdh1111zIbsuRUVFsf/++3/pHD4/pkmTJtG6desGMVZeXh4Rn/0K1vXZYYcdciEbEdG+ffsG4xcvXhxjx46NJ598MpYsWRJ1dXWxcuXKWLhw4QbnNm/evBg1alSDZQMGDIgbb7yxwbLevXtv8H2+zLx58+KYY475wn4mTpwYdXV1cdhhh0WnTp1i9913jyFDhsSQIUPi2GOPjR122CF69OgRgwYNiu7du8fgwYPj8MMPjxNOOCF23nnnrzSnDXHPLABsAwoKCmKHoqaN8tpSH36aN29e7Lbbbutcd+CBB8aCBQviqquuio8//jhOPPHE3H2aLVq0+NL3btGixUbNs1mzZg2+XvvUhc9/HRFfePLCl73H5/+ZfcSIEfHiiy/GjTfeGDNmzIgXX3wxWrduHatXr/7S+W2MHXfccYu8z/q0bNkyZs+eHb/5zW+iffv2MW7cuOjRo0csW7YsmjRpElOnTo1HH3009t1337j55ptjn332iQULFuRtPmIWAGh006dPjzlz5sTxxx+/3jElJSUxbNiw+NnPfhaTJk2KBx54IJYuXRr7779/vP322/F//+///RpnvPmeeeaZOPfcc+OII47Ifcjq/fffbzCmWbNmUVdX12BZ165d45lnnvnCe+27775bdH7r28/ee++du3+3adOmUVVVFddcc028/PLL8cYbb8T06dMj4rN4HzBgQPzgBz+IF154IYqKiuKhhx7aonP8PLcZAABfq1WrVkVNTU3U1dXF4sWLY8qUKTFhwoQ46qij4rTTTlvnNj/5yU+iffv2ccABB0RhYWHcd999UVFREWVlZTFw4MD4p3/6pzj++OPjJz/5Sey5554xf/78KCgoiCFDhnzNR/fl9tprr7j77rujd+/esXz58rj44ou/cHW5c+fOMW3atBgwYEAUFxfHzjvvHBdffHGceOKJccABB0RVVVX84Q9/iAcffDAef/zxzZrHe++9Fy+++GKDZe3bt48LL7ww+vTpE1dddVUMGzYsqqur45Zbbolbb701IiImT54c//M//xP/9E//FDvvvHM88sgjUV9fH/vss0/MnDkzpk2bFocffni0a9cuZs6cGe+991507dp1s+a4MVyZBQC+VlOmTIn27dtH586dY8iQIfHEE0/ETTfdFL/73e8aPIHg81q2bBnXXHNN9O7dO/r06RNvvPFGPPLII1FY+FnKPPDAA9GnT58YPnx47LvvvvG9733vC1c2txY///nP44MPPogDDzwwTj311Dj33HO/8HSF66+/PqZOnRqVlZW5D1cNHTo0brzxxrjuuuuiW7du8Z//+Z/xy1/+Mg455JDNmsc999wTBxxwQIPXz372szjwwAPjt7/9bdx7772x3377xbhx4+LKK6+MkSNHRsRnH0x78MEH49BDD42uXbvG7bffHr/5zW+iW7duUVJSEn/605/iiCOOiL333jvGjh0b119/fV5/+UVBls9nJWylli9fHqWlpVFbWxslJSWNPR0A2GSffPJJLFiwIHbbbbdo3rx5Y08HNsuGfo43ttdcmQUAIFliFgCAZIlZAACSJWYBAEiWmAUAIFliFgCAZIlZAACSJWYBAEiWmAUAIFliFgD4WtXU1MR5550Xe+65ZzRv3jzKy8tjwIABcdttt8XKlSsbe3obrXPnzjFx4sS8vf/IkSNj6NCheXv/bUXTxp4AALD9+J//+Z8YMGBAlJWVxY9+9KPo3r17FBcXx5w5c+KOO+6IXXbZJY4++uhGm1+WZVFXVxdNm359ibR69eooKir62va3rXFlFgD42px55pnRtGnTeP755+PEE0+Mrl27xu677x7HHHNM/PGPf4xvf/vbubHLli2Lf/3Xf422bdtGSUlJHHroofHSSy/l1l9xxRXRs2fPuPvuu6Nz585RWloaJ510Unz44Ye5MfX19TFhwoTYbbfdokWLFtGjR4+4//77c+uffPLJKCgoiEcffTR69eoVxcXF8ec//zn++te/xjHHHBPl5eWx0047RZ8+feLxxx/PbXfIIYfEm2++GRdccEEUFBREQUFBbt0DDzwQ3bp1i+Li4ujcuXNcf/31Db4HnTt3jquuuipOO+20KCkpiVGjRm3W9/Kpp56Kvn37RnFxcbRv3z4uvfTS+PTTT3Pr77///ujevXu0aNEiWrduHVVVVbFixYrccfft2zd23HHHKCsriwEDBsSbb765WfNobGIWALYFWRaxekXjvLJso6b4t7/9Lf7rv/4rzjrrrNhxxx3XOebzUfjP//zPsWTJknj00Udj1qxZceCBB8agQYNi6dKluTF//etf4+GHH47JkyfH5MmT46mnnoqrr746t37ChAlx1113xe233x6vvvpqXHDBBXHKKafEU0891WC/l156aVx99dUxb9682H///eOjjz6KI444IqZNmxYvvPBCDBkyJL797W/HwoULIyLiwQcfjF133TWuvPLKePfdd+Pdd9+NiIhZs2bFiSeeGCeddFLMmTMnrrjiirj88svjzjvvbLC/6667Lnr06BEvvPBCXH755Rv1/fu8d955J4444ojo06dPvPTSS3HbbbfFz3/+8/iP//iPiIh49913Y/jw4fEv//IvMW/evHjyySfjuOOOiyzL4tNPP42hQ4fGwIED4+WXX47q6uoYNWpUg+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qMHV1ojP/rn+mWee+cJ77b333tGkSZNNP4j16Nq1azzwwAORZVnu6uwzzzwTLVu2jF133TUiPgv7AQMGxIABA2LcuHHRqVOneOihh2L06NEREXHAAQfEAQccEGPGjIn+/fvHPffcI2YBADbk1ltvjQEDBkTv3r3jiiuuiP333z8KCwvjueeei/nz50evXr0iIqKqqir69+8fQ4cOjWuuuSb23nvvWLRoUfzxj3+MY489dqP+mb5ly5Zx0UUXxQUXXBD19fXxjW98I2pra+OZZ56JkpKSGDFixHq33WuvveLBBx+Mb3/721FQUBCXX3557orvWp07d44//elPcdJJJ0VxcXG0adMmLrzwwujTp09cddVVMWzYsKiuro5bbrklbr311s36ftXW1saLL77YYFnr1q3jzDPPjIkTJ8Y555wTZ599drz22msxfvz4GD16dBQWFsbMmTNj2rRpcfjhh0e7du1i5syZ8d5770XXrl1jwYIFcccdd8TRRx8dHTp0iNdeey1ef/31OO200zZrjo0u2w7V1tZmEZHV1tY29lQAYLN8/PHH2dy5c7OPP/64saeyyRYtWpSdffbZ2W677ZY1a9Ys22mnnbK+fftm1157bbZixYrcuOXLl2fnnHNO1qFDh6xZs2ZZZWVldvLJJ2cLFy7MsizLxo8fn/Xo0aPBe99www1Zp06dcl/X19dnEydOzPbZZ5+sWbNmWdu2bbPBgwdnTz31VJZlWfbEE09kEZF98MEHDd5nwYIF2Te/+c2sRYsWWWVlZXbLLbdkAwcOzM4777zcmOrq6mz//ffPiouLs88n1f3335/tu+++WbNmzbKOHTtm1157bYP37tSpU3bDDTd86fdpxIgRWUR84XXGGWdkWZZlTz75ZNanT5+sqKgoq6ioyC655JJszZo1WZZl2dy5c7PBgwdnbdu2zYqLi7O99947u/nmm7Msy7Kampps6NChWfv27bOioqKsU6dO2bhx47K6urovndOWtqGf443ttYIs28jnaWxDli9fHqWlpVFbWxslJSWNPR0A2GSffPJJLFiwIHbbbbdo3rx5Y08HNsuGfo43ttc8zQAAgGSJWQAAkiVmAQBIlpgFACBZYhYAErYdfo6bbciW+PkVswCQoLW/+WrlypWNPBPYfGt/fv/xN7ltCr80AQAS1KRJkygrK4slS5ZERMQOO+yQ+01QsLXLsixWrlwZS5YsibKysq/029HELAAkqqKiIiIiF7SQmrKystzP8eYSswCQqIKCgmjfvn20a9cu1qxZ09jTgU3SrFmzr3RFdi0xCwCJa9KkyRaJAkiRD4ABAJAsMQsAQLLELAAAyRKzAAAkS8wCAJAsMQsAQLLELAAAyRKzAAAkS8wCAJAsMQsAQLLELAAAyRKzAAAkS8wCAJAsMQsAQLLELAAAyRKzAAAkS8wCAJAsMQsAQLLELAAAyRKzAAAkS8wCAJAsMQsAQLLELAAAyRKzAAAkS8wCAJCsryVmf/rTn0bnzp2jefPm0a9fv3j22Wc3OP6+++6LLl26RPPmzaN79+7xyCOPrHfsd7/73SgoKIiJEydu4VkDALC1y3vMTpo0KUaPHh3jx4+P2bNnR48ePWLw4MGxZMmSdY6fMWNGDB8+PM4444x44YUXYujQoTF06NB45ZVXvjD2oYceir/85S/RoUOHfB8GAABboYIsy7J87qBfv37Rp0+fuOWWWyIior6+PiorK+Occ86JSy+99Avjhw0bFitWrIjJkyfnlh100EHRs2fPuP3223PL3nnnnejXr1889thjceSRR8b5558f559//jrnsGrVqli1alXu6+XLl0dlZWXU1tZGSUnJFjpSAAC2lOXLl0dpaemX9lper8yuXr06Zs2aFVVVVX/fYWFhVFVVRXV19Tq3qa6ubjA+ImLw4MENxtfX18epp54aF198cXTr1u1L5zFhwoQoLS3NvSorKzfziAAA2JrkNWbff//9qKuri/Ly8gbLy8vLo6amZp3b1NTUfOn4H//4x9G0adM499xzN2oeY8aMidra2tzrrbfe2sQjAQBga9S0sSewqWbNmhU33nhjzJ49OwoKCjZqm+Li4iguLs7zzAAA+Lrl9cpsmzZtokmTJrF48eIGyxcvXhwVFRXr3KaiomKD459++ulYsmRJdOzYMZo2bRpNmzaNN998My688MLo3LlzXo4DAICtU15jtqioKHr16hXTpk3LLauvr49p06ZF//7917lN//79G4yPiJg6dWpu/Kmnnhovv/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477hgdOnSI0047LRYtWpTvwwAAYCuT95idNGlSjB49OsaPHx+zZ8+OHj16xODBg2PJkiXrHD9jxowYPnx4nHHGGfHCCy/E0KFDY+jQofHKK69ERMTKlStj9uzZcfnll8fs2bPjwQcfjNdeey2OPvrofB8KAABbmYIsy7J87qBfv37Rp0+fuOWWWyIior6+PiorK+Occ86JSy+99Avjhw0bFitWrIjJkyfnlh100EHRs2fPuP3229e5j+eeey769u0bb775ZnTs2PEL61etWhWrVq3Kfb18+fKorKyM2traKCkp+aqHCADAFrZ8+fIoLS390l7L65XZ1atXx6xZs6KqqurvOywsjKqqqqiurl7nNtXV1Q3GR0QMHjx4veMjImpra6OgoCDKysrWuX7ChAlRWlqae1VWVm76wQAAsNXJa8y+//77UVdXF+Xl5Q2Wl5eXR01NzTq3qamp2aTxn3zySVxyySUxfPjw9Vb7mDFjora2Nvd66623NuNoAADY2jRt7Al8FWvWrIkTTzwxsiyL2267bb3jiouLo7i4+GucGQAAX4e8xmybNm2iSZMmsXjx4gbLFy9eHBUVFevcpqKiYqPGrw3ZN998M6ZPn+7eVwCA7VBebzMoKiqKXr16xbRp03LL6uvrY9q0adG/f/91btO/f/8G4yMipk6d2mD82pB9/fXX4/HHH4/WrVvn5wAAANiq5f02g9GjR8eIESOid+/e0bdv35g4cWKsWLEiTj/99IiIOO2002KXXXaJCRMmRETEeeedFwMHDozrr78+jjzyyLj33nvj+eefjzvuuCMiPgvZE044IWbPnh2TJ0+Ourq63P20rVq1iqKionwfEgAAW4m8x+ywYcPivffei3HjxkVNTU307NkzpkyZkvuQ18KFC6Ow8O8XiA8++OC45557YuzYsXHZZZfFXnvtFQ8//HDst99+ERHxzjvvxO9///uIiOjZs2eDfT3xxBNxyCGH5PuQAADYSuT9ObNbo419bhkAAI1jq3jOLAAA5JOYBQAgWWIWAIBkiVkAAJIlZgEASJaYBQAgWWIWAIBkiVkAAJIlZgEASJaYBQAgWWIWAIBkiVkAAJIlZgEASJaYBQAgWWIWAIBkiVkAAJI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l6VlZVf9dAAANgK5DVm33///airq4vy8vIGy8vLy6Ompmad29TU1Gxw/No/N+U9x4wZE7W1tbnXW2+9tVnHAwDA1qVpY0/g61BcXBzFxcWNPQ0AALawvF6ZbdOmTTRp0iQWL17cYPnixYujoqJindtUVFRscPzaPzflPQEA2DblNWaLioqiV69eMW3atNyy+vr6mDZtWvTv33+d2/Tv37/B+IiIqVOn5sbvtttuUVFR0WDM8uXLY+bMmet9TwAAtk15v81g9OjRMWLEiOjdu3f07ds3Jk6cGCtWrIjTTz89IiJOO+202GWXXWLChAkREXHeeefFwIED4/rrr48jjzwy7r333nj++efjjjvuiIiIgoKCOP/88+M//uM/Yq+99orddtstLr/88ujQoUMMHTo034cDAMBWJO8xO2zYsHjvvfdi3LhxUVNTEz179owpU6bkPsC1cOHCKCz8+wXigw8+OO65554YO3ZsXHbZZbHXXnvFww8/HPvtt19uzPe+971YsWJFjBo1KpYtWxbf+MY3YsqUKdG8efN8Hw4AAFuRvD9ndmu0sc8tAwCgcWwVz5kFAIB8ErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJylvMLl26NE4++eQoKSmJsrKyOOOMM+Kjjz7a4DaffPJJnHXWWdG6devYaaed4vjjj4/Fixfn1r/00ksxfPjwqKysjBYtWkTXrl3jxhtvzNchAACwlctbzJ588snx6quvxtSpU2Py5Mnxpz/9KUaNGrXBbS644IL4wx/+EPfdd1889dRTsWjRojjuuONy62fNmhXt2rWLX/3qV/Hqq6/G97///RgzZkzccsst+ToMAAC2YgVZlmVb+k3nzZsX++67bzz33HPRu3fviIiYMmVKHHHEEfH2229Hhw4dvrBNbW1ttG3bNu6555444YQTIiJi/vz50bVr16iuro6DDjponfs666yzYt68eTF9+vT1zmfVqlWxatWq3NfLly+PysrKqK2tjZKSkq9yqAAA5MHy5cujtLT0S3stL1dmq6uro6ysLBeyERFVVVVRWFgYM2fOXOc2s2bNijVr1kRVVVVuWZcuXaJjx45RXV293n3V1tZGq1atNjifCRMmRGlpae5VWVm5iUcEAMDWKC8xW1NTE+3atWuwrGnTptGqVauoqalZ7zZFRUVRVlbWYHl5efl6t5kxY0ZMmjTpS29fGDNmTNTW1uZeb7311sYfDAAAW61NitlLL700CgoKNviaP39+vubawCuvvBLHHHNMjB8/Pg4//PANji0uLo6SkpIGLwAA0td0UwZfeOGFMXLkyA2O2X333aOioiKWLFnSYPmnn34aS5cujYqKinVuV1FREatXr45ly5Y1uDq7ePHiL2wzd+7cGDRoUIwaNSrGjh27KYcAAMA2ZJNitm3bttG2bdsvHde/f/9YtmxZzJo1K3r16hUREdOnT4/6+vro16/fOrfp1atXNGvWLKZNmxbHH398RES89tprsXDhwujfv39u3KuvvhqHHnpojBgxIn74wx9uyvQBANjG5OVpBhER3/rWt2Lx4sVx++23x5o1a+L000+P3r17xz333BMREe+8804MGjQo7rrrrujbt29ERPz7v/97PPLII3HnnXdGSUlJnHPOORHx2b2xEZ/dWnDooYfG4MGD49prr83tq0mTJhsV2Wtt7KfjAABoHBvba5t0ZXZT/PrXv46zzz47Bg0aFIWFhXH88cfHTTfdlFu/Zs2aeO2112LlypW5ZTfccENu7KpVq2Lw4MFx66235tbff//98d5778WvfvWr+NWvfpVb3qlTp3jjjTfydSgAAGyl8nZldmvmyiwAwNatUZ8zCwAAXwcxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkCwxCwBAssQsAADJErMAACRLzAIAkKy8xezSpUvj5JNPjpKSkigrK4szzjgjPvroow1u88knn8RZZ50VrVu3jp122imOP/74WLx48TrH/u1vf4tdd901CgoKYtmyZXk4AgAAtnZ5i9mTTz45Xn311Zg6dWpMnjw5/vSnP8WoUaM2uM0FF1wQf/jDH+K+++6Lp556KhYtWhTHHXfcOseeccYZsf/+++dj6gAAJKIgy7JsS7/pvHnzYt99943nnnsuevfuHRERU6ZMiSOOOCLefvvt6NChwx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hvjzjvvjIKCgsaezjalaWNPgMZz4YUXxsiRIzc4Zvfdd4+KiopYsmRJg+WffvppLF26NCoqKta5XUVFRaxevTqWLVvW4Mre4sWLc9tMnz495syZE/fff39EfPZJ64iINm3axPe///34wQ9+sJlHtv1o7HO41ty5c2PQoEExatSoGDt27GYdC3/Xpk2baNKkyRee/rGu7/1aFRUVGxy/9s/FixdH+/btG4zp2bPnFpw9+Th/a60N2TfffDOmT5/uqmye5OMcPv3007FkyZIG/xJZV1cXF154YUycODHeeOONLXsQ25PGvmmXrd/aDw89//zzuWWPPfbYRn146P77788tmz9/foMPD/33f/93NmfOnNzrF7/4RRYR2YwZM9b7aVE2T77OYZZl2SuvvJK1a9cuu/jii/N3ANuhvn37ZmeffXbu67q6umyXXXbZ4IdPjjrqqAbL+vfv/4UPgF133XW59bW1tT4Alidb+vxlWZatXr06Gzp0aNatW7dsyZIl+Zk4OVv6HL7//vsN/ps3Z86crEOHDtkll1ySzZ8/P38Hsh0Qs2yUIUOGZAcccEA2c+bM7M9//nO21157NXis09tvv53ts88+2cyZM3PLvvvd72YdO3bMpk+fnj3//PNZ//79s/79+693H0888YSnGeRRPs7hnDlzsrZt22annHJK9u677+Ze/kP71d17771ZcXFxduedd2Zz587NRo0alZWVlWU1NTVZlmXZqaeeml166aW58c8880zWtGnT7LrrrsvmzZuXjR8/fp2P5iorK8t+97vfZS+//HJ2zDHHeDRXnmzp87d69ers6KOPznbdddfsxRdfbPD3bdWqVY1yjNu6fPwd/EeeZrBliFk2yt/+9rds+PDh2U477ZSVlJRkp59+evbhhx/m1i9YsCCLiOyJJ57ILfv444+zM888M9t5552zHXbYITv22GOzd999d737ELP5lY9zOH78+CwivvDq1KnT13hk266bb74569ixY1ZUVJT17ds3+8tf/pJbN3DgwGzEiBENxv/2t7/N9t5776yoqCjr1q1b9sc//rHB+vr6+uzyyy/PysvLs+Li4mzQoEHZa6+99nUcynZpS56/tX8/1/X6/N9Ztqwt/XfwH4nZLaMgy/7/jYoAAJAYTzMAACBZYhYAgGSJWQAAkiVmAQBIlpgFACBZYhYAgGSJWQAAkiVmAQBIlpgFACBZYhYAgGSJWQAAkvX/AJ7Jh1tAnsjpAAAAAElFTkSuQmCC\",\n                        \"text/plain\": [\n                            \"<Figure size 800x800 with 1 Axes>\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                }\n            ],\n            \"source\": [\n                \"from matplotlib.pyplot import plot, legend\\n\",\n                \"figure(figsize=(8,8))\\n\",\n                \"plot(dlosses[100:], label=\\\"Discriminator Loss\\\")\\n\",\n                \"plot(glosses[100:], label=\\\"Generator Loss\\\")\\n\",\n                \"legend()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 6,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"name\": \"stdout\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 32ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 47ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 9ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 9ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 9ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 8ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 8ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 8ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 8ms/step\\n\",\n                        \"\\u001b[1m1/1\\u001b[0m \\u001b[32m\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\\u001b[0m\\u001b[37m\\u001b[0m \\u001b[1m0s\\u001b[0m 8ms/step\\n\"\n                    ]\n                },\n                {\n                    \"data\": {\n                        \"text/plain\": [\n                            \"<matplotlib.image.AxesImage at 0x34f32bd70>\"\n                        ]\n                    },\n                    \"execution_count\": 6,\n                    \"metadata\": {},\n                    \"output_type\": \"execute_result\"\n                },\n                {\n                    \"data\": {\n                        \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAakAAAGiCAYAAABd6zmYAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/H5lhTAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOz9WYytWZqehz1r+oc9x3zmnCu7pp67i01R1kSZsARfGIZAwIDBC18ZIGGhr9i0QKJNwpQF2KAB8oK3vmteWRYkUIBbalKim2Srh+rqqsqqzMo8J88UcSJiR+zxn9bgi+/f+1SDbLJk092V9FnAQeaJExF77/Wv9Y3v+34qpZR4s96sN+vNerPerB/Dpf+k38Cb9Wa9WW/Wm/Vm/VHrjZN6s96sN+vNerN+bNcbJ/VmvVlv1pv1Zv3YrjdO6s16s96sN+vN+rFdb5zUm/VmvVlv1pv1Y7veOKk36816s96sN+vHdr1xUm/Wm/VmvVlv1o/teuOk3qw36816s96sH9v1xkm9WW/Wm/VmvVk/tuuNk3qz3qw36816s35s15+Yk/o7f+fv8Pbbb1MUBd/4xjf4p//0n/5JvZU36816s96sN+vHdP2JOKlf+7Vf45d/+Zf5a3/tr/E7v/M7/NRP/RR/7s/9OV69evUn8XberDfrzXqz3qwf06X+JARmv/GNb/ALv/AL/O2//bcBiDHy8OFD/tJf+kv85b/8l/+4386b9Wa9WW/Wm/Vjuuwf9wu2bctv//Zv8yu/8iv7r2mt+bN/9s/ym7/5m//cn2mahqZp9n+PMTKfzzk6OkIp9f/z9/xmvVlv1pv1Zv2rXSklVqsV9+7dQ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CbW1ttGvXLqqpqaE5c+b475FJcsg4JUVE9MEHH9CECRMoGAzS7Nmz6fDhw8PdpDvKkiVLqKKigoLBII0bN46WLFlCra2tfnkikaAXXniBxowZQ9nZ2fTkk09SR0fHMLb49rB//34CcNXP8uXLiYjN0N944w0qKyujUChEc+fOpZaWlrT36OnpoaVLl1Jubi7l5+fTc889R9FodBh68+/5JznE43GaN28elZSUUCAQoKqqKlqxYsVVi7bRIIdryQAAffzxx36dm5kLf/zxBy1YsIDC4TAVFxfTunXrKJlMDnFv/j03kkN7ezvNmTOHioqKKBQK0T333EPr16+ngYGBtPfJFDmoVB0KhUKhGLFk1J2UQqFQKP5bKCWlUCgUihGLUlIKhUKhGLEoJaVQKBSKEYtSUgqFQqEYsSglpVAoFIoRi1JSCoVCoRixKCWlUCgUihGLUlIKhUKhGLEoJaVQKBSKEYtSUgqFQqEYsSglpVAoFIoRy/8BTe01WZjb6NoAAAAASUVORK5CYII=\",\n                        \"text/plain\": [\n                            \"<Figure size 640x480 with 1 Axes>\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                }\n            ],\n            \"source\": [\n                \"x = []\\n\",\n                \"for i in range(10):\\n\",\n                \"  x.append(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\\n\",\n                \"imshow(np.concatenate(x, axis=0))\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we export the _generator_ to onnx\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 7,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\">Model: \\\"sequential\\\"</span>\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1mModel: \\\"sequential\\\"\\u001b[0m\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\">\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503<span style=\\\"font-weight: bold\\\"> Layer (type)                    </span>\u2503<span style=\\\"font-weight: bold\\\"> Output Shape           </span>\u2503<span style=\\\"font-weight: bold\\\">       Param # </span>\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 dense_2 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Dense</span>)                 \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">316,736</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_3           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502        <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">12,544</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_3 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3136</span>)           \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503\\u001b[1m \\u001b[0m\\u001b[1mLayer (type)                   \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1mOutput Shape          \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1m      Param #\\u001b[0m\\u001b[1m \\u001b[0m\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 dense_2 (\\u001b[38;5;33mDense\\u001b[0m)                 \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502       \\u001b[38;5;34m316,736\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_3           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502        \\u001b[38;5;34m12,544\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_3 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m3136\\u001b[0m)           \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Total params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">329,280</span> (1.26 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Total params: \\u001b[0m\\u001b[38;5;34m329,280\\u001b[0m (1.26 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">323,008</span> (1.23 MB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Trainable params: \\u001b[0m\\u001b[38;5;34m323,008\\u001b[0m (1.23 MB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Non-trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">6,272</span> (24.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Non-trainable params: \\u001b[0m\\u001b[38;5;34m6,272\\u001b[0m (24.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\">Model: \\\"sequential_1\\\"</span>\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1mModel: \\\"sequential_1\\\"\\u001b[0m\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\">\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503<span style=\\\"font-weight: bold\\\"> Layer (type)                    </span>\u2503<span style=\\\"font-weight: bold\\\"> Output Shape           </span>\u2503<span style=\\\"font-weight: bold\\\">       Param # </span>\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 reshape_1 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Reshape</span>)             \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">7</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">64</span>)       \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose                \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502       <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">204,928</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2DTranspose</span>)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_4           \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502           <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">512</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">BatchNormalization</span>)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_4 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">ELU</span>)                     \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">14</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">128</span>)    \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503\\u001b[1m \\u001b[0m\\u001b[1mLayer (type)                   \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1mOutput Shape          \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1m      Param #\\u001b[0m\\u001b[1m \\u001b[0m\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 reshape_1 (\\u001b[38;5;33mReshape\\u001b[0m)             \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m7\\u001b[0m, \\u001b[38;5;34m64\\u001b[0m)       \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 conv2d_transpose                \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502       \\u001b[38;5;34m204,928\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mConv2DTranspose\\u001b[0m)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 batch_normalization_4           \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502           \\u001b[38;5;34m512\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mBatchNormalization\\u001b[0m)            \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 elu_4 (\\u001b[38;5;33mELU\\u001b[0m)                     \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m14\\u001b[0m, \\u001b[38;5;34m128\\u001b[0m)    \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Total params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">205,440</span> (802.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Total params: \\u001b[0m\\u001b[38;5;34m205,440\\u001b[0m (802.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">205,184</span> (801.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Trainable params: \\u001b[0m\\u001b[38;5;34m205,184\\u001b[0m (801.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Non-trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">256</span> (1.00 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Non-trainable params: \\u001b[0m\\u001b[38;5;34m256\\u001b[0m (1.00 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\">Model: \\\"sequential_2\\\"</span>\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1mModel: \\\"sequential_2\\\"\\u001b[0m\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\">\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503<span style=\\\"font-weight: bold\\\"> Layer (type)                    </span>\u2503<span style=\\\"font-weight: bold\\\"> Output Shape           </span>\u2503<span style=\\\"font-weight: bold\\\">       Param # </span>\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 conv2d_transpose_1              \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)      \u2502         <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3,201</span> \u2502\\n\",\n                            \"\u2502 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Conv2DTranspose</span>)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 activation (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Activation</span>)         \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">1</span>)      \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_2 (<span style=\\\"color: #0087ff; text-decoration-color: #0087ff\\\">Reshape</span>)             \u2502 (<span style=\\\"color: #00d7ff; text-decoration-color: #00d7ff\\\">None</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>, <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">28</span>)         \u2502             <span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\",\n                            \"\u2503\\u001b[1m \\u001b[0m\\u001b[1mLayer (type)                   \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1mOutput Shape          \\u001b[0m\\u001b[1m \\u001b[0m\u2503\\u001b[1m \\u001b[0m\\u001b[1m      Param #\\u001b[0m\\u001b[1m \\u001b[0m\u2503\\n\",\n                            \"\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\",\n                            \"\u2502 conv2d_transpose_1              \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)      \u2502         \\u001b[38;5;34m3,201\\u001b[0m \u2502\\n\",\n                            \"\u2502 (\\u001b[38;5;33mConv2DTranspose\\u001b[0m)               \u2502                        \u2502               \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 activation (\\u001b[38;5;33mActivation\\u001b[0m)         \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m1\\u001b[0m)      \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\",\n                            \"\u2502 reshape_2 (\\u001b[38;5;33mReshape\\u001b[0m)             \u2502 (\\u001b[38;5;45mNone\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m, \\u001b[38;5;34m28\\u001b[0m)         \u2502             \\u001b[38;5;34m0\\u001b[0m \u2502\\n\",\n                            \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Total params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3,201</span> (12.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Total params: \\u001b[0m\\u001b[38;5;34m3,201\\u001b[0m (12.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">3,201</span> (12.50 KB)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Trainable params: \\u001b[0m\\u001b[38;5;34m3,201\\u001b[0m (12.50 KB)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"data\": {\n                        \"text/html\": [\n                            \"<pre style=\\\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\\\"><span style=\\\"font-weight: bold\\\"> Non-trainable params: </span><span style=\\\"color: #00af00; text-decoration-color: #00af00\\\">0</span> (0.00 B)\\n\",\n                            \"</pre>\\n\"\n                        ],\n                        \"text/plain\": [\n                            \"\\u001b[1m Non-trainable params: \\u001b[0m\\u001b[38;5;34m0\\u001b[0m (0.00 B)\\n\"\n                        ]\n                    },\n                    \"metadata\": {},\n                    \"output_type\": \"display_data\"\n                },\n                {\n                    \"name\": \"stderr\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"transpose_input for input_0: shape must be rank 4, ignored\\n\"\n                    ]\n                }\n            ],\n            \"source\": [\n                \"\\n\",\n                \"import numpy as np\\n\",\n                \"import tf2onnx\\n\",\n                \"import tensorflow as tf\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"# split the model into 3 parts\\n\",\n                \"gm2 = tf.keras.models.Sequential(gm.layers[0:4])\\n\",\n                \"# display gm2 \\n\",\n                \"gm2.summary()\\n\",\n                \"gm2.output_names=['output']\\n\",\n                \"\\n\",\n                \"gm3 = tf.keras.models.Sequential(gm.layers[4:8])\\n\",\n                \"#  display gm3\\n\",\n                \"gm3.summary() \\n\",\n                \"gm3.output_names=['output']\\n\",\n                \"\\n\",\n                \"gm4 = tf.keras.models.Sequential(gm.layers[8:])\\n\",\n                \"# display gm4\\n\",\n                \"gm4.summary()\\n\",\n                \"gm4.output_names=['output'] \\n\",\n                \"\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*np.random.rand(1,*[1, ZDIM])\\n\",\n                \"inter_x1 = gm2(x[0])\\n\",\n                \"inter_x2 = gm3(inter_x1)\\n\",\n                \"\\n\",\n                \"output_path = \\\"network_split_0.onnx\\\"\\n\",\n                \"spec = tf.TensorSpec([1, ZDIM], tf.float32, name='input_0')\\n\",\n                \"tf2onnx.convert.from_keras(gm2, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=output_path)\\n\",\n                \"output_path = \\\"network_split_1.onnx\\\"\\n\",\n                \"spec = tf.TensorSpec(inter_x1.shape, tf.float32, name='elu1')\\n\",\n                \"tf2onnx.convert.from_keras(gm3, input_signature=[spec], inputs_as_nchw=['input_1'], opset=12, output_path=output_path)\\n\",\n                \"output_path = \\\"network_split_2.onnx\\\"\\n\",\n                \"spec = tf.TensorSpec(inter_x2.shape, tf.float32, name='elu2')\\n\",\n                \"tf2onnx.convert.from_keras(gm4, input_signature=[spec], inputs_as_nchw=['input_2'], opset=12, output_path=output_path)\\n\",\n                \"\\n\",\n                \"data_array = x.reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"inter_x1 = inter_x1.numpy().reshape([-1]).tolist()\\n\",\n                \"inter_x2 = inter_x2.numpy().reshape([-1]).tolist()\\n\",\n                \"data_2 = dict(input_data = [inter_x1])\\n\",\n                \"data_3 = dict(input_data = [inter_x2])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"data_path = os.path.join('gan_input_0.json')\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\",\n                \"data_path = os.path.join('gan_input_1.json')\\n\",\n                \"json.dump( data_2, open(data_path, 'w' ))\\n\",\n                \"data_path = os.path.join('gan_input_2.json')\\n\",\n                \"json.dump( data_3, open(data_path, 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"###  KZG commitment intermediate calculations\\n\",\n                \"\\n\",\n                \"the visibility parameters are:\\n\",\n                \"- `input_visibility`: \\\"polycommit\\\"\\n\",\n                \"- `param_visibility`: \\\"public\\\"\\n\",\n                \"- `output_visibility`: polycommit\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 8,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"data\": {\n                        \"text/plain\": [\n                            \"True\"\n                        ]\n                    },\n                    \"execution_count\": 8,\n                    \"metadata\": {},\n                    \"output_type\": \"execute_result\"\n                }\n            ],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"srs_path = os.path.join('kzg.srs')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n                \"run_args.output_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"run_args.input_scale = 0\\n\",\n                \"run_args.param_scale = 0\\n\",\n                \"run_args.logrows = 18\\n\",\n                \"\\n\",\n                \"ezkl.get_srs(logrows=run_args.logrows, commitment=ezkl.PyCommitments.KZG)\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Circuit compilation\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 9,\n            \"metadata\": {},\n            \"outputs\": [\n                {\n                    \"name\": \"stderr\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"\\n\",\n                        \"\\n\",\n                        \" <------------- Numerical Fidelity Report (input_scale: 0, param_scale: 0, scale_input_multiplier: 10) ------------->\\n\",\n                        \"\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+-----------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| mean_error     | median_error | max_error   | min_error    | mean_abs_error | median_abs_error | max_abs_error | min_abs_error   | mean_squared_error | mean_percent_error | mean_abs_percent_error |\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+-----------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| -0.00045216593 | 0.0071961936 | 0.059581105 | -0.051913798 | 0.011681631    | 0.0071961936     | 0.059581105   | 0.0000062934123 | 0.0002161761       | 1                  | 1                      |\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+-----------------+--------------------+--------------------+------------------------+\\n\",\n                        \"\\n\",\n                        \"\\n\"\n                    ]\n                },\n                {\n                    \"name\": \"stdout\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"Setting up split model 0\\n\",\n                        \"Setting up split model 1\\n\"\n                    ]\n                },\n                {\n                    \"name\": \"stderr\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"\\n\",\n                        \"\\n\",\n                        \" <------------- Numerical Fidelity Report (input_scale: 0, param_scale: 0, scale_input_multiplier: 10) ------------->\\n\",\n                        \"\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| mean_error     | median_error | max_error   | min_error    | mean_abs_error | median_abs_error | max_abs_error | min_abs_error | mean_squared_error | mean_percent_error | mean_abs_percent_error |\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| -0.00008474619 | -0.002256453 | 0.003519658 | -0.003081262 | 0.0018818051   | 0.002256453      | 0.003519658   | 0.00017167516 | 0.000003900568     | 1                  | 1                      |\\n\",\n                        \"+----------------+--------------+-------------+--------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"\\n\",\n                        \"\\n\"\n                    ]\n                },\n                {\n                    \"name\": \"stdout\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"Setting up split model 2\\n\"\n                    ]\n                },\n                {\n                    \"name\": \"stderr\",\n                    \"output_type\": \"stream\",\n                    \"text\": [\n                        \"\\n\",\n                        \"\\n\",\n                        \" <------------- Numerical Fidelity Report (input_scale: 0, param_scale: 0, scale_input_multiplier: 10) ------------->\\n\",\n                        \"\\n\",\n                        \"+-------------+--------------+-------------+-------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| mean_error  | median_error | max_error   | min_error   | mean_abs_error | median_abs_error | max_abs_error | min_abs_error | mean_squared_error | mean_percent_error | mean_abs_percent_error |\\n\",\n                        \"+-------------+--------------+-------------+-------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"| -0.49951223 | -0.49951398  | -0.49951398 | -0.49951398 | 0.49951223     | 0.49951398       | 0.49951398    | 0.49951398    | 0.24951272         | -0.9980509         | 0.9980509              |\\n\",\n                        \"+-------------+--------------+-------------+-------------+----------------+------------------+---------------+---------------+--------------------+--------------------+------------------------+\\n\",\n                        \"\\n\",\n                        \"\\n\"\n                    ]\n                }\n            ],\n            \"source\": [\n                \"# iterate over each submodel gen-settings, compile circuit and setup zkSNARK\\n\",\n                \"\\n\",\n                \"def setup(i):\\n\",\n                \"    print(\\\"Setting up split model \\\"+str(i))\\n\",\n                \"    # file names\\n\",\n                \"    model_path = os.path.join('network_split_'+str(i)+'.onnx')\\n\",\n                \"    settings_path = os.path.join('settings_split_'+str(i)+'.json')\\n\",\n                \"    data_path =  os.path.join('gan_input_'+str(i)+'.json')\\n\",\n                \"    compiled_model_path = os.path.join('network_split_'+str(i)+'.compiled')\\n\",\n                \"    pk_path = os.path.join('test_split_'+str(i)+'.pk')\\n\",\n                \"    vk_path = os.path.join('test_split_'+str(i)+'.vk')\\n\",\n                \"    witness_path = os.path.join('witness_split_'+str(i)+'.json')\\n\",\n                \"\\n\",\n                \"    if i > 0:\\n\",\n                \"         prev_witness_path = os.path.join('witness_split_'+str(i-1)+'.json')\\n\",\n                \"         witness = json.load(open(prev_witness_path, 'r'))\\n\",\n                \"         data = dict(input_data = witness['outputs'])\\n\",\n                \"         # Serialize data into file:\\n\",\n                \"         json.dump(data, open(data_path, 'w' ))\\n\",\n                \"    else:\\n\",\n                \"         data_path = os.path.join('gan_input_0.json')\\n\",\n                \"\\n\",\n                \"    # generate settings for the current model\\n\",\n                \"    res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"    res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\", scales=[run_args.input_scale], max_logrows=run_args.logrows)\\n\",\n                \"    assert res == True\\n\",\n                \"\\n\",\n                \"    # load settings and print them to the console\\n\",\n                \"    settings = json.load(open(settings_path, 'r'))\\n\",\n                \"    settings['run_args']['logrows'] = run_args.logrows\\n\",\n                \"    json.dump(settings, open(settings_path, 'w' ))\\n\",\n                \"\\n\",\n                \"    res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    res = ezkl.setup(\\n\",\n                \"         compiled_model_path,\\n\",\n                \"         vk_path,\\n\",\n                \"         pk_path,\\n\",\n                \"      )\\n\",\n                \"\\n\",\n                \"    assert res == True\\n\",\n                \"    assert os.path.isfile(vk_path)\\n\",\n                \"    assert os.path.isfile(pk_path)\\n\",\n                \"    res = ezkl.gen_witness(data_path, compiled_model_path, witness_path, vk_path)\\n\",\n                \"    run_args.input_scale = settings[\\\"model_output_scales\\\"][0]\\n\",\n                \"\\n\",\n                \"for i in range(3):\\n\",\n                \"    setup(i)\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Proof generation\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"print(\\\"Proving split models\\\")\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"def prove_model(i): \\n\",\n                \"    proof_path = os.path.join('proof_split_'+str(i)+'.json')\\n\",\n                \"    witness_path = os.path.join('witness_split_'+str(i)+'.json')\\n\",\n                \"    compiled_model_path = os.path.join('network_split_'+str(i)+'.compiled')\\n\",\n                \"    pk_path = os.path.join('test_split_'+str(i)+'.pk')\\n\",\n                \"    vk_path = os.path.join('test_split_'+str(i)+'.vk')\\n\",\n                \"    settings_path = os.path.join('settings_split_'+str(i)+'.json')\\n\",\n                \"\\n\",\n                \"    res = ezkl.prove(\\n\",\n                \"            witness_path,\\n\",\n                \"            compiled_model_path,\\n\",\n                \"            pk_path,\\n\",\n                \"            proof_path,\\n\",\n                \"            \\\"for-aggr\\\",\\n\",\n                \"        )\\n\",\n                \"\\n\",\n                \"    print(res)\\n\",\n                \"    assert os.path.isfile(proof_path)\\n\",\n                \"\\n\",\n                \"    # Verify the proof\\n\",\n                \"    if i > 0:\\n\",\n                \"        # swap the proof commitments if we are not the first model\\n\",\n                \"        prev_witness_path = os.path.join('witness_split_'+str(i-1)+'.json')\\n\",\n                \"        prev_witness = json.load(open(prev_witness_path, 'r'))\\n\",\n                \"\\n\",\n                \"        witness = json.load(open(witness_path, 'r'))\\n\",\n                \"\\n\",\n                \"        print(prev_witness[\\\"processed_outputs\\\"])\\n\",\n                \"        print(witness[\\\"processed_inputs\\\"])\\n\",\n                \"\\n\",\n                \"        witness[\\\"processed_inputs\\\"] = prev_witness[\\\"processed_outputs\\\"]\\n\",\n                \"\\n\",\n                \"        # now save the witness\\n\",\n                \"        with open(witness_path, \\\"w\\\") as f:\\n\",\n                \"            json.dump(witness, f)\\n\",\n                \"\\n\",\n                \"        res = ezkl.swap_proof_commitments(proof_path, witness_path)\\n\",\n                \"\\n\",\n                \"    res = ezkl.verify(\\n\",\n                \"            proof_path,\\n\",\n                \"            settings_path,\\n\",\n                \"            vk_path,\\n\",\n                \"        )\\n\",\n                \"\\n\",\n                \"    assert res == True\\n\",\n                \"    print(\\\"verified\\\")\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"for i in range(3):\\n\",\n                \"    print(\\\"----- proving split \\\"+str(i))\\n\",\n                \"    prove_model(i)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"You can also mock aggregate the split proofs into a single proof. This is useful if you want to verify the proof on chain at a lower cost. Here we mock aggregate the proofs to save time. You can use other notebooks to see how to aggregate in full ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now mock aggregate the proofs\\n\",\n                \"proofs = []\\n\",\n                \"for i in range(3):\\n\",\n                \"    proof_path = os.path.join('proof_split_'+str(i)+'.json')\\n\",\n                \"    proofs.append(proof_path)\\n\",\n                \"\\n\",\n                \"ezkl.mock_aggregate(proofs, logrows=22, split_proofs = True)\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.12.2\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/mnist_vae.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# what is the variational?\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Credits to [geohot](https://github.com/geohot/ai-notebooks/blob/master/mnist_gan.ipynb) for most of this code\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"tf2onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"import os\\n\",\n                \"import time\\n\",\n                \"import random\\n\",\n                \"\\n\",\n                \"import tensorflow as tf\\n\",\n                \"import tensorflow.keras.backend as K\\n\",\n                \"from tensorflow.keras.optimizers import Adam\\n\",\n                \"from tensorflow.keras.layers import *\\n\",\n                \"from tensorflow.keras.models import Model\\n\",\n                \"from tensorflow.keras.losses import mse\\n\",\n                \"from tensorflow.keras.datasets import mnist\\n\",\n                \"(x_train, y_train), (x_test, y_test) = mnist.load_data()\\n\",\n                \"x_train, x_test = [x/255.0 for x in [x_train, x_test]]\\n\",\n                \"y_train, y_test = [tf.keras.utils.to_categorical(x) for x in [y_train, y_test]]\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ZDIM = 4\\n\",\n                \"\\n\",\n                \"def get_encoder():\\n\",\n                \"  x = in1 = Input((28,28))\\n\",\n                \"  x = Reshape((28,28,1))(x)\\n\",\n                \"\\n\",\n                \"  x = Conv2D(64, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"  x = BatchNormalization()(x)\\n\",\n                \"  x = ELU()(x)\\n\",\n                \"\\n\",\n                \"  x = Conv2D(128, (5,5), padding='same', strides=(2,2))(x)\\n\",\n                \"  x = BatchNormalization()(x)\\n\",\n                \"  x = ELU()(x)\\n\",\n                \"\\n\",\n                \"  x = Flatten()(x)\\n\",\n                \"  x = Dense(ZDIM)(x)\\n\",\n                \"  return Model(in1, x)\\n\",\n                \"\\n\",\n                \"def get_decoder():\\n\",\n                \"  x = in1 = Input((ZDIM,))\\n\",\n                \"\\n\",\n                \"  x = Dense(7*7*64)(x)\\n\",\n                \"  x = BatchNormalization()(x)\\n\",\n                \"  x = ELU()(x)\\n\",\n                \"  x = Reshape((7,7,64))(x)\\n\",\n                \"\\n\",\n                \"  x = Conv2DTranspose(128, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"  x = BatchNormalization()(x)\\n\",\n                \"  x = ELU()(x)\\n\",\n                \"\\n\",\n                \"  x = Conv2DTranspose(1, (5,5), strides=(2,2), padding='same')(x)\\n\",\n                \"  x = Activation('sigmoid')(x)\\n\",\n                \"  x = Reshape((28,28))(x)\\n\",\n                \"  return Model(in1, x)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Regular Autoencoder\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# normal autoencoder without the variational\\n\",\n                \"enc = get_encoder()\\n\",\n                \"dec = get_decoder()\\n\",\n                \"ae = Model(enc.input, dec(enc.output))\\n\",\n                \"ae.compile('adam', 'mse')\\n\",\n                \"ae.summary()\\n\",\n                \"# make the epochs larger for better results\\n\",\n                \"ae.fit(x_train, x_train, batch_size=128, epochs=1, shuffle=1, validation_data=(x_test, x_test))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# while the autoencoder might work without the variational, the sampling doesn't\\n\",\n                \"import numpy as np\\n\",\n                \"from matplotlib.pyplot import figure, imshow\\n\",\n                \"imshow(np.concatenate(ae.predict(np.array([random.choice(x_test) for i in range(10)])), axis=1))\\n\",\n                \"figure(figsize=(16,16))\\n\",\n                \"imshow(np.concatenate(ae.layers[-1].predict(np.random.normal(size=(10, ZDIM))), axis=1))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os \\n\",\n                \"\\n\",\n                \"model_path = os.path.join('ae.onnx')\\n\",\n                \"compiled_model_path = os.path.join('ae.compiled')\\n\",\n                \"pk_path = os.path.join('ae.pk')\\n\",\n                \"vk_path = os.path.join('ae.vk')\\n\",\n                \"settings_path = os.path.join('ae_settings.json')\\n\",\n                \"srs_path = os.path.join('ae_kzg.srs')\\n\",\n                \"witness_path = os.path.join('ae_witness.json')\\n\",\n                \"data_path = os.path.join('ae_input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we export the decoder (which presumably is what we want) -- to onnx\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import numpy as np\\n\",\n                \"import tf2onnx\\n\",\n                \"import tensorflow as tf\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"shape = [1, ZDIM]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*np.random.rand(1,*shape)\\n\",\n                \"\\n\",\n                \"spec = tf.TensorSpec(shape, tf.float32, name='input_0')\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"tf2onnx.convert.from_keras(dec, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\\n\",\n                \"\\n\",\n                \"data_array = x.reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"!RUST_LOG=trace\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (0.1 * np.random.rand(20, *shape)).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file\\n\",\n                \"witness_path = \\\"ae_witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('ae.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Variational Autoencoder\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"in1 = Input((28,28))\\n\",\n                \"x = get_encoder()(in1)\\n\",\n                \"\\n\",\n                \"# add the variational\\n\",\n                \"z_mu = Dense(ZDIM)(x)\\n\",\n                \"z_log_var = Dense(ZDIM)(x)\\n\",\n                \"z = Lambda(lambda x: x[0] + K.exp(0.5 * x[1]) * K.random_normal(shape=K.shape(x[0])))([z_mu, z_log_var])\\n\",\n                \"dec = get_decoder()\\n\",\n                \"dec.output_names=['output']\\n\",\n                \"\\n\",\n                \"out = dec(z)\\n\",\n                \"\\n\",\n                \"mse_loss = mse(Reshape((28*28,))(in1), Reshape((28*28,))(out)) * 28 * 28\\n\",\n                \"kl_loss = 1 + z_log_var - K.square(z_mu) - K.exp(z_log_var)\\n\",\n                \"kl_loss = -0.5 * K.mean(kl_loss, axis=-1)\\n\",\n                \"\\n\",\n                \"vae = Model(in1, out)\\n\",\n                \"vae.add_loss(K.mean(mse_loss + kl_loss))\\n\",\n                \"vae.compile('adam')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# z is sampled from z_mu and z_log_var with gaussian noise\\n\",\n                \"test = Model(in1, [z, z_mu, z_log_var])\\n\",\n                \"test.predict(x_train[0:1])\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"vae.fit(x_train, batch_size=128, epochs=1, shuffle=1, validation_data=(x_test, None))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"imshow(np.concatenate(vae.predict(np.array([random.choice(x_test) for i in range(10)])), axis=1))\\n\",\n                \"figure(figsize=(16,16))\\n\",\n                \"imshow(np.concatenate(vae.layers[5].predict(np.random.normal(size=(10, ZDIM))), axis=1))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os \\n\",\n                \"\\n\",\n                \"model_path = os.path.join('vae.onnx')\\n\",\n                \"compiled_model_path = os.path.join('vae.compiled')\\n\",\n                \"pk_path = os.path.join('vae.pk')\\n\",\n                \"vk_path = os.path.join('vae.vk')\\n\",\n                \"settings_path = os.path.join('vae_settings.json')\\n\",\n                \"srs_path = os.path.join('vae_kzg.srs')\\n\",\n                \"witness_path = os.path.join('vae_witness.json')\\n\",\n                \"data_path = os.path.join('vae_input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import numpy as np\\n\",\n                \"import tf2onnx\\n\",\n                \"import tensorflow as tf\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*np.random.rand(1,*[1, ZDIM])\\n\",\n                \"\\n\",\n                \"spec = tf.TensorSpec([1, ZDIM], tf.float32, name='input_0')\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"tf2onnx.convert.from_keras(dec, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\\n\",\n                \"\\n\",\n                \"data_array = x.reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"!RUST_LOG=trace\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"witness_path = \\\"vae_witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# uncomment to mock prove\\n\",\n                \"# res = ezkl.mock(witness_path, compiled_model_path)\\n\",\n                \"# assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/nbeats_timeseries_forecasting.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"TB8jFLoLwZ8K\"\n      },\n      \"source\": [\n        \"# N-BEATS Time Series Forecasting\\n\",\n        \"In this tutorial we utilize the N-BEATS (Neural basis expansion analysis for interpretable time series forecasting\\n\",\n        \") for forecasting the price of ethereum.\\n\",\n        \"\\n\",\n        \"For more details regarding N-BEATS, visit this link [https://arxiv.org/abs/1905.10437](https://arxiv.org/abs/1905.10437)\\n\",\n        \"\\n\",\n        \"The code for N-BEATS used is adapted from [nbeats-pytorch](https://pypi.org/project/nbeats-pytorch/)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"Ccy0MgZLwY1Z\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import pandas as pd\\n\",\n        \"import torch\\n\",\n        \"from torch import nn, optim\\n\",\n        \"from torch.nn import functional as F\\n\",\n        \"from torch.nn.functional import mse_loss, l1_loss, binary_cross_entropy, cross_entropy\\n\",\n        \"from torch.optim import Optimizer\\n\",\n        \"import matplotlib.pyplot as plt\\n\",\n        \"import requests\\n\",\n        \"import json\\n\",\n        \"from torch.utils.data import DataLoader, TensorDataset\\n\",\n        \"import numpy as np\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"ovxRhGv0xS0i\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Fetch data\\n\",\n        \"coins = [\\\"ETH\\\"]\\n\",\n        \"days_ago_to_fetch = 2000 # 7 years\\n\",\n        \"coin_history = {}\\n\",\n        \"hist_length = 0\\n\",\n        \"average_returns = {}\\n\",\n        \"cumulative_returns = {}\\n\",\n        \"\\n\",\n        \"def index_history_coin(hist):\\n\",\n        \"    hist = hist.set_index('time')\\n\",\n        \"    hist.index = pd.to_datetime(hist.index, unit='s')\\n\",\n        \"    return hist\\n\",\n        \"\\n\",\n        \"def filter_history_by_date(hist):\\n\",\n        \"    result = hist[hist.index.year >= 2017]\\n\",\n        \"    return result\\n\",\n        \"\\n\",\n        \"def fetch_history_coin(coin):\\n\",\n        \"    endpoint_url = \\\"https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym=USD&limit={:d}\\\".format(coin, days_ago_to_fetch)\\n\",\n        \"    res = requests.get(endpoint_url)\\n\",\n        \"    hist = pd.DataFrame(json.loads(res.content)['Data'])\\n\",\n        \"    hist = index_history_coin(hist)\\n\",\n        \"    hist = filter_history_by_date(hist)\\n\",\n        \"    return hist\\n\",\n        \"\\n\",\n        \"def get_history_from_file(filename):\\n\",\n        \"    return pd.read_csv(filename)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"for coin in coins:\\n\",\n        \"    coin_history[coin] = fetch_history_coin(coin)\\n\",\n        \"\\n\",\n        \"hist_length = len(coin_history[coins[0]])\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"CNeFMmvpx5ig\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# save to file\\n\",\n        \"# coin_history['ETH'].to_csv(\\\"eth_price.csv\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"_wPJcU8EyOsF\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# read from file\\n\",\n        \"coin_history['ETH'] = get_history_from_file(\\\"eth_price.csv\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"ij_DBZl7yQqE\",\n        \"outputId\": \"3b7838de-fa00-4560-cbcb-62c11e311a0f\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# calculate returns\\n\",\n        \"\\n\",\n        \"def add_all_returns():\\n\",\n        \"    for coin in coins:\\n\",\n        \"        hist = coin_history[coin]\\n\",\n        \"        hist['return'] = (hist['close'] - hist['open']) / hist['open']\\n\",\n        \"        average = hist[\\\"return\\\"].mean()\\n\",\n        \"        average_returns[coin] = average\\n\",\n        \"        cumulative_returns[coin] = (hist[\\\"return\\\"] + 1).prod() - 1\\n\",\n        \"        hist['excess_return'] = hist['return'] - average\\n\",\n        \"        coin_history[coin] = hist\\n\",\n        \"\\n\",\n        \"add_all_returns()\\n\",\n        \"\\n\",\n        \"# display data\\n\",\n        \"cumulative_returns\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"nW3xWLCNyeGN\",\n        \"outputId\": \"a5d7f42b-447b-4ec4-8b42-4bd845ba3b3b\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# average return per day\\n\",\n        \"average_returns\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"J9AOW3czykk-\",\n        \"outputId\": \"23d9564c-ae0e-4bb4-cf3e-bdb46e9e1639\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Excess matrix\\n\",\n        \"excess_matrix = np.zeros((hist_length, len(coins)))\\n\",\n        \"\\n\",\n        \"for i in range(0, hist_length):\\n\",\n        \"    for idx, coin in enumerate(coins):\\n\",\n        \"        excess_matrix[i][idx] = coin_history[coin].iloc[i]['excess_return']\\n\",\n        \"\\n\",\n        \"excess_matrix\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 424\n        },\n        \"id\": \"A3GuFe_-yq_Q\",\n        \"outputId\": \"3313aa46-88ef-4dbb-e07d-6cc6c9584eb9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# pretty print excess matrix\\n\",\n        \"pretty_matrix = pd.DataFrame(excess_matrix).copy()\\n\",\n        \"pretty_matrix.columns = coins\\n\",\n        \"pretty_matrix.index = coin_history[coins[0]].index\\n\",\n        \"\\n\",\n        \"pretty_matrix\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"rRYQ63frys8K\",\n        \"outputId\": \"d4df3245-f4e6-4511-dd8a-7c7e52cb4982\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Risk modelling\\n\",\n        \"\\n\",\n        \"# variance co-var matrix\\n\",\n        \"product_matrix = np.matmul(excess_matrix.transpose(), excess_matrix)\\n\",\n        \"var_covar_matrix = product_matrix / hist_length\\n\",\n        \"\\n\",\n        \"var_covar_matrix\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 81\n        },\n        \"id\": \"F_0y258Iz2-1\",\n        \"outputId\": \"f161c55d-5600-41da-f065-821c87340f33\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# pretty var_covar\\n\",\n        \"pretty_var_covar = pd.DataFrame(var_covar_matrix).copy()\\n\",\n        \"pretty_var_covar.columns = coins\\n\",\n        \"pretty_var_covar.index = coins\\n\",\n        \"\\n\",\n        \"pretty_var_covar\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"_HS7sq_Xz4Js\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Std dev\\n\",\n        \"\\n\",\n        \"std_dev = np.zeros((len(coins), 1))\\n\",\n        \"neg_std_dev = np.zeros((len(coins), 1))\\n\",\n        \"\\n\",\n        \"for idx, coin in enumerate(coins):\\n\",\n        \"    std_dev[idx][0] = np.std(coin_history[coin]['return'])\\n\",\n        \"    coin_history[coin]['downside_return'] = 0\\n\",\n        \"\\n\",\n        \"    coin_history[coin].loc[coin_history[coin]['return'] < 0,\\n\",\n        \"                           'downside_return'] = coin_history[coin]['return']**2\\n\",\n        \"    neg_std_dev[idx][0] = np.sqrt(coin_history[coin]['downside_return'].mean())\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 81\n        },\n        \"id\": \"gLpf-k1az77u\",\n        \"outputId\": \"d6dc063f-05b7-4a9f-de59-cc60b0cfee5e\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# pretty std\\n\",\n        \"pretty_std = pd.DataFrame(std_dev).copy()\\n\",\n        \"pretty_neg_std = pd.DataFrame(neg_std_dev).copy()\\n\",\n        \"pretty_comb = pd.concat([pretty_std, pretty_neg_std], axis=1)\\n\",\n        \"\\n\",\n        \"pretty_comb.columns = ['std dev', 'neg std dev']\\n\",\n        \"pretty_comb.index = coins\\n\",\n        \"\\n\",\n        \"pretty_comb\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"MAd19PQcz9A5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# std_product_mat\\n\",\n        \"std_product_matrix = np.matmul(std_dev, std_dev.transpose())\\n\",\n        \"\\n\",\n        \"# neg_prod_mat\\n\",\n        \"neg_std_product_matrix = np.matmul(neg_std_dev, neg_std_dev.transpose())\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 81\n        },\n        \"id\": \"O8aD5ZiYz-8E\",\n        \"outputId\": \"945391f5-8e3b-4369-cc0c-1cf927f72ef2\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"pretty_std_prod = pd.DataFrame(std_product_matrix).copy()\\n\",\n        \"pretty_std_prod.columns = coins\\n\",\n        \"pretty_std_prod.index = coins\\n\",\n        \"\\n\",\n        \"pretty_std_prod\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 81\n        },\n        \"id\": \"KecwUguO0Ago\",\n        \"outputId\": \"f77f4bd2-3314-4d7e-8525-078825a83a8c\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Corr matrix\\n\",\n        \"corr_matrix = var_covar_matrix / std_product_matrix\\n\",\n        \"pretty_corr = pd.DataFrame(corr_matrix).copy()\\n\",\n        \"pretty_corr.columns = coins\\n\",\n        \"pretty_corr.index = coins\\n\",\n        \"\\n\",\n        \"pretty_corr\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 424\n        },\n        \"id\": \"m62kaZFu0C0p\",\n        \"outputId\": \"b3c10014-afe1-4cdb-e5a3-3a1361b54501\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# see additional stuff we have added to the DF\\n\",\n        \"coin_history['ETH']\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"JdtkDBc90rM6\",\n        \"outputId\": \"19d1c7af-809e-4b1b-a1a0-b50bba67d425\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"def simulate_portfolio_growth(initial_amount, daily_returns):\\n\",\n        \"    portfolio_value = [initial_amount]\\n\",\n        \"    for ret in daily_returns:\\n\",\n        \"        portfolio_value.append(portfolio_value[-1] * (1 + ret))\\n\",\n        \"    return portfolio_value\\n\",\n        \"\\n\",\n        \"initial_investment = 100000\\n\",\n        \"\\n\",\n        \"eth_portfolio = simulate_portfolio_growth(initial_investment, coin_history[\\\"ETH\\\"]['return'])\\n\",\n        \"\\n\",\n        \"print(\\\"ETH Portfolio Growth:\\\", eth_portfolio)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 564\n        },\n        \"id\": \"ADBacxHA27v0\",\n        \"outputId\": \"3f5f8f35-4efc-473d-a5af-12515fa897b6\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Plotting the growth\\n\",\n        \"plt.figure(figsize=(10,6))\\n\",\n        \"plt.plot(eth_portfolio, label='ETH Portfolio', color='blue')\\n\",\n        \"plt.title('Portfolio Growth Over Time')\\n\",\n        \"plt.xlabel('Days')\\n\",\n        \"plt.ylabel('Portfolio Value')\\n\",\n        \"plt.legend()\\n\",\n        \"plt.grid(True)\\n\",\n        \"plt.show()\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"fWAx5OZ-302J\",\n        \"outputId\": \"a94346ac-4c16-428d-eac1-d8fbbd9208b4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# close dataframe\\n\",\n        \"eth_df = coin_history['ETH'][['close']].copy()\\n\",\n        \"\\n\",\n        \"# Convert to tensor\\n\",\n        \"close_tensor = torch.tensor(eth_df.values)\\n\",\n        \"\\n\",\n        \"# return dataframe\\n\",\n        \"eth_df = coin_history['ETH'][['return']].copy()\\n\",\n        \"\\n\",\n        \"# Convert to tensor\\n\",\n        \"return_tensor = torch.tensor(eth_df.values)\\n\",\n        \"\\n\",\n        \"# return_tensor = torch.tensor(eth_df.values)\\n\",\n        \"print(close_tensor)\\n\",\n        \"print(return_tensor)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"4M6hIqZ15aqs\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# Adapted from https://pypi.org/project/nbeats-pytorch/\\n\",\n        \"# author = {Philippe Remy},\\n\",\n        \"\\n\",\n        \"def squeeze_last_dim(tensor):\\n\",\n        \"    if len(tensor.shape) == 3 and tensor.shape[-1] == 1:  # (128, 10, 1) => (128, 10).\\n\",\n        \"        return tensor[..., 0]\\n\",\n        \"    return tensor\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def seasonality_model(thetas, t, device):\\n\",\n        \"    p = thetas.size()[-1]\\n\",\n        \"    assert p <= thetas.shape[1], 'thetas_dim is too big.'\\n\",\n        \"    p1, p2 = (p // 2, p // 2) if p % 2 == 0 else (p // 2, p // 2 + 1)\\n\",\n        \"    s1 = torch.tensor(np.array([np.cos(2 * np.pi * i * t) for i in range(p1)])).float()  # H/2-1\\n\",\n        \"    s2 = torch.tensor(np.array([np.sin(2 * np.pi * i * t) for i in range(p2)])).float()\\n\",\n        \"    S = torch.cat([s1, s2])\\n\",\n        \"    return thetas.mm(S.to(device))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def trend_model(thetas, t, device):\\n\",\n        \"    p = thetas.size()[-1]\\n\",\n        \"    assert p <= 4, 'thetas_dim is too big.'\\n\",\n        \"    T = torch.tensor(np.array([t ** i for i in range(p)])).float()\\n\",\n        \"    return thetas.mm(T.to(device))\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"def linear_space(backcast_length, forecast_length, is_forecast=True):\\n\",\n        \"    horizon = forecast_length if is_forecast else backcast_length\\n\",\n        \"    return np.arange(0, horizon) / horizon\\n\",\n        \"\\n\",\n        \"class Block(nn.Module):\\n\",\n        \"\\n\",\n        \"    def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5, share_thetas=False,\\n\",\n        \"                 nb_harmonics=None):\\n\",\n        \"        super(Block, self).__init__()\\n\",\n        \"        self.units = units\\n\",\n        \"        self.thetas_dim = thetas_dim\\n\",\n        \"        self.backcast_length = backcast_length\\n\",\n        \"        self.forecast_length = forecast_length\\n\",\n        \"        self.share_thetas = share_thetas\\n\",\n        \"        self.fc1 = nn.Linear(backcast_length, units)\\n\",\n        \"        self.fc2 = nn.Linear(units, units)\\n\",\n        \"        self.fc3 = nn.Linear(units, units)\\n\",\n        \"        self.fc4 = nn.Linear(units, units)\\n\",\n        \"        self.device = device\\n\",\n        \"        self.backcast_linspace = linear_space(backcast_length, forecast_length, is_forecast=False)\\n\",\n        \"        self.forecast_linspace = linear_space(backcast_length, forecast_length, is_forecast=True)\\n\",\n        \"        if share_thetas:\\n\",\n        \"            self.theta_f_fc = self.theta_b_fc = nn.Linear(units, thetas_dim, bias=False)\\n\",\n        \"        else:\\n\",\n        \"            self.theta_b_fc = nn.Linear(units, thetas_dim, bias=False)\\n\",\n        \"            self.theta_f_fc = nn.Linear(units, thetas_dim, bias=False)\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        x = squeeze_last_dim(x)\\n\",\n        \"        x = F.relu(self.fc1(x.to(self.device)))\\n\",\n        \"        x = F.relu(self.fc2(x))\\n\",\n        \"        x = F.relu(self.fc3(x))\\n\",\n        \"        x = F.relu(self.fc4(x))\\n\",\n        \"        return x\\n\",\n        \"\\n\",\n        \"    def __str__(self):\\n\",\n        \"        block_type = type(self).__name__\\n\",\n        \"        return f'{block_type}(units={self.units}, thetas_dim={self.thetas_dim}, ' \\\\\\n\",\n        \"               f'backcast_length={self.backcast_length}, forecast_length={self.forecast_length}, ' \\\\\\n\",\n        \"               f'share_thetas={self.share_thetas}) at @{id(self)}'\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class SeasonalityBlock(Block):\\n\",\n        \"\\n\",\n        \"    def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5, nb_harmonics=None):\\n\",\n        \"        if nb_harmonics:\\n\",\n        \"            super(SeasonalityBlock, self).__init__(units, nb_harmonics, device, backcast_length,\\n\",\n        \"                                                   forecast_length, share_thetas=True)\\n\",\n        \"        else:\\n\",\n        \"            super(SeasonalityBlock, self).__init__(units, forecast_length, device, backcast_length,\\n\",\n        \"                                                   forecast_length, share_thetas=True)\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        x = super(SeasonalityBlock, self).forward(x)\\n\",\n        \"        backcast = seasonality_model(self.theta_b_fc(x), self.backcast_linspace, self.device)\\n\",\n        \"        forecast = seasonality_model(self.theta_f_fc(x), self.forecast_linspace, self.device)\\n\",\n        \"        return backcast, forecast\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class TrendBlock(Block):\\n\",\n        \"\\n\",\n        \"    def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5, nb_harmonics=None):\\n\",\n        \"        super(TrendBlock, self).__init__(units, thetas_dim, device, backcast_length,\\n\",\n        \"                                         forecast_length, share_thetas=True)\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        x = super(TrendBlock, self).forward(x)\\n\",\n        \"        backcast = trend_model(self.theta_b_fc(x), self.backcast_linspace, self.device)\\n\",\n        \"        forecast = trend_model(self.theta_f_fc(x), self.forecast_linspace, self.device)\\n\",\n        \"        return backcast, forecast\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class GenericBlock(Block):\\n\",\n        \"\\n\",\n        \"    def __init__(self, units, thetas_dim, device, backcast_length=10, forecast_length=5, nb_harmonics=None):\\n\",\n        \"        super(GenericBlock, self).__init__(units, thetas_dim, device, backcast_length, forecast_length)\\n\",\n        \"\\n\",\n        \"        self.backcast_fc = nn.Linear(thetas_dim, backcast_length)\\n\",\n        \"        self.forecast_fc = nn.Linear(thetas_dim, forecast_length)\\n\",\n        \"\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        # no constraint for generic arch.\\n\",\n        \"        x = super(GenericBlock, self).forward(x)\\n\",\n        \"\\n\",\n        \"        theta_b = self.theta_b_fc(x)\\n\",\n        \"        theta_f = self.theta_f_fc(x)\\n\",\n        \"\\n\",\n        \"        backcast = self.backcast_fc(theta_b)  # generic. 3.3.\\n\",\n        \"        forecast = self.forecast_fc(theta_f)  # generic. 3.3.\\n\",\n        \"\\n\",\n        \"        return backcast, forecast\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class NBEATS(nn.Module):\\n\",\n        \"    SEASONALITY_BLOCK = 'seasonality'\\n\",\n        \"    TREND_BLOCK = 'trend'\\n\",\n        \"    GENERIC_BLOCK = 'generic'\\n\",\n        \"\\n\",\n        \"    def __init__(\\n\",\n        \"        self,\\n\",\n        \"        device=torch.device(\\\"cpu\\\"),\\n\",\n        \"        stack_types=(GENERIC_BLOCK, GENERIC_BLOCK),\\n\",\n        \"        nb_blocks_per_stack=1,\\n\",\n        \"        forecast_length=7,\\n\",\n        \"        backcast_length=14,\\n\",\n        \"        theta_dims=(2,2),\\n\",\n        \"        share_weights_in_stack=False,\\n\",\n        \"        hidden_layer_units=32,\\n\",\n        \"        nb_harmonics=None,\\n\",\n        \"    ):\\n\",\n        \"        super(NBEATS, self).__init__()\\n\",\n        \"        self.forecast_length = forecast_length\\n\",\n        \"        self.backcast_length = backcast_length\\n\",\n        \"        self.hidden_layer_units = hidden_layer_units\\n\",\n        \"        self.nb_blocks_per_stack = nb_blocks_per_stack\\n\",\n        \"        self.share_weights_in_stack = share_weights_in_stack\\n\",\n        \"        self.nb_harmonics = nb_harmonics  # for seasonal data\\n\",\n        \"        self.stack_types = stack_types\\n\",\n        \"        self.stacks = nn.ModuleList()\\n\",\n        \"        self.thetas_dim = theta_dims\\n\",\n        \"        self.device = device\\n\",\n        \"        print('| N-Beats')\\n\",\n        \"        for stack_id in range(len(self.stack_types)):\\n\",\n        \"            stack = self.create_stack(stack_id)\\n\",\n        \"            self.stacks.append(stack)\\n\",\n        \"        self.to(self.device)\\n\",\n        \"        # self.asset_weight_layer = nn.Softmax(dim=1)\\n\",\n        \"        # self.asset_classes = asset_classes\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    def create_stack(self, stack_id):\\n\",\n        \"        stack_type = self.stack_types[stack_id]\\n\",\n        \"        print(f'| --  Stack {stack_type.title()} (#{stack_id}) (share_weights_in_stack={self.share_weights_in_stack})')\\n\",\n        \"        blocks = nn.ModuleList()\\n\",\n        \"        for block_id in range(self.nb_blocks_per_stack):\\n\",\n        \"            block_init = NBEATS.select_block(stack_type)\\n\",\n        \"            if self.share_weights_in_stack and block_id != 0:\\n\",\n        \"                block = blocks[-1]  # pick up the last one when we share weights.\\n\",\n        \"            else:\\n\",\n        \"                block = block_init(\\n\",\n        \"                    self.hidden_layer_units, self.thetas_dim[stack_id],\\n\",\n        \"                    self.device, self.backcast_length, self.forecast_length,\\n\",\n        \"                    self.nb_harmonics\\n\",\n        \"                )\\n\",\n        \"            print(f'     | -- {block}')\\n\",\n        \"            blocks.append(block)\\n\",\n        \"        return blocks\\n\",\n        \"\\n\",\n        \"    @staticmethod\\n\",\n        \"    def select_block(block_type):\\n\",\n        \"        if block_type == NBEATS.SEASONALITY_BLOCK:\\n\",\n        \"            return SeasonalityBlock\\n\",\n        \"        elif block_type == NBEATS.TREND_BLOCK:\\n\",\n        \"            return TrendBlock\\n\",\n        \"        else:\\n\",\n        \"            return GenericBlock\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    def get_generic_and_interpretable_outputs(self):\\n\",\n        \"        g_pred = sum([a['value'][0] for a in self._intermediary_outputs if 'generic' in a['layer'].lower()])\\n\",\n        \"        i_pred = sum([a['value'][0] for a in self._intermediary_outputs if 'generic' not in a['layer'].lower()])\\n\",\n        \"        outputs = {o['layer']: o['value'][0] for o in self._intermediary_outputs}\\n\",\n        \"        return g_pred, i_pred,\\n\",\n        \"\\n\",\n        \"    def forward(self, backcast):\\n\",\n        \"        self._intermediary_outputs = []\\n\",\n        \"        backcast = squeeze_last_dim(backcast)\\n\",\n        \"        forecast = torch.zeros(size=(backcast.size()[0], self.forecast_length,))  # maybe batch size here.\\n\",\n        \"        for stack_id in range(len(self.stacks)):\\n\",\n        \"            for block_id in range(len(self.stacks[stack_id])):\\n\",\n        \"                b, f = self.stacks[stack_id][block_id](backcast)\\n\",\n        \"                backcast = backcast.to(self.device) - b\\n\",\n        \"                forecast = forecast.to(self.device) + f\\n\",\n        \"                block_type = self.stacks[stack_id][block_id].__class__.__name__\\n\",\n        \"                layer_name = f'stack_{stack_id}-{block_type}_{block_id}'\\n\",\n        \"\\n\",\n        \"        return backcast, forecast\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"tTH313qbRLMG\",\n        \"outputId\": \"34275438-5548-4a8b-f4a9-d96056ebde1c\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from torch.utils.data import Dataset, DataLoader\\n\",\n        \"\\n\",\n        \"class TimeSeriesDataset(Dataset):\\n\",\n        \"    def __init__(self, close_data, return_data, backcast_length, forecast_length, shuffle=True):\\n\",\n        \"        self.close_data = close_data\\n\",\n        \"        self.return_data = return_data\\n\",\n        \"        self.backcast_length = backcast_length\\n\",\n        \"        self.forecast_length = forecast_length\\n\",\n        \"        self.indices = list(range(len(self.close_data) - self.backcast_length - self.forecast_length + 1))\\n\",\n        \"        if shuffle:\\n\",\n        \"            np.random.shuffle(self.indices)\\n\",\n        \"\\n\",\n        \"    def __len__(self):\\n\",\n        \"        return len(self.close_data) - self.backcast_length - self.forecast_length + 1\\n\",\n        \"\\n\",\n        \"    def __getitem__(self, idx):\\n\",\n        \"        start = idx\\n\",\n        \"        end = idx + self.backcast_length\\n\",\n        \"        x = self.close_data[start:end]  # Take columns as needed\\n\",\n        \"        y = self.close_data[end:end+self.forecast_length]  # Adjust as per forecast columns needed\\n\",\n        \"        return x, y\\n\",\n        \"\\n\",\n        \"# Hyperparameters\\n\",\n        \"BACKCAST_LENGTH = 14\\n\",\n        \"FORECAST_LENGTH = 7\\n\",\n        \"\\n\",\n        \"train_length = round(len(close_tensor) * 0.7)\\n\",\n        \"train_dataset = TimeSeriesDataset(close_tensor[0:train_length], return_tensor[0:train_length], BACKCAST_LENGTH, FORECAST_LENGTH)\\n\",\n        \"test_dataset = TimeSeriesDataset(close_tensor[train_length:], return_tensor[train_length:], BACKCAST_LENGTH, FORECAST_LENGTH)\\n\",\n        \"train_loader = DataLoader(train_dataset)\\n\",\n        \"\\n\",\n        \"model = NBEATS(forecast_length=FORECAST_LENGTH, backcast_length=BACKCAST_LENGTH, device=('cuda' if torch.cuda.is_available() else 'cpu'))\\n\",\n        \"model = model.to('cuda' if torch.cuda.is_available() else 'cpu')\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"JJ8-nh2GLKN_\",\n        \"outputId\": \"0d761daa-0f14-4a50-be41-b17993a4a182\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"EPOCHS = 1\\n\",\n        \"\\n\",\n        \"num_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\\n\",\n        \"print(f\\\"Number of trainable parameters in model: {num_parameters}\\\")\\n\",\n        \"\\n\",\n        \"criterion = torch.nn.L1Loss()\\n\",\n        \"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\\n\",\n        \"\\n\",\n        \"for epoch in range(EPOCHS):\\n\",\n        \"    total_loss = 0.0\\n\",\n        \"    for batch_idx, (x, y) in enumerate(train_loader):\\n\",\n        \"        # Zero gradients\\n\",\n        \"        optimizer.zero_grad()\\n\",\n        \"\\n\",\n        \"        x = x.clone().detach().to(dtype=torch.float)\\n\",\n        \"        x = x.to('cuda' if torch.cuda.is_available() else 'cpu')\\n\",\n        \"        y = y.clone().detach().to(dtype=torch.float)\\n\",\n        \"        y = y.to('cuda' if torch.cuda.is_available() else 'cpu')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"        # Forward pass\\n\",\n        \"        forecast = model(x)\\n\",\n        \"\\n\",\n        \"        loss = criterion(forecast[0], y)\\n\",\n        \"\\n\",\n        \"        # Backprop and optimize\\n\",\n        \"        loss.backward()\\n\",\n        \"        optimizer.step()\\n\",\n        \"\\n\",\n        \"        # add positive gain for logging\\n\",\n        \"        total_loss += loss  # add the positive gain_loss for logging\\n\",\n        \"\\n\",\n        \"    avg_loss = total_loss / len(train_loader)\\n\",\n        \"    print(f\\\"Epoch {epoch+1}/{EPOCHS}, Average Loss: {avg_loss:.4f}\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"jWLKwNFLYDOk\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"import ezkl\\n\",\n        \"import os\\n\",\n        \"import json\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"dhOHiCmt4pUn\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"xsZ9xg7I48l4\",\n        \"outputId\": \"6dec08c6-f55e-4df1-b957-55d025286018\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n        \"x_export = None\\n\",\n        \"for batch_idx, (x, y) in enumerate(train_loader):\\n\",\n        \"    x_export = x.clone().detach().to(dtype=torch.float)\\n\",\n        \"    break\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"model.eval()\\n\",\n        \"\\n\",\n        \"    # Export the model\\n\",\n        \"torch.onnx.export(model,               # model being run\\n\",\n        \"                      x_export,                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array])\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path, 'w' ))\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"5qdEFK_75GUb\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"run_args = ezkl.PyRunArgs()\\n\",\n        \"run_args.input_visibility = \\\"private\\\"\\n\",\n        \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n        \"run_args.output_visibility = \\\"public\\\"\\n\",\n        \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n        \"\\n\",\n        \"!RUST_LOG=trace\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\", max_logrows = 20, scales = [3])\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"pxDJPz-Q5LPF\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"ptcb4SGA5Qeb\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"OE7t0okU5WBQ\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 30,\n      \"metadata\": {\n        \"id\": \"12YIcFr85X9-\"\n      },\n      \"outputs\": [\n        {\n          \"name\": \"stderr\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"spawning module 2\\n\"\n          ]\n        },\n        {\n          \"name\": \"stdout\",\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"quotient_poly_degree 4\\n\",\n            \"n 262144\\n\",\n            \"extended_k 20\\n\"\n          ]\n        }\n      ],\n      \"source\": [\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"CSbWeZB35awS\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"aGt8f4LS5dTP\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# VERIFY IT\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"accelerator\": \"GPU\",\n    \"colab\": {\n      \"gpuType\": \"T4\",\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/proof_splitting.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Proof splitting\\n\",\n                \"\\n\",\n                \"Here we showcase how to split a larger circuit into multiple smaller proofs. This is useful if you want to prove over multiple machines, or if you want to split a proof into multiple parts to reduce the memory requirements.\\n\",\n                \"\\n\",\n                \"We showcase how to do this in the case where:\\n\",\n                \"- intermediate calculations can be public (i.e. they do not need to be kept secret) and we can stitch the circuits together using instances\\n\",\n                \"- intermediate calculations need to be kept secret (but not blinded !)  and we need to use the low overhead kzg commitment scheme detailed [here](https://blog.ezkl.xyz/post/commits/) to stitch the circuits together. \\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"First we import the necessary dependencies and set up logging to be as informative as possible. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# uncomment for more descriptive logging \\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.INFO)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we define our model. It is a humble model with but a conv layer and a $ReLU$ non-linearity, but it is a model nonetheless\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, \\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=3, out_channels=1, kernel_size=2, stride=4)\\n\",\n                \"        self.conv2 = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=2, stride=4)\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = self.conv2(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        return x\\n\",\n                \"    \\n\",\n                \"    def split_1(self, x):\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        return x\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# this is where you'd train your model\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \\n\",\n                \"Now we export the model to onnx and create a corresponding (randomly generated) input file.\\n\",\n                \"\\n\",\n                \"You can replace the random `x` with real data if you so wish. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = torch.rand(1,*[3, 8, 8], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"data_path = os.path.join(os.getcwd(), \\\"input_0.json\\\")\\n\",\n                \"data = dict(input_data = [((x).detach().numpy()).reshape([-1]).tolist()])\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\",\n                \"\\n\",\n                \"inter_1 = circuit.split_1(x)\\n\",\n                \"data_path = os.path.join(os.getcwd(), \\\"input_1.json\\\")\\n\",\n                \"data = dict(input_data = [((inter_1).detach().numpy()).reshape([-1]).tolist()])\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we split the model into two parts. The first part is the first conv layer and the second part is the rest of the model.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import onnx\\n\",\n                \"\\n\",\n                \"input_path = \\\"network.onnx\\\"\\n\",\n                \"output_path = \\\"network_split_0.onnx\\\"\\n\",\n                \"input_names = [\\\"input\\\"]\\n\",\n                \"output_names = [\\\"/relu/Relu_output_0\\\"]\\n\",\n                \"# first model\\n\",\n                \"onnx.utils.extract_model(input_path, output_path, input_names, output_names)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import onnx\\n\",\n                \"\\n\",\n                \"input_path = \\\"network.onnx\\\"\\n\",\n                \"output_path = \\\"network_split_1.onnx\\\"\\n\",\n                \"input_names = [\\\"/relu/Relu_output_0\\\"]\\n\",\n                \"output_names = [\\\"output\\\"]\\n\",\n                \"# second model\\n\",\n                \"onnx.utils.extract_model(input_path, output_path, input_names, output_names)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Public intermediate calculations\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n                \"- `input_visibility` defines the visibility of the model inputs\\n\",\n                \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n                \"- `output_visibility` defines the visibility of the model outputs\\n\",\n                \"\\n\",\n                \"There are currently 5 visibility settings:\\n\",\n                \"- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \\n\",\n                \"- `private`: known only to the prover\\n\",\n                \"- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \\n\",\n                \"- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypted element, the public key used to encrypt, and the hash of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\\n\",\n                \"- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be modified directly within the proof bytes.  \\n\",\n                \"\\n\",\n                \"Here we create the following setup:\\n\",\n                \"- `input_visibility`: \\\"public\\\"\\n\",\n                \"- `param_visibility`: \\\"public\\\"\\n\",\n                \"- `output_visibility`: public\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"public\\\"\\n\",\n                \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.input_scale = 2\\n\",\n                \"run_args.logrows = 8\\n\",\n                \"\\n\",\n                \"ezkl.get_srs(logrows=run_args.logrows, commitment=ezkl.PyCommitments.KZG)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. \\n\",\n                \"\\n\",\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \\n\",\n                \"\\n\",\n                \"We also need to generate the (partial) circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# iterate over each submodel gen-settings, compile circuit and setup zkSNARK\\n\",\n                \"\\n\",\n                \"def setup(i):\\n\",\n                \"    # file names\\n\",\n                \"    model_path = os.path.join('network_split_'+str(i)+'.onnx')\\n\",\n                \"    settings_path = os.path.join('settings_split_'+str(i)+'.json')\\n\",\n                \"    data_path =  os.path.join('input_'+str(i)+'.json')\\n\",\n                \"    compiled_model_path = os.path.join('network_split_'+str(i)+'.compiled')\\n\",\n                \"    pk_path = os.path.join('test_split_'+str(i)+'.pk')\\n\",\n                \"    vk_path = os.path.join('test_split_'+str(i)+'.vk')\\n\",\n                \"    witness_path = os.path.join('witness_split_'+str(i)+'.json')\\n\",\n                \"\\n\",\n                \"    if i > 0:\\n\",\n                \"         prev_witness_path = os.path.join('witness_split_'+str(i-1)+'.json')\\n\",\n                \"         witness = json.load(open(prev_witness_path, 'r'))\\n\",\n                \"         data = dict(input_data = witness['outputs'])\\n\",\n                \"         # Serialize data into file:\\n\",\n                \"         json.dump(data, open(data_path, 'w' ))\\n\",\n                \"    else:\\n\",\n                \"         data_path = os.path.join('input_0.json')\\n\",\n                \"\\n\",\n                \"    # generate settings for the current model\\n\",\n                \"    res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"    res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\", scales=[run_args.input_scale], max_logrows=run_args.logrows)\\n\",\n                \"    assert res == True\\n\",\n                \"\\n\",\n                \"    # load settings and print them to the console\\n\",\n                \"    settings = json.load(open(settings_path, 'r'))\\n\",\n                \"    settings['run_args']['logrows'] = run_args.logrows\\n\",\n                \"    json.dump(settings, open(settings_path, 'w' ))\\n\",\n                \"\\n\",\n                \"    res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    res = ezkl.setup(\\n\",\n                \"         compiled_model_path,\\n\",\n                \"         vk_path,\\n\",\n                \"         pk_path,\\n\",\n                \"      )\\n\",\n                \"\\n\",\n                \"    assert res == True\\n\",\n                \"    assert os.path.isfile(vk_path)\\n\",\n                \"    assert os.path.isfile(pk_path)\\n\",\n                \"\\n\",\n                \"    res = ezkl.gen_witness(data_path, compiled_model_path, witness_path, vk_path)\\n\",\n                \"    run_args.input_scale = settings[\\\"model_output_scales\\\"][0]\\n\",\n                \"\\n\",\n                \"for i in range(2):\\n\",\n                \"    setup(i)\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"def prove_model(i):\\n\",\n                \"    proof_path = os.path.join('proof_split_'+str(i)+'.json')\\n\",\n                \"    witness_path = os.path.join('witness_split_'+str(i)+'.json')\\n\",\n                \"    compiled_model_path = os.path.join('network_split_'+str(i)+'.compiled')\\n\",\n                \"    pk_path = os.path.join('test_split_'+str(i)+'.pk')\\n\",\n                \"    vk_path = os.path.join('test_split_'+str(i)+'.vk')\\n\",\n                \"    settings_path = os.path.join('settings_split_'+str(i)+'.json')\\n\",\n                \"\\n\",\n                \"    res = ezkl.prove(\\n\",\n                \"            witness_path,\\n\",\n                \"            compiled_model_path,\\n\",\n                \"            pk_path,\\n\",\n                \"            proof_path,\\n\",\n                \"            \\\"for-aggr\\\",\\n\",\n                \"        )\\n\",\n                \"\\n\",\n                \"    print(res)\\n\",\n                \"    res_1_proof = res[\\\"proof\\\"]\\n\",\n                \"    assert os.path.isfile(proof_path)\\n\",\n                \"\\n\",\n                \"    # # Verify the proof\\n\",\n                \"    if i > 0:\\n\",\n                \"        print(\\\"swapping commitments\\\")\\n\",\n                \"        # swap the proof commitments if we are not the first model\\n\",\n                \"        prev_witness_path = os.path.join('witness_split_'+str(i-1)+'.json')\\n\",\n                \"        prev_witness = json.load(open(prev_witness_path, 'r'))\\n\",\n                \"\\n\",\n                \"        witness = json.load(open(witness_path, 'r'))\\n\",\n                \"\\n\",\n                \"        print(prev_witness[\\\"processed_outputs\\\"])\\n\",\n                \"        print(witness[\\\"processed_inputs\\\"])\\n\",\n                \"        witness[\\\"processed_inputs\\\"] = prev_witness[\\\"processed_outputs\\\"]\\n\",\n                \"\\n\",\n                \"        # now save the witness\\n\",\n                \"        with open(witness_path, \\\"w\\\") as f:\\n\",\n                \"            json.dump(witness, f)\\n\",\n                \"\\n\",\n                \"        res = ezkl.swap_proof_commitments(proof_path, witness_path)\\n\",\n                \"        print(res)\\n\",\n                \"        \\n\",\n                \"        # load proof and then print \\n\",\n                \"        proof = json.load(open(proof_path, 'r'))\\n\",\n                \"        res_2_proof = proof[\\\"hex_proof\\\"]\\n\",\n                \"        # show diff in hex strings\\n\",\n                \"        print(res_1_proof)\\n\",\n                \"        print(res_2_proof)\\n\",\n                \"        assert res_1_proof == res_2_proof\\n\",\n                \"\\n\",\n                \"    res = ezkl.verify(\\n\",\n                \"            proof_path,\\n\",\n                \"            settings_path,\\n\",\n                \"            vk_path,\\n\",\n                \"        )\\n\",\n                \"\\n\",\n                \"    assert res == True\\n\",\n                \"    print(\\\"verified\\\")\\n\",\n                \"\\n\",\n                \"for i in range(2):\\n\",\n                \"    prove_model(i)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"###  KZG commitment intermediate calculations\\n\",\n                \"\\n\",\n                \"This time the visibility parameters are:\\n\",\n                \"- `input_visibility`: \\\"polycommit\\\"\\n\",\n                \"- `param_visibility`: \\\"public\\\"\\n\",\n                \"- `output_visibility`: polycommit\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n                \"run_args.output_visibility = \\\"polycommit\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"run_args.input_scale = 2\\n\",\n                \"run_args.logrows = 8\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"for i in range(2):\\n\",\n                \"    setup(i)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"for i in range(2):\\n\",\n                \"    prove_model(i)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"You can also mock aggregate the split proofs into a single proof. This is useful if you want to verify the proof on chain at a lower cost. Here we mock aggregate the proofs to save time. You can use other notebooks to see how to aggregate in full ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now mock aggregate the proofs\\n\",\n                \"proofs = []\\n\",\n                \"for i in range(2):\\n\",\n                \"    proof_path = os.path.join('proof_split_'+str(i)+'.json')\\n\",\n                \"    proofs.append(proof_path)\\n\",\n                \"\\n\",\n                \"ezkl.mock_aggregate(proofs, logrows=22, split_proofs = True)\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"ezkl\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        },\n        \"orig_nbformat\": 4\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/random_forest.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {\n                \"image-2.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAokAAARDCAYAAAAEdLvJAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/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4B4E0BQYOHGglJSVp3qXxy3VvWuIa98nkNwMGDLCuXbtm8pbcK0EB7BOE4jQEMiRAkJghSG4TTgG1MD766KP2q1/9yh588EH7+c9/bh/5yEeSLuw555xjo0aNSvq65i7QvrY//elP7Zvf/Kbde++9NnPmzLr9hpu7NijfX3rppXb//ffHZXfw4MH22GOPuZ1R4r6MOTBhwgQbPXp03ZF073fWWWfZ2LFj6+4X5g/pWmEf5l8HZYuCAEFiFGqZMqYloEV1L7vsMvvc5z5nt9xyi1100UWmlkE/pM9//vMugP3qV79qV155pQuYpkyZ4oesZSwPGq/Yu3dvGzp06HH3vOCCC477u7E/FCAOGzas7ut071d3owh8SNcK+wj8SChiqAWivVJtqKuWwmVDYOPGjfbee+9Z//79bc2aNTZx4kS75JJL3NItb775pv361792jy0qKrL/+I//MLV2rV+//rjZwF6Ln07U/rRXXXWVffe733XXffSjH7UPfehDbhHpF1980f70pz+54409p7i42LZv3+7O0dI03//+991MbR1Qq+Kzzz5ry5Ytc9//8Ic/tJtuusntR6zvtm3bZmrpefvtt23lypV2/vnnu+f+6Ec/qrvGXeiDf8hWLXjKp5J8FTR6f+uYguPPfOYzrttdx++55x6bNGmSTZ8+3a2/KOv/9//+n0615u7Xr18/++QnP2l33HGHO//UU0+1Xr161dWHOxiRfzRnJQbsI/JjoJiRE6AlMXJVToHTEVCLlLoalyxZYp07d7bLL7/cbrvtNps1a5b16NHDTj/9dHd7BSubN292rXu//OUvXbDiPVeBnZfUna37KE2ePNlOOukku/766+3aa6+1MWPGuBawpp7zyCOPuNbNL3/5y3byySe7YMhbnqZjx47HLSvTpUsX9xytB6l7qxtdAerIkSOtT58+9pWvfMUFQQoW/Zbeeust12Ws4FDplFNOMW2bp8DYS+p6/853vuPMtSi3PF577TV77rnn7K9//WtdgKjzm7ufjDp16uTd2gWe7du3r/s7Sh+as5IF9lH6RVDWKAkQJEaptilrSgKaEKKxiL/4xS9cQHjnnXe61rsRI0a4btCpU6faueeeawrK1HKlpCDs73//u2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FTkSuQmCC\"\n                },\n                \"image.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAUAAAAEbCAYAAACr2V2eAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/PGzLySIb4h7mNFNU/8RBzRWnS9hUvGGvvK4KUPF8yFOeoD9IeQRgEmshAxhRzimEAM41D+2Uk0djIog2MDFlagowiHtlOkcBjkJmKGHBmiiBBL5Cch7t369w2bWrkKJN+AQKWpaYfA2S7FvG9qI0dA7w5wes1VS/25rFAL2stxyedwGuh8dN3XUSC0D9Qrrvtedd36Mfk/ABfmJ+uTZFvl1hD0AAAAVmVYSWZNTQAqAAAACAABh2kABAAAAAEAAAAaAAAAAAADkoYABwAAABIAAABEoAIABAAAAAEAAAFAoAMABAAAAAEAAAEbAAAAAEFTQ0lJAAAAU2NyZWVuc2hvdP5iyG4AAAHWaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA2LjAuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5z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3FApR4mSnLyZNdh58Tw8BBDA9vsiUpK6uzgwYMCDzPcpBoTTjx483+sPVnLzzzjvPZqf1ryNGjLDHGj2dOHFi5jbha5mTNXbQr18/8/nPf75gqaPEyc6gmDTZefA9PQQQwPT4IrGS/OQnP7HTUMI3eO6558wjjzxiT0kATzrppMzl8LXMSQ4g4CAB5gGW0alqOl5wwQVGLyU/4ogj7IYE99xzj33v7MiRI22tThsWvPXWW+aXv/ylUdNUNS/VzLQe9b777susKunRo4e55pprjFZ3LFq0yPzud7+zJR02bJg566yz7Psr3njjDaP8gz0A86W56qqrzK233trIUi36VxP40UcfNZdddplRx/2UKVPMvffea9cUB9fU3/mNb3zD9O3b175s6f777zcNDQ12GtD5559vunTpYqegPPDAA+a1115rdI+0fNGLz+UXjc5qtci0adPMu+++a4unVSqXXnqp6d69u7VL1zS6nM/utNhEOcpDgBpgeTjaXLQSQX1sL730kpk8ebJ58sknzbe+9S17TQKja7fccosVP/0xqjl6++23myuvvNKuKpGwBeGwww4zN954o72mZtfw4cPtJQnTTTfdZPPXSovgvC7mS6NF/tmThDUhOViidvPNN1sRlQBqKVj4mgRaKy2uuOIK8+tf/9pcdNFFthyjR482mvQrkZYIH3LIIfZ8Gn/on46EXj6ZN2+eOfXUUzPFHDJkiHnooYfstdWrV9t/LrqYz+5MQg6cIIAAltmNEoslS5bYXJ999lm7QiFYmiVhDNarqp/t5ZdftuKi5WLPPPOMGTRoUKY0+kNVzU7TRubOnZvpE3ziiSfstlfjxo0zQ4cONZ07d24yTSZCEQcTJkywgnjiiSeaQw891Kg2pZquhFK1yNNOO81Ob5k9e3YRuVcmycKFC+2NTjjhBPtPYuDAgZkbL1u2zNbYAx/079/fXstndyYhB04QQADL7EbVysJB31UzVNCSrSCoiRX+ruMgXnZcXVN8faZOnWoFUC8/z25yZuen+KUGlV/L2LRjij533XWXFeZXXnnFXHvttfYVnGoin3vuuaXeKrH0qoVrkEivC1X3Q3hFSnheYsBZBclnd2KFJOOqEEAAy4xdu7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IoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgEEMA4tIgLAQg4RQABdMqdGAMBCMQhgADGoUVcCEDAKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgE/gcCHHjHKxBaJwAAAABJRU5ErkJggg==\"\n                }\n            },\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Random forest\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image.png](attachment:image.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image-2.png](attachment:image-2.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `sk2torch` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"sk2torch\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from sklearn.ensemble import RandomForestClassifier as Rf\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = Rf()\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"torch_rf = convert(clr, 'torch')\\n\",\n                \"# assert predictions from torch are = to sklearn \\n\",\n                \"diffs = []\\n\",\n                \"for i in range(len(X_test)):\\n\",\n                \"    torch_pred = torch_rf.predict(torch.tensor(X_test[i].reshape(1, -1)))\\n\",\n                \"    sk_pred = clr.predict(X_test[i].reshape(1, -1))\\n\",\n                \"    diffs.append(torch_pred[0].round() - sk_pred[0])\\n\",\n                \"\\n\",\n                \"print(\\\"num diffs\\\", sum(diffs))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# !!!!!!!!!!!!!!!!! This cell will flash a warning about onnx runtime compat but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=False)\\n\",\n                \"torch_out = torch_rf.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(torch_rf.model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=11,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[o.reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.12.2\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/set_membership.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n      \"metadata\": {\n        \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\"\n      },\n      \"source\": [\n        \"## Hash set membership demo\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"95613ee9\",\n      \"metadata\": {\n        \"id\": \"95613ee9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"pytest\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"import logging\\n\",\n        \"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n        \"logging.basicConfig(format=FORMAT)\\n\",\n        \"logging.getLogger().setLevel(logging.DEBUG)\\n\",\n        \"\\n\",\n        \"# here we create and (potentially train a model)\\n\",\n        \"\\n\",\n        \"# make sure you have the dependencies required here already installed\\n\",\n        \"from torch import nn\\n\",\n        \"import ezkl\\n\",\n        \"import os\\n\",\n        \"import json\\n\",\n        \"import torch\\n\",\n        \"\\n\",\n        \"class MyModel(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(MyModel, self).__init__()\\n\",\n        \"\\n\",\n        \"    def forward(self, x, y):\\n\",\n        \"        diff = (x - y)\\n\",\n        \"        membership_test = torch.prod(diff, dim=1)\\n\",\n        \"        return (membership_test,y)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"circuit = MyModel()\\n\",\n        \"\\n\",\n        \"# Train the model as you like here (skipped for brevity)\\n\",\n        \"\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b37637c4\",\n      \"metadata\": {\n        \"id\": \"b37637c4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"c833f08c\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"c833f08c\",\n        \"outputId\": \"b5c794e1-c787-4b65-e267-c005e661df1b\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# print pytorch version\\n\",\n        \"print(torch.__version__)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"82db373a\",\n      \"metadata\": {\n        \"id\": \"82db373a\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"\\n\",\n        \"x = torch.zeros(1,*[1], requires_grad=True)\\n\",\n        \"y = torch.tensor([0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], requires_grad=True)\\n\",\n        \"\\n\",\n        \"y_input = [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\\n\",\n        \"\\n\",\n        \"# Create an empty list to store the results\\n\",\n        \"result = []\\n\",\n        \"\\n\",\n        \"# Loop through each element in the y tensor\\n\",\n        \"for e in y_input:\\n\",\n        \"    # Apply the custom function and append the result to the list\\n\",\n        \"    print(ezkl.float_to_felt(e,7))\\n\",\n        \"    result.append(ezkl.poseidon_hash([ezkl.float_to_felt(e, 7)])[0])\\n\",\n        \"\\n\",\n        \"y = y.unsqueeze(0)\\n\",\n        \"y = y.reshape(1, 9)\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"circuit.eval()\\n\",\n        \"\\n\",\n        \"    # Export the model\\n\",\n        \"torch.onnx.export(circuit,               # model being run\\n\",\n        \"                      (x,y),                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=14,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"data_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"data_array_y = result\\n\",\n        \"print(data_array_y)\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array_x, data_array_y])\\n\",\n        \"\\n\",\n        \"print(data)\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path, 'w' ))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"d5e374a2\",\n      \"metadata\": {\n        \"id\": \"d5e374a2\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"run_args = ezkl.PyRunArgs()\\n\",\n        \"# \\\"hashed/private\\\" means that the output of the hashing is not visible to the verifier and is instead fed into the computational graph\\n\",\n        \"run_args.input_visibility = \\\"hashed/private/0\\\"\\n\",\n        \"# we set it to fix the set we want to check membership for\\n\",\n        \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n        \"# the output is public -- set membership fails if it is not = 0\\n\",\n        \"run_args.output_visibility = \\\"fixed\\\"\\n\",\n        \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n        \"# never rebase the scale\\n\",\n        \"run_args.scale_rebase_multiplier = 1000\\n\",\n        \"# logrows\\n\",\n        \"run_args.logrows = 11\\n\",\n        \"\\n\",\n        \"#  this creates the following sequence of ops:\\n\",\n        \"# 1. hash the input -> poseidon(x)\\n\",\n        \"# 2. compute the set difference -> poseidon(x) - set\\n\",\n        \"# 3. compute the product of the set difference -> prod(poseidon(x) - set)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n        \"assert res == True\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"3aa4f090\",\n      \"metadata\": {\n        \"id\": \"3aa4f090\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"8b74dcee\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"8b74dcee\",\n        \"outputId\": \"f7b9198c-2b3d-48bb-c67e-8478333cedb5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"18c8b7c7\",\n      \"metadata\": {\n        \"id\": \"18c8b7c7\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate the witness file\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"Y94vCo5Znrim\",\n      \"metadata\": {\n        \"id\": \"Y94vCo5Znrim\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate a faulty input + witness file (x input not in the set)\\n\",\n        \"\\n\",\n        \"data_path_faulty = os.path.join('input_faulty.json')\\n\",\n        \"\\n\",\n        \"witness_path_faulty = os.path.join('witness_faulty.json')\\n\",\n        \"\\n\",\n        \"x = torch.ones(1,*[1], requires_grad=True)\\n\",\n        \"y = torch.tensor([0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], requires_grad=True)\\n\",\n        \"\\n\",\n        \"y = y.unsqueeze(0)\\n\",\n        \"y = y.reshape(1, 9)\\n\",\n        \"\\n\",\n        \"data_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"data_array_y = result\\n\",\n        \"print(data_array_y)\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array_x, data_array_y])\\n\",\n        \"\\n\",\n        \"print(data)\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path_faulty, 'w' ))\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path_faulty, compiled_model_path, witness_path_faulty)\\n\",\n        \"assert os.path.isfile(witness_path_faulty)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"FQfGdcUNpvuK\",\n      \"metadata\": {\n        \"id\": \"FQfGdcUNpvuK\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate a truthy input + witness file (x input not in the set)\\n\",\n        \"import random\\n\",\n        \"\\n\",\n        \"# Generate a random integer between 1 and 8, inclusive\\n\",\n        \"random_value = random.randint(1, 8)\\n\",\n        \"\\n\",\n        \"data_path_truthy = os.path.join('input_truthy.json')\\n\",\n        \"\\n\",\n        \"witness_path_truthy = os.path.join('witness_truthy.json')\\n\",\n        \"\\n\",\n        \"set = [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\\n\",\n        \"\\n\",\n        \"x = torch.tensor([set[random_value]])\\n\",\n        \"y = torch.tensor(set, requires_grad=True)\\n\",\n        \"\\n\",\n        \"y = y.unsqueeze(0)\\n\",\n        \"y = y.reshape(1, 9)\\n\",\n        \"\\n\",\n        \"x = x.unsqueeze(0)\\n\",\n        \"x = x.reshape(1,1)\\n\",\n        \"\\n\",\n        \"data_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"data_array_y = result\\n\",\n        \"print(data_array_y)\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array_x, data_array_y])\\n\",\n        \"\\n\",\n        \"print(data)\\n\",\n        \"\\n\",\n        \"# Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path_truthy, 'w' ))\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path_truthy, compiled_model_path, witness_path_truthy)\\n\",\n        \"assert os.path.isfile(witness_path_truthy)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"41fd15a8\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"witness = json.load(open(witness_path, \\\"r\\\"))\\n\",\n        \"witness\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b1c561a8\",\n      \"metadata\": {\n        \"id\": \"b1c561a8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n        \"# WE GOT KEYS\\n\",\n        \"# WE GOT CIRCUIT PARAMETERS\\n\",\n        \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n        \"\\n\",\n        \"# we force the output to be 0 this corresponds to the set membership test being true -- and we set this to a fixed vis output\\n\",\n        \"# this means that the output is fixed and the verifier can see it but that if the input is not in the set the output will not be 0 and the verifier will reject\\n\",\n        \"witness = json.load(open(witness_path, \\\"r\\\"))\\n\",\n        \"witness[\\\"outputs\\\"][0] = [\\\"0000000000000000000000000000000000000000000000000000000000000000\\\"]\\n\",\n        \"json.dump(witness, open(witness_path, \\\"w\\\"))\\n\",\n        \"\\n\",\n        \"witness = json.load(open(witness_path, \\\"r\\\"))\\n\",\n        \"print(witness[\\\"outputs\\\"][0])\\n\",\n        \"\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        witness_path = witness_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"c384cbc8\",\n      \"metadata\": {\n        \"id\": \"c384cbc8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"XAC73EvtpM-W\",\n      \"metadata\": {\n        \"id\": \"XAC73EvtpM-W\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A FAULTY PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path_faulty = os.path.join('test_faulty.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path_faulty,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path_faulty,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path_faulty)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"_x19Q4FUrKb6\",\n      \"metadata\": {\n        \"id\": \"_x19Q4FUrKb6\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A TRUTHY PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path_truthy = os.path.join('test_truthy.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path_truthy,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path_truthy,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path_truthy)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"76f00d41\",\n      \"metadata\": {\n        \"id\": \"76f00d41\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# VERIFY IT\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path_truthy,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"4nqEx7-qpciQ\",\n      \"metadata\": {\n        \"id\": \"4nqEx7-qpciQ\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import pytest\\n\",\n        \"def test_verification():\\n\",\n        \"    with pytest.raises(RuntimeError, match='Failed to run verify: The constraint system is not satisfied'):\\n\",\n        \"        ezkl.verify(\\n\",\n        \"            proof_path_faulty,\\n\",\n        \"            settings_path,\\n\",\n        \"            vk_path,\\n\",\n        \"            \\n\",\n        \"        )\\n\",\n        \"\\n\",\n        \"# Run the test function\\n\",\n        \"test_verification()\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3 (ipykernel)\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/simple_demo_aggregated_proofs.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL Jupyter Notebook Demo (Aggregated Proofs) \\n\",\n                \"\\n\",\n                \"Demonstrates how to use EZKL with aggregated proofs\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers\\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\\n\",\n                \"        self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\\n\",\n                \"\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"        self.d1 = nn.Linear(48, 48)\\n\",\n                \"        self.d2 = nn.Linear(48, 10)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        # 32x1x28x28 => 32x32x26x26\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = self.conv2(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # flatten => 32 x (32*26*26)\\n\",\n                \"        x = x.flatten(start_dim = 1)\\n\",\n                \"\\n\",\n                \"        # 32 x (32*26*26) => 32x128\\n\",\n                \"        x = self.d1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # logits => 32x10\\n\",\n                \"        logits = self.d2(x)\\n\",\n                \"\\n\",\n                \"        return logits\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# Train the model as you like here (skipped for brevity)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"srs_path = os.path.join('kzg.srs')\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"aggregate_proof_path = os.path.join('aggr.pf')\\n\",\n                \"aggregate_vk_path = os.path.join('aggr.vk')\\n\",\n                \"aggregate_pk_path = os.path.join('aggr.pk')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"shape = [1, 28, 28]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*torch.rand(1,*shape, requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"for-aggr\\\",  # IMPORTANT NOTE: To produce an aggregated EVM proof you will want to use poseidon for the smaller proofs\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"0832b909\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Generate a larger SRS. This is needed for the aggregated proof\\n\",\n                \"\\n\",\n                \"res = ezkl.get_srs(settings_path=None, logrows=21, commitment=ezkl.PyCommitments.KZG)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c5a64be6\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Run mock aggregate to check whether the proof works\\n\",\n                \"# Use mock to check for validity as it takes a shorter time to check compared to a full aggregated proof\\n\",\n                \"\\n\",\n                \"res = ezkl.mock_aggregate([proof_path], 21)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"fee8acc6\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Setup the vk and pk for aggregate\\n\",\n                \"res = ezkl.setup_aggregate(\\n\",\n                \"    [proof_path],\\n\",\n                \"    aggregate_vk_path,\\n\",\n                \"    aggregate_pk_path,\\n\",\n                \"    21\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert os.path.isfile(aggregate_vk_path)\\n\",\n                \"assert os.path.isfile(aggregate_pk_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"171702d3\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Run aggregate proof\\n\",\n                \"res = ezkl.aggregate(\\n\",\n                \"    [proof_path],\\n\",\n                \"    aggregate_proof_path,\\n\",\n                \"    aggregate_pk_path,\\n\",\n                \"    \\\"evm\\\",\\n\",\n                \"    21,\\n\",\n                \"    \\\"safe\\\"\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert os.path.isfile(aggregate_proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"671dfdd5\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Check if the proof is valid\\n\",\n                \"res = ezkl.verify_aggr(\\n\",\n                \"    aggregate_proof_path,\\n\",\n                \"    aggregate_vk_path,\\n\",\n                \"    21,\\n\",\n                \")\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"50eba2f4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Create a smart contract verifier for the aggregated proof\\n\",\n                \"\\n\",\n                \"sol_code_path = os.path.join(\\\"Verifier.sol\\\")\\n\",\n                \"abi_path = os.path.join(\\\"Verifier_ABI.json\\\")\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier_aggr(\\n\",\n                \"    [settings_path],\\n\",\n                \"    aggregate_vk_path,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    abi_path,\\n\",\n                \"    logrows=21)\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/simple_demo_all_public.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL Jupyter Notebook Demo \\n\",\n                \"\\n\",\n                \"Here we demonstrate the use of the EZKL package in a Jupyter notebook whereby all components of the circuit are public or pre-committed to. This is the simplest case of using EZKL (proof of computation).\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers\\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\\n\",\n                \"        self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\\n\",\n                \"\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"        self.d1 = nn.Linear(48, 48)\\n\",\n                \"        self.d2 = nn.Linear(48, 10)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        # 32x1x28x28 => 32x32x26x26\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = self.conv2(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # flatten => 32 x (32*26*26)\\n\",\n                \"        x = x.flatten(start_dim = 1)\\n\",\n                \"\\n\",\n                \"        # 32 x (32*26*26) => 32x128\\n\",\n                \"        x = self.d1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # logits => 32x10\\n\",\n                \"        logits = self.d2(x)\\n\",\n                \"\\n\",\n                \"        return logits\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# Train the model as you like here (skipped for brevity)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"shape = [1, 28, 28]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*torch.rand(1,*shape, requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"py_run_args = ezkl.PyRunArgs()\\n\",\n                \"py_run_args.input_visibility = \\\"public\\\"\\n\",\n                \"py_run_args.output_visibility = \\\"public\\\"\\n\",\n                \"py_run_args.param_visibility = \\\"fixed\\\" # \\\"fixed\\\" for params means that the committed to params are used for all proofs\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/simple_demo_public_input_output.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL Jupyter Notebook Demo \\n\",\n                \"\\n\",\n                \"Here we demonstrate how to use the EZKL package to run a private network on public data to produce a public output.\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers\\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\\n\",\n                \"        self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\\n\",\n                \"\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"        self.d1 = nn.Linear(48, 48)\\n\",\n                \"        self.d2 = nn.Linear(48, 10)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        # 32x1x28x28 => 32x32x26x26\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = self.conv2(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # flatten => 32 x (32*26*26)\\n\",\n                \"        x = x.flatten(start_dim = 1)\\n\",\n                \"\\n\",\n                \"        # 32 x (32*26*26) => 32x128\\n\",\n                \"        x = self.d1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # logits => 32x10\\n\",\n                \"        logits = self.d2(x)\\n\",\n                \"\\n\",\n                \"        return logits\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# Train the model as you like here (skipped for brevity)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"shape = [1, 28, 28]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*torch.rand(1,*shape, requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"py_run_args = ezkl.PyRunArgs()\\n\",\n                \"py_run_args.input_visibility = \\\"public\\\"\\n\",\n                \"py_run_args.output_visibility = \\\"public\\\"\\n\",\n                \"py_run_args.param_visibility = \\\"private\\\" # private by default\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/simple_demo_public_network_output.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## EZKL Jupyter Notebook Demo \\n\",\n                \"\\n\",\n                \"Here we demonstrate how to use the EZKL package to run a publicly known / committed to network on some private data, producing a public output.\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers\\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\\n\",\n                \"        self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\\n\",\n                \"\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"        self.d1 = nn.Linear(48, 48)\\n\",\n                \"        self.d2 = nn.Linear(48, 10)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        # 32x1x28x28 => 32x32x26x26\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = self.conv2(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # flatten => 32 x (32*26*26)\\n\",\n                \"        x = x.flatten(start_dim = 1)\\n\",\n                \"\\n\",\n                \"        # 32 x (32*26*26) => 32x128\\n\",\n                \"        x = self.d1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"\\n\",\n                \"        # logits => 32x10\\n\",\n                \"        logits = self.d2(x)\\n\",\n                \"\\n\",\n                \"        return logits\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"# Train the model as you like here (skipped for brevity)\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"shape = [1, 28, 28]\\n\",\n                \"# After training, export to onnx (network.onnx) and create a data file (input.json)\\n\",\n                \"x = 0.1*torch.rand(1,*shape, requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(data_path, 'w' ))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"py_run_args = ezkl.PyRunArgs()\\n\",\n                \"py_run_args.input_visibility = \\\"private\\\"\\n\",\n                \"py_run_args.output_visibility = \\\"public\\\"\\n\",\n                \"py_run_args.param_visibility = \\\"fixed\\\" # private by default\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args)\\n\",\n                \"\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 9,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/sklearn_mlp.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Sklearn MLP to ONNX\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format. \\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `hummingbird-ml` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from sklearn.neural_network import MLPClassifier\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = MLPClassifier()\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"circuit = convert(clr, \\\"torch\\\", X_test[:1]).model\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=True)\\n\",\n                \"torch_out = circuit(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/solvency.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n      \"metadata\": {\n        \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\"\n      },\n      \"source\": [\n        \"## Solvency demo\\n\",\n        \"\\n\",\n        \"Here we create a demo of a solvency calculation in the manner of [summa-solvency](https://github.com/summa-dev/summa-solvency). The aim here is to demonstrate the use of the new polycommit method detailed [here](https://blog.ezkl.xyz/post/commits/). \\n\",\n        \"\\n\",\n        \"In this setup:\\n\",\n        \"- the commitments to users, respective balances, and total balance are known are publicly known to the prover and verifier. \\n\",\n        \"- We leave the outputs of the model as public as well (known to the  verifier and prover). \\n\",\n        \"\\n\",\n        \"The circuit calculates the total sum of the balances, and checks that it is less than the total balance which is precommited to.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"95613ee9\",\n      \"metadata\": {\n        \"id\": \"95613ee9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"pytest\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"# uncomment to enable logging\\n\",\n        \"# import logging\\n\",\n        \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n        \"# logging.basicConfig(format=FORMAT)\\n\",\n        \"# logging.getLogger().setLevel(logging.DEBUG)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# here we create and (potentially train a model)\\n\",\n        \"\\n\",\n        \"# make sure you have the dependencies required here already installed\\n\",\n        \"from torch import nn\\n\",\n        \"import ezkl\\n\",\n        \"import os\\n\",\n        \"import json\\n\",\n        \"import torch\\n\",\n        \"\\n\",\n        \"class Circuit(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(Circuit, self).__init__()\\n\",\n        \"\\n\",\n        \"    def forward(self, users, balances, total):\\n\",\n        \"        nil = torch.nn.Parameter(torch.tensor([0.0]))\\n\",\n        \"        # calculate the total balance across all users second term will be ignored by the optimizer but will force it to be included in a separate col for commitment\\n\",\n        \"        balances = torch.sum(balances, dim=1) + nil * users\\n\",\n        \"        # now check if the total balance is less than the total\\n\",\n        \"        return (balances[:,0] <= total)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"circuit = Circuit()\\n\",\n        \"\\n\",\n        \"# Train the model as you like here (skipped for brevity)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b37637c4\",\n      \"metadata\": {\n        \"id\": \"b37637c4\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"model_path = os.path.join('network.onnx')\\n\",\n        \"compiled_model_path = os.path.join('network.compiled')\\n\",\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"settings_path = os.path.join('settings.json')\\n\",\n        \"\\n\",\n        \"witness_path = os.path.join('witness.json')\\n\",\n        \"data_path = os.path.join('input.json')\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"1c21e56e\",\n      \"metadata\": {},\n      \"source\": [\n        \"We create dummy data here for the sake of demonstration. In a real world scenario, the data would be provided by the users, and the commitments would be made by some trusted party.\\n\",\n        \"\\n\",\n        \"The users are generated as hashes of the integers 0 to 9. The balances are generated as integers between 0 and 10. \\n\",\n        \"\\n\",\n        \"The total balance is the sum of the balances.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"dfd6c7e7\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"\\n\",\n        \"user_preimages = [0.0, 1.0, 2.0, 3.0, 4.0, 9.0]\\n\",\n        \"balances = torch.tensor([0, 2, 3, 4, 5, 10])\\n\",\n        \"balances = balances.reshape(1, 6)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# Create an empty list to store the hashes of float -- which I guess we'll call the users here\\n\",\n        \"users = []\\n\",\n        \"\\n\",\n        \"# Loop through each element in the y tensor\\n\",\n        \"for e in user_preimages:\\n\",\n        \"    # Apply the custom function and append the result to the list\\n\",\n        \"    users.append(ezkl.poseidon_hash([ezkl.float_to_felt(e, 0)])[0])\\n\",\n        \"\\n\",\n        \"users_t = torch.tensor(user_preimages)\\n\",\n        \"users_t = users_t.reshape(1, 6)\\n\",\n        \"\\n\",\n        \"total = torch.tensor([25])\\n\",\n        \"total = total.reshape(1, 1)\\n\",\n        \"\\n\",\n        \"# Flips thegraph into inference mode\\n\",\n        \"circuit.eval()\\n\",\n        \"\\n\",\n        \"    # Export the model\\n\",\n        \"torch.onnx.export(circuit,               # model being run\\n\",\n        \"                      (users_t,balances,total),                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=17,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=False,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    \\n\",\n        \"data_array_x = users\\n\",\n        \"data_array_y = ((balances).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"data_array_z = ((total).detach().numpy()).reshape([-1]).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [data_array_x, data_array_y, data_array_z])\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path, 'w' ))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"22d3d8df\",\n      \"metadata\": {},\n      \"source\": [\n        \"This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n        \"- `input_visibility` defines the visibility of the model inputs\\n\",\n        \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n        \"- `output_visibility` defines the visibility of the model outputs\\n\",\n        \"\\n\",\n        \"There are currently 5 visibility settings:\\n\",\n        \"- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \\n\",\n        \"- `private`: known only to the prover\\n\",\n        \"- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \\n\",\n        \"- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypted element, the public key used to encrypt, and the hash of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\\n\",\n        \"- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be modified directly within the proof bytes.  \\n\",\n        \"\\n\",\n        \"Here we create the following setup:\\n\",\n        \"- `input_visibility`: \\\"polycommit\\\"\\n\",\n        \"- `param_visibility`: \\\"public\\\"\\n\",\n        \"- `output_visibility`: public\\n\",\n        \"\\n\",\n        \"We encourage you to play around with other setups :) \\n\",\n        \"\\n\",\n        \"Shoutouts: \\n\",\n        \"\\n\",\n        \"- [summa-solvency](https://github.com/summa-dev/summa-solvency) for their help with the poseidon hashing chip. \\n\",\n        \"- [timeofey](https://github.com/timoftime) for providing inspiration in our developement of the el-gamal encryption circuit in Halo2. \"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"d5e374a2\",\n      \"metadata\": {\n        \"id\": \"d5e374a2\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"run_args = ezkl.PyRunArgs()\\n\",\n        \"# \\\"polycommit\\\" means that the output of the hashing is not visible to the verifier and is instead fed into the computational graph\\n\",\n        \"run_args.input_visibility = \\\"polycommit\\\"\\n\",\n        \"# the parameters are public\\n\",\n        \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n        \"# the output is public (this is the inequality test)\\n\",\n        \"run_args.output_visibility = \\\"public\\\"\\n\",\n        \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n        \"# never rebase the scale\\n\",\n        \"run_args.scale_rebase_multiplier = 1000\\n\",\n        \"# logrows\\n\",\n        \"run_args.logrows = 11\\n\",\n        \"run_args.lookup_range = (-1000,1000)\\n\",\n        \"run_args.input_scale = 0\\n\",\n        \"run_args.param_scale = 0\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# TODO: Dictionary outputs\\n\",\n        \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n        \"assert res == True\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"3aa4f090\",\n      \"metadata\": {\n        \"id\": \"3aa4f090\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"8b74dcee\",\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"8b74dcee\",\n        \"outputId\": \"f7b9198c-2b3d-48bb-c67e-8478333cedb5\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# srs path\\n\",\n        \"res = ezkl.get_srs( settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"f7c98c96\",\n      \"metadata\": {},\n      \"source\": [\n        \"We'll generate two proofs, one with the correct total balance, and one with an incorrect total balance.\\n\",\n        \"\\n\",\n        \"## Correct total balance\\n\",\n        \"\\n\",\n        \"The data file above has a total balance of above the user total balance. We'll generate a proof with this total balance.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"93e90079\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# setup keypair\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"efa0ac91\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"!export RUST_BACKTRACE=1\\n\",\n        \"\\n\",\n        \"witness_path = \\\"witness.json\\\"\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path, vk_path)\\n\",\n        \"assert os.path.isfile(witness_path)\\n\",\n        \"\\n\",\n        \"# we force the output to be 1 this corresponds to the solvency test being true -- and we set this to a fixed vis output\\n\",\n        \"# this means that the output is fixed and the verifier can see it but that if the input is not in the set the output will not be 0 and the verifier will reject\\n\",\n        \"witness = json.load(open(witness_path, \\\"r\\\"))\\n\",\n        \"witness[\\\"outputs\\\"][0] = [ezkl.float_to_felt(1.0, 0)]\\n\",\n        \"json.dump(witness, open(witness_path, \\\"w\\\"))\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"90973daf\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"proof_path = os.path.join('proof.json')\\n\",\n        \"# proof path\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert os.path.isfile(proof_path)\\n\",\n        \"\\n\",\n        \"print(res)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"ef79b4ee\",\n      \"metadata\": {},\n      \"source\": [\n        \"- now we swap the commitments of the proof as a way to demonstrate that the proof is valid given some public inputs \\n\",\n        \"- this is just for testing purposes and would require fetching public commits from the blockchain or some other source\\n\",\n        \"- see https://blog.ezkl.xyz/post/commits/ for more details\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"8bb46735\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"\\n\",\n        \"res = ezkl.swap_proof_commitments(proof_path, witness_path)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"59f3b1e9\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# verify the proof\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_path,\\n\",\n        \"        vk_path,\\n\",\n        \"        \\n\",\n        \"    )\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"77dec3dd\",\n      \"metadata\": {},\n      \"source\": [\n        \"### Faulty proof\\n\",\n        \"\\n\",\n        \"We'll generate a proof with a total balance of 10. This is below the user total balance.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"FQfGdcUNpvuK\",\n      \"metadata\": {\n        \"id\": \"FQfGdcUNpvuK\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate a truthy input + witness file (x input not in the set)\\n\",\n        \"import random\\n\",\n        \"\\n\",\n        \"data_path_truthy = os.path.join('input.json')\\n\",\n        \"data = json.load(open(data_path, 'r' ))\\n\",\n        \"data['input_data'][2] = [10]\\n\",\n        \"\\n\",\n        \"data_path_faulty = os.path.join('input_faulty.json')\\n\",\n        \"# Serialize data into file:\\n\",\n        \"json.dump( data, open(data_path_faulty, 'w' ))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"b1c561a8\",\n      \"metadata\": {\n        \"id\": \"b1c561a8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# now generate the witness file\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(data_path_faulty, compiled_model_path, witness_path, vk_path)\\n\",\n        \"assert os.path.isfile(witness_path)\\n\",\n        \"\\n\",\n        \"# we force the output to be 1 this corresponds to the solvency test being true -- and we set this to a fixed vis output\\n\",\n        \"# this means that the output is fixed and the verifier can see it but that if the input is not in the set the output will not be 0 and the verifier will reject\\n\",\n        \"witness = json.load(open(witness_path, \\\"r\\\"))\\n\",\n        \"witness[\\\"outputs\\\"][0] = [ezkl.float_to_felt(1.0, 0)]\\n\",\n        \"json.dump(witness, open(witness_path, \\\"w\\\"))\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"c384cbc8\",\n      \"metadata\": {\n        \"id\": \"c384cbc8\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# GENERATE A PROOF\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"res = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_model_path,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"print(res)\\n\",\n        \"assert os.path.isfile(proof_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"4edaca46\",\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"res = ezkl.swap_proof_commitments(proof_path, witness_path)\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"id\": \"638d776f\",\n      \"metadata\": {},\n      \"source\": [\n        \"Now we test that verification fails\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"id\": \"4nqEx7-qpciQ\",\n      \"metadata\": {\n        \"id\": \"4nqEx7-qpciQ\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"import pytest\\n\",\n        \"\\n\",\n        \"def test_verification():\\n\",\n        \"    with pytest.raises(RuntimeError, match='Failed to run verify: The constraint system is not satisfied'):\\n\",\n        \"        ezkl.verify(\\n\",\n        \"            proof_path,\\n\",\n        \"            settings_path,\\n\",\n        \"            vk_path,\\n\",\n        \"            \\n\",\n        \"        )\\n\",\n        \"\\n\",\n        \"# Run the test function\\n\",\n        \"test_verification()\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3 (ipykernel)\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 5\n}"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/stacked_regression.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Stacked Regression\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Sklearn based models are slightly finicky to get into a suitable onnx format.\\n\",\n                \"This notebook showcases how to do so using the `hummingbird-ml` python package !\\n\",\n                \"\\n\",\n                \"We're going to combine a few models to create a stacked regression model.\\n\",\n                \"1. Linear Ridge Regression\\n\",\n                \"2. Support Vector Regression\\n\",\n                \"3. Random Forest Regression as a meta-estimator\\n\",\n                \"\\n\",\n                \"We then use hummingbird to convert the model to Torch and ONNX formats.\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"We then use ezkl to run zk-proofs.\\n\",\n                \"\\n\",\n                \"The generated onnx should look like this:\\n\",\n                \"\\n\",\n                \"![Alt text](image.png)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"scikit-learn==1.3.1\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"import os\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import json\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.linear_model import RidgeCV\\n\",\n                \"from sklearn.svm import LinearSVR\\n\",\n                \"from sklearn.ensemble import RandomForestRegressor\\n\",\n                \"from sklearn.ensemble import StackingRegressor\\n\",\n                \"\\n\",\n                \"estimators = [\\n\",\n                \"     ('lr', RidgeCV()),\\n\",\n                \"     ('svr', LinearSVR(dual=\\\"auto\\\", random_state=42))\\n\",\n                \"]\\n\",\n                \"\\n\",\n                \"X = np.array([[1, 1], [1, 2], [2, 2], [2, 3], [3, 3], [4, 4], [6, 8]])\\n\",\n                \"# y = 1 * x_0 + 2 * x_1 + 3\\n\",\n                \"y = np.dot(X, np.array([1, 2])) + 3\\n\",\n                \"\\n\",\n                \"reg = StackingRegressor(\\n\",\n                \"     estimators=estimators,\\n\",\n                \"     final_estimator=RandomForestRegressor(n_estimators=2,\\n\",\n                \"                                           random_state=42)\\n\",\n                \")\\n\",\n                \"reg.fit(X, y)\\n\",\n                \"reg.score(X, y)\\n\",\n                \"\\n\",\n                \"circuit = convert(reg, \\\"torch\\\", X[:1]).model\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b0a6f4b\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"print(circuit)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=True)\\n\",\n                \"torch_out = circuit(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = (torch.rand(20, *shape, requires_grad=True).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/svm.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Support Vector Machines\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"sk2torch\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.svm import SVC\\n\",\n                \"import sk2torch\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Create a dataset of two Gaussians. There will be some overlap\\n\",\n                \"# between the two classes, which adds some uncertainty to the model.\\n\",\n                \"xs = np.concatenate(\\n\",\n                \"    [\\n\",\n                \"        np.random.random(size=(256, 2)) + [1, 0],\\n\",\n                \"        np.random.random(size=(256, 2)) + [-1, 0],\\n\",\n                \"    ],\\n\",\n                \"    axis=0,\\n\",\n                \")\\n\",\n                \"ys = np.array([False] * 256 + [True] * 256)\\n\",\n                \"\\n\",\n                \"# Train an SVM on the data and wrap it in PyTorch.\\n\",\n                \"sk_model = SVC(probability=True)\\n\",\n                \"sk_model.fit(xs, ys)\\n\",\n                \"model = sk2torch.wrap(sk_model)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"7f0ca328\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import matplotlib.pyplot as plt\\n\",\n                \"# Create a coordinate grid to compute a vector field on.\\n\",\n                \"spaced = np.linspace(-2, 2, num=25)\\n\",\n                \"grid_xs = torch.tensor([[x, y] for x in spaced for y in spaced], requires_grad=True)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Compute the gradients of the SVM output.\\n\",\n                \"outputs = model.predict_proba(grid_xs)[:, 1]\\n\",\n                \"(input_grads,) = torch.autograd.grad(outputs.sum(), (grid_xs,))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Create a quiver plot of the vector field.\\n\",\n                \"plt.quiver(\\n\",\n                \"    grid_xs[:, 0].detach().numpy(),\\n\",\n                \"    grid_xs[:, 1].detach().numpy(),\\n\",\n                \"    input_grads[:, 0].detach().numpy(),\\n\",\n                \"    input_grads[:, 1].detach().numpy(),\\n\",\n                \")\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = xs.shape[1:]\\n\",\n                \"x = grid_xs[0:1]\\n\",\n                \"torch_out = model.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[o.reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"d5e374a2\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = ((grid_xs[0:20]).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 10,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"id\": \"760580d4\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Linear SVC\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"481824fe\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"### Linear SVC\\n\",\n                \"\\n\",\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"sk2torch\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.svm import LinearSVC\\n\",\n                \"import sk2torch\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"xs = np.concatenate(\\n\",\n                \"    [\\n\",\n                \"        np.random.random(size=(256, 2)) + [1, 0],\\n\",\n                \"        np.random.random(size=(256, 2)) + [-1, 0],\\n\",\n                \"    ],\\n\",\n                \"    axis=0,\\n\",\n                \")\\n\",\n                \"ys = np.array([False] * 256 + [True] * 256)\\n\",\n                \"\\n\",\n                \"# Train an SVM on the data and wrap it in PyTorch.\\n\",\n                \"sk_model = LinearSVC()\\n\",\n                \"sk_model.fit(xs, ys)\\n\",\n                \"model = sk2torch.wrap(sk_model)\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"7d1d47fe\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = xs.shape[1:]\\n\",\n                \"x = grid_xs[0:1]\\n\",\n                \"torch_out = model.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                  do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[o.reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"7c00b3f6\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"69536185\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path)\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"resources\\\")\\n\",\n                \"assert res == True\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/tictactoe_autoencoder.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Autoencoder Tic Tac Toe Verifier\\n\",\n                \"\\n\",\n                \"This is another approach of verifying games but using an anomaly detection approach instead of classification.\\n\",\n                \"\\n\",\n                \"Make sure to use a GPU otherwise you'll take a super long time to train\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 1,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"!RUST_LOG=trace\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Create TicTacToe Game States\\n\",\n                \"\\n\",\n                \"The game states are in the form of\\n\",\n                \"```json\\n\",\n                \"[\\n\",\n                \"    {\\n\",\n                \"        \\\"history\\\": [\\n\",\n                \"            [null, null, null, null, null, null, null, null, null],\\n\",\n                \"            [\\\"X\\\", null, null, null, null, null, null, null, null],\\n\",\n                \"            ...\\n\",\n                \"        ],\\n\",\n                \"        \\\"outcome\\\": \\\"X\\\"\\n\",\n                \"    }\\n\",\n                \"]\\n\",\n                \"```\\n\",\n                \"\\n\",\n                \"To create the game states for tic tac toe, do a recursive a tree search of possible gameplay.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 2,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"def check_winner(board):\\n\",\n                \"    winning_combinations = [\\n\",\n                \"        [0, 1, 2], [3, 4, 5], [6, 7, 8],  # rows\\n\",\n                \"        [0, 3, 6], [1, 4, 7], [2, 5, 8],  # columns\\n\",\n                \"        [0, 4, 8], [2, 4, 6]              # diagonals\\n\",\n                \"    ]\\n\",\n                \"    for combo in winning_combinations:\\n\",\n                \"        if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] is not None:\\n\",\n                \"            return board[combo[0]]\\n\",\n                \"    return None\\n\",\n                \"\\n\",\n                \"def generate_games(board, player):\\n\",\n                \"    winner = check_winner(board)\\n\",\n                \"    if winner or None not in board:\\n\",\n                \"        # Game is over, save the outcome and board state\\n\",\n                \"        return [{\\n\",\n                \"            \\\"history\\\": [list(board)],\\n\",\n                \"            \\\"outcome\\\": winner if winner else \\\"Draw\\\"\\n\",\n                \"        }]\\n\",\n                \"\\n\",\n                \"    games = []\\n\",\n                \"    for i in range(9):\\n\",\n                \"        if board[i] is None:\\n\",\n                \"            new_board = board.copy()\\n\",\n                \"            new_board[i] = player\\n\",\n                \"            next_player = 'O' if player == 'X' else 'X'\\n\",\n                \"            next_games = generate_games(new_board, next_player)\\n\",\n                \"            for game in next_games:\\n\",\n                \"                game[\\\"history\\\"].insert(0, list(board))\\n\",\n                \"            games.extend(next_games)\\n\",\n                \"\\n\",\n                \"    return games\\n\",\n                \"\\n\",\n                \"initial_board = [None for _ in range(9)]\\n\",\n                \"games = generate_games(initial_board, 'X')\\n\",\n                \"\\n\",\n                \"with open(\\\"tic_tac_toe_games.json\\\", \\\"w\\\") as file:\\n\",\n                \"    file.write(\\\"[\\\\n\\\")  # Start of the list\\n\",\n                \"    for i, game in enumerate(games):\\n\",\n                \"        json.dump(game, file, separators=(',', ': '))\\n\",\n                \"        if i != len(games) - 1:  # If it's not the last game, add a comma\\n\",\n                \"            file.write(\\\",\\\\n\\\")\\n\",\n                \"        else:\\n\",\n                \"            file.write(\\\"\\\\n\\\")\\n\",\n                \"    file.write(\\\"]\\\\n\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now, let's make a list of illegal game play by running through the legal games and making bad games.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 3,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"with open(\\\"tic_tac_toe_games_bad.json\\\", \\\"w\\\") as file:\\n\",\n                \"    file.write(\\\"[\\\\n\\\")\\n\",\n                \"    for i, game in enumerate(games):\\n\",\n                \"        # we the permute the games\\n\",\n                \"        game_history = game['history']\\n\",\n                \"        new_game_history = []\\n\",\n                \"        for moves in game_history:\\n\",\n                \"            new_moves = []\\n\",\n                \"            for move in moves:\\n\",\n                \"                if move is None:\\n\",\n                \"                    new_moves.append('X')\\n\",\n                \"                elif move == 'X':\\n\",\n                \"                    new_moves.append('O')\\n\",\n                \"                else:\\n\",\n                \"                    new_moves.append(None)\\n\",\n                \"            new_game_history.append(new_moves)\\n\",\n                \"        game['history'] = new_game_history\\n\",\n                \"\\n\",\n                \"        json.dump(game, file, separators=(',', ': '))\\n\",\n                \"\\n\",\n                \"        if i != len(games) - 1:  # If it's not the last game, add a comma\\n\",\n                \"            file.write(\\\",\\\\n\\\")\\n\",\n                \"        else:\\n\",\n                \"            file.write(\\\"\\\\n\\\")\\n\",\n                \"    file.write(\\\"]\\\\n\\\")\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Create a neural net to verify the execution of the tic tac toe model\\n\",\n                \"\\n\",\n                \"1. We use an autoencoder to verify the execution. An autoencoder is essentially a fan-in, fan-out architecture. It can be used for generative tasks, but in this case we use it as an anomaly detection approach.\\n\",\n                \"\\n\",\n                \"2. The autoencoder helps us extract out the latent distribution of normal tic tac toe games. If there's a weird tic tac toe game, we can then reject it if the distribution is not within some threshold we want. We can quantify this distribution via the mean absolute error between the data point and the reconstructed data.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 4,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"import torch.nn as nn\\n\",\n                \"from torch.utils.data import DataLoader, IterableDataset, random_split\\n\",\n                \"import torch.optim as optim\\n\",\n                \"import json\\n\",\n                \"import torch.nn.functional as F\\n\",\n                \"\\n\",\n                \"class TicTacToeNet(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(TicTacToeNet, self).__init__()\\n\",\n                \"        self.return_x = True\\n\",\n                \"        self.dense = nn.Linear(11 * 9 * 3, 50)\\n\",\n                \"        self.dense1 = nn.Linear(50, 20)\\n\",\n                \"        self.dense2 = nn.Linear(20, 10)\\n\",\n                \"        self.dense3 = nn.Linear(10, 20)\\n\",\n                \"        self.dense4 = nn.Linear(20, 50)\\n\",\n                \"        self.dense5 = nn.Linear(50, 11 * 9 * 3)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        # Store original input\\n\",\n                \"        original_x = x.clone()\\n\",\n                \"\\n\",\n                \"        # Neural network operations\\n\",\n                \"        x = F.relu(self.dense(x))\\n\",\n                \"        x = F.relu(self.dense1(x))\\n\",\n                \"        x = F.relu(self.dense2(x))\\n\",\n                \"        x = F.relu(self.dense3(x))\\n\",\n                \"        x = F.relu(self.dense4(x))\\n\",\n                \"        x = self.dense5(x)  # Not applying activation on final layer\\n\",\n                \"\\n\",\n                \"        # Calculate L1 loss\\n\",\n                \"        l1_loss = torch.mean(torch.abs(x - original_x))\\n\",\n                \"\\n\",\n                \"        if self.return_x:\\n\",\n                \"            return x, l1_loss\\n\",\n                \"        else:\\n\",\n                \"            return l1_loss\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Load all possible tictactoe games\\n\",\n                \"\\n\",\n                \"We want to load good games and bad games for the classification later.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": 6,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"class JsonDataset(IterableDataset):\\n\",\n                \"    def __init__(self, file):\\n\",\n                \"        self.file_good = file\\n\",\n                \"        self.length = self.compute_length(self.file_good)\\n\",\n                \"        self.data = self.load_data(self.file_good)\\n\",\n                \"\\n\",\n                \"    def __iter__(self):\\n\",\n                \"        for i in range(len(self.data)):\\n\",\n                \"            yield self.data[i]\\n\",\n                \"\\n\",\n                \"    def parse_json_object(self, line):\\n\",\n                \"        try:\\n\",\n                \"            return json.loads(line)\\n\",\n                \"        except json.JSONDecodeError:\\n\",\n                \"            return None\\n\",\n                \"\\n\",\n                \"    def encode_board(self, board):\\n\",\n                \"        encoding = []\\n\",\n                \"        for cell in board:\\n\",\n                \"            if cell == 'X':\\n\",\n                \"                encoding.extend([1,0,0])\\n\",\n                \"            elif cell == 'O':\\n\",\n                \"                encoding.extend([0,1,0])\\n\",\n                \"            else:\\n\",\n                \"                encoding.extend([0,0,1])\\n\",\n                \"\\n\",\n                \"        return encoding\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    def encode_outcome(self, outcome):\\n\",\n                \"        if outcome == 'X':\\n\",\n                \"            return [1,0,0]\\n\",\n                \"        elif outcome == 'O':\\n\",\n                \"            return [0,1,0]\\n\",\n                \"        else:\\n\",\n                \"            return [0,0,1]\\n\",\n                \"\\n\",\n                \"    def compute_length(self, file_good):\\n\",\n                \"        count = 0\\n\",\n                \"        with open(file_good, 'r') as f:\\n\",\n                \"            # Skip the first line (which is \\\"[\\\")\\n\",\n                \"            next(f)\\n\",\n                \"            for line in f:\\n\",\n                \"                if line.strip() not in [\\\",\\\", \\\"]\\\"]:\\n\",\n                \"                    count += 1\\n\",\n                \"\\n\",\n                \"        return count\\n\",\n                \"\\n\",\n                \"    def __len__(self):\\n\",\n                \"        return self.length\\n\",\n                \"\\n\",\n                \"    def __getitem__(self, idx):\\n\",\n                \"        padded_history, sample_outcome = self.data[idx]\\n\",\n                \"\\n\",\n                \"        return torch.tensor(padded_history, dtype=torch.float), torch.tensor(sample_outcome, dtype=torch.float)\\n\",\n                \"\\n\",\n                \"    def process_file(self, file, is_good):\\n\",\n                \"        data = []\\n\",\n                \"        with open(file, 'r') as f:\\n\",\n                \"            next(f)\\n\",\n                \"            for line in f:\\n\",\n                \"                # Remove the trailing comma for all lines except the last one (which is \\\"]\\\")\\n\",\n                \"                if line.endswith(\\\",\\\\n\\\"):\\n\",\n                \"                    line = line[:-2]\\n\",\n                \"                sample = self.parse_json_object(line)\\n\",\n                \"                if sample is not None:\\n\",\n                \"                    max_length = 10  # Maximum length of a Tic Tac Toe game\\n\",\n                \"                    history = sample['history']\\n\",\n                \"\\n\",\n                \"                    if len(history) == max_length:\\n\",\n                \"                        padded_history = history\\n\",\n                \"                    else:\\n\",\n                \"                        padded_history = history + [[None] * 9 for _ in range(max_length - len(history))]\\n\",\n                \"\\n\",\n                \"                    padded_history = [self.encode_board(x) for x in padded_history]\\n\",\n                \"                    sample_outcome = self.encode_outcome(sample['outcome'])\\n\",\n                \"                    sample_outcome.extend([0,0,1] * 8)\\n\",\n                \"                    padded_history.append(sample_outcome)\\n\",\n                \"\\n\",\n                \"                    if is_good:\\n\",\n                \"                        # data.append((padded_history, sample_outcome, 0))\\n\",\n                \"                        data.append((padded_history, [1, 0]))\\n\",\n                \"                    else:\\n\",\n                \"                        # data.append((padded_history, sample_outcome, 1))\\n\",\n                \"                        data.append((padded_history, [0, 1]))\\n\",\n                \"\\n\",\n                \"        return data\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    def load_data(self, file_good):\\n\",\n                \"        data_good = self.process_file(file_good, True)\\n\",\n                \"        # data_bad = self.process_file(file_bad, False)\\n\",\n                \"        # data_good.extend(data_bad)\\n\",\n                \"\\n\",\n                \"        return data_good\\n\",\n                \"\\n\",\n                \"def collate_fn(batch):\\n\",\n                \"    histories, outcomes = zip(*batch)\\n\",\n                \"\\n\",\n                \"    # Convert nested lists to tensor\\n\",\n                \"    histories_tensor = torch.tensor(histories, dtype=torch.float32)\\n\",\n                \"    outcomes_tensor = torch.tensor(outcomes, dtype=torch.int64)\\n\",\n                \"\\n\",\n                \"    return histories_tensor, outcomes_tensor\\n\",\n                \"\\n\",\n                \"dataset = JsonDataset('tic_tac_toe_games.json')\\n\",\n                \"\\n\",\n                \"total_size = len(dataset)\\n\",\n                \"train_size = int(0.8 * total_size)\\n\",\n                \"test_size = total_size - train_size\\n\",\n                \"\\n\",\n                \"train_dataset, test_dataset = random_split(dataset, [train_size, test_size])\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\\n\",\n                \"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Train\\n\",\n                \"\\n\",\n                \"Note that during training we want to neural network to try to recreate its inputs. To do this we compare the L1Loss or Mean Absolute Error between the prediction and the input.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"device = torch.device(\\\"cuda\\\" if torch.cuda.is_available() else \\\"cpu\\\")\\n\",\n                \"model = TicTacToeNet().to(device)\\n\",\n                \"criterion = nn.L1Loss()\\n\",\n                \"optimizer = optim.Adam(model.parameters(), lr=0.001)\\n\",\n                \"\\n\",\n                \"# You may want to increase this\\n\",\n                \"MAX_EPOCH = 1\\n\",\n                \"\\n\",\n                \"for epoch in range(MAX_EPOCH):\\n\",\n                \"    model.train()\\n\",\n                \"\\n\",\n                \"    for history, valid in train_loader:\\n\",\n                \"\\n\",\n                \"        history = history.to(device)\\n\",\n                \"        optimizer.zero_grad()\\n\",\n                \"        history = history.view(history.size(0), -1)\\n\",\n                \"        prediction, _ = model(history)\\n\",\n                \"        loss = criterion(prediction, history)\\n\",\n                \"        loss.backward()\\n\",\n                \"        optimizer.step()\\n\",\n                \"\\n\",\n                \"        # Gather data and report\\n\",\n                \"\\n\",\n                \"    # Validation phase\\n\",\n                \"    model.eval()\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    with torch.no_grad():\\n\",\n                \"        total_count = 0\\n\",\n                \"        total_loss = 0\\n\",\n                \"        for history, valid in test_loader:\\n\",\n                \"            history = history.to(device)\\n\",\n                \"            history = history.view(history.size(0), -1)\\n\",\n                \"\\n\",\n                \"            valid = valid.to(device)\\n\",\n                \"            prediction, _ = model(history)\\n\",\n                \"            loss = criterion(prediction, history)\\n\",\n                \"\\n\",\n                \"            total_loss += loss\\n\",\n                \"\\n\",\n                \"            total_count += 1\\n\",\n                \"\\n\",\n                \"            # get values for the accuracy\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    avg_loss = total_loss / total_count\\n\",\n                \"    print(f\\\"Epoch {epoch + 1}/{MAX_EPOCH} - Loss: {avg_loss:.2f}\\\")\\n\",\n                \"    print(history[-1])\\n\",\n                \"    print(prediction[-1])\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Get the ranges for normal data\\n\",\n                \"\\n\",\n                \"We plot the range of possible losses for normal data.\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# set model to get loss out\\n\",\n                \"model.eval()\\n\",\n                \"model.return_x = False\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"loss_list = []\\n\",\n                \"\\n\",\n                \"for history, valid in test_loader:\\n\",\n                \"    history = history.to(device)\\n\",\n                \"    history = history.view(history.size(0), -1)\\n\",\n                \"    loss = model(history)\\n\",\n                \"    loss_list.append(loss.cpu().detach().numpy())\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# visualize\\n\",\n                \"import matplotlib.pyplot as plt\\n\",\n                \"\\n\",\n                \"plt.hist(loss_list, bins=50)\\n\",\n                \"plt.xlabel(\\\"Normal loss\\\")\\n\",\n                \"plt.ylabel(\\\"No of examples\\\")\\n\",\n                \"plt.show()\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Get the ranges for bad data\\n\",\n                \"\\n\",\n                \"Likewise, we plot the ranges of losses for bad data.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# load bad data\\n\",\n                \"bad_dataset = JsonDataset('tic_tac_toe_games_bad.json')\\n\",\n                \"\\n\",\n                \"bad_total_size = len(bad_dataset)\\n\",\n                \"bad_train_size = int(0.8 * bad_total_size)\\n\",\n                \"bad_test_size = bad_total_size - bad_train_size\\n\",\n                \"\\n\",\n                \"bad_train_dataset, bad_test_dataset = random_split(bad_dataset, [bad_train_size, bad_test_size])\\n\",\n                \"\\n\",\n                \"bad_train_loader = DataLoader(bad_train_dataset, batch_size=32, shuffle=True)\\n\",\n                \"bad_test_loader = DataLoader(bad_test_dataset, batch_size=32, shuffle=False)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"bad_loss_list = []\\n\",\n                \"\\n\",\n                \"for history, valid in bad_test_loader:\\n\",\n                \"    history = history.to(device)\\n\",\n                \"    history = history.view(history.size(0), -1)\\n\",\n                \"    loss = model(history)\\n\",\n                \"    bad_loss_list.append(loss.cpu().detach().numpy())\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import matplotlib.pyplot as plt\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"plt.hist(bad_loss_list, bins=50)\\n\",\n                \"plt.xlabel(\\\"Normal loss\\\")\\n\",\n                \"plt.ylabel(\\\"No of examples\\\")\\n\",\n                \"plt.show()\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"**Note:** By visual inspection we can see that if the loss is greater than `~0.200` the data is likely anomalous (this value will probably change depending on the runs). There seems to be no overlap in loss between good gameplay and bad gameplay.\\n\",\n                \"\\n\",\n                \"We could alternatively set the threshold to 4 standard deviation away from the mean of normal values. Or you can vary this according to the error tolerance required.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import numpy as np\\n\",\n                \"threshold = np.mean(loss_list)+ 4 * np.std(loss_list)\\n\",\n                \"print(threshold)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Export Onnx and Data\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Set the model to evaluation mode\\n\",\n                \"model = model.cpu()\\n\",\n                \"model.eval()\\n\",\n                \"\\n\",\n                \"# Obtain a sample datapoint from the DataLoader\\n\",\n                \"sample_data_iter = iter(train_loader)\\n\",\n                \"sample_history, _ = next(sample_data_iter)\\n\",\n                \"\\n\",\n                \"# Move the sample datapoint to the cpu so it is the same as the model\\n\",\n                \"x = sample_history.to('cpu')\\n\",\n                \"x = x.view(x.size(0), -1)\\n\",\n                \"\\n\",\n                \"# Export the model using ONNX\\n\",\n                \"torch.onnx.export(\\n\",\n                \"    model,                        # model being run\\n\",\n                \"    x,                            # model input (or a tuple for multiple inputs)\\n\",\n                \"    \\\"tictactoe_network.onnx\\\",     # where to save the model (can be a file or file-like object)\\n\",\n                \"    export_params=True,           # store the trained parameter weights inside the model file\\n\",\n                \"    opset_version=10,             # the ONNX version to export the model to\\n\",\n                \"    do_constant_folding=True,     # whether to execute constant folding for optimization\\n\",\n                \"    input_names=['input'],        # the model's input names\\n\",\n                \"    output_names=['output'],      # the model's output names\\n\",\n                \"    dynamic_axes={\\n\",\n                \"        'input': {0: 'batch_size'},     # variable length axes\\n\",\n                \"        'output': {0: 'batch_size'}\\n\",\n                \"    }\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"data_array = ((x[0]).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"data.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Prove the Tic Tac Toe Anomaly Detection Model\\n\",\n                \"\\n\",\n                \"We import the ezkl library to setup the zk system.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os\\n\",\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"data_path = os.path.join(\\\"data.json\\\")\\n\",\n                \"model_path = os.path.join('tictactoe_network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.ezkl')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"proof_path = os.path.join('proof.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.gen_settings(model_path, settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# IMPORTANT NOTE: You may want to set the scale ranges and set to \\\"accuracy\\\"\\n\",\n                \"# In it's current state, it will likely truncate values\\n\",\n                \"# For testing we will just stick to resources to reduce computational costs\\n\",\n                \"# Example:\\n\",\n                \"# ezkl.calibrate_settings(data_path, model_path, settings_path, \\\"accuracy\\\", scales = [2,9])\\n\",\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = ((x[0:20]).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\", scales = [11])\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.setup(\\n\",\n                \"    compiled_model_path,\\n\",\n                \"    vk_path,\\n\",\n                \"    pk_path,\\n\",\n                \")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"with open(data_path, \\\"r\\\") as f:\\n\",\n                \"    data = json.load(f)\\n\",\n                \"    print(len(data['input_data'][0]))\\n\",\n                \"\\n\",\n                \"ezkl.gen_witness(data_path, compiled_model_path, witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.mock(witness_path, compiled_model_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"accelerator\": \"GPU\",\n        \"colab\": {\n            \"gpuType\": \"V100\",\n            \"provenance\": []\n        },\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.12.2\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 4\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/tictactoe_binary_classification.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Binary Classification Tic Tac Toe Verifier\\n\",\n                \"\\n\",\n                \"We create an ML model that verifies TicTacToe Games\\n\",\n                \"\\n\",\n                \"Make sure to use a GPU otherwise you'll take a super long time to train\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Create TicTacToe Game States\\n\",\n                \"\\n\",\n                \"The game states are in the form of\\n\",\n                \"```json\\n\",\n                \"[\\n\",\n                \"    {\\n\",\n                \"        \\\"history\\\": [\\n\",\n                \"            [null, null, null, null, null, null, null, null, null],\\n\",\n                \"            [\\\"X\\\", null, null, null, null, null, null, null, null],\\n\",\n                \"            ...\\n\",\n                \"        ],\\n\",\n                \"        \\\"outcome\\\": \\\"X\\\"\\n\",\n                \"    }\\n\",\n                \"]\\n\",\n                \"```\\n\",\n                \"\\n\",\n                \"To create the game states for tic tac toe, do a recursive a tree search of possible gameplay.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"def check_winner(board):\\n\",\n                \"    winning_combinations = [\\n\",\n                \"        [0, 1, 2], [3, 4, 5], [6, 7, 8],  # rows\\n\",\n                \"        [0, 3, 6], [1, 4, 7], [2, 5, 8],  # columns\\n\",\n                \"        [0, 4, 8], [2, 4, 6]              # diagonals\\n\",\n                \"    ]\\n\",\n                \"    for combo in winning_combinations:\\n\",\n                \"        if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] is not None:\\n\",\n                \"            return board[combo[0]]\\n\",\n                \"    return None\\n\",\n                \"\\n\",\n                \"def generate_games(board, player):\\n\",\n                \"    winner = check_winner(board)\\n\",\n                \"    if winner or None not in board:\\n\",\n                \"        # Game is over, save the outcome and board state\\n\",\n                \"        return [{\\n\",\n                \"            \\\"history\\\": [list(board)],\\n\",\n                \"            \\\"outcome\\\": winner if winner else \\\"Draw\\\"\\n\",\n                \"        }]\\n\",\n                \"\\n\",\n                \"    games = []\\n\",\n                \"    for i in range(9):\\n\",\n                \"        if board[i] is None:\\n\",\n                \"            new_board = board.copy()\\n\",\n                \"            new_board[i] = player\\n\",\n                \"            next_player = 'O' if player == 'X' else 'X'\\n\",\n                \"            next_games = generate_games(new_board, next_player)\\n\",\n                \"            for game in next_games:\\n\",\n                \"                game[\\\"history\\\"].insert(0, list(board))\\n\",\n                \"            games.extend(next_games)\\n\",\n                \"\\n\",\n                \"    return games\\n\",\n                \"\\n\",\n                \"initial_board = [None for _ in range(9)]\\n\",\n                \"games = generate_games(initial_board, 'X')\\n\",\n                \"\\n\",\n                \"with open(\\\"tic_tac_toe_games.json\\\", \\\"w\\\") as file:\\n\",\n                \"    file.write(\\\"[\\\\n\\\")  # Start of the list\\n\",\n                \"    for i, game in enumerate(games):\\n\",\n                \"        json.dump(game, file, separators=(',', ': '))\\n\",\n                \"        if i != len(games) - 1:  # If it's not the last game, add a comma\\n\",\n                \"            file.write(\\\",\\\\n\\\")\\n\",\n                \"        else:\\n\",\n                \"            file.write(\\\"\\\\n\\\")\\n\",\n                \"    file.write(\\\"]\\\\n\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now, let's make a list of illegal game play by running through the legal games and making bad games.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"with open(\\\"tic_tac_toe_games_bad.json\\\", \\\"w\\\") as file:\\n\",\n                \"    file.write(\\\"[\\\\n\\\")\\n\",\n                \"    for i, game in enumerate(games):\\n\",\n                \"        # we the permute the games\\n\",\n                \"        game_history = game['history']\\n\",\n                \"        new_game_history = []\\n\",\n                \"        for moves in game_history:\\n\",\n                \"            new_moves = []\\n\",\n                \"            for move in moves:\\n\",\n                \"                if move is None:\\n\",\n                \"                    new_moves.append('X')\\n\",\n                \"                elif move == 'X':\\n\",\n                \"                    new_moves.append('O')\\n\",\n                \"                else:\\n\",\n                \"                    new_moves.append(None)\\n\",\n                \"            new_game_history.append(new_moves)\\n\",\n                \"        game['history'] = new_game_history\\n\",\n                \"\\n\",\n                \"        json.dump(game, file, separators=(',', ': '))\\n\",\n                \"\\n\",\n                \"        if i != len(games) - 1:  # If it's not the last game, add a comma\\n\",\n                \"            file.write(\\\",\\\\n\\\")\\n\",\n                \"        else:\\n\",\n                \"            file.write(\\\"\\\\n\\\")\\n\",\n                \"    file.write(\\\"]\\\\n\\\")\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Create a neural net to verify the execution of the tic tac toe model\\n\",\n                \"\\n\",\n                \"1. Given the data generated above classify whether the tic tac toe games are valid. This approach uses a binary classification as the tic tac toe state space is fairly small. For larger state spaces, we will want to use anomaly detection based approaches.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"import torch.nn as nn\\n\",\n                \"from torch.utils.data import DataLoader, IterableDataset, random_split\\n\",\n                \"import torch.optim as optim\\n\",\n                \"import json\\n\",\n                \"import torch.nn.functional as F\\n\",\n                \"\\n\",\n                \"class TicTacToeNet(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(TicTacToeNet, self).__init__()\\n\",\n                \"        self.dense = nn.Linear(11 * 9 * 3, 50)  # Adjusted for 11*9 input features\\n\",\n                \"        self.dense1 = nn.Linear(50, 20)\\n\",\n                \"        self.dense2 = nn.Linear(20, 10)\\n\",\n                \"        self.dense3 = nn.Linear(10, 2)\\n\",\n                \"\\n\",\n                \"    def forward(self, x):\\n\",\n                \"        x = x.view(x.size(0), -1)  # Flatten the input\\n\",\n                \"        x = F.relu(self.dense(x))\\n\",\n                \"        x = F.relu(self.dense1(x))\\n\",\n                \"        x = F.relu(self.dense2(x))\\n\",\n                \"        x = F.relu(self.dense3(x))\\n\",\n                \"        return x\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Load all possible tictactoe games\\n\",\n                \"\\n\",\n                \"We want to load good games and bad games for the classification later.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"class JsonDataset(IterableDataset):\\n\",\n                \"    def __init__(self, file_good, file_bad):\\n\",\n                \"        self.file_good = file_good\\n\",\n                \"        self.file_bad = file_bad\\n\",\n                \"        self.length = self.compute_length(self.file_good, self.file_bad)\\n\",\n                \"        self.data = self.load_data(self.file_good, self.file_bad)\\n\",\n                \"\\n\",\n                \"    def __iter__(self):\\n\",\n                \"        for i in range(len(self.data)):\\n\",\n                \"            yield self.data[i]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    def parse_json_object(self, line):\\n\",\n                \"        try:\\n\",\n                \"            return json.loads(line)\\n\",\n                \"        except json.JSONDecodeError:\\n\",\n                \"            return None\\n\",\n                \"\\n\",\n                \"    def encode_board(self, board):\\n\",\n                \"        encoding = []\\n\",\n                \"        for cell in board:\\n\",\n                \"            if cell == 'X':\\n\",\n                \"                encoding.extend([1,0,0])\\n\",\n                \"            elif cell == 'O':\\n\",\n                \"                encoding.extend([0,1,0])\\n\",\n                \"            else:\\n\",\n                \"                encoding.extend([0,0,1])\\n\",\n                \"\\n\",\n                \"        return encoding\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    def encode_outcome(self, outcome):\\n\",\n                \"        if outcome == 'X':\\n\",\n                \"            return [1,0,0]\\n\",\n                \"        elif outcome == 'O':\\n\",\n                \"            return [0,1,0]\\n\",\n                \"        else:\\n\",\n                \"            return [0,0,1]\\n\",\n                \"\\n\",\n                \"    def compute_length(self, file_good, file_bad):\\n\",\n                \"        count = 0\\n\",\n                \"        with open(file_good, 'r') as f:\\n\",\n                \"            # Skip the first line (which is \\\"[\\\")\\n\",\n                \"            next(f)\\n\",\n                \"            for line in f:\\n\",\n                \"                if line.strip() not in [\\\",\\\", \\\"]\\\"]:\\n\",\n                \"                    count += 1\\n\",\n                \"        with open(file_bad, 'r') as f:\\n\",\n                \"            # Skip the first line (which is \\\"[\\\")\\n\",\n                \"            next(f)\\n\",\n                \"            for line in f:\\n\",\n                \"                if line.strip() not in [\\\",\\\", \\\"]\\\"]:\\n\",\n                \"                    count += 1\\n\",\n                \"\\n\",\n                \"        return count\\n\",\n                \"\\n\",\n                \"    def __len__(self):\\n\",\n                \"        return self.length\\n\",\n                \"\\n\",\n                \"    def __getitem__(self, idx):\\n\",\n                \"        padded_history, sample_outcome = self.data[idx]\\n\",\n                \"        return torch.tensor(padded_history, dtype=torch.float), torch.tensor(sample_outcome, dtype=torch.float)\\n\",\n                \"\\n\",\n                \"    def process_file(self, file, is_good):\\n\",\n                \"        data = []\\n\",\n                \"        with open(file, 'r') as f:\\n\",\n                \"            next(f)\\n\",\n                \"            for line in f:\\n\",\n                \"                # Remove the trailing comma for all lines except the last one (which is \\\"]\\\")\\n\",\n                \"                if line.endswith(\\\",\\\\n\\\"):\\n\",\n                \"                    line = line[:-2]\\n\",\n                \"                sample = self.parse_json_object(line)\\n\",\n                \"                if sample is not None:\\n\",\n                \"                    max_length = 10  # Maximum length of a Tic Tac Toe game\\n\",\n                \"                    history = sample['history']\\n\",\n                \"\\n\",\n                \"                    if len(history) == max_length:\\n\",\n                \"                        padded_history = history\\n\",\n                \"                    else:\\n\",\n                \"                        padded_history = history + [[None] * 9 for _ in range(max_length - len(history))]\\n\",\n                \"\\n\",\n                \"                    padded_history = [self.encode_board(x) for x in padded_history]\\n\",\n                \"                    sample_outcome = self.encode_outcome(sample['outcome'])\\n\",\n                \"                    sample_outcome.extend([0,0,1] * 8)\\n\",\n                \"                    padded_history.append(sample_outcome)\\n\",\n                \"\\n\",\n                \"                    if is_good:\\n\",\n                \"                        # data.append((padded_history, sample_outcome, 0))\\n\",\n                \"                        data.append((padded_history, [1, 0]))\\n\",\n                \"                    else:\\n\",\n                \"                        # data.append((padded_history, sample_outcome, 1))\\n\",\n                \"                        data.append((padded_history, [0, 1]))\\n\",\n                \"\\n\",\n                \"        return data\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    def load_data(self, file_good, file_bad):\\n\",\n                \"        data_good = self.process_file(file_good, True)\\n\",\n                \"        data_bad = self.process_file(file_bad, False)\\n\",\n                \"        data_good.extend(data_bad)\\n\",\n                \"\\n\",\n                \"        return data_good\\n\",\n                \"\\n\",\n                \"def collate_fn(batch):\\n\",\n                \"    histories, outcomes = zip(*batch)\\n\",\n                \"\\n\",\n                \"    # Convert nested lists to tensor\\n\",\n                \"    histories_tensor = torch.tensor(histories, dtype=torch.float32)\\n\",\n                \"    outcomes_tensor = torch.tensor(outcomes, dtype=torch.int64)\\n\",\n                \"\\n\",\n                \"    return histories_tensor, outcomes_tensor\\n\",\n                \"\\n\",\n                \"dataset = JsonDataset('tic_tac_toe_games.json', 'tic_tac_toe_games_bad.json')\\n\",\n                \"\\n\",\n                \"total_size = len(dataset)\\n\",\n                \"train_size = int(0.8 * total_size)\\n\",\n                \"test_size = total_size - train_size\\n\",\n                \"\\n\",\n                \"train_dataset, test_dataset = random_split(dataset, [train_size, test_size])\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\\n\",\n                \"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Train\\n\",\n                \"\\n\",\n                \"In this training step we'll just use the CrossEntropyLoss and have the neural network classify good games and bad games.\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"device = torch.device(\\\"cuda\\\" if torch.cuda.is_available() else \\\"cpu\\\")\\n\",\n                \"model = TicTacToeNet().to(device)\\n\",\n                \"criterion = nn.CrossEntropyLoss()\\n\",\n                \"optimizer = optim.Adam(model.parameters(), lr=0.001)\\n\",\n                \"\\n\",\n                \"# you may want to increase this\\n\",\n                \"MAX_EPOCH = 1\\n\",\n                \"\\n\",\n                \"for epoch in range(MAX_EPOCH):\\n\",\n                \"    model.train()\\n\",\n                \"\\n\",\n                \"    for history, valid in train_loader:\\n\",\n                \"\\n\",\n                \"        history = history.to(device)\\n\",\n                \"        valid = valid.to(device)\\n\",\n                \"        optimizer.zero_grad()\\n\",\n                \"        prediction = model(history)\\n\",\n                \"        loss = criterion(prediction, valid)\\n\",\n                \"        loss.backward()\\n\",\n                \"        optimizer.step()\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    # Validation phase\\n\",\n                \"    model.eval()\\n\",\n                \"    total_count = 0\\n\",\n                \"    correct_count = 0\\n\",\n                \"\\n\",\n                \"    with torch.no_grad():\\n\",\n                \"        for history, valid in test_loader:\\n\",\n                \"            history = history.to(device)\\n\",\n                \"            valid = valid.to(device)\\n\",\n                \"            prediction = model(history)\\n\",\n                \"\\n\",\n                \"            # Convert predictions to class labels\\n\",\n                \"            _, predicted_labels = torch.max(prediction, 1)\\n\",\n                \"\\n\",\n                \"            # Convert true labels to class labels\\n\",\n                \"            _, true_class_labels = torch.max(valid, 1)\\n\",\n                \"\\n\",\n                \"            # Count correct predictions\\n\",\n                \"            correct_predictions = (predicted_labels == true_class_labels).sum().item()\\n\",\n                \"\\n\",\n                \"            total_predictions = prediction.shape[0]\\n\",\n                \"\\n\",\n                \"            # get values for the accuracy\\n\",\n                \"            correct_count += correct_predictions\\n\",\n                \"            total_count += total_predictions\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"    accuracy = 100 * correct_count / total_count\\n\",\n                \"    print(f\\\"Epoch {epoch + 1}/{MAX_EPOCH} - Accuracy: {accuracy:.2f}%\\\")\\n\",\n                \"    print(history[-1])\\n\",\n                \"    print(valid[-1])\\n\",\n                \"    print(predicted_labels[-1])\\n\",\n                \"    print(true_class_labels[-1])\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"print(prediction)\\n\",\n                \"print(valid)\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"**Note:** It's reasonable for the tic tac toe model to approach 100% classification accuracy as the state space of the game is fairly small\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"## Export Onnx and Data\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Set the model to evaluation mode\\n\",\n                \"model = model.cpu()\\n\",\n                \"model.eval()\\n\",\n                \"\\n\",\n                \"# Obtain a sample datapoint from the DataLoader\\n\",\n                \"sample_data_iter = iter(train_loader)\\n\",\n                \"sample_history, _ = next(sample_data_iter)\\n\",\n                \"\\n\",\n                \"# Move the sample datapoint to the cpu so it is the same as the model\\n\",\n                \"x = sample_history.to('cpu')\\n\",\n                \"\\n\",\n                \"# Export the model using ONNX\\n\",\n                \"torch.onnx.export(\\n\",\n                \"    model,                        # model being run\\n\",\n                \"    x,                            # model input (or a tuple for multiple inputs)\\n\",\n                \"    \\\"tictactoe_network.onnx\\\",     # where to save the model (can be a file or file-like object)\\n\",\n                \"    export_params=True,           # store the trained parameter weights inside the model file\\n\",\n                \"    opset_version=10,             # the ONNX version to export the model to\\n\",\n                \"    do_constant_folding=True,     # whether to execute constant folding for optimization\\n\",\n                \"    input_names=['input'],        # the model's input names\\n\",\n                \"    output_names=['output'],      # the model's output names\\n\",\n                \"    dynamic_axes={\\n\",\n                \"        'input': {0: 'batch_size'},     # variable length axes\\n\",\n                \"        'output': {0: 'batch_size'}\\n\",\n                \"    }\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"data_array = ((x[0]).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"data.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Prove the Tic Tac Toe Classification Model\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!RUST_LOG=trace\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os\\n\",\n                \"import ezkl\\n\",\n                \"\\n\",\n                \"data_path = os.path.join(\\\"data.json\\\")\\n\",\n                \"model_path = os.path.join('tictactoe_network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.ezkl')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"proof_path = os.path.join('proof.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.gen_settings(model_path, settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"cal_path = os.path.join(\\\"calibration.json\\\")\\n\",\n                \"\\n\",\n                \"data_array = ((x[0:20]).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [data_array])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(cal_path, 'w'))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\", scales = [4])\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.get_srs(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.setup(\\n\",\n                \"    compiled_model_path,\\n\",\n                \"    vk_path,\\n\",\n                \"    pk_path,\\n\",\n                \"    \\n\",\n                \")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import json\\n\",\n                \"\\n\",\n                \"with open(data_path, \\\"r\\\") as f:\\n\",\n                \"    data = json.load(f)\\n\",\n                \"    print(len(data['input_data'][0]))\\n\",\n                \"\\n\",\n                \"ezkl.gen_witness(data_path, compiled_model_path, witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"ezkl.mock(witness_path, compiled_model_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"accelerator\": \"GPU\",\n        \"colab\": {\n            \"gpuType\": \"T4\",\n            \"provenance\": []\n        },\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.12.2\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 4\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/variance.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"uKQPd7_5ANe-\"\n      },\n      \"source\": [\n        \"# Calculate the variance of an asset \\n\",\n        \"\\n\",\n        \"In this example we will calculate the variance of an asset using ezkl. Here's a diagram of the process:\\n\",\n        \"\\n\",\n        \"![ezkl.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAEMYAAAlkCAYAAADmIc6gAAAAAXNSR0IArs4c6QAAIABJREFUeF7s3QmY1XW9P/APu8gyoCAKyO6ug7uCkmXLWKltZNfq1m0vqJuBWWmlpZZpoC1Qmv+6bbcsKk3LqG5l6owmuIy4AzIooIDCsDowDP/nN3pozpxzmDP7mTOv3/P0pOd8l8/39f3Ocnye73t67N69e3d4CBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBSYQA/BGAW2I8ohQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCoFxCM4SAQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgUpIBgjILcFkURIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgIxnAGCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEClJAMEZBbouiCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEBGM4AwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgUpIBijILdFUQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAoIxnAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIGCFBCMUZDboigCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAHBGM4AAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAQQoIxijIbVEUAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQICAYAxngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAoCAFBGMU5LYoigABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAQDCGM0CAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIFCQAoIxCnJbFEWAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQICAYwxkgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAoSAHBGAW5LYoiQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAQjOEMECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIFKSAYIyC3BZFESBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQICMZwBggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBApSQDBGQW6LoggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBARjOAMECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIFKSAYoyC3RVEECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKCMZwBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBghQQjFGQ26IoAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABwRjOAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQEEKCMYoyG1RFAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAgGAMZ4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQKAgBQRjFOS2KIoAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQEAwhjNAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBQkAKCMQpyWxRFgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAgGMMZIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQKEgBwRgFuS2KIkCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQEIzhDBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBSkgGCMgtwWRREgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECAjGcAYIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQKUkAwRkFui6IIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQEYzgDBAgQIECAAAECBSmwc9fu+rr69OpRkPUpigABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEGh/AcEY7W9sBgIECBAgQIAAgWYI1NTWxYyfPh63P/xCfa+PvGpUfO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ROVXT81aeE1tXSRnxkOAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgUn4BgjOLb0z0rmrNwZf0/VyzdGFMmDan/5ykTS/a8P3XSv/+5iBksjQABAgQKROD865fEHU9saLKa8085MC49d3wM7t87rW3d7oj/vee5+Mrvl+cMyBg1tF/8/aITYmC/Xk3Oo0HhCvz10RfjfTc+klHgB6eNjJL+veuDUpav2x6rNtTUB6eknt49e0S/Pj1jxOC+Me+9h8fkgwcW7iJVRoAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECOQlIBgjL6au2WjkrDubLHzqK0EZs8rGhqCMJrk0IECAAIEWCvzwztXxxd8ta7L3pW+ZEB87Y9Re223fURcf+fGj8bfHsodsnDR+cNz8ycnRo0eT02lQgAI1tXUx72/Pxjf/VNWq6sYN6x/lF5/YqjF0JkCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBDpfQDBG5+9Bu1UwfV5llC+rbtb4SVBGEpLR+BGa0SxGjQkQIECggcDyddvj9K8vatLk7MnD4ob3H9Fku6TB7t0RX7p5WSSBG9meC88aG7PeMCavsTTqeIFtO3bFfU9virWbd8b6zTti7aYd8fhz2+KRVVti/ZadbVLQQUP6xeIvn9wmYxmEAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQ6DwBwRidZ98hM5cvfTkYo+KVgIyKpRubHZaRKjQVmiEko0O2ziQECBAoGoHzr18SdzyxIet6xuy3T3zs1aPi3GOHx/4D+zR7zd//x7Px1d8/nbXfLZ+aHCeNH9zsMXVoX4F1m3fEW75TGSvWb2/Xia5428T44LSR7TqHwQkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECA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R6ZJBgjFZKRvJj8+4KZpc5OJwk03p+GZQjH6KRNMS0BAgS6kEC2YIzPvWlcfPp1B7fpKtZu3hGv+vri2PRSbc5xk5CN0oMHxvFjBsWY/feJmtq6eOr57fHEc1uj8pkt9SEKe3uWXjU19u3bKx5fszV21UUcNWpAm66hEAdLAjreMe/hWLp2W0Z5g/fpHe886YB4/2kHxaQD9i248rfvqIuKZdVx6sTB9fvmIUCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBJov0O2DMcqXVsf0+ZU55YRiNP9QtUePvYVjrJ47rT2mNCYBAgQIFIlAtmCMS84eHzPPHN3mK1y/ZWe863sPx2Nrtrb52MmAT199WiThGt3t2blrd/z47tVx7/JNsaa6JiYfPCjOnjwsTp1QEj16dDcN6yVAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAt1LoNsHY4ycdWfOHReKUVhfDLnCMWaXjY3ZZWMKq1jVECBAgEDBCGQLxvjyuePj469u+2CMZNFJiMNnfvlk/Hbx2jYzGDqgT/zq48fEUaMGtNmYBiJAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIdAWBbh2MMX1eZZQvq866T0IxCvP45grHWD13WmEWrCoCBAgQ6HSBjg7GSC34tofWx9W3V8XStdtaZNCvd8847ZCSOPPw/eK8k0fEwH69WjSOTgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBrizQbYMxypdWx/T5lVn3TihGYR/pbOEYs8vGxuyyMYVduOoIECBAoFMEdtXtjoMvvCtt7ovfPC4++dqDO6See5dXR/Kz655l1VFbtzvnnL179ojDDxoQZUfvH687cr8oHT0wevTokBJNQoAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAA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gAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAl1BoGiDMRoGISQbMXViSSyYWdoV9iTvGl/cujOO/tI9ae2/+tYJ8eFXjcp7jGJsmC0Yo+FrxXgWinEfrYkAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBRtMMbIWXem7e7ssrExu2xMUe34srXbY9pVi9LWdON/HRFvKh1WVOts7mLKl1bH9PmV9d0ahmA0PBOr506rfz8JzKhYunHPFLPKxr7cb1JJc6fVngABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEGhjgaIMxmgYjJDyWjCjtOjCDiqWVcc75r0cAJF6/nDBsXHcmEFtfEy63nC5QjDmLKyqX0wqKGX6vMooX1addYFJqEbyTJk0JKa88s8CM7reWVAxAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECHRdgaIMxsgWdrB67rSuu0s5Kv/9g+vi4z95PO3dBy47JUYM7lt0a23ughoHY+QKS5m7sCpnMEauOVOBGbPKxtY3EZbR3N3RngABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI5CfQLYIxkiCDBTNL8xPpQq1+8M9VcenNy9MqfnbOtOjZowstop1KbRiOsmBGaVQsq445C6vaabaIVFjGlElDYsrEkvp5BGa0G7eBCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQKCbCBRlMMbIWXembV+xBmNccevTMf/vz+5Z64B+veKpr0/tJkd378tsHIyRtJ67sCrKl1V3qE8qMGNW2dj6eYVldCi/yQgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgiwsUXTBG+dLqmD6/Mm1bZpeNjdllY7r4VmWW/8mfPxG/Xbx2zxujhvaL+750ctGtsyULmrNwZcxZWFXfteH+NwxNSYVWdFZYxpRJQ2LKxJL6GgVmtGSX9SFAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBYhfoFsEYC2aUFmXwwHnfezjuemrjnjN65MgB8dcLjy/2M5vX+nIFY0yfVxmpIIyG5yIJVEmeua+EaXR0WEYydyqoY1bZ2PpahGXktdUaESBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEARCxRdMEbDQITUvhVrMMarrlocS9du23M8p0wsid/MLC3i45r/0nIFY+R6PdfInR2YkQrLmDJpSCT7mzwCM/I/B1oSIECAAAECBAgQIND1BVKfy1IrqVj2crBhrif12anx+z5Ldf2zYAUECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBA9xQoumCM6fMqo7zRJZliDcYYf9HdUVNbt+fknnHY0PjFx47unie50arbKhgjG2bqUlZyGati6cb6Jo3PXHtvQiowY1bZ2PqpXPBqb3HjEyBAgAABAgQIECDQngLJ56yGgRfJZ632/pyV+lyVrCsJI6z//1cCCX3Oas/dNjYBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAoHkCgjGa51Uwrddu3hHHXnpvWj2vP3K/+PGHjyqYGjuzkFzBGMllq+nzK+tLSy5BLZhZ2mZldnZgRupSV3KhK3WZS2BGm22vgQgQIECAAAECBAgQaEOB5DNb8sxZWNWGo7bPUA0DNJIZUiEaqdmEabSPu1EJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB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j9/618DUvv2ssfdW5k7xwmDifjVOzI3nN1dnK2AkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQuCYgGMNOIECAAAECBAgQIECAAAECBAi0U0AwRjvXvdOsBWPYDwQIECBAIEegV+Fs3QIx4hTrWIibF4KRfsq4Akov37IEOu2r9Ovm+LGpsHF6tqwutUOAwJgE4uv42n2wdyroOO7vdbwfj2mpRtbNZz7/ZPjDD14NFz54Nfz++x8MH/7k50bS1zt++HXhnsO3jaTtpjSaDpxKz8k9tikrbB4ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIERiMgGGM0rlolQIAAAQIECBAgQIAAAQIECFRdQDBG1VdovOMTjDFeb70RIECAQIUFehXOxmLZeJxdOFrhWeQPra5FuHlhBem5jKOAuXaLbcADCXQKxhDEMhCniwhMXCAW32/t7BUOwxj3/T0d/JRgXVk5MXG3tgzgkUefDNt/sRcu/Per4U8//FD4wF9+NsSfDXP88Le+OHzf337BME204lrBGK1YZpMkQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgULrA2tpaWF1d3W93bm4urK+vl96HBgkQIECAAAECBAgQIECAAAECBKonIBijemsyyREJxpikvr4JECBAoBICeaER6YHF8IX5Y1Ph+MxUJcbb7yDqGooR55kXgiEYo98d4PwiAuki9XRxumCMInrOIVAdgV739Oz9fVJhV+n3lmRMG6dma/tZozo7YPCRfOrhx8N7Pvpw+PMHHg6XHng4/MmHHgoff+ixng3ectOh8LY3Hgvfcfyenuc6IYS8vR9d7H+7gwABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBbgKCMewPAgQIECBAgAABAgQIECBAgEA7BQRjtHPdO81aMIb9QIAAAQKtFehVPBsDMSZVMFvWotQ5FCMa5IVgZJ80ng4xKMtNO+0SSO+p48emwsbp2QOAToEZ7RIyWwLVFoj3iq3LV8PFnb1CA63C/b3u9+dC0A046ROfeSz84Qevhu2dh8IDD34+XLn6aPjEZx4PTz75dHje7TeHEy89HM58w3R4wV23NWC245lC+r6a7t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QIECBAgAABAgQIECBAgAABAgQIECBAgACBCgoIxqjgohgSAQIECBAgQIAAAQIECBAgQGBMAoIxxgRdk24EY9RkoQyTAAECoxIQiDEqWe2OUyC7j9PhGAozx7kS1e0r+zT7GIxx8vylgwF7qn11187ICLRdIPv+lfVwn2v7Dpns/PP+LSFsarJroncCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECTRMQjNG0FTUfAgQIECBAgAABAgQIECBAgEBxAcEYxa3acKZgjDassjkSIEAgIxAL2OJxbnO3kI2Cy0JMTpqwwJEzFzqO4MrKiQmPTveTFkg/zT6+p21dvhou7uztD0sB76RXR/8ECPQSyIYPxPex9Oc497legn4/CoFOoS3CpkahrU0CBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEC7RUQjNHetTdzAgQIECBAgAABAgQIECBAgIBgDHsgLSAYw34gQIBAiwTynujcafqx4DIeZxeOtkjIVOss0G1/C3ep88oOP/Zs4W62oFwB7/DGWiBAYPQC6QCo7PuYgJ/R++vhRoF06FTyW5+57BQCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBMoWWFtbC6urqwfNrq+vh7m5ubK70R4BAgQIECBAgAABAgQIECBAgEAFBQRjVHBRJjgkwRgTxNc1AQIExiXQbyDG/LGpcHxmalzD0w+B0gTSRcPZRq+snCitHw3VSyBduBuLx+NxcWdv/78KeOu1lkZLoM0C2c9zMdTn5PlLByTCMdq8O8Y/92zoVByBPTj+ddAjAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgTYICMZowyqbIwECBAgQIECAAAECBAgQIEAgX0Awhp2RFhCMYT8QIECgoQKxeDIe5zZ3C81QcXghJidVXKBbCIw9XvHFG+Hw0oEpcR+k3xcFpowQXtMECJQukA76ie9n2c967nWlk2uwg0BeGFkMaxGuZ8sQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIFC2gGCMskW1R4AAAQIECExa4OMf/3h4+9vfHj70oQ+Fqamp8MY3vjG89rWvnfSwxtr//fffH/b29sKrXvWq8O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tpaD5+A9JFeULH3EsVx4ohQahRvqSea458LoJ8rafFGRLmG/9oXbx6T/UcyaMwB3174QF8u+6EKoKjM9tYhJFoJEACJEAC+Y8AhTHy35wxYxIgARIgARIgARIgARIgARIgARIgARKwh4C3t3eWZhTGsIdiwWtTKIQxYg5cRLfZ8dlmb1GfAIT72n/iV8FbDoVvRN1mxSPm4EXLwAd19Magjs47Jajw0eSISYAESIAESIAESIAESIAESIAESIAESIAESIAESIAESCDvEThz5QaCxq3XLaB7uU01THzMxykDCJ6wAScupGrGqlquJOLGhDilPwYhgfxOICX1JuoNj8m1YZQsXhRB3mUtQhhhPh4IrFWWgga5NhvmO16w8RQi5u/TbChzfHh6K/PBFVqkpWegwYh1SE3PUI3Xq001THLSM8UpSeehIJev38SfO85i0+FLOHkxFSIodfrKDVy6lg531+KWIvaaFUrd/m+tCqUQWtcdLsX/O0meRgIkUHgJvPX9XizalKwLQESJlg8OQm3PUrq+OemwJekyHoraqtuF3OdiR7XQ9aODOQJTf0vAh38fUW20aUwIqpXLHeEUcyOhNwmQAAmQgC2BqKgoREZG3v7n6OhoSFEEjQRIgARIgARIgARIgARIgARIgARIgARIoOAQiI2NhQikWhuFMQrO/DoykkItjHH8vTaOsMvzbeVFnO/WncTmpMtIPHvd8lKJa4liqFS2BCqVdUHFsiUQVKssHg3yKrQK+NbCGOE+HljUNyDPzysTJAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESME7gnd8T8P4K9YIoiRRa1wOL+wagiJNODB65+CDmrjmumaQU7O2fGm58IPQkgQJMIOHsdYRP3njXRti4ehk82MQT/tXc0KBKadTydM1Xv5feuHkLyZfSkHw5zcLM27MUKriVuGv88lpHV1Jvor4BYZXVw5rDx8vV4fTnrD6OUUsOasYR4SMRQKLdIfDzltP4YvVxxCVcMo2leNEi6BxQEc+HV0G4TzmnPa9NJ8IG+Y7A8QupSDhzHedSbiDj1q3/3pUpU8JSDC97sbxst24BZ66kWcRjUm9koIpHSUveztqv5uWxK+V26PQ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1r19Oq6bOT8eRulE1/SmV596LZ1Gc8gBAgQIECgngLCL+qpOb1jCcSYXn+zEyBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEhCM0fj7o9JgjIGBgZTJZBpfkBkIECBAoKUFBGO09PYojgABAgQqERCMUYmSPgQIzESBa+9cmd70tavT7cseT71dHekH794/rb/eOjNxqRWt6ZX//pd00c0PFvT9vxMOSQt22LSi63UiQCCly259KL1s6PICiufvtWX6/rtaNxgjV+zDjz+Vzj7vjvTF392WHnxsVVXbueWm66cX7L1letG+89Lz9twyzd1kTlXX60yAAAECBOotIPyi3qKtNV4EYkQ749zJv8li4TGdaeEx81trAaohQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECMwCAcEYjd3kcr4xa09PT4rHc00wRmP3wugECBBoFwHBGO2yU+okQIAAgbIC+35scVq28smxx+esu0669fQjiBEgQIDALBN4z7evSz+97N6CVf964cFpv502m2USlktg6gJ3rXgiHfKJCwsGOLx7bvqvY/ef+qBNvnLV06vTL664L11yy0NpyT2PpBvufiTdveKJFL+Pz4nbbLFB2n3rjdMe222c9tx+0/T/9pqbdt164yZXaToCBAgQIJCS8IvZeRdEKMZkgRgRhhFNIMbsvEesmgABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEGgNAcEYjd2HaoIxopLR0cm/hKaxFRudAAECBKZbQDDGdO+A+QkQIECgZoEXnn5puuaOlQXj3Hza4WnDOevWPLYBCBAgQKB9BE79+c3pi7+/raDgb79z33TUgnntswiVEphmgaeeXp12+eD5BVV0b7tJ+tOHD53mykxPgAABAgTaU0D4RXvuWyOqFojRCFVjEiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQaJyAYo3G2MXJ/f38K41JtYGAgDQ0NFTwUv8tkMo0tyugECBAg0NICgjFaensUR4AAAQKVCLz5a1en31zzQEHXX2YOTgfuslkll+tDgAABAjNE4Ovn35E++t9LC1bz4Zfumt7/wl1myAotg0BzBPb4y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IECKTi8IsgqTUAo9XCL0oFb9j62S0wWSBG6JQKxRCIMbvvG6snQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEZqeAYIz67ntnZ+fYgBGKEeEY+W2yYIzomz/GwMBAymQy9S3SaAQIECDQ0gKCMVp6exRHgAABAgQIECBAgAABAgQIECBAgACBqQkIv5iam6tmnkA8F177xStKLixCL6IJxJh5+25FBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFaBARj1KJXeG2x5ejo6LjBKwnGGBoaSoODg9lrBWPUb3+MRIAAgXYREIzRLjulTgIECBAgQIAAAQIECBAgQIAAAQIECBQJCL9wSxCYXOCMc28tCL7o6+pIvd1zsxeOLFmeFi1dUTBILixj4THzJx9cDwIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgRkpIBijftuaH3rR09OThoeHxw1ebTBGDFAqYKN+VRuJAAECBFpNQDBGq+2IeggQIECAAAECBAgQIECAAAECBAgQIJAnMBPDL3KhBLHM3q6O1NfdYc8JNEwgnkOfP3d0LAwjAi+KwzJyk0cohkCMhm2FgQkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECbSMgGKM+W1XsGKEYEY5R3CoJxohrOjs7xy4dGBhImUymPoUahQABAgRaXkAwRstvkQIJECBAgAABAgQIECBAgAABAgQIEJjpAo0Ovwi/cgEU0zn3TN9X62s9AYEYrbcnKiJAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQItKKAYIz67Eq+YwRiRDBGqVZpMMbQ0FAaHBzMDiEYoz57ZBQCBAi0i4BgjHbZKXUSIECAAAECBAgQIECAAAECBAgQINDWAtMZQDGdc7f1pil+xggIxJgxW2khBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIGmCAjGqA9zceBFhGOUalMJxohxRkdH61OoUQgQIECg5QUEY7T8FimQAAECBAgQIECAAAECBAgQIECAAIF2EZjOAIrpnLtd9keds1OgVCjGwmM6U29XR+rr7pidKFZNgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAwoYBgjNpvkGLDiUIs8oMxBgYG0tDQ0FgBxdd1dnaWfaz2qo1AgAABAq0qIBijVXdGXQQIECBAgAABAgQIECBAgAABAgQItKRAfgBFFDiyZHlatHRFTbX2dXWk3u65Y2OUOrAf82bnWztXPeaN8SqZu6bFuZjANAu89swrCp6jEYqx8Jj501yV6QkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBFpZQDBG7buTH3bR09OThoeHyw4aQRiDg4PZxycLxigO0chkMrUXawQCBAgQaHkBwRgtv0UKJECAAAECBAgQIECAAAECBAgQIECg2QLCL5otbj4CjRPIfz4LxGics5EJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAjNJQDBGbbtZ7BehGBGOUa5VE4yR33eywI3aVuFqAgQIEGglAcEYrbQbaiFAgAABAgQIECBAgAABAgQIECBAoGkCwi+aRm0iAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQItJWAYIzatqu/vz+FYbRKwiuKgzHi2tz1xaEaxXszOjpaW7GuJkCAAIG2EBCM0RbbpEgCBAgQIECAAAECBAgQIECAAAECBKYiMJ3hFyNLV4yVPLJkeVqU9/eprCWu6evqSL3dc7OX93Z1ZH/2da/5qREgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAfQQEY9Tm2NnZOTZAcbBFqZGrCcaI6/PHHxgYSJlMpraCXU2AAAECLS8gGKPlt0iBBAgQIECAAAECBAgQIECAAAECBAhMJCD8wv1BgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAvUUEIwxdc1iu9HR0UkHqzYYo7i/YIxJiXUgQIBA2wsIxmj7LbQAAgQIECBAgAABAgQIECBAgAABAjNfYCaFX/R1dWQ3rLd77pqfa//e173m9xoBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQITK+AYIy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gQaD8BwRjtt2cqJkCAAAECBAgQIECAAAECBFpAoNHhFxF2EU34RQtsthIIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBWScwm4MxIpQigiWKWwRWRFBFI1q+9+joaCr++1TmLN7DqYZsTGVu1xAgQIBAfQUEY9TX02gECBAgQIAAAQIECBAgQIDADBIQfjGDNtNSCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQJVCMzWYIwIxIhgjOLW6FCJRgRjDA0NpcHBwYKlROiGRoAAAQLtJyAYo/32TMUECBAgQIAAAQIECBAgQIBAHQUi/CLayNK1P5csT4vW/nmq0/R1daTe7rlrxl2yPPsz/+/1GD9/zN6ujtTX3THVcl1HgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBQJDBbgzEiFCPCMYrb8PBwinCMRrVmBWMMDAykTCbTqGUYlwABAgQaJCAYo0GwhiVAgAABAgQIECBAgAABAgRaSyACMOodfhErjMAL4RettdeqIUCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAjUKjAbgzEiECOCMUq1dgzGiHWU2sfR0dFabw/XEyBAgECTBQRjNBncdAQIECBAgAABAgQIECBAgEDjBIrDL2KmRUtXTHnCvq6O7LXCL6ZM6EICBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQFsKzMZgjAjFiHCM4tbT05MiGKORLd87giuK/z7VuYeGhtLg4GDB5QMDAymTyUx1SNcRIECAwDQICMaYBnRTEiBAgAABAgQIECBAgAABAlMXyA+/iFFGliyvKfwixogAjEaGX8TYudbb1ZH6utcEbmgECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKtKTDbgjEiECOCMUq1CMWIcIxGtmYGY8Q6InxDI0CAAIH2ERCM0T57pVICBAgQIECAAAECBAgQIDBrBJoRfpGPuWjpippsc8EauUGEX9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xURIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQqFRgpgdjhEMujCICIqLlQiIiFCMXllGpV639mhWMEXVGAEh+GEju781ec61mridAgMBsEhCMMZt221oJECBAgAABAgQIECBAoG4C+eEXMejIkuVp0dIVdRu/1oH6ujqyQ/R2z13zs6sj9XWv+Z1GgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMDEArMhGKNYIMIpent708DAQNNvj2YGYzR9cSYkQIAAgZoFBGPUTGgAAgQIECBAgAABAgQIEJipAu0QfpELvog9EH4xU+9E6yJAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEGi2wGwMxmi2cf58gjGmU9/cBAgQaH0BwRitv0cqJECAAAECBAgQIECAAIEGC+QHYIwsWZ4WLV3R4BkrH76vqyMJv6jcS08CBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEC9RAQjFEPxcrHEIxRuZWeBAgQmI0CgjFm465bMwECBAgQIECAAAECBGahQH74RSy/lQIwhF/MwhvSkgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBFpaQDBGc7dHMEZzvc1GgACBdhMQjNFuO6ZeAgQIECBAgAABAgQIECgrEOEX0UaWrv25ZHlatPbP080m/GK6d8D8BAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBCoXEIxRuVU9ehYHYyxevDgNDg5mhx4eHk49PT31mMYYBAgQINCmAoIx2nTjlE2AAAECBAgQIECAAIHZLBABGMIvZvMdYO0ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEGiuQH4wRoQwR1BBNSENj3CcKxhgYGEiZTKYxExuVAAECBNpCQDBGW2yTIgkQIECAAAECBAgQIDA7Bc4499axhY8sWZ4WLV0x7RB9XR2pt3vuWB29XR2pr7tj2utSAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEC9RMQjFE/y0pGEoxRiZI+BAgQmL0CgjFm795bOQECBAgQIECAAAECBFpa4LVnXjFtQRjCL1r61lAcAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgYYLCMZoOHHBBIIxmuttNgIECLSbgGCMdtsx9RIgQIAAAQIECBAgQGCWCOx4/HkNXanwi4byGpwAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAWwsIxmju9gnGaK632QgQINBuAoIx2m3H1EuAAAECBAgQIECAAIEZKrBoyYo0snTF2OrOOHe05pUKv6iZ0AAECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEZqWAYIzmbrtgjOZ6m40AAQLtJiAYo912TL0ECBAgQIAAAQIECBCYYQJnnHtrqiUEQ/jFDLshLIcAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBACwgIxmjuJgjGaK632QgQINBuAoIx2m3H1EuAAAECBAgQIECAAIEZJrDj8edNuiLhF5MS6UCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQB0FBGPUEbOCoYaGhtLg4GC258DAQFpnnXUK/p7JZCoYRRcCBAgQmKkCgjFm6s5aFwECBAgQIECAAAECBNpE4LVnXpEWLV2RIvwiWm/33DU/uzpSX/ea32kECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBBopoBgjGZqpyQYo7neZiNAgEC7CQjGaLcdUy8BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEBDBQRjNJR33OCCMZrrbTYCBAi0m4BgjHbbMfUSIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAg0VEAwRkN5xw0uGKO53mYjQIBAuwkIxmi3HVMvAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAQwUEYzSUd9zggjGa6202AgQItJuAYIx22zH1EiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQINFRAMEZDeccNLhijud5mI0CAQLsJCMZotx1TLwECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQEMFBGM0lHfc4MXBGL29vam/vz/br6enJw0PDze3ILMRIECAQEsJCMZoqe1QDAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAwHQLCMZo7g4Ixmiut9kIECDQbgKCMdptx9RLgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECDQUAHBGA3lHTe4YIzmepuNAAEC7SYgGKPddky9BAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECDRUQjNFQ3nGDC8ZorrfZCBAg0G4CgjHabcfUS4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAg0FABwRgN5R03uGCM5nqbjQABAu0mIBij3XZMvQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAg0VEIzRUN5xgwvGaK632QgQINBuAoIx2m3H1EuAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQINBQAcEYDeUdN7hgjOZ6m40AAQLtJiAYo912TL0ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQINFRCM0VDecYMLxmiut9kIECDQbgKCMdptx9RLgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECDQUAHBGA3lHTe4YIzmepuNAAEC7SYgGKPddky9BAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECDRUQjNFQ3nGDC8ZorrfZCBAg0G4CgjHabcfUS4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDA/2fvTqDkrMr8AV8gKttxmThCUCIEQYIZEMxgwhBwIBIgUbIYo0hAJBFRlm4WQdmO7IalGzEJEBFkb1CWDFEkCAkoiTlEjCJBGCMJMyBiHNF/iEuA/7l1pjNVXVVd1d3V31L93HNyYrrud9/3PreC3an6fkWAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAj0q4BgjH7lLVt86dKlYdq0aYWvjxo1KrS2tpb8uaOjI9mGVCNAgACBTAkIxsjUcWiGAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgbQHBGMmegGCMZL1VI0CAQN4EBGPk7cT0S4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAg0K8CgjH6lbds8a7BGB0dHaH4DFavXp1sQ6oRIECAQKYEBGNk6jg0Q4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgkLaAYIxkT0AwRrLeqhEgQCBvAoIx8nZi+iVAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEOhXAcEY/cpbtrhgjGS9VSNAgEDeBARj5O3E9EuAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQINCvAoIx+pW3bHHBGMl6q0aAAIG8CQjGyNuJ6ZcAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQKBfBQRj9Ctv2eKCMZL1Vo0AAQJ5ExCMkbcT0y8BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEC/CgjG6FfessUFYyTrrRoBAgTyJiAYI28npl8CBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIF+FRCM0a+8ZYsLxkjWWzUCBAjkTUAwRt5OTL8ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAg/m1rpwAAIABJREFUQIAAAQL9KiAYo195yxYXjJGst2oECBDIm4BgjLydmH4JECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgT6VUAwRr/yli0uGCNZb9UIECCQNwHBGHk7Mf0SIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAj0q4BgjH7lLVtcMEay3qoRIEAgbwKCMfJ2YvolQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBDoVwHBGP3KW7a4YIxkvVUjQIBA3gQEY+TtxPRLgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECDQrwKCMfqVt2xxwRjJeqtGgACBvAkIxsjbiemXAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgXwUEY/Qrb8XFi81Xr14dpk2bFmJgRhwdHR1h1KhRyTelIgECBAhkQkAwRiaOQRMECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQJZERCMkfxJCMZI3lxFAgQI5EVAMEZeTkqfBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECiQgIxkiEuaSIYIzkzVUkQIBAXgQEY+TlpPRJgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQiIBgjESYS4oIxkjeXEUCBAjkRUAwRl5OSp8ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKJCAjGSIS5pIhgjOTNVSRAgEBeBARj5OWk9EmAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIJCIgGCMRJhLigjGSN5cRQIECORFQDBGXk5KnwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAokICMZIhLmkiGCM5M1VJECAQF4EBGPk5aT0SYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgkIiAYIxEmEuKCMZI3lxFAgQI5EVAMEZeTkqfBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECiQgIxkiEuaSIYIzkzVUkQIBAXgQEY+TlpPRJgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQiIBgjESYS4oIxkjeXEUCBAjkRUAwRl5OSp8ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKJCAjGSIS5pIhgjOTNVSRAgEBeBARj5OWk9EmAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIJCIgGCMRJhLigjGSN5cRQIECORFQDBGXk5KnwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAokICMZIhLmkSNdgjPb29tDW1laY09LSElpbW5NvSkUCBAgQyISAYIxMHIMmCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEsiIgGCP5kxCMkby5igQIEMiLgGCMvJyUPgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBBIREIyRCHNJkWnTpoWlS5cWvtbR0VH4321tbYU/t7S0hNbW1uSbUpEAAQIEMiEgGCMTx6AJAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBrAgIxkj+JARjJG+uIgECBPIiIBgjLyelTwIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgUQEBGMkwlxSRDBG8uYqEiBAIC8CgjHyclL6JECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQSERAMEYizCVFBGMkb64iAQIE8iIgGCMvJ6VPAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBRAQEYyTCXFJEMEby5ioSIEAgLwKCMfJyUvokQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBBIREAwRiLMJUUEYyRvriIBAgTyIiAYIy8npU8CBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFEBARjJMJcUkQwRvLmKhIgQCAvAoIx8nJS+iRAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEEhEQDBGIswlRQRjJG+uIgECBPIiIBgjLyelTwIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgUQEBGMkwlxSRDBG8uYqEiBAIC8CgjHyclL6JECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQSERAMEYizCVFBGMkb64iAQIE8iIgGCMvJ6VPAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBRAQEYyTCXFJEMEby5ioSIEAgLwKCMfJyUvokQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBBIREAwRiLMJUW6BmPEB+PX4hg1alTo6OhIvikVCRAgQCATAoIxMnEMmiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEMiKgGCM5E9CMEby5ioSIEAgLwKCMfJyUvokQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBBIREAwRiLMJUWKgzFaWlrC6NGjQ/xaHKNGjQodHR3JN6UiAQIECGRCQDBGJo5BEwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAlkREIyR/Em0t7eHtra2QmHBGMn7q0iAAIEsCwjGyPLp6I0AAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQCBxAcEYiZMHwRjJm6tIgACBvAgIxsjLSemTAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgEQHBGIkwlxQRjJG8uYoECBDIi4BgjLyclD4JECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQSERCMkQhzSRHBGMmbq0iAAIG8CAjGyMtJ6ZMAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQCARAcEYiTCXFBGMkby5igQIEMiLgGCMvJyUPgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBBIRKA7GaG1tDW1tbYW6LS0tIf7ZaLyAYIzGm1qRAAECzSIgGKNZTtI+CBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEGiIgGKMhjD1aRDBGj7hMJkCAwIASEIwxoI7bZgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBGoJCMaoJdT4xwVjNN7UigQIEGgWAcEYzXKS9kGAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQINAQAcEYDWHs0SKCMXrEZTIBAgQGlIBgjAF13DZLgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBQS0AwRi2hxj/eNRijtbU1FJ/D6tWrG1/UigQIECCQCwHBGLk4Jk0SIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgkJSAYIynp/6sjGCN5cxUJECCQFwHBGHk5KX0SIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgkIiAYIxHmkiKCMZI3V5EAAQJ5ERCMkZeT0icBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEAiAoIxEmEuKSIYI3lzFQkQIJAXAcEYeTkpfRIgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECCQiIBgjEeaSIoIxkjdXkQABAnkREIyRl5PSJwECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQCICgjESYS4psnTp0jBt2rTC10aNGhU6OjpC8TmsXr06+aZUJECAAIFMCAjGyMQxaIIAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQCArAoIxkj8JwRjJm6tIgACBvAgIxsjLSemTAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgEQHBGIkwlxQRjJG8uYoECBDIi4BgjLyclD4JECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQSERCMkQhzSRHBGMmbq0iAAIG8CAjGyMtJ6ZMAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAA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MmI3+/G37sb8XtdARlpn5b6BAgQIECAAAECBAgQIECAAAECBAgQIECAQLMICMZI5yQFY6TjrioBAgSyLiAYI+snpD8CBAgQIECAAAECBAgQIECAAAECBAgQ6Fag3kCMeIOgMAxPJgIECBAgQIAAgTwLxGCM+GvJkiXdhmQIyMjzKeudAAECBAgQIECAAAECBAgQIECAAAECBAgQyIqAYIx0TkIwRjruqhIgQCDrAoIxsn5C+iNAgAABAgQIECBAgAABAgQIECBAgACBigL1BGLEGwJHjx4tEMNziAABAgQIECBAoOkEYkBG/J44/l5tCMhoumO3IQIECBAgQIAAAQIECBAgQIAAAQIECBAgQCBBAcEYCWIXlRKMkY67qgQIEMi6gGCMrJ+Q/ggQIECAAAECBAgQIECAAAECBAgQIECgRKCeQIzW1tbCNS0tLfQIECBAgAABAgQINLVADMaIv5YsWVI1JENARlM/BWyOAAECBAgQIECAAAECBAgQIECAAAECBAgQ6CcBwRj9BFtj2a7BGO3t7YXA+Dji+8E63xuWTneqEiBAgEBaAoIx0pJXlwABAgQIECBAgAABAgQIECBAgAABAgR6JFBvIIYwjB6xmkyAAAECBAgQINBEAjEgI37fHH+vNGJARkdHRxPt2FYIECBAgAABAgQIECBAgAABAgQIECBAgAABAv0nIBij/2y7W1kwRjruqhIgQCDrAoIxsn5C+iNAgAABAgQIECBAgAABAgQIECBAgMAAFxCIMcCfALZPgAABAgQIECDQY4FaARkxHCOGZBgECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQLVBQRjpPPsEIyRjruqBAgQyLqAYIysn5D+CBAgQIAAAQIECBAgQIAAAQIECBAgMIAFaoVitLa2hpaWlgEsZOsECBAgQIAAAQIEqgt0F5ARv4+O308bBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEClQUEY6TzzBCMkY67qgQIEMi6gGCMrJ+Q/ggQIECAAAECBAgQIECAAAECBAgQIDAABWp9wnW8gS9+wrVPuR6ATw5bJkCAAAECBAgQ6LGAgIwek7mAAAECBAgQIECAAAECBAgQIECAAAECBAgQIBAEY6TzJBCMkY67qgQIEMi6gGCMrJ+Q/ggQIECAAAECBAgQIECAAAECBAgQIDDABNra2kJ7e3vVXcdQjPjp1gYBAgQIECBAgAABAj0TqBaQEQPnOsPnerai2QQIECBAgAABAgQIECBAgAABAgQIECBAgACB5hUQjJHO2QrGSMddVQIECGRdQDBG1k9IfwQIECBAgAABAgQIECBAgAABAgQIEBhAAt2FYgjEGEBPBFslQIAAAQIECBDoV4EYkDFt2rSyGjGALn7fbRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECIQgGCOdZ4FgjHTcVSVAgEDWBQRjZP2E9EeAAAECBAgQIECAAAECBAgQIECAAIEBINBdIEbcvlCMAfAksEUCBAgQIECAAIHEBWI4RgzJKB6jRo0KHR0difeiIAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgawKCMdI5keLXsOLrVvH1rPj+sjgEvadzJqoSIEAgCwKCMbJwCnogQIAAAQIECBAgQIAAAQIECBAgQIDAABboLhRDIMYAfmLYOgECBAgQIECAQCIC7e3tG99I2FkwhmPE78Xj7wYBAgQIECBAgAABAgQIECBAgAABAgQIECBAYKAKCMZI5+QFY6TjrioBAgSyLiAYI+snpD8CBAgQIECAAAECBAgQIECAAAECBAg0sUClT6ju3K5QjCY+eFsjQIAAAQIECBDIlEDnp2zF34uHT9zK1DFphgABAgQIECBAgAABAgQIECBAgAABAgQIEEhYQDBGwuD/W04wRjruqhIgQCDrAoIxsn5C+iNAgAABAgQIECBAgAABAgQIECBAgECTCnQXitHR0eHTqZv03G2LAAECBAgQIEAguwLt7e2hra2tpMFRo0aFGFoXfzcIECBAgAABAgQIECBAgAABAgQIECBAgAABAgNJQDBGOqctGCMdd1UJECCQdQHBGFk/If0RIECAAAECBAgQIECAAAECBAgQIECgyQTip1DHFy8rjXizXQzFMAgQIECAAAECBAgQSEegUjhG7KSlpaUQkGEQIECAAAECBAgQIECAAAECBAgQIECAAAECBAaKgGCMdE5aMEY67qoSIEAg6wKCMbJ+QvojQIAA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eKMQhrFixYqN15988snhpJNO6p9mrUqAAIEcCQjGSOewBGOk464qAQIEsi4gGCPrJ6Q/AgQIECBAgAABAgQIECBAgAABAgQIZEigra0txBceKw03uGXooLRCgAABAgQIECBAIGWBaoF6MUwvhuoZBAgQIECAAAECBAgQIECAAAECBAg0TmDq1Klh2bJlJQvGoIzx48fXLPL3v/897LzzzmXz4nrbbLNNzetNIECAQDMLCMZI53SXLl0apk2bVig+atSo0NHREYrPwvvU0jkXVQkQIJC2gGCMtE9AfQIECBAgQIAAAQIECBAgQIAAAQIECORIIL7gGF947Do6X4DM0Va0SoAAAQIECBAgQIBAPwoUf5JX1zLCMfoR3tIECBAgQIAAAQIECBAgQIAAAQIDUqDSa/mzZs3aeFNxdygbNmwIO+20U9mUhx9+OAwbNmxAeto0AQIEOgUEY6TzXBCMkY67qgQIEMi6gGCMrJ+Q/ggQIECAAAECBAgQIECAAAECBAgQIJARgeIXHLu2FFP5YziGQYAAAQIECBAgQIAAgU4Bbxb1XCBAgAABAgQIECBAgAABAgQIECCQjMARRxwRHn300ZJiZ599dpgxY0bNBl5//fWw4447ls37j//4j7D77rvXvN4EAgQINLOA1zrSOV3BGOm4q0qAAIGsCwjGyPoJ6Y8AAQIECBAgQIAAAQIECBAgQIAAAQIZEaj0CTOxtRiIEYMxDAIECBAgQIAAAQIECBQLtLe3h7a2tsKXWlpaQvxz51i9ejUsAgQIECBAgAABAgQIECBAgAABAgQaJHDkkUeGxYsXl6x28sknh5NOOqmuCsU3fndecPvtt4fRo0fXdb1JBAg0TuCVV14Jy5YtC3vttVcYPHhw4xa2Uq8EBGP0iq3PFwnG6DOhBQgQINCUAoIxmvJYbYoAAQIECBAgQIAAAQIECBAgQIAAAQKNF6j0RphYJYZixHAMgwABAgQIECBAgAABAsUCxcEY8eutra0lQRnxzwYBAgQIECBAgAABAgQIECBAgAABAn0XOProo8NDDz1UstDMmTPDWWedVdfild4P8K1vfSt89KMfret6kwhUE9iwYUO4++67wy9/+cvw3HPPha233jo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2tvbQ3xDc+fPEfHNjJ1D2F7WT09/BAgQIECAAAECBAgQIECAAAECeRAYP3582U3548aNK9xEX2v8+c9/Dv/yL/9SNu38888v3OxvEOipQAyKGDNmTFi3bl1PLw2nnXZaOP7443t8XVoXxD1OmDAhrFq1qmILe+65ZzjjjDMK77GpNdasWVNw627MmjUrxPfxGMkJCMZIzrq4kmCMdNxVJUCAQNYFBGNk/YT0R4AAAQIECBAgQIAAAQIECBAgQIAAgZQFqn26cwzFqOeF+5TbV54AAQIECBAgQIAAgZQFit+82LWVlpaW0NramnKHyhMgQIAAAQIECBAgQIAAAQIECBDIt8DYsWPDs88+W7KJT3ziE+Hyyy+vubEYYrDXXnuVzbvsssvC1KlTa15vAoGuAldeeWW44ooreg1zxBFHhK997Wth0KBBvV4jqQtj6MVtt91WsVx8T80NN9wQtthii7rbufPOO8Opp57a7fzFixeHHXbYoe41TeybgGCMvvn19mrBGL2Vcx0BAgSaW0AwRnOfr90RIECAAAECBAgQIECAAAECBAgQIECgTwLVbmCLL97HYAyDAAECBAgQIECAAAEC9QjET7CLP190HYIx6tEzhwABAgQIECBAgAABAgQIECBAgED3AmPGjAlr1qwpmXTkkUeG888/vybdiy++WPFDMebMmRPGjx9f83oTCHQV+Pd///ewatWqPsFMmjQpxHCWLIdj3H///eHYY4+tuM+dd9453HPPPWHrrbfuscMPf/jDQqD0unXrKl675557hu9+97uZtunxpjN8gWCMdA5HMEY67qoSIEAg6wKCMbJ+QvojQIAAAQIECBAgQIAAAQIECBAgQIBAigJuXksRX2kCBAgQIECAAAECTSTQ3t4e2traCjuKYRjxz51j9erVTbRTWyFAgAABAgQIECBAgAABAgQIECCQvMBee+0V1q5dW1L4uOOOC2eccUbNZp577rmw//77l827/vrrwwEHHFDzehMIFAv87W9/C7vssktVlBjYsu+++4Y//OEP4eqrry4LdCm+cOrUqeHrX/962GyzzTKH/PLLLxf+3lQLr1i4cGG3DrU29Oyzz4axY8dWnXbBBReE6dOn11rG4w0QEIzRAMReLCEY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OkZ68yAQIEsiogGCOrJ6MvAgQIECBAgAABAgQIECBAgAABAgQIpCwQ31TQ+QnOxa10dHQUPtHZIECAAAECBAgQIECAQE8EioMx4s8UxT9vCMboiaS5BAgQIECAAAECBAgQIECAAIGBJ/D888+Hs846q3DTeU/HggULwogRI3p6WW7mv/rqq4VAkK4j/nvcpEmTau7jkUceCdOnTy+b95Of/CS85z3vqXm9CQSKBW688cZw9tlnl6E8/fTTYYsttugW64knniiEuaxbt67ivMmTJ4dLL700DBo0KDX0//mf/wkf/OAHK9afM2dOGD9+fMN7mzJlSkngT3GBq6++OhxyyCENr2nB/xMQjJHes0EwRnr2KhMgQCCrAoIxsnoy+iJAgAABAgQIECBAgAABAgQIECBAgEDKAsUvLha34oa1lA9GeQIECBAgQIAAAQI5FvAG0hwfntYJECBAgAABAgQIECBAgAABAikIvPbaa+Hmm28O55xzTq+rn3baaeH444/v9fVZv/CVV14Ju+++e1mb1157bRg3blzN9h966KFw9NFHl8372c9+FgYPHlzzehOaSyD+nfv2t78d7rnnnvDkk0+GoUOHhs9//vMVw1Mq7fzyyy8P3/jGN8oeqve9Ji+88EL43Oc+F1auXFkR9rDDDgtXXnll2GSTTVKBrxb8seeee4a77767X/qKIdPxw20qjRj6E8N/jP4T8LpG/9nWWrlrMEZxAHtLS0tobW2ttYTHCRAgQKDJBARjNNmB2g4BAgQIECBAgAABAgQIECBAgAABAgQaIVDtRfX4qc4dHR2NKGENAgQIECBAgAABAgQGoEB88278eaPr8AbGAfhksGUCBAgQIECAAAECBAgQIECAQA2BGPgwY8aMsGzZsj5ZDRkyJPz4xz8OgwYN6tM6Wb147dq1Ya+99ipr76abbgr77bdfzbZ/+MMfFoIPuo4YTLDlllvWvN6E5hKYNWtWmD17dtmmYjjNMcccU3OzZ5xxRrjttttK5sWAlRi0Uu/44x//GKZMmRJWrVpV8ZJzzz23EJ6Rxjj44IMrhnZcf/314YADDui3lj796U+Hxx57rOL6d955Z9h77737rfZAX7g4nCG+Z6ozpMR7q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l8KXv/zlnixnbp0CgjHqhOqHaYIx+gHVkgQIEMi5gGCMnB+g9gkQIECAAAECBAgQIECAAAECBAgQINBogWovpAvGaLS09QgQIECAAAECBAgMTIH29vbQ1tZWtvmWlpayN+APTCG7JkCAAAECBAgQIECAAAECBAgMXIFTTjklfPe7360KEG/Kv+qqq8KIESPK5ixcuDDMmDGj6rUxQCPewP62t72tqYCfe+65sP/++5ft6ac//WnYdttta+71zjvvDKeeemrJvKFDh4ZHH3205rUmNJ9ADJC59dZbu91Yd0EXMdgmvu+keEyaNCnEfxfu7Yj/nlzp+iSDMX7+85+Hww47rGwLMZxn/vz5vd1aj6+bMmVKePzxx8uui/99W758edhiiy16vKYLuhcQjJHeM0QwRnr2KhMgQCCrAoIxsnoy+iJAgAABAgQIECBAgAABAgQIECBAgEBKAtWCMXx6c0oHoiwBAgQIECBAgACBJhMQjNFkB2o7BAgQIECAAAECBAgQIECAAIEGCdxxxx3htNNOq7paDH+45pprur3x+9577w0nnnhi1TWuvvrqcMghhzSo42wsUy0Y4xe/+EVdISCVgjGGDx8e7r///mxsUBeJCmzYsCFcdtllYe7cud3W/dWvfhW23nrrsjlHHHFEWajKhAkTwuzZs3u9j0rP0bhYksEYl19+efjGN75RtocTTjihLFim1xut48KHHnooHH300RVnxnObOnVqHauY0hMBwRg90WrsXMEYjfW0GgECBJpBQDBGM5yiPRAgQIAAAQIECBAgQIAAAQIECBAgQKCBAtVuUhOM0UBkSxEgQIAAAQIECBAYwALVwvhGjRoV4s8dBgECBAgQIECAAAECBAgQIECAwMAT+POf/xzivw+tW7eu4uZHjhwZbrrpprDlllvWxBk7dmx49tlnK8479dRTQ7yRvZnGr3/963DQQQeVbSkavPnNb6651ZtvvjmceeaZJfP23nvvEMMIsjj++te/Fs735ZdfDnvssUcYPHhwFtvMfZ0TVWcAACAASURBVE8vvfRSmDdvXuFXpRGDU2KAStdx1FFHhUWLFpV8ecyYMSE+z3o7li9fHiZPnlxyedL/nnzwwQeHlStXlm3hyiuvDBMnTuzt1np83WuvvRbif+NWrVpVdm387+T3vve9Hq/pgu4FBGOk9wwRjJGevcoECBDIqoBgjKyejL4IECBAgAABAgQIECBAgAABAgQIECCQksC0adNCvFGt60jykzZS2rqyBAgQIECAAAECBAgkJFD8Zsbikn7uSOgAlCFAgAABAgQIECBAgAABAgQIZEzgkksuCXPnzq3Y1c477xzuuuuu8Na3vrWurr/xjW+Eyy+/vOLcww47LMTHm2k88cQTFW/Mr/ff2q699tpw4YUXlpAccMAB4frrr88c07Jly8JnP/vZjQEqW221Vbj99tvD7rvv3tBe//jHP4YYDLH55puH7bffPgwaNKih6+dpsb/85S/hgQceCL/4xS/Cc889F97ylreEf/qnfwoXXXRR2HTTTcu2cswxx4QHH3yw5OsjRowICxYs6PW2YxjEpEmTwooVKzauEYNy9ttvv16v2dMLY7jHmjVryi6Lf3/GjRvX0+X6ND+GX5x88skV14ihJDvuuGOf1ndxqYBgjPSeEYIx0rNXmQABAlkVEIyR1ZPRFwECBAgQIECAAAECBAgQIECAAAECBFISqBSMkfQnbaS0dWUJECBAgAABAgQIEEhIQDBGQtDKECBAgAABAgQIECBAgAABAgRyIBBvtt9///0rdhqDD+JN+e95z3vq3sny5cvD5MmTK84fPnx4uP/+++teKw8TH3vssfDpT3+6pNXo9tRTT9XVfnt7e2hrayuZm8UAkV/+8pdhwoQJZXsaMmRIWLx4cSGwoRGjq+fQoUPDd77znTBs2LBGLN9va7zxxhvh6aefDi+88EJYu3Zt4VcM9Nhmm23CtttuG971rncVfo9hH/05vvCFL4Qf/OAHJSWi4aOPPtqnsq+88kq49957C+EUO+ywQzjiiCP6tF5PL95tt902BrIUX5tGMMY//vGP8OEPf7hwxl1HS0tLaG1t7en2zO9GQDBGek8PwRjp2atMgACBrAoIxsjqyeiLAAECBAgQIECAAAECBAgQIECAAAECKQlUukFNMEZKh6EsAQIECBAgQIAAgSYVqBTIF7da76dYNimLbREgQIAAAQIECBAgQIAAAQIEBqTAWWedFW666aaKe7/rrrvChz70oR65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N9/vz54Q9/+EPYb7/9wkEHHVRy2YknnhjuvffemvtpxIQY4BL3FUMoNt1008KSU6dODcuWLStb/q677gof+tCHelQ2nsvEiROrXhPrdxeIE52ifdLjjDPOCLfddltZ2Xnz5pWdV9K9NUs9wRjpnaRgjPTsVSZAgEBWBQRjZPVk9EWAAAECBAgQIECAAAECBAgQIECAAIEUBCrdmCYYI4WDUJIAAQIECBAgQIDAABCoFMwnGGMAHLwtEiBAgAABAgQIECBAgAABAgT+VyCGTDz00ENlHnfeeWfYe++9M+X0q1/9qnATftcAib40OWPGjEKoQl/HMcccEx588MGSZeLN8scdd1xdS1cKk+hNsEBdxRowqdL7GuKy3/zmN8PHPvaxHleIIRRHHXVUxevOP//8EIMoqo34+Le+9a1ua8bnTfx3z/e85z2FeS+//HIhbCIGF7z44osVr43/djpp0qSyx+K1I0eOrFpv7NixhXU7gyOqTXzmmWfCBRdcUDVg49JLLw377LNPIVih+Dl/xx13FAI3Osf69etDDNG48sore+ze2wvifxu+/vWvh2HDhoW99torrF27tmyp3/zmN2HQoEE9KhHXnDNnTtVr7rvvvhDPpevftc4L4gfOxPfXJD2+853vhHPOOaes7Ne+9rXw2c9+Nul2mrKeYIz0jlUwRnr2KhMgQCCrAoIxsnoy+iJAgAABAgQIECBAgAABAgQIECBAgEAKApXeQLJ69eoUOlGSAAECBAgQIECAAIFmFxCM0ewnbH8ECBAgQIAAAQIECBAgQIAAge4FZs6cGR544IGySUuWLAnbbbddZvjqDcX4xCc+EXbZZZdC7/HXkCFDwrve9a7w61//Ohx66KEV93PPPfeEPffcs097jcELy5YtK1mjVqBD5+R//OMf4X3ve19Z/fvvvz8MHz68T33118U//vGPw2c+85my5XsTNBJDHw488MCKARU777xziA7VAhZiIEZ0rja22mqrcOONN1YNsnjllVfCuHHjKtb+4he/GE4//fSypWNgSWtra8WSgwcPDgsXLgzx93pHDHmIAQpr1qwpuaStra0Q5BGfW8UjhlLE4Jqu4/nnnw/f//73w4IFC8KKFSvqLd+neT/60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6U1n7mUyAQDYBwRjZnMwiQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEOl5AMEbHmzc9UTBG9XuggnwL/Pd//3ekgIz1118/evfune9iVUegjQKCMdoIaDkBAgQIECBAgAABAgQIECBAgAABAgTqSUAwRj11011qReCTTz6JLbbYouTD+3379o1bb711ybV23HHHmD17dodcMwVW/Od//mebz3r99ddj4MCBLe5z6KGHFoIMjPYVSCEnI0aMKHnItddeG1tvvXVh3n333RcHHXRQyTWVmnD22WfHnnvu2art/va3v8WoUaMKYRDVHul955prrik75OPDDz+MY489tmJhJIMHD46rrroqlllmmSUk119/fcn3t5deeimWX375NjN+8MEHkT7HePbZZ9u8V9YNUjDJxIkTs04vzEsfU9PH1uZG+uaRBx54oKz9TCZAIJuAYIxsTmYRIECAAAECBAgQIECAAAECBAgQIECAAAECHS8gGKPjzZueKBij+j1QAQECBPIiIBgjL51QBwECBAgQIECAAAECBAgQIECAAAECBHIgIBgjB01QQqcTePLJJ2OPPfYoee/Ro0fHwQcfvGReetj+1FNPLbmu1IT04H4KITjqqKOKTv3zn/8cq666aqntir79V7/6VZx33nktzrnrrrtigw02aNMZFpcWSIETjz/+eNGJ6XWRQgyWW265wryPPvooNtlkk1i4cGHpA0rMGD58eMyYMSNmzpzZ4syhQ4cWwi3KHb/73e/iF7/4RUXqTGf37NkzevToEa+99lqb9pw6dWp861vfynSdFCKx3377RfrYUMlxww03xLe//e0lW06aNClOPvnkoke88sorS14Dra1l8eLFccQRR8Tdd99d1hb7779/IZglfUz4whe+EI8++mhhjxTsknWk1/Aqq6ySdXrhJ6jstttuzc7feOON4/bbb8+8l4kECGQXaPz/IA2rhg0bFum/FwYBAgQIECBAgAABAgQIECBAgAABAgQIECBAoJoCgjGqqf+/ZwvGqH4PVECAAIG8CAjGyEsn1EGAAAECBAgQIECAAAECBAgQIECAAIEcCAjGyEETlNDpBEaMGJHpQe8HH3ww1lprrSU+b7/9dvTr16/NXuPHj48ddtgh1l133aJ73XbbbYVghNaORYsWFeqdP39+s1uss846cd9997V2e+syCrz++usxcODAkrNTOMDYsWOXmpdCFFKYQltG6nMKQJkwYUIhkKWlMWjQoJg4cWJZR/3jH/9o02u04bD038KddtopNtxww0IoRsNIr92HHnoo0vtCen8sd9x8882x2WabFV326aefFh4Ev+WWW8rdvuT89LGmcQBO8r/sssuKrqtEMMZZZ50Vl19+ecn6GibsvPPOcdxxx8XXvva1ZtcsWLAgrr322jj33HNL7nnTTTfF5ptvXnJew4SHH3449t1332bnb7HFFnHjjTdm3stEAgSyCzQXjNG/f/+YMmVK9k3MJECAAAECBAgQIECAAAECBAgQIECAAAECBAi0g4BgjHZALXNLwRhlgplOgACBOhYQjFHHzXU1AgQIECBAgAABAgQIECBAgAABAgQIlCvQ9KG0OXPmlLuF+QQIlCHw97//veSD8mm7lkIj9t9//1Y9oN9QYtr33nvvjS5dusSee+4Zjz/+eIvVX3rppTFkyJAybrf01N///vdx6KGHtrh+9OjRcfDBB7d6fwuzCZx++ulx1VVXlZx85ZVXFgJTGo9nnnkmvv/975dcW2xCw75//OMfY/fdd29xau/eveOBBx4o66zbb799qeCHshb//5NTGEcK5Sg1UjDNFVdcUQj4KGekGjfeeOMWl6SgimKBIeWc1XTuNttssyTY5L333osBAwbEwoULi27Z1mCMFPAxbNiwzGVfffXV8Z3vfCfT/Cx7p1COvfbaK9N+adLdd98dhx12WLPzBw8eXHa/Mx9sIoFOLiAYo5O/AFyfAAECBAgQIECAAAECBAgQIECAAAECBAjkWEAwRvWbIxij+j1QAQECBPIiIBgjL51QBwECBAgQIECAAAECBAgQIECAAAECBHIgIBgjB01QQqcSuOSSS+Lcc88teefjjjsujjzyyM/MKxU2UWrj8ePHxy677FKYduKJJ8YNN9zQ4pKRI0fGIYccUmrLFt++xx57xJNPPtni25944on48pe/3Or9LSwtkEIQvvnNb5YMQ0g7vfjii9GtW7fPbJrCAV5++eXShzUzI4Vd3HfffbHsssvGW2+9VQhmKDZee+21WGaZZTKfNXXq1EjvK60Z3bt3j+uvvz769u1b1vJ0j8svv3xJ4ESpxT179iyE2fzbv/3bZ6bOnj07dtxxx1JbLPX2FFaz/vrrF8Jt3nnnnZg3b1489dRTMX/+/M/skwI5UjBHGuPGjYsLLrig5FltCcZINWy11VaZXm+9evWKa665phAClHV88MEHsd566xWdfswxx8TRRx+ddcuYNm1ajBgxotn5u+66a8HNIECg8gKCMSpvakcCBAgQIECAAAECBAgQIECAAAECBAgQIECgMgKCMSrj2JZdBGO0Rc9aAgQI1JeAYIz66qfbECBAgAABAgQIECBAgAABAgQIECBAoE0CgjHaxGcxgbIEFi1aFP369Wv2AfamG91///3x9a9//TP7f/zx4GXpTAAAIABJREFUx/Gtb30r0x5NF6cH9B999NHo2rVr4U0pJOP8889v8Q777bdfjBkzpqw7Nkwu9cD/FltsETfeeGOr9rYou0AKPkkBKKVGsQCArHs0d8Z5550XP/rRjwpvSq//5l7TjdelIJUvfelLpcpd8vabb745hg8fnnl+w8TNN988Lrzwwmj8zTTlbvLmm29Gut8tt9xScmnqwWGHHbbUvE8//TR23333QqhFlpFCRs4444xI7ztNR9orBZs8/PDDhRCTjz76KBYvXhwpnGabbbaJBQsWRP/+/TMFVkyfPr1k+ERL9R5//PExZcqUktfp06dPXHfddbHqqquWnNt4QpYglPQxK33syjomTZoUJ598crPT99xzzzj77LOzbmUeAQJlCAjGKAPLVAIECBAgQIAAAQIECBAgQIAAAQIECBAgQKBDBQRjdCh3s4c17cHMmTNj7NixhbnDhg1r1fcJVP9WKiBAgACB1ggIxmiNmjUECBAgQIAAAQIECBAgQIAAAQIECBCoUwHBGHXaWNfKpcBdd90VP/vZz0rWlh7av+mmm1qc95vf/CZ+8YtflNyn6YSTTjopDj300CV/XOoh8/RAfXpovDUjBQGkQIWWRgrkSA/tG+0nkMISBg0aFK+++mrJQ66//vrYcsstm5334YcfFsIV5s2bV3KfxhO6d+8eTz/9dHTr1m3JH2+66aZFQ11uvfXW6Nu3b+ZzUhDEvvvum3l+mpjm//KXv1wSEFPW4iaTk/FZZ50VV1xxRcltksVqq622ZN7tt98eRx11VMl1acIRRxwRRx99dCy//PKZ5jed9Ktf/aoQ4pFlDB06NEaNGpVl6lJz/vjHPxaCPkqN1N/JkyfHSiutVGrqUm/P6jVhwoQYPHhw5r0vvfTSOOecc5qdf/DBB8fo0aMz72UiAQLZBQRjZLcykwABAgQIECBAgAABAgQIECBAgAABAgQIEOhYAcEYHevd3GmCMarfAxUQIEAgLwKCMfLSCXUQIECAAAECBAgQIECAAAECBAgQIEAgBwKCMXLQBCV0GoEf/vCH8dRTT5W877hx42LXXXdtcd7ixYvjRz/6Uaa9Gm/ypz/9KXr06LHkj+6777446KCDWjynV69e8cgjj5Sst+mEf/zjH7HJJpsUXffcc8/FyiuvXPbeFmQXePzxx2PPPfcsuSD1+aGHHoplllmmxbmtCaBIISwpjKXx2HHHHWP27NktnpNCCoYMGVKy5oYJH3/8cWy88caxcOHCTGtSME0KlenSpUum+VknpdCJFD5RbDT9qTXpnrNmzSp5xOmnn152+EfjTRcsWBD9+/fPbNSzZ89IP22nnPHJJ5/ETjvtVLS3Dfsdc8wxkV5zX/rSlwofJ1ZYYYWiR7300ktx2WWXxc0335yppPQxdvXVV880N026+OKL48ILL2x2fgouGTFiROa9TCRAILuAYIzsVmYSIECAAAECBAgQIECAAAECBAgQIECAAAECHSsgGKNjvZs7TTBG9XugAgIECORFQDBGXjqhDgIECBAgQIAAAQIECBAgQIAAAQIECORAQDBGDpqghE4h8MILLxQeHC81unfvHs8880wsv/zyRae+/PLLMXjw4FLbLXn77rvvHhdccMFS89M53//+94vu8eKLL0a3bt0yn5MmXnXVVZEe5m9p7LDDDnHllVeWtafJ5QsccsghMX369JILTznllDjwwANLzhs+fHjmcIK02YMPPhhrrbXWUvvuv//+hT9vaaQzUoBEOWPbbbeNV199teSSoUOHxqhRo0rOa+2EUj6bb7553HTTTYXtUzDM9773vZJHpbCNLPOKbTRy5Mi47rrrSp7VeMK9994b6667buY1d911V6TQkdaMFBDyne98J1Igx+c///lIHwPTeP311+Oaa64phLZkHQMHDozJkydnnV6Yd+6558Yll1zS7Jrjjz8+jjjiiLL2M5kAgWwCgjGyOZlFgAABAgQIECBAgAABAgQIECBAgAABAgQIdLyAYIyON296omCM6vdABQQIEMiLgGCMvHRCHQQIECBAgAABAgQIECBAgAABAgQIEMiBgGCMHDRBCZ1C4IQTTogbb7yx5F3TQ9jpYews4+KLL44LL7wwy9T43e9+FxtttNFSc+fPnx+bbrpp0fU333xzbLbZZpnOSJMWLVoUW265ZcybN6/FNVdccUXsuOOOmfc0sXyBN954o9CHLOPZZ5+NVVZZpeTU9HrZaqutYuHChSXnptCWCRMmfGbeaaed1uyfN0xsTbBBlmCMfv36xW9+85tYdtllS9be2gnvv/9+bLDBBkWXv/TSS4XQm5NPPjkmTZpUdO5JJ50Uhx56aGvLKaybMWNG/OQnPyl7jxQgkoJEsoz0Pp+CLbKEk2TZry1zkuk222xT1hYpxCeF+TQ3Tj311DjggAPK2s9kAgSyCQjGyOZkFgECBAgQIECAAAECBAgQIECAAAECBAgQINDxAoIxOt686YmCMarfAxUQIEAgLwKCMfLSCXUQIECAAAECBAgQIECAAAECBAgQIEAgBwKCMXLQBCXUvcC7774bffv2zXTPRx55JHr16pVp7kcffRS77LJLzJ49u+j8zTffPG666aZm5/zHf/xH0aCDch8MnzlzZqSPK8XGiy++GN26dct0R5NaJ3DOOefEpZdeWnJx6tW5555bcl7DhBSwcuSRR5acf/311zcbzHHdddfFyJEji65PAQvlBFhkCcZoqZ6SFylzwj777BPpfbilceuttxY+FpSqeZ111om77747lltuuTIr+L/pKcBku+22KxpS09LmKUhk2rRpmc5Odzr66KMzzW3PSYMGDYqJEyeWfUSxkJIzzzwz9t5777L3tIAAgdICgjFKG5lBgAABAgQIECBAgAABAgQIECBAgAABAgQIVEdAMEZ13Buf2rQH6W0N34vSv3//mDJlSvWLVAEBAgQIdIiAYIwOYXYIAQIECBAgQIAAAQIECBAgQIAAAQIEakNAMEZt9EmVtS1w+eWXx1lnnVXyEq15sPutt96KnXfeOebPn9/s/t27d4+bb7451ltvvWbfftBBB8V9993XYm277rprjBs3rmTtDRNGjx4dkydPbnH+4MGDY8KECZn3M7F8gRSI8M1vfrNo4EnDrrfffntsvPHGZR1y/vnnx/jx41tcs//++0cKVOnSpctn5jz33HPxve99r+h5f/jDH2LttdfOXFOpkIn0PpDO7dq1a+Y9Wzvxhz/8YTz11FMtLr/oootim222iU022aToEel9drPNNmttGYV1p512Wpve1/785z/HqquuWrKGUv4lN6jAhNTj9HFsjTXWKHu3E044IW688cZm140aNSqGDh1a9p4WECBQWkAwRmkjMwgQIECAAAECBAgQIECAAAECBAgQIECAAIHqCAjGqI5741MFY1S/ByogQIBAXgQEY+SlE+ogQIAAAQIECBAgQIAAAQIECBAgQIBADgQEY+SgCUqoa4G33347+vXrl+mOEydOjBSOUe54/vnnCz8ZIwUiNB49evSI3/72t9G7d+8Wt5w6dWocd9xxLb69Z8+eMXPmzEwlLVq0KDbaaKOigQzprCOPPDLTfia1TiCFsKQwllKjT58+ceedd5aa9pm3f/LJJ3H88cfHtGnTPvO2n/3sZ/GLX/yi2VCMNDmt3XzzzVsMcklzUnjED37wg8x1lQpm2GqrreK6667LvF9rJ7733nuF13+xceWVV8bKK6+85CfZNDd3iy22aDGoIWttTz75ZOyxxx5Zpzc7LwWglNrjhRdeiJ122qnoOSm0Io2mH5/aVFyTxbfeemv07du3VVueeeaZccUVVzS7Nn2sKvbxsVUHWkSAQEFAMIYXAgECBAgQIECAAAECBAgQIECAAAECBAgQIJBXAcEY1e+MYIzq90AFBAgQyIuAYIy8dEIdBAgQIECAAAECBAgQIECAAAECBAgQyIGAYIwcNEEJdS1wyCGHxPTp00veMQVQPProo9G1a9eSc5ub8Prrr8dPf/rTePXVV2P99deP7373u7HXXnvF6quvXnS/d955pxBUUGykh+y/9KUvlazr8ccfjz333LPovDPOOCP22WefknuZ0DqBWbNmxZAhQzItzhJ80NJGn376afzqV7+KtEcKYEmvoZ/85CeZgl1OO+20mDBhQos17r///pHmZB2lgjEGDx5c9Lys55Sal0JGDj/88KLT7rrrrkjvc+mOLY1092JvL1XHK6+8ErvsskubgyiyBIqce+65cckllxQtafz48dG/f/9IoSlPPfVUqfLLensK/bn00ksLH/NaO0aMGNFsyEvaL30MTUEzBgEClRcQjFF5UzsSIECAAAECBAgQIECAAAECBAgQIECAAAEClREQjFEZx7bsIhijLXrWEiBAoL4EBGPUVz/dhgABAgQIECBAgAABAgQIECBAgAABAm0SEIzRJj6LCRQVuOmmm+KYY47JpHTiiSfGYYcdlmluS5MWLVpUeFO54RrpIfpnn322xbMvvPDC+OEPf1iytmnTpkV6yLzYSA/Sp487RuUFPvjgg9hpp50K4SilRvfu3ePpp5+Obt26lZpa9O3pzHL3ePDBB4sGP6SQmBkzZkSXLl0y1VYqGGPgwIExefLkTHu1dlIW+xQgkoIh7r333kiBOS2N66+/PrbccstWlfLXv/61EIoxf/78kusnTpxYeH8tNrdYKM4nn3xSCEQptr5fv34xderUQi8/+uijuO666wqBKlnqK3WBFLAzatSosl9/Tfc99thj47e//W2zx+2www5x5ZVXlirF2wkQaIVAc8EYaZs5c+a0YjdLCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKVExCMUTnL1u4kGKO1ctYRIECg/gQEY9RfT92IAAECBAgQIECAAAECBAgQIECAAAECrRYQjNFqOgsJFBVI4QTpgf2sI4UUrLbaalmnV3TemWeeGVdccUWLe2Z9OHzChAlx2mmnFa0tnbX33ntXtH6b/a9ACgm49tprM3EMHTq0ML8a45///GdsvPHGRY/+/e9/H+uvv36m8koFYwwaNChSCER7jpNPPjkmTZpU9IiG96Pbb789jjrqqBbn3nXXXbHBBhuUXe4777wTu+22W8ydO7fk2vQ62XrrreP000+Pq666qsX5p556ahxwwAHNvn3WrFkxZMiQsvv44YcfRgoNGj9+fMybN69krU0n9O7dO37xi1/EjjvuWPba5hakcJAU6tPcSMEfqVaDAIHKCwjGqLypHQkQIECAAAECBAgQIECAAAECBAgQIECAAIHKCAjGqIxjW3YRjNEWPWsJECBQXwKCMeqrn25DgAABAgQIECBAgAABAgQIECBAgACBNgkIxmgTn8UEmhVYsGBB7LrrrpHCMbKMPffcM84+++wsU9tlzt133x2HHXZY0b1ffPHF6NatW9E5F110UYwdO7bonDFjxsR+++3XLvfozJvecMMNceKJJ2YmePTRR+OrX/1q5vmVnlgqzCKFFRQLj2hcT6m9evXqFffcc0/J129r7vjJJ5/EhRdeWAh5KDUawj5SCEO6X0vjscceizXXXLPUdku9/b333ov03/PZs2eXXJdeJw3v788//3zsvPPOLa7p06dP3Hnnnc2+Pf354Ycf3uLaLbbYIm688cYW3/7xxx/HHXfcEenjz/Tp01uc17Nnz9hoo40KYSFbbrllbLrpptGlS5eS98w6oVgwRjp75syZWbcyjwCBMgQEY5SBZSoBAgQIECBAgAABAgQIECBAgAABAgQIECDQoQKCMTqUu9nDBGNUvwcqIECAQF4EBGPkpRPqIECAAAECBAgQIECAAAECBAgQIECAQA4EBGPkoAlKqCuBFIoxdOjQsh6mfuCBB6J3795Vc3jrrbdiwIABRc+fOHFiDBo0qOic0047LSZMmFB0zsCBA+PSSy+NFVdcsWr3rbeD77rrrvjZz36W+Vq77bZbyQCTzJu1cmIKZ0hhHi2NYoEMTddked3tv//+keZVcqT39XSPFO5Qapxxxhmxzz77FKaVCsa49tprY+utty615ZK3v/DCC3HkkUdmCuL57ne/G5dddtlSwRKlgkVa+vh0+eWXx1lnndVinSnsJ4X+ZBkpJOOVV16Jd955J+bPnx+f+9zn4mtf+1qstdZascIKK2TZotVzjj/++JgyZUqL61977bVYZpllWr2/hQQINC8gGMMrgwABAgQIECBAgAABAgQIECBAgAABAgQIEMirgGCM6nem8Q9mGTZsWOF7WlJf0ujfv3/Rr/FWv3oVECBAgEAlBQRjVFLTXgQIECBAgAABAgQIECBAgAABAgQIEKhxAcEYNd5A5edOYJdddolnn302c11DhgwpBEVUe2y66aaFB9JbGnvttVfRh+DTutGjR8fkyZNLXqVHjx4xfPjw2H333aNbt24l57d1wgcffLDkgfs111wzVl999bZumZv1Dz74YKTQh3LG9OnTY7311itnScXnlgqHSAfOmDEj1lhjjZJnz549O3bccceS88aNGxe77rpryXmlJixatCimTp0ap59+eixcuLDU9EhhFClEomHcc889hfCclsYee+wR559/fsl9Ux0p5CLL3LRZz549I/V+5ZVXXmrvX//613HKKae0eN5RRx0VI0aM+MzbR40aFSnEo6WRJUyn5CU7YEKpj1vPPPNMfOELX+iAShxBoHMJCMboXP12WwIECBAgQIAAAQIECBAgQIAAAQIECBAgUEsCgjGq3y3BGNXvgQoIECCQFwHBGHnphDoIECBAgAABAgQIECBAgAABAgQIECCQAwHBGDloghLqRiA9qP71r3+9rPvccccdseGGG5a1pj0m//znP4/bbrutxa27d+8ezz//fCy77LItzkkP16eH7LOOtOcPfvCDWH/99WPdddeNtddeu+QD6B999FH8v//3/5b8WrBgQTT8eu+99yL9+tvf/hZvv/12vPXWW4VfTcMLevfuHT/96U8LP01k+eWXz1puLuelYISzzz47c22DBw+OCRMmZJ7fXhNfeeWV2G677Ypuf+aZZ8bee++dqYQUMDNr1qySc8vZs/Fmn3zySTz33HOFYIlbbrkl5s2bV/KsNKG5MIqnnnoqfvjDHxZdf/zxx8cRRxzR4pxXX3010k/FKSeE5/bbb4+NN974M3u+++670bdv36Lv+08//fRnQmz222+/eOihh1pcl8I0UqhG3seYMWPi6quvbrHMW2+9tahP3u+nPgJ5FRCMkdfOqIsAAQIECBAgQIAAAQIECBAgQIAAAQIECBAQjFH914BgjOr3QAUECBDIi4BgjLx0Qh0ECBAgQIAAAQIECBAgQIAAAQIECBDIgYBgjBw0QQl1I5BCGAYMGJD5PltttVVcd911mee358RUx8iRI4seUeoB8bFjx0b65oS2jh49ehQCMlZeeeXCVinsIj28P3/+/LZuvdT6FFowevTo2GmnnaJLly4V3bujNjvxxBPjhhtuyHzczTffHJtttlnm+e01MQVN9OnT5zOhJY3PGzhwYEyePDlTCSn0IWsIQ79+/WKPPfaIbbfdNlZfffUW93///ffjxRdfjN///veR3Mp9/aXgl2nTpsUGG2yw1Bl/+ctfYtCgQSXvlcIqDj/88EK/0vvDp59+GmntnXfeGel9rZwxfvz42GWXXVpcUioY59xzzy0EyTQe++yzTzzyyCMt7pnqTx8z8j4uuOCCGDduXItlnnrqqXHAAQfk/RrqI1BzAoIxaq5lCiZAgAABAgQIECBAgAABAgQIECBAgAABAp1GQDBG9VstGKP6PVABAQIE8iIgGCMvnVAHAQIECBAgQIAAAQIECBAgQIAAAQIEciDw7//+70tVMWfOnBxUpQQCtSnw3//93/Gtb30rc/F5CSlIBb/55puxxRZbFK39yCOPjOOOO67FOY8++mjsvffeme+fl4nbbLNNnHfeefHFL34xLyVlrmPUqFFx7bXXZpqfpyCWVPAJJ5wQN954Y9Han3/++VhppZVK3m/RokWFoIu5c+eWnNt4Qgrn+MpXvhKrrLJKLLvsspHeh9944414+eWXy9qn6eR11lknJk2aVNi76UhBLxtttFGb9i9n8ZgxY2K//fYruuSFF14oBMS0NNJ97r333qUCZLL0L4WKrL/++uWU2+Fzp0yZEscff3yL5+68885xySWXdHhdDiRQ7wKCMeq9w+5HgAABAgQIECBAgAABAgQIECBAgAABAgRqV0AwRvV7Jxij+j1QAQECBPIiIBgjL51QBwECBAgQIECAAAECBAgQIECAAAECBHIgIBgjB01QQl0JbLrppjF//vySd0phDOnB+TyNIUOGxKxZs1osqXfv3vHAAw+0+PaPPvoodthhh3j11VfzdK1MtfTo0SOmTp0aa6+9dqb5eZlU6qH+xnXeeuut0bdv37yUHg8++GDsv//+Reu59NJLI70us4zbb789jjrqqCxT23XOwIEDC0EKn//851s8p9T7WqUKvOKKK2LHHXfMtN3hhx8ed955Z4tzb7jhhvj2t7+95O3pjueee27Rvbfffvu46qqrMp1frUmPPfZY7LXXXi0enz42PP3000uFglSrVucSqCcBwRj11E13IUCAAAECBAgQIECAAAECBAgQIECAAAEC9SUgGKP6/WwajDF8+PBo+B63/v37R/peCYMAAQIEOoeAYIzO0We3JECAAAECBAgQIECAAAECBAgQIECAQCYBwRiZm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IAAAQIECBAgQIAAAQIE2kNAMEZ7qJa3p2CM8rzMJkCAQD0LCMao5+66GwECBAgQIECAAAECBAgQIECAAAECBMoUEIxRJpjpBDIIfPrpp3HooYfG9OnTl5rdu3fv+PWvfx1N3+8ybNlhUyZNmhQnn3xy0fNOP/30kmEGaYM777wzjjvuuFi4cGGH1d/Wg55++ulWhwq09ey2rH/uuefie9/73me2OP744+Pwww+PLl26tGX7dlu7aNGi2GijjYq+Rnr27FkIY+nWrVtZdTzzzDNx4403xpQpU8paV2pyej9OATKDBw+OPn36tMl23LhxccEFF5Q6MtPbUxjNgQceWDS0JstGKWBlxx13/ExPUqjPCy+8sNR9//KXv8SgQYOybBsDBw6MK664ouw+Ztq8jZPefvvt6NevX9Fdhg4dGqNGjWrjSZYTINAgIBjDa4EAAQIECBAgQIAAAQIECBAgQIAAAQIECBDIq4BgjOp3RjBG9XugAgIECORFQDBGXjqhDgIECBAgQIAAAQIECBAgQIAAAQIECORAQDBGDpqghLoUSGEQp5xySkybNi169eoVu+66axx22GGx4oor5vq+b731VgwYMKBojekB+UceeSR69OhR8i5/+9vf4pZbbin8mj17dsn51ZyQwg7Gjx9fzRLadPajjz4aP//5z2P+/Pmx1VZbxVFHHRXf+ta32rRnRyw+8cQT44Ybbih61LBhw2L48OGtKueDDz6IP//5z/HEE0/EY489Fk8++WTZ+2yzzTax5ZZbxrbbbhtrr7122euLLcgSRlNs/Q477BAnnXRSfO1rX6tYXTNnziwEqqTXUsP42c9+FieccMJnzhgxYkTh41yWsfnmm8cll1wSX/7yl7NMb/Wc//mf/4l58+ZFCrz45z//GQsWLIiPPvqo8H6x1lprNbvv1KlTC0E+LY2DDz44Ro8e3eqaLCRAYGmBloIxUphR//79cREgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEqiYgGKNq9EsOFoxR/R6ogAABAnkREIyRl06ogwABAgQIECBAgAABAgQIECBAgAABAjkQEIyRgyaLIG/pAAAgAElEQVQogUDOBL7//e/HM888U7SqPffcM84+++yy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AECBAgQIECAQLUEBGNUS/7/zk1fO0p9SCN97Sh9Danx15fmzJlT/SJVQIAAAQIdIiAYo0OYHUKAAAECBAgQIECAAAECBAgQIECAAIHaEGgajOFhtNromyoJtLfA22+/HUOHDo1nn322xaPSg+yTJk1q71Ls30kErrvuuhg5cmTR2956663Rt2/fTiJSW9dcvHhxnHDCCTF16tQ2Fd6jR4/44he/GJ/73OeiW7du8a9//Svmz58fc+fObdO+DYsFY1SE0SYE2iwgGKPNhDYgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIE2klAMEY7wZaxrWCMMrBMJUCAQJ0LCMao8wa7HgECBAgQIECAAAECBAgQIECAAAECBMoREIxRjpa5BDqXQHogffTo0YWfvNHcOP/882OPPfboXChu264CTz31VBxyyCGFIISmo1evXvGHP/yhEJhg5FMghWOceOKJLX7MyEPVt912W2yyySZ5KEUNBDq1gGCMTt1+lydAgAABAgQIECBAgAABAgQIECBAgAABArkWEIxR/fYIxqh+D1RAgACBvAgIxshLJ9RBgAABAgQIECBAgAABAgQIECBAgACBHAgIxshBE5RAIOcC9957byEgY968eUsqHTx4cFx99dXRpUuXnFevvFoTePfdd+Pss8/+TLiCQIPa6GQKxxg3blxcdNFFuSt45MiRheAVgwCB6gsIxqh+D1RAgAABAgQIECBAgAABAgQIECBAgAABAgQINC8gGKP6rwzBGNXvgQoIECCQFwHBGHnphDoIECBAgAABAgQIECBAgAABAgQIECCQAwHBGDloghII1IDAp59+Gn//+99j/vz58bnPfS6+9KUvRffu3WugciXWqsCHH34Yb731VixatChWXHHFWGONNWr1Kp2y7hdeeCGOPfbYmD17dtXv36NHjzj99NNjp512qnotCiBA4H8FBGN4JRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQJ5FRCMUf3OCMaofg9UQIAAgbwICMbISyfUQYAAAQIECBAgQIAAAQIECBAgQIAAgRwICMbIQROUQIAAAQIE6lDg448/jmuuuSYuvvjiWLhwYYffsGfPnvGTn/wkDjzwwFhppZU6/HwHEiDQsoBgDK8OAgQIECBAgAABAgQIECBAgAABAgQIECBAIK8CgjGq3xnBGNXvgQoIECCQFwHBGHnphDoIECBAgAABAgQIECBAgAABAgQIECCQAwHBGDloghIIECBAgEAdC/zzn/+MK664Ii699NJ2veX6668f2267bfTp0yd69+4d3/jGN2KZZZZp1zNtToBA6wQEY7TOzSoCBAgQIECAAAECBAgQIECAAAECBAgQIECg/QUEY7S/cakTmgvGaNqX/v37l9rG2wkQIECgDgQEY9RBE12BAAECBAgQIECAAAECBAgQIECAAAEClRIQjFEpSfsQIECAAAECxQTmz58fd955Z9xwww0xe/bsNmP16NEjBg0aFFtvvXUMGDAgVl999TbvaQMCBDpGQDBGxzg7hQABAgQIECBAgAABAgQIECBAgAABAgQIEChfQDBG+WaVXiEYo9Ki9iNAgEDtCgjGqN3eqZwAAQIECBAgQIAAAQIECBAgQIAAAQIVFxCMUXFSGxIgQIAAAQIlBP7rv/4r/vjHP8YzzzwTTz75ZMydO7ekWZ8+fWLTTTeNDTfcMDbeeONYd911o0uXLiXXmUCAQP4EBGPkrycqIkCAAAECBAgQIECAAAECBAgQIECAAAECBP5XQDBG9V8JgjGq3wMVECBAIC8CgjHy0gl1ECBAgAABAgQIECBAgAABAgQIECBAIAcCgjFy0AQlECBAgACBTi6wePHieP/99+O9996LhQsXxrLLLhvLLLNMrLjiirHKKqvEv/3bv3VyIdcnUF8Cjf8fZPjw4TF27NjCBYcNGxbp9wYBAgQIECBAgAABAgQIECBAgAABAgQIECBAoFoCgjGqJf9/5wrGqH4PVECAAIG8CAjGyEsn1EGAAAECBAgQIECAAAECBAgQIECAAIEcCAjGyEETlECAAAECBAgQIECgEwkIxuhEzXZVAgQIECBAgAABAgQIECBAgAABAgQIECBQYwKCMarfMMEY1e+BCggQIJAXAcEYeemEOggQIECAAAECBAgQIECAAAECBAgQIJADAcEYOWiCEggQIECAAAECBAh0IgHBGJ2o2a5KgAABAgQIECBAgAABAgQIECBAgAABAgRqTEAwRvUbJhij+j1QAQECBPIiIBgjL51QBwECBAgQIECAAAECBAgQIECAAAECBHIgIBgjB01QAgECBAgQIECAAIFOJCAYoxM121UJECBAgAABAgQIECBAgAABAgQIECBAgECNCQjGyEfDGn89ac6cOdG0L/37989HoaogQIAAgXYVEIzRrrw2J0CAAAECBAgQIECAAAECBAgQIECAQG0JCMaorX6plgABAgQIECBAgECtCwjGqPUOqp8AAQIECBAgQIAAAQIECBAgQIAAAQIECNSvgGCMfPRWMEY++qAKAgQIVFtAMEa1O+B8AgQIECBAgAABAgQIECBAgAABAgQI5EhAMEaOmqEUAgQIECBAgAABAp1AQDBGJ2iyKxIgQIAAAQIECBAgQIAAAQIECBAgQIAAgRoVEIyRj8YJxshHH1RBgACBagsIxqh2B5xPgAABAgQIECBAgAABAgQIECBAgACBHAkIxshRM5RCgAABAgQIECBAoBMICMboBE12RQIECBAgQIAAAQIECBAgQIAAAQIECBAgUKMCgjHy0TjBGPnogyoIECBQbQHBGNXugPMJECBAgAABAgQIECBAgAABAgQIECCQIwHBGDlqhlIIECBAgAABAgQIdAIBwRidoMmuSIAAAQIECBAgQIAAAQIECBAgQIAAAQIEalRAMEY+GicYIx99UAUBAgSqLSAYo9odcD4BAgQIECBAgAABAgQIECBAgAABAgRyJCAYI0fNUAoBAgQIECBAgACBTiAgGKMTNNkVCRAgQIAAAQIECBAgQIAAAQIECBAgQIBAjQoIxshH4wRj5KMPqiBAgEC1BQRjVLsDzidAgAABAgQIECBAgAABAgQIECBAgECOBARj5KgZSiFAgAABAgQIECDQCQQEY3SCJrsiAQIECBAgQIAAAQIECBAgQIAAAQIECBCoUQHBGPloXNNgjIsuuijGjh1bKG7YsGExfPjwfBSqCgIECBBoVwHBGO3Ka3MCBAgQIECAAAECBAgQIECAAAECBAjUloBgjNrql2oJECBAgAABAgQI1LqAYIxa76D6CRAgQIAAAQIECBAgQIAAAQIECBAgQIBA/QoIxshHbwVj5KMPqiBAgEC1BQRjVLsDzidAgAABAgQIECBAgAABAgQIECBAgECOBARj5KgZSiFAgAABAgQ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AECBAgQIFCDAk2DMYYNGxbDhw+vwZsomQABAgQIECBAgACBWhAQjFELXVIjAQIECBAgQIAAAQIECBAgQIAAAQIECBDonAKCMfLRd8EY+eiDKggQIFBtAcEY1e6A8wkQIECAAAECBAgQIECAAAECBAgQIJAjAcEYOWqGUggQIECAAAECBAjUuUD6iWrpGxnTSD9RLYXyNf59+klrBgECBAgQIECAAAECBAgQIECAAAECBAgQIECgWgKCMaolv/S5gjHy0QdVECBAoNoCgjGq3QHnEyBAgAABAgQIECBAgAABAgQIECBAIEcCgjFy1AylECBAgAABAgQIEKhzAcEYdd5g1yNAgAABAgQIECBAgAABAgQIECBAgAABAjUuIBgjHw0UjJGPPqiCAAEC1RYQjFHtDjifAAECBAgQIECAAAECBAgQIECAAAECORIQjJGjZiiFAAECBAgQIECAQJ0LCMao8wa7HgECBAgQIECAAAECBAgQIECAAAECBAgQqHEBwRj5aKBgjHz0QRUECBCotoBgjGp3wPkECBAgQIAAAQIECBAgQIAAAQIECBDIkYBgjBw1QykECBAgQIAAAQIE6lxAMEadN9j1CBAgQIAAAQIECBAgQIAAAQIECBAgQIBAjQsIxshHA5sGY6Sq0p+l0b9//5gyZUo+ClUFAQIECLSrgGCMduW1OQECBAgQIECAAAECBAgQIECAAAECBGpLQDBGbfVLtQQIECBAgAABAgRqWUAwRi13T+0ECBAgQIAAAQIECBAgQIAAAQIECBAgQKD+BQRj5KPHgjHy0QdVECBAoNoCgjGq3QHnEyBAgAABAgQIECBAgAABAgQIECBAIEcCgjFy1AylECBAgAABAgQIEKhzAcEYdd5g1yNAgAABAgQIECBAgAABAgQIECBAgAABAjUuIBgjHw0UjJGPPqiCAAEC1RYQjFHtDjifAAECBAgQIECAAAECBAgQIECAAAECORIQjJGjZiiFAAECBAgQIECAQJ0LCMao8wa7HgECBAgQIECAAAECBAgQIECAAAECBAgQqHEBwRj5aKBgjHz0QRUECBCotoBgjGp3wPkECBAgQIAAAQIECBAgQIAAAQIECBDIkYBgjBw1QykECBAgQIAAAQIE6lxAMEadN9j1CBAgQIAAAQIECBAgQIAAAQIECBAgQIBAjQsIxshHA5v2YcCAAZHCMtLo379/TJkyJR+FqoIAAQIE2lVAMEa78tqcAAECBAgQIECAAAECBAgQIECAAAECtSUgGKO2+qVaAgQIECBAgAABArUsIBijlrundgIECBAgQIAAAQIECBAgQIAAAQIECBAgUP8CgjHy0WPBGPnogyoIECBQbQHBGNXugPMJECBAgAABAgQIECBAgAABAgQIECCQIwHBGDlqhlIIECBAgAABAgQI1LlA02CM9NO8Gv8/yZw5c+pcwPUIECBAgAABAgQIECBAgAABAgQIECBAgACBPAsIxshHdwRj5KMPqiBAgEC1BQRjVLsDzidAgAABAgQIECBAgAABAgQIECBAgECOBARj5KgZSiFAgAABAgQIECBQ5wKCMeq8wa5HgAABAgQIECBAgAABAgQIECBAgAABAgRqXEAwRj4aKBgjH31QBQECBKotIBij2h1wPgECBAgQIECAAAECBAgQIECAAAECBHIkIBgjR81QCgECBAgQIECAAIE6FxCMUecNdj0CBAgQIECAAAECBAgQIECAAAECBAgQIFDjAoIx8tFAwRj56IMqCBAgUG0BwRjV7oDzCRAgQIAAAQIECBAgQIAAAQIECBAgkCMBwRg5aoZSCBAgQIAAAQIECNS5gGCMOm+w6xEgQIAAAQIECBAgQIAAAQIECBAgQIAAgRoXEIyRjwYKxshHH1RBgACBagsIxqh2B5xPgAABAgQIECBAgAABAgQIECBAgACBHAkIxshRM5RCgAABAgQIECBAoM4FBGPUeYNdjwABAgQIECBAgAABAgQIECBAgAABAgQI1LiAYIx8NFAwRj76oAoCBAhUW0AwRrU74HwCBAgQIECAAAECBAgQIECAAAECBAjkSEAwRo6aoRQCBAgQIECAAAECdS4gGKPOG+x6BAgQIECAAAECBAgQIECAAAECBAgQIECgxgUEY+SjgYIx8tEHVRAgQKDaAoIxqt0B5xMgQIAAAQIECBAgQIAAAQIECBAgQCBHAoIxctQMpRAgQIAAAQIECBCocwHBGHXeYNcjQIAAAQIECBAgQIAAAQIECBAgQIAAAQ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NSHgGCM/PRRMEZ+eqESAgQIVEtAMEa15J1LgAABAgQI5EqgtYEYDQ9zpgc7DQIECBAgQIAAgQgBGV4FBGpfQDBG7ffQDQgQIECAAAECBAjUioBgjFrplDoJECBAgAABAgQIECBAgAABAgQIECBAgEDnFBCMkZ++C8bITy9UQoAAgWoJCMaolrxzCRAgQIAAgVwItCYQo3///jFgwIAQhpGLFiqCAAECBAgQyLHAj3/840JQRqmRPr9KgWPpnwYBAtUXEIxR/R6ogAABAgQiFi5cGI8++mg8//zz8be//S3eeeedwj/nz58fPXr0iK9+9avxla98Jb785S8Xfq2xxhqx0UYbxXLLLYePAAECBGpIQDBGDTVLqQQIECBAgAABAgQIECBAgAABAgQIECBAoBMKCMbIT9MFY+SnFyohQIBAtQQEY1RL3rkECBAgQIBAVQVaE4jR8LCmBzar2jqHEyBAgAABAjUmkIIx0udeWQIyUvBY+pzLIECgugKCMarr73QCBAh0doH7778/fvOb38T06dPLpujevXvsscce8f3vfz822WST6NKlS9l7WECAAAECHSvQXDBGc3/WsVU5jQABAgQIECBAgAABAgQIECBAgAABAgQIECDwvwKCMfLzShCMkZ9eqIQAAQLVEhCMUS155xIgQIAAAQJVEyg3FCM9nJke0jQIECBAgAABAgRaL5A1ICOFkDUEkrX+NCsJEGiLgGCMtuhZS4AAgdoR+PTTT+O9996LxYsXxyqrrBLLLrts1YufPHlyjB49uiJ1rLPOOnHOOefEZpttVpH9bEKAAAEC7SMgGKN9XO1KgAABAgQIECBAgAABAgQIECBAgAABAgQIVEZAMEZlHCuxi2CMSijagwABArUtIBijtvunegIECBAgQKAMAYEYZWCZSoAAAQIECBBoJ4HGXyQqdkQKJksBGQYBAh0vIBij482dSIAAgfYWeOONN+Lhhx+OJ554It58883Cr3nz5i11bI8ePWLNNdeML3/5y7HGGmvEpptuGt/+9rcj/XlHjMsuuyzOPvvsih910EEHxYgRI2KFFVao+N42JECAAIG2CwjGaLuhHQgQIECAAAECBAgQIECAAAECBAgQIECAAIH2ExCM0X625e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SHw8ssvx6hRo5b8VJT2OKPYnr17947x48dHnz59yjr66quvjjFjxpS1ptKTTznllDjwwAMrva39CBAgQKAMAcEYZWCZSoAAAQIECBAgQIAAAQIECBAgQIAAAQIECHS4gGCMDidv8UDBGPnphUoIECBQLQHBGNWSdy4BAgQIECDQLgKN/0e3pQOGDx8e6aeNGwQIECBAgAABAvkTmDlzZqTP6YoN4Rj565uK6ktAMEZ99dNtCBCoX4F//etfhUCK9CsP49RTT40DDjggUynz58+PrbbaKhYuXJhpfvfu3WPPPfeMQYMGxWqrrRYrr7xyfO5zn4tPPvkkFi9eHO+9917Mnj07nn766Zg0aVKmPRsmjRw5Mg455JCy1phMgAABApUTEIxROUs7ESBAgAABAgQIECBAgAABAgQIECBAgAABApUXEIxRedPW7igYo7Vy1hEgQKB+BARj1E8v3YQAAQIECHR6AaEYnf4lAIAAAQIECBCoI4FSn9sJx6ijZrtK7gQEY+SuJQoiQIDAZwReeOGFOProo+Pll1+uiE4Knlh77bXjr3/9a6TQitaOrCETF198cVx44YWZjhk9enQhcKNr166Z5r///vtx0003xTnnnJMpeGPnnXeOSy65JNPeJhEgQIBA5QUEY1Te1I4ECBAgQIAAAQIECBAgQIAAAQIECBAgQIBA5QQEY1TOsq07CcZoq6D1BAgQqH0BwRi130M3IECAAAECBCJi7Nixkf7CoaWRHpwcPnx4pH8aBAgQIECAAAECtSHQ+AtKzVUsHKM2+qjK2hMQjFF7PVMxAQKdT2DIkCExa9asNl28X79+hcCJDTfcML761a9Gly5dCvt98MEH8cQTT8Qdd9wR06ZNK/uM0047Lfbff/+i67LWv9tuuxX+3q8147333ovx48fHVVddVXT5oEGDYuLEia05whoCBAgQqICAYIwKINqCAIFOJTBz5syK3nfGjBkV3a9hs0rX2S5FNrNprdbdUT6d/fst6uH+AwYM6KiXS4edUw996TAsBxEgQIAAAQIECBAgQIBAqwQEY7SKrV0WCcZoF1abEiBAoKYEBGPUVLsUS4AAAQIECDQnUCoUIwViDBs2DB4BAgQIECBAgEANCgjHqMGmKbnmBQRj1HwLXYAAgToXmDdvXpvDX4855pg46qijYplllimqlUIybrjhhrjgggti4cKFmWXPOuus2GuvvZqd//bbb0cK5Sg1evXqFXfffXesuOKKpaYWffsrr7wSY8aMiQcffLDZeQMHDozJkye36QyLCRAgQKD1AoIxWm9nJQEC+RNoGqrQXOhE0zmCGPLXRxURIECAAIEsAs2FsjT9s6ZhNIJcssiaQ4AAAQIECBAgQCB/AoIx8tMTwRj56YVKCBAgUC0BwRjVkncuAQIECBAgUBEBoRgVYbQJAQIECBAgQCDXAqXCMVIIWgpDMwgQqIyAYIzKONqFAAEC7SXw6quvxrbbbtvq7VNIxH777VfW+hSKcf3110f6vCxrQMY999wT3/jGNz5zzrRp02LEiBElz7/ttttik002KTkv64Rnn302HnnkkfjLX/4SL730UsyaNSu6d+8exx57bBx00EFZtzGPAAECBCosIBijwqC2I0CgXQUaQiwaAi8afi/col3ZbU6AAAECBOpOoCEgo/HXN4Vm1F2bXYgAAQIECBAgQKCOBARj5KeZgjHy0wuVECBAoFoCgjGqJe9cAgQIECBAoM0CQjHaTGgDAgQIECBAgEDNCDT+gkZzRQvHqJlWKrQGBARj1ECTlEiAQKcWmDt3bmy11VZlG/To0SPGjx8f3/72t8te27AghWJMnDgxzjvvvJJ7DBw4MCZPnvyZeaecckr8+te/Lrp+1113jXHjxpU8wwQCBAgQqH0BwRi130M3IFBvAinkQvBFvXXVfQgQIECAQG0INIRjpH8OGDCgULTAjNronSoJECBAgAABAgTqW0AwRn76KxgjP71QCQECBKolIBijWvLOJUCAAAECBNokIBSjTXwWEyBAgAABAgRqUqBpOEb6RrDGP41xypQpvjmsJjur6LwJCMbIW0fUQ4AAgaUFFixYEBtuuGFZLH379i0EWqy66qplrWtp8vTp0+OQQw4pudekSZNim222WWreT3/607j//vuLrr3vvvtinXXWKbm/CQQIECBQ+wKCMWq/h25AoNYF0ted00h/z9j47xorda+Gh1kbHm5t2LfxQ66teeC1PWptqK099m4IG6mUa9Z92uMuWc82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p5FjESBAgAABAgQIECBAgAABAgQIECAwrMC2BZYWVg47Lo5OgAABAgQIECgKCMZoNicEYzRzsxcBAgQIECBAgAABAgQIECCwMAGhGAsb8JF0t8twjOKb3GNBT/7PsrCMkVBoBgECBAgQIDAxgeJ5TL75sVA3Fu1mwRjx+wjKUAgQIECAwJgF8qFP8TkW35vzpatQjKphGNGWYpvG7KltBAgQIECAAAECBAgQIECAAAECBAi0L7A+OtpY6eHVVfsHUyMBAgQIECBAgEBjgW3nbVmFzt820wrGaDzl7EiAAAECBAgQIECAAAECBAgsRaBJKIaU/aXMju772WU4Rr7uLAgjv9AnFqh6w2z3Y+wIBAgQIEBgjgLFEK58H+O848033xSMMceB1ycCBAjMVKAYehHhkvnSdihGlTCMOP6mgI6ZDoFuESBAgAABAgQIECBAgAABAgQIECBQIvD08eMUbx4vllvHxymeZVMIECBAgAABAgTGIbDtvC1rnfO37eMkGGMcc1grCBAgQIAAAQIECBAgQIAAgREKxEWn64uLFD+rloPVKt1erapubjsClQS6CscoLliNRaqvvPJKyhbgZGEZlRppIwIECBAgQIBATuDRo0fPgy+KMM45TBUCBAgQmJrArhDJYihGBExG0GTdUjUMI+oViFFX1/YECBAgQIAAAQIECBAgQIAAAQIE5i8QoRibnnPzgqf5j70eEiBAgAABAtMSEIzRfLwEYzS3sycBAgQIECBAgAABAgQIECAwY4G3z8/T9fl5rR4KxajFZeOaAn2FY8TinThWVopvwa3ZbJsTIECAAAECCxbILyLOMwjGWPCk0HUCBAhMUCD/fbwYerFPKEaESD18+DDFz/hVViIMI0p8jioECBAgQIAAAQIECBAgQIAAAQIECBDIC+xaXHl4dQWLAAECBAgQIEBgRAJlwRjWJGwfLMEYI5rImkKAAAECBAgQIECAAAECBAiMQ0AoxjjGQSteFiiGY0SIRSyeyd4qG3s0eTNtftGqhapmHgECBAgQINCWwIMHD144T8nqjfON/CLgOKeJcxiFAAECBAiMTSA+r/LhkfnPrCahGFkYRnxGVi0RiCEMo6qW7QgQIECAAAECBAgQ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9783FSykIz4uwic2LRdPkijizbeu3fvhWovLy9faks+/OLw8PCF7aN9sY9CgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEC7AtsWUUYoRiyiVAgQIECAAAECBMYtUPZyUMEY1cZPMEY1J1sRIECAAAECBAgQIECAAAECAwsIxRh4ABx+b4EIvNgWfBGVDxmQEW2rEo4R4RfRzgcPHtz0JV+yv9sbSgUECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECNwI7FpEKRjDJCFAgAABAgQITENAMEY74yQYox1HtRAgQIAAAQIECBAgQIAAAQIdCgjF6BBX1b0LRAhF/Hr48OHNz00lwifefPPNrdtkIRrxs61SJxwjC/nIH/v+/fvp9PS0reaohwABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMDiBZ6cnNyEY0Q5WK3S9fn5zX97q/jipwYAAgQIECBAYEICZcEYcZ53e7WaUI+GaapgjGHcHZUAAQIECBAgQIAAAQIECBCoKCAUoyKUzSYpkAVMjCUgY1s4xr17917wvby8TGdnZy8Fe86qEnUAACAASURBVKzX60mOg0YTIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQGJtAcQFlhGFkIRl3Li5uwjEUAgQIECBAgACB8QuUrYlwbldtDAVjVHOyFQECBAgQIECAAAECBAgQIDCAQNkFoGKTXBAaYJAcsjWBspCMXQe6e/duOj09TfFz37IpHCPqjiCMfIljFQM97t+/f9MOhQABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACB/QSenJw8D8Io1nR4dbVf5fYmQIAAAQIECBDoTWDXeV00wjqIakMhGKOak60IECBAgAABAgQIECBAgACBngXqhGJE8v3ByYkE/J7HyOG6ERhDQEbVcIyiQIRlXF5edgOjVgIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQILElgfHW3sbTwvF4snFQIECBAgQIAAgWkICMZoZ5wEY7TjqBYCBAgQIECAAAECBAgQIECgRY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+5CLqE4yxiGHWSQIECBAgQIAAAQIECBAgUE2g7AJMvhY346qZ2mo6AmWBGAerVbr1xhs3b4lUCBAgQIAAAQIECBAgQIAAAQIECBCYj0AEZDx96630zltvPX9T66beCciYz5jrCQECBAgQIECAAAECBAgQ6FMgrj1kQRjZ9YX87+NZPIUAAQIECBAgQGA+AvlQtE29EozRbKwFYzRzsxcBAgQIECBAgAABAgQIEJidgFCM2Q2pDlUUqBKIcXu1qlibzQgQIECAAAECBAgQIECAAAECBAgQmLJALFS5vrgQkDHlQdR2AgQIECBAgAABAgQIECAwMoH8s3nZS3niGkQUL6ga2WBpDgECBAgQIECgBYFdwRhxPigYrRmyYIxmbvYiQIAAAQIECBAgQIAAAQKzEigLBsh31o24WQ394juza+4frFZJIMbipwgAAgQIECBAgAABAgQIECBAgACBBQuUhWRkb3jNFrQsmErXCRAgQIAAAQIECBAgQIAAgR0C+YWR8UzS9fn58629LdzUIUCAAAECBAjMSyDuL0Uw2rYiGKP5eAvGaG5nTwIECBAgQIAAAQIECBAgMAsBoRizGEadqCmwa97HxcbX33hDKEZNU5sTIECAAAECBAgQIECAAAECBAgQmKtAlYAMb/aa6+jrFwECBAgQIECAAAECBAgQ2E8gvzAyC9nMFkpaFLmfrb0JECBAgAABAmMUEIzR3agIxujOVs0ECBAgQIAAAQIECBAgQGD0AkIxRj9EGtiyQNmcjzcy3F6tWj6q6ggQIECAAAECBAgQIECAAAECBAgQmIPAroCMbGFL/FQIECBAgAABAgQIECBAgAABAplAhGDENYUoEax5fXHxwu9dSzBXCBAgQIAAAQLzEvC8enfjKRijO1s1EyBAgAABAgQIECBAgACBUQuUXXDJN15YwKiHUuMqCuya8+Z4RUSbESBAgAABAgQIECBAgAABAgQIECBws3gle7NrkcO1RhOEAAECBAgQIECAAAECBAgQyASK1xAiGCN/TeHw6goWAQIECBAgQIDAzATK1mnEOaFwtGaDLhijmZu9CBAgQIAAAQIECBAgQIDApAXKLrbkO+ch3kkPtca/L7BtzsdFxbi4qBA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1JlIG2t+Oabpdc559hDLsFm0bVtm1Rfd510bN5seuYqzKHwyivFkZFhuoadOza9/LLsnT49ZlPMv/BCKbrqqpiNF2wgb2urbP35zw3No/iGG6TXr39tqC2NEEAAAQQQQAABBBBIZIHANzJprYW3NCXyDjP3WAsQjBFrccZDAAEEEEAAgUQRaFy+XGrvuSdq080eMUIKL71UMoYOjdoYFEYAAQQQQAABBBBAAAF7CgR+AIT7GvbcJ2aFQNHhdc8AACAASURBVLeA/70U3mDMeYEAAggggAACCCCAAAIIRCYQ7BlQgggjc6U3AggggAACqSyw5cgjQy6f+zCxOTtsEYzR9NJLsvfOO3VXXP7445I1fLhuOxocKNDy9ttSff31pllcxcVSMmOGZB97rOkaidCx7uGHpX7hwphOtei66yT/3HNjOmbgYC1vvSXVN9xgaA59ly+X9EMPNdSWRggggAACCCCAAAIIJLJAsLTw7jVxcySRd5e5x0OAYIx4qDMmAggggAACCCSKQOu6dVJ7773StWNH1KacM2qUFFx2mWQMHhy1MSiMAAIIIIAAAggggAAC9hIgGMNe+8FsENAT4F6KnhBfRwABBBBAAAEEEEAAAQTCE9D68CrPfoZnSGsEEEAAAQQQ2C+g9+JVfsaI3Zlii2CMukcekfonntBddf+33hIV0sBhTMBdWyv75syR5pUrjXXQaJU9cqSUTJuWEu4qPESFiMT6KH/0Uck6+uhYD/vdeNU33igtq1cbGn/A2rXizM831JZGCCCAAAIIIIAAAggksoD/g2da6yhfsEDUxQsOBBAwJsDDnMacaIUAAggggAACqSvQsnatVF97bdQBcsaMkcLJkyX9kEOiPhYDIIAAAggggAACCCCAQHwFAu918Kay+O4HoyMQSiDwoWq+XzlfEEAAAQQQQAABBBBAAIHIBYI9B8rvXJHbUgEBBBBAAIFUEyAYwz47botgjJqbb5bmVat0VQb+858iTqduu5Rv4PVK82uvSe3s2eJpbjbNUXzLLdLrrLNEHA7TNRKp447TTovq29iCWThzc6XPs89KWv/+MefytrTI1l/8wvC4fA8apqIhAggggAACCCCAQAIL6F20UEsjGCOB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SXv7zzz/TdaolAncKCMa4E85pBAgQIECAAAECBAgQIECAAAECdQoMfYH3noCMICYko851Y1YECBAgQIAAAQIECBAgQIAAAQJ1CITX78IFvO/HY++EYuDFpdcRBWLUsQ7MggABAgQILCkgoGNJ7WX7EnqwrLfeCBAgQIAAAQIECBAgQGCcQHhN4vd+f/OkX6fTzv9xbzI5YAEBwRgLIOuCAAECBAgQIECAAAECBAgQIECgLIGx4RX3hGTEDfbhDldLb3aLL06/7PdeqC5raRotAQIECBAgQIAAAQIECBAgQIDATAIh6CI87g3ECOcKxZipOJolQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEJhcIoRi39jCHPcchGMODQA4CgjFyqIIxECBAgAABAgQIECBAgAABAgQIZCsQNsQPDa+4N3BibBDH1Fj3BHtMPQbtESBAgAABAgQIECBAgAABAgQIEFhaYEgYRjqmW6EZS49ffwQIECBAgAABAgQIECBAgAABAgQIECBAgACBewTCeySX3vdI2/vPP//c07xzCMwiIBhjFlaNEiBAgAABAgQIECBAgAABAgQI1CZwT3hFDJwIFjE045bLPf3canPM9+8Z85j2HUuAAAECBAgQIECAAAECBAgQIEBgLYHw2ttH294Mwn05HHbPTXP12PA62lPT7F4Ph7Wmo18CBAgQIECAAAECBAgQIECAAAECBAgQIECAwGiB8H7J7/3+5nm/TqfB+59vNuYAAhMICMaYAFETBAgQIECAAAECBAgQIECAAAEC2xG4N7giBmO87PeDXiQO/YTH++m0i58vrRw394eLAIYGeyw9Rv0RIECAAAECBAgQIECAAAECBAgQuCYQ7njWvc729fHasfH1sGvHhtCM8BCIYd0RIECAAAECBAgQIECAAAECBAgQIECAAAECJQr87//8z81hh/dDvBdyk8kBCwsIxlgYXHcECBAgQIAAAQIECBAgQIAAAQL1CNwbkhEEwib7EJIRP7+mEvsJx6wVkjF2zPVU2UwIECBAgAABAgQIECBAgAABAgRKEgivn320bTfkW2EY4TW6cHzY3HnrWBtAS1oFxkqAAAECBAgQIECAAAECBAgQIECAAAECBAj0Cfze72/uRQ7vn/w6nQASyE5AMEZ2JTEgAgQIECBAgAABAgQIECBAgACB0gTiZvvPtr35YvGluYUXkcPjVljGI2EcU7qm442fT9m+tggQIECAAAECBAgQIECAAAECBAjcEkhDMMa+NhdDMa71EcIwwsMd0W5VwvcJECBAgAABAgQIECBAgAABAgQIECBAgACB3AX+HI83g8LDHEIohr3BuVdzm+MTjLHNups1AQIECBAgQIAAAQIECBAgQIDAjAIxvCJ0ET6/9xFfVH5qmt1z+PMVnhHbyyUkI4wnjO3SOO+dv/MIECBAgAABAgQIECBAgAABAgQIxNfYPtq2wxgbgDFWUBjGWDHHEyBAgAABAgQIECBAgAABAgQIECBAgAABArkLDA3FCO+TCAzPvZrbHZ9gjO3W3swJECBAgAABAgQIECBAgAABAgQWEIjBGO+n00MhGXGoaThGDKII3wsXBoSLArrPHwjjmIokjvNlv5caPRWqdggQIECAAAECBAgQIECAAAEClQrE17Ni+EWY5lKvdQl8rXRRmRYBAgQIECBAgAABAgQIECBAgAABAgQIECDQCYT3YX7v9zc1wnsmv06nm8c5gMBaAoIx1pLXLwECBAgQIECAAAECBAgQIECAwCYFwovLuYVYLFGINChjif70QYAAgVwE0kCjXMZkHAQIECBAgAABAgRKFcghDLRUu7XHvUbgxaU5xyCM8H13PFt7ZeifAAECBAgQIECAAAECBAgQIECAAAECBAgQmFNgaChGGMN//vlnzqFom8DDAoIxHibUAAECBAgQIECAAAECBAgQIECAAIHHBNI7Yi51J8zHRuxsAgQIECBAgAABAgQIECBAgAABAnkLpAEYz02zE1yYd72MjgABAgQIECBAgAABAgQIECBAgAABAgQIEJhe4Pd+vxsSPv/rdPJeyvT8WpxYQDDGxKCaI0CAAAECBAgQIECAAAECBAgQIDCVQF9gRmh7yAvUU41BOwQIECBAgAABAgQIECBAgAABAgRyFIhBF09N82N4QjByrJYxESBAgAABAgQIECBAgAABAgQIECBAgAABAksLDA3FeDkcdq+Hw9LD0x+B0QKCMUaTOYEAAQIECBAgQIAAAQIECBAgQIBAXgLnQRkfbfs9wM/k82ujFraRV02NhgABAgQIECBAgAABAgQIECCwtEAMmli63/Ngi77+Q9hFeKw1xqVN9EeAAAECBAgQIECAAAECBAgQIECAAAECBAgQeETgz/G4ez8ebzYhFOMmkQMyEhCMkVExDIUAAQIECBAgQIAAAQIECBAgQIDAmgIhHOP9dOqGkHNQRrgAIlwwscYFETm7PLJ20jCVR9rJ/dyhQTG5z+OR8dW6hh8xcS4BAgQIECBAgACBJQVKv6h/SIDBkp5j+oqvI4w5Z85jS18Lc9pomwABAgQIECBAgAABAgQIECBAgAABAgQIECBA4H4BoRj32zkzbwHBGHnXx+gIECBAgAABAgQIECBAgAABAgQIrCIQL54PQRklXEi/ZljGKgXSKQECswiU8PNulomv3OhWwnlWZtb9RAJCliaCXKCZki/cXoBHFwsI5HYB/gJTvqsLwQB3sTmJAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECvQJDQzHCe7W/vm6mh5JAKQKCMUqplHESIECAAAECBAgQIECAAAECBAgQWFGgtKCMQBUvsHrZ7zs5F1ytuIB0TYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgMJvA0FCMMID//PPPbOPQMIG5BARjzCWrXQIECBAgQIAAAQIECBAgQIAAAQIVC4SgjI+23YW7psfQjBKmG8Mxwh3E4x2cBWaUUDljJECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQ6BMYE4rx63RysznLqEgBwRhFls2gCRAgQIAAAQIECBAgQIAAAQIECOQlEMMx3k+nbmAlhWWE8cZwjJf9vhu/sIy81pfRECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI/C0wJhTj5XDYvR4OGAkUKSAYo8iyGTQBAgQIECBAgAABAgQIECBAgACBvAVKD8oIujEc46lpds9N04ELzMh73RkdAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQGArAkIxtlJp8wwCgjGsAwIECBAgQIAAAQIECBAgQIAAAQIEFhGoISwjQMVwjJf9vnMTlrHI8tEJAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAl4BQDEthawKCMbZWcfMlQIAAAQIECBAgQIAAAQIECBAgkJFACMv4aNvdZ9t2o4rhGRkNcdBQYjjGU9PsnpumO0dgxiA6BxEgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECIwQEIoxAsuh1QgIxqimlCZCgAABAgQIECBAgAABAgQIECBAoA6BWsIyQjViOMbLft8VR1hGHWvULAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECawgIxVhDXZ85CAjGyKEKxkCAAAECBAgQIECAAAECBAgQIECAwFWBGsMynppm99w03bwFZvgHQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgcE3g936/C3tqhzxeDofd6+Ew5FDHEChCQDBGEWUySAIECBAgQIAAAQIECBAgQIAAAQIEzgXiC/vvp1P3raEv9OcqGcMxBGbkWiHjIkCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgsLxD2yIb9skP3ygrFWL5GepxfQDDG/MZ6IECAAAECBAgQIECAAAECBAgQIEBgIYH4gv9H2+4+27brdeibAAsNcXQ3MTDjZb/vzo1/H92QEwgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBIoS+HM87t6Px8FjFooxmMqBhQkIxiisYIZLgAABAgQIECBAgAABAgQIECBAgMB4gfPAjNLDMoKAwIzx68AZBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFSBIRilFIp41xCQDDGEsr6IECAAAECBAgQIECAAAECBAgQIEAgS4EYkPF+OnXjqykw46lpds9N080rhmhkWQSDIkCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQ+CEgFMOCIPBTQDCGFUGAAAECBAgQIECAAAECBAgQIECAAIFEIIZjfLTt7rNtu+8IzLBECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIElhAYG4rx63RyE7UlCqOPVQUEY6zKr3MCBAgQIECAAAECBAgQIECAAAECBEoREJhRSqWMkwABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBQnkDYq/p7vx81cKEYo7gcXLCAYIyCi2foBAgQIECAAAECBAgQIECAAAECBAisLxADM95Pp24w8e/rj+yxETy/vX038NQ0u+em6f6efv2xHpxNgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAQBP4cj7v343EwRtjPGUIxPAhsRUAwxlYqbZ4ECBAgQIAAAQIECBAgQIAAAQIECCwqUGtgRkAUmrHoUtIZAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgULHA2FCMl8Nh93o4VCxiagT+FhCMYVUQIECAAAECBAgQIECAAAECBAgQIEBgIYEYlvHRtrvPtu16jV9baAiLdBODM56aZvfcNF2faZjGIoPQCQECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgc4Hf+/2ovaRCMTIvqOHNJiAYYzZaDRMgQIAAAQIECBAgQIAAAQIECBAgQGCYwFYCM4JGX2hG+vVhYo4iQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECJQr8Od43L0fj6MmIBRjFJeDKxMQjFFZQU2HAAECBAgQIECAAAECBAgQIECAAIF6BLYUmBGrJjijnvVrJgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMDfAveEYvw6nb5vTsaUwBYFBGNssermTIAAAQIECBAgQIAAAQIECBAgQIBA0QJbDMyIBUuDM8LXnpum+1b8etGFNXgCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgWoGw//P9dNrFfaBDJvpyOOxeD4chhzqGQNUCgjGqLq/JESBAgAABAgQIECBAgAABAgQIECCwNYEth2aEWqcBGU9N8x2ccf69ra0L8yVAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgTWE/hzPO7ej8dRAxCKMYrLwZULCMaovMCmR4AAAQIECBAgQIAAAQIECBAgQIAAgSCw9cCMdBXE8IwQnBEez/Hj25vFQoAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCYVEAoxqScGtuogGCMjRbetAkQIECAAAECBAgQIECAAAECBAgQIBAFYmjG++n0jRK/tkWlGJwR5h7CMwRnbHEVmDMBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEHhM4J5AjLCH8Veyn/OxETibQD0CgjHqqaWZECBAgAABAgQIECBAgAABAgQIECBAYFKBNBzjo213n23btb/l0Iww/0vBGeffm7QYGiNAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgSKEbgnFOPlcNi9Hg7FzNFACSwpIBhjSW19ESBAgAABAgQIECBAgAABAgQIECBAoCKBGJCRhmaE6W09OCMYnIdndF9rmq766fcqWg6mQoAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIENi9wTyBGQBOKsfmlA+CGgGAMS4QAAQIECBAgQIAAAQIECBAgQIAAAQIEJhdIwzHS4AyhGT+pY0jGUwzN+PoYjhKgMfmy1CABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEJhFIOyPfD+dRt9cTCDGLOXQaIUCgjEqLKopESBAgAABAgQIECBAgAABAgQIECBAIHeBGJARQjPC4/Pro+CMvyuXBmSEAI1n4Rm5L2/jI0CAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAl1ZmcAACAASURBVAECBAgQIECAAIENCfw5Hnfvx+PoGQvFGE3mhA0LCMbYcPFNnQABAgQIECBAgAABAgQIECBAgAABArkKpAEZITwjBmeE8QrP+Ltq5+EZ4QgBGrmubuMiQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgRoE7g3ECHv+Xvb7Xbr3rwYPcyAwp4BgjDl1tU2AAAECBAgQIECAAAECBAgQIECAAAECswkIzxhPex6gITxjvKEzCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQGDbAvcGYgS1l8Nh93o4bBvQ7AncISAY4w40pxAgQIAAAQIECBAgQIAAAQIECBAgQIBAGQIxPOOjbbsBf359TEM1ypjJcqMUnrGctZ4IECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAoAyBsO8w7EV8Px7vHrBQjLvpnEhgJxjDIiBAgAABAgQIECBAgAABAgQIECBAgACBzQqkARnhDasYnBFAhGdcXhbCMzb7T8bECRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgsCmBP8djt7fwkT2FAjE2tWRMdiYBwRgzwWqWAAECBAgQIECAAAECBAgQIECAAAECBOoQEJ5xXx2FZ9zn5iwCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQWFcghGGEx/vXx3tHIxDjXjnnEfhbQDCGVUGAAAECBAgQIECAAAECBAgQIECAAAECBB4UEJ5xH2AMz3hqmq6B56+P3edvb/c16iwCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIDBSIIRhfLbtLt0POLKJH4cLxXhEz7kE/hYQjGFVECBAgAABAgQIECBAgAABAgQIECBAgACBBQTOwzNCl+FNtPiY6s20BaayWBdpOMZ5eIbgjMXKoCMCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAhUJxD27H207e79eJx0bgIxJuXUGIFvAcEYFgMBAgQIECBAgAABAgQIECBAgAABAgQIEMhIQIDGuGKch2c8N813A8Izxlk6mgABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAjUL/PkKwZg6DCOYCcSoeeWYWw4CgjFyqIIxECBAgAABAgQIECBAgAABAgQIECBAgACBkQLXAjTS741stsrDL4VnCM6ostwmRYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgU4g7KX7aNvdZ9t2n8/xEIgxh6o2CfwtIBjDqiBAgAABAgQIECBAgAABAgQIECBAgAABAhULnAdohDf44mOuN/pK47wUnBHmITyjtGoaLwECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECWxb4czx203//+jiXRQjEeG4ae8zmAtYugTMBwRiWBAECBAgQIECAAAECBAgQIECAAAECBAgQ2LjAeXhG4IgBGsIzfoZjPIU3Mpvme8UIztj4Px7TJ0CAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEBgVYGlgjDiJEMgxuvhsOqcdU5giwKCMbZYdXMmQIAAAQIECBAgQIAAAQIECBAgQIAAAQIjBYRnXAeLARkhOCM8YniG4IyRC83hBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQuCKwdBBGGEoIwwgPgRiWJoH1BARjrGevZwIECBAgQIAAAQIECBAgQIAAAQIECBAgUJWA8IzL5UwDMkJ4RgzOCGcIz6jqn4HJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAwkUDYk/bRtl1r78fjRK0OayaEYYR9XvZ3DfNyFIG5BQRjzC2sfQIECBAgQIAAAQIECBAgQIAAAQIECBAgQOBb4Dw84/PrTctwQPq9LZIJz9hi1c2ZAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIEosGYQRti/FW96JAzDmiSQn4BgjPxqYkQECBAgQIAAAQIECBAgQIAAAQIECBAgQGDTAsIzLpc/vuEa3oANj3BHgvjwZuym/9mYPAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIGiBNIQjHCDpTVurPRyOHRmr18fiwI0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OMndwzOCG+Ih7tChEcapjF7cXRAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAYGGB8+CL0P1n2+5KuxHPy1f4Rdj3Y8/PwotIdwQKExCMUVjBDJcAAQIECBAgQIAAAQIECBAgQIAAAQIECBAg0CdwLTwjHF/am95TVFloxhSK2iBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEFhaoJbgi9RNCMbSq0h/BOoSEIxRVz3NhgABAgQIECBAgAABAgQIECBAgAABAgQIECBwVeD8TfNwp4j42Ep4hsAM/0gIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgTWFLi0h6eW/TtCMNZcXfomUKeAYIw662pWBAgQIECAAAECBAgQIECAAAECBAgQIECAAIG7BdI32D/adrel8IwYmvGy33d+8e93YzqRAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEBgUwLnoRdh8nH/TS3BF7GgYW/NU9N0f31uGnttNrXSTZbAsgKCMZb11hsBAgQIECBAgAABAgQIECBAgAABAgQIECBAoAqBrYVnCMyoYtmaBAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEDgIYEthV6kUGkARvj66+HwkKOTCRAgMFZAMMZYMccTIECAAAECBAgQIECAAAECBAgQIECAAAECBAgMEthCeIbAjEFLwUEECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgewFthp6kRYmDcB4bppd3BuTffEMkACB6gUEY1RfYhMkQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECOQrkG4o+Gzb74GmoRr5jr5/ZHFDwFPYHNA03UE2CZRWReMlQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEahEQePGzkmn4RfiOAIxaVrp5EKhbQDBG3fU1OwIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBA0QLnGxNieEaJwRkCM4peigZPgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIZCTQF3YRhlfy3pIpeYVfTKmpLQIEchAQjJFDFYyBAAECBAgQIECAAAECBAgQIECAAAECBAgQIEBgtEAajvHRtsVubBCYMbr0TiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQqFegLvBB28Xex+4IvwlFxH0qly8O0CBDYsIBgjA0X39QJECBAgAABAgQIECBAgAABAgQIECBAgAABArUKpJskSt0cITCj1tVpXgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAYFsC18IugkR6c5RtyVyereALK4EAAQI/BQRjWBEECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQKbEig9NENgxqaWq8kSIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIEsBYRd3F+WdO9HbOW5abpP4/fub92ZBAgQqFNAMEaddTUrAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBkQK1BGa87PfdzG2UGLkAHE6AAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBDYsEPdNBIKPtv2W+Pz6PP3+hpkGTT3s2Xj6CroIJwi9GMTmIAIECFwVEIxhgRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBC4IlByYEZ6hxGbLCxzAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCwLQFhF9PXW+jF9KZaJECAwBABwRhDlBxDgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA4ExAYIYlQYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECCwtIOxiHvH05iOxBzchmcdaqwQIELhHQDDGPWrOIUCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIHBBoPTAjKem2dnYYXkTIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIHlBIRdzGct8GI+Wy0TIEBgSQHBGEtq64sAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQGCzAqUGZsQNIi/7fVe7+PfNFtLECRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAAAFhFwOQHjhE4MUDeE4lQIBAgQKCMQosmiETIECAAAECBAgQIECAAAECBAgQIECAAAECBAjUI3AemJFujMl1lsIycq2McREgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAnALpe/xpP59t2/21hPf85/R5tO2+sIvQ5nPTdE27mcejws4nQIBAuQKCMcqtnZETIECAAAECBAgQIECAAAECBAgQIECAAAECBAhULBA3y7yfTt0sc988Iyyj4sVoagQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEKhYQNjFvMUVdjGvr9YJECCwFQHBGFuptHkSIECAAAECBAgQIECAAAECBAgQIECAAAECBAhUIVBSYIawjCqWnEkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgOAFhF/OWTNjFvL5aJ0CAAIG/BQRjWBUECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEChdIN/R8tm03m/i13KYmLCO3ihgPAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEyhAQdjFvnYRdzOurdQIECBB4TEAwxmN+ziZAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQrUApgRnCMrJdQgZGgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBWQWEXczKuxN2Ma+v1gkQIEBgOQHBGMtZ64kAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAFgJxY9H76dSNJ/49i8F9DUJYRk7VMBYCBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAiME+gLvPhs266RHN+jHje7dY8WdrGuv94JECBAYB0BwRjruOuVAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQFYCwjKyKofBECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAIDuBvrCLMEiBF4+XStjF44ZaIECAAIG6BQRj1F1fsyNAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBwt0C6qSlsZMrxrj1xc9DLft/NM/797kk7kQABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAhsT6Au8EHbx+CIQdvG4oRYIECBAgEAUEIxhLRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgMFjgPCwjnJhbYIawjMHldCABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAhULCLyYvrjCLqY31SIBAgQIEBgiIBhjiJJjCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBC4KhA2VH207S7XuwYJy7CACRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCoRUDgxbSVFHYxrafWCBAgQIDAHAKCMeZQ1SYBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABArs0LCNuzMqJRVhGTtUwFgIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIE+gIvgkquNyjIuWLCLnKujrERIECAAIHxAoIxxps5gwABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBOwTSTVxh45awjDsQnUKAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQJECfaEXAi/GlVLYxTgvRxMgQIAAgZoEBGPUVE1zIUCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIFCYQClhGU9Ns3tumk43brYqjNpwCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCYQUDgxWOowi4e83M2AQIECBDYioBgjK1U2jwJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIFCJQWliGoIxCFpZhEiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEBghIPBiBFbPoX2BF25G8JipswkQIECAwJYFBGNsufrmToAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQKAQgdzDMtJNXWEzl7CMQhaWYRIgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECGxOQODF/SXvC7sIrQm8uN/UmQQIECBAgMAwAcEYw5wcRYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAZgLnYRlhePFrOQxVWEYOVTAGAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBLQj0hV2EeX+2bTf9nN5HzLEefYEXwi5yrJQxESBAgACB7QoIxthu7c2cAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQJUCYVPbR9tmuclNWEaVS86kCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEZhAQdvE4qsCLxw21QIAAAQIECOQhIBgjjzoYBQECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECMwoIy5gRV9MECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEBgoIuxgIdeMwgRfTOGqFAAECBAgQKEdAMEY5tTJSAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmFBCWMSGmpggQIECAAAECBAgQIECAAAECBAgQIECAAAECBDYt0Bd48dm2nUn83qaBRkw+hF48Nc2PM56//h4DMUY051ACBAgQIECAQBUCgjGqKKNJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAwhUAalpHjBr24Cc7GtymqrQ0CBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFbAgIvbgkN/34MtUhDL7zvN9zPkQQIECBAgMC2BQRjbLv+Zk+AAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAwBWBdKNfuKNVrmEZYQphA52Nc5YzAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAUIEYGp8eH94TC48c3xcbOq+lj+sLvAhjCO/dxe8tPSb9ESBAgAABAgRqExCMUVtFzYcAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgVkF4ibA99Op6yfXTYFxk93Lft+N06a7WZeFxgkQmEEg15+vM0z1riY/vjan33VyRSfFUKilp+T36tLi+iNAgAABAgQIECBAgAABAgQIEBgjkIa/x/MEXowR/P9j+0IvhNXfZ+ksAgQIECBAgMAjAoIxHtFzLgECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBJJwjNzDMkKxwua9p3B3qqbpaufCXkuYQL/AFKEMUwYXxA3Lc9RrirnOMS5tEqhZYOjv3/A7+9pjaDDI0P5qNjc3AgQIECBAgAABAgQIECBAgEAtAkIvHq9kX9hF976Z988ex9UCAQIECBAgQGAmAcEYM8FqlgABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBbQvETYmlhGXEar3s992nLqDd9vqda/ZDAhjGh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p/fM3fa0X/1uA8kLz72tdrCl5LWG6d6okAAQIECBAgQGAaAcEY0zhqhQABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAtkLpHdGszk0+3IZIIGbAnNtXH40cObmwHsOOL/A+5425jhnLuM5xqrNPATuuegivXjj0iz6gpzOj72n7zzUjGJKgb4gDSEaUwpriwABAgQIECBAgAABAgSWFBB8cVlb6MWSK1FfBAgQIECAAAECOQgIxsihCsZAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBFQUEZqyIr+tFBYaEHDwSCnFPuMOQMS2KpDMCBKoXGBKgcS2s41JIx5B2q8ctbILnv4Pi78D095nfU4UV1XAJECBAgAABAgQIECBQmEBf8IXXGHY7oReFLWTDJUCAAAECBAgQWERAMMYizDohQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAmQJxA+r76dRNwIbUMuu41qhvXUw7NIRiSODErb7WMtAvAQIEtizQ97yhL3SjL2zDc478Vk76u1aIRn71MSICBAgQIECAAAECBAjkKCD44u+qCL3IcaUaEwECBAgQIECAQAkCgjFKqJIxEiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAIDOBeLFquLg1XszqAtbMinRjOH1BEteCKi6FUwikYVpFXgAAHpZJREFUKKvuRkuAAIGSBQRtlFO9vhCNMPr0+YTnEOXU00gJECBAgAABAgQIECBwSSB9ryAcs/X3C4Re+LdCgAABAgQIECBAYD4BwRjz2WqZAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECmxPoC8wICEIzpl8Kly44DT2dh1i48HR6fy0SIECAQPkC6fOTEPYVH/Einvh3z2Pmr3Xf8xrPZ+Z31wMBAgQIECBAgAABAgSGCPSFX2zx/8pCL4asFscQIECAAAECBAgQmE9AMMZ8tlomQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgUTg/OLTrd857tLisLnWPxsCBAgQIJCvwPmFPzFQQ5jGsjUTpLGst94IECBAgAABAgQIENiGQPg/73lw5FYCMLwuv401bpYECBAgQIAAAQJlCwjGKLt+Rk+AAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFqBPru2p5eZFr6Blwba6tZqiZCgAABAgRGCQjTGMU1y8F9QRqho+em+e4vPWaWQWiUAAECBAgQIECAAAECmQikARjhNfjSX3sfwhr+z/eU/h/w63P/Fxyi5xgCBAgQIECAAAECeQgIxsijDkZBgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgMFcgvQ6Au8CFOJF1raWDuwsA4jQIAAAQIEvgWEaay7GM6fv8WLp9Igje753tvbugPVOwECBAgQIECAAAECBK4IbCkAQ/CFfwoECBAgQIAAAQIE6hcQjFF/jc2QAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECmxOIF5N+tO0u3PEuPsbc+e7WncVdCLm5ZWXCBAgQIEAga4HcwsOyxpphcH3PHQVpzACtSQIECBAgQIAAAQIEfgik4RfhG+H18DGvg5fA2RdOHf6/5TX6EqpnjAQIECBAgAABAgSmExCMMZ2llggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgQIGwSdgG2gILZ8gECBAgQIDA3QJ9IRqhsXsDxe4eyEZPPH/u+dQ0nUQapOH56UYXh2kTIECAAAECBAgQuCCQBmDE/7vVEoAh+MKyJ0CAAAECBAgQIEBgiIBgjCFKjiFAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAhsUOL/Q6qNtOwUhGssthjQkQ4jGcu56IkCAAAECBAgQILCGwHkARk3hF/H/M8E1BAMKBFxjhemTAAECBAgQIECAQLkCgjHKrZ2REyBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBrATSi7ZiiEYYoCCNZcokRGMZZ70QIECAAAECBAgQeFSgxgCM8P8R4RePrgznEyBAgAABAgQIECBwSUAwhrVBgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIrCLQF6SRhmiEQdVyh+RVgC90KkAjp2oYCwECBAgQIECAQO0CNYVgpOEXz02zS/9vUXsdzY8AAQIECBAgQIAAgXUFBGOs6693AgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAYKCAII2BUBMeJkRjQkxNESBAgAABAgQIVC/w53js5hgC/0oN+UvDL8JcBGBUv2xNkAABAgQIECBAgEARAoIxiiiTQRIgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQJjBfqCNEIb4SK19FHqBWtjPeY8XoDGnLraJkCAAAECBAgQyE0g/B/i4+v/FaWGYAjAyG1VGQ8BAgQIECBAgAABAtcEBGNYHwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACB3e6vOzqnF7qlQII0Hlsu5yEa4Q7U6SP9/mM9OZsAAQIECBAgQIDA4wKlh2CkARjhubfn24+vCS0QIECAAAECBAgQILC8gGCM5c31SIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECFQikIZkCNKYtqjnARqh9TREwwV903prjQABAgQIECBA4N+wvPR5fUmheAIwrGACBAgQIECAAAECBGoWEIxRc3XNjQABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEMhKQJDG9OU4D8h4apquEyEa01trkQABAgQIECBQk0AagvF+PBYzNQEYxZTKQAkQIECAAAECBAgQmFBAMMaEmJoiQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECEwlcH536nDn6s+2/dF8SXewnsrlkXaEaDyi51wCBAgQIECAQLkCJYZgCMAod70ZOQECBAgQIECAAAEC0wsIxpjeVIsECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgUUF0oCMEKARHmmIhgCN8eUQojHezBkECBAgQIAAgRwESgvBEICRw6oxBgIECBAgQIAAAQIEchcQjJF7hYyPAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIDChgBCNCTG/mhKiMb2pFgkQIECAAAECQwT+HI/fh70nnw85d41j0hCM18NhjSHokwABAgQIECBAgAABAkUKCMYosmwGTYAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCYX0CIxjzGaZDGU9N8d/Kcfv72Nk/nWiVAgAABAgQIFCoQQzA+23aXPk/NdTovX8EX4TneeZBarmM2LgIECBAgQIAAAQIECOQqIBgj18oYFwECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECgEAEBGvMWqi9IIw3RCL272HLeGmidAAECBAgQWE4gPLf8aNuuwxJCMMLzsBh2JgRjuXWiJwIECBAgQIAAAQIEtiUgGGNb9TZbAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMBqAgI05qc/D8hIL9KMvQvRmL8OeiBAgAABAgSGCQjBGObkKAIECBAgQIAAAQIECGxdQDDG1leA+RMgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEMhQQorFMUdKQjBiiEXoOdzuPD0Eay9RCLwQIECBAoGaB0gIwuudDb2+7NGTMc6KaV6i5ESBAgAABAgQIECCQu4BgjNwrZHwECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIXBdIAjXDQR9t2x35+fey+9t//EpxIoC9IIw3RCN24aHQibM0QIECAAIHCBNLwi/h8rJTnYUIwCltshkuAAAECBAgQIECAwOYEBGNsruQmTIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBDYpoAQjWXrfh6Qkd5xPR2JII1l66I3AgQIECDwiEDJ4Rdx3kIwHlkBziVAgAABAgQIECBAgMA6AoIx1nHXKwECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQMYCQjTWKY4wjXXc9UqAAAECBKJADcEXaTWFYFjbBAgQIECAAAECBAgQqENAMEYddTQLAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBlQSEaKwE/9VtGqbx1DTfg3lOP397W3eQeidAgAABAhkJpOEXn227O38uk9FQRw1FCMYoLgcTIECAAAECBAgQIECgKAHBGEWVy2AJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgRKFxCksX4F0zCNMJpLgRrhe+fHrj96IyBAgAABAsMF/hyP3cE1BWDE38/x93cIw/L7eviacCQBAgQIECBAgAABAgRKFBCMUWLVjJkAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQGAzAmmQxkfbdvMOF7emj1ru9F5CUYVqlFAlYyRAgMB2BcJzgvB8oaYgjPC7VwjGdte0mRMgQIAAAQIECBAgQCAICMawDggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAhUInAekNEXpCFEY51i993JPl7kG0YU7nZ//ug7Z53R65UAAQIEchaIYRjvx2POwxw0NiEYg5gcRIAAAQIECBAgQIAAgc0JCMbYXMlNmAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMC/AoI0yloJ50EZabBGmMl5uIZgjbLqa7QECBAYK/DneNx9tu1fv8/HtrPW8UIw1pLXLwECBAgQIECAAAECBMoTEIxRXs2MmAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgMAqAmmQxkfbdmMIF+Smj/OwjVUGqtNegb6gjFvhGqEhARsWFAECBPIRCGEY4fH+9TGfkV0eiQCMEqpkjAQIECBAgAABAgQIEMhbQDBG3vUxOgIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQJFCpwHZMQgjTCZNExDkEZ55b0VsPHcNL2TErBRXq2NmACBPATC78rwezT3MAwBGHmsF6MgQIAAAQIECBAgQIBAjQKCMWqsqjkRIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQKFDgUphGGqQRpiVMo8Di9gz5VsBGOKUvZEPARh31NwsCBG4L/DkeuzCpnH7vnYdfdD+r395uT8YRBAgQIECAAAECBAgQIEDgAQHBGA/gOZUAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgXUFhGms659D75cuyH5qmh/DE7KRQ7WMgQCBWwIhDCM83r8+3jp+ju+n4Reh/fDzU/jFHNLaJECAAAECBAgQIECAAIGhAoIxhko5jgABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBKgTOwzTCpD7a9ntun8nn3ff++98q5m0StwWEbNw2cgQBAtMLrBGGIfxi+jpqkQABAgQIECBAgAABAgTmExCMMZ+tlgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQqExAqEZlBZ15On1BG09N86PX57O/h29eCuiYebiaJ0BgQYGlwjDSAIzw88bPlwWLrCsCBAgQIECAAAECBAgQmExAMMZklBoiQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAZYGxoRqhpb5zGG9P4NKF7EI2trcWzLhsgSXCMGIQhhCMsteK0RMgQIAAAQIECBAgQIDATwHBGFYEAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEChEQrlFIoTIeZl/IxpCAjTClSwEdGU/X0AisKhCDMD7bdtago5fDoZvn69fHVSetcwIECBAgQIAAAQIECBAgMIOAYIwZUDVJgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBXAWEa+RamfLGdSkoQ9BGebU04scFws/Wj7btGno/Hh9v8EYLwjBmJ9YBAQIECBAgQIAAAQIECGQkIBgjo2IYCgECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBEoQuBWuEebw+XWBeDqfvvNKmK8xLiswNHAjjOq5aS4O7lI7y85Gb7UJpAEY4efckj/XhGHUtprMhwABAgQIECBAgAABAgSGCgjGGCrlOAIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBCYVODSBeUfSahGX8BGGMSSF6NPOmmNZSNwKzjj6UroRpjEtVCO80ne6isbFAPpfrb0/Qxa62dOWDthLb4eDqpDgAABAgQIECBAgAABAgQ2KyAYY7OlN3ECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAjUI9B30Xp6cXuYqZCNeupd60zGBmjcCu/ocxoT6HHNeexYl6jZkLCdOI7058FaoRfXTF4Ohy58JUfnJWqpDwIECBAgQIAAAQIECBAgkAoIxrAeCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAIjAkZCMc3he0keMF9opLgEAZAiEMIzxevz6WMWqjJECAAAECBAgQIECAAAEC8wsIxpjfWA8ECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgsFGBS0EZH237Q0TIxkYXiGlvWuD57W331DS75/Dn7W3TFiZPgAABAgQIECBAgAABAgSuCQjGsD4IECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEABAkI2CiiSIRK4IfByOHRHvH59BEaAAAECBAgQIECAAAECBAjcFhCMcdvIEQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAoCoBIRtVldNkMhV4fnvbPTVNNzpBGJkWybAIECBAgAABAgQIECBAoAgBwRhFlMkgCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIBAvgJ9QRsfbfvXgD97vhYOuhTUke+MjYzAT4E0BOO5aXbh7x4ECBAgQIAAAQIECBAgQIDANAKCMaZx1AoBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECAwocClsIy+wI3Q7aXQjTgk4RsTFmejTcWwi6em6QQEYGx0IZg2AQIECBAgQIAAAQIECCwuIBhjcXIdEiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABArkJ3ArOuBTIkc7jVjhHeuyt/nLz2cJ4+oIvwrzj17dgYI4ECBAgQIAAAQIECBAgQCBHAcEYOVbFmAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECu93ungCNISEefbhjgj1uFeeecd9qM35/aFDFU9P81eTz2deGtjV0bI4jQIAAAQIECBAgQIAAAQIEphcQjDG9qRYJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEBCMMQGiJggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBKYXEIwxvakWCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEJhAQjDEBoiYIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgSmFxCMMb2pFgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBCYQEIwxAaImCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEphcQjDG9qRYJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEBCMMQGiJggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBKYXEIwxvakWCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEJhAQjDEBoiYIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgSmFxCMMb2pFgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBCYQEIwxAaImCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEphcQjDG9qRYJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEBCMMQGiJggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBKYXEIwxvakWCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEJhAQjDEBoiYIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgSmFxCMMb2pFgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBCYQEIwxAaImCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEphcQjDG9qRYJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEBCMMQGiJggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBKYXEIwxvakWCRAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEJhAQjDEBoiYIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgSmFxCMMb2pFgkQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBCYQEIwxAaImCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEphcQjDG9qRYJECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQmEBCMMQGiJggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBKYX+D9YdIGypKSLmAAAAABJRU5ErkJggg==)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"2wIAHwqH2_mo\"\n      },\n      \"source\": [\n        \"**Import Dependencies**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"9Byiv2Nc2MsK\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# check if notebook is in colab\\n\",\n        \"try:\\n\",\n        \"    # install ezkl\\n\",\n        \"    import google.colab\\n\",\n        \"    import subprocess\\n\",\n        \"    import sys\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n        \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n        \"\\n\",\n        \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n        \"except:\\n\",\n        \"    pass\\n\",\n        \"\\n\",\n        \"import ezkl\\n\",\n        \"import torch\\n\",\n        \"import datetime\\n\",\n        \"import pandas as pd\\n\",\n        \"import requests\\n\",\n        \"import json\\n\",\n        \"import os\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"osjj-0Ta3E8O\"\n      },\n      \"source\": [\n        \"**Create Computational Graph**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"x1vl9ZXF3EEW\",\n        \"outputId\": \"bda21d02-fe5f-4fb2-8106-f51a8e2e67aa\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"from torch import nn\\n\",\n        \"import torch\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"class Model(nn.Module):\\n\",\n        \"    def __init__(self):\\n\",\n        \"        super(Model, self).__init__()\\n\",\n        \"\\n\",\n        \"    # x is a time series maybe the ETH/USDC price, that we get from Uni Oracle\\n\",\n        \"    def forward(self, x):\\n\",\n        \"        # return [torch.var(x, unbiased=False, dim=[1,2])]\\n\",\n        \"        return [torch.mean(x)]\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"circuit = Model()\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"x = 0.1*torch.rand(1,*[1,20], requires_grad=True)\\n\",\n        \"\\n\",\n        \"# # print(torch.__version__)\\n\",\n        \"device = torch.device(\\\"cuda:0\\\" if torch.cuda.is_available() else \\\"cpu\\\")\\n\",\n        \"\\n\",\n        \"print(device)\\n\",\n        \"\\n\",\n        \"circuit.to(device)\\n\",\n        \"\\n\",\n        \"# Flips the neural net into inference mode\\n\",\n        \"circuit.eval()\\n\",\n        \"\\n\",\n        \"# Export the model\\n\",\n        \"torch.onnx.export(circuit,               # model being run\\n\",\n        \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n        \"                      \\\"lol.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n        \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n        \"                      opset_version=11,          # the ONNX version to export the model to\\n\",\n        \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n        \"                      input_names = ['input'],   # the model's input names\\n\",\n        \"                      output_names = ['output'], # the model's output names\\n\",\n        \"                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\\n\",\n        \"                                    'output' : {0 : 'batch_size'}})\\n\",\n        \"\\n\",\n        \"# export(circuit, input_shape=[1, 20])\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"E3qCeX-X5xqd\"\n      },\n      \"source\": [\n        \"**Set Data Source and Get Data**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"6RAMplxk5xPk\",\n        \"outputId\": \"bd2158fe-0c00-44fd-e632-6a3f70cdb7c9\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"def get_url(coin, currency, start, end):\\n\",\n        \"  url = f\\\"https://api.coingecko.com/api/v3/coins/{coin}/market_chart/range?vs_currency={currency}&from={start}&to={end}\\\"\\n\",\n        \"  return url\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"timenow = datetime.datetime.now()\\n\",\n        \"timenow_unix_sec = int(datetime.datetime.timestamp(timenow))\\n\",\n        \"time7days = timenow - datetime.timedelta(days=7)\\n\",\n        \"time7days_unix_sec = int(datetime.datetime.timestamp(time7days))\\n\",\n        \"\\n\",\n        \"print(timenow_unix_sec)\\n\",\n        \"print(time7days_unix_sec)\\n\",\n        \"\\n\",\n        \"eth_price_url = get_url(\\\"ethereum\\\", \\\"usd\\\", time7days_unix_sec, timenow_unix_sec)\\n\",\n        \"print(eth_price_url)\\n\",\n        \"\\n\",\n        \"data = requests.get(eth_price_url)\\n\",\n        \"print(data)\\n\",\n        \"\\n\",\n        \"new_data = {\\\"time\\\": [], \\\"prices\\\": []}\\n\",\n        \"\\n\",\n        \"for k, v in data.json().items():\\n\",\n        \"  if k == \\\"prices\\\":\\n\",\n        \"    for x in v:\\n\",\n        \"      new_data[\\\"time\\\"].append(x[0])\\n\",\n        \"      new_data[\\\"prices\\\"].append(x[1])\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 424\n        },\n        \"id\": \"WSj1Uxln65vf\",\n        \"outputId\": \"51422d71-9680-4b51-c4df-e400d20f988b\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"df = pd.DataFrame(new_data)\\n\",\n        \"df\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"eLJ7oirQ_HQR\"\n      },\n      \"source\": [\n        \"**EZKL Workflow**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# make an input.json file from the df above\\n\",\n        \"input_filename = os.path.join('input.json')\\n\",\n        \"# get the last 20 prices and make a list\\n\",\n        \"df_prices = df['prices'].tail(20).tolist()\\n\",\n        \"\\n\",\n        \"data = dict(input_data = [df_prices])\\n\",\n        \"\\n\",\n        \"    # Serialize data into file:\\n\",\n        \"json.dump( data, open(input_filename, 'w' ))\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"4MmE9SX66_Il\",\n        \"outputId\": \"16403639-66a4-4280-ac7f-6966b75de5a3\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# generate settings\\n\",\n        \"onnx_filename = os.path.join('lol.onnx')\\n\",\n        \"compiled_filename = os.path.join('lol.compiled')\\n\",\n        \"settings_filename = os.path.join('settings.json')\\n\",\n        \"srs_path = os.path.join('kzg.params')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"ezkl.gen_settings(onnx_filename, settings_filename)\\n\",\n        \"ezkl.calibrate_settings(\\n\",\n        \"    input_filename, onnx_filename, settings_filename, \\\"resources\\\", scales = [4])\\n\",\n        \"res = ezkl.get_srs(settings_filename)\\n\",\n        \"ezkl.compile_circuit(onnx_filename, compiled_filename, settings_filename)\\n\",\n        \"\\n\",\n        \"# show the settings.json\\n\",\n        \"with open(\\\"settings.json\\\") as f:\\n\",\n        \"  data = json.load(f)\\n\",\n        \"  json_formatted_str = json.dumps(data, indent=2)\\n\",\n        \"\\n\",\n        \"  print(json_formatted_str)\\n\",\n        \"\\n\",\n        \"assert os.path.exists(\\\"settings.json\\\")\\n\",\n        \"assert os.path.exists(\\\"input.json\\\")\\n\",\n        \"assert os.path.exists(\\\"lol.onnx\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 7,\n      \"metadata\": {\n        \"id\": \"fULvvnK7_CMb\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"pk_path = os.path.join('test.pk')\\n\",\n        \"vk_path = os.path.join('test.vk')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"# setup the proof\\n\",\n        \"res = ezkl.setup(\\n\",\n        \"        compiled_filename,\\n\",\n        \"        vk_path,\\n\",\n        \"        pk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"assert os.path.isfile(vk_path)\\n\",\n        \"assert os.path.isfile(pk_path)\\n\",\n        \"assert os.path.isfile(settings_filename)\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"\\n\",\n        \"witness_path = \\\"witness.json\\\"\\n\",\n        \"\\n\",\n        \"res = ezkl.gen_witness(input_filename, compiled_filename, witness_path)\\n\",\n        \"assert os.path.isfile(witness_path)\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"Oog3j6Kd-Wed\",\n        \"outputId\": \"5839d0c1-5b43-476e-c2f8-6707de562260\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# prove the zk circuit\\n\",\n        \"# GENERATE A PROOF\\n\",\n        \"proof_path = os.path.join('test.pf')\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"proof = ezkl.prove(\\n\",\n        \"        witness_path,\\n\",\n        \"        compiled_filename,\\n\",\n        \"        pk_path,\\n\",\n        \"        proof_path,\\n\",\n        \"        \\\"single\\\",\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"assert os.path.isfile(proof_path)\\n\",\n        \"\\n\",\n        \"# verify\\n\",\n        \"res = ezkl.verify(\\n\",\n        \"        proof_path,\\n\",\n        \"        settings_filename,\\n\",\n        \"        vk_path,\\n\",\n        \"    )\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"print(\\\"verified\\\")\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"W7tAa-DFAtvS\"\n      },\n      \"source\": [\n        \"# Part 2 (Using the ZK Computational Graph Onchain!)\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"8Ym91kaVAIB6\"\n      },\n      \"source\": [\n        \"**Now How Do We Do It Onchain?????**\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 339\n        },\n        \"id\": \"fodkNgwS70FM\",\n        \"outputId\": \"827b5efd-f74f-44de-c114-861b3a86daf2\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"# first we need to create evm verifier\\n\",\n        \"print(vk_path)\\n\",\n        \"print(settings_filename)\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"abi_path = 'test.abi'\\n\",\n        \"sol_code_path = 'test.sol'\\n\",\n        \"\\n\",\n        \"res = ezkl.create_evm_verifier(\\n\",\n        \"        vk_path,\\n\",\n        \"        settings_filename,\\n\",\n        \"        sol_code_path,\\n\",\n        \"        abi_path,\\n\",\n        \"    )\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# Make sure anvil is running locally first\\n\",\n        \"# run with $ anvil -p 3030\\n\",\n        \"# we use the default anvil node here\\n\",\n        \"import json\\n\",\n        \"\\n\",\n        \"address_path = os.path.join(\\\"address.json\\\")\\n\",\n        \"\\n\",\n        \"res = ezkl.deploy_evm(\\n\",\n        \"    address_path,\\n\",\n        \"    sol_code_path,\\n\",\n        \"    'http://127.0.0.1:3030'\\n\",\n        \")\\n\",\n        \"\\n\",\n        \"assert res == True\\n\",\n        \"\\n\",\n        \"with open(address_path, 'r') as file:\\n\",\n        \"    addr = file.read().rstrip()\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {},\n      \"outputs\": [],\n      \"source\": [\n        \"# read the address from addr_path\\n\",\n        \"addr = None\\n\",\n        \"with open(address_path, 'r') as f:\\n\",\n        \"    addr = f.read()\\n\",\n        \"\\n\",\n        \"res = ezkl.verify_evm(\\n\",\n        \"    addr,\\n\",\n        \"    proof_path,\\n\",\n        \"    \\\"http://127.0.0.1:3030\\\"\\n\",\n        \")\\n\",\n        \"assert res == True\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"mPFmUizd_gCp\"\n      },\n      \"outputs\": [],\n      \"source\": []\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.9.15\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/voice_judge.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"# Voice judgoor\\n\",\n                \"\\n\",\n                \"Here we showcase a full-end-to-end flow of:\\n\",\n                \"1. training a model for a specific task (judging voices)\\n\",\n                \"2. creating a proof of judgment\\n\",\n                \"3. creating and deploying an evm verifier\\n\",\n                \"4. verifying the proof of judgment using the verifier\\n\",\n                \"\\n\",\n                \"First we download a few voice related datasets from kaggle, which are all labelled using the same emotion and tone labelling standard.\\n\",\n                \"\\n\",\n                \"We have 8 emotions in both speaking and singing datasets: neutral, calm, happy, sad, angry, fear, disgust, surprise.\\n\",\n                \"\\n\",\n                \"To download the dataset make sure you have the kaggle cli installed in your local env `pip install kaggle`. Make sure you set up your `kaggle.json` file as detailed [here](https://www.kaggle.com/docs/api#getting-started-installation-&-authentication).\\n\",\n                \"Then run the associated `voice_data.sh` data download script: `sh voice_data.sh`.\\n\",\n                \"\\n\",\n                \"Make sure you set the `VOICE_DATA_DIR` variables to point to the directory the `voice_data.sh` script has downloaded to. This script also accepts an argument to download to a specific directory: `sh voice_data.sh /path/to/voice/data`.\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"import os\\n\",\n                \"# os.environ[\\\"VOICE_DATA_DIR\\\"] = \\\".\\\"\\n\",\n                \"\\n\",\n                \"voice_data_dir = os.environ.get('VOICE_DATA_DIR')\\n\",\n                \"\\n\",\n                \"#  if is none set to \\\"\\\"\\n\",\n                \"if voice_data_dir is None:\\n\",\n                \"    voice_data_dir = \\\"\\\"\\n\",\n                \"\\n\",\n                \"print(\\\"voice_data_dir: \\\", voice_data_dir)\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### TESS Dataset\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"from torch import nn\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"import json\\n\",\n                \"import pandas as pd\\n\",\n                \"import logging\\n\",\n                \"\\n\",\n                \"# read in VOICE_DATA_DIR from environment variable\\n\",\n                \"\\n\",\n                \"# FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\\n\",\n                \"# logging.basicConfig(format=FORMAT)\\n\",\n                \"# logging.getLogger().setLevel(logging.INFO)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Tess = os.path.join(voice_data_dir, \\\"data/TESS/\\\")\\n\",\n                \"\\n\",\n                \"tess = os.listdir(Tess)\\n\",\n                \"\\n\",\n                \"emotions = []\\n\",\n                \"files = []\\n\",\n                \"\\n\",\n                \"for item in tess:\\n\",\n                \"    items = os.listdir(Tess + item)\\n\",\n                \"    for file in items:\\n\",\n                \"        part = file.split('.')[0]\\n\",\n                \"        part = part.split('_')[2]\\n\",\n                \"        if part == 'ps':\\n\",\n                \"            emotions.append('surprise')\\n\",\n                \"        else:\\n\",\n                \"            emotions.append(part)\\n\",\n                \"        files.append(Tess + item + '/' + file)\\n\",\n                \"\\n\",\n                \"tess_df = pd.concat([pd.DataFrame(emotions, columns=['Emotions']), pd.DataFrame(files, columns=['Files'])], axis=1)\\n\",\n                \"tess_df\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### RAVDESS SONG dataset\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"Ravdess = os.path.join(voice_data_dir, \\\"data/RAVDESS_SONG/audio_song_actors_01-24/\\\")\\n\",\n                \"\\n\",\n                \"ravdess_list = os.listdir(Ravdess)\\n\",\n                \"\\n\",\n                \"files = []\\n\",\n                \"emotions = []\\n\",\n                \"\\n\",\n                \"for item in ravdess_list:\\n\",\n                \"    actor = os.listdir(Ravdess + item)\\n\",\n                \"    for file in actor:\\n\",\n                \"        name = file.split('.')[0]\\n\",\n                \"        parts = name.split('-')\\n\",\n                \"        emotions.append(int(parts[2]))\\n\",\n                \"        files.append(Ravdess + item + '/' + file)\\n\",\n                \"\\n\",\n                \"emotion_data = pd.DataFrame(emotions, columns=['Emotions'])\\n\",\n                \"files_data = pd.DataFrame(files, columns=['Files'])\\n\",\n                \"\\n\",\n                \"ravdess_song_df = pd.concat([emotion_data, files_data], axis=1)\\n\",\n                \"\\n\",\n                \"ravdess_song_df.Emotions.replace({1:'neutral', 2:'calm', 3:'happy', 4:'sad', 5:'angry', 6:'fear', 7:'disgust', 8:'surprise'}, inplace=True)\\n\",\n                \"\\n\",\n                \"ravdess_song_df\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### RAVDESS SPEECH Dataset\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"Ravdess = os.path.join(voice_data_dir, \\\"data/RAVDESS_SPEECH/audio_speech_actors_01-24/\\\")\\n\",\n                \"\\n\",\n                \"ravdess_list = os.listdir(Ravdess)\\n\",\n                \"\\n\",\n                \"files = []\\n\",\n                \"emotions = []\\n\",\n                \"\\n\",\n                \"for item in ravdess_list:\\n\",\n                \"    actor = os.listdir(Ravdess + item)\\n\",\n                \"    for file in actor:\\n\",\n                \"        name = file.split('.')[0]\\n\",\n                \"        parts = name.split('-')\\n\",\n                \"        emotions.append(int(parts[2]))\\n\",\n                \"        files.append(Ravdess + item + '/' + file)\\n\",\n                \"        \\n\",\n                \"emotion_data = pd.DataFrame(emotions, columns=['Emotions'])\\n\",\n                \"files_data = pd.DataFrame(files, columns=['Files'])\\n\",\n                \"\\n\",\n                \"ravdess_df = pd.concat([emotion_data, files_data], axis=1)\\n\",\n                \"\\n\",\n                \"ravdess_df.Emotions.replace({1:'neutral', 2:'calm', 3:'happy', 4:'sad', 5:'angry', 6:'fear', 7:'disgust', 8:'surprise'}, inplace=True)\\n\",\n                \"\\n\",\n                \"ravdess_df\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### CREMA Dataset\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"Crema = os.path.join(voice_data_dir, \\\"data/CREMA-D/\\\")\\n\",\n                \"\\n\",\n                \"crema = os.listdir(Crema)\\n\",\n                \"emotions = []\\n\",\n                \"files = []\\n\",\n                \"\\n\",\n                \"for item in crema:\\n\",\n                \"    files.append(Crema + item)\\n\",\n                \"    \\n\",\n                \"    parts = item.split('_')\\n\",\n                \"    if parts[2] == 'SAD':\\n\",\n                \"        emotions.append('sad')\\n\",\n                \"    elif parts[2] == 'ANG':\\n\",\n                \"        emotions.append('angry')\\n\",\n                \"    elif parts[2] == 'DIS':\\n\",\n                \"        emotions.append('disgust')\\n\",\n                \"    elif parts[2] == 'FEA':\\n\",\n                \"        emotions.append('fear')\\n\",\n                \"    elif parts[2] == 'HAP':\\n\",\n                \"        emotions.append('happy')\\n\",\n                \"    elif parts[2] == 'NEU':\\n\",\n                \"        emotions.append('neutral')\\n\",\n                \"    else :\\n\",\n                \"        emotions.append('unknown')\\n\",\n                \"        \\n\",\n                \"emotions_data = pd.DataFrame(emotions, columns=['Emotions'])\\n\",\n                \"files_data = pd.DataFrame(files, columns=['Files'])\\n\",\n                \"\\n\",\n                \"crema_df = pd.concat([emotions_data, files_data], axis=1)\\n\",\n                \"\\n\",\n                \"crema_df\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### SAVEE Dataset\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"Savee = os.path.join(voice_data_dir,\\\"data/SAVEE/\\\")\\n\",\n                \"\\n\",\n                \"savee = os.listdir(Savee)\\n\",\n                \"\\n\",\n                \"emotions = []\\n\",\n                \"files = []\\n\",\n                \"\\n\",\n                \"for item in savee:\\n\",\n                \"    files.append(Savee + item)\\n\",\n                \"    part = item.split('_')[1]\\n\",\n                \"    ele = part[:-6]\\n\",\n                \"    if ele == 'a':\\n\",\n                \"        emotions.append('angry')\\n\",\n                \"    elif ele == 'd':\\n\",\n                \"        emotions.append('disgust')\\n\",\n                \"    elif ele == 'f':\\n\",\n                \"        emotions.append('fear')\\n\",\n                \"    elif ele == 'h':\\n\",\n                \"        emotions.append('happy')\\n\",\n                \"    elif ele == 'n':\\n\",\n                \"        emotions.append('neutral')\\n\",\n                \"    elif ele == 'sa':\\n\",\n                \"        emotions.append('sad')\\n\",\n                \"    else:\\n\",\n                \"        emotions.append('surprise')\\n\",\n                \"\\n\",\n                \"savee_df = pd.concat([pd.DataFrame(emotions, columns=['Emotions']), pd.DataFrame(files, columns=['Files'])], axis=1)\\n\",\n                \"savee_df\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Combining all datasets\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"df = pd.concat([ravdess_df, ravdess_song_df, crema_df, tess_df, savee_df], axis = 0)\\n\",\n                \"# relabel indices\\n\",\n                \"df.index = range(len(df.index))\\n\",\n                \"df.to_csv(\\\"df.csv\\\",index=False)\\n\",\n                \"df\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import seaborn as sns\\n\",\n                \"sns.histplot(data=df, x=\\\"Emotions\\\")\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Training \\n\",\n                \"\\n\",\n                \"Here we convert all audio files into 2D frequency-domain spectrograms so that we can leverage convolutional neural networks, which tend to be more efficient than time-series model like RNNs or LSTMs.\\n\",\n                \"We thus: \\n\",\n                \"1. Extract the mel spectrogram from each of the audio recordings. \\n\",\n                \"2. Rescale each of these to the decibel (DB) scale. \\n\",\n                \"3. Define the model as the following model: `(x) -> (conv) -> (relu) -> (linear) -> (y)`\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"You may notice that we introduce a second computational graph `(key) -> (key)`. The reasons for this are to do with MEV, and if you are not interested you can skip the following paragraph. \\n\",\n                \"\\n\",\n                \"Let's say that obtaining a high score from the judge and then submitting said score to the EVM verifier could result in the issuance of a reward (financial or otherwise). There is an incentive then for MEV bots to scalp any issued valid proof and submit a duplicate transaction with the same proof to the verifier contract in the hopes of obtaining the reward before the original issuer. Here we add `(key) -> (key)` such that the transaction creator's public key / address is both a private input AND a public input to the proof. As such the on-chain verification only succeeds if the key passed in during proof time is also passed in as a public input to the contract. The reward issued by the contract can then be irrevocably tied to that key such that even if the proof is submitted by another actor, the reward would STILL go to the original singer / transaction issuer. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"import librosa\\n\",\n                \"import numpy as np\\n\",\n                \"import matplotlib.pyplot as plt\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"#stft extraction from augmented data\\n\",\n                \"def extract_mel_spec(filename):\\n\",\n                \"    x,sr=librosa.load(filename,duration=3,offset=0.5)\\n\",\n                \"    X = librosa.feature.melspectrogram(y=x, sr=sr)\\n\",\n                \"    Xdb = librosa.power_to_db(X, ref=np.max)\\n\",\n                \"    Xdb = Xdb.reshape(1,128,-1)\\n\",\n                \"    return Xdb\\n\",\n                \"\\n\",\n                \"Xdb=df.iloc[:,1].apply(lambda x: extract_mel_spec(x))\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we convert label to a number between 0 and 1 where 1 is pleasant surprised and 0 is disgust and the rest are floats in between. The model loves pleasantly surprised voices and hates disgust ;) \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# get max size\\n\",\n                \"max_size = 0\\n\",\n                \"for i in range(len(Xdb)):\\n\",\n                \"    if Xdb[i].shape[2] > max_size:\\n\",\n                \"        max_size = Xdb[i].shape[2]\\n\",\n                \"\\n\",\n                \"# 0 pad 2nd dim to max size\\n\",\n                \"Xdb=Xdb.apply(lambda x: np.pad(x,((0,0),(0,0),(0,max_size-x.shape[2]))))\\n\",\n                \"\\n\",\n                \"Xdb=pd.DataFrame(Xdb)\\n\",\n                \"Xdb['label'] = df['Emotions']\\n\",\n                \"# convert label to a number between 0 and 1 where 1 is pleasant surprised and 0 is disgust and the rest are floats in betwee\\n\",\n                \"Xdb['label'] = Xdb['label'].apply(lambda x: 1 if x=='surprise' else 0 if x=='disgust' else 0.2 if x=='fear' else 0.4 if x=='happy' else 0.6 if x=='sad' else 0.8)\\n\",\n                \"\\n\",\n                \"Xdb.iloc[0,0][0].shape\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import torch\\n\",\n                \"# Defines the model\\n\",\n                \"# we got convs, we got relu, we got linear layers\\n\",\n                \"# What else could one want ????\\n\",\n                \"\\n\",\n                \"class MyModel(nn.Module):\\n\",\n                \"    def __init__(self):\\n\",\n                \"        super(MyModel, self).__init__()\\n\",\n                \"\\n\",\n                \"        self.conv1 = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=5, stride=4)\\n\",\n                \"\\n\",\n                \"        self.d1 = nn.Linear(992, 1)\\n\",\n                \"\\n\",\n                \"        self.sigmoid = nn.Sigmoid()\\n\",\n                \"        self.relu = nn.ReLU()\\n\",\n                \"\\n\",\n                \"    def forward(self, key, x):\\n\",\n                \"        # 32x1x28x28 => 32x32x26x26\\n\",\n                \"        x = self.conv1(x)\\n\",\n                \"        x = self.relu(x)\\n\",\n                \"        x = x.flatten(start_dim=1)\\n\",\n                \"        x = self.d1(x)\\n\",\n                \"        x = self.sigmoid(x)\\n\",\n                \"\\n\",\n                \"        return [key, x]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"circuit = MyModel()\\n\",\n                \"\\n\",\n                \"output = circuit(0, torch.tensor(Xdb.iloc[0,0][0].reshape(1,1,128,130)))\\n\",\n                \"\\n\",\n                \"output\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we leverage the classic Adam optimizer, coupled with 0.001 weight decay so as to regularize the model. The weight decay (a.k.a L2 regularization) can also help on the zk-circuit end of things in that it prevents inputs to Halo2 lookup tables from falling out of range (lookup tables are how we represent non-linearities like ReLU and Sigmoid inside our circuits). \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"from tqdm import tqdm\\n\",\n                \"\\n\",\n                \"# Train the model using pytorch\\n\",\n                \"n_epochs = 10    # number of epochs to run\\n\",\n                \"batch_size = 10  # size of each batch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"loss_fn = nn.MSELoss()  #MSE\\n\",\n                \"# adds l2 regularization\\n\",\n                \"optimizer = torch.optim.Adam(circuit.parameters(), lr=0.001, weight_decay=0.001)\\n\",\n                \"\\n\",\n                \"# randomly shuffle dataset\\n\",\n                \"Xdb = Xdb.sample(frac=1).reset_index(drop=True)\\n\",\n                \"\\n\",\n                \"# split into train and test and validation sets with 80% train, 10% test, 10% validation\\n\",\n                \"train = Xdb.iloc[:int(len(Xdb)*0.8)]\\n\",\n                \"test = Xdb.iloc[int(len(Xdb)*0.8):int(len(Xdb)*0.9)]\\n\",\n                \"val = Xdb.iloc[int(len(Xdb)*0.9):]\\n\",\n                \"\\n\",\n                \"batches_per_epoch = len(train)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"def get_loss(Xbatch, ybatch):\\n\",\n                \"    y_pred = circuit(0, Xbatch)[1]\\n\",\n                \"    loss = loss_fn(y_pred, ybatch)\\n\",\n                \"    return loss\\n\",\n                \"\\n\",\n                \"for epoch in range(n_epochs):\\n\",\n                \"    # X is a torch Variable\\n\",\n                \"    permutation = torch.randperm(batches_per_epoch)\\n\",\n                \"\\n\",\n                \"    with tqdm(range(batches_per_epoch), unit=\\\"batch\\\", mininterval=0) as bar:\\n\",\n                \"        bar.set_description(f\\\"Epoch {epoch}\\\")\\n\",\n                \"        for i in bar:\\n\",\n                \"            start = i * batch_size\\n\",\n                \"            # take a batch\\n\",\n                \"            indices = np.random.choice(batches_per_epoch, batch_size)\\n\",\n                \"\\n\",\n                \"            data = np.concatenate(train.iloc[indices.tolist(),0].values)\\n\",\n                \"            labels = train.iloc[indices.tolist(),1].values.astype(np.float32)\\n\",\n                \"\\n\",\n                \"            data = data.reshape(batch_size,1,128,130)\\n\",\n                \"            labels = labels.reshape(batch_size,1)\\n\",\n                \"\\n\",\n                \"            # convert to tensors\\n\",\n                \"            Xbatch = torch.tensor(data)\\n\",\n                \"            ybatch = torch.tensor(labels)\\n\",\n                \"\\n\",\n                \"            # forward pass\\n\",\n                \"            loss = get_loss(Xbatch, ybatch)\\n\",\n                \"            # backward pass\\n\",\n                \"            optimizer.zero_grad()\\n\",\n                \"            loss.backward()\\n\",\n                \"            # update weights\\n\",\n                \"            optimizer.step()\\n\",\n                \"\\n\",\n                \"            bar.set_postfix(\\n\",\n                \"                batch_loss=float(loss),\\n\",\n                \"            )\\n\",\n                \"        # get validation loss\\n\",\n                \"        val_data = np.concatenate(val.iloc[:,0].values)\\n\",\n                \"        val_labels = val.iloc[:,1].values.astype(np.float32)\\n\",\n                \"        val_data = val_data.reshape(len(val),1,128,130)\\n\",\n                \"        val_labels = val_labels.reshape(len(val),1)\\n\",\n                \"        val_loss = get_loss(torch.tensor(val_data), torch.tensor(val_labels))\\n\",\n                \"        print(f\\\"Validation loss: {val_loss}\\\")\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# get validation loss\\n\",\n                \"test_data = np.concatenate(test.iloc[:,0].values)\\n\",\n                \"test_labels = val.iloc[:,1].values.astype(np.float32)\\n\",\n                \"test_data = val_data.reshape(len(val),1,128,130)\\n\",\n                \"test_labels = val_labels.reshape(len(val),1)\\n\",\n                \"test_loss = get_loss(torch.tensor(test_data), torch.tensor(test_labels))\\n\",\n                \"print(f\\\"Test loss: {test_loss}\\\")\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": []\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"#\\n\",\n                \"val_data = {\\n\",\n                \"    \\\"input_data\\\": [np.zeros(100).tolist(), np.concatenate(val.iloc[:100,0].values).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"# save as json file\\n\",\n                \"with open(\\\"val_data.json\\\", \\\"w\\\") as f:\\n\",\n                \"    json.dump(val_data, f)\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"x = 0.1*torch.rand(1,*[1, 128, 130], requires_grad=True)\\n\",\n                \"key = torch.rand(1,*[1], requires_grad=True)\\n\",\n                \"\\n\",\n                \"# Flips the neural net into inference mode\\n\",\n                \"circuit.eval()\\n\",\n                \"\\n\",\n                \"    # Export the model\\n\",\n                \"torch.onnx.export(circuit,               # model being run\\n\",\n                \"                      (key, x),                   # model input (or a tuple for multiple inputs)\\n\",\n                \"                      \\\"network.onnx\\\",            # where to save the model (can be a file or file-like object)\\n\",\n                \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n                \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n                \"                      input_names = ['input'],   # the model's input names\\n\",\n                \"                      output_names = ['output'], # the model's output names\\n\",\n                \"                      dynamic_axes={'input' : {0 : 'batch_size'},\\n\",\n                \"                                    'input.1' : {0 : 'batch_size'}, # variable length axes\\n\",\n                \"                                    'output' : {0 : 'batch_size'}})\\n\",\n                \"\\n\",\n                \"key_array = ((key).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_data = [key_array, data_array])\\n\",\n                \"\\n\",\n                \"    # Serialize data into file:\\n\",\n                \"json.dump( data, open(\\\"input.json\\\", 'w' ))\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# ezkl.export(circuit, input_shape = [[1], [1025, 130]], run_gen_witness=False, run_calibrate_settings=False)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we set the visibility of the different parts of the circuit, whereby the model params and the outputs of the computational graph (the key and the judgment) are public\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import ezkl\\n\",\n                \"import os \\n\",\n                \"\\n\",\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"srs_path = os.path.join('kzg.params')\\n\",\n                \"data_path = os.path.join('input.json')\\n\",\n                \"val_data = os.path.join('val_data.json')\\n\",\n                \"\\n\",\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.input_visibility = \\\"private\\\"\\n\",\n                \"run_args.param_visibility = \\\"fixed\\\"\\n\",\n                \"run_args.output_visibility = \\\"public\\\"\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https://zcash.github.io/halo2/design/proving-system/lookup.html)), it is often best to _calibrate_ this settings file as some data can fall out of range of these lookups.\\n\",\n                \"\\n\",\n                \"You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we use the validation dataset we used during training. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(val_data, model_path, settings_path, \\\"resources\\\", scales = [4])\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n                \"\\n\",\n                \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.get_srs(settings_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"We now need to generate the (partial) circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"witness_path = \\\"witness.json\\\"\\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"As a sanity check we can run a mock proof. This just checks that all the constraints are valid. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.mock(witness_path, compiled_model_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!export RUST_LOG=trace\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"Now we generate a full proof. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"And verify it as a sanity check. \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"import os\\n\",\n                \"abi_path = 'test.abi'\\n\",\n                \"sol_code_path = 'test.sol'\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"srs_path = os.path.join('kzg.params')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.create_evm_verifier(\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"        settings_path,\\n\",\n                \"        sol_code_path,\\n\",\n                \"        abi_path,\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"### Verify if the Verifier Works Locally\"\n            ]\n        },\n        {\n            \"attachments\": {},\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [\n                \"#### Deploy The Contract\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# Make sure anvil is running locally first\\n\",\n                \"# run with $ anvil -p 3030\\n\",\n                \"# we use the default anvil node here\\n\",\n                \"import json\\n\",\n                \"\\n\",\n                \"address_path = os.path.join(\\\"address.json\\\")\\n\",\n                \"\\n\",\n                \"res = ezkl.deploy_evm(\\n\",\n                \"    address_path,\\n\",\n                \"    sol_code_path,\\n\",\n                \"    'http://127.0.0.1:3030'\\n\",\n                \")\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"\\n\",\n                \"with open(address_path, 'r') as file:\\n\",\n                \"    addr = file.read().rstrip()\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# make sure anvil is running locally\\n\",\n                \"# $ anvil -p 3030\\n\",\n                \"\\n\",\n                \"res = ezkl.verify_evm(\\n\",\n                \"    addr,\\n\",\n                \"    proof_path,\\n\",\n                \"    \\\"http://127.0.0.1:3030\\\"\\n\",\n                \")\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": []\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/world_rotation.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"attachments\": {},\n   \"cell_type\": \"markdown\",\n   \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n   \"metadata\": {},\n   \"source\": [\n    \"## World rotation\\n\",\n    \"\\n\",\n    \"Here we demonstrate how to use the EZKL package to rotate an on-chain world. \\n\",\n    \"\\n\",\n    \"![zk-gaming-diagram-transformed](https://hackmd.io/_uploads/HkApuQGV6.png)\\n\",\n    \"> **A typical ZK application flow**. For the shape rotators out there \u2014 this is an easily digestible example. A user computes a ZK-proof that they have calculated a valid rotation of a world. They submit this proof to a verifier contract which governs an on-chain world, along with a new set of coordinates, and the world rotation updates. Observe that it\u2019s possible for one player to initiate a *global* change.\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"95613ee9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# check if notebook is in colab\\n\",\n    \"try:\\n\",\n    \"    # install ezkl\\n\",\n    \"    import google.colab\\n\",\n    \"    import subprocess\\n\",\n    \"    import sys\\n\",\n    \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n    \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n    \"\\n\",\n    \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n    \"except:\\n\",\n    \"    pass\\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from torch import nn\\n\",\n    \"import ezkl\\n\",\n    \"import os\\n\",\n    \"import json\\n\",\n    \"import torch\\n\",\n    \"import math\\n\",\n    \"\\n\",\n    \"# these are constants for the rotation\\n\",\n    \"phi = torch.tensor(5 * math.pi / 180)\\n\",\n    \"s = torch.sin(phi)\\n\",\n    \"c = torch.cos(phi)\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"class RotateStuff(nn.Module):\\n\",\n    \"    def __init__(self):\\n\",\n    \"        super(RotateStuff, self).__init__()\\n\",\n    \"\\n\",\n    \"        # create a rotation matrix -- the matrix is constant and is transposed for convenience\\n\",\n    \"        self.rot = torch.stack([torch.stack([c, -s]),\\n\",\n    \"                   torch.stack([s, c])]).t()\\n\",\n    \"\\n\",\n    \"    def forward(self, x):\\n\",\n    \"        x_rot = x @ self.rot   # same as x_rot = (rot @ x.t()).t() due to rot in O(n) (SO(n) even)\\n\",\n    \"        return x_rot\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"circuit = RotateStuff()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"This will showcase the principle directions of rotation by plotting the rotation of a single unit vector.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from matplotlib import pyplot\\n\",\n    \"pyplot.figure(figsize=(3, 3))\\n\",\n    \"pyplot.arrow(0, 0, 1, 0, width=0.02, alpha=0.5)\\n\",\n    \"pyplot.arrow(0, 0, 0, 1, width=0.02, alpha=0.5)\\n\",\n    \"pyplot.arrow(0, 0, circuit.rot[0, 0].item(), circuit.rot[0, 1].item(), width=0.02)\\n\",\n    \"pyplot.arrow(0, 0, circuit.rot[1, 0].item(), circuit.rot[1, 1].item(), width=0.02)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b37637c4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model_path = os.path.join('network.onnx')\\n\",\n    \"compiled_model_path = os.path.join('network.compiled')\\n\",\n    \"pk_path = os.path.join('test.pk')\\n\",\n    \"vk_path = os.path.join('test.vk')\\n\",\n    \"settings_path = os.path.join('settings.json')\\n\",\n    \"srs_path = os.path.join('kzg.srs')\\n\",\n    \"witness_path = os.path.join('witness.json')\\n\",\n    \"data_path = os.path.join('input.json')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"82db373a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"\\n\",\n    \"\\n\",\n    \"# initial principle vectors for the rotation are as in the plot above\\n\",\n    \"x = torch.tensor([[1, 0], [0, 1]], dtype=torch.float32)\\n\",\n    \"\\n\",\n    \"# Flips the neural net into inference mode\\n\",\n    \"circuit.eval()\\n\",\n    \"\\n\",\n    \"    # Export the model\\n\",\n    \"torch.onnx.export(circuit,               # model being run\\n\",\n    \"                      x,                   # model input (or a tuple for multiple inputs)\\n\",\n    \"                      model_path,            # where to save the model (can be a file or file-like object)\\n\",\n    \"                      export_params=True,        # store the trained parameter weights inside the model file\\n\",\n    \"                      opset_version=10,          # the ONNX version to export the model to\\n\",\n    \"                      do_constant_folding=True,  # whether to execute constant folding for optimization\\n\",\n    \"                      input_names = ['input'],   # the model's input names\\n\",\n    \"                      output_names = ['output'], # the model's output names\\n\",\n    \"                      )\\n\",\n    \"\\n\",\n    \"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n    \"\\n\",\n    \"data = dict(input_data = [data_array])\\n\",\n    \"\\n\",\n    \"    # Serialize data into file:\\n\",\n    \"json.dump( data, open(data_path, 'w' ))\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### World rotation in 2D on-chain\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For demo purposes we deploy these coordinates to a contract running locally using Anvil. This creates our on-chain world. We then rotate the world using the EZKL package and submit the proof to the contract. The contract then updates the world rotation. For demo purposes we do this repeatedly, rotating the world by 1 transform each time.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import subprocess\\n\",\n    \"import time\\n\",\n    \"import threading\\n\",\n    \"\\n\",\n    \"# make sure anvil is running locally\\n\",\n    \"# $ anvil -p 3030\\n\",\n    \"\\n\",\n    \"RPC_URL = \\\"http://localhost:3030\\\"\\n\",\n    \"\\n\",\n    \"# Save process globally\\n\",\n    \"anvil_process = None\\n\",\n    \"\\n\",\n    \"def start_anvil():\\n\",\n    \"    global anvil_process\\n\",\n    \"    if anvil_process is None:\\n\",\n    \"        anvil_process = subprocess.Popen([\\\"anvil\\\", \\\"-p\\\", \\\"3030\\\", \\\"--code-size-limit=41943040\\\"])\\n\",\n    \"        if anvil_process.returncode is not None:\\n\",\n    \"            raise Exception(\\\"failed to start anvil process\\\")\\n\",\n    \"        time.sleep(3)\\n\",\n    \"\\n\",\n    \"def stop_anvil():\\n\",\n    \"    global anvil_process\\n\",\n    \"    if anvil_process is not None:\\n\",\n    \"        anvil_process.terminate()\\n\",\n    \"        anvil_process = None\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We define our `PyRunArgs` objects which contains the visibility parameters for out model. \\n\",\n    \"- `input_visibility` defines the visibility of the model inputs\\n\",\n    \"- `param_visibility` defines the visibility of the model weights and constants and parameters \\n\",\n    \"- `output_visibility` defines the visibility of the model outputs\\n\",\n    \"\\n\",\n    \"Here we create the following setup:\\n\",\n    \"- `input_visibility`: \\\"public\\\"\\n\",\n    \"- `param_visibility`: \\\"fixed\\\"\\n\",\n    \"- `output_visibility`: public\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d5e374a2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"py_run_args = ezkl.PyRunArgs()\\n\",\n    \"py_run_args.input_visibility = \\\"public\\\"\\n\",\n    \"py_run_args.output_visibility = \\\"public\\\"\\n\",\n    \"py_run_args.param_visibility = \\\"private\\\" # private by default\\n\",\n    \"py_run_args.scale_rebase_multiplier = 10\\n\",\n    \"\\n\",\n    \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3aa4f090\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n    \"assert res == True\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We also define a contract that holds out test data. This contract will contain in its storage the data that we will read from and attest to. In production you would not need to set up a local anvil instance. Instead you would replace RPC_URL with the actual RPC endpoint of the chain you are deploying your verifiers too, reading from the data on said chain.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ezkl.setup_test_evm_witness(\\n\",\n    \"    data_path,\\n\",\n    \"    compiled_model_path,\\n\",\n    \"    # we write the call data to the same file as the input data\\n\",\n    \"    data_path,\\n\",\n    \"    input_source=ezkl.PyTestDataSource.OnChain,\\n\",\n    \"    output_source=ezkl.PyTestDataSource.File,\\n\",\n    \"    rpc_url=RPC_URL)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https://blog.ethereum.org/2023/01/16/announcing-kzg-ceremony). The `get_srs` command retrieves a correctly sized SRS given the calibrated settings file from [here](https://github.com/han0110/halo2-kzg-srs). \\n\",\n    \"\\n\",\n    \"These SRS were generated with [this](https://github.com/privacy-scaling-explorations/perpetualpowersoftau) ceremony. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8b74dcee\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# srs path\\n\",\n    \"res = ezkl.get_srs( settings_path)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"18c8b7c7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# now generate the witness file \\n\",\n    \"\\n\",\n    \"witness = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n    \"assert os.path.isfile(witness_path)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b1c561a8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"res = ezkl.setup(\\n\",\n    \"        compiled_model_path,\\n\",\n    \"        vk_path,\\n\",\n    \"        pk_path,\\n\",\n    \"        \\n\",\n    \"    )\\n\",\n    \"\\n\",\n    \"assert res == True\\n\",\n    \"assert os.path.isfile(vk_path)\\n\",\n    \"assert os.path.isfile(pk_path)\\n\",\n    \"assert os.path.isfile(settings_path)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We can now create an EVM verifier contract from our circuit. This contract will be deployed to the chain we are using. In this case we are using a local anvil instance.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"abi_path = 'test.abi'\\n\",\n    \"sol_code_path = 'test.sol'\\n\",\n    \"\\n\",\n    \"res = ezkl.create_evm_verifier(\\n\",\n    \"        vk_path,\\n\",\n    \"        \\n\",\n    \"        settings_path,\\n\",\n    \"        sol_code_path,\\n\",\n    \"        abi_path,\\n\",\n    \"    )\\n\",\n    \"assert res == True\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\\n\",\n    \"\\n\",\n    \"addr_path_verifier = \\\"addr_verifier.txt\\\"\\n\",\n    \"\\n\",\n    \"res = ezkl.deploy_evm(\\n\",\n    \"    addr_path_verifier,\\n\",\n    \"    sol_code_path,\\n\",\n    \"    'http://127.0.0.1:3030'\\n\",\n    \")\\n\",\n    \"\\n\",\n    \"assert res == True\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"With the vanilla verifier deployed, we can now create the data attestation contract, which will read in the instances from the calldata to the verifier, attest to them, call the verifier and then return the result. \\n\",\n    \"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"abi_path = 'test.abi'\\n\",\n    \"sol_code_path = 'test.sol'\\n\",\n    \"input_path = 'input.json'\\n\",\n    \"\\n\",\n    \"res = ezkl.create_evm_data_attestation(\\n\",\n    \"        input_path,\\n\",\n    \"        settings_path,\\n\",\n    \"        sol_code_path,\\n\",\n    \"        abi_path,\\n\",\n    \"    )\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"addr_path_da = \\\"addr_da.txt\\\"\\n\",\n    \"\\n\",\n    \"res = ezkl.deploy_da_evm(\\n\",\n    \"        addr_path_da,\\n\",\n    \"        input_path,\\n\",\n    \"        settings_path,\\n\",\n    \"        sol_code_path,\\n\",\n    \"        RPC_URL,\\n\",\n    \"    )\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Now we can pull in the data from the contract and calculate a new set of coordinates. We then rotate the world by 1 transform and submit the proof to the contract. The contract could then update the world rotation (logic not inserted here). For demo purposes we do this repeatedly, rotating the world by 1 transform. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c384cbc8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# GENERATE A PROOF\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"proof_path = os.path.join('test.pf')\\n\",\n    \"\\n\",\n    \"res = ezkl.prove(\\n\",\n    \"        witness_path,\\n\",\n    \"        compiled_model_path,\\n\",\n    \"        pk_path,\\n\",\n    \"        proof_path,\\n\",\n    \"        \\n\",\n    \"        \\\"single\\\",\\n\",\n    \"    )\\n\",\n    \"\\n\",\n    \"print(res)\\n\",\n    \"assert os.path.isfile(proof_path)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Call the view only verify method on the contract to verify the proof. Since it is a view function this is safe to use in production since you don't have to pass your private key.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"76f00d41\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# read the verifier address\\n\",\n    \"addr_verifier = None\\n\",\n    \"with open(addr_path_verifier, 'r') as f:\\n\",\n    \"    addr = f.read()\\n\",\n    \"#read the data attestation address\\n\",\n    \"addr_da = None\\n\",\n    \"with open(addr_path_da, 'r') as f:\\n\",\n    \"    addr_da = f.read()\\n\",\n    \"\\n\",\n    \"res = ezkl.verify_evm(\\n\",\n    \"    addr,\\n\",\n    \"    proof_path,\\n\",\n    \"    RPC_URL,\\n\",\n    \"    addr_da,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"As a sanity check lets plot the rotations of the unit vectors. We can see that the unit vectors rotate as expected by the output of the circuit. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"witness['outputs'][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"settings = json.load(open(settings_path, 'r'))\\n\",\n    \"out_scale = settings[\\\"model_output_scales\\\"][0]\\n\",\n    \"\\n\",\n    \"from matplotlib import pyplot\\n\",\n    \"pyplot.figure(figsize=(3, 3))\\n\",\n    \"pyplot.arrow(0, 0, 1, 0, width=0.02, alpha=0.5)\\n\",\n    \"pyplot.arrow(0, 0, 0, 1, width=0.02, alpha=0.5)\\n\",\n    \"\\n\",\n    \"arrow_x = ezkl.felt_to_float(witness['outputs'][0][0], out_scale)\\n\",\n    \"arrow_y = ezkl.felt_to_float(witness['outputs'][0][1], out_scale)\\n\",\n    \"pyplot.arrow(0, 0, arrow_x, arrow_y, width=0.02)\\n\",\n    \"arrow_x = ezkl.felt_to_float(witness['outputs'][0][2], out_scale)\\n\",\n    \"arrow_y = ezkl.felt_to_float(witness['outputs'][0][3], out_scale)\\n\",\n    \"pyplot.arrow(0, 0, arrow_x, arrow_y, width=0.02)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.15\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/notebooks/xgboost.ipynb",
        "content": "{\n    \"cells\": [\n        {\n            \"attachments\": {\n                \"image-3.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAywAAAV+CAYAAACUGLpbAAAMPWlDQ1BJQ0MgUHJvZmlsZQAASImVVwdYU8kWnltSIbQAAlJCb4JIDSAlhBZAercRkgChhBgIKnZ0UcG1iwVs6KqIYqfZETuLYsO+WFBR1sWCXXmTArruK9873zf3/vefM/85c+7cMgCon+CKxbmoBgB5okJJbEgAIzkllUF6ChCgA8hgONDj8grErOjoCABt8Px3e3cDekO76iDT+mf/fzVNvqCABwASDXE6v4CXB/FBAPAqnlhSCABRxptPLhTLMGxAWwIThHiBDGcqcJUMpyvwXrlPfCwb4lYAyKpcriQTALXLkGcU8TKhhlofxE4ivlAEgDoDYt+8vHw+xGkQ20AfMcQyfWb6DzqZf9NMH9LkcjOHsGIuciMHCgvEudyp/2c5/rfl5UoHY1jBppolCY2VzRnW7WZOfrgMq0LcK0qPjIJYC+IPQr7cH2KUmiUNTVD4o4a8AjasGdCF2InPDQyH2BDiYFFuZISST88QBnMghisEnSIs5MRDrAfxAkFBUJzSZ5MkP1YZC63PkLBZSv4cVyKPK4t1X5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SgvQiFQXFwshYWFkpycHIrbN7inhpbMzEzb70vUoFK8QAABBBBwnQCBxXVN7twKNxdYhgwZImeeeab87W9/M0FFA8upp54qp512muzdu1d69eolf//73wkszv31sEzNjhw5IjokTJerDvWhm4/qYhL6xYEAAggggIBdBQgsdm05yt1EwFdgaXJSozd0srMO0dFx/1Y8mHRvxVZpW5l0LlUgE+3b9pT/u1oDS6dOnRy33Hd72HAPBBBAAAH7CBBY7NNWlLQFgdYElhZuGfGPCSwRb4J2L4C/wJKSkiJnn322mXOyePFi2bRpU0DP7tGjh+imqb4OAosvFd5DAAEEELCbAIHFbi1Gef0KEFj80vCBhQT8BZb77rtP/vnPf5ohijfddNPRn7t162aGkOlQMj10In3nzp1l//79pufkjjvukMcee0y8n9evKoGlvgY/I4AAAgjYVYDAYteWo9xNBHQuSocOHZq8b+c3vD0sujwthzMEfAWWLl26mL2BvHsAaSjR5Yh1jpWu8tWzZ0/55JNPZOfOnaJhZu3atdK1a1dZtmyZeT179mxZuXJlEyACSxMS3kAAAQQQsKEAgcWGjUaRfQvs2rWrxQ34fF9p3Xdra2vNalL6L+oczhDwFVgGDhwouqnpa6+91qCSOln+xBNPNF+64tfcuXPNohELFy40AUXf+8///E/561//2uA67wsCi1eC7wgggAACdhYgsNi59Sh7AwHtYUlKSmrwnt1faA+L/mt7Wlqa3atC+f8t4Cuw6CaP9957r/zpT38yE/KPOeYYKSkpMctxv/3222YDyP79+8sbb7xhlijWz88//3xz/j333CMPPvigT18Ci08W3kQAAQQQsJkAgcVmDUZx/QsQWPzb8Il1BHwFFi2dLrM9btw4ycvLk9TUVHniiSfkyiuvNL2Guprd4cOHZcGCBfKrX/3KzHOJioqSl156Sa6//noz6V73GGp8EFgai/AaAQQQQMCOAgQWO7YaZfYpQGDxycKbFhPIzs42vSi+9mHReSvaS6i9K95De1+0p63+0fg9DS++lubW++i8Lnro6uvxMwIIIICA3QQILHZrMcrrV4DA4peGDywkkJ+fL9rzEY7hi/qc5ORk0SWTORBAAA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/x1c0mdX6L30H/V194dLUfjo70Diw4T0yFm+ge6zt3w9ippvXRYlB76s36mf+xrz5PWTV9rCNFeiMLCQvNZ47Lqder13nvvydKlS4/eS3+oqqoy16uF1lnDit7zqaeeMjZ79uwx58+cOVPmzp1rQp+uaqZLROsmk1puXRBBjbQ86qftUP9Q2wsuuEBeeeUVGT16tOzevduU3/veNddcI3PmzDHzlepfpz8TWBqL8BoBBBBAIFgBAkuwYpyPAAIBC/gLLAMHDpQTTzxRevbsKc8884z5g/uWW24xfzQvX75czjjjDPOHroYX/UP8oYcekunTp5vnPvroo6J/cF9//fXm+9///ne5+eabZfv27TJkyBBz7pVXXmn+1X/MmDGmB0b/wG58tGdg0WB0ww03mD1isrKy5B//+Iccf/zxMmLECPPHvbee9913n3z77bcyYMAA+fDDD03AuOSSS+TNN9+Uc889V15++WW58cYb5cknn5SzzjrLBLDvvvtOzj77bPn+++/NexpE9Lj//vtFP1uxYoX84he/kI0bN8qgQYNEe6yWLFkiv/rVryQ3N1dmz55t3td7bN682QSea6+9Vnbu3GneV7+bbrpJXnjhBbnqqqtMMGwcWE499VQTZjRE6nV6//Hjx5vQsnr1ahNitPfm66+/bsxMYGkiwhsIIIAAAsEKEFiCFeN8BBAIWMBfYPntb38rX375pfmDWXtRPv30U9HAor0o+seyfv7II4+Yf/nXn72BZd26dXLo0CETYrTXQv+o1wCjw5X69+8v1113nfnjXSfS//73vxc9X3slfB3tGVg0pPTp00fmz58vw4cPNz082suhE/v1j3jtDdKepNtuu00ee+wx6devnwk0OmRLeyy0Hvq+lkmXAdZrtedDe2L00HDy/PPPy6WXXmqChQYR9frf//1fMyxLg4QOjTvhhBNEe0M0UFx22WXmPq+//rox0WChn3322WeigbFv375y+eWXm2CjoVDLqKFlx44dTbimTJlirnn66aflJz/5iQlhei/tvdGApM/VXqAvvviiybX0sDQh4Q0EEEAAgSAFCCxBgnE6AggELuArsOiQJf1X/bffftsM2TrttNPkzjvvNH+A6x/EGlj0D/T/+q//Mj0RF1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puyB0QQCAIAd2xXsNLfHx8EFe17VSdz6JzZTSwcCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBAgsrmpuKosAAggggAACCCCAgL0ECCz2ai9KiwACCCCAAAIIIICAqwQILK5qbiqLAAIIIIAAAggggIC9BAgs9movSosAAggggAACCCCAgKsECCyuam4qiwACCCCAAAIIIICAvQQILPZqL0qLAAIIIIAAAggggICrBP4/LTSuZ2kLvQEAAAAASUVORK5CYII=\"\n                },\n                \"image.png\": {\n                    \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAUAAAAEbCAYAAACr2V2eAAABYmlDQ1BJQ0MgUHJvZmlsZQAAKJF1kDFLw1AUhU9stSAVHRwEHQKKUy01rdi1LSKCQxoVqlvyWlMlTR9JRNTFQRengi5uUhd/gS4OjoKDguAgIoKDP0DsoiXeNGpbxft43I/DvYfDBTrCKudGEEDJdCxlOi3mFpfE0Au60ENPQEBlNk/J8iyN4Lu3V+2O5qhuxzyvq5px+bw3PJi1N6Nscmv173xbdecLNqP+QT/BuOUAQoxYXne4x9vE/RaFIj7wWPf5xGPN5/PGzLySIb4h7mNFNU/8RBzRWnS9hUvGGvvK4KUPF8yFOeoD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AKQIIoFPuxBgIQCAOAQQwDi3iQgACThFAAJ1yJ8ZAAAJxCCCAcWgRFwIQcIoAAuiUOzEGAhCIQwABjEOLuBCAgFMEEECn3IkxEIBAHAIIYBxaxIUABJwigAA65U6MgQAE4hBAAOPQIi4EIOAUAQTQKXdiDAQgEIcAAhiHFnEhAAGnCCCATrkTYyAAgTgE/gcCHHjHKxBaJwAAAABJRU5ErkJggg==\"\n                }\n            },\n            \"cell_type\": \"markdown\",\n            \"id\": \"cf69bb3f-94e6-4dba-92cd-ce08df117d67\",\n            \"metadata\": {},\n            \"source\": [\n                \"## XGBoost models\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"XGBoost based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image.png](attachment:image.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \\n\",\n                \"\\n\",\n                \"\\n\",\n                \"![image-3.png](attachment:image-3.png)\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"This notebook showcases how to do that using the `hummingbird` python package ! \"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"a60b90d6\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"!python -m pip install hummingbird_ml\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"95613ee9\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# check if notebook is in colab\\n\",\n                \"try:\\n\",\n                \"    # install ezkl\\n\",\n                \"    import google.colab\\n\",\n                \"    import subprocess\\n\",\n                \"    import sys\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"ezkl\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"onnx\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"hummingbird-ml\\\"])\\n\",\n                \"    subprocess.check_call([sys.executable, \\\"-m\\\", \\\"pip\\\", \\\"install\\\", \\\"xgboost\\\"])\\n\",\n                \"\\n\",\n                \"# rely on local installation of ezkl if the notebook is not in colab\\n\",\n                \"except:\\n\",\n                \"    pass\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# here we create and (potentially train a model)\\n\",\n                \"\\n\",\n                \"# make sure you have the dependencies required here already installed\\n\",\n                \"import json\\n\",\n                \"import numpy as np\\n\",\n                \"from sklearn.datasets import load_iris\\n\",\n                \"from sklearn.model_selection import train_test_split\\n\",\n                \"from xgboost import XGBClassifier as Gbc\\n\",\n                \"import torch\\n\",\n                \"import ezkl\\n\",\n                \"import os\\n\",\n                \"from torch import nn\\n\",\n                \"import xgboost as xgb\\n\",\n                \"from hummingbird.ml import convert\\n\",\n                \"\\n\",\n                \"NUM_CLASSES = 3\\n\",\n                \"\\n\",\n                \"iris = load_iris()\\n\",\n                \"X, y = iris.data, iris.target\\n\",\n                \"X = X.astype(np.float32)\\n\",\n                \"X_train, X_test, y_train, y_test = train_test_split(X, y)\\n\",\n                \"clr = Gbc(n_estimators=12)\\n\",\n                \"clr.fit(X_train, y_train)\\n\",\n                \"\\n\",\n                \"# convert to torch\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"torch_gbt = convert(clr, 'torch')\\n\",\n                \"\\n\",\n                \"print(torch_gbt)\\n\",\n                \"# assert predictions from torch are = to sklearn\\n\",\n                \"diffs = []\\n\",\n                \"\\n\",\n                \"for i in range(len(X_test)):\\n\",\n                \"    torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\\n\",\n                \"    sk_pred = clr.predict(X_test[i].reshape(1, -1))\\n\",\n                \"    diffs.append(torch_pred != sk_pred[0])\\n\",\n                \"\\n\",\n                \"print(\\\"num diff: \\\", sum(diffs))\\n\",\n                \"\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b37637c4\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"model_path = os.path.join('network.onnx')\\n\",\n                \"compiled_model_path = os.path.join('network.compiled')\\n\",\n                \"pk_path = os.path.join('test.pk')\\n\",\n                \"vk_path = os.path.join('test.vk')\\n\",\n                \"settings_path = os.path.join('settings.json')\\n\",\n                \"\\n\",\n                \"witness_path = os.path.join('witness.json')\\n\",\n                \"data_path = os.path.join('input.json')\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"82db373a\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# !!!!!!!!!!!!!!!!! This cell will flash a warning about onnx runtime compat but it is fine !!!!!!!!!!!!!!!!!!!!!\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# export to onnx format\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"# Input to the model\\n\",\n                \"shape = X_train.shape[1:]\\n\",\n                \"x = torch.rand(1, *shape, requires_grad=False)\\n\",\n                \"torch_out = torch_gbt.predict(x)\\n\",\n                \"# Export the model\\n\",\n                \"torch.onnx.export(torch_gbt.model,               # model being run\\n\",\n                \"                  # model input (or a tuple for multiple inputs)\\n\",\n                \"                  x,\\n\",\n                \"                  # where to save the model (can be a file or file-like object)\\n\",\n                \"                  \\\"network.onnx\\\",\\n\",\n                \"                  export_params=True,        # store the trained parameter weights inside the model file\\n\",\n                \"                  opset_version=18,          # the ONNX version to export the model to\\n\",\n                \"                  input_names=['input'],   # the model's input names\\n\",\n                \"                  output_names=['output'],  # the model's output names\\n\",\n                \"                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\\n\",\n                \"                                'output': {0: 'batch_size'}})\\n\",\n                \"\\n\",\n                \"d = ((x).detach().numpy()).reshape([-1]).tolist()\\n\",\n                \"\\n\",\n                \"data = dict(input_shapes=[shape],\\n\",\n                \"            input_data=[d],\\n\",\n                \"            output_data=[(o).reshape([-1]).tolist() for o in torch_out])\\n\",\n                \"\\n\",\n                \"# Serialize data into file:\\n\",\n                \"json.dump(data, open(\\\"input.json\\\", 'w'))\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"run_args = ezkl.PyRunArgs()\\n\",\n                \"run_args.variables = [(\\\"batch_size\\\", 1)]\\n\",\n                \"\\n\",\n                \"# TODO: Dictionary outputs\\n\",\n                \"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\\n\",\n                \"assert res == True\\n\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# generate a bunch of dummy calibration data\\n\",\n                \"cal_data = {\\n\",\n                \"    \\\"input_data\\\": [(torch.rand(20, *shape)).flatten().tolist()],\\n\",\n                \"}\\n\",\n                \"\\n\",\n                \"cal_path = os.path.join('calibration.json')\\n\",\n                \"# save as json file\\n\",\n                \"with open(cal_path, \\\"w\\\") as f:\\n\",\n                \"    json.dump(cal_data, f)\\n\",\n                \"\\n\",\n                \"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \\\"resources\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"3aa4f090\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\\n\",\n                \"assert res == True\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"8b74dcee\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# srs path\\n\",\n                \"res = ezkl.get_srs( settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"18c8b7c7\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# now generate the witness file \\n\",\n                \"\\n\",\n                \"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\\n\",\n                \"assert os.path.isfile(witness_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"b1c561a8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"\\n\",\n                \"# HERE WE SETUP THE CIRCUIT PARAMS\\n\",\n                \"# WE GOT KEYS\\n\",\n                \"# WE GOT CIRCUIT PARAMETERS\\n\",\n                \"# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"res = ezkl.setup(\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"assert os.path.isfile(vk_path)\\n\",\n                \"assert os.path.isfile(pk_path)\\n\",\n                \"assert os.path.isfile(settings_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"c384cbc8\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# GENERATE A PROOF\\n\",\n                \"\\n\",\n                \"\\n\",\n                \"proof_path = os.path.join('test.pf')\\n\",\n                \"\\n\",\n                \"res = ezkl.prove(\\n\",\n                \"        witness_path,\\n\",\n                \"        compiled_model_path,\\n\",\n                \"        pk_path,\\n\",\n                \"        proof_path,\\n\",\n                \"        \\n\",\n                \"        \\\"single\\\",\\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"print(res)\\n\",\n                \"assert os.path.isfile(proof_path)\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"76f00d41\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        },\n        {\n            \"cell_type\": \"code\",\n            \"execution_count\": null,\n            \"id\": \"1f50a8d0\",\n            \"metadata\": {},\n            \"outputs\": [],\n            \"source\": [\n                \"# VERIFY IT\\n\",\n                \"\\n\",\n                \"res = ezkl.verify(\\n\",\n                \"        proof_path,\\n\",\n                \"        settings_path,\\n\",\n                \"        vk_path,\\n\",\n                \"        \\n\",\n                \"    )\\n\",\n                \"\\n\",\n                \"assert res == True\\n\",\n                \"print(\\\"verified\\\")\"\n            ]\n        }\n    ],\n    \"metadata\": {\n        \"kernelspec\": {\n            \"display_name\": \"Python 3 (ipykernel)\",\n            \"language\": \"python\",\n            \"name\": \"python3\"\n        },\n        \"language_info\": {\n            \"codemirror_mode\": {\n                \"name\": \"ipython\",\n                \"version\": 3\n            },\n            \"file_extension\": \".py\",\n            \"mimetype\": \"text/x-python\",\n            \"name\": \"python\",\n            \"nbconvert_exporter\": \"python\",\n            \"pygments_lexer\": \"ipython3\",\n            \"version\": \"3.9.15\"\n        }\n    },\n    \"nbformat\": 4,\n    \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_average/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.AvgPool2d(2, 1, (1, 1))\n\n    def forward(self, x):\n        return self.layer(x)[0]\n\n\ncircuit = Model()\nexport(circuit, input_shape=[3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_batch_norm/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.BatchNorm2d(3)\n\n    def forward(self, x):\n        return self.layer(x)\n\n\ncircuit = Model()\nexport(circuit, input_shape=[3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_concat/gen.py",
        "content": "import torch\nfrom torch import nn\nfrom ezkl import export\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return torch.concat([x, x], 2)\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[3, 2, 3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_conv/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.Conv2d(3, 1, (1, 1), 1, 1)\n\n    def forward(self, x):\n        return self.layer(x)\n\ncircuit = Model()\nexport(circuit, input_shape = [3, 1, 1])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_conv_transpose/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n        self.convtranspose = nn.ConvTranspose2d(3, 3, (5, 5), stride=2, padding=2, output_padding=1)\n\n    def forward(self, x):\n        y = self.convtranspose(x)\n        return y\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 5, 5]\n    x = 0.1*torch.rand(1,*shape, requires_grad=True)\n\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      (x),                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes = [shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\nif __name__ == \"__main__\":\n    main()"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_div/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n\n    def forward(self, x):\n        return x/ 10\n\n\ncircuit = Circuit()\nexport(circuit, input_shape = [1])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_downsample/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.Conv2d(3, 1, (1, 1), 2, 1)\n\n    def forward(self, x):\n        return self.layer(x)\n\n\ncircuit = Model()\nexport(circuit, input_shape=[3, 6, 6])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_eltwise_div/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n\n    def forward(self, x):\n        return x/(2*x)\n\n\ncircuit = Circuit()\nexport(circuit, input_shape=[1])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_elu/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\n\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n        self.layer = nn.ELU()\n\n    def forward(self, x):\n        return self.layer(x)\n\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 2, 3]\n    x = 0.1*torch.rand(1, *shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      # model input (or a tuple for multiple inputs)\n                      x,\n                      # where to save the model (can be a file or file-like object)\n                      \"network.onnx\",\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names=['input'],   # the model's input names\n                      output_names=['output'],  # the model's output names\n                      dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                    'output': {0: 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes=[shape, shape, shape],\n                input_data=[d],\n                output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_erf/gen.py",
        "content": "import json\nimport torch \nfrom torch import nn\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n\n    def forward(self, x):\n        return torch.special.erf(x)\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3]\n    x = torch.rand(1,*shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      x,                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes = [shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump( data, open( \"input.json\", 'w' ) )\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_flatten/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n        self.flatten = nn.Flatten()\n\n    def forward(self, x):\n        return self.flatten(x)\n\n\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 2, 3]\n    x = 0.1*torch.rand(1,*shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      x,                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes = [shape, shape, shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump( data, open( \"input.json\", 'w' ) )\n\nif __name__ == \"__main__\":\n    main()\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_gelu_noappx/gen.py",
        "content": "import json\nimport torch \nfrom torch import nn\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n        self.layer = nn.GELU() # approximation = false in our case\n\n    def forward(self, x):\n        return self.layer(x)\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3]\n    x = torch.rand(1,*shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      x,                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes = [shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump( data, open( \"input.json\", 'w' ) )\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_gelu_tanh_appx/gen.py",
        "content": "import json\nimport torch \nfrom torch import nn\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n        self.layer = nn.GELU('tanh') # approximation = false in our case\n\n    def forward(self, x):\n        return self.layer(x)\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3]\n    x = torch.rand(1,*shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      x,                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes = [shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump( data, open( \"input.json\", 'w' ) )\n\nif __name__ == \"__main__\":\n    main()"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_identity/gen.py",
        "content": "import torch\nfrom torch import nn\nimport json\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return x\n\n\ncircuit = MyModel()\n\nx = 0.1*torch.rand(1, *[2], requires_grad=True)\n\n# Flips the neural net into inference mode\ncircuit.eval()\n\n# Export the model\ntorch.onnx.export(circuit,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_data=[data_array])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_instance_norm/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\nimport torch\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n        self.layer = nn.InstanceNorm2d(3).eval()\n\n    def forward(self, x):\n        return [self.layer(x)]\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_leakyrelu/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.LeakyReLU(negative_slope=0.05)\n\n    def forward(self, x):\n        return self.layer(x)\n\ncircuit = Model()\nexport(circuit, input_shape = [3])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_linear/gen.py",
        "content": "import random\nimport math\nimport numpy as np\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport json\n\n\nmodel = nn.Linear(1, 1)\nx = torch.randn(1, 1)\n\nprint(x)\n\n# Flips the neural net into inference mode\nmodel.eval()\nmodel.to('cpu')\n\n# Export the model\ntorch.onnx.export(model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata_json = dict(input_data=[data_array])\n\nprint(data_json)\n\n# Serialize data into file:\njson.dump(data_json, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_lppool/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.LPPool2d(2, 1, (1, 1))\n\n    def forward(self, x):\n        return self.layer(x)[0]\n\n\ncircuit = Model()\n\nx = torch.empty(1, 3, 2, 2).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_max_pool/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\nimport torch\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.MaxPool2d(2, 1, (1, 1), 1, 1)\n\n    def forward(self, x):\n        return self.layer(x)[0]\n\n\ncircuit = Model()\n\n\n# Input to the model\nshape = [3, 2, 2]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = circuit(x)\n# Export the model\ntorch.onnx.export(circuit,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=14,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[(o).reshape([-1]).tolist() for o in torch_out])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_pad/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n\n    def forward(self, x):\n        return nn.functional.pad(x, (1,1))\n\n\n\ncircuit = Model()\nexport(circuit, input_shape = [3, 2, 2])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_powf/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return torch.pow(x, -0.1)\n\n\ncircuit = MyModel()\n\n\nx = torch.rand(1, 4)\n\ntorch.onnx.export(circuit, (x), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_prelu/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.layer = nn.PReLU(num_parameters=3, init=0.25)\n\n    def forward(self, x):\n        return self.layer(x)\n\ncircuit = Model()\nexport(circuit, input_shape = [3, 2, 2])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_relu/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n        self.layer = nn.ReLU()\n\n    def forward(self, x):\n        return self.layer(x)\n\ncircuit = MyModel()\nexport(circuit, input_shape = [3])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_reshape/gen.py",
        "content": "import torch\nfrom torch import nn\nfrom ezkl import export\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        x = x.reshape([-1, 6])\n        return x\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[1, 3, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_sigmoid/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n        self.layer = nn.Sigmoid()\n\n    def forward(self, x):\n        return self.layer(x)\n\ncircuit = MyModel()\nexport(circuit, input_shape = [3])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_slice/gen.py",
        "content": "import torch\nfrom torch import nn\nfrom ezkl import export\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return x[:,1:2]\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[3, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_softmax/gen.py",
        "content": "import torch\nfrom torch import nn\nfrom ezkl import export\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n        self.layer = nn.Softmax(dim=1)\n\n    def forward(self, x):\n        return self.layer(x)\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[3])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_sqrt/gen.py",
        "content": "import torch \nfrom torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return torch.sqrt(x)\n\ncircuit = MyModel()\nexport(circuit, input_shape = [3])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_tiny_div/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n\n    def forward(self, x):\n        return x/ 10000\n\n\ncircuit = Circuit()\n\n\nx = torch.empty(1, 8).random_(0, 2)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_topk/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        topk_largest = torch.topk(x, 4)\n        topk_smallest = torch.topk(x, 4, largest=False)\n        print(topk_largest)\n        print(topk_smallest)\n        return topk_largest.values + topk_smallest.values\n\n\ncircuit = MyModel()\n\n\nx = torch.randint(10, (1, 6))\ny = circuit(x)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=14,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d],\n    output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in y]\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_upsample/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n        self.upsample = nn.Upsample(scale_factor=2, mode='nearest')\n\n    def forward(self, x):\n        y = self.upsample(x)\n        return y\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 5, 5]\n    x = 0.1*torch.rand(1,*shape, requires_grad=True)\n\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      (x),                   # model input (or a tuple for multiple inputs)\n                      \"network.onnx\",            # where to save the model (can be a file or file-like object)\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=11,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names = ['input'],   # the model's input names\n                      output_names = ['output'], # the model's output names\n                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n                                    'output' : {0 : 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\n    data = dict(input_shapes = [shape],\n                input_data = [d],\n                output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\nif __name__ == \"__main__\":\n    main()"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_var/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\nimport torch\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return [torch.var(x, unbiased=False, dim=[1,2])]\n\ncircuit = MyModel()\nexport(circuit, input_shape = [1,3,3])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/1l_where/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return [torch.where(x >= 0.0, 3.0, 5.0)]\n\n\ncircuit = MyModel()\n\n\nx = torch.randint(1, (1, 64))\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/2l_relu_fc/gen.py",
        "content": "from torch import nn\nimport torch.nn.init as init\nfrom ezkl import export\n\nclass Model(nn.Module):\n    def __init__(self, inplace=False):\n        super(Model, self).__init__()\n\n        self.aff1 = nn.Linear(3,1)\n        self.relu = nn.ReLU()\n        self._initialize_weights()\n\n    def forward(self, x):\n        x =  self.aff1(x)\n        x =  self.relu(x)\n        return (x)\n\n\n    def _initialize_weights(self):\n        init.orthogonal_(self.aff1.weight)\n\ncircuit = Model()\nexport(circuit, input_shape = [3])"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/2l_sigmoid_small/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n        self.relu = nn.ReLU()\n        self.sigmoid = nn.Sigmoid()\n        self.fc = nn.Linear(3, 2)\n\n    def forward(self, x):\n        x = self.sigmoid(x)\n        x = self.sigmoid(x)\n\n        return x\n\ncircuit = MyModel()\nexport(circuit, input_shape = [1])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/3l_relu_conv_fc/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n        self.conv1 = nn.Conv2d(1,4, kernel_size=5, stride=2)\n        self.conv2 = nn.Conv2d(4,4, kernel_size=5, stride=2)\n        self.relu = nn.ReLU()\n        self.fc = nn.Linear(4*4*4, 10)\n\n    def forward(self, x):\n        x = x.view(-1,1,28,28)\n        x = self.relu(self.conv1(x))\n        x = self.relu(self.conv2(x))\n        x = x.view(-1,4*4*4)\n        x = self.fc(x)\n        return x\n\ncircuit = MyModel()\nexport(circuit, input_shape = [1,28,28])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/4l_relu_conv_fc/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\n        self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\n        \n        self.relu = nn.ReLU()\n\n        self.d1 = nn.Linear(48, 48)\n        self.d2 = nn.Linear(48, 10)\n\n    def forward(self, x):\n        # 32x1x28x28 => 32x32x26x26\n        x = self.conv1(x)\n        x = self.relu(x)\n        x = self.conv2(x)\n        x = self.relu(x)\n\n        # flatten => 32 x (32*26*26)\n        x = x.flatten(start_dim = 1)\n    #    x = x.flatten()\n\n        # 32 x (32*26*26) => 32x128\n        x = self.d1(x)\n        x = self.relu(x)\n\n        # logits => 32x10\n        logits = self.d2(x)\n       \n        return logits\n\ncircuit = MyModel()\nexport(circuit, input_shape = [1,28,28])\n\n\n    \n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/arange/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self):\n        return torch.arange(0, 10, 2)\n\n\ncircuit = MyModel()\n\n\n\ntorch.onnx.export(circuit, (), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  output_names=['output'],  # the model's output names\n                )\n\n\n\n\ndata = dict(\n    input_data=[[]],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/bitshift/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x, y, z):\n      \n        return x << 2, y >> 3, z << 1, w >> 4\n\n\ncircuit = MyModel()\n\n# random integers between 0 and 100\nx = torch.empty(1, 3).uniform_(0, 100).to(torch.int32)\ny = torch.empty(1, 3).uniform_(0, 100).to(torch.int32)\nz = torch.empty(1, 3).uniform_(0, 100).to(torch.int32)\nw = torch.empty(1, 3).uniform_(0, 100).to(torch.int32)\n\ntorch.onnx.export(circuit, (w, x, y, z), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=16,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input', 'input1', 'input2',\n                               'input3'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'input2': {0: 'batch_size'},\n                                'input3': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}, \n                                'output1': {0: 'batch_size'},\n                                'output2': {0: 'batch_size'},\n                                'output3': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\nd2 = ((y).detach().numpy()).reshape([-1]).tolist()\nd3 = ((z).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d, d1, d2, d3],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/bitwise_ops/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x, y, z):\n        # bitwise and \n        and_xy = torch.bitwise_and(x, y)    \n        # bitwise or\n        or_yz = torch.bitwise_or(y, z)\n        # bitwise not\n        not_wyz = torch.bitwise_not(or_yz)\n        return not_wyz\n\n\ncircuit = MyModel()\n\na = torch.empty(1, 3).uniform_(0, 1)\n\nw = torch.bernoulli(a).to(torch.bool)\nx = torch.bernoulli(a).to(torch.bool)\ny = torch.bernoulli(a).to(torch.bool)\nz = torch.bernoulli(a).to(torch.bool)\n\ntorch.onnx.export(circuit, (w, x, y, z), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=16,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input', 'input1', 'input2',\n                               'input3'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'input2': {0: 'batch_size'},\n                                'input3': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\nd2 = ((y).detach().numpy()).reshape([-1]).tolist()\nd3 = ((z).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d, d1, d2, d3],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/blackman_window/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        # bitwise and \n        bmw = torch.blackman_window(8) + x\n        return bmw\n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=16,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/boolean/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x, y, z):\n        return [((x & y)) == (x & (y | (z ^ w)))]\n\n\ncircuit = MyModel()\n\na = torch.empty(1, 3).uniform_(0, 1)\n\nw = torch.bernoulli(a).to(torch.bool)\nx = torch.bernoulli(a).to(torch.bool)\ny = torch.bernoulli(a).to(torch.bool)\nz = torch.bernoulli(a).to(torch.bool)\n\ntorch.onnx.export(circuit, (w, x, y, z), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input', 'input1', 'input2',\n                               'input3'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'input2': {0: 'batch_size'},\n                                'input3': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\nd2 = ((y).detach().numpy()).reshape([-1]).tolist()\nd3 = ((z).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d, d1, d2, d3],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/boolean_identity/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return [x]\n\n\ncircuit = MyModel()\n\na = torch.empty(1, 3).uniform_(0, 1)\n\nx = torch.bernoulli(a).to(torch.bool)\n\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/celu/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.CELU()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/clip/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.clamp(x, min=0.4, max=0.8)\n        return m\n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 2, 2, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/decision_tree/gen.py",
        "content": "# Train a model.\nimport json\nimport onnxruntime as rt\nfrom skl2onnx import to_onnx\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier as De\nimport sk2torch\nimport torch\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = De()\nclr.fit(X_train, y_train)\n\ntorch_model = sk2torch.wrap(clr)\n\n\n# Convert into ONNX format.\n# export to onnx format\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=True)\ntorch_out = torch_model(x)\n# Export the model\ntorch.onnx.export(torch_model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/doodles/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        return x\n\n\ncircuit = MyModel()\nexport(circuit, input_shape=[1, 64, 64])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/eye/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = x @ torch.eye(8)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/gather_elements/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x):\n        return torch.gather(w, 1, x)\n\n\ncircuit = MyModel()\n\n\nw = torch.rand(1, 15, 18)\nx = torch.randint(0, 15, (1, 15, 2))\n\ntorch.onnx.export(circuit, (w, x), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input', 'input1'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d, d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/gather_nd/gen.py",
        "content": "from torch import nn\nimport json\nimport numpy as np\nimport tf2onnx\n\n\nimport tensorflow as tf\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Model\n\n\n# gather_nd in tf then export to onnx\n\n\n\n\nx = in1 = Input((15, 18,))\nw = in2 = Input((15, 1), dtype=tf.int32)\nx = tf.gather_nd(x, w, batch_dims=1)\ntm = Model((in1, in2), x )\ntm.summary()\ntm.compile(optimizer='adam', loss='mse')\n\nshape = [1, 15, 18]\nindex_shape = [1, 15, 1]\n# After training, export to onnx (network.onnx) and create a data file (input.json)\nx = 0.1*np.random.rand(1,*shape)\n# w = random int tensor\nw = np.random.randint(0, 10, index_shape)\n\nspec = tf.TensorSpec(shape, tf.float32, name='input_0')\nindex_spec = tf.TensorSpec(index_shape, tf.int32, name='input_1')\n\nmodel_path = \"network.onnx\"\n\ntf2onnx.convert.from_keras(tm, input_signature=[spec, index_spec], inputs_as_nchw=['input_0', 'input_1'], opset=12, output_path=model_path)\n\n\nd = x.reshape([-1]).tolist()\nd1 = w.reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d, d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/gradient_boosted_trees/gen.py",
        "content": "# make sure you have the dependencies required here already installed\nimport json\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier as Gbc\nimport sk2torch\nimport torch\nimport ezkl\nimport os\nfrom torch import nn\n\nNUM_CLASSES = 3\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = Gbc(n_estimators=10)\nclr.fit(X_train, y_train)\n\n\ntrees = []\nfor bundle in clr.estimators_:\n    tree_bundle = []\n    for tree in bundle:\n        tree_bundle.append(sk2torch.wrap(tree))\n    trees.append(tree_bundle)\n\n\nclass GradientBoostedTrees(nn.Module):\n    def __init__(self, trees):\n        super(GradientBoostedTrees, self).__init__()\n        bundle_modules = []\n        for bundle in trees:\n            module = nn.ModuleList(bundle)\n            bundle_modules.append(module)\n        self.trees = nn.ModuleList(bundle_modules)\n        self.num_classifiers = torch.tensor(\n            [len(self.trees) for _ in range(NUM_CLASSES)])\n\n    def forward(self, x):\n        # first bundle\n        local_pred = self.trees[0][0](x)\n        local_pred = local_pred.reshape(-1, 1)\n        for tree in self.trees[0][1:]:\n            tree_out = tree(x)\n            tree_out = tree_out.reshape(-1, 1)\n            local_pred = torch.cat((local_pred, tree_out), 1)\n        local_pred = local_pred.reshape(-1, NUM_CLASSES)\n        out = local_pred\n\n        for bundle in self.trees[1:]:\n            local_pred = bundle[0](x)\n            local_pred = local_pred.reshape(-1, 1)\n            for tree in bundle[1:]:\n                tree_out = tree(x)\n                tree_out = tree_out.reshape(-1, 1)\n                local_pred = torch.cat((local_pred, tree_out), 1)\n            # local_pred = local_pred.reshape(x.shape[0], 3)\n            local_pred = local_pred.reshape(-1, NUM_CLASSES)\n            out = out + local_pred\n        output = out / self.num_classifiers\n        return out.reshape(-1, NUM_CLASSES)\n\n\ntorch_rf = GradientBoostedTrees(trees)\n# assert predictions from torch are = to sklearn\n\nfor i in range(len(X_test)):\n    torch_pred = torch_rf(torch.tensor(X_test[i].reshape(1, -1)))\n    sk_pred = clr.predict(X_test[i].reshape(1, -1))\n    print(torch_pred, sk_pred[0])\n    assert torch_pred.argmax() == sk_pred[0]\n\n\ntorch_rf.eval()\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = torch_rf(x)\n# Export the model\ntorch.onnx.export(torch_rf,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/gru/gen.py",
        "content": "import random\nimport math\nimport numpy as np\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport json\n\n\nmodel = nn.GRU(3, 3)  # Input dim is 3, output dim is 3\nx = torch.randn(1, 3)  # make a sequence of length 5\n\nprint(x)\n\n# Flips the neural net into inference mode\nmodel.eval()\nmodel.to('cpu')\n\n# Export the model\ntorch.onnx.export(model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata_json = dict(input_data=[data_array])\n\nprint(data_json)\n\n# Serialize data into file:\njson.dump(data_json, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/hard_max/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.argmax(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/hard_sigmoid/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.Hardsigmoid()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/hard_swish/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):\n        m = nn.Hardswish()(x)\n        return m\n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/hummingbird_decision_tree/gen.py",
        "content": "# Train a model.\nimport json\nimport onnxruntime as rt\nfrom skl2onnx import to_onnx\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier as De\nfrom hummingbird.ml import convert\nimport torch\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = De()\nclr.fit(X_train, y_train)\n\ntorch_model = convert(clr, \"pytorch\").model\n\n\n# Convert into ONNX format.\n# export to onnx format\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=True)\ntorch_out = torch_model(x)\n# Export the model\ntorch.onnx.export(torch_model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/layernorm/gen.py",
        "content": "import torch\nimport torch.nn as nn\nimport json\n\n\n# A single model that only does layernorm\nclass LayerNorm(nn.Module):\n    def __init__(self, hidden_size):\n        super().__init__()\n        self.ln = nn.LayerNorm(hidden_size)\n\n    def forward(self, x):\n        return self.ln(x)\n    \n\nx = torch.randn(1, 10, 10)\nmodel = LayerNorm(10)\nout = model(x)\n\ntorch.onnx.export(model, x, \"network.onnx\", export_params=True, do_constant_folding=True, input_names = ['input'],output_names = ['output'],dynamic_axes={'input' : {0 : 'batch_size'},'output' : {0 : 'batch_size'}})\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\ndata = dict(input_data = [data_array], output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in out])\njson.dump( data, open( \"input.json\", 'w' ) )\n\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/less/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x):\n        return torch.less(w, x)\n\n\ncircuit = MyModel()\n\n\nw = torch.rand(1, 4)\nx = torch.rand(1, 4)\n\ntorch.onnx.export(circuit, (w, x), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input', 'input1'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d, d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/lightgbm/gen.py",
        "content": "# make sure you have the dependencies required here already installed\nimport json\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom lightgbm import LGBMClassifier as Gbc\nimport torch\nimport ezkl\nimport os\nfrom torch import nn\nimport xgboost as xgb\nfrom hummingbird.ml import convert\n\nNUM_CLASSES = 3\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = Gbc(n_estimators=12)\nclr.fit(X_train, y_train)\n\n# convert to torch\n\n\ntorch_gbt = convert(clr, 'torch', X_test[:1])\n\nprint(torch_gbt)\n# assert predictions from torch are = to sklearn\ndiffs = []\n\nfor i in range(len(X_test)):\n    torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\n    sk_pred = clr.predict(X_test[i].reshape(1, -1))\n    diffs.append(torch_pred != sk_pred[0])\n\nprint(\"num diff: \", sum(diffs))\n\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = torch_gbt.predict(x)\n# Export the model\ntorch.onnx.export(torch_gbt.model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[(o).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/linear_regression/gen.py",
        "content": "import os\nimport torch\nimport ezkl\nimport json\nfrom hummingbird.ml import convert\n\n\n# here we create and (potentially train a model)\n\n# make sure you have the dependencies required here already installed\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nX = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])\n# y = 1 * x_0 + 2 * x_1 + 3\ny = np.dot(X, np.array([1, 2])) + 3\nreg = LinearRegression().fit(X, y)\nreg.score(X, y)\n\ncircuit = convert(reg, \"torch\", X[:1]).model\n\n\n# export to onnx format\n# !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!!\n\n# Input to the model\nshape = X.shape[1:]\nx = torch.rand(1, *shape, requires_grad=True)\ntorch_out = circuit(x)\n# Export the model\ntorch.onnx.export(circuit,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/log_softmax/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.LogSoftmax()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/logsumexp/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.logsumexp(x, dim=1)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 2, 2, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/lstm/gen.py",
        "content": "import random\nimport math\nimport numpy as np\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport json\n\n\nmodel = nn.LSTM(3, 3)  # Input dim is 3, output dim is 3\nx = torch.randn(1, 3)  # make a sequence of length 5\n\nprint(x)\n\n# Flips the neural net into inference mode\nmodel.eval()\nmodel.to('cpu')\n\n# Export the model\ntorch.onnx.export(model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata_json = dict(input_data=[data_array])\n\nprint(data_json)\n\n# Serialize data into file:\njson.dump(data_json, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/ltsf/gen.py",
        "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport json\n\nclass moving_avg(nn.Module):\n    \"\"\"\n    Moving average block to highlight the trend of time series\n    \"\"\"\n    def __init__(self, kernel_size, stride):\n        super(moving_avg, self).__init__()\n        self.kernel_size = kernel_size\n        self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)\n\n    def forward(self, x):\n        # padding on the both ends of time series\n        front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1)\n        end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1)\n        x = torch.cat([front, x, end], dim=1)\n        x = self.avg(x.permute(0, 2, 1))\n        x = x.permute(0, 2, 1)\n        return x\n\n\nclass series_decomp(nn.Module):\n    \"\"\"\n    Series decomposition block\n    \"\"\"\n    def __init__(self, kernel_size):\n        super(series_decomp, self).__init__()\n        self.moving_avg = moving_avg(kernel_size, stride=1)\n\n    def forward(self, x):\n        moving_mean = self.moving_avg(x)\n        res = x - moving_mean\n        return res, moving_mean\n\nclass Model(nn.Module):\n    \"\"\"\n    Decomposition-Linear\n    \"\"\"\n    def __init__(self, configs):\n        super(Model, self).__init__()\n        self.seq_len = configs['seq_len']\n        self.pred_len = configs['pred_len']\n\n        # Decompsition Kernel Size\n        kernel_size = 25\n        self.decompsition = series_decomp(kernel_size)\n        self.individual = configs['individual']\n        self.channels = configs['enc_in']\n\n        if self.individual:\n            self.Linear_Seasonal = nn.ModuleList()\n            self.Linear_Trend = nn.ModuleList()\n            \n            for i in range(self.channels):\n                self.Linear_Seasonal.append(nn.Linear(self.seq_len,self.pred_len))\n                self.Linear_Trend.append(nn.Linear(self.seq_len,self.pred_len))\n\n                # Use this two lines if you want to visualize the weights\n                # self.Linear_Seasonal[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len]))\n                # self.Linear_Trend[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len]))\n        else:\n            self.Linear_Seasonal = nn.Linear(self.seq_len,self.pred_len)\n            self.Linear_Trend = nn.Linear(self.seq_len,self.pred_len)\n            \n            # Use this two lines if you want to visualize the weights\n            # self.Linear_Seasonal.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len]))\n            # self.Linear_Trend.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len]))\n\n    def forward(self, x):\n        # x: [Batch, Input length, Channel]\n        seasonal_init, trend_init = self.decompsition(x)\n        seasonal_init, trend_init = seasonal_init.permute(0,2,1), trend_init.permute(0,2,1)\n        if self.individual:\n            seasonal_output = torch.zeros([seasonal_init.size(0),seasonal_init.size(1),self.pred_len],dtype=seasonal_init.dtype).to(seasonal_init.device)\n            trend_output = torch.zeros([trend_init.size(0),trend_init.size(1),self.pred_len],dtype=trend_init.dtype).to(trend_init.device)\n            for i in range(self.channels):\n                seasonal_output[:,i,:] = self.Linear_Seasonal[i](seasonal_init[:,i,:])\n                trend_output[:,i,:] = self.Linear_Trend[i](trend_init[:,i,:])\n        else:\n            seasonal_output = self.Linear_Seasonal(seasonal_init)\n            trend_output = self.Linear_Trend(trend_init)\n\n        x = seasonal_output + trend_output\n        return x.permute(0,2,1) # to [Batch, Output length, Channel]\n    \n    \nconfigs = {\n    'seq_len': 96,\n    'pred_len': 1,\n    'individual': True,\n    'enc_in': 1,\n}\ncircuit = Model(configs)\n\n\nx = torch.empty(1, 96, 1).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/max/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\nimport torch\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n\n    def forward(self, x):\n        return [torch.max(x)]\n\n\ncircuit = Model()\nexport(circuit, input_shape=[3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/min/gen.py",
        "content": "from torch import nn\nfrom ezkl import export\nimport torch\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n\n    def forward(self, x):\n        return [torch.min(x)]\n\n\ncircuit = Model()\nexport(circuit, input_shape=[3, 2, 2])\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/mish/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.Mish()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/multihead_attention/gen.py",
        "content": "# 1. We define a simple transformer model with MultiHeadAttention layers\nimport ezkl\nimport json\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ScaledDotProductAttention(nn.Module):\n    def __init__(self, d_model, dropout=0.1):\n        super().__init__()\n        self.temperature = d_model ** 0.5\n        self.dropout = nn.Dropout(dropout)\n\n    def forward(self, q, k, v):\n        attn = torch.matmul(q / self.temperature, k.transpose(2, 3))\n        attn = F.softmax(attn, dim=-1)\n        attn = self.dropout(attn)\n        output = torch.matmul(attn, v)\n        return output, attn\n\n\nclass MultiHeadAttention(nn.Module):\n    def __init__(self, n_heads, d_model, dropout=0.1):\n        super().__init__()\n\n        self.n_heads = n_heads\n        self.d_model = d_model\n        self.d_k = d_model // n_heads\n\n        self.w_qs = nn.Linear(d_model, d_model)\n        self.w_ks = nn.Linear(d_model, d_model)\n        self.w_vs = nn.Linear(d_model, d_model)\n        self.fc = nn.Linear(d_model, d_model)\n\n        self.attention = ScaledDotProductAttention(d_model)\n\n        self.dropout = nn.Dropout(dropout)\n        self.layer_norm = nn.LayerNorm(d_model)\n\n    def forward(self, q, k, v):\n        n_batches = q.size(0)\n\n        q = self.w_qs(q).view(n_batches, -1, self.n_heads,\n                              self.d_k).transpose(1, 2)\n        k = self.w_ks(k).view(n_batches, -1, self.n_heads,\n                              self.d_k).transpose(1, 2)\n        v = self.w_vs(v).view(n_batches, -1, self.n_heads,\n                              self.d_k).transpose(1, 2)\n\n        q, attn = self.attention(q, k, v)\n\n        q = q.transpose(1, 2).contiguous().view(n_batches, -1, self.d_model)\n        q = self.dropout(self.fc(q))\n        return self.layer_norm(q)\n\n\nclass SimpleTransformer(nn.Module):\n    def __init__(self, nlayer, d_model=512, n_heads=8):\n        super().__init__()\n\n        self.layers = nn.ModuleList(\n            [MultiHeadAttention(n_heads, d_model) for _ in range(nlayer)])\n        # self.layers = nn.ModuleList([MultiHeadAttention(n_heads, d_model)])\n        self.fc = nn.Linear(d_model, 1)\n\n    def forward(self, x):\n        # assuming x is of shape [batch_size, sequence_length, d_model]\n        for layer in self.layers:\n            x = layer(x, x, x)\n        x = x.mean(dim=1)  # taking mean over the sequence length\n        x = self.fc(x)\n        return x\n\n\n# 2. We export it\nmodel = SimpleTransformer(2, d_model=128)\ninput_shape = [1, 16, 128]\nx = 0.1*torch.rand(1, *input_shape, requires_grad=True)\n\n# Export the model\ntorch.onnx.export(model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_data=[data_array])\njson.dump(data, open(\"input.json\", 'w'))\n\n\n# 3. We do our ezkl work\n\n\n# ezkl.gen_settings(\"network.onnx\", \"settings.json\")\n\n# !RUST_LOG = full\n# res = ezkl.calibrate_settings(\n#     \"input.json\", \"network.onnx\", \"settings.json\", \"resources\")\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/nanoGPT/gen.py",
        "content": "\n\n\"\"\"\nReference: https://github.com/karpathy/nanoGPT\n\"\"\"\n\nimport json\nimport math\nfrom dataclasses import dataclass\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport sys\nimport os\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(SCRIPT_DIR))\n\n\ndef new_gelu(x):\n    \"\"\"\n    Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).\n    Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415\n    \"\"\"\n    return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x)))\n\n\nclass LayerNorm(nn.Module):\n    \"\"\" LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False \"\"\"\n\n    def __init__(self, ndim, bias):\n        super().__init__()\n        self.weight = nn.Parameter(torch.ones(ndim))\n        self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None\n\n    def forward(self, input):\n        return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)\n\n\nclass CausalSelfAttention(nn.Module):\n\n    def __init__(self, config):\n        super().__init__()\n        assert config.n_embd % config.n_head == 0\n        # key, query, value projections for all heads, but in a batch\n        self.c_attn = nn.Linear(\n            config.n_embd, 3 * config.n_embd, bias=config.bias)\n        # output projection\n        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)\n        # regularization\n        self.attn_dropout = nn.Dropout(config.dropout)\n        self.resid_dropout = nn.Dropout(config.dropout)\n        self.n_head = config.n_head\n        self.n_embd = config.n_embd\n        self.dropout = config.dropout\n\n        # causal mask to ensure that attention is only applied to the left in the input sequence\n        self.register_buffer(\"bias\", torch.tril(torch.ones(config.block_size, config.block_size))\n                             .view(1, 1, config.block_size, config.block_size))\n\n    def forward(self, x):\n        B, T, C = x.size()  # batch size, sequence length, embedding dimensionality (n_embd)\n        # calculate query, key, values for all heads in batch and move head forward to be the batch dim\n        q, k, v = self.c_attn(x).split(self.n_embd, dim=2)\n        k = k.view(B, T, self.n_head, C //\n                   self.n_head).transpose(1, 2)  # (B, nh, T, hs)\n        q = q.view(B, T, self.n_head, C //\n                   self.n_head).transpose(1, 2)  # (B, nh, T, hs)\n        v = v.view(B, T, self.n_head, C //\n                   self.n_head).transpose(1, 2)  # (B, nh, T, hs)\n\n        # manual implementation of attention\n        # q shape:(B, nh, T, hs), k transpose shape (B, nh, hs, T) -> (B, nh, T, T)\n        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n        att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float(-10))\n        att = F.softmax(att, dim=-1)\n        att = self.attn_dropout(att)\n        y = att @ v  # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n        # re-assemble all head outputs side by side\n        y = y.transpose(1, 2).contiguous().view(B, T, C)\n\n        y = self.resid_dropout(self.c_proj(y))\n        return y\n\n\nclass MLP(nn.Module):\n\n    def __init__(self, config):\n        super().__init__()\n        self.c_fc = nn.Linear(\n            config.n_embd, 4 * config.n_embd, bias=config.bias)\n        self.c_proj = nn.Linear(\n            4 * config.n_embd, config.n_embd, bias=config.bias)\n        self.dropout = nn.Dropout(config.dropout)\n\n    def forward(self, x):\n        x = self.c_fc(x)\n        x = new_gelu(x)\n        x = self.c_proj(x)\n        x = self.dropout(x)\n        return x\n\n\nclass Block(nn.Module):\n\n    def __init__(self, config):\n        super().__init__()\n        self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)\n        self.attn = CausalSelfAttention(config)\n        self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)\n        self.mlp = MLP(config)\n\n    def forward(self, x):\n        x = x + self.attn(self.ln_1(x))\n        x = x + self.mlp(self.ln_2(x))\n        return x\n\n\n@dataclass\nclass GPTConfig:\n    block_size: int = 1024\n    # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency\n    vocab_size: int = 50304\n    n_layer: int = 12\n    n_head: int = 12\n    n_embd: int = 768\n    dropout: float = 0.0\n    # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster\n    bias: bool = True\n\n\nclass GPT(nn.Module):\n\n    def __init__(self, config):\n        super().__init__()\n        assert config.vocab_size is not None\n        assert config.block_size is not None\n        self.config = config\n\n        self.transformer = nn.ModuleDict(dict(\n            wte=nn.Embedding(config.vocab_size, config.n_embd),\n            wpe=nn.Embedding(config.block_size, config.n_embd),\n            drop=nn.Dropout(config.dropout),\n            h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),\n            ln_f=LayerNorm(config.n_embd, bias=config.bias),\n        ))\n\n        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n\n        # weight-tying\n        # https://paperswithcode.com/method/weight-tying\n        self.transformer.wte.weight = self.lm_head.weight\n        self.block = Block(config)\n        # init all weights\n        self.apply(self._init_weights)\n        # apply special scaled init to the residual projections, per GPT-2 paper\n        for pn, p in self.named_parameters():\n            if pn.endswith('c_proj.weight'):\n                torch.nn.init.normal_(\n                    p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))\n\n        # report number of parameters\n        print(\"number of parameters: %.2fM\" % (self.get_num_params()/1e6,))\n\n    def get_num_params(self, non_embedding=True):\n        \"\"\"\n        Return the number of parameters in the model.\n        For non-embedding count (default), the position embeddings get subtracted.\n        The token embeddings would too, except due to the parameter sharing these\n        params are actually used as weights in the final layer, so we include them.\n        \"\"\"\n        n_params = sum(p.numel() for p in self.parameters())\n        if non_embedding:\n            n_params -= self.transformer.wpe.weight.numel()\n        return n_params\n\n    def _init_weights(self, module):\n        if isinstance(module, nn.Linear):\n            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n            if module.bias is not None:\n                torch.nn.init.zeros_(module.bias)\n        elif isinstance(module, nn.Embedding):\n            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n\n    def forward(self, idx, targets=None):\n        device = idx.device\n        b, t = idx.size()\n        assert t <= self.config.block_size, f\"Cannot forward sequence of length {t}, block size is only {self.config.block_size}\"\n        pos = torch.arange(0, t, dtype=torch.long,\n                           device=device).unsqueeze(0)  # shape (1, t)\n\n        # # # forward the GPT model itself\n        # token embeddings of shape (b, t, n_embd), idx -> token_emb\n        idx = self.transformer.wte(idx)\n        # position embeddings of shape (1, t, n_embd)\n        pos_emb = self.transformer.wpe(pos)\n        idx = self.transformer.drop(idx + pos_emb)\n\n        for block in self.transformer.h:\n            idx = block(idx)\n\n        idx = self.transformer.ln_f(idx)\n        idx = self.lm_head(idx)\n\n        return idx\n\n\ngptconf = GPTConfig(block_size=64, vocab_size=65, n_layer=4,\n                    n_head=4, n_embd=64, dropout=0.0, bias=False)\nmodel = GPT(gptconf)\nmodel.get_num_params()\n\n\nshape = [1, 64]\nx = torch.randint(65, (1, 64))\ntorch_out = model(x)\n\ntorch.onnx.export(model, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/oh_decision_tree/gen.py",
        "content": "# Train a model.\nimport json\nimport onnxruntime as rt\nfrom skl2onnx import to_onnx\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier as De\nimport sk2torch\nimport torch\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = De()\nclr.fit(X_train, y_train)\n\ntorch_model = sk2torch.wrap(clr)\n\n\n# Convert into ONNX format.\n# export to onnx format\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=True)\ntorch_out = torch_model(x)\n# Export the model\ntorch.onnx.export(torch_model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=10,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/quantize_dequantize/gen.py",
        "content": "import json\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.ao.quantization import QuantStub, DeQuantStub\n\n# define NN architecture\n\n\nclass PredictLiquidationsV0(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.quant = QuantStub()\n        self.layer_1 = nn.Linear(in_features=41, out_features=1)\n        self.dequant = DeQuantStub()\n\n    def forward(self, x):\n        x = self.quant(x)\n        x = self.layer_1(x)\n        x = self.dequant(x)\n        return x\n\n\n# instantiate the model\nmodel_0 = PredictLiquidationsV0()\n\n# for QAT\n# model_0.qconfig = torch.ao.quantization.get_default_qat_qconfig('fbgemm')\ntorch.ao.quantization.prepare_qat(model_0, inplace=True)\n\n\n# convert to a QAT model\nquantized_model_0 = torch.ao.quantization.convert(\n    model_0.eval(), inplace=False)\n\n# evaluate quantized_model_0\n# ...\n\nx = torch.randn((1, 41), requires_grad=True)\n\n# export as onnx\nquantized_model_0.eval()\ntorch.onnx.export(quantized_model_0,\n                  torch.randn((1, 41), requires_grad=True),\n                  'network.onnx',\n                  input_names=['input'],\n                  output_names=['output'],\n                  dynamic_axes={'input': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_data=[d],)\n\n# save to input.json\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/random_forest/gen.py",
        "content": "# make sure you have the dependencies required here already installed\nimport json\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier as Rf\nimport sk2torch\nimport torch\nimport ezkl\nimport os\nfrom torch import nn\n\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = Rf()\nclr.fit(X_train, y_train)\n\n\ntrees = []\nfor tree in clr.estimators_:\n    trees.append(sk2torch.wrap(tree))\n\nprint(trees)\n\n\nclass RandomForest(nn.Module):\n    def __init__(self, trees):\n        super(RandomForest, self).__init__()\n        self.trees = nn.ModuleList(trees)\n\n    def forward(self, x):\n        out = self.trees[0](x)\n        for tree in self.trees[1:]:\n            out += tree(x)\n        return out / len(self.trees)\n\n\ntorch_rf = RandomForest(trees)\n# assert predictions from torch are = to sklearn\n\nfor i in range(len(X_test)):\n    torch_pred = torch_rf(torch.tensor(X_test[i].reshape(1, -1)))\n    sk_pred = clr.predict(X_test[i].reshape(1, -1))\n    print(torch_pred, sk_pred[0])\n    assert torch_pred[0].round() == sk_pred[0]\n\n\ntorch_rf.eval()\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = torch_rf(x)\n# Export the model\ntorch.onnx.export(torch_rf,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/reducel1/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.norm(x, p=1, dim=1)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 2, 2, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/reducel2/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.norm(x, p=2, dim=1)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 2, 2, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/remainder/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):                  \n        return x % 0.5\n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/rnn/gen.py",
        "content": "import random\nimport math\nimport numpy as np\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport json\n\n\nmodel = nn.RNN(3, 3)  # Input dim is 3, output dim is 3\nx = torch.randn(1, 3)  # make a sequence of length 5\n\nprint(x)\n\n# Flips the neural net into inference mode\nmodel.eval()\nmodel.to('cpu')\n\n# Export the model\ntorch.onnx.export(model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\ndata_array = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata_json = dict(input_data=[data_array])\n\nprint(data_json)\n\n# Serialize data into file:\njson.dump(data_json, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/rounding_ops/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n\n    def forward(self, w, x, y):\n\n        return torch.round(w), torch.floor(x), torch.ceil(y)\n\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 2, 3]\n    w = 0.1*torch.rand(1, *shape, requires_grad=True)\n    x = 0.1*torch.rand(1, *shape, requires_grad=True)\n    y = 0.1*torch.rand(1, *shape, requires_grad=True)\n    torch_out = torch_model(w, x, y)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      # model input (or a tuple for multiple inputs)\n                      (w, x, y),\n                      # where to save the model (can be a file or file-like object)\n                      \"network.onnx\",\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=16,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names=['w', 'x', 'y'],   # the model's input names\n                      # the model's output names\n                      output_names=['output_w', 'output_x', 'output_y'],\n                      dynamic_axes={'x': {0: 'batch_size'},    # variable length axes\n                                    'y': {0: 'batch_size'},\n                                    'w': {0: 'batch_size'},\n                                    'output_w': {0: 'batch_size'},\n                                    'output_x': {0: 'batch_size'},\n                                    'output_y': {0: 'batch_size'}\n                                    })\n\n    dw = ((w).detach().numpy()).reshape([-1]).tolist()\n    dx = ((x).detach().numpy()).reshape([-1]).tolist()\n    dy = ((y).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes=[shape, shape, shape, shape],\n                input_data=[dw, dx, dy],\n                output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/scatter_elements/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, w, x, src):\n        # scatter_elements\n        return w.scatter(2, x, src)\n\n\ncircuit = MyModel()\n\n\nw = torch.rand(1, 15, 18)\nsrc = torch.rand(1, 15, 2)\nx = torch.randint(0, 15, (1, 15, 2))\n\ntorch.onnx.export(circuit, (w, x, src), \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  # the model's input names\n                  input_names=['input', 'input1', 'input2'],\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'input1': {0: 'batch_size'},\n                                'input2': {0: 'batch_size'},\n                                'output': {0: 'batch_size'}})\n\n\nd = ((w).detach().numpy()).reshape([-1]).tolist()\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\nd2 = ((src).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d, d1, d2],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/scatter_nd/gen.py",
        "content": "import torch\nimport torch.nn as nn\nimport sys\nimport json\n\nsys.path.append(\"..\")\n\nclass Model(nn.Module):\n    \"\"\"\n    Just one Linear layer\n    \"\"\"\n    def __init__(self, configs):\n        super(Model, self).__init__()\n        self.seq_len = configs.seq_len\n        self.pred_len = configs.pred_len\n\n        # Use this line if you want to visualize the weights\n        # self.Linear.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len]))\n        self.channels = configs.enc_in\n        self.individual = configs.individual\n        if self.individual:\n            self.Linear = nn.ModuleList()\n            for i in range(self.channels):\n                self.Linear.append(nn.Linear(self.seq_len,self.pred_len))\n        else:\n            self.Linear = nn.Linear(self.seq_len, self.pred_len)\n\n    def forward(self, x):\n        # x: [Batch, Input length, Channel]\n        if self.individual:\n            output = torch.zeros([x.size(0),self.pred_len,x.size(2)],dtype=x.dtype).to(x.device)\n            for i in range(self.channels):\n                output[:,:,i] = self.Linear[i](x[:,:,i])\n            x = output\n        else:\n            x = self.Linear(x.permute(0,2,1)).permute(0,2,1)\n        return x # [Batch, Output length, Channel]\n\nclass Configs:\n    def __init__(self, seq_len, pred_len, enc_in=321, individual=True):\n      self.seq_len = seq_len\n      self.pred_len = pred_len\n      self.enc_in = enc_in\n      self.individual = individual\n\nmodel = 'Linear'\nseq_len = 10\npred_len = 4\nenc_in = 3\n\nconfigs = Configs(seq_len, pred_len, enc_in, True)\ncircuit = Model(configs)\n\nx = torch.randn(1, seq_len, pred_len)\n\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=15,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  # the model's input names\n                  input_names=['input'],\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/self_attention/gen.py",
        "content": "\n\"\"\"\nReference: https://github.com/karpathy/nanoGPT :)\n\"\"\"\n\nimport torch\nimport json\nfrom torch import nn\nimport math\nfrom dataclasses import dataclass\nfrom torch.nn import functional as F\n\n\n@dataclass\nclass GPTConfig:\n    block_size: int = 1024\n    vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency\n    n_layer: int = 12\n    n_head: int = 12\n    n_embd: int = 768\n    dropout: float = 0.0\n    bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster\n\n    \ndef new_gelu(x):\n    \"\"\"\n    Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).\n    Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415\n    \"\"\"\n    return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x)))\n\nclass CausalSelfAttention(nn.Module):\n\n    def __init__(self, config):\n        super().__init__()\n        assert config.n_embd % config.n_head == 0\n        # key, query, value projections for all heads, but in a batch\n        self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)\n        # output projection\n        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)\n        # regularization\n        self.attn_dropout = nn.Dropout(config.dropout)\n        self.resid_dropout = nn.Dropout(config.dropout)\n        self.n_head = config.n_head\n        self.n_embd = config.n_embd\n        self.dropout = config.dropout\n\n        # causal mask to ensure that attention is only applied to the left in the input sequence\n        self.register_buffer(\"bias\", torch.tril(torch.ones(config.block_size, config.block_size))\n                                        .view(1, 1, config.block_size, config.block_size))\n\n    def forward(self, x):\n        B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)\n        # calculate query, key, values for all heads in batch and move head forward to be the batch dim\n        q, k, v  = self.c_attn(x).split(self.n_embd, dim=2)\n        k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n        q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n        v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n\n        # manual implementation of attention\n        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) #q shape:(B, nh, T, hs), k transpose shape (B, nh, hs, T) -> (B, nh, T, T)\n        att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float(-10))\n        att = F.softmax(att, dim=-1)\n        att = self.attn_dropout(att)\n        y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n        y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side\n\n        y = self.resid_dropout(self.c_proj(y))\n        return y\n    \n\n  \nclass MLP(nn.Module):\n    def __init__(self, config):\n        super().__init__()\n        self.c_fc    = nn.Linear(config.n_embd, 4 * config.n_embd)\n        self.c_proj  = nn.Linear(4 * config.n_embd, config.n_embd)\n        self.dropout = nn.Dropout(config.dropout)\n\n    def forward(self, x):\n        x = self.c_fc(x)\n        x = new_gelu(x)\n        x = self.c_proj(x)\n        x = self.dropout(x)\n        return x\n    \nclass Block(nn.Module):\n    def __init__(self, config):\n        super().__init__()\n        self.ln_1 = nn.LayerNorm(config.n_embd)\n        self.attention = CausalSelfAttention(config)\n        self.ln_2 = nn.LayerNorm(config.n_embd)\n        self.mlp = MLP(config)\n\n    def forward(self, x):\n        x = x + self.attention(self.ln_1(x))\n        x = x + self.mlp(self.ln_2(x))\n        return x\n\n\n\nshape = [1, 64, 64]\nx =  torch.ones(1, 64, 64)\nconfig = GPTConfig(block_size = 64, vocab_size = 65, n_layer = 4, n_head = 4, n_embd = 64,dropout = 0.0, bias = False)\nmodel = Block(config)\ntorch_out = model(x)\n\ntorch.onnx.export(model, x, \"network.onnx\",\n       export_params=True,        # store the trained parameter weights inside the model file\n        opset_version=10,          # the ONNX version to export the model to\n        do_constant_folding=True,  # whether to execute constant folding for optimization\n        input_names = ['input'],   # the model's input names\n        output_names = ['output'], # the model's output names\n        dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes\n        'output' : {0 : 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes = [shape],\n            input_data = [d],\n            output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump( data, open( \"input.json\", 'w' ) )\n\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/selu/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.SELU()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/softplus/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.Softplus()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/softsign/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = nn.Softsign()(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 8).uniform_(0, 1)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/trig/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\n\nclass Circuit(nn.Module):\n    def __init__(self):\n        super(Circuit, self).__init__()\n        self.softplus = nn.Softplus()\n\n    def forward(self, x):\n        x = self.softplus(x)\n        x = torch.cos(x)\n        x = torch.sin(x)\n        x = torch.tan(x)\n        x = torch.acos(x)\n        x = torch.asin(x)\n        x = torch.atan(x)\n        # x = torch.cosh(x)\n        # x = torch.sinh(x)\n        x = torch.tanh(x)\n        # x = torch.acosh(x)\n        # x = torch.asinh(x)\n        # x = torch.atanh(x)\n        return (-x).abs().sign()\n\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 2, 3]\n    x = 0.1*torch.rand(1, *shape, requires_grad=True)\n    torch_out = torch_model(x)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      # model input (or a tuple for multiple inputs)\n                      x,\n                      # where to save the model (can be a file or file-like object)\n                      \"network.onnx\",\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names=['input'],   # the model's input names\n                      output_names=['output'],  # the model's output names\n                      dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                    'output': {0: 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes=[shape, shape, shape],\n                input_data=[d],\n                output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/tril/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.triu(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 3, 3).uniform_(0, 5)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/triu/gen.py",
        "content": "from torch import nn\nimport torch\nimport json\nimport numpy as np\n\n\nclass MyModel(nn.Module):\n    def __init__(self):\n        super(MyModel, self).__init__()\n\n    def forward(self, x):          \n        m = torch.tril(x)\n        \n        return m \n\n\ncircuit = MyModel()\n\nx = torch.empty(1, 3, 3).uniform_(0, 5)\n\nout = circuit(x)\n\nprint(out)\n\ntorch.onnx.export(circuit, x, \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=17,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},  # variable length axes\n                                'output': {0: 'batch_size'}})\n\n\nd1 = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(\n    input_data=[d1],\n)\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/tutorial/gen.py",
        "content": "import io\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport torch.nn as nn\nimport torch.nn.init as init\nimport json\n\n\nclass Circuit(nn.Module):\n    def __init__(self, inplace=False):\n        super(Circuit, self).__init__()\n\n        self.relu = nn.ReLU()\n        self.sigmoid = nn.Sigmoid()\n        self.conv = nn.Conv2d(3, 3, (2, 2), 1, 2)\n\n        self._initialize_weights()\n\n    def forward(self, x, y, z):\n        x = self.sigmoid(self.conv(y@x**2 + (x) - (self.relu(z)))) + 2\n        return (x, self.relu(z) / 3)\n\n    def _initialize_weights(self):\n        init.orthogonal_(self.conv.weight)\n\n\ndef main():\n    torch_model = Circuit()\n    # Input to the model\n    shape = [3, 2, 2]\n    x = 0.1*torch.rand(1, *shape, requires_grad=True)\n    y = 0.1*torch.rand(1, *shape, requires_grad=True)\n    z = 0.1*torch.rand(1, *shape, requires_grad=True)\n    torch_out = torch_model(x, y, z)\n    # Export the model\n    torch.onnx.export(torch_model,               # model being run\n                      # model input (or a tuple for multiple inputs)\n                      (x, y, z),\n                      # where to save the model (can be a file or file-like object)\n                      \"network.onnx\",\n                      export_params=True,        # store the trained parameter weights inside the model file\n                      opset_version=10,          # the ONNX version to export the model to\n                      do_constant_folding=True,  # whether to execute constant folding for optimization\n                      input_names=['input'],   # the model's input names\n                      output_names=['output'],  # the model's output names\n                      dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                    'output': {0: 'batch_size'}})\n\n    d = ((x).detach().numpy()).reshape([-1]).tolist()\n    dy = ((y).detach().numpy()).reshape([-1]).tolist()\n    dz = ((z).detach().numpy()).reshape([-1]).tolist()\n\n    data = dict(input_shapes=[shape, shape, shape],\n                input_data=[d, dy, dz],\n                output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out])\n\n    # Serialize data into file:\n    json.dump(data, open(\"input.json\", 'w'))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/xgboost/gen.py",
        "content": "# make sure you have the dependencies required here already installed\nimport json\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier as Gbc\nimport torch\nimport ezkl\nimport os\nfrom torch import nn\nimport xgboost as xgb\nfrom hummingbird.ml import convert\n\nNUM_CLASSES = 3\n\niris = load_iris()\nX, y = iris.data, iris.target\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = Gbc(n_estimators=12)\nclr.fit(X_train, y_train)\n\n# convert to torch\n\n\ntorch_gbt = convert(clr, 'torch')\n\nprint(torch_gbt)\n# assert predictions from torch are = to sklearn\ndiffs = []\n\nfor i in range(len(X_test)):\n    torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\n    sk_pred = clr.predict(X_test[i].reshape(1, -1))\n    diffs.append(torch_pred != sk_pred[0])\n\nprint(\"num diff: \", sum(diffs))\n\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = torch_gbt.predict(x)\n# Export the model\ntorch.onnx.export(torch_gbt.model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n\nd = ((x).detach().numpy()).reshape([-1]).tolist()\n\ndata = dict(input_shapes=[shape],\n            input_data=[d],\n            output_data=[(o).reshape([-1]).tolist() for o in torch_out])\n\n# Serialize data into file:\njson.dump(data, open(\"input.json\", 'w'))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "examples/onnx/xgboost_reg/gen.py",
        "content": "# make sure you have the dependencies required here already installed\nimport json\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBRegressor as Gbc\nimport torch\nimport ezkl\nimport os\nfrom torch import nn\nimport xgboost as xgb\nfrom hummingbird.ml import convert\n\nNUM_CLASSES = 3\n\nX, y = np.random.rand(1000, 4), np.random.rand(1000, 1)\nX = X.astype(np.float32)\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nclr = Gbc(n_estimators=12)\nclr.fit(X_train, y_train)\n\n# convert to torch\n\n\ntorch_gbt = convert(clr, 'torch')\n\nprint(torch_gbt)\n# assert predictions from torch are = to sklearn\ndiffs = []\n\n\n# Input to the model\nshape = X_train.shape[1:]\nx = torch.rand(1, *shape, requires_grad=False)\ntorch_out = torch_gbt.predict(x)\n# Export the model\ntorch.onnx.export(torch_gbt.model,               # model being run\n                  # model input (or a tuple for multiple inputs)\n                  x,\n                  # where to save the model (can be a file or file-like object)\n                  \"network.onnx\",\n                  export_params=True,        # store the trained parameter weights inside the model file\n                  opset_version=11,          # the ONNX version to export the model to\n                  do_constant_folding=True,  # whether to execute constant folding for optimization\n                  input_names=['input'],   # the model's input names\n                  output_names=['output'],  # the model's output names\n                  dynamic_axes={'input': {0: 'batch_size'},    # variable length axes\n                                'output': {0: 'batch_size'}})\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "jest.config.js",
        "content": "module.exports = {\n    preset: 'ts-jest',\n    testEnvironment: 'node',\n  };"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/bin/ezkl.rs",
        "content": "// ignore file if compiling for wasm\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse clap::Parser;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored_json::ToColoredJson;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse ezkl::commands::Cli;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse ezkl::execute::run;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse ezkl::logger::init_logger;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse log::{debug, error, info};\n#[cfg(not(any(target_arch = \"wasm32\", feature = \"no-banner\")))]\nuse rand::prelude::SliceRandom;\n#[cfg(not(target_arch = \"wasm32\"))]\n#[cfg(feature = \"icicle\")]\nuse std::env;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::error::Error;\n\n#[tokio::main(flavor = \"current_thread\")]\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn main() -> Result<(), Box<dyn Error>> {\n    let args = Cli::parse();\n    init_logger();\n    #[cfg(not(any(target_arch = \"wasm32\", feature = \"no-banner\")))]\n    banner();\n    #[cfg(feature = \"icicle\")]\n    if env::var(\"ENABLE_ICICLE_GPU\").is_ok() {\n        info!(\"Running with ICICLE GPU\");\n    } else {\n        info!(\"Running with CPU\");\n    }\n    debug!(\"command: \\n {}\", &args.as_json()?.to_colored_json_auto()?);\n    let res = run(args.command).await;\n    match &res {\n        Ok(_) => info!(\"succeeded\"),\n        Err(e) => error!(\"failed: {}\", e),\n    };\n    res.map(|_| ())\n}\n\n#[cfg(target_arch = \"wasm32\")]\npub fn main() {}\n\n#[cfg(not(any(target_arch = \"wasm32\", feature = \"no-banner\")))]\nfn banner() {\n    let ell: Vec<&str> = vec![\n        \"for Neural Networks\",\n        \"Linear Algebra\",\n        \"for Layers\",\n        \"for the Laconic\",\n        \"Learning\",\n        \"for Liberty\",\n        \"for the Lyrical\",\n    ];\n    info!(\n        \"{}\",\n        format!(\n            \"\n\n        \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557  \u2588\u2588\u2557\u2588\u2588\u2557\n        \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2551\n        \u2588\u2588\u2588\u2588\u2588\u2557    \u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2551\n        \u2588\u2588\u2554\u2550\u2550\u255d   \u2588\u2588\u2588\u2554\u255d  \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551\n        \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551  \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\n        \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d  \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n        -----------------------------------------------------------\n        Easy Zero Knowledge {}.\n        -----------------------------------------------------------\n\n        \",\n            ell.choose(&mut rand::thread_rng()).unwrap()\n        )\n    );\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/mod.rs",
        "content": "///\npub mod modules;\n\n///\npub mod table;\n\n///\npub mod utils;\n\n///\npub mod ops;\n\npub use ops::chip::*;\npub use ops::*;\n\n/// Tests\n#[cfg(test)]\nmod tests;\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/mod.rs",
        "content": "///\npub mod poseidon;\n\n///\npub mod polycommit;\n\n///\npub mod planner;\nuse halo2_proofs::{\n    circuit::Layouter,\n    plonk::{ConstraintSystem, Error},\n};\nuse halo2curves::ff::PrimeField;\npub use planner::*;\n\nuse crate::tensor::{TensorType, ValTensor};\n\nuse super::region::ConstantsMap;\n\n/// Module trait used to extend ezkl functionality\npub trait Module<F: PrimeField + TensorType + PartialOrd> {\n    /// Config\n    type Config;\n    /// The return type after an input assignment\n    type InputAssignments;\n    /// The inputs used in the run function\n    type RunInputs;\n    /// The params used in configure\n    type Params;\n\n    /// construct new module from config\n    fn new(config: Self::Config) -> Self;\n    /// Configure\n    fn configure(meta: &mut ConstraintSystem<F>, params: Self::Params) -> Self::Config;\n    /// Name\n    fn name(&self) -> &'static str;\n    /// Run the operation the module represents\n    fn run(input: Self::RunInputs) -> Result<Vec<Vec<F>>, Box<dyn std::error::Error>>;\n    /// Layout inputs\n    fn layout_inputs(\n        &self,\n        layouter: &mut impl Layouter<F>,\n        input: &[ValTensor<F>],\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<Self::InputAssignments, Error>;\n    /// Layout\n    fn layout(\n        &self,\n        layouter: &mut impl Layouter<F>,\n        input: &[ValTensor<F>],\n        row_offset: usize,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<ValTensor<F>, Error>;\n    /// Number of instance values the module uses every time it is applied\n    fn instance_increment_input(&self) -> Vec<usize>;\n    /// Number of rows used by the module\n    fn num_rows(input_len: usize) -> usize;\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/planner.rs",
        "content": "use std::cmp;\nuse std::collections::HashMap;\nuse std::fmt;\nuse std::marker::PhantomData;\n\nuse halo2curves::ff::Field;\n\nuse halo2_proofs::{\n    circuit::{\n        layouter::{RegionColumn, RegionLayouter, RegionShape, SyncDeps, TableLayouter},\n        Cell, Layouter, Region, RegionIndex, RegionStart, Table, Value,\n    },\n    plonk::{\n        Advice, Any, Assigned, Assignment, Challenge, Circuit, Column, Error, Fixed, FloorPlanner,\n        Instance, Selector, TableColumn,\n    },\n};\nuse log::{debug, trace};\n\n/// A simple [`FloorPlanner`] that performs minimal optimizations.\n#[derive(Debug)]\npub struct ModulePlanner;\n\nimpl FloorPlanner for ModulePlanner {\n    fn synthesize<F: Field, CS: Assignment<F> + SyncDeps, C: Circuit<F>>(\n        cs: &mut CS,\n        circuit: &C,\n        config: C::Config,\n        constants: Vec<Column<Fixed>>,\n    ) -> Result<(), Error> {\n        let layouter = ModuleLayouter::new(cs, constants)?;\n        circuit.synthesize(config, layouter)\n    }\n}\n///\npub type ModuleIdx = usize;\n///\npub type RegionIdx = usize;\n\n/// A [`Layouter`] for a circuit with multiple modules.\npub struct ModuleLayouter<'a, F: Field, CS: Assignment<F> + 'a> {\n    cs: &'a mut CS,\n    constants: Vec<Column<Fixed>>,\n    /// Stores the starting row for each region.\n    regions: HashMap<ModuleIdx, HashMap<RegionIdx, RegionStart>>,\n    /// Stores the starting row for each region.\n    region_idx: HashMap<RegionIdx, ModuleIdx>,\n    /// Stores the first empty row for each column.\n    columns: HashMap<(ModuleIdx, RegionColumn), usize>,\n    /// Stores the table fixed columns.\n    table_columns: Vec<TableColumn>,\n    _marker: PhantomData<F>,\n    /// current module\n    current_module: usize,\n    /// num_constants\n    total_constants: usize,\n}\n\nimpl<'a, F: Field, CS: Assignment<F> + 'a> fmt::Debug for ModuleLayouter<'a, F, CS> {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        f.debug_struct(\"ModuleLayouter\")\n            .field(\"regions\", &self.regions)\n            .field(\"columns\", &self.columns)\n            .field(\"total_constants\", &self.total_constants)\n            .finish()\n    }\n}\n\nimpl<'a, F: Field, CS: Assignment<F>> ModuleLayouter<'a, F, CS> {\n    /// Creates a new module layouter.\n    pub fn new(cs: &'a mut CS, constants: Vec<Column<Fixed>>) -> Result<Self, Error> {\n        let ret = ModuleLayouter {\n            cs,\n            constants,\n            regions: HashMap::default(),\n            columns: HashMap::default(),\n            region_idx: HashMap::default(),\n            table_columns: vec![],\n            current_module: 0,\n            total_constants: 0,\n            _marker: PhantomData,\n        };\n        Ok(ret)\n    }\n\n    ///\n    fn get_constant_col_cartesian_coord(\n        &self,\n        linear_coord: usize,\n        col_size: usize,\n    ) -> (usize, usize) {\n        let x = linear_coord / col_size;\n        let y = linear_coord % col_size;\n        (x, y)\n    }\n}\n\nimpl<'a, F: Field, CS: Assignment<F> + 'a + SyncDeps> Layouter<F> for ModuleLayouter<'a, F, CS> {\n    type Root = Self;\n\n    fn assign_region<A, AR, N, NR>(&mut self, name: N, mut assignment: A) -> Result<AR, Error>\n    where\n        A: FnMut(Region<'_, F>) -> Result<AR, Error>,\n        N: Fn() -> NR,\n        NR: Into<String>,\n    {\n        // if the name contains the required substring we increment the current module idx\n        if Into::<String>::into(name()).contains(\"_enter_module_\") {\n            let name = Into::<String>::into(name());\n            let index = match name.split(\"_enter_module_\").last() {\n                Some(v) => v,\n                None => {\n                    log::error!(\"Invalid module name\");\n                    return Err(Error::Synthesis);\n                }\n            };\n            let index = index.parse::<usize>().map_err(|_| {\n                log::error!(\"Invalid module name\");\n                Error::Synthesis\n            })?;\n            if !self.regions.contains_key(&index) {\n                debug!(\"spawning module {}\", index)\n            };\n            self.current_module = index;\n        }\n\n        let region_index = self.region_idx.len();\n        self.region_idx.insert(region_index, self.current_module);\n\n        // Get shape of the region.\n        let mut shape = RegionShape::new(region_index.into());\n        {\n            let region: &mut dyn RegionLayouter<F> = &mut shape;\n            assignment(region.into())?;\n        }\n\n        // Modules are stacked horizontally across new columns -- THIS ASSUMES THE MODULES HAVE NON OVERLAPPING COLUMNS.\n        let region_start = match self.regions.get_mut(&self.current_module) {\n            Some(v) => {\n                let mut region_start = 0;\n                for column in shape.columns().iter() {\n                    region_start = cmp::max(\n                        region_start,\n                        self.columns\n                            .get(&(self.current_module, *column))\n                            .cloned()\n                            .unwrap_or(0),\n                    );\n                }\n\n                v.insert(region_index, region_start.into());\n                region_start\n            }\n            None => {\n                let map = HashMap::from([(region_index, 0.into())]);\n                self.regions.insert(self.current_module, map);\n                0\n            }\n        };\n\n        // Update column usage information.\n        for column in shape.columns() {\n            self.columns.insert(\n                (self.current_module, *column),\n                region_start + shape.row_count(),\n            );\n        }\n\n        // Assign region cells.\n        self.cs.enter_region(name);\n        let mut region = ModuleLayouterRegion::new(self, region_index.into());\n        let result = {\n            let region: &mut dyn RegionLayouter<F> = &mut region;\n            assignment(region.into())\n        }?;\n        let constants_to_assign = region.constants;\n        self.cs.exit_region();\n\n        // Assign constants. For the simple floor planner, we assign constants in order in\n        // the first `constants` column.\n        if self.constants.is_empty() {\n            if !constants_to_assign.is_empty() {\n                return Err(Error::NotEnoughColumnsForConstants);\n            }\n        } else {\n            for (constant, advice) in constants_to_assign {\n                // read path from OS env\n                let (constant_column, y) = crate::graph::GLOBAL_SETTINGS.with(|settings| {\n                    match settings.borrow().as_ref() {\n                        Some(settings) => {\n                            let col_size = settings.available_col_size();\n                            let (x, y) = self\n                                .get_constant_col_cartesian_coord(self.total_constants, col_size);\n                            (self.constants[x], y)\n                        }\n                        None => (self.constants[0], self.total_constants),\n                    }\n                });\n\n                self.cs.assign_fixed(\n                    || format!(\"Constant({:?})\", constant.evaluate()),\n                    constant_column,\n                    y,\n                    || Value::known(constant),\n                )?;\n\n                let region_module = self.region_idx[&advice.region_index];\n\n                self.cs.copy(\n                    constant_column.into(),\n                    y,\n                    advice.column,\n                    *self.regions[&region_module][&advice.region_index] + advice.row_offset,\n                )?;\n                self.total_constants += 1;\n            }\n        }\n\n        trace!(\"region {} assigned\", region_index);\n        trace!(\"total_constants: {:?}\", self.total_constants);\n        let max_row_index = self\n            .columns\n            .iter()\n            .filter(|((module, _), _)| *module == self.current_module)\n            .map(|(_, row)| *row)\n            .max()\n            .unwrap_or(0);\n        trace!(\"max_row_index: {:?}\", max_row_index);\n\n        Ok(result)\n    }\n\n    fn assign_table<A, N, NR>(&mut self, name: N, mut assignment: A) -> Result<(), Error>\n    where\n        A: FnMut(Table<'_, F>) -> Result<(), Error>,\n        N: Fn() -> NR,\n        NR: Into<String>,\n    {\n        // Maintenance hazard: there is near-duplicate code in `v1::AssignmentPass::assign_table`.\n        // Assign table cells.\n        self.cs.enter_region(name);\n        let mut table =\n            halo2_proofs::circuit::SimpleTableLayouter::new(self.cs, &self.table_columns);\n        {\n            let table: &mut dyn TableLayouter<F> = &mut table;\n            assignment(table.into())\n        }?;\n        let default_and_assigned = table.default_and_assigned;\n        self.cs.exit_region();\n\n        // Check that all table columns have the same length `first_unused`,\n        // and all cells up to that length are assigned.\n        let first_unused = {\n            match default_and_assigned\n                .values()\n                .map(|(_, assigned)| {\n                    if assigned.iter().all(|b| *b) {\n                        Some(assigned.len())\n                    } else {\n                        None\n                    }\n                })\n                .reduce(|acc, item| match (acc, item) {\n                    (Some(a), Some(b)) if a == b => Some(a),\n                    _ => None,\n                }) {\n                Some(Some(len)) => len,\n                _ => return Err(Error::Synthesis), // TODO better error\n            }\n        };\n\n        // Record these columns so that we can prevent them from being used again.\n        for column in default_and_assigned.keys() {\n            self.table_columns.push(*column);\n        }\n\n        for (col, (default_val, _)) in default_and_assigned {\n            // default_val must be Some because we must have assigned\n            // at least one cell in each column, and in that case we checked\n            // that all cells up to first_unused were assigned.\n            let default_val = default_val.ok_or(Error::Synthesis)?;\n\n            self.cs\n                .fill_from_row(col.inner(), first_unused, default_val)?;\n        }\n\n        Ok(())\n    }\n\n    fn constrain_instance(\n        &mut self,\n        cell: Cell,\n        instance: Column<Instance>,\n        row: usize,\n    ) -> Result<(), Error> {\n        let module_idx = self.region_idx[&cell.region_index];\n\n        self.cs.copy(\n            cell.column,\n            *self.regions[&module_idx][&cell.region_index] + cell.row_offset,\n            instance.into(),\n            row,\n        )\n    }\n\n    fn get_challenge(&self, challenge: Challenge) -> Value<F> {\n        self.cs.get_challenge(challenge)\n    }\n\n    fn get_root(&mut self) -> &mut Self::Root {\n        self\n    }\n\n    fn push_namespace<NR, N>(&mut self, name_fn: N)\n    where\n        NR: Into<String>,\n        N: FnOnce() -> NR,\n    {\n        self.cs.push_namespace(name_fn)\n    }\n\n    fn pop_namespace(&mut self, gadget_name: Option<String>) {\n        self.cs.pop_namespace(gadget_name)\n    }\n}\n\nstruct ModuleLayouterRegion<'r, 'a, F: Field, CS: Assignment<F> + 'a> {\n    layouter: &'r mut ModuleLayouter<'a, F, CS>,\n    region_index: RegionIndex,\n    /// Stores the constants to be assigned, and the cells to which they are copied.\n    constants: Vec<(Assigned<F>, Cell)>,\n}\n\nimpl<'r, 'a, F: Field, CS: Assignment<F> + 'a> fmt::Debug for ModuleLayouterRegion<'r, 'a, F, CS> {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        f.debug_struct(\"ModuleLayouterRegion\")\n            .field(\"layouter\", &self.layouter)\n            .field(\"region_index\", &self.region_index)\n            .finish()\n    }\n}\n\nimpl<'r, 'a, F: Field, CS: Assignment<F> + 'a> ModuleLayouterRegion<'r, 'a, F, CS> {\n    fn new(layouter: &'r mut ModuleLayouter<'a, F, CS>, region_index: RegionIndex) -> Self {\n        ModuleLayouterRegion {\n            layouter,\n            region_index,\n            constants: vec![],\n        }\n    }\n}\n\nimpl<'r, 'a, F: Field, CS: Assignment<F> + 'a + SyncDeps> RegionLayouter<F>\n    for ModuleLayouterRegion<'r, 'a, F, CS>\n{\n    fn instance_value(\n        &mut self,\n        instance: Column<Instance>,\n        row: usize,\n    ) -> Result<Value<F>, Error> {\n        self.layouter.cs.query_instance(instance, row)\n    }\n\n    fn enable_selector<'v>(\n        &'v mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        selector: &Selector,\n        offset: usize,\n    ) -> Result<(), Error> {\n        let module_idx = self.layouter.region_idx[&self.region_index];\n        self.layouter.cs.enable_selector(\n            annotation,\n            selector,\n            *self.layouter.regions[&module_idx][&self.region_index] + offset,\n        )\n    }\n\n    fn name_column<'v>(\n        &'v mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        column: Column<Any>,\n    ) {\n        self.layouter.cs.annotate_column(annotation, column);\n    }\n\n    fn assign_advice<'v>(\n        &'v mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        column: Column<Advice>,\n        offset: usize,\n        to: &'v mut (dyn FnMut() -> Value<Assigned<F>> + 'v),\n    ) -> Result<Cell, Error> {\n        let module_idx = self.layouter.region_idx[&self.region_index];\n\n        self.layouter.cs.assign_advice(\n            annotation,\n            column,\n            *self.layouter.regions[&module_idx][&self.region_index] + offset,\n            to,\n        )?;\n\n        Ok(Cell {\n            region_index: self.region_index,\n            row_offset: offset,\n            column: column.into(),\n        })\n    }\n\n    fn assign_advice_from_constant<'v>(\n        &'v mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        column: Column<Advice>,\n        offset: usize,\n        constant: Assigned<F>,\n    ) -> Result<Cell, Error> {\n        let advice =\n            self.assign_advice(annotation, column, offset, &mut || Value::known(constant))?;\n        self.constrain_constant(advice, constant)?;\n\n        Ok(advice)\n    }\n\n    fn assign_advice_from_instance<'v>(\n        &mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        instance: Column<Instance>,\n        row: usize,\n        advice: Column<Advice>,\n        offset: usize,\n    ) -> Result<(Cell, Value<F>), Error> {\n        let value = self.layouter.cs.query_instance(instance, row)?;\n\n        let cell = self.assign_advice(annotation, advice, offset, &mut || value.to_field())?;\n        let module_idx = self.layouter.region_idx[&cell.region_index];\n\n        self.layouter.cs.copy(\n            cell.column,\n            *self.layouter.regions[&module_idx][&cell.region_index] + cell.row_offset,\n            instance.into(),\n            row,\n        )?;\n\n        Ok((cell, value))\n    }\n\n    fn assign_fixed<'v>(\n        &'v mut self,\n        annotation: &'v (dyn Fn() -> String + 'v),\n        column: Column<Fixed>,\n        offset: usize,\n        to: &'v mut (dyn FnMut() -> Value<Assigned<F>> + 'v),\n    ) -> Result<Cell, Error> {\n        let module_idx = self.layouter.region_idx[&self.region_index];\n\n        self.layouter.cs.assign_fixed(\n            annotation,\n            column,\n            *self.layouter.regions[&module_idx][&self.region_index] + offset,\n            to,\n        )?;\n\n        Ok(Cell {\n            region_index: self.region_index,\n            row_offset: offset,\n            column: column.into(),\n        })\n    }\n\n    fn constrain_constant(&mut self, cell: Cell, constant: Assigned<F>) -> Result<(), Error> {\n        self.constants.push((constant, cell));\n        Ok(())\n    }\n\n    fn constrain_equal(&mut self, left: Cell, right: Cell) -> Result<(), Error> {\n        let left_module = self.layouter.region_idx[&left.region_index];\n        let right_module = self.layouter.region_idx[&right.region_index];\n\n        self.layouter.cs.copy(\n            left.column,\n            *self.layouter.regions[&left_module][&left.region_index] + left.row_offset,\n            right.column,\n            *self.layouter.regions[&right_module][&right.region_index] + right.row_offset,\n        )?;\n\n        Ok(())\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use halo2curves::pasta::vesta;\n\n    use super::ModulePlanner;\n    use halo2_proofs::{\n        dev::MockProver,\n        plonk::{Advice, Circuit, Column, Error},\n    };\n\n    #[test]\n    fn not_enough_columns_for_constants() {\n        struct MyCircuit {}\n\n        impl Circuit<vesta::Scalar> for MyCircuit {\n            type Config = Column<Advice>;\n            type FloorPlanner = ModulePlanner;\n            type Params = ();\n\n            fn without_witnesses(&self) -> Self {\n                MyCircuit {}\n            }\n\n            fn configure(\n                meta: &mut halo2_proofs::plonk::ConstraintSystem<vesta::Scalar>,\n            ) -> Self::Config {\n                meta.advice_column()\n            }\n\n            fn synthesize(\n                &self,\n                config: Self::Config,\n                mut layouter: impl halo2_proofs::circuit::Layouter<vesta::Scalar>,\n            ) -> Result<(), halo2_proofs::plonk::Error> {\n                layouter.assign_region(\n                    || \"assign constant\",\n                    |mut region| {\n                        region.assign_advice_from_constant(\n                            || \"one\",\n                            config,\n                            0,\n                            vesta::Scalar::one(),\n                        )\n                    },\n                )?;\n\n                Ok(())\n            }\n        }\n\n        let circuit = MyCircuit {};\n        assert!(matches!(\n            MockProver::run(3, &circuit, vec![]).unwrap_err(),\n            Error::NotEnoughColumnsForConstants,\n        ));\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/polycommit.rs",
        "content": "/*\nAn easy-to-use implementation of the Poseidon Hash in the form of a Halo2 Chip. While the Poseidon Hash function\nis already implemented in halo2_gadgets, there is no wrapper chip that makes it easy to use in other circuits.\nThanks to https://github.com/summa-dev/summa-solvency/blob/master/src/chips/poseidon/hash.rs for the inspiration (and also helping us understand how to use this).\n*/\n\nuse std::collections::HashMap;\n\n// This chip adds a set of advice columns to the gadget Chip to store the inputs of the hash\nuse halo2_proofs::halo2curves::bn256::Fr as Fp;\nuse halo2_proofs::poly::commitment::{Blind, CommitmentScheme, Params};\nuse halo2_proofs::{circuit::*, plonk::*};\nuse halo2curves::bn256::G1Affine;\nuse halo2curves::group::prime::PrimeCurveAffine;\nuse halo2curves::group::Curve;\nuse halo2curves::CurveAffine;\n\nuse crate::circuit::region::ConstantsMap;\nuse crate::tensor::{Tensor, ValTensor, ValType, VarTensor};\n\nuse super::Module;\n\n/// The number of instance columns used by the PolyCommit hash function\npub const NUM_INSTANCE_COLUMNS: usize = 0;\n/// The number of advice columns used by the PolyCommit hash function\npub const NUM_INNER_COLS: usize = 1;\n\n#[derive(Debug, Clone)]\n/// Configuration for the PolyCommit chip\npub struct PolyCommitConfig {\n    ///\n    pub inputs: VarTensor,\n}\n\ntype InputAssignments = ();\n\n///\n#[derive(Debug)]\npub struct PolyCommitChip {\n    config: PolyCommitConfig,\n}\n\nimpl PolyCommitChip {\n    /// Commit to the message using the KZG commitment scheme\n    pub fn commit<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>(\n        message: Vec<Scheme::Scalar>,\n        num_unusable_rows: u32,\n        params: &Scheme::ParamsProver,\n    ) -> Vec<G1Affine> {\n        let k = params.k();\n        let domain = halo2_proofs::poly::EvaluationDomain::new(2, k);\n        let n = 2_u64.pow(k) - num_unusable_rows as u64;\n        let num_poly = (message.len() / n as usize) + 1;\n        let mut poly = vec![domain.empty_lagrange(); num_poly];\n\n        (0..num_unusable_rows).for_each(|i| {\n            for p in &mut poly {\n                p[(n + i as u64) as usize] = Blind::default().0;\n            }\n        });\n\n        for (i, m) in message.iter().enumerate() {\n            let x = i / (n as usize);\n            let y = i % (n as usize);\n            poly[x][y] = *m;\n        }\n\n        let mut advice_commitments_projective = vec![];\n        for a in poly {\n            advice_commitments_projective.push(params.commit_lagrange(&a, Blind::default()))\n        }\n\n        let mut advice_commitments =\n            vec![G1Affine::identity(); advice_commitments_projective.len()];\n        <G1Affine as CurveAffine>::CurveExt::batch_normalize(\n            &advice_commitments_projective,\n            &mut advice_commitments,\n        );\n        advice_commitments\n    }\n}\n\nimpl Module<Fp> for PolyCommitChip {\n    type Config = PolyCommitConfig;\n    type InputAssignments = InputAssignments;\n    type RunInputs = Vec<Fp>;\n    type Params = (usize, usize);\n\n    fn name(&self) -> &'static str {\n        \"PolyCommit\"\n    }\n\n    fn instance_increment_input(&self) -> Vec<usize> {\n        vec![0]\n    }\n\n    /// Constructs a new PoseidonChip\n    fn new(config: Self::Config) -> Self {\n        Self { config }\n    }\n\n    /// Configuration of the PoseidonChip\n    fn configure(meta: &mut ConstraintSystem<Fp>, params: Self::Params) -> Self::Config {\n        let inputs = VarTensor::new_unblinded_advice(meta, params.0, NUM_INNER_COLS, params.1);\n        Self::Config { inputs }\n    }\n\n    fn layout_inputs(\n        &self,\n        _: &mut impl Layouter<Fp>,\n        _: &[ValTensor<Fp>],\n        _: &mut ConstantsMap<Fp>,\n    ) -> Result<Self::InputAssignments, Error> {\n        Ok(())\n    }\n\n    /// L is the number of inputs to the hash function\n    /// Takes the cells containing the input values of the hash function and return the cell containing the hash output\n    /// It uses the pow5_chip to compute the hash\n    fn layout(\n        &self,\n        layouter: &mut impl Layouter<Fp>,\n        input: &[ValTensor<Fp>],\n        _: usize,\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<ValTensor<Fp>, Error> {\n        assert_eq!(input.len(), 1);\n\n        let local_constants = constants.clone();\n        layouter.assign_region(\n            || \"PolyCommit\",\n            |mut region| {\n                let mut local_inner_constants = local_constants.clone();\n                let res = self.config.inputs.assign(\n                    &mut region,\n                    0,\n                    &input[0],\n                    &mut local_inner_constants,\n                )?;\n                *constants = local_inner_constants;\n                Ok(res)\n            },\n        )\n    }\n\n    ///\n    fn run(message: Vec<Fp>) -> Result<Vec<Vec<Fp>>, Box<dyn std::error::Error>> {\n        Ok(vec![message])\n    }\n\n    fn num_rows(_: usize) -> usize {\n        0\n    }\n}\n\n#[allow(unused)]\nmod tests {\n\n    use crate::circuit::modules::ModulePlanner;\n\n    use super::*;\n\n    use std::marker::PhantomData;\n\n    use halo2_proofs::{\n        circuit::{Layouter, SimpleFloorPlanner, Value},\n        plonk::{Circuit, ConstraintSystem},\n    };\n    use halo2curves::ff::Field;\n\n    const K: usize = 8;\n    const R: usize = 2048;\n\n    struct HashCircuit {\n        message: ValTensor<Fp>,\n    }\n\n    impl Circuit<Fp> for HashCircuit {\n        type Config = PolyCommitConfig;\n        type FloorPlanner = ModulePlanner;\n        type Params = ();\n\n        fn without_witnesses(&self) -> Self {\n            let empty_val: Vec<ValType<Fp>> = vec![Value::<Fp>::unknown().into(); R];\n            let message: Tensor<ValType<Fp>> = empty_val.into_iter().into();\n\n            Self {\n                message: message.into(),\n            }\n        }\n\n        fn configure(meta: &mut ConstraintSystem<Fp>) -> Self::Config {\n            let params = (K, R);\n            PolyCommitChip::configure(meta, params)\n        }\n\n        fn synthesize(\n            &self,\n            config: Self::Config,\n            mut layouter: impl Layouter<Fp>,\n        ) -> Result<(), Error> {\n            let polycommit_chip = PolyCommitChip::new(config);\n            polycommit_chip.layout(\n                &mut layouter,\n                &[self.message.clone()],\n                0,\n                &mut HashMap::new(),\n            );\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn polycommit_chip_for_a_range_of_input_sizes() {\n        let rng = rand::rngs::OsRng;\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        env_logger::init();\n\n        {\n            let i = 32;\n            // print a bunch of new lines\n            println!(\n                \"i is {} -------------------------------------------------\",\n                i\n            );\n\n            let message: Vec<Fp> = (0..i).map(|_| Fp::random(rng)).collect::<Vec<_>>();\n\n            let mut message: Tensor<ValType<Fp>> =\n                message.into_iter().map(|m| Value::known(m).into()).into();\n\n            let circuit = HashCircuit {\n                message: message.into(),\n            };\n            let prover = halo2_proofs::dev::MockProver::run(K as u32, &circuit, vec![]).unwrap();\n\n            assert_eq!(prover.verify(), Ok(()))\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn polycommit_chip_much_longer_input() {\n        #[cfg(not(target_arch = \"wasm32\"))]\n        env_logger::init();\n\n        let rng = rand::rngs::OsRng;\n\n        let mut message: Vec<Fp> = (0..2048).map(|_| Fp::random(rng)).collect::<Vec<_>>();\n\n        let mut message: Tensor<ValType<Fp>> =\n            message.into_iter().map(|m| Value::known(m).into()).into();\n\n        let circuit = HashCircuit {\n            message: message.into(),\n        };\n        let prover = halo2_proofs::dev::MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        assert_eq!(prover.verify(), Ok(()))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/poseidon.rs",
        "content": "/*\nAn easy-to-use implementation of the Poseidon Hash in the form of a Halo2 Chip. While the Poseidon Hash function\nis already implemented in halo2_gadgets, there is no wrapper chip that makes it easy to use in other circuits.\nThanks to https://github.com/summa-dev/summa-solvency/blob/master/src/chips/poseidon/hash.rs for the inspiration (and also helping us understand how to use this).\n*/\n\npub mod poseidon_params;\npub mod spec;\n\n// This chip adds a set of advice columns to the gadget Chip to store the inputs of the hash\nuse halo2_gadgets::poseidon::{primitives::*, Hash, Pow5Chip, Pow5Config};\nuse halo2_proofs::arithmetic::Field;\nuse halo2_proofs::halo2curves::bn256::Fr as Fp;\nuse halo2_proofs::{circuit::*, plonk::*};\n// use maybe_rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator};\nuse maybe_rayon::prelude::ParallelIterator;\nuse maybe_rayon::slice::ParallelSlice;\n\nuse std::marker::PhantomData;\n\nuse crate::circuit::region::ConstantsMap;\nuse crate::tensor::{Tensor, ValTensor, ValType};\n\nuse super::Module;\n\n/// The number of instance columns used by the Poseidon hash function\npub const NUM_INSTANCE_COLUMNS: usize = 1;\n\n#[derive(Debug, Clone)]\n/// WIDTH, RATE and L are const generics for the struct, which represent the width, rate, and number of inputs for the Poseidon hash function, respectively.\n/// This means they are values that are known at compile time and can be used to specialize the implementation of the struct.\n/// The actual chip provided by halo2_gadgets is added to the parent Chip.\npub struct PoseidonConfig<const WIDTH: usize, const RATE: usize> {\n    ///\n    pub hash_inputs: Vec<Column<Advice>>,\n    ///\n    pub instance: Option<Column<Instance>>,\n    ///\n    pub pow5_config: Pow5Config<Fp, WIDTH, RATE>,\n}\n\ntype InputAssignments = (Vec<AssignedCell<Fp, Fp>>, AssignedCell<Fp, Fp>);\n\n/// PoseidonChip is a wrapper around the Pow5Chip that adds a set of advice columns to the gadget Chip to store the inputs of the hash\n#[derive(Debug, Clone)]\npub struct PoseidonChip<\n    S: Spec<Fp, WIDTH, RATE> + Sync,\n    const WIDTH: usize,\n    const RATE: usize,\n    const L: usize,\n> {\n    config: PoseidonConfig<WIDTH, RATE>,\n    _marker: PhantomData<S>,\n}\n\nimpl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize>\n    PoseidonChip<S, WIDTH, RATE, L>\n{\n    /// Creates a new PoseidonChip\n    pub fn configure_with_cols(\n        meta: &mut ConstraintSystem<Fp>,\n        partial_sbox: Column<Advice>,\n        rc_a: [Column<Fixed>; WIDTH],\n        rc_b: [Column<Fixed>; WIDTH],\n        hash_inputs: Vec<Column<Advice>>,\n        instance: Option<Column<Instance>>,\n    ) -> PoseidonConfig<WIDTH, RATE> {\n        let pow5_config = Pow5Chip::configure::<S>(\n            meta,\n            hash_inputs.clone().try_into().unwrap(),\n            partial_sbox,\n            rc_a,\n            rc_b,\n        );\n\n        PoseidonConfig {\n            pow5_config,\n            instance,\n            hash_inputs,\n        }\n    }\n}\n\nimpl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize>\n    PoseidonChip<S, WIDTH, RATE, L>\n{\n    /// Configuration of the PoseidonChip\n    pub fn configure_with_optional_instance(\n        meta: &mut ConstraintSystem<Fp>,\n        instance: Option<Column<Instance>>,\n    ) -> PoseidonConfig<WIDTH, RATE> {\n        //  instantiate the required columns\n        let hash_inputs = (0..WIDTH).map(|_| meta.advice_column()).collect::<Vec<_>>();\n        for input in &hash_inputs {\n            meta.enable_equality(*input);\n        }\n\n        let partial_sbox = meta.advice_column();\n        let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n        let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n\n        for input in hash_inputs.iter().take(WIDTH) {\n            meta.enable_equality(*input);\n        }\n        meta.enable_constant(rc_b[0]);\n\n        Self::configure_with_cols(\n            meta,\n            partial_sbox,\n            rc_a.try_into().unwrap(),\n            rc_b.try_into().unwrap(),\n            hash_inputs,\n            instance,\n        )\n    }\n}\n\nimpl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize>\n    Module<Fp> for PoseidonChip<S, WIDTH, RATE, L>\n{\n    type Config = PoseidonConfig<WIDTH, RATE>;\n    type InputAssignments = InputAssignments;\n    type RunInputs = Vec<Fp>;\n    type Params = ();\n\n    fn name(&self) -> &'static str {\n        \"Poseidon\"\n    }\n\n    fn instance_increment_input(&self) -> Vec<usize> {\n        vec![1]\n    }\n\n    /// Constructs a new PoseidonChip\n    fn new(config: Self::Config) -> Self {\n        Self {\n            config,\n            _marker: PhantomData,\n        }\n    }\n\n    /// Configuration of the PoseidonChip\n    fn configure(meta: &mut ConstraintSystem<Fp>, _: Self::Params) -> Self::Config {\n        //  instantiate the required columns\n        let hash_inputs = (0..WIDTH).map(|_| meta.advice_column()).collect::<Vec<_>>();\n        for input in &hash_inputs {\n            meta.enable_equality(*input);\n        }\n\n        let partial_sbox = meta.advice_column();\n        let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n        let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n\n        for input in hash_inputs.iter().take(WIDTH) {\n            meta.enable_equality(*input);\n        }\n        meta.enable_constant(rc_b[0]);\n\n        let instance = meta.instance_column();\n        meta.enable_equality(instance);\n\n        Self::configure_with_cols(\n            meta,\n            partial_sbox,\n            rc_a.try_into().unwrap(),\n            rc_b.try_into().unwrap(),\n            hash_inputs,\n            Some(instance),\n        )\n    }\n\n    fn layout_inputs(\n        &self,\n        layouter: &mut impl Layouter<Fp>,\n        message: &[ValTensor<Fp>],\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<Self::InputAssignments, Error> {\n        assert_eq!(message.len(), 1);\n        let message = message[0].clone();\n\n        let start_time = instant::Instant::now();\n\n        let local_constants = constants.clone();\n\n        let res = layouter.assign_region(\n            || \"load message\",\n            |mut region| {\n                let assigned_message: Result<Vec<AssignedCell<Fp, Fp>>, Error> = match &message {\n                    ValTensor::Value { inner: v, .. } => v\n                        .iter()\n                        .enumerate()\n                        .map(|(i, value)| {\n                            let x = i % WIDTH;\n                            let y = i / WIDTH;\n\n                            match value {\n                                ValType::Value(v) => region.assign_advice(\n                                    || format!(\"load message_{}\", i),\n                                    self.config.hash_inputs[x],\n                                    y,\n                                    || *v,\n                                ),\n                                ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                                    Ok(v.clone())\n                                }\n                                ValType::Constant(f) => {\n                                    if local_constants.contains_key(f) {\n                                        Ok(constants.get(f).unwrap().assigned_cell().ok_or({\n                                            log::error!(\"constant not previously assigned\");\n                                            Error::Synthesis\n                                        })?)\n                                    } else {\n                                        let res = region.assign_advice_from_constant(\n                                            || format!(\"load message_{}\", i),\n                                            self.config.hash_inputs[x],\n                                            y,\n                                            *f,\n                                        )?;\n\n                                        constants\n                                            .insert(*f, ValType::AssignedConstant(res.clone(), *f));\n\n                                        Ok(res)\n                                    }\n                                }\n                                e => {\n                                    log::error!(\n                                        \"wrong input type {:?}, must be previously assigned\",\n                                        e\n                                    );\n                                    Err(Error::Synthesis)\n                                }\n                            }\n                        })\n                        .collect(),\n                    ValTensor::Instance {\n                        dims,\n                        inner: col,\n                        idx,\n                        initial_offset,\n                        ..\n                    } => {\n                        // this should never ever fail\n                        let num_elems = dims[*idx].iter().product::<usize>();\n                        (0..num_elems)\n                            .map(|i| {\n                                let x = i % WIDTH;\n                                let y = i / WIDTH;\n                                region.assign_advice_from_instance(\n                                    || \"pub input anchor\",\n                                    *col,\n                                    initial_offset + i,\n                                    self.config.hash_inputs[x],\n                                    y,\n                                )\n                            })\n                            .collect()\n                    }\n                };\n\n                let offset = message.len() / WIDTH + 1;\n\n                let zero_val = region\n                    .assign_advice_from_constant(\n                        || \"\",\n                        self.config.hash_inputs[0],\n                        offset,\n                        Fp::ZERO,\n                    )\n                    .unwrap();\n\n                Ok((assigned_message?, zero_val))\n            },\n        );\n        log::trace!(\n            \"input (N={:?}) layout took: {:?}\",\n            message.len(),\n            start_time.elapsed()\n        );\n        res\n    }\n\n    /// L is the number of inputs to the hash function\n    /// Takes the cells containing the input values of the hash function and return the cell containing the hash output\n    /// It uses the pow5_chip to compute the hash\n    fn layout(\n        &self,\n        layouter: &mut impl Layouter<Fp>,\n        input: &[ValTensor<Fp>],\n        row_offset: usize,\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<ValTensor<Fp>, Error> {\n        let (mut input_cells, zero_val) = self.layout_inputs(layouter, input, constants)?;\n        // extract the values from the input cells\n        let mut assigned_input: Tensor<ValType<Fp>> =\n            input_cells.iter().map(|e| ValType::from(e.clone())).into();\n        let len = assigned_input.len();\n\n        let start_time = instant::Instant::now();\n\n        let mut one_iter = false;\n        // do the Tree dance baby\n        while input_cells.len() > 1 || !one_iter {\n            let hashes: Result<Vec<AssignedCell<Fp, Fp>>, Error> = input_cells\n                .chunks(L)\n                .enumerate()\n                .map(|(i, block)| {\n                    let _start_time = instant::Instant::now();\n\n                    let mut block = block.to_vec();\n                    let remainder = block.len() % L;\n\n                    if remainder != 0 {\n                        block.extend(vec![zero_val.clone(); L - remainder]);\n                    }\n\n                    let pow5_chip = Pow5Chip::construct(self.config.pow5_config.clone());\n                    // initialize the hasher\n                    let hasher = Hash::<_, _, S, ConstantLength<L>, WIDTH, RATE>::init(\n                        pow5_chip,\n                        layouter.namespace(|| \"block_hasher\"),\n                    )?;\n\n                    let hash = hasher.hash(\n                        layouter.namespace(|| \"hash\"),\n                        block.to_vec().try_into().map_err(|_| Error::Synthesis)?,\n                    );\n\n                    if i == 0 {\n                        log::trace!(\"block (L={:?}) took: {:?}\", L, _start_time.elapsed());\n                    }\n\n                    hash\n                })\n                .collect();\n\n            log::trace!(\"hashes (N={:?}) took: {:?}\", len, start_time.elapsed());\n            one_iter = true;\n            input_cells = hashes?;\n        }\n\n        let duration = start_time.elapsed();\n        log::trace!(\"layout (N={:?}) took: {:?}\", len, duration);\n\n        let result = Tensor::from(input_cells.iter().map(|e| ValType::from(e.clone())));\n\n        let output = match result[0].clone() {\n            ValType::PrevAssigned(v) => v,\n            _ => {\n                log::error!(\"wrong input type, must be previously assigned\");\n                return Err(Error::Synthesis);\n            }\n        };\n\n        if let Some(instance) = self.config.instance {\n            layouter.assign_region(\n                || \"constrain output\",\n                |mut region| {\n                    let expected_var = region.assign_advice_from_instance(\n                        || \"pub input anchor\",\n                        instance,\n                        row_offset,\n                        self.config.hash_inputs[0],\n                        0,\n                    )?;\n\n                    region.constrain_equal(output.cell(), expected_var.cell())\n                },\n            )?;\n\n            assigned_input.reshape(input[0].dims()).map_err(|e| {\n                log::error!(\"reshape failed: {:?}\", e);\n                Error::Synthesis\n            })?;\n\n            Ok(assigned_input.into())\n        } else {\n            Ok(result.into())\n        }\n    }\n\n    ///\n    fn run(message: Vec<Fp>) -> Result<Vec<Vec<Fp>>, Box<dyn std::error::Error>> {\n        let mut hash_inputs = message;\n\n        let len = hash_inputs.len();\n\n        let start_time = instant::Instant::now();\n\n        let mut one_iter = false;\n        // do the Tree dance baby\n        while hash_inputs.len() > 1 || !one_iter {\n            let hashes: Vec<Fp> = hash_inputs\n                .par_chunks(L)\n                .map(|block| {\n                    let mut block = block.to_vec();\n                    let remainder = block.len() % L;\n\n                    if remainder != 0 {\n                        block.extend(vec![Fp::ZERO; L - remainder].iter());\n                    }\n\n                    let message = block.try_into().map_err(|_| Error::Synthesis)?;\n\n                    Ok(halo2_gadgets::poseidon::primitives::Hash::<\n                        _,\n                        S,\n                        ConstantLength<L>,\n                        { WIDTH },\n                        { RATE },\n                    >::init()\n                    .hash(message))\n                })\n                .collect::<Result<Vec<_>, Error>>()?;\n            one_iter = true;\n            hash_inputs = hashes;\n        }\n\n        let duration = start_time.elapsed();\n        log::trace!(\"run (N={:?}) took: {:?}\", len, duration);\n\n        Ok(vec![hash_inputs])\n    }\n\n    fn num_rows(mut input_len: usize) -> usize {\n        // this was determined by running the circuit and looking at the number of constraints\n        // in the test called hash_for_a_range_of_input_sizes, then regressing in python to find the slope\n        let fixed_cost: usize = 41 * L;\n\n        let mut num_rows = 0;\n\n        loop {\n            // the number of times the input_len is divisible by L\n            let num_chunks = input_len / L + 1;\n            num_rows += num_chunks * fixed_cost;\n            if num_chunks == 1 {\n                break;\n            }\n            input_len = num_chunks;\n        }\n\n        num_rows\n    }\n}\n\n#[allow(unused)]\nmod tests {\n\n    use crate::circuit::modules::ModulePlanner;\n\n    use super::{\n        spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH},\n        *,\n    };\n\n    use std::{collections::HashMap, marker::PhantomData};\n\n    use halo2_gadgets::poseidon::primitives::Spec;\n    use halo2_proofs::{\n        circuit::{Layouter, SimpleFloorPlanner, Value},\n        plonk::{Circuit, ConstraintSystem},\n    };\n    use halo2curves::ff::Field;\n\n    const WIDTH: usize = POSEIDON_WIDTH;\n    const RATE: usize = POSEIDON_RATE;\n    const R: usize = 240;\n\n    struct HashCircuit<S: Spec<Fp, WIDTH, RATE>, const L: usize> {\n        message: ValTensor<Fp>,\n        _spec: PhantomData<S>,\n    }\n\n    impl<S: Spec<Fp, WIDTH, RATE>, const L: usize> Circuit<Fp> for HashCircuit<S, L> {\n        type Config = PoseidonConfig<WIDTH, RATE>;\n        type FloorPlanner = ModulePlanner;\n        type Params = ();\n\n        fn without_witnesses(&self) -> Self {\n            let empty_val: Vec<ValType<Fp>> = vec![Value::<Fp>::unknown().into()];\n            let message: Tensor<ValType<Fp>> = empty_val.into_iter().into();\n\n            Self {\n                message: message.into(),\n                _spec: PhantomData,\n            }\n        }\n\n        fn configure(meta: &mut ConstraintSystem<Fp>) -> PoseidonConfig<WIDTH, RATE> {\n            PoseidonChip::<PoseidonSpec, WIDTH, RATE, L>::configure(meta, ())\n        }\n\n        fn synthesize(\n            &self,\n            config: PoseidonConfig<WIDTH, RATE>,\n            mut layouter: impl Layouter<Fp>,\n        ) -> Result<(), Error> {\n            let chip: PoseidonChip<PoseidonSpec, WIDTH, RATE, L> = PoseidonChip::new(config);\n            chip.layout(\n                &mut layouter,\n                &[self.message.clone()],\n                0,\n                &mut HashMap::new(),\n            )?;\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn poseidon_hash() {\n        let rng = rand::rngs::OsRng;\n\n        let message = [Fp::random(rng), Fp::random(rng)];\n        let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 2>::run(message.to_vec()).unwrap();\n\n        let mut message: Tensor<ValType<Fp>> =\n            message.into_iter().map(|m| Value::known(m).into()).into();\n\n        let k = 9;\n        let circuit = HashCircuit::<PoseidonSpec, 2> {\n            message: message.into(),\n            _spec: PhantomData,\n        };\n        let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap();\n        assert_eq!(prover.verify(), Ok(()))\n    }\n\n    #[test]\n    fn poseidon_hash_longer_input() {\n        let rng = rand::rngs::OsRng;\n\n        let message = [Fp::random(rng), Fp::random(rng), Fp::random(rng)];\n        let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 3>::run(message.to_vec()).unwrap();\n\n        let mut message: Tensor<ValType<Fp>> =\n            message.into_iter().map(|m| Value::known(m).into()).into();\n\n        let k = 9;\n        let circuit = HashCircuit::<PoseidonSpec, 3> {\n            message: message.into(),\n            _spec: PhantomData,\n        };\n        let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap();\n        assert_eq!(prover.verify(), Ok(()))\n    }\n\n    #[test]\n    #[ignore]\n    fn hash_for_a_range_of_input_sizes() {\n        let rng = rand::rngs::OsRng;\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        env_logger::init();\n\n        {\n            let i = 32;\n            // print a bunch of new lines\n            println!(\n                \"i is {} -------------------------------------------------\",\n                i\n            );\n\n            let message: Vec<Fp> = (0..i).map(|_| Fp::random(rng)).collect::<Vec<_>>();\n            let output =\n                PoseidonChip::<PoseidonSpec, WIDTH, RATE, 32>::run(message.clone()).unwrap();\n\n            let mut message: Tensor<ValType<Fp>> =\n                message.into_iter().map(|m| Value::known(m).into()).into();\n\n            let k = 17;\n            let circuit = HashCircuit::<PoseidonSpec, 32> {\n                message: message.into(),\n                _spec: PhantomData,\n            };\n            let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap();\n\n            assert_eq!(prover.verify(), Ok(()))\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn poseidon_hash_much_longer_input() {\n        let rng = rand::rngs::OsRng;\n\n        let mut message: Vec<Fp> = (0..2048).map(|_| Fp::random(rng)).collect::<Vec<_>>();\n\n        let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 25>::run(message.clone()).unwrap();\n\n        let mut message: Tensor<ValType<Fp>> =\n            message.into_iter().map(|m| Value::known(m).into()).into();\n\n        let k = 17;\n        let circuit = HashCircuit::<PoseidonSpec, 25> {\n            message: message.into(),\n            _spec: PhantomData,\n        };\n        let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap();\n        assert_eq!(prover.verify(), Ok(()))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/poseidon/poseidon_params.rs",
        "content": "//! This file was generated by running generate_params.py\n//! Number of round constants: 340\n//! Round constants for GF(p):\n//! Parameters for using rate 4 Poseidon with the BN256 field.\n//! The parameters can be reproduced by running the following Sage script from\n//! [this repository](https://github.com/daira/pasta-hadeshash):\n//!\n//! ```text\n//! $ sage generate_parameters_grain.sage 1 0 254 5 8 60 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 --rust\n//! ```\n//!\n//! where 1 means \"prime field\", 0 means \"non-negative sbox\", 254 is the bitsize\n//! of the field, 5 is the Poseidon width (rate + 1), 8 is the number of full\n//! rounds, 60 is the number of partial rounds.\n//! More info here => <https://hackmd.io/@letargicus/SJOvx48Nn>\nuse halo2_proofs::halo2curves::bn256::Fr as Fp;\npub(crate) const ROUND_CONSTANTS: [[Fp; 2]; 64] = [\n    [\n        Fp::from_raw([\n            0x6c7d_c0db_d0ab_d7a7,\n            0xa71a_a177_534c_dd1b,\n            0xfe1f_aaba_294c_ba38,\n            0x09c4_6e9e_c68e_9bd4,\n        ]),\n        Fp::from_raw([\n            0x3c1d_83ff_a604_cb81,\n            0xc514_2b3a_e405_b834,\n            0x2a97_ed93_7f31_35cf,\n            0x0c03_5653_0896_eec4,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x317e_a977_cc15_4a30,\n            0xa00e_a5aa_bd62_68bd,\n            0x142e_5118_2bb5_4cf4,\n            0x1e28_a1d9_3569_8ad1,\n        ]),\n        Fp::from_raw([\n            0x4cf9_e2b1_2b91_251f,\n            0x0e57_57c3_e008_db96,\n            0x0809_65db_30e2_98e4,\n            0x27af_2d83_1a9d_2748,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x79aa_f435_45b7_4e03,\n            0x4129_1462_f214_cd08,\n            0x3a6a_3cfe_16ae_175a,\n            0x1e6f_11ce_60fc_8f51,\n        ]),\n        Fp::from_raw([\n            0xf719_2062_68d1_42d3,\n            0x0446_2ed1_4c36_13d8,\n            0x8541_819c_b681_f0be,\n            0x2a67_384d_3bbd_5e43,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x3640_8f5d_5c9f_45d0,\n            0xb985_e381_f025_1889,\n            0x1609_f8e1_2fbf_ecf0,\n            0x0b66_fdf3_5609_3a61,\n        ]),\n        Fp::from_raw([\n            0xdaa6_852d_bdb0_9e21,\n            0x0b26_c83c_c5ce_beed,\n            0x830c_6109_3c2a_de37,\n            0x012e_e3ec_1e78_d470,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x2d10_8e7b_445b_b1b9,\n            0x6cd1_c431_b099_b6bb,\n            0xfd88_f67f_8175_e3fd,\n            0x0252_ba5f_6760_bfbd,\n        ]),\n        Fp::from_raw([\n            0xef5a_eaad_7ca9_32f1,\n            0x5439_1a89_35ff_71d6,\n            0x6c6b_ec3c_ef54_2963,\n            0x1794_74cc_eca5_ff67,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x7e1a_2589_bbed_2b91,\n            0x9c1f_974a_2649_69b3,\n            0x9228_ff4a_503f_d4ed,\n            0x2c24_2613_79a5_1bfa,\n        ]),\n        Fp::from_raw([\n            0x53e6_6c05_5180_1b05,\n            0xc2f6_3f50_01fc_0fc5,\n            0xac2f_288b_d069_5b43,\n            0x1cc1_d7b6_2692_e63e,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x5d9e_ff5f_d9c9_1b56,\n            0x0078_4dbf_17fb_acd0,\n            0xb2ed_55f8_5297_9e96,\n            0x2550_5930_1aad_a98b,\n        ]),\n        Fp::from_raw([\n            0xb11c_29ce_7e59_efd9,\n            0xaea2_4234_970a_8193,\n            0x79e1_f5c0_eccd_32b3,\n            0x2843_7be3_ac1c_b2e4,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x3387_62c3_7f5f_2043,\n            0x1854_8da8_fb4f_78d4,\n            0x1ca4_fa6b_5376_6eb1,\n            0x2821_6a44_2f2e_1f71,\n        ]),\n        Fp::from_raw([\n            0x131f_2377_3234_82c9,\n            0xeee1_efce_0309_4581,\n            0x1f39_f4e7_056d_d03f,\n            0x2c1f_47cd_17fa_5adf,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x646b_8566_a621_afc9,\n            0xd9da_fca2_7663_8a63,\n            0x8632_bcc9_356c_eb7d,\n            0x07ab_ad02_b7a5_ebc4,\n        ]),\n        Fp::from_raw([\n            0x37da_0c4d_15f9_6c3c,\n            0x9429_f908_80a6_9cd1,\n            0x275b_33ff_aab5_1dfe,\n            0x0230_2646_01ff_df29,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x717e_5d66_899a_a0a9,\n            0xa864_4145_57ee_289e,\n            0xa0f1_6865_6497_ca40,\n            0x1bc9_7305_4e51_d905,\n        ]),\n        Fp::from_raw([\n            0x2a6b_2228_8f0a_67fc,\n            0xd249_aff5_c2d8_421f,\n            0x206c_3157_e863_41ed,\n            0x2e1c_22f9_6443_5008,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xa704_52bc_2bba_86b8,\n            0x9e8e_a159_8e46_c9f7,\n            0x121c_1d5f_461b_bc50,\n            0x1224_f38d_f67c_5378,\n        ]),\n        Fp::from_raw([\n            0x69d2_9891_86cd_e20e,\n            0xd7bf_e8cd_9dfe_da19,\n            0x9280_b4bd_9ed0_068f,\n            0x02e4_e69d_8ba5_9e51,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x6d47_e973_5d98_018e,\n            0x4f19_ee36_4e65_3f07,\n            0x7f5d_f81f_c04f_f3ee,\n            0x1f1e_ccc3_4aab_a013,\n        ]),\n        Fp::from_raw([\n            0xeacb_8a4d_4284_f582,\n            0x1424_4480_32cd_1819,\n            0x7426_6c30_39a9_a731,\n            0x1672_ad3d_709a_3539,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x1d2e_d602_df8c_8fc7,\n            0xcda6_961f_284d_2499,\n            0x56f4_4af5_192b_4ae9,\n            0x283e_3fdc_2c6e_420c,\n        ]),\n        Fp::from_raw([\n            0x614f_bd69_ff39_4bcc,\n            0x6837_51f8_fdff_59d6,\n            0xd0db_0957_170f_a013,\n            0x1c2a_3d12_0c55_0ecf,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x96cb_6b81_7765_3fbd,\n            0x143a_9a43_773e_a6f2,\n            0xf789_7a73_2345_6efe,\n            0x216f_8487_7aac_6172,\n        ]),\n        Fp::from_raw([\n            0x11a1_f515_52f9_4788,\n            0xceaa_47ea_61ca_59a4,\n            0x64ba_7e8e_3e28_d12b,\n            0x2c0d_272b_ecf2_a757,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xcb4a_6c3d_8954_6f43,\n            0x170a_5480_abe0_508f,\n            0x484e_e7a7_4c45_4e9f,\n            0x16e3_4299_865c_0e28,\n        ]),\n        Fp::from_raw([\n            0x48cd_9397_5548_8fc5,\n            0x7720_4776_5802_290f,\n            0x375a_232a_6fb9_cc71,\n            0x175c_eba5_99e9_6f5b,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xd8c5_ffbb_44a1_ee32,\n            0x6aa4_10bf_bc35_4f54,\n            0xfead_9e17_58b0_2806,\n            0x0c75_9444_0dc4_8c16,\n        ]),\n        Fp::from_raw([\n            0x9247_9882_d919_fd8d,\n            0x760e_2001_3ccf_912c,\n            0xc466_db7d_7eb6_fd8f,\n            0x1a3c_29bc_39f2_1bb5,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x95c8_eeab_cd22_e68f,\n            0x0855_d349_074f_5a66,\n            0xc098_6ea0_49b2_5340,\n            0x0ccf_dd90_6f34_26e5,\n        ]),\n        Fp::from_raw([\n            0xe0e6_99b6_7dd9_e796,\n            0x66a7_a8a3_fd06_5b3c,\n            0x2bdb_475c_e6c9_4118,\n            0x14f6_bc81_d9f1_86f6,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x88ed_eb73_86b9_7052,\n            0xcc09_9810_c9c4_95c8,\n            0x9702_ca70_b2f6_c5aa,\n            0x0962_b827_89fb_3d12,\n        ]),\n        Fp::from_raw([\n            0xafef_0c8f_6a31_a86d,\n            0x1328_4ab0_1ef0_2575,\n            0xbf20_c79d_e251_27bc,\n            0x1a88_0af7_074d_18b3,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x4c30_12bb_7ae9_311b,\n            0x20af_2924_fc20_ff3f,\n            0xcd5e_77f0_211c_154b,\n            0x10cb_a184_19a6_a332,\n        ]),\n        Fp::from_raw([\n            0x756a_2849_f302_f10d,\n            0xfa27_b731_9cae_3406,\n            0xbdc7_6ba6_3a9e_aca8,\n            0x057e_62a9_a8f8_9b3e,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xafa0_413b_4428_0cee,\n            0xb961_303b_bf65_cff5,\n            0xd44a_df53_84b4_988c,\n            0x287c_971d_e91d_c0ab,\n        ]),\n        Fp::from_raw([\n            0x6f7f_7960_e306_891d,\n            0x1e56_2bc4_6d4a_ba4e,\n            0xb3bc_a9da_0cca_908f,\n            0x21df_3388_af16_87bb,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x3eff_8b56_0e16_82b3,\n            0x789d_f8f7_0b49_8fd8,\n            0x3e25_cc97_4d09_34cd,\n            0x1be5_c887_d25b_ce70,\n        ]),\n        Fp::from_raw([\n            0x48d5_9c27_06a0_d5c1,\n            0xd2cb_5d42_fda5_acea,\n            0x6811_7175_cea2_cd0d,\n            0x268d_a36f_76e5_68fb,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xbd06_460c_c26a_5ed6,\n            0xc5d8_bb74_135e_bd05,\n            0xc609_beaf_5510_ecec,\n            0x0e17_ab09_1f6e_ae50,\n        ]),\n        Fp::from_raw([\n            0x040f_5caa_1f62_af40,\n            0x91ef_62d8_cf83_d270,\n            0x7aee_535a_b074_a430,\n            0x04d7_27e7_28ff_a0a6,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x2b15_417d_7e39_ca6e,\n            0x3370_2ac1_0f1b_fd86,\n            0x81b5_4976_2bc0_22ed,\n            0x0ddb_d7bf_9c29_3415,\n        ]),\n        Fp::from_raw([\n            0x8a29_c49c_8789_654b,\n            0x34f5_b0d1_d3af_9b58,\n            0x7681_62e8_2989_c6c2,\n            0x2790_eb33_5162_1752,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x84b7_6420_6142_f9e9,\n            0x395f_3d9a_b8b2_fd09,\n            0x4471_9501_93d8_a570,\n            0x1e45_7c60_1a63_b73e,\n        ]),\n        Fp::from_raw([\n            0xc4c6_86fc_46e0_91b0,\n            0xfa90_ecd0_c43f_f91f,\n            0x638d_6ab2_bbe7_135f,\n            0x21ae_6430_1dca_9625,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x5858_534e_ed8d_350b,\n            0x854b_e9e3_432e_0955,\n            0x4da2_9316_6f49_4928,\n            0x0379_f63c_8ce3_468d,\n        ]),\n        Fp::from_raw([\n            0x8c9f_58a3_24c3_5049,\n            0xca0e_4921_a466_86ac,\n            0x6a74_4a08_0809_e054,\n            0x002d_5642_0359_d026,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x0fc2_c5af_9635_15a6,\n            0xda8d_6245_9e21_f409,\n            0x1d68_b3cd_32e1_0bbe,\n            0x1231_58e5_965b_5d9b,\n        ]),\n        Fp::from_raw([\n            0x60c8_0eb4_9cad_9ec1,\n            0x0fbb_2b6f_5283_6d4e,\n            0x661d_14bb_f6cb_e042,\n            0x0be2_9fc4_0847_a941,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x2338_02f2_4fdf_4c1a,\n            0x36db_9d85_9cad_5f9a,\n            0x5771_6142_015a_453c,\n            0x1ac9_6991_dec2_bb05,\n        ]),\n        Fp::from_raw([\n            0x51ca_3355_bcb0_627e,\n            0x5e12_c9fa_97f1_8a92,\n            0x5f49_64fc_61d2_3b3e,\n            0x1596_443f_763d_bcc2,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xd6d0_49ea_e3ba_3212,\n            0xf185_7d9f_17e7_15ae,\n            0x6b28_61d4_ec3a_eae0,\n            0x12e0_bcd3_654b_dfa7,\n        ]),\n        Fp::from_raw([\n            0x04e6_c76c_7cf9_64ba,\n            0xceab_ac7f_3715_4b19,\n            0x9ea7_3d4a_f9af_2a50,\n            0x0fc9_2b4f_1bbe_a82b,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x9c7e_9652_3387_2762,\n            0xb14f_7c77_2223_6f4f,\n            0xd6f2_e592_a801_3f40,\n            0x1f9c_0b16_1044_6442,\n        ]),\n        Fp::from_raw([\n            0x8d15_9f64_3dbb_f4d3,\n            0x050d_914d_a38b_4c05,\n            0xf8cd_e061_57a7_82f4,\n            0x0ebd_7424_4ae7_2675,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x7a83_9839_dccf_c6d1,\n            0x3b06_71e9_7346_ee39,\n            0x69a9_fafd_4ab9_51c0,\n            0x2cb7_f0ed_39e1_6e9f,\n        ]),\n        Fp::from_raw([\n            0x90c7_2bca_7352_d9bf,\n            0xce76_1d05_14ce_5266,\n            0x5605_443e_e41b_ab20,\n            0x1a9d_6e2e_cff0_22cc,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x87da_182d_648e_c72f,\n            0xd0c1_3326_a9a7_ba30,\n            0x5ea8_3c3b_c44a_9331,\n            0x2a11_5439_607f_335a,\n        ]),\n        Fp::from_raw([\n            0x9535_c115_c5a4_c060,\n            0xe738_b563_05cd_44f2,\n            0x15b8_fa7a_ee3e_3410,\n            0x23f9_b652_9b5d_040d,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x260e_b939_f0e6_e8a7,\n            0xa3ce_97c1_6d58_b68b,\n            0x249a_c6ba_484b_b9c3,\n            0x0587_2c16_db0f_72a2,\n        ]),\n        Fp::from_raw([\n            0x2b62_4a7c_dedd_f6a7,\n            0x0219_b615_1d55_b5c5,\n            0xca20_fb80_1180_75f4,\n            0x1300_bdee_08bb_7824,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x072e_4e7b_7d52_b376,\n            0x8d7a_d299_16d9_8cb1,\n            0xe638_1786_3a8f_6c28,\n            0x19b9_b63d_2f10_8e17,\n        ]),\n        Fp::from_raw([\n            0x24a2_0128_481b_4f7f,\n            0x13d1_c887_26b5_ec42,\n            0xb5bd_a237_6685_22f6,\n            0x015b_ee13_57e3_c015,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xea92_c785_b128_ffd1,\n            0xfe1e_1ce4_bab2_18cb,\n            0x1b97_07a4_f161_5e4e,\n            0x2953_736e_94bb_6b9f,\n        ]),\n        Fp::from_raw([\n            0x4ce7_266e_d660_8dfc,\n            0x851b_98d3_72b4_5f54,\n            0x862f_8061_80c0_385f,\n            0x0b06_9353_ba09_1618,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x4f58_8ac9_7d81_f429,\n            0x55ae_b7eb_9306_b64e,\n            0x15e4_e0bc_fb93_817e,\n            0x304f_74d4_61cc_c131,\n        ]),\n        Fp::from_raw([\n            0xb8ee_5415_cde9_13fc,\n            0xaad2_a164_a461_7a4c,\n            0xe8a3_3f5e_77df_e4f5,\n            0x15bb_f146_ce9b_ca09,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xa9ff_2385_9572_c8c6,\n            0x9b8f_4b85_0405_c10c,\n            0x4490_1031_4879_64ed,\n            0x0ab4_dfe0_c274_2cde,\n        ]),\n        Fp::from_raw([\n            0x251d_e39f_9639_779a,\n            0xef5e_edfe_a546_dea9,\n            0x97f4_5f76_49a1_9675,\n            0x0e32_db32_0a04_4e31,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xa307_8efa_516d_a016,\n            0x6797_733a_8277_4896,\n            0xb276_35a7_8b68_88e6,\n            0x0a17_56aa_1f37_8ca4,\n        ]),\n        Fp::from_raw([\n            0x4254_d6a2_a25d_93ef,\n            0x95e6_1d32_8f85_efa9,\n            0x47fd_1717_7f95_2ef8,\n            0x044c_4a33_b10f_6934,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xd37b_07b5_466c_4b8b,\n            0xfe08_79d7_9a49_6891,\n            0xbe65_5b53_7f66_f700,\n            0x2ed3_611b_725b_8a70,\n        ]),\n        Fp::from_raw([\n            0xd833_9ea7_1208_58aa,\n            0xadfd_eb9c_fdd3_47b5,\n            0xc8ec_c3d7_22aa_2e0e,\n            0x1f9b_a4e8_bab7_ce42,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xb740_56f8_65c5_d3da,\n            0xa38e_82ac_4502_066d,\n            0x8f7e_e907_a84e_518a,\n            0x1b23_3043_052e_8c28,\n        ]),\n        Fp::from_raw([\n            0xca2f_97b0_2087_5954,\n            0x9020_53bf_c0f1_4db0,\n            0x7403_1ab7_2bd5_5b4c,\n            0x2431_e1cc_164b_b8d0,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xa791_f273_9658_01fd,\n            0xa13e_3220_9758_3319,\n            0x30cd_6953_a0a7_db45,\n            0x082f_934c_91f5_aac3,\n        ]),\n        Fp::from_raw([\n            0x9ad6_bb93_0c48_997c,\n            0xc772_45e2_ae7c_be99,\n            0xa34b_e074_3155_42a3,\n            0x2b9a_0a22_3e75_38b0,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xb0b5_89cc_7021_4e7d,\n            0x8164_163e_75a8_a00e,\n            0xceb8_5483_b887_a9be,\n            0x0e1c_d91e_dd2c_fa2c,\n        ]),\n        Fp::from_raw([\n            0x88d3_2460_1ceb_e2f9,\n            0x9977_4f19_854d_00f5,\n            0xc951_f614_77e3_6989,\n            0x2e1e_ac0f_2bfd_fd63,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x23d7_4811_5b50_0b83,\n            0x7345_784d_8efd_b33c,\n            0x0c76_158e_769d_6d15,\n            0x0cbf_a95f_37fb_7406,\n        ]),\n        Fp::from_raw([\n            0x980c_232d_fa4a_4f84,\n            0x76d9_91e3_a775_13d9,\n            0xd65a_d49d_8a61_e9a6,\n            0x08f0_5b3b_e923_ed44,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x25a2_dd51_0c04_7ef6,\n            0xe728_4925_dc07_58a3,\n            0x52bf_8e21_984d_0443,\n            0x2271_9e2a_070b_cd08,\n        ]),\n        Fp::from_raw([\n            0xf41f_62b2_f268_30c0,\n            0x7bdb_f036_1199_82c0,\n            0xc060_f7fc_c3a1_ab4c,\n            0x041f_596a_9ee1_cb2b,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x19fc_dd09_86b1_0f89,\n            0x021b_e1c2_d0dc_464a,\n            0x8762_8eb0_6f6b_1d4c,\n            0x233f_d35d_e1be_520a,\n        ]),\n        Fp::from_raw([\n            0xefcb_453c_61c9_c267,\n            0xd31e_078a_a1b4_707e,\n            0x4325_e0a4_23eb_c810,\n            0x0524_b46d_1aa8_7a5e,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xcc44_8623_7c51_5211,\n            0x4227_bb95_4b0f_3199,\n            0xce47_fcac_894b_8582,\n            0x2c34_f424_c81e_5716,\n        ]),\n        Fp::from_raw([\n            0xf330_1032_7de4_915e,\n            0x2dd2_025b_5457_cc97,\n            0x207e_ffc2_b554_1fb7,\n            0x0b5f_2a4b_6338_7819,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xaefa_c41f_e05c_659f,\n            0xc174_35d2_f57a_f6ce,\n            0xc5b7_2fe4_39d2_cfd6,\n            0x2220_7856_082c_cc54,\n        ]),\n        Fp::from_raw([\n            0x2785_4048_ce2c_8171,\n            0xcdfb_2101_94ca_f79f,\n            0x4e24_159b_7f89_50b5,\n            0x24d5_7a8b_f5da_63fe,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x7391_9bb2_3b79_396e,\n            0x374a_d709_7bb0_1a85,\n            0x3b37_1d75_bd69_3f98,\n            0x0afa_b181_fdd5_e058,\n        ]),\n        Fp::from_raw([\n            0xf162_90d6_2b11_28ee,\n            0x76c0_0571_94c1_6c0b,\n            0x998a_52ef_ac7c_bd56,\n            0x2dba_9b10_8f20_8772,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x5aff_13e6_bce4_20b3,\n            0xcbb8_3de0_bd59_2b25,\n            0x56f8_81c7_88f5_3f83,\n            0x2634_9b66_edb8_b16f,\n        ]),\n        Fp::from_raw([\n            0x2352_88a3_e6f1_37db,\n            0xd81a_56d2_8ecc_193b,\n            0x685e_95f9_2339_753a,\n            0x25af_7ce0_e5e1_0357,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x1f7c_0187_fe35_011f,\n            0x70ee_d7aa_e88b_2bff,\n            0xc094_d6a5_5edd_68b9,\n            0x25b4_ce7b_d229_4390,\n        ]),\n        Fp::from_raw([\n            0x8cb9_d54c_1e02_b631,\n            0xde9c_ef28_ebdf_30b1,\n            0x387e_53f1_908a_88e5,\n            0x22c5_43f1_0f6c_89ec,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xdf66_8e74_882f_87a9,\n            0x425e_906a_919d_7a34,\n            0x4fc7_908a_9f19_1e1e,\n            0x0236_f93e_7789_c472,\n        ]),\n        Fp::from_raw([\n            0x9cb4_97af_980c_4b52,\n            0x652b_dae1_14eb_0165,\n            0x0e7d_27e3_7d05_da99,\n            0x2935_0b40_1166_ca01,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xee12_6091_6652_363f,\n            0x65ed_b75d_844e_bb89,\n            0x6bd3_1bba_b547_f75a,\n            0x0eed_787d_6582_0d3f,\n        ]),\n        Fp::from_raw([\n            0x1906_f656_f4de_6fad,\n            0xfdcd_0e99_bd94_297d,\n            0x036a_753f_520b_3291,\n            0x07cc_1170_f13b_46f2,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x2059_4356_89e8_acea,\n            0x9087_86d7_f9f5_d10c,\n            0xf49b_cf61_3a3d_30b1,\n            0x22b9_3923_3b1d_7205,\n        ]),\n        Fp::from_raw([\n            0xadd6_50ac_e60a_e5a6,\n            0x740f_083a_5aa8_5438,\n            0x8aad_1dc8_bc33_e870,\n            0x0145_1762_a0aa_b81c,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xe704_fec0_892f_ce89,\n            0xe32e_aa61_dec7_da57,\n            0x61fa_bf10_25d4_6d1f,\n            0x2350_6bb5_d872_7d44,\n        ]),\n        Fp::from_raw([\n            0x7f8b_d689_0735_5522,\n            0x2a37_0953_1e1e_fea9,\n            0xbac0_6ae3_f71b_dd09,\n            0x2e48_4c44_e838_aea0,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x4541_8da2_6835_b54c,\n            0xaf4a_5945_45ce_dc25,\n            0x379e_78c5_0bd2_e42b,\n            0x0f4b_c7d0_7eba_fd64,\n        ]),\n        Fp::from_raw([\n            0xe620_996d_50d8_e74e,\n            0x5158_2388_725d_f460,\n            0xfa76_6378_62fa_aee8,\n            0x1f4d_3c8f_6583_e9e5,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x53eb_9bcb_48fe_7389,\n            0xfae0_2abc_7b68_1d91,\n            0x2660_d07b_e0e4_a988,\n            0x0935_14e0_c707_11f8,\n        ]),\n        Fp::from_raw([\n            0x4a58_e0a3_47e1_53d8,\n            0x43ee_83ec_e472_28f2,\n            0x4669_9a2b_5f3b_c036,\n            0x1ada_b0c8_e2b3_bad3,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x1a22_dbef_9e80_dad2,\n            0x378c_1b94_b807_2bac,\n            0xd147_09eb_b474_641a,\n            0x1672_b172_6057_d99d,\n        ]),\n        Fp::from_raw([\n            0x30d4_7b23_9b47_9c14,\n            0xc5d8_e2fa_e0ac_c4ee,\n            0x8f44_f53f_dcab_468c,\n            0x1dfd_53d4_576a_f2e3,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xbc7f_2077_5320_5c60,\n            0xe6d7_7d64_0f6f_c3de,\n            0xa70a_3626_3a37_e17f,\n            0x0c68_88a1_0b75_b0f3,\n        ]),\n        Fp::from_raw([\n            0x8509_1ecc_a9d1_e508,\n            0x611a_61e0_0ee6_848b,\n            0x92b3_4a7e_77d1_2fe8,\n            0x1add_b933_a65b_e770,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x7935_628e_299d_1791,\n            0xf638_ff54_25f0_afff,\n            0x5c10_ae18_d1de_933c,\n            0x00d7_540d_cd26_8a84,\n        ]),\n        Fp::from_raw([\n            0xd316_939d_20b8_2c0e,\n            0x26fe_dde4_acd9_9db1,\n            0x01b2_827a_5664_ca9c,\n            0x140c_0e42_687e_9ead,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xc091_e2ae_5656_5984,\n            0xc20a_0f9b_24f8_c5ed,\n            0x91ba_89b8_d13d_1806,\n            0x2f0c_3a11_5d43_17d1,\n        ]),\n        Fp::from_raw([\n            0xd8c5_38a1_dc95_8c61,\n            0x08a0_cff6_70b2_2b82,\n            0x3006_ed22_0cf9_c810,\n            0x0c4e_e778_ff7c_1455,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x27c3_d748_5de7_4c69,\n            0x9424_ed26_c0ac_c662,\n            0x3693_f004_40cc_c360,\n            0x1704_f276_6d46_f82c,\n        ]),\n        Fp::from_raw([\n            0x39b6_6fe9_009c_3cfa,\n            0xf076_9c9f_8544_e402,\n            0xa7a0_2c1b_51d2_44ab,\n            0x2f2d_19cc_3ea5_d78e,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xd6c7_66a8_06fc_6629,\n            0xdd7e_e6cb_9cfe_d9c7,\n            0x5053_f112_e2a8_e8dc,\n            0x1ae0_3853_b75f_caba,\n        ]),\n        Fp::from_raw([\n            0x4e41_a86d_daf0_56d5,\n            0x3556_921b_2d6f_014e,\n            0x51d1_31d0_fa61_aa5f,\n            0x0971_aabf_7952_41df,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x5f5c_29f7_bfe2_f646,\n            0xda62_4f83_80df_1c87,\n            0x91d4_cf6b_6e0d_e73e,\n            0x1408_c316_e601_4e1a,\n        ]),\n        Fp::from_raw([\n            0x4169_1f39_822e_f5bd,\n            0x6c89_f1f7_73ef_2853,\n            0x248a_be42_b543_093b,\n            0x1667_f3fe_2edb_e850,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x424c_6957_6500_fe37,\n            0x5b81_7184_09e5_c133,\n            0xa48b_0a03_557c_df91,\n            0x13bf_7c5d_0d2c_4376,\n        ]),\n        Fp::from_raw([\n            0x19bc_0ba7_43a6_2c2c,\n            0x024b_9534_7856_b797,\n            0x3016_adf3_d353_3c24,\n            0x0762_0a6d_fb0b_6cec,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x1675_de3e_1982_b4d0,\n            0x75d2_959e_2f32_2b73,\n            0x36a8_ca08_bdbd_d8b0,\n            0x1574_c7ef_0c43_545f,\n        ]),\n        Fp::from_raw([\n            0xc06e_03a7_ff83_78f0,\n            0x5bd4_1845_71c2_54fd,\n            0xfd56_7970_a717_ceec,\n            0x269e_4b5b_7a2e_b21a,\n        ]),\n    ],\n]; // n: 254\n   // t: 5\n   // N: 1270\n   // Result Algorithm 1:\n   // [True, 0]\n   // Result Algorithm 2:\n   // [True, None]\n   // Result Algorithm 3:\n   // [True, None]\n   // Prime number: 0x0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\n   // MDS matrix:\npub(crate) const MDS: [[Fp; 2]; 2] = [\n    [\n        Fp::from_raw([\n            0xbcec_a70b_d2af_7ad5,\n            0xaf07_f38a_f8c9_52a7,\n            0xec10_3453_51a2_3a3a,\n            0x066f_6f85_d6f6_8a85,\n        ]),\n        Fp::from_raw([\n            0x0546_2b9f_8125_b1e8,\n            0x20a7_c02b_bd8b_ea73,\n            0x7782_e150_9b1d_0fdb,\n            0x2b9d_4b41_10c9_ae99,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0xf573_f431_221f_8ff9,\n            0xb6c0_9d55_7013_fff1,\n            0x2bf6_7a44_93cc_262f,\n            0x0cc5_7cdb_b085_07d6,\n        ]),\n        Fp::from_raw([\n            0x21bc_d147_9432_03c8,\n            0xade8_57e8_6eb5_c3a1,\n            0xa31a_6ed6_9724_e1ad,\n            0x1274_e649_a32e_d355,\n        ]),\n    ],\n]; // Inverse MDS matrix:\npub(crate) const MDS_INV: [[Fp; 2]; 2] = [\n    [\n        Fp::from_raw([\n            0x8dbe_bd0f_a8c5_3e66,\n            0x0554_569d_9b29_d1ea,\n            0x7081_9ab1_c784_6f21,\n            0x13ab_ec39_0ada_7f43,\n        ]),\n        Fp::from_raw([\n            0xaaf6_185b_1a1e_60fe,\n            0xbd52_1ead_5dfe_0345,\n            0x4c98_62a1_d97d_1510,\n            0x1eb9_e1dc_19a3_3a62,\n        ]),\n    ],\n    [\n        Fp::from_raw([\n            0x763f_7875_036b_cb02,\n            0x8ce5_1690_30a2_ad69,\n            0x601a_bc49_fdad_4f03,\n            0x0fc1_c939_4db8_9bb2,\n        ]),\n        Fp::from_raw([\n            0x8abc_ed6b_d147_c8be,\n            0x2b7e_ac34_3459_61bc,\n            0x9502_054e_dc03_e7b2,\n            0x16a9_e98c_493a_902b,\n        ]),\n    ],\n];\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/modules/poseidon/spec.rs",
        "content": "//! This file was generated by running generate_params.py\n//! Specification for rate 5 Poseidon using the BN256 curve.\n//! Patterned after [halo2_gadgets::poseidon::primitives::P128Pow5T3]\nuse halo2_gadgets::poseidon::primitives::*;\nuse halo2_proofs::arithmetic::Field;\nuse halo2_proofs::halo2curves::bn256::Fr as Fp;\n\nuse super::poseidon_params;\n\n/// The specification for the Poseidon hash function.\n#[derive(Debug, Clone, Copy)]\npub struct PoseidonSpec;\n\n/// Basically the number of columns allocated within the poseidon chip\npub const POSEIDON_WIDTH: usize = 2;\n/// The number of full SBox rounds\npub const POSEIDON_RATE: usize = 1;\n\npub(crate) type Mds<Fp, const T: usize> = [[Fp; T]; T];\n\nimpl Spec<Fp, POSEIDON_WIDTH, POSEIDON_RATE> for PoseidonSpec {\n    fn full_rounds() -> usize {\n        8\n    }\n\n    fn partial_rounds() -> usize {\n        56\n    }\n\n    fn sbox(val: Fp) -> Fp {\n        val.pow_vartime([5])\n    }\n\n    fn secure_mds() -> usize {\n        unimplemented!()\n    }\n\n    fn constants() -> (\n        Vec<[Fp; POSEIDON_WIDTH]>,\n        Mds<Fp, POSEIDON_WIDTH>,\n        Mds<Fp, POSEIDON_WIDTH>,\n    ) {\n        (\n            poseidon_params::ROUND_CONSTANTS[..].to_vec(),\n            poseidon_params::MDS,\n            poseidon_params::MDS_INV,\n        )\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/base.rs",
        "content": "use crate::tensor::TensorType;\nuse std::{\n    fmt,\n    ops::{Add, Mul, Neg, Sub},\n};\n\n#[allow(missing_docs)]\n/// An enum representing the operations that can be used to express more complex operations via accumulation\n#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]\npub enum BaseOp {\n    Dot,\n    DotInit,\n    CumProdInit,\n    CumProd,\n    Add,\n    Mult,\n    Sub,\n    SumInit,\n    Sum,\n    IsBoolean,\n}\n\n/// Matches a [BaseOp] to an operation over inputs\nimpl BaseOp {\n    /// forward func\n    pub fn nonaccum_f<\n        T: TensorType + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Neg<Output = T>,\n    >(\n        &self,\n        inputs: (T, T),\n    ) -> T {\n        let (a, b) = inputs;\n        match &self {\n            BaseOp::Add => a + b,\n            BaseOp::Sub => a - b,\n            BaseOp::Mult => a * b,\n            BaseOp::IsBoolean => b,\n            _ => panic!(\"nonaccum_f called on accumulating operation\"),\n        }\n    }\n\n    /// forward func\n    pub fn accum_f<\n        T: TensorType + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Neg<Output = T>,\n    >(\n        &self,\n        prev_output: T,\n        a: Vec<T>,\n        b: Vec<T>,\n    ) -> T {\n        let zero = T::zero().unwrap();\n        let one = T::one().unwrap();\n\n        match &self {\n            BaseOp::DotInit => a.into_iter().zip(b).fold(zero, |acc, (a, b)| acc + a * b),\n            BaseOp::Dot => prev_output + a.into_iter().zip(b).fold(zero, |acc, (a, b)| acc + a * b),\n            BaseOp::CumProdInit => b.into_iter().fold(one, |acc, b| acc * b),\n            BaseOp::CumProd => prev_output * b.into_iter().fold(one, |acc, b| acc * b),\n            BaseOp::SumInit => b.into_iter().fold(zero, |acc, b| acc + b),\n            BaseOp::Sum => prev_output + b.into_iter().fold(zero, |acc, b| acc + b),\n            _ => panic!(\"accum_f called on non-accumulating operation\"),\n        }\n    }\n\n    /// display func\n    pub fn as_str(&self) -> &'static str {\n        match self {\n            BaseOp::Dot => \"DOT\",\n            BaseOp::DotInit => \"DOTINIT\",\n            BaseOp::CumProdInit => \"CUMPRODINIT\",\n            BaseOp::CumProd => \"CUMPROD\",\n            BaseOp::Add => \"ADD\",\n            BaseOp::Sub => \"SUB\",\n            BaseOp::Mult => \"MULT\",\n            BaseOp::Sum => \"SUM\",\n            BaseOp::SumInit => \"SUMINIT\",\n            BaseOp::IsBoolean => \"ISBOOLEAN\",\n        }\n    }\n\n    /// Returns the range of the query offset for this operation.\n    pub fn query_offset_rng(&self) -> (i32, usize) {\n        match self {\n            BaseOp::DotInit => (0, 1),\n            BaseOp::Dot => (-1, 2),\n            BaseOp::CumProd => (-1, 2),\n            BaseOp::CumProdInit => (0, 1),\n            BaseOp::Add => (0, 1),\n            BaseOp::Sub => (0, 1),\n            BaseOp::Mult => (0, 1),\n            BaseOp::Sum => (-1, 2),\n            BaseOp::SumInit => (0, 1),\n            BaseOp::IsBoolean => (0, 1),\n        }\n    }\n\n    /// Returns the number of inputs for this operation.\n    pub fn num_inputs(&self) -> usize {\n        match self {\n            BaseOp::DotInit => 2,\n            BaseOp::Dot => 2,\n            BaseOp::CumProdInit => 1,\n            BaseOp::CumProd => 1,\n            BaseOp::Add => 2,\n            BaseOp::Sub => 2,\n            BaseOp::Mult => 2,\n            BaseOp::Sum => 1,\n            BaseOp::SumInit => 1,\n            BaseOp::IsBoolean => 0,\n        }\n    }\n\n    /// Returns the number of outputs for this operation.\n    pub fn constraint_idx(&self) -> usize {\n        match self {\n            BaseOp::DotInit => 0,\n            BaseOp::Dot => 1,\n            BaseOp::Add => 0,\n            BaseOp::Sub => 0,\n            BaseOp::Mult => 0,\n            BaseOp::Sum => 1,\n            BaseOp::SumInit => 0,\n            BaseOp::CumProd => 1,\n            BaseOp::CumProdInit => 0,\n            BaseOp::IsBoolean => 0,\n        }\n    }\n}\n\nimpl fmt::Display for BaseOp {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, \"{}\", self.as_str())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/chip.rs",
        "content": "use std::str::FromStr;\n\nuse thiserror::Error;\n\nuse halo2_proofs::{\n    circuit::Layouter,\n    plonk::{ConstraintSystem, Constraints, Expression, Selector},\n    poly::Rotation,\n};\nuse log::debug;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::{\n    conversion::{FromPyObject, PyTryFrom},\n    exceptions::PyValueError,\n    prelude::*,\n    types::PyString,\n};\nuse serde::{Deserialize, Serialize};\nuse tosubcommand::ToFlags;\n\nuse crate::{\n    circuit::{\n        ops::base::BaseOp,\n        table::{Range, RangeCheck, Table},\n        utils,\n    },\n    tensor::{Tensor, TensorType, ValTensor, VarTensor},\n};\nuse std::{collections::BTreeMap, error::Error, marker::PhantomData};\n\nuse super::{lookup::LookupOp, region::RegionCtx, Op};\nuse halo2curves::ff::{Field, PrimeField};\n\n/// circuit related errors.\n#[derive(Debug, Error)]\npub enum CircuitError {\n    /// Shape mismatch in circuit construction\n    #[error(\"dimension mismatch in circuit construction for op: {0}\")]\n    DimMismatch(String),\n    /// Error when instantiating lookup tables\n    #[error(\"failed to instantiate lookup tables\")]\n    LookupInstantiation,\n    /// A lookup table was was already assigned\n    #[error(\"attempting to initialize an already instantiated lookup table\")]\n    TableAlreadyAssigned,\n    /// This operation is unsupported\n    #[error(\"unsupported operation in graph\")]\n    UnsupportedOp,\n    ///\n    #[error(\"invalid einsum expression\")]\n    InvalidEinsum,\n}\n\n#[allow(missing_docs)]\n/// An enum representing activating the sanity checks we can perform on the accumulated arguments\n#[derive(\n    Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default, Copy,\n)]\npub enum CheckMode {\n    #[default]\n    SAFE,\n    UNSAFE,\n}\n\nimpl std::fmt::Display for CheckMode {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            CheckMode::SAFE => write!(f, \"safe\"),\n            CheckMode::UNSAFE => write!(f, \"unsafe\"),\n        }\n    }\n}\n\nimpl ToFlags for CheckMode {\n    /// Convert the struct to a subcommand string\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl From<String> for CheckMode {\n    fn from(value: String) -> Self {\n        match value.to_lowercase().as_str() {\n            \"safe\" => CheckMode::SAFE,\n            \"unsafe\" => CheckMode::UNSAFE,\n            _ => {\n                log::error!(\"Invalid value for CheckMode\");\n                log::warn!(\"defaulting to SAFE\");\n                CheckMode::SAFE\n            }\n        }\n    }\n}\n\n#[allow(missing_docs)]\n/// An enum representing the tolerance we can accept for the accumulated arguments, either absolute or percentage\n#[derive(Clone, Default, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Copy)]\npub struct Tolerance {\n    pub val: f32,\n    pub scale: utils::F32,\n}\n\nimpl std::fmt::Display for Tolerance {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(f, \"{:.2}\", self.val)\n    }\n}\n\nimpl ToFlags for Tolerance {\n    /// Convert the struct to a subcommand string\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl FromStr for Tolerance {\n    type Err = String;\n\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        if let Ok(val) = s.parse::<f32>() {\n            Ok(Tolerance {\n                val,\n                scale: utils::F32(1.0),\n            })\n        } else {\n            Err(\n                \"Invalid tolerance value provided. It should expressed as a percentage (f32).\"\n                    .to_string(),\n            )\n        }\n    }\n}\n\nimpl From<f32> for Tolerance {\n    fn from(value: f32) -> Self {\n        Tolerance {\n            val: value,\n            scale: utils::F32(1.0),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Converts CheckMode into a PyObject (Required for CheckMode to be compatible with Python)\nimpl IntoPy<PyObject> for CheckMode {\n    fn into_py(self, py: Python) -> PyObject {\n        match self {\n            CheckMode::SAFE => \"safe\".to_object(py),\n            CheckMode::UNSAFE => \"unsafe\".to_object(py),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Obtains CheckMode from PyObject (Required for CheckMode to be compatible with Python)\nimpl<'source> FromPyObject<'source> for CheckMode {\n    fn extract(ob: &'source PyAny) -> PyResult<Self> {\n        let trystr = <PyString as PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n        match strval.to_lowercase().as_str() {\n            \"safe\" => Ok(CheckMode::SAFE),\n            \"unsafe\" => Ok(CheckMode::UNSAFE),\n            _ => Err(PyValueError::new_err(\"Invalid value for CheckMode\")),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Converts Tolerance into a PyObject (Required for Tolerance to be compatible with Python)\nimpl IntoPy<PyObject> for Tolerance {\n    fn into_py(self, py: Python) -> PyObject {\n        (self.val, self.scale.0).to_object(py)\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Obtains Tolerance from PyObject (Required for Tolerance to be compatible with Python)\nimpl<'source> FromPyObject<'source> for Tolerance {\n    fn extract(ob: &'source PyAny) -> PyResult<Self> {\n        if let Ok((val, scale)) = ob.extract::<(f32, f32)>() {\n            Ok(Tolerance {\n                val,\n                scale: utils::F32(scale),\n            })\n        } else {\n            Err(PyValueError::new_err(\"Invalid tolerance value provided. \"))\n        }\n    }\n}\n\n/// A struct representing the selectors for the dynamic lookup tables\n#[derive(Clone, Debug, Default)]\npub struct DynamicLookups {\n    /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops.\n    pub lookup_selectors: BTreeMap<(usize, usize), Selector>,\n    /// Selectors for the dynamic lookup tables\n    pub table_selectors: Vec<Selector>,\n    /// Inputs:\n    pub inputs: Vec<VarTensor>,\n    /// tables\n    pub tables: Vec<VarTensor>,\n}\n\nimpl DynamicLookups {\n    /// Returns a new [DynamicLookups] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        let dummy_var = VarTensor::dummy(col_size, num_inner_cols);\n        let single_col_dummy_var = VarTensor::dummy(col_size, 1);\n\n        Self {\n            lookup_selectors: BTreeMap::new(),\n            table_selectors: vec![],\n            inputs: vec![dummy_var.clone(), dummy_var.clone(), dummy_var.clone()],\n            tables: vec![\n                single_col_dummy_var.clone(),\n                single_col_dummy_var.clone(),\n                single_col_dummy_var.clone(),\n            ],\n        }\n    }\n}\n\n/// A struct representing the selectors for the dynamic lookup tables\n#[derive(Clone, Debug, Default)]\npub struct Shuffles {\n    /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops.\n    pub input_selectors: BTreeMap<(usize, usize), Selector>,\n    /// Selectors for the dynamic lookup tables\n    pub reference_selectors: Vec<Selector>,\n    /// Inputs:\n    pub inputs: Vec<VarTensor>,\n    /// tables\n    pub references: Vec<VarTensor>,\n}\n\nimpl Shuffles {\n    /// Returns a new [DynamicLookups] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        let dummy_var = VarTensor::dummy(col_size, num_inner_cols);\n        let single_col_dummy_var = VarTensor::dummy(col_size, 1);\n\n        Self {\n            input_selectors: BTreeMap::new(),\n            reference_selectors: vec![],\n            inputs: vec![dummy_var.clone(), dummy_var.clone()],\n            references: vec![single_col_dummy_var.clone(), single_col_dummy_var.clone()],\n        }\n    }\n}\n\n/// A struct representing the selectors for the static lookup tables\n#[derive(Clone, Debug, Default)]\npub struct StaticLookups<F: PrimeField + TensorType + PartialOrd> {\n    /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops.\n    pub selectors: BTreeMap<(LookupOp, usize, usize), Selector>,\n    /// Selectors for the dynamic lookup tables\n    pub tables: BTreeMap<LookupOp, Table<F>>,\n    ///\n    pub index: VarTensor,\n    ///\n    pub output: VarTensor,\n    ///\n    pub input: VarTensor,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> StaticLookups<F> {\n    /// Returns a new [StaticLookups] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        let dummy_var = VarTensor::dummy(col_size, num_inner_cols);\n\n        Self {\n            selectors: BTreeMap::new(),\n            tables: BTreeMap::new(),\n            index: dummy_var.clone(),\n            output: dummy_var.clone(),\n            input: dummy_var,\n        }\n    }\n}\n\n/// A struct representing the selectors for custom gates\n#[derive(Clone, Debug, Default)]\npub struct CustomGates {\n    /// the inputs to the accumulated operations.\n    pub inputs: Vec<VarTensor>,\n    /// the (currently singular) output of the accumulated operations.\n    pub output: VarTensor,\n    /// selector\n    pub selectors: BTreeMap<(BaseOp, usize, usize), Selector>,\n}\n\nimpl CustomGates {\n    /// Returns a new [CustomGates] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        let dummy_var = VarTensor::dummy(col_size, num_inner_cols);\n        Self {\n            inputs: vec![dummy_var.clone(), dummy_var.clone()],\n            output: dummy_var,\n            selectors: BTreeMap::new(),\n        }\n    }\n}\n\n/// A struct representing the selectors for the range checks\n#[derive(Clone, Debug, Default)]\npub struct RangeChecks<F: PrimeField + TensorType + PartialOrd> {\n    /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops.\n    pub selectors: BTreeMap<(Range, usize, usize), Selector>,\n    /// Selectors for the dynamic lookup tables\n    pub ranges: BTreeMap<Range, RangeCheck<F>>,\n    ///\n    pub index: VarTensor,\n    ///\n    pub input: VarTensor,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> RangeChecks<F> {\n    /// Returns a new [RangeChecks] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        let dummy_var = VarTensor::dummy(col_size, num_inner_cols);\n        Self {\n            selectors: BTreeMap::new(),\n            ranges: BTreeMap::new(),\n            index: dummy_var.clone(),\n            input: dummy_var,\n        }\n    }\n}\n\n/// Configuration for an accumulated arg.\n#[derive(Clone, Debug, Default)]\npub struct BaseConfig<F: PrimeField + TensorType + PartialOrd> {\n    /// Custom gates\n    pub custom_gates: CustomGates,\n    /// StaticLookups\n    pub static_lookups: StaticLookups<F>,\n    /// [Selector]s for the dynamic lookup tables\n    pub dynamic_lookups: DynamicLookups,\n    /// [Selector]s for the range checks\n    pub range_checks: RangeChecks<F>,\n    /// [Selector]s for the shuffles\n    pub shuffles: Shuffles,\n    /// Activate sanity checks\n    pub check_mode: CheckMode,\n    _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> BaseConfig<F> {\n    /// Returns a new [BaseConfig] with no inputs, no selectors, and no tables.\n    pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self {\n        Self {\n            custom_gates: CustomGates::dummy(col_size, num_inner_cols),\n            static_lookups: StaticLookups::dummy(col_size, num_inner_cols),\n            dynamic_lookups: DynamicLookups::dummy(col_size, num_inner_cols),\n            shuffles: Shuffles::dummy(col_size, num_inner_cols),\n            range_checks: RangeChecks::dummy(col_size, num_inner_cols),\n            check_mode: CheckMode::SAFE,\n            _marker: PhantomData,\n        }\n    }\n\n    /// Configures [BaseOp]s for a given [ConstraintSystem].\n    /// # Arguments\n    /// * `meta` - The [ConstraintSystem] to configure the operations in.\n    /// * `inputs` - The explicit inputs to the operations.\n    /// * `output` - The variable representing the (currently singular) output of the operations.\n    /// * `check_mode` - The variable representing the (currently singular) output of the operations.\n    pub fn configure(\n        meta: &mut ConstraintSystem<F>,\n        inputs: &[VarTensor; 2],\n        output: &VarTensor,\n        check_mode: CheckMode,\n    ) -> Self {\n        // setup a selector per base op\n        let mut nonaccum_selectors = BTreeMap::new();\n        let mut accum_selectors = BTreeMap::new();\n\n        if inputs[0].num_cols() != inputs[1].num_cols() {\n            log::warn!(\"input shapes do not match\");\n        }\n        if inputs[0].num_cols() != output.num_cols() {\n            log::warn!(\"input and output shapes do not match\");\n        }\n\n        for i in 0..output.num_blocks() {\n            for j in 0..output.num_inner_cols() {\n                nonaccum_selectors.insert((BaseOp::Add, i, j), meta.selector());\n                nonaccum_selectors.insert((BaseOp::Sub, i, j), meta.selector());\n                nonaccum_selectors.insert((BaseOp::Mult, i, j), meta.selector());\n                nonaccum_selectors.insert((BaseOp::IsBoolean, i, j), meta.selector());\n            }\n        }\n\n        for i in 0..output.num_blocks() {\n            accum_selectors.insert((BaseOp::DotInit, i, 0), meta.selector());\n            accum_selectors.insert((BaseOp::Dot, i, 0), meta.selector());\n            accum_selectors.insert((BaseOp::CumProd, i, 0), meta.selector());\n            accum_selectors.insert((BaseOp::CumProdInit, i, 0), meta.selector());\n            accum_selectors.insert((BaseOp::Sum, i, 0), meta.selector());\n            accum_selectors.insert((BaseOp::SumInit, i, 0), meta.selector());\n        }\n\n        for ((base_op, block_idx, inner_col_idx), selector) in nonaccum_selectors.iter() {\n            meta.create_gate(base_op.as_str(), |meta| {\n                let selector = meta.query_selector(*selector);\n\n                let zero = Expression::<F>::Constant(F::ZERO);\n                let mut qis = vec![zero; 2];\n                for (i, q_i) in qis\n                    .iter_mut()\n                    .enumerate()\n                    .take(2)\n                    .skip(2 - base_op.num_inputs())\n                {\n                    *q_i = inputs[i]\n                        .query_rng(meta, *block_idx, *inner_col_idx, 0, 1)\n                        .expect(\"non accum: input query failed\")[0]\n                        .clone()\n                }\n\n                // Get output expressions for each input channel\n                let (rotation_offset, rng) = base_op.query_offset_rng();\n\n                let constraints = match base_op {\n                    BaseOp::IsBoolean => {\n                        let expected_output: Tensor<Expression<F>> = output\n                            .query_rng(meta, *block_idx, *inner_col_idx, 0, 1)\n                            .expect(\"non accum: output query failed\");\n\n                        let output = expected_output[base_op.constraint_idx()].clone();\n\n                        vec![(output.clone()) * (output.clone() - Expression::Constant(F::from(1)))]\n                    }\n                    _ => {\n                        let expected_output: Tensor<Expression<F>> = output\n                            .query_rng(meta, *block_idx, *inner_col_idx, rotation_offset, rng)\n                            .expect(\"non accum: output query failed\");\n\n                        let res = base_op.nonaccum_f((qis[0].clone(), qis[1].clone()));\n                        vec![expected_output[base_op.constraint_idx()].clone() - res]\n                    }\n                };\n\n                Constraints::with_selector(selector, constraints)\n            });\n        }\n\n        for ((base_op, block_idx, _), selector) in accum_selectors.iter() {\n            meta.create_gate(base_op.as_str(), |meta| {\n                let selector = meta.query_selector(*selector);\n                let mut qis = vec![vec![]; 2];\n                for (i, q_i) in qis\n                    .iter_mut()\n                    .enumerate()\n                    .take(2)\n                    .skip(2 - base_op.num_inputs())\n                {\n                    *q_i = inputs[i]\n                        .query_whole_block(meta, *block_idx, 0, 1)\n                        .expect(\"accum: input query failed\")\n                        .into_iter()\n                        .collect()\n                }\n\n                // Get output expressions for each input channel\n                let (rotation_offset, rng) = base_op.query_offset_rng();\n\n                let expected_output: Tensor<Expression<F>> = output\n                    .query_rng(meta, *block_idx, 0, rotation_offset, rng)\n                    .expect(\"accum: output query failed\");\n\n                let res =\n                    base_op.accum_f(expected_output[0].clone(), qis[0].clone(), qis[1].clone());\n                let constraints = vec![expected_output[base_op.constraint_idx()].clone() - res];\n\n                Constraints::with_selector(selector, constraints)\n            });\n        }\n\n        // selectors is the merger of nonaccum and accum selectors\n        let selectors = nonaccum_selectors\n            .into_iter()\n            .chain(accum_selectors)\n            .collect();\n\n        Self {\n            custom_gates: CustomGates {\n                inputs: inputs.to_vec(),\n                output: output.clone(),\n                selectors,\n            },\n            static_lookups: StaticLookups::default(),\n            dynamic_lookups: DynamicLookups::default(),\n            shuffles: Shuffles::default(),\n            range_checks: RangeChecks::default(),\n            check_mode,\n            _marker: PhantomData,\n        }\n    }\n\n    /// Configures and creates lookup selectors\n    #[allow(clippy::too_many_arguments)]\n    pub fn configure_lookup(\n        &mut self,\n        cs: &mut ConstraintSystem<F>,\n        input: &VarTensor,\n        output: &VarTensor,\n        index: &VarTensor,\n        lookup_range: Range,\n        logrows: usize,\n        nl: &LookupOp,\n    ) -> Result<(), Box<dyn Error>>\n    where\n        F: Field,\n    {\n        if !index.is_advice() {\n            return Err(\"wrong input type for lookup index\".into());\n        }\n        if !input.is_advice() {\n            return Err(\"wrong input type for lookup input\".into());\n        }\n        if !output.is_advice() {\n            return Err(\"wrong input type for lookup output\".into());\n        }\n\n        // we borrow mutably twice so we need to do this dance\n\n        let table = if !self.static_lookups.tables.contains_key(nl) {\n            // as all tables have the same input we see if there's another table who's input we can reuse\n            let table = if let Some(table) = self.static_lookups.tables.values().next() {\n                Table::<F>::configure(\n                    cs,\n                    lookup_range,\n                    logrows,\n                    nl,\n                    Some(table.table_inputs.clone()),\n                )\n            } else {\n                Table::<F>::configure(cs, lookup_range, logrows, nl, None)\n            };\n            self.static_lookups.tables.insert(nl.clone(), table.clone());\n            table\n        } else {\n            return Ok(());\n        };\n\n        for x in 0..input.num_blocks() {\n            for y in 0..input.num_inner_cols() {\n                let len = table.selector_constructor.degree;\n\n                let multi_col_selector = cs.complex_selector();\n\n                for ((col_idx, input_col), output_col) in table\n                    .table_inputs\n                    .iter()\n                    .enumerate()\n                    .zip(table.table_outputs.iter())\n                {\n                    cs.lookup(\"\", |cs| {\n                        let mut res = vec![];\n                        let sel = cs.query_selector(multi_col_selector);\n\n                        let synthetic_sel = match len {\n                            1 => Expression::Constant(F::from(1)),\n                            _ => match index {\n                                VarTensor::Advice { inner: advices, .. } => {\n                                    cs.query_advice(advices[x][y], Rotation(0))\n                                }\n                                _ => unreachable!(),\n                            },\n                        };\n\n                        let input_query = match &input {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[x][y], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        };\n\n                        let output_query = match &output {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[x][y], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        };\n\n                        // we index from 1 to avoid the zero element creating soundness issues\n                        // this is 0 if the index is the same as the column index (starting from 1)\n\n                        let col_expr = sel.clone()\n                            * table\n                                .selector_constructor\n                                .get_expr_at_idx(col_idx, synthetic_sel);\n\n                        let multiplier =\n                            table.selector_constructor.get_selector_val_at_idx(col_idx);\n\n                        let not_expr = Expression::Constant(multiplier) - col_expr.clone();\n\n                        let (default_x, default_y) = table.get_first_element(col_idx);\n\n                        log::trace!(\"---------------- col {:?} ------------------\", col_idx,);\n                        log::trace!(\"expr: {:?}\", col_expr,);\n                        log::trace!(\"multiplier: {:?}\", multiplier);\n                        log::trace!(\"not_expr: {:?}\", not_expr);\n                        log::trace!(\"default x: {:?}\", default_x);\n                        log::trace!(\"default y: {:?}\", default_y);\n\n                        res.extend([\n                            (\n                                col_expr.clone() * input_query.clone()\n                                    + not_expr.clone() * Expression::Constant(default_x),\n                                *input_col,\n                            ),\n                            (\n                                col_expr.clone() * output_query.clone()\n                                    + not_expr.clone() * Expression::Constant(default_y),\n                                *output_col,\n                            ),\n                        ]);\n\n                        res\n                    });\n                }\n                self.static_lookups\n                    .selectors\n                    .insert((nl.clone(), x, y), multi_col_selector);\n            }\n        }\n        // if we haven't previously initialized the input/output, do so now\n        if let VarTensor::Empty = self.static_lookups.input {\n            debug!(\"assigning lookup input\");\n            self.static_lookups.input = input.clone();\n        }\n        if let VarTensor::Empty = self.static_lookups.output {\n            debug!(\"assigning lookup output\");\n            self.static_lookups.output = output.clone();\n        }\n        if let VarTensor::Empty = self.static_lookups.index {\n            debug!(\"assigning lookup index\");\n            self.static_lookups.index = index.clone();\n        }\n        Ok(())\n    }\n\n    /// Configures and creates lookup selectors\n    #[allow(clippy::too_many_arguments)]\n    pub fn configure_dynamic_lookup(\n        &mut self,\n        cs: &mut ConstraintSystem<F>,\n        lookups: &[VarTensor; 3],\n        tables: &[VarTensor; 3],\n    ) -> Result<(), Box<dyn Error>>\n    where\n        F: Field,\n    {\n        for l in lookups.iter() {\n            if !l.is_advice() {\n                return Err(\"wrong input type for dynamic lookup\".into());\n            }\n        }\n\n        for t in tables.iter() {\n            if !t.is_advice() || t.num_blocks() > 1 || t.num_inner_cols() > 1 {\n                return Err(\"wrong table type for dynamic lookup\".into());\n            }\n        }\n\n        let one = Expression::Constant(F::ONE);\n\n        let s_ltable = cs.complex_selector();\n\n        for x in 0..lookups[0].num_blocks() {\n            for y in 0..lookups[0].num_inner_cols() {\n                let s_lookup = cs.complex_selector();\n\n                cs.lookup_any(\"lookup\", |cs| {\n                    let s_lookupq = cs.query_selector(s_lookup);\n                    let mut expression = vec![];\n                    let s_ltableq = cs.query_selector(s_ltable);\n                    let mut lookup_queries = vec![one.clone()];\n\n                    for lookup in lookups {\n                        lookup_queries.push(match lookup {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[x][y], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        });\n                    }\n\n                    let mut table_queries = vec![one.clone()];\n                    for table in tables {\n                        table_queries.push(match table {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[0][0], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        });\n                    }\n\n                    let lhs = lookup_queries.into_iter().map(|c| c * s_lookupq.clone());\n                    let rhs = table_queries.into_iter().map(|c| c * s_ltableq.clone());\n                    expression.extend(lhs.zip(rhs));\n\n                    expression\n                });\n                self.dynamic_lookups\n                    .lookup_selectors\n                    .entry((x, y))\n                    .or_insert(s_lookup);\n            }\n        }\n        self.dynamic_lookups.table_selectors.push(s_ltable);\n\n        // if we haven't previously initialized the input/output, do so now\n        if self.dynamic_lookups.tables.is_empty() {\n            debug!(\"assigning dynamic lookup table\");\n            self.dynamic_lookups.tables = tables.to_vec();\n        }\n        if self.dynamic_lookups.inputs.is_empty() {\n            debug!(\"assigning dynamic lookup input\");\n            self.dynamic_lookups.inputs = lookups.to_vec();\n        }\n\n        Ok(())\n    }\n\n    /// Configures and creates lookup selectors\n    #[allow(clippy::too_many_arguments)]\n    pub fn configure_shuffles(\n        &mut self,\n        cs: &mut ConstraintSystem<F>,\n        inputs: &[VarTensor; 2],\n        references: &[VarTensor; 2],\n    ) -> Result<(), Box<dyn Error>>\n    where\n        F: Field,\n    {\n        for l in inputs.iter() {\n            if !l.is_advice() {\n                return Err(\"wrong input type for dynamic lookup\".into());\n            }\n        }\n\n        for t in references.iter() {\n            if !t.is_advice() || t.num_blocks() > 1 || t.num_inner_cols() > 1 {\n                return Err(\"wrong table type for dynamic lookup\".into());\n            }\n        }\n\n        let one = Expression::Constant(F::ONE);\n\n        let s_reference = cs.complex_selector();\n\n        for x in 0..inputs[0].num_blocks() {\n            for y in 0..inputs[0].num_inner_cols() {\n                let s_input = cs.complex_selector();\n\n                cs.lookup_any(\"lookup\", |cs| {\n                    let s_inputq = cs.query_selector(s_input);\n                    let mut expression = vec![];\n                    let s_referenceq = cs.query_selector(s_reference);\n                    let mut input_queries = vec![one.clone()];\n\n                    for input in inputs {\n                        input_queries.push(match input {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[x][y], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        });\n                    }\n\n                    let mut ref_queries = vec![one.clone()];\n                    for reference in references {\n                        ref_queries.push(match reference {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[0][0], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        });\n                    }\n\n                    let lhs = input_queries.into_iter().map(|c| c * s_inputq.clone());\n                    let rhs = ref_queries.into_iter().map(|c| c * s_referenceq.clone());\n                    expression.extend(lhs.zip(rhs));\n\n                    expression\n                });\n                self.shuffles\n                    .input_selectors\n                    .entry((x, y))\n                    .or_insert(s_input);\n            }\n        }\n        self.shuffles.reference_selectors.push(s_reference);\n\n        // if we haven't previously initialized the input/output, do so now\n        if self.shuffles.references.is_empty() {\n            debug!(\"assigning shuffles reference\");\n            self.shuffles.references = references.to_vec();\n        }\n        if self.shuffles.inputs.is_empty() {\n            debug!(\"assigning shuffles input\");\n            self.shuffles.inputs = inputs.to_vec();\n        }\n\n        Ok(())\n    }\n\n    /// Configures and creates lookup selectors\n    #[allow(clippy::too_many_arguments)]\n    pub fn configure_range_check(\n        &mut self,\n        cs: &mut ConstraintSystem<F>,\n        input: &VarTensor,\n        index: &VarTensor,\n        range: Range,\n        logrows: usize,\n    ) -> Result<(), Box<dyn Error>>\n    where\n        F: Field,\n    {\n        if !input.is_advice() {\n            return Err(\"wrong input type for lookup input\".into());\n        }\n\n        // we borrow mutably twice so we need to do this dance\n\n        let range_check = if let std::collections::btree_map::Entry::Vacant(e) =\n            self.range_checks.ranges.entry(range)\n        {\n            // as all tables have the same input we see if there's another table who's input we can reuse\n            let range_check = RangeCheck::<F>::configure(cs, range, logrows);\n            e.insert(range_check.clone());\n            range_check\n        } else {\n            return Ok(());\n        };\n\n        for x in 0..input.num_blocks() {\n            for y in 0..input.num_inner_cols() {\n                let len = range_check.selector_constructor.degree;\n                let multi_col_selector = cs.complex_selector();\n\n                for (col_idx, input_col) in range_check.inputs.iter().enumerate() {\n                    cs.lookup(\"\", |cs| {\n                        let mut res = vec![];\n                        let sel = cs.query_selector(multi_col_selector);\n\n                        let synthetic_sel = match len {\n                            1 => Expression::Constant(F::from(1)),\n                            _ => match index {\n                                VarTensor::Advice { inner: advices, .. } => {\n                                    cs.query_advice(advices[x][y], Rotation(0))\n                                }\n                                _ => unreachable!(),\n                            },\n                        };\n\n                        let input_query = match &input {\n                            VarTensor::Advice { inner: advices, .. } => {\n                                cs.query_advice(advices[x][y], Rotation(0))\n                            }\n                            _ => unreachable!(),\n                        };\n\n                        let default_x = range_check.get_first_element(col_idx);\n\n                        let col_expr = sel.clone()\n                            * range_check\n                                .selector_constructor\n                                .get_expr_at_idx(col_idx, synthetic_sel);\n\n                        let multiplier = range_check\n                            .selector_constructor\n                            .get_selector_val_at_idx(col_idx);\n\n                        let not_expr = Expression::Constant(multiplier) - col_expr.clone();\n\n                        res.extend([(\n                            col_expr.clone() * input_query.clone()\n                                + not_expr.clone() * Expression::Constant(default_x),\n                            *input_col,\n                        )]);\n\n                        log::trace!(\"---------------- col {:?} ------------------\", col_idx,);\n                        log::trace!(\"expr: {:?}\", col_expr,);\n                        log::trace!(\"multiplier: {:?}\", multiplier);\n                        log::trace!(\"not_expr: {:?}\", not_expr);\n                        log::trace!(\"default x: {:?}\", default_x);\n\n                        res\n                    });\n                }\n                self.range_checks\n                    .selectors\n                    .insert((range, x, y), multi_col_selector);\n            }\n        }\n        // if we haven't previously initialized the input/output, do so now\n        if let VarTensor::Empty = self.range_checks.input {\n            debug!(\"assigning range check input\");\n            self.range_checks.input = input.clone();\n        }\n\n        if let VarTensor::Empty = self.range_checks.index {\n            debug!(\"assigning range check index\");\n            self.range_checks.index = index.clone();\n        }\n\n        Ok(())\n    }\n\n    /// layout_tables must be called before layout.\n    pub fn layout_tables(&mut self, layouter: &mut impl Layouter<F>) -> Result<(), Box<dyn Error>> {\n        for (i, table) in self.static_lookups.tables.values_mut().enumerate() {\n            if !table.is_assigned {\n                debug!(\n                    \"laying out table for {}\",\n                    crate::circuit::ops::Op::<F>::as_string(&table.nonlinearity)\n                );\n                if i == 0 {\n                    table.layout(layouter, false)?;\n                } else {\n                    table.layout(layouter, true)?;\n                }\n            }\n        }\n        Ok(())\n    }\n\n    /// layout_range_checks must be called before layout.\n    pub fn layout_range_checks(\n        &mut self,\n        layouter: &mut impl Layouter<F>,\n    ) -> Result<(), Box<dyn Error>> {\n        for range_check in self.range_checks.ranges.values_mut() {\n            if !range_check.is_assigned {\n                debug!(\"laying out range check for {:?}\", range_check.range);\n                range_check.layout(layouter)?;\n            }\n        }\n        Ok(())\n    }\n\n    /// Assigns variables to the regions created when calling `configure`.\n    /// # Arguments\n    /// * `values` - The explicit values to the operations.\n    /// * `layouter` - A Halo2 Layouter.\n    /// * `op` - The operation being represented.\n    pub fn layout(\n        &mut self,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n        op: Box<dyn Op<F>>,\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        op.layout(self, region, values)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/hybrid.rs",
        "content": "use super::*;\nuse crate::{\n    circuit::{layouts, utils, Tolerance},\n    fieldutils::i128_to_felt,\n    graph::multiplier_to_scale,\n    tensor::{self, Tensor, TensorType, ValTensor},\n};\nuse halo2curves::ff::PrimeField;\nuse serde::{Deserialize, Serialize};\n// import run args from model\n\n#[allow(missing_docs)]\n/// An enum representing the operations that consist of both lookups and arithmetic operations.\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub enum HybridOp {\n    Recip {\n        input_scale: utils::F32,\n        output_scale: utils::F32,\n        use_range_check_for_int: bool,\n    },\n    Div {\n        denom: utils::F32,\n        use_range_check_for_int: bool,\n    },\n    ReduceMax {\n        axes: Vec<usize>,\n    },\n    ReduceArgMax {\n        dim: usize,\n    },\n    SumPool {\n        padding: Vec<(usize, usize)>,\n        stride: Vec<usize>,\n        kernel_shape: Vec<usize>,\n        normalized: bool,\n    },\n    MaxPool {\n        padding: Vec<(usize, usize)>,\n        stride: Vec<usize>,\n        pool_dims: Vec<usize>,\n    },\n    ReduceMin {\n        axes: Vec<usize>,\n    },\n    ReduceArgMin {\n        dim: usize,\n    },\n    Softmax {\n        input_scale: utils::F32,\n        output_scale: utils::F32,\n        axes: Vec<usize>,\n    },\n    RangeCheck(Tolerance),\n    Greater,\n    GreaterEqual,\n    Less,\n    LessEqual,\n    Equals,\n    Gather {\n        dim: usize,\n        constant_idx: Option<Tensor<usize>>,\n    },\n    TopK {\n        dim: usize,\n        k: usize,\n        largest: bool,\n    },\n    OneHot {\n        dim: usize,\n        num_classes: usize,\n    },\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for HybridOp {\n    ///\n    fn requires_homogenous_input_scales(&self) -> Vec<usize> {\n        match self {\n            HybridOp::Greater | HybridOp::Less | HybridOp::Equals => vec![0, 1],\n            HybridOp::GreaterEqual | HybridOp::LessEqual => vec![0, 1],\n            _ => vec![],\n        }\n    }\n\n    /// Returns a reference to the Any trait.\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        match self {\n            HybridOp::Recip {\n                input_scale,\n                output_scale,\n                use_range_check_for_int,\n            } => format!(\n                \"RECIP (input_scale={}, output_scale={}, use_range_check_for_int={})\",\n                input_scale, output_scale, use_range_check_for_int\n            ),\n            HybridOp::Div {\n                denom,\n                use_range_check_for_int,\n            } => format!(\n                \"DIV (denom={}, use_range_check_for_int={})\",\n                denom, use_range_check_for_int\n            ),\n            HybridOp::SumPool {\n                padding,\n                stride,\n                kernel_shape,\n                normalized,\n            } => format!(\n                \"SUMPOOL (padding={:?}, stride={:?}, kernel_shape={:?}, normalized={})\",\n                padding, stride, kernel_shape, normalized\n            ),\n            HybridOp::ReduceMax { axes } => format!(\"REDUCEMAX (axes={:?})\", axes),\n            HybridOp::ReduceArgMax { dim } => format!(\"REDUCEARGMAX (dim={})\", dim),\n            HybridOp::MaxPool {\n                padding,\n                stride,\n                pool_dims,\n            } => format!(\n                \"MaxPool (padding={:?}, stride={:?}, pool_dims={:?})\",\n                padding, stride, pool_dims\n            ),\n            HybridOp::ReduceMin { axes } => format!(\"REDUCEMIN (axes={:?})\", axes),\n            HybridOp::ReduceArgMin { dim } => format!(\"REDUCEARGMIN (dim={})\", dim),\n            HybridOp::Softmax {\n                input_scale,\n                output_scale,\n                axes,\n            } => {\n                format!(\n                    \"SOFTMAX (input_scale={}, output_scale={}, axes={:?})\",\n                    input_scale, output_scale, axes\n                )\n            }\n            HybridOp::RangeCheck(p) => format!(\"RANGECHECK (tol={:?})\", p),\n            HybridOp::Greater => \"GREATER\".into(),\n            HybridOp::GreaterEqual => \"GREATEREQUAL\".into(),\n            HybridOp::Less => \"LESS\".into(),\n            HybridOp::LessEqual => \"LESSEQUAL\".into(),\n            HybridOp::Equals => \"EQUALS\".into(),\n            HybridOp::Gather { dim, .. } => format!(\"GATHER (dim={})\", dim),\n            HybridOp::TopK { k, dim, largest } => {\n                format!(\"TOPK (k={}, dim={}, largest={})\", k, dim, largest)\n            }\n            HybridOp::OneHot { dim, num_classes } => {\n                format!(\"ONEHOT (dim={}, num_classes={})\", dim, num_classes)\n            }\n        }\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn std::error::Error>> {\n        Ok(Some(match self {\n            HybridOp::SumPool {\n                padding,\n                stride,\n                kernel_shape,\n                normalized,\n            } => layouts::sumpool(\n                config,\n                region,\n                values[..].try_into()?,\n                padding,\n                stride,\n                kernel_shape,\n                *normalized,\n            )?,\n            HybridOp::Recip {\n                input_scale,\n                output_scale,\n                use_range_check_for_int,\n            } => {\n                if input_scale.0.fract() == 0.0\n                    && output_scale.0.fract() == 0.0\n                    && *use_range_check_for_int\n                {\n                    layouts::recip(\n                        config,\n                        region,\n                        values[..].try_into()?,\n                        i128_to_felt(input_scale.0 as i128),\n                        i128_to_felt(output_scale.0 as i128),\n                    )?\n                } else {\n                    layouts::nonlinearity(\n                        config,\n                        region,\n                        values.try_into()?,\n                        &LookupOp::Recip {\n                            input_scale: *input_scale,\n                            output_scale: *output_scale,\n                        },\n                    )?\n                }\n            }\n            HybridOp::Div {\n                denom,\n                use_range_check_for_int,\n                ..\n            } => {\n                if denom.0.fract() == 0.0 && *use_range_check_for_int {\n                    layouts::loop_div(\n                        config,\n                        region,\n                        values[..].try_into()?,\n                        i128_to_felt(denom.0 as i128),\n                    )?\n                } else {\n                    layouts::nonlinearity(\n                        config,\n                        region,\n                        values.try_into()?,\n                        &LookupOp::Div { denom: *denom },\n                    )?\n                }\n            }\n            HybridOp::Gather { dim, constant_idx } => {\n                if let Some(idx) = constant_idx {\n                    tensor::ops::gather(values[0].get_inner_tensor()?, idx, *dim)?.into()\n                } else {\n                    layouts::gather(config, region, values[..].try_into()?, *dim)?\n                }\n            }\n\n            HybridOp::MaxPool {\n                padding,\n                stride,\n                pool_dims,\n            } => layouts::max_pool(\n                config,\n                region,\n                values[..].try_into()?,\n                padding,\n                stride,\n                pool_dims,\n            )?,\n            HybridOp::ReduceMax { axes } => {\n                layouts::max_axes(config, region, values[..].try_into()?, axes)?\n            }\n            HybridOp::ReduceArgMax { dim } => {\n                layouts::argmax_axes(config, region, values[..].try_into()?, *dim)?\n            }\n            HybridOp::ReduceMin { axes } => {\n                layouts::min_axes(config, region, values[..].try_into()?, axes)?\n            }\n            HybridOp::ReduceArgMin { dim } => {\n                layouts::argmin_axes(config, region, values[..].try_into()?, *dim)?\n            }\n            HybridOp::Softmax {\n                input_scale,\n                output_scale,\n                axes,\n            } => layouts::softmax_axes(\n                config,\n                region,\n                values[..].try_into()?,\n                *input_scale,\n                *output_scale,\n                axes,\n            )?,\n            HybridOp::RangeCheck(tol) => layouts::range_check_percent(\n                config,\n                region,\n                values[..].try_into()?,\n                tol.scale,\n                tol.val,\n            )?,\n            HybridOp::Greater => layouts::greater(config, region, values[..].try_into()?)?,\n            HybridOp::GreaterEqual => {\n                layouts::greater_equal(config, region, values[..].try_into()?)?\n            }\n            HybridOp::Less => layouts::less(config, region, values[..].try_into()?)?,\n            HybridOp::LessEqual => layouts::less_equal(config, region, values[..].try_into()?)?,\n            HybridOp::Equals => layouts::equals(config, region, values[..].try_into()?)?,\n            HybridOp::TopK { dim, k, largest } => {\n                layouts::topk_axes(config, region, values[..].try_into()?, *k, *dim, *largest)?\n            }\n            HybridOp::OneHot { dim, num_classes } => {\n                layouts::one_hot_axis(config, region, values[..].try_into()?, *num_classes, *dim)?\n            }\n        }))\n    }\n\n    fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        let scale = match self {\n            HybridOp::Greater { .. }\n            | HybridOp::GreaterEqual { .. }\n            | HybridOp::Less { .. }\n            | HybridOp::LessEqual { .. }\n            | HybridOp::ReduceArgMax { .. }\n            | HybridOp::OneHot { .. }\n            | HybridOp::ReduceArgMin { .. } => 0,\n            HybridOp::Softmax { output_scale, .. } | HybridOp::Recip { output_scale, .. } => {\n                multiplier_to_scale(output_scale.0 as f64)\n            }\n            _ => in_scales[0],\n        };\n        Ok(scale)\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/layouts.rs",
        "content": "use std::{\n    collections::{HashMap, HashSet},\n    error::Error,\n    ops::Range,\n};\n\nuse halo2_proofs::circuit::Value;\nuse halo2curves::ff::PrimeField;\nuse itertools::Itertools;\nuse log::{error, trace};\nuse maybe_rayon::{\n    iter::IntoParallelRefIterator,\n    prelude::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator},\n    slice::ParallelSliceMut,\n};\n\nuse self::tensor::{create_constant_tensor, create_zero_tensor};\n\nuse super::{\n    chip::{BaseConfig, CircuitError},\n    region::RegionCtx,\n};\nuse crate::{\n    circuit::{ops::base::BaseOp, utils},\n    fieldutils::{felt_to_i128, i128_to_felt},\n    tensor::{\n        create_unit_tensor, get_broadcasted_shape,\n        ops::{accumulated, add, mult, sub},\n        Tensor, TensorError, ValType,\n    },\n};\n\nuse super::*;\nuse crate::circuit::ops::lookup::LookupOp;\n\n/// Same as div but splits the division into N parts\npub(crate) fn loop_div<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    value: &[ValTensor<F>; 1],\n    divisor: F,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    if divisor == F::ONE {\n        return Ok(value[0].clone());\n    }\n\n    // if integer val is divisible by 2, we can use a faster method and div > F::S\n    let mut divisor = divisor;\n    let mut num_parts = 1;\n\n    while felt_to_i128(divisor) % 2 == 0 && felt_to_i128(divisor) > (2_i128.pow(F::S - 4)) {\n        divisor = i128_to_felt(felt_to_i128(divisor) / 2);\n        num_parts += 1;\n    }\n\n    let output = div(config, region, value, divisor)?;\n    if num_parts == 1 {\n        return Ok(output);\n    }\n\n    let divisor_int = 2_i128.pow(num_parts - 1);\n    let divisor_felt = i128_to_felt(divisor_int);\n    if divisor_int <= 2_i128.pow(F::S - 3) {\n        div(config, region, &[output], divisor_felt)\n    } else {\n        // keep splitting the divisor until it satisfies the condition\n        loop_div(config, region, &[output], divisor_felt)\n    }\n}\n\n/// Div accumulated layout\npub(crate) fn div<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    value: &[ValTensor<F>; 1],\n    div: F,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    if div == F::ONE {\n        return Ok(value[0].clone());\n    }\n\n    let input = value[0].clone();\n    let input_dims = input.dims();\n\n    let range_check_bracket = felt_to_i128(div) / 2;\n\n    let divisor = create_constant_tensor(div, 1);\n\n    let divisor = region.assign(&config.custom_gates.inputs[1], &divisor)?;\n    region.increment(divisor.len());\n\n    let is_assigned = !input.any_unknowns()? && !divisor.any_unknowns()?;\n\n    let mut claimed_output: ValTensor<F> = if is_assigned {\n        let input_evals = input.get_int_evals()?;\n        tensor::ops::nonlinearities::const_div(&input_evals.clone(), felt_to_i128(div) as f64)\n            .par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<Value<F>>>()\n            .into()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); input.len()]),\n            &[input.len()],\n        )?\n        .into()\n    };\n    claimed_output.reshape(input_dims)?;\n    region.assign(&config.custom_gates.output, &claimed_output)?;\n    region.increment(claimed_output.len());\n\n    let product = pairwise(\n        config,\n        region,\n        &[claimed_output.clone(), divisor.clone()],\n        BaseOp::Mult,\n    )?;\n\n    let diff_with_input = pairwise(\n        config,\n        region,\n        &[product.clone(), input.clone()],\n        BaseOp::Sub,\n    )?;\n\n    range_check(\n        config,\n        region,\n        &[diff_with_input],\n        &(-range_check_bracket, range_check_bracket),\n    )?;\n\n    Ok(claimed_output)\n}\n\n/// recip accumulated layout\npub(crate) fn recip<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    value: &[ValTensor<F>; 1],\n    input_scale: F,\n    output_scale: F,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let input = value[0].clone();\n    let input_dims = input.dims();\n\n    let integer_input_scale = felt_to_i128(input_scale);\n    let integer_output_scale = felt_to_i128(output_scale);\n\n    // range_check_bracket is min of input_scale * output_scale and 2^F::S - 3\n    let range_check_len = std::cmp::min(integer_output_scale, 2_i128.pow(F::S - 4));\n\n    let input_scale_ratio = if range_check_len > 0 {\n        i128_to_felt(integer_input_scale * integer_output_scale / range_check_len)\n    } else {\n        F::ONE\n    };\n\n    let range_check_bracket = range_check_len / 2;\n\n    let is_assigned = !input.any_unknowns()?;\n\n    let mut claimed_output: ValTensor<F> = if is_assigned {\n        let input_evals = input.get_int_evals()?;\n        tensor::ops::nonlinearities::recip(\n            &input_evals,\n            felt_to_i128(input_scale) as f64,\n            felt_to_i128(output_scale) as f64,\n        )\n        .par_iter()\n        .map(|x| Value::known(i128_to_felt(*x)))\n        .collect::<Tensor<Value<F>>>()\n        .into()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); input.len()]),\n            &[input.len()],\n        )?\n        .into()\n    };\n    claimed_output.reshape(input_dims)?;\n    let claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?;\n    region.increment(claimed_output.len());\n\n    // this is now of scale 2 * scale\n    let product = pairwise(\n        config,\n        region,\n        &[claimed_output.clone(), input.clone()],\n        BaseOp::Mult,\n    )?;\n\n    // divide by input_scale\n    let rebased_div = loop_div(config, region, &[product], input_scale_ratio)?;\n\n    let zero_inverse_val =\n        tensor::ops::nonlinearities::zero_recip(felt_to_i128(output_scale) as f64)[0];\n    let zero_inverse = create_constant_tensor(i128_to_felt(zero_inverse_val), 1);\n\n    let equal_zero_mask = equals_zero(config, region, &[input.clone()])?;\n\n    let equal_inverse_mask = equals(config, region, &[claimed_output.clone(), zero_inverse])?;\n\n    // assert the two masks are equal\n    enforce_equality(\n        config,\n        region,\n        &[equal_zero_mask.clone(), equal_inverse_mask],\n    )?;\n\n    let unit_scale = create_constant_tensor(i128_to_felt(range_check_len), 1);\n\n    let unit_mask = pairwise(config, region, &[equal_zero_mask, unit_scale], BaseOp::Mult)?;\n\n    // now add the unit mask to the rebased_div\n    let rebased_offset_div = pairwise(config, region, &[rebased_div, unit_mask], BaseOp::Add)?;\n\n    // at most the error should be in the original unit scale's range\n    range_check(\n        config,\n        region,\n        &[rebased_offset_div],\n        &(range_check_bracket, 3 * range_check_bracket),\n    )?;\n\n    Ok(claimed_output)\n}\n\n/// Dot product of two tensors.\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::einsum;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n/// use ezkl::circuit::layouts::dot;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 3, 3],\n/// ).unwrap());\n/// let y = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 5, 10, -4, 2, -1, 2, 0, 1]),\n///     &[1, 3, 3],\n/// ).unwrap());\n/// assert_eq!(dot::<Fp>(&dummy_config, &mut dummy_region, &[x, y]).unwrap().get_int_evals().unwrap()[0], 86);\n/// ```\npub fn dot<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    region.flush()?;\n    // time this entire function run\n    let global_start = instant::Instant::now();\n\n    let mut values = values.clone();\n\n    // this section has been optimized to death, don't mess with it\n    let mut removal_indices = values[0].get_const_zero_indices()?;\n    let second_zero_indices = values[1].get_const_zero_indices()?;\n    removal_indices.extend(second_zero_indices);\n    removal_indices.par_sort_unstable();\n    removal_indices.dedup();\n\n    // is already sorted\n    values[0].remove_indices(&mut removal_indices, true)?;\n    values[1].remove_indices(&mut removal_indices, true)?;\n\n    let elapsed = global_start.elapsed();\n    trace!(\"filtering const zero indices took: {:?}\", elapsed);\n\n    if values[0].len() != values[1].len() {\n        return Err(Box::new(TensorError::DimMismatch(\"dot\".to_string())));\n    }\n\n    // if empty return a const\n    if values[0].is_empty() && values[1].is_empty() {\n        return Ok(create_zero_tensor(1));\n    }\n\n    let start = instant::Instant::now();\n    let mut inputs = vec![];\n    let block_width = config.custom_gates.output.num_inner_cols();\n\n    let mut assigned_len = 0;\n    for (i, input) in values.iter_mut().enumerate() {\n        input.pad_to_zero_rem(block_width, ValType::Constant(F::ZERO))?;\n        let inp = {\n            let (res, len) = region.assign_with_duplication(\n                &config.custom_gates.inputs[i],\n                input,\n                &config.check_mode,\n                false,\n            )?;\n            assigned_len = len;\n            res.get_inner()?\n        };\n        inputs.push(inp);\n    }\n\n    let elapsed = start.elapsed();\n    trace!(\"assigning inputs took: {:?}\", elapsed);\n\n    // Now we can assign the dot product\n    // time this step\n    let start = instant::Instant::now();\n    let accumulated_dot = accumulated::dot(&[inputs[0].clone(), inputs[1].clone()], block_width)?;\n    let elapsed = start.elapsed();\n    trace!(\"calculating accumulated dot took: {:?}\", elapsed);\n\n    let start = instant::Instant::now();\n    let (output, output_assigned_len) = region.assign_with_duplication(\n        &config.custom_gates.output,\n        &accumulated_dot.into(),\n        &config.check_mode,\n        true,\n    )?;\n    let elapsed = start.elapsed();\n    trace!(\"assigning output took: {:?}\", elapsed);\n\n    // enable the selectors\n    if !region.is_dummy() {\n        (0..output_assigned_len)\n            .map(|i| {\n                let (x, _, z) = config\n                    .custom_gates\n                    .output\n                    .cartesian_coord(region.linear_coord() + i * block_width);\n                // hop over duplicates at start of column\n                if z == 0 && i > 0 {\n                    return Ok(());\n                }\n                let selector = if i == 0 {\n                    config.custom_gates.selectors.get(&(BaseOp::DotInit, x, 0))\n                } else {\n                    config.custom_gates.selectors.get(&(BaseOp::Dot, x, 0))\n                };\n                region.enable(selector, z)?;\n\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    let last_elem = output.get_slice(&[output.len() - 1..output.len()])?;\n\n    region.increment(assigned_len);\n\n    // last element is the result\n\n    let elapsed = global_start.elapsed();\n    trace!(\"dot layout took: {:?}, row {}\", elapsed, region.row());\n    trace!(\"----------------------------\");\n    Ok(last_elem)\n}\n\n/// Computes the einstein sum of a set of tensors.\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::einsum;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// // matmul case\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[2, 1, 2, 1, 1, 1]),\n///  &[2, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[2, 3, 2, 1, 1, 1]),\n/// &[3, 2],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"ij,jk->ik\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[8, 9, 5, 5]), &[2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // element wise multiplication\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]),\n///  &[3, 3],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"ij,ij->ij\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 4, 9, 2, 6, 12, 3, 8, 15]), &[3, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// // dot product of A with the transpose of B.\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]),\n///  &[3, 3],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"ik,jk->ij\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[14, 14, 14, 20, 20, 20, 26, 26, 26]), &[3, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // dot product\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]),\n///  &[3, 3],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"ik,ik->i\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[14, 20, 26]), &[3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// // dot product\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3]),\n///  &[3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3]),\n///  &[3],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"i,i->\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[14]), &[1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// // wut ?\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8]),\n///  &[2, 2],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"anm,bm->ba\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[68, 80, 95, 113, 134, 158]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // wutttttt ?\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8]),\n///  &[2, 2],\n/// ).unwrap());\n/// let z =  ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8, 9, 9]),\n///  &[2, 3],\n/// ).unwrap());\n///\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[z, x, k], \"bn,anm,bm->ba\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[390, 414, 534, 994, 1153, 1384]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// // contraction with a single common axis\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8]),\n///  &[2, 2],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"abc,cd->\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[648]), &[1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // contraction with no common axes (outer product)\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]),\n///  &[3, 3, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8]),\n///  &[2, 2],\n/// ).unwrap());\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"abc,ed->\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1296]), &[1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // trivial axes mapping\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5, 7, 8]),\n///  &[2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[4, 5]),\n///  &[2],\n/// ).unwrap());\n///\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], \"mk,k->m\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[41, 68]), &[2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], \"mk,k->mn\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[41, 68]), &[2, 1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[0, 0, 0, 3]),\n///  &[1, 4],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[213, 227, 74, 77]),\n///  &[4],\n/// ).unwrap());\n///\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], \"mk,k->ma\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[231]), &[1, 1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// // subtle difference\n/// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], \"mk,n->ma\").unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1773]), &[1, 1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// ```\n///\npub fn einsum<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    inputs: &[ValTensor<F>],\n    equation: &str,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut equation = equation.split(\"->\");\n    let inputs_eq = equation.next().ok_or(CircuitError::InvalidEinsum)?;\n    let output_eq = equation.next().ok_or(CircuitError::InvalidEinsum)?;\n    let inputs_eq = inputs_eq.split(',').collect::<Vec<_>>();\n\n    // Check that the number of inputs matches the number of inputs in the equation\n    if inputs.len() != inputs_eq.len() {\n        return Err(Box::new(TensorError::DimMismatch(\"einsum\".to_string())));\n    }\n\n    let mut indices_to_size = HashMap::new();\n    for (i, input) in inputs.iter().enumerate() {\n        for j in 0..inputs_eq[i].len() {\n            let c = inputs_eq[i]\n                .chars()\n                .nth(j)\n                .ok_or(CircuitError::InvalidEinsum)?;\n            if let std::collections::hash_map::Entry::Vacant(e) = indices_to_size.entry(c) {\n                e.insert(input.dims()[j]);\n            } else if indices_to_size[&c] != input.dims()[j] {\n                return Err(Box::new(TensorError::DimMismatch(\"einsum\".to_string())));\n            }\n        }\n    }\n\n    // maps unrepresented indices in the output to a trivial 1\n    for c in output_eq.chars() {\n        indices_to_size.entry(c).or_insert(1);\n    }\n\n    // Compute the output tensor shape\n    let mut output_shape: Vec<usize> = output_eq\n        .chars()\n        .map(|c| {\n            indices_to_size\n                .get(&c)\n                .ok_or(CircuitError::InvalidEinsum)\n                .copied()\n        })\n        .collect::<Result<Vec<_>, _>>()?;\n\n    if output_shape.is_empty() {\n        output_shape.push(1);\n    }\n\n    // Create a new output tensor with the computed shape\n    let mut output: Tensor<ValType<F>> = Tensor::new(None, &output_shape)?;\n\n    let mut seen = HashSet::new();\n    let mut common_indices_to_inputs = vec![];\n    for input in inputs_eq.iter().take(inputs.len()) {\n        for c in input.chars() {\n            if !seen.contains(&c) {\n                seen.insert(c);\n            } else {\n                common_indices_to_inputs.push(c);\n            }\n        }\n    }\n\n    let non_common_indices = indices_to_size\n        .keys()\n        .filter(|&x| !common_indices_to_inputs.contains(x))\n        .collect::<Vec<_>>();\n\n    let non_common_coord_size = non_common_indices\n        .iter()\n        .map(|d| {\n            // If the current index is in the output equation, then the slice should be the current coordinate\n            if output_eq.contains(**d) {\n                Ok(1)\n            // Otherwise, the slice should be the entire dimension of the input tensor\n            } else {\n                indices_to_size\n                    .get(d)\n                    .ok_or(CircuitError::InvalidEinsum)\n                    .copied()\n            }\n        })\n        .collect::<Result<Vec<_>, _>>()?\n        .iter()\n        .product::<usize>();\n\n    let cartesian_coord = output_shape\n        .iter()\n        .map(|d| 0..*d)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    // Get the indices common across input tensors\n    let mut common_coord = common_indices_to_inputs\n        .iter()\n        .map(|d| {\n            // If the current index is in the output equation, then the slice should be the current coordinate\n            if output_eq.contains(*d) {\n                Ok(0..1)\n            // Otherwise, the slice should be the entire dimension of the input tensor\n            } else {\n                Ok(0..*indices_to_size.get(d).ok_or(CircuitError::InvalidEinsum)?)\n            }\n        })\n        .collect::<Result<Vec<Range<_>>, Box<dyn Error>>>()?\n        .into_iter()\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    // If there are no common indices, then we need to add an empty slice to force one iteration of the loop\n    if common_coord.is_empty() {\n        common_coord.push(vec![]);\n    }\n\n    let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| {\n        let coord = cartesian_coord[i].clone();\n        // Compute the slice of each input tensor given the current coordinate of the output tensor\n        let inputs = (0..inputs.len())\n            .map(|idx| {\n                let mut slice = vec![];\n                for (i, c) in inputs_eq[idx].chars().enumerate() {\n                    // If the current index is in the output equation, then the slice should be the current coordinate\n                    if let Some(idx) = output_eq.find(c) {\n                        slice.push(coord[idx]..coord[idx] + 1);\n                    // Otherwise, the slice should be the entire dimension of the input tensor\n                    } else {\n                        slice.push(0..inputs[idx].dims()[i]);\n                    }\n                }\n                // Get the slice of the input tensor\n                inputs[idx].get_slice(&slice)\n            })\n            .collect::<Result<Vec<_>, _>>()?;\n\n        // in this case its just a dot product :)\n        if non_common_coord_size == 1 && inputs.len() == 2 {\n            Ok(dot(\n                config,\n                region,\n                inputs[..].try_into().map_err(|e| {\n                    error!(\"{}\", e);\n                    halo2_proofs::plonk::Error::Synthesis\n                })?,\n            )?\n            .get_inner_tensor()?[0]\n                .clone())\n        } else {\n            let mut prod_res = None;\n\n            // Compute the cartesian product of all common indices\n            for common_dim in &common_coord {\n                let inputs = (0..inputs.len())\n                    .map(|idx| {\n                        let mut slice = vec![];\n                        // Iterate over all indices in the input equation\n                        for (i, c) in inputs_eq[idx].chars().enumerate() {\n                            // If the current index is common to multiple inputs, then the slice should be the current coordinate\n                            if let Some(j) = common_indices_to_inputs.iter().position(|&r| r == c) {\n                                slice.push(common_dim[j]..common_dim[j] + 1);\n                            } else {\n                                slice.push(0..inputs[idx].dims()[i]);\n                            }\n                        }\n                        // Get the slice of the input tensor\n                        inputs[idx].get_slice(&slice).map_err(|e| {\n                            error!(\"{}\", e);\n                            halo2_proofs::plonk::Error::Synthesis\n                        })\n                    })\n                    .collect::<Result<Vec<_>, _>>()?;\n\n                let mut input_pairs = vec![];\n\n                for input in inputs {\n                    input_pairs.push(input.get_inner_tensor()?.clone().into_iter());\n                }\n\n                let input_pairs = input_pairs\n                    .into_iter()\n                    .multi_cartesian_product()\n                    .collect::<Vec<_>>();\n\n                // Compute the product of all input tensors\n                for pair in input_pairs {\n                    let product_across_pair = prod(config, region, &[pair.into()])?;\n\n                    if let Some(product) = prod_res {\n                        prod_res = Some(\n                            pairwise(config, region, &[product, product_across_pair], BaseOp::Add)\n                                .map_err(|e| {\n                                    error!(\"{}\", e);\n                                    halo2_proofs::plonk::Error::Synthesis\n                                })?,\n                        );\n                    } else {\n                        prod_res = Some(product_across_pair);\n                    }\n                }\n            }\n            Ok::<_, region::RegionError>(\n                prod_res\n                    .ok_or(Into::<region::RegionError>::into(\"missing prod\"))?\n                    .get_inner_tensor()?[0]\n                    .clone(),\n            )\n        }\n    };\n\n    region.flush()?;\n    region.apply_in_loop(&mut output, inner_loop_function)?;\n\n    let output: ValTensor<F> = output.into();\n\n    Ok(output)\n}\n\nfn _sort_ascending<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut input = values[0].clone();\n    input.flatten();\n\n    let is_assigned = !input.any_unknowns()?;\n\n    let sorted = if is_assigned {\n        let mut int_evals = input.get_int_evals()?;\n        int_evals.par_sort_unstable_by(|a, b| a.cmp(b));\n        int_evals\n            .par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<Value<F>>>()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); input.len()]),\n            &[input.len()],\n        )?\n    };\n\n    let assigned_sort = region.assign(&config.custom_gates.inputs[0], &sorted.into())?;\n\n    region.increment(assigned_sort.len());\n\n    let window_a = assigned_sort.get_slice(&[0..assigned_sort.len() - 1])?;\n    let window_b = assigned_sort.get_slice(&[1..assigned_sort.len()])?;\n\n    let is_greater = greater_equal(config, region, &[window_b.clone(), window_a.clone()])?;\n\n    let unit = create_unit_tensor(is_greater.len());\n\n    enforce_equality(config, region, &[unit, is_greater])?;\n\n    // assert that this is a permutation/shuffle\n    shuffles(config, region, &[assigned_sort.clone()], &[input.clone()])?;\n\n    Ok(assigned_sort)\n}\n\n/// Returns top K values.\nfn _select_topk<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    k: usize,\n    largest: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut sorted = _sort_ascending(config, region, values)?;\n    if largest {\n        sorted.reverse()?;\n    }\n    sorted.get_slice(&[0..k])\n}\n\n/// Returns top K values.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::topk_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2,3],\n/// ).unwrap());\n/// let result = topk_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 2, 1, true).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[15, 2, 1, 1]),\n///     &[2,2],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn topk_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    k: usize,\n    dim: usize,\n    largest: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let topk_at_k = move |config: &BaseConfig<F>,\n                          region: &mut RegionCtx<F>,\n                          values: &[ValTensor<F>; 1]|\n          -> Result<ValTensor<F>, Box<dyn Error>> {\n        _select_topk(config, region, values, k, largest)\n    };\n\n    let output: ValTensor<F> = multi_dim_axes_op(config, region, values, &[dim], topk_at_k)?;\n\n    Ok(output)\n}\n\nfn select<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let start = instant::Instant::now();\n    let (mut input, index) = (values[0].clone(), values[1].clone());\n    input.flatten();\n\n    // these will be assigned as constants\n    let dim_indices: ValTensor<F> =\n        Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into();\n\n    let is_assigned = !input.any_unknowns()? && !index.any_unknowns()?;\n\n    let output: ValTensor<F> = if is_assigned && region.witness_gen() {\n        let felt_evals = input.get_felt_evals()?;\n        index\n            .get_int_evals()?\n            .par_iter()\n            .map(|x| Value::known(felt_evals.get(&[*x as usize])))\n            .collect::<Tensor<Value<F>>>()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); index.len()]),\n            &[index.len()],\n        )?\n    }\n    .into();\n\n    let (_, assigned_output) =\n        dynamic_lookup(config, region, &[index, output], &[dim_indices, input])?;\n\n    let end = start.elapsed();\n    trace!(\"select took: {:?}\", end);\n\n    Ok(assigned_output)\n}\n\nfn one_hot<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    num_classes: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // assert values is flat\n    assert_eq!(values[0].dims().len(), 1);\n    // assert its a single elelemnt\n    assert_eq!(values[0].len(), 1);\n    let input = values[0].clone();\n    let is_assigned = !input.any_unknowns()?;\n\n    let output: ValTensor<F> = if is_assigned {\n        let int_evals = input.get_int_evals()?;\n        let res = tensor::ops::one_hot(&int_evals, num_classes, 1)?;\n        res.par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<_>>()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); num_classes]),\n            &[num_classes],\n        )?\n    }\n    .into();\n\n    let assigned_input = region.assign(&config.custom_gates.inputs[0], &input)?;\n\n    // now assert all elems are 0 or 1\n    let assigned_output = boolean_identity(config, region, &[output.clone()], true)?;\n    region.increment(std::cmp::max(assigned_output.len(), assigned_input.len()));\n\n    let sum = sum(config, region, &[assigned_output.clone()])?;\n    // assert sum is 1\n    let unit = create_unit_tensor(1);\n\n    enforce_equality(config, region, &[unit.clone(), sum])?;\n\n    let gathered = gather(\n        config,\n        region,\n        &[assigned_output.clone(), assigned_input.clone()],\n        0,\n    )?;\n\n    enforce_equality(config, region, &[unit, gathered])?;\n\n    Ok(assigned_output)\n}\n\n/// Dynamic lookup\npub(crate) fn dynamic_lookup<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    lookups: &[ValTensor<F>; 2],\n    tables: &[ValTensor<F>; 2],\n) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> {\n    let start = instant::Instant::now();\n    // if not all lookups same length err\n    if lookups[0].len() != lookups[1].len() {\n        return Err(\"lookups must be same length\".into());\n    }\n\n    // if not all inputs same length err\n    if tables[0].len() != tables[1].len() {\n        return Err(\"tables must be same length\".into());\n    }\n\n    let dynamic_lookup_index = region.dynamic_lookup_index();\n\n    let (lookup_0, lookup_1) = (lookups[0].clone(), lookups[1].clone());\n    let (table_0, table_1) = (tables[0].clone(), tables[1].clone());\n\n    let table_0 = region.assign_dynamic_lookup(&config.dynamic_lookups.tables[0], &table_0)?;\n    let _table_1 = region.assign_dynamic_lookup(&config.dynamic_lookups.tables[1], &table_1)?;\n    let table_len = table_0.len();\n\n    trace!(\"assigning tables took: {:?}\", start.elapsed());\n\n    // now create a vartensor of constants for the dynamic lookup index\n    let table_index = create_constant_tensor(F::from(dynamic_lookup_index as u64), table_len);\n    let _table_index =\n        region.assign_dynamic_lookup(&config.dynamic_lookups.tables[2], &table_index)?;\n\n    trace!(\"assigning table index took: {:?}\", start.elapsed());\n\n    let lookup_0 = region.assign(&config.dynamic_lookups.inputs[0], &lookup_0)?;\n    let lookup_1 = region.assign(&config.dynamic_lookups.inputs[1], &lookup_1)?;\n    let lookup_len = lookup_0.len();\n\n    trace!(\"assigning lookups took: {:?}\", start.elapsed());\n\n    // now set the lookup index\n    let lookup_index = create_constant_tensor(F::from(dynamic_lookup_index as u64), lookup_len);\n\n    let _lookup_index = region.assign(&config.dynamic_lookups.inputs[2], &lookup_index)?;\n\n    trace!(\"assigning lookup index took: {:?}\", start.elapsed());\n\n    if !region.is_dummy() {\n        (0..table_len)\n            .map(|i| {\n                let table_selector = config.dynamic_lookups.table_selectors[0];\n                let (_, _, z) = config.dynamic_lookups.tables[0]\n                    .cartesian_coord(region.combined_dynamic_shuffle_coord() + i);\n                region.enable(Some(&table_selector), z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    if !region.is_dummy() {\n        // Enable the selectors\n        (0..lookup_len)\n            .map(|i| {\n                let (x, y, z) =\n                    config.dynamic_lookups.inputs[0].cartesian_coord(region.linear_coord() + i);\n                let lookup_selector = config\n                    .dynamic_lookups\n                    .lookup_selectors\n                    .get(&(x, y))\n                    .ok_or(\"missing selectors\")?;\n\n                region.enable(Some(lookup_selector), z)?;\n\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    region.increment_dynamic_lookup_col_coord(table_len);\n    region.increment_dynamic_lookup_index(1);\n    region.increment(lookup_len);\n\n    let end = start.elapsed();\n    trace!(\"dynamic lookup took: {:?}\", end);\n\n    Ok((lookup_0, lookup_1))\n}\n\n/// Shuffle arg\npub(crate) fn shuffles<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    input: &[ValTensor<F>; 1],\n    reference: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let shuffle_index = region.shuffle_index();\n    let (input, reference) = (input[0].clone(), reference[0].clone());\n\n    // assert input and reference are same length\n    if input.len() != reference.len() {\n        return Err(\"input and reference must be same length\".into());\n    }\n\n    let reference = region.assign_shuffle(&config.shuffles.references[0], &reference)?;\n    let reference_len = reference.len();\n\n    // now create a vartensor of constants for the shuffle index\n    let index = create_constant_tensor(F::from(shuffle_index as u64), reference_len);\n    let index = region.assign_shuffle(&config.shuffles.references[1], &index)?;\n\n    let input = region.assign(&config.shuffles.inputs[0], &input)?;\n    region.assign(&config.shuffles.inputs[1], &index)?;\n\n    if !region.is_dummy() {\n        (0..reference_len)\n            .map(|i| {\n                let ref_selector = config.shuffles.reference_selectors[0];\n                let (_, _, z) = config.shuffles.references[0]\n                    .cartesian_coord(region.combined_dynamic_shuffle_coord() + i);\n                region.enable(Some(&ref_selector), z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    if !region.is_dummy() {\n        // Enable the selectors\n        (0..reference_len)\n            .map(|i| {\n                let (x, y, z) =\n                    config.custom_gates.inputs[0].cartesian_coord(region.linear_coord() + i);\n                let input_selector = config\n                    .shuffles\n                    .input_selectors\n                    .get(&(x, y))\n                    .ok_or(\"missing selectors\")?;\n\n                region.enable(Some(input_selector), z)?;\n\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    region.increment_shuffle_col_coord(reference_len);\n    region.increment_shuffle_index(1);\n    region.increment(reference_len);\n\n    Ok(input)\n}\n\n/// One hot accumulated layout\npub(crate) fn one_hot_axis<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    num_classes: usize,\n    dim: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let input = values[0].clone();\n    let input_inner = input.get_inner_tensor()?;\n\n    let mut output_dims = values[0].dims().to_vec();\n    output_dims.insert(dim, num_classes);\n\n    let mut op_tensors: Tensor<ValTensor<F>> = Tensor::new(None, input_inner.dims())?;\n\n    let inner_loop_function =\n        |i: usize, region: &mut RegionCtx<'_, F>| -> Result<ValTensor<F>, _> {\n            let inp = input_inner[i].clone();\n            let tensor = Tensor::new(Some(&[inp.clone()]), &[1])?;\n\n            Ok(one_hot(config, region, &[tensor.into()], num_classes)?)\n        };\n\n    region.apply_in_loop(&mut op_tensors, inner_loop_function)?;\n\n    // Allocate memory for the output tensor\n    let cartesian_coord = output_dims\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let mut output = Tensor::<ValType<F>>::new(None, &output_dims)?;\n\n    output = output.par_enum_map(|i, _| {\n        let coord = cartesian_coord[i].clone();\n        let mut op_idx = coord.clone();\n        let coord_at_dims = vec![coord[dim]];\n        op_idx.remove(dim);\n\n        let op_tensor = op_tensors.get(&op_idx);\n\n        let op_tensor = op_tensor.get_inner_tensor()?;\n\n        let one_hot_val = op_tensor.get(&coord_at_dims).clone();\n\n        Ok::<_, region::RegionError>(one_hot_val)\n    })?;\n\n    Ok(output.into())\n}\n\n/// Gather accumulated layout\npub(crate) fn gather<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    dim: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (input, mut index_clone) = (values[0].clone(), values[1].clone());\n    index_clone.flatten();\n    if index_clone.is_singleton() {\n        index_clone.reshape(&[1])?;\n    }\n\n    // Calculate the output tensor size\n    let input_dims = input.dims();\n    let mut output_size = input_dims.to_vec();\n    output_size[dim] = index_clone.dims()[0];\n\n    let linear_index =\n        linearize_element_index(config, region, &[index_clone], input_dims, dim, true)?;\n\n    let mut output = select(config, region, &[input, linear_index])?;\n\n    output.reshape(&output_size)?;\n\n    Ok(output)\n}\n\n/// Gather accumulated layout\npub(crate) fn gather_elements<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    dim: usize,\n) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> {\n    let (input, index) = (values[0].clone(), values[1].clone());\n\n    assert_eq!(input.dims().len(), index.dims().len());\n\n    // Calculate the output tensor size\n    let output_size = index.dims().to_vec();\n\n    let linear_index = linearize_element_index(config, region, &[index], input.dims(), dim, false)?;\n\n    let mut output = select(config, region, &[input, linear_index.clone()])?;\n\n    output.reshape(&output_size)?;\n\n    Ok((output, linear_index))\n}\n\n/// Gather accumulated layout\npub(crate) fn gather_nd<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    batch_dims: usize,\n) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> {\n    let (input, index) = (values[0].clone(), values[1].clone());\n\n    let index_dims = index.dims().to_vec();\n    let input_dims = input.dims().to_vec();\n    let last_value = index_dims\n        .last()\n        .ok_or(TensorError::DimMismatch(\"gather_nd\".to_string()))?;\n    if index_dims.last() > Some(&(input_dims.len() - batch_dims)) {\n        return Err(TensorError::DimMismatch(\"gather_nd\".to_string()).into());\n    }\n\n    let output_size =\n    // If indices_shape[-1] == r-b, since the rank of indices is q,\n    // indices can be thought of as N (q-b-1)-dimensional tensors containing 1-D tensors of dimension r-b,\n    // where N is an integer equals to the product of 1 and all the elements in the batch dimensions of the indices_shape.\n    // Let us think of each such r-b ranked tensor as indices_slice.\n    // Each scalar value corresponding to data[0:b-1,indices_slice] is filled into\n    // the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor\n     // if indices_shape[-1] < r-b, since the rank of indices is q, indices can be thought of as N (q-b-1)-dimensional tensor containing 1-D tensors of dimension < r-b.\n    // Let us think of each such tensors as indices_slice.\n    // Each tensor slice corresponding to data[0:b-1, indices_slice , :] is filled into the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor\n    {\n        let output_rank = input_dims.len() + index_dims.len() - 1 - batch_dims - last_value;\n\n        let mut dims = index_dims[..index_dims.len() - 1].to_vec();\n        let input_offset = batch_dims + last_value;\n        dims.extend(input_dims[input_offset..input_dims.len()].to_vec());\n\n        assert_eq!(output_rank, dims.len());\n        dims\n\n    };\n\n    let linear_index = linearize_nd_index(config, region, &[index], input.dims(), batch_dims)?;\n\n    let mut output = select(config, region, &[input, linear_index.clone()])?;\n\n    output.reshape(&output_size)?;\n\n    Ok((output, linear_index))\n}\n\n/// Takes a tensor representing a multi-dimensional index and returns a tensor representing the linearized index.\n/// The linearized index is the index of the element in the flattened tensor.\n/// FOr instance if the dims is [3,5,2], the linearized index of [2] at dim 1 is 2*5 + 3 = 13\npub(crate) fn linearize_element_index<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    dims: &[usize],\n    dim: usize,\n    is_flat_index: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let start_time = instant::Instant::now();\n    let index = values[0].clone();\n    if !is_flat_index {\n        assert_eq!(index.dims().len(), dims.len());\n        // if the index is already flat, return it\n        if index.dims().len() == 1 {\n            return Ok(index);\n        }\n    }\n\n    let dim_multiplier: Tensor<usize> = Tensor::new(None, &[dims.len()])?;\n\n    let dim_multiplier: Tensor<F> = dim_multiplier.par_enum_map(|i, _| {\n        let mut res = 1;\n        for dim in dims.iter().skip(i + 1) {\n            res *= dim;\n        }\n\n        Ok::<_, region::RegionError>(F::from(res as u64))\n    })?;\n\n    let iteration_dims = if is_flat_index {\n        let mut dims = dims.to_vec();\n        dims[dim] = index.len();\n        dims\n    } else {\n        index.dims().to_vec()\n    };\n\n    let cartesian_coord = iteration_dims\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let val_dim_multiplier: ValTensor<F> = dim_multiplier\n        .get_slice(&[dim..dim + 1])?\n        .map(|x| ValType::Constant(x))\n        .into();\n\n    let mut output = Tensor::new(None, &[cartesian_coord.len()])?;\n\n    let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| {\n        let coord = cartesian_coord[i].clone();\n        let slice: Vec<Range<usize>> = if is_flat_index {\n            coord[dim..dim + 1].iter().map(|x| *x..*x + 1).collect()\n        } else {\n            coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>()\n        };\n\n        let index_val = index.get_slice(&slice)?;\n\n        let mut const_offset = F::ZERO;\n        for i in 0..dims.len() {\n            if i != dim {\n                const_offset += F::from(coord[i] as u64) * dim_multiplier[i];\n            }\n        }\n        let const_offset = create_constant_tensor(const_offset, 1);\n\n        let res = pairwise(\n            config,\n            region,\n            &[index_val, val_dim_multiplier.clone()],\n            BaseOp::Mult,\n        )?;\n\n        let res = pairwise(config, region, &[res, const_offset], BaseOp::Add)?;\n\n        Ok(res.get_inner_tensor()?[0].clone())\n    };\n\n    region.apply_in_loop(&mut output, inner_loop_function)?;\n\n    let elapsed = start_time.elapsed();\n    trace!(\"linearize_element_index took: {:?}\", elapsed);\n\n    Ok(output.into())\n}\n\n/// Takes a tensor representing a nd index and returns a tensor representing the linearized index.\n/// The linearized index is the index of the element in the flattened tensor.\n/// Given data tensor of rank r >= 1, indices tensor of rank q >= 1, and batch_dims integer b, this operator gathers slices of data into an output tensor of rank q + r - indices_shape[-1] - 1 - b.\n/// indices is an q-dimensional integer tensor, best thought of as a (q-1)-dimensional tensor of index-tuples into data, where each element defines a slice of data\n/// batch_dims (denoted as b) is an integer indicating the number of batch dimensions, i.e the leading b number of dimensions of data tensor and indices are representing the batches, and the gather starts from the b+1 dimension.\n/// Some salient points about the inputs\u2019 rank and shape:\n///     r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks r and q\n///     The first b dimensions of the shape of indices tensor and data tensor must be equal.\n///     b < min(q, r) is to be honored.\n///     The indices_shape[-1] should have a value between 1 (inclusive) and rank r-b (inclusive)\n///     All values in indices are expected to be within bounds [-s, s-1] along axis of size s (i.e.) -data_shape[i] <= indices[...,i] <= data_shape[i] - 1. It is an error if any of the index values are out of bounds.\n// The output is computed as follows:\n/// The output tensor is obtained by mapping each index-tuple in the indices tensor to the corresponding slice of the input data.\n///     If indices_shape[-1] > r-b => error condition\n///     If indices_shape[-1] == r-b, since the rank of indices is q, indices can be thought of as N (q-b-1)-dimensional tensors containing 1-D tensors of dimension r-b, where N is an integer equals to the product of 1 and all the elements in the batch dimensions of the indices_shape.\n///     Let us think of each such r-b ranked tensor as indices_slice. Each scalar value corresponding to data[0:b-1,indices_slice] is filled into the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor (Example 1 below)\n///     If indices_shape[-1] < r-b, since the rank of indices is q, indices can be thought of as N (q-b-1)-dimensional tensor containing 1-D tensors of dimension < r-b. Let us think of each such tensors as indices_slice. Each tensor slice corresponding to data[0:b-1, indices_slice , :] is filled into the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor (Examples 2, 3, 4 and 5 below)\npub(crate) fn linearize_nd_index<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    dims: &[usize],\n    batch_dims: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let index = values[0].clone();\n    let index_dims = index.dims().to_vec();\n\n    let last_dim = index.dims().last().unwrap();\n    let input_rank = dims[batch_dims..].len();\n\n    let dim_multiplier: Tensor<usize> = Tensor::new(None, &[dims.len()])?;\n    let dim_multiplier: Tensor<F> = dim_multiplier.par_enum_map(|i, _| {\n        let mut res = 1;\n        for dim in dims.iter().skip(i + 1) {\n            res *= dim;\n        }\n        Ok::<_, region::RegionError>(F::from(res as u64))\n    })?;\n\n    let iteration_dims = index.dims()[0..batch_dims].to_vec();\n\n    let mut batch_cartesian_coord = iteration_dims\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    if batch_cartesian_coord.is_empty() {\n        batch_cartesian_coord.push(vec![]);\n    }\n\n    let index_dim_multiplier: ValTensor<F> = dim_multiplier\n        .get_slice(&[batch_dims..dims.len()])?\n        .map(|x| ValType::Constant(x))\n        .into();\n\n    let mut outer_results = vec![];\n\n    for coord in batch_cartesian_coord {\n        let slice: Vec<Range<usize>> = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n\n        let mut index_slice = index.get_slice(&slice)?;\n        index_slice.reshape(&index_dims[batch_dims..])?;\n\n        // expand the index to the full dims by iterating over the rest of the dims and inserting constants\n        // eg in the case\n        // batch_dims = 0\n        // data    = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape    = [2, 2, 2]\n        // indices = [[0,1],[1,0]]                 # indices_shape = [2, 2]\n        // output  = [[2,3],[4,5]]                 # output_shape  = [2, 2]\n        // the index should be expanded to the shape [2,2,3]: [[0,1,0],[0,1,1],[1,0,0],[1,0,1]]\n\n        let mut inner_cartesian_coord = index_slice.dims()[0..index_slice.dims().len() - 1]\n            .iter()\n            .map(|x| 0..*x)\n            .multi_cartesian_product()\n            .collect::<Vec<_>>();\n\n        if inner_cartesian_coord.is_empty() {\n            inner_cartesian_coord.push(vec![]);\n        }\n\n        let indices = if last_dim < &input_rank {\n            inner_cartesian_coord\n                .iter()\n                .map(|x| {\n                    let slice = x.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n                    let index = index_slice.get_slice(&slice)?;\n\n                    // map over cartesian coord of rest of dims and insert constants\n                    let grid = (*last_dim..input_rank)\n                        .map(|x| 0..dims[x])\n                        .multi_cartesian_product();\n\n                    Ok(grid\n                        .map(|x| {\n                            let index = index.clone();\n                            let constant_valtensor: ValTensor<F> = Tensor::from(\n                                x.into_iter().map(|x| ValType::Constant(F::from(x as u64))),\n                            )\n                            .into();\n                            index.concat(constant_valtensor)\n                        })\n                        .collect::<Result<Vec<_>, TensorError>>()?)\n                })\n                .collect::<Result<Vec<_>, Box<dyn Error>>>()?\n                .into_iter()\n                .flatten()\n                .collect::<Vec<_>>()\n        } else {\n            inner_cartesian_coord\n                .iter()\n                .map(|x| {\n                    let slice = x.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n                    index_slice.get_slice(&slice)\n                })\n                .collect::<Result<Vec<_>, Box<dyn Error>>>()?\n        };\n\n        let mut const_offset = F::ZERO;\n        for i in 0..batch_dims {\n            const_offset += F::from(coord[i] as u64) * dim_multiplier[i];\n        }\n\n        let const_offset = create_constant_tensor(const_offset, 1);\n\n        let mut results = vec![];\n\n        for index_val in indices {\n            let mut index_val = index_val.clone();\n            index_val.flatten();\n            let res = pairwise(\n                config,\n                region,\n                &[index_val.clone(), index_dim_multiplier.clone()],\n                BaseOp::Mult,\n            )?;\n            let res = res.concat(const_offset.clone())?;\n            let res = sum(config, region, &[res])?;\n            results.push(res.get_inner_tensor()?.clone());\n            // assert than res is less than the product of the dims\n            if region.witness_gen() {\n                assert!(\n                res.get_int_evals()?\n                    .iter()\n                    .all(|x| *x < dims.iter().product::<usize>() as i128),\n                \"res is greater than the product of the dims {} (coord={}, index_dim_multiplier={}, res={})\",\n                dims.iter().product::<usize>(),\n                index_val.show(),\n                index_dim_multiplier.show(),\n                res.show()\n            );\n            }\n        }\n\n        let result_tensor = Tensor::from(results.into_iter());\n\n        outer_results.push(result_tensor.combine()?);\n    }\n\n    let output = Tensor::from(outer_results.into_iter());\n    let output = output.combine()?;\n\n    Ok(output.into())\n}\n\npub(crate) fn get_missing_set_elements<\n    F: PrimeField + TensorType + PartialOrd + std::hash::Hash,\n>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    ordered: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (mut input, fullset) = (values[0].clone(), values[1].clone());\n    let set_len = fullset.len();\n    input.flatten();\n\n    let is_assigned = !input.any_unknowns()? && !fullset.any_unknowns()?;\n\n    let mut claimed_output: ValTensor<F> = if is_assigned {\n        let input_evals = input.get_int_evals()?;\n        let mut fullset_evals = fullset.get_int_evals()?.into_iter().collect::<Vec<_>>();\n\n        // get the difference between the two vectors\n        for eval in input_evals.iter() {\n            // delete first occurence of that value\n            if let Some(pos) = fullset_evals.iter().position(|x| x == eval) {\n                fullset_evals.remove(pos);\n            }\n        }\n\n        // if fullset + input is the same length, then input is a subset of fullset, else randomly delete elements, this is a patch for\n        // the fact that we can't have a tensor of unknowns when using constant during gen-settings\n        if fullset_evals.len() != set_len - input.len() {\n            fullset_evals.truncate(set_len - input.len());\n        }\n\n        fullset_evals\n            .par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<Value<F>>>()\n            .into()\n    } else {\n        let dim = fullset.len() - input.len();\n        Tensor::new(Some(&vec![Value::<F>::unknown(); dim]), &[dim])?.into()\n    };\n\n    // assign the claimed output\n    claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?;\n\n    // input and claimed output should be the shuffles of fullset\n    // concatentate input and claimed output\n    let input_and_claimed_output = input.concat(claimed_output.clone())?;\n\n    // assert that this is a permutation/shuffle\n    shuffles(\n        config,\n        region,\n        &[input_and_claimed_output.clone()],\n        &[fullset.clone()],\n    )?;\n\n    if ordered {\n        // assert that the claimed output is sorted\n        claimed_output = _sort_ascending(config, region, &[claimed_output])?;\n    }\n\n    Ok(claimed_output)\n}\n\n/// Gather accumulated layout\npub(crate) fn scatter_elements<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 3],\n    dim: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (input, mut index, src) = (values[0].clone(), values[1].clone(), values[2].clone());\n\n    assert_eq!(input.dims().len(), index.dims().len());\n\n    if !index.all_prev_assigned() {\n        index = region.assign(&config.custom_gates.inputs[1], &index)?;\n        region.increment(index.len());\n    }\n\n    let is_assigned = !input.any_unknowns()? && !index.any_unknowns()? && !src.any_unknowns()?;\n\n    let claimed_output: ValTensor<F> = if is_assigned && region.witness_gen() {\n        let input_inner = input.get_int_evals()?;\n        let index_inner = index.get_int_evals()?.map(|x| x as usize);\n        let src_inner = src.get_int_evals()?;\n\n        let res = tensor::ops::scatter(&input_inner, &index_inner, &src_inner, dim)?;\n\n        res.par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<Value<F>>>()\n            .into()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); input.len()]),\n            &[input.len()],\n        )?\n        .into()\n    };\n\n    // assign the claimed output\n    let mut claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?;\n    region.increment(claimed_output.len());\n    claimed_output.reshape(input.dims())?;\n\n    // scatter elements is the inverse of gather elements\n    let (gather_src, linear_index) = gather_elements(\n        config,\n        region,\n        &[claimed_output.clone(), index.clone()],\n        dim,\n    )?;\n\n    // assert this is equal to the src\n    enforce_equality(config, region, &[gather_src, src])?;\n\n    let full_index_set: ValTensor<F> =\n        Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into();\n    let input_indices = get_missing_set_elements(\n        config,\n        region,\n        &[linear_index, full_index_set.clone()],\n        true,\n    )?;\n\n    claimed_output.flatten();\n    let (gather_input, _) = gather_elements(\n        config,\n        region,\n        &[claimed_output.clone(), input_indices.clone()],\n        0,\n    )?;\n    // assert this is a subset of the input\n    dynamic_lookup(\n        config,\n        region,\n        &[input_indices, gather_input],\n        &[full_index_set, input.clone()],\n    )?;\n\n    claimed_output.reshape(input.dims())?;\n\n    Ok(claimed_output)\n}\n\n/// Scatter Nd\npub(crate) fn scatter_nd<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 3],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (input, mut index, src) = (values[0].clone(), values[1].clone(), values[2].clone());\n\n    if !index.all_prev_assigned() {\n        index = region.assign(&config.custom_gates.inputs[1], &index)?;\n        region.increment(index.len());\n    }\n\n    let is_assigned = !input.any_unknowns()? && !index.any_unknowns()? && !src.any_unknowns()?;\n\n    let claimed_output: ValTensor<F> = if is_assigned && region.witness_gen() {\n        let input_inner = input.get_int_evals()?;\n        let index_inner = index.get_int_evals()?.map(|x| x as usize);\n        let src_inner = src.get_int_evals()?;\n\n        let res = tensor::ops::scatter_nd(&input_inner, &index_inner, &src_inner)?;\n\n        res.par_iter()\n            .map(|x| Value::known(i128_to_felt(*x)))\n            .collect::<Tensor<Value<F>>>()\n            .into()\n    } else {\n        Tensor::new(\n            Some(&vec![Value::<F>::unknown(); input.len()]),\n            &[input.len()],\n        )?\n        .into()\n    };\n\n    // assign the claimed output\n    let mut claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?;\n    region.increment(claimed_output.len());\n    claimed_output.reshape(input.dims())?;\n\n    // scatter elements is the inverse of gather elements\n    let (gather_src, linear_index) =\n        gather_nd(config, region, &[claimed_output.clone(), index.clone()], 0)?;\n\n    // assert this is equal to the src\n    enforce_equality(config, region, &[gather_src, src])?;\n\n    let full_index_set: ValTensor<F> =\n        Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into();\n\n    let input_indices = get_missing_set_elements(\n        config,\n        region,\n        &[linear_index, full_index_set.clone()],\n        true,\n    )?;\n\n    // now that it is flattened we can gather over elements on dim 0\n    claimed_output.flatten();\n    let (gather_input, _) = gather_elements(\n        config,\n        region,\n        &[claimed_output.clone(), input_indices.clone()],\n        0,\n    )?;\n\n    // assert this is a subset of the input\n    dynamic_lookup(\n        config,\n        region,\n        &[input_indices, gather_input],\n        &[full_index_set, input.clone()],\n    )?;\n\n    claimed_output.reshape(input.dims())?;\n\n    Ok(claimed_output)\n}\n\n/// Sums a tensor.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::sum;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = sum::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap();\n/// let expected = 21;\n/// assert_eq!(result.get_int_evals().unwrap()[0], expected);\n/// ```\npub fn sum<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    region.flush()?;\n    // time this entire function run\n    let global_start = instant::Instant::now();\n\n    let mut values = values.clone();\n\n    // this section has been optimized to death, don't mess with it\n    let mut removal_indices = values[0].get_const_zero_indices()?;\n    removal_indices.par_sort_unstable();\n    removal_indices.dedup();\n\n    // is already sorted\n    values[0].remove_indices(&mut removal_indices, true)?;\n\n    let elapsed = global_start.elapsed();\n    trace!(\"filtering const zero indices took: {:?}\", elapsed);\n\n    // if empty return a const\n    if values[0].is_empty() {\n        return Ok(create_zero_tensor(1));\n    }\n\n    let block_width = config.custom_gates.output.num_inner_cols();\n\n    let assigned_len: usize;\n    let input = {\n        let mut input = values[0].clone();\n        input.pad_to_zero_rem(block_width, ValType::Constant(F::ZERO))?;\n        let (res, len) = region.assign_with_duplication(\n            &config.custom_gates.inputs[1],\n            &input,\n            &config.check_mode,\n            false,\n        )?;\n        assigned_len = len;\n        res.get_inner()?\n    };\n\n    // Now we can assign the dot product\n    let accumulated_sum = accumulated::sum(&input, block_width)?;\n\n    let (output, output_assigned_len) = region.assign_with_duplication(\n        &config.custom_gates.output,\n        &accumulated_sum.into(),\n        &config.check_mode,\n        true,\n    )?;\n\n    // enable the selectors\n    if !region.is_dummy() {\n        for i in 0..output_assigned_len {\n            let (x, _, z) = config\n                .custom_gates\n                .output\n                .cartesian_coord(region.linear_coord() + i * block_width);\n            // skip over duplicates at start of column\n            if z == 0 && i > 0 {\n                continue;\n            }\n            let selector = if i == 0 {\n                config.custom_gates.selectors.get(&(BaseOp::SumInit, x, 0))\n            } else {\n                config.custom_gates.selectors.get(&(BaseOp::Sum, x, 0))\n            };\n\n            region.enable(selector, z)?;\n        }\n    }\n\n    let last_elem = output.get_slice(&[output.len() - 1..output.len()])?;\n\n    region.increment(assigned_len);\n\n    // last element is the result\n    Ok(last_elem)\n}\n\n/// Takes prod of tensor's elements.\n/// # Arguments\n///\n/// * `a` - Tensor\n/// * `b` - Single value\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::prod;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = prod::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap();\n/// let expected = 0;\n/// assert_eq!(result.get_int_evals().unwrap()[0], expected);\n/// ```\npub fn prod<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    region.flush()?;\n    // time this entire function run\n    let global_start = instant::Instant::now();\n\n    // this section has been optimized to death, don't mess with it\n    let removal_indices = values[0].get_const_zero_indices()?;\n\n    let elapsed = global_start.elapsed();\n    trace!(\"finding const zero indices took: {:?}\", elapsed);\n    // if empty return a const\n    if !removal_indices.is_empty() {\n        return Ok(create_zero_tensor(1));\n    }\n\n    let block_width = config.custom_gates.output.num_inner_cols();\n    let assigned_len: usize;\n    let input = {\n        let mut input = values[0].clone();\n        input.pad_to_zero_rem(block_width, ValType::Constant(F::ONE))?;\n        let (res, len) = region.assign_with_duplication(\n            &config.custom_gates.inputs[1],\n            &input,\n            &config.check_mode,\n            false,\n        )?;\n        assigned_len = len;\n        res.get_inner()?\n    };\n\n    // Now we can assign the dot product\n    let accumulated_prod = accumulated::prod(&input, block_width)?;\n\n    let (output, output_assigned_len) = region.assign_with_duplication(\n        &config.custom_gates.output,\n        &accumulated_prod.into(),\n        &config.check_mode,\n        true,\n    )?;\n\n    // enable the selectors\n    if !region.is_dummy() {\n        (0..output_assigned_len)\n            .map(|i| {\n                let (x, _, z) = config\n                    .custom_gates\n                    .output\n                    .cartesian_coord(region.linear_coord() + i * block_width);\n                // skip over duplicates at start of column\n                if z == 0 && i > 0 {\n                    return Ok(());\n                }\n                let selector = if i == 0 {\n                    config\n                        .custom_gates\n                        .selectors\n                        .get(&(BaseOp::CumProdInit, x, 0))\n                } else {\n                    config.custom_gates.selectors.get(&(BaseOp::CumProd, x, 0))\n                };\n\n                region.enable(selector, z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    let last_elem = output.get_slice(&[output.len() - 1..output.len()])?;\n\n    region.increment(assigned_len);\n\n    // last element is the result\n    Ok(last_elem)\n}\n\n/// Axes wise op wrapper\nfn axes_wise_op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n    // generic layout op\n    op: impl Fn(\n            &BaseConfig<F>,\n            &mut RegionCtx<F>,\n            &[ValTensor<F>; 1],\n        ) -> Result<ValTensor<F>, Box<dyn Error>>\n        + Send\n        + Sync,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n\n    let a = &values[0];\n\n    if axes.is_empty() {\n        return Ok(a.clone());\n    }\n\n    let mut new_dims = vec![];\n    for i in 0..a.dims().len() {\n        if !axes.contains(&i) {\n            new_dims.push(a.dims()[i]);\n        } else {\n            new_dims.push(1);\n        }\n    }\n\n    let mut res = Tensor::new(None, &new_dims)?;\n\n    let cartesian_coord = new_dims\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| {\n        let coord = cartesian_coord[i].clone();\n        let mut prod_dims = vec![];\n        for (i, c) in coord.iter().enumerate() {\n            if axes.contains(&i) {\n                prod_dims.push(0..a.dims()[i]);\n            } else {\n                prod_dims.push(*c..*c + 1);\n            }\n        }\n        let values = a.get_slice(&prod_dims)?;\n        let op = op(config, region, &[values])?;\n\n        Ok(op.get_inner_tensor()?[0].clone())\n    };\n\n    region.apply_in_loop(&mut res, inner_loop_function)?;\n\n    Ok(res.into())\n}\n\n/// Takes product of a tensor along specific axes.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::prod_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = prod_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[60, 0]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn prod_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n    axes_wise_op(config, region, values, axes, prod)\n}\n\n/// Sums a tensor along specific axes.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::sum_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = sum_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[19, 2]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn sum_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n    axes_wise_op(config, region, values, axes, sum)\n}\n\n/// Argmax of a tensor along specific axes.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::argmax_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = argmax_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 1).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[1, 0]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn argmax_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    dim: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // these will be assigned as constants\n    let argmax =\n        move |config: &BaseConfig<F>,\n              region: &mut RegionCtx<F>,\n              values: &[ValTensor<F>; 1]|\n              -> Result<ValTensor<F>, Box<dyn Error>> { argmax(config, region, values) };\n\n    // calculate value of output\n    axes_wise_op(config, region, values, &[dim], argmax)\n}\n\n/// Max of a tensor along specific axes.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::max_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = max_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[15, 1]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn max_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n\n    axes_wise_op(config, region, values, axes, max)\n}\n\n/// Argmin of a tensor along specific axes.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::argmin_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = argmin_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 1).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[0, 2]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn argmin_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    dim: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n\n    let argmin =\n        move |config: &BaseConfig<F>,\n              region: &mut RegionCtx<F>,\n              values: &[ValTensor<F>; 1]|\n              -> Result<ValTensor<F>, Box<dyn Error>> { argmin(config, region, values) };\n\n    axes_wise_op(config, region, values, &[dim], argmin)\n}\n\n/// Mins a tensor along specific axes.\n/// # Arguments\n///\n/// * `a` - Tensor\n/// * `b` - Single value\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::min_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 15, 2, 1, 1, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = min_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[2, 0]),\n///     &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn min_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // calculate value of output\n\n    axes_wise_op(config, region, values, axes, min)\n}\n\n/// Pairwise (elementwise) op layout\npub(crate) fn pairwise<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    op: BaseOp,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // time to calculate the value of the output\n    let global_start = instant::Instant::now();\n\n    let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone());\n\n    let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?;\n\n    lhs.expand(&broadcasted_shape)?;\n    rhs.expand(&broadcasted_shape)?;\n\n    // original values\n    let orig_lhs = lhs.clone();\n    let orig_rhs = rhs.clone();\n\n    // get indices of zeros\n    let first_zero_indices = lhs.get_const_zero_indices()?;\n    let second_zero_indices = rhs.get_const_zero_indices()?;\n    let mut removal_indices = match op {\n        BaseOp::Add | BaseOp::Mult => {\n            let mut removal_indices = first_zero_indices.clone();\n            removal_indices.extend(second_zero_indices.clone());\n            removal_indices\n        }\n        BaseOp::Sub => second_zero_indices.clone(),\n        _ => return Err(Box::new(CircuitError::UnsupportedOp)),\n    };\n    removal_indices.dedup();\n\n    let removal_indices: HashSet<&usize> = HashSet::from_iter(removal_indices.iter());\n    let removal_indices_ptr = &removal_indices;\n\n    if lhs.len() != rhs.len() {\n        return Err(Box::new(CircuitError::DimMismatch(format!(\n            \"pairwise {} layout\",\n            op.as_str()\n        ))));\n    }\n\n    let mut inputs = vec![];\n    for (i, input) in [lhs.clone(), rhs.clone()].iter().enumerate() {\n        let inp = {\n            let res = region.assign_with_omissions(\n                &config.custom_gates.inputs[i],\n                input,\n                removal_indices_ptr,\n            )?;\n\n            res.get_inner()?\n        };\n\n        inputs.push(inp);\n    }\n\n    // Now we can assign the dot product\n    // time the calc\n    let start = instant::Instant::now();\n    let op_result = match op {\n        BaseOp::Add => add(&inputs),\n        BaseOp::Sub => sub(&inputs),\n        BaseOp::Mult => mult(&inputs),\n        _ => return Err(Box::new(CircuitError::UnsupportedOp)),\n    }\n    .map_err(|e| {\n        error!(\"{}\", e);\n        halo2_proofs::plonk::Error::Synthesis\n    })?;\n    let elapsed = start.elapsed();\n\n    let assigned_len = inputs[0].len() - removal_indices.len();\n    let mut output = region.assign_with_omissions(\n        &config.custom_gates.output,\n        &op_result.into(),\n        removal_indices_ptr,\n    )?;\n    trace!(\"pairwise {} calc took {:?}\", op.as_str(), elapsed);\n\n    // Enable the selectors\n    if !region.is_dummy() {\n        (0..assigned_len)\n            .map(|i| {\n                let (x, y, z) =\n                    config.custom_gates.inputs[0].cartesian_coord(region.linear_coord() + i);\n                let selector = config.custom_gates.selectors.get(&(op.clone(), x, y));\n\n                region.enable(selector, z)?;\n\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n    region.increment(assigned_len);\n\n    let a_tensor = orig_lhs.get_inner_tensor()?;\n    let b_tensor = orig_rhs.get_inner_tensor()?;\n\n    let first_zero_indices: HashSet<&usize> = HashSet::from_iter(first_zero_indices.iter());\n    let second_zero_indices: HashSet<&usize> = HashSet::from_iter(second_zero_indices.iter());\n\n    trace!(\"setting up indices took {:?}\", start.elapsed());\n\n    // infill the zero indices with the correct values from values[0] or values[1]\n    if !removal_indices_ptr.is_empty() {\n        output\n            .get_inner_tensor_mut()?\n            .par_enum_map_mut_filtered(removal_indices_ptr, |i| {\n                let val = match op {\n                    BaseOp::Add => {\n                        let a_is_null = first_zero_indices.contains(&i);\n                        let b_is_null = second_zero_indices.contains(&i);\n\n                        if a_is_null && b_is_null {\n                            ValType::Constant(F::ZERO)\n                        } else if a_is_null {\n                            b_tensor[i].clone()\n                        } else {\n                            a_tensor[i].clone()\n                        }\n                    }\n                    BaseOp::Sub => {\n                        let a_is_null = first_zero_indices.contains(&i);\n                        // by default b is null in this case for sub\n                        if a_is_null {\n                            ValType::Constant(F::ZERO)\n                        } else {\n                            a_tensor[i].clone()\n                        }\n                    }\n                    BaseOp::Mult => ValType::Constant(F::ZERO),\n                    // can safely panic as the prior check ensures this is not called\n                    _ => unreachable!(),\n                };\n                Ok::<_, TensorError>(val)\n            })?;\n    }\n\n    output.reshape(&broadcasted_shape)?;\n\n    let end = global_start.elapsed();\n    trace!(\n        \"pairwise {} layout took {:?}, row: {}\",\n        op.as_str(),\n        end,\n        region.row()\n    );\n\n    Ok(output)\n}\n\n/// Mean of squares axes\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::mean_of_squares_axes;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[2, 15, 2, 1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = mean_of_squares_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap();\n/// let expected = Tensor::<i128>::new(\n/// Some(&[78, 1]),\n/// &[2, 1],\n/// ).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn mean_of_squares_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let squared = pow(config, region, values, 2)?;\n    let sum_squared = sum_axes(config, region, &[squared], axes)?;\n\n    let dividand: usize = values[0].len() / sum_squared.len();\n\n    let mean_squared = div(config, region, &[sum_squared], F::from(dividand as u64))?;\n    Ok(mean_squared)\n}\n\n/// expand the tensor to the given shape\npub(crate) fn expand<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    shape: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut assigned_input = region.assign(&config.custom_gates.inputs[0], &values[0])?;\n    assigned_input.expand(shape)?;\n    region.increment(assigned_input.len());\n    Ok(assigned_input)\n}\n\n/// Greater than operation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::greater;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[1, 12, 6, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = greater::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 1, 1, 0, 0, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn greater<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone());\n\n    let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?;\n\n    lhs.expand(&broadcasted_shape)?;\n    rhs.expand(&broadcasted_shape)?;\n\n    let diff = pairwise(config, region, &[lhs, rhs], BaseOp::Sub)?;\n\n    nonlinearity(\n        config,\n        region,\n        &[diff],\n        &LookupOp::GreaterThan { a: utils::F32(0.) },\n    )\n}\n\n/// Greater equals than operation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::greater_equal;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[1, 12, 6, 4, 3, 2]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 4]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = greater_equal::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 0, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn greater_equal<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone());\n\n    let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?;\n\n    lhs.expand(&broadcasted_shape)?;\n    rhs.expand(&broadcasted_shape)?;\n\n    let diff = pairwise(config, region, &[lhs, rhs], BaseOp::Sub)?;\n\n    nonlinearity(\n        config,\n        region,\n        &[diff],\n        &LookupOp::GreaterThanEqual { a: utils::F32(0.) },\n    )\n}\n\n/// Less than to operation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::less;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 0, 5, 4, 5, 1]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = less::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 0, 1]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\n///\npub fn less<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // just flip the order and use greater\n    greater(config, region, &[values[1].clone(), values[0].clone()])\n}\n\n/// Less equals than operation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::less_equal;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 0, 5, 4, 5, 1]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = less_equal::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 0, 1, 1, 1]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\n///\npub fn less_equal<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // just flip the order and use greater\n    greater_equal(config, region, &[values[1].clone(), values[0].clone()])\n}\n\n/// Elementwise applies and to two tensors\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::and;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 1, 1, 1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 0, 1, 0, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = and::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 0, 1, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn and<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let a = boolean_identity(config, region, &[values[0].clone()], true)?;\n    let b = boolean_identity(config, region, &[values[1].clone()], true)?;\n\n    let res = pairwise(config, region, &[a, b], BaseOp::Mult)?;\n\n    Ok(res)\n}\n\n/// Elementwise applies or to two tensors .\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::or;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[1, 1, 1, 1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 0, 1, 0, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = or::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 1, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn or<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let a = values[0].clone();\n    let b = values[1].clone();\n\n    let b = boolean_identity(config, region, &[b], true)?;\n\n    let iff_values = &[a.clone(), a, b];\n\n    let res = iff(config, region, iff_values)?;\n\n    Ok(res)\n}\n\n/// Elementwise applies equals to two tensors .\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::equals;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 1, 1, 1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 0, 1, 0, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = equals::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 0, 1, 1]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn equals<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let diff = pairwise(config, region, values, BaseOp::Sub)?;\n    equals_zero(config, region, &[diff])\n}\n\n/// Equality boolean operation\npub(crate) fn equals_zero<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let values = values[0].clone();\n    let values_inverse = values.inverse()?;\n    let product_values_and_invert = pairwise(\n        config,\n        region,\n        &[values.clone(), values_inverse],\n        BaseOp::Mult,\n    )?;\n\n    // constant of 1\n    let ones = create_unit_tensor(1);\n    // subtract\n    let output = pairwise(\n        config,\n        region,\n        &[ones, product_values_and_invert],\n        BaseOp::Sub,\n    )?;\n\n    // take the product of diff and output\n    let prod_check = pairwise(config, region, &[values, output.clone()], BaseOp::Mult)?;\n\n    let zero_tensor = create_zero_tensor(prod_check.len());\n    enforce_equality(config, region, &[prod_check, zero_tensor])?;\n\n    Ok(output)\n}\n\n/// Elementwise applies xor to two tensors\n/// # Arguments\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::xor;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///  Some(&[1, 1, 1, 1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n/// Some(&[1, 0, 1, 0, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = xor::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 1, 0, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\n///\npub fn xor<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let lhs = values[0].clone();\n    let rhs = values[1].clone();\n\n    let lhs_not = not(config, region, &[lhs.clone()])?;\n    let rhs_not = not(config, region, &[rhs.clone()])?;\n\n    let lhs_and_rhs_not = and(config, region, &[lhs, rhs_not.clone()])?;\n    let lhs_not_and_rhs = and(config, region, &[rhs, lhs_not])?;\n\n    // we can safely use add and not OR here because we know that lhs_and_rhs_not and lhs_not_and_rhs are =1 at different incices\n    let res: ValTensor<F> = pairwise(\n        config,\n        region,\n        &[lhs_and_rhs_not, lhs_not_and_rhs],\n        BaseOp::Add,\n    )?;\n\n    Ok(res)\n}\n\n/// Elementwise applies not to a tensor .\n/// # Arguments\n/// * `a` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::not;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 1, 1, 1, 1, 0]),\n///   &[2, 3],\n/// ).unwrap());\n/// let result = not::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 1]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn not<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mask = values[0].clone();\n\n    let unit = create_unit_tensor(1);\n    let nil = create_zero_tensor(1);\n\n    let res = iff(config, region, &[mask, nil, unit])?;\n\n    Ok(res)\n}\n\n/// IFF operation.\n/// # Arguments\n/// * `mask` - Tensor of 0s and 1s\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::iff;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let mask = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[1, 0, 1, 0, 1, 0]),\n/// &[2, 3],\n/// ).unwrap());\n/// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///   Some(&[7, 8, 9, 10, 11, 12]),\n/// &[2, 3],\n/// ).unwrap());\n/// let result = iff::<Fp>(&dummy_config, &mut dummy_region, &[mask, a, b]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 8, 3, 10, 5, 12]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn iff<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 3],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // if mask > 0 then output a else output b\n    let (mask, a, b) = (&values[0], &values[1], &values[2]);\n\n    let unit = create_unit_tensor(1);\n    // make sure mask is boolean\n    let assigned_mask = boolean_identity(config, region, &[mask.clone()], true)?;\n\n    let one_minus_mask = pairwise(config, region, &[unit, assigned_mask.clone()], BaseOp::Sub)?;\n\n    let masked_a = pairwise(config, region, &[a.clone(), assigned_mask], BaseOp::Mult)?;\n\n    let masked_b = pairwise(config, region, &[b.clone(), one_minus_mask], BaseOp::Mult)?;\n\n    let res = pairwise(config, region, &[masked_a, masked_b], BaseOp::Add)?;\n\n    Ok(res)\n}\n\n/// Negates a tensor.\n/// # Arguments\n///\n/// * `a` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::neg;\n///\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = neg::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[-2, -1, -2, -1, -1, -1]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn neg<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let nil = create_zero_tensor(1);\n    pairwise(config, region, &[nil, values[0].clone()], BaseOp::Sub)\n}\n\n/// Applies sum pooling over ND tensor of shape B x C x D1 x D2 x ... x DN.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::sumpool;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 1, 3, 3],\n/// ).unwrap());\n/// let pooled = sumpool::<Fp>(&dummy_config, &mut dummy_region, &[x.clone()], &vec![(0, 0); 2], &vec![1;2], &vec![2, 2], false).unwrap();\n/// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[11, 8, 8, 10]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(pooled.get_int_evals().unwrap(), expected);\n///\n/// // This time with normalization\n/// let pooled = sumpool::<Fp>(&dummy_config, &mut dummy_region, &[x], &vec![(0, 0); 2], &vec![1;2],  &vec![2, 2], true).unwrap();\n/// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[3, 2, 2, 3]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(pooled.get_int_evals().unwrap(), expected);\n/// ```\npub fn sumpool<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>],\n    padding: &[(usize, usize)],\n    stride: &[usize],\n    kernel_shape: &[usize],\n    normalized: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let batch_size = values[0].dims()[0];\n    let image_channels = values[0].dims()[1];\n\n    let kernel_len = kernel_shape.iter().product();\n\n    let mut kernel = create_unit_tensor(kernel_len);\n    let mut kernel_dims = vec![1, 1];\n    kernel_dims.extend(kernel_shape);\n    kernel.reshape(&kernel_dims)?;\n\n    let kernel = region.assign(&config.custom_gates.inputs[1], &kernel)?;\n    region.increment(kernel.len());\n\n    let cartesian_coord = [(0..batch_size), (0..image_channels)]\n        .iter()\n        .cloned()\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let mut res = vec![];\n\n    cartesian_coord\n        .iter()\n        .map(|coord| {\n            let (b, i) = (coord[0], coord[1]);\n            let input = values[0].get_slice(&[b..b + 1, i..i + 1])?;\n            let output = conv(config, region, &[input, kernel.clone()], padding, stride)?;\n            res.push(output);\n            Ok(())\n        })\n        .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n    let shape = &res[0].dims()[2..];\n    let mut last_elem = res[1..]\n        .iter()\n        .try_fold(res[0].clone(), |acc, elem| acc.concat(elem.clone()))?;\n    last_elem.reshape(&[&[batch_size, image_channels], shape].concat())?;\n\n    if normalized {\n        last_elem = loop_div(config, region, &[last_elem], F::from(kernel_len as u64))?;\n    }\n    Ok(last_elem)\n}\n\n/// Applies  max pooling over a ND tensor of shape B x C x D1 x D2 x ... x DN.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::max_pool;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 1, 3, 3],\n/// ).unwrap());\n/// let pooled = max_pool::<Fp>(&dummy_config, &mut dummy_region, &[x], &vec![(0, 0); 2], &vec![1;2], &vec![2;2]).unwrap();\n/// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[5, 4, 4, 6]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(pooled.get_int_evals().unwrap(), expected);\n///\n/// ```\npub fn max_pool<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    padding: &[(usize, usize)],\n    stride: &[usize],\n    pool_dims: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let image = values[0].clone();\n\n    let image_dims = image.dims();\n\n    let (batch, input_channels) = (image_dims[0], image_dims[1]);\n\n    let mut padded_image = image.clone();\n    padded_image.pad(padding.to_vec(), 2)?;\n\n    let slides = image_dims[2..]\n        .iter()\n        .enumerate()\n        .map(|(i, d)| {\n            let d = padding[i].0 + d + padding[i].1;\n            d.checked_sub(pool_dims[i])\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))?\n                .checked_div(stride[i])\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))?\n                .checked_add(1)\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))\n        })\n        .collect::<Result<Vec<_>, TensorError>>()?;\n\n    let mut output_dims = vec![batch, input_channels];\n    output_dims.extend(slides);\n\n    let mut output: Tensor<ValType<F>> = Tensor::new(None, &output_dims)?;\n\n    let cartesian_coord = output_dims\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    output\n        .iter_mut()\n        .enumerate()\n        .map(|(flat_index, o)| {\n            let coord = &cartesian_coord[flat_index];\n            let (b, i) = (coord[0], coord[1]);\n\n            let mut slice = vec![b..b + 1, i..i + 1];\n            slice.extend(\n                coord[2..]\n                    .iter()\n                    .zip(stride.iter())\n                    .zip(pool_dims.iter())\n                    .map(|((c, s), k)| {\n                        let start = c * s;\n                        let end = start + k;\n                        start..end\n                    }),\n            );\n\n            let slice = padded_image.get_slice(&slice)?;\n            let max_w = max(config, region, &[slice])?;\n            *o = max_w.get_inner_tensor()?[0].clone();\n            Ok(())\n        })\n        .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n    let res: ValTensor<F> = output.into();\n\n    Ok(res)\n}\n\n/// Performs a deconvolution on the given input tensor.\n/// # Examples\n/// ```\n// // expected ouputs are taken from pytorch torch.nn.functional.conv_transpose2d\n///\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::deconv;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n/// use ezkl::tensor::ValTensor;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let c = ValTensor::from_i128_tensor(Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 2, 2, 3]).unwrap());\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n///\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, c], &vec![(1, 1); 2], &vec![1;2], &vec![2;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 32, 0, 32, 0, 6, 0, 12, 0, 4, 0, 8, 0, 4, 0, 8, 0, 0, 0, 3, 0, 0, 0, 2]), &[1, 2, 3, 4]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 1, 1, 5]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![1;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[6, 14, 4, 2, 17, 21, 0, 1, 5]), &[1, 1, 3, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 1, 1, 5]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![1;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[17]), &[1, 1, 1, 1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 1, 1, 5]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![2; 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[10, 4, 0, 3]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 1, 1, 5]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![2; 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[6, 2, 12, 4, 2, 10, 4, 20, 0, 0, 3, 1, 0, 0, 1, 5]), &[1, 1, 4, 4]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 2]),\n///     &[1, 1, 2, 1],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![2; 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 0]), &[1, 1, 2, 1]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 2]),\n///     &[1, 1, 2, 1],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![2; 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 1, 4, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n///\n/// let c = ValTensor::from_i128_tensor(Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 2, 2, 3]).unwrap());\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 4, 0, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n///\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, c], &vec![(1, 1); 2], &vec![0;2], &vec![2;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 32, 0, 0, 6, 0, 0, 4, 0, 0, 0, 0]), &[1, 2, 2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[3, 8, 0, 8, 4, 9, 8, 1, 8]),\n///     &[1, 1, 3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[1, 0, 4, 6]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[1]),\n///     &[1],\n/// ).unwrap());\n/// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(1, 1); 2], &vec![0;2], &vec![1;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[55, 58, 66, 69]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// ```\npub fn deconv<\n    F: PrimeField + TensorType + PartialOrd + std::hash::Hash + std::marker::Send + std::marker::Sync,\n>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    inputs: &[ValTensor<F>],\n    padding: &[(usize, usize)],\n    output_padding: &[usize],\n    stride: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let has_bias = inputs.len() == 3;\n    let (image, kernel) = (&inputs[0], &inputs[1]);\n\n    if stride.iter().any(|&s| s == 0) {\n        return Err(Box::new(TensorError::DimMismatch(\n            \"non-positive stride is not supported for deconv\".to_string(),\n        )));\n    }\n\n    let null_val = ValType::Constant(F::ZERO);\n\n    let mut expanded_image = image.clone();\n\n    for (i, s) in stride.iter().enumerate() {\n        expanded_image.intercalate_values(null_val.clone(), *s, 2 + i)?;\n    }\n\n    expanded_image.pad(\n        kernel.dims()[2..]\n            .iter()\n            .map(|d| (d - 1, d - 1))\n            .collect::<Vec<_>>(),\n        2,\n    )?; // pad to the kernel size\n\n    // flip order\n    let channel_coord = (0..kernel.dims()[0])\n        .cartesian_product(0..kernel.dims()[1])\n        .collect::<Vec<_>>();\n\n    let slice_coord = expanded_image\n        .dims()\n        .iter()\n        .enumerate()\n        .map(|(i, d)| {\n            if i >= 2 {\n                padding[i - 2].0..d - padding[i - 2].1 + output_padding[i - 2]\n            } else {\n                0..*d\n            }\n        })\n        .collect::<Vec<_>>();\n\n    let sliced_expanded_image = expanded_image.get_slice(&slice_coord)?;\n\n    let mut inverted_kernels = vec![];\n\n    for (i, j) in channel_coord {\n        let channel = kernel.get_slice(&[i..i + 1, j..j + 1])?;\n        let mut channel = Tensor::from(channel.get_inner_tensor()?.clone().into_iter().rev());\n        channel.reshape(&kernel.dims()[2..])?;\n        inverted_kernels.push(channel);\n    }\n\n    let mut deconv_kernel =\n        Tensor::new(Some(&inverted_kernels), &[inverted_kernels.len()])?.combine()?;\n    deconv_kernel.reshape(kernel.dims())?;\n\n    // tensorflow formatting patch\n    if kernel.dims()[0] == sliced_expanded_image.dims()[1] {\n        let mut dims = deconv_kernel.dims().to_vec();\n        dims.swap(0, 1);\n        deconv_kernel.reshape(&dims)?;\n    }\n\n    let conv_input = if has_bias {\n        vec![\n            sliced_expanded_image,\n            deconv_kernel.clone().into(),\n            inputs[2].clone(),\n        ]\n    } else {\n        vec![sliced_expanded_image, deconv_kernel.clone().into()]\n    };\n\n    let conv_dim = kernel.dims()[2..].len();\n\n    let output = conv(\n        config,\n        region,\n        &conv_input,\n        &vec![(0, 0); conv_dim],\n        &vec![1; conv_dim],\n    )?;\n\n    Ok(output)\n}\n\n/// Applies convolution over a ND tensor of shape C x H x D1...DN (and adds a bias).\n/// ```\n/// // expected ouputs are taken from pytorch torch.nn.functional.conv2d\n///\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::conv;\n/// use ezkl::tensor::val::ValTensor;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 1, 3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 1, 1, 1]),\n///     &[1, 1, 2, 2],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[0]),\n///     &[1],\n/// ).unwrap());\n/// let result = conv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[31, 16, 8, 26]), &[1, 1, 2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // Now test single channel\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6, 5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 2, 3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 1, 1, 1, 5, 2, 1, 1]),\n///     &[2, 1, 2, 2],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[1, 1]),\n///     &[2],\n/// ).unwrap());\n///\n/// let result = conv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap();\n/// let expected =  Tensor::<i128>::new(Some(&[32, 17, 9, 27, 34, 20, 13, 26]), &[1, 2, 2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n///\n/// // Now test multi channel\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6, 5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 2, 3, 3],\n/// ).unwrap());\n/// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[5, 1, 1, 1, 5, 2, 1, 1, 5, 3, 1, 1, 5, 4, 1, 1, 5, 1, 1, 1, 5, 2, 1, 1, 5, 3, 1, 1, 5, 4, 1, 1]),\n///     &[4, 2, 2, 2],\n/// ).unwrap());\n/// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[1, 1, 1, 1]),\n///     &[4],\n/// ).unwrap());\n///\n/// let result =conv(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[65, 36, 21, 52, 73, 48, 37, 48, 65, 36, 21, 52, 73, 48, 37, 48]), &[1, 4, 2, 2]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\n///\npub fn conv<\n    F: PrimeField + TensorType + PartialOrd + std::hash::Hash + std::marker::Send + std::marker::Sync,\n>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>],\n    padding: &[(usize, usize)],\n    stride: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let has_bias = values.len() == 3;\n    let (mut image, mut kernel) = (values[0].clone(), values[1].clone());\n\n    if stride.iter().any(|&s| s == 0) {\n        return Err(Box::new(TensorError::DimMismatch(\n            \"non-positive stride is not supported for conv\".to_string(),\n        )));\n    }\n\n    // we specifically want to use the same kernel and image for all the convolutions and need to enforce this by assigning them\n    // 1. assign the kernel\n    let mut assigned_len = vec![];\n\n    if !kernel.all_prev_assigned() {\n        kernel = region.assign(&config.custom_gates.inputs[0], &kernel)?;\n        assigned_len.push(kernel.len());\n    }\n    // 2. assign the image\n    if !image.all_prev_assigned() {\n        image = region.assign(&config.custom_gates.inputs[1], &image)?;\n        assigned_len.push(image.len());\n    }\n\n    if !assigned_len.is_empty() {\n        // safe to unwrap since we've just checked it has at least one element\n        region.increment(*assigned_len.iter().max().unwrap());\n    }\n\n    let image_dims = image.dims();\n    let kernel_dims = kernel.dims();\n\n    let mut padded_image = image.clone();\n    padded_image.pad(padding.to_vec(), 2)?;\n\n    let batch_size = image_dims[0];\n    let input_channels = image_dims[1];\n    let output_channels = kernel_dims[0];\n\n    log::debug!(\n        \"batch_size: {}, output_channels: {}, input_channels: {}\",\n        batch_size,\n        output_channels,\n        input_channels\n    );\n\n    let slides = image_dims[2..]\n        .iter()\n        .enumerate()\n        .map(|(i, d)| {\n            let d = padding[i].0 + d + padding[i].1;\n            d.checked_sub(kernel_dims[i + 2])\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))?\n                .checked_div(stride[i])\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))?\n                .checked_add(1)\n                .ok_or_else(|| TensorError::Overflow(\"conv\".to_string()))\n        })\n        .collect::<Result<Vec<_>, TensorError>>()?;\n\n    log::debug!(\"slides: {:?}\", slides);\n\n    let num_groups = input_channels / kernel_dims[1];\n    let input_channels_per_group = input_channels / num_groups;\n    let output_channels_per_group = output_channels / num_groups;\n\n    log::debug!(\n        \"num_groups: {}, input_channels_per_group: {}, output_channels_per_group: {}\",\n        num_groups,\n        input_channels_per_group,\n        output_channels_per_group\n    );\n\n    if output_channels_per_group == 0 {\n        return Err(Box::new(TensorError::DimMismatch(format!(\n            \"Given groups={}, expected kernel to be at least {} at dimension 0 but got {} instead\",\n            num_groups, num_groups, output_channels_per_group\n        ))));\n    }\n\n    let num_outputs =\n        batch_size * num_groups * output_channels_per_group * slides.iter().product::<usize>();\n\n    log::debug!(\"num_outputs: {}\", num_outputs);\n\n    let mut output: Tensor<ValType<F>> = Tensor::new(None, &[num_outputs])?;\n\n    let mut iterations = vec![0..batch_size, 0..num_groups, 0..output_channels_per_group];\n    for slide in slides.iter() {\n        iterations.push(0..*slide);\n    }\n\n    let cartesian_coord = iterations\n        .iter()\n        .cloned()\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let inner_loop_function = |idx: usize, region: &mut RegionCtx<F>| {\n        let cartesian_coord_per_group = &cartesian_coord[idx];\n        let (batch, group, i) = (\n            cartesian_coord_per_group[0],\n            cartesian_coord_per_group[1],\n            cartesian_coord_per_group[2],\n        );\n\n        let start_channel = group * input_channels_per_group;\n        let end_channel = start_channel + input_channels_per_group;\n\n        let mut slices = vec![batch..batch + 1, start_channel..end_channel];\n        for (i, stride) in stride.iter().enumerate() {\n            let coord = cartesian_coord_per_group[3 + i] * stride;\n            let kernel_dim = kernel_dims[2 + i];\n            slices.push(coord..(coord + kernel_dim));\n        }\n\n        let mut local_image = padded_image.get_slice(&slices)?;\n\n        local_image.flatten();\n\n        let start_kernel_index = group * output_channels_per_group + i;\n        let end_kernel_index = start_kernel_index + 1;\n        let mut local_kernel = kernel.get_slice(&[start_kernel_index..end_kernel_index])?;\n\n        local_kernel.flatten();\n\n        // this is dot product notation in einsum format\n        let mut res = einsum(config, region, &[local_image, local_kernel], \"i,i->\")?;\n\n        if has_bias {\n            let bias_index = if values[2].len() > 1 {\n                start_kernel_index\n            } else {\n                0\n            };\n\n            let bias = values[2].get_single_elem(bias_index)?;\n            res = pairwise(config, region, &[res, bias], BaseOp::Add)?;\n        }\n        region.flush()?;\n\n        Ok(res.get_inner_tensor()?[0].clone())\n    };\n\n    region.flush()?;\n    region.apply_in_loop(&mut output, inner_loop_function)?;\n\n    let reshape_output = |output: &mut Tensor<ValType<F>>| -> Result<(), TensorError> {\n        // remove dummy batch dimension if we added one\n        let mut dims = vec![batch_size, output_channels];\n        dims.extend(slides.iter().cloned());\n        output.reshape(&dims)?;\n\n        Ok(())\n    };\n\n    // remove dummy batch dimension if we added one\n    reshape_output(&mut output)?;\n\n    let output: ValTensor<_> = output.into();\n\n    Ok(output)\n}\n\n/// Power accumulated layout\npub(crate) fn pow<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    exponent: u32,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut t = values[0].clone();\n\n    for _ in 1..exponent {\n        t = pairwise(config, region, &[t, values[0].clone()], BaseOp::Mult)?;\n    }\n\n    Ok(t)\n}\n\n/// Rescaled op accumulated layout\npub(crate) fn rescale<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>],\n    scales: &[(usize, u128)],\n) -> Result<Vec<ValTensor<F>>, Box<dyn Error>> {\n    let mut rescaled_inputs = vec![];\n    for (i, ri) in values.iter().enumerate() {\n        if scales[i].1 == 1 {\n            rescaled_inputs.push(ri.clone());\n            continue;\n        }\n\n        let multiplier = create_constant_tensor(F::from(scales[i].1 as u64), 1);\n        let scaled_input = pairwise(config, region, &[ri.clone(), multiplier], BaseOp::Mult)?;\n        rescaled_inputs.push(scaled_input);\n    }\n\n    Ok(rescaled_inputs)\n}\n\n/// Dummy (no contraints) reshape layout\npub(crate) fn reshape<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    values: &[ValTensor<F>; 1],\n    new_dims: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut t = values[0].clone();\n    t.reshape(new_dims)?;\n    Ok(t)\n}\n\n/// Dummy (no contraints) move_axis layout\npub(crate) fn move_axis<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    values: &[ValTensor<F>; 1],\n    source: usize,\n    destination: usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut t = values[0].clone();\n    t.move_axis(source, destination)?;\n    Ok(t)\n}\n\n/// resize layout\npub(crate) fn resize<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    scales: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut output = region.assign(&config.custom_gates.output, &values[0])?;\n    region.increment(output.len());\n    output.resize(scales)?;\n\n    Ok(output)\n}\n\n/// Slice layout\npub(crate) fn slice<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axis: &usize,\n    start: &usize,\n    end: &usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // assigns the instance to the advice.\n    let mut output = values[0].clone();\n\n    let is_assigned = output.all_prev_assigned();\n    if !is_assigned {\n        output = region.assign(&config.custom_gates.output, &values[0])?;\n        region.increment(output.len());\n    }\n\n    output.slice(axis, start, end)?;\n\n    Ok(output)\n}\n\n/// Trilu layout\npub(crate) fn trilu<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    k: &i32,\n    upper: &bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // assigns the instance to the advice.\n    let mut output = values[0].clone();\n\n    let is_assigned = output.all_prev_assigned();\n    if !is_assigned {\n        output = region.assign(&config.custom_gates.inputs[0], &values[0])?;\n    }\n\n    let res = tensor::ops::trilu(output.get_inner_tensor()?, *k, *upper)?;\n\n    let output = region.assign(&config.custom_gates.output, &res.into())?;\n    region.increment(output.len());\n\n    Ok(output)\n}\n\n/// Concat layout\npub(crate) fn concat<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    values: &[ValTensor<F>],\n    axis: &usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let collected_inner: Result<Vec<&Tensor<_>>, _> =\n        values.iter().map(|e| e.get_inner_tensor()).collect();\n    let collected_inner = collected_inner?;\n\n    Ok(tensor::ops::concat(&collected_inner, *axis)?.into())\n}\n\n/// Identity constraint. Usually used to constrain an instance column to an advice so the returned cells / values can be operated upon.\npub(crate) fn identity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut output = values[0].clone();\n    if !output.all_prev_assigned() {\n        output = region.assign(&config.custom_gates.output, &values[0])?;\n        region.increment(output.len());\n    }\n\n    Ok(output)\n}\n\n/// Boolean identity constraint. Usually used to constrain an instance column to an advice so the returned cells / values can be operated upon.\npub(crate) fn boolean_identity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    assign: bool,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let output = if assign || !values[0].get_const_indices()?.is_empty() {\n        // get zero constants indices\n        let output = region.assign(&config.custom_gates.output, &values[0])?;\n        region.increment(output.len());\n        output\n    } else {\n        values[0].clone()\n    };\n    // Enable the selectors\n    if !region.is_dummy() {\n        (0..output.len())\n            .map(|j| {\n                let index = region.linear_coord() - j - 1;\n\n                let (x, y, z) = config.custom_gates.output.cartesian_coord(index);\n                let selector = config\n                    .custom_gates\n                    .selectors\n                    .get(&(BaseOp::IsBoolean, x, y));\n\n                region.enable(selector, z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    Ok(output)\n}\n\n/// Downsample layout\npub(crate) fn downsample<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axis: &usize,\n    stride: &usize,\n    modulo: &usize,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let input = region.assign(&config.custom_gates.inputs[0], &values[0])?;\n    let processed_output =\n        tensor::ops::downsample(input.get_inner_tensor()?, *axis, *stride, *modulo)?;\n    let output = region.assign(&config.custom_gates.output, &processed_output.into())?;\n    region.increment(std::cmp::max(input.len(), output.len()));\n    Ok(output)\n}\n\n/// layout for enforcing two sets of cells to be equal\npub(crate) fn enforce_equality<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // assert of same len\n    if values[0].len() != values[1].len() {\n        return Err(Box::new(TensorError::DimMismatch(\n            \"enforce_equality\".to_string(),\n        )));\n    }\n\n    // assigns the instance to the advice.\n    let input = region.assign(&config.custom_gates.inputs[1], &values[0])?;\n    let output = region.assign(&config.custom_gates.output, &values[1])?;\n\n    if !region.is_dummy() {\n        region.constrain_equal(&input, &output)?;\n    }\n\n    region.increment(output.len());\n\n    Ok(output)\n}\n\n/// layout for range check.\npub(crate) fn range_check<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    range: &crate::circuit::table::Range,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    region.add_used_range_check(*range)?;\n\n    // time the entire operation\n    let timer = instant::Instant::now();\n\n    let x = values[0].clone();\n\n    let w = region.assign(&config.range_checks.input, &x)?;\n\n    let assigned_len = x.len();\n\n    let is_dummy = region.is_dummy();\n\n    let table_index: ValTensor<F> = w\n        .get_inner_tensor()?\n        .par_enum_map(|_, e| {\n            Ok::<ValType<F>, TensorError>(if let Some(f) = e.get_felt_eval() {\n                let col_idx = if !is_dummy {\n                    let table = config\n                        .range_checks\n                        .ranges\n                        .get(range)\n                        .ok_or(TensorError::TableLookupError)?;\n                    table.get_col_index(f)\n                } else {\n                    F::ZERO\n                };\n                Value::known(col_idx).into()\n            } else {\n                Value::<F>::unknown().into()\n            })\n        })?\n        .into();\n\n    region.assign(&config.range_checks.index, &table_index)?;\n\n    if !is_dummy {\n        (0..assigned_len)\n            .map(|i| {\n                let (x, y, z) = config\n                    .range_checks\n                    .input\n                    .cartesian_coord(region.linear_coord() + i);\n                let selector = config.range_checks.selectors.get(&(*range, x, y));\n                region.enable(selector, z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    let is_assigned = !w.any_unknowns()?;\n    if is_assigned && region.witness_gen() {\n        // assert is within range\n        let int_values = w.get_int_evals()?;\n        for v in int_values.iter() {\n            if v < &range.0 || v > &range.1 {\n                log::error!(\"Value ({:?}) out of range: {:?}\", v, range);\n                return Err(Box::new(TensorError::TableLookupError));\n            }\n        }\n    }\n\n    region.increment(assigned_len);\n\n    let elapsed = timer.elapsed();\n    trace!(\n        \"range check {:?} layout took {:?}, row: {:?}\",\n        range,\n        elapsed,\n        region.row()\n    );\n\n    Ok(w)\n}\n\n/// layout for nonlinearity check.\npub(crate) fn nonlinearity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    nl: &LookupOp,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    region.add_used_lookup(nl.clone(), values)?;\n\n    // time the entire operation\n    let timer = instant::Instant::now();\n\n    let x = values[0].clone();\n\n    let removal_indices = values[0].get_const_indices()?;\n    let removal_indices: HashSet<&usize> = HashSet::from_iter(removal_indices.iter());\n    let removal_indices_ptr = &removal_indices;\n\n    let w = region.assign_with_omissions(&config.static_lookups.input, &x, removal_indices_ptr)?;\n\n    let output = w.get_inner_tensor()?.par_enum_map(|i, e| {\n        Ok::<_, TensorError>(if let Some(f) = e.get_felt_eval() {\n            if !removal_indices.contains(&i) {\n                Value::known(nl.f(&[Tensor::from(vec![f].into_iter())])?.output[0]).into()\n            } else {\n                ValType::Constant(nl.f(&[Tensor::from(vec![f].into_iter())])?.output[0])\n            }\n        } else {\n            Value::<F>::unknown().into()\n        })\n    })?;\n\n    let assigned_len = x.len() - removal_indices.len();\n    let mut output = region.assign_with_omissions(\n        &config.static_lookups.output,\n        &output.into(),\n        removal_indices_ptr,\n    )?;\n\n    let is_dummy = region.is_dummy();\n\n    let table_index: ValTensor<F> = w\n        .get_inner_tensor()?\n        .par_enum_map(|i, e| {\n            Ok::<_, TensorError>(if let Some(f) = e.get_felt_eval() {\n                let col_idx = if !is_dummy {\n                    let table = config\n                        .static_lookups\n                        .tables\n                        .get(nl)\n                        .ok_or(TensorError::TableLookupError)?;\n                    table.get_col_index(f)\n                } else {\n                    F::ZERO\n                };\n                if !removal_indices.contains(&i) {\n                    Value::known(col_idx).into()\n                } else {\n                    ValType::Constant(col_idx)\n                }\n            } else {\n                Value::<F>::unknown().into()\n            })\n        })?\n        .into();\n\n    region.assign_with_omissions(\n        &config.static_lookups.index,\n        &table_index,\n        removal_indices_ptr,\n    )?;\n\n    if !is_dummy {\n        (0..assigned_len)\n            .map(|i| {\n                let (x, y, z) = config\n                    .static_lookups\n                    .input\n                    .cartesian_coord(region.linear_coord() + i);\n                let selector = config.static_lookups.selectors.get(&(nl.clone(), x, y));\n                region.enable(selector, z)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n    }\n\n    region.increment(assigned_len);\n\n    output.reshape(x.dims())?;\n\n    let elapsed = timer.elapsed();\n    trace!(\n        \"nonlinearity {} layout took {:?}, row: {:?}\",\n        <LookupOp as Op<F>>::as_string(nl),\n        elapsed,\n        region.row()\n    );\n\n    // constrain the calculated output to a column\n    Ok(output)\n}\n\n/// Argmax\npub(crate) fn argmax<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // this is safe because we later constrain it\n    let argmax = values[0]\n        .get_int_evals()?\n        .into_par_iter()\n        .enumerate()\n        // we value the first index in the case of a tie\n        .max_by_key(|(idx, value)| (*value, -(*idx as i64)))\n        .map(|(idx, _)| idx as i128);\n    let argmax_val: ValTensor<F> = match argmax {\n        None => Tensor::new(Some(&[Value::<F>::unknown()]), &[1])?.into(),\n        Some(i) => Tensor::new(Some(&[Value::known(i128_to_felt::<F>(i))]), &[1])?.into(),\n    };\n\n    let assigned_argmax: ValTensor<F> =\n        region.assign(&config.custom_gates.inputs[1], &argmax_val)?;\n    region.increment(assigned_argmax.len());\n\n    let claimed_val = select(\n        config,\n        region,\n        &[values[0].clone(), assigned_argmax.clone()],\n    )?;\n\n    let max_val = max(config, region, &[values[0].clone()])?;\n\n    enforce_equality(config, region, &[claimed_val, max_val])?;\n\n    Ok(assigned_argmax)\n}\n\n/// Argmin\npub(crate) fn argmin<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // this is safe because we later constrain it\n    let argmin = values[0]\n        .get_int_evals()?\n        .into_par_iter()\n        .enumerate()\n        // we value the first index in the case of a tie\n        .min_by_key(|(idx, value)| (*value, (*idx as i64)))\n        .map(|(idx, _)| idx as i128);\n    let argmin_val: ValTensor<F> = match argmin {\n        None => Tensor::new(Some(&[Value::<F>::unknown()]), &[1])?.into(),\n        Some(i) => Tensor::new(Some(&[Value::known(i128_to_felt::<F>(i))]), &[1])?.into(),\n    };\n\n    let assigned_argmin: ValTensor<F> =\n        region.assign(&config.custom_gates.inputs[1], &argmin_val)?;\n    region.increment(assigned_argmin.len());\n\n    // these will be assigned as constants\n    let claimed_val = select(\n        config,\n        region,\n        &[values[0].clone(), assigned_argmin.clone()],\n    )?;\n    let min_val = min(config, region, &[values[0].clone()])?;\n\n    enforce_equality(config, region, &[claimed_val, min_val])?;\n\n    Ok(assigned_argmin)\n}\n\n/// max layout\npub(crate) fn max<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let input_len = values[0].len();\n    _sort_ascending(config, region, values)?.get_slice(&[input_len - 1..input_len])\n}\n\n/// min layout\npub(crate) fn min<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    _sort_ascending(config, region, values)?.get_slice(&[0..1])\n}\n\nfn multi_dim_axes_op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    axes: &[usize],\n    op: impl Fn(\n            &BaseConfig<F>,\n            &mut RegionCtx<F>,\n            &[ValTensor<F>; 1],\n        ) -> Result<ValTensor<F>, Box<dyn Error>>\n        + Send\n        + Sync,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let mut input = values[0].clone();\n\n    if !input.all_prev_assigned() {\n        input = region.assign(&config.custom_gates.inputs[0], &input)?;\n        region.increment(input.len());\n    }\n\n    if input.dims().len() == 1 {\n        return op(config, region, &[input]);\n    }\n\n    // Calculate the output tensor size\n    let input_dims = input.dims();\n\n    let mut sorted_axes = axes.to_vec();\n    // descending order\n    sorted_axes.sort_by(|x, y| y.cmp(x));\n\n    let mut output_size_without_dim = input_dims.to_vec();\n    for dim in &sorted_axes {\n        output_size_without_dim.remove(*dim);\n    }\n\n    let mut op_tensors = Tensor::<ValTensor<F>>::new(None, &output_size_without_dim)?;\n\n    // Allocate memory for the output tensor\n    let cartesian_coord = output_size_without_dim\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let inner_loop_function = |i: usize, region: &mut RegionCtx<F>| {\n        let coord = cartesian_coord[i].clone();\n        let mut slice = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n\n        for dim in &sorted_axes {\n            slice.insert(*dim, 0..input_dims[*dim]);\n        }\n\n        let mut sliced_input = input.get_slice(&slice)?;\n        sliced_input.flatten();\n\n        Ok(op(config, region, &[sliced_input])?)\n    };\n\n    region.apply_in_loop(&mut op_tensors, inner_loop_function)?;\n\n    // assert all op_tensors have the same dims\n    let sample_op_output_size = op_tensors[0].dims();\n\n    // now deduce the output size from the dims of the output tensors\n    let mut output_size = input_dims.to_vec();\n    for dim in axes.iter().enumerate() {\n        output_size[*dim.1] = sample_op_output_size[dim.0];\n    }\n\n    // Allocate memory for the output tensor\n    let cartesian_coord = output_size\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let mut output = Tensor::<ValType<F>>::new(None, &output_size)?;\n\n    output = output.par_enum_map(|i, _| {\n        let coord = cartesian_coord[i].clone();\n        let mut op_idx = coord.clone();\n        let mut coord_at_dims = vec![];\n        for dim in &sorted_axes {\n            op_idx.remove(*dim);\n        }\n        for dim in axes {\n            coord_at_dims.push(coord[*dim]);\n        }\n\n        let topk_elem = op_tensors\n            .get(&op_idx)\n            .get_inner_tensor()?\n            .get(&coord_at_dims)\n            .clone();\n\n        Ok::<_, region::RegionError>(topk_elem)\n    })?;\n\n    Ok(output.into())\n}\n\n/// softmax layout\npub(crate) fn softmax_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    input_scale: utils::F32,\n    output_scale: utils::F32,\n    axes: &[usize],\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let soft_max_at_scale = move |config: &BaseConfig<F>,\n                                  region: &mut RegionCtx<F>,\n                                  values: &[ValTensor<F>; 1]|\n          -> Result<ValTensor<F>, Box<dyn Error>> {\n        softmax(config, region, values, input_scale, output_scale)\n    };\n\n    let output = multi_dim_axes_op(config, region, values, axes, soft_max_at_scale)?;\n\n    Ok(output)\n}\n\n/// percent func\npub(crate) fn percent<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    input_scale: utils::F32,\n    output_scale: utils::F32,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    let is_assigned = values[0].all_prev_assigned();\n    let mut input = values[0].clone();\n    if !is_assigned {\n        input = region.assign(&config.custom_gates.inputs[0], &values[0])?;\n        region.increment(input.len());\n    };\n    // sum of exps\n    let denom = sum(config, region, &[input.clone()])?;\n\n    let input_felt_scale = F::from(input_scale.0 as u64);\n    let output_felt_scale = F::from(output_scale.0 as u64);\n    let inv_denom = recip(\n        config,\n        region,\n        &[denom],\n        input_felt_scale,\n        output_felt_scale,\n    )?;\n    // product of num * (1 / denom) = 2*output_scale\n    let percent = pairwise(config, region, &[input, inv_denom], BaseOp::Mult)?;\n\n    // rebase the percent to 2x the scale\n    loop_div(config, region, &[percent], input_felt_scale)\n}\n\n/// Applies softmax\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::softmax;\n/// use ezkl::tensor::val::ValTensor;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[2, 2, 3, 2, 2, 0]),\n///     &[2, 3],\n/// ).unwrap());\n/// let result = softmax::<Fp>(&dummy_config, &mut dummy_region, &[x], 128.0.into(), (128.0 * 128.0).into()).unwrap();\n/// // doubles the scale of the input\n/// let expected = Tensor::<i128>::new(Some(&[2734, 2734, 2756, 2734, 2734, 2691]), &[2, 3]).unwrap();\n/// assert_eq!(result.get_int_evals().unwrap(), expected);\n/// ```\npub fn softmax<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 1],\n    input_scale: utils::F32,\n    output_scale: utils::F32,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    // get the max then subtract it\n    let max_val = max(config, region, values)?;\n    // rebase the input to 0\n    let sub = pairwise(config, region, &[values[0].clone(), max_val], BaseOp::Sub)?;\n    // elementwise exponential\n    let ex = nonlinearity(\n        config,\n        region,\n        &[sub],\n        &LookupOp::Exp { scale: input_scale },\n    )?;\n\n    percent(config, region, &[ex.clone()], input_scale, output_scale)\n}\n\n/// Checks that the percent error between the expected public output and the actual output value\n/// is within the percent error expressed by the `tol` input, where `tol == 1.0` means the percent\n/// error tolerance is 1 percent.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::circuit::ops::layouts::range_check_percent;\n///  use ezkl::tensor::val::ValTensor;\n/// use halo2curves::bn256::Fr as Fp;\n/// use ezkl::circuit::region::RegionCtx;\n/// use ezkl::circuit::BaseConfig;\n///\n/// let dummy_config = BaseConfig::dummy(12, 2);\n/// let mut dummy_region = RegionCtx::new_dummy(0,2,true);\n///\n/// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///     Some(&[100, 200, 300, 400, 500, 600]),\n///     &[2, 3],\n/// ).unwrap());\n/// let y = ValTensor::from_i128_tensor(Tensor::<i128>::new(\n///    Some(&[101, 201, 302, 403, 503, 603]),\n///   &[2, 3],\n/// ).unwrap());\n/// let result = range_check_percent::<Fp>(&dummy_config, &mut dummy_region, &[x, y], 1024.0.into(), 1.0).unwrap();\n/// ```\npub fn range_check_percent<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n    config: &BaseConfig<F>,\n    region: &mut RegionCtx<F>,\n    values: &[ValTensor<F>; 2],\n    scale: utils::F32,\n    tol: f32,\n) -> Result<ValTensor<F>, Box<dyn Error>> {\n    if tol == 0.0 {\n        // regular equality constraint\n        return enforce_equality(config, region, values);\n    }\n\n    let mut values = [values[0].clone(), values[1].clone()];\n\n    values[0] = region.assign(&config.custom_gates.inputs[0], &values[0])?;\n    values[1] = region.assign(&config.custom_gates.inputs[1], &values[1])?;\n    let total_assigned_0 = values[0].len();\n    let total_assigned_1 = values[1].len();\n    let total_assigned = std::cmp::max(total_assigned_0, total_assigned_1);\n    region.increment(total_assigned);\n\n    // Calculate the difference between the expected output and actual output\n    let diff = pairwise(config, region, &values, BaseOp::Sub)?;\n\n    // integer scale\n    let int_scale = scale.0 as i128;\n    // felt scale\n    let felt_scale = i128_to_felt(int_scale);\n    // range check len capped at 2^(S-3) and make it divisible 2\n    let range_check_bracket = std::cmp::min(\n        utils::F32(scale.0),\n        utils::F32(2_f32.powf((F::S - 5) as f32)),\n    )\n    .0;\n\n    let range_check_bracket_int = range_check_bracket as i128;\n\n    // input scale ratio we multiply by tol such that in the new scale range_check_len represents tol percent\n    let input_scale_ratio = ((scale.0.powf(2.0) / range_check_bracket) * tol) as i128 / 2 * 2;\n\n    let recip = recip(\n        config,\n        region,\n        &[values[0].clone()],\n        felt_scale,\n        felt_scale * F::from(100),\n    )?;\n\n    log::debug!(\"recip: {}\", recip.show());\n\n    // Multiply the difference by the recip\n    let product = pairwise(config, region, &[diff, recip], BaseOp::Mult)?;\n\n    log::debug!(\"product: {}\", product.show());\n    let rebased_product = loop_div(config, region, &[product], i128_to_felt(input_scale_ratio))?;\n    log::debug!(\"rebased_product: {}\", rebased_product.show());\n\n    // check that it is within the tolerance range\n    range_check(\n        config,\n        region,\n        &[rebased_product],\n        &(-range_check_bracket_int, range_check_bracket_int),\n    )\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/lookup.rs",
        "content": "use super::*;\nuse serde::{Deserialize, Serialize};\nuse std::error::Error;\n\nuse crate::{\n    circuit::{layouts, table::Range, utils},\n    fieldutils::{felt_to_i128, i128_to_felt},\n    graph::multiplier_to_scale,\n    tensor::{self, Tensor, TensorError, TensorType},\n};\n\nuse super::Op;\nuse halo2curves::ff::PrimeField;\n\n#[allow(missing_docs)]\n/// An enum representing the operations that can be used to express more complex operations via accumulation\n#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]\npub enum LookupOp {\n    Abs,\n    Div {\n        denom: utils::F32,\n    },\n    Cast {\n        scale: utils::F32,\n    },\n    ReLU,\n    Max {\n        scale: utils::F32,\n        a: utils::F32,\n    },\n    Min {\n        scale: utils::F32,\n        a: utils::F32,\n    },\n    Ceil {\n        scale: utils::F32,\n    },\n    Floor {\n        scale: utils::F32,\n    },\n    Round {\n        scale: utils::F32,\n    },\n    RoundHalfToEven {\n        scale: utils::F32,\n    },\n    Sqrt {\n        scale: utils::F32,\n    },\n    Rsqrt {\n        scale: utils::F32,\n    },\n    Recip {\n        input_scale: utils::F32,\n        output_scale: utils::F32,\n    },\n    LeakyReLU {\n        slope: utils::F32,\n    },\n    Sigmoid {\n        scale: utils::F32,\n    },\n    Ln {\n        scale: utils::F32,\n    },\n    Exp {\n        scale: utils::F32,\n    },\n    Cos {\n        scale: utils::F32,\n    },\n    ACos {\n        scale: utils::F32,\n    },\n    Cosh {\n        scale: utils::F32,\n    },\n    ACosh {\n        scale: utils::F32,\n    },\n    Sin {\n        scale: utils::F32,\n    },\n    ASin {\n        scale: utils::F32,\n    },\n    Sinh {\n        scale: utils::F32,\n    },\n    ASinh {\n        scale: utils::F32,\n    },\n    Tan {\n        scale: utils::F32,\n    },\n    ATan {\n        scale: utils::F32,\n    },\n    Tanh {\n        scale: utils::F32,\n    },\n    ATanh {\n        scale: utils::F32,\n    },\n    Erf {\n        scale: utils::F32,\n    },\n    GreaterThan {\n        a: utils::F32,\n    },\n    LessThan {\n        a: utils::F32,\n    },\n    GreaterThanEqual {\n        a: utils::F32,\n    },\n    LessThanEqual {\n        a: utils::F32,\n    },\n    Sign,\n    KroneckerDelta,\n    Pow {\n        scale: utils::F32,\n        a: utils::F32,\n    },\n    HardSwish {\n        scale: utils::F32,\n    },\n}\n\nimpl LookupOp {\n    /// Returns the range of values that can be represented by the table\n    pub fn bit_range(max_len: usize) -> Range {\n        let range = (max_len - 1) as f64 / 2_f64;\n        let range = range as i128;\n        (-range, range)\n    }\n\n    /// Matches a [Op] to an operation in the `tensor::ops` module.\n    pub(crate) fn f<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n        &self,\n        x: &[Tensor<F>],\n    ) -> Result<ForwardResult<F>, TensorError> {\n        let x = x[0].clone().map(|x| felt_to_i128(x));\n        let res = match &self {\n            LookupOp::Abs => Ok(tensor::ops::abs(&x)?),\n            LookupOp::Ceil { scale } => Ok(tensor::ops::nonlinearities::ceil(&x, scale.into())),\n            LookupOp::Floor { scale } => Ok(tensor::ops::nonlinearities::floor(&x, scale.into())),\n            LookupOp::Round { scale } => Ok(tensor::ops::nonlinearities::round(&x, scale.into())),\n            LookupOp::RoundHalfToEven { scale } => Ok(\n                tensor::ops::nonlinearities::round_half_to_even(&x, scale.into()),\n            ),\n            LookupOp::Pow { scale, a } => Ok(tensor::ops::nonlinearities::pow(\n                &x,\n                scale.0.into(),\n                a.0.into(),\n            )),\n            LookupOp::KroneckerDelta => Ok(tensor::ops::nonlinearities::kronecker_delta(&x)),\n            LookupOp::Max { scale, a } => Ok(tensor::ops::nonlinearities::max(\n                &x,\n                scale.0.into(),\n                a.0.into(),\n            )),\n            LookupOp::Min { scale, a } => Ok(tensor::ops::nonlinearities::min(\n                &x,\n                scale.0.into(),\n                a.0.into(),\n            )),\n            LookupOp::Sign => Ok(tensor::ops::nonlinearities::sign(&x)),\n            LookupOp::LessThan { a } => Ok(tensor::ops::nonlinearities::less_than(\n                &x,\n                f32::from(*a).into(),\n            )),\n            LookupOp::LessThanEqual { a } => Ok(tensor::ops::nonlinearities::less_than_equal(\n                &x,\n                f32::from(*a).into(),\n            )),\n            LookupOp::GreaterThan { a } => Ok(tensor::ops::nonlinearities::greater_than(\n                &x,\n                f32::from(*a).into(),\n            )),\n            LookupOp::GreaterThanEqual { a } => Ok(\n                tensor::ops::nonlinearities::greater_than_equal(&x, f32::from(*a).into()),\n            ),\n            LookupOp::Div { denom } => Ok(tensor::ops::nonlinearities::const_div(\n                &x,\n                f32::from(*denom).into(),\n            )),\n            LookupOp::Cast { scale } => Ok(tensor::ops::nonlinearities::const_div(\n                &x,\n                f32::from(*scale).into(),\n            )),\n            LookupOp::Recip {\n                input_scale,\n                output_scale,\n            } => Ok(tensor::ops::nonlinearities::recip(\n                &x,\n                input_scale.into(),\n                output_scale.into(),\n            )),\n            LookupOp::ReLU => Ok(tensor::ops::nonlinearities::leakyrelu(&x, 0_f64)),\n\n            LookupOp::LeakyReLU { slope: a } => {\n                Ok(tensor::ops::nonlinearities::leakyrelu(&x, a.0.into()))\n            }\n            LookupOp::Sigmoid { scale } => {\n                Ok(tensor::ops::nonlinearities::sigmoid(&x, scale.into()))\n            }\n            LookupOp::Sqrt { scale } => Ok(tensor::ops::nonlinearities::sqrt(&x, scale.into())),\n            LookupOp::Rsqrt { scale } => Ok(tensor::ops::nonlinearities::rsqrt(&x, scale.into())),\n            LookupOp::Erf { scale } => Ok(tensor::ops::nonlinearities::erffunc(&x, scale.into())),\n            LookupOp::Exp { scale } => Ok(tensor::ops::nonlinearities::exp(&x, scale.into())),\n            LookupOp::Ln { scale } => Ok(tensor::ops::nonlinearities::ln(&x, scale.into())),\n            LookupOp::Cos { scale } => Ok(tensor::ops::nonlinearities::cos(&x, scale.into())),\n            LookupOp::ACos { scale } => Ok(tensor::ops::nonlinearities::acos(&x, scale.into())),\n            LookupOp::Cosh { scale } => Ok(tensor::ops::nonlinearities::cosh(&x, scale.into())),\n            LookupOp::ACosh { scale } => Ok(tensor::ops::nonlinearities::acosh(&x, scale.into())),\n            LookupOp::Sin { scale } => Ok(tensor::ops::nonlinearities::sin(&x, scale.into())),\n            LookupOp::ASin { scale } => Ok(tensor::ops::nonlinearities::asin(&x, scale.into())),\n            LookupOp::Sinh { scale } => Ok(tensor::ops::nonlinearities::sinh(&x, scale.into())),\n            LookupOp::ASinh { scale } => Ok(tensor::ops::nonlinearities::asinh(&x, scale.into())),\n            LookupOp::Tan { scale } => Ok(tensor::ops::nonlinearities::tan(&x, scale.into())),\n            LookupOp::ATan { scale } => Ok(tensor::ops::nonlinearities::atan(&x, scale.into())),\n            LookupOp::ATanh { scale } => Ok(tensor::ops::nonlinearities::atanh(&x, scale.into())),\n            LookupOp::Tanh { scale } => Ok(tensor::ops::nonlinearities::tanh(&x, scale.into())),\n            LookupOp::HardSwish { scale } => {\n                Ok(tensor::ops::nonlinearities::hardswish(&x, scale.into()))\n            }\n        }?;\n\n        let output = res.map(|x| i128_to_felt(x));\n\n        Ok(ForwardResult { output })\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for LookupOp {\n    /// Returns a reference to the Any trait.\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    /// Returns the name of the operation\n    fn as_string(&self) -> String {\n        match self {\n            LookupOp::Abs => \"ABS\".into(),\n            LookupOp::Ceil { scale } => format!(\"CEIL(scale={})\", scale),\n            LookupOp::Floor { scale } => format!(\"FLOOR(scale={})\", scale),\n            LookupOp::Round { scale } => format!(\"ROUND(scale={})\", scale),\n            LookupOp::RoundHalfToEven { scale } => format!(\"ROUND_HALF_TO_EVEN(scale={})\", scale),\n            LookupOp::Pow { a, scale } => format!(\"POW(scale={}, exponent={})\", scale, a),\n            LookupOp::KroneckerDelta => \"K_DELTA\".into(),\n            LookupOp::Max { scale, a } => format!(\"MAX(scale={}, a={})\", scale, a),\n            LookupOp::Min { scale, a } => format!(\"MIN(scale={}, a={})\", scale, a),\n            LookupOp::Sign => \"SIGN\".into(),\n            LookupOp::GreaterThan { a } => format!(\"GREATER_THAN(a={})\", a),\n            LookupOp::GreaterThanEqual { a } => format!(\"GREATER_THAN_EQUAL(a={})\", a),\n            LookupOp::LessThan { a } => format!(\"LESS_THAN(a={})\", a),\n            LookupOp::LessThanEqual { a } => format!(\"LESS_THAN_EQUAL(a={})\", a),\n            LookupOp::Recip {\n                input_scale,\n                output_scale,\n            } => format!(\n                \"RECIP(input_scale={}, output_scale={})\",\n                input_scale, output_scale\n            ),\n            LookupOp::Div { denom, .. } => format!(\"DIV(denom={})\", denom),\n            LookupOp::Cast { scale } => format!(\"CAST(scale={})\", scale),\n            LookupOp::Ln { scale } => format!(\"LN(scale={})\", scale),\n            LookupOp::ReLU => \"RELU\".to_string(),\n            LookupOp::LeakyReLU { slope: a } => format!(\"L_RELU(slope={})\", a),\n            LookupOp::Sigmoid { scale } => format!(\"SIGMOID(scale={})\", scale),\n            LookupOp::Sqrt { scale } => format!(\"SQRT(scale={})\", scale),\n            LookupOp::Erf { scale } => format!(\"ERF(scale={})\", scale),\n            LookupOp::Rsqrt { scale } => format!(\"RSQRT(scale={})\", scale),\n            LookupOp::Exp { scale } => format!(\"EXP(scale={})\", scale),\n            LookupOp::Tan { scale } => format!(\"TAN(scale={})\", scale),\n            LookupOp::ATan { scale } => format!(\"ATAN(scale={})\", scale),\n            LookupOp::Tanh { scale } => format!(\"TANH(scale={})\", scale),\n            LookupOp::ATanh { scale } => format!(\"ATANH(scale={})\", scale),\n            LookupOp::Cos { scale } => format!(\"COS(scale={})\", scale),\n            LookupOp::ACos { scale } => format!(\"ACOS(scale={})\", scale),\n            LookupOp::Cosh { scale } => format!(\"COSH(scale={})\", scale),\n            LookupOp::ACosh { scale } => format!(\"ACOSH(scale={})\", scale),\n            LookupOp::Sin { scale } => format!(\"SIN(scale={})\", scale),\n            LookupOp::ASin { scale } => format!(\"ASIN(scale={})\", scale),\n            LookupOp::Sinh { scale } => format!(\"SINH(scale={})\", scale),\n            LookupOp::ASinh { scale } => format!(\"ASINH(scale={})\", scale),\n            LookupOp::HardSwish { scale } => format!(\"HARDSWISH(scale={})\", scale),\n        }\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        Ok(Some(layouts::nonlinearity(\n            config,\n            region,\n            values[..].try_into()?,\n            self,\n        )?))\n    }\n\n    /// Returns the scale of the output of the operation.\n    fn out_scale(&self, inputs_scale: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        let scale = match self {\n            LookupOp::Cast { scale } => {\n                let in_scale = inputs_scale[0];\n                in_scale + multiplier_to_scale(1. / scale.0 as f64)\n            }\n            LookupOp::Recip { output_scale, .. } => multiplier_to_scale(output_scale.into()),\n            LookupOp::Sign\n            | LookupOp::GreaterThan { .. }\n            | LookupOp::LessThan { .. }\n            | LookupOp::GreaterThanEqual { .. }\n            | LookupOp::LessThanEqual { .. }\n            | LookupOp::KroneckerDelta => 0,\n            _ => inputs_scale[0],\n        };\n        Ok(scale)\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/mod.rs",
        "content": "use std::{any::Any, error::Error};\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::{\n    graph::quantize_tensor,\n    tensor::{self, Tensor, TensorType, ValTensor},\n};\nuse halo2curves::ff::PrimeField;\n\nuse self::{lookup::LookupOp, region::RegionCtx};\n\n///\npub mod base;\n///\npub mod chip;\n///\npub mod hybrid;\n/// Layouts for specific functions (composed of base ops)\npub mod layouts;\n///\npub mod lookup;\n///\npub mod poly;\n///\npub mod region;\n\n/// A struct representing the result of a forward pass.\n#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]\npub struct ForwardResult<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> {\n    pub(crate) output: Tensor<F>,\n}\n\n/// A trait representing operations that can be represented as constraints in a circuit.\npub trait Op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>:\n    std::fmt::Debug + Send + Sync + Any\n{\n    /// Returns a string representation of the operation.\n    fn as_string(&self) -> String;\n\n    /// Layouts the operation in a circuit.\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>>;\n\n    /// Returns the scale of the output of the operation.\n    fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>>;\n\n    /// Do any of the inputs to this op require homogenous input scales?\n    fn requires_homogenous_input_scales(&self) -> Vec<usize> {\n        vec![]\n    }\n\n    /// Returns true if the operation is an input.\n    fn is_input(&self) -> bool {\n        false\n    }\n\n    /// Returns true if the operation is a constant.\n    fn is_constant(&self) -> bool {\n        false\n    }\n\n    /// Boxes and clones\n    fn clone_dyn(&self) -> Box<dyn Op<F>>;\n\n    /// Returns a reference to the Any trait.\n    fn as_any(&self) -> &dyn Any;\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Clone for Box<dyn Op<F>> {\n    fn clone(&self) -> Self {\n        self.clone_dyn()\n    }\n}\n\n///\n#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]\npub enum InputType {\n    ///\n    Bool,\n    ///\n    F16,\n    ///\n    F32,\n    ///\n    F64,\n    ///\n    Int,\n    ///\n    TDim,\n}\n\nimpl InputType {\n    ///\n    pub fn is_integer(&self) -> bool {\n        matches!(self, InputType::Int | InputType::TDim | InputType::Bool)\n    }\n\n    ///\n    pub fn roundtrip<T: num::ToPrimitive + num::FromPrimitive + Clone>(&self, input: &mut T) {\n        match self {\n            InputType::Bool => {\n                let boolean_input = input.clone().to_i64().unwrap();\n                assert!(boolean_input == 0 || boolean_input == 1);\n                *input = T::from_i64(boolean_input).unwrap();\n            }\n            InputType::F16 => {\n                // TODO: implement f16\n                let f32_input = input.clone().to_f32().unwrap();\n                *input = T::from_f32(f32_input).unwrap();\n            }\n            InputType::F32 => {\n                let f32_input = input.clone().to_f32().unwrap();\n                *input = T::from_f32(f32_input).unwrap();\n            }\n            InputType::F64 => {\n                let f64_input = input.clone().to_f64().unwrap();\n                *input = T::from_f64(f64_input).unwrap();\n            }\n            InputType::Int | InputType::TDim => {\n                let int_input = input.clone().to_i128().unwrap();\n                *input = T::from_i128(int_input).unwrap();\n            }\n        }\n    }\n}\n\n///\n#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]\npub struct Input {\n    ///\n    pub scale: crate::Scale,\n    ///\n    pub datum_type: InputType,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for Input {\n    fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        Ok(self.scale)\n    }\n\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        \"Input\".into()\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        let value = values[0].clone();\n        if !value.all_prev_assigned() {\n            match self.datum_type {\n                InputType::Bool => {\n                    log::debug!(\"constraining input to be boolean\");\n                    Ok(Some(super::layouts::boolean_identity(\n                        config,\n                        region,\n                        values[..].try_into()?,\n                        true,\n                    )?))\n                }\n                _ => Ok(Some(super::layouts::identity(\n                    config,\n                    region,\n                    values[..].try_into()?,\n                )?)),\n            }\n        } else {\n            Ok(Some(value))\n        }\n    }\n\n    fn is_input(&self) -> bool {\n        true\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n\n/// An unknown operation.\n#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]\npub struct Unknown;\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for Unknown {\n    fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        Ok(0)\n    }\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        \"Unknown\".into()\n    }\n    fn layout(\n        &self,\n        _: &mut crate::circuit::BaseConfig<F>,\n        _: &mut RegionCtx<F>,\n        _: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        Err(Box::new(super::CircuitError::UnsupportedOp))\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n\n///\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct Constant<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> {\n    ///\n    pub quantized_values: Tensor<F>,\n    ///\n    pub raw_values: Tensor<f32>,\n    ///\n    #[serde(skip)]\n    pub pre_assigned_val: Option<ValTensor<F>>,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Constant<F> {\n    ///\n    pub fn new(quantized_values: Tensor<F>, raw_values: Tensor<f32>) -> Self {\n        Self {\n            quantized_values,\n            raw_values,\n            pre_assigned_val: None,\n        }\n    }\n    /// Rebase the scale of the constant\n    pub fn rebase_scale(&mut self, new_scale: crate::Scale) -> Result<(), Box<dyn Error>> {\n        let visibility = self.quantized_values.visibility().unwrap();\n        self.quantized_values = quantize_tensor(self.raw_values.clone(), new_scale, &visibility)?;\n        Ok(())\n    }\n\n    /// Empty raw value\n    pub fn empty_raw_value(&mut self) {\n        self.raw_values = Tensor::new(None, &[0]).unwrap();\n    }\n\n    ///\n    pub fn pre_assign(&mut self, val: ValTensor<F>) {\n        self.pre_assigned_val = Some(val)\n    }\n}\n\nimpl<\n        F: PrimeField\n            + TensorType\n            + PartialOrd\n            + std::hash::Hash\n            + Serialize\n            + for<'de> Deserialize<'de>,\n    > Op<F> for Constant<F>\n{\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        format!(\"CONST (scale={})\", self.quantized_values.scale().unwrap())\n    }\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        _: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        let value = if let Some(value) = &self.pre_assigned_val {\n            value.clone()\n        } else {\n            self.quantized_values.clone().try_into()?\n        };\n        // we gotta constrain it once if its used multiple times\n        Ok(Some(layouts::identity(config, region, &[value])?))\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n\n    fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        Ok(self.quantized_values.scale().unwrap())\n    }\n\n    fn is_constant(&self) -> bool {\n        true\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/poly.rs",
        "content": "use crate::{\n    circuit::layouts,\n    tensor::{self, Tensor, TensorError},\n};\n\nuse super::{base::BaseOp, *};\n\n#[allow(missing_docs)]\n/// An enum representing the operations that can be expressed as arithmetic (non lookup) operations.\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub enum PolyOp {\n    GatherElements {\n        dim: usize,\n        constant_idx: Option<Tensor<usize>>,\n    },\n    GatherND {\n        batch_dims: usize,\n        indices: Option<Tensor<usize>>,\n    },\n    ScatterElements {\n        dim: usize,\n        constant_idx: Option<Tensor<usize>>,\n    },\n    ScatterND {\n        constant_idx: Option<Tensor<usize>>,\n    },\n    MultiBroadcastTo {\n        shape: Vec<usize>,\n    },\n    Einsum {\n        equation: String,\n    },\n    Conv {\n        padding: Vec<(usize, usize)>,\n        stride: Vec<usize>,\n    },\n    Downsample {\n        axis: usize,\n        stride: usize,\n        modulo: usize,\n    },\n    DeConv {\n        padding: Vec<(usize, usize)>,\n        output_padding: Vec<usize>,\n        stride: Vec<usize>,\n    },\n    Add,\n    Sub,\n    Neg,\n    Mult,\n    Identity {\n        out_scale: Option<crate::Scale>,\n    },\n    Reshape(Vec<usize>),\n    MoveAxis {\n        source: usize,\n        destination: usize,\n    },\n    Flatten(Vec<usize>),\n    Pad(Vec<(usize, usize)>),\n    Sum {\n        axes: Vec<usize>,\n    },\n    MeanOfSquares {\n        axes: Vec<usize>,\n    },\n    Prod {\n        axes: Vec<usize>,\n        len_prod: usize,\n    },\n    Pow(u32),\n    Concat {\n        axis: usize,\n    },\n    Slice {\n        axis: usize,\n        start: usize,\n        end: usize,\n    },\n    Iff,\n    Resize {\n        scale_factor: Vec<usize>,\n    },\n    Not,\n    And,\n    Or,\n    Xor,\n    Trilu {\n        upper: bool,\n        k: i32,\n    },\n}\n\nimpl<\n        F: PrimeField\n            + TensorType\n            + PartialOrd\n            + std::hash::Hash\n            + Serialize\n            + for<'de> Deserialize<'de>,\n    > Op<F> for PolyOp\n{\n    /// Returns a reference to the Any trait.\n    fn as_any(&self) -> &dyn Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        match &self {\n            PolyOp::GatherElements { dim, constant_idx } => format!(\n                \"GATHERELEMENTS (dim={}, constant_idx{})\",\n                dim,\n                constant_idx.is_some()\n            ),\n            PolyOp::GatherND {\n                batch_dims,\n                indices,\n            } => format!(\n                \"GATHERND (batch_dims={}, constant_idx{})\",\n                batch_dims,\n                indices.is_some()\n            ),\n            PolyOp::MeanOfSquares { axes } => format!(\"MEANOFSQUARES (axes={:?})\", axes),\n            PolyOp::ScatterElements { dim, constant_idx } => format!(\n                \"SCATTERELEMENTS (dim={}, constant_idx{})\",\n                dim,\n                constant_idx.is_some()\n            ),\n            PolyOp::ScatterND { constant_idx } => {\n                format!(\"SCATTERND (constant_idx={})\", constant_idx.is_some())\n            }\n            PolyOp::MultiBroadcastTo { shape } => format!(\"MULTIBROADCASTTO (shape={:?})\", shape),\n            PolyOp::MoveAxis { .. } => \"MOVEAXIS\".into(),\n            PolyOp::Downsample { .. } => \"DOWNSAMPLE\".into(),\n            PolyOp::Resize { .. } => \"RESIZE\".into(),\n            PolyOp::Iff => \"IFF\".into(),\n            PolyOp::Einsum { equation, .. } => format!(\"EINSUM {}\", equation),\n            PolyOp::Identity { out_scale } => {\n                format!(\"IDENTITY (out_scale={:?})\", out_scale)\n            }\n            PolyOp::Reshape(shape) => format!(\"RESHAPE (shape={:?})\", shape),\n            PolyOp::Flatten(_) => \"FLATTEN\".into(),\n            PolyOp::Pad(pads) => format!(\"PAD (pads={:?})\", pads),\n            PolyOp::Add => \"ADD\".into(),\n            PolyOp::Mult => \"MULT\".into(),\n            PolyOp::Sub => \"SUB\".into(),\n            PolyOp::Sum { axes } => format!(\"SUM (axes={:?})\", axes),\n            PolyOp::Prod { .. } => \"PROD\".into(),\n            PolyOp::Pow(_) => \"POW\".into(),\n            PolyOp::Conv { stride, padding } => {\n                format!(\"CONV (stride={:?}, padding={:?})\", stride, padding)\n            }\n            PolyOp::DeConv {\n                stride,\n                padding,\n                output_padding,\n            } => {\n                format!(\n                    \"DECONV (stride={:?}, padding={:?}, output_padding={:?})\",\n                    stride, padding, output_padding\n                )\n            }\n            PolyOp::Concat { axis } => format!(\"CONCAT (axis={})\", axis),\n            PolyOp::Slice { axis, start, end } => {\n                format!(\"SLICE (axis={}, start={}, end={})\", axis, start, end)\n            }\n            PolyOp::Neg => \"NEG\".into(),\n            PolyOp::Not => \"NOT\".into(),\n            PolyOp::And => \"AND\".into(),\n            PolyOp::Or => \"OR\".into(),\n            PolyOp::Xor => \"XOR\".into(),\n            PolyOp::Trilu { upper, k } => format!(\"TRILU (upper={}, k={})\", upper, k),\n        }\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<F>,\n        region: &mut RegionCtx<F>,\n        values: &[ValTensor<F>],\n    ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> {\n        Ok(Some(match self {\n            PolyOp::MultiBroadcastTo { shape } => {\n                layouts::expand(config, region, values[..].try_into()?, shape)?\n            }\n            PolyOp::MeanOfSquares { axes } => {\n                layouts::mean_of_squares_axes(config, region, values[..].try_into()?, axes)?\n            }\n            PolyOp::Xor => layouts::xor(config, region, values[..].try_into()?)?,\n            PolyOp::Or => layouts::or(config, region, values[..].try_into()?)?,\n            PolyOp::And => layouts::and(config, region, values[..].try_into()?)?,\n            PolyOp::Not => layouts::not(config, region, values[..].try_into()?)?,\n            PolyOp::MoveAxis {\n                source,\n                destination,\n            } => layouts::move_axis(values[..].try_into()?, *source, *destination)?,\n            PolyOp::Downsample {\n                axis,\n                stride,\n                modulo,\n            } => layouts::downsample(config, region, values[..].try_into()?, axis, stride, modulo)?,\n            PolyOp::Resize { scale_factor } => {\n                layouts::resize(config, region, values[..].try_into()?, scale_factor)?\n            }\n            PolyOp::Neg => layouts::neg(config, region, values[..].try_into()?)?,\n            PolyOp::Iff => layouts::iff(config, region, values[..].try_into()?)?,\n            PolyOp::Einsum { equation } => layouts::einsum(config, region, values, equation)?,\n            PolyOp::Sum { axes } => {\n                layouts::sum_axes(config, region, values[..].try_into()?, axes)?\n            }\n            PolyOp::Prod { axes, .. } => {\n                layouts::prod_axes(config, region, values[..].try_into()?, axes)?\n            }\n            PolyOp::Conv { padding, stride } => {\n                layouts::conv(config, region, values[..].try_into()?, padding, stride)?\n            }\n            PolyOp::GatherElements { dim, constant_idx } => {\n                if let Some(idx) = constant_idx {\n                    tensor::ops::gather_elements(values[0].get_inner_tensor()?, idx, *dim)?.into()\n                } else {\n                    layouts::gather_elements(config, region, values[..].try_into()?, *dim)?.0\n                }\n            }\n            PolyOp::GatherND {\n                batch_dims,\n                indices,\n            } => {\n                if let Some(idx) = indices {\n                    tensor::ops::gather_nd(values[0].get_inner_tensor()?, idx, *batch_dims)?.into()\n                } else {\n                    layouts::gather_nd(config, region, values[..].try_into()?, *batch_dims)?.0\n                }\n            }\n            PolyOp::ScatterElements { dim, constant_idx } => {\n                if let Some(idx) = constant_idx {\n                    tensor::ops::scatter(\n                        values[0].get_inner_tensor()?,\n                        idx,\n                        values[1].get_inner_tensor()?,\n                        *dim,\n                    )?\n                    .into()\n                } else {\n                    layouts::scatter_elements(config, region, values[..].try_into()?, *dim)?\n                }\n            }\n            PolyOp::ScatterND { constant_idx } => {\n                if let Some(idx) = constant_idx {\n                    tensor::ops::scatter_nd(\n                        values[0].get_inner_tensor()?,\n                        idx,\n                        values[1].get_inner_tensor()?,\n                    )?\n                    .into()\n                } else {\n                    layouts::scatter_nd(config, region, values[..].try_into()?)?\n                }\n            }\n            PolyOp::DeConv {\n                padding,\n                output_padding,\n                stride,\n            } => layouts::deconv(\n                config,\n                region,\n                values[..].try_into()?,\n                padding,\n                output_padding,\n                stride,\n            )?,\n            PolyOp::Add => layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Add)?,\n            PolyOp::Sub => layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Sub)?,\n            PolyOp::Mult => {\n                layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Mult)?\n            }\n            PolyOp::Identity { .. } => layouts::identity(config, region, values[..].try_into()?)?,\n            PolyOp::Reshape(d) | PolyOp::Flatten(d) => layouts::reshape(values[..].try_into()?, d)?,\n            PolyOp::Pad(p) => {\n                if values.len() != 1 {\n                    return Err(Box::new(TensorError::DimError(\n                        \"Pad operation requires a single input\".to_string(),\n                    )));\n                }\n                let mut input = values[0].clone();\n                input.pad(p.clone(), 0)?;\n                input\n            }\n            PolyOp::Pow(exp) => layouts::pow(config, region, values[..].try_into()?, *exp)?,\n            PolyOp::Concat { axis } => layouts::concat(values[..].try_into()?, axis)?,\n            PolyOp::Slice { axis, start, end } => {\n                layouts::slice(config, region, values[..].try_into()?, axis, start, end)?\n            }\n            PolyOp::Trilu { upper, k } => {\n                layouts::trilu(config, region, values[..].try_into()?, k, upper)?\n            }\n        }))\n    }\n\n    fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        let scale = match self {\n            PolyOp::MeanOfSquares { .. } => 2 * in_scales[0],\n            PolyOp::Xor | PolyOp::Or | PolyOp::And | PolyOp::Not => 0,\n            PolyOp::Iff => in_scales[1],\n            PolyOp::Einsum { .. } => {\n                let mut scale = in_scales[0];\n                for s in in_scales.iter().skip(1) {\n                    scale += *s;\n                }\n                scale\n            }\n            PolyOp::Prod { len_prod, .. } => in_scales[0] * (*len_prod as crate::Scale),\n            PolyOp::Sum { .. } => in_scales[0],\n            PolyOp::Conv { .. } => {\n                let input_scale = in_scales[0];\n                let kernel_scale = in_scales[1];\n                let output_scale = input_scale + kernel_scale;\n                if in_scales.len() == 3 {\n                    let bias_scale = in_scales[2];\n                    assert_eq!(output_scale, bias_scale);\n                }\n                output_scale\n            }\n            PolyOp::DeConv { .. } => {\n                let input_scale = in_scales[0];\n                let kernel_scale = in_scales[1];\n                let output_scale = input_scale + kernel_scale;\n                if in_scales.len() == 3 {\n                    let bias_scale = in_scales[2];\n                    assert_eq!(output_scale, bias_scale);\n                }\n                output_scale\n            }\n            PolyOp::Add => {\n                let scale_a = in_scales[0];\n                let scale_b = in_scales[1];\n                assert_eq!(scale_a, scale_b);\n                scale_a\n            }\n            PolyOp::Sub => in_scales[0],\n            PolyOp::Mult => {\n                let mut scale = in_scales[0];\n                scale += in_scales[1];\n                scale\n            }\n            PolyOp::Reshape(_) | PolyOp::Flatten(_) => in_scales[0],\n            PolyOp::Pow(pow) => in_scales[0] * (*pow as crate::Scale),\n            PolyOp::Identity { out_scale } => out_scale.unwrap_or(in_scales[0]),\n            _ => in_scales[0],\n        };\n        Ok(scale)\n    }\n\n    fn requires_homogenous_input_scales(&self) -> Vec<usize> {\n        if matches!(self, PolyOp::Add { .. } | PolyOp::Sub) {\n            vec![0, 1]\n        } else if matches!(self, PolyOp::Iff) {\n            vec![1, 2]\n        } else if matches!(self, PolyOp::Concat { .. }) {\n            (0..100).collect()\n        } else if matches!(self, PolyOp::ScatterElements { .. })\n            | matches!(self, PolyOp::ScatterND { .. })\n        {\n            vec![0, 2]\n        } else {\n            vec![]\n        }\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<F>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/ops/region.rs",
        "content": "use crate::{\n    circuit::table::Range,\n    tensor::{Tensor, TensorError, TensorType, ValTensor, ValType, VarTensor},\n};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored::Colorize;\nuse halo2_proofs::{\n    circuit::Region,\n    plonk::{Error, Selector},\n};\nuse halo2curves::ff::PrimeField;\nuse portable_atomic::AtomicI128 as AtomicInt;\nuse std::{\n    cell::RefCell,\n    collections::{HashMap, HashSet},\n    sync::{\n        atomic::{AtomicUsize, Ordering},\n        Arc, Mutex,\n    },\n};\n\nuse super::lookup::LookupOp;\n\n/// Constants map\npub type ConstantsMap<F> = HashMap<F, ValType<F>>;\n\n/// Dynamic lookup index\n#[derive(Clone, Debug, Default)]\npub struct DynamicLookupIndex {\n    index: usize,\n    col_coord: usize,\n}\n\nimpl DynamicLookupIndex {\n    /// Create a new dynamic lookup index\n    pub fn new(index: usize, col_coord: usize) -> DynamicLookupIndex {\n        DynamicLookupIndex { index, col_coord }\n    }\n\n    /// Get the lookup index\n    pub fn index(&self) -> usize {\n        self.index\n    }\n\n    /// Get the column coord\n    pub fn col_coord(&self) -> usize {\n        self.col_coord\n    }\n\n    /// update with another dynamic lookup index\n    pub fn update(&mut self, other: &DynamicLookupIndex) {\n        self.index += other.index;\n        self.col_coord += other.col_coord;\n    }\n}\n\n/// Dynamic lookup index\n#[derive(Clone, Debug, Default)]\npub struct ShuffleIndex {\n    index: usize,\n    col_coord: usize,\n}\n\nimpl ShuffleIndex {\n    /// Create a new dynamic lookup index\n    pub fn new(index: usize, col_coord: usize) -> ShuffleIndex {\n        ShuffleIndex { index, col_coord }\n    }\n\n    /// Get the lookup index\n    pub fn index(&self) -> usize {\n        self.index\n    }\n\n    /// Get the column coord\n    pub fn col_coord(&self) -> usize {\n        self.col_coord\n    }\n\n    /// update with another shuffle index\n    pub fn update(&mut self, other: &ShuffleIndex) {\n        self.index += other.index;\n        self.col_coord += other.col_coord;\n    }\n}\n\n/// Region error\n#[derive(Debug, thiserror::Error)]\npub enum RegionError {\n    /// wrap other regions\n    #[error(\"Wrapped region: {0}\")]\n    Wrapped(String),\n}\n\nimpl From<String> for RegionError {\n    fn from(e: String) -> Self {\n        Self::Wrapped(e)\n    }\n}\n\nimpl From<&str> for RegionError {\n    fn from(e: &str) -> Self {\n        Self::Wrapped(e.to_string())\n    }\n}\n\nimpl From<TensorError> for RegionError {\n    fn from(e: TensorError) -> Self {\n        Self::Wrapped(format!(\"{:?}\", e))\n    }\n}\n\nimpl From<Error> for RegionError {\n    fn from(e: Error) -> Self {\n        Self::Wrapped(format!(\"{:?}\", e))\n    }\n}\n\nimpl From<Box<dyn std::error::Error>> for RegionError {\n    fn from(e: Box<dyn std::error::Error>) -> Self {\n        Self::Wrapped(format!(\"{:?}\", e))\n    }\n}\n\n#[derive(Debug)]\n/// A context for a region\npub struct RegionCtx<'a, F: PrimeField + TensorType + PartialOrd + std::hash::Hash> {\n    region: Option<RefCell<Region<'a, F>>>,\n    row: usize,\n    linear_coord: usize,\n    num_inner_cols: usize,\n    dynamic_lookup_index: DynamicLookupIndex,\n    shuffle_index: ShuffleIndex,\n    used_lookups: HashSet<LookupOp>,\n    used_range_checks: HashSet<Range>,\n    max_lookup_inputs: i128,\n    min_lookup_inputs: i128,\n    max_range_size: i128,\n    witness_gen: bool,\n    assigned_constants: ConstantsMap<F>,\n}\n\nimpl<'a, F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RegionCtx<'a, F> {\n    #[cfg(not(target_arch = \"wasm32\"))]\n    ///\n    pub fn debug_report(&self) {\n        log::debug!(\n            \"(rows={}, coord={}, constants={}, max_lookup_inputs={}, min_lookup_inputs={}, max_range_size={}, dynamic_lookup_col_coord={}, shuffle_col_coord={})\",\n            self.row().to_string().blue(),\n            self.linear_coord().to_string().yellow(),\n            self.total_constants().to_string().red(),\n            self.max_lookup_inputs().to_string().green(),\n            self.min_lookup_inputs().to_string().green(),\n            self.max_range_size().to_string().green(),\n            self.dynamic_lookup_col_coord().to_string().green(),\n            self.shuffle_col_coord().to_string().green());\n    }\n\n    ///\n    pub fn assigned_constants(&self) -> &ConstantsMap<F> {\n        &self.assigned_constants\n    }\n\n    ///\n    pub fn update_constants(&mut self, constants: ConstantsMap<F>) {\n        self.assigned_constants.extend(constants);\n    }\n\n    ///\n    pub fn increment_dynamic_lookup_index(&mut self, n: usize) {\n        self.dynamic_lookup_index.index += n;\n    }\n\n    ///\n    pub fn increment_dynamic_lookup_col_coord(&mut self, n: usize) {\n        self.dynamic_lookup_index.col_coord += n;\n    }\n\n    ///\n    pub fn increment_shuffle_index(&mut self, n: usize) {\n        self.shuffle_index.index += n;\n    }\n\n    ///\n    pub fn increment_shuffle_col_coord(&mut self, n: usize) {\n        self.shuffle_index.col_coord += n;\n    }\n\n    ///\n    pub fn witness_gen(&self) -> bool {\n        self.witness_gen\n    }\n\n    /// Create a new region context\n    pub fn new(region: Region<'a, F>, row: usize, num_inner_cols: usize) -> RegionCtx<'a, F> {\n        let region = Some(RefCell::new(region));\n        let linear_coord = row * num_inner_cols;\n\n        RegionCtx {\n            region,\n            num_inner_cols,\n            row,\n            linear_coord,\n            dynamic_lookup_index: DynamicLookupIndex::default(),\n            shuffle_index: ShuffleIndex::default(),\n            used_lookups: HashSet::new(),\n            used_range_checks: HashSet::new(),\n            max_lookup_inputs: 0,\n            min_lookup_inputs: 0,\n            max_range_size: 0,\n            witness_gen: true,\n            assigned_constants: HashMap::new(),\n        }\n    }\n\n    /// Create a new region context\n    pub fn new_with_constants(\n        region: Region<'a, F>,\n        row: usize,\n        num_inner_cols: usize,\n        constants: ConstantsMap<F>,\n    ) -> RegionCtx<'a, F> {\n        let mut new_self = Self::new(region, row, num_inner_cols);\n        new_self.assigned_constants = constants;\n        new_self\n    }\n    /// Create a new region context from a wrapped region\n    pub fn from_wrapped_region(\n        region: Option<RefCell<Region<'a, F>>>,\n        row: usize,\n        num_inner_cols: usize,\n        dynamic_lookup_index: DynamicLookupIndex,\n        shuffle_index: ShuffleIndex,\n    ) -> RegionCtx<'a, F> {\n        let linear_coord = row * num_inner_cols;\n        RegionCtx {\n            region,\n            num_inner_cols,\n            linear_coord,\n            row,\n            dynamic_lookup_index,\n            shuffle_index,\n            used_lookups: HashSet::new(),\n            used_range_checks: HashSet::new(),\n            max_lookup_inputs: 0,\n            min_lookup_inputs: 0,\n            max_range_size: 0,\n            witness_gen: false,\n            assigned_constants: HashMap::new(),\n        }\n    }\n\n    /// Create a new region context\n    pub fn new_dummy(row: usize, num_inner_cols: usize, witness_gen: bool) -> RegionCtx<'a, F> {\n        let region = None;\n        let linear_coord = row * num_inner_cols;\n\n        RegionCtx {\n            region,\n            num_inner_cols,\n            linear_coord,\n            row,\n            dynamic_lookup_index: DynamicLookupIndex::default(),\n            shuffle_index: ShuffleIndex::default(),\n            used_lookups: HashSet::new(),\n            used_range_checks: HashSet::new(),\n            max_lookup_inputs: 0,\n            min_lookup_inputs: 0,\n            max_range_size: 0,\n            witness_gen,\n            assigned_constants: HashMap::new(),\n        }\n    }\n\n    /// Create a new region context\n    pub fn new_dummy_with_linear_coord(\n        row: usize,\n        linear_coord: usize,\n        num_inner_cols: usize,\n        witness_gen: bool,\n    ) -> RegionCtx<'a, F> {\n        let region = None;\n        RegionCtx {\n            region,\n            num_inner_cols,\n            linear_coord,\n            row,\n            dynamic_lookup_index: DynamicLookupIndex::default(),\n            shuffle_index: ShuffleIndex::default(),\n            used_lookups: HashSet::new(),\n            used_range_checks: HashSet::new(),\n            max_lookup_inputs: 0,\n            min_lookup_inputs: 0,\n            max_range_size: 0,\n            witness_gen,\n            assigned_constants: HashMap::new(),\n        }\n    }\n\n    /// Apply a function in a loop to the region\n    pub fn apply_in_loop<T: TensorType + Send + Sync>(\n        &mut self,\n        output: &mut Tensor<T>,\n        inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError>\n            + Send\n            + Sync,\n    ) -> Result<(), RegionError> {\n        if self.is_dummy() {\n            self.dummy_loop(output, inner_loop_function)?;\n        } else {\n            self.real_loop(output, inner_loop_function)?;\n        }\n        Ok(())\n    }\n\n    /// Run a loop\n    pub fn real_loop<T: TensorType + Send + Sync>(\n        &mut self,\n        output: &mut Tensor<T>,\n        inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError>,\n    ) -> Result<(), RegionError> {\n        output\n            .iter_mut()\n            .enumerate()\n            .map(|(i, o)| {\n                *o = inner_loop_function(i, self)?;\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, RegionError>>()?;\n\n        Ok(())\n    }\n\n    /// Create a new region context per loop iteration\n    /// hacky but it works\n\n    pub fn dummy_loop<T: TensorType + Send + Sync>(\n        &mut self,\n        output: &mut Tensor<T>,\n        inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError>\n            + Send\n            + Sync,\n    ) -> Result<(), RegionError> {\n        let row = AtomicUsize::new(self.row());\n        let linear_coord = AtomicUsize::new(self.linear_coord());\n        let max_lookup_inputs = AtomicInt::new(self.max_lookup_inputs());\n        let min_lookup_inputs = AtomicInt::new(self.min_lookup_inputs());\n        let lookups = Arc::new(Mutex::new(self.used_lookups.clone()));\n        let range_checks = Arc::new(Mutex::new(self.used_range_checks.clone()));\n        let dynamic_lookup_index = Arc::new(Mutex::new(self.dynamic_lookup_index.clone()));\n        let shuffle_index = Arc::new(Mutex::new(self.shuffle_index.clone()));\n        let constants = Arc::new(Mutex::new(self.assigned_constants.clone()));\n\n        *output = output\n            .par_enum_map(|idx, _| {\n                // we kick off the loop with the current offset\n                let starting_offset = row.load(Ordering::SeqCst);\n                let starting_linear_coord = linear_coord.load(Ordering::SeqCst);\n                // get inner value of the locked lookups\n\n                // we need to make sure that the region is not shared between threads\n                let mut local_reg = Self::new_dummy_with_linear_coord(\n                    starting_offset,\n                    starting_linear_coord,\n                    self.num_inner_cols,\n                    self.witness_gen,\n                );\n                let res = inner_loop_function(idx, &mut local_reg);\n                // we update the offset and constants\n                row.fetch_add(local_reg.row() - starting_offset, Ordering::SeqCst);\n                linear_coord.fetch_add(\n                    local_reg.linear_coord() - starting_linear_coord,\n                    Ordering::SeqCst,\n                );\n\n                max_lookup_inputs.fetch_max(local_reg.max_lookup_inputs(), Ordering::SeqCst);\n                min_lookup_inputs.fetch_min(local_reg.min_lookup_inputs(), Ordering::SeqCst);\n                // update the lookups\n                let mut lookups = lookups.lock().unwrap();\n                lookups.extend(local_reg.used_lookups());\n                // update the range checks\n                let mut range_checks = range_checks.lock().unwrap();\n                range_checks.extend(local_reg.used_range_checks());\n                // update the dynamic lookup index\n                let mut dynamic_lookup_index = dynamic_lookup_index.lock().unwrap();\n                dynamic_lookup_index.update(&local_reg.dynamic_lookup_index);\n                // update the shuffle index\n                let mut shuffle_index = shuffle_index.lock().unwrap();\n                shuffle_index.update(&local_reg.shuffle_index);\n                // update the constants\n                let mut constants = constants.lock().unwrap();\n                constants.extend(local_reg.assigned_constants);\n\n                res\n            })\n            .map_err(|e| RegionError::from(format!(\"dummy_loop: {:?}\", e)))?;\n        self.linear_coord = linear_coord.into_inner();\n        #[allow(trivial_numeric_casts)]\n        {\n            self.max_lookup_inputs = max_lookup_inputs.into_inner();\n            self.min_lookup_inputs = min_lookup_inputs.into_inner();\n        }\n        self.row = row.into_inner();\n        self.used_lookups = Arc::try_unwrap(lookups)\n            .map_err(|e| RegionError::from(format!(\"dummy_loop: failed to get lookups: {:?}\", e)))?\n            .into_inner()\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get lookups: {:?}\", e))\n            })?;\n        self.used_range_checks = Arc::try_unwrap(range_checks)\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get range checks: {:?}\", e))\n            })?\n            .into_inner()\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get range checks: {:?}\", e))\n            })?;\n        self.dynamic_lookup_index = Arc::try_unwrap(dynamic_lookup_index)\n            .map_err(|e| {\n                RegionError::from(format!(\n                    \"dummy_loop: failed to get dynamic lookup index: {:?}\",\n                    e\n                ))\n            })?\n            .into_inner()\n            .map_err(|e| {\n                RegionError::from(format!(\n                    \"dummy_loop: failed to get dynamic lookup index: {:?}\",\n                    e\n                ))\n            })?;\n        self.shuffle_index = Arc::try_unwrap(shuffle_index)\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get shuffle index: {:?}\", e))\n            })?\n            .into_inner()\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get shuffle index: {:?}\", e))\n            })?;\n        self.assigned_constants = Arc::try_unwrap(constants)\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get constants: {:?}\", e))\n            })?\n            .into_inner()\n            .map_err(|e| {\n                RegionError::from(format!(\"dummy_loop: failed to get constants: {:?}\", e))\n            })?;\n\n        Ok(())\n    }\n\n    /// Update the max and min from inputs\n    pub fn update_max_min_lookup_inputs(\n        &mut self,\n        inputs: &[ValTensor<F>],\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        let (mut min, mut max) = (0, 0);\n        for i in inputs {\n            max = max.max(i.get_int_evals()?.into_iter().max().unwrap_or_default());\n            min = min.min(i.get_int_evals()?.into_iter().min().unwrap_or_default());\n        }\n        self.max_lookup_inputs = self.max_lookup_inputs.max(max);\n        self.min_lookup_inputs = self.min_lookup_inputs.min(min);\n        Ok(())\n    }\n\n    /// Update the max and min from inputs\n    pub fn update_max_min_lookup_range(\n        &mut self,\n        range: Range,\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        if range.0 > range.1 {\n            return Err(format!(\"update_max_min_lookup_range: invalid range {:?}\", range).into());\n        }\n\n        let range_size = (range.1 - range.0).abs();\n\n        self.max_range_size = self.max_range_size.max(range_size);\n        Ok(())\n    }\n\n    /// Check if the region is dummy\n    pub fn is_dummy(&self) -> bool {\n        self.region.is_none()\n    }\n\n    /// add used lookup\n    pub fn add_used_lookup(\n        &mut self,\n        lookup: LookupOp,\n        inputs: &[ValTensor<F>],\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        self.used_lookups.insert(lookup);\n        self.update_max_min_lookup_inputs(inputs)\n    }\n\n    /// add used range check\n    pub fn add_used_range_check(&mut self, range: Range) -> Result<(), Box<dyn std::error::Error>> {\n        self.used_range_checks.insert(range);\n        self.update_max_min_lookup_range(range)\n    }\n\n    /// Get the offset\n    pub fn row(&self) -> usize {\n        self.row\n    }\n\n    /// Linear coordinate\n    pub fn linear_coord(&self) -> usize {\n        self.linear_coord\n    }\n\n    /// Get the total number of constants\n    pub fn total_constants(&self) -> usize {\n        self.assigned_constants.len()\n    }\n\n    /// Get the dynamic lookup index\n    pub fn dynamic_lookup_index(&self) -> usize {\n        self.dynamic_lookup_index.index\n    }\n\n    /// Get the dynamic lookup column coordinate\n    pub fn dynamic_lookup_col_coord(&self) -> usize {\n        self.dynamic_lookup_index.col_coord\n    }\n\n    /// Get the shuffle index\n    pub fn shuffle_index(&self) -> usize {\n        self.shuffle_index.index\n    }\n\n    /// Get the shuffle column coordinate\n    pub fn shuffle_col_coord(&self) -> usize {\n        self.shuffle_index.col_coord\n    }\n\n    /// get used lookups\n    pub fn used_lookups(&self) -> HashSet<LookupOp> {\n        self.used_lookups.clone()\n    }\n\n    /// get used range checks\n    pub fn used_range_checks(&self) -> HashSet<Range> {\n        self.used_range_checks.clone()\n    }\n\n    /// max lookup inputs\n    pub fn max_lookup_inputs(&self) -> i128 {\n        self.max_lookup_inputs\n    }\n\n    /// min lookup inputs\n    pub fn min_lookup_inputs(&self) -> i128 {\n        self.min_lookup_inputs\n    }\n\n    /// max range check\n    pub fn max_range_size(&self) -> i128 {\n        self.max_range_size\n    }\n\n    /// Assign a valtensor to a vartensor\n    pub fn assign(\n        &mut self,\n        var: &VarTensor,\n        values: &ValTensor<F>,\n    ) -> Result<ValTensor<F>, Error> {\n        if let Some(region) = &self.region {\n            var.assign(\n                &mut region.borrow_mut(),\n                self.linear_coord,\n                values,\n                &mut self.assigned_constants,\n            )\n        } else {\n            if !values.is_instance() {\n                let values_map = values.create_constants_map_iterator();\n                self.assigned_constants.extend(values_map);\n            }\n            Ok(values.clone())\n        }\n    }\n\n    ///\n    pub fn combined_dynamic_shuffle_coord(&self) -> usize {\n        self.dynamic_lookup_col_coord() + self.shuffle_col_coord()\n    }\n\n    /// Assign a valtensor to a vartensor\n    pub fn assign_dynamic_lookup(\n        &mut self,\n        var: &VarTensor,\n        values: &ValTensor<F>,\n    ) -> Result<ValTensor<F>, Error> {\n        if let Some(region) = &self.region {\n            var.assign(\n                &mut region.borrow_mut(),\n                self.combined_dynamic_shuffle_coord(),\n                values,\n                &mut self.assigned_constants,\n            )\n        } else {\n            if !values.is_instance() {\n                let values_map = values.create_constants_map_iterator();\n                self.assigned_constants.extend(values_map);\n            }\n            Ok(values.clone())\n        }\n    }\n\n    /// Assign a valtensor to a vartensor\n    pub fn assign_shuffle(\n        &mut self,\n        var: &VarTensor,\n        values: &ValTensor<F>,\n    ) -> Result<ValTensor<F>, Error> {\n        self.assign_dynamic_lookup(var, values)\n    }\n\n    /// Assign a valtensor to a vartensor\n    pub fn assign_with_omissions(\n        &mut self,\n        var: &VarTensor,\n        values: &ValTensor<F>,\n        ommissions: &HashSet<&usize>,\n    ) -> Result<ValTensor<F>, Error> {\n        if let Some(region) = &self.region {\n            var.assign_with_omissions(\n                &mut region.borrow_mut(),\n                self.linear_coord,\n                values,\n                ommissions,\n                &mut self.assigned_constants,\n            )\n        } else {\n            let inner_tensor = values.get_inner_tensor().unwrap();\n            let mut values_map = values.create_constants_map();\n\n            for o in ommissions {\n                if let ValType::Constant(value) = inner_tensor.get_flat_index(**o) {\n                    values_map.remove(&value);\n                }\n            }\n\n            self.assigned_constants.extend(values_map);\n\n            Ok(values.clone())\n        }\n    }\n\n    /// Assign a valtensor to a vartensor with duplication\n    pub fn assign_with_duplication(\n        &mut self,\n        var: &VarTensor,\n        values: &ValTensor<F>,\n        check_mode: &crate::circuit::CheckMode,\n        single_inner_col: bool,\n    ) -> Result<(ValTensor<F>, usize), Error> {\n        if let Some(region) = &self.region {\n            // duplicates every nth element to adjust for column overflow\n            let (res, len) = var.assign_with_duplication(\n                &mut region.borrow_mut(),\n                self.row,\n                self.linear_coord,\n                values,\n                check_mode,\n                single_inner_col,\n                &mut self.assigned_constants,\n            )?;\n            Ok((res, len))\n        } else {\n            let (_, len) = var.dummy_assign_with_duplication(\n                self.row,\n                self.linear_coord,\n                values,\n                single_inner_col,\n                &mut self.assigned_constants,\n            )?;\n            Ok((values.clone(), len))\n        }\n    }\n\n    /// Enable a selector\n    pub fn enable(&mut self, selector: Option<&Selector>, offset: usize) -> Result<(), Error> {\n        match &self.region {\n            Some(region) => selector.unwrap().enable(&mut region.borrow_mut(), offset),\n            None => Ok(()),\n        }\n    }\n\n    /// constrain equal\n    pub fn constrain_equal(&mut self, a: &ValTensor<F>, b: &ValTensor<F>) -> Result<(), Error> {\n        if let Some(region) = &self.region {\n            let a = a.get_inner_tensor().unwrap();\n            let b = b.get_inner_tensor().unwrap();\n            assert_eq!(a.len(), b.len());\n            a.iter().zip(b.iter()).try_for_each(|(a, b)| {\n                let a = a.get_prev_assigned();\n                let b = b.get_prev_assigned();\n                // if they're both assigned, we can constrain them\n                if let (Some(a), Some(b)) = (&a, &b) {\n                    region.borrow_mut().constrain_equal(a.cell(), b.cell())\n                } else if a.is_some() || b.is_some() {\n                    log::error!(\n                        \"constrain_equal: one of the tensors is assigned and the other is not\"\n                    );\n                    return Err(Error::Synthesis);\n                } else {\n                    Ok(())\n                }\n            })\n        } else {\n            Ok(())\n        }\n    }\n\n    /// Increment the offset by 1\n    pub fn next(&mut self) {\n        self.linear_coord += 1;\n        if self.linear_coord % self.num_inner_cols == 0 {\n            self.row += 1;\n        }\n    }\n\n    /// Increment the offset\n    pub fn increment(&mut self, n: usize) {\n        for _ in 0..n {\n            self.next()\n        }\n    }\n\n    /// flush row to the next row\n    pub fn flush(&mut self) -> Result<(), Box<dyn std::error::Error>> {\n        // increment by the difference between the current linear coord and the next row\n        let remainder = self.linear_coord % self.num_inner_cols;\n        if remainder != 0 {\n            let diff = self.num_inner_cols - remainder;\n            self.increment(diff);\n        }\n        if self.linear_coord % self.num_inner_cols != 0 {\n            return Err(\"flush: linear coord is not aligned with the next row\".into());\n        }\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/table.rs",
        "content": "use std::{error::Error, marker::PhantomData};\n\nuse halo2curves::ff::PrimeField;\n\nuse halo2_proofs::{\n    circuit::{Layouter, Value},\n    plonk::{ConstraintSystem, Expression, TableColumn},\n};\nuse log::{debug, warn};\nuse maybe_rayon::prelude::{IntoParallelIterator, ParallelIterator};\n\nuse crate::{\n    circuit::CircuitError,\n    fieldutils::i128_to_felt,\n    tensor::{Tensor, TensorType},\n};\n\nuse crate::circuit::lookup::LookupOp;\n\n/// The range of the lookup table.\npub type Range = (i128, i128);\n\n/// The safety factor for the range of the lookup table.\npub const RANGE_MULTIPLIER: i128 = 2;\n/// The safety factor offset for the number of rows in the lookup table.\npub const RESERVED_BLINDING_ROWS_PAD: usize = 3;\n\n#[derive(Debug, Clone)]\n///\npub struct SelectorConstructor<F: PrimeField> {\n    ///\n    pub degree: usize,\n    ///\n    _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SelectorConstructor<F> {\n    ///\n    pub fn new(degree: usize) -> Self {\n        Self {\n            degree,\n            _marker: PhantomData,\n        }\n    }\n\n    ///\n    pub fn get_expr_at_idx(&self, i: usize, expr: Expression<F>) -> Expression<F> {\n        let indices = 0..self.degree;\n        indices\n            .into_par_iter()\n            .filter(|x| *x != i)\n            .map(|i| {\n                if i == 0 {\n                    expr.clone()\n                } else {\n                    (Expression::Constant(F::from(i as u64))) - expr.clone()\n                }\n            })\n            .reduce(|| Expression::Constant(F::from(1_u64)), |acc, x| acc * x)\n    }\n\n    ///\n    pub fn get_selector_val_at_idx(&self, i: usize) -> F {\n        let indices = 0..self.degree;\n        indices\n            .into_par_iter()\n            .filter(|x| *x != i)\n            .map(|x| {\n                if x == 0 {\n                    F::from(i as u64)\n                } else {\n                    F::from(x as u64) - F::from(i as u64)\n                }\n            })\n            .product()\n    }\n}\n\n/// Halo2 lookup table for element wise non-linearities.\n#[derive(Clone, Debug)]\npub struct Table<F: PrimeField> {\n    /// Non-linearity to be used in table.\n    pub nonlinearity: LookupOp,\n    /// Input to table.\n    pub table_inputs: Vec<TableColumn>,\n    /// col size\n    pub col_size: usize,\n    /// Output of table\n    pub table_outputs: Vec<TableColumn>,\n    /// selector cn\n    pub selector_constructor: SelectorConstructor<F>,\n    /// Flags if table has been previously assigned to.\n    pub is_assigned: bool,\n    /// Number of bits used in lookup table.\n    pub range: Range,\n    _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Table<F> {\n    /// get column index given input\n    pub fn get_col_index(&self, input: F) -> F {\n        //    range is split up into chunks of size col_size, find the chunk that input is in\n        let chunk =\n            (crate::fieldutils::felt_to_i128(input) - self.range.0).abs() / (self.col_size as i128);\n\n        i128_to_felt(chunk)\n    }\n\n    /// get first_element of column\n    pub fn get_first_element(&self, chunk: usize) -> (F, F) {\n        let chunk = chunk as i128;\n        // we index from 1 to prevent soundness issues\n        let first_element = i128_to_felt(chunk * (self.col_size as i128) + self.range.0);\n        let op_f = self\n            .nonlinearity\n            .f(&[Tensor::from(vec![first_element].into_iter())])\n            .unwrap();\n        (first_element, op_f.output[0])\n    }\n\n    ///\n    pub fn cal_col_size(logrows: usize, reserved_blinding_rows: usize) -> usize {\n        2usize.pow(logrows as u32) - reserved_blinding_rows\n    }\n\n    ///\n    pub fn cal_bit_range(bits: usize, reserved_blinding_rows: usize) -> usize {\n        2usize.pow(bits as u32) - reserved_blinding_rows\n    }\n}\n\n///\npub fn num_cols_required(range_len: i128, col_size: usize) -> usize {\n    // number of cols needed to store the range\n    (range_len / (col_size as i128)) as usize + 1\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Table<F> {\n    /// Configures the table.\n    pub fn configure(\n        cs: &mut ConstraintSystem<F>,\n        range: Range,\n        logrows: usize,\n        nonlinearity: &LookupOp,\n        preexisting_inputs: Option<Vec<TableColumn>>,\n    ) -> Table<F> {\n        let factors = cs.blinding_factors() + RESERVED_BLINDING_ROWS_PAD;\n        let col_size = Self::cal_col_size(logrows, factors);\n        // number of cols needed to store the range\n        let num_cols = num_cols_required((range.1 - range.0).abs(), col_size);\n\n        debug!(\"table range: {:?}\", range);\n\n        let table_inputs = preexisting_inputs.unwrap_or_else(|| {\n            let mut cols = vec![];\n            for _ in 0..num_cols {\n                cols.push(cs.lookup_table_column());\n            }\n            cols\n        });\n\n        let num_cols = table_inputs.len();\n\n        if num_cols > 1 {\n            warn!(\"Using {} columns for non-linearity table.\", num_cols);\n        }\n\n        let table_outputs = table_inputs\n            .iter()\n            .map(|_| cs.lookup_table_column())\n            .collect::<Vec<_>>();\n\n        Table {\n            nonlinearity: nonlinearity.clone(),\n            table_inputs,\n            table_outputs,\n            is_assigned: false,\n            selector_constructor: SelectorConstructor::new(num_cols),\n            col_size,\n            range,\n            _marker: PhantomData,\n        }\n    }\n\n    /// Take a linear coordinate and output the (column, row) position in the storage block.\n    pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize) {\n        let x = linear_coord / self.col_size;\n        let y = linear_coord % self.col_size;\n        (x, y)\n    }\n\n    /// Assigns values to the constraints generated when calling `configure`.\n    pub fn layout(\n        &mut self,\n        layouter: &mut impl Layouter<F>,\n        preassigned_input: bool,\n    ) -> Result<(), Box<dyn Error>> {\n        if self.is_assigned {\n            return Err(Box::new(CircuitError::TableAlreadyAssigned));\n        }\n\n        let smallest = self.range.0;\n        let largest = self.range.1;\n\n        let inputs: Tensor<F> = Tensor::from(smallest..=largest).map(|x| i128_to_felt(x));\n        let evals = self.nonlinearity.f(&[inputs.clone()])?;\n        let chunked_inputs = inputs.chunks(self.col_size);\n\n        self.is_assigned = true;\n\n        let col_multipliers: Vec<F> = (0..chunked_inputs.len())\n            .map(|x| self.selector_constructor.get_selector_val_at_idx(x))\n            .collect();\n\n        let _ = chunked_inputs\n            .enumerate()\n            .map(|(chunk_idx, inputs)| {\n                layouter.assign_table(\n                    || \"nl table\",\n                    |mut table| {\n                        let _ = inputs\n                            .iter()\n                            .enumerate()\n                            .map(|(mut row_offset, input)| {\n                                let col_multiplier = col_multipliers[chunk_idx];\n\n                                row_offset += chunk_idx * self.col_size;\n                                let (x, y) = self.cartesian_coord(row_offset);\n                                if !preassigned_input {\n                                    table.assign_cell(\n                                        || format!(\"nl_i_col row {}\", row_offset),\n                                        self.table_inputs[x],\n                                        y,\n                                        || Value::known(*input * col_multiplier),\n                                    )?;\n                                }\n\n                                let output = evals.output[row_offset];\n\n                                table.assign_cell(\n                                    || format!(\"nl_o_col row {}\", row_offset),\n                                    self.table_outputs[x],\n                                    y,\n                                    || Value::known(output * col_multiplier),\n                                )?;\n\n                                Ok(())\n                            })\n                            .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?;\n                        Ok(())\n                    },\n                )\n            })\n            .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?;\n        Ok(())\n    }\n}\n\n/// Halo2 range check column\n#[derive(Clone, Debug)]\npub struct RangeCheck<F: PrimeField> {\n    /// Input to table.\n    pub inputs: Vec<TableColumn>,\n    /// col size\n    pub col_size: usize,\n    /// selector cn\n    pub selector_constructor: SelectorConstructor<F>,\n    /// Flags if table has been previously assigned to.\n    pub is_assigned: bool,\n    /// Number of bits used in lookup table.\n    pub range: Range,\n    _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RangeCheck<F> {\n    /// get first_element of column\n    pub fn get_first_element(&self, chunk: usize) -> F {\n        let chunk = chunk as i128;\n        // we index from 1 to prevent soundness issues\n        i128_to_felt(chunk * (self.col_size as i128) + self.range.0)\n    }\n\n    ///\n    pub fn cal_col_size(logrows: usize, reserved_blinding_rows: usize) -> usize {\n        2usize.pow(logrows as u32) - reserved_blinding_rows\n    }\n\n    ///\n    pub fn cal_bit_range(bits: usize, reserved_blinding_rows: usize) -> usize {\n        2usize.pow(bits as u32) - reserved_blinding_rows\n    }\n\n    /// get column index given input\n    pub fn get_col_index(&self, input: F) -> F {\n        //    range is split up into chunks of size col_size, find the chunk that input is in\n        let chunk =\n            (crate::fieldutils::felt_to_i128(input) - self.range.0).abs() / (self.col_size as i128);\n\n        i128_to_felt(chunk)\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RangeCheck<F> {\n    /// Configures the table.\n    pub fn configure(cs: &mut ConstraintSystem<F>, range: Range, logrows: usize) -> RangeCheck<F> {\n        log::debug!(\"range check range: {:?}\", range);\n\n        let factors = cs.blinding_factors() + RESERVED_BLINDING_ROWS_PAD;\n        let col_size = Self::cal_col_size(logrows, factors);\n        // number of cols needed to store the range\n        let num_cols = num_cols_required((range.1 - range.0).abs(), col_size);\n\n        let inputs = {\n            let mut cols = vec![];\n            for _ in 0..num_cols {\n                cols.push(cs.lookup_table_column());\n            }\n            cols\n        };\n\n        let num_cols = inputs.len();\n\n        if num_cols > 1 {\n            warn!(\"Using {} columns for range-check.\", num_cols);\n        }\n\n        RangeCheck {\n            inputs,\n            col_size,\n            is_assigned: false,\n            selector_constructor: SelectorConstructor::new(num_cols),\n            range,\n            _marker: PhantomData,\n        }\n    }\n\n    /// Take a linear coordinate and output the (column, row) position in the storage block.\n    pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize) {\n        let x = linear_coord / self.col_size;\n        let y = linear_coord % self.col_size;\n        (x, y)\n    }\n\n    /// Assigns values to the constraints generated when calling `configure`.\n    pub fn layout(&mut self, layouter: &mut impl Layouter<F>) -> Result<(), Box<dyn Error>> {\n        if self.is_assigned {\n            return Err(Box::new(CircuitError::TableAlreadyAssigned));\n        }\n\n        let smallest = self.range.0;\n        let largest = self.range.1;\n\n        let inputs: Tensor<F> = Tensor::from(smallest..=largest).map(|x| i128_to_felt(x));\n        let chunked_inputs = inputs.chunks(self.col_size);\n\n        self.is_assigned = true;\n\n        let col_multipliers: Vec<F> = (0..chunked_inputs.len())\n            .map(|x| self.selector_constructor.get_selector_val_at_idx(x))\n            .collect();\n\n        let _ = chunked_inputs\n            .enumerate()\n            .map(|(chunk_idx, inputs)| {\n                layouter.assign_table(\n                    || \"range check table\",\n                    |mut table| {\n                        let _ = inputs\n                            .iter()\n                            .enumerate()\n                            .map(|(mut row_offset, input)| {\n                                let col_multiplier = col_multipliers[chunk_idx];\n\n                                row_offset += chunk_idx * self.col_size;\n                                let (x, y) = self.cartesian_coord(row_offset);\n                                table.assign_cell(\n                                    || format!(\"rc_i_col row {}\", row_offset),\n                                    self.inputs[x],\n                                    y,\n                                    || Value::known(*input * col_multiplier),\n                                )?;\n\n                                Ok(())\n                            })\n                            .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?;\n                        Ok(())\n                    },\n                )\n            })\n            .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?;\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/tests.rs",
        "content": "use crate::circuit::ops::poly::PolyOp;\nuse crate::circuit::*;\nuse crate::tensor::{Tensor, TensorType, ValTensor, VarTensor};\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    dev::MockProver,\n    plonk::{Circuit, ConstraintSystem, Error},\n};\nuse halo2curves::bn256::Fr as F;\nuse halo2curves::ff::{Field, PrimeField};\nuse ops::lookup::LookupOp;\nuse ops::region::RegionCtx;\nuse rand::rngs::OsRng;\nuse std::marker::PhantomData;\n\n#[derive(Default)]\nstruct TestParams;\n\n#[cfg(test)]\nmod matmul {\n\n    use super::*;\n\n    const K: usize = 9;\n    const LEN: usize = 3;\n\n    #[derive(Clone)]\n    struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MatmulCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"ij,jk->ik\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn matmulcircuit() {\n        // parameters\n        let mut a =\n            Tensor::from((0..(LEN + 1) * LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        a.reshape(&[LEN, LEN + 1]).unwrap();\n\n        let mut w = Tensor::from((0..LEN + 1).map(|i| Value::known(F::from((i + 1) as u64))));\n        w.reshape(&[LEN + 1, 1]).unwrap();\n\n        let circuit = MatmulCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(w)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod matmul_col_overflow_double_col {\n    use super::*;\n\n    const K: usize = 5;\n    const LEN: usize = 6;\n    const NUM_INNER_COLS: usize = 2;\n\n    #[derive(Clone)]\n    struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MatmulCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"ij,jk->ik\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn matmulcircuit() {\n        // parameters\n        let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        a.reshape(&[LEN, LEN]).unwrap();\n\n        let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        w.reshape(&[LEN, 1]).unwrap();\n\n        let circuit = MatmulCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(w)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod matmul_col_overflow {\n    use super::*;\n\n    const K: usize = 5;\n    const LEN: usize = 6;\n\n    #[derive(Clone)]\n    struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MatmulCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"ij,jk->ik\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn matmulcircuit() {\n        // parameters\n        let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        a.reshape(&[LEN, LEN]).unwrap();\n\n        let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        w.reshape(&[LEN, 1]).unwrap();\n\n        let circuit = MatmulCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(w)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\nmod matmul_col_ultra_overflow_double_col {\n\n    use halo2_proofs::poly::kzg::{\n        commitment::KZGCommitmentScheme,\n        multiopen::{ProverSHPLONK, VerifierSHPLONK},\n        strategy::SingleStrategy,\n    };\n    use snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 20;\n    const NUM_INNER_COLS: usize = 2;\n\n    #[derive(Clone)]\n    struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MatmulCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"ij,jk->ik\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn matmulcircuit() {\n        // get some logs fam\n        crate::logger::init_logger();\n        // parameters\n        let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        a.reshape(&[LEN, LEN]).unwrap();\n\n        let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        w.reshape(&[LEN, 1]).unwrap();\n\n        let circuit = MatmulCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(w)],\n            _marker: PhantomData,\n        };\n\n        let params = crate::pfsys::srs::gen_srs::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>,\n        >(K as u32);\n\n        let pk = crate::pfsys::create_keys::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>,\n            MatmulCircuit<F>,\n        >(&circuit, &params, true)\n        .unwrap();\n\n        let prover = crate::pfsys::create_proof_circuit::<\n            KZGCommitmentScheme<_>,\n            _,\n            ProverSHPLONK<_>,\n            VerifierSHPLONK<_>,\n            SingleStrategy<_>,\n            _,\n            EvmTranscript<_, _, _, _>,\n            EvmTranscript<_, _, _, _>,\n        >(\n            circuit.clone(),\n            vec![],\n            &params,\n            &pk,\n            // use safe mode to verify that the proof is correct\n            CheckMode::SAFE,\n            crate::Commitments::KZG,\n            crate::pfsys::TranscriptType::EVM,\n            None,\n            None,\n        );\n\n        assert!(prover.is_ok());\n    }\n}\n\n#[cfg(test)]\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\nmod matmul_col_ultra_overflow {\n\n    use halo2_proofs::poly::kzg::{\n        commitment::KZGCommitmentScheme,\n        multiopen::{ProverSHPLONK, VerifierSHPLONK},\n        strategy::SingleStrategy,\n    };\n    use snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 20;\n\n    #[derive(Clone)]\n    struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MatmulCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"ij,jk->ik\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn matmulcircuit() {\n        // get some logs fam\n        crate::logger::init_logger();\n        // parameters\n        let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        a.reshape(&[LEN, LEN]).unwrap();\n\n        let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64))));\n        w.reshape(&[LEN, 1]).unwrap();\n\n        let circuit = MatmulCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(w)],\n            _marker: PhantomData,\n        };\n\n        let params = crate::pfsys::srs::gen_srs::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>,\n        >(K as u32);\n\n        let pk = crate::pfsys::create_keys::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>,\n            MatmulCircuit<F>,\n        >(&circuit, &params, true)\n        .unwrap();\n\n        let prover = crate::pfsys::create_proof_circuit::<\n            KZGCommitmentScheme<_>,\n            _,\n            ProverSHPLONK<_>,\n            VerifierSHPLONK<_>,\n            SingleStrategy<_>,\n            _,\n            EvmTranscript<_, _, _, _>,\n            EvmTranscript<_, _, _, _>,\n        >(\n            circuit.clone(),\n            vec![],\n            &params,\n            &pk,\n            // use safe mode to verify that the proof is correct\n            CheckMode::SAFE,\n            crate::Commitments::KZG,\n            crate::pfsys::TranscriptType::EVM,\n            None,\n            None,\n        );\n\n        assert!(prover.is_ok());\n    }\n}\n\n#[cfg(test)]\nmod dot {\n    use ops::poly::PolyOp;\n\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn dotcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod dot_col_overflow_triple_col {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 50;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            // used for constants in the padding\n            let _fixed = cs.fixed_column();\n            cs.enable_constant(_fixed);\n\n            let a = VarTensor::new_advice(cs, K, 3, LEN);\n            let b = VarTensor::new_advice(cs, K, 3, LEN);\n            let output = VarTensor::new_advice(cs, K, 3, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 3);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn dotcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod dot_col_overflow {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 50;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn dotcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod sum {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 1],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Sum { axes: vec![0] }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn sumcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod sum_col_overflow_double_col {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 20;\n    const NUM_INNER_COLS: usize = 2;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 1],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n            let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n            let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Sum { axes: vec![0] }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn sumcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod sum_col_overflow {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 20;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 1],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Sum { axes: vec![0] }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn sumcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod composition {\n\n    use super::*;\n\n    const K: usize = 9;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            // lots of stacked dot products\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        let _ = config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .unwrap();\n                        let _ = config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .unwrap();\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs.clone(),\n                                Box::new(PolyOp::Einsum {\n                                    equation: \"i,i->\".to_string(),\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn dotcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod conv {\n\n    use super::*;\n\n    const K: usize = 22;\n    const LEN: usize = 100;\n\n    #[derive(Clone)]\n    struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: Vec<ValTensor<F>>,\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for ConvCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &self.inputs,\n                                Box::new(PolyOp::Conv {\n                                    padding: vec![(1, 1); 2],\n                                    stride: vec![2; 2],\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn convcircuit() {\n        // parameters\n        let kernel_height = 2;\n        let kernel_width = 3;\n        let image_height = 5;\n        let image_width = 7;\n        let in_channels = 3;\n        let out_channels = 2;\n\n        let mut image =\n            Tensor::from((0..in_channels * image_height * image_width).map(|_| F::random(OsRng)));\n        image\n            .reshape(&[1, in_channels, image_height, image_width])\n            .unwrap();\n        image.set_visibility(&crate::graph::Visibility::Private);\n\n        let image = ValTensor::try_from(image).unwrap();\n\n        let mut kernels = Tensor::from(\n            (0..{ out_channels * in_channels * kernel_height * kernel_width })\n                .map(|_| F::random(OsRng)),\n        );\n        kernels\n            .reshape(&[out_channels, in_channels, kernel_height, kernel_width])\n            .unwrap();\n        kernels.set_visibility(&crate::graph::Visibility::Private);\n\n        let kernels = ValTensor::try_from(kernels).unwrap();\n        let mut bias = Tensor::from((0..{ out_channels }).map(|_| F::random(OsRng)));\n        bias.set_visibility(&crate::graph::Visibility::Private);\n\n        let bias = ValTensor::try_from(bias).unwrap();\n\n        let circuit = ConvCircuit::<F> {\n            inputs: [image, kernels, bias].to_vec(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n\n    #[test]\n    fn convcircuitnobias() {\n        // parameters\n        let kernel_height = 2;\n        let kernel_width = 2;\n        let image_height = 4;\n        let image_width = 5;\n        let in_channels = 3;\n        let out_channels = 2;\n\n        let mut image =\n            Tensor::from((0..in_channels * image_height * image_width).map(|i| F::from(i as u64)));\n        image\n            .reshape(&[1, in_channels, image_height, image_width])\n            .unwrap();\n        image.set_visibility(&crate::graph::Visibility::Private);\n\n        let mut kernels = Tensor::from(\n            (0..{ out_channels * in_channels * kernel_height * kernel_width })\n                .map(|i| F::from(i as u64)),\n        );\n        kernels\n            .reshape(&[out_channels, in_channels, kernel_height, kernel_width])\n            .unwrap();\n        kernels.set_visibility(&crate::graph::Visibility::Private);\n\n        let image = ValTensor::try_from(image).unwrap();\n        let kernels = ValTensor::try_from(kernels).unwrap();\n\n        let circuit = ConvCircuit::<F> {\n            inputs: [image, kernels].to_vec(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\nmod conv_col_ultra_overflow {\n\n    use halo2_proofs::poly::{\n        kzg::strategy::SingleStrategy,\n        kzg::{\n            commitment::KZGCommitmentScheme,\n            multiopen::{ProverSHPLONK, VerifierSHPLONK},\n        },\n    };\n    use snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 28;\n\n    #[derive(Clone)]\n    struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> {\n        image: ValTensor<F>,\n        kernel: ValTensor<F>,\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for ConvCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(\n                                &mut region,\n                                &[self.image.clone(), self.kernel.clone()],\n                                Box::new(PolyOp::Conv {\n                                    padding: vec![(1, 1); 2],\n                                    stride: vec![2; 2],\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn conv_circuit() {\n        // parameters\n        let kernel_height = 2;\n        let kernel_width = 2;\n        let image_height = LEN;\n        let image_width = LEN;\n        let in_channels = 3;\n        let out_channels = 2;\n\n        // get some logs fam\n        crate::logger::init_logger();\n        let mut image =\n            Tensor::from((0..in_channels * image_height * image_width).map(|i| F::from(i as u64)));\n        image\n            .reshape(&[1, in_channels, image_height, image_width])\n            .unwrap();\n        image.set_visibility(&crate::graph::Visibility::Private);\n\n        let mut kernels = Tensor::from(\n            (0..{ out_channels * in_channels * kernel_height * kernel_width })\n                .map(|i| F::from(i as u64)),\n        );\n        kernels\n            .reshape(&[out_channels, in_channels, kernel_height, kernel_width])\n            .unwrap();\n        kernels.set_visibility(&crate::graph::Visibility::Private);\n\n        let circuit = ConvCircuit::<F> {\n            image: ValTensor::try_from(image).unwrap(),\n            kernel: ValTensor::try_from(kernels).unwrap(),\n            _marker: PhantomData,\n        };\n\n        let params = crate::pfsys::srs::gen_srs::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>,\n        >(K as u32);\n\n        let pk = crate::pfsys::create_keys::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>,\n            ConvCircuit<F>,\n        >(&circuit, &params, true)\n        .unwrap();\n\n        let prover = crate::pfsys::create_proof_circuit::<\n            KZGCommitmentScheme<_>,\n            _,\n            ProverSHPLONK<_>,\n            VerifierSHPLONK<_>,\n            SingleStrategy<_>,\n            _,\n            EvmTranscript<_, _, _, _>,\n            EvmTranscript<_, _, _, _>,\n        >(\n            circuit.clone(),\n            vec![],\n            &params,\n            &pk,\n            // use safe mode to verify that the proof is correct\n            CheckMode::SAFE,\n            crate::Commitments::KZG,\n            crate::pfsys::TranscriptType::EVM,\n            None,\n            None,\n        );\n\n        assert!(prover.is_ok());\n    }\n}\n\n#[cfg(test)]\n// not wasm 32 unknown\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\nmod conv_relu_col_ultra_overflow {\n\n    use halo2_proofs::poly::kzg::{\n        commitment::KZGCommitmentScheme,\n        multiopen::{ProverSHPLONK, VerifierSHPLONK},\n        strategy::SingleStrategy,\n    };\n    use snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 28;\n\n    #[derive(Clone)]\n    struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> {\n        image: ValTensor<F>,\n        kernel: ValTensor<F>,\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for ConvCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN);\n            let mut base_config =\n                Self::Config::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::SAFE);\n            // sets up a new relu table\n            base_config\n                .configure_lookup(cs, &b, &output, &a, (-3, 3), K, &LookupOp::ReLU)\n                .unwrap();\n            base_config.clone()\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            config.layout_tables(&mut layouter).unwrap();\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        let output = config\n                            .layout(\n                                &mut region,\n                                &[self.image.clone(), self.kernel.clone()],\n                                Box::new(PolyOp::Conv {\n                                    padding: vec![(1, 1); 2],\n                                    stride: vec![2; 2],\n                                }),\n                            )\n                            .map_err(|_| Error::Synthesis);\n                        let _output = config\n                            .layout(\n                                &mut region,\n                                &[output.unwrap().unwrap()],\n                                Box::new(LookupOp::ReLU),\n                            )\n                            .unwrap();\n                        Ok(())\n                    },\n                )\n                .unwrap();\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn conv_relu_circuit() {\n        // parameters\n        let kernel_height = 2;\n        let kernel_width = 2;\n        let image_height = LEN;\n        let image_width = LEN;\n        let in_channels = 3;\n        let out_channels = 2;\n\n        // get some logs fam\n        crate::logger::init_logger();\n        let mut image =\n            Tensor::from((0..in_channels * image_height * image_width).map(|_| F::from(0)));\n        image\n            .reshape(&[1, in_channels, image_height, image_width])\n            .unwrap();\n        image.set_visibility(&crate::graph::Visibility::Private);\n\n        let mut kernels = Tensor::from(\n            (0..{ out_channels * in_channels * kernel_height * kernel_width }).map(|_| F::from(0)),\n        );\n        kernels\n            .reshape(&[out_channels, in_channels, kernel_height, kernel_width])\n            .unwrap();\n        kernels.set_visibility(&crate::graph::Visibility::Private);\n\n        let circuit = ConvCircuit::<F> {\n            image: ValTensor::try_from(image).unwrap(),\n            kernel: ValTensor::try_from(kernels).unwrap(),\n            _marker: PhantomData,\n        };\n\n        let params = crate::pfsys::srs::gen_srs::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>,\n        >(K as u32);\n\n        let pk = crate::pfsys::create_keys::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>,\n            ConvCircuit<F>,\n        >(&circuit, &params, true)\n        .unwrap();\n\n        let prover = crate::pfsys::create_proof_circuit::<\n            KZGCommitmentScheme<_>,\n            _,\n            ProverSHPLONK<_>,\n            VerifierSHPLONK<_>,\n            SingleStrategy<_>,\n            _,\n            EvmTranscript<_, _, _, _>,\n            EvmTranscript<_, _, _, _>,\n        >(\n            circuit.clone(),\n            vec![],\n            &params,\n            &pk,\n            CheckMode::SAFE,\n            crate::Commitments::KZG,\n            crate::pfsys::TranscriptType::EVM,\n            // use safe mode to verify that the proof is correct\n            None,\n            None,\n        );\n\n        assert!(prover.is_ok());\n    }\n}\n\n#[cfg(test)]\nmod add_w_shape_casting {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn addcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..1).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod add {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn addcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod dynamic_lookup {\n    use super::*;\n\n    const K: usize = 6;\n    const LEN: usize = 4;\n    const NUM_LOOP: usize = 5;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        tables: [[ValTensor<F>; 2]; NUM_LOOP],\n        lookups: [[ValTensor<F>; 2]; NUM_LOOP],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 2, LEN);\n            let b = VarTensor::new_advice(cs, K, 2, LEN);\n            let c: VarTensor = VarTensor::new_advice(cs, K, 2, LEN);\n\n            let d = VarTensor::new_advice(cs, K, 1, LEN);\n            let e = VarTensor::new_advice(cs, K, 1, LEN);\n            let f: VarTensor = VarTensor::new_advice(cs, K, 1, LEN);\n\n            let _constant = VarTensor::constant_cols(cs, K, LEN * NUM_LOOP, false);\n\n            let mut config =\n                Self::Config::configure(cs, &[a.clone(), b.clone()], &c, CheckMode::SAFE);\n            config\n                .configure_dynamic_lookup(\n                    cs,\n                    &[a.clone(), b.clone(), c.clone()],\n                    &[d.clone(), e.clone(), f.clone()],\n                )\n                .unwrap();\n            config\n        }\n\n        fn synthesize(\n            &self,\n            config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        for i in 0..NUM_LOOP {\n                            layouts::dynamic_lookup(\n                                &config,\n                                &mut region,\n                                &self.lookups[i],\n                                &self.tables[i],\n                            )\n                            .map_err(|_| Error::Synthesis)?;\n                        }\n                        assert_eq!(\n                            region.dynamic_lookup_col_coord(),\n                            NUM_LOOP * self.tables[0][0].len()\n                        );\n                        assert_eq!(region.dynamic_lookup_index(), NUM_LOOP);\n\n                        Ok(())\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn dynamiclookupcircuit() {\n        // parameters\n        let tables = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                [\n                    ValTensor::from(Tensor::from(\n                        (0..LEN).map(|i| Value::known(F::from((i * loop_idx) as u64 + 1))),\n                    )),\n                    ValTensor::from(Tensor::from(\n                        (0..LEN).map(|i| Value::known(F::from((loop_idx * i * i) as u64 + 1))),\n                    )),\n                ]\n            })\n            .collect::<Vec<_>>();\n\n        let lookups = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                [\n                    ValTensor::from(Tensor::from(\n                        (0..3).map(|i| Value::known(F::from((i * loop_idx) as u64 + 1))),\n                    )),\n                    ValTensor::from(Tensor::from(\n                        (0..3).map(|i| Value::known(F::from((loop_idx * i * i) as u64 + 1))),\n                    )),\n                ]\n            })\n            .collect::<Vec<_>>();\n\n        let circuit = MyCircuit::<F> {\n            tables: tables.clone().try_into().unwrap(),\n            lookups: lookups.try_into().unwrap(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n\n        let lookups = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                let prev_idx = if loop_idx == 0 {\n                    NUM_LOOP - 1\n                } else {\n                    loop_idx - 1\n                };\n                [\n                    ValTensor::from(Tensor::from(\n                        (0..3).map(|i| Value::known(F::from((i * prev_idx) as u64 + 1))),\n                    )),\n                    ValTensor::from(Tensor::from(\n                        (0..3).map(|i| Value::known(F::from((prev_idx * i * i) as u64 + 1))),\n                    )),\n                ]\n            })\n            .collect::<Vec<_>>();\n\n        let circuit = MyCircuit::<F> {\n            tables: tables.try_into().unwrap(),\n            lookups: lookups.try_into().unwrap(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        assert!(prover.verify().is_err());\n    }\n}\n\n#[cfg(test)]\nmod shuffle {\n    use super::*;\n\n    const K: usize = 6;\n    const LEN: usize = 4;\n    const NUM_LOOP: usize = 5;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [[ValTensor<F>; 1]; NUM_LOOP],\n        references: [[ValTensor<F>; 1]; NUM_LOOP],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 2, LEN);\n            let b = VarTensor::new_advice(cs, K, 2, LEN);\n            let c: VarTensor = VarTensor::new_advice(cs, K, 2, LEN);\n\n            let d = VarTensor::new_advice(cs, K, 1, LEN);\n            let e = VarTensor::new_advice(cs, K, 1, LEN);\n\n            let _constant = VarTensor::constant_cols(cs, K, LEN * NUM_LOOP, false);\n\n            let mut config =\n                Self::Config::configure(cs, &[a.clone(), b.clone()], &c, CheckMode::SAFE);\n            config\n                .configure_shuffles(cs, &[a.clone(), b.clone()], &[d.clone(), e.clone()])\n                .unwrap();\n            config\n        }\n\n        fn synthesize(\n            &self,\n            config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        for i in 0..NUM_LOOP {\n                            layouts::shuffles(\n                                &config,\n                                &mut region,\n                                &self.inputs[i],\n                                &self.references[i],\n                            )\n                            .map_err(|_| Error::Synthesis)?;\n                        }\n                        assert_eq!(\n                            region.shuffle_col_coord(),\n                            NUM_LOOP * self.references[0][0].len()\n                        );\n                        assert_eq!(region.shuffle_index(), NUM_LOOP);\n\n                        Ok(())\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn shufflecircuit() {\n        // parameters\n        let references = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                [ValTensor::from(Tensor::from((0..LEN).map(|i| {\n                    Value::known(F::from((i * loop_idx) as u64 + 1))\n                })))]\n            })\n            .collect::<Vec<_>>();\n\n        let inputs = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                [ValTensor::from(Tensor::from((0..LEN).rev().map(|i| {\n                    Value::known(F::from((i * loop_idx) as u64 + 1))\n                })))]\n            })\n            .collect::<Vec<_>>();\n\n        let circuit = MyCircuit::<F> {\n            references: references.clone().try_into().unwrap(),\n            inputs: inputs.try_into().unwrap(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n\n        let inputs = (0..NUM_LOOP)\n            .map(|loop_idx| {\n                let prev_idx = if loop_idx == 0 {\n                    NUM_LOOP - 1\n                } else {\n                    loop_idx - 1\n                };\n                [ValTensor::from(Tensor::from((0..LEN).rev().map(|i| {\n                    Value::known(F::from((i * prev_idx) as u64 + 1))\n                })))]\n            })\n            .collect::<Vec<_>>();\n\n        let circuit = MyCircuit::<F> {\n            references: references.try_into().unwrap(),\n            inputs: inputs.try_into().unwrap(),\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        assert!(prover.verify().is_err());\n    }\n}\n\n#[cfg(test)]\nmod add_with_overflow {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 50;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn addcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod add_with_overflow_and_poseidon {\n    use std::collections::HashMap;\n\n    use halo2curves::bn256::Fr;\n\n    use crate::circuit::modules::{\n        poseidon::{\n            spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH},\n            PoseidonChip, PoseidonConfig,\n        },\n        Module, ModulePlanner,\n    };\n\n    use super::*;\n\n    const K: usize = 15;\n    const LEN: usize = 50;\n    const WIDTH: usize = POSEIDON_WIDTH;\n    const RATE: usize = POSEIDON_RATE;\n\n    #[derive(Debug, Clone)]\n    struct MyCircuitConfig {\n        base: BaseConfig<Fr>,\n        poseidon: PoseidonConfig<WIDTH, RATE>,\n    }\n\n    #[derive(Clone)]\n    struct MyCircuit {\n        inputs: [ValTensor<Fr>; 2],\n    }\n\n    impl Circuit<Fr> for MyCircuit {\n        type Config = MyCircuitConfig;\n        type FloorPlanner = ModulePlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            let base = BaseConfig::configure(cs, &[a, b], &output, CheckMode::SAFE);\n            VarTensor::constant_cols(cs, K, 2, false);\n\n            let poseidon = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::configure(cs, ());\n\n            MyCircuitConfig { base, poseidon }\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<Fr>,\n        ) -> Result<(), Error> {\n            let poseidon_chip: PoseidonChip<PoseidonSpec, WIDTH, RATE, WIDTH> =\n                PoseidonChip::new(config.poseidon.clone());\n\n            let assigned_inputs_a =\n                poseidon_chip.layout(&mut layouter, &self.inputs[0..1], 0, &mut HashMap::new())?;\n            let assigned_inputs_b =\n                poseidon_chip.layout(&mut layouter, &self.inputs[1..2], 1, &mut HashMap::new())?;\n\n            layouter.assign_region(|| \"_new_module\", |_| Ok(()))?;\n\n            let inputs = vec![assigned_inputs_a, assigned_inputs_b];\n\n            layouter.assign_region(\n                || \"model\",\n                |region| {\n                    let mut region = RegionCtx::new(region, 0, 1);\n                    config\n                        .base\n                        .layout(&mut region, &inputs, Box::new(PolyOp::Add))\n                        .map_err(|_| Error::Synthesis)\n                },\n            )?;\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn addcircuit() {\n        let a = (0..LEN)\n            .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1))\n            .collect::<Vec<_>>();\n        let b = (0..LEN)\n            .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1))\n            .collect::<Vec<_>>();\n        let commitment_a =\n            PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(a.clone()).unwrap()[0][0];\n\n        let commitment_b =\n            PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(b.clone()).unwrap()[0][0];\n\n        // parameters\n        let a = Tensor::from(a.into_iter().map(Value::known));\n        let b = Tensor::from(b.into_iter().map(Value::known));\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n        };\n\n        let prover =\n            MockProver::run(K as u32, &circuit, vec![vec![commitment_a, commitment_b]]).unwrap();\n        prover.assert_satisfied();\n    }\n\n    #[test]\n    fn addcircuit_bad_hashes() {\n        let a = (0..LEN)\n            .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1))\n            .collect::<Vec<_>>();\n        let b = (0..LEN)\n            .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1))\n            .collect::<Vec<_>>();\n        let commitment_a = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(a.clone())\n            .unwrap()[0][0]\n            + Fr::one();\n\n        let commitment_b = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(b.clone())\n            .unwrap()[0][0]\n            + Fr::one();\n\n        // parameters\n        let a = Tensor::from(a.into_iter().map(Value::known));\n        let b = Tensor::from(b.into_iter().map(Value::known));\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n        };\n\n        let prover =\n            MockProver::run(K as u32, &circuit, vec![vec![commitment_a, commitment_b]]).unwrap();\n        assert!(prover.verify().is_err());\n    }\n}\n\n#[cfg(test)]\nmod sub {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Sub))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn subcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod mult {\n    use super::*;\n\n    const K: usize = 4;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Mult))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn multcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod pow {\n    use super::*;\n\n    const K: usize = 8;\n    const LEN: usize = 4;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 1],\n        _marker: PhantomData<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE)\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Pow(5)))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn powcircuit() {\n        // parameters\n        let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1))));\n\n        let circuit = MyCircuit::<F> {\n            inputs: [ValTensor::from(a)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod matmul_relu {\n    use super::*;\n\n    const K: usize = 18;\n    const LEN: usize = 32;\n    use crate::circuit::lookup::LookupOp;\n\n    #[derive(Clone)]\n    struct MyCircuit<F: PrimeField + TensorType + PartialOrd> {\n        inputs: [ValTensor<F>; 2],\n        _marker: PhantomData<F>,\n    }\n\n    // A columnar ReLu MLP\n    #[derive(Clone)]\n    struct MyConfig<F: PrimeField + TensorType + PartialOrd> {\n        base_config: BaseConfig<F>,\n    }\n\n    impl Circuit<F> for MyCircuit<F> {\n        type Config = MyConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let a = VarTensor::new_advice(cs, K, 1, LEN);\n            let b = VarTensor::new_advice(cs, K, 1, LEN);\n            let output = VarTensor::new_advice(cs, K, 1, LEN);\n\n            let mut base_config =\n                BaseConfig::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::SAFE);\n            // sets up a new relu table\n            base_config\n                .configure_lookup(cs, &b, &output, &a, (-32768, 32768), K, &LookupOp::ReLU)\n                .unwrap();\n\n            MyConfig { base_config }\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>,\n        ) -> Result<(), Error> {\n            config.base_config.layout_tables(&mut layouter).unwrap();\n            layouter.assign_region(\n                || \"\",\n                |region| {\n                    let mut region = RegionCtx::new(region, 0, 1);\n                    let op = PolyOp::Einsum {\n                        equation: \"ij,jk->ik\".to_string(),\n                    };\n                    let output = config\n                        .base_config\n                        .layout(&mut region, &self.inputs, Box::new(op))\n                        .unwrap();\n                    let _output = config\n                        .base_config\n                        .layout(&mut region, &[output.unwrap()], Box::new(LookupOp::ReLU))\n                        .unwrap();\n                    Ok(())\n                },\n            )?;\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn matmulrelucircuit() {\n        // parameters\n        let mut a = Tensor::from((0..LEN * LEN).map(|_| Value::known(F::from(1))));\n        a.reshape(&[LEN, LEN]).unwrap();\n\n        // parameters\n        let mut b = Tensor::from((0..LEN).map(|_| Value::known(F::from(1))));\n        b.reshape(&[LEN, 1]).unwrap();\n\n        let circuit = MyCircuit {\n            inputs: [ValTensor::from(a), ValTensor::from(b)],\n            _marker: PhantomData,\n        };\n\n        let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\nmod relu {\n    use super::*;\n    use halo2_proofs::{\n        circuit::{Layouter, SimpleFloorPlanner, Value},\n        dev::MockProver,\n        plonk::{Circuit, ConstraintSystem, Error},\n    };\n\n    #[derive(Clone)]\n    struct ReLUCircuit<F: PrimeField + TensorType + PartialOrd> {\n        pub input: ValTensor<F>,\n    }\n\n    impl Circuit<F> for ReLUCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let advices = (0..3)\n                .map(|_| VarTensor::new_advice(cs, 4, 1, 3))\n                .collect::<Vec<_>>();\n\n            let nl = LookupOp::ReLU;\n\n            let mut config = BaseConfig::default();\n\n            config\n                .configure_lookup(cs, &advices[0], &advices[1], &advices[2], (-6, 6), 4, &nl)\n                .unwrap();\n            config\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>, // layouter is our 'write buffer' for the circuit\n        ) -> Result<(), Error> {\n            config.layout_tables(&mut layouter).unwrap();\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &[self.input.clone()], Box::new(LookupOp::ReLU))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn relucircuit() {\n        let input: Tensor<Value<F>> =\n            Tensor::new(Some(&[Value::<F>::known(F::from(1_u64)); 4]), &[4]).unwrap();\n\n        let circuit = ReLUCircuit::<F> {\n            input: ValTensor::from(input),\n        };\n\n        let prover = MockProver::run(4_u32, &circuit, vec![]).unwrap();\n        prover.assert_satisfied();\n    }\n}\n\n#[cfg(test)]\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\nmod lookup_ultra_overflow {\n    use super::*;\n    use halo2_proofs::{\n        circuit::{Layouter, SimpleFloorPlanner, Value},\n        plonk::{Circuit, ConstraintSystem, Error},\n        poly::kzg::{\n            commitment::KZGCommitmentScheme,\n            multiopen::{ProverSHPLONK, VerifierSHPLONK},\n            strategy::SingleStrategy,\n        },\n    };\n    use snark_verifier::system::halo2::transcript::evm::EvmTranscript;\n\n    #[derive(Clone)]\n    struct ReLUCircuit<F: PrimeField + TensorType + PartialOrd> {\n        pub input: ValTensor<F>,\n    }\n\n    impl Circuit<F> for ReLUCircuit<F> {\n        type Config = BaseConfig<F>;\n        type FloorPlanner = SimpleFloorPlanner;\n        type Params = TestParams;\n\n        fn without_witnesses(&self) -> Self {\n            self.clone()\n        }\n\n        fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config {\n            let advices = (0..3)\n                .map(|_| VarTensor::new_advice(cs, 4, 1, 3))\n                .collect::<Vec<_>>();\n\n            let nl = LookupOp::ReLU;\n\n            let mut config = BaseConfig::default();\n\n            config\n                .configure_lookup(\n                    cs,\n                    &advices[0],\n                    &advices[1],\n                    &advices[2],\n                    (-1024, 1024),\n                    4,\n                    &nl,\n                )\n                .unwrap();\n            config\n        }\n\n        fn synthesize(\n            &self,\n            mut config: Self::Config,\n            mut layouter: impl Layouter<F>, // layouter is our 'write buffer' for the circuit\n        ) -> Result<(), Error> {\n            config.layout_tables(&mut layouter).unwrap();\n            layouter\n                .assign_region(\n                    || \"\",\n                    |region| {\n                        let mut region = RegionCtx::new(region, 0, 1);\n                        config\n                            .layout(&mut region, &[self.input.clone()], Box::new(LookupOp::ReLU))\n                            .map_err(|_| Error::Synthesis)\n                    },\n                )\n                .unwrap();\n\n            Ok(())\n        }\n    }\n\n    #[test]\n    #[ignore]\n    fn relucircuit() {\n        // get some logs fam\n        crate::logger::init_logger();\n        // parameters\n        let a = Tensor::from((0..4).map(|i| Value::known(F::from(i + 1))));\n\n        let circuit = ReLUCircuit::<F> {\n            input: ValTensor::from(a),\n        };\n\n        let params = crate::pfsys::srs::gen_srs::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>,\n        >(4_u32);\n\n        let pk = crate::pfsys::create_keys::<\n            halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>,\n            ReLUCircuit<F>,\n        >(&circuit, &params, true)\n        .unwrap();\n\n        let prover = crate::pfsys::create_proof_circuit::<\n            KZGCommitmentScheme<_>,\n            _,\n            ProverSHPLONK<_>,\n            VerifierSHPLONK<_>,\n            SingleStrategy<_>,\n            _,\n            EvmTranscript<_, _, _, _>,\n            EvmTranscript<_, _, _, _>,\n        >(\n            circuit.clone(),\n            vec![],\n            &params,\n            &pk,\n            // use safe mode to verify that the proof is correct\n            CheckMode::SAFE,\n            crate::Commitments::KZG,\n            crate::pfsys::TranscriptType::EVM,\n            None,\n            None,\n        );\n\n        assert!(prover.is_ok());\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/circuit/utils.rs",
        "content": "use serde::{Deserialize, Serialize};\n\n// --------------------------------------------------------------------------------------------\n//\n// Float Utils to enable the usage of f32s as the keys of HashMaps\n// This section is taken from the `eq_float` crate verbatim -- but we also implement deserialization methods\n//\n//\n\nuse std::cmp::Ordering;\nuse std::fmt;\nuse std::hash::{Hash, Hasher};\n\n#[derive(Debug, Default, Clone, Copy)]\n/// f32 wrapper\npub struct F32(pub f32);\n\nimpl<'de> Deserialize<'de> for F32 {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: serde::Deserializer<'de>,\n    {\n        let float = f32::deserialize(deserializer)?;\n        Ok(F32(float))\n    }\n}\n\nimpl Serialize for F32 {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: serde::Serializer,\n    {\n        f32::serialize(&self.0, serializer)\n    }\n}\n\n/// This works like `PartialEq` on `f32`, except that `NAN == NAN` is true.\nimpl PartialEq for F32 {\n    fn eq(&self, other: &Self) -> bool {\n        if self.0.is_nan() && other.0.is_nan() {\n            true\n        } else {\n            self.0 == other.0\n        }\n    }\n}\n\nimpl Eq for F32 {}\n\n/// This works like `PartialOrd` on `f32`, except that `NAN` sorts below all other floats\n/// (and is equal to another NAN). This always returns a `Some`.\nimpl PartialOrd for F32 {\n    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n        Some(self.cmp(other))\n    }\n}\n\n/// This works like `PartialOrd` on `f32`, except that `NAN` sorts below all other floats\n/// (and is equal to another NAN).\nimpl Ord for F32 {\n    fn cmp(&self, other: &Self) -> Ordering {\n        self.0.partial_cmp(&other.0).unwrap_or_else(|| {\n            if self.0.is_nan() && !other.0.is_nan() {\n                Ordering::Less\n            } else if !self.0.is_nan() && other.0.is_nan() {\n                Ordering::Greater\n            } else {\n                Ordering::Equal\n            }\n        })\n    }\n}\n\nimpl Hash for F32 {\n    fn hash<H: Hasher>(&self, state: &mut H) {\n        if self.0.is_nan() {\n            0x7fc00000u32.hash(state); // a particular bit representation for NAN\n        } else if self.0 == 0.0 {\n            // catches both positive and negative zero\n            0u32.hash(state);\n        } else {\n            self.0.to_bits().hash(state);\n        }\n    }\n}\n\nimpl From<F32> for f32 {\n    fn from(f: F32) -> Self {\n        f.0\n    }\n}\n\nimpl From<f32> for F32 {\n    fn from(f: f32) -> Self {\n        F32(f)\n    }\n}\n\nimpl From<f64> for F32 {\n    fn from(f: f64) -> Self {\n        F32(f as f32)\n    }\n}\n\nimpl From<usize> for F32 {\n    fn from(f: usize) -> Self {\n        F32(f as f32)\n    }\n}\n\nimpl From<F32> for f64 {\n    fn from(f: F32) -> Self {\n        f.0 as f64\n    }\n}\n\nimpl From<&F32> for f64 {\n    fn from(f: &F32) -> Self {\n        f.0 as f64\n    }\n}\n\nimpl fmt::Display for F32 {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        self.0.fmt(f)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use std::collections::hash_map::DefaultHasher;\n    use std::hash::{Hash, Hasher};\n\n    use super::F32;\n\n    fn calculate_hash<T: Hash>(t: &T) -> u64 {\n        let mut s = DefaultHasher::new();\n        t.hash(&mut s);\n        s.finish()\n    }\n\n    #[test]\n    fn f32_eq() {\n        assert!(F32(std::f32::NAN) == F32(std::f32::NAN));\n        assert!(F32(std::f32::NAN) != F32(5.0));\n        assert!(F32(5.0) != F32(std::f32::NAN));\n        assert!(F32(0.0) == F32(-0.0));\n    }\n\n    #[test]\n    fn f32_cmp() {\n        assert!(F32(std::f32::NAN) == F32(std::f32::NAN));\n        assert!(F32(std::f32::NAN) < F32(5.0));\n        assert!(F32(5.0) > F32(std::f32::NAN));\n        assert!(F32(0.0) == F32(-0.0));\n    }\n\n    #[test]\n    fn f32_hash() {\n        assert!(calculate_hash(&F32(0.0)) == calculate_hash(&F32(-0.0)));\n        assert!(calculate_hash(&F32(std::f32::NAN)) == calculate_hash(&F32(-std::f32::NAN)));\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/commands.rs",
        "content": "use clap::{Parser, Subcommand};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse ethers::types::H160;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::{\n    conversion::{FromPyObject, PyTryFrom},\n    exceptions::PyValueError,\n    prelude::*,\n    types::PyString,\n};\nuse serde::{Deserialize, Serialize};\nuse std::path::PathBuf;\nuse std::{error::Error, str::FromStr};\nuse tosubcommand::{ToFlags, ToSubcommand};\n\nuse crate::{pfsys::ProofType, Commitments, RunArgs};\n\nuse crate::circuit::CheckMode;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::graph::TestDataSource;\nuse crate::pfsys::TranscriptType;\n\n/// The default path to the .json data file\npub const DEFAULT_DATA: &str = \"input.json\";\n/// The default path to the .onnx model file\npub const DEFAULT_MODEL: &str = \"network.onnx\";\n/// The default path to the compiled model file\npub const DEFAULT_COMPILED_CIRCUIT: &str = \"model.compiled\";\n/// The default path to the .json witness file\npub const DEFAULT_WITNESS: &str = \"witness.json\";\n/// The default path to the circuit settings file\npub const DEFAULT_SETTINGS: &str = \"settings.json\";\n/// The default path to the proving key file\npub const DEFAULT_PK: &str = \"pk.key\";\n/// The default path to the verification key file\npub const DEFAULT_VK: &str = \"vk.key\";\n/// The default path to the proving key file for aggregated proofs\npub const DEFAULT_PK_AGGREGATED: &str = \"pk_aggr.key\";\n/// The default path to the verification key file for aggregated proofs\npub const DEFAULT_VK_AGGREGATED: &str = \"vk_aggr.key\";\n/// The default path to the proof file\npub const DEFAULT_PROOF: &str = \"proof.json\";\n/// The default path to the proof file for aggregated proofs\npub const DEFAULT_PROOF_AGGREGATED: &str = \"proof_aggr.json\";\n/// Default for whether to split proofs\npub const DEFAULT_SPLIT: &str = \"false\";\n/// Default verifier abi\npub const DEFAULT_VERIFIER_ABI: &str = \"verifier_abi.json\";\n/// Default verifier abi for aggregated proofs\npub const DEFAULT_VERIFIER_AGGREGATED_ABI: &str = \"verifier_aggr_abi.json\";\n/// Default verifier abi for data attestation\npub const DEFAULT_VERIFIER_DA_ABI: &str = \"verifier_da_abi.json\";\n/// Default solidity code\npub const DEFAULT_SOL_CODE: &str = \"evm_deploy.sol\";\n/// Default solidity code for aggregated proofs\npub const DEFAULT_SOL_CODE_AGGREGATED: &str = \"evm_deploy_aggr.sol\";\n/// Default solidity code for data attestation\npub const DEFAULT_SOL_CODE_DA: &str = \"evm_deploy_da.sol\";\n/// Default contract address\npub const DEFAULT_CONTRACT_ADDRESS: &str = \"contract.address\";\n/// Default contract address for data attestation\npub const DEFAULT_CONTRACT_ADDRESS_DA: &str = \"contract_da.address\";\n/// Default contract address for vk\npub const DEFAULT_CONTRACT_ADDRESS_VK: &str = \"contract_vk.address\";\n/// Default check mode\npub const DEFAULT_CHECKMODE: &str = \"safe\";\n/// Default calibration target\npub const DEFAULT_CALIBRATION_TARGET: &str = \"resources\";\n/// Default logrows for aggregated proofs\npub const DEFAULT_AGGREGATED_LOGROWS: &str = \"23\";\n/// Default optimizer runs\npub const DEFAULT_OPTIMIZER_RUNS: &str = \"1\";\n/// Default fuzz runs\npub const DEFAULT_FUZZ_RUNS: &str = \"10\";\n/// Default calibration file\npub const DEFAULT_CALIBRATION_FILE: &str = \"calibration.json\";\n/// Default lookup safety margin\npub const DEFAULT_LOOKUP_SAFETY_MARGIN: &str = \"2\";\n/// Default Compress selectors\npub const DEFAULT_DISABLE_SELECTOR_COMPRESSION: &str = \"false\";\n/// Default render vk seperately\npub const DEFAULT_RENDER_VK_SEPERATELY: &str = \"false\";\n/// Default VK sol path\npub const DEFAULT_VK_SOL: &str = \"vk.sol\";\n/// Default VK abi path\npub const DEFAULT_VK_ABI: &str = \"vk.abi\";\n/// Default scale rebase multipliers for calibration\npub const DEFAULT_SCALE_REBASE_MULTIPLIERS: &str = \"1,2,10\";\n/// Default use reduced srs for verification\npub const DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION: &str = \"false\";\n/// Default only check for range check rebase\npub const DEFAULT_ONLY_RANGE_CHECK_REBASE: &str = \"false\";\n/// Default commitment\npub const DEFAULT_COMMITMENT: &str = \"kzg\";\n\n#[cfg(feature = \"python-bindings\")]\n/// Converts TranscriptType into a PyObject (Required for TranscriptType to be compatible with Python)\nimpl IntoPy<PyObject> for TranscriptType {\n    fn into_py(self, py: Python) -> PyObject {\n        match self {\n            TranscriptType::Poseidon => \"poseidon\".to_object(py),\n            TranscriptType::EVM => \"evm\".to_object(py),\n        }\n    }\n}\n#[cfg(feature = \"python-bindings\")]\n/// Obtains TranscriptType from PyObject (Required for TranscriptType to be compatible with Python)\nimpl<'source> FromPyObject<'source> for TranscriptType {\n    fn extract(ob: &'source PyAny) -> PyResult<Self> {\n        let trystr = <PyString as PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n        match strval.to_lowercase().as_str() {\n            \"poseidon\" => Ok(TranscriptType::Poseidon),\n            \"evm\" => Ok(TranscriptType::EVM),\n            _ => Err(PyValueError::new_err(\"Invalid value for TranscriptType\")),\n        }\n    }\n}\n\n#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]\n/// Determines what the calibration pass should optimize for\npub enum CalibrationTarget {\n    /// Optimizes for reducing cpu and memory usage\n    Resources {\n        /// Whether to allow for column overflow. This can reduce memory usage (eg. for a browser environment), but may result in a verifier that doesn't fit on the blockchain.\n        col_overflow: bool,\n    },\n    /// Optimizes for numerical accuracy given the fixed point representation\n    Accuracy,\n}\n\nimpl Default for CalibrationTarget {\n    fn default() -> Self {\n        CalibrationTarget::Resources {\n            col_overflow: false,\n        }\n    }\n}\n\nimpl std::fmt::Display for CalibrationTarget {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(\n            f,\n            \"{}\",\n            match self {\n                CalibrationTarget::Resources { col_overflow: true } => {\n                    \"resources/col-overflow\".to_string()\n                }\n                CalibrationTarget::Resources {\n                    col_overflow: false,\n                } => \"resources\".to_string(),\n                CalibrationTarget::Accuracy => \"accuracy\".to_string(),\n            }\n        )\n    }\n}\n\nimpl ToFlags for CalibrationTarget {\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl From<&str> for CalibrationTarget {\n    fn from(s: &str) -> Self {\n        match s {\n            \"resources\" => CalibrationTarget::Resources {\n                col_overflow: false,\n            },\n            \"resources/col-overflow\" => CalibrationTarget::Resources { col_overflow: true },\n            \"accuracy\" => CalibrationTarget::Accuracy,\n            _ => {\n                log::error!(\"Invalid value for CalibrationTarget\");\n                log::warn!(\"Defaulting to resources\");\n                CalibrationTarget::default()\n            }\n        }\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\n#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]\n/// wrapper for H160 to make it easy to parse into flag vals\npub struct H160Flag {\n    inner: H160,\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl From<H160Flag> for H160 {\n    fn from(val: H160Flag) -> H160 {\n        val.inner\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl ToFlags for H160Flag {\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{:#x}\", self.inner)]\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl From<&str> for H160Flag {\n    fn from(s: &str) -> Self {\n        Self {\n            inner: H160::from_str(s).unwrap(),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Converts CalibrationTarget into a PyObject (Required for CalibrationTarget to be compatible with Python)\nimpl IntoPy<PyObject> for CalibrationTarget {\n    fn into_py(self, py: Python) -> PyObject {\n        match self {\n            CalibrationTarget::Resources { col_overflow: true } => {\n                \"resources/col-overflow\".to_object(py)\n            }\n            CalibrationTarget::Resources {\n                col_overflow: false,\n            } => \"resources\".to_object(py),\n            CalibrationTarget::Accuracy => \"accuracy\".to_object(py),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Obtains CalibrationTarget from PyObject (Required for CalibrationTarget to be compatible with Python)\nimpl<'source> FromPyObject<'source> for CalibrationTarget {\n    fn extract(ob: &'source PyAny) -> PyResult<Self> {\n        let trystr = <PyString as PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n        match strval.to_lowercase().as_str() {\n            \"resources\" => Ok(CalibrationTarget::Resources {\n                col_overflow: false,\n            }),\n            \"resources/col-overflow\" => Ok(CalibrationTarget::Resources { col_overflow: true }),\n            \"accuracy\" => Ok(CalibrationTarget::Accuracy),\n            _ => Err(PyValueError::new_err(\"Invalid value for CalibrationTarget\")),\n        }\n    }\n}\n// not wasm\nuse lazy_static::lazy_static;\n\n// if CARGO VERSION is 0.0.0 replace with \"source - no compatibility guaranteed\"\nlazy_static! {\n    /// The version of the ezkl library\n    pub static ref VERSION: &'static str =  if env!(\"CARGO_PKG_VERSION\") == \"0.0.0\" {\n       \"source - no compatibility guaranteed\"\n    } else {\n        env!(\"CARGO_PKG_VERSION\")\n    };\n}\n\n#[allow(missing_docs)]\n#[derive(Parser, Debug, Clone, Deserialize, Serialize)]\n#[command(author, about, long_about = None)]\n#[clap(version = *VERSION)]\npub struct Cli {\n    #[command(subcommand)]\n    #[allow(missing_docs)]\n    pub command: Commands,\n}\n\nimpl Cli {\n    /// Export the ezkl configuration as json\n    pub fn as_json(&self) -> Result<String, Box<dyn Error>> {\n        let serialized = match serde_json::to_string(&self) {\n            Ok(s) => s,\n            Err(e) => {\n                return Err(Box::new(e));\n            }\n        };\n        Ok(serialized)\n    }\n    /// Parse an ezkl configuration from a json\n    pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> {\n        serde_json::from_str(arg_json)\n    }\n}\n\n#[allow(missing_docs)]\n#[derive(Debug, Subcommand, Clone, Deserialize, Serialize, PartialEq, PartialOrd, ToSubcommand)]\npub enum Commands {\n    #[cfg(feature = \"empty-cmd\")]\n    /// Creates an empty buffer\n    Empty,\n    /// Loads model and prints model table\n    Table {\n        /// The path to the .onnx model file\n        #[arg(short = 'M', long, default_value = DEFAULT_MODEL)]\n        model: PathBuf,\n        /// proving arguments\n        #[clap(flatten)]\n        args: RunArgs,\n    },\n\n    /// Generates the witness from an input file.\n    GenWitness {\n        /// The path to the .json data file\n        #[arg(short = 'D', long, default_value = DEFAULT_DATA)]\n        data: PathBuf,\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)]\n        compiled_circuit: PathBuf,\n        /// Path to output the witness .json file\n        #[arg(short = 'O', long, default_value = DEFAULT_WITNESS)]\n        output: PathBuf,\n        /// Path to the verification key file (optional - solely used to generate kzg commits)\n        #[arg(short = 'V', long)]\n        vk_path: Option<PathBuf>,\n        /// Path to the srs file (optional - solely used to generate kzg commits)\n        #[arg(short = 'P', long)]\n        srs_path: Option<PathBuf>,\n    },\n\n    /// Produces the proving hyperparameters, from run-args\n    GenSettings {\n        /// The path to the .onnx model file\n        #[arg(short = 'M', long, default_value = DEFAULT_MODEL)]\n        model: PathBuf,\n        /// The path to generate the circuit settings .json file to\n        #[arg(short = 'O', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// proving arguments\n        #[clap(flatten)]\n        args: RunArgs,\n    },\n\n    /// Calibrates the proving scale, lookup bits and logrows from a circuit settings file.\n    #[cfg(not(target_arch = \"wasm32\"))]\n    CalibrateSettings {\n        /// The path to the .json calibration data file.\n        #[arg(short = 'D', long, default_value = DEFAULT_CALIBRATION_FILE)]\n        data: PathBuf,\n        /// The path to the .onnx model file\n        #[arg(short = 'M', long, default_value = DEFAULT_MODEL)]\n        model: PathBuf,\n        /// The path to load circuit settings .json file AND overwrite (generated using the gen-settings command).\n        #[arg(short = 'O', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        #[arg(long = \"target\", default_value = DEFAULT_CALIBRATION_TARGET)]\n        /// Target for calibration. Set to \"resources\" to optimize for computational resource. Otherwise, set to \"accuracy\" to optimize for accuracy.\n        target: CalibrationTarget,\n        /// the lookup safety margin to use for calibration. if the max lookup is 2^k, then the max lookup will be 2^k * lookup_safety_margin. larger = safer but slower\n        #[arg(long, default_value = DEFAULT_LOOKUP_SAFETY_MARGIN)]\n        lookup_safety_margin: i128,\n        /// Optional scales to specifically try for calibration. Example, --scales 0,4\n        #[arg(long, value_delimiter = ',', allow_hyphen_values = true)]\n        scales: Option<Vec<crate::Scale>>,\n        /// Optional scale rebase multipliers to specifically try for calibration. This is the multiplier at which we divide to return to the input scale. Example, --scale-rebase-multipliers 0,4\n        #[arg(\n            long,\n            value_delimiter = ',',\n            allow_hyphen_values = true,\n            default_value = DEFAULT_SCALE_REBASE_MULTIPLIERS\n        )]\n        scale_rebase_multiplier: Vec<u32>,\n        /// max logrows to use for calibration, 26 is the max public SRS size\n        #[arg(long)]\n        max_logrows: Option<u32>,\n        // whether to only range check rebases (instead of trying both range check and lookup)\n        #[arg(long, default_value = DEFAULT_ONLY_RANGE_CHECK_REBASE)]\n        only_range_check_rebase: bool,\n    },\n\n    /// Generates a dummy SRS\n    #[command(name = \"gen-srs\", arg_required_else_help = true)]\n    GenSrs {\n        /// The path to output the generated SRS\n        #[arg(long)]\n        srs_path: PathBuf,\n        /// number of logrows to use for srs\n        #[arg(long)]\n        logrows: usize,\n        /// commitment used\n        #[arg(long, default_value = DEFAULT_COMMITMENT)]\n        commitment: Commitments,\n    },\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Gets an SRS from a circuit settings file.\n    #[command(name = \"get-srs\")]\n    GetSrs {\n        /// The path to output the desired srs file, if set to None will save to $EZKL_REPO_PATH/srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// Path to the circuit settings .json file to read in logrows from. Overriden by logrows if specified.\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: Option<PathBuf>,\n        /// Number of logrows to use for srs. Overrides settings_path if specified.\n        #[arg(long, default_value = None)]\n        logrows: Option<u32>,\n        /// Commitment used\n        #[arg(long, default_value = None)]\n        commitment: Option<Commitments>,\n    },\n    /// Loads model and input and runs mock prover (for testing)\n    Mock {\n        /// The path to the .json witness file (generated using the gen-witness command)\n        #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)]\n        witness: PathBuf,\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)]\n        model: PathBuf,\n    },\n\n    /// Mock aggregate proofs\n    MockAggregate {\n        /// The path to the snarks to aggregate over (generated using the prove command with the --proof-type=for-aggr flag)\n        #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)]\n        aggregation_snarks: Vec<PathBuf>,\n        /// logrows used for aggregation circuit\n        #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)]\n        logrows: u32,\n        /// whether the accumulated are segments of a larger proof\n        #[arg(long, default_value = DEFAULT_SPLIT)]\n        split_proofs: bool,\n    },\n\n    /// setup aggregation circuit :)\n    SetupAggregate {\n        /// The path to samples of snarks that will be aggregated over (generated using the prove command with the --proof-type=for-aggr flag)\n        #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)]\n        sample_snarks: Vec<PathBuf>,\n        /// The path to save the desired verification key file to\n        #[arg(long, default_value = DEFAULT_VK_AGGREGATED)]\n        vk_path: PathBuf,\n        /// The path to save the proving key to\n        #[arg(long, default_value = DEFAULT_PK_AGGREGATED)]\n        pk_path: PathBuf,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// logrows used for aggregation circuit\n        #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)]\n        logrows: u32,\n        /// whether the accumulated are segments of a larger proof\n        #[arg(long, default_value = DEFAULT_SPLIT)]\n        split_proofs: bool,\n        /// compress selectors\n        #[arg(long, default_value = DEFAULT_DISABLE_SELECTOR_COMPRESSION)]\n        disable_selector_compression: bool,\n        /// commitment used\n        #[arg(long, default_value = DEFAULT_COMMITMENT)]\n        commitment: Option<Commitments>,\n    },\n    /// Aggregates proofs :)\n    Aggregate {\n        /// The path to the snarks to aggregate over (generated using the prove command with the --proof-type=for-aggr flag)\n        #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)]\n        aggregation_snarks: Vec<PathBuf>,\n        /// The path to load the desired proving key file (generated using the setup-aggregate command)\n        #[arg(long, default_value = DEFAULT_PK_AGGREGATED)]\n        pk_path: PathBuf,\n        /// The path to output the proof file to\n        #[arg(long, default_value = DEFAULT_PROOF_AGGREGATED)]\n        proof_path: PathBuf,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        #[arg(\n            long,\n            require_equals = true,\n            num_args = 0..=1,\n            default_value_t = TranscriptType::default(),\n            value_enum\n        )]\n        transcript: TranscriptType,\n        /// logrows used for aggregation circuit\n        #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)]\n        logrows: u32,\n        /// run sanity checks during calculations (safe or unsafe)\n        #[arg(long, default_value = DEFAULT_CHECKMODE)]\n        check_mode: CheckMode,\n        /// whether the accumulated proofs are segments of a larger circuit\n        #[arg(long, default_value = DEFAULT_SPLIT)]\n        split_proofs: bool,\n        /// commitment used\n        #[arg(long, default_value = DEFAULT_COMMITMENT)]\n        commitment: Option<Commitments>,\n    },\n    /// Compiles a circuit from onnx to a simplified graph (einsum + other ops) and parameters as sets of field elements\n    CompileCircuit {\n        /// The path to the .onnx model file\n        #[arg(short = 'M', long, default_value = DEFAULT_MODEL)]\n        model: PathBuf,\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(long, default_value = DEFAULT_COMPILED_CIRCUIT)]\n        compiled_circuit: PathBuf,\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n    },\n    /// Creates pk and vk\n    Setup {\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)]\n        compiled_circuit: PathBuf,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// The path to output the verification key file to\n        #[arg(long, default_value = DEFAULT_VK)]\n        vk_path: PathBuf,\n        /// The path to output the proving key file to\n        #[arg(long, default_value = DEFAULT_PK)]\n        pk_path: PathBuf,\n        /// The graph witness (optional - used to override fixed values in the circuit)\n        #[arg(short = 'W', long)]\n        witness: Option<PathBuf>,\n        /// compress selectors\n        #[arg(long, default_value = DEFAULT_DISABLE_SELECTOR_COMPRESSION)]\n        disable_selector_compression: bool,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Deploys a test contact that the data attester reads from and creates a data attestation formatted input.json file that contains call data information\n    #[command(arg_required_else_help = true)]\n    SetupTestEvmData {\n        /// The path to the .json data file, which should include both the network input (possibly private) and the network output (public input to the proof)\n        #[arg(short = 'D', long)]\n        data: PathBuf,\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(short = 'M', long)]\n        compiled_circuit: PathBuf,\n        /// For testing purposes only. The optional path to the .json data file that will be generated that contains the OnChain data storage information\n        /// derived from the file information in the data .json file.\n        /// Should include both the network input (possibly private) and the network output (public input to the proof)\n        #[arg(short = 'T', long)]\n        test_data: PathBuf,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n        /// where the input data come from\n        #[arg(long, default_value = \"on-chain\")]\n        input_source: TestDataSource,\n        /// where the output data come from\n        #[arg(long, default_value = \"on-chain\")]\n        output_source: TestDataSource,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// The Data Attestation Verifier contract stores the account calls to fetch data to feed into ezkl. This call data can be updated by an admin account. This tests that admin account is able to update this call data.\n    #[command(arg_required_else_help = true)]\n    TestUpdateAccountCalls {\n        /// The path to the verifier contract's address\n        #[arg(long)]\n        addr: H160Flag,\n        /// The path to the .json data file.\n        #[arg(short = 'D', long)]\n        data: PathBuf,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Swaps the positions in the transcript that correspond to commitments\n    SwapProofCommitments {\n        /// The path to the proof file\n        #[arg(short = 'P', long, default_value = DEFAULT_PROOF)]\n        proof_path: PathBuf,\n        /// The path to the witness file\n        #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)]\n        witness_path: PathBuf,\n    },\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Loads model, data, and creates proof\n    Prove {\n        /// The path to the .json witness file (generated using the gen-witness command)\n        #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)]\n        witness: PathBuf,\n        /// The path to the compiled model file (generated using the compile-circuit command)\n        #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)]\n        compiled_circuit: PathBuf,\n        /// The path to load the desired proving key file (generated using the setup command)\n        #[arg(long, default_value = DEFAULT_PK)]\n        pk_path: PathBuf,\n        /// The path to output the proof file to\n        #[arg(long, default_value = DEFAULT_PROOF)]\n        proof_path: PathBuf,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        #[arg(\n            long,\n            require_equals = true,\n            num_args = 0..=1,\n            default_value_t = ProofType::Single,\n            value_enum\n        )]\n        proof_type: ProofType,\n        /// run sanity checks during calculations (safe or unsafe)\n        #[arg(long, default_value = DEFAULT_CHECKMODE)]\n        check_mode: CheckMode,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Creates an Evm verifier for a single proof\n    #[command(name = \"create-evm-verifier\")]\n    CreateEvmVerifier {\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// The path to load the desired verification key file\n        #[arg(long, default_value = DEFAULT_VK)]\n        vk_path: PathBuf,\n        /// The path to output the Solidity code\n        #[arg(long, default_value = DEFAULT_SOL_CODE)]\n        sol_code_path: PathBuf,\n        /// The path to output the Solidity verifier ABI\n        #[arg(long, default_value = DEFAULT_VERIFIER_ABI)]\n        abi_path: PathBuf,\n        /// Whether the verifier key should be rendered as a separate contract.\n        /// We recommend disabling selector compression if this is enabled.\n        /// To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command.        \n        #[arg(long, default_value = DEFAULT_RENDER_VK_SEPERATELY)]\n        render_vk_seperately: bool,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Creates an Evm verifier for a single proof\n    #[command(name = \"create-evm-vk\")]\n    CreateEvmVK {\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// The path to load the desired verification key file\n        #[arg(long, default_value = DEFAULT_VK)]\n        vk_path: PathBuf,\n        /// The path to output the Solidity code\n        #[arg(long, default_value = DEFAULT_VK_SOL)]\n        sol_code_path: PathBuf,\n        /// The path to output the Solidity verifier ABI\n        #[arg(long, default_value = DEFAULT_VK_ABI)]\n        abi_path: PathBuf,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Creates an Evm verifier that attests to on-chain inputs for a single proof\n    #[command(name = \"create-evm-da\")]\n    CreateEvmDataAttestation {\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// The path to output the Solidity code\n        #[arg(long, default_value = DEFAULT_SOL_CODE_DA)]\n        sol_code_path: PathBuf,\n        /// The path to output the Solidity verifier ABI\n        #[arg(long, default_value = DEFAULT_VERIFIER_DA_ABI)]\n        abi_path: PathBuf,\n        /// The path to the .json data file, which should\n        /// contain the necessary calldata and account addresses\n        /// needed to read from all the on-chain\n        /// view functions that return the data that the network\n        /// ingests as inputs.\n        #[arg(short = 'D', long, default_value = DEFAULT_DATA)]\n        data: PathBuf,\n    },\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Creates an Evm verifier for an aggregate proof\n    #[command(name = \"create-evm-verifier-aggr\")]\n    CreateEvmVerifierAggr {\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// The path to load the desired verification key file\n        #[arg(long, default_value = DEFAULT_VK_AGGREGATED)]\n        vk_path: PathBuf,\n        /// The path to the Solidity code\n        #[arg(long, default_value = DEFAULT_SOL_CODE_AGGREGATED)]\n        sol_code_path: PathBuf,\n        /// The path to output the Solidity verifier ABI\n        #[arg(long, default_value = DEFAULT_VERIFIER_AGGREGATED_ABI)]\n        abi_path: PathBuf,\n        // aggregated circuit settings paths, used to calculate the number of instances in the aggregate proof\n        #[arg(long, default_value = DEFAULT_SETTINGS, value_delimiter = ',', allow_hyphen_values = true)]\n        aggregation_settings: Vec<PathBuf>,\n        // logrows used for aggregation circuit\n        #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)]\n        logrows: u32,\n        /// Whether the verifier key should be rendered as a separate contract.\n        /// We recommend disabling selector compression if this is enabled.\n        /// To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command.        \n        #[arg(long, default_value = DEFAULT_RENDER_VK_SEPERATELY)]\n        render_vk_seperately: bool,\n    },\n    /// Verifies a proof, returning accept or reject\n    Verify {\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// The path to the proof file (generated using the prove command)\n        #[arg(long, default_value = DEFAULT_PROOF)]\n        proof_path: PathBuf,\n        /// The path to the verification key file (generated using the setup command)\n        #[arg(long, default_value = DEFAULT_VK)]\n        vk_path: PathBuf,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// Reduce SRS logrows to the number of instances rather than the number of logrows used for proofs (only works if the srs were generated in the same ceremony)\n        #[arg(long, default_value = DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION)]\n        reduced_srs: bool,\n    },\n    /// Verifies an aggregate proof, returning accept or reject\n    VerifyAggr {\n        /// The path to the proof file (generated using the prove command)\n        #[arg(long, default_value = DEFAULT_PROOF_AGGREGATED)]\n        proof_path: PathBuf,\n        /// The path to the verification key file (generated using the setup-aggregate command)\n        #[arg(long, default_value = DEFAULT_VK_AGGREGATED)]\n        vk_path: PathBuf,\n        /// reduced srs\n        #[arg(long, default_value = DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION)]\n        reduced_srs: bool,\n        /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs\n        #[arg(long)]\n        srs_path: Option<PathBuf>,\n        /// logrows used for aggregation circuit\n        #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)]\n        logrows: u32,\n        /// commitment\n        #[arg(long, default_value = DEFAULT_COMMITMENT)]\n        commitment: Option<Commitments>,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Deploys an evm verifier that is generated by ezkl\n    DeployEvmVerifier {\n        /// The path to the Solidity code (generated using the create-evm-verifier command)\n        #[arg(long, default_value = DEFAULT_SOL_CODE)]\n        sol_code_path: PathBuf,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n        #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS)]\n        /// The path to output the contract address\n        addr_path: PathBuf,\n        /// The optimizer runs to set on the verifier. Lower values optimize for deployment cost, while higher values optimize for gas cost.\n        #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)]\n        optimizer_runs: usize,\n        /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil\n        #[arg(short = 'P', long)]\n        private_key: Option<String>,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Deploys an evm verifier that is generated by ezkl\n    DeployEvmVK {\n        /// The path to the Solidity code (generated using the create-evm-verifier command)\n        #[arg(long, default_value = DEFAULT_VK_SOL)]\n        sol_code_path: PathBuf,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n        #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS_VK)]\n        /// The path to output the contract address\n        addr_path: PathBuf,\n        /// The optimizer runs to set on the verifier. Lower values optimize for deployment cost, while higher values optimize for gas cost.\n        #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)]\n        optimizer_runs: usize,\n        /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil\n        #[arg(short = 'P', long)]\n        private_key: Option<String>,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Deploys an evm verifier that allows for data attestation\n    #[command(name = \"deploy-evm-da\")]\n    DeployEvmDataAttestation {\n        /// The path to the .json data file, which should include both the network input (possibly private) and the network output (public input to the proof)\n        #[arg(short = 'D', long, default_value = DEFAULT_DATA)]\n        data: PathBuf,\n        /// The path to load circuit settings .json file from (generated using the gen-settings command)\n        #[arg(long, default_value = DEFAULT_SETTINGS)]\n        settings_path: PathBuf,\n        /// The path to the Solidity code\n        #[arg(long, default_value = DEFAULT_SOL_CODE_DA)]\n        sol_code_path: PathBuf,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n        #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS_DA)]\n        /// The path to output the contract address\n        addr_path: PathBuf,\n        /// The optimizer runs to set on the verifier. (Lower values optimize for deployment, while higher values optimize for execution)\n        #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)]\n        optimizer_runs: usize,\n        /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil\n        #[arg(short = 'P', long)]\n        private_key: Option<String>,\n    },\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Verifies a proof using a local Evm executor, returning accept or reject\n    #[command(name = \"verify-evm\")]\n    VerifyEvm {\n        /// The path to the proof file (generated using the prove command)\n        #[arg(long, default_value = DEFAULT_PROOF)]\n        proof_path: PathBuf,\n        /// The path to verifier contract's address\n        #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS)]\n        addr_verifier: H160Flag,\n        /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n        #[arg(short = 'U', long)]\n        rpc_url: Option<String>,\n        /// does the verifier use data attestation ?\n        #[arg(long)]\n        addr_da: Option<H160Flag>,\n        // is the vk rendered seperately, if so specify an address\n        #[arg(long)]\n        addr_vk: Option<H160Flag>,\n    },\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/eth.rs",
        "content": "use crate::graph::input::{CallsToAccount, FileSourceInner, GraphData};\nuse crate::graph::modules::POSEIDON_INSTANCES;\nuse crate::graph::DataSource;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::graph::GraphSettings;\nuse crate::pfsys::evm::EvmVerificationError;\nuse crate::pfsys::Snark;\nuse ethers::abi::Contract;\nuse ethers::contract::abigen;\nuse ethers::contract::ContractFactory;\nuse ethers::core::k256::ecdsa::SigningKey;\nuse ethers::middleware::SignerMiddleware;\nuse ethers::prelude::ContractInstance;\n#[cfg(target_arch = \"wasm32\")]\nuse ethers::prelude::Wallet;\nuse ethers::providers::Middleware;\nuse ethers::providers::{Http, Provider};\nuse ethers::signers::Signer;\nuse ethers::solc::{CompilerInput, Solc};\nuse ethers::types::transaction::eip2718::TypedTransaction;\nuse ethers::types::TransactionRequest;\nuse ethers::types::H160;\nuse ethers::types::U256;\nuse ethers::types::{Bytes, I256};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse ethers::{\n    prelude::{LocalWallet, Wallet},\n    utils::{Anvil, AnvilInstance},\n};\nuse halo2_solidity_verifier::encode_calldata;\nuse halo2curves::bn256::{Fr, G1Affine};\nuse halo2curves::group::ff::PrimeField;\nuse log::{debug, info, warn};\nuse std::error::Error;\nuse std::path::PathBuf;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::time::Duration;\nuse std::{convert::TryFrom, sync::Arc};\n\n/// A local ethers-rs based client\npub type EthersClient = Arc<SignerMiddleware<Provider<Http>, Wallet<SigningKey>>>;\n\n// Generate contract bindings OUTSIDE the functions so they are part of library\nabigen!(TestReads, \"./abis/TestReads.json\");\nabigen!(DataAttestation, \"./abis/DataAttestation.json\");\nabigen!(QuantizeData, \"./abis/QuantizeData.json\");\n\nconst TESTREADS_SOL: &str = include_str!(\"../contracts/TestReads.sol\");\nconst QUANTIZE_DATA_SOL: &str = include_str!(\"../contracts/QuantizeData.sol\");\nconst ATTESTDATA_SOL: &str = include_str!(\"../contracts/AttestData.sol\");\nconst LOADINSTANCES_SOL: &str = include_str!(\"../contracts/LoadInstances.sol\");\n\n/// Return an instance of Anvil and a client for the given RPC URL. If none is provided, a local client is used.\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn setup_eth_backend(\n    rpc_url: Option<&str>,\n    private_key: Option<&str>,\n) -> Result<(AnvilInstance, EthersClient), Box<dyn Error>> {\n    // Launch anvil\n    let anvil = Anvil::new()\n        .args([\"--code-size-limit=41943040\", \"--disable-block-gas-limit\"])\n        .spawn();\n\n    let endpoint: String;\n    if let Some(rpc_url) = rpc_url {\n        endpoint = rpc_url.to_string();\n    } else {\n        endpoint = anvil.endpoint();\n    };\n\n    // Connect to the network\n    let provider = Provider::<Http>::try_from(endpoint)?.interval(Duration::from_millis(10u64));\n\n    let chain_id = provider.get_chainid().await?.as_u64();\n    info!(\"using chain {}\", chain_id);\n\n    // Instantiate the wallet\n    let wallet: LocalWallet;\n    if let Some(private_key) = private_key {\n        debug!(\"using private key {}\", private_key);\n        // Sanity checks for private_key\n        let private_key_format_error =\n            \"Private key must be in hex format, 64 chars, without 0x prefix\";\n        if private_key.len() != 64 {\n            return Err(private_key_format_error.into());\n        }\n        let private_key_buffer = hex::decode(private_key)?;\n        let signing_key = SigningKey::from_slice(&private_key_buffer)?;\n        wallet = LocalWallet::from(signing_key);\n    } else {\n        wallet = anvil.keys()[0].clone().into();\n    }\n\n    // Instantiate the client with the signer\n    let client = Arc::new(SignerMiddleware::new(\n        provider,\n        wallet.with_chain_id(chain_id),\n    ));\n\n    Ok((anvil, client))\n}\n\n///\npub async fn deploy_contract_via_solidity(\n    sol_code_path: PathBuf,\n    rpc_url: Option<&str>,\n    runs: usize,\n    private_key: Option<&str>,\n    contract_name: &str,\n) -> Result<ethers::types::Address, Box<dyn Error>> {\n    // anvil instance must be alive at least until the factory completes the deploy\n    let (anvil, client) = setup_eth_backend(rpc_url, private_key).await?;\n\n    let (abi, bytecode, runtime_bytecode) =\n        get_contract_artifacts(sol_code_path, contract_name, runs)?;\n\n    let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?;\n    let contract = factory.deploy(())?.send().await?;\n    let addr = contract.address();\n\n    drop(anvil);\n    Ok(addr)\n}\n\n///\npub async fn deploy_da_verifier_via_solidity(\n    settings_path: PathBuf,\n    input: PathBuf,\n    sol_code_path: PathBuf,\n    rpc_url: Option<&str>,\n    runs: usize,\n    private_key: Option<&str>,\n) -> Result<ethers::types::Address, Box<dyn Error>> {\n    let (anvil, client) = setup_eth_backend(rpc_url, private_key).await?;\n\n    let input = GraphData::from_path(input)?;\n\n    let settings = GraphSettings::load(&settings_path)?;\n\n    let mut scales: Vec<u32> = vec![];\n    // The data that will be stored in the test contracts that will eventually be read from.\n    let mut calls_to_accounts = vec![];\n\n    let mut instance_shapes = vec![];\n    let mut model_instance_offset = 0;\n\n    if settings.run_args.input_visibility.is_hashed() {\n        instance_shapes.push(POSEIDON_INSTANCES)\n    } else if settings.run_args.input_visibility.is_public() {\n        for idx in 0..settings.model_input_scales.len() {\n            let shape = &settings.model_instance_shapes[idx];\n            instance_shapes.push(shape.iter().product::<usize>());\n            model_instance_offset += 1;\n        }\n    }\n\n    if settings.run_args.param_visibility.is_hashed() {\n        return Err(Box::new(EvmVerificationError::InvalidVisibility));\n    }\n\n    if settings.run_args.output_visibility.is_hashed() {\n        instance_shapes.push(POSEIDON_INSTANCES)\n    } else if settings.run_args.output_visibility.is_public() {\n        for idx in model_instance_offset..model_instance_offset + settings.model_output_scales.len()\n        {\n            let shape = &settings.model_instance_shapes[idx];\n            instance_shapes.push(shape.iter().product::<usize>());\n        }\n    }\n\n    let mut instance_idx = 0;\n    let mut contract_instance_offset = 0;\n\n    if let DataSource::OnChain(source) = input.input_data {\n        if settings.run_args.input_visibility.is_hashed_public() {\n            // set scales 1.0\n            scales.extend(vec![0; instance_shapes[instance_idx]]);\n            instance_idx += 1;\n        } else {\n            let input_scales = settings.model_input_scales;\n            // give each input a scale\n            for scale in input_scales {\n                scales.extend(vec![scale as u32; instance_shapes[instance_idx]]);\n                instance_idx += 1;\n            }\n        }\n        for call in source.calls {\n            calls_to_accounts.push(call);\n        }\n    } else if let DataSource::File(source) = input.input_data {\n        if settings.run_args.input_visibility.is_public() {\n            instance_idx += source.len();\n            for s in source {\n                contract_instance_offset += s.len();\n            }\n        }\n    }\n\n    if let Some(DataSource::OnChain(source)) = input.output_data {\n        if settings.run_args.output_visibility.is_hashed_public() {\n            // set scales 1.0\n            scales.extend(vec![0; instance_shapes[instance_idx]]);\n        } else {\n            let input_scales = settings.model_output_scales;\n            // give each output a scale\n            for scale in input_scales {\n                scales.extend(vec![scale as u32; instance_shapes[instance_idx]]);\n                instance_idx += 1;\n            }\n        }\n        for call in source.calls {\n            calls_to_accounts.push(call);\n        }\n    }\n\n    let (contract_addresses, call_data, decimals) = if !calls_to_accounts.is_empty() {\n        parse_calls_to_accounts(calls_to_accounts)?\n    } else {\n        return Err(\"Data source for either input_data or output_data must be OnChain\".into());\n    };\n\n    let (abi, bytecode, runtime_bytecode) =\n        get_contract_artifacts(sol_code_path, \"DataAttestation\", runs)?;\n    let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?;\n\n    info!(\"call_data: {:#?}\", call_data);\n    info!(\"contract_addresses: {:#?}\", contract_addresses);\n    info!(\"decimals: {:#?}\", decimals);\n\n    let contract = factory\n        .deploy((\n            contract_addresses,\n            call_data,\n            decimals,\n            scales,\n            contract_instance_offset as u32,\n            client.address(),\n        ))?\n        .send()\n        .await?;\n\n    drop(anvil);\n    Ok(contract.address())\n}\n\ntype ParsedCallsToAccount = (Vec<H160>, Vec<Vec<Bytes>>, Vec<Vec<U256>>);\n\nfn parse_calls_to_accounts(\n    calls_to_accounts: Vec<CallsToAccount>,\n) -> Result<ParsedCallsToAccount, Box<dyn Error>> {\n    let mut contract_addresses = vec![];\n    let mut call_data = vec![];\n    let mut decimals: Vec<Vec<U256>> = vec![];\n    for (i, val) in calls_to_accounts.iter().enumerate() {\n        let contract_address_bytes = hex::decode(val.address.clone())?;\n        let contract_address = H160::from_slice(&contract_address_bytes);\n        contract_addresses.push(contract_address);\n        call_data.push(vec![]);\n        decimals.push(vec![]);\n        for (call, decimal) in &val.call_data {\n            let call_data_bytes = hex::decode(call)?;\n            call_data[i].push(ethers::types::Bytes::from(call_data_bytes));\n            decimals[i].push(ethers::types::U256::from_dec_str(&decimal.to_string())?);\n        }\n    }\n    Ok((contract_addresses, call_data, decimals))\n}\n\npub async fn update_account_calls(\n    addr: H160,\n    input: PathBuf,\n    rpc_url: Option<&str>,\n) -> Result<(), Box<dyn Error>> {\n    let input = GraphData::from_path(input)?;\n\n    // The data that will be stored in the test contracts that will eventually be read from.\n    let mut calls_to_accounts = vec![];\n\n    if let DataSource::OnChain(source) = input.input_data {\n        for call in source.calls {\n            calls_to_accounts.push(call);\n        }\n    }\n\n    if let Some(DataSource::OnChain(source)) = input.output_data {\n        for call in source.calls {\n            calls_to_accounts.push(call);\n        }\n    }\n\n    let (contract_addresses, call_data, decimals) = if !calls_to_accounts.is_empty() {\n        parse_calls_to_accounts(calls_to_accounts)?\n    } else {\n        return Err(\"Data source for either input_data or output_data must be OnChain\".into());\n    };\n\n    let (anvil, client) = setup_eth_backend(rpc_url, None).await?;\n\n    let contract = DataAttestation::new(addr, client.clone());\n\n    contract\n        .update_account_calls(\n            contract_addresses.clone(),\n            call_data.clone(),\n            decimals.clone(),\n        )\n        .send()\n        .await?;\n\n    // Instantiate a different wallet\n    let wallet: LocalWallet = anvil.keys()[1].clone().into();\n\n    let client = Arc::new(client.with_signer(wallet.with_chain_id(anvil.chain_id())));\n\n    // update contract signer with non admin account\n    let contract = DataAttestation::new(addr, client.clone());\n\n    // call to update_account_calls should fail\n\n    if (contract\n        .update_account_calls(contract_addresses, call_data, decimals)\n        .send()\n        .await)\n        .is_err()\n    {\n        info!(\"update_account_calls failed as expected\");\n    } else {\n        return Err(\"update_account_calls should have failed\".into());\n    }\n\n    Ok(())\n}\n\n/// Verify a proof using a Solidity verifier contract\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn verify_proof_via_solidity(\n    proof: Snark<Fr, G1Affine>,\n    addr: ethers::types::Address,\n    addr_vk: Option<H160>,\n    rpc_url: Option<&str>,\n) -> Result<bool, Box<dyn Error>> {\n    let flattened_instances = proof.instances.into_iter().flatten();\n\n    let encoded = encode_calldata(\n        addr_vk.as_ref().map(|x| x.0),\n        &proof.proof,\n        &flattened_instances.collect::<Vec<_>>(),\n    );\n\n    info!(\"encoded: {:#?}\", hex::encode(&encoded));\n    let (anvil, client) = setup_eth_backend(rpc_url, None).await?;\n    let tx: TypedTransaction = TransactionRequest::default()\n        .to(addr)\n        .from(client.address())\n        .data(encoded)\n        .into();\n    debug!(\"transaction {:#?}\", tx);\n\n    let result = client.call(&tx, None).await;\n\n    if result.is_err() {\n        return Err(Box::new(EvmVerificationError::SolidityExecution));\n    }\n    let result = result?;\n    info!(\"result: {:#?}\", result.to_vec());\n    // decode return bytes value into uint8\n    let result = result.to_vec().last().ok_or(\"no contract output\")? == &1u8;\n    if !result {\n        return Err(Box::new(EvmVerificationError::InvalidProof));\n    }\n\n    let gas = client.estimate_gas(&tx, None).await?;\n\n    info!(\"estimated verify gas cost: {:#?}\", gas);\n\n    // if gas is greater than 30 million warn the user that the gas cost is above ethereum's 30 million block gas limit\n    if gas > 30_000_000.into() {\n        warn!(\n            \"Gas cost of verify transaction is greater than 30 million block gas limit. It will fail on mainnet.\"\n        );\n    } else if gas > 15_000_000.into() {\n        warn!(\n            \"Gas cost of verify transaction is greater than 15 million, the target block size for ethereum\"\n        );\n    }\n\n    drop(anvil);\n    Ok(true)\n}\n\nfn count_decimal_places(num: f32) -> usize {\n    // Convert the number to a string\n    let s = num.to_string();\n\n    // Find the decimal point\n    match s.find('.') {\n        Some(index) => {\n            // Count the number of characters after the decimal point\n            s[index + 1..].len()\n        }\n        None => 0,\n    }\n}\n\n///\npub async fn setup_test_contract<M: 'static + Middleware>(\n    client: Arc<M>,\n    data: &[Vec<FileSourceInner>],\n) -> Result<(ContractInstance<Arc<M>, M>, Vec<u8>), Box<dyn Error>> {\n    // save the abi to a tmp file\n    let mut sol_path = std::env::temp_dir();\n    sol_path.push(\"testreads.sol\");\n    std::fs::write(&sol_path, TESTREADS_SOL)?;\n\n    // Compile the contract\n    let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_path, \"TestReads\", 0)?;\n\n    let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?;\n\n    let mut decimals = vec![];\n    let mut scaled_by_decimals_data = vec![];\n    for input in &data[0] {\n        if input.is_float() {\n            let input = input.to_float() as f32;\n            let decimal_places = count_decimal_places(input) as u8;\n            let scaled_by_decimals = input * f32::powf(10., decimal_places.into());\n            scaled_by_decimals_data.push(I256::from(scaled_by_decimals as i128));\n            decimals.push(decimal_places);\n        } else if input.is_field() {\n            let input = input.to_field(0);\n            let hex_str_fr = format!(\"{:?}\", input);\n            scaled_by_decimals_data.push(I256::from_raw(U256::from_str_radix(&hex_str_fr, 16)?));\n            decimals.push(0);\n        }\n    }\n\n    let contract = factory.deploy(scaled_by_decimals_data)?.send().await?;\n    Ok((contract, decimals))\n}\n\n/// Verify a proof using a Solidity DataAttestation contract.\n/// Used for testing purposes.\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn verify_proof_with_data_attestation(\n    proof: Snark<Fr, G1Affine>,\n    addr_verifier: ethers::types::Address,\n    addr_da: ethers::types::Address,\n    addr_vk: Option<H160>,\n    rpc_url: Option<&str>,\n) -> Result<bool, Box<dyn Error>> {\n    use ethers::abi::{Function, Param, ParamType, StateMutability, Token};\n\n    let mut public_inputs: Vec<U256> = vec![];\n    let flattened_instances = proof.instances.into_iter().flatten();\n\n    for val in flattened_instances.clone() {\n        let bytes = val.to_repr();\n        let u = U256::from_little_endian(bytes.as_slice());\n        public_inputs.push(u);\n    }\n\n    let encoded_verifier = encode_calldata(\n        addr_vk.as_ref().map(|x| x.0),\n        &proof.proof,\n        &flattened_instances.collect::<Vec<_>>(),\n    );\n\n    info!(\"encoded: {:#?}\", hex::encode(&encoded_verifier));\n\n    info!(\"public_inputs: {:#?}\", public_inputs);\n    info!(\n        \"proof: {:#?}\",\n        ethers::types::Bytes::from(proof.proof.to_vec())\n    );\n\n    #[allow(deprecated)]\n    let func = Function {\n        name: \"verifyWithDataAttestation\".to_owned(),\n        inputs: vec![\n            Param {\n                name: \"verifier\".to_owned(),\n                kind: ParamType::Address,\n                internal_type: None,\n            },\n            Param {\n                name: \"encoded\".to_owned(),\n                kind: ParamType::Bytes,\n                internal_type: None,\n            },\n        ],\n        outputs: vec![Param {\n            name: \"success\".to_owned(),\n            kind: ParamType::Bool,\n            internal_type: None,\n        }],\n        constant: None,\n        state_mutability: StateMutability::View,\n    };\n\n    let encoded = func.encode_input(&[\n        Token::Address(addr_verifier),\n        Token::Bytes(encoded_verifier),\n    ])?;\n\n    info!(\"encoded: {:#?}\", hex::encode(&encoded));\n    let (anvil, client) = setup_eth_backend(rpc_url, None).await?;\n    let tx: TypedTransaction = TransactionRequest::default()\n        .to(addr_da)\n        .from(client.address())\n        .data(encoded)\n        .into();\n    debug!(\"transaction {:#?}\", tx);\n    info!(\n        \"estimated verify gas cost: {:#?}\",\n        client.estimate_gas(&tx, None).await?\n    );\n\n    let result = client.call(&tx, None).await;\n    if result.is_err() {\n        return Err(Box::new(EvmVerificationError::SolidityExecution));\n    }\n    let result = result?;\n    info!(\"result: {:#?}\", result);\n    // decode return bytes value into uint8\n    let result = result.to_vec().last().ok_or(\"no contract output\")? == &1u8;\n    if !result {\n        return Err(Box::new(EvmVerificationError::InvalidProof));\n    }\n    drop(anvil);\n    Ok(true)\n}\n\n/// get_provider returns a JSON RPC HTTP Provider\npub fn get_provider(rpc_url: &str) -> Result<Provider<Http>, Box<dyn Error>> {\n    let provider = Provider::<Http>::try_from(rpc_url)?;\n    debug!(\"{:#?}\", provider);\n    Ok(provider)\n}\n\n/// Tests on-chain data storage by deploying a contract that stores the network input and or output\n/// data in its storage. It does this by converting the floating point values to integers and storing the\n/// the number of decimals of the floating point value on chain.\npub async fn test_on_chain_data<M: 'static + Middleware>(\n    client: Arc<M>,\n    data: &[Vec<FileSourceInner>],\n) -> Result<Vec<CallsToAccount>, Box<dyn Error>> {\n    let (contract, decimals) = setup_test_contract(client.clone(), data).await?;\n\n    let contract = TestReads::new(contract.address(), client.clone());\n\n    // Get the encoded call data for each input\n    let mut calldata = vec![];\n    for (i, _) in data.iter().flatten().enumerate() {\n        let function = contract.method::<_, I256>(\"arr\", i as u32)?;\n        let call = function.calldata().ok_or(\"could not get calldata\")?;\n        // Push (call, decimals) to the calldata vector.\n        calldata.push((hex::encode(call), decimals[i]));\n    }\n    // Instantiate a new CallsToAccount struct\n    let calls_to_account = CallsToAccount {\n        call_data: calldata,\n        address: hex::encode(contract.address().as_bytes()),\n    };\n    info!(\"calls_to_account: {:#?}\", calls_to_account);\n    Ok(vec![calls_to_account])\n}\n\n/// Reads on-chain inputs, returning the raw encoded data returned from making all the calls in on_chain_input_data\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn read_on_chain_inputs<M: 'static + Middleware>(\n    client: Arc<M>,\n    address: H160,\n    data: &Vec<CallsToAccount>,\n) -> Result<(Vec<Bytes>, Vec<u8>), Box<dyn Error>> {\n    // Iterate over all on-chain inputs\n    let mut fetched_inputs = vec![];\n    let mut decimals = vec![];\n    for on_chain_data in data {\n        // Construct the address\n        let contract_address_bytes = hex::decode(on_chain_data.address.clone())?;\n        let contract_address = H160::from_slice(&contract_address_bytes);\n        for (call_data, decimal) in &on_chain_data.call_data {\n            let call_data_bytes = hex::decode(call_data.clone())?;\n            let tx: TypedTransaction = TransactionRequest::default()\n                .to(contract_address)\n                .from(address)\n                .data(call_data_bytes)\n                .into();\n            debug!(\"transaction {:#?}\", tx);\n\n            let result = client.call(&tx, None).await?;\n            debug!(\"return data {:#?}\", result);\n            fetched_inputs.push(result);\n            decimals.push(*decimal);\n        }\n    }\n    Ok((fetched_inputs, decimals))\n}\n\n///\n#[cfg(not(target_arch = \"wasm32\"))]\npub async fn evm_quantize<M: 'static + Middleware>(\n    client: Arc<M>,\n    scales: Vec<crate::Scale>,\n    data: &(Vec<ethers::types::Bytes>, Vec<u8>),\n) -> Result<Vec<Fr>, Box<dyn Error>> {\n    // save the sol to a tmp file\n    let mut sol_path = std::env::temp_dir();\n    sol_path.push(\"quantizedata.sol\");\n    std::fs::write(&sol_path, QUANTIZE_DATA_SOL)?;\n\n    let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_path, \"QuantizeData\", 0)?;\n    let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?;\n\n    let contract = factory.deploy(())?.send().await?;\n\n    let contract = QuantizeData::new(contract.address(), client.clone());\n\n    let fetched_inputs = data.0.clone();\n    let decimals = data.1.clone();\n\n    let fetched_inputs = fetched_inputs\n        .iter()\n        .map(|x| Result::<_, std::convert::Infallible>::Ok(ethers::types::Bytes::from(x.to_vec())))\n        .collect::<Result<Vec<Bytes>, _>>()?;\n\n    let decimals = decimals\n        .iter()\n        .map(|x| U256::from_dec_str(&x.to_string()))\n        .collect::<Result<Vec<U256>, _>>()?;\n\n    let scales = scales\n        .iter()\n        .map(|x| U256::from_dec_str(&x.to_string()))\n        .collect::<Result<Vec<U256>, _>>()?;\n\n    info!(\"scales: {:#?}\", scales);\n    info!(\"decimals: {:#?}\", decimals);\n    info!(\"fetched_inputs: {:#?}\", fetched_inputs);\n\n    let results = contract\n        .quantize_data(fetched_inputs, decimals, scales)\n        .call()\n        .await?;\n\n    let felts = contract.to_field_element(results.clone()).call().await?;\n    info!(\"evm quantization contract results: {:#?}\", felts,);\n\n    let results = felts\n        .iter()\n        .map(|x| PrimeField::from_str_vartime(&x.to_string()).unwrap())\n        .collect::<Vec<Fr>>();\n    info!(\"evm quantization results: {:#?}\", results,);\n    Ok(results.to_vec())\n}\n\n/// Generates the contract factory for a solidity verifier, optionally compiling the code with optimizer runs set on the Solc compiler.\nfn get_sol_contract_factory<M: 'static + Middleware>(\n    abi: Contract,\n    bytecode: Bytes,\n    runtime_bytecode: Bytes,\n    client: Arc<M>,\n) -> Result<ContractFactory<M>, Box<dyn Error>> {\n    const MAX_RUNTIME_BYTECODE_SIZE: usize = 24577;\n    let size = runtime_bytecode.len();\n    debug!(\"runtime bytecode size: {:#?}\", size);\n    if size > MAX_RUNTIME_BYTECODE_SIZE {\n        // `_runtime_bytecode` exceeds the limit\n        warn!(\n            \"Solidity runtime bytecode size is: {:#?},\n            which exceeds 24577 bytes spurious dragon limit.\n            Contract will fail to deploy on any chain with \n            EIP 140 enabled\",\n            size\n        );\n    }\n    Ok(ContractFactory::new(abi, bytecode, client))\n}\n\n/// Compiles a solidity verifier contract and returns the abi, bytecode, and runtime bytecode\n#[cfg(not(target_arch = \"wasm32\"))]\npub fn get_contract_artifacts(\n    sol_code_path: PathBuf,\n    contract_name: &str,\n    runs: usize,\n) -> Result<(Contract, Bytes, Bytes), Box<dyn Error>> {\n    if !sol_code_path.exists() {\n        return Err(\"sol_code_path does not exist\".into());\n    }\n    // Create the compiler input, enabling the optimizer and setting the optimzer runs.\n    let input: CompilerInput = if runs > 0 {\n        let mut i = CompilerInput::new(sol_code_path)?[0]\n            .clone()\n            .optimizer(runs);\n        i.settings.optimizer.enable();\n        i\n    } else {\n        CompilerInput::new(sol_code_path)?[0].clone()\n    };\n    let compiled = Solc::default().compile(&input)?;\n\n    let (abi, bytecode, runtime_bytecode) = match compiled.find(contract_name) {\n        Some(c) => c.into_parts_or_default(),\n        None => {\n            return Err(\"could not find contract\".into());\n        }\n    };\n    Ok((abi, bytecode, runtime_bytecode))\n}\n\n/// Sets the constants stored in the da verifier\npub fn fix_da_sol(\n    input_data: Option<Vec<CallsToAccount>>,\n    output_data: Option<Vec<CallsToAccount>>,\n) -> Result<String, Box<dyn Error>> {\n    let mut accounts_len = 0;\n    let mut contract = ATTESTDATA_SOL.to_string();\n    let load_instances = LOADINSTANCES_SOL.to_string();\n    // replace the import statement with the load_instances contract, not including the\n    // `SPDX-License-Identifier: MIT pragma solidity ^0.8.20;` at the top of the file\n    contract = contract.replace(\n        \"import './LoadInstances.sol';\",\n        &load_instances[load_instances\n            .find(\"contract\")\n            .ok_or(\"could not get load-instances contract\")?..],\n    );\n\n    // fill in the quantization params and total calls\n    // as constants to the contract to save on gas\n    if let Some(input_data) = input_data {\n        let input_calls: usize = input_data.iter().map(|v| v.call_data.len()).sum();\n        accounts_len = input_data.len();\n        contract = contract.replace(\n            \"uint256 constant INPUT_CALLS = 0;\",\n            &format!(\"uint256 constant INPUT_CALLS = {};\", input_calls),\n        );\n    }\n    if let Some(output_data) = output_data {\n        let output_calls: usize = output_data.iter().map(|v| v.call_data.len()).sum();\n        accounts_len += output_data.len();\n        contract = contract.replace(\n            \"uint256 constant OUTPUT_CALLS = 0;\",\n            &format!(\"uint256 constant OUTPUT_CALLS = {};\", output_calls),\n        );\n    }\n    contract = contract.replace(\"AccountCall[]\", &format!(\"AccountCall[{}]\", accounts_len));\n\n    Ok(contract)\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/execute.rs",
        "content": "use crate::circuit::CheckMode;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::commands::CalibrationTarget;\nuse crate::commands::Commands;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::commands::H160Flag;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::eth::{deploy_contract_via_solidity, deploy_da_verifier_via_solidity};\n#[cfg(not(target_arch = \"wasm32\"))]\n#[allow(unused_imports)]\nuse crate::eth::{fix_da_sol, get_contract_artifacts, verify_proof_via_solidity};\nuse crate::graph::input::GraphData;\nuse crate::graph::{GraphCircuit, GraphSettings, GraphWitness, Model};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::graph::{TestDataSource, TestSources};\nuse crate::pfsys::evm::aggregation_kzg::{AggregationCircuit, PoseidonTranscript};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::pfsys::{\n    create_keys, load_pk, load_vk, save_params, save_pk, Snark, StrategyType, TranscriptType,\n};\nuse crate::pfsys::{\n    create_proof_circuit, swap_proof_commitments_polycommit, verify_proof_circuit, ProofSplitCommit,\n};\nuse crate::pfsys::{save_vk, srs::*};\nuse crate::tensor::TensorError;\nuse crate::{Commitments, RunArgs};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored::Colorize;\n#[cfg(unix)]\nuse gag::Gag;\nuse halo2_proofs::dev::VerifyFailure;\nuse halo2_proofs::plonk::{self, Circuit};\nuse halo2_proofs::poly::commitment::{CommitmentScheme, Params};\nuse halo2_proofs::poly::commitment::{ParamsProver, Verifier};\nuse halo2_proofs::poly::ipa::commitment::{IPACommitmentScheme, ParamsIPA};\nuse halo2_proofs::poly::ipa::multiopen::{ProverIPA, VerifierIPA};\nuse halo2_proofs::poly::ipa::strategy::AccumulatorStrategy as IPAAccumulatorStrategy;\nuse halo2_proofs::poly::ipa::strategy::SingleStrategy as IPASingleStrategy;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK};\nuse halo2_proofs::poly::kzg::strategy::AccumulatorStrategy as KZGAccumulatorStrategy;\nuse halo2_proofs::poly::kzg::{\n    commitment::ParamsKZG, strategy::SingleStrategy as KZGSingleStrategy,\n};\nuse halo2_proofs::poly::VerificationStrategy;\nuse halo2_proofs::transcript::{EncodedChallenge, TranscriptReadBuffer};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse halo2_solidity_verifier;\nuse halo2curves::bn256::{Bn256, Fr, G1Affine};\nuse halo2curves::ff::{FromUniformBytes, WithSmallOrderMulGroup};\nuse halo2curves::serde::SerdeObject;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse indicatif::{ProgressBar, ProgressStyle};\nuse instant::Instant;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse itertools::Itertools;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse log::debug;\nuse log::{info, trace, warn};\nuse serde::de::DeserializeOwned;\nuse serde::Serialize;\nuse snark_verifier::loader::native::NativeLoader;\nuse snark_verifier::system::halo2::compile;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse snark_verifier::system::halo2::Config;\nuse std::error::Error;\nuse std::fs::File;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::io::{Cursor, Write};\nuse std::path::Path;\nuse std::path::PathBuf;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::process::Command;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::sync::OnceLock;\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::EZKL_BUF_CAPACITY;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::io::BufWriter;\nuse std::time::Duration;\nuse tabled::Tabled;\nuse thiserror::Error;\n\n#[cfg(not(target_arch = \"wasm32\"))]\nstatic _SOLC_REQUIREMENT: OnceLock<bool> = OnceLock::new();\n#[cfg(not(target_arch = \"wasm32\"))]\nfn check_solc_requirement() {\n    info!(\"checking solc installation..\");\n    _SOLC_REQUIREMENT.get_or_init(|| match Command::new(\"solc\").arg(\"--version\").output() {\n        Ok(output) => {\n            debug!(\"solc output: {:#?}\", output);\n            debug!(\"solc output success: {:#?}\", output.status.success());\n            if !output.status.success() {\n                log::error!(\n                    \"`solc` check failed: {}\",\n                    String::from_utf8_lossy(&output.stderr)\n                );\n                return false;\n            }\n            debug!(\"solc check passed, proceeding\");\n            true\n        }\n        Err(_) => {\n            log::error!(\"`solc` check failed: solc not found\");\n            false\n        }\n    });\n}\n\nuse lazy_static::lazy_static;\n\nlazy_static! {\n    #[derive(Debug)]\n    /// The path to the ezkl related data.\n    pub static ref EZKL_REPO_PATH: String =\n        std::env::var(\"EZKL_REPO_PATH\").unwrap_or_else(|_|\n            // $HOME/.ezkl/\n            format!(\"{}/.ezkl\", std::env::var(\"HOME\").unwrap())\n        );\n\n    /// The path to the ezkl related data (SRS)\n    pub static ref EZKL_SRS_REPO_PATH: String = format!(\"{}/srs\", *EZKL_REPO_PATH);\n\n}\n\n/// A wrapper for tensor related errors.\n#[derive(Debug, Error)]\npub enum ExecutionError {\n    /// Shape mismatch in a operation\n    #[error(\"verification failed\")]\n    VerifyError(Vec<VerifyFailure>),\n}\n\nlazy_static::lazy_static! {\n    // read from env EZKL_WORKING_DIR var or default to current dir\n    static ref WORKING_DIR: PathBuf = {\n        let wd = std::env::var(\"EZKL_WORKING_DIR\").unwrap_or_else(|_| \".\".to_string());\n        PathBuf::from(wd)\n    };\n}\n\n/// Run an ezkl command with given args\npub async fn run(command: Commands) -> Result<String, Box<dyn Error>> {\n    // set working dir\n    std::env::set_current_dir(WORKING_DIR.as_path())?;\n\n    match command {\n        #[cfg(feature = \"empty-cmd\")]\n        Commands::Empty => Ok(String::new()),\n        Commands::GenSrs {\n            srs_path,\n            logrows,\n            commitment,\n        } => gen_srs_cmd(srs_path, logrows as u32, commitment),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::GetSrs {\n            srs_path,\n            settings_path,\n            logrows,\n            commitment,\n        } => get_srs_cmd(srs_path, settings_path, logrows, commitment).await,\n        Commands::Table { model, args } => table(model, args),\n        Commands::GenSettings {\n            model,\n            settings_path,\n            args,\n        } => gen_circuit_settings(model, settings_path, args),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::CalibrateSettings {\n            model,\n            settings_path,\n            data,\n            target,\n            lookup_safety_margin,\n            scales,\n            scale_rebase_multiplier,\n            max_logrows,\n            only_range_check_rebase,\n        } => calibrate(\n            model,\n            data,\n            settings_path,\n            target,\n            lookup_safety_margin,\n            scales,\n            scale_rebase_multiplier,\n            only_range_check_rebase,\n            max_logrows,\n        )\n        .map(|e| serde_json::to_string(&e).unwrap()),\n        Commands::GenWitness {\n            data,\n            compiled_circuit,\n            output,\n            vk_path,\n            srs_path,\n        } => gen_witness(compiled_circuit, data, Some(output), vk_path, srs_path)\n            .map(|e| serde_json::to_string(&e).unwrap()),\n        Commands::Mock { model, witness } => mock(model, witness),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::CreateEvmVerifier {\n            vk_path,\n            srs_path,\n            settings_path,\n            sol_code_path,\n            abi_path,\n            render_vk_seperately,\n        } => create_evm_verifier(\n            vk_path,\n            srs_path,\n            settings_path,\n            sol_code_path,\n            abi_path,\n            render_vk_seperately,\n        ),\n        Commands::CreateEvmVK {\n            vk_path,\n            srs_path,\n            settings_path,\n            sol_code_path,\n            abi_path,\n        } => create_evm_vk(vk_path, srs_path, settings_path, sol_code_path, abi_path),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::CreateEvmDataAttestation {\n            settings_path,\n            sol_code_path,\n            abi_path,\n            data,\n        } => create_evm_data_attestation(settings_path, sol_code_path, abi_path, data),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::CreateEvmVerifierAggr {\n            vk_path,\n            srs_path,\n            sol_code_path,\n            abi_path,\n            aggregation_settings,\n            logrows,\n            render_vk_seperately,\n        } => create_evm_aggregate_verifier(\n            vk_path,\n            srs_path,\n            sol_code_path,\n            abi_path,\n            aggregation_settings,\n            logrows,\n            render_vk_seperately,\n        ),\n        Commands::CompileCircuit {\n            model,\n            compiled_circuit,\n            settings_path,\n        } => compile_circuit(model, compiled_circuit, settings_path),\n        Commands::Setup {\n            compiled_circuit,\n            srs_path,\n            vk_path,\n            pk_path,\n            witness,\n            disable_selector_compression,\n        } => setup(\n            compiled_circuit,\n            srs_path,\n            vk_path,\n            pk_path,\n            witness,\n            disable_selector_compression,\n        ),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::SetupTestEvmData {\n            data,\n            compiled_circuit,\n            test_data,\n            rpc_url,\n            input_source,\n            output_source,\n        } => {\n            setup_test_evm_witness(\n                data,\n                compiled_circuit,\n                test_data,\n                rpc_url,\n                input_source,\n                output_source,\n            )\n            .await\n        }\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::TestUpdateAccountCalls {\n            addr,\n            data,\n            rpc_url,\n        } => test_update_account_calls(addr, data, rpc_url).await,\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::SwapProofCommitments {\n            proof_path,\n            witness_path,\n        } => swap_proof_commitments_cmd(proof_path, witness_path)\n            .map(|e| serde_json::to_string(&e).unwrap()),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::Prove {\n            witness,\n            compiled_circuit,\n            pk_path,\n            proof_path,\n            srs_path,\n            proof_type,\n            check_mode,\n        } => prove(\n            witness,\n            compiled_circuit,\n            pk_path,\n            Some(proof_path),\n            srs_path,\n            proof_type,\n            check_mode,\n        )\n        .map(|e| serde_json::to_string(&e).unwrap()),\n        Commands::MockAggregate {\n            aggregation_snarks,\n            logrows,\n            split_proofs,\n        } => mock_aggregate(aggregation_snarks, logrows, split_proofs),\n        Commands::SetupAggregate {\n            sample_snarks,\n            vk_path,\n            pk_path,\n            srs_path,\n            logrows,\n            split_proofs,\n            disable_selector_compression,\n            commitment,\n        } => setup_aggregate(\n            sample_snarks,\n            vk_path,\n            pk_path,\n            srs_path,\n            logrows,\n            split_proofs,\n            disable_selector_compression,\n            commitment.into(),\n        ),\n        Commands::Aggregate {\n            proof_path,\n            aggregation_snarks,\n            pk_path,\n            srs_path,\n            transcript,\n            logrows,\n            check_mode,\n            split_proofs,\n            commitment,\n        } => aggregate(\n            proof_path,\n            aggregation_snarks,\n            pk_path,\n            srs_path,\n            transcript,\n            logrows,\n            check_mode,\n            split_proofs,\n            commitment.into(),\n        )\n        .map(|e| serde_json::to_string(&e).unwrap()),\n        Commands::Verify {\n            proof_path,\n            settings_path,\n            vk_path,\n            srs_path,\n            reduced_srs,\n        } => verify(proof_path, settings_path, vk_path, srs_path, reduced_srs)\n            .map(|e| serde_json::to_string(&e).unwrap()),\n        Commands::VerifyAggr {\n            proof_path,\n            vk_path,\n            srs_path,\n            reduced_srs,\n            logrows,\n            commitment,\n        } => verify_aggr(\n            proof_path,\n            vk_path,\n            srs_path,\n            logrows,\n            reduced_srs,\n            commitment.into(),\n        )\n        .map(|e| serde_json::to_string(&e).unwrap()),\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::DeployEvmVerifier {\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n        } => {\n            deploy_evm(\n                sol_code_path,\n                rpc_url,\n                addr_path,\n                optimizer_runs,\n                private_key,\n                \"Halo2Verifier\",\n            )\n            .await\n        }\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::DeployEvmVK {\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n        } => {\n            deploy_evm(\n                sol_code_path,\n                rpc_url,\n                addr_path,\n                optimizer_runs,\n                private_key,\n                \"Halo2VerifyingKey\",\n            )\n            .await\n        }\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::DeployEvmDataAttestation {\n            data,\n            settings_path,\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n        } => {\n            deploy_da_evm(\n                data,\n                settings_path,\n                sol_code_path,\n                rpc_url,\n                addr_path,\n                optimizer_runs,\n                private_key,\n            )\n            .await\n        }\n        #[cfg(not(target_arch = \"wasm32\"))]\n        Commands::VerifyEvm {\n            proof_path,\n            addr_verifier,\n            rpc_url,\n            addr_da,\n            addr_vk,\n        } => verify_evm(proof_path, addr_verifier, rpc_url, addr_da, addr_vk).await,\n    }\n}\n\n/// Get the srs path\npub fn get_srs_path(logrows: u32, srs_path: Option<PathBuf>, commitment: Commitments) -> PathBuf {\n    if let Some(srs_path) = srs_path {\n        srs_path\n    } else {\n        if !Path::new(&*EZKL_SRS_REPO_PATH).exists() {\n            std::fs::create_dir_all(&*EZKL_SRS_REPO_PATH).unwrap();\n        }\n        match commitment {\n            Commitments::KZG => Path::new(&*EZKL_SRS_REPO_PATH).join(format!(\"kzg{}.srs\", logrows)),\n            Commitments::IPA => Path::new(&*EZKL_SRS_REPO_PATH).join(format!(\"ipa{}.srs\", logrows)),\n        }\n    }\n}\n\nfn srs_exists_check(logrows: u32, srs_path: Option<PathBuf>, commitment: Commitments) -> bool {\n    Path::new(&get_srs_path(logrows, srs_path, commitment)).exists()\n}\n\npub(crate) fn gen_srs_cmd(\n    srs_path: PathBuf,\n    logrows: u32,\n    commitment: Commitments,\n) -> Result<String, Box<dyn Error>> {\n    match commitment {\n        Commitments::KZG => {\n            let params = gen_srs::<KZGCommitmentScheme<Bn256>>(logrows);\n            save_params::<KZGCommitmentScheme<Bn256>>(&srs_path, &params)?;\n        }\n        Commitments::IPA => {\n            let params = gen_srs::<IPACommitmentScheme<G1Affine>>(logrows);\n            save_params::<IPACommitmentScheme<G1Affine>>(&srs_path, &params)?;\n        }\n    }\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nasync fn fetch_srs(uri: &str) -> Result<Vec<u8>, Box<dyn Error>> {\n    let pb = {\n        let pb = init_spinner();\n        pb.set_message(\"Downloading SRS (this may take a while) ...\");\n        pb\n    };\n    let client = reqwest::Client::new();\n    // wasm doesn't require it to be mutable\n    #[allow(unused_mut)]\n    let mut resp = client.get(uri).body(vec![]).send().await?;\n    let mut buf = vec![];\n    while let Some(chunk) = resp.chunk().await? {\n        buf.extend(chunk.to_vec());\n    }\n\n    pb.finish_with_message(\"SRS downloaded.\");\n    Ok(std::mem::take(&mut buf))\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn get_file_hash(path: &PathBuf) -> Result<String, Box<dyn Error>> {\n    use std::io::Read;\n    let file = std::fs::File::open(path)?;\n    let mut reader = std::io::BufReader::new(file);\n    let mut buffer = vec![];\n    let bytes_read = reader.read_to_end(&mut buffer)?;\n    info!(\n        \"read {} bytes from file (vector of len = {})\",\n        bytes_read,\n        buffer.len()\n    );\n\n    let hash = sha256::digest(buffer);\n    info!(\"file hash: {}\", hash);\n\n    Ok(hash)\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn check_srs_hash(\n    logrows: u32,\n    srs_path: Option<PathBuf>,\n    commitment: Commitments,\n) -> Result<String, Box<dyn Error>> {\n    let path = get_srs_path(logrows, srs_path, commitment);\n    let hash = get_file_hash(&path)?;\n\n    let predefined_hash = match crate::srs_sha::PUBLIC_SRS_SHA256_HASHES.get(&logrows) {\n        Some(h) => h,\n        None => return Err(format!(\"SRS (k={}) hash not found in public set\", logrows).into()),\n    };\n\n    if hash != *predefined_hash {\n        // delete file\n        warn!(\"removing SRS file at {}\", path.display());\n        std::fs::remove_file(path)?;\n        return Err(\n            \"SRS hash does not match the expected hash. Remote SRS may have been tampered with.\"\n                .into(),\n        );\n    }\n    Ok(hash)\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn get_srs_cmd(\n    srs_path: Option<PathBuf>,\n    settings_path: Option<PathBuf>,\n    logrows: Option<u32>,\n    commitment: Option<Commitments>,\n) -> Result<String, Box<dyn Error>> {\n    // logrows overrides settings\n\n    let err_string = \"You will need to provide a valid settings file to use the settings option. You should run gen-settings to generate a settings file (and calibrate-settings to pick optimal logrows).\";\n\n    let k = if let Some(k) = logrows {\n        k\n    } else if let Some(settings_p) = &settings_path {\n        if settings_p.exists() {\n            let settings = GraphSettings::load(settings_p)?;\n            settings.run_args.logrows\n        } else {\n            return Err(err_string.into());\n        }\n    } else {\n        return Err(err_string.into());\n    };\n\n    let commitment = if let Some(c) = commitment {\n        c\n    } else if let Some(settings_p) = settings_path {\n        if settings_p.exists() {\n            let settings = GraphSettings::load(&settings_p)?;\n            settings.run_args.commitment.into()\n        } else {\n            return Err(err_string.into());\n        }\n    } else {\n        return Err(err_string.into());\n    };\n\n    if !srs_exists_check(k, srs_path.clone(), commitment) {\n        if matches!(commitment, Commitments::KZG) {\n            info!(\"SRS does not exist, downloading...\");\n            let srs_uri = format!(\"{}{}\", PUBLIC_SRS_URL, k);\n            let mut reader = Cursor::new(fetch_srs(&srs_uri).await?);\n            // check the SRS\n            #[cfg(not(target_arch = \"wasm32\"))]\n            let pb = init_spinner();\n            #[cfg(not(target_arch = \"wasm32\"))]\n            pb.set_message(\"Validating SRS (this may take a while) ...\");\n            let params = ParamsKZG::<Bn256>::read(&mut reader)?;\n            #[cfg(not(target_arch = \"wasm32\"))]\n            pb.finish_with_message(\"SRS validated.\");\n\n            info!(\"Saving SRS to disk...\");\n            let mut file = std::fs::File::create(get_srs_path(k, srs_path.clone(), commitment))?;\n            let mut buffer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, &mut file);\n            params.write(&mut buffer)?;\n\n            info!(\"Saved SRS to disk.\");\n\n            info!(\"SRS downloaded\");\n        } else {\n            let path = get_srs_path(k, srs_path.clone(), commitment);\n            gen_srs_cmd(path, k, commitment)?;\n        }\n    } else {\n        info!(\"SRS already exists at that path\");\n    };\n    // check the hash\n    if matches!(commitment, Commitments::KZG) {\n        check_srs_hash(k, srs_path.clone(), commitment)?;\n    }\n\n    Ok(String::new())\n}\n\npub(crate) fn table(model: PathBuf, run_args: RunArgs) -> Result<String, Box<dyn Error>> {\n    let model = Model::from_run_args(&run_args, &model)?;\n    info!(\"\\n {}\", model.table_nodes());\n    Ok(String::new())\n}\n\npub(crate) fn gen_witness(\n    compiled_circuit_path: PathBuf,\n    data: PathBuf,\n    output: Option<PathBuf>,\n    vk_path: Option<PathBuf>,\n    srs_path: Option<PathBuf>,\n) -> Result<GraphWitness, Box<dyn Error>> {\n    // these aren't real values so the sanity checks are mostly meaningless\n\n    let mut circuit = GraphCircuit::load(compiled_circuit_path)?;\n    let data = GraphData::from_path(data)?;\n    let settings = circuit.settings().clone();\n\n    let vk = if let Some(vk) = vk_path {\n        Some(load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(\n            vk,\n            settings.clone(),\n        )?)\n    } else {\n        None\n    };\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    let mut input = circuit.load_graph_input(&data)?;\n    #[cfg(target_arch = \"wasm32\")]\n    let mut input = circuit.load_graph_input(&data)?;\n\n    // if any of the settings have kzg visibility then we need to load the srs\n\n    let commitment: Commitments = settings.run_args.commitment.into();\n\n    let start_time = Instant::now();\n    let witness = if settings.module_requires_polycommit() {\n        if get_srs_path(settings.run_args.logrows, srs_path.clone(), commitment).exists() {\n            match Commitments::from(settings.run_args.commitment) {\n                Commitments::KZG => {\n                    let srs: ParamsKZG<Bn256> = load_params_prover::<KZGCommitmentScheme<Bn256>>(\n                        srs_path.clone(),\n                        settings.run_args.logrows,\n                        commitment,\n                    )?;\n                    circuit.forward::<KZGCommitmentScheme<_>>(\n                        &mut input,\n                        vk.as_ref(),\n                        Some(&srs),\n                        true,\n                    )?\n                }\n                Commitments::IPA => {\n                    let srs: ParamsIPA<G1Affine> =\n                        load_params_prover::<IPACommitmentScheme<G1Affine>>(\n                            srs_path.clone(),\n                            settings.run_args.logrows,\n                            commitment,\n                        )?;\n                    circuit.forward::<IPACommitmentScheme<_>>(\n                        &mut input,\n                        vk.as_ref(),\n                        Some(&srs),\n                        true,\n                    )?\n                }\n            }\n        } else {\n            warn!(\"SRS for poly commit does not exist (will be ignored)\");\n            circuit.forward::<KZGCommitmentScheme<Bn256>>(&mut input, vk.as_ref(), None, true)?\n        }\n    } else {\n        circuit.forward::<KZGCommitmentScheme<Bn256>>(&mut input, vk.as_ref(), None, true)?\n    };\n\n    // print each variable tuple (symbol, value) as symbol=value\n    trace!(\n        \"witness generation {:?} took {:?}\",\n        circuit\n            .settings()\n            .run_args\n            .variables\n            .iter()\n            .map(|v| { format!(\"{}={}\", v.0, v.1) })\n            .collect::<Vec<_>>(),\n        start_time.elapsed()\n    );\n\n    if let Some(output_path) = output {\n        witness.save(output_path)?;\n    }\n\n    // print the witness in debug\n    debug!(\"witness: \\n {}\", witness.as_json()?.to_colored_json_auto()?);\n\n    Ok(witness)\n}\n\n/// Generate a circuit settings file\npub(crate) fn gen_circuit_settings(\n    model_path: PathBuf,\n    params_output: PathBuf,\n    run_args: RunArgs,\n) -> Result<String, Box<dyn Error>> {\n    let circuit = GraphCircuit::from_run_args(&run_args, &model_path)?;\n    let params = circuit.settings();\n    params.save(&params_output)?;\n    Ok(String::new())\n}\n\n// not for wasm targets\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn init_spinner() -> ProgressBar {\n    let pb = indicatif::ProgressBar::new_spinner();\n    pb.set_draw_target(indicatif::ProgressDrawTarget::stdout());\n    pb.enable_steady_tick(Duration::from_millis(200));\n    pb.set_style(\n        ProgressStyle::with_template(\"[{elapsed_precise}] {spinner:.blue} {msg}\")\n            .unwrap()\n            .tick_strings(&[\n                \"------ - \u2728 \",\n                \"------ - \u23f3 \",\n                \"------ - \ud83c\udf0e \",\n                \"------ - \ud83d\udd0e \",\n                \"------ - \ud83e\udd79 \",\n                \"------ - \ud83e\udee0 \",\n                \"------ - \ud83d\udc7e \",\n            ]),\n    );\n    pb\n}\n\n// not for wasm targets\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn init_bar(len: u64) -> ProgressBar {\n    let pb = ProgressBar::new(len);\n    pb.set_draw_target(indicatif::ProgressDrawTarget::stdout());\n    pb.enable_steady_tick(Duration::from_millis(200));\n    let sty = ProgressStyle::with_template(\n        \"[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}\",\n    )\n    .unwrap()\n    .progress_chars(\"##-\");\n    pb.set_style(sty);\n    pb\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored_json::ToColoredJson;\n\n#[derive(Debug, Clone, Tabled)]\n/// Accuracy tearsheet\npub struct AccuracyResults {\n    mean_error: f32,\n    median_error: f32,\n    max_error: f32,\n    min_error: f32,\n    mean_abs_error: f32,\n    median_abs_error: f32,\n    max_abs_error: f32,\n    min_abs_error: f32,\n    mean_squared_error: f32,\n    mean_percent_error: f32,\n    mean_abs_percent_error: f32,\n}\n\nimpl AccuracyResults {\n    /// Create a new accuracy results struct\n    pub fn new(\n        mut original_preds: Vec<crate::tensor::Tensor<f32>>,\n        mut calibrated_preds: Vec<crate::tensor::Tensor<f32>>,\n    ) -> Result<Self, Box<dyn Error>> {\n        let mut errors = vec![];\n        let mut abs_errors = vec![];\n        let mut squared_errors = vec![];\n        let mut percentage_errors = vec![];\n        let mut abs_percentage_errors = vec![];\n\n        for (original, calibrated) in original_preds.iter_mut().zip(calibrated_preds.iter_mut()) {\n            original.flatten();\n            calibrated.flatten();\n            let error = (original.clone() - calibrated.clone())?;\n            let abs_error = error.map(|x| x.abs());\n            let squared_error = error.map(|x| x.powi(2));\n            let percentage_error = error.enum_map(|i, x| {\n                // if everything is 0 then we can't divide by 0 so we just return 0\n                let res = if original[i] == 0.0 && x == 0.0 {\n                    0.0\n                } else {\n                    x / original[i]\n                };\n                Ok::<f32, TensorError>(res)\n            })?;\n            let abs_percentage_error = percentage_error.map(|x| x.abs());\n\n            errors.extend(error);\n            abs_errors.extend(abs_error);\n            squared_errors.extend(squared_error);\n            percentage_errors.extend(percentage_error);\n            abs_percentage_errors.extend(abs_percentage_error);\n        }\n\n        let mean_percent_error =\n            percentage_errors.iter().sum::<f32>() / percentage_errors.len() as f32;\n        let mean_abs_percent_error =\n            abs_percentage_errors.iter().sum::<f32>() / abs_percentage_errors.len() as f32;\n        let mean_error = errors.iter().sum::<f32>() / errors.len() as f32;\n        let median_error = errors[errors.len() / 2];\n        let max_error = *errors\n            .iter()\n            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n            .unwrap();\n        let min_error = *errors\n            .iter()\n            .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n            .unwrap();\n\n        let mean_abs_error = abs_errors.iter().sum::<f32>() / abs_errors.len() as f32;\n        let median_abs_error = abs_errors[abs_errors.len() / 2];\n        let max_abs_error = *abs_errors\n            .iter()\n            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n            .unwrap();\n        let min_abs_error = *abs_errors\n            .iter()\n            .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n            .unwrap();\n\n        let mean_squared_error = squared_errors.iter().sum::<f32>() / squared_errors.len() as f32;\n\n        Ok(Self {\n            mean_error,\n            median_error,\n            max_error,\n            min_error,\n            mean_abs_error,\n            median_abs_error,\n            max_abs_error,\n            min_abs_error,\n            mean_squared_error,\n            mean_percent_error,\n            mean_abs_percent_error,\n        })\n    }\n}\n\n/// Calibrate the circuit parameters to a given a dataset\n#[cfg(not(target_arch = \"wasm32\"))]\n#[allow(trivial_casts)]\n#[allow(clippy::too_many_arguments)]\npub(crate) fn calibrate(\n    model_path: PathBuf,\n    data: PathBuf,\n    settings_path: PathBuf,\n    target: CalibrationTarget,\n    lookup_safety_margin: i128,\n    scales: Option<Vec<crate::Scale>>,\n    scale_rebase_multiplier: Vec<u32>,\n    only_range_check_rebase: bool,\n    max_logrows: Option<u32>,\n) -> Result<GraphSettings, Box<dyn Error>> {\n    use log::error;\n    use std::collections::HashMap;\n    use tabled::Table;\n\n    let data = GraphData::from_path(data)?;\n    // load the pre-generated settings\n    let settings = GraphSettings::load(&settings_path)?;\n    // now retrieve the run args\n    // we load the model to get the input and output shapes\n\n    let model = Model::from_run_args(&settings.run_args, &model_path)?;\n\n    let chunks = data.split_into_batches(model.graph.input_shapes()?)?;\n    info!(\"num calibration batches: {}\", chunks.len());\n\n    debug!(\"running onnx predictions...\");\n    let original_predictions = Model::run_onnx_predictions(\n        &settings.run_args,\n        &model_path,\n        &chunks,\n        model.graph.input_shapes()?,\n    )?;\n\n    let range = if let Some(scales) = scales {\n        scales\n    } else {\n        (11..14).collect::<Vec<crate::Scale>>()\n    };\n\n    let div_rebasing = if only_range_check_rebase {\n        vec![false]\n    } else {\n        vec![true, false]\n    };\n\n    let mut found_params: Vec<GraphSettings> = vec![];\n\n    // 2 x 2 grid\n    let range_grid = range\n        .iter()\n        .cartesian_product(range.iter())\n        .map(|(a, b)| (*a, *b))\n        .collect::<Vec<(crate::Scale, crate::Scale)>>();\n\n    // remove all entries where input_scale > param_scale\n    let mut range_grid = range_grid\n        .into_iter()\n        .filter(|(a, b)| a <= b)\n        .collect::<Vec<(crate::Scale, crate::Scale)>>();\n\n    // if all integers\n    let all_scale_0 = model\n        .graph\n        .get_input_types()?\n        .iter()\n        .all(|t| t.is_integer());\n    if all_scale_0 {\n        // set all a values to 0 then dedup\n        range_grid = range_grid\n            .iter()\n            .map(|(_, b)| (0, *b))\n            .sorted()\n            .dedup()\n            .collect::<Vec<(crate::Scale, crate::Scale)>>();\n    }\n\n    let range_grid = range_grid\n        .iter()\n        .cartesian_product(scale_rebase_multiplier.iter())\n        .map(|(a, b)| (*a, *b))\n        .collect::<Vec<((crate::Scale, crate::Scale), u32)>>();\n\n    let range_grid = range_grid\n        .iter()\n        .cartesian_product(div_rebasing.iter())\n        .map(|(a, b)| (*a, *b))\n        .collect::<Vec<(((crate::Scale, crate::Scale), u32), bool)>>();\n\n    let mut forward_pass_res = HashMap::new();\n\n    let pb = init_bar(range_grid.len() as u64);\n    pb.set_message(\"calibrating...\");\n\n    let mut num_failed = 0;\n    let mut num_passed = 0;\n\n    for (((input_scale, param_scale), scale_rebase_multiplier), div_rebasing) in range_grid {\n        pb.set_message(format!(\n            \"i-scale: {}, p-scale: {}, rebase-(x): {}, div-rebase: {}, fail: {}, pass: {}\",\n            input_scale.to_string().blue(),\n            param_scale.to_string().blue(),\n            scale_rebase_multiplier.to_string().blue(),\n            div_rebasing.to_string().yellow(),\n            num_failed.to_string().red(),\n            num_passed.to_string().green()\n        ));\n\n        let key = (\n            input_scale,\n            param_scale,\n            scale_rebase_multiplier,\n            div_rebasing,\n        );\n        forward_pass_res.insert(key, vec![]);\n\n        let local_run_args = RunArgs {\n            input_scale,\n            param_scale,\n            scale_rebase_multiplier,\n            div_rebasing,\n            ..settings.run_args.clone()\n        };\n\n        // if unix get a gag\n        #[cfg(unix)]\n        let _r = match Gag::stdout() {\n            Ok(g) => Some(g),\n            _ => None,\n        };\n        #[cfg(unix)]\n        let _g = match Gag::stderr() {\n            Ok(g) => Some(g),\n            _ => None,\n        };\n\n        let mut circuit = match GraphCircuit::from_run_args(&local_run_args, &model_path) {\n            Ok(c) => c,\n            Err(e) => {\n                error!(\"circuit creation from run args failed: {:?}\", e);\n                pb.inc(1);\n                num_failed += 1;\n                continue;\n            }\n        };\n\n        let forward_res = chunks\n            .iter()\n            .map(|chunk| {\n                let chunk = chunk.clone();\n\n                let data = circuit\n                    .load_graph_from_file_exclusively(&chunk)\n                    .map_err(|e| format!(\"failed to load circuit inputs: {}\", e))?;\n\n                let forward_res = circuit\n                    .forward::<KZGCommitmentScheme<Bn256>>(&mut data.clone(), None, None, true)\n                    .map_err(|e| format!(\"failed to forward: {}\", e))?;\n\n                // push result to the hashmap\n                forward_pass_res\n                    .get_mut(&key)\n                    .ok_or(\"key not found\")?\n                    .push(forward_res);\n\n                Ok(()) as Result<(), String>\n            })\n            .collect::<Result<Vec<()>, String>>();\n\n        match forward_res {\n            Ok(_) => (),\n            // typically errors will be due to the circuit overflowing the i128 limit\n            Err(e) => {\n                error!(\"forward pass failed: {:?}\", e);\n                pb.inc(1);\n                num_failed += 1;\n                continue;\n            }\n        }\n\n        // drop the gag\n        #[cfg(unix)]\n        drop(_r);\n        #[cfg(unix)]\n        drop(_g);\n\n        let result = forward_pass_res.get(&key).ok_or(\"key not found\")?;\n\n        let min_lookup_range = result\n            .iter()\n            .map(|x| x.min_lookup_inputs)\n            .min()\n            .unwrap_or(0);\n\n        let max_lookup_range = result\n            .iter()\n            .map(|x| x.max_lookup_inputs)\n            .max()\n            .unwrap_or(0);\n\n        let max_range_size = result.iter().map(|x| x.max_range_size).max().unwrap_or(0);\n\n        let res = circuit.calc_min_logrows(\n            (min_lookup_range, max_lookup_range),\n            max_range_size,\n            max_logrows,\n            lookup_safety_margin,\n        );\n\n        if res.is_ok() {\n            let new_settings = circuit.settings().clone();\n\n            let found_run_args = RunArgs {\n                input_scale: new_settings.run_args.input_scale,\n                param_scale: new_settings.run_args.param_scale,\n                div_rebasing: new_settings.run_args.div_rebasing,\n                lookup_range: new_settings.run_args.lookup_range,\n                logrows: new_settings.run_args.logrows,\n                scale_rebase_multiplier: new_settings.run_args.scale_rebase_multiplier,\n                ..settings.run_args.clone()\n            };\n\n            let found_settings = GraphSettings {\n                run_args: found_run_args,\n                required_lookups: new_settings.required_lookups,\n                required_range_checks: new_settings.required_range_checks,\n                model_output_scales: new_settings.model_output_scales,\n                model_input_scales: new_settings.model_input_scales,\n                num_rows: new_settings.num_rows,\n                total_assignments: new_settings.total_assignments,\n                total_const_size: new_settings.total_const_size,\n                ..settings.clone()\n            };\n\n            found_params.push(found_settings.clone());\n\n            debug!(\n                \"found settings: \\n {}\",\n                found_settings.as_json()?.to_colored_json_auto()?\n            );\n            num_passed += 1;\n        } else {\n            error!(\"calibration failed {}\", res.err().unwrap());\n            num_failed += 1;\n        }\n\n        pb.inc(1);\n    }\n\n    pb.finish_with_message(\"Calibration Done.\");\n\n    if found_params.is_empty() {\n        return Err(\"calibration failed, could not find any suitable parameters given the calibration dataset\".into());\n    }\n\n    debug!(\"Found {} sets of parameters\", found_params.len());\n\n    // now find the best params according to the target\n    let mut best_params = match target {\n        CalibrationTarget::Resources { .. } => {\n            let mut param_iterator = found_params.iter().sorted_by_key(|p| p.run_args.logrows);\n\n            let min_logrows = param_iterator\n                .next()\n                .ok_or(\"no params found\")?\n                .run_args\n                .logrows;\n\n            // pick the ones that have the minimum logrows but also the largest scale:\n            // this is the best tradeoff between resource usage and accuracy\n            found_params\n                .iter()\n                .filter(|p| p.run_args.logrows == min_logrows)\n                .max_by_key(|p| {\n                    (\n                        p.run_args.input_scale,\n                        p.run_args.param_scale,\n                        // we want the largest rebase multiplier as it means we can use less constraints\n                        p.run_args.scale_rebase_multiplier,\n                    )\n                })\n                .ok_or(\"no params found\")?\n                .clone()\n        }\n        CalibrationTarget::Accuracy => {\n            let param_iterator = found_params.iter().sorted_by_key(|p| {\n                (\n                    p.run_args.input_scale,\n                    p.run_args.param_scale,\n                    // we want the largest rebase multiplier as it means we can use less constraints\n                    p.run_args.scale_rebase_multiplier,\n                )\n            });\n\n            let last = param_iterator.last().ok_or(\"no params found\")?;\n            let max_scale = (\n                last.run_args.input_scale,\n                last.run_args.param_scale,\n                last.run_args.scale_rebase_multiplier,\n            );\n\n            // pick the ones that have the max scale but also the smallest logrows:\n            // this is the best tradeoff between resource usage and accuracy\n            found_params\n                .iter()\n                .filter(|p| {\n                    (\n                        p.run_args.input_scale,\n                        p.run_args.param_scale,\n                        p.run_args.scale_rebase_multiplier,\n                    ) == max_scale\n                })\n                .min_by_key(|p| p.run_args.logrows)\n                .ok_or(\"no params found\")?\n                .clone()\n        }\n    };\n\n    let outputs = forward_pass_res\n        .get(&(\n            best_params.run_args.input_scale,\n            best_params.run_args.param_scale,\n            best_params.run_args.scale_rebase_multiplier,\n            best_params.run_args.div_rebasing,\n        ))\n        .ok_or(\"no params found\")?\n        .iter()\n        .map(|x| x.get_float_outputs(&best_params.model_output_scales))\n        .collect::<Vec<_>>();\n\n    let accuracy_res = AccuracyResults::new(\n        original_predictions.into_iter().flatten().collect(),\n        outputs.into_iter().flatten().collect(),\n    )?;\n\n    let tear_sheet_table = Table::new(vec![accuracy_res]);\n\n    warn!(\n        \"\\n\\n <------------- Numerical Fidelity Report (input_scale: {}, param_scale: {}, scale_input_multiplier: {}) ------------->\\n\\n{}\\n\\n\",\n        best_params.run_args.input_scale,\n        best_params.run_args.param_scale,\n        best_params.run_args.scale_rebase_multiplier,\n        tear_sheet_table.to_string().as_str()\n    );\n\n    if matches!(target, CalibrationTarget::Resources { col_overflow: true }) {\n        let lookup_log_rows = best_params.lookup_log_rows_with_blinding();\n        let module_log_row = best_params.module_constraint_logrows_with_blinding();\n        let instance_logrows = best_params.log2_total_instances_with_blinding();\n        let dynamic_lookup_logrows = best_params.dynamic_lookup_and_shuffle_logrows_with_blinding();\n\n        let mut reduction = std::cmp::max(lookup_log_rows, module_log_row);\n        reduction = std::cmp::max(reduction, instance_logrows);\n        reduction = std::cmp::max(reduction, dynamic_lookup_logrows);\n        reduction = std::cmp::max(reduction, crate::graph::MIN_LOGROWS);\n\n        info!(\n            \"logrows > bits, shrinking logrows: {} -> {}\",\n            best_params.run_args.logrows, reduction\n        );\n\n        best_params.run_args.logrows = reduction;\n    }\n\n    best_params.save(&settings_path)?;\n\n    debug!(\"Saved parameters.\");\n\n    Ok(best_params)\n}\n\npub(crate) fn mock(\n    compiled_circuit_path: PathBuf,\n    data_path: PathBuf,\n) -> Result<String, Box<dyn Error>> {\n    // mock should catch any issues by default so we set it to safe\n    let mut circuit = GraphCircuit::load(compiled_circuit_path)?;\n\n    let data = GraphWitness::from_path(data_path)?;\n\n    circuit.load_graph_witness(&data)?;\n\n    let public_inputs = circuit.prepare_public_inputs(&data)?;\n\n    info!(\"Mock proof\");\n\n    let prover = halo2_proofs::dev::MockProver::run(\n        circuit.settings().run_args.logrows,\n        &circuit,\n        vec![public_inputs],\n    )\n    .map_err(Box::<dyn Error>::from)?;\n    prover\n        .verify()\n        .map_err(|e| Box::<dyn Error>::from(ExecutionError::VerifyError(e)))?;\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn create_evm_verifier(\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n    render_vk_seperately: bool,\n) -> Result<String, Box<dyn Error>> {\n    check_solc_requirement();\n\n    let settings = GraphSettings::load(&settings_path)?;\n    let commitment: Commitments = settings.run_args.commitment.into();\n    let params = load_params_verifier::<KZGCommitmentScheme<Bn256>>(\n        srs_path,\n        settings.run_args.logrows,\n        commitment,\n    )?;\n\n    let num_instance = settings.total_instances();\n    let num_instance: usize = num_instance.iter().sum::<usize>();\n\n    let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)?;\n    trace!(\"params computed\");\n\n    let generator = halo2_solidity_verifier::SolidityGenerator::new(\n        &params,\n        &vk,\n        halo2_solidity_verifier::BatchOpenScheme::Bdfg21,\n        num_instance,\n    );\n    let verifier_solidity = if render_vk_seperately {\n        generator.render_separately()?.0 // ignore the rendered vk for now and generate it in create_evm_vk\n    } else {\n        generator.render()?\n    };\n\n    File::create(sol_code_path.clone())?.write_all(verifier_solidity.as_bytes())?;\n\n    // fetch abi of the contract\n    let (abi, _, _) = get_contract_artifacts(sol_code_path, \"Halo2Verifier\", 0)?;\n    // save abi to file\n    serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?;\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn create_evm_vk(\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n) -> Result<String, Box<dyn Error>> {\n    check_solc_requirement();\n    let settings = GraphSettings::load(&settings_path)?;\n    let commitment: Commitments = settings.run_args.commitment.into();\n    let params = load_params_verifier::<KZGCommitmentScheme<Bn256>>(\n        srs_path,\n        settings.run_args.logrows,\n        commitment,\n    )?;\n\n    let num_instance = settings.total_instances();\n    let num_instance: usize = num_instance.iter().sum::<usize>();\n\n    let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)?;\n    trace!(\"params computed\");\n\n    let generator = halo2_solidity_verifier::SolidityGenerator::new(\n        &params,\n        &vk,\n        halo2_solidity_verifier::BatchOpenScheme::Bdfg21,\n        num_instance,\n    );\n\n    let vk_solidity = generator.render_separately()?.1;\n\n    File::create(sol_code_path.clone())?.write_all(vk_solidity.as_bytes())?;\n\n    // fetch abi of the contract\n    let (abi, _, _) = get_contract_artifacts(sol_code_path, \"Halo2VerifyingKey\", 0)?;\n    // save abi to file\n    serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?;\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn create_evm_data_attestation(\n    settings_path: PathBuf,\n    _sol_code_path: PathBuf,\n    _abi_path: PathBuf,\n    _input: PathBuf,\n) -> Result<String, Box<dyn Error>> {\n    #[allow(unused_imports)]\n    use crate::graph::{DataSource, VarVisibility};\n    check_solc_requirement();\n\n    let settings = GraphSettings::load(&settings_path)?;\n\n    let visibility = VarVisibility::from_args(&settings.run_args)?;\n    trace!(\"params computed\");\n\n    let data = GraphData::from_path(_input)?;\n\n    let output_data = if let Some(DataSource::OnChain(source)) = data.output_data {\n        if visibility.output.is_private() {\n            return Err(\"private output data on chain is not supported on chain\".into());\n        }\n        let mut on_chain_output_data = vec![];\n        for call in source.calls {\n            on_chain_output_data.push(call);\n        }\n        Some(on_chain_output_data)\n    } else {\n        None\n    };\n\n    let input_data = if let DataSource::OnChain(source) = data.input_data {\n        if visibility.input.is_private() {\n            return Err(\"private input data on chain is not supported on chain\".into());\n        }\n        let mut on_chain_input_data = vec![];\n        for call in source.calls {\n            on_chain_input_data.push(call);\n        }\n        Some(on_chain_input_data)\n    } else {\n        None\n    };\n\n    if input_data.is_some() || output_data.is_some() {\n        let output = fix_da_sol(input_data, output_data)?;\n        let mut f = File::create(_sol_code_path.clone())?;\n        let _ = f.write(output.as_bytes());\n        // fetch abi of the contract\n        let (abi, _, _) = get_contract_artifacts(_sol_code_path, \"DataAttestation\", 0)?;\n        // save abi to file\n        serde_json::to_writer(std::fs::File::create(_abi_path)?, &abi)?;\n    } else {\n        return Err(\n            \"Neither input or output data source is on-chain. Atleast one must be on chain.\".into(),\n        );\n    }\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn deploy_da_evm(\n    data: PathBuf,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    rpc_url: Option<String>,\n    addr_path: PathBuf,\n    runs: usize,\n    private_key: Option<String>,\n) -> Result<String, Box<dyn Error>> {\n    check_solc_requirement();\n    let contract_address = deploy_da_verifier_via_solidity(\n        settings_path,\n        data,\n        sol_code_path,\n        rpc_url.as_deref(),\n        runs,\n        private_key.as_deref(),\n    )\n    .await?;\n    info!(\"Contract deployed at: {}\", contract_address);\n\n    let mut f = File::create(addr_path)?;\n    write!(f, \"{:#?}\", contract_address)?;\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn deploy_evm(\n    sol_code_path: PathBuf,\n    rpc_url: Option<String>,\n    addr_path: PathBuf,\n    runs: usize,\n    private_key: Option<String>,\n    contract_name: &str,\n) -> Result<String, Box<dyn Error>> {\n    check_solc_requirement();\n    let contract_address = deploy_contract_via_solidity(\n        sol_code_path,\n        rpc_url.as_deref(),\n        runs,\n        private_key.as_deref(),\n        contract_name,\n    )\n    .await?;\n\n    info!(\"Contract deployed at: {:#?}\", contract_address);\n\n    let mut f = File::create(addr_path)?;\n    write!(f, \"{:#?}\", contract_address)?;\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn verify_evm(\n    proof_path: PathBuf,\n    addr_verifier: H160Flag,\n    rpc_url: Option<String>,\n    addr_da: Option<H160Flag>,\n    addr_vk: Option<H160Flag>,\n) -> Result<String, Box<dyn Error>> {\n    use crate::eth::verify_proof_with_data_attestation;\n    check_solc_requirement();\n\n    let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?;\n\n    let result = if let Some(addr_da) = addr_da {\n        verify_proof_with_data_attestation(\n            proof.clone(),\n            addr_verifier.into(),\n            addr_da.into(),\n            addr_vk.map(|s| s.into()),\n            rpc_url.as_deref(),\n        )\n        .await?\n    } else {\n        verify_proof_via_solidity(\n            proof.clone(),\n            addr_verifier.into(),\n            addr_vk.map(|s| s.into()),\n            rpc_url.as_deref(),\n        )\n        .await?\n    };\n\n    info!(\"Solidity verification result: {}\", result);\n\n    if !result {\n        return Err(\"Solidity verification failed\".into());\n    }\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) fn create_evm_aggregate_verifier(\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n    circuit_settings: Vec<PathBuf>,\n    logrows: u32,\n    render_vk_seperately: bool,\n) -> Result<String, Box<dyn Error>> {\n    check_solc_requirement();\n    let srs_path = get_srs_path(logrows, srs_path, Commitments::KZG);\n    let params: ParamsKZG<Bn256> = load_srs_verifier::<KZGCommitmentScheme<Bn256>>(srs_path)?;\n\n    let mut settings: Vec<GraphSettings> = vec![];\n\n    for path in circuit_settings.iter() {\n        let s = GraphSettings::load(path)?;\n        settings.push(s);\n    }\n\n    let num_instance: usize = settings\n        .iter()\n        .map(|s| s.total_instances().iter().sum::<usize>())\n        .sum();\n\n    let num_instance = AggregationCircuit::num_instance(num_instance);\n    assert_eq!(num_instance.len(), 1);\n    let num_instance = num_instance[0];\n\n    let agg_vk = load_vk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(vk_path, ())?;\n\n    let mut generator = halo2_solidity_verifier::SolidityGenerator::new(\n        &params,\n        &agg_vk,\n        halo2_solidity_verifier::BatchOpenScheme::Bdfg21,\n        num_instance,\n    );\n\n    let acc_encoding = halo2_solidity_verifier::AccumulatorEncoding::new(\n        0,\n        AggregationCircuit::num_limbs(),\n        AggregationCircuit::num_bits(),\n    );\n\n    generator = generator.set_acc_encoding(Some(acc_encoding));\n\n    let verifier_solidity = if render_vk_seperately {\n        generator.render_separately()?.0 // ignore the rendered vk for now and generate it in create_evm_vk\n    } else {\n        generator.render()?\n    };\n\n    File::create(sol_code_path.clone())?.write_all(verifier_solidity.as_bytes())?;\n\n    // fetch abi of the contract\n    let (abi, _, _) = get_contract_artifacts(sol_code_path, \"Halo2Verifier\", 0)?;\n    // save abi to file\n    serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?;\n\n    Ok(String::new())\n}\n\npub(crate) fn compile_circuit(\n    model_path: PathBuf,\n    compiled_circuit: PathBuf,\n    settings_path: PathBuf,\n) -> Result<String, Box<dyn Error>> {\n    let settings = GraphSettings::load(&settings_path)?;\n    let circuit = GraphCircuit::from_settings(&settings, &model_path, CheckMode::UNSAFE)?;\n    circuit.save(compiled_circuit)?;\n    Ok(String::new())\n}\n\npub(crate) fn setup(\n    compiled_circuit: PathBuf,\n    srs_path: Option<PathBuf>,\n    vk_path: PathBuf,\n    pk_path: PathBuf,\n    witness: Option<PathBuf>,\n    disable_selector_compression: bool,\n) -> Result<String, Box<dyn Error>> {\n    // these aren't real values so the sanity checks are mostly meaningless\n\n    let mut circuit = GraphCircuit::load(compiled_circuit)?;\n\n    if let Some(witness) = witness {\n        let data = GraphWitness::from_path(witness)?;\n        circuit.load_graph_witness(&data)?;\n    }\n\n    let logrows = circuit.settings().run_args.logrows;\n    let commitment: Commitments = circuit.settings().run_args.commitment.into();\n\n    let pk = match commitment {\n        Commitments::KZG => {\n            let params = load_params_prover::<KZGCommitmentScheme<Bn256>>(\n                srs_path,\n                logrows,\n                Commitments::KZG,\n            )?;\n            create_keys::<KZGCommitmentScheme<Bn256>, GraphCircuit>(\n                &circuit,\n                &params,\n                disable_selector_compression,\n            )?\n        }\n        Commitments::IPA => {\n            let params = load_params_prover::<IPACommitmentScheme<G1Affine>>(\n                srs_path,\n                logrows,\n                Commitments::IPA,\n            )?;\n            create_keys::<IPACommitmentScheme<G1Affine>, GraphCircuit>(\n                &circuit,\n                &params,\n                disable_selector_compression,\n            )?\n        }\n    };\n    save_vk::<G1Affine>(&vk_path, pk.get_vk())?;\n    save_pk::<G1Affine>(&pk_path, &pk)?;\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn setup_test_evm_witness(\n    data_path: PathBuf,\n    compiled_circuit_path: PathBuf,\n    test_data: PathBuf,\n    rpc_url: Option<String>,\n    input_source: TestDataSource,\n    output_source: TestDataSource,\n) -> Result<String, Box<dyn Error>> {\n    use crate::graph::TestOnChainData;\n\n    info!(\"run this command in background to keep the instance running for testing\");\n    let mut data = GraphData::from_path(data_path)?;\n    let mut circuit = GraphCircuit::load(compiled_circuit_path)?;\n\n    // if both input and output are from files fail\n    if matches!(input_source, TestDataSource::File) && matches!(output_source, TestDataSource::File)\n    {\n        return Err(\"Both input and output cannot be from files\".into());\n    }\n\n    let test_on_chain_data = TestOnChainData {\n        data: test_data.clone(),\n        rpc: rpc_url,\n        data_sources: TestSources {\n            input: input_source,\n            output: output_source,\n        },\n    };\n\n    circuit\n        .populate_on_chain_test_data(&mut data, test_on_chain_data)\n        .await?;\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::pfsys::ProofType;\n#[cfg(not(target_arch = \"wasm32\"))]\npub(crate) async fn test_update_account_calls(\n    addr: H160Flag,\n    data: PathBuf,\n    rpc_url: Option<String>,\n) -> Result<String, Box<dyn Error>> {\n    use crate::eth::update_account_calls;\n\n    check_solc_requirement();\n    update_account_calls(addr.into(), data, rpc_url.as_deref()).await?;\n\n    Ok(String::new())\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\n#[allow(clippy::too_many_arguments)]\npub(crate) fn prove(\n    data_path: PathBuf,\n    compiled_circuit_path: PathBuf,\n    pk_path: PathBuf,\n    proof_path: Option<PathBuf>,\n    srs_path: Option<PathBuf>,\n    proof_type: ProofType,\n    check_mode: CheckMode,\n) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> {\n    let data = GraphWitness::from_path(data_path)?;\n    let mut circuit = GraphCircuit::load(compiled_circuit_path)?;\n\n    circuit.load_graph_witness(&data)?;\n\n    let pretty_public_inputs = circuit.pretty_public_inputs(&data)?;\n    let public_inputs = circuit.prepare_public_inputs(&data)?;\n\n    let circuit_settings = circuit.settings().clone();\n\n    let strategy: StrategyType = proof_type.into();\n    let transcript: TranscriptType = proof_type.into();\n    let proof_split_commits: Option<ProofSplitCommit> = data.into();\n\n    let commitment = circuit_settings.run_args.commitment.into();\n    let logrows = circuit_settings.run_args.logrows;\n    // creates and verifies the proof\n    let mut snark = match commitment {\n        Commitments::KZG => {\n            let pk =\n                load_pk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(pk_path, circuit.params())?;\n\n            let params = load_params_prover::<KZGCommitmentScheme<Bn256>>(\n                srs_path,\n                logrows,\n                Commitments::KZG,\n            )?;\n            match strategy {\n                StrategyType::Single => create_proof_circuit::<\n                    KZGCommitmentScheme<Bn256>,\n                    _,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    KZGSingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit,\n                    vec![public_inputs],\n                    &params,\n                    &pk,\n                    check_mode,\n                    commitment,\n                    transcript,\n                    proof_split_commits,\n                    None,\n                ),\n                StrategyType::Accum => {\n                    let protocol = Some(compile(\n                        &params,\n                        pk.get_vk(),\n                        Config::kzg().with_num_instance(vec![public_inputs.len()]),\n                    ));\n\n                    create_proof_circuit::<\n                        KZGCommitmentScheme<Bn256>,\n                        _,\n                        ProverSHPLONK<_>,\n                        VerifierSHPLONK<_>,\n                        KZGAccumulatorStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(\n                        circuit,\n                        vec![public_inputs],\n                        &params,\n                        &pk,\n                        check_mode,\n                        commitment,\n                        transcript,\n                        proof_split_commits,\n                        protocol,\n                    )\n                }\n            }\n        }\n        Commitments::IPA => {\n            let pk =\n                load_pk::<IPACommitmentScheme<G1Affine>, GraphCircuit>(pk_path, circuit.params())?;\n\n            let params = load_params_prover::<IPACommitmentScheme<G1Affine>>(\n                srs_path,\n                circuit_settings.run_args.logrows,\n                Commitments::IPA,\n            )?;\n            match strategy {\n                StrategyType::Single => create_proof_circuit::<\n                    IPACommitmentScheme<G1Affine>,\n                    _,\n                    ProverIPA<_>,\n                    VerifierIPA<_>,\n                    IPASingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit,\n                    vec![public_inputs],\n                    &params,\n                    &pk,\n                    check_mode,\n                    commitment,\n                    transcript,\n                    proof_split_commits,\n                    None,\n                ),\n                StrategyType::Accum => {\n                    let protocol = Some(compile(\n                        &params,\n                        pk.get_vk(),\n                        Config::ipa().with_num_instance(vec![public_inputs.len()]),\n                    ));\n                    create_proof_circuit::<\n                        IPACommitmentScheme<G1Affine>,\n                        _,\n                        ProverIPA<_>,\n                        VerifierIPA<_>,\n                        IPAAccumulatorStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(\n                        circuit,\n                        vec![public_inputs],\n                        &params,\n                        &pk,\n                        check_mode,\n                        commitment,\n                        transcript,\n                        proof_split_commits,\n                        protocol,\n                    )\n                }\n            }\n        }\n    }?;\n\n    snark.pretty_public_inputs = pretty_public_inputs;\n\n    if let Some(proof_path) = proof_path {\n        snark.save(&proof_path)?;\n    }\n\n    Ok(snark)\n}\n\npub(crate) fn swap_proof_commitments_cmd(\n    proof_path: PathBuf,\n    witness: PathBuf,\n) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> {\n    let snark = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?;\n    let witness = GraphWitness::from_path(witness)?;\n    let commitments = witness.get_polycommitments();\n\n    if commitments.is_empty() {\n        log::warn!(\"no commitments found in witness\");\n    }\n\n    let snark_new = swap_proof_commitments_polycommit(&snark, &commitments)?;\n\n    if snark_new.proof != *snark.proof {\n        log::warn!(\"swap proof has created a different proof\");\n    }\n\n    snark_new.save(&proof_path)?;\n    Ok(snark_new)\n}\n\npub(crate) fn mock_aggregate(\n    aggregation_snarks: Vec<PathBuf>,\n    logrows: u32,\n    split_proofs: bool,\n) -> Result<String, Box<dyn Error>> {\n    let mut snarks = vec![];\n    for proof_path in aggregation_snarks.iter() {\n        match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) {\n            Ok(snark) => {\n                snarks.push(snark);\n            }\n            Err(_) => {\n                return Err(\n                    \"invalid sample commitment type for aggregation, must be KZG\"\n                        .to_string()\n                        .into(),\n                );\n            }\n        }\n    }\n    // proof aggregation\n    #[cfg(not(target_arch = \"wasm32\"))]\n    let pb = {\n        let pb = init_spinner();\n        pb.set_message(\"Aggregating (may take a while)...\");\n        pb\n    };\n\n    let circuit = AggregationCircuit::new(&G1Affine::generator().into(), snarks, split_proofs)?;\n\n    let prover = halo2_proofs::dev::MockProver::run(logrows, &circuit, vec![circuit.instances()])\n        .map_err(Box::<dyn Error>::from)?;\n    prover\n        .verify()\n        .map_err(|e| Box::<dyn Error>::from(ExecutionError::VerifyError(e)))?;\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pb.finish_with_message(\"Done.\");\n    Ok(String::new())\n}\n\npub(crate) fn setup_aggregate(\n    sample_snarks: Vec<PathBuf>,\n    vk_path: PathBuf,\n    pk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    logrows: u32,\n    split_proofs: bool,\n    disable_selector_compression: bool,\n    commitment: Commitments,\n) -> Result<String, Box<dyn Error>> {\n    let mut snarks = vec![];\n    for proof_path in sample_snarks.iter() {\n        match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) {\n            Ok(snark) => {\n                snarks.push(snark);\n            }\n            Err(_) => {\n                return Err(\n                    \"invalid sample commitment type for aggregation, must be KZG\"\n                        .to_string()\n                        .into(),\n                );\n            }\n        }\n    }\n\n    let circuit = AggregationCircuit::new(&G1Affine::generator().into(), snarks, split_proofs)?;\n\n    let pk = match commitment {\n        Commitments::KZG => {\n            let params = load_params_prover::<KZGCommitmentScheme<Bn256>>(\n                srs_path,\n                logrows,\n                Commitments::KZG,\n            )?;\n\n            create_keys::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(\n                &circuit,\n                &params,\n                disable_selector_compression,\n            )?\n        }\n        Commitments::IPA => {\n            let params = load_params_prover::<IPACommitmentScheme<G1Affine>>(\n                srs_path,\n                logrows,\n                Commitments::IPA,\n            )?;\n            create_keys::<IPACommitmentScheme<G1Affine>, AggregationCircuit>(\n                &circuit,\n                &params,\n                disable_selector_compression,\n            )?\n        }\n    };\n    save_vk::<G1Affine>(&vk_path, pk.get_vk())?;\n    save_pk::<G1Affine>(&pk_path, &pk)?;\n\n    Ok(String::new())\n}\n\n#[allow(clippy::too_many_arguments)]\npub(crate) fn aggregate(\n    proof_path: PathBuf,\n    aggregation_snarks: Vec<PathBuf>,\n    pk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    transcript: TranscriptType,\n    logrows: u32,\n    check_mode: CheckMode,\n    split_proofs: bool,\n    commitment: Commitments,\n) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> {\n    let mut snarks = vec![];\n    for proof_path in aggregation_snarks.iter() {\n        match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) {\n            Ok(snark) => {\n                snarks.push(snark);\n            }\n            Err(_) => {\n                return Err(\n                    \"invalid sample commitment type for aggregation, must be KZG\"\n                        .to_string()\n                        .into(),\n                );\n            }\n        }\n    }\n\n    // proof aggregation\n    #[cfg(not(target_arch = \"wasm32\"))]\n    let pb = {\n        let pb = init_spinner();\n        pb.set_message(\"Aggregating (may take a while)...\");\n        pb\n    };\n\n    let now = Instant::now();\n\n    let snark = match commitment {\n        Commitments::KZG => {\n            let pk = load_pk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(pk_path, ())?;\n            let params: ParamsKZG<Bn256> = load_params_prover::<KZGCommitmentScheme<_>>(\n                srs_path.clone(),\n                logrows,\n                Commitments::KZG,\n            )?;\n            let circuit = AggregationCircuit::new(\n                &ParamsProver::<G1Affine>::get_g(&params)[0].into(),\n                snarks,\n                split_proofs,\n            )?;\n            let public_inputs = circuit.instances();\n            match transcript {\n                TranscriptType::EVM => create_proof_circuit::<\n                    KZGCommitmentScheme<Bn256>,\n                    _,\n                    ProverSHPLONK<_>,\n                    VerifierSHPLONK<_>,\n                    KZGSingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit,\n                    vec![public_inputs],\n                    &params,\n                    &pk,\n                    check_mode,\n                    commitment,\n                    transcript,\n                    None,\n                    None,\n                ),\n                TranscriptType::Poseidon => {\n                    let protocol = Some(compile(\n                        &params,\n                        pk.get_vk(),\n                        Config::kzg().with_num_instance(vec![public_inputs.len()]),\n                    ));\n\n                    create_proof_circuit::<\n                        KZGCommitmentScheme<Bn256>,\n                        _,\n                        ProverSHPLONK<_>,\n                        VerifierSHPLONK<_>,\n                        KZGAccumulatorStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(\n                        circuit,\n                        vec![public_inputs],\n                        &params,\n                        &pk,\n                        check_mode,\n                        commitment,\n                        transcript,\n                        None,\n                        protocol,\n                    )\n                }\n            }\n        }\n        Commitments::IPA => {\n            let pk = load_pk::<IPACommitmentScheme<_>, AggregationCircuit>(pk_path, ())?;\n            let params: ParamsIPA<_> = load_params_prover::<IPACommitmentScheme<_>>(\n                srs_path.clone(),\n                logrows,\n                Commitments::IPA,\n            )?;\n            let circuit = AggregationCircuit::new(\n                &ParamsProver::<G1Affine>::get_g(&params)[0].into(),\n                snarks,\n                split_proofs,\n            )?;\n            let public_inputs = circuit.instances();\n\n            match transcript {\n                TranscriptType::EVM => create_proof_circuit::<\n                    IPACommitmentScheme<G1Affine>,\n                    _,\n                    ProverIPA<_>,\n                    VerifierIPA<_>,\n                    IPASingleStrategy<_>,\n                    _,\n                    EvmTranscript<_, _, _, _>,\n                    EvmTranscript<_, _, _, _>,\n                >(\n                    circuit,\n                    vec![public_inputs],\n                    &params,\n                    &pk,\n                    check_mode,\n                    commitment,\n                    transcript,\n                    None,\n                    None,\n                ),\n                TranscriptType::Poseidon => {\n                    let protocol = Some(compile(\n                        &params,\n                        pk.get_vk(),\n                        Config::ipa().with_num_instance(vec![public_inputs.len()]),\n                    ));\n\n                    create_proof_circuit::<\n                        IPACommitmentScheme<G1Affine>,\n                        _,\n                        ProverIPA<_>,\n                        VerifierIPA<_>,\n                        IPAAccumulatorStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(\n                        circuit,\n                        vec![public_inputs],\n                        &params,\n                        &pk,\n                        check_mode,\n                        commitment,\n                        transcript,\n                        None,\n                        protocol,\n                    )\n                }\n            }\n        }\n    }?;\n    // the K used for the aggregation circuit\n\n    let elapsed = now.elapsed();\n    info!(\n        \"Aggregation proof took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n    snark.save(&proof_path)?;\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pb.finish_with_message(\"Done.\");\n\n    Ok(snark)\n}\n\npub(crate) fn verify(\n    proof_path: PathBuf,\n    settings_path: PathBuf,\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    reduced_srs: bool,\n) -> Result<bool, Box<dyn Error>> {\n    let circuit_settings = GraphSettings::load(&settings_path)?;\n\n    let logrows = circuit_settings.run_args.logrows;\n    let commitment = circuit_settings.run_args.commitment.into();\n\n    match commitment {\n        Commitments::KZG => {\n            let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?;\n            let params: ParamsKZG<Bn256> = if reduced_srs {\n                // only need G_0 for the verification with shplonk\n                load_params_verifier::<KZGCommitmentScheme<Bn256>>(srs_path, 1, Commitments::KZG)?\n            } else {\n                load_params_verifier::<KZGCommitmentScheme<Bn256>>(\n                    srs_path,\n                    logrows,\n                    Commitments::KZG,\n                )?\n            };\n            match proof.transcript_type {\n                TranscriptType::EVM => {\n                    verify_commitment::<\n                        KZGCommitmentScheme<Bn256>,\n                        VerifierSHPLONK<'_, Bn256>,\n                        _,\n                        KZGSingleStrategy<_>,\n                        EvmTranscript<G1Affine, _, _, _>,\n                        GraphCircuit,\n                        _,\n                    >(proof_path, circuit_settings, vk_path, &params, logrows)\n                }\n                TranscriptType::Poseidon => {\n                    verify_commitment::<\n                        KZGCommitmentScheme<Bn256>,\n                        VerifierSHPLONK<'_, Bn256>,\n                        _,\n                        KZGSingleStrategy<_>,\n                        PoseidonTranscript<NativeLoader, _>,\n                        GraphCircuit,\n                        _,\n                    >(proof_path, circuit_settings, vk_path, &params, logrows)\n                }\n            }\n        }\n        Commitments::IPA => {\n            let proof = Snark::load::<IPACommitmentScheme<G1Affine>>(&proof_path)?;\n            let params: ParamsIPA<_> = load_params_verifier::<IPACommitmentScheme<G1Affine>>(\n                srs_path,\n                logrows,\n                Commitments::IPA,\n            )?;\n            match proof.transcript_type {\n                TranscriptType::EVM => {\n                    verify_commitment::<\n                        IPACommitmentScheme<G1Affine>,\n                        VerifierIPA<_>,\n                        _,\n                        IPASingleStrategy<_>,\n                        EvmTranscript<G1Affine, _, _, _>,\n                        GraphCircuit,\n                        _,\n                    >(proof_path, circuit_settings, vk_path, &params, logrows)\n                }\n                TranscriptType::Poseidon => {\n                    verify_commitment::<\n                        IPACommitmentScheme<G1Affine>,\n                        VerifierIPA<_>,\n                        _,\n                        IPASingleStrategy<_>,\n                        PoseidonTranscript<NativeLoader, _>,\n                        GraphCircuit,\n                        _,\n                    >(proof_path, circuit_settings, vk_path, &params, logrows)\n                }\n            }\n        }\n    }\n}\n\nfn verify_commitment<\n    'a,\n    Scheme: CommitmentScheme,\n    V: Verifier<'a, Scheme>,\n    E: EncodedChallenge<Scheme::Curve>,\n    Strategy: VerificationStrategy<'a, Scheme, V>,\n    TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>,\n    C: Circuit<<Scheme as CommitmentScheme>::Scalar, Params = Params>,\n    Params,\n>(\n    proof_path: PathBuf,\n    settings: Params,\n    vk_path: PathBuf,\n    params: &'a Scheme::ParamsVerifier,\n    logrows: u32,\n) -> Result<bool, Box<dyn Error>>\nwhere\n    Scheme::Scalar: FromUniformBytes<64>\n        + SerdeObject\n        + Serialize\n        + DeserializeOwned\n        + WithSmallOrderMulGroup<3>,\n    Scheme::Curve: SerdeObject + Serialize + DeserializeOwned,\n    Scheme::ParamsVerifier: 'a,\n{\n    let proof = Snark::load::<Scheme>(&proof_path)?;\n\n    let strategy = Strategy::new(params);\n    let vk = load_vk::<Scheme, C>(vk_path, settings)?;\n    let now = Instant::now();\n\n    let result =\n        verify_proof_circuit::<V, _, _, _, TR>(&proof, params, &vk, strategy, 1 << logrows);\n\n    let elapsed = now.elapsed();\n    info!(\n        \"verify took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n    info!(\"verified: {}\", result.is_ok());\n    result.map_err(|e: plonk::Error| e.into()).map(|_| true)\n}\n\npub(crate) fn verify_aggr(\n    proof_path: PathBuf,\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    logrows: u32,\n    reduced_srs: bool,\n    commitment: Commitments,\n) -> Result<bool, Box<dyn Error>> {\n    match commitment {\n        Commitments::KZG => {\n            let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?;\n            let params: ParamsKZG<Bn256> = if reduced_srs {\n                // only need G_0 for the verification with shplonk\n                load_params_verifier::<KZGCommitmentScheme<Bn256>>(srs_path, 1, Commitments::KZG)?\n            } else {\n                load_params_verifier::<KZGCommitmentScheme<Bn256>>(\n                    srs_path,\n                    logrows,\n                    Commitments::KZG,\n                )?\n            };\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_commitment::<\n                    KZGCommitmentScheme<Bn256>,\n                    VerifierSHPLONK<'_, Bn256>,\n                    _,\n                    KZGSingleStrategy<_>,\n                    EvmTranscript<_, _, _, _>,\n                    AggregationCircuit,\n                    _,\n                >(proof_path, (), vk_path, &params, logrows),\n                TranscriptType::Poseidon => {\n                    verify_commitment::<\n                        KZGCommitmentScheme<Bn256>,\n                        VerifierSHPLONK<'_, Bn256>,\n                        _,\n                        KZGAccumulatorStrategy<_>,\n                        PoseidonTranscript<NativeLoader, _>,\n                        AggregationCircuit,\n                        _,\n                    >(proof_path, (), vk_path, &params, logrows)\n                }\n            }\n        }\n        Commitments::IPA => {\n            let proof = Snark::load::<IPACommitmentScheme<G1Affine>>(&proof_path)?;\n            let params: ParamsIPA<_> = load_params_verifier::<IPACommitmentScheme<G1Affine>>(\n                srs_path,\n                logrows,\n                Commitments::IPA,\n            )?;\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_commitment::<\n                    IPACommitmentScheme<G1Affine>,\n                    VerifierIPA<_>,\n                    _,\n                    IPASingleStrategy<_>,\n                    EvmTranscript<_, _, _, _>,\n                    AggregationCircuit,\n                    _,\n                >(proof_path, (), vk_path, &params, logrows),\n                TranscriptType::Poseidon => {\n                    verify_commitment::<\n                        IPACommitmentScheme<G1Affine>,\n                        VerifierIPA<_>,\n                        _,\n                        IPAAccumulatorStrategy<_>,\n                        PoseidonTranscript<NativeLoader, _>,\n                        AggregationCircuit,\n                        _,\n                    >(proof_path, (), vk_path, &params, logrows)\n                }\n            }\n        }\n    }\n}\n\n/// helper function for load_params\npub(crate) fn load_params_verifier<Scheme: CommitmentScheme>(\n    srs_path: Option<PathBuf>,\n    logrows: u32,\n    commitment: Commitments,\n) -> Result<Scheme::ParamsVerifier, Box<dyn Error>> {\n    let srs_path = get_srs_path(logrows, srs_path, commitment);\n    let mut params = load_srs_verifier::<Scheme>(srs_path)?;\n    info!(\"downsizing params to {} logrows\", logrows);\n    if logrows < params.k() {\n        params.downsize(logrows);\n    }\n    Ok(params)\n}\n\n/// helper function for load_params\npub(crate) fn load_params_prover<Scheme: CommitmentScheme>(\n    srs_path: Option<PathBuf>,\n    logrows: u32,\n    commitment: Commitments,\n) -> Result<Scheme::ParamsProver, Box<dyn Error>> {\n    let srs_path = get_srs_path(logrows, srs_path, commitment);\n    let mut params = load_srs_prover::<Scheme>(srs_path)?;\n    info!(\"downsizing params to {} logrows\", logrows);\n    if logrows < params.k() {\n        params.downsize(logrows);\n    }\n    Ok(params)\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/fieldutils.rs",
        "content": "use halo2_proofs::arithmetic::Field;\n/// Utilities for converting from Halo2 PrimeField types to integers (and vice-versa).\nuse halo2curves::ff::PrimeField;\n\n/// Converts an i32 to a PrimeField element.\npub fn i32_to_felt<F: PrimeField>(x: i32) -> F {\n    if x >= 0 {\n        F::from(x as u64)\n    } else {\n        -F::from(x.unsigned_abs() as u64)\n    }\n}\n\n/// Converts an i128 to a PrimeField element.\npub fn i128_to_felt<F: PrimeField>(x: i128) -> F {\n    if x >= 0 {\n        F::from_u128(x as u128)\n    } else {\n        -F::from_u128((-x) as u128)\n    }\n}\n\n/// Converts a PrimeField element to an i32.\npub fn felt_to_i32<F: PrimeField + PartialOrd + Field>(x: F) -> i32 {\n    if x > F::from(i32::MAX as u64) {\n        let rep = (-x).to_repr();\n        let negtmp: &[u8] = rep.as_ref();\n        let lower_32 = u32::from_le_bytes(negtmp[..4].try_into().unwrap());\n        -(lower_32 as i32)\n    } else {\n        let rep = (x).to_repr();\n        let tmp: &[u8] = rep.as_ref();\n        let lower_32 = u32::from_le_bytes(tmp[..4].try_into().unwrap());\n        lower_32 as i32\n    }\n}\n\n/// Converts a PrimeField element to an f64.\npub fn felt_to_f64<F: PrimeField + PartialOrd + Field>(x: F) -> f64 {\n    if x > F::from_u128(i128::MAX as u128) {\n        let rep = (-x).to_repr();\n        let negtmp: &[u8] = rep.as_ref();\n        let lower_128: u128 = u128::from_le_bytes(negtmp[..16].try_into().unwrap());\n        -(lower_128 as f64)\n    } else {\n        let rep = (x).to_repr();\n        let tmp: &[u8] = rep.as_ref();\n        let lower_128: u128 = u128::from_le_bytes(tmp[..16].try_into().unwrap());\n        lower_128 as f64\n    }\n}\n\n/// Converts a PrimeField element to an i128.\npub fn felt_to_i128<F: PrimeField + PartialOrd + Field>(x: F) -> i128 {\n    if x > F::from_u128(i128::MAX as u128) {\n        let rep = (-x).to_repr();\n        let negtmp: &[u8] = rep.as_ref();\n        let lower_128: u128 = u128::from_le_bytes(negtmp[..16].try_into().unwrap());\n        -(lower_128 as i128)\n    } else {\n        let rep = (x).to_repr();\n        let tmp: &[u8] = rep.as_ref();\n        let lower_128: u128 = u128::from_le_bytes(tmp[..16].try_into().unwrap());\n        lower_128 as i128\n    }\n}\n\n#[cfg(test)]\nmod test {\n\n    use super::*;\n    use halo2curves::pasta::Fp as F;\n\n    #[test]\n    fn test_conv() {\n        let res: F = i32_to_felt(-15i32);\n        assert_eq!(res, -F::from(15));\n\n        let res: F = i32_to_felt(2_i32.pow(17));\n        assert_eq!(res, F::from(131072));\n\n        let res: F = i128_to_felt(-15i128);\n        assert_eq!(res, -F::from(15));\n\n        let res: F = i128_to_felt(2_i128.pow(17));\n        assert_eq!(res, F::from(131072));\n    }\n\n    #[test]\n    fn felttoi32() {\n        for x in -(2i32.pow(16))..(2i32.pow(16)) {\n            let fieldx: F = i32_to_felt::<F>(x);\n            let xf: i32 = felt_to_i32::<F>(fieldx);\n            assert_eq!(x, xf);\n        }\n    }\n\n    #[test]\n    fn felttoi128() {\n        for x in -(2i128.pow(20))..(2i128.pow(20)) {\n            let fieldx: F = i128_to_felt::<F>(x);\n            let xf: i128 = felt_to_i128::<F>(fieldx);\n            assert_eq!(x, xf);\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/input.rs",
        "content": "use super::quantize_float;\nuse super::GraphError;\nuse crate::circuit::InputType;\nuse crate::fieldutils::i128_to_felt;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::tensor::Tensor;\nuse crate::EZKL_BUF_CAPACITY;\nuse halo2curves::bn256::Fr as Fp;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse postgres::{Client, NoTls};\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::prelude::*;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::types::PyDict;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::ToPyObject;\nuse serde::ser::SerializeStruct;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::io::BufReader;\nuse std::io::BufWriter;\nuse std::io::Read;\nuse std::panic::UnwindSafe;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_core::{\n    tract_data::{prelude::Tensor as TractTensor, TVec},\n    value::TValue,\n};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_hir::tract_num_traits::ToPrimitive;\n\ntype Decimals = u8;\ntype Call = String;\ntype RPCUrl = String;\n\n///\n#[derive(Clone, Debug, PartialOrd, PartialEq)]\npub enum FileSourceInner {\n    /// Inner elements of float inputs coming from a file\n    Float(f64),\n    /// Inner elements of bool inputs coming from a file\n    Bool(bool),\n    /// Inner elements of inputs coming from a witness\n    Field(Fp),\n}\n\nimpl FileSourceInner {\n    ///\n    pub fn is_float(&self) -> bool {\n        matches!(self, FileSourceInner::Float(_))\n    }\n    ///\n    pub fn is_bool(&self) -> bool {\n        matches!(self, FileSourceInner::Bool(_))\n    }\n    ///\n    pub fn is_field(&self) -> bool {\n        matches!(self, FileSourceInner::Field(_))\n    }\n}\n\nimpl Serialize for FileSourceInner {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match self {\n            FileSourceInner::Field(data) => data.serialize(serializer),\n            FileSourceInner::Bool(data) => data.serialize(serializer),\n            FileSourceInner::Float(data) => data.serialize(serializer),\n        }\n    }\n}\n\n// !!! ALWAYS USE JSON SERIALIZATION FOR GRAPH INPUT\n// UNTAGGED ENUMS WONT WORK :( as highlighted here:\nimpl<'de> Deserialize<'de> for FileSourceInner {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: Deserializer<'de>,\n    {\n        let this_json: Box<serde_json::value::RawValue> = Deserialize::deserialize(deserializer)?;\n\n        let bool_try: Result<bool, _> = serde_json::from_str(this_json.get());\n        if let Ok(t) = bool_try {\n            return Ok(FileSourceInner::Bool(t));\n        }\n        let float_try: Result<f64, _> = serde_json::from_str(this_json.get());\n        if let Ok(t) = float_try {\n            return Ok(FileSourceInner::Float(t));\n        }\n        let field_try: Result<Fp, _> = serde_json::from_str(this_json.get());\n        if let Ok(t) = field_try {\n            return Ok(FileSourceInner::Field(t));\n        }\n\n        Err(serde::de::Error::custom(\n            \"failed to deserialize FileSourceInner\",\n        ))\n    }\n}\n\n/// Elements of inputs coming from a file\npub type FileSource = Vec<Vec<FileSourceInner>>;\n\nimpl FileSourceInner {\n    /// Create a new FileSourceInner\n    pub fn new_float(f: f64) -> Self {\n        FileSourceInner::Float(f)\n    }\n    /// Create a new FileSourceInner\n    pub fn new_field(f: Fp) -> Self {\n        FileSourceInner::Field(f)\n    }\n    /// Create a new FileSourceInner\n    pub fn new_bool(f: bool) -> Self {\n        FileSourceInner::Bool(f)\n    }\n\n    ///\n    pub fn as_type(&mut self, input_type: &InputType) {\n        match self {\n            FileSourceInner::Float(f) => input_type.roundtrip(f),\n            FileSourceInner::Bool(_) => assert!(matches!(input_type, InputType::Bool)),\n            FileSourceInner::Field(_) => {}\n        }\n    }\n\n    /// Convert to a field element\n    pub fn to_field(&self, scale: crate::Scale) -> Fp {\n        match self {\n            FileSourceInner::Float(f) => i128_to_felt(quantize_float(f, 0.0, scale).unwrap()),\n            FileSourceInner::Bool(f) => {\n                if *f {\n                    Fp::one()\n                } else {\n                    Fp::zero()\n                }\n            }\n            FileSourceInner::Field(f) => *f,\n        }\n    }\n    /// Convert to a float\n    pub fn to_float(&self) -> f64 {\n        match self {\n            FileSourceInner::Float(f) => *f,\n            FileSourceInner::Bool(f) => {\n                if *f {\n                    1.0\n                } else {\n                    0.0\n                }\n            }\n            FileSourceInner::Field(f) => crate::fieldutils::felt_to_i128(*f) as f64,\n        }\n    }\n}\n\n/// Inner elements of inputs/outputs coming from on-chain\n#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)]\npub struct OnChainSource {\n    /// Vector of calls to accounts\n    pub calls: Vec<CallsToAccount>,\n    /// RPC url\n    pub rpc: RPCUrl,\n}\n\nimpl OnChainSource {\n    /// Create a new OnChainSource\n    pub fn new(calls: Vec<CallsToAccount>, rpc: RPCUrl) -> Self {\n        OnChainSource { calls, rpc }\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\n/// Inner elements of inputs/outputs coming from postgres DB\n#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)]\npub struct PostgresSource {\n    /// postgres host\n    pub host: RPCUrl,\n    /// user to connect to postgres\n    pub user: String,\n    /// password to connect to postgres\n    pub password: String,\n    /// query to execute\n    pub query: String,\n    /// dbname\n    pub dbname: String,\n    /// port\n    pub port: String,\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl PostgresSource {\n    /// Create a new PostgresSource\n    pub fn new(\n        host: RPCUrl,\n        port: String,\n        user: String,\n        query: String,\n        dbname: String,\n        password: String,\n    ) -> Self {\n        PostgresSource {\n            host,\n            user,\n            password,\n            query,\n            dbname,\n            port,\n        }\n    }\n\n    /// Fetch data from postgres\n    pub fn fetch(&self) -> Result<Vec<Vec<pg_bigdecimal::PgNumeric>>, Box<dyn std::error::Error>> {\n        // clone to move into thread\n        let user = self.user.clone();\n        let host = self.host.clone();\n        let query = self.query.clone();\n        let dbname = self.dbname.clone();\n        let port = self.port.clone();\n        let password = self.password.clone();\n\n        let config = if password.is_empty() {\n            format!(\n                \"host={} user={} dbname={} port={}\",\n                host, user, dbname, port\n            )\n        } else {\n            format!(\n                \"host={} user={} dbname={} port={} password={}\",\n                host, user, dbname, port, password\n            )\n        };\n\n        let mut client = Client::connect(&config, NoTls)?;\n        let mut res: Vec<pg_bigdecimal::PgNumeric> = Vec::new();\n        // extract rows from query\n        for row in client.query(&query, &[])? {\n            // extract features from row\n            for i in 0..row.len() {\n                res.push(row.get(i));\n            }\n        }\n        Ok(vec![res])\n    }\n\n    /// Fetch data from postgres and format it as a FileSource\n    pub fn fetch_and_format_as_file(\n        &self,\n    ) -> Result<Vec<Vec<FileSourceInner>>, Box<dyn std::error::Error>> {\n        Ok(self\n            .fetch()?\n            .iter()\n            .map(|d| {\n                d.iter()\n                    .map(|d| {\n                        FileSourceInner::Float(\n                            d.n.as_ref()\n                                .unwrap()\n                                .to_f64()\n                                .ok_or(\"could not convert decimal to f64\")\n                                .unwrap(),\n                        )\n                    })\n                    .collect()\n            })\n            .collect())\n    }\n}\n\nimpl OnChainSource {\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Create dummy local on-chain data to test the OnChain data source\n    pub async fn test_from_file_data(\n        data: &FileSource,\n        scales: Vec<crate::Scale>,\n        mut shapes: Vec<Vec<usize>>,\n        rpc: Option<&str>,\n    ) -> Result<(Vec<Tensor<Fp>>, Self), Box<dyn std::error::Error>> {\n        use crate::eth::{evm_quantize, read_on_chain_inputs, test_on_chain_data};\n        use log::debug;\n\n        // Set up local anvil instance for reading on-chain data\n        let (anvil, client) = crate::eth::setup_eth_backend(rpc, None).await?;\n\n        let address = client.address();\n\n        let mut scales = scales;\n        // set scales to 1 where data is a field element\n        for (idx, i) in data.iter().enumerate() {\n            if i.iter().all(|e| e.is_field()) {\n                scales[idx] = 0;\n                shapes[idx] = vec![i.len()];\n            }\n        }\n\n        let calls_to_accounts = test_on_chain_data(client.clone(), data).await?;\n        debug!(\"Calls to accounts: {:?}\", calls_to_accounts);\n        let inputs = read_on_chain_inputs(client.clone(), address, &calls_to_accounts).await?;\n        debug!(\"Inputs: {:?}\", inputs);\n\n        let mut quantized_evm_inputs = vec![];\n\n        let mut prev = 0;\n        for (idx, i) in data.iter().enumerate() {\n            quantized_evm_inputs.extend(\n                evm_quantize(\n                    client.clone(),\n                    vec![scales[idx]; i.len()],\n                    &(\n                        inputs.0[prev..i.len()].to_vec(),\n                        inputs.1[prev..i.len()].to_vec(),\n                    ),\n                )\n                .await?,\n            );\n            prev += i.len();\n        }\n\n        // on-chain data has already been quantized at this point. Just need to reshape it and push into tensor vector\n        let mut inputs: Vec<Tensor<Fp>> = vec![];\n        for (input, shape) in [quantized_evm_inputs].iter().zip(shapes) {\n            let mut t: Tensor<Fp> = input.iter().cloned().collect();\n            t.reshape(&shape)?;\n            inputs.push(t);\n        }\n\n        let used_rpc = rpc.unwrap_or(&anvil.endpoint()).to_string();\n\n        // Fill the input_data field of the GraphData struct\n        Ok((\n            inputs,\n            OnChainSource::new(calls_to_accounts.clone(), used_rpc),\n        ))\n    }\n}\n\n/// Defines the view only calls to accounts to fetch the on-chain input data.\n/// This data will be included as part of the first elements in the publicInputs\n/// for the sol evm verifier and will be  verifyWithDataAttestation.sol\n#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)]\npub struct CallsToAccount {\n    /// A vector of tuples, where index 0 of tuples\n    /// are the byte strings representing the ABI encoded function calls to\n    /// read the data from the address. This call must return a single\n    /// elementary type (<https://docs.soliditylang.org/en/v0.8.20/abi-spec.html#types>).\n    /// The second index of the tuple is the number of decimals for f32 conversion.\n    /// We don't support dynamic types currently.\n    pub call_data: Vec<(Call, Decimals)>,\n    /// Address of the contract to read the data from.\n    pub address: String,\n}\n/// Enum that defines source of the inputs/outputs to the EZKL model\n#[derive(Clone, Debug, Serialize, PartialOrd, PartialEq)]\n#[serde(untagged)]\npub enum DataSource {\n    /// .json File data source.\n    File(FileSource),\n    /// On-chain data source. The first element is the calls to the account, and the second is the RPC url.\n    OnChain(OnChainSource),\n    /// Postgres DB\n    #[cfg(not(target_arch = \"wasm32\"))]\n    DB(PostgresSource),\n}\n\nimpl Default for DataSource {\n    fn default() -> Self {\n        DataSource::File(vec![vec![]])\n    }\n}\n\nimpl From<FileSource> for DataSource {\n    fn from(data: FileSource) -> Self {\n        DataSource::File(data)\n    }\n}\n\nimpl From<Vec<Vec<Fp>>> for DataSource {\n    fn from(data: Vec<Vec<Fp>>) -> Self {\n        DataSource::File(\n            data.iter()\n                .map(|e| e.iter().map(|e| FileSourceInner::Field(*e)).collect())\n                .collect(),\n        )\n    }\n}\n\nimpl From<Vec<Vec<f64>>> for DataSource {\n    fn from(data: Vec<Vec<f64>>) -> Self {\n        DataSource::File(\n            data.iter()\n                .map(|e| e.iter().map(|e| FileSourceInner::Float(*e)).collect())\n                .collect(),\n        )\n    }\n}\n\nimpl From<OnChainSource> for DataSource {\n    fn from(data: OnChainSource) -> Self {\n        DataSource::OnChain(data)\n    }\n}\n\n// !!! ALWAYS USE JSON SERIALIZATION FOR GRAPH INPUT\n// UNTAGGED ENUMS WONT WORK :( as highlighted here:\nimpl<'de> Deserialize<'de> for DataSource {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: Deserializer<'de>,\n    {\n        let this_json: Box<serde_json::value::RawValue> = Deserialize::deserialize(deserializer)?;\n\n        let first_try: Result<FileSource, _> = serde_json::from_str(this_json.get());\n\n        if let Ok(t) = first_try {\n            return Ok(DataSource::File(t));\n        }\n        let second_try: Result<OnChainSource, _> = serde_json::from_str(this_json.get());\n        if let Ok(t) = second_try {\n            return Ok(DataSource::OnChain(t));\n        }\n        #[cfg(not(target_arch = \"wasm32\"))]\n        {\n            let third_try: Result<PostgresSource, _> = serde_json::from_str(this_json.get());\n            if let Ok(t) = third_try {\n                return Ok(DataSource::DB(t));\n            }\n        }\n\n        Err(serde::de::Error::custom(\"failed to deserialize DataSource\"))\n    }\n}\n\n/// Input to graph as a datasource\n/// Always use JSON serialization for GraphData. Seriously.\n#[derive(Clone, Debug, Deserialize, Default, PartialEq)]\npub struct GraphData {\n    /// Inputs to the model / computational graph (can be empty vectors if inputs are coming from on-chain).\n    pub input_data: DataSource,\n    /// Outputs of the model / computational graph (can be empty vectors if outputs are coming from on-chain).\n    pub output_data: Option<DataSource>,\n}\n\nimpl UnwindSafe for GraphData {}\n\nimpl GraphData {\n    // not wasm\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Convert the input data to tract data\n    pub fn to_tract_data(\n        &self,\n        shapes: &[Vec<usize>],\n        datum_types: &[tract_onnx::prelude::DatumType],\n    ) -> Result<TVec<TValue>, Box<dyn std::error::Error>> {\n        let mut inputs = TVec::new();\n        match &self.input_data {\n            DataSource::File(data) => {\n                for (i, input) in data.iter().enumerate() {\n                    if !input.is_empty() {\n                        let dt = datum_types[i];\n                        let input = input.iter().map(|e| e.to_float()).collect::<Vec<f64>>();\n                        let tt = TractTensor::from_shape(&shapes[i], &input)?;\n                        let tt = tt.cast_to_dt(dt)?;\n                        inputs.push(tt.into_owned().into());\n                    }\n                }\n            }\n            _ => {\n                return Err(Box::new(GraphError::InvalidDims(\n                    0,\n                    \"non file data cannot be split into batches\".to_string(),\n                )))\n            }\n        }\n        Ok(inputs)\n    }\n\n    ///\n    pub fn new(input_data: DataSource) -> Self {\n        GraphData {\n            input_data,\n            output_data: None,\n        }\n    }\n\n    /// Load the model input from a file\n    pub fn from_path(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> {\n        let reader = std::fs::File::open(path)?;\n        let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, reader);\n        let mut buf = String::new();\n        reader.read_to_string(&mut buf)?;\n        let graph_input = serde_json::from_str(&buf)?;\n        Ok(graph_input)\n    }\n\n    /// Save the model input to a file\n    pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> {\n        // buf writer\n        let writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?);\n        serde_json::to_writer(writer, self)?;\n        Ok(())\n    }\n\n    ///\n    pub fn split_into_batches(\n        &self,\n        input_shapes: Vec<Vec<usize>>,\n    ) -> Result<Vec<Self>, Box<dyn std::error::Error>> {\n        // split input data into batches\n        let mut batched_inputs = vec![];\n\n        let iterable = match self {\n            GraphData {\n                input_data: DataSource::File(data),\n                output_data: _,\n            } => data.clone(),\n            GraphData {\n                input_data: DataSource::OnChain(_),\n                output_data: _,\n            } => {\n                return Err(Box::new(GraphError::InvalidDims(\n                    0,\n                    \"on-chain data cannot be split into batches\".to_string(),\n                )))\n            }\n            #[cfg(not(target_arch = \"wasm32\"))]\n            GraphData {\n                input_data: DataSource::DB(data),\n                output_data: _,\n            } => data.fetch_and_format_as_file()?,\n        };\n\n        for (i, shape) in input_shapes.iter().enumerate() {\n            // ensure the input is evenly divisible by batch_size\n            let input_size = shape.clone().iter().product::<usize>();\n            let input = &iterable[i];\n            if input.len() % input_size != 0 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    0,\n                    \"calibration data length must be evenly divisible by the original input_size\"\n                        .to_string(),\n                )));\n            }\n            let mut batches = vec![];\n            for batch in input.chunks(input_size) {\n                batches.push(batch.to_vec());\n            }\n            batched_inputs.push(batches);\n        }\n\n        // now merge all the batches for each input into a vector of batches\n        // first assert each input has the same number of batches\n        let num_batches = if batched_inputs.is_empty() {\n            0\n        } else {\n            let num_batches = batched_inputs[0].len();\n            for input in batched_inputs.iter() {\n                assert_eq!(input.len(), num_batches);\n            }\n            num_batches\n        };\n        // now merge the batches\n        let mut input_batches = vec![];\n        for i in 0..num_batches {\n            let mut batch = vec![];\n            for input in batched_inputs.iter() {\n                batch.push(input[i].clone());\n            }\n            input_batches.push(DataSource::File(batch));\n        }\n\n        if input_batches.is_empty() {\n            input_batches.push(DataSource::File(vec![vec![]]));\n        }\n\n        // create a new GraphWitness for each batch\n        let batches = input_batches\n            .into_iter()\n            .map(GraphData::new)\n            .collect::<Vec<GraphData>>();\n\n        Ok(batches)\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for CallsToAccount {\n    fn to_object(&self, py: Python) -> PyObject {\n        let dict = PyDict::new(py);\n        dict.set_item(\"account\", &self.address).unwrap();\n        dict.set_item(\"call_data\", &self.call_data).unwrap();\n        dict.to_object(py)\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for DataSource {\n    fn to_object(&self, py: Python) -> PyObject {\n        match self {\n            DataSource::File(data) => data.to_object(py),\n            DataSource::OnChain(source) => {\n                let dict = PyDict::new(py);\n                dict.set_item(\"rpc_url\", &source.rpc).unwrap();\n                dict.set_item(\"calls_to_accounts\", &source.calls).unwrap();\n                dict.to_object(py)\n            }\n            DataSource::DB(source) => {\n                let dict = PyDict::new(py);\n                dict.set_item(\"host\", &source.host).unwrap();\n                dict.set_item(\"user\", &source.user).unwrap();\n                dict.set_item(\"query\", &source.query).unwrap();\n                dict.to_object(py)\n            }\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nuse crate::pfsys::field_to_string;\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for FileSourceInner {\n    fn to_object(&self, py: Python) -> PyObject {\n        match self {\n            FileSourceInner::Field(data) => field_to_string(data).to_object(py),\n            FileSourceInner::Bool(data) => data.to_object(py),\n            FileSourceInner::Float(data) => data.to_object(py),\n        }\n    }\n}\n\nimpl Serialize for GraphData {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut state = serializer.serialize_struct(\"GraphData\", 4)?;\n        state.serialize_field(\"input_data\", &self.input_data)?;\n        state.serialize_field(\"output_data\", &self.output_data)?;\n        state.end()\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    // this is for backwards compatibility with the old format\n    fn test_data_source_serialization_round_trip() {\n        let source = DataSource::from(vec![vec![0.053_262_424, 0.074_970_566, 0.052_355_476]]);\n\n        let serialized = serde_json::to_string(&source).unwrap();\n\n        const JSON: &str = r#\"[[0.053262424,0.074970566,0.052355476]]\"#;\n\n        assert_eq!(serialized, JSON);\n\n        let expect = serde_json::from_str::<DataSource>(JSON)\n            .map_err(|e| e.to_string())\n            .unwrap();\n\n        assert_eq!(expect, source);\n    }\n\n    #[test]\n    // this is for backwards compatibility with the old format\n    fn test_graph_input_serialization_round_trip() {\n        let file = GraphData::new(DataSource::from(vec![vec![\n            0.05326242372393608,\n            0.07497056573629379,\n            0.05235547572374344,\n        ]]));\n\n        let serialized = serde_json::to_string(&file).unwrap();\n\n        const JSON: &str = r#\"{\"input_data\":[[0.05326242372393608,0.07497056573629379,0.05235547572374344]],\"output_data\":null}\"#;\n\n        assert_eq!(serialized, JSON);\n\n        let graph_input3 = serde_json::from_str::<GraphData>(JSON)\n            .map_err(|e| e.to_string())\n            .unwrap();\n        assert_eq!(graph_input3, file);\n    }\n\n    //  test for the compatibility with the serialized elements from the mclbn256 library\n    #[test]\n    fn test_python_compat() {\n        let source = Fp::from_raw([18445520602771460712, 838677322461845011, 3079992810, 0]);\n\n        let original_addr = \"0x000000000000000000000000b794f5ea0ba39494ce839613fffba74279579268\";\n\n        assert_eq!(format!(\"{:?}\", source), original_addr);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/mod.rs",
        "content": "/// Representations of a computational graph's inputs.\npub mod input;\n/// Crate for defining a computational graph and building a ZK-circuit from it.\npub mod model;\n/// Representations of a computational graph's modules.\npub mod modules;\n/// Inner elements of a computational graph that represent a single operation / constraints.\npub mod node;\n/// Helper functions\npub mod utilities;\n/// Representations of a computational graph's variables.\npub mod vars;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored_json::ToColoredJson;\n#[cfg(unix)]\nuse gag::Gag;\nuse halo2_proofs::plonk::VerifyingKey;\nuse halo2_proofs::poly::commitment::CommitmentScheme;\npub use input::DataSource;\nuse itertools::Itertools;\nuse tosubcommand::ToFlags;\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse self::input::OnChainSource;\nuse self::input::{FileSource, GraphData};\nuse self::modules::{GraphModules, ModuleConfigs, ModuleForwardResult, ModuleSizes};\nuse crate::circuit::lookup::LookupOp;\nuse crate::circuit::modules::ModulePlanner;\nuse crate::circuit::region::ConstantsMap;\nuse crate::circuit::table::{num_cols_required, Range, Table, RESERVED_BLINDING_ROWS_PAD};\nuse crate::circuit::{CheckMode, InputType};\nuse crate::fieldutils::felt_to_f64;\nuse crate::pfsys::PrettyElements;\nuse crate::tensor::{Tensor, ValTensor};\nuse crate::{RunArgs, EZKL_BUF_CAPACITY};\n\nuse halo2_proofs::{\n    circuit::Layouter,\n    plonk::{Circuit, ConstraintSystem, Error as PlonkError},\n};\nuse halo2curves::bn256::{self, Fr as Fp, G1Affine};\nuse halo2curves::ff::{Field, PrimeField};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse lazy_static::lazy_static;\nuse log::{debug, error, trace, warn};\nuse maybe_rayon::prelude::{IntoParallelRefIterator, ParallelIterator};\npub use model::*;\npub use node::*;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::prelude::*;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::types::PyDict;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::ToPyObject;\nuse serde::{Deserialize, Serialize};\nuse std::ops::Deref;\nuse thiserror::Error;\npub use utilities::*;\npub use vars::*;\n\n#[cfg(feature = \"python-bindings\")]\nuse crate::pfsys::field_to_string;\n\n/// The safety factor for the range of the lookup table.\npub const RANGE_MULTIPLIER: i128 = 2;\n\n/// The maximum number of columns in a lookup table.\npub const MAX_NUM_LOOKUP_COLS: usize = 12;\n\n/// Max representation of a lookup table input\npub const MAX_LOOKUP_ABS: i128 = (MAX_NUM_LOOKUP_COLS as i128) * 2_i128.pow(MAX_PUBLIC_SRS);\n\n#[cfg(not(target_arch = \"wasm32\"))]\nlazy_static! {\n    /// Max circuit area\n    pub static ref EZKL_MAX_CIRCUIT_AREA: Option<usize> =\n        if let Ok(max_circuit_area) = std::env::var(\"EZKL_MAX_CIRCUIT_AREA\") {\n            Some(max_circuit_area.parse().unwrap_or(0))\n        } else {\n            None\n        };\n}\n\n#[cfg(target_arch = \"wasm32\")]\nconst EZKL_MAX_CIRCUIT_AREA: Option<usize> = None;\n\n/// circuit related errors.\n#[derive(Debug, Error)]\npub enum GraphError {\n    /// The wrong inputs were passed to a lookup node\n    #[error(\"invalid inputs for a lookup node\")]\n    InvalidLookupInputs,\n    /// Shape mismatch in circuit construction\n    #[error(\"invalid dimensions used for node {0} ({1})\")]\n    InvalidDims(usize, String),\n    /// Wrong method was called to configure an op\n    #[error(\"wrong method was called to configure node {0} ({1})\")]\n    WrongMethod(usize, String),\n    /// A requested node is missing in the graph\n    #[error(\"a requested node is missing in the graph: {0}\")]\n    MissingNode(usize),\n    /// The wrong method was called on an operation\n    #[error(\"an unsupported method was called on node {0} ({1})\")]\n    OpMismatch(usize, String),\n    /// This operation is unsupported\n    #[error(\"unsupported operation in graph\")]\n    UnsupportedOp,\n    /// This operation is unsupported\n    #[error(\"unsupported datatype in graph\")]\n    UnsupportedDataType,\n    /// A node has missing parameters\n    #[error(\"a node is missing required params: {0}\")]\n    MissingParams(String),\n    /// A node has missing parameters\n    #[error(\"a node is has misformed params: {0}\")]\n    MisformedParams(String),\n    /// Error in the configuration of the visibility of variables\n    #[error(\"there should be at least one set of public variables\")]\n    Visibility,\n    /// Ezkl only supports divisions by constants\n    #[error(\"ezkl currently only supports division by constants\")]\n    NonConstantDiv,\n    /// Ezkl only supports constant powers\n    #[error(\"ezkl currently only supports constant exponents\")]\n    NonConstantPower,\n    /// Error when attempting to rescale an operation\n    #[error(\"failed to rescale inputs for {0}\")]\n    RescalingError(String),\n    /// Error when attempting to load a model\n    #[error(\"failed to load\")]\n    ModelLoad,\n    /// Packing exponent is too large\n    #[error(\"largest packing exponent exceeds max. try reducing the scale\")]\n    PackingExponent,\n    /// Invalid Input Types\n    #[error(\"invalid input types\")]\n    InvalidInputTypes,\n    /// Missing results\n    #[error(\"missing results\")]\n    MissingResults,\n}\n\n///\npub const ASSUMED_BLINDING_FACTORS: usize = 5;\n/// The minimum number of rows in the grid\npub const MIN_LOGROWS: u32 = 6;\n\n/// 26\npub const MAX_PUBLIC_SRS: u32 = bn256::Fr::S - 2;\n\n///\npub const RESERVED_BLINDING_ROWS: usize = ASSUMED_BLINDING_FACTORS + RESERVED_BLINDING_ROWS_PAD;\n\nuse std::cell::RefCell;\n\nthread_local!(\n    /// This is a global variable that holds the settings for the graph\n    /// This is used to pass settings to the layouter and other parts of the circuit without needing to heavily modify the Halo2 API in a new fork\n    pub static GLOBAL_SETTINGS: RefCell<Option<GraphSettings>> = const { RefCell::new(None) }\n);\n\n/// Result from a forward pass\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\npub struct GraphWitness {\n    /// The inputs of the forward pass\n    pub inputs: Vec<Vec<Fp>>,\n    /// The prettified outputs of the forward pass, we use a String to maximize compatibility with Python and JS clients\n    pub pretty_elements: Option<PrettyElements>,\n    /// The output of the forward pass\n    pub outputs: Vec<Vec<Fp>>,\n    /// Any hashes of inputs generated during the forward pass\n    pub processed_inputs: Option<ModuleForwardResult>,\n    /// Any hashes of params generated during the forward pass\n    pub processed_params: Option<ModuleForwardResult>,\n    /// Any hashes of outputs generated during the forward pass\n    pub processed_outputs: Option<ModuleForwardResult>,\n    /// max lookup input\n    pub max_lookup_inputs: i128,\n    /// max lookup input\n    pub min_lookup_inputs: i128,\n    /// max range check size\n    pub max_range_size: i128,\n}\n\nimpl GraphWitness {\n    ///\n    pub fn get_float_outputs(&self, scales: &[crate::Scale]) -> Vec<Tensor<f32>> {\n        self.outputs\n            .iter()\n            .enumerate()\n            .map(|(i, x)| {\n                x.iter()\n                    .map(|y| (felt_to_f64(*y) / scale_to_multiplier(scales[i])) as f32)\n                    .collect::<Tensor<f32>>()\n            })\n            .collect()\n    }\n\n    ///\n    pub fn new(inputs: Vec<Vec<Fp>>, outputs: Vec<Vec<Fp>>) -> Self {\n        GraphWitness {\n            inputs,\n            outputs,\n            pretty_elements: None,\n            processed_inputs: None,\n            processed_params: None,\n            processed_outputs: None,\n            max_lookup_inputs: 0,\n            min_lookup_inputs: 0,\n            max_range_size: 0,\n        }\n    }\n\n    /// Generate the rescaled elements for the witness\n    pub fn generate_rescaled_elements(\n        &mut self,\n        input_scales: Vec<crate::Scale>,\n        output_scales: Vec<crate::Scale>,\n        visibility: VarVisibility,\n    ) {\n        let mut pretty_elements = PrettyElements {\n            rescaled_inputs: self\n                .inputs\n                .iter()\n                .enumerate()\n                .map(|(i, t)| {\n                    let scale = input_scales[i];\n                    t.iter()\n                        .map(|x| dequantize(*x, scale, 0.).to_string())\n                        .collect()\n                })\n                .collect(),\n            inputs: self\n                .inputs\n                .iter()\n                .map(|t| t.iter().map(|x| format!(\"{:?}\", x)).collect())\n                .collect(),\n            rescaled_outputs: self\n                .outputs\n                .iter()\n                .enumerate()\n                .map(|(i, t)| {\n                    let scale = output_scales[i];\n                    t.iter()\n                        .map(|x| dequantize(*x, scale, 0.).to_string())\n                        .collect()\n                })\n                .collect(),\n            outputs: self\n                .outputs\n                .iter()\n                .map(|t| t.iter().map(|x| format!(\"{:?}\", x)).collect())\n                .collect(),\n            ..Default::default()\n        };\n\n        if let Some(processed_inputs) = self.processed_inputs.clone() {\n            pretty_elements.processed_inputs = processed_inputs\n                .get_result(visibility.input)\n                .iter()\n                // gets printed as hex string\n                .map(|x| x.iter().map(|y| format!(\"{:?}\", y)).collect())\n                .collect();\n        }\n\n        if let Some(processed_params) = self.processed_params.clone() {\n            pretty_elements.processed_params = processed_params\n                .get_result(visibility.params)\n                .iter()\n                // gets printed as hex string\n                .map(|x| x.iter().map(|y| format!(\"{:?}\", y)).collect())\n                .collect();\n        }\n\n        if let Some(processed_outputs) = self.processed_outputs.clone() {\n            pretty_elements.processed_outputs = processed_outputs\n                .get_result(visibility.output)\n                .iter()\n                // gets printed as hex string\n                .map(|x| x.iter().map(|y| format!(\"{:?}\", y)).collect())\n                .collect();\n        }\n\n        self.pretty_elements = Some(pretty_elements);\n    }\n\n    ///\n    pub fn get_polycommitments(&self) -> Vec<G1Affine> {\n        let mut commitments = vec![];\n        if let Some(processed_inputs) = &self.processed_inputs {\n            if let Some(commits) = &processed_inputs.polycommit {\n                commitments.extend(commits.iter().flatten());\n            }\n        }\n        if let Some(processed_params) = &self.processed_params {\n            if let Some(commits) = &processed_params.polycommit {\n                commitments.extend(commits.iter().flatten());\n            }\n        }\n        if let Some(processed_outputs) = &self.processed_outputs {\n            if let Some(commits) = &processed_outputs.polycommit {\n                commitments.extend(commits.iter().flatten());\n            }\n        }\n        commitments\n    }\n\n    /// Export the ezkl witness as json\n    pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> {\n        let serialized = match serde_json::to_string(&self) {\n            Ok(s) => s,\n            Err(e) => {\n                return Err(Box::new(e));\n            }\n        };\n        Ok(serialized)\n    }\n\n    /// Load the model input from a file\n    pub fn from_path(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> {\n        let file = std::fs::File::open(path.clone())\n            .map_err(|_| format!(\"failed to load {}\", path.display()))?;\n\n        let reader = std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, file);\n        serde_json::from_reader(reader).map_err(|e| e.into())\n    }\n\n    /// Save the model input to a file\n    pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> {\n        // use buf writer\n        let writer =\n            std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?);\n\n        serde_json::to_writer(writer, &self).map_err(|e| e.into())\n    }\n\n    ///\n    pub fn get_input_tensor(&self) -> Vec<Tensor<Fp>> {\n        self.inputs\n            .clone()\n            .into_iter()\n            .map(|i| Tensor::from(i.into_iter()))\n            .collect::<Vec<Tensor<Fp>>>()\n    }\n\n    ///\n    pub fn get_output_tensor(&self) -> Vec<Tensor<Fp>> {\n        self.outputs\n            .clone()\n            .into_iter()\n            .map(|i| Tensor::from(i.into_iter()))\n            .collect::<Vec<Tensor<Fp>>>()\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for GraphWitness {\n    fn to_object(&self, py: Python) -> PyObject {\n        // Create a Python dictionary\n        let dict = PyDict::new(py);\n        let dict_inputs = PyDict::new(py);\n        let dict_params = PyDict::new(py);\n        let dict_outputs = PyDict::new(py);\n\n        let inputs: Vec<Vec<String>> = self\n            .inputs\n            .iter()\n            .map(|x| x.iter().map(field_to_string).collect())\n            .collect();\n\n        let outputs: Vec<Vec<String>> = self\n            .outputs\n            .iter()\n            .map(|x| x.iter().map(field_to_string).collect())\n            .collect();\n\n        dict.set_item(\"inputs\", inputs).unwrap();\n        dict.set_item(\"outputs\", outputs).unwrap();\n        dict.set_item(\"max_lookup_inputs\", self.max_lookup_inputs)\n            .unwrap();\n        dict.set_item(\"min_lookup_inputs\", self.min_lookup_inputs)\n            .unwrap();\n        dict.set_item(\"max_range_size\", self.max_range_size)\n            .unwrap();\n\n        if let Some(processed_inputs) = &self.processed_inputs {\n            //poseidon_hash\n            if let Some(processed_inputs_poseidon_hash) = &processed_inputs.poseidon_hash {\n                insert_poseidon_hash_pydict(dict_inputs, processed_inputs_poseidon_hash).unwrap();\n            }\n            if let Some(processed_inputs_polycommit) = &processed_inputs.polycommit {\n                insert_polycommit_pydict(dict_inputs, processed_inputs_polycommit).unwrap();\n            }\n\n            dict.set_item(\"processed_inputs\", dict_inputs).unwrap();\n        }\n\n        if let Some(processed_params) = &self.processed_params {\n            if let Some(processed_params_poseidon_hash) = &processed_params.poseidon_hash {\n                insert_poseidon_hash_pydict(dict_params, processed_params_poseidon_hash).unwrap();\n            }\n            if let Some(processed_params_polycommit) = &processed_params.polycommit {\n                insert_polycommit_pydict(dict_inputs, processed_params_polycommit).unwrap();\n            }\n\n            dict.set_item(\"processed_params\", dict_params).unwrap();\n        }\n\n        if let Some(processed_outputs) = &self.processed_outputs {\n            if let Some(processed_outputs_poseidon_hash) = &processed_outputs.poseidon_hash {\n                insert_poseidon_hash_pydict(dict_outputs, processed_outputs_poseidon_hash).unwrap();\n            }\n            if let Some(processed_outputs_polycommit) = &processed_outputs.polycommit {\n                insert_polycommit_pydict(dict_inputs, processed_outputs_polycommit).unwrap();\n            }\n\n            dict.set_item(\"processed_outputs\", dict_outputs).unwrap();\n        }\n\n        dict.to_object(py)\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nfn insert_poseidon_hash_pydict(pydict: &PyDict, poseidon_hash: &Vec<Fp>) -> Result<(), PyErr> {\n    let poseidon_hash: Vec<String> = poseidon_hash.iter().map(field_to_string).collect();\n    pydict.set_item(\"poseidon_hash\", poseidon_hash)?;\n\n    Ok(())\n}\n\n#[cfg(feature = \"python-bindings\")]\nfn insert_polycommit_pydict(pydict: &PyDict, commits: &Vec<Vec<G1Affine>>) -> Result<(), PyErr> {\n    use crate::python::PyG1Affine;\n    let poseidon_hash: Vec<Vec<PyG1Affine>> = commits\n        .iter()\n        .map(|c| c.iter().map(|x| PyG1Affine::from(*x)).collect())\n        .collect();\n    pydict.set_item(\"polycommit\", poseidon_hash)?;\n\n    Ok(())\n}\n\n/// model parameters\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\npub struct GraphSettings {\n    /// run args\n    pub run_args: RunArgs,\n    /// the potential number of rows used by the circuit\n    pub num_rows: usize,\n    /// total linear coordinate of assignments\n    pub total_assignments: usize,\n    /// total const size\n    pub total_const_size: usize,\n    /// total dynamic column size\n    pub total_dynamic_col_size: usize,\n    /// number of dynamic lookups\n    pub num_dynamic_lookups: usize,\n    /// number of shuffles\n    pub num_shuffles: usize,\n    /// total shuffle column size\n    pub total_shuffle_col_size: usize,\n    /// the shape of public inputs to the model (in order of appearance)\n    pub model_instance_shapes: Vec<Vec<usize>>,\n    /// model output scales\n    pub model_output_scales: Vec<crate::Scale>,\n    /// model input scales\n    pub model_input_scales: Vec<crate::Scale>,\n    /// the of instance cells used by modules\n    pub module_sizes: ModuleSizes,\n    /// required_lookups\n    pub required_lookups: Vec<LookupOp>,\n    /// required range_checks\n    pub required_range_checks: Vec<Range>,\n    /// check mode\n    pub check_mode: CheckMode,\n    /// ezkl version used\n    pub version: String,\n    /// num blinding factors\n    pub num_blinding_factors: Option<usize>,\n    /// unix time timestamp\n    pub timestamp: Option<u128>,\n}\n\nimpl GraphSettings {\n    /// Calc the number of rows required for lookup tables\n    pub fn lookup_log_rows(&self) -> u32 {\n        ((self.run_args.lookup_range.1 - self.run_args.lookup_range.0) as f32)\n            .log2()\n            .ceil() as u32\n    }\n\n    /// Calc the number of rows required for lookup tables\n    pub fn lookup_log_rows_with_blinding(&self) -> u32 {\n        ((self.run_args.lookup_range.1 - self.run_args.lookup_range.0) as f32\n            + RESERVED_BLINDING_ROWS as f32)\n            .log2()\n            .ceil() as u32\n    }\n\n    fn model_constraint_logrows_with_blinding(&self) -> u32 {\n        (self.num_rows as f64 + RESERVED_BLINDING_ROWS as f64)\n            .log2()\n            .ceil() as u32\n    }\n\n    fn dynamic_lookup_and_shuffle_logrows(&self) -> u32 {\n        (self.total_dynamic_col_size as f64 + self.total_shuffle_col_size as f64)\n            .log2()\n            .ceil() as u32\n    }\n\n    /// calculate the number of rows required for the dynamic lookup and shuffle\n    pub fn dynamic_lookup_and_shuffle_logrows_with_blinding(&self) -> u32 {\n        (self.total_dynamic_col_size as f64\n            + self.total_shuffle_col_size as f64\n            + RESERVED_BLINDING_ROWS as f64)\n            .log2()\n            .ceil() as u32\n    }\n\n    fn dynamic_lookup_and_shuffle_col_size(&self) -> usize {\n        self.total_dynamic_col_size + self.total_shuffle_col_size\n    }\n\n    /// calculate the number of rows required for the module constraints\n    pub fn module_constraint_logrows(&self) -> u32 {\n        (self.module_sizes.max_constraints() as f64).log2().ceil() as u32\n    }\n\n    /// calculate the number of rows required for the module constraints\n    pub fn module_constraint_logrows_with_blinding(&self) -> u32 {\n        (self.module_sizes.max_constraints() as f64 + RESERVED_BLINDING_ROWS as f64)\n            .log2()\n            .ceil() as u32\n    }\n\n    fn constants_logrows(&self) -> u32 {\n        (self.total_const_size as f64 / self.run_args.num_inner_cols as f64)\n            .log2()\n            .ceil() as u32\n    }\n\n    /// calculate the total number of instances\n    pub fn total_instances(&self) -> Vec<usize> {\n        let mut instances: Vec<usize> = self\n            .model_instance_shapes\n            .iter()\n            .map(|x| x.iter().product())\n            .collect();\n        instances.extend(self.module_sizes.num_instances());\n\n        instances\n    }\n\n    /// calculate the log2 of the total number of instances\n    pub fn log2_total_instances(&self) -> u32 {\n        let sum = self.total_instances().iter().sum::<usize>();\n\n        // max between 1 and the log2 of the sums\n        std::cmp::max((sum as f64).log2().ceil() as u32, 1)\n    }\n\n    /// calculate the log2 of the total number of instances\n    pub fn log2_total_instances_with_blinding(&self) -> u32 {\n        let sum = self.total_instances().iter().sum::<usize>() + RESERVED_BLINDING_ROWS;\n\n        // max between 1 and the log2 of the sums\n        std::cmp::max((sum as f64).log2().ceil() as u32, 1)\n    }\n\n    /// save params to file\n    pub fn save(&self, path: &std::path::PathBuf) -> Result<(), std::io::Error> {\n        // buf writer\n        let writer =\n            std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?);\n        serde_json::to_writer(writer, &self).map_err(|e| {\n            error!(\"failed to save settings file at {}\", e);\n            std::io::Error::new(std::io::ErrorKind::Other, e)\n        })\n    }\n    /// load params from file\n    pub fn load(path: &std::path::PathBuf) -> Result<Self, std::io::Error> {\n        // buf reader\n        let reader =\n            std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::open(path)?);\n        serde_json::from_reader(reader).map_err(|e| {\n            error!(\"failed to load settings file at {}\", e);\n            std::io::Error::new(std::io::ErrorKind::Other, e)\n        })\n    }\n\n    /// Export the ezkl configuration as json\n    pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> {\n        let serialized = match serde_json::to_string(&self) {\n            Ok(s) => s,\n            Err(e) => {\n                return Err(Box::new(e));\n            }\n        };\n        Ok(serialized)\n    }\n    /// Parse an ezkl configuration from a json\n    pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> {\n        serde_json::from_str(arg_json)\n    }\n\n    fn set_num_blinding_factors(&mut self, num_blinding_factors: usize) {\n        self.num_blinding_factors = Some(num_blinding_factors);\n    }\n\n    ///\n    pub fn available_col_size(&self) -> usize {\n        let base = 2u32;\n        if let Some(num_blinding_factors) = self.num_blinding_factors {\n            base.pow(self.run_args.logrows) as usize - num_blinding_factors - 1\n        } else {\n            log::error!(\"num_blinding_factors not set\");\n            log::warn!(\"using default available_col_size\");\n            base.pow(self.run_args.logrows) as usize - ASSUMED_BLINDING_FACTORS - 1\n        }\n    }\n\n    ///\n    pub fn uses_modules(&self) -> bool {\n        !self.module_sizes.max_constraints() > 0\n    }\n\n    /// if any visibility is encrypted or hashed\n    pub fn module_requires_fixed(&self) -> bool {\n        self.run_args.input_visibility.is_hashed()\n            || self.run_args.output_visibility.is_hashed()\n            || self.run_args.param_visibility.is_hashed()\n    }\n\n    /// requires dynamic lookup\n    pub fn requires_dynamic_lookup(&self) -> bool {\n        self.num_dynamic_lookups > 0\n    }\n\n    /// requires dynamic shuffle\n    pub fn requires_shuffle(&self) -> bool {\n        self.num_shuffles > 0\n    }\n\n    /// any kzg visibility\n    pub fn module_requires_polycommit(&self) -> bool {\n        self.run_args.input_visibility.is_polycommit()\n            || self.run_args.output_visibility.is_polycommit()\n            || self.run_args.param_visibility.is_polycommit()\n    }\n}\n\n/// Configuration for a computational graph / model loaded from a `.onnx` file.\n#[derive(Clone, Debug)]\npub struct GraphConfig {\n    model_config: ModelConfig,\n    module_configs: ModuleConfigs,\n    circuit_size: CircuitSize,\n}\n\n/// Defines the circuit for a computational graph / model loaded from a `.onnx` file.\n#[derive(Clone, Debug, Default, Serialize, Deserialize)]\npub struct CoreCircuit {\n    /// The model / graph of computations.\n    pub model: Model,\n    /// The settings of the model.\n    pub settings: GraphSettings,\n}\n\n/// Defines the circuit for a computational graph / model loaded from a `.onnx` file.\n#[derive(Clone, Debug, Default, Serialize, Deserialize)]\npub struct GraphCircuit {\n    /// Core circuit\n    pub core: CoreCircuit,\n    /// The witness data for the model.\n    pub graph_witness: GraphWitness,\n}\n\nimpl GraphCircuit {\n    /// Settings for the graph\n    pub fn settings(&self) -> &GraphSettings {\n        &self.core.settings\n    }\n    /// Settings for the graph (mutable)\n    pub fn settings_mut(&mut self) -> &mut GraphSettings {\n        &mut self.core.settings\n    }\n    /// The model\n    pub fn model(&self) -> &Model {\n        &self.core.model\n    }\n    ///\n    pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> {\n        let f = std::fs::File::create(path)?;\n        let writer = std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);\n        bincode::serialize_into(writer, &self)?;\n        Ok(())\n    }\n\n    ///\n    pub fn load(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> {\n        // read bytes from file\n        let f = std::fs::File::open(path)?;\n        let reader = std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, f);\n        let result: GraphCircuit = bincode::deserialize_from(reader)?;\n\n        Ok(result)\n    }\n}\n\n#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)]\n/// The data source for a test\npub enum TestDataSource {\n    /// The data is loaded from a file\n    File,\n    /// The data is loaded from the chain\n    #[default]\n    OnChain,\n}\n\nimpl std::fmt::Display for TestDataSource {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            TestDataSource::File => write!(f, \"file\"),\n            TestDataSource::OnChain => write!(f, \"on-chain\"),\n        }\n    }\n}\n\nimpl ToFlags for TestDataSource {}\n\nimpl From<String> for TestDataSource {\n    fn from(value: String) -> Self {\n        match value.to_lowercase().as_str() {\n            \"file\" => TestDataSource::File,\n            \"on-chain\" => TestDataSource::OnChain,\n            _ => {\n                error!(\"invalid data source: {}\", value);\n                warn!(\"using default data source: on-chain\");\n                TestDataSource::default()\n            }\n        }\n    }\n}\n\n#[derive(Clone, Debug, Default)]\n///\npub struct TestSources {\n    ///\n    pub input: TestDataSource,\n    ///\n    pub output: TestDataSource,\n}\n\n///\n#[derive(Clone, Debug, Default)]\npub struct TestOnChainData {\n    /// The path to the test witness\n    pub data: std::path::PathBuf,\n    /// rpc endpoint\n    pub rpc: Option<String>,\n    ///\n    pub data_sources: TestSources,\n}\n\nimpl GraphCircuit {\n    ///\n    pub fn new(\n        model: Model,\n        run_args: &RunArgs,\n    ) -> Result<GraphCircuit, Box<dyn std::error::Error>> {\n        // // placeholder dummy inputs - must call prepare_public_inputs to load data afterwards\n        let mut inputs: Vec<Vec<Fp>> = vec![];\n        for shape in model.graph.input_shapes()? {\n            let t: Vec<Fp> = vec![Fp::zero(); shape.iter().product::<usize>()];\n            inputs.push(t);\n        }\n\n        // dummy module settings, must load from GraphData after\n        let mut settings = model.gen_params(run_args, run_args.check_mode)?;\n\n        let mut num_params = 0;\n        if !model.const_shapes().is_empty() {\n            for shape in model.const_shapes() {\n                num_params += shape.iter().product::<usize>();\n            }\n        }\n\n        let sizes = GraphModules::num_constraints_and_instances(\n            model.graph.input_shapes()?,\n            vec![vec![num_params]],\n            model.graph.output_shapes()?,\n            VarVisibility::from_args(run_args)?,\n        );\n\n        // number of instances used by modules\n        settings.module_sizes = sizes.clone();\n\n        // as they occupy independent rows\n        settings.num_rows = std::cmp::max(settings.num_rows, sizes.max_constraints());\n\n        let core = CoreCircuit {\n            model,\n            settings: settings.clone(),\n        };\n\n        Ok(GraphCircuit {\n            core,\n            graph_witness: GraphWitness::new(inputs, vec![]),\n        })\n    }\n\n    ///\n    pub fn new_from_settings(\n        model: Model,\n        mut settings: GraphSettings,\n        check_mode: CheckMode,\n    ) -> Result<GraphCircuit, Box<dyn std::error::Error>> {\n        // placeholder dummy inputs - must call prepare_public_inputs to load data afterwards\n        let mut inputs: Vec<Vec<Fp>> = vec![];\n        for shape in model.graph.input_shapes()? {\n            let t: Vec<Fp> = vec![Fp::zero(); shape.iter().product::<usize>()];\n            inputs.push(t);\n        }\n\n        // dummy module settings, must load from GraphData after\n\n        settings.check_mode = check_mode;\n\n        let core = CoreCircuit {\n            model,\n            settings: settings.clone(),\n        };\n\n        Ok(GraphCircuit {\n            core,\n            graph_witness: GraphWitness::new(inputs, vec![]),\n        })\n    }\n\n    /// load inputs and outputs for the model\n    pub fn load_graph_witness(\n        &mut self,\n        data: &GraphWitness,\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        self.graph_witness = data.clone();\n        // load the module settings\n        Ok(())\n    }\n\n    /// Prepare the public inputs for the circuit.\n    pub fn prepare_public_inputs(\n        &self,\n        data: &GraphWitness,\n    ) -> Result<Vec<Fp>, Box<dyn std::error::Error>> {\n        // the ordering here is important, we want the inputs to come before the outputs\n        // as they are configured in that order as Column<Instances>\n        let mut public_inputs: Vec<Fp> = vec![];\n        if self.settings().run_args.input_visibility.is_public() {\n            public_inputs.extend(self.graph_witness.inputs.clone().into_iter().flatten())\n        } else if let Some(processed_inputs) = &data.processed_inputs {\n            public_inputs.extend(processed_inputs.get_instances().into_iter().flatten());\n        }\n\n        if let Some(processed_params) = &data.processed_params {\n            public_inputs.extend(processed_params.get_instances().into_iter().flatten());\n        }\n\n        if self.settings().run_args.output_visibility.is_public() {\n            public_inputs.extend(self.graph_witness.outputs.clone().into_iter().flatten());\n        } else if let Some(processed_outputs) = &data.processed_outputs {\n            public_inputs.extend(processed_outputs.get_instances().into_iter().flatten());\n        }\n\n        if public_inputs.len() < 11 {\n            debug!(\"public inputs: {:?}\", public_inputs);\n        } else {\n            debug!(\"public inputs: {:?} ...\", &public_inputs[0..10]);\n        }\n\n        Ok(public_inputs)\n    }\n\n    /// get rescaled public inputs as floating points for the circuit.\n    pub fn pretty_public_inputs(\n        &self,\n        data: &GraphWitness,\n    ) -> Result<Option<PrettyElements>, Box<dyn std::error::Error>> {\n        // dequantize the supplied data using the provided scale.\n        // the ordering here is important, we want the inputs to come before the outputs\n        // as they are configured in that order as Column<Instances>\n\n        if data.pretty_elements.is_none() {\n            warn!(\"no rescaled elements found in witness data\");\n            return Ok(None);\n        }\n\n        let mut public_inputs = PrettyElements::default();\n        let elements = data.pretty_elements.as_ref().unwrap();\n\n        if self.settings().run_args.input_visibility.is_public() {\n            public_inputs.rescaled_inputs = elements.rescaled_inputs.clone();\n            public_inputs.inputs = elements.inputs.clone();\n        } else if data.processed_inputs.is_some() {\n            public_inputs.processed_inputs = elements.processed_inputs.clone();\n        }\n\n        if data.processed_params.is_some() {\n            public_inputs.processed_params = elements.processed_params.clone();\n        }\n\n        if self.settings().run_args.output_visibility.is_public() {\n            public_inputs.rescaled_outputs = elements.rescaled_outputs.clone();\n            public_inputs.outputs = elements.outputs.clone();\n        } else if data.processed_outputs.is_some() {\n            public_inputs.processed_outputs = elements.processed_outputs.clone();\n        }\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        debug!(\n            \"rescaled and processed public inputs: {}\",\n            serde_json::to_string(&public_inputs)?.to_colored_json_auto()?\n        );\n\n        Ok(Some(public_inputs))\n    }\n\n    ///\n    #[cfg(target_arch = \"wasm32\")]\n    pub fn load_graph_input(\n        &mut self,\n        data: &GraphData,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        let shapes = self.model().graph.input_shapes()?;\n        let scales = self.model().graph.get_input_scales();\n        let input_types = self.model().graph.get_input_types()?;\n        self.process_data_source(&data.input_data, shapes, scales, input_types)\n    }\n\n    ///\n    pub fn load_graph_from_file_exclusively(\n        &mut self,\n        data: &GraphData,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        let shapes = self.model().graph.input_shapes()?;\n        let scales = self.model().graph.get_input_scales();\n        let input_types = self.model().graph.get_input_types()?;\n        debug!(\"input scales: {:?}\", scales);\n\n        match &data.input_data {\n            DataSource::File(file_data) => {\n                self.load_file_data(file_data, &shapes, scales, input_types)\n            }\n            _ => Err(\"Cannot use non-file data source as input for this method.\".into()),\n        }\n    }\n\n    ///\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn load_graph_input(\n        &mut self,\n        data: &GraphData,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        let shapes = self.model().graph.input_shapes()?;\n        let scales = self.model().graph.get_input_scales();\n        let input_types = self.model().graph.get_input_types()?;\n        debug!(\"input scales: {:?}\", scales);\n\n        self.process_data_source(&data.input_data, shapes, scales, input_types)\n    }\n\n    #[cfg(target_arch = \"wasm32\")]\n    /// Process the data source for the model\n    fn process_data_source(\n        &mut self,\n        data: &DataSource,\n        shapes: Vec<Vec<usize>>,\n        scales: Vec<crate::Scale>,\n        input_types: Vec<InputType>,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        match &data {\n            DataSource::File(file_data) => {\n                self.load_file_data(file_data, &shapes, scales, input_types)\n            }\n            DataSource::OnChain(_) => {\n                Err(\"Cannot use on-chain data source as input for this method.\".into())\n            }\n        }\n    }\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Process the data source for the model\n    fn process_data_source(\n        &mut self,\n        data: &DataSource,\n        shapes: Vec<Vec<usize>>,\n        scales: Vec<crate::Scale>,\n        input_types: Vec<InputType>,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        match &data {\n            DataSource::OnChain(source) => {\n                let mut per_item_scale = vec![];\n                for (i, shape) in shapes.iter().enumerate() {\n                    per_item_scale.extend(vec![scales[i]; shape.iter().product::<usize>()]);\n                }\n\n                // start runtime and fetch data\n                let runtime = tokio::runtime::Builder::new_current_thread()\n                    .enable_all()\n                    .build()?;\n\n                runtime.block_on(async {\n                    self.load_on_chain_data(source.clone(), &shapes, per_item_scale)\n                        .await\n                })\n            }\n            DataSource::File(file_data) => {\n                self.load_file_data(file_data, &shapes, scales, input_types)\n            }\n            DataSource::DB(pg) => {\n                let data = pg.fetch_and_format_as_file()?;\n                self.load_file_data(&data, &shapes, scales, input_types)\n            }\n        }\n    }\n\n    /// Prepare on chain test data\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub async fn load_on_chain_data(\n        &mut self,\n        source: OnChainSource,\n        shapes: &Vec<Vec<usize>>,\n        scales: Vec<crate::Scale>,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        use crate::eth::{evm_quantize, read_on_chain_inputs, setup_eth_backend};\n        let (_, client) = setup_eth_backend(Some(&source.rpc), None).await?;\n        let inputs = read_on_chain_inputs(client.clone(), client.address(), &source.calls).await?;\n        // quantize the supplied data using the provided scale + QuantizeData.sol\n        let quantized_evm_inputs = evm_quantize(client, scales, &inputs).await?;\n        // on-chain data has already been quantized at this point. Just need to reshape it and push into tensor vector\n        let mut inputs: Vec<Tensor<Fp>> = vec![];\n        for (input, shape) in [quantized_evm_inputs].iter().zip(shapes) {\n            let mut t: Tensor<Fp> = input.iter().cloned().collect();\n            t.reshape(shape)?;\n            inputs.push(t);\n        }\n\n        Ok(inputs)\n    }\n\n    ///\n    pub fn load_file_data(\n        &mut self,\n        file_data: &FileSource,\n        shapes: &Vec<Vec<usize>>,\n        scales: Vec<crate::Scale>,\n        input_types: Vec<InputType>,\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        // quantize the supplied data using the provided scale.\n        let mut data: Vec<Tensor<Fp>> = vec![];\n        for (((d, shape), scale), input_type) in file_data\n            .iter()\n            .zip(shapes)\n            .zip(scales)\n            .zip(input_types.iter())\n        {\n            let t: Vec<Fp> = d\n                .par_iter()\n                .map(|x| {\n                    let mut x = x.clone();\n                    x.as_type(input_type);\n                    x.to_field(scale)\n                })\n                .collect();\n\n            let mut t: Tensor<Fp> = t.into_iter().into();\n            t.reshape(shape)?;\n\n            data.push(t);\n        }\n        Ok(data)\n    }\n\n    ///\n    pub fn load_witness_file_data(\n        &mut self,\n        file_data: &[Vec<Fp>],\n        shapes: &[Vec<usize>],\n    ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> {\n        // quantize the supplied data using the provided scale.\n        let mut data: Vec<Tensor<Fp>> = vec![];\n        for (d, shape) in file_data.iter().zip(shapes) {\n            let mut t: Tensor<Fp> = d.clone().into_iter().into();\n            t.reshape(shape)?;\n            data.push(t);\n        }\n        Ok(data)\n    }\n\n    fn calc_safe_lookup_range(min_max_lookup: Range, lookup_safety_margin: i128) -> Range {\n        (\n            lookup_safety_margin * min_max_lookup.0,\n            lookup_safety_margin * min_max_lookup.1,\n        )\n    }\n\n    fn calc_num_cols(range_len: i128, max_logrows: u32) -> usize {\n        let max_col_size = Table::<Fp>::cal_col_size(max_logrows as usize, RESERVED_BLINDING_ROWS);\n        num_cols_required(range_len, max_col_size)\n    }\n\n    fn table_size_logrows(\n        &self,\n        safe_lookup_range: Range,\n        max_range_size: i128,\n    ) -> Result<u32, Box<dyn std::error::Error>> {\n        // pick the range with the largest absolute size safe_lookup_range or max_range_size\n        let safe_range = std::cmp::max(\n            (safe_lookup_range.1 - safe_lookup_range.0).abs(),\n            max_range_size,\n        );\n\n        let min_bits = (safe_range as f64 + RESERVED_BLINDING_ROWS as f64 + 1.)\n            .log2()\n            .ceil() as u32;\n\n        Ok(min_bits)\n    }\n\n    /// calculate the minimum logrows required for the circuit\n    pub fn calc_min_logrows(\n        &mut self,\n        min_max_lookup: Range,\n        max_range_size: i128,\n        max_logrows: Option<u32>,\n        lookup_safety_margin: i128,\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        // load the max logrows\n        let max_logrows = max_logrows.unwrap_or(MAX_PUBLIC_SRS);\n        let max_logrows = std::cmp::min(max_logrows, MAX_PUBLIC_SRS);\n        let mut max_logrows = std::cmp::max(max_logrows, MIN_LOGROWS);\n        let mut min_logrows = MIN_LOGROWS;\n\n        let safe_lookup_range = Self::calc_safe_lookup_range(min_max_lookup, lookup_safety_margin);\n\n        // check if has overflowed max lookup input\n        if (min_max_lookup.1 - min_max_lookup.0).abs() > MAX_LOOKUP_ABS / lookup_safety_margin {\n            let err_string = format!(\"max lookup input {:?} is too large\", min_max_lookup);\n            return Err(err_string.into());\n        }\n\n        if max_range_size.abs() > MAX_LOOKUP_ABS {\n            let err_string = format!(\"max range check size {:?} is too large\", max_range_size);\n            return Err(err_string.into());\n        }\n\n        // These are hard lower limits, we can't overflow instances or modules constraints\n        let instance_logrows = self.settings().log2_total_instances();\n        let module_constraint_logrows = self.settings().module_constraint_logrows();\n        let dynamic_lookup_logrows = self.settings().dynamic_lookup_and_shuffle_logrows();\n        min_logrows = std::cmp::max(\n            min_logrows,\n            // max of the instance logrows and the module constraint logrows and the dynamic lookup logrows is the lower limit\n            *[\n                instance_logrows,\n                module_constraint_logrows,\n                dynamic_lookup_logrows,\n            ]\n            .iter()\n            .max()\n            .unwrap(),\n        );\n\n        // These are upper limits, going above these is wasteful, but they are not hard limits\n        let model_constraint_logrows = self.settings().model_constraint_logrows_with_blinding();\n        let min_bits = self.table_size_logrows(safe_lookup_range, max_range_size)?;\n        let constants_logrows = self.settings().constants_logrows();\n        max_logrows = std::cmp::min(\n            max_logrows,\n            // max of the model constraint logrows, min_bits, and the constants logrows is the upper limit\n            *[model_constraint_logrows, min_bits, constants_logrows]\n                .iter()\n                .max()\n                .unwrap(),\n        );\n\n        // we now have a min and max logrows\n        max_logrows = std::cmp::max(min_logrows, max_logrows);\n\n        // degrade the max logrows until the extended k is small enough\n        while min_logrows < max_logrows\n            && !self.extended_k_is_small_enough(max_logrows, safe_lookup_range, max_range_size)\n        {\n            max_logrows -= 1;\n        }\n\n        if !self.extended_k_is_small_enough(max_logrows, safe_lookup_range, max_range_size) {\n            let err_string = format!(\n                \"extended k is too large to accommodate the quotient polynomial with logrows {}\",\n                max_logrows\n            );\n            debug!(\"{}\", err_string);\n            return Err(err_string.into());\n        }\n\n        let logrows = max_logrows;\n\n        let model = self.model().clone();\n        let settings_mut = self.settings_mut();\n        settings_mut.run_args.lookup_range = safe_lookup_range;\n        settings_mut.run_args.logrows = logrows;\n\n        *settings_mut = GraphCircuit::new(model, &settings_mut.run_args)?\n            .settings()\n            .clone();\n\n        debug!(\n            \"setting lookup_range to: {:?}, setting logrows to: {}\",\n            self.settings().run_args.lookup_range,\n            self.settings().run_args.logrows\n        );\n\n        Ok(())\n    }\n\n    fn extended_k_is_small_enough(\n        &self,\n        k: u32,\n        safe_lookup_range: Range,\n        max_range_size: i128,\n    ) -> bool {\n        // if num cols is too large then the extended k is too large\n        if Self::calc_num_cols(safe_lookup_range.1 - safe_lookup_range.0, k) > MAX_NUM_LOOKUP_COLS\n            || Self::calc_num_cols(max_range_size, k) > MAX_NUM_LOOKUP_COLS\n        {\n            return false;\n        }\n\n        let mut settings = self.settings().clone();\n        settings.run_args.lookup_range = safe_lookup_range;\n        settings.run_args.logrows = k;\n        settings.required_range_checks = vec![(0, max_range_size)];\n        let mut cs = ConstraintSystem::default();\n        // if unix get a gag\n        #[cfg(unix)]\n        let _r = match Gag::stdout() {\n            Ok(g) => Some(g),\n            _ => None,\n        };\n        #[cfg(unix)]\n        let _g = match Gag::stderr() {\n            Ok(g) => Some(g),\n            _ => None,\n        };\n\n        Self::configure_with_params(&mut cs, settings);\n\n        // drop the gag\n        #[cfg(unix)]\n        drop(_r);\n        #[cfg(unix)]\n        drop(_g);\n\n        #[cfg(feature = \"mv-lookup\")]\n        let cs = cs.chunk_lookups();\n        // quotient_poly_degree * params.n - 1 is the degree of the quotient polynomial\n        let max_degree = cs.degree();\n        let quotient_poly_degree = (max_degree - 1) as u64;\n        // n = 2^k\n        let n = 1u64 << k;\n        let mut extended_k = k;\n\n        while (1 << extended_k) < (n * quotient_poly_degree) {\n            extended_k += 1;\n            if extended_k > bn256::Fr::S {\n                return false;\n            }\n        }\n        true\n    }\n\n    /// Runs the forward pass of the model / graph of computations and any associated hashing.\n    pub fn forward<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>(\n        &self,\n        inputs: &mut [Tensor<Fp>],\n        vk: Option<&VerifyingKey<G1Affine>>,\n        srs: Option<&Scheme::ParamsProver>,\n        witness_gen: bool,\n    ) -> Result<GraphWitness, Box<dyn std::error::Error>> {\n        let original_inputs = inputs.to_vec();\n\n        let visibility = VarVisibility::from_args(&self.settings().run_args)?;\n        let mut processed_inputs = None;\n        let mut processed_params = None;\n        let mut processed_outputs = None;\n\n        if visibility.input.requires_processing() {\n            let module_outlets = visibility.input.overwrites_inputs();\n            if !module_outlets.is_empty() {\n                let mut module_inputs = vec![];\n                for outlet in &module_outlets {\n                    module_inputs.push(inputs[*outlet].clone());\n                }\n                let res =\n                    GraphModules::forward::<Scheme>(&module_inputs, &visibility.input, vk, srs)?;\n                processed_inputs = Some(res.clone());\n                let module_results = res.get_result(visibility.input.clone());\n\n                for (i, outlet) in module_outlets.iter().enumerate() {\n                    inputs[*outlet] = Tensor::from(module_results[i].clone().into_iter());\n                }\n            } else {\n                processed_inputs = Some(GraphModules::forward::<Scheme>(\n                    inputs,\n                    &visibility.input,\n                    vk,\n                    srs,\n                )?);\n            }\n        }\n\n        if visibility.params.requires_processing() {\n            let params = self.model().get_all_params();\n            if !params.is_empty() {\n                let flattened_params = Tensor::new(Some(&params), &[params.len()])?.combine()?;\n                processed_params = Some(GraphModules::forward::<Scheme>(\n                    &[flattened_params],\n                    &visibility.params,\n                    vk,\n                    srs,\n                )?);\n            }\n        }\n\n        let mut model_results =\n            self.model()\n                .forward(inputs, &self.settings().run_args, witness_gen)?;\n\n        if visibility.output.requires_processing() {\n            let module_outlets = visibility.output.overwrites_inputs();\n            if !module_outlets.is_empty() {\n                let mut module_inputs = vec![];\n                for outlet in &module_outlets {\n                    module_inputs.push(model_results.outputs[*outlet].clone());\n                }\n                let res =\n                    GraphModules::forward::<Scheme>(&module_inputs, &visibility.output, vk, srs)?;\n                processed_outputs = Some(res.clone());\n                let module_results = res.get_result(visibility.output.clone());\n\n                for (i, outlet) in module_outlets.iter().enumerate() {\n                    model_results.outputs[*outlet] =\n                        Tensor::from(module_results[i].clone().into_iter());\n                }\n            } else {\n                processed_outputs = Some(GraphModules::forward::<Scheme>(\n                    &model_results.outputs,\n                    &visibility.output,\n                    vk,\n                    srs,\n                )?);\n            }\n        }\n\n        let mut witness = GraphWitness {\n            inputs: original_inputs\n                .iter()\n                .map(|t| t.deref().to_vec())\n                .collect_vec(),\n            pretty_elements: None,\n            outputs: model_results\n                .outputs\n                .iter()\n                .map(|t| t.deref().to_vec())\n                .collect_vec(),\n            processed_inputs,\n            processed_params,\n            processed_outputs,\n            max_lookup_inputs: model_results.max_lookup_inputs,\n            min_lookup_inputs: model_results.min_lookup_inputs,\n            max_range_size: model_results.max_range_size,\n        };\n\n        witness.generate_rescaled_elements(\n            self.model().graph.get_input_scales(),\n            self.model().graph.get_output_scales()?,\n            visibility,\n        );\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        log::trace!(\n            \"witness: \\n {}\",\n            &witness.as_json()?.to_colored_json_auto()?\n        );\n\n        Ok(witness)\n    }\n\n    /// Create a new circuit from a set of input data and [RunArgs].\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn from_run_args(\n        run_args: &RunArgs,\n        model_path: &std::path::Path,\n    ) -> Result<Self, Box<dyn std::error::Error>> {\n        let model = Model::from_run_args(run_args, model_path)?;\n        Self::new(model, run_args)\n    }\n\n    /// Create a new circuit from a set of input data and [GraphSettings].\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn from_settings(\n        params: &GraphSettings,\n        model_path: &std::path::Path,\n        check_mode: CheckMode,\n    ) -> Result<Self, Box<dyn std::error::Error>> {\n        params.run_args.validate()?;\n        let model = Model::from_run_args(&params.run_args, model_path)?;\n        Self::new_from_settings(model, params.clone(), check_mode)\n    }\n\n    ///\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub async fn populate_on_chain_test_data(\n        &mut self,\n        data: &mut GraphData,\n        test_on_chain_data: TestOnChainData,\n    ) -> Result<(), Box<dyn std::error::Error>> {\n        // Set up local anvil instance for reading on-chain data\n\n        let input_scales = self.model().graph.get_input_scales();\n        let output_scales = self.model().graph.get_output_scales()?;\n        let input_shapes = self.model().graph.input_shapes()?;\n        let output_shapes = self.model().graph.output_shapes()?;\n\n        if matches!(\n            test_on_chain_data.data_sources.input,\n            TestDataSource::OnChain\n        ) {\n            // if not public then fail\n            if self.settings().run_args.input_visibility.is_private() {\n                return Err(\"Cannot use on-chain data source as private data\".into());\n            }\n\n            let input_data = match &data.input_data {\n                DataSource::File(input_data) => input_data,\n                _ => {\n                    return Err(\"Cannot use non file source as input for on-chain test.\n                    Manually populate on-chain data from file source instead\"\n                        .into())\n                }\n            };\n            // Get the flatten length of input_data\n            // if the input source is a field then set scale to 0\n\n            let datam: (Vec<Tensor<Fp>>, OnChainSource) = OnChainSource::test_from_file_data(\n                input_data,\n                input_scales,\n                input_shapes,\n                test_on_chain_data.rpc.as_deref(),\n            )\n            .await?;\n            data.input_data = datam.1.into();\n        }\n        if matches!(\n            test_on_chain_data.data_sources.output,\n            TestDataSource::OnChain\n        ) {\n            // if not public then fail\n            if self.settings().run_args.output_visibility.is_private() {\n                return Err(\"Cannot use on-chain data source as private data\".into());\n            }\n\n            let output_data = match &data.output_data {\n                Some(DataSource::File(output_data)) => output_data,\n                Some(DataSource::OnChain(_)) => {\n                    return Err(\n                        \"Cannot use on-chain data source as output for on-chain test. \n                    Will manually populate on-chain data from file source instead\"\n                            .into(),\n                    )\n                }\n                _ => return Err(\"No output data found\".into()),\n            };\n            let datum: (Vec<Tensor<Fp>>, OnChainSource) = OnChainSource::test_from_file_data(\n                output_data,\n                output_scales,\n                output_shapes,\n                test_on_chain_data.rpc.as_deref(),\n            )\n            .await?;\n            data.output_data = Some(datum.1.into());\n        }\n        // Save the updated GraphData struct to the data_path\n        data.save(test_on_chain_data.data)?;\n        Ok(())\n    }\n}\n\n#[derive(Clone, Debug, Default, Serialize, Deserialize)]\n/// The configuration for the graph circuit\npub struct CircuitSize {\n    num_instances: usize,\n    num_advice_columns: usize,\n    num_fixed: usize,\n    num_challenges: usize,\n    num_selectors: usize,\n    logrows: u32,\n}\n\nimpl CircuitSize {\n    ///\n    pub fn from_cs<F: Field>(cs: &ConstraintSystem<F>, logrows: u32) -> Self {\n        CircuitSize {\n            num_instances: cs.num_instance_columns(),\n            num_advice_columns: cs.num_advice_columns(),\n            num_fixed: cs.num_fixed_columns(),\n            num_challenges: cs.num_challenges(),\n            num_selectors: cs.num_selectors(),\n            logrows,\n        }\n    }\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Export the ezkl configuration as json\n    pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> {\n        let serialized = match serde_json::to_string(&self) {\n            Ok(s) => s,\n            Err(e) => {\n                return Err(Box::new(e));\n            }\n        };\n        Ok(serialized)\n    }\n\n    /// number of columns\n    pub fn num_columns(&self) -> usize {\n        self.num_instances + self.num_advice_columns + self.num_fixed\n    }\n\n    /// area of the circuit\n    pub fn area(&self) -> usize {\n        self.num_columns() * (1 << self.logrows)\n    }\n\n    /// area less than max\n    pub fn area_less_than_max(&self) -> bool {\n        if EZKL_MAX_CIRCUIT_AREA.is_some() {\n            self.area() < EZKL_MAX_CIRCUIT_AREA.unwrap()\n        } else {\n            true\n        }\n    }\n}\n\nimpl Circuit<Fp> for GraphCircuit {\n    type Config = GraphConfig;\n    type FloorPlanner = ModulePlanner;\n    type Params = GraphSettings;\n\n    fn without_witnesses(&self) -> Self {\n        self.clone()\n    }\n\n    fn params(&self) -> Self::Params {\n        // safe to clone because the model is Arc'd\n        self.settings().clone()\n    }\n\n    fn configure_with_params(cs: &mut ConstraintSystem<Fp>, params: Self::Params) -> Self::Config {\n        let mut params = params.clone();\n        params.set_num_blinding_factors(cs.blinding_factors());\n        GLOBAL_SETTINGS.with(|settings| {\n            *settings.borrow_mut() = Some(params.clone());\n        });\n        let visibility = match VarVisibility::from_args(&params.run_args) {\n            Ok(v) => v,\n            Err(e) => {\n                log::error!(\"failed to create visibility: {:?}\", e);\n                log::warn!(\"using default visibility\");\n                VarVisibility::default()\n            }\n        };\n\n        let mut module_configs = ModuleConfigs::from_visibility(\n            cs,\n            params.module_sizes.clone(),\n            params.run_args.logrows as usize,\n        );\n\n        let mut vars = ModelVars::new(cs, &params);\n\n        module_configs.configure_complex_modules(cs, visibility, params.module_sizes.clone());\n\n        vars.instantiate_instance(\n            cs,\n            params.model_instance_shapes.clone(),\n            params.run_args.input_scale,\n            module_configs.instance,\n        );\n\n        let base = Model::configure(cs, &vars, &params).unwrap();\n\n        let model_config = ModelConfig { base, vars };\n\n        debug!(\n            \"degree: {}, log2_ceil of degrees: {:?}\",\n            cs.degree(),\n            (cs.degree() as f32).log2().ceil()\n        );\n\n        let circuit_size = CircuitSize::from_cs(cs, params.run_args.logrows);\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        debug!(\n            \"circuit size: \\n {}\",\n            circuit_size\n                .as_json()\n                .unwrap()\n                .to_colored_json_auto()\n                .unwrap()\n        );\n\n        GraphConfig {\n            model_config,\n            module_configs,\n            circuit_size,\n        }\n    }\n\n    fn configure(_: &mut ConstraintSystem<Fp>) -> Self::Config {\n        unimplemented!(\"you should call configure_with_params instead\")\n    }\n\n    fn synthesize(\n        &self,\n        config: Self::Config,\n        mut layouter: impl Layouter<Fp>,\n    ) -> Result<(), PlonkError> {\n        // check if the circuit area is less than the max\n        if !config.circuit_size.area_less_than_max() {\n            error!(\n                \"circuit area {} is larger than the max allowed area {}\",\n                config.circuit_size.area(),\n                EZKL_MAX_CIRCUIT_AREA.unwrap()\n            );\n            return Err(PlonkError::Synthesis);\n        }\n\n        trace!(\"Setting input in synthesize\");\n        let input_vis = &self.settings().run_args.input_visibility;\n        let output_vis = &self.settings().run_args.output_visibility;\n        let mut graph_modules = GraphModules::new();\n\n        let mut constants = ConstantsMap::new();\n\n        let mut config = config.clone();\n\n        let mut inputs = self\n            .graph_witness\n            .get_input_tensor()\n            .iter_mut()\n            .map(|i| {\n                i.set_visibility(input_vis);\n                ValTensor::try_from(i.clone()).map_err(|e| {\n                    log::error!(\"failed to convert input to valtensor: {:?}\", e);\n                    PlonkError::Synthesis\n                })\n            })\n            .collect::<Result<Vec<ValTensor<Fp>>, PlonkError>>()?;\n\n        let outputs = self\n            .graph_witness\n            .get_output_tensor()\n            .iter_mut()\n            .map(|i| {\n                i.set_visibility(output_vis);\n                ValTensor::try_from(i.clone()).map_err(|e| {\n                    log::error!(\"failed to convert output to valtensor: {:?}\", e);\n                    PlonkError::Synthesis\n                })\n            })\n            .collect::<Result<Vec<ValTensor<Fp>>, PlonkError>>()?;\n\n        let mut instance_offset = 0;\n        trace!(\"running input module layout\");\n\n        let input_visibility = &self.settings().run_args.input_visibility;\n        let outlets = input_visibility.overwrites_inputs();\n\n        if !outlets.is_empty() {\n            let mut input_outlets = vec![];\n            for outlet in &outlets {\n                input_outlets.push(inputs[*outlet].clone());\n            }\n            graph_modules.layout(\n                &mut layouter,\n                &mut config.module_configs,\n                &mut input_outlets,\n                input_visibility,\n                &mut instance_offset,\n                &mut constants,\n            )?;\n            // replace inputs with the outlets\n            for (i, outlet) in outlets.iter().enumerate() {\n                inputs[*outlet] = input_outlets[i].clone();\n            }\n        } else {\n            graph_modules.layout(\n                &mut layouter,\n                &mut config.module_configs,\n                &mut inputs,\n                input_visibility,\n                &mut instance_offset,\n                &mut constants,\n            )?;\n        }\n\n        // now we need to assign the flattened params to the model\n        let mut model = self.model().clone();\n        let param_visibility = &self.settings().run_args.param_visibility;\n        trace!(\"running params module layout\");\n        if !self.model().get_all_params().is_empty() && param_visibility.requires_processing() {\n            // now we need to flatten the params\n            let consts = self.model().get_all_params();\n\n            let mut flattened_params = {\n                let mut t = Tensor::new(Some(&consts), &[consts.len()])\n                    .map_err(|_| {\n                        log::error!(\"failed to flatten params\");\n                        PlonkError::Synthesis\n                    })?\n                    .combine()\n                    .map_err(|_| {\n                        log::error!(\"failed to combine params\");\n                        PlonkError::Synthesis\n                    })?;\n                t.set_visibility(param_visibility);\n                vec![t.try_into().map_err(|_| {\n                    log::error!(\"failed to convert params to valtensor\");\n                    PlonkError::Synthesis\n                })?]\n            };\n\n            // now do stuff to the model params\n            graph_modules.layout(\n                &mut layouter,\n                &mut config.module_configs,\n                &mut flattened_params,\n                param_visibility,\n                &mut instance_offset,\n                &mut constants,\n            )?;\n\n            let shapes = self.model().const_shapes();\n            trace!(\"replacing processed consts\");\n            let split_params = split_valtensor(&flattened_params[0], shapes).map_err(|_| {\n                log::error!(\"failed to split params\");\n                PlonkError::Synthesis\n            })?;\n\n            // now the flattened_params have been assigned to and we-assign them to the model consts such that they are constrained to be equal\n            model.replace_consts(&split_params);\n        }\n\n        // create a new module for the model (space 2)\n        layouter.assign_region(|| \"_enter_module_2\", |_| Ok(()))?;\n        trace!(\"laying out model\");\n\n        let mut vars = config.model_config.vars.clone();\n        vars.set_initial_instance_offset(instance_offset);\n\n        let mut outputs = model\n            .layout(\n                config.model_config.clone(),\n                &mut layouter,\n                &self.settings().run_args,\n                &inputs,\n                &mut vars,\n                &outputs,\n                &mut constants,\n            )\n            .map_err(|e| {\n                log::error!(\"{}\", e);\n                PlonkError::Synthesis\n            })?;\n        trace!(\"running output module layout\");\n\n        let output_visibility = &self.settings().run_args.output_visibility;\n        let outlets = output_visibility.overwrites_inputs();\n\n        instance_offset += vars.get_instance_len();\n\n        if !outlets.is_empty() {\n            let mut output_outlets = vec![];\n            for outlet in &outlets {\n                output_outlets.push(outputs[*outlet].clone());\n            }\n            // this will re-enter module 0\n            graph_modules.layout(\n                &mut layouter,\n                &mut config.module_configs,\n                &mut output_outlets,\n                &self.settings().run_args.output_visibility,\n                &mut instance_offset,\n                &mut constants,\n            )?;\n\n            // replace outputs with the outlets\n            for (i, outlet) in outlets.iter().enumerate() {\n                outputs[*outlet] = output_outlets[i].clone();\n            }\n        } else {\n            graph_modules.layout(\n                &mut layouter,\n                &mut config.module_configs,\n                &mut outputs,\n                &self.settings().run_args.output_visibility,\n                &mut instance_offset,\n                &mut constants,\n            )?;\n        }\n\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/model.rs",
        "content": "use super::extract_const_quantized_values;\nuse super::node::*;\nuse super::scale_to_multiplier;\nuse super::vars::*;\nuse super::GraphError;\nuse super::GraphSettings;\nuse crate::circuit::hybrid::HybridOp;\nuse crate::circuit::region::ConstantsMap;\nuse crate::circuit::region::RegionCtx;\nuse crate::circuit::table::Range;\nuse crate::circuit::Input;\nuse crate::circuit::InputType;\nuse crate::circuit::Unknown;\nuse crate::tensor::ValType;\nuse crate::{\n    circuit::{lookup::LookupOp, BaseConfig as PolyConfig, CheckMode, Op},\n    tensor::{Tensor, ValTensor},\n    RunArgs,\n};\nuse halo2curves::bn256::Fr as Fp;\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse super::input::GraphData;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored::Colorize;\nuse halo2_proofs::{\n    circuit::{Layouter, Value},\n    plonk::ConstraintSystem,\n};\nuse halo2curves::ff::Field;\nuse itertools::Itertools;\nuse log::error;\nuse log::{debug, info, trace};\nuse serde::Deserialize;\nuse serde::Serialize;\nuse std::collections::BTreeMap;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::error::Error;\nuse std::fs;\nuse std::io::Read;\nuse std::path::PathBuf;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tabled::Table;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::prelude::{\n    Framework, Graph, InferenceFact, InferenceModelExt, SymbolValues, TypedFact, TypedOp,\n};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_core::internal::DatumType;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_hir::ops::scan::Scan;\nuse unzip_n::unzip_n;\n\nunzip_n!(pub 3);\n\n#[cfg(not(target_arch = \"wasm32\"))]\ntype TractResult = (Graph<TypedFact, Box<dyn TypedOp>>, SymbolValues);\n/// The result of a forward pass.\n#[derive(Clone, Debug)]\npub struct ForwardResult {\n    /// The outputs of the forward pass.\n    pub outputs: Vec<Tensor<Fp>>,\n    /// The maximum value of any input to a lookup operation.\n    pub max_lookup_inputs: i128,\n    /// The minimum value of any input to a lookup operation.\n    pub min_lookup_inputs: i128,\n    /// The max range check size\n    pub max_range_size: i128,\n}\n\nimpl From<DummyPassRes> for ForwardResult {\n    fn from(res: DummyPassRes) -> Self {\n        Self {\n            outputs: res.outputs,\n            max_lookup_inputs: res.max_lookup_inputs,\n            min_lookup_inputs: res.min_lookup_inputs,\n            max_range_size: res.max_range_size,\n        }\n    }\n}\n\n/// A circuit configuration for the entirety of a model loaded from an Onnx file.\n#[derive(Clone, Debug)]\npub struct ModelConfig {\n    /// The base configuration for the circuit\n    pub base: PolyConfig<Fp>,\n    /// A wrapper for holding all columns that will be assigned to by the model\n    pub vars: ModelVars<Fp>,\n}\n\n/// Representation of execution graph\npub type NodeGraph = BTreeMap<usize, NodeType>;\n\n/// A struct for loading from an Onnx file and converting a computational graph to a circuit.\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\npub struct DummyPassRes {\n    /// number of rows use\n    pub num_rows: usize,\n    /// num dynamic lookups\n    pub num_dynamic_lookups: usize,\n    /// dynamic lookup col size\n    pub dynamic_lookup_col_coord: usize,\n    /// num shuffles\n    pub num_shuffles: usize,\n    /// shuffle\n    pub shuffle_col_coord: usize,\n    /// linear coordinate\n    pub linear_coord: usize,\n    /// total const size\n    pub total_const_size: usize,\n    /// lookup ops\n    pub lookup_ops: HashSet<LookupOp>,\n    /// range checks\n    pub range_checks: HashSet<Range>,\n    /// max lookup inputs\n    pub max_lookup_inputs: i128,\n    /// min lookup inputs\n    pub min_lookup_inputs: i128,\n    /// min range check\n    pub max_range_size: i128,\n    /// outputs\n    pub outputs: Vec<Tensor<Fp>>,\n}\n\n/// A struct for loading from an Onnx file and converting a computational graph to a circuit.\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\npub struct Model {\n    /// input indices\n    pub graph: ParsedNodes,\n    /// Defines which inputs to the model are public and private (params, inputs, outputs) using [VarVisibility].\n    pub visibility: VarVisibility,\n}\n\n///\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]\npub enum OutputMapping {\n    ///\n    Single {\n        ///\n        outlet: usize,\n        ///\n        is_state: bool,\n    },\n    ///\n    Stacked {\n        ///\n        outlet: usize,\n        ///\n        axis: usize,\n        ///\n        is_state: bool,\n    },\n}\n\nimpl OutputMapping {\n    ///\n    pub fn is_state(&self) -> bool {\n        match self {\n            OutputMapping::Single { is_state, .. } => *is_state,\n            OutputMapping::Stacked { is_state, .. } => *is_state,\n        }\n    }\n\n    ///\n    pub fn outlet(&self) -> usize {\n        match self {\n            OutputMapping::Single { outlet, .. } => *outlet,\n            OutputMapping::Stacked { outlet, .. } => *outlet,\n        }\n    }\n}\n\n///\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]\npub enum InputMapping {\n    ///\n    Full,\n    ///\n    State,\n    ///\n    Stacked {\n        ///\n        axis: usize,\n        ///\n        chunk: usize,\n    },\n}\n\nfn number_of_iterations(mappings: &[InputMapping], dims: Vec<&[usize]>) -> usize {\n    let mut number_of_iterations =\n        dims.iter()\n            .zip(mappings)\n            .filter_map(|(dims, mapping)| match mapping {\n                InputMapping::Stacked { axis, chunk } => Some(\n                    // number of iterations given the dim size along the axis\n                    // and the chunk size\n                    (dims[*axis] + chunk - 1) / chunk,\n                ),\n                _ => None,\n            });\n    // assert all collected number of iterations are equal\n    assert!(number_of_iterations.clone().all_equal());\n\n    number_of_iterations.next().unwrap_or(1)\n}\n\nfn input_state_idx(input_mappings: &[InputMapping]) -> Vec<usize> {\n    input_mappings\n        .iter()\n        .enumerate()\n        .filter(|(_, r)| matches!(r, InputMapping::State))\n        .map(|(index, _)| index)\n        .collect::<Vec<_>>()\n}\n\nfn output_state_idx(output_mappings: &[Vec<OutputMapping>]) -> Vec<usize> {\n    output_mappings\n        .iter()\n        .flatten()\n        .filter_map(|x| if x.is_state() { Some(x.outlet()) } else { None })\n        .collect::<Vec<_>>()\n}\n\n/// Enables model as subnode of other models\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]\npub enum NodeType {\n    /// A node in the model\n    Node(Node),\n    /// A submodel\n    SubGraph {\n        /// The subgraph\n        model: Model,\n        /// The subgraph's inputs\n        inputs: Vec<Outlet>,\n        /// the subgraph's idx within the parent graph\n        idx: usize,\n        /// output mappings\n        output_mappings: Vec<Vec<OutputMapping>>,\n        /// input mappings\n        input_mappings: Vec<InputMapping>,\n        ///\n        out_dims: Vec<Vec<usize>>,\n        ///\n        out_scales: Vec<crate::Scale>,\n    },\n}\n\nimpl NodeType {\n    ///\n    pub fn is_lookup(&self) -> bool {\n        match self {\n            NodeType::Node(n) => n.opkind.is_lookup(),\n            NodeType::SubGraph { .. } => false,\n        }\n    }\n    ///\n    pub fn num_uses(&self) -> usize {\n        match self {\n            NodeType::Node(n) => n.num_uses,\n            NodeType::SubGraph { .. } => 0,\n        }\n    }\n\n    /// Returns the indices of the node's inputs.\n    pub fn inputs(&self) -> Vec<Outlet> {\n        match self {\n            NodeType::Node(n) => n.inputs.clone(),\n            NodeType::SubGraph { inputs, .. } => inputs.clone(),\n        }\n    }\n\n    /// Returns the dimensions of the node's output.\n    pub fn out_dims(&self) -> Vec<Vec<usize>> {\n        match self {\n            NodeType::Node(n) => vec![n.out_dims.clone()],\n            NodeType::SubGraph { out_dims, .. } => out_dims.clone(),\n        }\n    }\n\n    /// Returns the scales of the node's output.\n    pub fn out_scales(&self) -> Vec<crate::Scale> {\n        match self {\n            NodeType::Node(n) => vec![n.out_scale],\n            NodeType::SubGraph { out_scales, .. } => out_scales.clone(),\n        }\n    }\n\n    /// Returns a string representation of the operation.\n    pub fn as_str(&self) -> String {\n        match self {\n            NodeType::Node(n) => n.opkind.as_string(),\n            NodeType::SubGraph { .. } => \"SUBGRAPH\".into(),\n        }\n    }\n\n    /// Returns true if the operation is a rebase\n    pub fn is_rebase(&self) -> bool {\n        match self {\n            NodeType::Node(n) => matches!(n.opkind, SupportedOp::RebaseScale { .. }),\n            NodeType::SubGraph { .. } => false,\n        }\n    }\n\n    /// Returns true if the operation is an input.\n    pub fn is_input(&self) -> bool {\n        match self {\n            NodeType::Node(n) => n.opkind.is_input(),\n            NodeType::SubGraph { .. } => false,\n        }\n    }\n    /// Returns true if the operation is a const.\n    pub fn is_constant(&self) -> bool {\n        match self {\n            NodeType::Node(n) => n.opkind.is_constant(),\n            NodeType::SubGraph { .. } => false,\n        }\n    }\n\n    /// Returns the node's unique identifier.\n    pub fn idx(&self) -> usize {\n        match self {\n            NodeType::Node(n) => n.idx,\n            NodeType::SubGraph { idx, .. } => *idx,\n        }\n    }\n\n    /// decrement const num times used\n    pub fn decrement_use(&mut self) {\n        match self {\n            NodeType::Node(n) => n.num_uses -= 1,\n            NodeType::SubGraph { .. } => log::warn!(\"Cannot decrement const of subgraph\"),\n        }\n    }\n\n    /// bunp scale of node\n    pub fn bump_scale(&mut self, scale: crate::Scale) {\n        match self {\n            NodeType::Node(n) => n.out_scale = scale,\n            NodeType::SubGraph { .. } => log::warn!(\"Cannot bump scale of subgraph\"),\n        }\n    }\n\n    /// Replace the operation kind of the node.\n    pub fn replace_opkind(&mut self, opkind: SupportedOp) {\n        match self {\n            NodeType::Node(n) => n.opkind = opkind,\n            NodeType::SubGraph { .. } => log::warn!(\"Cannot replace opkind of subgraph\"),\n        }\n    }\n\n    /// Returns the operation kind of the node (if any).\n    pub fn opkind(&self) -> SupportedOp {\n        match self {\n            NodeType::Node(n) => n.opkind.clone(),\n            NodeType::SubGraph { .. } => SupportedOp::Unknown(Unknown),\n        }\n    }\n}\n\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\n/// A set of EZKL nodes that represent a computational graph.\npub struct ParsedNodes {\n    /// The nodes in the graph.\n    pub nodes: BTreeMap<usize, NodeType>,\n    inputs: Vec<usize>,\n    outputs: Vec<Outlet>,\n}\n\nimpl ParsedNodes {\n    /// Returns the number of the computational graph's inputs\n    pub fn num_inputs(&self) -> usize {\n        let input_nodes = self.inputs.iter();\n        input_nodes.len()\n    }\n\n    /// Input types\n    pub fn get_input_types(&self) -> Result<Vec<InputType>, GraphError> {\n        self.inputs\n            .iter()\n            .map(|o| {\n                match self\n                    .nodes\n                    .get(o)\n                    .ok_or(GraphError::MissingNode(*o))?\n                    .opkind()\n                {\n                    SupportedOp::Input(Input { datum_type, .. }) => Ok(datum_type.clone()),\n                    _ => Err(GraphError::InvalidInputTypes),\n                }\n            })\n            .collect::<Result<Vec<_>, _>>()\n    }\n\n    ///  Returns shapes of the computational graph's inputs\n    pub fn input_shapes(&self) -> Result<Vec<Vec<usize>>, Box<dyn Error>> {\n        let mut inputs = vec![];\n\n        for input in self.inputs.iter() {\n            let node = self\n                .nodes\n                .get(input)\n                .ok_or(GraphError::MissingNode(*input))?;\n            let input_dims = node.out_dims();\n            let input_dim = input_dims.first().ok_or(GraphError::MissingNode(*input))?;\n            inputs.push(input_dim.clone());\n        }\n\n        Ok(inputs)\n    }\n\n    /// Returns the number of the computational graph's outputs\n    pub fn num_outputs(&self) -> usize {\n        let output_nodes = self.outputs.iter();\n        output_nodes.len()\n    }\n\n    /// Returns shapes of the computational graph's outputs\n    pub fn output_shapes(&self) -> Result<Vec<Vec<usize>>, GraphError> {\n        let mut outputs = vec![];\n\n        for output in self.outputs.iter() {\n            let (idx, outlet) = output;\n            let node = self.nodes.get(idx).ok_or(GraphError::MissingNode(*idx))?;\n            let out_dims = node.out_dims();\n            let out_dim = out_dims\n                .get(*outlet)\n                .ok_or(GraphError::MissingNode(*outlet))?;\n            outputs.push(out_dim.clone());\n        }\n\n        Ok(outputs)\n    }\n\n    /// Returns the fixed point scale of the computational graph's inputs\n    pub fn get_input_scales(&self) -> Vec<crate::Scale> {\n        let input_nodes = self.inputs.iter();\n        input_nodes\n            .flat_map(|idx| {\n                self.nodes\n                    .get(idx)\n                    .ok_or(GraphError::MissingNode(*idx))\n                    .map(|n| n.out_scales())\n                    .unwrap_or_default()\n            })\n            .collect()\n    }\n\n    /// Returns the fixed point scale of the computational graph's outputs\n    pub fn get_output_scales(&self) -> Result<Vec<crate::Scale>, GraphError> {\n        let output_nodes = self.outputs.iter();\n        output_nodes\n            .map(|(idx, outlet)| {\n                Ok(self\n                    .nodes\n                    .get(idx)\n                    .ok_or(GraphError::MissingNode(*idx))?\n                    .out_scales()[*outlet])\n            })\n            .collect::<Result<Vec<_>, GraphError>>()\n    }\n}\n\nimpl Model {\n    /// Creates a `Model` from a specified path to an Onnx file.\n    /// # Arguments\n    /// * `reader` - A reader for an Onnx file.\n    /// * `run_args` - [RunArgs]\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn new(reader: &mut dyn std::io::Read, run_args: &RunArgs) -> Result<Self, Box<dyn Error>> {\n        let visibility = VarVisibility::from_args(run_args)?;\n\n        let graph = Self::load_onnx_model(reader, run_args, &visibility)?;\n\n        let om = Model { graph, visibility };\n\n        debug!(\"\\n {}\", om.table_nodes());\n\n        Ok(om)\n    }\n\n    ///\n    pub fn save(&self, path: PathBuf) -> Result<(), Box<dyn Error>> {\n        let f = std::fs::File::create(path)?;\n        let writer = std::io::BufWriter::new(f);\n        bincode::serialize_into(writer, &self)?;\n        Ok(())\n    }\n\n    ///\n    pub fn load(path: PathBuf) -> Result<Self, Box<dyn Error>> {\n        // read bytes from file\n        let mut f = std::fs::File::open(&path)?;\n        let metadata = fs::metadata(&path)?;\n        let mut buffer = vec![0; metadata.len() as usize];\n        f.read_exact(&mut buffer)?;\n        let result = bincode::deserialize(&buffer)?;\n        Ok(result)\n    }\n\n    /// Generate model parameters for the circuit\n    pub fn gen_params(\n        &self,\n        run_args: &RunArgs,\n        check_mode: CheckMode,\n    ) -> Result<GraphSettings, Box<dyn Error>> {\n        let instance_shapes = self.instance_shapes()?;\n        #[cfg(not(target_arch = \"wasm32\"))]\n        debug!(\n            \"{} {} {}\",\n            \"model has\".blue(),\n            instance_shapes.len().to_string().blue(),\n            \"instances\".blue()\n        );\n\n        let inputs: Vec<ValTensor<Fp>> = self\n            .graph\n            .input_shapes()?\n            .iter()\n            .map(|shape| {\n                let len = shape.iter().product();\n                let mut t: ValTensor<Fp> = (0..len)\n                    .map(|_| {\n                        if !self.visibility.input.is_fixed() {\n                            ValType::Value(Value::<Fp>::unknown())\n                        } else {\n                            ValType::Constant(Fp::random(&mut rand::thread_rng()))\n                        }\n                    })\n                    .collect::<Vec<_>>()\n                    .into();\n\n                t.reshape(shape)?;\n                Ok(t)\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n        let res = self.dummy_layout(run_args, &inputs, false)?;\n\n        // if we're using percentage tolerance, we need to add the necessary range check ops for it.\n\n        Ok(GraphSettings {\n            run_args: run_args.clone(),\n            model_instance_shapes: instance_shapes,\n            module_sizes: crate::graph::modules::ModuleSizes::default(),\n            num_rows: res.num_rows,\n            total_assignments: res.linear_coord,\n            required_lookups: res.lookup_ops.into_iter().collect(),\n            required_range_checks: res.range_checks.into_iter().collect(),\n            model_output_scales: self.graph.get_output_scales()?,\n            model_input_scales: self.graph.get_input_scales(),\n            num_dynamic_lookups: res.num_dynamic_lookups,\n            total_dynamic_col_size: res.dynamic_lookup_col_coord,\n            num_shuffles: res.num_shuffles,\n            total_shuffle_col_size: res.shuffle_col_coord,\n            total_const_size: res.total_const_size,\n            check_mode,\n            version: env!(\"CARGO_PKG_VERSION\").to_string(),\n            num_blinding_factors: None,\n            // unix time timestamp\n            #[cfg(not(target_arch = \"wasm32\"))]\n            timestamp: Some(\n                instant::SystemTime::now()\n                    .duration_since(instant::SystemTime::UNIX_EPOCH)?\n                    .as_millis(),\n            ),\n            #[cfg(target_arch = \"wasm32\")]\n            timestamp: None,\n        })\n    }\n\n    /// Runs a forward pass on sample data !\n    /// # Arguments\n    /// * `reader` - A reader for an Onnx file.\n    /// * `model_inputs` - A vector of [Tensor]s to use as inputs to the model.\n    /// * `run_args` - [RunArgs]\n    pub fn forward(\n        &self,\n        model_inputs: &[Tensor<Fp>],\n        run_args: &RunArgs,\n        witness_gen: bool,\n    ) -> Result<ForwardResult, Box<dyn Error>> {\n        let valtensor_inputs: Vec<ValTensor<Fp>> = model_inputs\n            .iter()\n            .map(|x| x.map(|elem| ValType::Value(Value::known(elem))).into())\n            .collect();\n        let res = self.dummy_layout(run_args, &valtensor_inputs, witness_gen)?;\n        Ok(res.into())\n    }\n\n    /// Loads an Onnx model from a specified path.\n    /// # Arguments\n    /// * `reader` - A reader for an Onnx file.\n    /// * `scale` - The scale to use for quantization.\n    /// * `public_params` - Whether to make the params public.\n    #[cfg(not(target_arch = \"wasm32\"))]\n    fn load_onnx_using_tract(\n        reader: &mut dyn std::io::Read,\n        run_args: &RunArgs,\n    ) -> Result<TractResult, Box<dyn Error>> {\n        use tract_onnx::{\n            tract_core::internal::IntoArcTensor, tract_hir::internal::GenericFactoid,\n        };\n\n        let mut model = tract_onnx::onnx().model_for_read(reader).map_err(|e| {\n            error!(\"Error loading model: {}\", e);\n            GraphError::ModelLoad\n        })?;\n\n        let variables: std::collections::HashMap<String, usize> =\n            std::collections::HashMap::from_iter(run_args.variables.clone());\n\n        for (i, id) in model.clone().inputs.iter().enumerate() {\n            let input = model.node_mut(id.node);\n            let mut fact: InferenceFact = input.outputs[0].fact.clone();\n\n            for (i, x) in fact.clone().shape.dims().enumerate() {\n                if matches!(x, GenericFactoid::Any) {\n                    let batch_size = match variables.get(\"batch_size\") {\n                        Some(x) => x,\n                        None => return Err(\"Unknown dimension batch_size in model inputs, set batch_size in variables\".into()),\n                    };\n                    fact.shape\n                        .set_dim(i, tract_onnx::prelude::TDim::Val(*batch_size as i64));\n                }\n            }\n\n            model.set_input_fact(i, fact)?;\n        }\n\n        for (i, _) in model.clone().outputs.iter().enumerate() {\n            model.set_output_fact(i, InferenceFact::default())?;\n        }\n\n        let mut symbol_values = SymbolValues::default();\n        for (symbol, value) in run_args.variables.iter() {\n            let symbol = model.symbol_table.sym(symbol);\n            symbol_values = symbol_values.with(&symbol, *value as i64);\n            debug!(\"set {} to {}\", symbol, value);\n        }\n\n        // Note: do not optimize the model, as the layout will depend on underlying hardware\n        let mut typed_model = model\n            .into_typed()?\n            .concretize_dims(&symbol_values)?\n            .into_decluttered()?;\n\n        // concretize constants\n        for node in typed_model.eval_order()? {\n            let node = typed_model.node_mut(node);\n            if let Some(op) = node.op_as_mut::<tract_onnx::tract_core::ops::konst::Const>() {\n                if op.0.datum_type() == DatumType::TDim {\n                    // get inner value to Arc<Tensor>\n                    let mut constant = op.0.as_ref().clone();\n                    // Generally a shape or hyperparam\n                    constant\n                        .as_slice_mut::<tract_onnx::prelude::TDim>()?\n                        .iter_mut()\n                        .for_each(|x| *x = x.eval(&symbol_values));\n\n                    op.0 = constant.into_arc_tensor();\n                }\n            }\n        }\n\n        Ok((typed_model, symbol_values))\n    }\n\n    /// Loads an Onnx model from a specified path.\n    /// # Arguments\n    /// * `reader` - A reader for an Onnx file.\n    /// * `scale` - The scale to use for quantization.\n    /// * `public_params` - Whether to make the params public.\n    #[cfg(not(target_arch = \"wasm32\"))]\n    fn load_onnx_model(\n        reader: &mut dyn std::io::Read,\n        run_args: &RunArgs,\n        visibility: &VarVisibility,\n    ) -> Result<ParsedNodes, Box<dyn Error>> {\n        let start_time = instant::Instant::now();\n\n        let (model, symbol_values) = Self::load_onnx_using_tract(reader, run_args)?;\n\n        let scales = VarScales::from_args(run_args)?;\n        let nodes = Self::nodes_from_graph(\n            &model,\n            run_args,\n            &scales,\n            visibility,\n            &symbol_values,\n            None,\n            None,\n        )?;\n\n        debug!(\"\\n {}\", model);\n\n        let parsed_nodes = ParsedNodes {\n            nodes,\n            inputs: model.inputs.iter().map(|o| o.node).collect(),\n            outputs: model.outputs.iter().map(|o| (o.node, o.slot)).collect(),\n        };\n\n        let duration = start_time.elapsed();\n        trace!(\"model loading took: {:?}\", duration);\n\n        Ok(parsed_nodes)\n    }\n\n    /// Formats nodes (including subgraphs) into tables !\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn table_nodes(&self) -> String {\n        let mut node_accumulator = vec![];\n        let mut string = String::new();\n        for (idx, node) in &self.graph.nodes {\n            match node {\n                NodeType::Node(n) => {\n                    node_accumulator.push(n);\n                }\n                NodeType::SubGraph { model, inputs, .. } => {\n                    let mut table = Table::new(node_accumulator.iter());\n                    table.with(tabled::settings::Style::modern());\n                    table.with(tabled::settings::Shadow::new(1));\n                    table.with(\n                        tabled::settings::style::BorderColor::default()\n                            .top(tabled::settings::Color::BG_YELLOW),\n                    );\n                    string = format!(\"{} \\n\\n  MAIN GRAPH \\n\\n{}\", string, table);\n                    node_accumulator = vec![];\n                    string = format!(\n                        \"{}\\n\\n SUBGRAPH AT IDX {} WITH INPUTS {:?}\\n{}\",\n                        string,\n                        idx,\n                        inputs,\n                        model.table_nodes(),\n                    );\n                }\n            }\n        }\n\n        let mut table = Table::new(node_accumulator.iter());\n        table.with(tabled::settings::Style::modern());\n        format!(\"{} \\n{}\", string, table)\n    }\n\n    /// Creates ezkl nodes from a tract graph\n    /// # Arguments\n    /// * `graph` - A tract graph.\n    /// * `run_args` - [RunArgs]\n    /// * `visibility` - Which inputs to the model are public and private (params, inputs, outputs) using [VarVisibility].\n    /// * `input_scales` - The scales of the model's inputs.\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn nodes_from_graph(\n        graph: &Graph<TypedFact, Box<dyn TypedOp>>,\n        run_args: &RunArgs,\n        scales: &VarScales,\n        visibility: &VarVisibility,\n        symbol_values: &SymbolValues,\n        override_input_scales: Option<Vec<crate::Scale>>,\n        override_output_scales: Option<HashMap<usize, crate::Scale>>,\n    ) -> Result<BTreeMap<usize, NodeType>, Box<dyn Error>> {\n        use crate::graph::node_output_shapes;\n\n        let mut nodes = BTreeMap::<usize, NodeType>::new();\n        let mut input_idx = 0;\n        for (i, n) in graph.nodes.iter().enumerate() {\n            // Extract the slope layer hyperparams\n            match n.op().downcast_ref::<Scan>() {\n                Some(b) => {\n                    let model = b.body.clone();\n                    let input_scales = n\n                        .inputs\n                        .iter()\n                        .map(|i| {\n                            Ok(nodes\n                                .get(&i.node)\n                                .ok_or(GraphError::MissingNode(i.node))?\n                                .out_scales()[0])\n                        })\n                        .collect::<Result<Vec<_>, GraphError>>()?;\n\n                    let mut input_mappings = vec![];\n                    for mapping in &b.input_mapping {\n                        match mapping {\n                            tract_onnx::tract_hir::ops::scan::InputMapping::Scan(info) => {\n                                input_mappings.push(InputMapping::Stacked {\n                                    axis: info.axis,\n                                    chunk: info.chunk as usize,\n                                });\n                            }\n                            tract_onnx::tract_hir::ops::scan::InputMapping::State => {\n                                input_mappings.push(InputMapping::State);\n                            }\n                            tract_onnx::tract_hir::ops::scan::InputMapping::Full => {\n                                input_mappings.push(InputMapping::Full);\n                            }\n                        }\n                    }\n\n                    let input_state_idx = input_state_idx(&input_mappings);\n\n                    let mut output_mappings = vec![];\n                    for (i, mapping) in b.output_mapping.iter().enumerate() {\n                        let mut mappings = vec![];\n                        if let Some(outlet) = mapping.last_value_slot {\n                            mappings.push(OutputMapping::Single {\n                                outlet,\n                                is_state: mapping.state,\n                            });\n                        } else if mapping.state {\n                            mappings.push(OutputMapping::Single {\n                                outlet: i,\n                                is_state: mapping.state,\n                            });\n                        }\n                        if let Some(last) = mapping.scan {\n                            mappings.push(OutputMapping::Stacked {\n                                outlet: last.0,\n                                axis: last.1.axis,\n                                is_state: false,\n                            });\n                        }\n\n                        output_mappings.push(mappings);\n                    }\n\n                    let output_state_idx = output_state_idx(&output_mappings);\n\n                    let mut output_scale_override = HashMap::new();\n                    // if input_state_idx and output_state_idx have mismatched scales we need to rebase the scale of the output node\n                    for (input_idx, output_idx) in input_state_idx.iter().zip(output_state_idx) {\n                        let input_scale = input_scales[*input_idx];\n                        // output mappings is a vec of vec. we need to find the outer index of the output node we want to rebase.\n                        let mut traversed_len = 0;\n                        for (outer_idx, mappings) in output_mappings.iter().enumerate() {\n                            let mapping_len = mappings.len();\n                            if traversed_len + mapping_len > output_idx {\n                                let output_node_idx = b.body.outputs[outer_idx].node;\n                                output_scale_override.insert(output_node_idx, input_scale);\n                            }\n                            traversed_len += mapping_len;\n                        }\n                    }\n\n                    let subgraph_nodes = Self::nodes_from_graph(\n                        &model,\n                        run_args,\n                        scales,\n                        visibility,\n                        symbol_values,\n                        Some(input_scales.clone()),\n                        Some(output_scale_override),\n                    )?;\n\n                    let subgraph = ParsedNodes {\n                        nodes: subgraph_nodes,\n                        inputs: model.inputs.iter().map(|o| o.node).collect(),\n                        outputs: model.outputs.iter().map(|o| (o.node, o.slot)).collect(),\n                    };\n\n                    let om = Model {\n                        graph: subgraph,\n                        visibility: visibility.clone(),\n                    };\n\n                    let out_dims = node_output_shapes(n, symbol_values)?;\n\n                    let mut output_scales = BTreeMap::new();\n\n                    for (i, _mapping) in b.output_mapping.iter().enumerate() {\n                        for mapping in b.output_mapping.iter() {\n                            if let Some(outlet) = mapping.last_value_slot {\n                                output_scales.insert(outlet, om.graph.get_output_scales()?[i]);\n                            }\n                            if let Some(last) = mapping.scan {\n                                output_scales.insert(last.0, om.graph.get_output_scales()?[i]);\n                            }\n                        }\n                    }\n\n                    let out_scales = output_scales.into_values().collect_vec();\n\n                    nodes.insert(\n                        i,\n                        NodeType::SubGraph {\n                            model: om,\n                            inputs: n.inputs.iter().map(|i| (i.node, i.slot)).collect_vec(),\n                            idx: i,\n                            output_mappings,\n                            input_mappings,\n                            out_dims,\n                            out_scales,\n                        },\n                    );\n                }\n                None => {\n                    let mut n = Node::new(\n                        n.clone(),\n                        &mut nodes,\n                        scales,\n                        &run_args.param_visibility,\n                        i,\n                        symbol_values,\n                        run_args.div_rebasing,\n                        run_args.rebase_frac_zero_constants,\n                    )?;\n                    if let Some(ref scales) = override_input_scales {\n                        if let Some(inp) = n.opkind.get_input() {\n                            let scale = scales[input_idx];\n                            n.opkind = SupportedOp::Input(Input {\n                                scale,\n                                datum_type: inp.datum_type,\n                            });\n                            input_idx += 1;\n                            n.out_scale = scale;\n                        }\n                    }\n                    if let Some(ref scales) = override_output_scales {\n                        if scales.contains_key(&i) {\n                            let scale_diff = n.out_scale - scales[&i];\n                            n.opkind = if scale_diff > 0 {\n                                RebaseScale::rebase(\n                                    n.opkind,\n                                    scales[&i],\n                                    n.out_scale,\n                                    1,\n                                    run_args.div_rebasing,\n                                )\n                            } else {\n                                RebaseScale::rebase_up(\n                                    n.opkind,\n                                    scales[&i],\n                                    n.out_scale,\n                                    run_args.div_rebasing,\n                                )\n                            };\n                            n.out_scale = scales[&i];\n                        }\n                    }\n                    nodes.insert(i, NodeType::Node(n));\n                }\n            }\n        }\n        Self::remove_unused_nodes(&mut nodes);\n\n        Ok(nodes)\n    }\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Removes all nodes that are consts with 0 uses\n    fn remove_unused_nodes(nodes: &mut BTreeMap<usize, NodeType>) {\n        // remove all nodes that are consts with 0 uses now\n        nodes.retain(|_, n| match n {\n            NodeType::Node(n) => match &mut n.opkind {\n                SupportedOp::Constant(c) => {\n                    c.empty_raw_value();\n                    n.num_uses > 0\n                }\n                _ => n.num_uses > 0,\n            },\n            NodeType::SubGraph { model, .. } => {\n                Self::remove_unused_nodes(&mut model.graph.nodes);\n                true\n            }\n        });\n    }\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    /// Run tract onnx model on sample data !\n    pub fn run_onnx_predictions(\n        run_args: &RunArgs,\n        model_path: &std::path::Path,\n        data_chunks: &[GraphData],\n        input_shapes: Vec<Vec<usize>>,\n    ) -> Result<Vec<Vec<Tensor<f32>>>, Box<dyn Error>> {\n        use tract_onnx::tract_core::internal::IntoArcTensor;\n\n        let (model, _) = Model::load_onnx_using_tract(\n            &mut std::fs::File::open(model_path)\n                .map_err(|_| format!(\"failed to load {}\", model_path.display()))?,\n            run_args,\n        )?;\n\n        let datum_types: Vec<DatumType> = model\n            .input_outlets()?\n            .iter()\n            .map(|o| model.node(o.node).outputs[o.slot].fact.datum_type)\n            .collect();\n\n        let runnable_model = model.into_runnable()?;\n        let mut outputs = vec![];\n        for chunk in data_chunks {\n            let result = runnable_model.run(chunk.to_tract_data(&input_shapes, &datum_types)?)?;\n            outputs.push(\n                result\n                    .into_iter()\n                    .map(|t| {\n                        crate::graph::utilities::extract_tensor_value(t.into_arc_tensor()).unwrap()\n                    })\n                    .collect(),\n            );\n        }\n        Ok(outputs)\n    }\n\n    /// Creates a `Model` from parsed run_args\n    /// # Arguments\n    /// * `params` - A [GraphSettings] struct holding parsed CLI arguments.\n    #[cfg(not(target_arch = \"wasm32\"))]\n    pub fn from_run_args(\n        run_args: &RunArgs,\n        model: &std::path::Path,\n    ) -> Result<Self, Box<dyn Error>> {\n        Model::new(\n            &mut std::fs::File::open(model)\n                .map_err(|_| format!(\"failed to load {}\", model.display()))?,\n            run_args,\n        )\n    }\n\n    /// Configures a model for the circuit\n    /// # Arguments\n    /// * `meta` - The constraint system.\n    /// * `vars` - The variables for the circuit.\n    /// * `settings` - [GraphSettings]\n    pub fn configure(\n        meta: &mut ConstraintSystem<Fp>,\n        vars: &ModelVars<Fp>,\n        settings: &GraphSettings,\n    ) -> Result<PolyConfig<Fp>, Box<dyn Error>> {\n        debug!(\"configuring model\");\n\n        let lookup_range = settings.run_args.lookup_range;\n        let logrows = settings.run_args.logrows as usize;\n        let required_lookups = settings.required_lookups.clone();\n        let required_range_checks = settings.required_range_checks.clone();\n\n        let mut base_gate = PolyConfig::configure(\n            meta,\n            vars.advices[0..2].try_into()?,\n            &vars.advices[2],\n            settings.check_mode,\n        );\n        // set scale for HybridOp::RangeCheck and call self.conf_lookup on that op for percentage tolerance case\n        let input = &vars.advices[0];\n        let output = &vars.advices[2];\n        let index = &vars.advices[1];\n        for op in required_lookups {\n            base_gate.configure_lookup(meta, input, output, index, lookup_range, logrows, &op)?;\n        }\n\n        for range in required_range_checks {\n            base_gate.configure_range_check(meta, input, index, range, logrows)?;\n        }\n\n        if settings.requires_dynamic_lookup() {\n            base_gate.configure_dynamic_lookup(\n                meta,\n                vars.advices[0..3].try_into()?,\n                vars.advices[3..6].try_into()?,\n            )?;\n        }\n\n        if settings.requires_shuffle() {\n            base_gate.configure_shuffles(\n                meta,\n                vars.advices[0..2].try_into()?,\n                vars.advices[3..5].try_into()?,\n            )?;\n        }\n\n        Ok(base_gate)\n    }\n\n    /// Assigns values to the regions created when calling `configure`.\n    /// # Arguments\n    /// * `config` - [ModelConfig] holding all node configs.\n    /// * `layouter` - Halo2 Layouter.\n    /// * `inputs` - The values to feed into the circuit.\n    /// * `vars` - The variables for the circuit.\n    /// * `witnessed_outputs` - The values to compare against.\n    /// * `constants` - The constants for the circuit.\n    pub fn layout(\n        &self,\n        mut config: ModelConfig,\n        layouter: &mut impl Layouter<Fp>,\n        run_args: &RunArgs,\n        inputs: &[ValTensor<Fp>],\n        vars: &mut ModelVars<Fp>,\n        witnessed_outputs: &[ValTensor<Fp>],\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<Vec<ValTensor<Fp>>, Box<dyn Error>> {\n        info!(\"model layout...\");\n\n        let start_time = instant::Instant::now();\n\n        let mut results = BTreeMap::<usize, Vec<ValTensor<Fp>>>::new();\n\n        let input_shapes = self.graph.input_shapes()?;\n        for (i, input_idx) in self.graph.inputs.iter().enumerate() {\n            if self.visibility.input.is_public() {\n                let instance = vars.instance.as_ref().ok_or(\"no instance\")?.clone();\n                results.insert(*input_idx, vec![instance]);\n                vars.increment_instance_idx();\n            } else {\n                let mut input = inputs[i].clone();\n                input.reshape(&input_shapes[i])?;\n                results.insert(*input_idx, vec![input]);\n            }\n        }\n\n        let instance_idx = vars.get_instance_idx();\n\n        config.base.layout_tables(layouter)?;\n        config.base.layout_range_checks(layouter)?;\n\n        let original_constants = constants.clone();\n\n        let outputs = layouter.assign_region(\n            || \"model\",\n            |region| {\n                let mut thread_safe_region = RegionCtx::new_with_constants(region, 0, run_args.num_inner_cols, original_constants.clone());\n                // we need to do this as this loop is called multiple times\n                vars.set_instance_idx(instance_idx);\n\n                let outputs = self\n                    .layout_nodes(&mut config, &mut thread_safe_region, &mut results)\n                    .map_err(|e| {\n                        error!(\"{}\", e);\n                        halo2_proofs::plonk::Error::Synthesis\n                    })?;\n\n                if run_args.output_visibility.is_public() || run_args.output_visibility.is_fixed() {\n                    let output_scales = self.graph.get_output_scales().map_err(|e| {\n                        error!(\"{}\", e);\n                        halo2_proofs::plonk::Error::Synthesis\n                    })?;\n                    let res = outputs\n                        .iter()\n                        .enumerate()\n                        .map(|(i, output)| {\n                            let mut tolerance = run_args.tolerance;\n                            tolerance.scale = scale_to_multiplier(output_scales[i]).into();\n\n                            let comparators = if run_args.output_visibility == Visibility::Public {\n                                let res = vars.instance.as_ref().ok_or(\"no instance\")?.clone();\n                                vars.increment_instance_idx();\n                                res\n                            } else {\n                                // if witnessed_outputs is of len less than i  error\n                                if witnessed_outputs.len() <= i {\n                                    return Err(\"you provided insufficient witness values to generate a fixed output\".into());\n                                }\n                                witnessed_outputs[i].clone()\n                            };\n\n                            config.base.layout(\n                                &mut thread_safe_region,\n                                &[output.clone(), comparators],\n                                Box::new(HybridOp::RangeCheck(tolerance)),\n                            )\n                        })\n                        .collect::<Result<Vec<_>,_>>();\n                    res.map_err(|e| {\n                        error!(\"{}\", e);\n                        halo2_proofs::plonk::Error::Synthesis\n                    })?;\n                }\n                // Then number of columns in the circuits\n                #[cfg(not(target_arch = \"wasm32\"))]\n                thread_safe_region.debug_report();\n\n                *constants = thread_safe_region.assigned_constants().clone();\n\n                Ok(outputs)\n            },\n\n        )?;\n\n        let duration = start_time.elapsed();\n        trace!(\"model layout took: {:?}\", duration);\n\n        Ok(outputs)\n    }\n\n    fn layout_nodes(\n        &self,\n        config: &mut ModelConfig,\n        region: &mut RegionCtx<Fp>,\n        results: &mut BTreeMap<usize, Vec<ValTensor<Fp>>>,\n    ) -> Result<Vec<ValTensor<Fp>>, Box<dyn Error>> {\n        // index over results to get original inputs\n        let orig_inputs: BTreeMap<usize, _> = results\n            .clone()\n            .into_iter()\n            .filter(|(idx, _)| self.graph.inputs.contains(idx))\n            .collect();\n\n        for (idx, node) in self.graph.nodes.iter() {\n            debug!(\"laying out {}: {}\", idx, node.as_str(),);\n            // Then number of columns in the circuits\n            #[cfg(not(target_arch = \"wasm32\"))]\n            region.debug_report();\n            debug!(\"input indices: {:?}\", node.inputs());\n            debug!(\"output scales: {:?}\", node.out_scales());\n            debug!(\n                \"input scales: {:?}\",\n                node.inputs()\n                    .iter()\n                    .map(|(idx, outlet)| self.graph.nodes[idx].out_scales()[*outlet])\n                    .collect_vec()\n            );\n\n            let mut values: Vec<ValTensor<Fp>> = if !node.is_input() {\n                node.inputs()\n                    .iter()\n                    .map(|(idx, outlet)| {\n                        Ok(results.get(idx).ok_or(GraphError::MissingResults)?[*outlet].clone())\n                    })\n                    .collect::<Result<Vec<_>, GraphError>>()?\n            } else {\n                // we re-assign inputs, always from the 0 outlet\n                vec![results.get(idx).ok_or(GraphError::MissingResults)?[0].clone()]\n            };\n            debug!(\"output dims: {:?}\", node.out_dims());\n            debug!(\n                \"input dims {:?}\",\n                values.iter().map(|v| v.dims()).collect_vec()\n            );\n\n            match &node {\n                NodeType::Node(n) => {\n                    let res = if node.is_constant() && node.num_uses() == 1 {\n                        log::debug!(\"node {} is a constant with 1 use\", n.idx);\n                        let mut node = n.clone();\n                        let c = node.opkind.get_mutable_constant().ok_or(\"no constant\")?;\n                        Some(c.quantized_values.clone().try_into()?)\n                    } else {\n                        config\n                            .base\n                            .layout(region, &values, n.opkind.clone_dyn())\n                            .map_err(|e| {\n                                error!(\"{}\", e);\n                                halo2_proofs::plonk::Error::Synthesis\n                            })?\n                    };\n\n                    if let Some(mut vt) = res {\n                        vt.reshape(&node.out_dims()[0])?;\n                        // we get the max as for fused nodes this corresponds to the node output\n                        results.insert(*idx, vec![vt.clone()]);\n                        //only use with mock prover\n                        debug!(\"------------ output node {:?}: {:?}\", idx, vt.show());\n                    }\n                }\n                NodeType::SubGraph {\n                    model,\n                    inputs,\n                    output_mappings,\n                    input_mappings,\n                    ..\n                } => {\n                    let original_values = values.clone();\n                    let input_mappings = input_mappings.clone();\n\n                    let input_dims = values.iter().map(|inp| inp.dims());\n                    let num_iter = number_of_iterations(&input_mappings, input_dims.collect());\n\n                    debug!(\n                        \"{} iteration(s) in a subgraph with inputs {:?}, sources {:?}, and outputs {:?}\",\n                        num_iter, inputs, model.graph.inputs, model.graph.outputs\n                    );\n\n                    let mut full_results: Vec<ValTensor<Fp>> = vec![];\n\n                    for i in 0..num_iter {\n                        debug!(\" -------------- subgraph iteration: {}\", i);\n                        // replace the Stacked input with the current chunk iter\n                        for ((mapping, inp), og_inp) in\n                            input_mappings.iter().zip(&mut values).zip(&original_values)\n                        {\n                            if let InputMapping::Stacked { axis, chunk } = mapping {\n                                let start = i * chunk;\n                                let end = (i + 1) * chunk;\n                                let mut sliced_input = og_inp.clone();\n                                sliced_input.slice(axis, &start, &end)?;\n                                *inp = sliced_input;\n                            }\n                        }\n\n                        let mut subgraph_results = BTreeMap::from_iter(\n                            model\n                                .graph\n                                .inputs\n                                .clone()\n                                .into_iter()\n                                .zip(values.clone().into_iter().map(|v| vec![v])),\n                        );\n\n                        let res = model.layout_nodes(config, region, &mut subgraph_results)?;\n\n                        let mut outlets = BTreeMap::new();\n                        let mut stacked_outlets = BTreeMap::new();\n\n                        for (mappings, outlet_res) in output_mappings.iter().zip(res) {\n                            for mapping in mappings {\n                                match mapping {\n                                    OutputMapping::Single { outlet, .. } => {\n                                        outlets.insert(outlet, outlet_res.clone());\n                                    }\n                                    OutputMapping::Stacked { outlet, axis, .. } => {\n                                        if !full_results.is_empty() {\n                                            let stacked_res = full_results[*outlet]\n                                                .clone()\n                                                .concat_axis(outlet_res.clone(), axis)?;\n                                            stacked_outlets.insert(outlet, stacked_res);\n                                        }\n                                        outlets.insert(outlet, outlet_res.clone());\n                                    }\n                                }\n                            }\n                        }\n\n                        // now extend with stacked elements\n                        let mut pre_stacked_outlets = outlets.clone();\n                        pre_stacked_outlets.extend(stacked_outlets);\n\n                        let outlets = outlets.into_values().collect_vec();\n\n                        full_results = pre_stacked_outlets.into_values().collect_vec();\n\n                        let output_states = output_state_idx(output_mappings);\n                        let input_states = input_state_idx(&input_mappings);\n\n                        assert_eq!(\n                            input_states.len(),\n                            output_states.len(),\n                            \"input and output states must be the same length, got {:?} and {:?}\",\n                            input_mappings,\n                            output_mappings\n                        );\n\n                        for (input_idx, output_idx) in input_states.iter().zip(output_states) {\n                            assert_eq!(\n                                values[*input_idx].dims(),\n                                outlets[output_idx].dims(),\n                                \"input and output dims must be the same, got {:?} and {:?}\",\n                                values[*input_idx].dims(),\n                                outlets[output_idx].dims()\n                            );\n                            values[*input_idx] = outlets[output_idx].clone();\n                        }\n                    }\n\n                    //only use with mock prover\n                    trace!(\n                        \"------------ output subgraph node {:?}: {:?}\",\n                        idx,\n                        full_results.iter().map(|x| x.show()).collect_vec()\n                    );\n\n                    results.insert(*idx, full_results);\n                }\n            }\n        }\n\n        // we do this so we can support multiple passes of the same model and have deterministic results (Non-assigned inputs etc... etc...)\n        results.extend(orig_inputs);\n\n        let output_nodes = self.graph.outputs.iter();\n        debug!(\n            \"model outputs are nodes: {:?}\",\n            output_nodes.clone().collect_vec()\n        );\n        let outputs = output_nodes\n            .map(|(idx, outlet)| {\n                Ok(results.get(idx).ok_or(GraphError::MissingResults)?[*outlet].clone())\n            })\n            .collect::<Result<Vec<_>, GraphError>>()?;\n\n        Ok(outputs)\n    }\n\n    /// Assigns dummy values to the regions created when calling `configure`.\n    /// # Arguments\n    /// * `input_shapes` - The shapes of the inputs to the model.\n    pub fn dummy_layout(\n        &self,\n        run_args: &RunArgs,\n        inputs: &[ValTensor<Fp>],\n        witness_gen: bool,\n    ) -> Result<DummyPassRes, Box<dyn Error>> {\n        debug!(\"calculating num of constraints using dummy model layout...\");\n\n        let start_time = instant::Instant::now();\n\n        let mut results = BTreeMap::<usize, Vec<ValTensor<Fp>>>::new();\n\n        for (i, input_idx) in self.graph.inputs.iter().enumerate() {\n            results.insert(*input_idx, vec![inputs[i].clone()]);\n        }\n\n        let mut dummy_config =\n            PolyConfig::dummy(run_args.logrows as usize, run_args.num_inner_cols);\n        let mut model_config = ModelConfig {\n            base: dummy_config.clone(),\n            vars: ModelVars::new_dummy(),\n        };\n\n        let mut region = RegionCtx::new_dummy(0, run_args.num_inner_cols, witness_gen);\n\n        let outputs = self.layout_nodes(&mut model_config, &mut region, &mut results)?;\n\n        if self.visibility.output.is_public() || self.visibility.output.is_fixed() {\n            let output_scales = self.graph.get_output_scales()?;\n            let res = outputs\n                .iter()\n                .enumerate()\n                .map(|(i, output)| {\n                    let mut comparator: ValTensor<Fp> = (0..output.len())\n                        .map(|_| {\n                            if !self.visibility.output.is_fixed() {\n                                ValType::Value(Value::<Fp>::unknown())\n                            } else {\n                                ValType::Constant(Fp::random(&mut rand::thread_rng()))\n                            }\n                        })\n                        .collect::<Vec<_>>()\n                        .into();\n                    comparator.reshape(output.dims())?;\n\n                    let mut tolerance = run_args.tolerance;\n                    tolerance.scale = scale_to_multiplier(output_scales[i]).into();\n\n                    dummy_config.layout(\n                        &mut region,\n                        &[output.clone(), comparator],\n                        Box::new(HybridOp::RangeCheck(tolerance)),\n                    )\n                })\n                .collect::<Result<Vec<_>, _>>();\n            res?;\n        } else if !self.visibility.output.is_private() {\n            for output in &outputs {\n                region.update_constants(output.create_constants_map());\n            }\n        }\n\n        let duration = start_time.elapsed();\n        trace!(\"dummy model layout took: {:?}\", duration);\n\n        // Then number of columns in the circuits\n        #[cfg(not(target_arch = \"wasm32\"))]\n        region.debug_report();\n\n        let outputs = outputs\n            .iter()\n            .map(|x| {\n                x.get_felt_evals()\n                    .unwrap_or(Tensor::new(Some(&[Fp::ZERO]), &[1]).unwrap())\n            })\n            .collect();\n\n        let res = DummyPassRes {\n            num_rows: region.row(),\n            linear_coord: region.linear_coord(),\n            total_const_size: region.total_constants(),\n            lookup_ops: region.used_lookups(),\n            range_checks: region.used_range_checks(),\n            max_lookup_inputs: region.max_lookup_inputs(),\n            min_lookup_inputs: region.min_lookup_inputs(),\n            max_range_size: region.max_range_size(),\n            num_dynamic_lookups: region.dynamic_lookup_index(),\n            dynamic_lookup_col_coord: region.dynamic_lookup_col_coord(),\n            num_shuffles: region.shuffle_index(),\n            shuffle_col_coord: region.shuffle_col_coord(),\n            outputs,\n        };\n\n        Ok(res)\n    }\n\n    /// Retrieves all constants from the model.\n    pub fn get_all_params(&self) -> Vec<Tensor<Fp>> {\n        let mut params = vec![];\n        for node in self.graph.nodes.values() {\n            match node {\n                NodeType::Node(_) => {\n                    if let Some(constant) = extract_const_quantized_values(node.opkind()) {\n                        params.push(constant);\n                    }\n                }\n                NodeType::SubGraph { model, .. } => {\n                    params.extend(model.get_all_params());\n                }\n            }\n        }\n        params\n    }\n\n    /// Shapes of the computational graph's constants\n    pub fn const_shapes(&self) -> Vec<Vec<usize>> {\n        let mut const_shapes = vec![];\n        for node in self.graph.nodes.values() {\n            match node {\n                NodeType::Node(_) => {\n                    if let Some(constant) = extract_const_quantized_values(node.opkind()) {\n                        const_shapes.push(constant.dims().to_vec());\n                    };\n                }\n                NodeType::SubGraph { model, .. } => {\n                    const_shapes.extend(model.const_shapes());\n                }\n            }\n        }\n        const_shapes\n    }\n\n    /// Replaces all constants in the model with the provided values (in order of indexing), returns the number of consts\n    pub fn replace_consts(&mut self, consts: &[ValTensor<Fp>]) -> usize {\n        let mut const_idx = 0;\n        for node in self.graph.nodes.values_mut() {\n            match node {\n                NodeType::Node(n) => {\n                    if let SupportedOp::Constant(c) = &n.opkind {\n                        let mut op = crate::circuit::Constant::new(\n                            c.quantized_values.clone(),\n                            c.raw_values.clone(),\n                        );\n                        op.pre_assign(consts[const_idx].clone());\n                        n.opkind = SupportedOp::Constant(op);\n\n                        const_idx += 1;\n                    }\n                }\n                NodeType::SubGraph { model, .. } => {\n                    let total_consts = model.replace_consts(&consts[const_idx..]);\n                    const_idx += total_consts;\n                }\n            }\n        }\n        const_idx\n    }\n\n    /// Shapes of the computational graph's public inputs (if any)\n    pub fn instance_shapes(&self) -> Result<Vec<Vec<usize>>, Box<dyn Error>> {\n        let mut instance_shapes = vec![];\n        if self.visibility.input.is_public() {\n            instance_shapes.extend(self.graph.input_shapes()?);\n        }\n        if self.visibility.output.is_public() {\n            instance_shapes.extend(self.graph.output_shapes()?);\n        }\n        Ok(instance_shapes)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/modules.rs",
        "content": "use crate::circuit::modules::polycommit::{PolyCommitChip, PolyCommitConfig};\nuse crate::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};\nuse crate::circuit::modules::poseidon::{PoseidonChip, PoseidonConfig};\nuse crate::circuit::modules::Module;\nuse crate::circuit::region::ConstantsMap;\nuse crate::tensor::{Tensor, ValTensor};\nuse halo2_proofs::circuit::Layouter;\nuse halo2_proofs::plonk::{Column, ConstraintSystem, Error, Instance, VerifyingKey};\nuse halo2_proofs::poly::commitment::CommitmentScheme;\nuse halo2curves::bn256::{Fr as Fp, G1Affine};\nuse itertools::Itertools;\nuse serde::{Deserialize, Serialize};\n\nuse super::{VarVisibility, Visibility};\n\n/// poseidon len to hash in tree\npub const POSEIDON_LEN_GRAPH: usize = 32;\n/// Poseidon number of instancess\npub const POSEIDON_INSTANCES: usize = 1;\n\n/// Poseidon module type\npub type ModulePoseidon =\n    PoseidonChip<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>;\n/// Poseidon module config\npub type ModulePoseidonConfig = PoseidonConfig<POSEIDON_WIDTH, POSEIDON_RATE>;\n\n///\n#[derive(Clone, Debug, Default)]\npub struct ModuleConfigs {\n    /// PolyCommit\n    polycommit: Vec<PolyCommitConfig>,\n    /// Poseidon\n    poseidon: Option<ModulePoseidonConfig>,\n    /// Instance\n    pub instance: Option<Column<Instance>>,\n}\n\nimpl ModuleConfigs {\n    /// Create new module configs from visibility of each variable\n    pub fn from_visibility(\n        cs: &mut ConstraintSystem<Fp>,\n        module_size: ModuleSizes,\n        logrows: usize,\n    ) -> Self {\n        let mut config = Self::default();\n\n        for size in module_size.polycommit {\n            config\n                .polycommit\n                .push(PolyCommitChip::configure(cs, (logrows, size)));\n        }\n\n        config\n    }\n\n    /// Configure the modules\n    pub fn configure_complex_modules(\n        &mut self,\n        cs: &mut ConstraintSystem<Fp>,\n        visibility: VarVisibility,\n        module_size: ModuleSizes,\n    ) {\n        if (visibility.input.is_hashed()\n            || visibility.output.is_hashed()\n            || visibility.params.is_hashed())\n            && module_size.poseidon.1[0] > 0\n        {\n            if visibility.input.is_hashed_public()\n                || visibility.output.is_hashed_public()\n                || visibility.params.is_hashed_public()\n            {\n                if let Some(inst) = self.instance {\n                    self.poseidon = Some(ModulePoseidon::configure_with_optional_instance(\n                        cs,\n                        Some(inst),\n                    ));\n                } else {\n                    let poseidon = ModulePoseidon::configure(cs, ());\n                    self.instance = poseidon.instance;\n                    self.poseidon = Some(poseidon);\n                }\n            } else if visibility.input.is_hashed_private()\n                || visibility.output.is_hashed_private()\n                || visibility.params.is_hashed_private()\n            {\n                self.poseidon = Some(ModulePoseidon::configure_with_optional_instance(cs, None));\n            }\n        };\n    }\n}\n\n/// Result from a forward pass\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]\npub struct ModuleForwardResult {\n    /// The inputs of the forward pass for poseidon\n    pub poseidon_hash: Option<Vec<Fp>>,\n    /// The outputs of the forward pass for PolyCommit\n    pub polycommit: Option<Vec<Vec<G1Affine>>>,\n}\n\nimpl ModuleForwardResult {\n    /// Get the result\n    pub fn get_result(&self, vis: Visibility) -> Vec<Vec<Fp>> {\n        if vis.is_hashed() {\n            self.poseidon_hash\n                .clone()\n                .unwrap()\n                .into_iter()\n                .map(|x| vec![x])\n                .collect()\n        } else {\n            vec![]\n        }\n    }\n\n    /// get instances\n    pub fn get_instances(&self) -> Vec<Vec<Fp>> {\n        if let Some(poseidon) = &self.poseidon_hash {\n            poseidon.iter().map(|x| vec![*x]).collect()\n        } else {\n            vec![]\n        }\n    }\n}\n\n#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]\n///\npub struct ModuleSizes {\n    polycommit: Vec<usize>,\n    poseidon: (usize, Vec<usize>),\n}\n\nimpl ModuleSizes {\n    /// Create new module sizes\n    pub fn new() -> Self {\n        ModuleSizes {\n            polycommit: vec![],\n            poseidon: (\n                0,\n                vec![0; crate::circuit::modules::poseidon::NUM_INSTANCE_COLUMNS],\n            ),\n        }\n    }\n\n    /// Get the number of constraints\n    pub fn max_constraints(&self) -> usize {\n        self.poseidon.0\n    }\n    /// Get the number of instances\n    pub fn num_instances(&self) -> Vec<usize> {\n        // concat\n        self.poseidon.1.clone()\n    }\n}\n\n/// Graph modules that can process inputs, params and outputs beyond the basic operations\n#[derive(Clone, Debug, Default, Serialize, Deserialize)]\npub struct GraphModules {\n    polycommit_idx: usize,\n}\nimpl GraphModules {\n    ///\n    pub fn new() -> GraphModules {\n        GraphModules { polycommit_idx: 0 }\n    }\n\n    ///\n    pub fn reset_index(&mut self) {\n        self.polycommit_idx = 0;\n    }\n}\n\nimpl GraphModules {\n    fn num_constraint_given_shapes(\n        visibility: Visibility,\n        shapes: Vec<Vec<usize>>,\n        sizes: &mut ModuleSizes,\n    ) {\n        for shape in shapes {\n            let total_len = shape.iter().product::<usize>();\n            if total_len > 0 {\n                if visibility.is_polycommit() {\n                    // 1 constraint for each polycommit commitment\n                    sizes.polycommit.push(total_len);\n                } else if visibility.is_hashed() {\n                    sizes.poseidon.0 += ModulePoseidon::num_rows(total_len);\n                    // 1 constraints for hash\n                    sizes.poseidon.1[0] += 1;\n                }\n            }\n        }\n    }\n    /// Get the number of constraints and instances for the module\n    pub fn num_constraints_and_instances(\n        input_shapes: Vec<Vec<usize>>,\n        params_shapes: Vec<Vec<usize>>,\n        output_shapes: Vec<Vec<usize>>,\n        visibility: VarVisibility,\n    ) -> ModuleSizes {\n        let mut module_sizes = ModuleSizes::new();\n\n        Self::num_constraint_given_shapes(visibility.input, input_shapes, &mut module_sizes);\n        Self::num_constraint_given_shapes(visibility.params, params_shapes, &mut module_sizes);\n        Self::num_constraint_given_shapes(visibility.output, output_shapes, &mut module_sizes);\n\n        module_sizes\n    }\n\n    /// Layout the module\n    fn layout_module(\n        module: &impl Module<Fp>,\n        layouter: &mut impl Layouter<Fp>,\n        x: &mut Vec<ValTensor<Fp>>,\n        instance_offset: &mut usize,\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<(), Error> {\n        // reserve module 0 for ... modules\n        // hash the input and replace the constrained cells in the input\n        let cloned_x = (*x).clone();\n        x[0] = module\n            .layout(layouter, &cloned_x, instance_offset.to_owned(), constants)\n            .unwrap();\n        for inc in module.instance_increment_input().iter() {\n            // increment the instance offset to make way for future module layouts\n            *instance_offset += inc;\n        }\n\n        Ok(())\n    }\n\n    /// Layout the module\n    pub fn layout(\n        &mut self,\n        layouter: &mut impl Layouter<Fp>,\n        configs: &mut ModuleConfigs,\n        values: &mut [ValTensor<Fp>],\n        element_visibility: &Visibility,\n        instance_offset: &mut usize,\n        constants: &mut ConstantsMap<Fp>,\n    ) -> Result<(), Error> {\n        if element_visibility.is_polycommit() && !values.is_empty() {\n            // concat values and sk to get the inputs\n            let mut inputs = values.iter_mut().map(|x| vec![x.clone()]).collect_vec();\n\n            // layout the module\n            inputs.iter_mut().for_each(|x| {\n                // create the module\n                let chip = PolyCommitChip::new(configs.polycommit[self.polycommit_idx].clone());\n                // reserve module 2 onwards for polycommit modules\n                let module_offset = 3 + self.polycommit_idx;\n                layouter\n                    .assign_region(|| format!(\"_enter_module_{}\", module_offset), |_| Ok(()))\n                    .unwrap();\n                Self::layout_module(&chip, layouter, x, instance_offset, constants).unwrap();\n                // increment the current index\n                self.polycommit_idx += 1;\n            });\n\n            // replace the inputs with the outputs\n            values.iter_mut().enumerate().for_each(|(i, x)| {\n                x.clone_from(&inputs[i][0]);\n            });\n        }\n\n        // If the module is hashed, then we need to hash the inputs\n        if element_visibility.is_hashed() && !values.is_empty() {\n            if let Some(config) = &mut configs.poseidon {\n                // reserve module 0 for poseidon modules\n                layouter.assign_region(|| \"_enter_module_0\", |_| Ok(()))?;\n                // create the module\n                let chip = ModulePoseidon::new(config.clone());\n                // concat values and sk to get the inputs\n                let mut inputs = values.iter_mut().map(|x| vec![x.clone()]).collect_vec();\n                // layout the module\n                inputs.iter_mut().for_each(|x| {\n                    Self::layout_module(&chip, layouter, x, instance_offset, constants).unwrap();\n                });\n                // replace the inputs with the outputs\n                values.iter_mut().enumerate().for_each(|(i, x)| {\n                    x.clone_from(&inputs[i][0]);\n                });\n            } else {\n                log::error!(\"Poseidon config not initialized\");\n                return Err(Error::Synthesis);\n            }\n            // If the module is encrypted, then we need to encrypt the inputs\n        }\n\n        Ok(())\n    }\n\n    /// Run forward pass\n    pub fn forward<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>(\n        inputs: &[Tensor<Scheme::Scalar>],\n        element_visibility: &Visibility,\n        vk: Option<&VerifyingKey<G1Affine>>,\n        srs: Option<&Scheme::ParamsProver>,\n    ) -> Result<ModuleForwardResult, Box<dyn std::error::Error>> {\n        let mut poseidon_hash = None;\n        let mut polycommit = None;\n\n        if element_visibility.is_hashed() {\n            let field_elements = inputs.iter().fold(vec![], |mut acc, x| {\n                let res = ModulePoseidon::run(x.to_vec()).unwrap()[0].clone();\n                acc.extend(res);\n                acc\n            });\n            poseidon_hash = Some(field_elements);\n        }\n\n        if element_visibility.is_polycommit() {\n            if let Some(vk) = vk {\n                if let Some(srs) = srs {\n                    let commitments = inputs.iter().fold(vec![], |mut acc, x| {\n                        let res = PolyCommitChip::commit::<Scheme>(\n                            x.to_vec(),\n                            (vk.cs().blinding_factors() + 1) as u32,\n                            srs,\n                        );\n                        acc.push(res);\n                        acc\n                    });\n                    polycommit = Some(commitments);\n                } else {\n                    log::warn!(\"no srs provided for polycommit. processed value will be none\");\n                }\n            } else {\n                log::debug!(\n                    \"no verifying key provided for polycommit. processed value will be none\"\n                );\n            }\n        }\n\n        Ok(ModuleForwardResult {\n            poseidon_hash,\n            polycommit,\n        })\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/node.rs",
        "content": "use super::scale_to_multiplier;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse super::utilities::node_output_shapes;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse super::VarScales;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse super::Visibility;\nuse crate::circuit::hybrid::HybridOp;\nuse crate::circuit::lookup::LookupOp;\nuse crate::circuit::poly::PolyOp;\nuse crate::circuit::Constant;\nuse crate::circuit::Input;\nuse crate::circuit::Op;\nuse crate::circuit::Unknown;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::graph::new_op_from_onnx;\nuse crate::tensor::TensorError;\nuse halo2curves::bn256::Fr as Fp;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse log::trace;\nuse serde::Deserialize;\nuse serde::Serialize;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::collections::BTreeMap;\nuse std::error::Error;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::fmt;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tabled::Tabled;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::{\n    self,\n    prelude::{Node as OnnxNode, SymbolValues, TypedFact, TypedOp},\n};\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn display_vector<T: fmt::Debug>(v: &Vec<T>) -> String {\n    if !v.is_empty() {\n        format!(\"{:?}\", v)\n    } else {\n        String::new()\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn display_opkind(v: &SupportedOp) -> String {\n    v.as_string()\n}\n\n/// A wrapper for an operation that has been rescaled.\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct Rescaled {\n    /// The operation that has to be rescaled.\n    pub inner: Box<SupportedOp>,\n    /// The scale of the operation's inputs.\n    pub scale: Vec<(usize, u128)>,\n}\n\nimpl Op<Fp> for Rescaled {\n    fn as_any(&self) -> &dyn std::any::Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        format!(\"RESCALED INPUT ({})\", self.inner.as_string())\n    }\n\n    fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        let in_scales = in_scales\n            .into_iter()\n            .zip(self.scale.iter())\n            .map(|(a, b)| a + crate::graph::multiplier_to_scale(b.1 as f64))\n            .collect();\n\n        Op::<Fp>::out_scale(&*self.inner, in_scales)\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<Fp>,\n        region: &mut crate::circuit::region::RegionCtx<Fp>,\n        values: &[crate::tensor::ValTensor<Fp>],\n    ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> {\n        if self.scale.len() != values.len() {\n            return Err(Box::new(TensorError::DimMismatch(\n                \"rescaled inputs\".to_string(),\n            )));\n        }\n\n        let res =\n            &crate::circuit::layouts::rescale(config, region, values[..].try_into()?, &self.scale)?\n                [..];\n        self.inner.layout(config, region, res)\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<Fp>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n\n/// A wrapper for an operation that has been rescaled.\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct RebaseScale {\n    /// The operation that has to be rescaled.\n    pub inner: Box<SupportedOp>,\n    /// rebase op\n    pub rebase_op: HybridOp,\n    /// scale being rebased to\n    pub target_scale: i32,\n    /// The original scale of the operation's inputs.\n    pub original_scale: i32,\n    /// multiplier\n    pub multiplier: f64,\n}\n\nimpl RebaseScale {\n    ///\n    pub fn rebase(\n        inner: SupportedOp,\n        global_scale: crate::Scale,\n        op_out_scale: crate::Scale,\n        scale_rebase_multiplier: u32,\n        div_rebasing: bool,\n    ) -> SupportedOp {\n        if (op_out_scale > (global_scale * scale_rebase_multiplier as i32))\n            && !inner.is_constant()\n            && !inner.is_input()\n        {\n            let multiplier =\n                scale_to_multiplier(op_out_scale - global_scale * scale_rebase_multiplier as i32);\n            if let Some(op) = inner.get_rebased() {\n                let multiplier = op.multiplier * multiplier;\n                SupportedOp::RebaseScale(RebaseScale {\n                    inner: op.inner.clone(),\n                    target_scale: op.target_scale,\n                    multiplier,\n                    rebase_op: HybridOp::Div {\n                        denom: crate::circuit::utils::F32((multiplier) as f32),\n                        use_range_check_for_int: !div_rebasing,\n                    },\n                    original_scale: op.original_scale,\n                })\n            } else {\n                SupportedOp::RebaseScale(RebaseScale {\n                    inner: Box::new(inner),\n                    target_scale: global_scale * scale_rebase_multiplier as i32,\n                    multiplier,\n                    rebase_op: HybridOp::Div {\n                        denom: crate::circuit::utils::F32(multiplier as f32),\n                        use_range_check_for_int: !div_rebasing,\n                    },\n                    original_scale: op_out_scale,\n                })\n            }\n        } else {\n            inner\n        }\n    }\n\n    ///\n    pub fn rebase_up(\n        inner: SupportedOp,\n        target_scale: crate::Scale,\n        op_out_scale: crate::Scale,\n        div_rebasing: bool,\n    ) -> SupportedOp {\n        if (op_out_scale < (target_scale)) && !inner.is_constant() && !inner.is_input() {\n            let multiplier = scale_to_multiplier(op_out_scale - target_scale);\n            if let Some(op) = inner.get_rebased() {\n                let multiplier = op.multiplier * multiplier;\n                SupportedOp::RebaseScale(RebaseScale {\n                    inner: op.inner.clone(),\n                    target_scale: op.target_scale,\n                    multiplier,\n                    original_scale: op.original_scale,\n                    rebase_op: HybridOp::Div {\n                        denom: crate::circuit::utils::F32((multiplier) as f32),\n                        use_range_check_for_int: !div_rebasing,\n                    },\n                })\n            } else {\n                SupportedOp::RebaseScale(RebaseScale {\n                    inner: Box::new(inner),\n                    target_scale,\n                    multiplier,\n                    original_scale: op_out_scale,\n                    rebase_op: HybridOp::Div {\n                        denom: crate::circuit::utils::F32(multiplier as f32),\n                        use_range_check_for_int: !div_rebasing,\n                    },\n                })\n            }\n        } else {\n            inner\n        }\n    }\n}\n\nimpl Op<Fp> for RebaseScale {\n    fn as_any(&self) -> &dyn std::any::Any {\n        self\n    }\n\n    fn as_string(&self) -> String {\n        format!(\n            \"REBASED (div={:?}, rebasing_op={}) ({})\",\n            self.multiplier,\n            <HybridOp as Op<Fp>>::as_string(&self.rebase_op),\n            self.inner.as_string()\n        )\n    }\n\n    fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        Ok(self.target_scale)\n    }\n\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<Fp>,\n        region: &mut crate::circuit::region::RegionCtx<Fp>,\n        values: &[crate::tensor::ValTensor<Fp>],\n    ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> {\n        let original_res = self\n            .inner\n            .layout(config, region, values)?\n            .ok_or(\"no inner layout\")?;\n        self.rebase_op.layout(config, region, &[original_res])\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<Fp>> {\n        Box::new(self.clone()) // Forward to the derive(Clone) impl\n    }\n}\n\n/// A single operation in a [crate::graph::Model].\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub enum SupportedOp {\n    /// A linear operation.\n    Linear(PolyOp),\n    /// A nonlinear operation.\n    Nonlinear(LookupOp),\n    /// A hybrid operation.\n    Hybrid(HybridOp),\n    ///\n    Input(Input),\n    ///\n    Constant(Constant<Fp>),\n    ///\n    Unknown(Unknown),\n    ///\n    Rescaled(Rescaled),\n    ///\n    RebaseScale(RebaseScale),\n}\n\nimpl SupportedOp {\n    ///\n    pub fn is_lookup(&self) -> bool {\n        match self {\n            SupportedOp::Nonlinear(_) => true,\n            SupportedOp::RebaseScale(op) => op.inner.is_lookup(),\n            _ => false,\n        }\n    }\n    ///\n    pub fn get_input(&self) -> Option<Input> {\n        match self {\n            SupportedOp::Input(op) => Some(op.clone()),\n            _ => None,\n        }\n    }\n\n    ///\n    pub fn get_rebased(&self) -> Option<&RebaseScale> {\n        match self {\n            SupportedOp::RebaseScale(op) => Some(op),\n            _ => None,\n        }\n    }\n\n    ///\n    pub fn get_lookup(&self) -> Option<&LookupOp> {\n        match self {\n            SupportedOp::Nonlinear(op) => Some(op),\n            _ => None,\n        }\n    }\n\n    ///\n    pub fn get_constant(&self) -> Option<&Constant<Fp>> {\n        match self {\n            SupportedOp::Constant(op) => Some(op),\n            _ => None,\n        }\n    }\n\n    ///\n    pub fn get_mutable_constant(&mut self) -> Option<&mut Constant<Fp>> {\n        match self {\n            SupportedOp::Constant(op) => Some(op),\n            _ => None,\n        }\n    }\n\n    #[cfg(not(target_arch = \"wasm32\"))]\n    fn homogenous_rescale(\n        &self,\n        in_scales: Vec<crate::Scale>,\n    ) -> Result<Box<dyn Op<Fp>>, Box<dyn Error>> {\n        let inputs_to_scale = self.requires_homogenous_input_scales();\n        // creates a rescaled op if the inputs are not homogenous\n        let op = self.clone_dyn();\n        super::homogenize_input_scales(op, in_scales, inputs_to_scale)\n    }\n\n    /// Since each associated value of `SupportedOp` implements `Op`, let's define a helper method to retrieve it.\n    fn as_op(&self) -> &dyn Op<Fp> {\n        match self {\n            SupportedOp::Linear(op) => op,\n            SupportedOp::Nonlinear(op) => op,\n            SupportedOp::Hybrid(op) => op,\n            SupportedOp::Input(op) => op,\n            SupportedOp::Constant(op) => op,\n            SupportedOp::Unknown(op) => op,\n            SupportedOp::Rescaled(op) => op,\n            SupportedOp::RebaseScale(op) => op,\n        }\n    }\n}\n\nimpl From<Box<dyn Op<Fp>>> for SupportedOp {\n    fn from(value: Box<dyn Op<Fp>>) -> Self {\n        if let Some(op) = value.as_any().downcast_ref::<PolyOp>() {\n            return SupportedOp::Linear(op.clone());\n        };\n\n        if let Some(op) = value.as_any().downcast_ref::<LookupOp>() {\n            return SupportedOp::Nonlinear(op.clone());\n        };\n\n        if let Some(op) = value.as_any().downcast_ref::<HybridOp>() {\n            return SupportedOp::Hybrid(op.clone());\n        };\n\n        if let Some(op) = value.as_any().downcast_ref::<Input>() {\n            return SupportedOp::Input(op.clone());\n        };\n\n        if let Some(op) = value.as_any().downcast_ref::<Constant<Fp>>() {\n            return SupportedOp::Constant(op.clone());\n        };\n\n        if let Some(op) = value.as_any().downcast_ref::<Unknown>() {\n            return SupportedOp::Unknown(op.clone());\n        };\n        if let Some(op) = value.as_any().downcast_ref::<Rescaled>() {\n            return SupportedOp::Rescaled(op.clone());\n        };\n        if let Some(op) = value.as_any().downcast_ref::<RebaseScale>() {\n            return SupportedOp::RebaseScale(op.clone());\n        };\n\n        log::error!(\"Unsupported op type\");\n        log::warn!(\"defaulting to Unknown\");\n        SupportedOp::Unknown(Unknown {})\n    }\n}\n\nimpl Op<Fp> for SupportedOp {\n    fn layout(\n        &self,\n        config: &mut crate::circuit::BaseConfig<Fp>,\n        region: &mut crate::circuit::region::RegionCtx<Fp>,\n        values: &[crate::tensor::ValTensor<Fp>],\n    ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> {\n        self.as_op().layout(config, region, values)\n    }\n\n    fn is_input(&self) -> bool {\n        self.as_op().is_input()\n    }\n\n    fn is_constant(&self) -> bool {\n        self.as_op().is_constant()\n    }\n\n    fn requires_homogenous_input_scales(&self) -> Vec<usize> {\n        self.as_op().requires_homogenous_input_scales()\n    }\n\n    fn clone_dyn(&self) -> Box<dyn Op<Fp>> {\n        self.as_op().clone_dyn()\n    }\n\n    fn as_string(&self) -> String {\n        self.as_op().as_string()\n    }\n\n    fn as_any(&self) -> &dyn std::any::Any {\n        self\n    }\n\n    fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> {\n        self.as_op().out_scale(in_scales)\n    }\n}\n\n/// A node's input is a tensor from another node's output.\npub type Outlet = (usize, usize);\n\n/// A single operation in a [crate::graph::Model].\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct Node {\n    /// [Op] i.e what operation this node represents.\n    pub opkind: SupportedOp,\n    /// The denominator in the fixed point representation for the node's output. Tensors of differing scales should not be combined.\n    pub out_scale: i32,\n    // Usually there is a simple in and out shape of the node as an operator.  For example, an Affine node has three input_shapes (one for the input, weight, and bias),\n    // but in_dim is [in], out_dim is [out]\n    /// The indices of the node's inputs.\n    pub inputs: Vec<Outlet>,\n    /// Dimensions of output.\n    pub out_dims: Vec<usize>,\n    /// The node's unique identifier.\n    pub idx: usize,\n    /// The node's num of uses\n    pub num_uses: usize,\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl Tabled for Node {\n    const LENGTH: usize = 6;\n\n    fn headers() -> Vec<std::borrow::Cow<'static, str>> {\n        let mut headers = Vec::with_capacity(Self::LENGTH);\n        for i in [\"idx\", \"opkind\", \"out_scale\", \"inputs\", \"out_dims\"] {\n            headers.push(std::borrow::Cow::Borrowed(i));\n        }\n        headers\n    }\n\n    fn fields(&self) -> Vec<std::borrow::Cow<'_, str>> {\n        let mut fields = Vec::with_capacity(Self::LENGTH);\n        fields.push(std::borrow::Cow::Owned(self.idx.to_string()));\n        fields.push(std::borrow::Cow::Owned(display_opkind(&self.opkind)));\n        fields.push(std::borrow::Cow::Owned(self.out_scale.to_string()));\n        fields.push(std::borrow::Cow::Owned(display_vector(&self.inputs)));\n        fields.push(std::borrow::Cow::Owned(display_vector(&self.out_dims)));\n        fields\n    }\n}\n\nimpl PartialEq for Node {\n    fn eq(&self, other: &Node) -> bool {\n        (self.out_scale == other.out_scale)\n            && (self.inputs == other.inputs)\n            && (self.out_dims == other.out_dims)\n            && (self.idx == other.idx)\n            && (self.opkind.as_string() == other.opkind.as_string())\n    }\n}\n\nimpl Node {\n    /// Converts a tract [OnnxNode] into an ezkl [Node].\n    /// # Arguments:\n    /// * `node` - [OnnxNode]\n    /// * `other_nodes` - [BTreeMap] of other previously initialized [Node]s in the computational graph.\n    /// * `public_params` - flag if parameters of model are public\n    /// * `idx` - The node's unique identifier.\n    #[cfg(not(target_arch = \"wasm32\"))]\n    #[allow(clippy::too_many_arguments)]\n    pub fn new(\n        node: OnnxNode<TypedFact, Box<dyn TypedOp>>,\n        other_nodes: &mut BTreeMap<usize, super::NodeType>,\n        scales: &VarScales,\n        param_visibility: &Visibility,\n        idx: usize,\n        symbol_values: &SymbolValues,\n        div_rebasing: bool,\n        rebase_frac_zero_constants: bool,\n    ) -> Result<Self, Box<dyn Error>> {\n        trace!(\"Create {:?}\", node);\n        trace!(\"Create op {:?}\", node.op);\n\n        let num_uses = std::cmp::max(\n            node.outputs\n                .iter()\n                .map(|outlet| outlet.successors.len())\n                .sum::<usize>(),\n            // cmp to 1 for outputs\n            1,\n        );\n\n        // load the node inputs\n        let mut inputs = vec![];\n\n        // we can only take the inputs as mutable once -- so we need to collect them first\n        let mut input_ids = node\n            .inputs\n            .iter()\n            .map(|i| (i.node, i.slot))\n            .collect::<Vec<_>>();\n\n        input_ids\n            .iter()\n            .map(|(i, _)| {\n                inputs.push(other_nodes.get(i).ok_or(\"input not found\")?.clone());\n                Ok(())\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n        let (mut opkind, deleted_indices) = new_op_from_onnx(\n            idx,\n            scales,\n            param_visibility,\n            node.clone(),\n            &mut inputs,\n            symbol_values,\n            rebase_frac_zero_constants,\n        )?; // parses the op name\n\n        // we can only take the inputs as mutable once -- so we need to collect them first\n        other_nodes.extend(\n            inputs\n                .iter()\n                .map(|i| (i.idx(), i.clone()))\n                .collect::<BTreeMap<_, _>>(),\n        );\n\n        input_ids.iter_mut().enumerate().for_each(|(i, (idx, _))| {\n            if deleted_indices.contains(&i) {\n                // this input is not used\n                *idx = usize::MAX;\n            }\n        });\n\n        // remove the inputs that are not used\n        input_ids.retain(|(idx, _)| *idx != usize::MAX);\n\n        // rescale the inputs if necessary to get consistent fixed points\n        let mut in_scales: Vec<crate::Scale> = input_ids\n            .iter()\n            .map(|(idx, outlet)| {\n                let idx = inputs\n                    .iter()\n                    .position(|x| *idx == x.idx())\n                    .ok_or(\"input not found\")?;\n                Ok(inputs[idx].out_scales()[*outlet])\n            })\n            .collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n        let homogenous_inputs = opkind.requires_homogenous_input_scales();\n        // autoamtically increases a constant's scale if it is only used once and\n        for input in homogenous_inputs\n            .into_iter()\n            .filter(|i| !deleted_indices.contains(i))\n        {\n            if inputs.len() > input {\n                let input_node = other_nodes\n                    .get_mut(&inputs[input].idx())\n                    .ok_or(\"input not found\")?;\n                let input_opkind = &mut input_node.opkind();\n                if let Some(constant) = input_opkind.get_mutable_constant() {\n                    rescale_const_with_single_use(\n                        constant,\n                        in_scales.clone(),\n                        param_visibility,\n                        input_node.num_uses(),\n                    )?;\n                    input_node.replace_opkind(constant.clone_dyn().into());\n                    let out_scale = input_opkind.out_scale(vec![])?;\n                    input_node.bump_scale(out_scale);\n                    in_scales[input] = out_scale;\n                }\n            }\n        }\n\n        opkind = opkind.homogenous_rescale(in_scales.clone())?.into();\n        let mut out_scale = opkind.out_scale(in_scales.clone())?;\n        // rescale the inputs if necessary to get consistent fixed points, we select the largest scale (highest precision)\n        let global_scale = scales.get_max();\n        opkind = RebaseScale::rebase(\n            opkind,\n            global_scale,\n            out_scale,\n            scales.rebase_multiplier,\n            div_rebasing,\n        );\n\n        out_scale = opkind.out_scale(in_scales)?;\n\n        // get the output shape\n        let out_dims = node_output_shapes(&node, symbol_values)?;\n        // nodes vs subgraphs always have a single output\n        let mut out_dims = out_dims[0].clone();\n\n        if out_dims.is_empty() {\n            out_dims = vec![1];\n        }\n\n        Ok(Node {\n            idx,\n            opkind,\n            inputs: input_ids,\n            out_dims,\n            out_scale,\n            num_uses,\n        })\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn rescale_const_with_single_use(\n    constant: &mut Constant<Fp>,\n    in_scales: Vec<crate::Scale>,\n    param_visibility: &Visibility,\n    num_uses: usize,\n) -> Result<(), Box<dyn Error>> {\n    if num_uses == 1 {\n        let current_scale = constant.out_scale(vec![])?;\n        let scale_max = in_scales.iter().max().ok_or(\"no scales\")?;\n        if scale_max > &current_scale {\n            let raw_values = constant.raw_values.clone();\n            constant.quantized_values =\n                super::quantize_tensor(raw_values, *scale_max, param_visibility)?;\n        }\n    }\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/utilities.rs",
        "content": "#[cfg(not(target_arch = \"wasm32\"))]\nuse super::GraphError;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse super::VarScales;\nuse super::{Rescaled, SupportedOp, Visibility};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::circuit::hybrid::HybridOp;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::circuit::lookup::LookupOp;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::circuit::poly::PolyOp;\nuse crate::circuit::Op;\nuse crate::tensor::{Tensor, TensorError, TensorType};\nuse halo2curves::bn256::Fr as Fp;\nuse halo2curves::ff::PrimeField;\nuse itertools::Itertools;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse log::{debug, warn};\nuse std::error::Error;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::sync::Arc;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::prelude::{DatumType, Node as OnnxNode, TypedFact, TypedOp};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_core::ops::{\n    array::{\n        Gather, GatherElements, GatherNd, MultiBroadcastTo, OneHot, ScatterElements, ScatterNd,\n        Slice, Topk,\n    },\n    change_axes::AxisOp,\n    cnn::{Conv, Deconv},\n    einsum::EinSum,\n    element_wise::ElementWiseOp,\n    nn::{LeakyRelu, Reduce, Softmax},\n    Downsample,\n};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::tract_hir::{\n    internal::DimLike,\n    ops::array::{Pad, PadMode, TypedConcat},\n    ops::cnn::PoolSpec,\n    ops::konst::Const,\n    ops::nn::DataFormat,\n    tract_core::ops::cast::Cast,\n    tract_core::ops::cnn::{conv::KernelFormat, MaxPool, PaddingSpec, SumPool},\n};\n\n/// Quantizes an iterable of f32s to a [Tensor] of i32s using a fixed point representation.\n/// Arguments\n///\n/// * `vec` - the vector to quantize.\n/// * `dims` - the dimensionality of the resulting [Tensor].\n/// * `shift` - offset used in the fixed point representation.\n/// * `scale` - `2^scale` used in the fixed point representation.\npub fn quantize_float(elem: &f64, shift: f64, scale: crate::Scale) -> Result<i128, TensorError> {\n    let mult = scale_to_multiplier(scale);\n    let max_value = ((i128::MAX as f64 - shift) / mult).round(); // the maximum value that can be represented w/o sig bit truncation\n\n    if *elem > max_value {\n        return Err(TensorError::SigBitTruncationError);\n    }\n\n    // we parallelize the quantization process as it seems to be quite slow at times\n    let scaled = (mult * *elem + shift).round() as i128;\n\n    Ok(scaled)\n}\n\n/// Dequantizes a field element to a f64 using a fixed point representation.\n/// Arguments\n/// * `felt` - the field element to dequantize.\n/// * `scale` - `2^scale` used in the fixed point representation.\n/// * `shift` - offset used in the fixed point representation.\npub fn dequantize(felt: Fp, scale: crate::Scale, shift: f64) -> f64 {\n    let int_rep = crate::fieldutils::felt_to_i128(felt);\n    let multiplier = scale_to_multiplier(scale);\n    int_rep as f64 / multiplier - shift\n}\n\n/// Converts a scale (log base 2) to a fixed point multiplier.\npub fn scale_to_multiplier(scale: crate::Scale) -> f64 {\n    f64::powf(2., scale as f64)\n}\n\n/// Converts a scale (log base 2) to a fixed point multiplier.\npub fn multiplier_to_scale(mult: f64) -> crate::Scale {\n    mult.log2().round() as crate::Scale\n}\n\n/// Gets the shape of a onnx node's outlets.\n#[cfg(not(target_arch = \"wasm32\"))]\npub fn node_output_shapes(\n    node: &OnnxNode<TypedFact, Box<dyn TypedOp>>,\n    symbol_values: &SymbolValues,\n) -> Result<Vec<Vec<usize>>, Box<dyn std::error::Error>> {\n    let mut shapes = Vec::new();\n    let outputs = node.outputs.to_vec();\n    for output in outputs {\n        let shape = output.fact.shape;\n        let shape = shape.eval_to_usize(symbol_values)?;\n        let mv = shape.to_vec();\n        shapes.push(mv)\n    }\n    Ok(shapes)\n}\n#[cfg(not(target_arch = \"wasm32\"))]\nuse tract_onnx::prelude::SymbolValues;\n#[cfg(not(target_arch = \"wasm32\"))]\n/// Extracts the raw values from a tensor.\npub fn extract_tensor_value(\n    input: Arc<tract_onnx::prelude::Tensor>,\n) -> Result<Tensor<f32>, Box<dyn std::error::Error>> {\n    use maybe_rayon::prelude::{IntoParallelRefIterator, ParallelIterator};\n\n    let dt = input.datum_type();\n    let dims = input.shape().to_vec();\n\n    let mut const_value: Tensor<f32>;\n    if dims.is_empty() && input.len() == 0 {\n        const_value = Tensor::<f32>::new(None, &dims)?;\n        return Ok(const_value);\n    }\n\n    match dt {\n        DatumType::F16 => {\n            let vec = input.as_slice::<tract_onnx::prelude::f16>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| (*x).into()).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::F32 => {\n            let vec = input.as_slice::<f32>()?.to_vec();\n            const_value = Tensor::<f32>::new(Some(&vec), &dims)?;\n        }\n        DatumType::F64 => {\n            let vec = input.as_slice::<f64>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::I64 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<i64>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::I32 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<i32>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::I16 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<i16>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::I8 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<i8>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::U8 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<u8>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::U16 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<u16>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::U32 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<u32>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::U64 => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<u64>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::Bool => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<bool>()?.to_vec();\n            let cast: Vec<f32> = vec.par_iter().map(|x| *x as usize as f32).collect();\n            const_value = Tensor::<f32>::new(Some(&cast), &dims)?;\n        }\n        DatumType::TDim => {\n            // Generally a shape or hyperparam\n            let vec = input.as_slice::<tract_onnx::prelude::TDim>()?.to_vec();\n\n            let cast: Result<Vec<f32>, &str> = vec\n                .par_iter()\n                .map(|x| match x.to_i64() {\n                    Ok(v) => Ok(v as f32),\n                    Err(_) => match x.to_i64() {\n                        Ok(v) => Ok(v as f32),\n                        Err(_) => Err(\"could not evaluate tdim\"),\n                    },\n                })\n                .collect();\n\n            const_value = Tensor::<f32>::new(Some(&cast?), &dims)?;\n        }\n        _ => return Err(\"unsupported data type\".into()),\n    }\n    const_value.reshape(&dims)?;\n\n    Ok(const_value)\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn load_op<C: tract_onnx::prelude::Op + Clone>(\n    op: &dyn tract_onnx::prelude::Op,\n    idx: usize,\n    name: String,\n) -> Result<C, Box<dyn std::error::Error>> {\n    // Extract the slope layer hyperparams\n    let op: &C = match op.downcast_ref::<C>() {\n        Some(b) => b,\n        None => {\n            return Err(Box::new(GraphError::OpMismatch(idx, name)));\n        }\n    };\n\n    Ok(op.clone())\n}\n\n/// Matches an onnx node to a [crate::circuit::Op].\n/// Arguments\n/// * `idx` - the index of the node in the graph.\n/// * `scale` - the global (circuit) scale.\n/// * `param_visibility` - [Visibility] of the node.\n/// * `node` - the [OnnxNode] to be matched.\n/// * `inputs` - the node's inputs.\n#[cfg(not(target_arch = \"wasm32\"))]\npub fn new_op_from_onnx(\n    idx: usize,\n    scales: &VarScales,\n    param_visibility: &Visibility,\n    node: OnnxNode<TypedFact, Box<dyn TypedOp>>,\n    inputs: &mut [super::NodeType],\n    symbol_values: &SymbolValues,\n    rebase_frac_zero_constants: bool,\n) -> Result<(SupportedOp, Vec<usize>), Box<dyn std::error::Error>> {\n    use tract_onnx::tract_core::ops::array::Trilu;\n\n    use crate::circuit::InputType;\n\n    let input_scales = inputs\n        .iter()\n        .flat_map(|x| x.out_scales())\n        .collect::<Vec<_>>();\n\n    let mut replace_const = |scale: crate::Scale,\n                             index: usize,\n                             default_op: SupportedOp|\n     -> Result<SupportedOp, Box<dyn std::error::Error>> {\n        let mut constant = inputs[index].opkind();\n        let constant = constant.get_mutable_constant();\n        if let Some(c) = constant {\n            inputs[index].bump_scale(scale);\n            c.rebase_scale(scale)?;\n            inputs[index].replace_opkind(SupportedOp::Constant(c.clone()));\n            Ok(SupportedOp::Linear(PolyOp::Identity {\n                out_scale: Some(scale),\n            }))\n        } else {\n            Ok(default_op)\n        }\n    };\n\n    debug!(\"Loading node: {:?}\", node);\n    let mut deleted_indices = vec![];\n    let node = match node.op().name().as_ref() {\n        \"ShiftLeft\" => {\n            // load shift amount\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                let raw_values = &c.raw_values;\n                if raw_values.len() != 1 {\n                    return Err(Box::new(GraphError::InvalidDims(\n                        idx,\n                        \"shift left\".to_string(),\n                    )));\n                }\n                SupportedOp::Linear(PolyOp::Identity {\n                    out_scale: Some(input_scales[0] - raw_values[0] as i32),\n                })\n            } else {\n                return Err(Box::new(GraphError::OpMismatch(\n                    idx,\n                    \"ShiftLeft\".to_string(),\n                )));\n            }\n        }\n        \"ShiftRight\" => {\n            // load shift amount\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                let raw_values = &c.raw_values;\n                if raw_values.len() != 1 {\n                    return Err(Box::new(GraphError::InvalidDims(\n                        idx,\n                        \"shift right\".to_string(),\n                    )));\n                }\n                SupportedOp::Linear(PolyOp::Identity {\n                    out_scale: Some(input_scales[0] + raw_values[0] as i32),\n                })\n            } else {\n                return Err(Box::new(GraphError::OpMismatch(\n                    idx,\n                    \"ShiftRight\".to_string(),\n                )));\n            }\n        }\n        \"MultiBroadcastTo\" => {\n            let op = load_op::<MultiBroadcastTo>(node.op(), idx, node.op().name().to_string())?;\n            let shape = op.shape.clone();\n            let shape = shape\n                .iter()\n                .map(|x| x.to_usize())\n                .collect::<Result<Vec<_>, _>>()?;\n            SupportedOp::Linear(PolyOp::MultiBroadcastTo { shape })\n        }\n\n        \"Range\" => {\n            let mut input_ops = vec![];\n\n            for (i, input) in inputs.iter_mut().enumerate() {\n                if !input.opkind().is_constant() {\n                    return Err(\"Range only supports constant inputs in a zk circuit\".into());\n                } else {\n                    input.decrement_use();\n                    deleted_indices.push(i);\n                    input_ops.push(input.opkind().clone());\n                }\n            }\n\n            assert_eq!(input_ops.len(), 3, \"Range requires 3 inputs\");\n            let input_ops = input_ops\n                .iter()\n                .map(|x| x.get_constant().ok_or(\"Range requires constant inputs\"))\n                .collect::<Result<Vec<_>, _>>()?;\n\n            let start = input_ops[0].raw_values.map(|x| x as usize)[0];\n            let end = input_ops[1].raw_values.map(|x| x as usize)[0];\n            let delta = input_ops[2].raw_values.map(|x| x as usize)[0];\n\n            let range = (start..end).step_by(delta).collect::<Vec<_>>();\n            let raw_value = range.iter().map(|x| *x as f32).collect::<Tensor<_>>();\n            // Quantize the raw value (integers)\n            let quantized_value = quantize_tensor(raw_value.clone(), 0, &Visibility::Fixed)?;\n\n            let c = crate::circuit::ops::Constant::new(quantized_value, raw_value);\n            // Create a constant op\n            SupportedOp::Constant(c)\n        }\n\n        \"Trilu\" => {\n            let op = load_op::<Trilu>(node.op(), idx, node.op().name().to_string())?;\n            let upper = op.upper;\n\n            // assert second input is a constant\n            let diagonal = if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                let raw_values = &c.raw_values;\n                if raw_values.len() != 1 {\n                    return Err(Box::new(GraphError::InvalidDims(idx, \"trilu\".to_string())));\n                }\n                raw_values[0] as i32\n            } else {\n                return Err(\"we only support constant inputs for trilu diagonal\".into());\n            };\n\n            SupportedOp::Linear(PolyOp::Trilu { upper, k: diagonal })\n        }\n\n        \"Gather\" => {\n            if inputs.len() != 2 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"gather\".to_string())));\n            };\n            let op = load_op::<Gather>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n\n            let mut op = SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::Gather {\n                dim: axis,\n                constant_idx: None,\n            });\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(inputs.len() - 1);\n                op = SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::Gather {\n                    dim: axis,\n                    constant_idx: Some(c.raw_values.map(|x| {\n                        if x == -1.0 {\n                            inputs[0].out_dims()[0][axis] - 1\n                        } else {\n                            x as usize\n                        }\n                    })),\n                });\n            }\n            // }\n\n            if inputs[1].opkind().is_input() {\n                inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input {\n                    scale: 0,\n                    datum_type: InputType::TDim,\n                }));\n                inputs[1].bump_scale(0);\n            }\n\n            op\n\n            // Extract the max value\n        }\n        \"Topk\" => {\n            let op = load_op::<Topk>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n            // if param_visibility.is_public() {\n            let k = if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(inputs.len() - 1);\n                c.raw_values.map(|x| x as usize)[0]\n            } else {\n                op.fallback_k.to_i64()? as usize\n            };\n\n            SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::TopK {\n                dim: axis,\n                k,\n                largest: op.largest,\n            })\n        }\n        \"Onehot\" => {\n            let op = load_op::<OneHot>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n            let num_classes = op.dim;\n\n            SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::OneHot {\n                dim: axis,\n                num_classes,\n            })\n        }\n        \"ScatterElements\" => {\n            if inputs.len() != 3 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"scatter elements\".to_string(),\n                )));\n            };\n            let op = load_op::<ScatterElements>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n\n            let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterElements {\n                dim: axis,\n                constant_idx: None,\n            });\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterElements {\n                    dim: axis,\n                    constant_idx: Some(c.raw_values.map(|x| x as usize)),\n                })\n            }\n            // }\n\n            if inputs[1].opkind().is_input() {\n                inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input {\n                    scale: 0,\n                    datum_type: InputType::TDim,\n                }));\n                inputs[1].bump_scale(0);\n            }\n\n            op\n\n            // Extract the max value\n        }\n        \"ScatterNd\" => {\n            if inputs.len() != 3 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"scatter nd\".to_string(),\n                )));\n            };\n            // just verify it deserializes correctly\n            let _op = load_op::<ScatterNd>(node.op(), idx, node.op().name().to_string())?;\n\n            let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterND {\n                constant_idx: None,\n            });\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterND {\n                    constant_idx: Some(c.raw_values.map(|x| x as usize)),\n                })\n            }\n            // }\n\n            if inputs[1].opkind().is_input() {\n                inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input {\n                    scale: 0,\n                    datum_type: InputType::TDim,\n                }));\n                inputs[1].bump_scale(0);\n            }\n\n            op\n        }\n\n        \"GatherNd\" => {\n            if inputs.len() != 2 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"gather nd\".to_string(),\n                )));\n            };\n            let op = load_op::<GatherNd>(node.op(), idx, node.op().name().to_string())?;\n            let batch_dims = op.batch_dims;\n\n            let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherND {\n                batch_dims,\n                indices: None,\n            });\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherND {\n                    batch_dims,\n                    indices: Some(c.raw_values.map(|x| x as usize)),\n                })\n            }\n            // }\n\n            if inputs[1].opkind().is_input() {\n                inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input {\n                    scale: 0,\n                    datum_type: InputType::TDim,\n                }));\n                inputs[1].bump_scale(0);\n            }\n\n            op\n        }\n\n        \"GatherElements\" => {\n            if inputs.len() != 2 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"gather elements\".to_string(),\n                )));\n            };\n            let op = load_op::<GatherElements>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n\n            let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherElements {\n                dim: axis,\n                constant_idx: None,\n            });\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherElements {\n                    dim: axis,\n                    constant_idx: Some(c.raw_values.map(|x| x as usize)),\n                })\n            }\n            // }\n\n            if inputs[1].opkind().is_input() {\n                inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input {\n                    scale: 0,\n                    datum_type: InputType::TDim,\n                }));\n                inputs[1].bump_scale(0);\n            }\n\n            op\n\n            // Extract the max value\n        }\n        \"MoveAxis\" => {\n            let op = load_op::<AxisOp>(node.op(), idx, node.op().name().to_string())?;\n            match op {\n                AxisOp::Move(from, to) => {\n                    let source = from.to_usize()?;\n                    let destination = to.to_usize()?;\n                    SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::MoveAxis {\n                        source,\n                        destination,\n                    })\n                }\n\n                _ => {\n                    return Err(Box::new(GraphError::OpMismatch(\n                        idx,\n                        \"MoveAxis\".to_string(),\n                    )))\n                }\n            }\n        }\n        \"Concat\" | \"InferenceConcat\" => {\n            let op = load_op::<TypedConcat>(node.op(), idx, node.op().name().to_string())?;\n            let axis = op.axis;\n            SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::Concat { axis })\n        }\n        \"Slice\" => {\n            let slice = load_op::<Slice>(node.op(), idx, node.op().name().to_string())?;\n\n            let axis = slice.axis;\n            let start = slice.start.to_usize()?;\n            let end = slice.end.to_usize()?;\n\n            SupportedOp::Linear(PolyOp::Slice { axis, start, end })\n        }\n        \"Const\" => {\n            let op: Const = load_op::<Const>(node.op(), idx, node.op().name().to_string())?;\n            let dt = op.0.datum_type();\n            // Raw values are always f32\n            let raw_value = extract_tensor_value(op.0)?;\n            // If bool or a tensor dimension then don't scale\n            let mut constant_scale = match dt {\n                DatumType::Bool\n                | DatumType::TDim\n                | DatumType::I64\n                | DatumType::I32\n                | DatumType::I16\n                | DatumType::I8\n                | DatumType::U8\n                | DatumType::U16\n                | DatumType::U32\n                | DatumType::U64 => 0,\n                DatumType::F16 | DatumType::F32 | DatumType::F64 => scales.params,\n                _ => return Err(Box::new(GraphError::UnsupportedDataType)),\n            };\n\n            // if all raw_values are round then set scale to 0\n            let all_round = raw_value.iter().all(|x| (x).fract() == 0.0);\n            if all_round && rebase_frac_zero_constants {\n                constant_scale = 0;\n            }\n\n            // Quantize the raw value\n            let quantized_value =\n                quantize_tensor(raw_value.clone(), constant_scale, param_visibility)?;\n            let c = crate::circuit::ops::Constant::new(quantized_value, raw_value);\n            // Create a constant op\n            SupportedOp::Constant(c)\n        }\n        \"Reduce<ArgMax(false)>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"argmax\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes: Vec<usize> = op.axes.into_iter().collect();\n            assert_eq!(axes.len(), 1, \"only support argmax over one axis\");\n\n            SupportedOp::Hybrid(HybridOp::ReduceArgMax { dim: axes[0] })\n        }\n        \"Reduce<ArgMin(false)>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"argmin\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes: Vec<usize> = op.axes.into_iter().collect();\n            assert_eq!(axes.len(), 1, \"only support argmin over one axis\");\n\n            SupportedOp::Hybrid(HybridOp::ReduceArgMin { dim: axes[0] })\n        }\n        \"Reduce<Min>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"min\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes = op.axes.into_iter().collect();\n\n            SupportedOp::Hybrid(HybridOp::ReduceMin { axes })\n        }\n        \"Reduce<Max>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"max\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes = op.axes.into_iter().collect();\n\n            SupportedOp::Hybrid(HybridOp::ReduceMax { axes })\n        }\n        \"Reduce<Prod>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"prod\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes: Vec<usize> = op.axes.into_iter().collect();\n\n            // length of prod along axes\n            let len_prod = inputs[0].out_dims()[0]\n                .iter()\n                .enumerate()\n                .filter(|(i, _)| axes.contains(i))\n                .map(|(_, v)| v)\n                .product::<usize>();\n\n            SupportedOp::Linear(PolyOp::Prod { axes, len_prod })\n        }\n        \"Reduce<Sum>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"sum\".to_string())));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes = op.axes.into_iter().collect();\n\n            SupportedOp::Linear(PolyOp::Sum { axes })\n        }\n        \"Reduce<MeanOfSquares>\" => {\n            if inputs.len() != 1 {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"mean of squares\".to_string(),\n                )));\n            };\n            let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?;\n            let axes = op.axes.into_iter().collect();\n\n            SupportedOp::Linear(PolyOp::MeanOfSquares { axes })\n        }\n\n        \"Max\" => {\n            // Extract the max value\n            // first find the input that is a constant\n            // and then extract the value\n            let const_inputs = inputs\n                .iter()\n                .enumerate()\n                .filter(|(_, n)| n.is_constant())\n                .map(|(i, _)| i)\n                .collect::<Vec<_>>();\n\n            if const_inputs.len() != 1 {\n                return Err(Box::new(GraphError::OpMismatch(idx, \"Max\".to_string())));\n            }\n\n            let const_idx = const_inputs[0];\n            let boxed_op = inputs[const_idx].opkind();\n            let unit = if let Some(c) = extract_const_raw_values(boxed_op) {\n                if c.len() == 1 {\n                    c[0]\n                } else {\n                    return Err(Box::new(GraphError::InvalidDims(idx, \"max\".to_string())));\n                }\n            } else {\n                return Err(Box::new(GraphError::OpMismatch(idx, \"Max\".to_string())));\n            };\n\n            if inputs.len() == 2 {\n                if let Some(node) = inputs.get_mut(const_idx) {\n                    node.decrement_use();\n                    deleted_indices.push(const_idx);\n                }\n                if unit == 0. {\n                    SupportedOp::Nonlinear(LookupOp::ReLU)\n                } else {\n                    // get the non-constant index\n                    let non_const_idx = if const_idx == 0 { 1 } else { 0 };\n                    SupportedOp::Nonlinear(LookupOp::Max {\n                        scale: scale_to_multiplier(inputs[non_const_idx].out_scales()[0]).into(),\n                        a: crate::circuit::utils::F32(unit),\n                    })\n                }\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"max\".to_string())));\n            }\n        }\n        \"Min\" => {\n            // Extract the min value\n            // first find the input that is a constant\n            // and then extract the value\n            let const_inputs = inputs\n                .iter()\n                .enumerate()\n                .filter(|(_, n)| n.is_constant())\n                .map(|(i, _)| i)\n                .collect::<Vec<_>>();\n\n            if const_inputs.len() != 1 {\n                return Err(Box::new(GraphError::OpMismatch(idx, \"Min\".to_string())));\n            }\n\n            let const_idx = const_inputs[0];\n            let boxed_op = inputs[const_idx].opkind();\n            let unit = if let Some(c) = extract_const_raw_values(boxed_op) {\n                if c.len() == 1 {\n                    c[0]\n                } else {\n                    return Err(Box::new(GraphError::InvalidDims(idx, \"min\".to_string())));\n                }\n            } else {\n                return Err(Box::new(GraphError::OpMismatch(idx, \"Min\".to_string())));\n            };\n\n            if inputs.len() == 2 {\n                if let Some(node) = inputs.get_mut(const_idx) {\n                    node.decrement_use();\n                    deleted_indices.push(const_idx);\n                }\n\n                // get the non-constant index\n                let non_const_idx = if const_idx == 0 { 1 } else { 0 };\n\n                SupportedOp::Nonlinear(LookupOp::Min {\n                    scale: scale_to_multiplier(inputs[non_const_idx].out_scales()[0]).into(),\n                    a: crate::circuit::utils::F32(unit),\n                })\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"min\".to_string())));\n            }\n        }\n        \"Recip\" => {\n            let in_scale = inputs[0].out_scales()[0];\n            let max_scale = std::cmp::max(scales.get_max(), in_scale);\n            // If the input scale is larger than the params scale\n            SupportedOp::Hybrid(HybridOp::Recip {\n                input_scale: (scale_to_multiplier(in_scale) as f32).into(),\n                output_scale: (scale_to_multiplier(max_scale) as f32).into(),\n                use_range_check_for_int: true,\n            })\n        }\n\n        \"LeakyRelu\" => {\n            // Extract the slope layer hyperparams\n            let leaky_op = load_op::<ElementWiseOp>(node.op(), idx, node.op().name().to_string())?;\n\n            let leaky_op: &LeakyRelu = match leaky_op.0.downcast_ref::<LeakyRelu>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(\n                        idx,\n                        \"leaky relu\".to_string(),\n                    )));\n                }\n            };\n\n            SupportedOp::Nonlinear(LookupOp::LeakyReLU {\n                slope: crate::circuit::utils::F32(leaky_op.alpha),\n            })\n        }\n        \"Scan\" => {\n            return Err(\"scan should never be analyzed explicitly\".into());\n        }\n        \"QuantizeLinearU8\" | \"DequantizeLinearF32\" => {\n            SupportedOp::Linear(PolyOp::Identity { out_scale: None })\n        }\n        \"Abs\" => SupportedOp::Nonlinear(LookupOp::Abs),\n        \"Neg\" => SupportedOp::Linear(PolyOp::Neg),\n        \"HardSwish\" => SupportedOp::Nonlinear(LookupOp::HardSwish {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Sigmoid\" => SupportedOp::Nonlinear(LookupOp::Sigmoid {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Sqrt\" => SupportedOp::Nonlinear(LookupOp::Sqrt {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Rsqrt\" => SupportedOp::Nonlinear(LookupOp::Rsqrt {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Exp\" => SupportedOp::Nonlinear(LookupOp::Exp {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Ln\" => SupportedOp::Nonlinear(LookupOp::Ln {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Sin\" => SupportedOp::Nonlinear(LookupOp::Sin {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Cos\" => SupportedOp::Nonlinear(LookupOp::Cos {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Tan\" => SupportedOp::Nonlinear(LookupOp::Tan {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Asin\" => SupportedOp::Nonlinear(LookupOp::ASin {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Acos\" => SupportedOp::Nonlinear(LookupOp::ACos {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Atan\" => SupportedOp::Nonlinear(LookupOp::ATan {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Sinh\" => SupportedOp::Nonlinear(LookupOp::Sinh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Cosh\" => SupportedOp::Nonlinear(LookupOp::Cosh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Tanh\" => SupportedOp::Nonlinear(LookupOp::Tanh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Asinh\" => SupportedOp::Nonlinear(LookupOp::ASinh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Acosh\" => SupportedOp::Nonlinear(LookupOp::ACosh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Atanh\" => SupportedOp::Nonlinear(LookupOp::ATanh {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Erf\" => SupportedOp::Nonlinear(LookupOp::Erf {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Source\" => {\n            let (scale, datum_type) = match node.outputs[0].fact.datum_type {\n                DatumType::Bool => (0, InputType::Bool),\n                DatumType::TDim => (0, InputType::TDim),\n                DatumType::I64\n                | DatumType::I32\n                | DatumType::I16\n                | DatumType::I8\n                | DatumType::U8\n                | DatumType::U16\n                | DatumType::U32\n                | DatumType::U64 => (0, InputType::Int),\n                DatumType::F16 => (scales.input, InputType::F16),\n                DatumType::F32 => (scales.input, InputType::F32),\n                DatumType::F64 => (scales.input, InputType::F64),\n                _ => return Err(Box::new(GraphError::UnsupportedDataType)),\n            };\n            SupportedOp::Input(crate::circuit::ops::Input { scale, datum_type })\n        }\n        \"Cast\" => {\n            let op = load_op::<Cast>(node.op(), idx, node.op().name().to_string())?;\n            let dt = op.to;\n\n            assert_eq!(input_scales.len(), 1);\n\n            match dt {\n                DatumType::Bool\n                | DatumType::TDim\n                | DatumType::I64\n                | DatumType::I32\n                | DatumType::I16\n                | DatumType::I8\n                | DatumType::U8\n                | DatumType::U16\n                | DatumType::U32\n                | DatumType::U64 => {\n                    if input_scales[0] != 0 {\n                        replace_const(\n                            0,\n                            0,\n                            SupportedOp::Nonlinear(LookupOp::Cast {\n                                scale: crate::circuit::utils::F32(scale_to_multiplier(\n                                    input_scales[0],\n                                )\n                                    as f32),\n                            }),\n                        )?\n                    } else {\n                        SupportedOp::Linear(PolyOp::Identity { out_scale: None })\n                    }\n                }\n                DatumType::F16 | DatumType::F32 | DatumType::F64 => {\n                    SupportedOp::Linear(PolyOp::Identity { out_scale: None })\n                }\n                _ => return Err(Box::new(GraphError::UnsupportedDataType)),\n            }\n        }\n        \"Add\" => SupportedOp::Linear(PolyOp::Add),\n        \"Sub\" => SupportedOp::Linear(PolyOp::Sub),\n        \"Mul\" => {\n            let mut op = SupportedOp::Linear(PolyOp::Mult);\n\n            let const_idx = inputs\n                .iter()\n                .enumerate()\n                .filter(|(_, n)| n.is_constant())\n                .map(|(i, _)| i)\n                .collect::<Vec<_>>();\n\n            if const_idx.len() > 1 {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"mul\".to_string())));\n            }\n\n            if const_idx.len() == 1 {\n                let const_idx = const_idx[0];\n                if let Some(c) = inputs[const_idx].opkind().get_mutable_constant() {\n                    if c.raw_values.len() == 1 && c.raw_values[0] < 1. {\n                        // if not divisible by 2 then we need to add a range check\n                        let raw_values = 1.0 / c.raw_values[0];\n                        if raw_values.log2().fract() == 0.0 {\n                            inputs[const_idx].decrement_use();\n                            deleted_indices.push(const_idx);\n                            op = SupportedOp::Linear(PolyOp::Identity {\n                                out_scale: Some(input_scales[0] + raw_values.log2() as i32),\n                            });\n                        }\n                    }\n                }\n            }\n            op\n        }\n        \"Iff\" => SupportedOp::Linear(PolyOp::Iff),\n        \"Less\" => {\n            if inputs.len() == 2 {\n                SupportedOp::Hybrid(HybridOp::Less)\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(idx, \"less\".to_string())));\n            }\n        }\n        \"LessEqual\" => {\n            if inputs.len() == 2 {\n                SupportedOp::Hybrid(HybridOp::LessEqual)\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"less equal\".to_string(),\n                )));\n            }\n        }\n        \"Greater\" => {\n            // Extract the slope layer hyperparams\n            if inputs.len() == 2 {\n                SupportedOp::Hybrid(HybridOp::Greater)\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"greater\".to_string(),\n                )));\n            }\n        }\n        \"GreaterEqual\" => {\n            // Extract the slope layer hyperparams\n            if inputs.len() == 2 {\n                SupportedOp::Hybrid(HybridOp::GreaterEqual)\n            } else {\n                return Err(Box::new(GraphError::InvalidDims(\n                    idx,\n                    \"greater equal\".to_string(),\n                )));\n            }\n        }\n        \"EinSum\" => {\n            // Extract the slope layer hyperparams\n            let op: &EinSum = match node.op().downcast_ref::<EinSum>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"einsum\".to_string())));\n                }\n            };\n\n            let axes = &op.axes;\n            SupportedOp::Linear(PolyOp::Einsum {\n                equation: axes.to_string(),\n            })\n        }\n        \"Softmax\" => {\n            // Extract the slope layer hyperparams\n            let softmax_op: &Softmax = match node.op().downcast_ref::<Softmax>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"softmax\".to_string())));\n                }\n            };\n\n            let in_scale = inputs[0].out_scales()[0];\n            let max_scale = std::cmp::max(scales.get_max(), in_scale);\n\n            SupportedOp::Hybrid(HybridOp::Softmax {\n                input_scale: scale_to_multiplier(in_scale).into(),\n                output_scale: scale_to_multiplier(max_scale).into(),\n                axes: softmax_op.axes.to_vec(),\n            })\n        }\n        \"MaxPool\" => {\n            // Extract the padding and stride layer hyperparams\n            let op = Box::new(node.op());\n            let sumpool_node: &MaxPool = match op.downcast_ref() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"Maxpool\".to_string())));\n                }\n            };\n\n            let pool_spec: &PoolSpec = &sumpool_node.pool_spec;\n\n            // only support pytorch type formatting for now\n            if pool_spec.data_format != DataFormat::NCHW {\n                return Err(Box::new(GraphError::MissingParams(\n                    \"data in wrong format\".to_string(),\n                )));\n            }\n\n            let stride = pool_spec\n                .strides\n                .clone()\n                .ok_or(GraphError::MissingParams(\"stride\".to_string()))?;\n            let padding = match &pool_spec.padding {\n                PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => {\n                    b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect()\n                }\n                _ => {\n                    return Err(Box::new(GraphError::MissingParams(\"padding\".to_string())));\n                }\n            };\n            let kernel_shape = &pool_spec.kernel_shape;\n\n            SupportedOp::Hybrid(HybridOp::MaxPool {\n                padding,\n                stride: stride.to_vec(),\n                pool_dims: kernel_shape.to_vec(),\n            })\n        }\n        \"Ceil\" => SupportedOp::Nonlinear(LookupOp::Ceil {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Floor\" => SupportedOp::Nonlinear(LookupOp::Floor {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Round\" => SupportedOp::Nonlinear(LookupOp::Round {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"RoundHalfToEven\" => SupportedOp::Nonlinear(LookupOp::RoundHalfToEven {\n            scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n        }),\n        \"Sign\" => SupportedOp::Nonlinear(LookupOp::Sign),\n        \"Pow\" => {\n            // Extract the slope layer hyperparams from a const\n\n            // if param_visibility.is_public() {\n            if let Some(c) = inputs[1].opkind().get_mutable_constant() {\n                inputs[1].decrement_use();\n                deleted_indices.push(1);\n                if c.raw_values.len() > 1 {\n                    unimplemented!(\"only support scalar pow\")\n                }\n                SupportedOp::Nonlinear(LookupOp::Pow {\n                    scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(),\n                    a: crate::circuit::utils::F32(c.raw_values[0]),\n                })\n            } else {\n                unimplemented!(\"only support constant pow for now\")\n            }\n        }\n        \"Cube\" => SupportedOp::Linear(PolyOp::Pow(3)),\n        \"Square\" => SupportedOp::Linear(PolyOp::Pow(2)),\n        \"Conv\" => {\n            let conv_node: &Conv = match node.op().downcast_ref::<Conv>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"conv\".to_string())));\n                }\n            };\n\n            if let Some(dilations) = &conv_node.pool_spec.dilations {\n                if dilations.iter().any(|x| *x != 1) {\n                    return Err(Box::new(GraphError::MisformedParams(\n                        \"non unit dilations not supported\".to_string(),\n                    )));\n                }\n            }\n\n            if ((conv_node.pool_spec.data_format != DataFormat::NCHW)\n                && (conv_node.pool_spec.data_format != DataFormat::CHW))\n                || (conv_node.kernel_fmt != KernelFormat::OIHW)\n            {\n                return Err(Box::new(GraphError::MisformedParams(\n                    \"data or kernel in wrong format\".to_string(),\n                )));\n            }\n\n            let stride = match conv_node.pool_spec.strides.clone() {\n                Some(s) => s.to_vec(),\n                None => {\n                    return Err(Box::new(GraphError::MissingParams(\"strides\".to_string())));\n                }\n            };\n\n            let padding = match &conv_node.pool_spec.padding {\n                PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => {\n                    b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect()\n                }\n                _ => {\n                    return Err(Box::new(GraphError::MissingParams(\"padding\".to_string())));\n                }\n            };\n\n            // if bias exists then rescale it to the input + kernel scale\n            if input_scales.len() == 3 {\n                let bias_scale = input_scales[2];\n                let input_scale = input_scales[0];\n                let kernel_scale = input_scales[1];\n\n                let output_scale = input_scale + kernel_scale;\n                if bias_scale != output_scale {\n                    replace_const(\n                        output_scale,\n                        2,\n                        SupportedOp::Unknown(crate::circuit::Unknown),\n                    )?;\n                }\n            }\n\n            SupportedOp::Linear(PolyOp::Conv { padding, stride })\n        }\n        \"Not\" => SupportedOp::Linear(PolyOp::Not),\n        \"And\" => SupportedOp::Linear(PolyOp::And),\n        \"Or\" => SupportedOp::Linear(PolyOp::Or),\n        \"Xor\" => SupportedOp::Linear(PolyOp::Xor),\n        \"Equals\" => SupportedOp::Hybrid(HybridOp::Equals),\n        \"Deconv\" => {\n            let deconv_node: &Deconv = match node.op().downcast_ref::<Deconv>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"deconv\".to_string())));\n                }\n            };\n\n            if let Some(dilations) = &deconv_node.pool_spec.dilations {\n                if dilations.iter().any(|x| *x != 1) {\n                    return Err(Box::new(GraphError::MisformedParams(\n                        \"non unit dilations not supported\".to_string(),\n                    )));\n                }\n            }\n\n            if (deconv_node.pool_spec.data_format != DataFormat::NCHW)\n                || (deconv_node.kernel_format != KernelFormat::OIHW)\n            {\n                return Err(Box::new(GraphError::MisformedParams(\n                    \"data or kernel in wrong format\".to_string(),\n                )));\n            }\n\n            let stride = match deconv_node.pool_spec.strides.clone() {\n                Some(s) => s.to_vec(),\n                None => {\n                    return Err(Box::new(GraphError::MissingParams(\"strides\".to_string())));\n                }\n            };\n            let padding = match &deconv_node.pool_spec.padding {\n                PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => {\n                    b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect()\n                }\n                _ => {\n                    return Err(Box::new(GraphError::MissingParams(\"padding\".to_string())));\n                }\n            };\n\n            // if bias exists then rescale it to the input + kernel scale\n            if input_scales.len() == 3 {\n                let bias_scale = input_scales[2];\n                let input_scale = input_scales[0];\n                let kernel_scale = input_scales[1];\n\n                let output_scale = input_scale + kernel_scale;\n                if bias_scale != output_scale {\n                    replace_const(\n                        output_scale,\n                        2,\n                        SupportedOp::Unknown(crate::circuit::Unknown),\n                    )?;\n                }\n            }\n\n            SupportedOp::Linear(PolyOp::DeConv {\n                padding,\n                output_padding: deconv_node.adjustments.to_vec(),\n                stride,\n            })\n        }\n        \"Downsample\" => {\n            let downsample_node: Downsample = match node.op().downcast_ref::<Downsample>() {\n                Some(b) => b.clone(),\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(\n                        idx,\n                        \"downsample\".to_string(),\n                    )));\n                }\n            };\n\n            SupportedOp::Linear(PolyOp::Downsample {\n                axis: downsample_node.axis,\n                stride: downsample_node.stride as usize,\n                modulo: downsample_node.modulo,\n            })\n        }\n\n        \"Resize\" => {\n            // this is a bit hacky, but we need to extract the resize node somehow\n            // and this is the only way I can think of\n            // see https://github.com/sonos/tract/issues/324\n\n            let resize_node = format!(\"{:?}\", node);\n\n            if !resize_node.contains(\"interpolator: Nearest\")\n                && !resize_node.contains(\"nearest: Floor\")\n            {\n                unimplemented!(\"Only nearest neighbor interpolation is supported\")\n            }\n            // check if optional scale factor is present\n            if inputs.len() != 2 && inputs.len() != 3 {\n                return Err(Box::new(GraphError::OpMismatch(idx, \"Resize\".to_string())));\n            }\n\n            let scale_factor_node =  // find optional_scales_input in the string and extract the value inside the Some\n            if resize_node.contains(\"optional_scales_input: None\") {\n                 None\n            } else {\n                Some(resize_node\n                .split(\"optional_scales_input: \")\n                .collect::<Vec<_>>()[1]\n                .split(\"Some(\")\n                .collect::<Vec<_>>()[1]\n                .split(')')\n                .collect::<Vec<_>>()[0]\n                .parse::<usize>()?)\n            };\n\n            let scale_factor = if let Some(scale_factor_node) = scale_factor_node {\n                let boxed_op = inputs[scale_factor_node].opkind();\n                if let Some(c) = extract_const_raw_values(boxed_op) {\n                    c.map(|x| x as usize).into_iter().collect::<Vec<usize>>()\n                } else {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"Resize\".to_string())));\n                }\n            } else {\n                // default\n                vec![1]\n            };\n\n            for i in 1..inputs.len() {\n                // remove the resize node from the inputs\n                if let Some(node) = inputs.get_mut(i) {\n                    node.decrement_use();\n                    deleted_indices.push(i);\n                }\n            }\n\n            SupportedOp::Linear(PolyOp::Resize { scale_factor })\n        }\n\n        \"SumPool\" => {\n            // Extract the padding and stride layer hyperparams\n            let op = Box::new(node.op());\n            let sumpool_node: &SumPool = match op.downcast_ref() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"sumpool\".to_string())));\n                }\n            };\n\n            let pool_spec: &PoolSpec = &sumpool_node.pool_spec;\n\n            // only support pytorch type formatting for now\n            if pool_spec.data_format != DataFormat::NCHW {\n                return Err(Box::new(GraphError::MissingParams(\n                    \"data in wrong format\".to_string(),\n                )));\n            }\n\n            let stride = pool_spec\n                .strides\n                .clone()\n                .ok_or(GraphError::MissingParams(\"stride\".to_string()))?;\n            let padding = match &pool_spec.padding {\n                PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => {\n                    b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect()\n                }\n                _ => {\n                    return Err(Box::new(GraphError::MissingParams(\"padding\".to_string())));\n                }\n            };\n\n            SupportedOp::Hybrid(HybridOp::SumPool {\n                padding,\n                stride: stride.to_vec(),\n                kernel_shape: pool_spec.kernel_shape.to_vec(),\n                normalized: sumpool_node.normalize,\n            })\n        }\n        // \"GlobalAvgPool\" => SupportedOp::Linear(PolyOp::SumPool {\n        //     padding: [(0, 0); 2],\n        //     stride: (1, 1),\n        //     kernel_shape: (inputs[0].out_dims()[0][1], inputs[0].out_dims()[0][2]),\n        // }),\n        \"Pad\" => {\n            let pad_node: &Pad = match node.op().downcast_ref::<Pad>() {\n                Some(b) => b,\n                None => {\n                    return Err(Box::new(GraphError::OpMismatch(idx, \"pad\".to_string())));\n                }\n            };\n            // we only support constant 0 padding\n            if pad_node.mode\n                != PadMode::Constant(tract_onnx::prelude::Arc::new(\n                    tract_onnx::prelude::Tensor::zero::<f32>(&[])?,\n                ))\n            {\n                return Err(Box::new(GraphError::MisformedParams(\n                    \"pad mode or pad type\".to_string(),\n                )));\n            }\n\n            SupportedOp::Linear(PolyOp::Pad(pad_node.pads.to_vec()))\n        }\n        \"RmAxis\" | \"Reshape\" | \"AddAxis\" => {\n            // Extract the slope layer hyperparams\n            let shapes = node_output_shapes(&node, symbol_values)?;\n            let mut output_shape = shapes[0].clone();\n            if output_shape.is_empty() {\n                output_shape = vec![1];\n            }\n\n            SupportedOp::Linear(PolyOp::Reshape(output_shape))\n        }\n        \"Flatten\" => {\n            let new_dims: Vec<usize> = vec![inputs[0].out_dims()[0].iter().product::<usize>()];\n            SupportedOp::Linear(PolyOp::Flatten(new_dims))\n        }\n        c => {\n            warn!(\"Unknown op: {}\", c);\n            SupportedOp::Unknown(crate::circuit::ops::Unknown)\n        }\n    };\n\n    Ok((node, deleted_indices))\n}\n\n/// Extracts the raw values from a [crate::circuit::ops::Constant] op.\npub fn extract_const_raw_values(op: SupportedOp) -> Option<Tensor<f32>> {\n    match op {\n        SupportedOp::Constant(crate::circuit::ops::Constant { raw_values, .. }) => Some(raw_values),\n        _ => None,\n    }\n}\n\n/// Extracts the quantized values from a [crate::circuit::ops::Constant] op.\npub fn extract_const_quantized_values(op: SupportedOp) -> Option<Tensor<Fp>> {\n    match op {\n        SupportedOp::Constant(crate::circuit::ops::Constant {\n            quantized_values, ..\n        }) => Some(quantized_values),\n        _ => None,\n    }\n}\n\n/// Converts a tensor to a [ValTensor] with a given scale.\npub fn quantize_tensor<F: PrimeField + TensorType + PartialOrd>(\n    const_value: Tensor<f32>,\n    scale: crate::Scale,\n    visibility: &Visibility,\n) -> Result<Tensor<F>, Box<dyn std::error::Error>> {\n    let mut value: Tensor<F> = const_value.par_enum_map(|_, x| {\n        Ok::<_, TensorError>(crate::fieldutils::i128_to_felt::<F>(quantize_float(\n            &(x).into(),\n            0.0,\n            scale,\n        )?))\n    })?;\n\n    value.set_scale(scale);\n    value.set_visibility(visibility);\n    Ok(value)\n}\n\nuse crate::tensor::ValTensor;\n/// Split a [ValTensor] into a vector of [ValTensor]s.\npub(crate) fn split_valtensor(\n    values: &ValTensor<Fp>,\n    shapes: Vec<Vec<usize>>,\n) -> Result<Vec<ValTensor<Fp>>, Box<dyn std::error::Error>> {\n    let mut tensors: Vec<ValTensor<Fp>> = Vec::new();\n    let mut start = 0;\n    for shape in shapes {\n        let end = start + shape.iter().product::<usize>();\n        let mut tensor = values.get_slice(&[start..end])?;\n        tensor.reshape(&shape)?;\n        tensors.push(tensor);\n        start = end;\n    }\n    Ok(tensors)\n}\n\n///\npub fn homogenize_input_scales(\n    op: Box<dyn Op<Fp>>,\n    input_scales: Vec<crate::Scale>,\n    inputs_to_scale: Vec<usize>,\n) -> Result<Box<dyn Op<Fp>>, Box<dyn Error>> {\n    let relevant_input_scales = input_scales\n        .clone()\n        .into_iter()\n        .enumerate()\n        .filter(|(idx, _)| inputs_to_scale.contains(idx))\n        .map(|(_, scale)| scale)\n        .collect_vec();\n\n    if inputs_to_scale.is_empty() {\n        return Ok(op);\n    }\n    // else if all inputs_scales at inputs_to_scale are the same, we don't need to do anything\n    if relevant_input_scales.windows(2).all(|w| w[0] == w[1]) {\n        return Ok(op);\n    }\n\n    let mut multipliers: Vec<u128> = vec![1; input_scales.len()];\n\n    let max_scale = input_scales.iter().max().ok_or(\"no max scale\")?;\n    let _ = input_scales\n        .iter()\n        .enumerate()\n        .map(|(idx, input_scale)| {\n            if !inputs_to_scale.contains(&idx) {\n                return;\n            }\n            let scale_diff = max_scale - input_scale;\n            if scale_diff > 0 {\n                let mult = crate::graph::scale_to_multiplier(scale_diff);\n                multipliers[idx] = mult as u128;\n            }\n        })\n        .collect_vec();\n\n    // only rescale if need to\n    if multipliers.iter().any(|&x| x > 1) {\n        Ok(Box::new(Rescaled {\n            inner: Box::new(op.into()),\n            scale: (0..input_scales.len()).zip(multipliers).collect_vec(),\n        }))\n    } else {\n        Ok(op)\n    }\n}\n\n#[cfg(test)]\npub mod tests {\n\n    use super::*;\n\n    #[test]\n    fn test_flatten_valtensors() {\n        let tensor1: Tensor<Fp> = (0..10).map(|x| x.into()).into();\n        let tensor2: Tensor<Fp> = (10..20).map(|x| x.into()).into();\n        let tensor3: Tensor<Fp> = (20..30).map(|x| x.into()).into();\n\n        let mut tensor = Tensor::new(Some(&[tensor1, tensor2, tensor3]), &[3])\n            .unwrap()\n            .combine()\n            .unwrap();\n\n        tensor.set_visibility(&Visibility::Public);\n\n        let flattened: ValTensor<Fp> = tensor.try_into().unwrap();\n\n        assert_eq!(flattened.len(), 30);\n\n        let split = split_valtensor(&flattened, vec![vec![2, 5], vec![10], vec![5, 2]]).unwrap();\n\n        assert_eq!(split.len(), 3);\n        assert_eq!(split[0].len(), 10);\n        assert_eq!(split[0].dims(), vec![2, 5]);\n        assert_eq!(split[1].len(), 10);\n        assert_eq!(split[1].dims(), vec![10]);\n        assert_eq!(split[2].dims(), vec![5, 2]);\n        assert_eq!(split[2].len(), 10);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/graph/vars.rs",
        "content": "use std::error::Error;\nuse std::fmt::Display;\n\nuse crate::tensor::TensorType;\nuse crate::tensor::{ValTensor, VarTensor};\nuse crate::RunArgs;\nuse halo2_proofs::plonk::{Column, ConstraintSystem, Instance};\nuse halo2curves::ff::PrimeField;\nuse itertools::Itertools;\nuse log::debug;\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::{\n    exceptions::PyValueError, types::PyString, FromPyObject, IntoPy, PyAny, PyObject, PyResult,\n    PyTryFrom, Python, ToPyObject,\n};\n\nuse serde::{Deserialize, Serialize};\nuse tosubcommand::ToFlags;\n\nuse super::*;\n\n/// Label enum to track whether model input, model parameters, and model output are public, private, or hashed\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)]\npub enum Visibility {\n    /// Mark an item as private to the prover (not in the proof submitted for verification)\n    #[default]\n    Private,\n    /// Mark an item as public (sent in the proof submitted for verification)\n    Public,\n    /// Mark an item as publicly committed to (hash sent in the proof submitted for verification)\n    Hashed {\n        /// Whether the hash is used as an instance (sent in the proof submitted for verification)\n        /// if false the hash is used as an advice (not in the proof submitted for verification) and is then sent to the computational graph\n        /// if true the hash is used as an instance (sent in the proof submitted for verification) the *inputs* to the hashing function are then sent to the computational graph\n        hash_is_public: bool,\n        ///\n        outlets: Vec<usize>,\n    },\n    /// Mark an item as publicly committed to (KZG commitment sent in the proof submitted for verification)\n    KZGCommit,\n    /// assigned as a constant in the circuit\n    Fixed,\n}\n\nimpl Display for Visibility {\n    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n        match self {\n            Visibility::KZGCommit => write!(f, \"polycommit\"),\n            Visibility::Private => write!(f, \"private\"),\n            Visibility::Public => write!(f, \"public\"),\n            Visibility::Fixed => write!(f, \"fixed\"),\n            Visibility::Hashed {\n                hash_is_public,\n                outlets,\n            } => {\n                if *hash_is_public {\n                    write!(f, \"hashed/public\")\n                } else {\n                    write!(f, \"hashed/private/{}\", outlets.iter().join(\",\"))\n                }\n            }\n        }\n    }\n}\n\nimpl ToFlags for Visibility {\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl<'a> From<&'a str> for Visibility {\n    fn from(s: &'a str) -> Self {\n        if s.contains(\"hashed/private\") {\n            // split on last occurence of '/'\n            let (_, outlets) = s.split_at(s.rfind('/').unwrap());\n            let outlets = outlets\n                .trim_start_matches('/')\n                .split(',')\n                .map(|s| s.parse::<usize>().unwrap())\n                .collect_vec();\n\n            return Visibility::Hashed {\n                hash_is_public: false,\n                outlets,\n            };\n        }\n        match s {\n            \"private\" => Visibility::Private,\n            \"public\" => Visibility::Public,\n            \"polycommit\" => Visibility::KZGCommit,\n            \"fixed\" => Visibility::Fixed,\n            \"hashed\" | \"hashed/public\" => Visibility::Hashed {\n                hash_is_public: true,\n                outlets: vec![],\n            },\n            _ => {\n                log::error!(\"Invalid value for Visibility: {}\", s);\n                log::warn!(\"Defaulting to private\");\n                Visibility::Private\n            }\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Converts Visibility into a PyObject (Required for Visibility to be compatible with Python)\nimpl IntoPy<PyObject> for Visibility {\n    fn into_py(self, py: Python) -> PyObject {\n        match self {\n            Visibility::Private => \"private\".to_object(py),\n            Visibility::Public => \"public\".to_object(py),\n            Visibility::Fixed => \"fixed\".to_object(py),\n            Visibility::KZGCommit => \"polycommit\".to_object(py),\n            Visibility::Hashed {\n                hash_is_public,\n                outlets,\n            } => {\n                if hash_is_public {\n                    \"hashed/public\".to_object(py)\n                } else {\n                    let outlets = outlets\n                        .iter()\n                        .map(|o| o.to_string())\n                        .collect_vec()\n                        .join(\",\");\n                    format!(\"hashed/private/{}\", outlets).to_object(py)\n                }\n            }\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Obtains Visibility from PyObject (Required for Visibility to be compatible with Python)\nimpl<'source> FromPyObject<'source> for Visibility {\n    fn extract(ob: &'source PyAny) -> PyResult<Self> {\n        let trystr = <PyString as PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n\n        let strval = strval.as_str();\n\n        if strval.contains(\"hashed/private\") {\n            // split on last occurence of '/'\n            let (_, outlets) = strval.split_at(strval.rfind('/').unwrap());\n            let outlets = outlets\n                .trim_start_matches('/')\n                .split(',')\n                .map(|s| s.parse::<usize>().unwrap())\n                .collect_vec();\n\n            return Ok(Visibility::Hashed {\n                hash_is_public: false,\n                outlets,\n            });\n        }\n\n        match strval.to_lowercase().as_str() {\n            \"private\" => Ok(Visibility::Private),\n            \"public\" => Ok(Visibility::Public),\n            \"polycommit\" => Ok(Visibility::KZGCommit),\n            \"hashed\" => Ok(Visibility::Hashed {\n                hash_is_public: true,\n                outlets: vec![],\n            }),\n            \"hashed/public\" => Ok(Visibility::Hashed {\n                hash_is_public: true,\n                outlets: vec![],\n            }),\n            \"fixed\" => Ok(Visibility::Fixed),\n            _ => Err(PyValueError::new_err(\"Invalid value for Visibility\")),\n        }\n    }\n}\n\nimpl Visibility {\n    #[allow(missing_docs)]\n    pub fn is_fixed(&self) -> bool {\n        matches!(&self, Visibility::Fixed)\n    }\n    #[allow(missing_docs)]\n    pub fn is_private(&self) -> bool {\n        matches!(&self, Visibility::Private) || self.is_hashed_private()\n    }\n\n    #[allow(missing_docs)]\n    pub fn is_public(&self) -> bool {\n        matches!(&self, Visibility::Public)\n    }\n    #[allow(missing_docs)]\n    pub fn is_hashed(&self) -> bool {\n        matches!(&self, Visibility::Hashed { .. })\n    }\n    #[allow(missing_docs)]\n    pub fn is_polycommit(&self) -> bool {\n        matches!(&self, Visibility::KZGCommit)\n    }\n\n    #[allow(missing_docs)]\n    pub fn is_hashed_public(&self) -> bool {\n        if let Visibility::Hashed {\n            hash_is_public: true,\n            ..\n        } = self\n        {\n            return true;\n        }\n        false\n    }\n    #[allow(missing_docs)]\n    pub fn is_hashed_private(&self) -> bool {\n        if let Visibility::Hashed {\n            hash_is_public: false,\n            ..\n        } = self\n        {\n            return true;\n        }\n        false\n    }\n\n    #[allow(missing_docs)]\n    pub fn requires_processing(&self) -> bool {\n        matches!(&self, Visibility::Hashed { .. }) | matches!(&self, Visibility::KZGCommit)\n    }\n    #[allow(missing_docs)]\n    pub fn overwrites_inputs(&self) -> Vec<usize> {\n        if let Visibility::Hashed { outlets, .. } = self {\n            return outlets.clone();\n        }\n        vec![]\n    }\n}\n\n/// Represents the scale of the model input, model parameters.\n#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)]\npub struct VarScales {\n    ///\n    pub input: crate::Scale,\n    ///\n    pub params: crate::Scale,\n    ///\n    pub rebase_multiplier: u32,\n}\n\nimpl std::fmt::Display for VarScales {\n    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n        write!(f, \"(inputs: {}, params: {})\", self.input, self.params)\n    }\n}\n\nimpl VarScales {\n    ///\n    pub fn get_max(&self) -> crate::Scale {\n        std::cmp::max(self.input, self.params)\n    }\n\n    ///\n    pub fn get_min(&self) -> crate::Scale {\n        std::cmp::min(self.input, self.params)\n    }\n\n    /// Place in [VarScales] struct.\n    pub fn from_args(args: &RunArgs) -> Result<Self, Box<dyn Error>> {\n        Ok(Self {\n            input: args.input_scale,\n            params: args.param_scale,\n            rebase_multiplier: args.scale_rebase_multiplier,\n        })\n    }\n}\n\n/// Represents whether the model input, model parameters, and model output are Public or Private to the prover.\n#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd)]\npub struct VarVisibility {\n    /// Input to the model or computational graph\n    pub input: Visibility,\n    /// Parameters, such as weights and biases, in the model\n    pub params: Visibility,\n    /// Output of the model or computational graph\n    pub output: Visibility,\n}\nimpl std::fmt::Display for VarVisibility {\n    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n        write!(\n            f,\n            \"(inputs: {}, params: {}, outputs: {})\",\n            self.input, self.params, self.output\n        )\n    }\n}\n\nimpl Default for VarVisibility {\n    fn default() -> Self {\n        Self {\n            input: Visibility::Private,\n            params: Visibility::Private,\n            output: Visibility::Public,\n        }\n    }\n}\n\nimpl VarVisibility {\n    /// Read from cli args whether the model input, model parameters, and model output are Public or Private to the prover.\n    /// Place in [VarVisibility] struct.\n    pub fn from_args(args: &RunArgs) -> Result<Self, Box<dyn Error>> {\n        let input_vis = &args.input_visibility;\n        let params_vis = &args.param_visibility;\n        let output_vis = &args.output_visibility;\n\n        if params_vis.is_public() {\n            return Err(\n                \"public visibility for params is deprecated, please use `fixed` instead\".into(),\n            );\n        }\n\n        if !output_vis.is_public()\n            & !params_vis.is_public()\n            & !input_vis.is_public()\n            & !output_vis.is_fixed()\n            & !params_vis.is_fixed()\n            & !input_vis.is_fixed()\n            & !output_vis.is_hashed()\n            & !params_vis.is_hashed()\n            & !input_vis.is_hashed()\n            & !output_vis.is_polycommit()\n            & !params_vis.is_polycommit()\n            & !input_vis.is_polycommit()\n        {\n            return Err(Box::new(GraphError::Visibility));\n        }\n        Ok(Self {\n            input: input_vis.clone(),\n            params: params_vis.clone(),\n            output: output_vis.clone(),\n        })\n    }\n}\n\n/// A wrapper for holding all columns that will be assigned to by a model.\n#[derive(Clone, Debug)]\npub struct ModelVars<F: PrimeField + TensorType + PartialOrd> {\n    #[allow(missing_docs)]\n    pub advices: Vec<VarTensor>,\n    #[allow(missing_docs)]\n    pub instance: Option<ValTensor<F>>,\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> ModelVars<F> {\n    /// Get instance col\n    pub fn get_instance_col(&self) -> Option<&Column<Instance>> {\n        if let Some(instance) = &self.instance {\n            match instance {\n                ValTensor::Instance { inner, .. } => Some(inner),\n                _ => None,\n            }\n        } else {\n            None\n        }\n    }\n\n    /// Set the initial instance offset\n    pub fn set_initial_instance_offset(&mut self, offset: usize) {\n        if let Some(instance) = &mut self.instance {\n            instance.set_initial_instance_offset(offset);\n        }\n    }\n\n    /// Get the total instance len\n    pub fn get_instance_len(&self) -> usize {\n        if let Some(instance) = &self.instance {\n            instance.get_total_instance_len()\n        } else {\n            0\n        }\n    }\n\n    /// Increment the instance offset\n    pub fn increment_instance_idx(&mut self) {\n        if let Some(instance) = &mut self.instance {\n            instance.increment_idx();\n        }\n    }\n\n    /// Reset the instance offset\n    pub fn set_instance_idx(&mut self, val: usize) {\n        if let Some(instance) = &mut self.instance {\n            instance.set_idx(val);\n        }\n    }\n\n    /// Get the instance offset\n    pub fn get_instance_idx(&self) -> usize {\n        if let Some(instance) = &self.instance {\n            instance.get_idx()\n        } else {\n            0\n        }\n    }\n\n    ///\n    pub fn instantiate_instance(\n        &mut self,\n        cs: &mut ConstraintSystem<F>,\n        instance_dims: Vec<Vec<usize>>,\n        instance_scale: crate::Scale,\n        existing_instance: Option<Column<Instance>>,\n    ) {\n        debug!(\"model uses {:?} instance dims\", instance_dims);\n        self.instance = if let Some(existing_instance) = existing_instance {\n            debug!(\"using existing instance\");\n            Some(ValTensor::new_instance_from_col(\n                instance_dims,\n                instance_scale,\n                existing_instance,\n            ))\n        } else {\n            Some(ValTensor::new_instance(cs, instance_dims, instance_scale))\n        };\n    }\n\n    /// Allocate all columns that will be assigned to by a model.\n    pub fn new(cs: &mut ConstraintSystem<F>, params: &GraphSettings) -> Self {\n        debug!(\"number of blinding factors: {}\", cs.blinding_factors());\n\n        let logrows = params.run_args.logrows as usize;\n        let var_len = params.total_assignments;\n        let num_inner_cols = params.run_args.num_inner_cols;\n        let num_constants = params.total_const_size;\n        let module_requires_fixed = params.module_requires_fixed();\n        let requires_dynamic_lookup = params.requires_dynamic_lookup();\n        let requires_shuffle = params.requires_shuffle();\n        let dynamic_lookup_and_shuffle_size = params.dynamic_lookup_and_shuffle_col_size();\n\n        let mut advices = (0..3)\n            .map(|_| VarTensor::new_advice(cs, logrows, num_inner_cols, var_len))\n            .collect_vec();\n\n        if requires_dynamic_lookup || requires_shuffle {\n            let num_cols = if requires_dynamic_lookup { 3 } else { 2 };\n            for _ in 0..num_cols {\n                let dynamic_lookup =\n                    VarTensor::new_advice(cs, logrows, 1, dynamic_lookup_and_shuffle_size);\n                if dynamic_lookup.num_blocks() > 1 {\n                    panic!(\"dynamic lookup or shuffle should only have one block\");\n                };\n                advices.push(dynamic_lookup);\n            }\n        }\n\n        debug!(\n            \"model uses {} advice blocks (size={})\",\n            advices.iter().map(|v| v.num_blocks()).sum::<usize>(),\n            num_inner_cols\n        );\n\n        let num_const_cols =\n            VarTensor::constant_cols(cs, logrows, num_constants, module_requires_fixed);\n        debug!(\"model uses {} fixed columns\", num_const_cols);\n\n        ModelVars {\n            advices,\n            instance: None,\n        }\n    }\n\n    /// Allocate all columns that will be assigned to by a model.\n    pub fn new_dummy() -> Self {\n        ModelVars {\n            advices: vec![],\n            instance: None,\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/lib.rs",
        "content": "#![deny(\n    bad_style,\n    dead_code,\n    improper_ctypes,\n    non_shorthand_field_patterns,\n    no_mangle_generic_items,\n    overflowing_literals,\n    path_statements,\n    patterns_in_fns_without_body,\n    unconditional_recursion,\n    unused,\n    unused_allocation,\n    unused_comparisons,\n    unused_parens,\n    while_true,\n    missing_docs,\n    trivial_casts,\n    trivial_numeric_casts,\n    unused_extern_crates,\n    unused_import_braces,\n    missing_debug_implementations,\n    unsafe_code\n)]\n// we allow this for our dynamic range based indexing scheme\n#![allow(clippy::single_range_in_vec_init)]\n\n//! A library for turning computational graphs, such as neural networks, into ZK-circuits.\n//!\n\nuse std::str::FromStr;\n\nuse circuit::{table::Range, CheckMode, Tolerance};\nuse clap::Args;\nuse graph::Visibility;\nuse halo2_proofs::poly::{\n    ipa::commitment::IPACommitmentScheme, kzg::commitment::KZGCommitmentScheme,\n};\nuse halo2curves::bn256::{Bn256, G1Affine};\nuse serde::{Deserialize, Serialize};\nuse tosubcommand::ToFlags;\n\n/// Methods for configuring tensor operations and assigning values to them in a Halo2 circuit.\npub mod circuit;\n/// CLI commands.\n#[cfg(not(target_arch = \"wasm32\"))]\npub mod commands;\n#[cfg(not(target_arch = \"wasm32\"))]\n// abigen doesn't generate docs for this module\n#[allow(missing_docs)]\n/// Utility functions for contracts\npub mod eth;\n/// Command execution\n///\n#[cfg(not(target_arch = \"wasm32\"))]\npub mod execute;\n/// Utilities for converting from Halo2 Field types to integers (and vice-versa).\npub mod fieldutils;\n/// Methods for loading onnx format models and automatically laying them out in\n/// a Halo2 circuit.\n#[cfg(feature = \"onnx\")]\npub mod graph;\n/// beautiful logging\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\npub mod logger;\n/// Tools for proofs and verification used by cli\npub mod pfsys;\n/// Python bindings\n#[cfg(feature = \"python-bindings\")]\npub mod python;\n/// srs sha hashes\n#[cfg(not(all(target_arch = \"wasm32\", target_os = \"unknown\")))]\npub mod srs_sha;\n/// An implementation of multi-dimensional tensors.\npub mod tensor;\n/// wasm prover and verifier\n#[cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))]\npub mod wasm;\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse lazy_static::lazy_static;\n\n/// The denominator in the fixed point representation used when quantizing inputs\npub type Scale = i32;\n\n#[cfg(not(target_arch = \"wasm32\"))]\n// Buf writer capacity\nlazy_static! {\n    /// The capacity of the buffer used for writing to disk\n    pub static ref EZKL_BUF_CAPACITY: usize = std::env::var(\"EZKL_BUF_CAPACITY\")\n        .unwrap_or(\"8000\".to_string())\n        .parse()\n        .unwrap();\n\n    /// The serialization format for the keys\n    pub static ref EZKL_KEY_FORMAT: String = std::env::var(\"EZKL_KEY_FORMAT\")\n        .unwrap_or(\"raw-bytes\".to_string());\n}\n\n#[cfg(target_arch = \"wasm32\")]\nconst EZKL_KEY_FORMAT: &str = \"raw-bytes\";\n\n#[cfg(target_arch = \"wasm32\")]\nconst EZKL_BUF_CAPACITY: &usize = &8000;\n\n#[derive(\n    Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default, Copy,\n)]\n/// Commitment scheme\npub enum Commitments {\n    #[default]\n    /// KZG\n    KZG,\n    /// IPA\n    IPA,\n}\n\nimpl From<Option<Commitments>> for Commitments {\n    fn from(value: Option<Commitments>) -> Self {\n        value.unwrap_or(Commitments::KZG)\n    }\n}\n\nimpl FromStr for Commitments {\n    type Err = String;\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        match s.to_lowercase().as_str() {\n            \"kzg\" => Ok(Commitments::KZG),\n            \"ipa\" => Ok(Commitments::IPA),\n            _ => Err(\"Invalid value for Commitments\".to_string()),\n        }\n    }\n}\n\nimpl From<KZGCommitmentScheme<Bn256>> for Commitments {\n    fn from(_value: KZGCommitmentScheme<Bn256>) -> Self {\n        Commitments::KZG\n    }\n}\n\nimpl From<IPACommitmentScheme<G1Affine>> for Commitments {\n    fn from(_value: IPACommitmentScheme<G1Affine>) -> Self {\n        Commitments::IPA\n    }\n}\n\nimpl std::fmt::Display for Commitments {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Commitments::KZG => write!(f, \"kzg\"),\n            Commitments::IPA => write!(f, \"ipa\"),\n        }\n    }\n}\n\nimpl ToFlags for Commitments {\n    /// Convert the struct to a subcommand string\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl From<String> for Commitments {\n    fn from(value: String) -> Self {\n        match value.to_lowercase().as_str() {\n            \"kzg\" => Commitments::KZG,\n            \"ipa\" => Commitments::IPA,\n            _ => {\n                log::error!(\"Invalid value for Commitments\");\n                log::warn!(\"defaulting to KZG\");\n                Commitments::KZG\n            }\n        }\n    }\n}\n\n/// Parameters specific to a proving run\n#[derive(Debug, Args, Deserialize, Serialize, Clone, PartialEq, PartialOrd, ToFlags)]\npub struct RunArgs {\n    /// The tolerance for error on model outputs\n    #[arg(short = 'T', long, default_value = \"0\")]\n    pub tolerance: Tolerance,\n    /// The denominator in the fixed point representation used when quantizing inputs\n    #[arg(short = 'S', long, default_value = \"7\", allow_hyphen_values = true)]\n    pub input_scale: Scale,\n    /// The denominator in the fixed point representation used when quantizing parameters\n    #[arg(long, default_value = \"7\", allow_hyphen_values = true)]\n    pub param_scale: Scale,\n    /// if the scale is ever > scale_rebase_multiplier * input_scale then the scale is rebased to input_scale (this a more advanced parameter, use with caution)\n    #[arg(long, default_value = \"1\")]\n    pub scale_rebase_multiplier: u32,\n    /// The min and max elements in the lookup table input column\n    #[arg(short = 'B', long, value_parser = parse_key_val::<i128, i128>, default_value = \"-32768->32768\")]\n    pub lookup_range: Range,\n    /// The log_2 number of rows\n    #[arg(short = 'K', long, default_value = \"17\")]\n    pub logrows: u32,\n    /// The log_2 number of rows\n    #[arg(short = 'N', long, default_value = \"2\")]\n    pub num_inner_cols: usize,\n    /// Hand-written parser for graph variables, eg. batch_size=1\n    #[arg(short = 'V', long, value_parser = parse_key_val::<String, usize>, default_value = \"batch_size->1\", value_delimiter = ',')]\n    pub variables: Vec<(String, usize)>,\n    /// Flags whether inputs are public, private, hashed, fixed, kzgcommit\n    #[arg(long, default_value = \"private\")]\n    pub input_visibility: Visibility,\n    /// Flags whether outputs are public, private, fixed, hashed, kzgcommit\n    #[arg(long, default_value = \"public\")]\n    pub output_visibility: Visibility,\n    /// Flags whether params are fixed, private, hashed, kzgcommit\n    #[arg(long, default_value = \"private\")]\n    pub param_visibility: Visibility,\n    #[arg(long, default_value = \"false\")]\n    /// Rebase the scale using lookup table for division instead of using a range check\n    pub div_rebasing: bool,\n    /// Should constants with 0.0 fraction be rebased to scale 0\n    #[arg(long, default_value = \"false\")]\n    pub rebase_frac_zero_constants: bool,\n    /// check mode (safe, unsafe, etc)\n    #[arg(long, default_value = \"unsafe\")]\n    pub check_mode: CheckMode,\n    /// commitment scheme\n    #[arg(long, default_value = \"kzg\")]\n    pub commitment: Option<Commitments>,\n}\n\nimpl Default for RunArgs {\n    fn default() -> Self {\n        Self {\n            tolerance: Tolerance::default(),\n            input_scale: 7,\n            param_scale: 7,\n            scale_rebase_multiplier: 1,\n            lookup_range: (-32768, 32768),\n            logrows: 17,\n            num_inner_cols: 2,\n            variables: vec![(\"batch_size\".to_string(), 1)],\n            input_visibility: Visibility::Private,\n            output_visibility: Visibility::Public,\n            param_visibility: Visibility::Private,\n            div_rebasing: false,\n            rebase_frac_zero_constants: false,\n            check_mode: CheckMode::UNSAFE,\n            commitment: None,\n        }\n    }\n}\n\nimpl RunArgs {\n    ///\n    pub fn validate(&self) -> Result<(), Box<dyn std::error::Error>> {\n        if self.param_visibility == Visibility::Public {\n            return Err(\n                \"params cannot be public instances, you are probably trying to use `fixed` or `kzgcommit`\"\n                    .into(),\n            );\n        }\n        if self.scale_rebase_multiplier < 1 {\n            return Err(\"scale_rebase_multiplier must be >= 1\".into());\n        }\n        if self.lookup_range.0 > self.lookup_range.1 {\n            return Err(\"lookup_range min is greater than max\".into());\n        }\n        if self.logrows < 1 {\n            return Err(\"logrows must be >= 1\".into());\n        }\n        if self.num_inner_cols < 1 {\n            return Err(\"num_inner_cols must be >= 1\".into());\n        }\n        if self.tolerance.val > 0.0 && self.output_visibility != Visibility::Public {\n            return Err(\"tolerance > 0.0 requires output_visibility to be public\".into());\n        }\n        Ok(())\n    }\n\n    /// Export the ezkl configuration as json\n    pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> {\n        let serialized = match serde_json::to_string(&self) {\n            Ok(s) => s,\n            Err(e) => {\n                return Err(Box::new(e));\n            }\n        };\n        Ok(serialized)\n    }\n    /// Parse an ezkl configuration from a json\n    pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> {\n        serde_json::from_str(arg_json)\n    }\n}\n\n/// Parse a single key-value pair\nfn parse_key_val<T, U>(\n    s: &str,\n) -> Result<(T, U), Box<dyn std::error::Error + Send + Sync + 'static>>\nwhere\n    T: std::str::FromStr + std::fmt::Debug,\n    T::Err: std::error::Error + Send + Sync + 'static,\n    U: std::str::FromStr + std::fmt::Debug,\n    U::Err: std::error::Error + Send + Sync + 'static,\n{\n    let pos = s\n        .find(\"->\")\n        .ok_or_else(|| format!(\"invalid x->y: no `->` found in `{s}`\"))?;\n    let a = s[..pos].parse()?;\n    let b = s[pos + 2..].parse()?;\n    Ok((a, b))\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/logger.rs",
        "content": "use colored::*;\nuse env_logger::Builder;\nuse log::{Level, LevelFilter, Record};\nuse std::env;\nuse std::fmt::Formatter;\nuse std::io::Write;\n\n/// sets the log level color\n#[allow(dead_code)]\npub fn level_color(level: &log::Level, msg: &str) -> String {\n    match level {\n        Level::Error => msg.red(),\n        Level::Warn => msg.yellow(),\n        Level::Info => msg.blue(),\n        Level::Debug => msg.green(),\n        Level::Trace => msg.magenta(),\n    }\n    .bold()\n    .to_string()\n}\n\n/// sets the log level text color\npub fn level_text_color(level: &log::Level, msg: &str) -> String {\n    match level {\n        Level::Error => msg.red(),\n        Level::Warn => msg.yellow(),\n        Level::Info => msg.white(),\n        Level::Debug => msg.white(),\n        Level::Trace => msg.white(),\n    }\n    .bold()\n    .to_string()\n}\n\n/// sets the log level token\nfn level_token(level: &Level) -> &str {\n    match *level {\n        Level::Error => \"E\",\n        Level::Warn => \"W\",\n        Level::Info => \"*\",\n        Level::Debug => \"D\",\n        Level::Trace => \"T\",\n    }\n}\n\n/// sets the log level prefix token\nfn prefix_token(level: &Level) -> String {\n    format!(\n        \"{}{}{}\",\n        \"[\".blue().bold(),\n        level_color(level, level_token(level)),\n        \"]\".blue().bold()\n    )\n}\n\n/// formats the log\npub fn format(buf: &mut Formatter, record: &Record<'_>) -> Result<(), std::fmt::Error> {\n    let sep = format!(\"\\n{} \", \" | \".white().bold());\n    let level = record.level();\n    writeln!(\n        buf,\n        \"{} {}\",\n        prefix_token(&level),\n        level_color(&level, record.args().as_str().unwrap()).replace('\\n', &sep),\n    )\n}\n\n/// initializes the logger\npub fn init_logger() {\n    let mut builder = Builder::new();\n\n    builder.format(move |buf, record| {\n        writeln!(\n            buf,\n            \"{} [{}, {}] - {}\",\n            prefix_token(&record.level()),\n            //    pretty print UTC time\n            chrono::Utc::now()\n                .format(\"%Y-%m-%d %H:%M:%S\")\n                .to_string()\n                .bright_magenta(),\n            record.metadata().target(),\n            level_text_color(&record.level(), &format!(\"{}\", record.args()))\n                .replace('\\n', &format!(\"\\n{} \", \" | \".white().bold()))\n        )\n    });\n    builder.target(env_logger::Target::Stdout);\n    builder.filter(None, LevelFilter::Info);\n    if env::var(\"RUST_LOG\").is_ok() {\n        builder.parse_filters(&env::var(\"RUST_LOG\").unwrap());\n    }\n    builder.init();\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/pfsys/evm/aggregation_kzg.rs",
        "content": "#[cfg(not(target_arch = \"wasm32\"))]\nuse crate::graph::CircuitSize;\nuse crate::pfsys::{Snark, SnarkWitness};\n#[cfg(not(target_arch = \"wasm32\"))]\nuse colored_json::ToColoredJson;\nuse halo2_proofs::circuit::AssignedCell;\nuse halo2_proofs::plonk::{self};\nuse halo2_proofs::{\n    circuit::{Layouter, SimpleFloorPlanner, Value},\n    plonk::{Circuit, ConstraintSystem},\n};\nuse halo2_wrong_ecc::{\n    integer::rns::Rns,\n    maingate::{\n        MainGate, MainGateConfig, MainGateInstructions, RangeChip, RangeConfig, RangeInstructions,\n        RegionCtx,\n    },\n    EccConfig,\n};\nuse halo2curves::bn256::{Bn256, Fq, Fr, G1Affine};\nuse halo2curves::ff::PrimeField;\nuse itertools::Itertools;\n#[cfg(not(target_arch = \"wasm32\"))]\nuse log::debug;\nuse log::trace;\nuse rand::rngs::OsRng;\nuse snark_verifier::loader::native::NativeLoader;\nuse snark_verifier::loader::EcPointLoader;\nuse snark_verifier::{\n    loader,\n    pcs::{\n        kzg::{\n            Bdfg21, KzgAccumulator, KzgAs, KzgSuccinctVerifyingKey, LimbsEncoding,\n            LimbsEncodingInstructions,\n        },\n        AccumulationScheme, AccumulationSchemeProver,\n    },\n    system,\n    util::arithmetic::fe_to_limbs,\n    verifier::{self, SnarkVerifier},\n};\nuse std::rc::Rc;\nuse thiserror::Error;\n\nconst LIMBS: usize = 4;\nconst BITS: usize = 68;\ntype As = KzgAs<Bn256, Bdfg21>;\n/// Type for aggregator verification\ntype PlonkSuccinctVerifier = verifier::plonk::PlonkSuccinctVerifier<As, LimbsEncoding<LIMBS, BITS>>;\n\nconst T: usize = 5;\nconst RATE: usize = 4;\nconst R_F: usize = 8;\nconst R_P: usize = 60;\n\ntype Svk = KzgSuccinctVerifyingKey<G1Affine>;\ntype BaseFieldEccChip = halo2_wrong_ecc::BaseFieldEccChip<G1Affine, LIMBS, BITS>;\n/// The loader type used in the transcript definition\ntype Halo2Loader<'a> = loader::halo2::Halo2Loader<'a, G1Affine, BaseFieldEccChip>;\n/// Application snark transcript\npub type PoseidonTranscript<L, S> =\n    system::halo2::transcript::halo2::PoseidonTranscript<G1Affine, L, S, T, RATE, R_F, R_P>;\n\n#[derive(Error, Debug)]\n/// Errors related to proof aggregation\npub enum AggregationError {\n    /// A KZG proof could not be verified\n    #[error(\"failed to verify KZG proof\")]\n    KZGProofVerification,\n    /// proof read errors\n    #[error(\"Failed to read proof\")]\n    ProofRead,\n    /// proof verification errors\n    #[error(\"Failed to verify proof\")]\n    ProofVerify,\n    /// proof creation errors\n    #[error(\"Failed to create proof\")]\n    ProofCreate,\n}\n\ntype AggregationResult<'a> = (\n    // accumulator\n    KzgAccumulator<G1Affine, Rc<Halo2Loader<'a>>>,\n    // the set of assigned cells\n    Vec<Vec<AssignedCell<Fr, Fr>>>,\n);\n\ntype LoadedProof<'a> = verifier::plonk::PlonkProof<\n    G1Affine,\n    Rc<\n        loader::halo2::Halo2Loader<\n            'a,\n            G1Affine,\n            halo2_wrong_ecc::BaseFieldEccChip<G1Affine, 4, 68>,\n        >,\n    >,\n    KzgAs<Bn256, Bdfg21>,\n>;\n\n/// Aggregate one or more application snarks of the same shape into a KzgAccumulator\npub fn aggregate<'a>(\n    svk: &Svk,\n    loader: &Rc<Halo2Loader<'a>>,\n    snarks: &[SnarkWitness<Fr, G1Affine>],\n    as_proof: Value<&'_ [u8]>,\n    split_proofs: bool,\n) -> Result<AggregationResult<'a>, plonk::Error> {\n    let assign_instances = |instances: &[Vec<Value<Fr>>]| {\n        instances\n            .iter()\n            .map(|instances| {\n                instances\n                    .iter()\n                    .map(|instance| loader.assign_scalar(*instance))\n                    .collect_vec()\n            })\n            .collect_vec()\n    };\n\n    let mut accumulators = vec![];\n    let mut snark_instances = vec![];\n    let mut proofs: Vec<LoadedProof<'_>> = vec![];\n\n    for snark in snarks.iter() {\n        let protocol = snark.protocol.as_ref().unwrap().loaded(loader);\n        let instances = assign_instances(&snark.instances);\n\n        // get assigned cells\n        snark_instances.extend(instances.iter().map(|instance| {\n            instance\n                .iter()\n                .map(|v| v.clone().into_assigned())\n                .collect_vec()\n        }));\n\n        // loader.ctx().constrain_equal(cell_0, cell_1)\n        let mut transcript = PoseidonTranscript::<Rc<Halo2Loader>, _>::new(loader, snark.proof());\n        let proof = PlonkSuccinctVerifier::read_proof(svk, &protocol, &instances, &mut transcript)\n            .map_err(|_| plonk::Error::Synthesis)?;\n\n        if split_proofs {\n            let previous_proof = proofs.last();\n            let split_commit = match snark.clone().split {\n                Some(split) => split,\n                None => {\n                    log::error!(\"Failed to split KZG commit for sequential proofs\");\n                    return Err(plonk::Error::Synthesis);\n                }\n            };\n            if let Some(previous_proof) = previous_proof {\n                // output of previous proof\n                let output = &previous_proof.witnesses[split_commit.start..split_commit.end];\n                // input of current proof\n                let split_commit_len = split_commit.end - split_commit.start;\n                let input = &proof.witnesses[..split_commit_len];\n                // these points were already assigned previously when loading the transcript so this is safe\n                // and equivalent to a copy constraint and an equality constraint\n                for (output, input) in output.iter().zip(input.iter()) {\n                    loader\n                        .ec_point_assert_eq(\"assert commits match\", output, input)\n                        .map_err(|e| {\n                            log::error!(\n                                \"Failed to match KZG commits for sequential proofs: {:?}\",\n                                e\n                            );\n                            plonk::Error::Synthesis\n                        })?;\n                }\n            }\n            proofs.push(proof.clone());\n        }\n\n        let mut accum = PlonkSuccinctVerifier::verify(svk, &protocol, &instances, &proof)\n            .map_err(|_| plonk::Error::Synthesis)?;\n        accumulators.append(&mut accum);\n    }\n    let accumulator = {\n        let mut transcript = PoseidonTranscript::<Rc<Halo2Loader>, _>::new(loader, as_proof);\n        let proof = As::read_proof(&Default::default(), &accumulators, &mut transcript).unwrap();\n        As::verify(&Default::default(), &accumulators, &proof).map_err(|_| plonk::Error::Synthesis)\n    }?;\n    Ok((accumulator, snark_instances))\n}\n\n/// The Halo2 Config for the aggregation circuit\n#[derive(Clone, Debug)]\npub struct AggregationConfig {\n    main_gate_config: MainGateConfig,\n    range_config: RangeConfig,\n}\n\nimpl AggregationConfig {\n    /// Configure the aggregation circuit\n    pub fn configure<F: PrimeField>(\n        meta: &mut ConstraintSystem<F>,\n        composition_bits: Vec<usize>,\n        overflow_bits: Vec<usize>,\n    ) -> Self {\n        let main_gate_config = MainGate::<F>::configure(meta);\n        let range_config =\n            RangeChip::<F>::configure(meta, &main_gate_config, composition_bits, overflow_bits);\n\n        #[cfg(not(target_arch = \"wasm32\"))]\n        {\n            let circuit_size = CircuitSize::from_cs(meta, 23);\n\n            // not wasm\n\n            debug!(\n                \"circuit size: \\n {}\",\n                circuit_size\n                    .as_json()\n                    .unwrap()\n                    .to_colored_json_auto()\n                    .unwrap()\n            );\n        }\n\n        AggregationConfig {\n            main_gate_config,\n            range_config,\n        }\n    }\n\n    /// Create a MainGate from the aggregation approach\n    pub fn main_gate(&self) -> MainGate<Fr> {\n        MainGate::new(self.main_gate_config.clone())\n    }\n\n    /// Create a range chip to decompose and range check inputs\n    pub fn range_chip(&self) -> RangeChip<Fr> {\n        RangeChip::new(self.range_config.clone())\n    }\n\n    /// Create an ecc chip for ec ops\n    pub fn ecc_chip(&self) -> BaseFieldEccChip {\n        BaseFieldEccChip::new(EccConfig::new(\n            self.range_config.clone(),\n            self.main_gate_config.clone(),\n        ))\n    }\n}\n\n/// Aggregation Circuit with a SuccinctVerifyingKey, application snark witnesses (each with a proof and instance variables), and the instance variables and the resulting aggregation circuit proof.\n#[derive(Clone, Debug)]\npub struct AggregationCircuit {\n    svk: Svk,\n    snarks: Vec<SnarkWitness<Fr, G1Affine>>,\n    instances: Vec<Fr>,\n    as_proof: Value<Vec<u8>>,\n    split_proof: bool,\n}\n\nimpl AggregationCircuit {\n    /// Create a new Aggregation Circuit with a SuccinctVerifyingKey, application snark witnesses (each with a proof and instance variables), and the instance variables and the resulting aggregation circuit proof.\n    pub fn new(\n        svk: &KzgSuccinctVerifyingKey<G1Affine>,\n        snarks: impl IntoIterator<Item = Snark<Fr, G1Affine>>,\n        split_proof: bool,\n    ) -> Result<Self, AggregationError> {\n        let snarks = snarks.into_iter().collect_vec();\n\n        let mut accumulators = vec![];\n\n        for snark in snarks.iter() {\n            trace!(\"Aggregating with snark instances {:?}\", snark.instances);\n            let mut transcript = PoseidonTranscript::<NativeLoader, _>::new(snark.proof.as_slice());\n            let proof = PlonkSuccinctVerifier::read_proof(\n                svk,\n                snark.protocol.as_ref().unwrap(),\n                &snark.instances,\n                &mut transcript,\n            )\n            .map_err(|e| {\n                log::error!(\"{:?}\", e);\n                AggregationError::ProofRead\n            })?;\n            let mut accum = PlonkSuccinctVerifier::verify(\n                svk,\n                snark.protocol.as_ref().unwrap(),\n                &snark.instances,\n                &proof,\n            )\n            .map_err(|_| AggregationError::ProofVerify)?;\n            accumulators.append(&mut accum);\n        }\n\n        trace!(\"Accumulator\");\n        let (accumulator, as_proof) = {\n            let mut transcript = PoseidonTranscript::<NativeLoader, _>::new(Vec::new());\n            let accumulator =\n                As::create_proof(&Default::default(), &accumulators, &mut transcript, OsRng)\n                    .map_err(|_| AggregationError::ProofCreate)?;\n            (accumulator, transcript.finalize())\n        };\n\n        trace!(\"KzgAccumulator\");\n        let KzgAccumulator { lhs, rhs } = accumulator;\n        let instances = [lhs.x, lhs.y, rhs.x, rhs.y]\n            .map(fe_to_limbs::<_, _, LIMBS, BITS>)\n            .concat();\n\n        Ok(Self {\n            svk: *svk,\n            snarks: snarks.into_iter().map_into().collect(),\n            instances,\n            as_proof: Value::known(as_proof),\n            split_proof,\n        })\n    }\n\n    ///\n    pub fn num_limbs() -> usize {\n        LIMBS\n    }\n    ///\n    pub fn num_bits() -> usize {\n        BITS\n    }\n\n    /// Accumulator indices used in generating verifier.\n    pub fn accumulator_indices() -> Vec<(usize, usize)> {\n        (0..4 * LIMBS).map(|idx| (0, idx)).collect()\n    }\n\n    /// Number of instance variables for the aggregation circuit, used in generating verifier.\n    pub fn num_instance(orginal_circuit_instances: usize) -> Vec<usize> {\n        let accumulation_instances = 4 * LIMBS;\n        vec![accumulation_instances + orginal_circuit_instances]\n    }\n\n    /// Instance variables for the aggregation circuit, fed to verifier.\n    pub fn instances(&self) -> Vec<Fr> {\n        // also get snark instances here\n        let mut snark_instances: Vec<Vec<Vec<Value<Fr>>>> = self\n            .snarks\n            .iter()\n            .map(|snark| snark.instances.clone())\n            .collect_vec();\n\n        // reduce from Vec<Vec<Vec<Value<Fr>>>> to Vec<Vec<Value<Fr>>>\n        let mut instances: Vec<Fr> = self.instances.clone();\n        for snark_instance in snark_instances.iter_mut() {\n            for instance in snark_instance.iter_mut() {\n                let mut felt_evals = vec![];\n                for value in instance.iter_mut() {\n                    value.map(|v| felt_evals.push(v));\n                }\n                instances.extend(felt_evals);\n            }\n        }\n\n        instances\n    }\n\n    fn as_proof(&self) -> Value<&[u8]> {\n        self.as_proof.as_ref().map(Vec::as_slice)\n    }\n}\n\nimpl Circuit<Fr> for AggregationCircuit {\n    type Config = AggregationConfig;\n    type FloorPlanner = SimpleFloorPlanner;\n    type Params = ();\n\n    fn without_witnesses(&self) -> Self {\n        Self {\n            svk: self.svk,\n            snarks: self\n                .snarks\n                .iter()\n                .map(SnarkWitness::without_witnesses)\n                .collect(),\n            instances: Vec::new(),\n            as_proof: Value::unknown(),\n            split_proof: self.split_proof,\n        }\n    }\n\n    fn configure(meta: &mut ConstraintSystem<Fr>) -> Self::Config {\n        AggregationConfig::configure(\n            meta,\n            vec![BITS / LIMBS],\n            Rns::<Fq, Fr, LIMBS, BITS>::construct().overflow_lengths(),\n        )\n    }\n\n    fn synthesize(\n        &self,\n        config: Self::Config,\n        mut layouter: impl Layouter<Fr>,\n    ) -> Result<(), plonk::Error> {\n        let main_gate = config.main_gate();\n        let range_chip = config.range_chip();\n\n        range_chip.load_table(&mut layouter)?;\n\n        let (accumulator_limbs, snark_instances) = layouter.assign_region(\n            || \"\",\n            |region| {\n                let ctx = RegionCtx::new(region, 0);\n\n                let ecc_chip = config.ecc_chip();\n                let loader = Halo2Loader::new(ecc_chip, ctx);\n                let (accumulator, snark_instances) = aggregate(\n                    &self.svk,\n                    &loader,\n                    &self.snarks,\n                    self.as_proof(),\n                    self.split_proof,\n                )?;\n\n                let accumulator_limbs = [accumulator.lhs, accumulator.rhs]\n                    .iter()\n                    .map(|ec_point| {\n                        loader\n                            .ecc_chip()\n                            .assign_ec_point_to_limbs(&mut loader.ctx_mut(), ec_point.assigned())\n                    })\n                    .collect::<Result<Vec<_>, plonk::Error>>()?\n                    .into_iter()\n                    .flatten();\n\n                Ok((accumulator_limbs, snark_instances))\n            },\n        )?;\n\n        let mut instance_offset = 0;\n        for limb in accumulator_limbs {\n            main_gate.expose_public(layouter.namespace(|| \"\"), limb, instance_offset)?;\n            instance_offset += 1;\n        }\n\n        for instance in snark_instances.into_iter() {\n            for elem in instance.into_iter() {\n                main_gate.expose_public(layouter.namespace(|| \"\"), elem, instance_offset)?;\n                instance_offset += 1;\n            }\n        }\n\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/pfsys/evm/mod.rs",
        "content": "use thiserror::Error;\n\n/// Aggregate proof generation for EVM using KZG\npub mod aggregation_kzg;\n\n#[derive(Error, Debug)]\n/// Errors related to evm verification\npub enum EvmVerificationError {\n    /// If the Solidity verifier worked but returned false\n    #[error(\"Solidity verifier found the proof invalid\")]\n    InvalidProof,\n    /// If the Solidity verifier threw and error (e.g. OutOfGas)\n    #[error(\"Execution of Solidity code failed\")]\n    SolidityExecution,\n    /// EVM execution errors\n    #[error(\"EVM execution of raw code failed\")]\n    RawExecution,\n    /// EVM verify errors\n    #[error(\"evm verification reverted\")]\n    Reverted,\n    /// EVM verify errors\n    #[error(\"evm deployment failed\")]\n    Deploy,\n    /// Invalid Visibilit\n    #[error(\"Invalid visibility\")]\n    InvalidVisibility,\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/pfsys/mod.rs",
        "content": "/// EVM related proving and verification\npub mod evm;\n\n/// SRS generation, processing, verification and downloading\npub mod srs;\n\nuse crate::circuit::CheckMode;\nuse crate::graph::GraphWitness;\nuse crate::pfsys::evm::aggregation_kzg::PoseidonTranscript;\nuse crate::{Commitments, EZKL_BUF_CAPACITY, EZKL_KEY_FORMAT};\nuse clap::ValueEnum;\nuse halo2_proofs::circuit::Value;\nuse halo2_proofs::plonk::{\n    create_proof, keygen_pk, keygen_vk_custom, verify_proof, Circuit, ProvingKey, VerifyingKey,\n};\nuse halo2_proofs::poly::commitment::{CommitmentScheme, Params, ParamsProver, Prover, Verifier};\nuse halo2_proofs::poly::ipa::commitment::IPACommitmentScheme;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2_proofs::poly::VerificationStrategy;\nuse halo2_proofs::transcript::{EncodedChallenge, TranscriptReadBuffer, TranscriptWriterBuffer};\nuse halo2curves::ff::{FromUniformBytes, PrimeField, WithSmallOrderMulGroup};\nuse halo2curves::serde::SerdeObject;\nuse halo2curves::CurveAffine;\nuse instant::Instant;\nuse log::{debug, info, trace};\n#[cfg(not(feature = \"det-prove\"))]\nuse rand::rngs::OsRng;\n#[cfg(feature = \"det-prove\")]\nuse rand::rngs::StdRng;\nuse serde::de::DeserializeOwned;\nuse serde::{Deserialize, Serialize};\nuse snark_verifier::loader::native::NativeLoader;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse snark_verifier::verifier::plonk::PlonkProtocol;\nuse std::error::Error;\nuse std::fs::File;\nuse std::io::{self, BufReader, BufWriter, Cursor, Write};\nuse std::ops::Deref;\nuse std::path::PathBuf;\nuse thiserror::Error as thisError;\nuse tosubcommand::ToFlags;\n\nuse halo2curves::bn256::{Bn256, Fr, G1Affine};\n\nfn serde_format_from_str(s: &str) -> halo2_proofs::SerdeFormat {\n    match s {\n        \"processed\" => halo2_proofs::SerdeFormat::Processed,\n        \"raw-bytes-unchecked\" => halo2_proofs::SerdeFormat::RawBytesUnchecked,\n        \"raw-bytes\" => halo2_proofs::SerdeFormat::RawBytes,\n        _ => panic!(\"invalid serde format\"),\n    }\n}\n\n#[allow(missing_docs)]\n#[derive(\n    ValueEnum, Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize, Serialize, PartialOrd,\n)]\npub enum ProofType {\n    #[default]\n    Single,\n    ForAggr,\n}\n\nimpl std::fmt::Display for ProofType {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(\n            f,\n            \"{}\",\n            match self {\n                ProofType::Single => \"single\",\n                ProofType::ForAggr => \"for-aggr\",\n            }\n        )\n    }\n}\n\nimpl ToFlags for ProofType {\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\nimpl From<ProofType> for TranscriptType {\n    fn from(val: ProofType) -> Self {\n        match val {\n            ProofType::Single => TranscriptType::EVM,\n            ProofType::ForAggr => TranscriptType::Poseidon,\n        }\n    }\n}\n\nimpl From<ProofType> for StrategyType {\n    fn from(val: ProofType) -> Self {\n        match val {\n            ProofType::Single => StrategyType::Single,\n            ProofType::ForAggr => StrategyType::Accum,\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for ProofType {\n    fn to_object(&self, py: Python) -> PyObject {\n        match self {\n            ProofType::Single => \"Single\".to_object(py),\n            ProofType::ForAggr => \"ForAggr\".to_object(py),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n/// Obtains StrategyType from PyObject (Required for StrategyType to be compatible with Python)\nimpl<'source> pyo3::FromPyObject<'source> for ProofType {\n    fn extract(ob: &'source pyo3::PyAny) -> pyo3::PyResult<Self> {\n        let trystr = <pyo3::types::PyString as pyo3::PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n        match strval.to_lowercase().as_str() {\n            \"single\" => Ok(ProofType::Single),\n            \"for-aggr\" => Ok(ProofType::ForAggr),\n            _ => Err(pyo3::exceptions::PyValueError::new_err(\n                \"Invalid value for ProofType\",\n            )),\n        }\n    }\n}\n\n#[allow(missing_docs)]\n#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]\npub enum StrategyType {\n    Single,\n    Accum,\n}\nimpl std::fmt::Display for StrategyType {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        self.to_possible_value()\n            .expect(\"no values are skipped\")\n            .get_name()\n            .fmt(f)\n    }\n}\n#[cfg(feature = \"python-bindings\")]\n/// Converts StrategyType into a PyObject (Required for StrategyType to be compatible with Python)\nimpl pyo3::IntoPy<PyObject> for StrategyType {\n    fn into_py(self, py: Python) -> PyObject {\n        match self {\n            StrategyType::Single => \"single\".to_object(py),\n            StrategyType::Accum => \"accum\".to_object(py),\n        }\n    }\n}\n#[cfg(feature = \"python-bindings\")]\n/// Obtains StrategyType from PyObject (Required for StrategyType to be compatible with Python)\nimpl<'source> pyo3::FromPyObject<'source> for StrategyType {\n    fn extract(ob: &'source pyo3::PyAny) -> pyo3::PyResult<Self> {\n        let trystr = <pyo3::types::PyString as pyo3::PyTryFrom>::try_from(ob)?;\n        let strval = trystr.to_string();\n        match strval.to_lowercase().as_str() {\n            \"single\" => Ok(StrategyType::Single),\n            \"accum\" => Ok(StrategyType::Accum),\n            _ => Err(pyo3::exceptions::PyValueError::new_err(\n                \"Invalid value for StrategyType\",\n            )),\n        }\n    }\n}\n\n#[derive(thisError, Debug)]\n/// Errors related to pfsys\npub enum PfSysError {\n    /// Packing exponent is too large\n    #[error(\"largest packing exponent exceeds max. try reducing the scale\")]\n    PackingExponent,\n}\n\n#[allow(missing_docs)]\n#[derive(\n    ValueEnum, Default, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, PartialOrd,\n)]\npub enum TranscriptType {\n    Poseidon,\n    #[default]\n    EVM,\n}\n\nimpl std::fmt::Display for TranscriptType {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(\n            f,\n            \"{}\",\n            match self {\n                TranscriptType::Poseidon => \"poseidon\",\n                TranscriptType::EVM => \"evm\",\n            }\n        )\n    }\n}\n\nimpl ToFlags for TranscriptType {\n    fn to_flags(&self) -> Vec<String> {\n        vec![format!(\"{}\", self)]\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\nimpl ToPyObject for TranscriptType {\n    fn to_object(&self, py: Python) -> PyObject {\n        match self {\n            TranscriptType::Poseidon => \"Poseidon\".to_object(py),\n            TranscriptType::EVM => \"EVM\".to_object(py),\n        }\n    }\n}\n\n#[cfg(feature = \"python-bindings\")]\n///\npub fn g1affine_to_pydict(g1affine_dict: &PyDict, g1affine: &G1Affine) {\n    let g1affine_x = field_to_string(&g1affine.x);\n    let g1affine_y = field_to_string(&g1affine.y);\n    g1affine_dict.set_item(\"x\", g1affine_x).unwrap();\n    g1affine_dict.set_item(\"y\", g1affine_y).unwrap();\n}\n\n#[cfg(feature = \"python-bindings\")]\nuse halo2curves::bn256::G1;\n#[cfg(feature = \"python-bindings\")]\n///\npub fn g1_to_pydict(g1_dict: &PyDict, g1: &G1) {\n    let g1_x = field_to_string(&g1.x);\n    let g1_y = field_to_string(&g1.y);\n    let g1_z = field_to_string(&g1.z);\n    g1_dict.set_item(\"x\", g1_x).unwrap();\n    g1_dict.set_item(\"y\", g1_y).unwrap();\n    g1_dict.set_item(\"z\", g1_z).unwrap();\n}\n\n/// converts fp into a little endian Hex string\npub fn field_to_string<F: PrimeField + SerdeObject + Serialize>(fp: &F) -> String {\n    let repr = serde_json::to_string(&fp).unwrap();\n    let b: String = serde_json::from_str(&repr).unwrap();\n    b\n}\n\n/// converts a little endian Hex string into a field element\npub fn string_to_field<F: PrimeField + SerdeObject + Serialize + DeserializeOwned>(\n    b: &String,\n) -> F {\n    let repr = serde_json::to_string(&b).unwrap();\n    let fp: F = serde_json::from_str(&repr).unwrap();\n    fp\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]\n/// Contains the instances of the circuit in human readable form\npub struct PrettyElements {\n    /// the inputs as rescaled floats -- represented as a String for maximum compatibility with Python and JS\n    pub rescaled_inputs: Vec<Vec<String>>,\n    /// the inputs as felts but 0x strings -- represented as a String for maximum compatibility with Python and JS\n    pub inputs: Vec<Vec<String>>,\n    /// the processed inputs (eg. hash of the inputs) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS\n    pub processed_inputs: Vec<Vec<String>>,\n    /// the processed params (eg. hash of the params) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS\n    pub processed_params: Vec<Vec<String>>,\n    /// the processed outputs (eg. hash of the outputs) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS\n    pub processed_outputs: Vec<Vec<String>>,\n    /// the outputs as rescaled floats (if any) -- represented as a String for maximum compatibility with Python and JS\n    pub rescaled_outputs: Vec<Vec<String>>,\n    /// the outputs as felts but 0x strings (if any) -- represented as a String for maximum compatibility with Python and JS\n    pub outputs: Vec<Vec<String>>,\n}\n\n/// An application snark with proof and instance variables ready for aggregation (raw field element)\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct Snark<F: PrimeField + SerdeObject, C: CurveAffine>\nwhere\n    C::Scalar: Serialize + DeserializeOwned,\n    C::ScalarExt: Serialize + DeserializeOwned,\n{\n    /// the protocol\n    pub protocol: Option<PlonkProtocol<C>>,\n    /// public instances of the snark\n    pub instances: Vec<Vec<F>>,\n    /// the proof\n    pub proof: Vec<u8>,\n    /// hex encoded proof\n    pub hex_proof: Option<String>,\n    /// transcript type\n    pub transcript_type: TranscriptType,\n    /// the split proof\n    pub split: Option<ProofSplitCommit>,\n    /// the proof instances as rescaled floats\n    pub pretty_public_inputs: Option<PrettyElements>,\n    /// timestamp\n    pub timestamp: Option<u128>,\n    /// commitment\n    pub commitment: Option<Commitments>,\n}\n\n#[cfg(feature = \"python-bindings\")]\nuse pyo3::{types::PyDict, PyObject, Python, ToPyObject};\n#[cfg(feature = \"python-bindings\")]\nimpl<F: PrimeField + SerdeObject + Serialize, C: CurveAffine + Serialize> ToPyObject for Snark<F, C>\nwhere\n    C::Scalar: Serialize + DeserializeOwned,\n    C::ScalarExt: Serialize + DeserializeOwned,\n{\n    fn to_object(&self, py: Python) -> PyObject {\n        let dict = PyDict::new(py);\n        let field_elems: Vec<Vec<String>> = self\n            .instances\n            .iter()\n            .map(|x| x.iter().map(|fp| field_to_string(fp)).collect())\n            .collect::<Vec<_>>();\n        dict.set_item(\"instances\", field_elems).unwrap();\n        let hex_proof = hex::encode(&self.proof);\n        dict.set_item(\"proof\", format!(\"0x{}\", hex_proof)).unwrap();\n        dict.set_item(\"transcript_type\", self.transcript_type)\n            .unwrap();\n        dict.to_object(py)\n    }\n}\n\nimpl<\n        F: PrimeField + SerdeObject + Serialize + FromUniformBytes<64> + DeserializeOwned,\n        C: CurveAffine + Serialize + DeserializeOwned,\n    > Snark<F, C>\nwhere\n    C::Scalar: Serialize + DeserializeOwned,\n    C::ScalarExt: Serialize + DeserializeOwned,\n{\n    /// Create a new application snark from proof and instance variables ready for aggregation\n    pub fn new(\n        protocol: Option<PlonkProtocol<C>>,\n        instances: Vec<Vec<F>>,\n        proof: Vec<u8>,\n        hex_proof: Option<String>,\n        transcript_type: TranscriptType,\n        split: Option<ProofSplitCommit>,\n        pretty_public_inputs: Option<PrettyElements>,\n        commitment: Option<Commitments>,\n    ) -> Self {\n        Self {\n            protocol,\n            instances,\n            proof,\n            hex_proof,\n            transcript_type,\n            split,\n            pretty_public_inputs,\n            // unix timestamp\n            timestamp: Some(\n                instant::SystemTime::now()\n                    .duration_since(instant::SystemTime::UNIX_EPOCH)\n                    .unwrap()\n                    .as_millis(),\n            ),\n            commitment,\n        }\n    }\n\n    /// create hex proof from proof\n    pub fn create_hex_proof(&mut self) {\n        let hex_proof = hex::encode(&self.proof);\n        self.hex_proof = Some(format!(\"0x{}\", hex_proof));\n    }\n\n    /// Saves the Proof to a specified `proof_path`.\n    pub fn save(&self, proof_path: &PathBuf) -> Result<(), Box<dyn Error>> {\n        let file = std::fs::File::create(proof_path)?;\n        let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, file);\n        serde_json::to_writer(&mut writer, &self)?;\n        Ok(())\n    }\n\n    /// Load a json serialized proof from the provided path.\n    pub fn load<Scheme: CommitmentScheme<Curve = C, Scalar = F>>(\n        proof_path: &PathBuf,\n    ) -> Result<Self, Box<dyn Error>>\n    where\n        <C as CurveAffine>::ScalarExt: FromUniformBytes<64>,\n    {\n        trace!(\"reading proof\");\n        let file = std::fs::File::open(proof_path)?;\n        let reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, file);\n        let proof: Self = serde_json::from_reader(reader)?;\n        Ok(proof)\n    }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n/// A proof split commit\npub struct ProofSplitCommit {\n    /// The start index of the output in the witness\n    start: usize,\n    /// The end index of the output in the witness\n    end: usize,\n}\n\nimpl From<GraphWitness> for Option<ProofSplitCommit> {\n    fn from(witness: GraphWitness) -> Self {\n        let mut elem_offset = 0;\n\n        if let Some(input) = witness.processed_inputs {\n            if let Some(polycommit) = input.polycommit {\n                // flatten and count number of elements\n                let num_elements = polycommit\n                    .iter()\n                    .map(|polycommit| polycommit.len())\n                    .sum::<usize>();\n\n                elem_offset += num_elements;\n            }\n        }\n\n        if let Some(params) = witness.processed_params {\n            if let Some(polycommit) = params.polycommit {\n                // flatten and count number of elements\n                let num_elements = polycommit\n                    .iter()\n                    .map(|polycommit| polycommit.len())\n                    .sum::<usize>();\n\n                elem_offset += num_elements;\n            }\n        }\n\n        if let Some(output) = witness.processed_outputs {\n            if let Some(polycommit) = output.polycommit {\n                // flatten and count number of elements\n                let num_elements = polycommit\n                    .iter()\n                    .map(|polycommit| polycommit.len())\n                    .sum::<usize>();\n\n                Some(ProofSplitCommit {\n                    start: elem_offset,\n                    end: elem_offset + num_elements,\n                })\n            } else {\n                None\n            }\n        } else {\n            None\n        }\n    }\n}\n\n/// An application snark with proof and instance variables ready for aggregation (wrapped field element)\n#[derive(Clone, Debug)]\npub struct SnarkWitness<F: PrimeField, C: CurveAffine> {\n    protocol: Option<PlonkProtocol<C>>,\n    instances: Vec<Vec<Value<F>>>,\n    proof: Value<Vec<u8>>,\n    split: Option<ProofSplitCommit>,\n}\n\nimpl<F: PrimeField, C: CurveAffine> SnarkWitness<F, C> {\n    fn without_witnesses(&self) -> Self {\n        SnarkWitness {\n            protocol: self.protocol.clone(),\n            instances: self\n                .instances\n                .iter()\n                .map(|instances| vec![Value::unknown(); instances.len()])\n                .collect(),\n            proof: Value::unknown(),\n            split: self.split.clone(),\n        }\n    }\n\n    fn proof(&self) -> Value<&[u8]> {\n        self.proof.as_ref().map(Vec::as_slice)\n    }\n}\n\nimpl<F: PrimeField + SerdeObject, C: CurveAffine> From<Snark<F, C>> for SnarkWitness<F, C>\nwhere\n    C::Scalar: Serialize + DeserializeOwned,\n    C::ScalarExt: Serialize + DeserializeOwned,\n{\n    fn from(snark: Snark<F, C>) -> Self {\n        Self {\n            protocol: snark.protocol,\n            instances: snark\n                .instances\n                .into_iter()\n                .map(|instances| instances.into_iter().map(Value::known).collect())\n                .collect(),\n            proof: Value::known(snark.proof),\n            split: snark.split,\n        }\n    }\n}\n\n/// Creates a [VerifyingKey] and [ProvingKey] for a [crate::graph::GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`).\npub fn create_keys<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(\n    circuit: &C,\n    params: &'_ Scheme::ParamsProver,\n    disable_selector_compression: bool,\n) -> Result<ProvingKey<Scheme::Curve>, halo2_proofs::plonk::Error>\nwhere\n    C: Circuit<Scheme::Scalar>,\n    <Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,\n{\n    //\tReal proof\n    let empty_circuit = <C as Circuit<Scheme::Scalar>>::without_witnesses(circuit);\n\n    // Initialize verifying key\n    let now = Instant::now();\n    trace!(\"preparing VK\");\n    let vk = keygen_vk_custom(params, &empty_circuit, !disable_selector_compression)?;\n    let elapsed = now.elapsed();\n    info!(\"VK took {}.{}\", elapsed.as_secs(), elapsed.subsec_millis());\n\n    // Initialize the proving key\n    let now = Instant::now();\n    let pk = keygen_pk(params, vk, &empty_circuit)?;\n    let elapsed = now.elapsed();\n    info!(\"PK took {}.{}\", elapsed.as_secs(), elapsed.subsec_millis());\n    Ok(pk)\n}\n\n/// a wrapper around halo2's create_proof\n#[allow(clippy::too_many_arguments)]\npub fn create_proof_circuit<\n    'params,\n    Scheme: CommitmentScheme,\n    C: Circuit<Scheme::Scalar>,\n    P: Prover<'params, Scheme>,\n    V: Verifier<'params, Scheme>,\n    Strategy: VerificationStrategy<'params, Scheme, V>,\n    E: EncodedChallenge<Scheme::Curve>,\n    TW: TranscriptWriterBuffer<Vec<u8>, Scheme::Curve, E>,\n    TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>,\n>(\n    circuit: C,\n    instances: Vec<Vec<Scheme::Scalar>>,\n    params: &'params Scheme::ParamsProver,\n    pk: &ProvingKey<Scheme::Curve>,\n    check_mode: CheckMode,\n    commitment: Commitments,\n    transcript_type: TranscriptType,\n    split: Option<ProofSplitCommit>,\n    protocol: Option<PlonkProtocol<Scheme::Curve>>,\n) -> Result<Snark<Scheme::Scalar, Scheme::Curve>, Box<dyn Error>>\nwhere\n    Scheme::ParamsVerifier: 'params,\n    Scheme::Scalar: Serialize\n        + DeserializeOwned\n        + SerdeObject\n        + PrimeField\n        + FromUniformBytes<64>\n        + WithSmallOrderMulGroup<3>,\n    Scheme::Curve: Serialize + DeserializeOwned,\n{\n    let strategy = Strategy::new(params.verifier_params());\n    let mut transcript = TranscriptWriterBuffer::<_, Scheme::Curve, _>::init(vec![]);\n    #[cfg(feature = \"det-prove\")]\n    let mut rng = <StdRng as rand::SeedableRng>::from_seed([0u8; 32]);\n    #[cfg(not(feature = \"det-prove\"))]\n    let mut rng = OsRng;\n\n    let pi_inner = instances\n        .iter()\n        .map(|e| e.deref())\n        .collect::<Vec<&[Scheme::Scalar]>>();\n    let pi_inner: &[&[&[Scheme::Scalar]]] = &[&pi_inner];\n    trace!(\"instances {:?}\", instances);\n    trace!(\n        \"pk num instance column: {:?}\",\n        pk.get_vk().cs().num_instance_columns()\n    );\n\n    info!(\"proof started...\");\n    // not wasm32 unknown\n    let now = Instant::now();\n\n    create_proof::<Scheme, P, _, _, TW, _>(\n        params,\n        pk,\n        &[circuit],\n        pi_inner,\n        &mut rng,\n        &mut transcript,\n    )?;\n    let proof = transcript.finalize();\n    let hex_proof = format!(\"0x{}\", hex::encode(&proof));\n\n    let checkable_pf = Snark::new(\n        protocol,\n        instances,\n        proof,\n        Some(hex_proof),\n        transcript_type,\n        split,\n        None,\n        Some(commitment),\n    );\n\n    // sanity check that the generated proof is valid\n    if check_mode == CheckMode::SAFE {\n        debug!(\"verifying generated proof\");\n        let verifier_params = params.verifier_params();\n        verify_proof_circuit::<V, Scheme, Strategy, E, TR>(\n            &checkable_pf,\n            verifier_params,\n            pk.get_vk(),\n            strategy,\n            verifier_params.n(),\n        )?;\n    }\n    let elapsed = now.elapsed();\n    info!(\n        \"proof took {}.{}\",\n        elapsed.as_secs(),\n        elapsed.subsec_millis()\n    );\n\n    Ok(checkable_pf)\n}\n\n/// Swaps the proof commitments to a new set in the proof\npub fn swap_proof_commitments<\n    Scheme: CommitmentScheme,\n    E: EncodedChallenge<Scheme::Curve>,\n    TW: TranscriptWriterBuffer<Vec<u8>, Scheme::Curve, E>,\n>(\n    snark: &Snark<Scheme::Scalar, Scheme::Curve>,\n    commitments: &[Scheme::Curve],\n) -> Result<Snark<Scheme::Scalar, Scheme::Curve>, Box<dyn Error>>\nwhere\n    Scheme::Scalar: SerdeObject\n        + PrimeField\n        + FromUniformBytes<64>\n        + WithSmallOrderMulGroup<3>\n        + Ord\n        + Serialize\n        + DeserializeOwned,\n    Scheme::Curve: Serialize + DeserializeOwned,\n{\n    let mut transcript_new: TW = TranscriptWriterBuffer::<_, Scheme::Curve, _>::init(vec![]);\n\n    // polycommit commitments are the first set of points in the proof, this we'll always be the first set of advice\n    for commit in commitments {\n        transcript_new\n            .write_point(*commit)\n            .map_err(|_| \"failed to write point\")?;\n    }\n\n    let proof_first_bytes = transcript_new.finalize();\n\n    let mut snark_new = snark.clone();\n    // swap the proof bytes for the new ones\n    snark_new.proof[..proof_first_bytes.len()].copy_from_slice(&proof_first_bytes);\n    snark_new.create_hex_proof();\n\n    Ok(snark_new)\n}\n\n/// Swap the proof commitments to a new set in the proof for KZG\npub fn swap_proof_commitments_polycommit(\n    snark: &Snark<Fr, G1Affine>,\n    commitments: &[G1Affine],\n) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> {\n    let proof = match snark.commitment {\n        Some(Commitments::KZG) => match snark.transcript_type {\n            TranscriptType::EVM => swap_proof_commitments::<\n                KZGCommitmentScheme<Bn256>,\n                _,\n                EvmTranscript<G1Affine, _, _, _>,\n            >(snark, commitments)?,\n            TranscriptType::Poseidon => swap_proof_commitments::<\n                KZGCommitmentScheme<Bn256>,\n                _,\n                PoseidonTranscript<NativeLoader, _>,\n            >(snark, commitments)?,\n        },\n        Some(Commitments::IPA) => match snark.transcript_type {\n            TranscriptType::EVM => swap_proof_commitments::<\n                IPACommitmentScheme<G1Affine>,\n                _,\n                EvmTranscript<G1Affine, _, _, _>,\n            >(snark, commitments)?,\n            TranscriptType::Poseidon => swap_proof_commitments::<\n                IPACommitmentScheme<G1Affine>,\n                _,\n                PoseidonTranscript<NativeLoader, _>,\n            >(snark, commitments)?,\n        },\n        None => {\n            return Err(\"commitment scheme not found\".into());\n        }\n    };\n\n    Ok(proof)\n}\n\n/// A wrapper around halo2's verify_proof\npub fn verify_proof_circuit<\n    'params,\n    V: Verifier<'params, Scheme>,\n    Scheme: CommitmentScheme,\n    Strategy: VerificationStrategy<'params, Scheme, V>,\n    E: EncodedChallenge<Scheme::Curve>,\n    TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>,\n>(\n    snark: &Snark<Scheme::Scalar, Scheme::Curve>,\n    params: &'params Scheme::ParamsVerifier,\n    vk: &VerifyingKey<Scheme::Curve>,\n    strategy: Strategy,\n    orig_n: u64,\n) -> Result<Strategy::Output, halo2_proofs::plonk::Error>\nwhere\n    Scheme::Scalar: SerdeObject\n        + PrimeField\n        + FromUniformBytes<64>\n        + WithSmallOrderMulGroup<3>\n        + Serialize\n        + DeserializeOwned,\n    Scheme::Curve: Serialize + DeserializeOwned,\n{\n    let pi_inner = snark\n        .instances\n        .iter()\n        .map(|e| e.deref())\n        .collect::<Vec<&[Scheme::Scalar]>>();\n    let instances: &[&[&[Scheme::Scalar]]] = &[&pi_inner];\n    trace!(\"instances {:?}\", instances);\n\n    let mut transcript = TranscriptReadBuffer::init(Cursor::new(snark.proof.clone()));\n    verify_proof::<Scheme, V, _, TR, _>(params, vk, strategy, instances, &mut transcript, orig_n)\n}\n\n/// Loads a [VerifyingKey] at `path`.\npub fn load_vk<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(\n    path: PathBuf,\n    params: <C as Circuit<Scheme::Scalar>>::Params,\n) -> Result<VerifyingKey<Scheme::Curve>, Box<dyn Error>>\nwhere\n    C: Circuit<Scheme::Scalar>,\n    Scheme::Curve: SerdeObject + CurveAffine,\n    Scheme::Scalar: PrimeField + SerdeObject + FromUniformBytes<64>,\n{\n    info!(\"loading verification key from {:?}\", path);\n    let f =\n        File::open(path.clone()).map_err(|_| format!(\"failed to load vk at {}\", path.display()))?;\n    let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, f);\n    let vk = VerifyingKey::<Scheme::Curve>::read::<_, C>(\n        &mut reader,\n        serde_format_from_str(&EZKL_KEY_FORMAT),\n        params,\n    )?;\n    info!(\"done loading verification key \u2705\");\n    Ok(vk)\n}\n\n/// Loads a [ProvingKey] at `path`.\npub fn load_pk<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(\n    path: PathBuf,\n    params: <C as Circuit<Scheme::Scalar>>::Params,\n) -> Result<ProvingKey<Scheme::Curve>, Box<dyn Error>>\nwhere\n    C: Circuit<Scheme::Scalar>,\n    Scheme::Curve: SerdeObject + CurveAffine,\n    Scheme::Scalar: PrimeField + SerdeObject + FromUniformBytes<64>,\n{\n    info!(\"loading proving key from {:?}\", path);\n    let f =\n        File::open(path.clone()).map_err(|_| format!(\"failed to load pk at {}\", path.display()))?;\n    let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, f);\n    let pk = ProvingKey::<Scheme::Curve>::read::<_, C>(\n        &mut reader,\n        serde_format_from_str(&EZKL_KEY_FORMAT),\n        params,\n    )?;\n    info!(\"done loading proving key \u2705\");\n    Ok(pk)\n}\n\n/// Saves a [ProvingKey] to `path`.\npub fn save_pk<C: SerdeObject + CurveAffine>(\n    path: &PathBuf,\n    pk: &ProvingKey<C>,\n) -> Result<(), io::Error>\nwhere\n    C::ScalarExt: FromUniformBytes<64> + SerdeObject,\n{\n    info!(\"saving proving key \ud83d\udcbe\");\n    let f = File::create(path)?;\n    let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);\n    pk.write(&mut writer, serde_format_from_str(&EZKL_KEY_FORMAT))?;\n    writer.flush()?;\n    info!(\"done saving proving key \u2705\");\n    Ok(())\n}\n\n/// Saves a [VerifyingKey] to `path`.\npub fn save_vk<C: CurveAffine + SerdeObject>(\n    path: &PathBuf,\n    vk: &VerifyingKey<C>,\n) -> Result<(), io::Error>\nwhere\n    C::ScalarExt: FromUniformBytes<64> + SerdeObject,\n{\n    info!(\"saving verification key \ud83d\udcbe\");\n    let f = File::create(path)?;\n    let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);\n    vk.write(&mut writer, serde_format_from_str(&EZKL_KEY_FORMAT))?;\n    writer.flush()?;\n    info!(\"done saving verification key \u2705\");\n    Ok(())\n}\n\n/// Saves [CommitmentScheme] parameters to `path`.\npub fn save_params<Scheme: CommitmentScheme>(\n    path: &PathBuf,\n    params: &'_ Scheme::ParamsVerifier,\n) -> Result<(), io::Error> {\n    info!(\"saving parameters \ud83d\udcbe\");\n    let f = File::create(path)?;\n    let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);\n    params.write(&mut writer)?;\n    writer.flush()?;\n    Ok(())\n}\n\n////////////////////////\n\n#[cfg(test)]\n#[cfg(not(target_arch = \"wasm32\"))]\nmod tests {\n\n    use super::*;\n    use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\n    use halo2curves::bn256::{Bn256, Fr, G1Affine};\n    use tempfile::Builder;\n\n    #[tokio::test]\n    async fn test_can_load_saved_srs() {\n        let tmp_dir = Builder::new().prefix(\"example\").tempdir().unwrap();\n        let fname = tmp_dir.path().join(\"polycommit.params\");\n        let srs = srs::gen_srs::<KZGCommitmentScheme<Bn256>>(1);\n        let res = save_params::<KZGCommitmentScheme<Bn256>>(&fname, &srs);\n        assert!(res.is_ok());\n        let res = srs::load_srs_prover::<KZGCommitmentScheme<Bn256>>(fname);\n        assert!(res.is_ok())\n    }\n\n    #[test]\n    fn test_snark_serialization_roundtrip() {\n        let snark = Snark::<Fr, G1Affine> {\n            proof: vec![1, 2, 3, 4, 5, 6, 7, 8],\n            instances: vec![vec![Fr::from(1)], vec![Fr::from(2)]],\n            transcript_type: TranscriptType::EVM,\n            protocol: None,\n            hex_proof: None,\n            split: None,\n            pretty_public_inputs: None,\n            timestamp: None,\n            commitment: None,\n        };\n\n        snark\n            .save(&\"test_snark_serialization_roundtrip.json\".into())\n            .unwrap();\n        let snark2 = Snark::<Fr, G1Affine>::load::<KZGCommitmentScheme<Bn256>>(\n            &\"test_snark_serialization_roundtrip.json\".into(),\n        )\n        .unwrap();\n        assert_eq!(snark.instances, snark2.instances);\n        assert_eq!(snark.proof, snark2.proof);\n        assert_eq!(snark.transcript_type, snark2.transcript_type);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/pfsys/srs.rs",
        "content": "use halo2_proofs::poly::commitment::CommitmentScheme;\nuse halo2_proofs::poly::commitment::Params;\nuse halo2_proofs::poly::commitment::ParamsProver;\nuse log::info;\nuse std::error::Error;\nuse std::fs::File;\nuse std::io::BufReader;\nuse std::path::PathBuf;\n\n/// for now we use the urls of the powers of tau ceremony from <https://github.com/han0110/halo2-kzg-srs>\npub const PUBLIC_SRS_URL: &str =\n    \"https://trusted-setup-halo2kzg.s3.eu-central-1.amazonaws.com/perpetual-powers-of-tau-raw-\";\n\n/// Helper function for generating SRS. Only use for testing\npub fn gen_srs<Scheme: CommitmentScheme>(k: u32) -> Scheme::ParamsProver {\n    Scheme::ParamsProver::new(k)\n}\n\n/// Loads the [CommitmentScheme::ParamsVerifier] at `path`.\npub fn load_srs_verifier<Scheme: CommitmentScheme>(\n    path: PathBuf,\n) -> Result<Scheme::ParamsVerifier, Box<dyn Error>> {\n    info!(\"loading srs from {:?}\", path);\n    let f = File::open(path.clone())\n        .map_err(|_| format!(\"failed to load srs at {}\", path.display()))?;\n    let mut reader = BufReader::new(f);\n    Params::<'_, Scheme::Curve>::read(&mut reader).map_err(Box::<dyn Error>::from)\n}\n\n/// Loads the [CommitmentScheme::ParamsVerifier] at `path`.\npub fn load_srs_prover<Scheme: CommitmentScheme>(\n    path: PathBuf,\n) -> Result<Scheme::ParamsProver, Box<dyn Error>> {\n    info!(\"loading srs from {:?}\", path);\n    let f = File::open(path.clone())\n        .map_err(|_| format!(\"failed to load srs at {}\", path.display()))?;\n    let mut reader = BufReader::new(f);\n    Params::<'_, Scheme::Curve>::read(&mut reader).map_err(Box::<dyn Error>::from)\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/python.rs",
        "content": "use crate::circuit::modules::polycommit::PolyCommitChip;\nuse crate::circuit::modules::poseidon::{\n    spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH},\n    PoseidonChip,\n};\nuse crate::circuit::modules::Module;\nuse crate::circuit::{CheckMode, Tolerance};\nuse crate::commands::*;\nuse crate::fieldutils::{felt_to_i128, i128_to_felt};\nuse crate::graph::modules::POSEIDON_LEN_GRAPH;\nuse crate::graph::TestDataSource;\nuse crate::graph::{\n    quantize_float, scale_to_multiplier, GraphCircuit, GraphSettings, Model, Visibility,\n};\nuse crate::pfsys::evm::aggregation_kzg::AggregationCircuit;\nuse crate::pfsys::{\n    load_pk, load_vk, save_params, save_vk, srs::gen_srs as ezkl_gen_srs, srs::load_srs_prover,\n    ProofType, TranscriptType,\n};\nuse crate::Commitments;\nuse crate::RunArgs;\nuse halo2_proofs::poly::ipa::commitment::IPACommitmentScheme;\nuse halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\nuse halo2curves::bn256::{Bn256, Fq, Fr, G1Affine, G1};\nuse pyo3::exceptions::{PyIOError, PyRuntimeError};\nuse pyo3::prelude::*;\nuse pyo3::wrap_pyfunction;\nuse pyo3_log;\nuse snark_verifier::util::arithmetic::PrimeField;\nuse std::str::FromStr;\nuse std::{fs::File, path::PathBuf};\nuse tokio::runtime::Runtime;\n\ntype PyFelt = String;\n\n/// pyclass representing an enum\n#[pyclass]\n#[derive(Debug, Clone)]\nenum PyTestDataSource {\n    /// The data is loaded from a file\n    File,\n    /// The data is loaded from the chain\n    OnChain,\n}\n\nimpl From<PyTestDataSource> for TestDataSource {\n    fn from(py_test_data_source: PyTestDataSource) -> Self {\n        match py_test_data_source {\n            PyTestDataSource::File => TestDataSource::File,\n            PyTestDataSource::OnChain => TestDataSource::OnChain,\n        }\n    }\n}\n\n/// pyclass containing the struct used for G1, this is mostly a helper class\n#[pyclass]\n#[derive(Debug, Clone)]\nstruct PyG1 {\n    #[pyo3(get, set)]\n    /// Field Element representing x\n    x: PyFelt,\n    #[pyo3(get, set)]\n    /// Field Element representing y\n    y: PyFelt,\n    /// Field Element representing y\n    #[pyo3(get, set)]\n    z: PyFelt,\n}\n\nimpl From<G1> for PyG1 {\n    fn from(g1: G1) -> Self {\n        PyG1 {\n            x: crate::pfsys::field_to_string::<Fq>(&g1.x),\n            y: crate::pfsys::field_to_string::<Fq>(&g1.y),\n            z: crate::pfsys::field_to_string::<Fq>(&g1.z),\n        }\n    }\n}\n\nimpl From<PyG1> for G1 {\n    fn from(val: PyG1) -> Self {\n        G1 {\n            x: crate::pfsys::string_to_field::<Fq>(&val.x),\n            y: crate::pfsys::string_to_field::<Fq>(&val.y),\n            z: crate::pfsys::string_to_field::<Fq>(&val.z),\n        }\n    }\n}\n\nimpl pyo3::ToPyObject for PyG1 {\n    fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {\n        let g1_dict = pyo3::types::PyDict::new(py);\n\n        g1_dict.set_item(\"x\", self.x.to_object(py)).unwrap();\n        g1_dict.set_item(\"y\", self.y.to_object(py)).unwrap();\n        g1_dict.set_item(\"z\", self.z.to_object(py)).unwrap();\n        g1_dict.into()\n    }\n}\n\n/// pyclass containing the struct used for G1\n#[pyclass]\n#[derive(Debug, Clone)]\npub struct PyG1Affine {\n    #[pyo3(get, set)]\n    ///\n    pub x: PyFelt,\n    #[pyo3(get, set)]\n    ///\n    pub y: PyFelt,\n}\n\nimpl From<G1Affine> for PyG1Affine {\n    fn from(g1: G1Affine) -> Self {\n        PyG1Affine {\n            x: crate::pfsys::field_to_string::<Fq>(&g1.x),\n            y: crate::pfsys::field_to_string::<Fq>(&g1.y),\n        }\n    }\n}\n\nimpl From<PyG1Affine> for G1Affine {\n    fn from(val: PyG1Affine) -> Self {\n        G1Affine {\n            x: crate::pfsys::string_to_field::<Fq>(&val.x),\n            y: crate::pfsys::string_to_field::<Fq>(&val.y),\n        }\n    }\n}\n\nimpl pyo3::ToPyObject for PyG1Affine {\n    fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {\n        let g1_dict = pyo3::types::PyDict::new(py);\n\n        g1_dict.set_item(\"x\", self.x.to_object(py)).unwrap();\n        g1_dict.set_item(\"y\", self.y.to_object(py)).unwrap();\n        g1_dict.into()\n    }\n}\n\n/// Python class containing the struct used for run_args\n///\n/// Returns\n/// -------\n/// PyRunArgs\n///\n#[pyclass]\n#[derive(Clone)]\nstruct PyRunArgs {\n    #[pyo3(get, set)]\n    /// float: The tolerance for error on model outputs\n    pub tolerance: f32,\n    #[pyo3(get, set)]\n    /// int: The denominator in the fixed point representation used when quantizing inputs\n    pub input_scale: crate::Scale,\n    #[pyo3(get, set)]\n    /// int:  The denominator in the fixed point representation used when quantizing parameters\n    pub param_scale: crate::Scale,\n    #[pyo3(get, set)]\n    /// int: If the scale is ever > scale_rebase_multiplier * input_scale then the scale is rebased to input_scale (this a more advanced parameter, use with caution)\n    pub scale_rebase_multiplier: u32,\n    #[pyo3(get, set)]\n    /// list[int]: The min and max elements in the lookup table input column\n    pub lookup_range: crate::circuit::table::Range,\n    #[pyo3(get, set)]\n    /// int: The log_2 number of rows\n    pub logrows: u32,\n    #[pyo3(get, set)]\n    /// int: The number of inner columns used for the lookup table\n    pub num_inner_cols: usize,\n    #[pyo3(get, set)]\n    /// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`\n    pub input_visibility: Visibility,\n    #[pyo3(get, set)]\n    /// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`\n    pub output_visibility: Visibility,\n    #[pyo3(get, set)]\n    /// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`\n    pub param_visibility: Visibility,\n    #[pyo3(get, set)]\n    /// list[tuple[str, int]]: Hand-written parser for graph variables, eg. batch_size=1\n    pub variables: Vec<(String, usize)>,\n    #[pyo3(get, set)]\n    /// bool: Rebase the scale using lookup table for division instead of using a range check\n    pub div_rebasing: bool,\n    #[pyo3(get, set)]\n    /// bool: Should constants with 0.0 fraction be rebased to scale 0\n    pub rebase_frac_zero_constants: bool,\n    #[pyo3(get, set)]\n    /// str: check mode, accepts `safe`, `unsafe`\n    pub check_mode: CheckMode,\n    #[pyo3(get, set)]\n    /// str: commitment type, accepts `kzg`, `ipa`\n    pub commitment: PyCommitments,\n}\n\n/// default instantiation of PyRunArgs\n#[pymethods]\nimpl PyRunArgs {\n    #[new]\n    fn new() -> Self {\n        RunArgs::default().into()\n    }\n}\n\n/// Conversion between PyRunArgs and RunArgs\nimpl From<PyRunArgs> for RunArgs {\n    fn from(py_run_args: PyRunArgs) -> Self {\n        RunArgs {\n            tolerance: Tolerance::from(py_run_args.tolerance),\n            input_scale: py_run_args.input_scale,\n            param_scale: py_run_args.param_scale,\n            num_inner_cols: py_run_args.num_inner_cols,\n            scale_rebase_multiplier: py_run_args.scale_rebase_multiplier,\n            lookup_range: py_run_args.lookup_range,\n            logrows: py_run_args.logrows,\n            input_visibility: py_run_args.input_visibility,\n            output_visibility: py_run_args.output_visibility,\n            param_visibility: py_run_args.param_visibility,\n            variables: py_run_args.variables,\n            div_rebasing: py_run_args.div_rebasing,\n            rebase_frac_zero_constants: py_run_args.rebase_frac_zero_constants,\n            check_mode: py_run_args.check_mode,\n            commitment: Some(py_run_args.commitment.into()),\n        }\n    }\n}\n\nimpl Into<PyRunArgs> for RunArgs {\n    fn into(self) -> PyRunArgs {\n        PyRunArgs {\n            tolerance: self.tolerance.val,\n            input_scale: self.input_scale,\n            param_scale: self.param_scale,\n            num_inner_cols: self.num_inner_cols,\n            scale_rebase_multiplier: self.scale_rebase_multiplier,\n            lookup_range: self.lookup_range,\n            logrows: self.logrows,\n            input_visibility: self.input_visibility,\n            output_visibility: self.output_visibility,\n            param_visibility: self.param_visibility,\n            variables: self.variables,\n            div_rebasing: self.div_rebasing,\n            rebase_frac_zero_constants: self.rebase_frac_zero_constants,\n            check_mode: self.check_mode,\n            commitment: self.commitment.into(),\n        }\n    }\n}\n\n#[pyclass]\n#[derive(Debug, Clone)]\n/// pyclass representing an enum, denoting the type of commitment\npub enum PyCommitments {\n    /// KZG commitment\n    KZG,\n    /// IPA commitment\n    IPA,\n}\n\nimpl From<Option<Commitments>> for PyCommitments {\n    fn from(commitment: Option<Commitments>) -> Self {\n        match commitment {\n            Some(Commitments::KZG) => PyCommitments::KZG,\n            Some(Commitments::IPA) => PyCommitments::IPA,\n            None => PyCommitments::KZG,\n        }\n    }\n}\n\nimpl From<PyCommitments> for Commitments {\n    fn from(py_commitments: PyCommitments) -> Self {\n        match py_commitments {\n            PyCommitments::KZG => Commitments::KZG,\n            PyCommitments::IPA => Commitments::IPA,\n        }\n    }\n}\n\nimpl Into<PyCommitments> for Commitments {\n    fn into(self) -> PyCommitments {\n        match self {\n            Commitments::KZG => PyCommitments::KZG,\n            Commitments::IPA => PyCommitments::IPA,\n        }\n    }\n}\n\nimpl FromStr for PyCommitments {\n    type Err = String;\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        match s.to_lowercase().as_str() {\n            \"kzg\" => Ok(PyCommitments::KZG),\n            \"ipa\" => Ok(PyCommitments::IPA),\n            _ => Err(\"Invalid value for Commitments\".to_string()),\n        }\n    }\n}\n\n/// Converts a field element hex string to big endian\n///\n/// Arguments\n/// -------\n/// felt: str\n///     The field element represented as a string\n///\n///\n/// Returns\n/// -------\n/// str\n///     field element represented as a string\n///\n#[pyfunction(signature = (\n    felt,\n))]\nfn felt_to_big_endian(felt: PyFelt) -> PyResult<String> {\n    let felt = crate::pfsys::string_to_field::<Fr>(&felt);\n    Ok(format!(\"{:?}\", felt))\n}\n\n/// Converts a field element hex string to an integer\n///\n/// Arguments\n/// -------\n/// felt: str\n///     The field element represented as a string\n///\n/// Returns\n/// -------\n/// int\n///\n#[pyfunction(signature = (\n    felt,\n))]\nfn felt_to_int(felt: PyFelt) -> PyResult<i128> {\n    let felt = crate::pfsys::string_to_field::<Fr>(&felt);\n    let int_rep = felt_to_i128(felt);\n    Ok(int_rep)\n}\n\n/// Converts a field element hex string to a floating point number\n///\n/// Arguments\n/// -------\n/// felt: str\n///    The field element represented as a string\n///\n/// scale: float\n///     The scaling factor used to convert the field element into a floating point representation\n///\n/// Returns\n/// -------\n/// float\n///\n#[pyfunction(signature = (\n    felt,\n    scale\n))]\nfn felt_to_float(felt: PyFelt, scale: crate::Scale) -> PyResult<f64> {\n    let felt = crate::pfsys::string_to_field::<Fr>(&felt);\n    let int_rep = felt_to_i128(felt);\n    let multiplier = scale_to_multiplier(scale);\n    let float_rep = int_rep as f64 / multiplier;\n    Ok(float_rep)\n}\n\n/// Converts a floating point element to a field element hex string\n///\n/// Arguments\n/// -------\n/// input: float\n///    The field element represented as a string\n///\n/// scale: float\n///     The scaling factor used to quantize the float into a field element\n///\n/// Returns\n/// -------\n/// str\n///     The field element represented as a string\n///\n#[pyfunction(signature = (\n    input,\n    scale\n))]\nfn float_to_felt(input: f64, scale: crate::Scale) -> PyResult<PyFelt> {\n    let int_rep = quantize_float(&input, 0.0, scale)\n        .map_err(|_| PyIOError::new_err(\"Failed to quantize input\"))?;\n    let felt = i128_to_felt(int_rep);\n    Ok(crate::pfsys::field_to_string::<Fr>(&felt))\n}\n\n/// Converts a buffer to vector of field elements\n///\n/// Arguments\n/// -------\n/// buffer: list[int]\n///     List of integers representing a buffer\n///\n/// Returns\n/// -------\n/// list[str]\n///     List of field elements represented as strings\n///\n#[pyfunction(signature = (\n    buffer\n))]\nfn buffer_to_felts(buffer: Vec<u8>) -> PyResult<Vec<String>> {\n    fn u8_array_to_u128_le(arr: [u8; 16]) -> u128 {\n        let mut n: u128 = 0;\n        for &b in arr.iter().rev() {\n            n <<= 8;\n            n |= b as u128;\n        }\n        n\n    }\n\n    let buffer = &buffer[..];\n\n    // Divide the buffer into chunks of 64 bytes\n    let chunks = buffer.chunks_exact(16);\n\n    // Get the remainder\n    let remainder = chunks.remainder();\n\n    // Add 0s to the remainder to make it 64 bytes\n    let mut remainder = remainder.to_vec();\n\n    // Collect chunks into a Vec<[u8; 16]>.\n    let chunks: Result<Vec<[u8; 16]>, PyErr> = chunks\n        .map(|slice| {\n            let array: [u8; 16] = slice\n                .try_into()\n                .map_err(|_| PyIOError::new_err(\"Failed to slice input buffer\"))?;\n            Ok(array)\n        })\n        .collect();\n\n    let mut chunks = chunks?;\n\n    if !remainder.is_empty() {\n        remainder.resize(16, 0);\n        // Convert the Vec<u8> to [u8; 16]\n        let remainder_array: [u8; 16] = remainder\n            .try_into()\n            .map_err(|_| PyIOError::new_err(\"Failed to slice remainder\"))?;\n        // append the remainder to the chunks\n        chunks.push(remainder_array);\n    }\n\n    // Convert each chunk to a field element\n    let field_elements: Vec<Fr> = chunks\n        .iter()\n        .map(|x| PrimeField::from_u128(u8_array_to_u128_le(*x)))\n        .collect();\n\n    let field_elements: Vec<String> = field_elements\n        .iter()\n        .map(|x| crate::pfsys::field_to_string::<Fr>(x))\n        .collect();\n\n    Ok(field_elements)\n}\n\n/// Generate a poseidon hash.\n///\n/// Arguments\n/// -------\n/// message: list[str]\n///     List of field elements represnted as strings\n///\n/// Returns\n/// -------\n/// list[str]\n///     List of field elements represented as strings\n///\n#[pyfunction(signature = (\n    message,\n))]\nfn poseidon_hash(message: Vec<PyFelt>) -> PyResult<Vec<PyFelt>> {\n    let message: Vec<Fr> = message\n        .iter()\n        .map(crate::pfsys::string_to_field::<Fr>)\n        .collect::<Vec<_>>();\n\n    let output =\n        PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(\n            message.clone(),\n        )\n        .map_err(|_| PyIOError::new_err(\"Failed to run poseidon\"))?;\n\n    let hash = output[0]\n        .iter()\n        .map(crate::pfsys::field_to_string::<Fr>)\n        .collect::<Vec<_>>();\n    Ok(hash)\n}\n\n/// Generate a kzg commitment.\n///\n/// Arguments\n/// -------\n/// message: list[str]\n///     List of field elements represnted as strings\n///\n/// vk_path: str\n///     Path to the verification key\n///\n/// settings_path: str\n///     Path to the settings file\n///\n/// srs_path: str\n///     Path to the Structure Reference String (SRS) file\n///\n/// Returns\n/// -------\n/// list[PyG1Affine]\n///\n#[pyfunction(signature = (\n    message,\n    vk_path=PathBuf::from(DEFAULT_VK),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    srs_path=None\n))]\nfn kzg_commit(\n    message: Vec<PyFelt>,\n    vk_path: PathBuf,\n    settings_path: PathBuf,\n    srs_path: Option<PathBuf>,\n) -> PyResult<Vec<PyG1Affine>> {\n    let message: Vec<Fr> = message\n        .iter()\n        .map(crate::pfsys::string_to_field::<Fr>)\n        .collect::<Vec<_>>();\n\n    let settings = GraphSettings::load(&settings_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to load circuit settings\"))?;\n\n    let srs_path =\n        crate::execute::get_srs_path(settings.run_args.logrows, srs_path, Commitments::KZG);\n\n    let srs = load_srs_prover::<KZGCommitmentScheme<Bn256>>(srs_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to load srs\"))?;\n\n    let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)\n        .map_err(|_| PyIOError::new_err(\"Failed to load vk\"))?;\n\n    let output = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(\n        message,\n        (vk.cs().blinding_factors() + 1) as u32,\n        &srs,\n    );\n\n    Ok(output.iter().map(|x| (*x).into()).collect::<Vec<_>>())\n}\n\n/// Generate an ipa commitment.\n///\n/// Arguments\n/// -------\n/// message: list[str]\n///     List of field elements represnted as strings\n///\n/// vk_path: str\n///     Path to the verification key\n///\n/// settings_path: str\n///     Path to the settings file\n///\n/// srs_path: str\n///     Path to the Structure Reference String (SRS) file\n///\n/// Returns\n/// -------\n/// list[PyG1Affine]\n///\n#[pyfunction(signature = (\n    message,\n    vk_path=PathBuf::from(DEFAULT_VK),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    srs_path=None\n))]\nfn ipa_commit(\n    message: Vec<PyFelt>,\n    vk_path: PathBuf,\n    settings_path: PathBuf,\n    srs_path: Option<PathBuf>,\n) -> PyResult<Vec<PyG1Affine>> {\n    let message: Vec<Fr> = message\n        .iter()\n        .map(crate::pfsys::string_to_field::<Fr>)\n        .collect::<Vec<_>>();\n\n    let settings = GraphSettings::load(&settings_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to load circuit settings\"))?;\n\n    let srs_path =\n        crate::execute::get_srs_path(settings.run_args.logrows, srs_path, Commitments::KZG);\n\n    let srs = load_srs_prover::<IPACommitmentScheme<G1Affine>>(srs_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to load srs\"))?;\n\n    let vk = load_vk::<IPACommitmentScheme<G1Affine>, GraphCircuit>(vk_path, settings)\n        .map_err(|_| PyIOError::new_err(\"Failed to load vk\"))?;\n\n    let output = PolyCommitChip::commit::<IPACommitmentScheme<G1Affine>>(\n        message,\n        (vk.cs().blinding_factors() + 1) as u32,\n        &srs,\n    );\n\n    Ok(output.iter().map(|x| (*x).into()).collect::<Vec<_>>())\n}\n\n/// Swap the commitments in a proof\n///\n/// Arguments\n/// -------\n/// proof_path: str\n///     Path to the proof file\n///\n/// witness_path: str\n///     Path to the witness file\n///\n#[pyfunction(signature = (\n    proof_path=PathBuf::from(DEFAULT_PROOF),\n    witness_path=PathBuf::from(DEFAULT_WITNESS),\n))]\nfn swap_proof_commitments(proof_path: PathBuf, witness_path: PathBuf) -> PyResult<()> {\n    crate::execute::swap_proof_commitments_cmd(proof_path, witness_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to swap commitments\"))?;\n\n    Ok(())\n}\n\n/// Generates a vk from a pk for a model circuit and saves it to a file\n///\n/// Arguments\n/// -------\n/// path_to_pk: str\n///     Path to the proving key\n///\n/// circuit_settings_path: str\n///     Path to the witness file\n///\n/// vk_output_path: str\n///     Path to create the vk file\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    path_to_pk=PathBuf::from(DEFAULT_PK),\n    circuit_settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    vk_output_path=PathBuf::from(DEFAULT_VK),\n))]\nfn gen_vk_from_pk_single(\n    path_to_pk: PathBuf,\n    circuit_settings_path: PathBuf,\n    vk_output_path: PathBuf,\n) -> PyResult<bool> {\n    let settings = GraphSettings::load(&circuit_settings_path)\n        .map_err(|_| PyIOError::new_err(\"Failed to load circuit settings\"))?;\n\n    let pk = load_pk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(path_to_pk, settings)\n        .map_err(|_| PyIOError::new_err(\"Failed to load pk\"))?;\n\n    let vk = pk.get_vk();\n\n    // now save\n    save_vk::<G1Affine>(&vk_output_path, vk)\n        .map_err(|_| PyIOError::new_err(\"Failed to save vk\"))?;\n\n    Ok(true)\n}\n\n/// Generates a vk from a pk for an aggregate circuit and saves it to a file\n///\n/// Arguments\n/// -------\n/// path_to_pk: str\n///     Path to the proving key\n///\n/// vk_output_path: str\n///     Path to create the vk file\n///\n/// Returns\n/// -------\n/// bool\n#[pyfunction(signature = (\n    path_to_pk=PathBuf::from(DEFAULT_PK_AGGREGATED),\n    vk_output_path=PathBuf::from(DEFAULT_VK_AGGREGATED),\n))]\nfn gen_vk_from_pk_aggr(path_to_pk: PathBuf, vk_output_path: PathBuf) -> PyResult<bool> {\n    let pk = load_pk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(path_to_pk, ())\n        .map_err(|_| PyIOError::new_err(\"Failed to load pk\"))?;\n\n    let vk = pk.get_vk();\n\n    // now save\n    save_vk::<G1Affine>(&vk_output_path, vk)\n        .map_err(|_| PyIOError::new_err(\"Failed to save vk\"))?;\n\n    Ok(true)\n}\n\n/// Displays the table as a string in python\n///\n/// Arguments\n/// ---------\n/// model: str\n///     Path to the onnx file\n///\n/// Returns\n/// ---------\n/// str\n///     Table of the nodes in the onnx file\n///\n#[pyfunction(signature = (\n    model = PathBuf::from(DEFAULT_MODEL),\n    py_run_args = None\n))]\nfn table(model: PathBuf, py_run_args: Option<PyRunArgs>) -> PyResult<String> {\n    let run_args: RunArgs = py_run_args.unwrap_or_else(PyRunArgs::new).into();\n    let mut reader = File::open(model).map_err(|_| PyIOError::new_err(\"Failed to open model\"))?;\n    let result = Model::new(&mut reader, &run_args);\n\n    match result {\n        Ok(m) => Ok(m.table_nodes()),\n        Err(_) => Err(PyIOError::new_err(\"Failed to import model\")),\n    }\n}\n\n/// Generates the Structured Reference String (SRS), use this only for testing purposes\n///\n/// Arguments\n/// ---------\n/// srs_path: str\n///     Path to the create the SRS file\n///\n/// logrows: int\n///     The number of logrows for the SRS file\n///\n#[pyfunction(signature = (\n    srs_path,\n    logrows,\n))]\nfn gen_srs(srs_path: PathBuf, logrows: usize) -> PyResult<()> {\n    let params = ezkl_gen_srs::<KZGCommitmentScheme<Bn256>>(logrows as u32);\n    save_params::<KZGCommitmentScheme<Bn256>>(&srs_path, &params)?;\n    Ok(())\n}\n\n/// Gets a public srs\n///\n/// Arguments\n/// ---------\n/// settings_path: str\n///     Path to the settings file\n///\n/// logrows: int\n///     The number of logrows for the SRS file\n///\n/// srs_path: str\n///     Path to the create the SRS file\n///\n/// commitment: str\n///     Specify the commitment used (\"kzg\", \"ipa\")\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    logrows=None,\n    srs_path=None,\n    commitment=None,\n))]\nfn get_srs(\n    settings_path: Option<PathBuf>,\n    logrows: Option<u32>,\n    srs_path: Option<PathBuf>,\n    commitment: Option<PyCommitments>,\n) -> PyResult<bool> {\n    let commitment: Option<Commitments> = match commitment {\n        Some(c) => Some(c.into()),\n        None => None,\n    };\n\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::get_srs_cmd(\n            srs_path,\n            settings_path,\n            logrows,\n            commitment,\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to get srs: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n    Ok(true)\n}\n\n/// Generates the circuit settings\n///\n/// Arguments\n/// ---------\n/// model: str\n///     Path to the onnx file\n///\n/// output: str\n///     Path to create the settings file\n///\n/// py_run_args: PyRunArgs\n///     PyRunArgs object to initialize the settings\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    model=PathBuf::from(DEFAULT_MODEL),\n    output=PathBuf::from(DEFAULT_SETTINGS),\n    py_run_args = None,\n))]\nfn gen_settings(\n    model: PathBuf,\n    output: PathBuf,\n    py_run_args: Option<PyRunArgs>,\n) -> Result<bool, PyErr> {\n    let run_args: RunArgs = py_run_args.unwrap_or_else(PyRunArgs::new).into();\n\n    crate::execute::gen_circuit_settings(model, output, run_args).map_err(|e| {\n        let err_str = format!(\"Failed to generate settings: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Calibrates the circuit settings\n///\n/// Arguments\n/// ---------\n/// data: str\n///     Path to the calibration data\n///\n/// model: str\n///     Path to the onnx file\n///\n/// settings: str\n///     Path to the settings file\n///\n/// lookup_safety_margin: int\n///      the lookup safety margin to use for calibration. if the max lookup is 2^k, then the max lookup will be 2^k * lookup_safety_margin. larger = safer but slower\n///\n/// scales: list[int]\n///     Optional scales to specifically try for calibration\n///\n/// scale_rebase_multiplier: list[int]\n///     Optional scale rebase multipliers to specifically try for calibration. This is the multiplier at which we divide to return to the input scale.\n///\n/// max_logrows: int\n///     Optional max logrows to use for calibration\n///\n/// only_range_check_rebase: bool\n///     Check ranges when rebasing\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    data = PathBuf::from(DEFAULT_CALIBRATION_FILE),\n    model = PathBuf::from(DEFAULT_MODEL),\n    settings = PathBuf::from(DEFAULT_SETTINGS),\n    target = CalibrationTarget::default(), // default is \"resources\n    lookup_safety_margin = DEFAULT_LOOKUP_SAFETY_MARGIN.parse().unwrap(),\n    scales = None,\n    scale_rebase_multiplier = DEFAULT_SCALE_REBASE_MULTIPLIERS.split(\",\").map(|x| x.parse().unwrap()).collect(),\n    max_logrows = None,\n    only_range_check_rebase = DEFAULT_ONLY_RANGE_CHECK_REBASE.parse().unwrap(),\n))]\nfn calibrate_settings(\n    data: PathBuf,\n    model: PathBuf,\n    settings: PathBuf,\n    target: CalibrationTarget,\n    lookup_safety_margin: i128,\n    scales: Option<Vec<crate::Scale>>,\n    scale_rebase_multiplier: Vec<u32>,\n    max_logrows: Option<u32>,\n    only_range_check_rebase: bool,\n) -> Result<bool, PyErr> {\n    crate::execute::calibrate(\n        model,\n        data,\n        settings,\n        target,\n        lookup_safety_margin,\n        scales,\n        scale_rebase_multiplier,\n        only_range_check_rebase,\n        max_logrows,\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to calibrate settings: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Runs the forward pass operation to generate a witness\n///\n/// Arguments\n/// ---------\n/// data: str\n///     Path to the data file\n///\n/// model: str\n///     Path to the compiled model file\n///\n/// output: str\n///     Path to create the witness file\n///\n/// vk_path: str\n///     Path to the verification key\n///\n/// srs_path: str\n///     Path to the SRS file\n///\n/// Returns\n/// -------\n/// dict\n///     Python object containing the witness values\n///\n#[pyfunction(signature = (\n    data=PathBuf::from(DEFAULT_DATA),\n    model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),\n    output=PathBuf::from(DEFAULT_WITNESS),\n    vk_path=None,\n    srs_path=None,\n))]\nfn gen_witness(\n    data: PathBuf,\n    model: PathBuf,\n    output: Option<PathBuf>,\n    vk_path: Option<PathBuf>,\n    srs_path: Option<PathBuf>,\n) -> PyResult<PyObject> {\n    let output =\n        crate::execute::gen_witness(model, data, output, vk_path, srs_path).map_err(|e| {\n            let err_str = format!(\"Failed to run generate witness: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n    Python::with_gil(|py| Ok(output.to_object(py)))\n}\n\n/// Mocks the prover\n///\n/// Arguments\n/// ---------\n/// witness: str\n///     Path to the witness file\n///\n/// model: str\n///     Path to the compiled model file\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    witness=PathBuf::from(DEFAULT_WITNESS),\n    model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),\n))]\nfn mock(witness: PathBuf, model: PathBuf) -> PyResult<bool> {\n    crate::execute::mock(model, witness).map_err(|e| {\n        let err_str = format!(\"Failed to run mock: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n    Ok(true)\n}\n\n/// Mocks the aggregate prover\n///\n/// Arguments\n/// ---------\n/// aggregation_snarks: list[str]\n///     List of paths to the relevant proof files\n///\n/// logrows: int\n///     Number of logrows to use for the aggregation circuit\n///\n/// split_proofs: bool\n///     Indicates whether the accumulated are segments of a larger proof\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    aggregation_snarks=vec![PathBuf::from(DEFAULT_PROOF)],\n    logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),\n    split_proofs = false,\n))]\nfn mock_aggregate(\n    aggregation_snarks: Vec<PathBuf>,\n    logrows: u32,\n    split_proofs: bool,\n) -> PyResult<bool> {\n    crate::execute::mock_aggregate(aggregation_snarks, logrows, split_proofs).map_err(|e| {\n        let err_str = format!(\"Failed to run mock: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Runs the setup process\n///\n/// Arguments\n/// ---------\n/// model: str\n///     Path to the compiled model file\n///\n/// vk_path: str\n///     Path to create the verification key file\n///\n/// pk_path: str\n///     Path to create the proving key file\n///\n/// srs_path: str\n///     Path to the SRS file\n///\n/// witness_path: str\n///     Path to the witness file\n///\n/// disable_selector_compression: bool\n///     Whether to compress the selectors or not\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),\n    vk_path=PathBuf::from(DEFAULT_VK),\n    pk_path=PathBuf::from(DEFAULT_PK),\n    srs_path=None,\n    witness_path = None,\n    disable_selector_compression=DEFAULT_DISABLE_SELECTOR_COMPRESSION.parse().unwrap(),\n))]\nfn setup(\n    model: PathBuf,\n    vk_path: PathBuf,\n    pk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    witness_path: Option<PathBuf>,\n    disable_selector_compression: bool,\n) -> Result<bool, PyErr> {\n    crate::execute::setup(\n        model,\n        srs_path,\n        vk_path,\n        pk_path,\n        witness_path,\n        disable_selector_compression,\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run setup: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Runs the prover on a set of inputs\n///\n/// Arguments\n/// ---------\n/// witness: str\n///     Path to the witness file\n///\n/// model: str\n///     Path to the compiled model file\n///\n/// pk_path: str\n///     Path to the proving key file\n///\n/// proof_path: str\n///     Path to create the proof file\n///\n/// proof_type: str\n///     Accepts `single`, `for-aggr`\n///\n/// srs_path: str\n///     Path to the SRS file\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    witness=PathBuf::from(DEFAULT_WITNESS),\n    model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),\n    pk_path=PathBuf::from(DEFAULT_PK),\n    proof_path=None,\n    proof_type=ProofType::default(),\n    srs_path=None,\n))]\nfn prove(\n    witness: PathBuf,\n    model: PathBuf,\n    pk_path: PathBuf,\n    proof_path: Option<PathBuf>,\n    proof_type: ProofType,\n    srs_path: Option<PathBuf>,\n) -> PyResult<PyObject> {\n    let snark = crate::execute::prove(\n        witness,\n        model,\n        pk_path,\n        proof_path,\n        srs_path,\n        proof_type,\n        CheckMode::UNSAFE,\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run prove: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Python::with_gil(|py| Ok(snark.to_object(py)))\n}\n\n/// Verifies a given proof\n///\n/// Arguments\n/// ---------\n/// proof_path: str\n///     Path to create the proof file\n///\n/// settings_path: str\n///     Path to the settings file\n///\n/// vk_path: str\n///     Path to the verification key file\n///\n/// srs_path: str\n///     Path to the SRS file\n///\n/// non_reduced_srs: bool\n///     Whether to reduce the number of SRS logrows to the number of instances rather than the number of logrows used for proofs (only works if the srs were generated in the same ceremony)\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    proof_path=PathBuf::from(DEFAULT_PROOF),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    vk_path=PathBuf::from(DEFAULT_VK),\n    srs_path=None,\n    reduced_srs=DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION.parse::<bool>().unwrap(),\n))]\nfn verify(\n    proof_path: PathBuf,\n    settings_path: PathBuf,\n    vk_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    reduced_srs: bool,\n) -> Result<bool, PyErr> {\n    crate::execute::verify(proof_path, settings_path, vk_path, srs_path, reduced_srs).map_err(\n        |e| {\n            let err_str = format!(\"Failed to run verify: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        },\n    )?;\n\n    Ok(true)\n}\n\n///  Runs the setup process for an aggregate setup\n///\n/// Arguments\n/// ---------\n/// sample_snarks: list[str]\n///     List of paths to the various proofs\n///\n/// vk_path: str\n///     Path to create the aggregated VK\n///\n/// pk_path: str\n///     Path to create the aggregated PK\n///\n/// logrows: int\n///     Number of logrows to use\n///\n/// split_proofs: bool\n///     Whether the accumulated are segments of a larger proof\n///\n/// srs_path: str\n///     Path to the SRS file\n///\n/// disable_selector_compression: bool\n///     Whether to compress selectors\n///\n/// commitment: str\n///     Accepts `kzg`, `ipa`\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    sample_snarks=vec![PathBuf::from(DEFAULT_PROOF)],\n    vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),\n    pk_path=PathBuf::from(DEFAULT_PK_AGGREGATED),\n    logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),\n    split_proofs = false,\n    srs_path = None,\n    disable_selector_compression=DEFAULT_DISABLE_SELECTOR_COMPRESSION.parse().unwrap(),\n    commitment=DEFAULT_COMMITMENT.parse().unwrap(),\n))]\nfn setup_aggregate(\n    sample_snarks: Vec<PathBuf>,\n    vk_path: PathBuf,\n    pk_path: PathBuf,\n    logrows: u32,\n    split_proofs: bool,\n    srs_path: Option<PathBuf>,\n    disable_selector_compression: bool,\n    commitment: PyCommitments,\n) -> Result<bool, PyErr> {\n    crate::execute::setup_aggregate(\n        sample_snarks,\n        vk_path,\n        pk_path,\n        srs_path,\n        logrows,\n        split_proofs,\n        disable_selector_compression,\n        commitment.into(),\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to setup aggregate: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Compiles the circuit for use in other steps\n///\n/// Arguments\n/// ---------\n/// model: str\n///     Path to the onnx model file\n///\n/// compiled_circuit: str\n///     Path to output the compiled circuit\n///\n/// settings_path: str\n///     Path to the settings files\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    model=PathBuf::from(DEFAULT_MODEL),\n    compiled_circuit=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n))]\nfn compile_circuit(\n    model: PathBuf,\n    compiled_circuit: PathBuf,\n    settings_path: PathBuf,\n) -> Result<bool, PyErr> {\n    crate::execute::compile_circuit(model, compiled_circuit, settings_path).map_err(|e| {\n        let err_str = format!(\"Failed to setup aggregate: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Creates an aggregated proof\n///\n/// Arguments\n/// ---------\n/// aggregation_snarks: list[str]\n///     List of paths to the various proofs\n///\n/// proof_path: str\n///     Path to output the aggregated proof\n///\n/// vk_path: str\n///     Path to the VK file\n///\n/// transcript:\n///     Proof transcript type to be used. `evm` used by default. `poseidon` is also supported\n///\n/// logrows:\n///     Logrows used for aggregation circuit\n///\n/// check_mode: str\n///     Run sanity checks during calculations. Accepts `safe` or `unsafe`\n///\n/// split-proofs: bool\n///      Whether the accumulated proofs are segments of a larger circuit\n///\n/// srs_path: str\n///     Path to the SRS used\n///\n/// commitment: str\n///     Accepts \"kzg\" or \"ipa\"\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    aggregation_snarks=vec![PathBuf::from(DEFAULT_PROOF)],\n    proof_path=PathBuf::from(DEFAULT_PROOF_AGGREGATED),\n    vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),\n    transcript=TranscriptType::default(),\n    logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),\n    check_mode=CheckMode::UNSAFE,\n    split_proofs = false,\n    srs_path=None,\n    commitment=DEFAULT_COMMITMENT.parse().unwrap(),\n))]\nfn aggregate(\n    aggregation_snarks: Vec<PathBuf>,\n    proof_path: PathBuf,\n    vk_path: PathBuf,\n    transcript: TranscriptType,\n    logrows: u32,\n    check_mode: CheckMode,\n    split_proofs: bool,\n    srs_path: Option<PathBuf>,\n    commitment: PyCommitments,\n) -> Result<bool, PyErr> {\n    // the K used for the aggregation circuit\n    crate::execute::aggregate(\n        proof_path,\n        aggregation_snarks,\n        vk_path,\n        srs_path,\n        transcript,\n        logrows,\n        check_mode,\n        split_proofs,\n        commitment.into(),\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run aggregate: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Verifies and aggregate proof\n///\n/// Arguments\n/// ---------\n/// proof_path: str\n///      The path to the proof file\n///\n/// vk_path: str\n///     The path to the verification key file\n///\n/// logrows: int\n///     logrows used for aggregation circuit\n///\n/// commitment: str\n///     Accepts \"kzg\" or \"ipa\"\n///\n/// reduced_srs: bool\n///     Whether to reduce the number of SRS logrows to the number of instances rather than the number of logrows used for proofs (only works if the srs were generated in the same ceremony)\n///\n/// srs_path: str\n///     The path to the SRS file\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    proof_path=PathBuf::from(DEFAULT_PROOF_AGGREGATED),\n    vk_path=PathBuf::from(DEFAULT_VK),\n    logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),\n    commitment=DEFAULT_COMMITMENT.parse().unwrap(),\n    reduced_srs=DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION.parse().unwrap(),\n    srs_path=None,\n))]\nfn verify_aggr(\n    proof_path: PathBuf,\n    vk_path: PathBuf,\n    logrows: u32,\n    commitment: PyCommitments,\n    reduced_srs: bool,\n    srs_path: Option<PathBuf>,\n) -> Result<bool, PyErr> {\n    crate::execute::verify_aggr(\n        proof_path,\n        vk_path,\n        srs_path,\n        logrows,\n        reduced_srs,\n        commitment.into(),\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run verify_aggr: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Creates an EVM compatible verifier, you will need solc installed in your environment to run this\n///\n/// Arguments\n/// ---------\n/// vk_path: str\n///     The path to the verification key file\n///\n/// settings_path: str\n///     The path to the settings file\n///\n/// sol_code_path: str\n///     The path to the create the solidity verifier\n///\n/// abi_path: str\n///     The path to create the ABI for the solidity verifier\n///\n/// srs_path: str\n///     The path to the SRS file\n///\n/// render_vk_separately: bool\n///     Whether the verifier key should be rendered as a separate contract. We recommend disabling selector compression if this is enabled. To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    vk_path=PathBuf::from(DEFAULT_VK),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),\n    abi_path=PathBuf::from(DEFAULT_VERIFIER_ABI),\n    srs_path=None,\n    render_vk_seperately = DEFAULT_RENDER_VK_SEPERATELY.parse().unwrap(),\n))]\nfn create_evm_verifier(\n    vk_path: PathBuf,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n    srs_path: Option<PathBuf>,\n    render_vk_seperately: bool,\n) -> Result<bool, PyErr> {\n    crate::execute::create_evm_verifier(\n        vk_path,\n        srs_path,\n        settings_path,\n        sol_code_path,\n        abi_path,\n        render_vk_seperately,\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run create_evm_verifier: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n\n    Ok(true)\n}\n\n/// Creates an EVM compatible data attestation verifier, you will need solc installed in your environment to run this\n///\n/// Arguments\n/// ---------\n/// input_data: str\n///     The path to the .json data file, which should contain the necessary calldata and account addresses needed to read from all the on-chain view functions that return the data that the network ingests as inputs\n///\n/// settings_path: str\n///     The path to the settings file\n///\n/// sol_code_path: str\n///     The path to the create the solidity verifier\n///\n/// abi_path: str\n///     The path to create the ABI for the solidity verifier\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    input_data=PathBuf::from(DEFAULT_DATA),\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    sol_code_path=PathBuf::from(DEFAULT_SOL_CODE_DA),\n    abi_path=PathBuf::from(DEFAULT_VERIFIER_DA_ABI),\n))]\nfn create_evm_data_attestation(\n    input_data: PathBuf,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n) -> Result<bool, PyErr> {\n    crate::execute::create_evm_data_attestation(settings_path, sol_code_path, abi_path, input_data)\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run create_evm_data_attestation: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n\n/// Setup test evm witness\n///\n/// Arguments\n/// ---------\n/// data_path: str\n///     The path to the .json data file, which should include both the network input (possibly private) and the network output (public input to the proof)\n///\n/// compiled_circuit_path: str\n///     The path to the compiled model file (generated using the compile-circuit command)\n///\n/// test_data: str\n///     For testing purposes only. The optional path to the .json data file that will be generated that contains the OnChain data storage information derived from the file information in the data .json file. Should include both the network input (possibly private) and the network output (public input to the proof)\n///\n/// input_sources: str\n///     Where the input data comes from\n///\n/// output_source: str\n///     Where the output data comes from\n///\n/// rpc_url: str\n///     RPC URL for an EVM compatible node, if None, uses Anvil as a local RPC node\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    data_path,\n    compiled_circuit_path,\n    test_data,\n    input_source,\n    output_source,\n    rpc_url=None,\n))]\nfn setup_test_evm_witness(\n    data_path: PathBuf,\n    compiled_circuit_path: PathBuf,\n    test_data: PathBuf,\n    input_source: PyTestDataSource,\n    output_source: PyTestDataSource,\n    rpc_url: Option<String>,\n) -> Result<bool, PyErr> {\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::setup_test_evm_witness(\n            data_path,\n            compiled_circuit_path,\n            test_data,\n            rpc_url,\n            input_source.into(),\n            output_source.into(),\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run setup_test_evm_witness: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n\n/// deploys the solidity verifier\n#[pyfunction(signature = (\n    addr_path,\n    sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),\n    rpc_url=None,\n    optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),\n    private_key=None,\n))]\nfn deploy_evm(\n    addr_path: PathBuf,\n    sol_code_path: PathBuf,\n    rpc_url: Option<String>,\n    optimizer_runs: usize,\n    private_key: Option<String>,\n) -> Result<bool, PyErr> {\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::deploy_evm(\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n            \"Halo2Verifier\",\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run deploy_evm: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n\n/// deploys the solidity vk verifier\n#[pyfunction(signature = (\n    addr_path,\n    sol_code_path=PathBuf::from(DEFAULT_VK_SOL),\n    rpc_url=None,\n    optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),\n    private_key=None,\n))]\nfn deploy_vk_evm(\n    addr_path: PathBuf,\n    sol_code_path: PathBuf,\n    rpc_url: Option<String>,\n    optimizer_runs: usize,\n    private_key: Option<String>,\n) -> Result<bool, PyErr> {\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::deploy_evm(\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n            \"Halo2VerifyingKey\",\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run deploy_evm: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n\n/// deploys the solidity da verifier\n#[pyfunction(signature = (\n    addr_path,\n    input_data,\n    settings_path=PathBuf::from(DEFAULT_SETTINGS),\n    sol_code_path=PathBuf::from(DEFAULT_SOL_CODE_DA),\n    rpc_url=None,\n    optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),\n    private_key=None\n))]\nfn deploy_da_evm(\n    addr_path: PathBuf,\n    input_data: PathBuf,\n    settings_path: PathBuf,\n    sol_code_path: PathBuf,\n    rpc_url: Option<String>,\n    optimizer_runs: usize,\n    private_key: Option<String>,\n) -> Result<bool, PyErr> {\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::deploy_da_evm(\n            input_data,\n            settings_path,\n            sol_code_path,\n            rpc_url,\n            addr_path,\n            optimizer_runs,\n            private_key,\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run deploy_da_evm: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n/// verifies an evm compatible proof, you will need solc installed in your environment to run this\n///\n/// Arguments\n/// ---------\n/// addr_verifier: str\n///     The path to verifier contract's address\n///\n/// proof_path: str\n///     The path to the proof file (generated using the prove command)\n///\n/// rpc_url: str\n///     RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state\n///\n/// addr_da: str\n///     does the verifier use data attestation ?\n///\n/// addr_vk: str\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    addr_verifier,\n    proof_path=PathBuf::from(DEFAULT_PROOF),\n    rpc_url=None,\n    addr_da = None,\n    addr_vk = None,\n))]\nfn verify_evm(\n    addr_verifier: &str,\n    proof_path: PathBuf,\n    rpc_url: Option<String>,\n    addr_da: Option<&str>,\n    addr_vk: Option<&str>,\n) -> Result<bool, PyErr> {\n    let addr_verifier = H160Flag::from(addr_verifier);\n    let addr_da = if let Some(addr_da) = addr_da {\n        let addr_da = H160Flag::from(addr_da);\n        Some(addr_da)\n    } else {\n        None\n    };\n    let addr_vk = if let Some(addr_vk) = addr_vk {\n        let addr_vk = H160Flag::from(addr_vk);\n        Some(addr_vk)\n    } else {\n        None\n    };\n\n    Runtime::new()\n        .unwrap()\n        .block_on(crate::execute::verify_evm(\n            proof_path,\n            addr_verifier,\n            rpc_url,\n            addr_da,\n            addr_vk,\n        ))\n        .map_err(|e| {\n            let err_str = format!(\"Failed to run verify_evm: {}\", e);\n            PyRuntimeError::new_err(err_str)\n        })?;\n\n    Ok(true)\n}\n\n/// Creates an evm compatible aggregate verifier, you will need solc installed in your environment to run this\n///\n/// Arguments\n/// ---------\n/// aggregation_settings: str\n///     path to the settings file\n///\n/// vk_path: str\n///     The path to load the desired verification key file\n///\n/// sol_code_path: str\n///     The path to the Solidity code\n///\n/// abi_path: str\n///     The path to output the Solidity verifier ABI\n///\n/// logrows: int\n///     Number of logrows used during aggregated setup\n///\n/// srs_path: str\n///     The path to the SRS file\n///\n/// render_vk_separately: bool\n///     Whether the verifier key should be rendered as a separate contract. We recommend disabling selector compression if this is enabled. To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command\n///\n/// Returns\n/// -------\n/// bool\n///\n#[pyfunction(signature = (\n    aggregation_settings=vec![PathBuf::from(DEFAULT_PROOF)],\n    vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),\n    sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),\n    abi_path=PathBuf::from(DEFAULT_VERIFIER_ABI),\n    logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),\n    srs_path=None,\n    render_vk_seperately = DEFAULT_RENDER_VK_SEPERATELY.parse().unwrap(),\n))]\nfn create_evm_verifier_aggr(\n    aggregation_settings: Vec<PathBuf>,\n    vk_path: PathBuf,\n    sol_code_path: PathBuf,\n    abi_path: PathBuf,\n    logrows: u32,\n    srs_path: Option<PathBuf>,\n    render_vk_seperately: bool,\n) -> Result<bool, PyErr> {\n    crate::execute::create_evm_aggregate_verifier(\n        vk_path,\n        srs_path,\n        sol_code_path,\n        abi_path,\n        aggregation_settings,\n        logrows,\n        render_vk_seperately,\n    )\n    .map_err(|e| {\n        let err_str = format!(\"Failed to run create_evm_verifier_aggr: {}\", e);\n        PyRuntimeError::new_err(err_str)\n    })?;\n    Ok(true)\n}\n\n// Python Module\n#[pymodule]\nfn ezkl(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n    pyo3_log::init();\n    m.add_class::<PyRunArgs>()?;\n    m.add_class::<PyG1Affine>()?;\n    m.add_class::<PyG1>()?;\n    m.add_class::<PyTestDataSource>()?;\n    m.add_class::<PyCommitments>()?;\n    m.add(\"__version__\", env!(\"CARGO_PKG_VERSION\"))?;\n    m.add_function(wrap_pyfunction!(felt_to_big_endian, m)?)?;\n    m.add_function(wrap_pyfunction!(felt_to_int, m)?)?;\n    m.add_function(wrap_pyfunction!(felt_to_float, m)?)?;\n    m.add_function(wrap_pyfunction!(kzg_commit, m)?)?;\n    m.add_function(wrap_pyfunction!(ipa_commit, m)?)?;\n    m.add_function(wrap_pyfunction!(swap_proof_commitments, m)?)?;\n    m.add_function(wrap_pyfunction!(poseidon_hash, m)?)?;\n    m.add_function(wrap_pyfunction!(float_to_felt, m)?)?;\n    m.add_function(wrap_pyfunction!(buffer_to_felts, m)?)?;\n    m.add_function(wrap_pyfunction!(gen_vk_from_pk_aggr, m)?)?;\n    m.add_function(wrap_pyfunction!(gen_vk_from_pk_single, m)?)?;\n    m.add_function(wrap_pyfunction!(table, m)?)?;\n    m.add_function(wrap_pyfunction!(mock, m)?)?;\n    m.add_function(wrap_pyfunction!(setup, m)?)?;\n    m.add_function(wrap_pyfunction!(prove, m)?)?;\n    m.add_function(wrap_pyfunction!(verify, m)?)?;\n    m.add_function(wrap_pyfunction!(gen_srs, m)?)?;\n    m.add_function(wrap_pyfunction!(get_srs, m)?)?;\n    m.add_function(wrap_pyfunction!(gen_witness, m)?)?;\n    m.add_function(wrap_pyfunction!(gen_settings, m)?)?;\n    m.add_function(wrap_pyfunction!(calibrate_settings, m)?)?;\n    m.add_function(wrap_pyfunction!(aggregate, m)?)?;\n    m.add_function(wrap_pyfunction!(mock_aggregate, m)?)?;\n    m.add_function(wrap_pyfunction!(setup_aggregate, m)?)?;\n    m.add_function(wrap_pyfunction!(compile_circuit, m)?)?;\n    m.add_function(wrap_pyfunction!(verify_aggr, m)?)?;\n    m.add_function(wrap_pyfunction!(create_evm_verifier, m)?)?;\n    m.add_function(wrap_pyfunction!(deploy_evm, m)?)?;\n    m.add_function(wrap_pyfunction!(deploy_vk_evm, m)?)?;\n    m.add_function(wrap_pyfunction!(deploy_da_evm, m)?)?;\n    m.add_function(wrap_pyfunction!(verify_evm, m)?)?;\n    m.add_function(wrap_pyfunction!(setup_test_evm_witness, m)?)?;\n    m.add_function(wrap_pyfunction!(create_evm_verifier_aggr, m)?)?;\n    m.add_function(wrap_pyfunction!(create_evm_data_attestation, m)?)?;\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/srs_sha.rs",
        "content": "use lazy_static::lazy_static;\nuse std::collections::HashMap;\n\nlazy_static! {\n    /// SRS SHA256 hashes\n    pub static ref PUBLIC_SRS_SHA256_HASHES: HashMap<u32, &'static str> = HashMap::from_iter([\n        (\n            1,\n            \"cafb2aa72c200ddc4e28aacabb8066e829207e2484b8d17059a566232f8a297b\",\n        ),\n        (\n            2,\n            \"8194ec51da5d332d2e17283ade34920644774452c2fadf33742e8c739e275d8e\",\n        ),\n        (\n            3,\n            \"0729e815bce2ac4dfad7819982c6479c3b22c32b71f64dca05e8fdd90e8535ef\",\n        ),\n        (\n            4,\n            \"2c0785da20217fcafd3b12cc363a95eb2529037cc8a9bddf8fb15025cbc8cdc9\",\n        ),\n        (\n            5,\n            \"5b950e3b76e7a9923d69f6d6585ce6b5f9458e5ec57a71c9de5005d32d544692\",\n        ),\n        (\n            6,\n            \"85030b2924111fc60acaf4fb8a7bad89531fbe0271aeab0c21e545f71eee273d\",\n        ),\n        (\n            7,\n            \"e65f95150519fe01c2bedf8f832f5249822ef84c9c017307419e10374ff9eeb1\",\n        ),\n        (\n            8,\n            \"446092fd1d6030e5bb2f2a8368267d5ed0fbdb6a766f6c5e4a4841827ad3106f\",\n        ),\n        (\n            9,\n            \"493d088951882ad81af11e08c791a38a37c0ffff14578cf2c7fb9b7bca654d8b\",\n        ),\n        (\n            10,\n            \"9705d450e5dfd06adb673705f7bc34418ec86339203198beceb2ae7f1ffefedb\",\n        ),\n        (\n            11,\n            \"257fa566ed9bc0767d3e63e92b5e966829fa3347d320a32055dc31ee7d33f8a4\",\n        ),\n        (\n            12,\n            \"28b151069f41abc121baa6d2eaa8f9e4c4d8326ddbefee2bd9c0776b80ac6fad\",\n        ),\n        (\n            13,\n            \"d5d94bb25bdc024f649213593027d861042ee807cafd94b49b54f1663f8f267d\",\n        ),\n        (\n            14,\n            \"c09129f064c08ecb07ea3689a2247dcc177de6837e7d2f5f946e30453abbccef\",\n        ),\n        (\n            15,\n            \"90807800a1c3b248a452e1732c45ee5099f38b737356f5542c0584ec9c3ebb45\",\n        ),\n        (\n            16,\n            \"2a1a494630e71bc026dd5c0eab4c1b9a5dbc656228c1f0d48f5dbd3909b161d3\",\n        ),\n        (\n            17,\n            \"41509f380362a8d14401c5ae92073154922fe23e45459ce6f696f58607655db7\",\n        ),\n        (\n            18,\n            \"d0148475717a2ba269784a178cb0ab617bc77f16c58d4a3cbdfe785b591c7034\",\n        ),\n        (\n            19,\n            \"d1a1655b4366a766d1578beb257849a92bf91cb1358c1a2c37ab180c5d3a204d\",\n        ),\n        (\n            20,\n            \"54ef75911da76d7a6b7ea341998aaf66cb06c679c53e0a88a4fe070dd3add963\",\n        ),\n        (\n            21,\n            \"486e044cf98704e07f41137d2b89698dc03d1fbf34d13b60902fea19a6013b4b\",\n        ),\n        (\n            22,\n            \"1ee9b4396db3e4e2516ac5016626ab6ba967f091d5d23afbdb7df122a0bb9d0c\",\n        ),\n        (\n            23,\n            \"748e48b9b6d06f9c82d26bf551d0af43ee2e801e4be56d7ccb20312e267fd1d6\",\n        ),\n        (\n            24,\n            \"f94fa4afa2f5147680f907d4dd96a8826206c26bd3328cd379feaed614b234de\",\n        ),\n        (\n            25,\n            \"dec49a69893fbcd66cd06296b2d936a6aceb431c130b2e52675fe4274b504f57\",\n        ),\n        (\n            26,\n            \"b198a51d48b88181508d8e4ea9dea39db285e4585663b29b7e4ded0c22a94875\",\n        ),\n    ]);\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/tensor/mod.rs",
        "content": "/// Implementations of common operations on tensors.\npub mod ops;\n/// A wrapper around a tensor of circuit variables / advices.\npub mod val;\n/// A wrapper around a tensor of Halo2 Value types.\npub mod var;\n\nuse halo2curves::ff::PrimeField;\nuse maybe_rayon::{\n    prelude::{\n        IndexedParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator,\n        ParallelIterator,\n    },\n    slice::ParallelSliceMut,\n};\nuse serde::{Deserialize, Serialize};\npub use val::*;\npub use var::*;\n\nuse crate::{\n    circuit::utils,\n    fieldutils::{felt_to_i32, i128_to_felt, i32_to_felt},\n    graph::Visibility,\n};\n\nuse halo2_proofs::{\n    arithmetic::Field,\n    circuit::{AssignedCell, Region, Value},\n    plonk::{Advice, Assigned, Column, ConstraintSystem, Expression, Fixed, VirtualCells},\n    poly::Rotation,\n};\nuse itertools::Itertools;\nuse std::error::Error;\nuse std::fmt::Debug;\nuse std::iter::Iterator;\nuse std::ops::{Add, Deref, DerefMut, Div, Mul, Neg, Range, Sub};\nuse std::{cmp::max, ops::Rem};\nuse thiserror::Error;\n/// A wrapper for tensor related errors.\n#[derive(Debug, Error)]\npub enum TensorError {\n    /// Shape mismatch in a operation\n    #[error(\"dimension mismatch in tensor op: {0}\")]\n    DimMismatch(String),\n    /// Shape when instantiating\n    #[error(\"dimensionality error when manipulating a tensor: {0}\")]\n    DimError(String),\n    /// wrong method was called on a tensor-like struct\n    #[error(\"wrong method called\")]\n    WrongMethod,\n    /// Significant bit truncation when instantiating\n    #[error(\"Significant bit truncation when instantiating, try lowering the scale\")]\n    SigBitTruncationError,\n    /// Failed to convert to field element tensor\n    #[error(\"Failed to convert to field element tensor\")]\n    FeltError,\n    /// Table lookup error\n    #[error(\"Table lookup error\")]\n    TableLookupError,\n    /// Unsupported operation\n    #[error(\"Unsupported operation on a tensor type\")]\n    Unsupported,\n    /// Overflow\n    #[error(\"Unsigned integer overflow or underflow error in op: {0}\")]\n    Overflow(String),\n}\n\n/// The (inner) type of tensor elements.\npub trait TensorType: Clone + Debug + 'static {\n    /// Returns the zero value.\n    fn zero() -> Option<Self> {\n        None\n    }\n    /// Returns the unit value.\n    fn one() -> Option<Self> {\n        None\n    }\n    /// Max operator for ordering values.\n    fn tmax(&self, _: &Self) -> Option<Self> {\n        None\n    }\n}\n\nmacro_rules! tensor_type {\n    ($rust_type:ty, $tensor_type:ident, $zero:expr, $one:expr) => {\n        impl TensorType for $rust_type {\n            fn zero() -> Option<Self> {\n                Some($zero)\n            }\n            fn one() -> Option<Self> {\n                Some($one)\n            }\n\n            fn tmax(&self, other: &Self) -> Option<Self> {\n                Some(max(*self, *other))\n            }\n        }\n    };\n}\n\nimpl TensorType for f32 {\n    fn zero() -> Option<Self> {\n        Some(0.0)\n    }\n\n    // f32 doesnt impl Ord so we cant just use max like we can for i32, usize.\n    // A comparison between f32s needs to handle NAN values.\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        match (self.is_nan(), other.is_nan()) {\n            (true, true) => Some(f32::NAN),\n            (true, false) => Some(*other),\n            (false, true) => Some(*self),\n            (false, false) => {\n                if self >= other {\n                    Some(*self)\n                } else {\n                    Some(*other)\n                }\n            }\n        }\n    }\n}\n\nimpl TensorType for f64 {\n    fn zero() -> Option<Self> {\n        Some(0.0)\n    }\n\n    // f32 doesnt impl Ord so we cant just use max like we can for i32, usize.\n    // A comparison between f32s needs to handle NAN values.\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        match (self.is_nan(), other.is_nan()) {\n            (true, true) => Some(f64::NAN),\n            (true, false) => Some(*other),\n            (false, true) => Some(*self),\n            (false, false) => {\n                if self >= other {\n                    Some(*self)\n                } else {\n                    Some(*other)\n                }\n            }\n        }\n    }\n}\n\ntensor_type!(bool, Bool, false, true);\ntensor_type!(i128, Int128, 0, 1);\ntensor_type!(i32, Int32, 0, 1);\ntensor_type!(usize, USize, 0, 1);\ntensor_type!((), Empty, (), ());\ntensor_type!(utils::F32, F32, utils::F32(0.0), utils::F32(1.0));\n\nimpl<T: TensorType> TensorType for Tensor<T> {\n    fn zero() -> Option<Self> {\n        Some(Tensor::new(Some(&[T::zero().unwrap()]), &[1]).unwrap())\n    }\n    fn one() -> Option<Self> {\n        Some(Tensor::new(Some(&[T::one().unwrap()]), &[1]).unwrap())\n    }\n}\n\nimpl<T: TensorType> TensorType for Value<T> {\n    fn zero() -> Option<Self> {\n        Some(Value::known(T::zero().unwrap()))\n    }\n\n    fn one() -> Option<Self> {\n        Some(Value::known(T::one().unwrap()))\n    }\n\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        Some(\n            (self.clone())\n                .zip(other.clone())\n                .map(|(a, b)| a.tmax(&b).unwrap()),\n        )\n    }\n}\n\nimpl<F: PrimeField + PartialOrd> TensorType for Assigned<F>\nwhere\n    F: Field,\n{\n    fn zero() -> Option<Self> {\n        Some(F::ZERO.into())\n    }\n\n    fn one() -> Option<Self> {\n        Some(F::ONE.into())\n    }\n\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        if self.evaluate() >= other.evaluate() {\n            Some(*self)\n        } else {\n            Some(*other)\n        }\n    }\n}\n\nimpl<F: PrimeField> TensorType for Expression<F>\nwhere\n    F: Field,\n{\n    fn zero() -> Option<Self> {\n        Some(Expression::Constant(F::ZERO))\n    }\n\n    fn one() -> Option<Self> {\n        Some(Expression::Constant(F::ONE))\n    }\n\n    fn tmax(&self, _: &Self) -> Option<Self> {\n        todo!()\n    }\n}\n\nimpl TensorType for Column<Advice> {}\nimpl TensorType for Column<Fixed> {}\n\nimpl<F: PrimeField + PartialOrd> TensorType for AssignedCell<Assigned<F>, F> {\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        let mut output: Option<Self> = None;\n        self.value_field().zip(other.value_field()).map(|(a, b)| {\n            if a.evaluate() >= b.evaluate() {\n                output = Some(self.clone());\n            } else {\n                output = Some(other.clone());\n            }\n        });\n        output\n    }\n}\n\nimpl<F: PrimeField + PartialOrd> TensorType for AssignedCell<F, F> {\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        let mut output: Option<Self> = None;\n        self.value().zip(other.value()).map(|(a, b)| {\n            if a >= b {\n                output = Some(self.clone());\n            } else {\n                output = Some(other.clone());\n            }\n        });\n        output\n    }\n}\n\n// specific types\nimpl TensorType for halo2curves::pasta::Fp {\n    fn zero() -> Option<Self> {\n        Some(halo2curves::pasta::Fp::zero())\n    }\n\n    fn one() -> Option<Self> {\n        Some(halo2curves::pasta::Fp::one())\n    }\n\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        Some((*self).max(*other))\n    }\n}\n\nimpl TensorType for halo2curves::bn256::Fr {\n    fn zero() -> Option<Self> {\n        Some(halo2curves::bn256::Fr::zero())\n    }\n\n    fn one() -> Option<Self> {\n        Some(halo2curves::bn256::Fr::one())\n    }\n\n    fn tmax(&self, other: &Self) -> Option<Self> {\n        Some((*self).max(*other))\n    }\n}\n\n/// A generic multi-dimensional array representation of a Tensor.\n/// The `inner` attribute contains a vector of values whereas `dims` corresponds to the dimensionality of the array\n/// and as such determines how we index, query for values, or slice a Tensor.\n#[derive(Clone, Debug, Eq, Serialize, Deserialize, PartialOrd, Ord)]\npub struct Tensor<T: TensorType> {\n    inner: Vec<T>,\n    dims: Vec<usize>,\n    scale: Option<crate::Scale>,\n    visibility: Option<Visibility>,\n}\n\nimpl<T: TensorType> IntoIterator for Tensor<T> {\n    type Item = T;\n    type IntoIter = ::std::vec::IntoIter<T>;\n\n    fn into_iter(self) -> Self::IntoIter {\n        self.inner.into_iter()\n    }\n}\n\nimpl<T: TensorType> Deref for Tensor<T> {\n    type Target = [T];\n\n    #[inline]\n    fn deref(&self) -> &[T] {\n        self.inner.deref()\n    }\n}\n\nimpl<T: TensorType> DerefMut for Tensor<T> {\n    #[inline]\n    fn deref_mut(&mut self) -> &mut [T] {\n        self.inner.deref_mut()\n    }\n}\n\nimpl<T: PartialEq + TensorType> PartialEq for Tensor<T> {\n    fn eq(&self, other: &Tensor<T>) -> bool {\n        self.dims == other.dims && self.deref() == other.deref()\n    }\n}\n\nimpl<I: Iterator> From<I> for Tensor<I::Item>\nwhere\n    I::Item: TensorType + Clone,\n    Vec<I::Item>: FromIterator<I::Item>,\n{\n    fn from(value: I) -> Tensor<I::Item> {\n        let data: Vec<I::Item> = value.collect::<Vec<I::Item>>();\n        Tensor::new(Some(&data), &[data.len()]).unwrap()\n    }\n}\n\nimpl<T> FromIterator<T> for Tensor<T>\nwhere\n    T: TensorType + Clone,\n    Vec<T>: FromIterator<T>,\n{\n    fn from_iter<I: IntoIterator<Item = T>>(value: I) -> Tensor<T> {\n        let data: Vec<I::Item> = value.into_iter().collect::<Vec<I::Item>>();\n        Tensor::new(Some(&data), &[data.len()]).unwrap()\n    }\n}\n\nimpl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<Assigned<F>, F>>>\n    for Tensor<i32>\n{\n    fn from(value: Tensor<AssignedCell<Assigned<F>, F>>) -> Tensor<i32> {\n        let mut output = Vec::new();\n        value.map(|x| {\n            x.evaluate().value().map(|y| {\n                let e = felt_to_i32(*y);\n                output.push(e);\n                e\n            })\n        });\n        Tensor::new(Some(&output), value.dims()).unwrap()\n    }\n}\n\nimpl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<F, F>>>\n    for Tensor<i32>\n{\n    fn from(value: Tensor<AssignedCell<F, F>>) -> Tensor<i32> {\n        let mut output = Vec::new();\n        value.map(|x| {\n            let mut i = 0;\n            x.value().map(|y| {\n                let e = felt_to_i32(*y);\n                output.push(e);\n                i += 1;\n            });\n            if i == 0 {\n                output.push(0);\n            }\n        });\n        Tensor::new(Some(&output), value.dims()).unwrap()\n    }\n}\n\nimpl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<Assigned<F>, F>>>\n    for Tensor<Value<F>>\n{\n    fn from(value: Tensor<AssignedCell<Assigned<F>, F>>) -> Tensor<Value<F>> {\n        let mut output = Vec::new();\n        for x in value.iter() {\n            output.push(x.value_field().evaluate());\n        }\n        Tensor::new(Some(&output), value.dims()).unwrap()\n    }\n}\n\nimpl<F: PrimeField + TensorType + Clone + PartialOrd> From<Tensor<Value<F>>> for Tensor<i32> {\n    fn from(t: Tensor<Value<F>>) -> Tensor<i32> {\n        let mut output = Vec::new();\n        t.map(|x| {\n            let mut i = 0;\n            x.map(|y| {\n                let e = felt_to_i32(y);\n                output.push(e);\n                i += 1;\n            });\n            if i == 0 {\n                output.push(0);\n            }\n        });\n        Tensor::new(Some(&output), t.dims()).unwrap()\n    }\n}\n\nimpl<F: PrimeField + TensorType + Clone + PartialOrd> From<Tensor<Value<F>>>\n    for Tensor<Value<Assigned<F>>>\n{\n    fn from(t: Tensor<Value<F>>) -> Tensor<Value<Assigned<F>>> {\n        let mut ta: Tensor<Value<Assigned<F>>> = Tensor::from((0..t.len()).map(|i| t[i].into()));\n        // safe to unwrap as we know the dims are correct\n        ta.reshape(t.dims()).unwrap();\n        ta\n    }\n}\n\nimpl<F: PrimeField + TensorType + Clone> From<Tensor<i32>> for Tensor<Value<F>> {\n    fn from(t: Tensor<i32>) -> Tensor<Value<F>> {\n        let mut ta: Tensor<Value<F>> =\n            Tensor::from((0..t.len()).map(|i| Value::known(i32_to_felt::<F>(t[i]))));\n        // safe to unwrap as we know the dims are correct\n        ta.reshape(t.dims()).unwrap();\n        ta\n    }\n}\n\nimpl<F: PrimeField + TensorType + Clone> From<Tensor<i128>> for Tensor<Value<F>> {\n    fn from(t: Tensor<i128>) -> Tensor<Value<F>> {\n        let mut ta: Tensor<Value<F>> =\n            Tensor::from((0..t.len()).map(|i| Value::known(i128_to_felt::<F>(t[i]))));\n        // safe to unwrap as we know the dims are correct\n        ta.reshape(t.dims()).unwrap();\n        ta\n    }\n}\n\nimpl<T: Clone + TensorType + std::marker::Send + std::marker::Sync>\n    maybe_rayon::iter::FromParallelIterator<T> for Tensor<T>\n{\n    fn from_par_iter<I>(par_iter: I) -> Self\n    where\n        I: maybe_rayon::iter::IntoParallelIterator<Item = T>,\n    {\n        let inner: Vec<T> = par_iter.into_par_iter().collect();\n        Tensor::new(Some(&inner), &[inner.len()]).unwrap()\n    }\n}\n\nimpl<T: Clone + TensorType + std::marker::Send + std::marker::Sync>\n    maybe_rayon::iter::IntoParallelIterator for Tensor<T>\n{\n    type Iter = maybe_rayon::vec::IntoIter<T>;\n    type Item = T;\n    fn into_par_iter(self) -> Self::Iter {\n        self.inner.into_par_iter()\n    }\n}\n\nimpl<'data, T: Clone + TensorType + std::marker::Send + std::marker::Sync>\n    maybe_rayon::iter::IntoParallelRefMutIterator<'data> for Tensor<T>\n{\n    type Iter = maybe_rayon::slice::IterMut<'data, T>;\n    type Item = &'data mut T;\n    fn par_iter_mut(&'data mut self) -> Self::Iter {\n        self.inner.par_iter_mut()\n    }\n}\n\nimpl<T: Clone + TensorType> Tensor<T> {\n    /// Sets (copies) the tensor values to the provided ones.\n    pub fn new(values: Option<&[T]>, dims: &[usize]) -> Result<Self, TensorError> {\n        let total_dims: usize = if !dims.is_empty() {\n            dims.iter().product()\n        } else if values.is_some() {\n            1\n        } else {\n            0\n        };\n        match values {\n            Some(v) => {\n                if total_dims != v.len() {\n                    return Err(TensorError::DimError(format!(\n                        \"Cannot create tensor of length {} with dims {:?}\",\n                        v.len(),\n                        dims\n                    )));\n                }\n                Ok(Tensor {\n                    inner: Vec::from(v),\n                    dims: Vec::from(dims),\n                    scale: None,\n                    visibility: None,\n                })\n            }\n            None => Ok(Tensor {\n                inner: vec![T::zero().unwrap(); total_dims],\n                dims: Vec::from(dims),\n                scale: None,\n                visibility: None,\n            }),\n        }\n    }\n\n    /// set the tensor's (optional) scale parameter\n    pub fn set_scale(&mut self, scale: crate::Scale) {\n        self.scale = Some(scale)\n    }\n\n    /// set the tensor's (optional) visibility parameter\n    pub fn set_visibility(&mut self, visibility: &Visibility) {\n        self.visibility = Some(visibility.clone())\n    }\n\n    /// getter for scale\n    pub fn scale(&self) -> Option<crate::Scale> {\n        self.scale\n    }\n\n    /// getter for visibility\n    pub fn visibility(&self) -> Option<Visibility> {\n        self.visibility.clone()\n    }\n\n    /// Returns the number of elements in the tensor.\n    pub fn len(&self) -> usize {\n        self.dims().iter().product::<usize>()\n    }\n    /// Checks if the number of elements in tensor is 0.\n    pub fn is_empty(&self) -> bool {\n        self.inner.len() == 0\n    }\n\n    /// Checks if the number of elements in tensor is 1 but with an empty dimension (this is for onnx compatibility).\n    pub fn is_singleton(&self) -> bool {\n        self.dims().is_empty() && self.len() == 1\n    }\n\n    /// Set one single value on the tensor.\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(None, &[3, 3, 3]).unwrap();\n    ///\n    /// a.set(&[0, 0, 1], 10);\n    /// assert_eq!(a[0 + 0 + 1], 10);\n    ///\n    /// a.set(&[2, 2, 0], 9);\n    /// assert_eq!(a[2*9 + 2*3 + 0], 9);\n    /// ```\n    pub fn set(&mut self, indices: &[usize], value: T) {\n        let index = self.get_index(indices);\n        self[index] = value;\n    }\n\n    /// Get a single value from the Tensor.\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();\n    ///\n    /// a[1*15 + 1*5 + 1] = 5;\n    /// assert_eq!(a.get(&[1, 1, 1]), 5);\n    /// ```\n    pub fn get(&self, indices: &[usize]) -> T {\n        let index = self.get_index(indices);\n        self[index].clone()\n    }\n\n    /// Get a mutable array index from rows / columns indices.\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();\n    ///\n    /// a[1*15 + 1*5 + 1] = 5;\n    /// assert_eq!(a.get(&[1, 1, 1]), 5);\n    /// ```\n    pub fn get_mut(&mut self, indices: &[usize]) -> &mut T {\n        assert_eq!(self.dims.len(), indices.len());\n        let mut index = 0;\n        let mut d = 1;\n        for i in (0..indices.len()).rev() {\n            assert!(self.dims[i] > indices[i]);\n            index += indices[i] * d;\n            d *= self.dims[i];\n        }\n        &mut self[index]\n    }\n\n    /// Pad to a length that is divisible by n\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1,2,3,4,5,6]), &[2, 3]).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 0]), &[8]).unwrap();\n    /// assert_eq!(a.pad_to_zero_rem(4, 0).unwrap(), expected);\n    ///\n    /// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 0, 0]), &[9]).unwrap();\n    /// assert_eq!(a.pad_to_zero_rem(9, 0).unwrap(), expected);\n    /// ```\n    pub fn pad_to_zero_rem(&self, n: usize, pad: T) -> Result<Tensor<T>, TensorError> {\n        let mut inner = self.inner.clone();\n        let remainder = self.len() % n;\n        if remainder != 0 {\n            inner.resize(self.len() + n - remainder, pad);\n        }\n        Tensor::new(Some(&inner), &[inner.len()])\n    }\n\n    /// Get a single value from the Tensor.\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();\n    ///\n    /// let flat_index = 1*15 + 1*5 + 1;\n    /// a[1*15 + 1*5 + 1] = 5;\n    /// assert_eq!(a.get_flat_index(flat_index), 5);\n    /// ```\n    pub fn get_flat_index(&self, index: usize) -> T {\n        self[index].clone()\n    }\n\n    /// Display a tensor\n    pub fn show(&self) -> String {\n        if self.len() > 12 {\n            let start = self[..12].to_vec();\n            // print the two split by ... in the middle\n            format!(\n                \"[{} ...]\",\n                start.iter().map(|x| format!(\"{:?}\", x)).join(\", \"),\n            )\n        } else {\n            format!(\"[{:?}]\", self.iter().map(|x| format!(\"{:?}\", x)).join(\", \"))\n        }\n    }\n\n    /// Get a slice from the Tensor.\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();\n    /// let mut b = Tensor::<i32>::new(Some(&[1, 2]), &[2]).unwrap();\n    ///\n    /// assert_eq!(a.get_slice(&[0..2]).unwrap(), b);\n    /// ```\n    pub fn get_slice(&self, indices: &[Range<usize>]) -> Result<Tensor<T>, TensorError>\n    where\n        T: Send + Sync,\n    {\n        if indices.is_empty() {\n            return Ok(self.clone());\n        }\n        if self.dims.len() < indices.len() {\n            return Err(TensorError::DimError(format!(\n                \"The dimensionality of the slice {:?} is greater than the tensor's {:?}\",\n                indices, self.dims\n            )));\n        } else if indices.iter().map(|x| x.end - x.start).collect::<Vec<_>>() == self.dims {\n            // else if slice is the same as dims, return self\n            return Ok(self.clone());\n        }\n\n        // if indices weren't specified we fill them in as required\n        let mut full_indices = indices.to_vec();\n\n        for i in 0..(self.dims.len() - indices.len()) {\n            full_indices.push(0..self.dims()[indices.len() + i])\n        }\n\n        let cartesian_coord: Vec<Vec<usize>> = full_indices\n            .iter()\n            .cloned()\n            .multi_cartesian_product()\n            .collect();\n\n        let res: Vec<T> = cartesian_coord\n            .par_iter()\n            .map(|e| {\n                let index = self.get_index(e);\n                self[index].clone()\n            })\n            .collect();\n\n        let dims: Vec<usize> = full_indices.iter().map(|e| e.end - e.start).collect();\n\n        Tensor::new(Some(&res), &dims)\n    }\n\n    /// Set a slice of the Tensor.\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();\n    /// let b = Tensor::<i32>::new(Some(&[1, 2, 3, 1, 2, 3]), &[2, 3]).unwrap();\n    /// a.set_slice(&[1..2], &Tensor::<i32>::new(Some(&[1, 2, 3]), &[1, 3]).unwrap()).unwrap();\n    /// assert_eq!(a, b);\n    /// ```\n    pub fn set_slice(\n        &mut self,\n        indices: &[Range<usize>],\n        value: &Tensor<T>,\n    ) -> Result<(), TensorError>\n    where\n        T: Send + Sync,\n    {\n        if indices.is_empty() {\n            return Ok(());\n        }\n        if self.dims.len() < indices.len() {\n            return Err(TensorError::DimError(format!(\n                \"The dimensionality of the slice {:?} is greater than the tensor's {:?}\",\n                indices, self.dims\n            )));\n        }\n\n        // if indices weren't specified we fill them in as required\n        let mut full_indices = indices.to_vec();\n\n        let omitted_dims = (indices.len()..self.dims.len())\n            .map(|i| self.dims[i])\n            .collect::<Vec<_>>();\n\n        for dim in &omitted_dims {\n            full_indices.push(0..*dim);\n        }\n\n        let full_dims = full_indices\n            .iter()\n            .map(|x| x.end - x.start)\n            .collect::<Vec<_>>();\n\n        // now broadcast the value to the full dims\n        let value = value.expand(&full_dims)?;\n\n        let cartesian_coord: Vec<Vec<usize>> = full_indices\n            .iter()\n            .cloned()\n            .multi_cartesian_product()\n            .collect();\n\n        let _ = cartesian_coord\n            .iter()\n            .enumerate()\n            .map(|(i, e)| {\n                self.set(e, value[i].clone());\n            })\n            .collect::<Vec<_>>();\n\n        Ok(())\n    }\n\n    /// Get the array index from rows / columns indices.\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();\n    ///\n    /// assert_eq!(a.get_index(&[2, 2, 2]), 26);\n    /// assert_eq!(a.get_index(&[1, 2, 2]), 17);\n    /// assert_eq!(a.get_index(&[1, 2, 0]), 15);\n    /// assert_eq!(a.get_index(&[1, 0, 1]), 10);\n    /// ```\n    pub fn get_index(&self, indices: &[usize]) -> usize {\n        assert_eq!(self.dims.len(), indices.len());\n        let mut index = 0;\n        let mut d = 1;\n        for i in (0..indices.len()).rev() {\n            assert!(self.dims[i] > indices[i]);\n            index += indices[i] * d;\n            d *= self.dims[i];\n        }\n        index\n    }\n\n    /// Duplicates every nth element\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 4, 5, 5, 6]), &[8]).unwrap();\n    /// assert_eq!(a.duplicate_every_n(3, 1, 0).unwrap(), expected);\n    /// assert_eq!(a.duplicate_every_n(7, 1, 0).unwrap(), a);\n    ///\n    /// let expected = Tensor::<i32>::new(Some(&[1, 1, 2, 3, 3, 4, 5, 5, 6]), &[9]).unwrap();\n    /// assert_eq!(a.duplicate_every_n(3, 1, 2).unwrap(), expected);\n    ///\n    /// ```\n    pub fn duplicate_every_n(\n        &self,\n        n: usize,\n        num_repeats: usize,\n        initial_offset: usize,\n    ) -> Result<Tensor<T>, TensorError> {\n        let mut inner: Vec<T> = vec![];\n        let mut offset = initial_offset;\n        for (i, elem) in self.inner.clone().into_iter().enumerate() {\n            if (i + offset + 1) % n == 0 {\n                inner.extend(vec![elem; 1 + num_repeats]);\n                offset += num_repeats;\n            } else {\n                inner.push(elem.clone());\n            }\n        }\n        Tensor::new(Some(&inner), &[inner.len()])\n    }\n\n    /// Removes every nth element\n    ///\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 4, 5, 6, 6]), &[8]).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 5, 6, 6]), &[7]).unwrap();\n    /// assert_eq!(a.remove_every_n(4, 1, 0).unwrap(), expected);\n    ///\n    ///\n    pub fn remove_every_n(\n        &self,\n        n: usize,\n        num_repeats: usize,\n        initial_offset: usize,\n    ) -> Result<Tensor<T>, TensorError> {\n        let mut inner: Vec<T> = vec![];\n        let mut indices_to_remove = std::collections::HashSet::new();\n        for i in 0..self.inner.len() {\n            if (i + initial_offset + 1) % n == 0 {\n                for j in 1..(1 + num_repeats) {\n                    indices_to_remove.insert(i + j);\n                }\n            }\n        }\n\n        let old_inner = self.inner.clone();\n        for (i, elem) in old_inner.into_iter().enumerate() {\n            if !indices_to_remove.contains(&i) {\n                inner.push(elem.clone());\n            }\n        }\n\n        Tensor::new(Some(&inner), &[inner.len()])\n    }\n\n    /// Remove indices\n    /// WARN: assumes indices are in ascending order for speed\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 6]), &[4]).unwrap();\n    /// let mut indices = vec![3, 4];\n    /// assert_eq!(a.remove_indices(&mut indices, true).unwrap(), expected);\n    ///\n    ///\n    /// let a = Tensor::<i32>::new(Some(&[52, -245, 153, 13, -4, -56, -163, 249, -128, -172, 396, 143, 2, -96, 504, -44, -158, -393, 61, 95, 191, 74, 64, -219, 553, 104, 235, 222, 44, -216, 63, -251, 40, -140, 112, -355, 60, 123, 26, -116, -89, -200, -109, 168, 135, -34, -99, -54, 5, -81, 322, 87, 4, -139, 420, 92, -295, -12, 262, -1, 26, -48, 231, 1, -335, 244, 188, -4, 5, -362, 57, -198, -184, -117, 40, 305, 49, 30, -59, -26, -37, 96]), &[82]).unwrap();\n    /// let b = Tensor::<i32>::new(Some(&[52, -245, 153, 13, -4, -56, -163, 249, -128, -172, 396, 143, 2, -96, 504, -44, -158, -393, 61, 95, 191, 74, 64, -219, 553, 104, 235, 222, 44, -216, 63, -251, 40, -140, 112, -355, 60, 123, 26, -116, -89, -200, -109, 168, 135, -34, -99, -54, 5, -81, 322, 87, 4, -139, 420, 92, -295, -12, 262, -1, 26, -48, 231, -335, 244, 188, 5, -362, 57, -198, -184, -117, 40, 305, 49, 30, -59, -26, -37, 96]), &[80]).unwrap();\n    /// let mut indices = vec![63, 67];\n    /// assert_eq!(a.remove_indices(&mut indices, true).unwrap(), b);\n    /// ```\n    pub fn remove_indices(\n        &self,\n        indices: &mut [usize],\n        is_sorted: bool,\n    ) -> Result<Tensor<T>, TensorError> {\n        let mut inner: Vec<T> = self.inner.clone();\n        // time it\n        if !is_sorted {\n            indices.par_sort_unstable();\n        }\n        // remove indices\n        for elem in indices.iter().rev() {\n            inner.remove(*elem);\n        }\n\n        Tensor::new(Some(&inner), &[inner.len()])\n    }\n\n    /// Returns the tensor's dimensions.\n    pub fn dims(&self) -> &[usize] {\n        &self.dims\n    }\n\n    ///Reshape the tensor\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();\n    /// a.reshape(&[9, 3]);\n    /// assert_eq!(a.dims(), &[9, 3]);\n    /// ```\n    pub fn reshape(&mut self, new_dims: &[usize]) -> Result<(), TensorError> {\n        // in onnx parlance this corresponds to converting a tensor to a single element\n        if new_dims.is_empty() {\n            if !(self.len() == 1 || self.is_empty()) {\n                return Err(TensorError::DimError(\n                    \"Cannot reshape to empty tensor\".to_string(),\n                ));\n            }\n            self.dims = vec![];\n        } else {\n            let product = if new_dims != [0] {\n                new_dims.iter().product::<usize>()\n            } else {\n                0\n            };\n            if self.len() != product {\n                return Err(TensorError::DimError(format!(\n                    \"Cannot reshape tensor of length {} to {:?}\",\n                    self.len(),\n                    new_dims\n                )));\n            }\n            self.dims = Vec::from(new_dims);\n        }\n        Ok(())\n    }\n\n    /// Move axis of the tensor\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();\n    /// let b = a.move_axis(0, 2).unwrap();\n    /// assert_eq!(b.dims(), &[3, 3, 3]);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 1, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6]), &[1, 2, 3]).unwrap();\n    /// let b = a.move_axis(0, 2).unwrap();\n    /// assert_eq!(b, expected);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();\n    /// let b = a.move_axis(1, 2).unwrap();\n    /// assert_eq!(b, expected);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();\n    /// let b = a.move_axis(2, 1).unwrap();\n    /// assert_eq!(b, expected);\n    /// ```\n    pub fn move_axis(&mut self, source: usize, destination: usize) -> Result<Self, TensorError> {\n        assert!(source < self.dims.len());\n        assert!(destination < self.dims.len());\n\n        let mut new_dims = self.dims.clone();\n        new_dims.remove(source);\n        new_dims.insert(destination, self.dims[source]);\n\n        // now reconfigure the elements appropriately in the new array\n        //  eg. if we have a 3x3x3 array and we want to move the 0th axis to the 2nd position\n        //  we need to move the elements at 0, 1, 2, 3, 4, 5, 6, 7, 8 to 0, 3, 6, 1, 4, 7, 2, 5, 8\n        //  so we need to move the elements at 0, 1, 2 to 0, 3, 6\n        //  and the elements at 3, 4, 5 to 1, 4, 7\n        //  and the elements at 6, 7, 8 to 2, 5, 8\n        let cartesian_coords = new_dims\n            .iter()\n            .map(|d| 0..*d)\n            .multi_cartesian_product()\n            .collect::<Vec<Vec<usize>>>();\n\n        let mut output = Tensor::new(None, &new_dims)?;\n\n        for coord in cartesian_coords {\n            let mut old_coord = vec![0; self.dims.len()];\n\n            // now fetch the old index\n            for (i, c) in coord.iter().enumerate() {\n                if i == destination {\n                    old_coord[source] = *c;\n                } else if i == source && source < destination {\n                    old_coord[source + 1] = *c;\n                } else if i == source && source > destination {\n                    old_coord[source - 1] = *c;\n                } else if (i < source && source < destination)\n                    || (i < destination && source > destination)\n                    || (i > source && source > destination)\n                    || (i > destination && source < destination)\n                {\n                    old_coord[i] = *c;\n                } else if i > source && source < destination {\n                    old_coord[i + 1] = *c;\n                } else if i > destination && source > destination {\n                    old_coord[i - 1] = *c;\n                } else {\n                    return Err(TensorError::DimError(\n                        \"Unknown condition for moving the axis\".to_string(),\n                    ));\n                }\n            }\n\n            let value = self.get(&old_coord);\n\n            output.set(&coord, value);\n        }\n\n        Ok(output)\n    }\n\n    /// Swap axes of the tensor\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();\n    /// let b = a.swap_axes(0, 2).unwrap();\n    /// assert_eq!(b.dims(), &[3, 3, 3]);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 1, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6]), &[2, 1, 3]).unwrap();\n    /// let b = a.swap_axes(0, 2).unwrap();\n    /// assert_eq!(b, expected);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();\n    /// let b = a.swap_axes(1, 2).unwrap();\n    /// assert_eq!(b, expected);\n    ///\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();\n    /// let b = a.swap_axes(2, 1).unwrap();\n    /// assert_eq!(b, expected);\n    /// ```\n    pub fn swap_axes(&mut self, source: usize, destination: usize) -> Result<Self, TensorError> {\n        assert!(source < self.dims.len());\n        assert!(destination < self.dims.len());\n        let mut new_dims = self.dims.clone();\n        new_dims[source] = self.dims[destination];\n        new_dims[destination] = self.dims[source];\n\n        // now reconfigure the elements appropriately in the new array\n        //  eg. if we have a 3x3x3 array and we want to move the 0th axis to the 2nd position\n        //  we need to move the elements at 0, 1, 2, 3, 4, 5, 6, 7, 8 to 0, 3, 6, 1, 4, 7, 2, 5, 8\n        //  so we need to move the elements at 0, 1, 2 to 0, 3, 6\n        //  and the elements at 3, 4, 5 to 1, 4, 7\n        //  and the elements at 6, 7, 8 to 2, 5, 8\n        let cartesian_coords = new_dims\n            .iter()\n            .map(|d| 0..*d)\n            .multi_cartesian_product()\n            .collect::<Vec<Vec<usize>>>();\n\n        let mut output = Tensor::new(None, &new_dims)?;\n\n        for coord in cartesian_coords {\n            let mut old_coord = vec![0; self.dims.len()];\n\n            // now fetch the old index\n            for (i, c) in coord.iter().enumerate() {\n                if i == destination {\n                    old_coord[source] = *c;\n                } else if i == source {\n                    old_coord[destination] = *c;\n                } else {\n                    old_coord[i] = *c;\n                }\n            }\n            output.set(&coord, self.get(&old_coord));\n        }\n\n        Ok(output)\n    }\n\n    /// Broadcasts the tensor to a given shape\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3, 1]).unwrap();\n    ///\n    /// let mut expected = Tensor::<i32>::new(Some(&[1, 1, 1, 2, 2, 2, 3, 3, 3]), &[3, 3]).unwrap();\n    /// assert_eq!(a.expand(&[3, 3]).unwrap(), expected);\n    ///\n    /// ```\n    pub fn expand(&self, shape: &[usize]) -> Result<Self, TensorError> {\n        if self.dims().len() > shape.len() {\n            return Err(TensorError::DimError(format!(\n                \"Cannot expand {:?} to the smaller shape {:?}\",\n                self.dims(),\n                shape\n            )));\n        }\n\n        if shape == self.dims() {\n            return Ok(self.clone());\n        }\n\n        for d in self.dims() {\n            if !(shape.contains(d) || *d == 1) {\n                return Err(TensorError::DimError(format!(\n                    \"The current dimension {} must be contained in the new shape {:?} or be 1\",\n                    d, shape\n                )));\n            }\n        }\n\n        let cartesian_coords = shape\n            .iter()\n            .map(|d| 0..*d)\n            .multi_cartesian_product()\n            .collect::<Vec<Vec<usize>>>();\n\n        let mut output = Tensor::new(None, shape)?;\n\n        for coord in cartesian_coords {\n            let mut new_coord = Vec::with_capacity(self.dims().len());\n            for (i, c) in coord.iter().enumerate() {\n                if i < self.dims().len() && self.dims()[i] == 1 {\n                    new_coord.push(0);\n                } else if i >= self.dims().len() {\n                    // do nothing at this point does not exist in the original tensor\n                } else {\n                    new_coord.push(*c);\n                }\n            }\n            output.set(&coord, self.get(&new_coord));\n        }\n\n        Ok(output)\n    }\n\n    ///Flatten the tensor shape\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();\n    /// a.flatten();\n    /// assert_eq!(a.dims(), &[27]);\n    /// ```\n    pub fn flatten(&mut self) {\n        if !self.dims().is_empty() && (self.dims() != [0]) {\n            self.dims = Vec::from([self.dims.iter().product::<usize>()]);\n        }\n    }\n\n    /// Maps a function to tensors\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();\n    /// let mut c = a.map(|x| i32::pow(x,2));\n    /// assert_eq!(c, Tensor::from([1, 16].into_iter()))\n    /// ```\n    pub fn map<F: FnMut(T) -> G, G: TensorType>(&self, mut f: F) -> Tensor<G> {\n        let mut t = Tensor::from(self.inner.iter().map(|e| f(e.clone())));\n        // safe to unwrap as we know the dims are correct\n        t.reshape(self.dims()).unwrap();\n        t\n    }\n\n    /// Maps a function to tensors and enumerates\n    /// ```\n    /// use ezkl::tensor::{Tensor, TensorError};\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();\n    /// let mut c = a.enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();\n    /// assert_eq!(c, Tensor::from([1, 25].into_iter()));\n    /// ```\n    pub fn enum_map<F: FnMut(usize, T) -> Result<G, E>, G: TensorType, E: Error>(\n        &self,\n        mut f: F,\n    ) -> Result<Tensor<G>, E> {\n        let vec: Result<Vec<G>, E> = self\n            .inner\n            .iter()\n            .enumerate()\n            .map(|(i, e)| f(i, e.clone()))\n            .collect();\n        let mut t: Tensor<G> = Tensor::from(vec?.iter().cloned());\n        // safe to unwrap as we know the dims are correct\n        t.reshape(self.dims()).unwrap();\n        Ok(t)\n    }\n\n    /// Maps a function to tensors and enumerates in parallel\n    /// ```\n    /// use ezkl::tensor::{Tensor, TensorError};\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();\n    /// let mut c = a.par_enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();\n    /// assert_eq!(c, Tensor::from([1, 25].into_iter()));\n    /// ```\n    pub fn par_enum_map<\n        F: Fn(usize, T) -> Result<G, E> + std::marker::Send + std::marker::Sync,\n        G: TensorType + std::marker::Send + std::marker::Sync,\n        E: Error + std::marker::Send + std::marker::Sync,\n    >(\n        &self,\n        f: F,\n    ) -> Result<Tensor<G>, E>\n    where\n        T: std::marker::Send + std::marker::Sync,\n    {\n        let vec: Result<Vec<G>, E> = self\n            .inner\n            .par_iter()\n            .enumerate()\n            .map(move |(i, e)| f(i, e.clone()))\n            .collect();\n        let mut t: Tensor<G> = Tensor::from(vec?.iter().cloned());\n        // safe to unwrap as we know the dims are correct\n        t.reshape(self.dims()).unwrap();\n        Ok(t)\n    }\n\n    /// Maps a function to tensors and enumerates in parallel\n    /// ```\n    /// use ezkl::tensor::{Tensor, TensorError};\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();\n    /// let mut c = a.par_enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();\n    /// assert_eq!(c, Tensor::from([1, 25].into_iter()));\n    /// ```\n    pub fn par_enum_map_mut_filtered<\n        F: Fn(usize) -> Result<T, E> + std::marker::Send + std::marker::Sync,\n        E: Error + std::marker::Send + std::marker::Sync,\n    >(\n        &mut self,\n        filter_indices: &std::collections::HashSet<&usize>,\n        f: F,\n    ) -> Result<(), E>\n    where\n        T: std::marker::Send + std::marker::Sync,\n    {\n        self.inner\n            .par_iter_mut()\n            .enumerate()\n            .filter(|(i, _)| filter_indices.contains(i))\n            .for_each(move |(i, e)| *e = f(i).unwrap());\n        Ok(())\n    }\n}\n\nimpl<T: Clone + TensorType> Tensor<Tensor<T>> {\n    /// Flattens a tensor of tensors\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();\n    /// let mut b = Tensor::<i32>::new(Some(&[1, 4]), &[2, 1]).unwrap();\n    /// let mut c = Tensor::new(Some(&[a,b]), &[2]).unwrap();\n    /// let mut d = c.combine().unwrap();\n    /// assert_eq!(d.dims(), &[8]);\n    /// ```\n    pub fn combine(&self) -> Result<Tensor<T>, TensorError> {\n        let mut dims = 0;\n        let mut inner = Vec::new();\n        for t in self.inner.clone().into_iter() {\n            dims += t.len();\n            inner.extend(t.inner);\n        }\n        Tensor::new(Some(&inner), &[dims])\n    }\n}\n\nimpl<T: TensorType + Add<Output = T> + std::marker::Send + std::marker::Sync> Add for Tensor<T> {\n    type Output = Result<Tensor<T>, TensorError>;\n    /// Adds tensors.\n    /// # Arguments\n    ///\n    /// * `self` - Tensor\n    /// * `rhs` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Add;\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 3, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = x.add(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 4, 4, 2, 2, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // Now test 1D casting\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2]),\n    ///     &[1]).unwrap();\n    /// let result = x.add(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 3, 3, 3]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    ///\n    /// // Now test 2D casting\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 3]),\n    ///     &[2]).unwrap();\n    /// let result = x.add(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 4, 4, 4]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn add(self, rhs: Self) -> Self::Output {\n        let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();\n        let mut lhs = self.expand(&broadcasted_shape).unwrap();\n        let rhs = rhs.expand(&broadcasted_shape).unwrap();\n\n        lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {\n            *o = o.clone() + r;\n        });\n\n        Ok(lhs)\n    }\n}\n\nimpl<T: TensorType + Neg<Output = T> + std::marker::Send + std::marker::Sync> Neg for Tensor<T> {\n    type Output = Tensor<T>;\n    /// Negates a tensor.\n    /// # Arguments\n    /// * `self` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Neg;\n    /// let x = Tensor::<i32>::new(\n    ///    Some(&[2, 1, 2, 1, 1, 1]),\n    ///   &[2, 3],\n    /// ).unwrap();\n    /// let result = x.neg();\n    /// let expected = Tensor::<i32>::new(Some(&[-2, -1, -2, -1, -1, -1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn neg(self) -> Self {\n        let mut output = self;\n        output.par_iter_mut().for_each(|x| {\n            *x = x.clone().neg();\n        });\n        output\n    }\n}\n\nimpl<T: TensorType + Sub<Output = T> + std::marker::Send + std::marker::Sync> Sub for Tensor<T> {\n    type Output = Result<Tensor<T>, TensorError>;\n    /// Subtracts tensors.\n    /// # Arguments\n    ///\n    /// * `self` - Tensor\n    /// * `rhs` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Sub;\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 3, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = x.sub(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[0, -2, 0, 0, 0, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // Now test 1D sub\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2]),\n    ///     &[1],\n    /// ).unwrap();\n    /// let result = x.sub(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[0, -1, 0, -1, -1, -1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // Now test 2D sub\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 3]),\n    ///     &[2],\n    /// ).unwrap();\n    /// let result = x.sub(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[0, -1, 0, -2, -2, -2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn sub(self, rhs: Self) -> Self::Output {\n        let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();\n        let mut lhs = self.expand(&broadcasted_shape).unwrap();\n        let rhs = rhs.expand(&broadcasted_shape).unwrap();\n\n        lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {\n            *o = o.clone() - r;\n        });\n\n        Ok(lhs)\n    }\n}\n\nimpl<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync> Mul for Tensor<T> {\n    type Output = Result<Tensor<T>, TensorError>;\n    /// Elementwise multiplies tensors.\n    /// # Arguments\n    ///\n    /// * `self` - Tensor\n    /// * `rhs` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Mul;\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 3, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = x.mul(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 1, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // Now test 1D mult\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2]),\n    ///     &[1]).unwrap();\n    /// let result = x.mul(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // Now test 2D mult\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = Tensor::<i32>::new(\n    ///     Some(&[2, 2]),\n    ///     &[2]).unwrap();\n    /// let result = x.mul(k).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn mul(self, rhs: Self) -> Self::Output {\n        let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();\n        let mut lhs = self.expand(&broadcasted_shape).unwrap();\n        let rhs = rhs.expand(&broadcasted_shape).unwrap();\n\n        lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {\n            *o = o.clone() * r;\n        });\n\n        Ok(lhs)\n    }\n}\n\nimpl<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync> Tensor<T> {\n    /// Elementwise raise a tensor to the nth power.\n    /// # Arguments\n    ///\n    /// * `self` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Mul;\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = x.pow(3).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[8, 3375, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn pow(&self, mut exp: u32) -> Result<Self, TensorError> {\n        // calculate value of output\n        let mut base = self.clone();\n        let mut acc = base.map(|_| T::one().unwrap());\n\n        while exp > 1 {\n            if (exp & 1) == 1 {\n                acc = acc.mul(base.clone())?;\n            }\n            exp /= 2;\n            base = base.clone().mul(base)?;\n        }\n\n        // since exp!=0, finally the exp must be 1.\n        // Deal with the final bit of the exponent separately, since\n        // squaring the base afterwards is not necessary and may cause a\n        // needless overflow.\n        acc.mul(base)\n    }\n}\n\nimpl<T: TensorType + Div<Output = T> + std::marker::Send + std::marker::Sync> Div for Tensor<T> {\n    type Output = Result<Tensor<T>, TensorError>;\n    /// Elementwise divide a tensor with another tensor.\n    /// # Arguments\n    ///\n    /// * `self` - Tensor\n    /// * `rhs` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Div;\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[4, 1, 4, 1, 1, 4]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let y = Tensor::<i32>::new(\n    ///     Some(&[2, 1, 2, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = x.div(y).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[2, 1, 2, 1, 1, 4]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// // test 1D casting\n    /// let x = Tensor::<i32>::new(\n    ///     Some(&[4, 1, 4, 1, 1, 4]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let y = Tensor::<i32>::new(\n    ///     Some(&[2]),\n    ///     &[1],\n    /// ).unwrap();\n    /// let result = x.div(y).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[2, 0, 2, 0, 0, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn div(self, rhs: Self) -> Self::Output {\n        let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();\n        let mut lhs = self.expand(&broadcasted_shape).unwrap();\n        let rhs = rhs.expand(&broadcasted_shape).unwrap();\n\n        lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {\n            *o = o.clone() / r;\n        });\n\n        Ok(lhs)\n    }\n}\n\n// implement remainder\nimpl<T: TensorType + Rem<Output = T> + std::marker::Send + std::marker::Sync> Rem for Tensor<T> {\n    type Output = Result<Tensor<T>, TensorError>;\n\n    /// Elementwise remainder of a tensor with another tensor.\n    /// # Arguments\n    /// * `self` - Tensor\n    /// * `rhs` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use std::ops::Rem;\n    /// let x = Tensor::<i32>::new(\n    ///    Some(&[4, 1, 4, 1, 1, 4]),\n    ///   &[2, 3],\n    /// ).unwrap();\n    /// let y = Tensor::<i32>::new(\n    ///    Some(&[2, 1, 2, 1, 1, 1]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = x.rem(y).unwrap();\n    /// let expected = Tensor::<i32>::new(Some(&[0, 0, 0, 0, 0, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    fn rem(self, rhs: Self) -> Self::Output {\n        let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();\n        let mut lhs = self.expand(&broadcasted_shape).unwrap();\n        let rhs = rhs.expand(&broadcasted_shape).unwrap();\n\n        lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {\n            *o = o.clone() % r;\n        });\n\n        Ok(lhs)\n    }\n}\n\n/// Returns the broadcasted shape of two tensors\n/// ```\n/// use ezkl::tensor::get_broadcasted_shape;\n/// let a = vec![2, 3];\n/// let b = vec![2, 3];\n/// let c = get_broadcasted_shape(&a, &b).unwrap();\n/// assert_eq!(c, vec![2, 3]);\n///\n/// let a = vec![2, 3];\n/// let b = vec![3];\n/// let c = get_broadcasted_shape(&a, &b).unwrap();\n/// assert_eq!(c, vec![2, 3]);\n///\n/// let a = vec![2, 3];\n/// let b = vec![2, 1];\n/// let c = get_broadcasted_shape(&a, &b).unwrap();\n/// assert_eq!(c, vec![2, 3]);\n///\n/// let a = vec![2, 3];\n/// let b = vec![1, 3];\n/// let c = get_broadcasted_shape(&a, &b).unwrap();\n/// assert_eq!(c, vec![2, 3]);\n///\n/// let a = vec![2, 3];\n/// let b = vec![1, 1];\n/// let c = get_broadcasted_shape(&a, &b).unwrap();\n/// assert_eq!(c, vec![2, 3]);\n///\n/// ```\n\npub fn get_broadcasted_shape(\n    shape_a: &[usize],\n    shape_b: &[usize],\n) -> Result<Vec<usize>, Box<dyn Error>> {\n    let num_dims_a = shape_a.len();\n    let num_dims_b = shape_b.len();\n\n    match (num_dims_a, num_dims_b) {\n        (a, b) if a == b => {\n            let mut broadcasted_shape = Vec::with_capacity(num_dims_a);\n            for (dim_a, dim_b) in shape_a.iter().zip(shape_b.iter()) {\n                let max_dim = dim_a.max(dim_b);\n                broadcasted_shape.push(*max_dim);\n            }\n            Ok(broadcasted_shape)\n        }\n        (a, b) if a < b => Ok(shape_b.to_vec()),\n        (a, b) if a > b => Ok(shape_a.to_vec()),\n        _ => Err(Box::new(TensorError::DimError(\n            \"Unknown condition for broadcasting\".to_string(),\n        ))),\n    }\n}\n////////////////////////\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_tensor() {\n        let data: Vec<f32> = vec![-1.0f32, 0.0, 1.0, 2.5];\n        let tensor = Tensor::<f32>::new(Some(&data), &[2, 2]).unwrap();\n        assert_eq!(&tensor[..], &data[..]);\n    }\n\n    #[test]\n    fn tensor_clone() {\n        let x = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();\n        assert_eq!(x, x.clone());\n    }\n\n    #[test]\n    fn tensor_eq() {\n        let a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();\n        let mut b = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3, 1]).unwrap();\n        b.reshape(&[3]).unwrap();\n        let c = Tensor::<i32>::new(Some(&[1, 2, 4]), &[3]).unwrap();\n        let d = Tensor::<i32>::new(Some(&[1, 2, 4]), &[3, 1]).unwrap();\n        assert_eq!(a, b);\n        assert_ne!(a, c);\n        assert_ne!(a, d);\n    }\n    #[test]\n    fn tensor_slice() {\n        let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();\n        let b = Tensor::<i32>::new(Some(&[1, 4]), &[2, 1]).unwrap();\n        assert_eq!(a.get_slice(&[0..2, 0..1]).unwrap(), b);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/tensor/ops.rs",
        "content": "use super::TensorError;\nuse crate::tensor::{Tensor, TensorType};\nuse itertools::Itertools;\nuse maybe_rayon::{iter::ParallelIterator, prelude::IntoParallelRefIterator};\npub use std::ops::{Add, Mul, Neg, Sub};\n\n/// Trilu operation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `k` - i32\n/// * `upper` - Boolean\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::trilu;\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[1, 3, 2],\n/// ).unwrap();\n/// let result = trilu(&a, 1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 2, 0, 0, 0, 0]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 0, 0]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 3, 4, 5, 6]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);  \n///\n/// let result = trilu(&a, -1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 0, 6]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, -1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 0, 3, 0, 5, 6]), &[1, 3, 2]).unwrap();\n/// assert_eq!(result, expected);  \n///\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[1, 2, 3],\n/// ).unwrap();\n/// let result = trilu(&a, 1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 2, 3, 0, 0, 6]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 5, 6]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 0, 5, 6]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 4, 5, 0]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);  \n///\n/// let result = trilu(&a, -1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, -1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 4, 0, 0]), &[1, 2, 3]).unwrap();\n/// assert_eq!(result, expected);  \n///\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9]),\n/// &[1, 3, 3],\n/// ).unwrap();\n/// let result = trilu(&a, 1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 2, 3, 0, 0, 6, 0, 0, 0]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 5, 6, 7, 8, 9]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 0, 5, 6, 0, 0, 9]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, 0, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 4, 5, 0, 7, 8, 9]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);  \n///\n/// let result = trilu(&a, -1, true).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 8, 9]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = trilu(&a, -1, false).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 4, 0, 0, 7, 8, 0]), &[1, 3, 3]).unwrap();\n/// assert_eq!(result, expected);  \n/// ```\npub fn trilu<T: TensorType + std::marker::Send + std::marker::Sync>(\n    a: &Tensor<T>,\n    k: i32,\n    upper: bool,\n) -> Result<Tensor<T>, TensorError> {\n    let mut output = a.clone();\n\n    // Given a 2-D matrix or batches of 2-D matrices, returns the upper or lower triangular part of the tensor(s).\n    // The attribute \u201cupper\u201d determines whether the upper or lower part is retained.\n    // If set to true, the upper triangular matrix is retained. Lower triangular matrix is retained otherwise.\n    // Default value for the \u201cupper\u201d attribute is true. Trilu takes one input tensor of shape [*, N, M], where * is zero or more batch dimensions.\n    // The upper triangular part consists of the elements on and above the given diagonal (k).\n    // The lower triangular part consists of elements on and below the diagonal. All other elements in the matrix are set to zero.\n\n    let batch_dims = &a.dims()[0..a.dims().len() - 2];\n    let batch_cartiesian = batch_dims.iter().map(|d| 0..*d).multi_cartesian_product();\n\n    for b in batch_cartiesian {\n        for i in 0..a.dims()[1] {\n            for j in 0..a.dims()[2] {\n                let mut coord = b.clone();\n                coord.push(i);\n                coord.push(j);\n                // If k = 0, the triangular part on and above/below the main diagonal is retained.\n\n                if upper {\n                    // If upper is set to true, a positive k retains the upper triangular matrix excluding the main diagonal and (k-1) diagonals above it.\n                    if (j as i32) < (i as i32) + k {\n                        output.set(&coord, T::zero().ok_or(TensorError::Unsupported)?);\n                    }\n                } else {\n                    // If upper is set to false, a positive k retains the lower triangular matrix including the main diagonal and k diagonals above it.\n                    if (j as i32) > (i as i32) + k {\n                        output.set(&coord, T::zero().ok_or(TensorError::Unsupported)?);\n                    }\n                }\n            }\n        }\n    }\n\n    Ok(output)\n}\n\n/// Resize using nearest neighbour interpolation.\n/// # Arguments\n/// * `a` - Tensor\n/// * `scales` - Vector of scales\n/// # Examples\n/// ```\n///\n///\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap();\n/// let result = resize(&a, &[1, 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]), &[2, 6]).unwrap();\n/// assert_eq!(result, expected);\n///\n///\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[2, 3],\n/// ).unwrap();\n/// let result = resize(&a, &[2, 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 4, 4, 5, 5, 6, 6]), &[4, 6]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::resize;\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4]),\n/// &[2, 2],\n/// ).unwrap();\n/// let result = resize(&a, &[2, 2]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4]), &[4, 4]).unwrap();\n/// assert_eq!(result, expected);\n///\n///\n/// let a = Tensor::<i128>::new(\n///   Some(&[1, 2, 3, 4, 5, 6]),\n/// &[3, 2],\n/// ).unwrap();\n/// let result = resize(&a, &[2, 3]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 5, 5, 5, 6, 6, 6]), &[6, 6]).unwrap();\n/// assert_eq!(result, expected);\n///\n///\n/// ```\npub fn resize<T: TensorType + Send + Sync>(\n    a: &Tensor<T>,\n    scales: &[usize],\n) -> Result<Tensor<T>, TensorError> {\n    let mut new_shape = vec![];\n    for (s, d) in scales.iter().zip(a.dims()) {\n        new_shape.push(s * d);\n    }\n\n    let mut output = Tensor::new(None, &new_shape)?;\n\n    let cartesian_coord: Vec<Vec<usize>> = new_shape\n        .iter()\n        .map(|d| (0..*d))\n        .multi_cartesian_product()\n        .collect();\n\n    // resize using nearest neighbour interpolation\n    // (i.e. just copy the value of the nearest neighbour to pad the tensor)\n    output = output.par_enum_map(|i, _| {\n        let mut coord = vec![];\n        for (j, (c, _d)) in cartesian_coord[i].iter().zip(new_shape.iter()).enumerate() {\n            let scale = scales[j];\n            let fragment = c / scale;\n            coord.push(fragment);\n        }\n\n        Ok::<_, TensorError>(a.get(&coord))\n    })?;\n\n    Ok(output)\n}\n\n/// Adds multiple tensors.\n/// # Arguments\n///\n/// * `t` - Vector of tensors\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::add;\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2, 3, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let result = add(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[4, 4, 4, 2, 2, 2]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// // Now test 1D casting\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2]),\n///     &[1]).unwrap();\n/// let result = add(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[4, 3, 4, 3, 3, 3]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn add<T: TensorType + Add<Output = T> + std::marker::Send + std::marker::Sync>(\n    t: &[Tensor<T>],\n) -> Result<Tensor<T>, TensorError> {\n    // calculate value of output\n    let mut output: Tensor<T> = t[0].clone();\n\n    for e in t[1..].iter() {\n        output = output.add(e.clone())?;\n    }\n\n    Ok(output)\n}\n\n/// Subtracts multiple tensors.\n/// # Arguments\n///\n/// * `a` - Tensor\n/// * `b` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::sub;\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2, 3, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let result = sub(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, -2, 0, 0, 0, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// // Now test 1D sub\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2]),\n///     &[1],\n/// ).unwrap();\n/// let result = sub(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, -1, 0, -1, -1, -1]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn sub<T: TensorType + Sub<Output = T> + std::marker::Send + std::marker::Sync>(\n    t: &[Tensor<T>],\n) -> Result<Tensor<T>, TensorError> {\n    // calculate value of output\n    let mut output: Tensor<T> = t[0].clone();\n\n    for e in t[1..].iter() {\n        output = (output - e.clone())?;\n    }\n\n    Ok(output)\n}\n\n/// Elementwise multiplies multiple tensors.\n/// # Arguments\n///\n/// * `t` - Tensors\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::mult;\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2, 3, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let result = mult(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[4, 3, 4, 1, 1, 1]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// // Now test 1D mult\n/// let x = Tensor::<i128>::new(\n///     Some(&[2, 1, 2, 1, 1, 1]),\n///     &[2, 3],\n/// ).unwrap();\n/// let k = Tensor::<i128>::new(\n///     Some(&[2]),\n///     &[1]).unwrap();\n/// let result = mult(&[x, k]).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn mult<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync>(\n    t: &[Tensor<T>],\n) -> Result<Tensor<T>, TensorError> {\n    // calculate value of output\n    let mut output: Tensor<T> = t[0].clone();\n\n    for e in t[1..].iter() {\n        output = (output * e.clone())?;\n    }\n\n    Ok(output)\n}\n\n/// Downsamples a tensor along a dimension.\n/// # Arguments\n/// * `input` - Tensor\n/// * `dim` - Dimension to downsample along\n/// * `stride` - Stride to downsample by\n/// *  `modulo` - Modulo to downsample by\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::downsample;\n/// let x = Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 4, 5, 6]),\n///  &[2, 3],\n/// ).unwrap();\n/// let result = downsample(&x, 0, 1, 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[4, 5, 6]), &[1, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = downsample(&x, 1, 2, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 3, 4, 6]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = downsample(&x, 1, 2, 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 5]), &[2, 1]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = downsample(&x, 1, 2, 2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[3, 6]), &[2, 1]).unwrap();\n/// assert_eq!(result, expected);\npub fn downsample<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    dim: usize,\n    stride: usize,\n    modulo: usize,\n) -> Result<Tensor<T>, TensorError> {\n    let mut output_shape = input.dims().to_vec();\n    // now downsample along axis dim offset by modulo, rounding up (+1 if remaidner is non-zero)\n    let remainder = (input.dims()[dim] - modulo) % stride;\n    let div = (input.dims()[dim] - modulo) / stride;\n    output_shape[dim] = div + (remainder > 0) as usize;\n    let mut output = Tensor::<T>::new(None, &output_shape)?;\n\n    if modulo > input.dims()[dim] {\n        return Err(TensorError::DimMismatch(\"downsample\".to_string()));\n    }\n\n    // now downsample along axis dim offset by modulo\n    let indices = (0..output_shape.len())\n        .map(|i| {\n            if i == dim {\n                let mut index = vec![0; output_shape[i]];\n                for (i, idx) in index.iter_mut().enumerate() {\n                    *idx = i * stride + modulo;\n                }\n                index\n            } else {\n                (0..output_shape[i]).collect_vec()\n            }\n        })\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    output = output.par_enum_map(|i, _: T| {\n        let coord = indices[i].clone();\n        Ok(input.get(&coord))\n    })?;\n\n    Ok(output)\n}\n\n/// Gathers a tensor along a dimension.\n/// # Arguments\n/// * `input` - Tensor\n/// * `dim` - Dimension to gather along\n/// * `index` - Tensor of indices to gather\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::gather;\n/// let x = Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 4, 5, 6]),\n///   &[2, 3],\n/// ).unwrap();\n/// let index = Tensor::<usize>::new(\n///   Some(&[0, 1]),\n///  &[2],\n/// ).unwrap();\n/// let result = gather(&x, &index, 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 4, 5]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn gather<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    index: &Tensor<usize>,\n    dim: usize,\n) -> Result<Tensor<T>, TensorError> {\n    let mut index_clone = index.clone();\n    index_clone.flatten();\n    if index_clone.is_singleton() {\n        index_clone.reshape(&[1])?;\n    }\n\n    // Calculate the output tensor size\n    let mut output_size = input.dims().to_vec();\n    output_size[dim] = index_clone.dims()[0];\n\n    // Allocate memory for the output tensor\n    let mut output = Tensor::new(None, &output_size)?;\n    let cartesian_coord = output_size\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    output = output.par_enum_map(|i, _: T| {\n        let coord = cartesian_coord[i].clone();\n        let index_val = index_clone.get(&[coord[dim]]);\n        let new_coord = coord\n            .iter()\n            .enumerate()\n            .map(|(i, x)| if i == dim { index_val } else { *x })\n            .collect::<Vec<_>>();\n\n        Ok(input.get(&new_coord))\n    })?;\n\n    // Reshape the output tensor\n    if index.is_singleton() {\n        output_size.remove(dim);\n    }\n\n    output.reshape(&output_size)?;\n\n    Ok(output)\n}\n\n/// Scatters a tensor along a dimension.\n/// # Arguments\n/// * `input` - Tensor\n/// * `dim` - Dimension to scatter along\n/// * `index` - Tensor of indices to scatter\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::scatter;\n/// let x = Tensor::<f64>::new(\n///   Some(&[1.0, 2.0, 3.0, 4.0]),\n/// &[2, 2],\n/// ).unwrap();\n/// let src = Tensor::<f64>::new(\n///  Some(&[5.0, 6.0, 7.0, 8.0]),\n/// &[2, 2],\n/// ).unwrap();\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 0, 1, 0]),\n/// &[2, 2],\n/// ).unwrap();\n/// let result = scatter(&x, &index, &src, 0).unwrap();\n/// let expected = Tensor::<f64>::new(Some(&[5.0, 8.0, 7.0, 4.0]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn scatter<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    index: &Tensor<usize>,\n    src: &Tensor<T>,\n    dim: usize,\n) -> Result<Tensor<T>, TensorError> {\n    // Writes all values from the tensor src into self at the indices specified in the index tensor.\n    // For each value in src, its output index is specified by its index in src for dimension != dim and by the corresponding value in index for dimension = dim.\n    assert_eq!(index.dims(), src.dims());\n    // Calculate the output tensor size\n    let src_size = src.dims().to_vec();\n\n    // For a 3-D tensor, self is updated as:\n    // self[index[i][j][k]][j][k] = src[i][j][k]  # if dim == 0\n    // self[i][index[i][j][k]][k] = src[i][j][k]  # if dim == 1\n    // self[i][j][index[i][j][k]] = src[i][j][k]  # if dim == 2\n\n    let mut output = input.clone();\n\n    let cartesian_coord = src_size\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    cartesian_coord.iter().for_each(|coord| {\n        let mut new_coord = coord.clone();\n        let index_val = index.get(coord);\n        new_coord[dim] = index_val;\n        let val = src.get(coord);\n        output.set(&new_coord, val);\n    });\n\n    Ok(output)\n}\n\n/// Gathers a tensor along a dimension.\n/// # Arguments\n/// * `input` - Tensor\n/// * `dim` - Dimension to gather along\n/// * `index` - Tensor of indices to gather\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::gather_elements;\n/// let x = Tensor::<i128>::new(\n///    Some(&[1, 2, 3, 4]),\n///   &[2, 2],\n/// ).unwrap();\n/// let index = Tensor::<usize>::new(\n///   Some(&[0, 0, 1, 0]),\n///  &[2, 2],\n/// ).unwrap();\n/// let result = gather_elements(&x, &index, 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 1, 4, 3]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn gather_elements<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    index: &Tensor<usize>,\n    dim: usize,\n) -> Result<Tensor<T>, TensorError> {\n    // Calculate the output tensor size\n    let output_size = index.dims().to_vec();\n    // same rank\n    assert_eq!(input.dims().len(), index.dims().len());\n\n    // Allocate memory for the output tensor\n    let mut output = Tensor::new(None, &output_size)?;\n    let cartesian_coord = output_size\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    output = output.par_enum_map(|i, _: T| {\n        let coord = cartesian_coord[i].clone();\n        let index_val = index.get(&coord);\n\n        let mut new_coord = coord.clone();\n        new_coord[dim] = index_val;\n\n        let val = input.get(&new_coord);\n\n        Ok(val)\n    })?;\n\n    // Reshape the output tensor\n    output.reshape(&output_size)?;\n\n    Ok(output)\n}\n\n/// Gather ND.\n/// # Arguments\n/// * `input` - Tensor\n/// * `index` - Tensor of indices to gather\n/// * `batch_dims` - Number of batch dimensions\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::gather_nd;\n/// let x = Tensor::<i128>::new(\n///   Some(&[0, 1, 2, 3]),\n/// &[2, 2],\n/// ).unwrap();\n/// let index = Tensor::<usize>::new(\n/// Some(&[0, 0, 1, 1]),\n/// &[2, 2],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 3]), &[2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n/// Some(&[1, 0]),\n/// &[2, 1],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 0, 1]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(\n///  Some(&[0, 1, 2, 3, 4, 5, 6, 7]),\n/// &[2, 2, 2],\n/// ).unwrap();\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 1, 1, 0]),\n/// &[2, 2],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 1, 1, 0]),\n/// &[2, 1, 2],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 1, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n/// Some(&[1, 0]),\n/// &[2, 1],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]),\n/// &[2, 2, 3],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 1, 0, 0, 1, 1, 1, 0]),\n/// &[2, 2, 2],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 3, 0, 1, 6, 7, 4, 5]), &[2, 2, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let index = Tensor::<usize>::new(\n///  Some(&[0, 1, 0, 1, 1, 1]),\n/// &[2, 3],\n/// ).unwrap();\n/// let result = gather_nd(&x, &index, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 7]), &[2]).unwrap();\n/// assert_eq!(result, expected);\n///\npub fn gather_nd<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    index: &Tensor<usize>,\n    batch_dims: usize,\n) -> Result<Tensor<T>, TensorError> {\n    // Calculate the output tensor size\n    let index_dims = index.dims().to_vec();\n    let input_dims = input.dims().to_vec();\n    let last_value = index_dims\n        .last()\n        .ok_or(TensorError::DimMismatch(\"gather_nd\".to_string()))?;\n    if last_value > &(input_dims.len() - batch_dims) {\n        return Err(TensorError::DimMismatch(\"gather_nd\".to_string()));\n    }\n\n    let output_size =\n    // If indices_shape[-1] == r-b, since the rank of indices is q,\n    // indices can be thought of as N (q-b-1)-dimensional tensors containing 1-D tensors of dimension r-b,\n    // where N is an integer equals to the product of 1 and all the elements in the batch dimensions of the indices_shape.\n    // Let us think of each such r-b ranked tensor as indices_slice.\n    // Each scalar value corresponding to data[0:b-1,indices_slice] is filled into\n    // the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor\n     // if indices_shape[-1] < r-b, since the rank of indices is q, indices can be thought of as N (q-b-1)-dimensional tensor containing 1-D tensors of dimension < r-b.\n    // Let us think of each such tensors as indices_slice.\n    // Each tensor slice corresponding to data[0:b-1, indices_slice , :] is filled into the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor\n    {\n        let output_rank = input_dims.len() + index_dims.len() - 1 - batch_dims - last_value;\n\n        let mut dims = index_dims[..index_dims.len() - 1].to_vec();\n        let input_offset = batch_dims + last_value;\n        dims.extend(input_dims[input_offset..input_dims.len()].to_vec());\n\n        assert_eq!(output_rank, dims.len());\n        dims\n\n    };\n\n    // cartesian coord over batch dims\n    let mut batch_cartesian_coord = input_dims[0..batch_dims]\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    if batch_cartesian_coord.is_empty() {\n        batch_cartesian_coord.push(vec![]);\n    }\n\n    let outputs = batch_cartesian_coord\n        .par_iter()\n        .map(|batch_coord| {\n            let batch_slice = batch_coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n            let mut index_slice = index.get_slice(&batch_slice)?;\n            index_slice.reshape(&index.dims()[batch_dims..])?;\n            let mut input_slice = input.get_slice(&batch_slice)?;\n            input_slice.reshape(&input.dims()[batch_dims..])?;\n\n            let mut inner_cartesian_coord = index_slice.dims()[0..index_slice.dims().len() - 1]\n                .iter()\n                .map(|x| 0..*x)\n                .multi_cartesian_product()\n                .collect::<Vec<_>>();\n\n            if inner_cartesian_coord.is_empty() {\n                inner_cartesian_coord.push(vec![]);\n            }\n\n            let output = inner_cartesian_coord\n                .iter()\n                .map(|coord| {\n                    let slice = coord\n                        .iter()\n                        .map(|x| *x..*x + 1)\n                        .chain(batch_coord.iter().map(|x| *x..*x + 1))\n                        .collect::<Vec<_>>();\n\n                    let index_slice = index_slice\n                        .get_slice(&slice)\n                        .unwrap()\n                        .iter()\n                        .map(|x| *x..*x + 1)\n                        .collect::<Vec<_>>();\n\n                    input_slice.get_slice(&index_slice).unwrap()\n                })\n                .collect::<Tensor<_>>();\n\n            output.combine()\n        })\n        .collect::<Result<Vec<_>, _>>()?;\n\n    let mut outputs = outputs.into_iter().flatten().collect::<Tensor<_>>();\n\n    outputs.reshape(&output_size)?;\n\n    Ok(outputs)\n}\n\n/// Scatter ND.\n/// This operator is the inverse of GatherND.\n/// # Arguments\n/// * `input` - Tensor\n/// * `index` - Tensor of indices to scatter\n/// * `src` - Tensor of src\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::scatter_nd;\n/// let x = Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 6, 7, 8]),\n/// &[8],\n/// ).unwrap();\n///\n/// let index = Tensor::<usize>::new(\n/// Some(&[4, 3, 1, 7]),\n/// &[4, 1],\n/// ).unwrap();\n/// let src = Tensor::<i128>::new(\n/// Some(&[9, 10, 11, 12]),\n/// &[4],\n/// ).unwrap();\n/// let result = scatter_nd(&x, &index, &src).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 11, 3, 10, 9, 6, 7, 12]), &[8]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,\n///         1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,\n///         8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8,\n///         8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8]),\n/// &[4, 4, 4],\n/// ).unwrap();\n///\n/// let index = Tensor::<usize>::new(\n///   Some(&[0, 2]),\n/// &[2, 1],\n/// ).unwrap();\n///\n/// let src = Tensor::<i128>::new(\n///  Some(&[5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,\n///         1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,\n///   ]),\n/// &[2, 4, 4],\n/// ).unwrap();\n///\n/// let result = scatter_nd(&x, &index, &src).unwrap();\n///\n/// let expected = Tensor::<i128>::new(\n///  Some(&[5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,\n///         1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,\n///         1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,\n///         8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8]),\n/// &[4, 4, 4],\n/// ).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 6, 7, 8]),\n/// &[2, 4],\n/// ).unwrap();\n///\n/// let index = Tensor::<usize>::new(\n/// Some(&[0, 1]),\n/// &[2, 1],\n/// ).unwrap();\n/// let src = Tensor::<i128>::new(\n/// Some(&[9, 10]),\n/// &[2],\n/// ).unwrap();\n/// let result = scatter_nd(&x, &index, &src).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[9, 9, 9, 9, 10, 10, 10, 10]), &[2, 4]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(\n///  Some(&[1, 2, 3, 4, 5, 6, 7, 8]),\n/// &[2, 4],\n/// ).unwrap();\n///\n/// let index = Tensor::<usize>::new(\n/// Some(&[0, 1]),\n/// &[1, 1, 2],\n/// ).unwrap();\n/// let src = Tensor::<i128>::new(\n/// Some(&[9]),\n/// &[1, 1],\n/// ).unwrap();\n/// let result = scatter_nd(&x, &index, &src).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 9, 3, 4, 5, 6, 7, 8]), &[2, 4]).unwrap();\n/// assert_eq!(result, expected);\n/// ````\n///\npub fn scatter_nd<T: TensorType + Send + Sync>(\n    input: &Tensor<T>,\n    index: &Tensor<usize>,\n    src: &Tensor<T>,\n) -> Result<Tensor<T>, TensorError> {\n    // Calculate the output tensor size\n    let index_dims = index.dims().to_vec();\n    let input_dims = input.dims().to_vec();\n    let last_value = index_dims\n        .last()\n        .ok_or(TensorError::DimMismatch(\"scatter_nd\".to_string()))?;\n    if last_value > &input_dims.len() {\n        return Err(TensorError::DimMismatch(\"scatter_nd\".to_string()));\n    }\n\n    let mut output = input.clone();\n\n    let cartesian_coord = index_dims[0..index_dims.len() - 1]\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    cartesian_coord\n        .iter()\n        .map(|coord| {\n            let slice = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n            let index_val = index.get_slice(&slice)?;\n            let index_slice = index_val.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();\n            let src_val = src.get_slice(&slice)?;\n            output.set_slice(&index_slice, &src_val)?;\n            Ok(())\n        })\n        .collect::<Result<Vec<_>, _>>()?;\n\n    Ok(output)\n}\n\n/// Abs a tensor.\n/// # Arguments\n/// * `a` - Tensor\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::abs;\n/// let x = Tensor::<i128>::new(\n///    Some(&[-2, 15, 2, -1, 1, 0]),\n/// &[2, 3],\n/// ).unwrap();\n/// let result = abs(&x).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, 0]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn abs<T: TensorType + Add<Output = T> + std::cmp::Ord + Neg<Output = T>>(\n    a: &Tensor<T>,\n) -> Result<Tensor<T>, TensorError> {\n    // calculate value of output\n    let mut output: Tensor<T> = a.clone();\n    output.iter_mut().for_each(|a_i| {\n        if *a_i < T::zero().unwrap() {\n            *a_i = -a_i.clone();\n        }\n    });\n    Ok(output)\n}\n\n/// Intercalates values into a tensor along a given axis.\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::intercalate_values;\n///\n/// let tensor = Tensor::<i128>::new(Some(&[1, 2, 3, 4]), &[2, 2]).unwrap();\n/// let result = intercalate_values(&tensor, 0, 2, 1).unwrap();\n///\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 2, 3, 0, 4]), &[2, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = intercalate_values(&expected, 0, 2, 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 0, 2, 0, 0, 0, 3, 0, 4]), &[3, 3]).unwrap();\n///\n/// assert_eq!(result, expected);\n///\n/// ```\npub fn intercalate_values<T: TensorType>(\n    tensor: &Tensor<T>,\n    value: T,\n    stride: usize,\n    axis: usize,\n) -> Result<Tensor<T>, TensorError> {\n    if stride == 1 {\n        return Ok(tensor.clone());\n    }\n\n    let mut output_dims = tensor.dims().to_vec();\n    output_dims[axis] = output_dims[axis] * stride - 1;\n\n    let mut output: Tensor<T> = Tensor::new(None, &output_dims)?;\n\n    let cartesian_coord = output\n        .dims()\n        .iter()\n        .map(|d| (0..*d))\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let mut tensor_slice_iter = tensor.iter();\n\n    output.iter_mut().enumerate().for_each(|(i, o)| {\n        let coord = &cartesian_coord[i];\n\n        if coord[axis] % stride == 0 {\n            *o = tensor_slice_iter.next().unwrap().clone();\n        } else {\n            *o = value.clone();\n        }\n    });\n\n    Ok(output)\n}\n\n/// One hot encodes a tensor along a given axis.\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::one_hot;\n/// let tensor = Tensor::<i128>::new(Some(&[1, 2, 3, 4]), &[2, 2]).unwrap();\n/// let result = one_hot(&tensor, 5, 2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 0,\n///                                           0, 0, 1, 0, 0,\n///                                           0, 0, 0, 1, 0,\n///                                           0, 0, 0, 0, 1]), &[2, 2, 5]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn one_hot(\n    tensor: &Tensor<i128>,\n    num_classes: usize,\n    axis: usize,\n) -> Result<Tensor<i128>, TensorError> {\n    let mut output_dims = tensor.dims().to_vec();\n    output_dims.insert(axis, num_classes);\n\n    let mut output: Tensor<i128> = Tensor::new(None, &output_dims)?;\n\n    let cartesian_coord = output\n        .dims()\n        .iter()\n        .map(|d| (0..*d))\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    output\n        .iter_mut()\n        .enumerate()\n        .map(|(i, o)| {\n            let coord = &cartesian_coord[i];\n            let coord_axis = coord[axis];\n\n            let mut coord_without_axis = coord.clone();\n            coord_without_axis.remove(axis);\n\n            let elem = tensor.get(&coord_without_axis) as usize;\n            if elem > num_classes {\n                return Err(TensorError::DimMismatch(format!(\n                    \"Expected element to be less than num_classes, but got {}\",\n                    elem\n                )));\n            };\n\n            if coord_axis == elem {\n                *o = 1;\n            } else {\n                *o = 0;\n            }\n            Ok(())\n        })\n        .collect::<Result<Vec<()>, TensorError>>()?;\n\n    Ok(output)\n}\n\n/// Pads a ND tensor of shape `B x C x H x D1 x D2 x ...` along all dimensions.\n/// # Arguments\n///\n/// * `image` - Tensor.\n/// * `padding` - Tuple of padding values in x and y directions.\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::pad;\n///\n/// let x = Tensor::<i128>::new(\n///     Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),\n///     &[1, 1, 3, 3],\n/// ).unwrap();\n/// let result = pad::<i128>(&x, vec![(0, 0), (0, 0), (1, 1), (1, 1)], 0).unwrap();\n/// let expected = Tensor::<i128>::new(\n///     Some(&[0, 0, 0, 0, 0, 0, 5, 2, 3, 0, 0, 0, 4, -1, 0, 0, 3, 1, 6, 0, 0, 0, 0, 0, 0]),\n///     &[1, 1, 5, 5],\n/// ).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let result = pad::<i128>(&x, vec![(1, 1), (1, 1)], 2).unwrap();\n/// assert_eq!(result, expected);\n/// ```\npub fn pad<T: TensorType>(\n    image: &Tensor<T>,\n    padding: Vec<(usize, usize)>,\n    offset: usize,\n) -> Result<Tensor<T>, TensorError> {\n    let padded_dims = image.dims()[offset..]\n        .iter()\n        .enumerate()\n        .map(|(i, d)| d + padding[i].0 + padding[i].1)\n        .collect::<Vec<_>>();\n\n    let mut output_dims = image.dims()[..offset].to_vec();\n    output_dims.extend(padded_dims);\n\n    let mut output = Tensor::<T>::new(None, &output_dims).unwrap();\n\n    let cartesian_coord = image\n        .dims()\n        .iter()\n        .map(|d| (0..*d))\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    for coord in cartesian_coord {\n        let rest = &coord[offset..];\n        let mut padded_res = coord[..offset].to_vec();\n        padded_res.extend(rest.iter().zip(padding.iter()).map(|(c, p)| c + p.0));\n        let image_val = image.get(&coord);\n        output.set(&padded_res, image_val);\n    }\n\n    output.reshape(&output_dims)?;\n    Ok(output)\n}\n\n/// Concatenates a list of tensors along a specified axis.\n/// # Arguments\n/// * `inputs` - A slice of tensors to concatenate.\n/// * `axis` - The axis along which to concatenate the tensors.\n///\n/// # Examples\n/// ```\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::concat;\n/// // tested against pytorch outputs for reference :)\n///\n/// // 1D example\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3]), &[3]).unwrap();\n/// let y = Tensor::<i128>::new(Some(&[4, 5, 6]), &[3]).unwrap();\n/// let result = concat(&[&x, &y], 0).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// // 2D example\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();\n/// let y = Tensor::<i128>::new(Some(&[7, 8, 9]), &[3, 1]).unwrap();\n/// let result = concat(&[&x, &y], 1).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 7, 3, 4, 8, 5, 6, 9]), &[3, 3]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// /// 4D example\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), &[2, 2, 2, 2]).unwrap();\n/// let y = Tensor::<i128>::new(Some(&[17, 18, 19, 20, 21, 22, 23, 14]), &[2, 2, 1, 2]).unwrap();\n/// let result = concat(&[&x, &y], 2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 17, 18, 5, 6, 7, 8, 19, 20, 9, 10, 11, 12, 21, 22, 13, 14, 15, 16, 23, 14]), &[2, 2, 3, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n///\n/// // 5D example\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), &[8, 1, 1, 1, 2]).unwrap();\n/// let y = Tensor::<i128>::new(Some(&[17, 18, 19, 20, 21, 22, 23, 14]), &[4, 1, 1, 1, 2]).unwrap();\n/// let result = concat(&[&x, &y], 0).unwrap();\n///\n/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 14]), &[12, 1, 1, 1, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// ```\n///\n/// # Errors\n/// Returns a TensorError if the tensors in `inputs` have incompatible dimensions for concatenation along the specified `axis`.\n\npub fn concat<T: TensorType + Send + Sync>(\n    inputs: &[&Tensor<T>],\n    axis: usize,\n) -> Result<Tensor<T>, TensorError> {\n    if inputs.len() == 1 {\n        return Ok(inputs[0].clone());\n    }\n\n    // Calculate the output tensor size\n    let mut output_size = inputs[0].dims().to_vec();\n    output_size[axis] = inputs.iter().map(|x| x.dims()[axis]).sum();\n\n    // Allocate memory for the output tensor\n    let mut output = Tensor::new(None, &output_size)?;\n    let cartesian_coord = output_size\n        .iter()\n        .map(|x| 0..*x)\n        .multi_cartesian_product()\n        .collect::<Vec<_>>();\n\n    let get_input_index = |index_along_axis: usize| -> (usize, usize) {\n        let mut current_idx = 0;\n        let mut input_idx = 0;\n        let mut input_coord_at_idx = 0;\n        for (i, elem) in inputs.iter().enumerate() {\n            current_idx += elem.dims()[axis];\n            if index_along_axis < current_idx {\n                input_idx = i;\n                // subtract the current\n                input_coord_at_idx = index_along_axis - (current_idx - elem.dims()[axis]);\n                break;\n            }\n        }\n        (input_idx, input_coord_at_idx)\n    };\n\n    output = output.par_enum_map(|i, _: T| {\n        let coord = cartesian_coord[i].clone();\n        let mut index = 0;\n        let mut input_index = 0;\n        let mut input_coord = coord.clone();\n        for (j, x) in coord.iter().enumerate() {\n            if j == axis {\n                (input_index, input_coord[j]) = get_input_index(*x);\n                break;\n            }\n            index += x;\n        }\n\n        Ok(inputs[input_index].get(&input_coord))\n    })?;\n\n    // Reshape the output tensor\n    output.reshape(&output_size)?;\n\n    Ok(output)\n}\n\n/// Slices a tensor from start to end along a given axis\n///\n/// /// # Examples\n/// ```\n/// // tested against pytorch output\n/// use ezkl::tensor::Tensor;\n/// use ezkl::tensor::ops::slice;\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();\n/// let result = slice(&x, &0, &1, &2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[3, 4]), &[1, 2]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();\n/// let result = slice(&x, &1, &1, &2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 4, 6]), &[3, 1]).unwrap();\n/// assert_eq!(result, expected);\n///\n/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 2, 3]).unwrap();\n/// let result = slice(&x, &2, &1, &2).unwrap();\n/// let expected = Tensor::<i128>::new(Some(&[2, 5, 8, 11]), &[2, 2, 1]).unwrap();\n/// assert_eq!(result, expected);\n/// ```\n///\npub fn slice<T: TensorType + Send + Sync>(\n    t: &Tensor<T>,\n    axis: &usize,\n    start: &usize,\n    end: &usize,\n) -> Result<Tensor<T>, TensorError> {\n    let mut slice = vec![];\n    for (i, d) in t.dims().iter().enumerate() {\n        if i != *axis {\n            slice.push(0..*d)\n        } else {\n            slice.push(*start..*end)\n        }\n    }\n\n    t.get_slice(&slice)\n}\n\n// ---------------------------------------------------------------------------------------------------------\n// -- nonlinear Functions ---------------------------------------------------------------------------------\n// ---------------------------------------------------------------------------------------------------------\n// ---------------------------------------------------------------------------------------------------------\n// ---------------------------------------------------------------------------------------------------------\n// ---------------------------------------------------------------------------------------------------------\n\n/// Activation functions\npub mod nonlinearities {\n    use super::*;\n\n    /// Ceiling operator.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    ///\n    /// use ezkl::tensor::ops::nonlinearities::ceil;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[1, 2, 3, 4, 5, 6]),\n    ///  &[3, 2],\n    /// ).unwrap();\n    /// let result = ceil(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 2, 4, 4, 6, 6]), &[3, 2]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn ceil(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale;\n            let rounded = kix.ceil() * scale;\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Floor operator.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::floor;\n    /// let x = Tensor::<i128>::new(\n    ///   Some(&[1, 2, 3, 4, 5, 6]),\n    ///  &[3, 2],\n    /// ).unwrap();\n    /// let result = floor(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 2, 2, 4, 4, 6]), &[3, 2]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn floor(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale;\n            let rounded = kix.floor() * scale;\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Round operator.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::round;\n    /// let x = Tensor::<i128>::new(\n    ///   Some(&[1, 2, 3, 4, 5, 6]),\n    /// &[3, 2],\n    /// ).unwrap();\n    /// let result = round(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 2, 4, 4, 6, 6]), &[3, 2]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn round(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale;\n            let rounded = kix.round() * scale;\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Round half to even operator.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::round_half_to_even;\n    /// let x = Tensor::<i128>::new(\n    ///   Some(&[1, 2, 3, 4, 5, 6]),\n    /// &[3, 2],\n    /// ).unwrap();\n    /// let result = round_half_to_even(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 2, 4, 4, 4, 6]), &[3, 2]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn round_half_to_even(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale;\n            let rounded = kix.round_ties_even() * scale;\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Raises to a floating point power.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `power` - Floating point power\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::pow;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 15, 2, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = pow(&x, 1.0, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 225, 4, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn pow(a: &Tensor<i128>, scale_input: f64, power: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let kix = scale_input * (kix).powf(power);\n            let rounded = kix.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Applies Kronecker delta to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::kronecker_delta;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 15, 2, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = kronecker_delta(&x);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn kronecker_delta<T: TensorType + std::cmp::PartialEq + Send + Sync>(\n        a: &Tensor<T>,\n    ) -> Tensor<T> {\n        a.par_enum_map(|_, a_i| {\n            if a_i == T::zero().unwrap() {\n                Ok::<_, TensorError>(T::one().unwrap())\n            } else {\n                Ok::<_, TensorError>(T::zero().unwrap())\n            }\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies sigmoid to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::sigmoid;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = sigmoid(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 1, 1]), &[2, 3]).unwrap();\n    ///\n    /// assert_eq!(result, expected);\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[65536]),\n    ///   &[1],\n    /// ).unwrap();\n    /// let result = sigmoid(&x, 65536.0);\n    /// let expected = Tensor::<i128>::new(Some(&[47911]), &[1]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    /// /// assert_eq!(result, expected);\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[256]),\n    ///   &[1],\n    /// ).unwrap();\n    /// let result = sigmoid(&x, 256.0);\n    /// let expected = Tensor::<i128>::new(Some(&[187]), &[1]).unwrap();\n    ///\n    /// ```\n    pub fn sigmoid(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input / (1.0 + (-kix).exp());\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies hardswish to a tensor of integers.\n    /// Hardswish is defined as:\n    // Hardswish(x)={0if x\u2264\u22123,xif x\u2265+3,x\u22c5(x+3)/6otherwise\n    // Hardswish(x)=\u23a9\n    // \u23a8\n    // \u23a7\u200b0xx\u22c5(x+3)/6\u200bif x\u2264\u22123,if x\u2265+3,otherwise\u200b\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::hardswish;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[-12, -3, 2, 1, 1, 15]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = hardswish(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 0, 2, 1, 1, 15]), &[2, 3]).unwrap();\n    ///\n    /// assert_eq!(result, expected);\n    ///\n    /// ```\n    pub fn hardswish(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let res = if kix <= -3.0 {\n                0.0\n            } else if kix >= 3.0 {\n                kix\n            } else {\n                kix * (kix + 3.0) / 6.0\n            };\n            let rounded = (res * scale_input).round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies exponential to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::exp;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = exp(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[7, 3269017, 7, 3, 3, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    ///\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[37, 12, 41]),\n    ///   &[3],\n    /// ).unwrap();\n    /// let result = exp(&x, 512.0);\n    ///\n    /// let expected = Tensor::<i128>::new(Some(&[550, 524, 555]), &[3]).unwrap();\n    ///\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn exp(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.exp();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies exponential to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::ln;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 3000]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = ln(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 3, 1, 0, 0, 8]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    ///\n    ///\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[37, 12, 41]),\n    ///   &[3],\n    /// ).unwrap();\n    /// let result = ln(&x, 512.0);\n    ///\n    /// let expected = Tensor::<i128>::new(Some(&[-1345, -1922, -1293]), &[3]).unwrap();\n    ///\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn ln(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.ln();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies sign to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::sign;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[-2, 15, 2, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = sign(&x);\n    /// let expected = Tensor::<i128>::new(Some(&[-1, 1, 1, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn sign(a: &Tensor<i128>) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| Ok::<_, TensorError>(a_i.signum()))\n            .unwrap()\n    }\n\n    /// Elementwise applies square root to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::sqrt;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[4, 25, 8, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = sqrt(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 5, 3, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn sqrt(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.sqrt();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies reciprocal square root to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::rsqrt;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[4, 25, 8, 1, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = rsqrt(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 1, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn rsqrt(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input / (kix.sqrt() + f64::EPSILON);\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies cosine to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::cos;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = cos(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(& [-1, 2, -1, 2, 2, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn cos(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.cos();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arccosine to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::acos;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = acos(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn acos(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.acos();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies cosh to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::cosh;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = cosh(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[27, 36002449669, 1490, 2, 2, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn cosh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.cosh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arccosineh to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::acosh;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = acosh(&x, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(& [2, 4, 3, 0, 0, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn acosh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.acosh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies sine to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::sin;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = sin(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn sin(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.sin();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arcsine to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::asin;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = asin(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(& [4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn asin(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.asin();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies sineh to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::sinh;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = sinh(&x, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[7, 268337, 55, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn sinh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.sinh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arcsineh to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::asinh;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = asinh(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn asinh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.asinh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies tan activation to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::tan;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = tan(&x, 64.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 26, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn tan(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.tan();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arctan activation to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::atan;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[4, 25, 8, 1, 1, 0]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let result = atan(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn atan(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.atan();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies tanh activation to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::tanh;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[4, 25, 8, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = tanh(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n\n    pub fn tanh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.tanh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies arctanh activation to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::atanh;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[4, 25, 8, 2, 2, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = atanh(&x, 32.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4, 34, 8, 2, 2, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n\n    pub fn atanh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * kix.atanh();\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Applies error function (erf) on a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale_input` - Single value\n    /// * `scale_output` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::erffunc;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[5, 28, 9, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = erffunc(&x, 128.0);\n    /// let expected = Tensor::<i128>::new(Some(&[6, 31, 10, 1, 1, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn erffunc(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {\n        const NCOEF: usize = 28;\n        const COF: [f64; 28] = [\n            -1.3026537197817094,\n            6.419_697_923_564_902e-1,\n            1.9476473204185836e-2,\n            -9.561_514_786_808_63e-3,\n            -9.46595344482036e-4,\n            3.66839497852761e-4,\n            4.2523324806907e-5,\n            -2.0278578112534e-5,\n            -1.624290004647e-6,\n            1.303655835580e-6,\n            1.5626441722e-8,\n            -8.5238095915e-8,\n            6.529054439e-9,\n            5.059343495e-9,\n            -9.91364156e-10,\n            -2.27365122e-10,\n            9.6467911e-11,\n            2.394038e-12,\n            -6.886027e-12,\n            8.94487e-13,\n            3.13092e-13,\n            -1.12708e-13,\n            3.81e-16,\n            7.106e-15,\n            -1.523e-15,\n            -9.4e-17,\n            1.21e-16,\n            -2.8e-17,\n        ];\n\n        /// Chebyshev coefficients\n        fn erfccheb(z: f64) -> f64 {\n            let mut d = 0f64;\n            let mut dd = 0f64;\n\n            assert!(z >= 0f64, \"erfccheb requires nonnegative argument\");\n            let t = 2f64 / (2f64 + z);\n            let ty = 4f64 * t - 2f64;\n            for j in (1..NCOEF - 1).rev() {\n                let tmp = d;\n                d = ty * d - dd + COF[j];\n                dd = tmp;\n            }\n            t * (-z.powi(2) + 0.5 * (COF[0] + ty * d) - dd).exp()\n        }\n\n        pub fn erf(x: f64) -> f64 {\n            if x >= 0f64 {\n                1.0 - erfccheb(x)\n            } else {\n                erfccheb(-x) - 1f64\n            }\n        }\n\n        a.par_enum_map(|_, a_i| {\n            let kix = (a_i as f64) / scale_input;\n            let fout = scale_input * erf(kix);\n            let rounded = fout.round();\n            Ok::<_, TensorError>(rounded as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies leaky relu to a tensor of integers.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `scale` - Single value\n    /// * `slope` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::leakyrelu;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, -5]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = leakyrelu(&x, 0.1);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, -1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn leakyrelu(a: &Tensor<i128>, slope: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let rounded = if a_i < 0 {\n                let d_inv_x = (slope) * (a_i as f64);\n                d_inv_x.round() as i128\n            } else {\n                let d_inv_x = a_i as f64;\n                d_inv_x.round() as i128\n            };\n            Ok::<_, TensorError>(rounded)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies max to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `b` - scalar\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::max;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 15, 2, 1, 1, -5]),\n    ///   &[2, 3],\n    /// ).unwrap();\n    /// let result = max(&x, 1.0, 1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn max(a: &Tensor<i128>, scale_input: f64, threshold: f64) -> Tensor<i128> {\n        // calculate value of output\n        a.par_enum_map(|_, a_i| {\n            let d_inv_x = (a_i as f64) / scale_input;\n            let rounded = if d_inv_x <= threshold {\n                (threshold * scale_input).round() as i128\n            } else {\n                (d_inv_x * scale_input).round() as i128\n            };\n            Ok::<_, TensorError>(rounded)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise applies min to a tensor of integers.\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `b` - scalar\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::min;\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 15, 2, 1, 1, -5]),\n    ///   &[2, 3],\n    /// ).unwrap();\n    /// let result = min(&x, 1.0, 2.0);\n    /// let expected = Tensor::<i128>::new(Some(&[2, 2, 2, 1, 1, -5]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn min(a: &Tensor<i128>, scale_input: f64, threshold: f64) -> Tensor<i128> {\n        // calculate value of output\n        a.par_enum_map(|_, a_i| {\n            let d_inv_x = (a_i as f64) / scale_input;\n            let rounded = if d_inv_x >= threshold {\n                (threshold * scale_input).round() as i128\n            } else {\n                (d_inv_x * scale_input).round() as i128\n            };\n            Ok::<_, TensorError>(rounded)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise divides a tensor with a const integer element.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::const_div;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 1, 2, 7, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = 2.0;\n    /// let result = const_div(&x, k);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 4, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn const_div(a: &Tensor<i128>, denom: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let d_inv_x = (a_i as f64) / (denom);\n            Ok::<_, TensorError>(d_inv_x.round() as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise inverse.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::recip;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 1, 2, 7, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = 2_f64;\n    /// let result = recip(&x, 1.0, k);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 2, 1, 0, 2, 2]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn recip(a: &Tensor<i128>, input_scale: f64, out_scale: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| {\n            let rescaled = (a_i as f64) / input_scale;\n            let denom = (1_f64) / (rescaled + f64::EPSILON);\n            let d_inv_x = out_scale * denom;\n            Ok::<_, TensorError>(d_inv_x.round() as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise inverse.\n    /// # Arguments\n    /// * `out_scale` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::zero_recip;\n    /// let k = 2_f64;\n    /// let result = zero_recip(1.0);\n    /// let expected = Tensor::<i128>::new(Some(&[4503599627370496]), &[1]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn zero_recip(out_scale: f64) -> Tensor<i128> {\n        let a = Tensor::<i128>::new(Some(&[0]), &[1]).unwrap();\n\n        a.par_enum_map(|_, a_i| {\n            let rescaled = a_i as f64;\n            let denom = (1_f64) / (rescaled + f64::EPSILON);\n            let d_inv_x = out_scale * denom;\n            Ok::<_, TensorError>(d_inv_x.round() as i128)\n        })\n        .unwrap()\n    }\n\n    /// Elementwise greater than\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::greater_than;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 1, 2, 7, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = 2.0;\n    /// let result = greater_than(&x, k);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 1, 0, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn greater_than(a: &Tensor<i128>, b: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) > 0_f64)))\n            .unwrap()\n    }\n\n    /// Elementwise greater than\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::greater_than_equal;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 1, 2, 7, 1, 1]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let k = 2.0;\n    /// let result = greater_than_equal(&x, k);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 1, 0, 0]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn greater_than_equal(a: &Tensor<i128>, b: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) >= 0_f64)))\n            .unwrap()\n    }\n\n    /// Elementwise less than\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::less_than;\n    ///\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 1, 2, 7, 1, 1]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let k = 2.0;\n    ///\n    /// let result = less_than(&x, k);\n    /// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn less_than(a: &Tensor<i128>, b: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) < 0_f64)))\n            .unwrap()\n    }\n\n    /// Elementwise less than\n    /// # Arguments\n    /// * `a` - Tensor\n    /// * `b` - Single value\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::nonlinearities::less_than_equal;\n    ///\n    /// let x = Tensor::<i128>::new(\n    ///    Some(&[2, 1, 2, 7, 1, 1]),\n    ///  &[2, 3],\n    /// ).unwrap();\n    /// let k = 2.0;\n    ///\n    /// let result = less_than_equal(&x, k);\n    /// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 0, 1, 1]), &[2, 3]).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn less_than_equal(a: &Tensor<i128>, b: f64) -> Tensor<i128> {\n        a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) <= 0_f64)))\n            .unwrap()\n    }\n}\n\n/// Ops that return the transcript i.e intermediate calcs of an op\npub mod accumulated {\n    use super::*;\n\n    /// Dot product of two tensors.\n    /// # Arguments\n    ///\n    /// * `inputs` - Vector of tensors of length 2.\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::accumulated::dot;\n    ///\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[5, 2]),\n    ///     &[2],\n    /// ).unwrap();\n    /// let y = Tensor::<i128>::new(\n    ///     Some(&[5, 5]),\n    ///     &[2],\n    /// ).unwrap();\n    /// let expected = Tensor::<i128>::new(\n    ///     Some(&[25, 35]),\n    ///     &[2],\n    /// ).unwrap();\n    /// assert_eq!(dot(&[x, y], 1).unwrap(), expected);\n    /// ```\n    pub fn dot<T: TensorType + Mul<Output = T> + Add<Output = T>>(\n        inputs: &[Tensor<T>; 2],\n        chunk_size: usize,\n    ) -> Result<Tensor<T>, TensorError> {\n        if inputs[0].clone().len() != inputs[1].clone().len() {\n            return Err(TensorError::DimMismatch(\"dot\".to_string()));\n        }\n        let (a, b): (Tensor<T>, Tensor<T>) = (inputs[0].clone(), inputs[1].clone());\n\n        let transcript: Tensor<T> = a\n            .iter()\n            .zip(b)\n            .chunks(chunk_size)\n            .into_iter()\n            .scan(T::zero().unwrap(), |acc, chunk| {\n                let k = chunk.fold(T::zero().unwrap(), |acc, (a_i, b_i)| {\n                    acc.clone() + a_i.clone() * b_i.clone()\n                });\n                *acc = acc.clone() + k.clone();\n                Some(acc.clone())\n            })\n            .collect();\n\n        Ok(transcript)\n    }\n\n    /// Sums a tensor.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::accumulated::sum;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = sum(&x, 1).unwrap();\n    /// let expected = Tensor::<i128>::new(\n    ///     Some(&[2, 17, 19, 20, 21, 21]),\n    ///     &[6],\n    /// ).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn sum<T: TensorType + Mul<Output = T> + Add<Output = T>>(\n        a: &Tensor<T>,\n        chunk_size: usize,\n    ) -> Result<Tensor<T>, TensorError> {\n        let transcript: Tensor<T> = a\n            .iter()\n            .chunks(chunk_size)\n            .into_iter()\n            .scan(T::zero().unwrap(), |acc, chunk| {\n                let k = chunk.fold(T::zero().unwrap(), |acc, a_i| acc.clone() + a_i.clone());\n                *acc = acc.clone() + k.clone();\n                Some(acc.clone())\n            })\n            .collect();\n\n        Ok(transcript)\n    }\n\n    /// Prod of a tensor.\n    /// # Arguments\n    ///\n    /// * `a` - Tensor\n    /// # Examples\n    /// ```\n    /// use ezkl::tensor::Tensor;\n    /// use ezkl::tensor::ops::accumulated::prod;\n    /// let x = Tensor::<i128>::new(\n    ///     Some(&[2, 15, 2, 1, 1, 0]),\n    ///     &[2, 3],\n    /// ).unwrap();\n    /// let result = prod(&x, 1).unwrap();\n    /// let expected = Tensor::<i128>::new(\n    ///     Some(&[2, 30, 60, 60, 60, 0]),\n    ///     &[6],\n    /// ).unwrap();\n    /// assert_eq!(result, expected);\n    /// ```\n    pub fn prod<T: TensorType + Mul<Output = T> + Add<Output = T>>(\n        a: &Tensor<T>,\n        chunk_size: usize,\n    ) -> Result<Tensor<T>, TensorError> {\n        let transcript: Tensor<T> = a\n            .iter()\n            .chunks(chunk_size)\n            .into_iter()\n            .scan(T::one().unwrap(), |acc, chunk| {\n                let k = chunk.fold(T::one().unwrap(), |acc, a_i| acc.clone() * a_i.clone());\n                *acc = acc.clone() * k.clone();\n                Some(acc.clone())\n            })\n            .collect();\n\n        Ok(transcript)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/tensor/val.rs",
        "content": "use core::{iter::FilterMap, slice::Iter};\n\nuse crate::circuit::region::ConstantsMap;\n\nuse super::{\n    ops::{intercalate_values, pad, resize},\n    *,\n};\nuse halo2_proofs::{arithmetic::Field, circuit::Cell, plonk::Instance};\n\npub(crate) fn create_constant_tensor<\n    F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,\n>(\n    val: F,\n    len: usize,\n) -> ValTensor<F> {\n    let mut constant = Tensor::from(vec![ValType::Constant(val); len].into_iter());\n    constant.set_visibility(&crate::graph::Visibility::Fixed);\n    ValTensor::from(constant)\n}\n\npub(crate) fn create_unit_tensor<\n    F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,\n>(\n    len: usize,\n) -> ValTensor<F> {\n    let mut unit = Tensor::from(vec![ValType::Constant(F::ONE); len].into_iter());\n    unit.set_visibility(&crate::graph::Visibility::Fixed);\n    ValTensor::from(unit)\n}\n\npub(crate) fn create_zero_tensor<\n    F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,\n>(\n    len: usize,\n) -> ValTensor<F> {\n    let mut zero = Tensor::from(vec![ValType::Constant(F::ZERO); len].into_iter());\n    zero.set_visibility(&crate::graph::Visibility::Fixed);\n    ValTensor::from(zero)\n}\n\n#[derive(Debug, Clone)]\n/// A [ValType] is a wrapper around Halo2 value(s).\npub enum ValType<F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd> {\n    /// value\n    Value(Value<F>),\n    /// assigned  value\n    AssignedValue(Value<Assigned<F>>),\n    /// previously assigned value\n    PrevAssigned(AssignedCell<F, F>),\n    /// constant\n    Constant(F),\n    /// assigned constant\n    AssignedConstant(AssignedCell<F, F>, F),\n}\n\nimpl<F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd> ValType<F> {\n    /// Returns the inner cell of the [ValType].\n    pub fn cell(&self) -> Option<Cell> {\n        match self {\n            ValType::PrevAssigned(cell) => Some(cell.cell()),\n            ValType::AssignedConstant(cell, _) => Some(cell.cell()),\n            _ => None,\n        }\n    }\n\n    /// Returns the assigned cell of the [ValType].\n    pub fn assigned_cell(&self) -> Option<AssignedCell<F, F>> {\n        match self {\n            ValType::PrevAssigned(cell) => Some(cell.clone()),\n            ValType::AssignedConstant(cell, _) => Some(cell.clone()),\n            _ => None,\n        }\n    }\n\n    /// Returns true if the value is previously assigned.\n    pub fn is_prev_assigned(&self) -> bool {\n        matches!(\n            self,\n            ValType::PrevAssigned(_) | ValType::AssignedConstant(..)\n        )\n    }\n    /// Returns true if the value is constant.\n    pub fn is_constant(&self) -> bool {\n        matches!(self, ValType::Constant(_) | ValType::AssignedConstant(..))\n    }\n\n    /// get felt eval\n    pub fn get_felt_eval(&self) -> Option<F> {\n        let mut res = None;\n        match self {\n            ValType::Value(v) => {\n                v.map(|f| {\n                    res = Some(f);\n                });\n            }\n            ValType::AssignedValue(v) => {\n                v.map(|f| {\n                    res = Some(f.evaluate());\n                });\n            }\n            ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                v.value_field().map(|f| {\n                    res = Some(f.evaluate());\n                });\n            }\n            ValType::Constant(v) => {\n                res = Some(*v);\n            }\n        }\n        res\n    }\n\n    /// get_prev_assigned\n    pub fn get_prev_assigned(&self) -> Option<AssignedCell<F, F>> {\n        match self {\n            ValType::PrevAssigned(v) => Some(v.clone()),\n            ValType::AssignedConstant(v, _) => Some(v.clone()),\n            _ => None,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<ValType<F>> for i32 {\n    fn from(val: ValType<F>) -> Self {\n        match val {\n            ValType::Value(v) => {\n                let mut output = 0_i32;\n                let mut i = 0;\n                v.map(|y| {\n                    let e = felt_to_i32(y);\n                    output = e;\n                    i += 1;\n                });\n                output\n            }\n            ValType::AssignedValue(v) => {\n                let mut output = 0_i32;\n                let mut i = 0;\n                v.evaluate().map(|y| {\n                    let e = felt_to_i32(y);\n                    output = e;\n                    i += 1;\n                });\n                output\n            }\n            ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                let mut output = 0_i32;\n                let mut i = 0;\n                v.value().map(|y| {\n                    let e = felt_to_i32(*y);\n                    output = e;\n                    i += 1;\n                });\n                output\n            }\n            ValType::Constant(v) => felt_to_i32(v),\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<F> for ValType<F> {\n    fn from(t: F) -> ValType<F> {\n        ValType::Constant(t)\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Value<F>> for ValType<F> {\n    fn from(t: Value<F>) -> ValType<F> {\n        ValType::Value(t)\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Value<Assigned<F>>> for ValType<F> {\n    fn from(t: Value<Assigned<F>>) -> ValType<F> {\n        ValType::AssignedValue(t)\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<AssignedCell<F, F>> for ValType<F> {\n    fn from(t: AssignedCell<F, F>) -> ValType<F> {\n        ValType::PrevAssigned(t)\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> TensorType for ValType<F>\nwhere\n    F: Field,\n{\n    fn zero() -> Option<Self> {\n        Some(ValType::Constant(<F as Field>::ZERO))\n    }\n    fn one() -> Option<Self> {\n        Some(ValType::Constant(<F as Field>::ONE))\n    }\n}\n\n/// A [ValTensor] is a wrapper around a [Tensor] of [ValType].\n/// or a column of an [Instance].\n/// This is the type used for all intermediate values in a circuit.\n/// It is also the type used for the inputs and outputs of a circuit.\n#[derive(Debug, Clone)]\npub enum ValTensor<F: PrimeField + TensorType + PartialOrd> {\n    /// A tensor of [Value], each containing a field element\n    Value {\n        /// Underlying [Tensor].\n        inner: Tensor<ValType<F>>,\n        /// Vector of dimensions of the tensor.\n        dims: Vec<usize>,\n        ///\n        scale: crate::Scale,\n    },\n    /// A tensor backed by an [Instance] column\n    Instance {\n        /// [Instance]\n        inner: Column<Instance>,\n        /// Vector of dimensions of the tensor.\n        dims: Vec<Vec<usize>>,\n        /// Current instance num\n        idx: usize,\n        ///\n        initial_offset: usize,\n        ///\n        scale: crate::Scale,\n    },\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> TensorType for ValTensor<F> {\n    fn zero() -> Option<Self> {\n        Some(ValTensor::Value {\n            inner: Tensor::zero()?,\n            dims: vec![],\n            scale: 0,\n        })\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Tensor<ValType<F>>> for ValTensor<F> {\n    fn from(t: Tensor<ValType<F>>) -> ValTensor<F> {\n        ValTensor::Value {\n            inner: t.map(|x| x),\n            dims: t.dims().to_vec(),\n            scale: 1,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Vec<ValType<F>>> for ValTensor<F> {\n    fn from(t: Vec<ValType<F>>) -> ValTensor<F> {\n        ValTensor::Value {\n            inner: t.clone().into_iter().into(),\n            dims: vec![t.len()],\n            scale: 1,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> TryFrom<Tensor<F>> for ValTensor<F> {\n    type Error = Box<dyn Error>;\n    fn try_from(t: Tensor<F>) -> Result<ValTensor<F>, Box<dyn Error>> {\n        let visibility = t.visibility.clone();\n        let dims = t.dims().to_vec();\n        let inner = t.into_iter().map(|x| {\n            if let Some(vis) = &visibility {\n                match vis {\n                    Visibility::Fixed => Ok(ValType::Constant(x)),\n                    _ => {\n                        Ok(Value::known(x).into())\n                    }\n                }\n            }\n            else {\n                Err(\"visibility should be set to convert a tensor of field elements to a ValTensor.\".into())\n            }\n        }).collect::<Result<Vec<_>, Box<dyn Error>>>()?;\n\n        let mut inner: Tensor<ValType<F>> = inner.into_iter().into();\n        inner.reshape(&dims)?;\n\n        Ok(ValTensor::Value {\n            inner,\n            dims,\n            scale: 1,\n        })\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Tensor<Value<F>>> for ValTensor<F> {\n    fn from(t: Tensor<Value<F>>) -> ValTensor<F> {\n        ValTensor::Value {\n            inner: t.map(|x| x.into()),\n            dims: t.dims().to_vec(),\n            scale: 1,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Tensor<Value<Assigned<F>>>> for ValTensor<F> {\n    fn from(t: Tensor<Value<Assigned<F>>>) -> ValTensor<F> {\n        ValTensor::Value {\n            inner: t.map(|x| x.into()),\n            dims: t.dims().to_vec(),\n            scale: 1,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> From<Tensor<AssignedCell<F, F>>> for ValTensor<F> {\n    fn from(t: Tensor<AssignedCell<F, F>>) -> ValTensor<F> {\n        ValTensor::Value {\n            inner: t.map(|x| x.into()),\n            dims: t.dims().to_vec(),\n            scale: 1,\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> ValTensor<F> {\n    /// Allocate a new [ValTensor::Value] from the given [Tensor] of [i128].\n    pub fn from_i128_tensor(t: Tensor<i128>) -> ValTensor<F> {\n        let inner = t.map(|x| ValType::Value(Value::known(i128_to_felt(x))));\n        inner.into()\n    }\n\n    /// Allocate a new [ValTensor::Instance] from the ConstraintSystem with the given tensor `dims`, optionally enabling `equality`.\n    pub fn new_instance(\n        cs: &mut ConstraintSystem<F>,\n        dims: Vec<Vec<usize>>,\n        scale: crate::Scale,\n    ) -> Self {\n        let col = cs.instance_column();\n        cs.enable_equality(col);\n\n        ValTensor::Instance {\n            inner: col,\n            dims,\n            initial_offset: 0,\n            idx: 0,\n            scale,\n        }\n    }\n\n    /// Allocate a new [ValTensor::Instance] from the ConstraintSystem with the given tensor `dims`, optionally enabling `equality`.\n    pub fn new_instance_from_col(\n        dims: Vec<Vec<usize>>,\n        scale: crate::Scale,\n        col: Column<Instance>,\n    ) -> Self {\n        ValTensor::Instance {\n            inner: col,\n            dims,\n            idx: 0,\n            initial_offset: 0,\n            scale,\n        }\n    }\n\n    ///\n    pub fn get_total_instance_len(&self) -> usize {\n        match self {\n            ValTensor::Instance { dims, .. } => dims\n                .iter()\n                .map(|x| {\n                    if !x.is_empty() {\n                        x.iter().product::<usize>()\n                    } else {\n                        0\n                    }\n                })\n                .sum(),\n            _ => 0,\n        }\n    }\n\n    ///\n    pub fn is_instance(&self) -> bool {\n        matches!(self, ValTensor::Instance { .. })\n    }\n\n    /// reverse order of elements whilst preserving the shape\n    pub fn reverse(&mut self) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value { inner: v, .. } => {\n                v.reverse();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(())\n    }\n\n    ///\n    pub fn set_initial_instance_offset(&mut self, offset: usize) {\n        if let ValTensor::Instance { initial_offset, .. } = self {\n            *initial_offset = offset;\n        }\n    }\n\n    ///\n    pub fn increment_idx(&mut self) {\n        if let ValTensor::Instance { idx, .. } = self {\n            *idx += 1;\n        }\n    }\n\n    ///\n    pub fn set_idx(&mut self, val: usize) {\n        if let ValTensor::Instance { idx, .. } = self {\n            *idx = val;\n        }\n    }\n\n    ///\n    pub fn get_idx(&self) -> usize {\n        match self {\n            ValTensor::Instance { idx, .. } => *idx,\n            _ => 0,\n        }\n    }\n\n    ///\n    pub fn any_unknowns(&self) -> Result<bool, Box<dyn Error>> {\n        match self {\n            ValTensor::Instance { .. } => Ok(true),\n            _ => Ok(self.get_inner()?.iter().any(|&x| {\n                let mut is_empty = true;\n                x.map(|_| is_empty = false);\n                is_empty\n            })),\n        }\n    }\n\n    /// Returns true if all the [ValTensor]'s [Value]s are assigned.\n    pub fn all_prev_assigned(&self) -> bool {\n        match self {\n            ValTensor::Value { inner, .. } => inner.iter().all(|x| x.is_prev_assigned()),\n            ValTensor::Instance { .. } => false,\n        }\n    }\n\n    /// Set the [ValTensor]'s scale.\n    pub fn set_scale(&mut self, scale: crate::Scale) {\n        match self {\n            ValTensor::Value { scale: s, .. } => *s = scale,\n            ValTensor::Instance { scale: s, .. } => *s = scale,\n        }\n    }\n\n    /// Returns the [ValTensor]'s scale.\n    pub fn scale(&self) -> crate::Scale {\n        match self {\n            ValTensor::Value { scale, .. } => *scale,\n            ValTensor::Instance { scale, .. } => *scale,\n        }\n    }\n\n    /// Returns the number of constants in the [ValTensor].\n    pub fn create_constants_map_iterator(\n        &self,\n    ) -> FilterMap<Iter<'_, ValType<F>>, fn(&ValType<F>) -> Option<(F, ValType<F>)>> {\n        match self {\n            ValTensor::Value { inner, .. } => inner.iter().filter_map(|x| {\n                if let ValType::Constant(v) = x {\n                    Some((*v, x.clone()))\n                } else {\n                    None\n                }\n            }),\n            ValTensor::Instance { .. } => {\n                unreachable!(\"Instance tensors do not have constants\")\n            }\n        }\n    }\n\n    /// Returns the number of constants in the [ValTensor].\n    pub fn create_constants_map(&self) -> ConstantsMap<F> {\n        match self {\n            ValTensor::Value { inner, .. } => inner\n                .par_iter()\n                .filter_map(|x| {\n                    if let ValType::Constant(v) = x {\n                        Some((*v, x.clone()))\n                    } else {\n                        None\n                    }\n                })\n                .collect(),\n            ValTensor::Instance { .. } => ConstantsMap::new(),\n        }\n    }\n\n    /// Fetch the underlying [Tensor] of field elements.\n    pub fn get_felt_evals(&self) -> Result<Tensor<F>, Box<dyn Error>> {\n        let mut felt_evals: Vec<F> = vec![];\n        match self {\n            ValTensor::Value {\n                inner: v, dims: _, ..\n            } => {\n                // we have to push to an externally created vector or else vaf.map() returns an evaluation wrapped in Value<> (which we don't want)\n                let _ = v.map(|vaf| {\n                    if let Some(f) = vaf.get_felt_eval() {\n                        felt_evals.push(f);\n                    }\n                });\n            }\n            _ => return Err(Box::new(TensorError::WrongMethod)),\n        };\n\n        let mut res: Tensor<F> = felt_evals.into_iter().into();\n        res.reshape(self.dims())?;\n        Ok(res)\n    }\n\n    /// Calls is_singleton on the inner tensor.\n    pub fn is_singleton(&self) -> bool {\n        match self {\n            ValTensor::Value { inner, .. } => inner.is_singleton(),\n            ValTensor::Instance { .. } => false,\n        }\n    }\n\n    /// Calls `int_evals` on the inner tensor.\n    pub fn get_int_evals(&self) -> Result<Tensor<i128>, Box<dyn Error>> {\n        // finally convert to vector of integers\n        let mut integer_evals: Vec<i128> = vec![];\n        match self {\n            ValTensor::Value {\n                inner: v, dims: _, ..\n            } => {\n                // we have to push to an externally created vector or else vaf.map() returns an evaluation wrapped in Value<> (which we don't want)\n                let _ = v.map(|vaf| match vaf {\n                    ValType::Value(v) => v.map(|f| {\n                        integer_evals.push(crate::fieldutils::felt_to_i128(f));\n                    }),\n                    ValType::AssignedValue(v) => v.map(|f| {\n                        integer_evals.push(crate::fieldutils::felt_to_i128(f.evaluate()));\n                    }),\n                    ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                        v.value_field().map(|f| {\n                            integer_evals.push(crate::fieldutils::felt_to_i128(f.evaluate()));\n                        })\n                    }\n                    ValType::Constant(v) => {\n                        integer_evals.push(crate::fieldutils::felt_to_i128(v));\n                        Value::unknown()\n                    }\n                });\n            }\n            _ => return Err(Box::new(TensorError::WrongMethod)),\n        };\n        let mut tensor: Tensor<i128> = integer_evals.into_iter().into();\n        match tensor.reshape(self.dims()) {\n            _ => {}\n        };\n\n        Ok(tensor)\n    }\n\n    /// Calls `pad_to_zero_rem` on the inner tensor.\n    pub fn pad_to_zero_rem(&mut self, n: usize, pad: ValType<F>) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.pad_to_zero_rem(n, pad)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(())\n    }\n\n    /// Calls `get_slice` on the inner tensor.\n    pub fn get_slice(&self, indices: &[Range<usize>]) -> Result<ValTensor<F>, Box<dyn Error>> {\n        if indices.iter().map(|x| x.end - x.start).collect::<Vec<_>>() == self.dims() {\n            return Ok(self.clone());\n        }\n        let slice = match self {\n            ValTensor::Value {\n                inner: v,\n                dims: _,\n                scale,\n            } => {\n                let inner = v.get_slice(indices)?;\n                let dims = inner.dims().to_vec();\n                ValTensor::Value {\n                    inner,\n                    dims,\n                    scale: *scale,\n                }\n            }\n            _ => return Err(Box::new(TensorError::WrongMethod)),\n        };\n        Ok(slice)\n    }\n\n    /// Calls `get_single_elem` on the inner tensor.\n    pub fn get_single_elem(&self, index: usize) -> Result<ValTensor<F>, Box<dyn Error>> {\n        let slice = match self {\n            ValTensor::Value {\n                inner: v,\n                dims: _,\n                scale,\n            } => {\n                let inner = Tensor::from(vec![v.get_flat_index(index)].into_iter());\n                ValTensor::Value {\n                    inner,\n                    dims: vec![1],\n                    scale: *scale,\n                }\n            }\n            _ => return Err(Box::new(TensorError::WrongMethod)),\n        };\n        Ok(slice)\n    }\n\n    /// Fetches the inner tensor as a `Tensor<ValType<F>`\n    pub fn get_inner_tensor(&self) -> Result<&Tensor<ValType<F>>, TensorError> {\n        Ok(match self {\n            ValTensor::Value { inner: v, .. } => v,\n            ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),\n        })\n    }\n\n    /// Fetches the inner tensor as a `Tensor<ValType<F>`\n    pub fn get_inner_tensor_mut(&mut self) -> Result<&mut Tensor<ValType<F>>, TensorError> {\n        Ok(match self {\n            ValTensor::Value { inner: v, .. } => v,\n            ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),\n        })\n    }\n\n    /// Fetches the inner tensor as a `Tensor<Value<F>>`\n    pub fn get_inner(&self) -> Result<Tensor<Value<F>>, TensorError> {\n        Ok(match self {\n            ValTensor::Value { inner: v, .. } => v.map(|x| match x {\n                ValType::Value(v) => v,\n                ValType::AssignedValue(v) => v.evaluate(),\n                ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                    v.value_field().evaluate()\n                }\n                ValType::Constant(v) => Value::known(v),\n            }),\n            ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),\n        })\n    }\n    /// Calls `expand` on the inner tensor.\n    pub fn expand(&mut self, dims: &[usize]) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.expand(dims)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(())\n    }\n\n    /// Calls `move_axis` on the inner tensor.\n    pub fn move_axis(&mut self, source: usize, destination: usize) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.move_axis(source, destination)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(())\n    }\n\n    /// Sets the [ValTensor]'s shape.\n    pub fn reshape(&mut self, new_dims: &[usize]) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                v.reshape(new_dims)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { dims: d, idx, .. } => {\n                if d[*idx].iter().product::<usize>() != new_dims.iter().product::<usize>() {\n                    return Err(Box::new(TensorError::DimError(format!(\n                        \"Cannot reshape {:?} to {:?} as they have number of elements\",\n                        d[*idx], new_dims\n                    ))));\n                }\n                d[*idx] = new_dims.to_vec();\n            }\n        };\n        Ok(())\n    }\n\n    /// Sets the [ValTensor]'s shape.\n    pub fn slice(\n        &mut self,\n        axis: &usize,\n        start: &usize,\n        end: &usize,\n    ) -> Result<(), Box<dyn Error>> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = crate::tensor::ops::slice(v, axis, start, end)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(())\n    }\n\n    /// Calls `flatten` on the inner [Tensor].\n    pub fn flatten(&mut self) {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                v.flatten();\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { dims: d, idx, .. } => {\n                d[*idx] = vec![d[*idx].iter().product()];\n            }\n        }\n    }\n\n    /// Calls `duplicate_every_n` on the inner [Tensor].\n    pub fn duplicate_every_n(\n        &mut self,\n        n: usize,\n        num_repeats: usize,\n        initial_offset: usize,\n    ) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.duplicate_every_n(n, num_repeats, initial_offset)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(TensorError::WrongMethod);\n            }\n        }\n        Ok(())\n    }\n\n    /// gets constants\n    pub fn get_const_zero_indices(&self) -> Result<Vec<usize>, TensorError> {\n        match self {\n            ValTensor::Value { inner: v, .. } => {\n                let mut indices = vec![];\n                for (i, e) in v.iter().enumerate() {\n                    if let ValType::Constant(r) = e {\n                        if *r == F::ZERO {\n                            indices.push(i);\n                        }\n                    } else if let ValType::AssignedConstant(_, r) = e {\n                        if *r == F::ZERO {\n                            indices.push(i);\n                        }\n                    }\n                }\n                Ok(indices)\n            }\n            ValTensor::Instance { .. } => Ok(vec![]),\n        }\n    }\n\n    /// gets constants\n    pub fn get_const_indices(&self) -> Result<Vec<usize>, TensorError> {\n        match self {\n            ValTensor::Value { inner: v, .. } => {\n                let mut indices = vec![];\n                for (i, e) in v.iter().enumerate() {\n                    if let ValType::Constant(_) = e {\n                        indices.push(i);\n                    } else if let ValType::AssignedConstant(_, _) = e {\n                        indices.push(i);\n                    }\n                }\n                Ok(indices)\n            }\n            ValTensor::Instance { .. } => Ok(vec![]),\n        }\n    }\n\n    /// calls `remove_indices` on the inner [Tensor].\n    pub fn remove_indices(\n        &mut self,\n        indices: &mut [usize],\n        is_sorted: bool,\n    ) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                // this is very slow how can we speed this up ?\n                *v = v.remove_indices(indices, is_sorted)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                if indices.is_empty() {\n                    return Ok(());\n                } else {\n                    return Err(TensorError::WrongMethod);\n                }\n            }\n        }\n        Ok(())\n    }\n\n    /// Calls `duplicate_every_n` on the inner [Tensor].\n    pub fn remove_every_n(\n        &mut self,\n        n: usize,\n        num_repeats: usize,\n        initial_offset: usize,\n    ) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.remove_every_n(n, num_repeats, initial_offset)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(TensorError::WrongMethod);\n            }\n        }\n        Ok(())\n    }\n\n    /// Calls `intercalate_values` on the inner [Tensor].\n    pub fn intercalate_values(\n        &mut self,\n        value: ValType<F>,\n        stride: usize,\n        axis: usize,\n    ) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = intercalate_values(v, value, stride, axis)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(TensorError::WrongMethod);\n            }\n        }\n        Ok(())\n    }\n    /// Calls `resize` on the inner [Tensor].\n    pub fn resize(&mut self, scales: &[usize]) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = resize(v, scales)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(TensorError::WrongMethod);\n            }\n        };\n        Ok(())\n    }\n    /// Calls `pad_spatial_dims` on the inner [Tensor].\n    pub fn pad(&mut self, padding: Vec<(usize, usize)>, offset: usize) -> Result<(), TensorError> {\n        match self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = pad(v, padding, offset)?;\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(TensorError::WrongMethod);\n            }\n        }\n        Ok(())\n    }\n\n    /// Calls `len` on the inner [Tensor].\n    pub fn len(&self) -> usize {\n        match self {\n            ValTensor::Value { dims, .. } => {\n                if !dims.is_empty() && (dims != &[0]) {\n                    dims.iter().product::<usize>()\n                } else {\n                    0\n                }\n            }\n            ValTensor::Instance { dims, idx, .. } => {\n                let dims = dims[*idx].clone();\n                if !dims.is_empty() && (dims != [0]) {\n                    dims.iter().product::<usize>()\n                } else {\n                    0\n                }\n            }\n        }\n    }\n\n    ///\n    pub fn is_empty(&self) -> bool {\n        self.len() == 0\n    }\n\n    /// Calls `concats` on the inner [Tensor].\n    pub fn concat(&self, other: Self) -> Result<Self, TensorError> {\n        let res = match (self, other) {\n            (ValTensor::Value { inner: v1, .. }, ValTensor::Value { inner: v2, .. }) => {\n                ValTensor::from(Tensor::new(Some(&[v1.clone(), v2]), &[2])?.combine()?)\n            }\n            _ => {\n                return Err(TensorError::WrongMethod);\n            }\n        };\n        Ok(res)\n    }\n\n    /// Calls `concats` on the inner [Tensor].\n    pub fn concat_axis(&self, other: Self, axis: &usize) -> Result<Self, TensorError> {\n        let res = match (self, other) {\n            (ValTensor::Value { inner: v1, .. }, ValTensor::Value { inner: v2, .. }) => {\n                let v = crate::tensor::ops::concat(&[v1, &v2], *axis)?;\n                ValTensor::from(v)\n            }\n            _ => {\n                return Err(TensorError::WrongMethod);\n            }\n        };\n        Ok(res)\n    }\n\n    /// Returns the `dims` attribute of the [ValTensor].\n    pub fn dims(&self) -> &[usize] {\n        match self {\n            ValTensor::Value { dims: d, .. } => d,\n            ValTensor::Instance { dims: d, idx, .. } => &d[*idx],\n        }\n    }\n    /// A [String] representation of the [ValTensor] for display, for example in showing intermediate values in a computational graph.\n    pub fn show(&self) -> String {\n        match self.clone() {\n            ValTensor::Value {\n                inner: v, dims: _, ..\n            } => {\n                let r: Tensor<i32> = v.map(|x| x.into());\n                if r.len() > 10 {\n                    let start = r[..5].to_vec();\n                    let end = r[r.len() - 5..].to_vec();\n                    // print the two split by ... in the middle\n                    format!(\n                        \"[{} ... {}]\",\n                        start.iter().map(|x| format!(\"{}\", x)).join(\", \"),\n                        end.iter().map(|x| format!(\"{}\", x)).join(\", \")\n                    )\n                } else {\n                    format!(\"{:?}\", r)\n                }\n            }\n            _ => \"ValTensor not PrevAssigned\".into(),\n        }\n    }\n}\n\nimpl<F: PrimeField + TensorType + PartialOrd> ValTensor<F> {\n    /// inverts the inner values\n    pub fn inverse(&self) -> Result<ValTensor<F>, Box<dyn Error>> {\n        let mut cloned_self = self.clone();\n\n        match &mut cloned_self {\n            ValTensor::Value {\n                inner: v, dims: d, ..\n            } => {\n                *v = v.map(|x| match x {\n                    ValType::AssignedValue(v) => ValType::AssignedValue(v.invert()),\n                    ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {\n                        ValType::AssignedValue(v.value_field().invert())\n                    }\n                    ValType::Value(v) => ValType::Value(v.map(|x| x.invert().unwrap_or(F::ZERO))),\n                    ValType::Constant(v) => ValType::Constant(v.invert().unwrap_or(F::ZERO)),\n                });\n                *d = v.dims().to_vec();\n            }\n            ValTensor::Instance { .. } => {\n                return Err(Box::new(TensorError::WrongMethod));\n            }\n        };\n        Ok(cloned_self)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/tensor/var.rs",
        "content": "use std::collections::HashSet;\n\nuse log::{debug, error, warn};\n\nuse crate::circuit::{region::ConstantsMap, CheckMode};\n\nuse super::*;\n/// A wrapper around Halo2's `Column<Fixed>` or `Column<Advice>`.\n/// Typically assign [ValTensor]s to [VarTensor]s when laying out a circuit.\n#[derive(Clone, Default, Debug, PartialEq, Eq)]\npub enum VarTensor {\n    /// A VarTensor for holding Advice values, which are assigned at proving time.\n    Advice {\n        /// Vec of Advice columns, we have [[xx][xx][xx]...] where each inner vec is xx columns\n        inner: Vec<Vec<Column<Advice>>>,\n        ///\n        num_inner_cols: usize,\n        /// Number of rows available to be used in each column of the storage\n        col_size: usize,\n    },\n    /// Dummy var\n    Dummy {\n        ///\n        num_inner_cols: usize,\n        /// Number of rows available to be used in each column of the storage\n        col_size: usize,\n    },\n    /// Empty var\n    #[default]\n    Empty,\n}\n\nimpl VarTensor {\n    ///\n    pub fn is_advice(&self) -> bool {\n        matches!(self, VarTensor::Advice { .. })\n    }\n\n    ///\n    pub fn max_rows<F: PrimeField>(cs: &ConstraintSystem<F>, logrows: usize) -> usize {\n        let base = 2u32;\n        base.pow(logrows as u32) as usize - cs.blinding_factors() - 1\n    }\n\n    /// Create a new VarTensor::Advice that is unblinded\n    /// Arguments\n    /// * `cs` - The constraint system\n    /// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.\n    /// * `capacity` - The number of advice cells to allocate\n    pub fn new_unblinded_advice<F: PrimeField>(\n        cs: &mut ConstraintSystem<F>,\n        logrows: usize,\n        num_inner_cols: usize,\n        capacity: usize,\n    ) -> Self {\n        let max_rows = Self::max_rows(cs, logrows) * num_inner_cols;\n\n        let mut modulo = (capacity / max_rows) + 1;\n        // we add a buffer for duplicated rows (we get at most 1 duplicated row per column)\n        modulo = ((capacity + modulo) / max_rows) + 1;\n        let mut advices = vec![];\n\n        if modulo > 1 {\n            warn!(\n                \"using column duplication for {} unblinded advice blocks\",\n                modulo - 1\n            );\n        }\n\n        for _ in 0..modulo {\n            let mut inner = vec![];\n            for _ in 0..num_inner_cols {\n                let col = cs.unblinded_advice_column();\n                cs.enable_equality(col);\n                inner.push(col);\n            }\n            advices.push(inner);\n        }\n\n        VarTensor::Advice {\n            inner: advices,\n            num_inner_cols,\n            col_size: max_rows,\n        }\n    }\n\n    /// Create a new VarTensor::Advice\n    /// Arguments\n    /// * `cs` - The constraint system\n    /// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.\n    /// * `capacity` - The number of advice cells to allocate\n    pub fn new_advice<F: PrimeField>(\n        cs: &mut ConstraintSystem<F>,\n        logrows: usize,\n        num_inner_cols: usize,\n        capacity: usize,\n    ) -> Self {\n        let max_rows = Self::max_rows(cs, logrows);\n        let max_assignments = Self::max_rows(cs, logrows) * num_inner_cols;\n\n        let mut modulo = (capacity / max_assignments) + 1;\n        // we add a buffer for duplicated rows (we get at most 1 duplicated row per column)\n        modulo = ((capacity + modulo) / max_assignments) + 1;\n        let mut advices = vec![];\n\n        if modulo > 1 {\n            debug!(\"using column duplication for {} advice blocks\", modulo - 1);\n        }\n\n        for _ in 0..modulo {\n            let mut inner = vec![];\n            for _ in 0..num_inner_cols {\n                let col = cs.advice_column();\n                cs.enable_equality(col);\n                inner.push(col);\n            }\n            advices.push(inner);\n        }\n\n        VarTensor::Advice {\n            inner: advices,\n            num_inner_cols,\n            col_size: max_rows,\n        }\n    }\n\n    /// Initializes fixed columns to support the VarTensor::Advice\n    /// Arguments\n    /// * `cs` - The constraint system\n    /// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.\n    /// * `capacity` - The number of advice cells to allocate\n    pub fn constant_cols<F: PrimeField>(\n        cs: &mut ConstraintSystem<F>,\n        logrows: usize,\n        num_constants: usize,\n        module_requires_fixed: bool,\n    ) -> usize {\n        if num_constants == 0 && !module_requires_fixed {\n            return 0;\n        } else if num_constants == 0 && module_requires_fixed {\n            let col = cs.fixed_column();\n            cs.enable_constant(col);\n            return 1;\n        }\n\n        let max_rows = Self::max_rows(cs, logrows);\n\n        let mut modulo = num_constants / max_rows + 1;\n        // we add a buffer for duplicated rows (we get at most 1 duplicated row per column)\n        modulo = (num_constants + modulo) / max_rows + 1;\n\n        if modulo > 1 {\n            debug!(\"using column duplication for {} fixed columns\", modulo - 1);\n        }\n\n        for _ in 0..modulo {\n            let col = cs.fixed_column();\n            cs.enable_constant(col);\n        }\n        modulo\n    }\n\n    /// Create a new VarTensor::Dummy\n    pub fn dummy(logrows: usize, num_inner_cols: usize) -> Self {\n        let base = 2u32;\n        let max_rows = base.pow(logrows as u32) as usize - 6;\n        VarTensor::Dummy {\n            col_size: max_rows,\n            num_inner_cols,\n        }\n    }\n\n    /// Gets the dims of the object the VarTensor represents\n    pub fn num_blocks(&self) -> usize {\n        match self {\n            VarTensor::Advice { inner, .. } => inner.len(),\n            _ => 0,\n        }\n    }\n\n    /// Num inner cols\n    pub fn num_inner_cols(&self) -> usize {\n        match self {\n            VarTensor::Advice { num_inner_cols, .. } | VarTensor::Dummy { num_inner_cols, .. } => {\n                *num_inner_cols\n            }\n            _ => 0,\n        }\n    }\n\n    /// Total number of columns\n    pub fn num_cols(&self) -> usize {\n        match self {\n            VarTensor::Advice { inner, .. } => inner[0].len() * inner.len(),\n            _ => 0,\n        }\n    }\n\n    /// Gets the size of each column\n    pub fn col_size(&self) -> usize {\n        match self {\n            VarTensor::Advice { col_size, .. } | VarTensor::Dummy { col_size, .. } => *col_size,\n            _ => 0,\n        }\n    }\n\n    /// Gets the size of each column\n    pub fn block_size(&self) -> usize {\n        match self {\n            VarTensor::Advice {\n                num_inner_cols,\n                col_size,\n                ..\n            }\n            | VarTensor::Dummy {\n                col_size,\n                num_inner_cols,\n                ..\n            } => *col_size * num_inner_cols,\n            _ => 0,\n        }\n    }\n\n    /// Take a linear coordinate and output the (column, row) position in the storage block.\n    pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize, usize) {\n        // x indexes over blocks of size num_inner_cols\n        let x = linear_coord / self.block_size();\n        // y indexes over the cols inside a block\n        let y = linear_coord % self.num_inner_cols();\n        // z indexes over the rows inside a col\n        let z = (linear_coord - x * self.block_size()) / self.num_inner_cols();\n        (x, y, z)\n    }\n}\n\nimpl VarTensor {\n    /// Retrieve the value of a specific cell in the tensor.\n    pub fn query_rng<F: PrimeField>(\n        &self,\n        meta: &mut VirtualCells<'_, F>,\n        x: usize,\n        y: usize,\n        z: i32,\n        rng: usize,\n    ) -> Result<Tensor<Expression<F>>, halo2_proofs::plonk::Error> {\n        match &self {\n            // when advice we have 1 col per row\n            VarTensor::Advice { inner: advices, .. } => {\n                let c = Tensor::from(\n                    // this should fail if dims is empty, should be impossible\n                    (0..rng).map(|i| meta.query_advice(advices[x][y], Rotation(z + i as i32))),\n                );\n                Ok(c)\n            }\n            _ => {\n                error!(\"VarTensor was not initialized\");\n                Err(halo2_proofs::plonk::Error::Synthesis)\n            }\n        }\n    }\n\n    /// Retrieve the value of a specific block at an offset in the tensor.\n    pub fn query_whole_block<F: PrimeField>(\n        &self,\n        meta: &mut VirtualCells<'_, F>,\n        x: usize,\n        z: i32,\n        rng: usize,\n    ) -> Result<Tensor<Expression<F>>, halo2_proofs::plonk::Error> {\n        match &self {\n            // when advice we have 1 col per row\n            VarTensor::Advice { inner: advices, .. } => {\n                let c = Tensor::from({\n                    // this should fail if dims is empty, should be impossible\n                    let cartesian = (0..rng).cartesian_product(0..self.num_inner_cols());\n                    cartesian.map(|(i, y)| meta.query_advice(advices[x][y], Rotation(z + i as i32)))\n                });\n                Ok(c)\n            }\n            _ => {\n                error!(\"VarTensor was not initialized\");\n                Err(halo2_proofs::plonk::Error::Synthesis)\n            }\n        }\n    }\n\n    /// Assigns a constant value to a specific cell in the tensor.\n    pub fn assign_constant<F: PrimeField + TensorType + PartialOrd>(\n        &self,\n        region: &mut Region<F>,\n        offset: usize,\n        coord: usize,\n        constant: F,\n    ) -> Result<AssignedCell<F, F>, halo2_proofs::plonk::Error> {\n        let (x, y, z) = self.cartesian_coord(offset + coord);\n        match &self {\n            VarTensor::Advice { inner: advices, .. } => {\n                region.assign_advice_from_constant(|| \"constant\", advices[x][y], z, constant)\n            }\n            _ => {\n                error!(\"VarTensor was not initialized\");\n                Err(halo2_proofs::plonk::Error::Synthesis)\n            }\n        }\n    }\n\n    /// Assigns [ValTensor] to the columns of the inner tensor.\n    pub fn assign_with_omissions<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n        &self,\n        region: &mut Region<F>,\n        offset: usize,\n        values: &ValTensor<F>,\n        omissions: &HashSet<&usize>,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<ValTensor<F>, halo2_proofs::plonk::Error> {\n        let mut assigned_coord = 0;\n        let mut res: ValTensor<F> = match values {\n            ValTensor::Instance { .. } => {\n                unimplemented!(\"cannot assign instance to advice columns with omissions\")\n            }\n            ValTensor::Value { inner: v, .. } => Ok::<ValTensor<F>, halo2_proofs::plonk::Error>(\n                v.enum_map(|coord, k| {\n                    if omissions.contains(&coord) {\n                        return Ok::<_, halo2_proofs::plonk::Error>(k);\n                    }\n                    let cell =\n                        self.assign_value(region, offset, k.clone(), assigned_coord, constants)?;\n                    assigned_coord += 1;\n                    Ok::<_, halo2_proofs::plonk::Error>(cell)\n                })?\n                .into(),\n            ),\n        }?;\n        res.set_scale(values.scale());\n        Ok(res)\n    }\n\n    /// Assigns [ValTensor] to the columns of the inner tensor.\n    pub fn assign<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n        &self,\n        region: &mut Region<F>,\n        offset: usize,\n        values: &ValTensor<F>,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<ValTensor<F>, halo2_proofs::plonk::Error> {\n        let mut res: ValTensor<F> = match values {\n            ValTensor::Instance {\n                inner: instance,\n                dims,\n                idx,\n                initial_offset,\n                ..\n            } => match &self {\n                VarTensor::Advice { inner: v, .. } => {\n                    let total_offset: usize = initial_offset\n                        + dims[..*idx]\n                            .iter()\n                            .map(|x| x.iter().product::<usize>())\n                            .sum::<usize>();\n                    let dims = &dims[*idx];\n                    // this should never ever fail\n                    let t: Tensor<i32> = Tensor::new(None, dims).unwrap();\n                    Ok(t.enum_map(|coord, _| {\n                        let (x, y, z) = self.cartesian_coord(offset + coord);\n                        region.assign_advice_from_instance(\n                            || \"pub input anchor\",\n                            *instance,\n                            coord + total_offset,\n                            v[x][y],\n                            z,\n                        )\n                    })?\n                    .into())\n                }\n                _ => {\n                    error!(\"Instance is only supported for advice columns\");\n                    Err(halo2_proofs::plonk::Error::Synthesis)\n                }\n            },\n            ValTensor::Value { inner: v, .. } => Ok(v\n                .enum_map(|coord, k| {\n                    self.assign_value(region, offset, k.clone(), coord, constants)\n                })?\n                .into()),\n        }?;\n        res.set_scale(values.scale());\n        Ok(res)\n    }\n\n    /// Assigns specific values (`ValTensor`) to the columns of the inner tensor but allows for column wrapping for accumulated operations.\n    /// Duplication occurs by copying the last cell of the column to the first cell next column and creating a copy constraint between the two.\n    pub fn dummy_assign_with_duplication<\n        F: PrimeField + TensorType + PartialOrd + std::hash::Hash,\n    >(\n        &self,\n        row: usize,\n        offset: usize,\n        values: &ValTensor<F>,\n        single_inner_col: bool,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<(ValTensor<F>, usize), halo2_proofs::plonk::Error> {\n        match values {\n            ValTensor::Instance { .. } => unimplemented!(\"duplication is not supported on instance columns. increase K if you require more rows.\"),\n            ValTensor::Value { inner: v, dims , ..} => {\n                let duplication_freq = if single_inner_col {\n                    self.col_size()\n                } else {\n                    self.block_size()\n                };\n\n                let num_repeats = if single_inner_col {\n                    1\n                } else {\n                    self.num_inner_cols()\n                };\n\n                let duplication_offset = if single_inner_col {\n                    row\n                } else {\n                    offset\n                };\n\n\n                // duplicates every nth element to adjust for column overflow\n                let mut res: ValTensor<F> = v.duplicate_every_n(duplication_freq, num_repeats, duplication_offset).unwrap().into();\n\n                let constants_map = res.create_constants_map();\n                constants.extend(constants_map);\n\n                let total_used_len = res.len();\n                res.remove_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();\n\n                res.reshape(dims).unwrap();\n                res.set_scale(values.scale());\n\n                Ok((res, total_used_len))\n            }\n        }\n    }\n\n    /// Assigns specific values (`ValTensor`) to the columns of the inner tensor but allows for column wrapping for accumulated operations.\n    /// Duplication occurs by copying the last cell of the column to the first cell next column and creating a copy constraint between the two.\n    pub fn assign_with_duplication<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n        &self,\n        region: &mut Region<F>,\n        row: usize,\n        offset: usize,\n        values: &ValTensor<F>,\n        check_mode: &CheckMode,\n        single_inner_col: bool,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<(ValTensor<F>, usize), halo2_proofs::plonk::Error> {\n        let mut prev_cell = None;\n\n        match values {\n            ValTensor::Instance { .. } => unimplemented!(\"duplication is not supported on instance columns. increase K if you require more rows.\"),\n            ValTensor::Value { inner: v, dims , ..} => {\n\n                let duplication_freq = if single_inner_col {\n                    self.col_size()\n                } else {\n                    self.block_size()\n                };\n\n                let num_repeats = if single_inner_col {\n                    1\n                } else {\n                    self.num_inner_cols()\n                };\n\n                let duplication_offset = if single_inner_col {\n                    row\n                } else {\n                    offset\n                };\n\n                // duplicates every nth element to adjust for column overflow\n                let v = v.duplicate_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();\n                let mut res: ValTensor<F> = {\n                    v.enum_map(|coord, k| {\n\n                    let step = if !single_inner_col {\n                        1\n                    } else {\n                        self.num_inner_cols()\n                    };\n\n                    let (x, y, z) = self.cartesian_coord(offset + coord * step);\n                    if matches!(check_mode, CheckMode::SAFE) && coord > 0 && z == 0 && y == 0 {\n                        // assert that duplication occurred correctly\n                        assert_eq!(Into::<i32>::into(k.clone()), Into::<i32>::into(v[coord - 1].clone()));\n                    };\n\n                    let cell = self.assign_value(region, offset, k.clone(), coord * step, constants)?;\n\n                    if single_inner_col {\n                    if z == 0 {\n                        // if we are at the end of the column, we need to copy the cell to the next column\n                        prev_cell = Some(cell.clone());\n                    } else if coord > 0 && z == 0 && single_inner_col {\n                        if let Some(prev_cell) = prev_cell.as_ref() {\n                            let cell = cell.cell().ok_or({\n                                error!(\"Error getting cell: {:?}\", (x,y));\n                                halo2_proofs::plonk::Error::Synthesis})?;\n                            let prev_cell = prev_cell.cell().ok_or({\n                                error!(\"Error getting cell: {:?}\", (x,y));\n                                halo2_proofs::plonk::Error::Synthesis})?;\n                            region.constrain_equal(prev_cell,cell)?;\n                        } else {\n                            error!(\"Error copy-constraining previous value: {:?}\", (x,y));\n                            return Err(halo2_proofs::plonk::Error::Synthesis);\n                        }\n                    }}\n\n                    Ok(cell)\n\n                })?.into()};\n                let total_used_len = res.len();\n                res.remove_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();\n\n                res.reshape(dims).unwrap();\n                res.set_scale(values.scale());\n\n                if matches!(check_mode, CheckMode::SAFE) {\n                     // during key generation this will be 0 so we use this as a flag to check\n                     // TODO: this isn't very safe and would be better to get the phase directly\n                    let is_assigned = !Into::<Tensor<i32>>::into(res.clone().get_inner().unwrap())\n                    .iter()\n                    .all(|&x| x == 0);\n                    if is_assigned {\n                        assert_eq!(\n                            Into::<Tensor<i32>>::into(values.get_inner().unwrap()),\n                            Into::<Tensor<i32>>::into(res.get_inner().unwrap())\n                    )};\n                }\n\n                Ok((res, total_used_len))\n            }\n        }\n    }\n\n    fn assign_value<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(\n        &self,\n        region: &mut Region<F>,\n        offset: usize,\n        k: ValType<F>,\n        coord: usize,\n        constants: &mut ConstantsMap<F>,\n    ) -> Result<ValType<F>, halo2_proofs::plonk::Error> {\n        let (x, y, z) = self.cartesian_coord(offset + coord);\n        let res = match k {\n            ValType::Value(v) => match &self {\n                VarTensor::Advice { inner: advices, .. } => {\n                    ValType::PrevAssigned(region.assign_advice(|| \"k\", advices[x][y], z, || v)?)\n                }\n                _ => unimplemented!(),\n            },\n            ValType::PrevAssigned(v) => match &self {\n                VarTensor::Advice { inner: advices, .. } => {\n                    ValType::PrevAssigned(v.copy_advice(|| \"k\", region, advices[x][y], z)?)\n                }\n                _ => unimplemented!(),\n            },\n            ValType::AssignedConstant(v, val) => match &self {\n                VarTensor::Advice { inner: advices, .. } => {\n                    ValType::AssignedConstant(v.copy_advice(|| \"k\", region, advices[x][y], z)?, val)\n                }\n                _ => unimplemented!(),\n            },\n            ValType::AssignedValue(v) => match &self {\n                VarTensor::Advice { inner: advices, .. } => ValType::PrevAssigned(\n                    region\n                        .assign_advice(|| \"k\", advices[x][y], z, || v)?\n                        .evaluate(),\n                ),\n                _ => unimplemented!(),\n            },\n            ValType::Constant(v) => {\n                if let std::collections::hash_map::Entry::Vacant(e) = constants.entry(v) {\n                    let value = ValType::AssignedConstant(\n                        self.assign_constant(region, offset, coord, v)?,\n                        v,\n                    );\n                    e.insert(value.clone());\n                    value\n                } else {\n                    let cell = constants.get(&v).unwrap();\n                    self.assign_value(region, offset, cell.clone(), coord, constants)?\n                }\n            }\n        };\n        Ok(res)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "src/wasm.rs",
        "content": "use crate::circuit::modules::polycommit::PolyCommitChip;\nuse crate::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};\nuse crate::circuit::modules::poseidon::PoseidonChip;\nuse crate::circuit::modules::Module;\nuse crate::fieldutils::felt_to_i128;\nuse crate::fieldutils::i128_to_felt;\nuse crate::graph::modules::POSEIDON_LEN_GRAPH;\nuse crate::graph::quantize_float;\nuse crate::graph::scale_to_multiplier;\nuse crate::graph::{GraphCircuit, GraphSettings};\nuse crate::pfsys::create_proof_circuit;\nuse crate::pfsys::evm::aggregation_kzg::AggregationCircuit;\nuse crate::pfsys::evm::aggregation_kzg::PoseidonTranscript;\nuse crate::pfsys::verify_proof_circuit;\nuse crate::pfsys::TranscriptType;\nuse crate::tensor::TensorType;\nuse crate::CheckMode;\nuse crate::Commitments;\nuse console_error_panic_hook;\nuse halo2_proofs::plonk::*;\nuse halo2_proofs::poly::commitment::{CommitmentScheme, ParamsProver};\nuse halo2_proofs::poly::ipa::multiopen::{ProverIPA, VerifierIPA};\nuse halo2_proofs::poly::ipa::{\n    commitment::{IPACommitmentScheme, ParamsIPA},\n    strategy::SingleStrategy as IPASingleStrategy,\n};\nuse halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;\nuse halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;\nuse halo2_proofs::poly::kzg::{\n    commitment::{KZGCommitmentScheme, ParamsKZG},\n    strategy::SingleStrategy as KZGSingleStrategy,\n};\nuse halo2_proofs::poly::VerificationStrategy;\nuse halo2_solidity_verifier::encode_calldata;\nuse halo2curves::bn256::{Bn256, Fr, G1Affine};\nuse halo2curves::ff::{FromUniformBytes, PrimeField};\nuse snark_verifier::loader::native::NativeLoader;\nuse snark_verifier::system::halo2::transcript::evm::EvmTranscript;\nuse std::str::FromStr;\nuse wasm_bindgen::prelude::*;\nuse wasm_bindgen_console_logger::DEFAULT_LOGGER;\n\n#[cfg(feature = \"web\")]\npub use wasm_bindgen_rayon::init_thread_pool;\n\n#[wasm_bindgen]\n/// Initialize logger for wasm\npub fn init_logger() {\n    log::set_logger(&DEFAULT_LOGGER).unwrap();\n}\n\n#[wasm_bindgen]\n/// Initialize panic hook for wasm\npub fn init_panic_hook() {\n    console_error_panic_hook::set_once();\n}\n\n/// Wrapper around the halo2 encode call data method\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn encodeVerifierCalldata(\n    proof: wasm_bindgen::Clamped<Vec<u8>>,\n    vk_address: Option<Vec<u8>>,\n) -> Result<Vec<u8>, JsError> {\n    let snark: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize proof: {}\", e)))?;\n\n    let vk_address: Option<[u8; 20]> = if let Some(vk_address) = vk_address {\n        let array: [u8; 20] = serde_json::from_slice(&vk_address[..])\n            .map_err(|e| JsError::new(&format!(\"Failed to deserialize vk address: {}\", e)))?;\n        Some(array)\n    } else {\n        None\n    };\n\n    let flattened_instances = snark.instances.into_iter().flatten();\n\n    let encoded = encode_calldata(\n        vk_address,\n        &snark.proof,\n        &flattened_instances.collect::<Vec<_>>(),\n    );\n\n    Ok(encoded)\n}\n\n/// Converts a hex string to a byte array\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn feltToBigEndian(array: wasm_bindgen::Clamped<Vec<u8>>) -> Result<String, JsError> {\n    let felt: Fr = serde_json::from_slice(&array[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize field element: {}\", e)))?;\n    Ok(format!(\"{:?}\", felt))\n}\n\n/// Converts a felt to a little endian string\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn feltToLittleEndian(array: wasm_bindgen::Clamped<Vec<u8>>) -> Result<String, JsError> {\n    let felt: Fr = serde_json::from_slice(&array[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize field element: {}\", e)))?;\n    let repr = serde_json::to_string(&felt).unwrap();\n    let b: String = serde_json::from_str(&repr).unwrap();\n    Ok(b)\n}\n\n/// Converts a hex string to a byte array\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn feltToInt(\n    array: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {\n    let felt: Fr = serde_json::from_slice(&array[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize field element: {}\", e)))?;\n    Ok(wasm_bindgen::Clamped(\n        serde_json::to_vec(&felt_to_i128(felt))\n            .map_err(|e| JsError::new(&format!(\"Failed to serialize integer: {}\", e)))?,\n    ))\n}\n\n/// Converts felts to a floating point element\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn feltToFloat(\n    array: wasm_bindgen::Clamped<Vec<u8>>,\n    scale: crate::Scale,\n) -> Result<f64, JsError> {\n    let felt: Fr = serde_json::from_slice(&array[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize field element: {}\", e)))?;\n    let int_rep = felt_to_i128(felt);\n    let multiplier = scale_to_multiplier(scale);\n    Ok(int_rep as f64 / multiplier)\n}\n\n/// Converts a floating point number to a hex string representing a fixed point field element\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn floatToFelt(\n    input: f64,\n    scale: crate::Scale,\n) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {\n    let int_rep =\n        quantize_float(&input, 0.0, scale).map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n    let felt = i128_to_felt(int_rep);\n    let vec = crate::pfsys::field_to_string::<halo2curves::bn256::Fr>(&felt);\n    Ok(wasm_bindgen::Clamped(serde_json::to_vec(&vec).map_err(\n        |e| JsError::new(&format!(\"Failed to serialize a float to felt{}\", e)),\n    )?))\n}\n\n/// Generate a kzg commitment.\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn kzgCommit(\n    message: wasm_bindgen::Clamped<Vec<u8>>,\n    vk: wasm_bindgen::Clamped<Vec<u8>>,\n    settings: wasm_bindgen::Clamped<Vec<u8>>,\n    params_ser: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {\n    let message: Vec<Fr> = serde_json::from_slice(&message[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize message: {}\", e)))?;\n\n    let mut reader = std::io::BufReader::new(&params_ser[..]);\n    let params: ParamsKZG<Bn256> =\n        halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n            .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n\n    let mut reader = std::io::BufReader::new(&vk[..]);\n    let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize settings: {}\", e)))?;\n    let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit_settings,\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize vk: {}\", e)))?;\n\n    let output = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(\n        message,\n        (vk.cs().blinding_factors() + 1) as u32,\n        &params,\n    );\n\n    Ok(wasm_bindgen::Clamped(\n        serde_json::to_vec(&output).map_err(|e| JsError::new(&format!(\"{}\", e)))?,\n    ))\n}\n\n/// Converts a buffer to vector of 4 u64s representing a fixed point field element\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn bufferToVecOfFelt(\n    buffer: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {\n    // Convert the buffer to a slice\n    let buffer: &[u8] = &buffer;\n\n    // Divide the buffer into chunks of 64 bytes\n    let chunks = buffer.chunks_exact(16);\n\n    // Get the remainder\n    let remainder = chunks.remainder();\n\n    // Add 0s to the remainder to make it 64 bytes\n    let mut remainder = remainder.to_vec();\n\n    // Collect chunks into a Vec<[u8; 16]>.\n    let chunks: Result<Vec<[u8; 16]>, JsError> = chunks\n        .map(|slice| {\n            let array: [u8; 16] = slice\n                .try_into()\n                .map_err(|_| JsError::new(\"failed to slice input chunks\"))?;\n            Ok(array)\n        })\n        .collect();\n\n    let mut chunks = chunks?;\n\n    if remainder.len() != 0 {\n        remainder.resize(16, 0);\n        // Convert the Vec<u8> to [u8; 16]\n        let remainder_array: [u8; 16] = remainder\n            .try_into()\n            .map_err(|_| JsError::new(\"failed to slice remainder\"))?;\n        // append the remainder to the chunks\n        chunks.push(remainder_array);\n    }\n\n    // Convert each chunk to a field element\n    let field_elements: Vec<Fr> = chunks\n        .iter()\n        .map(|x| PrimeField::from_u128(u8_array_to_u128_le(*x)))\n        .collect();\n\n    Ok(wasm_bindgen::Clamped(\n        serde_json::to_vec(&field_elements)\n            .map_err(|e| JsError::new(&format!(\"Failed to serialize field elements: {}\", e)))?,\n    ))\n}\n\n/// Generate a poseidon hash in browser. Input message\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn poseidonHash(\n    message: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {\n    let message: Vec<Fr> = serde_json::from_slice(&message[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize message: {}\", e)))?;\n\n    let output =\n        PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(\n            message.clone(),\n        )\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n\n    Ok(wasm_bindgen::Clamped(serde_json::to_vec(&output).map_err(\n        |e| JsError::new(&format!(\"Failed to serialize poseidon hash output: {}\", e)),\n    )?))\n}\n\n/// Generate a witness file from input.json, compiled model and a settings.json file.\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn genWitness(\n    compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,\n    input: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<Vec<u8>, JsError> {\n    let mut circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize compiled model: {}\", e)))?;\n    let input: crate::graph::input::GraphData = serde_json::from_slice(&input[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize input: {}\", e)))?;\n\n    let mut input = circuit\n        .load_graph_input(&input)\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n\n    let witness = circuit\n        .forward::<KZGCommitmentScheme<Bn256>>(&mut input, None, None, false)\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n\n    serde_json::to_vec(&witness)\n        .map_err(|e| JsError::new(&format!(\"Failed to serialize witness: {}\", e)))\n}\n\n/// Generate verifying key in browser\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn genVk(\n    compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,\n    params_ser: wasm_bindgen::Clamped<Vec<u8>>,\n    compress_selectors: bool,\n) -> Result<Vec<u8>, JsError> {\n    // Read in kzg params\n    let mut reader = std::io::BufReader::new(&params_ser[..]);\n    let params: ParamsKZG<Bn256> =\n        halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n            .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n    // Read in compiled circuit\n    let circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize compiled model: {}\", e)))?;\n\n    // Create verifying key\n    let vk = create_vk_wasm::<KZGCommitmentScheme<Bn256>, Fr, GraphCircuit>(\n        &circuit,\n        &params,\n        compress_selectors,\n    )\n    .map_err(Box::<dyn std::error::Error>::from)\n    .map_err(|e| JsError::new(&format!(\"Failed to create verifying key: {}\", e)))?;\n\n    let mut serialized_vk = Vec::new();\n    vk.write(&mut serialized_vk, halo2_proofs::SerdeFormat::RawBytes)\n        .map_err(|e| JsError::new(&format!(\"Failed to serialize vk: {}\", e)))?;\n\n    Ok(serialized_vk)\n}\n\n/// Generate proving key in browser\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn genPk(\n    vk: wasm_bindgen::Clamped<Vec<u8>>,\n    compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,\n    params_ser: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<Vec<u8>, JsError> {\n    // Read in kzg params\n    let mut reader = std::io::BufReader::new(&params_ser[..]);\n    let params: ParamsKZG<Bn256> =\n        halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n            .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n    // Read in compiled circuit\n    let circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize compiled model: {}\", e)))?;\n\n    // Read in verifying key\n    let mut reader = std::io::BufReader::new(&vk[..]);\n    let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit.settings().clone(),\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize verifying key: {}\", e)))?;\n    // Create proving key\n    let pk = create_pk_wasm::<KZGCommitmentScheme<Bn256>, Fr, GraphCircuit>(vk, &circuit, &params)\n        .map_err(Box::<dyn std::error::Error>::from)\n        .map_err(|e| JsError::new(&format!(\"Failed to create proving key: {}\", e)))?;\n\n    let mut serialized_pk = Vec::new();\n    pk.write(&mut serialized_pk, halo2_proofs::SerdeFormat::RawBytes)\n        .map_err(|e| JsError::new(&format!(\"Failed to serialize pk: {}\", e)))?;\n\n    Ok(serialized_pk)\n}\n\n/// Verify proof in browser using wasm\n#[wasm_bindgen]\npub fn verify(\n    proof_js: wasm_bindgen::Clamped<Vec<u8>>,\n    vk: wasm_bindgen::Clamped<Vec<u8>>,\n    settings: wasm_bindgen::Clamped<Vec<u8>>,\n    srs: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<bool, JsError> {\n    let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize settings: {}\", e)))?;\n\n    let proof: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof_js[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize proof: {}\", e)))?;\n\n    let mut reader = std::io::BufReader::new(&vk[..]);\n    let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit_settings.clone(),\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize vk: {}\", e)))?;\n\n    let orig_n = 1 << circuit_settings.run_args.logrows;\n\n    let commitment = circuit_settings.run_args.commitment.into();\n\n    let mut reader = std::io::BufReader::new(&srs[..]);\n    let result = match commitment {\n        Commitments::KZG => {\n            let params: ParamsKZG<Bn256> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n            let strategy = KZGSingleStrategy::new(params.verifier_params());\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_proof_circuit::<\n                    VerifierSHPLONK<'_, Bn256>,\n                    KZGCommitmentScheme<Bn256>,\n                    KZGSingleStrategy<_>,\n                    _,\n                    EvmTranscript<G1Affine, _, _, _>,\n                >(&proof, &params, &vk, strategy, orig_n),\n\n                TranscriptType::Poseidon => {\n                    verify_proof_circuit::<\n                        VerifierSHPLONK<'_, Bn256>,\n                        KZGCommitmentScheme<Bn256>,\n                        KZGSingleStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(&proof, &params, &vk, strategy, orig_n)\n                }\n            }\n        }\n        Commitments::IPA => {\n            let params: ParamsIPA<_> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n            let strategy = IPASingleStrategy::new(params.verifier_params());\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_proof_circuit::<\n                    VerifierIPA<_>,\n                    IPACommitmentScheme<G1Affine>,\n                    IPASingleStrategy<_>,\n                    _,\n                    EvmTranscript<G1Affine, _, _, _>,\n                >(&proof, &params, &vk, strategy, orig_n),\n                TranscriptType::Poseidon => {\n                    verify_proof_circuit::<\n                        VerifierIPA<_>,\n                        IPACommitmentScheme<G1Affine>,\n                        IPASingleStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(&proof, &params, &vk, strategy, orig_n)\n                }\n            }\n        }\n    };\n\n    match result {\n        Ok(_) => Ok(true),\n        Err(e) => Err(JsError::new(&format!(\"{}\", e))),\n    }\n}\n\n#[wasm_bindgen]\n#[allow(non_snake_case)]\n/// Verify aggregate proof in browser using wasm\npub fn verifyAggr(\n    proof_js: wasm_bindgen::Clamped<Vec<u8>>,\n    vk: wasm_bindgen::Clamped<Vec<u8>>,\n    logrows: u64,\n    srs: wasm_bindgen::Clamped<Vec<u8>>,\n    commitment: &str,\n) -> Result<bool, JsError> {\n    let proof: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof_js[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize proof: {}\", e)))?;\n\n    let mut reader = std::io::BufReader::new(&vk[..]);\n    let vk = VerifyingKey::<G1Affine>::read::<_, AggregationCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        (),\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize vk: {}\", e)))?;\n\n    let commit = Commitments::from_str(commitment).map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n\n    let orig_n = 1 << logrows;\n\n    let mut reader = std::io::BufReader::new(&srs[..]);\n    let result = match commit {\n        Commitments::KZG => {\n            let params: ParamsKZG<Bn256> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n            let strategy = KZGSingleStrategy::new(params.verifier_params());\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_proof_circuit::<\n                    VerifierSHPLONK<'_, Bn256>,\n                    KZGCommitmentScheme<Bn256>,\n                    KZGSingleStrategy<_>,\n                    _,\n                    EvmTranscript<G1Affine, _, _, _>,\n                >(&proof, &params, &vk, strategy, orig_n),\n\n                TranscriptType::Poseidon => {\n                    verify_proof_circuit::<\n                        VerifierSHPLONK<'_, Bn256>,\n                        KZGCommitmentScheme<Bn256>,\n                        KZGSingleStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(&proof, &params, &vk, strategy, orig_n)\n                }\n            }\n        }\n        Commitments::IPA => {\n            let params: ParamsIPA<_> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n            let strategy = IPASingleStrategy::new(params.verifier_params());\n            match proof.transcript_type {\n                TranscriptType::EVM => verify_proof_circuit::<\n                    VerifierIPA<_>,\n                    IPACommitmentScheme<G1Affine>,\n                    IPASingleStrategy<_>,\n                    _,\n                    EvmTranscript<G1Affine, _, _, _>,\n                >(&proof, &params, &vk, strategy, orig_n),\n                TranscriptType::Poseidon => {\n                    verify_proof_circuit::<\n                        VerifierIPA<_>,\n                        IPACommitmentScheme<G1Affine>,\n                        IPASingleStrategy<_>,\n                        _,\n                        PoseidonTranscript<NativeLoader, _>,\n                    >(&proof, &params, &vk, strategy, orig_n)\n                }\n            }\n        }\n    };\n\n    match result {\n        Ok(_) => Ok(true),\n        Err(e) => Err(JsError::new(&format!(\"{}\", e))),\n    }\n}\n\n/// Prove in browser using wasm\n#[wasm_bindgen]\npub fn prove(\n    witness: wasm_bindgen::Clamped<Vec<u8>>,\n    pk: wasm_bindgen::Clamped<Vec<u8>>,\n    compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,\n    srs: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<Vec<u8>, JsError> {\n    #[cfg(feature = \"det-prove\")]\n    log::set_max_level(log::LevelFilter::Debug);\n    #[cfg(not(feature = \"det-prove\"))]\n    log::set_max_level(log::LevelFilter::Info);\n\n    // read in circuit\n    let mut circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize circuit: {}\", e)))?;\n\n    // read in model input\n    let data: crate::graph::GraphWitness = serde_json::from_slice(&witness[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize witness: {}\", e)))?;\n\n    // read in proving key\n    let mut reader = std::io::BufReader::new(&pk[..]);\n    let pk = ProvingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit.settings().clone(),\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize proving key: {}\", e)))?;\n\n    // prep public inputs\n    circuit\n        .load_graph_witness(&data)\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n    let public_inputs = circuit\n        .prepare_public_inputs(&data)\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n    let proof_split_commits: Option<crate::pfsys::ProofSplitCommit> = data.into();\n\n    // read in kzg params\n    let mut reader = std::io::BufReader::new(&srs[..]);\n    let commitment = circuit.settings().run_args.commitment.into();\n    // creates and verifies the proof\n    let proof = match commitment {\n        Commitments::KZG => {\n            let params: ParamsKZG<Bn256> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize srs: {}\", e)))?;\n\n            create_proof_circuit::<\n                KZGCommitmentScheme<Bn256>,\n                _,\n                ProverSHPLONK<_>,\n                VerifierSHPLONK<_>,\n                KZGSingleStrategy<_>,\n                _,\n                EvmTranscript<_, _, _, _>,\n                EvmTranscript<_, _, _, _>,\n            >(\n                circuit,\n                vec![public_inputs],\n                &params,\n                &pk,\n                CheckMode::UNSAFE,\n                crate::Commitments::KZG,\n                TranscriptType::EVM,\n                proof_split_commits,\n                None,\n            )\n        }\n        Commitments::IPA => {\n            let params: ParamsIPA<_> =\n                halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n                    .map_err(|e| JsError::new(&format!(\"Failed to deserialize srs: {}\", e)))?;\n\n            create_proof_circuit::<\n                IPACommitmentScheme<G1Affine>,\n                _,\n                ProverIPA<_>,\n                VerifierIPA<_>,\n                IPASingleStrategy<_>,\n                _,\n                EvmTranscript<_, _, _, _>,\n                EvmTranscript<_, _, _, _>,\n            >(\n                circuit,\n                vec![public_inputs],\n                &params,\n                &pk,\n                CheckMode::UNSAFE,\n                crate::Commitments::IPA,\n                TranscriptType::EVM,\n                proof_split_commits,\n                None,\n            )\n        }\n    }\n    .map_err(|e| JsError::new(&format!(\"{}\", e)))?;\n\n    Ok(serde_json::to_string(&proof)\n        .map_err(|e| JsError::new(&format!(\"{}\", e)))?\n        .into_bytes())\n}\n\n// VALIDATION FUNCTIONS\n\n/// Witness file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn witnessValidation(witness: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {\n    let _: crate::graph::GraphWitness = serde_json::from_slice(&witness[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize witness: {}\", e)))?;\n\n    Ok(true)\n}\n/// Compiled circuit validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn compiledCircuitValidation(\n    compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<bool, JsError> {\n    let _: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize compiled circuit: {}\", e)))?;\n\n    Ok(true)\n}\n/// Input file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn inputValidation(input: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {\n    let _: crate::graph::input::GraphData = serde_json::from_slice(&input[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize input: {}\", e)))?;\n\n    Ok(true)\n}\n/// Proof file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn proofValidation(proof: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {\n    let _: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize proof: {}\", e)))?;\n\n    Ok(true)\n}\n/// Vk file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn vkValidation(\n    vk: wasm_bindgen::Clamped<Vec<u8>>,\n    settings: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<bool, JsError> {\n    let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize settings: {}\", e)))?;\n    let mut reader = std::io::BufReader::new(&vk[..]);\n    let _ = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit_settings,\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize vk: {}\", e)))?;\n\n    Ok(true)\n}\n/// Pk file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn pkValidation(\n    pk: wasm_bindgen::Clamped<Vec<u8>>,\n    settings: wasm_bindgen::Clamped<Vec<u8>>,\n) -> Result<bool, JsError> {\n    let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize settings: {}\", e)))?;\n    let mut reader = std::io::BufReader::new(&pk[..]);\n    let _ = ProvingKey::<G1Affine>::read::<_, GraphCircuit>(\n        &mut reader,\n        halo2_proofs::SerdeFormat::RawBytes,\n        circuit_settings,\n    )\n    .map_err(|e| JsError::new(&format!(\"Failed to deserialize proving key: {}\", e)))?;\n\n    Ok(true)\n}\n/// Settings file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn settingsValidation(settings: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {\n    let _: GraphSettings = serde_json::from_slice(&settings[..])\n        .map_err(|e| JsError::new(&format!(\"Failed to deserialize settings: {}\", e)))?;\n\n    Ok(true)\n}\n/// Srs file validation\n#[wasm_bindgen]\n#[allow(non_snake_case)]\npub fn srsValidation(srs: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {\n    let mut reader = std::io::BufReader::new(&srs[..]);\n    let _: ParamsKZG<Bn256> =\n        halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)\n            .map_err(|e| JsError::new(&format!(\"Failed to deserialize params: {}\", e)))?;\n\n    Ok(true)\n}\n\n// HELPER FUNCTIONS\n\n/// Creates a [ProvingKey] for a [GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`) for the WASM target\n#[cfg(target_arch = \"wasm32\")]\npub fn create_vk_wasm<Scheme: CommitmentScheme, F: PrimeField + TensorType, C: Circuit<F>>(\n    circuit: &C,\n    params: &'_ Scheme::ParamsProver,\n    compress_selectors: bool,\n) -> Result<VerifyingKey<Scheme::Curve>, halo2_proofs::plonk::Error>\nwhere\n    C: Circuit<Scheme::Scalar>,\n    <Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,\n{\n    //\tReal proof\n    let empty_circuit = <C as Circuit<F>>::without_witnesses(circuit);\n\n    // Initialize the verifying key\n    let vk = keygen_vk_custom(params, &empty_circuit, compress_selectors)?;\n    Ok(vk)\n}\n/// Creates a [ProvingKey] from a [VerifyingKey] for a [GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`) for the WASM target\n#[cfg(target_arch = \"wasm32\")]\npub fn create_pk_wasm<Scheme: CommitmentScheme, F: PrimeField + TensorType, C: Circuit<F>>(\n    vk: VerifyingKey<Scheme::Curve>,\n    circuit: &C,\n    params: &'_ Scheme::ParamsProver,\n) -> Result<ProvingKey<Scheme::Curve>, halo2_proofs::plonk::Error>\nwhere\n    C: Circuit<Scheme::Scalar>,\n    <Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,\n{\n    //\tReal proof\n    let empty_circuit = <C as Circuit<F>>::without_witnesses(circuit);\n\n    // Initialize the proving key\n    let pk = keygen_pk(params, vk, &empty_circuit)?;\n    Ok(pk)\n}\n\n///\npub fn u8_array_to_u128_le(arr: [u8; 16]) -> u128 {\n    let mut n: u128 = 0;\n    for &b in arr.iter().rev() {\n        n <<= 8;\n        n |= b as u128;\n    }\n    n\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/integration_tests.rs",
        "content": "#[cfg(not(target_arch = \"wasm32\"))]\n#[cfg(test)]\nmod native_tests {\n\n    use ezkl::circuit::Tolerance;\n    use ezkl::fieldutils::{felt_to_i128, i128_to_felt};\n    // use ezkl::circuit::table::RESERVED_BLINDING_ROWS_PAD;\n    use ezkl::graph::input::{FileSource, FileSourceInner, GraphData};\n    use ezkl::graph::{DataSource, GraphSettings, GraphWitness};\n    use ezkl::Commitments;\n    use lazy_static::lazy_static;\n    use rand::Rng;\n    use std::env::var;\n    use std::io::{Read, Write};\n    use std::process::{Child, Command};\n    use std::sync::Once;\n    static COMPILE: Once = Once::new();\n    #[allow(dead_code)]\n    static COMPILE_WASM: Once = Once::new();\n    static ENV_SETUP: Once = Once::new();\n\n    //Sure to run this once\n    #[derive(Debug)]\n    #[allow(dead_code)]\n    enum Hardfork {\n        London,\n        ArrowGlacier,\n        GrayGlacier,\n        Paris,\n        Shanghai,\n        Latest,\n    }\n    lazy_static! {\n        static ref CARGO_TARGET_DIR: String =\n            var(\"CARGO_TARGET_DIR\").unwrap_or_else(|_| \"./target\".to_string());\n        static ref ANVIL_URL: String = \"http://localhost:3030\".to_string();\n        static ref LIMITLESS_ANVIL_URL: String = \"http://localhost:8545\".to_string();\n        static ref ANVIL_DEFAULT_PRIVATE_KEY: String =\n            \"ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\".to_string();\n    }\n\n    fn start_anvil(limitless: bool, hardfork: Hardfork) -> Child {\n        let mut args = vec![\"-p\"];\n        if limitless {\n            args.push(\"8545\");\n            args.push(\"--code-size-limit=41943040\");\n            args.push(\"--disable-block-gas-limit\");\n        } else {\n            args.push(\"3030\");\n        }\n        match hardfork {\n            Hardfork::Paris => args.push(\"--hardfork=paris\"),\n            Hardfork::London => args.push(\"--hardfork=london\"),\n            Hardfork::Latest => {}\n            Hardfork::Shanghai => args.push(\"--hardfork=shanghai\"),\n            Hardfork::ArrowGlacier => args.push(\"--hardfork=arrowGlacier\"),\n            Hardfork::GrayGlacier => args.push(\"--hardfork=grayGlacier\"),\n        }\n        let child = Command::new(\"anvil\")\n            .args(args)\n            .spawn()\n            .expect(\"failed to start anvil process\");\n        std::thread::sleep(std::time::Duration::from_secs(3));\n        child\n    }\n\n    fn init_binary() {\n        COMPILE.call_once(|| {\n            println!(\"using cargo target dir: {}\", *CARGO_TARGET_DIR);\n            build_ezkl();\n        });\n    }\n\n    ///\n    #[allow(dead_code)]\n    pub fn init_wasm() {\n        COMPILE_WASM.call_once(|| {\n            build_wasm_ezkl();\n        });\n    }\n\n    fn setup_py_env() {\n        ENV_SETUP.call_once(|| {\n            // supposes that you have a virtualenv called .env and have run the following\n            // equivalent of python -m venv .env\n            // source .env/bin/activate\n            // pip install -r requirements.txt\n            // maturin develop --release --features python-bindings\n\n            // now install torch, pandas, numpy, seaborn, jupyter\n            let status = Command::new(\"pip\")\n                .args([\"install\", \"numpy\", \"onnxruntime\", \"onnx\"])\n                .stdout(std::process::Stdio::null())\n                .status()\n                .expect(\"failed to execute process\");\n\n            assert!(status.success());\n        });\n    }\n\n    fn download_srs(logrows: u32, commitment: Commitments) {\n        // if does not exist, download it\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"get-srs\",\n                \"--logrows\",\n                &format!(\"{}\", logrows),\n                \"--commitment\",\n                &commitment.to_string(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    fn init_params(settings_path: std::path::PathBuf) {\n        println!(\"using settings path: {}\", settings_path.to_str().unwrap());\n        // read in settings json\n        let settings =\n            std::fs::read_to_string(settings_path).expect(\"failed to read settings file\");\n        // read in to GraphSettings object\n        let settings: GraphSettings = serde_json::from_str(&settings).unwrap();\n        let logrows = settings.run_args.logrows;\n\n        download_srs(logrows, settings.run_args.commitment.into());\n    }\n\n    fn mv_test_(test_dir: &str, test: &str) {\n        let path: std::path::PathBuf = format!(\"{}/{}\", test_dir, test).into();\n        if !path.exists() {\n            let status = Command::new(\"cp\")\n                .args([\n                    \"-R\",\n                    &format!(\"./examples/onnx/{}\", test),\n                    &format!(\"{}/{}\", test_dir, test),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n        }\n    }\n\n    fn mk_data_batches_(test_dir: &str, test: &str, output_dir: &str, num_batches: usize) {\n        let path: std::path::PathBuf = format!(\"{}/{}\", test_dir, test).into();\n        if !path.exists() {\n            panic!(\"test_dir does not exist\")\n        } else {\n            // copy the directory\n            let status = Command::new(\"cp\")\n                .args([\n                    \"-R\",\n                    &format!(\"{}/{}\", test_dir, test),\n                    &format!(\"{}/{}\", test_dir, output_dir),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n\n            assert!(status.success());\n\n            let data = GraphData::from_path(format!(\"{}/{}/input.json\", test_dir, test).into())\n                .expect(\"failed to load input data\");\n\n            let input_data = match data.input_data {\n                DataSource::File(data) => data,\n                _ => panic!(\"Only File data sources support batching\"),\n            };\n\n            let duplicated_input_data: FileSource = input_data\n                .iter()\n                .map(|data| (0..num_batches).flat_map(|_| data.clone()).collect())\n                .collect();\n\n            let duplicated_data = GraphData::new(DataSource::File(duplicated_input_data));\n\n            let res =\n                duplicated_data.save(format!(\"{}/{}/input.json\", test_dir, output_dir).into());\n\n            assert!(res.is_ok());\n        }\n    }\n\n    const PF_FAILURE: &str = \"examples/test_failure_proof.json\";\n\n    const PF_FAILURE_AGGR: &str = \"examples/test_failure_aggr_proof.json\";\n\n    const LARGE_TESTS: [&str; 5] = [\n        \"self_attention\",\n        \"nanoGPT\",\n        \"multihead_attention\",\n        \"mobilenet\",\n        \"mnist_gan\",\n    ];\n\n    const ACCURACY_CAL_TESTS: [&str; 6] = [\n        \"accuracy\",\n        \"1l_mlp\",\n        \"4l_relu_conv_fc\",\n        \"1l_elu\",\n        \"1l_prelu\",\n        \"1l_tiny_div\",\n    ];\n\n    const TESTS: [&str; 92] = [\n        \"1l_mlp\", //0\n        \"1l_slice\",\n        \"1l_concat\",\n        \"1l_flatten\",\n        // \"1l_average\",\n        \"1l_div\",\n        \"1l_pad\", // 5\n        \"1l_reshape\",\n        \"1l_eltwise_div\",\n        \"1l_sigmoid\",\n        \"1l_sqrt\",\n        \"1l_softmax\", //10\n        // \"1l_instance_norm\",\n        \"1l_batch_norm\",\n        \"1l_prelu\",\n        \"1l_leakyrelu\",\n        \"1l_gelu_noappx\",\n        // \"1l_gelu_tanh_appx\",\n        \"1l_relu\", //15\n        \"1l_downsample\",\n        \"1l_tanh\",\n        \"2l_relu_sigmoid_small\",\n        \"2l_relu_fc\",\n        \"2l_relu_small\", //20\n        \"2l_relu_sigmoid\",\n        \"1l_conv\",\n        \"2l_sigmoid_small\",\n        \"2l_relu_sigmoid_conv\",\n        \"3l_relu_conv_fc\", //25\n        \"4l_relu_conv_fc\",\n        \"1l_erf\",\n        \"1l_var\",\n        \"1l_elu\",\n        \"min\", //30\n        \"max\",\n        \"1l_max_pool\",\n        \"1l_conv_transpose\",\n        \"1l_upsample\",\n        \"1l_identity\", //35\n        \"idolmodel\",\n        \"trig\",\n        \"prelu_gmm\",\n        \"lstm\",\n        \"rnn\", //40\n        \"quantize_dequantize\",\n        \"1l_where\",\n        \"boolean\",\n        \"boolean_identity\",\n        \"decision_tree\", // 45\n        \"random_forest\",\n        \"gradient_boosted_trees\",\n        \"1l_topk\",\n        \"xgboost\",\n        \"lightgbm\", //50\n        \"hummingbird_decision_tree\",\n        \"oh_decision_tree\",\n        \"linear_svc\",\n        \"gather_elements\",\n        \"less\", //55\n        \"xgboost_reg\",\n        \"1l_powf\",\n        \"scatter_elements\",\n        \"1l_linear\",\n        \"linear_regression\", //60\n        \"sklearn_mlp\",\n        \"1l_mean\",\n        \"rounding_ops\",\n        // \"mean_as_constrain\",\n        \"arange\",\n        \"layernorm\", //65\n        \"bitwise_ops\",\n        \"blackman_window\",\n        \"softsign\", //68\n        \"softplus\",\n        \"selu\", //70\n        \"hard_sigmoid\",\n        \"log_softmax\",\n        \"eye\",\n        \"ltsf\",\n        \"remainder\", //75\n        \"bitshift\",\n        \"gather_nd\",\n        \"scatter_nd\",\n        \"celu\",\n        \"gru\",        // 80\n        \"hard_swish\", // 81\n        \"hard_max\",\n        \"tril\",      // 83\n        \"triu\",      // 84\n        \"logsumexp\", // 85\n        \"clip\",\n        \"mish\",\n        \"reducel1\",\n        \"reducel2\", // 89\n        \"1l_lppool\",\n        \"lstm_large\", // 91\n    ];\n\n    const WASM_TESTS: [&str; 46] = [\n        \"1l_mlp\",\n        \"1l_slice\",\n        \"1l_concat\",\n        \"1l_flatten\",\n        // \"1l_average\",\n        \"1l_div\",\n        \"1l_pad\",\n        \"1l_reshape\",\n        \"1l_eltwise_div\",\n        \"1l_sigmoid\",\n        \"1l_sqrt\",\n        \"1l_softmax\",\n        // \"1l_instance_norm\",\n        \"1l_batch_norm\",\n        \"1l_prelu\",\n        \"1l_leakyrelu\",\n        \"1l_gelu_noappx\",\n        // \"1l_gelu_tanh_appx\",\n        \"1l_relu\",\n        \"1l_downsample\",\n        \"1l_tanh\",\n        \"2l_relu_sigmoid_small\",\n        \"2l_relu_fc\",\n        \"2l_relu_small\",\n        \"2l_relu_sigmoid\",\n        \"1l_conv\",\n        \"2l_sigmoid_small\",\n        \"2l_relu_sigmoid_conv\",\n        \"3l_relu_conv_fc\",\n        \"4l_relu_conv_fc\",\n        \"1l_erf\",\n        \"1l_var\",\n        \"1l_elu\",\n        \"min\",\n        \"max\",\n        \"1l_max_pool\",\n        \"1l_conv_transpose\",\n        \"1l_upsample\",\n        \"1l_identity\",\n        // \"idolmodel\",\n        \"trig\",\n        \"prelu_gmm\",\n        \"lstm\",\n        \"rnn\",\n        \"quantize_dequantize\",\n        \"1l_where\",\n        \"boolean\",\n        \"boolean_identity\",\n        \"gradient_boosted_trees\",\n        \"1l_topk\",\n        // \"xgboost\",\n        // \"lightgbm\",\n        // \"hummingbird_decision_tree\",\n    ];\n\n    #[cfg(not(feature = \"icicle\"))]\n    const TESTS_AGGR: [&str; 21] = [\n        \"1l_mlp\",\n        \"1l_flatten\",\n        \"1l_average\",\n        \"1l_reshape\",\n        \"1l_div\",\n        \"1l_pad\",\n        \"1l_sigmoid\",\n        \"1l_gelu_noappx\",\n        \"1l_sqrt\",\n        \"1l_prelu\",\n        \"1l_var\",\n        \"1l_leakyrelu\",\n        \"1l_relu\",\n        \"1l_tanh\",\n        \"2l_relu_fc\",\n        \"2l_relu_sigmoid_small\",\n        \"2l_relu_small\",\n        \"1l_conv\",\n        \"min\",\n        \"max\",\n        \"1l_max_pool\",\n    ];\n\n    #[cfg(feature = \"icicle\")]\n    const TESTS_AGGR: [&str; 3] = [\"1l_mlp\", \"1l_flatten\", \"1l_average\"];\n\n    const TESTS_EVM: [&str; 23] = [\n        \"1l_mlp\",\n        \"1l_flatten\",\n        \"1l_average\",\n        \"1l_reshape\",\n        \"1l_sigmoid\",\n        \"1l_div\",\n        \"1l_sqrt\",\n        \"1l_prelu\",\n        \"1l_var\",\n        \"1l_leakyrelu\",\n        \"1l_gelu_noappx\",\n        \"1l_relu\",\n        \"1l_tanh\",\n        \"2l_relu_sigmoid_small\",\n        \"2l_relu_small\",\n        \"min\",\n        \"max\",\n        \"1l_max_pool\",\n        \"idolmodel\",\n        \"1l_identity\",\n        \"lstm\",\n        \"rnn\",\n        \"quantize_dequantize\",\n    ];\n\n    const TESTS_EVM_AGGR: [&str; 18] = [\n        \"1l_mlp\",\n        \"1l_reshape\",\n        \"1l_sigmoid\",\n        \"1l_div\",\n        \"1l_sqrt\",\n        \"1l_prelu\",\n        \"1l_var\",\n        \"1l_leakyrelu\",\n        \"1l_gelu_noappx\",\n        \"1l_relu\",\n        \"1l_tanh\",\n        \"2l_relu_sigmoid_small\",\n        \"2l_relu_small\",\n        \"2l_relu_fc\",\n        \"min\",\n        \"max\",\n        \"idolmodel\",\n        \"1l_identity\",\n    ];\n\n    const EXAMPLES: [&str; 2] = [\"mlp_4d_einsum\", \"conv2d_mnist\"];\n\n    macro_rules! test_func_aggr {\n    () => {\n        #[cfg(test)]\n        mod tests_aggr {\n            use seq_macro::seq;\n            use crate::native_tests::TESTS_AGGR;\n            use test_case::test_case;\n            use crate::native_tests::aggr_prove_and_verify;\n            use crate::native_tests::kzg_aggr_mock_prove_and_verify;\n            use tempdir::TempDir;\n            use ezkl::Commitments;\n\n            #[cfg(not(feature=\"icicle\"))]\n            seq!(N in 0..=20 {\n\n            #(#[test_case(TESTS_AGGR[N])])*\n            fn kzg_aggr_mock_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                kzg_aggr_mock_prove_and_verify(path, test.to_string());\n                test_dir.close().unwrap();\n            }\n\n\n\n            #(#[test_case(TESTS_AGGR[N])])*\n            fn kzg_aggr_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                aggr_prove_and_verify(path, test.to_string(), \"private\", \"private\", \"public\", Commitments::KZG);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS_AGGR[N])])*\n            fn ipa_aggr_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                aggr_prove_and_verify(path, test.to_string(), \"private\", \"private\", \"public\", Commitments::IPA);\n                test_dir.close().unwrap();\n            }\n\n            });\n\n            #[cfg(feature=\"icicle\")]\n            seq!(N in 0..=2 {\n            #(#[test_case(TESTS_AGGR[N])])*\n            fn aggr_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(test_dir.path().to_str().unwrap(), test);\n                aggr_prove_and_verify(path, test.to_string(), \"private\", \"private\", \"public\", Commitments::KZG);\n                test_dir.close().unwrap();\n            }\n            });\n    }\n    };\n}\n\n    macro_rules! test_func {\n    () => {\n        #[cfg(test)]\n        mod tests {\n            use seq_macro::seq;\n            use crate::native_tests::TESTS;\n            use crate::native_tests::WASM_TESTS;\n            use crate::native_tests::ACCURACY_CAL_TESTS;\n            use crate::native_tests::LARGE_TESTS;\n            use test_case::test_case;\n            use crate::native_tests::mock;\n            use crate::native_tests::accuracy_measurement;\n            use crate::native_tests::prove_and_verify;\n            use crate::native_tests::run_js_tests;\n            use crate::native_tests::render_circuit;\n            use crate::native_tests::model_serialization_different_binaries;\n            use rand::Rng;\n            use tempdir::TempDir;\n            use ezkl::Commitments;\n\n            #[test]\n            fn model_serialization_different_binaries_() {\n                let test = \"1l_mlp\";\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::native_tests::mv_test_(path, test);\n                // percent tolerance test\n                model_serialization_different_binaries(path, test.to_string());\n                test_dir.close().unwrap();\n            }\n\n            seq!(N in 0..=5 {\n            #(#[test_case(ACCURACY_CAL_TESTS[N])])*\n            fn mock_accuracy_cal_tests(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"fixed\", \"public\", 1, \"accuracy\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n        });\n\n            seq!(N in 0..=91 {\n\n            #(#[test_case(TESTS[N])])*\n            #[ignore]\n            fn render_circuit_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                render_circuit(path, test.to_string());\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn accuracy_measurement_div_rebase_(test: &str) {\n                crate::native_tests::init_binary();\n                crate::native_tests::setup_py_env();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                accuracy_measurement(path, test.to_string(), \"private\", \"private\", \"public\", 1, \"accuracy\", 2.6, true);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn accuracy_measurement_public_outputs_(test: &str) {\n                crate::native_tests::init_binary();\n                crate::native_tests::setup_py_env();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                accuracy_measurement(path, test.to_string(), \"private\", \"private\", \"public\", 1, \"accuracy\", 2.6, false);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn accuracy_measurement_fixed_params_(test: &str) {\n                crate::native_tests::init_binary();\n                crate::native_tests::setup_py_env();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                accuracy_measurement(path, test.to_string(), \"private\", \"fixed\", \"private\", 1, \"accuracy\", 2.6 , false);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn accuracy_measurement_public_inputs_(test: &str) {\n                crate::native_tests::init_binary();\n                crate::native_tests::setup_py_env();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                accuracy_measurement(path, test.to_string(), \"public\", \"private\", \"private\", 1, \"accuracy\", 2.6, false);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn resources_accuracy_measurement_public_outputs_(test: &str) {\n                crate::native_tests::init_binary();\n                crate::native_tests::setup_py_env();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                accuracy_measurement(path, test.to_string(), \"private\", \"private\", \"public\", 1, \"resources\", 3.1, false);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_public_outputs_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"private\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_tolerance_public_outputs_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                // gen random number between 0.0 and 1.0\n                let tolerance = rand::thread_rng().gen_range(0.0..1.0) * 100.0;\n                mock(path, test.to_string(), \"private\", \"private\", \"public\", 1, \"resources\", None, tolerance);\n                test_dir.close().unwrap();\n            }\n\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_large_batch_public_outputs_(test: &str) {\n                // currently variable output rank is not supported in ONNX\n                if test != \"gather_nd\" && test != \"lstm_large\" {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let large_batch_dir = &format!(\"large_batches_{}\", test);\n                    crate::native_tests::mk_data_batches_(path, test, &large_batch_dir, 10);\n                    mock(path, large_batch_dir.to_string(), \"private\", \"private\", \"public\", 10, \"resources\", None, 0.0);\n                    test_dir.close().unwrap();\n                }\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_public_inputs_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"private\", \"private\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_fixed_inputs_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"fixed\", \"private\", \"private\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_fixed_outputs_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"private\", \"fixed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_fixed_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"fixed\", \"private\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_input_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"hashed\", \"private\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_kzg_input_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"polycommit\", \"private\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"hashed\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_kzg_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"polycommit\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_output_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"private\", \"hashed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_kzg_output_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"private\", \"polycommit\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_output_fixed_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"fixed\", \"hashed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_output_kzg_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"public\", \"polycommit\", \"hashed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_kzg_all_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"polycommit\", \"polycommit\", \"polycommit\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_input_output_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"hashed\", \"private\", \"hashed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_input_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                // needs an extra row for the large model\n                mock(path, test.to_string(),\"hashed\", \"hashed\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn mock_hashed_all_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                // needs an extra row for the large model\n                mock(path, test.to_string(),\"hashed\", \"hashed\", \"hashed\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_single_col(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_triple_col(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 3, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_quadruple_col(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 4, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_octuple_col(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 8, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_tight_lookup_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 1, None, false, \"single\", Commitments::KZG, 1);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn ipa_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 1, None, false, \"single\", Commitments::IPA, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_public_input_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"public\", \"private\", \"public\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_fixed_params_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"fixed\", \"public\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_hashed_output(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"hashed\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn kzg_prove_and_verify_kzg_output(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"polycommit\", 1, None, false, \"single\", Commitments::KZG, 2);\n               test_dir.close().unwrap();\n            }\n\n            #(#[test_case(TESTS[N])])*\n            fn ipa_prove_and_verify_ipa_output(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n               prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"polycommit\", 1, None, false, \"single\", Commitments::IPA, 2);\n               test_dir.close().unwrap();\n            }\n\n            });\n\n            seq!(N in 0..=45 {\n\n                #(#[test_case(WASM_TESTS[N])])*\n                fn kzg_prove_and_verify_with_overflow_(test: &str) {\n                    crate::native_tests::init_binary();\n                    // crate::native_tests::init_wasm();\n                    let test_dir = TempDir::new(test).unwrap();\n                    env_logger::init();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"private\", \"public\", 1, None, true, \"single\", Commitments::KZG, 2);\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testWasm\", false);\n                    // test_dir.close().unwrap();\n                }\n\n                #(#[test_case(WASM_TESTS[N])])*\n                fn kzg_prove_and_verify_with_overflow_hashed_inputs_(test: &str) {\n                    crate::native_tests::init_binary();\n                    // crate::native_tests::init_wasm();\n                    let test_dir = TempDir::new(test).unwrap();\n                    env_logger::init();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    prove_and_verify(path, test.to_string(), \"safe\", \"hashed\", \"private\", \"public\", 1, None, true, \"single\", Commitments::KZG, 2);\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testWasm\", false);\n                    // test_dir.close().unwrap();\n                }\n\n                #(#[test_case(WASM_TESTS[N])])*\n                fn kzg_prove_and_verify_with_overflow_fixed_params_(test: &str) {\n                    crate::native_tests::init_binary();\n                    // crate::native_tests::init_wasm();\n                    let test_dir = TempDir::new(test).unwrap();\n                    env_logger::init();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    prove_and_verify(path, test.to_string(), \"safe\", \"private\", \"fixed\", \"public\", 1, None, true, \"single\", Commitments::KZG, 2);\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testWasm\", false);\n                    test_dir.close().unwrap();\n                }\n\n            });\n\n            seq!(N in 0..=4 {\n\n            #(#[test_case(LARGE_TESTS[N])])*\n            #[ignore]\n            fn large_prove_and_verify_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                prove_and_verify(path, test.to_string(), \"unsafe\", \"private\", \"fixed\", \"public\", 1, None, false, \"single\", Commitments::KZG, 2);\n                test_dir.close().unwrap();\n            }\n\n            #(#[test_case(LARGE_TESTS[N])])*\n            #[ignore]\n            fn large_mock_(test: &str) {\n                crate::native_tests::init_binary();\n                let test_dir = TempDir::new(test).unwrap();\n                let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                mock(path, test.to_string(), \"private\", \"fixed\", \"public\", 1, \"resources\", None, 0.0);\n                test_dir.close().unwrap();\n            }\n        });\n    }\n    };\n}\n\n    macro_rules! test_func_evm {\n    () => {\n        #[cfg(test)]\n        mod tests_evm {\n            use seq_macro::seq;\n            use crate::native_tests::TESTS_EVM;\n            use crate::native_tests::TESTS_EVM_AGGR;\n            use test_case::test_case;\n            use crate::native_tests::kzg_evm_prove_and_verify;\n            use crate::native_tests::kzg_evm_prove_and_verify_render_seperately;\n\n            use crate::native_tests::kzg_evm_on_chain_input_prove_and_verify;\n            use crate::native_tests::kzg_evm_aggr_prove_and_verify;\n            use tempdir::TempDir;\n            use crate::native_tests::Hardfork;\n            use crate::native_tests::run_js_tests;\n\n            /// Currently only on chain inputs that return a non-negative value are supported.\n            const TESTS_ON_CHAIN_INPUT: [&str; 17] = [\n                \"1l_mlp\",\n                \"1l_average\",\n                \"1l_reshape\",\n                \"1l_sigmoid\",\n                \"1l_div\",\n                \"1l_sqrt\",\n                \"1l_prelu\",\n                \"1l_var\",\n                \"1l_leakyrelu\",\n                \"1l_gelu_noappx\",\n                \"1l_relu\",\n                \"1l_tanh\",\n                \"2l_relu_sigmoid_small\",\n                \"2l_relu_small\",\n                \"2l_relu_fc\",\n                \"min\",\n                \"max\"\n            ];\n\n            seq!(N in 0..=16 {\n                #(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Latest))])*\n                #(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Paris))])*\n                #(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::London))])*\n                #(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Shanghai))])*\n                fn kzg_evm_on_chain_input_prove_and_verify_(test: (&str,Hardfork)) {\n                    let (test,hardfork) = test;\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(true, hardfork);\n                    kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), \"on-chain\", \"file\", \"public\", \"private\");\n                    // test_dir.close().unwrap();\n                }\n\n                #(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*\n                fn kzg_evm_on_chain_output_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);\n                    kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), \"file\", \"on-chain\", \"private\", \"public\");\n                    // test_dir.close().unwrap();\n                }\n\n                #(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*\n                fn kzg_evm_on_chain_input_output_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);\n                    kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), \"on-chain\", \"on-chain\", \"public\", \"public\");\n                    test_dir.close().unwrap();\n                }\n\n                #(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*\n                fn kzg_evm_on_chain_input_output_hashed_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);\n                    kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), \"on-chain\", \"on-chain\", \"hashed\", \"hashed\");\n                    test_dir.close().unwrap();\n                }\n            });\n\n\n            seq!(N in 0..=17 {\n                // these take a particularly long time to run\n                #(#[test_case(TESTS_EVM_AGGR[N])])*\n                #[ignore]\n                fn kzg_evm_aggr_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_aggr_prove_and_verify(path, test.to_string(), \"private\", \"private\", \"public\");\n                    test_dir.close().unwrap();\n                }\n\n            });\n\n\n            seq!(N in 0..=22 {\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"private\", \"private\", \"public\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n\n                }\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_prove_and_verify_render_seperately_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify_render_seperately(2, path, test.to_string(), \"private\", \"private\", \"public\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", true);\n                    test_dir.close().unwrap();\n\n                }\n\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_hashed_input_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let mut _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"hashed\", \"private\", \"private\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n\n                #(#[test_case((TESTS_EVM[N], Hardfork::Latest))])*\n                #(#[test_case((TESTS_EVM[N], Hardfork::Paris))])*\n                #(#[test_case((TESTS_EVM[N], Hardfork::London))])*\n                #(#[test_case((TESTS_EVM[N], Hardfork::Shanghai))])*\n                fn kzg_evm_kzg_input_prove_and_verify_(test: (&str, Hardfork)) {\n                    let (test,hardfork) = test;\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let mut _anvil_child = crate::native_tests::start_anvil(false, hardfork);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"polycommit\", \"private\", \"public\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_hashed_params_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"private\", \"hashed\", \"public\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n\n                }\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_hashed_output_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"private\", \"private\", \"hashed\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_kzg_params_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"private\", \"polycommit\", \"public\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_kzg_output_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"private\", \"private\", \"polycommit\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n                #(#[test_case(TESTS_EVM[N])])*\n                fn kzg_evm_kzg_all_prove_and_verify_(test: &str) {\n                    crate::native_tests::init_binary();\n                    let test_dir = TempDir::new(test).unwrap();\n                    let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);\n                    let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);\n                    kzg_evm_prove_and_verify(2, path, test.to_string(), \"polycommit\", \"polycommit\", \"polycommit\");\n                    #[cfg(not(feature = \"icicle\"))]\n                    run_js_tests(path, test.to_string(), \"testBrowserEvmVerify\", false);\n                    test_dir.close().unwrap();\n                }\n\n\n\n\n            });\n    }\n    };\n}\n\n    macro_rules! test_func_examples {\n    () => {\n        #[cfg(test)]\n        mod tests_examples {\n            use seq_macro::seq;\n            use crate::native_tests::EXAMPLES;\n            use test_case::test_case;\n            use crate::native_tests::run_example as run;\n            seq!(N in 0..=1 {\n            #(#[test_case(EXAMPLES[N])])*\n            fn example_(test: &str) {\n                run(test.to_string());\n            }\n            });\n    }\n    };\n}\n\n    test_func!();\n    test_func_aggr!();\n    test_func_evm!();\n    test_func_examples!();\n\n    fn model_serialization_different_binaries(test_dir: &str, example_name: String) {\n        let status = Command::new(\"cargo\")\n            .args([\n                \"run\",\n                \"--bin\",\n                \"ezkl\",\n                \"--\",\n                \"gen-settings\",\n                \"-M\",\n                format!(\"{}/{}/network.onnx\", test_dir, example_name).as_str(),\n                &format!(\n                    \"--settings-path={}/{}/settings.json\",\n                    test_dir, example_name\n                ),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(\"cargo\")\n            .args([\n                \"run\",\n                \"--bin\",\n                \"ezkl\",\n                \"--\",\n                \"compile-circuit\",\n                \"-M\",\n                format!(\"{}/{}/network.onnx\", test_dir, example_name).as_str(),\n                \"--compiled-circuit\",\n                format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                &format!(\n                    \"--settings-path={}/{}/settings.json\",\n                    test_dir, example_name\n                ),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // now alter binary slightly\n        // create new temp cargo.toml with a different version\n        // cpy old cargo.toml to cargo.toml.bak\n        let status = Command::new(\"cp\")\n            .args([\"Cargo.toml\", \"Cargo.toml.bak\"])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let mut cargo_toml = std::fs::File::open(\"Cargo.toml\").unwrap();\n        let mut cargo_toml_contents = String::new();\n        cargo_toml.read_to_string(&mut cargo_toml_contents).unwrap();\n        let mut cargo_toml_contents = cargo_toml_contents.split('\\n').collect::<Vec<_>>();\n\n        // draw a random version number from 0.0.0 to 0.100.100\n        let mut rng = rand::thread_rng();\n        let version = &format!(\n            \"version = \\\"0.{}.{}-test\\\"\",\n            rng.gen_range(0..100),\n            rng.gen_range(0..100)\n        );\n        let cargo_toml_contents = cargo_toml_contents\n            .iter_mut()\n            .map(|line| {\n                if line.starts_with(\"version\") {\n                    *line = version;\n                }\n                *line\n            })\n            .collect::<Vec<_>>();\n        let mut cargo_toml = std::fs::File::create(\"Cargo.toml\").unwrap();\n        cargo_toml\n            .write_all(cargo_toml_contents.join(\"\\n\").as_bytes())\n            .unwrap();\n\n        let status = Command::new(\"cargo\")\n            .args([\n                \"run\",\n                \"--bin\",\n                \"ezkl\",\n                \"--\",\n                \"gen-witness\",\n                \"-D\",\n                &format!(\"{}/{}/input.json\", test_dir, example_name),\n                \"-M\",\n                &format!(\"{}/{}/network.compiled\", test_dir, example_name),\n                \"-O\",\n                &format!(\"{}/{}/witness.json\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // now delete cargo.toml and move cargo.toml.bak to cargo.toml\n        let status = Command::new(\"rm\")\n            .args([\"Cargo.toml\"])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(\"mv\")\n            .args([\"Cargo.toml.bak\", \"Cargo.toml\"])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // Mock prove (fast, but does not cover some potential issues)\n    fn run_example(example_name: String) {\n        let status = Command::new(\"cargo\")\n            .args([\"run\", \"--release\", \"--example\", example_name.as_str()])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // Mock prove (fast, but does not cover some potential issues)\n    #[allow(clippy::too_many_arguments)]\n    fn mock(\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n        batch_size: usize,\n        cal_target: &str,\n        scales_to_use: Option<Vec<u32>>,\n        tolerance: f32,\n    ) {\n        let mut tolerance = tolerance;\n        gen_circuit_settings_and_witness(\n            test_dir,\n            example_name.clone(),\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            batch_size,\n            cal_target,\n            scales_to_use,\n            2,\n            false,\n            &mut tolerance,\n            Commitments::KZG,\n            2,\n        );\n\n        if tolerance > 0.0 {\n            // load witness and shift the output by a small amount that is less than tolerance percent\n            let witness = GraphWitness::from_path(\n                format!(\"{}/{}/witness.json\", test_dir, example_name).into(),\n            )\n            .unwrap();\n            let witness = witness.clone();\n            let outputs = witness.outputs.clone();\n\n            // get values as i128\n            let output_perturbed_safe: Vec<Vec<halo2curves::bn256::Fr>> = outputs\n                .iter()\n                .map(|sv| {\n                    sv.iter()\n                        .map(|v| {\n                            // randomly perturb by a small amount less than tolerance\n                            let perturbation = if v == &halo2curves::bn256::Fr::zero() {\n                                halo2curves::bn256::Fr::zero()\n                            } else {\n                                i128_to_felt(\n                                    (felt_to_i128(*v) as f32\n                                        * (rand::thread_rng().gen_range(-0.01..0.01) * tolerance))\n                                        as i128,\n                                )\n                            };\n\n                            *v + perturbation\n                        })\n                        .collect::<Vec<_>>()\n                })\n                .collect::<Vec<_>>();\n\n            // get values as i128\n            let output_perturbed_bad: Vec<Vec<halo2curves::bn256::Fr>> = outputs\n                .iter()\n                .map(|sv| {\n                    sv.iter()\n                        .map(|v| {\n                            // randomly perturb by a small amount less than tolerance\n                            let perturbation = if v == &halo2curves::bn256::Fr::zero() {\n                                halo2curves::bn256::Fr::from(2)\n                            } else {\n                                i128_to_felt(\n                                    (felt_to_i128(*v) as f32\n                                        * (rand::thread_rng().gen_range(0.02..0.1) * tolerance))\n                                        as i128,\n                                )\n                            };\n                            *v + perturbation\n                        })\n                        .collect::<Vec<_>>()\n                })\n                .collect::<Vec<_>>();\n\n            let good_witness = GraphWitness {\n                outputs: output_perturbed_safe,\n                ..witness.clone()\n            };\n\n            // save\n            good_witness\n                .save(format!(\"{}/{}/witness_ok.json\", test_dir, example_name).into())\n                .unwrap();\n\n            let bad_witness = GraphWitness {\n                outputs: output_perturbed_bad,\n                ..witness.clone()\n            };\n\n            // save\n            bad_witness\n                .save(format!(\"{}/{}/witness_bad.json\", test_dir, example_name).into())\n                .unwrap();\n\n            let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n                .args([\n                    \"mock\",\n                    \"-W\",\n                    format!(\"{}/{}/witness.json\", test_dir, example_name).as_str(),\n                    \"-M\",\n                    format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n\n            let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n                .args([\n                    \"mock\",\n                    \"-W\",\n                    format!(\"{}/{}/witness_ok.json\", test_dir, example_name).as_str(),\n                    \"-M\",\n                    format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n\n            let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n                .args([\n                    \"mock\",\n                    \"-W\",\n                    format!(\"{}/{}/witness_bad.json\", test_dir, example_name).as_str(),\n                    \"-M\",\n                    format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(!status.success());\n        } else {\n            let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n                .args([\n                    \"mock\",\n                    \"-W\",\n                    format!(\"{}/{}/witness.json\", test_dir, example_name).as_str(),\n                    \"-M\",\n                    format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n        }\n    }\n\n    #[allow(clippy::too_many_arguments)]\n    fn gen_circuit_settings_and_witness(\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n        batch_size: usize,\n        cal_target: &str,\n        scales_to_use: Option<Vec<u32>>,\n        num_inner_columns: usize,\n        div_rebasing: bool,\n        tolerance: &mut f32,\n        commitment: Commitments,\n        lookup_safety_margin: usize,\n    ) {\n        let mut args = vec![\n            \"gen-settings\".to_string(),\n            \"-M\".to_string(),\n            format!(\"{}/{}/network.onnx\", test_dir, example_name),\n            format!(\n                \"--settings-path={}/{}/settings.json\",\n                test_dir, example_name\n            ),\n            format!(\"--variables=batch_size->{}\", batch_size),\n            format!(\"--input-visibility={}\", input_visibility),\n            format!(\"--param-visibility={}\", param_visibility),\n            format!(\"--output-visibility={}\", output_visibility),\n            format!(\"--num-inner-cols={}\", num_inner_columns),\n            format!(\"--tolerance={}\", tolerance),\n            format!(\"--commitment={}\", commitment),\n        ];\n\n        if div_rebasing {\n            args.push(\"--div-rebasing\".to_string());\n        };\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(args)\n            .stdout(std::process::Stdio::null())\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let mut calibrate_args = vec![\n            \"calibrate-settings\".to_string(),\n            \"--data\".to_string(),\n            format!(\"{}/{}/input.json\", test_dir, example_name),\n            \"-M\".to_string(),\n            format!(\"{}/{}/network.onnx\", test_dir, example_name),\n            format!(\n                \"--settings-path={}/{}/settings.json\",\n                test_dir, example_name\n            ),\n            format!(\"--target={}\", cal_target),\n            format!(\"--lookup-safety-margin={}\", lookup_safety_margin),\n        ];\n\n        if let Some(scales) = scales_to_use {\n            let scales = scales\n                .iter()\n                .map(|s| s.to_string())\n                .collect::<Vec<_>>()\n                .join(\",\");\n            calibrate_args.push(\"--scales\".to_string());\n            calibrate_args.push(scales);\n        }\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(calibrate_args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let mut settings =\n            GraphSettings::load(&format!(\"{}/{}/settings.json\", test_dir, example_name).into())\n                .unwrap();\n\n        let any_output_scales_smol = settings.model_output_scales.iter().any(|s| *s <= 0);\n\n        if any_output_scales_smol {\n            // set the tolerance to 0.0\n            settings.run_args.tolerance = Tolerance {\n                val: 0.0,\n                scale: 0.0.into(),\n            };\n            settings\n                .save(&format!(\"{}/{}/settings.json\", test_dir, example_name).into())\n                .unwrap();\n            *tolerance = 0.0;\n        }\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"compile-circuit\",\n                \"-M\",\n                format!(\"{}/{}/network.onnx\", test_dir, example_name).as_str(),\n                \"--compiled-circuit\",\n                format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                &format!(\n                    \"--settings-path={}/{}/settings.json\",\n                    test_dir, example_name\n                ),\n            ])\n            .stdout(std::process::Stdio::null())\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"gen-witness\",\n                \"-D\",\n                &format!(\"{}/{}/input.json\", test_dir, example_name),\n                \"-M\",\n                &format!(\"{}/{}/network.compiled\", test_dir, example_name),\n                \"-O\",\n                &format!(\"{}/{}/witness.json\", test_dir, example_name),\n            ])\n            .stdout(std::process::Stdio::null())\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // Mock prove (fast, but does not cover some potential issues)\n    #[allow(clippy::too_many_arguments)]\n    fn accuracy_measurement(\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n        batch_size: usize,\n        cal_target: &str,\n        target_perc: f32,\n        div_rebasing: bool,\n    ) {\n        gen_circuit_settings_and_witness(\n            test_dir,\n            example_name.clone(),\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            batch_size,\n            cal_target,\n            None,\n            2,\n            div_rebasing,\n            &mut 0.0,\n            Commitments::KZG,\n            2,\n        );\n\n        println!(\n            \" ------------ running accuracy measurement for {}\",\n            example_name\n        );\n        // run python ./output_comparison.py in the test dir\n        let status = Command::new(\"python\")\n            .args([\n                \"tests/output_comparison.py\",\n                &format!(\"{}/{}/network.onnx\", test_dir, example_name),\n                &format!(\"{}/{}/input.json\", test_dir, example_name),\n                &format!(\"{}/{}/witness.json\", test_dir, example_name),\n                &format!(\"{}/{}/settings.json\", test_dir, example_name),\n                &format!(\"{}\", target_perc),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n\n        assert!(status.success());\n    }\n\n    // Mock prove (fast, but does not cover some potential issues)\n    fn render_circuit(test_dir: &str, example_name: String) {\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"render-circuit\",\n                \"-M\",\n                format!(\"{}/{}/network.onnx\", test_dir, example_name).as_str(),\n                \"-O\",\n                format!(\"{}/{}/render.png\", test_dir, example_name).as_str(),\n                \"--lookup-range=-32768->32768\",\n                \"-K=17\",\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    fn kzg_aggr_mock_prove_and_verify(test_dir: &str, example_name: String) {\n        prove_and_verify(\n            test_dir,\n            example_name.clone(),\n            \"safe\",\n            \"private\",\n            \"private\",\n            \"public\",\n            2,\n            None,\n            false,\n            \"for-aggr\",\n            Commitments::KZG,\n            2,\n        );\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"mock-aggregate\",\n                \"--logrows=23\",\n                \"--aggregation-snarks\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    fn aggr_prove_and_verify(\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n        commitment: Commitments,\n    ) {\n        prove_and_verify(\n            test_dir,\n            example_name.clone(),\n            \"safe\",\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            2,\n            None,\n            false,\n            \"for-aggr\",\n            Commitments::KZG,\n            2,\n        );\n\n        download_srs(23, commitment);\n        // now setup-aggregate\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"setup-aggregate\",\n                \"--sample-snarks\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--logrows=23\",\n                \"--vk-path\",\n                &format!(\"{}/{}/aggr.vk\", test_dir, example_name),\n                \"--pk-path\",\n                &format!(\"{}/{}/aggr.pk\", test_dir, example_name),\n                &format!(\"--commitment={}\", commitment),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"aggregate\",\n                \"--logrows=23\",\n                \"--aggregation-snarks\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--proof-path\",\n                &format!(\"{}/{}/aggr.pf\", test_dir, example_name),\n                \"--pk-path\",\n                &format!(\"{}/{}/aggr.pk\", test_dir, example_name),\n                &format!(\"--commitment={}\", commitment),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"verify-aggr\",\n                \"--logrows=23\",\n                \"--proof-path\",\n                &format!(\"{}/{}/aggr.pf\", test_dir, example_name),\n                \"--vk-path\",\n                &format!(\"{}/{}/aggr.vk\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    fn kzg_evm_aggr_prove_and_verify(\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n    ) {\n        aggr_prove_and_verify(\n            test_dir,\n            example_name.clone(),\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            Commitments::KZG,\n        );\n\n        download_srs(23, Commitments::KZG);\n\n        let vk_arg = &format!(\"{}/{}/aggr.vk\", test_dir, example_name);\n\n        fn build_args<'a>(base_args: Vec<&'a str>, sol_arg: &'a str) -> Vec<&'a str> {\n            let mut args = base_args;\n\n            args.push(\"--sol-code-path\");\n            args.push(sol_arg);\n            args\n        }\n\n        let sol_arg = format!(\"{}/{}/kzg_aggr.sol\", test_dir, example_name);\n        let addr_path_arg = format!(\"--addr-path={}/{}/addr.txt\", test_dir, example_name);\n        let rpc_arg = format!(\"--rpc-url={}\", *ANVIL_URL);\n        let settings_arg = format!(\"{}/{}/settings.json\", test_dir, example_name);\n        let private_key = format!(\"--private-key={}\", *ANVIL_DEFAULT_PRIVATE_KEY);\n\n        let base_args = vec![\n            \"create-evm-verifier-aggr\",\n            \"--vk-path\",\n            vk_arg.as_str(),\n            \"--aggregation-settings\",\n            settings_arg.as_str(),\n            \"--logrows=23\",\n        ];\n\n        let args = build_args(base_args, &sol_arg);\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // deploy the verifier\n        let args = vec![\n            \"deploy-evm-verifier\",\n            rpc_arg.as_str(),\n            addr_path_arg.as_str(),\n            \"--sol-code-path\",\n            sol_arg.as_str(),\n            private_key.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // read in the address\n        let addr = std::fs::read_to_string(format!(\"{}/{}/addr.txt\", test_dir, example_name))\n            .expect(\"failed to read address file\");\n\n        let deployed_addr_arg = format!(\"--addr-verifier={}\", addr);\n\n        let pf_arg = format!(\"{}/{}/aggr.pf\", test_dir, example_name);\n\n        let mut base_args = vec![\n            \"verify-evm\",\n            \"--proof-path\",\n            pf_arg.as_str(),\n            deployed_addr_arg.as_str(),\n            rpc_arg.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&base_args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        // As sanity check, add example that should fail.\n        base_args[2] = PF_FAILURE_AGGR;\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(base_args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(!status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    #[allow(clippy::too_many_arguments)]\n    fn prove_and_verify(\n        test_dir: &str,\n        example_name: String,\n        checkmode: &str,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n        num_inner_columns: usize,\n        scales_to_use: Option<Vec<u32>>,\n        overflow: bool,\n        proof_type: &str,\n        commitment: Commitments,\n        lookup_safety_margin: usize,\n    ) {\n        let target_str = if overflow {\n            \"resources/col-overflow\"\n        } else {\n            \"resources\"\n        };\n\n        gen_circuit_settings_and_witness(\n            test_dir,\n            example_name.clone(),\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            1,\n            target_str,\n            scales_to_use,\n            num_inner_columns,\n            false,\n            &mut 0.0,\n            commitment,\n            lookup_safety_margin,\n        );\n\n        let settings_path = format!(\"{}/{}/settings.json\", test_dir, example_name);\n\n        init_params(settings_path.clone().into());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"setup\",\n                \"-M\",\n                &format!(\"{}/{}/network.compiled\", test_dir, example_name),\n                \"--pk-path\",\n                &format!(\"{}/{}/key.pk\", test_dir, example_name),\n                \"--vk-path\",\n                &format!(\"{}/{}/key.vk\", test_dir, example_name),\n                \"--disable-selector-compression\",\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"prove\",\n                \"-W\",\n                format!(\"{}/{}/witness.json\", test_dir, example_name).as_str(),\n                \"-M\",\n                format!(\"{}/{}/network.compiled\", test_dir, example_name).as_str(),\n                \"--proof-path\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--pk-path\",\n                &format!(\"{}/{}/key.pk\", test_dir, example_name),\n                &format!(\"--check-mode={}\", checkmode),\n                &format!(\"--proof-type={}\", proof_type),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"swap-proof-commitments\",\n                \"--proof-path\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--witness-path\",\n                format!(\"{}/{}/witness.json\", test_dir, example_name).as_str(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"verify\",\n                format!(\"--settings-path={}\", settings_path).as_str(),\n                \"--proof-path\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--vk-path\",\n                &format!(\"{}/{}/key.vk\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // load settings file\n        let settings =\n            std::fs::read_to_string(settings_path.clone()).expect(\"failed to read settings file\");\n\n        let graph_settings = serde_json::from_str::<GraphSettings>(&settings)\n            .expect(\"failed to parse settings file\");\n\n        // get_srs for the graph_settings_num_instances\n        download_srs(1, graph_settings.run_args.commitment.into());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"verify\",\n                format!(\"--settings-path={}\", settings_path).as_str(),\n                \"--proof-path\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--vk-path\",\n                &format!(\"{}/{}/key.vk\", test_dir, example_name),\n                \"--reduced-srs\",\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    fn kzg_evm_prove_and_verify(\n        num_inner_columns: usize,\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n    ) {\n        let anvil_url = ANVIL_URL.as_str();\n\n        prove_and_verify(\n            test_dir,\n            example_name.clone(),\n            \"safe\",\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            num_inner_columns,\n            None,\n            false,\n            \"single\",\n            Commitments::KZG,\n            2,\n        );\n\n        let settings_path = format!(\"{}/{}/settings.json\", test_dir, example_name);\n        init_params(settings_path.clone().into());\n\n        let vk_arg = format!(\"{}/{}/key.vk\", test_dir, example_name);\n        let rpc_arg = format!(\"--rpc-url={}\", anvil_url);\n        let addr_path_arg = format!(\"--addr-path={}/{}/addr.txt\", test_dir, example_name);\n        let settings_arg = format!(\"--settings-path={}\", settings_path);\n\n        // create the verifier\n        let mut args = vec![\"create-evm-verifier\", \"--vk-path\", &vk_arg, &settings_arg];\n\n        let sol_arg = format!(\"{}/{}/kzg.sol\", test_dir, example_name);\n\n        // create everything to test the pipeline\n        args.push(\"--sol-code-path\");\n        args.push(sol_arg.as_str());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // deploy the verifier\n        let mut args = vec![\n            \"deploy-evm-verifier\",\n            rpc_arg.as_str(),\n            addr_path_arg.as_str(),\n        ];\n\n        args.push(\"--sol-code-path\");\n        args.push(sol_arg.as_str());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // read in the address\n        let addr = std::fs::read_to_string(format!(\"{}/{}/addr.txt\", test_dir, example_name))\n            .expect(\"failed to read address file\");\n\n        let deployed_addr_arg = format!(\"--addr-verifier={}\", addr);\n\n        // now verify the proof\n        let pf_arg = format!(\"{}/{}/proof.pf\", test_dir, example_name);\n        let mut args = vec![\n            \"verify-evm\",\n            \"--proof-path\",\n            pf_arg.as_str(),\n            rpc_arg.as_str(),\n            deployed_addr_arg.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        // As sanity check, add example that should fail.\n        args[2] = PF_FAILURE;\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(!status.success());\n    }\n\n    // prove-serialize-verify, the usual full path\n    fn kzg_evm_prove_and_verify_render_seperately(\n        num_inner_columns: usize,\n        test_dir: &str,\n        example_name: String,\n        input_visibility: &str,\n        param_visibility: &str,\n        output_visibility: &str,\n    ) {\n        let anvil_url = ANVIL_URL.as_str();\n\n        prove_and_verify(\n            test_dir,\n            example_name.clone(),\n            \"safe\",\n            input_visibility,\n            param_visibility,\n            output_visibility,\n            num_inner_columns,\n            None,\n            false,\n            \"single\",\n            Commitments::KZG,\n            2,\n        );\n\n        let settings_path = format!(\"{}/{}/settings.json\", test_dir, example_name);\n        init_params(settings_path.clone().into());\n\n        let vk_arg = format!(\"{}/{}/key.vk\", test_dir, example_name);\n        let rpc_arg = format!(\"--rpc-url={}\", anvil_url);\n        let addr_path_arg = format!(\"--addr-path={}/{}/addr.txt\", test_dir, example_name);\n        let settings_arg = format!(\"--settings-path={}\", settings_path);\n        let sol_arg = format!(\"--sol-code-path={}/{}/kzg.sol\", test_dir, example_name);\n\n        // create the verifier\n        let args = vec![\n            \"create-evm-verifier\",\n            \"--vk-path\",\n            &vk_arg,\n            &settings_arg,\n            &sol_arg,\n            \"--render-vk-seperately\",\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let addr_path_arg_vk = format!(\"--addr-path={}/{}/addr_vk.txt\", test_dir, example_name);\n        let sol_arg_vk = format!(\"--sol-code-path={}/{}/vk.sol\", test_dir, example_name);\n        // create the verifier\n        let args = vec![\n            \"create-evm-vk\",\n            \"--vk-path\",\n            &vk_arg,\n            &settings_arg,\n            &sol_arg_vk,\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // deploy the verifier\n        let args = vec![\n            \"deploy-evm-verifier\",\n            rpc_arg.as_str(),\n            addr_path_arg.as_str(),\n            sol_arg.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // read in the address\n        let addr = std::fs::read_to_string(format!(\"{}/{}/addr.txt\", test_dir, example_name))\n            .expect(\"failed to read address file\");\n\n        let deployed_addr_arg = format!(\"--addr-verifier={}\", addr);\n\n        // deploy the vk\n        let args = vec![\n            \"deploy-evm-vk\",\n            rpc_arg.as_str(),\n            addr_path_arg_vk.as_str(),\n            sol_arg_vk.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        // read in the address\n        let addr_vk = std::fs::read_to_string(format!(\"{}/{}/addr_vk.txt\", test_dir, example_name))\n            .expect(\"failed to read address file\");\n\n        let deployed_addr_arg_vk = format!(\"--addr-vk={}\", addr_vk);\n\n        // now verify the proof\n        let pf_arg = format!(\"{}/{}/proof.pf\", test_dir, example_name);\n        let mut args = vec![\n            \"verify-evm\",\n            \"--proof-path\",\n            pf_arg.as_str(),\n            rpc_arg.as_str(),\n            deployed_addr_arg.as_str(),\n            deployed_addr_arg_vk.as_str(),\n        ];\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        // As sanity check, add example that should fail.\n        args[2] = PF_FAILURE;\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(!status.success());\n    }\n\n    // run js browser evm verify tests for a given example\n    fn run_js_tests(test_dir: &str, example_name: String, js_test: &str, vk: bool) {\n        let example = format!(\"--example={}\", example_name);\n        let dir = format!(\"--dir={}\", test_dir);\n        let mut args = vec![\"run\", \"test\", js_test, &example, &dir];\n        let vk_string: String;\n        if vk {\n            vk_string = format!(\"--vk={}\", vk);\n            args.push(&vk_string);\n        };\n        let status = Command::new(\"pnpm\")\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    fn kzg_evm_on_chain_input_prove_and_verify(\n        test_dir: &str,\n        example_name: String,\n        input_source: &str,\n        output_source: &str,\n        input_visibility: &str,\n        output_visibility: &str,\n    ) {\n        gen_circuit_settings_and_witness(\n            test_dir,\n            example_name.clone(),\n            input_visibility,\n            \"private\",\n            output_visibility,\n            1,\n            \"resources\",\n            // we need the accuracy\n            Some(vec![4]),\n            1,\n            false,\n            &mut 0.0,\n            Commitments::KZG,\n            2,\n        );\n\n        let model_path = format!(\"{}/{}/network.compiled\", test_dir, example_name);\n        let settings_path = format!(\"{}/{}/settings.json\", test_dir, example_name);\n\n        init_params(settings_path.clone().into());\n\n        let data_path = format!(\"{}/{}/input.json\", test_dir, example_name);\n        let witness_path = format!(\"{}/{}/witness.json\", test_dir, example_name);\n        let test_on_chain_data_path = format!(\"{}/{}/on_chain_input.json\", test_dir, example_name);\n        let rpc_arg = format!(\"--rpc-url={}\", LIMITLESS_ANVIL_URL.as_str());\n        let private_key = format!(\"--private-key={}\", *ANVIL_DEFAULT_PRIVATE_KEY);\n\n        let test_input_source = format!(\"--input-source={}\", input_source);\n        let test_output_source = format!(\"--output-source={}\", output_source);\n\n        // load witness\n        let witness: GraphWitness = GraphWitness::from_path(witness_path.clone().into()).unwrap();\n        let mut input: GraphData = GraphData::from_path(data_path.clone().into()).unwrap();\n\n        if input_visibility == \"hashed\" {\n            let hashes = witness.processed_inputs.unwrap().poseidon_hash.unwrap();\n            input.input_data = DataSource::File(\n                hashes\n                    .iter()\n                    .map(|h| vec![FileSourceInner::Field(*h)])\n                    .collect(),\n            );\n        }\n        if output_visibility == \"hashed\" {\n            let hashes = witness.processed_outputs.unwrap().poseidon_hash.unwrap();\n            input.output_data = Some(DataSource::File(\n                hashes\n                    .iter()\n                    .map(|h| vec![FileSourceInner::Field(*h)])\n                    .collect(),\n            ));\n        } else {\n            input.output_data = Some(DataSource::File(\n                witness\n                    .pretty_elements\n                    .unwrap()\n                    .rescaled_outputs\n                    .iter()\n                    .map(|o| {\n                        o.iter()\n                            .map(|f| FileSourceInner::Float(f.parse().unwrap()))\n                            .collect()\n                    })\n                    .collect(),\n            ));\n        }\n\n        input.save(data_path.clone().into()).unwrap();\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"setup-test-evm-data\",\n                \"-D\",\n                data_path.as_str(),\n                \"-M\",\n                &model_path,\n                \"--test-data\",\n                test_on_chain_data_path.as_str(),\n                rpc_arg.as_str(),\n                test_input_source.as_str(),\n                test_output_source.as_str(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"setup\",\n                \"-M\",\n                &model_path,\n                \"--pk-path\",\n                &format!(\"{}/{}/key.pk\", test_dir, example_name),\n                \"--vk-path\",\n                &format!(\"{}/{}/key.vk\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"prove\",\n                \"-W\",\n                &witness_path,\n                \"-M\",\n                &model_path,\n                \"--proof-path\",\n                &format!(\"{}/{}/proof.pf\", test_dir, example_name),\n                \"--pk-path\",\n                &format!(\"{}/{}/key.pk\", test_dir, example_name),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let vk_arg = format!(\"{}/{}/key.vk\", test_dir, example_name);\n\n        let settings_arg = format!(\"--settings-path={}\", settings_path);\n\n        // create the verifier\n        let mut args = vec![\"create-evm-verifier\", \"--vk-path\", &vk_arg, &settings_arg];\n\n        let sol_arg = format!(\"{}/{}/kzg.sol\", test_dir, example_name);\n\n        args.push(\"--sol-code-path\");\n        args.push(sol_arg.as_str());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let addr_path_verifier_arg = format!(\n            \"--addr-path={}/{}/addr_verifier.txt\",\n            test_dir, example_name\n        );\n\n        // deploy the verifier\n        let mut args = vec![\n            \"deploy-evm-verifier\",\n            rpc_arg.as_str(),\n            addr_path_verifier_arg.as_str(),\n        ];\n\n        args.push(\"--sol-code-path\");\n        args.push(sol_arg.as_str());\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let sol_arg = format!(\"{}/{}/kzg.sol\", test_dir, example_name);\n\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"create-evm-da\",\n                &settings_arg,\n                \"--sol-code-path\",\n                sol_arg.as_str(),\n                \"-D\",\n                test_on_chain_data_path.as_str(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let addr_path_da_arg = format!(\"--addr-path={}/{}/addr_da.txt\", test_dir, example_name);\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"deploy-evm-da\",\n                format!(\"--settings-path={}\", settings_path).as_str(),\n                \"-D\",\n                test_on_chain_data_path.as_str(),\n                \"--sol-code-path\",\n                sol_arg.as_str(),\n                rpc_arg.as_str(),\n                addr_path_da_arg.as_str(),\n                private_key.as_str(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let pf_arg = format!(\"{}/{}/proof.pf\", test_dir, example_name);\n        // read in the verifier address\n        let addr_verifier =\n            std::fs::read_to_string(format!(\"{}/{}/addr_verifier.txt\", test_dir, example_name))\n                .expect(\"failed to read address file\");\n\n        let deployed_addr_verifier_arg = format!(\"--addr-verifier={}\", addr_verifier);\n\n        // read in the da address\n        let addr_da = std::fs::read_to_string(format!(\"{}/{}/addr_da.txt\", test_dir, example_name))\n            .expect(\"failed to read address file\");\n\n        let deployed_addr_da_arg = format!(\"--addr-da={}\", addr_da);\n\n        let args = vec![\n            \"verify-evm\",\n            \"--proof-path\",\n            pf_arg.as_str(),\n            deployed_addr_verifier_arg.as_str(),\n            deployed_addr_da_arg.as_str(),\n            rpc_arg.as_str(),\n        ];\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        // Create a new set of test on chain data\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args([\n                \"setup-test-evm-data\",\n                \"-D\",\n                data_path.as_str(),\n                \"-M\",\n                &model_path,\n                \"--test-data\",\n                test_on_chain_data_path.as_str(),\n                rpc_arg.as_str(),\n                test_input_source.as_str(),\n                test_output_source.as_str(),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n\n        assert!(status.success());\n\n        let deployed_addr_arg = format!(\"--addr={}\", addr_da);\n\n        let args = vec![\n            \"test-update-account-calls\",\n            deployed_addr_arg.as_str(),\n            \"-D\",\n            test_on_chain_data_path.as_str(),\n            rpc_arg.as_str(),\n        ];\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(&args)\n            .status()\n            .expect(\"failed to execute process\");\n\n        assert!(status.success());\n        // As sanity check, add example that should fail.\n        let args = vec![\n            \"verify-evm\",\n            \"--proof-path\",\n            PF_FAILURE,\n            deployed_addr_verifier_arg.as_str(),\n            deployed_addr_da_arg.as_str(),\n            rpc_arg.as_str(),\n        ];\n        let status = Command::new(format!(\"{}/release/ezkl\", *CARGO_TARGET_DIR))\n            .args(args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(!status.success());\n    }\n\n    fn build_ezkl() {\n        #[cfg(feature = \"icicle\")]\n        let args = [\n            \"build\",\n            \"--release\",\n            \"--bin\",\n            \"ezkl\",\n            \"--features\",\n            \"icicle\",\n        ];\n        #[cfg(not(feature = \"icicle\"))]\n        let args = [\"build\", \"--release\", \"--bin\", \"ezkl\"];\n        #[cfg(not(feature = \"mv-lookup\"))]\n        let args = [\n            \"build\",\n            \"--release\",\n            \"--bin\",\n            \"ezkl\",\n            \"--no-default-features\",\n            \"--features\",\n            \"ezkl\",\n        ];\n\n        let status = Command::new(\"cargo\")\n            .args(args)\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    #[allow(dead_code)]\n    fn build_wasm_ezkl() {\n        // wasm-pack build --target nodejs --out-dir ./tests/wasm/nodejs . -- -Z build-std=\"panic_abort,std\"\n        let status = Command::new(\"wasm-pack\")\n            .args([\n                \"build\",\n                \"--release\",\n                \"--target\",\n                \"nodejs\",\n                \"--out-dir\",\n                \"./tests/wasm/nodejs\",\n                \".\",\n                \"--\",\n                \"-Z\",\n                \"build-std=panic_abort,std\",\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n        // fix the memory size\n        //   sed -i \"3s|.*|imports['env'] = {memory: new WebAssembly.Memory({initial:20,maximum:65536,shared:true})}|\" tests/wasm/nodejs/ezkl.js\n        let status = Command::new(\"sed\")\n            .args([\n                \"-i\",\n                // is required on macos\n                // \"\\\".js\\\"\",\n                \"3s|.*|imports['env'] = {memory: new WebAssembly.Memory({initial:20,maximum:65536,shared:true})}|\",\n                \"./tests/wasm/nodejs/ezkl.js\",\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/output_comparison.py",
        "content": "import ezkl\nimport json\nimport onnx\nimport onnxruntime\nimport numpy as np\nimport sys\n\n\ndef get_ezkl_output(witness_file, settings_file):\n    # convert the quantized ezkl output to float value\n    witness_output = json.load(open(witness_file))\n    outputs = witness_output['outputs']\n    with open(settings_file) as f:\n        settings = json.load(f)\n    ezkl_outputs = [[ezkl.felt_to_float(\n        outputs[i][j], settings['model_output_scales'][i]) for j in range(len(outputs[i]))] for i in range(len(outputs))]\n    return ezkl_outputs\n\n\ndef get_onnx_output(model_file, input_file):\n    # generate the ML model output from the ONNX file\n    onnx_model = onnx.load(model_file)\n    onnx.checker.check_model(onnx_model)\n\n    with open(input_file) as f:\n        inputs = json.load(f)\n    # reshape the input to the model\n    num_inputs = len(onnx_model.graph.input)\n\n    onnx_input = dict()\n    for i in range(num_inputs):\n        input_node = onnx_model.graph.input[i]\n        dims = []\n        elem_type = input_node.type.tensor_type.elem_type\n        print(\"elem_type: \", elem_type)\n        for dim in input_node.type.tensor_type.shape.dim:\n            if dim.dim_value == 0:\n                dims.append(1)\n            else:\n                dims.append(dim.dim_value)\n        if elem_type == 6:\n            inputs_onnx = np.array(inputs['input_data'][i]).astype(\n                np.int32).reshape(dims)\n        elif elem_type == 7:\n            inputs_onnx = np.array(inputs['input_data'][i]).astype(\n                np.int64).reshape(dims)\n        elif elem_type == 9:\n            inputs_onnx = np.array(inputs['input_data'][i]).astype(\n                bool).reshape(dims)\n        else:\n            inputs_onnx = np.array(inputs['input_data'][i]).astype(\n                np.float32).reshape(dims)\n        onnx_input[input_node.name] = inputs_onnx\n    try:\n        onnx_session = onnxruntime.InferenceSession(model_file)\n        onnx_output = onnx_session.run(None, onnx_input)\n    except Exception as e:\n        print(\"error: \", e)\n        onnx_output = inputs['output_data']\n    print(\"onnx \", onnx_output)\n    return onnx_output[0]\n\n\ndef compare_outputs(zk_output, onnx_output):\n    # calculate percentage difference between the 2 outputs (which are lists)\n\n    res = []\n\n    contains_sublist = any(isinstance(sub, list) for sub in zk_output)\n    print(\"zk \", zk_output)\n    if contains_sublist:\n        try:\n            if len(onnx_output) == 1:\n                zk_output = zk_output[0]\n        except Exception as e:\n            zk_output = zk_output[0]\n    print(\"zk \", zk_output)\n\n    zip_object = zip(np.array(zk_output).flatten(),\n                     np.array(onnx_output).flatten())\n    for (i, (list1_i, list2_i)) in enumerate(zip_object):\n        if list1_i == 0.0 and list2_i == 0.0:\n            res.append(0)\n        else:\n            diff = list1_i - list2_i\n            res.append(100 * (diff) / (list2_i))\n            # iterate and print the diffs  if they are greater than 0.0\n            if abs(diff) > 0.0:\n                print(\"------- index: \", i)\n                print(\"------- diff: \", diff)\n                print(\"------- zk_output: \", list1_i)\n                print(\"------- onnx_output: \", list2_i)\n\n    return res\n\n\nif __name__ == '__main__':\n    # model file is first argument to script\n    model_file = sys.argv[1]\n    # input file is second argument to script\n    input_file = sys.argv[2]\n    # witness file is third argument to script\n    witness_file = sys.argv[3]\n    # settings file is fourth argument to script\n    settings_file = sys.argv[4]\n    # target\n    target = float(sys.argv[5])\n    # get the ezkl output\n    ezkl_output = get_ezkl_output(witness_file, settings_file)\n    # get the onnx output\n    onnx_output = get_onnx_output(model_file, input_file)\n    # compare the outputs\n    percentage_difference = compare_outputs(ezkl_output, onnx_output)\n    mean_percentage_difference = np.mean(np.abs(percentage_difference))\n    max_percentage_difference = np.max(np.abs(percentage_difference))\n    # print the percentage difference\n    print(\"mean percent diff: \", mean_percentage_difference)\n    print(\"max percent diff: \", max_percentage_difference)\n    assert mean_percentage_difference < target, \"Percentage difference is too high\"\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/py_integration_tests.rs",
        "content": "#[cfg(not(target_arch = \"wasm32\"))]\n#[cfg(test)]\nmod py_tests {\n\n    use lazy_static::lazy_static;\n    use std::env::var;\n    use std::process::{Child, Command};\n    use std::sync::Once;\n    use tempdir::TempDir;\n    static COMPILE: Once = Once::new();\n    static ENV_SETUP: Once = Once::new();\n    static DOWNLOAD_VOICE_DATA: Once = Once::new();\n\n    //Sure to run this once\n\n    lazy_static! {\n        static ref CARGO_TARGET_DIR: String =\n            var(\"CARGO_TARGET_DIR\").unwrap_or_else(|_| \"./target\".to_string());\n        static ref ANVIL_URL: String = \"http://localhost:3030\".to_string();\n    }\n\n    fn start_anvil(limitless: bool) -> Child {\n        let mut args = vec![\"-p\", \"3030\"];\n        if limitless {\n            args.push(\"--code-size-limit=41943040\");\n            args.push(\"--disable-block-gas-limit\");\n        }\n        let child = Command::new(\"anvil\")\n            .args(args)\n            // .stdout(Stdio::piped())\n            .spawn()\n            .expect(\"failed to start anvil process\");\n\n        std::thread::sleep(std::time::Duration::from_secs(3));\n        child\n    }\n\n    fn download_voice_data() {\n        let voice_data_dir = shellexpand::tilde(\"~/data/voice_data\");\n\n        DOWNLOAD_VOICE_DATA.call_once(|| {\n            let status = Command::new(\"bash\")\n                .args([\"examples/notebooks/voice_data.sh\", &voice_data_dir])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n        });\n        // set VOICE_DATA_DIR environment variable\n        std::env::set_var(\"VOICE_DATA_DIR\", format!(\"{}\", voice_data_dir));\n    }\n\n    fn setup_py_env() {\n        ENV_SETUP.call_once(|| {\n            // supposes that you have a virtualenv called .env and have run the following\n            // equivalent of python -m venv .env\n            // source .env/bin/activate\n            // pip install -r requirements.txt\n            // maturin develop --release --features python-bindings\n            // first install tf2onnx as it has protobuf conflict with onnx\n            let status = Command::new(\"pip\")\n                .args([\"install\", \"tf2onnx==1.16.1\"])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n            // now install torch, pandas, numpy, seaborn, jupyter\n            let status = Command::new(\"pip\")\n                .args([\n                    \"install\",\n                    \"torch-geometric==2.5.2\",\n                    \"torch==2.2.2\",\n                    \"torchvision==0.17.2\",\n                    \"pandas==2.2.1\",\n                    \"numpy==1.26.4\",\n                    \"seaborn==0.13.2\",\n                    \"notebook==7.1.2\",\n                    \"nbconvert==7.16.3\",\n                    \"onnx==1.16.0\",\n                    \"kaggle==1.6.8\",\n                    \"py-solc-x==2.0.2\",\n                    \"web3==6.16.0\",\n                    \"librosa==0.10.1\",\n                    \"keras==3.1.1\",\n                    \"tensorflow==2.16.1\",\n                    \"tensorflow-datasets==4.9.4\",\n                    \"pytorch-lightning==2.2.1\",\n                    \"sk2torch==1.2.0\",\n                    \"scikit-learn==1.4.1.post1\",\n                    \"xgboost==2.0.3\",\n                    \"hummingbird-ml==0.4.11\",\n                    \"lightgbm==4.3.0\",\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n            let status = Command::new(\"pip\")\n                .args([\"install\", \"numpy==1.23\"])\n                .status()\n                .expect(\"failed to execute process\");\n\n            assert!(status.success());\n        });\n    }\n\n    fn init_binary() {\n        COMPILE.call_once(|| {\n            println!(\"using cargo target dir: {}\", *CARGO_TARGET_DIR);\n            setup_py_env();\n        });\n    }\n\n    fn mv_test_(test_dir: &str, test: &str) {\n        let path: std::path::PathBuf = format!(\"{}/{}\", test_dir, test).into();\n        if !path.exists() {\n            let status = Command::new(\"cp\")\n                .args([\n                    \"-R\",\n                    &format!(\"./examples/notebooks/{}\", test),\n                    &format!(\"{}/{}\", test_dir, test),\n                ])\n                .status()\n                .expect(\"failed to execute process\");\n            assert!(status.success());\n        }\n    }\n\n    const TESTS: [&str; 32] = [\n        \"proof_splitting.ipynb\", // 0\n        \"variance.ipynb\",\n        \"mnist_gan.ipynb\",\n        // \"mnist_vae.ipynb\",\n        \"keras_simple_demo.ipynb\",\n        \"mnist_gan_proof_splitting.ipynb\", // 4\n        \"hashed_vis.ipynb\",                // 5\n        \"simple_demo_all_public.ipynb\",\n        \"data_attest.ipynb\",\n        \"little_transformer.ipynb\",\n        \"simple_demo_aggregated_proofs.ipynb\",\n        \"ezkl_demo.ipynb\", // 10\n        \"lstm.ipynb\",\n        \"set_membership.ipynb\", // 12\n        \"decision_tree.ipynb\",\n        \"random_forest.ipynb\",\n        \"gradient_boosted_trees.ipynb\", // 15\n        \"xgboost.ipynb\",\n        \"lightgbm.ipynb\",\n        \"svm.ipynb\",\n        \"simple_demo_public_input_output.ipynb\",\n        \"simple_demo_public_network_output.ipynb\", // 20\n        \"gcn.ipynb\",\n        \"linear_regression.ipynb\",\n        \"stacked_regression.ipynb\",\n        \"data_attest_hashed.ipynb\",\n        \"kzg_vis.ipynb\", // 25\n        \"kmeans.ipynb\",\n        \"solvency.ipynb\",\n        \"sklearn_mlp.ipynb\",\n        \"generalized_inverse.ipynb\",\n        \"mnist_classifier.ipynb\", // 30\n        \"world_rotation.ipynb\",\n    ];\n\n    macro_rules! test_func {\n    () => {\n        #[cfg(test)]\n        mod tests {\n            use seq_macro::seq;\n            use crate::py_tests::TESTS;\n            use test_case::test_case;\n            use super::*;\n\n\n            seq!(N in 0..=31 {\n\n            #(#[test_case(TESTS[N])])*\n            fn run_notebook_(test: &str) {\n                crate::py_tests::init_binary();\n                let mut limitless = false;\n                if test == TESTS[5] {\n                    limitless = true;\n                }\n                let mut anvil_child = crate::py_tests::start_anvil(limitless);\n                let test_dir: TempDir = TempDir::new(\"nb\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, test);\n                run_notebook(path, test);\n                test_dir.close().unwrap();\n                anvil_child.kill().unwrap();\n            }\n            });\n            #[test]\n            fn voice_notebook_() {\n                crate::py_tests::init_binary();\n                let mut anvil_child = crate::py_tests::start_anvil(false);\n                crate::py_tests::download_voice_data();\n                let test_dir: TempDir = TempDir::new(\"voice_judge\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, \"voice_judge.ipynb\");\n                run_notebook(path, \"voice_judge.ipynb\");\n                test_dir.close().unwrap();\n                anvil_child.kill().unwrap();\n            }\n\n            #[test]\n            fn postgres_notebook_() {\n                crate::py_tests::init_binary();\n                let test_dir: TempDir = TempDir::new(\"mean_postgres\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, \"mean_postgres.ipynb\");\n                run_notebook(path, \"mean_postgres.ipynb\");\n                test_dir.close().unwrap();\n            }\n\n            #[test]\n            fn tictactoe_autoencoder_notebook_() {\n                crate::py_tests::init_binary();\n                let test_dir: TempDir = TempDir::new(\"tictactoe_autoencoder\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, \"tictactoe_autoencoder.ipynb\");\n                run_notebook(path, \"tictactoe_autoencoder.ipynb\");\n                test_dir.close().unwrap();\n            }\n\n            #[test]\n            fn tictactoe_binary_classification_notebook_() {\n                crate::py_tests::init_binary();\n                let test_dir: TempDir = TempDir::new(\"tictactoe_binary_classification\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, \"tictactoe_binary_classification.ipynb\");\n                run_notebook(path, \"tictactoe_binary_classification.ipynb\");\n                test_dir.close().unwrap();\n            }\n\n            #[test]\n            fn nbeats_notebook_() {\n                crate::py_tests::init_binary();\n                let test_dir: TempDir = TempDir::new(\"nbeats\").unwrap();\n                let path = test_dir.path().to_str().unwrap();\n                crate::py_tests::mv_test_(path, \"nbeats_timeseries_forecasting.ipynb\");\n                crate::py_tests::mv_test_(path, \"eth_price.csv\");\n                run_notebook(path, \"nbeats_timeseries_forecasting.ipynb\");\n                test_dir.close().unwrap();\n            }\n\n\n    }\n    };\n}\n\n    fn run_notebook(test_dir: &str, test: &str) {\n        // activate venv\n        let status = Command::new(\"bash\")\n            .arg(\"-c\")\n            .arg(\"source .env/bin/activate\")\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n\n        let path: std::path::PathBuf = format!(\"{}/{}\", test_dir, test).into();\n        let status = Command::new(\"jupyter\")\n            .args([\n                \"nbconvert\",\n                \"--to\",\n                \"notebook\",\n                \"--execute\",\n                (path.to_str().unwrap()),\n            ])\n            .status()\n            .expect(\"failed to execute process\");\n        assert!(status.success());\n    }\n\n    test_func!();\n}\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/python/binding_tests.py",
        "content": "import ezkl\nimport os\nimport pytest\nimport json\nimport subprocess\nimport time\n\nfolder_path = os.path.abspath(\n    os.path.join(\n        os.path.dirname(__file__),\n        '.',\n    )\n)\n\nexamples_path = os.path.abspath(\n    os.path.join(\n        folder_path,\n        '..',\n        '..',\n        'examples',\n    )\n)\n\nsrs_path = os.path.join(folder_path, 'kzg_test.params')\nparams_k17_path = os.path.join(folder_path, 'kzg_test_k17.params')\nparams_k20_path = os.path.join(folder_path, 'kzg_test_k20.params')\nanvil_url = \"http://localhost:3030\"\n\n\ndef setup_module(module):\n    \"\"\"setup anvil.\"\"\"\n    global proc\n    # requires an anvil install\n    proc = subprocess.Popen([\"anvil\", \"-p\", \"3030\"])\n    time.sleep(1)\n\n\ndef teardown_module(module):\n    \"\"\"teardown anvil.\n    \"\"\"\n    proc.terminate()\n\n\ndef test_py_run_args():\n    \"\"\"\n    Test for PyRunArgs\n    \"\"\"\n    run_args = ezkl.PyRunArgs()\n    run_args.input_visibility = \"hashed\"\n    run_args.output_visibility = \"hashed\"\n    run_args.tolerance = 1.5\n\n\ndef test_poseidon_hash():\n    \"\"\"\n    Test for poseidon_hash\n    \"\"\"\n    message = [1.0, 2.0, 3.0, 4.0]\n    message = [ezkl.float_to_felt(x, 7) for x in message]\n    res = ezkl.poseidon_hash(message)\n    assert ezkl.felt_to_big_endian(\n        res[0]) == \"0x0da7e5e5c8877242fa699f586baf770d731defd54f952d4adeb85047a0e32f45\"\n\n\n\ndef test_field_serialization():\n    \"\"\"\n    Test field element serialization\n    \"\"\"\n\n    input = 890\n    scale = 7\n    felt = ezkl.float_to_felt(input, scale)\n    roundtrip_input = ezkl.felt_to_float(felt, scale)\n    assert input == roundtrip_input\n\n    input = -700\n    scale = 7\n    felt = ezkl.float_to_felt(input, scale)\n    roundtrip_input = ezkl.felt_to_float(felt, scale)\n    assert input == roundtrip_input\n\n\ndef test_buffer_to_felts():\n    \"\"\"\n    Test buffer_to_felt\n    \"\"\"\n    buffer = bytearray(\"a sample string!\", 'utf-8')\n    felts = ezkl.buffer_to_felts(buffer)\n    ref_felt_1 = \"0x0000000000000000000000000000000021676e6972747320656c706d61732061\"\n    assert ezkl.felt_to_big_endian(felts[0]) == ref_felt_1\n\n    buffer = bytearray(\"a sample string!\"+\"high\", 'utf-8')\n    felts = ezkl.buffer_to_felts(buffer)\n    ref_felt_2 = \"0x0000000000000000000000000000000000000000000000000000000068676968\"\n    assert [ezkl.felt_to_big_endian(felts[0]),  ezkl.felt_to_big_endian(felts[1])] == [ref_felt_1, ref_felt_2]\n\n\ndef test_gen_srs():\n    \"\"\"\n    test for gen_srs() with 17 logrows and 20 logrows.\n    You may want to comment this test as it takes a long time to run\n    \"\"\"\n    ezkl.gen_srs(params_k17_path, 17)\n    assert os.path.isfile(params_k17_path)\n\n    ezkl.gen_srs(params_k20_path, 20)\n    assert os.path.isfile(params_k20_path)\n\n\n\ndef test_calibrate_over_user_range():\n    data_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'input.json'\n    )\n    model_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'network.onnx'\n    )\n    output_path = os.path.join(\n        folder_path,\n        'settings.json'\n    )\n\n    run_args = ezkl.PyRunArgs()\n    run_args.input_visibility = \"hashed\"\n    run_args.output_visibility = \"hashed\"\n\n    # TODO: Dictionary outputs\n    res = ezkl.gen_settings(\n        model_path, output_path, py_run_args=run_args)\n    assert res == True\n\n    res = ezkl.calibrate_settings(\n        data_path, model_path, output_path, \"resources\", 1, [0, 1, 2])\n    assert res == True\n    assert os.path.isfile(output_path)\n\n\n\ndef test_calibrate():\n    data_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'input.json'\n    )\n    model_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'network.onnx'\n    )\n    output_path = os.path.join(\n        folder_path,\n        'settings.json'\n    )\n\n    run_args = ezkl.PyRunArgs()\n    run_args.input_visibility = \"hashed\"\n    run_args.output_visibility = \"hashed\"\n\n    # TODO: Dictionary outputs\n    res = ezkl.gen_settings(\n        model_path, output_path, py_run_args=run_args)\n    assert res == True\n\n    res = ezkl.calibrate_settings(\n        data_path, model_path, output_path, \"resources\")\n    assert res == True\n    assert os.path.isfile(output_path)\n\n\ndef test_model_compile():\n    \"\"\"\n   Test for model compilation/serialization\n   \"\"\"\n    model_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'network.onnx'\n    )\n    compiled_model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n    settings_path = os.path.join(\n        folder_path,\n        'settings.json'\n    )\n    res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n    assert res == True\n\n\ndef test_forward():\n    \"\"\"\n    Test for vanilla forward pass\n    \"\"\"\n    data_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'input.json'\n    )\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n    output_path = os.path.join(\n        folder_path,\n        'witness.json'\n    )\n\n    res = ezkl.gen_witness(data_path, model_path, output_path)\n\n    with open(output_path, \"r\") as f:\n        data = json.load(f)\n\n    assert data[\"inputs\"] == res[\"inputs\"]\n    assert data[\"outputs\"] == res[\"outputs\"]\n\n    assert data[\"processed_inputs\"][\"poseidon_hash\"] == res[\"processed_inputs\"][\"poseidon_hash\"]\n    assert data[\"processed_outputs\"][\"poseidon_hash\"] == res[\"processed_outputs\"][\"poseidon_hash\"]\n\n\ndef test_get_srs():\n    \"\"\"\n    Test for get_srs\n    \"\"\"\n    settings_path = os.path.join(folder_path, 'settings.json')\n    res = ezkl.get_srs(settings_path, srs_path=srs_path)\n\n    assert res == True\n\n    assert os.path.isfile(srs_path)\n\n    another_srs_path = os.path.join(folder_path, \"kzg_test_k8.params\")\n\n    res = ezkl.get_srs(logrows=8, srs_path=another_srs_path, commitment=ezkl.PyCommitments.KZG)\n\n    assert os.path.isfile(another_srs_path)\n\n\ndef test_mock():\n    \"\"\"\n    Test for mock\n    \"\"\"\n\n    data_path = os.path.join(\n        folder_path,\n        'witness.json'\n    )\n\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n\n    settings_path = os.path.join(folder_path, 'settings.json')\n\n    res = ezkl.mock(data_path, model_path)\n    assert res == True\n\n\ndef test_setup():\n    \"\"\"\n    Test for setup\n    \"\"\"\n\n    data_path = os.path.join(\n        folder_path,\n        'witness.json'\n    )\n\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n\n    pk_path = os.path.join(folder_path, 'test.pk')\n    vk_path = os.path.join(folder_path, 'test.vk')\n    settings_path = os.path.join(folder_path, 'settings.json')\n\n    res = ezkl.setup(\n        model_path,\n        vk_path,\n        pk_path,\n        srs_path=srs_path,\n    )\n    assert res == True\n    assert os.path.isfile(vk_path)\n    assert os.path.isfile(pk_path)\n    assert os.path.isfile(settings_path)\n\n    res = ezkl.gen_vk_from_pk_single(pk_path, settings_path, vk_path)\n    assert res == True\n    assert os.path.isfile(vk_path)\n\n\ndef test_setup_evm():\n    \"\"\"\n    Test for setup\n    \"\"\"\n\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n\n    pk_path = os.path.join(folder_path, 'test_evm.pk')\n    vk_path = os.path.join(folder_path, 'test_evm.vk')\n\n    res = ezkl.setup(\n        model_path,\n        vk_path,\n        pk_path,\n        srs_path=srs_path,\n    )\n    assert res == True\n    assert os.path.isfile(vk_path)\n    assert os.path.isfile(pk_path)\n\n\ndef test_prove_and_verify():\n    \"\"\"\n    Test for prove and verify\n    \"\"\"\n\n    data_path = os.path.join(\n        folder_path,\n        'witness.json'\n    )\n\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n\n    pk_path = os.path.join(folder_path, 'test.pk')\n    proof_path = os.path.join(folder_path, 'test.pf')\n\n    res = ezkl.prove(\n        data_path,\n        model_path,\n        pk_path,\n        proof_path,\n        \"for-aggr\",\n        srs_path=srs_path,\n    )\n    assert res['transcript_type'] == 'Poseidon'\n    assert os.path.isfile(proof_path)\n\n    settings_path = os.path.join(folder_path, 'settings.json')\n    vk_path = os.path.join(folder_path, 'test.vk')\n    res = ezkl.verify(proof_path, settings_path,\n                      vk_path, srs_path)\n    assert res == True\n    assert os.path.isfile(vk_path)\n\n\ndef test_prove_evm():\n    \"\"\"\n    Test for prove using evm transcript\n    \"\"\"\n\n    data_path = os.path.join(\n        folder_path,\n        'witness.json'\n    )\n\n    model_path = os.path.join(\n        folder_path,\n        'model.compiled'\n    )\n\n    pk_path = os.path.join(folder_path, 'test_evm.pk')\n    proof_path = os.path.join(folder_path, 'test_evm.pf')\n    res = ezkl.prove(\n        data_path,\n        model_path,\n        pk_path,\n        proof_path,\n        \"single\",\n        srs_path=srs_path,\n    )\n    assert res['transcript_type'] == 'EVM'\n    assert os.path.isfile(proof_path)\n\n\n\n\ndef test_create_evm_verifier():\n    \"\"\"\n    Create EVM verifier with solidity code\n    In order to run this test you will need to install solc in your environment\n    \"\"\"\n    vk_path = os.path.join(folder_path, 'test_evm.vk')\n    settings_path = os.path.join(folder_path, 'settings.json')\n    sol_code_path = os.path.join(folder_path, 'test.sol')\n    abi_path = os.path.join(folder_path, 'test.abi')\n\n    res = ezkl.create_evm_verifier(\n        vk_path,\n        settings_path,\n        sol_code_path,\n        abi_path,\n        srs_path=srs_path,\n    )\n\n    assert res == True\n    assert os.path.isfile(sol_code_path)\n\n\ndef test_deploy_evm():\n    \"\"\"\n    Test deployment of the verifier smart contract\n    In order to run this you will need to install solc in your environment\n    \"\"\"\n    addr_path = os.path.join(folder_path, 'address.json')\n    sol_code_path = os.path.join(folder_path, 'test.sol')\n\n    # TODO: without optimization there will be out of gas errors\n    # sol_code_path = os.path.join(folder_path, 'test.sol')\n\n    res = ezkl.deploy_evm(\n        addr_path,\n        sol_code_path,\n        rpc_url=anvil_url,\n    )\n\n    assert res == True\n\n\ndef test_deploy_evm_with_private_key():\n    \"\"\"\n    Test deployment of the verifier smart contract using a custom private key\n    In order to run this you will need to install solc in your environment\n    \"\"\"\n    addr_path = os.path.join(folder_path, 'address.json')\n    sol_code_path = os.path.join(folder_path, 'test.sol')\n\n    # TODO: without optimization there will be out of gas errors\n    # sol_code_path = os.path.join(folder_path, 'test.sol')\n\n    anvil_default_private_key = \"ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\"\n\n    res = ezkl.deploy_evm(\n        addr_path,\n        sol_code_path,\n        rpc_url=anvil_url,\n        private_key=anvil_default_private_key\n    )\n\n    assert res == True\n\n    custom_zero_balance_private_key = \"ff9dfe0b6d31e93ba13460a4d6f63b5e31dd9532b1304f1cbccea7092a042aa4\"\n\n    with pytest.raises(RuntimeError, match=\"Failed to run deploy_evm\"):\n        res = ezkl.deploy_evm(\n            addr_path,\n            sol_code_path,\n            rpc_url=anvil_url,\n            private_key=custom_zero_balance_private_key\n        )\n\n\ndef test_verify_evm():\n    \"\"\"\n    Verifies an evm proof\n    In order to run this you will need to install solc in your environment\n    \"\"\"\n    proof_path = os.path.join(folder_path, 'test_evm.pf')\n    addr_path = os.path.join(folder_path, 'address.json')\n\n    with open(addr_path, 'r') as file:\n        addr = file.read().rstrip()\n\n    print(addr)\n\n    # TODO: without optimization there will be out of gas errors\n    # sol_code_path = os.path.join(folder_path, 'test.sol')\n\n    res = ezkl.verify_evm(\n        addr,\n        proof_path,\n        rpc_url=anvil_url,\n        # sol_code_path\n        # optimizer_runs\n    )\n\n    assert res == True\n\n\ndef test_aggregate_and_verify_aggr():\n    data_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'input.json'\n    )\n\n    model_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'network.onnx'\n    )\n\n    compiled_model_path = os.path.join(\n        folder_path,\n        'compiled_relu.onnx'\n    )\n\n    pk_path = os.path.join(folder_path, '1l_relu.pk')\n    vk_path = os.path.join(folder_path, '1l_relu.vk')\n    settings_path = os.path.join(\n        folder_path, '1l_relu_aggr_settings.json')\n\n   # TODO: Dictionary outputs\n    res = ezkl.gen_settings(model_path, settings_path)\n    assert res == True\n\n    res = ezkl.calibrate_settings(\n        data_path, model_path, settings_path, \"resources\")\n    assert res == True\n    assert os.path.isfile(settings_path)\n\n    res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n    assert res == True\n\n    ezkl.setup(\n        compiled_model_path,\n        vk_path,\n        pk_path,\n        srs_path=srs_path,\n    )\n\n    proof_path = os.path.join(folder_path, '1l_relu.pf')\n\n    output_path = os.path.join(\n        folder_path,\n        '1l_relu_aggr_witness.json'\n    )\n\n    res = ezkl.gen_witness(data_path, compiled_model_path,\n                           output_path)\n\n    ezkl.prove(\n        output_path,\n        compiled_model_path,\n        pk_path,\n        proof_path,\n        \"for-aggr\",\n        srs_path=srs_path,\n    )\n\n    # mock aggregate\n    res = ezkl.mock_aggregate([proof_path], 20)\n    assert res == True\n\n    aggregate_proof_path = os.path.join(folder_path, 'aggr_1l_relu.pf')\n    aggregate_vk_path = os.path.join(folder_path, 'aggr_1l_relu.vk')\n    aggregate_pk_path = os.path.join(folder_path, 'aggr_1l_relu.pk')\n\n    res = ezkl.setup_aggregate(\n        [proof_path],\n        aggregate_vk_path,\n        aggregate_pk_path,\n        20,\n        srs_path=params_k20_path,\n    )\n\n    res = ezkl.gen_vk_from_pk_aggr(aggregate_pk_path, aggregate_vk_path)\n    assert res == True\n    assert os.path.isfile(vk_path)\n\n    res = ezkl.aggregate(\n        [proof_path],\n        aggregate_proof_path,\n        aggregate_pk_path,\n        \"poseidon\",\n        20,\n        \"unsafe\",\n        srs_path=params_k20_path,\n    )\n\n    assert res == True\n    assert os.path.isfile(aggregate_proof_path)\n    assert os.path.isfile(aggregate_vk_path)\n\n    res = ezkl.verify_aggr(\n        aggregate_proof_path,\n        aggregate_vk_path,\n        20,\n        srs_path=params_k20_path,\n    )\n    assert res == True\n\n\ndef test_evm_aggregate_and_verify_aggr():\n    data_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'input.json'\n    )\n\n    model_path = os.path.join(\n        examples_path,\n        'onnx',\n        '1l_relu',\n        'network.onnx'\n    )\n\n    pk_path = os.path.join(folder_path, '1l_relu.pk')\n    vk_path = os.path.join(folder_path, '1l_relu.vk')\n    settings_path = os.path.join(\n        folder_path, '1l_relu_evm_aggr_settings.json')\n\n    ezkl.gen_settings(\n        model_path,\n        settings_path,\n    )\n\n    ezkl.calibrate_settings(\n        data_path,\n        model_path,\n        settings_path,\n        \"resources\",\n    )\n\n    compiled_model_path = os.path.join(\n        folder_path,\n        'compiled_relu.onnx'\n    )\n\n    res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n    assert res == True\n\n    ezkl.setup(\n        compiled_model_path,\n        vk_path,\n        pk_path,\n        srs_path=srs_path,\n    )\n\n    proof_path = os.path.join(folder_path, '1l_relu.pf')\n\n    output_path = os.path.join(\n        folder_path,\n        '1l_relu_aggr_evm_witness.json'\n    )\n\n    res = ezkl.gen_witness(data_path, compiled_model_path,\n                           output_path)\n\n    ezkl.prove(\n        output_path,\n        compiled_model_path,\n        pk_path,\n        proof_path,\n        \"for-aggr\",\n        srs_path=srs_path,\n    )\n\n    aggregate_proof_path = os.path.join(folder_path, 'aggr_evm_1l_relu.pf')\n    aggregate_vk_path = os.path.join(folder_path, 'aggr_evm_1l_relu.vk')\n    aggregate_pk_path = os.path.join(folder_path, 'aggr_evm_1l_relu.pk')\n\n    res = ezkl.setup_aggregate(\n        [proof_path],\n        aggregate_vk_path,\n        aggregate_pk_path,\n        20,\n        srs_path=params_k20_path,\n    )\n\n    res = ezkl.aggregate(\n        [proof_path],\n        aggregate_proof_path,\n        aggregate_pk_path,\n        \"evm\",\n        20,\n        \"unsafe\",\n        srs_path=params_k20_path,\n    )\n\n    assert res == True\n    assert os.path.isfile(aggregate_proof_path)\n    assert os.path.isfile(aggregate_vk_path)\n\n    sol_code_path = os.path.join(folder_path, 'aggr_evm_1l_relu.sol')\n    abi_path = os.path.join(folder_path, 'aggr_evm_1l_relu.abi')\n\n    res = ezkl.create_evm_verifier_aggr(\n        [settings_path],\n        aggregate_vk_path,\n        sol_code_path,\n        abi_path,\n        logrows=20,\n        srs_path=params_k20_path,\n    )\n\n    assert res == True\n    assert os.path.isfile(sol_code_path)\n\n    addr_path = os.path.join(folder_path, 'address_aggr.json')\n\n    res = ezkl.deploy_evm(\n        addr_path,\n        sol_code_path,\n        rpc_url=anvil_url,\n    )\n\n    # as a sanity check\n    res = ezkl.verify_aggr(\n        aggregate_proof_path,\n        aggregate_vk_path,\n        20,\n        srs_path=params_k20_path,\n    )\n    assert res == True\n\n    # with open(addr_path, 'r') as file:\n    #     addr_aggr = file.read().rstrip()\n\n    # res = ezkl.verify_evm(\n    #     aggregate_proof_path,\n    #     addr_aggr,\n    #     rpc_url=anvil_url,\n    # )\n\n    # assert res == True\n\n\ndef get_examples():\n    EXAMPLES_OMIT = [\n        # these are too large\n        'mobilenet_large',\n        'mobilenet',\n        'doodles',\n        'nanoGPT',\n        \"self_attention\",\n        'multihead_attention',\n        'large_op_graph',\n        '1l_instance_norm',\n        'variable_cnn',\n        'accuracy',\n        'linear_regression',\n        \"mnist_gan\",\n    ]\n    examples = []\n    for subdir, _, _ in os.walk(os.path.join(examples_path, \"onnx\")):\n        name = subdir.split('/')[-1]\n        if name in EXAMPLES_OMIT or name == \"onnx\":\n            continue\n        else:\n            examples.append((\n                os.path.join(subdir, \"network.onnx\"),\n                os.path.join(subdir, \"input.json\"),\n            ))\n    return examples\n\n\n@pytest.mark.parametrize(\"model_file, input_file\", get_examples())\ndef test_all_examples(model_file, input_file):\n    \"\"\"Tests all examples in the examples folder\"\"\"\n    # gen settings\n    settings_path = os.path.join(folder_path, \"settings.json\")\n    compiled_model_path = os.path.join(folder_path, 'network.ezkl')\n    pk_path = os.path.join(folder_path, 'test.pk')\n    vk_path = os.path.join(folder_path, 'test.vk')\n    witness_path = os.path.join(folder_path, 'witness.json')\n    proof_path = os.path.join(folder_path, 'proof.json')\n\n    print(\"Testing example: \", model_file)\n    res = ezkl.gen_settings(model_file, settings_path)\n    assert res\n\n    res = ezkl.calibrate_settings(\n        input_file, model_file, settings_path, \"resources\")\n    assert res\n\n    print(\"Compiling example: \", model_file)\n    res = ezkl.compile_circuit(model_file, compiled_model_path, settings_path)\n    assert res\n\n    with open(settings_path, 'r') as f:\n        data = json.load(f)\n\n    logrows = data[\"run_args\"][\"logrows\"]\n    srs_path = os.path.join(folder_path, f\"srs_{logrows}\")\n\n    # generate the srs file if the path does not exist\n    if not os.path.exists(srs_path):\n        print(\"Generating srs file: \", srs_path)\n        ezkl.gen_srs(os.path.join(folder_path, srs_path), logrows)\n\n    print(\"Setting up example: \", model_file)\n    res = ezkl.setup(\n        compiled_model_path,\n        vk_path,\n        pk_path,\n        srs_path\n    )\n    assert res == True\n    assert os.path.isfile(vk_path)\n    assert os.path.isfile(pk_path)\n\n    print(\"Generating witness for example: \", model_file)\n    res = ezkl.gen_witness(input_file, compiled_model_path, witness_path)\n    assert os.path.isfile(witness_path)\n\n    print(\"Proving example: \", model_file)\n    ezkl.prove(\n        witness_path,\n        compiled_model_path,\n        pk_path,\n        proof_path,\n        \"single\",\n        srs_path=srs_path,\n    )\n\n    assert os.path.isfile(proof_path)\n\n    print(\"Verifying example: \", model_file)\n    res = ezkl.verify(\n        proof_path,\n        settings_path,\n        vk_path,\n        srs_path=srs_path,\n    )\n\n    assert res == True\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/python/srs_utils.py",
        "content": "\"\"\"\nThis is meant to be used locally for development.\nGenerating the SRS is costly so we run this instead of creating a new SRS each\ntime we run tests.\n\"\"\"\n\nimport ezkl\nimport os\n\nsrs_path = os.path.abspath(\n    os.path.join(\n        os.path.dirname(__file__),\n        '.',\n        'kzg_test.params',\n    )\n)\n\n\ndef gen_test_srs(logrows=17):\n    \"\"\"Generates a test srs with 17 log rows\"\"\"\n    ezkl.gen_srs(srs_path, logrows)\n\n\ndef delete_test_srs():\n    \"\"\"Deletes test srs after tests are done\"\"\"\n    os.remove(srs_path)\n\n\nif __name__ == \"__main__\":\n    # gen_test_srs()\n    path = os.path.abspath(\n        os.path.join(\n            os.path.dirname(__file__),\n            '..',\n            '..',\n            'examples',\n            'onnx',\n            '1l_average',\n            'network.onnx'\n        )\n    )\n    print(ezkl.table(path))\n"
    },
    {
        "repo": "https://github.com/zkonduit/ezkl",
        "file_path": "tests/wasm.rs",
        "content": "#[cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))]\n#[cfg(test)]\nmod wasm32 {\n    use ezkl::circuit::modules::polycommit::PolyCommitChip;\n    use ezkl::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};\n    use ezkl::circuit::modules::poseidon::PoseidonChip;\n    use ezkl::circuit::modules::Module;\n    use ezkl::graph::modules::POSEIDON_LEN_GRAPH;\n    use ezkl::graph::GraphCircuit;\n    use ezkl::graph::{GraphSettings, GraphWitness};\n    use ezkl::pfsys;\n    use ezkl::wasm::{\n        bufferToVecOfFelt, compiledCircuitValidation, encodeVerifierCalldata, feltToBigEndian,\n        feltToFloat, feltToInt, feltToLittleEndian, genPk, genVk, genWitness, inputValidation,\n        kzgCommit, pkValidation, poseidonHash, proofValidation, prove, settingsValidation,\n        srsValidation, u8_array_to_u128_le, verify, verifyAggr, vkValidation, witnessValidation,\n    };\n    use halo2_proofs::plonk::VerifyingKey;\n    use halo2_proofs::poly::commitment::CommitmentScheme;\n    use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;\n    use halo2_proofs::poly::kzg::commitment::ParamsKZG;\n    use halo2_solidity_verifier::encode_calldata;\n    use halo2curves::bn256::Bn256;\n    use halo2curves::bn256::{Fr, G1Affine};\n    use snark_verifier::util::arithmetic::PrimeField;\n    use wasm_bindgen::JsError;\n    #[cfg(feature = \"web\")]\n    pub use wasm_bindgen_rayon::init_thread_pool;\n    use wasm_bindgen_test::*;\n\n    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);\n\n    pub const WITNESS: &[u8] = include_bytes!(\"../tests/wasm/witness.json\");\n    pub const NETWORK_COMPILED: &[u8] = include_bytes!(\"../tests/wasm/model.compiled\");\n    pub const NETWORK: &[u8] = include_bytes!(\"../tests/wasm/network.onnx\");\n    pub const INPUT: &[u8] = include_bytes!(\"../tests/wasm/input.json\");\n    pub const PROOF: &[u8] = include_bytes!(\"../tests/wasm/proof.json\");\n    pub const PROOF_AGGR: &[u8] = include_bytes!(\"../tests/wasm/proof_aggr.json\");\n    pub const SETTINGS: &[u8] = include_bytes!(\"../tests/wasm/settings.json\");\n    pub const PK: &[u8] = include_bytes!(\"../tests/wasm/pk.key\");\n    pub const VK: &[u8] = include_bytes!(\"../tests/wasm/vk.key\");\n    pub const VK_AGGR: &[u8] = include_bytes!(\"../tests/wasm/vk_aggr.key\");\n    pub const SRS: &[u8] = include_bytes!(\"../tests/wasm/kzg\");\n    pub const SRS1: &[u8] = include_bytes!(\"../tests/wasm/kzg1.srs\");\n\n    #[wasm_bindgen_test]\n    async fn can_verify_aggr() {\n        let value = verifyAggr(\n            wasm_bindgen::Clamped(PROOF_AGGR.to_vec()),\n            wasm_bindgen::Clamped(VK_AGGR.to_vec()),\n            21,\n            wasm_bindgen::Clamped(SRS1.to_vec()),\n            \"kzg\",\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        // should not fail\n        assert!(value);\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_encode_verifier_calldata() {\n        let ser_proof = wasm_bindgen::Clamped(PROOF.to_vec());\n\n        // with no vk address\n        let calldata = encodeVerifierCalldata(ser_proof.clone(), None)\n            .map_err(|_| \"failed\")\n            .unwrap();\n\n        let snark: pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&PROOF).unwrap();\n        let flattened_instances = snark.instances.into_iter().flatten();\n        let reference_calldata = encode_calldata(\n            None,\n            &snark.proof,\n            &flattened_instances.clone().collect::<Vec<_>>(),\n        );\n        assert_eq!(calldata, reference_calldata);\n        // with vk address\n        let vk_address = hex::decode(\"0000000000000000000000000000000000000000\").unwrap();\n\n        let vk_address: [u8; 20] = {\n            let mut array = [0u8; 20];\n            array.copy_from_slice(&vk_address);\n            array\n        };\n\n        let serialized = serde_json::to_vec(&vk_address).unwrap();\n\n        let calldata = encodeVerifierCalldata(ser_proof, Some(serialized))\n            .map_err(|_| \"failed\")\n            .unwrap();\n        let reference_calldata = encode_calldata(\n            Some(vk_address),\n            &snark.proof,\n            &flattened_instances.collect::<Vec<_>>(),\n        );\n        assert_eq!(calldata, reference_calldata);\n    }\n\n    #[wasm_bindgen_test]\n    fn verify_kzg_commit() {\n        // create a vector of field elements Vec<Fr> and assign it to the message variable\n        let mut message: Vec<Fr> = vec![];\n        for i in 0..32 {\n            message.push(Fr::from(i as u64));\n        }\n        let message_ser = serde_json::to_vec(&message).unwrap();\n\n        let settings: GraphSettings = serde_json::from_slice(&SETTINGS).unwrap();\n        let mut reader = std::io::BufReader::new(SRS);\n        let params: ParamsKZG<Bn256> =\n            halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader).unwrap();\n        let mut reader = std::io::BufReader::new(VK);\n        let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(\n            &mut reader,\n            halo2_proofs::SerdeFormat::RawBytes,\n            settings.clone(),\n        )\n        .unwrap();\n        let commitment_ser = kzgCommit(\n            wasm_bindgen::Clamped(message_ser),\n            wasm_bindgen::Clamped(VK.to_vec()),\n            wasm_bindgen::Clamped(SETTINGS.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n        let commitment: Vec<halo2curves::bn256::G1Affine> =\n            serde_json::from_slice(&commitment_ser[..]).unwrap();\n        let reference_commitment = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(\n            message,\n            (vk.cs().blinding_factors() + 1) as u32,\n            &params,\n        );\n\n        assert_eq!(commitment, reference_commitment);\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_field_serialization_roundtrip() {\n        for i in 0..32 {\n            let field_element = Fr::from(i);\n            let serialized = serde_json::to_vec(&field_element).unwrap();\n\n            let clamped = wasm_bindgen::Clamped(serialized);\n            let scale = 2;\n            let floating_point = feltToFloat(clamped.clone(), scale)\n                .map_err(|_| \"failed\")\n                .unwrap();\n            assert_eq!(floating_point, (i as f64) / 4.0);\n\n            let integer: i128 =\n                serde_json::from_slice(&feltToInt(clamped.clone()).map_err(|_| \"failed\").unwrap())\n                    .unwrap();\n            assert_eq!(integer, i as i128);\n\n            let hex_string = format!(\"{:?}\", field_element.clone());\n            let returned_string: String = feltToBigEndian(clamped.clone())\n                .map_err(|_| \"failed\")\n                .unwrap();\n            assert_eq!(hex_string, returned_string);\n            let repr = serde_json::to_string(&field_element).unwrap();\n            let little_endian_string: String = serde_json::from_str(&repr).unwrap();\n            let returned_string: String =\n                feltToLittleEndian(clamped).map_err(|_| \"failed\").unwrap();\n            assert_eq!(little_endian_string, returned_string);\n        }\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_buffer_to_field_elements() {\n        let string_high = String::from(\"high\");\n        let mut buffer = string_high.clone().into_bytes();\n        let clamped = wasm_bindgen::Clamped(buffer.clone());\n\n        let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| \"failed\").unwrap();\n\n        let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();\n\n        buffer.resize(16, 0);\n\n        let reference_int = u8_array_to_u128_le(buffer.try_into().unwrap());\n\n        let reference_field_element_high = PrimeField::from_u128(reference_int);\n\n        assert_eq!(field_elements[0], reference_field_element_high);\n\n        // length 16 string (divisible by 16 so doesn't need padding)\n        let string_sample = String::from(\"a sample string!\");\n        let buffer = string_sample.clone().into_bytes();\n        let clamped = wasm_bindgen::Clamped(buffer.clone());\n\n        let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| \"failed\").unwrap();\n\n        let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();\n\n        let reference_int = u8_array_to_u128_le(buffer.try_into().unwrap());\n\n        let reference_field_element_sample = PrimeField::from_u128(reference_int);\n\n        assert_eq!(field_elements[0], reference_field_element_sample);\n\n        let string_concat = string_sample + &string_high;\n\n        let buffer = string_concat.into_bytes();\n        let clamped = wasm_bindgen::Clamped(buffer.clone());\n\n        let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| \"failed\").unwrap();\n\n        let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();\n\n        assert_eq!(field_elements[0], reference_field_element_sample);\n        assert_eq!(field_elements[1], reference_field_element_high);\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_hash() {\n        let mut message: Vec<Fr> = vec![];\n        for i in 0..32 {\n            message.push(Fr::from(i as u64));\n        }\n\n        let message_ser = serde_json::to_vec(&message).unwrap();\n\n        let hash = poseidonHash(wasm_bindgen::Clamped(message_ser))\n            .map_err(|_| \"failed\")\n            .unwrap();\n        let hash: Vec<Vec<Fr>> = serde_json::from_slice(&hash[..]).unwrap();\n\n        let reference_hash =\n            PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(\n                message.clone(),\n            )\n            .map_err(|_| \"failed\")\n            .unwrap();\n\n        assert_eq!(hash, reference_hash)\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_gen_witness() {\n        let witness = genWitness(\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(INPUT.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        let witness: GraphWitness = serde_json::from_slice(&witness[..]).unwrap();\n\n        let reference_witness: GraphWitness = serde_json::from_slice(&WITNESS).unwrap();\n        // should not fail\n        assert_eq!(witness, reference_witness);\n    }\n\n    #[wasm_bindgen_test]\n    async fn gen_pk_test() {\n        let vk = genVk(\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n            true,\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        let pk = genPk(\n            wasm_bindgen::Clamped(vk),\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        assert!(pk.len() > 0);\n    }\n\n    #[wasm_bindgen_test]\n    async fn gen_vk_test() {\n        let vk = genVk(\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n            true,\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        assert!(vk.len() > 0);\n    }\n\n    #[wasm_bindgen_test]\n    async fn pk_is_valid_test() {\n        let vk = genVk(\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n            true,\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        let pk = genPk(\n            wasm_bindgen::Clamped(vk.clone()),\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        // prove\n        let proof = prove(\n            wasm_bindgen::Clamped(WITNESS.to_vec()),\n            wasm_bindgen::Clamped(pk.clone()),\n            wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        assert!(proof.len() > 0);\n\n        let value = verify(\n            wasm_bindgen::Clamped(proof.to_vec()),\n            wasm_bindgen::Clamped(vk),\n            wasm_bindgen::Clamped(SETTINGS.to_vec()),\n            wasm_bindgen::Clamped(SRS.to_vec()),\n        )\n        .map_err(|_| \"failed\")\n        .unwrap();\n\n        // should not fail\n        assert!(value);\n    }\n\n    #[wasm_bindgen_test]\n    async fn verify_validations() {\n        // Run witness validation on network (should fail)\n        let witness = witnessValidation(wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()));\n        assert!(witness.is_err());\n        // Run witness validation on witness (should pass)\n        let witness = witnessValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));\n        assert!(witness.is_ok());\n        // Run compiled circuit validation on onnx network (should fail)\n        let circuit = compiledCircuitValidation(wasm_bindgen::Clamped(NETWORK.to_vec()));\n        assert!(circuit.is_err());\n        // Run compiled circuit validation on comiled network (should pass)\n        let circuit = compiledCircuitValidation(wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()));\n        assert!(circuit.is_ok());\n        // Run input validation on witness (should fail)\n        let input = inputValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));\n        assert!(input.is_err());\n        // Run input validation on input (should pass)\n        let input = inputValidation(wasm_bindgen::Clamped(INPUT.to_vec()));\n        assert!(input.is_ok());\n        // Run proof validation on witness (should fail)\n        let proof = proofValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));\n        assert!(proof.is_err());\n        // Run proof validation on proof (should pass)\n        let proof = proofValidation(wasm_bindgen::Clamped(PROOF.to_vec()));\n        assert!(proof.is_ok());\n        // // Run vk validation on SRS (should fail)\n        // let vk = vkValidation(\n        //     wasm_bindgen::Clamped(SRS.to_vec()),\n        //     wasm_bindgen::Clamped(SETTINGS.to_vec())\n        // );\n        // assert!(vk.is_err());\n\n        // Run vk validation on vk (should pass)\n        let vk = vkValidation(\n            wasm_bindgen::Clamped(VK.to_vec()),\n            wasm_bindgen::Clamped(SETTINGS.to_vec()),\n        );\n        assert!(vk.is_ok());\n        // // Run pk validation on vk (should fail)\n        // let pk = pkValidation(\n        //     wasm_bindgen::Clamped(VK.to_vec()),\n        //     wasm_bindgen::Clamped(SETTINGS.to_vec())\n        // );\n        // assert!(pk.is_err());\n        // Run pk validation on pk (should pass)\n        let pk = pkValidation(\n            wasm_bindgen::Clamped(PK.to_vec()),\n            wasm_bindgen::Clamped(SETTINGS.to_vec()),\n        );\n\n        assert!(pk.is_ok());\n        // Run settings validation on proof (should fail)\n        let settings = settingsValidation(wasm_bindgen::Clamped(PROOF.to_vec()));\n        assert!(settings.is_err());\n        // Run settings validation on settings (should pass)\n        let settings = settingsValidation(wasm_bindgen::Clamped(SETTINGS.to_vec()));\n        assert!(settings.is_ok());\n        // // Run srs validation on vk (should fail)\n        // let srs = srsValidation(\n        //     wasm_bindgen::Clamped(VK.to_vec())\n        // );\n        // assert!(srs.is_err());\n        // Run srs validation on srs (should pass)\n        let srs = srsValidation(wasm_bindgen::Clamped(SRS.to_vec()));\n        assert!(srs.is_ok());\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "keras2circom/circom.py",
        "content": "# Ref: https://github.com/zk-ml/uchikoma/blob/main/python/uchikoma/circom.py\nfrom __future__ import annotations\n\nimport typing\n\nimport os\nfrom os import path\nimport json\nfrom dataclasses import dataclass\n\nimport re\nimport numpy as np\n\nclass SafeDict(dict):\n    def __missing__(self, key):\n        return '{' + key + '}'\n\n# template string for circom\ncircom_template_string = '''pragma circom 2.0.0;\n\n{include}\ntemplate Model() {brace_left}\n{signal}\n{component}\n{main}\n{brace_right}\n\ncomponent main = Model();\n'''\n\ntemplates: typing.Dict[str, Template] = {\n\n}\n\ndef parse_shape(shape: typing.List[int]) -> str:\n    '''parse shape to integers enclosed by []'''\n    shape_str = ''\n    for dim in shape:\n        shape_str += '[{}]'.format(dim)\n    return shape_str\n    \ndef parse_index(shape: typing.List[int]) -> str:\n    '''parse shape to indices enclosed by []'''\n    index_str = ''\n    for i in range(len(shape)):\n        index_str += '[i{}]'.format(i)\n    return index_str\n\n@dataclass\nclass Template:\n    op_name: str\n    fpath: str\n\n    args: typing.Dict[str]\n\n    input_names: typing.List[str]   = None\n    input_dims: typing.List[int]    = None\n    output_names: typing.List[str]  = None\n    output_dims: typing.List[int]   = None\n\n    def __str__(self) -> str:\n        args_str = ', '.join(self.args)\n        args_str = '(' + args_str + ')'\n        return '{:>20}{:30} {}{}{}{} \\t<-- {}'.format(\n            self.op_name, args_str,\n            self.input_names, self.input_dims,\n            self.output_names, self.output_dims,\n            self.fpath)\n\ndef file_parse(fpath):\n    '''parse circom file and register templates'''\n    with open(fpath, 'r') as f:\n        lines = f.read().split('\\n')\n\n    lines = [l for l in lines if not l.strip().startswith('//')]\n    lines = ' '.join(lines)\n\n    lines = re.sub('/\\*.*?\\*/', 'IGN', lines)\n\n    funcs = re.findall('template (\\w+) ?\\((.*?)\\) ?\\{(.*?)\\}', lines)\n    for func in funcs:\n        op_name = func[0].strip()\n        args = func[1].split(',')\n        main = func[2].strip()\n        assert op_name not in templates, \\\n            'duplicated template: {} in {} vs. {}'.format(\n                    op_name, templates[op_name].fpath, fpath)\n\n        signals = re.findall('signal (\\w+) (\\w+)(.*?);', main)\n        infos = [[] for i in range(4)]\n        for sig in signals:\n            sig_types = ['input', 'output']\n            assert sig[0] in sig_types, sig[1] + ' | ' + main\n            idx = sig_types.index(sig[0])\n            infos[idx*2+0].append(sig[1])\n\n            sig_dim = sig[2].count('[')\n            infos[idx*2+1].append(sig_dim)\n        templates[op_name] = Template(\n                op_name, fpath,\n                [a.strip() for a in args],\n                *infos)\n\n\ndef dir_parse(dir_path, skips=[]):\n    '''parse circom files in a directory'''\n    names = os.listdir(dir_path)\n    for name in names:\n        if name in skips:\n            continue\n\n        fpath = path.join(dir_path, name)\n        if os.path.isdir(fpath):\n            dir_parse(fpath)\n        elif os.path.isfile(fpath):\n            if fpath.endswith('.circom'):\n                file_parse(fpath)\n\n@dataclass\nclass Signal:\n    name: str\n    shape: typing.List[int]\n    value: typing.Any = None\n\n    def inject_signal(self, comp_name: str) -> str:\n        '''inject signal into the beginning of the circuit'''\n        if self.value is not None or self.name == 'out' or self.name == 'remainder':\n            return 'signal input {}_{}{};\\n'.format(\n                    comp_name, self.name, parse_shape(self.shape))\n        return ''\n    \n    def inject_main(self, comp_name: str, prev_comp_name: str = None, prev_signal: Signal = None) -> str:\n        '''inject signal into main'''\n        inject_str = ''\n        if self.value is not None or self.name == 'out' or self.name == 'remainder':\n            if comp_name.endswith('softmax') and self.name == 'out':\n                inject_str += '{}.out <== {}_out[0];\\n'.format(\n                            comp_name, comp_name)\n                return inject_str\n            for i in range(len(self.shape)):\n                inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, self.shape[i], i)\n            if 'activation' in comp_name or 're_lu' in comp_name:\n                inject_str += '{}{}{}.{} <== {}_{}{};\\n'.format(' '*(i+1)*4,\n                            comp_name, parse_index(self.shape), self.name,\n                            comp_name, self.name, parse_index(self.shape))\n            else:\n                inject_str += '{}{}.{}{} <== {}_{}{};\\n'.format(' '*(i+1)*4,\n                            comp_name, self.name, parse_index(self.shape),\n                            comp_name, self.name, parse_index(self.shape))\n            inject_str += '}'*len(self.shape)+'\\n'\n            return inject_str\n        \n        if self.shape != prev_signal.shape:\n            raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))\n            \n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, self.shape[i], i)\n        \n        if 'activation' in comp_name or 're_lu' in comp_name:\n            inject_str += '{}{}{}.{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        comp_name, parse_index(self.shape), self.name,\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        elif 'activation' in prev_comp_name or 're_lu' in prev_comp_name:\n            inject_str += '{}{}.{}{} <== {}{}.{};\\n'.format(' '*(i+1)*4,\n                        comp_name, self.name, parse_index(self.shape),\n                        prev_comp_name, parse_index(self.shape), prev_signal.name)\n        else:\n            inject_str += '{}{}.{}{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        comp_name, self.name, parse_index(self.shape),\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n    \n    def inject_input_signal(self) -> str:\n        '''inject the circuit input signal'''\n        if self.value is not None:\n            raise ValueError('input signal should not have value')\n        return 'signal input in{};\\n'.format(parse_shape(self.shape))\n    \n    def inject_output_signal(self) -> str:\n        '''inject the circuit output signal'''\n        if self.value is not None:\n            raise ValueError('output signal should not have value')\n        return 'signal output out{};\\n'.format(parse_shape(self.shape)) \n    \n    def inject_input_main(self, comp_name: str) -> str:\n        '''inject the circuit input signal into main'''\n        if self.value is not None:\n            raise ValueError('input signal should not have value')\n        inject_str = ''\n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                        ' '*i*4, i, i, self.shape[i], i)\n        inject_str += '{}{}.{}{} <== in{};\\n'.format(' '*(i+1)*4,\n                    comp_name, self.name, parse_index(self.shape),\n                    parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n    \n    def inject_output_main(self, prev_comp_name: str, prev_signal: Signal) -> str:\n        '''inject the circuit output signal into main'''        \n        if self.value is not None:\n            raise ValueError('output signal should not have value')\n        if self.shape != prev_signal.shape:\n            raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))\n        \n        if 'softmax' in prev_comp_name:\n            return 'out[0] <== {}.out;\\n'.format(prev_comp_name)\n        \n        inject_str = ''\n\n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                        ' '*i*4, i, i, self.shape[i], i)\n        \n        if 're_lu' in prev_comp_name:\n            inject_str += '{}out{} <== {}{}.{};\\n'.format(' '*(i+1)*4,\n                        parse_index(self.shape),\n                        prev_comp_name, parse_index(self.shape), prev_signal.name)\n        else:\n            inject_str += '{}out{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        parse_index(self.shape),\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n\n@dataclass\nclass Component:\n    name: str\n    template: Template\n    inputs: typing.List[Signal]\n    outputs: typing.List[Signal]\n    # optional args\n    args: typing.Dict[str, typing.Any] = None\n\n    def inject_include(self) -> str:\n        '''include the component template'''\n        return 'include \"../{}\";\\n'.format(self.template.fpath)\n    \n    def inject_signal(self, prev_comp: Component = None, last_comp: bool = False) -> str:\n        '''inject the component signals'''\n        inject_str = ''\n        for signal in self.inputs:\n            if signal.name == 'out' or signal.name == 'remainder':\n                inject_str += signal.inject_signal(self.name)\n                if last_comp is True and signal.name == 'out':\n                    inject_str += signal.inject_output_signal()\n            elif signal.value is None and prev_comp is None:\n                inject_str += signal.inject_input_signal()\n            elif signal.value is not None:\n                inject_str += signal.inject_signal(self.name)\n        return inject_str\n    \n    def inject_component(self) -> str:\n        '''inject the component declaration'''\n        if self.template.op_name == 'ReLU':\n            for signal in self.inputs:\n                if signal.name == 'out':\n                    output_signal = signal\n                    break\n            inject_str = 'component {}{};\\n'.format(self.name, parse_shape(output_signal.shape))\n            for i in range(len(output_signal.shape)):\n                inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, output_signal.shape[i], i)\n            inject_str += '{}{}{} = ReLU();\\n'.format(' '*(i+1)*4,\n                        self.name, parse_index(output_signal.shape))\n            inject_str += '}'*len(output_signal.shape)+'\\n'\n            return inject_str\n\n        return 'component {} = {}({});\\n'.format(\n            self.name, self.template.op_name, self.parse_args(self.template.args, self.args))\n    \n    def inject_main(self, prev_comp: Component = None, last_comp: bool = False) -> str:\n        '''inject the component main'''\n        inject_str = ''\n        for signal in self.inputs:\n            if signal.value is not None or signal.name == 'out' or signal.name == 'remainder':\n                inject_str += signal.inject_main(self.name)\n            elif prev_comp is None:\n                inject_str += signal.inject_input_main(self.name)\n            else:\n                for sig in prev_comp.inputs:\n                    if sig.name == 'out':\n                        output_signal = sig\n                        break\n                if output_signal is None:\n                    output_signal = prev_comp.outputs[0]\n                inject_str += signal.inject_main(self.name, prev_comp.name, output_signal)\n                print\n        if last_comp:\n            for signal in self.inputs:\n                if signal.name == 'out':\n                    inject_str += signal.inject_output_main(self.name, signal)\n                    break\n            for signal in self.outputs:\n                inject_str += signal.inject_output_main(self.name, signal)\n        return inject_str\n\n    def to_json(self, dec: int) -> typing.Dict[str, typing.Any]:\n        '''convert the component params to json format'''\n        json_dict = {}\n        for signal in self.inputs:\n            if signal.value is not None:\n                if signal.name == 'bias' or signal.name == 'b':\n                    scaling = float(10**(2*dec))\n                else:\n                    scaling = float(10**dec)\n                value = [str(int(v*scaling)) for v in signal.value.flatten().tolist()]\n                # reshape the value to match the circom shape\n                if len(signal.shape) > 1:\n                    value = np.array(value).reshape(signal.shape).tolist()\n                json_dict.update({f'{self.name}_{signal.name}': value})\n        return json_dict\n    \n    @staticmethod\n    def parse_args(template_args: typing.List[str], args: typing.Dict[str, typing.Any]) -> str:\n        '''parse the args to a format string, ready to be injected'''\n        args_str = '{'+'}, {'.join(template_args)+'}'\n        return args_str.format(**args)\n\n@dataclass\nclass Circuit:\n    components: typing.List[Component]\n\n    def __init__(self):\n        self.components = []\n\n    def add_component(self, component: Component):\n        self.components.append(component)\n    \n    def add_components(self, components: typing.List[Component]):\n        self.components.extend(components)\n\n    def inject_include(self) -> str:\n        '''inject the include statements'''\n        inject_str = []\n        for component in self.components:\n            inject_str.append(component.inject_include())\n        return ''.join(set(inject_str))\n\n    def inject_signal(self) -> str:\n        '''inject the signal declarations'''\n        inject_str = self.components[0].inject_signal()\n        for i in range(1, len(self.components)):\n            inject_str += self.components[i].inject_signal(self.components[i-1], i==len(self.components)-1)\n        return inject_str\n\n    def inject_component(self) -> str:\n        '''inject the component declarations'''\n        inject_str = ''\n        for component in self.components:\n            inject_str += component.inject_component()\n        return inject_str\n    \n    def inject_main(self) -> str:\n        '''inject the main template'''\n        inject_str = self.components[0].inject_main()\n        for i in range(1, len(self.components)):\n            inject_str += self.components[i].inject_main(self.components[i-1], i==len(self.components)-1)\n        return inject_str\n\n    def to_circom(self) -> str:\n        '''convert the circuit to a circom file'''\n        return circom_template_string.format(**{\n            'include': self.inject_include(),\n            'brace_left': '{',\n            'signal': self.inject_signal(),\n            'component': self.inject_component(),\n            'main': self.inject_main(),\n            'brace_right': '}',\n        })\n\n    def to_json(self, dec: int) -> str:\n        '''convert the model weights to json format'''\n        json_dict = {}\n\n        for component in self.components:\n            json_dict.update(component.to_json(dec))\n        \n        return json.dumps(json_dict)"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "keras2circom/model.py",
        "content": "# Read keras model into list of parameters like op, input, output, weight, bias\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nimport typing\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.layers import Layer as KerasLayer\nimport numpy as np\n\nsupported_ops = [\n    'Activation',\n    'AveragePooling2D',\n    'BatchNormalization',\n    'Conv2D',\n    'Dense',\n    'Flatten',\n    'GlobalAveragePooling2D',\n    'GlobalMaxPooling2D',\n    'MaxPooling2D',\n    'ReLU',\n    'Softmax',\n]\n\nskip_ops = [\n    'Dropout',\n    'InputLayer',\n]\n\n\n# read each layer in a model and convert it to a class called Layer\n@dataclass\nclass Layer:\n    ''' A single layer in a Keras model. '''\n    op: str\n    name: str\n    input: typing.List[int]\n    output: typing.List[int]\n    config: typing.Dict[str, typing.Any]\n    weights: typing.List[np.ndarray]\n\n    def __init__(self, layer: KerasLayer):\n        self.op = layer.__class__.__name__\n        self.name = layer.name\n        self.input = layer.input_shape[1:]\n        self.output = layer.output_shape[1:]\n        self.config = layer.get_config()\n        self.weights = layer.get_weights()\n\nclass Model:\n    layers: typing.List[Layer]\n\n    def __init__(self, filename: str, raw: bool = False):\n        ''' Load a Keras model from a file. '''\n        model = load_model(filename)\n        \n        self.layers = [Layer(layer) for layer in model.layers if self._for_transpilation(layer.__class__.__name__)]\n    \n    @staticmethod\n    def _for_transpilation(op: str) -> bool:\n        if op in skip_ops:\n            return False\n        if op in supported_ops:\n            return True\n        raise NotImplementedError(f'Unsupported op: {op}')"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "keras2circom/script.py",
        "content": "from .circom import Circuit, Component\n\n# template string for circuit.py\npython_template_string = '''\"\"\" Make an interger-only circuit of the corresponding CIRCOM circuit.\n\nUsage:\n    circuit.py <circuit.json> <input.json> [-o <output>]\n    circuit.py (-h | --help)\n\nOptions:\n    -h --help                               Show this screen.\n    -o <output> --output=<output>           Output directory [default: output].\n\n\"\"\"\n\nfrom docopt import docopt\nimport json\n\ntry:\n    from keras2circom.util import *\nexcept:\n    import sys\n    import os\n    # add parent directory to sys.path\n    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n    from keras2circom.util import *\n\ndef inference(input, circuit):\n    out = input['in']\n    output = {brackets}\n    \n{components}\n    return out, output\n\n\ndef main():\n    \"\"\" Main entry point of the app \"\"\"\n    args = docopt(__doc__)\n    \n    # parse input.json\n    with open(args['<input.json>']) as f:\n        input = json.load(f)\n    \n    # parse circuit.json\n    with open(args['<circuit.json>']) as f:\n        circuit = json.load(f)\n\n    out, output = inference(input, circuit)\n\n    # write output.json\n    with open(args['--output'] + '/output.json', 'w') as f:\n        json.dump(output, f)\n\nif __name__ == \"__main__\":\n    \"\"\" This is executed when run from the command line \"\"\"\n    main()\n'''\n\n\ndef to_py(circuit: Circuit, dec: int) -> str:\n    comp_str = \"\"\n\n    for component in circuit.components:\n        comp_str += transpile_component(component, dec)\n\n    return python_template_string.format(\n        brackets=\"{}\",\n        components=comp_str,\n    )\n\ndef transpile_component(component: Component, dec: int) -> str:\n    comp_str = \"\"\n    if component.template.op_name == \"AveragePooling2D\":\n        comp_str += \"    out, remainder = AveragePooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            poolSize=component.args[\"poolSize\"],\n            strides=component.args[\"strides\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"BatchNormalization2D\":\n        comp_str += \"    out, remainder = BatchNormalizationInt({nRows}, {nCols}, {nChannels}, {n}, {input}, {a}, {b})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            a=\"circuit['{name}_a']\".format(name=component.name),\n            b=\"circuit['{name}_b']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Conv1D\":\n        comp_str += \"    out, remainder = Conv1DInt({nInputs}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nInputs=component.args[\"nInputs\"],\n            nChannels=component.args[\"nChannels\"],\n            nFilters=component.args[\"nFilters\"],\n            kernelSize=component.args[\"kernelSize\"],\n            strides=component.args[\"strides\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Conv2D\":\n        comp_str += \"    out, remainder = Conv2DInt({nRows}, {nCols}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            nFilters=component.args[\"nFilters\"],\n            kernelSize=component.args[\"kernelSize\"],\n            strides=component.args[\"strides\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Dense\":\n        comp_str += \"    out, remainder = DenseInt({nInputs}, {nOutputs}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nInputs=component.args[\"nInputs\"],\n            nOutputs=component.args[\"nOutputs\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"GlobalAveragePooling2D\":\n        comp_str += \"    out, remainder = GlobalAveragePooling2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"GlobalMaxPooling2D\":\n        comp_str += \"    out = GlobalMaxPooling2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"MaxPooling2D\":\n        comp_str += \"    out = MaxPooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            poolSize=component.args[\"poolSize\"],\n            strides=component.args[\"strides\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Flatten2D\":\n        comp_str += \"    out = Flatten2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"ReLU\":\n        nRows, nCols, nChannels = component.inputs[0].shape\n        comp_str += \"    out = ReLUInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=nRows,\n            nCols=nCols,\n            nChannels=nChannels,\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"ArgMax\":\n        comp_str += \"    out = ArgMaxInt(out)\\n\"\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    else:\n        raise ValueError(\"Unknown component type: {}\".format(component.template.op_name))"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "keras2circom/transpiler.py",
        "content": "from .circom import *\nfrom .model import *\nfrom .script import *\n\nimport os\n\ndef transpile(filename: str, output_dir: str = 'output', raw: bool = False, dec: int = 18) -> Circuit:\n    ''' Transpile a Keras model to a CIRCOM circuit.'''\n    \n    model = Model(filename, raw)\n\n    circuit = Circuit()\n    for layer in model.layers[:-1]:\n        circuit.add_components(transpile_layer(layer, dec))\n    \n    circuit.add_components(transpile_layer(model.layers[-1], dec, True))\n\n    if raw:\n        if circuit.components[-1].template.op_name == 'ArgMax':\n            circuit.components.pop()\n    # create output directory if it doesn't exist\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    \n    with open(output_dir + '/circuit.circom', 'w') as f:\n        f.write(circuit.to_circom())\n    \n    with open(output_dir + '/circuit.json', 'w') as f:\n        f.write(circuit.to_json(int(dec)))\n    \n    with open(output_dir + '/circuit.py', 'w') as f:\n        f.write(to_py(circuit, int(dec)))\n    \n    return circuit\n\ndef transpile_layer(layer: Layer, dec: int = 18, last: bool = False) -> typing.List[Component]:\n    ''' Transpile a Keras layer to CIRCOM component(s).'''\n    if layer.op == 'Activation':\n        if layer.config['activation'] == 'softmax':\n            if last:\n                return transpile_ArgMax(layer)\n            raise ValueError('Softmax must be the last layer')\n        if layer.config['activation'] == 'relu':\n            return transpile_ReLU(layer)\n        if layer.config['activation'] == 'linear':\n            return []\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} not implemented')\n    \n    if layer.op == 'Softmax':\n        if last:\n            return transpile_ArgMax(layer)\n        raise ValueError('Softmax must be the last layer')\n    \n    if layer.op == 'ReLU':\n        return transpile_ReLU(layer)\n\n    if layer.op == 'AveragePooling2D':\n        return transpile_AveragePooling2D(layer)\n    \n    if layer.op == 'BatchNormalization':\n        return transpile_BatchNormalization2D(layer, dec)\n\n    if layer.op == 'Conv2D':\n        return transpile_Conv2D(layer, dec)\n    \n    if layer.op == 'Dense':\n        return transpile_Dense(layer, dec, last)\n        \n    if layer.op == 'Flatten':\n        return transpile_Flatten2D(layer)\n\n    if layer.op == 'GlobalAveragePooling2D':\n        return transpile_GlobalAveragePooling2D(layer)\n        \n    if layer.op == 'GlobalMaxPooling2D':\n        return transpile_GlobalMaxPooling2D(layer)\n    \n    if layer.op == 'MaxPooling2D':\n        return transpile_MaxPooling2D(layer)\n    \n    raise NotImplementedError(f'Layer {layer.op} is not supported yet.')\n\ndef transpile_ArgMax(layer: Layer) -> typing.List[Component]:\n    return [Component(layer.name, templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})]\n\ndef transpile_ReLU(layer: Layer) -> typing.List[Component]:\n    return [Component(layer.name, templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])]\n\ndef transpile_AveragePooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['pool_size'][0] != layer.config['pool_size'][1]:\n        raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    \n    return [Component(layer.name, templates['AveragePooling2D'], [Signal('in', layer.input), Signal('out', layer.output), Signal('remainder', layer.output)],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'poolSize': layer.config['pool_size'][0],\n        'strides': layer.config['strides'][0],\n        })]\n\ndef transpile_BatchNormalization2D(layer: Layer, dec: int) -> typing.List[Component]:\n    if layer.input.__len__() != 3:\n        raise NotImplementedError('Only 2D inputs are supported')\n    if layer.config['axis'][0] != 3:\n        raise NotImplementedError('Only axis=3 is supported')\n    if layer.config['center'] != True:\n        raise NotImplementedError('Only center=True is supported')\n    if layer.config['scale'] != True:\n        raise NotImplementedError('Only scale=True is supported')\n    \n    gamma = layer.weights[0]\n    beta = layer.weights[1]\n    moving_mean = layer.weights[2]\n    moving_var = layer.weights[3]\n    epsilon = layer.config['epsilon']\n\n    a = gamma/(moving_var+epsilon)**.5\n    b = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n    \n    return [Component(layer.name, templates['BatchNormalization2D'], [\n        Signal('in', layer.input),\n        Signal('a', a.shape, a),\n        Signal('b', b.shape, b),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'n': '10**'+dec,\n        })]\n\ndef transpile_Conv2D(layer: Layer, dec: int) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    if layer.config['kernel_size'][0] != layer.config['kernel_size'][1]:\n        raise NotImplementedError('Only kernel_size[0] == kernel_size[1] is supported')\n    if layer.config['dilation_rate'][0] != 1:\n        raise NotImplementedError('Only dilation_rate[0] == 1 is supported')\n    if layer.config['dilation_rate'][1] != 1:\n        raise NotImplementedError('Only dilation_rate[1] == 1 is supported')\n    if layer.config['groups'] != 1:\n        raise NotImplementedError('Only groups == 1 is supported')\n    if layer.config['activation'] not in ['linear', 'relu']:\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} is not supported')\n    \n    if layer.config['use_bias'] == False:\n        layer.weights.append(np.zeros(layer.weights[0].shape[-1]))\n\n    conv = Component(layer.name, templates['Conv2D'], [\n        Signal('in', layer.input),\n        Signal('weights', layer.weights[0].shape, layer.weights[0]),\n        Signal('bias', layer.weights[1].shape, layer.weights[1]),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'nFilters': layer.config['filters'],\n        'kernelSize': layer.config['kernel_size'][0],\n        'strides': layer.config['strides'][0],\n        'n': '10**'+dec,\n        })\n    \n    if layer.config['activation'] == 'relu':\n        activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])\n        return [conv, activation]\n    \n    return [conv]\n\ndef transpile_Dense(layer: Layer, dec: int, last: bool = False) -> typing.List[Component]:\n    if not last and layer.config['activation'] == 'softmax':\n        raise NotImplementedError('Softmax is only supported as last layer')\n    if layer.config['activation'] not in ['linear', 'relu', 'softmax']:\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} is not supported')\n    if layer.config['use_bias'] == False:\n        layer.weights.append(np.zeros(layer.weights[0].shape[-1]))\n    \n    dense = Component(layer.name, templates['Dense'], [\n        Signal('in', layer.input),\n        Signal('weights', layer.weights[0].shape, layer.weights[0]),\n        Signal('bias', layer.weights[1].shape, layer.weights[1]),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nInputs': layer.input[0],\n        'nOutputs': layer.output[0],\n        'n': '10**'+dec,\n        })\n    \n    if layer.config['activation'] == 'relu':\n        activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])\n        return [dense, activation]\n    \n    if layer.config['activation'] == 'softmax':\n        activation = Component(layer.name+'_softmax', templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})\n        return [dense, activation]\n    \n    return [dense]\n\ndef transpile_Flatten2D(layer: Layer) -> typing.List[Component]:\n    if layer.input.__len__() != 3:\n        raise NotImplementedError('Only 2D inputs are supported')\n    \n    return [Component(layer.name, templates['Flatten2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_GlobalAveragePooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['keepdims']:\n        raise NotImplementedError('Only keepdims=False is supported')\n\n    return [Component(layer.name, templates['GlobalAveragePooling2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_GlobalMaxPooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['keepdims']:\n        raise NotImplementedError('Only keepdims=False is supported')\n\n    return [Component(layer.name, templates['GlobalMaxPooling2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_MaxPooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['pool_size'][0] != layer.config['pool_size'][1]:\n        raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    \n    return [Component(layer.name, templates['MaxPooling2D'], [Signal('in', layer.input), Signal('out', layer.output)], [],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'poolSize': layer.config['pool_size'][0],\n        'strides': layer.config['strides'][0],\n        })]\n"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "keras2circom/util.py",
        "content": "# assume all inputs are strings\ndef AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\n    out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n    remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n    for i in range((nRows-poolSize)//strides + 1):\n        for j in range((nCols-poolSize)//strides + 1):\n            for k in range(nChannels):\n                for x in range(poolSize):\n                    for y in range(poolSize):\n                        out[i][j][k] += int(input[i*strides+x][j*strides+y][k])\n                remainder[i][j][k] = str(out[i][j][k] % poolSize**2)\n                out[i][j][k] = str(out[i][j][k] // poolSize**2)\n    return out, remainder\n\ndef BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\n    out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n    remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n    for i in range(nRows):\n        for j in range(nCols):\n            for k in range(nChannels):\n                out[i][j][k] = int(X_in[i][j][k])*int(a_in[k]) + int(b_in[k])\n                remainder[i][j][k] = str(out[i][j][k] % n)\n                out[i][j][k] = str(out[i][j][k] // n)\n    return out, remainder\n\ndef Conv1DInt(nInputs, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n    out = [[0 for _ in range(nFilters)] for j in range((nInputs - kernelSize)//strides + 1)]\n    remainder = [[None for _ in range(nFilters)] for _ in range((nInputs - kernelSize)//strides + 1)]\n    for i in range((nInputs - kernelSize)//strides + 1):\n        for j in range(nFilters):\n            for k in range(kernelSize):\n                for l in range(nChannels):\n                    out[i][j] += int(input[i*strides + k][l])*int(weights[k][l][j])\n            out[i][j] += int(bias[j])\n            remainder[i][j] = str(out[i][j] % n)\n            out[i][j] = str(out[i][j] // n)\n    return out, remainder\n\ndef Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n    out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n    remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n    for i in range((nRows - kernelSize)//strides + 1):\n        for j in range((nCols - kernelSize)//strides + 1):\n            for m in range(nFilters):\n                for k in range(nChannels):\n                    for x in range(kernelSize):\n                        for y in range(kernelSize):\n                            out[i][j][m] += int(input[i*strides+x][j*strides+y][k])*int(weights[x][y][k][m])\n                out[i][j][m] += int(bias[m])\n                remainder[i][j][m] = str(out[i][j][m] % n)\n                out[i][j][m] = str(out[i][j][m] // n)\n    return out, remainder\n\ndef DenseInt(nInputs, nOutputs, n, input, weights, bias):\n    out = [0 for _ in range(nOutputs)]\n    remainder = [None for _ in range(nOutputs)]\n    for j in range(nOutputs):\n        for i in range(nInputs):\n            out[j] += int(input[i])*int(weights[i][j])\n        out[j] += int(bias[j])\n        remainder[j] = str(out[j] % n)\n        out[j] = str(out[j] // n)\n    return out, remainder\n\ndef GlobalAveragePooling2DInt(nRows, nCols, nChannels, input):\n    out = [0 for _ in range(nChannels)]\n    remainder = [None for _ in range(nChannels)]\n    for k in range(nChannels):\n        for i in range(nRows):\n            for j in range(nCols):\n                out[k] += int(input[i][j][k])\n        remainder[k] = str(out[k] % (nRows * nCols))\n        out[k] = str(out[k] // (nRows * nCols))\n    return out, remainder\n\ndef GlobalMaxPooling2DInt(nRows, nCols, nChannels, input):\n    out = [max(int(input[i][j][k]) for i in range(nRows) for j in range(nCols)) for k in range(nChannels)]\n    return out\n\ndef MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n    out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\n    return out\n\ndef Flatten2DInt(nRows, nCols, nChannels, input):\n    out = [str(int(input[i][j][k])) for i in range(nRows) for j in range(nCols) for k in range(nChannels)]\n    return out\n\ndef ReLUInt(nRows, nCols, nChannels, input):\n    out = [[[str(max(int(input[i][j][k]), 0)) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n    return out\n\ndef ArgMaxInt(input):\n    return [input.index(str(max(int(input[i]) for i in range(len(input)))))]"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "main.py",
        "content": "\"\"\" Transpile a Keras model to a CIRCOM circuit.\n\nUsage:\n    main.py <model.h5> [-o <output>] [--raw] [-d <decimals>]\n    main.py (-h | --help)\n\nOptions:\n    -h --help                               Show this screen.\n    -o <output> --output=<output>           Output directory [default: output].\n    --raw                                   Output raw model outputs instead of the argmax of outputs [default: False].\n    -d <decimals> --decimals=<decimals>     Number of decimals for model precision [default: 18].\n\n\"\"\"\nfrom docopt import docopt\n\nfrom keras2circom import circom, transpiler\n\ndef main():\n    \"\"\" Main entry point of the app \"\"\"\n    args = docopt(__doc__)\n    circom.dir_parse('node_modules/circomlib-ml/circuits/', skips=['util.circom', 'circomlib-matrix', 'circomlib', 'crypto'])\n    transpiler.transpile(args['<model.h5>'], args['--output'], args['--raw'], args['--decimals'])\n\nif __name__ == \"__main__\":\n    \"\"\" This is executed when run from the command line \"\"\"\n    main()"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "models/model.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# list of supported layers\\n\",\n    \"from tensorflow.keras.layers import (\\n\",\n    \"    Input,\\n\",\n    \"    Activation,\\n\",\n    \"    AveragePooling2D,\\n\",\n    \"    BatchNormalization,\\n\",\n    \"    Conv2D,\\n\",\n    \"    Dense,\\n\",\n    \"    Dropout,\\n\",\n    \"    Flatten,\\n\",\n    \"    GlobalAveragePooling2D,\\n\",\n    \"    GlobalMaxPooling2D,\\n\",\n    \"    MaxPooling2D,\\n\",\n    \"    ReLU,\\n\",\n    \"    Softmax,\\n\",\n    \"    )\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"from tensorflow.keras.datasets import mnist\\n\",\n    \"from tensorflow.keras.utils import to_categorical\\n\",\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import tensorflow as tf\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# load MNIST dataset\\n\",\n    \"(X_train, y_train), (X_test, y_test) = mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# convert y_train and y_test to one-hot encoding\\n\",\n    \"y_train = to_categorical(y_train)\\n\",\n    \"y_test = to_categorical(y_test)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# reshape X_train and X_test to 4D tensor\\n\",\n    \"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\\n\",\n    \"X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\\n\",\n    \"\\n\",\n    \"#normalizing\\n\",\n    \"X_train = X_train.astype('float32')\\n\",\n    \"X_test = X_test.astype('float32')\\n\",\n    \"X_train /= 255.0\\n\",\n    \"X_test /= 255.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(28,28,1))\\n\",\n    \"out = Conv2D(4, 3, use_bias=False)(inputs)\\n\",\n    \"out = BatchNormalization()(out)\\n\",\n    \"out = Activation('relu')(out)\\n\",\n    \"out = MaxPooling2D()(out)\\n\",\n    \"out = Conv2D(8, 3, use_bias=True, strides=2)(out)\\n\",\n    \"out = ReLU()(out)\\n\",\n    \"out = AveragePooling2D()(out)\\n\",\n    \"out = Flatten()(out)\\n\",\n    \"# out = Dropout(0.5)(out)\\n\",\n    \"out = Dense(10, activation=\\\"softmax\\\")(out)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 28, 28, 1)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d (Conv2D)             (None, 26, 26, 4)         36        \\n\",\n      \"                                                                 \\n\",\n      \" batch_normalization (BatchN  (None, 26, 26, 4)        16        \\n\",\n      \" ormalization)                                                   \\n\",\n      \"                                                                 \\n\",\n      \" activation (Activation)     (None, 26, 26, 4)         0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d (MaxPooling2D  (None, 13, 13, 4)        0         \\n\",\n      \" )                                                               \\n\",\n      \"                                                                 \\n\",\n      \" conv2d_1 (Conv2D)           (None, 6, 6, 8)           296       \\n\",\n      \"                                                                 \\n\",\n      \" re_lu (ReLU)                (None, 6, 6, 8)           0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d (AverageP  (None, 3, 3, 8)          0         \\n\",\n      \" ooling2D)                                                       \\n\",\n      \"                                                                 \\n\",\n      \" flatten (Flatten)           (None, 72)                0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 10)                730       \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 1,078\\n\",\n      \"Trainable params: 1,070\\n\",\n      \"Non-trainable params: 8\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.compile(\\n\",\n    \"    loss='categorical_crossentropy',\\n\",\n    \"    optimizer='adam',\\n\",\n    \"    metrics=['acc']\\n\",\n    \"    )\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/15\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-11-26 21:47:52.776729: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.5203 - acc: 0.8386 - val_loss: 0.2099 - val_acc: 0.9363\\n\",\n      \"Epoch 2/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1926 - acc: 0.9419 - val_loss: 0.1497 - val_acc: 0.9543\\n\",\n      \"Epoch 3/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1551 - acc: 0.9522 - val_loss: 0.1263 - val_acc: 0.9591\\n\",\n      \"Epoch 4/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1361 - acc: 0.9580 - val_loss: 0.1139 - val_acc: 0.9628\\n\",\n      \"Epoch 5/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1253 - acc: 0.9617 - val_loss: 0.1031 - val_acc: 0.9679\\n\",\n      \"Epoch 6/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1168 - acc: 0.9636 - val_loss: 0.0976 - val_acc: 0.9697\\n\",\n      \"Epoch 7/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1113 - acc: 0.9650 - val_loss: 0.0923 - val_acc: 0.9711\\n\",\n      \"Epoch 8/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1072 - acc: 0.9673 - val_loss: 0.0884 - val_acc: 0.9732\\n\",\n      \"Epoch 9/15\\n\",\n      \"1875/1875 [==============================] - 12s 7ms/step - loss: 0.1026 - acc: 0.9683 - val_loss: 0.0879 - val_acc: 0.9725\\n\",\n      \"Epoch 10/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.0999 - acc: 0.9691 - val_loss: 0.0928 - val_acc: 0.9719\\n\",\n      \"Epoch 11/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0968 - acc: 0.9702 - val_loss: 0.0954 - val_acc: 0.9699\\n\",\n      \"Epoch 12/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0945 - acc: 0.9706 - val_loss: 0.0841 - val_acc: 0.9740\\n\",\n      \"Epoch 13/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0926 - acc: 0.9718 - val_loss: 0.0826 - val_acc: 0.9748\\n\",\n      \"Epoch 14/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0893 - acc: 0.9723 - val_loss: 0.0803 - val_acc: 0.9751\\n\",\n      \"Epoch 15/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0892 - acc: 0.9723 - val_loss: 0.0767 - val_acc: 0.9757\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x177842d60>\"\n      ]\n     },\n     \"execution_count\": 8,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.save('model.h5')\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  },\n  \"orig_nbformat\": 4,\n  \"vscode\": {\n   \"interpreter\": {\n    \"hash\": \"71414dc221f26c27f268040756e42b4f7499507456a67f7434828e3314a20678\"\n   }\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "test/accuracy.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!cd .. && python main.py models/model.h5\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import sys\\n\",\n    \"import os\\n\",\n    \"# add parent directory to sys.path\\n\",\n    \"sys.path.append(os.path.dirname((os.getcwd())))\\n\",\n    \"from output.circuit import inference\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open('../output/circuit.json') as f:\\n\",\n    \"    circuit = json.load(f)\\n\",\n    \"\\n\",\n    \"with open('y_test.json') as f:\\n\",\n    \"    y_test = json.load(f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"#0: 100.00%\\n\",\n      \"#1: 100.00%\\n\",\n      \"#2: 100.00%\\n\",\n      \"#3: 100.00%\\n\",\n      \"#4: 100.00%\\n\",\n      \"#5: 100.00%\\n\",\n      \"#6: 100.00%\\n\",\n      \"#7: 100.00%\\n\",\n      \"#8: 100.00%\\n\",\n      \"#9: 100.00%\\n\",\n      \"#10: 100.00%\\n\",\n      \"#11: 100.00%\\n\",\n      \"#12: 100.00%\\n\",\n      \"#13: 100.00%\\n\",\n      \"#14: 100.00%\\n\",\n      \"#15: 100.00%\\n\",\n      \"#16: 100.00%\\n\",\n      \"#17: 100.00%\\n\",\n      \"#18: 94.74%\\n\",\n      \"#19: 95.00%\\n\",\n      \"#20: 95.24%\\n\",\n      \"#21: 95.45%\\n\",\n      \"#22: 95.65%\\n\",\n      \"#23: 95.83%\\n\",\n      \"#24: 96.00%\\n\",\n      \"#25: 96.15%\\n\",\n      \"#26: 96.30%\\n\",\n      \"#27: 96.43%\\n\",\n      \"#28: 96.55%\\n\",\n      \"#29: 96.67%\\n\",\n      \"#30: 96.77%\\n\",\n      \"#31: 96.88%\\n\",\n      \"#32: 96.97%\\n\",\n      \"#33: 97.06%\\n\",\n      \"#34: 97.14%\\n\",\n      \"#35: 97.22%\\n\",\n      \"#36: 97.30%\\n\",\n      \"#37: 97.37%\\n\",\n      \"#38: 97.44%\\n\",\n      \"#39: 97.50%\\n\",\n      \"#40: 97.56%\\n\",\n      \"#41: 97.62%\\n\",\n      \"#42: 97.67%\\n\",\n      \"#43: 97.73%\\n\",\n      \"#44: 97.78%\\n\",\n      \"#45: 97.83%\\n\",\n      \"#46: 97.87%\\n\",\n      \"#47: 97.92%\\n\",\n      \"#48: 97.96%\\n\",\n      \"#49: 98.00%\\n\",\n      \"#50: 98.04%\\n\",\n      \"#51: 98.08%\\n\",\n      \"#52: 98.11%\\n\",\n      \"#53: 98.15%\\n\",\n      \"#54: 98.18%\\n\",\n      \"#55: 98.21%\\n\",\n      \"#56: 98.25%\\n\",\n      \"#57: 98.28%\\n\",\n      \"#58: 98.31%\\n\",\n      \"#59: 98.33%\\n\",\n      \"#60: 98.36%\\n\",\n      \"#61: 98.39%\\n\",\n      \"#62: 98.41%\\n\",\n      \"#63: 98.44%\\n\",\n      \"#64: 98.46%\\n\",\n      \"#65: 98.48%\\n\",\n      \"#66: 98.51%\\n\",\n      \"#67: 98.53%\\n\",\n      \"#68: 98.55%\\n\",\n      \"#69: 98.57%\\n\",\n      \"#70: 98.59%\\n\",\n      \"#71: 98.61%\\n\",\n      \"#72: 98.63%\\n\",\n      \"#73: 98.65%\\n\",\n      \"#74: 98.67%\\n\",\n      \"#75: 98.68%\\n\",\n      \"#76: 98.70%\\n\",\n      \"#77: 98.72%\\n\",\n      \"#78: 98.73%\\n\",\n      \"#79: 98.75%\\n\",\n      \"#80: 98.77%\\n\",\n      \"#81: 98.78%\\n\",\n      \"#82: 98.80%\\n\",\n      \"#83: 98.81%\\n\",\n      \"#84: 98.82%\\n\",\n      \"#85: 98.84%\\n\",\n      \"#86: 98.85%\\n\",\n      \"#87: 98.86%\\n\",\n      \"#88: 98.88%\\n\",\n      \"#89: 98.89%\\n\",\n      \"#90: 98.90%\\n\",\n      \"#91: 98.91%\\n\",\n      \"#92: 98.92%\\n\",\n      \"#93: 98.94%\\n\",\n      \"#94: 98.95%\\n\",\n      \"#95: 98.96%\\n\",\n      \"#96: 98.97%\\n\",\n      \"#97: 98.98%\\n\",\n      \"#98: 98.99%\\n\",\n      \"#99: 99.00%\\n\",\n      \"#100: 99.01%\\n\",\n      \"#101: 99.02%\\n\",\n      \"#102: 99.03%\\n\",\n      \"#103: 99.04%\\n\",\n      \"#104: 99.05%\\n\",\n      \"#105: 99.06%\\n\",\n      \"#106: 99.07%\\n\",\n      \"#107: 99.07%\\n\",\n      \"#108: 99.08%\\n\",\n      \"#109: 99.09%\\n\",\n      \"#110: 99.10%\\n\",\n      \"#111: 99.11%\\n\",\n      \"#112: 99.12%\\n\",\n      \"#113: 99.12%\\n\",\n      \"#114: 99.13%\\n\",\n      \"#115: 99.14%\\n\",\n      \"#116: 99.15%\\n\",\n      \"#117: 99.15%\\n\",\n      \"#118: 99.16%\\n\",\n      \"#119: 99.17%\\n\",\n      \"#120: 99.17%\\n\",\n      \"#121: 99.18%\\n\",\n      \"#122: 99.19%\\n\",\n      \"#123: 99.19%\\n\",\n      \"#124: 99.20%\\n\",\n      \"#125: 99.21%\\n\",\n      \"#126: 99.21%\\n\",\n      \"#127: 99.22%\\n\",\n      \"#128: 99.22%\\n\",\n      \"#129: 99.23%\\n\",\n      \"#130: 99.24%\\n\",\n      \"#131: 99.24%\\n\",\n      \"#132: 99.25%\\n\",\n      \"#133: 99.25%\\n\",\n      \"#134: 99.26%\\n\",\n      \"#135: 99.26%\\n\",\n      \"#136: 99.27%\\n\",\n      \"#137: 99.28%\\n\",\n      \"#138: 99.28%\\n\",\n      \"#139: 99.29%\\n\",\n      \"#140: 99.29%\\n\",\n      \"#141: 99.30%\\n\",\n      \"#142: 99.30%\\n\",\n      \"#143: 99.31%\\n\",\n      \"#144: 99.31%\\n\",\n      \"#145: 99.32%\\n\",\n      \"#146: 99.32%\\n\",\n      \"#147: 99.32%\\n\",\n      \"#148: 99.33%\\n\",\n      \"#149: 99.33%\\n\",\n      \"#150: 99.34%\\n\",\n      \"#151: 98.68%\\n\",\n      \"#152: 98.69%\\n\",\n      \"#153: 98.70%\\n\",\n      \"#154: 98.71%\\n\",\n      \"#155: 98.72%\\n\",\n      \"#156: 98.73%\\n\",\n      \"#157: 98.73%\\n\",\n      \"#158: 98.74%\\n\",\n      \"#159: 98.75%\\n\",\n      \"#160: 98.76%\\n\",\n      \"#161: 98.77%\\n\",\n      \"#162: 98.77%\\n\",\n      \"#163: 98.78%\\n\",\n      \"#164: 98.79%\\n\",\n      \"#165: 98.80%\\n\",\n      \"#166: 98.80%\\n\",\n      \"#167: 98.81%\\n\",\n      \"#168: 98.82%\\n\",\n      \"#169: 98.82%\\n\",\n      \"#170: 98.83%\\n\",\n      \"#171: 98.84%\\n\",\n      \"#172: 98.84%\\n\",\n      \"#173: 98.85%\\n\",\n      \"#174: 98.86%\\n\",\n      \"#175: 98.86%\\n\",\n      \"#176: 98.87%\\n\",\n      \"#177: 98.88%\\n\",\n      \"#178: 98.88%\\n\",\n      \"#179: 98.89%\\n\",\n      \"#180: 98.90%\\n\",\n      \"#181: 98.90%\\n\",\n      \"#182: 98.91%\\n\",\n      \"#183: 98.91%\\n\",\n      \"#184: 98.92%\\n\",\n      \"#185: 98.92%\\n\",\n      \"#186: 98.93%\\n\",\n      \"#187: 98.94%\\n\",\n      \"#188: 98.94%\\n\",\n      \"#189: 98.95%\\n\",\n      \"#190: 98.95%\\n\",\n      \"#191: 98.96%\\n\",\n      \"#192: 98.96%\\n\",\n      \"#193: 98.97%\\n\",\n      \"#194: 98.97%\\n\",\n      \"#195: 98.98%\\n\",\n      \"#196: 98.98%\\n\",\n      \"#197: 98.99%\\n\",\n      \"#198: 98.99%\\n\",\n      \"#199: 99.00%\\n\",\n      \"#200: 99.00%\\n\",\n      \"#201: 99.01%\\n\",\n      \"#202: 99.01%\\n\",\n      \"#203: 99.02%\\n\",\n      \"#204: 99.02%\\n\",\n      \"#205: 99.03%\\n\",\n      \"#206: 99.03%\\n\",\n      \"#207: 99.04%\\n\",\n      \"#208: 99.04%\\n\",\n      \"#209: 99.05%\\n\",\n      \"#210: 99.05%\\n\",\n      \"#211: 99.06%\\n\",\n      \"#212: 99.06%\\n\",\n      \"#213: 99.07%\\n\",\n      \"#214: 99.07%\\n\",\n      \"#215: 99.07%\\n\",\n      \"#216: 99.08%\\n\",\n      \"#217: 99.08%\\n\",\n      \"#218: 99.09%\\n\",\n      \"#219: 99.09%\\n\",\n      \"#220: 99.10%\\n\",\n      \"#221: 99.10%\\n\",\n      \"#222: 99.10%\\n\",\n      \"#223: 99.11%\\n\",\n      \"#224: 99.11%\\n\",\n      \"#225: 99.12%\\n\",\n      \"#226: 99.12%\\n\",\n      \"#227: 99.12%\\n\",\n      \"#228: 99.13%\\n\",\n      \"#229: 99.13%\\n\",\n      \"#230: 99.13%\\n\",\n      \"#231: 99.14%\\n\",\n      \"#232: 99.14%\\n\",\n      \"#233: 99.15%\\n\",\n      \"#234: 99.15%\\n\",\n      \"#235: 99.15%\\n\",\n      \"#236: 99.16%\\n\",\n      \"#237: 99.16%\\n\",\n      \"#238: 99.16%\\n\",\n      \"#239: 99.17%\\n\",\n      \"#240: 99.17%\\n\",\n      \"#241: 98.76%\\n\",\n      \"#242: 98.77%\\n\",\n      \"#243: 98.77%\\n\",\n      \"#244: 98.78%\\n\",\n      \"#245: 98.78%\\n\",\n      \"#246: 98.79%\\n\",\n      \"#247: 98.39%\\n\",\n      \"#248: 98.39%\\n\",\n      \"#249: 98.40%\\n\",\n      \"#250: 98.41%\\n\",\n      \"#251: 98.41%\\n\",\n      \"#252: 98.42%\\n\",\n      \"#253: 98.43%\\n\",\n      \"#254: 98.43%\\n\",\n      \"#255: 98.44%\\n\",\n      \"#256: 98.44%\\n\",\n      \"#257: 98.45%\\n\",\n      \"#258: 98.46%\\n\",\n      \"#259: 98.08%\\n\",\n      \"#260: 98.08%\\n\",\n      \"#261: 98.09%\\n\",\n      \"#262: 98.10%\\n\",\n      \"#263: 98.11%\\n\",\n      \"#264: 97.74%\\n\",\n      \"#265: 97.74%\\n\",\n      \"#266: 97.38%\\n\",\n      \"#267: 97.39%\\n\",\n      \"#268: 97.40%\\n\",\n      \"#269: 97.41%\\n\",\n      \"#270: 97.42%\\n\",\n      \"#271: 97.43%\\n\",\n      \"#272: 97.44%\\n\",\n      \"#273: 97.45%\\n\",\n      \"#274: 97.45%\\n\",\n      \"#275: 97.46%\\n\",\n      \"#276: 97.47%\\n\",\n      \"#277: 97.48%\\n\",\n      \"#278: 97.49%\\n\",\n      \"#279: 97.50%\\n\",\n      \"#280: 97.51%\\n\",\n      \"#281: 97.52%\\n\",\n      \"#282: 97.17%\\n\",\n      \"#283: 97.18%\\n\",\n      \"#284: 97.19%\\n\",\n      \"#285: 97.20%\\n\",\n      \"#286: 97.21%\\n\",\n      \"#287: 97.22%\\n\",\n      \"#288: 97.23%\\n\",\n      \"#289: 97.24%\\n\",\n      \"#290: 97.25%\\n\",\n      \"#291: 97.26%\\n\",\n      \"#292: 97.27%\\n\",\n      \"#293: 97.28%\\n\",\n      \"#294: 97.29%\\n\",\n      \"#295: 97.30%\\n\",\n      \"#296: 97.31%\\n\",\n      \"#297: 97.32%\\n\",\n      \"#298: 97.32%\\n\",\n      \"#299: 97.33%\\n\",\n      \"#300: 97.34%\\n\",\n      \"#301: 97.35%\\n\",\n      \"#302: 97.36%\\n\",\n      \"#303: 97.37%\\n\",\n      \"#304: 97.38%\\n\",\n      \"#305: 97.39%\\n\",\n      \"#306: 97.39%\\n\",\n      \"#307: 97.40%\\n\",\n      \"#308: 97.41%\\n\",\n      \"#309: 97.42%\\n\",\n      \"#310: 97.43%\\n\",\n      \"#311: 97.44%\\n\",\n      \"#312: 97.44%\\n\",\n      \"#313: 97.45%\\n\",\n      \"#314: 97.46%\\n\",\n      \"#315: 97.47%\\n\",\n      \"#316: 97.48%\\n\",\n      \"#317: 97.48%\\n\",\n      \"#318: 97.49%\\n\",\n      \"#319: 97.50%\\n\",\n      \"#320: 97.20%\\n\",\n      \"#321: 97.20%\\n\",\n      \"#322: 97.21%\\n\",\n      \"#323: 97.22%\\n\",\n      \"#324: 97.23%\\n\",\n      \"#325: 97.24%\\n\",\n      \"#326: 97.25%\\n\",\n      \"#327: 97.26%\\n\",\n      \"#328: 97.26%\\n\",\n      \"#329: 97.27%\\n\",\n      \"#330: 97.28%\\n\",\n      \"#331: 97.29%\\n\",\n      \"#332: 97.30%\\n\",\n      \"#333: 97.31%\\n\",\n      \"#334: 97.31%\\n\",\n      \"#335: 97.32%\\n\",\n      \"#336: 97.33%\\n\",\n      \"#337: 97.34%\\n\",\n      \"#338: 97.35%\\n\",\n      \"#339: 97.35%\\n\",\n      \"#340: 97.36%\\n\",\n      \"#341: 97.37%\\n\",\n      \"#342: 97.38%\\n\",\n      \"#343: 97.38%\\n\",\n      \"#344: 97.39%\\n\",\n      \"#345: 97.40%\\n\",\n      \"#346: 97.41%\\n\",\n      \"#347: 97.41%\\n\",\n      \"#348: 97.42%\\n\",\n      \"#349: 97.43%\\n\",\n      \"#350: 97.44%\\n\",\n      \"#351: 97.44%\\n\",\n      \"#352: 97.45%\\n\",\n      \"#353: 97.46%\\n\",\n      \"#354: 97.46%\\n\",\n      \"#355: 97.47%\\n\",\n      \"#356: 97.48%\\n\",\n      \"#357: 97.49%\\n\",\n      \"#358: 97.21%\\n\",\n      \"#359: 97.22%\\n\",\n      \"#360: 97.23%\\n\",\n      \"#361: 97.24%\\n\",\n      \"#362: 97.25%\\n\",\n      \"#363: 97.25%\\n\",\n      \"#364: 97.26%\\n\",\n      \"#365: 97.27%\\n\",\n      \"#366: 97.28%\\n\",\n      \"#367: 97.28%\\n\",\n      \"#368: 97.29%\\n\",\n      \"#369: 97.30%\\n\",\n      \"#370: 97.30%\\n\",\n      \"#371: 97.31%\\n\",\n      \"#372: 97.32%\\n\",\n      \"#373: 97.33%\\n\",\n      \"#374: 97.33%\\n\",\n      \"#375: 97.34%\\n\",\n      \"#376: 97.35%\\n\",\n      \"#377: 97.35%\\n\",\n      \"#378: 97.36%\\n\",\n      \"#379: 97.37%\\n\",\n      \"#380: 97.38%\\n\",\n      \"#381: 97.38%\\n\",\n      \"#382: 97.39%\\n\",\n      \"#383: 97.40%\\n\",\n      \"#384: 97.40%\\n\",\n      \"#385: 97.41%\\n\",\n      \"#386: 97.42%\\n\",\n      \"#387: 97.42%\\n\",\n      \"#388: 97.43%\\n\",\n      \"#389: 97.44%\\n\",\n      \"#390: 97.44%\\n\",\n      \"#391: 97.45%\\n\",\n      \"#392: 97.46%\\n\",\n      \"#393: 97.46%\\n\",\n      \"#394: 97.47%\\n\",\n      \"#395: 97.47%\\n\",\n      \"#396: 97.48%\\n\",\n      \"#397: 97.49%\\n\",\n      \"#398: 97.49%\\n\",\n      \"#399: 97.50%\\n\",\n      \"#400: 97.51%\\n\",\n      \"#401: 97.51%\\n\",\n      \"#402: 97.52%\\n\",\n      \"#403: 97.28%\\n\",\n      \"#404: 97.28%\\n\",\n      \"#405: 97.29%\\n\",\n      \"#406: 97.30%\\n\",\n      \"#407: 97.30%\\n\",\n      \"#408: 97.31%\\n\",\n      \"#409: 97.32%\\n\",\n      \"#410: 97.32%\\n\",\n      \"#411: 97.33%\\n\",\n      \"#412: 97.34%\\n\",\n      \"#413: 97.34%\\n\",\n      \"#414: 97.35%\\n\",\n      \"#415: 97.36%\\n\",\n      \"#416: 97.36%\\n\",\n      \"#417: 97.37%\\n\",\n      \"#418: 97.37%\\n\",\n      \"#419: 97.38%\\n\",\n      \"#420: 97.39%\\n\",\n      \"#421: 97.39%\\n\",\n      \"#422: 97.40%\\n\",\n      \"#423: 97.41%\\n\",\n      \"#424: 97.41%\\n\",\n      \"#425: 97.42%\\n\",\n      \"#426: 97.42%\\n\",\n      \"#427: 97.43%\\n\",\n      \"#428: 97.44%\\n\",\n      \"#429: 97.44%\\n\",\n      \"#430: 97.45%\\n\",\n      \"#431: 97.45%\\n\",\n      \"#432: 97.46%\\n\",\n      \"#433: 97.47%\\n\",\n      \"#434: 97.47%\\n\",\n      \"#435: 97.25%\\n\",\n      \"#436: 97.25%\\n\",\n      \"#437: 97.26%\\n\",\n      \"#438: 97.27%\\n\",\n      \"#439: 97.27%\\n\",\n      \"#440: 97.28%\\n\",\n      \"#441: 97.29%\\n\",\n      \"#442: 97.29%\\n\",\n      \"#443: 97.30%\\n\",\n      \"#444: 97.30%\\n\",\n      \"#445: 97.09%\\n\",\n      \"#446: 97.09%\\n\",\n      \"#447: 97.10%\\n\",\n      \"#448: 97.10%\\n\",\n      \"#449: 97.11%\\n\",\n      \"#450: 97.12%\\n\",\n      \"#451: 97.12%\\n\",\n      \"#452: 97.13%\\n\",\n      \"#453: 97.14%\\n\",\n      \"#454: 97.14%\\n\",\n      \"#455: 97.15%\\n\",\n      \"#456: 97.16%\\n\",\n      \"#457: 97.16%\\n\",\n      \"#458: 97.17%\\n\",\n      \"#459: 97.17%\\n\",\n      \"#460: 97.18%\\n\",\n      \"#461: 97.19%\\n\",\n      \"#462: 97.19%\\n\",\n      \"#463: 97.20%\\n\",\n      \"#464: 96.99%\\n\",\n      \"#465: 97.00%\\n\",\n      \"#466: 97.00%\\n\",\n      \"#467: 97.01%\\n\",\n      \"#468: 97.01%\\n\",\n      \"#469: 97.02%\\n\",\n      \"#470: 97.03%\\n\",\n      \"#471: 97.03%\\n\",\n      \"#472: 97.04%\\n\",\n      \"#473: 97.05%\\n\",\n      \"#474: 97.05%\\n\",\n      \"#475: 97.06%\\n\",\n      \"#476: 97.06%\\n\",\n      \"#477: 97.07%\\n\",\n      \"#478: 97.08%\\n\",\n      \"#479: 97.08%\\n\",\n      \"#480: 97.09%\\n\",\n      \"#481: 97.10%\\n\",\n      \"#482: 97.10%\\n\",\n      \"#483: 97.11%\\n\",\n      \"#484: 97.11%\\n\",\n      \"#485: 97.12%\\n\",\n      \"#486: 97.13%\\n\",\n      \"#487: 97.13%\\n\",\n      \"#488: 97.14%\\n\",\n      \"#489: 97.14%\\n\",\n      \"#490: 97.15%\\n\",\n      \"#491: 97.15%\\n\",\n      \"#492: 97.16%\\n\",\n      \"#493: 97.17%\\n\",\n      \"#494: 97.17%\\n\",\n      \"#495: 96.98%\\n\",\n      \"#496: 96.98%\\n\",\n      \"#497: 96.99%\\n\",\n      \"#498: 96.99%\\n\",\n      \"#499: 97.00%\\n\",\n      \"#500: 97.01%\\n\",\n      \"#501: 97.01%\\n\",\n      \"#502: 97.02%\\n\",\n      \"#503: 97.02%\\n\",\n      \"#504: 97.03%\\n\",\n      \"#505: 97.04%\\n\",\n      \"#506: 97.04%\\n\",\n      \"#507: 97.05%\\n\",\n      \"#508: 97.05%\\n\",\n      \"#509: 97.06%\\n\",\n      \"#510: 97.06%\\n\",\n      \"#511: 97.07%\\n\",\n      \"#512: 97.08%\\n\",\n      \"#513: 97.08%\\n\",\n      \"#514: 97.09%\\n\",\n      \"#515: 97.09%\\n\",\n      \"#516: 97.10%\\n\",\n      \"#517: 97.10%\\n\",\n      \"#518: 97.11%\\n\",\n      \"#519: 97.12%\\n\",\n      \"#520: 97.12%\\n\",\n      \"#521: 97.13%\\n\",\n      \"#522: 97.13%\\n\",\n      \"#523: 97.14%\\n\",\n      \"#524: 97.14%\\n\",\n      \"#525: 97.15%\\n\",\n      \"#526: 97.15%\\n\",\n      \"#527: 97.16%\\n\",\n      \"#528: 97.16%\\n\",\n      \"#529: 97.17%\\n\",\n      \"#530: 97.18%\\n\",\n      \"#531: 97.18%\\n\",\n      \"#532: 97.19%\\n\",\n      \"#533: 97.19%\\n\",\n      \"#534: 97.20%\\n\",\n      \"#535: 97.20%\\n\",\n      \"#536: 97.21%\\n\",\n      \"#537: 97.21%\\n\",\n      \"#538: 97.22%\\n\",\n      \"#539: 97.22%\\n\",\n      \"#540: 97.23%\\n\",\n      \"#541: 97.23%\\n\",\n      \"#542: 97.05%\\n\",\n      \"#543: 97.06%\\n\",\n      \"#544: 97.06%\\n\",\n      \"#545: 97.07%\\n\",\n      \"#546: 97.07%\\n\",\n      \"#547: 97.08%\\n\",\n      \"#548: 97.09%\\n\",\n      \"#549: 97.09%\\n\",\n      \"#550: 97.10%\\n\",\n      \"#551: 97.10%\\n\",\n      \"#552: 97.11%\\n\",\n      \"#553: 97.11%\\n\",\n      \"#554: 97.12%\\n\",\n      \"#555: 97.12%\\n\",\n      \"#556: 97.13%\\n\",\n      \"#557: 97.13%\\n\",\n      \"#558: 97.14%\\n\",\n      \"#559: 97.14%\\n\",\n      \"#560: 97.15%\\n\",\n      \"#561: 97.15%\\n\",\n      \"#562: 97.16%\\n\",\n      \"#563: 97.16%\\n\",\n      \"#564: 97.17%\\n\",\n      \"#565: 97.17%\\n\",\n      \"#566: 97.18%\\n\",\n      \"#567: 97.18%\\n\",\n      \"#568: 97.19%\\n\",\n      \"#569: 97.19%\\n\",\n      \"#570: 97.20%\\n\",\n      \"#571: 97.20%\\n\",\n      \"#572: 97.21%\\n\",\n      \"#573: 97.21%\\n\",\n      \"#574: 97.22%\\n\",\n      \"#575: 97.22%\\n\",\n      \"#576: 97.23%\\n\",\n      \"#577: 97.23%\\n\",\n      \"#578: 97.24%\\n\",\n      \"#579: 97.24%\\n\",\n      \"#580: 97.25%\\n\",\n      \"#581: 97.25%\\n\",\n      \"#582: 97.08%\\n\",\n      \"#583: 97.09%\\n\",\n      \"#584: 97.09%\\n\",\n      \"#585: 97.10%\\n\",\n      \"#586: 97.10%\\n\",\n      \"#587: 97.11%\\n\",\n      \"#588: 97.11%\\n\",\n      \"#589: 97.12%\\n\",\n      \"#590: 97.12%\\n\",\n      \"#591: 97.13%\\n\",\n      \"#592: 97.13%\\n\",\n      \"#593: 97.14%\\n\",\n      \"#594: 97.14%\\n\",\n      \"#595: 97.15%\\n\",\n      \"#596: 97.15%\\n\",\n      \"#597: 97.16%\\n\",\n      \"#598: 97.16%\\n\",\n      \"#599: 97.17%\\n\",\n      \"#600: 97.17%\\n\",\n      \"#601: 97.18%\\n\",\n      \"#602: 97.18%\\n\",\n      \"#603: 97.19%\\n\",\n      \"#604: 97.19%\\n\",\n      \"#605: 97.03%\\n\",\n      \"#606: 97.03%\\n\",\n      \"#607: 97.04%\\n\",\n      \"#608: 97.04%\\n\",\n      \"#609: 97.05%\\n\",\n      \"#610: 97.05%\\n\",\n      \"#611: 97.06%\\n\",\n      \"#612: 97.06%\\n\",\n      \"#613: 97.07%\\n\",\n      \"#614: 97.07%\\n\",\n      \"#615: 97.08%\\n\",\n      \"#616: 97.08%\\n\",\n      \"#617: 97.09%\\n\",\n      \"#618: 97.09%\\n\",\n      \"#619: 97.10%\\n\",\n      \"#620: 97.10%\\n\",\n      \"#621: 97.11%\\n\",\n      \"#622: 97.11%\\n\",\n      \"#623: 97.12%\\n\",\n      \"#624: 97.12%\\n\",\n      \"#625: 97.12%\\n\",\n      \"#626: 97.13%\\n\",\n      \"#627: 97.13%\\n\",\n      \"#628: 97.14%\\n\",\n      \"#629: 97.14%\\n\",\n      \"#630: 97.15%\\n\",\n      \"#631: 97.15%\\n\",\n      \"#632: 97.16%\\n\",\n      \"#633: 97.16%\\n\",\n      \"#634: 97.17%\\n\",\n      \"#635: 97.17%\\n\",\n      \"#636: 97.17%\\n\",\n      \"#637: 97.18%\\n\",\n      \"#638: 97.18%\\n\",\n      \"#639: 97.19%\\n\",\n      \"#640: 97.19%\\n\",\n      \"#641: 97.20%\\n\",\n      \"#642: 97.20%\\n\",\n      \"#643: 97.20%\\n\",\n      \"#644: 97.21%\\n\",\n      \"#645: 97.21%\\n\",\n      \"#646: 97.22%\\n\",\n      \"#647: 97.22%\\n\",\n      \"#648: 97.23%\\n\",\n      \"#649: 97.23%\\n\",\n      \"#650: 97.24%\\n\",\n      \"#651: 97.24%\\n\",\n      \"#652: 97.24%\\n\",\n      \"#653: 97.25%\\n\",\n      \"#654: 97.25%\\n\",\n      \"#655: 97.26%\\n\",\n      \"#656: 97.26%\\n\",\n      \"#657: 97.26%\\n\",\n      \"#658: 97.27%\\n\",\n      \"#659: 97.27%\\n\",\n      \"#660: 97.28%\\n\",\n      \"#661: 97.28%\\n\",\n      \"#662: 97.29%\\n\",\n      \"#663: 97.29%\\n\",\n      \"#664: 97.29%\\n\",\n      \"#665: 97.30%\\n\",\n      \"#666: 97.30%\\n\",\n      \"#667: 97.31%\\n\",\n      \"#668: 97.31%\\n\",\n      \"#669: 97.31%\\n\",\n      \"#670: 97.32%\\n\",\n      \"#671: 97.32%\\n\",\n      \"#672: 97.33%\\n\",\n      \"#673: 97.33%\\n\",\n      \"#674: 97.33%\\n\",\n      \"#675: 97.34%\\n\",\n      \"#676: 97.34%\\n\",\n      \"#677: 97.35%\\n\",\n      \"#678: 97.35%\\n\",\n      \"#679: 97.35%\\n\",\n      \"#680: 97.36%\\n\",\n      \"#681: 97.36%\\n\",\n      \"#682: 97.36%\\n\",\n      \"#683: 97.37%\\n\",\n      \"#684: 97.23%\\n\",\n      \"#685: 97.23%\\n\",\n      \"#686: 97.23%\\n\",\n      \"#687: 97.24%\\n\",\n      \"#688: 97.24%\\n\",\n      \"#689: 97.10%\\n\",\n      \"#690: 97.11%\\n\",\n      \"#691: 97.11%\\n\",\n      \"#692: 97.11%\\n\",\n      \"#693: 97.12%\\n\",\n      \"#694: 97.12%\\n\",\n      \"#695: 97.13%\\n\",\n      \"#696: 97.13%\\n\",\n      \"#697: 97.13%\\n\",\n      \"#698: 97.14%\\n\",\n      \"#699: 97.14%\\n\",\n      \"#700: 97.15%\\n\",\n      \"#701: 97.15%\\n\",\n      \"#702: 97.16%\\n\",\n      \"#703: 97.16%\\n\",\n      \"#704: 97.16%\\n\",\n      \"#705: 97.17%\\n\",\n      \"#706: 97.17%\\n\",\n      \"#707: 97.18%\\n\",\n      \"#708: 97.18%\\n\",\n      \"#709: 97.18%\\n\",\n      \"#710: 97.19%\\n\",\n      \"#711: 97.19%\\n\",\n      \"#712: 97.19%\\n\",\n      \"#713: 97.20%\\n\",\n      \"#714: 97.20%\\n\",\n      \"#715: 97.21%\\n\",\n      \"#716: 97.21%\\n\",\n      \"#717: 97.08%\\n\",\n      \"#718: 97.08%\\n\",\n      \"#719: 97.08%\\n\",\n      \"#720: 97.09%\\n\",\n      \"#721: 97.09%\\n\",\n      \"#722: 97.10%\\n\",\n      \"#723: 97.10%\\n\",\n      \"#724: 97.10%\\n\",\n      \"#725: 97.11%\\n\",\n      \"#726: 96.97%\\n\",\n      \"#727: 96.98%\\n\",\n      \"#728: 96.98%\\n\",\n      \"#729: 96.99%\\n\",\n      \"#730: 96.99%\\n\",\n      \"#731: 96.99%\\n\",\n      \"#732: 97.00%\\n\",\n      \"#733: 97.00%\\n\",\n      \"#734: 97.01%\\n\",\n      \"#735: 97.01%\\n\",\n      \"#736: 97.01%\\n\",\n      \"#737: 97.02%\\n\",\n      \"#738: 97.02%\\n\",\n      \"#739: 97.03%\\n\",\n      \"#740: 97.03%\\n\",\n      \"#741: 97.04%\\n\",\n      \"#742: 97.04%\\n\",\n      \"#743: 97.04%\\n\",\n      \"#744: 97.05%\\n\",\n      \"#745: 97.05%\\n\",\n      \"#746: 97.05%\\n\",\n      \"#747: 97.06%\\n\",\n      \"#748: 97.06%\\n\",\n      \"#749: 97.07%\\n\",\n      \"#750: 97.07%\\n\",\n      \"#751: 97.07%\\n\",\n      \"#752: 97.08%\\n\",\n      \"#753: 97.08%\\n\",\n      \"#754: 97.09%\\n\",\n      \"#755: 97.09%\\n\",\n      \"#756: 97.09%\\n\",\n      \"#757: 97.10%\\n\",\n      \"#758: 97.10%\\n\",\n      \"#759: 97.11%\\n\",\n      \"#760: 97.11%\\n\",\n      \"#761: 97.11%\\n\",\n      \"#762: 97.12%\\n\",\n      \"#763: 97.12%\\n\",\n      \"#764: 97.12%\\n\",\n      \"#765: 97.13%\\n\",\n      \"#766: 97.13%\\n\",\n      \"#767: 97.14%\\n\",\n      \"#768: 97.14%\\n\",\n      \"#769: 97.14%\\n\",\n      \"#770: 97.15%\\n\",\n      \"#771: 97.15%\\n\",\n      \"#772: 97.15%\\n\",\n      \"#773: 97.16%\\n\",\n      \"#774: 97.16%\\n\",\n      \"#775: 97.16%\\n\",\n      \"#776: 97.17%\\n\",\n      \"#777: 97.17%\\n\",\n      \"#778: 97.18%\\n\",\n      \"#779: 97.18%\\n\",\n      \"#780: 97.18%\\n\",\n      \"#781: 97.19%\\n\",\n      \"#782: 97.19%\\n\",\n      \"#783: 97.19%\\n\",\n      \"#784: 97.20%\\n\",\n      \"#785: 97.20%\\n\",\n      \"#786: 97.20%\\n\",\n      \"#787: 97.21%\\n\",\n      \"#788: 97.21%\\n\",\n      \"#789: 97.22%\\n\",\n      \"#790: 97.22%\\n\",\n      \"#791: 97.22%\\n\",\n      \"#792: 97.23%\\n\",\n      \"#793: 97.23%\\n\",\n      \"#794: 97.23%\\n\",\n      \"#795: 97.24%\\n\",\n      \"#796: 97.24%\\n\",\n      \"#797: 97.24%\\n\",\n      \"#798: 97.25%\\n\",\n      \"#799: 97.25%\\n\",\n      \"#800: 97.25%\\n\",\n      \"#801: 97.26%\\n\",\n      \"#802: 97.26%\\n\",\n      \"#803: 97.26%\\n\",\n      \"#804: 97.27%\\n\",\n      \"#805: 97.27%\\n\",\n      \"#806: 97.27%\\n\",\n      \"#807: 97.28%\\n\",\n      \"#808: 97.28%\\n\",\n      \"#809: 97.28%\\n\",\n      \"#810: 97.29%\\n\",\n      \"#811: 97.29%\\n\",\n      \"#812: 97.29%\\n\",\n      \"#813: 97.17%\\n\",\n      \"#814: 97.18%\\n\",\n      \"#815: 97.18%\\n\",\n      \"#816: 97.18%\\n\",\n      \"#817: 97.19%\\n\",\n      \"#818: 97.19%\\n\",\n      \"#819: 97.20%\\n\",\n      \"#820: 97.20%\\n\",\n      \"#821: 97.20%\\n\",\n      \"#822: 97.21%\\n\",\n      \"#823: 97.21%\\n\",\n      \"#824: 97.21%\\n\",\n      \"#825: 97.22%\\n\",\n      \"#826: 97.22%\\n\",\n      \"#827: 97.22%\\n\",\n      \"#828: 97.23%\\n\",\n      \"#829: 97.23%\\n\",\n      \"#830: 97.23%\\n\",\n      \"#831: 97.24%\\n\",\n      \"#832: 97.24%\\n\",\n      \"#833: 97.24%\\n\",\n      \"#834: 97.25%\\n\",\n      \"#835: 97.25%\\n\",\n      \"#836: 97.25%\\n\",\n      \"#837: 97.26%\\n\",\n      \"#838: 97.26%\\n\",\n      \"#839: 97.26%\\n\",\n      \"#840: 97.27%\\n\",\n      \"#841: 97.27%\\n\",\n      \"#842: 97.27%\\n\",\n      \"#843: 97.27%\\n\",\n      \"#844: 97.28%\\n\",\n      \"#845: 97.28%\\n\",\n      \"#846: 97.28%\\n\",\n      \"#847: 97.29%\\n\",\n      \"#848: 97.29%\\n\",\n      \"#849: 97.29%\\n\",\n      \"#850: 97.30%\\n\",\n      \"#851: 97.30%\\n\",\n      \"#852: 97.30%\\n\",\n      \"#853: 97.31%\\n\",\n      \"#854: 97.31%\\n\",\n      \"#855: 97.31%\\n\",\n      \"#856: 97.32%\\n\",\n      \"#857: 97.32%\\n\",\n      \"#858: 97.32%\\n\",\n      \"#859: 97.33%\\n\",\n      \"#860: 97.33%\\n\",\n      \"#861: 97.33%\\n\",\n      \"#862: 97.33%\\n\",\n      \"#863: 97.34%\\n\",\n      \"#864: 97.34%\\n\",\n      \"#865: 97.34%\\n\",\n      \"#866: 97.35%\\n\",\n      \"#867: 97.35%\\n\",\n      \"#868: 97.35%\\n\",\n      \"#869: 97.36%\\n\",\n      \"#870: 97.36%\\n\",\n      \"#871: 97.36%\\n\",\n      \"#872: 97.37%\\n\",\n      \"#873: 97.37%\\n\",\n      \"#874: 97.37%\\n\",\n      \"#875: 97.37%\\n\",\n      \"#876: 97.38%\\n\",\n      \"#877: 97.38%\\n\",\n      \"#878: 97.38%\\n\",\n      \"#879: 97.39%\\n\",\n      \"#880: 97.39%\\n\",\n      \"#881: 97.39%\\n\",\n      \"#882: 97.40%\\n\",\n      \"#883: 97.40%\\n\",\n      \"#884: 97.40%\\n\",\n      \"#885: 97.40%\\n\",\n      \"#886: 97.41%\\n\",\n      \"#887: 97.41%\\n\",\n      \"#888: 97.41%\\n\",\n      \"#889: 97.42%\\n\",\n      \"#890: 97.42%\\n\",\n      \"#891: 97.42%\\n\",\n      \"#892: 97.42%\\n\",\n      \"#893: 97.43%\\n\",\n      \"#894: 97.43%\\n\",\n      \"#895: 97.43%\\n\",\n      \"#896: 97.44%\\n\",\n      \"#897: 97.44%\\n\",\n      \"#898: 97.33%\\n\",\n      \"#899: 97.33%\\n\",\n      \"#900: 97.34%\\n\",\n      \"#901: 97.34%\\n\",\n      \"#902: 97.34%\\n\",\n      \"#903: 97.35%\\n\",\n      \"#904: 97.35%\\n\",\n      \"#905: 97.35%\\n\",\n      \"#906: 97.35%\\n\",\n      \"#907: 97.36%\\n\",\n      \"#908: 97.36%\\n\",\n      \"#909: 97.36%\\n\",\n      \"#910: 97.37%\\n\",\n      \"#911: 97.37%\\n\",\n      \"#912: 97.37%\\n\",\n      \"#913: 97.37%\\n\",\n      \"#914: 97.38%\\n\",\n      \"#915: 97.38%\\n\",\n      \"#916: 97.38%\\n\",\n      \"#917: 97.39%\\n\",\n      \"#918: 97.39%\\n\",\n      \"#919: 97.39%\\n\",\n      \"#920: 97.39%\\n\",\n      \"#921: 97.40%\\n\",\n      \"#922: 97.40%\\n\",\n      \"#923: 97.40%\\n\",\n      \"#924: 97.41%\\n\",\n      \"#925: 97.41%\\n\",\n      \"#926: 97.41%\\n\",\n      \"#927: 97.41%\\n\",\n      \"#928: 97.42%\\n\",\n      \"#929: 97.42%\\n\",\n      \"#930: 97.42%\\n\",\n      \"#931: 97.42%\\n\",\n      \"#932: 97.43%\\n\",\n      \"#933: 97.43%\\n\",\n      \"#934: 97.43%\\n\",\n      \"#935: 97.44%\\n\",\n      \"#936: 97.44%\\n\",\n      \"#937: 97.44%\\n\",\n      \"#938: 97.44%\\n\",\n      \"#939: 97.45%\\n\",\n      \"#940: 97.45%\\n\",\n      \"#941: 97.45%\\n\",\n      \"#942: 97.45%\\n\",\n      \"#943: 97.46%\\n\",\n      \"#944: 97.46%\\n\",\n      \"#945: 97.46%\\n\",\n      \"#946: 97.47%\\n\",\n      \"#947: 97.36%\\n\",\n      \"#948: 97.37%\\n\",\n      \"#949: 97.37%\\n\",\n      \"#950: 97.37%\\n\",\n      \"#951: 97.37%\\n\",\n      \"#952: 97.38%\\n\",\n      \"#953: 97.38%\\n\",\n      \"#954: 97.38%\\n\",\n      \"#955: 97.38%\\n\",\n      \"#956: 97.28%\\n\",\n      \"#957: 97.29%\\n\",\n      \"#958: 97.29%\\n\",\n      \"#959: 97.29%\\n\",\n      \"#960: 97.29%\\n\",\n      \"#961: 97.30%\\n\",\n      \"#962: 97.30%\\n\",\n      \"#963: 97.30%\\n\",\n      \"#964: 97.31%\\n\",\n      \"#965: 97.20%\\n\",\n      \"#966: 97.21%\\n\",\n      \"#967: 97.21%\\n\",\n      \"#968: 97.21%\\n\",\n      \"#969: 97.22%\\n\",\n      \"#970: 97.22%\\n\",\n      \"#971: 97.22%\\n\",\n      \"#972: 97.23%\\n\",\n      \"#973: 97.23%\\n\",\n      \"#974: 97.23%\\n\",\n      \"#975: 97.23%\\n\",\n      \"#976: 97.24%\\n\",\n      \"#977: 97.24%\\n\",\n      \"#978: 97.24%\\n\",\n      \"#979: 97.24%\\n\",\n      \"#980: 97.25%\\n\",\n      \"#981: 97.25%\\n\",\n      \"#982: 97.25%\\n\",\n      \"#983: 97.26%\\n\",\n      \"#984: 97.26%\\n\",\n      \"#985: 97.26%\\n\",\n      \"#986: 97.26%\\n\",\n      \"#987: 97.27%\\n\",\n      \"#988: 97.27%\\n\",\n      \"#989: 97.27%\\n\",\n      \"#990: 97.28%\\n\",\n      \"#991: 97.28%\\n\",\n      \"#992: 97.28%\\n\",\n      \"#993: 97.28%\\n\",\n      \"#994: 97.29%\\n\",\n      \"#995: 97.29%\\n\",\n      \"#996: 97.29%\\n\",\n      \"#997: 97.29%\\n\",\n      \"#998: 97.30%\\n\",\n      \"#999: 97.30%\\n\",\n      \"#1000: 97.30%\\n\",\n      \"#1001: 97.31%\\n\",\n      \"#1002: 97.31%\\n\",\n      \"#1003: 97.31%\\n\",\n      \"#1004: 97.31%\\n\",\n      \"#1005: 97.32%\\n\",\n      \"#1006: 97.32%\\n\",\n      \"#1007: 97.32%\\n\",\n      \"#1008: 97.32%\\n\",\n      \"#1009: 97.33%\\n\",\n      \"#1010: 97.33%\\n\",\n      \"#1011: 97.33%\\n\",\n      \"#1012: 97.33%\\n\",\n      \"#1013: 97.34%\\n\",\n      \"#1014: 97.24%\\n\",\n      \"#1015: 97.24%\\n\",\n      \"#1016: 97.25%\\n\",\n      \"#1017: 97.25%\\n\",\n      \"#1018: 97.25%\\n\",\n      \"#1019: 97.25%\\n\",\n      \"#1020: 97.26%\\n\",\n      \"#1021: 97.26%\\n\",\n      \"#1022: 97.26%\\n\",\n      \"#1023: 97.27%\\n\",\n      \"#1024: 97.27%\\n\",\n      \"#1025: 97.27%\\n\",\n      \"#1026: 97.27%\\n\",\n      \"#1027: 97.28%\\n\",\n      \"#1028: 97.28%\\n\",\n      \"#1029: 97.28%\\n\",\n      \"#1030: 97.28%\\n\",\n      \"#1031: 97.29%\\n\",\n      \"#1032: 97.29%\\n\",\n      \"#1033: 97.29%\\n\",\n      \"#1034: 97.29%\\n\",\n      \"#1035: 97.30%\\n\",\n      \"#1036: 97.30%\\n\",\n      \"#1037: 97.30%\\n\",\n      \"#1038: 97.31%\\n\",\n      \"#1039: 97.21%\\n\",\n      \"#1040: 97.21%\\n\",\n      \"#1041: 97.22%\\n\",\n      \"#1042: 97.22%\\n\",\n      \"#1043: 97.22%\\n\",\n      \"#1044: 97.22%\\n\",\n      \"#1045: 97.23%\\n\",\n      \"#1046: 97.23%\\n\",\n      \"#1047: 97.23%\\n\",\n      \"#1048: 97.24%\\n\",\n      \"#1049: 97.24%\\n\",\n      \"#1050: 97.24%\\n\",\n      \"#1051: 97.24%\\n\",\n      \"#1052: 97.25%\\n\",\n      \"#1053: 97.25%\\n\",\n      \"#1054: 97.25%\\n\",\n      \"#1055: 97.25%\\n\",\n      \"#1056: 97.26%\\n\",\n      \"#1057: 97.26%\\n\",\n      \"#1058: 97.26%\\n\",\n      \"#1059: 97.26%\\n\",\n      \"#1060: 97.27%\\n\",\n      \"#1061: 97.27%\\n\",\n      \"#1062: 97.18%\\n\",\n      \"#1063: 97.18%\\n\",\n      \"#1064: 97.18%\\n\",\n      \"#1065: 97.19%\\n\",\n      \"#1066: 97.19%\\n\",\n      \"#1067: 97.19%\\n\",\n      \"#1068: 97.10%\\n\",\n      \"#1069: 97.10%\\n\",\n      \"#1070: 97.11%\\n\",\n      \"#1071: 97.11%\\n\",\n      \"#1072: 97.11%\\n\",\n      \"#1073: 97.11%\\n\",\n      \"#1074: 97.12%\\n\",\n      \"#1075: 97.12%\\n\",\n      \"#1076: 97.12%\\n\",\n      \"#1077: 97.12%\\n\",\n      \"#1078: 97.13%\\n\",\n      \"#1079: 97.13%\\n\",\n      \"#1080: 97.13%\\n\",\n      \"#1081: 97.13%\\n\",\n      \"#1082: 97.14%\\n\",\n      \"#1083: 97.14%\\n\",\n      \"#1084: 97.14%\\n\",\n      \"#1085: 97.15%\\n\",\n      \"#1086: 97.15%\\n\",\n      \"#1087: 97.15%\\n\",\n      \"#1088: 97.15%\\n\",\n      \"#1089: 97.16%\\n\",\n      \"#1090: 97.16%\\n\",\n      \"#1091: 97.16%\\n\",\n      \"#1092: 97.16%\\n\",\n      \"#1093: 97.17%\\n\",\n      \"#1094: 97.17%\\n\",\n      \"#1095: 97.17%\\n\",\n      \"#1096: 97.17%\\n\",\n      \"#1097: 97.18%\\n\",\n      \"#1098: 97.18%\\n\",\n      \"#1099: 97.18%\\n\",\n      \"#1100: 97.18%\\n\",\n      \"#1101: 97.19%\\n\",\n      \"#1102: 97.19%\\n\",\n      \"#1103: 97.19%\\n\",\n      \"#1104: 97.19%\\n\",\n      \"#1105: 97.20%\\n\",\n      \"#1106: 97.20%\\n\",\n      \"#1107: 97.11%\\n\",\n      \"#1108: 97.11%\\n\",\n      \"#1109: 97.12%\\n\",\n      \"#1110: 97.12%\\n\",\n      \"#1111: 97.12%\\n\",\n      \"#1112: 97.04%\\n\",\n      \"#1113: 97.04%\\n\",\n      \"#1114: 96.95%\\n\",\n      \"#1115: 96.95%\\n\",\n      \"#1116: 96.96%\\n\",\n      \"#1117: 96.96%\\n\",\n      \"#1118: 96.96%\\n\",\n      \"#1119: 96.96%\\n\",\n      \"#1120: 96.97%\\n\",\n      \"#1121: 96.97%\\n\",\n      \"#1122: 96.97%\\n\",\n      \"#1123: 96.98%\\n\",\n      \"#1124: 96.98%\\n\",\n      \"#1125: 96.89%\\n\",\n      \"#1126: 96.89%\\n\",\n      \"#1127: 96.90%\\n\",\n      \"#1128: 96.90%\\n\",\n      \"#1129: 96.90%\\n\",\n      \"#1130: 96.91%\\n\",\n      \"#1131: 96.91%\\n\",\n      \"#1132: 96.91%\\n\",\n      \"#1133: 96.91%\\n\",\n      \"#1134: 96.92%\\n\",\n      \"#1135: 96.92%\\n\",\n      \"#1136: 96.92%\\n\",\n      \"#1137: 96.92%\\n\",\n      \"#1138: 96.93%\\n\",\n      \"#1139: 96.93%\\n\",\n      \"#1140: 96.93%\\n\",\n      \"#1141: 96.94%\\n\",\n      \"#1142: 96.94%\\n\",\n      \"#1143: 96.85%\\n\",\n      \"#1144: 96.86%\\n\",\n      \"#1145: 96.86%\\n\",\n      \"#1146: 96.86%\\n\",\n      \"#1147: 96.86%\\n\",\n      \"#1148: 96.87%\\n\",\n      \"#1149: 96.87%\\n\",\n      \"#1150: 96.87%\\n\",\n      \"#1151: 96.88%\\n\",\n      \"#1152: 96.88%\\n\",\n      \"#1153: 96.88%\\n\",\n      \"#1154: 96.88%\\n\",\n      \"#1155: 96.89%\\n\",\n      \"#1156: 96.89%\\n\",\n      \"#1157: 96.89%\\n\",\n      \"#1158: 96.89%\\n\",\n      \"#1159: 96.90%\\n\",\n      \"#1160: 96.90%\\n\",\n      \"#1161: 96.90%\\n\",\n      \"#1162: 96.90%\\n\",\n      \"#1163: 96.91%\\n\",\n      \"#1164: 96.91%\\n\",\n      \"#1165: 96.91%\\n\",\n      \"#1166: 96.92%\\n\",\n      \"#1167: 96.92%\\n\",\n      \"#1168: 96.92%\\n\",\n      \"#1169: 96.92%\\n\",\n      \"#1170: 96.93%\\n\",\n      \"#1171: 96.93%\\n\",\n      \"#1172: 96.93%\\n\",\n      \"#1173: 96.93%\\n\",\n      \"#1174: 96.94%\\n\",\n      \"#1175: 96.94%\\n\",\n      \"#1176: 96.94%\\n\",\n      \"#1177: 96.94%\\n\",\n      \"#1178: 96.95%\\n\",\n      \"#1179: 96.95%\\n\",\n      \"#1180: 96.95%\\n\",\n      \"#1181: 96.95%\\n\",\n      \"#1182: 96.87%\\n\",\n      \"#1183: 96.88%\\n\",\n      \"#1184: 96.88%\\n\",\n      \"#1185: 96.88%\\n\",\n      \"#1186: 96.88%\\n\",\n      \"#1187: 96.89%\\n\",\n      \"#1188: 96.89%\\n\",\n      \"#1189: 96.89%\\n\",\n      \"#1190: 96.89%\\n\",\n      \"#1191: 96.81%\\n\",\n      \"#1192: 96.81%\\n\",\n      \"#1193: 96.82%\\n\",\n      \"#1194: 96.82%\\n\",\n      \"#1195: 96.82%\\n\",\n      \"#1196: 96.83%\\n\",\n      \"#1197: 96.83%\\n\",\n      \"#1198: 96.83%\\n\",\n      \"#1199: 96.83%\\n\",\n      \"#1200: 96.84%\\n\",\n      \"#1201: 96.84%\\n\",\n      \"#1202: 96.84%\\n\",\n      \"#1203: 96.84%\\n\",\n      \"#1204: 96.85%\\n\",\n      \"#1205: 96.85%\\n\",\n      \"#1206: 96.85%\\n\",\n      \"#1207: 96.85%\\n\",\n      \"#1208: 96.86%\\n\",\n      \"#1209: 96.86%\\n\",\n      \"#1210: 96.86%\\n\",\n      \"#1211: 96.86%\\n\",\n      \"#1212: 96.87%\\n\",\n      \"#1213: 96.87%\\n\",\n      \"#1214: 96.87%\\n\",\n      \"#1215: 96.88%\\n\",\n      \"#1216: 96.88%\\n\",\n      \"#1217: 96.88%\\n\",\n      \"#1218: 96.88%\\n\",\n      \"#1219: 96.89%\\n\",\n      \"#1220: 96.89%\\n\",\n      \"#1221: 96.89%\\n\",\n      \"#1222: 96.89%\\n\",\n      \"#1223: 96.90%\\n\",\n      \"#1224: 96.90%\\n\",\n      \"#1225: 96.90%\\n\",\n      \"#1226: 96.82%\\n\",\n      \"#1227: 96.82%\\n\",\n      \"#1228: 96.83%\\n\",\n      \"#1229: 96.83%\\n\",\n      \"#1230: 96.83%\\n\",\n      \"#1231: 96.83%\\n\",\n      \"#1232: 96.84%\\n\",\n      \"#1233: 96.84%\\n\",\n      \"#1234: 96.84%\\n\",\n      \"#1235: 96.84%\\n\",\n      \"#1236: 96.85%\\n\",\n      \"#1237: 96.85%\\n\",\n      \"#1238: 96.85%\\n\",\n      \"#1239: 96.85%\\n\",\n      \"#1240: 96.86%\\n\",\n      \"#1241: 96.86%\\n\",\n      \"#1242: 96.86%\\n\",\n      \"#1243: 96.86%\\n\",\n      \"#1244: 96.87%\\n\",\n      \"#1245: 96.87%\\n\",\n      \"#1246: 96.87%\\n\",\n      \"#1247: 96.79%\\n\",\n      \"#1248: 96.80%\\n\",\n      \"#1249: 96.80%\\n\",\n      \"#1250: 96.80%\\n\",\n      \"#1251: 96.81%\\n\",\n      \"#1252: 96.81%\\n\",\n      \"#1253: 96.81%\\n\",\n      \"#1254: 96.81%\\n\",\n      \"#1255: 96.82%\\n\",\n      \"#1256: 96.82%\\n\",\n      \"#1257: 96.82%\\n\",\n      \"#1258: 96.82%\\n\",\n      \"#1259: 96.83%\\n\",\n      \"#1260: 96.75%\\n\",\n      \"#1261: 96.75%\\n\",\n      \"#1262: 96.75%\\n\",\n      \"#1263: 96.76%\\n\",\n      \"#1264: 96.76%\\n\",\n      \"#1265: 96.76%\\n\",\n      \"#1266: 96.76%\\n\",\n      \"#1267: 96.77%\\n\",\n      \"#1268: 96.77%\\n\",\n      \"#1269: 96.77%\\n\",\n      \"#1270: 96.77%\\n\",\n      \"#1271: 96.78%\\n\",\n      \"#1272: 96.78%\\n\",\n      \"#1273: 96.78%\\n\",\n      \"#1274: 96.78%\\n\",\n      \"#1275: 96.79%\\n\",\n      \"#1276: 96.79%\\n\",\n      \"#1277: 96.79%\\n\",\n      \"#1278: 96.79%\\n\",\n      \"#1279: 96.80%\\n\",\n      \"#1280: 96.80%\\n\",\n      \"#1281: 96.80%\\n\",\n      \"#1282: 96.80%\\n\",\n      \"#1283: 96.81%\\n\",\n      \"#1284: 96.81%\\n\",\n      \"#1285: 96.81%\\n\",\n      \"#1286: 96.81%\\n\",\n      \"#1287: 96.82%\\n\",\n      \"#1288: 96.82%\\n\",\n      \"#1289: 96.82%\\n\",\n      \"#1290: 96.75%\\n\",\n      \"#1291: 96.75%\\n\",\n      \"#1292: 96.75%\\n\",\n      \"#1293: 96.75%\\n\",\n      \"#1294: 96.76%\\n\",\n      \"#1295: 96.76%\\n\",\n      \"#1296: 96.76%\\n\",\n      \"#1297: 96.76%\\n\",\n      \"#1298: 96.77%\\n\",\n      \"#1299: 96.69%\\n\",\n      \"#1300: 96.69%\\n\",\n      \"#1301: 96.70%\\n\",\n      \"#1302: 96.70%\\n\",\n      \"#1303: 96.70%\\n\",\n      \"#1304: 96.70%\\n\",\n      \"#1305: 96.71%\\n\",\n      \"#1306: 96.71%\\n\",\n      \"#1307: 96.71%\\n\",\n      \"#1308: 96.72%\\n\",\n      \"#1309: 96.72%\\n\",\n      \"#1310: 96.72%\\n\",\n      \"#1311: 96.72%\\n\",\n      \"#1312: 96.73%\\n\",\n      \"#1313: 96.73%\\n\",\n      \"#1314: 96.73%\\n\",\n      \"#1315: 96.73%\\n\",\n      \"#1316: 96.74%\\n\",\n      \"#1317: 96.74%\\n\",\n      \"#1318: 96.74%\\n\",\n      \"#1319: 96.67%\\n\",\n      \"#1320: 96.67%\\n\",\n      \"#1321: 96.67%\\n\",\n      \"#1322: 96.67%\\n\",\n      \"#1323: 96.68%\\n\",\n      \"#1324: 96.68%\\n\",\n      \"#1325: 96.68%\\n\",\n      \"#1326: 96.68%\\n\",\n      \"#1327: 96.69%\\n\",\n      \"#1328: 96.69%\\n\",\n      \"#1329: 96.69%\\n\",\n      \"#1330: 96.69%\\n\",\n      \"#1331: 96.70%\\n\",\n      \"#1332: 96.70%\\n\",\n      \"#1333: 96.70%\\n\",\n      \"#1334: 96.70%\\n\",\n      \"#1335: 96.71%\\n\",\n      \"#1336: 96.71%\\n\",\n      \"#1337: 96.71%\\n\",\n      \"#1338: 96.71%\\n\",\n      \"#1339: 96.72%\\n\",\n      \"#1340: 96.72%\\n\",\n      \"#1341: 96.72%\\n\",\n      \"#1342: 96.72%\\n\",\n      \"#1343: 96.73%\\n\",\n      \"#1344: 96.73%\\n\",\n      \"#1345: 96.73%\\n\",\n      \"#1346: 96.73%\\n\",\n      \"#1347: 96.74%\\n\",\n      \"#1348: 96.74%\\n\",\n      \"#1349: 96.74%\\n\",\n      \"#1350: 96.74%\\n\",\n      \"#1351: 96.75%\\n\",\n      \"#1352: 96.75%\\n\",\n      \"#1353: 96.75%\\n\",\n      \"#1354: 96.75%\\n\",\n      \"#1355: 96.76%\\n\",\n      \"#1356: 96.76%\\n\",\n      \"#1357: 96.76%\\n\",\n      \"#1358: 96.76%\\n\",\n      \"#1359: 96.76%\\n\",\n      \"#1360: 96.77%\\n\",\n      \"#1361: 96.77%\\n\",\n      \"#1362: 96.77%\\n\",\n      \"#1363: 96.77%\\n\",\n      \"#1364: 96.70%\\n\",\n      \"#1365: 96.71%\\n\",\n      \"#1366: 96.71%\\n\",\n      \"#1367: 96.71%\\n\",\n      \"#1368: 96.71%\\n\",\n      \"#1369: 96.72%\\n\",\n      \"#1370: 96.72%\\n\",\n      \"#1371: 96.72%\\n\",\n      \"#1372: 96.72%\\n\",\n      \"#1373: 96.72%\\n\",\n      \"#1374: 96.73%\\n\",\n      \"#1375: 96.73%\\n\",\n      \"#1376: 96.73%\\n\",\n      \"#1377: 96.73%\\n\",\n      \"#1378: 96.74%\\n\",\n      \"#1379: 96.74%\\n\",\n      \"#1380: 96.74%\\n\",\n      \"#1381: 96.74%\\n\",\n      \"#1382: 96.75%\\n\",\n      \"#1383: 96.68%\\n\",\n      \"#1384: 96.68%\\n\",\n      \"#1385: 96.68%\\n\",\n      \"#1386: 96.68%\\n\",\n      \"#1387: 96.69%\\n\",\n      \"#1388: 96.69%\\n\",\n      \"#1389: 96.69%\\n\",\n      \"#1390: 96.69%\\n\",\n      \"#1391: 96.70%\\n\",\n      \"#1392: 96.70%\\n\",\n      \"#1393: 96.70%\\n\",\n      \"#1394: 96.70%\\n\",\n      \"#1395: 96.70%\\n\",\n      \"#1396: 96.71%\\n\",\n      \"#1397: 96.71%\\n\",\n      \"#1398: 96.71%\\n\",\n      \"#1399: 96.71%\\n\",\n      \"#1400: 96.72%\\n\",\n      \"#1401: 96.72%\\n\",\n      \"#1402: 96.72%\\n\",\n      \"#1403: 96.72%\\n\",\n      \"#1404: 96.73%\\n\",\n      \"#1405: 96.73%\\n\",\n      \"#1406: 96.73%\\n\",\n      \"#1407: 96.73%\\n\",\n      \"#1408: 96.74%\\n\",\n      \"#1409: 96.74%\\n\",\n      \"#1410: 96.74%\\n\",\n      \"#1411: 96.74%\\n\",\n      \"#1412: 96.74%\\n\",\n      \"#1413: 96.75%\\n\",\n      \"#1414: 96.75%\\n\",\n      \"#1415: 96.68%\\n\",\n      \"#1416: 96.68%\\n\",\n      \"#1417: 96.69%\\n\",\n      \"#1418: 96.69%\\n\",\n      \"#1419: 96.69%\\n\",\n      \"#1420: 96.69%\\n\",\n      \"#1421: 96.69%\\n\",\n      \"#1422: 96.70%\\n\",\n      \"#1423: 96.70%\\n\",\n      \"#1424: 96.70%\\n\",\n      \"#1425: 96.70%\\n\",\n      \"#1426: 96.71%\\n\",\n      \"#1427: 96.71%\\n\",\n      \"#1428: 96.71%\\n\",\n      \"#1429: 96.71%\\n\",\n      \"#1430: 96.72%\\n\",\n      \"#1431: 96.72%\\n\",\n      \"#1432: 96.72%\\n\",\n      \"#1433: 96.72%\\n\",\n      \"#1434: 96.72%\\n\",\n      \"#1435: 96.73%\\n\",\n      \"#1436: 96.73%\\n\",\n      \"#1437: 96.73%\\n\",\n      \"#1438: 96.73%\\n\",\n      \"#1439: 96.74%\\n\",\n      \"#1440: 96.67%\\n\",\n      \"#1441: 96.67%\\n\",\n      \"#1442: 96.67%\\n\",\n      \"#1443: 96.68%\\n\",\n      \"#1444: 96.68%\\n\",\n      \"#1445: 96.68%\\n\",\n      \"#1446: 96.68%\\n\",\n      \"#1447: 96.69%\\n\",\n      \"#1448: 96.69%\\n\",\n      \"#1449: 96.69%\\n\",\n      \"#1450: 96.69%\\n\",\n      \"#1451: 96.69%\\n\",\n      \"#1452: 96.70%\\n\",\n      \"#1453: 96.70%\\n\",\n      \"#1454: 96.70%\\n\",\n      \"#1455: 96.70%\\n\",\n      \"#1456: 96.71%\\n\",\n      \"#1457: 96.71%\\n\",\n      \"#1458: 96.71%\\n\",\n      \"#1459: 96.71%\\n\",\n      \"#1460: 96.71%\\n\",\n      \"#1461: 96.72%\\n\",\n      \"#1462: 96.72%\\n\",\n      \"#1463: 96.72%\\n\",\n      \"#1464: 96.72%\\n\",\n      \"#1465: 96.73%\\n\",\n      \"#1466: 96.73%\\n\",\n      \"#1467: 96.73%\\n\",\n      \"#1468: 96.73%\\n\",\n      \"#1469: 96.73%\\n\",\n      \"#1470: 96.74%\\n\",\n      \"#1471: 96.74%\\n\",\n      \"#1472: 96.74%\\n\",\n      \"#1473: 96.74%\\n\",\n      \"#1474: 96.75%\\n\",\n      \"#1475: 96.75%\\n\",\n      \"#1476: 96.75%\\n\",\n      \"#1477: 96.75%\\n\",\n      \"#1478: 96.75%\\n\",\n      \"#1479: 96.76%\\n\",\n      \"#1480: 96.76%\\n\",\n      \"#1481: 96.76%\\n\",\n      \"#1482: 96.76%\\n\",\n      \"#1483: 96.77%\\n\",\n      \"#1484: 96.77%\\n\",\n      \"#1485: 96.77%\\n\",\n      \"#1486: 96.77%\\n\",\n      \"#1487: 96.77%\\n\",\n      \"#1488: 96.78%\\n\",\n      \"#1489: 96.78%\\n\",\n      \"#1490: 96.78%\\n\",\n      \"#1491: 96.78%\\n\",\n      \"#1492: 96.78%\\n\",\n      \"#1493: 96.79%\\n\",\n      \"#1494: 96.79%\\n\",\n      \"#1495: 96.79%\\n\",\n      \"#1496: 96.79%\\n\",\n      \"#1497: 96.80%\\n\",\n      \"#1498: 96.80%\\n\",\n      \"#1499: 96.80%\\n\",\n      \"#1500: 96.80%\\n\",\n      \"#1501: 96.80%\\n\",\n      \"#1502: 96.81%\\n\",\n      \"#1503: 96.81%\\n\",\n      \"#1504: 96.81%\\n\",\n      \"#1505: 96.81%\\n\",\n      \"#1506: 96.81%\\n\",\n      \"#1507: 96.82%\\n\",\n      \"#1508: 96.82%\\n\",\n      \"#1509: 96.82%\\n\",\n      \"#1510: 96.82%\\n\",\n      \"#1511: 96.83%\\n\",\n      \"#1512: 96.83%\\n\",\n      \"#1513: 96.83%\\n\",\n      \"#1514: 96.83%\\n\",\n      \"#1515: 96.83%\\n\",\n      \"#1516: 96.84%\\n\",\n      \"#1517: 96.84%\\n\",\n      \"#1518: 96.84%\\n\",\n      \"#1519: 96.84%\\n\",\n      \"#1520: 96.84%\\n\",\n      \"#1521: 96.85%\\n\",\n      \"#1522: 96.85%\\n\",\n      \"#1523: 96.85%\\n\",\n      \"#1524: 96.85%\\n\",\n      \"#1525: 96.85%\\n\",\n      \"#1526: 96.86%\\n\",\n      \"#1527: 96.79%\\n\",\n      \"#1528: 96.80%\\n\",\n      \"#1529: 96.80%\\n\",\n      \"#1530: 96.73%\\n\",\n      \"#1531: 96.74%\\n\",\n      \"#1532: 96.74%\\n\",\n      \"#1533: 96.74%\\n\",\n      \"#1534: 96.74%\\n\",\n      \"#1535: 96.74%\\n\",\n      \"#1536: 96.75%\\n\",\n      \"#1537: 96.75%\\n\",\n      \"#1538: 96.75%\\n\",\n      \"#1539: 96.75%\\n\",\n      \"#1540: 96.76%\\n\",\n      \"#1541: 96.76%\\n\",\n      \"#1542: 96.76%\\n\",\n      \"#1543: 96.76%\\n\",\n      \"#1544: 96.76%\\n\",\n      \"#1545: 96.77%\\n\",\n      \"#1546: 96.77%\\n\",\n      \"#1547: 96.77%\\n\",\n      \"#1548: 96.77%\\n\",\n      \"#1549: 96.77%\\n\",\n      \"#1550: 96.78%\\n\",\n      \"#1551: 96.78%\\n\",\n      \"#1552: 96.78%\\n\",\n      \"#1553: 96.72%\\n\",\n      \"#1554: 96.72%\\n\",\n      \"#1555: 96.72%\\n\",\n      \"#1556: 96.72%\\n\",\n      \"#1557: 96.73%\\n\",\n      \"#1558: 96.73%\\n\",\n      \"#1559: 96.67%\\n\",\n      \"#1560: 96.67%\\n\",\n      \"#1561: 96.67%\\n\",\n      \"#1562: 96.67%\\n\",\n      \"#1563: 96.68%\\n\",\n      \"#1564: 96.68%\\n\",\n      \"#1565: 96.68%\\n\",\n      \"#1566: 96.68%\\n\",\n      \"#1567: 96.68%\\n\",\n      \"#1568: 96.69%\\n\",\n      \"#1569: 96.69%\\n\",\n      \"#1570: 96.69%\\n\",\n      \"#1571: 96.69%\\n\",\n      \"#1572: 96.69%\\n\",\n      \"#1573: 96.70%\\n\",\n      \"#1574: 96.70%\\n\",\n      \"#1575: 96.70%\\n\",\n      \"#1576: 96.70%\\n\",\n      \"#1577: 96.70%\\n\",\n      \"#1578: 96.71%\\n\",\n      \"#1579: 96.71%\\n\",\n      \"#1580: 96.71%\\n\",\n      \"#1581: 96.71%\\n\",\n      \"#1582: 96.72%\\n\",\n      \"#1583: 96.72%\\n\",\n      \"#1584: 96.72%\\n\",\n      \"#1585: 96.72%\\n\",\n      \"#1586: 96.72%\\n\",\n      \"#1587: 96.73%\\n\",\n      \"#1588: 96.73%\\n\",\n      \"#1589: 96.73%\\n\",\n      \"#1590: 96.73%\\n\",\n      \"#1591: 96.73%\\n\",\n      \"#1592: 96.74%\\n\",\n      \"#1593: 96.74%\\n\",\n      \"#1594: 96.74%\\n\",\n      \"#1595: 96.74%\\n\",\n      \"#1596: 96.74%\\n\",\n      \"#1597: 96.75%\\n\",\n      \"#1598: 96.75%\\n\",\n      \"#1599: 96.75%\\n\",\n      \"#1600: 96.75%\\n\",\n      \"#1601: 96.75%\\n\",\n      \"#1602: 96.76%\\n\",\n      \"#1603: 96.76%\\n\",\n      \"#1604: 96.76%\\n\",\n      \"#1605: 96.76%\\n\",\n      \"#1606: 96.76%\\n\",\n      \"#1607: 96.70%\\n\",\n      \"#1608: 96.71%\\n\",\n      \"#1609: 96.71%\\n\",\n      \"#1610: 96.71%\\n\",\n      \"#1611: 96.65%\\n\",\n      \"#1612: 96.65%\\n\",\n      \"#1613: 96.65%\\n\",\n      \"#1614: 96.66%\\n\",\n      \"#1615: 96.66%\\n\",\n      \"#1616: 96.66%\\n\",\n      \"#1617: 96.66%\\n\",\n      \"#1618: 96.66%\\n\",\n      \"#1619: 96.67%\\n\",\n      \"#1620: 96.67%\\n\",\n      \"#1621: 96.61%\\n\",\n      \"#1622: 96.61%\\n\",\n      \"#1623: 96.61%\\n\",\n      \"#1624: 96.62%\\n\",\n      \"#1625: 96.62%\\n\",\n      \"#1626: 96.62%\\n\",\n      \"#1627: 96.62%\\n\",\n      \"#1628: 96.62%\\n\",\n      \"#1629: 96.63%\\n\",\n      \"#1630: 96.63%\\n\",\n      \"#1631: 96.63%\\n\",\n      \"#1632: 96.63%\\n\",\n      \"#1633: 96.63%\\n\",\n      \"#1634: 96.64%\\n\",\n      \"#1635: 96.64%\\n\",\n      \"#1636: 96.64%\\n\",\n      \"#1637: 96.64%\\n\",\n      \"#1638: 96.64%\\n\",\n      \"#1639: 96.65%\\n\",\n      \"#1640: 96.59%\\n\",\n      \"#1641: 96.59%\\n\",\n      \"#1642: 96.59%\\n\",\n      \"#1643: 96.59%\\n\",\n      \"#1644: 96.60%\\n\",\n      \"#1645: 96.60%\\n\",\n      \"#1646: 96.60%\\n\",\n      \"#1647: 96.60%\\n\",\n      \"#1648: 96.60%\\n\",\n      \"#1649: 96.61%\\n\",\n      \"#1650: 96.61%\\n\",\n      \"#1651: 96.61%\\n\",\n      \"#1652: 96.61%\\n\",\n      \"#1653: 96.61%\\n\",\n      \"#1654: 96.62%\\n\",\n      \"#1655: 96.62%\\n\",\n      \"#1656: 96.62%\\n\",\n      \"#1657: 96.62%\\n\",\n      \"#1658: 96.62%\\n\",\n      \"#1659: 96.63%\\n\",\n      \"#1660: 96.63%\\n\",\n      \"#1661: 96.63%\\n\",\n      \"#1662: 96.63%\\n\",\n      \"#1663: 96.63%\\n\",\n      \"#1664: 96.64%\\n\",\n      \"#1665: 96.64%\\n\",\n      \"#1666: 96.64%\\n\",\n      \"#1667: 96.64%\\n\",\n      \"#1668: 96.64%\\n\",\n      \"#1669: 96.65%\\n\",\n      \"#1670: 96.65%\\n\",\n      \"#1671: 96.65%\\n\",\n      \"#1672: 96.65%\\n\",\n      \"#1673: 96.65%\\n\",\n      \"#1674: 96.66%\\n\",\n      \"#1675: 96.66%\\n\",\n      \"#1676: 96.66%\\n\",\n      \"#1677: 96.66%\\n\",\n      \"#1678: 96.66%\\n\",\n      \"#1679: 96.67%\\n\",\n      \"#1680: 96.67%\\n\",\n      \"#1681: 96.61%\\n\",\n      \"#1682: 96.61%\\n\",\n      \"#1683: 96.62%\\n\",\n      \"#1684: 96.62%\\n\",\n      \"#1685: 96.62%\\n\",\n      \"#1686: 96.56%\\n\",\n      \"#1687: 96.56%\\n\",\n      \"#1688: 96.57%\\n\",\n      \"#1689: 96.57%\\n\",\n      \"#1690: 96.57%\\n\",\n      \"#1691: 96.57%\\n\",\n      \"#1692: 96.57%\\n\",\n      \"#1693: 96.58%\\n\",\n      \"#1694: 96.58%\\n\",\n      \"#1695: 96.58%\\n\",\n      \"#1696: 96.58%\\n\",\n      \"#1697: 96.58%\\n\",\n      \"#1698: 96.59%\\n\",\n      \"#1699: 96.59%\\n\",\n      \"#1700: 96.59%\\n\",\n      \"#1701: 96.59%\\n\",\n      \"#1702: 96.59%\\n\",\n      \"#1703: 96.60%\\n\",\n      \"#1704: 96.60%\\n\",\n      \"#1705: 96.60%\\n\",\n      \"#1706: 96.60%\\n\",\n      \"#1707: 96.60%\\n\",\n      \"#1708: 96.61%\\n\",\n      \"#1709: 96.55%\\n\",\n      \"#1710: 96.55%\\n\",\n      \"#1711: 96.55%\\n\",\n      \"#1712: 96.56%\\n\",\n      \"#1713: 96.56%\\n\",\n      \"#1714: 96.56%\\n\",\n      \"#1715: 96.56%\\n\",\n      \"#1716: 96.56%\\n\",\n      \"#1717: 96.51%\\n\",\n      \"#1718: 96.51%\\n\",\n      \"#1719: 96.51%\\n\",\n      \"#1720: 96.51%\\n\",\n      \"#1721: 96.52%\\n\",\n      \"#1722: 96.52%\\n\",\n      \"#1723: 96.52%\\n\",\n      \"#1724: 96.52%\\n\",\n      \"#1725: 96.52%\\n\",\n      \"#1726: 96.53%\\n\",\n      \"#1727: 96.53%\\n\",\n      \"#1728: 96.53%\\n\",\n      \"#1729: 96.53%\\n\",\n      \"#1730: 96.53%\\n\",\n      \"#1731: 96.54%\\n\",\n      \"#1732: 96.54%\\n\",\n      \"#1733: 96.54%\\n\",\n      \"#1734: 96.54%\\n\",\n      \"#1735: 96.54%\\n\",\n      \"#1736: 96.55%\\n\",\n      \"#1737: 96.49%\\n\",\n      \"#1738: 96.49%\\n\",\n      \"#1739: 96.49%\\n\",\n      \"#1740: 96.50%\\n\",\n      \"#1741: 96.50%\\n\",\n      \"#1742: 96.50%\\n\",\n      \"#1743: 96.50%\\n\",\n      \"#1744: 96.50%\\n\",\n      \"#1745: 96.51%\\n\",\n      \"#1746: 96.51%\\n\",\n      \"#1747: 96.45%\\n\",\n      \"#1748: 96.46%\\n\",\n      \"#1749: 96.46%\\n\",\n      \"#1750: 96.46%\\n\",\n      \"#1751: 96.46%\\n\",\n      \"#1752: 96.46%\\n\",\n      \"#1753: 96.47%\\n\",\n      \"#1754: 96.41%\\n\",\n      \"#1755: 96.41%\\n\",\n      \"#1756: 96.41%\\n\",\n      \"#1757: 96.42%\\n\",\n      \"#1758: 96.42%\\n\",\n      \"#1759: 96.42%\\n\",\n      \"#1760: 96.42%\\n\",\n      \"#1761: 96.42%\\n\",\n      \"#1762: 96.43%\\n\",\n      \"#1763: 96.43%\\n\",\n      \"#1764: 96.43%\\n\",\n      \"#1765: 96.43%\\n\",\n      \"#1766: 96.43%\\n\",\n      \"#1767: 96.44%\\n\",\n      \"#1768: 96.44%\\n\",\n      \"#1769: 96.44%\\n\",\n      \"#1770: 96.44%\\n\",\n      \"#1771: 96.44%\\n\",\n      \"#1772: 96.45%\\n\",\n      \"#1773: 96.45%\\n\",\n      \"#1774: 96.45%\\n\",\n      \"#1775: 96.45%\\n\",\n      \"#1776: 96.45%\\n\",\n      \"#1777: 96.46%\\n\",\n      \"#1778: 96.46%\\n\",\n      \"#1779: 96.46%\\n\",\n      \"#1780: 96.46%\\n\",\n      \"#1781: 96.46%\\n\",\n      \"#1782: 96.47%\\n\",\n      \"#1783: 96.47%\\n\",\n      \"#1784: 96.47%\\n\",\n      \"#1785: 96.47%\\n\",\n      \"#1786: 96.47%\\n\",\n      \"#1787: 96.48%\\n\",\n      \"#1788: 96.48%\\n\",\n      \"#1789: 96.48%\\n\",\n      \"#1790: 96.48%\\n\",\n      \"#1791: 96.48%\\n\",\n      \"#1792: 96.49%\\n\",\n      \"#1793: 96.49%\\n\",\n      \"#1794: 96.49%\\n\",\n      \"#1795: 96.49%\\n\",\n      \"#1796: 96.49%\\n\",\n      \"#1797: 96.50%\\n\",\n      \"#1798: 96.50%\\n\",\n      \"#1799: 96.50%\\n\",\n      \"#1800: 96.50%\\n\",\n      \"#1801: 96.50%\\n\",\n      \"#1802: 96.51%\\n\",\n      \"#1803: 96.51%\\n\",\n      \"#1804: 96.51%\\n\",\n      \"#1805: 96.51%\\n\",\n      \"#1806: 96.51%\\n\",\n      \"#1807: 96.52%\\n\",\n      \"#1808: 96.52%\\n\",\n      \"#1809: 96.52%\\n\",\n      \"#1810: 96.52%\\n\",\n      \"#1811: 96.52%\\n\",\n      \"#1812: 96.53%\\n\",\n      \"#1813: 96.53%\\n\",\n      \"#1814: 96.53%\\n\",\n      \"#1815: 96.53%\\n\",\n      \"#1816: 96.53%\\n\",\n      \"#1817: 96.53%\\n\",\n      \"#1818: 96.54%\\n\",\n      \"#1819: 96.54%\\n\",\n      \"#1820: 96.54%\\n\",\n      \"#1821: 96.54%\\n\",\n      \"#1822: 96.54%\\n\",\n      \"#1823: 96.55%\\n\",\n      \"#1824: 96.55%\\n\",\n      \"#1825: 96.55%\\n\",\n      \"#1826: 96.55%\\n\",\n      \"#1827: 96.55%\\n\",\n      \"#1828: 96.56%\\n\",\n      \"#1829: 96.56%\\n\",\n      \"#1830: 96.56%\\n\",\n      \"#1831: 96.56%\\n\",\n      \"#1832: 96.56%\\n\",\n      \"#1833: 96.56%\\n\",\n      \"#1834: 96.57%\\n\",\n      \"#1835: 96.57%\\n\",\n      \"#1836: 96.57%\\n\",\n      \"#1837: 96.57%\\n\",\n      \"#1838: 96.57%\\n\",\n      \"#1839: 96.58%\\n\",\n      \"#1840: 96.58%\\n\",\n      \"#1841: 96.58%\\n\",\n      \"#1842: 96.58%\\n\",\n      \"#1843: 96.58%\\n\",\n      \"#1844: 96.59%\\n\",\n      \"#1845: 96.59%\\n\",\n      \"#1846: 96.59%\\n\",\n      \"#1847: 96.59%\\n\",\n      \"#1848: 96.59%\\n\",\n      \"#1849: 96.59%\\n\",\n      \"#1850: 96.60%\\n\",\n      \"#1851: 96.60%\\n\",\n      \"#1852: 96.60%\\n\",\n      \"#1853: 96.60%\\n\",\n      \"#1854: 96.60%\\n\",\n      \"#1855: 96.61%\\n\",\n      \"#1856: 96.61%\\n\",\n      \"#1857: 96.61%\\n\",\n      \"#1858: 96.61%\\n\",\n      \"#1859: 96.61%\\n\",\n      \"#1860: 96.61%\\n\",\n      \"#1861: 96.62%\\n\",\n      \"#1862: 96.62%\\n\",\n      \"#1863: 96.62%\\n\",\n      \"#1864: 96.62%\\n\",\n      \"#1865: 96.62%\\n\",\n      \"#1866: 96.63%\\n\",\n      \"#1867: 96.63%\\n\",\n      \"#1868: 96.63%\\n\",\n      \"#1869: 96.63%\\n\",\n      \"#1870: 96.63%\\n\",\n      \"#1871: 96.63%\\n\",\n      \"#1872: 96.64%\\n\",\n      \"#1873: 96.64%\\n\",\n      \"#1874: 96.64%\\n\",\n      \"#1875: 96.64%\\n\",\n      \"#1876: 96.64%\\n\",\n      \"#1877: 96.65%\\n\",\n      \"#1878: 96.65%\\n\",\n      \"#1879: 96.65%\\n\",\n      \"#1880: 96.65%\\n\",\n      \"#1881: 96.65%\\n\",\n      \"#1882: 96.65%\\n\",\n      \"#1883: 96.60%\\n\",\n      \"#1884: 96.60%\\n\",\n      \"#1885: 96.61%\\n\",\n      \"#1886: 96.61%\\n\",\n      \"#1887: 96.61%\\n\",\n      \"#1888: 96.61%\\n\",\n      \"#1889: 96.61%\\n\",\n      \"#1890: 96.62%\\n\",\n      \"#1891: 96.62%\\n\",\n      \"#1892: 96.62%\\n\",\n      \"#1893: 96.62%\\n\",\n      \"#1894: 96.62%\\n\",\n      \"#1895: 96.62%\\n\",\n      \"#1896: 96.63%\\n\",\n      \"#1897: 96.63%\\n\",\n      \"#1898: 96.63%\\n\",\n      \"#1899: 96.63%\\n\",\n      \"#1900: 96.63%\\n\",\n      \"#1901: 96.58%\\n\",\n      \"#1902: 96.58%\\n\",\n      \"#1903: 96.59%\\n\",\n      \"#1904: 96.59%\\n\",\n      \"#1905: 96.59%\\n\",\n      \"#1906: 96.59%\\n\",\n      \"#1907: 96.59%\\n\",\n      \"#1908: 96.60%\\n\",\n      \"#1909: 96.60%\\n\",\n      \"#1910: 96.60%\\n\",\n      \"#1911: 96.60%\\n\",\n      \"#1912: 96.60%\\n\",\n      \"#1913: 96.60%\\n\",\n      \"#1914: 96.61%\\n\",\n      \"#1915: 96.61%\\n\",\n      \"#1916: 96.61%\\n\",\n      \"#1917: 96.61%\\n\",\n      \"#1918: 96.61%\\n\",\n      \"#1919: 96.61%\\n\",\n      \"#1920: 96.62%\\n\",\n      \"#1921: 96.62%\\n\",\n      \"#1922: 96.62%\\n\",\n      \"#1923: 96.62%\\n\",\n      \"#1924: 96.62%\\n\",\n      \"#1925: 96.63%\\n\",\n      \"#1926: 96.63%\\n\",\n      \"#1927: 96.63%\\n\",\n      \"#1928: 96.63%\\n\",\n      \"#1929: 96.63%\\n\",\n      \"#1930: 96.63%\\n\",\n      \"#1931: 96.64%\\n\",\n      \"#1932: 96.64%\\n\",\n      \"#1933: 96.64%\\n\",\n      \"#1934: 96.64%\\n\",\n      \"#1935: 96.64%\\n\",\n      \"#1936: 96.64%\\n\",\n      \"#1937: 96.65%\\n\",\n      \"#1938: 96.65%\\n\",\n      \"#1939: 96.65%\\n\",\n      \"#1940: 96.65%\\n\",\n      \"#1941: 96.65%\\n\",\n      \"#1942: 96.65%\\n\",\n      \"#1943: 96.66%\\n\",\n      \"#1944: 96.66%\\n\",\n      \"#1945: 96.66%\\n\",\n      \"#1946: 96.66%\\n\",\n      \"#1947: 96.66%\\n\",\n      \"#1948: 96.66%\\n\",\n      \"#1949: 96.67%\\n\",\n      \"#1950: 96.67%\\n\",\n      \"#1951: 96.67%\\n\",\n      \"#1952: 96.67%\\n\",\n      \"#1953: 96.67%\\n\",\n      \"#1954: 96.68%\\n\",\n      \"#1955: 96.63%\\n\",\n      \"#1956: 96.63%\\n\",\n      \"#1957: 96.63%\\n\",\n      \"#1958: 96.63%\\n\",\n      \"#1959: 96.63%\\n\",\n      \"#1960: 96.63%\\n\",\n      \"#1961: 96.64%\\n\",\n      \"#1962: 96.64%\\n\",\n      \"#1963: 96.64%\\n\",\n      \"#1964: 96.64%\\n\",\n      \"#1965: 96.64%\\n\",\n      \"#1966: 96.64%\\n\",\n      \"#1967: 96.65%\\n\",\n      \"#1968: 96.65%\\n\",\n      \"#1969: 96.65%\\n\",\n      \"#1970: 96.65%\\n\",\n      \"#1971: 96.65%\\n\",\n      \"#1972: 96.65%\\n\",\n      \"#1973: 96.66%\\n\",\n      \"#1974: 96.66%\\n\",\n      \"#1975: 96.66%\\n\",\n      \"#1976: 96.66%\\n\",\n      \"#1977: 96.66%\\n\",\n      \"#1978: 96.66%\\n\",\n      \"#1979: 96.67%\\n\",\n      \"#1980: 96.67%\\n\",\n      \"#1981: 96.67%\\n\",\n      \"#1982: 96.67%\\n\",\n      \"#1983: 96.67%\\n\",\n      \"#1984: 96.68%\\n\",\n      \"#1985: 96.68%\\n\",\n      \"#1986: 96.68%\\n\",\n      \"#1987: 96.68%\\n\",\n      \"#1988: 96.68%\\n\",\n      \"#1989: 96.68%\\n\",\n      \"#1990: 96.69%\\n\",\n      \"#1991: 96.69%\\n\",\n      \"#1992: 96.69%\\n\",\n      \"#1993: 96.69%\\n\",\n      \"#1994: 96.69%\\n\",\n      \"#1995: 96.69%\\n\",\n      \"#1996: 96.70%\\n\",\n      \"#1997: 96.70%\\n\",\n      \"#1998: 96.70%\\n\",\n      \"#1999: 96.70%\\n\",\n      \"#2000: 96.70%\\n\",\n      \"#2001: 96.70%\\n\",\n      \"#2002: 96.70%\\n\",\n      \"#2003: 96.71%\\n\",\n      \"#2004: 96.71%\\n\",\n      \"#2005: 96.71%\\n\",\n      \"#2006: 96.71%\\n\",\n      \"#2007: 96.71%\\n\",\n      \"#2008: 96.71%\\n\",\n      \"#2009: 96.72%\\n\",\n      \"#2010: 96.72%\\n\",\n      \"#2011: 96.72%\\n\",\n      \"#2012: 96.72%\\n\",\n      \"#2013: 96.72%\\n\",\n      \"#2014: 96.72%\\n\",\n      \"#2015: 96.73%\\n\",\n      \"#2016: 96.73%\\n\",\n      \"#2017: 96.73%\\n\",\n      \"#2018: 96.68%\\n\",\n      \"#2019: 96.68%\\n\",\n      \"#2020: 96.68%\\n\",\n      \"#2021: 96.69%\\n\",\n      \"#2022: 96.69%\\n\",\n      \"#2023: 96.69%\\n\",\n      \"#2024: 96.69%\\n\",\n      \"#2025: 96.64%\\n\",\n      \"#2026: 96.65%\\n\",\n      \"#2027: 96.65%\\n\",\n      \"#2028: 96.65%\\n\",\n      \"#2029: 96.65%\\n\",\n      \"#2030: 96.65%\\n\",\n      \"#2031: 96.65%\\n\",\n      \"#2032: 96.66%\\n\",\n      \"#2033: 96.66%\\n\",\n      \"#2034: 96.66%\\n\",\n      \"#2035: 96.66%\\n\",\n      \"#2036: 96.66%\\n\",\n      \"#2037: 96.66%\\n\",\n      \"#2038: 96.67%\\n\",\n      \"#2039: 96.67%\\n\",\n      \"#2040: 96.67%\\n\",\n      \"#2041: 96.67%\\n\",\n      \"#2042: 96.67%\\n\",\n      \"#2043: 96.62%\\n\",\n      \"#2044: 96.63%\\n\",\n      \"#2045: 96.63%\\n\",\n      \"#2046: 96.63%\\n\",\n      \"#2047: 96.63%\\n\",\n      \"#2048: 96.63%\\n\",\n      \"#2049: 96.63%\\n\",\n      \"#2050: 96.64%\\n\",\n      \"#2051: 96.64%\\n\",\n      \"#2052: 96.64%\\n\",\n      \"#2053: 96.64%\\n\",\n      \"#2054: 96.64%\\n\",\n      \"#2055: 96.64%\\n\",\n      \"#2056: 96.65%\\n\",\n      \"#2057: 96.65%\\n\",\n      \"#2058: 96.65%\\n\",\n      \"#2059: 96.65%\\n\",\n      \"#2060: 96.65%\\n\",\n      \"#2061: 96.65%\\n\",\n      \"#2062: 96.66%\\n\",\n      \"#2063: 96.66%\\n\",\n      \"#2064: 96.66%\\n\",\n      \"#2065: 96.66%\\n\",\n      \"#2066: 96.66%\\n\",\n      \"#2067: 96.66%\\n\",\n      \"#2068: 96.67%\\n\",\n      \"#2069: 96.67%\\n\",\n      \"#2070: 96.62%\\n\",\n      \"#2071: 96.62%\\n\",\n      \"#2072: 96.62%\\n\",\n      \"#2073: 96.62%\\n\",\n      \"#2074: 96.63%\\n\",\n      \"#2075: 96.63%\\n\",\n      \"#2076: 96.63%\\n\",\n      \"#2077: 96.63%\\n\",\n      \"#2078: 96.63%\\n\",\n      \"#2079: 96.63%\\n\",\n      \"#2080: 96.64%\\n\",\n      \"#2081: 96.64%\\n\",\n      \"#2082: 96.64%\\n\",\n      \"#2083: 96.64%\\n\",\n      \"#2084: 96.64%\\n\",\n      \"#2085: 96.64%\\n\",\n      \"#2086: 96.65%\\n\",\n      \"#2087: 96.65%\\n\",\n      \"#2088: 96.65%\\n\",\n      \"#2089: 96.65%\\n\",\n      \"#2090: 96.65%\\n\",\n      \"#2091: 96.65%\\n\",\n      \"#2092: 96.66%\\n\",\n      \"#2093: 96.66%\\n\",\n      \"#2094: 96.66%\\n\",\n      \"#2095: 96.66%\\n\",\n      \"#2096: 96.66%\\n\",\n      \"#2097: 96.66%\\n\",\n      \"#2098: 96.62%\\n\",\n      \"#2099: 96.62%\\n\",\n      \"#2100: 96.62%\\n\",\n      \"#2101: 96.62%\\n\",\n      \"#2102: 96.62%\\n\",\n      \"#2103: 96.63%\\n\",\n      \"#2104: 96.63%\\n\",\n      \"#2105: 96.63%\\n\",\n      \"#2106: 96.63%\\n\",\n      \"#2107: 96.63%\\n\",\n      \"#2108: 96.63%\\n\",\n      \"#2109: 96.59%\\n\",\n      \"#2110: 96.59%\\n\",\n      \"#2111: 96.59%\\n\",\n      \"#2112: 96.59%\\n\",\n      \"#2113: 96.59%\\n\",\n      \"#2114: 96.60%\\n\",\n      \"#2115: 96.60%\\n\",\n      \"#2116: 96.60%\\n\",\n      \"#2117: 96.60%\\n\",\n      \"#2118: 96.55%\\n\",\n      \"#2119: 96.56%\\n\",\n      \"#2120: 96.56%\\n\",\n      \"#2121: 96.56%\\n\",\n      \"#2122: 96.56%\\n\",\n      \"#2123: 96.56%\\n\",\n      \"#2124: 96.56%\\n\",\n      \"#2125: 96.57%\\n\",\n      \"#2126: 96.57%\\n\",\n      \"#2127: 96.57%\\n\",\n      \"#2128: 96.57%\\n\",\n      \"#2129: 96.57%\\n\",\n      \"#2130: 96.53%\\n\",\n      \"#2131: 96.53%\\n\",\n      \"#2132: 96.53%\\n\",\n      \"#2133: 96.53%\\n\",\n      \"#2134: 96.53%\\n\",\n      \"#2135: 96.49%\\n\",\n      \"#2136: 96.49%\\n\",\n      \"#2137: 96.49%\\n\",\n      \"#2138: 96.49%\\n\",\n      \"#2139: 96.50%\\n\",\n      \"#2140: 96.50%\\n\",\n      \"#2141: 96.50%\\n\",\n      \"#2142: 96.50%\\n\",\n      \"#2143: 96.50%\\n\",\n      \"#2144: 96.50%\\n\",\n      \"#2145: 96.51%\\n\",\n      \"#2146: 96.51%\\n\",\n      \"#2147: 96.51%\\n\",\n      \"#2148: 96.51%\\n\",\n      \"#2149: 96.51%\\n\",\n      \"#2150: 96.51%\\n\",\n      \"#2151: 96.51%\\n\",\n      \"#2152: 96.52%\\n\",\n      \"#2153: 96.52%\\n\",\n      \"#2154: 96.52%\\n\",\n      \"#2155: 96.52%\\n\",\n      \"#2156: 96.52%\\n\",\n      \"#2157: 96.52%\\n\",\n      \"#2158: 96.53%\\n\",\n      \"#2159: 96.53%\\n\",\n      \"#2160: 96.53%\\n\",\n      \"#2161: 96.53%\\n\",\n      \"#2162: 96.53%\\n\",\n      \"#2163: 96.53%\\n\",\n      \"#2164: 96.54%\\n\",\n      \"#2165: 96.54%\\n\",\n      \"#2166: 96.54%\\n\",\n      \"#2167: 96.54%\\n\",\n      \"#2168: 96.54%\\n\",\n      \"#2169: 96.54%\\n\",\n      \"#2170: 96.55%\\n\",\n      \"#2171: 96.55%\\n\",\n      \"#2172: 96.55%\\n\",\n      \"#2173: 96.55%\\n\",\n      \"#2174: 96.55%\\n\",\n      \"#2175: 96.55%\\n\",\n      \"#2176: 96.55%\\n\",\n      \"#2177: 96.56%\\n\",\n      \"#2178: 96.56%\\n\",\n      \"#2179: 96.56%\\n\",\n      \"#2180: 96.56%\\n\",\n      \"#2181: 96.56%\\n\",\n      \"#2182: 96.56%\\n\",\n      \"#2183: 96.57%\\n\",\n      \"#2184: 96.57%\\n\",\n      \"#2185: 96.52%\\n\",\n      \"#2186: 96.48%\\n\",\n      \"#2187: 96.48%\\n\",\n      \"#2188: 96.48%\\n\",\n      \"#2189: 96.44%\\n\",\n      \"#2190: 96.44%\\n\",\n      \"#2191: 96.44%\\n\",\n      \"#2192: 96.44%\\n\",\n      \"#2193: 96.44%\\n\",\n      \"#2194: 96.45%\\n\",\n      \"#2195: 96.45%\\n\",\n      \"#2196: 96.45%\\n\",\n      \"#2197: 96.45%\\n\",\n      \"#2198: 96.45%\\n\",\n      \"#2199: 96.45%\\n\",\n      \"#2200: 96.46%\\n\",\n      \"#2201: 96.46%\\n\",\n      \"#2202: 96.46%\\n\",\n      \"#2203: 96.46%\\n\",\n      \"#2204: 96.46%\\n\",\n      \"#2205: 96.46%\\n\",\n      \"#2206: 96.47%\\n\",\n      \"#2207: 96.47%\\n\",\n      \"#2208: 96.47%\\n\",\n      \"#2209: 96.47%\\n\",\n      \"#2210: 96.47%\\n\",\n      \"#2211: 96.47%\\n\",\n      \"#2212: 96.48%\\n\",\n      \"#2213: 96.48%\\n\",\n      \"#2214: 96.48%\\n\",\n      \"#2215: 96.48%\\n\",\n      \"#2216: 96.48%\\n\",\n      \"#2217: 96.48%\\n\",\n      \"#2218: 96.48%\\n\",\n      \"#2219: 96.49%\\n\",\n      \"#2220: 96.49%\\n\",\n      \"#2221: 96.49%\\n\",\n      \"#2222: 96.49%\\n\",\n      \"#2223: 96.49%\\n\",\n      \"#2224: 96.49%\\n\",\n      \"#2225: 96.50%\\n\",\n      \"#2226: 96.50%\\n\",\n      \"#2227: 96.50%\\n\",\n      \"#2228: 96.50%\\n\",\n      \"#2229: 96.50%\\n\",\n      \"#2230: 96.50%\\n\",\n      \"#2231: 96.51%\\n\",\n      \"#2232: 96.51%\\n\",\n      \"#2233: 96.51%\\n\",\n      \"#2234: 96.51%\\n\",\n      \"#2235: 96.51%\\n\",\n      \"#2236: 96.51%\\n\",\n      \"#2237: 96.51%\\n\",\n      \"#2238: 96.52%\\n\",\n      \"#2239: 96.52%\\n\",\n      \"#2240: 96.52%\\n\",\n      \"#2241: 96.52%\\n\",\n      \"#2242: 96.52%\\n\",\n      \"#2243: 96.52%\\n\",\n      \"#2244: 96.53%\\n\",\n      \"#2245: 96.53%\\n\",\n      \"#2246: 96.53%\\n\",\n      \"#2247: 96.53%\\n\",\n      \"#2248: 96.53%\\n\",\n      \"#2249: 96.53%\\n\",\n      \"#2250: 96.53%\\n\",\n      \"#2251: 96.54%\\n\",\n      \"#2252: 96.54%\\n\",\n      \"#2253: 96.54%\\n\",\n      \"#2254: 96.54%\\n\",\n      \"#2255: 96.54%\\n\",\n      \"#2256: 96.54%\\n\",\n      \"#2257: 96.55%\\n\",\n      \"#2258: 96.55%\\n\",\n      \"#2259: 96.55%\\n\",\n      \"#2260: 96.55%\\n\",\n      \"#2261: 96.55%\\n\",\n      \"#2262: 96.55%\\n\",\n      \"#2263: 96.55%\\n\",\n      \"#2264: 96.56%\\n\",\n      \"#2265: 96.56%\\n\",\n      \"#2266: 96.52%\\n\",\n      \"#2267: 96.52%\\n\",\n      \"#2268: 96.52%\\n\",\n      \"#2269: 96.52%\\n\",\n      \"#2270: 96.52%\\n\",\n      \"#2271: 96.52%\\n\",\n      \"#2272: 96.52%\\n\",\n      \"#2273: 96.53%\\n\",\n      \"#2274: 96.53%\\n\",\n      \"#2275: 96.53%\\n\",\n      \"#2276: 96.53%\\n\",\n      \"#2277: 96.53%\\n\",\n      \"#2278: 96.53%\\n\",\n      \"#2279: 96.54%\\n\",\n      \"#2280: 96.49%\\n\",\n      \"#2281: 96.49%\\n\",\n      \"#2282: 96.50%\\n\",\n      \"#2283: 96.50%\\n\",\n      \"#2284: 96.50%\\n\",\n      \"#2285: 96.50%\\n\",\n      \"#2286: 96.50%\\n\",\n      \"#2287: 96.50%\\n\",\n      \"#2288: 96.51%\\n\",\n      \"#2289: 96.51%\\n\",\n      \"#2290: 96.51%\\n\",\n      \"#2291: 96.51%\\n\",\n      \"#2292: 96.51%\\n\",\n      \"#2293: 96.51%\\n\",\n      \"#2294: 96.51%\\n\",\n      \"#2295: 96.52%\\n\",\n      \"#2296: 96.52%\\n\",\n      \"#2297: 96.52%\\n\",\n      \"#2298: 96.52%\\n\",\n      \"#2299: 96.52%\\n\",\n      \"#2300: 96.52%\\n\",\n      \"#2301: 96.52%\\n\",\n      \"#2302: 96.53%\\n\",\n      \"#2303: 96.53%\\n\",\n      \"#2304: 96.53%\\n\",\n      \"#2305: 96.53%\\n\",\n      \"#2306: 96.53%\\n\",\n      \"#2307: 96.53%\\n\",\n      \"#2308: 96.49%\\n\",\n      \"#2309: 96.49%\\n\",\n      \"#2310: 96.50%\\n\",\n      \"#2311: 96.50%\\n\",\n      \"#2312: 96.50%\\n\",\n      \"#2313: 96.50%\\n\",\n      \"#2314: 96.50%\\n\",\n      \"#2315: 96.50%\\n\",\n      \"#2316: 96.50%\\n\",\n      \"#2317: 96.51%\\n\",\n      \"#2318: 96.51%\\n\",\n      \"#2319: 96.51%\\n\",\n      \"#2320: 96.51%\\n\",\n      \"#2321: 96.51%\\n\",\n      \"#2322: 96.51%\\n\",\n      \"#2323: 96.51%\\n\",\n      \"#2324: 96.52%\\n\",\n      \"#2325: 96.52%\\n\",\n      \"#2326: 96.52%\\n\",\n      \"#2327: 96.52%\\n\",\n      \"#2328: 96.52%\\n\",\n      \"#2329: 96.52%\\n\",\n      \"#2330: 96.53%\\n\",\n      \"#2331: 96.53%\\n\",\n      \"#2332: 96.53%\\n\",\n      \"#2333: 96.53%\\n\",\n      \"#2334: 96.53%\\n\",\n      \"#2335: 96.53%\\n\",\n      \"#2336: 96.53%\\n\",\n      \"#2337: 96.54%\\n\",\n      \"#2338: 96.54%\\n\",\n      \"#2339: 96.54%\\n\",\n      \"#2340: 96.54%\\n\",\n      \"#2341: 96.54%\\n\",\n      \"#2342: 96.54%\\n\",\n      \"#2343: 96.54%\\n\",\n      \"#2344: 96.55%\\n\",\n      \"#2345: 96.55%\\n\",\n      \"#2346: 96.55%\\n\",\n      \"#2347: 96.55%\\n\",\n      \"#2348: 96.55%\\n\",\n      \"#2349: 96.55%\\n\",\n      \"#2350: 96.55%\\n\",\n      \"#2351: 96.56%\\n\",\n      \"#2352: 96.56%\\n\",\n      \"#2353: 96.56%\\n\",\n      \"#2354: 96.56%\\n\",\n      \"#2355: 96.56%\\n\",\n      \"#2356: 96.56%\\n\",\n      \"#2357: 96.56%\\n\",\n      \"#2358: 96.57%\\n\",\n      \"#2359: 96.57%\\n\",\n      \"#2360: 96.57%\\n\",\n      \"#2361: 96.57%\\n\",\n      \"#2362: 96.57%\\n\",\n      \"#2363: 96.57%\\n\",\n      \"#2364: 96.58%\\n\",\n      \"#2365: 96.58%\\n\",\n      \"#2366: 96.58%\\n\",\n      \"#2367: 96.58%\\n\",\n      \"#2368: 96.58%\\n\",\n      \"#2369: 96.58%\\n\",\n      \"#2370: 96.58%\\n\",\n      \"#2371: 96.59%\\n\",\n      \"#2372: 96.59%\\n\",\n      \"#2373: 96.59%\\n\",\n      \"#2374: 96.59%\\n\",\n      \"#2375: 96.59%\\n\",\n      \"#2376: 96.59%\\n\",\n      \"#2377: 96.59%\\n\",\n      \"#2378: 96.60%\\n\",\n      \"#2379: 96.60%\\n\",\n      \"#2380: 96.60%\\n\",\n      \"#2381: 96.60%\\n\",\n      \"#2382: 96.60%\\n\",\n      \"#2383: 96.60%\\n\",\n      \"#2384: 96.60%\\n\",\n      \"#2385: 96.61%\\n\",\n      \"#2386: 96.61%\\n\",\n      \"#2387: 96.61%\\n\",\n      \"#2388: 96.61%\\n\",\n      \"#2389: 96.61%\\n\",\n      \"#2390: 96.61%\\n\",\n      \"#2391: 96.61%\\n\",\n      \"#2392: 96.62%\\n\",\n      \"#2393: 96.62%\\n\",\n      \"#2394: 96.62%\\n\",\n      \"#2395: 96.62%\\n\",\n      \"#2396: 96.62%\\n\",\n      \"#2397: 96.62%\\n\",\n      \"#2398: 96.62%\\n\",\n      \"#2399: 96.62%\\n\",\n      \"#2400: 96.63%\\n\",\n      \"#2401: 96.63%\\n\",\n      \"#2402: 96.63%\\n\",\n      \"#2403: 96.63%\\n\",\n      \"#2404: 96.63%\\n\",\n      \"#2405: 96.63%\\n\",\n      \"#2406: 96.63%\\n\",\n      \"#2407: 96.64%\\n\",\n      \"#2408: 96.64%\\n\",\n      \"#2409: 96.64%\\n\",\n      \"#2410: 96.64%\\n\",\n      \"#2411: 96.64%\\n\",\n      \"#2412: 96.64%\\n\",\n      \"#2413: 96.64%\\n\",\n      \"#2414: 96.65%\\n\",\n      \"#2415: 96.65%\\n\",\n      \"#2416: 96.65%\\n\",\n      \"#2417: 96.65%\\n\",\n      \"#2418: 96.65%\\n\",\n      \"#2419: 96.65%\\n\",\n      \"#2420: 96.65%\\n\",\n      \"#2421: 96.66%\\n\",\n      \"#2422: 96.66%\\n\",\n      \"#2423: 96.66%\\n\",\n      \"#2424: 96.66%\\n\",\n      \"#2425: 96.66%\\n\",\n      \"#2426: 96.66%\\n\",\n      \"#2427: 96.66%\\n\",\n      \"#2428: 96.67%\\n\",\n      \"#2429: 96.67%\\n\",\n      \"#2430: 96.67%\\n\",\n      \"#2431: 96.67%\\n\",\n      \"#2432: 96.67%\\n\",\n      \"#2433: 96.67%\\n\",\n      \"#2434: 96.67%\\n\",\n      \"#2435: 96.67%\\n\",\n      \"#2436: 96.68%\\n\",\n      \"#2437: 96.68%\\n\",\n      \"#2438: 96.68%\\n\",\n      \"#2439: 96.68%\\n\",\n      \"#2440: 96.68%\\n\",\n      \"#2441: 96.68%\\n\",\n      \"#2442: 96.68%\\n\",\n      \"#2443: 96.69%\\n\",\n      \"#2444: 96.69%\\n\",\n      \"#2445: 96.69%\\n\",\n      \"#2446: 96.69%\\n\",\n      \"#2447: 96.69%\\n\",\n      \"#2448: 96.69%\\n\",\n      \"#2449: 96.69%\\n\",\n      \"#2450: 96.70%\\n\",\n      \"#2451: 96.70%\\n\",\n      \"#2452: 96.70%\\n\",\n      \"#2453: 96.70%\\n\",\n      \"#2454: 96.66%\\n\",\n      \"#2455: 96.66%\\n\",\n      \"#2456: 96.66%\\n\",\n      \"#2457: 96.66%\\n\",\n      \"#2458: 96.67%\\n\",\n      \"#2459: 96.67%\\n\",\n      \"#2460: 96.67%\\n\",\n      \"#2461: 96.67%\\n\",\n      \"#2462: 96.63%\\n\",\n      \"#2463: 96.63%\\n\",\n      \"#2464: 96.63%\\n\",\n      \"#2465: 96.63%\\n\",\n      \"#2466: 96.64%\\n\",\n      \"#2467: 96.64%\\n\",\n      \"#2468: 96.64%\\n\",\n      \"#2469: 96.64%\\n\",\n      \"#2470: 96.64%\\n\",\n      \"#2471: 96.64%\\n\",\n      \"#2472: 96.64%\\n\",\n      \"#2473: 96.65%\\n\",\n      \"#2474: 96.65%\\n\",\n      \"#2475: 96.65%\\n\",\n      \"#2476: 96.65%\\n\",\n      \"#2477: 96.65%\\n\",\n      \"#2478: 96.65%\\n\",\n      \"#2479: 96.65%\\n\",\n      \"#2480: 96.65%\\n\",\n      \"#2481: 96.66%\\n\",\n      \"#2482: 96.66%\\n\",\n      \"#2483: 96.66%\\n\",\n      \"#2484: 96.66%\\n\",\n      \"#2485: 96.66%\\n\",\n      \"#2486: 96.66%\\n\",\n      \"#2487: 96.66%\\n\",\n      \"#2488: 96.63%\\n\",\n      \"#2489: 96.63%\\n\",\n      \"#2490: 96.63%\\n\",\n      \"#2491: 96.63%\\n\",\n      \"#2492: 96.63%\\n\",\n      \"#2493: 96.63%\\n\",\n      \"#2494: 96.63%\\n\",\n      \"#2495: 96.63%\\n\",\n      \"#2496: 96.64%\\n\",\n      \"#2497: 96.64%\\n\",\n      \"#2498: 96.64%\\n\",\n      \"#2499: 96.64%\\n\",\n      \"#2500: 96.64%\\n\",\n      \"#2501: 96.64%\\n\",\n      \"#2502: 96.64%\\n\",\n      \"#2503: 96.65%\\n\",\n      \"#2504: 96.65%\\n\",\n      \"#2505: 96.65%\\n\",\n      \"#2506: 96.65%\\n\",\n      \"#2507: 96.65%\\n\",\n      \"#2508: 96.65%\\n\",\n      \"#2509: 96.65%\\n\",\n      \"#2510: 96.65%\\n\",\n      \"#2511: 96.66%\\n\",\n      \"#2512: 96.66%\\n\",\n      \"#2513: 96.66%\\n\",\n      \"#2514: 96.66%\\n\",\n      \"#2515: 96.66%\\n\",\n      \"#2516: 96.66%\\n\",\n      \"#2517: 96.66%\\n\",\n      \"#2518: 96.67%\\n\",\n      \"#2519: 96.67%\\n\",\n      \"#2520: 96.67%\\n\",\n      \"#2521: 96.67%\\n\",\n      \"#2522: 96.67%\\n\",\n      \"#2523: 96.67%\\n\",\n      \"#2524: 96.67%\\n\",\n      \"#2525: 96.67%\\n\",\n      \"#2526: 96.68%\\n\",\n      \"#2527: 96.68%\\n\",\n      \"#2528: 96.68%\\n\",\n      \"#2529: 96.68%\\n\",\n      \"#2530: 96.68%\\n\",\n      \"#2531: 96.68%\\n\",\n      \"#2532: 96.68%\\n\",\n      \"#2533: 96.65%\\n\",\n      \"#2534: 96.61%\\n\",\n      \"#2535: 96.61%\\n\",\n      \"#2536: 96.61%\\n\",\n      \"#2537: 96.61%\\n\",\n      \"#2538: 96.61%\\n\",\n      \"#2539: 96.61%\\n\",\n      \"#2540: 96.62%\\n\",\n      \"#2541: 96.62%\\n\",\n      \"#2542: 96.62%\\n\",\n      \"#2543: 96.62%\\n\",\n      \"#2544: 96.62%\\n\",\n      \"#2545: 96.62%\\n\",\n      \"#2546: 96.62%\\n\",\n      \"#2547: 96.62%\\n\",\n      \"#2548: 96.63%\\n\",\n      \"#2549: 96.63%\\n\",\n      \"#2550: 96.63%\\n\",\n      \"#2551: 96.63%\\n\",\n      \"#2552: 96.63%\\n\",\n      \"#2553: 96.63%\\n\",\n      \"#2554: 96.63%\\n\",\n      \"#2555: 96.64%\\n\",\n      \"#2556: 96.64%\\n\",\n      \"#2557: 96.64%\\n\",\n      \"#2558: 96.64%\\n\",\n      \"#2559: 96.64%\\n\",\n      \"#2560: 96.60%\\n\",\n      \"#2561: 96.60%\\n\",\n      \"#2562: 96.61%\\n\",\n      \"#2563: 96.61%\\n\",\n      \"#2564: 96.61%\\n\",\n      \"#2565: 96.61%\\n\",\n      \"#2566: 96.61%\\n\",\n      \"#2567: 96.61%\\n\",\n      \"#2568: 96.61%\\n\",\n      \"#2569: 96.61%\\n\",\n      \"#2570: 96.62%\\n\",\n      \"#2571: 96.62%\\n\",\n      \"#2572: 96.62%\\n\",\n      \"#2573: 96.62%\\n\",\n      \"#2574: 96.62%\\n\",\n      \"#2575: 96.62%\\n\",\n      \"#2576: 96.62%\\n\",\n      \"#2577: 96.63%\\n\",\n      \"#2578: 96.63%\\n\",\n      \"#2579: 96.63%\\n\",\n      \"#2580: 96.63%\\n\",\n      \"#2581: 96.63%\\n\",\n      \"#2582: 96.63%\\n\",\n      \"#2583: 96.63%\\n\",\n      \"#2584: 96.63%\\n\",\n      \"#2585: 96.64%\\n\",\n      \"#2586: 96.64%\\n\",\n      \"#2587: 96.64%\\n\",\n      \"#2588: 96.64%\\n\",\n      \"#2589: 96.64%\\n\",\n      \"#2590: 96.64%\\n\",\n      \"#2591: 96.64%\\n\",\n      \"#2592: 96.64%\\n\",\n      \"#2593: 96.65%\\n\",\n      \"#2594: 96.61%\\n\",\n      \"#2595: 96.61%\\n\",\n      \"#2596: 96.61%\\n\",\n      \"#2597: 96.57%\\n\",\n      \"#2598: 96.58%\\n\",\n      \"#2599: 96.58%\\n\",\n      \"#2600: 96.58%\\n\",\n      \"#2601: 96.58%\\n\",\n      \"#2602: 96.58%\\n\",\n      \"#2603: 96.58%\\n\",\n      \"#2604: 96.58%\\n\",\n      \"#2605: 96.58%\\n\",\n      \"#2606: 96.59%\\n\",\n      \"#2607: 96.59%\\n\",\n      \"#2608: 96.59%\\n\",\n      \"#2609: 96.59%\\n\",\n      \"#2610: 96.59%\\n\",\n      \"#2611: 96.59%\\n\",\n      \"#2612: 96.59%\\n\",\n      \"#2613: 96.60%\\n\",\n      \"#2614: 96.60%\\n\",\n      \"#2615: 96.60%\\n\",\n      \"#2616: 96.60%\\n\",\n      \"#2617: 96.60%\\n\",\n      \"#2618: 96.60%\\n\",\n      \"#2619: 96.60%\\n\",\n      \"#2620: 96.60%\\n\",\n      \"#2621: 96.61%\\n\",\n      \"#2622: 96.61%\\n\",\n      \"#2623: 96.61%\\n\",\n      \"#2624: 96.61%\\n\",\n      \"#2625: 96.61%\\n\",\n      \"#2626: 96.61%\\n\",\n      \"#2627: 96.61%\\n\",\n      \"#2628: 96.61%\\n\",\n      \"#2629: 96.62%\\n\",\n      \"#2630: 96.62%\\n\",\n      \"#2631: 96.62%\\n\",\n      \"#2632: 96.62%\\n\",\n      \"#2633: 96.62%\\n\",\n      \"#2634: 96.62%\\n\",\n      \"#2635: 96.62%\\n\",\n      \"#2636: 96.59%\\n\",\n      \"#2637: 96.59%\\n\",\n      \"#2638: 96.59%\\n\",\n      \"#2639: 96.59%\\n\",\n      \"#2640: 96.59%\\n\",\n      \"#2641: 96.59%\\n\",\n      \"#2642: 96.59%\\n\",\n      \"#2643: 96.60%\\n\",\n      \"#2644: 96.60%\\n\",\n      \"#2645: 96.60%\\n\",\n      \"#2646: 96.60%\\n\",\n      \"#2647: 96.60%\\n\",\n      \"#2648: 96.60%\\n\",\n      \"#2649: 96.60%\\n\",\n      \"#2650: 96.61%\\n\",\n      \"#2651: 96.61%\\n\",\n      \"#2652: 96.61%\\n\",\n      \"#2653: 96.61%\\n\",\n      \"#2654: 96.57%\\n\",\n      \"#2655: 96.57%\\n\",\n      \"#2656: 96.58%\\n\",\n      \"#2657: 96.58%\\n\",\n      \"#2658: 96.58%\\n\",\n      \"#2659: 96.58%\\n\",\n      \"#2660: 96.58%\\n\",\n      \"#2661: 96.58%\\n\",\n      \"#2662: 96.58%\\n\",\n      \"#2663: 96.58%\\n\",\n      \"#2664: 96.59%\\n\",\n      \"#2665: 96.59%\\n\",\n      \"#2666: 96.59%\\n\",\n      \"#2667: 96.59%\\n\",\n      \"#2668: 96.59%\\n\",\n      \"#2669: 96.59%\\n\",\n      \"#2670: 96.59%\\n\",\n      \"#2671: 96.59%\\n\",\n      \"#2672: 96.60%\\n\",\n      \"#2673: 96.60%\\n\",\n      \"#2674: 96.60%\\n\",\n      \"#2675: 96.60%\\n\",\n      \"#2676: 96.60%\\n\",\n      \"#2677: 96.60%\\n\",\n      \"#2678: 96.60%\\n\",\n      \"#2679: 96.60%\\n\",\n      \"#2680: 96.61%\\n\",\n      \"#2681: 96.61%\\n\",\n      \"#2682: 96.61%\\n\",\n      \"#2683: 96.61%\\n\",\n      \"#2684: 96.61%\\n\",\n      \"#2685: 96.61%\\n\",\n      \"#2686: 96.61%\\n\",\n      \"#2687: 96.61%\\n\",\n      \"#2688: 96.62%\\n\",\n      \"#2689: 96.62%\\n\",\n      \"#2690: 96.62%\\n\",\n      \"#2691: 96.62%\\n\",\n      \"#2692: 96.62%\\n\",\n      \"#2693: 96.62%\\n\",\n      \"#2694: 96.62%\\n\",\n      \"#2695: 96.62%\\n\",\n      \"#2696: 96.63%\\n\",\n      \"#2697: 96.63%\\n\",\n      \"#2698: 96.63%\\n\",\n      \"#2699: 96.63%\\n\",\n      \"#2700: 96.63%\\n\",\n      \"#2701: 96.63%\\n\",\n      \"#2702: 96.63%\\n\",\n      \"#2703: 96.63%\\n\",\n      \"#2704: 96.64%\\n\",\n      \"#2705: 96.64%\\n\",\n      \"#2706: 96.64%\\n\",\n      \"#2707: 96.64%\\n\",\n      \"#2708: 96.64%\\n\",\n      \"#2709: 96.64%\\n\",\n      \"#2710: 96.64%\\n\",\n      \"#2711: 96.64%\\n\",\n      \"#2712: 96.65%\\n\",\n      \"#2713: 96.65%\\n\",\n      \"#2714: 96.65%\\n\",\n      \"#2715: 96.65%\\n\",\n      \"#2716: 96.65%\\n\",\n      \"#2717: 96.65%\\n\",\n      \"#2718: 96.65%\\n\",\n      \"#2719: 96.65%\\n\",\n      \"#2720: 96.66%\\n\",\n      \"#2721: 96.66%\\n\",\n      \"#2722: 96.66%\\n\",\n      \"#2723: 96.66%\\n\",\n      \"#2724: 96.66%\\n\",\n      \"#2725: 96.66%\\n\",\n      \"#2726: 96.66%\\n\",\n      \"#2727: 96.66%\\n\",\n      \"#2728: 96.67%\\n\",\n      \"#2729: 96.67%\\n\",\n      \"#2730: 96.67%\\n\",\n      \"#2731: 96.67%\\n\",\n      \"#2732: 96.67%\\n\",\n      \"#2733: 96.67%\\n\",\n      \"#2734: 96.67%\\n\",\n      \"#2735: 96.67%\\n\",\n      \"#2736: 96.68%\\n\",\n      \"#2737: 96.68%\\n\",\n      \"#2738: 96.68%\\n\",\n      \"#2739: 96.68%\\n\",\n      \"#2740: 96.68%\\n\",\n      \"#2741: 96.68%\\n\",\n      \"#2742: 96.68%\\n\",\n      \"#2743: 96.68%\\n\",\n      \"#2744: 96.68%\\n\",\n      \"#2745: 96.69%\\n\",\n      \"#2746: 96.69%\\n\",\n      \"#2747: 96.69%\\n\",\n      \"#2748: 96.69%\\n\",\n      \"#2749: 96.69%\\n\",\n      \"#2750: 96.69%\\n\",\n      \"#2751: 96.69%\\n\",\n      \"#2752: 96.69%\\n\",\n      \"#2753: 96.70%\\n\",\n      \"#2754: 96.70%\\n\",\n      \"#2755: 96.70%\\n\",\n      \"#2756: 96.70%\\n\",\n      \"#2757: 96.70%\\n\",\n      \"#2758: 96.70%\\n\",\n      \"#2759: 96.70%\\n\",\n      \"#2760: 96.67%\\n\",\n      \"#2761: 96.67%\\n\",\n      \"#2762: 96.67%\\n\",\n      \"#2763: 96.67%\\n\",\n      \"#2764: 96.67%\\n\",\n      \"#2765: 96.67%\\n\",\n      \"#2766: 96.68%\\n\",\n      \"#2767: 96.68%\\n\",\n      \"#2768: 96.68%\\n\",\n      \"#2769: 96.68%\\n\",\n      \"#2770: 96.64%\\n\",\n      \"#2771: 96.65%\\n\",\n      \"#2772: 96.65%\\n\",\n      \"#2773: 96.65%\\n\",\n      \"#2774: 96.65%\\n\",\n      \"#2775: 96.65%\\n\",\n      \"#2776: 96.65%\\n\",\n      \"#2777: 96.65%\\n\",\n      \"#2778: 96.62%\\n\",\n      \"#2779: 96.62%\\n\",\n      \"#2780: 96.58%\\n\",\n      \"#2781: 96.59%\\n\",\n      \"#2782: 96.59%\\n\",\n      \"#2783: 96.59%\\n\",\n      \"#2784: 96.59%\\n\",\n      \"#2785: 96.59%\\n\",\n      \"#2786: 96.59%\\n\",\n      \"#2787: 96.59%\\n\",\n      \"#2788: 96.59%\\n\",\n      \"#2789: 96.59%\\n\",\n      \"#2790: 96.60%\\n\",\n      \"#2791: 96.60%\\n\",\n      \"#2792: 96.60%\\n\",\n      \"#2793: 96.60%\\n\",\n      \"#2794: 96.60%\\n\",\n      \"#2795: 96.60%\\n\",\n      \"#2796: 96.60%\\n\",\n      \"#2797: 96.60%\\n\",\n      \"#2798: 96.61%\\n\",\n      \"#2799: 96.61%\\n\",\n      \"#2800: 96.61%\\n\",\n      \"#2801: 96.61%\\n\",\n      \"#2802: 96.61%\\n\",\n      \"#2803: 96.61%\\n\",\n      \"#2804: 96.61%\\n\",\n      \"#2805: 96.61%\\n\",\n      \"#2806: 96.62%\\n\",\n      \"#2807: 96.62%\\n\",\n      \"#2808: 96.62%\\n\",\n      \"#2809: 96.62%\\n\",\n      \"#2810: 96.62%\\n\",\n      \"#2811: 96.62%\\n\",\n      \"#2812: 96.62%\\n\",\n      \"#2813: 96.62%\\n\",\n      \"#2814: 96.63%\\n\",\n      \"#2815: 96.63%\\n\",\n      \"#2816: 96.63%\\n\",\n      \"#2817: 96.63%\\n\",\n      \"#2818: 96.63%\\n\",\n      \"#2819: 96.63%\\n\",\n      \"#2820: 96.63%\\n\",\n      \"#2821: 96.63%\\n\",\n      \"#2822: 96.63%\\n\",\n      \"#2823: 96.60%\\n\",\n      \"#2824: 96.60%\\n\",\n      \"#2825: 96.60%\\n\",\n      \"#2826: 96.60%\\n\",\n      \"#2827: 96.61%\\n\",\n      \"#2828: 96.61%\\n\",\n      \"#2829: 96.61%\\n\",\n      \"#2830: 96.61%\\n\",\n      \"#2831: 96.61%\\n\",\n      \"#2832: 96.61%\\n\",\n      \"#2833: 96.61%\\n\",\n      \"#2834: 96.61%\\n\",\n      \"#2835: 96.61%\\n\",\n      \"#2836: 96.62%\\n\",\n      \"#2837: 96.62%\\n\",\n      \"#2838: 96.62%\\n\",\n      \"#2839: 96.62%\\n\",\n      \"#2840: 96.62%\\n\",\n      \"#2841: 96.62%\\n\",\n      \"#2842: 96.62%\\n\",\n      \"#2843: 96.62%\\n\",\n      \"#2844: 96.63%\\n\",\n      \"#2845: 96.63%\\n\",\n      \"#2846: 96.63%\\n\",\n      \"#2847: 96.63%\\n\",\n      \"#2848: 96.63%\\n\",\n      \"#2849: 96.63%\\n\",\n      \"#2850: 96.63%\\n\",\n      \"#2851: 96.63%\\n\",\n      \"#2852: 96.64%\\n\",\n      \"#2853: 96.64%\\n\",\n      \"#2854: 96.64%\\n\",\n      \"#2855: 96.64%\\n\",\n      \"#2856: 96.64%\\n\",\n      \"#2857: 96.64%\\n\",\n      \"#2858: 96.64%\\n\",\n      \"#2859: 96.64%\\n\",\n      \"#2860: 96.64%\\n\",\n      \"#2861: 96.65%\\n\",\n      \"#2862: 96.65%\\n\",\n      \"#2863: 96.65%\\n\",\n      \"#2864: 96.65%\\n\",\n      \"#2865: 96.65%\\n\",\n      \"#2866: 96.65%\\n\",\n      \"#2867: 96.65%\\n\",\n      \"#2868: 96.65%\\n\",\n      \"#2869: 96.66%\\n\",\n      \"#2870: 96.66%\\n\",\n      \"#2871: 96.66%\\n\",\n      \"#2872: 96.66%\\n\",\n      \"#2873: 96.66%\\n\",\n      \"#2874: 96.66%\\n\",\n      \"#2875: 96.66%\\n\",\n      \"#2876: 96.66%\\n\",\n      \"#2877: 96.66%\\n\",\n      \"#2878: 96.67%\\n\",\n      \"#2879: 96.67%\\n\",\n      \"#2880: 96.67%\\n\",\n      \"#2881: 96.67%\\n\",\n      \"#2882: 96.67%\\n\",\n      \"#2883: 96.67%\\n\",\n      \"#2884: 96.67%\\n\",\n      \"#2885: 96.67%\\n\",\n      \"#2886: 96.67%\\n\",\n      \"#2887: 96.68%\\n\",\n      \"#2888: 96.68%\\n\",\n      \"#2889: 96.68%\\n\",\n      \"#2890: 96.68%\\n\",\n      \"#2891: 96.68%\\n\",\n      \"#2892: 96.68%\\n\",\n      \"#2893: 96.68%\\n\",\n      \"#2894: 96.68%\\n\",\n      \"#2895: 96.69%\\n\",\n      \"#2896: 96.65%\\n\",\n      \"#2897: 96.65%\\n\",\n      \"#2898: 96.65%\\n\",\n      \"#2899: 96.66%\\n\",\n      \"#2900: 96.66%\\n\",\n      \"#2901: 96.66%\\n\",\n      \"#2902: 96.66%\\n\",\n      \"#2903: 96.66%\\n\",\n      \"#2904: 96.66%\\n\",\n      \"#2905: 96.66%\\n\",\n      \"#2906: 96.66%\\n\",\n      \"#2907: 96.66%\\n\",\n      \"#2908: 96.67%\\n\",\n      \"#2909: 96.67%\\n\",\n      \"#2910: 96.67%\\n\",\n      \"#2911: 96.67%\\n\",\n      \"#2912: 96.67%\\n\",\n      \"#2913: 96.67%\\n\",\n      \"#2914: 96.67%\\n\",\n      \"#2915: 96.67%\\n\",\n      \"#2916: 96.67%\\n\",\n      \"#2917: 96.68%\\n\",\n      \"#2918: 96.68%\\n\",\n      \"#2919: 96.68%\\n\",\n      \"#2920: 96.68%\\n\",\n      \"#2921: 96.68%\\n\",\n      \"#2922: 96.68%\\n\",\n      \"#2923: 96.68%\\n\",\n      \"#2924: 96.68%\\n\",\n      \"#2925: 96.68%\\n\",\n      \"#2926: 96.69%\\n\",\n      \"#2927: 96.65%\\n\",\n      \"#2928: 96.65%\\n\",\n      \"#2929: 96.66%\\n\",\n      \"#2930: 96.66%\\n\",\n      \"#2931: 96.66%\\n\",\n      \"#2932: 96.66%\\n\",\n      \"#2933: 96.66%\\n\",\n      \"#2934: 96.66%\\n\",\n      \"#2935: 96.66%\\n\",\n      \"#2936: 96.66%\\n\",\n      \"#2937: 96.66%\\n\",\n      \"#2938: 96.67%\\n\",\n      \"#2939: 96.63%\\n\",\n      \"#2940: 96.63%\\n\",\n      \"#2941: 96.63%\\n\",\n      \"#2942: 96.64%\\n\",\n      \"#2943: 96.64%\\n\",\n      \"#2944: 96.64%\\n\",\n      \"#2945: 96.64%\\n\",\n      \"#2946: 96.64%\\n\",\n      \"#2947: 96.64%\\n\",\n      \"#2948: 96.64%\\n\",\n      \"#2949: 96.64%\\n\",\n      \"#2950: 96.65%\\n\",\n      \"#2951: 96.65%\\n\",\n      \"#2952: 96.61%\\n\",\n      \"#2953: 96.61%\\n\",\n      \"#2954: 96.62%\\n\",\n      \"#2955: 96.62%\\n\",\n      \"#2956: 96.62%\\n\",\n      \"#2957: 96.62%\\n\",\n      \"#2958: 96.62%\\n\",\n      \"#2959: 96.62%\\n\",\n      \"#2960: 96.62%\\n\",\n      \"#2961: 96.62%\\n\",\n      \"#2962: 96.63%\\n\",\n      \"#2963: 96.63%\\n\",\n      \"#2964: 96.63%\\n\",\n      \"#2965: 96.63%\\n\",\n      \"#2966: 96.63%\\n\",\n      \"#2967: 96.63%\\n\",\n      \"#2968: 96.63%\\n\",\n      \"#2969: 96.63%\\n\",\n      \"#2970: 96.63%\\n\",\n      \"#2971: 96.64%\\n\",\n      \"#2972: 96.64%\\n\",\n      \"#2973: 96.64%\\n\",\n      \"#2974: 96.64%\\n\",\n      \"#2975: 96.64%\\n\",\n      \"#2976: 96.64%\\n\",\n      \"#2977: 96.64%\\n\",\n      \"#2978: 96.64%\\n\",\n      \"#2979: 96.64%\\n\",\n      \"#2980: 96.65%\\n\",\n      \"#2981: 96.65%\\n\",\n      \"#2982: 96.65%\\n\",\n      \"#2983: 96.65%\\n\",\n      \"#2984: 96.65%\\n\",\n      \"#2985: 96.65%\\n\",\n      \"#2986: 96.65%\\n\",\n      \"#2987: 96.65%\\n\",\n      \"#2988: 96.65%\\n\",\n      \"#2989: 96.66%\\n\",\n      \"#2990: 96.66%\\n\",\n      \"#2991: 96.66%\\n\",\n      \"#2992: 96.66%\\n\",\n      \"#2993: 96.66%\\n\",\n      \"#2994: 96.66%\\n\",\n      \"#2995: 96.63%\\n\",\n      \"#2996: 96.63%\\n\",\n      \"#2997: 96.63%\\n\",\n      \"#2998: 96.63%\\n\",\n      \"#2999: 96.63%\\n\",\n      \"#3000: 96.63%\\n\",\n      \"#3001: 96.64%\\n\",\n      \"#3002: 96.64%\\n\",\n      \"#3003: 96.64%\\n\",\n      \"#3004: 96.64%\\n\",\n      \"#3005: 96.61%\\n\",\n      \"#3006: 96.61%\\n\",\n      \"#3007: 96.61%\\n\",\n      \"#3008: 96.61%\\n\",\n      \"#3009: 96.61%\\n\",\n      \"#3010: 96.61%\\n\",\n      \"#3011: 96.61%\\n\",\n      \"#3012: 96.61%\\n\",\n      \"#3013: 96.62%\\n\",\n      \"#3014: 96.62%\\n\",\n      \"#3015: 96.62%\\n\",\n      \"#3016: 96.62%\\n\",\n      \"#3017: 96.62%\\n\",\n      \"#3018: 96.62%\\n\",\n      \"#3019: 96.62%\\n\",\n      \"#3020: 96.62%\\n\",\n      \"#3021: 96.62%\\n\",\n      \"#3022: 96.63%\\n\",\n      \"#3023: 96.63%\\n\",\n      \"#3024: 96.63%\\n\",\n      \"#3025: 96.63%\\n\",\n      \"#3026: 96.63%\\n\",\n      \"#3027: 96.63%\\n\",\n      \"#3028: 96.63%\\n\",\n      \"#3029: 96.63%\\n\",\n      \"#3030: 96.60%\\n\",\n      \"#3031: 96.60%\\n\",\n      \"#3032: 96.60%\\n\",\n      \"#3033: 96.61%\\n\",\n      \"#3034: 96.61%\\n\",\n      \"#3035: 96.61%\\n\",\n      \"#3036: 96.61%\\n\",\n      \"#3037: 96.61%\\n\",\n      \"#3038: 96.61%\\n\",\n      \"#3039: 96.61%\\n\",\n      \"#3040: 96.61%\\n\",\n      \"#3041: 96.61%\\n\",\n      \"#3042: 96.62%\\n\",\n      \"#3043: 96.62%\\n\",\n      \"#3044: 96.62%\\n\",\n      \"#3045: 96.62%\\n\",\n      \"#3046: 96.62%\\n\",\n      \"#3047: 96.62%\\n\",\n      \"#3048: 96.62%\\n\",\n      \"#3049: 96.62%\\n\",\n      \"#3050: 96.62%\\n\",\n      \"#3051: 96.63%\\n\",\n      \"#3052: 96.63%\\n\",\n      \"#3053: 96.63%\\n\",\n      \"#3054: 96.63%\\n\",\n      \"#3055: 96.63%\\n\",\n      \"#3056: 96.63%\\n\",\n      \"#3057: 96.63%\\n\",\n      \"#3058: 96.63%\\n\",\n      \"#3059: 96.63%\\n\",\n      \"#3060: 96.60%\\n\",\n      \"#3061: 96.60%\\n\",\n      \"#3062: 96.60%\\n\",\n      \"#3063: 96.61%\\n\",\n      \"#3064: 96.61%\\n\",\n      \"#3065: 96.61%\\n\",\n      \"#3066: 96.61%\\n\",\n      \"#3067: 96.61%\\n\",\n      \"#3068: 96.61%\\n\",\n      \"#3069: 96.61%\\n\",\n      \"#3070: 96.61%\\n\",\n      \"#3071: 96.61%\\n\",\n      \"#3072: 96.62%\\n\",\n      \"#3073: 96.58%\\n\",\n      \"#3074: 96.59%\\n\",\n      \"#3075: 96.59%\\n\",\n      \"#3076: 96.59%\\n\",\n      \"#3077: 96.59%\\n\",\n      \"#3078: 96.59%\\n\",\n      \"#3079: 96.59%\\n\",\n      \"#3080: 96.59%\\n\",\n      \"#3081: 96.59%\\n\",\n      \"#3082: 96.59%\\n\",\n      \"#3083: 96.60%\\n\",\n      \"#3084: 96.60%\\n\",\n      \"#3085: 96.60%\\n\",\n      \"#3086: 96.60%\\n\",\n      \"#3087: 96.60%\\n\",\n      \"#3088: 96.60%\\n\",\n      \"#3089: 96.60%\\n\",\n      \"#3090: 96.60%\\n\",\n      \"#3091: 96.60%\\n\",\n      \"#3092: 96.61%\\n\",\n      \"#3093: 96.61%\\n\",\n      \"#3094: 96.61%\\n\",\n      \"#3095: 96.61%\\n\",\n      \"#3096: 96.61%\\n\",\n      \"#3097: 96.61%\\n\",\n      \"#3098: 96.61%\\n\",\n      \"#3099: 96.61%\\n\",\n      \"#3100: 96.61%\\n\",\n      \"#3101: 96.62%\\n\",\n      \"#3102: 96.62%\\n\",\n      \"#3103: 96.62%\\n\",\n      \"#3104: 96.62%\\n\",\n      \"#3105: 96.62%\\n\",\n      \"#3106: 96.62%\\n\",\n      \"#3107: 96.62%\\n\",\n      \"#3108: 96.62%\\n\",\n      \"#3109: 96.62%\\n\",\n      \"#3110: 96.62%\\n\",\n      \"#3111: 96.63%\\n\",\n      \"#3112: 96.63%\\n\",\n      \"#3113: 96.63%\\n\",\n      \"#3114: 96.60%\\n\",\n      \"#3115: 96.60%\\n\",\n      \"#3116: 96.60%\\n\",\n      \"#3117: 96.60%\\n\",\n      \"#3118: 96.60%\\n\",\n      \"#3119: 96.60%\\n\",\n      \"#3120: 96.60%\\n\",\n      \"#3121: 96.60%\\n\",\n      \"#3122: 96.61%\\n\",\n      \"#3123: 96.61%\\n\",\n      \"#3124: 96.61%\\n\",\n      \"#3125: 96.61%\\n\",\n      \"#3126: 96.61%\\n\",\n      \"#3127: 96.61%\\n\",\n      \"#3128: 96.61%\\n\",\n      \"#3129: 96.61%\\n\",\n      \"#3130: 96.61%\\n\",\n      \"#3131: 96.62%\\n\",\n      \"#3132: 96.62%\\n\",\n      \"#3133: 96.62%\\n\",\n      \"#3134: 96.62%\\n\",\n      \"#3135: 96.62%\\n\",\n      \"#3136: 96.62%\\n\",\n      \"#3137: 96.62%\\n\",\n      \"#3138: 96.62%\\n\",\n      \"#3139: 96.62%\\n\",\n      \"#3140: 96.63%\\n\",\n      \"#3141: 96.63%\\n\",\n      \"#3142: 96.63%\\n\",\n      \"#3143: 96.63%\\n\",\n      \"#3144: 96.63%\\n\",\n      \"#3145: 96.63%\\n\",\n      \"#3146: 96.63%\\n\",\n      \"#3147: 96.63%\\n\",\n      \"#3148: 96.63%\\n\",\n      \"#3149: 96.63%\\n\",\n      \"#3150: 96.64%\\n\",\n      \"#3151: 96.64%\\n\",\n      \"#3152: 96.64%\\n\",\n      \"#3153: 96.64%\\n\",\n      \"#3154: 96.64%\\n\",\n      \"#3155: 96.64%\\n\",\n      \"#3156: 96.64%\\n\",\n      \"#3157: 96.64%\\n\",\n      \"#3158: 96.64%\\n\",\n      \"#3159: 96.65%\\n\",\n      \"#3160: 96.65%\\n\",\n      \"#3161: 96.65%\\n\",\n      \"#3162: 96.65%\\n\",\n      \"#3163: 96.65%\\n\",\n      \"#3164: 96.65%\\n\",\n      \"#3165: 96.65%\\n\",\n      \"#3166: 96.65%\\n\",\n      \"#3167: 96.65%\\n\",\n      \"#3168: 96.66%\\n\",\n      \"#3169: 96.66%\\n\",\n      \"#3170: 96.66%\\n\",\n      \"#3171: 96.66%\\n\",\n      \"#3172: 96.66%\\n\",\n      \"#3173: 96.66%\\n\",\n      \"#3174: 96.66%\\n\",\n      \"#3175: 96.66%\\n\",\n      \"#3176: 96.66%\\n\",\n      \"#3177: 96.66%\\n\",\n      \"#3178: 96.67%\\n\",\n      \"#3179: 96.67%\\n\",\n      \"#3180: 96.67%\\n\",\n      \"#3181: 96.67%\\n\",\n      \"#3182: 96.67%\\n\",\n      \"#3183: 96.67%\\n\",\n      \"#3184: 96.67%\\n\",\n      \"#3185: 96.67%\\n\",\n      \"#3186: 96.67%\\n\",\n      \"#3187: 96.68%\\n\",\n      \"#3188: 96.68%\\n\",\n      \"#3189: 96.65%\\n\",\n      \"#3190: 96.65%\\n\",\n      \"#3191: 96.65%\\n\",\n      \"#3192: 96.65%\\n\",\n      \"#3193: 96.65%\\n\",\n      \"#3194: 96.65%\\n\",\n      \"#3195: 96.65%\\n\",\n      \"#3196: 96.65%\\n\",\n      \"#3197: 96.65%\\n\",\n      \"#3198: 96.66%\\n\",\n      \"#3199: 96.66%\\n\",\n      \"#3200: 96.66%\\n\",\n      \"#3201: 96.66%\\n\",\n      \"#3202: 96.66%\\n\",\n      \"#3203: 96.66%\\n\",\n      \"#3204: 96.66%\\n\",\n      \"#3205: 96.66%\\n\",\n      \"#3206: 96.66%\\n\",\n      \"#3207: 96.66%\\n\",\n      \"#3208: 96.67%\\n\",\n      \"#3209: 96.67%\\n\",\n      \"#3210: 96.67%\\n\",\n      \"#3211: 96.67%\\n\",\n      \"#3212: 96.67%\\n\",\n      \"#3213: 96.67%\\n\",\n      \"#3214: 96.67%\\n\",\n      \"#3215: 96.67%\\n\",\n      \"#3216: 96.67%\\n\",\n      \"#3217: 96.67%\\n\",\n      \"#3218: 96.68%\\n\",\n      \"#3219: 96.68%\\n\",\n      \"#3220: 96.68%\\n\",\n      \"#3221: 96.68%\\n\",\n      \"#3222: 96.68%\\n\",\n      \"#3223: 96.68%\\n\",\n      \"#3224: 96.68%\\n\",\n      \"#3225: 96.68%\\n\",\n      \"#3226: 96.68%\\n\",\n      \"#3227: 96.69%\\n\",\n      \"#3228: 96.69%\\n\",\n      \"#3229: 96.69%\\n\",\n      \"#3230: 96.69%\\n\",\n      \"#3231: 96.69%\\n\",\n      \"#3232: 96.69%\\n\",\n      \"#3233: 96.69%\\n\",\n      \"#3234: 96.69%\\n\",\n      \"#3235: 96.69%\\n\",\n      \"#3236: 96.69%\\n\",\n      \"#3237: 96.70%\\n\",\n      \"#3238: 96.70%\\n\",\n      \"#3239: 96.67%\\n\",\n      \"#3240: 96.67%\\n\",\n      \"#3241: 96.67%\\n\",\n      \"#3242: 96.67%\\n\",\n      \"#3243: 96.67%\\n\",\n      \"#3244: 96.67%\\n\",\n      \"#3245: 96.67%\\n\",\n      \"#3246: 96.64%\\n\",\n      \"#3247: 96.64%\\n\",\n      \"#3248: 96.65%\\n\",\n      \"#3249: 96.65%\\n\",\n      \"#3250: 96.65%\\n\",\n      \"#3251: 96.65%\\n\",\n      \"#3252: 96.65%\\n\",\n      \"#3253: 96.65%\\n\",\n      \"#3254: 96.65%\\n\",\n      \"#3255: 96.65%\\n\",\n      \"#3256: 96.65%\\n\",\n      \"#3257: 96.65%\\n\",\n      \"#3258: 96.66%\\n\",\n      \"#3259: 96.66%\\n\",\n      \"#3260: 96.66%\\n\",\n      \"#3261: 96.66%\\n\",\n      \"#3262: 96.63%\\n\",\n      \"#3263: 96.63%\\n\",\n      \"#3264: 96.63%\\n\",\n      \"#3265: 96.63%\\n\",\n      \"#3266: 96.63%\\n\",\n      \"#3267: 96.63%\\n\",\n      \"#3268: 96.64%\\n\",\n      \"#3269: 96.64%\\n\",\n      \"#3270: 96.64%\\n\",\n      \"#3271: 96.64%\\n\",\n      \"#3272: 96.64%\\n\",\n      \"#3273: 96.64%\\n\",\n      \"#3274: 96.64%\\n\",\n      \"#3275: 96.64%\\n\",\n      \"#3276: 96.64%\\n\",\n      \"#3277: 96.64%\\n\",\n      \"#3278: 96.65%\\n\",\n      \"#3279: 96.65%\\n\",\n      \"#3280: 96.65%\\n\",\n      \"#3281: 96.65%\\n\",\n      \"#3282: 96.65%\\n\",\n      \"#3283: 96.65%\\n\",\n      \"#3284: 96.65%\\n\",\n      \"#3285: 96.65%\\n\",\n      \"#3286: 96.65%\\n\",\n      \"#3287: 96.65%\\n\",\n      \"#3288: 96.66%\\n\",\n      \"#3289: 96.63%\\n\",\n      \"#3290: 96.63%\\n\",\n      \"#3291: 96.63%\\n\",\n      \"#3292: 96.63%\\n\",\n      \"#3293: 96.63%\\n\",\n      \"#3294: 96.63%\\n\",\n      \"#3295: 96.63%\\n\",\n      \"#3296: 96.63%\\n\",\n      \"#3297: 96.63%\\n\",\n      \"#3298: 96.64%\\n\",\n      \"#3299: 96.64%\\n\",\n      \"#3300: 96.64%\\n\",\n      \"#3301: 96.64%\\n\",\n      \"#3302: 96.64%\\n\",\n      \"#3303: 96.64%\\n\",\n      \"#3304: 96.64%\\n\",\n      \"#3305: 96.64%\\n\",\n      \"#3306: 96.64%\\n\",\n      \"#3307: 96.64%\\n\",\n      \"#3308: 96.65%\\n\",\n      \"#3309: 96.65%\\n\",\n      \"#3310: 96.65%\\n\",\n      \"#3311: 96.65%\\n\",\n      \"#3312: 96.65%\\n\",\n      \"#3313: 96.65%\\n\",\n      \"#3314: 96.65%\\n\",\n      \"#3315: 96.65%\\n\",\n      \"#3316: 96.62%\\n\",\n      \"#3317: 96.62%\\n\",\n      \"#3318: 96.63%\\n\",\n      \"#3319: 96.60%\\n\",\n      \"#3320: 96.60%\\n\",\n      \"#3321: 96.60%\\n\",\n      \"#3322: 96.60%\\n\",\n      \"#3323: 96.60%\\n\",\n      \"#3324: 96.60%\\n\",\n      \"#3325: 96.60%\\n\",\n      \"#3326: 96.60%\\n\",\n      \"#3327: 96.60%\\n\",\n      \"#3328: 96.61%\\n\",\n      \"#3329: 96.61%\\n\",\n      \"#3330: 96.61%\\n\",\n      \"#3331: 96.61%\\n\",\n      \"#3332: 96.61%\\n\",\n      \"#3333: 96.58%\\n\",\n      \"#3334: 96.58%\\n\",\n      \"#3335: 96.58%\\n\",\n      \"#3336: 96.58%\\n\",\n      \"#3337: 96.58%\\n\",\n      \"#3338: 96.59%\\n\",\n      \"#3339: 96.59%\\n\",\n      \"#3340: 96.59%\\n\",\n      \"#3341: 96.59%\\n\",\n      \"#3342: 96.59%\\n\",\n      \"#3343: 96.59%\\n\",\n      \"#3344: 96.59%\\n\",\n      \"#3345: 96.59%\\n\",\n      \"#3346: 96.59%\\n\",\n      \"#3347: 96.59%\\n\",\n      \"#3348: 96.60%\\n\",\n      \"#3349: 96.60%\\n\",\n      \"#3350: 96.60%\\n\",\n      \"#3351: 96.60%\\n\",\n      \"#3352: 96.60%\\n\",\n      \"#3353: 96.60%\\n\",\n      \"#3354: 96.60%\\n\",\n      \"#3355: 96.60%\\n\",\n      \"#3356: 96.60%\\n\",\n      \"#3357: 96.61%\\n\",\n      \"#3358: 96.61%\\n\",\n      \"#3359: 96.61%\\n\",\n      \"#3360: 96.61%\\n\",\n      \"#3361: 96.61%\\n\",\n      \"#3362: 96.61%\\n\",\n      \"#3363: 96.61%\\n\",\n      \"#3364: 96.61%\\n\",\n      \"#3365: 96.61%\\n\",\n      \"#3366: 96.61%\\n\",\n      \"#3367: 96.62%\\n\",\n      \"#3368: 96.62%\\n\",\n      \"#3369: 96.62%\\n\",\n      \"#3370: 96.62%\\n\",\n      \"#3371: 96.62%\\n\",\n      \"#3372: 96.62%\\n\",\n      \"#3373: 96.62%\\n\",\n      \"#3374: 96.62%\\n\",\n      \"#3375: 96.62%\\n\",\n      \"#3376: 96.62%\\n\",\n      \"#3377: 96.63%\\n\",\n      \"#3378: 96.63%\\n\",\n      \"#3379: 96.63%\\n\",\n      \"#3380: 96.63%\\n\",\n      \"#3381: 96.63%\\n\",\n      \"#3382: 96.63%\\n\",\n      \"#3383: 96.63%\\n\",\n      \"#3384: 96.63%\\n\",\n      \"#3385: 96.63%\\n\",\n      \"#3386: 96.63%\\n\",\n      \"#3387: 96.64%\\n\",\n      \"#3388: 96.64%\\n\",\n      \"#3389: 96.64%\\n\",\n      \"#3390: 96.64%\\n\",\n      \"#3391: 96.64%\\n\",\n      \"#3392: 96.64%\\n\",\n      \"#3393: 96.64%\\n\",\n      \"#3394: 96.64%\\n\",\n      \"#3395: 96.64%\\n\",\n      \"#3396: 96.64%\\n\",\n      \"#3397: 96.65%\\n\",\n      \"#3398: 96.65%\\n\",\n      \"#3399: 96.65%\\n\",\n      \"#3400: 96.65%\\n\",\n      \"#3401: 96.65%\\n\",\n      \"#3402: 96.65%\\n\",\n      \"#3403: 96.65%\\n\",\n      \"#3404: 96.65%\\n\",\n      \"#3405: 96.65%\\n\",\n      \"#3406: 96.65%\\n\",\n      \"#3407: 96.65%\\n\",\n      \"#3408: 96.66%\\n\",\n      \"#3409: 96.66%\\n\",\n      \"#3410: 96.66%\\n\",\n      \"#3411: 96.66%\\n\",\n      \"#3412: 96.66%\\n\",\n      \"#3413: 96.66%\\n\",\n      \"#3414: 96.66%\\n\",\n      \"#3415: 96.66%\\n\",\n      \"#3416: 96.66%\\n\",\n      \"#3417: 96.66%\\n\",\n      \"#3418: 96.67%\\n\",\n      \"#3419: 96.67%\\n\",\n      \"#3420: 96.67%\\n\",\n      \"#3421: 96.67%\\n\",\n      \"#3422: 96.67%\\n\",\n      \"#3423: 96.67%\\n\",\n      \"#3424: 96.67%\\n\",\n      \"#3425: 96.67%\\n\",\n      \"#3426: 96.67%\\n\",\n      \"#3427: 96.67%\\n\",\n      \"#3428: 96.68%\\n\",\n      \"#3429: 96.68%\\n\",\n      \"#3430: 96.68%\\n\",\n      \"#3431: 96.68%\\n\",\n      \"#3432: 96.68%\\n\",\n      \"#3433: 96.68%\\n\",\n      \"#3434: 96.68%\\n\",\n      \"#3435: 96.68%\\n\",\n      \"#3436: 96.68%\\n\",\n      \"#3437: 96.68%\\n\",\n      \"#3438: 96.69%\\n\",\n      \"#3439: 96.69%\\n\",\n      \"#3440: 96.69%\\n\",\n      \"#3441: 96.69%\\n\",\n      \"#3442: 96.69%\\n\",\n      \"#3443: 96.69%\\n\",\n      \"#3444: 96.69%\\n\",\n      \"#3445: 96.69%\\n\",\n      \"#3446: 96.69%\\n\",\n      \"#3447: 96.69%\\n\",\n      \"#3448: 96.69%\\n\",\n      \"#3449: 96.70%\\n\",\n      \"#3450: 96.70%\\n\",\n      \"#3451: 96.70%\\n\",\n      \"#3452: 96.70%\\n\",\n      \"#3453: 96.70%\\n\",\n      \"#3454: 96.70%\\n\",\n      \"#3455: 96.70%\\n\",\n      \"#3456: 96.70%\\n\",\n      \"#3457: 96.70%\\n\",\n      \"#3458: 96.70%\\n\",\n      \"#3459: 96.71%\\n\",\n      \"#3460: 96.71%\\n\",\n      \"#3461: 96.71%\\n\",\n      \"#3462: 96.71%\\n\",\n      \"#3463: 96.71%\\n\",\n      \"#3464: 96.71%\\n\",\n      \"#3465: 96.71%\\n\",\n      \"#3466: 96.71%\\n\",\n      \"#3467: 96.71%\\n\",\n      \"#3468: 96.71%\\n\",\n      \"#3469: 96.71%\\n\",\n      \"#3470: 96.72%\\n\",\n      \"#3471: 96.72%\\n\",\n      \"#3472: 96.72%\\n\",\n      \"#3473: 96.72%\\n\",\n      \"#3474: 96.72%\\n\",\n      \"#3475: 96.72%\\n\",\n      \"#3476: 96.72%\\n\",\n      \"#3477: 96.72%\\n\",\n      \"#3478: 96.72%\\n\",\n      \"#3479: 96.72%\\n\",\n      \"#3480: 96.73%\\n\",\n      \"#3481: 96.73%\\n\",\n      \"#3482: 96.73%\\n\",\n      \"#3483: 96.73%\\n\",\n      \"#3484: 96.73%\\n\",\n      \"#3485: 96.73%\\n\",\n      \"#3486: 96.73%\\n\",\n      \"#3487: 96.73%\\n\",\n      \"#3488: 96.73%\\n\",\n      \"#3489: 96.73%\\n\",\n      \"#3490: 96.73%\\n\",\n      \"#3491: 96.74%\\n\",\n      \"#3492: 96.74%\\n\",\n      \"#3493: 96.74%\\n\",\n      \"#3494: 96.74%\\n\",\n      \"#3495: 96.74%\\n\",\n      \"#3496: 96.74%\\n\",\n      \"#3497: 96.74%\\n\",\n      \"#3498: 96.74%\\n\",\n      \"#3499: 96.74%\\n\",\n      \"#3500: 96.74%\\n\",\n      \"#3501: 96.74%\\n\",\n      \"#3502: 96.75%\\n\",\n      \"#3503: 96.72%\\n\",\n      \"#3504: 96.72%\\n\",\n      \"#3505: 96.72%\\n\",\n      \"#3506: 96.72%\\n\",\n      \"#3507: 96.72%\\n\",\n      \"#3508: 96.72%\\n\",\n      \"#3509: 96.72%\\n\",\n      \"#3510: 96.72%\\n\",\n      \"#3511: 96.73%\\n\",\n      \"#3512: 96.73%\\n\",\n      \"#3513: 96.73%\\n\",\n      \"#3514: 96.73%\\n\",\n      \"#3515: 96.73%\\n\",\n      \"#3516: 96.73%\\n\",\n      \"#3517: 96.73%\\n\",\n      \"#3518: 96.73%\\n\",\n      \"#3519: 96.73%\\n\",\n      \"#3520: 96.71%\\n\",\n      \"#3521: 96.71%\\n\",\n      \"#3522: 96.71%\\n\",\n      \"#3523: 96.71%\\n\",\n      \"#3524: 96.71%\\n\",\n      \"#3525: 96.71%\\n\",\n      \"#3526: 96.71%\\n\",\n      \"#3527: 96.71%\\n\",\n      \"#3528: 96.71%\\n\",\n      \"#3529: 96.71%\\n\",\n      \"#3530: 96.71%\\n\",\n      \"#3531: 96.72%\\n\",\n      \"#3532: 96.72%\\n\",\n      \"#3533: 96.72%\\n\",\n      \"#3534: 96.72%\\n\",\n      \"#3535: 96.72%\\n\",\n      \"#3536: 96.72%\\n\",\n      \"#3537: 96.72%\\n\",\n      \"#3538: 96.72%\\n\",\n      \"#3539: 96.72%\\n\",\n      \"#3540: 96.72%\\n\",\n      \"#3541: 96.73%\\n\",\n      \"#3542: 96.73%\\n\",\n      \"#3543: 96.73%\\n\",\n      \"#3544: 96.73%\\n\",\n      \"#3545: 96.73%\\n\",\n      \"#3546: 96.73%\\n\",\n      \"#3547: 96.73%\\n\",\n      \"#3548: 96.73%\\n\",\n      \"#3549: 96.73%\\n\",\n      \"#3550: 96.73%\\n\",\n      \"#3551: 96.73%\\n\",\n      \"#3552: 96.74%\\n\",\n      \"#3553: 96.74%\\n\",\n      \"#3554: 96.74%\\n\",\n      \"#3555: 96.74%\\n\",\n      \"#3556: 96.74%\\n\",\n      \"#3557: 96.74%\\n\",\n      \"#3558: 96.74%\\n\",\n      \"#3559: 96.71%\\n\",\n      \"#3560: 96.71%\\n\",\n      \"#3561: 96.72%\\n\",\n      \"#3562: 96.72%\\n\",\n      \"#3563: 96.72%\\n\",\n      \"#3564: 96.72%\\n\",\n      \"#3565: 96.72%\\n\",\n      \"#3566: 96.72%\\n\",\n      \"#3567: 96.72%\\n\",\n      \"#3568: 96.72%\\n\",\n      \"#3569: 96.72%\\n\",\n      \"#3570: 96.72%\\n\",\n      \"#3571: 96.72%\\n\",\n      \"#3572: 96.73%\\n\",\n      \"#3573: 96.73%\\n\",\n      \"#3574: 96.73%\\n\",\n      \"#3575: 96.73%\\n\",\n      \"#3576: 96.73%\\n\",\n      \"#3577: 96.73%\\n\",\n      \"#3578: 96.73%\\n\",\n      \"#3579: 96.73%\\n\",\n      \"#3580: 96.73%\\n\",\n      \"#3581: 96.73%\\n\",\n      \"#3582: 96.73%\\n\",\n      \"#3583: 96.74%\\n\",\n      \"#3584: 96.74%\\n\",\n      \"#3585: 96.74%\\n\",\n      \"#3586: 96.74%\\n\",\n      \"#3587: 96.74%\\n\",\n      \"#3588: 96.74%\\n\",\n      \"#3589: 96.74%\\n\",\n      \"#3590: 96.74%\\n\",\n      \"#3591: 96.74%\\n\",\n      \"#3592: 96.74%\\n\",\n      \"#3593: 96.74%\\n\",\n      \"#3594: 96.75%\\n\",\n      \"#3595: 96.75%\\n\",\n      \"#3596: 96.75%\\n\",\n      \"#3597: 96.72%\\n\",\n      \"#3598: 96.72%\\n\",\n      \"#3599: 96.72%\\n\",\n      \"#3600: 96.72%\\n\",\n      \"#3601: 96.72%\\n\",\n      \"#3602: 96.72%\\n\",\n      \"#3603: 96.73%\\n\",\n      \"#3604: 96.73%\\n\",\n      \"#3605: 96.73%\\n\",\n      \"#3606: 96.73%\\n\",\n      \"#3607: 96.73%\\n\",\n      \"#3608: 96.73%\\n\",\n      \"#3609: 96.73%\\n\",\n      \"#3610: 96.73%\\n\",\n      \"#3611: 96.73%\\n\",\n      \"#3612: 96.73%\\n\",\n      \"#3613: 96.73%\\n\",\n      \"#3614: 96.74%\\n\",\n      \"#3615: 96.74%\\n\",\n      \"#3616: 96.74%\\n\",\n      \"#3617: 96.74%\\n\",\n      \"#3618: 96.74%\\n\",\n      \"#3619: 96.74%\\n\",\n      \"#3620: 96.74%\\n\",\n      \"#3621: 96.74%\\n\",\n      \"#3622: 96.74%\\n\",\n      \"#3623: 96.74%\\n\",\n      \"#3624: 96.74%\\n\",\n      \"#3625: 96.75%\\n\",\n      \"#3626: 96.75%\\n\",\n      \"#3627: 96.75%\\n\",\n      \"#3628: 96.75%\\n\",\n      \"#3629: 96.75%\\n\",\n      \"#3630: 96.75%\\n\",\n      \"#3631: 96.75%\\n\",\n      \"#3632: 96.75%\\n\",\n      \"#3633: 96.75%\\n\",\n      \"#3634: 96.75%\\n\",\n      \"#3635: 96.75%\\n\",\n      \"#3636: 96.76%\\n\",\n      \"#3637: 96.76%\\n\",\n      \"#3638: 96.76%\\n\",\n      \"#3639: 96.76%\\n\",\n      \"#3640: 96.76%\\n\",\n      \"#3641: 96.76%\\n\",\n      \"#3642: 96.76%\\n\",\n      \"#3643: 96.76%\\n\",\n      \"#3644: 96.76%\\n\",\n      \"#3645: 96.76%\\n\",\n      \"#3646: 96.76%\\n\",\n      \"#3647: 96.77%\\n\",\n      \"#3648: 96.77%\\n\",\n      \"#3649: 96.77%\\n\",\n      \"#3650: 96.77%\\n\",\n      \"#3651: 96.77%\\n\",\n      \"#3652: 96.77%\\n\",\n      \"#3653: 96.77%\\n\",\n      \"#3654: 96.77%\\n\",\n      \"#3655: 96.77%\\n\",\n      \"#3656: 96.77%\\n\",\n      \"#3657: 96.77%\\n\",\n      \"#3658: 96.78%\\n\",\n      \"#3659: 96.78%\\n\",\n      \"#3660: 96.78%\\n\",\n      \"#3661: 96.78%\\n\",\n      \"#3662: 96.78%\\n\",\n      \"#3663: 96.78%\\n\",\n      \"#3664: 96.78%\\n\",\n      \"#3665: 96.78%\\n\",\n      \"#3666: 96.78%\\n\",\n      \"#3667: 96.78%\\n\",\n      \"#3668: 96.78%\\n\",\n      \"#3669: 96.78%\\n\",\n      \"#3670: 96.79%\\n\",\n      \"#3671: 96.79%\\n\",\n      \"#3672: 96.79%\\n\",\n      \"#3673: 96.79%\\n\",\n      \"#3674: 96.79%\\n\",\n      \"#3675: 96.79%\\n\",\n      \"#3676: 96.79%\\n\",\n      \"#3677: 96.79%\\n\",\n      \"#3678: 96.79%\\n\",\n      \"#3679: 96.79%\\n\",\n      \"#3680: 96.79%\\n\",\n      \"#3681: 96.80%\\n\",\n      \"#3682: 96.80%\\n\",\n      \"#3683: 96.80%\\n\",\n      \"#3684: 96.80%\\n\",\n      \"#3685: 96.80%\\n\",\n      \"#3686: 96.80%\\n\",\n      \"#3687: 96.80%\\n\",\n      \"#3688: 96.80%\\n\",\n      \"#3689: 96.80%\\n\",\n      \"#3690: 96.80%\\n\",\n      \"#3691: 96.80%\\n\",\n      \"#3692: 96.80%\\n\",\n      \"#3693: 96.81%\\n\",\n      \"#3694: 96.81%\\n\",\n      \"#3695: 96.81%\\n\",\n      \"#3696: 96.81%\\n\",\n      \"#3697: 96.81%\\n\",\n      \"#3698: 96.81%\\n\",\n      \"#3699: 96.81%\\n\",\n      \"#3700: 96.81%\\n\",\n      \"#3701: 96.81%\\n\",\n      \"#3702: 96.81%\\n\",\n      \"#3703: 96.81%\\n\",\n      \"#3704: 96.82%\\n\",\n      \"#3705: 96.82%\\n\",\n      \"#3706: 96.82%\\n\",\n      \"#3707: 96.82%\\n\",\n      \"#3708: 96.82%\\n\",\n      \"#3709: 96.82%\\n\",\n      \"#3710: 96.82%\\n\",\n      \"#3711: 96.82%\\n\",\n      \"#3712: 96.82%\\n\",\n      \"#3713: 96.82%\\n\",\n      \"#3714: 96.82%\\n\",\n      \"#3715: 96.82%\\n\",\n      \"#3716: 96.83%\\n\",\n      \"#3717: 96.83%\\n\",\n      \"#3718: 96.83%\\n\",\n      \"#3719: 96.83%\\n\",\n      \"#3720: 96.83%\\n\",\n      \"#3721: 96.83%\\n\",\n      \"#3722: 96.83%\\n\",\n      \"#3723: 96.83%\\n\",\n      \"#3724: 96.83%\\n\",\n      \"#3725: 96.83%\\n\",\n      \"#3726: 96.81%\\n\",\n      \"#3727: 96.81%\\n\",\n      \"#3728: 96.81%\\n\",\n      \"#3729: 96.81%\\n\",\n      \"#3730: 96.81%\\n\",\n      \"#3731: 96.81%\\n\",\n      \"#3732: 96.81%\\n\",\n      \"#3733: 96.81%\\n\",\n      \"#3734: 96.81%\\n\",\n      \"#3735: 96.81%\\n\",\n      \"#3736: 96.82%\\n\",\n      \"#3737: 96.82%\\n\",\n      \"#3738: 96.79%\\n\",\n      \"#3739: 96.79%\\n\",\n      \"#3740: 96.79%\\n\",\n      \"#3741: 96.79%\\n\",\n      \"#3742: 96.79%\\n\",\n      \"#3743: 96.79%\\n\",\n      \"#3744: 96.80%\\n\",\n      \"#3745: 96.80%\\n\",\n      \"#3746: 96.80%\\n\",\n      \"#3747: 96.80%\\n\",\n      \"#3748: 96.80%\\n\",\n      \"#3749: 96.80%\\n\",\n      \"#3750: 96.80%\\n\",\n      \"#3751: 96.80%\\n\",\n      \"#3752: 96.80%\\n\",\n      \"#3753: 96.80%\\n\",\n      \"#3754: 96.80%\\n\",\n      \"#3755: 96.81%\\n\",\n      \"#3756: 96.81%\\n\",\n      \"#3757: 96.78%\\n\",\n      \"#3758: 96.78%\\n\",\n      \"#3759: 96.78%\\n\",\n      \"#3760: 96.78%\\n\",\n      \"#3761: 96.78%\\n\",\n      \"#3762: 96.78%\\n\",\n      \"#3763: 96.79%\\n\",\n      \"#3764: 96.79%\\n\",\n      \"#3765: 96.79%\\n\",\n      \"#3766: 96.79%\\n\",\n      \"#3767: 96.76%\\n\",\n      \"#3768: 96.76%\\n\",\n      \"#3769: 96.76%\\n\",\n      \"#3770: 96.76%\\n\",\n      \"#3771: 96.77%\\n\",\n      \"#3772: 96.77%\\n\",\n      \"#3773: 96.77%\\n\",\n      \"#3774: 96.77%\\n\",\n      \"#3775: 96.77%\\n\",\n      \"#3776: 96.77%\\n\",\n      \"#3777: 96.77%\\n\",\n      \"#3778: 96.77%\\n\",\n      \"#3779: 96.77%\\n\",\n      \"#3780: 96.75%\\n\",\n      \"#3781: 96.75%\\n\",\n      \"#3782: 96.75%\\n\",\n      \"#3783: 96.75%\\n\",\n      \"#3784: 96.75%\\n\",\n      \"#3785: 96.75%\\n\",\n      \"#3786: 96.75%\\n\",\n      \"#3787: 96.75%\\n\",\n      \"#3788: 96.75%\\n\",\n      \"#3789: 96.75%\\n\",\n      \"#3790: 96.76%\\n\",\n      \"#3791: 96.76%\\n\",\n      \"#3792: 96.76%\\n\",\n      \"#3793: 96.76%\\n\",\n      \"#3794: 96.76%\\n\",\n      \"#3795: 96.76%\\n\",\n      \"#3796: 96.76%\\n\",\n      \"#3797: 96.76%\\n\",\n      \"#3798: 96.76%\\n\",\n      \"#3799: 96.76%\\n\",\n      \"#3800: 96.76%\\n\",\n      \"#3801: 96.76%\\n\",\n      \"#3802: 96.77%\\n\",\n      \"#3803: 96.77%\\n\",\n      \"#3804: 96.77%\\n\",\n      \"#3805: 96.77%\\n\",\n      \"#3806: 96.77%\\n\",\n      \"#3807: 96.77%\\n\",\n      \"#3808: 96.74%\\n\",\n      \"#3809: 96.75%\\n\",\n      \"#3810: 96.75%\\n\",\n      \"#3811: 96.75%\\n\",\n      \"#3812: 96.75%\\n\",\n      \"#3813: 96.75%\\n\",\n      \"#3814: 96.75%\\n\",\n      \"#3815: 96.75%\\n\",\n      \"#3816: 96.75%\\n\",\n      \"#3817: 96.75%\\n\",\n      \"#3818: 96.75%\\n\",\n      \"#3819: 96.75%\\n\",\n      \"#3820: 96.75%\\n\",\n      \"#3821: 96.76%\\n\",\n      \"#3822: 96.76%\\n\",\n      \"#3823: 96.76%\\n\",\n      \"#3824: 96.76%\\n\",\n      \"#3825: 96.76%\\n\",\n      \"#3826: 96.76%\\n\",\n      \"#3827: 96.76%\\n\",\n      \"#3828: 96.76%\\n\",\n      \"#3829: 96.76%\\n\",\n      \"#3830: 96.76%\\n\",\n      \"#3831: 96.76%\\n\",\n      \"#3832: 96.76%\\n\",\n      \"#3833: 96.77%\\n\",\n      \"#3834: 96.77%\\n\",\n      \"#3835: 96.77%\\n\",\n      \"#3836: 96.77%\\n\",\n      \"#3837: 96.77%\\n\",\n      \"#3838: 96.77%\\n\",\n      \"#3839: 96.77%\\n\",\n      \"#3840: 96.77%\\n\",\n      \"#3841: 96.77%\\n\",\n      \"#3842: 96.77%\\n\",\n      \"#3843: 96.77%\\n\",\n      \"#3844: 96.78%\\n\",\n      \"#3845: 96.78%\\n\",\n      \"#3846: 96.78%\\n\",\n      \"#3847: 96.78%\\n\",\n      \"#3848: 96.78%\\n\",\n      \"#3849: 96.78%\\n\",\n      \"#3850: 96.75%\\n\",\n      \"#3851: 96.75%\\n\",\n      \"#3852: 96.76%\\n\",\n      \"#3853: 96.76%\\n\",\n      \"#3854: 96.76%\\n\",\n      \"#3855: 96.73%\\n\",\n      \"#3856: 96.73%\\n\",\n      \"#3857: 96.73%\\n\",\n      \"#3858: 96.73%\\n\",\n      \"#3859: 96.74%\\n\",\n      \"#3860: 96.74%\\n\",\n      \"#3861: 96.74%\\n\",\n      \"#3862: 96.74%\\n\",\n      \"#3863: 96.74%\\n\",\n      \"#3864: 96.74%\\n\",\n      \"#3865: 96.74%\\n\",\n      \"#3866: 96.74%\\n\",\n      \"#3867: 96.74%\\n\",\n      \"#3868: 96.74%\\n\",\n      \"#3869: 96.74%\\n\",\n      \"#3870: 96.75%\\n\",\n      \"#3871: 96.75%\\n\",\n      \"#3872: 96.75%\\n\",\n      \"#3873: 96.75%\\n\",\n      \"#3874: 96.75%\\n\",\n      \"#3875: 96.75%\\n\",\n      \"#3876: 96.75%\\n\",\n      \"#3877: 96.75%\\n\",\n      \"#3878: 96.75%\\n\",\n      \"#3879: 96.75%\\n\",\n      \"#3880: 96.75%\\n\",\n      \"#3881: 96.75%\\n\",\n      \"#3882: 96.76%\\n\",\n      \"#3883: 96.76%\\n\",\n      \"#3884: 96.76%\\n\",\n      \"#3885: 96.76%\\n\",\n      \"#3886: 96.76%\\n\",\n      \"#3887: 96.76%\\n\",\n      \"#3888: 96.76%\\n\",\n      \"#3889: 96.76%\\n\",\n      \"#3890: 96.76%\\n\",\n      \"#3891: 96.76%\\n\",\n      \"#3892: 96.76%\\n\",\n      \"#3893: 96.76%\\n\",\n      \"#3894: 96.77%\\n\",\n      \"#3895: 96.77%\\n\",\n      \"#3896: 96.77%\\n\",\n      \"#3897: 96.77%\\n\",\n      \"#3898: 96.77%\\n\",\n      \"#3899: 96.77%\\n\",\n      \"#3900: 96.77%\\n\",\n      \"#3901: 96.77%\\n\",\n      \"#3902: 96.77%\\n\",\n      \"#3903: 96.77%\\n\",\n      \"#3904: 96.77%\\n\",\n      \"#3905: 96.77%\\n\",\n      \"#3906: 96.75%\\n\",\n      \"#3907: 96.75%\\n\",\n      \"#3908: 96.75%\\n\",\n      \"#3909: 96.75%\\n\",\n      \"#3910: 96.75%\\n\",\n      \"#3911: 96.75%\\n\",\n      \"#3912: 96.75%\\n\",\n      \"#3913: 96.76%\\n\",\n      \"#3914: 96.76%\\n\",\n      \"#3915: 96.76%\\n\",\n      \"#3916: 96.76%\\n\",\n      \"#3917: 96.76%\\n\",\n      \"#3918: 96.76%\\n\",\n      \"#3919: 96.76%\\n\",\n      \"#3920: 96.76%\\n\",\n      \"#3921: 96.76%\\n\",\n      \"#3922: 96.76%\\n\",\n      \"#3923: 96.76%\\n\",\n      \"#3924: 96.76%\\n\",\n      \"#3925: 96.77%\\n\",\n      \"#3926: 96.77%\\n\",\n      \"#3927: 96.77%\\n\",\n      \"#3928: 96.77%\\n\",\n      \"#3929: 96.77%\\n\",\n      \"#3930: 96.77%\\n\",\n      \"#3931: 96.77%\\n\",\n      \"#3932: 96.77%\\n\",\n      \"#3933: 96.77%\\n\",\n      \"#3934: 96.77%\\n\",\n      \"#3935: 96.77%\\n\",\n      \"#3936: 96.77%\\n\",\n      \"#3937: 96.78%\\n\",\n      \"#3938: 96.78%\\n\",\n      \"#3939: 96.78%\\n\",\n      \"#3940: 96.78%\\n\",\n      \"#3941: 96.78%\\n\",\n      \"#3942: 96.78%\\n\",\n      \"#3943: 96.75%\\n\",\n      \"#3944: 96.76%\\n\",\n      \"#3945: 96.76%\\n\",\n      \"#3946: 96.76%\\n\",\n      \"#3947: 96.76%\\n\",\n      \"#3948: 96.76%\\n\",\n      \"#3949: 96.76%\\n\",\n      \"#3950: 96.76%\\n\",\n      \"#3951: 96.76%\\n\",\n      \"#3952: 96.76%\\n\",\n      \"#3953: 96.76%\\n\",\n      \"#3954: 96.76%\\n\",\n      \"#3955: 96.76%\\n\",\n      \"#3956: 96.77%\\n\",\n      \"#3957: 96.77%\\n\",\n      \"#3958: 96.77%\\n\",\n      \"#3959: 96.77%\\n\",\n      \"#3960: 96.77%\\n\",\n      \"#3961: 96.77%\\n\",\n      \"#3962: 96.77%\\n\",\n      \"#3963: 96.77%\\n\",\n      \"#3964: 96.77%\\n\",\n      \"#3965: 96.77%\\n\",\n      \"#3966: 96.77%\\n\",\n      \"#3967: 96.77%\\n\",\n      \"#3968: 96.78%\\n\",\n      \"#3969: 96.78%\\n\",\n      \"#3970: 96.78%\\n\",\n      \"#3971: 96.78%\\n\",\n      \"#3972: 96.78%\\n\",\n      \"#3973: 96.78%\\n\",\n      \"#3974: 96.78%\\n\",\n      \"#3975: 96.78%\\n\",\n      \"#3976: 96.76%\\n\",\n      \"#3977: 96.76%\\n\",\n      \"#3978: 96.76%\\n\",\n      \"#3979: 96.76%\\n\",\n      \"#3980: 96.76%\\n\",\n      \"#3981: 96.76%\\n\",\n      \"#3982: 96.76%\\n\",\n      \"#3983: 96.76%\\n\",\n      \"#3984: 96.76%\\n\",\n      \"#3985: 96.76%\\n\",\n      \"#3986: 96.76%\\n\",\n      \"#3987: 96.77%\\n\",\n      \"#3988: 96.77%\\n\",\n      \"#3989: 96.77%\\n\",\n      \"#3990: 96.77%\\n\",\n      \"#3991: 96.77%\\n\",\n      \"#3992: 96.77%\\n\",\n      \"#3993: 96.77%\\n\",\n      \"#3994: 96.77%\\n\",\n      \"#3995: 96.77%\\n\",\n      \"#3996: 96.77%\\n\",\n      \"#3997: 96.77%\\n\",\n      \"#3998: 96.77%\\n\",\n      \"#3999: 96.78%\\n\",\n      \"#4000: 96.78%\\n\",\n      \"#4001: 96.78%\\n\",\n      \"#4002: 96.78%\\n\",\n      \"#4003: 96.78%\\n\",\n      \"#4004: 96.78%\\n\",\n      \"#4005: 96.78%\\n\",\n      \"#4006: 96.78%\\n\",\n      \"#4007: 96.78%\\n\",\n      \"#4008: 96.78%\\n\",\n      \"#4009: 96.78%\\n\",\n      \"#4010: 96.78%\\n\",\n      \"#4011: 96.78%\\n\",\n      \"#4012: 96.79%\\n\",\n      \"#4013: 96.79%\\n\",\n      \"#4014: 96.79%\\n\",\n      \"#4015: 96.79%\\n\",\n      \"#4016: 96.79%\\n\",\n      \"#4017: 96.79%\\n\",\n      \"#4018: 96.79%\\n\",\n      \"#4019: 96.79%\\n\",\n      \"#4020: 96.79%\\n\",\n      \"#4021: 96.79%\\n\",\n      \"#4022: 96.79%\\n\",\n      \"#4023: 96.79%\\n\",\n      \"#4024: 96.80%\\n\",\n      \"#4025: 96.80%\\n\",\n      \"#4026: 96.80%\\n\",\n      \"#4027: 96.80%\\n\",\n      \"#4028: 96.80%\\n\",\n      \"#4029: 96.80%\\n\",\n      \"#4030: 96.80%\\n\",\n      \"#4031: 96.80%\\n\",\n      \"#4032: 96.80%\\n\",\n      \"#4033: 96.80%\\n\",\n      \"#4034: 96.80%\\n\",\n      \"#4035: 96.80%\\n\",\n      \"#4036: 96.80%\\n\",\n      \"#4037: 96.81%\\n\",\n      \"#4038: 96.81%\\n\",\n      \"#4039: 96.81%\\n\",\n      \"#4040: 96.81%\\n\",\n      \"#4041: 96.81%\\n\",\n      \"#4042: 96.81%\\n\",\n      \"#4043: 96.81%\\n\",\n      \"#4044: 96.81%\\n\",\n      \"#4045: 96.81%\\n\",\n      \"#4046: 96.81%\\n\",\n      \"#4047: 96.81%\\n\",\n      \"#4048: 96.81%\\n\",\n      \"#4049: 96.81%\\n\",\n      \"#4050: 96.82%\\n\",\n      \"#4051: 96.82%\\n\",\n      \"#4052: 96.82%\\n\",\n      \"#4053: 96.82%\\n\",\n      \"#4054: 96.82%\\n\",\n      \"#4055: 96.82%\\n\",\n      \"#4056: 96.82%\\n\",\n      \"#4057: 96.82%\\n\",\n      \"#4058: 96.82%\\n\",\n      \"#4059: 96.82%\\n\",\n      \"#4060: 96.82%\\n\",\n      \"#4061: 96.82%\\n\",\n      \"#4062: 96.83%\\n\",\n      \"#4063: 96.80%\\n\",\n      \"#4064: 96.80%\\n\",\n      \"#4065: 96.80%\\n\",\n      \"#4066: 96.80%\\n\",\n      \"#4067: 96.80%\\n\",\n      \"#4068: 96.81%\\n\",\n      \"#4069: 96.81%\\n\",\n      \"#4070: 96.81%\\n\",\n      \"#4071: 96.81%\\n\",\n      \"#4072: 96.81%\\n\",\n      \"#4073: 96.81%\\n\",\n      \"#4074: 96.81%\\n\",\n      \"#4075: 96.81%\\n\",\n      \"#4076: 96.81%\\n\",\n      \"#4077: 96.81%\\n\",\n      \"#4078: 96.79%\\n\",\n      \"#4079: 96.79%\\n\",\n      \"#4080: 96.79%\\n\",\n      \"#4081: 96.79%\\n\",\n      \"#4082: 96.79%\\n\",\n      \"#4083: 96.79%\\n\",\n      \"#4084: 96.79%\\n\",\n      \"#4085: 96.79%\\n\",\n      \"#4086: 96.79%\\n\",\n      \"#4087: 96.80%\\n\",\n      \"#4088: 96.80%\\n\",\n      \"#4089: 96.80%\\n\",\n      \"#4090: 96.80%\\n\",\n      \"#4091: 96.80%\\n\",\n      \"#4092: 96.80%\\n\",\n      \"#4093: 96.80%\\n\",\n      \"#4094: 96.80%\\n\",\n      \"#4095: 96.80%\\n\",\n      \"#4096: 96.80%\\n\",\n      \"#4097: 96.80%\\n\",\n      \"#4098: 96.80%\\n\",\n      \"#4099: 96.80%\\n\",\n      \"#4100: 96.81%\\n\",\n      \"#4101: 96.81%\\n\",\n      \"#4102: 96.81%\\n\",\n      \"#4103: 96.81%\\n\",\n      \"#4104: 96.81%\\n\",\n      \"#4105: 96.81%\\n\",\n      \"#4106: 96.81%\\n\",\n      \"#4107: 96.81%\\n\",\n      \"#4108: 96.81%\\n\",\n      \"#4109: 96.81%\\n\",\n      \"#4110: 96.81%\\n\",\n      \"#4111: 96.81%\\n\",\n      \"#4112: 96.81%\\n\",\n      \"#4113: 96.82%\\n\",\n      \"#4114: 96.82%\\n\",\n      \"#4115: 96.82%\\n\",\n      \"#4116: 96.79%\\n\",\n      \"#4117: 96.79%\\n\",\n      \"#4118: 96.80%\\n\",\n      \"#4119: 96.80%\\n\",\n      \"#4120: 96.80%\\n\",\n      \"#4121: 96.80%\\n\",\n      \"#4122: 96.80%\\n\",\n      \"#4123: 96.77%\\n\",\n      \"#4124: 96.78%\\n\",\n      \"#4125: 96.78%\\n\",\n      \"#4126: 96.78%\\n\",\n      \"#4127: 96.78%\\n\",\n      \"#4128: 96.78%\\n\",\n      \"#4129: 96.78%\\n\",\n      \"#4130: 96.78%\\n\",\n      \"#4131: 96.78%\\n\",\n      \"#4132: 96.78%\\n\",\n      \"#4133: 96.78%\\n\",\n      \"#4134: 96.78%\\n\",\n      \"#4135: 96.78%\\n\",\n      \"#4136: 96.79%\\n\",\n      \"#4137: 96.79%\\n\",\n      \"#4138: 96.79%\\n\",\n      \"#4139: 96.79%\\n\",\n      \"#4140: 96.79%\\n\",\n      \"#4141: 96.79%\\n\",\n      \"#4142: 96.79%\\n\",\n      \"#4143: 96.79%\\n\",\n      \"#4144: 96.79%\\n\",\n      \"#4145: 96.79%\\n\",\n      \"#4146: 96.79%\\n\",\n      \"#4147: 96.79%\\n\",\n      \"#4148: 96.79%\\n\",\n      \"#4149: 96.80%\\n\",\n      \"#4150: 96.80%\\n\",\n      \"#4151: 96.80%\\n\",\n      \"#4152: 96.80%\\n\",\n      \"#4153: 96.80%\\n\",\n      \"#4154: 96.80%\\n\",\n      \"#4155: 96.80%\\n\",\n      \"#4156: 96.80%\\n\",\n      \"#4157: 96.80%\\n\",\n      \"#4158: 96.80%\\n\",\n      \"#4159: 96.80%\\n\",\n      \"#4160: 96.80%\\n\",\n      \"#4161: 96.80%\\n\",\n      \"#4162: 96.81%\\n\",\n      \"#4163: 96.78%\\n\",\n      \"#4164: 96.78%\\n\",\n      \"#4165: 96.78%\\n\",\n      \"#4166: 96.78%\\n\",\n      \"#4167: 96.79%\\n\",\n      \"#4168: 96.79%\\n\",\n      \"#4169: 96.79%\\n\",\n      \"#4170: 96.79%\\n\",\n      \"#4171: 96.79%\\n\",\n      \"#4172: 96.79%\\n\",\n      \"#4173: 96.79%\\n\",\n      \"#4174: 96.79%\\n\",\n      \"#4175: 96.79%\\n\",\n      \"#4176: 96.77%\\n\",\n      \"#4177: 96.77%\\n\",\n      \"#4178: 96.77%\\n\",\n      \"#4179: 96.77%\\n\",\n      \"#4180: 96.77%\\n\",\n      \"#4181: 96.77%\\n\",\n      \"#4182: 96.77%\\n\",\n      \"#4183: 96.77%\\n\",\n      \"#4184: 96.77%\\n\",\n      \"#4185: 96.77%\\n\",\n      \"#4186: 96.78%\\n\",\n      \"#4187: 96.78%\\n\",\n      \"#4188: 96.78%\\n\",\n      \"#4189: 96.78%\\n\",\n      \"#4190: 96.78%\\n\",\n      \"#4191: 96.78%\\n\",\n      \"#4192: 96.78%\\n\",\n      \"#4193: 96.78%\\n\",\n      \"#4194: 96.78%\\n\",\n      \"#4195: 96.78%\\n\",\n      \"#4196: 96.78%\\n\",\n      \"#4197: 96.78%\\n\",\n      \"#4198: 96.78%\\n\",\n      \"#4199: 96.79%\\n\",\n      \"#4200: 96.79%\\n\",\n      \"#4201: 96.79%\\n\",\n      \"#4202: 96.79%\\n\",\n      \"#4203: 96.79%\\n\",\n      \"#4204: 96.79%\\n\",\n      \"#4205: 96.77%\\n\",\n      \"#4206: 96.77%\\n\",\n      \"#4207: 96.77%\\n\",\n      \"#4208: 96.77%\\n\",\n      \"#4209: 96.77%\\n\",\n      \"#4210: 96.77%\\n\",\n      \"#4211: 96.77%\\n\",\n      \"#4212: 96.77%\\n\",\n      \"#4213: 96.77%\\n\",\n      \"#4214: 96.77%\\n\",\n      \"#4215: 96.77%\\n\",\n      \"#4216: 96.77%\\n\",\n      \"#4217: 96.78%\\n\",\n      \"#4218: 96.78%\\n\",\n      \"#4219: 96.78%\\n\",\n      \"#4220: 96.78%\\n\",\n      \"#4221: 96.78%\\n\",\n      \"#4222: 96.78%\\n\",\n      \"#4223: 96.78%\\n\",\n      \"#4224: 96.78%\\n\",\n      \"#4225: 96.78%\\n\",\n      \"#4226: 96.78%\\n\",\n      \"#4227: 96.78%\\n\",\n      \"#4228: 96.78%\\n\",\n      \"#4229: 96.78%\\n\",\n      \"#4230: 96.79%\\n\",\n      \"#4231: 96.79%\\n\",\n      \"#4232: 96.79%\\n\",\n      \"#4233: 96.79%\\n\",\n      \"#4234: 96.79%\\n\",\n      \"#4235: 96.79%\\n\",\n      \"#4236: 96.79%\\n\",\n      \"#4237: 96.79%\\n\",\n      \"#4238: 96.79%\\n\",\n      \"#4239: 96.79%\\n\",\n      \"#4240: 96.79%\\n\",\n      \"#4241: 96.79%\\n\",\n      \"#4242: 96.79%\\n\",\n      \"#4243: 96.80%\\n\",\n      \"#4244: 96.80%\\n\",\n      \"#4245: 96.80%\\n\",\n      \"#4246: 96.80%\\n\",\n      \"#4247: 96.80%\\n\",\n      \"#4248: 96.80%\\n\",\n      \"#4249: 96.80%\\n\",\n      \"#4250: 96.80%\\n\",\n      \"#4251: 96.80%\\n\",\n      \"#4252: 96.80%\\n\",\n      \"#4253: 96.80%\\n\",\n      \"#4254: 96.80%\\n\",\n      \"#4255: 96.80%\\n\",\n      \"#4256: 96.78%\\n\",\n      \"#4257: 96.78%\\n\",\n      \"#4258: 96.78%\\n\",\n      \"#4259: 96.78%\\n\",\n      \"#4260: 96.78%\\n\",\n      \"#4261: 96.79%\\n\",\n      \"#4262: 96.79%\\n\",\n      \"#4263: 96.79%\\n\",\n      \"#4264: 96.79%\\n\",\n      \"#4265: 96.77%\\n\",\n      \"#4266: 96.77%\\n\",\n      \"#4267: 96.77%\\n\",\n      \"#4268: 96.77%\\n\",\n      \"#4269: 96.77%\\n\",\n      \"#4270: 96.77%\\n\",\n      \"#4271: 96.77%\\n\",\n      \"#4272: 96.77%\\n\",\n      \"#4273: 96.77%\\n\",\n      \"#4274: 96.77%\\n\",\n      \"#4275: 96.77%\\n\",\n      \"#4276: 96.77%\\n\",\n      \"#4277: 96.77%\\n\",\n      \"#4278: 96.77%\\n\",\n      \"#4279: 96.78%\\n\",\n      \"#4280: 96.78%\\n\",\n      \"#4281: 96.78%\\n\",\n      \"#4282: 96.78%\\n\",\n      \"#4283: 96.78%\\n\",\n      \"#4284: 96.78%\\n\",\n      \"#4285: 96.78%\\n\",\n      \"#4286: 96.78%\\n\",\n      \"#4287: 96.78%\\n\",\n      \"#4288: 96.78%\\n\",\n      \"#4289: 96.78%\\n\",\n      \"#4290: 96.78%\\n\",\n      \"#4291: 96.78%\\n\",\n      \"#4292: 96.79%\\n\",\n      \"#4293: 96.79%\\n\",\n      \"#4294: 96.79%\\n\",\n      \"#4295: 96.79%\\n\",\n      \"#4296: 96.79%\\n\",\n      \"#4297: 96.79%\\n\",\n      \"#4298: 96.79%\\n\",\n      \"#4299: 96.79%\\n\",\n      \"#4300: 96.79%\\n\",\n      \"#4301: 96.79%\\n\",\n      \"#4302: 96.79%\\n\",\n      \"#4303: 96.79%\\n\",\n      \"#4304: 96.79%\\n\",\n      \"#4305: 96.80%\\n\",\n      \"#4306: 96.77%\\n\",\n      \"#4307: 96.77%\\n\",\n      \"#4308: 96.77%\\n\",\n      \"#4309: 96.77%\\n\",\n      \"#4310: 96.78%\\n\",\n      \"#4311: 96.78%\\n\",\n      \"#4312: 96.78%\\n\",\n      \"#4313: 96.78%\\n\",\n      \"#4314: 96.78%\\n\",\n      \"#4315: 96.78%\\n\",\n      \"#4316: 96.78%\\n\",\n      \"#4317: 96.78%\\n\",\n      \"#4318: 96.78%\\n\",\n      \"#4319: 96.78%\\n\",\n      \"#4320: 96.78%\\n\",\n      \"#4321: 96.78%\\n\",\n      \"#4322: 96.78%\\n\",\n      \"#4323: 96.79%\\n\",\n      \"#4324: 96.79%\\n\",\n      \"#4325: 96.79%\\n\",\n      \"#4326: 96.79%\\n\",\n      \"#4327: 96.79%\\n\",\n      \"#4328: 96.79%\\n\",\n      \"#4329: 96.79%\\n\",\n      \"#4330: 96.79%\\n\",\n      \"#4331: 96.79%\\n\",\n      \"#4332: 96.79%\\n\",\n      \"#4333: 96.79%\\n\",\n      \"#4334: 96.79%\\n\",\n      \"#4335: 96.79%\\n\",\n      \"#4336: 96.80%\\n\",\n      \"#4337: 96.80%\\n\",\n      \"#4338: 96.80%\\n\",\n      \"#4339: 96.80%\\n\",\n      \"#4340: 96.80%\\n\",\n      \"#4341: 96.80%\\n\",\n      \"#4342: 96.80%\\n\",\n      \"#4343: 96.80%\\n\",\n      \"#4344: 96.80%\\n\",\n      \"#4345: 96.80%\\n\",\n      \"#4346: 96.80%\\n\",\n      \"#4347: 96.80%\\n\",\n      \"#4348: 96.80%\\n\",\n      \"#4349: 96.80%\\n\",\n      \"#4350: 96.81%\\n\",\n      \"#4351: 96.81%\\n\",\n      \"#4352: 96.81%\\n\",\n      \"#4353: 96.81%\\n\",\n      \"#4354: 96.81%\\n\",\n      \"#4355: 96.81%\\n\",\n      \"#4356: 96.81%\\n\",\n      \"#4357: 96.81%\\n\",\n      \"#4358: 96.81%\\n\",\n      \"#4359: 96.81%\\n\",\n      \"#4360: 96.81%\\n\",\n      \"#4361: 96.81%\\n\",\n      \"#4362: 96.81%\\n\",\n      \"#4363: 96.81%\\n\",\n      \"#4364: 96.82%\\n\",\n      \"#4365: 96.82%\\n\",\n      \"#4366: 96.82%\\n\",\n      \"#4367: 96.82%\\n\",\n      \"#4368: 96.82%\\n\",\n      \"#4369: 96.82%\\n\",\n      \"#4370: 96.82%\\n\",\n      \"#4371: 96.82%\\n\",\n      \"#4372: 96.82%\\n\",\n      \"#4373: 96.82%\\n\",\n      \"#4374: 96.82%\\n\",\n      \"#4375: 96.82%\\n\",\n      \"#4376: 96.82%\\n\",\n      \"#4377: 96.83%\\n\",\n      \"#4378: 96.83%\\n\",\n      \"#4379: 96.83%\\n\",\n      \"#4380: 96.83%\\n\",\n      \"#4381: 96.83%\\n\",\n      \"#4382: 96.83%\\n\",\n      \"#4383: 96.83%\\n\",\n      \"#4384: 96.83%\\n\",\n      \"#4385: 96.83%\\n\",\n      \"#4386: 96.83%\\n\",\n      \"#4387: 96.83%\\n\",\n      \"#4388: 96.83%\\n\",\n      \"#4389: 96.83%\\n\",\n      \"#4390: 96.83%\\n\",\n      \"#4391: 96.81%\\n\",\n      \"#4392: 96.81%\\n\",\n      \"#4393: 96.81%\\n\",\n      \"#4394: 96.81%\\n\",\n      \"#4395: 96.82%\\n\",\n      \"#4396: 96.82%\\n\",\n      \"#4397: 96.82%\\n\",\n      \"#4398: 96.82%\\n\",\n      \"#4399: 96.82%\\n\",\n      \"#4400: 96.80%\\n\",\n      \"#4401: 96.80%\\n\",\n      \"#4402: 96.80%\\n\",\n      \"#4403: 96.80%\\n\",\n      \"#4404: 96.80%\\n\",\n      \"#4405: 96.80%\\n\",\n      \"#4406: 96.80%\\n\",\n      \"#4407: 96.80%\\n\",\n      \"#4408: 96.80%\\n\",\n      \"#4409: 96.80%\\n\",\n      \"#4410: 96.80%\\n\",\n      \"#4411: 96.80%\\n\",\n      \"#4412: 96.80%\\n\",\n      \"#4413: 96.81%\\n\",\n      \"#4414: 96.81%\\n\",\n      \"#4415: 96.81%\\n\",\n      \"#4416: 96.81%\\n\",\n      \"#4417: 96.81%\\n\",\n      \"#4418: 96.81%\\n\",\n      \"#4419: 96.81%\\n\",\n      \"#4420: 96.81%\\n\",\n      \"#4421: 96.81%\\n\",\n      \"#4422: 96.81%\\n\",\n      \"#4423: 96.81%\\n\",\n      \"#4424: 96.81%\\n\",\n      \"#4425: 96.81%\\n\",\n      \"#4426: 96.81%\\n\",\n      \"#4427: 96.82%\\n\",\n      \"#4428: 96.82%\\n\",\n      \"#4429: 96.82%\\n\",\n      \"#4430: 96.82%\\n\",\n      \"#4431: 96.82%\\n\",\n      \"#4432: 96.82%\\n\",\n      \"#4433: 96.82%\\n\",\n      \"#4434: 96.82%\\n\",\n      \"#4435: 96.82%\\n\",\n      \"#4436: 96.82%\\n\",\n      \"#4437: 96.82%\\n\",\n      \"#4438: 96.82%\\n\",\n      \"#4439: 96.82%\\n\",\n      \"#4440: 96.83%\\n\",\n      \"#4441: 96.83%\\n\",\n      \"#4442: 96.83%\\n\",\n      \"#4443: 96.80%\\n\",\n      \"#4444: 96.81%\\n\",\n      \"#4445: 96.81%\\n\",\n      \"#4446: 96.81%\\n\",\n      \"#4447: 96.81%\\n\",\n      \"#4448: 96.81%\\n\",\n      \"#4449: 96.81%\\n\",\n      \"#4450: 96.81%\\n\",\n      \"#4451: 96.81%\\n\",\n      \"#4452: 96.81%\\n\",\n      \"#4453: 96.81%\\n\",\n      \"#4454: 96.81%\\n\",\n      \"#4455: 96.81%\\n\",\n      \"#4456: 96.81%\\n\",\n      \"#4457: 96.81%\\n\",\n      \"#4458: 96.82%\\n\",\n      \"#4459: 96.82%\\n\",\n      \"#4460: 96.82%\\n\",\n      \"#4461: 96.82%\\n\",\n      \"#4462: 96.82%\\n\",\n      \"#4463: 96.82%\\n\",\n      \"#4464: 96.82%\\n\",\n      \"#4465: 96.82%\\n\",\n      \"#4466: 96.82%\\n\",\n      \"#4467: 96.82%\\n\",\n      \"#4468: 96.82%\\n\",\n      \"#4469: 96.82%\\n\",\n      \"#4470: 96.82%\\n\",\n      \"#4471: 96.82%\\n\",\n      \"#4472: 96.83%\\n\",\n      \"#4473: 96.83%\\n\",\n      \"#4474: 96.83%\\n\",\n      \"#4475: 96.83%\\n\",\n      \"#4476: 96.83%\\n\",\n      \"#4477: 96.83%\\n\",\n      \"#4478: 96.83%\\n\",\n      \"#4479: 96.83%\\n\",\n      \"#4480: 96.83%\\n\",\n      \"#4481: 96.83%\\n\",\n      \"#4482: 96.83%\\n\",\n      \"#4483: 96.83%\\n\",\n      \"#4484: 96.83%\\n\",\n      \"#4485: 96.83%\\n\",\n      \"#4486: 96.84%\\n\",\n      \"#4487: 96.84%\\n\",\n      \"#4488: 96.84%\\n\",\n      \"#4489: 96.84%\\n\",\n      \"#4490: 96.84%\\n\",\n      \"#4491: 96.84%\\n\",\n      \"#4492: 96.84%\\n\",\n      \"#4493: 96.84%\\n\",\n      \"#4494: 96.84%\\n\",\n      \"#4495: 96.84%\\n\",\n      \"#4496: 96.84%\\n\",\n      \"#4497: 96.82%\\n\",\n      \"#4498: 96.82%\\n\",\n      \"#4499: 96.82%\\n\",\n      \"#4500: 96.80%\\n\",\n      \"#4501: 96.80%\\n\",\n      \"#4502: 96.80%\\n\",\n      \"#4503: 96.80%\\n\",\n      \"#4504: 96.80%\\n\",\n      \"#4505: 96.78%\\n\",\n      \"#4506: 96.78%\\n\",\n      \"#4507: 96.78%\\n\",\n      \"#4508: 96.78%\\n\",\n      \"#4509: 96.78%\\n\",\n      \"#4510: 96.79%\\n\",\n      \"#4511: 96.79%\\n\",\n      \"#4512: 96.79%\\n\",\n      \"#4513: 96.79%\\n\",\n      \"#4514: 96.79%\\n\",\n      \"#4515: 96.79%\\n\",\n      \"#4516: 96.79%\\n\",\n      \"#4517: 96.79%\\n\",\n      \"#4518: 96.79%\\n\",\n      \"#4519: 96.79%\\n\",\n      \"#4520: 96.79%\\n\",\n      \"#4521: 96.79%\\n\",\n      \"#4522: 96.79%\\n\",\n      \"#4523: 96.79%\\n\",\n      \"#4524: 96.80%\\n\",\n      \"#4525: 96.80%\\n\",\n      \"#4526: 96.80%\\n\",\n      \"#4527: 96.80%\\n\",\n      \"#4528: 96.80%\\n\",\n      \"#4529: 96.80%\\n\",\n      \"#4530: 96.80%\\n\",\n      \"#4531: 96.80%\\n\",\n      \"#4532: 96.80%\\n\",\n      \"#4533: 96.80%\\n\",\n      \"#4534: 96.80%\\n\",\n      \"#4535: 96.80%\\n\",\n      \"#4536: 96.78%\\n\",\n      \"#4537: 96.78%\\n\",\n      \"#4538: 96.78%\\n\",\n      \"#4539: 96.78%\\n\",\n      \"#4540: 96.78%\\n\",\n      \"#4541: 96.79%\\n\",\n      \"#4542: 96.79%\\n\",\n      \"#4543: 96.79%\\n\",\n      \"#4544: 96.79%\\n\",\n      \"#4545: 96.79%\\n\",\n      \"#4546: 96.79%\\n\",\n      \"#4547: 96.79%\\n\",\n      \"#4548: 96.79%\\n\",\n      \"#4549: 96.79%\\n\",\n      \"#4550: 96.79%\\n\",\n      \"#4551: 96.79%\\n\",\n      \"#4552: 96.79%\\n\",\n      \"#4553: 96.79%\\n\",\n      \"#4554: 96.79%\\n\",\n      \"#4555: 96.80%\\n\",\n      \"#4556: 96.80%\\n\",\n      \"#4557: 96.80%\\n\",\n      \"#4558: 96.80%\\n\",\n      \"#4559: 96.80%\\n\",\n      \"#4560: 96.80%\\n\",\n      \"#4561: 96.80%\\n\",\n      \"#4562: 96.80%\\n\",\n      \"#4563: 96.80%\\n\",\n      \"#4564: 96.80%\\n\",\n      \"#4565: 96.80%\\n\",\n      \"#4566: 96.80%\\n\",\n      \"#4567: 96.80%\\n\",\n      \"#4568: 96.80%\\n\",\n      \"#4569: 96.81%\\n\",\n      \"#4570: 96.81%\\n\",\n      \"#4571: 96.78%\\n\",\n      \"#4572: 96.79%\\n\",\n      \"#4573: 96.79%\\n\",\n      \"#4574: 96.79%\\n\",\n      \"#4575: 96.79%\\n\",\n      \"#4576: 96.79%\\n\",\n      \"#4577: 96.79%\\n\",\n      \"#4578: 96.77%\\n\",\n      \"#4579: 96.77%\\n\",\n      \"#4580: 96.77%\\n\",\n      \"#4581: 96.77%\\n\",\n      \"#4582: 96.77%\\n\",\n      \"#4583: 96.77%\\n\",\n      \"#4584: 96.77%\\n\",\n      \"#4585: 96.77%\\n\",\n      \"#4586: 96.77%\\n\",\n      \"#4587: 96.77%\\n\",\n      \"#4588: 96.77%\\n\",\n      \"#4589: 96.78%\\n\",\n      \"#4590: 96.78%\\n\",\n      \"#4591: 96.78%\\n\",\n      \"#4592: 96.78%\\n\",\n      \"#4593: 96.78%\\n\",\n      \"#4594: 96.78%\\n\",\n      \"#4595: 96.78%\\n\",\n      \"#4596: 96.78%\\n\",\n      \"#4597: 96.78%\\n\",\n      \"#4598: 96.78%\\n\",\n      \"#4599: 96.78%\\n\",\n      \"#4600: 96.78%\\n\",\n      \"#4601: 96.78%\\n\",\n      \"#4602: 96.78%\\n\",\n      \"#4603: 96.79%\\n\",\n      \"#4604: 96.79%\\n\",\n      \"#4605: 96.79%\\n\",\n      \"#4606: 96.79%\\n\",\n      \"#4607: 96.79%\\n\",\n      \"#4608: 96.79%\\n\",\n      \"#4609: 96.79%\\n\",\n      \"#4610: 96.79%\\n\",\n      \"#4611: 96.79%\\n\",\n      \"#4612: 96.79%\\n\",\n      \"#4613: 96.79%\\n\",\n      \"#4614: 96.79%\\n\",\n      \"#4615: 96.77%\\n\",\n      \"#4616: 96.77%\\n\",\n      \"#4617: 96.77%\\n\",\n      \"#4618: 96.77%\\n\",\n      \"#4619: 96.77%\\n\",\n      \"#4620: 96.78%\\n\",\n      \"#4621: 96.78%\\n\",\n      \"#4622: 96.78%\\n\",\n      \"#4623: 96.78%\\n\",\n      \"#4624: 96.78%\\n\",\n      \"#4625: 96.78%\\n\",\n      \"#4626: 96.78%\\n\",\n      \"#4627: 96.78%\\n\",\n      \"#4628: 96.78%\\n\",\n      \"#4629: 96.78%\\n\",\n      \"#4630: 96.78%\\n\",\n      \"#4631: 96.78%\\n\",\n      \"#4632: 96.78%\\n\",\n      \"#4633: 96.78%\\n\",\n      \"#4634: 96.79%\\n\",\n      \"#4635: 96.79%\\n\",\n      \"#4636: 96.79%\\n\",\n      \"#4637: 96.79%\\n\",\n      \"#4638: 96.79%\\n\",\n      \"#4639: 96.77%\\n\",\n      \"#4640: 96.77%\\n\",\n      \"#4641: 96.77%\\n\",\n      \"#4642: 96.77%\\n\",\n      \"#4643: 96.77%\\n\",\n      \"#4644: 96.77%\\n\",\n      \"#4645: 96.77%\\n\",\n      \"#4646: 96.77%\\n\",\n      \"#4647: 96.77%\\n\",\n      \"#4648: 96.77%\\n\",\n      \"#4649: 96.77%\\n\",\n      \"#4650: 96.77%\\n\",\n      \"#4651: 96.78%\\n\",\n      \"#4652: 96.78%\\n\",\n      \"#4653: 96.78%\\n\",\n      \"#4654: 96.78%\\n\",\n      \"#4655: 96.78%\\n\",\n      \"#4656: 96.78%\\n\",\n      \"#4657: 96.78%\\n\",\n      \"#4658: 96.78%\\n\",\n      \"#4659: 96.78%\\n\",\n      \"#4660: 96.78%\\n\",\n      \"#4661: 96.78%\\n\",\n      \"#4662: 96.78%\\n\",\n      \"#4663: 96.78%\\n\",\n      \"#4664: 96.78%\\n\",\n      \"#4665: 96.79%\\n\",\n      \"#4666: 96.79%\\n\",\n      \"#4667: 96.79%\\n\",\n      \"#4668: 96.79%\\n\",\n      \"#4669: 96.79%\\n\",\n      \"#4670: 96.79%\\n\",\n      \"#4671: 96.79%\\n\",\n      \"#4672: 96.79%\\n\",\n      \"#4673: 96.79%\\n\",\n      \"#4674: 96.79%\\n\",\n      \"#4675: 96.79%\\n\",\n      \"#4676: 96.79%\\n\",\n      \"#4677: 96.79%\\n\",\n      \"#4678: 96.79%\\n\",\n      \"#4679: 96.79%\\n\",\n      \"#4680: 96.80%\\n\",\n      \"#4681: 96.80%\\n\",\n      \"#4682: 96.80%\\n\",\n      \"#4683: 96.80%\\n\",\n      \"#4684: 96.80%\\n\",\n      \"#4685: 96.80%\\n\",\n      \"#4686: 96.80%\\n\",\n      \"#4687: 96.80%\\n\",\n      \"#4688: 96.80%\\n\",\n      \"#4689: 96.80%\\n\",\n      \"#4690: 96.80%\\n\",\n      \"#4691: 96.80%\\n\",\n      \"#4692: 96.80%\\n\",\n      \"#4693: 96.80%\\n\",\n      \"#4694: 96.81%\\n\",\n      \"#4695: 96.81%\\n\",\n      \"#4696: 96.81%\\n\",\n      \"#4697: 96.81%\\n\",\n      \"#4698: 96.81%\\n\",\n      \"#4699: 96.81%\\n\",\n      \"#4700: 96.81%\\n\",\n      \"#4701: 96.81%\\n\",\n      \"#4702: 96.81%\\n\",\n      \"#4703: 96.81%\\n\",\n      \"#4704: 96.81%\\n\",\n      \"#4705: 96.81%\\n\",\n      \"#4706: 96.81%\\n\",\n      \"#4707: 96.81%\\n\",\n      \"#4708: 96.81%\\n\",\n      \"#4709: 96.82%\\n\",\n      \"#4710: 96.82%\\n\",\n      \"#4711: 96.82%\\n\",\n      \"#4712: 96.82%\\n\",\n      \"#4713: 96.82%\\n\",\n      \"#4714: 96.82%\\n\",\n      \"#4715: 96.82%\\n\",\n      \"#4716: 96.82%\\n\",\n      \"#4717: 96.82%\\n\",\n      \"#4718: 96.82%\\n\",\n      \"#4719: 96.82%\\n\",\n      \"#4720: 96.82%\\n\",\n      \"#4721: 96.82%\\n\",\n      \"#4722: 96.82%\\n\",\n      \"#4723: 96.82%\\n\",\n      \"#4724: 96.83%\\n\",\n      \"#4725: 96.83%\\n\",\n      \"#4726: 96.83%\\n\",\n      \"#4727: 96.83%\\n\",\n      \"#4728: 96.83%\\n\",\n      \"#4729: 96.83%\\n\",\n      \"#4730: 96.83%\\n\",\n      \"#4731: 96.83%\\n\",\n      \"#4732: 96.83%\\n\",\n      \"#4733: 96.83%\\n\",\n      \"#4734: 96.83%\\n\",\n      \"#4735: 96.83%\\n\",\n      \"#4736: 96.83%\\n\",\n      \"#4737: 96.81%\\n\",\n      \"#4738: 96.81%\\n\",\n      \"#4739: 96.81%\\n\",\n      \"#4740: 96.79%\\n\",\n      \"#4741: 96.79%\\n\",\n      \"#4742: 96.80%\\n\",\n      \"#4743: 96.80%\\n\",\n      \"#4744: 96.80%\\n\",\n      \"#4745: 96.80%\\n\",\n      \"#4746: 96.80%\\n\",\n      \"#4747: 96.80%\\n\",\n      \"#4748: 96.80%\\n\",\n      \"#4749: 96.80%\\n\",\n      \"#4750: 96.80%\\n\",\n      \"#4751: 96.78%\\n\",\n      \"#4752: 96.78%\\n\",\n      \"#4753: 96.78%\\n\",\n      \"#4754: 96.78%\\n\",\n      \"#4755: 96.78%\\n\",\n      \"#4756: 96.78%\\n\",\n      \"#4757: 96.78%\\n\",\n      \"#4758: 96.79%\\n\",\n      \"#4759: 96.79%\\n\",\n      \"#4760: 96.79%\\n\",\n      \"#4761: 96.77%\\n\",\n      \"#4762: 96.77%\\n\",\n      \"#4763: 96.77%\\n\",\n      \"#4764: 96.77%\\n\",\n      \"#4765: 96.77%\\n\",\n      \"#4766: 96.77%\\n\",\n      \"#4767: 96.77%\\n\",\n      \"#4768: 96.77%\\n\",\n      \"#4769: 96.77%\\n\",\n      \"#4770: 96.77%\\n\",\n      \"#4771: 96.77%\\n\",\n      \"#4772: 96.77%\\n\",\n      \"#4773: 96.77%\\n\",\n      \"#4774: 96.77%\\n\",\n      \"#4775: 96.78%\\n\",\n      \"#4776: 96.78%\\n\",\n      \"#4777: 96.78%\\n\",\n      \"#4778: 96.78%\\n\",\n      \"#4779: 96.78%\\n\",\n      \"#4780: 96.78%\\n\",\n      \"#4781: 96.78%\\n\",\n      \"#4782: 96.78%\\n\",\n      \"#4783: 96.76%\\n\",\n      \"#4784: 96.76%\\n\",\n      \"#4785: 96.76%\\n\",\n      \"#4786: 96.76%\\n\",\n      \"#4787: 96.76%\\n\",\n      \"#4788: 96.76%\\n\",\n      \"#4789: 96.76%\\n\",\n      \"#4790: 96.76%\\n\",\n      \"#4791: 96.77%\\n\",\n      \"#4792: 96.77%\\n\",\n      \"#4793: 96.77%\\n\",\n      \"#4794: 96.77%\\n\",\n      \"#4795: 96.77%\\n\",\n      \"#4796: 96.77%\\n\",\n      \"#4797: 96.77%\\n\",\n      \"#4798: 96.77%\\n\",\n      \"#4799: 96.77%\\n\",\n      \"#4800: 96.77%\\n\",\n      \"#4801: 96.77%\\n\",\n      \"#4802: 96.77%\\n\",\n      \"#4803: 96.77%\\n\",\n      \"#4804: 96.77%\\n\",\n      \"#4805: 96.77%\\n\",\n      \"#4806: 96.78%\\n\",\n      \"#4807: 96.76%\\n\",\n      \"#4808: 96.74%\\n\",\n      \"#4809: 96.74%\\n\",\n      \"#4810: 96.74%\\n\",\n      \"#4811: 96.74%\\n\",\n      \"#4812: 96.74%\\n\",\n      \"#4813: 96.74%\\n\",\n      \"#4814: 96.74%\\n\",\n      \"#4815: 96.74%\\n\",\n      \"#4816: 96.74%\\n\",\n      \"#4817: 96.74%\\n\",\n      \"#4818: 96.74%\\n\",\n      \"#4819: 96.74%\\n\",\n      \"#4820: 96.74%\\n\",\n      \"#4821: 96.74%\\n\",\n      \"#4822: 96.74%\\n\",\n      \"#4823: 96.75%\\n\",\n      \"#4824: 96.75%\\n\",\n      \"#4825: 96.75%\\n\",\n      \"#4826: 96.75%\\n\",\n      \"#4827: 96.75%\\n\",\n      \"#4828: 96.75%\\n\",\n      \"#4829: 96.75%\\n\",\n      \"#4830: 96.75%\\n\",\n      \"#4831: 96.75%\\n\",\n      \"#4832: 96.75%\\n\",\n      \"#4833: 96.75%\\n\",\n      \"#4834: 96.75%\\n\",\n      \"#4835: 96.75%\\n\",\n      \"#4836: 96.75%\\n\",\n      \"#4837: 96.75%\\n\",\n      \"#4838: 96.73%\\n\",\n      \"#4839: 96.74%\\n\",\n      \"#4840: 96.74%\\n\",\n      \"#4841: 96.74%\\n\",\n      \"#4842: 96.74%\\n\",\n      \"#4843: 96.74%\\n\",\n      \"#4844: 96.74%\\n\",\n      \"#4845: 96.74%\\n\",\n      \"#4846: 96.74%\\n\",\n      \"#4847: 96.74%\\n\",\n      \"#4848: 96.74%\\n\",\n      \"#4849: 96.74%\\n\",\n      \"#4850: 96.74%\\n\",\n      \"#4851: 96.74%\\n\",\n      \"#4852: 96.72%\\n\",\n      \"#4853: 96.72%\\n\",\n      \"#4854: 96.73%\\n\",\n      \"#4855: 96.73%\\n\",\n      \"#4856: 96.73%\\n\",\n      \"#4857: 96.73%\\n\",\n      \"#4858: 96.73%\\n\",\n      \"#4859: 96.73%\\n\",\n      \"#4860: 96.71%\\n\",\n      \"#4861: 96.71%\\n\",\n      \"#4862: 96.71%\\n\",\n      \"#4863: 96.71%\\n\",\n      \"#4864: 96.71%\\n\",\n      \"#4865: 96.71%\\n\",\n      \"#4866: 96.71%\\n\",\n      \"#4867: 96.71%\\n\",\n      \"#4868: 96.71%\\n\",\n      \"#4869: 96.71%\\n\",\n      \"#4870: 96.72%\\n\",\n      \"#4871: 96.72%\\n\",\n      \"#4872: 96.72%\\n\",\n      \"#4873: 96.72%\\n\",\n      \"#4874: 96.70%\\n\",\n      \"#4875: 96.70%\\n\",\n      \"#4876: 96.70%\\n\",\n      \"#4877: 96.70%\\n\",\n      \"#4878: 96.70%\\n\",\n      \"#4879: 96.68%\\n\",\n      \"#4880: 96.68%\\n\",\n      \"#4881: 96.68%\\n\",\n      \"#4882: 96.68%\\n\",\n      \"#4883: 96.68%\\n\",\n      \"#4884: 96.68%\\n\",\n      \"#4885: 96.68%\\n\",\n      \"#4886: 96.69%\\n\",\n      \"#4887: 96.69%\\n\",\n      \"#4888: 96.69%\\n\",\n      \"#4889: 96.69%\\n\",\n      \"#4890: 96.67%\\n\",\n      \"#4891: 96.67%\\n\",\n      \"#4892: 96.67%\\n\",\n      \"#4893: 96.67%\\n\",\n      \"#4894: 96.67%\\n\",\n      \"#4895: 96.67%\\n\",\n      \"#4896: 96.67%\\n\",\n      \"#4897: 96.67%\\n\",\n      \"#4898: 96.67%\\n\",\n      \"#4899: 96.67%\\n\",\n      \"#4900: 96.67%\\n\",\n      \"#4901: 96.67%\\n\",\n      \"#4902: 96.68%\\n\",\n      \"#4903: 96.68%\\n\",\n      \"#4904: 96.68%\\n\",\n      \"#4905: 96.68%\\n\",\n      \"#4906: 96.68%\\n\",\n      \"#4907: 96.68%\\n\",\n      \"#4908: 96.68%\\n\",\n      \"#4909: 96.68%\\n\",\n      \"#4910: 96.68%\\n\",\n      \"#4911: 96.68%\\n\",\n      \"#4912: 96.68%\\n\",\n      \"#4913: 96.68%\\n\",\n      \"#4914: 96.68%\\n\",\n      \"#4915: 96.68%\\n\",\n      \"#4916: 96.68%\\n\",\n      \"#4917: 96.69%\\n\",\n      \"#4918: 96.69%\\n\",\n      \"#4919: 96.69%\\n\",\n      \"#4920: 96.69%\\n\",\n      \"#4921: 96.69%\\n\",\n      \"#4922: 96.69%\\n\",\n      \"#4923: 96.69%\\n\",\n      \"#4924: 96.69%\\n\",\n      \"#4925: 96.69%\\n\",\n      \"#4926: 96.69%\\n\",\n      \"#4927: 96.69%\\n\",\n      \"#4928: 96.69%\\n\",\n      \"#4929: 96.69%\\n\",\n      \"#4930: 96.69%\\n\",\n      \"#4931: 96.70%\\n\",\n      \"#4932: 96.70%\\n\",\n      \"#4933: 96.70%\\n\",\n      \"#4934: 96.70%\\n\",\n      \"#4935: 96.70%\\n\",\n      \"#4936: 96.70%\\n\",\n      \"#4937: 96.70%\\n\",\n      \"#4938: 96.70%\\n\",\n      \"#4939: 96.70%\\n\",\n      \"#4940: 96.70%\\n\",\n      \"#4941: 96.70%\\n\",\n      \"#4942: 96.70%\\n\",\n      \"#4943: 96.70%\\n\",\n      \"#4944: 96.70%\\n\",\n      \"#4945: 96.70%\\n\",\n      \"#4946: 96.71%\\n\",\n      \"#4947: 96.71%\\n\",\n      \"#4948: 96.71%\\n\",\n      \"#4949: 96.71%\\n\",\n      \"#4950: 96.71%\\n\",\n      \"#4951: 96.71%\\n\",\n      \"#4952: 96.71%\\n\",\n      \"#4953: 96.71%\\n\",\n      \"#4954: 96.71%\\n\",\n      \"#4955: 96.71%\\n\",\n      \"#4956: 96.69%\\n\",\n      \"#4957: 96.69%\\n\",\n      \"#4958: 96.69%\\n\",\n      \"#4959: 96.69%\\n\",\n      \"#4960: 96.69%\\n\",\n      \"#4961: 96.69%\\n\",\n      \"#4962: 96.70%\\n\",\n      \"#4963: 96.70%\\n\",\n      \"#4964: 96.70%\\n\",\n      \"#4965: 96.70%\\n\",\n      \"#4966: 96.70%\\n\",\n      \"#4967: 96.70%\\n\",\n      \"#4968: 96.70%\\n\",\n      \"#4969: 96.70%\\n\",\n      \"#4970: 96.70%\\n\",\n      \"#4971: 96.70%\\n\",\n      \"#4972: 96.70%\\n\",\n      \"#4973: 96.70%\\n\",\n      \"#4974: 96.70%\\n\",\n      \"#4975: 96.70%\\n\",\n      \"#4976: 96.70%\\n\",\n      \"#4977: 96.71%\\n\",\n      \"#4978: 96.69%\\n\",\n      \"#4979: 96.69%\\n\",\n      \"#4980: 96.69%\\n\",\n      \"#4981: 96.69%\\n\",\n      \"#4982: 96.69%\\n\",\n      \"#4983: 96.69%\\n\",\n      \"#4984: 96.69%\\n\",\n      \"#4985: 96.69%\\n\",\n      \"#4986: 96.69%\\n\",\n      \"#4987: 96.69%\\n\",\n      \"#4988: 96.69%\\n\",\n      \"#4989: 96.69%\\n\",\n      \"#4990: 96.69%\\n\",\n      \"#4991: 96.69%\\n\",\n      \"#4992: 96.70%\\n\",\n      \"#4993: 96.70%\\n\",\n      \"#4994: 96.70%\\n\",\n      \"#4995: 96.70%\\n\",\n      \"#4996: 96.70%\\n\",\n      \"#4997: 96.70%\\n\",\n      \"#4998: 96.70%\\n\",\n      \"#4999: 96.70%\\n\",\n      \"#5000: 96.70%\\n\",\n      \"#5001: 96.70%\\n\",\n      \"#5002: 96.70%\\n\",\n      \"#5003: 96.70%\\n\",\n      \"#5004: 96.70%\\n\",\n      \"#5005: 96.70%\\n\",\n      \"#5006: 96.70%\\n\",\n      \"#5007: 96.71%\\n\",\n      \"#5008: 96.71%\\n\",\n      \"#5009: 96.71%\\n\",\n      \"#5010: 96.71%\\n\",\n      \"#5011: 96.71%\\n\",\n      \"#5012: 96.71%\\n\",\n      \"#5013: 96.71%\\n\",\n      \"#5014: 96.71%\\n\",\n      \"#5015: 96.71%\\n\",\n      \"#5016: 96.71%\\n\",\n      \"#5017: 96.71%\\n\",\n      \"#5018: 96.71%\\n\",\n      \"#5019: 96.71%\\n\",\n      \"#5020: 96.71%\\n\",\n      \"#5021: 96.71%\\n\",\n      \"#5022: 96.72%\\n\",\n      \"#5023: 96.72%\\n\",\n      \"#5024: 96.72%\\n\",\n      \"#5025: 96.72%\\n\",\n      \"#5026: 96.72%\\n\",\n      \"#5027: 96.72%\\n\",\n      \"#5028: 96.72%\\n\",\n      \"#5029: 96.72%\\n\",\n      \"#5030: 96.72%\\n\",\n      \"#5031: 96.72%\\n\",\n      \"#5032: 96.72%\\n\",\n      \"#5033: 96.72%\\n\",\n      \"#5034: 96.72%\\n\",\n      \"#5035: 96.72%\\n\",\n      \"#5036: 96.72%\\n\",\n      \"#5037: 96.72%\\n\",\n      \"#5038: 96.73%\\n\",\n      \"#5039: 96.73%\\n\",\n      \"#5040: 96.73%\\n\",\n      \"#5041: 96.73%\\n\",\n      \"#5042: 96.73%\\n\",\n      \"#5043: 96.73%\\n\",\n      \"#5044: 96.73%\\n\",\n      \"#5045: 96.73%\\n\",\n      \"#5046: 96.73%\\n\",\n      \"#5047: 96.73%\\n\",\n      \"#5048: 96.73%\\n\",\n      \"#5049: 96.73%\\n\",\n      \"#5050: 96.73%\\n\",\n      \"#5051: 96.73%\\n\",\n      \"#5052: 96.73%\\n\",\n      \"#5053: 96.74%\\n\",\n      \"#5054: 96.74%\\n\",\n      \"#5055: 96.74%\\n\",\n      \"#5056: 96.74%\\n\",\n      \"#5057: 96.74%\\n\",\n      \"#5058: 96.74%\\n\",\n      \"#5059: 96.74%\\n\",\n      \"#5060: 96.74%\\n\",\n      \"#5061: 96.74%\\n\",\n      \"#5062: 96.74%\\n\",\n      \"#5063: 96.74%\\n\",\n      \"#5064: 96.74%\\n\",\n      \"#5065: 96.74%\\n\",\n      \"#5066: 96.74%\\n\",\n      \"#5067: 96.74%\\n\",\n      \"#5068: 96.74%\\n\",\n      \"#5069: 96.75%\\n\",\n      \"#5070: 96.75%\\n\",\n      \"#5071: 96.75%\\n\",\n      \"#5072: 96.75%\\n\",\n      \"#5073: 96.75%\\n\",\n      \"#5074: 96.75%\\n\",\n      \"#5075: 96.75%\\n\",\n      \"#5076: 96.75%\\n\",\n      \"#5077: 96.75%\\n\",\n      \"#5078: 96.75%\\n\",\n      \"#5079: 96.75%\\n\",\n      \"#5080: 96.75%\\n\",\n      \"#5081: 96.75%\\n\",\n      \"#5082: 96.75%\\n\",\n      \"#5083: 96.75%\\n\",\n      \"#5084: 96.76%\\n\",\n      \"#5085: 96.76%\\n\",\n      \"#5086: 96.76%\\n\",\n      \"#5087: 96.76%\\n\",\n      \"#5088: 96.76%\\n\",\n      \"#5089: 96.76%\\n\",\n      \"#5090: 96.76%\\n\",\n      \"#5091: 96.76%\\n\",\n      \"#5092: 96.76%\\n\",\n      \"#5093: 96.76%\\n\",\n      \"#5094: 96.76%\\n\",\n      \"#5095: 96.76%\\n\",\n      \"#5096: 96.76%\\n\",\n      \"#5097: 96.76%\\n\",\n      \"#5098: 96.76%\\n\",\n      \"#5099: 96.76%\\n\",\n      \"#5100: 96.77%\\n\",\n      \"#5101: 96.77%\\n\",\n      \"#5102: 96.77%\\n\",\n      \"#5103: 96.77%\\n\",\n      \"#5104: 96.77%\\n\",\n      \"#5105: 96.77%\\n\",\n      \"#5106: 96.77%\\n\",\n      \"#5107: 96.77%\\n\",\n      \"#5108: 96.77%\\n\",\n      \"#5109: 96.77%\\n\",\n      \"#5110: 96.77%\\n\",\n      \"#5111: 96.77%\\n\",\n      \"#5112: 96.77%\\n\",\n      \"#5113: 96.77%\\n\",\n      \"#5114: 96.77%\\n\",\n      \"#5115: 96.77%\\n\",\n      \"#5116: 96.78%\\n\",\n      \"#5117: 96.78%\\n\",\n      \"#5118: 96.78%\\n\",\n      \"#5119: 96.78%\\n\",\n      \"#5120: 96.78%\\n\",\n      \"#5121: 96.78%\\n\",\n      \"#5122: 96.78%\\n\",\n      \"#5123: 96.78%\\n\",\n      \"#5124: 96.78%\\n\",\n      \"#5125: 96.78%\\n\",\n      \"#5126: 96.78%\\n\",\n      \"#5127: 96.78%\\n\",\n      \"#5128: 96.78%\\n\",\n      \"#5129: 96.78%\\n\",\n      \"#5130: 96.78%\\n\",\n      \"#5131: 96.78%\\n\",\n      \"#5132: 96.79%\\n\",\n      \"#5133: 96.79%\\n\",\n      \"#5134: 96.79%\\n\",\n      \"#5135: 96.79%\\n\",\n      \"#5136: 96.79%\\n\",\n      \"#5137: 96.79%\\n\",\n      \"#5138: 96.79%\\n\",\n      \"#5139: 96.79%\\n\",\n      \"#5140: 96.77%\\n\",\n      \"#5141: 96.77%\\n\",\n      \"#5142: 96.77%\\n\",\n      \"#5143: 96.77%\\n\",\n      \"#5144: 96.77%\\n\",\n      \"#5145: 96.77%\\n\",\n      \"#5146: 96.77%\\n\",\n      \"#5147: 96.78%\\n\",\n      \"#5148: 96.78%\\n\",\n      \"#5149: 96.78%\\n\",\n      \"#5150: 96.78%\\n\",\n      \"#5151: 96.78%\\n\",\n      \"#5152: 96.78%\\n\",\n      \"#5153: 96.78%\\n\",\n      \"#5154: 96.78%\\n\",\n      \"#5155: 96.78%\\n\",\n      \"#5156: 96.78%\\n\",\n      \"#5157: 96.78%\\n\",\n      \"#5158: 96.78%\\n\",\n      \"#5159: 96.76%\\n\",\n      \"#5160: 96.76%\\n\",\n      \"#5161: 96.76%\\n\",\n      \"#5162: 96.77%\\n\",\n      \"#5163: 96.77%\\n\",\n      \"#5164: 96.77%\\n\",\n      \"#5165: 96.77%\\n\",\n      \"#5166: 96.77%\\n\",\n      \"#5167: 96.77%\\n\",\n      \"#5168: 96.77%\\n\",\n      \"#5169: 96.77%\\n\",\n      \"#5170: 96.77%\\n\",\n      \"#5171: 96.77%\\n\",\n      \"#5172: 96.77%\\n\",\n      \"#5173: 96.77%\\n\",\n      \"#5174: 96.77%\\n\",\n      \"#5175: 96.77%\\n\",\n      \"#5176: 96.75%\\n\",\n      \"#5177: 96.76%\\n\",\n      \"#5178: 96.76%\\n\",\n      \"#5179: 96.76%\\n\",\n      \"#5180: 96.76%\\n\",\n      \"#5181: 96.76%\\n\",\n      \"#5182: 96.76%\\n\",\n      \"#5183: 96.74%\\n\",\n      \"#5184: 96.74%\\n\",\n      \"#5185: 96.74%\\n\",\n      \"#5186: 96.74%\\n\",\n      \"#5187: 96.74%\\n\",\n      \"#5188: 96.74%\\n\",\n      \"#5189: 96.74%\\n\",\n      \"#5190: 96.74%\\n\",\n      \"#5191: 96.74%\\n\",\n      \"#5192: 96.75%\\n\",\n      \"#5193: 96.75%\\n\",\n      \"#5194: 96.75%\\n\",\n      \"#5195: 96.75%\\n\",\n      \"#5196: 96.75%\\n\",\n      \"#5197: 96.75%\\n\",\n      \"#5198: 96.75%\\n\",\n      \"#5199: 96.75%\\n\",\n      \"#5200: 96.75%\\n\",\n      \"#5201: 96.75%\\n\",\n      \"#5202: 96.75%\\n\",\n      \"#5203: 96.75%\\n\",\n      \"#5204: 96.75%\\n\",\n      \"#5205: 96.75%\\n\",\n      \"#5206: 96.75%\\n\",\n      \"#5207: 96.75%\\n\",\n      \"#5208: 96.76%\\n\",\n      \"#5209: 96.76%\\n\",\n      \"#5210: 96.76%\\n\",\n      \"#5211: 96.76%\\n\",\n      \"#5212: 96.76%\\n\",\n      \"#5213: 96.76%\\n\",\n      \"#5214: 96.76%\\n\",\n      \"#5215: 96.76%\\n\",\n      \"#5216: 96.76%\\n\",\n      \"#5217: 96.76%\\n\",\n      \"#5218: 96.76%\\n\",\n      \"#5219: 96.76%\\n\",\n      \"#5220: 96.76%\\n\",\n      \"#5221: 96.76%\\n\",\n      \"#5222: 96.76%\\n\",\n      \"#5223: 96.76%\\n\",\n      \"#5224: 96.77%\\n\",\n      \"#5225: 96.77%\\n\",\n      \"#5226: 96.77%\\n\",\n      \"#5227: 96.77%\\n\",\n      \"#5228: 96.77%\\n\",\n      \"#5229: 96.77%\\n\",\n      \"#5230: 96.77%\\n\",\n      \"#5231: 96.77%\\n\",\n      \"#5232: 96.77%\\n\",\n      \"#5233: 96.77%\\n\",\n      \"#5234: 96.77%\\n\",\n      \"#5235: 96.77%\\n\",\n      \"#5236: 96.77%\\n\",\n      \"#5237: 96.77%\\n\",\n      \"#5238: 96.77%\\n\",\n      \"#5239: 96.77%\\n\",\n      \"#5240: 96.78%\\n\",\n      \"#5241: 96.78%\\n\",\n      \"#5242: 96.78%\\n\",\n      \"#5243: 96.78%\\n\",\n      \"#5244: 96.78%\\n\",\n      \"#5245: 96.78%\\n\",\n      \"#5246: 96.78%\\n\",\n      \"#5247: 96.78%\\n\",\n      \"#5248: 96.78%\\n\",\n      \"#5249: 96.78%\\n\",\n      \"#5250: 96.78%\\n\",\n      \"#5251: 96.78%\\n\",\n      \"#5252: 96.78%\\n\",\n      \"#5253: 96.78%\\n\",\n      \"#5254: 96.78%\\n\",\n      \"#5255: 96.78%\\n\",\n      \"#5256: 96.79%\\n\",\n      \"#5257: 96.79%\\n\",\n      \"#5258: 96.79%\\n\",\n      \"#5259: 96.79%\\n\",\n      \"#5260: 96.79%\\n\",\n      \"#5261: 96.79%\\n\",\n      \"#5262: 96.79%\\n\",\n      \"#5263: 96.79%\\n\",\n      \"#5264: 96.79%\\n\",\n      \"#5265: 96.79%\\n\",\n      \"#5266: 96.79%\\n\",\n      \"#5267: 96.79%\\n\",\n      \"#5268: 96.79%\\n\",\n      \"#5269: 96.79%\\n\",\n      \"#5270: 96.79%\\n\",\n      \"#5271: 96.79%\\n\",\n      \"#5272: 96.79%\\n\",\n      \"#5273: 96.80%\\n\",\n      \"#5274: 96.80%\\n\",\n      \"#5275: 96.80%\\n\",\n      \"#5276: 96.80%\\n\",\n      \"#5277: 96.80%\\n\",\n      \"#5278: 96.80%\\n\",\n      \"#5279: 96.80%\\n\",\n      \"#5280: 96.80%\\n\",\n      \"#5281: 96.80%\\n\",\n      \"#5282: 96.80%\\n\",\n      \"#5283: 96.80%\\n\",\n      \"#5284: 96.80%\\n\",\n      \"#5285: 96.80%\\n\",\n      \"#5286: 96.80%\\n\",\n      \"#5287: 96.80%\\n\",\n      \"#5288: 96.80%\\n\",\n      \"#5289: 96.81%\\n\",\n      \"#5290: 96.81%\\n\",\n      \"#5291: 96.81%\\n\",\n      \"#5292: 96.81%\\n\",\n      \"#5293: 96.81%\\n\",\n      \"#5294: 96.81%\\n\",\n      \"#5295: 96.81%\\n\",\n      \"#5296: 96.81%\\n\",\n      \"#5297: 96.81%\\n\",\n      \"#5298: 96.81%\\n\",\n      \"#5299: 96.81%\\n\",\n      \"#5300: 96.81%\\n\",\n      \"#5301: 96.81%\\n\",\n      \"#5302: 96.81%\\n\",\n      \"#5303: 96.81%\\n\",\n      \"#5304: 96.81%\\n\",\n      \"#5305: 96.81%\\n\",\n      \"#5306: 96.82%\\n\",\n      \"#5307: 96.82%\\n\",\n      \"#5308: 96.82%\\n\",\n      \"#5309: 96.82%\\n\",\n      \"#5310: 96.82%\\n\",\n      \"#5311: 96.82%\\n\",\n      \"#5312: 96.82%\\n\",\n      \"#5313: 96.82%\\n\",\n      \"#5314: 96.82%\\n\",\n      \"#5315: 96.82%\\n\",\n      \"#5316: 96.82%\\n\",\n      \"#5317: 96.82%\\n\",\n      \"#5318: 96.82%\\n\",\n      \"#5319: 96.82%\\n\",\n      \"#5320: 96.82%\\n\",\n      \"#5321: 96.82%\\n\",\n      \"#5322: 96.83%\\n\",\n      \"#5323: 96.83%\\n\",\n      \"#5324: 96.83%\\n\",\n      \"#5325: 96.83%\\n\",\n      \"#5326: 96.83%\\n\",\n      \"#5327: 96.83%\\n\",\n      \"#5328: 96.83%\\n\",\n      \"#5329: 96.83%\\n\",\n      \"#5330: 96.83%\\n\",\n      \"#5331: 96.83%\\n\",\n      \"#5332: 96.83%\\n\",\n      \"#5333: 96.83%\\n\",\n      \"#5334: 96.83%\\n\",\n      \"#5335: 96.83%\\n\",\n      \"#5336: 96.83%\\n\",\n      \"#5337: 96.83%\\n\",\n      \"#5338: 96.83%\\n\",\n      \"#5339: 96.84%\\n\",\n      \"#5340: 96.84%\\n\",\n      \"#5341: 96.84%\\n\",\n      \"#5342: 96.84%\\n\",\n      \"#5343: 96.84%\\n\",\n      \"#5344: 96.84%\\n\",\n      \"#5345: 96.84%\\n\",\n      \"#5346: 96.84%\\n\",\n      \"#5347: 96.84%\\n\",\n      \"#5348: 96.84%\\n\",\n      \"#5349: 96.84%\\n\",\n      \"#5350: 96.84%\\n\",\n      \"#5351: 96.84%\\n\",\n      \"#5352: 96.84%\\n\",\n      \"#5353: 96.84%\\n\",\n      \"#5354: 96.84%\\n\",\n      \"#5355: 96.84%\\n\",\n      \"#5356: 96.85%\\n\",\n      \"#5357: 96.85%\\n\",\n      \"#5358: 96.85%\\n\",\n      \"#5359: 96.85%\\n\",\n      \"#5360: 96.85%\\n\",\n      \"#5361: 96.85%\\n\",\n      \"#5362: 96.85%\\n\",\n      \"#5363: 96.85%\\n\",\n      \"#5364: 96.85%\\n\",\n      \"#5365: 96.85%\\n\",\n      \"#5366: 96.85%\\n\",\n      \"#5367: 96.85%\\n\",\n      \"#5368: 96.85%\\n\",\n      \"#5369: 96.85%\\n\",\n      \"#5370: 96.85%\\n\",\n      \"#5371: 96.85%\\n\",\n      \"#5372: 96.85%\\n\",\n      \"#5373: 96.86%\\n\",\n      \"#5374: 96.86%\\n\",\n      \"#5375: 96.86%\\n\",\n      \"#5376: 96.86%\\n\",\n      \"#5377: 96.86%\\n\",\n      \"#5378: 96.86%\\n\",\n      \"#5379: 96.86%\\n\",\n      \"#5380: 96.86%\\n\",\n      \"#5381: 96.86%\\n\",\n      \"#5382: 96.86%\\n\",\n      \"#5383: 96.86%\\n\",\n      \"#5384: 96.86%\\n\",\n      \"#5385: 96.86%\\n\",\n      \"#5386: 96.86%\\n\",\n      \"#5387: 96.86%\\n\",\n      \"#5388: 96.86%\\n\",\n      \"#5389: 96.86%\\n\",\n      \"#5390: 96.87%\\n\",\n      \"#5391: 96.87%\\n\",\n      \"#5392: 96.87%\\n\",\n      \"#5393: 96.87%\\n\",\n      \"#5394: 96.87%\\n\",\n      \"#5395: 96.87%\\n\",\n      \"#5396: 96.87%\\n\",\n      \"#5397: 96.87%\\n\",\n      \"#5398: 96.87%\\n\",\n      \"#5399: 96.87%\\n\",\n      \"#5400: 96.87%\\n\",\n      \"#5401: 96.87%\\n\",\n      \"#5402: 96.87%\\n\",\n      \"#5403: 96.87%\\n\",\n      \"#5404: 96.87%\\n\",\n      \"#5405: 96.87%\\n\",\n      \"#5406: 96.87%\\n\",\n      \"#5407: 96.88%\\n\",\n      \"#5408: 96.88%\\n\",\n      \"#5409: 96.88%\\n\",\n      \"#5410: 96.88%\\n\",\n      \"#5411: 96.88%\\n\",\n      \"#5412: 96.88%\\n\",\n      \"#5413: 96.88%\\n\",\n      \"#5414: 96.88%\\n\",\n      \"#5415: 96.88%\\n\",\n      \"#5416: 96.88%\\n\",\n      \"#5417: 96.88%\\n\",\n      \"#5418: 96.88%\\n\",\n      \"#5419: 96.88%\\n\",\n      \"#5420: 96.88%\\n\",\n      \"#5421: 96.88%\\n\",\n      \"#5422: 96.88%\\n\",\n      \"#5423: 96.88%\\n\",\n      \"#5424: 96.88%\\n\",\n      \"#5425: 96.89%\\n\",\n      \"#5426: 96.89%\\n\",\n      \"#5427: 96.89%\\n\",\n      \"#5428: 96.89%\\n\",\n      \"#5429: 96.89%\\n\",\n      \"#5430: 96.89%\\n\",\n      \"#5431: 96.89%\\n\",\n      \"#5432: 96.89%\\n\",\n      \"#5433: 96.89%\\n\",\n      \"#5434: 96.89%\\n\",\n      \"#5435: 96.89%\\n\",\n      \"#5436: 96.89%\\n\",\n      \"#5437: 96.89%\\n\",\n      \"#5438: 96.89%\\n\",\n      \"#5439: 96.89%\\n\",\n      \"#5440: 96.89%\\n\",\n      \"#5441: 96.89%\\n\",\n      \"#5442: 96.90%\\n\",\n      \"#5443: 96.90%\\n\",\n      \"#5444: 96.90%\\n\",\n      \"#5445: 96.90%\\n\",\n      \"#5446: 96.90%\\n\",\n      \"#5447: 96.90%\\n\",\n      \"#5448: 96.90%\\n\",\n      \"#5449: 96.90%\\n\",\n      \"#5450: 96.90%\\n\",\n      \"#5451: 96.90%\\n\",\n      \"#5452: 96.90%\\n\",\n      \"#5453: 96.90%\\n\",\n      \"#5454: 96.90%\\n\",\n      \"#5455: 96.90%\\n\",\n      \"#5456: 96.90%\\n\",\n      \"#5457: 96.90%\\n\",\n      \"#5458: 96.90%\\n\",\n      \"#5459: 96.90%\\n\",\n      \"#5460: 96.91%\\n\",\n      \"#5461: 96.91%\\n\",\n      \"#5462: 96.91%\\n\",\n      \"#5463: 96.91%\\n\",\n      \"#5464: 96.91%\\n\",\n      \"#5465: 96.91%\\n\",\n      \"#5466: 96.91%\\n\",\n      \"#5467: 96.91%\\n\",\n      \"#5468: 96.91%\\n\",\n      \"#5469: 96.91%\\n\",\n      \"#5470: 96.91%\\n\",\n      \"#5471: 96.91%\\n\",\n      \"#5472: 96.91%\\n\",\n      \"#5473: 96.91%\\n\",\n      \"#5474: 96.91%\\n\",\n      \"#5475: 96.91%\\n\",\n      \"#5476: 96.91%\\n\",\n      \"#5477: 96.91%\\n\",\n      \"#5478: 96.92%\\n\",\n      \"#5479: 96.92%\\n\",\n      \"#5480: 96.92%\\n\",\n      \"#5481: 96.92%\\n\",\n      \"#5482: 96.92%\\n\",\n      \"#5483: 96.92%\\n\",\n      \"#5484: 96.92%\\n\",\n      \"#5485: 96.92%\\n\",\n      \"#5486: 96.92%\\n\",\n      \"#5487: 96.92%\\n\",\n      \"#5488: 96.92%\\n\",\n      \"#5489: 96.92%\\n\",\n      \"#5490: 96.92%\\n\",\n      \"#5491: 96.92%\\n\",\n      \"#5492: 96.92%\\n\",\n      \"#5493: 96.92%\\n\",\n      \"#5494: 96.92%\\n\",\n      \"#5495: 96.93%\\n\",\n      \"#5496: 96.93%\\n\",\n      \"#5497: 96.93%\\n\",\n      \"#5498: 96.93%\\n\",\n      \"#5499: 96.93%\\n\",\n      \"#5500: 96.93%\\n\",\n      \"#5501: 96.93%\\n\",\n      \"#5502: 96.93%\\n\",\n      \"#5503: 96.93%\\n\",\n      \"#5504: 96.93%\\n\",\n      \"#5505: 96.93%\\n\",\n      \"#5506: 96.93%\\n\",\n      \"#5507: 96.93%\\n\",\n      \"#5508: 96.93%\\n\",\n      \"#5509: 96.93%\\n\",\n      \"#5510: 96.93%\\n\",\n      \"#5511: 96.93%\\n\",\n      \"#5512: 96.93%\\n\",\n      \"#5513: 96.94%\\n\",\n      \"#5514: 96.94%\\n\",\n      \"#5515: 96.94%\\n\",\n      \"#5516: 96.94%\\n\",\n      \"#5517: 96.94%\\n\",\n      \"#5518: 96.94%\\n\",\n      \"#5519: 96.94%\\n\",\n      \"#5520: 96.94%\\n\",\n      \"#5521: 96.94%\\n\",\n      \"#5522: 96.94%\\n\",\n      \"#5523: 96.94%\\n\",\n      \"#5524: 96.94%\\n\",\n      \"#5525: 96.94%\\n\",\n      \"#5526: 96.94%\\n\",\n      \"#5527: 96.94%\\n\",\n      \"#5528: 96.94%\\n\",\n      \"#5529: 96.94%\\n\",\n      \"#5530: 96.94%\\n\",\n      \"#5531: 96.95%\\n\",\n      \"#5532: 96.95%\\n\",\n      \"#5533: 96.95%\\n\",\n      \"#5534: 96.95%\\n\",\n      \"#5535: 96.95%\\n\",\n      \"#5536: 96.95%\\n\",\n      \"#5537: 96.95%\\n\",\n      \"#5538: 96.95%\\n\",\n      \"#5539: 96.95%\\n\",\n      \"#5540: 96.95%\\n\",\n      \"#5541: 96.95%\\n\",\n      \"#5542: 96.95%\\n\",\n      \"#5543: 96.95%\\n\",\n      \"#5544: 96.95%\\n\",\n      \"#5545: 96.95%\\n\",\n      \"#5546: 96.95%\\n\",\n      \"#5547: 96.95%\\n\",\n      \"#5548: 96.95%\\n\",\n      \"#5549: 96.95%\\n\",\n      \"#5550: 96.96%\\n\",\n      \"#5551: 96.96%\\n\",\n      \"#5552: 96.96%\\n\",\n      \"#5553: 96.96%\\n\",\n      \"#5554: 96.96%\\n\",\n      \"#5555: 96.96%\\n\",\n      \"#5556: 96.96%\\n\",\n      \"#5557: 96.96%\\n\",\n      \"#5558: 96.96%\\n\",\n      \"#5559: 96.96%\\n\",\n      \"#5560: 96.96%\\n\",\n      \"#5561: 96.96%\\n\",\n      \"#5562: 96.96%\\n\",\n      \"#5563: 96.96%\\n\",\n      \"#5564: 96.96%\\n\",\n      \"#5565: 96.96%\\n\",\n      \"#5566: 96.96%\\n\",\n      \"#5567: 96.96%\\n\",\n      \"#5568: 96.97%\\n\",\n      \"#5569: 96.97%\\n\",\n      \"#5570: 96.97%\\n\",\n      \"#5571: 96.97%\\n\",\n      \"#5572: 96.97%\\n\",\n      \"#5573: 96.97%\\n\",\n      \"#5574: 96.97%\\n\",\n      \"#5575: 96.97%\\n\",\n      \"#5576: 96.97%\\n\",\n      \"#5577: 96.97%\\n\",\n      \"#5578: 96.97%\\n\",\n      \"#5579: 96.97%\\n\",\n      \"#5580: 96.97%\\n\",\n      \"#5581: 96.97%\\n\",\n      \"#5582: 96.97%\\n\",\n      \"#5583: 96.97%\\n\",\n      \"#5584: 96.97%\\n\",\n      \"#5585: 96.97%\\n\",\n      \"#5586: 96.98%\\n\",\n      \"#5587: 96.98%\\n\",\n      \"#5588: 96.98%\\n\",\n      \"#5589: 96.98%\\n\",\n      \"#5590: 96.98%\\n\",\n      \"#5591: 96.98%\\n\",\n      \"#5592: 96.98%\\n\",\n      \"#5593: 96.98%\\n\",\n      \"#5594: 96.98%\\n\",\n      \"#5595: 96.98%\\n\",\n      \"#5596: 96.98%\\n\",\n      \"#5597: 96.98%\\n\",\n      \"#5598: 96.98%\\n\",\n      \"#5599: 96.98%\\n\",\n      \"#5600: 96.96%\\n\",\n      \"#5601: 96.97%\\n\",\n      \"#5602: 96.97%\\n\",\n      \"#5603: 96.97%\\n\",\n      \"#5604: 96.97%\\n\",\n      \"#5605: 96.97%\\n\",\n      \"#5606: 96.97%\\n\",\n      \"#5607: 96.97%\\n\",\n      \"#5608: 96.97%\\n\",\n      \"#5609: 96.97%\\n\",\n      \"#5610: 96.97%\\n\",\n      \"#5611: 96.97%\\n\",\n      \"#5612: 96.97%\\n\",\n      \"#5613: 96.97%\\n\",\n      \"#5614: 96.97%\\n\",\n      \"#5615: 96.97%\\n\",\n      \"#5616: 96.97%\\n\",\n      \"#5617: 96.97%\\n\",\n      \"#5618: 96.97%\\n\",\n      \"#5619: 96.98%\\n\",\n      \"#5620: 96.98%\\n\",\n      \"#5621: 96.98%\\n\",\n      \"#5622: 96.98%\\n\",\n      \"#5623: 96.98%\\n\",\n      \"#5624: 96.98%\\n\",\n      \"#5625: 96.98%\\n\",\n      \"#5626: 96.98%\\n\",\n      \"#5627: 96.98%\\n\",\n      \"#5628: 96.98%\\n\",\n      \"#5629: 96.98%\\n\",\n      \"#5630: 96.98%\\n\",\n      \"#5631: 96.98%\\n\",\n      \"#5632: 96.98%\\n\",\n      \"#5633: 96.98%\\n\",\n      \"#5634: 96.98%\\n\",\n      \"#5635: 96.98%\\n\",\n      \"#5636: 96.98%\\n\",\n      \"#5637: 96.98%\\n\",\n      \"#5638: 96.99%\\n\",\n      \"#5639: 96.99%\\n\",\n      \"#5640: 96.99%\\n\",\n      \"#5641: 96.99%\\n\",\n      \"#5642: 96.99%\\n\",\n      \"#5643: 96.99%\\n\",\n      \"#5644: 96.99%\\n\",\n      \"#5645: 96.99%\\n\",\n      \"#5646: 96.99%\\n\",\n      \"#5647: 96.99%\\n\",\n      \"#5648: 96.99%\\n\",\n      \"#5649: 96.99%\\n\",\n      \"#5650: 96.99%\\n\",\n      \"#5651: 96.99%\\n\",\n      \"#5652: 96.99%\\n\",\n      \"#5653: 96.99%\\n\",\n      \"#5654: 96.99%\\n\",\n      \"#5655: 96.99%\\n\",\n      \"#5656: 96.99%\\n\",\n      \"#5657: 97.00%\\n\",\n      \"#5658: 97.00%\\n\",\n      \"#5659: 97.00%\\n\",\n      \"#5660: 97.00%\\n\",\n      \"#5661: 97.00%\\n\",\n      \"#5662: 97.00%\\n\",\n      \"#5663: 97.00%\\n\",\n      \"#5664: 97.00%\\n\",\n      \"#5665: 97.00%\\n\",\n      \"#5666: 97.00%\\n\",\n      \"#5667: 97.00%\\n\",\n      \"#5668: 97.00%\\n\",\n      \"#5669: 97.00%\\n\",\n      \"#5670: 97.00%\\n\",\n      \"#5671: 97.00%\\n\",\n      \"#5672: 97.00%\\n\",\n      \"#5673: 97.00%\\n\",\n      \"#5674: 97.00%\\n\",\n      \"#5675: 97.00%\\n\",\n      \"#5676: 97.01%\\n\",\n      \"#5677: 97.01%\\n\",\n      \"#5678: 97.01%\\n\",\n      \"#5679: 97.01%\\n\",\n      \"#5680: 97.01%\\n\",\n      \"#5681: 97.01%\\n\",\n      \"#5682: 97.01%\\n\",\n      \"#5683: 97.01%\\n\",\n      \"#5684: 97.01%\\n\",\n      \"#5685: 97.01%\\n\",\n      \"#5686: 97.01%\\n\",\n      \"#5687: 97.01%\\n\",\n      \"#5688: 97.01%\\n\",\n      \"#5689: 97.01%\\n\",\n      \"#5690: 97.01%\\n\",\n      \"#5691: 97.01%\\n\",\n      \"#5692: 97.01%\\n\",\n      \"#5693: 97.01%\\n\",\n      \"#5694: 97.01%\\n\",\n      \"#5695: 97.02%\\n\",\n      \"#5696: 97.02%\\n\",\n      \"#5697: 97.02%\\n\",\n      \"#5698: 97.02%\\n\",\n      \"#5699: 97.02%\\n\",\n      \"#5700: 97.02%\\n\",\n      \"#5701: 97.02%\\n\",\n      \"#5702: 97.02%\\n\",\n      \"#5703: 97.02%\\n\",\n      \"#5704: 97.02%\\n\",\n      \"#5705: 97.02%\\n\",\n      \"#5706: 97.02%\\n\",\n      \"#5707: 97.02%\\n\",\n      \"#5708: 97.02%\\n\",\n      \"#5709: 97.02%\\n\",\n      \"#5710: 97.02%\\n\",\n      \"#5711: 97.02%\\n\",\n      \"#5712: 97.02%\\n\",\n      \"#5713: 97.02%\\n\",\n      \"#5714: 97.03%\\n\",\n      \"#5715: 97.03%\\n\",\n      \"#5716: 97.03%\\n\",\n      \"#5717: 97.03%\\n\",\n      \"#5718: 97.03%\\n\",\n      \"#5719: 97.03%\\n\",\n      \"#5720: 97.03%\\n\",\n      \"#5721: 97.03%\\n\",\n      \"#5722: 97.03%\\n\",\n      \"#5723: 97.03%\\n\",\n      \"#5724: 97.03%\\n\",\n      \"#5725: 97.03%\\n\",\n      \"#5726: 97.03%\\n\",\n      \"#5727: 97.03%\\n\",\n      \"#5728: 97.03%\\n\",\n      \"#5729: 97.03%\\n\",\n      \"#5730: 97.03%\\n\",\n      \"#5731: 97.03%\\n\",\n      \"#5732: 97.03%\\n\",\n      \"#5733: 97.04%\\n\",\n      \"#5734: 97.02%\\n\",\n      \"#5735: 97.02%\\n\",\n      \"#5736: 97.02%\\n\",\n      \"#5737: 97.02%\\n\",\n      \"#5738: 97.02%\\n\",\n      \"#5739: 97.02%\\n\",\n      \"#5740: 97.02%\\n\",\n      \"#5741: 97.02%\\n\",\n      \"#5742: 97.02%\\n\",\n      \"#5743: 97.02%\\n\",\n      \"#5744: 97.02%\\n\",\n      \"#5745: 97.02%\\n\",\n      \"#5746: 97.02%\\n\",\n      \"#5747: 97.03%\\n\",\n      \"#5748: 97.03%\\n\",\n      \"#5749: 97.03%\\n\",\n      \"#5750: 97.03%\\n\",\n      \"#5751: 97.03%\\n\",\n      \"#5752: 97.03%\\n\",\n      \"#5753: 97.03%\\n\",\n      \"#5754: 97.03%\\n\",\n      \"#5755: 97.03%\\n\",\n      \"#5756: 97.03%\\n\",\n      \"#5757: 97.03%\\n\",\n      \"#5758: 97.03%\\n\",\n      \"#5759: 97.03%\\n\",\n      \"#5760: 97.03%\\n\",\n      \"#5761: 97.03%\\n\",\n      \"#5762: 97.03%\\n\",\n      \"#5763: 97.03%\\n\",\n      \"#5764: 97.03%\\n\",\n      \"#5765: 97.03%\\n\",\n      \"#5766: 97.03%\\n\",\n      \"#5767: 97.04%\\n\",\n      \"#5768: 97.04%\\n\",\n      \"#5769: 97.04%\\n\",\n      \"#5770: 97.04%\\n\",\n      \"#5771: 97.04%\\n\",\n      \"#5772: 97.04%\\n\",\n      \"#5773: 97.04%\\n\",\n      \"#5774: 97.04%\\n\",\n      \"#5775: 97.04%\\n\",\n      \"#5776: 97.04%\\n\",\n      \"#5777: 97.04%\\n\",\n      \"#5778: 97.04%\\n\",\n      \"#5779: 97.04%\\n\",\n      \"#5780: 97.04%\\n\",\n      \"#5781: 97.04%\\n\",\n      \"#5782: 97.04%\\n\",\n      \"#5783: 97.04%\\n\",\n      \"#5784: 97.04%\\n\",\n      \"#5785: 97.04%\\n\",\n      \"#5786: 97.05%\\n\",\n      \"#5787: 97.05%\\n\",\n      \"#5788: 97.05%\\n\",\n      \"#5789: 97.05%\\n\",\n      \"#5790: 97.05%\\n\",\n      \"#5791: 97.05%\\n\",\n      \"#5792: 97.05%\\n\",\n      \"#5793: 97.05%\\n\",\n      \"#5794: 97.05%\\n\",\n      \"#5795: 97.05%\\n\",\n      \"#5796: 97.05%\\n\",\n      \"#5797: 97.05%\\n\",\n      \"#5798: 97.05%\\n\",\n      \"#5799: 97.05%\\n\",\n      \"#5800: 97.05%\\n\",\n      \"#5801: 97.05%\\n\",\n      \"#5802: 97.05%\\n\",\n      \"#5803: 97.05%\\n\",\n      \"#5804: 97.05%\\n\",\n      \"#5805: 97.05%\\n\",\n      \"#5806: 97.06%\\n\",\n      \"#5807: 97.06%\\n\",\n      \"#5808: 97.06%\\n\",\n      \"#5809: 97.06%\\n\",\n      \"#5810: 97.06%\\n\",\n      \"#5811: 97.06%\\n\",\n      \"#5812: 97.06%\\n\",\n      \"#5813: 97.06%\\n\",\n      \"#5814: 97.06%\\n\",\n      \"#5815: 97.06%\\n\",\n      \"#5816: 97.06%\\n\",\n      \"#5817: 97.06%\\n\",\n      \"#5818: 97.06%\\n\",\n      \"#5819: 97.06%\\n\",\n      \"#5820: 97.06%\\n\",\n      \"#5821: 97.06%\\n\",\n      \"#5822: 97.06%\\n\",\n      \"#5823: 97.06%\\n\",\n      \"#5824: 97.06%\\n\",\n      \"#5825: 97.06%\\n\",\n      \"#5826: 97.07%\\n\",\n      \"#5827: 97.07%\\n\",\n      \"#5828: 97.07%\\n\",\n      \"#5829: 97.07%\\n\",\n      \"#5830: 97.07%\\n\",\n      \"#5831: 97.07%\\n\",\n      \"#5832: 97.07%\\n\",\n      \"#5833: 97.07%\\n\",\n      \"#5834: 97.07%\\n\",\n      \"#5835: 97.07%\\n\",\n      \"#5836: 97.07%\\n\",\n      \"#5837: 97.07%\\n\",\n      \"#5838: 97.07%\\n\",\n      \"#5839: 97.07%\\n\",\n      \"#5840: 97.07%\\n\",\n      \"#5841: 97.06%\\n\",\n      \"#5842: 97.04%\\n\",\n      \"#5843: 97.04%\\n\",\n      \"#5844: 97.04%\\n\",\n      \"#5845: 97.04%\\n\",\n      \"#5846: 97.04%\\n\",\n      \"#5847: 97.04%\\n\",\n      \"#5848: 97.04%\\n\",\n      \"#5849: 97.04%\\n\",\n      \"#5850: 97.04%\\n\",\n      \"#5851: 97.04%\\n\",\n      \"#5852: 97.04%\\n\",\n      \"#5853: 97.04%\\n\",\n      \"#5854: 97.05%\\n\",\n      \"#5855: 97.05%\\n\",\n      \"#5856: 97.05%\\n\",\n      \"#5857: 97.05%\\n\",\n      \"#5858: 97.05%\\n\",\n      \"#5859: 97.05%\\n\",\n      \"#5860: 97.05%\\n\",\n      \"#5861: 97.05%\\n\",\n      \"#5862: 97.05%\\n\",\n      \"#5863: 97.05%\\n\",\n      \"#5864: 97.05%\\n\",\n      \"#5865: 97.05%\\n\",\n      \"#5866: 97.05%\\n\",\n      \"#5867: 97.05%\\n\",\n      \"#5868: 97.05%\\n\",\n      \"#5869: 97.05%\\n\",\n      \"#5870: 97.05%\\n\",\n      \"#5871: 97.05%\\n\",\n      \"#5872: 97.05%\\n\",\n      \"#5873: 97.05%\\n\",\n      \"#5874: 97.06%\\n\",\n      \"#5875: 97.06%\\n\",\n      \"#5876: 97.06%\\n\",\n      \"#5877: 97.06%\\n\",\n      \"#5878: 97.06%\\n\",\n      \"#5879: 97.06%\\n\",\n      \"#5880: 97.06%\\n\",\n      \"#5881: 97.06%\\n\",\n      \"#5882: 97.06%\\n\",\n      \"#5883: 97.06%\\n\",\n      \"#5884: 97.06%\\n\",\n      \"#5885: 97.06%\\n\",\n      \"#5886: 97.06%\\n\",\n      \"#5887: 97.04%\\n\",\n      \"#5888: 97.05%\\n\",\n      \"#5889: 97.05%\\n\",\n      \"#5890: 97.05%\\n\",\n      \"#5891: 97.05%\\n\",\n      \"#5892: 97.05%\\n\",\n      \"#5893: 97.05%\\n\",\n      \"#5894: 97.05%\\n\",\n      \"#5895: 97.05%\\n\",\n      \"#5896: 97.05%\\n\",\n      \"#5897: 97.05%\\n\",\n      \"#5898: 97.05%\\n\",\n      \"#5899: 97.05%\\n\",\n      \"#5900: 97.05%\\n\",\n      \"#5901: 97.05%\\n\",\n      \"#5902: 97.05%\\n\",\n      \"#5903: 97.05%\\n\",\n      \"#5904: 97.05%\\n\",\n      \"#5905: 97.05%\\n\",\n      \"#5906: 97.05%\\n\",\n      \"#5907: 97.05%\\n\",\n      \"#5908: 97.06%\\n\",\n      \"#5909: 97.06%\\n\",\n      \"#5910: 97.06%\\n\",\n      \"#5911: 97.06%\\n\",\n      \"#5912: 97.06%\\n\",\n      \"#5913: 97.06%\\n\",\n      \"#5914: 97.06%\\n\",\n      \"#5915: 97.06%\\n\",\n      \"#5916: 97.06%\\n\",\n      \"#5917: 97.06%\\n\",\n      \"#5918: 97.06%\\n\",\n      \"#5919: 97.06%\\n\",\n      \"#5920: 97.06%\\n\",\n      \"#5921: 97.06%\\n\",\n      \"#5922: 97.06%\\n\",\n      \"#5923: 97.06%\\n\",\n      \"#5924: 97.06%\\n\",\n      \"#5925: 97.06%\\n\",\n      \"#5926: 97.06%\\n\",\n      \"#5927: 97.06%\\n\",\n      \"#5928: 97.07%\\n\",\n      \"#5929: 97.07%\\n\",\n      \"#5930: 97.07%\\n\",\n      \"#5931: 97.07%\\n\",\n      \"#5932: 97.07%\\n\",\n      \"#5933: 97.07%\\n\",\n      \"#5934: 97.07%\\n\",\n      \"#5935: 97.07%\\n\",\n      \"#5936: 97.07%\\n\",\n      \"#5937: 97.07%\\n\",\n      \"#5938: 97.07%\\n\",\n      \"#5939: 97.07%\\n\",\n      \"#5940: 97.07%\\n\",\n      \"#5941: 97.07%\\n\",\n      \"#5942: 97.07%\\n\",\n      \"#5943: 97.07%\\n\",\n      \"#5944: 97.07%\\n\",\n      \"#5945: 97.07%\\n\",\n      \"#5946: 97.07%\\n\",\n      \"#5947: 97.07%\\n\",\n      \"#5948: 97.08%\\n\",\n      \"#5949: 97.08%\\n\",\n      \"#5950: 97.08%\\n\",\n      \"#5951: 97.08%\\n\",\n      \"#5952: 97.08%\\n\",\n      \"#5953: 97.08%\\n\",\n      \"#5954: 97.08%\\n\",\n      \"#5955: 97.06%\\n\",\n      \"#5956: 97.06%\\n\",\n      \"#5957: 97.06%\\n\",\n      \"#5958: 97.06%\\n\",\n      \"#5959: 97.06%\\n\",\n      \"#5960: 97.06%\\n\",\n      \"#5961: 97.06%\\n\",\n      \"#5962: 97.07%\\n\",\n      \"#5963: 97.07%\\n\",\n      \"#5964: 97.07%\\n\",\n      \"#5965: 97.07%\\n\",\n      \"#5966: 97.07%\\n\",\n      \"#5967: 97.07%\\n\",\n      \"#5968: 97.07%\\n\",\n      \"#5969: 97.07%\\n\",\n      \"#5970: 97.07%\\n\",\n      \"#5971: 97.07%\\n\",\n      \"#5972: 97.07%\\n\",\n      \"#5973: 97.05%\\n\",\n      \"#5974: 97.05%\\n\",\n      \"#5975: 97.05%\\n\",\n      \"#5976: 97.06%\\n\",\n      \"#5977: 97.06%\\n\",\n      \"#5978: 97.06%\\n\",\n      \"#5979: 97.06%\\n\",\n      \"#5980: 97.06%\\n\",\n      \"#5981: 97.06%\\n\",\n      \"#5982: 97.06%\\n\",\n      \"#5983: 97.06%\\n\",\n      \"#5984: 97.06%\\n\",\n      \"#5985: 97.06%\\n\",\n      \"#5986: 97.06%\\n\",\n      \"#5987: 97.06%\\n\",\n      \"#5988: 97.06%\\n\",\n      \"#5989: 97.06%\\n\",\n      \"#5990: 97.06%\\n\",\n      \"#5991: 97.06%\\n\",\n      \"#5992: 97.06%\\n\",\n      \"#5993: 97.06%\\n\",\n      \"#5994: 97.06%\\n\",\n      \"#5995: 97.06%\\n\",\n      \"#5996: 97.07%\\n\",\n      \"#5997: 97.05%\\n\",\n      \"#5998: 97.05%\\n\",\n      \"#5999: 97.05%\\n\",\n      \"#6000: 97.05%\\n\",\n      \"#6001: 97.05%\\n\",\n      \"#6002: 97.05%\\n\",\n      \"#6003: 97.05%\\n\",\n      \"#6004: 97.05%\\n\",\n      \"#6005: 97.05%\\n\",\n      \"#6006: 97.05%\\n\",\n      \"#6007: 97.05%\\n\",\n      \"#6008: 97.05%\\n\",\n      \"#6009: 97.05%\\n\",\n      \"#6010: 97.06%\\n\",\n      \"#6011: 97.06%\\n\",\n      \"#6012: 97.06%\\n\",\n      \"#6013: 97.06%\\n\",\n      \"#6014: 97.06%\\n\",\n      \"#6015: 97.06%\\n\",\n      \"#6016: 97.06%\\n\",\n      \"#6017: 97.06%\\n\",\n      \"#6018: 97.06%\\n\",\n      \"#6019: 97.06%\\n\",\n      \"#6020: 97.06%\\n\",\n      \"#6021: 97.06%\\n\",\n      \"#6022: 97.06%\\n\",\n      \"#6023: 97.05%\\n\",\n      \"#6024: 97.05%\\n\",\n      \"#6025: 97.05%\\n\",\n      \"#6026: 97.05%\\n\",\n      \"#6027: 97.05%\\n\",\n      \"#6028: 97.05%\\n\",\n      \"#6029: 97.05%\\n\",\n      \"#6030: 97.05%\\n\",\n      \"#6031: 97.05%\\n\",\n      \"#6032: 97.05%\\n\",\n      \"#6033: 97.05%\\n\",\n      \"#6034: 97.05%\\n\",\n      \"#6035: 97.05%\\n\",\n      \"#6036: 97.05%\\n\",\n      \"#6037: 97.05%\\n\",\n      \"#6038: 97.05%\\n\",\n      \"#6039: 97.05%\\n\",\n      \"#6040: 97.05%\\n\",\n      \"#6041: 97.05%\\n\",\n      \"#6042: 97.05%\\n\",\n      \"#6043: 97.05%\\n\",\n      \"#6044: 97.06%\\n\",\n      \"#6045: 97.06%\\n\",\n      \"#6046: 97.06%\\n\",\n      \"#6047: 97.06%\\n\",\n      \"#6048: 97.06%\\n\",\n      \"#6049: 97.06%\\n\",\n      \"#6050: 97.06%\\n\",\n      \"#6051: 97.06%\\n\",\n      \"#6052: 97.06%\\n\",\n      \"#6053: 97.06%\\n\",\n      \"#6054: 97.06%\\n\",\n      \"#6055: 97.06%\\n\",\n      \"#6056: 97.06%\\n\",\n      \"#6057: 97.06%\\n\",\n      \"#6058: 97.06%\\n\",\n      \"#6059: 97.05%\\n\",\n      \"#6060: 97.05%\\n\",\n      \"#6061: 97.05%\\n\",\n      \"#6062: 97.05%\\n\",\n      \"#6063: 97.05%\\n\",\n      \"#6064: 97.05%\\n\",\n      \"#6065: 97.03%\\n\",\n      \"#6066: 97.03%\\n\",\n      \"#6067: 97.03%\\n\",\n      \"#6068: 97.03%\\n\",\n      \"#6069: 97.03%\\n\",\n      \"#6070: 97.04%\\n\",\n      \"#6071: 97.04%\\n\",\n      \"#6072: 97.04%\\n\",\n      \"#6073: 97.04%\\n\",\n      \"#6074: 97.04%\\n\",\n      \"#6075: 97.04%\\n\",\n      \"#6076: 97.04%\\n\",\n      \"#6077: 97.04%\\n\",\n      \"#6078: 97.04%\\n\",\n      \"#6079: 97.04%\\n\",\n      \"#6080: 97.04%\\n\",\n      \"#6081: 97.04%\\n\",\n      \"#6082: 97.04%\\n\",\n      \"#6083: 97.04%\\n\",\n      \"#6084: 97.04%\\n\",\n      \"#6085: 97.03%\\n\",\n      \"#6086: 97.03%\\n\",\n      \"#6087: 97.03%\\n\",\n      \"#6088: 97.03%\\n\",\n      \"#6089: 97.03%\\n\",\n      \"#6090: 97.03%\\n\",\n      \"#6091: 97.01%\\n\",\n      \"#6092: 97.01%\\n\",\n      \"#6093: 97.01%\\n\",\n      \"#6094: 97.01%\\n\",\n      \"#6095: 97.01%\\n\",\n      \"#6096: 97.01%\\n\",\n      \"#6097: 97.02%\\n\",\n      \"#6098: 97.02%\\n\",\n      \"#6099: 97.02%\\n\",\n      \"#6100: 97.02%\\n\",\n      \"#6101: 97.02%\\n\",\n      \"#6102: 97.02%\\n\",\n      \"#6103: 97.02%\\n\",\n      \"#6104: 97.02%\\n\",\n      \"#6105: 97.02%\\n\",\n      \"#6106: 97.02%\\n\",\n      \"#6107: 97.02%\\n\",\n      \"#6108: 97.02%\\n\",\n      \"#6109: 97.02%\\n\",\n      \"#6110: 97.02%\\n\",\n      \"#6111: 97.02%\\n\",\n      \"#6112: 97.02%\\n\",\n      \"#6113: 97.02%\\n\",\n      \"#6114: 97.02%\\n\",\n      \"#6115: 97.02%\\n\",\n      \"#6116: 97.02%\\n\",\n      \"#6117: 97.03%\\n\",\n      \"#6118: 97.03%\\n\",\n      \"#6119: 97.03%\\n\",\n      \"#6120: 97.03%\\n\",\n      \"#6121: 97.03%\\n\",\n      \"#6122: 97.03%\\n\",\n      \"#6123: 97.03%\\n\",\n      \"#6124: 97.03%\\n\",\n      \"#6125: 97.03%\\n\",\n      \"#6126: 97.03%\\n\",\n      \"#6127: 97.03%\\n\",\n      \"#6128: 97.03%\\n\",\n      \"#6129: 97.03%\\n\",\n      \"#6130: 97.03%\\n\",\n      \"#6131: 97.03%\\n\",\n      \"#6132: 97.03%\\n\",\n      \"#6133: 97.03%\\n\",\n      \"#6134: 97.03%\\n\",\n      \"#6135: 97.03%\\n\",\n      \"#6136: 97.03%\\n\",\n      \"#6137: 97.03%\\n\",\n      \"#6138: 97.04%\\n\",\n      \"#6139: 97.04%\\n\",\n      \"#6140: 97.04%\\n\",\n      \"#6141: 97.04%\\n\",\n      \"#6142: 97.04%\\n\",\n      \"#6143: 97.04%\\n\",\n      \"#6144: 97.04%\\n\",\n      \"#6145: 97.04%\\n\",\n      \"#6146: 97.04%\\n\",\n      \"#6147: 97.04%\\n\",\n      \"#6148: 97.04%\\n\",\n      \"#6149: 97.04%\\n\",\n      \"#6150: 97.04%\\n\",\n      \"#6151: 97.04%\\n\",\n      \"#6152: 97.04%\\n\",\n      \"#6153: 97.04%\\n\",\n      \"#6154: 97.04%\\n\",\n      \"#6155: 97.04%\\n\",\n      \"#6156: 97.04%\\n\",\n      \"#6157: 97.04%\\n\",\n      \"#6158: 97.04%\\n\",\n      \"#6159: 97.05%\\n\",\n      \"#6160: 97.05%\\n\",\n      \"#6161: 97.05%\\n\",\n      \"#6162: 97.05%\\n\",\n      \"#6163: 97.05%\\n\",\n      \"#6164: 97.05%\\n\",\n      \"#6165: 97.05%\\n\",\n      \"#6166: 97.05%\\n\",\n      \"#6167: 97.05%\\n\",\n      \"#6168: 97.05%\\n\",\n      \"#6169: 97.05%\\n\",\n      \"#6170: 97.05%\\n\",\n      \"#6171: 97.05%\\n\",\n      \"#6172: 97.04%\\n\",\n      \"#6173: 97.04%\\n\",\n      \"#6174: 97.04%\\n\",\n      \"#6175: 97.04%\\n\",\n      \"#6176: 97.04%\\n\",\n      \"#6177: 97.04%\\n\",\n      \"#6178: 97.04%\\n\",\n      \"#6179: 97.04%\\n\",\n      \"#6180: 97.04%\\n\",\n      \"#6181: 97.04%\\n\",\n      \"#6182: 97.04%\\n\",\n      \"#6183: 97.04%\\n\",\n      \"#6184: 97.04%\\n\",\n      \"#6185: 97.04%\\n\",\n      \"#6186: 97.04%\\n\",\n      \"#6187: 97.04%\\n\",\n      \"#6188: 97.04%\\n\",\n      \"#6189: 97.04%\\n\",\n      \"#6190: 97.04%\\n\",\n      \"#6191: 97.04%\\n\",\n      \"#6192: 97.05%\\n\",\n      \"#6193: 97.05%\\n\",\n      \"#6194: 97.05%\\n\",\n      \"#6195: 97.05%\\n\",\n      \"#6196: 97.05%\\n\",\n      \"#6197: 97.05%\\n\",\n      \"#6198: 97.05%\\n\",\n      \"#6199: 97.05%\\n\",\n      \"#6200: 97.05%\\n\",\n      \"#6201: 97.05%\\n\",\n      \"#6202: 97.05%\\n\",\n      \"#6203: 97.05%\\n\",\n      \"#6204: 97.05%\\n\",\n      \"#6205: 97.05%\\n\",\n      \"#6206: 97.05%\\n\",\n      \"#6207: 97.05%\\n\",\n      \"#6208: 97.05%\\n\",\n      \"#6209: 97.05%\\n\",\n      \"#6210: 97.05%\\n\",\n      \"#6211: 97.05%\\n\",\n      \"#6212: 97.05%\\n\",\n      \"#6213: 97.06%\\n\",\n      \"#6214: 97.06%\\n\",\n      \"#6215: 97.06%\\n\",\n      \"#6216: 97.06%\\n\",\n      \"#6217: 97.06%\\n\",\n      \"#6218: 97.06%\\n\",\n      \"#6219: 97.06%\\n\",\n      \"#6220: 97.06%\\n\",\n      \"#6221: 97.06%\\n\",\n      \"#6222: 97.06%\\n\",\n      \"#6223: 97.06%\\n\",\n      \"#6224: 97.06%\\n\",\n      \"#6225: 97.06%\\n\",\n      \"#6226: 97.06%\\n\",\n      \"#6227: 97.06%\\n\",\n      \"#6228: 97.06%\\n\",\n      \"#6229: 97.06%\\n\",\n      \"#6230: 97.06%\\n\",\n      \"#6231: 97.06%\\n\",\n      \"#6232: 97.06%\\n\",\n      \"#6233: 97.06%\\n\",\n      \"#6234: 97.06%\\n\",\n      \"#6235: 97.07%\\n\",\n      \"#6236: 97.07%\\n\",\n      \"#6237: 97.07%\\n\",\n      \"#6238: 97.07%\\n\",\n      \"#6239: 97.07%\\n\",\n      \"#6240: 97.07%\\n\",\n      \"#6241: 97.07%\\n\",\n      \"#6242: 97.07%\\n\",\n      \"#6243: 97.07%\\n\",\n      \"#6244: 97.07%\\n\",\n      \"#6245: 97.07%\\n\",\n      \"#6246: 97.07%\\n\",\n      \"#6247: 97.07%\\n\",\n      \"#6248: 97.07%\\n\",\n      \"#6249: 97.07%\\n\",\n      \"#6250: 97.07%\\n\",\n      \"#6251: 97.07%\\n\",\n      \"#6252: 97.07%\\n\",\n      \"#6253: 97.07%\\n\",\n      \"#6254: 97.07%\\n\",\n      \"#6255: 97.07%\\n\",\n      \"#6256: 97.08%\\n\",\n      \"#6257: 97.08%\\n\",\n      \"#6258: 97.08%\\n\",\n      \"#6259: 97.08%\\n\",\n      \"#6260: 97.08%\\n\",\n      \"#6261: 97.08%\\n\",\n      \"#6262: 97.08%\\n\",\n      \"#6263: 97.08%\\n\",\n      \"#6264: 97.08%\\n\",\n      \"#6265: 97.08%\\n\",\n      \"#6266: 97.08%\\n\",\n      \"#6267: 97.08%\\n\",\n      \"#6268: 97.08%\\n\",\n      \"#6269: 97.08%\\n\",\n      \"#6270: 97.08%\\n\",\n      \"#6271: 97.08%\\n\",\n      \"#6272: 97.08%\\n\",\n      \"#6273: 97.08%\\n\",\n      \"#6274: 97.08%\\n\",\n      \"#6275: 97.08%\\n\",\n      \"#6276: 97.08%\\n\",\n      \"#6277: 97.09%\\n\",\n      \"#6278: 97.09%\\n\",\n      \"#6279: 97.09%\\n\",\n      \"#6280: 97.09%\\n\",\n      \"#6281: 97.09%\\n\",\n      \"#6282: 97.09%\\n\",\n      \"#6283: 97.09%\\n\",\n      \"#6284: 97.09%\\n\",\n      \"#6285: 97.09%\\n\",\n      \"#6286: 97.09%\\n\",\n      \"#6287: 97.09%\\n\",\n      \"#6288: 97.09%\\n\",\n      \"#6289: 97.09%\\n\",\n      \"#6290: 97.09%\\n\",\n      \"#6291: 97.09%\\n\",\n      \"#6292: 97.09%\\n\",\n      \"#6293: 97.09%\\n\",\n      \"#6294: 97.09%\\n\",\n      \"#6295: 97.09%\\n\",\n      \"#6296: 97.09%\\n\",\n      \"#6297: 97.09%\\n\",\n      \"#6298: 97.09%\\n\",\n      \"#6299: 97.10%\\n\",\n      \"#6300: 97.10%\\n\",\n      \"#6301: 97.10%\\n\",\n      \"#6302: 97.10%\\n\",\n      \"#6303: 97.10%\\n\",\n      \"#6304: 97.10%\\n\",\n      \"#6305: 97.10%\\n\",\n      \"#6306: 97.10%\\n\",\n      \"#6307: 97.10%\\n\",\n      \"#6308: 97.10%\\n\",\n      \"#6309: 97.10%\\n\",\n      \"#6310: 97.10%\\n\",\n      \"#6311: 97.10%\\n\",\n      \"#6312: 97.10%\\n\",\n      \"#6313: 97.10%\\n\",\n      \"#6314: 97.10%\\n\",\n      \"#6315: 97.10%\\n\",\n      \"#6316: 97.10%\\n\",\n      \"#6317: 97.10%\\n\",\n      \"#6318: 97.10%\\n\",\n      \"#6319: 97.10%\\n\",\n      \"#6320: 97.10%\\n\",\n      \"#6321: 97.11%\\n\",\n      \"#6322: 97.11%\\n\",\n      \"#6323: 97.11%\\n\",\n      \"#6324: 97.11%\\n\",\n      \"#6325: 97.11%\\n\",\n      \"#6326: 97.11%\\n\",\n      \"#6327: 97.11%\\n\",\n      \"#6328: 97.11%\\n\",\n      \"#6329: 97.11%\\n\",\n      \"#6330: 97.11%\\n\",\n      \"#6331: 97.11%\\n\",\n      \"#6332: 97.11%\\n\",\n      \"#6333: 97.11%\\n\",\n      \"#6334: 97.11%\\n\",\n      \"#6335: 97.11%\\n\",\n      \"#6336: 97.11%\\n\",\n      \"#6337: 97.11%\\n\",\n      \"#6338: 97.11%\\n\",\n      \"#6339: 97.11%\\n\",\n      \"#6340: 97.11%\\n\",\n      \"#6341: 97.11%\\n\",\n      \"#6342: 97.11%\\n\",\n      \"#6343: 97.12%\\n\",\n      \"#6344: 97.12%\\n\",\n      \"#6345: 97.12%\\n\",\n      \"#6346: 97.12%\\n\",\n      \"#6347: 97.12%\\n\",\n      \"#6348: 97.12%\\n\",\n      \"#6349: 97.12%\\n\",\n      \"#6350: 97.12%\\n\",\n      \"#6351: 97.12%\\n\",\n      \"#6352: 97.12%\\n\",\n      \"#6353: 97.12%\\n\",\n      \"#6354: 97.12%\\n\",\n      \"#6355: 97.12%\\n\",\n      \"#6356: 97.12%\\n\",\n      \"#6357: 97.12%\\n\",\n      \"#6358: 97.12%\\n\",\n      \"#6359: 97.12%\\n\",\n      \"#6360: 97.12%\\n\",\n      \"#6361: 97.12%\\n\",\n      \"#6362: 97.12%\\n\",\n      \"#6363: 97.12%\\n\",\n      \"#6364: 97.12%\\n\",\n      \"#6365: 97.13%\\n\",\n      \"#6366: 97.13%\\n\",\n      \"#6367: 97.13%\\n\",\n      \"#6368: 97.13%\\n\",\n      \"#6369: 97.13%\\n\",\n      \"#6370: 97.13%\\n\",\n      \"#6371: 97.13%\\n\",\n      \"#6372: 97.13%\\n\",\n      \"#6373: 97.13%\\n\",\n      \"#6374: 97.13%\\n\",\n      \"#6375: 97.13%\\n\",\n      \"#6376: 97.13%\\n\",\n      \"#6377: 97.13%\\n\",\n      \"#6378: 97.13%\\n\",\n      \"#6379: 97.13%\\n\",\n      \"#6380: 97.13%\\n\",\n      \"#6381: 97.13%\\n\",\n      \"#6382: 97.13%\\n\",\n      \"#6383: 97.13%\\n\",\n      \"#6384: 97.13%\\n\",\n      \"#6385: 97.13%\\n\",\n      \"#6386: 97.13%\\n\",\n      \"#6387: 97.14%\\n\",\n      \"#6388: 97.14%\\n\",\n      \"#6389: 97.14%\\n\",\n      \"#6390: 97.14%\\n\",\n      \"#6391: 97.14%\\n\",\n      \"#6392: 97.14%\\n\",\n      \"#6393: 97.14%\\n\",\n      \"#6394: 97.14%\\n\",\n      \"#6395: 97.14%\\n\",\n      \"#6396: 97.14%\\n\",\n      \"#6397: 97.14%\\n\",\n      \"#6398: 97.14%\\n\",\n      \"#6399: 97.14%\\n\",\n      \"#6400: 97.14%\\n\",\n      \"#6401: 97.14%\\n\",\n      \"#6402: 97.14%\\n\",\n      \"#6403: 97.14%\\n\",\n      \"#6404: 97.14%\\n\",\n      \"#6405: 97.14%\\n\",\n      \"#6406: 97.14%\\n\",\n      \"#6407: 97.14%\\n\",\n      \"#6408: 97.14%\\n\",\n      \"#6409: 97.15%\\n\",\n      \"#6410: 97.15%\\n\",\n      \"#6411: 97.15%\\n\",\n      \"#6412: 97.15%\\n\",\n      \"#6413: 97.15%\\n\",\n      \"#6414: 97.15%\\n\",\n      \"#6415: 97.15%\\n\",\n      \"#6416: 97.15%\\n\",\n      \"#6417: 97.15%\\n\",\n      \"#6418: 97.15%\\n\",\n      \"#6419: 97.15%\\n\",\n      \"#6420: 97.15%\\n\",\n      \"#6421: 97.15%\\n\",\n      \"#6422: 97.15%\\n\",\n      \"#6423: 97.15%\\n\",\n      \"#6424: 97.15%\\n\",\n      \"#6425: 97.15%\\n\",\n      \"#6426: 97.15%\\n\",\n      \"#6427: 97.15%\\n\",\n      \"#6428: 97.15%\\n\",\n      \"#6429: 97.15%\\n\",\n      \"#6430: 97.15%\\n\",\n      \"#6431: 97.15%\\n\",\n      \"#6432: 97.16%\\n\",\n      \"#6433: 97.16%\\n\",\n      \"#6434: 97.16%\\n\",\n      \"#6435: 97.16%\\n\",\n      \"#6436: 97.16%\\n\",\n      \"#6437: 97.16%\\n\",\n      \"#6438: 97.16%\\n\",\n      \"#6439: 97.16%\\n\",\n      \"#6440: 97.16%\\n\",\n      \"#6441: 97.16%\\n\",\n      \"#6442: 97.16%\\n\",\n      \"#6443: 97.16%\\n\",\n      \"#6444: 97.16%\\n\",\n      \"#6445: 97.16%\\n\",\n      \"#6446: 97.16%\\n\",\n      \"#6447: 97.16%\\n\",\n      \"#6448: 97.16%\\n\",\n      \"#6449: 97.16%\\n\",\n      \"#6450: 97.16%\\n\",\n      \"#6451: 97.16%\\n\",\n      \"#6452: 97.16%\\n\",\n      \"#6453: 97.16%\\n\",\n      \"#6454: 97.16%\\n\",\n      \"#6455: 97.17%\\n\",\n      \"#6456: 97.17%\\n\",\n      \"#6457: 97.17%\\n\",\n      \"#6458: 97.17%\\n\",\n      \"#6459: 97.17%\\n\",\n      \"#6460: 97.17%\\n\",\n      \"#6461: 97.17%\\n\",\n      \"#6462: 97.17%\\n\",\n      \"#6463: 97.17%\\n\",\n      \"#6464: 97.17%\\n\",\n      \"#6465: 97.17%\\n\",\n      \"#6466: 97.17%\\n\",\n      \"#6467: 97.17%\\n\",\n      \"#6468: 97.17%\\n\",\n      \"#6469: 97.17%\\n\",\n      \"#6470: 97.17%\\n\",\n      \"#6471: 97.17%\\n\",\n      \"#6472: 97.17%\\n\",\n      \"#6473: 97.17%\\n\",\n      \"#6474: 97.17%\\n\",\n      \"#6475: 97.17%\\n\",\n      \"#6476: 97.17%\\n\",\n      \"#6477: 97.18%\\n\",\n      \"#6478: 97.18%\\n\",\n      \"#6479: 97.18%\\n\",\n      \"#6480: 97.18%\\n\",\n      \"#6481: 97.18%\\n\",\n      \"#6482: 97.18%\\n\",\n      \"#6483: 97.18%\\n\",\n      \"#6484: 97.18%\\n\",\n      \"#6485: 97.18%\\n\",\n      \"#6486: 97.18%\\n\",\n      \"#6487: 97.18%\\n\",\n      \"#6488: 97.18%\\n\",\n      \"#6489: 97.18%\\n\",\n      \"#6490: 97.18%\\n\",\n      \"#6491: 97.18%\\n\",\n      \"#6492: 97.18%\\n\",\n      \"#6493: 97.18%\\n\",\n      \"#6494: 97.18%\\n\",\n      \"#6495: 97.18%\\n\",\n      \"#6496: 97.18%\\n\",\n      \"#6497: 97.18%\\n\",\n      \"#6498: 97.18%\\n\",\n      \"#6499: 97.18%\\n\",\n      \"#6500: 97.19%\\n\",\n      \"#6501: 97.19%\\n\",\n      \"#6502: 97.19%\\n\",\n      \"#6503: 97.19%\\n\",\n      \"#6504: 97.19%\\n\",\n      \"#6505: 97.17%\\n\",\n      \"#6506: 97.17%\\n\",\n      \"#6507: 97.17%\\n\",\n      \"#6508: 97.17%\\n\",\n      \"#6509: 97.17%\\n\",\n      \"#6510: 97.17%\\n\",\n      \"#6511: 97.17%\\n\",\n      \"#6512: 97.17%\\n\",\n      \"#6513: 97.18%\\n\",\n      \"#6514: 97.18%\\n\",\n      \"#6515: 97.18%\\n\",\n      \"#6516: 97.18%\\n\",\n      \"#6517: 97.18%\\n\",\n      \"#6518: 97.18%\\n\",\n      \"#6519: 97.18%\\n\",\n      \"#6520: 97.18%\\n\",\n      \"#6521: 97.18%\\n\",\n      \"#6522: 97.18%\\n\",\n      \"#6523: 97.18%\\n\",\n      \"#6524: 97.18%\\n\",\n      \"#6525: 97.18%\\n\",\n      \"#6526: 97.18%\\n\",\n      \"#6527: 97.18%\\n\",\n      \"#6528: 97.18%\\n\",\n      \"#6529: 97.18%\\n\",\n      \"#6530: 97.18%\\n\",\n      \"#6531: 97.18%\\n\",\n      \"#6532: 97.18%\\n\",\n      \"#6533: 97.18%\\n\",\n      \"#6534: 97.18%\\n\",\n      \"#6535: 97.18%\\n\",\n      \"#6536: 97.19%\\n\",\n      \"#6537: 97.19%\\n\",\n      \"#6538: 97.19%\\n\",\n      \"#6539: 97.19%\\n\",\n      \"#6540: 97.19%\\n\",\n      \"#6541: 97.19%\\n\",\n      \"#6542: 97.19%\\n\",\n      \"#6543: 97.19%\\n\",\n      \"#6544: 97.19%\\n\",\n      \"#6545: 97.19%\\n\",\n      \"#6546: 97.19%\\n\",\n      \"#6547: 97.19%\\n\",\n      \"#6548: 97.19%\\n\",\n      \"#6549: 97.19%\\n\",\n      \"#6550: 97.19%\\n\",\n      \"#6551: 97.19%\\n\",\n      \"#6552: 97.19%\\n\",\n      \"#6553: 97.19%\\n\",\n      \"#6554: 97.19%\\n\",\n      \"#6555: 97.18%\\n\",\n      \"#6556: 97.18%\\n\",\n      \"#6557: 97.18%\\n\",\n      \"#6558: 97.18%\\n\",\n      \"#6559: 97.18%\\n\",\n      \"#6560: 97.18%\\n\",\n      \"#6561: 97.18%\\n\",\n      \"#6562: 97.18%\\n\",\n      \"#6563: 97.18%\\n\",\n      \"#6564: 97.18%\\n\",\n      \"#6565: 97.18%\\n\",\n      \"#6566: 97.18%\\n\",\n      \"#6567: 97.18%\\n\",\n      \"#6568: 97.18%\\n\",\n      \"#6569: 97.18%\\n\",\n      \"#6570: 97.18%\\n\",\n      \"#6571: 97.19%\\n\",\n      \"#6572: 97.17%\\n\",\n      \"#6573: 97.17%\\n\",\n      \"#6574: 97.17%\\n\",\n      \"#6575: 97.17%\\n\",\n      \"#6576: 97.17%\\n\",\n      \"#6577: 97.17%\\n\",\n      \"#6578: 97.16%\\n\",\n      \"#6579: 97.16%\\n\",\n      \"#6580: 97.16%\\n\",\n      \"#6581: 97.16%\\n\",\n      \"#6582: 97.16%\\n\",\n      \"#6583: 97.16%\\n\",\n      \"#6584: 97.16%\\n\",\n      \"#6585: 97.16%\\n\",\n      \"#6586: 97.16%\\n\",\n      \"#6587: 97.16%\\n\",\n      \"#6588: 97.16%\\n\",\n      \"#6589: 97.16%\\n\",\n      \"#6590: 97.16%\\n\",\n      \"#6591: 97.16%\\n\",\n      \"#6592: 97.16%\\n\",\n      \"#6593: 97.16%\\n\",\n      \"#6594: 97.16%\\n\",\n      \"#6595: 97.16%\\n\",\n      \"#6596: 97.17%\\n\",\n      \"#6597: 97.15%\\n\",\n      \"#6598: 97.15%\\n\",\n      \"#6599: 97.14%\\n\",\n      \"#6600: 97.14%\\n\",\n      \"#6601: 97.14%\\n\",\n      \"#6602: 97.14%\\n\",\n      \"#6603: 97.14%\\n\",\n      \"#6604: 97.14%\\n\",\n      \"#6605: 97.14%\\n\",\n      \"#6606: 97.14%\\n\",\n      \"#6607: 97.14%\\n\",\n      \"#6608: 97.14%\\n\",\n      \"#6609: 97.14%\\n\",\n      \"#6610: 97.14%\\n\",\n      \"#6611: 97.14%\\n\",\n      \"#6612: 97.14%\\n\",\n      \"#6613: 97.14%\\n\",\n      \"#6614: 97.14%\\n\",\n      \"#6615: 97.14%\\n\",\n      \"#6616: 97.14%\\n\",\n      \"#6617: 97.14%\\n\",\n      \"#6618: 97.14%\\n\",\n      \"#6619: 97.15%\\n\",\n      \"#6620: 97.15%\\n\",\n      \"#6621: 97.15%\\n\",\n      \"#6622: 97.15%\\n\",\n      \"#6623: 97.15%\\n\",\n      \"#6624: 97.15%\\n\",\n      \"#6625: 97.15%\\n\",\n      \"#6626: 97.15%\\n\",\n      \"#6627: 97.15%\\n\",\n      \"#6628: 97.15%\\n\",\n      \"#6629: 97.15%\\n\",\n      \"#6630: 97.15%\\n\",\n      \"#6631: 97.15%\\n\",\n      \"#6632: 97.15%\\n\",\n      \"#6633: 97.15%\\n\",\n      \"#6634: 97.15%\\n\",\n      \"#6635: 97.15%\\n\",\n      \"#6636: 97.15%\\n\",\n      \"#6637: 97.15%\\n\",\n      \"#6638: 97.15%\\n\",\n      \"#6639: 97.15%\\n\",\n      \"#6640: 97.15%\\n\",\n      \"#6641: 97.15%\\n\",\n      \"#6642: 97.15%\\n\",\n      \"#6643: 97.16%\\n\",\n      \"#6644: 97.16%\\n\",\n      \"#6645: 97.16%\\n\",\n      \"#6646: 97.16%\\n\",\n      \"#6647: 97.16%\\n\",\n      \"#6648: 97.16%\\n\",\n      \"#6649: 97.16%\\n\",\n      \"#6650: 97.16%\\n\",\n      \"#6651: 97.16%\\n\",\n      \"#6652: 97.16%\\n\",\n      \"#6653: 97.16%\\n\",\n      \"#6654: 97.16%\\n\",\n      \"#6655: 97.16%\\n\",\n      \"#6656: 97.16%\\n\",\n      \"#6657: 97.16%\\n\",\n      \"#6658: 97.16%\\n\",\n      \"#6659: 97.16%\\n\",\n      \"#6660: 97.16%\\n\",\n      \"#6661: 97.16%\\n\",\n      \"#6662: 97.16%\\n\",\n      \"#6663: 97.16%\\n\",\n      \"#6664: 97.16%\\n\",\n      \"#6665: 97.16%\\n\",\n      \"#6666: 97.17%\\n\",\n      \"#6667: 97.17%\\n\",\n      \"#6668: 97.17%\\n\",\n      \"#6669: 97.17%\\n\",\n      \"#6670: 97.17%\\n\",\n      \"#6671: 97.17%\\n\",\n      \"#6672: 97.17%\\n\",\n      \"#6673: 97.17%\\n\",\n      \"#6674: 97.17%\\n\",\n      \"#6675: 97.17%\\n\",\n      \"#6676: 97.17%\\n\",\n      \"#6677: 97.17%\\n\",\n      \"#6678: 97.17%\\n\",\n      \"#6679: 97.17%\\n\",\n      \"#6680: 97.17%\\n\",\n      \"#6681: 97.17%\\n\",\n      \"#6682: 97.17%\\n\",\n      \"#6683: 97.17%\\n\",\n      \"#6684: 97.17%\\n\",\n      \"#6685: 97.17%\\n\",\n      \"#6686: 97.17%\\n\",\n      \"#6687: 97.17%\\n\",\n      \"#6688: 97.17%\\n\",\n      \"#6689: 97.17%\\n\",\n      \"#6690: 97.18%\\n\",\n      \"#6691: 97.18%\\n\",\n      \"#6692: 97.18%\\n\",\n      \"#6693: 97.18%\\n\",\n      \"#6694: 97.18%\\n\",\n      \"#6695: 97.18%\\n\",\n      \"#6696: 97.18%\\n\",\n      \"#6697: 97.18%\\n\",\n      \"#6698: 97.18%\\n\",\n      \"#6699: 97.18%\\n\",\n      \"#6700: 97.18%\\n\",\n      \"#6701: 97.18%\\n\",\n      \"#6702: 97.18%\\n\",\n      \"#6703: 97.18%\\n\",\n      \"#6704: 97.18%\\n\",\n      \"#6705: 97.18%\\n\",\n      \"#6706: 97.18%\\n\",\n      \"#6707: 97.18%\\n\",\n      \"#6708: 97.18%\\n\",\n      \"#6709: 97.18%\\n\",\n      \"#6710: 97.18%\\n\",\n      \"#6711: 97.18%\\n\",\n      \"#6712: 97.18%\\n\",\n      \"#6713: 97.18%\\n\",\n      \"#6714: 97.19%\\n\",\n      \"#6715: 97.19%\\n\",\n      \"#6716: 97.19%\\n\",\n      \"#6717: 97.19%\\n\",\n      \"#6718: 97.19%\\n\",\n      \"#6719: 97.19%\\n\",\n      \"#6720: 97.19%\\n\",\n      \"#6721: 97.19%\\n\",\n      \"#6722: 97.19%\\n\",\n      \"#6723: 97.19%\\n\",\n      \"#6724: 97.19%\\n\",\n      \"#6725: 97.19%\\n\",\n      \"#6726: 97.19%\\n\",\n      \"#6727: 97.19%\\n\",\n      \"#6728: 97.19%\\n\",\n      \"#6729: 97.19%\\n\",\n      \"#6730: 97.19%\\n\",\n      \"#6731: 97.19%\\n\",\n      \"#6732: 97.19%\\n\",\n      \"#6733: 97.19%\\n\",\n      \"#6734: 97.19%\\n\",\n      \"#6735: 97.19%\\n\",\n      \"#6736: 97.19%\\n\",\n      \"#6737: 97.20%\\n\",\n      \"#6738: 97.20%\\n\",\n      \"#6739: 97.20%\\n\",\n      \"#6740: 97.18%\\n\",\n      \"#6741: 97.18%\\n\",\n      \"#6742: 97.18%\\n\",\n      \"#6743: 97.18%\\n\",\n      \"#6744: 97.18%\\n\",\n      \"#6745: 97.18%\\n\",\n      \"#6746: 97.18%\\n\",\n      \"#6747: 97.18%\\n\",\n      \"#6748: 97.18%\\n\",\n      \"#6749: 97.19%\\n\",\n      \"#6750: 97.19%\\n\",\n      \"#6751: 97.19%\\n\",\n      \"#6752: 97.19%\\n\",\n      \"#6753: 97.19%\\n\",\n      \"#6754: 97.19%\\n\",\n      \"#6755: 97.17%\\n\",\n      \"#6756: 97.16%\\n\",\n      \"#6757: 97.16%\\n\",\n      \"#6758: 97.16%\\n\",\n      \"#6759: 97.16%\\n\",\n      \"#6760: 97.16%\\n\",\n      \"#6761: 97.16%\\n\",\n      \"#6762: 97.16%\\n\",\n      \"#6763: 97.16%\\n\",\n      \"#6764: 97.16%\\n\",\n      \"#6765: 97.16%\\n\",\n      \"#6766: 97.16%\\n\",\n      \"#6767: 97.16%\\n\",\n      \"#6768: 97.16%\\n\",\n      \"#6769: 97.16%\\n\",\n      \"#6770: 97.16%\\n\",\n      \"#6771: 97.16%\\n\",\n      \"#6772: 97.17%\\n\",\n      \"#6773: 97.17%\\n\",\n      \"#6774: 97.17%\\n\",\n      \"#6775: 97.17%\\n\",\n      \"#6776: 97.17%\\n\",\n      \"#6777: 97.17%\\n\",\n      \"#6778: 97.17%\\n\",\n      \"#6779: 97.17%\\n\",\n      \"#6780: 97.17%\\n\",\n      \"#6781: 97.17%\\n\",\n      \"#6782: 97.17%\\n\",\n      \"#6783: 97.16%\\n\",\n      \"#6784: 97.16%\\n\",\n      \"#6785: 97.16%\\n\",\n      \"#6786: 97.16%\\n\",\n      \"#6787: 97.16%\\n\",\n      \"#6788: 97.16%\\n\",\n      \"#6789: 97.16%\\n\",\n      \"#6790: 97.16%\\n\",\n      \"#6791: 97.16%\\n\",\n      \"#6792: 97.16%\\n\",\n      \"#6793: 97.16%\\n\",\n      \"#6794: 97.16%\\n\",\n      \"#6795: 97.16%\\n\",\n      \"#6796: 97.16%\\n\",\n      \"#6797: 97.16%\\n\",\n      \"#6798: 97.16%\\n\",\n      \"#6799: 97.16%\\n\",\n      \"#6800: 97.16%\\n\",\n      \"#6801: 97.16%\\n\",\n      \"#6802: 97.16%\\n\",\n      \"#6803: 97.16%\\n\",\n      \"#6804: 97.16%\\n\",\n      \"#6805: 97.16%\\n\",\n      \"#6806: 97.16%\\n\",\n      \"#6807: 97.17%\\n\",\n      \"#6808: 97.17%\\n\",\n      \"#6809: 97.17%\\n\",\n      \"#6810: 97.17%\\n\",\n      \"#6811: 97.17%\\n\",\n      \"#6812: 97.17%\\n\",\n      \"#6813: 97.17%\\n\",\n      \"#6814: 97.17%\\n\",\n      \"#6815: 97.17%\\n\",\n      \"#6816: 97.17%\\n\",\n      \"#6817: 97.17%\\n\",\n      \"#6818: 97.17%\\n\",\n      \"#6819: 97.17%\\n\",\n      \"#6820: 97.17%\\n\",\n      \"#6821: 97.17%\\n\",\n      \"#6822: 97.17%\\n\",\n      \"#6823: 97.17%\\n\",\n      \"#6824: 97.17%\\n\",\n      \"#6825: 97.17%\\n\",\n      \"#6826: 97.17%\\n\",\n      \"#6827: 97.17%\\n\",\n      \"#6828: 97.17%\\n\",\n      \"#6829: 97.17%\\n\",\n      \"#6830: 97.17%\\n\",\n      \"#6831: 97.18%\\n\",\n      \"#6832: 97.18%\\n\",\n      \"#6833: 97.18%\\n\",\n      \"#6834: 97.18%\\n\",\n      \"#6835: 97.18%\\n\",\n      \"#6836: 97.18%\\n\",\n      \"#6837: 97.18%\\n\",\n      \"#6838: 97.18%\\n\",\n      \"#6839: 97.18%\\n\",\n      \"#6840: 97.18%\\n\",\n      \"#6841: 97.18%\\n\",\n      \"#6842: 97.18%\\n\",\n      \"#6843: 97.18%\\n\",\n      \"#6844: 97.18%\\n\",\n      \"#6845: 97.18%\\n\",\n      \"#6846: 97.18%\\n\",\n      \"#6847: 97.18%\\n\",\n      \"#6848: 97.18%\\n\",\n      \"#6849: 97.18%\\n\",\n      \"#6850: 97.18%\\n\",\n      \"#6851: 97.18%\\n\",\n      \"#6852: 97.18%\\n\",\n      \"#6853: 97.18%\\n\",\n      \"#6854: 97.18%\\n\",\n      \"#6855: 97.18%\\n\",\n      \"#6856: 97.19%\\n\",\n      \"#6857: 97.19%\\n\",\n      \"#6858: 97.19%\\n\",\n      \"#6859: 97.19%\\n\",\n      \"#6860: 97.19%\\n\",\n      \"#6861: 97.19%\\n\",\n      \"#6862: 97.19%\\n\",\n      \"#6863: 97.19%\\n\",\n      \"#6864: 97.19%\\n\",\n      \"#6865: 97.19%\\n\",\n      \"#6866: 97.19%\\n\",\n      \"#6867: 97.19%\\n\",\n      \"#6868: 97.19%\\n\",\n      \"#6869: 97.19%\\n\",\n      \"#6870: 97.19%\\n\",\n      \"#6871: 97.19%\\n\",\n      \"#6872: 97.19%\\n\",\n      \"#6873: 97.19%\\n\",\n      \"#6874: 97.19%\\n\",\n      \"#6875: 97.19%\\n\",\n      \"#6876: 97.19%\\n\",\n      \"#6877: 97.19%\\n\",\n      \"#6878: 97.19%\\n\",\n      \"#6879: 97.19%\\n\",\n      \"#6880: 97.20%\\n\",\n      \"#6881: 97.20%\\n\",\n      \"#6882: 97.20%\\n\",\n      \"#6883: 97.20%\\n\",\n      \"#6884: 97.20%\\n\",\n      \"#6885: 97.20%\\n\",\n      \"#6886: 97.20%\\n\",\n      \"#6887: 97.20%\\n\",\n      \"#6888: 97.20%\\n\",\n      \"#6889: 97.20%\\n\",\n      \"#6890: 97.20%\\n\",\n      \"#6891: 97.20%\\n\",\n      \"#6892: 97.20%\\n\",\n      \"#6893: 97.20%\\n\",\n      \"#6894: 97.20%\\n\",\n      \"#6895: 97.20%\\n\",\n      \"#6896: 97.20%\\n\",\n      \"#6897: 97.20%\\n\",\n      \"#6898: 97.20%\\n\",\n      \"#6899: 97.20%\\n\",\n      \"#6900: 97.20%\\n\",\n      \"#6901: 97.20%\\n\",\n      \"#6902: 97.20%\\n\",\n      \"#6903: 97.20%\\n\",\n      \"#6904: 97.20%\\n\",\n      \"#6905: 97.21%\\n\",\n      \"#6906: 97.21%\\n\",\n      \"#6907: 97.21%\\n\",\n      \"#6908: 97.21%\\n\",\n      \"#6909: 97.21%\\n\",\n      \"#6910: 97.21%\\n\",\n      \"#6911: 97.21%\\n\",\n      \"#6912: 97.21%\\n\",\n      \"#6913: 97.21%\\n\",\n      \"#6914: 97.21%\\n\",\n      \"#6915: 97.21%\\n\",\n      \"#6916: 97.21%\\n\",\n      \"#6917: 97.21%\\n\",\n      \"#6918: 97.21%\\n\",\n      \"#6919: 97.21%\\n\",\n      \"#6920: 97.21%\\n\",\n      \"#6921: 97.21%\\n\",\n      \"#6922: 97.21%\\n\",\n      \"#6923: 97.21%\\n\",\n      \"#6924: 97.21%\\n\",\n      \"#6925: 97.21%\\n\",\n      \"#6926: 97.21%\\n\",\n      \"#6927: 97.21%\\n\",\n      \"#6928: 97.21%\\n\",\n      \"#6929: 97.22%\\n\",\n      \"#6930: 97.22%\\n\",\n      \"#6931: 97.22%\\n\",\n      \"#6932: 97.22%\\n\",\n      \"#6933: 97.22%\\n\",\n      \"#6934: 97.22%\\n\",\n      \"#6935: 97.22%\\n\",\n      \"#6936: 97.22%\\n\",\n      \"#6937: 97.22%\\n\",\n      \"#6938: 97.22%\\n\",\n      \"#6939: 97.22%\\n\",\n      \"#6940: 97.22%\\n\",\n      \"#6941: 97.22%\\n\",\n      \"#6942: 97.22%\\n\",\n      \"#6943: 97.22%\\n\",\n      \"#6944: 97.22%\\n\",\n      \"#6945: 97.22%\\n\",\n      \"#6946: 97.22%\\n\",\n      \"#6947: 97.22%\\n\",\n      \"#6948: 97.22%\\n\",\n      \"#6949: 97.22%\\n\",\n      \"#6950: 97.22%\\n\",\n      \"#6951: 97.22%\\n\",\n      \"#6952: 97.22%\\n\",\n      \"#6953: 97.22%\\n\",\n      \"#6954: 97.23%\\n\",\n      \"#6955: 97.23%\\n\",\n      \"#6956: 97.23%\\n\",\n      \"#6957: 97.23%\\n\",\n      \"#6958: 97.23%\\n\",\n      \"#6959: 97.23%\\n\",\n      \"#6960: 97.23%\\n\",\n      \"#6961: 97.23%\\n\",\n      \"#6962: 97.23%\\n\",\n      \"#6963: 97.23%\\n\",\n      \"#6964: 97.23%\\n\",\n      \"#6965: 97.23%\\n\",\n      \"#6966: 97.23%\\n\",\n      \"#6967: 97.23%\\n\",\n      \"#6968: 97.23%\\n\",\n      \"#6969: 97.23%\\n\",\n      \"#6970: 97.23%\\n\",\n      \"#6971: 97.23%\\n\",\n      \"#6972: 97.23%\\n\",\n      \"#6973: 97.23%\\n\",\n      \"#6974: 97.23%\\n\",\n      \"#6975: 97.23%\\n\",\n      \"#6976: 97.23%\\n\",\n      \"#6977: 97.23%\\n\",\n      \"#6978: 97.23%\\n\",\n      \"#6979: 97.23%\\n\",\n      \"#6980: 97.24%\\n\",\n      \"#6981: 97.24%\\n\",\n      \"#6982: 97.24%\\n\",\n      \"#6983: 97.24%\\n\",\n      \"#6984: 97.24%\\n\",\n      \"#6985: 97.24%\\n\",\n      \"#6986: 97.24%\\n\",\n      \"#6987: 97.24%\\n\",\n      \"#6988: 97.24%\\n\",\n      \"#6989: 97.24%\\n\",\n      \"#6990: 97.24%\\n\",\n      \"#6991: 97.24%\\n\",\n      \"#6992: 97.24%\\n\",\n      \"#6993: 97.24%\\n\",\n      \"#6994: 97.24%\\n\",\n      \"#6995: 97.24%\\n\",\n      \"#6996: 97.24%\\n\",\n      \"#6997: 97.24%\\n\",\n      \"#6998: 97.24%\\n\",\n      \"#6999: 97.24%\\n\",\n      \"#7000: 97.24%\\n\",\n      \"#7001: 97.24%\\n\",\n      \"#7002: 97.24%\\n\",\n      \"#7003: 97.24%\\n\",\n      \"#7004: 97.24%\\n\",\n      \"#7005: 97.25%\\n\",\n      \"#7006: 97.25%\\n\",\n      \"#7007: 97.25%\\n\",\n      \"#7008: 97.25%\\n\",\n      \"#7009: 97.25%\\n\",\n      \"#7010: 97.25%\\n\",\n      \"#7011: 97.25%\\n\",\n      \"#7012: 97.25%\\n\",\n      \"#7013: 97.25%\\n\",\n      \"#7014: 97.25%\\n\",\n      \"#7015: 97.25%\\n\",\n      \"#7016: 97.25%\\n\",\n      \"#7017: 97.25%\\n\",\n      \"#7018: 97.25%\\n\",\n      \"#7019: 97.25%\\n\",\n      \"#7020: 97.25%\\n\",\n      \"#7021: 97.25%\\n\",\n      \"#7022: 97.25%\\n\",\n      \"#7023: 97.25%\\n\",\n      \"#7024: 97.25%\\n\",\n      \"#7025: 97.25%\\n\",\n      \"#7026: 97.25%\\n\",\n      \"#7027: 97.25%\\n\",\n      \"#7028: 97.25%\\n\",\n      \"#7029: 97.25%\\n\",\n      \"#7030: 97.26%\\n\",\n      \"#7031: 97.26%\\n\",\n      \"#7032: 97.26%\\n\",\n      \"#7033: 97.26%\\n\",\n      \"#7034: 97.26%\\n\",\n      \"#7035: 97.26%\\n\",\n      \"#7036: 97.26%\\n\",\n      \"#7037: 97.26%\\n\",\n      \"#7038: 97.26%\\n\",\n      \"#7039: 97.26%\\n\",\n      \"#7040: 97.24%\\n\",\n      \"#7041: 97.25%\\n\",\n      \"#7042: 97.25%\\n\",\n      \"#7043: 97.25%\\n\",\n      \"#7044: 97.25%\\n\",\n      \"#7045: 97.25%\\n\",\n      \"#7046: 97.25%\\n\",\n      \"#7047: 97.25%\\n\",\n      \"#7048: 97.25%\\n\",\n      \"#7049: 97.25%\\n\",\n      \"#7050: 97.25%\\n\",\n      \"#7051: 97.25%\\n\",\n      \"#7052: 97.25%\\n\",\n      \"#7053: 97.25%\\n\",\n      \"#7054: 97.25%\\n\",\n      \"#7055: 97.25%\\n\",\n      \"#7056: 97.25%\\n\",\n      \"#7057: 97.25%\\n\",\n      \"#7058: 97.25%\\n\",\n      \"#7059: 97.25%\\n\",\n      \"#7060: 97.25%\\n\",\n      \"#7061: 97.25%\\n\",\n      \"#7062: 97.25%\\n\",\n      \"#7063: 97.25%\\n\",\n      \"#7064: 97.25%\\n\",\n      \"#7065: 97.25%\\n\",\n      \"#7066: 97.25%\\n\",\n      \"#7067: 97.26%\\n\",\n      \"#7068: 97.26%\\n\",\n      \"#7069: 97.26%\\n\",\n      \"#7070: 97.26%\\n\",\n      \"#7071: 97.26%\\n\",\n      \"#7072: 97.26%\\n\",\n      \"#7073: 97.26%\\n\",\n      \"#7074: 97.26%\\n\",\n      \"#7075: 97.26%\\n\",\n      \"#7076: 97.26%\\n\",\n      \"#7077: 97.26%\\n\",\n      \"#7078: 97.26%\\n\",\n      \"#7079: 97.26%\\n\",\n      \"#7080: 97.26%\\n\",\n      \"#7081: 97.26%\\n\",\n      \"#7082: 97.26%\\n\",\n      \"#7083: 97.26%\\n\",\n      \"#7084: 97.26%\\n\",\n      \"#7085: 97.26%\\n\",\n      \"#7086: 97.26%\\n\",\n      \"#7087: 97.26%\\n\",\n      \"#7088: 97.26%\\n\",\n      \"#7089: 97.26%\\n\",\n      \"#7090: 97.26%\\n\",\n      \"#7091: 97.26%\\n\",\n      \"#7092: 97.26%\\n\",\n      \"#7093: 97.27%\\n\",\n      \"#7094: 97.27%\\n\",\n      \"#7095: 97.27%\\n\",\n      \"#7096: 97.27%\\n\",\n      \"#7097: 97.27%\\n\",\n      \"#7098: 97.27%\\n\",\n      \"#7099: 97.27%\\n\",\n      \"#7100: 97.27%\\n\",\n      \"#7101: 97.27%\\n\",\n      \"#7102: 97.27%\\n\",\n      \"#7103: 97.27%\\n\",\n      \"#7104: 97.27%\\n\",\n      \"#7105: 97.27%\\n\",\n      \"#7106: 97.27%\\n\",\n      \"#7107: 97.27%\\n\",\n      \"#7108: 97.27%\\n\",\n      \"#7109: 97.27%\\n\",\n      \"#7110: 97.27%\\n\",\n      \"#7111: 97.27%\\n\",\n      \"#7112: 97.27%\\n\",\n      \"#7113: 97.27%\\n\",\n      \"#7114: 97.27%\\n\",\n      \"#7115: 97.27%\\n\",\n      \"#7116: 97.27%\\n\",\n      \"#7117: 97.27%\\n\",\n      \"#7118: 97.27%\\n\",\n      \"#7119: 97.28%\\n\",\n      \"#7120: 97.28%\\n\",\n      \"#7121: 97.26%\\n\",\n      \"#7122: 97.26%\\n\",\n      \"#7123: 97.26%\\n\",\n      \"#7124: 97.26%\\n\",\n      \"#7125: 97.26%\\n\",\n      \"#7126: 97.26%\\n\",\n      \"#7127: 97.26%\\n\",\n      \"#7128: 97.26%\\n\",\n      \"#7129: 97.27%\\n\",\n      \"#7130: 97.27%\\n\",\n      \"#7131: 97.27%\\n\",\n      \"#7132: 97.27%\\n\",\n      \"#7133: 97.27%\\n\",\n      \"#7134: 97.27%\\n\",\n      \"#7135: 97.27%\\n\",\n      \"#7136: 97.27%\\n\",\n      \"#7137: 97.27%\\n\",\n      \"#7138: 97.27%\\n\",\n      \"#7139: 97.27%\\n\",\n      \"#7140: 97.27%\\n\",\n      \"#7141: 97.27%\\n\",\n      \"#7142: 97.27%\\n\",\n      \"#7143: 97.27%\\n\",\n      \"#7144: 97.27%\\n\",\n      \"#7145: 97.27%\\n\",\n      \"#7146: 97.27%\\n\",\n      \"#7147: 97.27%\\n\",\n      \"#7148: 97.27%\\n\",\n      \"#7149: 97.27%\\n\",\n      \"#7150: 97.27%\\n\",\n      \"#7151: 97.27%\\n\",\n      \"#7152: 97.27%\\n\",\n      \"#7153: 97.27%\\n\",\n      \"#7154: 97.27%\\n\",\n      \"#7155: 97.28%\\n\",\n      \"#7156: 97.28%\\n\",\n      \"#7157: 97.28%\\n\",\n      \"#7158: 97.28%\\n\",\n      \"#7159: 97.28%\\n\",\n      \"#7160: 97.28%\\n\",\n      \"#7161: 97.28%\\n\",\n      \"#7162: 97.28%\\n\",\n      \"#7163: 97.28%\\n\",\n      \"#7164: 97.28%\\n\",\n      \"#7165: 97.28%\\n\",\n      \"#7166: 97.28%\\n\",\n      \"#7167: 97.28%\\n\",\n      \"#7168: 97.28%\\n\",\n      \"#7169: 97.28%\\n\",\n      \"#7170: 97.28%\\n\",\n      \"#7171: 97.28%\\n\",\n      \"#7172: 97.28%\\n\",\n      \"#7173: 97.28%\\n\",\n      \"#7174: 97.28%\\n\",\n      \"#7175: 97.28%\\n\",\n      \"#7176: 97.28%\\n\",\n      \"#7177: 97.28%\\n\",\n      \"#7178: 97.28%\\n\",\n      \"#7179: 97.28%\\n\",\n      \"#7180: 97.28%\\n\",\n      \"#7181: 97.28%\\n\",\n      \"#7182: 97.29%\\n\",\n      \"#7183: 97.29%\\n\",\n      \"#7184: 97.29%\\n\",\n      \"#7185: 97.29%\\n\",\n      \"#7186: 97.29%\\n\",\n      \"#7187: 97.29%\\n\",\n      \"#7188: 97.29%\\n\",\n      \"#7189: 97.29%\\n\",\n      \"#7190: 97.29%\\n\",\n      \"#7191: 97.29%\\n\",\n      \"#7192: 97.29%\\n\",\n      \"#7193: 97.29%\\n\",\n      \"#7194: 97.29%\\n\",\n      \"#7195: 97.29%\\n\",\n      \"#7196: 97.29%\\n\",\n      \"#7197: 97.29%\\n\",\n      \"#7198: 97.29%\\n\",\n      \"#7199: 97.29%\\n\",\n      \"#7200: 97.29%\\n\",\n      \"#7201: 97.29%\\n\",\n      \"#7202: 97.29%\\n\",\n      \"#7203: 97.29%\\n\",\n      \"#7204: 97.29%\\n\",\n      \"#7205: 97.29%\\n\",\n      \"#7206: 97.29%\\n\",\n      \"#7207: 97.29%\\n\",\n      \"#7208: 97.30%\\n\",\n      \"#7209: 97.30%\\n\",\n      \"#7210: 97.30%\\n\",\n      \"#7211: 97.30%\\n\",\n      \"#7212: 97.30%\\n\",\n      \"#7213: 97.30%\\n\",\n      \"#7214: 97.30%\\n\",\n      \"#7215: 97.30%\\n\",\n      \"#7216: 97.30%\\n\",\n      \"#7217: 97.30%\\n\",\n      \"#7218: 97.30%\\n\",\n      \"#7219: 97.30%\\n\",\n      \"#7220: 97.30%\\n\",\n      \"#7221: 97.30%\\n\",\n      \"#7222: 97.30%\\n\",\n      \"#7223: 97.30%\\n\",\n      \"#7224: 97.30%\\n\",\n      \"#7225: 97.30%\\n\",\n      \"#7226: 97.30%\\n\",\n      \"#7227: 97.30%\\n\",\n      \"#7228: 97.30%\\n\",\n      \"#7229: 97.30%\\n\",\n      \"#7230: 97.30%\\n\",\n      \"#7231: 97.30%\\n\",\n      \"#7232: 97.30%\\n\",\n      \"#7233: 97.30%\\n\",\n      \"#7234: 97.30%\\n\",\n      \"#7235: 97.31%\\n\",\n      \"#7236: 97.31%\\n\",\n      \"#7237: 97.31%\\n\",\n      \"#7238: 97.31%\\n\",\n      \"#7239: 97.31%\\n\",\n      \"#7240: 97.31%\\n\",\n      \"#7241: 97.31%\\n\",\n      \"#7242: 97.31%\\n\",\n      \"#7243: 97.31%\\n\",\n      \"#7244: 97.31%\\n\",\n      \"#7245: 97.31%\\n\",\n      \"#7246: 97.31%\\n\",\n      \"#7247: 97.31%\\n\",\n      \"#7248: 97.31%\\n\",\n      \"#7249: 97.31%\\n\",\n      \"#7250: 97.31%\\n\",\n      \"#7251: 97.31%\\n\",\n      \"#7252: 97.31%\\n\",\n      \"#7253: 97.31%\\n\",\n      \"#7254: 97.31%\\n\",\n      \"#7255: 97.31%\\n\",\n      \"#7256: 97.31%\\n\",\n      \"#7257: 97.31%\\n\",\n      \"#7258: 97.31%\\n\",\n      \"#7259: 97.31%\\n\",\n      \"#7260: 97.31%\\n\",\n      \"#7261: 97.31%\\n\",\n      \"#7262: 97.32%\\n\",\n      \"#7263: 97.32%\\n\",\n      \"#7264: 97.32%\\n\",\n      \"#7265: 97.32%\\n\",\n      \"#7266: 97.32%\\n\",\n      \"#7267: 97.32%\\n\",\n      \"#7268: 97.32%\\n\",\n      \"#7269: 97.32%\\n\",\n      \"#7270: 97.32%\\n\",\n      \"#7271: 97.32%\\n\",\n      \"#7272: 97.32%\\n\",\n      \"#7273: 97.32%\\n\",\n      \"#7274: 97.32%\\n\",\n      \"#7275: 97.32%\\n\",\n      \"#7276: 97.32%\\n\",\n      \"#7277: 97.32%\\n\",\n      \"#7278: 97.32%\\n\",\n      \"#7279: 97.32%\\n\",\n      \"#7280: 97.32%\\n\",\n      \"#7281: 97.32%\\n\",\n      \"#7282: 97.32%\\n\",\n      \"#7283: 97.32%\\n\",\n      \"#7284: 97.32%\\n\",\n      \"#7285: 97.32%\\n\",\n      \"#7286: 97.32%\\n\",\n      \"#7287: 97.32%\\n\",\n      \"#7288: 97.32%\\n\",\n      \"#7289: 97.33%\\n\",\n      \"#7290: 97.33%\\n\",\n      \"#7291: 97.33%\\n\",\n      \"#7292: 97.33%\\n\",\n      \"#7293: 97.33%\\n\",\n      \"#7294: 97.33%\\n\",\n      \"#7295: 97.33%\\n\",\n      \"#7296: 97.33%\\n\",\n      \"#7297: 97.33%\\n\",\n      \"#7298: 97.33%\\n\",\n      \"#7299: 97.33%\\n\",\n      \"#7300: 97.33%\\n\",\n      \"#7301: 97.33%\\n\",\n      \"#7302: 97.33%\\n\",\n      \"#7303: 97.33%\\n\",\n      \"#7304: 97.33%\\n\",\n      \"#7305: 97.33%\\n\",\n      \"#7306: 97.33%\\n\",\n      \"#7307: 97.33%\\n\",\n      \"#7308: 97.33%\\n\",\n      \"#7309: 97.33%\\n\",\n      \"#7310: 97.33%\\n\",\n      \"#7311: 97.33%\\n\",\n      \"#7312: 97.33%\\n\",\n      \"#7313: 97.33%\\n\",\n      \"#7314: 97.33%\\n\",\n      \"#7315: 97.33%\\n\",\n      \"#7316: 97.33%\\n\",\n      \"#7317: 97.34%\\n\",\n      \"#7318: 97.34%\\n\",\n      \"#7319: 97.34%\\n\",\n      \"#7320: 97.34%\\n\",\n      \"#7321: 97.34%\\n\",\n      \"#7322: 97.34%\\n\",\n      \"#7323: 97.34%\\n\",\n      \"#7324: 97.34%\\n\",\n      \"#7325: 97.34%\\n\",\n      \"#7326: 97.34%\\n\",\n      \"#7327: 97.34%\\n\",\n      \"#7328: 97.34%\\n\",\n      \"#7329: 97.34%\\n\",\n      \"#7330: 97.34%\\n\",\n      \"#7331: 97.34%\\n\",\n      \"#7332: 97.34%\\n\",\n      \"#7333: 97.34%\\n\",\n      \"#7334: 97.34%\\n\",\n      \"#7335: 97.34%\\n\",\n      \"#7336: 97.34%\\n\",\n      \"#7337: 97.34%\\n\",\n      \"#7338: 97.34%\\n\",\n      \"#7339: 97.34%\\n\",\n      \"#7340: 97.34%\\n\",\n      \"#7341: 97.34%\\n\",\n      \"#7342: 97.34%\\n\",\n      \"#7343: 97.34%\\n\",\n      \"#7344: 97.35%\\n\",\n      \"#7345: 97.35%\\n\",\n      \"#7346: 97.35%\\n\",\n      \"#7347: 97.35%\\n\",\n      \"#7348: 97.35%\\n\",\n      \"#7349: 97.35%\\n\",\n      \"#7350: 97.35%\\n\",\n      \"#7351: 97.35%\\n\",\n      \"#7352: 97.35%\\n\",\n      \"#7353: 97.35%\\n\",\n      \"#7354: 97.35%\\n\",\n      \"#7355: 97.35%\\n\",\n      \"#7356: 97.35%\\n\",\n      \"#7357: 97.35%\\n\",\n      \"#7358: 97.35%\\n\",\n      \"#7359: 97.35%\\n\",\n      \"#7360: 97.35%\\n\",\n      \"#7361: 97.35%\\n\",\n      \"#7362: 97.35%\\n\",\n      \"#7363: 97.35%\\n\",\n      \"#7364: 97.35%\\n\",\n      \"#7365: 97.35%\\n\",\n      \"#7366: 97.35%\\n\",\n      \"#7367: 97.35%\\n\",\n      \"#7368: 97.35%\\n\",\n      \"#7369: 97.35%\\n\",\n      \"#7370: 97.35%\\n\",\n      \"#7371: 97.35%\\n\",\n      \"#7372: 97.36%\\n\",\n      \"#7373: 97.36%\\n\",\n      \"#7374: 97.36%\\n\",\n      \"#7375: 97.36%\\n\",\n      \"#7376: 97.36%\\n\",\n      \"#7377: 97.36%\\n\",\n      \"#7378: 97.36%\\n\",\n      \"#7379: 97.36%\\n\",\n      \"#7380: 97.36%\\n\",\n      \"#7381: 97.36%\\n\",\n      \"#7382: 97.36%\\n\",\n      \"#7383: 97.36%\\n\",\n      \"#7384: 97.36%\\n\",\n      \"#7385: 97.36%\\n\",\n      \"#7386: 97.36%\\n\",\n      \"#7387: 97.36%\\n\",\n      \"#7388: 97.36%\\n\",\n      \"#7389: 97.36%\\n\",\n      \"#7390: 97.36%\\n\",\n      \"#7391: 97.36%\\n\",\n      \"#7392: 97.36%\\n\",\n      \"#7393: 97.36%\\n\",\n      \"#7394: 97.36%\\n\",\n      \"#7395: 97.36%\\n\",\n      \"#7396: 97.36%\\n\",\n      \"#7397: 97.36%\\n\",\n      \"#7398: 97.36%\\n\",\n      \"#7399: 97.36%\\n\",\n      \"#7400: 97.37%\\n\",\n      \"#7401: 97.37%\\n\",\n      \"#7402: 97.37%\\n\",\n      \"#7403: 97.37%\\n\",\n      \"#7404: 97.37%\\n\",\n      \"#7405: 97.37%\\n\",\n      \"#7406: 97.37%\\n\",\n      \"#7407: 97.37%\\n\",\n      \"#7408: 97.37%\\n\",\n      \"#7409: 97.37%\\n\",\n      \"#7410: 97.37%\\n\",\n      \"#7411: 97.37%\\n\",\n      \"#7412: 97.37%\\n\",\n      \"#7413: 97.37%\\n\",\n      \"#7414: 97.37%\\n\",\n      \"#7415: 97.37%\\n\",\n      \"#7416: 97.37%\\n\",\n      \"#7417: 97.37%\\n\",\n      \"#7418: 97.37%\\n\",\n      \"#7419: 97.37%\\n\",\n      \"#7420: 97.37%\\n\",\n      \"#7421: 97.37%\\n\",\n      \"#7422: 97.37%\\n\",\n      \"#7423: 97.37%\\n\",\n      \"#7424: 97.37%\\n\",\n      \"#7425: 97.37%\\n\",\n      \"#7426: 97.37%\\n\",\n      \"#7427: 97.37%\\n\",\n      \"#7428: 97.38%\\n\",\n      \"#7429: 97.38%\\n\",\n      \"#7430: 97.38%\\n\",\n      \"#7431: 97.38%\\n\",\n      \"#7432: 97.38%\\n\",\n      \"#7433: 97.38%\\n\",\n      \"#7434: 97.38%\\n\",\n      \"#7435: 97.38%\\n\",\n      \"#7436: 97.38%\\n\",\n      \"#7437: 97.38%\\n\",\n      \"#7438: 97.38%\\n\",\n      \"#7439: 97.38%\\n\",\n      \"#7440: 97.38%\\n\",\n      \"#7441: 97.38%\\n\",\n      \"#7442: 97.38%\\n\",\n      \"#7443: 97.38%\\n\",\n      \"#7444: 97.38%\\n\",\n      \"#7445: 97.38%\\n\",\n      \"#7446: 97.38%\\n\",\n      \"#7447: 97.38%\\n\",\n      \"#7448: 97.38%\\n\",\n      \"#7449: 97.38%\\n\",\n      \"#7450: 97.38%\\n\",\n      \"#7451: 97.37%\\n\",\n      \"#7452: 97.37%\\n\",\n      \"#7453: 97.37%\\n\",\n      \"#7454: 97.37%\\n\",\n      \"#7455: 97.37%\\n\",\n      \"#7456: 97.37%\\n\",\n      \"#7457: 97.37%\\n\",\n      \"#7458: 97.37%\\n\",\n      \"#7459: 97.37%\\n\",\n      \"#7460: 97.37%\\n\",\n      \"#7461: 97.37%\\n\",\n      \"#7462: 97.37%\\n\",\n      \"#7463: 97.37%\\n\",\n      \"#7464: 97.37%\\n\",\n      \"#7465: 97.37%\\n\",\n      \"#7466: 97.38%\\n\",\n      \"#7467: 97.38%\\n\",\n      \"#7468: 97.38%\\n\",\n      \"#7469: 97.38%\\n\",\n      \"#7470: 97.38%\\n\",\n      \"#7471: 97.38%\\n\",\n      \"#7472: 97.38%\\n\",\n      \"#7473: 97.38%\\n\",\n      \"#7474: 97.38%\\n\",\n      \"#7475: 97.38%\\n\",\n      \"#7476: 97.38%\\n\",\n      \"#7477: 97.38%\\n\",\n      \"#7478: 97.38%\\n\",\n      \"#7479: 97.38%\\n\",\n      \"#7480: 97.38%\\n\",\n      \"#7481: 97.38%\\n\",\n      \"#7482: 97.38%\\n\",\n      \"#7483: 97.38%\\n\",\n      \"#7484: 97.38%\\n\",\n      \"#7485: 97.38%\\n\",\n      \"#7486: 97.38%\\n\",\n      \"#7487: 97.38%\\n\",\n      \"#7488: 97.38%\\n\",\n      \"#7489: 97.38%\\n\",\n      \"#7490: 97.38%\\n\",\n      \"#7491: 97.38%\\n\",\n      \"#7492: 97.38%\\n\",\n      \"#7493: 97.38%\\n\",\n      \"#7494: 97.38%\\n\",\n      \"#7495: 97.39%\\n\",\n      \"#7496: 97.39%\\n\",\n      \"#7497: 97.39%\\n\",\n      \"#7498: 97.39%\\n\",\n      \"#7499: 97.39%\\n\",\n      \"#7500: 97.39%\\n\",\n      \"#7501: 97.39%\\n\",\n      \"#7502: 97.39%\\n\",\n      \"#7503: 97.39%\\n\",\n      \"#7504: 97.39%\\n\",\n      \"#7505: 97.39%\\n\",\n      \"#7506: 97.39%\\n\",\n      \"#7507: 97.39%\\n\",\n      \"#7508: 97.39%\\n\",\n      \"#7509: 97.39%\\n\",\n      \"#7510: 97.39%\\n\",\n      \"#7511: 97.39%\\n\",\n      \"#7512: 97.39%\\n\",\n      \"#7513: 97.39%\\n\",\n      \"#7514: 97.38%\\n\",\n      \"#7515: 97.38%\\n\",\n      \"#7516: 97.38%\\n\",\n      \"#7517: 97.38%\\n\",\n      \"#7518: 97.38%\\n\",\n      \"#7519: 97.38%\\n\",\n      \"#7520: 97.38%\\n\",\n      \"#7521: 97.38%\\n\",\n      \"#7522: 97.38%\\n\",\n      \"#7523: 97.38%\\n\",\n      \"#7524: 97.38%\\n\",\n      \"#7525: 97.38%\\n\",\n      \"#7526: 97.38%\\n\",\n      \"#7527: 97.38%\\n\",\n      \"#7528: 97.38%\\n\",\n      \"#7529: 97.38%\\n\",\n      \"#7530: 97.38%\\n\",\n      \"#7531: 97.38%\\n\",\n      \"#7532: 97.38%\\n\",\n      \"#7533: 97.39%\\n\",\n      \"#7534: 97.39%\\n\",\n      \"#7535: 97.39%\\n\",\n      \"#7536: 97.39%\\n\",\n      \"#7537: 97.39%\\n\",\n      \"#7538: 97.39%\\n\",\n      \"#7539: 97.39%\\n\",\n      \"#7540: 97.39%\\n\",\n      \"#7541: 97.39%\\n\",\n      \"#7542: 97.39%\\n\",\n      \"#7543: 97.39%\\n\",\n      \"#7544: 97.39%\\n\",\n      \"#7545: 97.39%\\n\",\n      \"#7546: 97.39%\\n\",\n      \"#7547: 97.39%\\n\",\n      \"#7548: 97.39%\\n\",\n      \"#7549: 97.39%\\n\",\n      \"#7550: 97.39%\\n\",\n      \"#7551: 97.39%\\n\",\n      \"#7552: 97.39%\\n\",\n      \"#7553: 97.39%\\n\",\n      \"#7554: 97.39%\\n\",\n      \"#7555: 97.39%\\n\",\n      \"#7556: 97.39%\\n\",\n      \"#7557: 97.39%\\n\",\n      \"#7558: 97.39%\\n\",\n      \"#7559: 97.39%\\n\",\n      \"#7560: 97.39%\\n\",\n      \"#7561: 97.39%\\n\",\n      \"#7562: 97.40%\\n\",\n      \"#7563: 97.40%\\n\",\n      \"#7564: 97.40%\\n\",\n      \"#7565: 97.40%\\n\",\n      \"#7566: 97.40%\\n\",\n      \"#7567: 97.40%\\n\",\n      \"#7568: 97.40%\\n\",\n      \"#7569: 97.40%\\n\",\n      \"#7570: 97.40%\\n\",\n      \"#7571: 97.40%\\n\",\n      \"#7572: 97.40%\\n\",\n      \"#7573: 97.40%\\n\",\n      \"#7574: 97.40%\\n\",\n      \"#7575: 97.40%\\n\",\n      \"#7576: 97.40%\\n\",\n      \"#7577: 97.40%\\n\",\n      \"#7578: 97.40%\\n\",\n      \"#7579: 97.40%\\n\",\n      \"#7580: 97.40%\\n\",\n      \"#7581: 97.40%\\n\",\n      \"#7582: 97.40%\\n\",\n      \"#7583: 97.40%\\n\",\n      \"#7584: 97.40%\\n\",\n      \"#7585: 97.40%\\n\",\n      \"#7586: 97.40%\\n\",\n      \"#7587: 97.40%\\n\",\n      \"#7588: 97.40%\\n\",\n      \"#7589: 97.40%\\n\",\n      \"#7590: 97.40%\\n\",\n      \"#7591: 97.41%\\n\",\n      \"#7592: 97.41%\\n\",\n      \"#7593: 97.41%\\n\",\n      \"#7594: 97.41%\\n\",\n      \"#7595: 97.41%\\n\",\n      \"#7596: 97.41%\\n\",\n      \"#7597: 97.41%\\n\",\n      \"#7598: 97.41%\\n\",\n      \"#7599: 97.41%\\n\",\n      \"#7600: 97.41%\\n\",\n      \"#7601: 97.41%\\n\",\n      \"#7602: 97.41%\\n\",\n      \"#7603: 97.41%\\n\",\n      \"#7604: 97.41%\\n\",\n      \"#7605: 97.41%\\n\",\n      \"#7606: 97.41%\\n\",\n      \"#7607: 97.41%\\n\",\n      \"#7608: 97.41%\\n\",\n      \"#7609: 97.41%\\n\",\n      \"#7610: 97.41%\\n\",\n      \"#7611: 97.41%\\n\",\n      \"#7612: 97.41%\\n\",\n      \"#7613: 97.41%\\n\",\n      \"#7614: 97.41%\\n\",\n      \"#7615: 97.41%\\n\",\n      \"#7616: 97.41%\\n\",\n      \"#7617: 97.41%\\n\",\n      \"#7618: 97.41%\\n\",\n      \"#7619: 97.41%\\n\",\n      \"#7620: 97.42%\\n\",\n      \"#7621: 97.42%\\n\",\n      \"#7622: 97.42%\\n\",\n      \"#7623: 97.42%\\n\",\n      \"#7624: 97.42%\\n\",\n      \"#7625: 97.42%\\n\",\n      \"#7626: 97.42%\\n\",\n      \"#7627: 97.42%\\n\",\n      \"#7628: 97.42%\\n\",\n      \"#7629: 97.42%\\n\",\n      \"#7630: 97.42%\\n\",\n      \"#7631: 97.42%\\n\",\n      \"#7632: 97.42%\\n\",\n      \"#7633: 97.42%\\n\",\n      \"#7634: 97.42%\\n\",\n      \"#7635: 97.42%\\n\",\n      \"#7636: 97.42%\\n\",\n      \"#7637: 97.42%\\n\",\n      \"#7638: 97.42%\\n\",\n      \"#7639: 97.42%\\n\",\n      \"#7640: 97.42%\\n\",\n      \"#7641: 97.42%\\n\",\n      \"#7642: 97.42%\\n\",\n      \"#7643: 97.42%\\n\",\n      \"#7644: 97.42%\\n\",\n      \"#7645: 97.42%\\n\",\n      \"#7646: 97.42%\\n\",\n      \"#7647: 97.42%\\n\",\n      \"#7648: 97.42%\\n\",\n      \"#7649: 97.42%\\n\",\n      \"#7650: 97.43%\\n\",\n      \"#7651: 97.43%\\n\",\n      \"#7652: 97.43%\\n\",\n      \"#7653: 97.43%\\n\",\n      \"#7654: 97.43%\\n\",\n      \"#7655: 97.43%\\n\",\n      \"#7656: 97.43%\\n\",\n      \"#7657: 97.43%\\n\",\n      \"#7658: 97.43%\\n\",\n      \"#7659: 97.43%\\n\",\n      \"#7660: 97.43%\\n\",\n      \"#7661: 97.43%\\n\",\n      \"#7662: 97.43%\\n\",\n      \"#7663: 97.43%\\n\",\n      \"#7664: 97.43%\\n\",\n      \"#7665: 97.43%\\n\",\n      \"#7666: 97.43%\\n\",\n      \"#7667: 97.43%\\n\",\n      \"#7668: 97.43%\\n\",\n      \"#7669: 97.43%\\n\",\n      \"#7670: 97.43%\\n\",\n      \"#7671: 97.43%\\n\",\n      \"#7672: 97.43%\\n\",\n      \"#7673: 97.43%\\n\",\n      \"#7674: 97.43%\\n\",\n      \"#7675: 97.43%\\n\",\n      \"#7676: 97.43%\\n\",\n      \"#7677: 97.43%\\n\",\n      \"#7678: 97.43%\\n\",\n      \"#7679: 97.43%\\n\",\n      \"#7680: 97.44%\\n\",\n      \"#7681: 97.44%\\n\",\n      \"#7682: 97.44%\\n\",\n      \"#7683: 97.44%\\n\",\n      \"#7684: 97.44%\\n\",\n      \"#7685: 97.44%\\n\",\n      \"#7686: 97.44%\\n\",\n      \"#7687: 97.44%\\n\",\n      \"#7688: 97.44%\\n\",\n      \"#7689: 97.44%\\n\",\n      \"#7690: 97.44%\\n\",\n      \"#7691: 97.44%\\n\",\n      \"#7692: 97.44%\\n\",\n      \"#7693: 97.44%\\n\",\n      \"#7694: 97.44%\\n\",\n      \"#7695: 97.44%\\n\",\n      \"#7696: 97.44%\\n\",\n      \"#7697: 97.44%\\n\",\n      \"#7698: 97.44%\\n\",\n      \"#7699: 97.44%\\n\",\n      \"#7700: 97.44%\\n\",\n      \"#7701: 97.44%\\n\",\n      \"#7702: 97.44%\\n\",\n      \"#7703: 97.44%\\n\",\n      \"#7704: 97.44%\\n\",\n      \"#7705: 97.44%\\n\",\n      \"#7706: 97.44%\\n\",\n      \"#7707: 97.44%\\n\",\n      \"#7708: 97.44%\\n\",\n      \"#7709: 97.44%\\n\",\n      \"#7710: 97.45%\\n\",\n      \"#7711: 97.45%\\n\",\n      \"#7712: 97.45%\\n\",\n      \"#7713: 97.45%\\n\",\n      \"#7714: 97.45%\\n\",\n      \"#7715: 97.45%\\n\",\n      \"#7716: 97.45%\\n\",\n      \"#7717: 97.45%\\n\",\n      \"#7718: 97.45%\\n\",\n      \"#7719: 97.45%\\n\",\n      \"#7720: 97.45%\\n\",\n      \"#7721: 97.45%\\n\",\n      \"#7722: 97.45%\\n\",\n      \"#7723: 97.45%\\n\",\n      \"#7724: 97.45%\\n\",\n      \"#7725: 97.45%\\n\",\n      \"#7726: 97.45%\\n\",\n      \"#7727: 97.45%\\n\",\n      \"#7728: 97.45%\\n\",\n      \"#7729: 97.45%\\n\",\n      \"#7730: 97.45%\\n\",\n      \"#7731: 97.45%\\n\",\n      \"#7732: 97.45%\\n\",\n      \"#7733: 97.45%\\n\",\n      \"#7734: 97.45%\\n\",\n      \"#7735: 97.45%\\n\",\n      \"#7736: 97.45%\\n\",\n      \"#7737: 97.45%\\n\",\n      \"#7738: 97.45%\\n\",\n      \"#7739: 97.45%\\n\",\n      \"#7740: 97.46%\\n\",\n      \"#7741: 97.46%\\n\",\n      \"#7742: 97.46%\\n\",\n      \"#7743: 97.46%\\n\",\n      \"#7744: 97.46%\\n\",\n      \"#7745: 97.46%\\n\",\n      \"#7746: 97.46%\\n\",\n      \"#7747: 97.46%\\n\",\n      \"#7748: 97.46%\\n\",\n      \"#7749: 97.46%\\n\",\n      \"#7750: 97.46%\\n\",\n      \"#7751: 97.46%\\n\",\n      \"#7752: 97.46%\\n\",\n      \"#7753: 97.46%\\n\",\n      \"#7754: 97.46%\\n\",\n      \"#7755: 97.46%\\n\",\n      \"#7756: 97.46%\\n\",\n      \"#7757: 97.46%\\n\",\n      \"#7758: 97.46%\\n\",\n      \"#7759: 97.46%\\n\",\n      \"#7760: 97.46%\\n\",\n      \"#7761: 97.46%\\n\",\n      \"#7762: 97.46%\\n\",\n      \"#7763: 97.46%\\n\",\n      \"#7764: 97.46%\\n\",\n      \"#7765: 97.46%\\n\",\n      \"#7766: 97.46%\\n\",\n      \"#7767: 97.46%\\n\",\n      \"#7768: 97.46%\\n\",\n      \"#7769: 97.46%\\n\",\n      \"#7770: 97.46%\\n\",\n      \"#7771: 97.47%\\n\",\n      \"#7772: 97.47%\\n\",\n      \"#7773: 97.47%\\n\",\n      \"#7774: 97.47%\\n\",\n      \"#7775: 97.47%\\n\",\n      \"#7776: 97.47%\\n\",\n      \"#7777: 97.47%\\n\",\n      \"#7778: 97.47%\\n\",\n      \"#7779: 97.47%\\n\",\n      \"#7780: 97.47%\\n\",\n      \"#7781: 97.47%\\n\",\n      \"#7782: 97.47%\\n\",\n      \"#7783: 97.47%\\n\",\n      \"#7784: 97.47%\\n\",\n      \"#7785: 97.47%\\n\",\n      \"#7786: 97.47%\\n\",\n      \"#7787: 97.47%\\n\",\n      \"#7788: 97.47%\\n\",\n      \"#7789: 97.47%\\n\",\n      \"#7790: 97.47%\\n\",\n      \"#7791: 97.47%\\n\",\n      \"#7792: 97.47%\\n\",\n      \"#7793: 97.47%\\n\",\n      \"#7794: 97.47%\\n\",\n      \"#7795: 97.47%\\n\",\n      \"#7796: 97.47%\\n\",\n      \"#7797: 97.47%\\n\",\n      \"#7798: 97.47%\\n\",\n      \"#7799: 97.47%\\n\",\n      \"#7800: 97.47%\\n\",\n      \"#7801: 97.48%\\n\",\n      \"#7802: 97.48%\\n\",\n      \"#7803: 97.48%\\n\",\n      \"#7804: 97.48%\\n\",\n      \"#7805: 97.48%\\n\",\n      \"#7806: 97.48%\\n\",\n      \"#7807: 97.48%\\n\",\n      \"#7808: 97.48%\\n\",\n      \"#7809: 97.48%\\n\",\n      \"#7810: 97.48%\\n\",\n      \"#7811: 97.48%\\n\",\n      \"#7812: 97.48%\\n\",\n      \"#7813: 97.48%\\n\",\n      \"#7814: 97.48%\\n\",\n      \"#7815: 97.48%\\n\",\n      \"#7816: 97.48%\\n\",\n      \"#7817: 97.48%\\n\",\n      \"#7818: 97.48%\\n\",\n      \"#7819: 97.48%\\n\",\n      \"#7820: 97.48%\\n\",\n      \"#7821: 97.48%\\n\",\n      \"#7822: 97.48%\\n\",\n      \"#7823: 97.48%\\n\",\n      \"#7824: 97.48%\\n\",\n      \"#7825: 97.48%\\n\",\n      \"#7826: 97.48%\\n\",\n      \"#7827: 97.48%\\n\",\n      \"#7828: 97.48%\\n\",\n      \"#7829: 97.48%\\n\",\n      \"#7830: 97.48%\\n\",\n      \"#7831: 97.48%\\n\",\n      \"#7832: 97.48%\\n\",\n      \"#7833: 97.49%\\n\",\n      \"#7834: 97.49%\\n\",\n      \"#7835: 97.49%\\n\",\n      \"#7836: 97.49%\\n\",\n      \"#7837: 97.49%\\n\",\n      \"#7838: 97.49%\\n\",\n      \"#7839: 97.49%\\n\",\n      \"#7840: 97.49%\\n\",\n      \"#7841: 97.49%\\n\",\n      \"#7842: 97.49%\\n\",\n      \"#7843: 97.49%\\n\",\n      \"#7844: 97.49%\\n\",\n      \"#7845: 97.48%\\n\",\n      \"#7846: 97.48%\\n\",\n      \"#7847: 97.48%\\n\",\n      \"#7848: 97.48%\\n\",\n      \"#7849: 97.48%\\n\",\n      \"#7850: 97.48%\\n\",\n      \"#7851: 97.48%\\n\",\n      \"#7852: 97.48%\\n\",\n      \"#7853: 97.48%\\n\",\n      \"#7854: 97.48%\\n\",\n      \"#7855: 97.48%\\n\",\n      \"#7856: 97.48%\\n\",\n      \"#7857: 97.48%\\n\",\n      \"#7858: 97.48%\\n\",\n      \"#7859: 97.48%\\n\",\n      \"#7860: 97.48%\\n\",\n      \"#7861: 97.48%\\n\",\n      \"#7862: 97.48%\\n\",\n      \"#7863: 97.48%\\n\",\n      \"#7864: 97.48%\\n\",\n      \"#7865: 97.48%\\n\",\n      \"#7866: 97.48%\\n\",\n      \"#7867: 97.48%\\n\",\n      \"#7868: 97.48%\\n\",\n      \"#7869: 97.48%\\n\",\n      \"#7870: 97.48%\\n\",\n      \"#7871: 97.48%\\n\",\n      \"#7872: 97.49%\\n\",\n      \"#7873: 97.49%\\n\",\n      \"#7874: 97.49%\\n\",\n      \"#7875: 97.49%\\n\",\n      \"#7876: 97.49%\\n\",\n      \"#7877: 97.49%\\n\",\n      \"#7878: 97.49%\\n\",\n      \"#7879: 97.49%\\n\",\n      \"#7880: 97.49%\\n\",\n      \"#7881: 97.49%\\n\",\n      \"#7882: 97.49%\\n\",\n      \"#7883: 97.49%\\n\",\n      \"#7884: 97.49%\\n\",\n      \"#7885: 97.49%\\n\",\n      \"#7886: 97.48%\\n\",\n      \"#7887: 97.48%\\n\",\n      \"#7888: 97.48%\\n\",\n      \"#7889: 97.48%\\n\",\n      \"#7890: 97.48%\\n\",\n      \"#7891: 97.48%\\n\",\n      \"#7892: 97.48%\\n\",\n      \"#7893: 97.48%\\n\",\n      \"#7894: 97.48%\\n\",\n      \"#7895: 97.48%\\n\",\n      \"#7896: 97.48%\\n\",\n      \"#7897: 97.48%\\n\",\n      \"#7898: 97.48%\\n\",\n      \"#7899: 97.48%\\n\",\n      \"#7900: 97.48%\\n\",\n      \"#7901: 97.48%\\n\",\n      \"#7902: 97.48%\\n\",\n      \"#7903: 97.48%\\n\",\n      \"#7904: 97.48%\\n\",\n      \"#7905: 97.48%\\n\",\n      \"#7906: 97.48%\\n\",\n      \"#7907: 97.48%\\n\",\n      \"#7908: 97.48%\\n\",\n      \"#7909: 97.48%\\n\",\n      \"#7910: 97.48%\\n\",\n      \"#7911: 97.48%\\n\",\n      \"#7912: 97.49%\\n\",\n      \"#7913: 97.49%\\n\",\n      \"#7914: 97.49%\\n\",\n      \"#7915: 97.47%\\n\",\n      \"#7916: 97.47%\\n\",\n      \"#7917: 97.47%\\n\",\n      \"#7918: 97.47%\\n\",\n      \"#7919: 97.47%\\n\",\n      \"#7920: 97.48%\\n\",\n      \"#7921: 97.48%\\n\",\n      \"#7922: 97.48%\\n\",\n      \"#7923: 97.48%\\n\",\n      \"#7924: 97.48%\\n\",\n      \"#7925: 97.48%\\n\",\n      \"#7926: 97.48%\\n\",\n      \"#7927: 97.46%\\n\",\n      \"#7928: 97.47%\\n\",\n      \"#7929: 97.47%\\n\",\n      \"#7930: 97.47%\\n\",\n      \"#7931: 97.47%\\n\",\n      \"#7932: 97.47%\\n\",\n      \"#7933: 97.47%\\n\",\n      \"#7934: 97.47%\\n\",\n      \"#7935: 97.47%\\n\",\n      \"#7936: 97.47%\\n\",\n      \"#7937: 97.47%\\n\",\n      \"#7938: 97.47%\\n\",\n      \"#7939: 97.47%\\n\",\n      \"#7940: 97.47%\\n\",\n      \"#7941: 97.47%\\n\",\n      \"#7942: 97.47%\\n\",\n      \"#7943: 97.47%\\n\",\n      \"#7944: 97.47%\\n\",\n      \"#7945: 97.47%\\n\",\n      \"#7946: 97.47%\\n\",\n      \"#7947: 97.47%\\n\",\n      \"#7948: 97.47%\\n\",\n      \"#7949: 97.47%\\n\",\n      \"#7950: 97.47%\\n\",\n      \"#7951: 97.47%\\n\",\n      \"#7952: 97.47%\\n\",\n      \"#7953: 97.47%\\n\",\n      \"#7954: 97.47%\\n\",\n      \"#7955: 97.47%\\n\",\n      \"#7956: 97.47%\\n\",\n      \"#7957: 97.47%\\n\",\n      \"#7958: 97.47%\\n\",\n      \"#7959: 97.47%\\n\",\n      \"#7960: 97.48%\\n\",\n      \"#7961: 97.48%\\n\",\n      \"#7962: 97.48%\\n\",\n      \"#7963: 97.48%\\n\",\n      \"#7964: 97.48%\\n\",\n      \"#7965: 97.48%\\n\",\n      \"#7966: 97.48%\\n\",\n      \"#7967: 97.48%\\n\",\n      \"#7968: 97.48%\\n\",\n      \"#7969: 97.48%\\n\",\n      \"#7970: 97.48%\\n\",\n      \"#7971: 97.48%\\n\",\n      \"#7972: 97.48%\\n\",\n      \"#7973: 97.48%\\n\",\n      \"#7974: 97.48%\\n\",\n      \"#7975: 97.48%\\n\",\n      \"#7976: 97.48%\\n\",\n      \"#7977: 97.48%\\n\",\n      \"#7978: 97.48%\\n\",\n      \"#7979: 97.48%\\n\",\n      \"#7980: 97.48%\\n\",\n      \"#7981: 97.48%\\n\",\n      \"#7982: 97.48%\\n\",\n      \"#7983: 97.48%\\n\",\n      \"#7984: 97.48%\\n\",\n      \"#7985: 97.48%\\n\",\n      \"#7986: 97.48%\\n\",\n      \"#7987: 97.48%\\n\",\n      \"#7988: 97.48%\\n\",\n      \"#7989: 97.48%\\n\",\n      \"#7990: 97.48%\\n\",\n      \"#7991: 97.48%\\n\",\n      \"#7992: 97.49%\\n\",\n      \"#7993: 97.49%\\n\",\n      \"#7994: 97.49%\\n\",\n      \"#7995: 97.49%\\n\",\n      \"#7996: 97.49%\\n\",\n      \"#7997: 97.49%\\n\",\n      \"#7998: 97.49%\\n\",\n      \"#7999: 97.49%\\n\",\n      \"#8000: 97.49%\\n\",\n      \"#8001: 97.49%\\n\",\n      \"#8002: 97.49%\\n\",\n      \"#8003: 97.49%\\n\",\n      \"#8004: 97.49%\\n\",\n      \"#8005: 97.49%\\n\",\n      \"#8006: 97.49%\\n\",\n      \"#8007: 97.49%\\n\",\n      \"#8008: 97.49%\\n\",\n      \"#8009: 97.49%\\n\",\n      \"#8010: 97.49%\\n\",\n      \"#8011: 97.49%\\n\",\n      \"#8012: 97.49%\\n\",\n      \"#8013: 97.49%\\n\",\n      \"#8014: 97.49%\\n\",\n      \"#8015: 97.49%\\n\",\n      \"#8016: 97.49%\\n\",\n      \"#8017: 97.49%\\n\",\n      \"#8018: 97.49%\\n\",\n      \"#8019: 97.49%\\n\",\n      \"#8020: 97.49%\\n\",\n      \"#8021: 97.49%\\n\",\n      \"#8022: 97.49%\\n\",\n      \"#8023: 97.50%\\n\",\n      \"#8024: 97.50%\\n\",\n      \"#8025: 97.50%\\n\",\n      \"#8026: 97.50%\\n\",\n      \"#8027: 97.50%\\n\",\n      \"#8028: 97.50%\\n\",\n      \"#8029: 97.50%\\n\",\n      \"#8030: 97.50%\\n\",\n      \"#8031: 97.50%\\n\",\n      \"#8032: 97.50%\\n\",\n      \"#8033: 97.50%\\n\",\n      \"#8034: 97.50%\\n\",\n      \"#8035: 97.50%\\n\",\n      \"#8036: 97.50%\\n\",\n      \"#8037: 97.50%\\n\",\n      \"#8038: 97.50%\\n\",\n      \"#8039: 97.50%\\n\",\n      \"#8040: 97.50%\\n\",\n      \"#8041: 97.50%\\n\",\n      \"#8042: 97.50%\\n\",\n      \"#8043: 97.50%\\n\",\n      \"#8044: 97.50%\\n\",\n      \"#8045: 97.50%\\n\",\n      \"#8046: 97.50%\\n\",\n      \"#8047: 97.49%\\n\",\n      \"#8048: 97.49%\\n\",\n      \"#8049: 97.49%\\n\",\n      \"#8050: 97.49%\\n\",\n      \"#8051: 97.49%\\n\",\n      \"#8052: 97.49%\\n\",\n      \"#8053: 97.49%\\n\",\n      \"#8054: 97.49%\\n\",\n      \"#8055: 97.49%\\n\",\n      \"#8056: 97.49%\\n\",\n      \"#8057: 97.49%\\n\",\n      \"#8058: 97.49%\\n\",\n      \"#8059: 97.48%\\n\",\n      \"#8060: 97.48%\\n\",\n      \"#8061: 97.48%\\n\",\n      \"#8062: 97.48%\\n\",\n      \"#8063: 97.48%\\n\",\n      \"#8064: 97.48%\\n\",\n      \"#8065: 97.48%\\n\",\n      \"#8066: 97.48%\\n\",\n      \"#8067: 97.48%\\n\",\n      \"#8068: 97.48%\\n\",\n      \"#8069: 97.48%\\n\",\n      \"#8070: 97.48%\\n\",\n      \"#8071: 97.49%\\n\",\n      \"#8072: 97.49%\\n\",\n      \"#8073: 97.49%\\n\",\n      \"#8074: 97.49%\\n\",\n      \"#8075: 97.49%\\n\",\n      \"#8076: 97.49%\\n\",\n      \"#8077: 97.49%\\n\",\n      \"#8078: 97.49%\\n\",\n      \"#8079: 97.49%\\n\",\n      \"#8080: 97.49%\\n\",\n      \"#8081: 97.49%\\n\",\n      \"#8082: 97.49%\\n\",\n      \"#8083: 97.49%\\n\",\n      \"#8084: 97.49%\\n\",\n      \"#8085: 97.49%\\n\",\n      \"#8086: 97.49%\\n\",\n      \"#8087: 97.49%\\n\",\n      \"#8088: 97.49%\\n\",\n      \"#8089: 97.49%\\n\",\n      \"#8090: 97.49%\\n\",\n      \"#8091: 97.48%\\n\",\n      \"#8092: 97.48%\\n\",\n      \"#8093: 97.48%\\n\",\n      \"#8094: 97.47%\\n\",\n      \"#8095: 97.47%\\n\",\n      \"#8096: 97.47%\\n\",\n      \"#8097: 97.47%\\n\",\n      \"#8098: 97.47%\\n\",\n      \"#8099: 97.47%\\n\",\n      \"#8100: 97.47%\\n\",\n      \"#8101: 97.47%\\n\",\n      \"#8102: 97.47%\\n\",\n      \"#8103: 97.47%\\n\",\n      \"#8104: 97.47%\\n\",\n      \"#8105: 97.47%\\n\",\n      \"#8106: 97.47%\\n\",\n      \"#8107: 97.47%\\n\",\n      \"#8108: 97.47%\\n\",\n      \"#8109: 97.47%\\n\",\n      \"#8110: 97.47%\\n\",\n      \"#8111: 97.47%\\n\",\n      \"#8112: 97.47%\\n\",\n      \"#8113: 97.47%\\n\",\n      \"#8114: 97.47%\\n\",\n      \"#8115: 97.47%\\n\",\n      \"#8116: 97.47%\\n\",\n      \"#8117: 97.47%\\n\",\n      \"#8118: 97.48%\\n\",\n      \"#8119: 97.48%\\n\",\n      \"#8120: 97.48%\\n\",\n      \"#8121: 97.48%\\n\",\n      \"#8122: 97.48%\\n\",\n      \"#8123: 97.48%\\n\",\n      \"#8124: 97.48%\\n\",\n      \"#8125: 97.48%\\n\",\n      \"#8126: 97.48%\\n\",\n      \"#8127: 97.48%\\n\",\n      \"#8128: 97.48%\\n\",\n      \"#8129: 97.48%\\n\",\n      \"#8130: 97.48%\\n\",\n      \"#8131: 97.48%\\n\",\n      \"#8132: 97.48%\\n\",\n      \"#8133: 97.48%\\n\",\n      \"#8134: 97.48%\\n\",\n      \"#8135: 97.48%\\n\",\n      \"#8136: 97.48%\\n\",\n      \"#8137: 97.48%\\n\",\n      \"#8138: 97.48%\\n\",\n      \"#8139: 97.48%\\n\",\n      \"#8140: 97.48%\\n\",\n      \"#8141: 97.48%\\n\",\n      \"#8142: 97.48%\\n\",\n      \"#8143: 97.48%\\n\",\n      \"#8144: 97.48%\\n\",\n      \"#8145: 97.48%\\n\",\n      \"#8146: 97.48%\\n\",\n      \"#8147: 97.48%\\n\",\n      \"#8148: 97.48%\\n\",\n      \"#8149: 97.48%\\n\",\n      \"#8150: 97.48%\\n\",\n      \"#8151: 97.49%\\n\",\n      \"#8152: 97.49%\\n\",\n      \"#8153: 97.49%\\n\",\n      \"#8154: 97.49%\\n\",\n      \"#8155: 97.49%\\n\",\n      \"#8156: 97.49%\\n\",\n      \"#8157: 97.49%\\n\",\n      \"#8158: 97.49%\\n\",\n      \"#8159: 97.49%\\n\",\n      \"#8160: 97.49%\\n\",\n      \"#8161: 97.49%\\n\",\n      \"#8162: 97.49%\\n\",\n      \"#8163: 97.49%\\n\",\n      \"#8164: 97.49%\\n\",\n      \"#8165: 97.49%\\n\",\n      \"#8166: 97.49%\\n\",\n      \"#8167: 97.49%\\n\",\n      \"#8168: 97.49%\\n\",\n      \"#8169: 97.49%\\n\",\n      \"#8170: 97.49%\\n\",\n      \"#8171: 97.49%\\n\",\n      \"#8172: 97.49%\\n\",\n      \"#8173: 97.49%\\n\",\n      \"#8174: 97.49%\\n\",\n      \"#8175: 97.49%\\n\",\n      \"#8176: 97.49%\\n\",\n      \"#8177: 97.49%\\n\",\n      \"#8178: 97.49%\\n\",\n      \"#8179: 97.49%\\n\",\n      \"#8180: 97.49%\\n\",\n      \"#8181: 97.49%\\n\",\n      \"#8182: 97.49%\\n\",\n      \"#8183: 97.50%\\n\",\n      \"#8184: 97.50%\\n\",\n      \"#8185: 97.50%\\n\",\n      \"#8186: 97.50%\\n\",\n      \"#8187: 97.50%\\n\",\n      \"#8188: 97.50%\\n\",\n      \"#8189: 97.50%\\n\",\n      \"#8190: 97.50%\\n\",\n      \"#8191: 97.50%\\n\",\n      \"#8192: 97.50%\\n\",\n      \"#8193: 97.50%\\n\",\n      \"#8194: 97.50%\\n\",\n      \"#8195: 97.50%\\n\",\n      \"#8196: 97.50%\\n\",\n      \"#8197: 97.50%\\n\",\n      \"#8198: 97.50%\\n\",\n      \"#8199: 97.50%\\n\",\n      \"#8200: 97.50%\\n\",\n      \"#8201: 97.50%\\n\",\n      \"#8202: 97.50%\\n\",\n      \"#8203: 97.50%\\n\",\n      \"#8204: 97.50%\\n\",\n      \"#8205: 97.50%\\n\",\n      \"#8206: 97.50%\\n\",\n      \"#8207: 97.50%\\n\",\n      \"#8208: 97.50%\\n\",\n      \"#8209: 97.50%\\n\",\n      \"#8210: 97.50%\\n\",\n      \"#8211: 97.50%\\n\",\n      \"#8212: 97.50%\\n\",\n      \"#8213: 97.50%\\n\",\n      \"#8214: 97.50%\\n\",\n      \"#8215: 97.50%\\n\",\n      \"#8216: 97.51%\\n\",\n      \"#8217: 97.51%\\n\",\n      \"#8218: 97.51%\\n\",\n      \"#8219: 97.51%\\n\",\n      \"#8220: 97.51%\\n\",\n      \"#8221: 97.51%\\n\",\n      \"#8222: 97.51%\\n\",\n      \"#8223: 97.51%\\n\",\n      \"#8224: 97.51%\\n\",\n      \"#8225: 97.51%\\n\",\n      \"#8226: 97.51%\\n\",\n      \"#8227: 97.51%\\n\",\n      \"#8228: 97.51%\\n\",\n      \"#8229: 97.51%\\n\",\n      \"#8230: 97.51%\\n\",\n      \"#8231: 97.51%\\n\",\n      \"#8232: 97.51%\\n\",\n      \"#8233: 97.51%\\n\",\n      \"#8234: 97.51%\\n\",\n      \"#8235: 97.51%\\n\",\n      \"#8236: 97.51%\\n\",\n      \"#8237: 97.51%\\n\",\n      \"#8238: 97.51%\\n\",\n      \"#8239: 97.51%\\n\",\n      \"#8240: 97.51%\\n\",\n      \"#8241: 97.51%\\n\",\n      \"#8242: 97.51%\\n\",\n      \"#8243: 97.51%\\n\",\n      \"#8244: 97.51%\\n\",\n      \"#8245: 97.51%\\n\",\n      \"#8246: 97.51%\\n\",\n      \"#8247: 97.51%\\n\",\n      \"#8248: 97.51%\\n\",\n      \"#8249: 97.52%\\n\",\n      \"#8250: 97.52%\\n\",\n      \"#8251: 97.52%\\n\",\n      \"#8252: 97.52%\\n\",\n      \"#8253: 97.52%\\n\",\n      \"#8254: 97.52%\\n\",\n      \"#8255: 97.52%\\n\",\n      \"#8256: 97.52%\\n\",\n      \"#8257: 97.52%\\n\",\n      \"#8258: 97.52%\\n\",\n      \"#8259: 97.52%\\n\",\n      \"#8260: 97.52%\\n\",\n      \"#8261: 97.52%\\n\",\n      \"#8262: 97.52%\\n\",\n      \"#8263: 97.52%\\n\",\n      \"#8264: 97.52%\\n\",\n      \"#8265: 97.52%\\n\",\n      \"#8266: 97.52%\\n\",\n      \"#8267: 97.52%\\n\",\n      \"#8268: 97.52%\\n\",\n      \"#8269: 97.52%\\n\",\n      \"#8270: 97.52%\\n\",\n      \"#8271: 97.52%\\n\",\n      \"#8272: 97.52%\\n\",\n      \"#8273: 97.52%\\n\",\n      \"#8274: 97.52%\\n\",\n      \"#8275: 97.52%\\n\",\n      \"#8276: 97.52%\\n\",\n      \"#8277: 97.52%\\n\",\n      \"#8278: 97.51%\\n\",\n      \"#8279: 97.51%\\n\",\n      \"#8280: 97.51%\\n\",\n      \"#8281: 97.51%\\n\",\n      \"#8282: 97.51%\\n\",\n      \"#8283: 97.51%\\n\",\n      \"#8284: 97.51%\\n\",\n      \"#8285: 97.51%\\n\",\n      \"#8286: 97.51%\\n\",\n      \"#8287: 97.51%\\n\",\n      \"#8288: 97.51%\\n\",\n      \"#8289: 97.52%\\n\",\n      \"#8290: 97.52%\\n\",\n      \"#8291: 97.52%\\n\",\n      \"#8292: 97.52%\\n\",\n      \"#8293: 97.52%\\n\",\n      \"#8294: 97.52%\\n\",\n      \"#8295: 97.52%\\n\",\n      \"#8296: 97.52%\\n\",\n      \"#8297: 97.52%\\n\",\n      \"#8298: 97.52%\\n\",\n      \"#8299: 97.52%\\n\",\n      \"#8300: 97.52%\\n\",\n      \"#8301: 97.52%\\n\",\n      \"#8302: 97.52%\\n\",\n      \"#8303: 97.52%\\n\",\n      \"#8304: 97.52%\\n\",\n      \"#8305: 97.52%\\n\",\n      \"#8306: 97.52%\\n\",\n      \"#8307: 97.52%\\n\",\n      \"#8308: 97.52%\\n\",\n      \"#8309: 97.52%\\n\",\n      \"#8310: 97.52%\\n\",\n      \"#8311: 97.52%\\n\",\n      \"#8312: 97.52%\\n\",\n      \"#8313: 97.52%\\n\",\n      \"#8314: 97.52%\\n\",\n      \"#8315: 97.52%\\n\",\n      \"#8316: 97.51%\\n\",\n      \"#8317: 97.51%\\n\",\n      \"#8318: 97.51%\\n\",\n      \"#8319: 97.51%\\n\",\n      \"#8320: 97.51%\\n\",\n      \"#8321: 97.51%\\n\",\n      \"#8322: 97.50%\\n\",\n      \"#8323: 97.50%\\n\",\n      \"#8324: 97.50%\\n\",\n      \"#8325: 97.49%\\n\",\n      \"#8326: 97.49%\\n\",\n      \"#8327: 97.49%\\n\",\n      \"#8328: 97.49%\\n\",\n      \"#8329: 97.49%\\n\",\n      \"#8330: 97.49%\\n\",\n      \"#8331: 97.49%\\n\",\n      \"#8332: 97.49%\\n\",\n      \"#8333: 97.49%\\n\",\n      \"#8334: 97.49%\\n\",\n      \"#8335: 97.49%\\n\",\n      \"#8336: 97.49%\\n\",\n      \"#8337: 97.49%\\n\",\n      \"#8338: 97.49%\\n\",\n      \"#8339: 97.49%\\n\",\n      \"#8340: 97.49%\\n\",\n      \"#8341: 97.49%\\n\",\n      \"#8342: 97.49%\\n\",\n      \"#8343: 97.50%\\n\",\n      \"#8344: 97.50%\\n\",\n      \"#8345: 97.50%\\n\",\n      \"#8346: 97.50%\\n\",\n      \"#8347: 97.50%\\n\",\n      \"#8348: 97.50%\\n\",\n      \"#8349: 97.50%\\n\",\n      \"#8350: 97.50%\\n\",\n      \"#8351: 97.50%\\n\",\n      \"#8352: 97.50%\\n\",\n      \"#8353: 97.49%\\n\",\n      \"#8354: 97.49%\\n\",\n      \"#8355: 97.49%\\n\",\n      \"#8356: 97.49%\\n\",\n      \"#8357: 97.49%\\n\",\n      \"#8358: 97.49%\\n\",\n      \"#8359: 97.49%\\n\",\n      \"#8360: 97.49%\\n\",\n      \"#8361: 97.49%\\n\",\n      \"#8362: 97.49%\\n\",\n      \"#8363: 97.49%\\n\",\n      \"#8364: 97.49%\\n\",\n      \"#8365: 97.49%\\n\",\n      \"#8366: 97.49%\\n\",\n      \"#8367: 97.49%\\n\",\n      \"#8368: 97.49%\\n\",\n      \"#8369: 97.49%\\n\",\n      \"#8370: 97.49%\\n\",\n      \"#8371: 97.49%\\n\",\n      \"#8372: 97.49%\\n\",\n      \"#8373: 97.49%\\n\",\n      \"#8374: 97.49%\\n\",\n      \"#8375: 97.48%\\n\",\n      \"#8376: 97.48%\\n\",\n      \"#8377: 97.48%\\n\",\n      \"#8378: 97.48%\\n\",\n      \"#8379: 97.48%\\n\",\n      \"#8380: 97.48%\\n\",\n      \"#8381: 97.48%\\n\",\n      \"#8382: 97.48%\\n\",\n      \"#8383: 97.48%\\n\",\n      \"#8384: 97.48%\\n\",\n      \"#8385: 97.48%\\n\",\n      \"#8386: 97.48%\\n\",\n      \"#8387: 97.48%\\n\",\n      \"#8388: 97.48%\\n\",\n      \"#8389: 97.49%\\n\",\n      \"#8390: 97.49%\\n\",\n      \"#8391: 97.49%\\n\",\n      \"#8392: 97.49%\\n\",\n      \"#8393: 97.49%\\n\",\n      \"#8394: 97.49%\\n\",\n      \"#8395: 97.49%\\n\",\n      \"#8396: 97.49%\\n\",\n      \"#8397: 97.49%\\n\",\n      \"#8398: 97.49%\\n\",\n      \"#8399: 97.49%\\n\",\n      \"#8400: 97.49%\\n\",\n      \"#8401: 97.49%\\n\",\n      \"#8402: 97.49%\\n\",\n      \"#8403: 97.49%\\n\",\n      \"#8404: 97.49%\\n\",\n      \"#8405: 97.49%\\n\",\n      \"#8406: 97.49%\\n\",\n      \"#8407: 97.49%\\n\",\n      \"#8408: 97.48%\\n\",\n      \"#8409: 97.48%\\n\",\n      \"#8410: 97.47%\\n\",\n      \"#8411: 97.47%\\n\",\n      \"#8412: 97.47%\\n\",\n      \"#8413: 97.47%\\n\",\n      \"#8414: 97.47%\\n\",\n      \"#8415: 97.47%\\n\",\n      \"#8416: 97.47%\\n\",\n      \"#8417: 97.47%\\n\",\n      \"#8418: 97.47%\\n\",\n      \"#8419: 97.47%\\n\",\n      \"#8420: 97.47%\\n\",\n      \"#8421: 97.47%\\n\",\n      \"#8422: 97.47%\\n\",\n      \"#8423: 97.47%\\n\",\n      \"#8424: 97.47%\\n\",\n      \"#8425: 97.47%\\n\",\n      \"#8426: 97.47%\\n\",\n      \"#8427: 97.47%\\n\",\n      \"#8428: 97.47%\\n\",\n      \"#8429: 97.47%\\n\",\n      \"#8430: 97.47%\\n\",\n      \"#8431: 97.47%\\n\",\n      \"#8432: 97.47%\\n\",\n      \"#8433: 97.47%\\n\",\n      \"#8434: 97.47%\\n\",\n      \"#8435: 97.48%\\n\",\n      \"#8436: 97.48%\\n\",\n      \"#8437: 97.48%\\n\",\n      \"#8438: 97.48%\\n\",\n      \"#8439: 97.48%\\n\",\n      \"#8440: 97.48%\\n\",\n      \"#8441: 97.48%\\n\",\n      \"#8442: 97.48%\\n\",\n      \"#8443: 97.48%\\n\",\n      \"#8444: 97.48%\\n\",\n      \"#8445: 97.48%\\n\",\n      \"#8446: 97.48%\\n\",\n      \"#8447: 97.48%\\n\",\n      \"#8448: 97.48%\\n\",\n      \"#8449: 97.48%\\n\",\n      \"#8450: 97.48%\\n\",\n      \"#8451: 97.48%\\n\",\n      \"#8452: 97.48%\\n\",\n      \"#8453: 97.48%\\n\",\n      \"#8454: 97.48%\\n\",\n      \"#8455: 97.48%\\n\",\n      \"#8456: 97.48%\\n\",\n      \"#8457: 97.48%\\n\",\n      \"#8458: 97.48%\\n\",\n      \"#8459: 97.48%\\n\",\n      \"#8460: 97.48%\\n\",\n      \"#8461: 97.48%\\n\",\n      \"#8462: 97.48%\\n\",\n      \"#8463: 97.48%\\n\",\n      \"#8464: 97.48%\\n\",\n      \"#8465: 97.48%\\n\",\n      \"#8466: 97.48%\\n\",\n      \"#8467: 97.48%\\n\",\n      \"#8468: 97.48%\\n\",\n      \"#8469: 97.49%\\n\",\n      \"#8470: 97.49%\\n\",\n      \"#8471: 97.49%\\n\",\n      \"#8472: 97.49%\\n\",\n      \"#8473: 97.49%\\n\",\n      \"#8474: 97.49%\\n\",\n      \"#8475: 97.49%\\n\",\n      \"#8476: 97.49%\\n\",\n      \"#8477: 97.49%\\n\",\n      \"#8478: 97.49%\\n\",\n      \"#8479: 97.49%\\n\",\n      \"#8480: 97.49%\\n\",\n      \"#8481: 97.49%\\n\",\n      \"#8482: 97.49%\\n\",\n      \"#8483: 97.49%\\n\",\n      \"#8484: 97.49%\\n\",\n      \"#8485: 97.49%\\n\",\n      \"#8486: 97.49%\\n\",\n      \"#8487: 97.49%\\n\",\n      \"#8488: 97.49%\\n\",\n      \"#8489: 97.49%\\n\",\n      \"#8490: 97.49%\\n\",\n      \"#8491: 97.49%\\n\",\n      \"#8492: 97.49%\\n\",\n      \"#8493: 97.49%\\n\",\n      \"#8494: 97.49%\\n\",\n      \"#8495: 97.49%\\n\",\n      \"#8496: 97.49%\\n\",\n      \"#8497: 97.49%\\n\",\n      \"#8498: 97.49%\\n\",\n      \"#8499: 97.49%\\n\",\n      \"#8500: 97.49%\\n\",\n      \"#8501: 97.49%\\n\",\n      \"#8502: 97.50%\\n\",\n      \"#8503: 97.50%\\n\",\n      \"#8504: 97.50%\\n\",\n      \"#8505: 97.50%\\n\",\n      \"#8506: 97.50%\\n\",\n      \"#8507: 97.50%\\n\",\n      \"#8508: 97.50%\\n\",\n      \"#8509: 97.50%\\n\",\n      \"#8510: 97.50%\\n\",\n      \"#8511: 97.50%\\n\",\n      \"#8512: 97.50%\\n\",\n      \"#8513: 97.50%\\n\",\n      \"#8514: 97.50%\\n\",\n      \"#8515: 97.50%\\n\",\n      \"#8516: 97.50%\\n\",\n      \"#8517: 97.50%\\n\",\n      \"#8518: 97.50%\\n\",\n      \"#8519: 97.50%\\n\",\n      \"#8520: 97.50%\\n\",\n      \"#8521: 97.50%\\n\",\n      \"#8522: 97.49%\\n\",\n      \"#8523: 97.49%\\n\",\n      \"#8524: 97.49%\\n\",\n      \"#8525: 97.49%\\n\",\n      \"#8526: 97.49%\\n\",\n      \"#8527: 97.49%\\n\",\n      \"#8528: 97.49%\\n\",\n      \"#8529: 97.49%\\n\",\n      \"#8530: 97.49%\\n\",\n      \"#8531: 97.49%\\n\",\n      \"#8532: 97.49%\\n\",\n      \"#8533: 97.49%\\n\",\n      \"#8534: 97.49%\\n\",\n      \"#8535: 97.49%\\n\",\n      \"#8536: 97.49%\\n\",\n      \"#8537: 97.49%\\n\",\n      \"#8538: 97.49%\\n\",\n      \"#8539: 97.49%\\n\",\n      \"#8540: 97.49%\\n\",\n      \"#8541: 97.49%\\n\",\n      \"#8542: 97.50%\\n\",\n      \"#8543: 97.50%\\n\",\n      \"#8544: 97.50%\\n\",\n      \"#8545: 97.50%\\n\",\n      \"#8546: 97.50%\\n\",\n      \"#8547: 97.50%\\n\",\n      \"#8548: 97.50%\\n\",\n      \"#8549: 97.50%\\n\",\n      \"#8550: 97.50%\\n\",\n      \"#8551: 97.50%\\n\",\n      \"#8552: 97.50%\\n\",\n      \"#8553: 97.50%\\n\",\n      \"#8554: 97.50%\\n\",\n      \"#8555: 97.50%\\n\",\n      \"#8556: 97.50%\\n\",\n      \"#8557: 97.50%\\n\",\n      \"#8558: 97.50%\\n\",\n      \"#8559: 97.50%\\n\",\n      \"#8560: 97.50%\\n\",\n      \"#8561: 97.50%\\n\",\n      \"#8562: 97.50%\\n\",\n      \"#8563: 97.50%\\n\",\n      \"#8564: 97.50%\\n\",\n      \"#8565: 97.50%\\n\",\n      \"#8566: 97.50%\\n\",\n      \"#8567: 97.50%\\n\",\n      \"#8568: 97.50%\\n\",\n      \"#8569: 97.50%\\n\",\n      \"#8570: 97.50%\\n\",\n      \"#8571: 97.50%\\n\",\n      \"#8572: 97.50%\\n\",\n      \"#8573: 97.50%\\n\",\n      \"#8574: 97.50%\\n\",\n      \"#8575: 97.50%\\n\",\n      \"#8576: 97.50%\\n\",\n      \"#8577: 97.51%\\n\",\n      \"#8578: 97.51%\\n\",\n      \"#8579: 97.51%\\n\",\n      \"#8580: 97.51%\\n\",\n      \"#8581: 97.51%\\n\",\n      \"#8582: 97.51%\\n\",\n      \"#8583: 97.51%\\n\",\n      \"#8584: 97.51%\\n\",\n      \"#8585: 97.51%\\n\",\n      \"#8586: 97.51%\\n\",\n      \"#8587: 97.51%\\n\",\n      \"#8588: 97.51%\\n\",\n      \"#8589: 97.51%\\n\",\n      \"#8590: 97.51%\\n\",\n      \"#8591: 97.51%\\n\",\n      \"#8592: 97.51%\\n\",\n      \"#8593: 97.51%\\n\",\n      \"#8594: 97.51%\\n\",\n      \"#8595: 97.51%\\n\",\n      \"#8596: 97.51%\\n\",\n      \"#8597: 97.51%\\n\",\n      \"#8598: 97.51%\\n\",\n      \"#8599: 97.51%\\n\",\n      \"#8600: 97.51%\\n\",\n      \"#8601: 97.51%\\n\",\n      \"#8602: 97.51%\\n\",\n      \"#8603: 97.51%\\n\",\n      \"#8604: 97.51%\\n\",\n      \"#8605: 97.51%\\n\",\n      \"#8606: 97.51%\\n\",\n      \"#8607: 97.51%\\n\",\n      \"#8608: 97.51%\\n\",\n      \"#8609: 97.51%\\n\",\n      \"#8610: 97.51%\\n\",\n      \"#8611: 97.52%\\n\",\n      \"#8612: 97.52%\\n\",\n      \"#8613: 97.52%\\n\",\n      \"#8614: 97.52%\\n\",\n      \"#8615: 97.52%\\n\",\n      \"#8616: 97.52%\\n\",\n      \"#8617: 97.52%\\n\",\n      \"#8618: 97.52%\\n\",\n      \"#8619: 97.52%\\n\",\n      \"#8620: 97.52%\\n\",\n      \"#8621: 97.52%\\n\",\n      \"#8622: 97.52%\\n\",\n      \"#8623: 97.52%\\n\",\n      \"#8624: 97.52%\\n\",\n      \"#8625: 97.52%\\n\",\n      \"#8626: 97.52%\\n\",\n      \"#8627: 97.52%\\n\",\n      \"#8628: 97.52%\\n\",\n      \"#8629: 97.52%\\n\",\n      \"#8630: 97.52%\\n\",\n      \"#8631: 97.52%\\n\",\n      \"#8632: 97.52%\\n\",\n      \"#8633: 97.52%\\n\",\n      \"#8634: 97.52%\\n\",\n      \"#8635: 97.52%\\n\",\n      \"#8636: 97.52%\\n\",\n      \"#8637: 97.52%\\n\",\n      \"#8638: 97.52%\\n\",\n      \"#8639: 97.52%\\n\",\n      \"#8640: 97.52%\\n\",\n      \"#8641: 97.52%\\n\",\n      \"#8642: 97.52%\\n\",\n      \"#8643: 97.52%\\n\",\n      \"#8644: 97.52%\\n\",\n      \"#8645: 97.52%\\n\",\n      \"#8646: 97.53%\\n\",\n      \"#8647: 97.53%\\n\",\n      \"#8648: 97.53%\\n\",\n      \"#8649: 97.53%\\n\",\n      \"#8650: 97.53%\\n\",\n      \"#8651: 97.53%\\n\",\n      \"#8652: 97.53%\\n\",\n      \"#8653: 97.53%\\n\",\n      \"#8654: 97.53%\\n\",\n      \"#8655: 97.53%\\n\",\n      \"#8656: 97.53%\\n\",\n      \"#8657: 97.53%\\n\",\n      \"#8658: 97.53%\\n\",\n      \"#8659: 97.53%\\n\",\n      \"#8660: 97.53%\\n\",\n      \"#8661: 97.53%\\n\",\n      \"#8662: 97.53%\\n\",\n      \"#8663: 97.53%\\n\",\n      \"#8664: 97.53%\\n\",\n      \"#8665: 97.53%\\n\",\n      \"#8666: 97.53%\\n\",\n      \"#8667: 97.53%\\n\",\n      \"#8668: 97.53%\\n\",\n      \"#8669: 97.53%\\n\",\n      \"#8670: 97.53%\\n\",\n      \"#8671: 97.53%\\n\",\n      \"#8672: 97.53%\\n\",\n      \"#8673: 97.53%\\n\",\n      \"#8674: 97.53%\\n\",\n      \"#8675: 97.53%\\n\",\n      \"#8676: 97.53%\\n\",\n      \"#8677: 97.53%\\n\",\n      \"#8678: 97.53%\\n\",\n      \"#8679: 97.53%\\n\",\n      \"#8680: 97.53%\\n\",\n      \"#8681: 97.54%\\n\",\n      \"#8682: 97.54%\\n\",\n      \"#8683: 97.54%\\n\",\n      \"#8684: 97.54%\\n\",\n      \"#8685: 97.54%\\n\",\n      \"#8686: 97.54%\\n\",\n      \"#8687: 97.54%\\n\",\n      \"#8688: 97.54%\\n\",\n      \"#8689: 97.54%\\n\",\n      \"#8690: 97.54%\\n\",\n      \"#8691: 97.54%\\n\",\n      \"#8692: 97.54%\\n\",\n      \"#8693: 97.54%\\n\",\n      \"#8694: 97.54%\\n\",\n      \"#8695: 97.54%\\n\",\n      \"#8696: 97.54%\\n\",\n      \"#8697: 97.54%\\n\",\n      \"#8698: 97.54%\\n\",\n      \"#8699: 97.54%\\n\",\n      \"#8700: 97.54%\\n\",\n      \"#8701: 97.54%\\n\",\n      \"#8702: 97.54%\\n\",\n      \"#8703: 97.54%\\n\",\n      \"#8704: 97.54%\\n\",\n      \"#8705: 97.54%\\n\",\n      \"#8706: 97.54%\\n\",\n      \"#8707: 97.54%\\n\",\n      \"#8708: 97.54%\\n\",\n      \"#8709: 97.54%\\n\",\n      \"#8710: 97.54%\\n\",\n      \"#8711: 97.54%\\n\",\n      \"#8712: 97.54%\\n\",\n      \"#8713: 97.54%\\n\",\n      \"#8714: 97.54%\\n\",\n      \"#8715: 97.54%\\n\",\n      \"#8716: 97.55%\\n\",\n      \"#8717: 97.55%\\n\",\n      \"#8718: 97.55%\\n\",\n      \"#8719: 97.55%\\n\",\n      \"#8720: 97.55%\\n\",\n      \"#8721: 97.55%\\n\",\n      \"#8722: 97.55%\\n\",\n      \"#8723: 97.55%\\n\",\n      \"#8724: 97.55%\\n\",\n      \"#8725: 97.55%\\n\",\n      \"#8726: 97.55%\\n\",\n      \"#8727: 97.55%\\n\",\n      \"#8728: 97.55%\\n\",\n      \"#8729: 97.55%\\n\",\n      \"#8730: 97.55%\\n\",\n      \"#8731: 97.55%\\n\",\n      \"#8732: 97.55%\\n\",\n      \"#8733: 97.55%\\n\",\n      \"#8734: 97.55%\\n\",\n      \"#8735: 97.55%\\n\",\n      \"#8736: 97.55%\\n\",\n      \"#8737: 97.55%\\n\",\n      \"#8738: 97.55%\\n\",\n      \"#8739: 97.55%\\n\",\n      \"#8740: 97.55%\\n\",\n      \"#8741: 97.55%\\n\",\n      \"#8742: 97.55%\\n\",\n      \"#8743: 97.55%\\n\",\n      \"#8744: 97.55%\\n\",\n      \"#8745: 97.55%\\n\",\n      \"#8746: 97.55%\\n\",\n      \"#8747: 97.55%\\n\",\n      \"#8748: 97.55%\\n\",\n      \"#8749: 97.55%\\n\",\n      \"#8750: 97.55%\\n\",\n      \"#8751: 97.55%\\n\",\n      \"#8752: 97.56%\\n\",\n      \"#8753: 97.56%\\n\",\n      \"#8754: 97.56%\\n\",\n      \"#8755: 97.56%\\n\",\n      \"#8756: 97.56%\\n\",\n      \"#8757: 97.56%\\n\",\n      \"#8758: 97.56%\\n\",\n      \"#8759: 97.56%\\n\",\n      \"#8760: 97.56%\\n\",\n      \"#8761: 97.56%\\n\",\n      \"#8762: 97.56%\\n\",\n      \"#8763: 97.56%\\n\",\n      \"#8764: 97.56%\\n\",\n      \"#8765: 97.56%\\n\",\n      \"#8766: 97.56%\\n\",\n      \"#8767: 97.56%\\n\",\n      \"#8768: 97.56%\\n\",\n      \"#8769: 97.56%\\n\",\n      \"#8770: 97.56%\\n\",\n      \"#8771: 97.56%\\n\",\n      \"#8772: 97.56%\\n\",\n      \"#8773: 97.56%\\n\",\n      \"#8774: 97.56%\\n\",\n      \"#8775: 97.56%\\n\",\n      \"#8776: 97.56%\\n\",\n      \"#8777: 97.56%\\n\",\n      \"#8778: 97.56%\\n\",\n      \"#8779: 97.56%\\n\",\n      \"#8780: 97.56%\\n\",\n      \"#8781: 97.56%\\n\",\n      \"#8782: 97.56%\\n\",\n      \"#8783: 97.56%\\n\",\n      \"#8784: 97.56%\\n\",\n      \"#8785: 97.56%\\n\",\n      \"#8786: 97.56%\\n\",\n      \"#8787: 97.56%\\n\",\n      \"#8788: 97.57%\\n\",\n      \"#8789: 97.57%\\n\",\n      \"#8790: 97.57%\\n\",\n      \"#8791: 97.57%\\n\",\n      \"#8792: 97.57%\\n\",\n      \"#8793: 97.57%\\n\",\n      \"#8794: 97.57%\\n\",\n      \"#8795: 97.57%\\n\",\n      \"#8796: 97.57%\\n\",\n      \"#8797: 97.57%\\n\",\n      \"#8798: 97.57%\\n\",\n      \"#8799: 97.57%\\n\",\n      \"#8800: 97.57%\\n\",\n      \"#8801: 97.57%\\n\",\n      \"#8802: 97.57%\\n\",\n      \"#8803: 97.57%\\n\",\n      \"#8804: 97.57%\\n\",\n      \"#8805: 97.57%\\n\",\n      \"#8806: 97.57%\\n\",\n      \"#8807: 97.57%\\n\",\n      \"#8808: 97.57%\\n\",\n      \"#8809: 97.57%\\n\",\n      \"#8810: 97.57%\\n\",\n      \"#8811: 97.57%\\n\",\n      \"#8812: 97.57%\\n\",\n      \"#8813: 97.57%\\n\",\n      \"#8814: 97.57%\\n\",\n      \"#8815: 97.57%\\n\",\n      \"#8816: 97.57%\\n\",\n      \"#8817: 97.57%\\n\",\n      \"#8818: 97.57%\\n\",\n      \"#8819: 97.57%\\n\",\n      \"#8820: 97.57%\\n\",\n      \"#8821: 97.57%\\n\",\n      \"#8822: 97.57%\\n\",\n      \"#8823: 97.57%\\n\",\n      \"#8824: 97.58%\\n\",\n      \"#8825: 97.58%\\n\",\n      \"#8826: 97.58%\\n\",\n      \"#8827: 97.58%\\n\",\n      \"#8828: 97.58%\\n\",\n      \"#8829: 97.58%\\n\",\n      \"#8830: 97.58%\\n\",\n      \"#8831: 97.58%\\n\",\n      \"#8832: 97.58%\\n\",\n      \"#8833: 97.58%\\n\",\n      \"#8834: 97.58%\\n\",\n      \"#8835: 97.58%\\n\",\n      \"#8836: 97.58%\\n\",\n      \"#8837: 97.58%\\n\",\n      \"#8838: 97.58%\\n\",\n      \"#8839: 97.58%\\n\",\n      \"#8840: 97.58%\\n\",\n      \"#8841: 97.58%\\n\",\n      \"#8842: 97.58%\\n\",\n      \"#8843: 97.58%\\n\",\n      \"#8844: 97.58%\\n\",\n      \"#8845: 97.58%\\n\",\n      \"#8846: 97.58%\\n\",\n      \"#8847: 97.58%\\n\",\n      \"#8848: 97.58%\\n\",\n      \"#8849: 97.58%\\n\",\n      \"#8850: 97.58%\\n\",\n      \"#8851: 97.58%\\n\",\n      \"#8852: 97.58%\\n\",\n      \"#8853: 97.58%\\n\",\n      \"#8854: 97.58%\\n\",\n      \"#8855: 97.58%\\n\",\n      \"#8856: 97.58%\\n\",\n      \"#8857: 97.58%\\n\",\n      \"#8858: 97.58%\\n\",\n      \"#8859: 97.58%\\n\",\n      \"#8860: 97.58%\\n\",\n      \"#8861: 97.59%\\n\",\n      \"#8862: 97.59%\\n\",\n      \"#8863: 97.59%\\n\",\n      \"#8864: 97.59%\\n\",\n      \"#8865: 97.59%\\n\",\n      \"#8866: 97.59%\\n\",\n      \"#8867: 97.59%\\n\",\n      \"#8868: 97.59%\\n\",\n      \"#8869: 97.59%\\n\",\n      \"#8870: 97.59%\\n\",\n      \"#8871: 97.59%\\n\",\n      \"#8872: 97.59%\\n\",\n      \"#8873: 97.59%\\n\",\n      \"#8874: 97.59%\\n\",\n      \"#8875: 97.59%\\n\",\n      \"#8876: 97.59%\\n\",\n      \"#8877: 97.59%\\n\",\n      \"#8878: 97.59%\\n\",\n      \"#8879: 97.59%\\n\",\n      \"#8880: 97.59%\\n\",\n      \"#8881: 97.59%\\n\",\n      \"#8882: 97.59%\\n\",\n      \"#8883: 97.59%\\n\",\n      \"#8884: 97.59%\\n\",\n      \"#8885: 97.59%\\n\",\n      \"#8886: 97.59%\\n\",\n      \"#8887: 97.59%\\n\",\n      \"#8888: 97.59%\\n\",\n      \"#8889: 97.59%\\n\",\n      \"#8890: 97.59%\\n\",\n      \"#8891: 97.59%\\n\",\n      \"#8892: 97.59%\\n\",\n      \"#8893: 97.59%\\n\",\n      \"#8894: 97.59%\\n\",\n      \"#8895: 97.59%\\n\",\n      \"#8896: 97.59%\\n\",\n      \"#8897: 97.59%\\n\",\n      \"#8898: 97.60%\\n\",\n      \"#8899: 97.60%\\n\",\n      \"#8900: 97.60%\\n\",\n      \"#8901: 97.60%\\n\",\n      \"#8902: 97.60%\\n\",\n      \"#8903: 97.60%\\n\",\n      \"#8904: 97.60%\\n\",\n      \"#8905: 97.60%\\n\",\n      \"#8906: 97.60%\\n\",\n      \"#8907: 97.60%\\n\",\n      \"#8908: 97.60%\\n\",\n      \"#8909: 97.60%\\n\",\n      \"#8910: 97.60%\\n\",\n      \"#8911: 97.60%\\n\",\n      \"#8912: 97.60%\\n\",\n      \"#8913: 97.60%\\n\",\n      \"#8914: 97.60%\\n\",\n      \"#8915: 97.60%\\n\",\n      \"#8916: 97.60%\\n\",\n      \"#8917: 97.60%\\n\",\n      \"#8918: 97.60%\\n\",\n      \"#8919: 97.60%\\n\",\n      \"#8920: 97.60%\\n\",\n      \"#8921: 97.60%\\n\",\n      \"#8922: 97.60%\\n\",\n      \"#8923: 97.60%\\n\",\n      \"#8924: 97.60%\\n\",\n      \"#8925: 97.60%\\n\",\n      \"#8926: 97.60%\\n\",\n      \"#8927: 97.60%\\n\",\n      \"#8928: 97.60%\\n\",\n      \"#8929: 97.60%\\n\",\n      \"#8930: 97.60%\\n\",\n      \"#8931: 97.60%\\n\",\n      \"#8932: 97.60%\\n\",\n      \"#8933: 97.60%\\n\",\n      \"#8934: 97.60%\\n\",\n      \"#8935: 97.61%\\n\",\n      \"#8936: 97.61%\\n\",\n      \"#8937: 97.61%\\n\",\n      \"#8938: 97.61%\\n\",\n      \"#8939: 97.61%\\n\",\n      \"#8940: 97.61%\\n\",\n      \"#8941: 97.61%\\n\",\n      \"#8942: 97.61%\\n\",\n      \"#8943: 97.61%\\n\",\n      \"#8944: 97.61%\\n\",\n      \"#8945: 97.61%\\n\",\n      \"#8946: 97.61%\\n\",\n      \"#8947: 97.61%\\n\",\n      \"#8948: 97.61%\\n\",\n      \"#8949: 97.61%\\n\",\n      \"#8950: 97.61%\\n\",\n      \"#8951: 97.61%\\n\",\n      \"#8952: 97.61%\\n\",\n      \"#8953: 97.61%\\n\",\n      \"#8954: 97.61%\\n\",\n      \"#8955: 97.61%\\n\",\n      \"#8956: 97.61%\\n\",\n      \"#8957: 97.61%\\n\",\n      \"#8958: 97.61%\\n\",\n      \"#8959: 97.61%\\n\",\n      \"#8960: 97.61%\\n\",\n      \"#8961: 97.61%\\n\",\n      \"#8962: 97.61%\\n\",\n      \"#8963: 97.61%\\n\",\n      \"#8964: 97.61%\\n\",\n      \"#8965: 97.61%\\n\",\n      \"#8966: 97.61%\\n\",\n      \"#8967: 97.61%\\n\",\n      \"#8968: 97.61%\\n\",\n      \"#8969: 97.61%\\n\",\n      \"#8970: 97.61%\\n\",\n      \"#8971: 97.61%\\n\",\n      \"#8972: 97.62%\\n\",\n      \"#8973: 97.62%\\n\",\n      \"#8974: 97.62%\\n\",\n      \"#8975: 97.62%\\n\",\n      \"#8976: 97.62%\\n\",\n      \"#8977: 97.62%\\n\",\n      \"#8978: 97.62%\\n\",\n      \"#8979: 97.62%\\n\",\n      \"#8980: 97.62%\\n\",\n      \"#8981: 97.62%\\n\",\n      \"#8982: 97.62%\\n\",\n      \"#8983: 97.62%\\n\",\n      \"#8984: 97.62%\\n\",\n      \"#8985: 97.62%\\n\",\n      \"#8986: 97.62%\\n\",\n      \"#8987: 97.62%\\n\",\n      \"#8988: 97.62%\\n\",\n      \"#8989: 97.62%\\n\",\n      \"#8990: 97.62%\\n\",\n      \"#8991: 97.62%\\n\",\n      \"#8992: 97.62%\\n\",\n      \"#8993: 97.62%\\n\",\n      \"#8994: 97.62%\\n\",\n      \"#8995: 97.62%\\n\",\n      \"#8996: 97.62%\\n\",\n      \"#8997: 97.62%\\n\",\n      \"#8998: 97.62%\\n\",\n      \"#8999: 97.62%\\n\",\n      \"#9000: 97.62%\\n\",\n      \"#9001: 97.62%\\n\",\n      \"#9002: 97.62%\\n\",\n      \"#9003: 97.62%\\n\",\n      \"#9004: 97.62%\\n\",\n      \"#9005: 97.62%\\n\",\n      \"#9006: 97.62%\\n\",\n      \"#9007: 97.62%\\n\",\n      \"#9008: 97.62%\\n\",\n      \"#9009: 97.61%\\n\",\n      \"#9010: 97.61%\\n\",\n      \"#9011: 97.61%\\n\",\n      \"#9012: 97.61%\\n\",\n      \"#9013: 97.61%\\n\",\n      \"#9014: 97.62%\\n\",\n      \"#9015: 97.60%\\n\",\n      \"#9016: 97.60%\\n\",\n      \"#9017: 97.60%\\n\",\n      \"#9018: 97.61%\\n\",\n      \"#9019: 97.59%\\n\",\n      \"#9020: 97.59%\\n\",\n      \"#9021: 97.59%\\n\",\n      \"#9022: 97.60%\\n\",\n      \"#9023: 97.60%\\n\",\n      \"#9024: 97.58%\\n\",\n      \"#9025: 97.58%\\n\",\n      \"#9026: 97.59%\\n\",\n      \"#9027: 97.59%\\n\",\n      \"#9028: 97.59%\\n\",\n      \"#9029: 97.59%\\n\",\n      \"#9030: 97.59%\\n\",\n      \"#9031: 97.59%\\n\",\n      \"#9032: 97.59%\\n\",\n      \"#9033: 97.59%\\n\",\n      \"#9034: 97.59%\\n\",\n      \"#9035: 97.59%\\n\",\n      \"#9036: 97.58%\\n\",\n      \"#9037: 97.58%\\n\",\n      \"#9038: 97.58%\\n\",\n      \"#9039: 97.58%\\n\",\n      \"#9040: 97.58%\\n\",\n      \"#9041: 97.58%\\n\",\n      \"#9042: 97.58%\\n\",\n      \"#9043: 97.58%\\n\",\n      \"#9044: 97.58%\\n\",\n      \"#9045: 97.58%\\n\",\n      \"#9046: 97.58%\\n\",\n      \"#9047: 97.58%\\n\",\n      \"#9048: 97.58%\\n\",\n      \"#9049: 97.58%\\n\",\n      \"#9050: 97.58%\\n\",\n      \"#9051: 97.58%\\n\",\n      \"#9052: 97.58%\\n\",\n      \"#9053: 97.58%\\n\",\n      \"#9054: 97.58%\\n\",\n      \"#9055: 97.58%\\n\",\n      \"#9056: 97.58%\\n\",\n      \"#9057: 97.58%\\n\",\n      \"#9058: 97.58%\\n\",\n      \"#9059: 97.58%\\n\",\n      \"#9060: 97.58%\\n\",\n      \"#9061: 97.58%\\n\",\n      \"#9062: 97.58%\\n\",\n      \"#9063: 97.58%\\n\",\n      \"#9064: 97.58%\\n\",\n      \"#9065: 97.58%\\n\",\n      \"#9066: 97.58%\\n\",\n      \"#9067: 97.58%\\n\",\n      \"#9068: 97.59%\\n\",\n      \"#9069: 97.59%\\n\",\n      \"#9070: 97.59%\\n\",\n      \"#9071: 97.57%\\n\",\n      \"#9072: 97.58%\\n\",\n      \"#9073: 97.58%\\n\",\n      \"#9074: 97.58%\\n\",\n      \"#9075: 97.58%\\n\",\n      \"#9076: 97.58%\\n\",\n      \"#9077: 97.58%\\n\",\n      \"#9078: 97.58%\\n\",\n      \"#9079: 97.58%\\n\",\n      \"#9080: 97.58%\\n\",\n      \"#9081: 97.58%\\n\",\n      \"#9082: 97.58%\\n\",\n      \"#9083: 97.58%\\n\",\n      \"#9084: 97.58%\\n\",\n      \"#9085: 97.58%\\n\",\n      \"#9086: 97.58%\\n\",\n      \"#9087: 97.58%\\n\",\n      \"#9088: 97.58%\\n\",\n      \"#9089: 97.58%\\n\",\n      \"#9090: 97.58%\\n\",\n      \"#9091: 97.58%\\n\",\n      \"#9092: 97.58%\\n\",\n      \"#9093: 97.58%\\n\",\n      \"#9094: 97.58%\\n\",\n      \"#9095: 97.58%\\n\",\n      \"#9096: 97.58%\\n\",\n      \"#9097: 97.58%\\n\",\n      \"#9098: 97.58%\\n\",\n      \"#9099: 97.58%\\n\",\n      \"#9100: 97.58%\\n\",\n      \"#9101: 97.58%\\n\",\n      \"#9102: 97.58%\\n\",\n      \"#9103: 97.58%\\n\",\n      \"#9104: 97.58%\\n\",\n      \"#9105: 97.58%\\n\",\n      \"#9106: 97.58%\\n\",\n      \"#9107: 97.58%\\n\",\n      \"#9108: 97.58%\\n\",\n      \"#9109: 97.59%\\n\",\n      \"#9110: 97.59%\\n\",\n      \"#9111: 97.59%\\n\",\n      \"#9112: 97.59%\\n\",\n      \"#9113: 97.59%\\n\",\n      \"#9114: 97.59%\\n\",\n      \"#9115: 97.59%\\n\",\n      \"#9116: 97.59%\\n\",\n      \"#9117: 97.59%\\n\",\n      \"#9118: 97.59%\\n\",\n      \"#9119: 97.59%\\n\",\n      \"#9120: 97.59%\\n\",\n      \"#9121: 97.59%\\n\",\n      \"#9122: 97.59%\\n\",\n      \"#9123: 97.59%\\n\",\n      \"#9124: 97.59%\\n\",\n      \"#9125: 97.59%\\n\",\n      \"#9126: 97.59%\\n\",\n      \"#9127: 97.59%\\n\",\n      \"#9128: 97.59%\\n\",\n      \"#9129: 97.59%\\n\",\n      \"#9130: 97.59%\\n\",\n      \"#9131: 97.59%\\n\",\n      \"#9132: 97.59%\\n\",\n      \"#9133: 97.59%\\n\",\n      \"#9134: 97.59%\\n\",\n      \"#9135: 97.59%\\n\",\n      \"#9136: 97.59%\\n\",\n      \"#9137: 97.59%\\n\",\n      \"#9138: 97.59%\\n\",\n      \"#9139: 97.59%\\n\",\n      \"#9140: 97.59%\\n\",\n      \"#9141: 97.59%\\n\",\n      \"#9142: 97.59%\\n\",\n      \"#9143: 97.59%\\n\",\n      \"#9144: 97.59%\\n\",\n      \"#9145: 97.59%\\n\",\n      \"#9146: 97.59%\\n\",\n      \"#9147: 97.60%\\n\",\n      \"#9148: 97.60%\\n\",\n      \"#9149: 97.60%\\n\",\n      \"#9150: 97.60%\\n\",\n      \"#9151: 97.60%\\n\",\n      \"#9152: 97.60%\\n\",\n      \"#9153: 97.60%\\n\",\n      \"#9154: 97.60%\\n\",\n      \"#9155: 97.60%\\n\",\n      \"#9156: 97.60%\\n\",\n      \"#9157: 97.60%\\n\",\n      \"#9158: 97.60%\\n\",\n      \"#9159: 97.60%\\n\",\n      \"#9160: 97.60%\\n\",\n      \"#9161: 97.60%\\n\",\n      \"#9162: 97.60%\\n\",\n      \"#9163: 97.60%\\n\",\n      \"#9164: 97.60%\\n\",\n      \"#9165: 97.60%\\n\",\n      \"#9166: 97.60%\\n\",\n      \"#9167: 97.60%\\n\",\n      \"#9168: 97.60%\\n\",\n      \"#9169: 97.60%\\n\",\n      \"#9170: 97.60%\\n\",\n      \"#9171: 97.60%\\n\",\n      \"#9172: 97.60%\\n\",\n      \"#9173: 97.60%\\n\",\n      \"#9174: 97.60%\\n\",\n      \"#9175: 97.60%\\n\",\n      \"#9176: 97.60%\\n\",\n      \"#9177: 97.60%\\n\",\n      \"#9178: 97.60%\\n\",\n      \"#9179: 97.60%\\n\",\n      \"#9180: 97.60%\\n\",\n      \"#9181: 97.60%\\n\",\n      \"#9182: 97.60%\\n\",\n      \"#9183: 97.60%\\n\",\n      \"#9184: 97.60%\\n\",\n      \"#9185: 97.61%\\n\",\n      \"#9186: 97.61%\\n\",\n      \"#9187: 97.61%\\n\",\n      \"#9188: 97.61%\\n\",\n      \"#9189: 97.61%\\n\",\n      \"#9190: 97.61%\\n\",\n      \"#9191: 97.61%\\n\",\n      \"#9192: 97.61%\\n\",\n      \"#9193: 97.61%\\n\",\n      \"#9194: 97.61%\\n\",\n      \"#9195: 97.61%\\n\",\n      \"#9196: 97.61%\\n\",\n      \"#9197: 97.61%\\n\",\n      \"#9198: 97.61%\\n\",\n      \"#9199: 97.61%\\n\",\n      \"#9200: 97.61%\\n\",\n      \"#9201: 97.61%\\n\",\n      \"#9202: 97.60%\\n\",\n      \"#9203: 97.60%\\n\",\n      \"#9204: 97.60%\\n\",\n      \"#9205: 97.60%\\n\",\n      \"#9206: 97.60%\\n\",\n      \"#9207: 97.60%\\n\",\n      \"#9208: 97.60%\\n\",\n      \"#9209: 97.60%\\n\",\n      \"#9210: 97.60%\\n\",\n      \"#9211: 97.60%\\n\",\n      \"#9212: 97.60%\\n\",\n      \"#9213: 97.60%\\n\",\n      \"#9214: 97.60%\\n\",\n      \"#9215: 97.60%\\n\",\n      \"#9216: 97.60%\\n\",\n      \"#9217: 97.60%\\n\",\n      \"#9218: 97.60%\\n\",\n      \"#9219: 97.60%\\n\",\n      \"#9220: 97.60%\\n\",\n      \"#9221: 97.60%\\n\",\n      \"#9222: 97.60%\\n\",\n      \"#9223: 97.60%\\n\",\n      \"#9224: 97.60%\\n\",\n      \"#9225: 97.60%\\n\",\n      \"#9226: 97.60%\\n\",\n      \"#9227: 97.61%\\n\",\n      \"#9228: 97.61%\\n\",\n      \"#9229: 97.61%\\n\",\n      \"#9230: 97.61%\\n\",\n      \"#9231: 97.61%\\n\",\n      \"#9232: 97.61%\\n\",\n      \"#9233: 97.61%\\n\",\n      \"#9234: 97.61%\\n\",\n      \"#9235: 97.61%\\n\",\n      \"#9236: 97.61%\\n\",\n      \"#9237: 97.61%\\n\",\n      \"#9238: 97.61%\\n\",\n      \"#9239: 97.61%\\n\",\n      \"#9240: 97.61%\\n\",\n      \"#9241: 97.61%\\n\",\n      \"#9242: 97.61%\\n\",\n      \"#9243: 97.61%\\n\",\n      \"#9244: 97.61%\\n\",\n      \"#9245: 97.61%\\n\",\n      \"#9246: 97.61%\\n\",\n      \"#9247: 97.61%\\n\",\n      \"#9248: 97.61%\\n\",\n      \"#9249: 97.61%\\n\",\n      \"#9250: 97.61%\\n\",\n      \"#9251: 97.61%\\n\",\n      \"#9252: 97.61%\\n\",\n      \"#9253: 97.61%\\n\",\n      \"#9254: 97.61%\\n\",\n      \"#9255: 97.61%\\n\",\n      \"#9256: 97.61%\\n\",\n      \"#9257: 97.61%\\n\",\n      \"#9258: 97.61%\\n\",\n      \"#9259: 97.61%\\n\",\n      \"#9260: 97.61%\\n\",\n      \"#9261: 97.61%\\n\",\n      \"#9262: 97.61%\\n\",\n      \"#9263: 97.61%\\n\",\n      \"#9264: 97.61%\\n\",\n      \"#9265: 97.61%\\n\",\n      \"#9266: 97.62%\\n\",\n      \"#9267: 97.62%\\n\",\n      \"#9268: 97.62%\\n\",\n      \"#9269: 97.62%\\n\",\n      \"#9270: 97.62%\\n\",\n      \"#9271: 97.62%\\n\",\n      \"#9272: 97.62%\\n\",\n      \"#9273: 97.62%\\n\",\n      \"#9274: 97.62%\\n\",\n      \"#9275: 97.62%\\n\",\n      \"#9276: 97.62%\\n\",\n      \"#9277: 97.62%\\n\",\n      \"#9278: 97.62%\\n\",\n      \"#9279: 97.62%\\n\",\n      \"#9280: 97.62%\\n\",\n      \"#9281: 97.62%\\n\",\n      \"#9282: 97.62%\\n\",\n      \"#9283: 97.62%\\n\",\n      \"#9284: 97.62%\\n\",\n      \"#9285: 97.62%\\n\",\n      \"#9286: 97.62%\\n\",\n      \"#9287: 97.62%\\n\",\n      \"#9288: 97.62%\\n\",\n      \"#9289: 97.62%\\n\",\n      \"#9290: 97.62%\\n\",\n      \"#9291: 97.62%\\n\",\n      \"#9292: 97.62%\\n\",\n      \"#9293: 97.62%\\n\",\n      \"#9294: 97.62%\\n\",\n      \"#9295: 97.62%\\n\",\n      \"#9296: 97.62%\\n\",\n      \"#9297: 97.62%\\n\",\n      \"#9298: 97.62%\\n\",\n      \"#9299: 97.62%\\n\",\n      \"#9300: 97.62%\\n\",\n      \"#9301: 97.62%\\n\",\n      \"#9302: 97.62%\\n\",\n      \"#9303: 97.62%\\n\",\n      \"#9304: 97.62%\\n\",\n      \"#9305: 97.63%\\n\",\n      \"#9306: 97.63%\\n\",\n      \"#9307: 97.63%\\n\",\n      \"#9308: 97.63%\\n\",\n      \"#9309: 97.63%\\n\",\n      \"#9310: 97.63%\\n\",\n      \"#9311: 97.63%\\n\",\n      \"#9312: 97.63%\\n\",\n      \"#9313: 97.63%\\n\",\n      \"#9314: 97.63%\\n\",\n      \"#9315: 97.63%\\n\",\n      \"#9316: 97.63%\\n\",\n      \"#9317: 97.63%\\n\",\n      \"#9318: 97.63%\\n\",\n      \"#9319: 97.63%\\n\",\n      \"#9320: 97.63%\\n\",\n      \"#9321: 97.63%\\n\",\n      \"#9322: 97.63%\\n\",\n      \"#9323: 97.63%\\n\",\n      \"#9324: 97.63%\\n\",\n      \"#9325: 97.63%\\n\",\n      \"#9326: 97.63%\\n\",\n      \"#9327: 97.63%\\n\",\n      \"#9328: 97.63%\\n\",\n      \"#9329: 97.63%\\n\",\n      \"#9330: 97.63%\\n\",\n      \"#9331: 97.63%\\n\",\n      \"#9332: 97.63%\\n\",\n      \"#9333: 97.63%\\n\",\n      \"#9334: 97.63%\\n\",\n      \"#9335: 97.63%\\n\",\n      \"#9336: 97.63%\\n\",\n      \"#9337: 97.63%\\n\",\n      \"#9338: 97.63%\\n\",\n      \"#9339: 97.63%\\n\",\n      \"#9340: 97.63%\\n\",\n      \"#9341: 97.63%\\n\",\n      \"#9342: 97.63%\\n\",\n      \"#9343: 97.63%\\n\",\n      \"#9344: 97.64%\\n\",\n      \"#9345: 97.64%\\n\",\n      \"#9346: 97.64%\\n\",\n      \"#9347: 97.64%\\n\",\n      \"#9348: 97.64%\\n\",\n      \"#9349: 97.64%\\n\",\n      \"#9350: 97.64%\\n\",\n      \"#9351: 97.64%\\n\",\n      \"#9352: 97.64%\\n\",\n      \"#9353: 97.64%\\n\",\n      \"#9354: 97.64%\\n\",\n      \"#9355: 97.64%\\n\",\n      \"#9356: 97.64%\\n\",\n      \"#9357: 97.64%\\n\",\n      \"#9358: 97.64%\\n\",\n      \"#9359: 97.64%\\n\",\n      \"#9360: 97.64%\\n\",\n      \"#9361: 97.64%\\n\",\n      \"#9362: 97.64%\\n\",\n      \"#9363: 97.64%\\n\",\n      \"#9364: 97.64%\\n\",\n      \"#9365: 97.64%\\n\",\n      \"#9366: 97.64%\\n\",\n      \"#9367: 97.64%\\n\",\n      \"#9368: 97.64%\\n\",\n      \"#9369: 97.64%\\n\",\n      \"#9370: 97.64%\\n\",\n      \"#9371: 97.64%\\n\",\n      \"#9372: 97.64%\\n\",\n      \"#9373: 97.64%\\n\",\n      \"#9374: 97.64%\\n\",\n      \"#9375: 97.64%\\n\",\n      \"#9376: 97.64%\\n\",\n      \"#9377: 97.64%\\n\",\n      \"#9378: 97.64%\\n\",\n      \"#9379: 97.64%\\n\",\n      \"#9380: 97.64%\\n\",\n      \"#9381: 97.64%\\n\",\n      \"#9382: 97.64%\\n\",\n      \"#9383: 97.64%\\n\",\n      \"#9384: 97.65%\\n\",\n      \"#9385: 97.65%\\n\",\n      \"#9386: 97.65%\\n\",\n      \"#9387: 97.65%\\n\",\n      \"#9388: 97.65%\\n\",\n      \"#9389: 97.65%\\n\",\n      \"#9390: 97.65%\\n\",\n      \"#9391: 97.65%\\n\",\n      \"#9392: 97.65%\\n\",\n      \"#9393: 97.65%\\n\",\n      \"#9394: 97.65%\\n\",\n      \"#9395: 97.65%\\n\",\n      \"#9396: 97.65%\\n\",\n      \"#9397: 97.65%\\n\",\n      \"#9398: 97.65%\\n\",\n      \"#9399: 97.65%\\n\",\n      \"#9400: 97.65%\\n\",\n      \"#9401: 97.65%\\n\",\n      \"#9402: 97.65%\\n\",\n      \"#9403: 97.65%\\n\",\n      \"#9404: 97.65%\\n\",\n      \"#9405: 97.65%\\n\",\n      \"#9406: 97.65%\\n\",\n      \"#9407: 97.65%\\n\",\n      \"#9408: 97.65%\\n\",\n      \"#9409: 97.65%\\n\",\n      \"#9410: 97.65%\\n\",\n      \"#9411: 97.65%\\n\",\n      \"#9412: 97.65%\\n\",\n      \"#9413: 97.65%\\n\",\n      \"#9414: 97.65%\\n\",\n      \"#9415: 97.65%\\n\",\n      \"#9416: 97.65%\\n\",\n      \"#9417: 97.65%\\n\",\n      \"#9418: 97.65%\\n\",\n      \"#9419: 97.65%\\n\",\n      \"#9420: 97.65%\\n\",\n      \"#9421: 97.65%\\n\",\n      \"#9422: 97.65%\\n\",\n      \"#9423: 97.65%\\n\",\n      \"#9424: 97.66%\\n\",\n      \"#9425: 97.66%\\n\",\n      \"#9426: 97.66%\\n\",\n      \"#9427: 97.66%\\n\",\n      \"#9428: 97.66%\\n\",\n      \"#9429: 97.66%\\n\",\n      \"#9430: 97.66%\\n\",\n      \"#9431: 97.66%\\n\",\n      \"#9432: 97.66%\\n\",\n      \"#9433: 97.66%\\n\",\n      \"#9434: 97.66%\\n\",\n      \"#9435: 97.66%\\n\",\n      \"#9436: 97.66%\\n\",\n      \"#9437: 97.66%\\n\",\n      \"#9438: 97.66%\\n\",\n      \"#9439: 97.66%\\n\",\n      \"#9440: 97.66%\\n\",\n      \"#9441: 97.66%\\n\",\n      \"#9442: 97.66%\\n\",\n      \"#9443: 97.66%\\n\",\n      \"#9444: 97.66%\\n\",\n      \"#9445: 97.66%\\n\",\n      \"#9446: 97.66%\\n\",\n      \"#9447: 97.66%\\n\",\n      \"#9448: 97.66%\\n\",\n      \"#9449: 97.66%\\n\",\n      \"#9450: 97.66%\\n\",\n      \"#9451: 97.66%\\n\",\n      \"#9452: 97.66%\\n\",\n      \"#9453: 97.66%\\n\",\n      \"#9454: 97.66%\\n\",\n      \"#9455: 97.66%\\n\",\n      \"#9456: 97.66%\\n\",\n      \"#9457: 97.66%\\n\",\n      \"#9458: 97.66%\\n\",\n      \"#9459: 97.66%\\n\",\n      \"#9460: 97.66%\\n\",\n      \"#9461: 97.66%\\n\",\n      \"#9462: 97.66%\\n\",\n      \"#9463: 97.66%\\n\",\n      \"#9464: 97.67%\\n\",\n      \"#9465: 97.67%\\n\",\n      \"#9466: 97.67%\\n\",\n      \"#9467: 97.67%\\n\",\n      \"#9468: 97.67%\\n\",\n      \"#9469: 97.67%\\n\",\n      \"#9470: 97.67%\\n\",\n      \"#9471: 97.67%\\n\",\n      \"#9472: 97.67%\\n\",\n      \"#9473: 97.67%\\n\",\n      \"#9474: 97.67%\\n\",\n      \"#9475: 97.67%\\n\",\n      \"#9476: 97.67%\\n\",\n      \"#9477: 97.67%\\n\",\n      \"#9478: 97.67%\\n\",\n      \"#9479: 97.67%\\n\",\n      \"#9480: 97.67%\\n\",\n      \"#9481: 97.67%\\n\",\n      \"#9482: 97.67%\\n\",\n      \"#9483: 97.67%\\n\",\n      \"#9484: 97.67%\\n\",\n      \"#9485: 97.67%\\n\",\n      \"#9486: 97.67%\\n\",\n      \"#9487: 97.67%\\n\",\n      \"#9488: 97.67%\\n\",\n      \"#9489: 97.67%\\n\",\n      \"#9490: 97.67%\\n\",\n      \"#9491: 97.67%\\n\",\n      \"#9492: 97.67%\\n\",\n      \"#9493: 97.67%\\n\",\n      \"#9494: 97.67%\\n\",\n      \"#9495: 97.67%\\n\",\n      \"#9496: 97.67%\\n\",\n      \"#9497: 97.67%\\n\",\n      \"#9498: 97.67%\\n\",\n      \"#9499: 97.67%\\n\",\n      \"#9500: 97.67%\\n\",\n      \"#9501: 97.67%\\n\",\n      \"#9502: 97.67%\\n\",\n      \"#9503: 97.67%\\n\",\n      \"#9504: 97.67%\\n\",\n      \"#9505: 97.68%\\n\",\n      \"#9506: 97.68%\\n\",\n      \"#9507: 97.68%\\n\",\n      \"#9508: 97.68%\\n\",\n      \"#9509: 97.68%\\n\",\n      \"#9510: 97.68%\\n\",\n      \"#9511: 97.68%\\n\",\n      \"#9512: 97.68%\\n\",\n      \"#9513: 97.68%\\n\",\n      \"#9514: 97.68%\\n\",\n      \"#9515: 97.68%\\n\",\n      \"#9516: 97.68%\\n\",\n      \"#9517: 97.68%\\n\",\n      \"#9518: 97.68%\\n\",\n      \"#9519: 97.68%\\n\",\n      \"#9520: 97.68%\\n\",\n      \"#9521: 97.68%\\n\",\n      \"#9522: 97.68%\\n\",\n      \"#9523: 97.68%\\n\",\n      \"#9524: 97.68%\\n\",\n      \"#9525: 97.68%\\n\",\n      \"#9526: 97.68%\\n\",\n      \"#9527: 97.68%\\n\",\n      \"#9528: 97.68%\\n\",\n      \"#9529: 97.68%\\n\",\n      \"#9530: 97.67%\\n\",\n      \"#9531: 97.67%\\n\",\n      \"#9532: 97.67%\\n\",\n      \"#9533: 97.67%\\n\",\n      \"#9534: 97.67%\\n\",\n      \"#9535: 97.67%\\n\",\n      \"#9536: 97.67%\\n\",\n      \"#9537: 97.67%\\n\",\n      \"#9538: 97.67%\\n\",\n      \"#9539: 97.67%\\n\",\n      \"#9540: 97.66%\\n\",\n      \"#9541: 97.66%\\n\",\n      \"#9542: 97.66%\\n\",\n      \"#9543: 97.66%\\n\",\n      \"#9544: 97.66%\\n\",\n      \"#9545: 97.66%\\n\",\n      \"#9546: 97.66%\\n\",\n      \"#9547: 97.66%\\n\",\n      \"#9548: 97.66%\\n\",\n      \"#9549: 97.66%\\n\",\n      \"#9550: 97.67%\\n\",\n      \"#9551: 97.67%\\n\",\n      \"#9552: 97.67%\\n\",\n      \"#9553: 97.67%\\n\",\n      \"#9554: 97.67%\\n\",\n      \"#9555: 97.67%\\n\",\n      \"#9556: 97.67%\\n\",\n      \"#9557: 97.67%\\n\",\n      \"#9558: 97.67%\\n\",\n      \"#9559: 97.67%\\n\",\n      \"#9560: 97.67%\\n\",\n      \"#9561: 97.67%\\n\",\n      \"#9562: 97.67%\\n\",\n      \"#9563: 97.67%\\n\",\n      \"#9564: 97.67%\\n\",\n      \"#9565: 97.67%\\n\",\n      \"#9566: 97.67%\\n\",\n      \"#9567: 97.67%\\n\",\n      \"#9568: 97.67%\\n\",\n      \"#9569: 97.67%\\n\",\n      \"#9570: 97.67%\\n\",\n      \"#9571: 97.67%\\n\",\n      \"#9572: 97.67%\\n\",\n      \"#9573: 97.67%\\n\",\n      \"#9574: 97.67%\\n\",\n      \"#9575: 97.67%\\n\",\n      \"#9576: 97.67%\\n\",\n      \"#9577: 97.67%\\n\",\n      \"#9578: 97.67%\\n\",\n      \"#9579: 97.67%\\n\",\n      \"#9580: 97.67%\\n\",\n      \"#9581: 97.67%\\n\",\n      \"#9582: 97.67%\\n\",\n      \"#9583: 97.67%\\n\",\n      \"#9584: 97.67%\\n\",\n      \"#9585: 97.67%\\n\",\n      \"#9586: 97.67%\\n\",\n      \"#9587: 97.66%\\n\",\n      \"#9588: 97.66%\\n\",\n      \"#9589: 97.66%\\n\",\n      \"#9590: 97.66%\\n\",\n      \"#9591: 97.66%\\n\",\n      \"#9592: 97.66%\\n\",\n      \"#9593: 97.67%\\n\",\n      \"#9594: 97.67%\\n\",\n      \"#9595: 97.67%\\n\",\n      \"#9596: 97.67%\\n\",\n      \"#9597: 97.67%\\n\",\n      \"#9598: 97.67%\\n\",\n      \"#9599: 97.67%\\n\",\n      \"#9600: 97.67%\\n\",\n      \"#9601: 97.67%\\n\",\n      \"#9602: 97.67%\\n\",\n      \"#9603: 97.67%\\n\",\n      \"#9604: 97.67%\\n\",\n      \"#9605: 97.67%\\n\",\n      \"#9606: 97.67%\\n\",\n      \"#9607: 97.67%\\n\",\n      \"#9608: 97.67%\\n\",\n      \"#9609: 97.67%\\n\",\n      \"#9610: 97.67%\\n\",\n      \"#9611: 97.67%\\n\",\n      \"#9612: 97.67%\\n\",\n      \"#9613: 97.67%\\n\",\n      \"#9614: 97.66%\\n\",\n      \"#9615: 97.66%\\n\",\n      \"#9616: 97.66%\\n\",\n      \"#9617: 97.66%\\n\",\n      \"#9618: 97.66%\\n\",\n      \"#9619: 97.66%\\n\",\n      \"#9620: 97.66%\\n\",\n      \"#9621: 97.66%\\n\",\n      \"#9622: 97.66%\\n\",\n      \"#9623: 97.66%\\n\",\n      \"#9624: 97.66%\\n\",\n      \"#9625: 97.66%\\n\",\n      \"#9626: 97.66%\\n\",\n      \"#9627: 97.66%\\n\",\n      \"#9628: 97.66%\\n\",\n      \"#9629: 97.66%\\n\",\n      \"#9630: 97.66%\\n\",\n      \"#9631: 97.66%\\n\",\n      \"#9632: 97.66%\\n\",\n      \"#9633: 97.66%\\n\",\n      \"#9634: 97.66%\\n\",\n      \"#9635: 97.67%\\n\",\n      \"#9636: 97.67%\\n\",\n      \"#9637: 97.67%\\n\",\n      \"#9638: 97.67%\\n\",\n      \"#9639: 97.67%\\n\",\n      \"#9640: 97.67%\\n\",\n      \"#9641: 97.67%\\n\",\n      \"#9642: 97.66%\\n\",\n      \"#9643: 97.66%\\n\",\n      \"#9644: 97.66%\\n\",\n      \"#9645: 97.66%\\n\",\n      \"#9646: 97.66%\\n\",\n      \"#9647: 97.66%\\n\",\n      \"#9648: 97.66%\\n\",\n      \"#9649: 97.66%\\n\",\n      \"#9650: 97.66%\\n\",\n      \"#9651: 97.66%\\n\",\n      \"#9652: 97.66%\\n\",\n      \"#9653: 97.66%\\n\",\n      \"#9654: 97.66%\\n\",\n      \"#9655: 97.66%\\n\",\n      \"#9656: 97.66%\\n\",\n      \"#9657: 97.66%\\n\",\n      \"#9658: 97.66%\\n\",\n      \"#9659: 97.66%\\n\",\n      \"#9660: 97.66%\\n\",\n      \"#9661: 97.66%\\n\",\n      \"#9662: 97.66%\\n\",\n      \"#9663: 97.66%\\n\",\n      \"#9664: 97.66%\\n\",\n      \"#9665: 97.66%\\n\",\n      \"#9666: 97.66%\\n\",\n      \"#9667: 97.66%\\n\",\n      \"#9668: 97.66%\\n\",\n      \"#9669: 97.66%\\n\",\n      \"#9670: 97.66%\\n\",\n      \"#9671: 97.66%\\n\",\n      \"#9672: 97.66%\\n\",\n      \"#9673: 97.66%\\n\",\n      \"#9674: 97.66%\\n\",\n      \"#9675: 97.66%\\n\",\n      \"#9676: 97.66%\\n\",\n      \"#9677: 97.66%\\n\",\n      \"#9678: 97.67%\\n\",\n      \"#9679: 97.67%\\n\",\n      \"#9680: 97.67%\\n\",\n      \"#9681: 97.67%\\n\",\n      \"#9682: 97.67%\\n\",\n      \"#9683: 97.67%\\n\",\n      \"#9684: 97.67%\\n\",\n      \"#9685: 97.67%\\n\",\n      \"#9686: 97.67%\\n\",\n      \"#9687: 97.67%\\n\",\n      \"#9688: 97.67%\\n\",\n      \"#9689: 97.67%\\n\",\n      \"#9690: 97.67%\\n\",\n      \"#9691: 97.67%\\n\",\n      \"#9692: 97.67%\\n\",\n      \"#9693: 97.67%\\n\",\n      \"#9694: 97.67%\\n\",\n      \"#9695: 97.67%\\n\",\n      \"#9696: 97.67%\\n\",\n      \"#9697: 97.67%\\n\",\n      \"#9698: 97.66%\\n\",\n      \"#9699: 97.66%\\n\",\n      \"#9700: 97.66%\\n\",\n      \"#9701: 97.66%\\n\",\n      \"#9702: 97.66%\\n\",\n      \"#9703: 97.66%\\n\",\n      \"#9704: 97.66%\\n\",\n      \"#9705: 97.66%\\n\",\n      \"#9706: 97.66%\\n\",\n      \"#9707: 97.66%\\n\",\n      \"#9708: 97.66%\\n\",\n      \"#9709: 97.66%\\n\",\n      \"#9710: 97.66%\\n\",\n      \"#9711: 97.66%\\n\",\n      \"#9712: 97.66%\\n\",\n      \"#9713: 97.66%\\n\",\n      \"#9714: 97.66%\\n\",\n      \"#9715: 97.66%\\n\",\n      \"#9716: 97.66%\\n\",\n      \"#9717: 97.66%\\n\",\n      \"#9718: 97.66%\\n\",\n      \"#9719: 97.66%\\n\",\n      \"#9720: 97.66%\\n\",\n      \"#9721: 97.67%\\n\",\n      \"#9722: 97.67%\\n\",\n      \"#9723: 97.67%\\n\",\n      \"#9724: 97.67%\\n\",\n      \"#9725: 97.67%\\n\",\n      \"#9726: 97.67%\\n\",\n      \"#9727: 97.67%\\n\",\n      \"#9728: 97.67%\\n\",\n      \"#9729: 97.66%\\n\",\n      \"#9730: 97.66%\\n\",\n      \"#9731: 97.66%\\n\",\n      \"#9732: 97.66%\\n\",\n      \"#9733: 97.66%\\n\",\n      \"#9734: 97.66%\\n\",\n      \"#9735: 97.66%\\n\",\n      \"#9736: 97.66%\\n\",\n      \"#9737: 97.66%\\n\",\n      \"#9738: 97.66%\\n\",\n      \"#9739: 97.66%\\n\",\n      \"#9740: 97.66%\\n\",\n      \"#9741: 97.66%\\n\",\n      \"#9742: 97.66%\\n\",\n      \"#9743: 97.66%\\n\",\n      \"#9744: 97.66%\\n\",\n      \"#9745: 97.65%\\n\",\n      \"#9746: 97.65%\\n\",\n      \"#9747: 97.65%\\n\",\n      \"#9748: 97.65%\\n\",\n      \"#9749: 97.65%\\n\",\n      \"#9750: 97.65%\\n\",\n      \"#9751: 97.65%\\n\",\n      \"#9752: 97.65%\\n\",\n      \"#9753: 97.65%\\n\",\n      \"#9754: 97.65%\\n\",\n      \"#9755: 97.65%\\n\",\n      \"#9756: 97.65%\\n\",\n      \"#9757: 97.65%\\n\",\n      \"#9758: 97.65%\\n\",\n      \"#9759: 97.65%\\n\",\n      \"#9760: 97.65%\\n\",\n      \"#9761: 97.65%\\n\",\n      \"#9762: 97.64%\\n\",\n      \"#9763: 97.64%\\n\",\n      \"#9764: 97.64%\\n\",\n      \"#9765: 97.64%\\n\",\n      \"#9766: 97.65%\\n\",\n      \"#9767: 97.65%\\n\",\n      \"#9768: 97.64%\\n\",\n      \"#9769: 97.64%\\n\",\n      \"#9770: 97.63%\\n\",\n      \"#9771: 97.63%\\n\",\n      \"#9772: 97.63%\\n\",\n      \"#9773: 97.63%\\n\",\n      \"#9774: 97.63%\\n\",\n      \"#9775: 97.63%\\n\",\n      \"#9776: 97.63%\\n\",\n      \"#9777: 97.63%\\n\",\n      \"#9778: 97.63%\\n\",\n      \"#9779: 97.63%\\n\",\n      \"#9780: 97.63%\\n\",\n      \"#9781: 97.63%\\n\",\n      \"#9782: 97.62%\\n\",\n      \"#9783: 97.62%\\n\",\n      \"#9784: 97.62%\\n\",\n      \"#9785: 97.62%\\n\",\n      \"#9786: 97.62%\\n\",\n      \"#9787: 97.62%\\n\",\n      \"#9788: 97.62%\\n\",\n      \"#9789: 97.62%\\n\",\n      \"#9790: 97.62%\\n\",\n      \"#9791: 97.62%\\n\",\n      \"#9792: 97.61%\\n\",\n      \"#9793: 97.61%\\n\",\n      \"#9794: 97.61%\\n\",\n      \"#9795: 97.61%\\n\",\n      \"#9796: 97.61%\\n\",\n      \"#9797: 97.61%\\n\",\n      \"#9798: 97.61%\\n\",\n      \"#9799: 97.61%\\n\",\n      \"#9800: 97.61%\\n\",\n      \"#9801: 97.61%\\n\",\n      \"#9802: 97.61%\\n\",\n      \"#9803: 97.61%\\n\",\n      \"#9804: 97.61%\\n\",\n      \"#9805: 97.61%\\n\",\n      \"#9806: 97.61%\\n\",\n      \"#9807: 97.61%\\n\",\n      \"#9808: 97.61%\\n\",\n      \"#9809: 97.61%\\n\",\n      \"#9810: 97.61%\\n\",\n      \"#9811: 97.60%\\n\",\n      \"#9812: 97.61%\\n\",\n      \"#9813: 97.61%\\n\",\n      \"#9814: 97.61%\\n\",\n      \"#9815: 97.61%\\n\",\n      \"#9816: 97.61%\\n\",\n      \"#9817: 97.61%\\n\",\n      \"#9818: 97.61%\\n\",\n      \"#9819: 97.61%\\n\",\n      \"#9820: 97.61%\\n\",\n      \"#9821: 97.61%\\n\",\n      \"#9822: 97.61%\\n\",\n      \"#9823: 97.61%\\n\",\n      \"#9824: 97.61%\\n\",\n      \"#9825: 97.61%\\n\",\n      \"#9826: 97.61%\\n\",\n      \"#9827: 97.61%\\n\",\n      \"#9828: 97.61%\\n\",\n      \"#9829: 97.61%\\n\",\n      \"#9830: 97.61%\\n\",\n      \"#9831: 97.61%\\n\",\n      \"#9832: 97.61%\\n\",\n      \"#9833: 97.61%\\n\",\n      \"#9834: 97.61%\\n\",\n      \"#9835: 97.61%\\n\",\n      \"#9836: 97.61%\\n\",\n      \"#9837: 97.61%\\n\",\n      \"#9838: 97.61%\\n\",\n      \"#9839: 97.60%\\n\",\n      \"#9840: 97.60%\\n\",\n      \"#9841: 97.60%\\n\",\n      \"#9842: 97.60%\\n\",\n      \"#9843: 97.60%\\n\",\n      \"#9844: 97.60%\\n\",\n      \"#9845: 97.60%\\n\",\n      \"#9846: 97.60%\\n\",\n      \"#9847: 97.60%\\n\",\n      \"#9848: 97.60%\\n\",\n      \"#9849: 97.60%\\n\",\n      \"#9850: 97.60%\\n\",\n      \"#9851: 97.60%\\n\",\n      \"#9852: 97.60%\\n\",\n      \"#9853: 97.61%\\n\",\n      \"#9854: 97.61%\\n\",\n      \"#9855: 97.61%\\n\",\n      \"#9856: 97.60%\\n\",\n      \"#9857: 97.60%\\n\",\n      \"#9858: 97.60%\\n\",\n      \"#9859: 97.60%\\n\",\n      \"#9860: 97.60%\\n\",\n      \"#9861: 97.60%\\n\",\n      \"#9862: 97.60%\\n\",\n      \"#9863: 97.60%\\n\",\n      \"#9864: 97.60%\\n\",\n      \"#9865: 97.60%\\n\",\n      \"#9866: 97.60%\\n\",\n      \"#9867: 97.59%\\n\",\n      \"#9868: 97.59%\\n\",\n      \"#9869: 97.59%\\n\",\n      \"#9870: 97.59%\\n\",\n      \"#9871: 97.59%\\n\",\n      \"#9872: 97.59%\\n\",\n      \"#9873: 97.59%\\n\",\n      \"#9874: 97.59%\\n\",\n      \"#9875: 97.59%\\n\",\n      \"#9876: 97.59%\\n\",\n      \"#9877: 97.59%\\n\",\n      \"#9878: 97.59%\\n\",\n      \"#9879: 97.59%\\n\",\n      \"#9880: 97.59%\\n\",\n      \"#9881: 97.59%\\n\",\n      \"#9882: 97.59%\\n\",\n      \"#9883: 97.59%\\n\",\n      \"#9884: 97.59%\\n\",\n      \"#9885: 97.59%\\n\",\n      \"#9886: 97.59%\\n\",\n      \"#9887: 97.59%\\n\",\n      \"#9888: 97.59%\\n\",\n      \"#9889: 97.59%\\n\",\n      \"#9890: 97.59%\\n\",\n      \"#9891: 97.59%\\n\",\n      \"#9892: 97.58%\\n\",\n      \"#9893: 97.57%\\n\",\n      \"#9894: 97.57%\\n\",\n      \"#9895: 97.57%\\n\",\n      \"#9896: 97.58%\\n\",\n      \"#9897: 97.58%\\n\",\n      \"#9898: 97.58%\\n\",\n      \"#9899: 97.58%\\n\",\n      \"#9900: 97.58%\\n\",\n      \"#9901: 97.58%\\n\",\n      \"#9902: 97.58%\\n\",\n      \"#9903: 97.58%\\n\",\n      \"#9904: 97.58%\\n\",\n      \"#9905: 97.57%\\n\",\n      \"#9906: 97.57%\\n\",\n      \"#9907: 97.57%\\n\",\n      \"#9908: 97.57%\\n\",\n      \"#9909: 97.57%\\n\",\n      \"#9910: 97.57%\\n\",\n      \"#9911: 97.57%\\n\",\n      \"#9912: 97.57%\\n\",\n      \"#9913: 97.57%\\n\",\n      \"#9914: 97.57%\\n\",\n      \"#9915: 97.57%\\n\",\n      \"#9916: 97.57%\\n\",\n      \"#9917: 97.57%\\n\",\n      \"#9918: 97.57%\\n\",\n      \"#9919: 97.57%\\n\",\n      \"#9920: 97.57%\\n\",\n      \"#9921: 97.57%\\n\",\n      \"#9922: 97.57%\\n\",\n      \"#9923: 97.57%\\n\",\n      \"#9924: 97.57%\\n\",\n      \"#9925: 97.57%\\n\",\n      \"#9926: 97.57%\\n\",\n      \"#9927: 97.57%\\n\",\n      \"#9928: 97.57%\\n\",\n      \"#9929: 97.57%\\n\",\n      \"#9930: 97.57%\\n\",\n      \"#9931: 97.57%\\n\",\n      \"#9932: 97.57%\\n\",\n      \"#9933: 97.57%\\n\",\n      \"#9934: 97.57%\\n\",\n      \"#9935: 97.57%\\n\",\n      \"#9936: 97.57%\\n\",\n      \"#9937: 97.57%\\n\",\n      \"#9938: 97.58%\\n\",\n      \"#9939: 97.58%\\n\",\n      \"#9940: 97.58%\\n\",\n      \"#9941: 97.58%\\n\",\n      \"#9942: 97.57%\\n\",\n      \"#9943: 97.57%\\n\",\n      \"#9944: 97.57%\\n\",\n      \"#9945: 97.57%\\n\",\n      \"#9946: 97.57%\\n\",\n      \"#9947: 97.57%\\n\",\n      \"#9948: 97.57%\\n\",\n      \"#9949: 97.57%\\n\",\n      \"#9950: 97.57%\\n\",\n      \"#9951: 97.57%\\n\",\n      \"#9952: 97.57%\\n\",\n      \"#9953: 97.57%\\n\",\n      \"#9954: 97.57%\\n\",\n      \"#9955: 97.57%\\n\",\n      \"#9956: 97.57%\\n\",\n      \"#9957: 97.57%\\n\",\n      \"#9958: 97.57%\\n\",\n      \"#9959: 97.57%\\n\",\n      \"#9960: 97.57%\\n\",\n      \"#9961: 97.57%\\n\",\n      \"#9962: 97.57%\\n\",\n      \"#9963: 97.57%\\n\",\n      \"#9964: 97.57%\\n\",\n      \"#9965: 97.57%\\n\",\n      \"#9966: 97.57%\\n\",\n      \"#9967: 97.57%\\n\",\n      \"#9968: 97.57%\\n\",\n      \"#9969: 97.57%\\n\",\n      \"#9970: 97.57%\\n\",\n      \"#9971: 97.57%\\n\",\n      \"#9972: 97.57%\\n\",\n      \"#9973: 97.57%\\n\",\n      \"#9974: 97.57%\\n\",\n      \"#9975: 97.57%\\n\",\n      \"#9976: 97.57%\\n\",\n      \"#9977: 97.57%\\n\",\n      \"#9978: 97.57%\\n\",\n      \"#9979: 97.58%\\n\",\n      \"#9980: 97.58%\\n\",\n      \"#9981: 97.58%\\n\",\n      \"#9982: 97.57%\\n\",\n      \"#9983: 97.57%\\n\",\n      \"#9984: 97.57%\\n\",\n      \"#9985: 97.57%\\n\",\n      \"#9986: 97.57%\\n\",\n      \"#9987: 97.57%\\n\",\n      \"#9988: 97.57%\\n\",\n      \"#9989: 97.57%\\n\",\n      \"#9990: 97.57%\\n\",\n      \"#9991: 97.57%\\n\",\n      \"#9992: 97.57%\\n\",\n      \"#9993: 97.57%\\n\",\n      \"#9994: 97.57%\\n\",\n      \"#9995: 97.57%\\n\",\n      \"#9996: 97.57%\\n\",\n      \"#9997: 97.57%\\n\",\n      \"#9998: 97.57%\\n\",\n      \"#9999: 97.57%\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"correct = 0\\n\",\n    \"for i in range(10000):\\n\",\n    \"    with open(f\\\"X_test/{i}.json\\\", \\\"r\\\") as f:\\n\",\n    \"        input = json.load(f)\\n\",\n    \"    out, _ = inference(input, circuit)\\n\",\n    \"    correct += 1 if out[0] == y_test[i] else 0\\n\",\n    \"    print(f\\\"#{i}: {correct / (i + 1) * 100:.2f}%\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "test/circuit.js",
        "content": "const chai = require('chai');\nconst fs = require('fs');\n\nconst wasm_tester = require('circom_tester').wasm;\n\nconst F1Field = require('ffjavascript').F1Field;\nconst Scalar = require('ffjavascript').Scalar;\nexports.p = Scalar.fromString('21888242871839275222246405745257275088548364400416034343698204186575808495617');\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst exec = require('await-exec');\n\nconst input = require('../test/X_test/0.json');\n\ndescribe('keras2circom test', function () {\n    this.timeout(100000000);\n\n    describe('softmax output', async () => {\n        it('softmax output test', async () => {\n            await exec('python main.py models/model.h5 && python output/circuit.py output/circuit.json test/X_test/0.json');\n\n            const model = JSON.parse(fs.readFileSync('./output/circuit.json'));\n            const output = JSON.parse(fs.readFileSync('./output/output.json'));\n\n            const INPUT = {...model, ...input, ...output};\n\n            const circuit = await wasm_tester('./output/circuit.circom');\n            const witness = await circuit.calculateWitness(INPUT, true);\n            assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n            assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));\n        });\n    });\n\n    describe('raw output', async () => {\n        it('raw output test', async () => {\n            await exec('python main.py models/model.h5 --raw && python output/circuit.py output/circuit.json test/X_test/0.json');\n\n            const model = JSON.parse(fs.readFileSync('./output/circuit.json'));\n            const output = JSON.parse(fs.readFileSync('./output/output.json'));\n\n            const INPUT = {...model, ...input, ...output};\n\n            const circuit = await wasm_tester('./output/circuit.circom');\n            const witness = await circuit.calculateWitness(INPUT, true);\n            assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        });\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/keras2circom",
        "file_path": "test/load_input.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.datasets import mnist\\n\",\n    \"import json\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# load MNIST dataset\\n\",\n    \"_, (X_test, y_test) = mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#normalizing\\n\",\n    \"X_test = X_test.astype('float32')\\n\",\n    \"X_test /= 255.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"for i in range(len(X_test)):\\n\",\n    \"    X = [str(int(x * float(10**18))) for x in X_test[i].flatten().tolist()]\\n\",\n    \"    X = np.array(X).reshape(28, 28, 1).tolist()\\n\",\n    \"    with open(f'X_test/{i}.json', 'w') as f:\\n\",\n    \"        json.dump({\\\"in\\\": X}, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open('y_test.json', 'w') as f:\\n\",\n    \"    json.dump(y_test.tolist(), f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/ArgMax.circom",
        "content": "// from 0xZKML/zk-mnist\n\npragma circom 2.0.0;\n\ninclude \"./circomlib/comparators.circom\";\ninclude \"./circomlib/switcher.circom\";\n\ntemplate ArgMax (n) {\n    signal input in[n];\n    signal input out;\n\n    assert (out < n);\n    component gts[n];        // store comparators\n    component switchers[n+1];  // switcher for comparing maxs\n    component aswitchers[n+1]; // switcher for arg max\n\n    signal maxs[n+1];\n    signal amaxs[n+1];\n\n    maxs[0] <== in[0];\n    amaxs[0] <== 0;\n    for(var i = 0; i < n; i++) {\n        gts[i] = GreaterThan(252); // changed to 252 (maximum) for better compatibility\n        switchers[i+1] = Switcher();\n        aswitchers[i+1] = Switcher();\n\n        gts[i].in[1] <== maxs[i];\n        gts[i].in[0] <== in[i];\n\n        switchers[i+1].sel <== gts[i].out;\n        switchers[i+1].L <== maxs[i];\n        switchers[i+1].R <== in[i];\n\n        aswitchers[i+1].sel <== gts[i].out;\n        aswitchers[i+1].L <== amaxs[i];\n        aswitchers[i+1].R <== i;\n        amaxs[i+1] <== aswitchers[i+1].outL;\n        maxs[i+1] <== switchers[i+1].outL;\n    }\n\n    out === amaxs[n];\n}\n\n// component main { public [ out ] } = ArgMax(5);\n\n/* INPUT = {\n    \"in\":  [\"2\",\"3\",\"1\",\"5\",\"4\"],\n    \"out\": \"3\"\n} */"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/AveragePooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./SumPooling2D.circom\";\n\n// AveragePooling2D layer, poolSize is required to be equal for both dimensions, might lose precision compared to SumPooling2D\ntemplate AveragePooling2D (nRows, nCols, nChannels, poolSize, strides) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n    signal input remainder[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n\n    component sumPooling2D = SumPooling2D (nRows, nCols, nChannels, poolSize, strides);\n\n    for (var i=0; i<nRows; i++) {\n        for (var j=0; j<nCols; j++) {\n            for (var k=0; k<nChannels; k++) {\n                sumPooling2D.in[i][j][k] <== in[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<(nRows-poolSize)\\strides+1; i++) {\n        for (var j=0; j<(nCols-poolSize)\\strides+1; j++) {\n            for (var k=0; k<nChannels; k++) {\n                assert(remainder[i][j][k] < poolSize * poolSize);\n                out[i][j][k] * poolSize * poolSize + remainder[i][j][k] === sumPooling2D.out[i][j][k];\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/BatchNormalization2D.circom",
        "content": "pragma circom 2.0.0;\n\n// BatchNormalization layer for 2D inputs\n// a = gamma/(moving_var+epsilon)**.5\n// b = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n// n = 10 to the power of the number of decimal places\ntemplate BatchNormalization2D(nRows, nCols, nChannels, n) {\n    signal input in[nRows][nCols][nChannels];\n    signal input a[nChannels];\n    signal input b[nChannels];\n    signal input out[nRows][nCols][nChannels];\n    signal input remainder[nRows][nCols][nChannels];\n\n    for (var i=0; i<nRows; i++) {\n        for (var j=0; j<nCols; j++) {\n            for (var k=0; k<nChannels; k++) {\n                assert(remainder[i][j][k] < n);\n                out[i][j][k] * n + remainder[i][j][k] === a[k]*in[i][j][k]+b[k];\n            }\n        }\n    }\n}\n\n// component main { public [ out ] } = BatchNormalization2D(1, 1, 1, 1000);\n\n/* INPUT = {\n    \"in\":  [\"123\"],\n    \"a\": [\"234\"],\n    \"b\": [\"345678\"],\n    \"out\": [\"374\"],\n    \"remainder\": [\"460\"]\n} */"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Conv1D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib-matrix/matElemMul.circom\";\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// Conv1D layer with valid padding\n// n = 10 to the power of the number of decimal places\ntemplate Conv1D (nInputs, nChannels, nFilters, kernelSize, strides, n) {\n    signal input in[nInputs][nChannels];\n    signal input weights[kernelSize][nChannels][nFilters];\n    signal input bias[nFilters];\n    signal input out[(nInputs-kernelSize)\\strides+1][nFilters];\n    signal input remainder[(nInputs-kernelSize)\\strides+1][nFilters];\n\n    component mul[(nInputs-kernelSize)\\strides+1][nChannels][nFilters];\n    component elemSum[(nInputs-kernelSize)\\strides+1][nChannels][nFilters];\n    component sum[(nInputs-kernelSize)\\strides+1][nFilters];\n\n    for (var i=0; i<(nInputs-kernelSize)\\strides+1; i++) {\n        for (var j=0; j<nChannels; j++) {\n            for (var k=0; k<nFilters; k++) {\n                mul[i][j][k] = matElemMul(kernelSize,1);\n                for (var x=0; x<kernelSize; x++) {\n                    mul[i][j][k].a[x][0] <== in[i*strides+x][j];\n                    mul[i][j][k].b[x][0] <== weights[x][j][k];\n                }\n                elemSum[i][j][k] = matElemSum(kernelSize,1);\n                for (var x=0; x<kernelSize; x++) {\n                    elemSum[i][j][k].a[x][0] <== mul[i][j][k].out[x][0];\n                }\n            }\n        }\n        for (var k=0; k<nFilters; k++) {\n            assert (remainder[i][k] < n);\n            sum[i][k] = Sum(nChannels);\n            for (var j=0; j<nChannels; j++) {\n                sum[i][k].in[j] <== elemSum[i][j][k].out;\n            }\n            out[i][k] * n + remainder[i][k] === sum[i][k].out + bias[k];\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Conv2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib-matrix/matElemMul.circom\";\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// Conv2D layer with valid padding\n// n = 10 to the power of the number of decimal places\ntemplate Conv2D (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {\n    signal input in[nRows][nCols][nChannels];\n    signal input weights[kernelSize][kernelSize][nChannels][nFilters];\n    signal input bias[nFilters];\n    signal input out[(nRows-kernelSize)\\strides+1][(nCols-kernelSize)\\strides+1][nFilters];\n    signal input remainder[(nRows-kernelSize)\\strides+1][(nCols-kernelSize)\\strides+1][nFilters];\n\n    component mul[(nRows-kernelSize)\\strides+1][(nCols-kernelSize)\\strides+1][nChannels][nFilters];\n    component elemSum[(nRows-kernelSize)\\strides+1][(nCols-kernelSize)\\strides+1][nChannels][nFilters];\n    component sum[(nRows-kernelSize)\\strides+1][(nCols-kernelSize)\\strides+1][nFilters];\n\n    for (var i=0; i<(nRows-kernelSize)\\strides+1; i++) {\n        for (var j=0; j<(nCols-kernelSize)\\strides+1; j++) {\n            for (var k=0; k<nChannels; k++) {\n                for (var m=0; m<nFilters; m++) {\n                    mul[i][j][k][m] = matElemMul(kernelSize,kernelSize);\n                    for (var x=0; x<kernelSize; x++) {\n                        for (var y=0; y<kernelSize; y++) {\n                            mul[i][j][k][m].a[x][y] <== in[i*strides+x][j*strides+y][k];\n                            mul[i][j][k][m].b[x][y] <== weights[x][y][k][m];\n                        }\n                    }\n                    elemSum[i][j][k][m] = matElemSum(kernelSize,kernelSize);\n                    for (var x=0; x<kernelSize; x++) {\n                        for (var y=0; y<kernelSize; y++) {\n                            elemSum[i][j][k][m].a[x][y] <== mul[i][j][k][m].out[x][y];\n                        }\n                    }\n                }\n            }\n            for (var m=0; m<nFilters; m++) {\n                assert (remainder[i][j][m] < n);\n                sum[i][j][m] = Sum(nChannels);\n                for (var k=0; k<nChannels; k++) {\n                    sum[i][j][m].in[k] <== elemSum[i][j][k][m].out;\n                }\n                out[i][j][m] * n + remainder[i][j][m] === sum[i][j][m].out + bias[m];\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Conv2Dsame.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./Conv2D.circom\";\n\ntemplate Conv2Dsame (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {\n    signal input in[nRows][nCols][nChannels];\n    signal input weights[kernelSize][kernelSize][nChannels][nFilters];\n    signal input bias[nFilters];\n\n    var rowPadding, colPadding;\n\n    if (nRows % strides == 0) {\n        rowPadding = (kernelSize - strides) > 0 ? (kernelSize - strides) : 0;\n    } else {\n        rowPadding = (kernelSize - (nRows % strides)) > 0 ? (kernelSize - (nRows % strides)) : 0;\n    }\n\n    if (nCols % strides == 0) {\n        colPadding = (kernelSize - strides) > 0 ? (kernelSize - strides) : 0;\n    } else {\n        colPadding = (kernelSize - (nCols % strides)) > 0 ? (kernelSize - (nCols % strides)) : 0;\n    }\n\n    signal input out[(nRows+rowPadding-kernelSize)\\strides+1][(nCols+colPadding-kernelSize)\\strides+1][nFilters];\n    signal input remainder[(nRows+rowPadding-kernelSize)\\strides+1][(nCols+colPadding-kernelSize)\\strides+1][nFilters];\n\n    component conv2d = Conv2D(nRows+rowPadding, nCols+colPadding, nChannels, nFilters, kernelSize, strides, n);\n\n    for (var i = rowPadding\\2; i < rowPadding\\2+nRows; i++) {\n        for (var j = colPadding\\2; j < colPadding\\2+nCols; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                conv2d.in[i][j][k] <== in[i-rowPadding\\2][j-colPadding\\2][k];\n            }\n        }\n    }\n\n    for (var i = 0; i< rowPadding\\2; i++) {\n        for (var j = 0; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                conv2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = nRows+rowPadding\\2; i < nRows+rowPadding; i++) {\n        for (var j = 0; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                conv2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = rowPadding\\2; i < nRows+rowPadding\\2; i++) {\n        for (var j = 0; j < colPadding\\2; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                conv2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n    \n    for (var i = rowPadding\\2; i < nRows+rowPadding\\2; i++) {\n        for (var j = nCols+colPadding\\2; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                conv2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = 0; i < kernelSize; i++) {\n        for (var j = 0; j < kernelSize; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                for (var l = 0; l < nFilters; l++) {\n                    conv2d.weights[i][j][k][l] <== weights[i][j][k][l];\n                }\n            }\n        }\n    }\n\n    for (var i = 0; i < nFilters; i++) {\n        conv2d.bias[i] <== bias[i];\n    }\n\n    for (var i = 0; i < (nRows+rowPadding-kernelSize)\\strides+1; i++) {\n        for (var j = 0; j < (nCols+colPadding-kernelSize)\\strides+1; j++) {\n            for (var k = 0; k < nFilters; k++) {\n                conv2d.out[i][j][k] <== out[i][j][k];\n                conv2d.remainder[i][j][k] <== remainder[i][j][k];\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Dense.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib-matrix/matMul.circom\";\n// Dense layer\n// n = 10 to the power of the number of decimal places\ntemplate Dense (nInputs, nOutputs, n) {\n    signal input in[nInputs];\n    signal input weights[nInputs][nOutputs];\n    signal input bias[nOutputs];\n    signal input out[nOutputs];\n    signal input remainder[nOutputs];\n\n    component dot[nOutputs];\n\n    for (var i=0; i<nOutputs; i++) {\n        assert (remainder[i] < n);\n        dot[i] = matMul(1,nInputs,1);\n        \n        for (var j=0; j<nInputs; j++) {\n            dot[i].a[0][j] <== in[j];\n            dot[i].b[j][0] <== weights[j][i];\n        }\n\n        out[i] * n + remainder[i] === dot[i].out[0][0] + bias[i];\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/DepthwiseConv2D.circom",
        "content": "pragma circom 2.1.1;\n// include \"./Conv2D.circom\";\n\ninclude \"./circomlib/sign.circom\";\ninclude \"./circomlib/bitify.circom\";\ninclude \"./circomlib/comparators.circom\";\ninclude \"./circomlib-matrix/matElemMul.circom\";\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// Depthwise Convolution layer with valid padding\n// Note that nFilters must be a multiple of nChannels\n// n = 10 to the power of the number of decimal places\n// component main = DepthwiseConv2D(34, 34, 8, 8, 3, 1);\ntemplate DepthwiseConv2D (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {\n    var outRows = (nRows-kernelSize)\\strides+1;\n    var outCols = (nCols-kernelSize)\\strides+1;\n\n    signal input in[nRows][nCols][nChannels];\n    signal input weights[kernelSize][kernelSize][nFilters]; // weights are 3d because depth is 1\n    signal input bias[nFilters];\n    signal input remainder[outRows][outCols][nFilters];\n\n    signal input out[outRows][outCols][nFilters];\n\n    component mul[outRows][outCols][nFilters];\n    component elemSum[outRows][outCols][nFilters];\n\n    var valid_groups = nFilters % nChannels;\n    var filtersPerChannel = nFilters / nChannels;\n\n    signal groups;\n    groups <== valid_groups;\n    component is_zero = IsZero();\n    is_zero.in <== groups;\n    is_zero.out === 1;\n\n    for (var row=0; row<outRows; row++) {\n        for (var col=0; col<outCols; col++) {\n            for (var filterMultiplier=1; filterMultiplier<=filtersPerChannel; filterMultiplier++) {\n                for (var channel=0; channel<nChannels; channel++) {\n                    var filter = filterMultiplier*channel;\n\n                    mul[row][col][filter] = matElemMul(kernelSize,kernelSize);\n\n                    for (var x=0; x<kernelSize; x++) {\n                        for (var y=0; y<kernelSize; y++) {\n                            mul[row][col][filter].a[x][y] <== in[row*strides+x][col*strides+y][channel];\n                            mul[row][col][filter].b[x][y] <== weights[x][y][filter];\n                        }\n                    }\n\n                    elemSum[row][col][filter] = matElemSum(kernelSize,kernelSize);\n                    for (var x=0; x<kernelSize; x++) {\n                        for (var y=0; y<kernelSize; y++) {\n                            elemSum[row][col][filter].a[x][y] <== mul[row][col][filter].out[x][y];\n                        }\n                    }\n                    out[row][col][filter] * n + remainder[row][col][filter] === elemSum[row][col][filter].out + bias[filter];\n                }\n            }\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Flatten2D.circom",
        "content": "pragma circom 2.0.0;\n\n// Flatten layer with that accepts a 2D input\ntemplate Flatten2D (nRows, nCols, nChannels) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[nRows*nCols*nChannels];\n\n    var idx = 0;\n\n    for (var i=0; i<nRows; i++) {\n        for (var j=0; j<nCols; j++) {\n            for (var k=0; k<nChannels; k++) {\n                out[idx] === in[i][j][k];\n                idx++;\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/GlobalAveragePooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./GlobalSumPooling2D.circom\";\n\n// GlobalAveragePooling2D layer, might lose precision compared to GlobalSumPooling2D\ntemplate GlobalAveragePooling2D (nRows, nCols, nChannels) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[nChannels];\n    signal input remainder[nChannels];\n\n    component globalSumPooling2D = GlobalSumPooling2D (nRows, nCols, nChannels);\n\n    for (var i=0; i<nRows; i++) {\n        for (var j=0; j<nCols; j++) {\n            for (var k=0; k<nChannels; k++) {\n                globalSumPooling2D.in[i][j][k] <== in[i][j][k];\n            }\n        }\n    }\n\n    for (var k=0; k<nChannels; k++) {\n        assert (remainder[k] < nRows*nCols);\n        out[k] * nRows * nCols + remainder[k] === globalSumPooling2D.out[k];\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/GlobalMaxPooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./util.circom\";\n\n// GlobalMaxPooling2D layer\ntemplate GlobalMaxPooling2D (nRows, nCols, nChannels) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[nChannels];\n\n    component max[nChannels];\n\n    for (var k=0; k<nChannels; k++) {\n        max[k] = Max(nRows*nCols);\n        for (var i=0; i<nRows; i++) {\n            for (var j=0; j<nCols; j++) {\n                max[k].in[i*nCols+j] <== in[i][j][k];\n            }\n        }\n        out[k] === max[k].out;\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/GlobalSumPooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// GlobalSumPooling2D layer, basically GlobalAveragePooling2D layer with a constant scaling, more optimized for circom\ntemplate GlobalSumPooling2D (nRows, nCols, nChannels) {\n    signal input in[nRows][nCols][nChannels];\n    signal output out[nChannels];\n\n    component elemSum[nChannels];\n\n    for (var k=0; k<nChannels; k++) {\n        elemSum[k] = matElemSum(nRows,nCols);\n        for (var i=0; i<nRows; i++) {\n            for (var j=0; j<nCols; j++) {\n                elemSum[k].a[i][j] <== in[i][j][k];\n            }\n        }\n        out[k] <== elemSum[k].out;\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/LeakyReLU.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./util.circom\";\n\n// LeakyReLU layer\ntemplate LeakyReLU (alpha) { // alpha is 10 times the actual alpha, since usual alpha is 0.2, 0.3, etc.\n    signal input in;\n    signal input out;\n    signal input remainder;\n\n    component isNegative = IsNegative();\n\n    isNegative.in <== in;\n\n    signal neg;\n    neg <== isNegative.out * alpha * in;\n\n    out * 10 + remainder === neg + 10 * in * (1 - isNegative.out);\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/MaxPooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./util.circom\";\n\n// MaxPooling2D layer\ntemplate MaxPooling2D (nRows, nCols, nChannels, poolSize, strides) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n\n    component max[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n\n    for (var i=0; i<(nRows-poolSize)\\strides+1; i++) {\n        for (var j=0; j<(nCols-poolSize)\\strides+1; j++) {\n            for (var k=0; k<nChannels; k++) {\n                max[i][j][k] = Max(poolSize*poolSize);\n                for (var x=0; x<poolSize; x++) {\n                    for (var y=0; y<poolSize; y++) {\n                        max[i][j][k].in[x*poolSize+y] <== in[i*strides+x][j*strides+y][k];\n                    }\n                }\n                out[i][j][k] === max[i][j][k].out;\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/MaxPooling2Dsame.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./MaxPooling2D.circom\";\n\ntemplate MaxPooling2Dsame (nRows, nCols, nChannels, poolSize, strides) {\n    signal input in[nRows][nCols][nChannels];\n    \n    var rowPadding, colPadding;\n\n    if (nRows % strides == 0) {\n        rowPadding = (poolSize - strides) > 0 ? (poolSize - strides) : 0;\n    } else {\n        rowPadding = (poolSize - (nRows % strides)) > 0 ? (poolSize - (nRows % strides)) : 0;\n    }\n\n    if (nCols % strides == 0) {\n        colPadding = (poolSize - strides) > 0 ? (poolSize - strides) : 0;\n    } else {\n        colPadding = (poolSize - (nCols % strides)) > 0 ? (poolSize - (nCols % strides)) : 0;\n    }\n\n    signal input out[(nRows+rowPadding-poolSize)\\strides+1][(nCols+colPadding-poolSize)\\strides+1][nChannels];\n\n    component max2d = MaxPooling2D(nRows+rowPadding, nCols+colPadding, nChannels, poolSize, strides);\n\n    for (var i = rowPadding\\2; i < rowPadding\\2+nRows; i++) {\n        for (var j = colPadding\\2; j < colPadding\\2+nCols; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.in[i][j][k] <== in[i-rowPadding\\2][j-colPadding\\2][k];\n            }\n        }\n    }\n\n    for (var i = 0; i< rowPadding\\2; i++) {\n        for (var j = 0; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = nRows+rowPadding\\2; i< nRows+rowPadding; i++) {\n        for (var j = 0; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = rowPadding\\2; i < nRows+rowPadding\\2; i++) {\n        for (var j = 0; j < colPadding\\2; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = rowPadding\\2; i < nRows+rowPadding\\2; i++) {\n        for (var j = nCols+colPadding\\2; j < nCols+colPadding; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.in[i][j][k] <== 0;\n            }\n        }\n    }\n\n    for (var i = 0; i < (nRows+rowPadding-poolSize)\\strides+1; i++) {\n        for (var j = 0; j < (nCols+colPadding-poolSize)\\strides+1; j++) {\n            for (var k = 0; k < nChannels; k++) {\n                max2d.out[i][j][k] <== out[i][j][k];\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/PointwiseConv2D.circom",
        "content": "pragma circom 2.1.1;\n// include \"./Conv2D.circom\";\n\ninclude \"./circomlib/sign.circom\";\ninclude \"./circomlib/bitify.circom\";\ninclude \"./circomlib/comparators.circom\";\ninclude \"./circomlib-matrix/matElemMul.circom\";\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// Pointwise Convolution layer\n// Note that nFilters must be a multiple of nChannels\ntemplate PointwiseConv2D (nRows, nCols, nChannels, nFilters, n) {\n    var outRows = nRows; // kernel size and strides are 1\n    var outCols = nCols;\n\n    signal input in[nRows][nCols][nChannels];\n    signal input weights[nChannels][nFilters]; // weights are 2d because kernel_size is 1\n    signal input bias[nFilters];\n    signal input out[outRows][outCols][nFilters];\n    signal input remainder[outRows][outCols][nFilters];\n\n    component sum[outRows][outCols][nFilters];\n\n    for (var row=0; row<outRows; row++) {\n        for (var col=0; col<outCols; col++) {\n            for (var filter=0; filter<nFilters; filter++) {\n                sum[row][col][filter] = Sum(nChannels);\n                for (var channel=0; channel<nChannels; channel++) {\n                    sum[row][col][filter].in[channel] <== in[row][col][channel] * weights[channel][filter];\n                }\n                out[row][col][filter] * n + remainder[row][col][filter] === sum[row][col][filter].out + bias[filter];\n            }\n        }\n    }\n}\n\n\n// component main = PointwiseConv2D(32, 32, 8, 16);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/ReLU.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./util.circom\";\n\n// ReLU layer\ntemplate ReLU () {\n    signal input in;\n    signal input out;\n\n    component isPositive = IsPositive();\n\n    isPositive.in <== in;\n    \n    out === in * isPositive.out;\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Reshape2D.circom",
        "content": "pragma circom 2.0.0;\n\n// Reshape layer with that accepts a 1D input\ntemplate Reshape2D (nRows, nCols, nChannels) {\n    signal input in[nRows*nCols*nChannels];\n    signal input out[nRows][nCols][nChannels];\n\n    for (var i=0; i<nRows; i++) {\n        for (var j=0; j<nCols; j++) {\n            for (var k=0; k<nChannels; k++) {\n                out[i][j][k] === in[i*nCols*nChannels + j*nChannels + k];\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/SeparableConv2D.circom",
        "content": "pragma circom 2.1.1;\n\ninclude \"./PointwiseConv2D.circom\";\ninclude \"./DepthwiseConv2D.circom\";\n\n// Separable convolution layer with valid padding.\n// Quantization is done by the caller by multiplying float values by 10**exp.\ntemplate SeparableConv2D (nRows, nCols, nChannels, nDepthFilters, nPointFilters, depthKernelSize, strides, n) {\n    var outRows = (nRows-depthKernelSize)\\strides+1;\n    var outCols = (nCols-depthKernelSize)\\strides+1;\n\n    signal input in[nRows][nCols][nChannels];\n    signal input depthWeights[depthKernelSize][depthKernelSize][nDepthFilters]; // weights are 3d because depth is 1\n    signal input depthBias[nDepthFilters];\n    signal input depthRemainder[outRows][outCols][nDepthFilters];\n    signal input depthOut[outRows][outCols][nDepthFilters];\n\n    signal input pointWeights[nChannels][nPointFilters]; // weights are 2d because depthKernelSize is one\n    signal input pointBias[nPointFilters];\n\n    signal input pointRemainder[outRows][outCols][nPointFilters];\n    signal input pointOut[outRows][outCols][nPointFilters];\n\n    component depthConv = DepthwiseConv2D(nRows, nCols, nChannels, nDepthFilters, depthKernelSize, strides, n);\n    component pointConv = PointwiseConv2D(outRows, outCols, nDepthFilters, nPointFilters, n);\n\n    for (var filter=0; filter<nDepthFilters; filter++) {\n        for (var x=0; x<depthKernelSize; x++) {\n            for (var y=0; y<depthKernelSize; y++) {\n                depthConv.weights[x][y][filter] <== depthWeights[x][y][filter];\n            }\n        }\n        depthConv.bias[filter] <== depthBias[filter];\n    }\n\n    for (var row=0; row < nRows; row++) {\n        for (var col=0; col < nCols; col++) {\n            for (var channel=0; channel < nChannels; channel++) {\n                depthConv.in[row][col][channel] <== in[row][col][channel];\n            }\n        }\n    }\n    for (var row=0; row < outRows; row++) {\n        for (var col=0; col < outCols; col++) {\n            for (var filter=0; filter < nDepthFilters; filter++) {\n                depthConv.remainder[row][col][filter] <== depthRemainder[row][col][filter];\n                depthConv.out[row][col][filter] <== depthOut[row][col][filter];\n                pointConv.in[row][col][filter] <== depthOut[row][col][filter];\n\n            }\n        }\n    }\n    for (var filter=0; filter < nPointFilters; filter++) {\n        for (var channel=0; channel < nChannels; channel++) {\n            pointConv.weights[channel][filter] <== pointWeights[channel][filter];\n        }\n        pointConv.bias[filter] <== pointBias[filter];\n    }\n    for (var row=0; row < outRows; row++) {\n        for (var col=0; col < outCols; col++) {\n            for (var filter=0; filter < nPointFilters; filter++) {\n                pointConv.remainder[row][col][filter] <== pointRemainder[row][col][filter];\n                pointConv.out[row][col][filter] <== pointOut[row][col][filter];\n            }\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/SumPooling2D.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib-matrix/matElemSum.circom\";\ninclude \"./util.circom\";\n\n// SumPooling2D layer, basically AveragePooling2D layer with a constant scaling, more optimized for circom\ntemplate SumPooling2D (nRows, nCols, nChannels, poolSize, strides) {\n    signal input in[nRows][nCols][nChannels];\n    signal output out[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n\n    component elemSum[(nRows-poolSize)\\strides+1][(nCols-poolSize)\\strides+1][nChannels];\n\n    for (var i=0; i<(nRows-poolSize)\\strides+1; i++) {\n        for (var j=0; j<(nCols-poolSize)\\strides+1; j++) {\n            for (var k=0; k<nChannels; k++) {\n                elemSum[i][j][k] = matElemSum(poolSize,poolSize);\n                for (var x=0; x<poolSize; x++) {\n                    for (var y=0; y<poolSize; y++) {\n                        elemSum[i][j][k].a[x][y] <== in[i*strides+x][j*strides+y][k];\n                    }\n                }\n                out[i][j][k] <== elemSum[i][j][k].out;\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/UpSampling2D.circom",
        "content": "pragma circom 2.0.0;\n\ntemplate UpSampling2D(nRows, nCols, nChannels, size) {\n    signal input in[nRows][nCols][nChannels];\n    signal input out[nRows * size][nCols * size][nChannels];\n\n    // nearest neighbor interpolation\n    for (var i = 0; i < nRows; i++) {\n        for (var j = 0; j < nCols; j++) {\n            for (var c = 0; c < nChannels; c++) {\n                for (var k = 0; k < size; k++) {\n                    for (var l = 0; l < size; l++) {\n                        out[i * size + k][j * size + l][c] === in[i][j][c];\n                    }\n                }\n            }\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Zanh.circom",
        "content": "pragma circom 2.0.0;\n\n// Polynomial approximation for the tanh layer\n// 0.006769816 + 0.554670504 * x - 0.009411195 * x**2 - 0.014187547 * x**3\n// 6769816 + 554670504 * x - 9411195 * x**2 - 14187547 * x**3\n// 6769816 + x * (554670504 - 9411195 * x - 14187547 * x**2)\n// n = 10 to the power of the number of decimal places\n// out and remainder are from division by n**2 so out has the same number of decimal places as in\ntemplate Zanh (n) {\n    signal input in;\n    signal input out;\n    signal input remainder;\n    \n    assert(remainder < (n**2) * (10**9));\n\n    signal tmp;\n\n    tmp <== 554670504 * n**2 - 9411195 * n * in - 14187547 * in * in;\n    // log(6769816 * n**3 + in * tmp);\n    out * (n**2) * (10**9) + remainder === 6769816 * n**3 + in * tmp;\n}\n\n// component main { public [ out ] } = Zanh(10**9);\n\n/* INPUT = {\n    \"in\":  \"123456789\",\n    \"out\": \"750775175\",\n    \"remainder\": \"35162208611038149371400257\"\n} */"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/ZeLU.circom",
        "content": "pragma circom 2.0.0;\n\n// Poly activation layer: https://arxiv.org/abs/2011.05530\n// n = 10 to the power of the number of decimal places\n// out and remainder are from division by n so out has the same number of decimal places as in\ntemplate ZeLU (n) {\n    signal input in;\n    signal input out;\n    signal input remainder;\n\n    assert(remainder < n);\n    \n    signal tmp;\n    tmp <== in * in + n*in;\n    out * n + remainder === tmp;\n}\n\n// component main { public [ out ] } = ZeLU(10**9);\n\n/* INPUT = {\n    \"in\":  \"123456789\",\n    \"out\": \"138698367\",\n    \"remainder\": \"750190521\"\n} */"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/Zigmoid.circom",
        "content": "pragma circom 2.0.0;\n\n// Polynomial approximation for the sigmoid layer\n// 0.502073021 + 0.198695283 * x - 0.001570683 * x**2 - 0.004001354 * x**3\n// 502073021 + 198695283 * x - 1570683 * x**2 - 4001354 * x**3\n// 502073021 + x * (198695283 - 1570683 * x - 4001354 * x**2)\n// n = 10 to the power of the number of decimal places\n// out and remainder are from division by n**2 so out has the same number of decimal places as in\ntemplate Zigmoid (n) {\n    signal input in;\n    signal input out;\n    signal input remainder;\n    \n    assert(remainder < (n**2) * (10**9));\n\n    signal tmp;\n\n    tmp <== 198695283 * n**2 - 1570683 * n * in - 4001354 * in * in;\n    // log(502073021 * n**3 + in * tmp);\n    out * (n**2) * (10**9) + remainder === 502073021 * n**3 + in * tmp;\n}\n\n// component main { public [ out ] } = Zigmoid(10**9);\n\n/* INPUT = {\n    \"in\":  \"123456789\",\n    \"out\": \"526571833\",\n    \"remainder\": \"686713237479944887069368574\"\n} */"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib-matrix/matElemMul.circom",
        "content": "pragma circom 2.0.0;\n\n// matrix multiplication by element\ntemplate matElemMul (m,n) {\n    signal input a[m][n];\n    signal input b[m][n];\n    signal output out[m][n];\n    \n    for (var i=0; i < m; i++) {\n        for (var j=0; j < n; j++) {\n            out[i][j] <== a[i][j] * b[i][j];\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib-matrix/matElemSum.circom",
        "content": "pragma circom 2.0.0;\n\n// sum of all elements in a matrix\ntemplate matElemSum (m,n) {\n    signal input a[m][n];\n    signal output out;\n\n    signal sum[m*n];\n    sum[0] <== a[0][0];\n    var idx = 0;\n    \n    for (var i=0; i < m; i++) {\n        for (var j=0; j < n; j++) {\n            if (idx > 0) {\n                sum[idx] <== sum[idx-1] + a[i][j];\n            }\n            idx++;\n        }\n    }\n\n    out <== sum[m*n-1];\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib-matrix/matMul.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"matElemMul.circom\";\ninclude \"matElemSum.circom\";\n\n// matrix multiplication\ntemplate matMul (m,n,p) {\n    signal input a[m][n];\n    signal input b[n][p];\n    signal output out[m][p];\n\n    component matElemMulComp[m][p];\n    component matElemSumComp[m][p];\n    \n    for (var i=0; i < m; i++) {\n        for (var j=0; j < p; j++) {\n            matElemMulComp[i][j] = matElemMul(1,n);\n            matElemSumComp[i][j] = matElemSum(1,n);\n            for (var k=0; k < n; k++) {      \n                matElemMulComp[i][j].a[0][k] <== a[i][k];\n                matElemMulComp[i][j].b[0][k] <== b[k][j];\n            }\n            for (var k=0; k < n; k++) {\n                matElemSumComp[i][j].a[0][k] <== matElemMulComp[i][j].out[0][k];\n            }\n            out[i][j] <== matElemSumComp[i][j].out;\n        }\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/aliascheck.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"compconstant.circom\";\n\n\ntemplate AliasCheck() {\n\n    signal input in[254];\n\n    component  compConstant = CompConstant(-1);\n\n    for (var i=0; i<254; i++) in[i] ==> compConstant.in[i];\n\n    compConstant.out === 0;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/babyjub.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"bitify.circom\";\ninclude \"escalarmulfix.circom\";\n\ntemplate BabyAdd() {\n    signal input x1;\n    signal input y1;\n    signal input x2;\n    signal input y2;\n    signal output xout;\n    signal output yout;\n\n    signal beta;\n    signal gamma;\n    signal delta;\n    signal tau;\n\n    var a = 168700;\n    var d = 168696;\n\n    beta <== x1*y2;\n    gamma <== y1*x2;\n    delta <== (-a*x1+y1)*(x2 + y2);\n    tau <== beta * gamma;\n\n    xout <-- (beta + gamma) / (1+ d*tau);\n    (1+ d*tau) * xout === (beta + gamma);\n\n    yout <-- (delta + a*beta - gamma) / (1-d*tau);\n    (1-d*tau)*yout === (delta + a*beta - gamma);\n}\n\ntemplate BabyDbl() {\n    signal input x;\n    signal input y;\n    signal output xout;\n    signal output yout;\n\n    component adder = BabyAdd();\n    adder.x1 <== x;\n    adder.y1 <== y;\n    adder.x2 <== x;\n    adder.y2 <== y;\n\n    adder.xout ==> xout;\n    adder.yout ==> yout;\n}\n\n\ntemplate BabyCheck() {\n    signal input x;\n    signal input y;\n\n    signal x2;\n    signal y2;\n\n    var a = 168700;\n    var d = 168696;\n\n    x2 <== x*x;\n    y2 <== y*y;\n\n    a*x2 + y2 === 1 + d*x2*y2;\n}\n\n// Extracts the public key from private key\ntemplate BabyPbk() {\n    signal input  in;\n    signal output Ax;\n    signal output Ay;\n\n    var BASE8[2] = [\n        5299619240641551281634865583518297030282874472190772894086521144482721001553,\n        16950150798460657717958625567821834550301663161624707787222815936182638968203\n    ];\n\n    component pvkBits = Num2Bits(253);\n    pvkBits.in <== in;\n\n    component mulFix = EscalarMulFix(253, BASE8);\n\n    var i;\n    for (i=0; i<253; i++) {\n        mulFix.e[i] <== pvkBits.out[i];\n    }\n    Ax  <== mulFix.out[0];\n    Ay  <== mulFix.out[1];\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/binsum.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/*\n\nBinary Sum\n==========\n\nThis component creates a binary sum componet of ops operands and n bits each operand.\n\ne is Number of carries: Depends on the number of operands in the input.\n\nMain Constraint:\n   in[0][0]     * 2^0  +  in[0][1]     * 2^1  + ..... + in[0][n-1]    * 2^(n-1)  +\n + in[1][0]     * 2^0  +  in[1][1]     * 2^1  + ..... + in[1][n-1]    * 2^(n-1)  +\n + ..\n + in[ops-1][0] * 2^0  +  in[ops-1][1] * 2^1  + ..... + in[ops-1][n-1] * 2^(n-1)  +\n ===\n   out[0] * 2^0  + out[1] * 2^1 +   + out[n+e-1] *2(n+e-1)\n\nTo waranty binary outputs:\n\n    out[0]     * (out[0] - 1) === 0\n    out[1]     * (out[0] - 1) === 0\n    .\n    .\n    .\n    out[n+e-1] * (out[n+e-1] - 1) == 0\n\n */\n\n\n/*\n    This function calculates the number of extra bits in the output to do the full sum.\n */\n pragma circom 2.0.0;\n\nfunction nbits(a) {\n    var n = 1;\n    var r = 0;\n    while (n-1<a) {\n        r++;\n        n *= 2;\n    }\n    return r;\n}\n\n\ntemplate BinSum(n, ops) {\n    var nout = nbits((2**n -1)*ops);\n    signal input in[ops][n];\n    signal output out[nout];\n\n    var lin = 0;\n    var lout = 0;\n\n    var k;\n    var j;\n\n    var e2;\n\n    e2 = 1;\n    for (k=0; k<n; k++) {\n        for (j=0; j<ops; j++) {\n            lin += in[j][k] * e2;\n        }\n        e2 = e2 + e2;\n    }\n\n    e2 = 1;\n    for (k=0; k<nout; k++) {\n        out[k] <-- (lin >> k) & 1;\n\n        // Ensure out is binary\n        out[k] * (out[k] - 1) === 0;\n\n        lout += out[k] * e2;\n\n        e2 = e2+e2;\n    }\n\n    // Ensure the sum;\n\n    lin === lout;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/bitify.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"comparators.circom\";\ninclude \"aliascheck.circom\";\n\n\ntemplate Num2Bits(n) {\n    signal input in;\n    signal output out[n];\n    var lc1=0;\n\n    var e2=1;\n    for (var i = 0; i<n; i++) {\n        out[i] <-- (in >> i) & 1;\n        out[i] * (out[i] -1 ) === 0;\n        lc1 += out[i] * e2;\n        e2 = e2+e2;\n    }\n\n    lc1 === in;\n}\n\ntemplate Num2Bits_strict() {\n    signal input in;\n    signal output out[254];\n\n    component aliasCheck = AliasCheck();\n    component n2b = Num2Bits(254);\n    in ==> n2b.in;\n\n    for (var i=0; i<254; i++) {\n        n2b.out[i] ==> out[i];\n        n2b.out[i] ==> aliasCheck.in[i];\n    }\n}\n\ntemplate Bits2Num(n) {\n    signal input in[n];\n    signal output out;\n    var lc1=0;\n\n    var e2 = 1;\n    for (var i = 0; i<n; i++) {\n        lc1 += in[i] * e2;\n        e2 = e2 + e2;\n    }\n\n    lc1 ==> out;\n}\n\ntemplate Bits2Num_strict() {\n    signal input in[254];\n    signal output out;\n\n    component aliasCheck = AliasCheck();\n    component b2n = Bits2Num(254);\n\n    for (var i=0; i<254; i++) {\n        in[i] ==> b2n.in[i];\n        in[i] ==> aliasCheck.in[i];\n    }\n\n    b2n.out ==> out;\n}\n\ntemplate Num2BitsNeg(n) {\n    signal input in;\n    signal output out[n];\n    var lc1=0;\n\n    component isZero;\n\n    isZero = IsZero();\n\n    var neg = n == 0 ? 0 : 2**n - in;\n\n    for (var i = 0; i<n; i++) {\n        out[i] <-- (neg >> i) & 1;\n        out[i] * (out[i] -1 ) === 0;\n        lc1 += out[i] * 2**i;\n    }\n\n    in ==> isZero.in;\n\n\n\n    lc1 + isZero.out * 2**n === 2**n - in;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/comparators.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"bitify.circom\";\ninclude \"binsum.circom\";\n\ntemplate IsZero() {\n    signal input in;\n    signal output out;\n\n    signal inv;\n\n    inv <-- in!=0 ? 1/in : 0;\n\n    out <== -in*inv +1;\n    in*out === 0;\n}\n\n\ntemplate IsEqual() {\n    signal input in[2];\n    signal output out;\n\n    component isz = IsZero();\n\n    in[1] - in[0] ==> isz.in;\n\n    isz.out ==> out;\n}\n\ntemplate ForceEqualIfEnabled() {\n    signal input enabled;\n    signal input in[2];\n\n    component isz = IsZero();\n\n    in[1] - in[0] ==> isz.in;\n\n    (1 - isz.out)*enabled === 0;\n}\n\n/*\n// N is the number of bits the input  have.\n// The MSF is the sign bit.\ntemplate LessThan(n) {\n    signal input in[2];\n    signal output out;\n\n    component num2Bits0;\n    component num2Bits1;\n\n    component adder;\n\n    adder = BinSum(n, 2);\n\n    num2Bits0 = Num2Bits(n);\n    num2Bits1 = Num2BitsNeg(n);\n\n    in[0] ==> num2Bits0.in;\n    in[1] ==> num2Bits1.in;\n\n    var i;\n    for (i=0;i<n;i++) {\n        num2Bits0.out[i] ==> adder.in[0][i];\n        num2Bits1.out[i] ==> adder.in[1][i];\n    }\n\n    adder.out[n-1] ==> out;\n}\n*/\n\ntemplate LessThan(n) {\n    assert(n <= 252);\n    signal input in[2];\n    signal output out;\n\n    component n2b = Num2Bits(n+1);\n\n    n2b.in <== in[0]+ (1<<n) - in[1];\n\n    out <== 1-n2b.out[n];\n}\n\n\n\n// N is the number of bits the input  have.\n// The MSF is the sign bit.\ntemplate LessEqThan(n) {\n    signal input in[2];\n    signal output out;\n\n    component lt = LessThan(n);\n\n    lt.in[0] <== in[0];\n    lt.in[1] <== in[1]+1;\n    lt.out ==> out;\n}\n\n// N is the number of bits the input  have.\n// The MSF is the sign bit.\ntemplate GreaterThan(n) {\n    signal input in[2];\n    signal output out;\n\n    component lt = LessThan(n);\n\n    lt.in[0] <== in[1];\n    lt.in[1] <== in[0];\n    lt.out ==> out;\n}\n\n// N is the number of bits the input  have.\n// The MSF is the sign bit.\ntemplate GreaterEqThan(n) {\n    signal input in[2];\n    signal output out;\n\n    component lt = LessThan(n);\n\n    lt.in[0] <== in[1];\n    lt.in[1] <== in[0]+1;\n    lt.out ==> out;\n}\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/compconstant.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"bitify.circom\";\n\n// Returns 1 if in (in binary) > ct\n\ntemplate CompConstant(ct) {\n    signal input in[254];\n    signal output out;\n\n    signal parts[127];\n    signal sout;\n\n    var clsb;\n    var cmsb;\n    var slsb;\n    var smsb;\n\n    var sum=0;\n\n    var b = (1 << 128) -1;\n    var a = 1;\n    var e = 1;\n    var i;\n\n    for (i=0;i<127; i++) {\n        clsb = (ct >> (i*2)) & 1;\n        cmsb = (ct >> (i*2+1)) & 1;\n        slsb = in[i*2];\n        smsb = in[i*2+1];\n\n        if ((cmsb==0)&&(clsb==0)) {\n            parts[i] <== -b*smsb*slsb + b*smsb + b*slsb;\n        } else if ((cmsb==0)&&(clsb==1)) {\n            parts[i] <== a*smsb*slsb - a*slsb + b*smsb - a*smsb + a;\n        } else if ((cmsb==1)&&(clsb==0)) {\n            parts[i] <== b*smsb*slsb - a*smsb + a;\n        } else {\n            parts[i] <== -a*smsb*slsb + a;\n        }\n\n        sum = sum + parts[i];\n\n        b = b -e;\n        a = a +e;\n        e = e*2;\n    }\n\n    sout <== sum;\n\n    component num2bits = Num2Bits(135);\n\n    num2bits.in <== sout;\n\n    out <== num2bits.out[127];\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/escalarmulany.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"montgomery.circom\";\ninclude \"babyjub.circom\";\ninclude \"comparators.circom\";\n\ntemplate Multiplexor2() {\n    signal input sel;\n    signal input in[2][2];\n    signal output out[2];\n\n    out[0] <== (in[1][0] - in[0][0])*sel + in[0][0];\n    out[1] <== (in[1][1] - in[0][1])*sel + in[0][1];\n}\n\ntemplate BitElementMulAny() {\n    signal input sel;\n    signal input dblIn[2];\n    signal input addIn[2];\n    signal output dblOut[2];\n    signal output addOut[2];\n\n    component doubler = MontgomeryDouble();\n    component adder = MontgomeryAdd();\n    component selector = Multiplexor2();\n\n\n    sel ==> selector.sel;\n\n    dblIn[0] ==> doubler.in[0];\n    dblIn[1] ==> doubler.in[1];\n    doubler.out[0] ==> adder.in1[0];\n    doubler.out[1] ==> adder.in1[1];\n    addIn[0] ==> adder.in2[0];\n    addIn[1] ==> adder.in2[1];\n    addIn[0] ==> selector.in[0][0];\n    addIn[1] ==> selector.in[0][1];\n    adder.out[0] ==> selector.in[1][0];\n    adder.out[1] ==> selector.in[1][1];\n\n    doubler.out[0] ==> dblOut[0];\n    doubler.out[1] ==> dblOut[1];\n    selector.out[0] ==> addOut[0];\n    selector.out[1] ==> addOut[1];\n}\n\n// p is montgomery point\n// n must be <= 248\n// returns out in twisted edwards\n// Double is in montgomery to be linked;\n\ntemplate SegmentMulAny(n) {\n    signal input e[n];\n    signal input p[2];\n    signal output out[2];\n    signal output dbl[2];\n\n    component bits[n-1];\n\n    component e2m = Edwards2Montgomery();\n\n    p[0] ==> e2m.in[0];\n    p[1] ==> e2m.in[1];\n\n    var i;\n\n    bits[0] = BitElementMulAny();\n    e2m.out[0] ==> bits[0].dblIn[0];\n    e2m.out[1] ==> bits[0].dblIn[1];\n    e2m.out[0] ==> bits[0].addIn[0];\n    e2m.out[1] ==> bits[0].addIn[1];\n    e[1] ==> bits[0].sel;\n\n    for (i=1; i<n-1; i++) {\n        bits[i] = BitElementMulAny();\n\n        bits[i-1].dblOut[0] ==> bits[i].dblIn[0];\n        bits[i-1].dblOut[1] ==> bits[i].dblIn[1];\n        bits[i-1].addOut[0] ==> bits[i].addIn[0];\n        bits[i-1].addOut[1] ==> bits[i].addIn[1];\n        e[i+1] ==> bits[i].sel;\n    }\n\n    bits[n-2].dblOut[0] ==> dbl[0];\n    bits[n-2].dblOut[1] ==> dbl[1];\n\n    component m2e = Montgomery2Edwards();\n\n    bits[n-2].addOut[0] ==> m2e.in[0];\n    bits[n-2].addOut[1] ==> m2e.in[1];\n\n    component eadder = BabyAdd();\n\n    m2e.out[0] ==> eadder.x1;\n    m2e.out[1] ==> eadder.y1;\n    -p[0] ==> eadder.x2;\n    p[1] ==> eadder.y2;\n\n    component lastSel = Multiplexor2();\n\n    e[0] ==> lastSel.sel;\n    eadder.xout ==> lastSel.in[0][0];\n    eadder.yout ==> lastSel.in[0][1];\n    m2e.out[0] ==> lastSel.in[1][0];\n    m2e.out[1] ==> lastSel.in[1][1];\n\n    lastSel.out[0] ==> out[0];\n    lastSel.out[1] ==> out[1];\n}\n\n// This function assumes that p is in the subgroup and it is different to 0\n\ntemplate EscalarMulAny(n) {\n    signal input e[n];              // Input in binary format\n    signal input p[2];              // Point (Twisted format)\n    signal output out[2];           // Point (Twisted format)\n\n    var nsegments = (n-1)\\148 +1;\n    var nlastsegment = n - (nsegments-1)*148;\n\n    component segments[nsegments];\n    component doublers[nsegments-1];\n    component m2e[nsegments-1];\n    component adders[nsegments-1];\n    component zeropoint = IsZero();\n    zeropoint.in <== p[0];\n\n    var s;\n    var i;\n    var nseg;\n\n    for (s=0; s<nsegments; s++) {\n\n        nseg = (s < nsegments-1) ? 148 : nlastsegment;\n\n        segments[s] = SegmentMulAny(nseg);\n\n        for (i=0; i<nseg; i++) {\n            e[s*148+i] ==> segments[s].e[i];\n        }\n\n        if (s==0) {\n            // force G8 point if input point is zero\n            segments[s].p[0] <== p[0] + (5299619240641551281634865583518297030282874472190772894086521144482721001553 - p[0])*zeropoint.out;\n            segments[s].p[1] <== p[1] + (16950150798460657717958625567821834550301663161624707787222815936182638968203 - p[1])*zeropoint.out;\n        } else {\n            doublers[s-1] = MontgomeryDouble();\n            m2e[s-1] = Montgomery2Edwards();\n            adders[s-1] = BabyAdd();\n\n            segments[s-1].dbl[0] ==> doublers[s-1].in[0];\n            segments[s-1].dbl[1] ==> doublers[s-1].in[1];\n\n            doublers[s-1].out[0] ==> m2e[s-1].in[0];\n            doublers[s-1].out[1] ==> m2e[s-1].in[1];\n\n            m2e[s-1].out[0] ==> segments[s].p[0];\n            m2e[s-1].out[1] ==> segments[s].p[1];\n\n            if (s==1) {\n                segments[s-1].out[0] ==> adders[s-1].x1;\n                segments[s-1].out[1] ==> adders[s-1].y1;\n            } else {\n                adders[s-2].xout ==> adders[s-1].x1;\n                adders[s-2].yout ==> adders[s-1].y1;\n            }\n            segments[s].out[0] ==> adders[s-1].x2;\n            segments[s].out[1] ==> adders[s-1].y2;\n        }\n    }\n\n    if (nsegments == 1) {\n        segments[0].out[0]*(1-zeropoint.out) ==> out[0];\n        segments[0].out[1]+(1-segments[0].out[1])*zeropoint.out ==> out[1];\n    } else {\n        adders[nsegments-2].xout*(1-zeropoint.out) ==> out[0];\n        adders[nsegments-2].yout+(1-adders[nsegments-2].yout)*zeropoint.out ==> out[1];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/escalarmulfix.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"mux3.circom\";\ninclude \"montgomery.circom\";\ninclude \"babyjub.circom\";\n\n/*\n    Window of 3 elements, it calculates\n        out = base + base*in[0] + 2*base*in[1] + 4*base*in[2]\n        out4 = 4*base\n\n    The result should be compensated.\n */\n\n/*\n\n    The scalar is s = a0 + a1*2^3 + a2*2^6 + ...... + a81*2^243\n    First We calculate Q = B + 2^3*B + 2^6*B + ......... + 2^246*B\n\n    Then we calculate S1 = 2*2^246*B + (1 + a0)*B + (2^3 + a1)*B + .....+ (2^243 + a81)*B\n\n    And Finaly we compute the result: RES = SQ - Q\n\n    As you can see the input of the adders cannot be equal nor zero, except for the last\n    substraction that it's done in montgomery.\n\n    A good way to see it is that the accumulator input of the adder >= 2^247*B and the other input\n    is the output of the windows that it's going to be <= 2^246*B\n */\ntemplate WindowMulFix() {\n    signal input in[3];\n    signal input base[2];\n    signal output out[2];\n    signal output out8[2];   // Returns 8*Base (To be linked)\n\n    component mux = MultiMux3(2);\n\n    mux.s[0] <== in[0];\n    mux.s[1] <== in[1];\n    mux.s[2] <== in[2];\n\n    component dbl2 = MontgomeryDouble();\n    component adr3 = MontgomeryAdd();\n    component adr4 = MontgomeryAdd();\n    component adr5 = MontgomeryAdd();\n    component adr6 = MontgomeryAdd();\n    component adr7 = MontgomeryAdd();\n    component adr8 = MontgomeryAdd();\n\n// in[0]  -> 1*BASE\n\n    mux.c[0][0] <== base[0];\n    mux.c[1][0] <== base[1];\n\n// in[1] -> 2*BASE\n    dbl2.in[0] <== base[0];\n    dbl2.in[1] <== base[1];\n    mux.c[0][1] <== dbl2.out[0];\n    mux.c[1][1] <== dbl2.out[1];\n\n// in[2] -> 3*BASE\n    adr3.in1[0] <== base[0];\n    adr3.in1[1] <== base[1];\n    adr3.in2[0] <== dbl2.out[0];\n    adr3.in2[1] <== dbl2.out[1];\n    mux.c[0][2] <== adr3.out[0];\n    mux.c[1][2] <== adr3.out[1];\n\n// in[3] -> 4*BASE\n    adr4.in1[0] <== base[0];\n    adr4.in1[1] <== base[1];\n    adr4.in2[0] <== adr3.out[0];\n    adr4.in2[1] <== adr3.out[1];\n    mux.c[0][3] <== adr4.out[0];\n    mux.c[1][3] <== adr4.out[1];\n\n// in[4] -> 5*BASE\n    adr5.in1[0] <== base[0];\n    adr5.in1[1] <== base[1];\n    adr5.in2[0] <== adr4.out[0];\n    adr5.in2[1] <== adr4.out[1];\n    mux.c[0][4] <== adr5.out[0];\n    mux.c[1][4] <== adr5.out[1];\n\n// in[5] -> 6*BASE\n    adr6.in1[0] <== base[0];\n    adr6.in1[1] <== base[1];\n    adr6.in2[0] <== adr5.out[0];\n    adr6.in2[1] <== adr5.out[1];\n    mux.c[0][5] <== adr6.out[0];\n    mux.c[1][5] <== adr6.out[1];\n\n// in[6] -> 7*BASE\n    adr7.in1[0] <== base[0];\n    adr7.in1[1] <== base[1];\n    adr7.in2[0] <== adr6.out[0];\n    adr7.in2[1] <== adr6.out[1];\n    mux.c[0][6] <== adr7.out[0];\n    mux.c[1][6] <== adr7.out[1];\n\n// in[7] -> 8*BASE\n    adr8.in1[0] <== base[0];\n    adr8.in1[1] <== base[1];\n    adr8.in2[0] <== adr7.out[0];\n    adr8.in2[1] <== adr7.out[1];\n    mux.c[0][7] <== adr8.out[0];\n    mux.c[1][7] <== adr8.out[1];\n\n    out8[0] <== adr8.out[0];\n    out8[1] <== adr8.out[1];\n\n    out[0] <== mux.out[0];\n    out[1] <== mux.out[1];\n}\n\n\n/*\n    This component does a multiplication of a escalar times a fix base\n    Signals:\n        e: The scalar in bits\n        base: the base point in edwards format\n        out:  The result\n        dbl: Point in Edwards to be linked to the next segment.\n */\n\ntemplate SegmentMulFix(nWindows) {\n    signal input e[nWindows*3];\n    signal input base[2];\n    signal output out[2];\n    signal output dbl[2];\n\n    var i;\n    var j;\n\n    // Convert the base to montgomery\n\n    component e2m = Edwards2Montgomery();\n    e2m.in[0] <== base[0];\n    e2m.in[1] <== base[1];\n\n    component windows[nWindows];\n    component adders[nWindows];\n    component cadders[nWindows];\n\n    // In the last step we add an extra doubler so that numbers do not match.\n    component dblLast = MontgomeryDouble();\n\n    for (i=0; i<nWindows; i++) {\n        windows[i] = WindowMulFix();\n        cadders[i] = MontgomeryAdd();\n        if (i==0) {\n            windows[i].base[0] <== e2m.out[0];\n            windows[i].base[1] <== e2m.out[1];\n            cadders[i].in1[0] <== e2m.out[0];\n            cadders[i].in1[1] <== e2m.out[1];\n        } else {\n            windows[i].base[0] <== windows[i-1].out8[0];\n            windows[i].base[1] <== windows[i-1].out8[1];\n            cadders[i].in1[0] <== cadders[i-1].out[0];\n            cadders[i].in1[1] <== cadders[i-1].out[1];\n        }\n        for (j=0; j<3; j++) {\n            windows[i].in[j] <== e[3*i+j];\n        }\n        if (i<nWindows-1) {\n            cadders[i].in2[0] <== windows[i].out8[0];\n            cadders[i].in2[1] <== windows[i].out8[1];\n        } else {\n            dblLast.in[0] <== windows[i].out8[0];\n            dblLast.in[1] <== windows[i].out8[1];\n            cadders[i].in2[0] <== dblLast.out[0];\n            cadders[i].in2[1] <== dblLast.out[1];\n        }\n    }\n\n    for (i=0; i<nWindows; i++) {\n        adders[i] = MontgomeryAdd();\n        if (i==0) {\n            adders[i].in1[0] <== dblLast.out[0];\n            adders[i].in1[1] <== dblLast.out[1];\n        } else {\n            adders[i].in1[0] <== adders[i-1].out[0];\n            adders[i].in1[1] <== adders[i-1].out[1];\n        }\n        adders[i].in2[0] <== windows[i].out[0];\n        adders[i].in2[1] <== windows[i].out[1];\n    }\n\n    component m2e = Montgomery2Edwards();\n    component cm2e = Montgomery2Edwards();\n\n    m2e.in[0] <== adders[nWindows-1].out[0];\n    m2e.in[1] <== adders[nWindows-1].out[1];\n    cm2e.in[0] <== cadders[nWindows-1].out[0];\n    cm2e.in[1] <== cadders[nWindows-1].out[1];\n\n    component cAdd = BabyAdd();\n    cAdd.x1 <== m2e.out[0];\n    cAdd.y1 <== m2e.out[1];\n    cAdd.x2 <== -cm2e.out[0];\n    cAdd.y2 <== cm2e.out[1];\n\n    cAdd.xout ==> out[0];\n    cAdd.yout ==> out[1];\n\n    windows[nWindows-1].out8[0] ==> dbl[0];\n    windows[nWindows-1].out8[1] ==> dbl[1];\n}\n\n\n/*\nThis component multiplies a escalar times a fixed point BASE (twisted edwards format)\n    Signals\n        e: The escalar in binary format\n        out: The output point in twisted edwards\n */\ntemplate EscalarMulFix(n, BASE) {\n    signal input e[n];              // Input in binary format\n    signal output out[2];           // Point (Twisted format)\n\n    var nsegments = (n-1)\\246 +1;       // 249 probably would work. But I'm not sure and for security I keep 246\n    var nlastsegment = n - (nsegments-1)*249;\n\n    component segments[nsegments];\n\n    component m2e[nsegments-1];\n    component adders[nsegments-1];\n\n    var s;\n    var i;\n    var nseg;\n    var nWindows;\n\n    for (s=0; s<nsegments; s++) {\n\n        nseg = (s < nsegments-1) ? 249 : nlastsegment;\n        nWindows = ((nseg - 1)\\3)+1;\n\n        segments[s] = SegmentMulFix(nWindows);\n\n        for (i=0; i<nseg; i++) {\n            segments[s].e[i] <== e[s*249+i];\n        }\n\n        for (i = nseg; i<nWindows*3; i++) {\n            segments[s].e[i] <== 0;\n        }\n\n        if (s==0) {\n            segments[s].base[0] <== BASE[0];\n            segments[s].base[1] <== BASE[1];\n        } else {\n            m2e[s-1] = Montgomery2Edwards();\n            adders[s-1] = BabyAdd();\n\n            segments[s-1].dbl[0] ==> m2e[s-1].in[0];\n            segments[s-1].dbl[1] ==> m2e[s-1].in[1];\n\n            m2e[s-1].out[0] ==> segments[s].base[0];\n            m2e[s-1].out[1] ==> segments[s].base[1];\n\n            if (s==1) {\n                segments[s-1].out[0] ==> adders[s-1].x1;\n                segments[s-1].out[1] ==> adders[s-1].y1;\n            } else {\n                adders[s-2].xout ==> adders[s-1].x1;\n                adders[s-2].yout ==> adders[s-1].y1;\n            }\n            segments[s].out[0] ==> adders[s-1].x2;\n            segments[s].out[1] ==> adders[s-1].y2;\n        }\n    }\n\n    if (nsegments == 1) {\n        segments[0].out[0] ==> out[0];\n        segments[0].out[1] ==> out[1];\n    } else {\n        adders[nsegments-2].xout ==> out[0];\n        adders[nsegments-2].yout ==> out[1];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/mimc.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ntemplate MiMC7(nrounds) {\n    signal input x_in;\n    signal input k;\n    signal output out;\n\n    var c[91] = [\n        0,\n        20888961410941983456478427210666206549300505294776164667214940546594746570981,\n        15265126113435022738560151911929040668591755459209400716467504685752745317193,\n        8334177627492981984476504167502758309043212251641796197711684499645635709656,\n        1374324219480165500871639364801692115397519265181803854177629327624133579404,\n        11442588683664344394633565859260176446561886575962616332903193988751292992472,\n        2558901189096558760448896669327086721003508630712968559048179091037845349145,\n        11189978595292752354820141775598510151189959177917284797737745690127318076389,\n        3262966573163560839685415914157855077211340576201936620532175028036746741754,\n        17029914891543225301403832095880481731551830725367286980611178737703889171730,\n        4614037031668406927330683909387957156531244689520944789503628527855167665518,\n        19647356996769918391113967168615123299113119185942498194367262335168397100658,\n        5040699236106090655289931820723926657076483236860546282406111821875672148900,\n        2632385916954580941368956176626336146806721642583847728103570779270161510514,\n        17691411851977575435597871505860208507285462834710151833948561098560743654671,\n        11482807709115676646560379017491661435505951727793345550942389701970904563183,\n        8360838254132998143349158726141014535383109403565779450210746881879715734773,\n        12663821244032248511491386323242575231591777785787269938928497649288048289525,\n        3067001377342968891237590775929219083706800062321980129409398033259904188058,\n        8536471869378957766675292398190944925664113548202769136103887479787957959589,\n        19825444354178182240559170937204690272111734703605805530888940813160705385792,\n        16703465144013840124940690347975638755097486902749048533167980887413919317592,\n        13061236261277650370863439564453267964462486225679643020432589226741411380501,\n        10864774797625152707517901967943775867717907803542223029967000416969007792571,\n        10035653564014594269791753415727486340557376923045841607746250017541686319774,\n        3446968588058668564420958894889124905706353937375068998436129414772610003289,\n        4653317306466493184743870159523234588955994456998076243468148492375236846006,\n        8486711143589723036499933521576871883500223198263343024003617825616410932026,\n        250710584458582618659378487568129931785810765264752039738223488321597070280,\n        2104159799604932521291371026105311735948154964200596636974609406977292675173,\n        16313562605837709339799839901240652934758303521543693857533755376563489378839,\n        6032365105133504724925793806318578936233045029919447519826248813478479197288,\n        14025118133847866722315446277964222215118620050302054655768867040006542798474,\n        7400123822125662712777833064081316757896757785777291653271747396958201309118,\n        1744432620323851751204287974553233986555641872755053103823939564833813704825,\n        8316378125659383262515151597439205374263247719876250938893842106722210729522,\n        6739722627047123650704294650168547689199576889424317598327664349670094847386,\n        21211457866117465531949733809706514799713333930924902519246949506964470524162,\n        13718112532745211817410303291774369209520657938741992779396229864894885156527,\n        5264534817993325015357427094323255342713527811596856940387954546330728068658,\n        18884137497114307927425084003812022333609937761793387700010402412840002189451,\n        5148596049900083984813839872929010525572543381981952060869301611018636120248,\n        19799686398774806587970184652860783461860993790013219899147141137827718662674,\n        19240878651604412704364448729659032944342952609050243268894572835672205984837,\n        10546185249390392695582524554167530669949955276893453512788278945742408153192,\n        5507959600969845538113649209272736011390582494851145043668969080335346810411,\n        18177751737739153338153217698774510185696788019377850245260475034576050820091,\n        19603444733183990109492724100282114612026332366576932662794133334264283907557,\n        10548274686824425401349248282213580046351514091431715597441736281987273193140,\n        1823201861560942974198127384034483127920205835821334101215923769688644479957,\n        11867589662193422187545516240823411225342068709600734253659804646934346124945,\n        18718569356736340558616379408444812528964066420519677106145092918482774343613,\n        10530777752259630125564678480897857853807637120039176813174150229243735996839,\n        20486583726592018813337145844457018474256372770211860618687961310422228379031,\n        12690713110714036569415168795200156516217175005650145422920562694422306200486,\n        17386427286863519095301372413760745749282643730629659997153085139065756667205,\n        2216432659854733047132347621569505613620980842043977268828076165669557467682,\n        6309765381643925252238633914530877025934201680691496500372265330505506717193,\n        20806323192073945401862788605803131761175139076694468214027227878952047793390,\n        4037040458505567977365391535756875199663510397600316887746139396052445718861,\n        19948974083684238245321361840704327952464170097132407924861169241740046562673,\n        845322671528508199439318170916419179535949348988022948153107378280175750024,\n        16222384601744433420585982239113457177459602187868460608565289920306145389382,\n        10232118865851112229330353999139005145127746617219324244541194256766741433339,\n        6699067738555349409504843460654299019000594109597429103342076743347235369120,\n        6220784880752427143725783746407285094967584864656399181815603544365010379208,\n        6129250029437675212264306655559561251995722990149771051304736001195288083309,\n        10773245783118750721454994239248013870822765715268323522295722350908043393604,\n        4490242021765793917495398271905043433053432245571325177153467194570741607167,\n        19596995117319480189066041930051006586888908165330319666010398892494684778526,\n        837850695495734270707668553360118467905109360511302468085569220634750561083,\n        11803922811376367215191737026157445294481406304781326649717082177394185903907,\n        10201298324909697255105265958780781450978049256931478989759448189112393506592,\n        13564695482314888817576351063608519127702411536552857463682060761575100923924,\n        9262808208636973454201420823766139682381973240743541030659775288508921362724,\n        173271062536305557219323722062711383294158572562695717740068656098441040230,\n        18120430890549410286417591505529104700901943324772175772035648111937818237369,\n        20484495168135072493552514219686101965206843697794133766912991150184337935627,\n        19155651295705203459475805213866664350848604323501251939850063308319753686505,\n        11971299749478202793661982361798418342615500543489781306376058267926437157297,\n        18285310723116790056148596536349375622245669010373674803854111592441823052978,\n        7069216248902547653615508023941692395371990416048967468982099270925308100727,\n        6465151453746412132599596984628739550147379072443683076388208843341824127379,\n        16143532858389170960690347742477978826830511669766530042104134302796355145785,\n        19362583304414853660976404410208489566967618125972377176980367224623492419647,\n        1702213613534733786921602839210290505213503664731919006932367875629005980493,\n        10781825404476535814285389902565833897646945212027592373510689209734812292327,\n        4212716923652881254737947578600828255798948993302968210248673545442808456151,\n        7594017890037021425366623750593200398174488805473151513558919864633711506220,\n        18979889247746272055963929241596362599320706910852082477600815822482192194401,\n        13602139229813231349386885113156901793661719180900395818909719758150455500533\n    ];\n\n    var t;\n    signal t2[nrounds];\n    signal t4[nrounds];\n    signal t6[nrounds];\n    signal t7[nrounds-1];\n\n    for (var i=0; i<nrounds; i++) {\n        t = (i==0) ? k+x_in : k + t7[i-1] + c[i];\n        t2[i] <== t*t;\n        t4[i] <== t2[i]*t2[i];\n        t6[i] <== t4[i]*t2[i];\n        if (i<nrounds-1) {\n            t7[i] <== t6[i]*t;\n        } else {\n            out <== t6[i]*t + k;\n        }\n    }\n}\n\ntemplate MultiMiMC7(nInputs, nRounds) {\n    signal input in[nInputs];\n    signal input k;\n    signal output out;\n    signal r[nInputs +1];\n\n    component mims[nInputs];\n\n    r[0] <== k;\n    for (var i=0; i<nInputs; i++) {\n        mims[i] = MiMC7(nRounds);\n        mims[i].x_in <== in[i];\n        mims[i].k <== r[i];\n        r[i+1] <== r[i] + in[i] + mims[i].out;\n    }\n\n    out <== r[nInputs];\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/montgomery.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/*\n    Source: https://en.wikipedia.org/wiki/Montgomery_curve\n\n                1 + y       1 + y\n    [u, v] = [ -------  , ---------- ]\n                1 - y      (1 - y)x\n\n */\n pragma circom 2.0.0;\n\ntemplate Edwards2Montgomery() {\n    signal input in[2];\n    signal output out[2];\n\n    out[0] <-- (1 + in[1]) / (1 - in[1]);\n    out[1] <-- out[0] / in[0];\n\n\n    out[0] * (1-in[1]) === (1 + in[1]);\n    out[1] * in[0] === out[0];\n}\n\n/*\n\n                u    u - 1\n    [x, y] = [ ---, ------- ]\n                v    u + 1\n\n */\ntemplate Montgomery2Edwards() {\n    signal input in[2];\n    signal output out[2];\n\n    out[0] <-- in[0] / in[1];\n    out[1] <-- (in[0] - 1) / (in[0] + 1);\n\n    out[0] * in[1] === in[0];\n    out[1] * (in[0] + 1) === in[0] - 1;\n}\n\n\n/*\n             x2 - x1\n    lamda = ---------\n             y2 - y1\n\n                                                    x3 + A + x1 + x2\n    x3 = B * lamda^2 - A - x1 -x2    =>  lamda^2 = ------------------\n                                                         B\n\n    y3 = (2*x1 + x2 + A)*lamda - B*lamda^3 - y1  =>\n\n\n    =>  y3 = lamda * ( 2*x1 + x2 + A  - x3 - A - x1 - x2)  - y1 =>\n\n    =>  y3 = lamda * ( x1 - x3 ) - y1\n\n----------\n\n             y2 - y1\n    lamda = ---------\n             x2 - x1\n\n    x3 = B * lamda^2 - A - x1 -x2\n\n    y3 = lamda * ( x1 - x3 ) - y1\n\n */\n\ntemplate MontgomeryAdd() {\n    signal input in1[2];\n    signal input in2[2];\n    signal output out[2];\n\n    var a = 168700;\n    var d = 168696;\n\n    var A = (2 * (a + d)) / (a - d);\n    var B = 4 / (a - d);\n\n    signal lamda;\n\n    lamda <-- (in2[1] - in1[1]) / (in2[0] - in1[0]);\n    lamda * (in2[0] - in1[0]) === (in2[1] - in1[1]);\n\n    out[0] <== B*lamda*lamda - A - in1[0] -in2[0];\n    out[1] <== lamda * (in1[0] - out[0]) - in1[1];\n}\n\n/*\n\n    x1_2 = x1*x1\n\n             3*x1_2 + 2*A*x1 + 1\n    lamda = ---------------------\n                   2*B*y1\n\n    x3 = B * lamda^2 - A - x1 -x1\n\n    y3 = lamda * ( x1 - x3 ) - y1\n\n */\ntemplate MontgomeryDouble() {\n    signal input in[2];\n    signal output out[2];\n\n    var a = 168700;\n    var d = 168696;\n\n    var A = (2 * (a + d)) / (a - d);\n    var B = 4 / (a - d);\n\n    signal lamda;\n    signal x1_2;\n\n    x1_2 <== in[0] * in[0];\n\n    lamda <-- (3*x1_2 + 2*A*in[0] + 1 ) / (2*B*in[1]);\n    lamda * (2*B*in[1]) === (3*x1_2 + 2*A*in[0] + 1 );\n\n    out[0] <== B*lamda*lamda - A - 2*in[0];\n    out[1] <== lamda * (in[0] - out[0]) - in[1];\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/mux3.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ntemplate MultiMux3(n) {\n    signal input c[n][8];  // Constants\n    signal input s[3];   // Selector\n    signal output out[n];\n\n    signal a210[n];\n    signal a21[n];\n    signal a20[n];\n    signal a2[n];\n\n    signal a10[n];\n    signal a1[n];\n    signal a0[n];\n    signal a[n];\n\n    // 4 constrains for the intermediary variables\n    signal  s10;\n    s10 <== s[1] * s[0];\n\n    for (var i=0; i<n; i++) {\n\n         a210[i] <==  ( c[i][ 7]-c[i][ 6]-c[i][ 5]+c[i][ 4] - c[i][ 3]+c[i][ 2]+c[i][ 1]-c[i][ 0] ) * s10;\n          a21[i] <==  ( c[i][ 6]-c[i][ 4]-c[i][ 2]+c[i][ 0] ) * s[1];\n          a20[i] <==  ( c[i][ 5]-c[i][ 4]-c[i][ 1]+c[i][ 0] ) * s[0];\n           a2[i] <==  ( c[i][ 4]-c[i][ 0] );\n\n          a10[i] <==  ( c[i][ 3]-c[i][ 2]-c[i][ 1]+c[i][ 0] ) * s10;\n           a1[i] <==  ( c[i][ 2]-c[i][ 0] ) * s[1];\n           a0[i] <==  ( c[i][ 1]-c[i][ 0] ) * s[0];\n            a[i] <==  ( c[i][ 0] );\n\n          out[i] <== ( a210[i] + a21[i] + a20[i] + a2[i] ) * s[2] +\n                     (  a10[i] +  a1[i] +  a0[i] +  a[i] );\n\n    }\n}\n\ntemplate Mux3() {\n    var i;\n    signal input c[8];  // Constants\n    signal input s[3];   // Selector\n    signal output out;\n\n    component mux = MultiMux3(1);\n\n    for (i=0; i<8; i++) {\n        mux.c[0][i] <== c[i];\n    }\n\n    for (i=0; i<3; i++) {\n      s[i] ==> mux.s[i];\n    }\n\n    mux.out[0] ==> out;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/sign.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"compconstant.circom\";\n\ntemplate Sign() {\n    signal input in[254];\n    signal output sign;\n\n    component comp = CompConstant(10944121435919637611123202872628637544274182200208017171849102093287904247808);\n\n    var i;\n\n    for (i=0; i<254; i++) {\n        comp.in[i] <== in[i];\n    }\n\n    sign <== comp.out;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/circomlib/switcher.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/*\n    Assume sel is binary.\n\n    If sel == 0 then outL = L and outR=R\n    If sel == 1 then outL = R and outR=L\n\n */\n \npragma circom 2.0.0;\n\ntemplate Switcher() {\n    signal input sel;\n    signal input L;\n    signal input R;\n    signal output outL;\n    signal output outR;\n\n    signal aux;\n\n    aux <== (R-L)*sel;    // We create aux in order to have only one multiplication\n    outL <==  aux + L;\n    outR <== -aux + R;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/crypto/ecdh.circom",
        "content": "// from privacy-scaling-explorations/maci\n\npragma circom 2.0.0;\n\ninclude \"../circomlib/bitify.circom\";\ninclude \"../circomlib/escalarmulany.circom\";\n\ntemplate Ecdh() {\n  // Note: private key\n  // Needs to be hashed, and then pruned before\n  // supplying it to the circuit\n  signal input private_key;\n  signal input public_key[2];\n\n  signal output shared_key;\n\n  component privBits = Num2Bits(253);\n  privBits.in <== private_key;\n\n  component mulFix = EscalarMulAny(253);\n  mulFix.p[0] <== public_key[0];\n  mulFix.p[1] <== public_key[1];\n\n  for (var i = 0; i < 253; i++) {\n    mulFix.e[i] <== privBits.out[i];\n  }\n\n  shared_key <== mulFix.out[0];\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/crypto/encrypt.circom",
        "content": "//from zk-ml/linear-regression-demo\n\npragma circom 2.0.0;\n\ninclude \"../circomlib/mimc.circom\";\n\ntemplate EncryptBits(N) {\n  signal input plaintext[N];\n  signal input shared_key;\n  signal output out[N+1];\n\n  component mimc = MultiMiMC7(N, 91);\n  for (var i=0; i<N; i++) {\n    mimc.in[i] <== plaintext[i];\n  }\n  mimc.k <== 0;\n  out[0] <== mimc.out;\n\n  component hasher[N];\n  for(var i=0; i<N; i++) {\n    hasher[i] = MiMC7(91);\n    hasher[i].x_in <== shared_key;\n    hasher[i].k <== out[0] + i;\n    out[i+1] <== plaintext[i] + hasher[i].out;\n  }\n}\n\ntemplate Encrypt() {\n  signal input plaintext;\n  signal input shared_key;\n  signal output out[2];\n\n  component mimc = MultiMiMC7(1, 91);\n  mimc.in[0] <== plaintext;\n  mimc.k <== 0;\n  out[0] <== mimc.out;\n\n  component hasher;\n  hasher = MiMC7(91);\n  hasher.x_in <== shared_key;\n  hasher.k <== out[0];\n  out[1] <== plaintext + hasher.out;\n}\n\n\ntemplate DecryptBits(N) {\n  signal input message[N+1];\n  signal input shared_key;\n  signal output out[N];\n\n  component hasher[N];\n\n  // iv is message[0]\n  for(var i=0; i<N; i++) {\n    hasher[i] = MiMC7(91);\n    hasher[i].x_in <== shared_key;\n    hasher[i].k <== message[0] + i;\n    out[i] <== message[i+1] - hasher[i].out;\n  }\n}\n\ntemplate Decrypt() {\n  signal input message[2];\n  signal input shared_key;\n  signal output out;\n\n  component hasher;\n\n  // iv is message[0]\n  hasher = MiMC7(91);\n  hasher.x_in <== shared_key;\n  hasher.k <== message[0];\n  out <== message[1] - hasher.out;\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/crypto/publickey_derivation.circom",
        "content": "// from privacy-scaling-explorations/maci\n\npragma circom 2.0.0;\n\ninclude \"../circomlib/bitify.circom\";\ninclude \"../circomlib/escalarmulfix.circom\";\n\ntemplate PublicKey() {\n  // Note: private key\n  // Needs to be hashed, and then pruned before\n  // supplying it to the circuit\n  signal input private_key;\n  signal output public_key[2];\n\n  component privBits = Num2Bits(253);\n  privBits.in <== private_key;\n\n  var BASE8[2] = [\n    5299619240641551281634865583518297030282874472190772894086521144482721001553,\n    16950150798460657717958625567821834550301663161624707787222815936182638968203\n  ];\n\n  component mulFix = EscalarMulFix(253, BASE8);\n  for (var i = 0; i < 253; i++) {\n    mulFix.e[i] <== privBits.out[i];\n  }\n\n  public_key[0] <== mulFix.out[0];\n  public_key[1] <== mulFix.out[1];\n}"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "circuits/util.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./circomlib/sign.circom\";\ninclude \"./circomlib/bitify.circom\";\ninclude \"./circomlib/comparators.circom\";\ninclude \"./circomlib/switcher.circom\";\n\ntemplate IsNegative() {\n    signal input in;\n    signal output out;\n\n    component num2Bits = Num2Bits(254);\n    num2Bits.in <== in;\n    component sign = Sign();\n    \n    for (var i = 0; i < 254; i++) {\n        sign.in[i] <== num2Bits.out[i];\n    }\n\n    out <== sign.sign;\n}\n\n/* Currently, IsPositive() treats zero as a positive number for better performance. \n   The following is the correct version which output is 1 when the signal in is a positive number, 0 when it is zero or a negative number\n\ntemplate IsPositive() {\n    signal input in;\n    signal output out;\n\n    component num2Bits = Num2Bits(254);\n    num2Bits.in <== in;\n    component sign = Sign();\n    \n    for (var i = 0; i < 254; i++) {\n        sign.in[i] <== num2Bits.out[i];\n    }\n    \n    component isz = IsZero();\n    isz.in <== in;\n    \n\n    out <== (1 - sign.sign) * (1 - isz.out);\n}\n*/\n\ntemplate IsPositive() {\n    signal input in;\n    signal output out;\n\n    component num2Bits = Num2Bits(254);\n    num2Bits.in <== in;\n    component sign = Sign();\n    \n    for (var i = 0; i < 254; i++) {\n        sign.in[i] <== num2Bits.out[i];\n    }\n\n    out <== 1 - sign.sign;\n}\n\ntemplate Sum(nInputs) {\n    signal input in[nInputs];\n    signal output out;\n\n    signal partialSum[nInputs];\n    partialSum[0] <== in[0];\n    \n    for (var i=1; i<nInputs; i++) {\n        partialSum[i] <== partialSum[i-1] + in[i];\n    }\n\n    out <== partialSum[nInputs-1];\n}\n\ntemplate Max(n) {\n    signal input in[n];\n    signal output out;\n\n    component gts[n];        // store comparators\n    component switchers[n+1];  // switcher for comparing maxs\n\n    signal maxs[n+1];\n\n    maxs[0] <== in[0];\n    for(var i = 0; i < n; i++) {\n        gts[i] = GreaterThan(252); // changed to 252 (maximum) for better compatibility\n        switchers[i+1] = Switcher();\n\n        gts[i].in[1] <== maxs[i];\n        gts[i].in[0] <== in[i];\n\n        switchers[i+1].sel <== gts[i].out;\n        switchers[i+1].L <== maxs[i];\n        switchers[i+1].R <== in[i];\n\n        maxs[i+1] <== switchers[i+1].outL;\n    }\n\n    out <== maxs[n];\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "index.js",
        "content": ""
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/averagePooling2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, AveragePooling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = AveragePooling2D(pool_size=2)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d (AverageP  (None, 2, 2, 3)          0         \\n\",\n      \" ooling2D)                                                       \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.4697424 , 0.26405168, 0.50556795],\\n\",\n       \"         [0.31879275, 0.10661064, 0.89969558],\\n\",\n       \"         [0.51674454, 0.44716256, 0.84376492],\\n\",\n       \"         [0.70730021, 0.23034467, 0.21298659],\\n\",\n       \"         [0.39270991, 0.26666702, 0.20998017]],\\n\",\n       \"\\n\",\n       \"        [[0.06338963, 0.40992356, 0.65531956],\\n\",\n       \"         [0.65641348, 0.61781921, 0.71094249],\\n\",\n       \"         [0.66084759, 0.01212395, 0.96300368],\\n\",\n       \"         [0.05580187, 0.96245161, 0.20798007],\\n\",\n       \"         [0.94943203, 0.05702934, 0.37272236]],\\n\",\n       \"\\n\",\n       \"        [[0.35969427, 0.24114588, 0.40254835],\\n\",\n       \"         [0.87560584, 0.29480004, 0.71005672],\\n\",\n       \"         [0.89799237, 0.03862642, 0.41636709],\\n\",\n       \"         [0.60385376, 0.00368971, 0.73375191],\\n\",\n       \"         [0.39912794, 0.02359739, 0.58151196]],\\n\",\n       \"\\n\",\n       \"        [[0.75162628, 0.57732706, 0.51714415],\\n\",\n       \"         [0.42886868, 0.4817775 , 0.55461973],\\n\",\n       \"         [0.96844644, 0.72937866, 0.96170145],\\n\",\n       \"         [0.09311228, 0.70769801, 0.37766384],\\n\",\n       \"         [0.22594407, 0.64493633, 0.84161072]],\\n\",\n       \"\\n\",\n       \"        [[0.94736999, 0.95913254, 0.66551587],\\n\",\n       \"         [0.12700579, 0.80182768, 0.24940166],\\n\",\n       \"         [0.26694546, 0.07422724, 0.87879383],\\n\",\n       \"         [0.26784968, 0.33568869, 0.71071351],\\n\",\n       \"         [0.36125259, 0.89039872, 0.57815661]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 28ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 19:58:12.306880: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.37708455, 0.34960127, 0.6928814 ],\\n\",\n       \"         [0.48517358, 0.41302067, 0.5569338 ]],\\n\",\n       \"\\n\",\n       \"        [[0.6039488 , 0.39876258, 0.5460923 ],\\n\",\n       \"         [0.6408512 , 0.3698482 , 0.6223711 ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\\n\",\n    \"    remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\\n\",\n    \"    for i in range((nRows-poolSize)//strides + 1):\\n\",\n    \"        for j in range((nCols-poolSize)//strides + 1):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                for x in range(poolSize):\\n\",\n    \"                    for y in range(poolSize):\\n\",\n    \"                        out[i][j][k] += input[i*strides+x][j*strides+y][k]\\n\",\n    \"                remainder[i][j][k] = str(out[i][j][k] % poolSize**2 % p)\\n\",\n    \"                out[i][j][k] = str(out[i][j][k] // poolSize**2 % p)\\n\",\n    \"    return Input, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['377084566964233814727207747512696832',\\n\",\n       \"    '349601274166158063422211165597466624',\\n\",\n       \"    '692881395085479491591287820028739584'],\\n\",\n       \"   ['485173550880783982864257598131011584',\\n\",\n       \"    '413020696901266553234304779809718272',\\n\",\n       \"    '556933813298750165384079226175488000']],\\n\",\n       \"  [['603948769893606922513439699094208512',\\n\",\n       \"    '398762621026204510661452706879635456',\\n\",\n       \"    '546092235924829818623026255726903296'],\\n\",\n       \"   ['640851212450790063364758949182046208',\\n\",\n       \"    '369848200094279040953444891822653440',\\n\",\n       \"    '622371069389430669959468896315506688']]],\\n\",\n       \" [[['0', '0', '0'], ['0', '0', '0']], [['0', '0', '0'], ['0', '0', '0']]])\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out, remainder = AveragePooling2DInt(5, 5, 3, 2, 2, X_in)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder \\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"averagePooling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = AveragePooling2D(pool_size=3, strides=2)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 10, 10, 3)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d_1 (Averag  (None, 4, 4, 3)          0         \\n\",\n      \" ePooling2D)                                                     \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 20ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.49083894, 0.6503702 , 0.45121744],\\n\",\n       \"         [0.3731585 , 0.55850077, 0.5209063 ],\\n\",\n       \"         [0.392081  , 0.4962937 , 0.44958603],\\n\",\n       \"         [0.5062166 , 0.5363207 , 0.5836957 ]],\\n\",\n       \"\\n\",\n       \"        [[0.4387001 , 0.51550937, 0.4842767 ],\\n\",\n       \"         [0.36599833, 0.6358112 , 0.42103994],\\n\",\n       \"         [0.45892367, 0.48430002, 0.48299968],\\n\",\n       \"         [0.47987926, 0.51054746, 0.48522002]],\\n\",\n       \"\\n\",\n       \"        [[0.4337698 , 0.5966541 , 0.34484175],\\n\",\n       \"         [0.50603914, 0.54209197, 0.3464988 ],\\n\",\n       \"         [0.5383602 , 0.40848657, 0.5954534 ],\\n\",\n       \"         [0.39340922, 0.5384207 , 0.6712477 ]],\\n\",\n       \"\\n\",\n       \"        [[0.52239245, 0.61681217, 0.5948292 ],\\n\",\n       \"         [0.6456814 , 0.56172687, 0.5704497 ],\\n\",\n       \"         [0.5970895 , 0.65395427, 0.61463684],\\n\",\n       \"         [0.49751964, 0.57090425, 0.50965226]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['490838913202839647482031788613930552',\\n\",\n       \"    '650370206452327739765809362325238215',\\n\",\n       \"    '451217443243932157150820354890924032'],\\n\",\n       \"   ['373158499178459549901037286246696732',\\n\",\n       \"    '558500757386374812373354359379751367',\\n\",\n       \"    '520906395265463287758066336793158542'],\\n\",\n       \"   ['392081032582640205401569336636735488',\\n\",\n       \"    '496293715863929836162024945736366307',\\n\",\n       \"    '449586010677657401563374125861539384'],\\n\",\n       \"   ['506216538770442893696705511483535815',\\n\",\n       \"    '536320651604328640569669741910920760',\\n\",\n       \"    '583695794530695154314058797408758442']],\\n\",\n       \"  [['438700122269240629018040116487826090',\\n\",\n       \"    '515509373055967873846597732290585486',\\n\",\n       \"    '484276697106518139982691888834194090'],\\n\",\n       \"   ['365998311298275897695359121353838136',\\n\",\n       \"    '635811225512657877386382358476401322',\\n\",\n       \"    '421039958668517212332658528902359722'],\\n\",\n       \"   ['458923652827692860008536397550744007',\\n\",\n       \"    '484300011977437346144682467789664711',\\n\",\n       \"    '482999719051088512471698660426980465'],\\n\",\n       \"   ['479879293099700576539663622281305201',\\n\",\n       \"    '510547498500066698646970955137781304',\\n\",\n       \"    '485220023120638790352795312775961713']],\\n\",\n       \"  [['433769787149101139024853526875005838',\\n\",\n       \"    '596654066230626723871865644707566933',\\n\",\n       \"    '344841746939097107506453705665223793'],\\n\",\n       \"   ['506039134280922806908200932494569927',\\n\",\n       \"    '542091990692138506014454460431291733',\\n\",\n       \"    '346498783957661696012159449997712497'],\\n\",\n       \"   ['538360180533623713187861074538630712',\\n\",\n       \"    '408486572499003056002511420888099498',\\n\",\n       \"    '595453351874211229959940839550251463'],\\n\",\n       \"   ['393409252869458006979621409013687182',\\n\",\n       \"    '538420708502221204218833774810030990',\\n\",\n       \"    '671247738849324010704751775607772501']],\\n\",\n       \"  [['522392440772653872755969912709229226',\\n\",\n       \"    '616812156272961914033749036925481415',\\n\",\n       \"    '594829232057008563695532312541731953'],\\n\",\n       \"   ['645681406847045116741310894926637738',\\n\",\n       \"    '561726846190701362338877345898226574',\\n\",\n       \"    '570449710887660887892445378356008277'],\\n\",\n       \"   ['597089469987715047812261496899676842',\\n\",\n       \"    '653954298836488871344502997077750215',\\n\",\n       \"    '614636841404824230076303162630384298'],\\n\",\n       \"   ['497519650100367473493056256852390343',\\n\",\n       \"    '570904266316369826537673219489981326',\\n\",\n       \"    '509652208506601100112410974135488056']]],\\n\",\n       \" [[['8', '1', '0'], ['4', '1', '2'], ['0', '5', '8'], ['1', '8', '6']],\\n\",\n       \"  [['6', '2', '6'], ['8', '6', '6'], ['1', '1', '7'], ['7', '8', '7']],\\n\",\n       \"  [['2', '3', '7'], ['1', '3', '7'], ['8', '6', '1'], ['2', '2', '3']],\\n\",\n       \"  [['6', '1', '7'], ['6', '2', '3'], ['6', '1', '6'], ['1', '2', '8']]])\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out, remainder = AveragePooling2DInt(10, 10, 3, 3, 2, X_in)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"averagePooling2D_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/batchNormalization.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, BatchNormalization, Dense, Flatten\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"out = BatchNormalization()(inputs)\\n\",\n    \"out = Flatten()(out)\\n\",\n    \"out = Dense(1)(out)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" batch_normalization (BatchN  (None, 5, 5, 3)          12        \\n\",\n      \" ormalization)                                                   \\n\",\n      \"                                                                 \\n\",\n      \" flatten (Flatten)           (None, 75)                0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 1)                 76        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 88\\n\",\n      \"Trainable params: 82\\n\",\n      \"Non-trainable params: 6\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.51546565, 0.46651282, 0.78133227],\\n\",\n       \"         [0.29092001, 0.15424294, 0.31568105],\\n\",\n       \"         [0.42554169, 0.17798232, 0.88401623],\\n\",\n       \"         [0.89061342, 0.56954272, 0.0481971 ],\\n\",\n       \"         [0.91385411, 0.87839928, 0.54333657]],\\n\",\n       \"\\n\",\n       \"        [[0.06954288, 0.9189417 , 0.16824991],\\n\",\n       \"         [0.61834797, 0.48611683, 0.05698664],\\n\",\n       \"         [0.54958275, 0.40614748, 0.93471022],\\n\",\n       \"         [0.96738304, 0.9310907 , 0.05346684],\\n\",\n       \"         [0.01504873, 0.45594357, 0.92055095]],\\n\",\n       \"\\n\",\n       \"        [[0.11021081, 0.40673465, 0.56412873],\\n\",\n       \"         [0.5385549 , 0.06119234, 0.5499304 ],\\n\",\n       \"         [0.409637  , 0.72651771, 0.71666944],\\n\",\n       \"         [0.99635655, 0.13653654, 0.10949123],\\n\",\n       \"         [0.2601131 , 0.70956364, 0.51173637]],\\n\",\n       \"\\n\",\n       \"        [[0.29500952, 0.50029805, 0.48711255],\\n\",\n       \"         [0.58302715, 0.07682466, 0.06070311],\\n\",\n       \"         [0.63143749, 0.55553472, 0.62363371],\\n\",\n       \"         [0.34286961, 0.28562232, 0.10381272],\\n\",\n       \"         [0.5267341 , 0.44532117, 0.74259914]],\\n\",\n       \"\\n\",\n       \"        [[0.89833895, 0.70393118, 0.3390096 ],\\n\",\n       \"         [0.31743696, 0.27991868, 0.41889825],\\n\",\n       \"         [0.88849899, 0.36099248, 0.8606479 ],\\n\",\n       \"         [0.8115506 , 0.9383675 , 0.29448095],\\n\",\n       \"         [0.97113074, 0.58140933, 0.96698766]]],\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       [[[0.22152899, 0.69173392, 0.10892224],\\n\",\n       \"         [0.45291025, 0.87475282, 0.78825403],\\n\",\n       \"         [0.30206652, 0.65193234, 0.74018285],\\n\",\n       \"         [0.28822764, 0.82794295, 0.88511038],\\n\",\n       \"         [0.65083834, 0.65900742, 0.37215784]],\\n\",\n       \"\\n\",\n       \"        [[0.42637533, 0.82491213, 0.99759185],\\n\",\n       \"         [0.5311499 , 0.71585492, 0.35118   ],\\n\",\n       \"         [0.24486032, 0.91171808, 0.77877967],\\n\",\n       \"         [0.1899115 , 0.01429132, 0.53225576],\\n\",\n       \"         [0.26831007, 0.3223111 , 0.2793977 ]],\\n\",\n       \"\\n\",\n       \"        [[0.43628462, 0.855694  , 0.45144496],\\n\",\n       \"         [0.17713725, 0.6788593 , 0.53221073],\\n\",\n       \"         [0.24239035, 0.29885874, 0.00793102],\\n\",\n       \"         [0.47036933, 0.83716811, 0.01747103],\\n\",\n       \"         [0.52148184, 0.88785307, 0.19371033]],\\n\",\n       \"\\n\",\n       \"        [[0.45964463, 0.11785621, 0.71888447],\\n\",\n       \"         [0.37170738, 0.91271932, 0.28649456],\\n\",\n       \"         [0.3974761 , 0.54316076, 0.56468016],\\n\",\n       \"         [0.65716588, 0.00913184, 0.42107159],\\n\",\n       \"         [0.62804608, 0.19359813, 0.13687296]],\\n\",\n       \"\\n\",\n       \"        [[0.15432216, 0.24376177, 0.73777443],\\n\",\n       \"         [0.37740194, 0.51219611, 0.18536464],\\n\",\n       \"         [0.00561986, 0.63145406, 0.57055781],\\n\",\n       \"         [0.45424905, 0.46157587, 0.87326481],\\n\",\n       \"         [0.44888708, 0.09268558, 0.54308092]]],\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       [[[0.44003404, 0.82605955, 0.53120479],\\n\",\n       \"         [0.34508592, 0.54358359, 0.63107103],\\n\",\n       \"         [0.18258236, 0.5828249 , 0.35215564],\\n\",\n       \"         [0.35995517, 0.58247612, 0.866913  ],\\n\",\n       \"         [0.37331628, 0.72105525, 0.86011076]],\\n\",\n       \"\\n\",\n       \"        [[0.0037806 , 0.80184814, 0.19458159],\\n\",\n       \"         [0.01779705, 0.68048193, 0.08877037],\\n\",\n       \"         [0.72192341, 0.94542319, 0.7099795 ],\\n\",\n       \"         [0.38773382, 0.0054821 , 0.86694736],\\n\",\n       \"         [0.59622908, 0.88670846, 0.54186724]],\\n\",\n       \"\\n\",\n       \"        [[0.91125128, 0.24628816, 0.91306807],\\n\",\n       \"         [0.20544878, 0.6600348 , 0.02261235],\\n\",\n       \"         [0.08034128, 0.50809017, 0.37310936],\\n\",\n       \"         [0.66526679, 0.6763669 , 0.3438879 ],\\n\",\n       \"         [0.54922619, 0.05982564, 0.21239447]],\\n\",\n       \"\\n\",\n       \"        [[0.09812086, 0.36775343, 0.23264159],\\n\",\n       \"         [0.07952414, 0.14821264, 0.30500863],\\n\",\n       \"         [0.78574487, 0.20629136, 0.28249732],\\n\",\n       \"         [0.18532948, 0.62820359, 0.40885501],\\n\",\n       \"         [0.53428171, 0.01419418, 0.96868481]],\\n\",\n       \"\\n\",\n       \"        [[0.46122128, 0.60562586, 0.19714442],\\n\",\n       \"         [0.83266218, 0.62255273, 0.48534285],\\n\",\n       \"         [0.78304596, 0.63898229, 0.91084764],\\n\",\n       \"         [0.04902518, 0.69016331, 0.16760015],\\n\",\n       \"         [0.88179687, 0.02644824, 0.78977572]]],\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       ...,\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       [[[0.17074279, 0.10103348, 0.63216146],\\n\",\n       \"         [0.32308489, 0.88627716, 0.84782501],\\n\",\n       \"         [0.1032571 , 0.02331302, 0.36067615],\\n\",\n       \"         [0.01463099, 0.89390044, 0.7491627 ],\\n\",\n       \"         [0.94200448, 0.90298754, 0.55947368]],\\n\",\n       \"\\n\",\n       \"        [[0.7041535 , 0.39417727, 0.07809514],\\n\",\n       \"         [0.52135847, 0.0290839 , 0.45233884],\\n\",\n       \"         [0.71856329, 0.81167091, 0.9178133 ],\\n\",\n       \"         [0.02404749, 0.49104236, 0.21492727],\\n\",\n       \"         [0.15136666, 0.01310515, 0.29748093]],\\n\",\n       \"\\n\",\n       \"        [[0.88120014, 0.16076401, 0.44107649],\\n\",\n       \"         [0.25002897, 0.68659302, 0.01653978],\\n\",\n       \"         [0.96055884, 0.40286758, 0.11771713],\\n\",\n       \"         [0.66927334, 0.77825925, 0.30680967],\\n\",\n       \"         [0.31482238, 0.7749523 , 0.11406879]],\\n\",\n       \"\\n\",\n       \"        [[0.53919419, 0.60783489, 0.55848085],\\n\",\n       \"         [0.32747631, 0.09879024, 0.28296219],\\n\",\n       \"         [0.65211663, 0.70552049, 0.55715698],\\n\",\n       \"         [0.31646225, 0.26783995, 0.47998016],\\n\",\n       \"         [0.37794728, 0.42765623, 0.97190187]],\\n\",\n       \"\\n\",\n       \"        [[0.53879646, 0.45261775, 0.46913403],\\n\",\n       \"         [0.2670922 , 0.79348712, 0.49027602],\\n\",\n       \"         [0.25085863, 0.10323594, 0.15697154],\\n\",\n       \"         [0.31783142, 0.54529695, 0.90404337],\\n\",\n       \"         [0.11790291, 0.15503706, 0.86422424]]],\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       [[[0.16965053, 0.19585652, 0.57609002],\\n\",\n       \"         [0.88591501, 0.90486881, 0.29608075],\\n\",\n       \"         [0.4261748 , 0.91284255, 0.40807448],\\n\",\n       \"         [0.9686301 , 0.74409545, 0.1479126 ],\\n\",\n       \"         [0.76802611, 0.07944974, 0.7871578 ]],\\n\",\n       \"\\n\",\n       \"        [[0.77475062, 0.40398437, 0.22643119],\\n\",\n       \"         [0.0104928 , 0.38809633, 0.48776304],\\n\",\n       \"         [0.22491731, 0.94079457, 0.97114209],\\n\",\n       \"         [0.65810206, 0.9100557 , 0.24727223],\\n\",\n       \"         [0.05758432, 0.54125367, 0.01468728]],\\n\",\n       \"\\n\",\n       \"        [[0.71953982, 0.17153423, 0.74242277],\\n\",\n       \"         [0.69007692, 0.16985619, 0.40592314],\\n\",\n       \"         [0.54681391, 0.5548588 , 0.47674301],\\n\",\n       \"         [0.57911416, 0.28571978, 0.39200726],\\n\",\n       \"         [0.11671085, 0.35797023, 0.65890719]],\\n\",\n       \"\\n\",\n       \"        [[0.85257004, 0.7955835 , 0.66530167],\\n\",\n       \"         [0.60683054, 0.66667651, 0.58183113],\\n\",\n       \"         [0.95010415, 0.77982033, 0.48321958],\\n\",\n       \"         [0.73954001, 0.21177226, 0.40730859],\\n\",\n       \"         [0.58235681, 0.54621676, 0.72576091]],\\n\",\n       \"\\n\",\n       \"        [[0.78679585, 0.07508165, 0.7500122 ],\\n\",\n       \"         [0.52093211, 0.58039123, 0.46972807],\\n\",\n       \"         [0.96323894, 0.99445506, 0.73634561],\\n\",\n       \"         [0.79991676, 0.66932491, 0.83293889],\\n\",\n       \"         [0.20586253, 0.41194998, 0.43086448]]],\\n\",\n       \"\\n\",\n       \"\\n\",\n       \"       [[[0.39755238, 0.44572733, 0.14839841],\\n\",\n       \"         [0.85064056, 0.46063306, 0.48205451],\\n\",\n       \"         [0.71843235, 0.16096294, 0.68091537],\\n\",\n       \"         [0.53677884, 0.1177746 , 0.2540637 ],\\n\",\n       \"         [0.27248667, 0.53513208, 0.88182579]],\\n\",\n       \"\\n\",\n       \"        [[0.41187651, 0.77931731, 0.24484454],\\n\",\n       \"         [0.79766554, 0.41731159, 0.95576332],\\n\",\n       \"         [0.72876755, 0.27933312, 0.3082945 ],\\n\",\n       \"         [0.76694795, 0.74242235, 0.62142724],\\n\",\n       \"         [0.97480578, 0.35289907, 0.64357369]],\\n\",\n       \"\\n\",\n       \"        [[0.00510661, 0.36997422, 0.16220858],\\n\",\n       \"         [0.9872583 , 0.95501977, 0.15935416],\\n\",\n       \"         [0.78867534, 0.54122521, 0.54486478],\\n\",\n       \"         [0.03354764, 0.05670898, 0.47520133],\\n\",\n       \"         [0.04376703, 0.69549825, 0.3957491 ]],\\n\",\n       \"\\n\",\n       \"        [[0.84051762, 0.79462166, 0.30602544],\\n\",\n       \"         [0.25025524, 0.08666752, 0.69194498],\\n\",\n       \"         [0.67076409, 0.13492286, 0.4590991 ],\\n\",\n       \"         [0.20405993, 0.07903494, 0.70707305],\\n\",\n       \"         [0.83720425, 0.75953423, 0.81481202]],\\n\",\n       \"\\n\",\n       \"        [[0.19551102, 0.46499979, 0.50975971],\\n\",\n       \"         [0.81569678, 0.34130601, 0.76208935],\\n\",\n       \"         [0.82885678, 0.10476159, 0.13018122],\\n\",\n       \"         [0.26689358, 0.79482095, 0.75352521],\\n\",\n       \"         [0.58703011, 0.11749016, 0.19427432]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_train = np.random.rand(100,5,5,3)\\n\",\n    \"X_train\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.21946477],\\n\",\n       \"       [0.3711923 ],\\n\",\n       \"       [0.24737705],\\n\",\n       \"       [0.16344551],\\n\",\n       \"       [0.57433513],\\n\",\n       \"       [0.76673914],\\n\",\n       \"       [0.7049643 ],\\n\",\n       \"       [0.67571894],\\n\",\n       \"       [0.15141958],\\n\",\n       \"       [0.84983105],\\n\",\n       \"       [0.05552415],\\n\",\n       \"       [0.95604334],\\n\",\n       \"       [0.70679183],\\n\",\n       \"       [0.86247509],\\n\",\n       \"       [0.01407803],\\n\",\n       \"       [0.55736261],\\n\",\n       \"       [0.19422897],\\n\",\n       \"       [0.86008897],\\n\",\n       \"       [0.2779906 ],\\n\",\n       \"       [0.55527211],\\n\",\n       \"       [0.16247257],\\n\",\n       \"       [0.13970005],\\n\",\n       \"       [0.92248072],\\n\",\n       \"       [0.93564244],\\n\",\n       \"       [0.28634139],\\n\",\n       \"       [0.23594509],\\n\",\n       \"       [0.44848018],\\n\",\n       \"       [0.35401733],\\n\",\n       \"       [0.99775489],\\n\",\n       \"       [0.1732102 ],\\n\",\n       \"       [0.81910272],\\n\",\n       \"       [0.46522896],\\n\",\n       \"       [0.99489404],\\n\",\n       \"       [0.55781089],\\n\",\n       \"       [0.13592596],\\n\",\n       \"       [0.43879534],\\n\",\n       \"       [0.81024602],\\n\",\n       \"       [0.94877655],\\n\",\n       \"       [0.75248092],\\n\",\n       \"       [0.30265859],\\n\",\n       \"       [0.42836091],\\n\",\n       \"       [0.59454105],\\n\",\n       \"       [0.43154069],\\n\",\n       \"       [0.67468033],\\n\",\n       \"       [0.58606549],\\n\",\n       \"       [0.1744458 ],\\n\",\n       \"       [0.49333982],\\n\",\n       \"       [0.06740779],\\n\",\n       \"       [0.00943958],\\n\",\n       \"       [0.4099619 ],\\n\",\n       \"       [0.49609765],\\n\",\n       \"       [0.31434293],\\n\",\n       \"       [0.24492819],\\n\",\n       \"       [0.27013361],\\n\",\n       \"       [0.69482176],\\n\",\n       \"       [0.93217975],\\n\",\n       \"       [0.57115641],\\n\",\n       \"       [0.64785497],\\n\",\n       \"       [0.09918379],\\n\",\n       \"       [0.55192952],\\n\",\n       \"       [0.81989582],\\n\",\n       \"       [0.05051461],\\n\",\n       \"       [0.93054128],\\n\",\n       \"       [0.67387306],\\n\",\n       \"       [0.76534683],\\n\",\n       \"       [0.6162766 ],\\n\",\n       \"       [0.96975296],\\n\",\n       \"       [0.79504513],\\n\",\n       \"       [0.42467985],\\n\",\n       \"       [0.11096869],\\n\",\n       \"       [0.22852679],\\n\",\n       \"       [0.65542355],\\n\",\n       \"       [0.35148172],\\n\",\n       \"       [0.77244589],\\n\",\n       \"       [0.35624866],\\n\",\n       \"       [0.2630125 ],\\n\",\n       \"       [0.20241856],\\n\",\n       \"       [0.35342962],\\n\",\n       \"       [0.4200376 ],\\n\",\n       \"       [0.21397308],\\n\",\n       \"       [0.38814001],\\n\",\n       \"       [0.82781448],\\n\",\n       \"       [0.14303959],\\n\",\n       \"       [0.83622505],\\n\",\n       \"       [0.19489373],\\n\",\n       \"       [0.50839397],\\n\",\n       \"       [0.94387189],\\n\",\n       \"       [0.26870297],\\n\",\n       \"       [0.66940445],\\n\",\n       \"       [0.31928558],\\n\",\n       \"       [0.25835398],\\n\",\n       \"       [0.59484484],\\n\",\n       \"       [0.21550068],\\n\",\n       \"       [0.19920632],\\n\",\n       \"       [0.85037438],\\n\",\n       \"       [0.64880356],\\n\",\n       \"       [0.19659417],\\n\",\n       \"       [0.12815503],\\n\",\n       \"       [0.70278136],\\n\",\n       \"       [0.65639473]])\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y_train = np.random.rand(100,1)\\n\",\n    \"y_train\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/10\\n\",\n      \"4/4 [==============================] - 0s 2ms/step - loss: 2.7752\\n\",\n      \"Epoch 2/10\\n\",\n      \"4/4 [==============================] - 0s 979us/step - loss: 2.6586\\n\",\n      \"Epoch 3/10\\n\",\n      \"4/4 [==============================] - 0s 649us/step - loss: 2.5723\\n\",\n      \"Epoch 4/10\\n\",\n      \"4/4 [==============================] - 0s 2ms/step - loss: 2.4804\\n\",\n      \"Epoch 5/10\\n\",\n      \"4/4 [==============================] - 0s 1ms/step - loss: 2.3874\\n\",\n      \"Epoch 6/10\\n\",\n      \"4/4 [==============================] - 0s 762us/step - loss: 2.2941\\n\",\n      \"Epoch 7/10\\n\",\n      \"4/4 [==============================] - 0s 889us/step - loss: 2.2374\\n\",\n      \"Epoch 8/10\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:00:14.999431: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"4/4 [==============================] - 0s 15ms/step - loss: 2.1879\\n\",\n      \"Epoch 9/10\\n\",\n      \"4/4 [==============================] - 0s 987us/step - loss: 2.1199\\n\",\n      \"Epoch 10/10\\n\",\n      \"4/4 [==============================] - 0s 1ms/step - loss: 2.0514\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x12dea6fa0>\"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.compile(\\\"adam\\\", \\\"mse\\\")\\n\",\n    \"model.fit(X_train, y_train, epochs=10)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'batch_normalization/gamma:0' shape=(3,) dtype=float32, numpy=array([0.9704942, 0.9639488, 0.9704298], dtype=float32)>,\\n\",\n       \" <tf.Variable 'batch_normalization/beta:0' shape=(3,) dtype=float32, numpy=array([ 0.02682306, -0.02748435,  0.02756111], dtype=float32)>,\\n\",\n       \" <tf.Variable 'batch_normalization/moving_mean:0' shape=(3,) dtype=float32, numpy=array([0.16209687, 0.1706537 , 0.16507432], dtype=float32)>,\\n\",\n       \" <tf.Variable 'batch_normalization/moving_variance:0' shape=(3,) dtype=float32, numpy=array([0.6963565, 0.6966989, 0.6962899], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 8,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.layers[1].weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.27455621, 0.27884516, 0.7259278 ],\\n\",\n       \"         [0.53377714, 0.6519488 , 0.86514377],\\n\",\n       \"         [0.49080768, 0.65021787, 0.68419028],\\n\",\n       \"         [0.0618392 , 0.02673969, 0.57868236],\\n\",\n       \"         [0.85494917, 0.71864642, 0.38163087]],\\n\",\n       \"\\n\",\n       \"        [[0.22703165, 0.33350008, 0.85208601],\\n\",\n       \"         [0.86850824, 0.43578265, 0.70671478],\\n\",\n       \"         [0.75415054, 0.97444638, 0.48606382],\\n\",\n       \"         [0.14784358, 0.45406111, 0.08556609],\\n\",\n       \"         [0.20530247, 0.25450988, 0.51542351]],\\n\",\n       \"\\n\",\n       \"        [[0.13544047, 0.01932561, 0.22823691],\\n\",\n       \"         [0.64891188, 0.18616972, 0.46087849],\\n\",\n       \"         [0.81283055, 0.5325164 , 0.32305024],\\n\",\n       \"         [0.75351508, 0.14501534, 0.44999686],\\n\",\n       \"         [0.42234362, 0.06347228, 0.63881747]],\\n\",\n       \"\\n\",\n       \"        [[0.85467296, 0.80260163, 0.14398915],\\n\",\n       \"         [0.57931829, 0.53329564, 0.7187654 ],\\n\",\n       \"         [0.80024988, 0.96224997, 0.8937722 ],\\n\",\n       \"         [0.33025203, 0.91751174, 0.62203916],\\n\",\n       \"         [0.93176317, 0.72790829, 0.14862771]],\\n\",\n       \"\\n\",\n       \"        [[0.60466651, 0.567648  , 0.37182924],\\n\",\n       \"         [0.76271487, 0.11624398, 0.81946002],\\n\",\n       \"         [0.4389968 , 0.90003205, 0.19711127],\\n\",\n       \"         [0.67622958, 0.53012144, 0.37373778],\\n\",\n       \"         [0.97509719, 0.48172791, 0.63218788]]]])\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 32ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[ 0.1575187 ,  0.09737267,  0.67934984],\\n\",\n       \"         [ 0.45877463,  0.5279483 ,  0.8411379 ],\\n\",\n       \"         [ 0.40883726,  0.52595073,  0.63084507],\\n\",\n       \"         [-0.0896923 , -0.19356653,  0.50823045],\\n\",\n       \"         [ 0.83202755,  0.60491985,  0.27922952]],\\n\",\n       \"\\n\",\n       \"        [[ 0.10228759,  0.16044651,  0.8259631 ],\\n\",\n       \"         [ 0.84778535,  0.2784844 ,  0.65702164],\\n\",\n       \"         [ 0.7148835 ,  0.9001226 ,  0.40059495],\\n\",\n       \"         [ 0.01025847,  0.29957846, -0.06483836],\\n\",\n       \"         [ 0.07703484,  0.06928882,  0.43471497]],\\n\",\n       \"\\n\",\n       \"        [[-0.00415592, -0.20212264,  0.10096472],\\n\",\n       \"         [ 0.5925795 , -0.00957828,  0.37132615],\\n\",\n       \"         [ 0.7830791 ,  0.39011884,  0.21115081],\\n\",\n       \"         [ 0.714145  , -0.05707199,  0.3586802 ],\\n\",\n       \"         [ 0.32927114, -0.15117574,  0.5781157 ]],\\n\",\n       \"\\n\",\n       \"        [[ 0.8317066 ,  0.7018073 ,  0.00305727],\\n\",\n       \"         [ 0.5117007 ,  0.39101806,  0.6710261 ],\\n\",\n       \"         [ 0.7684583 ,  0.88604754,  0.8744081 ],\\n\",\n       \"         [ 0.22224607,  0.83441794,  0.558617  ],\\n\",\n       \"         [ 0.92129767,  0.6156084 ,  0.0084479 ]],\\n\",\n       \"\\n\",\n       \"        [[ 0.54115933,  0.43066198,  0.26783872],\\n\",\n       \"         [ 0.72483665, -0.09027521,  0.78804713],\\n\",\n       \"         [ 0.34862483,  0.81424564,  0.06479244],\\n\",\n       \"         [ 0.624327  ,  0.38735494,  0.2700567 ],\\n\",\n       \"         [ 0.97165865,  0.33150697,  0.5704112 ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"new_model = Model(inputs, model.layers[1].output)\\n\",\n    \"y = new_model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"gamma = model.layers[1].weights[0].numpy()\\n\",\n    \"beta = model.layers[1].weights[1].numpy()\\n\",\n    \"moving_mean = model.layers[1].weights[2].numpy()\\n\",\n    \"moving_var = model.layers[1].weights[3].numpy()\\n\",\n    \"epsilon = model.layers[1].epsilon\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"a = gamma/(moving_var+epsilon)**.5\\n\",\n    \"b = beta-gamma*moving_mean/(moving_var+epsilon)**.5\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[ 1.38897775e-08, -4.41621682e-09, -1.46314817e-08],\\n\",\n       \"         [ 1.22362858e-08,  2.73325588e-08, -4.77779197e-08],\\n\",\n       \"         [-1.14818392e-08, -8.60447691e-09, -5.83081214e-08],\\n\",\n       \"         [-5.10371694e-09, -8.67723293e-09,  2.98262304e-10],\\n\",\n       \"         [-7.37144357e-09, -6.87929902e-09, -3.09108445e-08]],\\n\",\n       \"\\n\",\n       \"        [[-3.70238870e-09,  9.08749898e-09,  6.04406457e-08],\\n\",\n       \"         [-8.04363320e-09, -2.61427017e-08, -4.75678711e-08],\\n\",\n       \"         [-2.29807172e-08, -3.35601555e-08, -3.61847423e-08],\\n\",\n       \"         [ 1.76612667e-09, -8.73801476e-10,  2.36584587e-09],\\n\",\n       \"         [ 5.96964625e-09, -1.35698691e-08, -2.09152273e-09]],\\n\",\n       \"\\n\",\n       \"        [[-2.18008088e-09,  3.40718009e-09,  1.14725877e-09],\\n\",\n       \"         [ 7.83470533e-09, -4.13062541e-09, -2.05064118e-08],\\n\",\n       \"         [ 5.68865103e-08,  3.01907888e-08, -1.38190100e-08],\\n\",\n       \"         [-2.30006845e-08, -8.84019241e-09, -3.75235497e-08],\\n\",\n       \"         [-1.33667987e-08,  2.45791437e-09,  1.05576055e-08]],\\n\",\n       \"\\n\",\n       \"        [[ 1.63983768e-08,  4.34060976e-09,  7.69416812e-09],\\n\",\n       \"         [ 1.96461017e-08, -2.64836226e-08, -5.55432413e-08],\\n\",\n       \"         [ 1.60446652e-08,  3.83262573e-08,  3.27252936e-08],\\n\",\n       \"         [-1.79053708e-08,  3.49677078e-08,  2.28655761e-09],\\n\",\n       \"         [ 3.06888477e-08, -6.37458319e-09, -7.83266337e-10]],\\n\",\n       \"\\n\",\n       \"        [[ 3.44015694e-09, -2.27795071e-08, -3.66268776e-09],\\n\",\n       \"         [ 8.27864410e-09, -8.66295551e-09, -9.44552192e-09],\\n\",\n       \"         [ 3.77712691e-08, -4.68591560e-08, -7.31272758e-09],\\n\",\n       \"         [ 1.90310351e-08,  2.21921187e-09, -1.20205449e-08],\\n\",\n       \"         [-1.50930767e-08, -1.72539832e-08,  6.61672261e-09]]]])\"\n      ]\n     },\n     \"execution_count\": 13,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y-(gamma*(X-moving_mean)/((moving_var+epsilon)**.5)+beta)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[ 6.29271463e-09, -1.51612348e-08,  4.78305939e-09],\\n\",\n       \"         [ 2.53706245e-09,  1.56956936e-08, -2.51350980e-08],\\n\",\n       \"         [-2.08326003e-08, -2.02372046e-08, -3.98614322e-08],\\n\",\n       \"         [-1.09757444e-08, -1.88196314e-08,  1.62983274e-08],\\n\",\n       \"         [-1.96752217e-08, -1.86755947e-08, -1.94802087e-08]],\\n\",\n       \"\\n\",\n       \"        [[-1.09140497e-08, -1.78816328e-09,  8.27806710e-08],\\n\",\n       \"         [-2.04573691e-08, -3.72628548e-08, -2.85988609e-08],\\n\",\n       \"         [-3.44670656e-08, -4.59679019e-08, -2.23324095e-08],\\n\",\n       \"         [-4.80335610e-09, -1.20376463e-08,  6.93103225e-09],\\n\",\n       \"         [-1.06580120e-09, -2.42567173e-08,  1.24416322e-08]],\\n\",\n       \"\\n\",\n       \"        [[-8.64898020e-09, -6.71749611e-09,  9.02084041e-09],\\n\",\n       \"         [-2.79820678e-09, -1.46541169e-08, -7.23810212e-09],\\n\",\n       \"         [ 4.49242945e-08,  1.88394085e-08, -3.74680098e-09],\\n\",\n       \"         [-3.44818796e-08, -1.92653107e-08, -2.45075741e-08],\\n\",\n       \"         [-2.21623482e-08, -7.77228767e-09,  2.79521442e-08]],\\n\",\n       \"\\n\",\n       \"        [[ 4.09683865e-09, -7.65636798e-09,  1.36141277e-08],\\n\",\n       \"         [ 9.57756097e-09, -3.78368655e-08, -3.62947893e-08],\\n\",\n       \"         [ 4.18447266e-09,  2.59476647e-08,  5.60319802e-08],\\n\",\n       \"         [-2.59541007e-08,  2.26960550e-08,  1.92920239e-08],\\n\",\n       \"         [ 1.77621440e-08, -1.81930180e-08,  5.24425681e-09]],\\n\",\n       \"\\n\",\n       \"        [[-6.83394596e-09, -3.42148641e-08,  7.54065804e-09],\\n\",\n       \"         [-3.27715710e-09, -1.90193002e-08,  1.21379391e-08],\\n\",\n       \"         [ 2.88406700e-08, -5.90890261e-08, -1.60918778e-10],\\n\",\n       \"         [ 8.17658918e-09, -9.12644371e-09, -7.72941988e-10],\\n\",\n       \"         [-2.83711992e-08, -2.84839613e-08,  2.38575276e-08]]]])\"\n      ]\n     },\n     \"execution_count\": 14,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y-(a*X+b)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\\n\",\n    \"a_in = [int(a[i]*1e36) for i in range(3)]\\n\",\n    \"b_in = [int(b[i]*1e72) for i in range(3)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\\n\",\n    \"    X = [[[str(X_in[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    A = [str(a_in[k] % p) for k in range(nChannels)]\\n\",\n    \"    B = [str(b_in[k] % p) for k in range(nChannels)]\\n\",\n    \"    out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\\n\",\n    \"    remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\\n\",\n    \"    for i in range(nRows):\\n\",\n    \"        for j in range(nCols):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                out[i][j][k] = (X_in[i][j][k]*a_in[k] + b_in[k])\\n\",\n    \"                remainder[i][j][k] = str(out[i][j][k] % n)\\n\",\n    \"                out[i][j][k] = str(out[i][j][k] // n % p)\\n\",\n    \"    return X, A, B, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['157518693472490790243750538747957882',\\n\",\n       \"    '97372681162554733176887955075564208',\\n\",\n       \"    '679349834904288174010983420548472594'],\\n\",\n       \"   ['458774623717973004897590573896222594',\\n\",\n       \"    '527948304216263291457870336316333444',\\n\",\n       \"    '841137911182461164557826291121517336'],\\n\",\n       \"   ['408837279648365652067755038590177210',\\n\",\n       \"    '525950750084159001810559673300027574',\\n\",\n       \"    '630845109746686169695072155498068928'],\\n\",\n       \"   ['21888242871839275222246405745257275088548274708124961881757683904418357553907',\\n\",\n       \"    '21888242871839275222246405745257275088548170833903911058199291157862382757945',\\n\",\n       \"    '508230431470837755985412821877993851'],\\n\",\n       \"   ['832027574187245701393604967574752718',\\n\",\n       \"    '604919869501858267645833548353564313',\\n\",\n       \"    '279229541231612628393358090302516442']],\\n\",\n       \"  [['102287601417742280387289538163651204',\\n\",\n       \"    '160446511507058261099060517183710523',\\n\",\n       \"    '825962997148680811368987640325934077'],\\n\",\n       \"   ['847785374117952740336862359672140583',\\n\",\n       \"    '278484441349921535654657902103684959',\\n\",\n       \"    '657021670330123182657390893609651294'],\\n\",\n       \"   ['714883540765130856969303509707571514',\\n\",\n       \"    '900122628880346975580290622927866446',\\n\",\n       \"    '400594972054699631420351232955312561'],\\n\",\n       \"   ['10258476396616863842152239203344050',\\n\",\n       \"    '299578470108401435866442829726136156',\\n\",\n       \"    '21888242871839275222246405745257275088548299562044382966913364566037249574881'],\\n\",\n       \"   ['77034839563439930876087711734475167',\\n\",\n       \"    '69288844285022374454862035586080571',\\n\",\n       \"    '434714960531237722761063240822063770']],\\n\",\n       \"  [['21888242871839275222246405745257275088548360244503864875852868041600221908663',\\n\",\n       \"    '21888242871839275222246405745257275088548162277779161866355363655040683885335',\\n\",\n       \"    '100964708546126595514097434616933959'],\\n\",\n       \"   ['592579486784107682988589813640686405',\\n\",\n       \"    '21888242871839275222246405745257275088548354822146812280026576875315705275880',\\n\",\n       \"    '371326155748081420061854877950882957'],\\n\",\n       \"   ['783079042809927963587133644460156189',\\n\",\n       \"    '390118818517159008054052294744317319',\\n\",\n       \"    '211150813869290941494836799384423040'],\\n\",\n       \"   ['714145039231177651343799972971259701',\\n\",\n       \"    '21888242871839275222246405745257275088548307328444034834297413996208073048117',\\n\",\n       \"    '358680213163427345690379627175515214'],\\n\",\n       \"   ['329271159876734251530552022145153369',\\n\",\n       \"    '21888242871839275222246405745257275088548213224686425649934303811174716724822',\\n\",\n       \"    '578115673723270972200332905482236663']],\\n\",\n       \"  [['831706579403069869857935985454018004',\\n\",\n       \"    '701807327774318518191690249279384790',\\n\",\n       \"    '3057252040078645241914286618837645'],\\n\",\n       \"   ['511700680215072064258322477636183971',\\n\",\n       \"    '391018100666836853673874037122153517',\\n\",\n       \"    '671026146943898182863942504121469642'],\\n\",\n       \"   ['768458302604925592394191747899082690',\\n\",\n       \"    '886047516147519780735326653713713464',\\n\",\n       \"    '874408069845400225234489253410344667'],\\n\",\n       \"   ['222246091689917701515896532244187761',\\n\",\n       \"    '834417916490041372048913944859818527',\\n\",\n       \"    '558616976519438572914283702703657983'],\\n\",\n       \"   ['921297651648561583336105580618598710',\\n\",\n       \"    '615608412338983701988855791011481577',\\n\",\n       \"    '8447895170210076430444298018909113']],\\n\",\n       \"  [['541159338632499440419779390078898826',\\n\",\n       \"    '430662010552296997105829163483722657',\\n\",\n       \"    '267838708966299969534341921959286450'],\\n\",\n       \"   ['724836650787685688836352855376326828',\\n\",\n       \"    '21888242871839275222246405745257275088548274125221931276103456351742703907060',\\n\",\n       \"    '788047122738312175009071698929184108'],\\n\",\n       \"   ['348624796636930142430096079480218740',\\n\",\n       \"    '814245700320563240509607601046393243',\\n\",\n       \"    '64792439502463893211811777556988475'],\\n\",\n       \"   ['624326995779251861311046568986208844',\\n\",\n       \"    '387354949302453930827325825546488462',\\n\",\n       \"    '270056695518959509623672894764882809'],\\n\",\n       \"   ['971658675431593506453919504060069966',\\n\",\n       \"    '331506996028517098372582336349879273',\\n\",\n       \"    '570411181434220420525142442837712479']]],\\n\",\n       \" [[['960480586600175329574532373343633408',\\n\",\n       \"    '16700446728492295766061281370439680',\\n\",\n       \"    '379639810818394963719156481312948224'],\\n\",\n       \"   ['388476442819984282074088736716488704',\\n\",\n       \"    '605933780470969152068605021142384640',\\n\",\n       \"    '798916055303936274984266387226099712'],\\n\",\n       \"   ['468208661324380829760178449488543744',\\n\",\n       \"    '819358397205938578920215010284142592',\\n\",\n       \"    '21589625405262166471345886990434304'],\\n\",\n       \"   ['697307730873745656946722950128599040',\\n\",\n       \"    '484544812284374194987581109665005568',\\n\",\n       \"    '165375951315867937763795967171100672'],\\n\",\n       \"   ['245646470350672698747537604682448896',\\n\",\n       \"    '516198956417707676498067467442061312',\\n\",\n       \"    '851127713155083345720389185963032576']],\\n\",\n       \"  [['963964631181695048142847483580514304',\\n\",\n       \"    '717110020036717348293837961318891520',\\n\",\n       \"    '559953044877040683984591286389702656'],\\n\",\n       \"   ['18430124250391465600117066342334464',\\n\",\n       \"    '132070511117078294010171654032850944',\\n\",\n       \"    '159098461579690714866905242830635008'],\\n\",\n       \"   ['627161913358867337554883287034363904',\\n\",\n       \"    '214447136123138332377227662874116096',\\n\",\n       \"    '882093469775889964276298230664265728'],\\n\",\n       \"   ['506592892690571316134013534512087040',\\n\",\n       \"    '120413569434570423403255788841467904',\\n\",\n       \"    '363677450590533494361708506394918912'],\\n\",\n       \"   ['1589009160702191880025766302318592',\\n\",\n       \"    '606881345580479787255639207307116544',\\n\",\n       \"    '959500312602351349459070457955221504']],\\n\",\n       \"  [['269867103629848361043137830460588032',\\n\",\n       \"    '990156537691794618122141045295677440',\\n\",\n       \"    '865669682192046160291865685070446592'],\\n\",\n       \"   ['290313896548079828952332075043651584',\\n\",\n       \"    '864848850508538634449993085726228480',\\n\",\n       \"    '602632316683732661972508737477279744'],\\n\",\n       \"   ['522550745079433503690896029362683904',\\n\",\n       \"    '360374127352021396321849249139523584',\\n\",\n       \"    '232224328255243390445419547970240512'],\\n\",\n       \"   ['605064041602877244147525705785147392',\\n\",\n       \"    '199177740608395626314729675502387200',\\n\",\n       \"    '919073451728990826614299904488505344'],\\n\",\n       \"   ['360317325587177670121175102173216768',\\n\",\n       \"    '320159996958358401900225542972506112',\\n\",\n       \"    '149208972882417206108392691362430976']],\\n\",\n       \"  [['403450033176818573530952678489718784',\\n\",\n       \"    '489675097836673889083870450733285376',\\n\",\n       \"    '878348273706607180847862755205578752'],\\n\",\n       \"   ['971247092328484848039979691100078080',\\n\",\n       \"    '614717678863967773495129714821431296',\\n\",\n       \"    '354994706810685515240551471042789376'],\\n\",\n       \"   ['175120840317815376550047548614639616',\\n\",\n       \"    '256810812410679590717730062889648128',\\n\",\n       \"    '32500220595245784184833778997264384'],\\n\",\n       \"   ['820630970242119026496832796320858112',\\n\",\n       \"    '450959634440169857524579916622856192',\\n\",\n       \"    '993116187387119510197936862871420928'],\\n\",\n       \"   ['141575526471072789135353484131958784',\\n\",\n       \"    '424325045683895850778427312979312640',\\n\",\n       \"    '504193266510591745485938882812837888']],\\n\",\n       \"  [['58216472724137800358267959826710528',\\n\",\n       \"    '768052861880136122281533170251726848',\\n\",\n       \"    '416638974419576874572829739330830336'],\\n\",\n       \"   ['257711363123831457072460090222575616',\\n\",\n       \"    '770799881808654090050761531714437120',\\n\",\n       \"    '553150637395247721839782017066074112'],\\n\",\n       \"   ['576779513601307433086800237942538240',\\n\",\n       \"    '70762290041252423558033638227443712',\\n\",\n       \"    '501500349611164148444025032284307456'],\\n\",\n       \"   ['213252321414434873609495117362626560',\\n\",\n       \"    '168126301731513097227967825069473792',\\n\",\n       \"    '210589547132072037234216859745648640'],\\n\",\n       \"   ['192717389299758634733578375953121280',\\n\",\n       \"    '629763589047996081611699278760116224',\\n\",\n       \"    '631810269670576590942597092109975552']]])\"\n      ]\n     },\n     \"execution_count\": 17,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, a_in, b_in, out, remainder = BatchNormalizationInt(5, 5, 3, 10**36, X_in, a_in, b_in)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"a\\\": a_in,\\n\",\n    \"    \\\"b\\\": b_in,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"batchNormalization_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3.8.6 ('tf24')\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4,\n  \"vscode\": {\n   \"interpreter\": {\n    \"hash\": \"11280bdb37aa6bc5d4cf1e4de756386eb1f9eecd8dcdefa77636dfac7be2370d\"\n   }\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/conv1d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Conv1D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(20,3))\\n\",\n    \"x = Conv1D(2,4,3)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 20, 3)]           0         \\n\",\n      \"                                                                 \\n\",\n      \" conv1d (Conv1D)             (None, 6, 2)              26        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 26\\n\",\n      \"Trainable params: 26\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'conv1d/kernel:0' shape=(4, 3, 2) dtype=float32, numpy=\\n\",\n       \" array([[[-0.05840281, -0.33957317],\\n\",\n       \"         [ 0.2264623 ,  0.05825561],\\n\",\n       \"         [ 0.16525698,  0.23405397]],\\n\",\n       \" \\n\",\n       \"        [[-0.5258953 , -0.3936214 ],\\n\",\n       \"         [ 0.13454366, -0.22821242],\\n\",\n       \"         [ 0.03147739, -0.01196778]],\\n\",\n       \" \\n\",\n       \"        [[ 0.35090238,  0.1396572 ],\\n\",\n       \"         [ 0.40993017, -0.27508488],\\n\",\n       \"         [ 0.116602  , -0.148987  ]],\\n\",\n       \" \\n\",\n       \"        [[ 0.37122232,  0.08273119],\\n\",\n       \"         [-0.29717228,  0.53457487],\\n\",\n       \"         [ 0.49348652, -0.04242468]]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'conv1d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[0.66937516, 0.6907002 , 0.96996117],\\n\",\n       \"        [0.19520127, 0.13998107, 0.09311981],\\n\",\n       \"        [0.75079076, 0.02970836, 0.07441652],\\n\",\n       \"        [0.17415405, 0.83571587, 0.60334393],\\n\",\n       \"        [0.10381228, 0.77579617, 0.2255741 ],\\n\",\n       \"        [0.13918275, 0.12624822, 0.16357286],\\n\",\n       \"        [0.69068874, 0.44852818, 0.23029813],\\n\",\n       \"        [0.31139241, 0.79853943, 0.48135381],\\n\",\n       \"        [0.40343184, 0.82898376, 0.89517967],\\n\",\n       \"        [0.28514992, 0.60441284, 0.27842517],\\n\",\n       \"        [0.77636577, 0.32528131, 0.3163831 ],\\n\",\n       \"        [0.86428116, 0.89781672, 0.31025656],\\n\",\n       \"        [0.50292735, 0.79692487, 0.12686924],\\n\",\n       \"        [0.86170435, 0.41107323, 0.27543757],\\n\",\n       \"        [0.84957032, 0.38557172, 0.99614999],\\n\",\n       \"        [0.88438519, 0.51217387, 0.40840027],\\n\",\n       \"        [0.4354065 , 0.75060067, 0.30749656],\\n\",\n       \"        [0.18944417, 0.52536988, 0.2426369 ],\\n\",\n       \"        [0.75967469, 0.98044579, 0.15048149],\\n\",\n       \"        [0.80339604, 0.65717107, 0.64046179]]])\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,20,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 35ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:02:12.254810: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[ 0.59507644,  0.45122126],\\n\",\n       \"        [ 0.69210184,  0.1576352 ],\\n\",\n       \"        [ 0.70753413, -0.43526217],\\n\",\n       \"        [ 0.53165036, -0.09032159],\\n\",\n       \"        [ 0.7328447 , -0.33714917],\\n\",\n       \"        [ 0.38855883, -0.09487797]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[int(X[0][i][j]*1e36) for j in range(3)] for i in range(20)]\\n\",\n    \"weights = [[[int(model.weights[0].numpy()[i][j][k]*1e36) for k in range(2)] for j in range(3)] for i in range(4)]\\n\",\n    \"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\\n\",\n    \"    \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def Conv1DInt(nInputs, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    Input = [[str(input[i][j] % p) for j in range(nChannels)] for i in range(nInputs)]\\n\",\n    \"    Weights = [[[str(weights[i][j][k] % p) for k in range(nFilters)] for j in range(nChannels)] for i in range(kernelSize)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nFilters)]\\n\",\n    \"    out = [[0 for _ in range(nFilters)] for j in range((nInputs - kernelSize)//strides + 1)]\\n\",\n    \"    remainder = [[None for _ in range(nFilters)] for _ in range((nInputs - kernelSize)//strides + 1)]\\n\",\n    \"    for i in range((nInputs - kernelSize)//strides + 1):\\n\",\n    \"        for j in range(nFilters):\\n\",\n    \"            for k in range(kernelSize):\\n\",\n    \"                for l in range(nChannels):\\n\",\n    \"                    out[i][j] += input[i*strides + k][l]*weights[k][l][j]\\n\",\n    \"            out[i][j] += bias[j]\\n\",\n    \"            remainder[i][j] = str(out[i][j] % n)\\n\",\n    \"            out[i][j] = str(out[i][j] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([['595076432565314636873373017613140151',\\n\",\n       \"   '451221242188051044982898155310089176'],\\n\",\n       \"  ['692101791264109605416098691984234110',\\n\",\n       \"   '157635196511948127458268143134517909'],\\n\",\n       \"  ['707534041076922026686504470881153950',\\n\",\n       \"   '21888242871839275222246405745257275088547929138190672685567302106918640005237'],\\n\",\n       \"  ['531650362682809033665109229370302980',\\n\",\n       \"   '21888242871839275222246405745257275088548274078760710220327439407996310078926'],\\n\",\n       \"  ['732844672853217673574394205962948992',\\n\",\n       \"   '21888242871839275222246405745257275088548027251228401034660957748100577552406'],\\n\",\n       \"  ['388558804761306031693830030956978129',\\n\",\n       \"   '21888242871839275222246405745257275088548269522397035548207044857128138122494']],\\n\",\n       \" [['559476430118783401148220455172177920',\\n\",\n       \"   '798629717274041486200430078621384704'],\\n\",\n       \"  ['222725218484853070285693236889518080',\\n\",\n       \"   '703236219970385258366708181735833600'],\\n\",\n       \"  ['935243375755259327550534863114207232',\\n\",\n       \"   '629676730817043015262169534306451456'],\\n\",\n       \"  ['168613979210646022892058708579188736',\\n\",\n       \"   '20078824844870090673720198793527296'],\\n\",\n       \"  ['382452121618037097983987448914378752',\\n\",\n       \"   '384848670804947558045463129800835072'],\\n\",\n       \"  ['997624818969376769735560795535704064',\\n\",\n       \"   '607655476452490925911677042723651584']])\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, weights, bias, out, remainder = Conv1DInt(20, 3, 2, 4, 3, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"conv1D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/conv2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Conv2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = Conv2D(2, 3)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d (Conv2D)             (None, 3, 3, 2)           56        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 56\\n\",\n      \"Trainable params: 56\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 3, 2) dtype=float32, numpy=\\n\",\n       \" array([[[[-0.2214439 , -0.15195417],\\n\",\n       \"          [-0.33063164, -0.2934303 ],\\n\",\n       \"          [ 0.05383286, -0.29145738]],\\n\",\n       \" \\n\",\n       \"         [[-0.03459874, -0.18074483],\\n\",\n       \"          [ 0.0829632 , -0.18525888],\\n\",\n       \"          [-0.30195278,  0.28627008]],\\n\",\n       \" \\n\",\n       \"         [[-0.16308369, -0.00504276],\\n\",\n       \"          [ 0.3425789 ,  0.23431945],\\n\",\n       \"          [ 0.3600672 , -0.12323308]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[-0.32080007,  0.34273505],\\n\",\n       \"          [ 0.18235081,  0.10385716],\\n\",\n       \"          [-0.1344554 , -0.33093956]],\\n\",\n       \" \\n\",\n       \"         [[ 0.26645142,  0.13327193],\\n\",\n       \"          [ 0.14260197, -0.01873457],\\n\",\n       \"          [ 0.04164705,  0.09329805]],\\n\",\n       \" \\n\",\n       \"         [[ 0.22617143,  0.00685191],\\n\",\n       \"          [ 0.04963994,  0.23333359],\\n\",\n       \"          [ 0.35556698, -0.2943074 ]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[-0.01687273, -0.23511177],\\n\",\n       \"          [ 0.3297963 ,  0.34760195],\\n\",\n       \"          [ 0.03496316,  0.09493944]],\\n\",\n       \" \\n\",\n       \"         [[ 0.15188134, -0.36046585],\\n\",\n       \"          [ 0.03922135,  0.09752569],\\n\",\n       \"          [-0.07491425,  0.22700274]],\\n\",\n       \" \\n\",\n       \"         [[ 0.32842422,  0.10250565],\\n\",\n       \"          [-0.32919353,  0.12664899],\\n\",\n       \"          [-0.16168171,  0.34737545]]]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'conv2d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.01897312, 0.08743388, 0.86222637],\\n\",\n       \"         [0.10109003, 0.28028469, 0.47527166],\\n\",\n       \"         [0.01512083, 0.32085385, 0.55800198],\\n\",\n       \"         [0.4642667 , 0.30473978, 0.4908111 ],\\n\",\n       \"         [0.35508257, 0.37433134, 0.78504401]],\\n\",\n       \"\\n\",\n       \"        [[0.86741939, 0.20455078, 0.75628909],\\n\",\n       \"         [0.49125544, 0.77870243, 0.00276785],\\n\",\n       \"         [0.15663838, 0.57212579, 0.99557935],\\n\",\n       \"         [0.94449608, 0.24962475, 0.12299833],\\n\",\n       \"         [0.99733666, 0.01757025, 0.78783541]],\\n\",\n       \"\\n\",\n       \"        [[0.48878705, 0.12012174, 0.9315336 ],\\n\",\n       \"         [0.21785634, 0.36211795, 0.66387035],\\n\",\n       \"         [0.90845156, 0.08354312, 0.49792257],\\n\",\n       \"         [0.89275096, 0.48364178, 0.29199137],\\n\",\n       \"         [0.42604607, 0.48339958, 0.24699135]],\\n\",\n       \"\\n\",\n       \"        [[0.49614912, 0.82873805, 0.51174584],\\n\",\n       \"         [0.40336063, 0.91275723, 0.98636519],\\n\",\n       \"         [0.77062345, 0.9014581 , 0.37892572],\\n\",\n       \"         [0.70837991, 0.13523834, 0.27672346],\\n\",\n       \"         [0.80903352, 0.01406841, 0.65278234]],\\n\",\n       \"\\n\",\n       \"        [[0.04710218, 0.17104368, 0.60839461],\\n\",\n       \"         [0.15986631, 0.37473407, 0.20861406],\\n\",\n       \"         [0.53476587, 0.31278845, 0.93248025],\\n\",\n       \"         [0.62650735, 0.05244101, 0.57899892],\\n\",\n       \"         [0.24521627, 0.01355308, 0.20119521]]]])\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 31ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:04:35.358347: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[ 0.7669913 ,  0.15274508],\\n\",\n       \"         [ 0.7217935 ,  0.43549562],\\n\",\n       \"         [ 0.956968  , -0.7293344 ]],\\n\",\n       \"\\n\",\n       \"        [[ 0.82161874, -0.08652828],\\n\",\n       \"         [ 0.45854256,  0.37499383],\\n\",\n       \"         [ 0.6369549 , -0.12588985]],\\n\",\n       \"\\n\",\n       \"        [[ 0.3617655 ,  0.5265081 ],\\n\",\n       \"         [ 0.5842541 ,  0.11949164],\\n\",\n       \"         [ 0.6298134 , -0.148645  ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\\n\",\n    \"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(3)] for i in range(3)]\\n\",\n    \"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    Weights = [[[[str(weights[i][j][k][l] % p) for l in range(nFilters)] for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nFilters)]\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    for i in range((nRows - kernelSize)//strides + 1):\\n\",\n    \"        for j in range((nCols - kernelSize)//strides + 1):\\n\",\n    \"            for m in range(nFilters):\\n\",\n    \"                for k in range(nChannels):\\n\",\n    \"                    for x in range(kernelSize):\\n\",\n    \"                        for y in range(kernelSize):\\n\",\n    \"                            out[i][j][m] += input[i*strides+x][j*strides+y][k] * weights[x][y][k][m]\\n\",\n    \"                out[i][j][m] += bias[m]\\n\",\n    \"                remainder[i][j][m] = str(out[i][j][m] % n)\\n\",\n    \"                out[i][j][m] = str(out[i][j][m] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['766991308610348168697678317289253491',\\n\",\n       \"    '152745147346569443334783280814065046'],\\n\",\n       \"   ['721793514622685877535765261453578285',\\n\",\n       \"    '435495635689848419191313701414477907'],\\n\",\n       \"   ['956968022633247456612037533749279884',\\n\",\n       \"    '21888242871839275222246405745257275088547635065957648765434334612742599273530']],\\n\",\n       \"  [['821618728955717473031173417522483642',\\n\",\n       \"    '21888242871839275222246405745257275088548277872099372923381843387091765217066'],\\n\",\n       \"   ['458542547820893552234319995890476448',\\n\",\n       \"    '374993810980093272528286581550476085'],\\n\",\n       \"   ['636954799020811143676097566965150012',\\n\",\n       \"    '21888242871839275222246405745257275088548238510569604144298779927709876426450']],\\n\",\n       \"  [['361765493481699222011118768701693995',\\n\",\n       \"    '526508029475490175970042650793369367'],\\n\",\n       \"   ['584254113344261709635215513635894572',\\n\",\n       \"    '119491582294697734028918864863442650'],\\n\",\n       \"   ['629813449657849355217882687452958040',\\n\",\n       \"    '21888242871839275222246405745257275088548215755396606066460162924422748870356']]],\\n\",\n       \" [[['917380913441791641383057190580912128',\\n\",\n       \"    '941668043113108989243166859307515904'],\\n\",\n       \"   ['830888825756591443304789567910969344',\\n\",\n       \"    '959036987931483834969450172534226944'],\\n\",\n       \"   ['807238014162219891553337682966872064',\\n\",\n       \"    '654744816405601974137858933743681536']],\\n\",\n       \"  [['495502502940535931874336973827080192',\\n\",\n       \"    '508085363950388829219862699527110656'],\\n\",\n       \"   ['570521634763453322817882508314542080',\\n\",\n       \"    '580659632640246114717880425476259840'],\\n\",\n       \"   ['730760440116275911813925660727967744',\\n\",\n       \"    '404713594680872184361509627048755200']],\\n\",\n       \"  [['285034561505172240143276776062189568',\\n\",\n       \"    '246179226164944809810447582952947712'],\\n\",\n       \"   ['383405024202190176779250406231375872',\\n\",\n       \"    '48073795245569756634196992877133824'],\\n\",\n       \"   ['41512468028555336013994905783238656',\\n\",\n       \"    '807192458327115051492426645956984832']]])\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, weights, bias, out, remainder = Conv2DInt(5, 5, 3, 2, 3, 1, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"conv2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = Conv2D(2, 4, 3)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 10, 10, 3)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d_1 (Conv2D)           (None, 3, 3, 2)           98        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 98\\n\",\n      \"Trainable params: 98\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'conv2d_1/kernel:0' shape=(4, 4, 3, 2) dtype=float32, numpy=\\n\",\n       \" array([[[[-0.2644725 , -0.06314689],\\n\",\n       \"          [-0.19228128, -0.15511811],\\n\",\n       \"          [ 0.11695373,  0.15373573]],\\n\",\n       \" \\n\",\n       \"         [[-0.25127184, -0.03327389],\\n\",\n       \"          [ 0.06582499,  0.13954943],\\n\",\n       \"          [-0.02274385, -0.24024239]],\\n\",\n       \" \\n\",\n       \"         [[-0.27345484,  0.07233012],\\n\",\n       \"          [ 0.03240535, -0.1362924 ],\\n\",\n       \"          [ 0.16554734, -0.19980597]],\\n\",\n       \" \\n\",\n       \"         [[ 0.12271923, -0.16348948],\\n\",\n       \"          [-0.24399345,  0.11112538],\\n\",\n       \"          [ 0.04153693,  0.09944585]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[ 0.07061589,  0.08067289],\\n\",\n       \"          [-0.25938636, -0.04698843],\\n\",\n       \"          [-0.18615322, -0.18926641]],\\n\",\n       \" \\n\",\n       \"         [[ 0.06828818,  0.10024589],\\n\",\n       \"          [-0.06301631, -0.21391404],\\n\",\n       \"          [ 0.17798159,  0.16077739]],\\n\",\n       \" \\n\",\n       \"         [[-0.18883933, -0.24141382],\\n\",\n       \"          [-0.1410877 , -0.1870578 ],\\n\",\n       \"          [-0.17638391,  0.12909776]],\\n\",\n       \" \\n\",\n       \"         [[ 0.24995095, -0.27214956],\\n\",\n       \"          [-0.16633804, -0.24534652],\\n\",\n       \"          [ 0.09470761, -0.1752578 ]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[-0.26973695, -0.16573134],\\n\",\n       \"          [ 0.0093652 ,  0.23317659],\\n\",\n       \"          [ 0.13521832, -0.18823144]],\\n\",\n       \" \\n\",\n       \"         [[ 0.1731261 ,  0.15210795],\\n\",\n       \"          [ 0.11972865,  0.11824197],\\n\",\n       \"          [-0.20316267, -0.01294529]],\\n\",\n       \" \\n\",\n       \"         [[ 0.14585042,  0.22254854],\\n\",\n       \"          [ 0.15764701,  0.0891107 ],\\n\",\n       \"          [ 0.00702351,  0.17262942]],\\n\",\n       \" \\n\",\n       \"         [[ 0.06677854, -0.07873373],\\n\",\n       \"          [-0.26536292, -0.1721809 ],\\n\",\n       \"          [-0.12418044, -0.11808449]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[ 0.09153298,  0.18611383],\\n\",\n       \"          [ 0.14009333, -0.19381046],\\n\",\n       \"          [-0.27251363,  0.07429421]],\\n\",\n       \" \\n\",\n       \"         [[ 0.12720028, -0.08216412],\\n\",\n       \"          [ 0.14116141, -0.10473494],\\n\",\n       \"          [-0.01652202, -0.11998361]],\\n\",\n       \" \\n\",\n       \"         [[-0.010129  ,  0.12356687],\\n\",\n       \"          [-0.00215057,  0.17525265],\\n\",\n       \"          [ 0.26925737,  0.18551975]],\\n\",\n       \" \\n\",\n       \"         [[-0.1616565 , -0.14463529],\\n\",\n       \"          [-0.18055108,  0.2564476 ],\\n\",\n       \"          [ 0.19239256, -0.11366163]]]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'conv2d_1/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.74916437, 0.48058547, 0.76332072],\\n\",\n       \"         [0.12424725, 0.17444765, 0.23397784],\\n\",\n       \"         [0.05504572, 0.73761126, 0.8872156 ],\\n\",\n       \"         [0.49900099, 0.92746041, 0.53705474],\\n\",\n       \"         [0.55972545, 0.16210532, 0.48132197],\\n\",\n       \"         [0.5848511 , 0.49854495, 0.08101739],\\n\",\n       \"         [0.18151106, 0.19916602, 0.72216404],\\n\",\n       \"         [0.8740212 , 0.76936566, 0.77574156],\\n\",\n       \"         [0.640459  , 0.97982307, 0.28733369],\\n\",\n       \"         [0.72894846, 0.08559827, 0.88796122]],\\n\",\n       \"\\n\",\n       \"        [[0.72655621, 0.74204472, 0.22625834],\\n\",\n       \"         [0.04455912, 0.02637621, 0.7410693 ],\\n\",\n       \"         [0.59282978, 0.27570664, 0.76839831],\\n\",\n       \"         [0.98853958, 0.32472733, 0.07214331],\\n\",\n       \"         [0.18975449, 0.50827871, 0.61454778],\\n\",\n       \"         [0.04411632, 0.5425321 , 0.08095671],\\n\",\n       \"         [0.98276969, 0.93905031, 0.27580299],\\n\",\n       \"         [0.01991902, 0.18288148, 0.56430848],\\n\",\n       \"         [0.60873785, 0.76133969, 0.94420434],\\n\",\n       \"         [0.29177495, 0.60971797, 0.75330394]],\\n\",\n       \"\\n\",\n       \"        [[0.73958658, 0.86792802, 0.38199042],\\n\",\n       \"         [0.60758291, 0.04444527, 0.89773701],\\n\",\n       \"         [0.81378908, 0.74925507, 0.94127002],\\n\",\n       \"         [0.52276966, 0.71515635, 0.0673889 ],\\n\",\n       \"         [0.88674225, 0.85171248, 0.25796752],\\n\",\n       \"         [0.06304501, 0.02557175, 0.7862988 ],\\n\",\n       \"         [0.13024858, 0.03026337, 0.53165512],\\n\",\n       \"         [0.98698478, 0.10343698, 0.14793739],\\n\",\n       \"         [0.19595613, 0.4755287 , 0.69081615],\\n\",\n       \"         [0.63616236, 0.64746281, 0.70686306]],\\n\",\n       \"\\n\",\n       \"        [[0.90697061, 0.70755438, 0.17101648],\\n\",\n       \"         [0.91618436, 0.75457803, 0.3753285 ],\\n\",\n       \"         [0.10891312, 0.63256771, 0.66998965],\\n\",\n       \"         [0.0031363 , 0.8577421 , 0.44313256],\\n\",\n       \"         [0.97431053, 0.31491313, 0.52870403],\\n\",\n       \"         [0.84949509, 0.57476833, 0.35833646],\\n\",\n       \"         [0.3259322 , 0.61810256, 0.97382616],\\n\",\n       \"         [0.92587238, 0.93189425, 0.02385008],\\n\",\n       \"         [0.91665173, 0.21392593, 0.48478448],\\n\",\n       \"         [0.43780191, 0.31732276, 0.10383084]],\\n\",\n       \"\\n\",\n       \"        [[0.40302491, 0.18641359, 0.28439078],\\n\",\n       \"         [0.80467361, 0.95795027, 0.76525912],\\n\",\n       \"         [0.09050706, 0.05142721, 0.5484936 ],\\n\",\n       \"         [0.72498561, 0.5350264 , 0.47320043],\\n\",\n       \"         [0.83032011, 0.36968621, 0.17519239],\\n\",\n       \"         [0.80183789, 0.53486298, 0.63113123],\\n\",\n       \"         [0.98299635, 0.17220543, 0.99893277],\\n\",\n       \"         [0.98120285, 0.15965491, 0.11500732],\\n\",\n       \"         [0.50294074, 0.54067477, 0.58704542],\\n\",\n       \"         [0.30811939, 0.86034992, 0.96053741]],\\n\",\n       \"\\n\",\n       \"        [[0.51231231, 0.36679594, 0.6387736 ],\\n\",\n       \"         [0.39364612, 0.65398604, 0.18194537],\\n\",\n       \"         [0.53904627, 0.31794439, 0.95598346],\\n\",\n       \"         [0.8201467 , 0.01759052, 0.21272062],\\n\",\n       \"         [0.8265654 , 0.62113986, 0.56095777],\\n\",\n       \"         [0.24749834, 0.71107743, 0.22825303],\\n\",\n       \"         [0.17445456, 0.27443303, 0.53532667],\\n\",\n       \"         [0.46250432, 0.81471236, 0.01852107],\\n\",\n       \"         [0.86219207, 0.21628477, 0.98052948],\\n\",\n       \"         [0.34121289, 0.33599059, 0.95218908]],\\n\",\n       \"\\n\",\n       \"        [[0.37520805, 0.46358272, 0.96812602],\\n\",\n       \"         [0.08123441, 0.61637145, 0.90839157],\\n\",\n       \"         [0.40060218, 0.47543454, 0.64913812],\\n\",\n       \"         [0.90053796, 0.70871333, 0.55043711],\\n\",\n       \"         [0.39746646, 0.30778257, 0.88554719],\\n\",\n       \"         [0.86349263, 0.11219438, 0.85574671],\\n\",\n       \"         [0.62224992, 0.48989345, 0.63991367],\\n\",\n       \"         [0.99134928, 0.98989598, 0.6173012 ],\\n\",\n       \"         [0.04768804, 0.33779174, 0.18604113],\\n\",\n       \"         [0.01957013, 0.57973428, 0.7495305 ]],\\n\",\n       \"\\n\",\n       \"        [[0.10672299, 0.71601061, 0.03377451],\\n\",\n       \"         [0.87905429, 0.78474207, 0.59381131],\\n\",\n       \"         [0.90857691, 0.96590608, 0.56500479],\\n\",\n       \"         [0.13149743, 0.52407683, 0.23988054],\\n\",\n       \"         [0.56993435, 0.26299209, 0.7549793 ],\\n\",\n       \"         [0.52225825, 0.6448658 , 0.04444777],\\n\",\n       \"         [0.03641049, 0.37206738, 0.94614889],\\n\",\n       \"         [0.51144329, 0.88620609, 0.59531982],\\n\",\n       \"         [0.45414305, 0.41827663, 0.08097343],\\n\",\n       \"         [0.40615607, 0.26751879, 0.03898047]],\\n\",\n       \"\\n\",\n       \"        [[0.89224853, 0.12348574, 0.32034526],\\n\",\n       \"         [0.64800157, 0.82504082, 0.19296447],\\n\",\n       \"         [0.88471839, 0.64119493, 0.03698128],\\n\",\n       \"         [0.99176407, 0.59193617, 0.30150652],\\n\",\n       \"         [0.72020934, 0.56545044, 0.91065986],\\n\",\n       \"         [0.80514643, 0.29937785, 0.74242392],\\n\",\n       \"         [0.09456567, 0.46145516, 0.554788  ],\\n\",\n       \"         [0.46704768, 0.33370513, 0.56795916],\\n\",\n       \"         [0.55089935, 0.89252818, 0.01030941],\\n\",\n       \"         [0.68112324, 0.5390893 , 0.31510111]],\\n\",\n       \"\\n\",\n       \"        [[0.94967068, 0.7825868 , 0.22214195],\\n\",\n       \"         [0.8453802 , 0.98304469, 0.98455021],\\n\",\n       \"         [0.50376912, 0.29307285, 0.78424416],\\n\",\n       \"         [0.26351673, 0.24259793, 0.48663014],\\n\",\n       \"         [0.42359605, 0.48513857, 0.55338817],\\n\",\n       \"         [0.22229073, 0.02676846, 0.15701487],\\n\",\n       \"         [0.35682851, 0.72597313, 0.64578716],\\n\",\n       \"         [0.60649997, 0.55222217, 0.01019997],\\n\",\n       \"         [0.28450479, 0.20816085, 0.19723797],\\n\",\n       \"         [0.95701904, 0.54230762, 0.38779384]]]])\"\n      ]\n     },\n     \"execution_count\": 17,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 22ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[-0.02103192, -0.00251862],\\n\",\n       \"         [-0.13590473, -0.43280643],\\n\",\n       \"         [-0.46592993, -0.6076722 ]],\\n\",\n       \"\\n\",\n       \"        [[-0.41985548, -0.28316095],\\n\",\n       \"         [-0.5124401 , -0.67603445],\\n\",\n       \"         [-0.30362517, -0.35066307]],\\n\",\n       \"\\n\",\n       \"        [[ 0.04719239, -0.77217025],\\n\",\n       \"         [-0.90729254, -0.5460546 ],\\n\",\n       \"         [-0.6157329 , -0.56018454]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\\n\",\n    \"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(4)] for i in range(4)]\\n\",\n    \"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['21888242871839275222246405745257275088548343368429240512769054624061005959510',\\n\",\n       \"    '21888242871839275222246405745257275088548361881856976212445268734113123308000'],\\n\",\n       \"   ['21888242871839275222246405745257275088548228495669861064087547662558271715284',\\n\",\n       \"    '21888242871839275222246405745257275088547931594040764149614699120473995978124'],\\n\",\n       \"   ['21888242871839275222246405745257275088547898470480336398546468994244949638791',\\n\",\n       \"    '21888242871839275222246405745257275088547756728190784802798484857861334105370']],\\n\",\n       \"  [['21888242871839275222246405745257275088547944544909737422432087456874316949324',\\n\",\n       \"    '21888242871839275222246405745257275088548081239515185091772880603232052577114'],\\n\",\n       \"   ['21888242871839275222246405745257275088547851960358367500079371782793385911358',\\n\",\n       \"    '21888242871839275222246405745257275088547688365801627855012444638213091512422'],\\n\",\n       \"   ['21888242871839275222246405745257275088548060775297780413313747663983226225838',\\n\",\n       \"    '21888242871839275222246405745257275088548013737249302248990923589248334943730']],\\n\",\n       \"  [['47192436853842599651386952076755831',\\n\",\n       \"    '21888242871839275222246405745257275088547592230115531216981433877552691800835'],\\n\",\n       \"   ['21888242871839275222246405745257275088547457107943733886642827877231280519319',\\n\",\n       \"    '21888242871839275222246405745257275088547818345751775722192552561821918626804'],\\n\",\n       \"   ['21888242871839275222246405745257275088547748667480051924165721939129997507240',\\n\",\n       \"    '21888242871839275222246405745257275088547804215881906491939765109262983554318']]],\\n\",\n       \" [[['268679458635749205024295605371928576',\\n\",\n       \"    '388806143166359782280358980933910528'],\\n\",\n       \"   ['587604291442575449740007779803856896',\\n\",\n       \"    '881363922854357799836717369522126848'],\\n\",\n       \"   ['861312932060957897553390674280185856',\\n\",\n       \"    '857846252928472736899563405831045120']],\\n\",\n       \"  [['84829649070177990320832563715768320',\\n\",\n       \"    '765867543468158475751770347286822912'],\\n\",\n       \"   ['238136771858729786452041694885969920',\\n\",\n       \"    '231361799849937010319349760697303040'],\\n\",\n       \"   ['357728239843398972090727278133116928',\\n\",\n       \"    '121546057864506428255684370605539328']],\\n\",\n       \"  [['568749905268752884676825625665732608',\\n\",\n       \"    '218395840383827537600516408079286272'],\\n\",\n       \"   ['390713141622087796116893701035261952',\\n\",\n       \"    '52043981850152859332227036686057472'],\\n\",\n       \"   ['355515461237650726718816599152787456',\\n\",\n       \"    '178351211698736250757067221797699584']]])\"\n      ]\n     },\n     \"execution_count\": 20,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, weights, bias, out, remainder = Conv2DInt(10, 10, 3, 2, 4, 3, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"conv2D_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/conv2d_same.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Conv2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = Conv2D(2, 3, padding=\\\"same\\\")(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d (Conv2D)             (None, 5, 5, 2)           56        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 56\\n\",\n      \"Trainable params: 56\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 3, 2) dtype=float32, numpy=\\n\",\n       \" array([[[[-0.22388998,  0.18217945],\\n\",\n       \"          [-0.31254017,  0.13933456],\\n\",\n       \"          [-0.14491144,  0.01168695]],\\n\",\n       \" \\n\",\n       \"         [[-0.18442051,  0.16668755],\\n\",\n       \"          [-0.15052032, -0.1277689 ],\\n\",\n       \"          [-0.17660408, -0.25577286]],\\n\",\n       \" \\n\",\n       \"         [[-0.3273484 ,  0.06551823],\\n\",\n       \"          [ 0.02335805,  0.30579627],\\n\",\n       \"          [ 0.05012453,  0.05196694]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[-0.15296353, -0.28653675],\\n\",\n       \"          [ 0.31760007,  0.27596015],\\n\",\n       \"          [ 0.06140944,  0.28459537]],\\n\",\n       \" \\n\",\n       \"         [[-0.271937  ,  0.3022167 ],\\n\",\n       \"          [ 0.34724104,  0.3508402 ],\\n\",\n       \"          [-0.26121286, -0.10477605]],\\n\",\n       \" \\n\",\n       \"         [[ 0.18311954,  0.15618789],\\n\",\n       \"          [ 0.21608043,  0.07763481],\\n\",\n       \"          [-0.17695144, -0.29946056]]],\\n\",\n       \" \\n\",\n       \" \\n\",\n       \"        [[[ 0.2186423 ,  0.2389586 ],\\n\",\n       \"          [-0.2976641 , -0.30056122],\\n\",\n       \"          [-0.35727727, -0.3631401 ]],\\n\",\n       \" \\n\",\n       \"         [[-0.04230955, -0.15279846],\\n\",\n       \"          [ 0.06897295, -0.08147189],\\n\",\n       \"          [-0.30367035,  0.21289521]],\\n\",\n       \" \\n\",\n       \"         [[-0.2920769 , -0.22767249],\\n\",\n       \"          [-0.29041147, -0.2403323 ],\\n\",\n       \"          [-0.20408599, -0.23004377]]]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'conv2d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.57357832, 0.79689708, 0.54481385],\\n\",\n       \"         [0.95096481, 0.06302099, 0.53424686],\\n\",\n       \"         [0.14555327, 0.16801407, 0.91837743],\\n\",\n       \"         [0.14042694, 0.26466775, 0.0754911 ],\\n\",\n       \"         [0.19354151, 0.89796698, 0.18080666]],\\n\",\n       \"\\n\",\n       \"        [[0.84893864, 0.94689375, 0.76889793],\\n\",\n       \"         [0.91280106, 0.81211903, 0.50614878],\\n\",\n       \"         [0.72629997, 0.09620774, 0.05074255],\\n\",\n       \"         [0.30178926, 0.4854865 , 0.46486629],\\n\",\n       \"         [0.87558861, 0.93289185, 0.33965317]],\\n\",\n       \"\\n\",\n       \"        [[0.23726595, 0.09253935, 0.08598877],\\n\",\n       \"         [0.24484708, 0.00811252, 0.23642884],\\n\",\n       \"         [0.65975124, 0.63633904, 0.82507772],\\n\",\n       \"         [0.53100731, 0.72433054, 0.66373751],\\n\",\n       \"         [0.43916625, 0.74347257, 0.6772263 ]],\\n\",\n       \"\\n\",\n       \"        [[0.87412193, 0.53853422, 0.34772628],\\n\",\n       \"         [0.7738511 , 0.97565729, 0.94426861],\\n\",\n       \"         [0.21537231, 0.65774623, 0.89405016],\\n\",\n       \"         [0.7411118 , 0.68792609, 0.3272619 ],\\n\",\n       \"         [0.44887834, 0.924486  , 0.48269841]],\\n\",\n       \"\\n\",\n       \"        [[0.13952337, 0.79659803, 0.97603335],\\n\",\n       \"         [0.66099459, 0.06934143, 0.99854059],\\n\",\n       \"         [0.31609368, 0.49596104, 0.93797069],\\n\",\n       \"         [0.04941322, 0.24709554, 0.58384416],\\n\",\n       \"         [0.71527804, 0.48976864, 0.98763569]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 51ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2024-02-04 01:25:53.532541: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[-0.7382064 , -0.17332056],\\n\",\n       \"         [-1.034698  , -0.43408912],\\n\",\n       \"         [-0.83073455, -0.6865788 ],\\n\",\n       \"         [-0.28542495,  0.0770359 ],\\n\",\n       \"         [-0.04129319,  0.02877748]],\\n\",\n       \"\\n\",\n       \"        [[-0.60671365,  0.38846642],\\n\",\n       \"         [-1.1027374 ,  0.71167284],\\n\",\n       \"         [-1.2792461 , -0.10405768],\\n\",\n       \"         [-1.1375024 , -0.28573734],\\n\",\n       \"         [-0.7037988 ,  0.3554073 ]],\\n\",\n       \"\\n\",\n       \"        [[-1.5469512 , -0.50975496],\\n\",\n       \"         [-2.0071907 , -0.25512454],\\n\",\n       \"         [-1.9879558 ,  0.09278526],\\n\",\n       \"         [-1.5013543 , -0.14000578],\\n\",\n       \"         [-0.7585893 ,  0.43752092]],\\n\",\n       \"\\n\",\n       \"        [[-0.7614179 ,  0.09177176],\\n\",\n       \"         [-1.688165  , -0.25309083],\\n\",\n       \"         [-0.8684121 ,  0.42702955],\\n\",\n       \"         [-1.6322078 ,  0.3133433 ],\\n\",\n       \"         [-1.1236074 ,  0.2770568 ]],\\n\",\n       \"\\n\",\n       \"        [[-0.54382604,  0.415062  ],\\n\",\n       \"         [-1.0068984 ,  0.6469521 ],\\n\",\n       \"         [-1.3391564 ,  0.42430705],\\n\",\n       \"         [-0.6338484 ,  0.63813394],\\n\",\n       \"         [-0.9111921 ,  0.5726407 ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\\n\",\n    \"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(3)] for i in range(3)]\\n\",\n    \"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    for i in range((nRows - kernelSize)//strides + 1):\\n\",\n    \"        for j in range((nCols - kernelSize)//strides + 1):\\n\",\n    \"            for m in range(nFilters):\\n\",\n    \"                for k in range(nChannels):\\n\",\n    \"                    for x in range(kernelSize):\\n\",\n    \"                        for y in range(kernelSize):\\n\",\n    \"                            out[i][j][m] += int(input[i*strides+x][j*strides+y][k])*int(weights[x][y][k][m])\\n\",\n    \"                out[i][j][m] += int(bias[m])\\n\",\n    \"                remainder[i][j][m] = str(out[i][j][m] % n)\\n\",\n    \"                out[i][j][m] = str(out[i][j][m] // n)\\n\",\n    \"    return out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def Conv2DsameInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    if nRows % strides == 0:\\n\",\n    \"        rowPadding = max(kernelSize - strides, 0)\\n\",\n    \"    else:\\n\",\n    \"        rowPadding = max(kernelSize - nRows % strides, 0)\\n\",\n    \"    if nCols % strides == 0:\\n\",\n    \"        colPadding = max(kernelSize - strides, 0)\\n\",\n    \"    else:\\n\",\n    \"        colPadding = max(kernelSize - nCols % strides, 0)\\n\",\n    \"    \\n\",\n    \"    _input = [[[0 for _ in range(nChannels)] for _ in range(nCols + colPadding)] for _ in range(nRows + rowPadding)]\\n\",\n    \"\\n\",\n    \"    for i in range(nRows):\\n\",\n    \"        for j in range(nCols):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                _input[i+rowPadding//2][j+colPadding//2][k] = input[i][j][k]\\n\",\n    \"    \\n\",\n    \"    out, remainder = Conv2DInt(nRows + rowPadding, nCols + colPadding, nChannels, nFilters, kernelSize, strides, n, _input, weights, bias)\\n\",\n    \"    return out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['-738206413373029545006965393527124494',\\n\",\n       \"    '-173320559228639935825945330543413025'],\\n\",\n       \"   ['-1034698083357167138897799627355946893',\\n\",\n       \"    '-434089078628623353676508551211157060'],\\n\",\n       \"   ['-830734559502817036444813835112148949',\\n\",\n       \"    '-686578771866623630758607927275546159'],\\n\",\n       \"   ['-285424960673894669036410085848276078',\\n\",\n       \"    '77035899885765173133597720803628368'],\\n\",\n       \"   ['-41293201078409047199874417933080796',\\n\",\n       \"    '28777494655737863382696013669386951']],\\n\",\n       \"  [['-606713676308333020774846244444307246',\\n\",\n       \"    '388466467207809267549922375129065936'],\\n\",\n       \"   ['-1102737485952039787132334772316590877',\\n\",\n       \"    '711672842283067459049106389539428334'],\\n\",\n       \"   ['-1279246107747464951673577203827572661',\\n\",\n       \"    '-104057682619248993879676863654015882'],\\n\",\n       \"   ['-1137502411882990109129978808062308003',\\n\",\n       \"    '-285737283216816113761016693211231047'],\\n\",\n       \"   ['-703798773277911056745141956845225462',\\n\",\n       \"    '355407338114374779173330249858051758']],\\n\",\n       \"  [['-1546951103062535866431703941066730304',\\n\",\n       \"    '-509754977574520651977576289008629976'],\\n\",\n       \"   ['-2007190678249673958423804906616390874',\\n\",\n       \"    '-255124530399913653884258580354194679'],\\n\",\n       \"   ['-1987955686599915815112948301772925117',\\n\",\n       \"    '92785353760923841311068732708486389'],\\n\",\n       \"   ['-1501354303867896914042548115076362343',\\n\",\n       \"    '-140005761885967356612636419407991713'],\\n\",\n       \"   ['-758589315783580773280487949446211355',\\n\",\n       \"    '437520880361906870599644364227465106']],\\n\",\n       \"  [['-761417923444182653301008173638043967',\\n\",\n       \"    '91771720385437306243354293205033102'],\\n\",\n       \"   ['-1688165103880073226811051249397561256',\\n\",\n       \"    '-253090840416308272240635021911178871'],\\n\",\n       \"   ['-868411975706764838263900420928401111',\\n\",\n       \"    '427029536451544469306217379046517378'],\\n\",\n       \"   ['-1632207770832291707418877818442334628',\\n\",\n       \"    '313343146963309014974813849350304619'],\\n\",\n       \"   ['-1123607486465218134583708408995464790',\\n\",\n       \"    '277056825693143901704758542110909098']],\\n\",\n       \"  [['-543826042689234949496060048498817249',\\n\",\n       \"    '415061953419939109346123158429653654'],\\n\",\n       \"   ['-1006898403524974693098527575437710832',\\n\",\n       \"    '646952095929760474345606121011841547'],\\n\",\n       \"   ['-1339156364320875137533821288468963984',\\n\",\n       \"    '424307047679243230200796457433761030'],\\n\",\n       \"   ['-633848388019879384336947814123500320',\\n\",\n       \"    '638133921526842615943818078787826079'],\\n\",\n       \"   ['-911192101070039979166490878519403558',\\n\",\n       \"    '572640728975516234503728848776059996']]],\\n\",\n       \" [[['732636700329184288172821299452706816',\\n\",\n       \"    '163633766656393366871975061931163648'],\\n\",\n       \"   ['106376739450670706774435272610283520',\\n\",\n       \"    '224263678919132314456428282264944640'],\\n\",\n       \"   ['302563808180207575103565765357338624',\\n\",\n       \"    '724302115124451087131827274648649728'],\\n\",\n       \"   ['414653571797565705485911652130881536',\\n\",\n       \"    '793412538503882240528593488489480192'],\\n\",\n       \"   ['802744020509610387937821108140507136',\\n\",\n       \"    '304480836101726291197711385865748480']],\\n\",\n       \"  [['859770729700736535878340696623546368',\\n\",\n       \"    '892305185639885971968166660350672896'],\\n\",\n       \"   ['159017773966938546227144022541991936',\\n\",\n       \"    '243286973980475632014665402361577472'],\\n\",\n       \"   ['45707991996386548824583584683655168',\\n\",\n       \"    '305057405020119480420035216424304640'],\\n\",\n       \"   ['513655874550133048911800632902418432',\\n\",\n       \"    '966709976332017469863264280209522688'],\\n\",\n       \"   ['198125756383956075595551934970331136',\\n\",\n       \"    '988945351929415067553212891893071872']],\\n\",\n       \"  [['787267116688540528237625132699353088',\\n\",\n       \"    '820149329025927193528840575260819456'],\\n\",\n       \"   ['472980868351632170335228269959315456',\\n\",\n       \"    '763189020330031063201267188022378496'],\\n\",\n       \"   ['644197050565810210754859371753111552',\\n\",\n       \"    '989731482915520051484045079570546688'],\\n\",\n       \"   ['948204822800878014118539586611183616',\\n\",\n       \"    '748247265754602884949081086979211264'],\\n\",\n       \"   ['716169397100995271731495802811449344',\\n\",\n       \"    '485403242675801265137341039288254464']],\\n\",\n       \"  [['43352138962814326789218918981435392',\\n\",\n       \"    '405166142631707980272441068569493504'],\\n\",\n       \"   ['810091229170266512829629243259355136',\\n\",\n       \"    '269653910662555626980942633563586560'],\\n\",\n       \"   ['676839398629154231820514533721505792',\\n\",\n       \"    '419805522694742694500594416384737280'],\\n\",\n       \"   ['745383827341964610018052023030644736',\\n\",\n       \"    '256049836598014041054468595098058752'],\\n\",\n       \"   ['675940914936064095590762595072606208',\\n\",\n       \"    '261569026192941931124614732445646848']],\\n\",\n       \"  [['945584600952117166014909825389953024',\\n\",\n       \"    '419123852798410471873927944123449344'],\\n\",\n       \"   ['610870231548665514822003410375540736',\\n\",\n       \"    '444338394948450192884055088832708608'],\\n\",\n       \"   ['392811864299264176482313886100357120',\\n\",\n       \"    '482398655357498430014877178936688640'],\\n\",\n       \"   ['865948833234167064622566980785799168',\\n\",\n       \"    '886966130974971444248685772183437312'],\\n\",\n       \"   ['195220905237827872879130999353507840',\\n\",\n       \"    '356250510761353797733544351900893184']]])\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"out, remainder = Conv2DsameInt(5, 5, 3, 2, 3, 1, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"conv2Dsame_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = Conv2D(2, 4, 3, padding=\\\"same\\\")(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 10, 10, 3)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d_1 (Conv2D)           (None, 4, 4, 2)           98        \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 98\\n\",\n      \"Trainable params: 98\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.15917131, 0.77313235, 0.70732347],\\n\",\n       \"         [0.85210236, 0.77747055, 0.9126757 ],\\n\",\n       \"         [0.93479056, 0.819227  , 0.70156189],\\n\",\n       \"         [0.79143794, 0.87801591, 0.82904976],\\n\",\n       \"         [0.68619248, 0.52939185, 0.9781374 ],\\n\",\n       \"         [0.60719573, 0.89925314, 0.76945961],\\n\",\n       \"         [0.87552557, 0.90534932, 0.87889951],\\n\",\n       \"         [0.3906682 , 0.95580616, 0.31789736],\\n\",\n       \"         [0.76477277, 0.81754225, 0.69839668],\\n\",\n       \"         [0.83091809, 0.08929047, 0.41690024]],\\n\",\n       \"\\n\",\n       \"        [[0.02156404, 0.1248342 , 0.10101914],\\n\",\n       \"         [0.89801399, 0.26753341, 0.07441736],\\n\",\n       \"         [0.02208311, 0.63957509, 0.89741475],\\n\",\n       \"         [0.34053784, 0.26694358, 0.75715605],\\n\",\n       \"         [0.53780638, 0.65565436, 0.91504456],\\n\",\n       \"         [0.25938895, 0.93164592, 0.89508771],\\n\",\n       \"         [0.59673249, 0.83579125, 0.43718874],\\n\",\n       \"         [0.15159799, 0.74559263, 0.75890839],\\n\",\n       \"         [0.14960964, 0.72981249, 0.3738258 ],\\n\",\n       \"         [0.77609438, 0.61152145, 0.26743727]],\\n\",\n       \"\\n\",\n       \"        [[0.86386277, 0.08854458, 0.1881181 ],\\n\",\n       \"         [0.44605901, 0.5362032 , 0.35993523],\\n\",\n       \"         [0.30153601, 0.2052692 , 0.94686662],\\n\",\n       \"         [0.19258428, 0.29545743, 0.67123322],\\n\",\n       \"         [0.64059575, 0.25641094, 0.1195399 ],\\n\",\n       \"         [0.38441147, 0.12147883, 0.39661277],\\n\",\n       \"         [0.58068678, 0.99196337, 0.80942971],\\n\",\n       \"         [0.42854507, 0.58075105, 0.17898182],\\n\",\n       \"         [0.59835861, 0.53916735, 0.58269423],\\n\",\n       \"         [0.73442298, 0.50103808, 0.55618813]],\\n\",\n       \"\\n\",\n       \"        [[0.70220035, 0.65299784, 0.06720906],\\n\",\n       \"         [0.98439586, 0.49217928, 0.29110757],\\n\",\n       \"         [0.40362701, 0.31214552, 0.33877257],\\n\",\n       \"         [0.63058855, 0.35760424, 0.46940153],\\n\",\n       \"         [0.13804137, 0.06058852, 0.55080509],\\n\",\n       \"         [0.76085309, 0.65603233, 0.76855789],\\n\",\n       \"         [0.82109332, 0.28625298, 0.5198722 ],\\n\",\n       \"         [0.52934891, 0.98676823, 0.45172351],\\n\",\n       \"         [0.26726209, 0.85657565, 0.95955236],\\n\",\n       \"         [0.19110728, 0.50206147, 0.05049411]],\\n\",\n       \"\\n\",\n       \"        [[0.01880872, 0.25428751, 0.32772514],\\n\",\n       \"         [0.1303663 , 0.75804367, 0.53268895],\\n\",\n       \"         [0.37711957, 0.72274233, 0.95032399],\\n\",\n       \"         [0.07563836, 0.93359311, 0.15796125],\\n\",\n       \"         [0.62045146, 0.64580923, 0.1557714 ],\\n\",\n       \"         [0.78905608, 0.85432612, 0.87425904],\\n\",\n       \"         [0.80316626, 0.51924423, 0.45801054],\\n\",\n       \"         [0.64371903, 0.55673077, 0.85455273],\\n\",\n       \"         [0.42522451, 0.75796177, 0.73794332],\\n\",\n       \"         [0.9042132 , 0.94432526, 0.84180072]],\\n\",\n       \"\\n\",\n       \"        [[0.77346326, 0.84811549, 0.97897457],\\n\",\n       \"         [0.9229139 , 0.8745595 , 0.81151275],\\n\",\n       \"         [0.31466683, 0.22968788, 0.32937946],\\n\",\n       \"         [0.32265255, 0.60866667, 0.74966551],\\n\",\n       \"         [0.89690681, 0.22652098, 0.38790477],\\n\",\n       \"         [0.73330962, 0.60714074, 0.53581188],\\n\",\n       \"         [0.492162  , 0.4240943 , 0.7783657 ],\\n\",\n       \"         [0.0186855 , 0.69752848, 0.52908628],\\n\",\n       \"         [0.84273096, 0.30658396, 0.70465779],\\n\",\n       \"         [0.8684895 , 0.06929279, 0.73560357]],\\n\",\n       \"\\n\",\n       \"        [[0.41183525, 0.06309388, 0.03012547],\\n\",\n       \"         [0.04789855, 0.39528684, 0.14238964],\\n\",\n       \"         [0.37892587, 0.73618744, 0.70410196],\\n\",\n       \"         [0.54405706, 0.07672244, 0.10798353],\\n\",\n       \"         [0.10530593, 0.46345768, 0.95231357],\\n\",\n       \"         [0.14640745, 0.47792646, 0.6955056 ],\\n\",\n       \"         [0.39633502, 0.68247493, 0.7154005 ],\\n\",\n       \"         [0.89354067, 0.92889669, 0.18524983],\\n\",\n       \"         [0.85684736, 0.40546574, 0.08902131],\\n\",\n       \"         [0.45694739, 0.57720739, 0.10578621]],\\n\",\n       \"\\n\",\n       \"        [[0.36785594, 0.17667226, 0.46407189],\\n\",\n       \"         [0.11640223, 0.37587536, 0.93314522],\\n\",\n       \"         [0.03840141, 0.7311801 , 0.23603065],\\n\",\n       \"         [0.54117032, 0.85714659, 0.0495661 ],\\n\",\n       \"         [0.08494766, 0.87966438, 0.37650164],\\n\",\n       \"         [0.95011446, 0.23333771, 0.26889821],\\n\",\n       \"         [0.86136317, 0.16072138, 0.03323276],\\n\",\n       \"         [0.31658215, 0.25675017, 0.59240392],\\n\",\n       \"         [0.07867128, 0.73161337, 0.96039619],\\n\",\n       \"         [0.95476936, 0.68330006, 0.99581875]],\\n\",\n       \"\\n\",\n       \"        [[0.73541155, 0.30482595, 0.11167008],\\n\",\n       \"         [0.20315806, 0.45939058, 0.90883005],\\n\",\n       \"         [0.62037448, 0.07781508, 0.85993374],\\n\",\n       \"         [0.1662502 , 0.96140805, 0.4741485 ],\\n\",\n       \"         [0.10682937, 0.36184028, 0.52263044],\\n\",\n       \"         [0.55662028, 0.01836474, 0.90787543],\\n\",\n       \"         [0.79930707, 0.76048754, 0.12106902],\\n\",\n       \"         [0.45491329, 0.94061578, 0.48757815],\\n\",\n       \"         [0.12918205, 0.18806973, 0.58812925],\\n\",\n       \"         [0.80431   , 0.97299797, 0.05632223]],\\n\",\n       \"\\n\",\n       \"        [[0.33911369, 0.9949053 , 0.61461519],\\n\",\n       \"         [0.78384667, 0.73316864, 0.85913351],\\n\",\n       \"         [0.38492166, 0.56317432, 0.59637715],\\n\",\n       \"         [0.3607973 , 0.05332751, 0.59008779],\\n\",\n       \"         [0.80225702, 0.88927018, 0.87653115],\\n\",\n       \"         [0.62173867, 0.62184283, 0.90795477],\\n\",\n       \"         [0.15894814, 0.54661812, 0.83119993],\\n\",\n       \"         [0.44861376, 0.28122679, 0.37193476],\\n\",\n       \"         [0.40747786, 0.24497888, 0.55174409],\\n\",\n       \"         [0.3188501 , 0.47713174, 0.23614857]]]])\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 28ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[-0.811051  , -1.4721096 ],\\n\",\n       \"         [-0.52853954, -0.47991082],\\n\",\n       \"         [-0.8595364 , -0.6705183 ],\\n\",\n       \"         [-0.07767564, -0.1320289 ]],\\n\",\n       \"\\n\",\n       \"        [[-0.9737919 , -0.5298958 ],\\n\",\n       \"         [-1.0687585 , -0.33069813],\\n\",\n       \"         [-0.96858287, -0.61539143],\\n\",\n       \"         [-0.34952405, -0.3947128 ]],\\n\",\n       \"\\n\",\n       \"        [[-1.1950083 , -0.39145365],\\n\",\n       \"         [-1.0355395 ,  0.37544912],\\n\",\n       \"         [-0.46857417, -0.46149284],\\n\",\n       \"         [-0.1579878 , -0.14529735]],\\n\",\n       \"\\n\",\n       \"        [[-0.7178327 , -0.6407934 ],\\n\",\n       \"         [-0.81823504, -0.48652953],\\n\",\n       \"         [-0.48897535, -0.5935499 ],\\n\",\n       \"         [-0.0888171 , -0.18892495]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 17,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\\n\",\n    \"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(4)] for i in range(4)]\\n\",\n    \"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"([[['-811051029307312151898080091259013408',\\n\",\n       \"    '-1472109697883872855085104222700990006'],\\n\",\n       \"   ['-528539552873451841296887387802887946',\\n\",\n       \"    '-479910753097361964472240108640655029'],\\n\",\n       \"   ['-859536355090285293603582494722226955',\\n\",\n       \"    '-670518221637687591501448018045711492'],\\n\",\n       \"   ['-77675673238639598916850751879067826',\\n\",\n       \"    '-132028915984577730731287477184728367']],\\n\",\n       \"  [['-973791923027617402137438972479106354',\\n\",\n       \"    '-529895757470201620182206632643141082'],\\n\",\n       \"   ['-1068758558577939368141318995900977305',\\n\",\n       \"    '-330698196577790148366400564712521445'],\\n\",\n       \"   ['-968582927650604267027127767242160672',\\n\",\n       \"    '-615391447297339813950840270560399175'],\\n\",\n       \"   ['-349524047948521414307381813385449474',\\n\",\n       \"    '-394712802987869376369174007174918150']],\\n\",\n       \"  [['-1195008336948108945640918772722080227',\\n\",\n       \"    '-391453675833271485890705066425298906'],\\n\",\n       \"   ['-1035539474474336745928350434338370235',\\n\",\n       \"    '375449144451453718974060701074107917'],\\n\",\n       \"   ['-468574096206261610672918401549766744',\\n\",\n       \"    '-461492881731804944422419395904964084'],\\n\",\n       \"   ['-157987822858060281896825874562638157',\\n\",\n       \"    '-145297327207434479738146166840718303']],\\n\",\n       \"  [['-717832718354692660291274590189907309',\\n\",\n       \"    '-640793387586819749749055661801718428'],\\n\",\n       \"   ['-818234976163909363095633653303124629',\\n\",\n       \"    '-486529556567947364827511906932334658'],\\n\",\n       \"   ['-488975320390965478682141686514332960',\\n\",\n       \"    '-593549900211690891912136829366038418'],\\n\",\n       \"   ['-88817120440234533520269026413841619',\\n\",\n       \"    '-188924963686509380494214483287084738']]],\\n\",\n       \" [[['57546413369690632436021828010377216',\\n\",\n       \"    '844338365610010970536479881582084096'],\\n\",\n       \"   ['713605335486457688719381102919155712',\\n\",\n       \"    '375215677051519710413966252668092416'],\\n\",\n       \"   ['755914587195177990836477246220271616',\\n\",\n       \"    '818027579922420637827386176052396032'],\\n\",\n       \"   ['66541310804045710582849369230278656',\\n\",\n       \"    '347409709477862532129959056406216704']],\\n\",\n       \"  [['289886146631823524117043901901045760',\\n\",\n       \"    '747073207457187946361744580709187584'],\\n\",\n       \"   ['596964332285599153985153944246026240',\\n\",\n       \"    '55475850457661407668048488535425024'],\\n\",\n       \"   ['170834380408647470600498462609899520',\\n\",\n       \"    '509441462772270674298218142377181184'],\\n\",\n       \"   ['34071275330636135911467390225874944',\\n\",\n       \"    '138225886497714127955769149616029696']],\\n\",\n       \"  [['799025578005122329965199425850572800',\\n\",\n       \"    '638105259408657768502010079451545600'],\\n\",\n       \"   ['646664651333832093639422680485593088',\\n\",\n       \"    '675100193761157594649844145046159360'],\\n\",\n       \"   ['445458083786331341876221205003894784',\\n\",\n       \"    '502163711096538860296377604167958528'],\\n\",\n       \"   ['47026304856349756806446693973229568',\\n\",\n       \"    '831593504386261794099030491582693376']],\\n\",\n       \"  [['939137107020160348118700928203227136',\\n\",\n       \"    '113237806886600667494639994056736768'],\\n\",\n       \"   ['659213932223174550761216604282814464',\\n\",\n       \"    '197300411875572149344585017353830400'],\\n\",\n       \"   ['421437083594697043343248459305058304',\\n\",\n       \"    '120269150227163283149044634810843136'],\\n\",\n       \"   ['198117022230724190125402300398698496',\\n\",\n       \"    '310521369112965179461249563143176192']]])\"\n      ]\n     },\n     \"execution_count\": 19,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"out, remainder = Conv2DsameInt(10, 10, 3, 2, 4, 3, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"conv2Dsame_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/dense.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Dense\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(20,))\\n\",\n    \"out = Dense(10)(inputs)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 20)]              0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 10)                210       \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 210\\n\",\n      \"Trainable params: 210\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.91709806, 0.82830839, 0.93914066, 0.57037095, 0.04271652,\\n\",\n       \"        0.35534695, 0.29179199, 0.80227101, 0.65690956, 0.59359125,\\n\",\n       \"        0.57083799, 0.64906287, 0.08615951, 0.20494363, 0.98687436,\\n\",\n       \"        0.70022373, 0.8282763 , 0.38845018, 0.1025627 , 0.46584396]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,20)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 31ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:08:46.369862: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[-0.9478299 , -0.2901961 ,  1.2173429 ,  0.9856129 ,  0.44817972,\\n\",\n       \"         0.8500049 ,  1.2243729 ,  1.1230452 , -0.8100219 ,  0.65824366]],\\n\",\n       \"      dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [int(x*1e36) for x in X[0]]\\n\",\n    \"weights = [[None for _ in range(10)] for _ in range(20)]\\n\",\n    \"for i in range(20):\\n\",\n    \"    for j in range(10):\\n\",\n    \"        weights[i][j] = int(model.get_weights()[0][i][j]*1e36)\\n\",\n    \"bias = [int(b*1e72) for b in model.get_weights()[1]]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\\n\",\n    \"    Input = [str(input[i] % p) for i in range(nInputs)]\\n\",\n    \"    Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nOutputs)]\\n\",\n    \"    out = [0 for _ in range(nOutputs)]\\n\",\n    \"    remainder = [None for _ in range(nOutputs)]\\n\",\n    \"    for j in range(nOutputs):\\n\",\n    \"        for i in range(nInputs):\\n\",\n    \"            out[j] += input[i] * weights[i][j]\\n\",\n    \"        out[j] += bias[j]\\n\",\n    \"        remainder[j] = str(out[j] % n)\\n\",\n    \"        out[j] = str(out[j] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\\n\",\n    \"        \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(['21888242871839275222246405745257275088547416570344934017690618098050994599407',\\n\",\n       \"  '21888242871839275222246405745257275088548074204322728883645171911568575253269',\\n\",\n       \"  '1217342773824182708964164664298235747',\\n\",\n       \"  '985612918881516198369842470059289901',\\n\",\n       \"  '448179765935532159653151439285979820',\\n\",\n       \"  '850005025728080684762697042708611430',\\n\",\n       \"  '1224373017260726380443809993782617513',\\n\",\n       \"  '1123045202502242457956309189904120564',\\n\",\n       \"  '21888242871839275222246405745257275088547554378545433689485043918282349046950',\\n\",\n       \"  '658243650814707862463466520227993190'],\\n\",\n       \" ['51492294878586576180273547728388096',\\n\",\n       \"  '777789140836427041572477556551057408',\\n\",\n       \"  '890475291130181473765283908913463296',\\n\",\n       \"  '963682024802736049277914862344732672',\\n\",\n       \"  '180838407593997560156976766263492608',\\n\",\n       \"  '458215330546393498330258578539020288',\\n\",\n       \"  '738904904497555276279419263936102400',\\n\",\n       \"  '770453107465054933435045502301241344',\\n\",\n       \"  '616225701137188004915996184419500032',\\n\",\n       \"  '106851476518473341575934978717384704'])\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, weights, bias, out, remainder = DenseInt(20, 10, 10**36, X_in, weights, bias)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"weights\\\": weights,\\n\",\n    \"    \\\"bias\\\": bias,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"dense_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/depthwiseConv2D.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"4d60427f-21e9-41b1-a5eb-0d36d2c395ea\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import torch\\n\",\n    \"import torch.nn as nn\\n\",\n    \"import torch.nn.functional as F\\n\",\n    \"import numpy as np\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"b1962e3f-18b6-43b2-88f8-e81a49f4edbc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\\n\",\n    \"CIRCOM_PRIME = 21888242871839275222246405745257275088548364400416034343698204186575808495617\\n\",\n    \"MAX_POSITIVE = CIRCOM_PRIME // 2\\n\",\n    \"MAX_NEGATIVE = MAX_POSITIVE + 1 # The most positive number\\n\",\n    \"\\n\",\n    \"EXPONENT = 15\\n\",\n    \"\\n\",\n    \"def from_circom(x):\\n\",\n    \"    if type(x) != int:\\n\",\n    \"        x = int(x)\\n\",\n    \"    if x > MAX_POSITIVE: \\n\",\n    \"        return x - CIRCOM_PRIME\\n\",\n    \"    return x\\n\",\n    \"    \\n\",\n    \"def to_circom(x):\\n\",\n    \"    if type(x) != int:\\n\",\n    \"        x = int(x)\\n\",\n    \"    if x < 0:\\n\",\n    \"        return x + CIRCOM_PRIME \\n\",\n    \"    return x\\n\",\n    \"\\n\",\n    \"class SeparableConv2D(nn.Module):\\n\",\n    \"    '''Separable convolution'''\\n\",\n    \"    def __init__(self, in_channels, out_channels, stride=1):\\n\",\n    \"        super(SeparableConv2D, self).__init__()\\n\",\n    \"        self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\\n\",\n    \"        self.pw_conv =  nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\\n\",\n    \"\\n\",\n    \"    def forward(self, x):\\n\",\n    \"        x = self.dw_conv(x)\\n\",\n    \"        x = self.pw_conv(x)\\n\",\n    \"        return x\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"a7ad1f77-24e0-470e-b4de-63234ac9542b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"input = torch.randn((1, 3, 5, 5))\\n\",\n    \"model = SeparableConv2D(3, 6)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"88e91743-d234-4e55-bd65-f4a5b0f5b350\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    assert(nFilters % nChannels == 0)\\n\",\n    \"    outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"    outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    \\n\",\n    \"    # out = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    remainder = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    # remainder = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"    \\n\",\n    \"    for row in range(outRows):\\n\",\n    \"        for col in range(outCols):\\n\",\n    \"            for channel in range(nChannels):\\n\",\n    \"                for x in range(kernelSize):\\n\",\n    \"                    for y in range(kernelSize):\\n\",\n    \"                        out[row][col][channel] += int(input[row*strides+x, col*strides+y, channel]) * int(weights[x, y, channel])\\n\",\n    \"                \\n\",\n    \"                out[row][col][channel] += int(bias[channel])\\n\",\n    \"                remainder[row][col][channel] = str(int(out[row][col][channel] % n))\\n\",\n    \"                out[row][col][channel] = int(out[row][col][channel] // n)\\n\",\n    \"                            \\n\",\n    \"    return out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"id\": \"e666c225-f618-43d4-b003-56f9b4699d2e\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"weights = model.dw_conv.weight.squeeze().detach().numpy()\\n\",\n    \"bias = torch.zeros(weights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"expected = model.dw_conv(input).detach().numpy()\\n\",\n    \"\\n\",\n    \"padded = F.pad(input, (1,1,1,1), \\\"constant\\\", 0)\\n\",\n    \"padded = padded.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"weights = weights.transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"quantized_image = padded * 10**EXPONENT\\n\",\n    \"quantized_weights = weights * 10**EXPONENT\\n\",\n    \"\\n\",\n    \"actual, rem = DepthwiseConv(7, 7, 3, 3, 3, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\\n\",\n    \"\\n\",\n    \"expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"expected = expected * 10**EXPONENT\\n\",\n    \"\\n\",\n    \"assert(np.allclose(expected, actual, atol=0.00001))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"904ce6c4-f1d4-43f3-80f0-5e3df61d5546\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"weights = model.dw_conv.weight.squeeze().detach().numpy()\\n\",\n    \"bias = torch.zeros(weights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"padded = F.pad(input, (1,1,1,1), \\\"constant\\\", 0)\\n\",\n    \"padded = padded.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"weights = weights.transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"quantized_image = padded * 10**EXPONENT\\n\",\n    \"quantized_weights = weights * 10**EXPONENT\\n\",\n    \"\\n\",\n    \"out, remainder = DepthwiseConv(7, 7, 3, 3, 3, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\\n\",\n    \"\\n\",\n    \"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_weights = quantized_weights.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_bias = bias.round().astype(int).astype(str).tolist()\\n\",\n    \"\\n\",\n    \"input_json_path = \\\"depthwiseConv2D_input.json\\\"\\n\",\n    \"with open(input_json_path, \\\"w\\\") as input_file:\\n\",\n    \"    json.dump({\\\"in\\\": circuit_in,\\n\",\n    \"               \\\"weights\\\": circuit_weights,\\n\",\n    \"               \\\"remainder\\\": remainder,\\n\",\n    \"               \\\"out\\\": out,\\n\",\n    \"               \\\"bias\\\": circuit_bias,\\n\",\n    \"              },\\n\",\n    \"              input_file)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"523588d7-4c81-4bb9-9dbd-e626b6d2a8a9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/flatten.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Flatten\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = Flatten()(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" flatten (Flatten)           (None, 75)                0         \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[]\"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.9191584 , 0.41015604, 0.0493302 ],\\n\",\n       \"         [0.20412956, 0.14984944, 0.71595293],\\n\",\n       \"         [0.57980447, 0.28233206, 0.30881941],\\n\",\n       \"         [0.98703541, 0.91977126, 0.89591016],\\n\",\n       \"         [0.29365768, 0.89541076, 0.97098122]],\\n\",\n       \"\\n\",\n       \"        [[0.28270309, 0.85760979, 0.12266525],\\n\",\n       \"         [0.2386079 , 0.93741419, 0.83312648],\\n\",\n       \"         [0.02935679, 0.68497567, 0.37248647],\\n\",\n       \"         [0.76807667, 0.72347087, 0.84375984],\\n\",\n       \"         [0.89233681, 0.87703334, 0.53846864]],\\n\",\n       \"\\n\",\n       \"        [[0.14028452, 0.61585222, 0.34271206],\\n\",\n       \"         [0.45404173, 0.26365195, 0.05140719],\\n\",\n       \"         [0.36253999, 0.51529482, 0.15006   ],\\n\",\n       \"         [0.82061228, 0.08937872, 0.65234282],\\n\",\n       \"         [0.31024437, 0.09785702, 0.40629764]],\\n\",\n       \"\\n\",\n       \"        [[0.75192339, 0.55825739, 0.86978978],\\n\",\n       \"         [0.76105885, 0.54160411, 0.72517187],\\n\",\n       \"         [0.28701856, 0.31868524, 0.46890464],\\n\",\n       \"         [0.0902    , 0.3022873 , 0.48529066],\\n\",\n       \"         [0.24453082, 0.93271481, 0.08555694]],\\n\",\n       \"\\n\",\n       \"        [[0.52171579, 0.22363436, 0.85212827],\\n\",\n       \"         [0.9823001 , 0.64424366, 0.96495129],\\n\",\n       \"         [0.61750385, 0.53921774, 0.75703119],\\n\",\n       \"         [0.57267588, 0.18643057, 0.26532282],\\n\",\n       \"         [0.22546175, 0.0340469 , 0.19259163]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 95ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 17:09:53.715790: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.9191584 , 0.41015604, 0.0493302 , 0.20412956, 0.14984943,\\n\",\n       \"        0.71595293, 0.5798045 , 0.28233206, 0.3088194 , 0.9870354 ,\\n\",\n       \"        0.91977125, 0.89591014, 0.2936577 , 0.8954108 , 0.97098124,\\n\",\n       \"        0.2827031 , 0.8576098 , 0.12266525, 0.2386079 , 0.93741417,\\n\",\n       \"        0.8331265 , 0.02935679, 0.6849757 , 0.37248647, 0.76807666,\\n\",\n       \"        0.72347087, 0.84375983, 0.8923368 , 0.87703335, 0.53846866,\\n\",\n       \"        0.14028452, 0.61585224, 0.34271204, 0.45404172, 0.26365197,\\n\",\n       \"        0.05140718, 0.36253998, 0.5152948 , 0.15006   , 0.82061225,\\n\",\n       \"        0.08937872, 0.6523428 , 0.31024438, 0.09785703, 0.40629762,\\n\",\n       \"        0.7519234 , 0.5582574 , 0.8697898 , 0.76105887, 0.5416041 ,\\n\",\n       \"        0.72517186, 0.28701857, 0.31868523, 0.46890464, 0.0902    ,\\n\",\n       \"        0.3022873 , 0.48529068, 0.24453081, 0.9327148 , 0.08555695,\\n\",\n       \"        0.5217158 , 0.22363436, 0.85212827, 0.9823001 , 0.64424366,\\n\",\n       \"        0.9649513 , 0.6175039 , 0.5392177 , 0.7570312 , 0.5726759 ,\\n\",\n       \"        0.18643057, 0.26532283, 0.22546175, 0.0340469 , 0.19259164]],\\n\",\n       \"      dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": (X*1e36).round().astype(int).flatten().tolist(),\\n\",\n    \"    \\\"out\\\": (X*1e36).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"flatten2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/globalAveragePooling2D.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, GlobalAveragePooling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"out = GlobalAveragePooling2D()(inputs)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" global_average_pooling2d (G  (None, 3)                0         \\n\",\n      \" lobalAveragePooling2D)                                          \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.20867486, 0.38680755, 0.84218508],\\n\",\n       \"         [0.23655331, 0.33771458, 0.73516473],\\n\",\n       \"         [0.49345271, 0.95094652, 0.25402692],\\n\",\n       \"         [0.22771833, 0.97688694, 0.52917136],\\n\",\n       \"         [0.5871173 , 0.50441061, 0.97392083]],\\n\",\n       \"\\n\",\n       \"        [[0.93934312, 0.52666508, 0.31051829],\\n\",\n       \"         [0.2163095 , 0.79177499, 0.3108483 ],\\n\",\n       \"         [0.53926143, 0.15753146, 0.99773704],\\n\",\n       \"         [0.12234007, 0.20568095, 0.11838809],\\n\",\n       \"         [0.9248088 , 0.52638782, 0.81404877]],\\n\",\n       \"\\n\",\n       \"        [[0.01465677, 0.32765939, 0.74282836],\\n\",\n       \"         [0.6800781 , 0.40869424, 0.62145002],\\n\",\n       \"         [0.67374829, 0.81617885, 0.39987386],\\n\",\n       \"         [0.82099264, 0.35918735, 0.47107381],\\n\",\n       \"         [0.83104015, 0.83004572, 0.28737773]],\\n\",\n       \"\\n\",\n       \"        [[0.74027671, 0.85697829, 0.49504698],\\n\",\n       \"         [0.94596904, 0.25070827, 0.22236492],\\n\",\n       \"         [0.00357426, 0.35882451, 0.32972314],\\n\",\n       \"         [0.57254891, 0.86380467, 0.30862848],\\n\",\n       \"         [0.93720522, 0.4496124 , 0.74115158]],\\n\",\n       \"\\n\",\n       \"        [[0.12640468, 0.76330103, 0.35499368],\\n\",\n       \"         [0.37773597, 0.016954  , 0.43058637],\\n\",\n       \"         [0.94290805, 0.06019639, 0.95692684],\\n\",\n       \"         [0.09562172, 0.61791084, 0.47187214],\\n\",\n       \"         [0.67092949, 0.27421069, 0.85342606]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 36ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:10:13.674664: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.5171708 , 0.5047629 , 0.54293334]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k] * 1e36) for k in range(3)] for j in range(5)] for i in range(5)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def GlobalAveragePooling2DInt(nRows, nCols, nChannels, input):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    out = [0 for _ in range(nChannels)]\\n\",\n    \"    remainder = [None for _ in range(nChannels)]\\n\",\n    \"    for k in range(nChannels):\\n\",\n    \"        for i in range(nRows):\\n\",\n    \"            for j in range(nCols):\\n\",\n    \"                out[k] += input[i][j][k]\\n\",\n    \"        remainder[k] = str(out[k] % (nRows * nCols))\\n\",\n    \"        out[k] = str(out[k] // (nRows * nCols) % p)\\n\",\n    \"    return Input, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(['517170777415975145178424005003973754',\\n\",\n       \"  '504762926219743484887371893374996971',\\n\",\n       \"  '542933334573104965421804807186892718'],\\n\",\n       \" ['22', '13', '2'])\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out, remainder = GlobalAveragePooling2DInt(5, 5, 3, X_in)\\n\",\n    \"out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out,\\n\",\n    \"    \\\"remainder\\\": remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"globalAveragePooling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/globalMaxPooling2D.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, GlobalMaxPooling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = GlobalMaxPooling2D()(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" global_max_pooling2d (Globa  (None, 3)                0         \\n\",\n      \" lMaxPooling2D)                                                  \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.91518641, 0.66718006, 0.92376279],\\n\",\n       \"         [0.97385149, 0.35848662, 0.25065166],\\n\",\n       \"         [0.02434808, 0.66270045, 0.51526436],\\n\",\n       \"         [0.97110905, 0.49335089, 0.27623285],\\n\",\n       \"         [0.88055993, 0.91070856, 0.89195416]],\\n\",\n       \"\\n\",\n       \"        [[0.7950447 , 0.42411655, 0.66516519],\\n\",\n       \"         [0.18674268, 0.3046312 , 0.77807526],\\n\",\n       \"         [0.13333453, 0.68076544, 0.64069414],\\n\",\n       \"         [0.63039814, 0.71725918, 0.74384312],\\n\",\n       \"         [0.48789065, 0.68079997, 0.25869622]],\\n\",\n       \"\\n\",\n       \"        [[0.55852658, 0.78138444, 0.0772444 ],\\n\",\n       \"         [0.71960766, 0.01860611, 0.63859032],\\n\",\n       \"         [0.04100894, 0.007163  , 0.28648401],\\n\",\n       \"         [0.70371242, 0.8565901 , 0.73254654],\\n\",\n       \"         [0.35201173, 0.3338802 , 0.83269692]],\\n\",\n       \"\\n\",\n       \"        [[0.31146493, 0.11242401, 0.46909255],\\n\",\n       \"         [0.785379  , 0.69905536, 0.99196427],\\n\",\n       \"         [0.29254832, 0.04347593, 0.40404928],\\n\",\n       \"         [0.64393514, 0.6579046 , 0.44890337],\\n\",\n       \"         [0.25879095, 0.64296721, 0.65792656]],\\n\",\n       \"\\n\",\n       \"        [[0.7972691 , 0.77522241, 0.02028976],\\n\",\n       \"         [0.71408815, 0.2214879 , 0.07804482],\\n\",\n       \"         [0.65261239, 0.62851164, 0.12214903],\\n\",\n       \"         [0.31611407, 0.18022595, 0.97735959],\\n\",\n       \"         [0.57391523, 0.8818251 , 0.06020382]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 31ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 20:16:54.369715: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.9738515 , 0.91070855, 0.9919643 ]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def GlobalMaxPooling2DInt(nRows, nCols, nChannels, input):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    out = [max(input[i][j][k] for i in range(nRows) for j in range(nCols)) for k in range(nChannels)]\\n\",\n    \"    return Input, out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[973851490313537338484516198430015488,\\n\",\n       \" 910708561343324144695836121136889856,\\n\",\n       \" 991964273065568131927416012428804096]\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out = GlobalMaxPooling2DInt(5,5,3,X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"globalMaxPooling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/lr_zanh.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# example from https://towardsdatascience.com/replicate-a-logistic-regression-model-as-an-artificial-neural-network-in-keras-cd6f49cf4b2c\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import pandas as pd\\n\",\n    \"from sklearn.datasets import load_breast_cancer\\n\",\n    \"from sklearn.model_selection import train_test_split\\n\",\n    \"from sklearn.linear_model import LogisticRegression\\n\",\n    \"from tensorflow.keras.models import Sequential\\n\",\n    \"from tensorflow.keras.layers import InputLayer\\n\",\n    \"from tensorflow.keras.layers import Dense\\n\",\n    \"import tensorflow as tf\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>mean radius</th>\\n\",\n       \"      <th>mean texture</th>\\n\",\n       \"      <th>mean perimeter</th>\\n\",\n       \"      <th>mean area</th>\\n\",\n       \"      <th>mean smoothness</th>\\n\",\n       \"      <th>mean compactness</th>\\n\",\n       \"      <th>mean concavity</th>\\n\",\n       \"      <th>mean concave points</th>\\n\",\n       \"      <th>mean symmetry</th>\\n\",\n       \"      <th>mean fractal dimension</th>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <th>worst radius</th>\\n\",\n       \"      <th>worst texture</th>\\n\",\n       \"      <th>worst perimeter</th>\\n\",\n       \"      <th>worst area</th>\\n\",\n       \"      <th>worst smoothness</th>\\n\",\n       \"      <th>worst compactness</th>\\n\",\n       \"      <th>worst concavity</th>\\n\",\n       \"      <th>worst concave points</th>\\n\",\n       \"      <th>worst symmetry</th>\\n\",\n       \"      <th>worst fractal dimension</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>17.99</td>\\n\",\n       \"      <td>10.38</td>\\n\",\n       \"      <td>122.80</td>\\n\",\n       \"      <td>1001.0</td>\\n\",\n       \"      <td>0.11840</td>\\n\",\n       \"      <td>0.27760</td>\\n\",\n       \"      <td>0.3001</td>\\n\",\n       \"      <td>0.14710</td>\\n\",\n       \"      <td>0.2419</td>\\n\",\n       \"      <td>0.07871</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>25.38</td>\\n\",\n       \"      <td>17.33</td>\\n\",\n       \"      <td>184.60</td>\\n\",\n       \"      <td>2019.0</td>\\n\",\n       \"      <td>0.1622</td>\\n\",\n       \"      <td>0.6656</td>\\n\",\n       \"      <td>0.7119</td>\\n\",\n       \"      <td>0.2654</td>\\n\",\n       \"      <td>0.4601</td>\\n\",\n       \"      <td>0.11890</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>20.57</td>\\n\",\n       \"      <td>17.77</td>\\n\",\n       \"      <td>132.90</td>\\n\",\n       \"      <td>1326.0</td>\\n\",\n       \"      <td>0.08474</td>\\n\",\n       \"      <td>0.07864</td>\\n\",\n       \"      <td>0.0869</td>\\n\",\n       \"      <td>0.07017</td>\\n\",\n       \"      <td>0.1812</td>\\n\",\n       \"      <td>0.05667</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>24.99</td>\\n\",\n       \"      <td>23.41</td>\\n\",\n       \"      <td>158.80</td>\\n\",\n       \"      <td>1956.0</td>\\n\",\n       \"      <td>0.1238</td>\\n\",\n       \"      <td>0.1866</td>\\n\",\n       \"      <td>0.2416</td>\\n\",\n       \"      <td>0.1860</td>\\n\",\n       \"      <td>0.2750</td>\\n\",\n       \"      <td>0.08902</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>19.69</td>\\n\",\n       \"      <td>21.25</td>\\n\",\n       \"      <td>130.00</td>\\n\",\n       \"      <td>1203.0</td>\\n\",\n       \"      <td>0.10960</td>\\n\",\n       \"      <td>0.15990</td>\\n\",\n       \"      <td>0.1974</td>\\n\",\n       \"      <td>0.12790</td>\\n\",\n       \"      <td>0.2069</td>\\n\",\n       \"      <td>0.05999</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>23.57</td>\\n\",\n       \"      <td>25.53</td>\\n\",\n       \"      <td>152.50</td>\\n\",\n       \"      <td>1709.0</td>\\n\",\n       \"      <td>0.1444</td>\\n\",\n       \"      <td>0.4245</td>\\n\",\n       \"      <td>0.4504</td>\\n\",\n       \"      <td>0.2430</td>\\n\",\n       \"      <td>0.3613</td>\\n\",\n       \"      <td>0.08758</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>11.42</td>\\n\",\n       \"      <td>20.38</td>\\n\",\n       \"      <td>77.58</td>\\n\",\n       \"      <td>386.1</td>\\n\",\n       \"      <td>0.14250</td>\\n\",\n       \"      <td>0.28390</td>\\n\",\n       \"      <td>0.2414</td>\\n\",\n       \"      <td>0.10520</td>\\n\",\n       \"      <td>0.2597</td>\\n\",\n       \"      <td>0.09744</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>14.91</td>\\n\",\n       \"      <td>26.50</td>\\n\",\n       \"      <td>98.87</td>\\n\",\n       \"      <td>567.7</td>\\n\",\n       \"      <td>0.2098</td>\\n\",\n       \"      <td>0.8663</td>\\n\",\n       \"      <td>0.6869</td>\\n\",\n       \"      <td>0.2575</td>\\n\",\n       \"      <td>0.6638</td>\\n\",\n       \"      <td>0.17300</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>20.29</td>\\n\",\n       \"      <td>14.34</td>\\n\",\n       \"      <td>135.10</td>\\n\",\n       \"      <td>1297.0</td>\\n\",\n       \"      <td>0.10030</td>\\n\",\n       \"      <td>0.13280</td>\\n\",\n       \"      <td>0.1980</td>\\n\",\n       \"      <td>0.10430</td>\\n\",\n       \"      <td>0.1809</td>\\n\",\n       \"      <td>0.05883</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>22.54</td>\\n\",\n       \"      <td>16.67</td>\\n\",\n       \"      <td>152.20</td>\\n\",\n       \"      <td>1575.0</td>\\n\",\n       \"      <td>0.1374</td>\\n\",\n       \"      <td>0.2050</td>\\n\",\n       \"      <td>0.4000</td>\\n\",\n       \"      <td>0.1625</td>\\n\",\n       \"      <td>0.2364</td>\\n\",\n       \"      <td>0.07678</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"<p>5 rows \u00d7 30 columns</p>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"   mean radius  mean texture  mean perimeter  mean area  mean smoothness  \\\\\\n\",\n       \"0        17.99         10.38          122.80     1001.0          0.11840   \\n\",\n       \"1        20.57         17.77          132.90     1326.0          0.08474   \\n\",\n       \"2        19.69         21.25          130.00     1203.0          0.10960   \\n\",\n       \"3        11.42         20.38           77.58      386.1          0.14250   \\n\",\n       \"4        20.29         14.34          135.10     1297.0          0.10030   \\n\",\n       \"\\n\",\n       \"   mean compactness  mean concavity  mean concave points  mean symmetry  \\\\\\n\",\n       \"0           0.27760          0.3001              0.14710         0.2419   \\n\",\n       \"1           0.07864          0.0869              0.07017         0.1812   \\n\",\n       \"2           0.15990          0.1974              0.12790         0.2069   \\n\",\n       \"3           0.28390          0.2414              0.10520         0.2597   \\n\",\n       \"4           0.13280          0.1980              0.10430         0.1809   \\n\",\n       \"\\n\",\n       \"   mean fractal dimension  ...  worst radius  worst texture  worst perimeter  \\\\\\n\",\n       \"0                 0.07871  ...         25.38          17.33           184.60   \\n\",\n       \"1                 0.05667  ...         24.99          23.41           158.80   \\n\",\n       \"2                 0.05999  ...         23.57          25.53           152.50   \\n\",\n       \"3                 0.09744  ...         14.91          26.50            98.87   \\n\",\n       \"4                 0.05883  ...         22.54          16.67           152.20   \\n\",\n       \"\\n\",\n       \"   worst area  worst smoothness  worst compactness  worst concavity  \\\\\\n\",\n       \"0      2019.0            0.1622             0.6656           0.7119   \\n\",\n       \"1      1956.0            0.1238             0.1866           0.2416   \\n\",\n       \"2      1709.0            0.1444             0.4245           0.4504   \\n\",\n       \"3       567.7            0.2098             0.8663           0.6869   \\n\",\n       \"4      1575.0            0.1374             0.2050           0.4000   \\n\",\n       \"\\n\",\n       \"   worst concave points  worst symmetry  worst fractal dimension  \\n\",\n       \"0                0.2654          0.4601                  0.11890  \\n\",\n       \"1                0.1860          0.2750                  0.08902  \\n\",\n       \"2                0.2430          0.3613                  0.08758  \\n\",\n       \"3                0.2575          0.6638                  0.17300  \\n\",\n       \"4                0.1625          0.2364                  0.07678  \\n\",\n       \"\\n\",\n       \"[5 rows x 30 columns]\"\n      ]\n     },\n     \"execution_count\": 3,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"cancer = load_breast_cancer()\\n\",\n    \"df = pd.DataFrame(cancer.data,\\n\",\n    \"                  columns=cancer.feature_names)\\n\",\n    \"df.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X = (df-df.mean())/df.std()\\n\",\n    \"# X = 2*(df-df.min())/(df.max()-df.min()) - 1\\n\",\n    \"# X = df\\n\",\n    \"y = pd.Series(cancer.target)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# change 0 to -1\\n\",\n    \"# y = y.apply(lambda x: -1 if x==0 else 1)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Make train and test sets\\n\",\n    \"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, \\n\",\n    \"                                                    shuffle=True, random_state=2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Accuracy: 0.97\\n\",\n      \"Precision: 0.99\\n\",\n      \"Recall: 0.97\\n\",\n      \"F-Score: 0.98\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# Initialize a logistic regression model\\n\",\n    \"log_reg_model = LogisticRegression(max_iter=2500,\\n\",\n    \"                                   random_state=42)\\n\",\n    \"\\n\",\n    \"# Train (fit) the model\\n\",\n    \"log_reg_model.fit(X_train, y_train)\\n\",\n    \"\\n\",\n    \"# Make predictions\\n\",\n    \"y_pred = log_reg_model.predict(X_test) # Predictions\\n\",\n    \"y_true = y_test # True values\\n\",\n    \"\\n\",\n    \"# Model evaluation\\n\",\n    \"from sklearn.metrics import accuracy_score\\n\",\n    \"from sklearn.metrics import precision_recall_fscore_support\\n\",\n    \"import numpy as np\\n\",\n    \"\\n\",\n    \"print(\\\"Accuracy:\\\", np.round(accuracy_score(y_true, y_pred), 2))\\n\",\n    \"precision, recall, fscore, _ = precision_recall_fscore_support(y_true, y_pred,\\n\",\n    \"                                                               average='binary')\\n\",\n    \"print(\\\"Precision:\\\", np.round(precision, 2))\\n\",\n    \"print(\\\"Recall:\\\", np.round(recall, 2))\\n\",\n    \"print(\\\"F-Score:\\\", np.round(fscore, 2))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model = Sequential()\\n\",\n    \"\\n\",\n    \"model.add(InputLayer(input_shape=(30, )))\\n\",\n    \"# No hidden layers\\n\",\n    \"model.add(Dense(1, activation='tanh'))\\n\",\n    \"\\n\",\n    \"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\\n\",\n    \"model.compile(optimizer=optimizer,\\n\",\n    \"                  loss='binary_crossentropy',\\n\",\n    \"                  metrics=['accuracy'])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/10\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-12 14:44:16.741589: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"12/12 [==============================] - 0s 12ms/step - loss: 2.0170 - accuracy: 0.7747 - val_loss: 0.9741 - val_accuracy: 0.8901\\n\",\n      \"Epoch 2/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 1.0516 - accuracy: 0.8929 - val_loss: 0.7816 - val_accuracy: 0.9011\\n\",\n      \"Epoch 3/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.8193 - accuracy: 0.9093 - val_loss: 0.7534 - val_accuracy: 0.9121\\n\",\n      \"Epoch 4/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.6689 - accuracy: 0.9341 - val_loss: 0.7462 - val_accuracy: 0.9121\\n\",\n      \"Epoch 5/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.6168 - accuracy: 0.9423 - val_loss: 0.7404 - val_accuracy: 0.9231\\n\",\n      \"Epoch 6/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.3145 - accuracy: 0.9560 - val_loss: 0.2055 - val_accuracy: 0.9670\\n\",\n      \"Epoch 7/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2109 - accuracy: 0.9505 - val_loss: 0.2063 - val_accuracy: 0.9670\\n\",\n      \"Epoch 8/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.1104 - accuracy: 0.9670 - val_loss: 0.0447 - val_accuracy: 0.9780\\n\",\n      \"Epoch 9/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0851 - accuracy: 0.9698 - val_loss: 0.0443 - val_accuracy: 0.9780\\n\",\n      \"Epoch 10/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.0745 - accuracy: 0.9698 - val_loss: 0.0453 - val_accuracy: 0.9670\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x15fd9eeb0>\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.fit(X_train, y_train,\\n\",\n    \"          epochs=10, batch_size=32,\\n\",\n    \"          validation_split=0.2,\\n\",\n    \"          shuffle=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"4/4 [==============================] - 0s 1ms/step - loss: 0.4077 - accuracy: 0.9474\\n\",\n      \"Test loss: 0.4076523780822754\\n\",\n      \"Test accuracy: 0.9473684430122375\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test_loss, test_acc = model.evaluate(X_test, y_test)\\n\",\n    \"print(\\\"Test loss:\\\", test_loss)\\n\",\n    \"print(\\\"Test accuracy:\\\", test_acc)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def zanh(x):\\n\",\n    \"    return 0.006769816 + 0.554670504 * x - 0.009411195 * x**2 - 0.014187547 * x**3\\n\",\n    \"\\n\",\n    \"zanh_model = Sequential()\\n\",\n    \"\\n\",\n    \"zanh_model.add(InputLayer(input_shape=(30, )))\\n\",\n    \"# No hidden layers\\n\",\n    \"zanh_model.add(Dense(1, activation=zanh))\\n\",\n    \"\\n\",\n    \"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\\n\",\n    \"zanh_model.compile(optimizer=optimizer,\\n\",\n    \"                  loss='binary_crossentropy',\\n\",\n    \"                  metrics=['accuracy'])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/10\\n\",\n      \"12/12 [==============================] - 0s 12ms/step - loss: 2.7550 - accuracy: 0.6978 - val_loss: 1.5429 - val_accuracy: 0.7912\\n\",\n      \"Epoch 2/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 1.5446 - accuracy: 0.8297 - val_loss: 0.5988 - val_accuracy: 0.9341\\n\",\n      \"Epoch 3/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.6857 - accuracy: 0.8791 - val_loss: 0.1382 - val_accuracy: 0.9670\\n\",\n      \"Epoch 4/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.2950 - accuracy: 0.9258 - val_loss: 0.1452 - val_accuracy: 0.9451\\n\",\n      \"Epoch 5/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.2493 - accuracy: 0.9478 - val_loss: 0.1188 - val_accuracy: 0.9670\\n\",\n      \"Epoch 6/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.1930 - accuracy: 0.9588 - val_loss: 0.1023 - val_accuracy: 0.9670\\n\",\n      \"Epoch 7/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.1749 - accuracy: 0.9643 - val_loss: 0.0879 - val_accuracy: 0.9670\\n\",\n      \"Epoch 8/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.1841 - accuracy: 0.9643 - val_loss: 0.0996 - val_accuracy: 0.9780\\n\",\n      \"Epoch 9/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.1695 - accuracy: 0.9670 - val_loss: 0.0836 - val_accuracy: 0.9670\\n\",\n      \"Epoch 10/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2076 - accuracy: 0.9588 - val_loss: 0.0839 - val_accuracy: 0.9780\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x15ff92ca0>\"\n      ]\n     },\n     \"execution_count\": 12,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"zanh_model.fit(X_train, y_train,\\n\",\n    \"          epochs=10, batch_size=32,\\n\",\n    \"          validation_split=0.2,\\n\",\n    \"          shuffle=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"4/4 [==============================] - 0s 1ms/step - loss: 0.2434 - accuracy: 0.9649\\n\",\n      \"Test loss: 0.24344508349895477\\n\",\n      \"Test accuracy: 0.9649122953414917\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test_loss, test_acc = zanh_model.evaluate(X_test, y_test)\\n\",\n    \"print(\\\"Test loss:\\\", test_loss)\\n\",\n    \"print(\\\"Test accuracy:\\\", test_acc)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/lr_zigmoid.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# example from https://towardsdatascience.com/replicate-a-logistic-regression-model-as-an-artificial-neural-network-in-keras-cd6f49cf4b2c\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import pandas as pd\\n\",\n    \"from sklearn.datasets import load_breast_cancer\\n\",\n    \"from sklearn.model_selection import train_test_split\\n\",\n    \"from sklearn.linear_model import LogisticRegression\\n\",\n    \"from tensorflow.keras.models import Sequential\\n\",\n    \"from tensorflow.keras.layers import InputLayer\\n\",\n    \"from tensorflow.keras.layers import Dense\\n\",\n    \"import tensorflow as tf\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>mean radius</th>\\n\",\n       \"      <th>mean texture</th>\\n\",\n       \"      <th>mean perimeter</th>\\n\",\n       \"      <th>mean area</th>\\n\",\n       \"      <th>mean smoothness</th>\\n\",\n       \"      <th>mean compactness</th>\\n\",\n       \"      <th>mean concavity</th>\\n\",\n       \"      <th>mean concave points</th>\\n\",\n       \"      <th>mean symmetry</th>\\n\",\n       \"      <th>mean fractal dimension</th>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <th>worst radius</th>\\n\",\n       \"      <th>worst texture</th>\\n\",\n       \"      <th>worst perimeter</th>\\n\",\n       \"      <th>worst area</th>\\n\",\n       \"      <th>worst smoothness</th>\\n\",\n       \"      <th>worst compactness</th>\\n\",\n       \"      <th>worst concavity</th>\\n\",\n       \"      <th>worst concave points</th>\\n\",\n       \"      <th>worst symmetry</th>\\n\",\n       \"      <th>worst fractal dimension</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>17.99</td>\\n\",\n       \"      <td>10.38</td>\\n\",\n       \"      <td>122.80</td>\\n\",\n       \"      <td>1001.0</td>\\n\",\n       \"      <td>0.11840</td>\\n\",\n       \"      <td>0.27760</td>\\n\",\n       \"      <td>0.3001</td>\\n\",\n       \"      <td>0.14710</td>\\n\",\n       \"      <td>0.2419</td>\\n\",\n       \"      <td>0.07871</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>25.38</td>\\n\",\n       \"      <td>17.33</td>\\n\",\n       \"      <td>184.60</td>\\n\",\n       \"      <td>2019.0</td>\\n\",\n       \"      <td>0.1622</td>\\n\",\n       \"      <td>0.6656</td>\\n\",\n       \"      <td>0.7119</td>\\n\",\n       \"      <td>0.2654</td>\\n\",\n       \"      <td>0.4601</td>\\n\",\n       \"      <td>0.11890</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>20.57</td>\\n\",\n       \"      <td>17.77</td>\\n\",\n       \"      <td>132.90</td>\\n\",\n       \"      <td>1326.0</td>\\n\",\n       \"      <td>0.08474</td>\\n\",\n       \"      <td>0.07864</td>\\n\",\n       \"      <td>0.0869</td>\\n\",\n       \"      <td>0.07017</td>\\n\",\n       \"      <td>0.1812</td>\\n\",\n       \"      <td>0.05667</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>24.99</td>\\n\",\n       \"      <td>23.41</td>\\n\",\n       \"      <td>158.80</td>\\n\",\n       \"      <td>1956.0</td>\\n\",\n       \"      <td>0.1238</td>\\n\",\n       \"      <td>0.1866</td>\\n\",\n       \"      <td>0.2416</td>\\n\",\n       \"      <td>0.1860</td>\\n\",\n       \"      <td>0.2750</td>\\n\",\n       \"      <td>0.08902</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>19.69</td>\\n\",\n       \"      <td>21.25</td>\\n\",\n       \"      <td>130.00</td>\\n\",\n       \"      <td>1203.0</td>\\n\",\n       \"      <td>0.10960</td>\\n\",\n       \"      <td>0.15990</td>\\n\",\n       \"      <td>0.1974</td>\\n\",\n       \"      <td>0.12790</td>\\n\",\n       \"      <td>0.2069</td>\\n\",\n       \"      <td>0.05999</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>23.57</td>\\n\",\n       \"      <td>25.53</td>\\n\",\n       \"      <td>152.50</td>\\n\",\n       \"      <td>1709.0</td>\\n\",\n       \"      <td>0.1444</td>\\n\",\n       \"      <td>0.4245</td>\\n\",\n       \"      <td>0.4504</td>\\n\",\n       \"      <td>0.2430</td>\\n\",\n       \"      <td>0.3613</td>\\n\",\n       \"      <td>0.08758</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>11.42</td>\\n\",\n       \"      <td>20.38</td>\\n\",\n       \"      <td>77.58</td>\\n\",\n       \"      <td>386.1</td>\\n\",\n       \"      <td>0.14250</td>\\n\",\n       \"      <td>0.28390</td>\\n\",\n       \"      <td>0.2414</td>\\n\",\n       \"      <td>0.10520</td>\\n\",\n       \"      <td>0.2597</td>\\n\",\n       \"      <td>0.09744</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>14.91</td>\\n\",\n       \"      <td>26.50</td>\\n\",\n       \"      <td>98.87</td>\\n\",\n       \"      <td>567.7</td>\\n\",\n       \"      <td>0.2098</td>\\n\",\n       \"      <td>0.8663</td>\\n\",\n       \"      <td>0.6869</td>\\n\",\n       \"      <td>0.2575</td>\\n\",\n       \"      <td>0.6638</td>\\n\",\n       \"      <td>0.17300</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>20.29</td>\\n\",\n       \"      <td>14.34</td>\\n\",\n       \"      <td>135.10</td>\\n\",\n       \"      <td>1297.0</td>\\n\",\n       \"      <td>0.10030</td>\\n\",\n       \"      <td>0.13280</td>\\n\",\n       \"      <td>0.1980</td>\\n\",\n       \"      <td>0.10430</td>\\n\",\n       \"      <td>0.1809</td>\\n\",\n       \"      <td>0.05883</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>22.54</td>\\n\",\n       \"      <td>16.67</td>\\n\",\n       \"      <td>152.20</td>\\n\",\n       \"      <td>1575.0</td>\\n\",\n       \"      <td>0.1374</td>\\n\",\n       \"      <td>0.2050</td>\\n\",\n       \"      <td>0.4000</td>\\n\",\n       \"      <td>0.1625</td>\\n\",\n       \"      <td>0.2364</td>\\n\",\n       \"      <td>0.07678</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"<p>5 rows \u00d7 30 columns</p>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"   mean radius  mean texture  mean perimeter  mean area  mean smoothness  \\\\\\n\",\n       \"0        17.99         10.38          122.80     1001.0          0.11840   \\n\",\n       \"1        20.57         17.77          132.90     1326.0          0.08474   \\n\",\n       \"2        19.69         21.25          130.00     1203.0          0.10960   \\n\",\n       \"3        11.42         20.38           77.58      386.1          0.14250   \\n\",\n       \"4        20.29         14.34          135.10     1297.0          0.10030   \\n\",\n       \"\\n\",\n       \"   mean compactness  mean concavity  mean concave points  mean symmetry  \\\\\\n\",\n       \"0           0.27760          0.3001              0.14710         0.2419   \\n\",\n       \"1           0.07864          0.0869              0.07017         0.1812   \\n\",\n       \"2           0.15990          0.1974              0.12790         0.2069   \\n\",\n       \"3           0.28390          0.2414              0.10520         0.2597   \\n\",\n       \"4           0.13280          0.1980              0.10430         0.1809   \\n\",\n       \"\\n\",\n       \"   mean fractal dimension  ...  worst radius  worst texture  worst perimeter  \\\\\\n\",\n       \"0                 0.07871  ...         25.38          17.33           184.60   \\n\",\n       \"1                 0.05667  ...         24.99          23.41           158.80   \\n\",\n       \"2                 0.05999  ...         23.57          25.53           152.50   \\n\",\n       \"3                 0.09744  ...         14.91          26.50            98.87   \\n\",\n       \"4                 0.05883  ...         22.54          16.67           152.20   \\n\",\n       \"\\n\",\n       \"   worst area  worst smoothness  worst compactness  worst concavity  \\\\\\n\",\n       \"0      2019.0            0.1622             0.6656           0.7119   \\n\",\n       \"1      1956.0            0.1238             0.1866           0.2416   \\n\",\n       \"2      1709.0            0.1444             0.4245           0.4504   \\n\",\n       \"3       567.7            0.2098             0.8663           0.6869   \\n\",\n       \"4      1575.0            0.1374             0.2050           0.4000   \\n\",\n       \"\\n\",\n       \"   worst concave points  worst symmetry  worst fractal dimension  \\n\",\n       \"0                0.2654          0.4601                  0.11890  \\n\",\n       \"1                0.1860          0.2750                  0.08902  \\n\",\n       \"2                0.2430          0.3613                  0.08758  \\n\",\n       \"3                0.2575          0.6638                  0.17300  \\n\",\n       \"4                0.1625          0.2364                  0.07678  \\n\",\n       \"\\n\",\n       \"[5 rows x 30 columns]\"\n      ]\n     },\n     \"execution_count\": 3,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"cancer = load_breast_cancer()\\n\",\n    \"df = pd.DataFrame(cancer.data,\\n\",\n    \"                  columns=cancer.feature_names)\\n\",\n    \"df.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X = (df-df.mean())/df.std()\\n\",\n    \"# X = 2*(df-df.min())/(df.max()-df.min()) - 1\\n\",\n    \"# X = df\\n\",\n    \"y = pd.Series(cancer.target)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Make train and test sets\\n\",\n    \"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, \\n\",\n    \"                                                    shuffle=True, random_state=2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Accuracy: 0.97\\n\",\n      \"Precision: 0.99\\n\",\n      \"Recall: 0.97\\n\",\n      \"F-Score: 0.98\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# Initialize a logistic regression model\\n\",\n    \"log_reg_model = LogisticRegression(max_iter=2500,\\n\",\n    \"                                   random_state=42)\\n\",\n    \"\\n\",\n    \"# Train (fit) the model\\n\",\n    \"log_reg_model.fit(X_train, y_train)\\n\",\n    \"\\n\",\n    \"# Make predictions\\n\",\n    \"y_pred = log_reg_model.predict(X_test) # Predictions\\n\",\n    \"y_true = y_test # True values\\n\",\n    \"\\n\",\n    \"# Model evaluation\\n\",\n    \"from sklearn.metrics import accuracy_score\\n\",\n    \"from sklearn.metrics import precision_recall_fscore_support\\n\",\n    \"import numpy as np\\n\",\n    \"\\n\",\n    \"print(\\\"Accuracy:\\\", np.round(accuracy_score(y_true, y_pred), 2))\\n\",\n    \"precision, recall, fscore, _ = precision_recall_fscore_support(y_true, y_pred,\\n\",\n    \"                                                               average='binary')\\n\",\n    \"print(\\\"Precision:\\\", np.round(precision, 2))\\n\",\n    \"print(\\\"Recall:\\\", np.round(recall, 2))\\n\",\n    \"print(\\\"F-Score:\\\", np.round(fscore, 2))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model = Sequential()\\n\",\n    \"\\n\",\n    \"model.add(InputLayer(input_shape=(30, )))\\n\",\n    \"# No hidden layers\\n\",\n    \"model.add(Dense(1, activation='sigmoid'))\\n\",\n    \"\\n\",\n    \"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\\n\",\n    \"model.compile(optimizer=optimizer,\\n\",\n    \"                  loss='binary_crossentropy',\\n\",\n    \"                  metrics=['accuracy'])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/10\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-12 14:37:31.395427: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"12/12 [==============================] - 0s 15ms/step - loss: 0.3646 - accuracy: 0.8407 - val_loss: 0.1326 - val_accuracy: 0.9341\\n\",\n      \"Epoch 2/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0995 - accuracy: 0.9643 - val_loss: 0.0896 - val_accuracy: 0.9560\\n\",\n      \"Epoch 3/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0793 - accuracy: 0.9808 - val_loss: 0.0776 - val_accuracy: 0.9670\\n\",\n      \"Epoch 4/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0734 - accuracy: 0.9808 - val_loss: 0.0749 - val_accuracy: 0.9560\\n\",\n      \"Epoch 5/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0705 - accuracy: 0.9780 - val_loss: 0.0735 - val_accuracy: 0.9560\\n\",\n      \"Epoch 6/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.0684 - accuracy: 0.9808 - val_loss: 0.0713 - val_accuracy: 0.9670\\n\",\n      \"Epoch 7/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0667 - accuracy: 0.9835 - val_loss: 0.0687 - val_accuracy: 0.9780\\n\",\n      \"Epoch 8/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0653 - accuracy: 0.9835 - val_loss: 0.0665 - val_accuracy: 0.9670\\n\",\n      \"Epoch 9/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0640 - accuracy: 0.9835 - val_loss: 0.0648 - val_accuracy: 0.9670\\n\",\n      \"Epoch 10/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.0628 - accuracy: 0.9835 - val_loss: 0.0635 - val_accuracy: 0.9670\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x160461eb0>\"\n      ]\n     },\n     \"execution_count\": 8,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.fit(X_train, y_train,\\n\",\n    \"          epochs=10, batch_size=32,\\n\",\n    \"          validation_split=0.2,\\n\",\n    \"          shuffle=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"4/4 [==============================] - 0s 1ms/step - loss: 0.0719 - accuracy: 0.9737\\n\",\n      \"Test loss: 0.07194967567920685\\n\",\n      \"Test accuracy: 0.9736841917037964\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test_loss, test_acc = model.evaluate(X_test, y_test)\\n\",\n    \"print(\\\"Test loss:\\\", test_loss)\\n\",\n    \"print(\\\"Test accuracy:\\\", test_acc)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def zigmoid(x):\\n\",\n    \"    return 0.502073021 + 0.198695283 * x - 0.001570683 * x**2 - 0.004001354 * x**3\\n\",\n    \"zigmoid_model = Sequential()\\n\",\n    \"\\n\",\n    \"zigmoid_model.add(InputLayer(input_shape=(30, )))\\n\",\n    \"# No hidden layers\\n\",\n    \"zigmoid_model.add(Dense(1, activation=zigmoid))\\n\",\n    \"\\n\",\n    \"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\\n\",\n    \"zigmoid_model.compile(optimizer=optimizer,\\n\",\n    \"                  loss='binary_crossentropy',\\n\",\n    \"                  metrics=['accuracy'])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/10\\n\",\n      \"12/12 [==============================] - 0s 11ms/step - loss: 1.1248 - accuracy: 0.7720 - val_loss: 0.5485 - val_accuracy: 0.9011\\n\",\n      \"Epoch 2/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.5224 - accuracy: 0.9121 - val_loss: 0.2269 - val_accuracy: 0.9780\\n\",\n      \"Epoch 3/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2841 - accuracy: 0.9423 - val_loss: 0.1875 - val_accuracy: 0.9560\\n\",\n      \"Epoch 4/10\\n\",\n      \"12/12 [==============================] - 0s 3ms/step - loss: 0.2715 - accuracy: 0.9588 - val_loss: 0.1772 - val_accuracy: 0.9560\\n\",\n      \"Epoch 5/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2591 - accuracy: 0.9560 - val_loss: 0.1714 - val_accuracy: 0.9670\\n\",\n      \"Epoch 6/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2549 - accuracy: 0.9560 - val_loss: 0.1657 - val_accuracy: 0.9670\\n\",\n      \"Epoch 7/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2559 - accuracy: 0.9533 - val_loss: 0.1639 - val_accuracy: 0.9670\\n\",\n      \"Epoch 8/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2508 - accuracy: 0.9533 - val_loss: 0.1605 - val_accuracy: 0.9670\\n\",\n      \"Epoch 9/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2475 - accuracy: 0.9560 - val_loss: 0.1590 - val_accuracy: 0.9670\\n\",\n      \"Epoch 10/10\\n\",\n      \"12/12 [==============================] - 0s 2ms/step - loss: 0.2490 - accuracy: 0.9588 - val_loss: 0.1591 - val_accuracy: 0.9560\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x1604f03a0>\"\n      ]\n     },\n     \"execution_count\": 11,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"zigmoid_model.fit(X_train, y_train,\\n\",\n    \"          epochs=10, batch_size=32,\\n\",\n    \"          validation_split=0.2,\\n\",\n    \"          shuffle=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"4/4 [==============================] - 0s 1ms/step - loss: 0.1795 - accuracy: 0.9561\\n\",\n      \"Test loss: 0.1795477569103241\\n\",\n      \"Test accuracy: 0.9561403393745422\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test_loss, test_acc = zigmoid_model.evaluate(X_test, y_test)\\n\",\n    \"print(\\\"Test loss:\\\", test_loss)\\n\",\n    \"print(\\\"Test accuracy:\\\", test_acc)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/maxPooling2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, MaxPooling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = MaxPooling2D(pool_size=2)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d (MaxPooling2D  (None, 2, 2, 3)          0         \\n\",\n      \" )                                                               \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.44076837, 0.4645178 , 0.88532658],\\n\",\n       \"         [0.98571178, 0.36091035, 0.37878294],\\n\",\n       \"         [0.09039054, 0.43555648, 0.70723494],\\n\",\n       \"         [0.75087575, 0.46161156, 0.27621923],\\n\",\n       \"         [0.3658674 , 0.76096207, 0.85368763]],\\n\",\n       \"\\n\",\n       \"        [[0.53353854, 0.18599507, 0.85547589],\\n\",\n       \"         [0.83705565, 0.3310797 , 0.42121576],\\n\",\n       \"         [0.97948862, 0.58870474, 0.022469  ],\\n\",\n       \"         [0.40446888, 0.15924946, 0.39474075],\\n\",\n       \"         [0.39336331, 0.83113873, 0.58711273]],\\n\",\n       \"\\n\",\n       \"        [[0.00324599, 0.84351736, 0.65574229],\\n\",\n       \"         [0.00423293, 0.09477659, 0.85111496],\\n\",\n       \"         [0.84792575, 0.32417744, 0.52031854],\\n\",\n       \"         [0.78577668, 0.63963473, 0.66767045],\\n\",\n       \"         [0.6838523 , 0.40963437, 0.296101  ]],\\n\",\n       \"\\n\",\n       \"        [[0.25513283, 0.21434056, 0.139309  ],\\n\",\n       \"         [0.61281984, 0.77039643, 0.3830965 ],\\n\",\n       \"         [0.52747206, 0.60847264, 0.60792949],\\n\",\n       \"         [0.63030064, 0.5966706 , 0.05825615],\\n\",\n       \"         [0.78633397, 0.4404418 , 0.30296519]],\\n\",\n       \"\\n\",\n       \"        [[0.4233433 , 0.2882031 , 0.85232675],\\n\",\n       \"         [0.60716483, 0.95202431, 0.39592074],\\n\",\n       \"         [0.55245804, 0.00922525, 0.50775513],\\n\",\n       \"         [0.65796373, 0.01939091, 0.10486254],\\n\",\n       \"         [0.06172721, 0.64735306, 0.22485494]]]])\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 29ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-23 21:44:15.505331: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.98571175, 0.4645178 , 0.88532656],\\n\",\n       \"         [0.9794886 , 0.58870476, 0.7072349 ]],\\n\",\n       \"\\n\",\n       \"        [[0.61281985, 0.84351736, 0.851115  ],\\n\",\n       \"         [0.8479257 , 0.6396347 , 0.6676704 ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    out = [[[str(max(input[i*strides + x][j*strides + y][k] for x in range(poolSize) for y in range(poolSize)) % p) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\\n\",\n    \"    return Input, out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[[['985711776216457240221750775571808256',\\n\",\n       \"   '464517795839652376609037137683152896',\\n\",\n       \"   '885326582306963556558255153072832512'],\\n\",\n       \"  ['979488619923621857462245439242764288',\\n\",\n       \"   '588704741840418336217153490575687680',\\n\",\n       \"   '707234940167889112717525758819434496']],\\n\",\n       \" [['612819836329411865644509177766215680',\\n\",\n       \"   '843517362609097245279278883187720192',\\n\",\n       \"   '851114962252709222552843081379479552'],\\n\",\n       \"  ['847925751912674500468804749306626048',\\n\",\n       \"   '639634733901388366288661852182282240',\\n\",\n       \"   '667670451847854954465177838892875776']]]\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out = MaxPooling2DInt(5, 5, 3, 2, 2, X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"maxPooling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = MaxPooling2D(pool_size=2, strides=3)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 10, 10, 3)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d_1 (MaxPooling  (None, 3, 3, 3)          0         \\n\",\n      \" 2D)                                                             \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.9790171 , 0.49837833, 0.23951505],\\n\",\n       \"         [0.85478487, 0.10183569, 0.57204256],\\n\",\n       \"         [0.12906496, 0.12259599, 0.61308313],\\n\",\n       \"         [0.68956844, 0.27468499, 0.73800473],\\n\",\n       \"         [0.97031435, 0.65275678, 0.57039273],\\n\",\n       \"         [0.48422669, 0.62184484, 0.12322611],\\n\",\n       \"         [0.45518299, 0.70342415, 0.77375435],\\n\",\n       \"         [0.1334539 , 0.78283045, 0.48137776],\\n\",\n       \"         [0.97002355, 0.70346344, 0.04099013],\\n\",\n       \"         [0.34556716, 0.30939804, 0.12870492]],\\n\",\n       \"\\n\",\n       \"        [[0.55049916, 0.15188193, 0.514953  ],\\n\",\n       \"         [0.07403779, 0.906408  , 0.20947497],\\n\",\n       \"         [0.57003003, 0.93417836, 0.09306473],\\n\",\n       \"         [0.17917856, 0.67291796, 0.4088607 ],\\n\",\n       \"         [0.10408118, 0.55822855, 0.62854813],\\n\",\n       \"         [0.20925919, 0.68269696, 0.60650138],\\n\",\n       \"         [0.94999975, 0.12429107, 0.41003125],\\n\",\n       \"         [0.16150869, 0.35470003, 0.54676562],\\n\",\n       \"         [0.14792857, 0.78346031, 0.25734593],\\n\",\n       \"         [0.89233997, 0.28742825, 0.13791151]],\\n\",\n       \"\\n\",\n       \"        [[0.79274313, 0.99061523, 0.68711779],\\n\",\n       \"         [0.57504418, 0.32618382, 0.16722838],\\n\",\n       \"         [0.09678065, 0.3591776 , 0.62750915],\\n\",\n       \"         [0.68795545, 0.01609884, 0.97099217],\\n\",\n       \"         [0.23381142, 0.84909675, 0.88405792],\\n\",\n       \"         [0.73191384, 0.98947014, 0.52221912],\\n\",\n       \"         [0.89714287, 0.03510341, 0.20639419],\\n\",\n       \"         [0.38323203, 0.16914071, 0.41209687],\\n\",\n       \"         [0.13122496, 0.53340704, 0.60455243],\\n\",\n       \"         [0.71565705, 0.67219914, 0.92696397]],\\n\",\n       \"\\n\",\n       \"        [[0.55416618, 0.74973965, 0.59748271],\\n\",\n       \"         [0.10440772, 0.32236564, 0.92791157],\\n\",\n       \"         [0.41841302, 0.27220821, 0.61662229],\\n\",\n       \"         [0.7338952 , 0.37152599, 0.31517472],\\n\",\n       \"         [0.20252929, 0.67581558, 0.34286098],\\n\",\n       \"         [0.01504774, 0.04681701, 0.14321044],\\n\",\n       \"         [0.3653292 , 0.25028834, 0.33848712],\\n\",\n       \"         [0.29191385, 0.34659568, 0.98273622],\\n\",\n       \"         [0.50778695, 0.7199723 , 0.05608854],\\n\",\n       \"         [0.72340647, 0.76685192, 0.37388969]],\\n\",\n       \"\\n\",\n       \"        [[0.52331559, 0.62356855, 0.26878584],\\n\",\n       \"         [0.15838795, 0.90184899, 0.23912789],\\n\",\n       \"         [0.41272637, 0.7610872 , 0.12672697],\\n\",\n       \"         [0.70626725, 0.98208145, 0.60164227],\\n\",\n       \"         [0.35664872, 0.41128872, 0.09382977],\\n\",\n       \"         [0.70544007, 0.82240552, 0.90325495],\\n\",\n       \"         [0.72007321, 0.24536308, 0.60690892],\\n\",\n       \"         [0.48655372, 0.46328671, 0.60648263],\\n\",\n       \"         [0.18854088, 0.45044603, 0.69043293],\\n\",\n       \"         [0.1217475 , 0.655353  , 0.87733639]],\\n\",\n       \"\\n\",\n       \"        [[0.02353603, 0.18097275, 0.19114613],\\n\",\n       \"         [0.72104431, 0.65310589, 0.48925075],\\n\",\n       \"         [0.26145721, 0.95118427, 0.64482692],\\n\",\n       \"         [0.08753618, 0.2596348 , 0.53771786],\\n\",\n       \"         [0.07314132, 0.06774864, 0.34392025],\\n\",\n       \"         [0.16282229, 0.95993633, 0.79667906],\\n\",\n       \"         [0.74674627, 0.53217006, 0.65900082],\\n\",\n       \"         [0.87522692, 0.13258819, 0.16230994],\\n\",\n       \"         [0.44525752, 0.67365898, 0.51766928],\\n\",\n       \"         [0.72182701, 0.43780393, 0.98069118]],\\n\",\n       \"\\n\",\n       \"        [[0.25691084, 0.11661927, 0.67618617],\\n\",\n       \"         [0.66069801, 0.9045992 , 0.86337172],\\n\",\n       \"         [0.08042041, 0.78517436, 0.69269604],\\n\",\n       \"         [0.44734739, 0.30140176, 0.18295808],\\n\",\n       \"         [0.07556447, 0.4891693 , 0.20302939],\\n\",\n       \"         [0.22243138, 0.65584446, 0.56134481],\\n\",\n       \"         [0.91535994, 0.429726  , 0.89466843],\\n\",\n       \"         [0.25180203, 0.12145168, 0.26456649],\\n\",\n       \"         [0.56398398, 0.18346371, 0.034341  ],\\n\",\n       \"         [0.37802503, 0.22614985, 0.85292929]],\\n\",\n       \"\\n\",\n       \"        [[0.19171201, 0.46156136, 0.78027617],\\n\",\n       \"         [0.1697258 , 0.36865057, 0.30921552],\\n\",\n       \"         [0.63491691, 0.76223827, 0.91491496],\\n\",\n       \"         [0.68871028, 0.86998105, 0.79183476],\\n\",\n       \"         [0.50452778, 0.27036477, 0.19829515],\\n\",\n       \"         [0.82527008, 0.35258264, 0.42346427],\\n\",\n       \"         [0.73552096, 0.76506646, 0.50324396],\\n\",\n       \"         [0.08392757, 0.11886597, 0.31341576],\\n\",\n       \"         [0.42816313, 0.8535268 , 0.59585608],\\n\",\n       \"         [0.00429868, 0.66229572, 0.07715835]],\\n\",\n       \"\\n\",\n       \"        [[0.95901268, 0.85618315, 0.47768876],\\n\",\n       \"         [0.66614175, 0.08345771, 0.80790147],\\n\",\n       \"         [0.29208239, 0.4360204 , 0.18332789],\\n\",\n       \"         [0.28169483, 0.63096452, 0.96729756],\\n\",\n       \"         [0.07859661, 0.92728092, 0.80810303],\\n\",\n       \"         [0.97020859, 0.87780948, 0.83993202],\\n\",\n       \"         [0.68006058, 0.68787335, 0.70198168],\\n\",\n       \"         [0.31865081, 0.97290491, 0.13625889],\\n\",\n       \"         [0.80537841, 0.03953296, 0.16870381],\\n\",\n       \"         [0.90864186, 0.54762421, 0.71436361]],\\n\",\n       \"\\n\",\n       \"        [[0.19054836, 0.34380661, 0.68153459],\\n\",\n       \"         [0.16505021, 0.0412163 , 0.36928843],\\n\",\n       \"         [0.38454084, 0.30131942, 0.29021317],\\n\",\n       \"         [0.74076099, 0.97099106, 0.30053946],\\n\",\n       \"         [0.62869618, 0.12455381, 0.62562719],\\n\",\n       \"         [0.91303674, 0.39900546, 0.92873058],\\n\",\n       \"         [0.7949276 , 0.00620029, 0.17023317],\\n\",\n       \"         [0.40570501, 0.1780136 , 0.19150324],\\n\",\n       \"         [0.56676977, 0.84413934, 0.73247166],\\n\",\n       \"         [0.0028076 , 0.26181396, 0.70691029]]]])\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 21ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.9790171 , 0.906408  , 0.5720426 ],\\n\",\n       \"         [0.9703143 , 0.67291796, 0.73800474],\\n\",\n       \"         [0.94999975, 0.7828305 , 0.77375436]],\\n\",\n       \"\\n\",\n       \"        [[0.5541662 , 0.901849  , 0.9279116 ],\\n\",\n       \"         [0.7338952 , 0.9820815 , 0.60164225],\\n\",\n       \"         [0.7200732 , 0.46328673, 0.98273623]],\\n\",\n       \"\\n\",\n       \"        [[0.660698  , 0.9045992 , 0.86337173],\\n\",\n       \"         [0.6887103 , 0.86998105, 0.7918348 ],\\n\",\n       \"         [0.9153599 , 0.76506644, 0.89466846]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[[['979017099491110018942067312821272576',\\n\",\n       \"   '906408000806632452114797174150135808',\\n\",\n       \"   '572042560577051270101001688850628608'],\\n\",\n       \"  ['970314350513558277989324779994218496',\\n\",\n       \"   '672917960272193945175567190387064832',\\n\",\n       \"   '738004729474624730341896972922781696'],\\n\",\n       \"  ['949999745668024165489517038806237184',\\n\",\n       \"   '782830451141896167400921576545189888',\\n\",\n       \"   '773754352982266439136539456512720896']],\\n\",\n       \" [['554166181126147404440246990770536448',\\n\",\n       \"   '901848991352918850169033731149398016',\\n\",\n       \"   '927911571088135929200009259356520448'],\\n\",\n       \"  ['733895199634136636354978553303924736',\\n\",\n       \"   '982081449688638090663868389740511232',\\n\",\n       \"   '601642265832659125360941789945528320'],\\n\",\n       \"  ['720073208604618054954869080641765376',\\n\",\n       \"   '463286712794445136678401315688153088',\\n\",\n       \"   '982736221843810664156369288039497728']],\\n\",\n       \" [['660698008644203700473074429819092992',\\n\",\n       \"   '904599195577579897660922571020828672',\\n\",\n       \"   '863371715944324158495051960144625664'],\\n\",\n       \"  ['688710284469165685404738243641999360',\\n\",\n       \"   '869981053223066390571414093008207872',\\n\",\n       \"   '791834758925232104719097862035603456'],\\n\",\n       \"  ['915359938539886757509738228069957632',\\n\",\n       \"   '765066456516048413755703502695301120',\\n\",\n       \"   '894668431976368139307673421153828864']]]\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, out = MaxPooling2DInt(10, 10, 3, 2, 3, X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"maxPooling2D_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/maxPooling2d_same.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, MaxPooling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = MaxPooling2D(pool_size=2, padding='same')(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 5, 5, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d (MaxPooling2D  (None, 3, 3, 3)          0         \\n\",\n      \" )                                                               \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.9854169 , 0.80569586, 0.63268445],\\n\",\n       \"         [0.96206047, 0.00886907, 0.67775967],\\n\",\n       \"         [0.46792544, 0.81360698, 0.34777212],\\n\",\n       \"         [0.90835439, 0.69174656, 0.98172619],\\n\",\n       \"         [0.10715328, 0.91657229, 0.81624555]],\\n\",\n       \"\\n\",\n       \"        [[0.57038264, 0.90280394, 0.77766336],\\n\",\n       \"         [0.63409067, 0.82595812, 0.38151341],\\n\",\n       \"         [0.79552045, 0.2163596 , 0.87461672],\\n\",\n       \"         [0.74681147, 0.47584101, 0.93002867],\\n\",\n       \"         [0.11400012, 0.97409111, 0.87404365]],\\n\",\n       \"\\n\",\n       \"        [[0.53957961, 0.50863284, 0.89012595],\\n\",\n       \"         [0.27801669, 0.55281537, 0.50004972],\\n\",\n       \"         [0.31374426, 0.41849849, 0.81763357],\\n\",\n       \"         [0.68099263, 0.21715725, 0.60245081],\\n\",\n       \"         [0.23044868, 0.89402184, 0.73802917]],\\n\",\n       \"\\n\",\n       \"        [[0.65681518, 0.45431134, 0.11186951],\\n\",\n       \"         [0.63232732, 0.09914006, 0.469778  ],\\n\",\n       \"         [0.53980327, 0.00999922, 0.32385368],\\n\",\n       \"         [0.51189833, 0.23540886, 0.48827071],\\n\",\n       \"         [0.97347711, 0.16329774, 0.73404494]],\\n\",\n       \"\\n\",\n       \"        [[0.02010803, 0.73200388, 0.75296659],\\n\",\n       \"         [0.47080583, 0.89997758, 0.77754373],\\n\",\n       \"         [0.45047643, 0.60846601, 0.22025449],\\n\",\n       \"         [0.81318524, 0.86405236, 0.44136216],\\n\",\n       \"         [0.53790431, 0.45931736, 0.00951743]]]])\"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 42ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2024-02-05 01:27:05.945781: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.9854169 , 0.90280396, 0.77766335],\\n\",\n       \"         [0.9083544 , 0.813607  , 0.98172617],\\n\",\n       \"         [0.11400012, 0.9740911 , 0.87404364]],\\n\",\n       \"\\n\",\n       \"        [[0.6568152 , 0.5528154 , 0.89012593],\\n\",\n       \"         [0.6809926 , 0.4184985 , 0.81763357],\\n\",\n       \"         [0.9734771 , 0.89402187, 0.7380292 ]],\\n\",\n       \"\\n\",\n       \"        [[0.47080582, 0.89997756, 0.7775437 ],\\n\",\n       \"         [0.8131852 , 0.86405236, 0.44136214],\\n\",\n       \"         [0.5379043 , 0.45931736, 0.00951743]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\\n\",\n    \"    out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\\n\",\n    \"    return out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def MaxPooling2DsameInt(nRows, nCols, nChannels, poolSize, strides, input):\\n\",\n    \"    if nRows % strides == 0:\\n\",\n    \"        rowPadding = max(poolSize - strides, 0)\\n\",\n    \"    else:\\n\",\n    \"        rowPadding = max(poolSize - nRows % strides, 0)\\n\",\n    \"    if nCols % strides == 0:\\n\",\n    \"        colPadding = max(poolSize - strides, 0)\\n\",\n    \"    else:\\n\",\n    \"        colPadding = max(poolSize - nCols % strides, 0)\\n\",\n    \"    \\n\",\n    \"    _input = [[[0 for _ in range(nChannels)] for _ in range(nCols + colPadding)] for _ in range(nRows + rowPadding)]\\n\",\n    \"\\n\",\n    \"    for i in range(nRows):\\n\",\n    \"        for j in range(nCols):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                _input[i+rowPadding//2][j+colPadding//2][k] = input[i][j][k]\\n\",\n    \"    \\n\",\n    \"    out = MaxPooling2DInt(nRows + rowPadding, nCols + colPadding, nChannels, poolSize, strides, _input)\\n\",\n    \"    return out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[[['985416895178787714183661703755988992',\\n\",\n       \"   '902803940435826284139749932730941440',\\n\",\n       \"   '777663362123877860598598645145665536'],\\n\",\n       \"  ['908354388868282470618698257109352448',\\n\",\n       \"   '813606982115283460844798537969434624',\\n\",\n       \"   '981726193592448973649175667344932864'],\\n\",\n       \"  ['114000116831430861403008392105033728',\\n\",\n       \"   '974091109200621567612816335791194112',\\n\",\n       \"   '874043654050301690820171495435665408']],\\n\",\n       \" [['656815180323522869339469446928924672',\\n\",\n       \"   '552815374291668108366329210074038272',\\n\",\n       \"   '890125946940297760199841005954924544'],\\n\",\n       \"  ['680992631793690390926240128859897856',\\n\",\n       \"   '418498494396639822766365224919367680',\\n\",\n       \"   '817633569064628434285947918592507904'],\\n\",\n       \"  ['973477114549060379932212627888930816',\\n\",\n       \"   '894021844181003495121759207996522496',\\n\",\n       \"   '738029169437394307130485433159385088']],\\n\",\n       \" [['470805829710577633964522992960536576',\\n\",\n       \"   '899977578211573860664606514781093888',\\n\",\n       \"   '777543729617406477245147183797239808'],\\n\",\n       \"  ['813185240376988213714402965620523008',\\n\",\n       \"   '864052363876363850452980196205133824',\\n\",\n       \"   '441362157036501413461183215236546560'],\\n\",\n       \"  ['537904308558723633624141672348647424',\\n\",\n       \"   '459317359421049476909261905824055296',\\n\",\n       \"   '9517425402804758462154346481057792']]]\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"out = MaxPooling2DsameInt(5, 5, 3, 2, 2, X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"maxPooling2Dsame_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = MaxPooling2D(pool_size=2, strides=3, padding='same')(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 10, 10, 3)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d_1 (MaxPooling  (None, 4, 4, 3)          0         \\n\",\n      \" 2D)                                                             \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[1.81060846e-01, 8.73335066e-01, 4.66591631e-01],\\n\",\n       \"         [4.19512826e-01, 5.04687534e-01, 5.55108518e-01],\\n\",\n       \"         [8.89727395e-01, 3.04715421e-01, 3.96868333e-01],\\n\",\n       \"         [3.19583099e-01, 7.59947198e-04, 8.95376898e-01],\\n\",\n       \"         [1.86082695e-01, 5.89361183e-01, 2.29939007e-01],\\n\",\n       \"         [3.77869457e-01, 5.93831349e-01, 6.17898741e-01],\\n\",\n       \"         [2.08890055e-01, 4.52999632e-02, 4.81015031e-02],\\n\",\n       \"         [9.68292068e-01, 4.24571806e-01, 4.18124731e-02],\\n\",\n       \"         [3.30703359e-02, 6.13358807e-01, 9.62525235e-01],\\n\",\n       \"         [8.80909151e-01, 3.16377883e-02, 4.07229564e-01]],\\n\",\n       \"\\n\",\n       \"        [[7.22047037e-01, 2.87769873e-01, 6.33057960e-01],\\n\",\n       \"         [5.87593115e-01, 9.95928671e-01, 9.47646805e-02],\\n\",\n       \"         [6.73764008e-01, 4.41940517e-01, 2.05872675e-01],\\n\",\n       \"         [2.74105248e-01, 3.41288944e-01, 7.03928155e-01],\\n\",\n       \"         [2.53407876e-01, 9.54086619e-01, 6.95949832e-01],\\n\",\n       \"         [7.72974380e-01, 6.94646688e-01, 2.39040667e-01],\\n\",\n       \"         [7.61119704e-01, 8.41368944e-01, 9.12971104e-01],\\n\",\n       \"         [3.19331761e-01, 2.36474093e-01, 3.11432211e-01],\\n\",\n       \"         [6.18384476e-01, 2.23794997e-01, 7.33884991e-01],\\n\",\n       \"         [1.00735392e-01, 7.42390580e-01, 7.43563278e-01]],\\n\",\n       \"\\n\",\n       \"        [[1.82788443e-01, 9.69266407e-01, 6.79896409e-02],\\n\",\n       \"         [5.47375743e-01, 7.00178164e-01, 1.62010347e-02],\\n\",\n       \"         [2.70368172e-01, 9.53685968e-01, 4.62933777e-01],\\n\",\n       \"         [4.80574859e-01, 1.55085614e-01, 2.38047469e-01],\\n\",\n       \"         [4.86919140e-01, 1.94033355e-02, 1.80402947e-01],\\n\",\n       \"         [3.96449294e-01, 4.95605585e-01, 2.26605072e-01],\\n\",\n       \"         [1.74141020e-02, 3.46487475e-03, 8.98099350e-01],\\n\",\n       \"         [7.85190855e-01, 3.05525061e-01, 2.04565391e-01],\\n\",\n       \"         [8.23700964e-01, 2.97490709e-01, 6.50482927e-02],\\n\",\n       \"         [1.26448774e-01, 8.10615035e-01, 5.09045959e-01]],\\n\",\n       \"\\n\",\n       \"        [[7.13680159e-01, 8.45319480e-01, 9.11203285e-01],\\n\",\n       \"         [8.27233800e-01, 4.12657299e-01, 6.97025851e-01],\\n\",\n       \"         [2.81018305e-01, 6.48955744e-01, 8.91153606e-01],\\n\",\n       \"         [6.29371477e-01, 7.75929101e-01, 7.79093686e-01],\\n\",\n       \"         [1.23716197e-01, 3.10122093e-01, 8.37055316e-01],\\n\",\n       \"         [1.68089475e-01, 9.54284278e-01, 3.18407200e-01],\\n\",\n       \"         [3.62606007e-01, 7.78830849e-01, 3.99089020e-01],\\n\",\n       \"         [8.51653764e-02, 5.34511941e-01, 6.04920400e-01],\\n\",\n       \"         [2.71115350e-01, 4.36692189e-01, 6.96241628e-01],\\n\",\n       \"         [8.65780466e-01, 3.22369175e-01, 7.43159548e-01]],\\n\",\n       \"\\n\",\n       \"        [[9.28690706e-02, 3.94089568e-01, 5.61323421e-01],\\n\",\n       \"         [5.90368083e-01, 9.74901900e-01, 9.47030261e-01],\\n\",\n       \"         [6.30178577e-01, 5.13484751e-01, 1.18185924e-01],\\n\",\n       \"         [4.38458544e-01, 5.63764554e-01, 7.66318218e-01],\\n\",\n       \"         [7.18648243e-01, 1.70367043e-01, 7.70642982e-01],\\n\",\n       \"         [2.22980409e-01, 3.74329609e-01, 4.80409175e-01],\\n\",\n       \"         [9.45617766e-01, 8.81617847e-01, 1.19580346e-01],\\n\",\n       \"         [9.15676461e-01, 9.70518691e-01, 2.43214092e-01],\\n\",\n       \"         [2.41451379e-01, 4.88548632e-01, 3.70190637e-01],\\n\",\n       \"         [4.59905504e-01, 3.80889550e-01, 3.85698952e-01]],\\n\",\n       \"\\n\",\n       \"        [[2.72104416e-01, 7.98516947e-01, 2.72194053e-01],\\n\",\n       \"         [9.48709871e-01, 2.66222380e-01, 9.42522429e-01],\\n\",\n       \"         [7.33569990e-01, 3.47061477e-01, 5.33050356e-01],\\n\",\n       \"         [6.11738759e-01, 8.68186611e-02, 3.75463635e-01],\\n\",\n       \"         [2.14948078e-01, 3.99863394e-01, 1.90922352e-01],\\n\",\n       \"         [5.10853285e-01, 8.50874635e-01, 3.81366847e-01],\\n\",\n       \"         [8.39025985e-01, 6.98107126e-01, 8.44114497e-01],\\n\",\n       \"         [6.99026648e-01, 6.91391860e-01, 5.95508900e-01],\\n\",\n       \"         [3.75264962e-01, 2.19625912e-02, 9.65963233e-01],\\n\",\n       \"         [8.73625070e-01, 1.70130110e-02, 4.28592791e-01]],\\n\",\n       \"\\n\",\n       \"        [[5.30376524e-01, 5.19931919e-01, 8.79621802e-01],\\n\",\n       \"         [5.93691399e-01, 9.43767391e-01, 3.85923387e-01],\\n\",\n       \"         [2.66910663e-02, 9.36911794e-01, 1.02611787e-01],\\n\",\n       \"         [3.59377042e-01, 2.67568222e-01, 5.35446422e-01],\\n\",\n       \"         [5.51850227e-01, 6.35787754e-01, 1.98619411e-01],\\n\",\n       \"         [8.49409850e-01, 6.72271595e-01, 2.39559395e-01],\\n\",\n       \"         [1.73809713e-02, 6.90213328e-01, 4.68996474e-01],\\n\",\n       \"         [2.98860826e-01, 9.70887693e-02, 7.59385182e-01],\\n\",\n       \"         [2.57726817e-01, 9.57823991e-01, 7.18212290e-01],\\n\",\n       \"         [7.01041664e-01, 7.78681302e-01, 2.83077120e-01]],\\n\",\n       \"\\n\",\n       \"        [[7.26341251e-01, 9.88746010e-02, 8.11023617e-01],\\n\",\n       \"         [5.17637504e-01, 1.22369589e-01, 6.26059218e-01],\\n\",\n       \"         [8.89381042e-01, 4.69513890e-01, 4.41358856e-01],\\n\",\n       \"         [1.31543858e-01, 2.52923839e-02, 4.59211802e-01],\\n\",\n       \"         [2.97316029e-01, 3.74157507e-01, 1.46629093e-01],\\n\",\n       \"         [5.42787121e-01, 4.83436833e-01, 6.48266145e-01],\\n\",\n       \"         [5.87451856e-01, 6.62348938e-01, 9.09155419e-01],\\n\",\n       \"         [4.19004871e-01, 1.82945864e-02, 6.63249102e-01],\\n\",\n       \"         [2.32421673e-01, 6.30460531e-01, 6.90273718e-02],\\n\",\n       \"         [1.00823603e-01, 6.38197200e-01, 1.54316174e-01]],\\n\",\n       \"\\n\",\n       \"        [[3.95104675e-01, 9.54576105e-01, 7.18833793e-01],\\n\",\n       \"         [6.55325673e-01, 2.09750597e-01, 5.08179296e-01],\\n\",\n       \"         [8.35434924e-01, 3.11732329e-01, 2.53760179e-01],\\n\",\n       \"         [6.01300571e-01, 1.74387890e-01, 1.28901152e-01],\\n\",\n       \"         [3.60114137e-01, 6.03481824e-01, 6.42517616e-01],\\n\",\n       \"         [4.74822395e-01, 4.06953697e-02, 8.06656676e-01],\\n\",\n       \"         [2.35227783e-01, 1.86636675e-01, 2.92355800e-01],\\n\",\n       \"         [7.57334531e-01, 3.02550198e-01, 8.78392401e-01],\\n\",\n       \"         [9.89429375e-01, 9.17356225e-01, 9.94972892e-01],\\n\",\n       \"         [3.38833764e-01, 2.39923972e-01, 2.49753676e-02]],\\n\",\n       \"\\n\",\n       \"        [[5.34504729e-02, 2.60437560e-01, 4.75257720e-01],\\n\",\n       \"         [5.10602046e-01, 7.24407672e-01, 1.27708925e-01],\\n\",\n       \"         [8.89866378e-01, 7.68391514e-01, 8.10330840e-01],\\n\",\n       \"         [9.04964699e-01, 9.07169014e-01, 3.30947299e-01],\\n\",\n       \"         [3.25628891e-01, 3.62460672e-01, 6.09180261e-01],\\n\",\n       \"         [3.97278800e-01, 2.87846815e-01, 9.51001737e-01],\\n\",\n       \"         [3.94260450e-01, 3.00806280e-01, 8.51360452e-01],\\n\",\n       \"         [3.62097670e-01, 2.24539340e-01, 7.61618704e-01],\\n\",\n       \"         [2.50380406e-01, 7.56360963e-01, 1.16230049e-01],\\n\",\n       \"         [9.01240322e-01, 3.73212987e-01, 7.36122529e-01]]]])\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 30ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.72204703, 0.99592865, 0.63305795],\\n\",\n       \"         [0.3195831 , 0.9540866 , 0.8953769 ],\\n\",\n       \"         [0.96829206, 0.841369  , 0.9129711 ],\\n\",\n       \"         [0.88090914, 0.7423906 , 0.7435633 ]],\\n\",\n       \"\\n\",\n       \"        [[0.8272338 , 0.9749019 , 0.94703025],\\n\",\n       \"         [0.71864825, 0.7759291 , 0.8370553 ],\\n\",\n       \"         [0.9456178 , 0.9705187 , 0.6049204 ],\\n\",\n       \"         [0.8657805 , 0.38088953, 0.74315953]],\\n\",\n       \"\\n\",\n       \"        [[0.72634125, 0.94376737, 0.8796218 ],\\n\",\n       \"         [0.5518502 , 0.6357877 , 0.5354464 ],\\n\",\n       \"         [0.5874519 , 0.6902133 , 0.9091554 ],\\n\",\n       \"         [0.70104164, 0.7786813 , 0.28307712]],\\n\",\n       \"\\n\",\n       \"        [[0.51060206, 0.7244077 , 0.47525772],\\n\",\n       \"         [0.9049647 , 0.90716904, 0.6091803 ],\\n\",\n       \"         [0.39426044, 0.30080628, 0.85136044],\\n\",\n       \"         [0.90124035, 0.373213  , 0.73612255]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[[['722047037048510692294577429613117440',\\n\",\n       \"   '995928671466629356695108803213918208',\\n\",\n       \"   '633057959701190742109452742097371136'],\\n\",\n       \"  ['319583098696415993297833594590330880',\\n\",\n       \"   '954086618948581700566160227891675136',\\n\",\n       \"   '895376897621437771937017335681908736'],\\n\",\n       \"  ['968292067860118608616536728156504064',\\n\",\n       \"   '841368944375512546814487235963912192',\\n\",\n       \"   '912971104374087013640201200717529088'],\\n\",\n       \"  ['880909150990983977881328708709515264',\\n\",\n       \"   '742390579543848987849194909946871808',\\n\",\n       \"   '743563277676321729157199064014520320']],\\n\",\n       \" [['827233800468269198331599375468331008',\\n\",\n       \"   '974901899794306633179826070214410240',\\n\",\n       \"   '947030261209948995604238219295588352'],\\n\",\n       \"  ['718648242610498931670595372570378240',\\n\",\n       \"   '775929100688812511565570103251566592',\\n\",\n       \"   '837055315861977089490188905893330944'],\\n\",\n       \"  ['945617766167062485510007332488085504',\\n\",\n       \"   '970518691217475177799962810208223232',\\n\",\n       \"   '604920400036749440823474048758448128'],\\n\",\n       \"  ['865780466166194901147341462043623424',\\n\",\n       \"   '380889549714929988856634904844173312',\\n\",\n       \"   '743159547886228828110355377787240448']],\\n\",\n       \" [['726341250795347218817727679288049664',\\n\",\n       \"   '943767390679553173919884888860786688',\\n\",\n       \"   '879621802069332614144323070292131840'],\\n\",\n       \"  ['551850226842807715717985301323317248',\\n\",\n       \"   '635787754066812906470475510293987328',\\n\",\n       \"   '535446422069610157460354392595103744'],\\n\",\n       \"  ['587451855996849487170757966572814336',\\n\",\n       \"   '690213328307762114218988812757893120',\\n\",\n       \"   '909155419360394098803395006243536896'],\\n\",\n       \"  ['701041664244132545037467114551640064',\\n\",\n       \"   '778681301680931345113753214299144192',\\n\",\n       \"   '283077119909484707357592139667079168']],\\n\",\n       \" [['510602045587970767184337129422454784',\\n\",\n       \"   '724407671943644015539146665914007552',\\n\",\n       \"   '475257720371555822213696431964815360'],\\n\",\n       \"  ['904964699224751401721193296243458048',\\n\",\n       \"   '907169014433129231084536890038157312',\\n\",\n       \"   '609180260647294075284256963443032064'],\\n\",\n       \"  ['394260450257245198773068562662686720',\\n\",\n       \"   '300806280328724832256760381278519296',\\n\",\n       \"   '851360451534335061119480218741899264'],\\n\",\n       \"  ['901240322382283207026350889182953472',\\n\",\n       \"   '373212986501062202469532290256994304',\\n\",\n       \"   '736122528767077629789884872958935040']]]\"\n      ]\n     },\n     \"execution_count\": 18,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"out = MaxPooling2DsameInt(10, 10, 3, 2, 3, X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"maxPooling2Dsame_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/mnist.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Conv2D, AveragePooling2D, Flatten, Softmax, Dense, Lambda, BatchNormalization, ReLU\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"from tensorflow.keras.datasets import mnist\\n\",\n    \"from tensorflow.keras.utils import to_categorical\\n\",\n    \"from tensorflow.keras.optimizers.legacy import SGD\\n\",\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import tensorflow as tf\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"(X_train, y_train), (X_test, y_test) = mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Convert y_train into one-hot format\\n\",\n    \"temp = []\\n\",\n    \"for i in range(len(y_train)):\\n\",\n    \"    temp.append(to_categorical(y_train[i], num_classes=10))\\n\",\n    \"y_train = np.array(temp)\\n\",\n    \"# Convert y_test into one-hot format\\n\",\n    \"temp = []\\n\",\n    \"for i in range(len(y_test)):    \\n\",\n    \"    temp.append(to_categorical(y_test[i], num_classes=10))\\n\",\n    \"y_test = np.array(temp)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#reshaping\\n\",\n    \"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\\n\",\n    \"X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\\n\",\n    \"\\n\",\n    \"#normalizing\\n\",\n    \"X_train = X_train.astype('float32')\\n\",\n    \"X_test = X_test.astype('float32')\\n\",\n    \"X_train /= 255.0\\n\",\n    \"X_test /= 255.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(28,28,1))\\n\",\n    \"out = Conv2D(4, 3, use_bias=True)(inputs)\\n\",\n    \"out = BatchNormalization()(out)\\n\",\n    \"out = ReLU()(out)\\n\",\n    \"out = AveragePooling2D()(out)\\n\",\n    \"out = Conv2D(8, 3, use_bias=True)(out)\\n\",\n    \"out = BatchNormalization()(out)\\n\",\n    \"out = ReLU()(out)\\n\",\n    \"out = AveragePooling2D()(out)\\n\",\n    \"out = Flatten()(out)\\n\",\n    \"out = Dense(10, activation=None)(out)\\n\",\n    \"out = Softmax()(out)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 28, 28, 1)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d (Conv2D)             (None, 26, 26, 4)         40        \\n\",\n      \"                                                                 \\n\",\n      \" batch_normalization (BatchN  (None, 26, 26, 4)        16        \\n\",\n      \" ormalization)                                                   \\n\",\n      \"                                                                 \\n\",\n      \" re_lu (ReLU)                (None, 26, 26, 4)         0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d (AverageP  (None, 13, 13, 4)        0         \\n\",\n      \" ooling2D)                                                       \\n\",\n      \"                                                                 \\n\",\n      \" conv2d_1 (Conv2D)           (None, 11, 11, 8)         296       \\n\",\n      \"                                                                 \\n\",\n      \" batch_normalization_1 (Batc  (None, 11, 11, 8)        32        \\n\",\n      \" hNormalization)                                                 \\n\",\n      \"                                                                 \\n\",\n      \" re_lu_1 (ReLU)              (None, 11, 11, 8)         0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d_1 (Averag  (None, 5, 5, 8)          0         \\n\",\n      \" ePooling2D)                                                     \\n\",\n      \"                                                                 \\n\",\n      \" flatten (Flatten)           (None, 200)               0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 10)                2010      \\n\",\n      \"                                                                 \\n\",\n      \" softmax (Softmax)           (None, 10)                0         \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 2,394\\n\",\n      \"Trainable params: 2,370\\n\",\n      \"Non-trainable params: 24\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.compile(\\n\",\n    \"    loss='categorical_crossentropy',\\n\",\n    \"    optimizer=SGD(learning_rate=0.01, momentum=0.9),\\n\",\n    \"    metrics=['acc']\\n\",\n    \"    )\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/15\\n\",\n      \"   1/1875 [..............................] - ETA: 5:16 - loss: 2.6515 - acc: 0.0625\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-24 02:23:16.557845: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.1896 - acc: 0.9434 - val_loss: 0.0808 - val_acc: 0.9753\\n\",\n      \"Epoch 2/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0787 - acc: 0.9761 - val_loss: 0.0602 - val_acc: 0.9808\\n\",\n      \"Epoch 3/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0650 - acc: 0.9803 - val_loss: 0.0546 - val_acc: 0.9831\\n\",\n      \"Epoch 4/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0592 - acc: 0.9816 - val_loss: 0.0613 - val_acc: 0.9812\\n\",\n      \"Epoch 5/15\\n\",\n      \"1875/1875 [==============================] - 7s 4ms/step - loss: 0.0536 - acc: 0.9837 - val_loss: 0.0594 - val_acc: 0.9808\\n\",\n      \"Epoch 6/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0497 - acc: 0.9847 - val_loss: 0.0618 - val_acc: 0.9794\\n\",\n      \"Epoch 7/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0470 - acc: 0.9855 - val_loss: 0.0824 - val_acc: 0.9748\\n\",\n      \"Epoch 8/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0451 - acc: 0.9863 - val_loss: 0.0410 - val_acc: 0.9843\\n\",\n      \"Epoch 9/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0433 - acc: 0.9865 - val_loss: 0.0561 - val_acc: 0.9822\\n\",\n      \"Epoch 10/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0425 - acc: 0.9871 - val_loss: 0.0455 - val_acc: 0.9847\\n\",\n      \"Epoch 11/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0397 - acc: 0.9875 - val_loss: 0.0524 - val_acc: 0.9825\\n\",\n      \"Epoch 12/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0391 - acc: 0.9879 - val_loss: 0.0382 - val_acc: 0.9875\\n\",\n      \"Epoch 13/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0381 - acc: 0.9879 - val_loss: 0.0371 - val_acc: 0.9868\\n\",\n      \"Epoch 14/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0360 - acc: 0.9887 - val_loss: 0.0371 - val_acc: 0.9870\\n\",\n      \"Epoch 15/15\\n\",\n      \"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0354 - acc: 0.9887 - val_loss: 0.0378 - val_acc: 0.9874\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x143103e80>\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"((28, 28, 1), 0.0, 1.0)\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = X_test[0]\\n\",\n    \"X.shape, X.min(), X.max()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 45ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"7\"\n      ]\n     },\n     \"execution_count\": 11,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.predict(X.reshape(1,28,28,1)).argmax()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    Weights = [[[[str(weights[i][j][k][l] % p) for l in range(nFilters)] for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nFilters)]\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\\n\",\n    \"    for i in range((nRows - kernelSize)//strides + 1):\\n\",\n    \"        for j in range((nCols - kernelSize)//strides + 1):\\n\",\n    \"            for m in range(nFilters):\\n\",\n    \"                for k in range(nChannels):\\n\",\n    \"                    for x in range(kernelSize):\\n\",\n    \"                        for y in range(kernelSize):\\n\",\n    \"                            out[i][j][m] += input[i*strides+x][j*strides+y][k] * weights[x][y][k][m]\\n\",\n    \"                out[i][j][m] += bias[m]\\n\",\n    \"                remainder[i][j][m] = str(out[i][j][m] % n)\\n\",\n    \"                out[i][j][m] = str(out[i][j][m] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[i][j][0]*1e18)] for j in range(28)] for i in range(28)]\\n\",\n    \"conv2d_1_weights = [[[[int(model.layers[1].weights[0][i][j][k][l]*1e18) for l in range(4)] for k in range(1)] for j in range(3)] for i in range(3)]\\n\",\n    \"conv2d_1_bias = [int(model.layers[1].weights[1][i]*1e36) for i in range(4)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['21888242871839275222246405745257275088548364400416034343698204178650554445275',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343698203817637026120037',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343698204118313744391231',\\n\",\n       \" '48458611567652']\"\n      ]\n     },\n     \"execution_count\": 14,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, conv2d_1_weights, conv2d_1_bias, conv2d_1_out, conv2d_1_remainder = Conv2DInt(28, 28, 1, 4, 3, 1, 10**18, X_in, conv2d_1_weights, conv2d_1_bias)\\n\",\n    \"conv2d_1_out[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 18ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([-7.9252541e-06, -3.6893881e-04, -6.8262067e-05,  4.8458613e-05],\\n\",\n       \"      dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"conv2d_model = Model(inputs, model.layers[1].output)\\n\",\n    \"conv2d_model.predict(X.reshape(1,28,28,1))[0][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"gamma = model.layers[2].weights[0].numpy()\\n\",\n    \"beta = model.layers[2].weights[1].numpy()\\n\",\n    \"moving_mean = model.layers[2].weights[2].numpy()\\n\",\n    \"moving_var = model.layers[2].weights[3].numpy()\\n\",\n    \"epsilon = model.layers[2].epsilon\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(array([2.841136 , 2.7350745, 2.0774858, 1.246628 ], dtype=float32),\\n\",\n       \" array([ 0.9730277 , -0.0507403 , -0.07507665, -0.5589396 ], dtype=float32))\"\n      ]\n     },\n     \"execution_count\": 17,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"a1 = gamma/(moving_var+epsilon)**.5\\n\",\n    \"b1 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\\n\",\n    \"a1, b1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\\n\",\n    \"    X = [[[str(X_in[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    A = [str(a_in[k] % p) for k in range(nChannels)]\\n\",\n    \"    B = [str(b_in[k] % p) for k in range(nChannels)]\\n\",\n    \"    out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\\n\",\n    \"    remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\\n\",\n    \"    for i in range(nRows):\\n\",\n    \"        for j in range(nCols):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                out[i][j][k] = (X_in[i][j][k]*a_in[k] + b_in[k])\\n\",\n    \"                remainder[i][j][k] = str(out[i][j][k] % n)\\n\",\n    \"                out[i][j][k] = str(out[i][j][k] // n % p)\\n\",\n    \"    return X, A, B, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"bn_1_in = [[[int(conv2d_1_out[i][j][k]) if int(conv2d_1_out[i][j][k]) < p//2 else int(conv2d_1_out[i][j][k]) - p for k in range(4)] for j in range(26)] for i in range(26)]\\n\",\n    \"bn_1_a = [int(a1[i]*1e18) for i in range(4)]\\n\",\n    \"bn_1_b = [int(b1[i]*1e36) for i in range(4)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['973005189421817592',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343698152437199136300055',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343698128968107786241045',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697645307409523760974']\"\n      ]\n     },\n     \"execution_count\": 20,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, bn_1_a, bn_1_b, bn_1_out, bn_1_remainder = BatchNormalizationInt(26, 26, 4, 10**18, bn_1_in, bn_1_a, bn_1_b)\\n\",\n    \"bn_1_out[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 22ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.97300524, -0.05174941, -0.07521845, -0.55887914], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 21,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"bn_1_model = Model(inputs, model.layers[2].output)\\n\",\n    \"bn_1_model.predict(X.reshape(1,28,28,1))[0][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"relu_1_in = [[[int(bn_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]\\n\",\n    \"relu_1_out = [[[str(relu_1_in[i][j][k]) if relu_1_in[i][j][k] < p//2 else 0 for k in range(4)] for j in range(26)] for i in range(26)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"avg2d_1_in = [[[int(relu_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\\n\",\n    \"    Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"    out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\\n\",\n    \"    remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\\n\",\n    \"    for i in range((nRows-poolSize)//strides + 1):\\n\",\n    \"        for j in range((nCols-poolSize)//strides + 1):\\n\",\n    \"            for k in range(nChannels):\\n\",\n    \"                for x in range(poolSize):\\n\",\n    \"                    for y in range(poolSize):\\n\",\n    \"                        out[i][j][k] += input[i*strides+x][j*strides+y][k]\\n\",\n    \"                remainder[i][j][k] = str(out[i][j][k] % poolSize**2 % p)\\n\",\n    \"                out[i][j][k] = str(out[i][j][k] // poolSize**2 % p)\\n\",\n    \"    return Input, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 25,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['1312195747641412224', '17351024717876988', '381448215010339593', '0']\"\n      ]\n     },\n     \"execution_count\": 25,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, avg2d_1_out, avg2d_1_remainder = AveragePooling2DInt(26, 26, 4, 2, 2, avg2d_1_in)\\n\",\n    \"avg2d_1_out[5][6]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 26,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 28ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([1.3121958 , 0.01735102, 0.38144833, 0.        ], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 26,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"avg2d_1_model = Model(inputs, model.layers[4].output)\\n\",\n    \"avg2d_1_model.predict(X.reshape(1,28,28,1))[0][5][6]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 27,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"conv2d_2_in = [[[int(avg2d_1_out[i][j][k]) for k in range(4)] for j in range(13)] for i in range(13)]\\n\",\n    \"conv2d_2_weights = [[[[int(model.layers[5].weights[0][i][j][k][l]*1e18) for l in range(8)] for k in range(4)] for j in range(3)] for i in range(3)]\\n\",\n    \"conv2d_2_bias = [int(model.layers[5].weights[1][i]*1e36) for i in range(8)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 28,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['151443532606342120',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343695445103896159586204',\\n\",\n       \" '1368543458414900467',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697889320797389307844',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343696909822999783625702',\\n\",\n       \" '3064925807006993607',\\n\",\n       \" '273553711551724155',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697690313879935243528']\"\n      ]\n     },\n     \"execution_count\": 28,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, conv2d_2_weights, conv2d_2_bias, conv2d_2_out, conv2d_2_remainder = Conv2DInt(13, 13, 4, 8, 3, 1, 10**18, conv2d_2_in, conv2d_2_weights, conv2d_2_bias)\\n\",\n    \"conv2d_2_out[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 29,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x147387d30> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\\n\",\n      \"1/1 [==============================] - 0s 27ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.15144362, -2.7590828 ,  1.3685436 , -0.3148657 , -1.2943636 ,\\n\",\n       \"        3.064926  ,  0.27355385, -0.5138727 ], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 29,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"conv2d_2_model = Model(inputs, model.layers[5].output)\\n\",\n    \"conv2d_2_model.predict(X.reshape(1,28,28,1))[0][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 30,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"gamma = model.layers[6].weights[0].numpy()\\n\",\n    \"beta = model.layers[6].weights[1].numpy()\\n\",\n    \"moving_mean = model.layers[6].weights[2].numpy()\\n\",\n    \"moving_var = model.layers[6].weights[3].numpy()\\n\",\n    \"epsilon = model.layers[6].epsilon\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 31,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(array([1.4172864, 1.0896717, 1.2455306, 1.9744203, 1.5216775, 1.6048892,\\n\",\n       \"        1.5560555, 1.5188278], dtype=float32),\\n\",\n       \" array([ 0.9693597 ,  2.5460322 , -2.3216164 ,  1.1771976 ,  1.7650728 ,\\n\",\n       \"        -5.5845942 , -0.36191303,  0.58835894], dtype=float32))\"\n      ]\n     },\n     \"execution_count\": 31,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"a2 = gamma/(moving_var+epsilon)**.5\\n\",\n    \"b2 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\\n\",\n    \"a2, b2\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 32,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"bn_2_in = [[[int(conv2d_2_out[i][j][k]) if int(conv2d_2_out[i][j][k]) < p//2 else int(conv2d_2_out[i][j][k]) - p for k in range(8)] for j in range(11)] for i in range(11)]\\n\",\n    \"bn_2_a = [int(a2[i]*1e18) for i in range(8)]\\n\",\n    \"bn_2_b = [int(b2[i]*1e36) for i in range(8)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 33,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['1183998554440588778',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697743724366639529790',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697587132926760373824',\\n\",\n       \" '555520188028190246',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697999655475625376512',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697538458512894177905',\\n\",\n       \" '63751744556936369',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343698012061380413810399']\"\n      ]\n     },\n     \"execution_count\": 33,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, bn_2_a, bn_2_b, bn_2_out, bn_2_remainder = BatchNormalizationInt(11, 11, 8, 10**18, bn_2_in, bn_2_a, bn_2_b)\\n\",\n    \"bn_2_out[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 34,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x1475103a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\\n\",\n      \"1/1 [==============================] - 0s 32ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 1.1839986 , -0.46046233, -0.61705345,  0.5555204 , -0.20453101,\\n\",\n       \"       -0.66572803,  0.06375193, -0.1921252 ], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 34,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"bn_2_model = Model(inputs, model.layers[6].output)\\n\",\n    \"bn_2_model.predict(X.reshape(1,28,28,1))[0][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 35,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['1183998554440588778',\\n\",\n       \" 0,\\n\",\n       \" 0,\\n\",\n       \" '555520188028190246',\\n\",\n       \" 0,\\n\",\n       \" 0,\\n\",\n       \" '63751744556936369',\\n\",\n       \" 0]\"\n      ]\n     },\n     \"execution_count\": 35,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"relu_2_in = [[[int(bn_2_out[i][j][k]) for k in range(8)] for j in range(11)] for i in range(11)]\\n\",\n    \"relu_2_out = [[[str(relu_2_in[i][j][k]) if relu_2_in[i][j][k] < p//2 else 0 for k in range(8)] for j in range(11)] for i in range(11)]\\n\",\n    \"relu_2_out[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 36,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 30ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([1.1839986 , 0.        , 0.        , 0.5555204 , 0.        ,\\n\",\n       \"       0.        , 0.06375193, 0.        ], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 36,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"relu_2_model = Model(inputs, model.layers[7].output)\\n\",\n    \"relu_2_model.predict(X.reshape(1,28,28,1))[0][0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 37,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"avg2d_2_in = [[[int(relu_2_out[i][j][k]) if int(relu_2_out[i][j][k]) < p//2 else int(relu_2_out[i][j][k]) - p for k in range(8)] for j in range(11)] for i in range(11)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 38,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['0',\\n\",\n       \" '3041275199357812815',\\n\",\n       \" '880404200542187368',\\n\",\n       \" '751626574290071696',\\n\",\n       \" '4631629684299696339',\\n\",\n       \" '0',\\n\",\n       \" '0',\\n\",\n       \" '141002623674408652']\"\n      ]\n     },\n     \"execution_count\": 38,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, avg2d_2_out, avg2d_2_remainder = AveragePooling2DInt(11, 11, 8, 2, 2, avg2d_2_in)\\n\",\n    \"avg2d_2_out[3][3]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 39,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 30ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([0.        , 3.0412755 , 0.88040376, 0.7516271 , 4.6316295 ,\\n\",\n       \"       0.        , 0.        , 0.14100271], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 39,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"avg2d_2_model = Model(inputs, model.layers[8].output)\\n\",\n    \"avg2d_2_model.predict(X.reshape(1,28,28,1))[0][3][3]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 40,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['240465720017978049',\\n\",\n       \" '312962931075997403',\\n\",\n       \" '16422062895818568',\\n\",\n       \" '0',\\n\",\n       \" '0',\\n\",\n       \" '1115397662044723147',\\n\",\n       \" '3743826354975568930',\\n\",\n       \" '1282135426254877774',\\n\",\n       \" '2558492900397241085',\\n\",\n       \" '0',\\n\",\n       \" '69224497325539673',\\n\",\n       \" '0',\\n\",\n       \" '60798814494206494',\\n\",\n       \" '2302583886918782205',\\n\",\n       \" '379552091654971946',\\n\",\n       \" '0',\\n\",\n       \" '1609754191355983350',\\n\",\n       \" '0',\\n\",\n       \" '27599924897036794',\\n\",\n       \" '30247813336316648']\"\n      ]\n     },\n     \"execution_count\": 40,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"flatten_out = [avg2d_2_out[i][j][k] for i in range(5) for j in range(5) for k in range(8)]\\n\",\n    \"flatten_out[100:120]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 41,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 32ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([0.24046564, 0.312963  , 0.0164221 , 0.        , 0.        ,\\n\",\n       \"       1.1153977 , 3.7438262 , 1.2821352 , 2.5584927 , 0.        ,\\n\",\n       \"       0.0692246 , 0.        , 0.06079884, 2.3025842 , 0.37955213,\\n\",\n       \"       0.        , 1.6097541 , 0.        , 0.02759986, 0.03024786],\\n\",\n       \"      dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 41,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"flatten_model = Model(inputs, model.layers[9].output)\\n\",\n    \"flatten_model.predict(X.reshape(1,28,28,1))[0][100:120]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 42,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"dense_in = [int(flatten_out[i]) if int(flatten_out[i]) < p//2 else int(flatten_out[i]) - p for i in range(200)]\\n\",\n    \"dense_weights = [[int(model.layers[10].weights[0][i][j]*1e18) for j in range(10)] for i in range(200)]\\n\",\n    \"dense_bias = [int(model.layers[10].weights[1][i]*1e36) for i in range(10)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 43,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\\n\",\n    \"    Input = [str(input[i] % p) for i in range(nInputs)]\\n\",\n    \"    Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nOutputs)]\\n\",\n    \"    out = [0 for _ in range(nOutputs)]\\n\",\n    \"    remainder = [None for _ in range(nOutputs)]\\n\",\n    \"    for j in range(nOutputs):\\n\",\n    \"        for i in range(nInputs):\\n\",\n    \"            out[j] += input[i] * weights[i][j]\\n\",\n    \"        out[j] += bias[j]\\n\",\n    \"        remainder[j] = str(out[j] % n)\\n\",\n    \"        out[j] = str(out[j] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 44,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['21888242871839275222246405745257275088548364400416034343696001558406187208579',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343694494011253998843463',\\n\",\n       \" '2502586410316628302',\\n\",\n       \" '7723360444146681933',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343688179933383346961393',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697101907583287035462',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343680804147065276585857',\\n\",\n       \" '21047995401855287971',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343695951614145619839501',\\n\",\n       \" '4230622081176419220']\"\n      ]\n     },\n     \"execution_count\": 44,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, dense_weights, dense_bias, dense_out, dense_remainder = DenseInt(200, 10, 10**18, dense_in, dense_weights, dense_bias)\\n\",\n    \"dense_out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 45,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['21888242871839275222246405745257275088548364400416034343696001558406187208579',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343694494011253998843463',\\n\",\n       \" '2502586410316628302',\\n\",\n       \" '7723360444146681933',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343688179933383346961393',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343697101907583287035462',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343680804147065276585857',\\n\",\n       \" '21047995401855287971',\\n\",\n       \" '21888242871839275222246405745257275088548364400416034343695951614145619839501',\\n\",\n       \" '4230622081176419220']\"\n      ]\n     },\n     \"execution_count\": 45,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"dense_out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 46,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 35ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ -2.2026286,  -3.7101758,   2.5025864,   7.7233634, -10.024254 ,\\n\",\n       \"        -1.1022782, -17.40004  ,  21.047997 ,  -2.2525737,   4.230623 ],\\n\",\n       \"      dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 46,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"dense_model = Model(inputs, model.layers[-2].output)\\n\",\n    \"dense_model.predict(X.reshape(1,28,28,1))[0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 47,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"conv2d_1_weights\\\": conv2d_1_weights,\\n\",\n    \"    \\\"conv2d_1_bias\\\": conv2d_1_bias,\\n\",\n    \"    \\\"conv2d_1_out\\\": conv2d_1_out,\\n\",\n    \"    \\\"conv2d_1_remainder\\\": conv2d_1_remainder,\\n\",\n    \"    \\\"bn_1_a\\\": bn_1_a,\\n\",\n    \"    \\\"bn_1_b\\\": bn_1_b,\\n\",\n    \"    \\\"bn_1_out\\\": bn_1_out,\\n\",\n    \"    \\\"bn_1_remainder\\\": bn_1_remainder,\\n\",\n    \"    \\\"relu_1_out\\\": relu_1_out,\\n\",\n    \"    \\\"avg2d_1_out\\\": avg2d_1_out,\\n\",\n    \"    \\\"avg2d_1_remainder\\\": avg2d_1_remainder,\\n\",\n    \"    \\\"conv2d_2_weights\\\": conv2d_2_weights,\\n\",\n    \"    \\\"conv2d_2_bias\\\": conv2d_2_bias,\\n\",\n    \"    \\\"conv2d_2_out\\\": conv2d_2_out,\\n\",\n    \"    \\\"conv2d_2_remainder\\\": conv2d_2_remainder,\\n\",\n    \"    \\\"bn_2_a\\\": bn_2_a,\\n\",\n    \"    \\\"bn_2_b\\\": bn_2_b,\\n\",\n    \"    \\\"bn_2_out\\\": bn_2_out,\\n\",\n    \"    \\\"bn_2_remainder\\\": bn_2_remainder,\\n\",\n    \"    \\\"relu_2_out\\\": relu_2_out,\\n\",\n    \"    \\\"avg2d_2_out\\\": avg2d_2_out,\\n\",\n    \"    \\\"avg2d_2_remainder\\\": avg2d_2_remainder,\\n\",\n    \"    \\\"flatten_out\\\": flatten_out,\\n\",\n    \"    \\\"dense_weights\\\": dense_weights,\\n\",\n    \"    \\\"dense_bias\\\": dense_bias,\\n\",\n    \"    \\\"dense_out\\\": dense_out,\\n\",\n    \"    \\\"dense_remainder\\\": dense_remainder,\\n\",\n    \"    \\\"argmax_out\\\": \\\"7\\\"\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 48,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 49,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"mnist_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"interpreter\": {\n   \"hash\": \"11280bdb37aa6bc5d4cf1e4de756386eb1f9eecd8dcdefa77636dfac7be2370d\"\n  },\n  \"kernelspec\": {\n   \"display_name\": \"Python 3.8.6 ('tf24')\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/model1.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Dense\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(3,))\\n\",\n    \"x = Dense(2, activation='relu')(inputs)\\n\",\n    \"outputs = Dense(1)(x)\\n\",\n    \"model = Model(inputs, outputs)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 3)]               0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 2)                 8         \\n\",\n      \"                                                                 \\n\",\n      \" dense_1 (Dense)             (None, 1)                 3         \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 11\\n\",\n      \"Trainable params: 11\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[<tf.Variable 'dense/kernel:0' shape=(3, 2) dtype=float32, numpy=\\n\",\n       \" array([[-0.72784126,  0.33670223],\\n\",\n       \"        [-0.7780691 ,  0.62421453],\\n\",\n       \"        [-1.0269804 ,  0.49905217]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'dense/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>,\\n\",\n       \" <tf.Variable 'dense_1/kernel:0' shape=(2, 1) dtype=float32, numpy=\\n\",\n       \" array([[-0.00755942],\\n\",\n       \"        [ 0.58352613]], dtype=float32)>,\\n\",\n       \" <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.weights\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.5545958 , 0.48267873, 0.46073158]])\"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 36ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-10-24 01:16:53.952999: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.41894716]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [int(x*1e36) for x in X[0]]\\n\",\n    \"Dense32weights = [[int(model.weights[0].numpy()[i][j]*1e36) for j in range(2)] for i in range(3)]\\n\",\n    \"Dense32bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\\n\",\n    \"Dense21weights = [[int(model.weights[2].numpy()[i][j]*1e36) for j in range(1)] for i in range(2)]\\n\",\n    \"Dense21bias = [int(model.weights[3].numpy()[i]*1e72) for i in range(1)]\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\\n\",\n    \"    Input = [str(input[i] % p) for i in range(nInputs)]\\n\",\n    \"    Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\\n\",\n    \"    Bias = [str(bias[i] % p) for i in range(nOutputs)]\\n\",\n    \"    out = [0 for _ in range(nOutputs)]\\n\",\n    \"    remainder = [None for _ in range(nOutputs)]\\n\",\n    \"    for j in range(nOutputs):\\n\",\n    \"        for i in range(nInputs):\\n\",\n    \"            out[j] += input[i] * weights[i][j]\\n\",\n    \"        out[j] += bias[j]\\n\",\n    \"        remainder[j] = str(out[j] % n)\\n\",\n    \"        out[j] = str(out[j] // n % p)\\n\",\n    \"    return Input, Weights, Bias, out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(['21888242871839275222246405745257275088547112023011337864689255117657466434208',\\n\",\n       \"  '717957812208694328223024234032338630'],\\n\",\n       \" ['749712352190261448543726154832412672',\\n\",\n       \"  '264894409627262887048751218981601280'])\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X_in, Dense32weights, Dense32bias, Dense32out, Dense32remainder = DenseInt(3, 2, 10**36, X_in, Dense32weights, Dense32bias)\\n\",\n    \"Dense32out, Dense32remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ReLUout = [Dense32out[i] if int(Dense32out[i]) < p//2 else 0 for i in range(2)]\\n\",\n    \"Dense21in = [int(ReLUout[i]) for i in range(2)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"(['418947146885730875576316926961913803'],\\n\",\n       \" ['695849152206718637828300508516843520'])\"\n      ]\n     },\n     \"execution_count\": 12,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"_, Dense21weights, Dense21bias, Dense21out, Dense21remainder = DenseInt(2, 1, 10**36, Dense21in, Dense21weights, Dense21bias)\\n\",\n    \"Dense21out, Dense21remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"Dense32weights\\\": Dense32weights,\\n\",\n    \"    \\\"Dense32bias\\\": Dense32bias,\\n\",\n    \"    \\\"Dense32out\\\": Dense32out,\\n\",\n    \"    \\\"Dense32remainder\\\": Dense32remainder,\\n\",\n    \"    \\\"ReLUout\\\": ReLUout,\\n\",\n    \"    \\\"Dense21weights\\\": Dense21weights,\\n\",\n    \"    \\\"Dense21bias\\\": Dense21bias,\\n\",\n    \"    \\\"Dense21out\\\": Dense21out,\\n\",\n    \"    \\\"Dense21remainder\\\": Dense21remainder\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"model1_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/pointwiseConv2D.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"2b70084b-44da-4142-9e24-c9c8231828db\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import torch\\n\",\n    \"import torch.nn as nn\\n\",\n    \"import torch.nn.functional as F\\n\",\n    \"import numpy as np\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"e7533193-266d-4a59-b9aa-54179d40aa41\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\\n\",\n    \"EXPONENT = 15\\n\",\n    \"\\n\",\n    \"class SeparableConv2D(nn.Module):\\n\",\n    \"    '''Separable convolution'''\\n\",\n    \"    def __init__(self, in_channels, out_channels, stride=1):\\n\",\n    \"        super(SeparableConv2D, self).__init__()\\n\",\n    \"        self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\\n\",\n    \"        self.pw_conv =  nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\\n\",\n    \"\\n\",\n    \"    def forward(self, x):\\n\",\n    \"        x = self.dw_conv(x)\\n\",\n    \"        x = self.pw_conv(x)\\n\",\n    \"        return x\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"4dec98ed-cd14-442b-93b5-8f3660726773\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"input = torch.randn((1, 3, 5, 5))\\n\",\n    \"model = SeparableConv2D(3, 6)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"92b62f7c-5ac1-4c69-9add-9a859d66c327\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\\n\",\n    \"    kernelSize = 1\\n\",\n    \"    outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"    outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    for row in range(outRows):\\n\",\n    \"        for col in range(outCols):\\n\",\n    \"            for filter in range(nFilters):\\n\",\n    \"                for k in range(nChannels):\\n\",\n    \"                    out[row][col][filter] += int(input[row*strides, col*strides, k]) * int(weights[k, filter])\\n\",\n    \"                    \\n\",\n    \"                out[row][col][filter] += int(bias[filter])\\n\",\n    \"                remainder[row][col][filter] = str(int(out[row][col][filter] % n))\\n\",\n    \"                out[row][col][filter] = int(out[row][col][filter] // n)\\n\",\n    \"                str_out[row][col][filter] = str(out[row][col][filter] % p)\\n\",\n    \"                            \\n\",\n    \"    return out, str_out, remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"id\": \"0c664ba3-b722-482b-84f4-f83bab1d1bdb\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"quantized_image.shape=(5, 5, 3)\\n\",\n      \"quantized_weights.shape=(3, 6)\\n\",\n      \"expected.shape=(1, 6, 5, 5)\\n\",\n      \"expected.shape=(5, 5, 6)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"weights = model.pw_conv.weight.detach().numpy()\\n\",\n    \"bias = torch.zeros(weights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"expected = model.pw_conv(input).detach().numpy()\\n\",\n    \"\\n\",\n    \"weights = weights.transpose((2, 3, 1, 0)).squeeze()\\n\",\n    \"\\n\",\n    \"quantized_image = input.squeeze().numpy().transpose((1, 2, 0)) * 10**EXPONENT\\n\",\n    \"quantized_weights = weights * 10**EXPONENT\\n\",\n    \"print(f\\\"{quantized_image.shape=}\\\")\\n\",\n    \"print(f\\\"{quantized_weights.shape=}\\\")\\n\",\n    \"\\n\",\n    \"actual, str_actual, remainder = PointwiseConv2d(5, 5, 3, 6, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\\n\",\n    \"\\n\",\n    \"actual_scaled = [[[actual[i][j][k] / 10**EXPONENT for k in range(6)] for j in range(5)] for i in range(5)]\\n\",\n    \"\\n\",\n    \"expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"assert(np.allclose(expected, actual_scaled, atol=0.00001))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"id\": \"8b595d39-ca92-4c45-b04e-e7eb85b4c843\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_weights = quantized_weights.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_bias = bias.round().astype(int).astype(str).tolist()\\n\",\n    \"\\n\",\n    \"input_json_path = \\\"pointwiseConv2D_input.json\\\"\\n\",\n    \"with open(input_json_path, \\\"w\\\") as input_file:\\n\",\n    \"    json.dump({\\\"in\\\": circuit_in,\\n\",\n    \"               \\\"weights\\\": circuit_weights,\\n\",\n    \"               \\\"remainder\\\": remainder,\\n\",\n    \"               \\\"out\\\": str_actual,\\n\",\n    \"               \\\"bias\\\": circuit_bias,\\n\",\n    \"              },\\n\",\n    \"              input_file)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cd6f84d3-4d70-421c-9067-5ed314c967a8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/remez.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from mpmath import mp\\n\",\n    \"import numpy as np\\n\",\n    \"\\n\",\n    \"# from https://github.com/DKenefake/OptimalPoly\\n\",\n    \"\\n\",\n    \"def bisection_search(f, low:float, high:float):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    A root finding method that does not rely on derivatives\\n\",\n    \"\\n\",\n    \"    :param f: a function f: X -> R\\n\",\n    \"    :param low: the lower bracket\\n\",\n    \"    :param high: the upper limit bracket\\n\",\n    \"    :return: the location of the root, e.g. f(mid) ~ 0\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    # flip high and low if out of order\\n\",\n    \"    if f(high) < f(low):\\n\",\n    \"        low, high = high, low\\n\",\n    \"\\n\",\n    \"    # find mid point\\n\",\n    \"    mid = .5 * (low + high)\\n\",\n    \"\\n\",\n    \"    while True:\\n\",\n    \"\\n\",\n    \"        # bracket up\\n\",\n    \"        if f(mid) < 0:\\n\",\n    \"            low = mid\\n\",\n    \"        # braket down\\n\",\n    \"        else:\\n\",\n    \"            high = mid\\n\",\n    \"\\n\",\n    \"        # update mid point\\n\",\n    \"        mid = .5 * (high + low)\\n\",\n    \"\\n\",\n    \"        # break if condition met\\n\",\n    \"        if abs(high - low) < 10 ** (-(mp.dps / 2)):\\n\",\n    \"            break\\n\",\n    \"\\n\",\n    \"    return mid\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def concave_max(f, low:float, high:float):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Forms a lambda for the approximate derivative and finds the root\\n\",\n    \"\\n\",\n    \"    :param f: a function f: X -> R\\n\",\n    \"    :param low: the lower bracket\\n\",\n    \"    :param high: the upper limit bracket\\n\",\n    \"    :return: the location of the root f'(mid) ~ 0\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    # create an approximate derivative expression\\n\",\n    \"    scale = high - low\\n\",\n    \"\\n\",\n    \"    h = mp.mpf('0.' + ''.join(['0' for i in range(int(mp.dps / 1.5))]) + '1') * scale\\n\",\n    \"    df = lambda x: (f(x + h) - f(x - h)) / (2.0 * h)\\n\",\n    \"\\n\",\n    \"    return bisection_search(df, low, high)\\n\",\n    \"\\n\",\n    \"def chev_points(n:int, lower:float = -1, upper:float = 1):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Generates a set of chebychev points spaced in the range [lower, upper]\\n\",\n    \"    :param n: number of points\\n\",\n    \"    :param lower: lower limit\\n\",\n    \"    :param upper: upper limit\\n\",\n    \"    :return: a list of multipressison chebychev points that are in the range [lower, upper]\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    #generate chebeshev points on a range [-1, 1]\\n\",\n    \"    index = np.arange(1, n+1)\\n\",\n    \"    range_ = abs(upper - lower)\\n\",\n    \"    return [(.5*(mp.cos((2*i-1)/(2*n)*mp.pi)+1))*range_ + lower for i in index]\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def remez(func, n_degree:int, lower:float=-1, upper:float=1, max_iter:int = 10):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    :param func: a function (or lambda) f: X -> R\\n\",\n    \"    :param n_degree: the degree of the polynomial to approximate the function f\\n\",\n    \"    :param lower: lower range of the approximation\\n\",\n    \"    :param upper: upper range of the approximation\\n\",\n    \"    :return: the polynomial coefficients, and an approximate maximum error associated with this approximation\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    # initialize the node points\\n\",\n    \"\\n\",\n    \"    x_points = chev_points(n_degree + 2, lower, upper)\\n\",\n    \"\\n\",\n    \"    A = mp.matrix(n_degree + 2)\\n\",\n    \"    coeffs = np.zeros(n_degree + 2)\\n\",\n    \"\\n\",\n    \"    # place in the E column\\n\",\n    \"    mean_error = float('inf')\\n\",\n    \"\\n\",\n    \"    for i in range(n_degree + 2):\\n\",\n    \"        A[i, n_degree + 1] = (-1) ** (i + 1)\\n\",\n    \"\\n\",\n    \"    for i in range(max_iter):\\n\",\n    \"\\n\",\n    \"        # build the system\\n\",\n    \"        vander = np.polynomial.chebyshev.chebvander(x_points, n_degree)\\n\",\n    \"\\n\",\n    \"        for i in range(n_degree + 2):\\n\",\n    \"            for j in range(n_degree + 1):\\n\",\n    \"                A[i, j] = vander[i, j]\\n\",\n    \"\\n\",\n    \"        b = mp.matrix([func(x) for x in x_points])\\n\",\n    \"        l = mp.lu_solve(A, b)\\n\",\n    \"\\n\",\n    \"        coeffs = l[:-1]\\n\",\n    \"\\n\",\n    \"        # build the residual expression\\n\",\n    \"        r_i = lambda x: (func(x) - np.polynomial.chebyshev.chebval(x, coeffs))\\n\",\n    \"\\n\",\n    \"        interval_list = list(zip(x_points, x_points[1:]))\\n\",\n    \"        #         interval_list = [[x_points[i], x_points[i+1]] for i in range(len(x_points)-1)]\\n\",\n    \"\\n\",\n    \"        intervals = [upper]\\n\",\n    \"        intervals.extend([bisection_search(r_i, *i) for i in interval_list])\\n\",\n    \"        intervals.append(lower)\\n\",\n    \"\\n\",\n    \"        extermum_interval = [[intervals[i], intervals[i + 1]] for i in range(len(intervals) - 1)]\\n\",\n    \"\\n\",\n    \"        extremums = [concave_max(r_i, *i) for i in extermum_interval]\\n\",\n    \"\\n\",\n    \"        extremums[0] = mp.mpf(upper)\\n\",\n    \"        extremums[-1] = mp.mpf(lower)\\n\",\n    \"\\n\",\n    \"        errors = [abs(r_i(i)) for i in extremums]\\n\",\n    \"        mean_error = np.mean(errors)\\n\",\n    \"\\n\",\n    \"        if np.max([abs(error - mean_error) for error in errors]) < 0.000001 * mean_error:\\n\",\n    \"            break\\n\",\n    \"\\n\",\n    \"        x_points = extremums\\n\",\n    \"\\n\",\n    \"    return [float(i) for i in np.polynomial.chebyshev.cheb2poly(coeffs)], float(mean_error)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['0.502073021', '0.198695283', '-0.001570683', '-0.004001354']\"\n      ]\n     },\n     \"execution_count\": 2,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"function = lambda x: mp.sigmoid(x)\\n\",\n    \"poly_coeffs, max_error = remez(function, 3, -5, 5)\\n\",\n    \"[np.format_float_positional(c, precision=9) for c in poly_coeffs]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"['0.006769816', '0.554670504', '-0.009411195', '-0.014187547']\"\n      ]\n     },\n     \"execution_count\": 3,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"function = lambda x: mp.tanh(x)\\n\",\n    \"poly_coeffs, max_error = remez(function, 3, -5, 5)\\n\",\n    \"[np.format_float_positional(c, precision=9) for c in poly_coeffs]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"sklearn\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/reshape2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, Reshape\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(75,))\\n\",\n    \"x = Reshape((5, 5, 3))(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 75)]              0         \\n\",\n      \"                                                                 \\n\",\n      \" reshape (Reshape)           (None, 5, 5, 3)           0         \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[0.72327659, 0.97464849, 0.2592479 , 0.63799774, 0.89013732,\\n\",\n       \"        0.95867971, 0.06431743, 0.55685192, 0.77031965, 0.09982323,\\n\",\n       \"        0.10704737, 0.40713332, 0.57294341, 0.21883552, 0.22967276,\\n\",\n       \"        0.6221842 , 0.64159904, 0.684413  , 0.59126341, 0.88438877,\\n\",\n       \"        0.56715972, 0.93006015, 0.85704814, 0.79864291, 0.39604054,\\n\",\n       \"        0.30495253, 0.38333952, 0.69453548, 0.59207958, 0.30889659,\\n\",\n       \"        0.17302571, 0.41351124, 0.37527957, 0.43118255, 0.31526054,\\n\",\n       \"        0.12925303, 0.30129156, 0.73921834, 0.98336451, 0.03352392,\\n\",\n       \"        0.27839826, 0.6811155 , 0.96320785, 0.16882282, 0.68572833,\\n\",\n       \"        0.20924115, 0.30604142, 0.09080768, 0.63244108, 0.55914947,\\n\",\n       \"        0.60870048, 0.49377892, 0.9710362 , 0.12959508, 0.62162852,\\n\",\n       \"        0.26827067, 0.84771621, 0.40895646, 0.52476578, 0.48532215,\\n\",\n       \"        0.27144489, 0.19194784, 0.85410267, 0.11912042, 0.37034274,\\n\",\n       \"        0.25759208, 0.88306728, 0.98917787, 0.61814043, 0.49141046,\\n\",\n       \"        0.74162286, 0.81722887, 0.4728493 , 0.19955073, 0.42201694]])\"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,75)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 44ms/step\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2024-02-04 00:14:24.910151: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.7232766 , 0.9746485 , 0.2592479 ],\\n\",\n       \"         [0.63799775, 0.8901373 , 0.9586797 ],\\n\",\n       \"         [0.06431743, 0.5568519 , 0.77031964],\\n\",\n       \"         [0.09982323, 0.10704737, 0.4071333 ],\\n\",\n       \"         [0.5729434 , 0.21883552, 0.22967276]],\\n\",\n       \"\\n\",\n       \"        [[0.6221842 , 0.64159906, 0.684413  ],\\n\",\n       \"         [0.5912634 , 0.88438874, 0.5671597 ],\\n\",\n       \"         [0.93006015, 0.85704815, 0.79864293],\\n\",\n       \"         [0.39604053, 0.30495253, 0.38333952],\\n\",\n       \"         [0.6945355 , 0.5920796 , 0.3088966 ]],\\n\",\n       \"\\n\",\n       \"        [[0.17302571, 0.41351125, 0.37527958],\\n\",\n       \"         [0.43118253, 0.31526053, 0.12925303],\\n\",\n       \"         [0.30129156, 0.73921835, 0.9833645 ],\\n\",\n       \"         [0.03352392, 0.27839825, 0.6811155 ],\\n\",\n       \"         [0.96320784, 0.16882282, 0.6857283 ]],\\n\",\n       \"\\n\",\n       \"        [[0.20924115, 0.30604142, 0.09080768],\\n\",\n       \"         [0.6324411 , 0.55914944, 0.60870045],\\n\",\n       \"         [0.4937789 , 0.9710362 , 0.12959507],\\n\",\n       \"         [0.6216285 , 0.26827067, 0.8477162 ],\\n\",\n       \"         [0.40895647, 0.5247658 , 0.48532215]],\\n\",\n       \"\\n\",\n       \"        [[0.2714449 , 0.19194785, 0.8541027 ],\\n\",\n       \"         [0.11912042, 0.37034273, 0.25759208],\\n\",\n       \"         [0.8830673 , 0.9891779 , 0.6181404 ],\\n\",\n       \"         [0.49141046, 0.74162287, 0.81722885],\\n\",\n       \"         [0.4728493 , 0.19955073, 0.42201695]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": (X*1e36).round().astype(int).flatten().tolist(),\\n\",\n    \"    \\\"out\\\": (X*1e36).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"reshape2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/separableConv2D.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"aa5be75a-ee5f-45b0-891b-da2dd340dd00\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import torch\\n\",\n    \"import torch.nn as nn\\n\",\n    \"import torch.nn.functional as F\\n\",\n    \"import numpy as np\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"f85ed78d-97ef-4979-acac-8d95b34a84ae\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\\n\",\n    \"CIRCOM_PRIME = 21888242871839275222246405745257275088548364400416034343698204186575808495617\\n\",\n    \"MAX_POSITIVE = CIRCOM_PRIME // 2\\n\",\n    \"MAX_NEGATIVE = MAX_POSITIVE + 1 # The most positive number\\n\",\n    \"CIRCOM_NEGATIVE_1 = 21888242871839275222246405745257275088548364400416034343698204186575808495617 - 1\\n\",\n    \"EXPONENT = 15\\n\",\n    \"\\n\",\n    \"class SeparableConv2D(nn.Module):\\n\",\n    \"    '''Separable convolution'''\\n\",\n    \"    def __init__(self, in_channels, out_channels, stride=1):\\n\",\n    \"        super(SeparableConv2D, self).__init__()\\n\",\n    \"        self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\\n\",\n    \"        self.pw_conv =  nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\\n\",\n    \"\\n\",\n    \"    def forward(self, x):\\n\",\n    \"        x = self.dw_conv(x)\\n\",\n    \"        x = self.pw_conv(x)\\n\",\n    \"        return x\\n\",\n    \"\\n\",\n    \"def from_circom(x):\\n\",\n    \"    if type(x) != int:\\n\",\n    \"        x = int(x)\\n\",\n    \"    if x > MAX_POSITIVE: \\n\",\n    \"        return x - CIRCOM_PRIME\\n\",\n    \"    return x\\n\",\n    \"    \\n\",\n    \"def to_circom(x):\\n\",\n    \"    if type(x) != int:\\n\",\n    \"        x = int(x)\\n\",\n    \"    if x < 0:\\n\",\n    \"        return x + CIRCOM_PRIME \\n\",\n    \"    return x\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"32e117a1-32aa-4b4b-91d0-4b4b78071b6b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"#     assert(nFilters % nChannels == 0)\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    \\n\",\n    \"#     out = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"#     remainder = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"    \\n\",\n    \"#     for row in range(outRows):\\n\",\n    \"#         for col in range(outCols):\\n\",\n    \"#             for channel in range(nChannels):\\n\",\n    \"#                 for x in range(kernelSize):\\n\",\n    \"#                     for y in range(kernelSize):\\n\",\n    \"#                         out[row, col, channel] += input[row*strides+x, col*strides+y, channel] * weights[x, y, channel]\\n\",\n    \"                \\n\",\n    \"#                 out[row][col][channel] += bias[channel]\\n\",\n    \"#                 remainder[row][col][channel] = out[row][col][channel] % n\\n\",\n    \"#                 out[row][col][channel] = out[row][col][channel] / n\\n\",\n    \"                            \\n\",\n    \"#     return out, remainder\\n\",\n    \"    \\n\",\n    \"# def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\\n\",\n    \"#     kernelSize = 1\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"#     out = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"#     for row in range(outRows):\\n\",\n    \"#         for col in range(outCols):\\n\",\n    \"#             for filter in range(nFilters):\\n\",\n    \"#                 for k in range(nChannels):\\n\",\n    \"#                     out[row, col, filter] += input[row*strides, col*strides, k] * weights[k, filter]\\n\",\n    \"                    \\n\",\n    \"#                 out[row][col][filter] += bias[filter]\\n\",\n    \"#                 out[row][col][filter] = out[row][col][filter] / n\\n\",\n    \"                            \\n\",\n    \"#     return out\\n\",\n    \"\\n\",\n    \"# def SeparableConvImpl(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"\\n\",\n    \"#     depthOut, rem = DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\\n\",\n    \"#     pointOut = PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, depthOut, pointWeights, pointBias)\\n\",\n    \"#     return pointOut\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"id\": \"e3dfadfd-2587-4708-9dd5-535a999ed359\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# def DepthwiseConvInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"#     assert(nFilters % nChannels == 0)\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    \\n\",\n    \"#     Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"#     Weights = [[[str(weights[i][j][k] % p) for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\\n\",\n    \"#     Bias = [str(bias[i] % p) for i in range(nFilters)]\\n\",\n    \"#     out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"#     str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"#     remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    \\n\",\n    \"#     for row in range(outRows):\\n\",\n    \"#         for col in range(outCols):\\n\",\n    \"#             for channel in range(nChannels):\\n\",\n    \"#                 for x in range(kernelSize):\\n\",\n    \"#                     for y in range(kernelSize):\\n\",\n    \"#                         out[row][col][channel] += int(input[row*strides+x][col*strides+y][channel]) * int(weights[x][y][channel])\\n\",\n    \"                        \\n\",\n    \"#                 out[row][col][channel] += int(bias[channel])\\n\",\n    \"#                 remainder[row][col][channel] = str(int(out[row][col][channel] % n))\\n\",\n    \"#                 out[row][col][channel] = int((out[row][col][channel] // n))\\n\",\n    \"#                 str_out[row][col][channel] = str(out[row][col][channel] % p)\\n\",\n    \"                \\n\",\n    \"#     return Input, Weights, Bias, out, str_out, remainder\\n\",\n    \"    \\n\",\n    \"# def PointwiseConv2dInt(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\\n\",\n    \"#     kernelSize = 1\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    \\n\",\n    \"#     Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\\n\",\n    \"#     Weights = [[str(weights[k][l] % p) for l in range(nFilters)] for k in range(nChannels)]\\n\",\n    \"#     Bias = [str(bias[i] % p) for i in range(nFilters)]\\n\",\n    \"#     out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"#     str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"#     remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    \\n\",\n    \"#     for row in range(outRows):\\n\",\n    \"#         for col in range(outCols):\\n\",\n    \"#             for filter in range(nFilters):\\n\",\n    \"#                 for channel in range(nChannels):\\n\",\n    \"#                     out[row][col][filter] += int(input[row*strides][col*strides][channel]) * int(weights[channel][filter])\\n\",\n    \"                            \\n\",\n    \"#                 out[row][col][filter] += int(bias[filter])\\n\",\n    \"#                 remainder[row][col][filter] = str(int(out[row][col][filter] % n))\\n\",\n    \"#                 out[row][col][filter] = str(out[row][col][filter] // n % p)\\n\",\n    \"#     return Input, Weights, Bias, out, remainder\\n\",\n    \"\\n\",\n    \"# def SeparableConvInt(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\\n\",\n    \"#     outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"#     outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"\\n\",\n    \"#     Input, DepthWeights, DepthBias, depthOut, depthStrOut, depthRemainder = DepthwiseConvInt(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\\n\",\n    \"#     test = [[[from_circom(int(depthStrOut[i][j][k])) for k in range(3)] for j in range(5)] for i in range(5)]\\n\",\n    \"#     assert(test == depthOut)\\n\",\n    \"#     pInput, PointWeights, PointBias, pointOut, pointRem = PointwiseConv2dInt(outRows, outCols, nChannels, nPointFilters, strides, n, depthOut, pointWeights, pointBias)\\n\",\n    \"    \\n\",\n    \"#     return Input, DepthWeights, DepthBias, depthOut, depthStrOut, depthRemainder, PointWeights, PointBias, pointOut, pointRem\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"id\": \"cc1a4a27-a1dc-4565-90e3-12e6d7122157\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\\n\",\n    \"    assert(nFilters % nChannels == 0)\\n\",\n    \"    outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"    outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    \\n\",\n    \"    # out = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    remainder = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    # remainder = np.zeros((outRows, outCols, nFilters))\\n\",\n    \"    \\n\",\n    \"    for row in range(outRows):\\n\",\n    \"        for col in range(outCols):\\n\",\n    \"            for channel in range(nChannels):\\n\",\n    \"                for x in range(kernelSize):\\n\",\n    \"                    for y in range(kernelSize):\\n\",\n    \"                        out[row][col][channel] += int(input[row*strides+x, col*strides+y, channel]) * int(weights[x, y, channel])\\n\",\n    \"                \\n\",\n    \"                out[row][col][channel] += int(bias[channel])\\n\",\n    \"                remainder[row][col][channel] = str(int(out[row][col][channel] % n))\\n\",\n    \"                out[row][col][channel] = int(out[row][col][channel] // n)\\n\",\n    \"                            \\n\",\n    \"    return out, remainder\\n\",\n    \"    \\n\",\n    \"def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\\n\",\n    \"    kernelSize = 1\\n\",\n    \"    outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"    outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"    out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\\n\",\n    \"    for row in range(outRows):\\n\",\n    \"        for col in range(outCols):\\n\",\n    \"            for filter in range(nFilters):\\n\",\n    \"                for k in range(nChannels):\\n\",\n    \"                    out[row][col][filter] += int(input[row*strides][col*strides][k]) * int(weights[k, filter])\\n\",\n    \"                    \\n\",\n    \"                out[row][col][filter] += int(bias[filter])\\n\",\n    \"                remainder[row][col][filter] = str(int(out[row][col][filter] % n))\\n\",\n    \"                out[row][col][filter] = int(out[row][col][filter] // n)\\n\",\n    \"                str_out[row][col][filter] = str(out[row][col][filter] % p)\\n\",\n    \"                            \\n\",\n    \"    return out, str_out, remainder\\n\",\n    \"    \\n\",\n    \"def SeparableConvImpl(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\\n\",\n    \"    outRows = (nRows - kernelSize)//strides + 1\\n\",\n    \"    outCols = (nCols - kernelSize)//strides + 1\\n\",\n    \"\\n\",\n    \"    depth_out, depth_remainder = DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\\n\",\n    \"    point_out, point_str_out, point_remainder = PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, depth_out, pointWeights, pointBias)\\n\",\n    \"    return depth_out, depth_remainder, point_out, point_str_out, point_remainder\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"id\": \"cfa6df6a-9a0c-4150-9df0-30e2700d4f6b\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"ename\": \"NameError\",\n     \"evalue\": \"name 'torch' is not defined\",\n     \"output_type\": \"error\",\n     \"traceback\": [\n      \"\\u001b[0;31m---------------------------------------------------------------------------\\u001b[0m\",\n      \"\\u001b[0;31mNameError\\u001b[0m                                 Traceback (most recent call last)\",\n      \"Cell \\u001b[0;32mIn[2], line 1\\u001b[0m\\n\\u001b[0;32m----> 1\\u001b[0m \\u001b[38;5;28minput\\u001b[39m \\u001b[38;5;241m=\\u001b[39m \\u001b[43mtorch\\u001b[49m\\u001b[38;5;241m.\\u001b[39mrandn((\\u001b[38;5;241m1\\u001b[39m, \\u001b[38;5;241m3\\u001b[39m, \\u001b[38;5;241m5\\u001b[39m, \\u001b[38;5;241m5\\u001b[39m))\\n\\u001b[1;32m      2\\u001b[0m model \\u001b[38;5;241m=\\u001b[39m SeparableConv2D(\\u001b[38;5;241m3\\u001b[39m, \\u001b[38;5;241m6\\u001b[39m)\\n\",\n      \"\\u001b[0;31mNameError\\u001b[0m: name 'torch' is not defined\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"input = torch.randn((1, 3, 5, 5))\\n\",\n    \"model = SeparableConv2D(3, 6)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"id\": \"5db59f3a-e610-473a-8dfc-1d5e812748f4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# weights = model.dw_conv.weight.squeeze().detach().numpy()\\n\",\n    \"# bias = torch.zeros(weights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"# expected = model.dw_conv(input).detach().numpy()\\n\",\n    \"\\n\",\n    \"# padded = F.pad(input, (1,1,1,1), \\\"constant\\\", 0) # Padding for convolution with \\\"same\\\" configuration\\n\",\n    \"# padded = padded.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"# weights = weights.transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# actual, rem = DepthwiseConv(7, 7, 3, 3, 3, 1, 1, padded, weights, bias)\\n\",\n    \"# expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# assert(np.allclose(expected, actual, atol=0.00001))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"id\": \"47ce42c7-b417-46ba-a31b-1ae23234a2cd\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# weights = model.pw_conv.weight.detach().numpy()\\n\",\n    \"# print(f\\\"{weights.shape=}\\\")\\n\",\n    \"# bias = torch.zeros(weights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"# expected = model.pw_conv(input).detach().numpy()\\n\",\n    \"\\n\",\n    \"# padded = input.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"# print(padded.shape)\\n\",\n    \"# weights = weights.transpose((2, 3, 1, 0)).squeeze()\\n\",\n    \"\\n\",\n    \"# actual = PointwiseConv2d(5, 5, 3, 6, 1, 1, padded, weights, bias)\\n\",\n    \"\\n\",\n    \"# expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# assert(np.allclose(expected, actual, atol=0.00001))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"id\": \"7a36a0a1-6965-4184-93a5-5d121d6d1856\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# depthWeights = model.dw_conv.weight.squeeze().detach().numpy()\\n\",\n    \"# depthBias = torch.zeros(depthWeights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"# depthWeights = depthWeights.transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# pointWeights = model.pw_conv.weight.detach().numpy()\\n\",\n    \"# print(f\\\"{depthWeights.shape=}\\\")\\n\",\n    \"# pointBias = torch.zeros(pointWeights.shape[0]).numpy()\\n\",\n    \"# pointWeights = pointWeights.transpose((2, 3, 1, 0)).squeeze()\\n\",\n    \"\\n\",\n    \"# expected = model(input).detach().numpy()\\n\",\n    \"# print(f\\\"{expected.shape=}\\\")\\n\",\n    \"\\n\",\n    \"# padded = F.pad(input, (1,1,1,1), \\\"constant\\\", 0) # Padding for convolution with \\\"same\\\" configuration\\n\",\n    \"# padded = padded.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# print(pointBias.shape)\\n\",\n    \"# actual = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 1, padded, depthWeights, pointWeights, depthBias, pointBias)\\n\",\n    \"# expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"# assert(np.allclose(expected, actual, atol=0.00001))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"id\": \"fd587b58-1646-4ec8-9a79-4f891dab0276\",\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"depthWeights.shape=(3, 3, 3)\\n\",\n      \"expected.shape=(1, 6, 5, 5)\\n\",\n      \"(6,)\\n\"\n     ]\n    },\n    {\n     \"ename\": \"NameError\",\n     \"evalue\": \"name 'depthOut' is not defined\",\n     \"output_type\": \"error\",\n     \"traceback\": [\n      \"\\u001b[0;31m---------------------------------------------------------------------------\\u001b[0m\",\n      \"\\u001b[0;31mNameError\\u001b[0m                                 Traceback (most recent call last)\",\n      \"Cell \\u001b[0;32mIn[10], line 23\\u001b[0m\\n\\u001b[1;32m     20\\u001b[0m quantized_depth_weights \\u001b[38;5;241m=\\u001b[39m depthWeights \\u001b[38;5;241m*\\u001b[39m \\u001b[38;5;241m10\\u001b[39m\\u001b[38;5;241m*\\u001b[39m\\u001b[38;5;241m*\\u001b[39mEXPONENT\\n\\u001b[1;32m     21\\u001b[0m quantized_point_weights \\u001b[38;5;241m=\\u001b[39m pointWeights \\u001b[38;5;241m*\\u001b[39m \\u001b[38;5;241m10\\u001b[39m\\u001b[38;5;241m*\\u001b[39m\\u001b[38;5;241m*\\u001b[39mEXPONENT\\n\\u001b[0;32m---> 23\\u001b[0m depth_out, depth_remainder, point_out, point_str_out, point_remainder \\u001b[38;5;241m=\\u001b[39m \\u001b[43mSeparableConvImpl\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;241;43m7\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m7\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m3\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m3\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m6\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m3\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m1\\u001b[39;49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[38;5;241;43m10\\u001b[39;49m\\u001b[38;5;241;43m*\\u001b[39;49m\\u001b[38;5;241;43m*\\u001b[39;49m\\u001b[43mEXPONENT\\u001b[49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[43mquantized_image\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mround\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[43m)\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mastype\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;28;43mint\\u001b[39;49m\\u001b[43m)\\u001b[49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[43mquantized_depth_weights\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mround\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[43m)\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mastype\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;28;43mint\\u001b[39;49m\\u001b[43m)\\u001b[49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[43mquantized_point_weights\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mround\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[43m)\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mastype\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;28;43mint\\u001b[39;49m\\u001b[43m)\\u001b[49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[43mdepthBias\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mastype\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;28;43mint\\u001b[39;49m\\u001b[43m)\\u001b[49m\\u001b[43m,\\u001b[49m\\u001b[43m \\u001b[49m\\u001b[43mpointBias\\u001b[49m\\u001b[38;5;241;43m.\\u001b[39;49m\\u001b[43mastype\\u001b[49m\\u001b[43m(\\u001b[49m\\u001b[38;5;28;43mint\\u001b[39;49m\\u001b[43m)\\u001b[49m\\u001b[43m)\\u001b[49m\\n\\u001b[1;32m     25\\u001b[0m actual_scaled \\u001b[38;5;241m=\\u001b[39m [[[point_out[i][j][k] \\u001b[38;5;241m/\\u001b[39m \\u001b[38;5;241m10\\u001b[39m\\u001b[38;5;241m*\\u001b[39m\\u001b[38;5;241m*\\u001b[39mEXPONENT \\u001b[38;5;28;01mfor\\u001b[39;00m k \\u001b[38;5;129;01min\\u001b[39;00m \\u001b[38;5;28mrange\\u001b[39m(\\u001b[38;5;241m6\\u001b[39m)] \\u001b[38;5;28;01mfor\\u001b[39;00m j \\u001b[38;5;129;01min\\u001b[39;00m \\u001b[38;5;28mrange\\u001b[39m(\\u001b[38;5;241m5\\u001b[39m)] \\u001b[38;5;28;01mfor\\u001b[39;00m i \\u001b[38;5;129;01min\\u001b[39;00m \\u001b[38;5;28mrange\\u001b[39m(\\u001b[38;5;241m5\\u001b[39m)]\\n\\u001b[1;32m     27\\u001b[0m expected \\u001b[38;5;241m=\\u001b[39m expected\\u001b[38;5;241m.\\u001b[39msqueeze()\\u001b[38;5;241m.\\u001b[39mtranspose((\\u001b[38;5;241m1\\u001b[39m, \\u001b[38;5;241m2\\u001b[39m, \\u001b[38;5;241m0\\u001b[39m))\\n\",\n      \"Cell \\u001b[0;32mIn[5], line 60\\u001b[0m, in \\u001b[0;36mSeparableConvImpl\\u001b[0;34m(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias)\\u001b[0m\\n\\u001b[1;32m     57\\u001b[0m outCols \\u001b[38;5;241m=\\u001b[39m (nCols \\u001b[38;5;241m-\\u001b[39m kernelSize)\\u001b[38;5;241m/\\u001b[39m\\u001b[38;5;241m/\\u001b[39mstrides \\u001b[38;5;241m+\\u001b[39m \\u001b[38;5;241m1\\u001b[39m\\n\\u001b[1;32m     59\\u001b[0m depth_out, depth_remainder \\u001b[38;5;241m=\\u001b[39m DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, \\u001b[38;5;28minput\\u001b[39m, depthWeights, depthBias)\\n\\u001b[0;32m---> 60\\u001b[0m point_out, point_str_out, point_remainder \\u001b[38;5;241m=\\u001b[39m PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, \\u001b[43mdepthOut\\u001b[49m, pointWeights, pointBias)\\n\\u001b[1;32m     61\\u001b[0m \\u001b[38;5;28;01mreturn\\u001b[39;00m depth_out, depth_remainder, point_out, point_str_out, point_remainder\\n\",\n      \"\\u001b[0;31mNameError\\u001b[0m: name 'depthOut' is not defined\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"depthWeights = model.dw_conv.weight.squeeze().detach().numpy()\\n\",\n    \"depthBias = torch.zeros(depthWeights.shape[0]).numpy()\\n\",\n    \"\\n\",\n    \"depthWeights = depthWeights.transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"pointWeights = model.pw_conv.weight.detach().numpy()\\n\",\n    \"print(f\\\"{depthWeights.shape=}\\\")\\n\",\n    \"pointBias = torch.zeros(pointWeights.shape[0]).numpy()\\n\",\n    \"pointWeights = pointWeights.transpose((2, 3, 1, 0)).squeeze()\\n\",\n    \"\\n\",\n    \"expected = model(input).detach().numpy()\\n\",\n    \"print(f\\\"{expected.shape=}\\\")\\n\",\n    \"\\n\",\n    \"padded = F.pad(input, (1,1,1,1), \\\"constant\\\", 0) # Padding for convolution with \\\"same\\\" configuration\\n\",\n    \"padded = padded.squeeze().numpy().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"print(pointBias.shape)\\n\",\n    \"# actual = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 1, padded, depthWeights, pointWeights, depthBias, pointBias)\\n\",\n    \"quantized_image = padded * 10**EXPONENT\\n\",\n    \"quantized_depth_weights = depthWeights * 10**EXPONENT\\n\",\n    \"quantized_point_weights = pointWeights * 10**EXPONENT\\n\",\n    \"\\n\",\n    \"depth_out, depth_remainder, point_out, point_str_out, point_remainder = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 10**EXPONENT, quantized_image.round().astype(int), quantized_depth_weights.round().astype(int), quantized_point_weights.round().astype(int), depthBias.astype(int), pointBias.astype(int))\\n\",\n    \"\\n\",\n    \"actual_scaled = [[[point_out[i][j][k] / 10**EXPONENT for k in range(6)] for j in range(5)] for i in range(5)]\\n\",\n    \"\\n\",\n    \"expected = expected.squeeze().transpose((1, 2, 0))\\n\",\n    \"\\n\",\n    \"assert(np.allclose(expected, actual_scaled, atol=0.00001))\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"# Input, DepthWeights, DepthBias, depthOut, depthStrOut, DepthRem, PointWeights, PointBias, pointOut, pointRem = SeparableConvInt(7, 7, 3, 3, 6, 3, 1, 10**EXPONENT, quantized_image.round().astype(int), quantized_depth_weights.round().astype(int), quantized_point_weights.round().astype(int), depthBias.astype(int), pointBias.astype(int))\\n\",\n    \"\\n\",\n    \"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_depth_weights = quantized_depth_weights.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_point_weights = quantized_point_weights.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_depth_bias = depthBias.round().astype(int).astype(str).tolist()\\n\",\n    \"circuit_point_bias = pointBias.round().astype(int).astype(str).tolist()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"input_json_path = \\\"separableConv2D_input.json\\\"\\n\",\n    \"with open(input_json_path, \\\"w\\\") as input_file:\\n\",\n    \"    json.dump({\\\"in\\\": circuit_in,\\n\",\n    \"               \\\"depthWeights\\\": circuit_depth_weights,\\n\",\n    \"               \\\"depthBias\\\": circuit_depth_bias,\\n\",\n    \"               \\\"depthRemainder\\\": depth_remainder,\\n\",\n    \"               \\\"depthOut\\\": depth_out,\\n\",\n    \"               \\n\",\n    \"               \\\"pointWeights\\\": circuit_point_weights,\\n\",\n    \"               \\\"pointBias\\\": circuit_point_bias,\\n\",\n    \"               \\\"pointRemainder\\\": point_remainder,\\n\",\n    \"               \\\"pointOut\\\": point_str_out,\\n\",\n    \"              },\\n\",\n    \"              input_file)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 44,\n   \"id\": \"f0dcbca8-7f2f-47ea-b662-29a8560774b1\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 289246014266912,  458852178050435, -104551710192411,\\n\",\n       \"        -85286796832706,   70991076566637, -373719950995314])\"\n      ]\n     },\n     \"execution_count\": 44,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"test = np.array(actual)\\n\",\n    \"test[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 45,\n   \"id\": \"3a652322-2fa0-4f51-bb2f-ed49bd94c65a\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([ 0.289246  ,  0.45885214, -0.10455171, -0.0852868 ,  0.07099106,\\n\",\n       \"       -0.37371993], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 45,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"expected[0][0]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"56d3dda8-af64-402e-9c86-b333ca6782ba\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.11.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/sumPooling2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, AveragePooling2D, Lambda\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(5,5,3))\\n\",\n    \"x = AveragePooling2D(pool_size=2)(inputs)\\n\",\n    \"x = Lambda(lambda x: x*4)(x)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \"Layer (type)                 Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \"input_1 (InputLayer)         [(None, 5, 5, 3)]         0         \\n\",\n      \"_________________________________________________________________\\n\",\n      \"average_pooling2d (AveragePo (None, 2, 2, 3)           0         \\n\",\n      \"_________________________________________________________________\\n\",\n      \"lambda (Lambda)              (None, 2, 2, 3)           0         \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.83128186, 0.15650764, 0.23798145],\\n\",\n       \"         [0.00277366, 0.8374127 , 0.95278315],\\n\",\n       \"         [0.3074389 , 0.21931738, 0.14886067],\\n\",\n       \"         [0.13590018, 0.98728255, 0.12085182],\\n\",\n       \"         [0.47212572, 0.51380922, 0.74891219]],\\n\",\n       \"\\n\",\n       \"        [[0.74680338, 0.2533205 , 0.5039968 ],\\n\",\n       \"         [0.14475403, 0.00791911, 0.4361197 ],\\n\",\n       \"         [0.69925568, 0.77507624, 0.40388991],\\n\",\n       \"         [0.29508251, 0.99375606, 0.84959701],\\n\",\n       \"         [0.88844918, 0.33910189, 0.9617212 ]],\\n\",\n       \"\\n\",\n       \"        [[0.76480625, 0.591287  , 0.0714191 ],\\n\",\n       \"         [0.94371681, 0.1695303 , 0.4476252 ],\\n\",\n       \"         [0.54372616, 0.83818804, 0.95211573],\\n\",\n       \"         [0.30485104, 0.15165265, 0.94709317],\\n\",\n       \"         [0.90827137, 0.58854675, 0.01857002]],\\n\",\n       \"\\n\",\n       \"        [[0.70123418, 0.43090173, 0.7096038 ],\\n\",\n       \"         [0.20637783, 0.20096581, 0.22956612],\\n\",\n       \"         [0.81978383, 0.16775403, 0.67412096],\\n\",\n       \"         [0.1011535 , 0.35596916, 0.36702071],\\n\",\n       \"         [0.5874605 , 0.79341372, 0.93292159]],\\n\",\n       \"\\n\",\n       \"        [[0.77997124, 0.46311399, 0.5465576 ],\\n\",\n       \"         [0.20406287, 0.37547625, 0.59862253],\\n\",\n       \"         [0.52933135, 0.84249092, 0.02969684],\\n\",\n       \"         [0.29114617, 0.10405779, 0.5359062 ],\\n\",\n       \"         [0.25197146, 0.83297465, 0.67025403]]]])\"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,5,5,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[1.7256129, 1.2551599, 2.1308813],\\n\",\n       \"         [1.4376774, 2.9754324, 1.5231993]],\\n\",\n       \"\\n\",\n       \"        [[2.6161351, 1.3926848, 1.4582142],\\n\",\n       \"         [1.7695144, 1.5135639, 2.9403505]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 12,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": (X*1000).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_json = {\\n\",\n    \"    \\\"out\\\": (y*1000).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"sumPooling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"sumPooling2D_output.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(out_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(10,10,3))\\n\",\n    \"x = AveragePooling2D(pool_size=2, strides=3)(inputs)\\n\",\n    \"x = Lambda(lambda x: x*4)(x)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_2\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \"Layer (type)                 Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \"input_3 (InputLayer)         [(None, 10, 10, 3)]       0         \\n\",\n      \"_________________________________________________________________\\n\",\n      \"average_pooling2d_2 (Average (None, 3, 3, 3)           0         \\n\",\n      \"_________________________________________________________________\\n\",\n      \"lambda_2 (Lambda)            (None, 3, 3, 3)           0         \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[0.31514958, 0.03200121, 0.29129004],\\n\",\n       \"         [0.35725668, 0.87252739, 0.77162311],\\n\",\n       \"         [0.61707883, 0.7945887 , 0.48907944],\\n\",\n       \"         [0.98197306, 0.88814753, 0.69652672],\\n\",\n       \"         [0.2518265 , 0.82753267, 0.57464263],\\n\",\n       \"         [0.62115028, 0.76805041, 0.65967975],\\n\",\n       \"         [0.32491691, 0.93353364, 0.74831234],\\n\",\n       \"         [0.45570461, 0.96830864, 0.8476189 ],\\n\",\n       \"         [0.02149766, 0.27808247, 0.18207897],\\n\",\n       \"         [0.15949257, 0.69372265, 0.43455872]],\\n\",\n       \"\\n\",\n       \"        [[0.70915807, 0.60410698, 0.94721792],\\n\",\n       \"         [0.5621233 , 0.65546021, 0.27357865],\\n\",\n       \"         [0.00414209, 0.08635782, 0.30528659],\\n\",\n       \"         [0.11492599, 0.15002234, 0.58496289],\\n\",\n       \"         [0.72848003, 0.55169839, 0.91708802],\\n\",\n       \"         [0.43479205, 0.08069621, 0.68404234],\\n\",\n       \"         [0.3946513 , 0.20447291, 0.10467492],\\n\",\n       \"         [0.78817621, 0.63518792, 0.00827133],\\n\",\n       \"         [0.0853401 , 0.75656605, 0.95034115],\\n\",\n       \"         [0.92239164, 0.06871402, 0.37783711]],\\n\",\n       \"\\n\",\n       \"        [[0.36000095, 0.35659628, 0.6507159 ],\\n\",\n       \"         [0.29486935, 0.49464939, 0.40502335],\\n\",\n       \"         [0.09509896, 0.08726498, 0.39326876],\\n\",\n       \"         [0.38827707, 0.50908505, 0.63443643],\\n\",\n       \"         [0.27030144, 0.67783072, 0.09309034],\\n\",\n       \"         [0.76360544, 0.67003754, 0.28767228],\\n\",\n       \"         [0.55305299, 0.60216561, 0.3544107 ],\\n\",\n       \"         [0.55839884, 0.86964781, 0.26053367],\\n\",\n       \"         [0.87306012, 0.78756102, 0.04817508],\\n\",\n       \"         [0.72406774, 0.67679246, 0.82272016]],\\n\",\n       \"\\n\",\n       \"        [[0.71765743, 0.50852032, 0.52047892],\\n\",\n       \"         [0.7484707 , 0.97207503, 0.08778545],\\n\",\n       \"         [0.15780167, 0.73192822, 0.40718403],\\n\",\n       \"         [0.93263197, 0.8772701 , 0.34486053],\\n\",\n       \"         [0.42436095, 0.80504181, 0.39139203],\\n\",\n       \"         [0.81358273, 0.56754054, 0.12608038],\\n\",\n       \"         [0.11843567, 0.61136361, 0.81339895],\\n\",\n       \"         [0.27636648, 0.57453166, 0.10632468],\\n\",\n       \"         [0.53090786, 0.14594835, 0.08140653],\\n\",\n       \"         [0.34118642, 0.27554414, 0.19515355]],\\n\",\n       \"\\n\",\n       \"        [[0.12974003, 0.6264065 , 0.56250089],\\n\",\n       \"         [0.05655555, 0.93847961, 0.71849845],\\n\",\n       \"         [0.57644684, 0.37077012, 0.53949152],\\n\",\n       \"         [0.45904117, 0.30854737, 0.73517714],\\n\",\n       \"         [0.64076017, 0.59373326, 0.83758554],\\n\",\n       \"         [0.80707699, 0.79461191, 0.69655474],\\n\",\n       \"         [0.79872758, 0.26420269, 0.29237624],\\n\",\n       \"         [0.45087863, 0.28258419, 0.50447663],\\n\",\n       \"         [0.29494657, 0.31770288, 0.49309187],\\n\",\n       \"         [0.82460949, 0.3940875 , 0.33865267]],\\n\",\n       \"\\n\",\n       \"        [[0.1108653 , 0.35294351, 0.44014634],\\n\",\n       \"         [0.4988099 , 0.34405962, 0.77622373],\\n\",\n       \"         [0.76444373, 0.88689451, 0.05756076],\\n\",\n       \"         [0.57160174, 0.0752442 , 0.5098132 ],\\n\",\n       \"         [0.22539676, 0.47741414, 0.28993556],\\n\",\n       \"         [0.43298235, 0.58710277, 0.69306001],\\n\",\n       \"         [0.9521223 , 0.87239108, 0.10672981],\\n\",\n       \"         [0.93125144, 0.19405455, 0.95483289],\\n\",\n       \"         [0.91030892, 0.85961313, 0.67439157],\\n\",\n       \"         [0.09377237, 0.75818836, 0.61985122]],\\n\",\n       \"\\n\",\n       \"        [[0.4344654 , 0.97297157, 0.89560878],\\n\",\n       \"         [0.91664946, 0.68966445, 0.0530751 ],\\n\",\n       \"         [0.72099738, 0.05779864, 0.30259649],\\n\",\n       \"         [0.55598956, 0.11611106, 0.24856552],\\n\",\n       \"         [0.40690072, 0.66148966, 0.22159354],\\n\",\n       \"         [0.53035294, 0.23237414, 0.82781172],\\n\",\n       \"         [0.20375017, 0.23486322, 0.36461596],\\n\",\n       \"         [0.05525619, 0.59671011, 0.08001122],\\n\",\n       \"         [0.11250979, 0.98519728, 0.57553523],\\n\",\n       \"         [0.6117834 , 0.65811775, 0.78386287]],\\n\",\n       \"\\n\",\n       \"        [[0.39532528, 0.78660638, 0.37617851],\\n\",\n       \"         [0.86246711, 0.59398046, 0.50843286],\\n\",\n       \"         [0.41395181, 0.96399598, 0.8374128 ],\\n\",\n       \"         [0.76981858, 0.41760042, 0.17438256],\\n\",\n       \"         [0.05937649, 0.93289121, 0.63833505],\\n\",\n       \"         [0.97571178, 0.06364159, 0.34572432],\\n\",\n       \"         [0.42278241, 0.52111442, 0.62746908],\\n\",\n       \"         [0.0401781 , 0.80713288, 0.26990436],\\n\",\n       \"         [0.21850787, 0.19009324, 0.04497292],\\n\",\n       \"         [0.16176602, 0.20893733, 0.34094974]],\\n\",\n       \"\\n\",\n       \"        [[0.13094336, 0.90151022, 0.82541695],\\n\",\n       \"         [0.73192844, 0.24791076, 0.3587372 ],\\n\",\n       \"         [0.88818939, 0.92023872, 0.69098959],\\n\",\n       \"         [0.08104613, 0.6361497 , 0.42552169],\\n\",\n       \"         [0.44517886, 0.99055202, 0.15580116],\\n\",\n       \"         [0.78742252, 0.04735346, 0.46423316],\\n\",\n       \"         [0.53474903, 0.79917168, 0.33019955],\\n\",\n       \"         [0.31087978, 0.65384266, 0.77275665],\\n\",\n       \"         [0.56393354, 0.5761927 , 0.4287843 ],\\n\",\n       \"         [0.57457285, 0.67154059, 0.52881047]],\\n\",\n       \"\\n\",\n       \"        [[0.78373278, 0.15164648, 0.92791502],\\n\",\n       \"         [0.0999971 , 0.47319914, 0.44424683],\\n\",\n       \"         [0.74758969, 0.04583226, 0.0579972 ],\\n\",\n       \"         [0.37325021, 0.12464474, 0.61199188],\\n\",\n       \"         [0.07404238, 0.65504221, 0.18787021],\\n\",\n       \"         [0.16955187, 0.12750002, 0.48252436],\\n\",\n       \"         [0.17829354, 0.85701326, 0.41402596],\\n\",\n       \"         [0.21677806, 0.18949005, 0.27735136],\\n\",\n       \"         [0.06721647, 0.16941253, 0.46916978],\\n\",\n       \"         [0.39921131, 0.17705116, 0.94534667]]]])\"\n      ]\n     },\n     \"execution_count\": 22,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = np.random.rand(1,10,10,3)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[1.9436876 , 2.1640959 , 2.2837098 ],\\n\",\n       \"         [2.0772057 , 2.4174008 , 2.7732203 ],\\n\",\n       \"         [1.963449  , 2.741503  , 1.7088774 ]],\\n\",\n       \"\\n\",\n       \"        [[1.6524236 , 3.0454814 , 1.8892637 ],\\n\",\n       \"         [2.4567943 , 2.5845926 , 2.3090153 ],\\n\",\n       \"         [1.6444083 , 1.7326821 , 1.7165766 ]],\\n\",\n       \"\\n\",\n       \"        [[2.6089072 , 3.043223  , 1.8332952 ],\\n\",\n       \"         [1.7920854 , 2.1280923 , 1.2828767 ],\\n\",\n       \"         [0.72196686, 2.1598206 , 1.3420006 ]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 23,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": (X*1000).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 25,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_json = {\\n\",\n    \"    \\\"out\\\": (y*1000).round().astype(int).flatten().tolist()\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 26,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"sumPooling2D_stride_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 27,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open(\\\"sumPooling2D_stride_output.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(out_json, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"tf24\",\n   \"language\": \"python\",\n   \"name\": \"tf24\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.8.6\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "models/upSampling2d.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.layers import Input, UpSampling2D\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(1,2,3))\\n\",\n    \"x = UpSampling2D(size=2)(inputs)\\n\",\n    \"model = Model(inputs, x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model_1\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_2 (InputLayer)        [(None, 1, 2, 3)]         0         \\n\",\n      \"                                                                 \\n\",\n      \" up_sampling2d_1 (UpSampling  (None, 2, 4, 3)          0         \\n\",\n      \" 2D)                                                             \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 0\\n\",\n      \"Trainable params: 0\\n\",\n      \"Non-trainable params: 0\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[842674, 497907,  66624],\\n\",\n       \"         [875287, 832625,  34934]]]])\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"X = (np.random.rand(1,1,2,3)*1e6).astype(int)\\n\",\n    \"X\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1/1 [==============================] - 0s 27ms/step\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"array([[[[842674., 497907.,  66624.],\\n\",\n       \"         [842674., 497907.,  66624.],\\n\",\n       \"         [875287., 832625.,  34934.],\\n\",\n       \"         [875287., 832625.,  34934.]],\\n\",\n       \"\\n\",\n       \"        [[842674., 497907.,  66624.],\\n\",\n       \"         [842674., 497907.,  66624.],\\n\",\n       \"         [875287., 832625.,  34934.],\\n\",\n       \"         [875287., 832625.,  34934.]]]], dtype=float32)\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"y = model.predict(X)\\n\",\n    \"y\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def UpSampling2DInt(nRows, nCols, nChannels, size, input):\\n\",\n    \"    out = [[[None for _ in range(nChannels)] for _ in range(nCols*size)] for _ in range(nRows*size)]\\n\",\n    \"    for i in range(nRows):\\n\",\n    \"        for j in range(nCols):\\n\",\n    \"            for c in range(nChannels):\\n\",\n    \"                for k in range(size):\\n\",\n    \"                    for l in range(size):\\n\",\n    \"                        out[i*size+k][j*size+l][c] = input[i][j][c]\\n\",\n    \"    return out\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"X_in = [[[int(X[0][i][j][k]) for k in range(3)] for j in range(2)] for i in range(1)]\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[[[842674, 497907, 66624],\\n\",\n       \"  [842674, 497907, 66624],\\n\",\n       \"  [875287, 832625, 34934],\\n\",\n       \"  [875287, 832625, 34934]],\\n\",\n       \" [[842674, 497907, 66624],\\n\",\n       \"  [842674, 497907, 66624],\\n\",\n       \"  [875287, 832625, 34934],\\n\",\n       \"  [875287, 832625, 34934]]]\"\n      ]\n     },\n     \"execution_count\": 19,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"out = UpSampling2DInt(1, 2, 3, 2, X_in)\\n\",\n    \"out\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"assert np.all(y[0].astype(int) == np.array(out))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"in_json = {\\n\",\n    \"    \\\"in\\\": X_in,\\n\",\n    \"    \\\"out\\\": out\\n\",\n    \"}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\\n\",\n    \"with open(\\\"upSampling2D_input.json\\\", \\\"w\\\") as f:\\n\",\n    \"    json.dump(in_json, f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/AveragePooling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"AveragePooling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // AveragePooling with strides==poolSize\n    it(\"(5,5,3) -> (2,2,3)\", async () => {\n        const INPUT = require(\"../models/averagePooling2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"AveragePooling2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n\n    // AveragePooling with strides!=poolSize\n    it(\"(10,10,3) -> (4,4,3)\", async () => {\n        const INPUT = require(\"../models/averagePooling2D_stride_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"AveragePooling2D_stride_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/BatchNormalization.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"BatchNormalization layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(5,5,3) -> (5,5,3)\", async () => {\n        const INPUT = require(\"../models/batchNormalization_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"BatchNormalization_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Conv1D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst INPUT = require(\"../models/conv1D_input.json\");\n\ndescribe(\"Conv1D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(20,3) -> (6,2)\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Conv1D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Conv2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"Conv2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(5,5,3) -> (3,3,2)\", async () => {\n        const INPUT = require(\"../models/conv2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Conv2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n\n    it(\"(10,10,3) -> (3,3,2)\", async () => {\n        const INPUT = require(\"../models/conv2D_stride_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Conv2D_stride_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Conv2Dsame.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"Conv2Dsame layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(5,5,3) -> (5,5,2)\", async () => {\n        const INPUT = require(\"../models/Conv2Dsame_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Conv2Dsame_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n\n    it(\"(10,10,3) -> (4,4,2)\", async () => {\n        const INPUT = require(\"../models/Conv2Dsame_stride_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Conv2Dsame_stride_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Dense.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"Dense layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"20 nodes -> 10 nodes\", async () => {\n        const INPUT = require(\"../models/dense_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Dense_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/DepthwiseConv2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"DepthwiseConv2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(7,7,3) -> (5,5,3)\", async () => {\n        const INPUT = require(\"../models/depthwiseConv2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"DepthwiseConv2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Flatten2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"Flatten2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(5,5,3) -> 75\", async () => {\n        const INPUT = require(\"../models/flatten2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Flatten2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/GlobalAveragePooling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"GlobalAveragePooling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // GlobalAveragePooling with strides==poolSize\n    it(\"(5,5,3) -> (3,)\", async () => {\n        const INPUT = require(\"../models/globalAveragePooling2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"GlobalAveragePooling2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/GlobalMaxPooling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"GlobalMaxPooling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // GlobalMaxPooling with strides==poolSize\n    it(\"(5,5,3) -> (3,)\", async () => {\n        const INPUT = require(\"../models/globalMaxPooling2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"GlobalMaxPooling2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/IsNegative.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"IsNegative test\", function () {\n    this.timeout(100000000);\n\n    it(\"Negative -> 1\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"IsNegative_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 516);\n        //assert.equal(circuit.constraints.length, 516);\n\n        const INPUT = {\n            \"in\": Fr.e(-1)\n        }\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(1)));\n    });\n\n    it(\"Positive -> 0\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"IsNegative_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 516);\n        //assert.equal(circuit.constraints.length, 516);\n\n        const INPUT = {\n            \"in\": \"1\"\n        }\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(0)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/IsPositive.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"IsPositive test\", function () {\n    this.timeout(100000000);\n\n    it(\"Positive -> 1\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"IsPositive_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 516);\n        //assert.equal(circuit.constraints.length, 516);\n\n        const INPUT = {\n            \"in\": \"1\"\n        }\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(1)));\n    });\n\n    it(\"Negative -> 0\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"IsPositive_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 516);\n        //assert.equal(circuit.constraints.length, 516);\n\n        const INPUT = {\n            \"in\": Fr.e(-1)\n        }\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(0)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/LeakyReLU.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"LeakyReLU layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"3 nodes\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"LeakyReLU_test.circom\"));\n\n        const INPUT = {\n            \"in\": [Fr.e(-11),\"0\",\"3\"],\n            \"out\": [Fr.e(-4),\"0\",\"3\"],\n            \"remainder\": [\"7\",\"0\",\"0\"]\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Max.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"Max test\", function () {\n    this.timeout(100000000);\n\n    it(\"Maximum of 4 numbers\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Max_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 516);\n        //assert.equal(circuit.constraints.length, 516);\n\n        const INPUT = {\n            \"in\": [\"1\",\"4\",\"2\",\"3\"]\n        }\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(4)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/MaxPooling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"MaxPooling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // MaxPooling with strides==poolSize\n    it(\"(5,5,3) -> (2,2,3)\", async () => {\n        const INPUT = require(\"../models/maxPooling2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"MaxPooling2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n\n    // MaxPooling with strides!=poolSize\n    it(\"(10,10,3) -> (3,3,3)\", async () => {\n        const INPUT = require(\"../models/maxPooling2D_stride_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"MaxPooling2D_stride_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/MaxPooling2Dsame.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"MaxPooling2Dsame layer test\", function () {\n    this.timeout(100000000);\n\n    // MaxPooling with strides==poolSize\n    it(\"(5,5,3) -> (3,3,3)\", async () => {\n        const INPUT = require(\"../models/maxPooling2Dsame_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"MaxPooling2Dsame_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n\n    // MaxPooling with strides!=poolSize\n    it(\"(10,10,3) -> (4,4,3)\", async () => {\n        const INPUT = require(\"../models/maxPooling2Dsame_stride_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"MaxPooling2Dsame_stride_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/PointwiseConv2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"PointwiseConv2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(7,7,3) -> (5,5,3)\", async () => {\n        const INPUT = require(\"../models/pointwiseConv2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"PointwiseConv2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/ReLU.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"ReLU layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"3 nodes\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"ReLU_test.circom\"));\n\n        const INPUT = {\n            \"in\": [Fr.e(-3),\"0\",\"3\"],\n            \"out\": [\"0\",\"0\",\"3\"]\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/Reshape2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"Reshape2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"75 -> (5,5,3)\", async () => {\n        const INPUT = require(\"../models/reshape2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"Reshape2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/SeparableConv2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\ndescribe(\"SeparableConv2D layer test\", function () {\n    this.timeout(100000000);\n\n    it(\"(7,7,3) -> (5,5,3)\", async () => {\n        const INPUT = require(\"../models/separableConv2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"SeparableConv2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/SumPooling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"SumPooling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // SumPooling with strides==poolSize\n    it(\"(5,5,3) -> (2,2,3)\", async () => {\n        const json = require(\"../models/sumPooling2D_input.json\");\n        const OUTPUT = require(\"../models/sumPooling2D_output.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"SumPooling2D_test.circom\"));\n        //await circuit.loadConstraints();\n        //assert.equal(circuit.nVars, 76);\n        //assert.equal(circuit.constraints.length, 0);\n\n        const INPUT = {\n            \"in\": json.in\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n\n        let ape = 0;\n\n        for (var i=0; i<OUTPUT.out.length; i++) {\n            // console.log(\"actual\", OUTPUT.out[i], \"predicted\", Fr.toString(witness[i+1]));\n            ape += Math.abs((OUTPUT.out[i]-parseInt(Fr.toString(witness[i+1])))/OUTPUT.out[i]);\n        }\n\n        const mape = ape/OUTPUT.out.length;\n\n        console.log(\"mean absolute % error\", mape);\n\n        assert(mape < 0.01);\n    });\n\n    // SumPooling with strides!=poolSize\n    it(\"(10,10,3) -> (3,3,3)\", async () => {\n        const json = require(\"../models/sumPooling2D_stride_input.json\");\n        const OUTPUT = require(\"../models/sumPooling2D_stride_output.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"SumPooling2D_stride_test.circom\"));\n\n        const INPUT = {\n            \"in\": json.in\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n\n        let ape = 0;\n\n        for (var i=0; i<OUTPUT.out.length; i++) {\n            // console.log(\"actual\", OUTPUT.out[i], \"predicted\", Fr.toString(witness[i+1]));\n            ape += Math.abs((OUTPUT.out[i]-parseInt(Fr.toString(witness[i+1])))/OUTPUT.out[i]);\n        }\n\n        const mape = ape/OUTPUT.out.length;\n\n        console.log(\"mean absolute % error\", mape);\n\n        assert(mape < 0.01);\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/UpSampling2D.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\n\n\ndescribe(\"UpSampling2D layer test\", function () {\n    this.timeout(100000000);\n\n    // UpSampling with strides==poolSize\n    it(\"(1,2,3) -> (2,4,3)\", async () => {\n        const INPUT = require(\"../models/upSampling2D_input.json\");\n\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"UpSampling2D_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/AveragePooling2D_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/AveragePooling2D.circom\";\n\n// poolSize!=strides\ncomponent main = AveragePooling2D(10, 10, 3, 3, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/AveragePooling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/AveragePooling2D.circom\";\n\n// poolSize=strides - default Keras settings\ncomponent main = AveragePooling2D(5, 5, 3, 2, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/BatchNormalization_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/BatchNormalization2D.circom\";\n\ncomponent main = BatchNormalization2D(5,5,3,10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Conv1D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv1D.circom\";\n\ncomponent main = Conv1D(20, 3, 2, 4, 3, 10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Conv2D_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2D.circom\";\n\ncomponent main = Conv2D(10, 10, 3, 2, 4, 3, 10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Conv2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2D.circom\";\n\ncomponent main = Conv2D(5, 5, 3, 2, 3, 1, 10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Conv2Dsame_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2Dsame.circom\";\n\ncomponent main = Conv2Dsame(10, 10, 3, 2, 4, 3, 10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Conv2Dsame_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2Dsame.circom\";\n\ncomponent main = Conv2Dsame(5, 5, 3, 2, 3, 1, 10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Dense_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Dense.circom\";\n\ncomponent main = Dense(20,10,10**36);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/DepthwiseConv2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/DepthwiseConv2D.circom\";\n\ncomponent main = DepthwiseConv2D(7, 7, 3, 3, 3, 1, 10**15);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Flatten2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Flatten2D.circom\";\n\ncomponent main = Flatten2D(5, 5, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/GlobalAveragePooling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/GlobalAveragePooling2D.circom\";\n\ncomponent main = GlobalAveragePooling2D(5, 5, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/GlobalMaxPooling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/GlobalMaxPooling2D.circom\";\n\ncomponent main = GlobalMaxPooling2D(5, 5, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/IsNegative_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/util.circom\";\n\ncomponent main = IsNegative();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/IsPositive_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/util.circom\";\n\ncomponent main = IsPositive();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/LeakyReLU_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/LeakyReLU.circom\";\n\ntemplate leaky_relu_test() {\n    signal input in[3];\n    signal input out[3];\n    signal input remainder[3];\n\n    component leaky_relu[3];\n\n    for (var i=0; i<3; i++) {\n        leaky_relu[i] = LeakyReLU(3);\n\n        leaky_relu[i].in <== in[i];\n        leaky_relu[i].out <== out[i];\n        leaky_relu[i].remainder <== remainder[i];\n    }\n}\n\ncomponent main = leaky_relu_test();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/MaxPooling2D_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/MaxPooling2D.circom\";\n\ncomponent main = MaxPooling2D(10, 10, 3, 2, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/MaxPooling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/MaxPooling2D.circom\";\n\n// poolSize=strides - default Keras settings\ncomponent main = MaxPooling2D(5, 5, 3, 2, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/MaxPooling2Dsame_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/MaxPooling2Dsame.circom\";\n\ncomponent main = MaxPooling2Dsame(10, 10, 3, 2, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/MaxPooling2Dsame_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/MaxPooling2Dsame.circom\";\n\n// poolSize=strides - default Keras settings\ncomponent main = MaxPooling2Dsame(5, 5, 3, 2, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Max_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/util.circom\";\n\ncomponent main = Max(4);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/PointwiseConv2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/PointwiseConv2D.circom\";\n\ncomponent main = PointwiseConv2D(5, 5, 3, 6, 10**15);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/ReLU_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/ReLU.circom\";\n\ntemplate relu_test() {\n    signal input in[3];\n    signal input out[3];\n\n    component relu[3];\n\n    for (var i=0; i<3; i++) {\n        relu[i] = ReLU();\n\n        relu[i].in <== in[i];\n        relu[i].out <== out[i];\n    }\n}\n\ncomponent main = relu_test();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/Reshape2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Reshape2D.circom\";\n\ncomponent main = Reshape2D(5, 5, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/SeparableConv2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/SeparableConv2D.circom\";\n\ncomponent main = SeparableConv2D(7, 7, 3, 3, 6, 3, 1, 10**15);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/SumPooling2D_stride_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/SumPooling2D.circom\";\n\ncomponent main = SumPooling2D(10, 10, 3, 2, 3);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/SumPooling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/SumPooling2D.circom\";\n\n// poolSize=strides - default Keras settings\ncomponent main = SumPooling2D(5, 5, 3, 2, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/UpSampling2D_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/UpSampling2D.circom\";\n\ncomponent main = UpSampling2D(1, 2, 3, 2);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/decryptMultiple_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/encrypt.circom\";\n\ncomponent main = DecryptBits(1000);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/decrypt_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/encrypt.circom\";\n\ncomponent main = Decrypt();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/ecdh_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/ecdh.circom\";\n\ncomponent main = Ecdh();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/encryptDecrypt_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/encrypt.circom\";\ninclude \"../../circuits/crypto/ecdh.circom\";\n\n// from zk-ml/linear-regression-demo\n\ntemplate Test() {\n    signal input message;\n    signal input shared_key;\n    signal output out;\n    signal input private_key;\n    signal input public_key[2];\n\n    component ecdh = Ecdh();\n\n    ecdh.private_key <== private_key;\n    ecdh.public_key[0] <== public_key[0];\n    ecdh.public_key[1] <== public_key[1];\n\n    log(ecdh.shared_key);\n    log(shared_key);\n    log(private_key);\n    log(public_key[0]);\n    log(public_key[1]);\n\n    shared_key === ecdh.shared_key;\n\n    component enc = Encrypt();\n    component dec = Decrypt();\n\n    message ==> enc.plaintext;\n    shared_key ==> enc.shared_key;\n    shared_key ==> dec.shared_key;\n    enc.out[0] ==> dec.message[0];\n    enc.out[1] ==> dec.message[1];\n\n    log(dec.out);\n    dec.out === message;\n    out <== 1;\n}\n\ncomponent main = Test();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/encryptMultiple_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/encrypt.circom\";\n\ncomponent main = EncryptBits(1000);"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/encrypt_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/encrypt.circom\";\n\ncomponent main = Encrypt();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/encrypted_mnist_latest_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2D.circom\";\ninclude \"../../circuits/Dense.circom\";\ninclude \"../../circuits/ArgMax.circom\";\ninclude \"../../circuits/Poly.circom\";\ninclude \"../../circuits/AveragePooling2D.circom\";\ninclude \"../../circuits/BatchNormalization2D.circom\";\ninclude \"../../circuits/Flatten2D.circom\";\ninclude \"../../circuits/crypto/encrypt.circom\";\ninclude \"../../circuits/crypto/ecdh.circom\";\n\ntemplate encrypted_mnist_latest() {\n    signal input in[28][28][1];\n    signal input conv2d_1_weights[3][3][1][4];\n    signal input conv2d_1_bias[4];\n    signal input bn_1_a[4];\n    signal input bn_1_b[4];\n    signal input conv2d_2_weights[3][3][4][8];\n    signal input conv2d_2_bias[8];\n    signal input bn_2_a[8];\n    signal input bn_2_b[8];\n    signal input dense_weights[200][10];\n    signal input dense_bias[10];\n    signal output out;\n\n    signal input private_key;\n    signal input public_key[2];\n\n    component ecdh = Ecdh();\n\n    ecdh.private_key <== private_key;\n    ecdh.public_key[0] <== public_key[0];\n    ecdh.public_key[1] <== public_key[1];\n\n    signal output message[3*3*1*4+4+4+4+3*3*4*8+8+8+8+200*10+10+1];\n\n    component enc = EncryptBits(3*3*1*4+4+4+4+3*3*4*8+8+8+8+200*10+10);\n    enc.shared_key <== ecdh.shared_key;\n\n    var idx = 0;\n\n    component conv2d_1 = Conv2D(28,28,1,4,3,1);\n    component bn_1 = BatchNormalization2D(26,26,4);\n    component poly_1[26][26][4];\n    component avg2d_1 = AveragePooling2D(26,26,4,2,2,25);\n    component conv2d_2 = Conv2D(13,13,4,8,3,1);\n    component bn_2 = BatchNormalization2D(11,11,8);\n    component poly_2[11][11][8];\n    component avg2d_2 = AveragePooling2D(11,11,8,2,2,25);\n    component flatten = Flatten2D(5,5,8);\n    component dense = Dense(200,10);\n    component argmax = ArgMax(10);\n\n    for (var i=0; i<28; i++) {\n        for (var j=0; j<28; j++) {\n            conv2d_1.in[i][j][0] <== in[i][j][0];\n        }\n    }\n\n    for (var i=0; i<3; i++) {\n        for (var j=0; j<3; j++) {\n            for (var m=0; m<4; m++) {\n                conv2d_1.weights[i][j][0][m] <== conv2d_1_weights[i][j][0][m];\n                enc.plaintext[idx] <== conv2d_1_weights[i][j][0][m];\n                idx++;\n            }\n        }\n    }\n    \n    for (var m=0; m<4; m++) {\n        conv2d_1.bias[m] <== conv2d_1_bias[m];\n        enc.plaintext[idx] <== conv2d_1_bias[m];\n        idx++;\n    }\n\n    for (var k=0; k<4; k++) {\n        bn_1.a[k] <== bn_1_a[k];\n        enc.plaintext[idx] <== bn_1_a[k];\n        idx++;\n    }\n\n    for (var k=0; k<4; k++) {\n        bn_1.b[k] <== bn_1_b[k];\n        enc.plaintext[idx] <== bn_1_b[k];\n        idx++;\n        for (var i=0; i<26; i++) {\n            for (var j=0; j<26; j++) {\n                bn_1.in[i][j][k] <== conv2d_1.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<26; i++) {\n        for (var j=0; j<26; j++) {\n            for (var k=0; k<4; k++) {\n                poly_1[i][j][k] = Poly(10**6);\n                poly_1[i][j][k].in <== bn_1.out[i][j][k];\n                avg2d_1.in[i][j][k] <== poly_1[i][j][k].out;\n            }\n        }\n    }\n\n    for (var i=0; i<13; i++) {\n        for (var j=0; j<13; j++) {\n            for (var k=0; k<4; k++) {\n                conv2d_2.in[i][j][k] <== avg2d_1.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<3; i++) {\n        for (var j=0; j<3; j++) {\n            for (var k=0; k<4; k++) {   \n                for (var m=0; m<8; m++) {\n                    conv2d_2.weights[i][j][k][m] <== conv2d_2_weights[i][j][k][m];\n                    enc.plaintext[idx] <== conv2d_2_weights[i][j][k][m];\n                    idx++;\n                }\n            }\n        }\n    }\n\n    for (var m=0; m<8; m++) {\n        conv2d_2.bias[m] <== conv2d_2_bias[m];\n        enc.plaintext[idx] <== conv2d_2_bias[m];\n        idx++;\n    }\n\n    for (var k=0; k<8; k++) {\n        bn_2.a[k] <== bn_2_a[k];\n        enc.plaintext[idx] <== bn_2_a[k];\n        idx++;\n    }\n\n    for (var k=0; k<8; k++) {\n        bn_2.b[k] <== bn_2_b[k];\n        enc.plaintext[idx] <== bn_2_b[k];\n        idx++;\n        for (var i=0; i<11; i++) {\n            for (var j=0; j<11; j++) {\n                bn_2.in[i][j][k] <== conv2d_2.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<11; i++) {\n        for (var j=0; j<11; j++) {\n            for (var k=0; k<8; k++) {\n                poly_2[i][j][k] = Poly(10**18);\n                poly_2[i][j][k].in <== bn_2.out[i][j][k];\n                avg2d_2.in[i][j][k] <== poly_2[i][j][k].out;\n            }\n        }\n    }\n\n    for (var i=0; i<5; i++) {\n        for (var j=0; j<5; j++) {\n            for (var k=0; k<8; k++) {\n                flatten.in[i][j][k] <== avg2d_2.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<200; i++) {\n        dense.in[i] <== flatten.out[i];\n        for (var j=0; j<10; j++) {\n            dense.weights[i][j] <== dense_weights[i][j];\n            enc.plaintext[idx] <== dense_weights[i][j];\n            idx++;\n        }\n    }\n\n    for (var i=0; i<10; i++) {\n        dense.bias[i] <== dense_bias[i];\n        enc.plaintext[idx] <== dense_bias[i];\n        idx++;\n    }\n\n    for (var i=0; i<10; i++) {\n        argmax.in[i] <== dense.out[i];\n    }\n\n    out <== argmax.out;\n\n    for (var i=0; i<3*3*1*4+4+4+4+3*3*4*8+8+8+8+200*10+10+1; i++) {\n        message[i] <== enc.out[i];\n    }\n}\n\ncomponent main = encrypted_mnist_latest();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/mnist_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Conv2D.circom\";\ninclude \"../../circuits/Dense.circom\";\ninclude \"../../circuits/ArgMax.circom\";\ninclude \"../../circuits/ReLU.circom\";\ninclude \"../../circuits/AveragePooling2D.circom\";\ninclude \"../../circuits/BatchNormalization2D.circom\";\ninclude \"../../circuits/Flatten2D.circom\";\n\ntemplate mnist() {\n    signal input in[28][28][1];\n\n    signal input conv2d_1_weights[3][3][1][4];\n    signal input conv2d_1_bias[4];\n    signal input conv2d_1_out[26][26][4];\n    signal input conv2d_1_remainder[26][26][4];\n\n    signal input bn_1_a[4];\n    signal input bn_1_b[4];\n    signal input bn_1_out[26][26][4];\n    signal input bn_1_remainder[26][26][4];\n\n    signal input relu_1_out[26][26][4];\n\n    signal input avg2d_1_out[13][13][4];\n    signal input avg2d_1_remainder[13][13][4];\n\n    signal input conv2d_2_weights[3][3][4][8];\n    signal input conv2d_2_bias[8];\n    signal input conv2d_2_out[11][11][8];\n    signal input conv2d_2_remainder[11][11][8];\n\n    signal input bn_2_a[8];\n    signal input bn_2_b[8];\n    signal input bn_2_out[11][11][8];\n    signal input bn_2_remainder[11][11][8];\n\n    signal input relu_2_out[11][11][8];\n\n    signal input avg2d_2_out[5][5][8];\n    signal input avg2d_2_remainder[5][5][8];\n\n    signal input flatten_out[200];\n\n    signal input dense_weights[200][10];\n    signal input dense_bias[10];\n    signal input dense_out[10];\n    signal input dense_remainder[10];\n\n    signal input argmax_out;\n\n    signal output out;\n\n    component conv2d_1 = Conv2D(28,28,1,4,3,1,10**18);\n    component bn_1 = BatchNormalization2D(26,26,4,10**18);\n    component relu_1[26][26][4];\n    component avg2d_1 = AveragePooling2D(26,26,4,2,2);\n    component conv2d_2 = Conv2D(13,13,4,8,3,1,10**18);\n    component bn_2 = BatchNormalization2D(11,11,8,10**18);\n    component relu_2[11][11][8];\n    component avg2d_2 = AveragePooling2D(11,11,8,2,2);\n    component flatten = Flatten2D(5,5,8);\n    component dense = Dense(200,10,10**18);\n    component argmax = ArgMax(10);\n\n    for (var i=0; i<28; i++) {\n        for (var j=0; j<28; j++) {\n            conv2d_1.in[i][j][0] <== in[i][j][0];\n        }\n    }\n\n    for (var m=0; m<4; m++) {\n        for (var i=0; i<3; i++) {\n            for (var j=0; j<3; j++) {\n                conv2d_1.weights[i][j][0][m] <== conv2d_1_weights[i][j][0][m];\n            }\n        }\n        conv2d_1.bias[m] <== conv2d_1_bias[m];\n    }\n\n    for (var k=0; k<4; k++) {\n        bn_1.a[k] <== bn_1_a[k];\n        bn_1.b[k] <== bn_1_b[k];\n        for (var i=0; i<26; i++) {\n            for (var j=0; j<26; j++) {\n                conv2d_1.out[i][j][k] <== conv2d_1_out[i][j][k];\n                conv2d_1.remainder[i][j][k] <== conv2d_1_remainder[i][j][k];\n                bn_1.in[i][j][k] <== conv2d_1.out[i][j][k];\n            }\n        }\n    }\n\n\n    for (var i=0; i<26; i++) {\n        for (var j=0; j<26; j++) {\n            for (var k=0; k<4; k++) {\n                bn_1.out[i][j][k] <== bn_1_out[i][j][k];\n                bn_1.remainder[i][j][k] <== bn_1_remainder[i][j][k];\n                relu_1[i][j][k] = ReLU();\n                relu_1[i][j][k].in <== bn_1.out[i][j][k];\n                relu_1[i][j][k].out <== relu_1_out[i][j][k];\n                avg2d_1.in[i][j][k] <== relu_1[i][j][k].out;\n            }\n        }\n    }\n\n    for (var i=0; i<13; i++) {\n        for (var j=0; j<13; j++) {\n            for (var k=0; k<4; k++) {\n                avg2d_1.out[i][j][k] <== avg2d_1_out[i][j][k];\n                avg2d_1.remainder[i][j][k] <== avg2d_1_remainder[i][j][k];\n                conv2d_2.in[i][j][k] <== avg2d_1.out[i][j][k];\n            }\n        }\n    }\n\n    for (var m=0; m<8; m++) {\n        for (var i=0; i<3; i++) {\n            for (var j=0; j<3; j++) {\n                for (var k=0; k<4; k++) {\n                    conv2d_2.weights[i][j][k][m] <== conv2d_2_weights[i][j][k][m];\n                }\n            }\n        }\n        conv2d_2.bias[m] <== conv2d_2_bias[m];\n    }\n\n    for (var k=0; k<8; k++) {\n        bn_2.a[k] <== bn_2_a[k];\n        bn_2.b[k] <== bn_2_b[k];\n        for (var i=0; i<11; i++) {\n            for (var j=0; j<11; j++) {\n                conv2d_2.out[i][j][k] <== conv2d_2_out[i][j][k];\n                conv2d_2.remainder[i][j][k] <== conv2d_2_remainder[i][j][k];\n                bn_2.in[i][j][k] <== conv2d_2.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<11; i++) {\n        for (var j=0; j<11; j++) {\n            for (var k=0; k<8; k++) {\n                bn_2.out[i][j][k] <== bn_2_out[i][j][k];\n                bn_2.remainder[i][j][k] <== bn_2_remainder[i][j][k];\n                relu_2[i][j][k] = ReLU();\n                relu_2[i][j][k].in <== bn_2.out[i][j][k];\n                relu_2[i][j][k].out <== relu_2_out[i][j][k];\n                avg2d_2.in[i][j][k] <== relu_2[i][j][k].out;\n            }\n        }\n    }\n\n    for (var i=0; i<5; i++) {\n        for (var j=0; j<5; j++) {\n            for (var k=0; k<8; k++) {\n                avg2d_2.out[i][j][k] <== avg2d_2_out[i][j][k];\n                avg2d_2.remainder[i][j][k] <== avg2d_2_remainder[i][j][k];\n                flatten.in[i][j][k] <== avg2d_2.out[i][j][k];\n            }\n        }\n    }\n\n    for (var i=0; i<200; i++) {\n        flatten.out[i] <== flatten_out[i];\n        dense.in[i] <== flatten.out[i];\n        for (var j=0; j<10; j++) {\n            dense.weights[i][j] <== dense_weights[i][j];\n        }\n    }\n\n    for (var i=0; i<10; i++) {\n        dense.bias[i] <== dense_bias[i];\n    }\n\n    for (var i=0; i<10; i++) {\n        dense.out[i] <== dense_out[i];\n        dense.remainder[i] <== dense_remainder[i];\n        argmax.in[i] <== dense.out[i];\n    }\n\n    argmax.out <== argmax_out;\n    out <== argmax.out;\n}\n\ncomponent main = mnist();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/model1_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/Dense.circom\";\ninclude \"../../circuits/ReLU.circom\";\n\ntemplate model1() {\n    signal input in[3];\n\n    signal input Dense32weights[3][2];\n    signal input Dense32bias[2];\n    signal input Dense32out[2];\n    signal input Dense32remainder[2];\n\n    signal input ReLUout[2];\n\n    signal input Dense21weights[2][1];\n    signal input Dense21bias[1];\n    signal input Dense21out[1];\n    signal input Dense21remainder[1];\n\n    signal output out;\n\n    component Dense32 = Dense(3,2, 10**36);\n    component relu[2];\n    component Dense21 = Dense(2,1, 10**36);\n\n    for (var i=0; i<3; i++) {\n        Dense32.in[i] <== in[i];\n        for (var j=0; j<2; j++) {\n            Dense32.weights[i][j] <== Dense32weights[i][j];\n        }\n    }\n\n    for (var i=0; i<2; i++) {\n        Dense32.bias[i] <== 0;\n        Dense32.out[i] <== Dense32out[i];\n        Dense32.remainder[i] <== Dense32remainder[i];\n    }\n\n    for (var i=0; i<2; i++) {\n        relu[i] = ReLU();\n        relu[i].in <== Dense32.out[i];\n        relu[i].out <== ReLUout[i];\n    }\n\n    for (var i=0; i<2; i++) {\n        Dense21.in[i] <== relu[i].out;\n        Dense21.weights[i][0] <== Dense21weights[i][0];\n    }\n    \n    Dense21.bias[0] <== 0;\n    Dense21.out[0] <== Dense21out[0];\n    Dense21.remainder[0] <== Dense21remainder[0];\n\n    out <== Dense21.out[0];\n}\n\ncomponent main = model1();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/circuits/publicKey_test.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../circuits/crypto/publickey_derivation.circom\";\n\ncomponent main = PublicKey();"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/encryption.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst { Keypair } = require(\"./modules/maci-domainobjs\");\nconst { encrypt, decrypt } = require(\"./modules/maci-crypto\");\n\ndescribe(\"crypto circuits test\", function () {\n    this.timeout(100000000);\n\n    it(\"public key test\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"publicKey_test.circom\"));\n\n        const keypair = new Keypair();\n\n        const INPUT = {\n            'private_key': keypair.privKey.asCircuitInputs(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]), Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]), Fr.e(keypair.pubKey.rawPubKey[0])));\n        assert(Fr.eq(Fr.e(witness[2]), Fr.e(keypair.pubKey.rawPubKey[1])));\n    });\n\n    it(\"ecdh full circuit test\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"ecdh_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const INPUT = {\n            'private_key': keypair.privKey.asCircuitInputs(),\n            'public_key': keypair2.pubKey.asCircuitInputs(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]), Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]), Fr.e(ecdhSharedKey)));\n\n    });\n\n    it(\"encrypt/decrypt test\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"encryptDecrypt_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const INPUT = {\n            'message': '123456789',\n            'shared_key': ecdhSharedKey.toString(),\n            'private_key': keypair.privKey.asCircuitInputs(),\n            'public_key': keypair2.pubKey.asCircuitInputs(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        //console.log(witness);\n\n        assert(Fr.eq(Fr.e(witness[0]), Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]), Fr.e(1)));\n\n    });\n\n    it(\"encrypt in circom, decrypt in js\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"encrypt_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const plaintext = 1234567890n;\n\n        const INPUT = {\n            'plaintext': plaintext.toString(),\n            'shared_key': ecdhSharedKey.toString(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        output1 = witness[1];\n        output2 = witness[2];\n\n        const ciphertext = {\n            iv: output1,\n            data: [output2],\n        }\n\n        assert(Fr.eq(Fr.e(decrypt(ciphertext, ecdhSharedKey)[0]), Fr.e(plaintext)));\n    });\n\n    it(\"encrypt in js, decrypt in circom\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"decrypt_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const plaintext = 1234567890n;\n\n        const ciphertext = encrypt([plaintext], ecdhSharedKey);\n\n        const INPUT = {\n            'message': [ciphertext.iv.toString(), ciphertext.data[0].toString()],\n            'shared_key': ecdhSharedKey.toString(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[1]), Fr.e(plaintext)));\n\n    });\n\n    it(\"encrypt multiple in circom, decrypt in js\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"encryptMultiple_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const plaintext = [...Array(1000).keys()];\n\n        const INPUT = {\n            'plaintext': plaintext.map(String),\n            'shared_key': ecdhSharedKey.toString(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        const ciphertext = {\n            iv: witness[1],\n            data: witness.slice(2,1002),\n        }\n\n        decryptedText = decrypt(ciphertext, ecdhSharedKey);\n\n        for (let i=0; i<1000; i++) {\n            assert(Fr.eq(Fr.e(decryptedText[i]), Fr.e(plaintext[i])));\n        }\n        \n    });\n\n    it(\"encrypt multiple in js, decrypt in circom\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"decryptMultiple_test.circom\"));\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        const plaintext = ([...Array(1000).keys()]).map(BigInt);\n\n        const ciphertext = encrypt(plaintext, ecdhSharedKey);\n\n        const INPUT = {\n            'message': [ciphertext.iv.toString(), ...ciphertext.data.map(String)],\n            'shared_key': ecdhSharedKey.toString(),\n        }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        for (let i=0; i<1000; i++) {\n            assert(Fr.eq(Fr.e(witness[i+1]), Fr.e(plaintext[i])));\n        }\n\n    });\n\n    // TODO: encrypt a model\n    it.skip(\"encrypt entire model in circom, decrypt in js\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"encrypted_mnist_latest_test.circom\"));\n        const json = require(\"../models/mnist_latest_input.json\");\n\n        let INPUT = {};\n        let plaintext = [\n            ...json['conv2d_1_weights'],\n            ...json['conv2d_1_bias'],\n            ...json['bn_1_a'],\n            ...json['bn_1_b'],\n            ...json['conv2d_2_weights'],\n            ...json['conv2d_2_bias'],\n            ...json['bn_2_a'],\n            ...json['bn_2_b'],\n            ...json['dense_weights'],\n            ...json['dense_bias'],\n        ];\n\n        for (const [key, value] of Object.entries(json)) {\n            if (Array.isArray(value)) {\n                let tmpArray = [];\n                for (let i = 0; i < value.flat().length; i++) {\n                    tmpArray.push(Fr.e(value.flat()[i]));\n                }\n                INPUT[key] = tmpArray;\n            } else {\n                INPUT[key] = Fr.e(value);\n            }\n        }\n\n        const keypair = new Keypair();\n        const keypair2 = new Keypair();\n\n        const ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        INPUT['private_key'] = keypair.privKey.asCircuitInputs();\n        INPUT['public_key'] = keypair2.pubKey.asCircuitInputs();\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));\n\n        const ciphertext = {\n            iv: witness[2],\n            data: witness.slice(3,2373),\n        }\n\n        decryptedText = decrypt(ciphertext, ecdhSharedKey);\n\n        for (let i=0; i<2370; i++) {\n            assert(Fr.eq(Fr.e(decryptedText[i]), Fr.e(plaintext[i])));\n        }\n        \n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/mnist.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst INPUT = require(\"../models/mnist_input.json\");\n\ndescribe(\"mnist test\", function () {\n    this.timeout(100000000);\n\n    it(\"should return correct output\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"mnist_test.circom\"));\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/model1.js",
        "content": "const chai = require(\"chai\");\nconst path = require(\"path\");\n\nconst wasm_tester = require(\"circom_tester\").wasm;\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst INPUT = require(\"../models/model1_input.json\");\n\ndescribe(\"model1 test\", function () {\n    this.timeout(100000000);\n\n    it(\"should return correct output\", async () => {\n        const circuit = await wasm_tester(path.join(__dirname, \"circuits\", \"model1_test.circom\"));\n\n        // const INPUT = {\n        //     \"in\": json.in,\n        //     \"Dense32weights\": json.Dense32weights,\n        //     \"Dense32bias\": json.Dense32bias,\n        //     \"Dense32out\": json.Dense32out,\n        //     \"Dense32remainder\": json.Dense32remainder,\n        //     \"ReLUout\": json.ReLUout,\n        //     \"Dense21weights\": json.Dense21weights,\n        //     \"Dense21bias\": json.Dense21bias,\n        //     \"Dense21out\": json.Dense21out,\n        //     \"Dense21remainder\": json.Dense21remainder,\n        // }\n\n        const witness = await circuit.calculateWitness(INPUT, true);\n\n        assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        assert(Fr.eq(witness[1],Fr.e(INPUT.Dense21out[0])));\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/circomlib-0.5.1.js",
        "content": "exports.smt = require(\"./src/smt\");\nexports.eddsa = require(\"./src/eddsa\");\nexports.mimc7 = require(\"./src/mimc7\");\nexports.mimcsponge = require(\"./src/mimcsponge\");\nexports.babyJub = require(\"./src/babyjub\");\nexports.pedersenHash = require(\"./src/pedersenHash\");\nexports.SMT = require(\"./src/smt\").SMT;\nexports.SMTMemDB = require(\"./src/smt_memdb\");\nexports.poseidon = require(\"./src/poseidon\");\n\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/maci-crypto.js",
        "content": "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.unpackPubKey = exports.packPubKey = exports.bigInt2Buffer = exports.SNARK_FIELD_SIZE = exports.NOTHING_UP_MY_SLEEVE_PUBKEY = exports.NOTHING_UP_MY_SLEEVE = exports.formatPrivKeyForBabyJub = exports.unstringifyBigInts = exports.stringifyBigInts = exports.verifySignature = exports.hashLeftRight = exports.hash11 = exports.hash5 = exports.hashOne = exports.sign = exports.decrypt = exports.encrypt = exports.genEcdhSharedKey = exports.genKeypair = exports.genPubKey = exports.genPrivKey = exports.genRandomSalt = void 0;\nconst assert = require('assert');\nconst crypto = require(\"crypto\");\nconst ethers = require(\"ethers\");\nconst ff = require('ffjavascript');\nconst createBlakeHash = require('blake-hash');\nconst circomlib_0_5_1_1 = require(\"./circomlib-0.5.1\");\nconst stringifyBigInts = ff.utils.stringifyBigInts;\nexports.stringifyBigInts = stringifyBigInts;\nconst unstringifyBigInts = ff.utils.unstringifyBigInts;\nexports.unstringifyBigInts = unstringifyBigInts;\nconst SNARK_FIELD_SIZE = BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617');\nexports.SNARK_FIELD_SIZE = SNARK_FIELD_SIZE;\n// A nothing-up-my-sleeve zero value\n// Should be equal to 8370432830353022751713833565135785980866757267633941821328460903436894336785\nconst NOTHING_UP_MY_SLEEVE = BigInt(ethers.utils.solidityKeccak256(['bytes'], [ethers.utils.toUtf8Bytes('Maci')])) % SNARK_FIELD_SIZE;\nexports.NOTHING_UP_MY_SLEEVE = NOTHING_UP_MY_SLEEVE;\n// The pubkey is the first Pedersen base point from iden3's circomlib\n// See https://github.com/iden3/circomlib/blob/d5ed1c3ce4ca137a6b3ca48bec4ac12c1b38957a/src/pedersen_printbases.js\nconst NOTHING_UP_MY_SLEEVE_PUBKEY = [\n    BigInt('10457101036533406547632367118273992217979173478358440826365724437999023779287'),\n    BigInt('19824078218392094440610104313265183977899662750282163392862422243483260492317')\n];\nexports.NOTHING_UP_MY_SLEEVE_PUBKEY = NOTHING_UP_MY_SLEEVE_PUBKEY;\n/*\n * Convert a BigInt to a Buffer\n */\nconst bigInt2Buffer = (i) => {\n    let hexStr = i.toString(16);\n    while (hexStr.length < 64) {\n        hexStr = '0' + hexStr;\n    }\n    return Buffer.from(hexStr, 'hex');\n};\nexports.bigInt2Buffer = bigInt2Buffer;\n// Hash up to 2 elements\nconst poseidonT3 = (inputs) => {\n    assert(inputs.length === 2);\n    return (0, circomlib_0_5_1_1.poseidon)(inputs);\n};\n// Hash up to 5 elements\nconst poseidonT6 = (inputs) => {\n    assert(inputs.length === 5);\n    return (0, circomlib_0_5_1_1.poseidon)(inputs);\n};\nconst hash5 = (elements) => {\n    const elementLength = elements.length;\n    if (elements.length > 5) {\n        throw new Error(`elements length should not greater than 5, got ${elements.length}`);\n    }\n    const elementsPadded = elements.slice();\n    if (elementLength < 5) {\n        for (let i = elementLength; i < 5; i++) {\n            elementsPadded.push(BigInt(0));\n        }\n    }\n    return poseidonT6(elementsPadded);\n};\nexports.hash5 = hash5;\n/*\n * A convenience function for to use Poseidon to hash a Plaintext with\n * no more than 11 elements\n */\nconst hash11 = (elements) => {\n    const elementLength = elements.length;\n    if (elementLength > 11) {\n        throw new TypeError(`elements length should not greater than 11, got ${elementLength}`);\n    }\n    const elementsPadded = elements.slice();\n    if (elementLength < 11) {\n        for (let i = elementLength; i < 11; i++) {\n            elementsPadded.push(BigInt(0));\n        }\n    }\n    return poseidonT3([\n        poseidonT3([\n            poseidonT6(elementsPadded.slice(0, 5)),\n            poseidonT6(elementsPadded.slice(5, 10))\n        ]),\n        elementsPadded[10]\n    ]);\n};\nexports.hash11 = hash11;\n/*\n * Hash a single BigInt with the Poseidon hash function\n */\nconst hashOne = (preImage) => {\n    return poseidonT3([preImage, BigInt(0)]);\n};\nexports.hashOne = hashOne;\n/*\n * Hash two BigInts with the Poseidon hash function\n */\nconst hashLeftRight = (left, right) => {\n    return poseidonT3([left, right]);\n};\nexports.hashLeftRight = hashLeftRight;\n/*\n * Returns a BabyJub-compatible random value. We create it by first generating\n * a random value (initially 256 bits large) modulo the snark field size as\n * described in EIP197. This results in a key size of roughly 253 bits and no\n * more than 254 bits. To prevent modulo bias, we then use this efficient\n * algorithm:\n * http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/lib/libc/crypt/arc4random_uniform.c\n * @return A BabyJub-compatible random value.\n */\nconst genRandomBabyJubValue = () => {\n    // Prevent modulo bias\n    //const lim = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000')\n    //const min = (lim - SNARK_FIELD_SIZE) % SNARK_FIELD_SIZE\n    const min = BigInt('6350874878119819312338956282401532410528162663560392320966563075034087161851');\n    let rand;\n    while (true) {\n        rand = BigInt('0x' + crypto.randomBytes(32).toString('hex'));\n        if (rand >= min) {\n            break;\n        }\n    }\n    const privKey = rand % SNARK_FIELD_SIZE;\n    assert(privKey < SNARK_FIELD_SIZE);\n    return privKey;\n};\n/*\n * @return A BabyJub-compatible private key.\n */\nconst genPrivKey = () => {\n    return genRandomBabyJubValue();\n};\nexports.genPrivKey = genPrivKey;\n/*\n * @return A BabyJub-compatible salt.\n */\nconst genRandomSalt = () => {\n    return genRandomBabyJubValue();\n};\nexports.genRandomSalt = genRandomSalt;\n/*\n * An internal function which formats a random private key to be compatible\n * with the BabyJub curve. This is the format which should be passed into the\n * PublicKey and other circuits.\n */\nconst formatPrivKeyForBabyJub = (privKey) => {\n    const sBuff = circomlib_0_5_1_1.eddsa.pruneBuffer(createBlakeHash(\"blake512\").update(bigInt2Buffer(privKey)).digest().slice(0, 32));\n    const s = ff.utils.leBuff2int(sBuff);\n    return ff.Scalar.shr(s, 3);\n};\nexports.formatPrivKeyForBabyJub = formatPrivKeyForBabyJub;\n/*\n * Losslessly reduces the size of the representation of a public key\n * @param pubKey The public key to pack\n * @return A packed public key\n */\nconst packPubKey = (pubKey) => {\n    return circomlib_0_5_1_1.babyJub.packPoint(pubKey);\n};\nexports.packPubKey = packPubKey;\n/*\n * Restores the original PubKey from its packed representation\n * @param packed The value to unpack\n * @return The unpacked public key\n */\nconst unpackPubKey = (packed) => {\n    return circomlib_0_5_1_1.babyJub.unpackPoint(packed);\n};\nexports.unpackPubKey = unpackPubKey;\n/*\n * @param privKey A private key generated using genPrivKey()\n * @return A public key associated with the private key\n */\nconst genPubKey = (privKey) => {\n    privKey = BigInt(privKey.toString());\n    assert(privKey < SNARK_FIELD_SIZE);\n    return circomlib_0_5_1_1.eddsa.prv2pub(bigInt2Buffer(privKey));\n};\nexports.genPubKey = genPubKey;\nconst genKeypair = () => {\n    const privKey = genPrivKey();\n    const pubKey = genPubKey(privKey);\n    const Keypair = { privKey, pubKey };\n    return Keypair;\n};\nexports.genKeypair = genKeypair;\n/*\n * Generates an Elliptic-curve Diffie\u2013Hellman shared key given a private key\n * and a public key.\n * @return The ECDH shared key.\n */\nconst genEcdhSharedKey = (privKey, pubKey) => {\n    return circomlib_0_5_1_1.babyJub.mulPointEscalar(pubKey, formatPrivKeyForBabyJub(privKey))[0];\n};\nexports.genEcdhSharedKey = genEcdhSharedKey;\n/*\n * Encrypts a plaintext using a given key.\n * @return The ciphertext.\n */\nconst encrypt = (plaintext, sharedKey) => {\n    // Generate the IV\n    const iv = circomlib_0_5_1_1.mimc7.multiHash(plaintext, BigInt(0));\n    const ciphertext = {\n        iv,\n        data: plaintext.map((e, i) => {\n            return e + circomlib_0_5_1_1.mimc7.hash(sharedKey, iv + BigInt(i));\n        }),\n    };\n    // TODO: add asserts here\n    return ciphertext;\n};\nexports.encrypt = encrypt;\n/*\n * Decrypts a ciphertext using a given key.\n * @return The plaintext.\n */\nconst decrypt = (ciphertext, sharedKey) => {\n    const plaintext = ciphertext.data.map((e, i) => {\n        return BigInt(e) - BigInt(circomlib_0_5_1_1.mimc7.hash(sharedKey, BigInt(ciphertext.iv) + BigInt(i)));\n    });\n    return plaintext;\n};\nexports.decrypt = decrypt;\n/*\n * Generates a signature given a private key and plaintext.\n * @return The signature.\n */\nconst sign = (privKey, msg) => {\n    return circomlib_0_5_1_1.eddsa.signPoseidon(bigInt2Buffer(privKey), msg);\n};\nexports.sign = sign;\n/*\n * Checks whether the signature of the given plaintext was created using the\n * private key associated with the given public key.\n * @return True if the signature is valid, and false otherwise.\n */\nconst verifySignature = (msg, signature, pubKey) => {\n    return circomlib_0_5_1_1.eddsa.verifyPoseidon(msg, signature, pubKey);\n};\nexports.verifySignature = verifySignature;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/maci-domainobjs.js",
        "content": "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PrivKey = exports.PubKey = exports.Keypair = exports.Message = exports.Command = exports.StateLeaf = void 0;\nconst assert = require('assert');\nconst maci_crypto_1 = require(\"./maci-crypto\");\nconst SERIALIZED_PRIV_KEY_PREFIX = 'macisk.';\nclass PrivKey {\n    constructor(rawPrivKey) {\n        this.copy = () => {\n            return new PrivKey(BigInt(this.rawPrivKey.toString()));\n        };\n        this.asCircuitInputs = () => {\n            return (0, maci_crypto_1.formatPrivKeyForBabyJub)(this.rawPrivKey).toString();\n        };\n        this.serialize = () => {\n            return SERIALIZED_PRIV_KEY_PREFIX + this.rawPrivKey.toString(16);\n        };\n        this.rawPrivKey = rawPrivKey;\n    }\n}\nexports.PrivKey = PrivKey;\nPrivKey.unserialize = (s) => {\n    const x = s.slice(SERIALIZED_PRIV_KEY_PREFIX.length);\n    return new PrivKey(BigInt('0x' + x));\n};\nPrivKey.isValidSerializedPrivKey = (s) => {\n    const correctPrefix = s.startsWith(SERIALIZED_PRIV_KEY_PREFIX);\n    const x = s.slice(SERIALIZED_PRIV_KEY_PREFIX.length);\n    let validValue = false;\n    try {\n        const value = BigInt('0x' + x);\n        validValue = value < maci_crypto_1.SNARK_FIELD_SIZE;\n    }\n    catch {\n        // comment to make linter happy \n    }\n    return correctPrefix && validValue;\n};\nconst SERIALIZED_PUB_KEY_PREFIX = 'macipk.';\nclass PubKey {\n    constructor(rawPubKey) {\n        this.copy = () => {\n            return new PubKey([\n                BigInt(this.rawPubKey[0].toString()),\n                BigInt(this.rawPubKey[1].toString()),\n            ]);\n        };\n        this.asContractParam = () => {\n            return {\n                x: this.rawPubKey[0].toString(),\n                y: this.rawPubKey[1].toString(),\n            };\n        };\n        this.asCircuitInputs = () => {\n            return this.rawPubKey.map((x) => x.toString());\n        };\n        this.asArray = () => {\n            return [\n                this.rawPubKey[0],\n                this.rawPubKey[1],\n            ];\n        };\n        this.serialize = () => {\n            // Blank leaves have pubkey [0, 0], which packPubKey does not support\n            if (BigInt(this.rawPubKey[0]) === BigInt(0) &&\n                BigInt(this.rawPubKey[1]) === BigInt(0)) {\n                return SERIALIZED_PUB_KEY_PREFIX + 'z';\n            }\n            const packed = (0, maci_crypto_1.packPubKey)(this.rawPubKey).toString('hex');\n            return SERIALIZED_PUB_KEY_PREFIX + packed.toString();\n        };\n        assert(rawPubKey.length === 2);\n        assert(rawPubKey[0] < maci_crypto_1.SNARK_FIELD_SIZE);\n        assert(rawPubKey[1] < maci_crypto_1.SNARK_FIELD_SIZE);\n        this.rawPubKey = rawPubKey;\n    }\n}\nexports.PubKey = PubKey;\nPubKey.unserialize = (s) => {\n    // Blank leaves have pubkey [0, 0], which packPubKey does not support\n    if (s === SERIALIZED_PUB_KEY_PREFIX + 'z') {\n        return new PubKey([BigInt(0), BigInt(0)]);\n    }\n    const len = SERIALIZED_PUB_KEY_PREFIX.length;\n    const packed = Buffer.from(s.slice(len), 'hex');\n    return new PubKey((0, maci_crypto_1.unpackPubKey)(packed));\n};\nPubKey.isValidSerializedPubKey = (s) => {\n    const correctPrefix = s.startsWith(SERIALIZED_PUB_KEY_PREFIX);\n    let validValue = false;\n    try {\n        PubKey.unserialize(s);\n        validValue = true;\n    }\n    catch {\n        // comment to make linter happy\n    }\n    return correctPrefix && validValue;\n};\nclass Keypair {\n    constructor(privKey) {\n        this.copy = () => {\n            return new Keypair(this.privKey.copy());\n        };\n        if (privKey) {\n            this.privKey = privKey;\n            this.pubKey = new PubKey((0, maci_crypto_1.genPubKey)(privKey.rawPrivKey));\n        }\n        else {\n            const rawKeyPair = (0, maci_crypto_1.genKeypair)();\n            this.privKey = new PrivKey(rawKeyPair.privKey);\n            this.pubKey = new PubKey(rawKeyPair.pubKey);\n        }\n    }\n    static genEcdhSharedKey(privKey, pubKey) {\n        return (0, maci_crypto_1.genEcdhSharedKey)(privKey.rawPrivKey, pubKey.rawPubKey);\n    }\n    equals(keypair) {\n        const equalPrivKey = this.privKey.rawPrivKey === keypair.privKey.rawPrivKey;\n        const equalPubKey = this.pubKey.rawPubKey[0] === keypair.pubKey.rawPubKey[0] &&\n            this.pubKey.rawPubKey[1] === keypair.pubKey.rawPubKey[1];\n        // If this assertion fails, something is very wrong and this function\n        // should not return anything \n        // XOR is equivalent to: (x && !y) || (!x && y ) \n        const x = (equalPrivKey && equalPubKey);\n        const y = (!equalPrivKey && !equalPubKey);\n        assert((x && !y) || (!x && y));\n        return equalPrivKey;\n    }\n}\nexports.Keypair = Keypair;\n/*\n * An encrypted command and signature.\n */\nclass Message {\n    constructor(iv, data) {\n        this.asArray = () => {\n            return [\n                this.iv,\n                ...this.data,\n            ];\n        };\n        this.asContractParam = () => {\n            return {\n                iv: this.iv.toString(),\n                data: this.data.map((x) => x.toString()),\n            };\n        };\n        this.asCircuitInputs = () => {\n            return this.asArray();\n        };\n        this.hash = () => {\n            return (0, maci_crypto_1.hash11)(this.asArray());\n        };\n        this.copy = () => {\n            return new Message(BigInt(this.iv.toString()), this.data.map((x) => BigInt(x.toString())));\n        };\n        assert(data.length === 10);\n        this.iv = iv;\n        this.data = data;\n    }\n}\nexports.Message = Message;\n/*\n * A leaf in the state tree, which maps public keys to votes\n */\nclass StateLeaf {\n    constructor(pubKey, voteOptionTreeRoot, voiceCreditBalance, nonce) {\n        this.asArray = () => {\n            return [\n                ...this.pubKey.asArray(),\n                this.voteOptionTreeRoot,\n                this.voiceCreditBalance,\n                this.nonce,\n            ];\n        };\n        this.asCircuitInputs = () => {\n            return this.asArray();\n        };\n        this.hash = () => {\n            return (0, maci_crypto_1.hash5)(this.asArray());\n        };\n        this.serialize = () => {\n            const j = {\n                pubKey: this.pubKey.serialize(),\n                voteOptionTreeRoot: this.voteOptionTreeRoot.toString(16),\n                voiceCreditBalance: this.voiceCreditBalance.toString(16),\n                nonce: this.nonce.toString(16),\n            };\n            return Buffer.from(JSON.stringify(j, null, 0), 'utf8').toString('base64');\n        };\n        this.pubKey = pubKey;\n        this.voteOptionTreeRoot = voteOptionTreeRoot;\n        this.voiceCreditBalance = voiceCreditBalance;\n        // The this is the current nonce. i.e. a user who has published 0 valid\n        // command should have this value at 0, and the first command should\n        // have a nonce of 1\n        this.nonce = nonce;\n    }\n    copy() {\n        return new StateLeaf(this.pubKey.copy(), BigInt(this.voteOptionTreeRoot.toString()), BigInt(this.voiceCreditBalance.toString()), BigInt(this.nonce.toString()));\n    }\n    static genBlankLeaf(emptyVoteOptionTreeRoot) {\n        return new StateLeaf(new PubKey(maci_crypto_1.NOTHING_UP_MY_SLEEVE_PUBKEY), emptyVoteOptionTreeRoot, BigInt(0), BigInt(0));\n    }\n    static genRandomLeaf() {\n        return new StateLeaf(new PubKey(maci_crypto_1.NOTHING_UP_MY_SLEEVE_PUBKEY), (0, maci_crypto_1.genRandomSalt)(), (0, maci_crypto_1.genRandomSalt)(), (0, maci_crypto_1.genRandomSalt)());\n    }\n}\nexports.StateLeaf = StateLeaf;\nStateLeaf.unserialize = (serialized) => {\n    const j = JSON.parse(Buffer.from(serialized, 'base64').toString('utf8'));\n    return new StateLeaf(PubKey.unserialize(j.pubKey), BigInt('0x' + j.voteOptionTreeRoot), BigInt('0x' + j.voiceCreditBalance), BigInt('0x' + j.nonce));\n};\n/*\n * Unencrypted data whose fields include the user's public key, vote etc.\n */\nclass Command {\n    constructor(stateIndex, newPubKey, voteOptionIndex, newVoteWeight, nonce, salt = (0, maci_crypto_1.genRandomSalt)()) {\n        this.copy = () => {\n            return new Command(BigInt(this.stateIndex.toString()), this.newPubKey.copy(), BigInt(this.voteOptionIndex.toString()), BigInt(this.newVoteWeight.toString()), BigInt(this.nonce.toString()), BigInt(this.salt.toString()));\n        };\n        this.asArray = () => {\n            return [\n                this.stateIndex,\n                ...this.newPubKey.asArray(),\n                this.voteOptionIndex,\n                this.newVoteWeight,\n                this.nonce,\n                this.salt,\n            ];\n        };\n        /*\n         * Check whether this command has deep equivalence to another command\n         */\n        this.equals = (command) => {\n            return this.stateIndex == command.stateIndex &&\n                this.newPubKey[0] == command.newPubKey[0] &&\n                this.newPubKey[1] == command.newPubKey[1] &&\n                this.voteOptionIndex == command.voteOptionIndex &&\n                this.newVoteWeight == command.newVoteWeight &&\n                this.nonce == command.nonce &&\n                this.salt == command.salt;\n        };\n        this.hash = () => {\n            return (0, maci_crypto_1.hash11)(this.asArray());\n        };\n        /*\n         * Signs this command and returns a Signature.\n         */\n        this.sign = (privKey) => {\n            return (0, maci_crypto_1.sign)(privKey.rawPrivKey, this.hash());\n        };\n        /*\n         * Returns true if the given signature is a correct signature of this\n         * command and signed by the private key associated with the given public\n         * key.\n         */\n        this.verifySignature = (signature, pubKey) => {\n            return (0, maci_crypto_1.verifySignature)(this.hash(), signature, pubKey.rawPubKey);\n        };\n        /*\n         * Encrypts this command along with a signature to produce a Message.\n         */\n        this.encrypt = (signature, sharedKey) => {\n            const plaintext = [\n                ...this.asArray(),\n                signature.R8[0],\n                signature.R8[1],\n                signature.S,\n            ];\n            const ciphertext = (0, maci_crypto_1.encrypt)(plaintext, sharedKey);\n            const message = new Message(ciphertext.iv, ciphertext.data);\n            return message;\n        };\n        this.stateIndex = stateIndex;\n        this.newPubKey = newPubKey;\n        this.voteOptionIndex = voteOptionIndex;\n        this.newVoteWeight = newVoteWeight;\n        this.nonce = nonce;\n        this.salt = salt;\n    }\n}\nexports.Command = Command;\n/*\n * Decrypts a Message to produce a Command.\n */\nCommand.decrypt = (message, sharedKey) => {\n    const decrypted = (0, maci_crypto_1.decrypt)(message, sharedKey);\n    const command = new Command(decrypted[0], new PubKey([decrypted[1], decrypted[2]]), decrypted[3], decrypted[4], decrypted[5], decrypted[6]);\n    const signature = {\n        R8: [decrypted[7], decrypted[8]],\n        S: decrypted[9],\n    };\n    return { command, signature };\n};\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/babyjub.js",
        "content": "const F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nconst utils = require(\"ffjavascript\").utils;\n\nexports.addPoint = addPoint;\nexports.mulPointEscalar = mulPointEscalar;\nexports.inCurve = inCurve;\nexports.inSubgroup = inSubgroup;\nexports.packPoint = packPoint;\nexports.unpackPoint = unpackPoint;\n\n\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst F = new F1Field(exports.p);\nexports.F = F;\n\nexports.Generator = [\n    F.e(\"995203441582195749578291179787384436505546430278305826713579947235728471134\"),\n    F.e(\"5472060717959818805561601436314318772137091100104008585924551046643952123905\")\n];\nexports.Base8 = [\n    F.e(\"5299619240641551281634865583518297030282874472190772894086521144482721001553\"),\n    F.e(\"16950150798460657717958625567821834550301663161624707787222815936182638968203\")\n];\nexports.order = Scalar.fromString(\"21888242871839275222246405745257275088614511777268538073601725287587578984328\");\nexports.subOrder = Scalar.shiftRight(exports.order, 3);\nexports.A = F.e(\"168700\");\nexports.D = F.e(\"168696\");\n\n\nfunction addPoint(a,b) {\n\n    const res = [];\n\n    /* does the equivalent of:\n     res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) *  bigInt(bigInt(\"1\") + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);\n    res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt(\"1\") - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);\n    */\n\n    const beta = F.mul(a[0],b[1]);\n    const gamma = F.mul(a[1],b[0]);\n    const delta = F.mul(\n        F.sub(a[1], F.mul(exports.A, a[0])),\n        F.add(b[0], b[1])\n    );\n    const tau = F.mul(beta, gamma);\n    const dtau = F.mul(exports.D, tau);\n\n    res[0] = F.div(\n        F.add(beta, gamma),\n        F.add(F.one, dtau)\n    );\n\n    res[1] = F.div(\n        F.add(delta, F.sub(F.mul(exports.A,beta), gamma)),\n        F.sub(F.one, dtau)\n    );\n\n    return res;\n}\n\nfunction mulPointEscalar(base, e) {\n    let res = [F.e(\"0\"),F.e(\"1\")];\n    let rem = e;\n    let exp = base;\n\n    while (! Scalar.isZero(rem)) {\n        if (Scalar.isOdd(rem)) {\n            res = addPoint(res, exp);\n        }\n        exp = addPoint(exp, exp);\n        rem = Scalar.shiftRight(rem, 1);\n    }\n\n    return res;\n}\n\nfunction inSubgroup(P) {\n    if (!inCurve(P)) return false;\n    const res= mulPointEscalar(P, exports.subOrder);\n    return (F.isZero(res[0]) && F.eq(res[1], F.one));\n}\n\nfunction inCurve(P) {\n\n    const x2 = F.square(P[0]);\n    const y2 = F.square(P[1]);\n\n    if (!F.eq(\n        F.add(F.mul(exports.A, x2), y2),\n        F.add(F.one, F.mul(F.mul(x2, y2), exports.D)))) return false;\n\n    return true;\n}\n\nfunction packPoint(P) {\n    const buff = utils.leInt2Buff(P[1], 32);\n    if (F.lt(P[0], F.zero)) {\n        buff[31] = buff[31] | 0x80;\n    }\n    return buff;\n}\n\nfunction unpackPoint(_buff) {\n    const buff = Buffer.from(_buff);\n    let sign = false;\n    const P = new Array(2);\n    if (buff[31] & 0x80) {\n        sign = true;\n        buff[31] = buff[31] & 0x7F;\n    }\n    P[1] = utils.leBuff2int(buff);\n    if (Scalar.gt(P[1], exports.p)) return null;\n\n    const y2 = F.square(P[1]);\n\n    let x = F.sqrt(F.div(\n        F.sub(F.one, y2),\n        F.sub(exports.A, F.mul(exports.D, y2))));\n\n    if (x == null) return null;\n\n    if (sign) x = F.neg(x);\n\n    P[0] = x;\n\n    return P;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/eddsa.js",
        "content": "const createBlakeHash = require(\"blake-hash\");\nconst Scalar = require(\"ffjavascript\").Scalar;\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst babyJub = require(\"./babyjub\");\nconst utils = require(\"ffjavascript\").utils;\nconst pedersenHash = require(\"./pedersenHash\").hash;\nconst mimc7 = require(\"./mimc7\");\nconst poseidon = require(\"./poseidon.js\");\nconst mimcsponge = require(\"./mimcsponge\");\n\n\nexports.prv2pub= prv2pub;\nexports.sign = sign;\nexports.signMiMC = signMiMC;\nexports.signPoseidon = signPoseidon;\nexports.signMiMCSponge = signMiMCSponge;\nexports.verify = verify;\nexports.verifyMiMC = verifyMiMC;\nexports.verifyPoseidon = verifyPoseidon;\nexports.verifyMiMCSponge = verifyMiMCSponge;\nexports.packSignature = packSignature;\nexports.unpackSignature = unpackSignature;\nexports.pruneBuffer = pruneBuffer;\n\n\nfunction pruneBuffer(_buff) {\n    const buff = Buffer.from(_buff);\n    buff[0] = buff[0] & 0xF8;\n    buff[31] = buff[31] & 0x7F;\n    buff[31] = buff[31] | 0x40;\n    return buff;\n}\n\nfunction prv2pub(prv) {\n    const sBuff = pruneBuffer(createBlakeHash(\"blake512\").update(prv).digest().slice(0,32));\n    let s = utils.leBuff2int(sBuff);\n    const A = babyJub.mulPointEscalar(babyJub.Base8, Scalar.shr(s,3));\n    return A;\n}\n\nfunction sign(prv, msg) {\n    const h1 = createBlakeHash(\"blake512\").update(prv).digest();\n    const sBuff = pruneBuffer(h1.slice(0,32));\n    const s = utils.leBuff2int(sBuff);\n    const A = babyJub.mulPointEscalar(babyJub.Base8, Scalar.shr(s, 3));\n\n    const rBuff = createBlakeHash(\"blake512\").update(Buffer.concat([h1.slice(32,64), msg])).digest();\n    let r = utils.leBuff2int(rBuff);\n    const Fr = new F1Field(babyJub.subOrder);\n    r = Fr.e(r);\n    const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);\n    const R8p = babyJub.packPoint(R8);\n    const Ap = babyJub.packPoint(A);\n    const hmBuff = pedersenHash(Buffer.concat([R8p, Ap, msg]));\n    const hm = utils.leBuff2int(hmBuff);\n    const S = Fr.add(r , Fr.mul(hm, s));\n    return {\n        R8: R8,\n        S: S\n    };\n}\n\nfunction signMiMC(prv, msg) {\n    const h1 = createBlakeHash(\"blake512\").update(prv).digest();\n    const sBuff = pruneBuffer(h1.slice(0,32));\n    const s = utils.leBuff2int(sBuff);\n    const A = babyJub.mulPointEscalar(babyJub.Base8, Scalar.shr(s, 3));\n\n    const msgBuff = utils.leInt2Buff(msg, 32);\n    const rBuff = createBlakeHash(\"blake512\").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();\n    let r = utils.leBuff2int(rBuff);\n    const Fr = new F1Field(babyJub.subOrder);\n    r = Fr.e(r);\n    const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);\n    const hm = mimc7.multiHash([R8[0], R8[1], A[0], A[1], msg]);\n    const S = Fr.add(r , Fr.mul(hm, s));\n    return {\n        R8: R8,\n        S: S\n    };\n}\n\nfunction signMiMCSponge(prv, msg) {\n    const h1 = createBlakeHash(\"blake512\").update(prv).digest();\n    const sBuff = pruneBuffer(h1.slice(0,32));\n    const s = utils.leBuff2int(sBuff);\n    const A = babyJub.mulPointEscalar(babyJub.Base8, Scalar.shr(s, 3));\n\n    const msgBuff = utils.leInt2Buff(msg, 32);\n    const rBuff = createBlakeHash(\"blake512\").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();\n    let r = utils.leBuff2int(rBuff);\n    const Fr = new F1Field(babyJub.subOrder);\n    r = Fr.e(r);\n    const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);\n    const hm = mimcsponge.multiHash([R8[0], R8[1], A[0], A[1], msg]);\n    const S = Fr.add(r , Fr.mul(hm, s));\n    return {\n        R8: R8,\n        S: S\n    };\n}\n\nfunction signPoseidon(prv, msg) {\n    const h1 = createBlakeHash(\"blake512\").update(prv).digest();\n    const sBuff = pruneBuffer(h1.slice(0,32));\n    const s = utils.leBuff2int(sBuff);\n    const A = babyJub.mulPointEscalar(babyJub.Base8, Scalar.shr(s, 3));\n\n    const msgBuff = utils.leInt2Buff(msg, 32);\n    const rBuff = createBlakeHash(\"blake512\").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();\n    let r = utils.leBuff2int(rBuff);\n    const Fr = new F1Field(babyJub.subOrder);\n    r = Fr.e(r);\n    const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);\n    const hm = poseidon([R8[0], R8[1], A[0], A[1], msg]);\n    const S = Fr.add(r , Fr.mul(hm, s));\n    return {\n        R8: R8,\n        S: S\n    };\n}\n\nfunction verify(msg, sig, A) {\n    // Check parameters\n    if (typeof sig != \"object\") return false;\n    if (!Array.isArray(sig.R8)) return false;\n    if (sig.R8.length!= 2) return false;\n    if (!babyJub.inCurve(sig.R8)) return false;\n    if (!Array.isArray(A)) return false;\n    if (A.length!= 2) return false;\n    if (!babyJub.inCurve(A)) return false;\n    if (sig.S>= babyJub.subOrder) return false;\n\n    const R8p = babyJub.packPoint(sig.R8);\n    const Ap = babyJub.packPoint(A);\n    const hmBuff = pedersenHash(Buffer.concat([R8p, Ap, msg]));\n    const hm = utils.leBuff2int(hmBuff);\n\n    const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);\n    let Pright = babyJub.mulPointEscalar(A, Scalar.mul(hm,8));\n    Pright = babyJub.addPoint(sig.R8, Pright);\n\n    if (!babyJub.F.eq(Pleft[0],Pright[0])) return false;\n    if (!babyJub.F.eq(Pleft[1],Pright[1])) return false;\n    return true;\n}\n\nfunction verifyMiMC(msg, sig, A) {\n    // Check parameters\n    if (typeof sig != \"object\") return false;\n    if (!Array.isArray(sig.R8)) return false;\n    if (sig.R8.length!= 2) return false;\n    if (!babyJub.inCurve(sig.R8)) return false;\n    if (!Array.isArray(A)) return false;\n    if (A.length!= 2) return false;\n    if (!babyJub.inCurve(A)) return false;\n    if (sig.S>= babyJub.subOrder) return false;\n\n    const hm = mimc7.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]);\n\n    const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);\n    let Pright = babyJub.mulPointEscalar(A, Scalar.mul(hm, 8));\n    Pright = babyJub.addPoint(sig.R8, Pright);\n\n    if (!babyJub.F.eq(Pleft[0],Pright[0])) return false;\n    if (!babyJub.F.eq(Pleft[1],Pright[1])) return false;\n    return true;\n}\n\n\nfunction verifyPoseidon(msg, sig, A) {\n    // Check parameters\n    if (typeof sig != \"object\") return false;\n    if (!Array.isArray(sig.R8)) return false;\n    if (sig.R8.length!= 2) return false;\n    if (!babyJub.inCurve(sig.R8)) return false;\n    if (!Array.isArray(A)) return false;\n    if (A.length!= 2) return false;\n    if (!babyJub.inCurve(A)) return false;\n    if (sig.S>= babyJub.subOrder) return false;\n\n    const hm = poseidon([sig.R8[0], sig.R8[1], A[0], A[1], msg]);\n\n    const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);\n    let Pright = babyJub.mulPointEscalar(A, Scalar.mul(hm, 8));\n    Pright = babyJub.addPoint(sig.R8, Pright);\n\n    if (!babyJub.F.eq(Pleft[0],Pright[0])) return false;\n    if (!babyJub.F.eq(Pleft[1],Pright[1])) return false;\n    return true;\n}\n\nfunction verifyMiMCSponge(msg, sig, A) {\n    // Check parameters\n    if (typeof sig != \"object\") return false;\n    if (!Array.isArray(sig.R8)) return false;\n    if (sig.R8.length!= 2) return false;\n    if (!babyJub.inCurve(sig.R8)) return false;\n    if (!Array.isArray(A)) return false;\n    if (A.length!= 2) return false;\n    if (!babyJub.inCurve(A)) return false;\n    if (sig.S>= babyJub.subOrder) return false;\n\n    const hm = mimcsponge.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]);\n\n    const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);\n    let Pright = babyJub.mulPointEscalar(A, hm.times(bigInt(\"8\")));\n    Pright = babyJub.addPoint(sig.R8, Pright);\n\n    if (!babyJub.F.eq(Pleft[0],Pright[0])) return false;\n    if (!babyJub.F.eq(Pleft[1],Pright[1])) return false;\n    return true;\n}\n\nfunction packSignature(sig) {\n    const R8p = babyJub.packPoint(sig.R8);\n    const Sp = utils.leInt2Buff(sig.S, 32);\n    return Buffer.concat([R8p, Sp]);\n}\n\nfunction unpackSignature(sigBuff) {\n    return {\n        R8: babyJub.unpackPoint(sigBuff.slice(0,32)),\n        S: utils.leBuff2int(sigBuff.slice(32,64))\n    };\n}\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/evmasm.js",
        "content": "// Copyright (c) 2018 Jordi Baylina\n// License: LGPL-3.0+\n//\n\n\nconst Web3Utils = require(\"web3-utils\");\n\nclass Contract {\n    constructor() {\n        this.code = [];\n        this.labels = {};\n        this.pendingLabels = {};\n    }\n\n    createTxData() {\n        let C;\n\n        // Check all labels are defined\n        const pendingLabels = Object.keys(this.pendingLabels);\n        if (pendingLabels.length>0) {\n            throw new Error(\"Lables not defined: \"+ pendingLabels.join(\", \"));\n        }\n\n        let setLoaderLength = 0;\n        let genLoadedLength = -1;\n\n        while  (genLoadedLength!=setLoaderLength) {\n            setLoaderLength = genLoadedLength;\n            C = new module.exports();\n            C.codesize();\n            C.push(setLoaderLength);\n            C.push(0);\n            C.codecopy();\n\n            C.push(this.code.length);\n            C.push(0);\n            C.return();\n            genLoadedLength = C.code.length;\n        }\n\n        return Web3Utils.bytesToHex(C.code.concat(this.code));\n    }\n\n    stop() { this.code.push(0x00); }\n    add()  { this.code.push(0x01); }\n    mul()  { this.code.push(0x02); }\n    sub()  { this.code.push(0x03); }\n    div()  { this.code.push(0x04); }\n    sdiv() { this.code.push(0x05); }\n    mod()  { this.code.push(0x06); }\n    smod()  { this.code.push(0x07); }\n    addmod()  { this.code.push(0x08); }\n    mulmod()  { this.code.push(0x09); }\n    exp()  { this.code.push(0x0a); }\n    signextend()  { this.code.push(0x0b); }\n\n    lt()   { this.code.push(0x10); }\n    gt()   { this.code.push(0x11); }\n    slt()  { this.code.push(0x12); }\n    sgt()  { this.code.push(0x13); }\n    eq()   { this.code.push(0x14); }\n    iszero()  { this.code.push(0x15); }\n    and()  { this.code.push(0x16); }\n    or()  { this.code.push(0x17); }\n    shor()  { this.code.push(0x18); }\n    not()  { this.code.push(0x19); }\n    byte()  { this.code.push(0x1a); }\n\n    keccak() { this.code.push(0x20); }\n    sha3() { this.code.push(0x20); }   // alias\n\n    address()  { this.code.push(0x30); }\n    balance()  { this.code.push(0x31); }\n    origin()  { this.code.push(0x32); }\n    caller()  { this.code.push(0x33); }\n    callvalue()  { this.code.push(0x34); }\n    calldataload()  { this.code.push(0x35); }\n    calldatasize()  { this.code.push(0x36); }\n    calldatacopy()  { this.code.push(0x37); }\n    codesize()  { this.code.push(0x38); }\n    codecopy()  { this.code.push(0x39); }\n    gasprice()  { this.code.push(0x3a); }\n    extcodesize()  { this.code.push(0x3b); }\n    extcodecopy()  { this.code.push(0x3c); }\n    returndatasize()  { this.code.push(0x3d); }\n    returndatacopy()  { this.code.push(0x3e); }\n\n    blockhash()  { this.code.push(0x40); }\n    coinbase()  { this.code.push(0x41); }\n    timestamp()  { this.code.push(0x42); }\n    number()  { this.code.push(0x43); }\n    difficulty()  { this.code.push(0x44); }\n    gaslimit()  { this.code.push(0x45); }\n\n    pop()  { this.code.push(0x50); }\n    mload()  { this.code.push(0x51); }\n    mstore()  { this.code.push(0x52); }\n    mstore8()  { this.code.push(0x53); }\n    sload()  { this.code.push(0x54); }\n    sstore()  { this.code.push(0x55); }\n\n    _pushLabel(label) {\n        if (typeof this.labels[label] != \"undefined\") {\n            this.push(this.labels[label]);\n        } else {\n            this.pendingLabels[label] = this.pendingLabels[label] || [];\n            this.pendingLabels[label].push(this.code.length);\n            this.push(\"0x000000\");\n        }\n    }\n\n    _fillLabel(label) {\n        if (!this.pendingLabels[label]) return;\n\n        let dst = this.labels[label];\n\n        const dst3 = [dst >> 16, (dst >> 8) & 0xFF, dst & 0xFF];\n\n        this.pendingLabels[label].forEach((p) => {\n            for (let i=0; i<3; i++) {\n                this.code[p+i+1] = dst3[i];\n            }\n        });\n\n        delete this.pendingLabels[label];\n    }\n\n\n    jmp(label)  {\n        if (typeof label !== \"undefined\") {\n            this._pushLabel(label);\n        }\n        this.code.push(0x56);\n    }\n\n    jmpi(label)  {\n        if (typeof label !== \"undefined\") {\n            this._pushLabel(label);\n        }\n        this.code.push(0x57);\n    }\n\n    pc()  { this.code.push(0x58); }\n    msize()  { this.code.push(0x59); }\n    gas()  { this.code.push(0x5a); }\n    label(name)  {\n        if (typeof this.labels[name] != \"undefined\") {\n            throw new Error(\"Label already defined\");\n        }\n        this.labels[name] = this.code.length;\n        this.code.push(0x5b);\n\n        this._fillLabel(name);\n    }\n\n    push(data) {\n        if (typeof data === \"number\") {\n            let isNeg;\n            if (data<0) {\n                isNeg = true;\n                data = -data;\n            }\n            data = data.toString(16);\n            if (data.length % 2 == 1) data = \"0\" + data;\n            data = \"0x\" + data;\n            if (isNeg) data = \"-\"+data;\n        }\n        const d = Web3Utils.hexToBytes(Web3Utils.toHex(data));\n        if (d.length == 0 || d.length > 32) {\n            throw new Error(\"Assertion failed\");\n        }\n        this.code = this.code.concat([0x5F + d.length], d);\n    }\n\n    dup(n) {\n        if (n < 0 || n >= 16) {\n            throw new Error(\"Assertion failed\");\n        }\n        this.code.push(0x80 + n);\n    }\n\n    swap(n) {\n        if (n < 1 || n > 16) {\n            throw new Error(\"Assertion failed\");\n        }\n        this.code.push(0x8f + n);\n    }\n\n    log0()  { this.code.push(0xa0); }\n    log1()  { this.code.push(0xa1); }\n    log2()  { this.code.push(0xa2); }\n    log3()  { this.code.push(0xa3); }\n    log4()  { this.code.push(0xa4); }\n\n    create()  { this.code.push(0xf0); }\n    call()  { this.code.push(0xf1); }\n    callcode()  { this.code.push(0xf2); }\n    return()  { this.code.push(0xf3); }\n    delegatecall()  { this.code.push(0xf4); }\n\n    staticcall()  { this.code.push(0xfa); }\n    revert()  { this.code.push(0xfd); }\n    invalid()  { this.code.push(0xfe); }\n    selfdestruct()  { this.code.push(0xff); }\n}\n\nmodule.exports = Contract;\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/g2_gencontract.js",
        "content": "// Copyright (c) 2018 Jordi Baylina\n// License: LGPL-3.0+\n//\n\nconst Contract = require(\"./evmasm\");\nconst G2 = require(\"snarkjs\").bn128.G2;\n\n\nfunction toHex256(a) {\n    let S = a.toString(16);\n    while (S.length < 64) S=\"0\"+S;\n    return \"0x\" + S;\n}\n\nfunction createCode(P, w) {\n\n    const C = new Contract();\n\n    const NPOINTS = 1 << (w-1);\n\n    const VAR_POS = C.allocMem(32);\n    const VAR_POINTS = C.allocMem( (NPOINTS)*4*32);\n    const savedP = C.allocMem(32);\n    const savedZ3 = C.allocMem(32);\n\n    // Check selector\n    C.push(\"0x0100000000000000000000000000000000000000000000000000000000\");\n    C.push(0);\n    C.calldataload();\n    C.div();\n    C.push(\"b65c7c74\"); // mulexp(uint256)\n    C.eq();\n    C.jmpi(\"start\");\n    C.invalid();\n\n    C.label(\"start\");\n\n    storeVals();\n\n    C.push( Math.floor(255/w)*w  );                // pos := 255\n    C.push(VAR_POS);\n    C.mstore();\n\n    C.push(\"21888242871839275222246405745257275088696311157297823662689037894645226208583\");\n    C.push(0);\n    C.push(0);\n    C.push(0);\n    C.push(0);\n    C.push(0);\n    C.push(0);\n\n    C.label(\"begin_loop\");      // ACC_X ACC_Y ACC_Z q\n\n    C.internalCall(\"double\");\n\n    // g = (e>>pos)&MASK\n    C.push(4);\n    C.calldataload();           // e ACC_X ACC_Y ACC_Z q\n\n    C.push(VAR_POS);\n    C.mload();                  // pos e ACC_X ACC_Y ACC_Z q\n    C.shr();\n\n    C.push(NPOINTS-1);\n    C.and();                    // g ACC_X ACC_Y ACC_Z q\n\n    C.internalCall(\"add\");      // acc_x acc_y acc_z\n\n    C.push(VAR_POS);\n    C.mload();                  // pos acc_x acc_y acc_z\n    C.dup(0);                   // pos pos acc_x acc_y acc_z\n    C.push(0);                  // 0 pos pos acc_x acc_y acc_z\n    C.eq();                     // eq pos acc_x acc_y acc_z\n    C.jmpi(\"after_loop\");       // pos acc_x acc_y acc_z\n    C.push(w);                  // 5 pos acc_x acc_y acc_z\n    C.sub();                    // pos acc_x acc_y acc_z\n    C.push(VAR_POS);\n    C.mstore();                 // acc_x acc_y acc_z\n    C.jmp(\"begin_loop\");\n    C.label(\"after_loop\");      // pos acc_x acc_y acc_z\n    C.pop();                    // acc_x acc_y acc_z\n\n    C.internalCall(\"affine\");   // acc_x acc_y\n\n    C.push(0);\n    C.mstore();\n    C.push(20);\n    C.mstore();\n    C.push(40);\n    C.mstore();\n    C.push(60);\n    C.mstore();\n\n    C.push(\"0x80\");\n    C.push(\"0x00\");\n    C.return();\n\n\n    double();\n    addPoint();\n    affine();\n\n    return C.createTxData();\n\n    function add(a,b,q) {\n        C.dup(q);\n        C.dup(a+1 + 1);\n        C.dup(b+1 + 2);\n        C.addmod();\n        C.dup(q + 1);\n        C.dup(a + 2);\n        C.dup(b + 3);\n        C.addmod();\n    }\n\n    function sub(a,b,q) {\n        C.dup(q);           // q\n        C.dup(a+1 + 1);     // ai q\n        C.dub(q + 2);       // q ai q\n        C.dup(b+1 + 3);     // bi q ai q\n        C.sub();            // -bi ai q\n        C.addmod();         // ci\n        C.dup(q + 1);       // q ci\n        C.dup(a + 2);       // ar q ci\n        C.dup(q + 3);       // q ar q ci\n        C.dup(b + 4);       // br q ar q ci\n        C.sub();            // -br ar q ci\n        C.addmod();         // cr ci\n    }\n\n    function mul(a, b, q) {\n        C.dup(q);           //  q\n        C.dup(q + 1);       //  q q\n        C.dup(a + 2);       //  ar q q\n        C.dup(b+1 + 3);     //  bi ar q q\n        C.mulmod();         //  ci1 q\n        C.dup(q + 2);       //  q ci1 q\n        C.dup(a+1 + 3);     //  ai q ci1 q\n        C.dup(b + 4);       //  ar ai q ci1 q\n        C.mulmod();         //  ci2 ci1 q\n        C.addmod();         //  ci\n        C.dup(q + 1);       //  q ci\n        C.dup(q + 2);       //  q q ci\n        C.dup(q + 3);       //  q q q ci\n        C.dup(a+1 + 4);     //  ai q q ci\n        C.dup(b+1 + 5);     //  bi ai q q ci\n        C.mulmod();         //  cr2 q q ci\n        C.sub();            //  -cr2 q ci\n        C.dup(q + 3);       //  q -cr2 q ci\n        C.dup(a + 4);       //  ar q -cr2 q ci\n        C.dup(b + 5);       //  br ar q -cr2 q ci\n        C.mulmod();         //  cr1 -cr2 q ci\n        C.addmod();         //  cr ci\n    }\n\n    function square(a, q) {\n        C.dup(q);           //  q\n        C.dup(q + 1);       //  q q\n        C.dup(a + 2);       //  ar q q\n        C.dup(a+1 + 3);     //  ai ar q q\n        C.mulmod();         //  arai q\n        C.dup(0);           //  arai arai q\n        C.addmod();         //  ci\n        C.dup(q + 1);       //  q ci\n        C.dup(q + 2);       //  q q ci\n        C.dup(q + 3);       //  q q q ci\n        C.dup(a+1 + 4);     //  ai q q ci\n        C.dup(a+1 + 5);     //  ai ai q q ci\n        C.mulmod();         //  cr2 q q ci\n        C.sub();            //  -cr2 q ci\n        C.dup(q + 3);       //  q -cr2 q ci\n        C.dup(a + 4);       //  ar q -cr2 q ci\n        C.dup(a + 5);       //  br ar q -cr2 q ci\n        C.mulmod();         //  cr1 -cr2 q ci\n        C.addmod();         //  cr ci\n    }\n\n    function add1(a, q) {\n        C.dup(a+1);         // im\n        C.dup(1 + q);       //  q\n        C.dup(2 + a);       //  re q im\n        C.push(1);          // 1 re q im\n        C.addmod();\n    }\n\n    function cmp(a, b) {\n        C.dup(a);\n        C.dup(b);\n        C.eq();\n        C.dup(a+1);\n        C.dup(a+1);\n        C.and();\n    }\n\n    function rm(a) {\n        if (a>0) C.swap(a);\n        C.pop();\n        if (a>0) C.swap(a);\n        C.pop();\n    }\n\n    function double() {\n        C.label(\"double\");       // xR, xI,    yR, yI,   zR zI, q\n\n        C.dup(4);\n        C.iszero();\n        C.dup(6);\n        C.iszero();\n        C.and();\n        C.jumpi(\"enddouble\");   // X Y Z q\n\n\n        // Z3 = 2*Y*Z // Remove Z\n        mul(2, 4, 6);           // yz X Y Z q\n        rm(6);                  // X Y yz q\n\n        add(4, 4, 6);           // 2yz X Y yz q\n        rm(6);                  // X Y Z3 q\n\n        // A = X^2\n        square(0,6);               // A X Y Z3 q\n\n        // B = Y^2  // Remove Y\n        square(4,8);              // B A X Y Z3 q\n        rm(6);                  // A X B Z3 q\n\n        // C = B^2\n        square(4,8);               // C A X B Z3 q\n\n        // D = (X+B)^2-A-C // Remove X, Remove B\n        add(4,6, 10);           // X+B C A X B Z3 q\n        rm(6);                  // C A X+B B Z3 q\n        rm(6);                  // A X+B C Z3 q\n        square(2,8);            // (X+B)^2 A X+B C Z3 q\n        rm(4);                  // A (X+B)^2 C Z3 q\n        sub(2, 0, 8);           // (X+B)^2-A A (X+B)^2 C Z3 q\n        rm(4);                  // A (X+B)^2-A C Z3 q\n        sub(2, 4, 8);           // (X+B)^2-A-C A (X+B)^2-A C Z3 q\n        rm(4);                  // A D C Z3 q\n\n        // D = D+D\n        add(2,2, 8);            // D+D A D C Z3 q\n        rm(4);                  // A D C Z3 q\n\n        // E=A+A+A\n        add(0, 0, 8);           // 2A A D C Z3 q\n        add(0, 2, 10);          // 3A 2A A D C Z3 q\n        rm(4);                  // 2A 3A D C Z3 q\n        rm(0);                  // E D C Z3 q\n\n        // F=E^2\n        square(0, 8);           // F E D C Z3 q\n\n        // X3= F - 2*D  // Remove F\n        add(4, 4, 10);          // 2D F E D C Z3 q\n        sub(2, 0, 12);          // F-2D 2D F E D C Z3 q\n        rm(4);                  // 2D X3 E D C Z3 q\n        rm(0);                  // X3 E D C Z3 q\n\n        // Y3 = E * (D - X3) - 8 * C  // Remove D C  E\n\n        sub(4, 0, 10);          // D-X3 X3 E D C Z3 q\n        rm(6);                  // X3 E D-X3 C Z3 q\n        mul(2, 4, 10);          // E*(D-X3) X3 E D-X3 C Z3 q\n        rm(6);                  // X3 E E*(D-X3) C Z3 q\n        rm(2);                  // X3 E*(D-X3) C Z3 q\n        add(4, 4, 8);           // 2C X3 E*(D-X3) C Z3 q\n        rm(6);                  // X3 E*(D-X3) 2C Z3 q\n        add(4, 4, 8);           // 4C X3 E*(D-X3) 2C Z3 q\n        rm(6);                  // X3 E*(D-X3) 4C Z3 q\n        add(4, 4, 8);           // 8C X3 E*(D-X3) 4C Z3 q\n        rm(6);                  // X3 E*(D-X3) 8C Z3 q\n        sub(2, 4, 8);           // E*(D-X3)-8C X3 E*(D-X3) 8C Z3 q\n        rm(6);                  // X3 E*(D-X3) Y3 Z3 q\n        rm(2);                  // X3 Y3 Z3 q\n\n        C.label(\"enddouble\");\n        C.returnCall();\n    }\n\n    function addPoint() {     // p, xR, xI,    yR, yI,   zR zI, q\n\n\n        C.dup(0);           // p p X2 Y2 Z2 q\n\n        C.push(savedP);\n        C.mstore();\n\n        C.iszero();         // X2 Y2 Z2 q\n        C.jumpi(\"endpadd\");\n\n\n        C.dup(4);\n        C.iszero();\n        C.dup(6);\n        C.iszero();\n        C.and();\n        C.jumpi(\"returnP\");   // X2 Y2 Z2 q\n\n\n\n        // lastZ3 = (Z2+1)^2 - Z2^2\n        add1(4, 6);         // Z2+1 X2 Y2 Z2 q\n        square(0, 8);       // (Z2+1)^2 Z2+1 X2 Y2 Z2 q\n        rm(2);              // (Z2+1)^2 X2 Y2 Z2 q\n        square(6, 8);       // Z2^2 (Z2+1)^2 X2 Y2 Z2 q\n\n\n        sub(2, 0, 10);      // (Z2+1)^2-Z2^2 Z2^2 (Z2+1)^2 X2 Y2 Z2 q\n\n        saveZ3();           // Z2^2 (Z2+1)^2 X2 Y2 Z2 q\n        rm(2);              // Z2^2 X2 Y2 Z2 q\n\n        // U2 = X2\n        // S2 = Y2          // Z2^2 U2 S2 Z2 q\n\n\n        // U1 = X1 * Z2^2\n        loadX();            // X1 Z2^2 U2 S2 Z2 q\n        mul(0, 2, 10);      // X1*Z2^2 X1 Z2^2 U2 S2 Z2 q\n        rm(2);              // X1*Z2^2 Z2^2 U2 S2 Z2 q\n\n\n        mul(2, 8, 10);      // Z2^3 U1 Z2^2 U2 S2 Z2 q\n        rm(4);              // U1 Z2^3 U2 S2 Z2 q\n        rm(8);              // Z2^3 U2 S2 U1 q\n\n        // S1 = Y1 * Z1^3\n        loadY();            // Y1 Z2^3 U2 S2 U1 q\n        mul(0, 2, 10);      // S1 Y1 Z2^3 U2 S2 U1 q\n        rm(4);              // Y1 S1 U2 S2 U1 q\n        rm(0);              // S1 U2 S2 U1 q\n\n        cmp(0, 4);          // c1 S1 U2 S2 U1 q\n        cmp(3, 7);          // c2 c1 S1 U2 S2 U1 q\n        C.and();            // c2&c1 S1 U2 S2 U1 q\n        C.jumpi(\"double1\"); // S1 U2 S2 U1 q\n\n\n        // Returns the double\n\n        // H = U2-U1  // Remove U2\n        C.sub(4, 8, 10);    // H S1 U2 S2 U1 q\n        rm(4);              // S1 H S2 U1 q\n\n        // // r = 2 * (S2-S1)  // Remove S2\n        C.sub(4, 4, 8);     // S1-S2 S1 H S2 U1 q\n        rm(6);              // S1 H S1-S2 U1 q\n        C.add(4, 4, 8);     // 2*(S1-S2) S1 H S1-S2 U1 q\n        rm(6);              // S1 H r U1 q\n\n        // I = (2 * H)^2\n        C.add(2, 2, 8);     // 2*H S1 H r U1 q\n        C.square(0, 10);    // (2*H)^2 2*H S1 H r U1 q\n        rm(2);              // I S1 H r U1 q\n\n        // V = U1 * I\n        mul(8, 0, 10);      // V I S1 H r U1 q\n        rm(10);             // I S1 H r V q\n\n        // J = H * I // Remove I\n        mul(4, 0, 10);      // J I S1 H r V q\n        rm(2);              // J S1 H r V q\n\n        // X3 = r^2 - J - 2 * V\n\n        // S1J2 = (S1*J)*2  // Remove S1\n        mul(2, 0, 10);      // S1*J J S1 H r V q\n        rm(4);              // J S1*J H r V q\n        add(2,2, 10);       // (S1*J)*2 J S1*J H r V q\n        rm(4);              // J S1J2 H r V q\n\n        // X3 = r^2 - J - 2 * V\n        square(6, 10);      // r^2 J S1J2 H r V q\n        sub(0, 2, 12);      // r^2-J r^2 J S1J2 H r V q\n        rm(2);              // r^2-J J S1J2 H r V q\n        rm(2);              // r^2-J S1J2 H r V q\n        add(8, 8, 10);      // 2*V r^2-J S1J2 H r V q\n        sub(2, 0, 12);      // r^2-J-2*V 2*V r^2-J S1J2 H r V q\n        rm(4);              // 2*V  X3 S1J2 H r V q\n        rm(0);              // X3 S1J2 H r V q\n\n        // Y3 = r * (V-X3)-S1J2\n\n        sub(8, 0, 10);      // V-X3 X3 S1J2 H r V q\n        rm(10);             // X3 S1J2 H r V-X3 q\n        mul(6, 8, 10);      // r*(V-X3) X3 S1J2 H r V-X3 q\n        rm(8);              // X3 S1J2 H r*(V-X3) V-X3 q\n        rm(8);              // S1J2 H r*(V-X3) X3 q\n        sub(4, 0, 8);       // Y3 S1J2 H r*(V-X3) X3 q\n        rm(6);              // S1J2 H Y3 X3 q\n        rm(0);              // H Y3 X3 q\n\n        // Z3 = lastZ * H\n        loadZ3();           // lastZ3 H Y3 X3 q\n        mul(0, 2, 8);       // Z3 lastZ3 H Y3 X3 q\n        rm(4);              // lastZ3 Z3 Y3 X3 q\n        rm(0);              // Z3 Y3 X3 q\n\n        C.swap(1);\n        C.swap(5);\n        C.swap(1);\n        C.swap(4);          // X3 Y3 Z3 q\n\n        // returns the point in memory\n        C.label(\"returnP\"); // X Y Z q\n        rm(0);\n        rm(0);\n        rm(0);\n        C.push(0);\n        C.push(1);\n        loadX();\n        loadY();\n        C.jump(\"endpadd\");\n\n        C.label(\"double1\"); // S1 U2 S2 U1 q\n        rm(0);\n        rm(0);\n        rm(0);\n        rm(0);\n        C.push(0);\n        C.push(1);\n        loadX();\n        loadY();\n        C.jump(\"double\");\n\n        C.label(\"endpadd\");\n        C.returnCall();\n\n        function loadX() {\n            C.push(savedP);\n            C.mload();                  // p\n            C.push(32);\n            C.mul();                    // P*32\n            C.push(VAR_POINTS+32);\n            C.add();                    // P*32+32\n            C.dup();                    // P*32+32 P*32+32\n            C.mload();                  // im P*32+32\n            C.swap(1);                  // P*32+32 im\n            C.push(0x20);               // 32 P*32+32 im\n            C.sub();                    // P*32 im\n            C.mload();                  // re im\n        }\n\n        function loadY() {\n            C.push(savedP);\n            C.mload();                  // p\n            C.push(32);\n            C.mul();                    // P*32\n            C.push(VAR_POINTS+32*3);\n            C.add();                    // P*32+32\n            C.dup();                    // P*32+32 P*32+32\n            C.mload();                  // im P*32+32\n            C.swap(1);                  // P*32+32 im\n            C.push(0x20);               // 32 P*32+32 im\n            C.sub();                    // P*32 im\n            C.mload();                  // re im\n        }\n\n        function loadZ3() {\n            C.push(savedZ3+32);\n            C.mload();                  // p\n            C.push(savedZ3);\n            C.mload();\n        }\n\n        function saveZ3() {\n            C.push(savedZ3);\n            C.mstore();\n            C.push(savedZ3+32);\n            C.mstore();\n        }\n    }\n\n    function affine() { // X Y Z q\n        // If Z2=0 return 0\n        C.label(\"affine\");\n        C.dup(4);\n        C.dup(5 + 1);\n        C.or();\n        C.jumpi(\"notZero\");     // X Y Z q\n        rm(0);\n        rm(0);\n        C.push(0);\n        C.push(0);\n\n        C.jmp(\"endAffine\");\n        C.label(\"notZero\");\n\n        inverse2(4,6);          // Z_inv X Y Z q\n        square(2, 8);           // Z2_inv Z_inv X Y Z q\n        mul(0, 2, 10);          // Z3_inv Z2_inv Z_inv X Y Z q\n        rm(4);                  // Z2_inv Z3_inv X Y Z q\n        C.push(1);\n        C.push(0);              // 1 Z2_inv Z3_inv X Y Z q\n        rm(10);                 // Z2_inv Z3_inv X Y 1 q\n        mul(2, 6, 10);          // YI Z2_inv Z3_inv X Y 1 q\n        rm(8);                  // Z2_inv Z3_inv X YI 1 q\n        mul(0, 4, 10);          // XI Z2_inv Z3_inv X YI 1 q\n        rm(6);                  // Z2_inv Z3_inv XI YI 1 q\n        rm(0);                  // Z3_inv XI YI 1 q\n        rm(0);                  // XI YI 1 q\n        C.label(\"endAffine\");\n        C.returnCall();\n    }\n\n    function inverse2(a, q) {\n        C.dup(q);           // q\n        C.dup(q + 1);       // q q\n        C.push(2);          // 2 q q\n        C.sub();            // q-2 q\n        C.dup(q + 2);       // q q-2 q\n        C.dup(q + 3);       // q q q-2 q\n        C.dup(a + 4);       // ar q q q-2 q\n        C.dup(a + 5);       // ar ar q q q-2 q\n        C.mulmod();         // t0 q q-2 q\n\n        C.dup(q   + 4);     // q t0 q q-2 q\n        C.dup(a+1 + 5);     // ai q t0 q q-2 q\n        C.dup(a+1 + 6);     // ai ai q t0 q q-2 q\n        C.mulmod();         // t1 t0 q q-2 q\n\n        C.addmod();         // t2 q-2 q\n        C.expmod();         // t3\n\n        C.dup(q + 1);       // q t3\n        C.dup(q + 2);       // q q t3\n        C.dup(q + 3);       // q q q t3\n        C.dup(1);           // t3 q q q t3\n        C.sub();            // -t3 q q t3\n        C.dup(a+1 + 3);     // ai -t3 q q t3\n        C.mulmod();         // ii q t3\n        C.swap(2);          // t3 q ii\n        C.dup(a + 3);       // ar t3 q ii\n        C.mulmod();         // ir ii\n    }\n\n    function storeVals() {\n        C.push(VAR_POINTS);                 // p\n        for (let i=0; i<NPOINTS; i++) {\n            const MP = G2.affine(G2.mulScalar(P, i));\n            for (let j=0; j<2; j++) {\n                for (let k=0; k<2; k++) {\n                    C.push(toHex256(MP[j][k]));     // MP[0][0] p\n                    C.dup(1);                       // p MP[0][0] p\n                    C.mstore();                     // p\n                    C.push(32);                     // 32 p\n                    C.add();                        // p+32\n                }\n            }\n        }\n    }\n\n}\n\nmodule.exports.abi = [\n    {\n        \"constant\": true,\n        \"inputs\": [\n            {\n                \"name\": \"escalar\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"name\": \"mulexp\",\n        \"outputs\": [\n            {\n                \"name\": \"\",\n                \"type\": \"uint256\"\n            },\n            {\n                \"name\": \"\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"payable\": false,\n        \"stateMutability\": \"pure\",\n        \"type\": \"function\"\n    }\n];\n\nmodule.exports.createCode = createCode;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimc7.js",
        "content": "const Scalar = require(\"ffjavascript\").Scalar;\nconst ZqField = require(\"ffjavascript\").ZqField;\n\nconst Web3Utils = require(\"web3-utils\");\nconst F = new ZqField(Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\"));\nexports.F = F;\n\nconst SEED = \"mimc\";\nconst NROUNDS = 91;\n\nexports.getIV = (seed) => {\n    if (typeof seed === \"undefined\") seed = SEED;\n    const c = Web3Utils.keccak256(seed+\"_iv\");\n    const cn = Scalar.FromString(Web3Utils.toBN(c).toString());\n    const iv = cn.mod(F.p);\n    return iv;\n};\n\nexports.getConstants = (seed, nRounds) => {\n    if (typeof seed === \"undefined\") seed = SEED;\n    if (typeof nRounds === \"undefined\") nRounds = NROUNDS;\n    const cts = new Array(nRounds);\n    let c = Web3Utils.keccak256(SEED);\n    for (let i=1; i<nRounds; i++) {\n        c = Web3Utils.keccak256(c);\n\n        const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));\n        const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);\n        cts[i] = Scalar.fromString(Web3Utils.toBN(c2).toString());\n    }\n    cts[0] = F.e(0);\n    return cts;\n};\n\nconst cts = exports.getConstants(SEED, 91);\n\nexports.hash =  (_x_in, _k) =>{\n    const x_in = F.e(_x_in);\n    const k = F.e(_k);\n    let r;\n    for (let i=0; i<NROUNDS; i++) {\n        const c = cts[i];\n        const t = (i==0) ? F.add(x_in, k) : F.add(F.add(r, k), c);\n        r = F.pow(t, 7);\n    }\n    return F.add(r, k);\n};\n\nexports.multiHash = (arr, key) => {\n    let r;\n    if (typeof(key) === \"undefined\") {\n        r = F.zero;\n    } else {\n        r = key;\n    }\n    for (let i=0; i<arr.length; i++) {\n        r = F.add(\n            F.add(\n                r,\n                arr[i]\n            ),\n            exports.hash(F.e(arr[i]), r)\n        );\n    }\n    return r;\n};\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimc_gencontract.js",
        "content": "// Copyright (c) 2018 Jordi Baylina\n// License: LGPL-3.0+\n//\n\nconst Web3Utils = require(\"web3-utils\");\n\nconst Contract = require(\"./evmasm\");\n\nfunction createCode(seed, n) {\n\n    let ci = Web3Utils.keccak256(seed);\n\n    const C = new Contract();\n\n    C.push(0x44);\n    C.push(\"0x00\");\n    C.push(\"0x00\");\n    C.calldatacopy();\n    C.push(\"0x0100000000000000000000000000000000000000000000000000000000\");\n    C.push(\"0x00\");\n    C.mload();\n    C.div();\n    C.push(\"0xd15ca109\"); // MiMCpe7(uint256,uint256)\n//    C.push(\"0x8c42199e\"); // MiMCpe7(uint256,uint256,uint256)\n    C.eq();\n    C.jmpi(\"start\");\n    C.invalid();\n\n    C.label(\"start\");\n    C.push(\"0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\");  // q\n    C.push(\"0x24\");\n    C.mload();          // k q\n\n\n    C.dup(1);           // q k q\n    C.dup(0);           // q q k q\n    C.push(\"0x04\");\n    C.mload();          // x q q k q\n    C.dup(3);           // k x q q k q\n    C.addmod();         // t=x+k q k q\n    C.dup(1);           // q t q k q\n    C.dup(0);           // q q t q k q\n    C.dup(2);           // t q q t q k q\n    C.dup(0);           // t t q q t q k q\n    C.mulmod();         // a=t^2 q t q k q\n    C.dup(1);           // q a q t q k q\n    C.dup(1);           // a q a q t q k q\n    C.dup(0);           // a a q a q t q k q\n    C.mulmod();         // b=t^4 a q t q k q\n    C.mulmod();         // c=t^6 t q k q\n    C.mulmod();         // r=t^7 k q\n\n    for (let i=0; i<n-1; i++) {\n        ci = Web3Utils.keccak256(ci);\n        C.dup(2);       // q r k q\n        C.dup(0);       // q q r k q\n        C.dup(0);       // q q q r k q\n        C.swap(3);      // r q q q k q\n        C.push(ci);     // c r q q k q\n        C.addmod();     // s=c+r q q k q\n        C.dup(3);       // k s q q k q\n        C.addmod();     // t=s+k q k q\n        C.dup(1);       // q t q k q\n        C.dup(0);       // q q t q k q\n        C.dup(2);       // t q q t q k q\n        C.dup(0);       // t t q q t q k q\n        C.mulmod();     // a=t^2 q t q k q\n        C.dup(1);       // q a q t q k q\n        C.dup(1);       // a q a q t q k q\n        C.dup(0);       // a a q a q t q k q\n        C.mulmod();     // b=t^4 a q t q k q\n        C.mulmod();     // c=t^6 t q k q\n        C.mulmod();     // r=t^7 k q\n    }\n\n    C.addmod();     // res=t^7+k\n    C.push(\"0x00\");\n    C.mstore();     // Save it to pos 0;\n    C.push(\"0x20\");\n    C.push(\"0x00\");\n    C.return();\n\n    return C.createTxData();\n}\n\nmodule.exports.abi = [\n    {\n        \"constant\": true,\n        \"inputs\": [\n            {\n                \"name\": \"in_x\",\n                \"type\": \"uint256\"\n            },\n            {\n                \"name\": \"in_k\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"name\": \"MiMCpe7\",\n        \"outputs\": [\n            {\n                \"name\": \"out_x\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"payable\": false,\n        \"stateMutability\": \"pure\",\n        \"type\": \"function\"\n    }\n];\n\nmodule.exports.createCode = createCode;\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimc_print_iv.js",
        "content": "const mimc7 = require(\"./mimc7.js\");\n\nconsole.log(\"IV: \"+mimc7.getIV().toString());\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimc_printconstants.js",
        "content": "const mimc7 = require(\"./mimc7.js\");\n\nconst nRounds = 91;\nlet S = \"[\\n\";\nconst cts = mimc7.getConstants();\nfor (let i=0; i<nRounds; i++) {\n    S = S + cts[i].toString();\n    if (i<nRounds-1) S = S + \",\";\n    S=S+\"\\n\";\n}\nS = S + \"]\\n\";\n\nconsole.log(S);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimc_printcontract.js",
        "content": "const mimcGenContract = require(\"./mimc_gencontract\");\n\nconst SEED = \"mimc\";\n\nlet nRounds;\nif (typeof process.argv[2] != \"undefined\") {\n    nRounds = parseInt(process.argv[2]);\n} else {\n    nRounds = 91;\n}\n\nconsole.log(mimcGenContract.createCode(SEED, nRounds));\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimcsponge.js",
        "content": "const Scalar = require(\"ffjavascript\").Scalar\nconst Web3Utils = require(\"web3-utils\");\nconst ZqField = require(\"ffjavascript\").ZqField;\nconst F = new ZqField(Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\"));\n\nconst SEED = \"mimcsponge\";\nconst NROUNDS = 220;\n\nexports.getIV = (seed) => {\n    if (typeof seed === \"undefined\") seed = SEED;\n    const c = Web3Utils.keccak256(seed+\"_iv\");\n    const cn = Scalar.fromString(Web3Utils.toBN(c).toString());\n    const iv = cn.mod(F.p);\n    return iv;\n};\n\nexports.getConstants = (seed, nRounds) => {\n    if (typeof seed === \"undefined\") seed = SEED;\n    if (typeof nRounds === \"undefined\") nRounds = NROUNDS;\n    const cts = new Array(nRounds);\n    let c = Web3Utils.keccak256(SEED);\n    for (let i=1; i<nRounds; i++) {\n        c = Web3Utils.keccak256(c);\n\n        const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));\n        const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);\n        cts[i] = F.e(Web3Utils.toBN(c2).toString());\n    }\n    cts[0] = F.e(0);\n    cts[cts.length - 1] = F.e(0);\n    return cts;\n};\n\nconst cts = exports.getConstants(SEED, NROUNDS);\n\nexports.hash = (_xL_in, _xR_in, _k) =>{\n    let xL = F.e(_xL_in);\n    let xR = F.e(_xR_in);\n    const k = F.e(_k);\n    for (let i=0; i<NROUNDS; i++) {\n        const c = cts[i];\n        const t = (i==0) ? F.add(xL, k) : F.add(F.add(xL, k), c);\n        const xR_tmp = F.e(xR);\n        if (i < (NROUNDS - 1)) {\n            xR = xL;\n            xL = F.add(xR_tmp, F.pow(t, 5));\n        } else {\n            xR = F.add(xR_tmp, F.pow(t, 5));\n        }\n    }\n    return {\n        xL: F.normalize(xL),\n        xR: F.normalize(xR),\n    };\n};\n\nexports.multiHash = (arr, key, numOutputs) => {\n    if (typeof(numOutputs) === \"undefined\") {\n        numOutputs = 1;\n    }\n    if (typeof(key) === \"undefined\") {\n        key = F.zero;\n    }\n\n    let R = F.zero;\n    let C = F.zero;\n\n    for (let i=0; i<arr.length; i++) {\n        R = F.add(R, F.e(arr[i]));\n        const S = exports.hash(R, C, key);\n        R = S.xL;\n        C = S.xR;\n    }\n    let outputs = [R];\n    for (let i=1; i < numOutputs; i++) {\n        const S = exports.hash(R, C, key);\n        R = S.xL;\n        C = S.xR;\n        outputs.push(R);\n    }\n    if (numOutputs == 1) {\n        return F.normalize(outputs[0]);\n    } else {\n        return outputs.map(x => F.normalize(x));\n    }\n};\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimcsponge_gencontract.js",
        "content": "// Copyright (c) 2018 Jordi Baylina\n// License: LGPL-3.0+\n//\n\nconst Web3Utils = require(\"web3-utils\");\n\nconst Contract = require(\"./evmasm\");\n\nfunction createCode(seed, n) {\n\n    let ci = Web3Utils.keccak256(seed);\n\n    const C = new Contract();\n\n    C.push(0x64);\n    C.push(\"0x00\");\n    C.push(\"0x00\");\n    C.calldatacopy();\n    C.push(\"0x0100000000000000000000000000000000000000000000000000000000\");\n    C.push(\"0x00\");\n    C.mload();\n    C.div();\n    C.push(\"0x3f1a1187\"); // MiMCSponge(uint256,uint256,uint256)\n    C.eq();\n    C.jmpi(\"start\");\n    C.invalid();\n\n    C.label(\"start\");\n    C.push(\"0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\");  // q\n    C.push(\"0x44\");\n    C.mload();          // k q\n    C.push(\"0x04\");\n    C.mload();          // xL k q\n    C.dup(2);           // q xL k q\n    C.push(\"0x24\");\n    C.mload();          // xR q xL k q\n    C.dup(1);           // q xR q xL k q\n    C.dup(0);           // q q xR q xL k q\n    C.dup(4);           // xL q q xR q xL k q\n    C.dup(6);           // k xL q q xR q xL k q\n    C.addmod();         // t=k+xL q xR q xL k q\n    C.dup(1);           // q t q xR q xL k q\n    C.dup(0);           // q q t q xR q xL k q\n    C.dup(2);           // t q q t q xR q xL k q\n    C.dup(0);           // t t q q t q xR q xL k q\n    C.mulmod();         // b=t^2 q t q xR q xL k q\n    C.dup(0);           // b b q t q xR q xL k q\n    C.mulmod();         // c=t^4 t q xR q xL k q\n    C.mulmod();         // d=t^5 xR q xL k q\n    C.addmod();         // e=t^5+xR xL k q (for next round: xL xR k q)\n\n    for (let i=0; i<n-1; i++) {\n        if (i < n-2) {\n          ci = Web3Utils.keccak256(ci);\n        } else {\n          ci = \"0x00\";\n        }\n        C.swap(1);      // xR xL k q\n        C.dup(3);       // q xR xL k q\n        C.dup(3);       // k q xR xL k q\n        C.dup(1);       // q k q xR xL k q\n        C.dup(4);       // xL q k q xR xL k q\n        C.push(ci);     // ci xL q k q xR xL k q\n        C.addmod();     // a=ci+xL k q xR xL k q\n        C.addmod();     // t=a+k xR xL k q\n        C.dup(4);       // q t xR xL k q\n        C.swap(1);      // t q xR xL k q\n        C.dup(1);       // q t q xR xL k q\n        C.dup(0);       // q q t q xR xL k q\n        C.dup(2);       // t q q t q xR xL k q\n        C.dup(0);       // t t q q t q xR xL k q\n        C.mulmod();     // b=t^2 q t q xR xL k q\n        C.dup(0);       // b b q t q xR xL k q\n        C.mulmod();     // c=t^4 t q xR xL k q\n        C.mulmod();     // d=t^5 xR xL k q\n        C.dup(4);       // q d xR xL k q\n        C.swap(2);      // xR d q xL k q\n        C.addmod();     // e=t^5+xR xL k q (for next round: xL xR k q)\n    }\n\n    C.push(\"0x20\");\n    C.mstore();     // Save it to pos 0;\n    C.push(\"0x00\");\n    C.mstore();     // Save it to pos 1;\n    C.push(\"0x40\");\n    C.push(\"0x00\");\n    C.return();\n\n    return C.createTxData();\n}\n\nmodule.exports.abi = [\n    {\n        \"constant\": true,\n        \"inputs\": [\n            {\n                \"name\": \"xL_in\",\n                \"type\": \"uint256\"\n            },\n            {\n                \"name\": \"xR_in\",\n                \"type\": \"uint256\"\n            },\n            {\n                \"name\": \"k\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"name\": \"MiMCSponge\",\n        \"outputs\": [\n            {\n                \"name\": \"xL\",\n                \"type\": \"uint256\"\n            },\n            {\n                \"name\": \"xR\",\n                \"type\": \"uint256\"\n            }\n        ],\n        \"payable\": false,\n        \"stateMutability\": \"pure\",\n        \"type\": \"function\"\n    }\n];\n\nmodule.exports.createCode = createCode;\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimcsponge_printconstants.js",
        "content": "const mimcsponge = require(\"./mimcsponge.js\");\n\nconst nRounds = 220;\nlet S = \"[\\n\";\nconst cts = mimcsponge.getConstants();\nfor (let i=0; i<nRounds; i++) {\n    S = S + cts[i].toString();\n    if (i<nRounds-1) S = S + \",\";\n    S=S+\"\\n\";\n}\nS = S + \"]\\n\";\n\nconsole.log(S);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/mimcsponge_printcontract.js",
        "content": "const mimcGenContract = require(\"./mimcsponge_gencontract\");\n\nconst SEED = \"mimcsponge\";\n\nlet nRounds;\nif (typeof process.argv[2] != \"undefined\") {\n    nRounds = parseInt(process.argv[2]);\n} else {\n    nRounds = 220;\n}\n\nconsole.log(mimcGenContract.createCode(SEED, nRounds));\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/pedersenHash.js",
        "content": "const babyJub = require(\"./babyjub\");\nconst createBlakeHash = require(\"blake-hash\");\nconst blake2b = require(\"blake2b\");\nconst Scalar = require(\"ffjavascript\").Scalar;\n\nconst GENPOINT_PREFIX = \"PedersenGenerator\";\nconst windowSize = 4;\nconst nWindowsPerSegment = 50;\n\nexports.hash = pedersenHash;\nexports.getBasePoint = getBasePoint;\n\nfunction baseHash(type, S) {\n    if (type == \"blake\") {\n        return createBlakeHash(\"blake256\").update(S).digest();\n    } else if (type == \"blake2b\") {\n        return Buffer.from(blake2b(32).update(Buffer.from(S)).digest());\n    }\n}\n\nfunction pedersenHash(msg, options) {\n    options = options || {};\n    options.baseHash = options.baseHash || \"blake\";\n    const bitsPerSegment = windowSize*nWindowsPerSegment;\n    const bits = buffer2bits(msg);\n\n    const nSegments = Math.floor((bits.length - 1)/(windowSize*nWindowsPerSegment)) +1;\n\n    let accP = [babyJub.F.zero,babyJub.F.one];\n\n    for (let s=0; s<nSegments; s++) {\n        let nWindows;\n        if (s == nSegments-1) {\n            nWindows = Math.floor(((bits.length - (nSegments - 1)*bitsPerSegment) - 1) / windowSize) +1;\n        } else {\n            nWindows = nWindowsPerSegment;\n        }\n        let escalar = Scalar.e(0);\n        let exp = Scalar.e(1);\n        for (let w=0; w<nWindows; w++) {\n            let o = s*bitsPerSegment + w*windowSize;\n            let acc = Scalar.e(1);\n            for (let b=0; ((b<windowSize-1)&&(o<bits.length)) ; b++) {\n                if (bits[o]) {\n                    acc = Scalar.add(acc, Scalar.shl(Scalar.e(1), b) );\n                }\n                o++;\n            }\n            if (o<bits.length) {\n                if (bits[o]) {\n                    acc = Scalar.neg(acc);\n                }\n                o++;\n            }\n            escalar = Scalar.add(escalar, Scalar.mul(acc, exp));\n            exp = Scalar.shl(exp, windowSize+1);\n        }\n\n        if (Scalar.lt(escalar, 0)) {\n            escalar = Scalar.add( escalar, babyJub.subOrder);\n        }\n\n        accP = babyJub.addPoint(accP, babyJub.mulPointEscalar(getBasePoint(options.baseHash, s), escalar));\n    }\n\n    return babyJub.packPoint(accP);\n}\n\nlet bases = [];\n\nfunction getBasePoint(baseHashType, pointIdx) {\n    if (pointIdx<bases.length) return bases[pointIdx];\n    let p= null;\n    let tryIdx = 0;\n    while (p==null) {\n        const S = GENPOINT_PREFIX + \"_\" + padLeftZeros(pointIdx, 32) + \"_\" + padLeftZeros(tryIdx, 32);\n        const h = baseHash(baseHashType, S);\n        h[31] = h[31] & 0xBF;  // Set 255th bit to 0 (256th is the signal and 254th is the last possible bit to 1)\n        p = babyJub.unpackPoint(h);\n        tryIdx++;\n    }\n\n    const p8 = babyJub.mulPointEscalar(p, 8);\n\n    if (!babyJub.inSubgroup(p8)) {\n        throw new Error(\"Point not in curve\");\n    }\n\n    bases[pointIdx] = p8;\n    return p8;\n}\n\nfunction padLeftZeros(idx, n) {\n    let sidx = \"\" + idx;\n    while (sidx.length<n) sidx = \"0\"+sidx;\n    return sidx;\n}\n\n/*\nInput a buffer\nReturns an array of booleans. 0 is LSB of first byte and so on.\n */\nfunction buffer2bits(buff) {\n    const res = new Array(buff.length*8);\n    for (let i=0; i<buff.length; i++) {\n        const b = buff[i];\n        res[i*8] = b & 0x01;\n        res[i*8+1] = b & 0x02;\n        res[i*8+2] = b & 0x04;\n        res[i*8+3] = b & 0x08;\n        res[i*8+4] = b & 0x10;\n        res[i*8+5] = b & 0x20;\n        res[i*8+6] = b & 0x40;\n        res[i*8+7] = b & 0x80;\n    }\n    return res;\n}\n\n\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/pedersen_printbases.js",
        "content": "const pedersenHash = require(\"./pedersenHash.js\");\n\nlet nBases;\nif (typeof process.argv[2] != \"undefined\") {\n    nBases = parseInt(process.argv[2]);\n} else {\n    nBases = 5;\n}\n\nlet baseHash;\nif (typeof process.argv[3] != \"undefined\") {\n    baseHash = process.argv[3];\n} else {\n    baseHash = \"blake\";\n}\n\n\nfor (let i=0; i < nBases; i++) {\n    const p = pedersenHash.getBasePoint(baseHash, i);\n    console.log(`[${p[0]},${p[1]}]`);\n}\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/poseidon.js",
        "content": "const assert = require(\"assert\");\nconst Scalar = require(\"ffjavascript\").Scalar;\nconst ZqField = require(\"ffjavascript\").ZqField;\nconst { unstringifyBigInts } = require(\"ffjavascript\").utils;\n\n// Prime 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\nconst F = new ZqField(Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\"));\n\n// Parameters are generated by a reference script https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/generate_parameters_grain.sage\n// Used like so: sage generate_parameters_grain.sage 1 0 254 2 8 56 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\nconst { C, M } = unstringifyBigInts(require(\"./poseidon_constants.json\"));\n\n// Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8)\n// Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py\n// And rounded up to nearest integer that divides by t\nconst N_ROUNDS_F = 8;\nconst N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63];\n\nconst pow5 = a => F.mul(a, F.square(F.square(a, a)));\n\nfunction poseidon(inputs) {\n    assert(inputs.length > 0);\n    assert(inputs.length < N_ROUNDS_P.length - 1);\n\n    const t = inputs.length + 1;\n    const nRoundsF = N_ROUNDS_F;\n    const nRoundsP = N_ROUNDS_P[t - 2];\n\n    let state = [F.zero, ...inputs.map(a => F.e(a))];\n    for (let r = 0; r < nRoundsF + nRoundsP; r++) {\n        state = state.map((a, i) => F.add(a, C[t - 2][r * t + i]));\n\n        if (r < nRoundsF / 2 || r >= nRoundsF / 2 + nRoundsP) {\n            state = state.map(a => pow5(a));\n        } else {\n            state[0] = pow5(state[0]);\n        }\n\n        state = state.map((_, i) =>\n            state.reduce((acc, a, j) => F.add(acc, F.mul(M[t - 2][i][j], a)), F.zero)\n        );\n    }\n    return F.normalize(state[0]);\n}\n\nmodule.exports = poseidon;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/poseidon_gencontract.js",
        "content": "// Copyright (c) 2018 Jordi Baylina\n// License: LGPL-3.0+\n//\n\nconst Contract = require(\"./evmasm\");\nconst { unstringifyBigInts } = require(\"ffjavascript\").utils;\nconst Web3Utils = require(\"web3-utils\");\n\nconst { C:K, M } = unstringifyBigInts(require(\"./poseidon_constants.json\"));\n\nconst N_ROUNDS_F = 8;\nconst N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63];\n\nfunction toHex256(a) {\n    let S = a.toString(16);\n    while (S.length < 64) S=\"0\"+S;\n    return \"0x\" + S;\n}\n\nfunction createCode(nInputs) {\n\n    if (( nInputs<1) || (nInputs>8)) throw new Error(\"Invalid number of inputs. Must be 1<=nInputs<=8\");\n    const t = nInputs + 1;\n    const nRoundsF = N_ROUNDS_F;\n    const nRoundsP = N_ROUNDS_P[t - 2];\n\n    const C = new Contract();\n\n    function saveM() {\n        for (let i=0; i<t; i++) {\n            for (let j=0; j<t; j++) {\n                C.push(toHex256(M[t-2][i][j]));\n                C.push((1+i*t+j)*32);\n                C.mstore();\n            }\n        }\n    }\n\n    function ark(r) {   // st, q\n        for (let i=0; i<t; i++) {\n            C.dup(t); // q, st, q\n            C.push(toHex256(K[t-2][r*t+i]));  // K, q, st, q\n            C.dup(2+i); // st[i], K, q, st, q\n            C.addmod(); // newSt[i], st, q\n            C.swap(1 + i); // xx, st, q\n            C.pop();\n        }\n    }\n\n    function sigma(p) {\n        // sq, q\n        C.dup(t);   // q, st, q\n        C.dup(1+p); // st[p] , q , st, q\n        C.dup(1);   // q, st[p] , q , st, q\n        C.dup(0);   // q, q, st[p] , q , st, q\n        C.dup(2);   // st[p] , q, q, st[p] , q , st, q\n        C.dup(0);   // st[p] , st[p] , q, q, st[p] , q , st, q\n        C.mulmod(); // st2[p], q, st[p] , q , st, q\n        C.dup(0);   // st2[p], st2[p], q, st[p] , q , st, q\n        C.mulmod(); // st4[p], st[p] , q , st, q\n        C.mulmod(); // st5[p], st, q\n        C.swap(1+p);\n        C.pop();      // newst, q\n    }\n\n    function mix() {\n        C.label(\"mix\");\n        for (let i=0; i<t; i++) {\n            for (let j=0; j<t; j++) {\n                if (j==0) {\n                    C.dup(i+t);      // q, newSt, oldSt, q\n                    C.push((1+i*t+j)*32);\n                    C.mload();      // M, q, newSt, oldSt, q\n                    C.dup(2+i+j);    // oldSt[j], M, q, newSt, oldSt, q\n                    C.mulmod();      // acc, newSt, oldSt, q\n                } else {\n                    C.dup(1+i+t);    // q, acc, newSt, oldSt, q\n                    C.push((1+i*t+j)*32);\n                    C.mload();      // M, q, acc, newSt, oldSt, q\n                    C.dup(3+i+j);    // oldSt[j], M, q, acc, newSt, oldSt, q\n                    C.mulmod();      // aux, acc, newSt, oldSt, q\n                    C.dup(2+i+t);    // q, aux, acc, newSt, oldSt, q\n                    C.swap(2);       // acc, aux, q, newSt, oldSt, q\n                    C.addmod();      // acc, newSt, oldSt, q\n                }\n            }\n        }\n        for (let i=0; i<t; i++) {\n            C.swap((t -i) + (t -i-1));\n            C.pop();\n        }\n        C.push(0);\n        C.mload();\n        C.jmp();\n    }\n\n\n    // Check selector\n    C.push(\"0x0100000000000000000000000000000000000000000000000000000000\");\n    C.push(0);\n    C.calldataload();\n    C.div();\n    C.dup(0);\n    C.push(Web3Utils.keccak256(`poseidon(uint256[${nInputs}])`).slice(0, 10)); // poseidon(uint256[n])\n    C.eq();\n    C.swap(1);\n    C.push(Web3Utils.keccak256(`poseidon(bytes32[${nInputs}])`).slice(0, 10)); // poseidon(bytes32[n])\n    C.eq();\n    C.or();\n    C.jmpi(\"start\");\n    C.invalid();\n\n    C.label(\"start\");\n\n    saveM();\n\n    C.push(\"0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\");  // q\n\n    // Load t values from the call data.\n    // The function has a single array param param\n    // [Selector (4)] [item1 (32)] [item2 (32)] ....\n    // Stack positions 0-nInputs.\n    for (let i=0; i<nInputs; i++) {\n        C.push(0x04+(0x20*(nInputs-i-1)));\n        C.calldataload();\n    }\n\n    C.push(0);\n\n    for (let i=0; i<nRoundsF+nRoundsP; i++) {\n        ark(i);\n        if ((i<nRoundsF/2) || (i>=nRoundsP+nRoundsF/2)) {\n            for (let j=0; j<t; j++) {\n                sigma(j);\n            }\n        } else {\n            sigma(0);\n        }\n        const strLabel = \"aferMix\"+i;\n        C._pushLabel(strLabel);\n        C.push(0);\n        C.mstore();\n        C.jmp(\"mix\");\n        C.label(strLabel);\n    }\n\n    C.push(\"0x00\");\n    C.mstore();     // Save it to pos 0;\n    C.push(\"0x20\");\n    C.push(\"0x00\");\n    C.return();\n\n    mix();\n\n    return C.createTxData();\n}\n\nfunction generateABI(nInputs) {\n    return [\n        {\n            \"constant\": true,\n            \"inputs\": [\n                {\n                    \"internalType\": `bytes32[${nInputs}]`,\n                    \"name\": \"input\",\n                    \"type\": `bytes32[${nInputs}]`\n                }\n            ],\n            \"name\": \"poseidon\",\n            \"outputs\": [\n                {\n                    \"internalType\": \"bytes32\",\n                    \"name\": \"\",\n                    \"type\": \"bytes32\"\n                }\n            ],\n            \"payable\": false,\n            \"stateMutability\": \"pure\",\n            \"type\": \"function\"\n        },\n        {\n            \"constant\": true,\n            \"inputs\": [\n                {\n                    \"internalType\": `uint256[${nInputs}]`,\n                    \"name\": \"input\",\n                    \"type\": `uint256[${nInputs}]`\n                }\n            ],\n            \"name\": \"poseidon\",\n            \"outputs\": [\n                {\n                    \"internalType\": \"uint256\",\n                    \"name\": \"\",\n                    \"type\": \"uint256\"\n                }\n            ],\n            \"payable\": false,\n            \"stateMutability\": \"pure\",\n            \"type\": \"function\"\n        }\n    ];\n}\n\nmodule.exports.generateABI = generateABI;\nmodule.exports.createCode = createCode;\n\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/poseidon_printcontract.js",
        "content": "const poseidonGenContract = require(\"./poseidon_gencontract\");\n\nif (process.argv.length != 3) {\n    console.log(\"Usage: node poseidon_gencontract.js [numberOfInputs]\");\n    process.exit(1);\n}\n\nconst nInputs = Number(process.argv[2]);\n\nconsole.log(nInputs);\n\nconsole.log(poseidonGenContract.createCode(nInputs));\n\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/poseidon_printmatrix.js",
        "content": "\n\nconst Poseidon = require(\"./poseidon.js\");\n\nconst M = Poseidon.getMatrix();\n\nlet S = \"[\\n    \";\n\nfor (let i=0; i<M.length; i++) {\n    const LC = M[i];\n    S = S + \"[\\n\";\n    for (let j=0; j<LC.length; j++) {\n        S = S + \"        \" + M[i][j].toString();\n        if (j<LC.length-1) S = S + \",\";\n        S = S + \"\\n\";\n    }\n    S = S + \"    ]\";\n    if (i<M.length-1) S = S + \",\";\n}\nS=S+ \"\\n]\\n\";\n\nconsole.log(S);\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/smt.js",
        "content": "const Scalar = require(\"ffjavascript\").Scalar;\nconst SMTMemDB = require(\"./smt_memdb\");\nconst {hash0, hash1, F} = require(\"./smt_hashes_poseidon\");\n\nclass SMT {\n\n    constructor(db, root) {\n        this.db = db;\n        this.root = root;\n    }\n\n    _splitBits(_key) {\n        const res = Scalar.bits(_key);\n\n        while (res.length<256) res.push(false);\n\n        return res;\n    }\n\n    async update(_key, _newValue) {\n        const key = Scalar.e(_key);\n        const newValue = F.e(_newValue);\n\n\n        const resFind = await this.find(key);\n        const res = {};\n        res.oldRoot = this.root;\n        res.oldKey = key;\n        res.oldValue = resFind.foundValue;\n        res.newKey = key;\n        res.newValue = newValue;\n        res.siblings = resFind.siblings;\n\n        const ins = [];\n        const dels = [];\n\n        let rtOld = hash1(key, resFind.foundValue);\n        let rtNew = hash1(key, newValue);\n        ins.push([rtNew, [1, key, newValue ]]);\n        dels.push(rtOld);\n\n        const keyBits = this._splitBits(key);\n        for (let level = resFind.siblings.length-1; level >=0; level--) {\n            let oldNode, newNode;\n            const sibling = resFind.siblings[level];\n            if (keyBits[level]) {\n                oldNode = [sibling, rtOld];\n                newNode = [sibling, rtNew];\n            } else {\n                oldNode = [rtOld, sibling];\n                newNode = [rtNew, sibling];\n            }\n            rtOld = hash0(oldNode[0], oldNode[1]);\n            rtNew = hash0(newNode[0], newNode[1]);\n            dels.push(rtOld);\n            ins.push([rtNew, newNode]);\n        }\n\n        res.newRoot = rtNew;\n\n        await this.db.multiDel(dels);\n        await this.db.multiIns(ins);\n        await this.db.setRoot(rtNew);\n        this.root = rtNew;\n\n        return res;\n    }\n\n    async delete(_key) {\n        const key = Scalar.e(_key);\n\n        const resFind = await this.find(key);\n        if (!resFind.found) throw new Error(\"Key does not exists\");\n\n        const res = {\n            siblings: [],\n            delKey: key,\n            delValue: resFind.foundValue\n        };\n\n        const dels = [];\n        const ins = [];\n        let rtOld = hash1(key, resFind.foundValue);\n        let rtNew;\n        dels.push(rtOld);\n\n        let mixed;\n        if (resFind.siblings.length > 0) {\n            const record = await this.db.get(resFind.siblings[resFind.siblings.length - 1]);\n            if ((record.length == 3)&&(F.eq(record[0], F.one))) {\n                mixed = false;\n                res.oldKey = record[1];\n                res.oldValue = record[2];\n                res.isOld0 = false;\n                rtNew = resFind.siblings[resFind.siblings.length - 1];\n            } else if (record.length == 2) {\n                mixed = true;\n                res.oldKey = key;\n                res.oldValue = F.zero;\n                res.isOld0 = true;\n                rtNew = F.zero;\n            } else {\n                throw new Error(\"Invalid node. Database corrupted\");\n            }\n        } else {\n            rtNew = F.zero;\n            res.oldKey = key;\n            res.oldValue = F.zero;\n            res.isOld0 = true;\n        }\n\n        const keyBits = this._splitBits(key);\n\n        for (let level = resFind.siblings.length-1; level >=0; level--) {\n            let newSibling = resFind.siblings[level];\n            if ((level == resFind.siblings.length-1)&&(!res.isOld0)) {\n                newSibling = F.zero;\n            }\n            const oldSibling = resFind.siblings[level];\n            if (keyBits[level]) {\n                rtOld = hash0(oldSibling, rtOld);\n            } else {\n                rtOld = hash0(rtOld, oldSibling);\n            }\n            dels.push(rtOld);\n            if (!F.isZero(newSibling)) {\n                mixed = true;\n            }\n\n            if (mixed) {\n                res.siblings.unshift(resFind.siblings[level]);\n                let newNode;\n                if (keyBits[level]) {\n                    newNode = [newSibling, rtNew];\n                } else {\n                    newNode = [rtNew, newSibling];\n                }\n                rtNew = hash0(newNode[0], newNode[1]);\n                ins.push([rtNew, newNode]);\n            }\n        }\n\n        await this.db.multiIns(ins);\n        await this.db.setRoot(rtNew);\n        this.root = rtNew;\n        await this.db.multiDel(dels);\n\n        res.newRoot = rtNew;\n        res.oldRoot = rtOld;\n\n        return res;\n    }\n\n    async insert(_key, _value) {\n        const key = Scalar.e(_key);\n        const value = F.e(_value);\n        let addedOne = false;\n        const res = {};\n        res.oldRoot = this.root;\n        const newKeyBits = this._splitBits(key);\n\n        let rtOld;\n\n        const resFind = await this.find(key);\n\n        if (resFind.found) throw new Error(\"Key already exists\");\n\n        res.siblings = resFind.siblings;\n        let mixed;\n\n        if (!resFind.isOld0) {\n            const oldKeyits = this._splitBits(resFind.notFoundKey);\n            for (let i= res.siblings.length; oldKeyits[i] == newKeyBits[i]; i++) {\n                res.siblings.push(F.zero);\n            }\n            rtOld = hash1(resFind.notFoundKey, resFind.notFoundValue);\n            res.siblings.push(rtOld);\n            addedOne = true;\n            mixed = false;\n        } else if (res.siblings.length >0) {\n            mixed = true;\n            rtOld = F.zero;\n        }\n\n        const inserts = [];\n        const dels = [];\n\n        let rt = hash1(key, value);\n        inserts.push([rt,[1, key, value]] );\n\n        for (let i=res.siblings.length-1; i>=0; i--) {\n            if ((i<res.siblings.length-1)&&(!F.isZero(res.siblings[i]))) {\n                mixed = true;\n            }\n            if (mixed) {\n                const oldSibling = resFind.siblings[i];\n                if (newKeyBits[i]) {\n                    rtOld = hash0(oldSibling, rtOld);\n                } else {\n                    rtOld = hash0(rtOld, oldSibling);\n                }\n                dels.push(rtOld);\n            }\n\n\n            let newRt;\n            if (newKeyBits[i]) {\n                newRt = hash0(res.siblings[i], rt);\n                inserts.push([newRt,[res.siblings[i], rt]] );\n            } else {\n                newRt = hash0(rt, res.siblings[i]);\n                inserts.push([newRt,[rt, res.siblings[i]]] );\n            }\n            rt = newRt;\n        }\n\n        if (addedOne) res.siblings.pop();\n        while ((res.siblings.length>0) && (F.isZero(res.siblings[res.siblings.length-1]))) {\n            res.siblings.pop();\n        }\n        res.oldKey = resFind.notFoundKey;\n        res.oldValue = resFind.notFoundValue;\n        res.newRoot = rt;\n        res.isOld0 = resFind.isOld0;\n\n\n        await this.db.multiIns(inserts);\n        await this.db.setRoot(rt);\n        this.root = rt;\n        await this.db.multiDel(dels);\n\n        return res;\n    }\n\n    async find(key) {\n        const keyBits = this._splitBits(key);\n        return await this._find(key, keyBits, this.root, 0);\n    }\n\n    async _find(key, keyBits, root, level) {\n        if (typeof root === \"undefined\") root = this.root;\n\n        let res;\n        if (F.isZero(root)) {\n            res = {\n                found: false,\n                siblings: [],\n                notFoundKey: key,\n                notFoundValue: F.zero,\n                isOld0: true\n            };\n            return res;\n        }\n\n        const record = await this.db.get(root);\n\n        if ((record.length==3)&&(F.eq(record[0],F.one))) {\n            if (F.eq(record[1],key)) {\n                res = {\n                    found: true,\n                    siblings: [],\n                    foundValue: record[2],\n                    isOld0: false\n                };\n            } else {\n                res = {\n                    found: false,\n                    siblings: [],\n                    notFoundKey: record[1],\n                    notFoundValue: record[2],\n                    isOld0: false\n                };\n            }\n        } else {\n            if (keyBits[level] == 0) {\n                res = await this._find(key, keyBits, record[0], level+1);\n                res.siblings.unshift(record[1]);\n            } else {\n                res = await this._find(key, keyBits, record[1], level+1);\n                res.siblings.unshift(record[0]);\n            }\n        }\n        return res;\n    }\n}\n\nasync function loadFromFile(fileName) {\n\n}\n\nasync function newMemEmptyTrie() {\n    const db = new SMTMemDB();\n    const rt = await db.getRoot();\n    const smt = new SMT(db, rt);\n    return smt;\n}\n\nmodule.exports.loadFromFile = loadFromFile;\nmodule.exports.newMemEmptyTrie = newMemEmptyTrie;\nmodule.exports.SMT = SMT;\nmodule.exports.SMTMemDB = SMTMemDB;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/smt_hashes_mimc.js",
        "content": "const mimc7 = require(\"./mimc7\");\nconst bigInt = require(\"big-integer\");\n\nexports.hash0 = function (left, right) {\n    return mimc7.multiHash(left, right);\n};\n\nexports.hash1 = function(key, value) {\n    return mimc7.multiHash([key, value], bigInt.one);\n};\n\nexports.F = mimc7.F;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/smt_hashes_poseidon.js",
        "content": "\nconst ZqField = require(\"ffjavascript\").ZqField;\nconst Scalar = require(\"ffjavascript\").Scalar;\n\nconst poseidon = require(\"./poseidon\");\n\nconst F = new ZqField(Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\"));\n\n\nexports.hash0 = function (left, right) {\n    return poseidon([left, right]);\n};\n\nexports.hash1 = function(key, value) {\n    return poseidon([key, value, F.one]);\n};\n\nexports.F = F;\n"
    },
    {
        "repo": "https://github.com/socathie/circomlib-ml",
        "file_path": "test/modules/src/smt_memdb.js",
        "content": "\nconst Scalar = require(\"ffjavascript\").Scalar;\nconst ZqField = require(\"ffjavascript\").ZqField;\n\n// Prime 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\nconst F = new ZqField(Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\"));\n\nclass SMTMemDb {\n    constructor() {\n        this.nodes = {};\n        this.root = F.zero;\n    }\n\n    async getRoot() {\n        return this.root;\n    }\n\n    _key2str(k) {\n        // const keyS = bigInt(key).leInt2Buff(32).toString(\"hex\");\n        const keyS = k.toString();\n        return keyS;\n    }\n\n    _normalize(n) {\n        for (let i=0; i<n.length; i++) {\n            n[i] = F.e(n[i]);\n        }\n    }\n\n    async get(key) {\n        const keyS = this._key2str(key);\n        return this.nodes[keyS];\n    }\n\n    async multiGet(keys) {\n        const promises = [];\n        for (let i=0; i<keys.length; i++) {\n            promises.push(this.get(keys[i]));\n        }\n        return await Promise.all(promises);\n    }\n\n    async setRoot(rt) {\n        this.root = rt;\n    }\n\n    async multiIns(inserts) {\n        for (let i=0; i<inserts.length; i++) {\n            const keyS = this._key2str(inserts[i][0]);\n            this._normalize(inserts[i][1]);\n            this.nodes[keyS] = inserts[i][1];\n        }\n    }\n\n    async multiDel(dels) {\n        for (let i=0; i<dels.length; i++) {\n            const keyS = this._key2str(dels[i]);\n            delete this.nodes[keyS];\n        }\n    }\n}\n\nmodule.exports = SMTMemDb;\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "build.rs",
        "content": "use eyre::{bail, eyre, Result, WrapErr as _};\nuse std::{\n    env::{var, VarError},\n    fs,\n    path::Path,\n    process::Command,\n};\nuse time::{format_description::well_known::Rfc3339, OffsetDateTime, UtcOffset};\n\nfn main() -> Result<()> {\n    let commit = rerun_if_git_changes().unwrap_or_else(|e| {\n        eprintln!(\"Warning: {}\", e);\n        None\n    });\n\n    println!(\n        \"cargo:rustc-env=COMMIT_SHA={}\",\n        env_or_cmd(\"COMMIT_SHA\", &[\"git\", \"rev-parse\", \"HEAD\"]).unwrap_or_else(|e| {\n            eprintln!(\"Warning: {}\", e);\n            commit.unwrap_or_else(|| \"0000000000000000000000000000000000000000\".to_string())\n        })\n    );\n    let build_date = OffsetDateTime::now_utc();\n    let commit_date = env_or_cmd(\"COMMIT_DATE\", &[\n        \"git\",\n        \"log\",\n        \"-n1\",\n        \"--pretty=format:'%aI'\",\n    ])\n    .and_then(|str| Ok(OffsetDateTime::parse(str.trim_matches('\\''), &Rfc3339)?))\n    .unwrap_or_else(|e| {\n        eprintln!(\"Warning: {}\", e);\n        OffsetDateTime::UNIX_EPOCH\n    });\n    println!(\n        \"cargo:rustc-env=COMMIT_DATE={}\",\n        commit_date.to_offset(UtcOffset::UTC).date()\n    );\n    println!(\n        \"cargo:rustc-env=BUILD_DATE={}\",\n        build_date.to_offset(UtcOffset::UTC).date()\n    );\n    println!(\n        \"cargo:rustc-env=TARGET={}\",\n        var(\"TARGET\").wrap_err(\"Fetching environment variable TARGET\")?\n    );\n\n    Ok(())\n}\n\nfn env_or_cmd(env: &str, cmd: &[&str]) -> Result<String> {\n    // Try env first\n    match var(env) {\n        Ok(s) => return Ok(s),\n        Err(VarError::NotPresent) => (),\n        Err(e) => bail!(e),\n    };\n\n    // Try command\n    let err = || {\n        format!(\n            \"Variable {} is unset and command \\\"{}\\\" failed\",\n            env,\n            cmd.join(\" \")\n        )\n    };\n    let output = Command::new(cmd[0])\n        .args(&cmd[1..])\n        .output()\n        .with_context(err)?;\n    if output.status.success() {\n        Ok(String::from_utf8(output.stdout)?.trim().to_string())\n    } else {\n        bail!(err())\n    }\n}\n\nfn rerun_if_git_changes() -> Result<Option<String>> {\n    let git_head = Path::new(\".git/HEAD\");\n\n    // Skip if not in a git repo\n    if !git_head.exists() {\n        eprintln!(\"No .git/HEAD found, not rerunning on git change\");\n        return Ok(None);\n    }\n\n    // TODO: Worktree support where `.git` is a file\n    println!(\"cargo:rerun-if-changed=.git/HEAD\");\n\n    // If HEAD contains a ref, then echo that path also.\n    let contents = fs::read_to_string(git_head).wrap_err(\"Error reading .git/HEAD\")?;\n    let head_ref = contents.split(\": \").collect::<Vec<_>>();\n    let commit = if head_ref.len() == 2 && head_ref[0] == \"ref\" {\n        let ref_path = Path::new(\".git\").join(head_ref[1].trim());\n        let ref_path_str = ref_path\n            .to_str()\n            .ok_or_else(|| eyre!(\"Could not convert ref path {:?} to string\", ref_path))?;\n        println!(\"cargo:rerun-if-changed={}\", ref_path_str);\n        fs::read_to_string(&ref_path).with_context(|| format!(\"Error reading {}\", ref_path_str))?\n    } else {\n        contents\n    };\n    Ok(Some(commit))\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "criterion.rs",
        "content": "use neural_zkp as lib;\n\nfn main() {\n    let mut criterion = criterion::Criterion::default().configure_from_args();\n    lib::bench::group(&mut criterion);\n    criterion.final_summary();\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "ref_cnn/benchmark_cnn.py",
        "content": "### Will take a long time! Took 13.2min on my machine (M1 Max MBP - DC)\nimport timeit\nimport numpy as np\nfrom vanilla_cnn import *\n\nif __name__ == \"__main__\":\n    \n    # instantiate matrices outside of time it block\n    np.random.seed(12345)\n\n    x = np.random.randint(low=-5, high=5, size=(120, 80, 3))\n\n    f = np.random.randint(low=-10, high=+10, size=(32, 5, 5, 3)) \n\n    k = np.random.randint(low=-10, high=+10, size=(32,5,5,32)) \n\n    weights1 = np.random.randint(low=-10, high=+10, size=(1000, 14688)) \n\n    biases1 = np.random.randint(low=-10, high=+10, size=(1000)) \n\n    weights2 = np.random.randint(low=-10, high=+10, size=(5, 1000)) \n\n    biases2 = np.random.randint(low=-10, high=+10, size=(5)) \n\n    times = []\n\n    runs = 100\n\n    for _ in range(runs):\n        starttime = timeit.default_timer()\n        # conv layer\n        x, n_params, n_multiplications, name = conv_layer(x, f)\n\n        # max pooling\n        x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\n\n        # relu layer\n        x, n_params, n_multiplications, name = relu_layer(x)\n\n        # conv layer\n        x, n_params, n_multiplications, name = conv_layer(x, k)\n\n        # max pooling\n        x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\n\n        # relu layer\n        x, n_params, n_multiplications, name = relu_layer(x)\n\n        # flatten\n        x, n_params, n_multiplications, name =  flatten_layer(x)\n\n        # fully connected\n        x, n_params, n_multiplications, name = fully_connected_layer(x, weights1, biases1)\n\n        # relu layer\n        x, n_params, n_multiplications, name = relu_layer(x)\n\n        # fully connected\n        x, n_params, n_multiplications, name = fully_connected_layer(x, weights2, biases2)\n\n        # normalization\n        x, n_params, n_multiplications, name = normalize(x)\n\n        times.append(timeit.default_timer() - starttime)\n\n        np.random.seed(12345)\n\n        x = np.random.randint(low=-5, high=5, size=(120, 80, 3))\n\n    average = sum(times) / len(times)\n    print(f'The average time is {average} seconds for {runs} runs')\n    # Result = 0.8297840171150046 for 1000 runs"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "ref_cnn/generate_cnn_json.py",
        "content": "# Imports\nimport json\nfrom json import JSONEncoder\nimport numpy as np\nfrom enum import Enum\nimport re\n\n# Encoder\nclass Encoder(JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj, Layer):\n            return obj.value[0]\n        return JSONEncoder.default(self, obj)\n\n\n# Layer definitions\ndef conv_layer(input, f):\n    \"\"\"\n    Evaluate the output of a convolutional layer using the filter f.\n    input.shape = (h, w, c)\n    f.shape = (c_out, hf, wf, c_in)\n    \"\"\"\n    h, w, c = input.shape\n    c_out, hf, wf, c_in = f.shape\n\n    assert c == c_in, \"Input channels must match!\"\n    assert hf%2 == 1, \"Height of the filter (f.shape[1]) must be an uneven number!\"\n    assert wf%2 == 1, \"Width of the filter (f.shape[2]) must be an uneven number!\"\n\n    # unilateral width and heght\n    dh = hf//2\n    dw = wf//2\n\n    # after convolution dw and dh get substracted from all sides of the image, c_out is number of convolutions which dictates # of channels\n    # initialize matrix with 0s\n    output = np.zeros(shape=(h-2*dh, w-2*dw, c_out))\n\n# run convolution\n# go over image height - kernel padding (2*dh)\n    for i in range(dh, h-dh):\n        # go over image width - kernel padding (2*dw)\n        for j in range(dw, w-dw):\n            # kernel slice\n            a = input[i-dh:i+dh+1, j-dw:j+dw+1]\n            for k in range(c_out):\n                # filter channel 1..c_out\n                b = f[k,:,:,:]\n                # apply filter\n                output[i-dh, j-dw, k] = (a*b).sum() # a.size multiplication\n    \n    n_params = f.size\n    n_multiplications = a.size * c_out * (w-2*dw) * (h-2*dh)\n    name = f\"conv {'x'.join([str(e) for e in f.shape])}\"\n    \n    return output, n_params, n_multiplications, name\n\n\ndef relu_layer(input):    \n    output = input.copy()\n    output[output<0] = 0\n    \n    n_params = 0\n    n_multiplications = input.size\n    \n    return output, n_params, n_multiplications, \"relu\"\n\n\ndef max_pooling_layer(input, s):\n    \"\"\"\n    Apply max pooling layer using a sxs patch.\n    \"\"\"\n    h, w, c = input.shape\n\n    assert h%s == 0, \"Height must be divisible by s!\"\n    assert w%s == 0, \"Width must be dibisible by s!\"\n\n    output = np.zeros(shape=(h//s, w//s, c))\n\n    for i in range(0, h, s):\n        for j in range(0, w, s):\n            for k in range(c):\n                a = input[i:i+s, j:j+s, k]\n                output[i//s, j//s, k] = a.max()\n    \n    n_params = 0\n    n_multiplications = input.size\n    return output, n_params, n_multiplications, \"max-pool\"\n\n\ndef flatten_layer(input):\n    output = input.flatten()\n    n_params = 0\n    n_multiplications = 0\n    return output, n_params, n_multiplications, \"flatten\"\n\n\ndef fully_connected_layer(input, weights, biases):\n    \"\"\"\n    Evaluate the output of a fully connected layer.\n    input.shape = (output_dim)\n    weights.shape = (output_dim, input_dim)\n    f.shape = (output_dim)\n    \"\"\"\n    assert input.ndim == 1, \"Input must be a flattend array!\"\n    assert weights.shape[1] == input.shape[0], \"Input shapes must match!\"\n    assert weights.shape[0] == biases.shape[0], \"Output shapes must match!\"\n\n    output = np.dot(weights, input) + biases\n    \n    n_params = weights.size + biases.size\n    n_multiplications = weights.size\n    name = f\"full {'x'.join([str(e) for e in weights.shape])}\"\n    \n    return output, n_params, n_multiplications, name\n\n\ndef normalize(input):\n    output = input / np.linalg.norm(input)\n    n_params = 0\n    n_multiplications = 1 + input.size\n    return output, n_params, n_multiplications, \"normalize\"\n\n############\n#      Model    #\n############\n\nclass Layer(Enum):\n    Convolution = 'convolution',\n    MaxPool = 'max_pool',\n    Relu = 'relu',\n    Flatten = 'flatten',\n    FullyConnected = 'fully_connected',\n    Normalize = 'normalize',\n\n\nnp.random.seed(12345)\n\np = \"{:>20} | {:>15} | {:>15} | {:>15} \"\nprint(p.format(\"layer\", \"output shape\", \"#parameters\", \"#ops\"))\nprint(p.format(\"-\"*20, \"-\"*15, \"-\"*15, \"-\"*15))\n\n\nshape = (120,80,3)\n\n# input\nx = np.random.randint(low=-5, high=5, size=shape)\n\ninitial = x.flatten().astype(np.float32, copy=False)\n\ndata = {\n    \"v\": 1,\n    \"dim\": shape,\n    \"data\": initial\n    }\n\n# conv layer\nshape = (32,5,5,3)\nf = np.random.randint(low=-10, high=+10, size=shape) \n\nconv1 = f.flatten().astype(np.float32, copy=False)\n\ndata = {\n    \"v\": 1,\n    \"dim\": shape,\n    \"data\": conv1\n    }\n\nconv = {\n    \"layer_type\": Layer.Convolution,\n    \"input_shape\": x.shape,\n    \"kernel\": data,\n}\n\nmodel = [conv]\n\nx, n_params, n_multiplications, name = conv_layer(x, f)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# max pooling\nmaxpool = {\n    \"layer_type\": Layer.MaxPool,\n    \"input_shape\": x.shape,\n    \"window\": 2,\n}\n\nmodel.append(maxpool)\n\nx, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# relu layer\nrelu = {\n    \"layer_type\": Layer.Relu,\n    \"input_shape\": x.shape\n}\n\nmodel.append(relu)\n\nx, n_params, n_multiplications, name = relu_layer(x)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# conv layer\nshape = (32,5,5,32)\n\nf = np.random.randint(low=-10, high=+10, size=shape) \n\nconv2 = f.flatten().astype(np.float32, copy=False)\n\ndata = {\n    \"v\": 1,\n    \"dim\": shape,\n    \"data\": conv2\n    }\n\nconv = {\n    \"layer_type\": Layer.Convolution,\n    \"input_shape\": x.shape,\n    \"kernel\":data\n}\n\nmodel.append(conv)\n\nx, n_params, n_multiplications, name = conv_layer(x, f)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# max pooling\nmaxpool = {\n    \"layer_type\": Layer.MaxPool,\n    \"input_shape\": x.shape,\n    \"window\": 2\n}\n\nmodel.append(maxpool)\n\nx, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# relu layer\nrelu = {\n    \"layer_type\": Layer.Relu,\n    \"input_shape\": x.shape,\n}\n\nmodel.append(relu)\n\nx, n_params, n_multiplications, name = relu_layer(x)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# flatten\nflatten = {\n    \"layer_type\": Layer.Flatten,\n    \"input_shape\": x.shape,\n}\n\nmodel.append(flatten)\n\nx, n_params, n_multiplications, name =  flatten_layer(x)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# fully connected\nshape = (1000, x.shape[0])\nweights = np.random.randint(low=-10, high=+10, size=shape)\n\n# weights json\ndata = {\n    \"v\": 1,\n    \"dim\": shape,\n    \"data\": weights.flatten().astype(np.float32, copy=False)\n}\n\n# biases json\nshape = [1000]\nbiases = np.random.randint(low=-10, high=+10, size=(1000))\n\ndata2 = {\n    \"v\": 1,\n    # ndarray can't take a single value, needs to be in json array\n    \"dim\": shape,\n    \"data\": biases.flatten().astype(np.float32, copy=False)\n}\n\nfully_connected = {\n    \"layer_type\": Layer.FullyConnected,\n    \"input_shape\": x.shape,\n    \"weights\":data,\n    \"biases\": data2\n}\n\nmodel.append(fully_connected)\n\nx, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# relu layer\nrelu = {\n    \"layer_type\": Layer.Relu,\n    \"input_shape\": x.shape,\n}\n\nmodel.append(relu)\n\nx, n_params, n_multiplications, name = relu_layer(x)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n# fully connected\nshape = (5, x.shape[0])\nweights = np.random.randint(low=-10, high=+10, size=shape)\n\ndata = {\n    \"v\": 1,\n    \"dim\": shape,\n    \"data\": weights.flatten().astype(np.float32, copy=False)\n}\n\nshape = [5]\nbiases = np.random.randint(low=-10, high=+10, size=shape)\n\ndata2 = {\n    \"v\": 1,\n    # ndarray can't take a single value, needs to be in json array\n    \"dim\": [5],\n    \"data\": biases.flatten().astype(np.float32, copy=False)\n}\n\nfully_connected = {\n    \"layer_type\": Layer.FullyConnected,\n    \"input_shape\": x.shape,\n    \"weights\":data,\n    \"biases\": data2\n}\n\nmodel.append(fully_connected)\n\nx, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\nassert(np.isclose(x, [ -9404869, -11033050, -34374361, -20396580,  70483360.]).all())\n\n# normalization\nnorm = {\n    \"layer_type\": Layer.Normalize,\n    \"input_shape\": x.shape,\n}\n\nmodel.append(norm)\n\nmodel = {\n    \"layers\": model\n}\n\nx, n_params, n_multiplications, name = normalize(x)\nprint(p.format(name, str(x.shape), n_params, n_multiplications))\n\n\nprint(\"\\nfinal output:\", x)\n\n\nmodel_data = json.dumps(model, cls=Encoder)\nwith open('../src/json/model.json', \"w\") as f:\n    print('\\ncreated model.json in the proto-neural-zkp/src/json folder')\n    f.write(model_data)"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "ref_cnn/prover_perf.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cf9cc6d3-87d9-4c07-8773-39cfcc94d0f5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# !pip install numpy pandas matplotlib watermark\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cb8f77a5-dc82-4c34-8ee8-4d510afb175d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import os\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"dc648e92-7bfa-4991-829b-012822604d0f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d306a253-dc0d-425f-b77a-44b0dfadcaa3\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import pandas as pd\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b73322c2-d188-4dae-8480-558a3317fd17\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import matplotlib as mpl\\n\",\n    \"\\n\",\n    \"# Defaults more suitable for 4K monitors\\n\",\n    \"mpl.rcParams[\\\"figure.dpi\\\"] = 120\\n\",\n    \"mpl.rcParams[\\\"figure.figsize\\\"] = [12.0, 8.0]\\n\",\n    \"# Change font to match Latex\\n\",\n    \"mpl.rcParams['mathtext.fontset'] = 'cm'\\n\",\n    \"mpl.rcParams['font.family'] = 'CMU Serif'\\n\",\n    \"# Export settings\\n\",\n    \"mpl.rcParams[\\\"savefig.bbox\\\"] = 'tight'\\n\",\n    \"mpl.rcParams[\\\"savefig.dpi\\\"] = 300\\n\",\n    \"mpl.rcParams[\\\"savefig.facecolor\\\"] = 'white'\\n\",\n    \"# High compression lossless WebP for animations using ffmpeg -> libwebp\\n\",\n    \"mpl.rcParams[\\\"animation.writer\\\"] = 'ffmpeg'\\n\",\n    \"mpl.rcParams[\\\"animation.codec\\\"] = 'webp'\\n\",\n    \"mpl.rcParams[\\\"animation.ffmpeg_args\\\"] = [\\\"-lossless\\\", \\\"1\\\", \\\"-qscale\\\", \\\"100\\\"]\\n\",\n    \"# Use anim.save(\\\"movie.webp\\\", fps=60)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"64b79d42-6bcf-49d4-899f-113f193f6d11\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import watermark.watermark as watermark\\n\",\n    \"print(watermark(machine=True, iso8601=True, python=True, iversions=True, globals_=globals()))\\n\",\n    \"print(os.getcwd())\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"33eec25e-635a-4779-b34f-09f638a246d2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df1 = pd.read_csv('../bench-1.csv')\\n\",\n    \"df1['ops'] = df.input_size * df.output_size\\n\",\n    \"df1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e0a47916-268f-42fb-8880-7298aef847e6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df2 = pd.read_csv('../bench-2.csv')\\n\",\n    \"df2['ops'] = df.input_size * df.output_size\\n\",\n    \"df2\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"fd37c694-d984-46af-af89-febee74eefcf\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df5 = pd.read_csv('../bench-5.csv')\\n\",\n    \"df5['ops'] = df.input_size * df.output_size\\n\",\n    \"df5\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d1d9a5d1-a8fa-417d-9ea3-378018f9ff36\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df10 = pd.read_csv('../bench-10.csv')\\n\",\n    \"df10['ops'] = df10.input_size * df10.output_size\\n\",\n    \"df10\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"952a923e-8241-4b78-a156-961bf1b85570\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"plt.title('Prover performance')\\n\",\n    \"plt.xlabel('# of muladds')\\n\",\n    \"plt.ylabel('proof time [s]')\\n\",\n    \"plt.plot(df1.ops, df1.proof_time_s, label='1 thread')\\n\",\n    \"plt.plot(df2.ops, df2.proof_time_s, label='2 thread')\\n\",\n    \"plt.plot(df5.ops, df5.proof_time_s, label='5 thread')\\n\",\n    \"plt.plot(df10.ops, df10.proof_time_s, label='10 threads')\\n\",\n    \"plt.ylim([0, 120])\\n\",\n    \"plt.legend()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"149a5d0c-a272-4fc4-b8fe-18771b9d6d44\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f758c3a7-4694-4673-971b-f5087b70c2ad\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"plt.title('Prover performance')\\n\",\n    \"plt.xlabel('# of muladds')\\n\",\n    \"plt.ylabel('utilization')\\n\",\n    \"plt.plot(df1.ops, df1.proof_time_s / (df2.proof_time_s * 2), label='2 thread utilization')\\n\",\n    \"plt.plot(df1.ops, df1.proof_time_s / (df5.proof_time_s * 5), label='5 thread utilization')\\n\",\n    \"plt.plot(df.ops, df1.proof_time_s / (df.proof_time_s * 10), label='10 thread utilization')\\n\",\n    \"plt.ylim([0, 1])\\n\",\n    \"plt.legend()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"25aaf206-4a58-47f1-8272-3df48b5e6e54\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"plt.title('Prover performance (1 threads)')\\n\",\n    \"plt.xlabel('# of muladds')\\n\",\n    \"plt.ylabel('memory [b]')\\n\",\n    \"plt.plot(df1.ops, df1.proof_mem_b, label='1 threads')\\n\",\n    \"plt.plot(df5.ops, df5.proof_mem_b, label='5 threads')\\n\",\n    \"plt.plot(df10.ops, df10.proof_mem_b, label='10 threads')\\n\",\n    \"plt.ylim([0, 1.1*np.max(df.proof_mem_b)])\\n\",\n    \"plt.legend()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3cef9590-7689-477f-bac3-21d68ff591c2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"99d7647e-e9f2-48ba-8ea3-27ab41b06808\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3 (ipykernel)\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.10\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "ref_cnn/vanilla_cnn.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d5c490d4\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Vanilla CNN layers implementation with numpy\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"794b9914-cce9-4d71-b20d-96df96f6403b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4c3349aa-434a-4c9b-a451-feeb341aaa72\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def conv_layer(input, f):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Evaluate the output of a convolutional layer using the filter f.\\n\",\n    \"    input.shape = (h, w, c)\\n\",\n    \"    f.shape = (c_out, hf, wf, c_in)\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    h, w, c = input.shape\\n\",\n    \"    c_out, hf, wf, c_in = f.shape\\n\",\n    \"\\n\",\n    \"    assert c == c_in, \\\"Input channels must match!\\\"\\n\",\n    \"    assert hf%2 == 1, \\\"Height of the filter (f.shape[1]) must be an uneven number!\\\"\\n\",\n    \"    assert wf%2 == 1, \\\"Width of the filter (f.shape[2]) must be an uneven number!\\\"\\n\",\n    \"\\n\",\n    \"    # unilateral width and heght\\n\",\n    \"    dh = hf//2\\n\",\n    \"    dw = wf//2\\n\",\n    \"\\n\",\n    \"    # after convolution dw and dh get substracted from all sides of the image, c_out is number of convolutions which dictates # of channels\\n\",\n    \"    # initialize matrix with 0s\\n\",\n    \"    output = np.zeros(shape=(h-2*dh, w-2*dw, c_out))\\n\",\n    \"\\n\",\n    \"# run convolution\\n\",\n    \"# go over image height - kernel padding (2*dh)\\n\",\n    \"    for i in range(dh, h-dh):\\n\",\n    \"        # go over image width - kernel padding (2*dw)\\n\",\n    \"        for j in range(dw, w-dw):\\n\",\n    \"            # kernel slice\\n\",\n    \"            a = input[i-dh:i+dh+1, j-dw:j+dw+1]\\n\",\n    \"            for k in range(c_out):\\n\",\n    \"                # filter channel 1..c_out\\n\",\n    \"                b = f[k,:,:,:]\\n\",\n    \"                # apply filter\\n\",\n    \"                output[i-dh, j-dw, k] = (a*b).sum() # a.size multiplication\\n\",\n    \"    \\n\",\n    \"    n_params = f.size\\n\",\n    \"    n_multiplications = a.size * c_out * (w-2*dw) * (h-2*dh)\\n\",\n    \"    name = f\\\"conv {'x'.join([str(e) for e in f.shape])}\\\"\\n\",\n    \"    \\n\",\n    \"    return output, n_params, n_multiplications, name\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def relu_layer(input):    \\n\",\n    \"    output = input.copy()\\n\",\n    \"    output[output<0] = 0\\n\",\n    \"    \\n\",\n    \"    n_params = 0\\n\",\n    \"    n_multiplications = input.size\\n\",\n    \"    \\n\",\n    \"    return output, n_params, n_multiplications, \\\"relu\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def max_pooling_layer(input, s):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Apply max pooling layer using a sxs patch.\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    h, w, c = input.shape\\n\",\n    \"\\n\",\n    \"    assert h%s == 0, \\\"Height must be divisible by s!\\\"\\n\",\n    \"    assert w%s == 0, \\\"Width must be dibisible by s!\\\"\\n\",\n    \"\\n\",\n    \"    output = np.zeros(shape=(h//s, w//s, c))\\n\",\n    \"\\n\",\n    \"    for i in range(0, h, s):\\n\",\n    \"        for j in range(0, w, s):\\n\",\n    \"            for k in range(c):\\n\",\n    \"                a = input[i:i+s, j:j+s, k]\\n\",\n    \"                output[i//s, j//s, k] = a.max()\\n\",\n    \"    \\n\",\n    \"    n_params = 0\\n\",\n    \"    n_multiplications = input.size\\n\",\n    \"    return output, n_params, n_multiplications, \\\"max-pool\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def flatten_layer(input):\\n\",\n    \"    output = input.flatten()\\n\",\n    \"    n_params = 0\\n\",\n    \"    n_multiplications = 0\\n\",\n    \"    return output, n_params, n_multiplications, \\\"flatten\\\"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def fully_connected_layer(input, weights, biases):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Evaluate the output of a fully connected layer.\\n\",\n    \"    input.shape = (output_dim)\\n\",\n    \"    weights.shape = (output_dim, input_dim)\\n\",\n    \"    f.shape = (output_dim)\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    assert input.ndim == 1, \\\"Input must be a flattend array!\\\"\\n\",\n    \"    assert weights.shape[1] == input.shape[0], \\\"Input shapes must match!\\\"\\n\",\n    \"    assert weights.shape[0] == biases.shape[0], \\\"Output shapes must match!\\\"\\n\",\n    \"\\n\",\n    \"    output = np.dot(weights, input) + biases\\n\",\n    \"    \\n\",\n    \"    n_params = weights.size + biases.size\\n\",\n    \"    n_multiplications = weights.size\\n\",\n    \"    name = f\\\"full {'x'.join([str(e) for e in weights.shape])}\\\"\\n\",\n    \"    \\n\",\n    \"    return output, n_params, n_multiplications, name\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def normalize(input):\\n\",\n    \"    output = input / np.linalg.norm(input)\\n\",\n    \"    n_params = 0\\n\",\n    \"    n_multiplications = 1 + input.size\\n\",\n    \"    return output, n_params, n_multiplications, \\\"normalize\\\"\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2896d5ed\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Vanilla CNN model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"00fd6550\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"np.random.seed(12345)\\n\",\n    \"\\n\",\n    \"p = \\\"{:>20} | {:>15} | {:>15} | {:>15} \\\"\\n\",\n    \"print(p.format(\\\"layer\\\", \\\"output shape\\\", \\\"#parameters\\\", \\\"#ops\\\"))\\n\",\n    \"print(p.format(\\\"-\\\"*20, \\\"-\\\"*15, \\\"-\\\"*15, \\\"-\\\"*15))\\n\",\n    \"\\n\",\n    \"# input\\n\",\n    \"x = np.random.randint(low=-5, high=5, size=(120,80,3))\\n\",\n    \"\\n\",\n    \"# conv layer\\n\",\n    \"f = np.random.randint(low=-10, high=+10, size=(32,5,5,3)) \\n\",\n    \"x, n_params, n_multiplications, name = conv_layer(x, f)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# max pooling\\n\",\n    \"x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# relu layer\\n\",\n    \"x, n_params, n_multiplications, name = relu_layer(x)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# conv layer\\n\",\n    \"f = np.random.randint(low=-10, high=+10, size=(32,5,5,32)) \\n\",\n    \"x, n_params, n_multiplications, name = conv_layer(x, f)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# max pooling\\n\",\n    \"x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# relu layer\\n\",\n    \"x, n_params, n_multiplications, name = relu_layer(x)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# flatten\\n\",\n    \"x, n_params, n_multiplications, name =  flatten_layer(x)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# fully connected\\n\",\n    \"weights = np.random.randint(low=-10, high=+10, size=(1000, x.shape[0])) \\n\",\n    \"biases = np.random.randint(low=-10, high=+10, size=(1000)) \\n\",\n    \"x, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# relu layer\\n\",\n    \"x, n_params, n_multiplications, name = relu_layer(x)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"# fully connected\\n\",\n    \"weights = np.random.randint(low=-10, high=+10, size=(5, x.shape[0])) \\n\",\n    \"biases = np.random.randint(low=-10, high=+10, size=(5)) \\n\",\n    \"x, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"assert(np.isclose(x, [ -9404869, -11033050, -34374361, -20396580,  70483360.]).all())\\n\",\n    \"\\n\",\n    \"# normalization\\n\",\n    \"x, n_params, n_multiplications, name = normalize(x)\\n\",\n    \"print(p.format(name, str(x.shape), n_params, n_multiplications))\\n\",\n    \"\\n\",\n    \"print(\\\"\\\\nfinal output:\\\", x)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"43c065d3-e68b-4a63-9e7e-237dbf704819\",\n   \"metadata\": {},\n   \"source\": [\n    \"# JSON example\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d97c695a-f706-401f-b85c-b46396a8c42f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\\n\",\n    \"\\n\",\n    \"# Encoder\\n\",\n    \"from json import JSONEncoder\\n\",\n    \"\\n\",\n    \"class Encoder(JSONEncoder):\\n\",\n    \"    def default(self, obj):\\n\",\n    \"        if isinstance(obj, np.ndarray):\\n\",\n    \"            return obj.tolist()\\n\",\n    \"        return JSONEncoder.default(self, obj)\\n\",\n    \"\\n\",\n    \"np.random.seed(12345)\\n\",\n    \"\\n\",\n    \"shape = (3,3,3)\\n\",\n    \"x = np.random.randint(low=-5, high=5, size=shape)\\n\",\n    \"\\n\",\n    \"x = x.flatten()\\n\",\n    \"\\n\",\n    \"# Serialization\\n\",\n    \"data = {\\n\",\n    \"    \\\"v\\\": 1,\\n\",\n    \"    \\\"dim\\\": shape,\\n\",\n    \"    \\\"data\\\": x\\n\",\n    \"    }\\n\",\n    \"\\n\",\n    \"json_data = json.dumps(data, cls=Encoder)\\n\",\n    \"\\n\",\n    \"with open(\\\"../src/json/test.json\\\", \\\"w\\\") as f:\\n\",\n    \"    f.write(json_data)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"e9f4e31a\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Miscellaneous\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a619bbbb-fad3-46ae-83b4-b74398cb953b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"8388608\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"5a1787ed-b448-40e2-96e7-7d597a4660e2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"4897963 / 8388608\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"33087999-ac7f-4ebd-b290-8dbbe3d0c51b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"np.log(262144)/np.log(2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ae322e92-7fcb-4270-9025-392773fc6da4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"4896000 * 3 / (14688 * 1000)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3078557e-adc4-4385-be93-567aa7d93e2d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"np.log(14688 * 800 / 3) / np.log(2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8316d646-b622-47b1-a58c-2ceb5de41c74\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"14688 * 400\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8abe8302-5958-427f-9453-7e2c4ff2cdc9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"14688 * 1600\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"70387136-104a-4a18-9f20-72847ecee8a0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"234076 * 100\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"93298188-6ed4-4e9e-b3cc-20f9778e38bc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"\\n\",\n    \"output = [-6276474000, 8343393300, 8266027500, -7525360600, 7814137000]\\n\",\n    \"norm = np.linalg.norm(output)\\n\",\n    \"norm\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d1b09558\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import math\\n\",\n    \"math.sqrt(6276474000**2 + 8343393300**2 + 8266027500**2 + 7525360600**2 + 7814137000**2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c9c85ea1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"output/norm\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3.9.13 64-bit\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.6\"\n  },\n  \"vscode\": {\n   \"interpreter\": {\n    \"hash\": \"b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e\"\n   }\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "ref_cnn/vanilla_cnn.py",
        "content": "import numpy as np\n\ndef conv_layer(input, f):\n    \"\"\"\n    Evaluate the output of a convolutional layer using the filter f.\n    input.shape = (h, w, c)\n    f.shape = (c_out, hf, wf, c_in)\n    \"\"\"\n    h, w, c = input.shape\n    c_out, hf, wf, c_in = f.shape\n\n    assert c == c_in, \"Input channels must match!\"\n    assert hf%2 == 1, \"Height of the filter (f.shape[1]) must be an uneven number!\"\n    assert wf%2 == 1, \"Width of the filter (f.shape[2]) must be an uneven number!\"\n\n    dh = hf//2\n    dw = wf//2\n\n    output = np.zeros(shape=(h-2*dh, w-2*dw, c_out))\n\n    for i in range(dh, h-dh):\n        for j in range(dw, w-dw):\n            a = input[i-dh:i+dh+1, j-dw:j+dw+1]\n            for k in range(c_out):\n                b = f[k,:,:,:]\n                output[i-dh, j-dw, k] = (a*b).sum() # a.size multiplication\n    \n    n_params = f.size\n    n_multiplications = a.size * c_out * (w-2*dw) * (h-2*dh)\n    name = f\"conv {'x'.join([str(e) for e in f.shape])}\"\n    \n    return output, n_params, n_multiplications, name\n\n\ndef relu_layer(input):    \n    output = input.copy()\n    output[output<0] = 0\n    \n    n_params = 0\n    n_multiplications = 0\n    \n    return output, n_params, n_multiplications, \"relu\"\n\n\ndef max_pooling_layer(input, s):\n    \"\"\"\n    Apply max pooling layer using a sxs patch.\n    \"\"\"\n    h, w, c = input.shape\n\n    assert h%s == 0, \"Height must be devisable by s!\"\n    assert w%s == 0, \"Width must be devisable by s!\"\n\n    output = np.zeros(shape=(h//s, w//s, c))\n\n    for i in range(0, h, s):\n        for j in range(0, w, s):\n            for k in range(c):\n                a = input[i:i+s, j:j+s, k]\n                output[i//s, j//s, k] = a.max()\n    \n    n_params = 0\n    n_multiplications = 0\n    return output, n_params, n_multiplications, \"max-pool\"\n\n\ndef flatten_layer(input):\n    output = input.flatten()\n    n_params = 0\n    n_multiplications = 0\n    return output, n_params, n_multiplications, \"flatten\"\n\n\ndef fully_connected_layer(input, weights, biases):\n    \"\"\"\n    Evaluate the output of a fully connected layer.\n    input.shape = (output_dim)\n    weights.shape = (output_dim, input_dim)\n    f.shape = (output_dim)\n    \"\"\"\n    assert input.ndim == 1, \"Input must be a flattend array!\"\n    assert weights.shape[1] == input.shape[0], \"Input shapes must match!\"\n    assert weights.shape[0] == biases.shape[0], \"Output shapes must match!\"\n\n    output = np.dot(weights, input) + biases\n    \n    n_params = weights.size + biases.size\n    n_multiplications = weights.size\n    name = f\"conv {'x'.join([str(e) for e in weights.shape])}\"\n    \n    return output, n_params, n_multiplications, name\n\ndef normalize(input):\n    output = input / np.linalg.norm(input)\n    n_params = 0\n    n_multiplications = 1 + input.size\n    return output, n_params, n_multiplications, \"normalize\"\n\n\nif __name__ == \"__main__\":\n    \n    np.random.seed(12345)\n\n    p = \"{:>20} | {:>15} | {:>15} | {:>15} \"\n    print(p.format(\"layer\", \"output shape\", \"#parameters\", \"#ops\"))\n    print(p.format(\"-\"*20, \"-\"*15, \"-\"*15, \"-\"*15))\n\n    # input\n    x = np.random.randint(low=-5, high=5, size=(120,80,3))\n\n    # conv layer\n    f = np.random.randint(low=-10, high=+10, size=(32,5,5,3)) \n    x, n_params, n_multiplications, name = conv_layer(x, f)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # max pooling\n    x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # relu layer\n    x, n_params, n_multiplications, name = relu_layer(x)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # conv layer\n    f = np.random.randint(low=-10, high=+10, size=(32,5,5,32)) \n    x, n_params, n_multiplications, name = conv_layer(x, f)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # max pooling\n    x, n_params, n_multiplications, name =  max_pooling_layer(x, 2)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # relu layer\n    x, n_params, n_multiplications, name = relu_layer(x)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # flatten\n    x, n_params, n_multiplications, name =  flatten_layer(x)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # fully connected\n    weights = np.random.randint(low=-10, high=+10, size=(1000, x.shape[0])) \n    biases = np.random.randint(low=-10, high=+10, size=(1000)) \n    x, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # relu layer\n    x, n_params, n_multiplications, name = relu_layer(x)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    # fully connected\n    weights = np.random.randint(low=-10, high=+10, size=(5, x.shape[0])) \n    biases = np.random.randint(low=-10, high=+10, size=(5)) \n    x, n_params, n_multiplications, name = fully_connected_layer(x, weights, biases)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    assert(np.isclose(x, [ -9404869, -11033050, -34374361, -20396580,  70483360.]).all())\n\n    # normalization\n    x, n_params, n_multiplications, name = normalize(x)\n    print(p.format(name, str(x.shape), n_params, n_multiplications))\n\n    print(\"\\nfinal output:\", x)"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/allocator.rs",
        "content": "use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};\npub use std::alloc::System as StdAlloc;\nuse std::alloc::{GlobalAlloc, Layout};\n\n#[cfg(feature = \"mimalloc\")]\npub use mimalloc::MiMalloc;\n\n#[cfg_attr(feature = \"std\", derive(Debug))]\npub struct Allocator<T: GlobalAlloc> {\n    inner:                 T,\n    pub allocated:         AtomicUsize,\n    pub peak_allocated:    AtomicUsize,\n    pub total_allocated:   AtomicUsize,\n    pub largest_allocated: AtomicUsize,\n    pub num_allocations:   AtomicUsize,\n}\n\n#[cfg(not(feature = \"mimalloc\"))]\n// TODO: Turn this into a generic constructor taking an `inner: T` once\n// #![feature(const_fn_trait_bound)] is stable.\npub const fn new_std() -> Allocator<StdAlloc> {\n    Allocator::new(StdAlloc)\n}\n\n#[cfg(feature = \"mimalloc\")]\npub const fn new_mimalloc() -> Allocator<MiMalloc> {\n    Allocator::new(MiMalloc)\n}\n\nimpl<T: GlobalAlloc> Allocator<T> {\n    pub const fn new(alloc: T) -> Self {\n        Self {\n            inner:             alloc,\n            allocated:         AtomicUsize::new(0),\n            peak_allocated:    AtomicUsize::new(0),\n            total_allocated:   AtomicUsize::new(0),\n            largest_allocated: AtomicUsize::new(0),\n            num_allocations:   AtomicUsize::new(0),\n        }\n    }\n\n    fn count_alloc(&self, size: usize) {\n        // TODO: We are doing a lot of atomic operations here, what is\n        // the performance impact?\n        let allocated = self.allocated.fetch_add(size, Relaxed);\n        self.total_allocated.fetch_add(size, Relaxed);\n        self.num_allocations.fetch_add(1, Relaxed);\n        // HACK: Using `allocated` here again is not completely fool proof\n        self.peak_allocated.fetch_max(allocated, Relaxed);\n        self.largest_allocated.fetch_max(size, Relaxed);\n    }\n\n    fn count_dealloc(&self, size: usize) {\n        self.allocated.fetch_sub(size, Relaxed);\n    }\n}\n\n// GlobalAlloc is an unsafe trait for allocators\n#[allow(unsafe_code)]\nunsafe impl<T: GlobalAlloc> GlobalAlloc for Allocator<T> {\n    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n        self.count_alloc(layout.size());\n        self.inner.alloc(layout)\n    }\n\n    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n        self.count_dealloc(layout.size());\n        self.inner.dealloc(ptr, layout);\n    }\n\n    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {\n        self.count_alloc(layout.size());\n        self.inner.alloc_zeroed(layout)\n    }\n\n    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {\n        let old_size = layout.size();\n        if new_size >= old_size {\n            self.count_alloc(new_size - old_size);\n        } else {\n            self.count_dealloc(old_size - new_size);\n        }\n        self.inner.realloc(ptr, layout, new_size)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/anyhow.rs",
        "content": "use eyre::eyre;\n\npub trait MapAny<T> {\n    fn map_any(self) -> eyre::Result<T>;\n}\n\nimpl<T> MapAny<T> for anyhow::Result<T> {\n    fn map_any(self) -> eyre::Result<T> {\n        self.map_err(|e| eyre!(e.to_string()))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/cli/logging.rs",
        "content": "#![warn(clippy::all, clippy::pedantic, clippy::cargo, clippy::nursery)]\n\nuse core::str::FromStr;\nuse eyre::{bail, Error as EyreError, Result as EyreResult, WrapErr as _};\nuse std::process::id as pid;\nuse structopt::StructOpt;\nuse tracing::{info, Level, Subscriber};\nuse tracing_log::{AsLog as _, LogTracer};\nuse tracing_subscriber::{\n    filter::{LevelFilter, Targets},\n    fmt::{self, time::Uptime},\n    layer::SubscriberExt,\n    Layer, Registry,\n};\n\n#[derive(Debug, PartialEq)]\nenum LogFormat {\n    Compact,\n    Pretty,\n    Json,\n}\n\nimpl LogFormat {\n    fn to_layer<S>(&self) -> impl Layer<S>\n    where\n        S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a> + Send + Sync,\n    {\n        let layer = fmt::Layer::new().with_writer(std::io::stderr);\n        match self {\n            LogFormat::Compact => {\n                Box::new(layer.event_format(fmt::format().with_timer(Uptime::default()).compact()))\n                    as Box<dyn Layer<S> + Send + Sync>\n            }\n            LogFormat::Pretty => Box::new(layer.event_format(fmt::format().pretty())),\n            LogFormat::Json => Box::new(layer.event_format(fmt::format().json())),\n        }\n    }\n}\n\nimpl FromStr for LogFormat {\n    type Err = EyreError;\n\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        Ok(match s {\n            \"compact\" => Self::Compact,\n            \"pretty\" => Self::Pretty,\n            \"json\" => Self::Json,\n            _ => bail!(\"Invalid log format: {}\", s),\n        })\n    }\n}\n\n#[derive(Debug, PartialEq, StructOpt)]\npub struct Options {\n    /// Verbose mode (-v, -vv, -vvv, etc.)\n    #[structopt(short, long, parse(from_occurrences))]\n    verbose: usize,\n\n    /// Apply an env_filter compatible log filter\n    #[structopt(long, env, default_value)]\n    log_filter: String,\n\n    /// Log format, one of 'compact', 'pretty' or 'json'\n    #[structopt(long, env, default_value = \"compact\")]\n    log_format: LogFormat,\n}\n\nimpl Options {\n    #[allow(dead_code)]\n    pub fn init(&self) -> EyreResult<()> {\n        // Log filtering is a combination of `--log-filter` and `--verbose` arguments.\n        let verbosity = {\n            let (all, app) = match self.verbose {\n                0 => (Level::INFO, Level::INFO),\n                1 => (Level::INFO, Level::DEBUG),\n                2 => (Level::INFO, Level::TRACE),\n                3 => (Level::DEBUG, Level::TRACE),\n                _ => (Level::TRACE, Level::TRACE),\n            };\n            Targets::new()\n                .with_default(all)\n                .with_target(\"lib\", app)\n                .with_target(env!(\"CARGO_CRATE_NAME\"), app)\n        };\n        let log_filter = if self.log_filter.is_empty() {\n            Targets::new()\n        } else {\n            self.log_filter\n                .parse()\n                .wrap_err(\"Error parsing log-filter\")?\n        };\n        // FIXME: The log-filter can not overwrite the global log level.\n        let targets = verbosity.with_targets(log_filter);\n\n        // Route events to stderr\n        let subscriber = Registry::default().with(self.log_format.to_layer().with_filter(targets));\n        tracing::subscriber::set_global_default(subscriber)?;\n\n        // Enable `log` crate compatibility with max level hint\n        LogTracer::builder()\n            .with_max_level(LevelFilter::current().as_log())\n            .init()?;\n\n        // Log version information\n        info!(\n            host = env!(\"TARGET\"),\n            pid = pid(),\n            main = &crate::main as *const _ as usize,\n            commit = &env!(\"COMMIT_SHA\")[..8],\n            \"{name} {version}\",\n            name = env!(\"CARGO_CRATE_NAME\"),\n            version = env!(\"CARGO_PKG_VERSION\"),\n        );\n\n        Ok(())\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n\n    #[test]\n    fn test_parse_args() {\n        let cmd = \"arg0 -v --log-filter foo -vvv\";\n        let options = Options::from_iter_safe(cmd.split(' ')).unwrap();\n        assert_eq!(options, Options {\n            verbose:    4,\n            log_filter: \"foo\".to_owned(),\n            log_format: LogFormat::Compact,\n        });\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/cli/main.rs",
        "content": "#![warn(clippy::all, clippy::pedantic, clippy::cargo, clippy::nursery)]\n\nuse neural_zkp as lib;\n\nmod logging;\nmod random;\n\nuse eyre::{Result as EyreResult, WrapErr as _};\nuse structopt::StructOpt;\nuse tokio::runtime::{self, Runtime};\nuse tracing::info;\n\nconst VERSION: &str = concat!(\n    env!(\"CARGO_PKG_VERSION\"),\n    \"\\n\",\n    env!(\"COMMIT_SHA\"),\n    \" \",\n    env!(\"COMMIT_DATE\"),\n    \"\\n\",\n    env!(\"TARGET\"),\n    \" \",\n    env!(\"BUILD_DATE\"),\n    \"\\n\",\n    env!(\"CARGO_PKG_AUTHORS\"),\n    \"\\n\",\n    env!(\"CARGO_PKG_HOMEPAGE\"),\n    \"\\n\",\n    env!(\"CARGO_PKG_DESCRIPTION\"),\n);\n\n#[derive(StructOpt)]\nstruct Options {\n    #[structopt(flatten)]\n    log: logging::Options,\n\n    #[structopt(flatten)]\n    app: lib::Options,\n\n    #[structopt(flatten)]\n    random: random::Options,\n\n    /// Number of compute threads to use (defaults to number of cores)\n    #[structopt(long)]\n    threads: Option<usize>,\n}\n\nfn main() -> EyreResult<()> {\n    // Install error handler\n    color_eyre::install()?;\n\n    // Parse CLI and handle help and version (which will stop the application).\n    let matches = Options::clap().long_version(VERSION).get_matches();\n    let options = Options::from_clap(&matches);\n\n    // Start subsystems\n    options.log.init()?;\n    let rng = options.random.init();\n    init_rayon(options.threads)?;\n    let runtime = init_tokio()?;\n\n    // Run main\n    let main_future = lib::main(rng, options.app);\n    runtime.block_on(main_future)?;\n\n    // Terminate successfully\n    info!(\"Program terminating normally\");\n    Ok(())\n}\n\nfn init_rayon(threads: Option<usize>) -> EyreResult<()> {\n    if let Some(threads) = threads {\n        rayon::ThreadPoolBuilder::new()\n            .num_threads(threads)\n            .build_global()\n            .context(\"Failed to build thread pool.\")?;\n    }\n    info!(\n        \"Using {} compute threads on {} cores\",\n        rayon::current_num_threads(),\n        num_cpus::get()\n    );\n    Ok(())\n}\n\nfn init_tokio() -> EyreResult<Runtime> {\n    runtime::Builder::new_multi_thread()\n        .enable_all()\n        .build()\n        .wrap_err(\"Error creating Tokio runtime\")\n    // TODO: Log num_workers once RuntimeMetrics are stable\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use tracing::{error, warn};\n    use tracing_test::traced_test;\n\n    #[test]\n    #[traced_test]\n    fn test_with_log_output() {\n        error!(\"logged on the error level\");\n        assert!(logs_contain(\"logged on the error level\"));\n    }\n\n    #[tokio::test]\n    #[traced_test]\n    #[allow(clippy::semicolon_if_nothing_returned)] // False positive\n    async fn async_test_with_log() {\n        // Local log\n        info!(\"This is being logged on the info level\");\n\n        // Log from a spawned task (which runs in a separate thread)\n        tokio::spawn(async {\n            warn!(\"This is being logged on the warn level from a spawned task\");\n        })\n        .await\n        .unwrap();\n\n        // Ensure that `logs_contain` works as intended\n        assert!(logs_contain(\"logged on the info level\"));\n        assert!(logs_contain(\"logged on the warn level\"));\n        assert!(!logs_contain(\"logged on the error level\"));\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/cli/random.rs",
        "content": "use rand::{rngs::OsRng, RngCore, SeedableRng};\nuse rand_pcg::Mcg128Xsl64;\nuse structopt::StructOpt;\nuse tracing::info;\n\npub type Generator = Mcg128Xsl64;\n\n#[derive(StructOpt)]\npub struct Options {\n    /// Random seed for deterministic random number generation.\n    /// If not specified a seed is periodically generated from OS entropy.\n    #[structopt(long, parse(try_from_str = parse_hex_u64))]\n    seed: Option<u64>,\n}\n\nimpl Options {\n    #[must_use]\n    pub fn init(self) -> Generator {\n        let rng_seed = self.seed.unwrap_or_else(random_seed);\n        info!(\"Using random seed {rng_seed:16x}\");\n        Mcg128Xsl64::seed_from_u64(rng_seed)\n    }\n}\n\n#[must_use]\nfn random_seed() -> u64 {\n    OsRng::default().next_u64()\n}\n\n#[must_use]\nfn parse_hex_u64(src: &str) -> Result<u64, std::num::ParseIntError> {\n    u64::from_str_radix(src, 16)\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/conv.rs",
        "content": "use ndarray::{s, Array, Array3, Array4, ArrayD, ArrayViewD, Ix3};\nuse serde::Serialize;\n\nuse super::{Layer, LayerJson};\n\n#[derive(Clone, Serialize)]\npub struct Convolution {\n    kernel:      Array4<f32>,\n    name:        String,\n    input_shape: Vec<usize>,\n}\n\nimpl Convolution {\n    #[must_use]\n    pub fn new(kernel: Array4<f32>, input_shape: Vec<usize>) -> Convolution {\n        let (c_out, hf, wf, c_in) = kernel.dim();\n        let name = format!(\"conv {}x{}x{}x{}\", c_out, hf, wf, c_in);\n\n        Convolution {\n            kernel,\n            name,\n            input_shape,\n        }\n    }\n}\n\nimpl Layer for Convolution {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n    \n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        // height, width, channels\n        let input = input.clone().into_dimensionality::<Ix3>().unwrap();\n        let (h, w, c) = input.dim();\n\n        // output channels, kernel height, kernel width, input channels\n        let (c_out, hf, wf, c_in) = self.kernel.dim();\n\n        assert_eq!(c, c_in, \"input channels must match\");\n\n        assert!(hf % 2 == 1, \"height of the kernel must be an odd number\");\n        assert!(wf % 2 == 1, \"width of the kernel must be an odd number\");\n\n        let window_dim = (hf, wf, c_in);\n        let output_shape = (h - hf + 1, w - wf + 1);\n        let mut output = Array3::zeros((output_shape.0, output_shape.1, c_out));\n\n        for i in 0..c_out {\n            let mut output_mut = output.slice_mut(s![.., .., i]);\n            let kernel = self.kernel.slice(s![i, .., .., ..]);\n            let values = input\n                .windows(window_dim)\n                .into_iter()\n                .map(|w| (&w * &kernel).sum());\n            let values = Array::from_iter(values)\n                .into_shape(output_shape)\n                .expect(\"Kernel result dimensions mismatch\");\n            output_mut.assign(&values);\n        }\n        output.into_dyn()\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        self.kernel.len()\n    }\n\n    fn num_muls(&self) -> usize {\n        // output channels, kernel height, kernel width, input channels\n        let (c_out, hf, wf, _) = self.kernel.dim();\n\n        let output_shape = self.output_shape();\n\n        output_shape[0] * output_shape[1] * c_out * hf * wf\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        let input_shape = self.input_shape();\n\n        let h = input_shape[0];\n        let w = input_shape[1];\n        let c = input_shape[2];\n\n        // output channels, kernel height, kernel width, input channels\n        let (c_out, hf, wf, c_in) = self.kernel.dim();\n\n        assert_eq!(c, c_in, \"input channels must match\");\n\n        assert!(hf % 2 == 1, \"height of the kernel must be an odd number\");\n        assert!(wf % 2 == 1, \"width of the kernel must be an odd number\");\n\n        vec![h - hf + 1, w - wf + 1, c_out]\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::Convolution {\n            kernel:      self.kernel.clone().into(),\n            input_shape: self.input_shape(),\n        }\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n\n    #[test]\n    fn test_small() {\n        use ndarray::array;\n        let input = array![\n            [\n                [0.51682377_f32],\n                [-2.3552072],\n                [-0.120499134],\n                [2.3132505],\n                [-3.470844]\n            ],\n            [[-1.1741579], [3.4295654], [-1.2318683], [-1.9749749], [\n                -0.8161392\n            ]],\n            [[4.7562046], [-2.8918338], [2.308525], [2.6111293], [\n                -1.0765815\n            ]],\n            [[-4.1224194], [3.022316], [-4.5339823], [4.2970715], [\n                2.6773367\n            ]],\n            [[-4.289216], [-3.3795083], [-2.651745], [-1.1392272], [\n                3.9378529\n            ]]\n        ];\n        let kernel: Array4<f32> = array![\n            [[1.0336475_f32], [-4.7104144], [-0.24099827]],\n            [[4.626501], [-6.941688], [-2.3483157]],\n            [[6.859131], [-2.4637365], [-3.9499497]]\n        ]\n        .into_shape((1, 3, 3, 1))\n        .unwrap();\n        let expected = array![\n            [[15.940444], [-9.205237], [13.396301]],\n            [[1.7727833], [-10.784569], [-48.952152]],\n            [[-22.043327], [8.725433], [-97.68271]]\n        ];\n\n        let conv = Convolution::new(kernel, vec![1, 5, 5, 1]);\n\n        let result = conv.apply(&input.into_dyn().view());\n\n        let delta = result - &expected;\n        let max_error = delta.into_iter().map(f32::abs).fold(0.0, f32::max);\n        dbg!(max_error);\n        assert!(max_error < 10.0 * f32::EPSILON);\n    }\n\n    #[test]\n    fn conv_test() {\n        use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\n        use rand::rngs::StdRng;\n        // man of culture fixed randomness seed\n        let seed = 694201337;\n        let mut rng = StdRng::seed_from_u64(seed);\n\n        let input = Array3::random_using((120, 80, 3), Uniform::<f32>::new(-5., 5.), &mut rng);\n        let kernel = Array4::random_using((32, 5, 5, 3), Uniform::<f32>::new(-10., 10.), &mut rng);\n\n        let conv = Convolution::new(kernel, vec![120, 80, 3]);\n\n        let result = conv\n            .apply(&input.into_dyn().view())\n            .into_dimensionality::<Ix3>()\n            .unwrap();\n\n        assert_eq!(conv.output_shape(), vec![116, 76, 32]);\n\n        let (dim_x, dim_y, dim_z) = result.dim();\n\n        println!(\n            \"# of parameters: {}\\n\n    output dim: {}x{}x{}\\n\n    # of multiplications: {}\n    {} output:\\n\n    {}\",\n            conv.num_params(),\n            dim_x,\n            dim_y,\n            dim_z,\n            conv.num_muls(),\n            conv.name(),\n            result\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/flatten.rs",
        "content": "use ndarray::{Array1, ArrayD, ArrayViewD};\nuse serde::Serialize;\n\nuse super::{Layer, LayerJson};\n\n#[derive(Clone, Serialize)]\npub struct Flatten {\n    name:        String,\n    input_shape: Vec<usize>,\n}\n\nimpl Flatten {\n    #[must_use]\n    pub fn new(input_shape: Vec<usize>) -> Flatten {\n        Flatten {\n            name: \"flatten\".into(),\n            input_shape,\n        }\n    }\n}\n\nimpl Layer for Flatten {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        Array1::from_iter(input.iter().copied()).into_dyn()\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        0\n    }\n\n    fn num_muls(&self) -> usize {\n        0\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        let mut output_shape = 1;\n\n        for i in self.input_shape() {\n            output_shape *= i;\n        }\n\n        vec![output_shape]\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::Flatten {\n            input_shape: self.input_shape(),\n        }\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use super::*;\n    use ndarray::Array3;\n    use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\n    use rand::rngs::StdRng;\n\n    #[test]\n    fn flatten_test() {\n        let seed = 694201337;\n        let mut rng = StdRng::seed_from_u64(seed);\n\n        let input = Array3::random_using((27, 17, 32), Uniform::<f32>::new(-5.0, 5.0), &mut rng);\n\n        let flat = Flatten::new(vec![27, 17, 32]);\n\n        let output = flat.apply(&input.into_dyn().view());\n\n        let n_multiplications = flat.num_muls();\n\n        let n_params = flat.num_params();\n\n        assert_eq!(output.len(), 14688);\n\n        println!(\n            \"\n        {} \\n\n        # of parameters: {}\\n\n        output dim: {} \\n\n        # of ops: {}\\n\n        output:\\n\n        {}\",\n            flat.name,\n            n_params,\n            output.len(),\n            n_multiplications,\n            output\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/fully_connected.rs",
        "content": "use ndarray::{Array1, Array2, ArrayD, ArrayViewD, Ix1};\nuse serde::Serialize;\n\nuse super::{Layer, LayerJson};\n\n#[derive(Clone, Serialize)]\npub struct FullyConnected {\n    weights: Array2<f32>,\n    biases:  Array1<f32>,\n    name:    String,\n}\n\nimpl FullyConnected {\n    #[must_use]\n    pub fn new(weights: Array2<f32>, biases: Array1<f32>) -> FullyConnected {\n        FullyConnected {\n            weights,\n            biases,\n            name: \"full\".into(),\n        }\n    }\n}\n\nimpl Layer for FullyConnected {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        assert!(input.ndim() == 1, \"Input must be a flattenened array!\");\n        assert!(\n            self.weights.shape()[1] == input.shape()[0],\n            \"Input shapes must match (for the dot product to work)!\"\n        );\n        assert!(\n            self.weights.shape()[0] == self.biases.shape()[0],\n            \"Output shapes must match!\"\n        );\n\n        let output = self\n            .weights\n            .dot(&input.clone().into_dimensionality::<Ix1>().unwrap())\n            + self.biases.clone();\n\n        output.into_dyn()\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        self.weights.len() + self.biases.len()\n    }\n\n    fn num_muls(&self) -> usize {\n        self.weights.len()\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        assert!(\n            self.weights.shape()[0] == self.biases.shape()[0],\n            \"Output shapes must match!\"\n        );\n\n        vec![self.weights.shape()[0]]\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        vec![self.weights.shape()[1]]\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::FullyConnected {\n            weights: self.weights.clone().into(),\n            biases:  self.biases.clone().into(),\n        }\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\n    use rand::rngs::StdRng;\n\n    #[test]\n    fn fully_connected_test() {\n        let seed = 694201337;\n        let mut rng = StdRng::seed_from_u64(seed);\n\n        let input = Array1::random_using(14688, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n        let weights =\n            Array2::random_using((1000, 14688), Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n        let biases = Array1::random_using(1000, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n\n        let fully_connected = FullyConnected::new(weights, biases);\n\n        let output = fully_connected.apply(&input.into_dyn().view());\n\n        let n_params = fully_connected.num_params();\n\n        let n_multiplications = fully_connected.num_muls();\n\n        println!(\n            \"\n        {}\n        # of parameters: {}\n        output dim: {}x1\n        # of ops: {}\n        output:\\n{}\",\n            fully_connected.name,\n            n_params,\n            output.len(),\n            n_multiplications,\n            output\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/maxpool.rs",
        "content": "use ndarray::{s, Array3, ArrayD, ArrayViewD, Ix3};\nuse ndarray_stats::QuantileExt;\nuse serde::Serialize;\n\nuse super::{Layer, LayerJson};\n\n#[derive(Clone, Serialize)]\npub struct MaxPool {\n    kernel_side: usize,\n    name:        String,\n    input_shape: Vec<usize>,\n}\n\nimpl MaxPool {\n    #[must_use]\n    pub fn new(kernel_side: usize, input_shape: Vec<usize>) -> MaxPool {\n        MaxPool {\n            name: \"max-pool\".into(),\n            kernel_side,\n            input_shape,\n        }\n    }\n}\n\nimpl Layer for MaxPool {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        let input = input.clone().into_dimensionality::<Ix3>().unwrap();\n        let (h, w, c) = input.dim();\n\n        assert!(h % self.kernel_side == 0, \"Height must be divisible by s!\");\n        assert!(w % self.kernel_side == 0, \"Width must be divisible by s!\");\n\n        let mut output = Array3::<f32>::zeros((h / self.kernel_side, w / self.kernel_side, c));\n\n        // TODO: turn loops into iterators and parallelize with rayon or\n        // ndarray::parallel\n        // let h_iter = (0..h).into_par_iter().filter(|x| x % s == 0);\n        for i in (0..h).step_by(self.kernel_side) {\n            for j in (0..w).step_by(self.kernel_side) {\n                for k in 0..c {\n                    let a = input.slice(s![i..i + self.kernel_side, j..j + self.kernel_side, k]);\n                    // https://docs.rs/ndarray-stats/latest/ndarray_stats/trait.QuantileExt.html#tymethod.max\n                    output[[i / self.kernel_side, j / self.kernel_side, k]] = *a.max().unwrap();\n                }\n            }\n        }\n\n        output.into_dyn()\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        0\n    }\n\n    fn num_muls(&self) -> usize {\n        let mut muls = 1;\n\n        for i in self.input_shape() {\n            muls *= i;\n        }\n\n        muls\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        let input_shape = self.input_shape();\n\n        let h = input_shape[0];\n        let w = input_shape[1];\n        let c = input_shape[2];\n\n        assert!(h % self.kernel_side == 0, \"Height must be divisible by s!\");\n        assert!(w % self.kernel_side == 0, \"Width must be divisible by s!\");\n\n        vec![w / self.kernel_side, h / self.kernel_side, c]\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::MaxPool {\n            window:      self.kernel_side,\n            input_shape: self.input_shape(),\n        }\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\n    use rand::rngs::StdRng;\n\n    #[test]\n    fn maxpool_test() {\n        let seed = 694201337;\n        let mut rng = StdRng::seed_from_u64(seed);\n\n        let input = Array3::random_using((116, 76, 32), Uniform::<f32>::new(-5.0, 5.0), &mut rng);\n\n        let maxpool = MaxPool::new(2, vec![126, 76, 32]);\n\n        let output = maxpool\n            .apply(&input.into_dyn().view())\n            .into_dimensionality::<Ix3>()\n            .unwrap();\n\n        let n_params = maxpool.num_params();\n\n        let n_multiplications = maxpool.num_muls();\n\n        assert_eq!(output.dim(), (58, 38, 32));\n\n        let (dim_x, dim_y, dim_z) = output.dim();\n\n        println!(\n            \"\n        {} \\n\n        # of parameters: {}\\n\n        output dim: {}x{}x{}\\n\n        # of ops: {}\\n\n        output:\\n\n        {}\",\n            maxpool.name, n_params, dim_x, dim_y, dim_z, n_multiplications, output\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/mod.rs",
        "content": "use std::fmt::{Display, Formatter, Result};\n\nuse erased_serde::serialize_trait_object;\nuse ndarray::{ArcArray, ArrayD, ArrayViewD, Ix1, Ix2, Ix4};\nuse serde::{Deserialize, Serialize};\n\npub mod conv;\npub mod flatten;\npub mod fully_connected;\npub mod maxpool;\npub mod normalize;\npub mod relu;\n\npub trait Layer: erased_serde::Serialize {\n    #[must_use]\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32>;\n\n    fn input_shape(&self) -> Vec<usize>;\n\n    #[must_use]\n    fn name(&self) -> &str;\n\n    #[must_use]\n    fn num_params(&self) -> usize;\n\n    #[must_use]\n    fn num_muls(&self) -> usize;\n\n    fn output_shape(&self) -> Vec<usize>;\n\n    #[must_use]\n    fn to_json(&self) -> LayerJson;\n\n    fn box_clone(&self) -> Box<dyn Layer>;\n}\n\nserialize_trait_object!(Layer);\n\nimpl Display for Box<dyn Layer> {\n    fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n        write!(\n            f,\n            \"{:<20} | {:?}{:<5} | {:<5} | {:<5}\",\n            self.name(),\n            self.output_shape(),\n            \"\",\n            self.num_params(),\n            self.num_muls(),\n        )\n    }\n}\n\nimpl Clone for Box<dyn Layer> {\n    fn clone(&self) -> Self {\n        //    self -> &Box<dyn Layer>\n        //   *self ->  Box<dyn Layer>\n        //  **self ->      dyn Layer\n        // &**self ->     &dyn Layer\n        Layer::box_clone(&**self)\n    }\n}\n\n#[derive(Clone, PartialEq, Deserialize, Serialize)]\n#[serde(rename_all = \"snake_case\")]\n#[serde(tag = \"layer_type\")]\npub enum LayerJson {\n    Convolution {\n        kernel:      ArcArray<f32, Ix4>,\n        input_shape: Vec<usize>,\n    },\n    MaxPool {\n        window:      usize,\n        input_shape: Vec<usize>,\n    },\n    FullyConnected {\n        weights: ArcArray<f32, Ix2>,\n        biases:  ArcArray<f32, Ix1>,\n    },\n    Relu {\n        input_shape: Vec<usize>,\n    },\n    Flatten {\n        input_shape: Vec<usize>,\n    },\n    Normalize {\n        input_shape: Vec<usize>,\n    },\n}\n\n#[derive(Clone, PartialEq, Serialize, Deserialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct NNJson {\n    pub layers: Vec<LayerJson>,\n}\n\nimpl TryFrom<LayerJson> for Box<dyn Layer> {\n    type Error = ();\n\n    fn try_from(value: LayerJson) -> std::result::Result<Self, ()> {\n        Ok(match value {\n            LayerJson::Convolution {\n                kernel,\n                input_shape,\n            } => Box::new(conv::Convolution::new(kernel.to_owned(), input_shape)),\n            LayerJson::MaxPool {\n                window,\n                input_shape,\n            } => Box::new(maxpool::MaxPool::new(window.to_owned(), input_shape)),\n            LayerJson::FullyConnected { weights, biases } => Box::new(\n                fully_connected::FullyConnected::new(weights.to_owned(), biases.to_owned()),\n            ),\n            LayerJson::Flatten { input_shape } => Box::new(flatten::Flatten::new(input_shape)),\n            LayerJson::Relu { input_shape } => Box::new(relu::Relu::new(input_shape)),\n            LayerJson::Normalize { input_shape } => {\n                Box::new(normalize::Normalize::new(input_shape))\n            }\n        })\n    }\n}\n\nimpl FromIterator<LayerJson> for NNJson {\n    fn from_iter<T: IntoIterator<Item = LayerJson>>(iter: T) -> Self {\n        let mut nnvec = vec![];\n\n        for i in iter {\n            nnvec.push(i);\n        }\n\n        Self { layers: nnvec }\n    }\n}\n\nimpl From<NeuralNetwork> for NNJson {\n    fn from(nn: NeuralNetwork) -> Self {\n        nn.layers.into_iter().map(|l| l.to_json()).collect()\n    }\n}\n\nimpl TryFrom<NNJson> for NeuralNetwork {\n    type Error = ();\n\n    fn try_from(value: NNJson) -> std::result::Result<Self, ()> {\n        Ok(Self {\n            layers: value\n                .layers\n                .into_iter()\n                .map(|i| i.try_into().unwrap())\n                .collect(),\n        })\n    }\n}\n\n#[derive(Clone, Serialize)]\npub struct NeuralNetwork {\n    layers: Vec<Box<dyn Layer>>,\n}\n\nimpl NeuralNetwork {\n    pub fn new() -> Self {\n        Self { layers: vec![] }\n    }\n\n    pub fn add_layer(&mut self, layer: Box<dyn Layer>) {\n        self.layers.push(layer);\n    }\n\n    pub fn apply(&self, input: &ArrayViewD<f32>, dim: usize) -> Option<ArrayD<f32>> {\n        if dim == 3 {\n            let mut output = input.view().into_owned();\n\n            for layer in &self.layers {\n                // TODO: add dimensionality sanity checks\n                output = layer.apply(&output.view());\n                println!(\"{}\", layer);\n            }\n            Some(output)\n        } else {\n            None\n        }\n    }\n}\n\nimpl Default for NeuralNetwork {\n    fn default() -> Self {\n        Self::new()\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/normalize.rs",
        "content": "use super::LayerJson;\nuse ndarray::{ArrayD, ArrayViewD};\nuse serde::Serialize;\n\nuse super::Layer;\n\n#[derive(Clone, Serialize)]\npub struct Normalize {\n    name:        String,\n    input_shape: Vec<usize>,\n}\n\nimpl Normalize {\n    #[must_use]\n    pub fn new(input_shape: Vec<usize>) -> Normalize {\n        Normalize {\n            name: \"normalize\".into(),\n            input_shape,\n        }\n    }\n}\n\nimpl Layer for Normalize {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        let input = input.clone().mapv(|x| x as i128);\n        let norm = f32::sqrt(input.mapv(|x| x.pow(2)).sum() as f32);\n        input.mapv(|x| x as f32 / norm).into_dyn()\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        0\n    }\n\n    fn num_muls(&self) -> usize {\n        let mut muls = 1;\n\n        for i in self.input_shape() {\n            muls *= i;\n        }\n\n        1 + muls\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::Normalize {\n            input_shape: self.input_shape(),\n        }\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use super::*;\n    use ndarray::{arr1, array};\n\n    #[test]\n    fn normalize_test() {\n        let input = arr1(&[\n            -6276474000.,\n            8343393300.,\n            8266027500.,\n            -7525360600.,\n            7814137000.,\n        ]);\n\n        let normalize = Normalize::new(vec![5]);\n\n        let output = normalize.apply(&input.into_dyn().view());\n\n        let expected = array![-0.36541474, 0.4857503, 0.48124605, -0.43812463, 0.4549371];\n\n        let delta = &output - &expected;\n\n        let max_error = delta.into_iter().map(f32::abs).fold(0.0, f32::max);\n\n        assert!(max_error < 10.0 * f32::EPSILON);\n\n        println!(\"{}\", output);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/layers/relu.rs",
        "content": "#![warn(clippy::all, clippy::pedantic, clippy::cargo, clippy::nursery)]\nuse ndarray::{ArrayD, ArrayViewD};\nuse serde::Serialize;\n\nuse super::{Layer, LayerJson};\n\n#[derive(Clone, Serialize)]\npub struct Relu {\n    name:        String,\n    input_shape: Vec<usize>,\n}\n\nimpl Relu {\n    #[must_use]\n    pub fn new(input_shape: Vec<usize>) -> Self {\n        Self {\n            name: \"relu\".into(),\n            input_shape,\n        }\n    }\n}\n\nimpl Layer for Relu {\n    fn box_clone(&self) -> Box<dyn Layer> {\n        Box::new(self.clone())\n    }\n    fn apply(&self, input: &ArrayViewD<f32>) -> ArrayD<f32> {\n        input.mapv(|x| f32::max(0.0, x))\n    }\n\n    fn name(&self) -> &str {\n        &self.name\n    }\n\n    fn num_params(&self) -> usize {\n        let mut params = 1;\n\n        for i in self.input_shape() {\n            params *= i;\n        }\n\n        params\n    }\n\n    fn num_muls(&self) -> usize {\n        0\n    }\n\n    fn output_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn input_shape(&self) -> Vec<usize> {\n        self.input_shape.clone()\n    }\n\n    fn to_json(&self) -> LayerJson {\n        LayerJson::Relu {\n            input_shape: self.input_shape(),\n        }\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use ndarray::{arr1, arr3, Ix1, Ix3};\n\n    // Array3 ReLU\n    #[test]\n    fn relu_test3() {\n        let input = arr3(&[[[1.2, -4.3], [-2.1, 4.3]], [[5.2, 6.1], [7.6, -1.8]], [\n            [9.3, 0.0],\n            [1.2, 3.4],\n        ]]);\n\n        let relu = Relu::new(vec![3, 2, 2]);\n\n        let output = relu.apply(&input.into_dyn().view());\n\n        let n_params = relu.num_params();\n\n        let n_multiplications = relu.num_muls();\n\n        assert_eq!(\n            output,\n            arr3(&[[[1.2, 0.0], [0.0, 4.3]], [[5.2, 6.1], [7.6, 0.0]], [\n                [9.3, 0.0],\n                [1.2, 3.4],\n            ]])\n            .into_dyn()\n        );\n\n        let size: (usize, usize, usize) = (3, 2, 2);\n\n        assert_eq!(\n            &output.clone().into_dimensionality::<Ix3>().unwrap().dim(),\n            &size\n        );\n\n        println!(\n            \"\n        {} \n        # of parameters: {}\n        output dim: {}x1\n        # of ops: {}\n        output:\\n{}\",\n            relu.name(),\n            n_params,\n            n_params,\n            n_multiplications,\n            output\n        );\n    }\n\n    // Array1 ReLU\n    #[test]\n    fn relu_test1() {\n        let input = arr1(&[-4., -3.4, 6., 7., 1., -3.]).into_dyn();\n\n        let relu = Relu::new(vec![6]);\n\n        let output = relu.apply(&input.into_dyn().view());\n\n        let n_params = relu.num_params();\n\n        let n_multiplications = relu.num_muls();\n\n        assert_eq!(output, arr1(&[0., 0., 6., 7., 1., 0.]).into_dyn());\n\n        assert_eq!(\n            output.clone().into_dimensionality::<Ix1>().unwrap().len(),\n            6\n        );\n\n        println!(\n            \"\n        {} \n        # of parameters: {}\n        output dim: {}x1\n        # of ops: {}\n        output:\\n{}\",\n            relu.name(),\n            n_params,\n            n_params,\n            n_multiplications,\n            output\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/lib.rs",
        "content": "// #![warn(clippy::all, clippy::pedantic, clippy::cargo, clippy::nursery)]\n// Stabilized soon: https://github.com/rust-lang/rust/pull/93827\n\n// Disable globally while still iterating on design\n#![allow(clippy::missing_panics_doc)]\n// TODO\n#![allow(unreadable_literal)]\n// benchmarking\n#![feature(test)]\n\nmod allocator;\nmod anyhow;\n\npub mod layers;\npub mod nn;\npub mod serialize;\n\nuse self::{allocator::Allocator, anyhow::MapAny as _};\nuse bytesize::ByteSize;\nuse eyre::{eyre, Result as EyreResult};\nuse log::Level;\nuse plonky2::{\n    field::types::Field,\n    iop::{\n        target::Target,\n        witness::{PartialWitness, Witness},\n    },\n    plonk::{\n        circuit_builder::CircuitBuilder,\n        circuit_data::{CircuitConfig, CircuitData},\n        config::{GenericConfig, KeccakGoldilocksConfig, PoseidonGoldilocksConfig},\n        proof::{CompressedProofWithPublicInputs, ProofWithPublicInputs},\n    },\n};\nuse rand::Rng as _;\nuse std::{iter::once, sync::atomic::Ordering, time::Instant};\nuse structopt::StructOpt;\nuse tracing::{info, trace};\n\ntype Rng = rand_pcg::Mcg128Xsl64;\n\n#[cfg(not(feature = \"mimalloc\"))]\n#[global_allocator]\npub static ALLOCATOR: Allocator<allocator::StdAlloc> = allocator::new_std();\n\n#[cfg(feature = \"mimalloc\")]\n#[global_allocator]\npub static ALLOCATOR: Allocator<allocator::MiMalloc> = allocator::new_mimalloc();\n\n#[derive(Clone, Debug, PartialEq, StructOpt)]\npub struct Options {\n    /// Bench over increasing output sizes\n    #[structopt(long)]\n    pub bench: bool,\n\n    /// The size of the input layer\n    #[structopt(long, default_value = \"1000\")]\n    pub input_size: usize,\n\n    /// The size of the output layer\n    #[structopt(long, default_value = \"1000\")]\n    pub output_size: usize,\n\n    /// Coefficient bits\n    #[structopt(long, default_value = \"16\")]\n    pub coefficient_bits: usize,\n\n    /// Number of wire columns\n    #[structopt(long, default_value = \"400\")]\n    pub num_wires: usize,\n\n    /// Number of routed wire columns\n    #[structopt(long, default_value = \"400\")]\n    pub num_routed_wires: usize,\n\n    /// Number of constants per constant gate\n    #[structopt(long, default_value = \"90\")]\n    pub constant_gate_size: usize,\n}\n\nconst D: usize = 2;\ntype C = PoseidonGoldilocksConfig;\n// type C = KeccakGoldilocksConfig;\ntype F = <C as GenericConfig<D>>::F;\ntype Builder = CircuitBuilder<F, D>;\ntype Proof = ProofWithPublicInputs<F, C, D>;\n\n// https://arxiv.org/pdf/1509.09308.pdf\n// https://en.wikipedia.org/wiki/Freivalds%27_algorithm ?\n\nfn to_field(value: i32) -> F {\n    if value >= 0 {\n        F::from_canonical_u32(value as u32)\n    } else {\n        -F::from_canonical_u32(-value as u32)\n    }\n}\n\n/// Compute the inner product of `coefficients` and `input`\nfn dot(builder: &mut Builder, coefficients: &[i32], input: &[Target]) -> Target {\n    // TODO: Compare this accumulator approach against a batch sum.\n    assert_eq!(coefficients.len(), input.len());\n    // builder.push_context(Level::Info, \"dot\");\n    let mut sum = builder.zero();\n    // iterates over array coefficients and input and performs the dot product:\n    // sum = co[0] * in[0] + co[1] * in[1] .... + co[len(co)] * in[len(in)] <=>\n    // len(co) = len (in) each coefficient needs to be a Goldilocks field\n    // element (modular arithmetic inside a field element) CircuitBuilder.\n    // mul_const_add()\n    // sum = co[0] * in[0] + co[1] * in[1] .... + co[len(co)] * in[len(in)] <=>\n    // len(co) = len (in) each coefficient needs to be a Goldilocks field\n    // element (modular arithmetic inside a field element) CircuitBuilder.\n    // mul_const_add()\n    for (&coefficient, &input) in coefficients.iter().zip(input) {\n        let coefficient = to_field(coefficient);\n        sum = builder.mul_const_add(coefficient, input, sum);\n    }\n    // builder.pop_context();\n    sum\n}\n\n// len(co) = k * len(in); k is a constant that belongs to N; k > 1 (ref 1)\nfn full(builder: &mut Builder, coefficients: &[i32], input: &[Target]) -> Vec<Target> {\n    let input_size = input.len();\n    // len(output_size) = k\n    let output_size = coefficients.len() / input_size;\n    // enforces (ref 1)\n    assert_eq!(coefficients.len(), input_size * output_size);\n\n    // TODO: read docs CircuitBuilder.push_context(), Level\n    builder.push_context(Level::Info, \"full\");\n\n    // output is a vector that contains dot products of coefficients and inputs,\n    // len(output) = k\n    // output is a vector that contains dot products of coefficients and inputs,\n    // len(output) = k\n    let mut output = Vec::with_capacity(output_size);\n    // &[i32].chunks_exact() creates an iterator over k arrays of len(input)\n    for coefficients in coefficients.chunks_exact(input_size) {\n        // builder enforces Goldilock fields modular arithmetic\n        output.push(dot(builder, coefficients, input));\n    }\n    builder.pop_context();\n    output\n}\n\n// Plonky2 circuit\nstruct Circuit {\n    inputs:  Vec<Target>,\n    outputs: Vec<Target>,\n    data:    CircuitData<F, C, D>,\n}\n\nimpl Circuit {\n    // options are inputs that can be changed from cli and have default values\n    fn build(options: &Options, coefficients: &[i32]) -> Circuit {\n        assert_eq!(coefficients.len(), options.input_size * options.output_size);\n        info!(\n            \"Building circuit for for {}x{} matrix-vector multiplication\",\n            options.input_size, options.output_size\n        );\n\n        let config = CircuitConfig {\n            num_wires: options.num_wires,\n            num_routed_wires: options.num_routed_wires,\n            // constant_gate_size: options.constant_gate_size,\n            ..CircuitConfig::default()\n        };\n        let mut builder = CircuitBuilder::<F, D>::new(config);\n\n        // Inputs\n        builder.push_context(Level::Info, \"Inputs\");\n        // TODO: Look at CircuitBuilder.add_virtual_targets()\n        let inputs = builder.add_virtual_targets(options.input_size);\n        inputs\n            .iter()\n            .for_each(|target| builder.register_public_input(*target));\n        builder.pop_context();\n\n        // Circuit\n        let outputs = full(&mut builder, &coefficients, &inputs);\n        outputs\n            .iter()\n            .for_each(|target| builder.register_public_input(*target));\n\n        // Log circuit size\n        builder.print_gate_counts(0);\n        let data = builder.build::<C>();\n\n        Self {\n            inputs,\n            outputs,\n            data,\n        }\n    }\n\n    fn prove(&self, input: &[i32]) -> EyreResult<Proof> {\n        info!(\"Proving {} size input\", input.len());\n        // TODO: Look into plonky2::iop::PartialWitness\n        // What's the difference between PW and W\n        let mut pw = PartialWitness::new();\n        for (&target, &value) in self.inputs.iter().zip(input) {\n            pw.set_target(target, to_field(value));\n        }\n        let proof = self.data.prove(pw).map_any()?;\n        // let compressed = proof.clone().compress(&self.data.common).map_any()?;\n        let proof_size = ByteSize(proof.to_bytes().map_any()?.len() as u64);\n        info!(\"Proof size: {proof_size}\");\n        Ok(proof)\n    }\n\n    fn verify(&self, proof: &Proof) -> EyreResult<()> {\n        info!(\n            \"Verifying proof with {} public inputs\",\n            proof.public_inputs.len()\n        );\n        // Why proof.clone()\n        self.data.verify(proof.clone()).map_any()\n    }\n}\n\npub async fn main(mut rng: Rng, mut options: Options) -> EyreResult<()> {\n    info!(\n        \"Computing proof for {}x{} matrix-vector multiplication\",\n        options.input_size, options.output_size\n    );\n\n    println!(\n        \"input_size,output_size,build_time_s,proof_time_s,proof_mem_b,proof_size_b,verify_time_s\"\n    );\n    // TODO: What does this line mean?\n    let output_sizes: Box<dyn Iterator<Item = usize>> = if options.bench {\n        Box::new((1..).map(|n| n * 1000))\n    } else {\n        // what is once\n        Box::new(once(options.output_size))\n    };\n\n    for output_size in output_sizes {\n        options.output_size = output_size;\n\n        // Coefficients\n        // what is quantizing?\n        let quantize_coeff = |c: i32| c % (1 << options.coefficient_bits);\n        let coefficients: Vec<i32> = (0..options.input_size * options.output_size)\n            .map(|_| quantize_coeff(rng.gen()))\n            .collect();\n        let now = Instant::now();\n        let circuit = Circuit::build(&options, &coefficients);\n        let circuit_build_time = now.elapsed();\n\n        // Set witness for proof\n        ALLOCATOR.peak_allocated.store(0, Ordering::Release);\n        let input_values = (0..options.input_size as i32)\n            .into_iter()\n            .map(|_| rng.gen())\n            .collect::<Vec<_>>();\n        let now = Instant::now();\n        let proof = circuit.prove(&input_values)?;\n        let proof_mem = ALLOCATOR.peak_allocated.load(Ordering::Acquire);\n        let proof_time = now.elapsed();\n        let proof_size = proof.to_bytes().map_any()?.len() as u64;\n        info!(\"Prover memory usage: {}\", ByteSize(proof_mem as u64));\n\n        // Verifying\n        let now = Instant::now();\n        circuit.verify(&proof)?;\n        let verify_time = now.elapsed();\n\n        println!(\n            \"{},{},{},{},{},{},{}\",\n            options.input_size,\n            options.output_size,\n            circuit_build_time.as_secs_f64(),\n            proof_time.as_secs_f64(),\n            proof_mem,\n            proof_size,\n            verify_time.as_secs_f64()\n        );\n    }\n\n    Ok(())\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use proptest::proptest;\n    use tracing::{error, warn};\n    use tracing_test::traced_test;\n\n    #[allow(clippy::eq_op)]\n    // fn test_with_proptest() {\n    //     proptest!(|(a in 0..5, b in 0..5)| {\n    //         assert_eq!(a + b, b + a);\n    //     });\n    // }\n    #[traced_test]\n    fn test_with_log_output() {\n        error!(\"logged on the error level\");\n        assert!(logs_contain(\"logged on the error level\"));\n    }\n\n    #[tokio::test]\n    #[traced_test]\n    #[allow(clippy::semicolon_if_nothing_returned)] // False positive\n    async fn async_test_with_log() {\n        // Local log\n        info!(\"This is being logged on the info level\");\n\n        // Log from a spawned task (which runs in a separate thread)\n        tokio::spawn(async {\n            warn!(\"This is being logged on the warn level from a spawned task\");\n        })\n        .await\n        .unwrap();\n\n        // Ensure that `logs_contain` works as intended\n        assert!(logs_contain(\"logged on the info level\"));\n        assert!(logs_contain(\"logged on the warn level\"));\n        assert!(!logs_contain(\"logged on the error level\"));\n    }\n}\n\n#[cfg(feature = \"bench\")]\npub mod bench {\n    use criterion::{black_box, BatchSize, Criterion};\n    use proptest::{\n        strategy::{Strategy, ValueTree},\n        test_runner::TestRunner,\n    };\n    use std::time::Duration;\n    use tokio::runtime;\n\n    pub fn group(criterion: &mut Criterion) {\n        bench_example_proptest(criterion);\n        bench_example_async(criterion);\n    }\n\n    /// Constructs an executor for async tests\n    pub(crate) fn runtime() -> runtime::Runtime {\n        runtime::Builder::new_multi_thread()\n            .enable_all()\n            .build()\n            .unwrap()\n    }\n\n    /// Example proptest benchmark\n    /// Uses proptest to randomize the benchmark input\n    fn bench_example_proptest(criterion: &mut Criterion) {\n        let input = (0..5, 0..5);\n        let mut runner = TestRunner::deterministic();\n        // Note: benchmarks need to have proper identifiers as names for\n        // the CI to pick them up correctly.\n        criterion.bench_function(\"example_proptest\", move |bencher| {\n            bencher.iter_batched(\n                || input.new_tree(&mut runner).unwrap().current(),\n                |(a, b)| {\n                    // Benchmark number addition\n                    black_box(a + b)\n                },\n                BatchSize::LargeInput,\n            );\n        });\n    }\n\n    /// Example async benchmark\n    /// See <https://bheisler.github.io/criterion.rs/book/user_guide/benchmarking_async.html>\n    fn bench_example_async(criterion: &mut Criterion) {\n        let duration = Duration::from_micros(1);\n        criterion.bench_function(\"example_async\", move |bencher| {\n            bencher.to_async(runtime()).iter(|| async {\n                tokio::time::sleep(duration).await;\n            });\n        });\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/nn.rs",
        "content": "use crate::layers::{\n    conv::Convolution, flatten::Flatten, fully_connected::FullyConnected, maxpool::MaxPool,\n    normalize::Normalize, relu::Relu, NeuralNetwork,\n};\nuse ndarray::{Array1, Array2, Array4};\nuse ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\nuse rand::rngs::StdRng;\n\n// TODO: add_layer! macro -> neural_net.add_layer(Box::new(layer: Layer))\n// TODO: rnd_Array(shape: Dim = D)\n\npub fn create_neural_net() -> NeuralNetwork {\n    let seed = 694201337;\n    let mut rng = StdRng::seed_from_u64(seed);\n\n    let mut neural_net = NeuralNetwork::new();\n\n    let kernel = Array4::random_using((32, 5, 5, 3), Uniform::<f32>::new(-10., 10.), &mut rng);\n\n    neural_net.add_layer(Box::new(Convolution::new(kernel, vec![120, 80, 3])));\n\n    neural_net.add_layer(Box::new(MaxPool::new(2, vec![116, 76, 32])));\n\n    neural_net.add_layer(Box::new(Relu::new(vec![58, 38, 32])));\n\n    let kernel = Array4::random_using((32, 5, 5, 32), Uniform::<f32>::new(-10., 10.), &mut rng);\n\n    neural_net.add_layer(Box::new(Convolution::new(kernel, vec![58, 38, 32])));\n\n    neural_net.add_layer(Box::new(MaxPool::new(2, vec![54, 34, 32])));\n    neural_net.add_layer(Box::new(Relu::new(vec![27, 17, 32])));\n    neural_net.add_layer(Box::new(Flatten::new(vec![27, 17, 32])));\n    let weights = Array2::random_using((1000, 14688), Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n    let biases = Array1::random_using(1000, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n    neural_net.add_layer(Box::new(FullyConnected::new(weights, biases)));\n    neural_net.add_layer(Box::new(Relu::new(vec![1000])));\n\n    let weights = Array2::random_using((5, 1000), Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n    let biases = Array1::random_using(5, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n\n    neural_net.add_layer(Box::new(FullyConnected::new(weights, biases)));\n    neural_net.add_layer(Box::new(Normalize::new(vec![5])));\n\n    neural_net\n}\n\npub fn log_nn_table() {\n    println!(\n        \"{:<20} | {:<15} | {:<15} | {:<15}\",\n        \"layer\", \"output shape\", \"#parameters\", \"#ops\"\n    );\n    println!(\"{:-<77}\", \"\");\n}\n\n#[cfg(test)]\npub mod tests {\n    extern crate test;\n    use crate::{\n        layers::{\n            conv::Convolution, flatten::Flatten, fully_connected::FullyConnected, maxpool::MaxPool,\n            normalize::Normalize, relu::Relu, NeuralNetwork,\n        },\n        serialize::deserialize_model_json,\n    };\n    use ndarray::{ArcArray, Array1, Array2, Array3, Array4, Ix1, Ix2, Ix3, Ix4};\n    use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt};\n    use rand::rngs::StdRng;\n\n    use std::fs;\n    use test::Bencher;\n\n    use super::log_nn_table;\n\n    #[test]\n    fn neural_net() {\n        // neural net layers:\n        // conv\n        // maxpool\n        // relu\n        // conv\n        // max pool\n        // relu\n        // flatten\n        // fully connected\n        // relu\n        // fully connected\n        // normalization\n\n        let seed = 694201337;\n        let mut rng = StdRng::seed_from_u64(seed);\n\n        log_nn_table();\n\n        let input = Array3::random_using((120, 80, 3), Uniform::<f32>::new(-5., 5.), &mut rng);\n\n        let mut neural_net = NeuralNetwork::new();\n\n        let kernel = Array4::random_using((32, 5, 5, 3), Uniform::<f32>::new(-10., 10.), &mut rng);\n\n        neural_net.add_layer(Box::new(Convolution::new(kernel, vec![120, 80, 3])));\n\n        neural_net.add_layer(Box::new(MaxPool::new(2, vec![116, 76, 32])));\n\n        neural_net.add_layer(Box::new(Relu::new(vec![58, 38, 32])));\n\n        let kernel = Array4::random_using((32, 5, 5, 32), Uniform::<f32>::new(-10., 10.), &mut rng);\n\n        neural_net.add_layer(Box::new(Convolution::new(kernel, vec![58, 38, 32])));\n\n        neural_net.add_layer(Box::new(MaxPool::new(2, vec![54, 34, 32])));\n        neural_net.add_layer(Box::new(Relu::new(vec![27, 17, 32])));\n        neural_net.add_layer(Box::new(Flatten::new(vec![27, 17, 32])));\n        let weights =\n            Array2::random_using((1000, 14688), Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n        let biases = Array1::random_using(1000, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n        neural_net.add_layer(Box::new(FullyConnected::new(weights, biases)));\n        neural_net.add_layer(Box::new(Relu::new(vec![1000])));\n\n        let weights = Array2::random_using((5, 1000), Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n        let biases = Array1::random_using(5, Uniform::<f32>::new(-10.0, 10.0), &mut rng);\n\n        neural_net.add_layer(Box::new(FullyConnected::new(weights, biases)));\n        neural_net.add_layer(Box::new(Normalize::new(vec![5])));\n\n        let output = neural_net.apply(&input.into_dyn().view(), 3);\n\n        if output.is_some() {\n            println!(\"final output (normalized):\\n{}\", output.unwrap());\n        } else {\n            print!(\"Unsupported dimensionality of input Array\");\n        }\n    }\n\n    #[bench]\n    fn bench_neural_net(b: &mut Bencher) {\n        log_nn_table();\n\n        let input_json =\n            fs::read_to_string(\"./src/json/initial.json\").expect(\"Unable to read file\");\n        let input = serde_json::from_str::<ArcArray<f32, Ix3>>(&input_json).unwrap();\n\n        let neural_net = deserialize_model_json(\"./src/json/model.json\");\n\n        // Python Vanilla CNN implementation, run time: 0.8297840171150046 (average over\n        // 1000 runs on M1 Max Macbook Pro)\n        b.iter(|| neural_net.apply(&input.clone().into_dyn().view(), 3));\n        // cargo bench - 0.151693329s +- 0.002147193s - (about 5.5x faster)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/worldcoin/proto-neural-zkp",
        "file_path": "src/serialize.rs",
        "content": "use std::{fs, io::Write};\n\nuse crate::layers::{NNJson, NeuralNetwork};\n\n/// path: &str -> e.g. deserialize_model_json(\"./src/json/model.json\")\n/// Deserializes a model from JSON from the NNJson Struct in mod.rs\npub fn deserialize_model_json(path: &str) -> NeuralNetwork {\n    let model_data = fs::read_to_string(path).expect(\"Unable to read file\");\n    let model_json = serde_json::from_str::<NNJson>(&model_data).unwrap();\n\n    let neural_net: NeuralNetwork = model_json.try_into().unwrap();\n\n    neural_net\n}\n\n/// path: &str - path for the creation of a json file containing serialized\n/// model representation\n/// model: NeuralNetwork - model to be serialized (dummy\n/// creation with nn::create_neural_net())\n/// example usage:\n/// serialize_model_json(\"./src/json/nn.json\", create_neural_net())\npub fn serialize_model_json(path: &str, model: NeuralNetwork) {\n    let mut file = fs::File::create(path).expect(\"Error encountered while creating file!\");\n\n    let model_json: NNJson = model.into();\n\n    file.write_all(serde_json::to_string(&model_json).unwrap().as_bytes())\n        .expect(\"Unable to write data\");\n}\n\n#[cfg(test)]\npub mod tests {\n    use ndarray::{ArcArray, Ix3};\n    use serde_json;\n    use std::fs;\n\n    extern crate test;\n    use test::Bencher;\n\n    use super::*;\n    use crate::nn::{create_neural_net, log_nn_table};\n\n    #[test]\n    fn serialize_nn_json() {\n        serialize_model_json(\"./src/json/nn.json\", create_neural_net())\n    }\n\n    #[test]\n    fn deserialize_nn_json() {\n        // initial log\n        log_nn_table();\n\n        // deserialize input JSON file into an ArcArray\n        let input_json =\n            fs::read_to_string(\"./src/json/initial.json\").expect(\"Unable to read file\");\n        let input = serde_json::from_str::<ArcArray<f32, Ix3>>(&input_json).unwrap();\n\n        // deserialize model\n        let neural_net = deserialize_model_json(\"./src/json/model.json\");\n\n        // run inference\n        let output = neural_net.apply(&input.into_dyn().view(), 3);\n\n        if output.is_some() {\n            println!(\"final output (normalized):\\n{}\", output.unwrap());\n        } else {\n            print!(\"Unsupported dimensionality of input Array\");\n        }\n    }\n\n    #[test]\n    fn serde_full_circle() {\n        serialize_model_json(\"./src/json/nn.json\", create_neural_net());\n\n        // initial log\n        log_nn_table();\n\n        // deserialize input JSON file into an ArcArray\n        let input_json =\n            fs::read_to_string(\"./src/json/initial.json\").expect(\"Unable to read file\");\n        let input = serde_json::from_str::<ArcArray<f32, Ix3>>(&input_json).unwrap();\n\n        // deserialize model\n        let neural_net = deserialize_model_json(\"./src/json/nn.json\");\n\n        // run inference\n        let output = neural_net.apply(&input.into_dyn().view(), 3);\n\n        if output.is_some() {\n            println!(\"final output (normalized):\\n{}\", output.unwrap());\n        } else {\n            print!(\"Unsupported dimensionality of input Array\");\n        }\n    }\n\n    #[bench]\n    fn bench_deserialize_neural_net(b: &mut Bencher) {\n        b.iter(deserialize_nn_json);\n        // full deserialization benchmark times (M1 Max Macbook Pro)\n        // cargo bench - 565,564,850 ns/iter (+/- 61,387,641)\n    }\n\n    #[bench]\n    fn bench_serialize_neural_net(b: &mut Bencher) {\n        b.iter(serialize_nn_json);\n        // full serialization benchmark times (M1 Max Macbook Pro)\n        // cargo bench - 579,057,637 ns/iter (+/- 20,202,535)\n    }\n}\n"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "keras2circom/circom.py",
        "content": "# Ref: https://github.com/zk-ml/uchikoma/blob/main/python/uchikoma/circom.py\nfrom __future__ import annotations\n\nimport typing\n\nimport os\nfrom os import path\nimport json\nfrom dataclasses import dataclass\n\nimport re\nimport numpy as np\n\nclass SafeDict(dict):\n    def __missing__(self, key):\n        return '{' + key + '}'\n\n# template string for circom\ncircom_template_string = '''pragma circom 2.0.0;\n\n{include}\ntemplate Model() {brace_left}\n{signal}\n{component}\n{main}\n{brace_right}\n\ncomponent main = Model();\n'''\n\ntemplates: typing.Dict[str, Template] = {\n\n}\n\ndef parse_shape(shape: typing.List[int]) -> str:\n    '''parse shape to integers enclosed by []'''\n    shape_str = ''\n    for dim in shape:\n        shape_str += '[{}]'.format(dim)\n    return shape_str\n    \ndef parse_index(shape: typing.List[int]) -> str:\n    '''parse shape to indices enclosed by []'''\n    index_str = ''\n    for i in range(len(shape)):\n        index_str += '[i{}]'.format(i)\n    return index_str\n\n@dataclass\nclass Template:\n    op_name: str\n    fpath: str\n\n    args: typing.Dict[str]\n\n    input_names: typing.List[str]   = None\n    input_dims: typing.List[int]    = None\n    output_names: typing.List[str]  = None\n    output_dims: typing.List[int]   = None\n\n    def __str__(self) -> str:\n        args_str = ', '.join(self.args)\n        args_str = '(' + args_str + ')'\n        return '{:>20}{:30} {}{}{}{} \\t<-- {}'.format(\n            self.op_name, args_str,\n            self.input_names, self.input_dims,\n            self.output_names, self.output_dims,\n            self.fpath)\n\ndef file_parse(fpath):\n    '''parse circom file and register templates'''\n    with open(fpath, 'r') as f:\n        lines = f.read().split('\\n')\n\n    lines = [l for l in lines if not l.strip().startswith('//')]\n    lines = ' '.join(lines)\n\n    lines = re.sub('/\\*.*?\\*/', 'IGN', lines)\n\n    funcs = re.findall('template (\\w+) ?\\((.*?)\\) ?\\{(.*?)\\}', lines)\n    for func in funcs:\n        op_name = func[0].strip()\n        args = func[1].split(',')\n        main = func[2].strip()\n        assert op_name not in templates, \\\n            'duplicated template: {} in {} vs. {}'.format(\n                    op_name, templates[op_name].fpath, fpath)\n\n        signals = re.findall('signal (\\w+) (\\w+)(.*?);', main)\n        infos = [[] for i in range(4)]\n        for sig in signals:\n            sig_types = ['input', 'output']\n            assert sig[0] in sig_types, sig[1] + ' | ' + main\n            idx = sig_types.index(sig[0])\n            infos[idx*2+0].append(sig[1])\n\n            sig_dim = sig[2].count('[')\n            infos[idx*2+1].append(sig_dim)\n        templates[op_name] = Template(\n                op_name, fpath,\n                [a.strip() for a in args],\n                *infos)\n\n\ndef dir_parse(dir_path, skips=[]):\n    '''parse circom files in a directory'''\n    names = os.listdir(dir_path)\n    for name in names:\n        if name in skips:\n            continue\n\n        fpath = path.join(dir_path, name)\n        if os.path.isdir(fpath):\n            dir_parse(fpath)\n        elif os.path.isfile(fpath):\n            if fpath.endswith('.circom'):\n                file_parse(fpath)\n\n@dataclass\nclass Signal:\n    name: str\n    shape: typing.List[int]\n    value: typing.Any = None\n\n    def inject_signal(self, comp_name: str) -> str:\n        '''inject signal into the beginning of the circuit'''\n        if self.value is not None or self.name == 'out' or self.name == 'remainder':\n            return 'signal input {}_{}{};\\n'.format(\n                    comp_name, self.name, parse_shape(self.shape))\n        return ''\n    \n    def inject_main(self, comp_name: str, prev_comp_name: str = None, prev_signal: Signal = None) -> str:\n        '''inject signal into main'''\n        inject_str = ''\n        if self.value is not None or self.name == 'out' or self.name == 'remainder':\n            if comp_name.endswith('softmax') and self.name == 'out':\n                inject_str += '{}.out <== {}_out[0];\\n'.format(\n                            comp_name, comp_name)\n                return inject_str\n            for i in range(len(self.shape)):\n                inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, self.shape[i], i)\n            if 'activation' in comp_name or 're_lu' in comp_name:\n                inject_str += '{}{}{}.{} <== {}_{}{};\\n'.format(' '*(i+1)*4,\n                            comp_name, parse_index(self.shape), self.name,\n                            comp_name, self.name, parse_index(self.shape))\n            else:\n                inject_str += '{}{}.{}{} <== {}_{}{};\\n'.format(' '*(i+1)*4,\n                            comp_name, self.name, parse_index(self.shape),\n                            comp_name, self.name, parse_index(self.shape))\n            inject_str += '}'*len(self.shape)+'\\n'\n            return inject_str\n        \n        if self.shape != prev_signal.shape:\n            raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))\n            \n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, self.shape[i], i)\n        \n        if 'activation' in comp_name or 're_lu' in comp_name:\n            inject_str += '{}{}{}.{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        comp_name, parse_index(self.shape), self.name,\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        elif 'activation' in prev_comp_name or 're_lu' in prev_comp_name:\n            inject_str += '{}{}.{}{} <== {}{}.{};\\n'.format(' '*(i+1)*4,\n                        comp_name, self.name, parse_index(self.shape),\n                        prev_comp_name, parse_index(self.shape), prev_signal.name)\n        else:\n            inject_str += '{}{}.{}{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        comp_name, self.name, parse_index(self.shape),\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n    \n    def inject_input_signal(self) -> str:\n        '''inject the circuit input signal'''\n        if self.value is not None:\n            raise ValueError('input signal should not have value')\n        return 'signal input in{};\\n'.format(parse_shape(self.shape))\n    \n    def inject_output_signal(self) -> str:\n        '''inject the circuit output signal'''\n        if self.value is not None:\n            raise ValueError('output signal should not have value')\n        return 'signal output out{};\\n'.format(parse_shape(self.shape)) \n    \n    def inject_input_main(self, comp_name: str) -> str:\n        '''inject the circuit input signal into main'''\n        if self.value is not None:\n            raise ValueError('input signal should not have value')\n        inject_str = ''\n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                        ' '*i*4, i, i, self.shape[i], i)\n        inject_str += '{}{}.{}{} <== in{};\\n'.format(' '*(i+1)*4,\n                    comp_name, self.name, parse_index(self.shape),\n                    parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n    \n    def inject_output_main(self, prev_comp_name: str, prev_signal: Signal) -> str:\n        '''inject the circuit output signal into main'''        \n        if self.value is not None:\n            raise ValueError('output signal should not have value')\n        if self.shape != prev_signal.shape:\n            raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))\n        \n        if 'softmax' in prev_comp_name:\n            return 'out[0] <== {}.out;\\n'.format(prev_comp_name)\n        \n        inject_str = ''\n\n        for i in range(len(self.shape)):\n            inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                        ' '*i*4, i, i, self.shape[i], i)\n        \n        if 're_lu' in prev_comp_name:\n            inject_str += '{}out{} <== {}{}.{};\\n'.format(' '*(i+1)*4,\n                        parse_index(self.shape),\n                        prev_comp_name, parse_index(self.shape), prev_signal.name)\n        else:\n            inject_str += '{}out{} <== {}.{}{};\\n'.format(' '*(i+1)*4,\n                        parse_index(self.shape),\n                        prev_comp_name, prev_signal.name, parse_index(self.shape))\n        inject_str += '}'*len(self.shape)+'\\n'\n        return inject_str\n\n@dataclass\nclass Component:\n    name: str\n    template: Template\n    inputs: typing.List[Signal]\n    outputs: typing.List[Signal]\n    # optional args\n    args: typing.Dict[str, typing.Any] = None\n\n    def inject_include(self) -> str:\n        '''include the component template'''\n        return 'include \"../{}\";\\n'.format(self.template.fpath)\n    \n    def inject_signal(self, prev_comp: Component = None, last_comp: bool = False) -> str:\n        '''inject the component signals'''\n        inject_str = ''\n        for signal in self.inputs:\n            if signal.name == 'out' or signal.name == 'remainder':\n                inject_str += signal.inject_signal(self.name)\n                if last_comp is True and signal.name == 'out':\n                    inject_str += signal.inject_output_signal()\n            elif signal.value is None and prev_comp is None:\n                inject_str += signal.inject_input_signal()\n            elif signal.value is not None:\n                inject_str += signal.inject_signal(self.name)\n        return inject_str\n    \n    def inject_component(self) -> str:\n        '''inject the component declaration'''\n        if self.template.op_name == 'ReLU':\n            for signal in self.inputs:\n                if signal.name == 'out':\n                    output_signal = signal\n                    break\n            inject_str = 'component {}{};\\n'.format(self.name, parse_shape(output_signal.shape))\n            for i in range(len(output_signal.shape)):\n                inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\\n'.format(\n                            ' '*i*4, i, i, output_signal.shape[i], i)\n            inject_str += '{}{}{} = ReLU();\\n'.format(' '*(i+1)*4,\n                        self.name, parse_index(output_signal.shape))\n            inject_str += '}'*len(output_signal.shape)+'\\n'\n            return inject_str\n\n        return 'component {} = {}({});\\n'.format(\n            self.name, self.template.op_name, self.parse_args(self.template.args, self.args))\n    \n    def inject_main(self, prev_comp: Component = None, last_comp: bool = False) -> str:\n        '''inject the component main'''\n        inject_str = ''\n        for signal in self.inputs:\n            if signal.value is not None or signal.name == 'out' or signal.name == 'remainder':\n                inject_str += signal.inject_main(self.name)\n            elif prev_comp is None:\n                inject_str += signal.inject_input_main(self.name)\n            else:\n                for sig in prev_comp.inputs:\n                    if sig.name == 'out':\n                        output_signal = sig\n                        break\n                if output_signal is None:\n                    output_signal = prev_comp.outputs[0]\n                inject_str += signal.inject_main(self.name, prev_comp.name, output_signal)\n                print\n        if last_comp:\n            for signal in self.inputs:\n                if signal.name == 'out':\n                    inject_str += signal.inject_output_main(self.name, signal)\n                    break\n            for signal in self.outputs:\n                inject_str += signal.inject_output_main(self.name, signal)\n        return inject_str\n\n    def to_json(self, dec: int) -> typing.Dict[str, typing.Any]:\n        '''convert the component params to json format'''\n        json_dict = {}\n        for signal in self.inputs:\n            if signal.value is not None:\n                if signal.name == 'bias' or signal.name == 'b':\n                    scaling = float(10**(2*dec))\n                else:\n                    scaling = float(10**dec)\n                value = [str(int(v*scaling)) for v in signal.value.flatten().tolist()]\n                # reshape the value to match the circom shape\n                if len(signal.shape) > 1:\n                    value = np.array(value).reshape(signal.shape).tolist()\n                json_dict.update({f'{self.name}_{signal.name}': value})\n        return json_dict\n    \n    @staticmethod\n    def parse_args(template_args: typing.List[str], args: typing.Dict[str, typing.Any]) -> str:\n        '''parse the args to a format string, ready to be injected'''\n        args_str = '{'+'}, {'.join(template_args)+'}'\n        return args_str.format(**args)\n\n@dataclass\nclass Circuit:\n    components: typing.List[Component]\n\n    def __init__(self):\n        self.components = []\n\n    def add_component(self, component: Component):\n        self.components.append(component)\n    \n    def add_components(self, components: typing.List[Component]):\n        self.components.extend(components)\n\n    def inject_include(self) -> str:\n        '''inject the include statements'''\n        inject_str = []\n        for component in self.components:\n            inject_str.append(component.inject_include())\n        return ''.join(set(inject_str))\n\n    def inject_signal(self) -> str:\n        '''inject the signal declarations'''\n        inject_str = self.components[0].inject_signal()\n        for i in range(1, len(self.components)):\n            inject_str += self.components[i].inject_signal(self.components[i-1], i==len(self.components)-1)\n        return inject_str\n\n    def inject_component(self) -> str:\n        '''inject the component declarations'''\n        inject_str = ''\n        for component in self.components:\n            inject_str += component.inject_component()\n        return inject_str\n    \n    def inject_main(self) -> str:\n        '''inject the main template'''\n        inject_str = self.components[0].inject_main()\n        for i in range(1, len(self.components)):\n            inject_str += self.components[i].inject_main(self.components[i-1], i==len(self.components)-1)\n        return inject_str\n\n    def to_circom(self) -> str:\n        '''convert the circuit to a circom file'''\n        return circom_template_string.format(**{\n            'include': self.inject_include(),\n            'brace_left': '{',\n            'signal': self.inject_signal(),\n            'component': self.inject_component(),\n            'main': self.inject_main(),\n            'brace_right': '}',\n        })\n\n    def to_json(self, dec: int) -> str:\n        '''convert the model weights to json format'''\n        json_dict = {}\n\n        for component in self.components:\n            json_dict.update(component.to_json(dec))\n        \n        return json.dumps(json_dict)"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "keras2circom/model.py",
        "content": "# Read keras model into list of parameters like op, input, output, weight, bias\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nimport typing\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.layers import Layer as KerasLayer\nimport numpy as np\n\nsupported_ops = [\n    'Activation',\n    'AveragePooling2D',\n    'BatchNormalization',\n    'Conv2D',\n    'Dense',\n    'Flatten',\n    'GlobalAveragePooling2D',\n    'GlobalMaxPooling2D',\n    'MaxPooling2D',\n    'ReLU',\n    'Softmax',\n]\n\nskip_ops = [\n    'Dropout',\n    'InputLayer',\n]\n\n\n# read each layer in a model and convert it to a class called Layer\n@dataclass\nclass Layer:\n    ''' A single layer in a Keras model. '''\n    op: str\n    name: str\n    input: typing.List[int]\n    output: typing.List[int]\n    config: typing.Dict[str, typing.Any]\n    weights: typing.List[np.ndarray]\n\n    def __init__(self, layer: KerasLayer):\n        self.op = layer.__class__.__name__\n        self.name = layer.name\n        self.input = layer.input_shape[1:]\n        self.output = layer.output_shape[1:]\n        self.config = layer.get_config()\n        self.weights = layer.get_weights()\n\nclass Model:\n    layers: typing.List[Layer]\n\n    def __init__(self, filename: str, raw: bool = False):\n        ''' Load a Keras model from a file. '''\n        model = load_model(filename)\n        \n        self.layers = [Layer(layer) for layer in model.layers if self._for_transpilation(layer.__class__.__name__)]\n    \n    @staticmethod\n    def _for_transpilation(op: str) -> bool:\n        if op in skip_ops:\n            return False\n        if op in supported_ops:\n            return True\n        raise NotImplementedError(f'Unsupported op: {op}')"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "keras2circom/script.py",
        "content": "from .circom import Circuit, Component\n\n# template string for circuit.py\npython_template_string = '''\"\"\" Make an interger-only circuit of the corresponding CIRCOM circuit.\n\nUsage:\n    circuit.py <circuit.json> <input.json> [-o <output>]\n    circuit.py (-h | --help)\n\nOptions:\n    -h --help                               Show this screen.\n    -o <output> --output=<output>           Output directory [default: output].\n\n\"\"\"\n\nfrom docopt import docopt\nimport json\n\ntry:\n    from keras2circom.util import *\nexcept:\n    import sys\n    import os\n    # add parent directory to sys.path\n    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n    from keras2circom.util import *\n\ndef inference(input, circuit):\n    out = input['in']\n    output = {brackets}\n    \n{components}\n    return out, output\n\n\ndef main():\n    \"\"\" Main entry point of the app \"\"\"\n    args = docopt(__doc__)\n    \n    # parse input.json\n    with open(args['<input.json>']) as f:\n        input = json.load(f)\n    \n    # parse circuit.json\n    with open(args['<circuit.json>']) as f:\n        circuit = json.load(f)\n\n    out, output = inference(input, circuit)\n\n    # write output.json\n    with open(args['--output'] + '/output.json', 'w') as f:\n        json.dump(output, f)\n\nif __name__ == \"__main__\":\n    \"\"\" This is executed when run from the command line \"\"\"\n    main()\n'''\n\n\ndef to_py(circuit: Circuit, dec: int) -> str:\n    comp_str = \"\"\n\n    for component in circuit.components:\n        comp_str += transpile_component(component, dec)\n\n    return python_template_string.format(\n        brackets=\"{}\",\n        components=comp_str,\n    )\n\ndef transpile_component(component: Component, dec: int) -> str:\n    comp_str = \"\"\n    if component.template.op_name == \"AveragePooling2D\":\n        comp_str += \"    out, remainder = AveragePooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            poolSize=component.args[\"poolSize\"],\n            strides=component.args[\"strides\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"BatchNormalization2D\":\n        comp_str += \"    out, remainder = BatchNormalizationInt({nRows}, {nCols}, {nChannels}, {n}, {input}, {a}, {b})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            a=\"circuit['{name}_a']\".format(name=component.name),\n            b=\"circuit['{name}_b']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Conv1D\":\n        comp_str += \"    out, remainder = Conv1DInt({nInputs}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nInputs=component.args[\"nInputs\"],\n            nChannels=component.args[\"nChannels\"],\n            nFilters=component.args[\"nFilters\"],\n            kernelSize=component.args[\"kernelSize\"],\n            strides=component.args[\"strides\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Conv2D\":\n        comp_str += \"    out, remainder = Conv2DInt({nRows}, {nCols}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            nFilters=component.args[\"nFilters\"],\n            kernelSize=component.args[\"kernelSize\"],\n            strides=component.args[\"strides\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Dense\":\n        comp_str += \"    out, remainder = DenseInt({nInputs}, {nOutputs}, {n}, {input}, {weights}, {bias})\\n\".format(\n            nInputs=component.args[\"nInputs\"],\n            nOutputs=component.args[\"nOutputs\"],\n            n=component.args[\"n\"],\n            input=\"out\",\n            weights=\"circuit['{name}_weights']\".format(name=component.name),\n            bias=\"circuit['{name}_bias']\".format(name=component.name),\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"GlobalAveragePooling2D\":\n        comp_str += \"    out, remainder = GlobalAveragePooling2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        comp_str += \"    output['{name}_remainder'] = remainder\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"GlobalMaxPooling2D\":\n        comp_str += \"    out = GlobalMaxPooling2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"MaxPooling2D\":\n        comp_str += \"    out = MaxPooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            poolSize=component.args[\"poolSize\"],\n            strides=component.args[\"strides\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"Flatten2D\":\n        comp_str += \"    out = Flatten2DInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=component.args[\"nRows\"],\n            nCols=component.args[\"nCols\"],\n            nChannels=component.args[\"nChannels\"],\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"ReLU\":\n        nRows, nCols, nChannels = component.inputs[0].shape\n        comp_str += \"    out = ReLUInt({nRows}, {nCols}, {nChannels}, {input})\\n\".format(\n            nRows=nRows,\n            nCols=nCols,\n            nChannels=nChannels,\n            input=\"out\"\n        )\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    elif component.template.op_name == \"ArgMax\":\n        comp_str += \"    out = ArgMaxInt(out)\\n\"\n        comp_str += \"    output['{name}_out'] = out\\n\".format(\n            name=component.name,\n        )\n        return comp_str+\"\\n\"\n    \n    else:\n        raise ValueError(\"Unknown component type: {}\".format(component.template.op_name))"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "keras2circom/transpiler.py",
        "content": "from .circom import *\nfrom .model import *\nfrom .script import *\n\nimport os\n\ndef transpile(filename: str, output_dir: str = 'output', raw: bool = False, dec: int = 18) -> Circuit:\n    ''' Transpile a Keras model to a CIRCOM circuit.'''\n    \n    model = Model(filename, raw)\n\n    circuit = Circuit()\n    for layer in model.layers[:-1]:\n        circuit.add_components(transpile_layer(layer, dec))\n    \n    circuit.add_components(transpile_layer(model.layers[-1], dec, True))\n\n    if raw:\n        if circuit.components[-1].template.op_name == 'ArgMax':\n            circuit.components.pop()\n    # create output directory if it doesn't exist\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    \n    with open(output_dir + '/circuit.circom', 'w') as f:\n        f.write(circuit.to_circom())\n    \n    with open(output_dir + '/circuit.json', 'w') as f:\n        f.write(circuit.to_json(int(dec)))\n    \n    with open(output_dir + '/circuit.py', 'w') as f:\n        f.write(to_py(circuit, int(dec)))\n    \n    return circuit\n\ndef transpile_layer(layer: Layer, dec: int = 18, last: bool = False) -> typing.List[Component]:\n    ''' Transpile a Keras layer to CIRCOM component(s).'''\n    if layer.op == 'Activation':\n        if layer.config['activation'] == 'softmax':\n            if last:\n                return transpile_ArgMax(layer)\n            raise ValueError('Softmax must be the last layer')\n        if layer.config['activation'] == 'relu':\n            return transpile_ReLU(layer)\n        if layer.config['activation'] == 'linear':\n            return []\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} not implemented')\n    \n    if layer.op == 'Softmax':\n        if last:\n            return transpile_ArgMax(layer)\n        raise ValueError('Softmax must be the last layer')\n    \n    if layer.op == 'ReLU':\n        return transpile_ReLU(layer)\n\n    if layer.op == 'AveragePooling2D':\n        return transpile_AveragePooling2D(layer)\n    \n    if layer.op == 'BatchNormalization':\n        return transpile_BatchNormalization2D(layer, dec)\n\n    if layer.op == 'Conv2D':\n        return transpile_Conv2D(layer, dec)\n    \n    if layer.op == 'Dense':\n        return transpile_Dense(layer, dec, last)\n        \n    if layer.op == 'Flatten':\n        return transpile_Flatten2D(layer)\n\n    if layer.op == 'GlobalAveragePooling2D':\n        return transpile_GlobalAveragePooling2D(layer)\n        \n    if layer.op == 'GlobalMaxPooling2D':\n        return transpile_GlobalMaxPooling2D(layer)\n    \n    if layer.op == 'MaxPooling2D':\n        return transpile_MaxPooling2D(layer)\n    \n    raise NotImplementedError(f'Layer {layer.op} is not supported yet.')\n\ndef transpile_ArgMax(layer: Layer) -> typing.List[Component]:\n    return [Component(layer.name, templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})]\n\ndef transpile_ReLU(layer: Layer) -> typing.List[Component]:\n    return [Component(layer.name, templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])]\n\ndef transpile_AveragePooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['pool_size'][0] != layer.config['pool_size'][1]:\n        raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    \n    return [Component(layer.name, templates['AveragePooling2D'], [Signal('in', layer.input), Signal('out', layer.output), Signal('remainder', layer.output)],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'poolSize': layer.config['pool_size'][0],\n        'strides': layer.config['strides'][0],\n        })]\n\ndef transpile_BatchNormalization2D(layer: Layer, dec: int) -> typing.List[Component]:\n    if layer.input.__len__() != 3:\n        raise NotImplementedError('Only 2D inputs are supported')\n    if layer.config['axis'][0] != 3:\n        raise NotImplementedError('Only axis=3 is supported')\n    if layer.config['center'] != True:\n        raise NotImplementedError('Only center=True is supported')\n    if layer.config['scale'] != True:\n        raise NotImplementedError('Only scale=True is supported')\n    \n    gamma = layer.weights[0]\n    beta = layer.weights[1]\n    moving_mean = layer.weights[2]\n    moving_var = layer.weights[3]\n    epsilon = layer.config['epsilon']\n\n    a = gamma/(moving_var+epsilon)**.5\n    b = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n    \n    return [Component(layer.name, templates['BatchNormalization2D'], [\n        Signal('in', layer.input),\n        Signal('a', a.shape, a),\n        Signal('b', b.shape, b),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'n': '10**'+dec,\n        })]\n\ndef transpile_Conv2D(layer: Layer, dec: int) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    if layer.config['kernel_size'][0] != layer.config['kernel_size'][1]:\n        raise NotImplementedError('Only kernel_size[0] == kernel_size[1] is supported')\n    if layer.config['dilation_rate'][0] != 1:\n        raise NotImplementedError('Only dilation_rate[0] == 1 is supported')\n    if layer.config['dilation_rate'][1] != 1:\n        raise NotImplementedError('Only dilation_rate[1] == 1 is supported')\n    if layer.config['groups'] != 1:\n        raise NotImplementedError('Only groups == 1 is supported')\n    if layer.config['activation'] not in ['linear', 'relu']:\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} is not supported')\n    \n    if layer.config['use_bias'] == False:\n        layer.weights.append(np.zeros(layer.weights[0].shape[-1]))\n\n    conv = Component(layer.name, templates['Conv2D'], [\n        Signal('in', layer.input),\n        Signal('weights', layer.weights[0].shape, layer.weights[0]),\n        Signal('bias', layer.weights[1].shape, layer.weights[1]),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'nFilters': layer.config['filters'],\n        'kernelSize': layer.config['kernel_size'][0],\n        'strides': layer.config['strides'][0],\n        'n': '10**'+dec,\n        })\n    \n    if layer.config['activation'] == 'relu':\n        activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])\n        return [conv, activation]\n    \n    return [conv]\n\ndef transpile_Dense(layer: Layer, dec: int, last: bool = False) -> typing.List[Component]:\n    if not last and layer.config['activation'] == 'softmax':\n        raise NotImplementedError('Softmax is only supported as last layer')\n    if layer.config['activation'] not in ['linear', 'relu', 'softmax']:\n        raise NotImplementedError(f'Activation {layer.config[\"activation\"]} is not supported')\n    if layer.config['use_bias'] == False:\n        layer.weights.append(np.zeros(layer.weights[0].shape[-1]))\n    \n    dense = Component(layer.name, templates['Dense'], [\n        Signal('in', layer.input),\n        Signal('weights', layer.weights[0].shape, layer.weights[0]),\n        Signal('bias', layer.weights[1].shape, layer.weights[1]),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nInputs': layer.input[0],\n        'nOutputs': layer.output[0],\n        'n': '10**'+dec,\n        })\n    \n    if layer.config['activation'] == 'relu':\n        activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])\n        return [dense, activation]\n    \n    if layer.config['activation'] == 'softmax':\n        activation = Component(layer.name+'_softmax', templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})\n        return [dense, activation]\n    \n    return [dense]\n\ndef transpile_Flatten2D(layer: Layer) -> typing.List[Component]:\n    if layer.input.__len__() != 3:\n        raise NotImplementedError('Only 2D inputs are supported')\n    \n    return [Component(layer.name, templates['Flatten2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_GlobalAveragePooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['keepdims']:\n        raise NotImplementedError('Only keepdims=False is supported')\n\n    return [Component(layer.name, templates['GlobalAveragePooling2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        Signal('remainder', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_GlobalMaxPooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['keepdims']:\n        raise NotImplementedError('Only keepdims=False is supported')\n\n    return [Component(layer.name, templates['GlobalMaxPooling2D'], [\n        Signal('in', layer.input),\n        Signal('out', layer.output),\n        ],[],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        })]\n\ndef transpile_MaxPooling2D(layer: Layer) -> typing.List[Component]:\n    if layer.config['data_format'] != 'channels_last':\n        raise NotImplementedError('Only data_format=\"channels_last\" is supported')\n    if layer.config['padding'] != 'valid':\n        raise NotImplementedError('Only padding=\"valid\" is supported')\n    if layer.config['pool_size'][0] != layer.config['pool_size'][1]:\n        raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')\n    if layer.config['strides'][0] != layer.config['strides'][1]:\n        raise NotImplementedError('Only strides[0] == strides[1] is supported')\n    \n    return [Component(layer.name, templates['MaxPooling2D'], [Signal('in', layer.input), Signal('out', layer.output)], [],{\n        'nRows': layer.input[0],\n        'nCols': layer.input[1],\n        'nChannels': layer.input[2],\n        'poolSize': layer.config['pool_size'][0],\n        'strides': layer.config['strides'][0],\n        })]\n"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "keras2circom/util.py",
        "content": "# assume all inputs are strings\ndef AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\n    out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n    remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n    for i in range((nRows-poolSize)//strides + 1):\n        for j in range((nCols-poolSize)//strides + 1):\n            for k in range(nChannels):\n                for x in range(poolSize):\n                    for y in range(poolSize):\n                        out[i][j][k] += int(input[i*strides+x][j*strides+y][k])\n                remainder[i][j][k] = str(out[i][j][k] % poolSize**2)\n                out[i][j][k] = str(out[i][j][k] // poolSize**2)\n    return out, remainder\n\ndef BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\n    out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n    remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n    for i in range(nRows):\n        for j in range(nCols):\n            for k in range(nChannels):\n                out[i][j][k] = int(X_in[i][j][k])*int(a_in[k]) + int(b_in[k])\n                remainder[i][j][k] = str(out[i][j][k] % n)\n                out[i][j][k] = str(out[i][j][k] // n)\n    return out, remainder\n\ndef Conv1DInt(nInputs, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n    out = [[0 for _ in range(nFilters)] for j in range((nInputs - kernelSize)//strides + 1)]\n    remainder = [[None for _ in range(nFilters)] for _ in range((nInputs - kernelSize)//strides + 1)]\n    for i in range((nInputs - kernelSize)//strides + 1):\n        for j in range(nFilters):\n            for k in range(kernelSize):\n                for l in range(nChannels):\n                    out[i][j] += int(input[i*strides + k][l])*int(weights[k][l][j])\n            out[i][j] += int(bias[j])\n            remainder[i][j] = str(out[i][j] % n)\n            out[i][j] = str(out[i][j] // n)\n    return out, remainder\n\ndef Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n    out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n    remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n    for i in range((nRows - kernelSize)//strides + 1):\n        for j in range((nCols - kernelSize)//strides + 1):\n            for m in range(nFilters):\n                for k in range(nChannels):\n                    for x in range(kernelSize):\n                        for y in range(kernelSize):\n                            out[i][j][m] += int(input[i*strides+x][j*strides+y][k])*int(weights[x][y][k][m])\n                out[i][j][m] += int(bias[m])\n                remainder[i][j][m] = str(out[i][j][m] % n)\n                out[i][j][m] = str(out[i][j][m] // n)\n    return out, remainder\n\ndef DenseInt(nInputs, nOutputs, n, input, weights, bias):\n    out = [0 for _ in range(nOutputs)]\n    remainder = [None for _ in range(nOutputs)]\n    for j in range(nOutputs):\n        for i in range(nInputs):\n            out[j] += int(input[i])*int(weights[i][j])\n        out[j] += int(bias[j])\n        remainder[j] = str(out[j] % n)\n        out[j] = str(out[j] // n)\n    return out, remainder\n\ndef GlobalAveragePooling2DInt(nRows, nCols, nChannels, input):\n    out = [0 for _ in range(nChannels)]\n    remainder = [None for _ in range(nChannels)]\n    for k in range(nChannels):\n        for i in range(nRows):\n            for j in range(nCols):\n                out[k] += int(input[i][j][k])\n        remainder[k] = str(out[k] % (nRows * nCols))\n        out[k] = str(out[k] // (nRows * nCols))\n    return out, remainder\n\ndef GlobalMaxPooling2DInt(nRows, nCols, nChannels, input):\n    out = [max(int(input[i][j][k]) for i in range(nRows) for j in range(nCols)) for k in range(nChannels)]\n    return out\n\ndef MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n    out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\n    return out\n\ndef Flatten2DInt(nRows, nCols, nChannels, input):\n    out = [str(int(input[i][j][k])) for i in range(nRows) for j in range(nCols) for k in range(nChannels)]\n    return out\n\ndef ReLUInt(nRows, nCols, nChannels, input):\n    out = [[[str(max(int(input[i][j][k]), 0)) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n    return out\n\ndef ArgMaxInt(input):\n    return [input.index(str(max(int(input[i]) for i in range(len(input)))))]"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "main.py",
        "content": "\"\"\" Transpile a Keras model to a CIRCOM circuit.\n\nUsage:\n    main.py <model.h5> [-o <output>] [--raw] [-d <decimals>]\n    main.py (-h | --help)\n\nOptions:\n    -h --help                               Show this screen.\n    -o <output> --output=<output>           Output directory [default: output].\n    --raw                                   Output raw model outputs instead of the argmax of outputs [default: False].\n    -d <decimals> --decimals=<decimals>     Number of decimals for model precision [default: 18].\n\n\"\"\"\nfrom docopt import docopt\n\nfrom keras2circom import circom, transpiler\n\ndef main():\n    \"\"\" Main entry point of the app \"\"\"\n    args = docopt(__doc__)\n    circom.dir_parse('node_modules/circomlib-ml/circuits/', skips=['util.circom', 'circomlib-matrix', 'circomlib', 'crypto'])\n    transpiler.transpile(args['<model.h5>'], args['--output'], args['--raw'], args['--decimals'])\n\nif __name__ == \"__main__\":\n    \"\"\" This is executed when run from the command line \"\"\"\n    main()"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "models/model.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# list of supported layers\\n\",\n    \"from tensorflow.keras.layers import (\\n\",\n    \"    Input,\\n\",\n    \"    Activation,\\n\",\n    \"    AveragePooling2D,\\n\",\n    \"    BatchNormalization,\\n\",\n    \"    Conv2D,\\n\",\n    \"    Dense,\\n\",\n    \"    Dropout,\\n\",\n    \"    Flatten,\\n\",\n    \"    GlobalAveragePooling2D,\\n\",\n    \"    GlobalMaxPooling2D,\\n\",\n    \"    MaxPooling2D,\\n\",\n    \"    ReLU,\\n\",\n    \"    Softmax,\\n\",\n    \"    )\\n\",\n    \"from tensorflow.keras import Model\\n\",\n    \"from tensorflow.keras.datasets import mnist\\n\",\n    \"from tensorflow.keras.utils import to_categorical\\n\",\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"import tensorflow as tf\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# load MNIST dataset\\n\",\n    \"(X_train, y_train), (X_test, y_test) = mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# convert y_train and y_test to one-hot encoding\\n\",\n    \"y_train = to_categorical(y_train)\\n\",\n    \"y_test = to_categorical(y_test)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# reshape X_train and X_test to 4D tensor\\n\",\n    \"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\\n\",\n    \"X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\\n\",\n    \"\\n\",\n    \"#normalizing\\n\",\n    \"X_train = X_train.astype('float32')\\n\",\n    \"X_test = X_test.astype('float32')\\n\",\n    \"X_train /= 255.0\\n\",\n    \"X_test /= 255.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"inputs = Input(shape=(28,28,1))\\n\",\n    \"out = Conv2D(4, 3, use_bias=False)(inputs)\\n\",\n    \"out = BatchNormalization()(out)\\n\",\n    \"out = Activation('relu')(out)\\n\",\n    \"out = MaxPooling2D()(out)\\n\",\n    \"out = Conv2D(8, 3, use_bias=True, strides=2)(out)\\n\",\n    \"out = ReLU()(out)\\n\",\n    \"out = AveragePooling2D()(out)\\n\",\n    \"out = Flatten()(out)\\n\",\n    \"# out = Dropout(0.5)(out)\\n\",\n    \"out = Dense(10, activation=\\\"softmax\\\")(out)\\n\",\n    \"model = Model(inputs, out)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Model: \\\"model\\\"\\n\",\n      \"_________________________________________________________________\\n\",\n      \" Layer (type)                Output Shape              Param #   \\n\",\n      \"=================================================================\\n\",\n      \" input_1 (InputLayer)        [(None, 28, 28, 1)]       0         \\n\",\n      \"                                                                 \\n\",\n      \" conv2d (Conv2D)             (None, 26, 26, 4)         36        \\n\",\n      \"                                                                 \\n\",\n      \" batch_normalization (BatchN  (None, 26, 26, 4)        16        \\n\",\n      \" ormalization)                                                   \\n\",\n      \"                                                                 \\n\",\n      \" activation (Activation)     (None, 26, 26, 4)         0         \\n\",\n      \"                                                                 \\n\",\n      \" max_pooling2d (MaxPooling2D  (None, 13, 13, 4)        0         \\n\",\n      \" )                                                               \\n\",\n      \"                                                                 \\n\",\n      \" conv2d_1 (Conv2D)           (None, 6, 6, 8)           296       \\n\",\n      \"                                                                 \\n\",\n      \" re_lu (ReLU)                (None, 6, 6, 8)           0         \\n\",\n      \"                                                                 \\n\",\n      \" average_pooling2d (AverageP  (None, 3, 3, 8)          0         \\n\",\n      \" ooling2D)                                                       \\n\",\n      \"                                                                 \\n\",\n      \" flatten (Flatten)           (None, 72)                0         \\n\",\n      \"                                                                 \\n\",\n      \" dense (Dense)               (None, 10)                730       \\n\",\n      \"                                                                 \\n\",\n      \"=================================================================\\n\",\n      \"Total params: 1,078\\n\",\n      \"Trainable params: 1,070\\n\",\n      \"Non-trainable params: 8\\n\",\n      \"_________________________________________________________________\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"model.summary()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.compile(\\n\",\n    \"    loss='categorical_crossentropy',\\n\",\n    \"    optimizer='adam',\\n\",\n    \"    metrics=['acc']\\n\",\n    \"    )\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Epoch 1/15\\n\"\n     ]\n    },\n    {\n     \"name\": \"stderr\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2023-11-26 21:47:52.776729: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\\n\"\n     ]\n    },\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.5203 - acc: 0.8386 - val_loss: 0.2099 - val_acc: 0.9363\\n\",\n      \"Epoch 2/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1926 - acc: 0.9419 - val_loss: 0.1497 - val_acc: 0.9543\\n\",\n      \"Epoch 3/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1551 - acc: 0.9522 - val_loss: 0.1263 - val_acc: 0.9591\\n\",\n      \"Epoch 4/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1361 - acc: 0.9580 - val_loss: 0.1139 - val_acc: 0.9628\\n\",\n      \"Epoch 5/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1253 - acc: 0.9617 - val_loss: 0.1031 - val_acc: 0.9679\\n\",\n      \"Epoch 6/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1168 - acc: 0.9636 - val_loss: 0.0976 - val_acc: 0.9697\\n\",\n      \"Epoch 7/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1113 - acc: 0.9650 - val_loss: 0.0923 - val_acc: 0.9711\\n\",\n      \"Epoch 8/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1072 - acc: 0.9673 - val_loss: 0.0884 - val_acc: 0.9732\\n\",\n      \"Epoch 9/15\\n\",\n      \"1875/1875 [==============================] - 12s 7ms/step - loss: 0.1026 - acc: 0.9683 - val_loss: 0.0879 - val_acc: 0.9725\\n\",\n      \"Epoch 10/15\\n\",\n      \"1875/1875 [==============================] - 11s 6ms/step - loss: 0.0999 - acc: 0.9691 - val_loss: 0.0928 - val_acc: 0.9719\\n\",\n      \"Epoch 11/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0968 - acc: 0.9702 - val_loss: 0.0954 - val_acc: 0.9699\\n\",\n      \"Epoch 12/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0945 - acc: 0.9706 - val_loss: 0.0841 - val_acc: 0.9740\\n\",\n      \"Epoch 13/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0926 - acc: 0.9718 - val_loss: 0.0826 - val_acc: 0.9748\\n\",\n      \"Epoch 14/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0893 - acc: 0.9723 - val_loss: 0.0803 - val_acc: 0.9751\\n\",\n      \"Epoch 15/15\\n\",\n      \"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0892 - acc: 0.9723 - val_loss: 0.0767 - val_acc: 0.9757\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"<keras.callbacks.History at 0x177842d60>\"\n      ]\n     },\n     \"execution_count\": 8,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"model.save('model.h5')\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  },\n  \"orig_nbformat\": 4,\n  \"vscode\": {\n   \"interpreter\": {\n    \"hash\": \"71414dc221f26c27f268040756e42b4f7499507456a67f7434828e3314a20678\"\n   }\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "test/accuracy.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!cd .. && python main.py models/model.h5\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import sys\\n\",\n    \"import os\\n\",\n    \"# add parent directory to sys.path\\n\",\n    \"sys.path.append(os.path.dirname((os.getcwd())))\\n\",\n    \"from output.circuit import inference\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open('../output/circuit.json') as f:\\n\",\n    \"    circuit = json.load(f)\\n\",\n    \"\\n\",\n    \"with open('y_test.json') as f:\\n\",\n    \"    y_test = json.load(f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"#0: 100.00%\\n\",\n      \"#1: 100.00%\\n\",\n      \"#2: 100.00%\\n\",\n      \"#3: 100.00%\\n\",\n      \"#4: 100.00%\\n\",\n      \"#5: 100.00%\\n\",\n      \"#6: 100.00%\\n\",\n      \"#7: 100.00%\\n\",\n      \"#8: 100.00%\\n\",\n      \"#9: 100.00%\\n\",\n      \"#10: 100.00%\\n\",\n      \"#11: 100.00%\\n\",\n      \"#12: 100.00%\\n\",\n      \"#13: 100.00%\\n\",\n      \"#14: 100.00%\\n\",\n      \"#15: 100.00%\\n\",\n      \"#16: 100.00%\\n\",\n      \"#17: 100.00%\\n\",\n      \"#18: 94.74%\\n\",\n      \"#19: 95.00%\\n\",\n      \"#20: 95.24%\\n\",\n      \"#21: 95.45%\\n\",\n      \"#22: 95.65%\\n\",\n      \"#23: 95.83%\\n\",\n      \"#24: 96.00%\\n\",\n      \"#25: 96.15%\\n\",\n      \"#26: 96.30%\\n\",\n      \"#27: 96.43%\\n\",\n      \"#28: 96.55%\\n\",\n      \"#29: 96.67%\\n\",\n      \"#30: 96.77%\\n\",\n      \"#31: 96.88%\\n\",\n      \"#32: 96.97%\\n\",\n      \"#33: 97.06%\\n\",\n      \"#34: 97.14%\\n\",\n      \"#35: 97.22%\\n\",\n      \"#36: 97.30%\\n\",\n      \"#37: 97.37%\\n\",\n      \"#38: 97.44%\\n\",\n      \"#39: 97.50%\\n\",\n      \"#40: 97.56%\\n\",\n      \"#41: 97.62%\\n\",\n      \"#42: 97.67%\\n\",\n      \"#43: 97.73%\\n\",\n      \"#44: 97.78%\\n\",\n      \"#45: 97.83%\\n\",\n      \"#46: 97.87%\\n\",\n      \"#47: 97.92%\\n\",\n      \"#48: 97.96%\\n\",\n      \"#49: 98.00%\\n\",\n      \"#50: 98.04%\\n\",\n      \"#51: 98.08%\\n\",\n      \"#52: 98.11%\\n\",\n      \"#53: 98.15%\\n\",\n      \"#54: 98.18%\\n\",\n      \"#55: 98.21%\\n\",\n      \"#56: 98.25%\\n\",\n      \"#57: 98.28%\\n\",\n      \"#58: 98.31%\\n\",\n      \"#59: 98.33%\\n\",\n      \"#60: 98.36%\\n\",\n      \"#61: 98.39%\\n\",\n      \"#62: 98.41%\\n\",\n      \"#63: 98.44%\\n\",\n      \"#64: 98.46%\\n\",\n      \"#65: 98.48%\\n\",\n      \"#66: 98.51%\\n\",\n      \"#67: 98.53%\\n\",\n      \"#68: 98.55%\\n\",\n      \"#69: 98.57%\\n\",\n      \"#70: 98.59%\\n\",\n      \"#71: 98.61%\\n\",\n      \"#72: 98.63%\\n\",\n      \"#73: 98.65%\\n\",\n      \"#74: 98.67%\\n\",\n      \"#75: 98.68%\\n\",\n      \"#76: 98.70%\\n\",\n      \"#77: 98.72%\\n\",\n      \"#78: 98.73%\\n\",\n      \"#79: 98.75%\\n\",\n      \"#80: 98.77%\\n\",\n      \"#81: 98.78%\\n\",\n      \"#82: 98.80%\\n\",\n      \"#83: 98.81%\\n\",\n      \"#84: 98.82%\\n\",\n      \"#85: 98.84%\\n\",\n      \"#86: 98.85%\\n\",\n      \"#87: 98.86%\\n\",\n      \"#88: 98.88%\\n\",\n      \"#89: 98.89%\\n\",\n      \"#90: 98.90%\\n\",\n      \"#91: 98.91%\\n\",\n      \"#92: 98.92%\\n\",\n      \"#93: 98.94%\\n\",\n      \"#94: 98.95%\\n\",\n      \"#95: 98.96%\\n\",\n      \"#96: 98.97%\\n\",\n      \"#97: 98.98%\\n\",\n      \"#98: 98.99%\\n\",\n      \"#99: 99.00%\\n\",\n      \"#100: 99.01%\\n\",\n      \"#101: 99.02%\\n\",\n      \"#102: 99.03%\\n\",\n      \"#103: 99.04%\\n\",\n      \"#104: 99.05%\\n\",\n      \"#105: 99.06%\\n\",\n      \"#106: 99.07%\\n\",\n      \"#107: 99.07%\\n\",\n      \"#108: 99.08%\\n\",\n      \"#109: 99.09%\\n\",\n      \"#110: 99.10%\\n\",\n      \"#111: 99.11%\\n\",\n      \"#112: 99.12%\\n\",\n      \"#113: 99.12%\\n\",\n      \"#114: 99.13%\\n\",\n      \"#115: 99.14%\\n\",\n      \"#116: 99.15%\\n\",\n      \"#117: 99.15%\\n\",\n      \"#118: 99.16%\\n\",\n      \"#119: 99.17%\\n\",\n      \"#120: 99.17%\\n\",\n      \"#121: 99.18%\\n\",\n      \"#122: 99.19%\\n\",\n      \"#123: 99.19%\\n\",\n      \"#124: 99.20%\\n\",\n      \"#125: 99.21%\\n\",\n      \"#126: 99.21%\\n\",\n      \"#127: 99.22%\\n\",\n      \"#128: 99.22%\\n\",\n      \"#129: 99.23%\\n\",\n      \"#130: 99.24%\\n\",\n      \"#131: 99.24%\\n\",\n      \"#132: 99.25%\\n\",\n      \"#133: 99.25%\\n\",\n      \"#134: 99.26%\\n\",\n      \"#135: 99.26%\\n\",\n      \"#136: 99.27%\\n\",\n      \"#137: 99.28%\\n\",\n      \"#138: 99.28%\\n\",\n      \"#139: 99.29%\\n\",\n      \"#140: 99.29%\\n\",\n      \"#141: 99.30%\\n\",\n      \"#142: 99.30%\\n\",\n      \"#143: 99.31%\\n\",\n      \"#144: 99.31%\\n\",\n      \"#145: 99.32%\\n\",\n      \"#146: 99.32%\\n\",\n      \"#147: 99.32%\\n\",\n      \"#148: 99.33%\\n\",\n      \"#149: 99.33%\\n\",\n      \"#150: 99.34%\\n\",\n      \"#151: 98.68%\\n\",\n      \"#152: 98.69%\\n\",\n      \"#153: 98.70%\\n\",\n      \"#154: 98.71%\\n\",\n      \"#155: 98.72%\\n\",\n      \"#156: 98.73%\\n\",\n      \"#157: 98.73%\\n\",\n      \"#158: 98.74%\\n\",\n      \"#159: 98.75%\\n\",\n      \"#160: 98.76%\\n\",\n      \"#161: 98.77%\\n\",\n      \"#162: 98.77%\\n\",\n      \"#163: 98.78%\\n\",\n      \"#164: 98.79%\\n\",\n      \"#165: 98.80%\\n\",\n      \"#166: 98.80%\\n\",\n      \"#167: 98.81%\\n\",\n      \"#168: 98.82%\\n\",\n      \"#169: 98.82%\\n\",\n      \"#170: 98.83%\\n\",\n      \"#171: 98.84%\\n\",\n      \"#172: 98.84%\\n\",\n      \"#173: 98.85%\\n\",\n      \"#174: 98.86%\\n\",\n      \"#175: 98.86%\\n\",\n      \"#176: 98.87%\\n\",\n      \"#177: 98.88%\\n\",\n      \"#178: 98.88%\\n\",\n      \"#179: 98.89%\\n\",\n      \"#180: 98.90%\\n\",\n      \"#181: 98.90%\\n\",\n      \"#182: 98.91%\\n\",\n      \"#183: 98.91%\\n\",\n      \"#184: 98.92%\\n\",\n      \"#185: 98.92%\\n\",\n      \"#186: 98.93%\\n\",\n      \"#187: 98.94%\\n\",\n      \"#188: 98.94%\\n\",\n      \"#189: 98.95%\\n\",\n      \"#190: 98.95%\\n\",\n      \"#191: 98.96%\\n\",\n      \"#192: 98.96%\\n\",\n      \"#193: 98.97%\\n\",\n      \"#194: 98.97%\\n\",\n      \"#195: 98.98%\\n\",\n      \"#196: 98.98%\\n\",\n      \"#197: 98.99%\\n\",\n      \"#198: 98.99%\\n\",\n      \"#199: 99.00%\\n\",\n      \"#200: 99.00%\\n\",\n      \"#201: 99.01%\\n\",\n      \"#202: 99.01%\\n\",\n      \"#203: 99.02%\\n\",\n      \"#204: 99.02%\\n\",\n      \"#205: 99.03%\\n\",\n      \"#206: 99.03%\\n\",\n      \"#207: 99.04%\\n\",\n      \"#208: 99.04%\\n\",\n      \"#209: 99.05%\\n\",\n      \"#210: 99.05%\\n\",\n      \"#211: 99.06%\\n\",\n      \"#212: 99.06%\\n\",\n      \"#213: 99.07%\\n\",\n      \"#214: 99.07%\\n\",\n      \"#215: 99.07%\\n\",\n      \"#216: 99.08%\\n\",\n      \"#217: 99.08%\\n\",\n      \"#218: 99.09%\\n\",\n      \"#219: 99.09%\\n\",\n      \"#220: 99.10%\\n\",\n      \"#221: 99.10%\\n\",\n      \"#222: 99.10%\\n\",\n      \"#223: 99.11%\\n\",\n      \"#224: 99.11%\\n\",\n      \"#225: 99.12%\\n\",\n      \"#226: 99.12%\\n\",\n      \"#227: 99.12%\\n\",\n      \"#228: 99.13%\\n\",\n      \"#229: 99.13%\\n\",\n      \"#230: 99.13%\\n\",\n      \"#231: 99.14%\\n\",\n      \"#232: 99.14%\\n\",\n      \"#233: 99.15%\\n\",\n      \"#234: 99.15%\\n\",\n      \"#235: 99.15%\\n\",\n      \"#236: 99.16%\\n\",\n      \"#237: 99.16%\\n\",\n      \"#238: 99.16%\\n\",\n      \"#239: 99.17%\\n\",\n      \"#240: 99.17%\\n\",\n      \"#241: 98.76%\\n\",\n      \"#242: 98.77%\\n\",\n      \"#243: 98.77%\\n\",\n      \"#244: 98.78%\\n\",\n      \"#245: 98.78%\\n\",\n      \"#246: 98.79%\\n\",\n      \"#247: 98.39%\\n\",\n      \"#248: 98.39%\\n\",\n      \"#249: 98.40%\\n\",\n      \"#250: 98.41%\\n\",\n      \"#251: 98.41%\\n\",\n      \"#252: 98.42%\\n\",\n      \"#253: 98.43%\\n\",\n      \"#254: 98.43%\\n\",\n      \"#255: 98.44%\\n\",\n      \"#256: 98.44%\\n\",\n      \"#257: 98.45%\\n\",\n      \"#258: 98.46%\\n\",\n      \"#259: 98.08%\\n\",\n      \"#260: 98.08%\\n\",\n      \"#261: 98.09%\\n\",\n      \"#262: 98.10%\\n\",\n      \"#263: 98.11%\\n\",\n      \"#264: 97.74%\\n\",\n      \"#265: 97.74%\\n\",\n      \"#266: 97.38%\\n\",\n      \"#267: 97.39%\\n\",\n      \"#268: 97.40%\\n\",\n      \"#269: 97.41%\\n\",\n      \"#270: 97.42%\\n\",\n      \"#271: 97.43%\\n\",\n      \"#272: 97.44%\\n\",\n      \"#273: 97.45%\\n\",\n      \"#274: 97.45%\\n\",\n      \"#275: 97.46%\\n\",\n      \"#276: 97.47%\\n\",\n      \"#277: 97.48%\\n\",\n      \"#278: 97.49%\\n\",\n      \"#279: 97.50%\\n\",\n      \"#280: 97.51%\\n\",\n      \"#281: 97.52%\\n\",\n      \"#282: 97.17%\\n\",\n      \"#283: 97.18%\\n\",\n      \"#284: 97.19%\\n\",\n      \"#285: 97.20%\\n\",\n      \"#286: 97.21%\\n\",\n      \"#287: 97.22%\\n\",\n      \"#288: 97.23%\\n\",\n      \"#289: 97.24%\\n\",\n      \"#290: 97.25%\\n\",\n      \"#291: 97.26%\\n\",\n      \"#292: 97.27%\\n\",\n      \"#293: 97.28%\\n\",\n      \"#294: 97.29%\\n\",\n      \"#295: 97.30%\\n\",\n      \"#296: 97.31%\\n\",\n      \"#297: 97.32%\\n\",\n      \"#298: 97.32%\\n\",\n      \"#299: 97.33%\\n\",\n      \"#300: 97.34%\\n\",\n      \"#301: 97.35%\\n\",\n      \"#302: 97.36%\\n\",\n      \"#303: 97.37%\\n\",\n      \"#304: 97.38%\\n\",\n      \"#305: 97.39%\\n\",\n      \"#306: 97.39%\\n\",\n      \"#307: 97.40%\\n\",\n      \"#308: 97.41%\\n\",\n      \"#309: 97.42%\\n\",\n      \"#310: 97.43%\\n\",\n      \"#311: 97.44%\\n\",\n      \"#312: 97.44%\\n\",\n      \"#313: 97.45%\\n\",\n      \"#314: 97.46%\\n\",\n      \"#315: 97.47%\\n\",\n      \"#316: 97.48%\\n\",\n      \"#317: 97.48%\\n\",\n      \"#318: 97.49%\\n\",\n      \"#319: 97.50%\\n\",\n      \"#320: 97.20%\\n\",\n      \"#321: 97.20%\\n\",\n      \"#322: 97.21%\\n\",\n      \"#323: 97.22%\\n\",\n      \"#324: 97.23%\\n\",\n      \"#325: 97.24%\\n\",\n      \"#326: 97.25%\\n\",\n      \"#327: 97.26%\\n\",\n      \"#328: 97.26%\\n\",\n      \"#329: 97.27%\\n\",\n      \"#330: 97.28%\\n\",\n      \"#331: 97.29%\\n\",\n      \"#332: 97.30%\\n\",\n      \"#333: 97.31%\\n\",\n      \"#334: 97.31%\\n\",\n      \"#335: 97.32%\\n\",\n      \"#336: 97.33%\\n\",\n      \"#337: 97.34%\\n\",\n      \"#338: 97.35%\\n\",\n      \"#339: 97.35%\\n\",\n      \"#340: 97.36%\\n\",\n      \"#341: 97.37%\\n\",\n      \"#342: 97.38%\\n\",\n      \"#343: 97.38%\\n\",\n      \"#344: 97.39%\\n\",\n      \"#345: 97.40%\\n\",\n      \"#346: 97.41%\\n\",\n      \"#347: 97.41%\\n\",\n      \"#348: 97.42%\\n\",\n      \"#349: 97.43%\\n\",\n      \"#350: 97.44%\\n\",\n      \"#351: 97.44%\\n\",\n      \"#352: 97.45%\\n\",\n      \"#353: 97.46%\\n\",\n      \"#354: 97.46%\\n\",\n      \"#355: 97.47%\\n\",\n      \"#356: 97.48%\\n\",\n      \"#357: 97.49%\\n\",\n      \"#358: 97.21%\\n\",\n      \"#359: 97.22%\\n\",\n      \"#360: 97.23%\\n\",\n      \"#361: 97.24%\\n\",\n      \"#362: 97.25%\\n\",\n      \"#363: 97.25%\\n\",\n      \"#364: 97.26%\\n\",\n      \"#365: 97.27%\\n\",\n      \"#366: 97.28%\\n\",\n      \"#367: 97.28%\\n\",\n      \"#368: 97.29%\\n\",\n      \"#369: 97.30%\\n\",\n      \"#370: 97.30%\\n\",\n      \"#371: 97.31%\\n\",\n      \"#372: 97.32%\\n\",\n      \"#373: 97.33%\\n\",\n      \"#374: 97.33%\\n\",\n      \"#375: 97.34%\\n\",\n      \"#376: 97.35%\\n\",\n      \"#377: 97.35%\\n\",\n      \"#378: 97.36%\\n\",\n      \"#379: 97.37%\\n\",\n      \"#380: 97.38%\\n\",\n      \"#381: 97.38%\\n\",\n      \"#382: 97.39%\\n\",\n      \"#383: 97.40%\\n\",\n      \"#384: 97.40%\\n\",\n      \"#385: 97.41%\\n\",\n      \"#386: 97.42%\\n\",\n      \"#387: 97.42%\\n\",\n      \"#388: 97.43%\\n\",\n      \"#389: 97.44%\\n\",\n      \"#390: 97.44%\\n\",\n      \"#391: 97.45%\\n\",\n      \"#392: 97.46%\\n\",\n      \"#393: 97.46%\\n\",\n      \"#394: 97.47%\\n\",\n      \"#395: 97.47%\\n\",\n      \"#396: 97.48%\\n\",\n      \"#397: 97.49%\\n\",\n      \"#398: 97.49%\\n\",\n      \"#399: 97.50%\\n\",\n      \"#400: 97.51%\\n\",\n      \"#401: 97.51%\\n\",\n      \"#402: 97.52%\\n\",\n      \"#403: 97.28%\\n\",\n      \"#404: 97.28%\\n\",\n      \"#405: 97.29%\\n\",\n      \"#406: 97.30%\\n\",\n      \"#407: 97.30%\\n\",\n      \"#408: 97.31%\\n\",\n      \"#409: 97.32%\\n\",\n      \"#410: 97.32%\\n\",\n      \"#411: 97.33%\\n\",\n      \"#412: 97.34%\\n\",\n      \"#413: 97.34%\\n\",\n      \"#414: 97.35%\\n\",\n      \"#415: 97.36%\\n\",\n      \"#416: 97.36%\\n\",\n      \"#417: 97.37%\\n\",\n      \"#418: 97.37%\\n\",\n      \"#419: 97.38%\\n\",\n      \"#420: 97.39%\\n\",\n      \"#421: 97.39%\\n\",\n      \"#422: 97.40%\\n\",\n      \"#423: 97.41%\\n\",\n      \"#424: 97.41%\\n\",\n      \"#425: 97.42%\\n\",\n      \"#426: 97.42%\\n\",\n      \"#427: 97.43%\\n\",\n      \"#428: 97.44%\\n\",\n      \"#429: 97.44%\\n\",\n      \"#430: 97.45%\\n\",\n      \"#431: 97.45%\\n\",\n      \"#432: 97.46%\\n\",\n      \"#433: 97.47%\\n\",\n      \"#434: 97.47%\\n\",\n      \"#435: 97.25%\\n\",\n      \"#436: 97.25%\\n\",\n      \"#437: 97.26%\\n\",\n      \"#438: 97.27%\\n\",\n      \"#439: 97.27%\\n\",\n      \"#440: 97.28%\\n\",\n      \"#441: 97.29%\\n\",\n      \"#442: 97.29%\\n\",\n      \"#443: 97.30%\\n\",\n      \"#444: 97.30%\\n\",\n      \"#445: 97.09%\\n\",\n      \"#446: 97.09%\\n\",\n      \"#447: 97.10%\\n\",\n      \"#448: 97.10%\\n\",\n      \"#449: 97.11%\\n\",\n      \"#450: 97.12%\\n\",\n      \"#451: 97.12%\\n\",\n      \"#452: 97.13%\\n\",\n      \"#453: 97.14%\\n\",\n      \"#454: 97.14%\\n\",\n      \"#455: 97.15%\\n\",\n      \"#456: 97.16%\\n\",\n      \"#457: 97.16%\\n\",\n      \"#458: 97.17%\\n\",\n      \"#459: 97.17%\\n\",\n      \"#460: 97.18%\\n\",\n      \"#461: 97.19%\\n\",\n      \"#462: 97.19%\\n\",\n      \"#463: 97.20%\\n\",\n      \"#464: 96.99%\\n\",\n      \"#465: 97.00%\\n\",\n      \"#466: 97.00%\\n\",\n      \"#467: 97.01%\\n\",\n      \"#468: 97.01%\\n\",\n      \"#469: 97.02%\\n\",\n      \"#470: 97.03%\\n\",\n      \"#471: 97.03%\\n\",\n      \"#472: 97.04%\\n\",\n      \"#473: 97.05%\\n\",\n      \"#474: 97.05%\\n\",\n      \"#475: 97.06%\\n\",\n      \"#476: 97.06%\\n\",\n      \"#477: 97.07%\\n\",\n      \"#478: 97.08%\\n\",\n      \"#479: 97.08%\\n\",\n      \"#480: 97.09%\\n\",\n      \"#481: 97.10%\\n\",\n      \"#482: 97.10%\\n\",\n      \"#483: 97.11%\\n\",\n      \"#484: 97.11%\\n\",\n      \"#485: 97.12%\\n\",\n      \"#486: 97.13%\\n\",\n      \"#487: 97.13%\\n\",\n      \"#488: 97.14%\\n\",\n      \"#489: 97.14%\\n\",\n      \"#490: 97.15%\\n\",\n      \"#491: 97.15%\\n\",\n      \"#492: 97.16%\\n\",\n      \"#493: 97.17%\\n\",\n      \"#494: 97.17%\\n\",\n      \"#495: 96.98%\\n\",\n      \"#496: 96.98%\\n\",\n      \"#497: 96.99%\\n\",\n      \"#498: 96.99%\\n\",\n      \"#499: 97.00%\\n\",\n      \"#500: 97.01%\\n\",\n      \"#501: 97.01%\\n\",\n      \"#502: 97.02%\\n\",\n      \"#503: 97.02%\\n\",\n      \"#504: 97.03%\\n\",\n      \"#505: 97.04%\\n\",\n      \"#506: 97.04%\\n\",\n      \"#507: 97.05%\\n\",\n      \"#508: 97.05%\\n\",\n      \"#509: 97.06%\\n\",\n      \"#510: 97.06%\\n\",\n      \"#511: 97.07%\\n\",\n      \"#512: 97.08%\\n\",\n      \"#513: 97.08%\\n\",\n      \"#514: 97.09%\\n\",\n      \"#515: 97.09%\\n\",\n      \"#516: 97.10%\\n\",\n      \"#517: 97.10%\\n\",\n      \"#518: 97.11%\\n\",\n      \"#519: 97.12%\\n\",\n      \"#520: 97.12%\\n\",\n      \"#521: 97.13%\\n\",\n      \"#522: 97.13%\\n\",\n      \"#523: 97.14%\\n\",\n      \"#524: 97.14%\\n\",\n      \"#525: 97.15%\\n\",\n      \"#526: 97.15%\\n\",\n      \"#527: 97.16%\\n\",\n      \"#528: 97.16%\\n\",\n      \"#529: 97.17%\\n\",\n      \"#530: 97.18%\\n\",\n      \"#531: 97.18%\\n\",\n      \"#532: 97.19%\\n\",\n      \"#533: 97.19%\\n\",\n      \"#534: 97.20%\\n\",\n      \"#535: 97.20%\\n\",\n      \"#536: 97.21%\\n\",\n      \"#537: 97.21%\\n\",\n      \"#538: 97.22%\\n\",\n      \"#539: 97.22%\\n\",\n      \"#540: 97.23%\\n\",\n      \"#541: 97.23%\\n\",\n      \"#542: 97.05%\\n\",\n      \"#543: 97.06%\\n\",\n      \"#544: 97.06%\\n\",\n      \"#545: 97.07%\\n\",\n      \"#546: 97.07%\\n\",\n      \"#547: 97.08%\\n\",\n      \"#548: 97.09%\\n\",\n      \"#549: 97.09%\\n\",\n      \"#550: 97.10%\\n\",\n      \"#551: 97.10%\\n\",\n      \"#552: 97.11%\\n\",\n      \"#553: 97.11%\\n\",\n      \"#554: 97.12%\\n\",\n      \"#555: 97.12%\\n\",\n      \"#556: 97.13%\\n\",\n      \"#557: 97.13%\\n\",\n      \"#558: 97.14%\\n\",\n      \"#559: 97.14%\\n\",\n      \"#560: 97.15%\\n\",\n      \"#561: 97.15%\\n\",\n      \"#562: 97.16%\\n\",\n      \"#563: 97.16%\\n\",\n      \"#564: 97.17%\\n\",\n      \"#565: 97.17%\\n\",\n      \"#566: 97.18%\\n\",\n      \"#567: 97.18%\\n\",\n      \"#568: 97.19%\\n\",\n      \"#569: 97.19%\\n\",\n      \"#570: 97.20%\\n\",\n      \"#571: 97.20%\\n\",\n      \"#572: 97.21%\\n\",\n      \"#573: 97.21%\\n\",\n      \"#574: 97.22%\\n\",\n      \"#575: 97.22%\\n\",\n      \"#576: 97.23%\\n\",\n      \"#577: 97.23%\\n\",\n      \"#578: 97.24%\\n\",\n      \"#579: 97.24%\\n\",\n      \"#580: 97.25%\\n\",\n      \"#581: 97.25%\\n\",\n      \"#582: 97.08%\\n\",\n      \"#583: 97.09%\\n\",\n      \"#584: 97.09%\\n\",\n      \"#585: 97.10%\\n\",\n      \"#586: 97.10%\\n\",\n      \"#587: 97.11%\\n\",\n      \"#588: 97.11%\\n\",\n      \"#589: 97.12%\\n\",\n      \"#590: 97.12%\\n\",\n      \"#591: 97.13%\\n\",\n      \"#592: 97.13%\\n\",\n      \"#593: 97.14%\\n\",\n      \"#594: 97.14%\\n\",\n      \"#595: 97.15%\\n\",\n      \"#596: 97.15%\\n\",\n      \"#597: 97.16%\\n\",\n      \"#598: 97.16%\\n\",\n      \"#599: 97.17%\\n\",\n      \"#600: 97.17%\\n\",\n      \"#601: 97.18%\\n\",\n      \"#602: 97.18%\\n\",\n      \"#603: 97.19%\\n\",\n      \"#604: 97.19%\\n\",\n      \"#605: 97.03%\\n\",\n      \"#606: 97.03%\\n\",\n      \"#607: 97.04%\\n\",\n      \"#608: 97.04%\\n\",\n      \"#609: 97.05%\\n\",\n      \"#610: 97.05%\\n\",\n      \"#611: 97.06%\\n\",\n      \"#612: 97.06%\\n\",\n      \"#613: 97.07%\\n\",\n      \"#614: 97.07%\\n\",\n      \"#615: 97.08%\\n\",\n      \"#616: 97.08%\\n\",\n      \"#617: 97.09%\\n\",\n      \"#618: 97.09%\\n\",\n      \"#619: 97.10%\\n\",\n      \"#620: 97.10%\\n\",\n      \"#621: 97.11%\\n\",\n      \"#622: 97.11%\\n\",\n      \"#623: 97.12%\\n\",\n      \"#624: 97.12%\\n\",\n      \"#625: 97.12%\\n\",\n      \"#626: 97.13%\\n\",\n      \"#627: 97.13%\\n\",\n      \"#628: 97.14%\\n\",\n      \"#629: 97.14%\\n\",\n      \"#630: 97.15%\\n\",\n      \"#631: 97.15%\\n\",\n      \"#632: 97.16%\\n\",\n      \"#633: 97.16%\\n\",\n      \"#634: 97.17%\\n\",\n      \"#635: 97.17%\\n\",\n      \"#636: 97.17%\\n\",\n      \"#637: 97.18%\\n\",\n      \"#638: 97.18%\\n\",\n      \"#639: 97.19%\\n\",\n      \"#640: 97.19%\\n\",\n      \"#641: 97.20%\\n\",\n      \"#642: 97.20%\\n\",\n      \"#643: 97.20%\\n\",\n      \"#644: 97.21%\\n\",\n      \"#645: 97.21%\\n\",\n      \"#646: 97.22%\\n\",\n      \"#647: 97.22%\\n\",\n      \"#648: 97.23%\\n\",\n      \"#649: 97.23%\\n\",\n      \"#650: 97.24%\\n\",\n      \"#651: 97.24%\\n\",\n      \"#652: 97.24%\\n\",\n      \"#653: 97.25%\\n\",\n      \"#654: 97.25%\\n\",\n      \"#655: 97.26%\\n\",\n      \"#656: 97.26%\\n\",\n      \"#657: 97.26%\\n\",\n      \"#658: 97.27%\\n\",\n      \"#659: 97.27%\\n\",\n      \"#660: 97.28%\\n\",\n      \"#661: 97.28%\\n\",\n      \"#662: 97.29%\\n\",\n      \"#663: 97.29%\\n\",\n      \"#664: 97.29%\\n\",\n      \"#665: 97.30%\\n\",\n      \"#666: 97.30%\\n\",\n      \"#667: 97.31%\\n\",\n      \"#668: 97.31%\\n\",\n      \"#669: 97.31%\\n\",\n      \"#670: 97.32%\\n\",\n      \"#671: 97.32%\\n\",\n      \"#672: 97.33%\\n\",\n      \"#673: 97.33%\\n\",\n      \"#674: 97.33%\\n\",\n      \"#675: 97.34%\\n\",\n      \"#676: 97.34%\\n\",\n      \"#677: 97.35%\\n\",\n      \"#678: 97.35%\\n\",\n      \"#679: 97.35%\\n\",\n      \"#680: 97.36%\\n\",\n      \"#681: 97.36%\\n\",\n      \"#682: 97.36%\\n\",\n      \"#683: 97.37%\\n\",\n      \"#684: 97.23%\\n\",\n      \"#685: 97.23%\\n\",\n      \"#686: 97.23%\\n\",\n      \"#687: 97.24%\\n\",\n      \"#688: 97.24%\\n\",\n      \"#689: 97.10%\\n\",\n      \"#690: 97.11%\\n\",\n      \"#691: 97.11%\\n\",\n      \"#692: 97.11%\\n\",\n      \"#693: 97.12%\\n\",\n      \"#694: 97.12%\\n\",\n      \"#695: 97.13%\\n\",\n      \"#696: 97.13%\\n\",\n      \"#697: 97.13%\\n\",\n      \"#698: 97.14%\\n\",\n      \"#699: 97.14%\\n\",\n      \"#700: 97.15%\\n\",\n      \"#701: 97.15%\\n\",\n      \"#702: 97.16%\\n\",\n      \"#703: 97.16%\\n\",\n      \"#704: 97.16%\\n\",\n      \"#705: 97.17%\\n\",\n      \"#706: 97.17%\\n\",\n      \"#707: 97.18%\\n\",\n      \"#708: 97.18%\\n\",\n      \"#709: 97.18%\\n\",\n      \"#710: 97.19%\\n\",\n      \"#711: 97.19%\\n\",\n      \"#712: 97.19%\\n\",\n      \"#713: 97.20%\\n\",\n      \"#714: 97.20%\\n\",\n      \"#715: 97.21%\\n\",\n      \"#716: 97.21%\\n\",\n      \"#717: 97.08%\\n\",\n      \"#718: 97.08%\\n\",\n      \"#719: 97.08%\\n\",\n      \"#720: 97.09%\\n\",\n      \"#721: 97.09%\\n\",\n      \"#722: 97.10%\\n\",\n      \"#723: 97.10%\\n\",\n      \"#724: 97.10%\\n\",\n      \"#725: 97.11%\\n\",\n      \"#726: 96.97%\\n\",\n      \"#727: 96.98%\\n\",\n      \"#728: 96.98%\\n\",\n      \"#729: 96.99%\\n\",\n      \"#730: 96.99%\\n\",\n      \"#731: 96.99%\\n\",\n      \"#732: 97.00%\\n\",\n      \"#733: 97.00%\\n\",\n      \"#734: 97.01%\\n\",\n      \"#735: 97.01%\\n\",\n      \"#736: 97.01%\\n\",\n      \"#737: 97.02%\\n\",\n      \"#738: 97.02%\\n\",\n      \"#739: 97.03%\\n\",\n      \"#740: 97.03%\\n\",\n      \"#741: 97.04%\\n\",\n      \"#742: 97.04%\\n\",\n      \"#743: 97.04%\\n\",\n      \"#744: 97.05%\\n\",\n      \"#745: 97.05%\\n\",\n      \"#746: 97.05%\\n\",\n      \"#747: 97.06%\\n\",\n      \"#748: 97.06%\\n\",\n      \"#749: 97.07%\\n\",\n      \"#750: 97.07%\\n\",\n      \"#751: 97.07%\\n\",\n      \"#752: 97.08%\\n\",\n      \"#753: 97.08%\\n\",\n      \"#754: 97.09%\\n\",\n      \"#755: 97.09%\\n\",\n      \"#756: 97.09%\\n\",\n      \"#757: 97.10%\\n\",\n      \"#758: 97.10%\\n\",\n      \"#759: 97.11%\\n\",\n      \"#760: 97.11%\\n\",\n      \"#761: 97.11%\\n\",\n      \"#762: 97.12%\\n\",\n      \"#763: 97.12%\\n\",\n      \"#764: 97.12%\\n\",\n      \"#765: 97.13%\\n\",\n      \"#766: 97.13%\\n\",\n      \"#767: 97.14%\\n\",\n      \"#768: 97.14%\\n\",\n      \"#769: 97.14%\\n\",\n      \"#770: 97.15%\\n\",\n      \"#771: 97.15%\\n\",\n      \"#772: 97.15%\\n\",\n      \"#773: 97.16%\\n\",\n      \"#774: 97.16%\\n\",\n      \"#775: 97.16%\\n\",\n      \"#776: 97.17%\\n\",\n      \"#777: 97.17%\\n\",\n      \"#778: 97.18%\\n\",\n      \"#779: 97.18%\\n\",\n      \"#780: 97.18%\\n\",\n      \"#781: 97.19%\\n\",\n      \"#782: 97.19%\\n\",\n      \"#783: 97.19%\\n\",\n      \"#784: 97.20%\\n\",\n      \"#785: 97.20%\\n\",\n      \"#786: 97.20%\\n\",\n      \"#787: 97.21%\\n\",\n      \"#788: 97.21%\\n\",\n      \"#789: 97.22%\\n\",\n      \"#790: 97.22%\\n\",\n      \"#791: 97.22%\\n\",\n      \"#792: 97.23%\\n\",\n      \"#793: 97.23%\\n\",\n      \"#794: 97.23%\\n\",\n      \"#795: 97.24%\\n\",\n      \"#796: 97.24%\\n\",\n      \"#797: 97.24%\\n\",\n      \"#798: 97.25%\\n\",\n      \"#799: 97.25%\\n\",\n      \"#800: 97.25%\\n\",\n      \"#801: 97.26%\\n\",\n      \"#802: 97.26%\\n\",\n      \"#803: 97.26%\\n\",\n      \"#804: 97.27%\\n\",\n      \"#805: 97.27%\\n\",\n      \"#806: 97.27%\\n\",\n      \"#807: 97.28%\\n\",\n      \"#808: 97.28%\\n\",\n      \"#809: 97.28%\\n\",\n      \"#810: 97.29%\\n\",\n      \"#811: 97.29%\\n\",\n      \"#812: 97.29%\\n\",\n      \"#813: 97.17%\\n\",\n      \"#814: 97.18%\\n\",\n      \"#815: 97.18%\\n\",\n      \"#816: 97.18%\\n\",\n      \"#817: 97.19%\\n\",\n      \"#818: 97.19%\\n\",\n      \"#819: 97.20%\\n\",\n      \"#820: 97.20%\\n\",\n      \"#821: 97.20%\\n\",\n      \"#822: 97.21%\\n\",\n      \"#823: 97.21%\\n\",\n      \"#824: 97.21%\\n\",\n      \"#825: 97.22%\\n\",\n      \"#826: 97.22%\\n\",\n      \"#827: 97.22%\\n\",\n      \"#828: 97.23%\\n\",\n      \"#829: 97.23%\\n\",\n      \"#830: 97.23%\\n\",\n      \"#831: 97.24%\\n\",\n      \"#832: 97.24%\\n\",\n      \"#833: 97.24%\\n\",\n      \"#834: 97.25%\\n\",\n      \"#835: 97.25%\\n\",\n      \"#836: 97.25%\\n\",\n      \"#837: 97.26%\\n\",\n      \"#838: 97.26%\\n\",\n      \"#839: 97.26%\\n\",\n      \"#840: 97.27%\\n\",\n      \"#841: 97.27%\\n\",\n      \"#842: 97.27%\\n\",\n      \"#843: 97.27%\\n\",\n      \"#844: 97.28%\\n\",\n      \"#845: 97.28%\\n\",\n      \"#846: 97.28%\\n\",\n      \"#847: 97.29%\\n\",\n      \"#848: 97.29%\\n\",\n      \"#849: 97.29%\\n\",\n      \"#850: 97.30%\\n\",\n      \"#851: 97.30%\\n\",\n      \"#852: 97.30%\\n\",\n      \"#853: 97.31%\\n\",\n      \"#854: 97.31%\\n\",\n      \"#855: 97.31%\\n\",\n      \"#856: 97.32%\\n\",\n      \"#857: 97.32%\\n\",\n      \"#858: 97.32%\\n\",\n      \"#859: 97.33%\\n\",\n      \"#860: 97.33%\\n\",\n      \"#861: 97.33%\\n\",\n      \"#862: 97.33%\\n\",\n      \"#863: 97.34%\\n\",\n      \"#864: 97.34%\\n\",\n      \"#865: 97.34%\\n\",\n      \"#866: 97.35%\\n\",\n      \"#867: 97.35%\\n\",\n      \"#868: 97.35%\\n\",\n      \"#869: 97.36%\\n\",\n      \"#870: 97.36%\\n\",\n      \"#871: 97.36%\\n\",\n      \"#872: 97.37%\\n\",\n      \"#873: 97.37%\\n\",\n      \"#874: 97.37%\\n\",\n      \"#875: 97.37%\\n\",\n      \"#876: 97.38%\\n\",\n      \"#877: 97.38%\\n\",\n      \"#878: 97.38%\\n\",\n      \"#879: 97.39%\\n\",\n      \"#880: 97.39%\\n\",\n      \"#881: 97.39%\\n\",\n      \"#882: 97.40%\\n\",\n      \"#883: 97.40%\\n\",\n      \"#884: 97.40%\\n\",\n      \"#885: 97.40%\\n\",\n      \"#886: 97.41%\\n\",\n      \"#887: 97.41%\\n\",\n      \"#888: 97.41%\\n\",\n      \"#889: 97.42%\\n\",\n      \"#890: 97.42%\\n\",\n      \"#891: 97.42%\\n\",\n      \"#892: 97.42%\\n\",\n      \"#893: 97.43%\\n\",\n      \"#894: 97.43%\\n\",\n      \"#895: 97.43%\\n\",\n      \"#896: 97.44%\\n\",\n      \"#897: 97.44%\\n\",\n      \"#898: 97.33%\\n\",\n      \"#899: 97.33%\\n\",\n      \"#900: 97.34%\\n\",\n      \"#901: 97.34%\\n\",\n      \"#902: 97.34%\\n\",\n      \"#903: 97.35%\\n\",\n      \"#904: 97.35%\\n\",\n      \"#905: 97.35%\\n\",\n      \"#906: 97.35%\\n\",\n      \"#907: 97.36%\\n\",\n      \"#908: 97.36%\\n\",\n      \"#909: 97.36%\\n\",\n      \"#910: 97.37%\\n\",\n      \"#911: 97.37%\\n\",\n      \"#912: 97.37%\\n\",\n      \"#913: 97.37%\\n\",\n      \"#914: 97.38%\\n\",\n      \"#915: 97.38%\\n\",\n      \"#916: 97.38%\\n\",\n      \"#917: 97.39%\\n\",\n      \"#918: 97.39%\\n\",\n      \"#919: 97.39%\\n\",\n      \"#920: 97.39%\\n\",\n      \"#921: 97.40%\\n\",\n      \"#922: 97.40%\\n\",\n      \"#923: 97.40%\\n\",\n      \"#924: 97.41%\\n\",\n      \"#925: 97.41%\\n\",\n      \"#926: 97.41%\\n\",\n      \"#927: 97.41%\\n\",\n      \"#928: 97.42%\\n\",\n      \"#929: 97.42%\\n\",\n      \"#930: 97.42%\\n\",\n      \"#931: 97.42%\\n\",\n      \"#932: 97.43%\\n\",\n      \"#933: 97.43%\\n\",\n      \"#934: 97.43%\\n\",\n      \"#935: 97.44%\\n\",\n      \"#936: 97.44%\\n\",\n      \"#937: 97.44%\\n\",\n      \"#938: 97.44%\\n\",\n      \"#939: 97.45%\\n\",\n      \"#940: 97.45%\\n\",\n      \"#941: 97.45%\\n\",\n      \"#942: 97.45%\\n\",\n      \"#943: 97.46%\\n\",\n      \"#944: 97.46%\\n\",\n      \"#945: 97.46%\\n\",\n      \"#946: 97.47%\\n\",\n      \"#947: 97.36%\\n\",\n      \"#948: 97.37%\\n\",\n      \"#949: 97.37%\\n\",\n      \"#950: 97.37%\\n\",\n      \"#951: 97.37%\\n\",\n      \"#952: 97.38%\\n\",\n      \"#953: 97.38%\\n\",\n      \"#954: 97.38%\\n\",\n      \"#955: 97.38%\\n\",\n      \"#956: 97.28%\\n\",\n      \"#957: 97.29%\\n\",\n      \"#958: 97.29%\\n\",\n      \"#959: 97.29%\\n\",\n      \"#960: 97.29%\\n\",\n      \"#961: 97.30%\\n\",\n      \"#962: 97.30%\\n\",\n      \"#963: 97.30%\\n\",\n      \"#964: 97.31%\\n\",\n      \"#965: 97.20%\\n\",\n      \"#966: 97.21%\\n\",\n      \"#967: 97.21%\\n\",\n      \"#968: 97.21%\\n\",\n      \"#969: 97.22%\\n\",\n      \"#970: 97.22%\\n\",\n      \"#971: 97.22%\\n\",\n      \"#972: 97.23%\\n\",\n      \"#973: 97.23%\\n\",\n      \"#974: 97.23%\\n\",\n      \"#975: 97.23%\\n\",\n      \"#976: 97.24%\\n\",\n      \"#977: 97.24%\\n\",\n      \"#978: 97.24%\\n\",\n      \"#979: 97.24%\\n\",\n      \"#980: 97.25%\\n\",\n      \"#981: 97.25%\\n\",\n      \"#982: 97.25%\\n\",\n      \"#983: 97.26%\\n\",\n      \"#984: 97.26%\\n\",\n      \"#985: 97.26%\\n\",\n      \"#986: 97.26%\\n\",\n      \"#987: 97.27%\\n\",\n      \"#988: 97.27%\\n\",\n      \"#989: 97.27%\\n\",\n      \"#990: 97.28%\\n\",\n      \"#991: 97.28%\\n\",\n      \"#992: 97.28%\\n\",\n      \"#993: 97.28%\\n\",\n      \"#994: 97.29%\\n\",\n      \"#995: 97.29%\\n\",\n      \"#996: 97.29%\\n\",\n      \"#997: 97.29%\\n\",\n      \"#998: 97.30%\\n\",\n      \"#999: 97.30%\\n\",\n      \"#1000: 97.30%\\n\",\n      \"#1001: 97.31%\\n\",\n      \"#1002: 97.31%\\n\",\n      \"#1003: 97.31%\\n\",\n      \"#1004: 97.31%\\n\",\n      \"#1005: 97.32%\\n\",\n      \"#1006: 97.32%\\n\",\n      \"#1007: 97.32%\\n\",\n      \"#1008: 97.32%\\n\",\n      \"#1009: 97.33%\\n\",\n      \"#1010: 97.33%\\n\",\n      \"#1011: 97.33%\\n\",\n      \"#1012: 97.33%\\n\",\n      \"#1013: 97.34%\\n\",\n      \"#1014: 97.24%\\n\",\n      \"#1015: 97.24%\\n\",\n      \"#1016: 97.25%\\n\",\n      \"#1017: 97.25%\\n\",\n      \"#1018: 97.25%\\n\",\n      \"#1019: 97.25%\\n\",\n      \"#1020: 97.26%\\n\",\n      \"#1021: 97.26%\\n\",\n      \"#1022: 97.26%\\n\",\n      \"#1023: 97.27%\\n\",\n      \"#1024: 97.27%\\n\",\n      \"#1025: 97.27%\\n\",\n      \"#1026: 97.27%\\n\",\n      \"#1027: 97.28%\\n\",\n      \"#1028: 97.28%\\n\",\n      \"#1029: 97.28%\\n\",\n      \"#1030: 97.28%\\n\",\n      \"#1031: 97.29%\\n\",\n      \"#1032: 97.29%\\n\",\n      \"#1033: 97.29%\\n\",\n      \"#1034: 97.29%\\n\",\n      \"#1035: 97.30%\\n\",\n      \"#1036: 97.30%\\n\",\n      \"#1037: 97.30%\\n\",\n      \"#1038: 97.31%\\n\",\n      \"#1039: 97.21%\\n\",\n      \"#1040: 97.21%\\n\",\n      \"#1041: 97.22%\\n\",\n      \"#1042: 97.22%\\n\",\n      \"#1043: 97.22%\\n\",\n      \"#1044: 97.22%\\n\",\n      \"#1045: 97.23%\\n\",\n      \"#1046: 97.23%\\n\",\n      \"#1047: 97.23%\\n\",\n      \"#1048: 97.24%\\n\",\n      \"#1049: 97.24%\\n\",\n      \"#1050: 97.24%\\n\",\n      \"#1051: 97.24%\\n\",\n      \"#1052: 97.25%\\n\",\n      \"#1053: 97.25%\\n\",\n      \"#1054: 97.25%\\n\",\n      \"#1055: 97.25%\\n\",\n      \"#1056: 97.26%\\n\",\n      \"#1057: 97.26%\\n\",\n      \"#1058: 97.26%\\n\",\n      \"#1059: 97.26%\\n\",\n      \"#1060: 97.27%\\n\",\n      \"#1061: 97.27%\\n\",\n      \"#1062: 97.18%\\n\",\n      \"#1063: 97.18%\\n\",\n      \"#1064: 97.18%\\n\",\n      \"#1065: 97.19%\\n\",\n      \"#1066: 97.19%\\n\",\n      \"#1067: 97.19%\\n\",\n      \"#1068: 97.10%\\n\",\n      \"#1069: 97.10%\\n\",\n      \"#1070: 97.11%\\n\",\n      \"#1071: 97.11%\\n\",\n      \"#1072: 97.11%\\n\",\n      \"#1073: 97.11%\\n\",\n      \"#1074: 97.12%\\n\",\n      \"#1075: 97.12%\\n\",\n      \"#1076: 97.12%\\n\",\n      \"#1077: 97.12%\\n\",\n      \"#1078: 97.13%\\n\",\n      \"#1079: 97.13%\\n\",\n      \"#1080: 97.13%\\n\",\n      \"#1081: 97.13%\\n\",\n      \"#1082: 97.14%\\n\",\n      \"#1083: 97.14%\\n\",\n      \"#1084: 97.14%\\n\",\n      \"#1085: 97.15%\\n\",\n      \"#1086: 97.15%\\n\",\n      \"#1087: 97.15%\\n\",\n      \"#1088: 97.15%\\n\",\n      \"#1089: 97.16%\\n\",\n      \"#1090: 97.16%\\n\",\n      \"#1091: 97.16%\\n\",\n      \"#1092: 97.16%\\n\",\n      \"#1093: 97.17%\\n\",\n      \"#1094: 97.17%\\n\",\n      \"#1095: 97.17%\\n\",\n      \"#1096: 97.17%\\n\",\n      \"#1097: 97.18%\\n\",\n      \"#1098: 97.18%\\n\",\n      \"#1099: 97.18%\\n\",\n      \"#1100: 97.18%\\n\",\n      \"#1101: 97.19%\\n\",\n      \"#1102: 97.19%\\n\",\n      \"#1103: 97.19%\\n\",\n      \"#1104: 97.19%\\n\",\n      \"#1105: 97.20%\\n\",\n      \"#1106: 97.20%\\n\",\n      \"#1107: 97.11%\\n\",\n      \"#1108: 97.11%\\n\",\n      \"#1109: 97.12%\\n\",\n      \"#1110: 97.12%\\n\",\n      \"#1111: 97.12%\\n\",\n      \"#1112: 97.04%\\n\",\n      \"#1113: 97.04%\\n\",\n      \"#1114: 96.95%\\n\",\n      \"#1115: 96.95%\\n\",\n      \"#1116: 96.96%\\n\",\n      \"#1117: 96.96%\\n\",\n      \"#1118: 96.96%\\n\",\n      \"#1119: 96.96%\\n\",\n      \"#1120: 96.97%\\n\",\n      \"#1121: 96.97%\\n\",\n      \"#1122: 96.97%\\n\",\n      \"#1123: 96.98%\\n\",\n      \"#1124: 96.98%\\n\",\n      \"#1125: 96.89%\\n\",\n      \"#1126: 96.89%\\n\",\n      \"#1127: 96.90%\\n\",\n      \"#1128: 96.90%\\n\",\n      \"#1129: 96.90%\\n\",\n      \"#1130: 96.91%\\n\",\n      \"#1131: 96.91%\\n\",\n      \"#1132: 96.91%\\n\",\n      \"#1133: 96.91%\\n\",\n      \"#1134: 96.92%\\n\",\n      \"#1135: 96.92%\\n\",\n      \"#1136: 96.92%\\n\",\n      \"#1137: 96.92%\\n\",\n      \"#1138: 96.93%\\n\",\n      \"#1139: 96.93%\\n\",\n      \"#1140: 96.93%\\n\",\n      \"#1141: 96.94%\\n\",\n      \"#1142: 96.94%\\n\",\n      \"#1143: 96.85%\\n\",\n      \"#1144: 96.86%\\n\",\n      \"#1145: 96.86%\\n\",\n      \"#1146: 96.86%\\n\",\n      \"#1147: 96.86%\\n\",\n      \"#1148: 96.87%\\n\",\n      \"#1149: 96.87%\\n\",\n      \"#1150: 96.87%\\n\",\n      \"#1151: 96.88%\\n\",\n      \"#1152: 96.88%\\n\",\n      \"#1153: 96.88%\\n\",\n      \"#1154: 96.88%\\n\",\n      \"#1155: 96.89%\\n\",\n      \"#1156: 96.89%\\n\",\n      \"#1157: 96.89%\\n\",\n      \"#1158: 96.89%\\n\",\n      \"#1159: 96.90%\\n\",\n      \"#1160: 96.90%\\n\",\n      \"#1161: 96.90%\\n\",\n      \"#1162: 96.90%\\n\",\n      \"#1163: 96.91%\\n\",\n      \"#1164: 96.91%\\n\",\n      \"#1165: 96.91%\\n\",\n      \"#1166: 96.92%\\n\",\n      \"#1167: 96.92%\\n\",\n      \"#1168: 96.92%\\n\",\n      \"#1169: 96.92%\\n\",\n      \"#1170: 96.93%\\n\",\n      \"#1171: 96.93%\\n\",\n      \"#1172: 96.93%\\n\",\n      \"#1173: 96.93%\\n\",\n      \"#1174: 96.94%\\n\",\n      \"#1175: 96.94%\\n\",\n      \"#1176: 96.94%\\n\",\n      \"#1177: 96.94%\\n\",\n      \"#1178: 96.95%\\n\",\n      \"#1179: 96.95%\\n\",\n      \"#1180: 96.95%\\n\",\n      \"#1181: 96.95%\\n\",\n      \"#1182: 96.87%\\n\",\n      \"#1183: 96.88%\\n\",\n      \"#1184: 96.88%\\n\",\n      \"#1185: 96.88%\\n\",\n      \"#1186: 96.88%\\n\",\n      \"#1187: 96.89%\\n\",\n      \"#1188: 96.89%\\n\",\n      \"#1189: 96.89%\\n\",\n      \"#1190: 96.89%\\n\",\n      \"#1191: 96.81%\\n\",\n      \"#1192: 96.81%\\n\",\n      \"#1193: 96.82%\\n\",\n      \"#1194: 96.82%\\n\",\n      \"#1195: 96.82%\\n\",\n      \"#1196: 96.83%\\n\",\n      \"#1197: 96.83%\\n\",\n      \"#1198: 96.83%\\n\",\n      \"#1199: 96.83%\\n\",\n      \"#1200: 96.84%\\n\",\n      \"#1201: 96.84%\\n\",\n      \"#1202: 96.84%\\n\",\n      \"#1203: 96.84%\\n\",\n      \"#1204: 96.85%\\n\",\n      \"#1205: 96.85%\\n\",\n      \"#1206: 96.85%\\n\",\n      \"#1207: 96.85%\\n\",\n      \"#1208: 96.86%\\n\",\n      \"#1209: 96.86%\\n\",\n      \"#1210: 96.86%\\n\",\n      \"#1211: 96.86%\\n\",\n      \"#1212: 96.87%\\n\",\n      \"#1213: 96.87%\\n\",\n      \"#1214: 96.87%\\n\",\n      \"#1215: 96.88%\\n\",\n      \"#1216: 96.88%\\n\",\n      \"#1217: 96.88%\\n\",\n      \"#1218: 96.88%\\n\",\n      \"#1219: 96.89%\\n\",\n      \"#1220: 96.89%\\n\",\n      \"#1221: 96.89%\\n\",\n      \"#1222: 96.89%\\n\",\n      \"#1223: 96.90%\\n\",\n      \"#1224: 96.90%\\n\",\n      \"#1225: 96.90%\\n\",\n      \"#1226: 96.82%\\n\",\n      \"#1227: 96.82%\\n\",\n      \"#1228: 96.83%\\n\",\n      \"#1229: 96.83%\\n\",\n      \"#1230: 96.83%\\n\",\n      \"#1231: 96.83%\\n\",\n      \"#1232: 96.84%\\n\",\n      \"#1233: 96.84%\\n\",\n      \"#1234: 96.84%\\n\",\n      \"#1235: 96.84%\\n\",\n      \"#1236: 96.85%\\n\",\n      \"#1237: 96.85%\\n\",\n      \"#1238: 96.85%\\n\",\n      \"#1239: 96.85%\\n\",\n      \"#1240: 96.86%\\n\",\n      \"#1241: 96.86%\\n\",\n      \"#1242: 96.86%\\n\",\n      \"#1243: 96.86%\\n\",\n      \"#1244: 96.87%\\n\",\n      \"#1245: 96.87%\\n\",\n      \"#1246: 96.87%\\n\",\n      \"#1247: 96.79%\\n\",\n      \"#1248: 96.80%\\n\",\n      \"#1249: 96.80%\\n\",\n      \"#1250: 96.80%\\n\",\n      \"#1251: 96.81%\\n\",\n      \"#1252: 96.81%\\n\",\n      \"#1253: 96.81%\\n\",\n      \"#1254: 96.81%\\n\",\n      \"#1255: 96.82%\\n\",\n      \"#1256: 96.82%\\n\",\n      \"#1257: 96.82%\\n\",\n      \"#1258: 96.82%\\n\",\n      \"#1259: 96.83%\\n\",\n      \"#1260: 96.75%\\n\",\n      \"#1261: 96.75%\\n\",\n      \"#1262: 96.75%\\n\",\n      \"#1263: 96.76%\\n\",\n      \"#1264: 96.76%\\n\",\n      \"#1265: 96.76%\\n\",\n      \"#1266: 96.76%\\n\",\n      \"#1267: 96.77%\\n\",\n      \"#1268: 96.77%\\n\",\n      \"#1269: 96.77%\\n\",\n      \"#1270: 96.77%\\n\",\n      \"#1271: 96.78%\\n\",\n      \"#1272: 96.78%\\n\",\n      \"#1273: 96.78%\\n\",\n      \"#1274: 96.78%\\n\",\n      \"#1275: 96.79%\\n\",\n      \"#1276: 96.79%\\n\",\n      \"#1277: 96.79%\\n\",\n      \"#1278: 96.79%\\n\",\n      \"#1279: 96.80%\\n\",\n      \"#1280: 96.80%\\n\",\n      \"#1281: 96.80%\\n\",\n      \"#1282: 96.80%\\n\",\n      \"#1283: 96.81%\\n\",\n      \"#1284: 96.81%\\n\",\n      \"#1285: 96.81%\\n\",\n      \"#1286: 96.81%\\n\",\n      \"#1287: 96.82%\\n\",\n      \"#1288: 96.82%\\n\",\n      \"#1289: 96.82%\\n\",\n      \"#1290: 96.75%\\n\",\n      \"#1291: 96.75%\\n\",\n      \"#1292: 96.75%\\n\",\n      \"#1293: 96.75%\\n\",\n      \"#1294: 96.76%\\n\",\n      \"#1295: 96.76%\\n\",\n      \"#1296: 96.76%\\n\",\n      \"#1297: 96.76%\\n\",\n      \"#1298: 96.77%\\n\",\n      \"#1299: 96.69%\\n\",\n      \"#1300: 96.69%\\n\",\n      \"#1301: 96.70%\\n\",\n      \"#1302: 96.70%\\n\",\n      \"#1303: 96.70%\\n\",\n      \"#1304: 96.70%\\n\",\n      \"#1305: 96.71%\\n\",\n      \"#1306: 96.71%\\n\",\n      \"#1307: 96.71%\\n\",\n      \"#1308: 96.72%\\n\",\n      \"#1309: 96.72%\\n\",\n      \"#1310: 96.72%\\n\",\n      \"#1311: 96.72%\\n\",\n      \"#1312: 96.73%\\n\",\n      \"#1313: 96.73%\\n\",\n      \"#1314: 96.73%\\n\",\n      \"#1315: 96.73%\\n\",\n      \"#1316: 96.74%\\n\",\n      \"#1317: 96.74%\\n\",\n      \"#1318: 96.74%\\n\",\n      \"#1319: 96.67%\\n\",\n      \"#1320: 96.67%\\n\",\n      \"#1321: 96.67%\\n\",\n      \"#1322: 96.67%\\n\",\n      \"#1323: 96.68%\\n\",\n      \"#1324: 96.68%\\n\",\n      \"#1325: 96.68%\\n\",\n      \"#1326: 96.68%\\n\",\n      \"#1327: 96.69%\\n\",\n      \"#1328: 96.69%\\n\",\n      \"#1329: 96.69%\\n\",\n      \"#1330: 96.69%\\n\",\n      \"#1331: 96.70%\\n\",\n      \"#1332: 96.70%\\n\",\n      \"#1333: 96.70%\\n\",\n      \"#1334: 96.70%\\n\",\n      \"#1335: 96.71%\\n\",\n      \"#1336: 96.71%\\n\",\n      \"#1337: 96.71%\\n\",\n      \"#1338: 96.71%\\n\",\n      \"#1339: 96.72%\\n\",\n      \"#1340: 96.72%\\n\",\n      \"#1341: 96.72%\\n\",\n      \"#1342: 96.72%\\n\",\n      \"#1343: 96.73%\\n\",\n      \"#1344: 96.73%\\n\",\n      \"#1345: 96.73%\\n\",\n      \"#1346: 96.73%\\n\",\n      \"#1347: 96.74%\\n\",\n      \"#1348: 96.74%\\n\",\n      \"#1349: 96.74%\\n\",\n      \"#1350: 96.74%\\n\",\n      \"#1351: 96.75%\\n\",\n      \"#1352: 96.75%\\n\",\n      \"#1353: 96.75%\\n\",\n      \"#1354: 96.75%\\n\",\n      \"#1355: 96.76%\\n\",\n      \"#1356: 96.76%\\n\",\n      \"#1357: 96.76%\\n\",\n      \"#1358: 96.76%\\n\",\n      \"#1359: 96.76%\\n\",\n      \"#1360: 96.77%\\n\",\n      \"#1361: 96.77%\\n\",\n      \"#1362: 96.77%\\n\",\n      \"#1363: 96.77%\\n\",\n      \"#1364: 96.70%\\n\",\n      \"#1365: 96.71%\\n\",\n      \"#1366: 96.71%\\n\",\n      \"#1367: 96.71%\\n\",\n      \"#1368: 96.71%\\n\",\n      \"#1369: 96.72%\\n\",\n      \"#1370: 96.72%\\n\",\n      \"#1371: 96.72%\\n\",\n      \"#1372: 96.72%\\n\",\n      \"#1373: 96.72%\\n\",\n      \"#1374: 96.73%\\n\",\n      \"#1375: 96.73%\\n\",\n      \"#1376: 96.73%\\n\",\n      \"#1377: 96.73%\\n\",\n      \"#1378: 96.74%\\n\",\n      \"#1379: 96.74%\\n\",\n      \"#1380: 96.74%\\n\",\n      \"#1381: 96.74%\\n\",\n      \"#1382: 96.75%\\n\",\n      \"#1383: 96.68%\\n\",\n      \"#1384: 96.68%\\n\",\n      \"#1385: 96.68%\\n\",\n      \"#1386: 96.68%\\n\",\n      \"#1387: 96.69%\\n\",\n      \"#1388: 96.69%\\n\",\n      \"#1389: 96.69%\\n\",\n      \"#1390: 96.69%\\n\",\n      \"#1391: 96.70%\\n\",\n      \"#1392: 96.70%\\n\",\n      \"#1393: 96.70%\\n\",\n      \"#1394: 96.70%\\n\",\n      \"#1395: 96.70%\\n\",\n      \"#1396: 96.71%\\n\",\n      \"#1397: 96.71%\\n\",\n      \"#1398: 96.71%\\n\",\n      \"#1399: 96.71%\\n\",\n      \"#1400: 96.72%\\n\",\n      \"#1401: 96.72%\\n\",\n      \"#1402: 96.72%\\n\",\n      \"#1403: 96.72%\\n\",\n      \"#1404: 96.73%\\n\",\n      \"#1405: 96.73%\\n\",\n      \"#1406: 96.73%\\n\",\n      \"#1407: 96.73%\\n\",\n      \"#1408: 96.74%\\n\",\n      \"#1409: 96.74%\\n\",\n      \"#1410: 96.74%\\n\",\n      \"#1411: 96.74%\\n\",\n      \"#1412: 96.74%\\n\",\n      \"#1413: 96.75%\\n\",\n      \"#1414: 96.75%\\n\",\n      \"#1415: 96.68%\\n\",\n      \"#1416: 96.68%\\n\",\n      \"#1417: 96.69%\\n\",\n      \"#1418: 96.69%\\n\",\n      \"#1419: 96.69%\\n\",\n      \"#1420: 96.69%\\n\",\n      \"#1421: 96.69%\\n\",\n      \"#1422: 96.70%\\n\",\n      \"#1423: 96.70%\\n\",\n      \"#1424: 96.70%\\n\",\n      \"#1425: 96.70%\\n\",\n      \"#1426: 96.71%\\n\",\n      \"#1427: 96.71%\\n\",\n      \"#1428: 96.71%\\n\",\n      \"#1429: 96.71%\\n\",\n      \"#1430: 96.72%\\n\",\n      \"#1431: 96.72%\\n\",\n      \"#1432: 96.72%\\n\",\n      \"#1433: 96.72%\\n\",\n      \"#1434: 96.72%\\n\",\n      \"#1435: 96.73%\\n\",\n      \"#1436: 96.73%\\n\",\n      \"#1437: 96.73%\\n\",\n      \"#1438: 96.73%\\n\",\n      \"#1439: 96.74%\\n\",\n      \"#1440: 96.67%\\n\",\n      \"#1441: 96.67%\\n\",\n      \"#1442: 96.67%\\n\",\n      \"#1443: 96.68%\\n\",\n      \"#1444: 96.68%\\n\",\n      \"#1445: 96.68%\\n\",\n      \"#1446: 96.68%\\n\",\n      \"#1447: 96.69%\\n\",\n      \"#1448: 96.69%\\n\",\n      \"#1449: 96.69%\\n\",\n      \"#1450: 96.69%\\n\",\n      \"#1451: 96.69%\\n\",\n      \"#1452: 96.70%\\n\",\n      \"#1453: 96.70%\\n\",\n      \"#1454: 96.70%\\n\",\n      \"#1455: 96.70%\\n\",\n      \"#1456: 96.71%\\n\",\n      \"#1457: 96.71%\\n\",\n      \"#1458: 96.71%\\n\",\n      \"#1459: 96.71%\\n\",\n      \"#1460: 96.71%\\n\",\n      \"#1461: 96.72%\\n\",\n      \"#1462: 96.72%\\n\",\n      \"#1463: 96.72%\\n\",\n      \"#1464: 96.72%\\n\",\n      \"#1465: 96.73%\\n\",\n      \"#1466: 96.73%\\n\",\n      \"#1467: 96.73%\\n\",\n      \"#1468: 96.73%\\n\",\n      \"#1469: 96.73%\\n\",\n      \"#1470: 96.74%\\n\",\n      \"#1471: 96.74%\\n\",\n      \"#1472: 96.74%\\n\",\n      \"#1473: 96.74%\\n\",\n      \"#1474: 96.75%\\n\",\n      \"#1475: 96.75%\\n\",\n      \"#1476: 96.75%\\n\",\n      \"#1477: 96.75%\\n\",\n      \"#1478: 96.75%\\n\",\n      \"#1479: 96.76%\\n\",\n      \"#1480: 96.76%\\n\",\n      \"#1481: 96.76%\\n\",\n      \"#1482: 96.76%\\n\",\n      \"#1483: 96.77%\\n\",\n      \"#1484: 96.77%\\n\",\n      \"#1485: 96.77%\\n\",\n      \"#1486: 96.77%\\n\",\n      \"#1487: 96.77%\\n\",\n      \"#1488: 96.78%\\n\",\n      \"#1489: 96.78%\\n\",\n      \"#1490: 96.78%\\n\",\n      \"#1491: 96.78%\\n\",\n      \"#1492: 96.78%\\n\",\n      \"#1493: 96.79%\\n\",\n      \"#1494: 96.79%\\n\",\n      \"#1495: 96.79%\\n\",\n      \"#1496: 96.79%\\n\",\n      \"#1497: 96.80%\\n\",\n      \"#1498: 96.80%\\n\",\n      \"#1499: 96.80%\\n\",\n      \"#1500: 96.80%\\n\",\n      \"#1501: 96.80%\\n\",\n      \"#1502: 96.81%\\n\",\n      \"#1503: 96.81%\\n\",\n      \"#1504: 96.81%\\n\",\n      \"#1505: 96.81%\\n\",\n      \"#1506: 96.81%\\n\",\n      \"#1507: 96.82%\\n\",\n      \"#1508: 96.82%\\n\",\n      \"#1509: 96.82%\\n\",\n      \"#1510: 96.82%\\n\",\n      \"#1511: 96.83%\\n\",\n      \"#1512: 96.83%\\n\",\n      \"#1513: 96.83%\\n\",\n      \"#1514: 96.83%\\n\",\n      \"#1515: 96.83%\\n\",\n      \"#1516: 96.84%\\n\",\n      \"#1517: 96.84%\\n\",\n      \"#1518: 96.84%\\n\",\n      \"#1519: 96.84%\\n\",\n      \"#1520: 96.84%\\n\",\n      \"#1521: 96.85%\\n\",\n      \"#1522: 96.85%\\n\",\n      \"#1523: 96.85%\\n\",\n      \"#1524: 96.85%\\n\",\n      \"#1525: 96.85%\\n\",\n      \"#1526: 96.86%\\n\",\n      \"#1527: 96.79%\\n\",\n      \"#1528: 96.80%\\n\",\n      \"#1529: 96.80%\\n\",\n      \"#1530: 96.73%\\n\",\n      \"#1531: 96.74%\\n\",\n      \"#1532: 96.74%\\n\",\n      \"#1533: 96.74%\\n\",\n      \"#1534: 96.74%\\n\",\n      \"#1535: 96.74%\\n\",\n      \"#1536: 96.75%\\n\",\n      \"#1537: 96.75%\\n\",\n      \"#1538: 96.75%\\n\",\n      \"#1539: 96.75%\\n\",\n      \"#1540: 96.76%\\n\",\n      \"#1541: 96.76%\\n\",\n      \"#1542: 96.76%\\n\",\n      \"#1543: 96.76%\\n\",\n      \"#1544: 96.76%\\n\",\n      \"#1545: 96.77%\\n\",\n      \"#1546: 96.77%\\n\",\n      \"#1547: 96.77%\\n\",\n      \"#1548: 96.77%\\n\",\n      \"#1549: 96.77%\\n\",\n      \"#1550: 96.78%\\n\",\n      \"#1551: 96.78%\\n\",\n      \"#1552: 96.78%\\n\",\n      \"#1553: 96.72%\\n\",\n      \"#1554: 96.72%\\n\",\n      \"#1555: 96.72%\\n\",\n      \"#1556: 96.72%\\n\",\n      \"#1557: 96.73%\\n\",\n      \"#1558: 96.73%\\n\",\n      \"#1559: 96.67%\\n\",\n      \"#1560: 96.67%\\n\",\n      \"#1561: 96.67%\\n\",\n      \"#1562: 96.67%\\n\",\n      \"#1563: 96.68%\\n\",\n      \"#1564: 96.68%\\n\",\n      \"#1565: 96.68%\\n\",\n      \"#1566: 96.68%\\n\",\n      \"#1567: 96.68%\\n\",\n      \"#1568: 96.69%\\n\",\n      \"#1569: 96.69%\\n\",\n      \"#1570: 96.69%\\n\",\n      \"#1571: 96.69%\\n\",\n      \"#1572: 96.69%\\n\",\n      \"#1573: 96.70%\\n\",\n      \"#1574: 96.70%\\n\",\n      \"#1575: 96.70%\\n\",\n      \"#1576: 96.70%\\n\",\n      \"#1577: 96.70%\\n\",\n      \"#1578: 96.71%\\n\",\n      \"#1579: 96.71%\\n\",\n      \"#1580: 96.71%\\n\",\n      \"#1581: 96.71%\\n\",\n      \"#1582: 96.72%\\n\",\n      \"#1583: 96.72%\\n\",\n      \"#1584: 96.72%\\n\",\n      \"#1585: 96.72%\\n\",\n      \"#1586: 96.72%\\n\",\n      \"#1587: 96.73%\\n\",\n      \"#1588: 96.73%\\n\",\n      \"#1589: 96.73%\\n\",\n      \"#1590: 96.73%\\n\",\n      \"#1591: 96.73%\\n\",\n      \"#1592: 96.74%\\n\",\n      \"#1593: 96.74%\\n\",\n      \"#1594: 96.74%\\n\",\n      \"#1595: 96.74%\\n\",\n      \"#1596: 96.74%\\n\",\n      \"#1597: 96.75%\\n\",\n      \"#1598: 96.75%\\n\",\n      \"#1599: 96.75%\\n\",\n      \"#1600: 96.75%\\n\",\n      \"#1601: 96.75%\\n\",\n      \"#1602: 96.76%\\n\",\n      \"#1603: 96.76%\\n\",\n      \"#1604: 96.76%\\n\",\n      \"#1605: 96.76%\\n\",\n      \"#1606: 96.76%\\n\",\n      \"#1607: 96.70%\\n\",\n      \"#1608: 96.71%\\n\",\n      \"#1609: 96.71%\\n\",\n      \"#1610: 96.71%\\n\",\n      \"#1611: 96.65%\\n\",\n      \"#1612: 96.65%\\n\",\n      \"#1613: 96.65%\\n\",\n      \"#1614: 96.66%\\n\",\n      \"#1615: 96.66%\\n\",\n      \"#1616: 96.66%\\n\",\n      \"#1617: 96.66%\\n\",\n      \"#1618: 96.66%\\n\",\n      \"#1619: 96.67%\\n\",\n      \"#1620: 96.67%\\n\",\n      \"#1621: 96.61%\\n\",\n      \"#1622: 96.61%\\n\",\n      \"#1623: 96.61%\\n\",\n      \"#1624: 96.62%\\n\",\n      \"#1625: 96.62%\\n\",\n      \"#1626: 96.62%\\n\",\n      \"#1627: 96.62%\\n\",\n      \"#1628: 96.62%\\n\",\n      \"#1629: 96.63%\\n\",\n      \"#1630: 96.63%\\n\",\n      \"#1631: 96.63%\\n\",\n      \"#1632: 96.63%\\n\",\n      \"#1633: 96.63%\\n\",\n      \"#1634: 96.64%\\n\",\n      \"#1635: 96.64%\\n\",\n      \"#1636: 96.64%\\n\",\n      \"#1637: 96.64%\\n\",\n      \"#1638: 96.64%\\n\",\n      \"#1639: 96.65%\\n\",\n      \"#1640: 96.59%\\n\",\n      \"#1641: 96.59%\\n\",\n      \"#1642: 96.59%\\n\",\n      \"#1643: 96.59%\\n\",\n      \"#1644: 96.60%\\n\",\n      \"#1645: 96.60%\\n\",\n      \"#1646: 96.60%\\n\",\n      \"#1647: 96.60%\\n\",\n      \"#1648: 96.60%\\n\",\n      \"#1649: 96.61%\\n\",\n      \"#1650: 96.61%\\n\",\n      \"#1651: 96.61%\\n\",\n      \"#1652: 96.61%\\n\",\n      \"#1653: 96.61%\\n\",\n      \"#1654: 96.62%\\n\",\n      \"#1655: 96.62%\\n\",\n      \"#1656: 96.62%\\n\",\n      \"#1657: 96.62%\\n\",\n      \"#1658: 96.62%\\n\",\n      \"#1659: 96.63%\\n\",\n      \"#1660: 96.63%\\n\",\n      \"#1661: 96.63%\\n\",\n      \"#1662: 96.63%\\n\",\n      \"#1663: 96.63%\\n\",\n      \"#1664: 96.64%\\n\",\n      \"#1665: 96.64%\\n\",\n      \"#1666: 96.64%\\n\",\n      \"#1667: 96.64%\\n\",\n      \"#1668: 96.64%\\n\",\n      \"#1669: 96.65%\\n\",\n      \"#1670: 96.65%\\n\",\n      \"#1671: 96.65%\\n\",\n      \"#1672: 96.65%\\n\",\n      \"#1673: 96.65%\\n\",\n      \"#1674: 96.66%\\n\",\n      \"#1675: 96.66%\\n\",\n      \"#1676: 96.66%\\n\",\n      \"#1677: 96.66%\\n\",\n      \"#1678: 96.66%\\n\",\n      \"#1679: 96.67%\\n\",\n      \"#1680: 96.67%\\n\",\n      \"#1681: 96.61%\\n\",\n      \"#1682: 96.61%\\n\",\n      \"#1683: 96.62%\\n\",\n      \"#1684: 96.62%\\n\",\n      \"#1685: 96.62%\\n\",\n      \"#1686: 96.56%\\n\",\n      \"#1687: 96.56%\\n\",\n      \"#1688: 96.57%\\n\",\n      \"#1689: 96.57%\\n\",\n      \"#1690: 96.57%\\n\",\n      \"#1691: 96.57%\\n\",\n      \"#1692: 96.57%\\n\",\n      \"#1693: 96.58%\\n\",\n      \"#1694: 96.58%\\n\",\n      \"#1695: 96.58%\\n\",\n      \"#1696: 96.58%\\n\",\n      \"#1697: 96.58%\\n\",\n      \"#1698: 96.59%\\n\",\n      \"#1699: 96.59%\\n\",\n      \"#1700: 96.59%\\n\",\n      \"#1701: 96.59%\\n\",\n      \"#1702: 96.59%\\n\",\n      \"#1703: 96.60%\\n\",\n      \"#1704: 96.60%\\n\",\n      \"#1705: 96.60%\\n\",\n      \"#1706: 96.60%\\n\",\n      \"#1707: 96.60%\\n\",\n      \"#1708: 96.61%\\n\",\n      \"#1709: 96.55%\\n\",\n      \"#1710: 96.55%\\n\",\n      \"#1711: 96.55%\\n\",\n      \"#1712: 96.56%\\n\",\n      \"#1713: 96.56%\\n\",\n      \"#1714: 96.56%\\n\",\n      \"#1715: 96.56%\\n\",\n      \"#1716: 96.56%\\n\",\n      \"#1717: 96.51%\\n\",\n      \"#1718: 96.51%\\n\",\n      \"#1719: 96.51%\\n\",\n      \"#1720: 96.51%\\n\",\n      \"#1721: 96.52%\\n\",\n      \"#1722: 96.52%\\n\",\n      \"#1723: 96.52%\\n\",\n      \"#1724: 96.52%\\n\",\n      \"#1725: 96.52%\\n\",\n      \"#1726: 96.53%\\n\",\n      \"#1727: 96.53%\\n\",\n      \"#1728: 96.53%\\n\",\n      \"#1729: 96.53%\\n\",\n      \"#1730: 96.53%\\n\",\n      \"#1731: 96.54%\\n\",\n      \"#1732: 96.54%\\n\",\n      \"#1733: 96.54%\\n\",\n      \"#1734: 96.54%\\n\",\n      \"#1735: 96.54%\\n\",\n      \"#1736: 96.55%\\n\",\n      \"#1737: 96.49%\\n\",\n      \"#1738: 96.49%\\n\",\n      \"#1739: 96.49%\\n\",\n      \"#1740: 96.50%\\n\",\n      \"#1741: 96.50%\\n\",\n      \"#1742: 96.50%\\n\",\n      \"#1743: 96.50%\\n\",\n      \"#1744: 96.50%\\n\",\n      \"#1745: 96.51%\\n\",\n      \"#1746: 96.51%\\n\",\n      \"#1747: 96.45%\\n\",\n      \"#1748: 96.46%\\n\",\n      \"#1749: 96.46%\\n\",\n      \"#1750: 96.46%\\n\",\n      \"#1751: 96.46%\\n\",\n      \"#1752: 96.46%\\n\",\n      \"#1753: 96.47%\\n\",\n      \"#1754: 96.41%\\n\",\n      \"#1755: 96.41%\\n\",\n      \"#1756: 96.41%\\n\",\n      \"#1757: 96.42%\\n\",\n      \"#1758: 96.42%\\n\",\n      \"#1759: 96.42%\\n\",\n      \"#1760: 96.42%\\n\",\n      \"#1761: 96.42%\\n\",\n      \"#1762: 96.43%\\n\",\n      \"#1763: 96.43%\\n\",\n      \"#1764: 96.43%\\n\",\n      \"#1765: 96.43%\\n\",\n      \"#1766: 96.43%\\n\",\n      \"#1767: 96.44%\\n\",\n      \"#1768: 96.44%\\n\",\n      \"#1769: 96.44%\\n\",\n      \"#1770: 96.44%\\n\",\n      \"#1771: 96.44%\\n\",\n      \"#1772: 96.45%\\n\",\n      \"#1773: 96.45%\\n\",\n      \"#1774: 96.45%\\n\",\n      \"#1775: 96.45%\\n\",\n      \"#1776: 96.45%\\n\",\n      \"#1777: 96.46%\\n\",\n      \"#1778: 96.46%\\n\",\n      \"#1779: 96.46%\\n\",\n      \"#1780: 96.46%\\n\",\n      \"#1781: 96.46%\\n\",\n      \"#1782: 96.47%\\n\",\n      \"#1783: 96.47%\\n\",\n      \"#1784: 96.47%\\n\",\n      \"#1785: 96.47%\\n\",\n      \"#1786: 96.47%\\n\",\n      \"#1787: 96.48%\\n\",\n      \"#1788: 96.48%\\n\",\n      \"#1789: 96.48%\\n\",\n      \"#1790: 96.48%\\n\",\n      \"#1791: 96.48%\\n\",\n      \"#1792: 96.49%\\n\",\n      \"#1793: 96.49%\\n\",\n      \"#1794: 96.49%\\n\",\n      \"#1795: 96.49%\\n\",\n      \"#1796: 96.49%\\n\",\n      \"#1797: 96.50%\\n\",\n      \"#1798: 96.50%\\n\",\n      \"#1799: 96.50%\\n\",\n      \"#1800: 96.50%\\n\",\n      \"#1801: 96.50%\\n\",\n      \"#1802: 96.51%\\n\",\n      \"#1803: 96.51%\\n\",\n      \"#1804: 96.51%\\n\",\n      \"#1805: 96.51%\\n\",\n      \"#1806: 96.51%\\n\",\n      \"#1807: 96.52%\\n\",\n      \"#1808: 96.52%\\n\",\n      \"#1809: 96.52%\\n\",\n      \"#1810: 96.52%\\n\",\n      \"#1811: 96.52%\\n\",\n      \"#1812: 96.53%\\n\",\n      \"#1813: 96.53%\\n\",\n      \"#1814: 96.53%\\n\",\n      \"#1815: 96.53%\\n\",\n      \"#1816: 96.53%\\n\",\n      \"#1817: 96.53%\\n\",\n      \"#1818: 96.54%\\n\",\n      \"#1819: 96.54%\\n\",\n      \"#1820: 96.54%\\n\",\n      \"#1821: 96.54%\\n\",\n      \"#1822: 96.54%\\n\",\n      \"#1823: 96.55%\\n\",\n      \"#1824: 96.55%\\n\",\n      \"#1825: 96.55%\\n\",\n      \"#1826: 96.55%\\n\",\n      \"#1827: 96.55%\\n\",\n      \"#1828: 96.56%\\n\",\n      \"#1829: 96.56%\\n\",\n      \"#1830: 96.56%\\n\",\n      \"#1831: 96.56%\\n\",\n      \"#1832: 96.56%\\n\",\n      \"#1833: 96.56%\\n\",\n      \"#1834: 96.57%\\n\",\n      \"#1835: 96.57%\\n\",\n      \"#1836: 96.57%\\n\",\n      \"#1837: 96.57%\\n\",\n      \"#1838: 96.57%\\n\",\n      \"#1839: 96.58%\\n\",\n      \"#1840: 96.58%\\n\",\n      \"#1841: 96.58%\\n\",\n      \"#1842: 96.58%\\n\",\n      \"#1843: 96.58%\\n\",\n      \"#1844: 96.59%\\n\",\n      \"#1845: 96.59%\\n\",\n      \"#1846: 96.59%\\n\",\n      \"#1847: 96.59%\\n\",\n      \"#1848: 96.59%\\n\",\n      \"#1849: 96.59%\\n\",\n      \"#1850: 96.60%\\n\",\n      \"#1851: 96.60%\\n\",\n      \"#1852: 96.60%\\n\",\n      \"#1853: 96.60%\\n\",\n      \"#1854: 96.60%\\n\",\n      \"#1855: 96.61%\\n\",\n      \"#1856: 96.61%\\n\",\n      \"#1857: 96.61%\\n\",\n      \"#1858: 96.61%\\n\",\n      \"#1859: 96.61%\\n\",\n      \"#1860: 96.61%\\n\",\n      \"#1861: 96.62%\\n\",\n      \"#1862: 96.62%\\n\",\n      \"#1863: 96.62%\\n\",\n      \"#1864: 96.62%\\n\",\n      \"#1865: 96.62%\\n\",\n      \"#1866: 96.63%\\n\",\n      \"#1867: 96.63%\\n\",\n      \"#1868: 96.63%\\n\",\n      \"#1869: 96.63%\\n\",\n      \"#1870: 96.63%\\n\",\n      \"#1871: 96.63%\\n\",\n      \"#1872: 96.64%\\n\",\n      \"#1873: 96.64%\\n\",\n      \"#1874: 96.64%\\n\",\n      \"#1875: 96.64%\\n\",\n      \"#1876: 96.64%\\n\",\n      \"#1877: 96.65%\\n\",\n      \"#1878: 96.65%\\n\",\n      \"#1879: 96.65%\\n\",\n      \"#1880: 96.65%\\n\",\n      \"#1881: 96.65%\\n\",\n      \"#1882: 96.65%\\n\",\n      \"#1883: 96.60%\\n\",\n      \"#1884: 96.60%\\n\",\n      \"#1885: 96.61%\\n\",\n      \"#1886: 96.61%\\n\",\n      \"#1887: 96.61%\\n\",\n      \"#1888: 96.61%\\n\",\n      \"#1889: 96.61%\\n\",\n      \"#1890: 96.62%\\n\",\n      \"#1891: 96.62%\\n\",\n      \"#1892: 96.62%\\n\",\n      \"#1893: 96.62%\\n\",\n      \"#1894: 96.62%\\n\",\n      \"#1895: 96.62%\\n\",\n      \"#1896: 96.63%\\n\",\n      \"#1897: 96.63%\\n\",\n      \"#1898: 96.63%\\n\",\n      \"#1899: 96.63%\\n\",\n      \"#1900: 96.63%\\n\",\n      \"#1901: 96.58%\\n\",\n      \"#1902: 96.58%\\n\",\n      \"#1903: 96.59%\\n\",\n      \"#1904: 96.59%\\n\",\n      \"#1905: 96.59%\\n\",\n      \"#1906: 96.59%\\n\",\n      \"#1907: 96.59%\\n\",\n      \"#1908: 96.60%\\n\",\n      \"#1909: 96.60%\\n\",\n      \"#1910: 96.60%\\n\",\n      \"#1911: 96.60%\\n\",\n      \"#1912: 96.60%\\n\",\n      \"#1913: 96.60%\\n\",\n      \"#1914: 96.61%\\n\",\n      \"#1915: 96.61%\\n\",\n      \"#1916: 96.61%\\n\",\n      \"#1917: 96.61%\\n\",\n      \"#1918: 96.61%\\n\",\n      \"#1919: 96.61%\\n\",\n      \"#1920: 96.62%\\n\",\n      \"#1921: 96.62%\\n\",\n      \"#1922: 96.62%\\n\",\n      \"#1923: 96.62%\\n\",\n      \"#1924: 96.62%\\n\",\n      \"#1925: 96.63%\\n\",\n      \"#1926: 96.63%\\n\",\n      \"#1927: 96.63%\\n\",\n      \"#1928: 96.63%\\n\",\n      \"#1929: 96.63%\\n\",\n      \"#1930: 96.63%\\n\",\n      \"#1931: 96.64%\\n\",\n      \"#1932: 96.64%\\n\",\n      \"#1933: 96.64%\\n\",\n      \"#1934: 96.64%\\n\",\n      \"#1935: 96.64%\\n\",\n      \"#1936: 96.64%\\n\",\n      \"#1937: 96.65%\\n\",\n      \"#1938: 96.65%\\n\",\n      \"#1939: 96.65%\\n\",\n      \"#1940: 96.65%\\n\",\n      \"#1941: 96.65%\\n\",\n      \"#1942: 96.65%\\n\",\n      \"#1943: 96.66%\\n\",\n      \"#1944: 96.66%\\n\",\n      \"#1945: 96.66%\\n\",\n      \"#1946: 96.66%\\n\",\n      \"#1947: 96.66%\\n\",\n      \"#1948: 96.66%\\n\",\n      \"#1949: 96.67%\\n\",\n      \"#1950: 96.67%\\n\",\n      \"#1951: 96.67%\\n\",\n      \"#1952: 96.67%\\n\",\n      \"#1953: 96.67%\\n\",\n      \"#1954: 96.68%\\n\",\n      \"#1955: 96.63%\\n\",\n      \"#1956: 96.63%\\n\",\n      \"#1957: 96.63%\\n\",\n      \"#1958: 96.63%\\n\",\n      \"#1959: 96.63%\\n\",\n      \"#1960: 96.63%\\n\",\n      \"#1961: 96.64%\\n\",\n      \"#1962: 96.64%\\n\",\n      \"#1963: 96.64%\\n\",\n      \"#1964: 96.64%\\n\",\n      \"#1965: 96.64%\\n\",\n      \"#1966: 96.64%\\n\",\n      \"#1967: 96.65%\\n\",\n      \"#1968: 96.65%\\n\",\n      \"#1969: 96.65%\\n\",\n      \"#1970: 96.65%\\n\",\n      \"#1971: 96.65%\\n\",\n      \"#1972: 96.65%\\n\",\n      \"#1973: 96.66%\\n\",\n      \"#1974: 96.66%\\n\",\n      \"#1975: 96.66%\\n\",\n      \"#1976: 96.66%\\n\",\n      \"#1977: 96.66%\\n\",\n      \"#1978: 96.66%\\n\",\n      \"#1979: 96.67%\\n\",\n      \"#1980: 96.67%\\n\",\n      \"#1981: 96.67%\\n\",\n      \"#1982: 96.67%\\n\",\n      \"#1983: 96.67%\\n\",\n      \"#1984: 96.68%\\n\",\n      \"#1985: 96.68%\\n\",\n      \"#1986: 96.68%\\n\",\n      \"#1987: 96.68%\\n\",\n      \"#1988: 96.68%\\n\",\n      \"#1989: 96.68%\\n\",\n      \"#1990: 96.69%\\n\",\n      \"#1991: 96.69%\\n\",\n      \"#1992: 96.69%\\n\",\n      \"#1993: 96.69%\\n\",\n      \"#1994: 96.69%\\n\",\n      \"#1995: 96.69%\\n\",\n      \"#1996: 96.70%\\n\",\n      \"#1997: 96.70%\\n\",\n      \"#1998: 96.70%\\n\",\n      \"#1999: 96.70%\\n\",\n      \"#2000: 96.70%\\n\",\n      \"#2001: 96.70%\\n\",\n      \"#2002: 96.70%\\n\",\n      \"#2003: 96.71%\\n\",\n      \"#2004: 96.71%\\n\",\n      \"#2005: 96.71%\\n\",\n      \"#2006: 96.71%\\n\",\n      \"#2007: 96.71%\\n\",\n      \"#2008: 96.71%\\n\",\n      \"#2009: 96.72%\\n\",\n      \"#2010: 96.72%\\n\",\n      \"#2011: 96.72%\\n\",\n      \"#2012: 96.72%\\n\",\n      \"#2013: 96.72%\\n\",\n      \"#2014: 96.72%\\n\",\n      \"#2015: 96.73%\\n\",\n      \"#2016: 96.73%\\n\",\n      \"#2017: 96.73%\\n\",\n      \"#2018: 96.68%\\n\",\n      \"#2019: 96.68%\\n\",\n      \"#2020: 96.68%\\n\",\n      \"#2021: 96.69%\\n\",\n      \"#2022: 96.69%\\n\",\n      \"#2023: 96.69%\\n\",\n      \"#2024: 96.69%\\n\",\n      \"#2025: 96.64%\\n\",\n      \"#2026: 96.65%\\n\",\n      \"#2027: 96.65%\\n\",\n      \"#2028: 96.65%\\n\",\n      \"#2029: 96.65%\\n\",\n      \"#2030: 96.65%\\n\",\n      \"#2031: 96.65%\\n\",\n      \"#2032: 96.66%\\n\",\n      \"#2033: 96.66%\\n\",\n      \"#2034: 96.66%\\n\",\n      \"#2035: 96.66%\\n\",\n      \"#2036: 96.66%\\n\",\n      \"#2037: 96.66%\\n\",\n      \"#2038: 96.67%\\n\",\n      \"#2039: 96.67%\\n\",\n      \"#2040: 96.67%\\n\",\n      \"#2041: 96.67%\\n\",\n      \"#2042: 96.67%\\n\",\n      \"#2043: 96.62%\\n\",\n      \"#2044: 96.63%\\n\",\n      \"#2045: 96.63%\\n\",\n      \"#2046: 96.63%\\n\",\n      \"#2047: 96.63%\\n\",\n      \"#2048: 96.63%\\n\",\n      \"#2049: 96.63%\\n\",\n      \"#2050: 96.64%\\n\",\n      \"#2051: 96.64%\\n\",\n      \"#2052: 96.64%\\n\",\n      \"#2053: 96.64%\\n\",\n      \"#2054: 96.64%\\n\",\n      \"#2055: 96.64%\\n\",\n      \"#2056: 96.65%\\n\",\n      \"#2057: 96.65%\\n\",\n      \"#2058: 96.65%\\n\",\n      \"#2059: 96.65%\\n\",\n      \"#2060: 96.65%\\n\",\n      \"#2061: 96.65%\\n\",\n      \"#2062: 96.66%\\n\",\n      \"#2063: 96.66%\\n\",\n      \"#2064: 96.66%\\n\",\n      \"#2065: 96.66%\\n\",\n      \"#2066: 96.66%\\n\",\n      \"#2067: 96.66%\\n\",\n      \"#2068: 96.67%\\n\",\n      \"#2069: 96.67%\\n\",\n      \"#2070: 96.62%\\n\",\n      \"#2071: 96.62%\\n\",\n      \"#2072: 96.62%\\n\",\n      \"#2073: 96.62%\\n\",\n      \"#2074: 96.63%\\n\",\n      \"#2075: 96.63%\\n\",\n      \"#2076: 96.63%\\n\",\n      \"#2077: 96.63%\\n\",\n      \"#2078: 96.63%\\n\",\n      \"#2079: 96.63%\\n\",\n      \"#2080: 96.64%\\n\",\n      \"#2081: 96.64%\\n\",\n      \"#2082: 96.64%\\n\",\n      \"#2083: 96.64%\\n\",\n      \"#2084: 96.64%\\n\",\n      \"#2085: 96.64%\\n\",\n      \"#2086: 96.65%\\n\",\n      \"#2087: 96.65%\\n\",\n      \"#2088: 96.65%\\n\",\n      \"#2089: 96.65%\\n\",\n      \"#2090: 96.65%\\n\",\n      \"#2091: 96.65%\\n\",\n      \"#2092: 96.66%\\n\",\n      \"#2093: 96.66%\\n\",\n      \"#2094: 96.66%\\n\",\n      \"#2095: 96.66%\\n\",\n      \"#2096: 96.66%\\n\",\n      \"#2097: 96.66%\\n\",\n      \"#2098: 96.62%\\n\",\n      \"#2099: 96.62%\\n\",\n      \"#2100: 96.62%\\n\",\n      \"#2101: 96.62%\\n\",\n      \"#2102: 96.62%\\n\",\n      \"#2103: 96.63%\\n\",\n      \"#2104: 96.63%\\n\",\n      \"#2105: 96.63%\\n\",\n      \"#2106: 96.63%\\n\",\n      \"#2107: 96.63%\\n\",\n      \"#2108: 96.63%\\n\",\n      \"#2109: 96.59%\\n\",\n      \"#2110: 96.59%\\n\",\n      \"#2111: 96.59%\\n\",\n      \"#2112: 96.59%\\n\",\n      \"#2113: 96.59%\\n\",\n      \"#2114: 96.60%\\n\",\n      \"#2115: 96.60%\\n\",\n      \"#2116: 96.60%\\n\",\n      \"#2117: 96.60%\\n\",\n      \"#2118: 96.55%\\n\",\n      \"#2119: 96.56%\\n\",\n      \"#2120: 96.56%\\n\",\n      \"#2121: 96.56%\\n\",\n      \"#2122: 96.56%\\n\",\n      \"#2123: 96.56%\\n\",\n      \"#2124: 96.56%\\n\",\n      \"#2125: 96.57%\\n\",\n      \"#2126: 96.57%\\n\",\n      \"#2127: 96.57%\\n\",\n      \"#2128: 96.57%\\n\",\n      \"#2129: 96.57%\\n\",\n      \"#2130: 96.53%\\n\",\n      \"#2131: 96.53%\\n\",\n      \"#2132: 96.53%\\n\",\n      \"#2133: 96.53%\\n\",\n      \"#2134: 96.53%\\n\",\n      \"#2135: 96.49%\\n\",\n      \"#2136: 96.49%\\n\",\n      \"#2137: 96.49%\\n\",\n      \"#2138: 96.49%\\n\",\n      \"#2139: 96.50%\\n\",\n      \"#2140: 96.50%\\n\",\n      \"#2141: 96.50%\\n\",\n      \"#2142: 96.50%\\n\",\n      \"#2143: 96.50%\\n\",\n      \"#2144: 96.50%\\n\",\n      \"#2145: 96.51%\\n\",\n      \"#2146: 96.51%\\n\",\n      \"#2147: 96.51%\\n\",\n      \"#2148: 96.51%\\n\",\n      \"#2149: 96.51%\\n\",\n      \"#2150: 96.51%\\n\",\n      \"#2151: 96.51%\\n\",\n      \"#2152: 96.52%\\n\",\n      \"#2153: 96.52%\\n\",\n      \"#2154: 96.52%\\n\",\n      \"#2155: 96.52%\\n\",\n      \"#2156: 96.52%\\n\",\n      \"#2157: 96.52%\\n\",\n      \"#2158: 96.53%\\n\",\n      \"#2159: 96.53%\\n\",\n      \"#2160: 96.53%\\n\",\n      \"#2161: 96.53%\\n\",\n      \"#2162: 96.53%\\n\",\n      \"#2163: 96.53%\\n\",\n      \"#2164: 96.54%\\n\",\n      \"#2165: 96.54%\\n\",\n      \"#2166: 96.54%\\n\",\n      \"#2167: 96.54%\\n\",\n      \"#2168: 96.54%\\n\",\n      \"#2169: 96.54%\\n\",\n      \"#2170: 96.55%\\n\",\n      \"#2171: 96.55%\\n\",\n      \"#2172: 96.55%\\n\",\n      \"#2173: 96.55%\\n\",\n      \"#2174: 96.55%\\n\",\n      \"#2175: 96.55%\\n\",\n      \"#2176: 96.55%\\n\",\n      \"#2177: 96.56%\\n\",\n      \"#2178: 96.56%\\n\",\n      \"#2179: 96.56%\\n\",\n      \"#2180: 96.56%\\n\",\n      \"#2181: 96.56%\\n\",\n      \"#2182: 96.56%\\n\",\n      \"#2183: 96.57%\\n\",\n      \"#2184: 96.57%\\n\",\n      \"#2185: 96.52%\\n\",\n      \"#2186: 96.48%\\n\",\n      \"#2187: 96.48%\\n\",\n      \"#2188: 96.48%\\n\",\n      \"#2189: 96.44%\\n\",\n      \"#2190: 96.44%\\n\",\n      \"#2191: 96.44%\\n\",\n      \"#2192: 96.44%\\n\",\n      \"#2193: 96.44%\\n\",\n      \"#2194: 96.45%\\n\",\n      \"#2195: 96.45%\\n\",\n      \"#2196: 96.45%\\n\",\n      \"#2197: 96.45%\\n\",\n      \"#2198: 96.45%\\n\",\n      \"#2199: 96.45%\\n\",\n      \"#2200: 96.46%\\n\",\n      \"#2201: 96.46%\\n\",\n      \"#2202: 96.46%\\n\",\n      \"#2203: 96.46%\\n\",\n      \"#2204: 96.46%\\n\",\n      \"#2205: 96.46%\\n\",\n      \"#2206: 96.47%\\n\",\n      \"#2207: 96.47%\\n\",\n      \"#2208: 96.47%\\n\",\n      \"#2209: 96.47%\\n\",\n      \"#2210: 96.47%\\n\",\n      \"#2211: 96.47%\\n\",\n      \"#2212: 96.48%\\n\",\n      \"#2213: 96.48%\\n\",\n      \"#2214: 96.48%\\n\",\n      \"#2215: 96.48%\\n\",\n      \"#2216: 96.48%\\n\",\n      \"#2217: 96.48%\\n\",\n      \"#2218: 96.48%\\n\",\n      \"#2219: 96.49%\\n\",\n      \"#2220: 96.49%\\n\",\n      \"#2221: 96.49%\\n\",\n      \"#2222: 96.49%\\n\",\n      \"#2223: 96.49%\\n\",\n      \"#2224: 96.49%\\n\",\n      \"#2225: 96.50%\\n\",\n      \"#2226: 96.50%\\n\",\n      \"#2227: 96.50%\\n\",\n      \"#2228: 96.50%\\n\",\n      \"#2229: 96.50%\\n\",\n      \"#2230: 96.50%\\n\",\n      \"#2231: 96.51%\\n\",\n      \"#2232: 96.51%\\n\",\n      \"#2233: 96.51%\\n\",\n      \"#2234: 96.51%\\n\",\n      \"#2235: 96.51%\\n\",\n      \"#2236: 96.51%\\n\",\n      \"#2237: 96.51%\\n\",\n      \"#2238: 96.52%\\n\",\n      \"#2239: 96.52%\\n\",\n      \"#2240: 96.52%\\n\",\n      \"#2241: 96.52%\\n\",\n      \"#2242: 96.52%\\n\",\n      \"#2243: 96.52%\\n\",\n      \"#2244: 96.53%\\n\",\n      \"#2245: 96.53%\\n\",\n      \"#2246: 96.53%\\n\",\n      \"#2247: 96.53%\\n\",\n      \"#2248: 96.53%\\n\",\n      \"#2249: 96.53%\\n\",\n      \"#2250: 96.53%\\n\",\n      \"#2251: 96.54%\\n\",\n      \"#2252: 96.54%\\n\",\n      \"#2253: 96.54%\\n\",\n      \"#2254: 96.54%\\n\",\n      \"#2255: 96.54%\\n\",\n      \"#2256: 96.54%\\n\",\n      \"#2257: 96.55%\\n\",\n      \"#2258: 96.55%\\n\",\n      \"#2259: 96.55%\\n\",\n      \"#2260: 96.55%\\n\",\n      \"#2261: 96.55%\\n\",\n      \"#2262: 96.55%\\n\",\n      \"#2263: 96.55%\\n\",\n      \"#2264: 96.56%\\n\",\n      \"#2265: 96.56%\\n\",\n      \"#2266: 96.52%\\n\",\n      \"#2267: 96.52%\\n\",\n      \"#2268: 96.52%\\n\",\n      \"#2269: 96.52%\\n\",\n      \"#2270: 96.52%\\n\",\n      \"#2271: 96.52%\\n\",\n      \"#2272: 96.52%\\n\",\n      \"#2273: 96.53%\\n\",\n      \"#2274: 96.53%\\n\",\n      \"#2275: 96.53%\\n\",\n      \"#2276: 96.53%\\n\",\n      \"#2277: 96.53%\\n\",\n      \"#2278: 96.53%\\n\",\n      \"#2279: 96.54%\\n\",\n      \"#2280: 96.49%\\n\",\n      \"#2281: 96.49%\\n\",\n      \"#2282: 96.50%\\n\",\n      \"#2283: 96.50%\\n\",\n      \"#2284: 96.50%\\n\",\n      \"#2285: 96.50%\\n\",\n      \"#2286: 96.50%\\n\",\n      \"#2287: 96.50%\\n\",\n      \"#2288: 96.51%\\n\",\n      \"#2289: 96.51%\\n\",\n      \"#2290: 96.51%\\n\",\n      \"#2291: 96.51%\\n\",\n      \"#2292: 96.51%\\n\",\n      \"#2293: 96.51%\\n\",\n      \"#2294: 96.51%\\n\",\n      \"#2295: 96.52%\\n\",\n      \"#2296: 96.52%\\n\",\n      \"#2297: 96.52%\\n\",\n      \"#2298: 96.52%\\n\",\n      \"#2299: 96.52%\\n\",\n      \"#2300: 96.52%\\n\",\n      \"#2301: 96.52%\\n\",\n      \"#2302: 96.53%\\n\",\n      \"#2303: 96.53%\\n\",\n      \"#2304: 96.53%\\n\",\n      \"#2305: 96.53%\\n\",\n      \"#2306: 96.53%\\n\",\n      \"#2307: 96.53%\\n\",\n      \"#2308: 96.49%\\n\",\n      \"#2309: 96.49%\\n\",\n      \"#2310: 96.50%\\n\",\n      \"#2311: 96.50%\\n\",\n      \"#2312: 96.50%\\n\",\n      \"#2313: 96.50%\\n\",\n      \"#2314: 96.50%\\n\",\n      \"#2315: 96.50%\\n\",\n      \"#2316: 96.50%\\n\",\n      \"#2317: 96.51%\\n\",\n      \"#2318: 96.51%\\n\",\n      \"#2319: 96.51%\\n\",\n      \"#2320: 96.51%\\n\",\n      \"#2321: 96.51%\\n\",\n      \"#2322: 96.51%\\n\",\n      \"#2323: 96.51%\\n\",\n      \"#2324: 96.52%\\n\",\n      \"#2325: 96.52%\\n\",\n      \"#2326: 96.52%\\n\",\n      \"#2327: 96.52%\\n\",\n      \"#2328: 96.52%\\n\",\n      \"#2329: 96.52%\\n\",\n      \"#2330: 96.53%\\n\",\n      \"#2331: 96.53%\\n\",\n      \"#2332: 96.53%\\n\",\n      \"#2333: 96.53%\\n\",\n      \"#2334: 96.53%\\n\",\n      \"#2335: 96.53%\\n\",\n      \"#2336: 96.53%\\n\",\n      \"#2337: 96.54%\\n\",\n      \"#2338: 96.54%\\n\",\n      \"#2339: 96.54%\\n\",\n      \"#2340: 96.54%\\n\",\n      \"#2341: 96.54%\\n\",\n      \"#2342: 96.54%\\n\",\n      \"#2343: 96.54%\\n\",\n      \"#2344: 96.55%\\n\",\n      \"#2345: 96.55%\\n\",\n      \"#2346: 96.55%\\n\",\n      \"#2347: 96.55%\\n\",\n      \"#2348: 96.55%\\n\",\n      \"#2349: 96.55%\\n\",\n      \"#2350: 96.55%\\n\",\n      \"#2351: 96.56%\\n\",\n      \"#2352: 96.56%\\n\",\n      \"#2353: 96.56%\\n\",\n      \"#2354: 96.56%\\n\",\n      \"#2355: 96.56%\\n\",\n      \"#2356: 96.56%\\n\",\n      \"#2357: 96.56%\\n\",\n      \"#2358: 96.57%\\n\",\n      \"#2359: 96.57%\\n\",\n      \"#2360: 96.57%\\n\",\n      \"#2361: 96.57%\\n\",\n      \"#2362: 96.57%\\n\",\n      \"#2363: 96.57%\\n\",\n      \"#2364: 96.58%\\n\",\n      \"#2365: 96.58%\\n\",\n      \"#2366: 96.58%\\n\",\n      \"#2367: 96.58%\\n\",\n      \"#2368: 96.58%\\n\",\n      \"#2369: 96.58%\\n\",\n      \"#2370: 96.58%\\n\",\n      \"#2371: 96.59%\\n\",\n      \"#2372: 96.59%\\n\",\n      \"#2373: 96.59%\\n\",\n      \"#2374: 96.59%\\n\",\n      \"#2375: 96.59%\\n\",\n      \"#2376: 96.59%\\n\",\n      \"#2377: 96.59%\\n\",\n      \"#2378: 96.60%\\n\",\n      \"#2379: 96.60%\\n\",\n      \"#2380: 96.60%\\n\",\n      \"#2381: 96.60%\\n\",\n      \"#2382: 96.60%\\n\",\n      \"#2383: 96.60%\\n\",\n      \"#2384: 96.60%\\n\",\n      \"#2385: 96.61%\\n\",\n      \"#2386: 96.61%\\n\",\n      \"#2387: 96.61%\\n\",\n      \"#2388: 96.61%\\n\",\n      \"#2389: 96.61%\\n\",\n      \"#2390: 96.61%\\n\",\n      \"#2391: 96.61%\\n\",\n      \"#2392: 96.62%\\n\",\n      \"#2393: 96.62%\\n\",\n      \"#2394: 96.62%\\n\",\n      \"#2395: 96.62%\\n\",\n      \"#2396: 96.62%\\n\",\n      \"#2397: 96.62%\\n\",\n      \"#2398: 96.62%\\n\",\n      \"#2399: 96.62%\\n\",\n      \"#2400: 96.63%\\n\",\n      \"#2401: 96.63%\\n\",\n      \"#2402: 96.63%\\n\",\n      \"#2403: 96.63%\\n\",\n      \"#2404: 96.63%\\n\",\n      \"#2405: 96.63%\\n\",\n      \"#2406: 96.63%\\n\",\n      \"#2407: 96.64%\\n\",\n      \"#2408: 96.64%\\n\",\n      \"#2409: 96.64%\\n\",\n      \"#2410: 96.64%\\n\",\n      \"#2411: 96.64%\\n\",\n      \"#2412: 96.64%\\n\",\n      \"#2413: 96.64%\\n\",\n      \"#2414: 96.65%\\n\",\n      \"#2415: 96.65%\\n\",\n      \"#2416: 96.65%\\n\",\n      \"#2417: 96.65%\\n\",\n      \"#2418: 96.65%\\n\",\n      \"#2419: 96.65%\\n\",\n      \"#2420: 96.65%\\n\",\n      \"#2421: 96.66%\\n\",\n      \"#2422: 96.66%\\n\",\n      \"#2423: 96.66%\\n\",\n      \"#2424: 96.66%\\n\",\n      \"#2425: 96.66%\\n\",\n      \"#2426: 96.66%\\n\",\n      \"#2427: 96.66%\\n\",\n      \"#2428: 96.67%\\n\",\n      \"#2429: 96.67%\\n\",\n      \"#2430: 96.67%\\n\",\n      \"#2431: 96.67%\\n\",\n      \"#2432: 96.67%\\n\",\n      \"#2433: 96.67%\\n\",\n      \"#2434: 96.67%\\n\",\n      \"#2435: 96.67%\\n\",\n      \"#2436: 96.68%\\n\",\n      \"#2437: 96.68%\\n\",\n      \"#2438: 96.68%\\n\",\n      \"#2439: 96.68%\\n\",\n      \"#2440: 96.68%\\n\",\n      \"#2441: 96.68%\\n\",\n      \"#2442: 96.68%\\n\",\n      \"#2443: 96.69%\\n\",\n      \"#2444: 96.69%\\n\",\n      \"#2445: 96.69%\\n\",\n      \"#2446: 96.69%\\n\",\n      \"#2447: 96.69%\\n\",\n      \"#2448: 96.69%\\n\",\n      \"#2449: 96.69%\\n\",\n      \"#2450: 96.70%\\n\",\n      \"#2451: 96.70%\\n\",\n      \"#2452: 96.70%\\n\",\n      \"#2453: 96.70%\\n\",\n      \"#2454: 96.66%\\n\",\n      \"#2455: 96.66%\\n\",\n      \"#2456: 96.66%\\n\",\n      \"#2457: 96.66%\\n\",\n      \"#2458: 96.67%\\n\",\n      \"#2459: 96.67%\\n\",\n      \"#2460: 96.67%\\n\",\n      \"#2461: 96.67%\\n\",\n      \"#2462: 96.63%\\n\",\n      \"#2463: 96.63%\\n\",\n      \"#2464: 96.63%\\n\",\n      \"#2465: 96.63%\\n\",\n      \"#2466: 96.64%\\n\",\n      \"#2467: 96.64%\\n\",\n      \"#2468: 96.64%\\n\",\n      \"#2469: 96.64%\\n\",\n      \"#2470: 96.64%\\n\",\n      \"#2471: 96.64%\\n\",\n      \"#2472: 96.64%\\n\",\n      \"#2473: 96.65%\\n\",\n      \"#2474: 96.65%\\n\",\n      \"#2475: 96.65%\\n\",\n      \"#2476: 96.65%\\n\",\n      \"#2477: 96.65%\\n\",\n      \"#2478: 96.65%\\n\",\n      \"#2479: 96.65%\\n\",\n      \"#2480: 96.65%\\n\",\n      \"#2481: 96.66%\\n\",\n      \"#2482: 96.66%\\n\",\n      \"#2483: 96.66%\\n\",\n      \"#2484: 96.66%\\n\",\n      \"#2485: 96.66%\\n\",\n      \"#2486: 96.66%\\n\",\n      \"#2487: 96.66%\\n\",\n      \"#2488: 96.63%\\n\",\n      \"#2489: 96.63%\\n\",\n      \"#2490: 96.63%\\n\",\n      \"#2491: 96.63%\\n\",\n      \"#2492: 96.63%\\n\",\n      \"#2493: 96.63%\\n\",\n      \"#2494: 96.63%\\n\",\n      \"#2495: 96.63%\\n\",\n      \"#2496: 96.64%\\n\",\n      \"#2497: 96.64%\\n\",\n      \"#2498: 96.64%\\n\",\n      \"#2499: 96.64%\\n\",\n      \"#2500: 96.64%\\n\",\n      \"#2501: 96.64%\\n\",\n      \"#2502: 96.64%\\n\",\n      \"#2503: 96.65%\\n\",\n      \"#2504: 96.65%\\n\",\n      \"#2505: 96.65%\\n\",\n      \"#2506: 96.65%\\n\",\n      \"#2507: 96.65%\\n\",\n      \"#2508: 96.65%\\n\",\n      \"#2509: 96.65%\\n\",\n      \"#2510: 96.65%\\n\",\n      \"#2511: 96.66%\\n\",\n      \"#2512: 96.66%\\n\",\n      \"#2513: 96.66%\\n\",\n      \"#2514: 96.66%\\n\",\n      \"#2515: 96.66%\\n\",\n      \"#2516: 96.66%\\n\",\n      \"#2517: 96.66%\\n\",\n      \"#2518: 96.67%\\n\",\n      \"#2519: 96.67%\\n\",\n      \"#2520: 96.67%\\n\",\n      \"#2521: 96.67%\\n\",\n      \"#2522: 96.67%\\n\",\n      \"#2523: 96.67%\\n\",\n      \"#2524: 96.67%\\n\",\n      \"#2525: 96.67%\\n\",\n      \"#2526: 96.68%\\n\",\n      \"#2527: 96.68%\\n\",\n      \"#2528: 96.68%\\n\",\n      \"#2529: 96.68%\\n\",\n      \"#2530: 96.68%\\n\",\n      \"#2531: 96.68%\\n\",\n      \"#2532: 96.68%\\n\",\n      \"#2533: 96.65%\\n\",\n      \"#2534: 96.61%\\n\",\n      \"#2535: 96.61%\\n\",\n      \"#2536: 96.61%\\n\",\n      \"#2537: 96.61%\\n\",\n      \"#2538: 96.61%\\n\",\n      \"#2539: 96.61%\\n\",\n      \"#2540: 96.62%\\n\",\n      \"#2541: 96.62%\\n\",\n      \"#2542: 96.62%\\n\",\n      \"#2543: 96.62%\\n\",\n      \"#2544: 96.62%\\n\",\n      \"#2545: 96.62%\\n\",\n      \"#2546: 96.62%\\n\",\n      \"#2547: 96.62%\\n\",\n      \"#2548: 96.63%\\n\",\n      \"#2549: 96.63%\\n\",\n      \"#2550: 96.63%\\n\",\n      \"#2551: 96.63%\\n\",\n      \"#2552: 96.63%\\n\",\n      \"#2553: 96.63%\\n\",\n      \"#2554: 96.63%\\n\",\n      \"#2555: 96.64%\\n\",\n      \"#2556: 96.64%\\n\",\n      \"#2557: 96.64%\\n\",\n      \"#2558: 96.64%\\n\",\n      \"#2559: 96.64%\\n\",\n      \"#2560: 96.60%\\n\",\n      \"#2561: 96.60%\\n\",\n      \"#2562: 96.61%\\n\",\n      \"#2563: 96.61%\\n\",\n      \"#2564: 96.61%\\n\",\n      \"#2565: 96.61%\\n\",\n      \"#2566: 96.61%\\n\",\n      \"#2567: 96.61%\\n\",\n      \"#2568: 96.61%\\n\",\n      \"#2569: 96.61%\\n\",\n      \"#2570: 96.62%\\n\",\n      \"#2571: 96.62%\\n\",\n      \"#2572: 96.62%\\n\",\n      \"#2573: 96.62%\\n\",\n      \"#2574: 96.62%\\n\",\n      \"#2575: 96.62%\\n\",\n      \"#2576: 96.62%\\n\",\n      \"#2577: 96.63%\\n\",\n      \"#2578: 96.63%\\n\",\n      \"#2579: 96.63%\\n\",\n      \"#2580: 96.63%\\n\",\n      \"#2581: 96.63%\\n\",\n      \"#2582: 96.63%\\n\",\n      \"#2583: 96.63%\\n\",\n      \"#2584: 96.63%\\n\",\n      \"#2585: 96.64%\\n\",\n      \"#2586: 96.64%\\n\",\n      \"#2587: 96.64%\\n\",\n      \"#2588: 96.64%\\n\",\n      \"#2589: 96.64%\\n\",\n      \"#2590: 96.64%\\n\",\n      \"#2591: 96.64%\\n\",\n      \"#2592: 96.64%\\n\",\n      \"#2593: 96.65%\\n\",\n      \"#2594: 96.61%\\n\",\n      \"#2595: 96.61%\\n\",\n      \"#2596: 96.61%\\n\",\n      \"#2597: 96.57%\\n\",\n      \"#2598: 96.58%\\n\",\n      \"#2599: 96.58%\\n\",\n      \"#2600: 96.58%\\n\",\n      \"#2601: 96.58%\\n\",\n      \"#2602: 96.58%\\n\",\n      \"#2603: 96.58%\\n\",\n      \"#2604: 96.58%\\n\",\n      \"#2605: 96.58%\\n\",\n      \"#2606: 96.59%\\n\",\n      \"#2607: 96.59%\\n\",\n      \"#2608: 96.59%\\n\",\n      \"#2609: 96.59%\\n\",\n      \"#2610: 96.59%\\n\",\n      \"#2611: 96.59%\\n\",\n      \"#2612: 96.59%\\n\",\n      \"#2613: 96.60%\\n\",\n      \"#2614: 96.60%\\n\",\n      \"#2615: 96.60%\\n\",\n      \"#2616: 96.60%\\n\",\n      \"#2617: 96.60%\\n\",\n      \"#2618: 96.60%\\n\",\n      \"#2619: 96.60%\\n\",\n      \"#2620: 96.60%\\n\",\n      \"#2621: 96.61%\\n\",\n      \"#2622: 96.61%\\n\",\n      \"#2623: 96.61%\\n\",\n      \"#2624: 96.61%\\n\",\n      \"#2625: 96.61%\\n\",\n      \"#2626: 96.61%\\n\",\n      \"#2627: 96.61%\\n\",\n      \"#2628: 96.61%\\n\",\n      \"#2629: 96.62%\\n\",\n      \"#2630: 96.62%\\n\",\n      \"#2631: 96.62%\\n\",\n      \"#2632: 96.62%\\n\",\n      \"#2633: 96.62%\\n\",\n      \"#2634: 96.62%\\n\",\n      \"#2635: 96.62%\\n\",\n      \"#2636: 96.59%\\n\",\n      \"#2637: 96.59%\\n\",\n      \"#2638: 96.59%\\n\",\n      \"#2639: 96.59%\\n\",\n      \"#2640: 96.59%\\n\",\n      \"#2641: 96.59%\\n\",\n      \"#2642: 96.59%\\n\",\n      \"#2643: 96.60%\\n\",\n      \"#2644: 96.60%\\n\",\n      \"#2645: 96.60%\\n\",\n      \"#2646: 96.60%\\n\",\n      \"#2647: 96.60%\\n\",\n      \"#2648: 96.60%\\n\",\n      \"#2649: 96.60%\\n\",\n      \"#2650: 96.61%\\n\",\n      \"#2651: 96.61%\\n\",\n      \"#2652: 96.61%\\n\",\n      \"#2653: 96.61%\\n\",\n      \"#2654: 96.57%\\n\",\n      \"#2655: 96.57%\\n\",\n      \"#2656: 96.58%\\n\",\n      \"#2657: 96.58%\\n\",\n      \"#2658: 96.58%\\n\",\n      \"#2659: 96.58%\\n\",\n      \"#2660: 96.58%\\n\",\n      \"#2661: 96.58%\\n\",\n      \"#2662: 96.58%\\n\",\n      \"#2663: 96.58%\\n\",\n      \"#2664: 96.59%\\n\",\n      \"#2665: 96.59%\\n\",\n      \"#2666: 96.59%\\n\",\n      \"#2667: 96.59%\\n\",\n      \"#2668: 96.59%\\n\",\n      \"#2669: 96.59%\\n\",\n      \"#2670: 96.59%\\n\",\n      \"#2671: 96.59%\\n\",\n      \"#2672: 96.60%\\n\",\n      \"#2673: 96.60%\\n\",\n      \"#2674: 96.60%\\n\",\n      \"#2675: 96.60%\\n\",\n      \"#2676: 96.60%\\n\",\n      \"#2677: 96.60%\\n\",\n      \"#2678: 96.60%\\n\",\n      \"#2679: 96.60%\\n\",\n      \"#2680: 96.61%\\n\",\n      \"#2681: 96.61%\\n\",\n      \"#2682: 96.61%\\n\",\n      \"#2683: 96.61%\\n\",\n      \"#2684: 96.61%\\n\",\n      \"#2685: 96.61%\\n\",\n      \"#2686: 96.61%\\n\",\n      \"#2687: 96.61%\\n\",\n      \"#2688: 96.62%\\n\",\n      \"#2689: 96.62%\\n\",\n      \"#2690: 96.62%\\n\",\n      \"#2691: 96.62%\\n\",\n      \"#2692: 96.62%\\n\",\n      \"#2693: 96.62%\\n\",\n      \"#2694: 96.62%\\n\",\n      \"#2695: 96.62%\\n\",\n      \"#2696: 96.63%\\n\",\n      \"#2697: 96.63%\\n\",\n      \"#2698: 96.63%\\n\",\n      \"#2699: 96.63%\\n\",\n      \"#2700: 96.63%\\n\",\n      \"#2701: 96.63%\\n\",\n      \"#2702: 96.63%\\n\",\n      \"#2703: 96.63%\\n\",\n      \"#2704: 96.64%\\n\",\n      \"#2705: 96.64%\\n\",\n      \"#2706: 96.64%\\n\",\n      \"#2707: 96.64%\\n\",\n      \"#2708: 96.64%\\n\",\n      \"#2709: 96.64%\\n\",\n      \"#2710: 96.64%\\n\",\n      \"#2711: 96.64%\\n\",\n      \"#2712: 96.65%\\n\",\n      \"#2713: 96.65%\\n\",\n      \"#2714: 96.65%\\n\",\n      \"#2715: 96.65%\\n\",\n      \"#2716: 96.65%\\n\",\n      \"#2717: 96.65%\\n\",\n      \"#2718: 96.65%\\n\",\n      \"#2719: 96.65%\\n\",\n      \"#2720: 96.66%\\n\",\n      \"#2721: 96.66%\\n\",\n      \"#2722: 96.66%\\n\",\n      \"#2723: 96.66%\\n\",\n      \"#2724: 96.66%\\n\",\n      \"#2725: 96.66%\\n\",\n      \"#2726: 96.66%\\n\",\n      \"#2727: 96.66%\\n\",\n      \"#2728: 96.67%\\n\",\n      \"#2729: 96.67%\\n\",\n      \"#2730: 96.67%\\n\",\n      \"#2731: 96.67%\\n\",\n      \"#2732: 96.67%\\n\",\n      \"#2733: 96.67%\\n\",\n      \"#2734: 96.67%\\n\",\n      \"#2735: 96.67%\\n\",\n      \"#2736: 96.68%\\n\",\n      \"#2737: 96.68%\\n\",\n      \"#2738: 96.68%\\n\",\n      \"#2739: 96.68%\\n\",\n      \"#2740: 96.68%\\n\",\n      \"#2741: 96.68%\\n\",\n      \"#2742: 96.68%\\n\",\n      \"#2743: 96.68%\\n\",\n      \"#2744: 96.68%\\n\",\n      \"#2745: 96.69%\\n\",\n      \"#2746: 96.69%\\n\",\n      \"#2747: 96.69%\\n\",\n      \"#2748: 96.69%\\n\",\n      \"#2749: 96.69%\\n\",\n      \"#2750: 96.69%\\n\",\n      \"#2751: 96.69%\\n\",\n      \"#2752: 96.69%\\n\",\n      \"#2753: 96.70%\\n\",\n      \"#2754: 96.70%\\n\",\n      \"#2755: 96.70%\\n\",\n      \"#2756: 96.70%\\n\",\n      \"#2757: 96.70%\\n\",\n      \"#2758: 96.70%\\n\",\n      \"#2759: 96.70%\\n\",\n      \"#2760: 96.67%\\n\",\n      \"#2761: 96.67%\\n\",\n      \"#2762: 96.67%\\n\",\n      \"#2763: 96.67%\\n\",\n      \"#2764: 96.67%\\n\",\n      \"#2765: 96.67%\\n\",\n      \"#2766: 96.68%\\n\",\n      \"#2767: 96.68%\\n\",\n      \"#2768: 96.68%\\n\",\n      \"#2769: 96.68%\\n\",\n      \"#2770: 96.64%\\n\",\n      \"#2771: 96.65%\\n\",\n      \"#2772: 96.65%\\n\",\n      \"#2773: 96.65%\\n\",\n      \"#2774: 96.65%\\n\",\n      \"#2775: 96.65%\\n\",\n      \"#2776: 96.65%\\n\",\n      \"#2777: 96.65%\\n\",\n      \"#2778: 96.62%\\n\",\n      \"#2779: 96.62%\\n\",\n      \"#2780: 96.58%\\n\",\n      \"#2781: 96.59%\\n\",\n      \"#2782: 96.59%\\n\",\n      \"#2783: 96.59%\\n\",\n      \"#2784: 96.59%\\n\",\n      \"#2785: 96.59%\\n\",\n      \"#2786: 96.59%\\n\",\n      \"#2787: 96.59%\\n\",\n      \"#2788: 96.59%\\n\",\n      \"#2789: 96.59%\\n\",\n      \"#2790: 96.60%\\n\",\n      \"#2791: 96.60%\\n\",\n      \"#2792: 96.60%\\n\",\n      \"#2793: 96.60%\\n\",\n      \"#2794: 96.60%\\n\",\n      \"#2795: 96.60%\\n\",\n      \"#2796: 96.60%\\n\",\n      \"#2797: 96.60%\\n\",\n      \"#2798: 96.61%\\n\",\n      \"#2799: 96.61%\\n\",\n      \"#2800: 96.61%\\n\",\n      \"#2801: 96.61%\\n\",\n      \"#2802: 96.61%\\n\",\n      \"#2803: 96.61%\\n\",\n      \"#2804: 96.61%\\n\",\n      \"#2805: 96.61%\\n\",\n      \"#2806: 96.62%\\n\",\n      \"#2807: 96.62%\\n\",\n      \"#2808: 96.62%\\n\",\n      \"#2809: 96.62%\\n\",\n      \"#2810: 96.62%\\n\",\n      \"#2811: 96.62%\\n\",\n      \"#2812: 96.62%\\n\",\n      \"#2813: 96.62%\\n\",\n      \"#2814: 96.63%\\n\",\n      \"#2815: 96.63%\\n\",\n      \"#2816: 96.63%\\n\",\n      \"#2817: 96.63%\\n\",\n      \"#2818: 96.63%\\n\",\n      \"#2819: 96.63%\\n\",\n      \"#2820: 96.63%\\n\",\n      \"#2821: 96.63%\\n\",\n      \"#2822: 96.63%\\n\",\n      \"#2823: 96.60%\\n\",\n      \"#2824: 96.60%\\n\",\n      \"#2825: 96.60%\\n\",\n      \"#2826: 96.60%\\n\",\n      \"#2827: 96.61%\\n\",\n      \"#2828: 96.61%\\n\",\n      \"#2829: 96.61%\\n\",\n      \"#2830: 96.61%\\n\",\n      \"#2831: 96.61%\\n\",\n      \"#2832: 96.61%\\n\",\n      \"#2833: 96.61%\\n\",\n      \"#2834: 96.61%\\n\",\n      \"#2835: 96.61%\\n\",\n      \"#2836: 96.62%\\n\",\n      \"#2837: 96.62%\\n\",\n      \"#2838: 96.62%\\n\",\n      \"#2839: 96.62%\\n\",\n      \"#2840: 96.62%\\n\",\n      \"#2841: 96.62%\\n\",\n      \"#2842: 96.62%\\n\",\n      \"#2843: 96.62%\\n\",\n      \"#2844: 96.63%\\n\",\n      \"#2845: 96.63%\\n\",\n      \"#2846: 96.63%\\n\",\n      \"#2847: 96.63%\\n\",\n      \"#2848: 96.63%\\n\",\n      \"#2849: 96.63%\\n\",\n      \"#2850: 96.63%\\n\",\n      \"#2851: 96.63%\\n\",\n      \"#2852: 96.64%\\n\",\n      \"#2853: 96.64%\\n\",\n      \"#2854: 96.64%\\n\",\n      \"#2855: 96.64%\\n\",\n      \"#2856: 96.64%\\n\",\n      \"#2857: 96.64%\\n\",\n      \"#2858: 96.64%\\n\",\n      \"#2859: 96.64%\\n\",\n      \"#2860: 96.64%\\n\",\n      \"#2861: 96.65%\\n\",\n      \"#2862: 96.65%\\n\",\n      \"#2863: 96.65%\\n\",\n      \"#2864: 96.65%\\n\",\n      \"#2865: 96.65%\\n\",\n      \"#2866: 96.65%\\n\",\n      \"#2867: 96.65%\\n\",\n      \"#2868: 96.65%\\n\",\n      \"#2869: 96.66%\\n\",\n      \"#2870: 96.66%\\n\",\n      \"#2871: 96.66%\\n\",\n      \"#2872: 96.66%\\n\",\n      \"#2873: 96.66%\\n\",\n      \"#2874: 96.66%\\n\",\n      \"#2875: 96.66%\\n\",\n      \"#2876: 96.66%\\n\",\n      \"#2877: 96.66%\\n\",\n      \"#2878: 96.67%\\n\",\n      \"#2879: 96.67%\\n\",\n      \"#2880: 96.67%\\n\",\n      \"#2881: 96.67%\\n\",\n      \"#2882: 96.67%\\n\",\n      \"#2883: 96.67%\\n\",\n      \"#2884: 96.67%\\n\",\n      \"#2885: 96.67%\\n\",\n      \"#2886: 96.67%\\n\",\n      \"#2887: 96.68%\\n\",\n      \"#2888: 96.68%\\n\",\n      \"#2889: 96.68%\\n\",\n      \"#2890: 96.68%\\n\",\n      \"#2891: 96.68%\\n\",\n      \"#2892: 96.68%\\n\",\n      \"#2893: 96.68%\\n\",\n      \"#2894: 96.68%\\n\",\n      \"#2895: 96.69%\\n\",\n      \"#2896: 96.65%\\n\",\n      \"#2897: 96.65%\\n\",\n      \"#2898: 96.65%\\n\",\n      \"#2899: 96.66%\\n\",\n      \"#2900: 96.66%\\n\",\n      \"#2901: 96.66%\\n\",\n      \"#2902: 96.66%\\n\",\n      \"#2903: 96.66%\\n\",\n      \"#2904: 96.66%\\n\",\n      \"#2905: 96.66%\\n\",\n      \"#2906: 96.66%\\n\",\n      \"#2907: 96.66%\\n\",\n      \"#2908: 96.67%\\n\",\n      \"#2909: 96.67%\\n\",\n      \"#2910: 96.67%\\n\",\n      \"#2911: 96.67%\\n\",\n      \"#2912: 96.67%\\n\",\n      \"#2913: 96.67%\\n\",\n      \"#2914: 96.67%\\n\",\n      \"#2915: 96.67%\\n\",\n      \"#2916: 96.67%\\n\",\n      \"#2917: 96.68%\\n\",\n      \"#2918: 96.68%\\n\",\n      \"#2919: 96.68%\\n\",\n      \"#2920: 96.68%\\n\",\n      \"#2921: 96.68%\\n\",\n      \"#2922: 96.68%\\n\",\n      \"#2923: 96.68%\\n\",\n      \"#2924: 96.68%\\n\",\n      \"#2925: 96.68%\\n\",\n      \"#2926: 96.69%\\n\",\n      \"#2927: 96.65%\\n\",\n      \"#2928: 96.65%\\n\",\n      \"#2929: 96.66%\\n\",\n      \"#2930: 96.66%\\n\",\n      \"#2931: 96.66%\\n\",\n      \"#2932: 96.66%\\n\",\n      \"#2933: 96.66%\\n\",\n      \"#2934: 96.66%\\n\",\n      \"#2935: 96.66%\\n\",\n      \"#2936: 96.66%\\n\",\n      \"#2937: 96.66%\\n\",\n      \"#2938: 96.67%\\n\",\n      \"#2939: 96.63%\\n\",\n      \"#2940: 96.63%\\n\",\n      \"#2941: 96.63%\\n\",\n      \"#2942: 96.64%\\n\",\n      \"#2943: 96.64%\\n\",\n      \"#2944: 96.64%\\n\",\n      \"#2945: 96.64%\\n\",\n      \"#2946: 96.64%\\n\",\n      \"#2947: 96.64%\\n\",\n      \"#2948: 96.64%\\n\",\n      \"#2949: 96.64%\\n\",\n      \"#2950: 96.65%\\n\",\n      \"#2951: 96.65%\\n\",\n      \"#2952: 96.61%\\n\",\n      \"#2953: 96.61%\\n\",\n      \"#2954: 96.62%\\n\",\n      \"#2955: 96.62%\\n\",\n      \"#2956: 96.62%\\n\",\n      \"#2957: 96.62%\\n\",\n      \"#2958: 96.62%\\n\",\n      \"#2959: 96.62%\\n\",\n      \"#2960: 96.62%\\n\",\n      \"#2961: 96.62%\\n\",\n      \"#2962: 96.63%\\n\",\n      \"#2963: 96.63%\\n\",\n      \"#2964: 96.63%\\n\",\n      \"#2965: 96.63%\\n\",\n      \"#2966: 96.63%\\n\",\n      \"#2967: 96.63%\\n\",\n      \"#2968: 96.63%\\n\",\n      \"#2969: 96.63%\\n\",\n      \"#2970: 96.63%\\n\",\n      \"#2971: 96.64%\\n\",\n      \"#2972: 96.64%\\n\",\n      \"#2973: 96.64%\\n\",\n      \"#2974: 96.64%\\n\",\n      \"#2975: 96.64%\\n\",\n      \"#2976: 96.64%\\n\",\n      \"#2977: 96.64%\\n\",\n      \"#2978: 96.64%\\n\",\n      \"#2979: 96.64%\\n\",\n      \"#2980: 96.65%\\n\",\n      \"#2981: 96.65%\\n\",\n      \"#2982: 96.65%\\n\",\n      \"#2983: 96.65%\\n\",\n      \"#2984: 96.65%\\n\",\n      \"#2985: 96.65%\\n\",\n      \"#2986: 96.65%\\n\",\n      \"#2987: 96.65%\\n\",\n      \"#2988: 96.65%\\n\",\n      \"#2989: 96.66%\\n\",\n      \"#2990: 96.66%\\n\",\n      \"#2991: 96.66%\\n\",\n      \"#2992: 96.66%\\n\",\n      \"#2993: 96.66%\\n\",\n      \"#2994: 96.66%\\n\",\n      \"#2995: 96.63%\\n\",\n      \"#2996: 96.63%\\n\",\n      \"#2997: 96.63%\\n\",\n      \"#2998: 96.63%\\n\",\n      \"#2999: 96.63%\\n\",\n      \"#3000: 96.63%\\n\",\n      \"#3001: 96.64%\\n\",\n      \"#3002: 96.64%\\n\",\n      \"#3003: 96.64%\\n\",\n      \"#3004: 96.64%\\n\",\n      \"#3005: 96.61%\\n\",\n      \"#3006: 96.61%\\n\",\n      \"#3007: 96.61%\\n\",\n      \"#3008: 96.61%\\n\",\n      \"#3009: 96.61%\\n\",\n      \"#3010: 96.61%\\n\",\n      \"#3011: 96.61%\\n\",\n      \"#3012: 96.61%\\n\",\n      \"#3013: 96.62%\\n\",\n      \"#3014: 96.62%\\n\",\n      \"#3015: 96.62%\\n\",\n      \"#3016: 96.62%\\n\",\n      \"#3017: 96.62%\\n\",\n      \"#3018: 96.62%\\n\",\n      \"#3019: 96.62%\\n\",\n      \"#3020: 96.62%\\n\",\n      \"#3021: 96.62%\\n\",\n      \"#3022: 96.63%\\n\",\n      \"#3023: 96.63%\\n\",\n      \"#3024: 96.63%\\n\",\n      \"#3025: 96.63%\\n\",\n      \"#3026: 96.63%\\n\",\n      \"#3027: 96.63%\\n\",\n      \"#3028: 96.63%\\n\",\n      \"#3029: 96.63%\\n\",\n      \"#3030: 96.60%\\n\",\n      \"#3031: 96.60%\\n\",\n      \"#3032: 96.60%\\n\",\n      \"#3033: 96.61%\\n\",\n      \"#3034: 96.61%\\n\",\n      \"#3035: 96.61%\\n\",\n      \"#3036: 96.61%\\n\",\n      \"#3037: 96.61%\\n\",\n      \"#3038: 96.61%\\n\",\n      \"#3039: 96.61%\\n\",\n      \"#3040: 96.61%\\n\",\n      \"#3041: 96.61%\\n\",\n      \"#3042: 96.62%\\n\",\n      \"#3043: 96.62%\\n\",\n      \"#3044: 96.62%\\n\",\n      \"#3045: 96.62%\\n\",\n      \"#3046: 96.62%\\n\",\n      \"#3047: 96.62%\\n\",\n      \"#3048: 96.62%\\n\",\n      \"#3049: 96.62%\\n\",\n      \"#3050: 96.62%\\n\",\n      \"#3051: 96.63%\\n\",\n      \"#3052: 96.63%\\n\",\n      \"#3053: 96.63%\\n\",\n      \"#3054: 96.63%\\n\",\n      \"#3055: 96.63%\\n\",\n      \"#3056: 96.63%\\n\",\n      \"#3057: 96.63%\\n\",\n      \"#3058: 96.63%\\n\",\n      \"#3059: 96.63%\\n\",\n      \"#3060: 96.60%\\n\",\n      \"#3061: 96.60%\\n\",\n      \"#3062: 96.60%\\n\",\n      \"#3063: 96.61%\\n\",\n      \"#3064: 96.61%\\n\",\n      \"#3065: 96.61%\\n\",\n      \"#3066: 96.61%\\n\",\n      \"#3067: 96.61%\\n\",\n      \"#3068: 96.61%\\n\",\n      \"#3069: 96.61%\\n\",\n      \"#3070: 96.61%\\n\",\n      \"#3071: 96.61%\\n\",\n      \"#3072: 96.62%\\n\",\n      \"#3073: 96.58%\\n\",\n      \"#3074: 96.59%\\n\",\n      \"#3075: 96.59%\\n\",\n      \"#3076: 96.59%\\n\",\n      \"#3077: 96.59%\\n\",\n      \"#3078: 96.59%\\n\",\n      \"#3079: 96.59%\\n\",\n      \"#3080: 96.59%\\n\",\n      \"#3081: 96.59%\\n\",\n      \"#3082: 96.59%\\n\",\n      \"#3083: 96.60%\\n\",\n      \"#3084: 96.60%\\n\",\n      \"#3085: 96.60%\\n\",\n      \"#3086: 96.60%\\n\",\n      \"#3087: 96.60%\\n\",\n      \"#3088: 96.60%\\n\",\n      \"#3089: 96.60%\\n\",\n      \"#3090: 96.60%\\n\",\n      \"#3091: 96.60%\\n\",\n      \"#3092: 96.61%\\n\",\n      \"#3093: 96.61%\\n\",\n      \"#3094: 96.61%\\n\",\n      \"#3095: 96.61%\\n\",\n      \"#3096: 96.61%\\n\",\n      \"#3097: 96.61%\\n\",\n      \"#3098: 96.61%\\n\",\n      \"#3099: 96.61%\\n\",\n      \"#3100: 96.61%\\n\",\n      \"#3101: 96.62%\\n\",\n      \"#3102: 96.62%\\n\",\n      \"#3103: 96.62%\\n\",\n      \"#3104: 96.62%\\n\",\n      \"#3105: 96.62%\\n\",\n      \"#3106: 96.62%\\n\",\n      \"#3107: 96.62%\\n\",\n      \"#3108: 96.62%\\n\",\n      \"#3109: 96.62%\\n\",\n      \"#3110: 96.62%\\n\",\n      \"#3111: 96.63%\\n\",\n      \"#3112: 96.63%\\n\",\n      \"#3113: 96.63%\\n\",\n      \"#3114: 96.60%\\n\",\n      \"#3115: 96.60%\\n\",\n      \"#3116: 96.60%\\n\",\n      \"#3117: 96.60%\\n\",\n      \"#3118: 96.60%\\n\",\n      \"#3119: 96.60%\\n\",\n      \"#3120: 96.60%\\n\",\n      \"#3121: 96.60%\\n\",\n      \"#3122: 96.61%\\n\",\n      \"#3123: 96.61%\\n\",\n      \"#3124: 96.61%\\n\",\n      \"#3125: 96.61%\\n\",\n      \"#3126: 96.61%\\n\",\n      \"#3127: 96.61%\\n\",\n      \"#3128: 96.61%\\n\",\n      \"#3129: 96.61%\\n\",\n      \"#3130: 96.61%\\n\",\n      \"#3131: 96.62%\\n\",\n      \"#3132: 96.62%\\n\",\n      \"#3133: 96.62%\\n\",\n      \"#3134: 96.62%\\n\",\n      \"#3135: 96.62%\\n\",\n      \"#3136: 96.62%\\n\",\n      \"#3137: 96.62%\\n\",\n      \"#3138: 96.62%\\n\",\n      \"#3139: 96.62%\\n\",\n      \"#3140: 96.63%\\n\",\n      \"#3141: 96.63%\\n\",\n      \"#3142: 96.63%\\n\",\n      \"#3143: 96.63%\\n\",\n      \"#3144: 96.63%\\n\",\n      \"#3145: 96.63%\\n\",\n      \"#3146: 96.63%\\n\",\n      \"#3147: 96.63%\\n\",\n      \"#3148: 96.63%\\n\",\n      \"#3149: 96.63%\\n\",\n      \"#3150: 96.64%\\n\",\n      \"#3151: 96.64%\\n\",\n      \"#3152: 96.64%\\n\",\n      \"#3153: 96.64%\\n\",\n      \"#3154: 96.64%\\n\",\n      \"#3155: 96.64%\\n\",\n      \"#3156: 96.64%\\n\",\n      \"#3157: 96.64%\\n\",\n      \"#3158: 96.64%\\n\",\n      \"#3159: 96.65%\\n\",\n      \"#3160: 96.65%\\n\",\n      \"#3161: 96.65%\\n\",\n      \"#3162: 96.65%\\n\",\n      \"#3163: 96.65%\\n\",\n      \"#3164: 96.65%\\n\",\n      \"#3165: 96.65%\\n\",\n      \"#3166: 96.65%\\n\",\n      \"#3167: 96.65%\\n\",\n      \"#3168: 96.66%\\n\",\n      \"#3169: 96.66%\\n\",\n      \"#3170: 96.66%\\n\",\n      \"#3171: 96.66%\\n\",\n      \"#3172: 96.66%\\n\",\n      \"#3173: 96.66%\\n\",\n      \"#3174: 96.66%\\n\",\n      \"#3175: 96.66%\\n\",\n      \"#3176: 96.66%\\n\",\n      \"#3177: 96.66%\\n\",\n      \"#3178: 96.67%\\n\",\n      \"#3179: 96.67%\\n\",\n      \"#3180: 96.67%\\n\",\n      \"#3181: 96.67%\\n\",\n      \"#3182: 96.67%\\n\",\n      \"#3183: 96.67%\\n\",\n      \"#3184: 96.67%\\n\",\n      \"#3185: 96.67%\\n\",\n      \"#3186: 96.67%\\n\",\n      \"#3187: 96.68%\\n\",\n      \"#3188: 96.68%\\n\",\n      \"#3189: 96.65%\\n\",\n      \"#3190: 96.65%\\n\",\n      \"#3191: 96.65%\\n\",\n      \"#3192: 96.65%\\n\",\n      \"#3193: 96.65%\\n\",\n      \"#3194: 96.65%\\n\",\n      \"#3195: 96.65%\\n\",\n      \"#3196: 96.65%\\n\",\n      \"#3197: 96.65%\\n\",\n      \"#3198: 96.66%\\n\",\n      \"#3199: 96.66%\\n\",\n      \"#3200: 96.66%\\n\",\n      \"#3201: 96.66%\\n\",\n      \"#3202: 96.66%\\n\",\n      \"#3203: 96.66%\\n\",\n      \"#3204: 96.66%\\n\",\n      \"#3205: 96.66%\\n\",\n      \"#3206: 96.66%\\n\",\n      \"#3207: 96.66%\\n\",\n      \"#3208: 96.67%\\n\",\n      \"#3209: 96.67%\\n\",\n      \"#3210: 96.67%\\n\",\n      \"#3211: 96.67%\\n\",\n      \"#3212: 96.67%\\n\",\n      \"#3213: 96.67%\\n\",\n      \"#3214: 96.67%\\n\",\n      \"#3215: 96.67%\\n\",\n      \"#3216: 96.67%\\n\",\n      \"#3217: 96.67%\\n\",\n      \"#3218: 96.68%\\n\",\n      \"#3219: 96.68%\\n\",\n      \"#3220: 96.68%\\n\",\n      \"#3221: 96.68%\\n\",\n      \"#3222: 96.68%\\n\",\n      \"#3223: 96.68%\\n\",\n      \"#3224: 96.68%\\n\",\n      \"#3225: 96.68%\\n\",\n      \"#3226: 96.68%\\n\",\n      \"#3227: 96.69%\\n\",\n      \"#3228: 96.69%\\n\",\n      \"#3229: 96.69%\\n\",\n      \"#3230: 96.69%\\n\",\n      \"#3231: 96.69%\\n\",\n      \"#3232: 96.69%\\n\",\n      \"#3233: 96.69%\\n\",\n      \"#3234: 96.69%\\n\",\n      \"#3235: 96.69%\\n\",\n      \"#3236: 96.69%\\n\",\n      \"#3237: 96.70%\\n\",\n      \"#3238: 96.70%\\n\",\n      \"#3239: 96.67%\\n\",\n      \"#3240: 96.67%\\n\",\n      \"#3241: 96.67%\\n\",\n      \"#3242: 96.67%\\n\",\n      \"#3243: 96.67%\\n\",\n      \"#3244: 96.67%\\n\",\n      \"#3245: 96.67%\\n\",\n      \"#3246: 96.64%\\n\",\n      \"#3247: 96.64%\\n\",\n      \"#3248: 96.65%\\n\",\n      \"#3249: 96.65%\\n\",\n      \"#3250: 96.65%\\n\",\n      \"#3251: 96.65%\\n\",\n      \"#3252: 96.65%\\n\",\n      \"#3253: 96.65%\\n\",\n      \"#3254: 96.65%\\n\",\n      \"#3255: 96.65%\\n\",\n      \"#3256: 96.65%\\n\",\n      \"#3257: 96.65%\\n\",\n      \"#3258: 96.66%\\n\",\n      \"#3259: 96.66%\\n\",\n      \"#3260: 96.66%\\n\",\n      \"#3261: 96.66%\\n\",\n      \"#3262: 96.63%\\n\",\n      \"#3263: 96.63%\\n\",\n      \"#3264: 96.63%\\n\",\n      \"#3265: 96.63%\\n\",\n      \"#3266: 96.63%\\n\",\n      \"#3267: 96.63%\\n\",\n      \"#3268: 96.64%\\n\",\n      \"#3269: 96.64%\\n\",\n      \"#3270: 96.64%\\n\",\n      \"#3271: 96.64%\\n\",\n      \"#3272: 96.64%\\n\",\n      \"#3273: 96.64%\\n\",\n      \"#3274: 96.64%\\n\",\n      \"#3275: 96.64%\\n\",\n      \"#3276: 96.64%\\n\",\n      \"#3277: 96.64%\\n\",\n      \"#3278: 96.65%\\n\",\n      \"#3279: 96.65%\\n\",\n      \"#3280: 96.65%\\n\",\n      \"#3281: 96.65%\\n\",\n      \"#3282: 96.65%\\n\",\n      \"#3283: 96.65%\\n\",\n      \"#3284: 96.65%\\n\",\n      \"#3285: 96.65%\\n\",\n      \"#3286: 96.65%\\n\",\n      \"#3287: 96.65%\\n\",\n      \"#3288: 96.66%\\n\",\n      \"#3289: 96.63%\\n\",\n      \"#3290: 96.63%\\n\",\n      \"#3291: 96.63%\\n\",\n      \"#3292: 96.63%\\n\",\n      \"#3293: 96.63%\\n\",\n      \"#3294: 96.63%\\n\",\n      \"#3295: 96.63%\\n\",\n      \"#3296: 96.63%\\n\",\n      \"#3297: 96.63%\\n\",\n      \"#3298: 96.64%\\n\",\n      \"#3299: 96.64%\\n\",\n      \"#3300: 96.64%\\n\",\n      \"#3301: 96.64%\\n\",\n      \"#3302: 96.64%\\n\",\n      \"#3303: 96.64%\\n\",\n      \"#3304: 96.64%\\n\",\n      \"#3305: 96.64%\\n\",\n      \"#3306: 96.64%\\n\",\n      \"#3307: 96.64%\\n\",\n      \"#3308: 96.65%\\n\",\n      \"#3309: 96.65%\\n\",\n      \"#3310: 96.65%\\n\",\n      \"#3311: 96.65%\\n\",\n      \"#3312: 96.65%\\n\",\n      \"#3313: 96.65%\\n\",\n      \"#3314: 96.65%\\n\",\n      \"#3315: 96.65%\\n\",\n      \"#3316: 96.62%\\n\",\n      \"#3317: 96.62%\\n\",\n      \"#3318: 96.63%\\n\",\n      \"#3319: 96.60%\\n\",\n      \"#3320: 96.60%\\n\",\n      \"#3321: 96.60%\\n\",\n      \"#3322: 96.60%\\n\",\n      \"#3323: 96.60%\\n\",\n      \"#3324: 96.60%\\n\",\n      \"#3325: 96.60%\\n\",\n      \"#3326: 96.60%\\n\",\n      \"#3327: 96.60%\\n\",\n      \"#3328: 96.61%\\n\",\n      \"#3329: 96.61%\\n\",\n      \"#3330: 96.61%\\n\",\n      \"#3331: 96.61%\\n\",\n      \"#3332: 96.61%\\n\",\n      \"#3333: 96.58%\\n\",\n      \"#3334: 96.58%\\n\",\n      \"#3335: 96.58%\\n\",\n      \"#3336: 96.58%\\n\",\n      \"#3337: 96.58%\\n\",\n      \"#3338: 96.59%\\n\",\n      \"#3339: 96.59%\\n\",\n      \"#3340: 96.59%\\n\",\n      \"#3341: 96.59%\\n\",\n      \"#3342: 96.59%\\n\",\n      \"#3343: 96.59%\\n\",\n      \"#3344: 96.59%\\n\",\n      \"#3345: 96.59%\\n\",\n      \"#3346: 96.59%\\n\",\n      \"#3347: 96.59%\\n\",\n      \"#3348: 96.60%\\n\",\n      \"#3349: 96.60%\\n\",\n      \"#3350: 96.60%\\n\",\n      \"#3351: 96.60%\\n\",\n      \"#3352: 96.60%\\n\",\n      \"#3353: 96.60%\\n\",\n      \"#3354: 96.60%\\n\",\n      \"#3355: 96.60%\\n\",\n      \"#3356: 96.60%\\n\",\n      \"#3357: 96.61%\\n\",\n      \"#3358: 96.61%\\n\",\n      \"#3359: 96.61%\\n\",\n      \"#3360: 96.61%\\n\",\n      \"#3361: 96.61%\\n\",\n      \"#3362: 96.61%\\n\",\n      \"#3363: 96.61%\\n\",\n      \"#3364: 96.61%\\n\",\n      \"#3365: 96.61%\\n\",\n      \"#3366: 96.61%\\n\",\n      \"#3367: 96.62%\\n\",\n      \"#3368: 96.62%\\n\",\n      \"#3369: 96.62%\\n\",\n      \"#3370: 96.62%\\n\",\n      \"#3371: 96.62%\\n\",\n      \"#3372: 96.62%\\n\",\n      \"#3373: 96.62%\\n\",\n      \"#3374: 96.62%\\n\",\n      \"#3375: 96.62%\\n\",\n      \"#3376: 96.62%\\n\",\n      \"#3377: 96.63%\\n\",\n      \"#3378: 96.63%\\n\",\n      \"#3379: 96.63%\\n\",\n      \"#3380: 96.63%\\n\",\n      \"#3381: 96.63%\\n\",\n      \"#3382: 96.63%\\n\",\n      \"#3383: 96.63%\\n\",\n      \"#3384: 96.63%\\n\",\n      \"#3385: 96.63%\\n\",\n      \"#3386: 96.63%\\n\",\n      \"#3387: 96.64%\\n\",\n      \"#3388: 96.64%\\n\",\n      \"#3389: 96.64%\\n\",\n      \"#3390: 96.64%\\n\",\n      \"#3391: 96.64%\\n\",\n      \"#3392: 96.64%\\n\",\n      \"#3393: 96.64%\\n\",\n      \"#3394: 96.64%\\n\",\n      \"#3395: 96.64%\\n\",\n      \"#3396: 96.64%\\n\",\n      \"#3397: 96.65%\\n\",\n      \"#3398: 96.65%\\n\",\n      \"#3399: 96.65%\\n\",\n      \"#3400: 96.65%\\n\",\n      \"#3401: 96.65%\\n\",\n      \"#3402: 96.65%\\n\",\n      \"#3403: 96.65%\\n\",\n      \"#3404: 96.65%\\n\",\n      \"#3405: 96.65%\\n\",\n      \"#3406: 96.65%\\n\",\n      \"#3407: 96.65%\\n\",\n      \"#3408: 96.66%\\n\",\n      \"#3409: 96.66%\\n\",\n      \"#3410: 96.66%\\n\",\n      \"#3411: 96.66%\\n\",\n      \"#3412: 96.66%\\n\",\n      \"#3413: 96.66%\\n\",\n      \"#3414: 96.66%\\n\",\n      \"#3415: 96.66%\\n\",\n      \"#3416: 96.66%\\n\",\n      \"#3417: 96.66%\\n\",\n      \"#3418: 96.67%\\n\",\n      \"#3419: 96.67%\\n\",\n      \"#3420: 96.67%\\n\",\n      \"#3421: 96.67%\\n\",\n      \"#3422: 96.67%\\n\",\n      \"#3423: 96.67%\\n\",\n      \"#3424: 96.67%\\n\",\n      \"#3425: 96.67%\\n\",\n      \"#3426: 96.67%\\n\",\n      \"#3427: 96.67%\\n\",\n      \"#3428: 96.68%\\n\",\n      \"#3429: 96.68%\\n\",\n      \"#3430: 96.68%\\n\",\n      \"#3431: 96.68%\\n\",\n      \"#3432: 96.68%\\n\",\n      \"#3433: 96.68%\\n\",\n      \"#3434: 96.68%\\n\",\n      \"#3435: 96.68%\\n\",\n      \"#3436: 96.68%\\n\",\n      \"#3437: 96.68%\\n\",\n      \"#3438: 96.69%\\n\",\n      \"#3439: 96.69%\\n\",\n      \"#3440: 96.69%\\n\",\n      \"#3441: 96.69%\\n\",\n      \"#3442: 96.69%\\n\",\n      \"#3443: 96.69%\\n\",\n      \"#3444: 96.69%\\n\",\n      \"#3445: 96.69%\\n\",\n      \"#3446: 96.69%\\n\",\n      \"#3447: 96.69%\\n\",\n      \"#3448: 96.69%\\n\",\n      \"#3449: 96.70%\\n\",\n      \"#3450: 96.70%\\n\",\n      \"#3451: 96.70%\\n\",\n      \"#3452: 96.70%\\n\",\n      \"#3453: 96.70%\\n\",\n      \"#3454: 96.70%\\n\",\n      \"#3455: 96.70%\\n\",\n      \"#3456: 96.70%\\n\",\n      \"#3457: 96.70%\\n\",\n      \"#3458: 96.70%\\n\",\n      \"#3459: 96.71%\\n\",\n      \"#3460: 96.71%\\n\",\n      \"#3461: 96.71%\\n\",\n      \"#3462: 96.71%\\n\",\n      \"#3463: 96.71%\\n\",\n      \"#3464: 96.71%\\n\",\n      \"#3465: 96.71%\\n\",\n      \"#3466: 96.71%\\n\",\n      \"#3467: 96.71%\\n\",\n      \"#3468: 96.71%\\n\",\n      \"#3469: 96.71%\\n\",\n      \"#3470: 96.72%\\n\",\n      \"#3471: 96.72%\\n\",\n      \"#3472: 96.72%\\n\",\n      \"#3473: 96.72%\\n\",\n      \"#3474: 96.72%\\n\",\n      \"#3475: 96.72%\\n\",\n      \"#3476: 96.72%\\n\",\n      \"#3477: 96.72%\\n\",\n      \"#3478: 96.72%\\n\",\n      \"#3479: 96.72%\\n\",\n      \"#3480: 96.73%\\n\",\n      \"#3481: 96.73%\\n\",\n      \"#3482: 96.73%\\n\",\n      \"#3483: 96.73%\\n\",\n      \"#3484: 96.73%\\n\",\n      \"#3485: 96.73%\\n\",\n      \"#3486: 96.73%\\n\",\n      \"#3487: 96.73%\\n\",\n      \"#3488: 96.73%\\n\",\n      \"#3489: 96.73%\\n\",\n      \"#3490: 96.73%\\n\",\n      \"#3491: 96.74%\\n\",\n      \"#3492: 96.74%\\n\",\n      \"#3493: 96.74%\\n\",\n      \"#3494: 96.74%\\n\",\n      \"#3495: 96.74%\\n\",\n      \"#3496: 96.74%\\n\",\n      \"#3497: 96.74%\\n\",\n      \"#3498: 96.74%\\n\",\n      \"#3499: 96.74%\\n\",\n      \"#3500: 96.74%\\n\",\n      \"#3501: 96.74%\\n\",\n      \"#3502: 96.75%\\n\",\n      \"#3503: 96.72%\\n\",\n      \"#3504: 96.72%\\n\",\n      \"#3505: 96.72%\\n\",\n      \"#3506: 96.72%\\n\",\n      \"#3507: 96.72%\\n\",\n      \"#3508: 96.72%\\n\",\n      \"#3509: 96.72%\\n\",\n      \"#3510: 96.72%\\n\",\n      \"#3511: 96.73%\\n\",\n      \"#3512: 96.73%\\n\",\n      \"#3513: 96.73%\\n\",\n      \"#3514: 96.73%\\n\",\n      \"#3515: 96.73%\\n\",\n      \"#3516: 96.73%\\n\",\n      \"#3517: 96.73%\\n\",\n      \"#3518: 96.73%\\n\",\n      \"#3519: 96.73%\\n\",\n      \"#3520: 96.71%\\n\",\n      \"#3521: 96.71%\\n\",\n      \"#3522: 96.71%\\n\",\n      \"#3523: 96.71%\\n\",\n      \"#3524: 96.71%\\n\",\n      \"#3525: 96.71%\\n\",\n      \"#3526: 96.71%\\n\",\n      \"#3527: 96.71%\\n\",\n      \"#3528: 96.71%\\n\",\n      \"#3529: 96.71%\\n\",\n      \"#3530: 96.71%\\n\",\n      \"#3531: 96.72%\\n\",\n      \"#3532: 96.72%\\n\",\n      \"#3533: 96.72%\\n\",\n      \"#3534: 96.72%\\n\",\n      \"#3535: 96.72%\\n\",\n      \"#3536: 96.72%\\n\",\n      \"#3537: 96.72%\\n\",\n      \"#3538: 96.72%\\n\",\n      \"#3539: 96.72%\\n\",\n      \"#3540: 96.72%\\n\",\n      \"#3541: 96.73%\\n\",\n      \"#3542: 96.73%\\n\",\n      \"#3543: 96.73%\\n\",\n      \"#3544: 96.73%\\n\",\n      \"#3545: 96.73%\\n\",\n      \"#3546: 96.73%\\n\",\n      \"#3547: 96.73%\\n\",\n      \"#3548: 96.73%\\n\",\n      \"#3549: 96.73%\\n\",\n      \"#3550: 96.73%\\n\",\n      \"#3551: 96.73%\\n\",\n      \"#3552: 96.74%\\n\",\n      \"#3553: 96.74%\\n\",\n      \"#3554: 96.74%\\n\",\n      \"#3555: 96.74%\\n\",\n      \"#3556: 96.74%\\n\",\n      \"#3557: 96.74%\\n\",\n      \"#3558: 96.74%\\n\",\n      \"#3559: 96.71%\\n\",\n      \"#3560: 96.71%\\n\",\n      \"#3561: 96.72%\\n\",\n      \"#3562: 96.72%\\n\",\n      \"#3563: 96.72%\\n\",\n      \"#3564: 96.72%\\n\",\n      \"#3565: 96.72%\\n\",\n      \"#3566: 96.72%\\n\",\n      \"#3567: 96.72%\\n\",\n      \"#3568: 96.72%\\n\",\n      \"#3569: 96.72%\\n\",\n      \"#3570: 96.72%\\n\",\n      \"#3571: 96.72%\\n\",\n      \"#3572: 96.73%\\n\",\n      \"#3573: 96.73%\\n\",\n      \"#3574: 96.73%\\n\",\n      \"#3575: 96.73%\\n\",\n      \"#3576: 96.73%\\n\",\n      \"#3577: 96.73%\\n\",\n      \"#3578: 96.73%\\n\",\n      \"#3579: 96.73%\\n\",\n      \"#3580: 96.73%\\n\",\n      \"#3581: 96.73%\\n\",\n      \"#3582: 96.73%\\n\",\n      \"#3583: 96.74%\\n\",\n      \"#3584: 96.74%\\n\",\n      \"#3585: 96.74%\\n\",\n      \"#3586: 96.74%\\n\",\n      \"#3587: 96.74%\\n\",\n      \"#3588: 96.74%\\n\",\n      \"#3589: 96.74%\\n\",\n      \"#3590: 96.74%\\n\",\n      \"#3591: 96.74%\\n\",\n      \"#3592: 96.74%\\n\",\n      \"#3593: 96.74%\\n\",\n      \"#3594: 96.75%\\n\",\n      \"#3595: 96.75%\\n\",\n      \"#3596: 96.75%\\n\",\n      \"#3597: 96.72%\\n\",\n      \"#3598: 96.72%\\n\",\n      \"#3599: 96.72%\\n\",\n      \"#3600: 96.72%\\n\",\n      \"#3601: 96.72%\\n\",\n      \"#3602: 96.72%\\n\",\n      \"#3603: 96.73%\\n\",\n      \"#3604: 96.73%\\n\",\n      \"#3605: 96.73%\\n\",\n      \"#3606: 96.73%\\n\",\n      \"#3607: 96.73%\\n\",\n      \"#3608: 96.73%\\n\",\n      \"#3609: 96.73%\\n\",\n      \"#3610: 96.73%\\n\",\n      \"#3611: 96.73%\\n\",\n      \"#3612: 96.73%\\n\",\n      \"#3613: 96.73%\\n\",\n      \"#3614: 96.74%\\n\",\n      \"#3615: 96.74%\\n\",\n      \"#3616: 96.74%\\n\",\n      \"#3617: 96.74%\\n\",\n      \"#3618: 96.74%\\n\",\n      \"#3619: 96.74%\\n\",\n      \"#3620: 96.74%\\n\",\n      \"#3621: 96.74%\\n\",\n      \"#3622: 96.74%\\n\",\n      \"#3623: 96.74%\\n\",\n      \"#3624: 96.74%\\n\",\n      \"#3625: 96.75%\\n\",\n      \"#3626: 96.75%\\n\",\n      \"#3627: 96.75%\\n\",\n      \"#3628: 96.75%\\n\",\n      \"#3629: 96.75%\\n\",\n      \"#3630: 96.75%\\n\",\n      \"#3631: 96.75%\\n\",\n      \"#3632: 96.75%\\n\",\n      \"#3633: 96.75%\\n\",\n      \"#3634: 96.75%\\n\",\n      \"#3635: 96.75%\\n\",\n      \"#3636: 96.76%\\n\",\n      \"#3637: 96.76%\\n\",\n      \"#3638: 96.76%\\n\",\n      \"#3639: 96.76%\\n\",\n      \"#3640: 96.76%\\n\",\n      \"#3641: 96.76%\\n\",\n      \"#3642: 96.76%\\n\",\n      \"#3643: 96.76%\\n\",\n      \"#3644: 96.76%\\n\",\n      \"#3645: 96.76%\\n\",\n      \"#3646: 96.76%\\n\",\n      \"#3647: 96.77%\\n\",\n      \"#3648: 96.77%\\n\",\n      \"#3649: 96.77%\\n\",\n      \"#3650: 96.77%\\n\",\n      \"#3651: 96.77%\\n\",\n      \"#3652: 96.77%\\n\",\n      \"#3653: 96.77%\\n\",\n      \"#3654: 96.77%\\n\",\n      \"#3655: 96.77%\\n\",\n      \"#3656: 96.77%\\n\",\n      \"#3657: 96.77%\\n\",\n      \"#3658: 96.78%\\n\",\n      \"#3659: 96.78%\\n\",\n      \"#3660: 96.78%\\n\",\n      \"#3661: 96.78%\\n\",\n      \"#3662: 96.78%\\n\",\n      \"#3663: 96.78%\\n\",\n      \"#3664: 96.78%\\n\",\n      \"#3665: 96.78%\\n\",\n      \"#3666: 96.78%\\n\",\n      \"#3667: 96.78%\\n\",\n      \"#3668: 96.78%\\n\",\n      \"#3669: 96.78%\\n\",\n      \"#3670: 96.79%\\n\",\n      \"#3671: 96.79%\\n\",\n      \"#3672: 96.79%\\n\",\n      \"#3673: 96.79%\\n\",\n      \"#3674: 96.79%\\n\",\n      \"#3675: 96.79%\\n\",\n      \"#3676: 96.79%\\n\",\n      \"#3677: 96.79%\\n\",\n      \"#3678: 96.79%\\n\",\n      \"#3679: 96.79%\\n\",\n      \"#3680: 96.79%\\n\",\n      \"#3681: 96.80%\\n\",\n      \"#3682: 96.80%\\n\",\n      \"#3683: 96.80%\\n\",\n      \"#3684: 96.80%\\n\",\n      \"#3685: 96.80%\\n\",\n      \"#3686: 96.80%\\n\",\n      \"#3687: 96.80%\\n\",\n      \"#3688: 96.80%\\n\",\n      \"#3689: 96.80%\\n\",\n      \"#3690: 96.80%\\n\",\n      \"#3691: 96.80%\\n\",\n      \"#3692: 96.80%\\n\",\n      \"#3693: 96.81%\\n\",\n      \"#3694: 96.81%\\n\",\n      \"#3695: 96.81%\\n\",\n      \"#3696: 96.81%\\n\",\n      \"#3697: 96.81%\\n\",\n      \"#3698: 96.81%\\n\",\n      \"#3699: 96.81%\\n\",\n      \"#3700: 96.81%\\n\",\n      \"#3701: 96.81%\\n\",\n      \"#3702: 96.81%\\n\",\n      \"#3703: 96.81%\\n\",\n      \"#3704: 96.82%\\n\",\n      \"#3705: 96.82%\\n\",\n      \"#3706: 96.82%\\n\",\n      \"#3707: 96.82%\\n\",\n      \"#3708: 96.82%\\n\",\n      \"#3709: 96.82%\\n\",\n      \"#3710: 96.82%\\n\",\n      \"#3711: 96.82%\\n\",\n      \"#3712: 96.82%\\n\",\n      \"#3713: 96.82%\\n\",\n      \"#3714: 96.82%\\n\",\n      \"#3715: 96.82%\\n\",\n      \"#3716: 96.83%\\n\",\n      \"#3717: 96.83%\\n\",\n      \"#3718: 96.83%\\n\",\n      \"#3719: 96.83%\\n\",\n      \"#3720: 96.83%\\n\",\n      \"#3721: 96.83%\\n\",\n      \"#3722: 96.83%\\n\",\n      \"#3723: 96.83%\\n\",\n      \"#3724: 96.83%\\n\",\n      \"#3725: 96.83%\\n\",\n      \"#3726: 96.81%\\n\",\n      \"#3727: 96.81%\\n\",\n      \"#3728: 96.81%\\n\",\n      \"#3729: 96.81%\\n\",\n      \"#3730: 96.81%\\n\",\n      \"#3731: 96.81%\\n\",\n      \"#3732: 96.81%\\n\",\n      \"#3733: 96.81%\\n\",\n      \"#3734: 96.81%\\n\",\n      \"#3735: 96.81%\\n\",\n      \"#3736: 96.82%\\n\",\n      \"#3737: 96.82%\\n\",\n      \"#3738: 96.79%\\n\",\n      \"#3739: 96.79%\\n\",\n      \"#3740: 96.79%\\n\",\n      \"#3741: 96.79%\\n\",\n      \"#3742: 96.79%\\n\",\n      \"#3743: 96.79%\\n\",\n      \"#3744: 96.80%\\n\",\n      \"#3745: 96.80%\\n\",\n      \"#3746: 96.80%\\n\",\n      \"#3747: 96.80%\\n\",\n      \"#3748: 96.80%\\n\",\n      \"#3749: 96.80%\\n\",\n      \"#3750: 96.80%\\n\",\n      \"#3751: 96.80%\\n\",\n      \"#3752: 96.80%\\n\",\n      \"#3753: 96.80%\\n\",\n      \"#3754: 96.80%\\n\",\n      \"#3755: 96.81%\\n\",\n      \"#3756: 96.81%\\n\",\n      \"#3757: 96.78%\\n\",\n      \"#3758: 96.78%\\n\",\n      \"#3759: 96.78%\\n\",\n      \"#3760: 96.78%\\n\",\n      \"#3761: 96.78%\\n\",\n      \"#3762: 96.78%\\n\",\n      \"#3763: 96.79%\\n\",\n      \"#3764: 96.79%\\n\",\n      \"#3765: 96.79%\\n\",\n      \"#3766: 96.79%\\n\",\n      \"#3767: 96.76%\\n\",\n      \"#3768: 96.76%\\n\",\n      \"#3769: 96.76%\\n\",\n      \"#3770: 96.76%\\n\",\n      \"#3771: 96.77%\\n\",\n      \"#3772: 96.77%\\n\",\n      \"#3773: 96.77%\\n\",\n      \"#3774: 96.77%\\n\",\n      \"#3775: 96.77%\\n\",\n      \"#3776: 96.77%\\n\",\n      \"#3777: 96.77%\\n\",\n      \"#3778: 96.77%\\n\",\n      \"#3779: 96.77%\\n\",\n      \"#3780: 96.75%\\n\",\n      \"#3781: 96.75%\\n\",\n      \"#3782: 96.75%\\n\",\n      \"#3783: 96.75%\\n\",\n      \"#3784: 96.75%\\n\",\n      \"#3785: 96.75%\\n\",\n      \"#3786: 96.75%\\n\",\n      \"#3787: 96.75%\\n\",\n      \"#3788: 96.75%\\n\",\n      \"#3789: 96.75%\\n\",\n      \"#3790: 96.76%\\n\",\n      \"#3791: 96.76%\\n\",\n      \"#3792: 96.76%\\n\",\n      \"#3793: 96.76%\\n\",\n      \"#3794: 96.76%\\n\",\n      \"#3795: 96.76%\\n\",\n      \"#3796: 96.76%\\n\",\n      \"#3797: 96.76%\\n\",\n      \"#3798: 96.76%\\n\",\n      \"#3799: 96.76%\\n\",\n      \"#3800: 96.76%\\n\",\n      \"#3801: 96.76%\\n\",\n      \"#3802: 96.77%\\n\",\n      \"#3803: 96.77%\\n\",\n      \"#3804: 96.77%\\n\",\n      \"#3805: 96.77%\\n\",\n      \"#3806: 96.77%\\n\",\n      \"#3807: 96.77%\\n\",\n      \"#3808: 96.74%\\n\",\n      \"#3809: 96.75%\\n\",\n      \"#3810: 96.75%\\n\",\n      \"#3811: 96.75%\\n\",\n      \"#3812: 96.75%\\n\",\n      \"#3813: 96.75%\\n\",\n      \"#3814: 96.75%\\n\",\n      \"#3815: 96.75%\\n\",\n      \"#3816: 96.75%\\n\",\n      \"#3817: 96.75%\\n\",\n      \"#3818: 96.75%\\n\",\n      \"#3819: 96.75%\\n\",\n      \"#3820: 96.75%\\n\",\n      \"#3821: 96.76%\\n\",\n      \"#3822: 96.76%\\n\",\n      \"#3823: 96.76%\\n\",\n      \"#3824: 96.76%\\n\",\n      \"#3825: 96.76%\\n\",\n      \"#3826: 96.76%\\n\",\n      \"#3827: 96.76%\\n\",\n      \"#3828: 96.76%\\n\",\n      \"#3829: 96.76%\\n\",\n      \"#3830: 96.76%\\n\",\n      \"#3831: 96.76%\\n\",\n      \"#3832: 96.76%\\n\",\n      \"#3833: 96.77%\\n\",\n      \"#3834: 96.77%\\n\",\n      \"#3835: 96.77%\\n\",\n      \"#3836: 96.77%\\n\",\n      \"#3837: 96.77%\\n\",\n      \"#3838: 96.77%\\n\",\n      \"#3839: 96.77%\\n\",\n      \"#3840: 96.77%\\n\",\n      \"#3841: 96.77%\\n\",\n      \"#3842: 96.77%\\n\",\n      \"#3843: 96.77%\\n\",\n      \"#3844: 96.78%\\n\",\n      \"#3845: 96.78%\\n\",\n      \"#3846: 96.78%\\n\",\n      \"#3847: 96.78%\\n\",\n      \"#3848: 96.78%\\n\",\n      \"#3849: 96.78%\\n\",\n      \"#3850: 96.75%\\n\",\n      \"#3851: 96.75%\\n\",\n      \"#3852: 96.76%\\n\",\n      \"#3853: 96.76%\\n\",\n      \"#3854: 96.76%\\n\",\n      \"#3855: 96.73%\\n\",\n      \"#3856: 96.73%\\n\",\n      \"#3857: 96.73%\\n\",\n      \"#3858: 96.73%\\n\",\n      \"#3859: 96.74%\\n\",\n      \"#3860: 96.74%\\n\",\n      \"#3861: 96.74%\\n\",\n      \"#3862: 96.74%\\n\",\n      \"#3863: 96.74%\\n\",\n      \"#3864: 96.74%\\n\",\n      \"#3865: 96.74%\\n\",\n      \"#3866: 96.74%\\n\",\n      \"#3867: 96.74%\\n\",\n      \"#3868: 96.74%\\n\",\n      \"#3869: 96.74%\\n\",\n      \"#3870: 96.75%\\n\",\n      \"#3871: 96.75%\\n\",\n      \"#3872: 96.75%\\n\",\n      \"#3873: 96.75%\\n\",\n      \"#3874: 96.75%\\n\",\n      \"#3875: 96.75%\\n\",\n      \"#3876: 96.75%\\n\",\n      \"#3877: 96.75%\\n\",\n      \"#3878: 96.75%\\n\",\n      \"#3879: 96.75%\\n\",\n      \"#3880: 96.75%\\n\",\n      \"#3881: 96.75%\\n\",\n      \"#3882: 96.76%\\n\",\n      \"#3883: 96.76%\\n\",\n      \"#3884: 96.76%\\n\",\n      \"#3885: 96.76%\\n\",\n      \"#3886: 96.76%\\n\",\n      \"#3887: 96.76%\\n\",\n      \"#3888: 96.76%\\n\",\n      \"#3889: 96.76%\\n\",\n      \"#3890: 96.76%\\n\",\n      \"#3891: 96.76%\\n\",\n      \"#3892: 96.76%\\n\",\n      \"#3893: 96.76%\\n\",\n      \"#3894: 96.77%\\n\",\n      \"#3895: 96.77%\\n\",\n      \"#3896: 96.77%\\n\",\n      \"#3897: 96.77%\\n\",\n      \"#3898: 96.77%\\n\",\n      \"#3899: 96.77%\\n\",\n      \"#3900: 96.77%\\n\",\n      \"#3901: 96.77%\\n\",\n      \"#3902: 96.77%\\n\",\n      \"#3903: 96.77%\\n\",\n      \"#3904: 96.77%\\n\",\n      \"#3905: 96.77%\\n\",\n      \"#3906: 96.75%\\n\",\n      \"#3907: 96.75%\\n\",\n      \"#3908: 96.75%\\n\",\n      \"#3909: 96.75%\\n\",\n      \"#3910: 96.75%\\n\",\n      \"#3911: 96.75%\\n\",\n      \"#3912: 96.75%\\n\",\n      \"#3913: 96.76%\\n\",\n      \"#3914: 96.76%\\n\",\n      \"#3915: 96.76%\\n\",\n      \"#3916: 96.76%\\n\",\n      \"#3917: 96.76%\\n\",\n      \"#3918: 96.76%\\n\",\n      \"#3919: 96.76%\\n\",\n      \"#3920: 96.76%\\n\",\n      \"#3921: 96.76%\\n\",\n      \"#3922: 96.76%\\n\",\n      \"#3923: 96.76%\\n\",\n      \"#3924: 96.76%\\n\",\n      \"#3925: 96.77%\\n\",\n      \"#3926: 96.77%\\n\",\n      \"#3927: 96.77%\\n\",\n      \"#3928: 96.77%\\n\",\n      \"#3929: 96.77%\\n\",\n      \"#3930: 96.77%\\n\",\n      \"#3931: 96.77%\\n\",\n      \"#3932: 96.77%\\n\",\n      \"#3933: 96.77%\\n\",\n      \"#3934: 96.77%\\n\",\n      \"#3935: 96.77%\\n\",\n      \"#3936: 96.77%\\n\",\n      \"#3937: 96.78%\\n\",\n      \"#3938: 96.78%\\n\",\n      \"#3939: 96.78%\\n\",\n      \"#3940: 96.78%\\n\",\n      \"#3941: 96.78%\\n\",\n      \"#3942: 96.78%\\n\",\n      \"#3943: 96.75%\\n\",\n      \"#3944: 96.76%\\n\",\n      \"#3945: 96.76%\\n\",\n      \"#3946: 96.76%\\n\",\n      \"#3947: 96.76%\\n\",\n      \"#3948: 96.76%\\n\",\n      \"#3949: 96.76%\\n\",\n      \"#3950: 96.76%\\n\",\n      \"#3951: 96.76%\\n\",\n      \"#3952: 96.76%\\n\",\n      \"#3953: 96.76%\\n\",\n      \"#3954: 96.76%\\n\",\n      \"#3955: 96.76%\\n\",\n      \"#3956: 96.77%\\n\",\n      \"#3957: 96.77%\\n\",\n      \"#3958: 96.77%\\n\",\n      \"#3959: 96.77%\\n\",\n      \"#3960: 96.77%\\n\",\n      \"#3961: 96.77%\\n\",\n      \"#3962: 96.77%\\n\",\n      \"#3963: 96.77%\\n\",\n      \"#3964: 96.77%\\n\",\n      \"#3965: 96.77%\\n\",\n      \"#3966: 96.77%\\n\",\n      \"#3967: 96.77%\\n\",\n      \"#3968: 96.78%\\n\",\n      \"#3969: 96.78%\\n\",\n      \"#3970: 96.78%\\n\",\n      \"#3971: 96.78%\\n\",\n      \"#3972: 96.78%\\n\",\n      \"#3973: 96.78%\\n\",\n      \"#3974: 96.78%\\n\",\n      \"#3975: 96.78%\\n\",\n      \"#3976: 96.76%\\n\",\n      \"#3977: 96.76%\\n\",\n      \"#3978: 96.76%\\n\",\n      \"#3979: 96.76%\\n\",\n      \"#3980: 96.76%\\n\",\n      \"#3981: 96.76%\\n\",\n      \"#3982: 96.76%\\n\",\n      \"#3983: 96.76%\\n\",\n      \"#3984: 96.76%\\n\",\n      \"#3985: 96.76%\\n\",\n      \"#3986: 96.76%\\n\",\n      \"#3987: 96.77%\\n\",\n      \"#3988: 96.77%\\n\",\n      \"#3989: 96.77%\\n\",\n      \"#3990: 96.77%\\n\",\n      \"#3991: 96.77%\\n\",\n      \"#3992: 96.77%\\n\",\n      \"#3993: 96.77%\\n\",\n      \"#3994: 96.77%\\n\",\n      \"#3995: 96.77%\\n\",\n      \"#3996: 96.77%\\n\",\n      \"#3997: 96.77%\\n\",\n      \"#3998: 96.77%\\n\",\n      \"#3999: 96.78%\\n\",\n      \"#4000: 96.78%\\n\",\n      \"#4001: 96.78%\\n\",\n      \"#4002: 96.78%\\n\",\n      \"#4003: 96.78%\\n\",\n      \"#4004: 96.78%\\n\",\n      \"#4005: 96.78%\\n\",\n      \"#4006: 96.78%\\n\",\n      \"#4007: 96.78%\\n\",\n      \"#4008: 96.78%\\n\",\n      \"#4009: 96.78%\\n\",\n      \"#4010: 96.78%\\n\",\n      \"#4011: 96.78%\\n\",\n      \"#4012: 96.79%\\n\",\n      \"#4013: 96.79%\\n\",\n      \"#4014: 96.79%\\n\",\n      \"#4015: 96.79%\\n\",\n      \"#4016: 96.79%\\n\",\n      \"#4017: 96.79%\\n\",\n      \"#4018: 96.79%\\n\",\n      \"#4019: 96.79%\\n\",\n      \"#4020: 96.79%\\n\",\n      \"#4021: 96.79%\\n\",\n      \"#4022: 96.79%\\n\",\n      \"#4023: 96.79%\\n\",\n      \"#4024: 96.80%\\n\",\n      \"#4025: 96.80%\\n\",\n      \"#4026: 96.80%\\n\",\n      \"#4027: 96.80%\\n\",\n      \"#4028: 96.80%\\n\",\n      \"#4029: 96.80%\\n\",\n      \"#4030: 96.80%\\n\",\n      \"#4031: 96.80%\\n\",\n      \"#4032: 96.80%\\n\",\n      \"#4033: 96.80%\\n\",\n      \"#4034: 96.80%\\n\",\n      \"#4035: 96.80%\\n\",\n      \"#4036: 96.80%\\n\",\n      \"#4037: 96.81%\\n\",\n      \"#4038: 96.81%\\n\",\n      \"#4039: 96.81%\\n\",\n      \"#4040: 96.81%\\n\",\n      \"#4041: 96.81%\\n\",\n      \"#4042: 96.81%\\n\",\n      \"#4043: 96.81%\\n\",\n      \"#4044: 96.81%\\n\",\n      \"#4045: 96.81%\\n\",\n      \"#4046: 96.81%\\n\",\n      \"#4047: 96.81%\\n\",\n      \"#4048: 96.81%\\n\",\n      \"#4049: 96.81%\\n\",\n      \"#4050: 96.82%\\n\",\n      \"#4051: 96.82%\\n\",\n      \"#4052: 96.82%\\n\",\n      \"#4053: 96.82%\\n\",\n      \"#4054: 96.82%\\n\",\n      \"#4055: 96.82%\\n\",\n      \"#4056: 96.82%\\n\",\n      \"#4057: 96.82%\\n\",\n      \"#4058: 96.82%\\n\",\n      \"#4059: 96.82%\\n\",\n      \"#4060: 96.82%\\n\",\n      \"#4061: 96.82%\\n\",\n      \"#4062: 96.83%\\n\",\n      \"#4063: 96.80%\\n\",\n      \"#4064: 96.80%\\n\",\n      \"#4065: 96.80%\\n\",\n      \"#4066: 96.80%\\n\",\n      \"#4067: 96.80%\\n\",\n      \"#4068: 96.81%\\n\",\n      \"#4069: 96.81%\\n\",\n      \"#4070: 96.81%\\n\",\n      \"#4071: 96.81%\\n\",\n      \"#4072: 96.81%\\n\",\n      \"#4073: 96.81%\\n\",\n      \"#4074: 96.81%\\n\",\n      \"#4075: 96.81%\\n\",\n      \"#4076: 96.81%\\n\",\n      \"#4077: 96.81%\\n\",\n      \"#4078: 96.79%\\n\",\n      \"#4079: 96.79%\\n\",\n      \"#4080: 96.79%\\n\",\n      \"#4081: 96.79%\\n\",\n      \"#4082: 96.79%\\n\",\n      \"#4083: 96.79%\\n\",\n      \"#4084: 96.79%\\n\",\n      \"#4085: 96.79%\\n\",\n      \"#4086: 96.79%\\n\",\n      \"#4087: 96.80%\\n\",\n      \"#4088: 96.80%\\n\",\n      \"#4089: 96.80%\\n\",\n      \"#4090: 96.80%\\n\",\n      \"#4091: 96.80%\\n\",\n      \"#4092: 96.80%\\n\",\n      \"#4093: 96.80%\\n\",\n      \"#4094: 96.80%\\n\",\n      \"#4095: 96.80%\\n\",\n      \"#4096: 96.80%\\n\",\n      \"#4097: 96.80%\\n\",\n      \"#4098: 96.80%\\n\",\n      \"#4099: 96.80%\\n\",\n      \"#4100: 96.81%\\n\",\n      \"#4101: 96.81%\\n\",\n      \"#4102: 96.81%\\n\",\n      \"#4103: 96.81%\\n\",\n      \"#4104: 96.81%\\n\",\n      \"#4105: 96.81%\\n\",\n      \"#4106: 96.81%\\n\",\n      \"#4107: 96.81%\\n\",\n      \"#4108: 96.81%\\n\",\n      \"#4109: 96.81%\\n\",\n      \"#4110: 96.81%\\n\",\n      \"#4111: 96.81%\\n\",\n      \"#4112: 96.81%\\n\",\n      \"#4113: 96.82%\\n\",\n      \"#4114: 96.82%\\n\",\n      \"#4115: 96.82%\\n\",\n      \"#4116: 96.79%\\n\",\n      \"#4117: 96.79%\\n\",\n      \"#4118: 96.80%\\n\",\n      \"#4119: 96.80%\\n\",\n      \"#4120: 96.80%\\n\",\n      \"#4121: 96.80%\\n\",\n      \"#4122: 96.80%\\n\",\n      \"#4123: 96.77%\\n\",\n      \"#4124: 96.78%\\n\",\n      \"#4125: 96.78%\\n\",\n      \"#4126: 96.78%\\n\",\n      \"#4127: 96.78%\\n\",\n      \"#4128: 96.78%\\n\",\n      \"#4129: 96.78%\\n\",\n      \"#4130: 96.78%\\n\",\n      \"#4131: 96.78%\\n\",\n      \"#4132: 96.78%\\n\",\n      \"#4133: 96.78%\\n\",\n      \"#4134: 96.78%\\n\",\n      \"#4135: 96.78%\\n\",\n      \"#4136: 96.79%\\n\",\n      \"#4137: 96.79%\\n\",\n      \"#4138: 96.79%\\n\",\n      \"#4139: 96.79%\\n\",\n      \"#4140: 96.79%\\n\",\n      \"#4141: 96.79%\\n\",\n      \"#4142: 96.79%\\n\",\n      \"#4143: 96.79%\\n\",\n      \"#4144: 96.79%\\n\",\n      \"#4145: 96.79%\\n\",\n      \"#4146: 96.79%\\n\",\n      \"#4147: 96.79%\\n\",\n      \"#4148: 96.79%\\n\",\n      \"#4149: 96.80%\\n\",\n      \"#4150: 96.80%\\n\",\n      \"#4151: 96.80%\\n\",\n      \"#4152: 96.80%\\n\",\n      \"#4153: 96.80%\\n\",\n      \"#4154: 96.80%\\n\",\n      \"#4155: 96.80%\\n\",\n      \"#4156: 96.80%\\n\",\n      \"#4157: 96.80%\\n\",\n      \"#4158: 96.80%\\n\",\n      \"#4159: 96.80%\\n\",\n      \"#4160: 96.80%\\n\",\n      \"#4161: 96.80%\\n\",\n      \"#4162: 96.81%\\n\",\n      \"#4163: 96.78%\\n\",\n      \"#4164: 96.78%\\n\",\n      \"#4165: 96.78%\\n\",\n      \"#4166: 96.78%\\n\",\n      \"#4167: 96.79%\\n\",\n      \"#4168: 96.79%\\n\",\n      \"#4169: 96.79%\\n\",\n      \"#4170: 96.79%\\n\",\n      \"#4171: 96.79%\\n\",\n      \"#4172: 96.79%\\n\",\n      \"#4173: 96.79%\\n\",\n      \"#4174: 96.79%\\n\",\n      \"#4175: 96.79%\\n\",\n      \"#4176: 96.77%\\n\",\n      \"#4177: 96.77%\\n\",\n      \"#4178: 96.77%\\n\",\n      \"#4179: 96.77%\\n\",\n      \"#4180: 96.77%\\n\",\n      \"#4181: 96.77%\\n\",\n      \"#4182: 96.77%\\n\",\n      \"#4183: 96.77%\\n\",\n      \"#4184: 96.77%\\n\",\n      \"#4185: 96.77%\\n\",\n      \"#4186: 96.78%\\n\",\n      \"#4187: 96.78%\\n\",\n      \"#4188: 96.78%\\n\",\n      \"#4189: 96.78%\\n\",\n      \"#4190: 96.78%\\n\",\n      \"#4191: 96.78%\\n\",\n      \"#4192: 96.78%\\n\",\n      \"#4193: 96.78%\\n\",\n      \"#4194: 96.78%\\n\",\n      \"#4195: 96.78%\\n\",\n      \"#4196: 96.78%\\n\",\n      \"#4197: 96.78%\\n\",\n      \"#4198: 96.78%\\n\",\n      \"#4199: 96.79%\\n\",\n      \"#4200: 96.79%\\n\",\n      \"#4201: 96.79%\\n\",\n      \"#4202: 96.79%\\n\",\n      \"#4203: 96.79%\\n\",\n      \"#4204: 96.79%\\n\",\n      \"#4205: 96.77%\\n\",\n      \"#4206: 96.77%\\n\",\n      \"#4207: 96.77%\\n\",\n      \"#4208: 96.77%\\n\",\n      \"#4209: 96.77%\\n\",\n      \"#4210: 96.77%\\n\",\n      \"#4211: 96.77%\\n\",\n      \"#4212: 96.77%\\n\",\n      \"#4213: 96.77%\\n\",\n      \"#4214: 96.77%\\n\",\n      \"#4215: 96.77%\\n\",\n      \"#4216: 96.77%\\n\",\n      \"#4217: 96.78%\\n\",\n      \"#4218: 96.78%\\n\",\n      \"#4219: 96.78%\\n\",\n      \"#4220: 96.78%\\n\",\n      \"#4221: 96.78%\\n\",\n      \"#4222: 96.78%\\n\",\n      \"#4223: 96.78%\\n\",\n      \"#4224: 96.78%\\n\",\n      \"#4225: 96.78%\\n\",\n      \"#4226: 96.78%\\n\",\n      \"#4227: 96.78%\\n\",\n      \"#4228: 96.78%\\n\",\n      \"#4229: 96.78%\\n\",\n      \"#4230: 96.79%\\n\",\n      \"#4231: 96.79%\\n\",\n      \"#4232: 96.79%\\n\",\n      \"#4233: 96.79%\\n\",\n      \"#4234: 96.79%\\n\",\n      \"#4235: 96.79%\\n\",\n      \"#4236: 96.79%\\n\",\n      \"#4237: 96.79%\\n\",\n      \"#4238: 96.79%\\n\",\n      \"#4239: 96.79%\\n\",\n      \"#4240: 96.79%\\n\",\n      \"#4241: 96.79%\\n\",\n      \"#4242: 96.79%\\n\",\n      \"#4243: 96.80%\\n\",\n      \"#4244: 96.80%\\n\",\n      \"#4245: 96.80%\\n\",\n      \"#4246: 96.80%\\n\",\n      \"#4247: 96.80%\\n\",\n      \"#4248: 96.80%\\n\",\n      \"#4249: 96.80%\\n\",\n      \"#4250: 96.80%\\n\",\n      \"#4251: 96.80%\\n\",\n      \"#4252: 96.80%\\n\",\n      \"#4253: 96.80%\\n\",\n      \"#4254: 96.80%\\n\",\n      \"#4255: 96.80%\\n\",\n      \"#4256: 96.78%\\n\",\n      \"#4257: 96.78%\\n\",\n      \"#4258: 96.78%\\n\",\n      \"#4259: 96.78%\\n\",\n      \"#4260: 96.78%\\n\",\n      \"#4261: 96.79%\\n\",\n      \"#4262: 96.79%\\n\",\n      \"#4263: 96.79%\\n\",\n      \"#4264: 96.79%\\n\",\n      \"#4265: 96.77%\\n\",\n      \"#4266: 96.77%\\n\",\n      \"#4267: 96.77%\\n\",\n      \"#4268: 96.77%\\n\",\n      \"#4269: 96.77%\\n\",\n      \"#4270: 96.77%\\n\",\n      \"#4271: 96.77%\\n\",\n      \"#4272: 96.77%\\n\",\n      \"#4273: 96.77%\\n\",\n      \"#4274: 96.77%\\n\",\n      \"#4275: 96.77%\\n\",\n      \"#4276: 96.77%\\n\",\n      \"#4277: 96.77%\\n\",\n      \"#4278: 96.77%\\n\",\n      \"#4279: 96.78%\\n\",\n      \"#4280: 96.78%\\n\",\n      \"#4281: 96.78%\\n\",\n      \"#4282: 96.78%\\n\",\n      \"#4283: 96.78%\\n\",\n      \"#4284: 96.78%\\n\",\n      \"#4285: 96.78%\\n\",\n      \"#4286: 96.78%\\n\",\n      \"#4287: 96.78%\\n\",\n      \"#4288: 96.78%\\n\",\n      \"#4289: 96.78%\\n\",\n      \"#4290: 96.78%\\n\",\n      \"#4291: 96.78%\\n\",\n      \"#4292: 96.79%\\n\",\n      \"#4293: 96.79%\\n\",\n      \"#4294: 96.79%\\n\",\n      \"#4295: 96.79%\\n\",\n      \"#4296: 96.79%\\n\",\n      \"#4297: 96.79%\\n\",\n      \"#4298: 96.79%\\n\",\n      \"#4299: 96.79%\\n\",\n      \"#4300: 96.79%\\n\",\n      \"#4301: 96.79%\\n\",\n      \"#4302: 96.79%\\n\",\n      \"#4303: 96.79%\\n\",\n      \"#4304: 96.79%\\n\",\n      \"#4305: 96.80%\\n\",\n      \"#4306: 96.77%\\n\",\n      \"#4307: 96.77%\\n\",\n      \"#4308: 96.77%\\n\",\n      \"#4309: 96.77%\\n\",\n      \"#4310: 96.78%\\n\",\n      \"#4311: 96.78%\\n\",\n      \"#4312: 96.78%\\n\",\n      \"#4313: 96.78%\\n\",\n      \"#4314: 96.78%\\n\",\n      \"#4315: 96.78%\\n\",\n      \"#4316: 96.78%\\n\",\n      \"#4317: 96.78%\\n\",\n      \"#4318: 96.78%\\n\",\n      \"#4319: 96.78%\\n\",\n      \"#4320: 96.78%\\n\",\n      \"#4321: 96.78%\\n\",\n      \"#4322: 96.78%\\n\",\n      \"#4323: 96.79%\\n\",\n      \"#4324: 96.79%\\n\",\n      \"#4325: 96.79%\\n\",\n      \"#4326: 96.79%\\n\",\n      \"#4327: 96.79%\\n\",\n      \"#4328: 96.79%\\n\",\n      \"#4329: 96.79%\\n\",\n      \"#4330: 96.79%\\n\",\n      \"#4331: 96.79%\\n\",\n      \"#4332: 96.79%\\n\",\n      \"#4333: 96.79%\\n\",\n      \"#4334: 96.79%\\n\",\n      \"#4335: 96.79%\\n\",\n      \"#4336: 96.80%\\n\",\n      \"#4337: 96.80%\\n\",\n      \"#4338: 96.80%\\n\",\n      \"#4339: 96.80%\\n\",\n      \"#4340: 96.80%\\n\",\n      \"#4341: 96.80%\\n\",\n      \"#4342: 96.80%\\n\",\n      \"#4343: 96.80%\\n\",\n      \"#4344: 96.80%\\n\",\n      \"#4345: 96.80%\\n\",\n      \"#4346: 96.80%\\n\",\n      \"#4347: 96.80%\\n\",\n      \"#4348: 96.80%\\n\",\n      \"#4349: 96.80%\\n\",\n      \"#4350: 96.81%\\n\",\n      \"#4351: 96.81%\\n\",\n      \"#4352: 96.81%\\n\",\n      \"#4353: 96.81%\\n\",\n      \"#4354: 96.81%\\n\",\n      \"#4355: 96.81%\\n\",\n      \"#4356: 96.81%\\n\",\n      \"#4357: 96.81%\\n\",\n      \"#4358: 96.81%\\n\",\n      \"#4359: 96.81%\\n\",\n      \"#4360: 96.81%\\n\",\n      \"#4361: 96.81%\\n\",\n      \"#4362: 96.81%\\n\",\n      \"#4363: 96.81%\\n\",\n      \"#4364: 96.82%\\n\",\n      \"#4365: 96.82%\\n\",\n      \"#4366: 96.82%\\n\",\n      \"#4367: 96.82%\\n\",\n      \"#4368: 96.82%\\n\",\n      \"#4369: 96.82%\\n\",\n      \"#4370: 96.82%\\n\",\n      \"#4371: 96.82%\\n\",\n      \"#4372: 96.82%\\n\",\n      \"#4373: 96.82%\\n\",\n      \"#4374: 96.82%\\n\",\n      \"#4375: 96.82%\\n\",\n      \"#4376: 96.82%\\n\",\n      \"#4377: 96.83%\\n\",\n      \"#4378: 96.83%\\n\",\n      \"#4379: 96.83%\\n\",\n      \"#4380: 96.83%\\n\",\n      \"#4381: 96.83%\\n\",\n      \"#4382: 96.83%\\n\",\n      \"#4383: 96.83%\\n\",\n      \"#4384: 96.83%\\n\",\n      \"#4385: 96.83%\\n\",\n      \"#4386: 96.83%\\n\",\n      \"#4387: 96.83%\\n\",\n      \"#4388: 96.83%\\n\",\n      \"#4389: 96.83%\\n\",\n      \"#4390: 96.83%\\n\",\n      \"#4391: 96.81%\\n\",\n      \"#4392: 96.81%\\n\",\n      \"#4393: 96.81%\\n\",\n      \"#4394: 96.81%\\n\",\n      \"#4395: 96.82%\\n\",\n      \"#4396: 96.82%\\n\",\n      \"#4397: 96.82%\\n\",\n      \"#4398: 96.82%\\n\",\n      \"#4399: 96.82%\\n\",\n      \"#4400: 96.80%\\n\",\n      \"#4401: 96.80%\\n\",\n      \"#4402: 96.80%\\n\",\n      \"#4403: 96.80%\\n\",\n      \"#4404: 96.80%\\n\",\n      \"#4405: 96.80%\\n\",\n      \"#4406: 96.80%\\n\",\n      \"#4407: 96.80%\\n\",\n      \"#4408: 96.80%\\n\",\n      \"#4409: 96.80%\\n\",\n      \"#4410: 96.80%\\n\",\n      \"#4411: 96.80%\\n\",\n      \"#4412: 96.80%\\n\",\n      \"#4413: 96.81%\\n\",\n      \"#4414: 96.81%\\n\",\n      \"#4415: 96.81%\\n\",\n      \"#4416: 96.81%\\n\",\n      \"#4417: 96.81%\\n\",\n      \"#4418: 96.81%\\n\",\n      \"#4419: 96.81%\\n\",\n      \"#4420: 96.81%\\n\",\n      \"#4421: 96.81%\\n\",\n      \"#4422: 96.81%\\n\",\n      \"#4423: 96.81%\\n\",\n      \"#4424: 96.81%\\n\",\n      \"#4425: 96.81%\\n\",\n      \"#4426: 96.81%\\n\",\n      \"#4427: 96.82%\\n\",\n      \"#4428: 96.82%\\n\",\n      \"#4429: 96.82%\\n\",\n      \"#4430: 96.82%\\n\",\n      \"#4431: 96.82%\\n\",\n      \"#4432: 96.82%\\n\",\n      \"#4433: 96.82%\\n\",\n      \"#4434: 96.82%\\n\",\n      \"#4435: 96.82%\\n\",\n      \"#4436: 96.82%\\n\",\n      \"#4437: 96.82%\\n\",\n      \"#4438: 96.82%\\n\",\n      \"#4439: 96.82%\\n\",\n      \"#4440: 96.83%\\n\",\n      \"#4441: 96.83%\\n\",\n      \"#4442: 96.83%\\n\",\n      \"#4443: 96.80%\\n\",\n      \"#4444: 96.81%\\n\",\n      \"#4445: 96.81%\\n\",\n      \"#4446: 96.81%\\n\",\n      \"#4447: 96.81%\\n\",\n      \"#4448: 96.81%\\n\",\n      \"#4449: 96.81%\\n\",\n      \"#4450: 96.81%\\n\",\n      \"#4451: 96.81%\\n\",\n      \"#4452: 96.81%\\n\",\n      \"#4453: 96.81%\\n\",\n      \"#4454: 96.81%\\n\",\n      \"#4455: 96.81%\\n\",\n      \"#4456: 96.81%\\n\",\n      \"#4457: 96.81%\\n\",\n      \"#4458: 96.82%\\n\",\n      \"#4459: 96.82%\\n\",\n      \"#4460: 96.82%\\n\",\n      \"#4461: 96.82%\\n\",\n      \"#4462: 96.82%\\n\",\n      \"#4463: 96.82%\\n\",\n      \"#4464: 96.82%\\n\",\n      \"#4465: 96.82%\\n\",\n      \"#4466: 96.82%\\n\",\n      \"#4467: 96.82%\\n\",\n      \"#4468: 96.82%\\n\",\n      \"#4469: 96.82%\\n\",\n      \"#4470: 96.82%\\n\",\n      \"#4471: 96.82%\\n\",\n      \"#4472: 96.83%\\n\",\n      \"#4473: 96.83%\\n\",\n      \"#4474: 96.83%\\n\",\n      \"#4475: 96.83%\\n\",\n      \"#4476: 96.83%\\n\",\n      \"#4477: 96.83%\\n\",\n      \"#4478: 96.83%\\n\",\n      \"#4479: 96.83%\\n\",\n      \"#4480: 96.83%\\n\",\n      \"#4481: 96.83%\\n\",\n      \"#4482: 96.83%\\n\",\n      \"#4483: 96.83%\\n\",\n      \"#4484: 96.83%\\n\",\n      \"#4485: 96.83%\\n\",\n      \"#4486: 96.84%\\n\",\n      \"#4487: 96.84%\\n\",\n      \"#4488: 96.84%\\n\",\n      \"#4489: 96.84%\\n\",\n      \"#4490: 96.84%\\n\",\n      \"#4491: 96.84%\\n\",\n      \"#4492: 96.84%\\n\",\n      \"#4493: 96.84%\\n\",\n      \"#4494: 96.84%\\n\",\n      \"#4495: 96.84%\\n\",\n      \"#4496: 96.84%\\n\",\n      \"#4497: 96.82%\\n\",\n      \"#4498: 96.82%\\n\",\n      \"#4499: 96.82%\\n\",\n      \"#4500: 96.80%\\n\",\n      \"#4501: 96.80%\\n\",\n      \"#4502: 96.80%\\n\",\n      \"#4503: 96.80%\\n\",\n      \"#4504: 96.80%\\n\",\n      \"#4505: 96.78%\\n\",\n      \"#4506: 96.78%\\n\",\n      \"#4507: 96.78%\\n\",\n      \"#4508: 96.78%\\n\",\n      \"#4509: 96.78%\\n\",\n      \"#4510: 96.79%\\n\",\n      \"#4511: 96.79%\\n\",\n      \"#4512: 96.79%\\n\",\n      \"#4513: 96.79%\\n\",\n      \"#4514: 96.79%\\n\",\n      \"#4515: 96.79%\\n\",\n      \"#4516: 96.79%\\n\",\n      \"#4517: 96.79%\\n\",\n      \"#4518: 96.79%\\n\",\n      \"#4519: 96.79%\\n\",\n      \"#4520: 96.79%\\n\",\n      \"#4521: 96.79%\\n\",\n      \"#4522: 96.79%\\n\",\n      \"#4523: 96.79%\\n\",\n      \"#4524: 96.80%\\n\",\n      \"#4525: 96.80%\\n\",\n      \"#4526: 96.80%\\n\",\n      \"#4527: 96.80%\\n\",\n      \"#4528: 96.80%\\n\",\n      \"#4529: 96.80%\\n\",\n      \"#4530: 96.80%\\n\",\n      \"#4531: 96.80%\\n\",\n      \"#4532: 96.80%\\n\",\n      \"#4533: 96.80%\\n\",\n      \"#4534: 96.80%\\n\",\n      \"#4535: 96.80%\\n\",\n      \"#4536: 96.78%\\n\",\n      \"#4537: 96.78%\\n\",\n      \"#4538: 96.78%\\n\",\n      \"#4539: 96.78%\\n\",\n      \"#4540: 96.78%\\n\",\n      \"#4541: 96.79%\\n\",\n      \"#4542: 96.79%\\n\",\n      \"#4543: 96.79%\\n\",\n      \"#4544: 96.79%\\n\",\n      \"#4545: 96.79%\\n\",\n      \"#4546: 96.79%\\n\",\n      \"#4547: 96.79%\\n\",\n      \"#4548: 96.79%\\n\",\n      \"#4549: 96.79%\\n\",\n      \"#4550: 96.79%\\n\",\n      \"#4551: 96.79%\\n\",\n      \"#4552: 96.79%\\n\",\n      \"#4553: 96.79%\\n\",\n      \"#4554: 96.79%\\n\",\n      \"#4555: 96.80%\\n\",\n      \"#4556: 96.80%\\n\",\n      \"#4557: 96.80%\\n\",\n      \"#4558: 96.80%\\n\",\n      \"#4559: 96.80%\\n\",\n      \"#4560: 96.80%\\n\",\n      \"#4561: 96.80%\\n\",\n      \"#4562: 96.80%\\n\",\n      \"#4563: 96.80%\\n\",\n      \"#4564: 96.80%\\n\",\n      \"#4565: 96.80%\\n\",\n      \"#4566: 96.80%\\n\",\n      \"#4567: 96.80%\\n\",\n      \"#4568: 96.80%\\n\",\n      \"#4569: 96.81%\\n\",\n      \"#4570: 96.81%\\n\",\n      \"#4571: 96.78%\\n\",\n      \"#4572: 96.79%\\n\",\n      \"#4573: 96.79%\\n\",\n      \"#4574: 96.79%\\n\",\n      \"#4575: 96.79%\\n\",\n      \"#4576: 96.79%\\n\",\n      \"#4577: 96.79%\\n\",\n      \"#4578: 96.77%\\n\",\n      \"#4579: 96.77%\\n\",\n      \"#4580: 96.77%\\n\",\n      \"#4581: 96.77%\\n\",\n      \"#4582: 96.77%\\n\",\n      \"#4583: 96.77%\\n\",\n      \"#4584: 96.77%\\n\",\n      \"#4585: 96.77%\\n\",\n      \"#4586: 96.77%\\n\",\n      \"#4587: 96.77%\\n\",\n      \"#4588: 96.77%\\n\",\n      \"#4589: 96.78%\\n\",\n      \"#4590: 96.78%\\n\",\n      \"#4591: 96.78%\\n\",\n      \"#4592: 96.78%\\n\",\n      \"#4593: 96.78%\\n\",\n      \"#4594: 96.78%\\n\",\n      \"#4595: 96.78%\\n\",\n      \"#4596: 96.78%\\n\",\n      \"#4597: 96.78%\\n\",\n      \"#4598: 96.78%\\n\",\n      \"#4599: 96.78%\\n\",\n      \"#4600: 96.78%\\n\",\n      \"#4601: 96.78%\\n\",\n      \"#4602: 96.78%\\n\",\n      \"#4603: 96.79%\\n\",\n      \"#4604: 96.79%\\n\",\n      \"#4605: 96.79%\\n\",\n      \"#4606: 96.79%\\n\",\n      \"#4607: 96.79%\\n\",\n      \"#4608: 96.79%\\n\",\n      \"#4609: 96.79%\\n\",\n      \"#4610: 96.79%\\n\",\n      \"#4611: 96.79%\\n\",\n      \"#4612: 96.79%\\n\",\n      \"#4613: 96.79%\\n\",\n      \"#4614: 96.79%\\n\",\n      \"#4615: 96.77%\\n\",\n      \"#4616: 96.77%\\n\",\n      \"#4617: 96.77%\\n\",\n      \"#4618: 96.77%\\n\",\n      \"#4619: 96.77%\\n\",\n      \"#4620: 96.78%\\n\",\n      \"#4621: 96.78%\\n\",\n      \"#4622: 96.78%\\n\",\n      \"#4623: 96.78%\\n\",\n      \"#4624: 96.78%\\n\",\n      \"#4625: 96.78%\\n\",\n      \"#4626: 96.78%\\n\",\n      \"#4627: 96.78%\\n\",\n      \"#4628: 96.78%\\n\",\n      \"#4629: 96.78%\\n\",\n      \"#4630: 96.78%\\n\",\n      \"#4631: 96.78%\\n\",\n      \"#4632: 96.78%\\n\",\n      \"#4633: 96.78%\\n\",\n      \"#4634: 96.79%\\n\",\n      \"#4635: 96.79%\\n\",\n      \"#4636: 96.79%\\n\",\n      \"#4637: 96.79%\\n\",\n      \"#4638: 96.79%\\n\",\n      \"#4639: 96.77%\\n\",\n      \"#4640: 96.77%\\n\",\n      \"#4641: 96.77%\\n\",\n      \"#4642: 96.77%\\n\",\n      \"#4643: 96.77%\\n\",\n      \"#4644: 96.77%\\n\",\n      \"#4645: 96.77%\\n\",\n      \"#4646: 96.77%\\n\",\n      \"#4647: 96.77%\\n\",\n      \"#4648: 96.77%\\n\",\n      \"#4649: 96.77%\\n\",\n      \"#4650: 96.77%\\n\",\n      \"#4651: 96.78%\\n\",\n      \"#4652: 96.78%\\n\",\n      \"#4653: 96.78%\\n\",\n      \"#4654: 96.78%\\n\",\n      \"#4655: 96.78%\\n\",\n      \"#4656: 96.78%\\n\",\n      \"#4657: 96.78%\\n\",\n      \"#4658: 96.78%\\n\",\n      \"#4659: 96.78%\\n\",\n      \"#4660: 96.78%\\n\",\n      \"#4661: 96.78%\\n\",\n      \"#4662: 96.78%\\n\",\n      \"#4663: 96.78%\\n\",\n      \"#4664: 96.78%\\n\",\n      \"#4665: 96.79%\\n\",\n      \"#4666: 96.79%\\n\",\n      \"#4667: 96.79%\\n\",\n      \"#4668: 96.79%\\n\",\n      \"#4669: 96.79%\\n\",\n      \"#4670: 96.79%\\n\",\n      \"#4671: 96.79%\\n\",\n      \"#4672: 96.79%\\n\",\n      \"#4673: 96.79%\\n\",\n      \"#4674: 96.79%\\n\",\n      \"#4675: 96.79%\\n\",\n      \"#4676: 96.79%\\n\",\n      \"#4677: 96.79%\\n\",\n      \"#4678: 96.79%\\n\",\n      \"#4679: 96.79%\\n\",\n      \"#4680: 96.80%\\n\",\n      \"#4681: 96.80%\\n\",\n      \"#4682: 96.80%\\n\",\n      \"#4683: 96.80%\\n\",\n      \"#4684: 96.80%\\n\",\n      \"#4685: 96.80%\\n\",\n      \"#4686: 96.80%\\n\",\n      \"#4687: 96.80%\\n\",\n      \"#4688: 96.80%\\n\",\n      \"#4689: 96.80%\\n\",\n      \"#4690: 96.80%\\n\",\n      \"#4691: 96.80%\\n\",\n      \"#4692: 96.80%\\n\",\n      \"#4693: 96.80%\\n\",\n      \"#4694: 96.81%\\n\",\n      \"#4695: 96.81%\\n\",\n      \"#4696: 96.81%\\n\",\n      \"#4697: 96.81%\\n\",\n      \"#4698: 96.81%\\n\",\n      \"#4699: 96.81%\\n\",\n      \"#4700: 96.81%\\n\",\n      \"#4701: 96.81%\\n\",\n      \"#4702: 96.81%\\n\",\n      \"#4703: 96.81%\\n\",\n      \"#4704: 96.81%\\n\",\n      \"#4705: 96.81%\\n\",\n      \"#4706: 96.81%\\n\",\n      \"#4707: 96.81%\\n\",\n      \"#4708: 96.81%\\n\",\n      \"#4709: 96.82%\\n\",\n      \"#4710: 96.82%\\n\",\n      \"#4711: 96.82%\\n\",\n      \"#4712: 96.82%\\n\",\n      \"#4713: 96.82%\\n\",\n      \"#4714: 96.82%\\n\",\n      \"#4715: 96.82%\\n\",\n      \"#4716: 96.82%\\n\",\n      \"#4717: 96.82%\\n\",\n      \"#4718: 96.82%\\n\",\n      \"#4719: 96.82%\\n\",\n      \"#4720: 96.82%\\n\",\n      \"#4721: 96.82%\\n\",\n      \"#4722: 96.82%\\n\",\n      \"#4723: 96.82%\\n\",\n      \"#4724: 96.83%\\n\",\n      \"#4725: 96.83%\\n\",\n      \"#4726: 96.83%\\n\",\n      \"#4727: 96.83%\\n\",\n      \"#4728: 96.83%\\n\",\n      \"#4729: 96.83%\\n\",\n      \"#4730: 96.83%\\n\",\n      \"#4731: 96.83%\\n\",\n      \"#4732: 96.83%\\n\",\n      \"#4733: 96.83%\\n\",\n      \"#4734: 96.83%\\n\",\n      \"#4735: 96.83%\\n\",\n      \"#4736: 96.83%\\n\",\n      \"#4737: 96.81%\\n\",\n      \"#4738: 96.81%\\n\",\n      \"#4739: 96.81%\\n\",\n      \"#4740: 96.79%\\n\",\n      \"#4741: 96.79%\\n\",\n      \"#4742: 96.80%\\n\",\n      \"#4743: 96.80%\\n\",\n      \"#4744: 96.80%\\n\",\n      \"#4745: 96.80%\\n\",\n      \"#4746: 96.80%\\n\",\n      \"#4747: 96.80%\\n\",\n      \"#4748: 96.80%\\n\",\n      \"#4749: 96.80%\\n\",\n      \"#4750: 96.80%\\n\",\n      \"#4751: 96.78%\\n\",\n      \"#4752: 96.78%\\n\",\n      \"#4753: 96.78%\\n\",\n      \"#4754: 96.78%\\n\",\n      \"#4755: 96.78%\\n\",\n      \"#4756: 96.78%\\n\",\n      \"#4757: 96.78%\\n\",\n      \"#4758: 96.79%\\n\",\n      \"#4759: 96.79%\\n\",\n      \"#4760: 96.79%\\n\",\n      \"#4761: 96.77%\\n\",\n      \"#4762: 96.77%\\n\",\n      \"#4763: 96.77%\\n\",\n      \"#4764: 96.77%\\n\",\n      \"#4765: 96.77%\\n\",\n      \"#4766: 96.77%\\n\",\n      \"#4767: 96.77%\\n\",\n      \"#4768: 96.77%\\n\",\n      \"#4769: 96.77%\\n\",\n      \"#4770: 96.77%\\n\",\n      \"#4771: 96.77%\\n\",\n      \"#4772: 96.77%\\n\",\n      \"#4773: 96.77%\\n\",\n      \"#4774: 96.77%\\n\",\n      \"#4775: 96.78%\\n\",\n      \"#4776: 96.78%\\n\",\n      \"#4777: 96.78%\\n\",\n      \"#4778: 96.78%\\n\",\n      \"#4779: 96.78%\\n\",\n      \"#4780: 96.78%\\n\",\n      \"#4781: 96.78%\\n\",\n      \"#4782: 96.78%\\n\",\n      \"#4783: 96.76%\\n\",\n      \"#4784: 96.76%\\n\",\n      \"#4785: 96.76%\\n\",\n      \"#4786: 96.76%\\n\",\n      \"#4787: 96.76%\\n\",\n      \"#4788: 96.76%\\n\",\n      \"#4789: 96.76%\\n\",\n      \"#4790: 96.76%\\n\",\n      \"#4791: 96.77%\\n\",\n      \"#4792: 96.77%\\n\",\n      \"#4793: 96.77%\\n\",\n      \"#4794: 96.77%\\n\",\n      \"#4795: 96.77%\\n\",\n      \"#4796: 96.77%\\n\",\n      \"#4797: 96.77%\\n\",\n      \"#4798: 96.77%\\n\",\n      \"#4799: 96.77%\\n\",\n      \"#4800: 96.77%\\n\",\n      \"#4801: 96.77%\\n\",\n      \"#4802: 96.77%\\n\",\n      \"#4803: 96.77%\\n\",\n      \"#4804: 96.77%\\n\",\n      \"#4805: 96.77%\\n\",\n      \"#4806: 96.78%\\n\",\n      \"#4807: 96.76%\\n\",\n      \"#4808: 96.74%\\n\",\n      \"#4809: 96.74%\\n\",\n      \"#4810: 96.74%\\n\",\n      \"#4811: 96.74%\\n\",\n      \"#4812: 96.74%\\n\",\n      \"#4813: 96.74%\\n\",\n      \"#4814: 96.74%\\n\",\n      \"#4815: 96.74%\\n\",\n      \"#4816: 96.74%\\n\",\n      \"#4817: 96.74%\\n\",\n      \"#4818: 96.74%\\n\",\n      \"#4819: 96.74%\\n\",\n      \"#4820: 96.74%\\n\",\n      \"#4821: 96.74%\\n\",\n      \"#4822: 96.74%\\n\",\n      \"#4823: 96.75%\\n\",\n      \"#4824: 96.75%\\n\",\n      \"#4825: 96.75%\\n\",\n      \"#4826: 96.75%\\n\",\n      \"#4827: 96.75%\\n\",\n      \"#4828: 96.75%\\n\",\n      \"#4829: 96.75%\\n\",\n      \"#4830: 96.75%\\n\",\n      \"#4831: 96.75%\\n\",\n      \"#4832: 96.75%\\n\",\n      \"#4833: 96.75%\\n\",\n      \"#4834: 96.75%\\n\",\n      \"#4835: 96.75%\\n\",\n      \"#4836: 96.75%\\n\",\n      \"#4837: 96.75%\\n\",\n      \"#4838: 96.73%\\n\",\n      \"#4839: 96.74%\\n\",\n      \"#4840: 96.74%\\n\",\n      \"#4841: 96.74%\\n\",\n      \"#4842: 96.74%\\n\",\n      \"#4843: 96.74%\\n\",\n      \"#4844: 96.74%\\n\",\n      \"#4845: 96.74%\\n\",\n      \"#4846: 96.74%\\n\",\n      \"#4847: 96.74%\\n\",\n      \"#4848: 96.74%\\n\",\n      \"#4849: 96.74%\\n\",\n      \"#4850: 96.74%\\n\",\n      \"#4851: 96.74%\\n\",\n      \"#4852: 96.72%\\n\",\n      \"#4853: 96.72%\\n\",\n      \"#4854: 96.73%\\n\",\n      \"#4855: 96.73%\\n\",\n      \"#4856: 96.73%\\n\",\n      \"#4857: 96.73%\\n\",\n      \"#4858: 96.73%\\n\",\n      \"#4859: 96.73%\\n\",\n      \"#4860: 96.71%\\n\",\n      \"#4861: 96.71%\\n\",\n      \"#4862: 96.71%\\n\",\n      \"#4863: 96.71%\\n\",\n      \"#4864: 96.71%\\n\",\n      \"#4865: 96.71%\\n\",\n      \"#4866: 96.71%\\n\",\n      \"#4867: 96.71%\\n\",\n      \"#4868: 96.71%\\n\",\n      \"#4869: 96.71%\\n\",\n      \"#4870: 96.72%\\n\",\n      \"#4871: 96.72%\\n\",\n      \"#4872: 96.72%\\n\",\n      \"#4873: 96.72%\\n\",\n      \"#4874: 96.70%\\n\",\n      \"#4875: 96.70%\\n\",\n      \"#4876: 96.70%\\n\",\n      \"#4877: 96.70%\\n\",\n      \"#4878: 96.70%\\n\",\n      \"#4879: 96.68%\\n\",\n      \"#4880: 96.68%\\n\",\n      \"#4881: 96.68%\\n\",\n      \"#4882: 96.68%\\n\",\n      \"#4883: 96.68%\\n\",\n      \"#4884: 96.68%\\n\",\n      \"#4885: 96.68%\\n\",\n      \"#4886: 96.69%\\n\",\n      \"#4887: 96.69%\\n\",\n      \"#4888: 96.69%\\n\",\n      \"#4889: 96.69%\\n\",\n      \"#4890: 96.67%\\n\",\n      \"#4891: 96.67%\\n\",\n      \"#4892: 96.67%\\n\",\n      \"#4893: 96.67%\\n\",\n      \"#4894: 96.67%\\n\",\n      \"#4895: 96.67%\\n\",\n      \"#4896: 96.67%\\n\",\n      \"#4897: 96.67%\\n\",\n      \"#4898: 96.67%\\n\",\n      \"#4899: 96.67%\\n\",\n      \"#4900: 96.67%\\n\",\n      \"#4901: 96.67%\\n\",\n      \"#4902: 96.68%\\n\",\n      \"#4903: 96.68%\\n\",\n      \"#4904: 96.68%\\n\",\n      \"#4905: 96.68%\\n\",\n      \"#4906: 96.68%\\n\",\n      \"#4907: 96.68%\\n\",\n      \"#4908: 96.68%\\n\",\n      \"#4909: 96.68%\\n\",\n      \"#4910: 96.68%\\n\",\n      \"#4911: 96.68%\\n\",\n      \"#4912: 96.68%\\n\",\n      \"#4913: 96.68%\\n\",\n      \"#4914: 96.68%\\n\",\n      \"#4915: 96.68%\\n\",\n      \"#4916: 96.68%\\n\",\n      \"#4917: 96.69%\\n\",\n      \"#4918: 96.69%\\n\",\n      \"#4919: 96.69%\\n\",\n      \"#4920: 96.69%\\n\",\n      \"#4921: 96.69%\\n\",\n      \"#4922: 96.69%\\n\",\n      \"#4923: 96.69%\\n\",\n      \"#4924: 96.69%\\n\",\n      \"#4925: 96.69%\\n\",\n      \"#4926: 96.69%\\n\",\n      \"#4927: 96.69%\\n\",\n      \"#4928: 96.69%\\n\",\n      \"#4929: 96.69%\\n\",\n      \"#4930: 96.69%\\n\",\n      \"#4931: 96.70%\\n\",\n      \"#4932: 96.70%\\n\",\n      \"#4933: 96.70%\\n\",\n      \"#4934: 96.70%\\n\",\n      \"#4935: 96.70%\\n\",\n      \"#4936: 96.70%\\n\",\n      \"#4937: 96.70%\\n\",\n      \"#4938: 96.70%\\n\",\n      \"#4939: 96.70%\\n\",\n      \"#4940: 96.70%\\n\",\n      \"#4941: 96.70%\\n\",\n      \"#4942: 96.70%\\n\",\n      \"#4943: 96.70%\\n\",\n      \"#4944: 96.70%\\n\",\n      \"#4945: 96.70%\\n\",\n      \"#4946: 96.71%\\n\",\n      \"#4947: 96.71%\\n\",\n      \"#4948: 96.71%\\n\",\n      \"#4949: 96.71%\\n\",\n      \"#4950: 96.71%\\n\",\n      \"#4951: 96.71%\\n\",\n      \"#4952: 96.71%\\n\",\n      \"#4953: 96.71%\\n\",\n      \"#4954: 96.71%\\n\",\n      \"#4955: 96.71%\\n\",\n      \"#4956: 96.69%\\n\",\n      \"#4957: 96.69%\\n\",\n      \"#4958: 96.69%\\n\",\n      \"#4959: 96.69%\\n\",\n      \"#4960: 96.69%\\n\",\n      \"#4961: 96.69%\\n\",\n      \"#4962: 96.70%\\n\",\n      \"#4963: 96.70%\\n\",\n      \"#4964: 96.70%\\n\",\n      \"#4965: 96.70%\\n\",\n      \"#4966: 96.70%\\n\",\n      \"#4967: 96.70%\\n\",\n      \"#4968: 96.70%\\n\",\n      \"#4969: 96.70%\\n\",\n      \"#4970: 96.70%\\n\",\n      \"#4971: 96.70%\\n\",\n      \"#4972: 96.70%\\n\",\n      \"#4973: 96.70%\\n\",\n      \"#4974: 96.70%\\n\",\n      \"#4975: 96.70%\\n\",\n      \"#4976: 96.70%\\n\",\n      \"#4977: 96.71%\\n\",\n      \"#4978: 96.69%\\n\",\n      \"#4979: 96.69%\\n\",\n      \"#4980: 96.69%\\n\",\n      \"#4981: 96.69%\\n\",\n      \"#4982: 96.69%\\n\",\n      \"#4983: 96.69%\\n\",\n      \"#4984: 96.69%\\n\",\n      \"#4985: 96.69%\\n\",\n      \"#4986: 96.69%\\n\",\n      \"#4987: 96.69%\\n\",\n      \"#4988: 96.69%\\n\",\n      \"#4989: 96.69%\\n\",\n      \"#4990: 96.69%\\n\",\n      \"#4991: 96.69%\\n\",\n      \"#4992: 96.70%\\n\",\n      \"#4993: 96.70%\\n\",\n      \"#4994: 96.70%\\n\",\n      \"#4995: 96.70%\\n\",\n      \"#4996: 96.70%\\n\",\n      \"#4997: 96.70%\\n\",\n      \"#4998: 96.70%\\n\",\n      \"#4999: 96.70%\\n\",\n      \"#5000: 96.70%\\n\",\n      \"#5001: 96.70%\\n\",\n      \"#5002: 96.70%\\n\",\n      \"#5003: 96.70%\\n\",\n      \"#5004: 96.70%\\n\",\n      \"#5005: 96.70%\\n\",\n      \"#5006: 96.70%\\n\",\n      \"#5007: 96.71%\\n\",\n      \"#5008: 96.71%\\n\",\n      \"#5009: 96.71%\\n\",\n      \"#5010: 96.71%\\n\",\n      \"#5011: 96.71%\\n\",\n      \"#5012: 96.71%\\n\",\n      \"#5013: 96.71%\\n\",\n      \"#5014: 96.71%\\n\",\n      \"#5015: 96.71%\\n\",\n      \"#5016: 96.71%\\n\",\n      \"#5017: 96.71%\\n\",\n      \"#5018: 96.71%\\n\",\n      \"#5019: 96.71%\\n\",\n      \"#5020: 96.71%\\n\",\n      \"#5021: 96.71%\\n\",\n      \"#5022: 96.72%\\n\",\n      \"#5023: 96.72%\\n\",\n      \"#5024: 96.72%\\n\",\n      \"#5025: 96.72%\\n\",\n      \"#5026: 96.72%\\n\",\n      \"#5027: 96.72%\\n\",\n      \"#5028: 96.72%\\n\",\n      \"#5029: 96.72%\\n\",\n      \"#5030: 96.72%\\n\",\n      \"#5031: 96.72%\\n\",\n      \"#5032: 96.72%\\n\",\n      \"#5033: 96.72%\\n\",\n      \"#5034: 96.72%\\n\",\n      \"#5035: 96.72%\\n\",\n      \"#5036: 96.72%\\n\",\n      \"#5037: 96.72%\\n\",\n      \"#5038: 96.73%\\n\",\n      \"#5039: 96.73%\\n\",\n      \"#5040: 96.73%\\n\",\n      \"#5041: 96.73%\\n\",\n      \"#5042: 96.73%\\n\",\n      \"#5043: 96.73%\\n\",\n      \"#5044: 96.73%\\n\",\n      \"#5045: 96.73%\\n\",\n      \"#5046: 96.73%\\n\",\n      \"#5047: 96.73%\\n\",\n      \"#5048: 96.73%\\n\",\n      \"#5049: 96.73%\\n\",\n      \"#5050: 96.73%\\n\",\n      \"#5051: 96.73%\\n\",\n      \"#5052: 96.73%\\n\",\n      \"#5053: 96.74%\\n\",\n      \"#5054: 96.74%\\n\",\n      \"#5055: 96.74%\\n\",\n      \"#5056: 96.74%\\n\",\n      \"#5057: 96.74%\\n\",\n      \"#5058: 96.74%\\n\",\n      \"#5059: 96.74%\\n\",\n      \"#5060: 96.74%\\n\",\n      \"#5061: 96.74%\\n\",\n      \"#5062: 96.74%\\n\",\n      \"#5063: 96.74%\\n\",\n      \"#5064: 96.74%\\n\",\n      \"#5065: 96.74%\\n\",\n      \"#5066: 96.74%\\n\",\n      \"#5067: 96.74%\\n\",\n      \"#5068: 96.74%\\n\",\n      \"#5069: 96.75%\\n\",\n      \"#5070: 96.75%\\n\",\n      \"#5071: 96.75%\\n\",\n      \"#5072: 96.75%\\n\",\n      \"#5073: 96.75%\\n\",\n      \"#5074: 96.75%\\n\",\n      \"#5075: 96.75%\\n\",\n      \"#5076: 96.75%\\n\",\n      \"#5077: 96.75%\\n\",\n      \"#5078: 96.75%\\n\",\n      \"#5079: 96.75%\\n\",\n      \"#5080: 96.75%\\n\",\n      \"#5081: 96.75%\\n\",\n      \"#5082: 96.75%\\n\",\n      \"#5083: 96.75%\\n\",\n      \"#5084: 96.76%\\n\",\n      \"#5085: 96.76%\\n\",\n      \"#5086: 96.76%\\n\",\n      \"#5087: 96.76%\\n\",\n      \"#5088: 96.76%\\n\",\n      \"#5089: 96.76%\\n\",\n      \"#5090: 96.76%\\n\",\n      \"#5091: 96.76%\\n\",\n      \"#5092: 96.76%\\n\",\n      \"#5093: 96.76%\\n\",\n      \"#5094: 96.76%\\n\",\n      \"#5095: 96.76%\\n\",\n      \"#5096: 96.76%\\n\",\n      \"#5097: 96.76%\\n\",\n      \"#5098: 96.76%\\n\",\n      \"#5099: 96.76%\\n\",\n      \"#5100: 96.77%\\n\",\n      \"#5101: 96.77%\\n\",\n      \"#5102: 96.77%\\n\",\n      \"#5103: 96.77%\\n\",\n      \"#5104: 96.77%\\n\",\n      \"#5105: 96.77%\\n\",\n      \"#5106: 96.77%\\n\",\n      \"#5107: 96.77%\\n\",\n      \"#5108: 96.77%\\n\",\n      \"#5109: 96.77%\\n\",\n      \"#5110: 96.77%\\n\",\n      \"#5111: 96.77%\\n\",\n      \"#5112: 96.77%\\n\",\n      \"#5113: 96.77%\\n\",\n      \"#5114: 96.77%\\n\",\n      \"#5115: 96.77%\\n\",\n      \"#5116: 96.78%\\n\",\n      \"#5117: 96.78%\\n\",\n      \"#5118: 96.78%\\n\",\n      \"#5119: 96.78%\\n\",\n      \"#5120: 96.78%\\n\",\n      \"#5121: 96.78%\\n\",\n      \"#5122: 96.78%\\n\",\n      \"#5123: 96.78%\\n\",\n      \"#5124: 96.78%\\n\",\n      \"#5125: 96.78%\\n\",\n      \"#5126: 96.78%\\n\",\n      \"#5127: 96.78%\\n\",\n      \"#5128: 96.78%\\n\",\n      \"#5129: 96.78%\\n\",\n      \"#5130: 96.78%\\n\",\n      \"#5131: 96.78%\\n\",\n      \"#5132: 96.79%\\n\",\n      \"#5133: 96.79%\\n\",\n      \"#5134: 96.79%\\n\",\n      \"#5135: 96.79%\\n\",\n      \"#5136: 96.79%\\n\",\n      \"#5137: 96.79%\\n\",\n      \"#5138: 96.79%\\n\",\n      \"#5139: 96.79%\\n\",\n      \"#5140: 96.77%\\n\",\n      \"#5141: 96.77%\\n\",\n      \"#5142: 96.77%\\n\",\n      \"#5143: 96.77%\\n\",\n      \"#5144: 96.77%\\n\",\n      \"#5145: 96.77%\\n\",\n      \"#5146: 96.77%\\n\",\n      \"#5147: 96.78%\\n\",\n      \"#5148: 96.78%\\n\",\n      \"#5149: 96.78%\\n\",\n      \"#5150: 96.78%\\n\",\n      \"#5151: 96.78%\\n\",\n      \"#5152: 96.78%\\n\",\n      \"#5153: 96.78%\\n\",\n      \"#5154: 96.78%\\n\",\n      \"#5155: 96.78%\\n\",\n      \"#5156: 96.78%\\n\",\n      \"#5157: 96.78%\\n\",\n      \"#5158: 96.78%\\n\",\n      \"#5159: 96.76%\\n\",\n      \"#5160: 96.76%\\n\",\n      \"#5161: 96.76%\\n\",\n      \"#5162: 96.77%\\n\",\n      \"#5163: 96.77%\\n\",\n      \"#5164: 96.77%\\n\",\n      \"#5165: 96.77%\\n\",\n      \"#5166: 96.77%\\n\",\n      \"#5167: 96.77%\\n\",\n      \"#5168: 96.77%\\n\",\n      \"#5169: 96.77%\\n\",\n      \"#5170: 96.77%\\n\",\n      \"#5171: 96.77%\\n\",\n      \"#5172: 96.77%\\n\",\n      \"#5173: 96.77%\\n\",\n      \"#5174: 96.77%\\n\",\n      \"#5175: 96.77%\\n\",\n      \"#5176: 96.75%\\n\",\n      \"#5177: 96.76%\\n\",\n      \"#5178: 96.76%\\n\",\n      \"#5179: 96.76%\\n\",\n      \"#5180: 96.76%\\n\",\n      \"#5181: 96.76%\\n\",\n      \"#5182: 96.76%\\n\",\n      \"#5183: 96.74%\\n\",\n      \"#5184: 96.74%\\n\",\n      \"#5185: 96.74%\\n\",\n      \"#5186: 96.74%\\n\",\n      \"#5187: 96.74%\\n\",\n      \"#5188: 96.74%\\n\",\n      \"#5189: 96.74%\\n\",\n      \"#5190: 96.74%\\n\",\n      \"#5191: 96.74%\\n\",\n      \"#5192: 96.75%\\n\",\n      \"#5193: 96.75%\\n\",\n      \"#5194: 96.75%\\n\",\n      \"#5195: 96.75%\\n\",\n      \"#5196: 96.75%\\n\",\n      \"#5197: 96.75%\\n\",\n      \"#5198: 96.75%\\n\",\n      \"#5199: 96.75%\\n\",\n      \"#5200: 96.75%\\n\",\n      \"#5201: 96.75%\\n\",\n      \"#5202: 96.75%\\n\",\n      \"#5203: 96.75%\\n\",\n      \"#5204: 96.75%\\n\",\n      \"#5205: 96.75%\\n\",\n      \"#5206: 96.75%\\n\",\n      \"#5207: 96.75%\\n\",\n      \"#5208: 96.76%\\n\",\n      \"#5209: 96.76%\\n\",\n      \"#5210: 96.76%\\n\",\n      \"#5211: 96.76%\\n\",\n      \"#5212: 96.76%\\n\",\n      \"#5213: 96.76%\\n\",\n      \"#5214: 96.76%\\n\",\n      \"#5215: 96.76%\\n\",\n      \"#5216: 96.76%\\n\",\n      \"#5217: 96.76%\\n\",\n      \"#5218: 96.76%\\n\",\n      \"#5219: 96.76%\\n\",\n      \"#5220: 96.76%\\n\",\n      \"#5221: 96.76%\\n\",\n      \"#5222: 96.76%\\n\",\n      \"#5223: 96.76%\\n\",\n      \"#5224: 96.77%\\n\",\n      \"#5225: 96.77%\\n\",\n      \"#5226: 96.77%\\n\",\n      \"#5227: 96.77%\\n\",\n      \"#5228: 96.77%\\n\",\n      \"#5229: 96.77%\\n\",\n      \"#5230: 96.77%\\n\",\n      \"#5231: 96.77%\\n\",\n      \"#5232: 96.77%\\n\",\n      \"#5233: 96.77%\\n\",\n      \"#5234: 96.77%\\n\",\n      \"#5235: 96.77%\\n\",\n      \"#5236: 96.77%\\n\",\n      \"#5237: 96.77%\\n\",\n      \"#5238: 96.77%\\n\",\n      \"#5239: 96.77%\\n\",\n      \"#5240: 96.78%\\n\",\n      \"#5241: 96.78%\\n\",\n      \"#5242: 96.78%\\n\",\n      \"#5243: 96.78%\\n\",\n      \"#5244: 96.78%\\n\",\n      \"#5245: 96.78%\\n\",\n      \"#5246: 96.78%\\n\",\n      \"#5247: 96.78%\\n\",\n      \"#5248: 96.78%\\n\",\n      \"#5249: 96.78%\\n\",\n      \"#5250: 96.78%\\n\",\n      \"#5251: 96.78%\\n\",\n      \"#5252: 96.78%\\n\",\n      \"#5253: 96.78%\\n\",\n      \"#5254: 96.78%\\n\",\n      \"#5255: 96.78%\\n\",\n      \"#5256: 96.79%\\n\",\n      \"#5257: 96.79%\\n\",\n      \"#5258: 96.79%\\n\",\n      \"#5259: 96.79%\\n\",\n      \"#5260: 96.79%\\n\",\n      \"#5261: 96.79%\\n\",\n      \"#5262: 96.79%\\n\",\n      \"#5263: 96.79%\\n\",\n      \"#5264: 96.79%\\n\",\n      \"#5265: 96.79%\\n\",\n      \"#5266: 96.79%\\n\",\n      \"#5267: 96.79%\\n\",\n      \"#5268: 96.79%\\n\",\n      \"#5269: 96.79%\\n\",\n      \"#5270: 96.79%\\n\",\n      \"#5271: 96.79%\\n\",\n      \"#5272: 96.79%\\n\",\n      \"#5273: 96.80%\\n\",\n      \"#5274: 96.80%\\n\",\n      \"#5275: 96.80%\\n\",\n      \"#5276: 96.80%\\n\",\n      \"#5277: 96.80%\\n\",\n      \"#5278: 96.80%\\n\",\n      \"#5279: 96.80%\\n\",\n      \"#5280: 96.80%\\n\",\n      \"#5281: 96.80%\\n\",\n      \"#5282: 96.80%\\n\",\n      \"#5283: 96.80%\\n\",\n      \"#5284: 96.80%\\n\",\n      \"#5285: 96.80%\\n\",\n      \"#5286: 96.80%\\n\",\n      \"#5287: 96.80%\\n\",\n      \"#5288: 96.80%\\n\",\n      \"#5289: 96.81%\\n\",\n      \"#5290: 96.81%\\n\",\n      \"#5291: 96.81%\\n\",\n      \"#5292: 96.81%\\n\",\n      \"#5293: 96.81%\\n\",\n      \"#5294: 96.81%\\n\",\n      \"#5295: 96.81%\\n\",\n      \"#5296: 96.81%\\n\",\n      \"#5297: 96.81%\\n\",\n      \"#5298: 96.81%\\n\",\n      \"#5299: 96.81%\\n\",\n      \"#5300: 96.81%\\n\",\n      \"#5301: 96.81%\\n\",\n      \"#5302: 96.81%\\n\",\n      \"#5303: 96.81%\\n\",\n      \"#5304: 96.81%\\n\",\n      \"#5305: 96.81%\\n\",\n      \"#5306: 96.82%\\n\",\n      \"#5307: 96.82%\\n\",\n      \"#5308: 96.82%\\n\",\n      \"#5309: 96.82%\\n\",\n      \"#5310: 96.82%\\n\",\n      \"#5311: 96.82%\\n\",\n      \"#5312: 96.82%\\n\",\n      \"#5313: 96.82%\\n\",\n      \"#5314: 96.82%\\n\",\n      \"#5315: 96.82%\\n\",\n      \"#5316: 96.82%\\n\",\n      \"#5317: 96.82%\\n\",\n      \"#5318: 96.82%\\n\",\n      \"#5319: 96.82%\\n\",\n      \"#5320: 96.82%\\n\",\n      \"#5321: 96.82%\\n\",\n      \"#5322: 96.83%\\n\",\n      \"#5323: 96.83%\\n\",\n      \"#5324: 96.83%\\n\",\n      \"#5325: 96.83%\\n\",\n      \"#5326: 96.83%\\n\",\n      \"#5327: 96.83%\\n\",\n      \"#5328: 96.83%\\n\",\n      \"#5329: 96.83%\\n\",\n      \"#5330: 96.83%\\n\",\n      \"#5331: 96.83%\\n\",\n      \"#5332: 96.83%\\n\",\n      \"#5333: 96.83%\\n\",\n      \"#5334: 96.83%\\n\",\n      \"#5335: 96.83%\\n\",\n      \"#5336: 96.83%\\n\",\n      \"#5337: 96.83%\\n\",\n      \"#5338: 96.83%\\n\",\n      \"#5339: 96.84%\\n\",\n      \"#5340: 96.84%\\n\",\n      \"#5341: 96.84%\\n\",\n      \"#5342: 96.84%\\n\",\n      \"#5343: 96.84%\\n\",\n      \"#5344: 96.84%\\n\",\n      \"#5345: 96.84%\\n\",\n      \"#5346: 96.84%\\n\",\n      \"#5347: 96.84%\\n\",\n      \"#5348: 96.84%\\n\",\n      \"#5349: 96.84%\\n\",\n      \"#5350: 96.84%\\n\",\n      \"#5351: 96.84%\\n\",\n      \"#5352: 96.84%\\n\",\n      \"#5353: 96.84%\\n\",\n      \"#5354: 96.84%\\n\",\n      \"#5355: 96.84%\\n\",\n      \"#5356: 96.85%\\n\",\n      \"#5357: 96.85%\\n\",\n      \"#5358: 96.85%\\n\",\n      \"#5359: 96.85%\\n\",\n      \"#5360: 96.85%\\n\",\n      \"#5361: 96.85%\\n\",\n      \"#5362: 96.85%\\n\",\n      \"#5363: 96.85%\\n\",\n      \"#5364: 96.85%\\n\",\n      \"#5365: 96.85%\\n\",\n      \"#5366: 96.85%\\n\",\n      \"#5367: 96.85%\\n\",\n      \"#5368: 96.85%\\n\",\n      \"#5369: 96.85%\\n\",\n      \"#5370: 96.85%\\n\",\n      \"#5371: 96.85%\\n\",\n      \"#5372: 96.85%\\n\",\n      \"#5373: 96.86%\\n\",\n      \"#5374: 96.86%\\n\",\n      \"#5375: 96.86%\\n\",\n      \"#5376: 96.86%\\n\",\n      \"#5377: 96.86%\\n\",\n      \"#5378: 96.86%\\n\",\n      \"#5379: 96.86%\\n\",\n      \"#5380: 96.86%\\n\",\n      \"#5381: 96.86%\\n\",\n      \"#5382: 96.86%\\n\",\n      \"#5383: 96.86%\\n\",\n      \"#5384: 96.86%\\n\",\n      \"#5385: 96.86%\\n\",\n      \"#5386: 96.86%\\n\",\n      \"#5387: 96.86%\\n\",\n      \"#5388: 96.86%\\n\",\n      \"#5389: 96.86%\\n\",\n      \"#5390: 96.87%\\n\",\n      \"#5391: 96.87%\\n\",\n      \"#5392: 96.87%\\n\",\n      \"#5393: 96.87%\\n\",\n      \"#5394: 96.87%\\n\",\n      \"#5395: 96.87%\\n\",\n      \"#5396: 96.87%\\n\",\n      \"#5397: 96.87%\\n\",\n      \"#5398: 96.87%\\n\",\n      \"#5399: 96.87%\\n\",\n      \"#5400: 96.87%\\n\",\n      \"#5401: 96.87%\\n\",\n      \"#5402: 96.87%\\n\",\n      \"#5403: 96.87%\\n\",\n      \"#5404: 96.87%\\n\",\n      \"#5405: 96.87%\\n\",\n      \"#5406: 96.87%\\n\",\n      \"#5407: 96.88%\\n\",\n      \"#5408: 96.88%\\n\",\n      \"#5409: 96.88%\\n\",\n      \"#5410: 96.88%\\n\",\n      \"#5411: 96.88%\\n\",\n      \"#5412: 96.88%\\n\",\n      \"#5413: 96.88%\\n\",\n      \"#5414: 96.88%\\n\",\n      \"#5415: 96.88%\\n\",\n      \"#5416: 96.88%\\n\",\n      \"#5417: 96.88%\\n\",\n      \"#5418: 96.88%\\n\",\n      \"#5419: 96.88%\\n\",\n      \"#5420: 96.88%\\n\",\n      \"#5421: 96.88%\\n\",\n      \"#5422: 96.88%\\n\",\n      \"#5423: 96.88%\\n\",\n      \"#5424: 96.88%\\n\",\n      \"#5425: 96.89%\\n\",\n      \"#5426: 96.89%\\n\",\n      \"#5427: 96.89%\\n\",\n      \"#5428: 96.89%\\n\",\n      \"#5429: 96.89%\\n\",\n      \"#5430: 96.89%\\n\",\n      \"#5431: 96.89%\\n\",\n      \"#5432: 96.89%\\n\",\n      \"#5433: 96.89%\\n\",\n      \"#5434: 96.89%\\n\",\n      \"#5435: 96.89%\\n\",\n      \"#5436: 96.89%\\n\",\n      \"#5437: 96.89%\\n\",\n      \"#5438: 96.89%\\n\",\n      \"#5439: 96.89%\\n\",\n      \"#5440: 96.89%\\n\",\n      \"#5441: 96.89%\\n\",\n      \"#5442: 96.90%\\n\",\n      \"#5443: 96.90%\\n\",\n      \"#5444: 96.90%\\n\",\n      \"#5445: 96.90%\\n\",\n      \"#5446: 96.90%\\n\",\n      \"#5447: 96.90%\\n\",\n      \"#5448: 96.90%\\n\",\n      \"#5449: 96.90%\\n\",\n      \"#5450: 96.90%\\n\",\n      \"#5451: 96.90%\\n\",\n      \"#5452: 96.90%\\n\",\n      \"#5453: 96.90%\\n\",\n      \"#5454: 96.90%\\n\",\n      \"#5455: 96.90%\\n\",\n      \"#5456: 96.90%\\n\",\n      \"#5457: 96.90%\\n\",\n      \"#5458: 96.90%\\n\",\n      \"#5459: 96.90%\\n\",\n      \"#5460: 96.91%\\n\",\n      \"#5461: 96.91%\\n\",\n      \"#5462: 96.91%\\n\",\n      \"#5463: 96.91%\\n\",\n      \"#5464: 96.91%\\n\",\n      \"#5465: 96.91%\\n\",\n      \"#5466: 96.91%\\n\",\n      \"#5467: 96.91%\\n\",\n      \"#5468: 96.91%\\n\",\n      \"#5469: 96.91%\\n\",\n      \"#5470: 96.91%\\n\",\n      \"#5471: 96.91%\\n\",\n      \"#5472: 96.91%\\n\",\n      \"#5473: 96.91%\\n\",\n      \"#5474: 96.91%\\n\",\n      \"#5475: 96.91%\\n\",\n      \"#5476: 96.91%\\n\",\n      \"#5477: 96.91%\\n\",\n      \"#5478: 96.92%\\n\",\n      \"#5479: 96.92%\\n\",\n      \"#5480: 96.92%\\n\",\n      \"#5481: 96.92%\\n\",\n      \"#5482: 96.92%\\n\",\n      \"#5483: 96.92%\\n\",\n      \"#5484: 96.92%\\n\",\n      \"#5485: 96.92%\\n\",\n      \"#5486: 96.92%\\n\",\n      \"#5487: 96.92%\\n\",\n      \"#5488: 96.92%\\n\",\n      \"#5489: 96.92%\\n\",\n      \"#5490: 96.92%\\n\",\n      \"#5491: 96.92%\\n\",\n      \"#5492: 96.92%\\n\",\n      \"#5493: 96.92%\\n\",\n      \"#5494: 96.92%\\n\",\n      \"#5495: 96.93%\\n\",\n      \"#5496: 96.93%\\n\",\n      \"#5497: 96.93%\\n\",\n      \"#5498: 96.93%\\n\",\n      \"#5499: 96.93%\\n\",\n      \"#5500: 96.93%\\n\",\n      \"#5501: 96.93%\\n\",\n      \"#5502: 96.93%\\n\",\n      \"#5503: 96.93%\\n\",\n      \"#5504: 96.93%\\n\",\n      \"#5505: 96.93%\\n\",\n      \"#5506: 96.93%\\n\",\n      \"#5507: 96.93%\\n\",\n      \"#5508: 96.93%\\n\",\n      \"#5509: 96.93%\\n\",\n      \"#5510: 96.93%\\n\",\n      \"#5511: 96.93%\\n\",\n      \"#5512: 96.93%\\n\",\n      \"#5513: 96.94%\\n\",\n      \"#5514: 96.94%\\n\",\n      \"#5515: 96.94%\\n\",\n      \"#5516: 96.94%\\n\",\n      \"#5517: 96.94%\\n\",\n      \"#5518: 96.94%\\n\",\n      \"#5519: 96.94%\\n\",\n      \"#5520: 96.94%\\n\",\n      \"#5521: 96.94%\\n\",\n      \"#5522: 96.94%\\n\",\n      \"#5523: 96.94%\\n\",\n      \"#5524: 96.94%\\n\",\n      \"#5525: 96.94%\\n\",\n      \"#5526: 96.94%\\n\",\n      \"#5527: 96.94%\\n\",\n      \"#5528: 96.94%\\n\",\n      \"#5529: 96.94%\\n\",\n      \"#5530: 96.94%\\n\",\n      \"#5531: 96.95%\\n\",\n      \"#5532: 96.95%\\n\",\n      \"#5533: 96.95%\\n\",\n      \"#5534: 96.95%\\n\",\n      \"#5535: 96.95%\\n\",\n      \"#5536: 96.95%\\n\",\n      \"#5537: 96.95%\\n\",\n      \"#5538: 96.95%\\n\",\n      \"#5539: 96.95%\\n\",\n      \"#5540: 96.95%\\n\",\n      \"#5541: 96.95%\\n\",\n      \"#5542: 96.95%\\n\",\n      \"#5543: 96.95%\\n\",\n      \"#5544: 96.95%\\n\",\n      \"#5545: 96.95%\\n\",\n      \"#5546: 96.95%\\n\",\n      \"#5547: 96.95%\\n\",\n      \"#5548: 96.95%\\n\",\n      \"#5549: 96.95%\\n\",\n      \"#5550: 96.96%\\n\",\n      \"#5551: 96.96%\\n\",\n      \"#5552: 96.96%\\n\",\n      \"#5553: 96.96%\\n\",\n      \"#5554: 96.96%\\n\",\n      \"#5555: 96.96%\\n\",\n      \"#5556: 96.96%\\n\",\n      \"#5557: 96.96%\\n\",\n      \"#5558: 96.96%\\n\",\n      \"#5559: 96.96%\\n\",\n      \"#5560: 96.96%\\n\",\n      \"#5561: 96.96%\\n\",\n      \"#5562: 96.96%\\n\",\n      \"#5563: 96.96%\\n\",\n      \"#5564: 96.96%\\n\",\n      \"#5565: 96.96%\\n\",\n      \"#5566: 96.96%\\n\",\n      \"#5567: 96.96%\\n\",\n      \"#5568: 96.97%\\n\",\n      \"#5569: 96.97%\\n\",\n      \"#5570: 96.97%\\n\",\n      \"#5571: 96.97%\\n\",\n      \"#5572: 96.97%\\n\",\n      \"#5573: 96.97%\\n\",\n      \"#5574: 96.97%\\n\",\n      \"#5575: 96.97%\\n\",\n      \"#5576: 96.97%\\n\",\n      \"#5577: 96.97%\\n\",\n      \"#5578: 96.97%\\n\",\n      \"#5579: 96.97%\\n\",\n      \"#5580: 96.97%\\n\",\n      \"#5581: 96.97%\\n\",\n      \"#5582: 96.97%\\n\",\n      \"#5583: 96.97%\\n\",\n      \"#5584: 96.97%\\n\",\n      \"#5585: 96.97%\\n\",\n      \"#5586: 96.98%\\n\",\n      \"#5587: 96.98%\\n\",\n      \"#5588: 96.98%\\n\",\n      \"#5589: 96.98%\\n\",\n      \"#5590: 96.98%\\n\",\n      \"#5591: 96.98%\\n\",\n      \"#5592: 96.98%\\n\",\n      \"#5593: 96.98%\\n\",\n      \"#5594: 96.98%\\n\",\n      \"#5595: 96.98%\\n\",\n      \"#5596: 96.98%\\n\",\n      \"#5597: 96.98%\\n\",\n      \"#5598: 96.98%\\n\",\n      \"#5599: 96.98%\\n\",\n      \"#5600: 96.96%\\n\",\n      \"#5601: 96.97%\\n\",\n      \"#5602: 96.97%\\n\",\n      \"#5603: 96.97%\\n\",\n      \"#5604: 96.97%\\n\",\n      \"#5605: 96.97%\\n\",\n      \"#5606: 96.97%\\n\",\n      \"#5607: 96.97%\\n\",\n      \"#5608: 96.97%\\n\",\n      \"#5609: 96.97%\\n\",\n      \"#5610: 96.97%\\n\",\n      \"#5611: 96.97%\\n\",\n      \"#5612: 96.97%\\n\",\n      \"#5613: 96.97%\\n\",\n      \"#5614: 96.97%\\n\",\n      \"#5615: 96.97%\\n\",\n      \"#5616: 96.97%\\n\",\n      \"#5617: 96.97%\\n\",\n      \"#5618: 96.97%\\n\",\n      \"#5619: 96.98%\\n\",\n      \"#5620: 96.98%\\n\",\n      \"#5621: 96.98%\\n\",\n      \"#5622: 96.98%\\n\",\n      \"#5623: 96.98%\\n\",\n      \"#5624: 96.98%\\n\",\n      \"#5625: 96.98%\\n\",\n      \"#5626: 96.98%\\n\",\n      \"#5627: 96.98%\\n\",\n      \"#5628: 96.98%\\n\",\n      \"#5629: 96.98%\\n\",\n      \"#5630: 96.98%\\n\",\n      \"#5631: 96.98%\\n\",\n      \"#5632: 96.98%\\n\",\n      \"#5633: 96.98%\\n\",\n      \"#5634: 96.98%\\n\",\n      \"#5635: 96.98%\\n\",\n      \"#5636: 96.98%\\n\",\n      \"#5637: 96.98%\\n\",\n      \"#5638: 96.99%\\n\",\n      \"#5639: 96.99%\\n\",\n      \"#5640: 96.99%\\n\",\n      \"#5641: 96.99%\\n\",\n      \"#5642: 96.99%\\n\",\n      \"#5643: 96.99%\\n\",\n      \"#5644: 96.99%\\n\",\n      \"#5645: 96.99%\\n\",\n      \"#5646: 96.99%\\n\",\n      \"#5647: 96.99%\\n\",\n      \"#5648: 96.99%\\n\",\n      \"#5649: 96.99%\\n\",\n      \"#5650: 96.99%\\n\",\n      \"#5651: 96.99%\\n\",\n      \"#5652: 96.99%\\n\",\n      \"#5653: 96.99%\\n\",\n      \"#5654: 96.99%\\n\",\n      \"#5655: 96.99%\\n\",\n      \"#5656: 96.99%\\n\",\n      \"#5657: 97.00%\\n\",\n      \"#5658: 97.00%\\n\",\n      \"#5659: 97.00%\\n\",\n      \"#5660: 97.00%\\n\",\n      \"#5661: 97.00%\\n\",\n      \"#5662: 97.00%\\n\",\n      \"#5663: 97.00%\\n\",\n      \"#5664: 97.00%\\n\",\n      \"#5665: 97.00%\\n\",\n      \"#5666: 97.00%\\n\",\n      \"#5667: 97.00%\\n\",\n      \"#5668: 97.00%\\n\",\n      \"#5669: 97.00%\\n\",\n      \"#5670: 97.00%\\n\",\n      \"#5671: 97.00%\\n\",\n      \"#5672: 97.00%\\n\",\n      \"#5673: 97.00%\\n\",\n      \"#5674: 97.00%\\n\",\n      \"#5675: 97.00%\\n\",\n      \"#5676: 97.01%\\n\",\n      \"#5677: 97.01%\\n\",\n      \"#5678: 97.01%\\n\",\n      \"#5679: 97.01%\\n\",\n      \"#5680: 97.01%\\n\",\n      \"#5681: 97.01%\\n\",\n      \"#5682: 97.01%\\n\",\n      \"#5683: 97.01%\\n\",\n      \"#5684: 97.01%\\n\",\n      \"#5685: 97.01%\\n\",\n      \"#5686: 97.01%\\n\",\n      \"#5687: 97.01%\\n\",\n      \"#5688: 97.01%\\n\",\n      \"#5689: 97.01%\\n\",\n      \"#5690: 97.01%\\n\",\n      \"#5691: 97.01%\\n\",\n      \"#5692: 97.01%\\n\",\n      \"#5693: 97.01%\\n\",\n      \"#5694: 97.01%\\n\",\n      \"#5695: 97.02%\\n\",\n      \"#5696: 97.02%\\n\",\n      \"#5697: 97.02%\\n\",\n      \"#5698: 97.02%\\n\",\n      \"#5699: 97.02%\\n\",\n      \"#5700: 97.02%\\n\",\n      \"#5701: 97.02%\\n\",\n      \"#5702: 97.02%\\n\",\n      \"#5703: 97.02%\\n\",\n      \"#5704: 97.02%\\n\",\n      \"#5705: 97.02%\\n\",\n      \"#5706: 97.02%\\n\",\n      \"#5707: 97.02%\\n\",\n      \"#5708: 97.02%\\n\",\n      \"#5709: 97.02%\\n\",\n      \"#5710: 97.02%\\n\",\n      \"#5711: 97.02%\\n\",\n      \"#5712: 97.02%\\n\",\n      \"#5713: 97.02%\\n\",\n      \"#5714: 97.03%\\n\",\n      \"#5715: 97.03%\\n\",\n      \"#5716: 97.03%\\n\",\n      \"#5717: 97.03%\\n\",\n      \"#5718: 97.03%\\n\",\n      \"#5719: 97.03%\\n\",\n      \"#5720: 97.03%\\n\",\n      \"#5721: 97.03%\\n\",\n      \"#5722: 97.03%\\n\",\n      \"#5723: 97.03%\\n\",\n      \"#5724: 97.03%\\n\",\n      \"#5725: 97.03%\\n\",\n      \"#5726: 97.03%\\n\",\n      \"#5727: 97.03%\\n\",\n      \"#5728: 97.03%\\n\",\n      \"#5729: 97.03%\\n\",\n      \"#5730: 97.03%\\n\",\n      \"#5731: 97.03%\\n\",\n      \"#5732: 97.03%\\n\",\n      \"#5733: 97.04%\\n\",\n      \"#5734: 97.02%\\n\",\n      \"#5735: 97.02%\\n\",\n      \"#5736: 97.02%\\n\",\n      \"#5737: 97.02%\\n\",\n      \"#5738: 97.02%\\n\",\n      \"#5739: 97.02%\\n\",\n      \"#5740: 97.02%\\n\",\n      \"#5741: 97.02%\\n\",\n      \"#5742: 97.02%\\n\",\n      \"#5743: 97.02%\\n\",\n      \"#5744: 97.02%\\n\",\n      \"#5745: 97.02%\\n\",\n      \"#5746: 97.02%\\n\",\n      \"#5747: 97.03%\\n\",\n      \"#5748: 97.03%\\n\",\n      \"#5749: 97.03%\\n\",\n      \"#5750: 97.03%\\n\",\n      \"#5751: 97.03%\\n\",\n      \"#5752: 97.03%\\n\",\n      \"#5753: 97.03%\\n\",\n      \"#5754: 97.03%\\n\",\n      \"#5755: 97.03%\\n\",\n      \"#5756: 97.03%\\n\",\n      \"#5757: 97.03%\\n\",\n      \"#5758: 97.03%\\n\",\n      \"#5759: 97.03%\\n\",\n      \"#5760: 97.03%\\n\",\n      \"#5761: 97.03%\\n\",\n      \"#5762: 97.03%\\n\",\n      \"#5763: 97.03%\\n\",\n      \"#5764: 97.03%\\n\",\n      \"#5765: 97.03%\\n\",\n      \"#5766: 97.03%\\n\",\n      \"#5767: 97.04%\\n\",\n      \"#5768: 97.04%\\n\",\n      \"#5769: 97.04%\\n\",\n      \"#5770: 97.04%\\n\",\n      \"#5771: 97.04%\\n\",\n      \"#5772: 97.04%\\n\",\n      \"#5773: 97.04%\\n\",\n      \"#5774: 97.04%\\n\",\n      \"#5775: 97.04%\\n\",\n      \"#5776: 97.04%\\n\",\n      \"#5777: 97.04%\\n\",\n      \"#5778: 97.04%\\n\",\n      \"#5779: 97.04%\\n\",\n      \"#5780: 97.04%\\n\",\n      \"#5781: 97.04%\\n\",\n      \"#5782: 97.04%\\n\",\n      \"#5783: 97.04%\\n\",\n      \"#5784: 97.04%\\n\",\n      \"#5785: 97.04%\\n\",\n      \"#5786: 97.05%\\n\",\n      \"#5787: 97.05%\\n\",\n      \"#5788: 97.05%\\n\",\n      \"#5789: 97.05%\\n\",\n      \"#5790: 97.05%\\n\",\n      \"#5791: 97.05%\\n\",\n      \"#5792: 97.05%\\n\",\n      \"#5793: 97.05%\\n\",\n      \"#5794: 97.05%\\n\",\n      \"#5795: 97.05%\\n\",\n      \"#5796: 97.05%\\n\",\n      \"#5797: 97.05%\\n\",\n      \"#5798: 97.05%\\n\",\n      \"#5799: 97.05%\\n\",\n      \"#5800: 97.05%\\n\",\n      \"#5801: 97.05%\\n\",\n      \"#5802: 97.05%\\n\",\n      \"#5803: 97.05%\\n\",\n      \"#5804: 97.05%\\n\",\n      \"#5805: 97.05%\\n\",\n      \"#5806: 97.06%\\n\",\n      \"#5807: 97.06%\\n\",\n      \"#5808: 97.06%\\n\",\n      \"#5809: 97.06%\\n\",\n      \"#5810: 97.06%\\n\",\n      \"#5811: 97.06%\\n\",\n      \"#5812: 97.06%\\n\",\n      \"#5813: 97.06%\\n\",\n      \"#5814: 97.06%\\n\",\n      \"#5815: 97.06%\\n\",\n      \"#5816: 97.06%\\n\",\n      \"#5817: 97.06%\\n\",\n      \"#5818: 97.06%\\n\",\n      \"#5819: 97.06%\\n\",\n      \"#5820: 97.06%\\n\",\n      \"#5821: 97.06%\\n\",\n      \"#5822: 97.06%\\n\",\n      \"#5823: 97.06%\\n\",\n      \"#5824: 97.06%\\n\",\n      \"#5825: 97.06%\\n\",\n      \"#5826: 97.07%\\n\",\n      \"#5827: 97.07%\\n\",\n      \"#5828: 97.07%\\n\",\n      \"#5829: 97.07%\\n\",\n      \"#5830: 97.07%\\n\",\n      \"#5831: 97.07%\\n\",\n      \"#5832: 97.07%\\n\",\n      \"#5833: 97.07%\\n\",\n      \"#5834: 97.07%\\n\",\n      \"#5835: 97.07%\\n\",\n      \"#5836: 97.07%\\n\",\n      \"#5837: 97.07%\\n\",\n      \"#5838: 97.07%\\n\",\n      \"#5839: 97.07%\\n\",\n      \"#5840: 97.07%\\n\",\n      \"#5841: 97.06%\\n\",\n      \"#5842: 97.04%\\n\",\n      \"#5843: 97.04%\\n\",\n      \"#5844: 97.04%\\n\",\n      \"#5845: 97.04%\\n\",\n      \"#5846: 97.04%\\n\",\n      \"#5847: 97.04%\\n\",\n      \"#5848: 97.04%\\n\",\n      \"#5849: 97.04%\\n\",\n      \"#5850: 97.04%\\n\",\n      \"#5851: 97.04%\\n\",\n      \"#5852: 97.04%\\n\",\n      \"#5853: 97.04%\\n\",\n      \"#5854: 97.05%\\n\",\n      \"#5855: 97.05%\\n\",\n      \"#5856: 97.05%\\n\",\n      \"#5857: 97.05%\\n\",\n      \"#5858: 97.05%\\n\",\n      \"#5859: 97.05%\\n\",\n      \"#5860: 97.05%\\n\",\n      \"#5861: 97.05%\\n\",\n      \"#5862: 97.05%\\n\",\n      \"#5863: 97.05%\\n\",\n      \"#5864: 97.05%\\n\",\n      \"#5865: 97.05%\\n\",\n      \"#5866: 97.05%\\n\",\n      \"#5867: 97.05%\\n\",\n      \"#5868: 97.05%\\n\",\n      \"#5869: 97.05%\\n\",\n      \"#5870: 97.05%\\n\",\n      \"#5871: 97.05%\\n\",\n      \"#5872: 97.05%\\n\",\n      \"#5873: 97.05%\\n\",\n      \"#5874: 97.06%\\n\",\n      \"#5875: 97.06%\\n\",\n      \"#5876: 97.06%\\n\",\n      \"#5877: 97.06%\\n\",\n      \"#5878: 97.06%\\n\",\n      \"#5879: 97.06%\\n\",\n      \"#5880: 97.06%\\n\",\n      \"#5881: 97.06%\\n\",\n      \"#5882: 97.06%\\n\",\n      \"#5883: 97.06%\\n\",\n      \"#5884: 97.06%\\n\",\n      \"#5885: 97.06%\\n\",\n      \"#5886: 97.06%\\n\",\n      \"#5887: 97.04%\\n\",\n      \"#5888: 97.05%\\n\",\n      \"#5889: 97.05%\\n\",\n      \"#5890: 97.05%\\n\",\n      \"#5891: 97.05%\\n\",\n      \"#5892: 97.05%\\n\",\n      \"#5893: 97.05%\\n\",\n      \"#5894: 97.05%\\n\",\n      \"#5895: 97.05%\\n\",\n      \"#5896: 97.05%\\n\",\n      \"#5897: 97.05%\\n\",\n      \"#5898: 97.05%\\n\",\n      \"#5899: 97.05%\\n\",\n      \"#5900: 97.05%\\n\",\n      \"#5901: 97.05%\\n\",\n      \"#5902: 97.05%\\n\",\n      \"#5903: 97.05%\\n\",\n      \"#5904: 97.05%\\n\",\n      \"#5905: 97.05%\\n\",\n      \"#5906: 97.05%\\n\",\n      \"#5907: 97.05%\\n\",\n      \"#5908: 97.06%\\n\",\n      \"#5909: 97.06%\\n\",\n      \"#5910: 97.06%\\n\",\n      \"#5911: 97.06%\\n\",\n      \"#5912: 97.06%\\n\",\n      \"#5913: 97.06%\\n\",\n      \"#5914: 97.06%\\n\",\n      \"#5915: 97.06%\\n\",\n      \"#5916: 97.06%\\n\",\n      \"#5917: 97.06%\\n\",\n      \"#5918: 97.06%\\n\",\n      \"#5919: 97.06%\\n\",\n      \"#5920: 97.06%\\n\",\n      \"#5921: 97.06%\\n\",\n      \"#5922: 97.06%\\n\",\n      \"#5923: 97.06%\\n\",\n      \"#5924: 97.06%\\n\",\n      \"#5925: 97.06%\\n\",\n      \"#5926: 97.06%\\n\",\n      \"#5927: 97.06%\\n\",\n      \"#5928: 97.07%\\n\",\n      \"#5929: 97.07%\\n\",\n      \"#5930: 97.07%\\n\",\n      \"#5931: 97.07%\\n\",\n      \"#5932: 97.07%\\n\",\n      \"#5933: 97.07%\\n\",\n      \"#5934: 97.07%\\n\",\n      \"#5935: 97.07%\\n\",\n      \"#5936: 97.07%\\n\",\n      \"#5937: 97.07%\\n\",\n      \"#5938: 97.07%\\n\",\n      \"#5939: 97.07%\\n\",\n      \"#5940: 97.07%\\n\",\n      \"#5941: 97.07%\\n\",\n      \"#5942: 97.07%\\n\",\n      \"#5943: 97.07%\\n\",\n      \"#5944: 97.07%\\n\",\n      \"#5945: 97.07%\\n\",\n      \"#5946: 97.07%\\n\",\n      \"#5947: 97.07%\\n\",\n      \"#5948: 97.08%\\n\",\n      \"#5949: 97.08%\\n\",\n      \"#5950: 97.08%\\n\",\n      \"#5951: 97.08%\\n\",\n      \"#5952: 97.08%\\n\",\n      \"#5953: 97.08%\\n\",\n      \"#5954: 97.08%\\n\",\n      \"#5955: 97.06%\\n\",\n      \"#5956: 97.06%\\n\",\n      \"#5957: 97.06%\\n\",\n      \"#5958: 97.06%\\n\",\n      \"#5959: 97.06%\\n\",\n      \"#5960: 97.06%\\n\",\n      \"#5961: 97.06%\\n\",\n      \"#5962: 97.07%\\n\",\n      \"#5963: 97.07%\\n\",\n      \"#5964: 97.07%\\n\",\n      \"#5965: 97.07%\\n\",\n      \"#5966: 97.07%\\n\",\n      \"#5967: 97.07%\\n\",\n      \"#5968: 97.07%\\n\",\n      \"#5969: 97.07%\\n\",\n      \"#5970: 97.07%\\n\",\n      \"#5971: 97.07%\\n\",\n      \"#5972: 97.07%\\n\",\n      \"#5973: 97.05%\\n\",\n      \"#5974: 97.05%\\n\",\n      \"#5975: 97.05%\\n\",\n      \"#5976: 97.06%\\n\",\n      \"#5977: 97.06%\\n\",\n      \"#5978: 97.06%\\n\",\n      \"#5979: 97.06%\\n\",\n      \"#5980: 97.06%\\n\",\n      \"#5981: 97.06%\\n\",\n      \"#5982: 97.06%\\n\",\n      \"#5983: 97.06%\\n\",\n      \"#5984: 97.06%\\n\",\n      \"#5985: 97.06%\\n\",\n      \"#5986: 97.06%\\n\",\n      \"#5987: 97.06%\\n\",\n      \"#5988: 97.06%\\n\",\n      \"#5989: 97.06%\\n\",\n      \"#5990: 97.06%\\n\",\n      \"#5991: 97.06%\\n\",\n      \"#5992: 97.06%\\n\",\n      \"#5993: 97.06%\\n\",\n      \"#5994: 97.06%\\n\",\n      \"#5995: 97.06%\\n\",\n      \"#5996: 97.07%\\n\",\n      \"#5997: 97.05%\\n\",\n      \"#5998: 97.05%\\n\",\n      \"#5999: 97.05%\\n\",\n      \"#6000: 97.05%\\n\",\n      \"#6001: 97.05%\\n\",\n      \"#6002: 97.05%\\n\",\n      \"#6003: 97.05%\\n\",\n      \"#6004: 97.05%\\n\",\n      \"#6005: 97.05%\\n\",\n      \"#6006: 97.05%\\n\",\n      \"#6007: 97.05%\\n\",\n      \"#6008: 97.05%\\n\",\n      \"#6009: 97.05%\\n\",\n      \"#6010: 97.06%\\n\",\n      \"#6011: 97.06%\\n\",\n      \"#6012: 97.06%\\n\",\n      \"#6013: 97.06%\\n\",\n      \"#6014: 97.06%\\n\",\n      \"#6015: 97.06%\\n\",\n      \"#6016: 97.06%\\n\",\n      \"#6017: 97.06%\\n\",\n      \"#6018: 97.06%\\n\",\n      \"#6019: 97.06%\\n\",\n      \"#6020: 97.06%\\n\",\n      \"#6021: 97.06%\\n\",\n      \"#6022: 97.06%\\n\",\n      \"#6023: 97.05%\\n\",\n      \"#6024: 97.05%\\n\",\n      \"#6025: 97.05%\\n\",\n      \"#6026: 97.05%\\n\",\n      \"#6027: 97.05%\\n\",\n      \"#6028: 97.05%\\n\",\n      \"#6029: 97.05%\\n\",\n      \"#6030: 97.05%\\n\",\n      \"#6031: 97.05%\\n\",\n      \"#6032: 97.05%\\n\",\n      \"#6033: 97.05%\\n\",\n      \"#6034: 97.05%\\n\",\n      \"#6035: 97.05%\\n\",\n      \"#6036: 97.05%\\n\",\n      \"#6037: 97.05%\\n\",\n      \"#6038: 97.05%\\n\",\n      \"#6039: 97.05%\\n\",\n      \"#6040: 97.05%\\n\",\n      \"#6041: 97.05%\\n\",\n      \"#6042: 97.05%\\n\",\n      \"#6043: 97.05%\\n\",\n      \"#6044: 97.06%\\n\",\n      \"#6045: 97.06%\\n\",\n      \"#6046: 97.06%\\n\",\n      \"#6047: 97.06%\\n\",\n      \"#6048: 97.06%\\n\",\n      \"#6049: 97.06%\\n\",\n      \"#6050: 97.06%\\n\",\n      \"#6051: 97.06%\\n\",\n      \"#6052: 97.06%\\n\",\n      \"#6053: 97.06%\\n\",\n      \"#6054: 97.06%\\n\",\n      \"#6055: 97.06%\\n\",\n      \"#6056: 97.06%\\n\",\n      \"#6057: 97.06%\\n\",\n      \"#6058: 97.06%\\n\",\n      \"#6059: 97.05%\\n\",\n      \"#6060: 97.05%\\n\",\n      \"#6061: 97.05%\\n\",\n      \"#6062: 97.05%\\n\",\n      \"#6063: 97.05%\\n\",\n      \"#6064: 97.05%\\n\",\n      \"#6065: 97.03%\\n\",\n      \"#6066: 97.03%\\n\",\n      \"#6067: 97.03%\\n\",\n      \"#6068: 97.03%\\n\",\n      \"#6069: 97.03%\\n\",\n      \"#6070: 97.04%\\n\",\n      \"#6071: 97.04%\\n\",\n      \"#6072: 97.04%\\n\",\n      \"#6073: 97.04%\\n\",\n      \"#6074: 97.04%\\n\",\n      \"#6075: 97.04%\\n\",\n      \"#6076: 97.04%\\n\",\n      \"#6077: 97.04%\\n\",\n      \"#6078: 97.04%\\n\",\n      \"#6079: 97.04%\\n\",\n      \"#6080: 97.04%\\n\",\n      \"#6081: 97.04%\\n\",\n      \"#6082: 97.04%\\n\",\n      \"#6083: 97.04%\\n\",\n      \"#6084: 97.04%\\n\",\n      \"#6085: 97.03%\\n\",\n      \"#6086: 97.03%\\n\",\n      \"#6087: 97.03%\\n\",\n      \"#6088: 97.03%\\n\",\n      \"#6089: 97.03%\\n\",\n      \"#6090: 97.03%\\n\",\n      \"#6091: 97.01%\\n\",\n      \"#6092: 97.01%\\n\",\n      \"#6093: 97.01%\\n\",\n      \"#6094: 97.01%\\n\",\n      \"#6095: 97.01%\\n\",\n      \"#6096: 97.01%\\n\",\n      \"#6097: 97.02%\\n\",\n      \"#6098: 97.02%\\n\",\n      \"#6099: 97.02%\\n\",\n      \"#6100: 97.02%\\n\",\n      \"#6101: 97.02%\\n\",\n      \"#6102: 97.02%\\n\",\n      \"#6103: 97.02%\\n\",\n      \"#6104: 97.02%\\n\",\n      \"#6105: 97.02%\\n\",\n      \"#6106: 97.02%\\n\",\n      \"#6107: 97.02%\\n\",\n      \"#6108: 97.02%\\n\",\n      \"#6109: 97.02%\\n\",\n      \"#6110: 97.02%\\n\",\n      \"#6111: 97.02%\\n\",\n      \"#6112: 97.02%\\n\",\n      \"#6113: 97.02%\\n\",\n      \"#6114: 97.02%\\n\",\n      \"#6115: 97.02%\\n\",\n      \"#6116: 97.02%\\n\",\n      \"#6117: 97.03%\\n\",\n      \"#6118: 97.03%\\n\",\n      \"#6119: 97.03%\\n\",\n      \"#6120: 97.03%\\n\",\n      \"#6121: 97.03%\\n\",\n      \"#6122: 97.03%\\n\",\n      \"#6123: 97.03%\\n\",\n      \"#6124: 97.03%\\n\",\n      \"#6125: 97.03%\\n\",\n      \"#6126: 97.03%\\n\",\n      \"#6127: 97.03%\\n\",\n      \"#6128: 97.03%\\n\",\n      \"#6129: 97.03%\\n\",\n      \"#6130: 97.03%\\n\",\n      \"#6131: 97.03%\\n\",\n      \"#6132: 97.03%\\n\",\n      \"#6133: 97.03%\\n\",\n      \"#6134: 97.03%\\n\",\n      \"#6135: 97.03%\\n\",\n      \"#6136: 97.03%\\n\",\n      \"#6137: 97.03%\\n\",\n      \"#6138: 97.04%\\n\",\n      \"#6139: 97.04%\\n\",\n      \"#6140: 97.04%\\n\",\n      \"#6141: 97.04%\\n\",\n      \"#6142: 97.04%\\n\",\n      \"#6143: 97.04%\\n\",\n      \"#6144: 97.04%\\n\",\n      \"#6145: 97.04%\\n\",\n      \"#6146: 97.04%\\n\",\n      \"#6147: 97.04%\\n\",\n      \"#6148: 97.04%\\n\",\n      \"#6149: 97.04%\\n\",\n      \"#6150: 97.04%\\n\",\n      \"#6151: 97.04%\\n\",\n      \"#6152: 97.04%\\n\",\n      \"#6153: 97.04%\\n\",\n      \"#6154: 97.04%\\n\",\n      \"#6155: 97.04%\\n\",\n      \"#6156: 97.04%\\n\",\n      \"#6157: 97.04%\\n\",\n      \"#6158: 97.04%\\n\",\n      \"#6159: 97.05%\\n\",\n      \"#6160: 97.05%\\n\",\n      \"#6161: 97.05%\\n\",\n      \"#6162: 97.05%\\n\",\n      \"#6163: 97.05%\\n\",\n      \"#6164: 97.05%\\n\",\n      \"#6165: 97.05%\\n\",\n      \"#6166: 97.05%\\n\",\n      \"#6167: 97.05%\\n\",\n      \"#6168: 97.05%\\n\",\n      \"#6169: 97.05%\\n\",\n      \"#6170: 97.05%\\n\",\n      \"#6171: 97.05%\\n\",\n      \"#6172: 97.04%\\n\",\n      \"#6173: 97.04%\\n\",\n      \"#6174: 97.04%\\n\",\n      \"#6175: 97.04%\\n\",\n      \"#6176: 97.04%\\n\",\n      \"#6177: 97.04%\\n\",\n      \"#6178: 97.04%\\n\",\n      \"#6179: 97.04%\\n\",\n      \"#6180: 97.04%\\n\",\n      \"#6181: 97.04%\\n\",\n      \"#6182: 97.04%\\n\",\n      \"#6183: 97.04%\\n\",\n      \"#6184: 97.04%\\n\",\n      \"#6185: 97.04%\\n\",\n      \"#6186: 97.04%\\n\",\n      \"#6187: 97.04%\\n\",\n      \"#6188: 97.04%\\n\",\n      \"#6189: 97.04%\\n\",\n      \"#6190: 97.04%\\n\",\n      \"#6191: 97.04%\\n\",\n      \"#6192: 97.05%\\n\",\n      \"#6193: 97.05%\\n\",\n      \"#6194: 97.05%\\n\",\n      \"#6195: 97.05%\\n\",\n      \"#6196: 97.05%\\n\",\n      \"#6197: 97.05%\\n\",\n      \"#6198: 97.05%\\n\",\n      \"#6199: 97.05%\\n\",\n      \"#6200: 97.05%\\n\",\n      \"#6201: 97.05%\\n\",\n      \"#6202: 97.05%\\n\",\n      \"#6203: 97.05%\\n\",\n      \"#6204: 97.05%\\n\",\n      \"#6205: 97.05%\\n\",\n      \"#6206: 97.05%\\n\",\n      \"#6207: 97.05%\\n\",\n      \"#6208: 97.05%\\n\",\n      \"#6209: 97.05%\\n\",\n      \"#6210: 97.05%\\n\",\n      \"#6211: 97.05%\\n\",\n      \"#6212: 97.05%\\n\",\n      \"#6213: 97.06%\\n\",\n      \"#6214: 97.06%\\n\",\n      \"#6215: 97.06%\\n\",\n      \"#6216: 97.06%\\n\",\n      \"#6217: 97.06%\\n\",\n      \"#6218: 97.06%\\n\",\n      \"#6219: 97.06%\\n\",\n      \"#6220: 97.06%\\n\",\n      \"#6221: 97.06%\\n\",\n      \"#6222: 97.06%\\n\",\n      \"#6223: 97.06%\\n\",\n      \"#6224: 97.06%\\n\",\n      \"#6225: 97.06%\\n\",\n      \"#6226: 97.06%\\n\",\n      \"#6227: 97.06%\\n\",\n      \"#6228: 97.06%\\n\",\n      \"#6229: 97.06%\\n\",\n      \"#6230: 97.06%\\n\",\n      \"#6231: 97.06%\\n\",\n      \"#6232: 97.06%\\n\",\n      \"#6233: 97.06%\\n\",\n      \"#6234: 97.06%\\n\",\n      \"#6235: 97.07%\\n\",\n      \"#6236: 97.07%\\n\",\n      \"#6237: 97.07%\\n\",\n      \"#6238: 97.07%\\n\",\n      \"#6239: 97.07%\\n\",\n      \"#6240: 97.07%\\n\",\n      \"#6241: 97.07%\\n\",\n      \"#6242: 97.07%\\n\",\n      \"#6243: 97.07%\\n\",\n      \"#6244: 97.07%\\n\",\n      \"#6245: 97.07%\\n\",\n      \"#6246: 97.07%\\n\",\n      \"#6247: 97.07%\\n\",\n      \"#6248: 97.07%\\n\",\n      \"#6249: 97.07%\\n\",\n      \"#6250: 97.07%\\n\",\n      \"#6251: 97.07%\\n\",\n      \"#6252: 97.07%\\n\",\n      \"#6253: 97.07%\\n\",\n      \"#6254: 97.07%\\n\",\n      \"#6255: 97.07%\\n\",\n      \"#6256: 97.08%\\n\",\n      \"#6257: 97.08%\\n\",\n      \"#6258: 97.08%\\n\",\n      \"#6259: 97.08%\\n\",\n      \"#6260: 97.08%\\n\",\n      \"#6261: 97.08%\\n\",\n      \"#6262: 97.08%\\n\",\n      \"#6263: 97.08%\\n\",\n      \"#6264: 97.08%\\n\",\n      \"#6265: 97.08%\\n\",\n      \"#6266: 97.08%\\n\",\n      \"#6267: 97.08%\\n\",\n      \"#6268: 97.08%\\n\",\n      \"#6269: 97.08%\\n\",\n      \"#6270: 97.08%\\n\",\n      \"#6271: 97.08%\\n\",\n      \"#6272: 97.08%\\n\",\n      \"#6273: 97.08%\\n\",\n      \"#6274: 97.08%\\n\",\n      \"#6275: 97.08%\\n\",\n      \"#6276: 97.08%\\n\",\n      \"#6277: 97.09%\\n\",\n      \"#6278: 97.09%\\n\",\n      \"#6279: 97.09%\\n\",\n      \"#6280: 97.09%\\n\",\n      \"#6281: 97.09%\\n\",\n      \"#6282: 97.09%\\n\",\n      \"#6283: 97.09%\\n\",\n      \"#6284: 97.09%\\n\",\n      \"#6285: 97.09%\\n\",\n      \"#6286: 97.09%\\n\",\n      \"#6287: 97.09%\\n\",\n      \"#6288: 97.09%\\n\",\n      \"#6289: 97.09%\\n\",\n      \"#6290: 97.09%\\n\",\n      \"#6291: 97.09%\\n\",\n      \"#6292: 97.09%\\n\",\n      \"#6293: 97.09%\\n\",\n      \"#6294: 97.09%\\n\",\n      \"#6295: 97.09%\\n\",\n      \"#6296: 97.09%\\n\",\n      \"#6297: 97.09%\\n\",\n      \"#6298: 97.09%\\n\",\n      \"#6299: 97.10%\\n\",\n      \"#6300: 97.10%\\n\",\n      \"#6301: 97.10%\\n\",\n      \"#6302: 97.10%\\n\",\n      \"#6303: 97.10%\\n\",\n      \"#6304: 97.10%\\n\",\n      \"#6305: 97.10%\\n\",\n      \"#6306: 97.10%\\n\",\n      \"#6307: 97.10%\\n\",\n      \"#6308: 97.10%\\n\",\n      \"#6309: 97.10%\\n\",\n      \"#6310: 97.10%\\n\",\n      \"#6311: 97.10%\\n\",\n      \"#6312: 97.10%\\n\",\n      \"#6313: 97.10%\\n\",\n      \"#6314: 97.10%\\n\",\n      \"#6315: 97.10%\\n\",\n      \"#6316: 97.10%\\n\",\n      \"#6317: 97.10%\\n\",\n      \"#6318: 97.10%\\n\",\n      \"#6319: 97.10%\\n\",\n      \"#6320: 97.10%\\n\",\n      \"#6321: 97.11%\\n\",\n      \"#6322: 97.11%\\n\",\n      \"#6323: 97.11%\\n\",\n      \"#6324: 97.11%\\n\",\n      \"#6325: 97.11%\\n\",\n      \"#6326: 97.11%\\n\",\n      \"#6327: 97.11%\\n\",\n      \"#6328: 97.11%\\n\",\n      \"#6329: 97.11%\\n\",\n      \"#6330: 97.11%\\n\",\n      \"#6331: 97.11%\\n\",\n      \"#6332: 97.11%\\n\",\n      \"#6333: 97.11%\\n\",\n      \"#6334: 97.11%\\n\",\n      \"#6335: 97.11%\\n\",\n      \"#6336: 97.11%\\n\",\n      \"#6337: 97.11%\\n\",\n      \"#6338: 97.11%\\n\",\n      \"#6339: 97.11%\\n\",\n      \"#6340: 97.11%\\n\",\n      \"#6341: 97.11%\\n\",\n      \"#6342: 97.11%\\n\",\n      \"#6343: 97.12%\\n\",\n      \"#6344: 97.12%\\n\",\n      \"#6345: 97.12%\\n\",\n      \"#6346: 97.12%\\n\",\n      \"#6347: 97.12%\\n\",\n      \"#6348: 97.12%\\n\",\n      \"#6349: 97.12%\\n\",\n      \"#6350: 97.12%\\n\",\n      \"#6351: 97.12%\\n\",\n      \"#6352: 97.12%\\n\",\n      \"#6353: 97.12%\\n\",\n      \"#6354: 97.12%\\n\",\n      \"#6355: 97.12%\\n\",\n      \"#6356: 97.12%\\n\",\n      \"#6357: 97.12%\\n\",\n      \"#6358: 97.12%\\n\",\n      \"#6359: 97.12%\\n\",\n      \"#6360: 97.12%\\n\",\n      \"#6361: 97.12%\\n\",\n      \"#6362: 97.12%\\n\",\n      \"#6363: 97.12%\\n\",\n      \"#6364: 97.12%\\n\",\n      \"#6365: 97.13%\\n\",\n      \"#6366: 97.13%\\n\",\n      \"#6367: 97.13%\\n\",\n      \"#6368: 97.13%\\n\",\n      \"#6369: 97.13%\\n\",\n      \"#6370: 97.13%\\n\",\n      \"#6371: 97.13%\\n\",\n      \"#6372: 97.13%\\n\",\n      \"#6373: 97.13%\\n\",\n      \"#6374: 97.13%\\n\",\n      \"#6375: 97.13%\\n\",\n      \"#6376: 97.13%\\n\",\n      \"#6377: 97.13%\\n\",\n      \"#6378: 97.13%\\n\",\n      \"#6379: 97.13%\\n\",\n      \"#6380: 97.13%\\n\",\n      \"#6381: 97.13%\\n\",\n      \"#6382: 97.13%\\n\",\n      \"#6383: 97.13%\\n\",\n      \"#6384: 97.13%\\n\",\n      \"#6385: 97.13%\\n\",\n      \"#6386: 97.13%\\n\",\n      \"#6387: 97.14%\\n\",\n      \"#6388: 97.14%\\n\",\n      \"#6389: 97.14%\\n\",\n      \"#6390: 97.14%\\n\",\n      \"#6391: 97.14%\\n\",\n      \"#6392: 97.14%\\n\",\n      \"#6393: 97.14%\\n\",\n      \"#6394: 97.14%\\n\",\n      \"#6395: 97.14%\\n\",\n      \"#6396: 97.14%\\n\",\n      \"#6397: 97.14%\\n\",\n      \"#6398: 97.14%\\n\",\n      \"#6399: 97.14%\\n\",\n      \"#6400: 97.14%\\n\",\n      \"#6401: 97.14%\\n\",\n      \"#6402: 97.14%\\n\",\n      \"#6403: 97.14%\\n\",\n      \"#6404: 97.14%\\n\",\n      \"#6405: 97.14%\\n\",\n      \"#6406: 97.14%\\n\",\n      \"#6407: 97.14%\\n\",\n      \"#6408: 97.14%\\n\",\n      \"#6409: 97.15%\\n\",\n      \"#6410: 97.15%\\n\",\n      \"#6411: 97.15%\\n\",\n      \"#6412: 97.15%\\n\",\n      \"#6413: 97.15%\\n\",\n      \"#6414: 97.15%\\n\",\n      \"#6415: 97.15%\\n\",\n      \"#6416: 97.15%\\n\",\n      \"#6417: 97.15%\\n\",\n      \"#6418: 97.15%\\n\",\n      \"#6419: 97.15%\\n\",\n      \"#6420: 97.15%\\n\",\n      \"#6421: 97.15%\\n\",\n      \"#6422: 97.15%\\n\",\n      \"#6423: 97.15%\\n\",\n      \"#6424: 97.15%\\n\",\n      \"#6425: 97.15%\\n\",\n      \"#6426: 97.15%\\n\",\n      \"#6427: 97.15%\\n\",\n      \"#6428: 97.15%\\n\",\n      \"#6429: 97.15%\\n\",\n      \"#6430: 97.15%\\n\",\n      \"#6431: 97.15%\\n\",\n      \"#6432: 97.16%\\n\",\n      \"#6433: 97.16%\\n\",\n      \"#6434: 97.16%\\n\",\n      \"#6435: 97.16%\\n\",\n      \"#6436: 97.16%\\n\",\n      \"#6437: 97.16%\\n\",\n      \"#6438: 97.16%\\n\",\n      \"#6439: 97.16%\\n\",\n      \"#6440: 97.16%\\n\",\n      \"#6441: 97.16%\\n\",\n      \"#6442: 97.16%\\n\",\n      \"#6443: 97.16%\\n\",\n      \"#6444: 97.16%\\n\",\n      \"#6445: 97.16%\\n\",\n      \"#6446: 97.16%\\n\",\n      \"#6447: 97.16%\\n\",\n      \"#6448: 97.16%\\n\",\n      \"#6449: 97.16%\\n\",\n      \"#6450: 97.16%\\n\",\n      \"#6451: 97.16%\\n\",\n      \"#6452: 97.16%\\n\",\n      \"#6453: 97.16%\\n\",\n      \"#6454: 97.16%\\n\",\n      \"#6455: 97.17%\\n\",\n      \"#6456: 97.17%\\n\",\n      \"#6457: 97.17%\\n\",\n      \"#6458: 97.17%\\n\",\n      \"#6459: 97.17%\\n\",\n      \"#6460: 97.17%\\n\",\n      \"#6461: 97.17%\\n\",\n      \"#6462: 97.17%\\n\",\n      \"#6463: 97.17%\\n\",\n      \"#6464: 97.17%\\n\",\n      \"#6465: 97.17%\\n\",\n      \"#6466: 97.17%\\n\",\n      \"#6467: 97.17%\\n\",\n      \"#6468: 97.17%\\n\",\n      \"#6469: 97.17%\\n\",\n      \"#6470: 97.17%\\n\",\n      \"#6471: 97.17%\\n\",\n      \"#6472: 97.17%\\n\",\n      \"#6473: 97.17%\\n\",\n      \"#6474: 97.17%\\n\",\n      \"#6475: 97.17%\\n\",\n      \"#6476: 97.17%\\n\",\n      \"#6477: 97.18%\\n\",\n      \"#6478: 97.18%\\n\",\n      \"#6479: 97.18%\\n\",\n      \"#6480: 97.18%\\n\",\n      \"#6481: 97.18%\\n\",\n      \"#6482: 97.18%\\n\",\n      \"#6483: 97.18%\\n\",\n      \"#6484: 97.18%\\n\",\n      \"#6485: 97.18%\\n\",\n      \"#6486: 97.18%\\n\",\n      \"#6487: 97.18%\\n\",\n      \"#6488: 97.18%\\n\",\n      \"#6489: 97.18%\\n\",\n      \"#6490: 97.18%\\n\",\n      \"#6491: 97.18%\\n\",\n      \"#6492: 97.18%\\n\",\n      \"#6493: 97.18%\\n\",\n      \"#6494: 97.18%\\n\",\n      \"#6495: 97.18%\\n\",\n      \"#6496: 97.18%\\n\",\n      \"#6497: 97.18%\\n\",\n      \"#6498: 97.18%\\n\",\n      \"#6499: 97.18%\\n\",\n      \"#6500: 97.19%\\n\",\n      \"#6501: 97.19%\\n\",\n      \"#6502: 97.19%\\n\",\n      \"#6503: 97.19%\\n\",\n      \"#6504: 97.19%\\n\",\n      \"#6505: 97.17%\\n\",\n      \"#6506: 97.17%\\n\",\n      \"#6507: 97.17%\\n\",\n      \"#6508: 97.17%\\n\",\n      \"#6509: 97.17%\\n\",\n      \"#6510: 97.17%\\n\",\n      \"#6511: 97.17%\\n\",\n      \"#6512: 97.17%\\n\",\n      \"#6513: 97.18%\\n\",\n      \"#6514: 97.18%\\n\",\n      \"#6515: 97.18%\\n\",\n      \"#6516: 97.18%\\n\",\n      \"#6517: 97.18%\\n\",\n      \"#6518: 97.18%\\n\",\n      \"#6519: 97.18%\\n\",\n      \"#6520: 97.18%\\n\",\n      \"#6521: 97.18%\\n\",\n      \"#6522: 97.18%\\n\",\n      \"#6523: 97.18%\\n\",\n      \"#6524: 97.18%\\n\",\n      \"#6525: 97.18%\\n\",\n      \"#6526: 97.18%\\n\",\n      \"#6527: 97.18%\\n\",\n      \"#6528: 97.18%\\n\",\n      \"#6529: 97.18%\\n\",\n      \"#6530: 97.18%\\n\",\n      \"#6531: 97.18%\\n\",\n      \"#6532: 97.18%\\n\",\n      \"#6533: 97.18%\\n\",\n      \"#6534: 97.18%\\n\",\n      \"#6535: 97.18%\\n\",\n      \"#6536: 97.19%\\n\",\n      \"#6537: 97.19%\\n\",\n      \"#6538: 97.19%\\n\",\n      \"#6539: 97.19%\\n\",\n      \"#6540: 97.19%\\n\",\n      \"#6541: 97.19%\\n\",\n      \"#6542: 97.19%\\n\",\n      \"#6543: 97.19%\\n\",\n      \"#6544: 97.19%\\n\",\n      \"#6545: 97.19%\\n\",\n      \"#6546: 97.19%\\n\",\n      \"#6547: 97.19%\\n\",\n      \"#6548: 97.19%\\n\",\n      \"#6549: 97.19%\\n\",\n      \"#6550: 97.19%\\n\",\n      \"#6551: 97.19%\\n\",\n      \"#6552: 97.19%\\n\",\n      \"#6553: 97.19%\\n\",\n      \"#6554: 97.19%\\n\",\n      \"#6555: 97.18%\\n\",\n      \"#6556: 97.18%\\n\",\n      \"#6557: 97.18%\\n\",\n      \"#6558: 97.18%\\n\",\n      \"#6559: 97.18%\\n\",\n      \"#6560: 97.18%\\n\",\n      \"#6561: 97.18%\\n\",\n      \"#6562: 97.18%\\n\",\n      \"#6563: 97.18%\\n\",\n      \"#6564: 97.18%\\n\",\n      \"#6565: 97.18%\\n\",\n      \"#6566: 97.18%\\n\",\n      \"#6567: 97.18%\\n\",\n      \"#6568: 97.18%\\n\",\n      \"#6569: 97.18%\\n\",\n      \"#6570: 97.18%\\n\",\n      \"#6571: 97.19%\\n\",\n      \"#6572: 97.17%\\n\",\n      \"#6573: 97.17%\\n\",\n      \"#6574: 97.17%\\n\",\n      \"#6575: 97.17%\\n\",\n      \"#6576: 97.17%\\n\",\n      \"#6577: 97.17%\\n\",\n      \"#6578: 97.16%\\n\",\n      \"#6579: 97.16%\\n\",\n      \"#6580: 97.16%\\n\",\n      \"#6581: 97.16%\\n\",\n      \"#6582: 97.16%\\n\",\n      \"#6583: 97.16%\\n\",\n      \"#6584: 97.16%\\n\",\n      \"#6585: 97.16%\\n\",\n      \"#6586: 97.16%\\n\",\n      \"#6587: 97.16%\\n\",\n      \"#6588: 97.16%\\n\",\n      \"#6589: 97.16%\\n\",\n      \"#6590: 97.16%\\n\",\n      \"#6591: 97.16%\\n\",\n      \"#6592: 97.16%\\n\",\n      \"#6593: 97.16%\\n\",\n      \"#6594: 97.16%\\n\",\n      \"#6595: 97.16%\\n\",\n      \"#6596: 97.17%\\n\",\n      \"#6597: 97.15%\\n\",\n      \"#6598: 97.15%\\n\",\n      \"#6599: 97.14%\\n\",\n      \"#6600: 97.14%\\n\",\n      \"#6601: 97.14%\\n\",\n      \"#6602: 97.14%\\n\",\n      \"#6603: 97.14%\\n\",\n      \"#6604: 97.14%\\n\",\n      \"#6605: 97.14%\\n\",\n      \"#6606: 97.14%\\n\",\n      \"#6607: 97.14%\\n\",\n      \"#6608: 97.14%\\n\",\n      \"#6609: 97.14%\\n\",\n      \"#6610: 97.14%\\n\",\n      \"#6611: 97.14%\\n\",\n      \"#6612: 97.14%\\n\",\n      \"#6613: 97.14%\\n\",\n      \"#6614: 97.14%\\n\",\n      \"#6615: 97.14%\\n\",\n      \"#6616: 97.14%\\n\",\n      \"#6617: 97.14%\\n\",\n      \"#6618: 97.14%\\n\",\n      \"#6619: 97.15%\\n\",\n      \"#6620: 97.15%\\n\",\n      \"#6621: 97.15%\\n\",\n      \"#6622: 97.15%\\n\",\n      \"#6623: 97.15%\\n\",\n      \"#6624: 97.15%\\n\",\n      \"#6625: 97.15%\\n\",\n      \"#6626: 97.15%\\n\",\n      \"#6627: 97.15%\\n\",\n      \"#6628: 97.15%\\n\",\n      \"#6629: 97.15%\\n\",\n      \"#6630: 97.15%\\n\",\n      \"#6631: 97.15%\\n\",\n      \"#6632: 97.15%\\n\",\n      \"#6633: 97.15%\\n\",\n      \"#6634: 97.15%\\n\",\n      \"#6635: 97.15%\\n\",\n      \"#6636: 97.15%\\n\",\n      \"#6637: 97.15%\\n\",\n      \"#6638: 97.15%\\n\",\n      \"#6639: 97.15%\\n\",\n      \"#6640: 97.15%\\n\",\n      \"#6641: 97.15%\\n\",\n      \"#6642: 97.15%\\n\",\n      \"#6643: 97.16%\\n\",\n      \"#6644: 97.16%\\n\",\n      \"#6645: 97.16%\\n\",\n      \"#6646: 97.16%\\n\",\n      \"#6647: 97.16%\\n\",\n      \"#6648: 97.16%\\n\",\n      \"#6649: 97.16%\\n\",\n      \"#6650: 97.16%\\n\",\n      \"#6651: 97.16%\\n\",\n      \"#6652: 97.16%\\n\",\n      \"#6653: 97.16%\\n\",\n      \"#6654: 97.16%\\n\",\n      \"#6655: 97.16%\\n\",\n      \"#6656: 97.16%\\n\",\n      \"#6657: 97.16%\\n\",\n      \"#6658: 97.16%\\n\",\n      \"#6659: 97.16%\\n\",\n      \"#6660: 97.16%\\n\",\n      \"#6661: 97.16%\\n\",\n      \"#6662: 97.16%\\n\",\n      \"#6663: 97.16%\\n\",\n      \"#6664: 97.16%\\n\",\n      \"#6665: 97.16%\\n\",\n      \"#6666: 97.17%\\n\",\n      \"#6667: 97.17%\\n\",\n      \"#6668: 97.17%\\n\",\n      \"#6669: 97.17%\\n\",\n      \"#6670: 97.17%\\n\",\n      \"#6671: 97.17%\\n\",\n      \"#6672: 97.17%\\n\",\n      \"#6673: 97.17%\\n\",\n      \"#6674: 97.17%\\n\",\n      \"#6675: 97.17%\\n\",\n      \"#6676: 97.17%\\n\",\n      \"#6677: 97.17%\\n\",\n      \"#6678: 97.17%\\n\",\n      \"#6679: 97.17%\\n\",\n      \"#6680: 97.17%\\n\",\n      \"#6681: 97.17%\\n\",\n      \"#6682: 97.17%\\n\",\n      \"#6683: 97.17%\\n\",\n      \"#6684: 97.17%\\n\",\n      \"#6685: 97.17%\\n\",\n      \"#6686: 97.17%\\n\",\n      \"#6687: 97.17%\\n\",\n      \"#6688: 97.17%\\n\",\n      \"#6689: 97.17%\\n\",\n      \"#6690: 97.18%\\n\",\n      \"#6691: 97.18%\\n\",\n      \"#6692: 97.18%\\n\",\n      \"#6693: 97.18%\\n\",\n      \"#6694: 97.18%\\n\",\n      \"#6695: 97.18%\\n\",\n      \"#6696: 97.18%\\n\",\n      \"#6697: 97.18%\\n\",\n      \"#6698: 97.18%\\n\",\n      \"#6699: 97.18%\\n\",\n      \"#6700: 97.18%\\n\",\n      \"#6701: 97.18%\\n\",\n      \"#6702: 97.18%\\n\",\n      \"#6703: 97.18%\\n\",\n      \"#6704: 97.18%\\n\",\n      \"#6705: 97.18%\\n\",\n      \"#6706: 97.18%\\n\",\n      \"#6707: 97.18%\\n\",\n      \"#6708: 97.18%\\n\",\n      \"#6709: 97.18%\\n\",\n      \"#6710: 97.18%\\n\",\n      \"#6711: 97.18%\\n\",\n      \"#6712: 97.18%\\n\",\n      \"#6713: 97.18%\\n\",\n      \"#6714: 97.19%\\n\",\n      \"#6715: 97.19%\\n\",\n      \"#6716: 97.19%\\n\",\n      \"#6717: 97.19%\\n\",\n      \"#6718: 97.19%\\n\",\n      \"#6719: 97.19%\\n\",\n      \"#6720: 97.19%\\n\",\n      \"#6721: 97.19%\\n\",\n      \"#6722: 97.19%\\n\",\n      \"#6723: 97.19%\\n\",\n      \"#6724: 97.19%\\n\",\n      \"#6725: 97.19%\\n\",\n      \"#6726: 97.19%\\n\",\n      \"#6727: 97.19%\\n\",\n      \"#6728: 97.19%\\n\",\n      \"#6729: 97.19%\\n\",\n      \"#6730: 97.19%\\n\",\n      \"#6731: 97.19%\\n\",\n      \"#6732: 97.19%\\n\",\n      \"#6733: 97.19%\\n\",\n      \"#6734: 97.19%\\n\",\n      \"#6735: 97.19%\\n\",\n      \"#6736: 97.19%\\n\",\n      \"#6737: 97.20%\\n\",\n      \"#6738: 97.20%\\n\",\n      \"#6739: 97.20%\\n\",\n      \"#6740: 97.18%\\n\",\n      \"#6741: 97.18%\\n\",\n      \"#6742: 97.18%\\n\",\n      \"#6743: 97.18%\\n\",\n      \"#6744: 97.18%\\n\",\n      \"#6745: 97.18%\\n\",\n      \"#6746: 97.18%\\n\",\n      \"#6747: 97.18%\\n\",\n      \"#6748: 97.18%\\n\",\n      \"#6749: 97.19%\\n\",\n      \"#6750: 97.19%\\n\",\n      \"#6751: 97.19%\\n\",\n      \"#6752: 97.19%\\n\",\n      \"#6753: 97.19%\\n\",\n      \"#6754: 97.19%\\n\",\n      \"#6755: 97.17%\\n\",\n      \"#6756: 97.16%\\n\",\n      \"#6757: 97.16%\\n\",\n      \"#6758: 97.16%\\n\",\n      \"#6759: 97.16%\\n\",\n      \"#6760: 97.16%\\n\",\n      \"#6761: 97.16%\\n\",\n      \"#6762: 97.16%\\n\",\n      \"#6763: 97.16%\\n\",\n      \"#6764: 97.16%\\n\",\n      \"#6765: 97.16%\\n\",\n      \"#6766: 97.16%\\n\",\n      \"#6767: 97.16%\\n\",\n      \"#6768: 97.16%\\n\",\n      \"#6769: 97.16%\\n\",\n      \"#6770: 97.16%\\n\",\n      \"#6771: 97.16%\\n\",\n      \"#6772: 97.17%\\n\",\n      \"#6773: 97.17%\\n\",\n      \"#6774: 97.17%\\n\",\n      \"#6775: 97.17%\\n\",\n      \"#6776: 97.17%\\n\",\n      \"#6777: 97.17%\\n\",\n      \"#6778: 97.17%\\n\",\n      \"#6779: 97.17%\\n\",\n      \"#6780: 97.17%\\n\",\n      \"#6781: 97.17%\\n\",\n      \"#6782: 97.17%\\n\",\n      \"#6783: 97.16%\\n\",\n      \"#6784: 97.16%\\n\",\n      \"#6785: 97.16%\\n\",\n      \"#6786: 97.16%\\n\",\n      \"#6787: 97.16%\\n\",\n      \"#6788: 97.16%\\n\",\n      \"#6789: 97.16%\\n\",\n      \"#6790: 97.16%\\n\",\n      \"#6791: 97.16%\\n\",\n      \"#6792: 97.16%\\n\",\n      \"#6793: 97.16%\\n\",\n      \"#6794: 97.16%\\n\",\n      \"#6795: 97.16%\\n\",\n      \"#6796: 97.16%\\n\",\n      \"#6797: 97.16%\\n\",\n      \"#6798: 97.16%\\n\",\n      \"#6799: 97.16%\\n\",\n      \"#6800: 97.16%\\n\",\n      \"#6801: 97.16%\\n\",\n      \"#6802: 97.16%\\n\",\n      \"#6803: 97.16%\\n\",\n      \"#6804: 97.16%\\n\",\n      \"#6805: 97.16%\\n\",\n      \"#6806: 97.16%\\n\",\n      \"#6807: 97.17%\\n\",\n      \"#6808: 97.17%\\n\",\n      \"#6809: 97.17%\\n\",\n      \"#6810: 97.17%\\n\",\n      \"#6811: 97.17%\\n\",\n      \"#6812: 97.17%\\n\",\n      \"#6813: 97.17%\\n\",\n      \"#6814: 97.17%\\n\",\n      \"#6815: 97.17%\\n\",\n      \"#6816: 97.17%\\n\",\n      \"#6817: 97.17%\\n\",\n      \"#6818: 97.17%\\n\",\n      \"#6819: 97.17%\\n\",\n      \"#6820: 97.17%\\n\",\n      \"#6821: 97.17%\\n\",\n      \"#6822: 97.17%\\n\",\n      \"#6823: 97.17%\\n\",\n      \"#6824: 97.17%\\n\",\n      \"#6825: 97.17%\\n\",\n      \"#6826: 97.17%\\n\",\n      \"#6827: 97.17%\\n\",\n      \"#6828: 97.17%\\n\",\n      \"#6829: 97.17%\\n\",\n      \"#6830: 97.17%\\n\",\n      \"#6831: 97.18%\\n\",\n      \"#6832: 97.18%\\n\",\n      \"#6833: 97.18%\\n\",\n      \"#6834: 97.18%\\n\",\n      \"#6835: 97.18%\\n\",\n      \"#6836: 97.18%\\n\",\n      \"#6837: 97.18%\\n\",\n      \"#6838: 97.18%\\n\",\n      \"#6839: 97.18%\\n\",\n      \"#6840: 97.18%\\n\",\n      \"#6841: 97.18%\\n\",\n      \"#6842: 97.18%\\n\",\n      \"#6843: 97.18%\\n\",\n      \"#6844: 97.18%\\n\",\n      \"#6845: 97.18%\\n\",\n      \"#6846: 97.18%\\n\",\n      \"#6847: 97.18%\\n\",\n      \"#6848: 97.18%\\n\",\n      \"#6849: 97.18%\\n\",\n      \"#6850: 97.18%\\n\",\n      \"#6851: 97.18%\\n\",\n      \"#6852: 97.18%\\n\",\n      \"#6853: 97.18%\\n\",\n      \"#6854: 97.18%\\n\",\n      \"#6855: 97.18%\\n\",\n      \"#6856: 97.19%\\n\",\n      \"#6857: 97.19%\\n\",\n      \"#6858: 97.19%\\n\",\n      \"#6859: 97.19%\\n\",\n      \"#6860: 97.19%\\n\",\n      \"#6861: 97.19%\\n\",\n      \"#6862: 97.19%\\n\",\n      \"#6863: 97.19%\\n\",\n      \"#6864: 97.19%\\n\",\n      \"#6865: 97.19%\\n\",\n      \"#6866: 97.19%\\n\",\n      \"#6867: 97.19%\\n\",\n      \"#6868: 97.19%\\n\",\n      \"#6869: 97.19%\\n\",\n      \"#6870: 97.19%\\n\",\n      \"#6871: 97.19%\\n\",\n      \"#6872: 97.19%\\n\",\n      \"#6873: 97.19%\\n\",\n      \"#6874: 97.19%\\n\",\n      \"#6875: 97.19%\\n\",\n      \"#6876: 97.19%\\n\",\n      \"#6877: 97.19%\\n\",\n      \"#6878: 97.19%\\n\",\n      \"#6879: 97.19%\\n\",\n      \"#6880: 97.20%\\n\",\n      \"#6881: 97.20%\\n\",\n      \"#6882: 97.20%\\n\",\n      \"#6883: 97.20%\\n\",\n      \"#6884: 97.20%\\n\",\n      \"#6885: 97.20%\\n\",\n      \"#6886: 97.20%\\n\",\n      \"#6887: 97.20%\\n\",\n      \"#6888: 97.20%\\n\",\n      \"#6889: 97.20%\\n\",\n      \"#6890: 97.20%\\n\",\n      \"#6891: 97.20%\\n\",\n      \"#6892: 97.20%\\n\",\n      \"#6893: 97.20%\\n\",\n      \"#6894: 97.20%\\n\",\n      \"#6895: 97.20%\\n\",\n      \"#6896: 97.20%\\n\",\n      \"#6897: 97.20%\\n\",\n      \"#6898: 97.20%\\n\",\n      \"#6899: 97.20%\\n\",\n      \"#6900: 97.20%\\n\",\n      \"#6901: 97.20%\\n\",\n      \"#6902: 97.20%\\n\",\n      \"#6903: 97.20%\\n\",\n      \"#6904: 97.20%\\n\",\n      \"#6905: 97.21%\\n\",\n      \"#6906: 97.21%\\n\",\n      \"#6907: 97.21%\\n\",\n      \"#6908: 97.21%\\n\",\n      \"#6909: 97.21%\\n\",\n      \"#6910: 97.21%\\n\",\n      \"#6911: 97.21%\\n\",\n      \"#6912: 97.21%\\n\",\n      \"#6913: 97.21%\\n\",\n      \"#6914: 97.21%\\n\",\n      \"#6915: 97.21%\\n\",\n      \"#6916: 97.21%\\n\",\n      \"#6917: 97.21%\\n\",\n      \"#6918: 97.21%\\n\",\n      \"#6919: 97.21%\\n\",\n      \"#6920: 97.21%\\n\",\n      \"#6921: 97.21%\\n\",\n      \"#6922: 97.21%\\n\",\n      \"#6923: 97.21%\\n\",\n      \"#6924: 97.21%\\n\",\n      \"#6925: 97.21%\\n\",\n      \"#6926: 97.21%\\n\",\n      \"#6927: 97.21%\\n\",\n      \"#6928: 97.21%\\n\",\n      \"#6929: 97.22%\\n\",\n      \"#6930: 97.22%\\n\",\n      \"#6931: 97.22%\\n\",\n      \"#6932: 97.22%\\n\",\n      \"#6933: 97.22%\\n\",\n      \"#6934: 97.22%\\n\",\n      \"#6935: 97.22%\\n\",\n      \"#6936: 97.22%\\n\",\n      \"#6937: 97.22%\\n\",\n      \"#6938: 97.22%\\n\",\n      \"#6939: 97.22%\\n\",\n      \"#6940: 97.22%\\n\",\n      \"#6941: 97.22%\\n\",\n      \"#6942: 97.22%\\n\",\n      \"#6943: 97.22%\\n\",\n      \"#6944: 97.22%\\n\",\n      \"#6945: 97.22%\\n\",\n      \"#6946: 97.22%\\n\",\n      \"#6947: 97.22%\\n\",\n      \"#6948: 97.22%\\n\",\n      \"#6949: 97.22%\\n\",\n      \"#6950: 97.22%\\n\",\n      \"#6951: 97.22%\\n\",\n      \"#6952: 97.22%\\n\",\n      \"#6953: 97.22%\\n\",\n      \"#6954: 97.23%\\n\",\n      \"#6955: 97.23%\\n\",\n      \"#6956: 97.23%\\n\",\n      \"#6957: 97.23%\\n\",\n      \"#6958: 97.23%\\n\",\n      \"#6959: 97.23%\\n\",\n      \"#6960: 97.23%\\n\",\n      \"#6961: 97.23%\\n\",\n      \"#6962: 97.23%\\n\",\n      \"#6963: 97.23%\\n\",\n      \"#6964: 97.23%\\n\",\n      \"#6965: 97.23%\\n\",\n      \"#6966: 97.23%\\n\",\n      \"#6967: 97.23%\\n\",\n      \"#6968: 97.23%\\n\",\n      \"#6969: 97.23%\\n\",\n      \"#6970: 97.23%\\n\",\n      \"#6971: 97.23%\\n\",\n      \"#6972: 97.23%\\n\",\n      \"#6973: 97.23%\\n\",\n      \"#6974: 97.23%\\n\",\n      \"#6975: 97.23%\\n\",\n      \"#6976: 97.23%\\n\",\n      \"#6977: 97.23%\\n\",\n      \"#6978: 97.23%\\n\",\n      \"#6979: 97.23%\\n\",\n      \"#6980: 97.24%\\n\",\n      \"#6981: 97.24%\\n\",\n      \"#6982: 97.24%\\n\",\n      \"#6983: 97.24%\\n\",\n      \"#6984: 97.24%\\n\",\n      \"#6985: 97.24%\\n\",\n      \"#6986: 97.24%\\n\",\n      \"#6987: 97.24%\\n\",\n      \"#6988: 97.24%\\n\",\n      \"#6989: 97.24%\\n\",\n      \"#6990: 97.24%\\n\",\n      \"#6991: 97.24%\\n\",\n      \"#6992: 97.24%\\n\",\n      \"#6993: 97.24%\\n\",\n      \"#6994: 97.24%\\n\",\n      \"#6995: 97.24%\\n\",\n      \"#6996: 97.24%\\n\",\n      \"#6997: 97.24%\\n\",\n      \"#6998: 97.24%\\n\",\n      \"#6999: 97.24%\\n\",\n      \"#7000: 97.24%\\n\",\n      \"#7001: 97.24%\\n\",\n      \"#7002: 97.24%\\n\",\n      \"#7003: 97.24%\\n\",\n      \"#7004: 97.24%\\n\",\n      \"#7005: 97.25%\\n\",\n      \"#7006: 97.25%\\n\",\n      \"#7007: 97.25%\\n\",\n      \"#7008: 97.25%\\n\",\n      \"#7009: 97.25%\\n\",\n      \"#7010: 97.25%\\n\",\n      \"#7011: 97.25%\\n\",\n      \"#7012: 97.25%\\n\",\n      \"#7013: 97.25%\\n\",\n      \"#7014: 97.25%\\n\",\n      \"#7015: 97.25%\\n\",\n      \"#7016: 97.25%\\n\",\n      \"#7017: 97.25%\\n\",\n      \"#7018: 97.25%\\n\",\n      \"#7019: 97.25%\\n\",\n      \"#7020: 97.25%\\n\",\n      \"#7021: 97.25%\\n\",\n      \"#7022: 97.25%\\n\",\n      \"#7023: 97.25%\\n\",\n      \"#7024: 97.25%\\n\",\n      \"#7025: 97.25%\\n\",\n      \"#7026: 97.25%\\n\",\n      \"#7027: 97.25%\\n\",\n      \"#7028: 97.25%\\n\",\n      \"#7029: 97.25%\\n\",\n      \"#7030: 97.26%\\n\",\n      \"#7031: 97.26%\\n\",\n      \"#7032: 97.26%\\n\",\n      \"#7033: 97.26%\\n\",\n      \"#7034: 97.26%\\n\",\n      \"#7035: 97.26%\\n\",\n      \"#7036: 97.26%\\n\",\n      \"#7037: 97.26%\\n\",\n      \"#7038: 97.26%\\n\",\n      \"#7039: 97.26%\\n\",\n      \"#7040: 97.24%\\n\",\n      \"#7041: 97.25%\\n\",\n      \"#7042: 97.25%\\n\",\n      \"#7043: 97.25%\\n\",\n      \"#7044: 97.25%\\n\",\n      \"#7045: 97.25%\\n\",\n      \"#7046: 97.25%\\n\",\n      \"#7047: 97.25%\\n\",\n      \"#7048: 97.25%\\n\",\n      \"#7049: 97.25%\\n\",\n      \"#7050: 97.25%\\n\",\n      \"#7051: 97.25%\\n\",\n      \"#7052: 97.25%\\n\",\n      \"#7053: 97.25%\\n\",\n      \"#7054: 97.25%\\n\",\n      \"#7055: 97.25%\\n\",\n      \"#7056: 97.25%\\n\",\n      \"#7057: 97.25%\\n\",\n      \"#7058: 97.25%\\n\",\n      \"#7059: 97.25%\\n\",\n      \"#7060: 97.25%\\n\",\n      \"#7061: 97.25%\\n\",\n      \"#7062: 97.25%\\n\",\n      \"#7063: 97.25%\\n\",\n      \"#7064: 97.25%\\n\",\n      \"#7065: 97.25%\\n\",\n      \"#7066: 97.25%\\n\",\n      \"#7067: 97.26%\\n\",\n      \"#7068: 97.26%\\n\",\n      \"#7069: 97.26%\\n\",\n      \"#7070: 97.26%\\n\",\n      \"#7071: 97.26%\\n\",\n      \"#7072: 97.26%\\n\",\n      \"#7073: 97.26%\\n\",\n      \"#7074: 97.26%\\n\",\n      \"#7075: 97.26%\\n\",\n      \"#7076: 97.26%\\n\",\n      \"#7077: 97.26%\\n\",\n      \"#7078: 97.26%\\n\",\n      \"#7079: 97.26%\\n\",\n      \"#7080: 97.26%\\n\",\n      \"#7081: 97.26%\\n\",\n      \"#7082: 97.26%\\n\",\n      \"#7083: 97.26%\\n\",\n      \"#7084: 97.26%\\n\",\n      \"#7085: 97.26%\\n\",\n      \"#7086: 97.26%\\n\",\n      \"#7087: 97.26%\\n\",\n      \"#7088: 97.26%\\n\",\n      \"#7089: 97.26%\\n\",\n      \"#7090: 97.26%\\n\",\n      \"#7091: 97.26%\\n\",\n      \"#7092: 97.26%\\n\",\n      \"#7093: 97.27%\\n\",\n      \"#7094: 97.27%\\n\",\n      \"#7095: 97.27%\\n\",\n      \"#7096: 97.27%\\n\",\n      \"#7097: 97.27%\\n\",\n      \"#7098: 97.27%\\n\",\n      \"#7099: 97.27%\\n\",\n      \"#7100: 97.27%\\n\",\n      \"#7101: 97.27%\\n\",\n      \"#7102: 97.27%\\n\",\n      \"#7103: 97.27%\\n\",\n      \"#7104: 97.27%\\n\",\n      \"#7105: 97.27%\\n\",\n      \"#7106: 97.27%\\n\",\n      \"#7107: 97.27%\\n\",\n      \"#7108: 97.27%\\n\",\n      \"#7109: 97.27%\\n\",\n      \"#7110: 97.27%\\n\",\n      \"#7111: 97.27%\\n\",\n      \"#7112: 97.27%\\n\",\n      \"#7113: 97.27%\\n\",\n      \"#7114: 97.27%\\n\",\n      \"#7115: 97.27%\\n\",\n      \"#7116: 97.27%\\n\",\n      \"#7117: 97.27%\\n\",\n      \"#7118: 97.27%\\n\",\n      \"#7119: 97.28%\\n\",\n      \"#7120: 97.28%\\n\",\n      \"#7121: 97.26%\\n\",\n      \"#7122: 97.26%\\n\",\n      \"#7123: 97.26%\\n\",\n      \"#7124: 97.26%\\n\",\n      \"#7125: 97.26%\\n\",\n      \"#7126: 97.26%\\n\",\n      \"#7127: 97.26%\\n\",\n      \"#7128: 97.26%\\n\",\n      \"#7129: 97.27%\\n\",\n      \"#7130: 97.27%\\n\",\n      \"#7131: 97.27%\\n\",\n      \"#7132: 97.27%\\n\",\n      \"#7133: 97.27%\\n\",\n      \"#7134: 97.27%\\n\",\n      \"#7135: 97.27%\\n\",\n      \"#7136: 97.27%\\n\",\n      \"#7137: 97.27%\\n\",\n      \"#7138: 97.27%\\n\",\n      \"#7139: 97.27%\\n\",\n      \"#7140: 97.27%\\n\",\n      \"#7141: 97.27%\\n\",\n      \"#7142: 97.27%\\n\",\n      \"#7143: 97.27%\\n\",\n      \"#7144: 97.27%\\n\",\n      \"#7145: 97.27%\\n\",\n      \"#7146: 97.27%\\n\",\n      \"#7147: 97.27%\\n\",\n      \"#7148: 97.27%\\n\",\n      \"#7149: 97.27%\\n\",\n      \"#7150: 97.27%\\n\",\n      \"#7151: 97.27%\\n\",\n      \"#7152: 97.27%\\n\",\n      \"#7153: 97.27%\\n\",\n      \"#7154: 97.27%\\n\",\n      \"#7155: 97.28%\\n\",\n      \"#7156: 97.28%\\n\",\n      \"#7157: 97.28%\\n\",\n      \"#7158: 97.28%\\n\",\n      \"#7159: 97.28%\\n\",\n      \"#7160: 97.28%\\n\",\n      \"#7161: 97.28%\\n\",\n      \"#7162: 97.28%\\n\",\n      \"#7163: 97.28%\\n\",\n      \"#7164: 97.28%\\n\",\n      \"#7165: 97.28%\\n\",\n      \"#7166: 97.28%\\n\",\n      \"#7167: 97.28%\\n\",\n      \"#7168: 97.28%\\n\",\n      \"#7169: 97.28%\\n\",\n      \"#7170: 97.28%\\n\",\n      \"#7171: 97.28%\\n\",\n      \"#7172: 97.28%\\n\",\n      \"#7173: 97.28%\\n\",\n      \"#7174: 97.28%\\n\",\n      \"#7175: 97.28%\\n\",\n      \"#7176: 97.28%\\n\",\n      \"#7177: 97.28%\\n\",\n      \"#7178: 97.28%\\n\",\n      \"#7179: 97.28%\\n\",\n      \"#7180: 97.28%\\n\",\n      \"#7181: 97.28%\\n\",\n      \"#7182: 97.29%\\n\",\n      \"#7183: 97.29%\\n\",\n      \"#7184: 97.29%\\n\",\n      \"#7185: 97.29%\\n\",\n      \"#7186: 97.29%\\n\",\n      \"#7187: 97.29%\\n\",\n      \"#7188: 97.29%\\n\",\n      \"#7189: 97.29%\\n\",\n      \"#7190: 97.29%\\n\",\n      \"#7191: 97.29%\\n\",\n      \"#7192: 97.29%\\n\",\n      \"#7193: 97.29%\\n\",\n      \"#7194: 97.29%\\n\",\n      \"#7195: 97.29%\\n\",\n      \"#7196: 97.29%\\n\",\n      \"#7197: 97.29%\\n\",\n      \"#7198: 97.29%\\n\",\n      \"#7199: 97.29%\\n\",\n      \"#7200: 97.29%\\n\",\n      \"#7201: 97.29%\\n\",\n      \"#7202: 97.29%\\n\",\n      \"#7203: 97.29%\\n\",\n      \"#7204: 97.29%\\n\",\n      \"#7205: 97.29%\\n\",\n      \"#7206: 97.29%\\n\",\n      \"#7207: 97.29%\\n\",\n      \"#7208: 97.30%\\n\",\n      \"#7209: 97.30%\\n\",\n      \"#7210: 97.30%\\n\",\n      \"#7211: 97.30%\\n\",\n      \"#7212: 97.30%\\n\",\n      \"#7213: 97.30%\\n\",\n      \"#7214: 97.30%\\n\",\n      \"#7215: 97.30%\\n\",\n      \"#7216: 97.30%\\n\",\n      \"#7217: 97.30%\\n\",\n      \"#7218: 97.30%\\n\",\n      \"#7219: 97.30%\\n\",\n      \"#7220: 97.30%\\n\",\n      \"#7221: 97.30%\\n\",\n      \"#7222: 97.30%\\n\",\n      \"#7223: 97.30%\\n\",\n      \"#7224: 97.30%\\n\",\n      \"#7225: 97.30%\\n\",\n      \"#7226: 97.30%\\n\",\n      \"#7227: 97.30%\\n\",\n      \"#7228: 97.30%\\n\",\n      \"#7229: 97.30%\\n\",\n      \"#7230: 97.30%\\n\",\n      \"#7231: 97.30%\\n\",\n      \"#7232: 97.30%\\n\",\n      \"#7233: 97.30%\\n\",\n      \"#7234: 97.30%\\n\",\n      \"#7235: 97.31%\\n\",\n      \"#7236: 97.31%\\n\",\n      \"#7237: 97.31%\\n\",\n      \"#7238: 97.31%\\n\",\n      \"#7239: 97.31%\\n\",\n      \"#7240: 97.31%\\n\",\n      \"#7241: 97.31%\\n\",\n      \"#7242: 97.31%\\n\",\n      \"#7243: 97.31%\\n\",\n      \"#7244: 97.31%\\n\",\n      \"#7245: 97.31%\\n\",\n      \"#7246: 97.31%\\n\",\n      \"#7247: 97.31%\\n\",\n      \"#7248: 97.31%\\n\",\n      \"#7249: 97.31%\\n\",\n      \"#7250: 97.31%\\n\",\n      \"#7251: 97.31%\\n\",\n      \"#7252: 97.31%\\n\",\n      \"#7253: 97.31%\\n\",\n      \"#7254: 97.31%\\n\",\n      \"#7255: 97.31%\\n\",\n      \"#7256: 97.31%\\n\",\n      \"#7257: 97.31%\\n\",\n      \"#7258: 97.31%\\n\",\n      \"#7259: 97.31%\\n\",\n      \"#7260: 97.31%\\n\",\n      \"#7261: 97.31%\\n\",\n      \"#7262: 97.32%\\n\",\n      \"#7263: 97.32%\\n\",\n      \"#7264: 97.32%\\n\",\n      \"#7265: 97.32%\\n\",\n      \"#7266: 97.32%\\n\",\n      \"#7267: 97.32%\\n\",\n      \"#7268: 97.32%\\n\",\n      \"#7269: 97.32%\\n\",\n      \"#7270: 97.32%\\n\",\n      \"#7271: 97.32%\\n\",\n      \"#7272: 97.32%\\n\",\n      \"#7273: 97.32%\\n\",\n      \"#7274: 97.32%\\n\",\n      \"#7275: 97.32%\\n\",\n      \"#7276: 97.32%\\n\",\n      \"#7277: 97.32%\\n\",\n      \"#7278: 97.32%\\n\",\n      \"#7279: 97.32%\\n\",\n      \"#7280: 97.32%\\n\",\n      \"#7281: 97.32%\\n\",\n      \"#7282: 97.32%\\n\",\n      \"#7283: 97.32%\\n\",\n      \"#7284: 97.32%\\n\",\n      \"#7285: 97.32%\\n\",\n      \"#7286: 97.32%\\n\",\n      \"#7287: 97.32%\\n\",\n      \"#7288: 97.32%\\n\",\n      \"#7289: 97.33%\\n\",\n      \"#7290: 97.33%\\n\",\n      \"#7291: 97.33%\\n\",\n      \"#7292: 97.33%\\n\",\n      \"#7293: 97.33%\\n\",\n      \"#7294: 97.33%\\n\",\n      \"#7295: 97.33%\\n\",\n      \"#7296: 97.33%\\n\",\n      \"#7297: 97.33%\\n\",\n      \"#7298: 97.33%\\n\",\n      \"#7299: 97.33%\\n\",\n      \"#7300: 97.33%\\n\",\n      \"#7301: 97.33%\\n\",\n      \"#7302: 97.33%\\n\",\n      \"#7303: 97.33%\\n\",\n      \"#7304: 97.33%\\n\",\n      \"#7305: 97.33%\\n\",\n      \"#7306: 97.33%\\n\",\n      \"#7307: 97.33%\\n\",\n      \"#7308: 97.33%\\n\",\n      \"#7309: 97.33%\\n\",\n      \"#7310: 97.33%\\n\",\n      \"#7311: 97.33%\\n\",\n      \"#7312: 97.33%\\n\",\n      \"#7313: 97.33%\\n\",\n      \"#7314: 97.33%\\n\",\n      \"#7315: 97.33%\\n\",\n      \"#7316: 97.33%\\n\",\n      \"#7317: 97.34%\\n\",\n      \"#7318: 97.34%\\n\",\n      \"#7319: 97.34%\\n\",\n      \"#7320: 97.34%\\n\",\n      \"#7321: 97.34%\\n\",\n      \"#7322: 97.34%\\n\",\n      \"#7323: 97.34%\\n\",\n      \"#7324: 97.34%\\n\",\n      \"#7325: 97.34%\\n\",\n      \"#7326: 97.34%\\n\",\n      \"#7327: 97.34%\\n\",\n      \"#7328: 97.34%\\n\",\n      \"#7329: 97.34%\\n\",\n      \"#7330: 97.34%\\n\",\n      \"#7331: 97.34%\\n\",\n      \"#7332: 97.34%\\n\",\n      \"#7333: 97.34%\\n\",\n      \"#7334: 97.34%\\n\",\n      \"#7335: 97.34%\\n\",\n      \"#7336: 97.34%\\n\",\n      \"#7337: 97.34%\\n\",\n      \"#7338: 97.34%\\n\",\n      \"#7339: 97.34%\\n\",\n      \"#7340: 97.34%\\n\",\n      \"#7341: 97.34%\\n\",\n      \"#7342: 97.34%\\n\",\n      \"#7343: 97.34%\\n\",\n      \"#7344: 97.35%\\n\",\n      \"#7345: 97.35%\\n\",\n      \"#7346: 97.35%\\n\",\n      \"#7347: 97.35%\\n\",\n      \"#7348: 97.35%\\n\",\n      \"#7349: 97.35%\\n\",\n      \"#7350: 97.35%\\n\",\n      \"#7351: 97.35%\\n\",\n      \"#7352: 97.35%\\n\",\n      \"#7353: 97.35%\\n\",\n      \"#7354: 97.35%\\n\",\n      \"#7355: 97.35%\\n\",\n      \"#7356: 97.35%\\n\",\n      \"#7357: 97.35%\\n\",\n      \"#7358: 97.35%\\n\",\n      \"#7359: 97.35%\\n\",\n      \"#7360: 97.35%\\n\",\n      \"#7361: 97.35%\\n\",\n      \"#7362: 97.35%\\n\",\n      \"#7363: 97.35%\\n\",\n      \"#7364: 97.35%\\n\",\n      \"#7365: 97.35%\\n\",\n      \"#7366: 97.35%\\n\",\n      \"#7367: 97.35%\\n\",\n      \"#7368: 97.35%\\n\",\n      \"#7369: 97.35%\\n\",\n      \"#7370: 97.35%\\n\",\n      \"#7371: 97.35%\\n\",\n      \"#7372: 97.36%\\n\",\n      \"#7373: 97.36%\\n\",\n      \"#7374: 97.36%\\n\",\n      \"#7375: 97.36%\\n\",\n      \"#7376: 97.36%\\n\",\n      \"#7377: 97.36%\\n\",\n      \"#7378: 97.36%\\n\",\n      \"#7379: 97.36%\\n\",\n      \"#7380: 97.36%\\n\",\n      \"#7381: 97.36%\\n\",\n      \"#7382: 97.36%\\n\",\n      \"#7383: 97.36%\\n\",\n      \"#7384: 97.36%\\n\",\n      \"#7385: 97.36%\\n\",\n      \"#7386: 97.36%\\n\",\n      \"#7387: 97.36%\\n\",\n      \"#7388: 97.36%\\n\",\n      \"#7389: 97.36%\\n\",\n      \"#7390: 97.36%\\n\",\n      \"#7391: 97.36%\\n\",\n      \"#7392: 97.36%\\n\",\n      \"#7393: 97.36%\\n\",\n      \"#7394: 97.36%\\n\",\n      \"#7395: 97.36%\\n\",\n      \"#7396: 97.36%\\n\",\n      \"#7397: 97.36%\\n\",\n      \"#7398: 97.36%\\n\",\n      \"#7399: 97.36%\\n\",\n      \"#7400: 97.37%\\n\",\n      \"#7401: 97.37%\\n\",\n      \"#7402: 97.37%\\n\",\n      \"#7403: 97.37%\\n\",\n      \"#7404: 97.37%\\n\",\n      \"#7405: 97.37%\\n\",\n      \"#7406: 97.37%\\n\",\n      \"#7407: 97.37%\\n\",\n      \"#7408: 97.37%\\n\",\n      \"#7409: 97.37%\\n\",\n      \"#7410: 97.37%\\n\",\n      \"#7411: 97.37%\\n\",\n      \"#7412: 97.37%\\n\",\n      \"#7413: 97.37%\\n\",\n      \"#7414: 97.37%\\n\",\n      \"#7415: 97.37%\\n\",\n      \"#7416: 97.37%\\n\",\n      \"#7417: 97.37%\\n\",\n      \"#7418: 97.37%\\n\",\n      \"#7419: 97.37%\\n\",\n      \"#7420: 97.37%\\n\",\n      \"#7421: 97.37%\\n\",\n      \"#7422: 97.37%\\n\",\n      \"#7423: 97.37%\\n\",\n      \"#7424: 97.37%\\n\",\n      \"#7425: 97.37%\\n\",\n      \"#7426: 97.37%\\n\",\n      \"#7427: 97.37%\\n\",\n      \"#7428: 97.38%\\n\",\n      \"#7429: 97.38%\\n\",\n      \"#7430: 97.38%\\n\",\n      \"#7431: 97.38%\\n\",\n      \"#7432: 97.38%\\n\",\n      \"#7433: 97.38%\\n\",\n      \"#7434: 97.38%\\n\",\n      \"#7435: 97.38%\\n\",\n      \"#7436: 97.38%\\n\",\n      \"#7437: 97.38%\\n\",\n      \"#7438: 97.38%\\n\",\n      \"#7439: 97.38%\\n\",\n      \"#7440: 97.38%\\n\",\n      \"#7441: 97.38%\\n\",\n      \"#7442: 97.38%\\n\",\n      \"#7443: 97.38%\\n\",\n      \"#7444: 97.38%\\n\",\n      \"#7445: 97.38%\\n\",\n      \"#7446: 97.38%\\n\",\n      \"#7447: 97.38%\\n\",\n      \"#7448: 97.38%\\n\",\n      \"#7449: 97.38%\\n\",\n      \"#7450: 97.38%\\n\",\n      \"#7451: 97.37%\\n\",\n      \"#7452: 97.37%\\n\",\n      \"#7453: 97.37%\\n\",\n      \"#7454: 97.37%\\n\",\n      \"#7455: 97.37%\\n\",\n      \"#7456: 97.37%\\n\",\n      \"#7457: 97.37%\\n\",\n      \"#7458: 97.37%\\n\",\n      \"#7459: 97.37%\\n\",\n      \"#7460: 97.37%\\n\",\n      \"#7461: 97.37%\\n\",\n      \"#7462: 97.37%\\n\",\n      \"#7463: 97.37%\\n\",\n      \"#7464: 97.37%\\n\",\n      \"#7465: 97.37%\\n\",\n      \"#7466: 97.38%\\n\",\n      \"#7467: 97.38%\\n\",\n      \"#7468: 97.38%\\n\",\n      \"#7469: 97.38%\\n\",\n      \"#7470: 97.38%\\n\",\n      \"#7471: 97.38%\\n\",\n      \"#7472: 97.38%\\n\",\n      \"#7473: 97.38%\\n\",\n      \"#7474: 97.38%\\n\",\n      \"#7475: 97.38%\\n\",\n      \"#7476: 97.38%\\n\",\n      \"#7477: 97.38%\\n\",\n      \"#7478: 97.38%\\n\",\n      \"#7479: 97.38%\\n\",\n      \"#7480: 97.38%\\n\",\n      \"#7481: 97.38%\\n\",\n      \"#7482: 97.38%\\n\",\n      \"#7483: 97.38%\\n\",\n      \"#7484: 97.38%\\n\",\n      \"#7485: 97.38%\\n\",\n      \"#7486: 97.38%\\n\",\n      \"#7487: 97.38%\\n\",\n      \"#7488: 97.38%\\n\",\n      \"#7489: 97.38%\\n\",\n      \"#7490: 97.38%\\n\",\n      \"#7491: 97.38%\\n\",\n      \"#7492: 97.38%\\n\",\n      \"#7493: 97.38%\\n\",\n      \"#7494: 97.38%\\n\",\n      \"#7495: 97.39%\\n\",\n      \"#7496: 97.39%\\n\",\n      \"#7497: 97.39%\\n\",\n      \"#7498: 97.39%\\n\",\n      \"#7499: 97.39%\\n\",\n      \"#7500: 97.39%\\n\",\n      \"#7501: 97.39%\\n\",\n      \"#7502: 97.39%\\n\",\n      \"#7503: 97.39%\\n\",\n      \"#7504: 97.39%\\n\",\n      \"#7505: 97.39%\\n\",\n      \"#7506: 97.39%\\n\",\n      \"#7507: 97.39%\\n\",\n      \"#7508: 97.39%\\n\",\n      \"#7509: 97.39%\\n\",\n      \"#7510: 97.39%\\n\",\n      \"#7511: 97.39%\\n\",\n      \"#7512: 97.39%\\n\",\n      \"#7513: 97.39%\\n\",\n      \"#7514: 97.38%\\n\",\n      \"#7515: 97.38%\\n\",\n      \"#7516: 97.38%\\n\",\n      \"#7517: 97.38%\\n\",\n      \"#7518: 97.38%\\n\",\n      \"#7519: 97.38%\\n\",\n      \"#7520: 97.38%\\n\",\n      \"#7521: 97.38%\\n\",\n      \"#7522: 97.38%\\n\",\n      \"#7523: 97.38%\\n\",\n      \"#7524: 97.38%\\n\",\n      \"#7525: 97.38%\\n\",\n      \"#7526: 97.38%\\n\",\n      \"#7527: 97.38%\\n\",\n      \"#7528: 97.38%\\n\",\n      \"#7529: 97.38%\\n\",\n      \"#7530: 97.38%\\n\",\n      \"#7531: 97.38%\\n\",\n      \"#7532: 97.38%\\n\",\n      \"#7533: 97.39%\\n\",\n      \"#7534: 97.39%\\n\",\n      \"#7535: 97.39%\\n\",\n      \"#7536: 97.39%\\n\",\n      \"#7537: 97.39%\\n\",\n      \"#7538: 97.39%\\n\",\n      \"#7539: 97.39%\\n\",\n      \"#7540: 97.39%\\n\",\n      \"#7541: 97.39%\\n\",\n      \"#7542: 97.39%\\n\",\n      \"#7543: 97.39%\\n\",\n      \"#7544: 97.39%\\n\",\n      \"#7545: 97.39%\\n\",\n      \"#7546: 97.39%\\n\",\n      \"#7547: 97.39%\\n\",\n      \"#7548: 97.39%\\n\",\n      \"#7549: 97.39%\\n\",\n      \"#7550: 97.39%\\n\",\n      \"#7551: 97.39%\\n\",\n      \"#7552: 97.39%\\n\",\n      \"#7553: 97.39%\\n\",\n      \"#7554: 97.39%\\n\",\n      \"#7555: 97.39%\\n\",\n      \"#7556: 97.39%\\n\",\n      \"#7557: 97.39%\\n\",\n      \"#7558: 97.39%\\n\",\n      \"#7559: 97.39%\\n\",\n      \"#7560: 97.39%\\n\",\n      \"#7561: 97.39%\\n\",\n      \"#7562: 97.40%\\n\",\n      \"#7563: 97.40%\\n\",\n      \"#7564: 97.40%\\n\",\n      \"#7565: 97.40%\\n\",\n      \"#7566: 97.40%\\n\",\n      \"#7567: 97.40%\\n\",\n      \"#7568: 97.40%\\n\",\n      \"#7569: 97.40%\\n\",\n      \"#7570: 97.40%\\n\",\n      \"#7571: 97.40%\\n\",\n      \"#7572: 97.40%\\n\",\n      \"#7573: 97.40%\\n\",\n      \"#7574: 97.40%\\n\",\n      \"#7575: 97.40%\\n\",\n      \"#7576: 97.40%\\n\",\n      \"#7577: 97.40%\\n\",\n      \"#7578: 97.40%\\n\",\n      \"#7579: 97.40%\\n\",\n      \"#7580: 97.40%\\n\",\n      \"#7581: 97.40%\\n\",\n      \"#7582: 97.40%\\n\",\n      \"#7583: 97.40%\\n\",\n      \"#7584: 97.40%\\n\",\n      \"#7585: 97.40%\\n\",\n      \"#7586: 97.40%\\n\",\n      \"#7587: 97.40%\\n\",\n      \"#7588: 97.40%\\n\",\n      \"#7589: 97.40%\\n\",\n      \"#7590: 97.40%\\n\",\n      \"#7591: 97.41%\\n\",\n      \"#7592: 97.41%\\n\",\n      \"#7593: 97.41%\\n\",\n      \"#7594: 97.41%\\n\",\n      \"#7595: 97.41%\\n\",\n      \"#7596: 97.41%\\n\",\n      \"#7597: 97.41%\\n\",\n      \"#7598: 97.41%\\n\",\n      \"#7599: 97.41%\\n\",\n      \"#7600: 97.41%\\n\",\n      \"#7601: 97.41%\\n\",\n      \"#7602: 97.41%\\n\",\n      \"#7603: 97.41%\\n\",\n      \"#7604: 97.41%\\n\",\n      \"#7605: 97.41%\\n\",\n      \"#7606: 97.41%\\n\",\n      \"#7607: 97.41%\\n\",\n      \"#7608: 97.41%\\n\",\n      \"#7609: 97.41%\\n\",\n      \"#7610: 97.41%\\n\",\n      \"#7611: 97.41%\\n\",\n      \"#7612: 97.41%\\n\",\n      \"#7613: 97.41%\\n\",\n      \"#7614: 97.41%\\n\",\n      \"#7615: 97.41%\\n\",\n      \"#7616: 97.41%\\n\",\n      \"#7617: 97.41%\\n\",\n      \"#7618: 97.41%\\n\",\n      \"#7619: 97.41%\\n\",\n      \"#7620: 97.42%\\n\",\n      \"#7621: 97.42%\\n\",\n      \"#7622: 97.42%\\n\",\n      \"#7623: 97.42%\\n\",\n      \"#7624: 97.42%\\n\",\n      \"#7625: 97.42%\\n\",\n      \"#7626: 97.42%\\n\",\n      \"#7627: 97.42%\\n\",\n      \"#7628: 97.42%\\n\",\n      \"#7629: 97.42%\\n\",\n      \"#7630: 97.42%\\n\",\n      \"#7631: 97.42%\\n\",\n      \"#7632: 97.42%\\n\",\n      \"#7633: 97.42%\\n\",\n      \"#7634: 97.42%\\n\",\n      \"#7635: 97.42%\\n\",\n      \"#7636: 97.42%\\n\",\n      \"#7637: 97.42%\\n\",\n      \"#7638: 97.42%\\n\",\n      \"#7639: 97.42%\\n\",\n      \"#7640: 97.42%\\n\",\n      \"#7641: 97.42%\\n\",\n      \"#7642: 97.42%\\n\",\n      \"#7643: 97.42%\\n\",\n      \"#7644: 97.42%\\n\",\n      \"#7645: 97.42%\\n\",\n      \"#7646: 97.42%\\n\",\n      \"#7647: 97.42%\\n\",\n      \"#7648: 97.42%\\n\",\n      \"#7649: 97.42%\\n\",\n      \"#7650: 97.43%\\n\",\n      \"#7651: 97.43%\\n\",\n      \"#7652: 97.43%\\n\",\n      \"#7653: 97.43%\\n\",\n      \"#7654: 97.43%\\n\",\n      \"#7655: 97.43%\\n\",\n      \"#7656: 97.43%\\n\",\n      \"#7657: 97.43%\\n\",\n      \"#7658: 97.43%\\n\",\n      \"#7659: 97.43%\\n\",\n      \"#7660: 97.43%\\n\",\n      \"#7661: 97.43%\\n\",\n      \"#7662: 97.43%\\n\",\n      \"#7663: 97.43%\\n\",\n      \"#7664: 97.43%\\n\",\n      \"#7665: 97.43%\\n\",\n      \"#7666: 97.43%\\n\",\n      \"#7667: 97.43%\\n\",\n      \"#7668: 97.43%\\n\",\n      \"#7669: 97.43%\\n\",\n      \"#7670: 97.43%\\n\",\n      \"#7671: 97.43%\\n\",\n      \"#7672: 97.43%\\n\",\n      \"#7673: 97.43%\\n\",\n      \"#7674: 97.43%\\n\",\n      \"#7675: 97.43%\\n\",\n      \"#7676: 97.43%\\n\",\n      \"#7677: 97.43%\\n\",\n      \"#7678: 97.43%\\n\",\n      \"#7679: 97.43%\\n\",\n      \"#7680: 97.44%\\n\",\n      \"#7681: 97.44%\\n\",\n      \"#7682: 97.44%\\n\",\n      \"#7683: 97.44%\\n\",\n      \"#7684: 97.44%\\n\",\n      \"#7685: 97.44%\\n\",\n      \"#7686: 97.44%\\n\",\n      \"#7687: 97.44%\\n\",\n      \"#7688: 97.44%\\n\",\n      \"#7689: 97.44%\\n\",\n      \"#7690: 97.44%\\n\",\n      \"#7691: 97.44%\\n\",\n      \"#7692: 97.44%\\n\",\n      \"#7693: 97.44%\\n\",\n      \"#7694: 97.44%\\n\",\n      \"#7695: 97.44%\\n\",\n      \"#7696: 97.44%\\n\",\n      \"#7697: 97.44%\\n\",\n      \"#7698: 97.44%\\n\",\n      \"#7699: 97.44%\\n\",\n      \"#7700: 97.44%\\n\",\n      \"#7701: 97.44%\\n\",\n      \"#7702: 97.44%\\n\",\n      \"#7703: 97.44%\\n\",\n      \"#7704: 97.44%\\n\",\n      \"#7705: 97.44%\\n\",\n      \"#7706: 97.44%\\n\",\n      \"#7707: 97.44%\\n\",\n      \"#7708: 97.44%\\n\",\n      \"#7709: 97.44%\\n\",\n      \"#7710: 97.45%\\n\",\n      \"#7711: 97.45%\\n\",\n      \"#7712: 97.45%\\n\",\n      \"#7713: 97.45%\\n\",\n      \"#7714: 97.45%\\n\",\n      \"#7715: 97.45%\\n\",\n      \"#7716: 97.45%\\n\",\n      \"#7717: 97.45%\\n\",\n      \"#7718: 97.45%\\n\",\n      \"#7719: 97.45%\\n\",\n      \"#7720: 97.45%\\n\",\n      \"#7721: 97.45%\\n\",\n      \"#7722: 97.45%\\n\",\n      \"#7723: 97.45%\\n\",\n      \"#7724: 97.45%\\n\",\n      \"#7725: 97.45%\\n\",\n      \"#7726: 97.45%\\n\",\n      \"#7727: 97.45%\\n\",\n      \"#7728: 97.45%\\n\",\n      \"#7729: 97.45%\\n\",\n      \"#7730: 97.45%\\n\",\n      \"#7731: 97.45%\\n\",\n      \"#7732: 97.45%\\n\",\n      \"#7733: 97.45%\\n\",\n      \"#7734: 97.45%\\n\",\n      \"#7735: 97.45%\\n\",\n      \"#7736: 97.45%\\n\",\n      \"#7737: 97.45%\\n\",\n      \"#7738: 97.45%\\n\",\n      \"#7739: 97.45%\\n\",\n      \"#7740: 97.46%\\n\",\n      \"#7741: 97.46%\\n\",\n      \"#7742: 97.46%\\n\",\n      \"#7743: 97.46%\\n\",\n      \"#7744: 97.46%\\n\",\n      \"#7745: 97.46%\\n\",\n      \"#7746: 97.46%\\n\",\n      \"#7747: 97.46%\\n\",\n      \"#7748: 97.46%\\n\",\n      \"#7749: 97.46%\\n\",\n      \"#7750: 97.46%\\n\",\n      \"#7751: 97.46%\\n\",\n      \"#7752: 97.46%\\n\",\n      \"#7753: 97.46%\\n\",\n      \"#7754: 97.46%\\n\",\n      \"#7755: 97.46%\\n\",\n      \"#7756: 97.46%\\n\",\n      \"#7757: 97.46%\\n\",\n      \"#7758: 97.46%\\n\",\n      \"#7759: 97.46%\\n\",\n      \"#7760: 97.46%\\n\",\n      \"#7761: 97.46%\\n\",\n      \"#7762: 97.46%\\n\",\n      \"#7763: 97.46%\\n\",\n      \"#7764: 97.46%\\n\",\n      \"#7765: 97.46%\\n\",\n      \"#7766: 97.46%\\n\",\n      \"#7767: 97.46%\\n\",\n      \"#7768: 97.46%\\n\",\n      \"#7769: 97.46%\\n\",\n      \"#7770: 97.46%\\n\",\n      \"#7771: 97.47%\\n\",\n      \"#7772: 97.47%\\n\",\n      \"#7773: 97.47%\\n\",\n      \"#7774: 97.47%\\n\",\n      \"#7775: 97.47%\\n\",\n      \"#7776: 97.47%\\n\",\n      \"#7777: 97.47%\\n\",\n      \"#7778: 97.47%\\n\",\n      \"#7779: 97.47%\\n\",\n      \"#7780: 97.47%\\n\",\n      \"#7781: 97.47%\\n\",\n      \"#7782: 97.47%\\n\",\n      \"#7783: 97.47%\\n\",\n      \"#7784: 97.47%\\n\",\n      \"#7785: 97.47%\\n\",\n      \"#7786: 97.47%\\n\",\n      \"#7787: 97.47%\\n\",\n      \"#7788: 97.47%\\n\",\n      \"#7789: 97.47%\\n\",\n      \"#7790: 97.47%\\n\",\n      \"#7791: 97.47%\\n\",\n      \"#7792: 97.47%\\n\",\n      \"#7793: 97.47%\\n\",\n      \"#7794: 97.47%\\n\",\n      \"#7795: 97.47%\\n\",\n      \"#7796: 97.47%\\n\",\n      \"#7797: 97.47%\\n\",\n      \"#7798: 97.47%\\n\",\n      \"#7799: 97.47%\\n\",\n      \"#7800: 97.47%\\n\",\n      \"#7801: 97.48%\\n\",\n      \"#7802: 97.48%\\n\",\n      \"#7803: 97.48%\\n\",\n      \"#7804: 97.48%\\n\",\n      \"#7805: 97.48%\\n\",\n      \"#7806: 97.48%\\n\",\n      \"#7807: 97.48%\\n\",\n      \"#7808: 97.48%\\n\",\n      \"#7809: 97.48%\\n\",\n      \"#7810: 97.48%\\n\",\n      \"#7811: 97.48%\\n\",\n      \"#7812: 97.48%\\n\",\n      \"#7813: 97.48%\\n\",\n      \"#7814: 97.48%\\n\",\n      \"#7815: 97.48%\\n\",\n      \"#7816: 97.48%\\n\",\n      \"#7817: 97.48%\\n\",\n      \"#7818: 97.48%\\n\",\n      \"#7819: 97.48%\\n\",\n      \"#7820: 97.48%\\n\",\n      \"#7821: 97.48%\\n\",\n      \"#7822: 97.48%\\n\",\n      \"#7823: 97.48%\\n\",\n      \"#7824: 97.48%\\n\",\n      \"#7825: 97.48%\\n\",\n      \"#7826: 97.48%\\n\",\n      \"#7827: 97.48%\\n\",\n      \"#7828: 97.48%\\n\",\n      \"#7829: 97.48%\\n\",\n      \"#7830: 97.48%\\n\",\n      \"#7831: 97.48%\\n\",\n      \"#7832: 97.48%\\n\",\n      \"#7833: 97.49%\\n\",\n      \"#7834: 97.49%\\n\",\n      \"#7835: 97.49%\\n\",\n      \"#7836: 97.49%\\n\",\n      \"#7837: 97.49%\\n\",\n      \"#7838: 97.49%\\n\",\n      \"#7839: 97.49%\\n\",\n      \"#7840: 97.49%\\n\",\n      \"#7841: 97.49%\\n\",\n      \"#7842: 97.49%\\n\",\n      \"#7843: 97.49%\\n\",\n      \"#7844: 97.49%\\n\",\n      \"#7845: 97.48%\\n\",\n      \"#7846: 97.48%\\n\",\n      \"#7847: 97.48%\\n\",\n      \"#7848: 97.48%\\n\",\n      \"#7849: 97.48%\\n\",\n      \"#7850: 97.48%\\n\",\n      \"#7851: 97.48%\\n\",\n      \"#7852: 97.48%\\n\",\n      \"#7853: 97.48%\\n\",\n      \"#7854: 97.48%\\n\",\n      \"#7855: 97.48%\\n\",\n      \"#7856: 97.48%\\n\",\n      \"#7857: 97.48%\\n\",\n      \"#7858: 97.48%\\n\",\n      \"#7859: 97.48%\\n\",\n      \"#7860: 97.48%\\n\",\n      \"#7861: 97.48%\\n\",\n      \"#7862: 97.48%\\n\",\n      \"#7863: 97.48%\\n\",\n      \"#7864: 97.48%\\n\",\n      \"#7865: 97.48%\\n\",\n      \"#7866: 97.48%\\n\",\n      \"#7867: 97.48%\\n\",\n      \"#7868: 97.48%\\n\",\n      \"#7869: 97.48%\\n\",\n      \"#7870: 97.48%\\n\",\n      \"#7871: 97.48%\\n\",\n      \"#7872: 97.49%\\n\",\n      \"#7873: 97.49%\\n\",\n      \"#7874: 97.49%\\n\",\n      \"#7875: 97.49%\\n\",\n      \"#7876: 97.49%\\n\",\n      \"#7877: 97.49%\\n\",\n      \"#7878: 97.49%\\n\",\n      \"#7879: 97.49%\\n\",\n      \"#7880: 97.49%\\n\",\n      \"#7881: 97.49%\\n\",\n      \"#7882: 97.49%\\n\",\n      \"#7883: 97.49%\\n\",\n      \"#7884: 97.49%\\n\",\n      \"#7885: 97.49%\\n\",\n      \"#7886: 97.48%\\n\",\n      \"#7887: 97.48%\\n\",\n      \"#7888: 97.48%\\n\",\n      \"#7889: 97.48%\\n\",\n      \"#7890: 97.48%\\n\",\n      \"#7891: 97.48%\\n\",\n      \"#7892: 97.48%\\n\",\n      \"#7893: 97.48%\\n\",\n      \"#7894: 97.48%\\n\",\n      \"#7895: 97.48%\\n\",\n      \"#7896: 97.48%\\n\",\n      \"#7897: 97.48%\\n\",\n      \"#7898: 97.48%\\n\",\n      \"#7899: 97.48%\\n\",\n      \"#7900: 97.48%\\n\",\n      \"#7901: 97.48%\\n\",\n      \"#7902: 97.48%\\n\",\n      \"#7903: 97.48%\\n\",\n      \"#7904: 97.48%\\n\",\n      \"#7905: 97.48%\\n\",\n      \"#7906: 97.48%\\n\",\n      \"#7907: 97.48%\\n\",\n      \"#7908: 97.48%\\n\",\n      \"#7909: 97.48%\\n\",\n      \"#7910: 97.48%\\n\",\n      \"#7911: 97.48%\\n\",\n      \"#7912: 97.49%\\n\",\n      \"#7913: 97.49%\\n\",\n      \"#7914: 97.49%\\n\",\n      \"#7915: 97.47%\\n\",\n      \"#7916: 97.47%\\n\",\n      \"#7917: 97.47%\\n\",\n      \"#7918: 97.47%\\n\",\n      \"#7919: 97.47%\\n\",\n      \"#7920: 97.48%\\n\",\n      \"#7921: 97.48%\\n\",\n      \"#7922: 97.48%\\n\",\n      \"#7923: 97.48%\\n\",\n      \"#7924: 97.48%\\n\",\n      \"#7925: 97.48%\\n\",\n      \"#7926: 97.48%\\n\",\n      \"#7927: 97.46%\\n\",\n      \"#7928: 97.47%\\n\",\n      \"#7929: 97.47%\\n\",\n      \"#7930: 97.47%\\n\",\n      \"#7931: 97.47%\\n\",\n      \"#7932: 97.47%\\n\",\n      \"#7933: 97.47%\\n\",\n      \"#7934: 97.47%\\n\",\n      \"#7935: 97.47%\\n\",\n      \"#7936: 97.47%\\n\",\n      \"#7937: 97.47%\\n\",\n      \"#7938: 97.47%\\n\",\n      \"#7939: 97.47%\\n\",\n      \"#7940: 97.47%\\n\",\n      \"#7941: 97.47%\\n\",\n      \"#7942: 97.47%\\n\",\n      \"#7943: 97.47%\\n\",\n      \"#7944: 97.47%\\n\",\n      \"#7945: 97.47%\\n\",\n      \"#7946: 97.47%\\n\",\n      \"#7947: 97.47%\\n\",\n      \"#7948: 97.47%\\n\",\n      \"#7949: 97.47%\\n\",\n      \"#7950: 97.47%\\n\",\n      \"#7951: 97.47%\\n\",\n      \"#7952: 97.47%\\n\",\n      \"#7953: 97.47%\\n\",\n      \"#7954: 97.47%\\n\",\n      \"#7955: 97.47%\\n\",\n      \"#7956: 97.47%\\n\",\n      \"#7957: 97.47%\\n\",\n      \"#7958: 97.47%\\n\",\n      \"#7959: 97.47%\\n\",\n      \"#7960: 97.48%\\n\",\n      \"#7961: 97.48%\\n\",\n      \"#7962: 97.48%\\n\",\n      \"#7963: 97.48%\\n\",\n      \"#7964: 97.48%\\n\",\n      \"#7965: 97.48%\\n\",\n      \"#7966: 97.48%\\n\",\n      \"#7967: 97.48%\\n\",\n      \"#7968: 97.48%\\n\",\n      \"#7969: 97.48%\\n\",\n      \"#7970: 97.48%\\n\",\n      \"#7971: 97.48%\\n\",\n      \"#7972: 97.48%\\n\",\n      \"#7973: 97.48%\\n\",\n      \"#7974: 97.48%\\n\",\n      \"#7975: 97.48%\\n\",\n      \"#7976: 97.48%\\n\",\n      \"#7977: 97.48%\\n\",\n      \"#7978: 97.48%\\n\",\n      \"#7979: 97.48%\\n\",\n      \"#7980: 97.48%\\n\",\n      \"#7981: 97.48%\\n\",\n      \"#7982: 97.48%\\n\",\n      \"#7983: 97.48%\\n\",\n      \"#7984: 97.48%\\n\",\n      \"#7985: 97.48%\\n\",\n      \"#7986: 97.48%\\n\",\n      \"#7987: 97.48%\\n\",\n      \"#7988: 97.48%\\n\",\n      \"#7989: 97.48%\\n\",\n      \"#7990: 97.48%\\n\",\n      \"#7991: 97.48%\\n\",\n      \"#7992: 97.49%\\n\",\n      \"#7993: 97.49%\\n\",\n      \"#7994: 97.49%\\n\",\n      \"#7995: 97.49%\\n\",\n      \"#7996: 97.49%\\n\",\n      \"#7997: 97.49%\\n\",\n      \"#7998: 97.49%\\n\",\n      \"#7999: 97.49%\\n\",\n      \"#8000: 97.49%\\n\",\n      \"#8001: 97.49%\\n\",\n      \"#8002: 97.49%\\n\",\n      \"#8003: 97.49%\\n\",\n      \"#8004: 97.49%\\n\",\n      \"#8005: 97.49%\\n\",\n      \"#8006: 97.49%\\n\",\n      \"#8007: 97.49%\\n\",\n      \"#8008: 97.49%\\n\",\n      \"#8009: 97.49%\\n\",\n      \"#8010: 97.49%\\n\",\n      \"#8011: 97.49%\\n\",\n      \"#8012: 97.49%\\n\",\n      \"#8013: 97.49%\\n\",\n      \"#8014: 97.49%\\n\",\n      \"#8015: 97.49%\\n\",\n      \"#8016: 97.49%\\n\",\n      \"#8017: 97.49%\\n\",\n      \"#8018: 97.49%\\n\",\n      \"#8019: 97.49%\\n\",\n      \"#8020: 97.49%\\n\",\n      \"#8021: 97.49%\\n\",\n      \"#8022: 97.49%\\n\",\n      \"#8023: 97.50%\\n\",\n      \"#8024: 97.50%\\n\",\n      \"#8025: 97.50%\\n\",\n      \"#8026: 97.50%\\n\",\n      \"#8027: 97.50%\\n\",\n      \"#8028: 97.50%\\n\",\n      \"#8029: 97.50%\\n\",\n      \"#8030: 97.50%\\n\",\n      \"#8031: 97.50%\\n\",\n      \"#8032: 97.50%\\n\",\n      \"#8033: 97.50%\\n\",\n      \"#8034: 97.50%\\n\",\n      \"#8035: 97.50%\\n\",\n      \"#8036: 97.50%\\n\",\n      \"#8037: 97.50%\\n\",\n      \"#8038: 97.50%\\n\",\n      \"#8039: 97.50%\\n\",\n      \"#8040: 97.50%\\n\",\n      \"#8041: 97.50%\\n\",\n      \"#8042: 97.50%\\n\",\n      \"#8043: 97.50%\\n\",\n      \"#8044: 97.50%\\n\",\n      \"#8045: 97.50%\\n\",\n      \"#8046: 97.50%\\n\",\n      \"#8047: 97.49%\\n\",\n      \"#8048: 97.49%\\n\",\n      \"#8049: 97.49%\\n\",\n      \"#8050: 97.49%\\n\",\n      \"#8051: 97.49%\\n\",\n      \"#8052: 97.49%\\n\",\n      \"#8053: 97.49%\\n\",\n      \"#8054: 97.49%\\n\",\n      \"#8055: 97.49%\\n\",\n      \"#8056: 97.49%\\n\",\n      \"#8057: 97.49%\\n\",\n      \"#8058: 97.49%\\n\",\n      \"#8059: 97.48%\\n\",\n      \"#8060: 97.48%\\n\",\n      \"#8061: 97.48%\\n\",\n      \"#8062: 97.48%\\n\",\n      \"#8063: 97.48%\\n\",\n      \"#8064: 97.48%\\n\",\n      \"#8065: 97.48%\\n\",\n      \"#8066: 97.48%\\n\",\n      \"#8067: 97.48%\\n\",\n      \"#8068: 97.48%\\n\",\n      \"#8069: 97.48%\\n\",\n      \"#8070: 97.48%\\n\",\n      \"#8071: 97.49%\\n\",\n      \"#8072: 97.49%\\n\",\n      \"#8073: 97.49%\\n\",\n      \"#8074: 97.49%\\n\",\n      \"#8075: 97.49%\\n\",\n      \"#8076: 97.49%\\n\",\n      \"#8077: 97.49%\\n\",\n      \"#8078: 97.49%\\n\",\n      \"#8079: 97.49%\\n\",\n      \"#8080: 97.49%\\n\",\n      \"#8081: 97.49%\\n\",\n      \"#8082: 97.49%\\n\",\n      \"#8083: 97.49%\\n\",\n      \"#8084: 97.49%\\n\",\n      \"#8085: 97.49%\\n\",\n      \"#8086: 97.49%\\n\",\n      \"#8087: 97.49%\\n\",\n      \"#8088: 97.49%\\n\",\n      \"#8089: 97.49%\\n\",\n      \"#8090: 97.49%\\n\",\n      \"#8091: 97.48%\\n\",\n      \"#8092: 97.48%\\n\",\n      \"#8093: 97.48%\\n\",\n      \"#8094: 97.47%\\n\",\n      \"#8095: 97.47%\\n\",\n      \"#8096: 97.47%\\n\",\n      \"#8097: 97.47%\\n\",\n      \"#8098: 97.47%\\n\",\n      \"#8099: 97.47%\\n\",\n      \"#8100: 97.47%\\n\",\n      \"#8101: 97.47%\\n\",\n      \"#8102: 97.47%\\n\",\n      \"#8103: 97.47%\\n\",\n      \"#8104: 97.47%\\n\",\n      \"#8105: 97.47%\\n\",\n      \"#8106: 97.47%\\n\",\n      \"#8107: 97.47%\\n\",\n      \"#8108: 97.47%\\n\",\n      \"#8109: 97.47%\\n\",\n      \"#8110: 97.47%\\n\",\n      \"#8111: 97.47%\\n\",\n      \"#8112: 97.47%\\n\",\n      \"#8113: 97.47%\\n\",\n      \"#8114: 97.47%\\n\",\n      \"#8115: 97.47%\\n\",\n      \"#8116: 97.47%\\n\",\n      \"#8117: 97.47%\\n\",\n      \"#8118: 97.48%\\n\",\n      \"#8119: 97.48%\\n\",\n      \"#8120: 97.48%\\n\",\n      \"#8121: 97.48%\\n\",\n      \"#8122: 97.48%\\n\",\n      \"#8123: 97.48%\\n\",\n      \"#8124: 97.48%\\n\",\n      \"#8125: 97.48%\\n\",\n      \"#8126: 97.48%\\n\",\n      \"#8127: 97.48%\\n\",\n      \"#8128: 97.48%\\n\",\n      \"#8129: 97.48%\\n\",\n      \"#8130: 97.48%\\n\",\n      \"#8131: 97.48%\\n\",\n      \"#8132: 97.48%\\n\",\n      \"#8133: 97.48%\\n\",\n      \"#8134: 97.48%\\n\",\n      \"#8135: 97.48%\\n\",\n      \"#8136: 97.48%\\n\",\n      \"#8137: 97.48%\\n\",\n      \"#8138: 97.48%\\n\",\n      \"#8139: 97.48%\\n\",\n      \"#8140: 97.48%\\n\",\n      \"#8141: 97.48%\\n\",\n      \"#8142: 97.48%\\n\",\n      \"#8143: 97.48%\\n\",\n      \"#8144: 97.48%\\n\",\n      \"#8145: 97.48%\\n\",\n      \"#8146: 97.48%\\n\",\n      \"#8147: 97.48%\\n\",\n      \"#8148: 97.48%\\n\",\n      \"#8149: 97.48%\\n\",\n      \"#8150: 97.48%\\n\",\n      \"#8151: 97.49%\\n\",\n      \"#8152: 97.49%\\n\",\n      \"#8153: 97.49%\\n\",\n      \"#8154: 97.49%\\n\",\n      \"#8155: 97.49%\\n\",\n      \"#8156: 97.49%\\n\",\n      \"#8157: 97.49%\\n\",\n      \"#8158: 97.49%\\n\",\n      \"#8159: 97.49%\\n\",\n      \"#8160: 97.49%\\n\",\n      \"#8161: 97.49%\\n\",\n      \"#8162: 97.49%\\n\",\n      \"#8163: 97.49%\\n\",\n      \"#8164: 97.49%\\n\",\n      \"#8165: 97.49%\\n\",\n      \"#8166: 97.49%\\n\",\n      \"#8167: 97.49%\\n\",\n      \"#8168: 97.49%\\n\",\n      \"#8169: 97.49%\\n\",\n      \"#8170: 97.49%\\n\",\n      \"#8171: 97.49%\\n\",\n      \"#8172: 97.49%\\n\",\n      \"#8173: 97.49%\\n\",\n      \"#8174: 97.49%\\n\",\n      \"#8175: 97.49%\\n\",\n      \"#8176: 97.49%\\n\",\n      \"#8177: 97.49%\\n\",\n      \"#8178: 97.49%\\n\",\n      \"#8179: 97.49%\\n\",\n      \"#8180: 97.49%\\n\",\n      \"#8181: 97.49%\\n\",\n      \"#8182: 97.49%\\n\",\n      \"#8183: 97.50%\\n\",\n      \"#8184: 97.50%\\n\",\n      \"#8185: 97.50%\\n\",\n      \"#8186: 97.50%\\n\",\n      \"#8187: 97.50%\\n\",\n      \"#8188: 97.50%\\n\",\n      \"#8189: 97.50%\\n\",\n      \"#8190: 97.50%\\n\",\n      \"#8191: 97.50%\\n\",\n      \"#8192: 97.50%\\n\",\n      \"#8193: 97.50%\\n\",\n      \"#8194: 97.50%\\n\",\n      \"#8195: 97.50%\\n\",\n      \"#8196: 97.50%\\n\",\n      \"#8197: 97.50%\\n\",\n      \"#8198: 97.50%\\n\",\n      \"#8199: 97.50%\\n\",\n      \"#8200: 97.50%\\n\",\n      \"#8201: 97.50%\\n\",\n      \"#8202: 97.50%\\n\",\n      \"#8203: 97.50%\\n\",\n      \"#8204: 97.50%\\n\",\n      \"#8205: 97.50%\\n\",\n      \"#8206: 97.50%\\n\",\n      \"#8207: 97.50%\\n\",\n      \"#8208: 97.50%\\n\",\n      \"#8209: 97.50%\\n\",\n      \"#8210: 97.50%\\n\",\n      \"#8211: 97.50%\\n\",\n      \"#8212: 97.50%\\n\",\n      \"#8213: 97.50%\\n\",\n      \"#8214: 97.50%\\n\",\n      \"#8215: 97.50%\\n\",\n      \"#8216: 97.51%\\n\",\n      \"#8217: 97.51%\\n\",\n      \"#8218: 97.51%\\n\",\n      \"#8219: 97.51%\\n\",\n      \"#8220: 97.51%\\n\",\n      \"#8221: 97.51%\\n\",\n      \"#8222: 97.51%\\n\",\n      \"#8223: 97.51%\\n\",\n      \"#8224: 97.51%\\n\",\n      \"#8225: 97.51%\\n\",\n      \"#8226: 97.51%\\n\",\n      \"#8227: 97.51%\\n\",\n      \"#8228: 97.51%\\n\",\n      \"#8229: 97.51%\\n\",\n      \"#8230: 97.51%\\n\",\n      \"#8231: 97.51%\\n\",\n      \"#8232: 97.51%\\n\",\n      \"#8233: 97.51%\\n\",\n      \"#8234: 97.51%\\n\",\n      \"#8235: 97.51%\\n\",\n      \"#8236: 97.51%\\n\",\n      \"#8237: 97.51%\\n\",\n      \"#8238: 97.51%\\n\",\n      \"#8239: 97.51%\\n\",\n      \"#8240: 97.51%\\n\",\n      \"#8241: 97.51%\\n\",\n      \"#8242: 97.51%\\n\",\n      \"#8243: 97.51%\\n\",\n      \"#8244: 97.51%\\n\",\n      \"#8245: 97.51%\\n\",\n      \"#8246: 97.51%\\n\",\n      \"#8247: 97.51%\\n\",\n      \"#8248: 97.51%\\n\",\n      \"#8249: 97.52%\\n\",\n      \"#8250: 97.52%\\n\",\n      \"#8251: 97.52%\\n\",\n      \"#8252: 97.52%\\n\",\n      \"#8253: 97.52%\\n\",\n      \"#8254: 97.52%\\n\",\n      \"#8255: 97.52%\\n\",\n      \"#8256: 97.52%\\n\",\n      \"#8257: 97.52%\\n\",\n      \"#8258: 97.52%\\n\",\n      \"#8259: 97.52%\\n\",\n      \"#8260: 97.52%\\n\",\n      \"#8261: 97.52%\\n\",\n      \"#8262: 97.52%\\n\",\n      \"#8263: 97.52%\\n\",\n      \"#8264: 97.52%\\n\",\n      \"#8265: 97.52%\\n\",\n      \"#8266: 97.52%\\n\",\n      \"#8267: 97.52%\\n\",\n      \"#8268: 97.52%\\n\",\n      \"#8269: 97.52%\\n\",\n      \"#8270: 97.52%\\n\",\n      \"#8271: 97.52%\\n\",\n      \"#8272: 97.52%\\n\",\n      \"#8273: 97.52%\\n\",\n      \"#8274: 97.52%\\n\",\n      \"#8275: 97.52%\\n\",\n      \"#8276: 97.52%\\n\",\n      \"#8277: 97.52%\\n\",\n      \"#8278: 97.51%\\n\",\n      \"#8279: 97.51%\\n\",\n      \"#8280: 97.51%\\n\",\n      \"#8281: 97.51%\\n\",\n      \"#8282: 97.51%\\n\",\n      \"#8283: 97.51%\\n\",\n      \"#8284: 97.51%\\n\",\n      \"#8285: 97.51%\\n\",\n      \"#8286: 97.51%\\n\",\n      \"#8287: 97.51%\\n\",\n      \"#8288: 97.51%\\n\",\n      \"#8289: 97.52%\\n\",\n      \"#8290: 97.52%\\n\",\n      \"#8291: 97.52%\\n\",\n      \"#8292: 97.52%\\n\",\n      \"#8293: 97.52%\\n\",\n      \"#8294: 97.52%\\n\",\n      \"#8295: 97.52%\\n\",\n      \"#8296: 97.52%\\n\",\n      \"#8297: 97.52%\\n\",\n      \"#8298: 97.52%\\n\",\n      \"#8299: 97.52%\\n\",\n      \"#8300: 97.52%\\n\",\n      \"#8301: 97.52%\\n\",\n      \"#8302: 97.52%\\n\",\n      \"#8303: 97.52%\\n\",\n      \"#8304: 97.52%\\n\",\n      \"#8305: 97.52%\\n\",\n      \"#8306: 97.52%\\n\",\n      \"#8307: 97.52%\\n\",\n      \"#8308: 97.52%\\n\",\n      \"#8309: 97.52%\\n\",\n      \"#8310: 97.52%\\n\",\n      \"#8311: 97.52%\\n\",\n      \"#8312: 97.52%\\n\",\n      \"#8313: 97.52%\\n\",\n      \"#8314: 97.52%\\n\",\n      \"#8315: 97.52%\\n\",\n      \"#8316: 97.51%\\n\",\n      \"#8317: 97.51%\\n\",\n      \"#8318: 97.51%\\n\",\n      \"#8319: 97.51%\\n\",\n      \"#8320: 97.51%\\n\",\n      \"#8321: 97.51%\\n\",\n      \"#8322: 97.50%\\n\",\n      \"#8323: 97.50%\\n\",\n      \"#8324: 97.50%\\n\",\n      \"#8325: 97.49%\\n\",\n      \"#8326: 97.49%\\n\",\n      \"#8327: 97.49%\\n\",\n      \"#8328: 97.49%\\n\",\n      \"#8329: 97.49%\\n\",\n      \"#8330: 97.49%\\n\",\n      \"#8331: 97.49%\\n\",\n      \"#8332: 97.49%\\n\",\n      \"#8333: 97.49%\\n\",\n      \"#8334: 97.49%\\n\",\n      \"#8335: 97.49%\\n\",\n      \"#8336: 97.49%\\n\",\n      \"#8337: 97.49%\\n\",\n      \"#8338: 97.49%\\n\",\n      \"#8339: 97.49%\\n\",\n      \"#8340: 97.49%\\n\",\n      \"#8341: 97.49%\\n\",\n      \"#8342: 97.49%\\n\",\n      \"#8343: 97.50%\\n\",\n      \"#8344: 97.50%\\n\",\n      \"#8345: 97.50%\\n\",\n      \"#8346: 97.50%\\n\",\n      \"#8347: 97.50%\\n\",\n      \"#8348: 97.50%\\n\",\n      \"#8349: 97.50%\\n\",\n      \"#8350: 97.50%\\n\",\n      \"#8351: 97.50%\\n\",\n      \"#8352: 97.50%\\n\",\n      \"#8353: 97.49%\\n\",\n      \"#8354: 97.49%\\n\",\n      \"#8355: 97.49%\\n\",\n      \"#8356: 97.49%\\n\",\n      \"#8357: 97.49%\\n\",\n      \"#8358: 97.49%\\n\",\n      \"#8359: 97.49%\\n\",\n      \"#8360: 97.49%\\n\",\n      \"#8361: 97.49%\\n\",\n      \"#8362: 97.49%\\n\",\n      \"#8363: 97.49%\\n\",\n      \"#8364: 97.49%\\n\",\n      \"#8365: 97.49%\\n\",\n      \"#8366: 97.49%\\n\",\n      \"#8367: 97.49%\\n\",\n      \"#8368: 97.49%\\n\",\n      \"#8369: 97.49%\\n\",\n      \"#8370: 97.49%\\n\",\n      \"#8371: 97.49%\\n\",\n      \"#8372: 97.49%\\n\",\n      \"#8373: 97.49%\\n\",\n      \"#8374: 97.49%\\n\",\n      \"#8375: 97.48%\\n\",\n      \"#8376: 97.48%\\n\",\n      \"#8377: 97.48%\\n\",\n      \"#8378: 97.48%\\n\",\n      \"#8379: 97.48%\\n\",\n      \"#8380: 97.48%\\n\",\n      \"#8381: 97.48%\\n\",\n      \"#8382: 97.48%\\n\",\n      \"#8383: 97.48%\\n\",\n      \"#8384: 97.48%\\n\",\n      \"#8385: 97.48%\\n\",\n      \"#8386: 97.48%\\n\",\n      \"#8387: 97.48%\\n\",\n      \"#8388: 97.48%\\n\",\n      \"#8389: 97.49%\\n\",\n      \"#8390: 97.49%\\n\",\n      \"#8391: 97.49%\\n\",\n      \"#8392: 97.49%\\n\",\n      \"#8393: 97.49%\\n\",\n      \"#8394: 97.49%\\n\",\n      \"#8395: 97.49%\\n\",\n      \"#8396: 97.49%\\n\",\n      \"#8397: 97.49%\\n\",\n      \"#8398: 97.49%\\n\",\n      \"#8399: 97.49%\\n\",\n      \"#8400: 97.49%\\n\",\n      \"#8401: 97.49%\\n\",\n      \"#8402: 97.49%\\n\",\n      \"#8403: 97.49%\\n\",\n      \"#8404: 97.49%\\n\",\n      \"#8405: 97.49%\\n\",\n      \"#8406: 97.49%\\n\",\n      \"#8407: 97.49%\\n\",\n      \"#8408: 97.48%\\n\",\n      \"#8409: 97.48%\\n\",\n      \"#8410: 97.47%\\n\",\n      \"#8411: 97.47%\\n\",\n      \"#8412: 97.47%\\n\",\n      \"#8413: 97.47%\\n\",\n      \"#8414: 97.47%\\n\",\n      \"#8415: 97.47%\\n\",\n      \"#8416: 97.47%\\n\",\n      \"#8417: 97.47%\\n\",\n      \"#8418: 97.47%\\n\",\n      \"#8419: 97.47%\\n\",\n      \"#8420: 97.47%\\n\",\n      \"#8421: 97.47%\\n\",\n      \"#8422: 97.47%\\n\",\n      \"#8423: 97.47%\\n\",\n      \"#8424: 97.47%\\n\",\n      \"#8425: 97.47%\\n\",\n      \"#8426: 97.47%\\n\",\n      \"#8427: 97.47%\\n\",\n      \"#8428: 97.47%\\n\",\n      \"#8429: 97.47%\\n\",\n      \"#8430: 97.47%\\n\",\n      \"#8431: 97.47%\\n\",\n      \"#8432: 97.47%\\n\",\n      \"#8433: 97.47%\\n\",\n      \"#8434: 97.47%\\n\",\n      \"#8435: 97.48%\\n\",\n      \"#8436: 97.48%\\n\",\n      \"#8437: 97.48%\\n\",\n      \"#8438: 97.48%\\n\",\n      \"#8439: 97.48%\\n\",\n      \"#8440: 97.48%\\n\",\n      \"#8441: 97.48%\\n\",\n      \"#8442: 97.48%\\n\",\n      \"#8443: 97.48%\\n\",\n      \"#8444: 97.48%\\n\",\n      \"#8445: 97.48%\\n\",\n      \"#8446: 97.48%\\n\",\n      \"#8447: 97.48%\\n\",\n      \"#8448: 97.48%\\n\",\n      \"#8449: 97.48%\\n\",\n      \"#8450: 97.48%\\n\",\n      \"#8451: 97.48%\\n\",\n      \"#8452: 97.48%\\n\",\n      \"#8453: 97.48%\\n\",\n      \"#8454: 97.48%\\n\",\n      \"#8455: 97.48%\\n\",\n      \"#8456: 97.48%\\n\",\n      \"#8457: 97.48%\\n\",\n      \"#8458: 97.48%\\n\",\n      \"#8459: 97.48%\\n\",\n      \"#8460: 97.48%\\n\",\n      \"#8461: 97.48%\\n\",\n      \"#8462: 97.48%\\n\",\n      \"#8463: 97.48%\\n\",\n      \"#8464: 97.48%\\n\",\n      \"#8465: 97.48%\\n\",\n      \"#8466: 97.48%\\n\",\n      \"#8467: 97.48%\\n\",\n      \"#8468: 97.48%\\n\",\n      \"#8469: 97.49%\\n\",\n      \"#8470: 97.49%\\n\",\n      \"#8471: 97.49%\\n\",\n      \"#8472: 97.49%\\n\",\n      \"#8473: 97.49%\\n\",\n      \"#8474: 97.49%\\n\",\n      \"#8475: 97.49%\\n\",\n      \"#8476: 97.49%\\n\",\n      \"#8477: 97.49%\\n\",\n      \"#8478: 97.49%\\n\",\n      \"#8479: 97.49%\\n\",\n      \"#8480: 97.49%\\n\",\n      \"#8481: 97.49%\\n\",\n      \"#8482: 97.49%\\n\",\n      \"#8483: 97.49%\\n\",\n      \"#8484: 97.49%\\n\",\n      \"#8485: 97.49%\\n\",\n      \"#8486: 97.49%\\n\",\n      \"#8487: 97.49%\\n\",\n      \"#8488: 97.49%\\n\",\n      \"#8489: 97.49%\\n\",\n      \"#8490: 97.49%\\n\",\n      \"#8491: 97.49%\\n\",\n      \"#8492: 97.49%\\n\",\n      \"#8493: 97.49%\\n\",\n      \"#8494: 97.49%\\n\",\n      \"#8495: 97.49%\\n\",\n      \"#8496: 97.49%\\n\",\n      \"#8497: 97.49%\\n\",\n      \"#8498: 97.49%\\n\",\n      \"#8499: 97.49%\\n\",\n      \"#8500: 97.49%\\n\",\n      \"#8501: 97.49%\\n\",\n      \"#8502: 97.50%\\n\",\n      \"#8503: 97.50%\\n\",\n      \"#8504: 97.50%\\n\",\n      \"#8505: 97.50%\\n\",\n      \"#8506: 97.50%\\n\",\n      \"#8507: 97.50%\\n\",\n      \"#8508: 97.50%\\n\",\n      \"#8509: 97.50%\\n\",\n      \"#8510: 97.50%\\n\",\n      \"#8511: 97.50%\\n\",\n      \"#8512: 97.50%\\n\",\n      \"#8513: 97.50%\\n\",\n      \"#8514: 97.50%\\n\",\n      \"#8515: 97.50%\\n\",\n      \"#8516: 97.50%\\n\",\n      \"#8517: 97.50%\\n\",\n      \"#8518: 97.50%\\n\",\n      \"#8519: 97.50%\\n\",\n      \"#8520: 97.50%\\n\",\n      \"#8521: 97.50%\\n\",\n      \"#8522: 97.49%\\n\",\n      \"#8523: 97.49%\\n\",\n      \"#8524: 97.49%\\n\",\n      \"#8525: 97.49%\\n\",\n      \"#8526: 97.49%\\n\",\n      \"#8527: 97.49%\\n\",\n      \"#8528: 97.49%\\n\",\n      \"#8529: 97.49%\\n\",\n      \"#8530: 97.49%\\n\",\n      \"#8531: 97.49%\\n\",\n      \"#8532: 97.49%\\n\",\n      \"#8533: 97.49%\\n\",\n      \"#8534: 97.49%\\n\",\n      \"#8535: 97.49%\\n\",\n      \"#8536: 97.49%\\n\",\n      \"#8537: 97.49%\\n\",\n      \"#8538: 97.49%\\n\",\n      \"#8539: 97.49%\\n\",\n      \"#8540: 97.49%\\n\",\n      \"#8541: 97.49%\\n\",\n      \"#8542: 97.50%\\n\",\n      \"#8543: 97.50%\\n\",\n      \"#8544: 97.50%\\n\",\n      \"#8545: 97.50%\\n\",\n      \"#8546: 97.50%\\n\",\n      \"#8547: 97.50%\\n\",\n      \"#8548: 97.50%\\n\",\n      \"#8549: 97.50%\\n\",\n      \"#8550: 97.50%\\n\",\n      \"#8551: 97.50%\\n\",\n      \"#8552: 97.50%\\n\",\n      \"#8553: 97.50%\\n\",\n      \"#8554: 97.50%\\n\",\n      \"#8555: 97.50%\\n\",\n      \"#8556: 97.50%\\n\",\n      \"#8557: 97.50%\\n\",\n      \"#8558: 97.50%\\n\",\n      \"#8559: 97.50%\\n\",\n      \"#8560: 97.50%\\n\",\n      \"#8561: 97.50%\\n\",\n      \"#8562: 97.50%\\n\",\n      \"#8563: 97.50%\\n\",\n      \"#8564: 97.50%\\n\",\n      \"#8565: 97.50%\\n\",\n      \"#8566: 97.50%\\n\",\n      \"#8567: 97.50%\\n\",\n      \"#8568: 97.50%\\n\",\n      \"#8569: 97.50%\\n\",\n      \"#8570: 97.50%\\n\",\n      \"#8571: 97.50%\\n\",\n      \"#8572: 97.50%\\n\",\n      \"#8573: 97.50%\\n\",\n      \"#8574: 97.50%\\n\",\n      \"#8575: 97.50%\\n\",\n      \"#8576: 97.50%\\n\",\n      \"#8577: 97.51%\\n\",\n      \"#8578: 97.51%\\n\",\n      \"#8579: 97.51%\\n\",\n      \"#8580: 97.51%\\n\",\n      \"#8581: 97.51%\\n\",\n      \"#8582: 97.51%\\n\",\n      \"#8583: 97.51%\\n\",\n      \"#8584: 97.51%\\n\",\n      \"#8585: 97.51%\\n\",\n      \"#8586: 97.51%\\n\",\n      \"#8587: 97.51%\\n\",\n      \"#8588: 97.51%\\n\",\n      \"#8589: 97.51%\\n\",\n      \"#8590: 97.51%\\n\",\n      \"#8591: 97.51%\\n\",\n      \"#8592: 97.51%\\n\",\n      \"#8593: 97.51%\\n\",\n      \"#8594: 97.51%\\n\",\n      \"#8595: 97.51%\\n\",\n      \"#8596: 97.51%\\n\",\n      \"#8597: 97.51%\\n\",\n      \"#8598: 97.51%\\n\",\n      \"#8599: 97.51%\\n\",\n      \"#8600: 97.51%\\n\",\n      \"#8601: 97.51%\\n\",\n      \"#8602: 97.51%\\n\",\n      \"#8603: 97.51%\\n\",\n      \"#8604: 97.51%\\n\",\n      \"#8605: 97.51%\\n\",\n      \"#8606: 97.51%\\n\",\n      \"#8607: 97.51%\\n\",\n      \"#8608: 97.51%\\n\",\n      \"#8609: 97.51%\\n\",\n      \"#8610: 97.51%\\n\",\n      \"#8611: 97.52%\\n\",\n      \"#8612: 97.52%\\n\",\n      \"#8613: 97.52%\\n\",\n      \"#8614: 97.52%\\n\",\n      \"#8615: 97.52%\\n\",\n      \"#8616: 97.52%\\n\",\n      \"#8617: 97.52%\\n\",\n      \"#8618: 97.52%\\n\",\n      \"#8619: 97.52%\\n\",\n      \"#8620: 97.52%\\n\",\n      \"#8621: 97.52%\\n\",\n      \"#8622: 97.52%\\n\",\n      \"#8623: 97.52%\\n\",\n      \"#8624: 97.52%\\n\",\n      \"#8625: 97.52%\\n\",\n      \"#8626: 97.52%\\n\",\n      \"#8627: 97.52%\\n\",\n      \"#8628: 97.52%\\n\",\n      \"#8629: 97.52%\\n\",\n      \"#8630: 97.52%\\n\",\n      \"#8631: 97.52%\\n\",\n      \"#8632: 97.52%\\n\",\n      \"#8633: 97.52%\\n\",\n      \"#8634: 97.52%\\n\",\n      \"#8635: 97.52%\\n\",\n      \"#8636: 97.52%\\n\",\n      \"#8637: 97.52%\\n\",\n      \"#8638: 97.52%\\n\",\n      \"#8639: 97.52%\\n\",\n      \"#8640: 97.52%\\n\",\n      \"#8641: 97.52%\\n\",\n      \"#8642: 97.52%\\n\",\n      \"#8643: 97.52%\\n\",\n      \"#8644: 97.52%\\n\",\n      \"#8645: 97.52%\\n\",\n      \"#8646: 97.53%\\n\",\n      \"#8647: 97.53%\\n\",\n      \"#8648: 97.53%\\n\",\n      \"#8649: 97.53%\\n\",\n      \"#8650: 97.53%\\n\",\n      \"#8651: 97.53%\\n\",\n      \"#8652: 97.53%\\n\",\n      \"#8653: 97.53%\\n\",\n      \"#8654: 97.53%\\n\",\n      \"#8655: 97.53%\\n\",\n      \"#8656: 97.53%\\n\",\n      \"#8657: 97.53%\\n\",\n      \"#8658: 97.53%\\n\",\n      \"#8659: 97.53%\\n\",\n      \"#8660: 97.53%\\n\",\n      \"#8661: 97.53%\\n\",\n      \"#8662: 97.53%\\n\",\n      \"#8663: 97.53%\\n\",\n      \"#8664: 97.53%\\n\",\n      \"#8665: 97.53%\\n\",\n      \"#8666: 97.53%\\n\",\n      \"#8667: 97.53%\\n\",\n      \"#8668: 97.53%\\n\",\n      \"#8669: 97.53%\\n\",\n      \"#8670: 97.53%\\n\",\n      \"#8671: 97.53%\\n\",\n      \"#8672: 97.53%\\n\",\n      \"#8673: 97.53%\\n\",\n      \"#8674: 97.53%\\n\",\n      \"#8675: 97.53%\\n\",\n      \"#8676: 97.53%\\n\",\n      \"#8677: 97.53%\\n\",\n      \"#8678: 97.53%\\n\",\n      \"#8679: 97.53%\\n\",\n      \"#8680: 97.53%\\n\",\n      \"#8681: 97.54%\\n\",\n      \"#8682: 97.54%\\n\",\n      \"#8683: 97.54%\\n\",\n      \"#8684: 97.54%\\n\",\n      \"#8685: 97.54%\\n\",\n      \"#8686: 97.54%\\n\",\n      \"#8687: 97.54%\\n\",\n      \"#8688: 97.54%\\n\",\n      \"#8689: 97.54%\\n\",\n      \"#8690: 97.54%\\n\",\n      \"#8691: 97.54%\\n\",\n      \"#8692: 97.54%\\n\",\n      \"#8693: 97.54%\\n\",\n      \"#8694: 97.54%\\n\",\n      \"#8695: 97.54%\\n\",\n      \"#8696: 97.54%\\n\",\n      \"#8697: 97.54%\\n\",\n      \"#8698: 97.54%\\n\",\n      \"#8699: 97.54%\\n\",\n      \"#8700: 97.54%\\n\",\n      \"#8701: 97.54%\\n\",\n      \"#8702: 97.54%\\n\",\n      \"#8703: 97.54%\\n\",\n      \"#8704: 97.54%\\n\",\n      \"#8705: 97.54%\\n\",\n      \"#8706: 97.54%\\n\",\n      \"#8707: 97.54%\\n\",\n      \"#8708: 97.54%\\n\",\n      \"#8709: 97.54%\\n\",\n      \"#8710: 97.54%\\n\",\n      \"#8711: 97.54%\\n\",\n      \"#8712: 97.54%\\n\",\n      \"#8713: 97.54%\\n\",\n      \"#8714: 97.54%\\n\",\n      \"#8715: 97.54%\\n\",\n      \"#8716: 97.55%\\n\",\n      \"#8717: 97.55%\\n\",\n      \"#8718: 97.55%\\n\",\n      \"#8719: 97.55%\\n\",\n      \"#8720: 97.55%\\n\",\n      \"#8721: 97.55%\\n\",\n      \"#8722: 97.55%\\n\",\n      \"#8723: 97.55%\\n\",\n      \"#8724: 97.55%\\n\",\n      \"#8725: 97.55%\\n\",\n      \"#8726: 97.55%\\n\",\n      \"#8727: 97.55%\\n\",\n      \"#8728: 97.55%\\n\",\n      \"#8729: 97.55%\\n\",\n      \"#8730: 97.55%\\n\",\n      \"#8731: 97.55%\\n\",\n      \"#8732: 97.55%\\n\",\n      \"#8733: 97.55%\\n\",\n      \"#8734: 97.55%\\n\",\n      \"#8735: 97.55%\\n\",\n      \"#8736: 97.55%\\n\",\n      \"#8737: 97.55%\\n\",\n      \"#8738: 97.55%\\n\",\n      \"#8739: 97.55%\\n\",\n      \"#8740: 97.55%\\n\",\n      \"#8741: 97.55%\\n\",\n      \"#8742: 97.55%\\n\",\n      \"#8743: 97.55%\\n\",\n      \"#8744: 97.55%\\n\",\n      \"#8745: 97.55%\\n\",\n      \"#8746: 97.55%\\n\",\n      \"#8747: 97.55%\\n\",\n      \"#8748: 97.55%\\n\",\n      \"#8749: 97.55%\\n\",\n      \"#8750: 97.55%\\n\",\n      \"#8751: 97.55%\\n\",\n      \"#8752: 97.56%\\n\",\n      \"#8753: 97.56%\\n\",\n      \"#8754: 97.56%\\n\",\n      \"#8755: 97.56%\\n\",\n      \"#8756: 97.56%\\n\",\n      \"#8757: 97.56%\\n\",\n      \"#8758: 97.56%\\n\",\n      \"#8759: 97.56%\\n\",\n      \"#8760: 97.56%\\n\",\n      \"#8761: 97.56%\\n\",\n      \"#8762: 97.56%\\n\",\n      \"#8763: 97.56%\\n\",\n      \"#8764: 97.56%\\n\",\n      \"#8765: 97.56%\\n\",\n      \"#8766: 97.56%\\n\",\n      \"#8767: 97.56%\\n\",\n      \"#8768: 97.56%\\n\",\n      \"#8769: 97.56%\\n\",\n      \"#8770: 97.56%\\n\",\n      \"#8771: 97.56%\\n\",\n      \"#8772: 97.56%\\n\",\n      \"#8773: 97.56%\\n\",\n      \"#8774: 97.56%\\n\",\n      \"#8775: 97.56%\\n\",\n      \"#8776: 97.56%\\n\",\n      \"#8777: 97.56%\\n\",\n      \"#8778: 97.56%\\n\",\n      \"#8779: 97.56%\\n\",\n      \"#8780: 97.56%\\n\",\n      \"#8781: 97.56%\\n\",\n      \"#8782: 97.56%\\n\",\n      \"#8783: 97.56%\\n\",\n      \"#8784: 97.56%\\n\",\n      \"#8785: 97.56%\\n\",\n      \"#8786: 97.56%\\n\",\n      \"#8787: 97.56%\\n\",\n      \"#8788: 97.57%\\n\",\n      \"#8789: 97.57%\\n\",\n      \"#8790: 97.57%\\n\",\n      \"#8791: 97.57%\\n\",\n      \"#8792: 97.57%\\n\",\n      \"#8793: 97.57%\\n\",\n      \"#8794: 97.57%\\n\",\n      \"#8795: 97.57%\\n\",\n      \"#8796: 97.57%\\n\",\n      \"#8797: 97.57%\\n\",\n      \"#8798: 97.57%\\n\",\n      \"#8799: 97.57%\\n\",\n      \"#8800: 97.57%\\n\",\n      \"#8801: 97.57%\\n\",\n      \"#8802: 97.57%\\n\",\n      \"#8803: 97.57%\\n\",\n      \"#8804: 97.57%\\n\",\n      \"#8805: 97.57%\\n\",\n      \"#8806: 97.57%\\n\",\n      \"#8807: 97.57%\\n\",\n      \"#8808: 97.57%\\n\",\n      \"#8809: 97.57%\\n\",\n      \"#8810: 97.57%\\n\",\n      \"#8811: 97.57%\\n\",\n      \"#8812: 97.57%\\n\",\n      \"#8813: 97.57%\\n\",\n      \"#8814: 97.57%\\n\",\n      \"#8815: 97.57%\\n\",\n      \"#8816: 97.57%\\n\",\n      \"#8817: 97.57%\\n\",\n      \"#8818: 97.57%\\n\",\n      \"#8819: 97.57%\\n\",\n      \"#8820: 97.57%\\n\",\n      \"#8821: 97.57%\\n\",\n      \"#8822: 97.57%\\n\",\n      \"#8823: 97.57%\\n\",\n      \"#8824: 97.58%\\n\",\n      \"#8825: 97.58%\\n\",\n      \"#8826: 97.58%\\n\",\n      \"#8827: 97.58%\\n\",\n      \"#8828: 97.58%\\n\",\n      \"#8829: 97.58%\\n\",\n      \"#8830: 97.58%\\n\",\n      \"#8831: 97.58%\\n\",\n      \"#8832: 97.58%\\n\",\n      \"#8833: 97.58%\\n\",\n      \"#8834: 97.58%\\n\",\n      \"#8835: 97.58%\\n\",\n      \"#8836: 97.58%\\n\",\n      \"#8837: 97.58%\\n\",\n      \"#8838: 97.58%\\n\",\n      \"#8839: 97.58%\\n\",\n      \"#8840: 97.58%\\n\",\n      \"#8841: 97.58%\\n\",\n      \"#8842: 97.58%\\n\",\n      \"#8843: 97.58%\\n\",\n      \"#8844: 97.58%\\n\",\n      \"#8845: 97.58%\\n\",\n      \"#8846: 97.58%\\n\",\n      \"#8847: 97.58%\\n\",\n      \"#8848: 97.58%\\n\",\n      \"#8849: 97.58%\\n\",\n      \"#8850: 97.58%\\n\",\n      \"#8851: 97.58%\\n\",\n      \"#8852: 97.58%\\n\",\n      \"#8853: 97.58%\\n\",\n      \"#8854: 97.58%\\n\",\n      \"#8855: 97.58%\\n\",\n      \"#8856: 97.58%\\n\",\n      \"#8857: 97.58%\\n\",\n      \"#8858: 97.58%\\n\",\n      \"#8859: 97.58%\\n\",\n      \"#8860: 97.58%\\n\",\n      \"#8861: 97.59%\\n\",\n      \"#8862: 97.59%\\n\",\n      \"#8863: 97.59%\\n\",\n      \"#8864: 97.59%\\n\",\n      \"#8865: 97.59%\\n\",\n      \"#8866: 97.59%\\n\",\n      \"#8867: 97.59%\\n\",\n      \"#8868: 97.59%\\n\",\n      \"#8869: 97.59%\\n\",\n      \"#8870: 97.59%\\n\",\n      \"#8871: 97.59%\\n\",\n      \"#8872: 97.59%\\n\",\n      \"#8873: 97.59%\\n\",\n      \"#8874: 97.59%\\n\",\n      \"#8875: 97.59%\\n\",\n      \"#8876: 97.59%\\n\",\n      \"#8877: 97.59%\\n\",\n      \"#8878: 97.59%\\n\",\n      \"#8879: 97.59%\\n\",\n      \"#8880: 97.59%\\n\",\n      \"#8881: 97.59%\\n\",\n      \"#8882: 97.59%\\n\",\n      \"#8883: 97.59%\\n\",\n      \"#8884: 97.59%\\n\",\n      \"#8885: 97.59%\\n\",\n      \"#8886: 97.59%\\n\",\n      \"#8887: 97.59%\\n\",\n      \"#8888: 97.59%\\n\",\n      \"#8889: 97.59%\\n\",\n      \"#8890: 97.59%\\n\",\n      \"#8891: 97.59%\\n\",\n      \"#8892: 97.59%\\n\",\n      \"#8893: 97.59%\\n\",\n      \"#8894: 97.59%\\n\",\n      \"#8895: 97.59%\\n\",\n      \"#8896: 97.59%\\n\",\n      \"#8897: 97.59%\\n\",\n      \"#8898: 97.60%\\n\",\n      \"#8899: 97.60%\\n\",\n      \"#8900: 97.60%\\n\",\n      \"#8901: 97.60%\\n\",\n      \"#8902: 97.60%\\n\",\n      \"#8903: 97.60%\\n\",\n      \"#8904: 97.60%\\n\",\n      \"#8905: 97.60%\\n\",\n      \"#8906: 97.60%\\n\",\n      \"#8907: 97.60%\\n\",\n      \"#8908: 97.60%\\n\",\n      \"#8909: 97.60%\\n\",\n      \"#8910: 97.60%\\n\",\n      \"#8911: 97.60%\\n\",\n      \"#8912: 97.60%\\n\",\n      \"#8913: 97.60%\\n\",\n      \"#8914: 97.60%\\n\",\n      \"#8915: 97.60%\\n\",\n      \"#8916: 97.60%\\n\",\n      \"#8917: 97.60%\\n\",\n      \"#8918: 97.60%\\n\",\n      \"#8919: 97.60%\\n\",\n      \"#8920: 97.60%\\n\",\n      \"#8921: 97.60%\\n\",\n      \"#8922: 97.60%\\n\",\n      \"#8923: 97.60%\\n\",\n      \"#8924: 97.60%\\n\",\n      \"#8925: 97.60%\\n\",\n      \"#8926: 97.60%\\n\",\n      \"#8927: 97.60%\\n\",\n      \"#8928: 97.60%\\n\",\n      \"#8929: 97.60%\\n\",\n      \"#8930: 97.60%\\n\",\n      \"#8931: 97.60%\\n\",\n      \"#8932: 97.60%\\n\",\n      \"#8933: 97.60%\\n\",\n      \"#8934: 97.60%\\n\",\n      \"#8935: 97.61%\\n\",\n      \"#8936: 97.61%\\n\",\n      \"#8937: 97.61%\\n\",\n      \"#8938: 97.61%\\n\",\n      \"#8939: 97.61%\\n\",\n      \"#8940: 97.61%\\n\",\n      \"#8941: 97.61%\\n\",\n      \"#8942: 97.61%\\n\",\n      \"#8943: 97.61%\\n\",\n      \"#8944: 97.61%\\n\",\n      \"#8945: 97.61%\\n\",\n      \"#8946: 97.61%\\n\",\n      \"#8947: 97.61%\\n\",\n      \"#8948: 97.61%\\n\",\n      \"#8949: 97.61%\\n\",\n      \"#8950: 97.61%\\n\",\n      \"#8951: 97.61%\\n\",\n      \"#8952: 97.61%\\n\",\n      \"#8953: 97.61%\\n\",\n      \"#8954: 97.61%\\n\",\n      \"#8955: 97.61%\\n\",\n      \"#8956: 97.61%\\n\",\n      \"#8957: 97.61%\\n\",\n      \"#8958: 97.61%\\n\",\n      \"#8959: 97.61%\\n\",\n      \"#8960: 97.61%\\n\",\n      \"#8961: 97.61%\\n\",\n      \"#8962: 97.61%\\n\",\n      \"#8963: 97.61%\\n\",\n      \"#8964: 97.61%\\n\",\n      \"#8965: 97.61%\\n\",\n      \"#8966: 97.61%\\n\",\n      \"#8967: 97.61%\\n\",\n      \"#8968: 97.61%\\n\",\n      \"#8969: 97.61%\\n\",\n      \"#8970: 97.61%\\n\",\n      \"#8971: 97.61%\\n\",\n      \"#8972: 97.62%\\n\",\n      \"#8973: 97.62%\\n\",\n      \"#8974: 97.62%\\n\",\n      \"#8975: 97.62%\\n\",\n      \"#8976: 97.62%\\n\",\n      \"#8977: 97.62%\\n\",\n      \"#8978: 97.62%\\n\",\n      \"#8979: 97.62%\\n\",\n      \"#8980: 97.62%\\n\",\n      \"#8981: 97.62%\\n\",\n      \"#8982: 97.62%\\n\",\n      \"#8983: 97.62%\\n\",\n      \"#8984: 97.62%\\n\",\n      \"#8985: 97.62%\\n\",\n      \"#8986: 97.62%\\n\",\n      \"#8987: 97.62%\\n\",\n      \"#8988: 97.62%\\n\",\n      \"#8989: 97.62%\\n\",\n      \"#8990: 97.62%\\n\",\n      \"#8991: 97.62%\\n\",\n      \"#8992: 97.62%\\n\",\n      \"#8993: 97.62%\\n\",\n      \"#8994: 97.62%\\n\",\n      \"#8995: 97.62%\\n\",\n      \"#8996: 97.62%\\n\",\n      \"#8997: 97.62%\\n\",\n      \"#8998: 97.62%\\n\",\n      \"#8999: 97.62%\\n\",\n      \"#9000: 97.62%\\n\",\n      \"#9001: 97.62%\\n\",\n      \"#9002: 97.62%\\n\",\n      \"#9003: 97.62%\\n\",\n      \"#9004: 97.62%\\n\",\n      \"#9005: 97.62%\\n\",\n      \"#9006: 97.62%\\n\",\n      \"#9007: 97.62%\\n\",\n      \"#9008: 97.62%\\n\",\n      \"#9009: 97.61%\\n\",\n      \"#9010: 97.61%\\n\",\n      \"#9011: 97.61%\\n\",\n      \"#9012: 97.61%\\n\",\n      \"#9013: 97.61%\\n\",\n      \"#9014: 97.62%\\n\",\n      \"#9015: 97.60%\\n\",\n      \"#9016: 97.60%\\n\",\n      \"#9017: 97.60%\\n\",\n      \"#9018: 97.61%\\n\",\n      \"#9019: 97.59%\\n\",\n      \"#9020: 97.59%\\n\",\n      \"#9021: 97.59%\\n\",\n      \"#9022: 97.60%\\n\",\n      \"#9023: 97.60%\\n\",\n      \"#9024: 97.58%\\n\",\n      \"#9025: 97.58%\\n\",\n      \"#9026: 97.59%\\n\",\n      \"#9027: 97.59%\\n\",\n      \"#9028: 97.59%\\n\",\n      \"#9029: 97.59%\\n\",\n      \"#9030: 97.59%\\n\",\n      \"#9031: 97.59%\\n\",\n      \"#9032: 97.59%\\n\",\n      \"#9033: 97.59%\\n\",\n      \"#9034: 97.59%\\n\",\n      \"#9035: 97.59%\\n\",\n      \"#9036: 97.58%\\n\",\n      \"#9037: 97.58%\\n\",\n      \"#9038: 97.58%\\n\",\n      \"#9039: 97.58%\\n\",\n      \"#9040: 97.58%\\n\",\n      \"#9041: 97.58%\\n\",\n      \"#9042: 97.58%\\n\",\n      \"#9043: 97.58%\\n\",\n      \"#9044: 97.58%\\n\",\n      \"#9045: 97.58%\\n\",\n      \"#9046: 97.58%\\n\",\n      \"#9047: 97.58%\\n\",\n      \"#9048: 97.58%\\n\",\n      \"#9049: 97.58%\\n\",\n      \"#9050: 97.58%\\n\",\n      \"#9051: 97.58%\\n\",\n      \"#9052: 97.58%\\n\",\n      \"#9053: 97.58%\\n\",\n      \"#9054: 97.58%\\n\",\n      \"#9055: 97.58%\\n\",\n      \"#9056: 97.58%\\n\",\n      \"#9057: 97.58%\\n\",\n      \"#9058: 97.58%\\n\",\n      \"#9059: 97.58%\\n\",\n      \"#9060: 97.58%\\n\",\n      \"#9061: 97.58%\\n\",\n      \"#9062: 97.58%\\n\",\n      \"#9063: 97.58%\\n\",\n      \"#9064: 97.58%\\n\",\n      \"#9065: 97.58%\\n\",\n      \"#9066: 97.58%\\n\",\n      \"#9067: 97.58%\\n\",\n      \"#9068: 97.59%\\n\",\n      \"#9069: 97.59%\\n\",\n      \"#9070: 97.59%\\n\",\n      \"#9071: 97.57%\\n\",\n      \"#9072: 97.58%\\n\",\n      \"#9073: 97.58%\\n\",\n      \"#9074: 97.58%\\n\",\n      \"#9075: 97.58%\\n\",\n      \"#9076: 97.58%\\n\",\n      \"#9077: 97.58%\\n\",\n      \"#9078: 97.58%\\n\",\n      \"#9079: 97.58%\\n\",\n      \"#9080: 97.58%\\n\",\n      \"#9081: 97.58%\\n\",\n      \"#9082: 97.58%\\n\",\n      \"#9083: 97.58%\\n\",\n      \"#9084: 97.58%\\n\",\n      \"#9085: 97.58%\\n\",\n      \"#9086: 97.58%\\n\",\n      \"#9087: 97.58%\\n\",\n      \"#9088: 97.58%\\n\",\n      \"#9089: 97.58%\\n\",\n      \"#9090: 97.58%\\n\",\n      \"#9091: 97.58%\\n\",\n      \"#9092: 97.58%\\n\",\n      \"#9093: 97.58%\\n\",\n      \"#9094: 97.58%\\n\",\n      \"#9095: 97.58%\\n\",\n      \"#9096: 97.58%\\n\",\n      \"#9097: 97.58%\\n\",\n      \"#9098: 97.58%\\n\",\n      \"#9099: 97.58%\\n\",\n      \"#9100: 97.58%\\n\",\n      \"#9101: 97.58%\\n\",\n      \"#9102: 97.58%\\n\",\n      \"#9103: 97.58%\\n\",\n      \"#9104: 97.58%\\n\",\n      \"#9105: 97.58%\\n\",\n      \"#9106: 97.58%\\n\",\n      \"#9107: 97.58%\\n\",\n      \"#9108: 97.58%\\n\",\n      \"#9109: 97.59%\\n\",\n      \"#9110: 97.59%\\n\",\n      \"#9111: 97.59%\\n\",\n      \"#9112: 97.59%\\n\",\n      \"#9113: 97.59%\\n\",\n      \"#9114: 97.59%\\n\",\n      \"#9115: 97.59%\\n\",\n      \"#9116: 97.59%\\n\",\n      \"#9117: 97.59%\\n\",\n      \"#9118: 97.59%\\n\",\n      \"#9119: 97.59%\\n\",\n      \"#9120: 97.59%\\n\",\n      \"#9121: 97.59%\\n\",\n      \"#9122: 97.59%\\n\",\n      \"#9123: 97.59%\\n\",\n      \"#9124: 97.59%\\n\",\n      \"#9125: 97.59%\\n\",\n      \"#9126: 97.59%\\n\",\n      \"#9127: 97.59%\\n\",\n      \"#9128: 97.59%\\n\",\n      \"#9129: 97.59%\\n\",\n      \"#9130: 97.59%\\n\",\n      \"#9131: 97.59%\\n\",\n      \"#9132: 97.59%\\n\",\n      \"#9133: 97.59%\\n\",\n      \"#9134: 97.59%\\n\",\n      \"#9135: 97.59%\\n\",\n      \"#9136: 97.59%\\n\",\n      \"#9137: 97.59%\\n\",\n      \"#9138: 97.59%\\n\",\n      \"#9139: 97.59%\\n\",\n      \"#9140: 97.59%\\n\",\n      \"#9141: 97.59%\\n\",\n      \"#9142: 97.59%\\n\",\n      \"#9143: 97.59%\\n\",\n      \"#9144: 97.59%\\n\",\n      \"#9145: 97.59%\\n\",\n      \"#9146: 97.59%\\n\",\n      \"#9147: 97.60%\\n\",\n      \"#9148: 97.60%\\n\",\n      \"#9149: 97.60%\\n\",\n      \"#9150: 97.60%\\n\",\n      \"#9151: 97.60%\\n\",\n      \"#9152: 97.60%\\n\",\n      \"#9153: 97.60%\\n\",\n      \"#9154: 97.60%\\n\",\n      \"#9155: 97.60%\\n\",\n      \"#9156: 97.60%\\n\",\n      \"#9157: 97.60%\\n\",\n      \"#9158: 97.60%\\n\",\n      \"#9159: 97.60%\\n\",\n      \"#9160: 97.60%\\n\",\n      \"#9161: 97.60%\\n\",\n      \"#9162: 97.60%\\n\",\n      \"#9163: 97.60%\\n\",\n      \"#9164: 97.60%\\n\",\n      \"#9165: 97.60%\\n\",\n      \"#9166: 97.60%\\n\",\n      \"#9167: 97.60%\\n\",\n      \"#9168: 97.60%\\n\",\n      \"#9169: 97.60%\\n\",\n      \"#9170: 97.60%\\n\",\n      \"#9171: 97.60%\\n\",\n      \"#9172: 97.60%\\n\",\n      \"#9173: 97.60%\\n\",\n      \"#9174: 97.60%\\n\",\n      \"#9175: 97.60%\\n\",\n      \"#9176: 97.60%\\n\",\n      \"#9177: 97.60%\\n\",\n      \"#9178: 97.60%\\n\",\n      \"#9179: 97.60%\\n\",\n      \"#9180: 97.60%\\n\",\n      \"#9181: 97.60%\\n\",\n      \"#9182: 97.60%\\n\",\n      \"#9183: 97.60%\\n\",\n      \"#9184: 97.60%\\n\",\n      \"#9185: 97.61%\\n\",\n      \"#9186: 97.61%\\n\",\n      \"#9187: 97.61%\\n\",\n      \"#9188: 97.61%\\n\",\n      \"#9189: 97.61%\\n\",\n      \"#9190: 97.61%\\n\",\n      \"#9191: 97.61%\\n\",\n      \"#9192: 97.61%\\n\",\n      \"#9193: 97.61%\\n\",\n      \"#9194: 97.61%\\n\",\n      \"#9195: 97.61%\\n\",\n      \"#9196: 97.61%\\n\",\n      \"#9197: 97.61%\\n\",\n      \"#9198: 97.61%\\n\",\n      \"#9199: 97.61%\\n\",\n      \"#9200: 97.61%\\n\",\n      \"#9201: 97.61%\\n\",\n      \"#9202: 97.60%\\n\",\n      \"#9203: 97.60%\\n\",\n      \"#9204: 97.60%\\n\",\n      \"#9205: 97.60%\\n\",\n      \"#9206: 97.60%\\n\",\n      \"#9207: 97.60%\\n\",\n      \"#9208: 97.60%\\n\",\n      \"#9209: 97.60%\\n\",\n      \"#9210: 97.60%\\n\",\n      \"#9211: 97.60%\\n\",\n      \"#9212: 97.60%\\n\",\n      \"#9213: 97.60%\\n\",\n      \"#9214: 97.60%\\n\",\n      \"#9215: 97.60%\\n\",\n      \"#9216: 97.60%\\n\",\n      \"#9217: 97.60%\\n\",\n      \"#9218: 97.60%\\n\",\n      \"#9219: 97.60%\\n\",\n      \"#9220: 97.60%\\n\",\n      \"#9221: 97.60%\\n\",\n      \"#9222: 97.60%\\n\",\n      \"#9223: 97.60%\\n\",\n      \"#9224: 97.60%\\n\",\n      \"#9225: 97.60%\\n\",\n      \"#9226: 97.60%\\n\",\n      \"#9227: 97.61%\\n\",\n      \"#9228: 97.61%\\n\",\n      \"#9229: 97.61%\\n\",\n      \"#9230: 97.61%\\n\",\n      \"#9231: 97.61%\\n\",\n      \"#9232: 97.61%\\n\",\n      \"#9233: 97.61%\\n\",\n      \"#9234: 97.61%\\n\",\n      \"#9235: 97.61%\\n\",\n      \"#9236: 97.61%\\n\",\n      \"#9237: 97.61%\\n\",\n      \"#9238: 97.61%\\n\",\n      \"#9239: 97.61%\\n\",\n      \"#9240: 97.61%\\n\",\n      \"#9241: 97.61%\\n\",\n      \"#9242: 97.61%\\n\",\n      \"#9243: 97.61%\\n\",\n      \"#9244: 97.61%\\n\",\n      \"#9245: 97.61%\\n\",\n      \"#9246: 97.61%\\n\",\n      \"#9247: 97.61%\\n\",\n      \"#9248: 97.61%\\n\",\n      \"#9249: 97.61%\\n\",\n      \"#9250: 97.61%\\n\",\n      \"#9251: 97.61%\\n\",\n      \"#9252: 97.61%\\n\",\n      \"#9253: 97.61%\\n\",\n      \"#9254: 97.61%\\n\",\n      \"#9255: 97.61%\\n\",\n      \"#9256: 97.61%\\n\",\n      \"#9257: 97.61%\\n\",\n      \"#9258: 97.61%\\n\",\n      \"#9259: 97.61%\\n\",\n      \"#9260: 97.61%\\n\",\n      \"#9261: 97.61%\\n\",\n      \"#9262: 97.61%\\n\",\n      \"#9263: 97.61%\\n\",\n      \"#9264: 97.61%\\n\",\n      \"#9265: 97.61%\\n\",\n      \"#9266: 97.62%\\n\",\n      \"#9267: 97.62%\\n\",\n      \"#9268: 97.62%\\n\",\n      \"#9269: 97.62%\\n\",\n      \"#9270: 97.62%\\n\",\n      \"#9271: 97.62%\\n\",\n      \"#9272: 97.62%\\n\",\n      \"#9273: 97.62%\\n\",\n      \"#9274: 97.62%\\n\",\n      \"#9275: 97.62%\\n\",\n      \"#9276: 97.62%\\n\",\n      \"#9277: 97.62%\\n\",\n      \"#9278: 97.62%\\n\",\n      \"#9279: 97.62%\\n\",\n      \"#9280: 97.62%\\n\",\n      \"#9281: 97.62%\\n\",\n      \"#9282: 97.62%\\n\",\n      \"#9283: 97.62%\\n\",\n      \"#9284: 97.62%\\n\",\n      \"#9285: 97.62%\\n\",\n      \"#9286: 97.62%\\n\",\n      \"#9287: 97.62%\\n\",\n      \"#9288: 97.62%\\n\",\n      \"#9289: 97.62%\\n\",\n      \"#9290: 97.62%\\n\",\n      \"#9291: 97.62%\\n\",\n      \"#9292: 97.62%\\n\",\n      \"#9293: 97.62%\\n\",\n      \"#9294: 97.62%\\n\",\n      \"#9295: 97.62%\\n\",\n      \"#9296: 97.62%\\n\",\n      \"#9297: 97.62%\\n\",\n      \"#9298: 97.62%\\n\",\n      \"#9299: 97.62%\\n\",\n      \"#9300: 97.62%\\n\",\n      \"#9301: 97.62%\\n\",\n      \"#9302: 97.62%\\n\",\n      \"#9303: 97.62%\\n\",\n      \"#9304: 97.62%\\n\",\n      \"#9305: 97.63%\\n\",\n      \"#9306: 97.63%\\n\",\n      \"#9307: 97.63%\\n\",\n      \"#9308: 97.63%\\n\",\n      \"#9309: 97.63%\\n\",\n      \"#9310: 97.63%\\n\",\n      \"#9311: 97.63%\\n\",\n      \"#9312: 97.63%\\n\",\n      \"#9313: 97.63%\\n\",\n      \"#9314: 97.63%\\n\",\n      \"#9315: 97.63%\\n\",\n      \"#9316: 97.63%\\n\",\n      \"#9317: 97.63%\\n\",\n      \"#9318: 97.63%\\n\",\n      \"#9319: 97.63%\\n\",\n      \"#9320: 97.63%\\n\",\n      \"#9321: 97.63%\\n\",\n      \"#9322: 97.63%\\n\",\n      \"#9323: 97.63%\\n\",\n      \"#9324: 97.63%\\n\",\n      \"#9325: 97.63%\\n\",\n      \"#9326: 97.63%\\n\",\n      \"#9327: 97.63%\\n\",\n      \"#9328: 97.63%\\n\",\n      \"#9329: 97.63%\\n\",\n      \"#9330: 97.63%\\n\",\n      \"#9331: 97.63%\\n\",\n      \"#9332: 97.63%\\n\",\n      \"#9333: 97.63%\\n\",\n      \"#9334: 97.63%\\n\",\n      \"#9335: 97.63%\\n\",\n      \"#9336: 97.63%\\n\",\n      \"#9337: 97.63%\\n\",\n      \"#9338: 97.63%\\n\",\n      \"#9339: 97.63%\\n\",\n      \"#9340: 97.63%\\n\",\n      \"#9341: 97.63%\\n\",\n      \"#9342: 97.63%\\n\",\n      \"#9343: 97.63%\\n\",\n      \"#9344: 97.64%\\n\",\n      \"#9345: 97.64%\\n\",\n      \"#9346: 97.64%\\n\",\n      \"#9347: 97.64%\\n\",\n      \"#9348: 97.64%\\n\",\n      \"#9349: 97.64%\\n\",\n      \"#9350: 97.64%\\n\",\n      \"#9351: 97.64%\\n\",\n      \"#9352: 97.64%\\n\",\n      \"#9353: 97.64%\\n\",\n      \"#9354: 97.64%\\n\",\n      \"#9355: 97.64%\\n\",\n      \"#9356: 97.64%\\n\",\n      \"#9357: 97.64%\\n\",\n      \"#9358: 97.64%\\n\",\n      \"#9359: 97.64%\\n\",\n      \"#9360: 97.64%\\n\",\n      \"#9361: 97.64%\\n\",\n      \"#9362: 97.64%\\n\",\n      \"#9363: 97.64%\\n\",\n      \"#9364: 97.64%\\n\",\n      \"#9365: 97.64%\\n\",\n      \"#9366: 97.64%\\n\",\n      \"#9367: 97.64%\\n\",\n      \"#9368: 97.64%\\n\",\n      \"#9369: 97.64%\\n\",\n      \"#9370: 97.64%\\n\",\n      \"#9371: 97.64%\\n\",\n      \"#9372: 97.64%\\n\",\n      \"#9373: 97.64%\\n\",\n      \"#9374: 97.64%\\n\",\n      \"#9375: 97.64%\\n\",\n      \"#9376: 97.64%\\n\",\n      \"#9377: 97.64%\\n\",\n      \"#9378: 97.64%\\n\",\n      \"#9379: 97.64%\\n\",\n      \"#9380: 97.64%\\n\",\n      \"#9381: 97.64%\\n\",\n      \"#9382: 97.64%\\n\",\n      \"#9383: 97.64%\\n\",\n      \"#9384: 97.65%\\n\",\n      \"#9385: 97.65%\\n\",\n      \"#9386: 97.65%\\n\",\n      \"#9387: 97.65%\\n\",\n      \"#9388: 97.65%\\n\",\n      \"#9389: 97.65%\\n\",\n      \"#9390: 97.65%\\n\",\n      \"#9391: 97.65%\\n\",\n      \"#9392: 97.65%\\n\",\n      \"#9393: 97.65%\\n\",\n      \"#9394: 97.65%\\n\",\n      \"#9395: 97.65%\\n\",\n      \"#9396: 97.65%\\n\",\n      \"#9397: 97.65%\\n\",\n      \"#9398: 97.65%\\n\",\n      \"#9399: 97.65%\\n\",\n      \"#9400: 97.65%\\n\",\n      \"#9401: 97.65%\\n\",\n      \"#9402: 97.65%\\n\",\n      \"#9403: 97.65%\\n\",\n      \"#9404: 97.65%\\n\",\n      \"#9405: 97.65%\\n\",\n      \"#9406: 97.65%\\n\",\n      \"#9407: 97.65%\\n\",\n      \"#9408: 97.65%\\n\",\n      \"#9409: 97.65%\\n\",\n      \"#9410: 97.65%\\n\",\n      \"#9411: 97.65%\\n\",\n      \"#9412: 97.65%\\n\",\n      \"#9413: 97.65%\\n\",\n      \"#9414: 97.65%\\n\",\n      \"#9415: 97.65%\\n\",\n      \"#9416: 97.65%\\n\",\n      \"#9417: 97.65%\\n\",\n      \"#9418: 97.65%\\n\",\n      \"#9419: 97.65%\\n\",\n      \"#9420: 97.65%\\n\",\n      \"#9421: 97.65%\\n\",\n      \"#9422: 97.65%\\n\",\n      \"#9423: 97.65%\\n\",\n      \"#9424: 97.66%\\n\",\n      \"#9425: 97.66%\\n\",\n      \"#9426: 97.66%\\n\",\n      \"#9427: 97.66%\\n\",\n      \"#9428: 97.66%\\n\",\n      \"#9429: 97.66%\\n\",\n      \"#9430: 97.66%\\n\",\n      \"#9431: 97.66%\\n\",\n      \"#9432: 97.66%\\n\",\n      \"#9433: 97.66%\\n\",\n      \"#9434: 97.66%\\n\",\n      \"#9435: 97.66%\\n\",\n      \"#9436: 97.66%\\n\",\n      \"#9437: 97.66%\\n\",\n      \"#9438: 97.66%\\n\",\n      \"#9439: 97.66%\\n\",\n      \"#9440: 97.66%\\n\",\n      \"#9441: 97.66%\\n\",\n      \"#9442: 97.66%\\n\",\n      \"#9443: 97.66%\\n\",\n      \"#9444: 97.66%\\n\",\n      \"#9445: 97.66%\\n\",\n      \"#9446: 97.66%\\n\",\n      \"#9447: 97.66%\\n\",\n      \"#9448: 97.66%\\n\",\n      \"#9449: 97.66%\\n\",\n      \"#9450: 97.66%\\n\",\n      \"#9451: 97.66%\\n\",\n      \"#9452: 97.66%\\n\",\n      \"#9453: 97.66%\\n\",\n      \"#9454: 97.66%\\n\",\n      \"#9455: 97.66%\\n\",\n      \"#9456: 97.66%\\n\",\n      \"#9457: 97.66%\\n\",\n      \"#9458: 97.66%\\n\",\n      \"#9459: 97.66%\\n\",\n      \"#9460: 97.66%\\n\",\n      \"#9461: 97.66%\\n\",\n      \"#9462: 97.66%\\n\",\n      \"#9463: 97.66%\\n\",\n      \"#9464: 97.67%\\n\",\n      \"#9465: 97.67%\\n\",\n      \"#9466: 97.67%\\n\",\n      \"#9467: 97.67%\\n\",\n      \"#9468: 97.67%\\n\",\n      \"#9469: 97.67%\\n\",\n      \"#9470: 97.67%\\n\",\n      \"#9471: 97.67%\\n\",\n      \"#9472: 97.67%\\n\",\n      \"#9473: 97.67%\\n\",\n      \"#9474: 97.67%\\n\",\n      \"#9475: 97.67%\\n\",\n      \"#9476: 97.67%\\n\",\n      \"#9477: 97.67%\\n\",\n      \"#9478: 97.67%\\n\",\n      \"#9479: 97.67%\\n\",\n      \"#9480: 97.67%\\n\",\n      \"#9481: 97.67%\\n\",\n      \"#9482: 97.67%\\n\",\n      \"#9483: 97.67%\\n\",\n      \"#9484: 97.67%\\n\",\n      \"#9485: 97.67%\\n\",\n      \"#9486: 97.67%\\n\",\n      \"#9487: 97.67%\\n\",\n      \"#9488: 97.67%\\n\",\n      \"#9489: 97.67%\\n\",\n      \"#9490: 97.67%\\n\",\n      \"#9491: 97.67%\\n\",\n      \"#9492: 97.67%\\n\",\n      \"#9493: 97.67%\\n\",\n      \"#9494: 97.67%\\n\",\n      \"#9495: 97.67%\\n\",\n      \"#9496: 97.67%\\n\",\n      \"#9497: 97.67%\\n\",\n      \"#9498: 97.67%\\n\",\n      \"#9499: 97.67%\\n\",\n      \"#9500: 97.67%\\n\",\n      \"#9501: 97.67%\\n\",\n      \"#9502: 97.67%\\n\",\n      \"#9503: 97.67%\\n\",\n      \"#9504: 97.67%\\n\",\n      \"#9505: 97.68%\\n\",\n      \"#9506: 97.68%\\n\",\n      \"#9507: 97.68%\\n\",\n      \"#9508: 97.68%\\n\",\n      \"#9509: 97.68%\\n\",\n      \"#9510: 97.68%\\n\",\n      \"#9511: 97.68%\\n\",\n      \"#9512: 97.68%\\n\",\n      \"#9513: 97.68%\\n\",\n      \"#9514: 97.68%\\n\",\n      \"#9515: 97.68%\\n\",\n      \"#9516: 97.68%\\n\",\n      \"#9517: 97.68%\\n\",\n      \"#9518: 97.68%\\n\",\n      \"#9519: 97.68%\\n\",\n      \"#9520: 97.68%\\n\",\n      \"#9521: 97.68%\\n\",\n      \"#9522: 97.68%\\n\",\n      \"#9523: 97.68%\\n\",\n      \"#9524: 97.68%\\n\",\n      \"#9525: 97.68%\\n\",\n      \"#9526: 97.68%\\n\",\n      \"#9527: 97.68%\\n\",\n      \"#9528: 97.68%\\n\",\n      \"#9529: 97.68%\\n\",\n      \"#9530: 97.67%\\n\",\n      \"#9531: 97.67%\\n\",\n      \"#9532: 97.67%\\n\",\n      \"#9533: 97.67%\\n\",\n      \"#9534: 97.67%\\n\",\n      \"#9535: 97.67%\\n\",\n      \"#9536: 97.67%\\n\",\n      \"#9537: 97.67%\\n\",\n      \"#9538: 97.67%\\n\",\n      \"#9539: 97.67%\\n\",\n      \"#9540: 97.66%\\n\",\n      \"#9541: 97.66%\\n\",\n      \"#9542: 97.66%\\n\",\n      \"#9543: 97.66%\\n\",\n      \"#9544: 97.66%\\n\",\n      \"#9545: 97.66%\\n\",\n      \"#9546: 97.66%\\n\",\n      \"#9547: 97.66%\\n\",\n      \"#9548: 97.66%\\n\",\n      \"#9549: 97.66%\\n\",\n      \"#9550: 97.67%\\n\",\n      \"#9551: 97.67%\\n\",\n      \"#9552: 97.67%\\n\",\n      \"#9553: 97.67%\\n\",\n      \"#9554: 97.67%\\n\",\n      \"#9555: 97.67%\\n\",\n      \"#9556: 97.67%\\n\",\n      \"#9557: 97.67%\\n\",\n      \"#9558: 97.67%\\n\",\n      \"#9559: 97.67%\\n\",\n      \"#9560: 97.67%\\n\",\n      \"#9561: 97.67%\\n\",\n      \"#9562: 97.67%\\n\",\n      \"#9563: 97.67%\\n\",\n      \"#9564: 97.67%\\n\",\n      \"#9565: 97.67%\\n\",\n      \"#9566: 97.67%\\n\",\n      \"#9567: 97.67%\\n\",\n      \"#9568: 97.67%\\n\",\n      \"#9569: 97.67%\\n\",\n      \"#9570: 97.67%\\n\",\n      \"#9571: 97.67%\\n\",\n      \"#9572: 97.67%\\n\",\n      \"#9573: 97.67%\\n\",\n      \"#9574: 97.67%\\n\",\n      \"#9575: 97.67%\\n\",\n      \"#9576: 97.67%\\n\",\n      \"#9577: 97.67%\\n\",\n      \"#9578: 97.67%\\n\",\n      \"#9579: 97.67%\\n\",\n      \"#9580: 97.67%\\n\",\n      \"#9581: 97.67%\\n\",\n      \"#9582: 97.67%\\n\",\n      \"#9583: 97.67%\\n\",\n      \"#9584: 97.67%\\n\",\n      \"#9585: 97.67%\\n\",\n      \"#9586: 97.67%\\n\",\n      \"#9587: 97.66%\\n\",\n      \"#9588: 97.66%\\n\",\n      \"#9589: 97.66%\\n\",\n      \"#9590: 97.66%\\n\",\n      \"#9591: 97.66%\\n\",\n      \"#9592: 97.66%\\n\",\n      \"#9593: 97.67%\\n\",\n      \"#9594: 97.67%\\n\",\n      \"#9595: 97.67%\\n\",\n      \"#9596: 97.67%\\n\",\n      \"#9597: 97.67%\\n\",\n      \"#9598: 97.67%\\n\",\n      \"#9599: 97.67%\\n\",\n      \"#9600: 97.67%\\n\",\n      \"#9601: 97.67%\\n\",\n      \"#9602: 97.67%\\n\",\n      \"#9603: 97.67%\\n\",\n      \"#9604: 97.67%\\n\",\n      \"#9605: 97.67%\\n\",\n      \"#9606: 97.67%\\n\",\n      \"#9607: 97.67%\\n\",\n      \"#9608: 97.67%\\n\",\n      \"#9609: 97.67%\\n\",\n      \"#9610: 97.67%\\n\",\n      \"#9611: 97.67%\\n\",\n      \"#9612: 97.67%\\n\",\n      \"#9613: 97.67%\\n\",\n      \"#9614: 97.66%\\n\",\n      \"#9615: 97.66%\\n\",\n      \"#9616: 97.66%\\n\",\n      \"#9617: 97.66%\\n\",\n      \"#9618: 97.66%\\n\",\n      \"#9619: 97.66%\\n\",\n      \"#9620: 97.66%\\n\",\n      \"#9621: 97.66%\\n\",\n      \"#9622: 97.66%\\n\",\n      \"#9623: 97.66%\\n\",\n      \"#9624: 97.66%\\n\",\n      \"#9625: 97.66%\\n\",\n      \"#9626: 97.66%\\n\",\n      \"#9627: 97.66%\\n\",\n      \"#9628: 97.66%\\n\",\n      \"#9629: 97.66%\\n\",\n      \"#9630: 97.66%\\n\",\n      \"#9631: 97.66%\\n\",\n      \"#9632: 97.66%\\n\",\n      \"#9633: 97.66%\\n\",\n      \"#9634: 97.66%\\n\",\n      \"#9635: 97.67%\\n\",\n      \"#9636: 97.67%\\n\",\n      \"#9637: 97.67%\\n\",\n      \"#9638: 97.67%\\n\",\n      \"#9639: 97.67%\\n\",\n      \"#9640: 97.67%\\n\",\n      \"#9641: 97.67%\\n\",\n      \"#9642: 97.66%\\n\",\n      \"#9643: 97.66%\\n\",\n      \"#9644: 97.66%\\n\",\n      \"#9645: 97.66%\\n\",\n      \"#9646: 97.66%\\n\",\n      \"#9647: 97.66%\\n\",\n      \"#9648: 97.66%\\n\",\n      \"#9649: 97.66%\\n\",\n      \"#9650: 97.66%\\n\",\n      \"#9651: 97.66%\\n\",\n      \"#9652: 97.66%\\n\",\n      \"#9653: 97.66%\\n\",\n      \"#9654: 97.66%\\n\",\n      \"#9655: 97.66%\\n\",\n      \"#9656: 97.66%\\n\",\n      \"#9657: 97.66%\\n\",\n      \"#9658: 97.66%\\n\",\n      \"#9659: 97.66%\\n\",\n      \"#9660: 97.66%\\n\",\n      \"#9661: 97.66%\\n\",\n      \"#9662: 97.66%\\n\",\n      \"#9663: 97.66%\\n\",\n      \"#9664: 97.66%\\n\",\n      \"#9665: 97.66%\\n\",\n      \"#9666: 97.66%\\n\",\n      \"#9667: 97.66%\\n\",\n      \"#9668: 97.66%\\n\",\n      \"#9669: 97.66%\\n\",\n      \"#9670: 97.66%\\n\",\n      \"#9671: 97.66%\\n\",\n      \"#9672: 97.66%\\n\",\n      \"#9673: 97.66%\\n\",\n      \"#9674: 97.66%\\n\",\n      \"#9675: 97.66%\\n\",\n      \"#9676: 97.66%\\n\",\n      \"#9677: 97.66%\\n\",\n      \"#9678: 97.67%\\n\",\n      \"#9679: 97.67%\\n\",\n      \"#9680: 97.67%\\n\",\n      \"#9681: 97.67%\\n\",\n      \"#9682: 97.67%\\n\",\n      \"#9683: 97.67%\\n\",\n      \"#9684: 97.67%\\n\",\n      \"#9685: 97.67%\\n\",\n      \"#9686: 97.67%\\n\",\n      \"#9687: 97.67%\\n\",\n      \"#9688: 97.67%\\n\",\n      \"#9689: 97.67%\\n\",\n      \"#9690: 97.67%\\n\",\n      \"#9691: 97.67%\\n\",\n      \"#9692: 97.67%\\n\",\n      \"#9693: 97.67%\\n\",\n      \"#9694: 97.67%\\n\",\n      \"#9695: 97.67%\\n\",\n      \"#9696: 97.67%\\n\",\n      \"#9697: 97.67%\\n\",\n      \"#9698: 97.66%\\n\",\n      \"#9699: 97.66%\\n\",\n      \"#9700: 97.66%\\n\",\n      \"#9701: 97.66%\\n\",\n      \"#9702: 97.66%\\n\",\n      \"#9703: 97.66%\\n\",\n      \"#9704: 97.66%\\n\",\n      \"#9705: 97.66%\\n\",\n      \"#9706: 97.66%\\n\",\n      \"#9707: 97.66%\\n\",\n      \"#9708: 97.66%\\n\",\n      \"#9709: 97.66%\\n\",\n      \"#9710: 97.66%\\n\",\n      \"#9711: 97.66%\\n\",\n      \"#9712: 97.66%\\n\",\n      \"#9713: 97.66%\\n\",\n      \"#9714: 97.66%\\n\",\n      \"#9715: 97.66%\\n\",\n      \"#9716: 97.66%\\n\",\n      \"#9717: 97.66%\\n\",\n      \"#9718: 97.66%\\n\",\n      \"#9719: 97.66%\\n\",\n      \"#9720: 97.66%\\n\",\n      \"#9721: 97.67%\\n\",\n      \"#9722: 97.67%\\n\",\n      \"#9723: 97.67%\\n\",\n      \"#9724: 97.67%\\n\",\n      \"#9725: 97.67%\\n\",\n      \"#9726: 97.67%\\n\",\n      \"#9727: 97.67%\\n\",\n      \"#9728: 97.67%\\n\",\n      \"#9729: 97.66%\\n\",\n      \"#9730: 97.66%\\n\",\n      \"#9731: 97.66%\\n\",\n      \"#9732: 97.66%\\n\",\n      \"#9733: 97.66%\\n\",\n      \"#9734: 97.66%\\n\",\n      \"#9735: 97.66%\\n\",\n      \"#9736: 97.66%\\n\",\n      \"#9737: 97.66%\\n\",\n      \"#9738: 97.66%\\n\",\n      \"#9739: 97.66%\\n\",\n      \"#9740: 97.66%\\n\",\n      \"#9741: 97.66%\\n\",\n      \"#9742: 97.66%\\n\",\n      \"#9743: 97.66%\\n\",\n      \"#9744: 97.66%\\n\",\n      \"#9745: 97.65%\\n\",\n      \"#9746: 97.65%\\n\",\n      \"#9747: 97.65%\\n\",\n      \"#9748: 97.65%\\n\",\n      \"#9749: 97.65%\\n\",\n      \"#9750: 97.65%\\n\",\n      \"#9751: 97.65%\\n\",\n      \"#9752: 97.65%\\n\",\n      \"#9753: 97.65%\\n\",\n      \"#9754: 97.65%\\n\",\n      \"#9755: 97.65%\\n\",\n      \"#9756: 97.65%\\n\",\n      \"#9757: 97.65%\\n\",\n      \"#9758: 97.65%\\n\",\n      \"#9759: 97.65%\\n\",\n      \"#9760: 97.65%\\n\",\n      \"#9761: 97.65%\\n\",\n      \"#9762: 97.64%\\n\",\n      \"#9763: 97.64%\\n\",\n      \"#9764: 97.64%\\n\",\n      \"#9765: 97.64%\\n\",\n      \"#9766: 97.65%\\n\",\n      \"#9767: 97.65%\\n\",\n      \"#9768: 97.64%\\n\",\n      \"#9769: 97.64%\\n\",\n      \"#9770: 97.63%\\n\",\n      \"#9771: 97.63%\\n\",\n      \"#9772: 97.63%\\n\",\n      \"#9773: 97.63%\\n\",\n      \"#9774: 97.63%\\n\",\n      \"#9775: 97.63%\\n\",\n      \"#9776: 97.63%\\n\",\n      \"#9777: 97.63%\\n\",\n      \"#9778: 97.63%\\n\",\n      \"#9779: 97.63%\\n\",\n      \"#9780: 97.63%\\n\",\n      \"#9781: 97.63%\\n\",\n      \"#9782: 97.62%\\n\",\n      \"#9783: 97.62%\\n\",\n      \"#9784: 97.62%\\n\",\n      \"#9785: 97.62%\\n\",\n      \"#9786: 97.62%\\n\",\n      \"#9787: 97.62%\\n\",\n      \"#9788: 97.62%\\n\",\n      \"#9789: 97.62%\\n\",\n      \"#9790: 97.62%\\n\",\n      \"#9791: 97.62%\\n\",\n      \"#9792: 97.61%\\n\",\n      \"#9793: 97.61%\\n\",\n      \"#9794: 97.61%\\n\",\n      \"#9795: 97.61%\\n\",\n      \"#9796: 97.61%\\n\",\n      \"#9797: 97.61%\\n\",\n      \"#9798: 97.61%\\n\",\n      \"#9799: 97.61%\\n\",\n      \"#9800: 97.61%\\n\",\n      \"#9801: 97.61%\\n\",\n      \"#9802: 97.61%\\n\",\n      \"#9803: 97.61%\\n\",\n      \"#9804: 97.61%\\n\",\n      \"#9805: 97.61%\\n\",\n      \"#9806: 97.61%\\n\",\n      \"#9807: 97.61%\\n\",\n      \"#9808: 97.61%\\n\",\n      \"#9809: 97.61%\\n\",\n      \"#9810: 97.61%\\n\",\n      \"#9811: 97.60%\\n\",\n      \"#9812: 97.61%\\n\",\n      \"#9813: 97.61%\\n\",\n      \"#9814: 97.61%\\n\",\n      \"#9815: 97.61%\\n\",\n      \"#9816: 97.61%\\n\",\n      \"#9817: 97.61%\\n\",\n      \"#9818: 97.61%\\n\",\n      \"#9819: 97.61%\\n\",\n      \"#9820: 97.61%\\n\",\n      \"#9821: 97.61%\\n\",\n      \"#9822: 97.61%\\n\",\n      \"#9823: 97.61%\\n\",\n      \"#9824: 97.61%\\n\",\n      \"#9825: 97.61%\\n\",\n      \"#9826: 97.61%\\n\",\n      \"#9827: 97.61%\\n\",\n      \"#9828: 97.61%\\n\",\n      \"#9829: 97.61%\\n\",\n      \"#9830: 97.61%\\n\",\n      \"#9831: 97.61%\\n\",\n      \"#9832: 97.61%\\n\",\n      \"#9833: 97.61%\\n\",\n      \"#9834: 97.61%\\n\",\n      \"#9835: 97.61%\\n\",\n      \"#9836: 97.61%\\n\",\n      \"#9837: 97.61%\\n\",\n      \"#9838: 97.61%\\n\",\n      \"#9839: 97.60%\\n\",\n      \"#9840: 97.60%\\n\",\n      \"#9841: 97.60%\\n\",\n      \"#9842: 97.60%\\n\",\n      \"#9843: 97.60%\\n\",\n      \"#9844: 97.60%\\n\",\n      \"#9845: 97.60%\\n\",\n      \"#9846: 97.60%\\n\",\n      \"#9847: 97.60%\\n\",\n      \"#9848: 97.60%\\n\",\n      \"#9849: 97.60%\\n\",\n      \"#9850: 97.60%\\n\",\n      \"#9851: 97.60%\\n\",\n      \"#9852: 97.60%\\n\",\n      \"#9853: 97.61%\\n\",\n      \"#9854: 97.61%\\n\",\n      \"#9855: 97.61%\\n\",\n      \"#9856: 97.60%\\n\",\n      \"#9857: 97.60%\\n\",\n      \"#9858: 97.60%\\n\",\n      \"#9859: 97.60%\\n\",\n      \"#9860: 97.60%\\n\",\n      \"#9861: 97.60%\\n\",\n      \"#9862: 97.60%\\n\",\n      \"#9863: 97.60%\\n\",\n      \"#9864: 97.60%\\n\",\n      \"#9865: 97.60%\\n\",\n      \"#9866: 97.60%\\n\",\n      \"#9867: 97.59%\\n\",\n      \"#9868: 97.59%\\n\",\n      \"#9869: 97.59%\\n\",\n      \"#9870: 97.59%\\n\",\n      \"#9871: 97.59%\\n\",\n      \"#9872: 97.59%\\n\",\n      \"#9873: 97.59%\\n\",\n      \"#9874: 97.59%\\n\",\n      \"#9875: 97.59%\\n\",\n      \"#9876: 97.59%\\n\",\n      \"#9877: 97.59%\\n\",\n      \"#9878: 97.59%\\n\",\n      \"#9879: 97.59%\\n\",\n      \"#9880: 97.59%\\n\",\n      \"#9881: 97.59%\\n\",\n      \"#9882: 97.59%\\n\",\n      \"#9883: 97.59%\\n\",\n      \"#9884: 97.59%\\n\",\n      \"#9885: 97.59%\\n\",\n      \"#9886: 97.59%\\n\",\n      \"#9887: 97.59%\\n\",\n      \"#9888: 97.59%\\n\",\n      \"#9889: 97.59%\\n\",\n      \"#9890: 97.59%\\n\",\n      \"#9891: 97.59%\\n\",\n      \"#9892: 97.58%\\n\",\n      \"#9893: 97.57%\\n\",\n      \"#9894: 97.57%\\n\",\n      \"#9895: 97.57%\\n\",\n      \"#9896: 97.58%\\n\",\n      \"#9897: 97.58%\\n\",\n      \"#9898: 97.58%\\n\",\n      \"#9899: 97.58%\\n\",\n      \"#9900: 97.58%\\n\",\n      \"#9901: 97.58%\\n\",\n      \"#9902: 97.58%\\n\",\n      \"#9903: 97.58%\\n\",\n      \"#9904: 97.58%\\n\",\n      \"#9905: 97.57%\\n\",\n      \"#9906: 97.57%\\n\",\n      \"#9907: 97.57%\\n\",\n      \"#9908: 97.57%\\n\",\n      \"#9909: 97.57%\\n\",\n      \"#9910: 97.57%\\n\",\n      \"#9911: 97.57%\\n\",\n      \"#9912: 97.57%\\n\",\n      \"#9913: 97.57%\\n\",\n      \"#9914: 97.57%\\n\",\n      \"#9915: 97.57%\\n\",\n      \"#9916: 97.57%\\n\",\n      \"#9917: 97.57%\\n\",\n      \"#9918: 97.57%\\n\",\n      \"#9919: 97.57%\\n\",\n      \"#9920: 97.57%\\n\",\n      \"#9921: 97.57%\\n\",\n      \"#9922: 97.57%\\n\",\n      \"#9923: 97.57%\\n\",\n      \"#9924: 97.57%\\n\",\n      \"#9925: 97.57%\\n\",\n      \"#9926: 97.57%\\n\",\n      \"#9927: 97.57%\\n\",\n      \"#9928: 97.57%\\n\",\n      \"#9929: 97.57%\\n\",\n      \"#9930: 97.57%\\n\",\n      \"#9931: 97.57%\\n\",\n      \"#9932: 97.57%\\n\",\n      \"#9933: 97.57%\\n\",\n      \"#9934: 97.57%\\n\",\n      \"#9935: 97.57%\\n\",\n      \"#9936: 97.57%\\n\",\n      \"#9937: 97.57%\\n\",\n      \"#9938: 97.58%\\n\",\n      \"#9939: 97.58%\\n\",\n      \"#9940: 97.58%\\n\",\n      \"#9941: 97.58%\\n\",\n      \"#9942: 97.57%\\n\",\n      \"#9943: 97.57%\\n\",\n      \"#9944: 97.57%\\n\",\n      \"#9945: 97.57%\\n\",\n      \"#9946: 97.57%\\n\",\n      \"#9947: 97.57%\\n\",\n      \"#9948: 97.57%\\n\",\n      \"#9949: 97.57%\\n\",\n      \"#9950: 97.57%\\n\",\n      \"#9951: 97.57%\\n\",\n      \"#9952: 97.57%\\n\",\n      \"#9953: 97.57%\\n\",\n      \"#9954: 97.57%\\n\",\n      \"#9955: 97.57%\\n\",\n      \"#9956: 97.57%\\n\",\n      \"#9957: 97.57%\\n\",\n      \"#9958: 97.57%\\n\",\n      \"#9959: 97.57%\\n\",\n      \"#9960: 97.57%\\n\",\n      \"#9961: 97.57%\\n\",\n      \"#9962: 97.57%\\n\",\n      \"#9963: 97.57%\\n\",\n      \"#9964: 97.57%\\n\",\n      \"#9965: 97.57%\\n\",\n      \"#9966: 97.57%\\n\",\n      \"#9967: 97.57%\\n\",\n      \"#9968: 97.57%\\n\",\n      \"#9969: 97.57%\\n\",\n      \"#9970: 97.57%\\n\",\n      \"#9971: 97.57%\\n\",\n      \"#9972: 97.57%\\n\",\n      \"#9973: 97.57%\\n\",\n      \"#9974: 97.57%\\n\",\n      \"#9975: 97.57%\\n\",\n      \"#9976: 97.57%\\n\",\n      \"#9977: 97.57%\\n\",\n      \"#9978: 97.57%\\n\",\n      \"#9979: 97.58%\\n\",\n      \"#9980: 97.58%\\n\",\n      \"#9981: 97.58%\\n\",\n      \"#9982: 97.57%\\n\",\n      \"#9983: 97.57%\\n\",\n      \"#9984: 97.57%\\n\",\n      \"#9985: 97.57%\\n\",\n      \"#9986: 97.57%\\n\",\n      \"#9987: 97.57%\\n\",\n      \"#9988: 97.57%\\n\",\n      \"#9989: 97.57%\\n\",\n      \"#9990: 97.57%\\n\",\n      \"#9991: 97.57%\\n\",\n      \"#9992: 97.57%\\n\",\n      \"#9993: 97.57%\\n\",\n      \"#9994: 97.57%\\n\",\n      \"#9995: 97.57%\\n\",\n      \"#9996: 97.57%\\n\",\n      \"#9997: 97.57%\\n\",\n      \"#9998: 97.57%\\n\",\n      \"#9999: 97.57%\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"correct = 0\\n\",\n    \"for i in range(10000):\\n\",\n    \"    with open(f\\\"X_test/{i}.json\\\", \\\"r\\\") as f:\\n\",\n    \"        input = json.load(f)\\n\",\n    \"    out, _ = inference(input, circuit)\\n\",\n    \"    correct += 1 if out[0] == y_test[i] else 0\\n\",\n    \"    print(f\\\"#{i}: {correct / (i + 1) * 100:.2f}%\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "test/circuit.js",
        "content": "const chai = require('chai');\nconst fs = require('fs');\n\nconst wasm_tester = require('circom_tester').wasm;\n\nconst F1Field = require('ffjavascript').F1Field;\nconst Scalar = require('ffjavascript').Scalar;\nexports.p = Scalar.fromString('21888242871839275222246405745257275088548364400416034343698204186575808495617');\nconst Fr = new F1Field(exports.p);\n\nconst assert = chai.assert;\n\nconst exec = require('await-exec');\n\nconst input = require('../test/X_test/0.json');\n\ndescribe('keras2circom test', function () {\n    this.timeout(100000000);\n\n    describe('softmax output', async () => {\n        it('softmax output test', async () => {\n            await exec('python main.py models/model.h5 && python output/circuit.py output/circuit.json test/X_test/0.json');\n\n            const model = JSON.parse(fs.readFileSync('./output/circuit.json'));\n            const output = JSON.parse(fs.readFileSync('./output/output.json'));\n\n            const INPUT = {...model, ...input, ...output};\n\n            const circuit = await wasm_tester('./output/circuit.circom');\n            const witness = await circuit.calculateWitness(INPUT, true);\n            assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n            assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));\n        });\n    });\n\n    describe('raw output', async () => {\n        it('raw output test', async () => {\n            await exec('python main.py models/model.h5 --raw && python output/circuit.py output/circuit.json test/X_test/0.json');\n\n            const model = JSON.parse(fs.readFileSync('./output/circuit.json'));\n            const output = JSON.parse(fs.readFileSync('./output/output.json'));\n\n            const INPUT = {...model, ...input, ...output};\n\n            const circuit = await wasm_tester('./output/circuit.circom');\n            const witness = await circuit.calculateWitness(INPUT, true);\n            assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));\n        });\n    });\n});"
    },
    {
        "repo": "https://github.com/Modulus-Labs/RockyBothttps://github.com/ora-io/keras2circom",
        "file_path": "test/load_input.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow.keras.datasets import mnist\\n\",\n    \"import json\\n\",\n    \"import numpy as np\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# load MNIST dataset\\n\",\n    \"_, (X_test, y_test) = mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#normalizing\\n\",\n    \"X_test = X_test.astype('float32')\\n\",\n    \"X_test /= 255.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"for i in range(len(X_test)):\\n\",\n    \"    X = [str(int(x * float(10**18))) for x in X_test[i].flatten().tolist()]\\n\",\n    \"    X = np.array(X).reshape(28, 28, 1).tolist()\\n\",\n    \"    with open(f'X_test/{i}.json', 'w') as f:\\n\",\n    \"        json.dump({\\\"in\\\": X}, f)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open('y_test.json', 'w') as f:\\n\",\n    \"    json.dump(y_test.tolist(), f)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/cma/cma.h",
        "content": "/* cma.h\n *\n * The MIT License (MIT)\n *\n * COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia.\n * AUTHOR: Rihards Novickis (rihards.novickis@edi.lv)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifndef VTA_DE10_NANO_KERNEL_MODULE_CMA_H_\n#define VTA_DE10_NANO_KERNEL_MODULE_CMA_H_\n\n/* Should be defined in settings.mk file */\n#ifndef CMA_IOCTL_MAGIC\n#define CMA_IOCTL_MAGIC 0xf2\n#endif\n\n#define CMA_ALLOC_CACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 1, 4)\n#define CMA_ALLOC_NONCACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 2, 4)\n#define CMA_FREE _IOC(_IOC_WRITE, CMA_IOCTL_MAGIC, 3, 4)\n#define CMA_GET_PHY_ADDR _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 4, 4)\n#define CMA_GET_SIZE _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 5, 4)\n\n#define CMA_IOCTL_MAXNR 5\n\n#endif  // VTA_DE10_NANO_KERNEL_MODULE_CMA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/cma/cma_api_impl.h",
        "content": "/*\n * The MIT License (MIT)\n *\n * COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia.\n * AUTHOR: Rihards Novickis (rihards.novickis@edi.lv)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n */\n\n/*!\n *  Copyright (c) 2018 by Contributors\n * \\file cma_api.cc\n * \\brief Application layer implementation for contigous memory allocation.\n */\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n#include \"cma_api.h\"\n\n#ifndef CMA_IOCTL_MAGIC\n#define CMA_IOCTL_MAGIC 0xf2\n#endif\n\n#define CMA_ALLOC_CACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 1, 4)\n#define CMA_ALLOC_NONCACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 2, 4)\n#define CMA_FREE _IOC(_IOC_WRITE, CMA_IOCTL_MAGIC, 3, 4)\n#define CMA_GET_PHY_ADDR _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 4, 4)\n#define CMA_GET_SIZE _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 5, 4)\n\n#define CMA_IOCTL_MAXNR 5\n\n#ifndef CMA_DEBUG\n#define CMA_DEBUG 0\n#endif\n#ifndef DRIVER_NODE_NAME\n#define DRIVER_NODE_NAME \"cma\"\n#endif\n\n#if CMA_DEBUG == 1\n#define __DEBUG(fmt, args...) printf(\"CMA_API_DEBUG: \" fmt, ##args)\n#else\n#define __DEBUG(fmt, args...)\n#endif\n\n#define ROUND_UP(N, S) ((((N) + (S)-1) / (S)) * (S))\n\n/* Private functions */\nvoid* cma_alloc(size_t size, unsigned ioctl_cmd);\n\n/* Global file descriptor */\nint cma_fd = 0;\n\nint cma_init(void) {\n  __DEBUG(\"Opening \\\"/dev/\" DRIVER_NODE_NAME \"\\\" file\\n\");\n\n  cma_fd = open(\"/dev/\" DRIVER_NODE_NAME, O_RDWR);\n  if (cma_fd == -1) {\n    __DEBUG(\"Failed to initialize api - \\\"%s\\\"\\n\", strerror(errno));\n    return -1;\n  }\n\n  return 0;\n}\n\nint cma_release(void) {\n  __DEBUG(\"Closing \\\"/dev/\" DRIVER_NODE_NAME \"\\\" file\\n\");\n\n  if (close(cma_fd) == -1) {\n    __DEBUG(\"Failed to finilize api - \\\"%s\\\"\\n\", strerror(errno));\n    return -1;\n  }\n\n  return 0;\n}\n\nvoid* cma_alloc_cached(size_t size) { return cma_alloc(size, CMA_ALLOC_CACHED); }\n\nvoid* cma_alloc_noncached(size_t size) { return cma_alloc(size, CMA_ALLOC_NONCACHED); }\n\nint cma_free(void* mem) {\n  __DEBUG(\"Releasing contigous memory from 0x%x\\n\", (unsigned)mem);\n  unsigned data, v_addr;\n\n  /* save user space pointer value */\n  data = (unsigned)mem;\n  v_addr = (unsigned)mem;\n\n  if (ioctl(cma_fd, CMA_GET_SIZE, &data) == -1) {\n    __DEBUG(\"cma_free - ioctl command unsuccsessful - 0\\n\");\n    return -1;\n  }\n  /* data now contains size */\n\n  /* unmap memory */\n  munmap(mem, data);\n\n  /* free cma entry */\n  if (ioctl(cma_fd, CMA_FREE, &v_addr) == -1) {\n    __DEBUG(\"cma_free - ioctl command unsuccsessful - 1\\n\");\n    return -1;\n  }\n\n  return 0;\n}\n\nunsigned cma_get_phy_addr(void* mem) {\n  unsigned data;\n  __DEBUG(\"Getting physical address from 0x%x\\n\", (unsigned)mem);\n\n  /* save user space pointer value */\n  data = (unsigned)mem;\n\n  /* get physical address */\n  if (ioctl(cma_fd, CMA_GET_PHY_ADDR, &data) == -1) {\n    __DEBUG(\"cma_free - ioctl command unsuccsessful\\n\");\n    return 0;\n  }\n  /* data now contains physical address */\n\n  return data;\n}\n\nvoid* cma_alloc(size_t size, unsigned ioctl_cmd) {\n  unsigned data;\n  void* mem;\n  __DEBUG(\"Allocating 0x%x bytes of contigous memory\\n\", size);\n\n  /* Page align size */\n  size = ROUND_UP(size, getpagesize());\n\n  /* ioctl cmd to allocate contigous memory */\n  data = (unsigned)size;\n  if (ioctl(cma_fd, ioctl_cmd, &data) == -1) {\n    __DEBUG(\"cma_alloc - ioctl command unsuccsessful\\n\");\n    return NULL;\n  }\n\n  /* at this point phy_addr is written to data */\n\n  /* mmap memory */\n  mem = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, cma_fd, data);\n  if (mem == MAP_FAILED) {\n    __DEBUG(\"cma_alloc - mmap unsuccsessful\\n\");\n    return NULL;\n  }\n\n  return mem;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/compiler-rt/builtin_fp16.h",
        "content": "/*\n * Copyright (c) 2009-2015 by llvm/compiler-rt contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n * \\file builtin_fp16.h\n * \\brief Functions for conversion between fp32 and fp16, adopted from compiler-rt.\n */\n#ifndef COMPILER_RT_BUILTIN_FP16_H_\n#define COMPILER_RT_BUILTIN_FP16_H_\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4305 4805)\n#endif\n\n#include <cstdint>\n\nstatic inline uint32_t __clz(uint32_t x) {\n  // count leading zeros\n  int n = 32;\n  uint32_t y;\n\n  y = x >> 16;\n  if (y) {\n    n = n - 16;\n    x = y;\n  }\n  y = x >> 8;\n  if (y) {\n    n = n - 8;\n    x = y;\n  }\n  y = x >> 4;\n  if (y) {\n    n = n - 4;\n    x = y;\n  }\n  y = x >> 2;\n  if (y) {\n    n = n - 2;\n    x = y;\n  }\n  y = x >> 1;\n  if (y) return n - 2;\n  return n - x;\n}\n\ntemplate <typename SRC_T, typename SRC_REP_T, int SRC_SIG_BITS, typename DST_T, typename DST_REP_T,\n          int DST_SIG_BITS>\nstatic inline DST_T __truncXfYf2__(SRC_T a) {\n  // Various constants whose values follow from the type parameters.\n  // Any reasonable optimizer will fold and propagate all of these.\n  const int srcBits = sizeof(SRC_T) * 8;\n  const int srcExpBits = srcBits - SRC_SIG_BITS - 1;\n  const int srcInfExp = (1 << srcExpBits) - 1;\n  const int srcExpBias = srcInfExp >> 1;\n\n  const SRC_REP_T srcMinNormal = SRC_REP_T(1) << SRC_SIG_BITS;\n  const SRC_REP_T srcSignificandMask = srcMinNormal - 1;\n  const SRC_REP_T srcInfinity = (SRC_REP_T)srcInfExp << SRC_SIG_BITS;\n  const SRC_REP_T srcSignMask = SRC_REP_T(1) << (SRC_SIG_BITS + srcExpBits);\n  const SRC_REP_T srcAbsMask = srcSignMask - 1;\n  const SRC_REP_T roundMask = (SRC_REP_T(1) << (SRC_SIG_BITS - DST_SIG_BITS)) - 1;\n  const SRC_REP_T halfway = SRC_REP_T(1) << (SRC_SIG_BITS - DST_SIG_BITS - 1);\n  const SRC_REP_T srcQNaN = SRC_REP_T(1) << (SRC_SIG_BITS - 1);\n  const SRC_REP_T srcNaNCode = srcQNaN - 1;\n\n  const int dstBits = sizeof(DST_T) * 8;\n  const int dstExpBits = dstBits - DST_SIG_BITS - 1;\n  const int dstInfExp = (1 << dstExpBits) - 1;\n  const int dstExpBias = dstInfExp >> 1;\n\n  const int underflowExponent = srcExpBias + 1 - dstExpBias;\n  const int overflowExponent = srcExpBias + dstInfExp - dstExpBias;\n  const SRC_REP_T underflow = (SRC_REP_T)underflowExponent << SRC_SIG_BITS;\n  const SRC_REP_T overflow = (SRC_REP_T)overflowExponent << SRC_SIG_BITS;\n\n  const DST_REP_T dstQNaN = DST_REP_T(1) << (DST_SIG_BITS - 1);\n  const DST_REP_T dstNaNCode = dstQNaN - 1;\n\n  // Break a into a sign and representation of the absolute value\n  union SrcExchangeType {\n    SRC_T f;\n    SRC_REP_T i;\n  };\n  SrcExchangeType src_rep;\n  src_rep.f = a;\n  const SRC_REP_T aRep = src_rep.i;\n  const SRC_REP_T aAbs = aRep & srcAbsMask;\n  const SRC_REP_T sign = aRep & srcSignMask;\n  DST_REP_T absResult;\n\n  if (aAbs - underflow < aAbs - overflow) {\n    // The exponent of a is within the range of normal numbers in the\n    // destination format.  We can convert by simply right-shifting with\n    // rounding and adjusting the exponent.\n    absResult = aAbs >> (SRC_SIG_BITS - DST_SIG_BITS);\n    absResult -= (DST_REP_T)(srcExpBias - dstExpBias) << DST_SIG_BITS;\n\n    const SRC_REP_T roundBits = aAbs & roundMask;\n    // Round to nearest\n    if (roundBits > halfway) absResult++;\n    // Ties to even\n    else if (roundBits == halfway)\n      absResult += absResult & 1;\n  } else if (aAbs > srcInfinity) {\n    // a is NaN.\n    // Conjure the result by beginning with infinity, setting the qNaN\n    // bit and inserting the (truncated) trailing NaN field.\n    absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;\n    absResult |= dstQNaN;\n    absResult |= ((aAbs & srcNaNCode) >> (SRC_SIG_BITS - DST_SIG_BITS)) & dstNaNCode;\n  } else if (aAbs >= overflow) {\n    // a overflows to infinity.\n    absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;\n  } else {\n    // a underflows on conversion to the destination type or is an exact\n    // zero.  The result may be a denormal or zero.  Extract the exponent\n    // to get the shift amount for the denormalization.\n    const int aExp = aAbs >> SRC_SIG_BITS;\n    const int shift = srcExpBias - dstExpBias - aExp + 1;\n\n    const SRC_REP_T significand = (aRep & srcSignificandMask) | srcMinNormal;\n\n    // Right shift by the denormalization amount with sticky.\n    if (shift > SRC_SIG_BITS) {\n      absResult = 0;\n    } else {\n      const bool sticky = significand << (srcBits - shift);\n      SRC_REP_T denormalizedSignificand = significand >> shift | sticky;\n      absResult = denormalizedSignificand >> (SRC_SIG_BITS - DST_SIG_BITS);\n      const SRC_REP_T roundBits = denormalizedSignificand & roundMask;\n      // Round to nearest\n      if (roundBits > halfway) absResult++;\n      // Ties to even\n      else if (roundBits == halfway)\n        absResult += absResult & 1;\n    }\n  }\n\n  // Apply the signbit to (DST_T)abs(a).\n  const DST_REP_T result = absResult | sign >> (srcBits - dstBits);\n  union DstExchangeType {\n    DST_T f;\n    DST_REP_T i;\n  };\n  DstExchangeType dst_rep;\n  dst_rep.i = result;\n  return dst_rep.f;\n}\n\ntemplate <typename SRC_T, typename SRC_REP_T, int SRC_SIG_BITS, typename DST_T, typename DST_REP_T,\n          int DST_SIG_BITS>\nstatic inline DST_T __extendXfYf2__(SRC_T a) {\n  // Various constants whose values follow from the type parameters.\n  // Any reasonable optimizer will fold and propagate all of these.\n  const int srcBits = sizeof(SRC_T) * 8;\n  const int srcExpBits = srcBits - SRC_SIG_BITS - 1;\n  const int srcInfExp = (1 << srcExpBits) - 1;\n  const int srcExpBias = srcInfExp >> 1;\n\n  const SRC_REP_T srcMinNormal = SRC_REP_T(1) << SRC_SIG_BITS;\n  const SRC_REP_T srcInfinity = (SRC_REP_T)srcInfExp << SRC_SIG_BITS;\n  const SRC_REP_T srcSignMask = SRC_REP_T(1) << (SRC_SIG_BITS + srcExpBits);\n  const SRC_REP_T srcAbsMask = srcSignMask - 1;\n  const SRC_REP_T srcQNaN = SRC_REP_T(1) << (SRC_SIG_BITS - 1);\n  const SRC_REP_T srcNaNCode = srcQNaN - 1;\n\n  const int dstBits = sizeof(DST_T) * 8;\n  const int dstExpBits = dstBits - DST_SIG_BITS - 1;\n  const int dstInfExp = (1 << dstExpBits) - 1;\n  const int dstExpBias = dstInfExp >> 1;\n\n  const DST_REP_T dstMinNormal = DST_REP_T(1) << DST_SIG_BITS;\n\n  // Break a into a sign and representation of the absolute value\n  union SrcExchangeType {\n    SRC_T f;\n    SRC_REP_T i;\n  };\n  SrcExchangeType src_rep;\n  src_rep.f = a;\n  const SRC_REP_T aRep = src_rep.i;\n  const SRC_REP_T aAbs = aRep & srcAbsMask;\n  const SRC_REP_T sign = aRep & srcSignMask;\n  DST_REP_T absResult;\n\n  // If sizeof(SRC_REP_T) < sizeof(int), the subtraction result is promoted\n  // to (signed) int.  To avoid that, explicitly cast to SRC_REP_T.\n  if ((SRC_REP_T)(aAbs - srcMinNormal) < srcInfinity - srcMinNormal) {\n    // a is a normal number.\n    // Extend to the destination type by shifting the significand and\n    // exponent into the proper position and rebiasing the exponent.\n    absResult = (DST_REP_T)aAbs << (DST_SIG_BITS - SRC_SIG_BITS);\n    absResult += (DST_REP_T)(dstExpBias - srcExpBias) << DST_SIG_BITS;\n  }\n\n  else if (aAbs >= srcInfinity) {\n    // a is NaN or infinity.\n    // Conjure the result by beginning with infinity, then setting the qNaN\n    // bit (if needed) and right-aligning the rest of the trailing NaN\n    // payload field.\n    absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;\n    absResult |= (DST_REP_T)(aAbs & srcQNaN) << (DST_SIG_BITS - SRC_SIG_BITS);\n    absResult |= (DST_REP_T)(aAbs & srcNaNCode) << (DST_SIG_BITS - SRC_SIG_BITS);\n  } else if (aAbs) {\n    // a is denormal.\n    // renormalize the significand and clear the leading bit, then insert\n    // the correct adjusted exponent in the destination type.\n    const int scale = __clz(aAbs) - __clz(srcMinNormal);\n    absResult = (DST_REP_T)aAbs << (DST_SIG_BITS - SRC_SIG_BITS + scale);\n    absResult ^= dstMinNormal;\n    const int resultExponent = dstExpBias - srcExpBias - scale + 1;\n    absResult |= (DST_REP_T)resultExponent << DST_SIG_BITS;\n  } else {\n    // a is zero.\n    absResult = 0;\n  }\n\n  // Apply the signbit to (DST_T)abs(a).\n  const DST_REP_T result = absResult | (DST_REP_T)sign << (dstBits - srcBits);\n  union DstExchangeType {\n    DST_T f;\n    DST_REP_T i;\n  };\n  DstExchangeType dst_rep;\n  dst_rep.i = result;\n  return dst_rep.f;\n}\n\n#endif  // COMPILER_RT_BUILTIN_FP16_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/libcrc/include/checksum.h",
        "content": "/*\n * Library: libcrc\n * File:    include/checksum.h\n * Author:  Lammert Bies\n *\n * This file is licensed under the MIT License as stated below\n *\n * Copyright (c) 1999-2018 Lammert Bies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Description\n * -----------\n * The headerfile include/checksum.h contains the definitions and prototypes\n * for routines that can be used to calculate several kinds of checksums.\n */\n\n#ifndef DEF_LIBCRC_CHECKSUM_H\n#define DEF_LIBCRC_CHECKSUM_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n/*\n * #define CRC_POLY_xxxx\n *\n * The constants of the form CRC_POLY_xxxx define the polynomials for some well\n * known CRC calculations.\n */\n\n#define CRC_POLY_16 0xA001\n#define CRC_POLY_32 0xEDB88320ul\n#define CRC_POLY_64 0x42F0E1EBA9EA3693ull\n#define CRC_POLY_CCITT 0x1021\n#define CRC_POLY_DNP 0xA6BC\n#define CRC_POLY_KERMIT 0x8408\n#define CRC_POLY_SICK 0x8005\n\n/*\n * #define CRC_START_xxxx\n *\n * The constants of the form CRC_START_xxxx define the values that are used for\n * initialization of a CRC value for common used calculation methods.\n */\n\n#define CRC_START_8 0x00\n#define CRC_START_16 0x0000\n#define CRC_START_MODBUS 0xFFFF\n#define CRC_START_XMODEM 0x0000\n#define CRC_START_CCITT_1D0F 0x1D0F\n#define CRC_START_CCITT_FFFF 0xFFFF\n#define CRC_START_KERMIT 0x0000\n#define CRC_START_SICK 0x0000\n#define CRC_START_DNP 0x0000\n#define CRC_START_32 0xFFFFFFFFul\n#define CRC_START_64_ECMA 0x0000000000000000ull\n#define CRC_START_64_WE 0xFFFFFFFFFFFFFFFFull\n\n/*\n * Prototype list of global functions\n */\n\nunsigned char* checksum_NMEA(const unsigned char* input_str, unsigned char* result);\nuint8_t crc_8(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_16(const unsigned char* input_str, size_t num_bytes);\nuint32_t crc_32(const unsigned char* input_str, size_t num_bytes);\nuint64_t crc_64_ecma(const unsigned char* input_str, size_t num_bytes);\nuint64_t crc_64_we(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_ccitt_1d0f(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_ccitt_ffff(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_dnp(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_kermit(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_modbus(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_sick(const unsigned char* input_str, size_t num_bytes);\nuint16_t crc_xmodem(const unsigned char* input_str, size_t num_bytes);\nuint8_t update_crc_8(uint8_t crc, unsigned char c);\nuint16_t update_crc_16(uint16_t crc, unsigned char c);\nuint32_t update_crc_32(uint32_t crc, unsigned char c);\nuint64_t update_crc_64_ecma(uint64_t crc, unsigned char c);\nuint16_t update_crc_ccitt(uint16_t crc, unsigned char c);\nuint16_t update_crc_dnp(uint16_t crc, unsigned char c);\nuint16_t update_crc_kermit(uint16_t crc, unsigned char c);\nuint16_t update_crc_sick(uint16_t crc, unsigned char c, unsigned char prev_byte);\n\n/*\n * Global CRC lookup tables\n */\n\nextern const uint32_t crc_tab32[];\nextern const uint64_t crc_tab64[];\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // DEF_LIBCRC_CHECKSUM_H\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/libcrc/src/crcccitt.c",
        "content": "/*\n * Library: libcrc\n * File:    src/crcccitt.c\n * Author:  Lammert Bies\n *\n * This file is licensed under the MIT License as stated below\n *\n * Copyright (c) 1999-2016 Lammert Bies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Description\n * -----------\n * The module src/crcccitt.c contains routines which are used to calculate the\n * CCITT CRC values of a string of bytes.\n */\n\n#include <inttypes.h>\n#include <stdbool.h>\n#include <stdlib.h>\n\n#include \"../tab/gentab_ccitt.inc\"\n#include \"checksum.h\"\n\nstatic uint16_t crc_ccitt_generic(const unsigned char* input_str, size_t num_bytes,\n                                  uint16_t start_value);\n\n/*\n * uint16_t crc_xmodem( const unsigned char *input_str, size_t num_bytes );\n *\n * The function crc_xmodem() performs a one-pass calculation of an X-Modem CRC\n * for a byte string that has been passed as a parameter.\n */\n\nuint16_t crc_xmodem(const unsigned char* input_str, size_t num_bytes) {\n  return crc_ccitt_generic(input_str, num_bytes, CRC_START_XMODEM);\n\n} /* crc_xmodem */\n\n/*\n * uint16_t crc_ccitt_1d0f( const unsigned char *input_str, size_t num_bytes );\n *\n * The function crc_ccitt_1d0f() performs a one-pass calculation of the CCITT\n * CRC for a byte string that has been passed as a parameter. The initial value\n * 0x1d0f is used for the CRC.\n */\n\nuint16_t crc_ccitt_1d0f(const unsigned char* input_str, size_t num_bytes) {\n  return crc_ccitt_generic(input_str, num_bytes, CRC_START_CCITT_1D0F);\n\n} /* crc_ccitt_1d0f */\n\n/*\n * uint16_t crc_ccitt_ffff( const unsigned char *input_str, size_t num_bytes );\n *\n * The function crc_ccitt_ffff() performs a one-pass calculation of the CCITT\n * CRC for a byte string that has been passed as a parameter. The initial value\n * 0xffff is used for the CRC.\n */\n\nuint16_t crc_ccitt_ffff(const unsigned char* input_str, size_t num_bytes) {\n  return crc_ccitt_generic(input_str, num_bytes, CRC_START_CCITT_FFFF);\n\n} /* crc_ccitt_ffff */\n\n/*\n * static uint16_t crc_ccitt_generic( const unsigned char *input_str, size_t num_bytes, uint16_t\n * start_value );\n *\n * The function crc_ccitt_generic() is a generic implementation of the CCITT\n * algorithm for a one-pass calculation of the CRC for a byte string. The\n * function accepts an initial start value for the crc.\n */\n\nstatic uint16_t crc_ccitt_generic(const unsigned char* input_str, size_t num_bytes,\n                                  uint16_t start_value) {\n  uint16_t crc;\n  const unsigned char* ptr;\n  size_t a;\n\n  crc = start_value;\n  ptr = input_str;\n\n  if (ptr != NULL)\n    for (a = 0; a < num_bytes; a++) {\n      crc = (crc << 8) ^ crc_tabccitt[((crc >> 8) ^ (uint16_t)*ptr++) & 0x00FF];\n    }\n\n  return crc;\n\n} /* crc_ccitt_generic */\n\n/*\n * uint16_t update_crc_ccitt( uint16_t crc, unsigned char c );\n *\n * The function update_crc_ccitt() calculates a new CRC-CCITT value based on\n * the previous value of the CRC and the next byte of the data to be checked.\n */\n\nuint16_t update_crc_ccitt(uint16_t crc, unsigned char c) {\n  return (crc << 8) ^ crc_tabccitt[((crc >> 8) ^ (uint16_t)c) & 0x00FF];\n\n} /* update_crc_ccitt */\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "3rdparty/picojson/picojson.h",
        "content": "/*\n * Copyright 2009-2010 Cybozu Labs, Inc.\n * Copyright 2011-2014 Kazuho Oku\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#pragma once\n\n#include <algorithm>\n#include <cstddef>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n// for isnan/isinf\n#if __cplusplus >= 201103L\n#include <cmath>\n#else\nextern \"C\" {\n#ifdef _MSC_VER\n#include <float.h>\n#elif defined(__INTEL_COMPILER)\n#include <mathimf.h>\n#else\n#include <math.h>\n#endif\n}\n#endif\n\n#ifndef PICOJSON_USE_RVALUE_REFERENCE\n#if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || \\\n    (defined(_MSC_VER) && _MSC_VER >= 1600)\n#define PICOJSON_USE_RVALUE_REFERENCE 1\n#else\n#define PICOJSON_USE_RVALUE_REFERENCE 0\n#endif\n#endif  // PICOJSON_USE_RVALUE_REFERENCE\n\n#ifndef PICOJSON_NOEXCEPT\n#if PICOJSON_USE_RVALUE_REFERENCE\n#define PICOJSON_NOEXCEPT noexcept\n#else\n#define PICOJSON_NOEXCEPT throw()\n#endif\n#endif\n\n// experimental support for int64_t (see README.mkdn for detail)\n#ifdef PICOJSON_USE_INT64\n#define __STDC_FORMAT_MACROS\n#include <errno.h>\n#include <inttypes.h>\n#endif\n\n// to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0\n#ifndef PICOJSON_USE_LOCALE\n#define PICOJSON_USE_LOCALE 1\n#endif\n#if PICOJSON_USE_LOCALE\nextern \"C\" {\n#include <locale.h>\n}\n#endif\n\n#ifndef PICOJSON_ASSERT\n#ifndef PICOJSON_DISABLE_EXCEPTION\n#define PICOJSON_ASSERT(e)                  \\\n  do {                                      \\\n    if (!(e)) throw std::runtime_error(#e); \\\n  } while (0)\n#else\n#define PICOJSON_ASSERT(e)  \\\n  do {                      \\\n    if (!(e)) std::abort(); \\\n  } while (0)\n#endif  // PICOJSON_DISABLE_EXCEPTION\n#endif\n\n#ifdef _MSC_VER\n#define SNPRINTF _snprintf_s\n#pragma warning(push)\n#pragma warning(disable : 4244)  // conversion from int to char\n#pragma warning(disable : 4127)  // conditional expression is constant\n#pragma warning(disable : 4702)  // unreachable code\n#else\n#define SNPRINTF snprintf\n#endif\n\nnamespace picojson {\n\nenum {\n  null_type,\n  boolean_type,\n  number_type,\n  string_type,\n  array_type,\n  object_type\n#ifdef PICOJSON_USE_INT64\n  ,\n  int64_type\n#endif\n};\n\nenum { INDENT_WIDTH = 2 };\n\nstruct null {};\n\nclass value {\n public:\n  typedef std::vector<value> array;\n  typedef std::unordered_map<std::string, value> object;\n  union _storage {\n    bool boolean_;\n    double number_;\n#ifdef PICOJSON_USE_INT64\n    int64_t int64_;\n#endif\n    std::string* string_;\n    array* array_;\n    object* object_;\n  };\n\n protected:\n  int type_;\n  _storage u_;\n\n public:\n  value();\n  value(int type, bool);\n  explicit value(bool b);\n#ifdef PICOJSON_USE_INT64\n  explicit value(int64_t i);\n#endif\n  explicit value(double n);\n  explicit value(const std::string& s);\n  explicit value(const array& a);\n  explicit value(const object& o);\n#if PICOJSON_USE_RVALUE_REFERENCE\n  explicit value(std::string&& s);\n  explicit value(array&& a);\n  explicit value(object&& o);\n#endif\n  explicit value(const char* s);\n  value(const char* s, size_t len);\n  ~value();\n  value(const value& x);\n  value& operator=(const value& x);\n#if PICOJSON_USE_RVALUE_REFERENCE\n  value(value&& x) PICOJSON_NOEXCEPT;\n  value& operator=(value&& x) PICOJSON_NOEXCEPT;\n#endif\n  void swap(value& x) PICOJSON_NOEXCEPT;\n  template <typename T>\n  bool is() const;\n  template <typename T>\n  const T& get() const;\n  template <typename T>\n  T& get();\n  template <typename T>\n  void set(const T&);\n#if PICOJSON_USE_RVALUE_REFERENCE\n  template <typename T>\n  void set(T&&);\n#endif\n  bool evaluate_as_boolean() const;\n  const value& get(const size_t idx) const;\n  const value& get(const std::string& key) const;\n  value& get(const size_t idx);\n  value& get(const std::string& key);\n\n  bool contains(const size_t idx) const;\n  bool contains(const std::string& key) const;\n  std::string to_str() const;\n  template <typename Iter>\n  void serialize(Iter os, bool prettify = false) const;\n  std::string serialize(bool prettify = false) const;\n\n private:\n  template <typename T>\n  // NOLINTNEXTLINE(runtime/explicit)\n  value(const T*);  // intentionally defined to block implicit conversion of\n                    // pointer to bool\n  template <typename Iter>\n  static void _indent(Iter os, int indent);\n  template <typename Iter>\n  void _serialize(Iter os, int indent) const;\n  std::string _serialize(int indent) const;\n  void clear();\n};\n\ntypedef value::array array;\ntypedef value::object object;\n\ninline value::value() : type_(null_type), u_() {}\n\ninline value::value(int type, bool) : type_(type), u_() {\n  switch (type) {\n#define INIT(p, v) \\\n  case p##type:    \\\n    u_.p = v;      \\\n    break\n    INIT(boolean_, false);\n    INIT(number_, 0.0);\n#ifdef PICOJSON_USE_INT64\n    INIT(int64_, 0);\n#endif\n    INIT(string_, new std::string());\n    INIT(array_, new array());\n    INIT(object_, new object());\n#undef INIT\n    default:\n      break;\n  }\n}\n\ninline value::value(bool b) : type_(boolean_type), u_() { u_.boolean_ = b; }\n\n#ifdef PICOJSON_USE_INT64\ninline value::value(int64_t i) : type_(int64_type), u_() { u_.int64_ = i; }\n#endif\n\ninline value::value(double n) : type_(number_type), u_() {\n  if (\n#ifdef _MSC_VER\n      !_finite(n)\n#elif __cplusplus >= 201103L\n      std::isnan(n) || std::isinf(n)\n#else\n      isnan(n) || isinf(n)\n#endif\n  ) {\n#ifndef PICOJSON_DISABLE_EXCEPTION\n    throw std::overflow_error(\"\");\n#else\n    std::abort();\n#endif\n  }\n  u_.number_ = n;\n}\n\ninline value::value(const std::string& s) : type_(string_type), u_() {\n  u_.string_ = new std::string(s);\n}\n\ninline value::value(const array& a) : type_(array_type), u_() { u_.array_ = new array(a); }\n\ninline value::value(const object& o) : type_(object_type), u_() { u_.object_ = new object(o); }\n\n#if PICOJSON_USE_RVALUE_REFERENCE\ninline value::value(std::string&& s) : type_(string_type), u_() {\n  u_.string_ = new std::string(std::move(s));\n}\n\ninline value::value(array&& a) : type_(array_type), u_() { u_.array_ = new array(std::move(a)); }\n\ninline value::value(object&& o) : type_(object_type), u_() {\n  u_.object_ = new object(std::move(o));\n}\n#endif\n\ninline value::value(const char* s) : type_(string_type), u_() { u_.string_ = new std::string(s); }\n\ninline value::value(const char* s, size_t len) : type_(string_type), u_() {\n  u_.string_ = new std::string(s, len);\n}\n\ninline void value::clear() {\n  switch (type_) {\n#define DEINIT(p) \\\n  case p##type:   \\\n    delete u_.p;  \\\n    break\n    DEINIT(string_);\n    DEINIT(array_);\n    DEINIT(object_);\n#undef DEINIT\n    default:\n      break;\n  }\n}\n\ninline value::~value() { clear(); }\n\ninline value::value(const value& x) : type_(x.type_), u_() {\n  switch (type_) {\n#define INIT(p, v) \\\n  case p##type:    \\\n    u_.p = v;      \\\n    break\n    INIT(string_, new std::string(*x.u_.string_));\n    INIT(array_, new array(*x.u_.array_));\n    INIT(object_, new object(*x.u_.object_));\n#undef INIT\n    default:\n      u_ = x.u_;\n      break;\n  }\n}\n\ninline value& value::operator=(const value& x) {\n  if (this != &x) {\n    value t(x);\n    swap(t);\n  }\n  return *this;\n}\n\n#if PICOJSON_USE_RVALUE_REFERENCE\ninline value::value(value&& x) PICOJSON_NOEXCEPT : type_(null_type), u_() { swap(x); }\ninline value& value::operator=(value&& x) PICOJSON_NOEXCEPT {\n  swap(x);\n  return *this;\n}\n#endif\ninline void value::swap(value& x) PICOJSON_NOEXCEPT {\n  std::swap(type_, x.type_);\n  std::swap(u_, x.u_);\n}\n\n#define IS(ctype, jtype)                 \\\n  template <>                            \\\n  inline bool value::is<ctype>() const { \\\n    return type_ == jtype##_type;        \\\n  }\nIS(null, null)\nIS(bool, boolean)\n#ifdef PICOJSON_USE_INT64\nIS(int64_t, int64)\n#endif\nIS(std::string, string)\nIS(array, array)\nIS(object, object)\n#undef IS\ntemplate <>\ninline bool value::is<double>() const {\n  return type_ == number_type\n#ifdef PICOJSON_USE_INT64\n         || type_ == int64_type\n#endif\n      // NOLINTNEXTLINE(whitespace/semicolon)\n      ;\n}\n\n#define GET(ctype, var)                                                                  \\\n  template <>                                                                            \\\n  inline const ctype& value::get<ctype>() const {                                        \\\n    PICOJSON_ASSERT(\"type mismatch! call is<type>() before get<type>()\" && is<ctype>()); \\\n    return var;                                                                          \\\n  }                                                                                      \\\n  template <>                                                                            \\\n  inline ctype& value::get<ctype>() {                                                    \\\n    PICOJSON_ASSERT(\"type mismatch! call is<type>() before get<type>()\" && is<ctype>()); \\\n    return var;                                                                          \\\n  }\nGET(bool, u_.boolean_)\nGET(std::string, *u_.string_)\nGET(array, *u_.array_)\nGET(object, *u_.object_)\n#ifdef PICOJSON_USE_INT64\nGET(double, (type_ == int64_type && (const_cast<value*>(this)->type_ = number_type,\n                                     const_cast<value*>(this)->u_.number_ = u_.int64_),\n             u_.number_))\nGET(int64_t, u_.int64_)\n#else\nGET(double, u_.number_)\n#endif\n#undef GET\n\n#define SET(ctype, jtype, setter)                    \\\n  template <>                                        \\\n  inline void value::set<ctype>(const ctype& _val) { \\\n    clear();                                         \\\n    type_ = jtype##_type;                            \\\n    setter                                           \\\n  }\nSET(bool, boolean, u_.boolean_ = _val;)\nSET(std::string, string, u_.string_ = new std::string(_val);)\nSET(array, array, u_.array_ = new array(_val);)\nSET(object, object, u_.object_ = new object(_val);)\nSET(double, number, u_.number_ = _val;)\n#ifdef PICOJSON_USE_INT64\nSET(int64_t, int64, u_.int64_ = _val;)\n#endif\n#undef SET\n\n#if PICOJSON_USE_RVALUE_REFERENCE\n#define MOVESET(ctype, jtype, setter)            \\\n  template <>                                    \\\n  inline void value::set<ctype>(ctype && _val) { \\\n    clear();                                     \\\n    type_ = jtype##_type;                        \\\n    setter                                       \\\n  }\nMOVESET(std::string, string, u_.string_ = new std::string(std::move(_val));)\nMOVESET(array, array, u_.array_ = new array(std::move(_val));)\nMOVESET(object, object, u_.object_ = new object(std::move(_val));)\n#undef MOVESET\n#endif\n\ninline bool value::evaluate_as_boolean() const {\n  switch (type_) {\n    case null_type:\n      return false;\n    case boolean_type:\n      return u_.boolean_;\n    case number_type:\n      return u_.number_ != 0;\n#ifdef PICOJSON_USE_INT64\n    case int64_type:\n      return u_.int64_ != 0;\n#endif\n    case string_type:\n      return !u_.string_->empty();\n    default:\n      return true;\n  }\n}\n\ninline const value& value::get(const size_t idx) const {\n  static value s_null;\n  PICOJSON_ASSERT(is<array>());\n  return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;\n}\n\ninline value& value::get(const size_t idx) {\n  static value s_null;\n  PICOJSON_ASSERT(is<array>());\n  return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;\n}\n\ninline const value& value::get(const std::string& key) const {\n  static value s_null;\n  PICOJSON_ASSERT(is<object>());\n  object::const_iterator i = u_.object_->find(key);\n  return i != u_.object_->end() ? i->second : s_null;\n}\n\ninline value& value::get(const std::string& key) {\n  static value s_null;\n  PICOJSON_ASSERT(is<object>());\n  object::iterator i = u_.object_->find(key);\n  return i != u_.object_->end() ? i->second : s_null;\n}\n\ninline bool value::contains(const size_t idx) const {\n  PICOJSON_ASSERT(is<array>());\n  return idx < u_.array_->size();\n}\n\ninline bool value::contains(const std::string& key) const {\n  PICOJSON_ASSERT(is<object>());\n  object::const_iterator i = u_.object_->find(key);\n  return i != u_.object_->end();\n}\n\ninline std::string value::to_str() const {\n  switch (type_) {\n    case null_type:\n      return \"null\";\n    case boolean_type:\n      return u_.boolean_ ? \"true\" : \"false\";\n#ifdef PICOJSON_USE_INT64\n    case int64_type: {\n      char buf[sizeof(\"-9223372036854775808\")];\n      SNPRINTF(buf, sizeof(buf), \"%\" PRId64, u_.int64_);\n      return buf;\n    }\n#endif\n    case number_type: {\n      char buf[256];\n      double tmp;\n      SNPRINTF(buf, sizeof(buf),\n               fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? \"%.f\" : \"%.17g\",\n               u_.number_);\n#if PICOJSON_USE_LOCALE\n      char* decimal_point = localeconv()->decimal_point;\n      if (strcmp(decimal_point, \".\") != 0) {\n        size_t decimal_point_len = strlen(decimal_point);\n        for (char* p = buf; *p != '\\0'; ++p) {\n          if (strncmp(p, decimal_point, decimal_point_len) == 0) {\n            return std::string(buf, p) + \".\" + (p + decimal_point_len);\n          }\n        }\n      }\n#endif\n      return buf;\n    }\n    case string_type:\n      return *u_.string_;\n    case array_type:\n      return \"array\";\n    case object_type:\n      return \"object\";\n    default:\n      PICOJSON_ASSERT(0);\n#ifdef _MSC_VER\n      __assume(0);\n#endif\n  }\n  return std::string();\n}\n\ntemplate <typename Iter>\nvoid copy(const std::string& s, Iter oi) {\n  std::copy(s.begin(), s.end(), oi);\n}\n\ntemplate <typename Iter>\nstruct serialize_str_char {\n  Iter oi;\n  void operator()(char c) {\n    switch (c) {\n#define MAP(val, sym) \\\n  case val:           \\\n    copy(sym, oi);    \\\n    break\n      MAP('\"', \"\\\\\\\"\");\n      MAP('\\\\', \"\\\\\\\\\");\n      MAP('/', \"\\\\/\");\n      MAP('\\b', \"\\\\b\");\n      MAP('\\f', \"\\\\f\");\n      MAP('\\n', \"\\\\n\");\n      MAP('\\r', \"\\\\r\");\n      MAP('\\t', \"\\\\t\");\n#undef MAP\n      default:\n        if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {\n          char buf[7];\n          SNPRINTF(buf, sizeof(buf), \"\\\\u%04x\", c & 0xff);\n          copy(buf, buf + 6, oi);\n        } else {\n          *oi++ = c;\n        }\n        break;\n    }\n  }\n};\n\ntemplate <typename Iter>\nvoid serialize_str(const std::string& s, Iter oi) {\n  *oi++ = '\"';\n  serialize_str_char<Iter> process_char = {oi};\n  std::for_each(s.begin(), s.end(), process_char);\n  *oi++ = '\"';\n}\n\ntemplate <typename Iter>\nvoid value::serialize(Iter oi, bool prettify) const {\n  return _serialize(oi, prettify ? 0 : -1);\n}\n\ninline std::string value::serialize(bool prettify) const { return _serialize(prettify ? 0 : -1); }\n\ntemplate <typename Iter>\nvoid value::_indent(Iter oi, int indent) {\n  *oi++ = '\\n';\n  for (int i = 0; i < indent * INDENT_WIDTH; ++i) {\n    *oi++ = ' ';\n  }\n}\n\ntemplate <typename Iter>\nvoid value::_serialize(Iter oi, int indent) const {\n  switch (type_) {\n    case string_type:\n      serialize_str(*u_.string_, oi);\n      break;\n    case array_type: {\n      *oi++ = '[';\n      if (indent != -1) {\n        ++indent;\n      }\n      for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) {\n        if (i != u_.array_->begin()) {\n          *oi++ = ',';\n        }\n        if (indent != -1) {\n          _indent(oi, indent);\n        }\n        i->_serialize(oi, indent);\n      }\n      if (indent != -1) {\n        --indent;\n        if (!u_.array_->empty()) {\n          _indent(oi, indent);\n        }\n      }\n      *oi++ = ']';\n      break;\n    }\n    case object_type: {\n      *oi++ = '{';\n      if (indent != -1) {\n        ++indent;\n      }\n      for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) {\n        if (i != u_.object_->begin()) {\n          *oi++ = ',';\n        }\n        if (indent != -1) {\n          _indent(oi, indent);\n        }\n        serialize_str(i->first, oi);\n        *oi++ = ':';\n        if (indent != -1) {\n          *oi++ = ' ';\n        }\n        i->second._serialize(oi, indent);\n      }\n      if (indent != -1) {\n        --indent;\n        if (!u_.object_->empty()) {\n          _indent(oi, indent);\n        }\n      }\n      *oi++ = '}';\n      break;\n    }\n    default:\n      copy(to_str(), oi);\n      break;\n  }\n  if (indent == 0) {\n    *oi++ = '\\n';\n  }\n}\n\ninline std::string value::_serialize(int indent) const {\n  std::string s;\n  _serialize(std::back_inserter(s), indent);\n  return s;\n}\n\ntemplate <typename Iter>\nclass input {\n protected:\n  Iter cur_, end_;\n  bool consumed_;\n  int line_;\n\n public:\n  input(const Iter& first, const Iter& last)\n      : cur_(first), end_(last), consumed_(false), line_(1) {}\n  int getc() {\n    if (consumed_) {\n      if (*cur_ == '\\n') {\n        ++line_;\n      }\n      ++cur_;\n    }\n    if (cur_ == end_) {\n      consumed_ = false;\n      return -1;\n    }\n    consumed_ = true;\n    return *cur_ & 0xff;\n  }\n  void ungetc() { consumed_ = false; }\n  Iter cur() const {\n    if (consumed_) {\n      input<Iter>* self = const_cast<input<Iter>*>(this);\n      self->consumed_ = false;\n      ++self->cur_;\n    }\n    return cur_;\n  }\n  int line() const { return line_; }\n  void skip_ws() {\n    while (1) {\n      int ch = getc();\n      if (!(ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r')) {\n        ungetc();\n        break;\n      }\n    }\n  }\n  bool expect(const int expected) {\n    skip_ws();\n    if (getc() != expected) {\n      ungetc();\n      return false;\n    }\n    return true;\n  }\n  bool match(const std::string& pattern) {\n    for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) {\n      if (getc() != *pi) {\n        ungetc();\n        return false;\n      }\n    }\n    return true;\n  }\n};\n\ntemplate <typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline int _parse_quadhex(input<Iter>& in) {\n  int uni_ch = 0, hex;\n  for (int i = 0; i < 4; i++) {\n    if ((hex = in.getc()) == -1) {\n      return -1;\n    }\n    if ('0' <= hex && hex <= '9') {\n      hex -= '0';\n    } else if ('A' <= hex && hex <= 'F') {\n      hex -= 'A' - 0xa;\n    } else if ('a' <= hex && hex <= 'f') {\n      hex -= 'a' - 0xa;\n    } else {\n      in.ungetc();\n      return -1;\n    }\n    uni_ch = uni_ch * 16 + hex;\n  }\n  return uni_ch;\n}\n\ntemplate <typename String, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline bool _parse_codepoint(String& out, input<Iter>& in) {\n  int uni_ch;\n  if ((uni_ch = _parse_quadhex(in)) == -1) {\n    return false;\n  }\n  if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {\n    if (0xdc00 <= uni_ch) {\n      // a second 16-bit of a surrogate pair appeared\n      return false;\n    }\n    // first 16-bit of surrogate pair, get the next one\n    if (in.getc() != '\\\\' || in.getc() != 'u') {\n      in.ungetc();\n      return false;\n    }\n    int second = _parse_quadhex(in);\n    if (!(0xdc00 <= second && second <= 0xdfff)) {\n      return false;\n    }\n    uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);\n    uni_ch += 0x10000;\n  }\n  if (uni_ch < 0x80) {\n    out.push_back(static_cast<char>(uni_ch));\n  } else {\n    if (uni_ch < 0x800) {\n      out.push_back(static_cast<char>(0xc0 | (uni_ch >> 6)));\n    } else {\n      if (uni_ch < 0x10000) {\n        out.push_back(static_cast<char>(0xe0 | (uni_ch >> 12)));\n      } else {\n        out.push_back(static_cast<char>(0xf0 | (uni_ch >> 18)));\n        out.push_back(static_cast<char>(0x80 | ((uni_ch >> 12) & 0x3f)));\n      }\n      out.push_back(static_cast<char>(0x80 | ((uni_ch >> 6) & 0x3f)));\n    }\n    out.push_back(static_cast<char>(0x80 | (uni_ch & 0x3f)));\n  }\n  return true;\n}\n\ntemplate <typename String, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline bool _parse_string(String& out, input<Iter>& in) {\n  while (1) {\n    int ch = in.getc();\n    if (ch < ' ') {\n      in.ungetc();\n      return false;\n    } else if (ch == '\"') {\n      return true;\n    } else if (ch == '\\\\') {\n      if ((ch = in.getc()) == -1) {\n        return false;\n      }\n      switch (ch) {\n#define MAP(sym, val)   \\\n  case sym:             \\\n    out.push_back(val); \\\n    break\n        MAP('\"', '\\\"');\n        MAP('\\\\', '\\\\');\n        MAP('/', '/');\n        MAP('b', '\\b');\n        MAP('f', '\\f');\n        MAP('n', '\\n');\n        MAP('r', '\\r');\n        MAP('t', '\\t');\n#undef MAP\n        case 'u':\n          if (!_parse_codepoint(out, in)) {\n            return false;\n          }\n          break;\n        default:\n          return false;\n      }\n    } else {\n      out.push_back(static_cast<char>(ch));\n    }\n  }\n  return false;\n}\n\ntemplate <typename Context, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline bool _parse_array(Context& ctx, input<Iter>& in) {\n  if (!ctx.parse_array_start()) {\n    return false;\n  }\n  size_t idx = 0;\n  if (in.expect(']')) {\n    return ctx.parse_array_stop(idx);\n  }\n  do {\n    if (!ctx.parse_array_item(in, idx)) {\n      return false;\n    }\n    idx++;\n  } while (in.expect(','));\n  return in.expect(']') && ctx.parse_array_stop(idx);\n}\n\ntemplate <typename Context, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline bool _parse_object(Context& ctx, input<Iter>& in) {\n  if (!ctx.parse_object_start()) {\n    return false;\n  }\n  if (in.expect('}')) {\n    return true;\n  }\n  do {\n    std::string key;\n    if (!in.expect('\"') || !_parse_string(key, in) || !in.expect(':')) {\n      return false;\n    }\n    if (!ctx.parse_object_item(in, key)) {\n      return false;\n    }\n  } while (in.expect(','));\n  return in.expect('}');\n}\n\ntemplate <typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline std::string _parse_number(input<Iter>& in) {\n  std::string num_str;\n  while (1) {\n    int ch = in.getc();\n    if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') {\n      num_str.push_back(static_cast<char>(ch));\n    } else if (ch == '.') {\n#if PICOJSON_USE_LOCALE\n      num_str += localeconv()->decimal_point;\n#else\n      num_str.push_back('.');\n#endif\n    } else {\n      in.ungetc();\n      break;\n    }\n  }\n  return num_str;\n}\n\ntemplate <typename Context, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline bool _parse(Context& ctx, input<Iter>& in) {\n  in.skip_ws();\n  int ch = in.getc();\n  switch (ch) {\n#define IS(ch, text, op)        \\\n  case ch:                      \\\n    if (in.match(text) && op) { \\\n      return true;              \\\n    } else {                    \\\n      return false;             \\\n    }\n    IS('n', \"ull\", ctx.set_null());\n    IS('f', \"alse\", ctx.set_bool(false));\n    IS('t', \"rue\", ctx.set_bool(true));\n#undef IS\n    case '\"':\n      return ctx.parse_string(in);\n    case '[':\n      return _parse_array(ctx, in);\n    case '{':\n      return _parse_object(ctx, in);\n    default:\n      if (('0' <= ch && ch <= '9') || ch == '-') {\n        double f;\n        char* endp;\n        in.ungetc();\n        std::string num_str(_parse_number(in));\n        if (num_str.empty()) {\n          return false;\n        }\n#ifdef PICOJSON_USE_INT64\n        {\n          errno = 0;\n          intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);\n          if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival &&\n              ival <= std::numeric_limits<int64_t>::max() &&\n              endp == num_str.c_str() + num_str.size()) {\n            ctx.set_int64(ival);\n            return true;\n          }\n        }\n#endif\n        f = strtod(num_str.c_str(), &endp);\n        if (endp == num_str.c_str() + num_str.size()) {\n          ctx.set_number(f);\n          return true;\n        }\n        return false;\n      }\n      break;\n  }\n  in.ungetc();\n  return false;\n}\n\nclass deny_parse_context {\n public:\n  bool set_null() { return false; }\n  bool set_bool(bool) { return false; }\n#ifdef PICOJSON_USE_INT64\n  bool set_int64(int64_t) { return false; }\n#endif\n  bool set_number(double) { return false; }\n  template <typename Iter>\n  bool parse_string(input<Iter>&) {\n    return false;\n  }\n  bool parse_array_start() { return false; }\n  template <typename Iter>\n  bool parse_array_item(input<Iter>&, size_t) {\n    return false;\n  }\n  bool parse_array_stop(size_t) { return false; }\n  bool parse_object_start() { return false; }\n  template <typename Iter>\n  bool parse_object_item(input<Iter>&, const std::string&) {\n    return false;\n  }\n};\n\nclass default_parse_context {\n protected:\n  value* out_;\n\n public:\n  // NOLINTNEXTLINE(runtime/explicit)\n  default_parse_context(value* out) : out_(out) {}\n  bool set_null() {\n    *out_ = value();\n    return true;\n  }\n  bool set_bool(bool b) {\n    *out_ = value(b);\n    return true;\n  }\n#ifdef PICOJSON_USE_INT64\n  bool set_int64(int64_t i) {\n    *out_ = value(i);\n    return true;\n  }\n#endif\n  bool set_number(double f) {\n    *out_ = value(f);\n    return true;\n  }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_string(input<Iter>& in) {\n    *out_ = value(string_type, false);\n    return _parse_string(out_->get<std::string>(), in);\n  }\n  bool parse_array_start() {\n    *out_ = value(array_type, false);\n    return true;\n  }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_array_item(input<Iter>& in, size_t) {\n    array& a = out_->get<array>();\n    a.push_back(value());\n    default_parse_context ctx(&a.back());\n    return _parse(ctx, in);\n  }\n  bool parse_array_stop(size_t) { return true; }\n  bool parse_object_start() {\n    *out_ = value(object_type, false);\n    return true;\n  }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_object_item(input<Iter>& in, const std::string& key) {\n    object& o = out_->get<object>();\n    default_parse_context ctx(&o[key]);\n    return _parse(ctx, in);\n  }\n\n private:\n  default_parse_context(const default_parse_context&);\n  default_parse_context& operator=(const default_parse_context&);\n};\n\nclass null_parse_context {\n public:\n  struct dummy_str {\n    void push_back(int) {}\n  };\n\n public:\n  null_parse_context() {}\n  bool set_null() { return true; }\n  bool set_bool(bool) { return true; }\n#ifdef PICOJSON_USE_INT64\n  bool set_int64(int64_t) { return true; }\n#endif\n  bool set_number(double) { return true; }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_string(input<Iter>& in) {\n    dummy_str s;\n    return _parse_string(s, in);\n  }\n  bool parse_array_start() { return true; }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_array_item(input<Iter>& in, size_t) {\n    return _parse(*this, in);\n  }\n  bool parse_array_stop(size_t) { return true; }\n  bool parse_object_start() { return true; }\n  template <typename Iter>\n  // NOLINTNEXTLINE(runtime/references)\n  bool parse_object_item(input<Iter>& in, const std::string&) {\n    return _parse(*this, in);\n  }\n\n private:\n  null_parse_context(const null_parse_context&);\n  null_parse_context& operator=(const null_parse_context&);\n};\n\n// obsolete, use the version below\ntemplate <typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline std::string parse(value& out, Iter& pos, const Iter& last) {\n  std::string err;\n  pos = parse(out, pos, last, &err);\n  return err;\n}\n\ntemplate <typename Context, typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) {\n  input<Iter> in(first, last);\n  if (!_parse(ctx, in) && err != NULL) {\n    char buf[64];\n    SNPRINTF(buf, sizeof(buf), \"syntax error at line %d near: \", in.line());\n    *err = buf;\n    while (1) {\n      int ch = in.getc();\n      if (ch == -1 || ch == '\\n') {\n        break;\n      } else if (ch >= ' ') {\n        err->push_back(static_cast<char>(ch));\n      }\n    }\n  }\n  return in.cur();\n}\n\ntemplate <typename Iter>\n// NOLINTNEXTLINE(runtime/references)\ninline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {\n  default_parse_context ctx(&out);\n  return _parse(ctx, first, last, err);\n}\n\n// NOLINTNEXTLINE(runtime/references)\ninline std::string parse(value& out, const std::string& s) {\n  std::string err;\n  parse(out, s.begin(), s.end(), &err);\n  return err;\n}\n\n// NOLINTNEXTLINE(runtime/references)\ninline std::string parse(value& out, std::istream& is) {\n  std::string err;\n  parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreambuf_iterator<char>(), &err);\n  return err;\n}\n\ntemplate <typename T>\nstruct last_error_t {\n  static std::string s;\n};\ntemplate <typename T>\n// NOLINTNEXTLINE(runtime/string)\nstd::string last_error_t<T>::s;\n\ninline void set_last_error(const std::string& s) { last_error_t<bool>::s = s; }\n\ninline const std::string& get_last_error() { return last_error_t<bool>::s; }\n\ninline bool operator==(const value& x, const value& y) {\n  if (x.is<null>()) return y.is<null>();\n#define PICOJSON_CMP(type) \\\n  if (x.is<type>()) return y.is<type>() && x.get<type>() == y.get<type>()\n  PICOJSON_CMP(bool);\n  PICOJSON_CMP(double);\n  PICOJSON_CMP(std::string);\n  PICOJSON_CMP(array);\n  PICOJSON_CMP(object);\n#undef PICOJSON_CMP\n  PICOJSON_ASSERT(0);\n#ifdef _MSC_VER\n  __assume(0);\n#endif\n  return false;\n}\n\ninline bool operator!=(const value& x, const value& y) { return !(x == y); }\n}  // namespace picojson\n\n#if !PICOJSON_USE_RVALUE_REFERENCE\nnamespace std {\ntemplate <>\ninline void swap(picojson::value& x, picojson::value& y) {\n  x.swap(y);\n}\n}  // namespace std\n#endif\n\ninline std::istream& operator>>(std::istream& is, picojson::value& x) {\n  picojson::set_last_error(std::string());\n  const std::string err(picojson::parse(x, is));\n  if (!err.empty()) {\n    picojson::set_last_error(err);\n    is.setstate(std::ios::failbit);\n  }\n  return is;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const picojson::value& x) {\n  x.serialize(std::ostream_iterator<char>(os));\n  return os;\n}\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_camera/app/src/main/java/org/apache/tvm/android/androidcamerademo/Camera2BasicFragment.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.android.androidcamerademo;\n\nimport android.annotation.SuppressLint;\nimport android.content.res.AssetManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.media.Image;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.os.SystemClock;\nimport android.util.Log;\nimport android.util.Size;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.widget.AppCompatTextView;\nimport androidx.camera.core.Camera;\nimport androidx.camera.core.CameraSelector;\nimport androidx.camera.core.ImageAnalysis;\nimport androidx.camera.core.ImageProxy;\nimport androidx.camera.core.Preview;\nimport androidx.camera.lifecycle.ProcessCameraProvider;\nimport androidx.camera.view.PreviewView;\nimport androidx.core.content.ContextCompat;\nimport androidx.fragment.app.Fragment;\nimport androidx.renderscript.Allocation;\nimport androidx.renderscript.Element;\nimport androidx.renderscript.RenderScript;\nimport androidx.renderscript.Script;\nimport androidx.renderscript.Type;\n\nimport com.google.common.util.concurrent.ListenableFuture;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.NDArray;\nimport org.apache.tvm.Device;\nimport org.apache.tvm.TVMType;\nimport org.apache.tvm.TVMValue;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.PriorityQueue;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.Semaphore;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class Camera2BasicFragment extends Fragment {\n    private static final String TAG = Camera2BasicFragment.class.getSimpleName();\n\n    // TVM constants\n    private static final int OUTPUT_INDEX = 0;\n    private static final int IMG_CHANNEL = 3;\n    private static final boolean EXE_GPU = false;\n    private static final int MODEL_INPUT_SIZE = 224;\n    private static final String MODEL_CL_LIB_FILE = \"deploy_lib_opencl.so\";\n    private static final String MODEL_CPU_LIB_FILE = \"deploy_lib_cpu.so\";\n    private static final String MODEL_GRAPH_FILE = \"deploy_graph.json\";\n    private static final String MODEL_PARAM_FILE = \"deploy_param.params\";\n    private static final String MODEL_LABEL_FILE = \"image_net_labels.json\";\n    private static final String MODELS = \"models\";\n    private static String INPUT_NAME = \"input_1\";\n    private static String[] models;\n    private static String mCurModel = \"\";\n    private final float[] mCHW = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];\n    private final float[] mCHW2 = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];\n    private final Semaphore isProcessingDone = new Semaphore(1);\n    private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(\n            3,\n            3,\n            1,\n            TimeUnit.SECONDS,\n            new LinkedBlockingQueue<>()\n    );\n    // rs creation just for demo. Create rs just once in onCreate and use it again.\n    private RenderScript rs;\n    private ScriptC_yuv420888 mYuv420;\n    private boolean mRunClassifier = false;\n\n    private AppCompatTextView mResultView;\n    private AppCompatTextView mInfoView;\n    private ListView mModelView;\n    private AssetManager assetManager;\n    private Module graphExecutorModule;\n    private JSONObject labels;\n    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;\n    private PreviewView previewView;\n    private ImageAnalysis imageAnalysis;\n\n    static Camera2BasicFragment newInstance() {\n        return new Camera2BasicFragment();\n    }\n\n    private static Matrix getTransformationMatrix(\n            final int srcWidth,\n            final int srcHeight,\n            final int dstWidth,\n            final int dstHeight,\n            final int applyRotation,\n            final boolean maintainAspectRatio) {\n        final Matrix matrix = new Matrix();\n\n        if (applyRotation != 0) {\n            if (applyRotation % 90 != 0) {\n                Log.w(TAG, \"Rotation of %d % 90 != 0 \" + applyRotation);\n            }\n\n            // Translate so center of image is at origin.\n            matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);\n\n            // Rotate around origin.\n            matrix.postRotate(applyRotation);\n        }\n\n        // Account for the already applied rotation, if any, and then determine how\n        // much scaling is needed for each axis.\n        final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;\n\n        final int inWidth = transpose ? srcHeight : srcWidth;\n        final int inHeight = transpose ? srcWidth : srcHeight;\n\n        // Apply scaling if necessary.\n        if (inWidth != dstWidth || inHeight != dstHeight) {\n            final float scaleFactorX = dstWidth / (float) inWidth;\n            final float scaleFactorY = dstHeight / (float) inHeight;\n\n            if (maintainAspectRatio) {\n                // Scale by minimum factor so that dst is filled completely while\n                // maintaining the aspect ratio. Some image may fall off the edge.\n                final float scaleFactor = Math.max(scaleFactorX, scaleFactorY);\n                matrix.postScale(scaleFactor, scaleFactor);\n            } else {\n                // Scale exactly to fill dst from src.\n                matrix.postScale(scaleFactorX, scaleFactorY);\n            }\n        }\n\n        if (applyRotation != 0) {\n            // Translate back from origin centered reference to destination frame.\n            matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);\n        }\n\n        return matrix;\n    }\n\n    private String[] getModels() {\n        String[] models;\n        try {\n            models = getActivity().getAssets().list(MODELS);\n        } catch (IOException e) {\n            return null;\n        }\n        return models;\n    }\n\n    @SuppressLint(\"DefaultLocale\")\n    private String[] inference(float[] chw) {\n        NDArray inputNdArray = NDArray.empty(new long[]{1, IMG_CHANNEL, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE}, new TVMType(\"float32\"));\n        inputNdArray.copyFrom(chw);\n        Function setInputFunc = graphExecutorModule.getFunction(\"set_input\");\n        setInputFunc.pushArg(INPUT_NAME).pushArg(inputNdArray).invoke();\n        // release tvm local variables\n        inputNdArray.release();\n        setInputFunc.release();\n\n        // get the function from the module(run it)\n        Function runFunc = graphExecutorModule.getFunction(\"run\");\n        runFunc.invoke();\n        // release tvm local variables\n        runFunc.release();\n\n        // get the function from the module(get output data)\n        NDArray outputNdArray = NDArray.empty(new long[]{1, 1000}, new TVMType(\"float32\"));\n        Function getOutputFunc = graphExecutorModule.getFunction(\"get_output\");\n        getOutputFunc.pushArg(OUTPUT_INDEX).pushArg(outputNdArray).invoke();\n        float[] output = outputNdArray.asFloatArray();\n        // release tvm local variables\n        outputNdArray.release();\n        getOutputFunc.release();\n\n        if (null != output) {\n            String[] results = new String[5];\n            // top-5\n            PriorityQueue<Integer> pq = new PriorityQueue<>(1000, (Integer idx1, Integer idx2) -> output[idx1] > output[idx2] ? -1 : 1);\n\n            // display the result from extracted output data\n            for (int j = 0; j < output.length; ++j) {\n                pq.add(j);\n            }\n            for (int l = 0; l < 5; l++) {\n                //noinspection ConstantConditions\n                int idx = pq.poll();\n                if (idx < labels.length()) {\n                    try {\n                        results[l] = String.format(\"%.2f\", output[idx]) + \" : \" + labels.getString(Integer.toString(idx));\n                    } catch (JSONException e) {\n                        Log.e(TAG, \"index out of range\", e);\n                    }\n                } else {\n                    results[l] = \"???: unknown\";\n                }\n            }\n            return results;\n        }\n        return new String[5];\n    }\n\n    private void updateActiveModel() {\n        Log.i(TAG, \"updating active model...\");\n        new LoadModelAsyncTask().execute();\n    }\n\n    @Override\n    public void onViewCreated(final View view, Bundle savedInstanceState) {\n\n        mResultView = view.findViewById(R.id.resultTextView);\n        mInfoView = view.findViewById(R.id.infoTextView);\n        mModelView = view.findViewById(R.id.modelListView);\n        if (assetManager == null) {\n            assetManager = getActivity().getAssets();\n        }\n\n        mModelView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);\n        models = getModels();\n\n        ArrayAdapter<String> modelAdapter =\n                new ArrayAdapter<>(\n                        getContext(), R.layout.listview_row, R.id.listview_row_text, models);\n        mModelView.setAdapter(modelAdapter);\n        mModelView.setItemChecked(0, true);\n        mModelView.setOnItemClickListener(\n                (parent, view1, position, id) -> updateActiveModel());\n\n        new LoadModelAsyncTask().execute();\n    }\n\n    @Override\n    public void onActivityCreated(Bundle savedInstanceState) {\n        super.onActivityCreated(savedInstanceState);\n    }\n\n    @Override\n    public void onDestroy() {\n        // release tvm local variables\n        if (null != graphExecutorModule)\n            graphExecutorModule.release();\n        super.onDestroy();\n    }\n\n    /**\n     * Read file from assets and return byte array.\n     *\n     * @param assets   The asset manager to be used to load assets.\n     * @param fileName The filepath of read file.\n     * @return byte[] file content\n     * @throws IOException\n     */\n    private byte[] getBytesFromFile(AssetManager assets, String fileName) throws IOException {\n        InputStream is = assets.open(fileName);\n        int length = is.available();\n        byte[] bytes = new byte[length];\n        // Read in the bytes\n        int offset = 0;\n        int numRead;\n        try {\n            while (offset < bytes.length\n                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {\n                offset += numRead;\n            }\n        } finally {\n            is.close();\n        }\n        // Ensure all the bytes have been read in\n        if (offset < bytes.length) {\n            throw new IOException(\"Could not completely read file \" + fileName);\n        }\n        return bytes;\n    }\n\n    /**\n     * Get application cache path where to place compiled functions.\n     *\n     * @param fileName library file name.\n     * @return String application cache folder path\n     * @throws IOException\n     */\n    private String getTempLibFilePath(String fileName) throws IOException {\n        File tempDir = File.createTempFile(\"tvm4j_demo_\", \"\");\n        if (!tempDir.delete() || !tempDir.mkdir()) {\n            throw new IOException(\"Couldn't create directory \" + tempDir.getAbsolutePath());\n        }\n        return (tempDir + File.separator + fileName);\n    }\n\n    private Bitmap YUV_420_888_toRGB(Image image, int width, int height) {\n        // Get the three image planes\n        Image.Plane[] planes = image.getPlanes();\n        ByteBuffer buffer = planes[0].getBuffer();\n        byte[] y = new byte[buffer.remaining()];\n        buffer.get(y);\n\n        buffer = planes[1].getBuffer();\n        byte[] u = new byte[buffer.remaining()];\n        buffer.get(u);\n\n        buffer = planes[2].getBuffer();\n        byte[] v = new byte[buffer.remaining()];\n        buffer.get(v);\n\n        int yRowStride = planes[0].getRowStride();\n        int uvRowStride = planes[1].getRowStride();\n        int uvPixelStride = planes[1].getPixelStride();\n\n\n        // Y,U,V are defined as global allocations, the out-Allocation is the Bitmap.\n        // Note also that uAlloc and vAlloc are 1-dimensional while yAlloc is 2-dimensional.\n        Type.Builder typeUcharY = new Type.Builder(rs, Element.U8(rs));\n        typeUcharY.setX(yRowStride).setY(height);\n        Allocation yAlloc = Allocation.createTyped(rs, typeUcharY.create());\n        yAlloc.copyFrom(y);\n        mYuv420.set_ypsIn(yAlloc);\n\n        Type.Builder typeUcharUV = new Type.Builder(rs, Element.U8(rs));\n        // note that the size of the u's and v's are as follows:\n        //      (  (width/2)*PixelStride + padding  ) * (height/2)\n        // =    (RowStride                          ) * (height/2)\n        typeUcharUV.setX(u.length);\n        Allocation uAlloc = Allocation.createTyped(rs, typeUcharUV.create());\n        uAlloc.copyFrom(u);\n        mYuv420.set_uIn(uAlloc);\n\n        Allocation vAlloc = Allocation.createTyped(rs, typeUcharUV.create());\n        vAlloc.copyFrom(v);\n        mYuv420.set_vIn(vAlloc);\n\n        // handover parameters\n        mYuv420.set_picWidth(width);\n        mYuv420.set_uvRowStride(uvRowStride);\n        mYuv420.set_uvPixelStride(uvPixelStride);\n\n        Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n        Allocation outAlloc = Allocation.createFromBitmap(rs, outBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);\n\n        Script.LaunchOptions lo = new Script.LaunchOptions();\n        lo.setX(0, width);  // by this we ignore the y\u2019s padding zone, i.e. the right side of x between width and yRowStride\n        lo.setY(0, height);\n\n        mYuv420.forEach_doConvert(outAlloc, lo);\n        outAlloc.copyTo(outBitmap);\n\n        return outBitmap;\n    }\n\n    private float[] getFrame(ImageProxy imageProxy) {\n        @SuppressLint(\"UnsafeOptInUsageError\")\n        Image image = imageProxy.getImage();\n        // extract the jpeg content\n        if (image == null) {\n            return null;\n        }\n        Bitmap imageBitmap = YUV_420_888_toRGB(image, image.getWidth(), image.getHeight());\n\n        imageProxy.close();\n        // crop input image at centre to model input size\n        Bitmap cropImageBitmap = Bitmap.createBitmap(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, Bitmap.Config.ARGB_8888);\n        Matrix frameToCropTransform = getTransformationMatrix(imageBitmap.getWidth(), imageBitmap.getHeight(),\n                MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, 0, true);\n        Canvas canvas = new Canvas(cropImageBitmap);\n        canvas.drawBitmap(imageBitmap, frameToCropTransform, null);\n\n        // image pixel int values\n        int[] pixelValues = new int[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE];\n        // image RGB float values\n\n        // pre-process the image data from 0-255 int to normalized float based on the\n        // provided parameters.\n        cropImageBitmap.getPixels(pixelValues, 0, MODEL_INPUT_SIZE, 0, 0, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE);\n        for (int j = 0; j < pixelValues.length; ++j) {\n            mCHW2[j * 3 + 0] = ((pixelValues[j] >> 16) & 0xFF) / 255.0f;\n            mCHW2[j * 3 + 1] = ((pixelValues[j] >> 8) & 0xFF) / 255.0f;\n            mCHW2[j * 3 + 2] = (pixelValues[j] & 0xFF) / 255.0f;\n        }\n\n        // pre-process the image rgb data transpose based on the provided parameters.\n        for (int k = 0; k < IMG_CHANNEL; ++k) {\n            for (int l = 0; l < MODEL_INPUT_SIZE; ++l) {\n                for (int m = 0; m < MODEL_INPUT_SIZE; ++m) {\n                    int dst_index = m + MODEL_INPUT_SIZE * l + MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * k;\n                    int src_index = k + IMG_CHANNEL * m + IMG_CHANNEL * MODEL_INPUT_SIZE * l;\n                    mCHW[dst_index] = mCHW2[src_index];\n                }\n            }\n        }\n\n        return mCHW;\n    }\n\n    @Override\n    public void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity());\n    }\n\n    @SuppressLint({\"RestrictedApi\", \"UnsafeExperimentalUsageError\"})\n    @Nullable\n    @Override\n    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n        View v = inflater.inflate(R.layout.fragment_camera2_basic, container, false);\n        previewView = v.findViewById(R.id.textureView);\n        rs = RenderScript.create(getActivity());\n        mYuv420 = new ScriptC_yuv420888(rs);\n        cameraProviderFuture.addListener(() -> {\n            try {\n                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();\n                bindPreview(cameraProvider);\n            } catch (ExecutionException | InterruptedException e) {\n                // No errors need to be handled for this Future. This should never be reached\n            }\n        }, ContextCompat.getMainExecutor(getActivity()));\n\n        imageAnalysis = new ImageAnalysis.Builder()\n                .setTargetResolution(new Size(224, 224))\n                .setMaxResolution(new Size(300, 300))\n                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)\n                .build();\n\n        imageAnalysis.setAnalyzer(threadPoolExecutor, image -> {\n            Log.e(TAG, \"w: \" + image.getWidth() + \" h: \" + image.getHeight());\n            if (mRunClassifier && isProcessingDone.tryAcquire()) {\n                long t1 = SystemClock.uptimeMillis();\n                //float[] chw = getFrame(image);\n                //float[] chw = YUV_420_888_toRGBPixels(image);\n                float[] chw = getFrame(image);\n                if (chw != null) {\n                    long t2 = SystemClock.uptimeMillis();\n                    String[] results = inference(chw);\n                    long t3 = SystemClock.uptimeMillis();\n                    StringBuilder msgBuilder = new StringBuilder();\n                    for (int l = 1; l < 5; l++) {\n                        msgBuilder.append(results[l]).append(\"\\n\");\n                    }\n                    String msg = msgBuilder.toString();\n                    msg += \"getFrame(): \" + (t2 - t1) + \"ms\" + \"\\n\";\n                    msg += \"inference(): \" + (t3 - t2) + \"ms\" + \"\\n\";\n                    String finalMsg = msg;\n                    this.getActivity().runOnUiThread(() -> {\n                        mResultView.setText(String.format(\"model: %s \\n %s\", mCurModel, results[0]));\n                        mInfoView.setText(finalMsg);\n                    });\n                }\n                isProcessingDone.release();\n            }\n            image.close();\n        });\n        return v;\n    }\n\n    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {\n        @SuppressLint(\"RestrictedApi\") Preview preview = new Preview.Builder()\n                .setMaxResolution(new Size(800, 800))\n                .setTargetName(\"Preview\")\n                .build();\n\n        preview.setSurfaceProvider(previewView.getPreviewSurfaceProvider());\n        CameraSelector cameraSelector =\n                new CameraSelector.Builder()\n                        .requireLensFacing(CameraSelector.LENS_FACING_BACK)\n                        .build();\n        Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);\n    }\n\n    @Override\n    public void onDestroyView() {\n        threadPoolExecutor.shutdownNow();\n        super.onDestroyView();\n    }\n\n    private void setInputName(String modelName) {\n        if (modelName.equals(\"mobilenet_v2\")) {\n            INPUT_NAME = \"input_1\";\n        } else if (modelName.equals(\"resnet18_v1\")) {\n            INPUT_NAME = \"data\";\n        } else {\n            throw new RuntimeException(\"Model input may not be right. Please set INPUT_NAME here explicitly.\");\n        }\n    }\n\n    /*\n       Load precompiled model on TVM graph executor and init the system.\n    */\n    private class LoadModelAsyncTask extends AsyncTask<Void, Void, Integer> {\n\n        @Override\n        protected Integer doInBackground(Void... args) {\n            mRunClassifier = false;\n            // load synset name\n            int modelIndex = mModelView.getCheckedItemPosition();\n            setInputName(models[modelIndex]);\n            String model = MODELS + \"/\" + models[modelIndex];\n            String labelFilename = MODEL_LABEL_FILE;\n            Log.i(TAG, \"Reading labels from: \" + model + \"/\" + labelFilename);\n            try {\n                labels = new JSONObject(new String(getBytesFromFile(assetManager, model + \"/\" + labelFilename)));\n            } catch (IOException | JSONException e) {\n                Log.e(TAG, \"Problem reading labels name file!\", e);\n                return -1;//failure\n            }\n\n            // load json graph\n            String modelGraph;\n            String graphFilename = MODEL_GRAPH_FILE;\n            Log.i(TAG, \"Reading json graph from: \" + model + \"/\" + graphFilename);\n            try {\n                modelGraph = new String(getBytesFromFile(assetManager, model + \"/\" + graphFilename));\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem reading json graph file!\", e);\n                return -1;//failure\n            }\n\n            // upload tvm compiled function on application cache folder\n            String libCacheFilePath;\n            String libFilename = EXE_GPU ? MODEL_CL_LIB_FILE : MODEL_CPU_LIB_FILE;\n            Log.i(TAG, \"Uploading compiled function to cache folder\");\n            try {\n                libCacheFilePath = getTempLibFilePath(libFilename);\n                byte[] modelLibByte = getBytesFromFile(assetManager, model + \"/\" + libFilename);\n                FileOutputStream fos = new FileOutputStream(libCacheFilePath);\n                fos.write(modelLibByte);\n                fos.close();\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem uploading compiled function!\", e);\n                return -1;//failure\n            }\n\n            // load parameters\n            byte[] modelParams;\n            try {\n                modelParams = getBytesFromFile(assetManager, model + \"/\" + MODEL_PARAM_FILE);\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem reading params file!\", e);\n                return -1;//failure\n            }\n\n            Log.i(TAG, \"creating java tvm device...\");\n            // create java tvm device\n            Device tvmDev = EXE_GPU ? Device.opencl() : Device.cpu();\n\n            Log.i(TAG, \"loading compiled functions...\");\n            Log.i(TAG, libCacheFilePath);\n            // tvm module for compiled functions\n            Module modelLib = Module.load(libCacheFilePath);\n\n\n            // get global function module for graph executor\n            Log.i(TAG, \"getting graph executor create handle...\");\n\n            Function runtimeCreFun = Function.getFunction(\"tvm.graph_executor.create\");\n            Log.i(TAG, \"creating graph executor...\");\n\n            Log.i(TAG, \"device type: \" + tvmDev.deviceType);\n            Log.i(TAG, \"device id: \" + tvmDev.deviceId);\n\n            TVMValue runtimeCreFunRes = runtimeCreFun.pushArg(modelGraph)\n                    .pushArg(modelLib)\n                    .pushArg(tvmDev.deviceType)\n                    .pushArg(tvmDev.deviceId)\n                    .invoke();\n\n            Log.i(TAG, \"as module...\");\n            graphExecutorModule = runtimeCreFunRes.asModule();\n            Log.i(TAG, \"getting graph executor load params handle...\");\n            // get the function from the module(load parameters)\n            Function loadParamFunc = graphExecutorModule.getFunction(\"load_params\");\n            Log.i(TAG, \"loading params...\");\n            loadParamFunc.pushArg(modelParams).invoke();\n            // release tvm local variables\n            modelLib.release();\n            loadParamFunc.release();\n            runtimeCreFun.release();\n            mCurModel = model;\n            mRunClassifier = true;\n            return 0;//success\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_camera/app/src/main/java/org/apache/tvm/android/androidcamerademo/MainActivity.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.android.androidcamerademo;\n\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.app.ActivityCompat;\nimport androidx.core.content.ContextCompat;\n\npublic class MainActivity extends AppCompatActivity implements\n        ActivityCompat.OnRequestPermissionsResultCallback {\n\n    private static final int PERMISSIONS_REQUEST_CODE = 1;\n\n    private String[] getRequiredPermissions() {\n        try {\n            PackageInfo info = getPackageManager()\n                    .getPackageInfo(getPackageName(), PackageManager.GET_PERMISSIONS);\n            String[] ps = info.requestedPermissions;\n            if (ps != null && ps.length > 0) {\n                return ps;\n            } else {\n                return new String[0];\n            }\n        } catch (Exception e) {\n            return new String[0];\n        }\n    }\n\n    private boolean allPermissionsGranted() {\n        for (String permission : getRequiredPermissions()) {\n            if (ContextCompat.checkSelfPermission(this, permission)\n                    != PackageManager.PERMISSION_GRANTED) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        if (!allPermissionsGranted()) {\n            requestPermissions(getRequiredPermissions(), PERMISSIONS_REQUEST_CODE);\n            return;\n        }\n        startFragment();\n    }\n\n    private void startFragment() {\n        getSupportFragmentManager()\n                .beginTransaction()\n                .replace(R.id.container, Camera2BasicFragment.newInstance())\n                .commit();\n    }\n\n    @Override\n    public void onRequestPermissionsResult(\n            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n            super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n        if (allPermissionsGranted()) {\n            startFragment();\n        } else {\n            Toast.makeText(this, \"Required permissions are not granted. App may not run\", Toast.LENGTH_SHORT).show();\n            finish();\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_camera/app/src/main/jni/tvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm_runtime.h\n * \\brief Pack all tvm runtime source files\n */\n#include <sys/stat.h>\n\n#include <fstream>\n\n#define DMLC_USE_LOGGING_LIBRARY <tvm/runtime/logging.h>\n#define TVM_USE_LIBBACKTRACE 0\n/* Enable custom logging - this will cause TVM to use a custom implementation\n * of tvm::runtime::detail::LogMessage. We use this to pass TVM log messages to\n * Android logcat.\n */\n#define TVM_LOG_CUSTOMIZE 1\n\n#include \"../src/runtime/c_runtime_api.cc\"\n#include \"../src/runtime/cpu_device_api.cc\"\n#include \"../src/runtime/dso_library.cc\"\n#include \"../src/runtime/file_utils.cc\"\n#include \"../src/runtime/graph_executor/graph_executor.cc\"\n#include \"../src/runtime/library_module.cc\"\n#include \"../src/runtime/logging.cc\"\n#include \"../src/runtime/minrpc/minrpc_logger.cc\"\n#include \"../src/runtime/module.cc\"\n#include \"../src/runtime/ndarray.cc\"\n#include \"../src/runtime/object.cc\"\n#include \"../src/runtime/profiling.cc\"\n#include \"../src/runtime/registry.cc\"\n#include \"../src/runtime/rpc/rpc_channel.cc\"\n#include \"../src/runtime/rpc/rpc_endpoint.cc\"\n#include \"../src/runtime/rpc/rpc_event_impl.cc\"\n#include \"../src/runtime/rpc/rpc_local_session.cc\"\n#include \"../src/runtime/rpc/rpc_module.cc\"\n#include \"../src/runtime/rpc/rpc_server_env.cc\"\n#include \"../src/runtime/rpc/rpc_session.cc\"\n#include \"../src/runtime/rpc/rpc_socket_impl.cc\"\n#include \"../src/runtime/system_library.cc\"\n#include \"../src/runtime/thread_pool.cc\"\n#include \"../src/runtime/threading_backend.cc\"\n#include \"../src/runtime/workspace_pool.cc\"\n\n#ifdef TVM_OPENCL_RUNTIME\n#include \"../src/runtime/opencl/opencl_device_api.cc\"\n#include \"../src/runtime/opencl/opencl_module.cc\"\n#include \"../src/runtime/source_utils.cc\"\n#endif\n\n#ifdef TVM_VULKAN_RUNTIME\n#include \"../src/runtime/vulkan/vulkan.cc\"\n#endif\n\n#ifdef USE_SORT\n#include \"../src/runtime/contrib/sort/sort.cc\"\n#endif\n\n#include <android/log.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace detail {\n// Override logging mechanism\n[[noreturn]] void LogFatalImpl(const std::string& file, int lineno, const std::string& message) {\n  std::string m = file + \":\" + std::to_string(lineno) + \": \" + message;\n  __android_log_write(ANDROID_LOG_FATAL, \"TVM_RUNTIME\", m.c_str());\n  throw InternalError(file, lineno, message);\n}\nvoid LogMessageImpl(const std::string& file, int lineno, int level, const std::string& message) {\n  std::string m = file + \":\" + std::to_string(lineno) + \": \" + message;\n  __android_log_write(ANDROID_LOG_DEBUG + level, \"TVM_RUNTIME\", m.c_str());\n}\n\n}  // namespace detail\n}  // namespace runtime\n}  // namespace tvm\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_camera/app/src/main/rs/yuv420888.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Source: https://stackoverflow.com/questions/36212904/yuv-420-888-interpretation-on-samsung-galaxy-s7-camera2\n#pragma version(1)\n#pragma rs java_package_name(org.apache.tvm.android.androidcamerademo);\n#pragma rs_fp_relaxed\n\nint32_t width;\nint32_t height;\n\nuint picWidth, uvPixelStride, uvRowStride ;\nrs_allocation ypsIn,uIn,vIn;\n\n// The LaunchOptions ensure that the Kernel does not enter the padding  zone of Y, so yRowStride can be ignored WITHIN the Kernel.\nuchar4 __attribute__((kernel)) doConvert(uint32_t x, uint32_t y) {\n\n    // index for accessing the uIn's and vIn's\n    uint uvIndex=  uvPixelStride * (x/2) + uvRowStride*(y/2);\n\n    // get the y,u,v values\n    uchar yps= rsGetElementAt_uchar(ypsIn, x, y);\n    uchar u= rsGetElementAt_uchar(uIn, uvIndex);\n    uchar v= rsGetElementAt_uchar(vIn, uvIndex);\n\n    // calc argb\n    int4 argb;\n    argb.r = yps + v * 1436 / 1024 - 179;\n    argb.g =  yps -u * 46549 / 131072 + 44 -v * 93604 / 131072 + 91;\n    argb.b = yps +u * 1814 / 1024 - 227;\n    argb.a = 255;\n\n    uchar4 out = convert_uchar4(clamp(argb, 0, 255));\n    return out;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_camera/models/prepare_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport logging\nimport pathlib\nfrom pathlib import Path\nfrom typing import Union\nimport os\nfrom os import environ\nimport json\n\nimport tvm\nimport tvm.relay as relay\nfrom tvm.contrib import utils, ndk, graph_executor as runtime\nfrom tvm.contrib.download import download_testdata, download\n\ntarget = \"llvm -mtriple=arm64-linux-android\"\ntarget_host = None\n\n\ndef del_dir(target: Union[Path, str], only_if_empty: bool = False):\n    target = Path(target).expanduser()\n    assert target.is_dir()\n    for p in sorted(target.glob(\"**/*\"), reverse=True):\n        if not p.exists():\n            continue\n        p.chmod(0o666)\n        if p.is_dir():\n            p.rmdir()\n        else:\n            if only_if_empty:\n                raise RuntimeError(f\"{p.parent} is not empty!\")\n            p.unlink()\n    target.rmdir()\n\n\ndef get_model(model_name, batch_size=1):\n    if model_name == \"resnet18_v1\":\n        import mxnet as mx\n        from mxnet import gluon\n        from mxnet.gluon.model_zoo import vision\n\n        gluon_model = vision.get_model(model_name, pretrained=True)\n        img_size = 224\n        data_shape = (batch_size, 3, img_size, img_size)\n        net, params = relay.frontend.from_mxnet(gluon_model, {\"data\": data_shape})\n        return (net, params)\n    elif model_name == \"mobilenet_v2\":\n        import keras\n        from keras.applications.mobilenet_v2 import MobileNetV2\n\n        keras.backend.clear_session()  # Destroys the current TF graph and creates a new one.\n        weights_url = \"\".join(\n            [\n                \"https://github.com/JonathanCMitchell/\",\n                \"mobilenet_v2_keras/releases/download/v1.1/\",\n                \"mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5\",\n            ]\n        )\n        weights_file = \"mobilenet_v2_weights.h5\"\n        weights_path = download_testdata(weights_url, weights_file, module=\"keras\")\n        keras_mobilenet_v2 = MobileNetV2(\n            alpha=0.5, include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000\n        )\n        keras_mobilenet_v2.load_weights(weights_path)\n\n        img_size = 224\n        data_shape = (batch_size, 3, img_size, img_size)\n        mod, params = relay.frontend.from_keras(keras_mobilenet_v2, {\"input_1\": data_shape})\n        return (mod, params)\n\n\ndef main(model_str, output_path):\n    if output_path.exists():\n        del_dir(output_path)\n    output_path.mkdir()\n    output_path_str = os.fspath(output_path)\n    print(model_str)\n    print(\"getting model...\")\n    net, params = get_model(model_str)\n    try:\n        os.mkdir(model_str)\n    except FileExistsError:\n        pass\n    print(\"building...\")\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(net, tvm.target.Target(target, target_host), params=params)\n    print(\"dumping lib...\")\n    lib.export_library(output_path_str + \"/\" + \"deploy_lib_cpu.so\", ndk.create_shared)\n    print(\"dumping graph...\")\n    with open(output_path_str + \"/\" + \"deploy_graph.json\", \"w\") as f:\n        f.write(graph)\n    print(\"dumping params...\")\n    with open(output_path_str + \"/\" + \"deploy_param.params\", \"wb\") as f:\n        f.write(tvm.runtime.save_param_dict(params))\n    print(\"dumping labels...\")\n    synset_url = \"\".join(\n        [\n            \"https://gist.githubusercontent.com/zhreshold/\",\n            \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n            \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n            \"imagenet1000_clsid_to_human.txt\",\n        ]\n    )\n    synset_path = output_path_str + \"/image_net_labels\"\n    download(synset_url, output_path_str + \"/image_net_labels\")\n    with open(synset_path) as fi:\n        synset = eval(fi.read())\n        with open(output_path_str + \"/image_net_labels.json\", \"w\") as fo:\n            json.dump(synset, fo, indent=4)\n    os.remove(synset_path)\n\n\nif __name__ == \"__main__\":\n    if environ.get(\"TVM_NDK_CC\") is None:\n        raise RuntimeError(\"Require environment variable TVM_NDK_CC\")\n    models_path = Path().absolute().parent.joinpath(\"app/src/main/assets/models/\")\n    if not models_path.exists():\n        models_path.mkdir()\n    models = {\n        \"mobilenet_v2\": models_path.joinpath(\"mobilenet_v2\"),\n        \"resnet18_v1\": models_path.joinpath(\"resnet18_v1\"),\n    }\n    for model, output_path in models.items():\n        main(model, output_path)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_deploy/app/src/main/java/org/apache/tvm/android/demo/MainActivity.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.android.demo;\n\nimport android.Manifest;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.res.AssetManager;\nimport android.app.AlertDialog;\nimport android.app.ProgressDialog;\nimport android.content.DialogInterface;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.os.SystemClock;\nimport android.provider.MediaStore;\nimport androidx.core.content.FileProvider;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.Toolbar;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Locale;\nimport java.util.Vector;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.NDArray;\nimport org.apache.tvm.Device;\nimport org.apache.tvm.TVMValue;\nimport org.apache.tvm.TVMType;\n\npublic class MainActivity extends AppCompatActivity {\n    private static final String TAG = MainActivity.class.getSimpleName();\n\n    private static final int PERMISSIONS_REQUEST    = 100;\n    private static final int PICTURE_FROM_GALLERY   = 101;\n    private static final int PICTURE_FROM_CAMERA    = 102;\n    private static final int IMAGE_PREVIEW_WIDTH    = 960;\n    private static final int IMAGE_PREVIEW_HEIGHT   = 720;\n\n    // TVM constants\n    private static final int OUTPUT_INDEX           = 0;\n    private static final int IMG_CHANNEL            = 3;\n    private static final String INPUT_NAME          = \"data\";\n\n    // Configuration values for extraction model. Note that the graph, lib and params is not\n    // included with TVM and must be manually placed in the assets/ directory by the user.\n    // Graphs and models downloaded from https://github.com/pjreddie/darknet/blob/ may be\n    // converted e.g. via  define_and_compile_model.py.\n    private static final boolean EXE_GPU            = false;\n    private static final int MODEL_INPUT_SIZE       = 224;\n    private static final String MODEL_CL_LIB_FILE   = \"file:///android_asset/deploy_lib_opencl.so\";\n    private static final String MODEL_CPU_LIB_FILE  = \"file:///android_asset/deploy_lib_cpu.so\";\n    private static final String MODEL_GRAPH_FILE    = \"file:///android_asset/deploy_graph.json\";\n    private static final String MODEL_PARAM_FILE    = \"file:///android_asset/deploy_param.params\";\n    private static final String MODEL_LABEL_FILE    = \"file:///android_asset/imagenet.shortnames.list\";\n\n    private Uri mCameraImageUri;\n    private ImageView mImageView;\n    private TextView mResultView;\n    private AssetManager assetManager;\n    private Module graphExecutorModule;\n    private Vector<String> labels = new Vector<String>();\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        Toolbar toolbar = findViewById(R.id.toolbar);\n        setSupportActionBar(toolbar);\n        assetManager = getAssets();\n\n        mImageView = (ImageView) findViewById(R.id.imageView);\n        mResultView = (TextView) findViewById(R.id.resultTextView);\n        findViewById(R.id.btnPickImage).setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                showPictureDialog();\n            }\n        });\n\n        if (hasPermission()) {\n            // instantiate tvm runtime and setup environment on background after application begin\n            new LoadModleAsyncTask().execute();\n        } else {\n            requestPermission();\n        }\n    }\n\n    /*\n        Load precompiled model on TVM graph executor and init the system.\n     */\n    private class LoadModleAsyncTask extends AsyncTask<Void, Void, Integer> {\n        ProgressDialog dialog = new ProgressDialog(MainActivity.this);\n\n        @Override\n        protected Integer doInBackground(Void... args) {\n\n            // load synset name\n            String lableFilename = MODEL_LABEL_FILE.split(\"file:///android_asset/\")[1];\n            Log.i(TAG, \"Reading synset name from: \" + lableFilename);\n            try {\n                String labelsContent = new String(getBytesFromFile(assetManager, lableFilename));\n                for (String line : labelsContent.split(\"\\\\r?\\\\n\")) {\n                    labels.add(line);\n                }\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem reading synset name file!\" + e);\n                return -1;//failure\n            }\n\n            // load json graph\n            String modelGraph = null;\n            String graphFilename = MODEL_GRAPH_FILE.split(\"file:///android_asset/\")[1];\n            Log.i(TAG, \"Reading json graph from: \" + graphFilename);\n            try {\n                modelGraph = new String(getBytesFromFile(assetManager, graphFilename));\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem reading json graph file!\" + e);\n                return -1;//failure\n            }\n\n            // upload tvm compiled function on application cache folder\n            String libCacheFilePath = null;\n            String libFilename = EXE_GPU ? MODEL_CL_LIB_FILE.split(\"file:///android_asset/\")[1] :\n                    MODEL_CPU_LIB_FILE.split(\"file:///android_asset/\")[1];\n            Log.i(TAG, \"Uploading compiled function to cache folder\");\n            try {\n                libCacheFilePath = getTempLibFilePath(libFilename);\n                byte[] modelLibByte = getBytesFromFile(assetManager, libFilename);\n                FileOutputStream fos = new FileOutputStream(libCacheFilePath);\n                fos.write(modelLibByte);\n                fos.close();\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem uploading compiled function!\" + e);\n                return -1;//failure\n            }\n\n            // load parameters\n            byte[] modelParams = null;\n            String paramFilename = MODEL_PARAM_FILE.split(\"file:///android_asset/\")[1];\n            try {\n                modelParams = getBytesFromFile(assetManager, paramFilename);\n            } catch (IOException e) {\n                Log.e(TAG, \"Problem reading params file!\" + e);\n                return -1;//failure\n            }\n\n            // create java tvm device\n            Device tvmDev = EXE_GPU ? Device.opencl() : Device.cpu();\n\n            // tvm module for compiled functions\n            Module modelLib = Module.load(libCacheFilePath);\n\n            // get global function module for graph executor\n            Function runtimeCreFun = Function.getFunction(\"tvm.graph_executor.create\");\n            TVMValue runtimeCreFunRes = runtimeCreFun.pushArg(modelGraph)\n                    .pushArg(modelLib)\n                    .pushArg(tvmDev.deviceType)\n                    .pushArg(tvmDev.deviceId)\n                    .invoke();\n            graphExecutorModule = runtimeCreFunRes.asModule();\n\n            // get the function from the module(load parameters)\n            Function loadParamFunc = graphExecutorModule.getFunction(\"load_params\");\n            loadParamFunc.pushArg(modelParams).invoke();\n\n            // release tvm local variables\n            modelLib.release();\n            loadParamFunc.release();\n            runtimeCreFun.release();\n\n            return 0;//success\n        }\n\n        @Override\n        protected void onPreExecute() {\n            dialog.setCancelable(false);\n            dialog.setMessage(\"Loading Model...\");\n            dialog.show();\n            super.onPreExecute();\n        }\n\n        @Override\n        protected void onPostExecute(Integer status) {\n            if (dialog != null && dialog.isShowing()) {\n                dialog.dismiss();\n            }\n            if (status != 0) {\n                showDialog(\"Error\", \"Fail to initialized model, check compiled model\");\n            }\n        }\n    }\n\n    /*\n        Execute prediction for processed decode input bitmap image content on TVM graph executor.\n     */\n    private class ModelRunAsyncTask extends AsyncTask<Bitmap, Void, Integer> {\n        ProgressDialog dialog = new ProgressDialog(MainActivity.this);\n\n        @Override\n        protected Integer doInBackground(Bitmap... bitmaps) {\n            if (null != graphExecutorModule) {\n                int count  = bitmaps.length;\n                for (int i = 0 ; i < count ; i++) {\n                    long processingTimeMs = SystemClock.uptimeMillis();\n                    Log.i(TAG, \"Decode JPEG image content\");\n\n                    // extract the jpeg content\n                    ByteArrayOutputStream stream = new ByteArrayOutputStream();\n                    bitmaps[i].compress(Bitmap.CompressFormat.JPEG,100,stream);\n                    byte[] byteArray = stream.toByteArray();\n                    Bitmap imageBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);\n\n                    // crop input image at centre to model input size\n                    // commecial deploy note:: instead of cropying image do resize\n                    // image to model input size so we never lost the image content\n                    Bitmap cropImageBitmap = Bitmap.createBitmap(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, Bitmap.Config.ARGB_8888);\n                    Matrix frameToCropTransform = getTransformationMatrix(imageBitmap.getWidth(), imageBitmap.getHeight(),\n                            MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, 0, true);\n                    Canvas canvas = new Canvas(cropImageBitmap);\n                    canvas.drawBitmap(imageBitmap, frameToCropTransform, null);\n\n                    // image pixel int values\n                    int[] pixelValues = new int[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE];\n                    // image RGB float values\n                    float[] imgRgbValues = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];\n                    // image RGB transpose float values\n                    float[] imgRgbTranValues = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];\n\n                    // pre-process the image data from 0-255 int to normalized float based on the\n                    // provided parameters.\n                    cropImageBitmap.getPixels(pixelValues, 0, MODEL_INPUT_SIZE, 0, 0, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE);\n                    for (int j = 0; j < pixelValues.length; ++j) {\n                        imgRgbValues[j * 3 + 0] = ((pixelValues[j] >> 16) & 0xFF)/255.0f;\n                        imgRgbValues[j * 3 + 1] = ((pixelValues[j] >> 8) & 0xFF)/255.0f;\n                        imgRgbValues[j * 3 + 2] = (pixelValues[j] & 0xFF)/255.0f;\n                    }\n\n                    // pre-process the image rgb data transpose based on the provided parameters.\n                    for (int k = 0; k < IMG_CHANNEL; ++k) {\n                        for (int l = 0; l < MODEL_INPUT_SIZE; ++l) {\n                            for (int m = 0; m < MODEL_INPUT_SIZE; ++m) {\n                                int dst_index = m + MODEL_INPUT_SIZE*l + MODEL_INPUT_SIZE*MODEL_INPUT_SIZE*k;\n                                int src_index = k + IMG_CHANNEL*m + IMG_CHANNEL*MODEL_INPUT_SIZE*l;\n                                imgRgbTranValues[dst_index] = imgRgbValues[src_index];\n                            }\n                        }\n                    }\n\n                    // get the function from the module(set input data)\n                    Log.i(TAG, \"set input data\");\n                    NDArray inputNdArray = NDArray.empty(new long[]{1, IMG_CHANNEL, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE}, new TVMType(\"float32\"));;\n                    inputNdArray.copyFrom(imgRgbTranValues);\n                    Function setInputFunc = graphExecutorModule.getFunction(\"set_input\");\n                    setInputFunc.pushArg(INPUT_NAME).pushArg(inputNdArray).invoke();\n                    // release tvm local variables\n                    inputNdArray.release();\n                    setInputFunc.release();\n\n                    // get the function from the module(run it)\n                    Log.i(TAG, \"run function on target\");\n                    Function runFunc = graphExecutorModule.getFunction(\"run\");\n                    runFunc.invoke();\n                    // release tvm local variables\n                    runFunc.release();\n\n                    // get the function from the module(get output data)\n                    Log.i(TAG, \"get output data\");\n                    NDArray outputNdArray = NDArray.empty(new long[]{1, 1000}, new TVMType(\"float32\"));\n                    Function getOutputFunc = graphExecutorModule.getFunction(\"get_output\");\n                    getOutputFunc.pushArg(OUTPUT_INDEX).pushArg(outputNdArray).invoke();\n                    float[] output = outputNdArray.asFloatArray();\n                    // release tvm local variables\n                    outputNdArray.release();\n                    getOutputFunc.release();\n\n                    // display the result from extracted output data\n                    if (null != output) {\n                        int maxPosition = -1;\n                        float maxValue = 0;\n                        for (int j = 0; j < output.length; ++j) {\n                            if (output[j] > maxValue) {\n                                maxValue = output[j];\n                                maxPosition = j;\n                            }\n                        }\n                        processingTimeMs = SystemClock.uptimeMillis() - processingTimeMs;\n                        String label = \"Prediction Result : \";\n                        label += labels.size() > maxPosition ? labels.get(maxPosition) : \"unknown\";\n                        label += \"\\nPrediction Time : \" + processingTimeMs + \"ms\";\n                        mResultView.setText(label);\n                    }\n                    Log.i(TAG, \"prediction finished\");\n                }\n                return 0;\n            }\n            return -1;\n        }\n\n        @Override\n        protected void onPreExecute() {\n            dialog.setCancelable(false);\n            dialog.setMessage(\"Prediction running on image...\");\n            dialog.show();\n            super.onPreExecute();\n        }\n\n        @Override\n        protected void onPostExecute(Integer status) {\n            if (dialog != null && dialog.isShowing()) {\n                dialog.dismiss();\n            }\n            if (status != 0) {\n                showDialog(\"Error\", \"Fail to predict image, GraphExecutor exception\");\n            }\n        }\n    }\n\n    @Override\n    protected void onDestroy() {\n        // release tvm local variables\n        if (null != graphExecutorModule)\n            graphExecutorModule.release();\n        super.onDestroy();\n    }\n\n    /**\n     * Read file from assets and return byte array.\n     *\n     * @param assets The asset manager to be used to load assets.\n     * @param fileName The filepath of read file.\n     * @return byte[] file content\n     * @throws IOException\n     */\n    private byte[] getBytesFromFile(AssetManager assets, String fileName) throws IOException {\n        InputStream is = assets.open(fileName);\n        int length = is.available();\n        byte[] bytes = new byte[length];\n        // Read in the bytes\n        int offset = 0;\n        int numRead = 0;\n        try {\n            while (offset < bytes.length\n                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {\n                offset += numRead;\n            }\n        } finally {\n            is.close();\n        }\n        // Ensure all the bytes have been read in\n        if (offset < bytes.length) {\n            throw new IOException(\"Could not completely read file \" + fileName);\n        }\n        return bytes;\n    }\n\n    /**\n     * Dialog show pick option for select image from Gallery or Camera.\n     */\n    private void showPictureDialog(){\n        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);\n        pictureDialog.setTitle(\"Select Action\");\n        String[] pictureDialogItems = {\n                \"Select photo from gallery\",\n                \"Capture photo from camera\" };\n        pictureDialog.setItems(pictureDialogItems,\n                new DialogInterface.OnClickListener() {\n                    @Override\n                    public void onClick(DialogInterface dialog, int which) {\n                        switch (which) {\n                            case 0:\n                                choosePhotoFromGallery();\n                                break;\n                            case 1:\n                                takePhotoFromCamera();\n                                break;\n                        }\n                    }\n                });\n        pictureDialog.show();\n    }\n\n    /**\n     * Request to pick image from Gallery.\n     */\n    public void choosePhotoFromGallery() {\n        Intent galleryIntent = new Intent(Intent.ACTION_PICK,\n                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);\n\n        startActivityForResult(galleryIntent, PICTURE_FROM_GALLERY);\n    }\n\n    /**\n     * Request to capture image from Camera.\n     */\n    private void takePhotoFromCamera() {\n        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);\n\n        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {\n            mCameraImageUri = Uri.fromFile(createImageFile());\n        } else {\n            File file = new File(createImageFile().getPath());\n            mCameraImageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + \".provider\", file);\n        }\n\n        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri);\n        startActivityForResult(intent, PICTURE_FROM_CAMERA);\n    }\n\n    @Override\n    public void onActivityResult(int requestCode, int resultCode, Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n        if (resultCode == this.RESULT_CANCELED) {\n            return;\n        }\n        Uri contentURI = null;\n        if (requestCode == PICTURE_FROM_GALLERY) {\n            if (data != null) {\n                contentURI = data.getData();\n            }\n        } else if (requestCode == PICTURE_FROM_CAMERA) {\n            contentURI = mCameraImageUri;\n        }\n        if (null != contentURI) {\n            try {\n                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);\n                Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_PREVIEW_HEIGHT, IMAGE_PREVIEW_WIDTH, true);\n                mImageView.setImageBitmap(scaled);\n                new ModelRunAsyncTask().execute(scaled);\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n    /**\n     * Get application cache path where to place compiled functions.\n     *\n     * @param fileName library file name.\n     * @return String application cache folder path\n     * @throws IOException\n     */\n    private final String getTempLibFilePath(String fileName) throws IOException {\n        File tempDir = File.createTempFile(\"tvm4j_demo_\", \"\");\n        if (!tempDir.delete() || !tempDir.mkdir()) {\n            throw new IOException(\"Couldn't create directory \" + tempDir.getAbsolutePath());\n        }\n        return (tempDir + File.separator + fileName);\n    }\n\n    /**\n     * Create image file under storage where camera application save captured image.\n     *\n     * @return File image file under sdcard where camera can save image\n     */\n    private File createImageFile() {\n        // Create an image file name\n        String timeStamp = new SimpleDateFormat(\"yyyyMMdd_HHmmss\", Locale.US).format(new Date());\n        String imageFileName = \"JPEG_\" + timeStamp + \"_\";\n        File storageDir = Environment.getExternalStoragePublicDirectory(\n                Environment.DIRECTORY_PICTURES);\n        try {\n            File image = File.createTempFile(\n                    imageFileName,  // prefix\n                    \".jpg\",         // suffix\n                    storageDir      // directory\n            );\n            return image;\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n\n    /**\n     * Show dialog to user.\n     *\n     * @param title dialog display title\n     * @param msg dialog display message\n     */\n    private void showDialog(String title, String msg) {\n        AlertDialog.Builder builder = new AlertDialog.Builder(this);\n        builder.setTitle(title);\n        builder.setMessage(msg);\n        builder.setCancelable(true);\n        builder.setNeutralButton(android.R.string.ok,\n                new DialogInterface.OnClickListener() {\n                    public void onClick(DialogInterface dialog, int id) {\n                        dialog.cancel();\n                        finish();\n                    }\n                });\n        builder.create().show();\n    }\n\n    @Override\n    public void onRequestPermissionsResult (final int requestCode, final String[] permissions, final int[] grantResults){\n        super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n        if (requestCode == PERMISSIONS_REQUEST) {\n            if (grantResults.length > 0\n                    && grantResults[0] == PackageManager.PERMISSION_GRANTED\n                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {\n                // instantiate tvm runtime and setup environment on background after application begin\n                new LoadModleAsyncTask().execute();\n            } else {\n                requestPermission();\n            }\n        }\n    }\n\n    /**\n     * Whether application has required mandatory permissions to run.\n     */\n    private boolean hasPermission() {\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n            return checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&\n                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;\n        } else {\n            return true;\n        }\n    }\n\n    /**\n     * Request required mandatory permission for application to run.\n     */\n    private void requestPermission() {\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n            if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) ||\n                    shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {\n                Toast.makeText(this,\n                        \"Camera AND storage permission are required for this demo\", Toast.LENGTH_LONG).show();\n            }\n            requestPermissions(new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST);\n        }\n    }\n\n    /**\n     * Returns a transformation matrix from one reference frame into another.\n     * Handles cropping (if maintaining aspect ratio is desired) and rotation.\n     *\n     * @param srcWidth Width of source frame.\n     * @param srcHeight Height of source frame.\n     * @param dstWidth Width of destination frame.\n     * @param dstHeight Height of destination frame.\n     * @param applyRotation Amount of rotation to apply from one frame to another.\n     *  Must be a multiple of 90.\n     * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant,\n     * cropping the image if necessary.\n     * @return The transformation fulfilling the desired requirements.\n     */\n    public static Matrix getTransformationMatrix(\n            final int srcWidth,\n            final int srcHeight,\n            final int dstWidth,\n            final int dstHeight,\n            final int applyRotation,\n            final boolean maintainAspectRatio) {\n        final Matrix matrix = new Matrix();\n\n        if (applyRotation != 0) {\n            if (applyRotation % 90 != 0) {\n                Log.w(TAG, \"Rotation of %d % 90 != 0 \" + applyRotation);\n            }\n\n            // Translate so center of image is at origin.\n            matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);\n\n            // Rotate around origin.\n            matrix.postRotate(applyRotation);\n        }\n\n        // Account for the already applied rotation, if any, and then determine how\n        // much scaling is needed for each axis.\n        final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;\n\n        final int inWidth = transpose ? srcHeight : srcWidth;\n        final int inHeight = transpose ? srcWidth : srcHeight;\n\n        // Apply scaling if necessary.\n        if (inWidth != dstWidth || inHeight != dstHeight) {\n            final float scaleFactorX = dstWidth / (float) inWidth;\n            final float scaleFactorY = dstHeight / (float) inHeight;\n\n            if (maintainAspectRatio) {\n                // Scale by minimum factor so that dst is filled completely while\n                // maintaining the aspect ratio. Some image may fall off the edge.\n                final float scaleFactor = Math.max(scaleFactorX, scaleFactorY);\n                matrix.postScale(scaleFactor, scaleFactor);\n            } else {\n                // Scale exactly to fill dst from src.\n                matrix.postScale(scaleFactorX, scaleFactorY);\n            }\n        }\n\n        if (applyRotation != 0) {\n            // Translate back from origin centered reference to destination frame.\n            matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);\n        }\n\n        return matrix;\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_deploy/app/src/main/jni/tvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm_runtime.h\n * \\brief Pack all tvm runtime source files\n */\n#include <sys/stat.h>\n\n#include <fstream>\n\n#define DMLC_USE_LOGGING_LIBRARY <tvm/runtime/logging.h>\n#define TVM_USE_LIBBACKTRACE 0\n\n#include \"../src/runtime/c_runtime_api.cc\"\n#include \"../src/runtime/cpu_device_api.cc\"\n#include \"../src/runtime/dso_library.cc\"\n#include \"../src/runtime/file_utils.cc\"\n#include \"../src/runtime/graph_executor/graph_executor.cc\"\n#include \"../src/runtime/library_module.cc\"\n#include \"../src/runtime/logging.cc\"\n#include \"../src/runtime/module.cc\"\n#include \"../src/runtime/ndarray.cc\"\n#include \"../src/runtime/object.cc\"\n#include \"../src/runtime/registry.cc\"\n#include \"../src/runtime/system_library.cc\"\n#include \"../src/runtime/thread_pool.cc\"\n#include \"../src/runtime/threading_backend.cc\"\n#include \"../src/runtime/workspace_pool.cc\"\n\n#ifdef TVM_OPENCL_RUNTIME\n#include \"../src/runtime/opencl/opencl_device_api.cc\"\n#include \"../src/runtime/opencl/opencl_module.cc\"\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/app/src/main/java/org/apache/tvm/tvmrpc/MainActivity.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.tvmrpc;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.Toolbar;\nimport android.widget.CompoundButton;\nimport android.widget.EditText;\nimport androidx.appcompat.widget.SwitchCompat;\nimport android.content.Intent;\n\n\npublic class MainActivity extends AppCompatActivity {\n  // wait time before automatic restart of RPC Activity\n  public static final int HANDLER_RESTART_DELAY = 5000;\n\n  private void showDialog(String title, String msg) {\n    AlertDialog.Builder builder = new AlertDialog.Builder(this);\n    builder.setTitle(title);\n    builder.setMessage(msg);\n    builder.setCancelable(true);\n    builder.setNeutralButton(android.R.string.ok,\n        new DialogInterface.OnClickListener() {\n          public void onClick(DialogInterface dialog, int id) {\n            dialog.cancel();\n          }\n        });\n    builder.create().show();\n  }\n\n  public Intent updateRPCPrefs() {\n    System.err.println(\"updating preferences...\");\n    EditText edProxyAddress = findViewById(R.id.input_address);\n    EditText edProxyPort = findViewById(R.id.input_port);\n    EditText edAppKey = findViewById(R.id.input_key);\n    SwitchCompat inputSwitch =  findViewById(R.id.switch_persistent);\n\n    final String proxyHost = edProxyAddress.getText().toString();\n    final int proxyPort = Integer.parseInt(edProxyPort.getText().toString());\n    final String key = edAppKey.getText().toString();\n    final boolean isChecked = inputSwitch.isChecked();\n\n    SharedPreferences pref = getApplicationContext().getSharedPreferences(\"RPCProxyPreference\", Context.MODE_PRIVATE);\n    SharedPreferences.Editor editor = pref.edit();\n    editor.putString(\"input_address\", proxyHost);\n    editor.putString(\"input_port\", edProxyPort.getText().toString());\n    editor.putString(\"input_key\", key);\n    editor.putBoolean(\"input_switch\", isChecked);\n    editor.commit();\n\n    Intent intent = new Intent(this, RPCActivity.class);\n    intent.putExtra(\"host\", proxyHost);\n    intent.putExtra(\"port\", proxyPort);\n    intent.putExtra(\"key\", key);\n    return intent;\n  }\n\n  private void setupRelaunch() {\n    final Context context = this;\n    final SwitchCompat switchPersistent = findViewById(R.id.switch_persistent);\n    final Runnable rPCStarter = new Runnable() {\n        public void run() {\n            if (switchPersistent.isChecked()) {\n              System.err.println(\"relaunching RPC activity...\");\n              Intent intent = ((MainActivity) context).updateRPCPrefs();\n              startActivity(intent);\n            }\n        }\n    };\n\n    Handler handler = new Handler(Looper.getMainLooper());\n    handler.postDelayed(rPCStarter, HANDLER_RESTART_DELAY);\n  }\n\n  @Override\n  protected void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.activity_main);\n    Toolbar toolbar = findViewById(R.id.toolbar);\n    setSupportActionBar(toolbar);\n    final Context context = this;\n\n    SwitchCompat switchPersistent = findViewById(R.id.switch_persistent);\n    switchPersistent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n      @Override\n      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n        if (isChecked) {\n          System.err.println(\"automatic RPC restart enabled...\");\n          updateRPCPrefs();\n          setupRelaunch();\n        } else {\n          System.err.println(\"automatic RPC restart disabled...\");\n          updateRPCPrefs();\n        }\n      }\n    });\n\n    enableInputView(true);\n  }\n\n  @Override\n  protected void onResume() {\n    System.err.println(\"MainActivity onResume...\");\n    enableInputView(true);\n    setupRelaunch();\n    super.onResume();\n  }\n\n  @Override\n  protected void onDestroy() {\n    super.onDestroy();\n  }\n\n  private void enableInputView(boolean enable) {\n    EditText edProxyAddress = findViewById(R.id.input_address);\n    EditText edProxyPort = findViewById(R.id.input_port);\n    EditText edAppKey = findViewById(R.id.input_key);\n    SwitchCompat input_switch = findViewById(R.id.switch_persistent);\n    edProxyAddress.setEnabled(enable);\n    edProxyPort.setEnabled(enable);\n    edAppKey.setEnabled(enable);\n\n    if (enable) {\n    SharedPreferences pref = getApplicationContext().getSharedPreferences(\"RPCProxyPreference\", Context.MODE_PRIVATE);\n    String inputAddress = pref.getString(\"input_address\", null);\n    if (null != inputAddress)\n        edProxyAddress.setText(inputAddress);\n    String inputPort = pref.getString(\"input_port\", null);\n    if (null != inputPort)\n        edProxyPort.setText(inputPort);\n    String inputKey = pref.getString(\"input_key\", null);\n    if (null != inputKey)\n        edAppKey.setText(inputKey);\n    boolean isChecked = pref.getBoolean(\"input_switch\", false);\n    input_switch.setChecked(isChecked);\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/app/src/main/java/org/apache/tvm/tvmrpc/RPCActivity.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.tvmrpc;\n\nimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.widget.Button;\nimport android.view.View;\n\npublic class RPCActivity extends AppCompatActivity {\n  private RPCProcessor tvmServerWorker;\n\n  @Override\n  protected void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.activity_rpc);\n\n    Button stopRPC = findViewById(R.id.button_stop_rpc);\n    stopRPC.setOnClickListener(new View.OnClickListener() {\n        public void onClick(View v) {\n            System.err.println(tvmServerWorker == null);\n            if (tvmServerWorker != null) {\n                // currently will raise a socket closed exception\n                tvmServerWorker.disconnect();\n            }\n            finish();\n            // prevent Android from recycling the process\n            System.exit(0);\n        }\n    });\n\n    System.err.println(\"rpc activity onCreate...\");\n    Intent intent = getIntent();\n    String host = intent.getStringExtra(\"host\");\n    int port = intent.getIntExtra(\"port\", 9090);\n    String key = intent.getStringExtra(\"key\");\n\n    tvmServerWorker = new RPCProcessor(this);\n    tvmServerWorker.setDaemon(true);\n    tvmServerWorker.start();\n    tvmServerWorker.connect(host, port, key);\n  }\n\n  @Override\n  protected void onDestroy() {\n    System.err.println(\"rpc activity onDestroy\");\n    tvmServerWorker.disconnect();\n    super.onDestroy();\n    android.os.Process.killProcess(android.os.Process.myPid());\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/app/src/main/java/org/apache/tvm/tvmrpc/RPCAndroidWatchdog.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.tvmrpc;\n\nimport android.app.Activity;\nimport org.apache.tvm.rpc.RPCWatchdog;\n\n/**\n * Watchdog for Android RPC.\n */\npublic class RPCAndroidWatchdog extends RPCWatchdog {\n  public Activity rpc_activity = null;\n  public RPCAndroidWatchdog(Activity activity) {\n    super();\n    rpc_activity = activity;\n  }\n\n  /**\n   * Method to non-destructively terminate the running thread on Android\n   */\n  @Override protected void terminate() {\n    rpc_activity.finish();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/app/src/main/java/org/apache/tvm/tvmrpc/RPCProcessor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.tvmrpc;\n\nimport android.app.Activity;\nimport android.os.ParcelFileDescriptor;\nimport java.net.Socket;\nimport org.apache.tvm.rpc.ConnectTrackerServerProcessor;\n\n/**\n * Connect to RPC proxy and deal with requests.\n */\nclass RPCProcessor extends Thread {\n  private String host;\n  private int port;\n  private String key;\n  private boolean running = false;\n  private long startTime;\n  private ConnectTrackerServerProcessor currProcessor;\n  private boolean first = true;\n  private Activity rpc_activity = null;\n\n  public RPCProcessor(Activity activity) {\n    super();\n    rpc_activity = activity;\n  }\n\n  @Override public void run() {\n    RPCAndroidWatchdog watchdog = new RPCAndroidWatchdog(rpc_activity);\n    watchdog.start();\n    while (true) {\n      synchronized (this) {\n        currProcessor = null;\n        while (!running) {\n          try {\n            this.wait();\n          } catch (InterruptedException e) {\n          }\n        }\n        try {\n          currProcessor = new ConnectTrackerServerProcessor(host, port, key, watchdog);\n        } catch (Throwable e) {\n          e.printStackTrace();\n          // kill if creating a new processor failed\n          System.exit(0);\n        }\n      }\n      if (currProcessor != null)\n        currProcessor.run();\n      watchdog.finishTimeout();\n    }\n  }\n\n  /**\n   * Disconnect from the proxy server.\n   */\n  synchronized void disconnect() {\n    if (running) {\n      running = false;\n      if (currProcessor != null) {\n        currProcessor.terminate();\n      }\n    }\n  }\n\n  /**\n   * Start rpc processor and connect to the proxy server.\n   * @param host proxy server host.\n   * @param port proxy server port.\n   * @param key proxy server key.\n   */\n  synchronized void connect(String host, int port, String key) {\n    this.host = host;\n    this.port = port;\n    this.key = key;\n    running = true;\n    this.notify();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/app/src/main/jni/tvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm_runtime.h\n * \\brief Pack all tvm runtime source files\n */\n#include <sys/stat.h>\n\n#include <fstream>\n\n#define DMLC_USE_LOGGING_LIBRARY <tvm/runtime/logging.h>\n#define TVM_USE_LIBBACKTRACE 0\n/* Enable custom logging - this will cause TVM to use a custom implementation\n * of tvm::runtime::detail::LogMessage. We use this to pass TVM log messages to\n * Android logcat.\n */\n#define TVM_LOG_CUSTOMIZE 1\n\n#include \"../src/runtime/c_runtime_api.cc\"\n#include \"../src/runtime/container.cc\"\n#include \"../src/runtime/cpu_device_api.cc\"\n#include \"../src/runtime/dso_library.cc\"\n#include \"../src/runtime/file_utils.cc\"\n#include \"../src/runtime/graph_executor/graph_executor.cc\"\n#include \"../src/runtime/graph_executor/graph_executor_factory.cc\"\n#include \"../src/runtime/library_module.cc\"\n#include \"../src/runtime/logging.cc\"\n#include \"../src/runtime/minrpc/minrpc_logger.cc\"\n#include \"../src/runtime/module.cc\"\n#include \"../src/runtime/ndarray.cc\"\n#include \"../src/runtime/object.cc\"\n#include \"../src/runtime/profiling.cc\"\n#include \"../src/runtime/registry.cc\"\n#include \"../src/runtime/rpc/rpc_channel.cc\"\n#include \"../src/runtime/rpc/rpc_endpoint.cc\"\n#include \"../src/runtime/rpc/rpc_event_impl.cc\"\n#include \"../src/runtime/rpc/rpc_local_session.cc\"\n#include \"../src/runtime/rpc/rpc_module.cc\"\n#include \"../src/runtime/rpc/rpc_server_env.cc\"\n#include \"../src/runtime/rpc/rpc_session.cc\"\n#include \"../src/runtime/rpc/rpc_socket_impl.cc\"\n#include \"../src/runtime/system_library.cc\"\n#include \"../src/runtime/thread_pool.cc\"\n#include \"../src/runtime/threading_backend.cc\"\n#include \"../src/runtime/workspace_pool.cc\"\n\n#ifdef TVM_OPENCL_RUNTIME\n#include \"../src/runtime/opencl/opencl_device_api.cc\"\n#include \"../src/runtime/opencl/opencl_module.cc\"\n#include \"../src/runtime/opencl/texture_pool.cc\"\n#include \"../src/runtime/source_utils.cc\"\n#endif\n\n#ifdef TVM_VULKAN_RUNTIME\n#include \"../src/runtime/vulkan/vulkan_buffer.cc\"\n#include \"../src/runtime/vulkan/vulkan_common.cc\"\n#include \"../src/runtime/vulkan/vulkan_device.cc\"\n#include \"../src/runtime/vulkan/vulkan_device_api.cc\"\n#include \"../src/runtime/vulkan/vulkan_instance.cc\"\n#include \"../src/runtime/vulkan/vulkan_module.cc\"\n#include \"../src/runtime/vulkan/vulkan_stream.cc\"\n#include \"../src/runtime/vulkan/vulkan_wrapped_func.cc\"\n#endif\n\n#ifdef USE_SORT\n#include \"../src/runtime/contrib/sort/sort.cc\"\n#endif\n\n#ifdef USE_RANDOM\n#include \"../src/runtime/contrib/random/random.cc\"\n#endif\n\n#include <android/log.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace detail {\n// Override logging mechanism\n[[noreturn]] void LogFatalImpl(const std::string& file, int lineno, const std::string& message) {\n  std::string m = file + \":\" + std::to_string(lineno) + \": \" + message;\n  __android_log_write(ANDROID_LOG_FATAL, \"TVM_RUNTIME\", m.c_str());\n  throw InternalError(file, lineno, message);\n}\nvoid LogMessageImpl(const std::string& file, int lineno, int level, const std::string& message) {\n  std::string m = file + \":\" + std::to_string(lineno) + \": \" + message;\n  __android_log_write(ANDROID_LOG_DEBUG + level, \"TVM_RUNTIME\", m.c_str());\n}\n\n}  // namespace detail\n}  // namespace runtime\n}  // namespace tvm\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/android_rpc/tests/android_rpc_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testcode for Android RPC.\n\nTo use it, start an RPC tracker with \"python -m tvm.exec.rpc_tracker\".\nUse the tracker's address and port when configuring the RPC app.\nUse \"android\" as the key if you wish to avoid modifying this script.\n\"\"\"\n\nimport tvm\nfrom tvm import te\nimport os\nfrom tvm import rpc\nfrom tvm.contrib import utils, ndk\nimport numpy as np\n\n# Set to be address of tvm proxy.\ntracker_host = os.environ[\"TVM_TRACKER_HOST\"]\ntracker_port = int(os.environ[\"TVM_TRACKER_PORT\"])\nkey = \"android\"\n\n# Change target configuration.\n# Run `adb shell cat /proc/cpuinfo` to find the arch.\narch = \"arm64\"\ntarget = \"llvm -mtriple=%s-linux-android\" % arch\n\n# whether enable to execute test on OpenCL target\ntest_opencl = False\n# whether enable to execute test on Vulkan target\ntest_vulkan = False\n\n\ndef test_rpc_module():\n    # graph\n    n = tvm.runtime.convert(1024)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    a_np = np.random.uniform(size=1024).astype(A.dtype)\n    temp = utils.tempdir()\n\n    # Establish remote connection with target hardware\n    tracker = rpc.connect_tracker(tracker_host, tracker_port)\n    remote = tracker.request(key, priority=0, session_timeout=60)\n\n    # Compile the Graph for CPU target\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=64)\n    s[B].parallel(xi)\n    s[B].pragma(xo, \"parallel_launch_point\")\n    s[B].pragma(xi, \"parallel_barrier_when_finish\")\n    f = tvm.build(s, [A, B], target, name=\"myadd_cpu\")\n    path_dso_cpu = temp.relpath(\"cpu_lib.so\")\n    f.export_library(path_dso_cpu, ndk.create_shared)\n\n    # Execute the portable graph on cpu target\n    print(\"Run CPU test ...\")\n    dev = remote.cpu(0)\n    remote.upload(path_dso_cpu)\n    f2 = remote.load_module(\"cpu_lib.so\")\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n    time_f = f2.time_evaluator(f2.entry_name, dev, number=10)\n    cost = time_f(a, b).mean\n    print(\"%g secs/op\\n\" % cost)\n    np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    # Compile the Graph for OpenCL target\n    if test_opencl:\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=64)\n        s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n        s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n        # Build the dynamic lib.\n        # If we don't want to do metal and only use cpu, just set target to be target\n        f = tvm.build(s, [A, B], tvm.target.Target(\"opencl\", host=target), name=\"myadd\")\n        path_dso_cl = temp.relpath(\"dev_lib_cl.so\")\n        f.export_library(path_dso_cl, ndk.create_shared)\n\n        print(\"Run GPU(OpenCL Flavor) test ...\")\n        dev = remote.cl(0)\n        remote.upload(path_dso_cl)\n        f1 = remote.load_module(\"dev_lib_cl.so\")\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n        time_f = f1.time_evaluator(f1.entry_name, dev, number=10)\n        cost = time_f(a, b).mean\n        print(\"%g secs/op\\n\" % cost)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    # Compile the Graph for Vulkan target\n    if test_vulkan:\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=64)\n        s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n        s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n        # Build the dynamic lib.\n        # If we don't want to do metal and only use cpu, just set target to be target\n        f = tvm.build(s, [A, B], tvm.target.Target(\"vulkan\", host=target), name=\"myadd\")\n        path_dso_vulkan = temp.relpath(\"dev_lib_vulkan.so\")\n        f.export_library(path_dso_vulkan, ndk.create_shared)\n\n        print(\"Run GPU(Vulkan Flavor) test ...\")\n        dev = remote.vulkan(0)\n        remote.upload(path_dso_vulkan)\n        f1 = remote.load_module(\"dev_lib_vulkan.so\")\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n        time_f = f1.time_evaluator(f1.entry_name, dev, number=10)\n        cost = time_f(a, b).mean\n        print(\"%g secs/op\\n\" % cost)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n\nif __name__ == \"__main__\":\n    test_rpc_module()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/benchmark/arm_cpu_imagenet_bench.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Benchmark script for ImageNet models on ARM CPU.\nsee README.md for the usage and results of this script.\n\"\"\"\nimport argparse\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib.utils import tempdir\nimport tvm.contrib.graph_executor as runtime\nfrom tvm import relay\n\nfrom util import get_network, print_progress\n\n\ndef evaluate_network(network, target, target_host, repeat):\n    # connect to remote device\n    tracker = tvm.rpc.connect_tracker(args.host, args.port)\n    remote = tracker.request(args.rpc_key)\n\n    print_progress(network)\n    net, params, input_shape, output_shape = get_network(network, batch_size=1)\n\n    print_progress(\"%-20s building...\" % network)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(net, target=tvm.target.Target(target, host=target_host), params=params)\n\n    tmp = tempdir()\n    if \"android\" in str(target):\n        from tvm.contrib import ndk\n\n        filename = \"%s.so\" % network\n        lib.export_library(tmp.relpath(filename), ndk.create_shared)\n    else:\n        filename = \"%s.tar\" % network\n        lib.export_library(tmp.relpath(filename))\n\n    # upload library and params\n    print_progress(\"%-20s uploading...\" % network)\n    dev = remote.device(str(target), 0)\n    remote.upload(tmp.relpath(filename))\n\n    rlib = remote.load_module(filename)\n    module = runtime.GraphModule(rlib[\"default\"](dev))\n    data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n    module.set_input(\"data\", data_tvm)\n\n    # evaluate\n    print_progress(\"%-20s evaluating...\" % network)\n    ftimer = module.module.time_evaluator(\"run\", dev, number=1, repeat=repeat)\n    prof_res = np.array(ftimer().results) * 1000  # multiply 1000 for converting to millisecond\n    print(\n        \"%-20s %-19s (%s)\" % (network, \"%.2f ms\" % np.mean(prof_res), \"%.2f ms\" % np.std(prof_res))\n    )\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--network\",\n        type=str,\n        choices=[\n            \"resnet-18\",\n            \"resnet-34\",\n            \"resnet-50\",\n            \"vgg-16\",\n            \"vgg-19\",\n            \"densenet-121\",\n            \"inception_v3\",\n            \"mobilenet\",\n            \"squeezenet_v1.0\",\n            \"squeezenet_v1.1\",\n        ],\n        help=\"The name of neural network\",\n    )\n    parser.add_argument(\n        \"--model\",\n        type=str,\n        choices=[\"rk3399\", \"mate10\", \"mate10pro\", \"p20\", \"p20pro\", \"pixel2\", \"rasp3b\", \"pynq\"],\n        default=\"rk3399\",\n        help=\"The model of the test device. If your device is not listed in \"\n        \"the choices list, pick the most similar one as argument.\",\n    )\n    parser.add_argument(\"--host\", type=str, default=\"127.0.0.1\")\n    parser.add_argument(\"--port\", type=int, default=9190)\n    parser.add_argument(\"--rpc-key\", type=str, required=True)\n    parser.add_argument(\"--repeat\", type=int, default=10)\n    args = parser.parse_args()\n\n    dtype = \"float32\"\n\n    if args.network is None:\n        networks = [\"squeezenet_v1.1\", \"mobilenet\", \"resnet-18\", \"vgg-16\"]\n    else:\n        networks = [args.network]\n\n    target = tvm.target.arm_cpu(model=args.model)\n    target_host = None\n\n    print(\"--------------------------------------------------\")\n    print(\"%-20s %-20s\" % (\"Network Name\", \"Mean Inference Time (std dev)\"))\n    print(\"--------------------------------------------------\")\n    for network in networks:\n        evaluate_network(network, target, target_host, args.repeat)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/benchmark/gpu_imagenet_bench.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Benchmark script for ImageNet models on GPU.\nsee README.md for the usage and results of this script.\n\"\"\"\nimport argparse\nimport threading\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nimport tvm.contrib.graph_executor as runtime\nfrom tvm import relay\n\nfrom util import get_network\n\n\ndef benchmark(network, target):\n    net, params, input_shape, output_shape = get_network(network, batch_size=1)\n\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(net, target=target, params=params)\n\n    # create runtime\n    dev = tvm.device(str(target), 0)\n    module = runtime.GraphModule(lib[\"default\"](dev))\n    data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n    module.set_input(\"data\", data_tvm)\n\n    # evaluate\n    ftimer = module.module.time_evaluator(\"run\", dev, number=1, repeat=args.repeat)\n    prof_res = np.array(ftimer().results) * 1000  # multiply 1000 for converting to millisecond\n    print(\n        \"%-20s %-19s (%s)\" % (network, \"%.2f ms\" % np.mean(prof_res), \"%.2f ms\" % np.std(prof_res))\n    )\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--network\",\n        type=str,\n        choices=[\n            \"resnet-18\",\n            \"resnet-34\",\n            \"resnet-50\",\n            \"vgg-16\",\n            \"vgg-19\",\n            \"densenet-121\",\n            \"inception_v3\",\n            \"mobilenet\",\n            \"squeezenet_v1.0\",\n            \"squeezenet_v1.1\",\n        ],\n        help=\"The name of neural network\",\n    )\n    parser.add_argument(\n        \"--device\",\n        type=str,\n        choices=[\"amd_apu\"],\n        default=\"amd_apu\",\n        help=\"The name of the test device. If your device is not listed in \"\n        \"the choices list, pick the most similar one as argument.\",\n    )\n    parser.add_argument(\n        \"--model\",\n        type=str,\n        choices=[\"1080ti\", \"titanx\", \"tx2\", \"gfx900\", \"v1000\"],\n        default=\"1080ti\",\n        help=\"The model of the test device. If your device is not listed in \"\n        \"the choices list, pick the most similar one as argument.\",\n    )\n    parser.add_argument(\"--repeat\", type=int, default=600)\n    parser.add_argument(\n        \"--target\",\n        type=str,\n        choices=[\"cuda\", \"opencl\", \"rocm\", \"nvptx\", \"metal\", \"vulkan\"],\n        default=\"cuda\",\n        help=\"The tvm compilation target\",\n    )\n    parser.add_argument(\"--thread\", type=int, default=1, help=\"The number of threads to be run.\")\n    args = parser.parse_args()\n\n    dtype = \"float32\"\n\n    if args.network is None:\n        networks = [\"resnet-50\", \"mobilenet\", \"vgg-19\", \"inception_v3\"]\n    else:\n        networks = [args.network]\n\n    target = tvm.target.Target(\"%s -device=%s -model=%s\" % (args.target, args.device, args.model))\n\n    print(\"--------------------------------------------------\")\n    print(\"%-20s %-20s\" % (\"Network Name\", \"Mean Inference Time (std dev)\"))\n    print(\"--------------------------------------------------\")\n    for network in networks:\n        if args.thread == 1:\n            benchmark(network, target)\n        else:\n            threads = list()\n            for n in range(args.thread):\n                thread = threading.Thread(\n                    target=benchmark, args=([network, target]), name=\"thread%d\" % n\n                )\n                threads.append(thread)\n\n            for thread in threads:\n                thread.start()\n\n            for thread in threads:\n                thread.join()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/benchmark/mobile_gpu_imagenet_bench.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Benchmark script for ImageNet models on mobile GPU.\nsee README.md for the usage and results of this script.\n\"\"\"\nimport argparse\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib.utils import tempdir\nimport tvm.contrib.graph_executor as runtime\nfrom tvm import relay\n\nfrom util import get_network, print_progress\n\n\ndef evaluate_network(network, target, target_host, dtype, repeat):\n    # connect to remote device\n    tracker = tvm.rpc.connect_tracker(args.host, args.port)\n    remote = tracker.request(args.rpc_key)\n\n    print_progress(network)\n    net, params, input_shape, output_shape = get_network(network, batch_size=1, dtype=dtype)\n\n    print_progress(\"%-20s building...\" % network)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(net, target=tvm.target.Target(target, host=target_host), params=params)\n\n    tmp = tempdir()\n    if \"android\" in str(target) or \"android\" in str(target_host):\n        from tvm.contrib import ndk\n\n        filename = \"%s.so\" % network\n        lib.export_library(tmp.relpath(filename), ndk.create_shared)\n    else:\n        filename = \"%s.tar\" % network\n        lib.export_library(tmp.relpath(filename))\n\n    # upload library and params\n    print_progress(\"%-20s uploading...\" % network)\n    dev = remote.device(str(target), 0)\n    remote.upload(tmp.relpath(filename))\n\n    rlib = remote.load_module(filename)\n    module = runtime.GraphModule(rlib[\"default\"](dev))\n    data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n    module.set_input(\"data\", data_tvm)\n\n    # evaluate\n    print_progress(\"%-20s evaluating...\" % network)\n    ftimer = module.module.time_evaluator(\"run\", dev, number=1, repeat=repeat)\n    prof_res = np.array(ftimer().results) * 1000  # multiply 1000 for converting to millisecond\n    print(\n        \"%-20s %-19s (%s)\" % (network, \"%.2f ms\" % np.mean(prof_res), \"%.2f ms\" % np.std(prof_res))\n    )\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--network\",\n        type=str,\n        choices=[\n            \"resnet-18\",\n            \"resnet-34\",\n            \"resnet-50\",\n            \"vgg-16\",\n            \"vgg-19\",\n            \"densenet-121\",\n            \"inception_v3\",\n            \"mobilenet\",\n            \"squeezenet_v1.0\",\n            \"squeezenet_v1.1\",\n        ],\n        help=\"The name of neural network\",\n    )\n    parser.add_argument(\n        \"--model\",\n        type=str,\n        choices=[\"rk3399\"],\n        default=\"rk3399\",\n        help=\"The model of the test device. If your device is not listed in \"\n        \"the choices list, pick the most similar one as argument.\",\n    )\n    parser.add_argument(\"--host\", type=str, default=\"127.0.0.1\")\n    parser.add_argument(\"--port\", type=int, default=9190)\n    parser.add_argument(\"--rpc-key\", type=str, required=True)\n    parser.add_argument(\"--repeat\", type=int, default=30)\n    parser.add_argument(\"--dtype\", type=str, default=\"float32\")\n    args = parser.parse_args()\n\n    if args.network is None:\n        networks = [\"squeezenet_v1.1\", \"mobilenet\", \"resnet-18\", \"vgg-16\"]\n    else:\n        networks = [args.network]\n\n    target = tvm.target.mali(model=args.model)\n    target_host = tvm.target.arm_cpu(model=args.model)\n\n    print(\"--------------------------------------------------\")\n    print(\"%-20s %-20s\" % (\"Network Name\", \"Mean Inference Time (std dev)\"))\n    print(\"--------------------------------------------------\")\n\n    for network in networks:\n        evaluate_network(network, target, target_host, args.dtype, args.repeat)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/benchmark/util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility for benchmark\"\"\"\n\nimport sys\nfrom tvm import relay\nfrom tvm.relay import testing\n\n\ndef get_network(name, batch_size, dtype=\"float32\"):\n    \"\"\"Get the symbol definition and random weight of a network\n\n    Parameters\n    ----------\n    name: str\n        The name of the network, can be 'resnet-18', 'resnet-50', 'vgg-16', 'inception_v3', 'mobilenet', ...\n    batch_size: int\n        batch size\n    dtype: str\n        Data type\n\n    Returns\n    -------\n    net: tvm.IRModule\n        The relay function of network definition\n    params: dict\n        The random parameters for benchmark\n    input_shape: tuple\n        The shape of input tensor\n    output_shape: tuple\n        The shape of output tensor\n    \"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n    output_shape = (batch_size, 1000)\n\n    if name == \"mobilenet\":\n        net, params = testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299)\n        net, params = testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif \"resnet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        net, params = testing.resnet.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"vgg\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        net, params = testing.vgg.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"densenet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        net, params = testing.densenet.get_workload(\n            densenet_size=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"squeezenet\" in name:\n        version = name.split(\"_v\")[1]\n        net, params = testing.squeezenet.get_workload(\n            batch_size=batch_size, version=version, dtype=dtype\n        )\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        net, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = net[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        net = tvm.IRModule.from_expr(net)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return net, params, input_shape, output_shape\n\n\ndef print_progress(msg):\n    \"\"\"print progress message\n\n    Parameters\n    ----------\n    msg: str\n        The message to print\n    \"\"\"\n    sys.stdout.write(msg + \"\\r\")\n    sys.stdout.flush()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/backtrace.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#define _GNU_SOURCE\n#include \"backtrace.h\"\n\n#include <dlfcn.h>\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nconst char* g_argv0 = NULL;\n\nvoid tvm_platform_abort_backtrace() {\n  void* trace[200];\n  int nptrs = backtrace(trace, sizeof(trace) / sizeof(void*));\n  fprintf(stderr, \"backtrace: %d\\n\", nptrs);\n  if (nptrs < 0) {\n    perror(\"backtracing\");\n  } else {\n    backtrace_symbols_fd(trace, nptrs, STDOUT_FILENO);\n\n    char cmd_buf[1024];\n    for (int i = 0; i < nptrs; i++) {\n      Dl_info info;\n      if (dladdr(trace[i], &info)) {\n        fprintf(stderr, \"symbol %d: %s %s %p (%p)\\n\", i, info.dli_sname, info.dli_fname,\n                info.dli_fbase, (void*)(trace[i] - info.dli_fbase));\n        snprintf(cmd_buf, sizeof(cmd_buf), \"addr2line --exe=%s -p -i -a -f %p\", g_argv0,\n                 (void*)(trace[i] - info.dli_fbase));\n        int result = system(cmd_buf);\n        if (result < 0) {\n          perror(\"invoking backtrace command\");\n        }\n      } else {\n        fprintf(stderr, \"symbol %d: %p (unmapped)\\n\", i, trace[i]);\n      }\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/backtrace.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nextern const char* g_argv0;\n\nvoid tvm_platform_abort_backtrace(void);\n\n#ifdef __cplusplus\n}\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/build_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Creates a simple TVM modules.\"\"\"\n\nimport argparse\nimport os\nfrom tvm import relay\nimport tvm\nfrom tvm import runtime as tvm_runtime\nimport logging\nfrom tvm.relay.backend import Runtime\nfrom tvm.contrib import cc as _cc\n\nRUNTIMES = [\n    (Runtime(\"crt\", {\"system-lib\": True}), \"{name}_c.{ext}\"),\n    (Runtime(\"cpp\", {\"system-lib\": True}), \"{name}_cpp.{ext}\"),\n]\n\n\ndef build_module(opts):\n    dshape = (1, 3, 224, 224)\n    from mxnet.gluon.model_zoo.vision import get_model\n\n    block = get_model(\"mobilenet0.25\", pretrained=True)\n    shape_dict = {\"data\": dshape}\n    mod, params = relay.frontend.from_mxnet(block, shape_dict)\n    func = mod[\"main\"]\n    func = relay.Function(\n        func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs\n    )\n\n    for runtime, file_format_str in RUNTIMES:\n        with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n            graph, lib, params = relay.build(func, \"llvm\", runtime=runtime, params=params)\n\n        build_dir = os.path.abspath(opts.out_dir)\n        if not os.path.isdir(build_dir):\n            os.makedirs(build_dir)\n        ext = \"tar\" if str(runtime) == \"crt\" else \"o\"\n        lib_file_name = os.path.join(build_dir, file_format_str.format(name=\"model\", ext=ext))\n        if str(runtime) == \"crt\":\n            lib.export_library(lib_file_name)\n        else:\n            # NOTE: at present, export_libarary will always create _another_ shared object, and you\n            # can't stably combine two shared objects together (in this case, init_array is not\n            # populated correctly when you do that). So for now, must continue to use save() with the\n            # C++ library.\n            # TODO(areusch): Obliterate runtime.cc and replace with libtvm_runtime.so.\n            lib.save(lib_file_name)\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"graph\", ext=\"json\")), \"w\"\n        ) as f_graph_json:\n            f_graph_json.write(graph)\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"params\", ext=\"bin\")), \"wb\"\n        ) as f_params:\n            f_params.write(tvm_runtime.save_param_dict(params))\n\n\ndef build_test_module(opts):\n    import numpy as np\n\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(1, 5))\n    z = relay.add(x, y)\n    func = relay.Function([x, y], z)\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(1, 5).astype(\"float32\")\n    params = {\"y\": y_data}\n\n    for runtime, file_format_str in RUNTIMES:\n        with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n            graph, lib, lowered_params = relay.build(\n                tvm.IRModule.from_expr(func),\n                \"llvm\",\n                runtime=runtime,\n                params=params,\n            )\n\n        build_dir = os.path.abspath(opts.out_dir)\n        if not os.path.isdir(build_dir):\n            os.makedirs(build_dir)\n        ext = \"tar\" if str(runtime) == \"crt\" else \"o\"\n        lib_file_name = os.path.join(build_dir, file_format_str.format(name=\"test_model\", ext=ext))\n        if str(runtime) == \"crt\":\n            lib.export_library(lib_file_name)\n        else:\n            # NOTE: at present, export_libarary will always create _another_ shared object, and you\n            # can't stably combine two shared objects together (in this case, init_array is not\n            # populated correctly when you do that). So for now, must continue to use save() with the\n            # C++ library.\n            # TODO(areusch): Obliterate runtime.cc and replace with libtvm_runtime.so.\n            lib.save(lib_file_name)\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"test_graph\", ext=\"json\")), \"w\"\n        ) as f_graph_json:\n            f_graph_json.write(graph)\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"test_params\", ext=\"bin\")), \"wb\"\n        ) as f_params:\n            f_params.write(tvm_runtime.save_param_dict(lowered_params))\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"test_data\", ext=\"bin\")), \"wb\"\n        ) as fp:\n            fp.write(x_data.astype(np.float32).tobytes())\n        x_output = x_data + y_data\n        with open(\n            os.path.join(build_dir, file_format_str.format(name=\"test_output\", ext=\"bin\")), \"wb\"\n        ) as fp:\n            fp.write(x_output.astype(np.float32).tobytes())\n\n\ndef build_inputs(opts):\n    from tvm.contrib import download\n    from PIL import Image\n    import numpy as np\n\n    build_dir = os.path.abspath(opts.out_dir)\n\n    # Download test image\n    image_url = \"https://homes.cs.washington.edu/~moreau/media/vta/cat.jpg\"\n    image_fn = os.path.join(build_dir, \"cat.png\")\n    download.download(image_url, image_fn)\n    image = Image.open(image_fn).resize((224, 224))\n\n    def transform_image(image):\n        image = np.array(image) - np.array([123.0, 117.0, 104.0])\n        image /= np.array([58.395, 57.12, 57.375])\n        image = image.transpose((2, 0, 1))\n        image = image[np.newaxis, :]\n        return image\n\n    x = transform_image(image)\n    print(\"x\", x.shape)\n    with open(os.path.join(build_dir, \"cat.bin\"), \"wb\") as fp:\n        fp.write(x.astype(np.float32).tobytes())\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-o\", \"--out-dir\", default=\".\")\n    parser.add_argument(\"-t\", \"--test\", action=\"store_true\")\n    opts = parser.parse_args()\n\n    if opts.test:\n        build_test_module(opts)\n    else:\n        build_module(opts)\n        build_inputs(opts)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/bundle.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/crt.h>\n#include <tvm/runtime/crt/graph_executor.h>\n#include <tvm/runtime/crt/packed_func.h>\n#include <tvm/runtime/crt/page_allocator.h>\n\n#ifdef ENABLE_TVM_ABORT_BACKTRACE\n#include \"backtrace.h\"\n#endif\n\n#define CRT_MEMORY_NUM_PAGES 16384\n#define CRT_MEMORY_PAGE_SIZE_LOG2 10\n\nstatic uint8_t g_crt_memory[CRT_MEMORY_NUM_PAGES * (1 << CRT_MEMORY_PAGE_SIZE_LOG2)];\nstatic MemoryManagerInterface* g_memory_manager;\n\n/*! \\brief macro to do C API call */\n#define TVM_CCALL(func)                                                              \\\n  do {                                                                               \\\n    int ret = (func);                                                                \\\n    if (ret != 0) {                                                                  \\\n      fprintf(stderr, \"%s: %d: error: %s\\n\", __FILE__, __LINE__, TVMGetLastError()); \\\n      exit(ret);                                                                     \\\n    }                                                                                \\\n  } while (0)\n\nTVM_DLL void* tvm_runtime_create(const char* json_data, const char* params_data,\n                                 const uint64_t params_size, const char* argv0) {\n#ifdef ENABLE_TVM_ABORT_BACKTRACE\n  g_argv0 = argv0;\n#endif\n\n  int64_t device_type = kDLCPU;\n  int64_t device_id = 0;\n\n  TVMByteArray params;\n  params.data = params_data;\n  params.size = params_size;\n\n  DLDevice dev;\n  dev.device_type = (DLDeviceType)device_type;\n  dev.device_id = device_id;\n\n  // declare pointers\n  TVM_CCALL(PageMemoryManagerCreate(&g_memory_manager, g_crt_memory, sizeof(g_crt_memory),\n                                    CRT_MEMORY_PAGE_SIZE_LOG2));\n  TVM_CCALL(TVMInitializeRuntime());\n  TVMPackedFunc pf;\n  TVMArgs args = TVMArgs_Create(NULL, NULL, 0);\n  TVM_CCALL(TVMPackedFunc_InitGlobalFunc(&pf, \"runtime.SystemLib\", &args));\n  TVM_CCALL(TVMPackedFunc_Call(&pf));\n\n  TVMModuleHandle mod_syslib = TVMArgs_AsModuleHandle(&pf.ret_value, 0);\n\n  // run modules\n  TVMGraphExecutor* graph_executor = NULL;\n  TVM_CCALL(TVMGraphExecutor_Create(json_data, mod_syslib, &dev, &graph_executor));\n  TVM_CCALL(TVMGraphExecutor_LoadParams(graph_executor, params.data, params.size));\n\n  return graph_executor;\n}\n\nTVM_DLL void tvm_runtime_destroy(void* executor) {\n  TVMGraphExecutor_Release((TVMGraphExecutor**)&executor);\n}\n\nTVM_DLL void tvm_runtime_set_input(void* executor, const char* name, DLTensor* tensor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_SetInput(graph_executor, name, tensor);\n}\n\nTVM_DLL void tvm_runtime_run(void* executor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_Run(graph_executor);\n}\n\nTVM_DLL void tvm_runtime_get_output(void* executor, int32_t index, DLTensor* tensor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_GetOutput(graph_executor, index, tensor);\n}\n\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stderr, msg, args);\n  va_end(args);\n}\n\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t error_code) {\n  fprintf(stderr, \"TVMPlatformAbort: %d\\n\", error_code);\n#ifdef ENABLE_TVM_ABORT_BACKTRACE\n  tvm_platform_abort_backtrace();\n#endif\n  exit(-1);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return g_memory_manager->Allocate(g_memory_manager, num_bytes, dev, out_ptr);\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return g_memory_manager->Free(g_memory_manager, ptr, dev);\n}\n\ntvm_crt_error_t TVMPlatformTimerStart() { return kTvmErrorFunctionCallNotImplemented; }\n\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/bundle.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_APPS_BUNDLE_DEPLOY_BUNDLE_H_\n#define TVM_APPS_BUNDLE_DEPLOY_BUNDLE_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\nTVM_DLL void* tvm_runtime_create(const char* json_data, const char* params_data,\n                                 const uint64_t params_size, const char* argv);\n\nTVM_DLL void tvm_runtime_destroy(void* runtime);\n\nTVM_DLL void tvm_runtime_set_input(void* runtime, const char* name, DLTensor* tensor);\n\nTVM_DLL void tvm_runtime_run(void* runtime);\n\nTVM_DLL void tvm_runtime_get_output(void* runtime, int32_t index, DLTensor* tensor);\n\n#endif /* TVM_APPS_BUNDLE_DEPLOY_BUNDLE_H_ */\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/bundle_static.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tvm/runtime/crt/crt.h>\n#include <tvm/runtime/crt/graph_executor.h>\n#include <tvm/runtime/crt/packed_func.h>\n#include <tvm/runtime/crt/page_allocator.h>\n#include <unistd.h>\n\n#ifdef ENABLE_TVM_PLATFORM_ABORT_BACKTRACE\n#include \"backtrace.h\"\n#endif\n#include \"bundle.h\"\n\n#define CRT_MEMORY_NUM_PAGES 16384\n#define CRT_MEMORY_PAGE_SIZE_LOG2 10\n\nstatic uint8_t g_crt_memory[CRT_MEMORY_NUM_PAGES * (1 << CRT_MEMORY_PAGE_SIZE_LOG2)];\nstatic MemoryManagerInterface* g_memory_manager;\n\n/*! \\brief macro to do C API call */\n#define TVM_CCALL(func)                                                              \\\n  do {                                                                               \\\n    tvm_crt_error_t ret = (func);                                                    \\\n    if (ret != kTvmErrorNoError) {                                                   \\\n      fprintf(stderr, \"%s: %d: error: %s\\n\", __FILE__, __LINE__, TVMGetLastError()); \\\n      exit(ret);                                                                     \\\n    }                                                                                \\\n  } while (0)\n\nTVM_DLL void* tvm_runtime_create(const char* json_data, const char* params_data,\n                                 const uint64_t params_size, const char* argv0) {\n#ifdef ENABLE_TVM_PLATFORM_ABORT_BACKTRACE\n  g_argv0 = argv0;\n#endif\n  int64_t device_type = kDLCPU;\n  int64_t device_id = 0;\n\n  TVMByteArray params;\n  params.data = params_data;\n  params.size = params_size;\n\n  DLDevice dev;\n  dev.device_type = (DLDeviceType)device_type;\n  dev.device_id = device_id;\n\n  // get pointers\n  TVM_CCALL(PageMemoryManagerCreate(&g_memory_manager, g_crt_memory, sizeof(g_crt_memory),\n                                    CRT_MEMORY_PAGE_SIZE_LOG2));\n  TVM_CCALL(TVMInitializeRuntime());\n  TVMPackedFunc pf;\n  TVMArgs args = TVMArgs_Create(NULL, NULL, 0);\n  TVM_CCALL(TVMPackedFunc_InitGlobalFunc(&pf, \"runtime.SystemLib\", &args));\n  TVM_CCALL(TVMPackedFunc_Call(&pf));\n\n  TVMModuleHandle mod_syslib = TVMArgs_AsModuleHandle(&pf.ret_value, 0);\n\n  // run modules\n  TVMGraphExecutor* graph_executor = NULL;\n  TVM_CCALL(TVMGraphExecutor_Create(json_data, mod_syslib, &dev, &graph_executor));\n  TVM_CCALL(TVMGraphExecutor_LoadParams(graph_executor, params.data, params.size));\n\n  return graph_executor;\n}\n\nTVM_DLL void tvm_runtime_destroy(void* executor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_Release(&graph_executor);\n}\n\nTVM_DLL void tvm_runtime_set_input(void* executor, const char* name, DLTensor* tensor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_SetInput(graph_executor, name, tensor);\n}\n\nTVM_DLL void tvm_runtime_run(void* executor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_Run(graph_executor);\n}\n\nTVM_DLL void tvm_runtime_get_output(void* executor, int32_t index, DLTensor* tensor) {\n  TVMGraphExecutor* graph_executor = (TVMGraphExecutor*)executor;\n  TVMGraphExecutor_GetOutput(graph_executor, index, tensor);\n}\n\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stderr, msg, args);\n  va_end(args);\n}\n\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t error_code) {\n  fprintf(stderr, \"TVMPlatformAbort: %d\\n\", error_code);\n#ifdef ENABLE_TVM_PLATFORM_ABORT_BACKTRACE\n  tvm_platform_abort_backtrace();\n#endif\n  exit(-1);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return g_memory_manager->Allocate(g_memory_manager, num_bytes, dev, out_ptr);\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return g_memory_manager->Free(g_memory_manager, ptr, dev);\n}\n\ntvm_crt_error_t TVMPlatformTimerStart() { return kTvmErrorFunctionCallNotImplemented; }\n\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/crt_config/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file apps/bundle_deploy/crt_config.h\n * \\brief CRT configuration for bundle_deploy app.\n */\n#ifndef TVM_RUNTIME_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Support low-level debugging in MISRA-C runtime */\n#define TVM_CRT_DEBUG 0\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\" */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 512\n\n#endif  // TVM_RUNTIME_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/demo_static.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <assert.h>\n#include <float.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n#include \"bundle.h\"\n\nextern const char build_graph_c_json[];\nextern unsigned int build_graph_c_json_len;\n\nextern const char build_params_c_bin[];\nextern unsigned int build_params_c_bin_len;\n\n#define OUTPUT_LEN 1000\n\nint main(int argc, char** argv) {\n  assert(argc == 2 && \"Usage: demo_static <cat.bin>\");\n\n  char* json_data = (char*)(build_graph_c_json);\n  char* params_data = (char*)(build_params_c_bin);\n  uint64_t params_size = build_params_c_bin_len;\n\n  struct timeval t0, t1, t2, t3, t4, t5;\n  gettimeofday(&t0, 0);\n\n  void* handle = tvm_runtime_create(json_data, params_data, params_size, argv[0]);\n  gettimeofday(&t1, 0);\n\n  float input_storage[1 * 3 * 224 * 224];\n  FILE* fp = fopen(argv[1], \"rb\");\n  (void)fread(input_storage, 3 * 224 * 224, 4, fp);\n  fclose(fp);\n\n  DLTensor input;\n  input.data = input_storage;\n  DLDevice dev = {kDLCPU, 0};\n  input.device = dev;\n  input.ndim = 4;\n  DLDataType dtype = {kDLFloat, 32, 1};\n  input.dtype = dtype;\n  int64_t shape[4] = {1, 3, 224, 224};\n  input.shape = shape;\n  input.strides = NULL;\n  input.byte_offset = 0;\n\n  tvm_runtime_set_input(handle, \"data\", &input);\n  gettimeofday(&t2, 0);\n\n  tvm_runtime_run(handle);\n  gettimeofday(&t3, 0);\n\n  float output_storage[OUTPUT_LEN];\n  DLTensor output;\n  output.data = output_storage;\n  DLDevice out_dev = {kDLCPU, 0};\n  output.device = out_dev;\n  output.ndim = 2;\n  DLDataType out_dtype = {kDLFloat, 32, 1};\n  output.dtype = out_dtype;\n  int64_t out_shape[2] = {1, OUTPUT_LEN};\n  output.shape = out_shape;\n  output.strides = NULL;\n  output.byte_offset = 0;\n\n  tvm_runtime_get_output(handle, 0, &output);\n  gettimeofday(&t4, 0);\n\n  float max_iter = -FLT_MAX;\n  int32_t max_index = -1;\n  for (int i = 0; i < OUTPUT_LEN; ++i) {\n    if (output_storage[i] > max_iter) {\n      max_iter = output_storage[i];\n      max_index = i;\n    }\n  }\n\n  tvm_runtime_destroy(handle);\n  gettimeofday(&t5, 0);\n\n  printf(\"The maximum position in output vector is: %d, with max-value %f.\\n\", max_index, max_iter);\n  printf(\n      \"timing: %.2f ms (create), %.2f ms (set_input), %.2f ms (run), \"\n      \"%.2f ms (get_output), %.2f ms (destroy)\\n\",\n      (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_usec - t0.tv_usec) / 1000.f,\n      (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.f,\n      (t3.tv_sec - t2.tv_sec) * 1000 + (t3.tv_usec - t2.tv_usec) / 1000.f,\n      (t4.tv_sec - t3.tv_sec) * 1000 + (t4.tv_usec - t3.tv_usec) / 1000.f,\n      (t5.tv_sec - t4.tv_sec) * 1000 + (t5.tv_usec - t4.tv_usec) / 1000.f);\n\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/bundle_deploy/test_static.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n#include \"bundle.h\"\n\nint main(int argc, char** argv) {\n  assert(argc == 5 && \"Usage: test_static <data.bin> <output.bin> <graph.json> <params.bin>\");\n\n  struct stat st;\n  char* json_data;\n  char* params_data;\n  uint64_t params_size;\n\n  FILE* fp = fopen(argv[3], \"rb\");\n  stat(argv[3], &st);\n  json_data = (char*)malloc(st.st_size);\n  fread(json_data, st.st_size, 1, fp);\n  fclose(fp);\n\n  fp = fopen(argv[4], \"rb\");\n  stat(argv[4], &st);\n  params_data = (char*)malloc(st.st_size);\n  fread(params_data, st.st_size, 1, fp);\n  params_size = st.st_size;\n  fclose(fp);\n\n  struct timeval t0, t1, t2, t3, t4, t5;\n  gettimeofday(&t0, 0);\n\n  void* handle = tvm_runtime_create(json_data, params_data, params_size, argv[0]);\n  gettimeofday(&t1, 0);\n\n  float input_storage[10 * 5];\n  fp = fopen(argv[1], \"rb\");\n  fread(input_storage, 10 * 5, 4, fp);\n  fclose(fp);\n\n  float result_storage[10 * 5];\n  fp = fopen(argv[2], \"rb\");\n  fread(result_storage, 10 * 5, 4, fp);\n  fclose(fp);\n\n  DLTensor input;\n  input.data = input_storage;\n  DLDevice dev = {kDLCPU, 0};\n  input.device = dev;\n  input.ndim = 2;\n  DLDataType dtype = {kDLFloat, 32, 1};\n  input.dtype = dtype;\n  int64_t shape[2] = {10, 5};\n  input.shape = shape;\n  input.strides = NULL;\n  input.byte_offset = 0;\n\n  tvm_runtime_set_input(handle, \"x\", &input);\n  gettimeofday(&t2, 0);\n\n  tvm_runtime_run(handle);\n  gettimeofday(&t3, 0);\n\n  float output_storage[10 * 5];\n  DLTensor output;\n  output.data = output_storage;\n  DLDevice out_dev = {kDLCPU, 0};\n  output.device = out_dev;\n  output.ndim = 2;\n  DLDataType out_dtype = {kDLFloat, 32, 1};\n  output.dtype = out_dtype;\n  int64_t out_shape[2] = {10, 5};\n  output.shape = out_shape;\n  output.strides = NULL;\n  output.byte_offset = 0;\n\n  tvm_runtime_get_output(handle, 0, &output);\n  gettimeofday(&t4, 0);\n\n  for (int i = 0; i < 10 * 5; ++i) {\n    assert(fabs(output_storage[i] - result_storage[i]) < 1e-5f);\n    if (fabs(output_storage[i] - result_storage[i]) >= 1e-5f) {\n      printf(\"got %f, expected %f\\n\", output_storage[i], result_storage[i]);\n    }\n  }\n\n  tvm_runtime_destroy(handle);\n  gettimeofday(&t5, 0);\n\n  printf(\n      \"timing: %.2f ms (create), %.2f ms (set_input), %.2f ms (run), \"\n      \"%.2f ms (get_output), %.2f ms (destroy)\\n\",\n      (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_usec - t0.tv_usec) / 1000.f,\n      (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.f,\n      (t3.tv_sec - t2.tv_sec) * 1000 + (t3.tv_usec - t2.tv_usec) / 1000.f,\n      (t4.tv_sec - t3.tv_sec) * 1000 + (t4.tv_usec - t3.tv_usec) / 1000.f,\n      (t5.tv_sec - t4.tv_sec) * 1000 + (t5.tv_usec - t4.tv_usec) / 1000.f);\n\n  free(json_data);\n  free(params_data);\n\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/cpp_rpc/rpc_env.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_env.h\n * \\brief Server environment of the RPC.\n */\n#ifndef TVM_APPS_CPP_RPC_ENV_H_\n#define TVM_APPS_CPP_RPC_ENV_H_\n\n#include <tvm/runtime/registry.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief RPCEnv The RPC Environment parameters for c++ rpc server\n */\nstruct RPCEnv {\n public:\n  /*!\n   * \\brief Constructor Init The RPC Environment initialize function\n   */\n  RPCEnv(const std::string& word_dir = \"\");\n  /*!\n   * \\brief GetPath To get the workpath from packed function\n   * \\param name The file name\n   * \\return The full path of file.\n   */\n  std::string GetPath(const std::string& file_name) const;\n  /*!\n   * \\brief The RPC Environment cleanup function\n   */\n  void CleanUp() const;\n\n private:\n  /*!\n   * \\brief Holds the environment path.\n   */\n  std::string base_;\n};  // RPCEnv\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_APPS_CPP_RPC_ENV_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/cpp_rpc/rpc_server.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_server.h\n * \\brief RPC Server implementation.\n */\n#ifndef TVM_APPS_CPP_RPC_SERVER_H_\n#define TVM_APPS_CPP_RPC_SERVER_H_\n\n#include <string>\n\n#include \"tvm/runtime/c_runtime_api.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n#if defined(WIN32)\n/*!\n * \\brief ServerLoopFromChild The Server loop process.\n * \\param sock The socket information\n * \\param addr The socket address information\n */\nvoid ServerLoopFromChild(SOCKET socket);\n#endif\n\n/*!\n * \\brief RPCServerCreate Creates the RPC Server.\n * \\param host The hostname of the server, Default=0.0.0.0\n * \\param port The port of the RPC, Default=9090\n * \\param port_end The end search port of the RPC, Default=9099\n * \\param tracker The address of RPC tracker in host:port format e.g. 10.77.1.234:9190 Default=\"\"\n * \\param key The key used to identify the device type in tracker. Default=\"\"\n * \\param custom_addr Custom IP Address to Report to RPC Tracker. Default=\"\"\n * \\param work_dir Custom work directory. Default=\"\"\n * \\param silent Whether run in silent mode. Default=True\n */\nvoid RPCServerCreate(std::string host = \"\", int port = 9090, int port_end = 9099,\n                     std::string tracker_addr = \"\", std::string key = \"\",\n                     std::string custom_addr = \"\", std::string work_dir = \"\", bool silent = true);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_APPS_CPP_RPC_SERVER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/cpp_rpc/rpc_tracker_client.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_tracker_client.h\n * \\brief RPC Tracker client to report resources.\n */\n#ifndef TVM_APPS_CPP_RPC_TRACKER_CLIENT_H_\n#define TVM_APPS_CPP_RPC_TRACKER_CLIENT_H_\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <set>\n#include <string>\n#include <vector>\n\n#include \"../../src/runtime/rpc/rpc_endpoint.h\"\n#include \"../../src/support/socket.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief TrackerClient Tracker client class.\n * \\param tracker The address of RPC tracker in host:port format e.g. 10.77.1.234:9190 Default=\"\"\n * \\param key The key used to identify the device type in tracker. Default=\"\"\n * \\param custom_addr Custom IP Address to Report to RPC Tracker. Default=\"\"\n */\nclass TrackerClient {\n public:\n  /*!\n   * \\brief Constructor.\n   */\n  TrackerClient(const std::string& tracker_addr, const std::string& key,\n                const std::string& custom_addr, int port)\n      : tracker_addr_(tracker_addr),\n        key_(key),\n        custom_addr_(custom_addr),\n        port_(port),\n        gen_(std::random_device{}()),\n        dis_(0.0, 1.0) {\n    if (custom_addr_.empty()) {\n      custom_addr_ = \"null\";\n    } else {\n      // Since custom_addr_ can be either the json value null which is not surrounded by quotes\n      // or a string containing the custom value which json does required to be quoted then we\n      // need to set custom_addr_ to be a string containing the quotes here.\n      custom_addr_ = \"\\\"\" + custom_addr_ + \"\\\"\";\n    }\n  }\n  /*!\n   * \\brief Destructor.\n   */\n  ~TrackerClient() {\n    // Free the resources\n    Close();\n  }\n  /*!\n   * \\brief IsValid Check tracker is valid.\n   */\n  bool IsValid() { return (!tracker_addr_.empty() && !tracker_sock_.IsClosed()); }\n  /*!\n   * \\brief TryConnect Connect to tracker if the tracker address is valid.\n   */\n  void TryConnect() {\n    if (!tracker_addr_.empty() && (tracker_sock_.IsClosed())) {\n      tracker_sock_ = ConnectWithRetry();\n\n      int code = kRPCTrackerMagic;\n      ICHECK_EQ(tracker_sock_.SendAll(&code, sizeof(code)), sizeof(code));\n      ICHECK_EQ(tracker_sock_.RecvAll(&code, sizeof(code)), sizeof(code));\n      ICHECK_EQ(code, kRPCTrackerMagic) << tracker_addr_.c_str() << \" is not RPC Tracker\";\n\n      std::ostringstream ss;\n      ss << \"[\" << static_cast<int>(TrackerCode::kUpdateInfo) << \", {\\\"key\\\": \\\"server:\" << key_\n         << \"\\\", \\\"addr\\\": [\" << custom_addr_ << \", \\\"\" << port_ << \"\\\"]}]\";\n      tracker_sock_.SendBytes(ss.str());\n\n      // Receive status and validate\n      std::string remote_status = tracker_sock_.RecvBytes();\n      ICHECK_EQ(std::stoi(remote_status), static_cast<int>(TrackerCode::kSuccess));\n    }\n  }\n  /*!\n   * \\brief Close Clean up tracker resources.\n   */\n  void Close() {\n    // close tracker resource\n    if (!tracker_sock_.IsClosed()) {\n      tracker_sock_.Close();\n    }\n  }\n  /*!\n   * \\brief ReportResourceAndGetKey Report resource to tracker.\n   * \\param port listening port.\n   * \\param matchkey Random match key output.\n   */\n  void ReportResourceAndGetKey(int port, std::string* matchkey) {\n    if (!tracker_sock_.IsClosed()) {\n      *matchkey = RandomKey(key_ + \":\", old_keyset_);\n\n      std::ostringstream ss;\n      ss << \"[\" << static_cast<int>(TrackerCode::kPut) << \", \\\"\" << key_ << \"\\\", [\" << port\n         << \", \\\"\" << *matchkey << \"\\\"], \" << custom_addr_ << \"]\";\n\n      tracker_sock_.SendBytes(ss.str());\n\n      // Receive status and validate\n      std::string remote_status = tracker_sock_.RecvBytes();\n      ICHECK_EQ(std::stoi(remote_status), static_cast<int>(TrackerCode::kSuccess));\n    } else {\n      *matchkey = key_;\n    }\n  }\n\n  /*!\n   * \\brief ReportResourceAndGetKey Report resource to tracker.\n   * \\param listen_sock Listen socket details for select.\n   * \\param port listening port.\n   * \\param ping_period Select wait time.\n   * \\param matchkey Random match key output.\n   */\n  void WaitConnectionAndUpdateKey(support::TCPSocket listen_sock, int port, int ping_period,\n                                  std::string* matchkey) {\n    int unmatch_period_count = 0;\n    int unmatch_timeout = 4;\n    while (true) {\n      if (!tracker_sock_.IsClosed()) {\n        support::PollHelper poller;\n        poller.WatchRead(listen_sock.sockfd);\n        poller.Poll(ping_period * 1000);\n        if (!poller.CheckRead(listen_sock.sockfd)) {\n          std::ostringstream ss;\n          ss << \"[\" << int(TrackerCode::kGetPendingMatchKeys) << \"]\";\n          tracker_sock_.SendBytes(ss.str());\n\n          // Receive status and validate\n          std::string pending_keys = tracker_sock_.RecvBytes();\n          old_keyset_.insert(*matchkey);\n\n          // if match key not in pending key set\n          // it means the key is acquired by a client but not used.\n          if (pending_keys.find(*matchkey) == std::string::npos) {\n            unmatch_period_count += 1;\n          } else {\n            unmatch_period_count = 0;\n          }\n          // regenerate match key if key is acquired but not used for a while\n          if (unmatch_period_count * ping_period > unmatch_timeout + ping_period) {\n            LOG(INFO) << \"no incoming connections, regenerate key ...\";\n\n            *matchkey = RandomKey(key_ + \":\", old_keyset_);\n\n            std::ostringstream ss;\n            ss << \"[\" << static_cast<int>(TrackerCode::kPut) << \", \\\"\" << key_ << \"\\\", [\" << port\n               << \", \\\"\" << *matchkey << \"\\\"], \" << custom_addr_ << \"]\";\n            tracker_sock_.SendBytes(ss.str());\n\n            std::string remote_status = tracker_sock_.RecvBytes();\n            ICHECK_EQ(std::stoi(remote_status), static_cast<int>(TrackerCode::kSuccess));\n            unmatch_period_count = 0;\n          }\n          continue;\n        }\n      }\n      break;\n    }\n  }\n\n private:\n  /*!\n   * \\brief Connect to a RPC address with retry.\n            This function is only reliable to short period of server restart.\n   * \\param timeout Timeout during retry\n   * \\param retry_period Number of seconds before we retry again.\n   * \\return TCPSocket The socket information if connect is success.\n   */\n  support::TCPSocket ConnectWithRetry(int timeout = 60, int retry_period = 5) {\n    auto tbegin = std::chrono::system_clock::now();\n    while (true) {\n      support::SockAddr addr(tracker_addr_);\n      support::TCPSocket sock;\n      sock.Create();\n      LOG(INFO) << \"Tracker connecting to \" << addr.AsString();\n      if (sock.Connect(addr)) {\n        return sock;\n      }\n\n      auto period = (std::chrono::duration_cast<std::chrono::seconds>(\n                         std::chrono::system_clock::now() - tbegin))\n                        .count();\n      ICHECK(period < timeout) << \"Failed to connect to server\" << addr.AsString();\n      LOG(WARNING) << \"Cannot connect to tracker \" << addr.AsString() << \" retry in \"\n                   << retry_period << \" seconds.\";\n      std::this_thread::sleep_for(std::chrono::seconds(retry_period));\n    }\n  }\n  /*!\n   * \\brief Random Generate a random number between 0 and 1.\n   * \\return random float value.\n   */\n  float Random() { return dis_(gen_); }\n  /*!\n   * \\brief Generate a random key.\n   * \\param prefix The string prefix.\n   * \\return cmap The conflict map set.\n   */\n  std::string RandomKey(const std::string& prefix, const std::set<std::string>& cmap) {\n    if (!cmap.empty()) {\n      while (true) {\n        std::string key = prefix + std::to_string(Random());\n        if (cmap.find(key) == cmap.end()) {\n          return key;\n        }\n      }\n    }\n    return prefix + std::to_string(Random());\n  }\n\n  std::string tracker_addr_;\n  std::string key_;\n  std::string custom_addr_;\n  int port_;\n  support::TCPSocket tracker_sock_;\n  std::set<std::string> old_keyset_;\n  std::mt19937 gen_;\n  std::uniform_real_distribution<float> dis_;\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_APPS_CPP_RPC_TRACKER_CLIENT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/cpp_rpc/win32_process.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file win32_process.h\n * \\brief Win32 process code to mimic a POSIX fork()\n */\n#ifndef TVM_APPS_CPP_RPC_WIN32_PROCESS_H_\n#define TVM_APPS_CPP_RPC_WIN32_PROCESS_H_\n\n#include <chrono>\n#include <string>\n\n#include \"../../src/support/socket.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief SpawnRPCChild Spawns a child process with a given timeout to run\n * \\param fd The client socket to duplicate in the child\n * \\param timeout The time in seconds to wait for the child to complete before termination\n */\nvoid SpawnRPCChild(SOCKET fd, std::chrono::seconds timeout);\n/*!\n * \\brief ChildProcSocketHandler Ran from the child process and runs server to handle the client\n * socket \\param mmap_path The memory mapped file path that will contain the information to\n * duplicate the client socket from the parent\n */\nvoid ChildProcSocketHandler(const std::string& mmap_path);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_APPS_CPP_RPC_WIN32_PROCESS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/dso_plugin_module/test_plugin_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport os\n\n\ndef test_plugin_module():\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    mod = tvm.runtime.load_module(os.path.join(curr_path, \"lib\", \"plugin_module.so\"))\n    # NOTE: we need to make sure all managed resources returned\n    # from mod get destructed before mod get unloaded.\n    #\n    # Failure mode we want to prevent from:\n    # We retain an object X whose destructor is within mod.\n    # The program will segfault if X get destructed after mod,\n    # because the destructor function has already been unloaded.\n    #\n    # The easiest way to achieve this is to wrap the\n    # logics related to mod inside a function.\n    def run_module(mod):\n        # normal functions\n        assert mod[\"AddOne\"](10) == 11\n        assert mod[\"SubOne\"](10) == 9\n        # advanced usecase: return a module\n        mymod = mod[\"CreateMyModule\"](10)\n        fadd = mymod[\"add\"]\n        assert fadd(10) == 20\n        assert mymod[\"mul\"](10) == 100\n\n    run_module(mod)\n\n\nif __name__ == \"__main__\":\n    test_plugin_module()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/extension/python/tvm_ext/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Example extension package of TVM.\"\"\"\nfrom __future__ import absolute_import\nimport os\nimport ctypes\n\n# Import TVM first to get library symbols\nimport tvm\nfrom tvm import te\n\n\ndef load_lib():\n    \"\"\"Load library, the functions will be registered into TVM\"\"\"\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    # load in as global so the global extern symbol is visible to other dll.\n    lib = ctypes.CDLL(os.path.join(curr_path, \"../../lib/libtvm_ext.so\"), ctypes.RTLD_GLOBAL)\n    return lib\n\n\n_LIB = load_lib()\n\n# Expose two functions into python\nbind_add = tvm.get_global_func(\"tvm_ext.bind_add\")\nsym_add = tvm.get_global_func(\"tvm_ext.sym_add\")\nivec_create = tvm.get_global_func(\"tvm_ext.ivec_create\")\nivec_get = tvm.get_global_func(\"tvm_ext.ivec_get\")\n\n\n@tvm.register_object(\"tvm_ext.IntVector\")\nclass IntVec(tvm.Object):\n    \"\"\"Example for using extension class in c++\"\"\"\n\n    @property\n    def _tvm_handle(self):\n        return self.handle.value\n\n    def __getitem__(self, idx):\n        return ivec_get(self, idx)\n\n\nnd_create = tvm.get_global_func(\"tvm_ext.nd_create\")\nnd_add_two = tvm.get_global_func(\"tvm_ext.nd_add_two\")\nnd_get_additional_info = tvm.get_global_func(\"tvm_ext.nd_get_additional_info\")\n\n\n@tvm.register_object(\"tvm_ext.NDSubClass\")\nclass NDSubClass(tvm.nd.NDArrayBase):\n    \"\"\"Example for subclassing TVM's NDArray infrastructure.\n\n    By inheriting TVM's NDArray, external libraries could\n    leverage TVM's FFI without any modification.\n    \"\"\"\n\n    @staticmethod\n    def create(additional_info):\n        return nd_create(additional_info)\n\n    @property\n    def additional_info(self):\n        return nd_get_additional_info(self)\n\n    def __add__(self, other):\n        return nd_add_two(self, other)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/extension/tests/test_ext.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm_ext\nimport tvm\nimport tvm._ffi.registry\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n\ndef test_bind_add():\n    def add(a, b):\n        return a + b\n\n    f = tvm_ext.bind_add(add, 1)\n    assert f(2) == 3\n\n\ndef test_ext_dev():\n    n = 10\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute((n,), lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    def check_llvm():\n        if not tvm.testing.device_enabled(\"llvm\"):\n            return\n        f = tvm.build(s, [A, B], \"ext_dev\", \"llvm\")\n        dev = tvm.ext_dev(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), a.numpy() + 1)\n\n    check_llvm()\n\n\ndef test_sym_add():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = tvm_ext.sym_add(a, b)\n    assert c.a == a and c.b == b\n\n\ndef test_ext_vec():\n    ivec = tvm_ext.ivec_create(1, 2, 3)\n    assert isinstance(ivec, tvm_ext.IntVec)\n    assert ivec[0] == 1\n    assert ivec[1] == 2\n\n    def ivec_cb(v2):\n        assert isinstance(v2, tvm_ext.IntVec)\n        assert v2[2] == 3\n\n    tvm.runtime.convert(ivec_cb)(ivec)\n\n\ndef test_extract_ext():\n    fdict = tvm._ffi.registry.extract_ext_funcs(tvm_ext._LIB.TVMExtDeclare)\n    assert fdict[\"mul\"](3, 4) == 12\n\n\ndef test_extern_call():\n    n = 10\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(\n        (n,), lambda *i: tvm.tir.call_extern(\"float32\", \"TVMTestAddOne\", A(*i)), name=\"B\"\n    )\n    s = te.create_schedule(B.op)\n\n    def check_llvm():\n        if not tvm.testing.device_enabled(\"llvm\"):\n            return\n        f = tvm.build(s, [A, B], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), a.numpy() + 1)\n\n    check_llvm()\n\n\ndef test_nd_subclass():\n    a = tvm_ext.NDSubClass.create(additional_info=3)\n    b = tvm_ext.NDSubClass.create(additional_info=5)\n    assert isinstance(a, tvm_ext.NDSubClass)\n    c = a + b\n    d = a + a\n    e = b + b\n    assert a.additional_info == 3\n    assert b.additional_info == 5\n    assert c.additional_info == 8\n    assert d.additional_info == 6\n    assert e.additional_info == 10\n\n\nif __name__ == \"__main__\":\n    test_nd_subclass()\n    test_extern_call()\n    test_ext_dev()\n    test_ext_vec()\n    test_bind_add()\n    test_sym_add()\n    test_extract_ext()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/hexagon_launcher/launcher_core.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_CORE_H_\n#define TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_CORE_H_\n\n#include <dlpack/dlpack.h>\n#include <dmlc/json.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <vector>\n\nstruct tensor_meta {\n  int ndim;\n  DLDataType dtype;\n  int64_t shape[];\n\n  int meta_size() const { return meta_size(ndim); }\n  int data_size() const {\n    int size = tvm::runtime::DataType(dtype).bytes();\n    for (int d = 0; d != ndim; ++d) {\n      size *= shape[d];\n    }\n    return size;\n  }\n\n  static int meta_size(int ndim) { return sizeof(tensor_meta) + ndim * sizeof(int64_t); }\n\n  std::string to_string() const;\n};\n\nstruct TensorConfig {\n  static const std::string file_key;\n  static const std::string shape_key;\n  static const std::string dtype_key;\n\n  std::string file_name;\n  std::vector<int> shape;\n  std::string dtype;\n  bool bad = false;\n\n  void Load(dmlc::JSONReader* reader);\n  void Save(dmlc::JSONWriter* writer) const;\n};\n\nstruct ModelConfig {\n  std::string model_library;\n  std::string model_json;\n  std::vector<TensorConfig> inputs;\n  bool bad = false;\n\n  void Load(dmlc::JSONReader* reader);\n};\n\nstruct OutputConfig {\n  uint64_t pcycles;\n  uint64_t usecs;\n  std::vector<TensorConfig> outputs;\n\n  void Save(dmlc::JSONWriter* writer) const;\n};\n\nstruct Model {\n  Model(tvm::runtime::Module executor, tvm::runtime::Module module, std::string json);\n\n  tvm::runtime::Module model_executor;\n  tvm::runtime::Module graph_module;\n  std::string graph_json;\n\n  static tvm::Device device() { return tvm::Device{static_cast<DLDeviceType>(kDLHexagon), 0}; }\n  static tvm::Device external() { return tvm::Device{static_cast<DLDeviceType>(kDLCPU), 0}; }\n\n  tvm::runtime::PackedFunc run;\n};\n\nstruct ExecutionSession {\n  explicit ExecutionSession(bool lwp_json = false) : gen_lwp_json(lwp_json) {}\n\n  template <typename T>\n  T* alloc(size_t bytes, size_t align = 1) {\n    return reinterpret_cast<T*>(alloc_mem(bytes, align));\n  }\n  void free(void* ptr) { free_mem(ptr); }\n\n  virtual void* alloc_mem(size_t bytes, size_t align) = 0;\n  virtual void free_mem(void* ptr) = 0;\n\n  virtual bool load_model(const std::string& model_path, const std::string& model_json) = 0;\n  virtual bool unload_model() = 0;\n\n  virtual bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) = 0;\n  virtual bool run(uint64_t* pcycles, uint64_t* usecs) = 0;\n  virtual bool get_num_outputs(int* num_outputs) = 0;\n  virtual bool get_output(int output_idx, tensor_meta* output_meta, int meta_size,\n                          void* output_data, int data_size) = 0;\n  bool gen_lwp_json = false;\n};\n\nbool read_model_config(const std::string& file_name, ModelConfig* model_config);\nbool write_output_config(const std::string& file_name, OutputConfig* output_config);\n\nvoid reset_device_api();\n\ntvm::runtime::Module load_module(const std::string& file_name);\n\nconst tvm::runtime::PackedFunc get_runtime_func(const std::string& name);\nconst tvm::runtime::PackedFunc get_module_func(tvm::runtime::Module module,\n                                               const std::string& name);\n\ntvm::runtime::Module create_aot_executor(tvm::runtime::Module factory_module, tvm::Device device);\ntvm::runtime::Module create_graph_executor(const std::string& graph_json,\n                                           tvm::runtime::Module graph_module, tvm::Device device);\n\n#endif  // TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_CORE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/hexagon_launcher/launcher_util.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_\n#define TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_\n\n#include <cstddef>\n#include <fstream>\n#include <string>\n\nsize_t get_file_size(std::ifstream& in_file);\nsize_t get_file_size(std::ifstream&& in_file);\n\nstd::string load_text_file(const std::string& file_name);\nvoid* load_binary_file(const std::string& file_name, void* buffer, size_t buffer_size);\nvoid write_binary_file(const std::string& file_name, void* buffer, size_t buffer_size);\n\n#endif  // TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/howto_deploy/prepare_test_libs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Script to prepare test_addone.so\"\"\"\nimport tvm\nimport numpy as np\nfrom tvm import te\nfrom tvm import relay\nimport os\n\n\ndef prepare_test_libs(base_path):\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    # Compile library as dynamic library\n    fadd_dylib = tvm.build(s, [A, B], \"llvm\", name=\"addone\")\n    dylib_path = os.path.join(base_path, \"test_addone_dll.so\")\n    fadd_dylib.export_library(dylib_path)\n\n    # Compile library in system library mode\n    fadd_syslib = tvm.build(s, [A, B], \"llvm\", name=\"addonesys\")\n    syslib_path = os.path.join(base_path, \"test_addone_sys.o\")\n    fadd_syslib.save(syslib_path)\n\n\ndef prepare_graph_lib(base_path):\n    x = relay.var(\"x\", shape=(2, 2), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(2, 2), dtype=\"float32\")\n    params = {\"y\": np.ones((2, 2), dtype=\"float32\")}\n    mod = tvm.IRModule.from_expr(relay.Function([x, y], x + y))\n    # build a module\n    compiled_lib = relay.build(mod, tvm.target.create(\"llvm\"), params=params)\n    # export it as a shared library\n    # If you are running cross compilation, you can also consider export\n    # to tar and invoke host compiler later.\n    dylib_path = os.path.join(base_path, \"test_relay_add.so\")\n    compiled_lib.export_library(dylib_path)\n\n\nif __name__ == \"__main__\":\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    prepare_test_libs(os.path.join(curr_path, \"lib\"))\n    prepare_graph_lib(os.path.join(curr_path, \"lib\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/howto_deploy/python_deploy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# brief Example code on load and run TVM module.s\n# file python_deploy.py\n\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n\ndef verify(mod, fname):\n    # Get the function from the module\n    f = mod.get_function(fname)\n    # Use tvm.nd.array to convert numpy ndarray to tvm\n    # NDArray type, so that function can be invoked normally\n    N = 10\n    x = tvm.nd.array(np.arange(N, dtype=np.float32))\n    y = tvm.nd.array(np.zeros(N, dtype=np.float32))\n    # Invoke the function\n    f(x, y)\n    np_x = x.numpy()\n    np_y = y.numpy()\n    # Verify correctness of function\n    assert np.all([xi + 1 == yi for xi, yi in zip(np_x, np_y)])\n    print(\"Finish verification...\")\n\n\nif __name__ == \"__main__\":\n    # The normal dynamic loading method for deployment\n    mod_dylib = tvm.runtime.load_module(\"lib/test_addone_dll.so\")\n    print(\"Verify dynamic loading from test_addone_dll.so\")\n    verify(mod_dylib, \"addone\")\n    # There might be methods to use the system lib way in\n    # python, but dynamic loading is good enough for now.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/init_proj.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport re\n\ndefault_team_id = \"3FR42MXLK9\"\ndefault_tvm_build_dir = \"path-to-tvm-ios-build-folder\"\n\nparser = argparse.ArgumentParser(\n    description=\"Update tvmrpc.xcodeproj\\\n developer information\"\n)\nparser.add_argument(\n    \"--team_id\",\n    type=str,\n    required=True,\n    help=\"Apple Developer Team ID.\\n\\\n                    Can be found here:\\n\\\n                    \\n\\\n                    https://developer.apple.com/account/#/membership\\n\\\n                    (example: {})\".format(\n        default_team_id\n    ),\n)\n\nparser.add_argument(\n    \"--tvm_build_dir\",\n    type=str,\n    required=True,\n    help=\"Path to directory with libtvm_runtime.dylib\",\n)\n\nargs = parser.parse_args()\nteam_id = args.team_id\ntvm_build_dir = args.tvm_build_dir\n\nfi = open(\"tvmrpc.xcodeproj/project.pbxproj\")\nproj_config = fi.read()\nfi.close()\n\nproj_config = proj_config.replace(default_team_id, team_id)\nproj_config = proj_config.replace(default_tvm_build_dir, tvm_build_dir)\nfo = open(\"tvmrpc.xcodeproj/project.pbxproj\", \"w\")\nfo.write(proj_config)\nfo.close()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tests/ios_rpc_mobilenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import rpc, relay\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.expr_functor import ExprMutator\nfrom tvm.relay import transform\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.quantize.quantize import prerequisite_optimize\nfrom tvm.contrib import utils, xcode, graph_executor, coreml_runtime\nfrom tvm.contrib.target import coreml as _coreml\n\nimport os\nimport re\nimport sys\nimport numpy as np\nfrom mxnet import gluon\nfrom PIL import Image\nimport coremltools\nimport argparse\n\n# Change target configuration, this is setting for iphone6s\n# arch = \"x86_64\"\n# sdk = \"iphonesimulator\"\narch = \"arm64\"\nsdk = \"iphoneos\"\ntarget_host = \"llvm -mtriple=%s-apple-darwin\" % arch\n\nMODES = {\"proxy\": rpc.connect, \"tracker\": rpc.connect_tracker, \"standalone\": rpc.connect}\n\n# override metal compiler to compile to iphone\n@tvm.register_func(\"tvm_callback_metal_compile\")\ndef compile_metal(src):\n    return xcode.compile_metal(src, sdk=sdk)\n\n\ndef prepare_input():\n    img_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\n    img_name = \"cat.png\"\n    synset_url = \"\".join(\n        [\n            \"https://gist.githubusercontent.com/zhreshold/\",\n            \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n            \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n            \"imagenet1000_clsid_to_human.txt\",\n        ]\n    )\n    synset_name = \"imagenet1000_clsid_to_human.txt\"\n    img_path = download_testdata(img_url, \"cat.png\", module=\"data\")\n    synset_path = download_testdata(synset_url, synset_name, module=\"data\")\n    with open(synset_path) as f:\n        synset = eval(f.read())\n        image = Image.open(img_path).resize((224, 224))\n\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image.astype(\"float32\"), synset\n\n\ndef get_model(model_name, data_shape):\n    gluon_model = gluon.model_zoo.vision.get_model(model_name, pretrained=True)\n    mod, params = relay.frontend.from_mxnet(gluon_model, {\"data\": data_shape})\n    # we want a probability so add a softmax operator\n    func = mod[\"main\"]\n    func = relay.Function(\n        func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs\n    )\n\n    return func, params\n\n\ndef test_mobilenet(host, port, key, mode):\n    temp = utils.tempdir()\n    image, synset = prepare_input()\n    model, params = get_model(\"mobilenetv2_1.0\", image.shape)\n\n    def run(mod, target):\n        with relay.build_config(opt_level=3):\n            lib = relay.build(\n                mod, target=tvm.target.Target(target, host=target_host), params=params\n            )\n        path_dso = temp.relpath(\"deploy.dylib\")\n        lib.export_library(path_dso, xcode.create_dylib, arch=arch, sdk=sdk)\n\n        # connect to the proxy\n        if mode == \"tracker\":\n            remote = MODES[mode](host, port).request(key)\n        else:\n            remote = MODES[mode](host, port, key=key)\n        remote.upload(path_dso)\n\n        if target == \"metal\":\n            dev = remote.metal(0)\n        else:\n            dev = remote.cpu(0)\n        lib = remote.load_module(\"deploy.dylib\")\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n\n        m.set_input(\"data\", tvm.nd.array(image, dev))\n        m.run()\n        tvm_output = m.get_output(0)\n        top1 = np.argmax(tvm_output.numpy()[0])\n        print(\"TVM prediction top-1:\", top1, synset[top1])\n\n        # evaluate\n        ftimer = m.module.time_evaluator(\"run\", dev, number=3, repeat=10)\n        prof_res = np.array(ftimer().results) * 1000\n        print(\"%-19s (%s)\" % (\"%.2f ms\" % np.mean(prof_res), \"%.2f ms\" % np.std(prof_res)))\n\n    def annotate(func, compiler):\n        \"\"\"\n        An annotator for Core ML.\n        \"\"\"\n        # Bind free variables to the constant values.\n        bind_dict = {}\n        for arg in func.params:\n            name = arg.name_hint\n            if name in params:\n                bind_dict[arg] = relay.const(params[name])\n\n        func = relay.bind(func, bind_dict)\n\n        # Annotate the entire graph for Core ML\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n\n        seq = tvm.transform.Sequential(\n            [\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n                transform.AnnotateTarget(compiler),\n                transform.MergeCompilerRegions(),\n                transform.PartitionGraph(),\n            ]\n        )\n\n        with relay.build_config(opt_level=3):\n            mod = seq(mod)\n\n        return mod\n\n    # CPU\n    run(model, target_host)\n    # Metal\n    run(model, \"metal\")\n    # CoreML\n    run(annotate(model, \"coremlcompiler\"), target_host)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Demo app demonstrates how ios_rpc works.\")\n    parser.add_argument(\"--host\", required=True, type=str, help=\"Adress of rpc server\")\n    parser.add_argument(\"--port\", type=int, default=9090, help=\"rpc port (default: 9090)\")\n    parser.add_argument(\"--key\", type=str, default=\"iphone\", help=\"device key (default: iphone)\")\n    parser.add_argument(\n        \"--mode\",\n        type=str,\n        default=\"tracker\",\n        help=\"type of RPC connection (default: tracker), possible values: {}\".format(\n            \", \".join(MODES.keys())\n        ),\n    )\n\n    args = parser.parse_args()\n    assert args.mode in MODES.keys()\n    test_mobilenet(args.host, args.port, args.key, args.mode)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tests/ios_rpc_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testcode for iOS RPC.\n\nTo use it, start a rpc proxy with \"python -m tvm.exec.rpc_proxy\".\nAnd configure the proxy host field as commented.\n\"\"\"\n\nimport tvm\nfrom tvm import te\nimport os\nimport re\nimport sys\nfrom tvm import rpc\nfrom tvm.contrib import utils, xcode\nimport numpy as np\nimport argparse\n\n# Change target configuration, this is setting for iphone6s\narch = \"arm64\"\nsdk = \"iphoneos\"\ntarget = \"llvm -mtriple=%s-apple-darwin\" % arch\n\nMODES = {\"proxy\": rpc.connect, \"tracker\": rpc.connect_tracker, \"standalone\": rpc.connect}\n\n# override metal compiler to compile to iphone\n@tvm.register_func(\"tvm_callback_metal_compile\")\ndef compile_metal(src):\n    return xcode.compile_metal(src, sdk=sdk)\n\n\ndef test_rpc_module(host, port, key, mode):\n    # graph\n    n = tvm.runtime.convert(1024)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    temp = utils.tempdir()\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=64)\n    s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    # Build the dynamic lib.\n    # If we don't want to do metal and only use cpu, just set target to be target\n    f = tvm.build(s, [A, B], tvm.target.Target(\"metal\", host=target), name=\"myadd\")\n    path_dso1 = temp.relpath(\"dev_lib.dylib\")\n    f.export_library(path_dso1, xcode.create_dylib, arch=arch, sdk=sdk)\n\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=64)\n    s[B].parallel(xi)\n    s[B].pragma(xo, \"parallel_launch_point\")\n    s[B].pragma(xi, \"parallel_barrier_when_finish\")\n    f = tvm.build(s, [A, B], target, name=\"myadd_cpu\")\n    path_dso2 = temp.relpath(\"cpu_lib.dylib\")\n    f.export_library(path_dso2, xcode.create_dylib, arch=arch, sdk=sdk)\n\n    # connect to the proxy\n    if mode == \"tracker\":\n        remote = MODES[mode](host, port).request(key)\n    else:\n        remote = MODES[mode](host, port, key=key)\n    remote.upload(path_dso1)\n    dev = remote.metal(0)\n    f1 = remote.load_module(\"dev_lib.dylib\")\n    a_np = np.random.uniform(size=1024).astype(A.dtype)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n    time_f = f1.time_evaluator(f1.entry_name, dev, number=10)\n    cost = time_f(a, b).mean\n    print(\"Metal: %g secs/op\" % cost)\n    np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n    # CPU\n    dev = remote.cpu(0)\n    remote.upload(path_dso2)\n    f2 = remote.load_module(\"cpu_lib.dylib\")\n    a_np = np.random.uniform(size=1024).astype(A.dtype)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n    time_f = f2.time_evaluator(f2.entry_name, dev, number=10)\n    cost = time_f(a, b).mean\n    print(\"CPU: %g secs/op\" % cost)\n    np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Demo app demonstrates how ios_rpc works.\")\n    parser.add_argument(\"--host\", required=True, type=str, help=\"Adress of rpc server\")\n    parser.add_argument(\"--port\", type=int, default=9090, help=\"rpc port (default: 9090)\")\n    parser.add_argument(\"--key\", type=str, default=\"iphone\", help=\"device key (default: iphone)\")\n    parser.add_argument(\n        \"--mode\",\n        type=str,\n        default=\"tracker\",\n        help=\"type of RPC connection (default: tracker), possible values: {}\".format(\n            \", \".join(MODES.keys())\n        ),\n    )\n\n    args = parser.parse_args()\n    assert args.mode in MODES.keys()\n    test_rpc_module(args.host, args.port, args.key, args.mode)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tvmrpc/AppDelegate.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file AppDelegate.h\n */\n\n#import <UIKit/UIKit.h>\n\n@interface AppDelegate : UIResponder <UIApplicationDelegate>\n\n@property(strong, nonatomic) UIWindow* window;\n\n@end\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tvmrpc/RPCArgs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_APPS_IOS_RPC_ARGS_H_\n#define TVM_APPS_IOS_RPC_ARGS_H_\n\n#import \"RPCServer.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*!\n * \\brief Struct representing arguments of iOS RPC app\n */\ntypedef struct RPCArgs_t {\n  /// Tracker or Proxy address (actually ip)\n  const char* host_url;\n\n  /// Tracker or Proxy port\n  int host_port;\n\n  /// device key to report\n  const char* key;\n\n  /// custom adress to report into Tracker. Ignored for other server modes.\n  const char* custom_addr;\n\n  /// Verbose mode. Will print status messages to std out.\n  /// 0 - no prints , 1 - print state to output\n  bool verbose;\n\n  /// Immediate server launch. No UI interaction.\n  /// 0 - UI interaction, 1 - automatically connect on launch\n  bool immediate_connect;\n\n  /// Server mode\n  RPCServerMode server_mode;\n} RPCArgs;\n\n/*!\n * \\brief Get current global RPC args\n */\nRPCArgs get_current_rpc_args(void);\n\n/*!\n * \\brief Set current global RPC args and update values in app cache\n */\nvoid set_current_rpc_args(RPCArgs args);\n\n/*!\n * \\brief Pars command line args and update current global RPC args\n * Also updates values in app cache\n */\nvoid update_rpc_args(int argc, char* argv[]);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_APPS_IOS_RPC_ARGS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tvmrpc/RPCServer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Provide interfaces to launch and control RPC Service routine\n */\n\n#import <Foundation/Foundation.h>\n\n/*!\n * \\brief Enum with possible status of RPC server\n * Used to report state to listener\n */\ntypedef enum {\n  RPCServerStatus_Launched,           // Worker thread is launched\n  RPCServerStatus_Stopped,            // Worker thread stopped\n  RPCServerStatus_Connected,          // Connected to Proxy/Tracker\n  RPCServerStatus_Disconnected,       // Disconnected from Proxy/Tracker\n  RPCServerStatus_RPCSessionStarted,  // RPC session is started\n  RPCServerStatus_RPCSessionFinished  // RPC session is finished\n} RPCServerStatus;\n\n/*!\n * \\brief Enum with modes of servicing supported by RPCServer\n */\ntypedef enum {\n  /// Tracker mode. Same as Standalone Server plus register it into Tracker.\n  RPCServerMode_Tracker,\n  /// Proxy mode. Connect to proxy server and wait response.\n  RPCServerMode_Proxy,\n  /// Standalone RPC server mode. Open port with RPC server and wait incoming connection.\n  RPCServerMode_Standalone\n} RPCServerMode;\n\n/*!\n * \\brief Listener for events happened with RPCServer\n */\n@protocol RPCServerEventListener <NSObject>\n/// Callback to notifying about new status\n- (void)onError:(NSString*)msg;\n/// Callback to notifying about error\n- (void)onStatusChanged:(RPCServerStatus)status;\n@end\n\n/*!\n * \\brief RPC Server instance\n * Contains internal worker thread plus\n */\n@interface RPCServer : NSObject <NSStreamDelegate>\n\n/// Event listener delegate to set\n@property(retain) id<RPCServerEventListener> delegate;\n/// Device key to report during RPC session\n@property(retain) NSString* key;\n/// Host address of Proxy/Tracker server (generally IPv4). Ignored for Standalone mode.\n@property(retain) NSString* host;\n/// Port of Proxy/Tracker server. Ignored for Standalone mode.\n@property int port;\n/// Custom address to report into tracker server (optional). Ignored for Standalone/Proxy modes\n@property(retain) NSString* custom_addr;\n/// Triger to enable printing of server state info\n@property BOOL verbose;\n/// RPC port opened on the device. Ignored for Proxy/Tracker modes\n@property int actual_port;\n/// IP address of the device. Ignored for Proxy/Tracker modes\n@property(retain) NSString* device_addr;\n\n/*!\n * \\brief Create server with specified sevicing mode\n * \\param mode Mode of server\n */\n+ (instancetype)serverWithMode:(RPCServerMode)mode;\n\n/*!\n * \\brief Start RPC server with options. Non blocking method\n */\n- (void)start;\n\n/*!\n * \\brief Stop RPC server. Non blocking method\n */\n- (void)stop;\n\n@end\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/ios_rpc/tvmrpc/ViewController.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ViewController.h\n */\n\n#import <UIKit/UIKit.h>\n#import \"RPCServer.h\"\n\n@interface ViewController : UIViewController <RPCServerEventListener, UITextFieldDelegate>\n\n@property(weak, nonatomic) IBOutlet UITextField* proxyURL;\n@property(weak, nonatomic) IBOutlet UITextField* proxyPort;\n@property(weak, nonatomic) IBOutlet UITextField* proxyKey;\n@property(weak, nonatomic) IBOutlet UILabel* statusLabel;\n@property(weak, nonatomic) IBOutlet UITextView* infoText;\n\n- (IBAction)connect:(id)sender;\n@property(retain, nonatomic) IBOutlet UIButton* ConnectButton;\n@property(retain, nonatomic) IBOutlet UISegmentedControl* ModeSelector;\n\n@end\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/lldb/tvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pretty Printers for lldb debugger.\nInstall the pretty printers by loading this file from .lldbinit:\n  command script import ~/bin/lldb/tvm.py\nUpdate the list of nodes for which debug information is displayed\nby adding to the list below.\n\"\"\"\n\n\nimport lldb\nimport lldb.formatters\n\ng_indent = 0\n\n\ndef __lldb_init_module(debugger, _):\n    # Only types that are supported by PrettyPrint() will be printed.\n    for node in [\n        \"tvm::Array\",\n        \"tvm::AttrFieldInfo\",\n        \"tvm::Attrs\",\n        \"tvm::BijectiveLayout\",\n        \"tvm::Buffer\",\n        \"tvm::Channel\",\n        \"tvm::EnvFunc\",\n        \"tvm::Expr\",\n        \"tvm::GenericFunc\",\n        \"tvm::Integer\",\n        \"tvm::IterVar\",\n        \"tvm::IterVarAttr\",\n        \"tvm::IterVarRelation\",\n        \"tvm::Layout\",\n        \"tvm::Map\",\n        \"tvm::Map\",\n        \"tvm::MemoryInfo\",\n        \"tvm::Operation\",\n        \"tvm::Range\",\n        \"tvm::Schedule\",\n        \"tvm::Stage\",\n        \"tvm::Stmt\",\n        \"tvm::Target\",\n        \"tvm::Tensor\",\n        \"tvm::TensorIntrin\",\n        \"tvm::TensorIntrinCall\",\n        \"tvm::TypedEnvFunc\",\n        \"tvm::tir::Var\",\n        \"tvm::ir::CommReducer\",\n        \"tvm::ir::FunctionRef\",\n        \"tvm::relay::BaseTensorType\",\n        \"tvm::relay::CCacheKey\",\n        \"tvm::relay::CCacheValue\",\n        \"tvm::relay::CachedFunc\",\n        \"tvm::relay::Call\",\n        \"tvm::relay::Clause\",\n        \"tvm::relay::Closure\",\n        \"tvm::relay::CompileEngine\",\n        \"tvm::relay::Constant\",\n        \"tvm::relay::Constructor\",\n        \"tvm::relay::ConstructorValue\",\n        \"tvm::relay::Expr\",\n        \"tvm::relay::FuncType\",\n        \"tvm::relay::Function\",\n        \"tvm::relay::GlobalTypeVar\",\n        \"tvm::relay::GlobalVar\",\n        \"tvm::relay::Id\",\n        \"tvm::relay::If\",\n        \"tvm::relay::IncompleteType\",\n        \"tvm::relay::InterpreterState\",\n        \"tvm::relay::Let\",\n        \"tvm::relay::Match\",\n        \"tvm::relay::Module\",\n        \"tvm::relay::NamedNDArray\",\n        \"tvm::relay::Op\",\n        \"tvm::relay::Pattern\",\n        \"tvm::relay::PatternConstructor\",\n        \"tvm::relay::PatternTuple\",\n        \"tvm::relay::PatternVar\",\n        \"tvm::relay::PatternWildcard\",\n        \"tvm::relay::RecClosure\",\n        \"tvm::relay::RefCreate\",\n        \"tvm::relay::RefRead\",\n        \"tvm::relay::RefType\",\n        \"tvm::relay::RefValue\",\n        \"tvm::relay::RefWrite\",\n        \"tvm::relay::SourceName\",\n        \"tvm::relay::Span\",\n        \"tvm::relay::TempExpr\",\n        \"tvm::relay::TensorType\",\n        \"tvm::relay::Tuple\",\n        \"tvm::relay::TupleGetItem\",\n        \"tvm::relay::TupleType\",\n        \"tvm::relay::Type\",\n        \"tvm::relay::TypeCall\",\n        \"tvm::relay::TypeConstraint\",\n        \"tvm::relay::TypeData\",\n        \"tvm::relay::TypeRelation\",\n        \"tvm::relay::TypeReporter\",\n        \"tvm::relay::TypeVar\",\n        \"tvm::relay::Value\",\n        \"tvm::relay::Var\",\n        \"tvm::relay::alter_op_layout::LayoutAlternatedExpr\",\n        \"tvm::relay::alter_op_layout::TransformMemorizer\",\n        \"tvm::relay::fold_scale_axis::Message\",\n        \"tvm::relay::fold_scale_axis:BackwardTransformer\",\n    ]:\n        debugger.HandleCommand(\n            \"type summary add -F tvm.NodeRef_SummaryProvider {node} -w tvm\".format(node=node)\n        )\n    debugger.HandleCommand(\"command script add -f tvm.PrettyPrint pp\")\n    debugger.HandleCommand(\"type category enable tvm\")\n\n\ndef _log(logger, fmt, *args, **kwargs):\n    global g_indent\n    logger >> \" \" * g_indent + fmt.format(*args, **kwargs)\n\n\ndef _GetContext(debugger):\n    target = debugger.GetSelectedTarget()\n    process = target.GetProcess()\n    thread = process.GetThreadAtIndex(0)\n    return thread.GetSelectedFrame()\n\n\ndef PrettyPrint(debugger, command, result, internal_dict):\n    ctx = _GetContext(debugger)\n    rc = ctx.EvaluateExpression(\"tvm::PrettyPrint({command})\".format(command=command))\n    result.AppendMessage(str(rc))\n\n\nclass EvaluateError(Exception):\n    def __init__(self, error):\n        super(Exception, self).__init__(str(error))\n\n\ndef _EvalExpression(logger, ctx, expr, value_name):\n    _log(logger, \"Evaluating {expr}\".format(expr=expr))\n\n    rc = ctx.EvaluateExpression(expr)\n    err = rc.GetError()\n    if err.Fail():\n        _log(logger, \"_EvalExpression failed: {err}\".format(err=err))\n        raise EvaluateError(err)\n    _log(logger, \"_EvalExpression success: {typename}\".format(typename=rc.GetTypeName()))\n    return rc\n\n\ndef _EvalExpressionAsString(logger, ctx, expr):\n    result = _EvalExpression(logger, ctx, expr, None)\n    return result.GetSummary() or result.GetValue() or \"--\"\n\n\ndef _EvalAsNodeRef(logger, ctx, value):\n    return _EvalExpressionAsString(logger, ctx, \"tvm::PrettyPrint({name})\".format(name=value.name))\n\n\ndef NodeRef_SummaryProvider(value, _):\n    global g_indent\n    g_indent += 2\n\n    try:\n        if not value or not value.IsValid():\n            return \"<invalid>\"\n\n        lldb.formatters.Logger._lldb_formatters_debug_level = 0\n        logger = lldb.formatters.Logger.Logger()\n\n        ctx = _GetContext(lldb.debugger)\n        return _EvalAsNodeRef(logger, ctx, value)\n\n    except EvaluateError as e:\n        return str(e)\n    finally:\n        g_indent -= 2\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/arduino/template_project/crt_config/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief CRT configuration for the host-linked CRT.\n */\n#ifndef TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n#define TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Support low-level debugging in MISRA-C runtime */\n#define TVM_CRT_DEBUG 0\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\" */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 8 * 1024\n\n/*! \\brief Maximum length of a PackedFunc function name. */\n#define TVM_CRT_MAX_FUNCTION_NAME_LENGTH_BYTES 30\n\n// #define TVM_CRT_FRAMER_ENABLE_LOGS\n\n#endif  // TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/arduino/template_project/microtvm_api_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport logging\nimport os.path\nimport pathlib\nimport re\nimport shutil\nimport subprocess\nimport tarfile\nimport tempfile\nimport time\nfrom string import Template\nfrom packaging import version\n\nfrom tvm.micro.project_api import server\n\n_LOG = logging.getLogger(__name__)\n\nMODEL_LIBRARY_FORMAT_RELPATH = pathlib.Path(\"src\") / \"model\" / \"model.tar\"\nAPI_SERVER_DIR = pathlib.Path(os.path.dirname(__file__) or os.path.getcwd())\nBUILD_DIR = API_SERVER_DIR / \"build\"\nMODEL_LIBRARY_FORMAT_PATH = API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH\n\nIS_TEMPLATE = not (API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH).exists()\n\nMIN_ARDUINO_CLI_VERSION = version.parse(\"0.18.0\")\n\nBOARDS = API_SERVER_DIR / \"boards.json\"\n\nARDUINO_CLI_CMD = shutil.which(\"arduino-cli\")\n\nMAKEFILE_FILENAME = \"Makefile\"\n\n# Data structure to hold the information microtvm_api_server.py needs\n# to communicate with each of these boards.\ntry:\n    with open(BOARDS) as boards:\n        BOARD_PROPERTIES = json.load(boards)\nexcept FileNotFoundError:\n    raise FileNotFoundError(f\"Board file {{{BOARDS}}} does not exist.\")\n\n\ndef get_cmsis_path(cmsis_path: pathlib.Path) -> pathlib.Path:\n    \"\"\"Returns CMSIS dependency path\"\"\"\n    if cmsis_path:\n        return pathlib.Path(cmsis_path)\n    if os.environ.get(\"CMSIS_PATH\"):\n        return pathlib.Path(os.environ.get(\"CMSIS_PATH\"))\n    assert False, \"'cmsis_path' option not passed!\"\n\n\nclass BoardAutodetectFailed(Exception):\n    \"\"\"Raised when no attached hardware is found matching the requested board\"\"\"\n\n\nPROJECT_TYPES = [\"example_project\", \"host_driven\"]\n\nPROJECT_OPTIONS = server.default_project_options(\n    project_type={\"choices\": tuple(PROJECT_TYPES)},\n    board={\"choices\": list(BOARD_PROPERTIES), \"optional\": [\"flash\", \"open_transport\"]},\n    warning_as_error={\"optional\": [\"build\", \"flash\"]},\n) + [\n    server.ProjectOption(\n        \"arduino_cli_cmd\",\n        required=([\"generate_project\", \"flash\", \"open_transport\"] if not ARDUINO_CLI_CMD else None),\n        optional=(\n            [\"generate_project\", \"build\", \"flash\", \"open_transport\"] if ARDUINO_CLI_CMD else None\n        ),\n        type=\"str\",\n        default=ARDUINO_CLI_CMD,\n        help=\"Path to the arduino-cli tool.\",\n    ),\n    server.ProjectOption(\n        \"port\",\n        optional=[\"flash\", \"open_transport\"],\n        type=\"int\",\n        default=None,\n        help=\"Port to use for connecting to hardware.\",\n    ),\n]\n\n\nclass Handler(server.ProjectAPIHandler):\n    def __init__(self):\n        super(Handler, self).__init__()\n        self._proc = None\n        self._port = None\n        self._serial = None\n        self._version = None\n\n    def server_info_query(self, tvm_version):\n        return server.ServerInfo(\n            platform_name=\"arduino\",\n            is_template=IS_TEMPLATE,\n            model_library_format_path=\"\" if IS_TEMPLATE else MODEL_LIBRARY_FORMAT_PATH,\n            project_options=PROJECT_OPTIONS,\n        )\n\n    def _copy_project_files(self, api_server_dir, project_dir, project_type):\n        \"\"\"Copies the files for project_type into project_dir.\n\n        Notes\n        -----\n        template_dir is NOT a project type, and that directory is never copied\n        in this function. template_dir only holds this file and its unit tests,\n        so this file is copied separately in generate_project.\n\n        \"\"\"\n        for item in (API_SERVER_DIR / \"src\" / project_type).iterdir():\n            if item.name == \"project.ino\":\n                continue\n            dest = project_dir / \"src\" / item.name\n            if item.is_dir():\n                shutil.copytree(item, dest)\n            else:\n                shutil.copy2(item, dest)\n\n        # Arduino requires the .ino file have the same filename as its containing folder\n        shutil.copy2(\n            API_SERVER_DIR / \"src\" / project_type / \"project.ino\",\n            project_dir / f\"{project_dir.stem}.ino\",\n        )\n\n    CRT_COPY_ITEMS = (\"include\", \"src\")\n\n    def _copy_standalone_crt(self, source_dir, standalone_crt_dir):\n        output_crt_dir = source_dir / \"standalone_crt\"\n        for item in self.CRT_COPY_ITEMS:\n            src_path = os.path.join(standalone_crt_dir, item)\n            dst_path = output_crt_dir / item\n            if os.path.isdir(src_path):\n                shutil.copytree(src_path, dst_path)\n            else:\n                shutil.copy2(src_path, dst_path)\n\n    # Example project is the \"minimum viable project\",\n    # and doesn't need a fancy RPC server\n    EXAMPLE_PROJECT_UNUSED_COMPONENTS = [\n        \"include/dmlc\",\n        \"src/support\",\n        \"src/runtime/minrpc\",\n        \"src/runtime/crt/graph_executor\",\n        \"src/runtime/crt/microtvm_rpc_common\",\n        \"src/runtime/crt/microtvm_rpc_server\",\n        \"src/runtime/crt/tab\",\n    ]\n\n    def _remove_unused_components(self, source_dir, project_type):\n        unused_components = []\n        if project_type == \"example_project\":\n            unused_components = self.EXAMPLE_PROJECT_UNUSED_COMPONENTS\n\n        for component in unused_components:\n            shutil.rmtree(source_dir / \"standalone_crt\" / component)\n\n    def _disassemble_mlf(self, mlf_tar_path, source_dir):\n        with tempfile.TemporaryDirectory() as mlf_unpacking_dir_str:\n            mlf_unpacking_dir = pathlib.Path(mlf_unpacking_dir_str)\n            with tarfile.open(mlf_tar_path, \"r:\") as tar:\n                tar.extractall(mlf_unpacking_dir)\n\n            model_dir = source_dir / \"model\"\n            model_dir.mkdir()\n\n            # Copy C files from model. The filesnames and quantity\n            # depend on the target string, so we just copy all c files\n            source_dir = mlf_unpacking_dir / \"codegen\" / \"host\" / \"src\"\n            for file in source_dir.rglob(\"*.c\"):\n                shutil.copy(file, model_dir)\n\n            # Return metadata.json for use in templating\n            with open(os.path.join(mlf_unpacking_dir, \"metadata.json\")) as f:\n                metadata = json.load(f)\n        return metadata\n\n    def _template_model_header(self, source_dir, metadata):\n        with open(source_dir / \"model.h\", \"r\") as f:\n            model_h_template = Template(f.read())\n\n        all_module_names = []\n        for name in metadata[\"modules\"].keys():\n            all_module_names.append(name)\n\n        assert all(\n            metadata[\"modules\"][mod_name][\"style\"] == \"full-model\" for mod_name in all_module_names\n        ), \"when generating AOT, expect only full-model Model Library Format\"\n\n        workspace_size_bytes = 0\n        for mod_name in all_module_names:\n            workspace_size_bytes += metadata[\"modules\"][mod_name][\"memory\"][\"functions\"][\"main\"][0][\n                \"workspace_size_bytes\"\n            ]\n        template_values = {\n            \"workspace_size_bytes\": workspace_size_bytes,\n        }\n\n        with open(source_dir / \"model.h\", \"w\") as f:\n            f.write(model_h_template.substitute(template_values))\n\n    # Arduino ONLY recognizes .ino, .ccp, .c, .h\n\n    CPP_FILE_EXTENSION_SYNONYMS = (\"cc\", \"cxx\")\n\n    def _change_cpp_file_extensions(self, source_dir):\n        for ext in self.CPP_FILE_EXTENSION_SYNONYMS:\n            for filename in source_dir.rglob(f\"*.{ext}\"):\n                filename.rename(filename.with_suffix(\".cpp\"))\n\n        for filename in source_dir.rglob(\"*.inc\"):\n            filename.rename(filename.with_suffix(\".h\"))\n\n    def _convert_includes(self, project_dir, source_dir):\n        \"\"\"Changes all #include statements in project_dir to be relevant to their\n        containing file's location.\n\n        Arduino only supports includes relative to a file's location, so this\n        function finds each time we #include a file and changes the path to\n        be relative to the file location. Does not do this for standard C\n        libraries. Also changes angle brackets syntax to double quotes syntax.\n\n        See Also\n        -----\n        https://www.arduino.cc/reference/en/language/structure/further-syntax/include/\n\n        \"\"\"\n        for ext in (\"c\", \"h\", \"cpp\"):\n            for filename in source_dir.rglob(f\"*.{ext}\"):\n                with filename.open(\"rb\") as src_file:\n                    lines = src_file.readlines()\n                    with filename.open(\"wb\") as dst_file:\n                        for line in lines:\n                            line_str = str(line, \"utf-8\")\n                            # Check if line has an include\n                            result = re.search(r\"#include\\s*[<\\\"]([^>]*)[>\\\"]\", line_str)\n                            if not result:\n                                dst_file.write(line)\n                            else:\n                                new_include = self._find_modified_include_path(\n                                    project_dir, filename, result.groups()[0]\n                                )\n                                updated_line = f'#include \"{new_include}\"\\n'\n                                dst_file.write(updated_line.encode(\"utf-8\"))\n\n    # Most of the files we used to be able to point to directly are under \"src/standalone_crt/include/\".\n    # Howver, crt_config.h lives under \"src/standalone_crt/crt_config/\", and more exceptions might\n    # be added in the future.\n    POSSIBLE_BASE_PATHS = [\"src/standalone_crt/include/\", \"src/standalone_crt/crt_config/\"]\n\n    def _find_modified_include_path(self, project_dir, file_path, include_path):\n        \"\"\"Takes a single #include path, and returns the location it should point to.\n\n        Examples\n        --------\n        >>> _find_modified_include_path(\n        ...     \"/path/to/project/dir\"\n        ...     \"/path/to/project/dir/src/standalone_crt/src/runtime/crt/common/ndarray.c\"\n        ...     \"tvm/runtime/crt/platform.h\"\n        ... )\n        \"../../../../../../src/standalone_crt/include/tvm/runtime/crt/platform.h\"\n\n        \"\"\"\n        if include_path.endswith(\".inc\"):\n            include_path = re.sub(r\"\\.[a-z]+$\", \".h\", include_path)\n\n        # Change includes referencing .cc and .cxx files to point to the renamed .cpp file\n        if include_path.endswith(self.CPP_FILE_EXTENSION_SYNONYMS):\n            include_path = re.sub(r\"\\.[a-z]+$\", \".cpp\", include_path)\n\n        # If the include already works, don't modify it\n        if (file_path.parents[0] / include_path).exists():\n            return include_path\n\n        relative_path = file_path.relative_to(project_dir)\n        up_dirs_path = \"../\" * str(relative_path).count(\"/\")\n\n        for base_path in self.POSSIBLE_BASE_PATHS:\n            full_potential_path = project_dir / base_path / include_path\n            if full_potential_path.exists():\n                return up_dirs_path + base_path + include_path\n\n        # If we can't find the file, just leave it untouched\n        # It's probably a standard C/C++ header\n        return include_path\n\n    CMSIS_INCLUDE_HEADERS = [\n        \"arm_nn_math_types.h\",\n        \"arm_nn_tables.h\",\n        \"arm_nn_types.h\",\n        \"arm_nnfunctions.h\",\n        \"arm_nnsupportfunctions.h\",\n    ]\n\n    def _cmsis_required(self, project_path: pathlib.Path) -> bool:\n        \"\"\"Check if CMSIS dependency is required.\"\"\"\n        project_path = pathlib.Path(project_path)\n        for path in (project_path / \"src\" / \"model\").iterdir():\n            if path.is_file():\n                # Encoding is for reading C generated code which also includes hex numbers\n                with open(path, \"r\", encoding=\"ISO-8859-1\") as lib_f:\n                    lib_content = lib_f.read()\n                if any(header in lib_content for header in self.CMSIS_INCLUDE_HEADERS):\n                    return True\n        return False\n\n    def _copy_cmsis(self, project_path: pathlib.Path, cmsis_path: str):\n        \"\"\"Copy CMSIS header files to project.\n        Note: We use this CMSIS package:https://www.arduino.cc/reference/en/libraries/arduino_cmsis-dsp/\n        However, the latest release does not include header files that are copied in this function.\n        \"\"\"\n        (project_path / \"include\" / \"cmsis\").mkdir()\n        cmsis_path = get_cmsis_path(cmsis_path)\n        for item in self.CMSIS_INCLUDE_HEADERS:\n            shutil.copy2(\n                cmsis_path / \"CMSIS\" / \"NN\" / \"Include\" / item,\n                project_path / \"include\" / \"cmsis\" / item,\n            )\n\n    def _populate_makefile(\n        self,\n        makefile_template_path: pathlib.Path,\n        makefile_path: pathlib.Path,\n        board: str,\n        verbose: bool,\n        arduino_cli_cmd: str,\n        build_extra_flags: str,\n    ):\n        \"\"\"Generate Makefile from template.\"\"\"\n        flags = {\n            \"FQBN\": self._get_fqbn(board),\n            \"VERBOSE_FLAG\": \"--verbose\" if verbose else \"\",\n            \"ARUINO_CLI_CMD\": self._get_arduino_cli_cmd(arduino_cli_cmd),\n            \"BOARD\": board,\n            \"BUILD_EXTRA_FLAGS\": build_extra_flags,\n        }\n\n        with open(makefile_path, \"w\") as makefile_f:\n            with open(makefile_template_path, \"r\") as makefile_template_f:\n                for line in makefile_template_f:\n                    SUBST_TOKEN_RE = re.compile(r\"<([A-Z_]+)>\")\n                    outs = []\n                    for i, m in enumerate(re.split(SUBST_TOKEN_RE, line)):\n                        if i % 2 == 1:\n                            m = flags[m]\n                        outs.append(m)\n                    line = \"\".join(outs)\n                    makefile_f.write(line)\n\n    def generate_project(self, model_library_format_path, standalone_crt_dir, project_dir, options):\n        # List all used project options\n        board = options[\"board\"]\n        verbose = options.get(\"verbose\")\n        project_type = options[\"project_type\"]\n        arduino_cli_cmd = options.get(\"arduino_cli_cmd\")\n        cmsis_path = options.get(\"cmsis_path\")\n        compile_definitions = options.get(\"compile_definitions\")\n        extra_files_tar = options.get(\"extra_files_tar\")\n\n        # Reference key directories with pathlib\n        project_dir = pathlib.Path(project_dir)\n        project_dir.mkdir()\n        source_dir = project_dir / \"src\"\n        source_dir.mkdir()\n\n        # Copies files from the template folder to project_dir\n        shutil.copy2(API_SERVER_DIR / \"microtvm_api_server.py\", project_dir)\n        shutil.copy2(BOARDS, project_dir / BOARDS.name)\n        self._copy_project_files(API_SERVER_DIR, project_dir, project_type)\n\n        # Copy standalone_crt into src folder\n        self._copy_standalone_crt(source_dir, standalone_crt_dir)\n        self._remove_unused_components(source_dir, project_type)\n\n        # Populate crt-config.h\n        crt_config_dir = project_dir / \"src\" / \"standalone_crt\" / \"crt_config\"\n        crt_config_dir.mkdir()\n        shutil.copy2(\n            API_SERVER_DIR / \"crt_config\" / \"crt_config.h\", crt_config_dir / \"crt_config.h\"\n        )\n\n        # Unpack the MLF and copy the relevant files\n        metadata = self._disassemble_mlf(model_library_format_path, source_dir)\n        shutil.copy2(model_library_format_path, project_dir / MODEL_LIBRARY_FORMAT_RELPATH)\n\n        # For AOT, template model.h with metadata to minimize space usage\n        if project_type == \"example_project\":\n            self._template_model_header(source_dir, metadata)\n\n        self._change_cpp_file_extensions(source_dir)\n\n        # Recursively change includes\n        self._convert_includes(project_dir, source_dir)\n\n        # create include directory\n        (project_dir / \"include\").mkdir()\n\n        # Populate extra_files\n        if extra_files_tar:\n            with tarfile.open(extra_files_tar, mode=\"r:*\") as tf:\n                tf.extractall(project_dir)\n\n        build_extra_flags = '\"build.extra_flags='\n        if extra_files_tar:\n            build_extra_flags += \"-I./include \"\n\n        if compile_definitions:\n            for item in compile_definitions:\n                build_extra_flags += f\"{item} \"\n\n        if self._cmsis_required(project_dir):\n            build_extra_flags += f\"-I./include/cmsis \"\n            self._copy_cmsis(project_dir, cmsis_path)\n\n        build_extra_flags += '\"'\n\n        # Check if build_extra_flags is empty\n        if build_extra_flags == '\"build.extra_flags=\"':\n            build_extra_flags = '\"\"'\n\n        # Populate Makefile\n        self._populate_makefile(\n            API_SERVER_DIR / f\"{MAKEFILE_FILENAME}.template\",\n            project_dir / MAKEFILE_FILENAME,\n            board,\n            verbose,\n            arduino_cli_cmd,\n            build_extra_flags,\n        )\n\n    def _get_arduino_cli_cmd(self, arduino_cli_cmd: str):\n        if not arduino_cli_cmd:\n            arduino_cli_cmd = ARDUINO_CLI_CMD\n        assert arduino_cli_cmd, \"'arduino_cli_cmd' command not passed and not found by default!\"\n        return arduino_cli_cmd\n\n    def _get_platform_version(self, arduino_cli_path: str) -> float:\n        # sample output of this command:\n        # 'arduino-cli alpha Version: 0.18.3 Commit: d710b642 Date: 2021-05-14T12:36:58Z\\n'\n        version_output = subprocess.run(\n            [arduino_cli_path, \"version\"], check=True, stdout=subprocess.PIPE\n        ).stdout.decode(\"utf-8\")\n        str_version = re.search(r\"Version: ([\\.0-9]*)\", version_output).group(1)\n\n        # Using too low a version should raise an error. Note that naively\n        # comparing floats will fail here: 0.7 > 0.21, but 0.21 is a higher\n        # version (hence we need version.parse)\n        return version.parse(str_version)\n\n    # This will only be run for build and upload\n    def _check_platform_version(self, cli_command: str, warning_as_error: bool):\n        if not self._version:\n            self._version = self._get_platform_version(cli_command)\n\n        if self._version < MIN_ARDUINO_CLI_VERSION:\n            message = (\n                f\"Arduino CLI version too old: found {self._version}, \"\n                f\"need at least {str(MIN_ARDUINO_CLI_VERSION)}.\"\n            )\n            if warning_as_error is not None and warning_as_error:\n                raise server.ServerError(message=message)\n            _LOG.warning(message)\n\n    def _get_fqbn(self, board: str):\n        o = BOARD_PROPERTIES[board]\n        return f\"{o['package']}:{o['architecture']}:{o['board']}\"\n\n    def build(self, options):\n        # List all used project options\n        arduino_cli_cmd = options.get(\"arduino_cli_cmd\")\n        warning_as_error = options.get(\"warning_as_error\")\n\n        cli_command = self._get_arduino_cli_cmd(arduino_cli_cmd)\n        self._check_platform_version(cli_command, warning_as_error)\n        compile_cmd = [\"make\", \"build\"]\n        # Specify project to compile\n        subprocess.run(compile_cmd, check=True, cwd=API_SERVER_DIR)\n\n    POSSIBLE_BOARD_LIST_HEADERS = (\"Port\", \"Protocol\", \"Type\", \"Board Name\", \"FQBN\", \"Core\")\n\n    def _parse_connected_boards(self, tabular_str):\n        \"\"\"Parses the tabular output from `arduino-cli board list` into a 2D array\n\n        Examples\n        --------\n        >>> list(_parse_connected_boards(bytes(\n        ...     \"Port         Type              Board Name FQBN                          Core               \\n\"\n        ...     \"/dev/ttyS4   Serial Port       Unknown                                                     \\n\"\n        ...     \"/dev/ttyUSB0 Serial Port (USB) Spresense  SPRESENSE:spresense:spresense SPRESENSE:spresense\\n\"\n        ...     \"\\n\",\n        ... \"utf-8\")))\n        [['/dev/ttys4', 'Serial Port', 'Unknown', '', ''], ['/dev/ttyUSB0', 'Serial Port (USB)',\n        'Spresense', 'SPRESENSE:spresense:spresense', 'SPRESENSE:spresense']]\n\n        \"\"\"\n\n        # Which column headers are present depends on the version of arduino-cli\n        column_regex = r\"\\s*|\".join(self.POSSIBLE_BOARD_LIST_HEADERS) + r\"\\s*\"\n        str_rows = tabular_str.split(\"\\n\")\n        column_headers = list(re.finditer(column_regex, str_rows[0]))\n        assert len(column_headers) > 0\n\n        for str_row in str_rows[1:]:\n            if not str_row.strip():\n                continue\n            device = {}\n\n            for column in column_headers:\n                col_name = column.group(0).strip().lower()\n                device[col_name] = str_row[column.start() : column.end()].strip()\n            yield device\n\n    def _auto_detect_port(self, arduino_cli_cmd: str, board: str) -> str:\n        list_cmd = [self._get_arduino_cli_cmd(arduino_cli_cmd), \"board\", \"list\"]\n        list_cmd_output = subprocess.run(\n            list_cmd, check=True, stdout=subprocess.PIPE\n        ).stdout.decode(\"utf-8\")\n\n        desired_fqbn = self._get_fqbn(board)\n        for device in self._parse_connected_boards(list_cmd_output):\n            if device[\"fqbn\"] == desired_fqbn:\n                return device[\"port\"]\n\n        # If no compatible boards, raise an error\n        raise BoardAutodetectFailed()\n\n    def _get_arduino_port(self, arduino_cli_cmd: str, board: str, port: int):\n        if not self._port:\n            if port:\n                self._port = port\n            else:\n                self._port = self._auto_detect_port(arduino_cli_cmd, board)\n\n        return self._port\n\n    def _get_board_from_makefile(self, makefile_path: pathlib.Path) -> str:\n        \"\"\"Get Board from generated Makefile.\"\"\"\n        with open(makefile_path) as makefile_f:\n            line = makefile_f.readline()\n            if \"BOARD\" in line:\n                board = re.sub(r\"\\s\", \"\", line).split(\":=\")[1]\n                return board\n        raise RuntimeError(\"Board was not found in Makefile: {}\".format(makefile_path))\n\n    FLASH_TIMEOUT_SEC = 60\n    FLASH_MAX_RETRIES = 5\n\n    def flash(self, options):\n        # List all used project options\n        arduino_cli_cmd = options.get(\"arduino_cli_cmd\")\n        warning_as_error = options.get(\"warning_as_error\")\n        port = options.get(\"port\")\n        board = options.get(\"board\")\n        if not board:\n            board = self._get_board_from_makefile(API_SERVER_DIR / MAKEFILE_FILENAME)\n\n        cli_command = self._get_arduino_cli_cmd(arduino_cli_cmd)\n        self._check_platform_version(cli_command, warning_as_error)\n        port = self._get_arduino_port(cli_command, board, port)\n\n        upload_cmd = [\"make\", \"flash\", f\"PORT={port}\"]\n        for _ in range(self.FLASH_MAX_RETRIES):\n            try:\n                subprocess.run(\n                    upload_cmd, check=True, timeout=self.FLASH_TIMEOUT_SEC, cwd=API_SERVER_DIR\n                )\n                break\n\n            # We only catch timeout errors - a subprocess.CalledProcessError\n            # (caused by subprocess.run returning non-zero code) will not\n            # be caught.\n            except subprocess.TimeoutExpired:\n                _LOG.warning(\n                    f\"Upload attempt to port {port} timed out after {self.FLASH_TIMEOUT_SEC} seconds\"\n                )\n\n        else:\n            raise RuntimeError(\n                f\"Unable to flash Arduino board after {self.FLASH_MAX_RETRIES} attempts\"\n            )\n\n    def open_transport(self, options):\n        import serial\n        import serial.tools.list_ports\n\n        # List all used project options\n        arduino_cli_cmd = options.get(\"arduino_cli_cmd\")\n        port = options.get(\"port\")\n        board = options.get(\"board\")\n        if not board:\n            board = self._get_board_from_makefile(API_SERVER_DIR / MAKEFILE_FILENAME)\n\n        # Zephyr example doesn't throw an error in this case\n        if self._serial is not None:\n            return\n\n        port = self._get_arduino_port(arduino_cli_cmd, board, port)\n\n        # It takes a moment for the Arduino code to finish initializing\n        # and start communicating over serial\n        for _ in range(10):\n            if any(serial.tools.list_ports.grep(port)):\n                break\n            time.sleep(0.5)\n\n        self._serial = serial.Serial(port, baudrate=115200, timeout=10)\n\n        return server.TransportTimeouts(\n            session_start_retry_timeout_sec=2.0,\n            session_start_timeout_sec=5.0,\n            session_established_timeout_sec=5.0,\n        )\n\n    def close_transport(self):\n        if self._serial is None:\n            return\n        self._serial.close()\n        self._serial = None\n\n    def read_transport(self, n, timeout_sec):\n        self._serial.timeout = timeout_sec\n        if self._serial is None:\n            raise server.TransportClosedError()\n        return self._serial.read(n)\n\n    def write_transport(self, data, timeout_sec):\n        self._serial.write_timeout = timeout_sec\n        if self._serial is None:\n            raise server.TransportClosedError()\n        return self._serial.write(data)\n\n\nif __name__ == \"__main__\":\n    server.main(Handler())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/arduino/template_project/src/example_project/model.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"model.h\"\n\n#include \"Arduino.h\"\n#include \"standalone_crt/include/dlpack/dlpack.h\"\n#include \"standalone_crt/include/tvm/runtime/crt/stack_allocator.h\"\n\n// AOT memory array, stack allocator wants it aligned\nstatic uint8_t g_aot_memory[WORKSPACE_SIZE]\n    __attribute__((aligned(TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)));\ntvm_workspace_t app_workspace;\n\n// Blink code for debugging purposes\nvoid TVMPlatformAbort(tvm_crt_error_t error) {\n  TVMLogf(\"TVMPlatformAbort: 0x%08x\\n\", error);\n  for (;;) {\n#ifdef LED_BUILTIN\n    digitalWrite(LED_BUILTIN, HIGH);\n    delay(250);\n    digitalWrite(LED_BUILTIN, LOW);\n    delay(250);\n    digitalWrite(LED_BUILTIN, HIGH);\n    delay(250);\n    digitalWrite(LED_BUILTIN, LOW);\n    delay(750);\n#endif\n  }\n}\n\nvoid TVMLogf(const char* msg, ...) {}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return StackMemoryManager_Allocate(&app_workspace, num_bytes, out_ptr);\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return StackMemoryManager_Free(&app_workspace, ptr);\n}\n\nunsigned long g_utvm_start_time_micros;\nint g_utvm_timer_running = 0;\n\ntvm_crt_error_t TVMPlatformTimerStart() {\n  if (g_utvm_timer_running) {\n    return kTvmErrorPlatformTimerBadState;\n  }\n  g_utvm_timer_running = 1;\n  g_utvm_start_time_micros = micros();\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  if (!g_utvm_timer_running) {\n    return kTvmErrorPlatformTimerBadState;\n  }\n  g_utvm_timer_running = 0;\n  unsigned long g_utvm_stop_time = micros() - g_utvm_start_time_micros;\n  *elapsed_time_seconds = ((double)g_utvm_stop_time) / 1e6;\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMPlatformGenerateRandom(uint8_t* buffer, size_t num_bytes) {\n  for (size_t i = 0; i < num_bytes; i++) {\n    buffer[i] = rand();\n  }\n  return kTvmErrorNoError;\n}\n\nvoid TVMInitialize() { StackMemoryManager_Init(&app_workspace, g_aot_memory, WORKSPACE_SIZE); }\n\nvoid TVMExecute(void* input_data, void* output_data) {\n  int ret_val = tvmgen_default___tvm_main__(input_data, output_data);\n  if (ret_val != 0) {\n    TVMPlatformAbort(kTvmErrorPlatformCheckFailure);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/arduino/template_project/src/example_project/model.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#define WORKSPACE_SIZE $workspace_size_bytes\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid TVMInitialize();\n\n/* TODO template this function signature with the input and output\n * data types and sizes. For example:\n *\n * void TVMExecute(uint8_t input_data[9216], uint8_t output_data[3]);\n *\n * Note this can only be done once MLF has JSON metadata describing\n * inputs and outputs.\n */\nvoid TVMExecute(void* input_data, void* output_data);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/arduino/template_project/src/host_driven/model_support.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"standalone_crt/include/dlpack/dlpack.h\"\n#include \"standalone_crt/include/tvm/runtime/crt/error_codes.h\"\n#include \"stdarg.h\"\n\n// Blink code for debugging purposes\nvoid TVMPlatformAbort(tvm_crt_error_t error) {\n  TVMLogf(\"TVMPlatformAbort: 0x%08x\\n\", error);\n  for (;;)\n    ;\n}\n\nsize_t TVMPlatformFormatMessage(char* out_buf, size_t out_buf_size_bytes, const char* fmt,\n                                va_list args) {\n  return vsnprintf(out_buf, out_buf_size_bytes, fmt, args);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  if (num_bytes == 0) {\n    num_bytes = sizeof(int);\n  }\n  *out_ptr = malloc(num_bytes);\n  return (*out_ptr == NULL) ? kTvmErrorPlatformNoMemory : kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  free(ptr);\n  return kTvmErrorNoError;\n}\n\nunsigned long g_utvm_start_time_micros;\nint g_utvm_timer_running = 0;\n\ntvm_crt_error_t TVMPlatformTimerStart() {\n  if (g_utvm_timer_running) {\n    return kTvmErrorPlatformTimerBadState;\n  }\n  g_utvm_timer_running = 1;\n  g_utvm_start_time_micros = micros();\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  if (!g_utvm_timer_running) {\n    return kTvmErrorPlatformTimerBadState;\n  }\n  g_utvm_timer_running = 0;\n  unsigned long g_utvm_stop_time = micros() - g_utvm_start_time_micros;\n  *elapsed_time_seconds = ((double)g_utvm_stop_time) / 1e6;\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMPlatformGenerateRandom(uint8_t* buffer, size_t num_bytes) {\n  for (size_t i = 0; i < num_bytes; i++) {\n    buffer[i] = rand();\n  }\n  return kTvmErrorNoError;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/cmsisnn/convert_image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pathlib\nimport re\nimport sys\nfrom PIL import Image\nimport numpy as np\n\n\ndef create_header_file(name, tensor_name, tensor_data, output_path):\n    \"\"\"\n    This function generates a header file containing the data from the numpy array provided.\n    \"\"\"\n    file_path = pathlib.Path(f\"{output_path}/\" + name).resolve()\n    # Create header file with npy_data as a C array\n    raw_path = file_path.with_suffix(\".h\").resolve()\n    with open(raw_path, \"w\") as header_file:\n        header_file.write(\n            \"\\n\"\n            + f\"const size_t {tensor_name}_len = {tensor_data.size};\\n\"\n            + f'__attribute__((section(\".data.tvm\"), aligned(16))) int8_t {tensor_name}[] = \"'\n        )\n\n        data_hexstr = tensor_data.tobytes().hex()\n        for i in range(0, len(data_hexstr), 2):\n            header_file.write(f\"\\\\x{data_hexstr[i:i+2]}\")\n        header_file.write('\";\\n\\n')\n\n\ndef create_headers(image_name):\n    \"\"\"\n    This function generates C header files for the input and output arrays required to run inferences\n    \"\"\"\n    img_path = os.path.join(\"./\", f\"{image_name}\")\n\n    # Resize image to 224x224\n    resized_image = Image.open(img_path).resize((224, 224))\n    img_data = np.asarray(resized_image).astype(\"float32\")\n\n    # # Add the batch dimension, as we are expecting 4-dimensional input: NCHW.\n    img_data = np.expand_dims(img_data, axis=0)\n\n    # Create input header file\n    input_data = img_data - 128\n    input_data = input_data.astype(np.int8)\n    create_header_file(\"inputs\", \"input\", input_data, \"./include\")\n    # Create output header file\n    output_data = np.zeros([2], np.int8)\n    create_header_file(\n        \"outputs\",\n        \"output\",\n        output_data,\n        \"./include\",\n    )\n\n\nif __name__ == \"__main__\":\n    create_headers(sys.argv[1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/cmsisnn/include/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n#endif  // TVM_RUNTIME_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/cmsisnn/include/tvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/stack_allocator.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t error_code) {\n  printf(\"TVMPlatformAbort: %d\\n\", error_code);\n  printf(\"EXITTHESIM\\n\");\n  exit(-1);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stdout, msg, args);\n  va_end(args);\n}\n\nTVM_DLL int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) { return 0; }\n\n#ifdef __cplusplus\n}\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/cmsisnn/src/demo_bare_metal.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdio.h>\n#include <tvm_runtime.h>\n#include <tvmgen_detection.h>\n\n#include \"uart.h\"\n\n// Header files generated by convert_image.py\n#include \"inputs.h\"\n#include \"outputs.h\"\n\nint main(int argc, char** argv) {\n  uart_init();\n  printf(\"Starting Demo\\n\");\n\n  printf(\"Running detection inference\\n\");\n  struct tvmgen_detection_outputs detection_outputs = {\n      .MobilenetV1_Predictions_Reshape_1 = output,\n  };\n  struct tvmgen_detection_inputs detection_inputs = {\n      .input = input,\n  };\n\n  tvmgen_detection_run(&detection_inputs, &detection_outputs);\n\n  // Report result\n  if (output[1] > output[0]) {\n    printf(\"Person detected.\\n\");\n  } else {\n    printf(\"No person detected.\\n\");\n  }\n\n  // The FVP will shut down when it receives \"EXITTHESIM\" on the UART\n  printf(\"EXITTHESIM\\n\");\n  while (1 == 1)\n    ;\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/convert_image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pathlib\nimport re\nimport sys\nfrom PIL import Image\nimport numpy as np\n\n\ndef create_header_file(name, section, tensor_name, tensor_data, output_path):\n    \"\"\"\n    This function generates a header file containing the data from the numpy array provided.\n    \"\"\"\n    file_path = pathlib.Path(f\"{output_path}/\" + name).resolve()\n    # Create header file with npy_data as a C array\n    raw_path = file_path.with_suffix(\".h\").resolve()\n    with open(raw_path, \"w\") as header_file:\n        header_file.write(\n            \"#include <tvmgen_default.h>\\n\"\n            + f\"const size_t {tensor_name}_len = {tensor_data.size};\\n\"\n            + f'int8_t {tensor_name}[] __attribute__((section(\"{section}\"), aligned(16))) = \"'\n        )\n\n        data_hexstr = tensor_data.tobytes().hex()\n        for i in range(0, len(data_hexstr), 2):\n            header_file.write(f\"\\\\x{data_hexstr[i:i+2]}\")\n        header_file.write('\";\\n\\n')\n\n\ndef create_headers(image_name):\n    \"\"\"\n    This function generates C header files for the input and output arrays required to run inferences\n    \"\"\"\n    img_path = os.path.join(\"./\", f\"{image_name}\")\n\n    # Resize image to 224x224\n    resized_image = Image.open(img_path).resize((224, 224))\n    img_data = np.asarray(resized_image).astype(\"float32\")\n\n    # # Add the batch dimension, as we are expecting 4-dimensional input: NCHW.\n    img_data = np.expand_dims(img_data, axis=0)\n\n    # Create input header file\n    input_data = img_data - 128\n    input_data = input_data.astype(np.int8)\n    create_header_file(\"inputs\", \"ethosu_scratch\", \"input\", input_data, \"./include\")\n    # Create output header file\n    output_data = np.zeros([1001], np.int8)\n    create_header_file(\n        \"outputs\",\n        \"output_data_sec\",\n        \"output\",\n        output_data,\n        \"./include\",\n    )\n\n\nif __name__ == \"__main__\":\n    create_headers(sys.argv[1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/convert_labels.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pathlib\nimport sys\n\n\ndef create_labels_header(labels_file, section, output_path):\n    \"\"\"\n    This function generates a header file containing the ImageNet labels as an array of strings\n    \"\"\"\n    labels_path = pathlib.Path(labels_file).resolve()\n    file_path = pathlib.Path(f\"{output_path}/labels.h\").resolve()\n\n    with open(labels_path) as f:\n        labels = f.readlines()\n\n    with open(file_path, \"w\") as header_file:\n        header_file.write(f'char* labels[] __attribute__((section(\"{section}\"), aligned(16))) = {{')\n\n        for _, label in enumerate(labels):\n            header_file.write(f'\"{label.rstrip()}\",')\n\n        header_file.write(\"};\\n\")\n\n\nif __name__ == \"__main__\":\n    create_labels_header(sys.argv[1], \"ethosu_scratch\", \"./include\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/FreeRTOSConfig.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/* Please refer to http://www.freertos.org/a00110.html for refernce. */\n#ifndef FREERTOS_CONFIG_H\n#define FREERTOS_CONFIG_H\n/******************************************************************************\n * Defines\n **********SYSTEM_CORE_CLOCK********************************************************************/\n/* Hardware features */\n#define configENABLE_MPU 0\n#define configENABLE_FPU 0\n#define configENABLE_TRUSTZONE 0\n/* Scheduling */\n#define configCPU_CLOCK_HZ 25000000\n#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0\n#define configUSE_PREEMPTION 1\n#define configUSE_TIME_SLICING 0\n#define configMAX_PRIORITIES 5\n#define configIDLE_SHOULD_YIELD 1\n#define configUSE_16_BIT_TICKS 0\n#define configRUN_FREERTOS_SECURE_ONLY 1\n/* Stack and heap */\n#define configMINIMAL_STACK_SIZE (uint16_t)128\n#define configMINIMAL_SECURE_STACK_SIZE 1024\n#define configTOTAL_HEAP_SIZE (size_t)(50 * 1024)\n#define configMAX_TASK_NAME_LEN 12\n/* OS features */\n#define configUSE_MUTEXES 1\n#define configUSE_TICKLESS_IDLE 1\n#define configUSE_APPLICATION_TASK_TAG 0\n#define configUSE_NEWLIB_REENTRANT 0\n#define configUSE_CO_ROUTINES 0\n#define configUSE_COUNTING_SEMAPHORES 1\n#define configUSE_RECURSIVE_MUTEXES 1\n#define configUSE_QUEUE_SETS 0\n#define configUSE_TASK_NOTIFICATIONS 1\n#define configUSE_TRACE_FACILITY 1\n/* Hooks */\n#define configUSE_IDLE_HOOK 0\n#define configUSE_TICK_HOOK 0\n#define configUSE_MALLOC_FAILED_HOOK 0\n/* Debug features */\n#define configCHECK_FOR_STACK_OVERFLOW 0\n#define configASSERT(x)       \\\n  if ((x) == 0) {             \\\n    taskDISABLE_INTERRUPTS(); \\\n    for (;;)                  \\\n      ;                       \\\n  }\n#define configQUEUE_REGISTRY_SIZE 0\n/* Timers and queues */\n#define configUSE_TIMERS 1\n#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1)\n#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE\n#define configTIMER_QUEUE_LENGTH 5\n/* Task settings */\n#define INCLUDE_vTaskPrioritySet 1\n#define INCLUDE_uxTaskPriorityGet 1\n#define INCLUDE_vTaskDelete 1\n#define INCLUDE_vTaskCleanUpResources 0\n#define INCLUDE_vTaskSuspend 1\n#define INCLUDE_vTaskDelayUntil 1\n#define INCLUDE_vTaskDelay 1\n#define INCLUDE_uxTaskGetStackHighWaterMark 0\n#define INCLUDE_xTaskGetIdleTaskHandle 0\n#define INCLUDE_eTaskGetState 1\n#define INCLUDE_xTaskResumeFromISR 0\n#define INCLUDE_xTaskGetCurrentTaskHandle 1\n#define INCLUDE_xTaskGetSchedulerState 0\n#define INCLUDE_xSemaphoreGetMutexHolder 0\n#define INCLUDE_xTimerPendFunctionCall 1\n#define configUSE_STATS_FORMATTING_FUNCTIONS 1\n#define configCOMMAND_INT_MAX_OUTPUT_SIZE 2048\n#ifdef __NVIC_PRIO_BITS\n#define configPRIO_BITS __NVIC_PRIO_BITS\n#else\n#define configPRIO_BITS 3\n#endif\n/* Interrupt settings */\n#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x07\n#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5\n#define configKERNEL_INTERRUPT_PRIORITY \\\n  (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS))\n#define configMAX_SYSCALL_INTERRUPT_PRIORITY \\\n  (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS))\n#ifndef __IASMARM__\n#define configGENERATE_RUN_TIME_STATS 0\n#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()\n#define portGET_RUN_TIME_COUNTER_VALUE() 0\n#define configTICK_RATE_HZ (TickType_t)1000\n#endif /* __IASMARM__ */\n#define xPortPendSVHandler PendSV_Handler\n#define vPortSVCHandler SVC_Handler\n#define xPortSysTickHandler SysTick_Handler\n#endif /* FREERTOS_CONFIG_H */\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n#endif  // TVM_RUNTIME_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/ethosu_55.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_55_H_\n#define TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_55_H_\n\n/* Define Arm(R) Ethos(TM)-U55 specific IRQs & base address */\n#define ETHOSU_NPU_FAIL (1 << 4)\n#define ETHOSU_IRQ ((IRQn_Type)56)\n#define ETHOSU_BASE_ADDRESS ((void*)0x48102000)\n\n#endif  // TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_55_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/ethosu_mod.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_MOD_H_\n#define TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_MOD_H_\n\n#include <ARMCM55.h>\n// TODO: Remove device specific information once RTOS support is available\n#include <ethosu_driver.h>\n#include <stdio.h>\n\n#include \"ethosu_55.h\"\n\nstruct ethosu_driver ethosu0_driver;\n\nvoid ethosuIrqHandler0() { ethosu_irq_handler(&ethosu0_driver); }\n\n// Initialize Arm(R) Ethos(TM)-U NPU driver\nint EthosuInit() {\n  if (ethosu_init(&ethosu0_driver, (void*)ETHOSU_BASE_ADDRESS, NULL, 0, 1, 1)) {\n    printf(\"Failed to initialize NPU.\\n\");\n    return -1;\n  }\n\n  // Assumes SCB->VTOR points to RW memory\n  NVIC_SetVector(ETHOSU_IRQ, (uint32_t)&ethosuIrqHandler0);\n  NVIC_EnableIRQ(ETHOSU_IRQ);\n\n  return 0;\n}\n\n#endif  // TVM_APPS_MICROTVM_ETHOS_U_ETHOSU_MOD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/tvm_ethosu_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_ETHOSU_ETHOSU_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_ETHOSU_ETHOSU_RUNTIME_H_\n\n#include <ethosu_driver.h>\n#include <stddef.h>\n#include <stdint.h>\n\ntypedef void tvm_device_ethos_u_t;\n\nint32_t TVMEthosULaunch(tvm_device_ethos_u_t* resource_handle, void* cms_data, size_t cms_data_size,\n                        uint64_t* base_addrs, size_t* base_addrs_size, int num_tensors);\n\nint32_t TVMDeviceEthosUActivate(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUOpen(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUClose(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUDeactivate(tvm_device_ethos_u_t* context);\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOSU_ETHOSU_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/include/tvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/stack_allocator.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t error_code) {\n  printf(\"TVMPlatformAbort: %d\\n\", error_code);\n  printf(\"EXITTHESIM\\n\");\n  exit(-1);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stdout, msg, args);\n  va_end(args);\n}\n\nTVM_DLL int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) { return 0; }\n\n#ifdef __cplusplus\n}\n#endif\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/src/demo_bare_metal.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdio.h>\n#include <tvm_runtime.h>\n\n#include \"ethosu_mod.h\"\n#include \"uart.h\"\n\n// Header files generated by convert_image.py and convert_labels.py\n#include \"inputs.h\"\n#include \"labels.h\"\n#include \"outputs.h\"\n\nint abs(int v) { return v * ((v > 0) - (v < 0)); }\n\nint main(int argc, char** argv) {\n  uart_init();\n  printf(\"Starting Demo\\n\");\n  EthosuInit();\n\n  printf(\"Running inference\\n\");\n  struct tvmgen_default_outputs outputs = {\n      .MobilenetV2_Predictions_Reshape_11 = output,\n  };\n  struct tvmgen_default_inputs inputs = {\n      .tfl_quantize = input,\n  };\n  struct ethosu_driver* driver = ethosu_reserve_driver();\n  struct tvmgen_default_devices devices = {\n      .ethos_u = driver,\n  };\n  tvmgen_default_run(&inputs, &outputs, &devices);\n  ethosu_release_driver(driver);\n\n  // Calculate index of max value\n  int8_t max_value = -128;\n  int32_t max_index = -1;\n  for (unsigned int i = 0; i < output_len; ++i) {\n    if (output[i] > max_value) {\n      max_value = output[i];\n      max_index = i;\n    }\n  }\n  printf(\"The image has been classified as '%s'\\n\", labels[max_index]);\n\n  // The FVP will shut down when it receives \"EXITTHESIM\" on the UART\n  printf(\"EXITTHESIM\\n\");\n  while (1 == 1)\n    ;\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/src/demo_freertos.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <FreeRTOS.h>\n#include <queue.h>\n#include <stdio.h>\n#include <task.h>\n#include <tvm_runtime.h>\n\n#include \"ethosu_mod.h\"\n#include \"uart.h\"\n\n// Header files generated by convert_image.py and convert_labels.py\n#include \"inputs.h\"\n#include \"labels.h\"\n#include \"outputs.h\"\n\nstatic void prvInferenceTask(void* pvParameters);\nstatic void prvDataCollectionTask(void* pvParameters);\n\n#define mainQUEUE_INFERENCE_TASK_PRIORITY (tskIDLE_PRIORITY + 3)\n#define mainQUEUE_INFERENCE_TASK_STACK_SIZE 4096\n#define mainQUEUE_DATA_TASK_PRIORITY (tskIDLE_PRIORITY + 2)\n#define mainQUEUE_DATA_TASK_STACK_SIZE configMINIMAL_STACK_SIZE\n#define mainQUEUE_LENGTH (1)\n#define mainQUEUE_SEND_FREQUENCY_MS (100 / portTICK_PERIOD_MS)\n\n/* The queue used to pass data to run through our model */\nstatic QueueHandle_t xQueue = NULL;\n\nint main(void) {\n  // Platform UART\n  uart_init();\n  // NPU\n  EthosuInit();\n\n  // Queue for inferences\n  xQueue = xQueueCreate(mainQUEUE_LENGTH, sizeof(uint8_t*));\n\n  if (xQueue != NULL) {\n    // Inference task\n    xTaskCreate(prvInferenceTask, \"Inference\", mainQUEUE_INFERENCE_TASK_STACK_SIZE, NULL,\n                mainQUEUE_INFERENCE_TASK_PRIORITY, NULL);\n\n    // Data collector task\n    xTaskCreate(prvDataCollectionTask, \"Data\", mainQUEUE_DATA_TASK_STACK_SIZE, NULL,\n                mainQUEUE_DATA_TASK_PRIORITY, NULL);\n\n    // Start the task scheduling\n    vTaskStartScheduler();\n  }\n\n  // The task scheduler should take over before this is reached\n  printf(\"Unreachable code reached!\\n\");\n}\n\n/*\n * This task emulates collection of data and sending it to another inference task\n * for processing\n */\nstatic void prvDataCollectionTask(void* pvParameters) {\n  // Unused\n  (void)pvParameters;\n\n  // Working\n  vTaskDelay(mainQUEUE_SEND_FREQUENCY_MS);\n\n  // Construct pointer to copy to queue\n  uint8_t** pucInputData = &input;\n  xQueueSend(xQueue, &pucInputData, 0U);\n}\n\n/*\n * This task emulates the inference of data sent by the collector task\n */\nstatic void prvInferenceTask(void* pvParameters) {\n  uint8_t* pucReceivedData;\n\n  // Unused\n  (void)pvParameters;\n\n  // Wait for data collection\n  xQueueReceive(xQueue, &pucReceivedData, portMAX_DELAY);\n\n  // Print output of inference and exit task\n  printf(\"Running inference\\n\");\n  struct tvmgen_default_inputs xInputs = {\n      .tfl_quantize = pucReceivedData,\n  };\n  struct tvmgen_default_outputs xOutputs = {\n      .MobilenetV2_Predictions_Reshape_11 = output,\n  };\n  struct ethosu_driver* xDriver = ethosu_reserve_driver();\n  struct tvmgen_default_devices xDevices = {\n      .ethos_u = xDriver,\n  };\n  tvmgen_default_run(&xInputs, &xOutputs, &xDevices);\n  ethosu_release_driver(xDriver);\n\n  // Calculate index of max value\n  int8_t ucMaxValue = -128;\n  int32_t lMaxIndex = -1;\n  for (unsigned int i = 0; i < output_len; ++i) {\n    if (output[i] > ucMaxValue) {\n      ucMaxValue = output[i];\n      lMaxIndex = i;\n    }\n  }\n  printf(\"The image has been classified as '%s'\\n\", labels[lMaxIndex]);\n\n  // The FVP will shut down when it receives \"EXITTHESIM\" on the UART\n  printf(\"EXITTHESIM\\n\");\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/ethosu/src/tvm_ethosu_runtime.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"tvm_ethosu_runtime.h\"\n\n#include <ethosu_driver.h>\n\nint32_t TVMEthosULaunch(tvm_device_ethos_u_t* context, void* cms_data, size_t cms_data_size,\n                        uint64_t* base_addrs, size_t* base_addrs_size, int num_tensors) {\n  struct ethosu_driver* driver = (struct ethosu_driver*)context;\n  int32_t result =\n      ethosu_invoke(driver, cms_data, cms_data_size, base_addrs, base_addrs_size, num_tensors);\n\n  // Map errors in invoke to TVM errors\n  if (result != 0) {\n    return -1;\n  }\n  return 0;\n}\n\nint32_t TVMDeviceEthosUActivate(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUOpen(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUClose(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUDeactivate(tvm_device_ethos_u_t* context) { return 0; }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/reference-vm/base-box-tool.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport argparse\nimport copy\nimport json\nimport logging\nimport pathlib\nimport os\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport pathlib\n\n_LOG = logging.getLogger(__name__)\n\n\nTHIS_DIR = pathlib.Path(os.path.realpath(os.path.dirname(__file__)))\n\n# List of vagrant providers supported by this tool\nALL_PROVIDERS = (\n    \"parallels\",\n    \"virtualbox\",\n    \"vmware_desktop\",\n)\n\n# List of supported electronics platforms. Each must correspond\n# to a sub-directory of this directory.\nALL_PLATFORMS = (\n    \"arduino\",\n    \"zephyr\",\n)\n\n# Extra scripts required to execute on provisioning\n# in [platform]/base-box/base_box_provision.sh\nEXTRA_SCRIPTS = [\n    \"apps/microtvm/reference-vm/base-box/base_box_setup_common.sh\",\n    \"docker/install/ubuntu_install_core.sh\",\n    \"docker/install/ubuntu_install_python.sh\",\n    \"docker/utils/apt-install-and-clear.sh\",\n    \"docker/install/ubuntu1804_install_llvm.sh\",\n    # Zephyr\n    \"docker/install/ubuntu_init_zephyr_project.sh\",\n    \"docker/install/ubuntu_install_zephyr_sdk.sh\",\n    \"docker/install/ubuntu_install_cmsis.sh\",\n    \"docker/install/ubuntu_install_nrfjprog.sh\",\n]\n\nPACKER_FILE_NAME = \"packer.json\"\n\n\n# List of identifying strings for microTVM boards for testing.\nwith open(THIS_DIR / \"..\" / \"zephyr\" / \"template_project\" / \"boards.json\") as f:\n    zephyr_boards = json.load(f)\n\nwith open(THIS_DIR / \"..\" / \"arduino\" / \"template_project\" / \"boards.json\") as f:\n    arduino_boards = json.load(f)\n\nALL_MICROTVM_BOARDS = {\n    \"arduino\": arduino_boards.keys(),\n    \"zephyr\": zephyr_boards.keys(),\n}\n\n\ndef parse_virtualbox_devices():\n    output = subprocess.check_output([\"VBoxManage\", \"list\", \"usbhost\"], encoding=\"utf-8\")\n    devices = []\n    current_dev = {}\n    for line in output.split(\"\\n\"):\n        if not line.strip():\n            if current_dev:\n                if \"VendorId\" in current_dev and \"ProductId\" in current_dev:\n                    devices.append(current_dev)\n                current_dev = {}\n\n            continue\n\n        key, value = line.split(\":\", 1)\n        value = value.lstrip(\" \")\n        current_dev[key] = value\n\n    if current_dev:\n        devices.append(current_dev)\n    return devices\n\n\nVIRTUALBOX_USB_DEVICE_RE = (\n    \"USBAttachVendorId[0-9]+=0x([0-9a-z]{4})\\n\" + \"USBAttachProductId[0-9]+=0x([0-9a-z]{4})\"\n)\n\n\ndef parse_virtualbox_attached_usb_devices(vm_uuid):\n    output = subprocess.check_output(\n        [\"VBoxManage\", \"showvminfo\", \"--machinereadable\", vm_uuid], encoding=\"utf-8\"\n    )\n\n    r = re.compile(VIRTUALBOX_USB_DEVICE_RE)\n    attached_usb_devices = r.findall(output, re.MULTILINE)\n\n    # List of couples (VendorId, ProductId) for all attached USB devices\n    return attached_usb_devices\n\n\nVIRTUALBOX_VID_PID_RE = re.compile(r\"0x([0-9A-Fa-f]{4}).*\")\n\n\ndef attach_virtualbox(vm_uuid, vid_hex=None, pid_hex=None, serial=None):\n    usb_devices = parse_virtualbox_devices()\n    for dev in usb_devices:\n        m = VIRTUALBOX_VID_PID_RE.match(dev[\"VendorId\"])\n        if not m:\n            _LOG.warning(\"Malformed VendorId: %s\", dev[\"VendorId\"])\n            continue\n\n        dev_vid_hex = m.group(1).lower()\n\n        m = VIRTUALBOX_VID_PID_RE.match(dev[\"ProductId\"])\n        if not m:\n            _LOG.warning(\"Malformed ProductId: %s\", dev[\"ProductId\"])\n            continue\n\n        dev_pid_hex = m.group(1).lower()\n\n        if (\n            vid_hex == dev_vid_hex\n            and pid_hex == dev_pid_hex\n            and (serial is None or serial == dev[\"SerialNumber\"])\n        ):\n            attached_devices = parse_virtualbox_attached_usb_devices(vm_uuid)\n            for vid, pid in parse_virtualbox_attached_usb_devices(vm_uuid):\n                if vid_hex == vid and pid_hex == pid:\n                    print(f\"USB dev {vid_hex}:{pid_hex} already attached. Skipping attach.\")\n                    return\n\n            rule_args = [\n                \"VBoxManage\",\n                \"usbfilter\",\n                \"add\",\n                \"0\",\n                \"--action\",\n                \"hold\",\n                \"--name\",\n                \"test device\",\n                \"--target\",\n                vm_uuid,\n                \"--vendorid\",\n                vid_hex,\n                \"--productid\",\n                pid_hex,\n            ]\n            if serial is not None:\n                rule_args.extend([\"--serialnumber\", serial])\n            subprocess.check_call(rule_args)\n            subprocess.check_call([\"VBoxManage\", \"controlvm\", vm_uuid, \"usbattach\", dev[\"UUID\"]])\n            return\n\n    raise Exception(\n        f\"Device with vid={vid_hex}, pid={pid_hex}, serial={serial!r} not found:\\n{usb_devices!r}\"\n    )\n\n\ndef attach_parallels(uuid, vid_hex=None, pid_hex=None, serial=None):\n    usb_devices = json.loads(\n        subprocess.check_output([\"prlsrvctl\", \"usb\", \"list\", \"-j\"], encoding=\"utf-8\")\n    )\n    for dev in usb_devices:\n        _, dev_vid_hex, dev_pid_hex, _, _, dev_serial = dev[\"System name\"].split(\"|\")\n        dev_vid_hex = dev_vid_hex.lower()\n        dev_pid_hex = dev_pid_hex.lower()\n        if (\n            vid_hex == dev_vid_hex\n            and pid_hex == dev_pid_hex\n            and (serial is None or serial == dev_serial)\n        ):\n            subprocess.check_call([\"prlsrvctl\", \"usb\", \"set\", dev[\"Name\"], uuid])\n            if \"Used-By-Vm-Name\" in dev:\n                subprocess.check_call(\n                    [\"prlctl\", \"set\", dev[\"Used-By-Vm-Name\"], \"--device-disconnect\", dev[\"Name\"]]\n                )\n            subprocess.check_call([\"prlctl\", \"set\", uuid, \"--device-connect\", dev[\"Name\"]])\n            return\n\n    raise Exception(\n        f\"Device with vid={vid_hex}, pid={pid_hex}, serial={serial!r} not found:\\n{usb_devices!r}\"\n    )\n\n\ndef attach_vmware(uuid, vid_hex=None, pid_hex=None, serial=None):\n    print(\"NOTE: vmware doesn't seem to support automatic attaching of devices :(\")\n    print(\"The VMWare VM UUID is {uuid}\")\n    print(\"Please attach the following usb device using the VMWare GUI:\")\n    if vid_hex is not None:\n        print(f\" - VID: {vid_hex}\")\n    if pid_hex is not None:\n        print(f\" - PID: {pid_hex}\")\n    if serial is not None:\n        print(f\" - Serial: {serial}\")\n    if vid_hex is None and pid_hex is None and serial is None:\n        print(\" - (no specifications given for USB device)\")\n    print()\n    print(\"Press [Enter] when the USB device is attached\")\n    input()\n\n\nATTACH_USB_DEVICE = {\n    \"parallels\": attach_parallels,\n    \"virtualbox\": attach_virtualbox,\n    \"vmware_desktop\": attach_vmware,\n}\n\n\ndef generate_packer_config(file_path, providers):\n    builders = []\n    provisioners = []\n    for provider_name in providers:\n        builders.append(\n            {\n                \"name\": f\"{provider_name}\",\n                \"type\": \"vagrant\",\n                \"box_name\": f\"microtvm-base-{provider_name}\",\n                \"output_dir\": f\"output-packer-{provider_name}\",\n                \"communicator\": \"ssh\",\n                \"source_path\": \"generic/ubuntu1804\",\n                \"provider\": provider_name,\n                \"template\": \"Vagrantfile.packer-template\",\n            }\n        )\n\n    repo_root = subprocess.check_output(\n        [\"git\", \"rev-parse\", \"--show-toplevel\"], encoding=\"utf-8\"\n    ).strip()\n\n    scripts_to_copy = EXTRA_SCRIPTS\n    for script in scripts_to_copy:\n        script_path = os.path.join(repo_root, script)\n        filename = os.path.basename(script_path)\n        provisioners.append({\"type\": \"file\", \"source\": script_path, \"destination\": f\"~/{filename}\"})\n\n    provisioners.append(\n        {\n            \"type\": \"shell\",\n            \"script\": \"base_box_setup.sh\",\n        }\n    )\n    provisioners.append(\n        {\n            \"type\": \"shell\",\n            \"script\": \"base_box_provision.sh\",\n        }\n    )\n\n    with open(file_path, \"w\") as f:\n        json.dump(\n            {\n                \"builders\": builders,\n                \"provisioners\": provisioners,\n            },\n            f,\n            sort_keys=True,\n            indent=2,\n        )\n\n\ndef build_command(args):\n    base_box_dir = THIS_DIR / \"base-box\"\n\n    generate_packer_config(\n        os.path.join(base_box_dir, PACKER_FILE_NAME),\n        args.provider or ALL_PROVIDERS,\n    )\n    env = copy.copy(os.environ)\n    packer_args = [\"packer\", \"build\", \"-force\"]\n    env[\"PACKER_LOG\"] = \"1\"\n    env[\"PACKER_LOG_PATH\"] = \"packer.log\"\n    if args.debug_packer:\n        packer_args += [\"-debug\"]\n\n    packer_args += [PACKER_FILE_NAME]\n\n    box_package_exists = False\n    if not args.force:\n        box_package_dirs = [(base_box_dir / f\"output-packer-{p}\") for p in args.provider]\n        for box_package_dir in box_package_dirs:\n            if box_package_dir.exists():\n                print(f\"A box package {box_package_dir} already exists. Refusing to overwrite it!\")\n                box_package_exists = True\n\n    if box_package_exists:\n        sys.exit(\"One or more box packages exist (see list above). To rebuild use '--force'\")\n\n    subprocess.check_call(packer_args, cwd=THIS_DIR / \"base-box\", env=env)\n\n\nREQUIRED_TEST_CONFIG_KEYS = {\n    \"vid_hex\": str,\n    \"pid_hex\": str,\n}\n\n\nVM_BOX_RE = re.compile(r'(.*\\.vm\\.box) = \"(.*)\"')\nVM_TVM_HOME_RE = re.compile(r'(.*tvm_home) = \"(.*)\"')\n\n# Paths, relative to the platform box directory, which will not be copied to release-test dir.\nSKIP_COPY_PATHS = [\".vagrant\", \"base-box\", \"scripts\"]\n\n\ndef do_build_release_test_vm(\n    release_test_dir, user_box_dir: pathlib.Path, base_box_dir: pathlib.Path, provider_name\n):\n    if os.path.exists(release_test_dir):\n        try:\n            subprocess.check_call([\"vagrant\", \"destroy\", \"-f\"], cwd=release_test_dir)\n        except subprocess.CalledProcessError:\n            _LOG.warning(\"vagrant destroy failed--removing dirtree anyhow\", exc_info=True)\n\n        shutil.rmtree(release_test_dir)\n\n    for dirpath, _, filenames in os.walk(user_box_dir):\n        rel_path = os.path.relpath(dirpath, user_box_dir)\n        if any(\n            rel_path == scp or rel_path.startswith(f\"{scp}{os.path.sep}\") for scp in SKIP_COPY_PATHS\n        ):\n            continue\n\n        dest_dir = os.path.join(release_test_dir, rel_path)\n        os.makedirs(dest_dir)\n        for filename in filenames:\n            shutil.copy2(os.path.join(dirpath, filename), os.path.join(dest_dir, filename))\n\n    release_test_vagrantfile = os.path.join(release_test_dir, \"Vagrantfile\")\n    with open(release_test_vagrantfile) as f:\n        lines = list(f)\n\n    found_box_line = False\n    with open(release_test_vagrantfile, \"w\") as f:\n        for line in lines:\n            # Skip setting version\n            if \"config.vm.box_version\" in line:\n                continue\n            m = VM_BOX_RE.match(line)\n            tvm_home_m = VM_TVM_HOME_RE.match(line)\n\n            if tvm_home_m:\n                # Adjust tvm home for testing step\n                f.write(f'{tvm_home_m.group(1)} = \"../../../..\"\\n')\n                continue\n            if not m:\n                f.write(line)\n                continue\n\n            box_package = os.path.join(\n                base_box_dir, f\"output-packer-{provider_name}\", \"package.box\"\n            )\n            box_relpath = os.path.relpath(box_package, release_test_dir)\n            f.write(f'{m.group(1)} = \"{box_relpath}\"\\n')\n            found_box_line = True\n\n    if not found_box_line:\n        _LOG.error(\n            \"testing provider %s: couldn't find config.box.vm = line in Vagrantfile; unable to test\",\n            provider_name,\n        )\n        return False\n\n    # Delete the old box registered with Vagrant, which may lead to a falsely-passing release test.\n    remove_args = [\"vagrant\", \"box\", \"remove\", box_relpath]\n    return_code = subprocess.call(remove_args, cwd=release_test_dir)\n    assert return_code in (0, 1), f'{\" \".join(remove_args)} returned exit code {return_code}'\n    subprocess.check_call([\"vagrant\", \"up\", f\"--provider={provider_name}\"], cwd=release_test_dir)\n    return True\n\n\ndef do_run_release_test(release_test_dir, provider_name, test_config, test_device_serial):\n    with open(\n        os.path.join(release_test_dir, \".vagrant\", \"machines\", \"default\", provider_name, \"id\")\n    ) as f:\n        machine_uuid = f.read()\n\n    # Check if target is not QEMU\n    if test_config[\"vid_hex\"] and test_config[\"pid_hex\"]:\n        ATTACH_USB_DEVICE[provider_name](\n            machine_uuid,\n            vid_hex=test_config[\"vid_hex\"],\n            pid_hex=test_config[\"pid_hex\"],\n            serial=test_device_serial,\n        )\n    tvm_home = os.path.realpath(THIS_DIR / \"..\" / \"..\" / \"..\")\n\n    def _quote_cmd(cmd):\n        return \" \".join(shlex.quote(a) for a in cmd)\n\n    test_cmd = (\n        _quote_cmd([\"cd\", tvm_home])\n        + \" && \"\n        + _quote_cmd(\n            [\n                f\"apps/microtvm/reference-vm/base-box/base_box_test.sh\",\n                test_config[\"microtvm_board\"],\n            ]\n        )\n    )\n    subprocess.check_call([\"vagrant\", \"ssh\", \"-c\", f\"bash -ec '{test_cmd}'\"], cwd=release_test_dir)\n\n\ndef test_command(args):\n    user_box_dir = THIS_DIR\n    base_box_dir = user_box_dir / \"base-box\"\n    boards_file = THIS_DIR / \"..\" / args.platform / \"template_project\" / \"boards.json\"\n    with open(boards_file) as f:\n        test_config = json.load(f)\n\n        # select microTVM test config\n        microtvm_test_config = test_config[args.microtvm_board]\n\n        for key, expected_type in REQUIRED_TEST_CONFIG_KEYS.items():\n            assert key in microtvm_test_config and isinstance(\n                microtvm_test_config[key], expected_type\n            ), f\"Expected key {key} of type {expected_type} in {boards_file}: {test_config!r}\"\n\n        microtvm_test_config[\"vid_hex\"] = microtvm_test_config[\"vid_hex\"].lower()\n        microtvm_test_config[\"pid_hex\"] = microtvm_test_config[\"pid_hex\"].lower()\n        microtvm_test_config[\"microtvm_board\"] = args.microtvm_board\n\n    providers = args.provider\n\n    release_test_dir = THIS_DIR / f\"release-test\"\n\n    if args.skip_build or args.skip_destroy:\n        assert (\n            len(providers) == 1\n        ), \"--skip-build and/or --skip-destroy was given, but >1 provider specified\"\n\n    test_failed = False\n    for provider_name in providers:\n        try:\n            if not args.skip_build:\n                do_build_release_test_vm(\n                    release_test_dir, user_box_dir, base_box_dir, provider_name\n                )\n            do_run_release_test(\n                release_test_dir,\n                provider_name,\n                microtvm_test_config,\n                args.test_device_serial,\n            )\n\n        except subprocess.CalledProcessError:\n            test_failed = True\n            sys.exit(\n                f\"\\n\\nERROR: Provider '{provider_name}' failed the release test. \"\n                \"You can re-run it to reproduce the issue without building everything \"\n                \"again by passing the --skip-build and specifying only the provider that failed. \"\n                \"The VM is still running in case you want to connect it via SSH to \"\n                \"investigate further the issue, thus it's necessary to destroy it manually \"\n                \"to release the resources back to the host, like a USB device attached to the VM.\"\n            )\n\n        finally:\n            # if we reached out here do_run_release_test() succeeded, hence we can\n            # destroy the VM and release the resources back to the host if user haven't\n            # requested to not destroy it.\n            if not (args.skip_destroy or test_failed):\n                subprocess.check_call([\"vagrant\", \"destroy\", \"-f\"], cwd=release_test_dir)\n                shutil.rmtree(release_test_dir)\n\n    print(f'\\n\\nThe release tests passed on all specified providers: {\", \".join(providers)}.')\n\n\ndef release_command(args):\n    if args.release_full_name:\n        vm_name = args.release_full_name\n    else:\n        vm_name = \"tlcpack/microtvm\"\n\n    if not args.skip_creating_release_version:\n        subprocess.check_call(\n            [\n                \"vagrant\",\n                \"cloud\",\n                \"version\",\n                \"create\",\n                vm_name,\n                args.release_version,\n            ]\n        )\n    if not args.release_version:\n        sys.exit(f\"--release-version must be specified\")\n\n    for provider_name in args.provider:\n        subprocess.check_call(\n            [\n                \"vagrant\",\n                \"cloud\",\n                \"publish\",\n                \"-f\",\n                vm_name,\n                args.release_version,\n                provider_name,\n                str(THIS_DIR / \"base-box\" / f\"output-packer-{provider_name}/package.box\"),\n            ]\n        )\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        description=\"Automates building, testing, and releasing a base box\"\n    )\n    subparsers = parser.add_subparsers(help=\"Action to perform.\")\n    subparsers.required = True\n    subparsers.dest = \"action\"\n    parser.add_argument(\n        \"--provider\",\n        choices=ALL_PROVIDERS,\n        action=\"append\",\n        required=True,\n        help=\"Name of the provider or providers to act on\",\n    )\n\n    # \"test\" has special options for different platforms, and \"build\", \"release\" might\n    # in the future, so we'll add the platform argument to each one individually.\n    platform_help_str = \"Platform to use (e.g. Arduino, Zephyr)\"\n\n    # Options for build subcommand\n    parser_build = subparsers.add_parser(\"build\", help=\"Build a base box.\")\n    parser_build.set_defaults(func=build_command)\n    parser_build.add_argument(\n        \"--debug-packer\",\n        action=\"store_true\",\n        help=(\"Run packer in debug mode, and write log to the base-box directory.\"),\n    )\n    parser_build.add_argument(\n        \"--force\",\n        action=\"store_true\",\n        help=(\"Force rebuilding a base box from scratch if one already exists.\"),\n    )\n\n    # Options for test subcommand\n    parser_test = subparsers.add_parser(\"test\", help=\"Test a base box before release.\")\n    parser_test.set_defaults(func=test_command)\n    parser_test.add_argument(\n        \"--skip-build\",\n        action=\"store_true\",\n        help=(\n            \"If given, assume a box has already been built in the release-test subdirectory, \"\n            \"so use that box to execute the release test script. If the tests fail the VM used \"\n            \"for testing will be left running for further investigation and will need to be \"\n            \"destroyed manually. If all tests pass on all specified providers no VM is left running, \"\n            \"unless --skip-destroy is given too.\"\n        ),\n    )\n    parser_test.add_argument(\n        \"--skip-destroy\",\n        action=\"store_true\",\n        help=(\n            \"Skip destroying the test VM even if all tests pass. Can only be used if a single \"\n            \"provider is specified. Default is to destroy the VM if all tests pass (and always \"\n            \"skip destroying it if a test fails).\"\n        ),\n    )\n    parser_test.add_argument(\n        \"--test-device-serial\",\n        help=(\n            \"If given, attach the test device with this USB serial number. Corresponds to the \"\n            \"iSerial field from `lsusb -v` output.\"\n        ),\n    )\n    parser_test_platform_subparsers = parser_test.add_subparsers(help=platform_help_str)\n    for platform in ALL_PLATFORMS:\n        platform_specific_parser = parser_test_platform_subparsers.add_parser(platform)\n        platform_specific_parser.set_defaults(platform=platform)\n        platform_specific_parser.add_argument(\n            \"--microtvm-board\",\n            choices=ALL_MICROTVM_BOARDS[platform],\n            required=True,\n            help=\"MicroTVM board used for testing.\",\n        )\n\n    # Options for release subcommand\n    parser_release = subparsers.add_parser(\"release\", help=\"Release base box to cloud.\")\n    parser_release.set_defaults(func=release_command)\n    parser_release.add_argument(\n        \"--release-version\",\n        required=True,\n        help=\"Version to release, in the form 'x.y.z'. Must be specified with release.\",\n    )\n    parser_release.add_argument(\n        \"--skip-creating-release-version\",\n        action=\"store_true\",\n        help=\"Skip creating the version and just upload for this provider.\",\n    )\n    parser_release.add_argument(\n        \"--release-full-name\",\n        required=False,\n        type=str,\n        default=None,\n        help=(\n            \"If set, it will use this as the full release name and version for the box. \"\n            \"If this set, it will ignore `--release-version`.\"\n        ),\n    )\n\n    args = parser.parse_args()\n    return args\n\n\ndef main():\n    args = parse_args()\n    args.func(args)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/crt_config/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt_config.h.template\n * \\brief Template for CRT configuration, to be modified on each target.\n */\n#ifndef TVM_RUNTIME_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONFIG_H_\n\n#include <tvm/runtime/crt/logging.h>\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 8192\n\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\" */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! \\brief Maximum length of a PackedFunc function name. */\n#define TVM_CRT_MAX_FUNCTION_NAME_LENGTH_BYTES 30\n\n/*! \\brief Log2 of the page size (bytes) for a virtual memory page. */\n#define TVM_CRT_PAGE_BITS 10  // 1 kB\n\n/*! \\brief Number of pages on device. */\n#define TVM_CRT_MAX_PAGES 300\n\n// #define TVM_CRT_FRAMER_ENABLE_LOGS\n\n#endif  // TVM_RUNTIME_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/microtvm_api_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport atexit\nimport collections\nimport collections.abc\nimport enum\nimport fcntl\nimport json\nimport logging\nimport os\nimport os.path\nimport pathlib\nimport queue\nimport re\nimport shlex\nimport shutil\nimport struct\nimport subprocess\nimport sys\nimport tarfile\nimport tempfile\nimport threading\nfrom typing import Union\nimport usb\nimport psutil\nimport stat\n\nimport serial\nimport serial.tools.list_ports\nimport yaml\n\nfrom tvm.micro.project_api import server\n\n\n_LOG = logging.getLogger(__name__)\n\n\nAPI_SERVER_DIR = pathlib.Path(os.path.dirname(__file__) or os.path.getcwd())\n\n\nBUILD_DIR = API_SERVER_DIR / \"build\"\n\n\nMODEL_LIBRARY_FORMAT_RELPATH = \"model.tar\"\n\n\nIS_TEMPLATE = not (API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH).exists()\n\n\nBOARDS = API_SERVER_DIR / \"boards.json\"\n\nCMAKELIST_FILENAME = \"CMakeLists.txt\"\n\n# Used to check Zephyr version installed on the host.\n# We only check two levels of the version.\nZEPHYR_VERSION = 2.7\n\nWEST_CMD = default = sys.executable + \" -m west\" if sys.executable else None\n\nZEPHYR_BASE = os.getenv(\"ZEPHYR_BASE\")\n\n# Data structure to hold the information microtvm_api_server.py needs\n# to communicate with each of these boards.\ntry:\n    with open(BOARDS) as boards:\n        BOARD_PROPERTIES = json.load(boards)\nexcept FileNotFoundError:\n    raise FileNotFoundError(f\"Board file {{{BOARDS}}} does not exist.\")\n\n\ndef check_call(cmd_args, *args, **kwargs):\n    cwd_str = \"\" if \"cwd\" not in kwargs else f\" (in cwd: {kwargs['cwd']})\"\n    _LOG.info(\"run%s: %s\", cwd_str, \" \".join(shlex.quote(a) for a in cmd_args))\n    return subprocess.check_call(cmd_args, *args, **kwargs)\n\n\nCACHE_ENTRY_RE = re.compile(r\"(?P<name>[^:]+):(?P<type>[^=]+)=(?P<value>.*)\")\n\n\nCMAKE_BOOL_MAP = dict(\n    [(k, True) for k in (\"1\", \"ON\", \"YES\", \"TRUE\", \"Y\")]\n    + [(k, False) for k in (\"0\", \"OFF\", \"NO\", \"FALSE\", \"N\", \"IGNORE\", \"NOTFOUND\", \"\")]\n)\n\n\nclass CMakeCache(collections.abc.Mapping):\n    def __init__(self, path):\n        self._path = path\n        self._dict = None\n\n    def __iter__(self):\n        return iter(self._dict)\n\n    def __getitem__(self, key):\n        if self._dict is None:\n            self._dict = self._read_cmake_cache()\n\n        return self._dict[key]\n\n    def __len__(self):\n        return len(self._dict)\n\n    def _read_cmake_cache(self):\n        \"\"\"Read a CMakeCache.txt-like file and return a dictionary of values.\"\"\"\n        entries = collections.OrderedDict()\n        with open(self._path, encoding=\"utf-8\") as f:\n            for line in f:\n                m = CACHE_ENTRY_RE.match(line.rstrip(\"\\n\"))\n                if not m:\n                    continue\n\n                if m.group(\"type\") == \"BOOL\":\n                    value = CMAKE_BOOL_MAP[m.group(\"value\").upper()]\n                else:\n                    value = m.group(\"value\")\n\n                entries[m.group(\"name\")] = value\n\n        return entries\n\n\nCMAKE_CACHE = CMakeCache(BUILD_DIR / \"CMakeCache.txt\")\n\n\nclass BoardError(Exception):\n    \"\"\"Raised when an attached board cannot be opened (i.e. missing /dev nodes, etc).\"\"\"\n\n\nclass BoardAutodetectFailed(Exception):\n    \"\"\"Raised when no attached hardware is found matching the board= given to ZephyrCompiler.\"\"\"\n\n\ndef _get_flash_runner():\n    flash_runner = CMAKE_CACHE.get(\"ZEPHYR_BOARD_FLASH_RUNNER\")\n    if flash_runner is not None:\n        return flash_runner\n\n    with open(CMAKE_CACHE[\"ZEPHYR_RUNNERS_YAML\"]) as f:\n        doc = yaml.load(f, Loader=yaml.FullLoader)\n    return doc[\"flash-runner\"]\n\n\ndef _find_board_from_cmake_file(cmake_file: Union[str, pathlib.Path]) -> str:\n    \"\"\"Find Zephyr board from generated CMakeLists.txt\"\"\"\n    zephyr_board = None\n    with open(cmake_file) as cmake_f:\n        for line in cmake_f:\n            if line.startswith(\"set(BOARD\"):\n                zephyr_board = line.strip(\"\\n\").strip(\"\\r\").strip(\")\").split(\" \")[1]\n                break\n\n    if not zephyr_board:\n        raise RuntimeError(f\"No Zephyr board set in the {cmake_file}.\")\n    return zephyr_board\n\n\ndef _find_platform_from_cmake_file(cmake_file: Union[str, pathlib.Path]) -> str:\n    emu_platform = None\n    with open(API_SERVER_DIR / CMAKELIST_FILENAME) as cmake_f:\n        for line in cmake_f:\n            set_platform = re.match(\"set\\(EMU_PLATFORM (.*)\\)\", line)\n            if set_platform:\n                emu_platform = set_platform.group(1)\n                break\n    return emu_platform\n\n\ndef _get_device_args(options):\n    flash_runner = _get_flash_runner()\n\n    if flash_runner == \"nrfjprog\":\n        return _get_nrf_device_args(options)\n\n    if flash_runner == \"openocd\":\n        return _get_openocd_device_args(options)\n\n    raise BoardError(\n        f\"Don't know how to find serial terminal for board {_find_board_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)} with flash \"\n        f\"runner {flash_runner}\"\n    )\n\n\ndef _get_board_mem_size_bytes(options):\n    board_file_path = (\n        pathlib.Path(get_zephyr_base(options))\n        / \"boards\"\n        / \"arm\"\n        / options[\"board\"]\n        / (options[\"board\"] + \".yaml\")\n    )\n    try:\n        with open(board_file_path) as f:\n            board_data = yaml.load(f, Loader=yaml.FullLoader)\n            return int(board_data[\"ram\"]) * 1024\n    except:\n        _LOG.warning(\"Board memory information is not available.\")\n    return None\n\n\nDEFAULT_HEAP_SIZE_BYTES = 216 * 1024\n\n\ndef _get_recommended_heap_size_bytes(options):\n    prop = BOARD_PROPERTIES[options[\"board\"]]\n    if \"recommended_heap_size_bytes\" in prop:\n        return prop[\"recommended_heap_size_bytes\"]\n    return DEFAULT_HEAP_SIZE_BYTES\n\n\ndef generic_find_serial_port(serial_number=None):\n    \"\"\"Find a USB serial port based on its serial number or its VID:PID.\n\n    This method finds a USB serial port device path based on the port's serial number (if given) or\n    based on the board's idVendor and idProduct ids.\n\n    Parameters\n    ----------\n    serial_number : str\n        The serial number associated to the USB serial port which the board is attached to. This is\n        the same number as shown by 'lsusb -v' in the iSerial field.\n\n    Returns\n    -------\n    Path to the USB serial port device, for example /dev/ttyACM1.\n    \"\"\"\n    if serial_number:\n        regex = serial_number\n    else:\n        prop = BOARD_PROPERTIES[_find_board_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)]\n        device_id = \":\".join([prop[\"vid_hex\"], prop[\"pid_hex\"]])\n        regex = device_id\n\n    serial_ports = list(serial.tools.list_ports.grep(regex))\n\n    if len(serial_ports) == 0:\n        raise Exception(f\"No serial port found for board {prop['board']}!\")\n\n    if len(serial_ports) != 1:\n        ports_lst = \"\"\n        for port in serial_ports:\n            ports_lst += f\"Serial port: {port.device}, serial number: {port.serial_number}\\n\"\n\n        raise Exception(\"Expected 1 serial port, found multiple ports:\\n {ports_lst}\")\n\n    return serial_ports[0].device\n\n\ndef _get_openocd_device_args(options):\n    serial_number = options.get(\"openocd_serial\")\n    return [\"--serial\", generic_find_serial_port(serial_number)]\n\n\ndef _get_nrf_device_args(options):\n    nrfjprog_args = [\"nrfjprog\", \"--ids\"]\n    nrfjprog_ids = subprocess.check_output(nrfjprog_args, encoding=\"utf-8\")\n    if not nrfjprog_ids.strip(\"\\n\"):\n        raise BoardAutodetectFailed(f'No attached boards recognized by {\" \".join(nrfjprog_args)}')\n\n    boards = nrfjprog_ids.split(\"\\n\")[:-1]\n    if len(boards) > 1:\n        if options[\"nrfjprog_snr\"] is None:\n            raise BoardError(\n                \"Multiple boards connected; specify one with nrfjprog_snr=: \" f'{\", \".join(boards)}'\n            )\n\n        if str(options[\"nrfjprog_snr\"]) not in boards:\n            raise BoardError(\n                f\"nrfjprog_snr ({options['nrfjprog_snr']}) not found in {nrfjprog_args}: {boards}\"\n            )\n\n        return [\"--snr\", options[\"nrfjprog_snr\"]]\n\n    if not boards:\n        return []\n\n    return [\"--snr\", boards[0]]\n\n\nPROJECT_TYPES = []\nif IS_TEMPLATE:\n    for d in (API_SERVER_DIR / \"src\").iterdir():\n        if d.is_dir():\n            PROJECT_TYPES.append(d.name)\n\nPROJECT_OPTIONS = server.default_project_options(\n    project_type={\"choices\": tuple(PROJECT_TYPES)},\n    board={\"choices\": list(BOARD_PROPERTIES)},\n    verbose={\"optional\": [\"generate_project\"]},\n) + [\n    server.ProjectOption(\n        \"gdbserver_port\",\n        optional=[\"open_transport\"],\n        type=\"int\",\n        default=None,\n        help=(\"If given, port number to use when running the local gdbserver.\"),\n    ),\n    server.ProjectOption(\n        \"nrfjprog_snr\",\n        optional=[\"open_transport\"],\n        type=\"int\",\n        default=None,\n        help=(\"When used with nRF targets, serial # of the attached board to use, from nrfjprog.\"),\n    ),\n    server.ProjectOption(\n        \"openocd_serial\",\n        optional=[\"open_transport\"],\n        type=\"int\",\n        default=None,\n        help=(\"When used with OpenOCD targets, serial # of the attached board to use.\"),\n    ),\n    server.ProjectOption(\n        \"west_cmd\",\n        optional=[\"generate_project\"],\n        type=\"str\",\n        default=WEST_CMD,\n        help=(\n            \"Path to the west tool. If given, supersedes both the zephyr_base \"\n            \"option and ZEPHYR_BASE environment variable.\"\n        ),\n    ),\n    server.ProjectOption(\n        \"zephyr_base\",\n        required=([\"generate_project\", \"open_transport\"] if not ZEPHYR_BASE else None),\n        optional=([\"generate_project\", \"open_transport\"] if ZEPHYR_BASE else [\"build\"]),\n        type=\"str\",\n        default=ZEPHYR_BASE,\n        help=\"Path to the zephyr base directory.\",\n    ),\n    server.ProjectOption(\n        \"config_main_stack_size\",\n        optional=[\"generate_project\"],\n        type=\"int\",\n        default=None,\n        help=\"Sets CONFIG_MAIN_STACK_SIZE for Zephyr board.\",\n    ),\n    server.ProjectOption(\n        \"arm_fvp_path\",\n        optional=[\"generate_project\", \"open_transport\"],\n        type=\"str\",\n        default=None,\n        help=\"Path to the FVP binary to invoke.\",\n    ),\n    server.ProjectOption(\n        \"use_fvp\",\n        optional=[\"generate_project\"],\n        type=\"bool\",\n        default=False,\n        help=\"Run on the FVP emulator instead of hardware.\",\n    ),\n    server.ProjectOption(\n        \"heap_size_bytes\",\n        optional=[\"generate_project\"],\n        type=\"int\",\n        default=None,\n        help=\"Sets the value for HEAP_SIZE_BYTES passed to K_HEAP_DEFINE() to service TVM memory allocation requests.\",\n    ),\n]\n\n\ndef get_zephyr_base(options: dict):\n    \"\"\"Returns Zephyr base path\"\"\"\n    zephyr_base = options.get(\"zephyr_base\", ZEPHYR_BASE)\n    assert zephyr_base, \"'zephyr_base' option not passed and not found by default!\"\n    return zephyr_base\n\n\ndef get_cmsis_path(options: dict) -> pathlib.Path:\n    \"\"\"Returns CMSIS dependency path\"\"\"\n    cmsis_path = options.get(\"cmsis_path\")\n    assert cmsis_path, \"'cmsis_path' option not passed!\"\n    return pathlib.Path(cmsis_path)\n\n\nclass Handler(server.ProjectAPIHandler):\n    def __init__(self):\n        super(Handler, self).__init__()\n        self._proc = None\n\n    def server_info_query(self, tvm_version):\n        return server.ServerInfo(\n            platform_name=\"zephyr\",\n            is_template=IS_TEMPLATE,\n            model_library_format_path=\"\"\n            if IS_TEMPLATE\n            else (API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH),\n            project_options=PROJECT_OPTIONS,\n        )\n\n    # These files and directories will be recursively copied into generated projects from the CRT.\n    CRT_COPY_ITEMS = (\"include\", \"Makefile\", \"src\")\n\n    # Maps extra line added to prj.conf to a tuple or list of zephyr_board for which it is needed.\n    EXTRA_PRJ_CONF_DIRECTIVES = {\n        \"CONFIG_TIMER_RANDOM_GENERATOR=y\": (\n            \"qemu_x86\",\n            \"qemu_riscv32\",\n            \"qemu_cortex_r5\",\n            \"qemu_riscv64\",\n        ),\n        \"CONFIG_ENTROPY_GENERATOR=y\": (\n            \"mps2_an521\",\n            \"nrf5340dk_nrf5340_cpuapp\",\n            \"nucleo_f746zg\",\n            \"nucleo_l4r5zi\",\n            \"stm32f746g_disco\",\n        ),\n    }\n\n    def _create_prj_conf(self, project_dir, options):\n        zephyr_board = options[\"board\"]\n        with open(project_dir / \"prj.conf\", \"w\") as f:\n            f.write(\n                \"# For UART used from main().\\n\"\n                \"CONFIG_RING_BUFFER=y\\n\"\n                \"CONFIG_UART_CONSOLE=n\\n\"\n                \"CONFIG_UART_INTERRUPT_DRIVEN=y\\n\"\n                \"\\n\"\n            )\n            f.write(\"# For TVMPlatformAbort().\\n\" \"CONFIG_REBOOT=y\\n\" \"\\n\")\n\n            if options[\"project_type\"] == \"host_driven\":\n                f.write(\n                    \"CONFIG_TIMING_FUNCTIONS=y\\n\"\n                    \"# For RPC server C++ bindings.\\n\"\n                    \"CONFIG_CPLUSPLUS=y\\n\"\n                    \"CONFIG_LIB_CPLUSPLUS=y\\n\"\n                    \"\\n\"\n                )\n\n            f.write(\"# For math routines\\n\" \"CONFIG_NEWLIB_LIBC=y\\n\" \"\\n\")\n\n            if self._has_fpu(zephyr_board):\n                f.write(\"# For models with floating point.\\n\" \"CONFIG_FPU=y\\n\" \"\\n\")\n\n            # Set main stack size, if needed.\n            if options.get(\"config_main_stack_size\") is not None:\n                f.write(f\"CONFIG_MAIN_STACK_SIZE={options['config_main_stack_size']}\\n\")\n\n            f.write(\"# For random number generation.\\n\" \"CONFIG_TEST_RANDOM_GENERATOR=y\\n\")\n\n            f.write(\"\\n# Extra prj.conf directives\\n\")\n            for line, board_list in self.EXTRA_PRJ_CONF_DIRECTIVES.items():\n                if zephyr_board in board_list:\n                    f.write(f\"{line}\\n\")\n\n            # TODO(mehrdadh): due to https://github.com/apache/tvm/issues/12721\n            if zephyr_board not in [\"qemu_riscv64\"]:\n                f.write(\"# For setting -O2 in compiler.\\n\" \"CONFIG_SPEED_OPTIMIZATIONS=y\\n\")\n\n            f.write(\"\\n\")\n\n    API_SERVER_CRT_LIBS_TOKEN = \"<API_SERVER_CRT_LIBS>\"\n    CMAKE_ARGS_TOKEN = \"<CMAKE_ARGS>\"\n    QEMU_PIPE_TOKEN = \"<QEMU_PIPE>\"\n    CMSIS_PATH_TOKEN = \"<CMSIS_PATH>\"\n\n    CRT_LIBS_BY_PROJECT_TYPE = {\n        \"host_driven\": \"microtvm_rpc_server microtvm_rpc_common aot_executor_module aot_executor common\",\n        \"aot_standalone_demo\": \"memory microtvm_rpc_common common\",\n    }\n\n    def _get_platform_version(self, zephyr_base: str) -> float:\n        with open(pathlib.Path(zephyr_base) / \"VERSION\", \"r\") as f:\n            lines = f.readlines()\n            for line in lines:\n                line = line.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n                if \"VERSION_MAJOR\" in line:\n                    version_major = line.split(\"=\")[1]\n                if \"VERSION_MINOR\" in line:\n                    version_minor = line.split(\"=\")[1]\n\n        return float(f\"{version_major}.{version_minor}\")\n\n    def _cmsis_required(self, project_path: Union[str, pathlib.Path]) -> bool:\n        \"\"\"Check if CMSIS dependency is required.\"\"\"\n        project_path = pathlib.Path(project_path)\n        for path in (project_path / \"codegen\" / \"host\" / \"src\").iterdir():\n            if path.is_file():\n                with open(path, \"r\") as lib_f:\n                    lib_content = lib_f.read()\n                if any(\n                    header in lib_content\n                    for header in [\n                        \"<arm_nnsupportfunctions.h>\",\n                        \"arm_nn_types.h\",\n                        \"arm_nnfunctions.h\",\n                    ]\n                ):\n                    return True\n        return False\n\n    def _generate_cmake_args(self, mlf_extracted_path, options) -> str:\n        cmake_args = \"\\n# cmake args\\n\"\n        if options.get(\"verbose\"):\n            cmake_args += \"set(CMAKE_VERBOSE_MAKEFILE TRUE)\\n\"\n\n        if options.get(\"zephyr_base\"):\n            cmake_args += f\"set(ZEPHYR_BASE {options['zephyr_base']})\\n\"\n\n        if options.get(\"west_cmd\"):\n            cmake_args += f\"set(WEST {options['west_cmd']})\\n\"\n\n        if self._is_qemu(options[\"board\"], options.get(\"use_fvp\")):\n            # Some boards support more than one emulator, so ensure QEMU is set.\n            cmake_args += f\"set(EMU_PLATFORM qemu)\\n\"\n\n        if self._is_fvp(options[\"board\"], options.get(\"use_fvp\")):\n            cmake_args += \"set(EMU_PLATFORM armfvp)\\n\"\n            cmake_args += \"set(ARMFVP_FLAGS -I)\\n\"\n\n        cmake_args += f\"set(BOARD {options['board']})\\n\"\n\n        enable_cmsis = self._cmsis_required(mlf_extracted_path)\n        if enable_cmsis:\n            assert os.environ.get(\"CMSIS_PATH\"), \"CMSIS_PATH is not defined.\"\n        cmake_args += f\"set(ENABLE_CMSIS {str(enable_cmsis).upper()})\\n\"\n\n        return cmake_args\n\n    def generate_project(self, model_library_format_path, standalone_crt_dir, project_dir, options):\n        zephyr_board = options[\"board\"]\n\n        # Check Zephyr version\n        version = self._get_platform_version(get_zephyr_base(options))\n        if version != ZEPHYR_VERSION:\n            message = f\"Zephyr version found is not supported: found {version}, expected {ZEPHYR_VERSION}.\"\n            if options.get(\"warning_as_error\") is not None and options[\"warning_as_error\"]:\n                raise server.ServerError(message=message)\n            _LOG.warning(message)\n\n        project_dir = pathlib.Path(project_dir)\n        # Make project directory.\n        project_dir.mkdir()\n\n        # Copy ourselves to the generated project. TVM may perform further build steps on the generated project\n        # by launching the copy.\n        shutil.copy2(__file__, project_dir / os.path.basename(__file__))\n\n        # Copy boards.json file to generated project.\n        shutil.copy2(BOARDS, project_dir / BOARDS.name)\n\n        # Copy overlay files\n        board_overlay_path = API_SERVER_DIR / \"app-overlay\" / f\"{zephyr_board}.overlay\"\n        if board_overlay_path.exists():\n            shutil.copy2(board_overlay_path, project_dir / f\"{zephyr_board}.overlay\")\n\n        # Place Model Library Format tarball in the special location, which this script uses to decide\n        # whether it's being invoked in a template or generated project.\n        project_model_library_format_tar_path = project_dir / MODEL_LIBRARY_FORMAT_RELPATH\n        shutil.copy2(model_library_format_path, project_model_library_format_tar_path)\n\n        # Extract Model Library Format tarball.into <project_dir>/model.\n        extract_path = os.path.splitext(project_model_library_format_tar_path)[0]\n        with tarfile.TarFile(project_model_library_format_tar_path) as tf:\n            os.makedirs(extract_path)\n            tf.extractall(path=extract_path)\n\n        if self._is_qemu(zephyr_board, options.get(\"use_fvp\")):\n            shutil.copytree(API_SERVER_DIR / \"qemu-hack\", project_dir / \"qemu-hack\")\n        elif self._is_fvp(zephyr_board, options.get(\"use_fvp\")):\n            shutil.copytree(API_SERVER_DIR / \"fvp-hack\", project_dir / \"fvp-hack\")\n\n        # Populate CRT.\n        crt_path = project_dir / \"crt\"\n        crt_path.mkdir()\n        for item in self.CRT_COPY_ITEMS:\n            src_path = os.path.join(standalone_crt_dir, item)\n            dst_path = crt_path / item\n            if os.path.isdir(src_path):\n                shutil.copytree(src_path, dst_path)\n            else:\n                shutil.copy2(src_path, dst_path)\n\n        # Populate Makefile.\n        with open(project_dir / CMAKELIST_FILENAME, \"w\") as cmake_f:\n            with open(API_SERVER_DIR / f\"{CMAKELIST_FILENAME}.template\", \"r\") as cmake_template_f:\n                for line in cmake_template_f:\n                    if self.API_SERVER_CRT_LIBS_TOKEN in line:\n                        crt_libs = self.CRT_LIBS_BY_PROJECT_TYPE[options[\"project_type\"]]\n                        line = line.replace(\"<API_SERVER_CRT_LIBS>\", crt_libs)\n\n                    if self.CMAKE_ARGS_TOKEN in line:\n                        line = self._generate_cmake_args(extract_path, options)\n\n                    if self.QEMU_PIPE_TOKEN in line:\n                        self.qemu_pipe_dir = pathlib.Path(tempfile.mkdtemp())\n                        line = line.replace(self.QEMU_PIPE_TOKEN, str(self.qemu_pipe_dir / \"fifo\"))\n\n                    if self.CMSIS_PATH_TOKEN in line and self._cmsis_required(extract_path):\n                        line = line.replace(self.CMSIS_PATH_TOKEN, str(os.environ[\"CMSIS_PATH\"]))\n\n                    cmake_f.write(line)\n\n                heap_size = _get_recommended_heap_size_bytes(options)\n                if options.get(\"heap_size_bytes\"):\n                    board_mem_size = _get_board_mem_size_bytes(options)\n                    heap_size = options[\"heap_size_bytes\"]\n                    if board_mem_size is not None:\n                        assert (\n                            heap_size < board_mem_size\n                        ), f\"Heap size {heap_size} is larger than memory size {board_mem_size} on this board.\"\n                cmake_f.write(\n                    f\"target_compile_definitions(app PUBLIC -DHEAP_SIZE_BYTES={heap_size})\\n\"\n                )\n\n                if options.get(\"compile_definitions\"):\n                    flags = options.get(\"compile_definitions\")\n                    for item in flags:\n                        cmake_f.write(f\"target_compile_definitions(app PUBLIC {item})\\n\")\n\n                if self._is_fvp(zephyr_board, options.get(\"use_fvp\")):\n                    cmake_f.write(f\"target_compile_definitions(app PUBLIC -DFVP=1)\\n\")\n\n        self._create_prj_conf(project_dir, options)\n\n        # Populate crt-config.h\n        crt_config_dir = project_dir / \"crt_config\"\n        crt_config_dir.mkdir()\n        shutil.copy2(\n            API_SERVER_DIR / \"crt_config\" / \"crt_config.h\", crt_config_dir / \"crt_config.h\"\n        )\n\n        # Populate src/\n        src_dir = project_dir / \"src\"\n        if options[\"project_type\"] != \"host_driven\" or self._is_fvp(\n            zephyr_board, options.get(\"use_fvp\")\n        ):\n            shutil.copytree(API_SERVER_DIR / \"src\" / options[\"project_type\"], src_dir)\n        else:\n            src_dir.mkdir()\n            shutil.copy2(API_SERVER_DIR / \"src\" / options[\"project_type\"] / \"main.c\", src_dir)\n\n        # Populate extra_files\n        if options.get(\"extra_files_tar\"):\n            with tarfile.open(options[\"extra_files_tar\"], mode=\"r:*\") as tf:\n                tf.extractall(project_dir)\n\n    def build(self, options):\n        if BUILD_DIR.exists():\n            shutil.rmtree(BUILD_DIR)\n        BUILD_DIR.mkdir()\n\n        zephyr_board = _find_board_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)\n        emu_platform = _find_platform_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)\n\n        env = os.environ\n        if self._is_fvp(zephyr_board, emu_platform == \"armfvp\"):\n            env[\"ARMFVP_BIN_PATH\"] = str((API_SERVER_DIR / \"fvp-hack\").resolve())\n            # Note: We need to explicitly modify the file permissions and make it an executable to pass CI tests.\n            # [To Do]: Move permission change to Build.groovy.j2\n            st = os.stat(env[\"ARMFVP_BIN_PATH\"] + \"/FVP_Corstone_SSE-300_Ethos-U55\")\n            os.chmod(\n                env[\"ARMFVP_BIN_PATH\"] + \"/FVP_Corstone_SSE-300_Ethos-U55\",\n                st.st_mode | stat.S_IEXEC,\n            )\n\n        check_call([\"cmake\", \"-GNinja\", \"..\"], cwd=BUILD_DIR, env=env)\n\n        args = [\"ninja\"]\n        if options.get(\"verbose\"):\n            args.append(\"-v\")\n        check_call(args, cwd=BUILD_DIR, env=env)\n\n    # A list of all zephyr_board values which are known to launch using QEMU. Many platforms which\n    # launch through QEMU by default include \"qemu\" in their name. However, not all do. This list\n    # includes those tested platforms which do not include qemu.\n    _KNOWN_QEMU_ZEPHYR_BOARDS = [\"mps2_an521\", \"mps3_an547\"]\n\n    # A list of all zephyr_board values which are known to launch using ARM FVP (this script configures\n    # Zephyr to use that launch method).\n    _KNOWN_FVP_ZEPHYR_BOARDS = [\"mps3_an547\"]\n\n    @classmethod\n    def _is_fvp(cls, board, use_fvp):\n        if use_fvp:\n            assert (\n                board in cls._KNOWN_FVP_ZEPHYR_BOARDS\n            ), \"FVP can't be used to emulate this board on Zephyr\"\n            return True\n        return False\n\n    @classmethod\n    def _is_qemu(cls, board, use_fvp=False):\n        return \"qemu\" in board or (\n            board in cls._KNOWN_QEMU_ZEPHYR_BOARDS and not cls._is_fvp(board, use_fvp)\n        )\n\n    @classmethod\n    def _has_fpu(cls, zephyr_board):\n        fpu_boards = [name for name, board in BOARD_PROPERTIES.items() if board[\"fpu\"]]\n        return zephyr_board in fpu_boards\n\n    def flash(self, options):\n        if _find_platform_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME):\n            return  # NOTE: qemu requires no flash step--it is launched from open_transport.\n\n        # The nRF5340DK requires an additional `nrfjprog --recover` before each flash cycle.\n        # This is because readback protection is enabled by default when this device is flashed.\n        # Otherwise, flashing may fail with an error such as the following:\n        #  ERROR: The operation attempted is unavailable due to readback protection in\n        #  ERROR: your device. Please use --recover to unlock the device.\n        zephyr_board = _find_board_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)\n        if zephyr_board.startswith(\"nrf5340dk\") and _get_flash_runner() == \"nrfjprog\":\n            recover_args = [\"nrfjprog\", \"--recover\"]\n            recover_args.extend(_get_nrf_device_args(options))\n            check_call(recover_args, cwd=API_SERVER_DIR / \"build\")\n\n        check_call([\"ninja\", \"flash\"], cwd=API_SERVER_DIR / \"build\")\n\n    def open_transport(self, options):\n        zephyr_board = _find_board_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)\n        emu_platform = _find_platform_from_cmake_file(API_SERVER_DIR / CMAKELIST_FILENAME)\n        if self._is_fvp(zephyr_board, emu_platform == \"armfvp\"):\n            transport = ZephyrFvpTransport(options)\n        elif self._is_qemu(zephyr_board):\n            transport = ZephyrQemuTransport(options)\n        else:\n            transport = ZephyrSerialTransport(options)\n\n        to_return = transport.open()\n        self._transport = transport\n        atexit.register(lambda: self.close_transport())\n        return to_return\n\n    def close_transport(self):\n        if self._transport is not None:\n            self._transport.close()\n            self._transport = None\n\n    def read_transport(self, n, timeout_sec):\n        if self._transport is None:\n            raise server.TransportClosedError()\n\n        return self._transport.read(n, timeout_sec)\n\n    def write_transport(self, data, timeout_sec):\n        if self._transport is None:\n            raise server.TransportClosedError()\n\n        return self._transport.write(data, timeout_sec)\n\n\ndef _set_nonblock(fd):\n    flag = fcntl.fcntl(fd, fcntl.F_GETFL)\n    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)\n    new_flag = fcntl.fcntl(fd, fcntl.F_GETFL)\n    assert (new_flag & os.O_NONBLOCK) != 0, \"Cannot set file descriptor {fd} to non-blocking\"\n\n\nclass ZephyrSerialTransport:\n\n    NRF5340_VENDOR_ID = 0x1366\n\n    # NRF5340_DK v1.0.0 uses VCOM2\n    # NRF5340_DK v2.0.0 uses VCOM1\n    NRF5340_DK_BOARD_VCOM_BY_PRODUCT_ID = {0x1055: \"VCOM2\", 0x1051: \"VCOM1\"}\n\n    @classmethod\n    def _lookup_baud_rate(cls, options):\n        # TODO(mehrdadh): remove this hack once dtlib.py is a standalone project\n        # https://github.com/zephyrproject-rtos/zephyr/blob/v2.7-branch/scripts/dts/README.txt\n        sys.path.insert(\n            0,\n            os.path.join(\n                get_zephyr_base(options), \"scripts\", \"dts\", \"python-devicetree\", \"src\", \"devicetree\"\n            ),\n        )\n        try:\n            import dtlib  # pylint: disable=import-outside-toplevel\n        finally:\n            sys.path.pop(0)\n\n        dt_inst = dtlib.DT(BUILD_DIR / \"zephyr\" / \"zephyr.dts\")\n        uart_baud = (\n            dt_inst.get_node(\"/chosen\")\n            .props[\"zephyr,console\"]\n            .to_path()\n            .props[\"current-speed\"]\n            .to_num()\n        )\n        _LOG.debug(\"zephyr transport: found UART baudrate from devicetree: %d\", uart_baud)\n\n        return uart_baud\n\n    @classmethod\n    def _find_nrf_serial_port(cls, options):\n        com_ports = subprocess.check_output(\n            [\"nrfjprog\", \"--com\"] + _get_device_args(options), encoding=\"utf-8\"\n        )\n        ports_by_vcom = {}\n        for line in com_ports.split(\"\\n\")[:-1]:\n            parts = line.split()\n            ports_by_vcom[parts[2]] = parts[1]\n\n        nrf_board = usb.core.find(idVendor=cls.NRF5340_VENDOR_ID)\n\n        if nrf_board == None:\n            raise Exception(\"_find_nrf_serial_port: unable to find NRF5340DK\")\n\n        if nrf_board.idProduct in cls.NRF5340_DK_BOARD_VCOM_BY_PRODUCT_ID:\n            vcom_port = cls.NRF5340_DK_BOARD_VCOM_BY_PRODUCT_ID[nrf_board.idProduct]\n        else:\n            raise Exception(\"_find_nrf_serial_port: unable to find known NRF5340DK product ID\")\n\n        return ports_by_vcom[vcom_port]\n\n    @classmethod\n    def _find_openocd_serial_port(cls, options):\n        serial_number = options.get(\"openocd_serial\")\n        return generic_find_serial_port(serial_number)\n\n    @classmethod\n    def _find_jlink_serial_port(cls, options):\n        return generic_find_serial_port()\n\n    @classmethod\n    def _find_stm32cubeprogrammer_serial_port(cls, options):\n        return generic_find_serial_port()\n\n    @classmethod\n    def _find_serial_port(cls, options):\n        flash_runner = _get_flash_runner()\n\n        if flash_runner == \"nrfjprog\":\n            return cls._find_nrf_serial_port(options)\n\n        if flash_runner == \"openocd\":\n            return cls._find_openocd_serial_port(options)\n\n        if flash_runner == \"jlink\":\n            return cls._find_jlink_serial_port(options)\n\n        if flash_runner == \"stm32cubeprogrammer\":\n            return cls._find_stm32cubeprogrammer_serial_port(options)\n\n        raise RuntimeError(f\"Don't know how to deduce serial port for flash runner {flash_runner}\")\n\n    def __init__(self, options):\n        self._options = options\n        self._port = None\n\n    def open(self):\n        port_path = self._find_serial_port(self._options)\n        self._port = serial.Serial(port_path, baudrate=self._lookup_baud_rate(self._options))\n        return server.TransportTimeouts(\n            session_start_retry_timeout_sec=2.0,\n            session_start_timeout_sec=5.0,\n            session_established_timeout_sec=5.0,\n        )\n\n    def close(self):\n        self._port.close()\n        self._port = None\n\n    def read(self, n, timeout_sec):\n        self._port.timeout = timeout_sec\n        to_return = self._port.read(n)\n        if not to_return:\n            raise server.IoTimeoutError()\n\n        return to_return\n\n    def write(self, data, timeout_sec):\n        self._port.write_timeout = timeout_sec\n        bytes_written = 0\n        while bytes_written < len(data):\n            n = self._port.write(data)\n            data = data[n:]\n            bytes_written += n\n\n\nclass ZephyrQemuMakeResult(enum.Enum):\n    QEMU_STARTED = \"qemu_started\"\n    MAKE_FAILED = \"make_failed\"\n    EOF = \"eof\"\n\n\nclass ZephyrQemuTransport:\n    \"\"\"The user-facing Zephyr QEMU transport class.\"\"\"\n\n    def __init__(self, options):\n        self.options = options\n        self.proc = None\n        self.pipe_dir = None\n        self.read_fd = None\n        self.write_fd = None\n        self._queue = queue.Queue()\n\n    def open(self):\n        with open(BUILD_DIR / \"CMakeCache.txt\", \"r\") as cmake_cache_f:\n            for line in cmake_cache_f:\n                if \"QEMU_PIPE:\" in line:\n                    self.pipe = pathlib.Path(line[line.find(\"=\") + 1 :])\n                    break\n        self.pipe_dir = self.pipe.parents[0]\n        self.write_pipe = self.pipe_dir / \"fifo.in\"\n        self.read_pipe = self.pipe_dir / \"fifo.out\"\n        os.mkfifo(self.write_pipe)\n        os.mkfifo(self.read_pipe)\n\n        env = None\n        if self.options.get(\"gdbserver_port\"):\n            env = os.environ.copy()\n            env[\"TVM_QEMU_GDBSERVER_PORT\"] = self.options[\"gdbserver_port\"]\n\n        self.proc = subprocess.Popen(\n            [\"ninja\", \"run\"],\n            cwd=BUILD_DIR,\n            env=env,\n            stdout=subprocess.PIPE,\n        )\n        self._wait_for_qemu()\n\n        # NOTE: although each pipe is unidirectional, open both as RDWR to work around a select\n        # limitation on linux. Without this, non-blocking I/O can't use timeouts because named\n        # FIFO are always considered ready to read when no one has opened them for writing.\n        self.read_fd = os.open(self.read_pipe, os.O_RDWR | os.O_NONBLOCK)\n        self.write_fd = os.open(self.write_pipe, os.O_RDWR | os.O_NONBLOCK)\n        _set_nonblock(self.read_fd)\n        _set_nonblock(self.write_fd)\n\n        return server.TransportTimeouts(\n            session_start_retry_timeout_sec=2.0,\n            session_start_timeout_sec=10.0,\n            session_established_timeout_sec=10.0,\n        )\n\n    def close(self):\n        did_write = False\n        if self.write_fd is not None:\n            try:\n                server.write_with_timeout(\n                    self.write_fd, b\"\\x01x\", 1.0\n                )  # Use a short timeout since we will kill the process\n                did_write = True\n            except server.IoTimeoutError:\n                pass\n            os.close(self.write_fd)\n            self.write_fd = None\n\n        if self.proc:\n            if not did_write:\n                self.proc.terminate()\n            try:\n                self.proc.wait(5.0)\n            except subprocess.TimeoutExpired:\n                self.proc.kill()\n\n        if self.read_fd:\n            os.close(self.read_fd)\n            self.read_fd = None\n\n        if self.pipe_dir is not None:\n            shutil.rmtree(self.pipe_dir)\n            self.pipe_dir = None\n\n    def read(self, n, timeout_sec):\n        return server.read_with_timeout(self.read_fd, n, timeout_sec)\n\n    def write(self, data, timeout_sec):\n        to_write = bytearray()\n        escape_pos = []\n        for i, b in enumerate(data):\n            if b == 0x01:\n                to_write.append(b)\n                escape_pos.append(i)\n            to_write.append(b)\n\n        while to_write:\n            num_written = server.write_with_timeout(self.write_fd, to_write, timeout_sec)\n            to_write = to_write[num_written:]\n\n    def _qemu_check_stdout(self):\n        for line in self.proc.stdout:\n            line = str(line)\n            _LOG.info(\"%s\", line)\n            if \"[QEMU] CPU\" in line:\n                self._queue.put(ZephyrQemuMakeResult.QEMU_STARTED)\n            else:\n                line = re.sub(\"[^a-zA-Z0-9 \\n]\", \"\", line)\n                pattern = r\"recipe for target (\\w*) failed\"\n                if re.search(pattern, line, re.IGNORECASE):\n                    self._queue.put(ZephyrQemuMakeResult.MAKE_FAILED)\n        self._queue.put(ZephyrQemuMakeResult.EOF)\n\n    def _wait_for_qemu(self):\n        threading.Thread(target=self._qemu_check_stdout, daemon=True).start()\n        while True:\n            try:\n                item = self._queue.get(timeout=120)\n            except Exception:\n                raise TimeoutError(\"QEMU setup timeout.\")\n\n            if item == ZephyrQemuMakeResult.QEMU_STARTED:\n                break\n\n            if item in [ZephyrQemuMakeResult.MAKE_FAILED, ZephyrQemuMakeResult.EOF]:\n                raise RuntimeError(\"QEMU setup failed.\")\n\n            raise ValueError(f\"{item} not expected.\")\n\n\nclass ZephyrFvpMakeResult(enum.Enum):\n    FVP_STARTED = \"fvp_started\"\n    MICROTVM_API_SERVER_INIT = \"fvp_initialized\"\n    MAKE_FAILED = \"make_failed\"\n    EOF = \"eof\"\n\n\nclass BlockingStream:\n    \"\"\"Reimplementation of Stream class from Iris with blocking semantics.\"\"\"\n\n    def __init__(self):\n        self.q = queue.Queue()\n        self.unread = None\n\n    def read(self, n=-1, timeout_sec=None):\n        assert (\n            n != -1\n        ), \"expect firmware to open stdin using raw mode, and therefore expect sized read requests\"\n\n        data = b\"\"\n        if self.unread:\n            data = data + self.unread\n            self.unread = None\n\n        while len(data) < n:\n            try:\n                # When there is some data to return, fetch as much as possible, then return what we can.\n                # When there is no data yet to return, block.\n                data += self.q.get(block=not len(data), timeout=timeout_sec)\n            except queue.Empty:\n                break\n\n        if len(data) > n:\n            self.unread = data[n:]\n            data = data[:n]\n\n        return data\n\n    readline = read\n\n    def write(self, data):\n        self.q.put(data)\n\n\nclass ZephyrFvpTransport:\n    \"\"\"A transport class that communicates with the ARM FVP via Iris server.\"\"\"\n\n    def __init__(self, options):\n        self.options = options\n        self.proc = None\n        self._queue = queue.Queue()\n        self._import_iris()\n\n    def _import_iris(self):\n        assert \"arm_fvp_path\" in self.options, \"arm_fvp_path is not defined.\"\n        # Location as seen in the FVP_Corstone_SSE-300_11.15_24 tar.\n        iris_lib_path = (\n            pathlib.Path(self.options[\"arm_fvp_path\"]).parent.parent.parent\n            / \"Iris\"\n            / \"Python\"\n            / \"iris\"\n        )\n\n        sys.path.insert(0, str(iris_lib_path.parent))\n        try:\n            import iris.NetworkModelInitializer\n        finally:\n            sys.path.pop(0)\n\n        self._iris_lib = iris\n\n        def _convertStringToU64Array(strValue):\n            numBytes = len(strValue)\n            if numBytes == 0:\n                return []\n\n            numU64 = (numBytes + 7) // 8\n            # Extend the string ending with '\\0', so that the string length is multiple of 8.\n            # E.g. 'hello' is extended to: 'hello'+\\0\\0\\0\n            strExt = strValue.ljust(8 * numU64, b\"\\0\")\n            # Convert the string to a list of uint64_t in little endian\n            return struct.unpack(\"<{}Q\".format(numU64), strExt)\n\n        iris.iris.convertStringToU64Array = _convertStringToU64Array\n\n    def open(self):\n        args = [\"ninja\"]\n        if self.options.get(\"verbose\"):\n            args.append(\"-v\")\n        args.append(\"run\")\n        env = dict(os.environ)\n        env[\"ARMFVP_BIN_PATH\"] = str(API_SERVER_DIR / \"fvp-hack\")\n        self.proc = subprocess.Popen(\n            args,\n            cwd=BUILD_DIR,\n            env=env,\n            stdout=subprocess.PIPE,\n        )\n        threading.Thread(target=self._fvp_check_stdout, daemon=True).start()\n\n        self.iris_port = self._wait_for_fvp()\n        _LOG.info(\"IRIS started on port %d\", self.iris_port)\n        NetworkModelInitializer = self._iris_lib.NetworkModelInitializer.NetworkModelInitializer\n        self._model_init = NetworkModelInitializer(\n            host=\"localhost\", port=self.iris_port, timeout_in_ms=1000\n        )\n        self._model = self._model_init.start()\n        self._target = self._model.get_target(\"component.FVP_MPS3_Corstone_SSE_300.cpu0\")\n\n        self._target.handle_semihost_io()\n        self._target._stdout = BlockingStream()\n        self._target._stdin = BlockingStream()\n        self._model.run(blocking=False, timeout=100)\n        self._wait_for_semihost_init()\n        _LOG.info(\"IRIS semihosting initialized.\")\n\n        return server.TransportTimeouts(\n            session_start_retry_timeout_sec=2.0,\n            session_start_timeout_sec=10.0,\n            session_established_timeout_sec=10.0,\n        )\n\n    def _fvp_check_stdout(self):\n        START_MSG = \"Iris server started listening to port\"\n        INIT_MSG = \"microTVM Zephyr runtime - running\"\n        for line in self.proc.stdout:\n            line = str(line, \"utf-8\")\n            _LOG.info(\"%s\", line)\n            start_msg = re.match(START_MSG + r\" ([0-9]+)\\n\", line)\n            init_msg = re.match(INIT_MSG, line)\n            if start_msg:\n                self._queue.put((ZephyrFvpMakeResult.FVP_STARTED, int(start_msg.group(1))))\n            elif init_msg:\n                self._queue.put((ZephyrFvpMakeResult.MICROTVM_API_SERVER_INIT, None))\n                break\n            else:\n                line = re.sub(\"[^a-zA-Z0-9 \\n]\", \"\", line)\n                pattern = r\"recipe for target (\\w*) failed\"\n                if re.search(pattern, line, re.IGNORECASE):\n                    self._queue.put((ZephyrFvpMakeResult.MAKE_FAILED, None))\n\n        self._queue.put((ZephyrFvpMakeResult.EOF, None))\n\n    def _wait_for_fvp(self):\n        \"\"\"waiting for the START_MSG to appear on the stdout\"\"\"\n        while True:\n            try:\n                item = self._queue.get(timeout=120)\n            except Exception:\n                raise TimeoutError(\"FVP setup timeout.\")\n\n            if item[0] == ZephyrFvpMakeResult.FVP_STARTED:\n                return item[1]\n\n            if item[0] in [ZephyrFvpMakeResult.MAKE_FAILED, ZephyrFvpMakeResult.EOF]:\n                raise RuntimeError(\"FVP setup failed.\")\n\n            raise ValueError(f\"{item} not expected.\")\n\n    def _wait_for_semihost_init(self):\n        \"\"\"waiting for the INIT_MSG to appear on the stdout\"\"\"\n        while True:\n            try:\n                item = self._queue.get(timeout=240)\n            except Exception:\n                raise TimeoutError(\"semihost init timeout.\")\n\n            if item[0] == ZephyrFvpMakeResult.MICROTVM_API_SERVER_INIT:\n                return\n\n            raise ValueError(f\"{item} not expected.\")\n\n    def close(self):\n        self._model._shutdown_model()\n        self._model.client.disconnect(force=True)\n        parent = psutil.Process(self.proc.pid)\n        if parent:\n            for child in parent.children(recursive=True):\n                child.terminate()\n            parent.terminate()\n\n    def read(self, n, timeout_sec):\n        return self._target.stdout.read(n, timeout_sec)\n\n    def write(self, data, timeout_sec):\n        self._target.stdin.write(data)\n\n\nif __name__ == \"__main__\":\n    server.main(Handler())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/aot_standalone_demo/main.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <assert.h>\n#include <float.h>\n#include <kernel.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/reboot.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/stack_allocator.h>\n#include <unistd.h>\n#include <zephyr.h>\n\n#include \"input_data.h\"\n#include \"output_data.h\"\n#include \"tvmgen_default.h\"\n#include \"zephyr_uart.h\"\n\n#ifdef CONFIG_ARCH_POSIX\n#include \"posix_board_if.h\"\n#endif\n\n// WORKSPACE_SIZE defined in Project API Makefile\n\nstatic uint8_t g_aot_memory[WORKSPACE_SIZE];\ntvm_workspace_t app_workspace;\n\n// Transport Commands.\n// Commands on host end with `\\n`\n// Commands on microTVM device end with `%`\nconst unsigned char CMD_WAKEUP[] = \"wakeup\\n\";\nconst unsigned char CMD_READY[] = \"ready\\n\";\nconst unsigned char CMD_INIT[] = \"init\";\nconst unsigned char CMD_INFER[] = \"infer\";\n\n#define CMD_SIZE 80u\n#define CMD_TERMINATOR '%'\n\nsize_t TVMPlatformFormatMessage(char* out_buf, size_t out_buf_size_bytes, const char* fmt,\n                                va_list args) {\n  return vsnprintk(out_buf, out_buf_size_bytes, fmt, args);\n}\n\nvoid TVMLogf(const char* msg, ...) {\n  char buffer[256];\n  int size;\n  va_list args;\n  va_start(args, msg);\n  size = vsprintf(buffer, msg, args);\n  va_end(args);\n  TVMPlatformWriteSerial(buffer, (uint32_t)size);\n}\n\nvoid TVMPlatformAbort(tvm_crt_error_t error) {\n  TVMLogf(\"TVMPlatformAbort: %08x\\n\", error);\n  sys_reboot(SYS_REBOOT_COLD);\n  for (;;)\n    ;\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  return StackMemoryManager_Allocate(&app_workspace, num_bytes, out_ptr);\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return StackMemoryManager_Free(&app_workspace, ptr);\n}\n\nvoid timer_expiry_function(struct k_timer* timer_id) { return; }\n\n#define MILLIS_TIL_EXPIRY 200\n#define TIME_TIL_EXPIRY (K_MSEC(MILLIS_TIL_EXPIRY))\nstruct k_timer g_microtvm_timer;\nuint32_t g_microtvm_start_time;\nint g_microtvm_timer_running = 0;\n\n// Called to start system timer.\ntvm_crt_error_t TVMPlatformTimerStart() {\n  if (g_microtvm_timer_running) {\n    TVMLogf(\"timer already running\");\n    return kTvmErrorPlatformTimerBadState;\n  }\n\n  k_timer_start(&g_microtvm_timer, TIME_TIL_EXPIRY, TIME_TIL_EXPIRY);\n  g_microtvm_start_time = k_cycle_get_32();\n  g_microtvm_timer_running = 1;\n  return kTvmErrorNoError;\n}\n\n// Called to stop system timer.\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  if (!g_microtvm_timer_running) {\n    TVMLogf(\"timer not running\");\n    return kTvmErrorSystemErrorMask | 2;\n  }\n\n  uint32_t stop_time = k_cycle_get_32();\n\n  // compute how long the work took\n  uint32_t cycles_spent = stop_time - g_microtvm_start_time;\n  if (stop_time < g_microtvm_start_time) {\n    // we rolled over *at least* once, so correct the rollover it was *only*\n    // once, because we might still use this result\n    cycles_spent = ~((uint32_t)0) - (g_microtvm_start_time - stop_time);\n  }\n\n  uint32_t ns_spent = (uint32_t)k_cyc_to_ns_floor64(cycles_spent);\n  double hw_clock_res_us = ns_spent / 1000.0;\n\n  // need to grab time remaining *before* stopping. when stopped, this function\n  // always returns 0.\n  int32_t time_remaining_ms = k_timer_remaining_get(&g_microtvm_timer);\n  k_timer_stop(&g_microtvm_timer);\n  // check *after* stopping to prevent extra expiries on the happy path\n  if (time_remaining_ms < 0) {\n    return kTvmErrorSystemErrorMask | 3;\n  }\n  uint32_t num_expiries = k_timer_status_get(&g_microtvm_timer);\n  uint32_t timer_res_ms = ((num_expiries * MILLIS_TIL_EXPIRY) + time_remaining_ms);\n  double approx_num_cycles =\n      (double)k_ticks_to_cyc_floor32(1) * (double)k_ms_to_ticks_ceil32(timer_res_ms);\n  // if we approach the limits of the HW clock datatype (uint32_t), use the\n  // coarse-grained timer result instead\n  if (approx_num_cycles > (0.5 * (~((uint32_t)0)))) {\n    *elapsed_time_seconds = timer_res_ms / 1000.0;\n  } else {\n    *elapsed_time_seconds = hw_clock_res_us / 1e6;\n  }\n\n  g_microtvm_timer_running = 0;\n  return kTvmErrorNoError;\n}\n\nvoid* TVMBackendAllocWorkspace(int device_type, int device_id, uint64_t nbytes, int dtype_code_hint,\n                               int dtype_bits_hint) {\n  tvm_crt_error_t err = kTvmErrorNoError;\n  void* ptr = 0;\n  DLDevice dev = {device_type, device_id};\n  assert(nbytes > 0);\n  err = TVMPlatformMemoryAllocate(nbytes, dev, &ptr);\n  CHECK_EQ(err, kTvmErrorNoError,\n           \"TVMBackendAllocWorkspace(%d, %d, %\" PRIu64 \", %d, %d) -> %\" PRId32, device_type,\n           device_id, nbytes, dtype_code_hint, dtype_bits_hint, err);\n  return ptr;\n}\n\nint TVMBackendFreeWorkspace(int device_type, int device_id, void* ptr) {\n  tvm_crt_error_t err = kTvmErrorNoError;\n  DLDevice dev = {device_type, device_id};\n  err = TVMPlatformMemoryFree(ptr, dev);\n  return err;\n}\n\nstatic uint8_t main_rx_buf[128];\nstatic uint8_t g_cmd_buf[128];\nstatic size_t g_cmd_buf_ind;\n\nvoid TVMInfer() {\n  struct tvmgen_default_inputs inputs = {\n      .input_1 = input_data,\n  };\n  struct tvmgen_default_outputs outputs = {\n      .Identity = output_data,\n  };\n\n  StackMemoryManager_Init(&app_workspace, g_aot_memory, WORKSPACE_SIZE);\n\n  double elapsed_time = 0;\n  TVMPlatformTimerStart();\n  int ret_val = tvmgen_default_run(&inputs, &outputs);\n  TVMPlatformTimerStop(&elapsed_time);\n\n  if (ret_val != 0) {\n    TVMLogf(\"Error: %d\\n\", ret_val);\n    TVMPlatformAbort(kTvmErrorPlatformCheckFailure);\n  }\n\n  size_t max_ind = -1;\n  float max_val = -FLT_MAX;\n  for (size_t i = 0; i < output_data_len; i++) {\n    if (output_data[i] >= max_val) {\n      max_ind = i;\n      max_val = output_data[i];\n    }\n  }\n  TVMLogf(\"result:%d:%d\\n\", max_ind, (uint32_t)(elapsed_time * 1000));\n}\n\n// Execute functions based on received command\nvoid command_ready(char* command) {\n  if (strncmp(command, CMD_INIT, CMD_SIZE) == 0) {\n    TVMPlatformWriteSerial(CMD_WAKEUP, sizeof(CMD_WAKEUP));\n  } else if (strncmp(command, CMD_INFER, CMD_SIZE) == 0) {\n    TVMInfer();\n  } else {\n    TVMPlatformWriteSerial(CMD_READY, sizeof(CMD_READY));\n  }\n}\n\n// Append received characters to buffer and check for termination character.\nvoid serial_callback(char* message, int len_bytes) {\n  for (int i = 0; i < len_bytes; i++) {\n    if (message[i] == CMD_TERMINATOR) {\n      g_cmd_buf[g_cmd_buf_ind] = (char)0;\n      command_ready(g_cmd_buf);\n      g_cmd_buf_ind = 0;\n    } else {\n      g_cmd_buf[g_cmd_buf_ind] = message[i];\n      g_cmd_buf_ind += 1;\n    }\n  }\n}\n\nvoid main(void) {\n  g_cmd_buf_ind = 0;\n  memset((char*)g_cmd_buf, 0, sizeof(g_cmd_buf));\n  TVMPlatformUARTInit();\n  k_timer_init(&g_microtvm_timer, NULL, NULL);\n\n  while (true) {\n    int bytes_read = TVMPlatformUartRxRead(main_rx_buf, sizeof(main_rx_buf));\n    if (bytes_read > 0) {\n      serial_callback(main_rx_buf, bytes_read);\n    }\n  }\n\n#ifdef CONFIG_ARCH_POSIX\n  posix_exit(0);\n#endif\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/aot_standalone_demo/zephyr_uart.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#include \"zephyr_uart.h\"\n\n#include <drivers/uart.h>\n#include <sys/ring_buffer.h>\n\n#include \"crt_config.h\"\n\nstatic const struct device* g_microtvm_uart;\n#define RING_BUF_SIZE_BYTES (TVM_CRT_MAX_PACKET_SIZE_BYTES + 100)\n\n// Ring buffer used to store data read from the UART on rx interrupt.\nRING_BUF_DECLARE(uart_rx_rbuf, RING_BUF_SIZE_BYTES);\n\nstatic uint8_t uart_data[8];\n// UART interrupt callback.\nvoid uart_irq_cb(const struct device* dev, void* user_data) {\n  while (uart_irq_update(dev) && uart_irq_is_pending(dev)) {\n    struct ring_buf* rbuf = (struct ring_buf*)user_data;\n    if (uart_irq_rx_ready(dev) != 0) {\n      for (;;) {\n        // Read a small chunk of data from the UART.\n        int bytes_read = uart_fifo_read(dev, uart_data, sizeof(uart_data));\n        if (bytes_read < 0) {\n          TVMPlatformAbort((tvm_crt_error_t)(0xbeef1));\n        } else if (bytes_read == 0) {\n          break;\n        }\n        // Write it into the ring buffer.\n        int bytes_written = ring_buf_put(rbuf, uart_data, bytes_read);\n        if (bytes_read != bytes_written) {\n          TVMPlatformAbort((tvm_crt_error_t)(0xbeef2));\n        }\n      }\n    }\n  }\n}\n\n// Used to initialize the UART receiver.\nvoid uart_rx_init(struct ring_buf* rbuf, const struct device* dev) {\n  uart_irq_callback_user_data_set(dev, uart_irq_cb, (void*)rbuf);\n  uart_irq_rx_enable(dev);\n}\n\nuint32_t TVMPlatformUartRxRead(uint8_t* data, uint32_t data_size_bytes) {\n  unsigned int key = irq_lock();\n  uint32_t bytes_read = ring_buf_get(&uart_rx_rbuf, data, data_size_bytes);\n  irq_unlock(key);\n  return bytes_read;\n}\n\nuint32_t TVMPlatformWriteSerial(const char* data, uint32_t size) {\n  for (uint32_t i = 0; i < size; i++) {\n    uart_poll_out(g_microtvm_uart, data[i]);\n  }\n  return size;\n}\n\n// Initialize UART\nvoid TVMPlatformUARTInit() {\n  // Claim console device.\n  g_microtvm_uart = device_get_binding(DT_LABEL(DT_CHOSEN(zephyr_console)));\n  const struct uart_config config = {.baudrate = 115200,\n                                     .parity = UART_CFG_PARITY_NONE,\n                                     .stop_bits = UART_CFG_STOP_BITS_1,\n                                     .data_bits = UART_CFG_DATA_BITS_8,\n                                     .flow_ctrl = UART_CFG_FLOW_CTRL_NONE};\n  uart_configure(g_microtvm_uart, &config);\n  uart_rx_init(&uart_rx_rbuf, g_microtvm_uart);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/aot_standalone_demo/zephyr_uart.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_APPS_MICROTVM_ZEPHYR_AOT_STANDALONE_DEMO_ZEPHYR_UART_H_\n#define TVM_APPS_MICROTVM_ZEPHYR_AOT_STANDALONE_DEMO_ZEPHYR_UART_H_\n\n#include <stdint.h>\n\n// Used to read data from the UART.\n\n/*!\n * \\brief Read Uart Rx buffer.\n * \\param data Pointer to read data.\n * \\param data_size_bytes Read request size in bytes.\n *\n * \\return Number of data read in bytes.\n */\nuint32_t TVMPlatformUartRxRead(uint8_t* data, uint32_t data_size_bytes);\n\n/*!\n * \\brief Write data in serial.\n * \\param data Pointer to data to write.\n * \\param size Size of data in bytes.\n *\n * \\return Number of write in bytes.\n */\nuint32_t TVMPlatformWriteSerial(const char* data, uint32_t size);\n\n/*!\n * \\brief Initialize Uart.\n */\nvoid TVMPlatformUARTInit();\n\n#endif /* TVM_APPS_MICROTVM_ZEPHYR_AOT_STANDALONE_DEMO_ZEPHYR_UART_H_ */\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/host_driven/fvp/semihost.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#include \"semihost.h\"\n\nint32_t stdout_fd;\nint32_t stdin_fd;\n\nuint32_t semihost_cmd(uint32_t opcode, void* arg) {\n  uint32_t ret_val;\n  __asm__ volatile(\n      \"mov r0, %[opcode]\\n\\t\"\n      \"mov r1, %[arg]\\n\\t\"\n      \"bkpt #0xab\\n\\r\"\n      \"mov %[ret_val], r0\"\n      : [ ret_val ] \"=r\"(ret_val)\n      : [ opcode ] \"r\"(opcode), [ arg ] \"r\"(arg)\n      : \"r1\", \"memory\");\n\n  return ret_val;\n}\n\nint32_t stdout_fd;\nint32_t stdin_fd;\n\nvoid init_semihosting() {\n  // https://github.com/ARM-software/abi-aa/blob/main/semihosting/semihosting.rst#sys-open-0x01\n  struct {\n    const char* file_name;\n    uint32_t mode;\n    uint32_t file_name_len;\n  } params;\n  params.file_name = \":tt\";\n  params.mode = 5;  // \"wb\"\n  params.file_name_len = 3;\n  stdout_fd = semihost_cmd(0x01, &params);\n\n  params.mode = 0;\n  stdin_fd = semihost_cmd(0x01, &params);\n}\n\nssize_t semihost_read(uint8_t* data, size_t size) {\n  struct {\n    uint32_t file_handle;\n    const uint8_t* data;\n    uint32_t size;\n  } read_req;\n  read_req.file_handle = stdin_fd;\n  read_req.data = data;\n  read_req.size = size;\n  uint32_t ret_val = semihost_cmd(0x06, &read_req);\n  return size - ret_val;\n}\n\nssize_t semihost_write(void* unused_context, const uint8_t* data, size_t size) {\n  struct {\n    uint32_t file_handle;\n    const uint8_t* data;\n    uint32_t size;\n  } write_req;\n  write_req.file_handle = stdout_fd;\n  write_req.data = data;\n  write_req.size = size;\n  uint32_t ret_val = semihost_cmd(0x05, &write_req);\n  return size - ret_val;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/host_driven/fvp/semihost.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#ifndef TVM_APPS_MICROTVM_ZEPHYR_HOST_DRIVEN_SEMIHOST_H_\n#define TVM_APPS_MICROTVM_ZEPHYR_HOST_DRIVEN_SEMIHOST_H_\n\n#include <kernel.h>\n#include <unistd.h>\n#include <zephyr.h>\n\nvoid init_semihosting();\n\nssize_t semihost_read(uint8_t* data, size_t size);\n\nssize_t semihost_write(void* unused_context, const uint8_t* data, size_t size);\n\n#endif /* TVM_APPS_MICROTVM_ZEPHYR_HOST_DRIVEN_SEMIHOST_H_ */\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr/template_project/src/host_driven/main.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This is a sample Zephyr-based application that contains the logic\n * needed to control a microTVM-based model via the UART. This is only\n * intended to be a demonstration, since typically you will want to incorporate\n * this logic into your own application.\n */\n#include <drivers/gpio.h>\n#include <drivers/uart.h>\n#include <fatal.h>\n#include <kernel.h>\n#include <random/rand32.h>\n#include <stdio.h>\n#include <sys/printk.h>\n#include <sys/reboot.h>\n#include <sys/ring_buffer.h>\n#include <timing/timing.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/microtvm_rpc_server.h>\n#include <unistd.h>\n#include <zephyr.h>\n\n#ifdef FVP\n#include \"fvp/semihost.h\"\n#endif\n\n#ifdef CONFIG_ARCH_POSIX\n#include \"posix_board_if.h\"\n#endif\n\n#include \"crt_config.h\"\n\nstatic const struct device* tvm_uart;\n\n#ifdef CONFIG_LED\n#define LED0_NODE DT_ALIAS(led0)\n#define LED0 DT_GPIO_LABEL(LED0_NODE, gpios)\n#define LED0_PIN DT_GPIO_PIN(LED0_NODE, gpios)\n#define LED0_FLAGS DT_GPIO_FLAGS(LED0_NODE, gpios)\nstatic const struct device* led0_pin;\n#endif  // CONFIG_LED\n\nstatic size_t g_num_bytes_requested = 0;\nstatic size_t g_num_bytes_written = 0;\nstatic size_t g_num_bytes_in_rx_buffer = 0;\n\n// Called by TVM to write serial data to the UART.\nssize_t uart_write(void* unused_context, const uint8_t* data, size_t size) {\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 1);\n#endif\n  g_num_bytes_requested += size;\n\n  for (size_t i = 0; i < size; i++) {\n    uart_poll_out(tvm_uart, data[i]);\n    g_num_bytes_written++;\n  }\n\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 0);\n#endif\n\n  return size;\n}\n\nssize_t serial_write(void* unused_context, const uint8_t* data, size_t size) {\n#ifdef FVP\n  return semihost_write(unused_context, data, size);\n#else\n  return uart_write(unused_context, data, size);\n#endif\n}\n\n// This is invoked by Zephyr from an exception handler, which will be invoked\n// if the device crashes. Here, we turn on the LED and spin.\nvoid k_sys_fatal_error_handler(unsigned int reason, const z_arch_esf_t* esf) {\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 1);\n#endif\n  for (;;)\n    ;\n}\n\n// Called by TVM when a message needs to be formatted.\nsize_t TVMPlatformFormatMessage(char* out_buf, size_t out_buf_size_bytes, const char* fmt,\n                                va_list args) {\n  return vsnprintk(out_buf, out_buf_size_bytes, fmt, args);\n}\n\n// Called by TVM when an internal invariant is violated, and execution cannot continue.\nvoid TVMPlatformAbort(tvm_crt_error_t error) {\n  TVMLogf(\"TVMError: 0x%x\", error);\n  sys_reboot(SYS_REBOOT_COLD);\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 1);\n#endif\n  for (;;)\n    ;\n}\n\n// Called by TVM to generate random data.\ntvm_crt_error_t TVMPlatformGenerateRandom(uint8_t* buffer, size_t num_bytes) {\n  uint32_t random;  // one unit of random data.\n\n  // Fill parts of `buffer` which are as large as `random`.\n  size_t num_full_blocks = num_bytes / sizeof(random);\n  for (int i = 0; i < num_full_blocks; ++i) {\n    random = sys_rand32_get();\n    memcpy(&buffer[i * sizeof(random)], &random, sizeof(random));\n  }\n\n  // Fill any leftover tail which is smaller than `random`.\n  size_t num_tail_bytes = num_bytes % sizeof(random);\n  if (num_tail_bytes > 0) {\n    random = sys_rand32_get();\n    memcpy(&buffer[num_bytes - num_tail_bytes], &random, num_tail_bytes);\n  }\n  return kTvmErrorNoError;\n}\n\n// Heap for use by TVMPlatformMemoryAllocate.\nK_HEAP_DEFINE(tvm_heap, HEAP_SIZE_BYTES);\n\n// Called by TVM to allocate memory.\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  *out_ptr = k_heap_alloc(&tvm_heap, num_bytes, K_NO_WAIT);\n  return (*out_ptr == NULL) ? kTvmErrorPlatformNoMemory : kTvmErrorNoError;\n}\n\n// Called by TVM to deallocate memory.\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  k_heap_free(&tvm_heap, ptr);\n  return kTvmErrorNoError;\n}\n\nvolatile timing_t g_microtvm_start_time, g_microtvm_end_time;\nint g_microtvm_timer_running = 0;\n\n// Called to start system timer.\ntvm_crt_error_t TVMPlatformTimerStart() {\n  if (g_microtvm_timer_running) {\n    TVMLogf(\"timer already running\");\n    return kTvmErrorPlatformTimerBadState;\n  }\n\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 1);\n#endif\n  g_microtvm_start_time = timing_counter_get();\n  g_microtvm_timer_running = 1;\n  return kTvmErrorNoError;\n}\n\n// Called to stop system timer.\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds) {\n  if (!g_microtvm_timer_running) {\n    TVMLogf(\"timer not running\");\n    return kTvmErrorSystemErrorMask | 2;\n  }\n\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 0);\n#endif\n\n  g_microtvm_end_time = timing_counter_get();\n  uint64_t cycles = timing_cycles_get(&g_microtvm_start_time, &g_microtvm_end_time);\n  uint64_t ns_spent = timing_cycles_to_ns(cycles);\n  *elapsed_time_seconds = ns_spent / (double)1e9;\n  g_microtvm_timer_running = 0;\n  return kTvmErrorNoError;\n}\n\n// Ring buffer used to store data read from the UART on rx interrupt.\n// This ring buffer size is only required for testing with QEMU and not for physical hardware.\n#define RING_BUF_SIZE_BYTES (TVM_CRT_MAX_PACKET_SIZE_BYTES + 100)\nRING_BUF_ITEM_DECLARE_SIZE(uart_rx_rbuf, RING_BUF_SIZE_BYTES);\n\n// UART interrupt callback.\nvoid uart_irq_cb(const struct device* dev, void* user_data) {\n  uart_irq_update(dev);\n  if (uart_irq_is_pending(dev)) {\n    struct ring_buf* rbuf = (struct ring_buf*)user_data;\n    if (uart_irq_rx_ready(dev) != 0) {\n      uint8_t* data;\n      uint32_t size;\n      size = ring_buf_put_claim(rbuf, &data, RING_BUF_SIZE_BYTES);\n      int rx_size = uart_fifo_read(dev, data, size);\n      // Write it into the ring buffer.\n      g_num_bytes_in_rx_buffer += rx_size;\n\n      if (g_num_bytes_in_rx_buffer > RING_BUF_SIZE_BYTES) {\n        TVMPlatformAbort((tvm_crt_error_t)0xbeef3);\n      }\n\n      if (rx_size < 0) {\n        TVMPlatformAbort((tvm_crt_error_t)0xbeef1);\n      }\n\n      int err = ring_buf_put_finish(rbuf, rx_size);\n      if (err != 0) {\n        TVMPlatformAbort((tvm_crt_error_t)0xbeef2);\n      }\n      // CHECK_EQ(bytes_read, bytes_written, \"bytes_read: %d; bytes_written: %d\", bytes_read,\n      // bytes_written);\n    }\n  }\n}\n\n// Used to initialize the UART receiver.\nvoid uart_rx_init(struct ring_buf* rbuf, const struct device* dev) {\n  uart_irq_callback_user_data_set(dev, uart_irq_cb, (void*)rbuf);\n  uart_irq_rx_enable(dev);\n}\n\n// The main function of this application.\nextern void __stdout_hook_install(int (*hook)(int));\nvoid main(void) {\n#ifdef CONFIG_LED\n  int ret;\n  led0_pin = device_get_binding(LED0);\n  if (led0_pin == NULL) {\n    for (;;)\n      ;\n  }\n  ret = gpio_pin_configure(led0_pin, LED0_PIN, GPIO_OUTPUT_ACTIVE | LED0_FLAGS);\n  if (ret < 0) {\n    TVMPlatformAbort((tvm_crt_error_t)0xbeef4);\n  }\n  gpio_pin_set(led0_pin, LED0_PIN, 1);\n#endif\n\n  // Claim console device.\n  tvm_uart = device_get_binding(DT_LABEL(DT_CHOSEN(zephyr_console)));\n  uart_rx_init(&uart_rx_rbuf, tvm_uart);\n\n  // Initialize system timing. We could stop and start it every time, but we'll\n  // be using it enough we should just keep it enabled.\n  timing_init();\n  timing_start();\n\n#ifdef FVP\n  init_semihosting();\n  // send some dummy log to speed up the initialization\n  for (int i = 0; i < 100; ++i) {\n    uart_write(NULL, \"dummy log...\\n\", 13);\n  }\n  uart_write(NULL, \"microTVM Zephyr runtime - running\\n\", 34);\n#endif\n\n  // Initialize microTVM RPC server, which will receive commands from the UART and execute them.\n  microtvm_rpc_server_t server = MicroTVMRpcServerInit(serial_write, NULL);\n  TVMLogf(\"microTVM Zephyr runtime - running\");\n\n#ifdef CONFIG_LED\n  gpio_pin_set(led0_pin, LED0_PIN, 0);\n#endif\n\n  // The main application loop. We continuously read commands from the UART\n  // and dispatch them to MicroTVMRpcServerLoop().\n  while (true) {\n#ifdef FVP\n    uint8_t data[128];\n    uint32_t bytes_read = semihost_read(data, 128);\n#else\n    uint8_t* data;\n    unsigned int key = irq_lock();\n    uint32_t bytes_read = ring_buf_get_claim(&uart_rx_rbuf, &data, RING_BUF_SIZE_BYTES);\n#endif\n    if (bytes_read > 0) {\n      uint8_t* ptr = data;\n      size_t bytes_remaining = bytes_read;\n      while (bytes_remaining > 0) {\n        // Pass the received bytes to the RPC server.\n        tvm_crt_error_t err = MicroTVMRpcServerLoop(server, &ptr, &bytes_remaining);\n        if (err != kTvmErrorNoError && err != kTvmErrorFramingShortPacket) {\n          TVMPlatformAbort(err);\n        }\n#ifdef FVP\n      }\n    }\n#else\n        g_num_bytes_in_rx_buffer -= bytes_read;\n        if (g_num_bytes_written != 0 || g_num_bytes_requested != 0) {\n          if (g_num_bytes_written != g_num_bytes_requested) {\n            TVMPlatformAbort((tvm_crt_error_t)0xbeef5);\n          }\n          g_num_bytes_written = 0;\n          g_num_bytes_requested = 0;\n        }\n      }\n      int err = ring_buf_get_finish(&uart_rx_rbuf, bytes_read);\n      if (err != 0) {\n        TVMPlatformAbort((tvm_crt_error_t)0xbeef6);\n      }\n    }\n    irq_unlock(key);\n#endif\n  }\n\n#ifdef CONFIG_ARCH_POSIX\n  posix_exit(0);\n#endif\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr_cmsisnn/include/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/crt_config.h\n * \\brief CRT configuration for demo app.\n */\n#ifndef TVM_RUNTIME_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Support low-level debugging in MISRA-C runtime */\n#define TVM_CRT_DEBUG 0\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\"\n */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 512\n\n#endif  // TVM_RUNTIME_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr_cmsisnn/model/convert_input.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pathlib\nimport sys\nimport numpy as np\n\n\ndef create_file(name, prefix, tensor_name, tensor_data, output_path):\n    \"\"\"\n    This function generates a header file containing the data from the numpy array provided.\n    \"\"\"\n    file_path = pathlib.Path(f\"{output_path}/\" + name).resolve()\n    # Create header file with npy_data as a C array\n    raw_path = file_path.with_suffix(\".c\").resolve()\n    with open(raw_path, \"w\") as header_file:\n        header_file.write(\n            \"#include <stddef.h>\\n\"\n            \"#include <stdint.h>\\n\"\n            f\"const size_t {tensor_name}_len = {tensor_data.size};\\n\"\n            f\"{prefix} float {tensor_name}_storage[] = \"\n        )\n        header_file.write(\"{\")\n        for i in np.ndindex(tensor_data.shape):\n            header_file.write(f\"{tensor_data[i]}, \")\n        header_file.write(\"};\\n\\n\")\n\n\ndef create_files(input_file, output_dir):\n    \"\"\"\n    This function generates C files for the input and output arrays required to run inferences\n    \"\"\"\n    # Create out folder\n    os.makedirs(output_dir, exist_ok=True)\n\n    # Create input header file\n    input_data = np.loadtxt(input_file)\n    create_file(\"inputs\", \"const\", \"input\", input_data, output_dir)\n\n    # Create output header file\n    output_data = np.zeros([12], np.float32)\n    create_file(\n        \"outputs\",\n        \"\",\n        \"output\",\n        output_data,\n        output_dir,\n    )\n\n\nif __name__ == \"__main__\":\n    create_files(sys.argv[1], sys.argv[2])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr_cmsisnn/model/convert_labels.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pathlib\nimport sys\n\n\ndef create_labels_header(labels_file, output_path):\n    \"\"\"\n    This function generates a header file containing the ImageNet labels as an array of strings\n    \"\"\"\n    labels_path = pathlib.Path(labels_file).resolve()\n    file_path = pathlib.Path(f\"{output_path}/labels.c\").resolve()\n\n    with open(labels_path) as f:\n        labels = f.readlines()\n\n    with open(file_path, \"w\") as header_file:\n        header_file.write(f\"char* labels[] = {{\")\n\n        for _, label in enumerate(labels):\n            header_file.write(f'\"{label.rstrip()}\",')\n\n        header_file.write(\"};\\n\")\n\n\nif __name__ == \"__main__\":\n    create_labels_header(sys.argv[1], sys.argv[2])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/microtvm/zephyr_cmsisnn/src/main.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/printk.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/stack_allocator.h>\n#include <zephyr.h>\n\n#include \"tvmgen_default.h\"\n\nextern char* labels[12];\nextern float input_storage[490];\nextern float output_storage[12];\n\nextern const size_t output_len;\n\nstatic uint8_t __attribute__((aligned(TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)))\ng_crt_workspace[TVMGEN_DEFAULT_WORKSPACE_SIZE];\ntvm_workspace_t app_workspace;\n\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stderr, msg, args);\n  va_end(args);\n}\n\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t error_code) {\n  fprintf(stderr, \"TVMPlatformAbort: %d\\n\", error_code);\n  exit(-1);\n}\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n  uintptr_t ret = StackMemoryManager_Allocate(&app_workspace, num_bytes, out_ptr);\n  return ret;\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  return StackMemoryManager_Free(&app_workspace, ptr);\n}\n\nvoid main(void) {\n  StackMemoryManager_Init(&app_workspace, g_crt_workspace, TVMGEN_DEFAULT_WORKSPACE_SIZE);\n\n  struct tvmgen_default_inputs inputs = {.input = input_storage};\n  struct tvmgen_default_outputs outputs = {.Identity = output_storage};\n\n  if (tvmgen_default_run(&inputs, &outputs) != 0) {\n    printk(\"Model run failed\\n\");\n    exit(-1);\n  }\n\n  // Calculate index of max value\n  float max_value = 0.0;\n  size_t max_index = -1;\n  for (unsigned int i = 0; i < output_len; ++i) {\n    if (output_storage[i] > max_value) {\n      max_value = output_storage[i];\n      max_index = i;\n    }\n  }\n  printk(\"The word is '%s'!\\n\", labels[max_index]);\n  exit(0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_as_torch.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for tvm torch module\"\"\"\nimport tempfile\n\nimport numpy as np\n\nimport torch\nimport torch.nn\n\nimport tvm\nfrom tvm.target.target import Target\nimport tvm.testing\nfrom tvm.contrib.torch import as_torch\nfrom tvm.script import tir as T\n\n\n@as_torch\ndef matmul(M: int, N: int, K: int, dtype: str):\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [M, K], dtype=dtype)\n        B = T.match_buffer(b, [N, K], dtype=dtype)\n        C = T.match_buffer(c, [M, N], dtype=dtype)\n        for i, j, k in T.grid(M, N, K):\n            with T.block():\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    return main\n\n\n@as_torch\n@tvm.script.ir_module\nclass ModuleGPU:\n    @T.prim_func\n    def main(A: T.Buffer[8, \"float32\"], B: T.Buffer[8, \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i_0 in T.thread_binding(2, thread=\"blockIdx.x\"):\n            for i_2 in T.thread_binding(2, thread=\"threadIdx.x\"):\n                for i_1 in T.serial(2):\n                    with T.block(\"B\"):\n                        vi = T.axis.spatial(8, i_0 * 4 + i_1 * 2 + i_2)\n                        T.reads(A[vi])\n                        T.writes(B[vi])\n                        B[vi] = A[vi] + T.float32(1)\n\n\n@as_torch\n@T.prim_func\ndef func_with_part_access_region(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    with T.block():\n        for i, j in T.grid(128, 128):\n            with T.block(\"s1\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[vi, vj])\n                B[vi, vj] = A[vi, vj] + T.float32(1)\n\n        for i, j in T.grid(128, 128):\n            with T.block(\"s2\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.writes(C[vi, vj])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\n@as_torch\n@tvm.script.ir_module\nclass MyModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle):\n        # We exchange data between function by handles, which are similar to pointer.\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # Create buffer from handles.\n        A = T.match_buffer(a, (8,), dtype=\"float32\")\n        B = T.match_buffer(b, (8,), dtype=\"float32\")\n        for i in range(8):\n            # A block is an abstraction for computation.\n            with T.block(\"B\"):\n                # Define a spatial block iterator and bind it to value i.\n                vi = T.axis.spatial(8, i)\n                B[vi] = A[vi] + 1.0\n\n\n@as_torch\n@T.prim_func\ndef loop_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i, ko in T.grid(128, 4):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i)\n                vk = T.axis.R(128, ko * 32 + ki)\n                T.reads([B[vi], A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@as_torch\ndef elementwise_with_root(M: int, N: int, dtype: str):\n    @T.prim_func\n    def f(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [M, N])\n        B = T.match_buffer(b, [M, N])\n        C = T.match_buffer(c, [M, N])\n\n        with T.block():\n            for i, j in T.grid(M, N):\n                with T.block(\"s1\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    B[vi, vj] = A[vi, vj] + T.float32(1)\n            for i, j in T.grid(M, N):\n                with T.block(\"s2\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    C[vi, vj] = B[vi, vj] + T.float32(1)\n\n    return f\n\n\nclass MinuesOnes(torch.nn.Module):\n    def __init__(self):\n        super(MinuesOnes, self).__init__()\n        self.engine = MyModule\n\n    def forward(self, *input):\n        self.engine.forward(*input)\n        return input[-1] - 1\n\n\ndef test_tvmscript_torch_matmul():\n    s1 = np.random.rand(128, 128).astype(\"float32\")\n    s2 = np.random.rand(128, 128).astype(\"float32\")\n    s3 = np.random.rand(128, 128).astype(\"float32\")\n\n    q1 = torch.from_numpy(s1)\n    q2 = torch.from_numpy(s2)\n    q3 = torch.from_numpy(s3)\n\n    numpy_result = np.matmul(s1, np.transpose(s2))\n\n    nn_module = matmul(128, 128, 128, \"float32\")\n\n    nn_module(q1, q2, q3)\n\n    tvm.testing.assert_allclose(q3.numpy(), numpy_result, atol=1e-5, rtol=1e-5)\n\n\ndef test_tvmscript_torch_decorator():\n    q1 = torch.arange(8).type(torch.float32)\n    q2 = torch.zeros((8,), dtype=torch.float32)\n\n    MyModule(q1, q2)\n\n    tvm.testing.assert_allclose(q2.numpy(), (q1 + 1).numpy(), atol=1e-5, rtol=1e-5)\n\n\ndef test_tvmscript_torch_gpu():\n    cuda0 = torch.device(\"cuda:0\")\n    q1 = torch.arange(8, device=cuda0).type(torch.float32)\n    q2 = torch.zeros((8,), dtype=torch.float32, device=cuda0)\n\n    with tempfile.NamedTemporaryFile(suffix=\".pt\") as tmp:\n        torch.save(ModuleGPU, tmp.name)\n        loaded_mod = torch.load(tmp.name)\n        loaded_mod(q1, q2)\n\n    tvm.testing.assert_allclose(q2.cpu().numpy(), (q1 + 1).cpu().numpy(), atol=1e-5, rtol=1e-5)\n\n\ndef test_torch_with_tvmscript():\n    ref_result = np.arange(8).astype(\"float32\")\n\n    q1 = torch.arange(8).type(torch.float32)\n    q2 = torch.zeros((8,), dtype=torch.float32)\n\n    nn_module = MinuesOnes()\n\n    ret = nn_module.forward(q1, q2)\n\n    tvm.testing.assert_allclose(ret.numpy(), ref_result, atol=1e-5, rtol=1e-5)\n\n\ndef test_tvmscript_torch_func_with_part_access_region():\n    a1 = torch.rand(128, 128)\n    a2 = torch.zeros(128, 128)\n    a3 = torch.zeros(128, 128)\n\n    result = a1 + 2\n\n    func_with_part_access_region.tune()\n    func_with_part_access_region(a1, a2, a3)\n\n    tvm.testing.assert_allclose(a3.numpy(), result.numpy(), atol=1e-5, rtol=1e-5)\n\n\ndef test_tvmscript_torch_loop_split():\n    x = torch.rand(128, 128).cuda()\n    y = torch.zeros(128).cuda()\n\n    result = torch.sum(x.cpu(), dim=1).numpy()\n\n    loop_split.tune(\n        \"nvidia/geforce-rtx-3070\",\n        max_trials_global=128,\n        strategy=\"replay-trace\",\n    )\n    loop_split(x, y)\n\n    tvm.testing.assert_allclose(y.cpu().numpy(), result, atol=1e-5, rtol=1e-5)\n\n\ndef test_tvmscript_torch_elementwise_with_root():\n    a1 = torch.rand(128, 128)\n    a2 = torch.zeros(128, 128)\n    a3 = torch.zeros(128, 128)\n\n    result = a1 + 2\n\n    func = elementwise_with_root(128, 128, \"float32\")\n    func.tune(\n        max_trials_global=128,\n        strategy=\"replay-trace\",\n    )\n    func(a1, a2, a3)\n\n    tvm.testing.assert_allclose(a3.numpy(), result.numpy(), atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_tvmscript_torch_matmul()\n    test_tvmscript_torch_decorator()\n    test_tvmscript_torch_gpu()\n    test_torch_with_tvmscript()\n    test_tvmscript_torch_func_with_part_access_region()\n    test_tvmscript_torch_loop_split()\n    test_tvmscript_torch_elementwise_with_root()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_boolean_tensor.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for boolean tensor support\"\"\"\nimport tempfile\n\nimport torch\n\nimport tvm\nimport tvm.testing\nfrom tvm.contrib.torch import as_torch, optimize_torch\nfrom tvm.script import tir as T\n\n\ndef negate(x):\n    return x.logical_not()\n\n\ndef sum_up_tensor(x):\n    return x.size(dim=0) - torch.sum(x.int())\n\n\ndef tensor_boolean_operation(x):\n    arr1 = (x + 0.3).floor().bool()\n    arr2 = (~((x + 0.7).int().bool())).bool()\n    ret = ((arr1 & arr2).byte() + 0.5).half()\n    return ~(ret.bool())\n\n\ndef test_bool_tensor_negate():\n    input = torch.ones(1, dtype=torch.bool)\n    optimized_negate = optimize_torch(\n        negate,\n        input,\n    )\n    with tempfile.NamedTemporaryFile(suffix=\".pt\") as tmp:\n        torch.save(optimized_negate, tmp.name)\n        loaded_mod = torch.load(tmp.name)\n        output = loaded_mod(negate(input))\n    tvm.testing.assert_allclose(input.numpy(), output.numpy(), atol=1e-5, rtol=1e-5)\n\n\ndef test_sum_up_tensor():\n    x = torch.randint(0, 2, (16,))\n    y = x.bool()\n    optimized_func = optimize_torch(\n        sum_up_tensor,\n        (y,),\n    )\n    ret1 = (x[x == 0]).size(dim=0)\n    ret2 = optimized_func(y).numpy()\n    tvm.testing.assert_allclose(ret1, ret2, atol=1e-5, rtol=1e-5)\n\n\ndef test_tensor_boolean_operation():\n    input = torch.rand(200)\n    model = optimize_torch(\n        tensor_boolean_operation,\n        input,\n    )\n    ret1 = tensor_boolean_operation(input)\n    ret2 = model(input)\n    tvm.testing.assert_allclose(ret1, ret2, atol=1e-5, rtol=1e-5)\n\n\n@as_torch\n@T.prim_func\ndef negate_tvmscript(\n    X: T.Buffer[(8, 8), \"bool\"],\n    Y: T.Buffer[(8, 8), \"float32\"],\n    Z: T.Buffer[(8, 8), \"bool\"],\n    U: T.Buffer[(8, 8), \"float32\"],\n) -> None:\n    for i, j in T.grid(8, 8):\n        with T.block():\n            if Y[i, j] > 0.0:\n                Z[i, j] = X[i, j]\n                U[i, j] = Y[i, j]\n            else:\n                Z[i, j] = not X[i, j]\n                U[i, j] = 0.0 - Y[i, j]\n\n\ndef negate_vanila(x, y):\n    z = torch.zeros(8, 8).bool()\n    for i in range(8):\n        for j in range(8):\n            if y[i, j] > 0:\n                z[i, j] = x[i, j]\n            else:\n                z[i, j] = ~x[i, j]\n    return z\n\n\ndef test_tvmscript_torch_decorator():\n    q1 = (torch.rand(8, 8) + 0.5).int().bool()\n    q2 = torch.rand(8, 8) - 0.5\n    q3 = torch.zeros(8, 8).bool()\n    q4 = torch.zeros(8, 8)\n\n    std1 = negate_vanila(q1, q2)\n    std2 = torch.abs(q2)\n\n    negate_tvmscript(q1, q2, q3, q4)\n\n    tvm.testing.assert_allclose(std1.numpy(), q3.numpy(), atol=1e-5, rtol=1e-5)\n    tvm.testing.assert_allclose(std2.numpy(), q4.numpy(), atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_tvmscript_torch_decorator()\n    test_bool_tensor_negate()\n    test_sum_up_tensor()\n    test_tensor_boolean_operation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_optimize_torch.py",
        "content": "# pylint: disable=missing-class-docstring\n#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for tvm torch module\"\"\"\nimport tempfile\n\nimport torch\nfrom torch.utils import benchmark\nfrom torchvision.models import resnet18\n\nimport tvm\nimport tvm.testing\nfrom tvm.contrib.torch import optimize_torch\nfrom tvm.meta_schedule import TuneConfig\n\n\ndef test_matmul_tuning_relay():\n    def matmul(x, w):\n        return torch.matmul(x, w)\n\n    x = torch.randn(15, 20)\n    w = torch.randn(20, 30)\n    example_inputs = (x, w)\n\n    rt_mod = optimize_torch(matmul, example_inputs)\n    torch_answer = torch.matmul(x, w).numpy()\n    tvm_answer = rt_mod(x, w).numpy()\n\n    tvm.testing.assert_allclose(torch_answer, tvm_answer, atol=1e-5, rtol=1e-5)\n\n\nclass InnerModel(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv = torch.nn.Conv2d(1, 20, 5)\n\n    def forward(self, x):\n        return torch.nn.functional.relu(self.conv(x))\n\n\nclass SimpleModel(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv = torch.nn.Conv2d(20, 20, 5)\n        self.relu = InnerModel()\n\n    def forward(self, x):\n        x = self.relu(x)\n        return torch.nn.functional.relu(self.conv(x))\n\n\ndef test_nested_module():\n    simple_module = SimpleModel()\n    example_input = torch.randn(20, 1, 10, 10)\n    optimized_module = optimize_torch(simple_module, example_input)\n    ret1 = simple_module(example_input).detach().numpy()\n    ret2 = optimized_module(example_input).detach().numpy()\n    tvm.testing.assert_allclose(ret1, ret2, atol=1e-5, rtol=1e-5)\n\n\ndef test_save_load_function():\n    def foo(x):\n        return 2 * x + 1\n\n    example_input = torch.rand(3)\n    opt_foo = optimize_torch(foo, example_input)\n    ret1 = opt_foo(example_input)\n    with tempfile.NamedTemporaryFile(suffix=\".pt\") as tmp:\n        torch.save(opt_foo, tmp.name)\n        loaded_mod = torch.load(tmp.name)\n        ret2 = loaded_mod(example_input)\n    tvm.testing.assert_allclose(ret1.numpy(), ret2.numpy(), atol=1e-5, rtol=1e-5)\n\n\nclass MyResNet18(torch.nn.Module):\n    def __init__(self, config, target=None):\n        super(MyResNet18, self).__init__()\n        self.means = torch.nn.Parameter(\n            torch.tensor([103.939, 116.779, 123.68]).resize_(1, 3, 1, 1)\n        ).cuda()\n        self.resnet = optimize_torch(resnet18(), [torch.rand(1, 3, 224, 224)], config, target)\n\n    def forward(self, input):\n        return self.resnet(input - self.means)\n\n\nclass JitModule(torch.nn.Module):\n    def __init__(self):\n        super(JitModule, self).__init__()\n        self.means = torch.nn.Parameter(\n            torch.tensor([103.939, 116.779, 123.68]).resize_(1, 3, 1, 1)\n        ).cuda()\n        self.resnet = torch.jit.optimize_for_inference(torch.jit.script(resnet18().cuda().eval()))\n\n    def forward(self, input):\n        return self.resnet(input - self.means)\n\n\n# default config for testing\nconfig = TuneConfig(\n    strategy=\"evolutionary\",\n    num_trials_per_iter=4,\n    max_trials_per_task=8,\n    max_trials_global=16,\n)\n\nif torch.cuda.is_available():\n    target_cuda = \"nvidia/geforce-rtx-3070\"\n    meta_module_resnet18 = MyResNet18(config, target_cuda)\n    jit_module_resnet18 = JitModule()\n\n\ndef compare_optimize_resnet18_to_torchscript():\n    results = []\n    for i in range(20):\n        test_input = torch.rand(1, 3, 224, 224).half().cuda()\n        sub_label = f\"[test {i}]\"\n        results.append(\n            benchmark.Timer(\n                stmt=\"meta_module_resnet18(test_input)\",\n                setup=\"from __main__ import meta_module_resnet18\",\n                globals={\"test_input\": test_input},\n                sub_label=sub_label,\n                description=\"tuning by meta\",\n            ).blocked_autorange()\n        )\n        results.append(\n            benchmark.Timer(\n                stmt=\"jit_module_resnet18(test_input)\",\n                setup=\"from __main__ import jit_module_resnet18\",\n                globals={\"test_input\": test_input},\n                sub_label=sub_label,\n                description=\"tuning by jit\",\n            ).blocked_autorange()\n        )\n    compare = benchmark.Compare(results)\n    compare.print()\n\n\nif __name__ == \"__main__\":\n    test_matmul_tuning_relay()\n    test_nested_module()\n    test_save_load_function()\n    if torch.cuda.is_available():\n        compare_optimize_resnet18_to_torchscript()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_torch_compile_cpu.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch module\"\"\"\nimport torch\nimport time\nimport tvm\nfrom tvm.contrib.torch import compile\n\n\nclass Model(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n\n    def forward(self, x: torch.Tensor):\n        return x * x\n\n\nmodel = Model()\nx = torch.rand([1, 3, 224, 224])\nmodel_jit = torch.jit.trace(model, x)\nprint(model_jit.graph)\n\nprint(\"run torchscript...\")\nfor i in range(20):\n    t = time.time()\n    model_jit(x)\n    print(time.time() - t)\n\n\noption = {\n    \"input_infos\": [\n        (\"x\", (1, 3, 224, 224)),\n    ],\n    \"default_dtype\": \"float16\",\n    \"export_dir\": \"pytorch_compiled\",\n    \"num_outputs\": 1,\n    \"tuning_n_trials\": 1,  # set zero to skip tuning\n    \"tuning_log_file\": \"tuning.log\",\n    \"target\": \"llvm\",\n    \"device\": tvm.cpu(),\n}\n\npytorch_tvm_module = compile(model_jit, option)\ntorch.jit.script(pytorch_tvm_module).save(\"model_tvm.pt\")\n\n\nprint(\"Run PyTorch...\")\nfor i in range(20):\n    t = time.time()\n    outputs = pytorch_tvm_module.forward([x.cpu()])\n    print(1000 * (time.time() - t))\nprint(outputs[0].shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_torch_compile_gpu.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch module\"\"\"\nimport torch\nimport time\nfrom torchvision.models import resnet50\nimport tvm\nfrom tvm.contrib.torch import compile\n\n\nmodel = resnet50().half().cuda()\nx = torch.rand([1, 3, 224, 224]).half().cuda()\nmodel_jit = torch.jit.trace(model, x)\nprint(model_jit.graph)\n\nprint(\"run torchscript...\")\nfor i in range(20):\n    t = time.time()\n    model_jit(x)\n    torch.cuda.synchronize()\n    print(time.time() - t)\n\n\noption = {\n    \"input_infos\": [\n        (\"x\", (1, 3, 224, 224)),\n    ],\n    \"default_dtype\": \"float16\",\n    \"export_dir\": \"pytorch_compiled\",\n    \"num_outputs\": 1,\n    \"tuning_n_trials\": 1,  # set zero to skip tuning\n    \"tuning_log_file\": \"tuning.log\",\n    \"target\": \"cuda\",\n    \"device\": tvm.cuda(0),\n}\n\npytorch_tvm_module = compile(model_jit, option)\ntorch.jit.script(pytorch_tvm_module).save(\"model_tvm.pt\")\n\n\nprint(\"Run PyTorch...\")\nfor i in range(20):\n    t = time.time()\n    outputs = pytorch_tvm_module.forward([x])\n    torch.cuda.synchronize()\n    print(1000 * (time.time() - t))\nprint(outputs[0].shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_torch_graph_module.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch module\"\"\"\nimport tempfile\nimport os\nimport logging\nimport torch\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te, relay\nimport tvm.contrib.torch\nfrom tvm.contrib import graph_runtime\n\nTVM_ASSETS = [\"mod.so\", \"graph.json\", \"params\"]\n\n\ndef test_use_pt_graph_module():\n    \"\"\"main test function\"\"\"\n\n    def build_export_graph(device):\n        \"\"\"relay build & export graph\"\"\"\n        x = relay.var(\"x\", shape=(10, 5))\n        y = relay.var(\"y\", shape=(1, 5))\n        z = relay.add(x, y)\n        z = relay.exp(z)\n        func = relay.Function([x, y], z)\n        x_data = np.random.rand(10, 5).astype(\"float32\")\n        y_data = np.random.rand(1, 5).astype(\"float32\")\n        params = {\"y\": y_data}\n\n        pt_device = torch.device(device)\n        if pt_device.type == \"cuda\":\n            target = \"cuda\"\n            ctx = tvm.cuda(pt_device.index)\n        else:\n            target = \"llvm\"\n            ctx = tvm.cpu(0)\n\n        graph, lib, params = relay.build(tvm.IRModule.from_expr(func), target=target, params=params)\n        mod = graph_runtime.create(graph, lib, device=ctx)\n        mod.set_input(**params)\n        mod.set_input(x=x_data)\n        mod.run()\n        res = mod.get_output(0).asnumpy()\n        ref_res = np.exp(y_data + x_data)\n        tvm.testing.assert_allclose(res, ref_res, atol=1e-5, rtol=1e-5)\n\n        # export to tempdir\n        export_dir = tempfile.mkdtemp(\"tvm_export\")\n        lib.export_library(os.path.join(export_dir, TVM_ASSETS[0]))\n        with open(os.path.join(export_dir, TVM_ASSETS[1]), \"w\") as fout:\n            fout.write(graph)\n        with open(os.path.join(export_dir, TVM_ASSETS[2]), \"wb\") as fout:\n            fout.write(relay.save_param_dict(params))\n\n        return export_dir\n\n    def test_pt_run(device, trace=True, to_device=None):\n        \"\"\"test add lib with Pytorch wrapper\"\"\"\n        print(\"\\n############## Test on device:\", device, \"#################\")\n        export_dir = build_export_graph(device)\n        engine = tvm.contrib.torch.GraphModule(num_inputs=2, num_outputs=1).to(device)\n\n        x = np.random.rand(10, 5).astype(\"float32\")\n        y = np.random.rand(1, 5).astype(\"float32\")\n\n        expect = np.exp(y + x)\n\n        def get_inputs_by_device(device):\n            inps = [torch.Tensor(x), torch.Tensor(y)]\n            if device == \"cpu\":\n                return inps\n            else:\n                device_type, device_id = device.split(\":\")\n                assert device_type == \"cuda\"\n                return [inp.cuda(int(device_id)) for inp in inps]\n\n        assets = [os.path.join(export_dir, i) for i in TVM_ASSETS]\n        engine.init((x.shape, y.shape), *assets)\n\n        outputs = engine.forward(get_inputs_by_device(device))\n        tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n\n        if trace:\n            print(\"\\n################ Test trace and load #################\")\n            scripted = torch.jit.script(engine)\n            scripted_dir = tempfile.mkdtemp(\"scripted\")\n            scripted_path = os.path.join(scripted_dir, \"model.pt\")\n            scripted.save(scripted_path)\n            loaded = torch.jit.load(scripted_path)\n            outputs = loaded.forward(get_inputs_by_device(device))\n            tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n            del scripted\n            del loaded\n\n        if to_device:\n            print(\n                \"\\n################ Test move from [{}] to [{}] #################\".format(\n                    device, to_device\n                )\n            )\n            engine = engine.to(to_device)\n            outputs = engine.forward(get_inputs_by_device(to_device))\n            tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n        del engine\n\n    test_pt_run(device=\"cuda:0\", trace=True, to_device=\"cuda:1\")\n    test_pt_run(device=\"cpu\", trace=True)\n\n\nif __name__ == \"__main__\":\n    test_use_pt_graph_module()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_torch_script.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch module\"\"\"\nimport os\nimport torch\nimport time\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tempfile\nfrom tvm.contrib.torch import PyTorchTVMModule, compile\n\n\nclass Model(torch.nn.Module):\n    def forward(self, x, y):\n        return torch.matmul(x, y.softmax(1))\n\n\nmodel = Model()\nmodel.cuda().half()\nx = torch.rand([1280, 2464, 4]).cuda().half()\ny = torch.rand([1280, 4, 1]).cuda().half()\nfor i in range(20):\n    t = time.time()\n    o = model(x, y)\n    torch.cuda.synchronize()\n    print(1000 * (time.time() - t))\nprint(o.shape)\n\n\nmodel_jit = torch.jit.script(model)\nprint(model_jit.graph)\ninput_shapes = [(\"x\", list(x.shape)), (\"y\", list(y.shape))]\ndtype = \"float16\"\nexport_dir = tempfile.mkdtemp(\"pytorch_compiled\")\nprint(\"tmp export_dir:\", export_dir)\n\n\nmod = PyTorchTVMModule()\nprint(\"Converting...\")\nmod.from_pytorch(model_jit, input_shapes, dtype)\n\nlog_file = os.path.join(export_dir, \"tuning.log\")\nif not os.path.exists(log_file):\n    print(\"Tuning...\")\n    mod.tune_tvm(log_file=log_file, n_trial=20)\n\nprint(\"Building...\")\ntvm_mod = mod.build_tvm(export_dir)\npytorch_mod = mod.build_pytorch_module(num_inputs=2, num_outputs=1)\n\n\n## Or you can load from a prebuilt tvm module\n# mod = PyTorchTVMModule()\n# tvm_mod = mod.load_tvm(export_dir)\n# pytorch_mod = mod.build_pytorch_module(num_inputs=2, num_outputs=1, input_infos=input_shapes)\n\n\nprint(\"Run TVM...\")\ntvm_x = tvm.nd.array(x.cpu().numpy().astype(dtype), device=tvm.gpu(0))\ntvm_y = tvm.nd.array(y.cpu().numpy().astype(dtype), device=tvm.gpu(0))\nfor i in range(20):\n    t = time.time()\n    tvm_mod.run(x=tvm_x, y=tvm_y)\n    print(1000 * (time.time() - t))\ntvm_output = tvm_mod.get_output(0)\nprint(tvm_output.shape)\n\n\nprint(\"Run PyTorch...\")\nfor i in range(20):\n    t = time.time()\n    outputs = pytorch_mod.forward([x, y])\n    torch.cuda.synchronize()\n    print(1000 * (time.time() - t))\nprint(outputs[0].shape)\n\n\nclass EnsembleModel(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.layer = torch.jit.script(pytorch_mod)\n\n    def forward(self, x, y, z) -> torch.Tensor:\n        if x > 1:\n            out = self.layer(y, z)[0]\n        else:\n            out = torch.ones([1280, 2464, 1])\n        return out\n\n\nprint(\"Exporting...\")\nscripted = torch.jit.script(EnsembleModel())\nprint(scripted.graph)\nscripted_path = os.path.join(export_dir, \"model_tvm.pt\")\nscripted.save(scripted_path)\n\n\n# print(o == outputs[0])\n# print(o - outputs[0])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_torch_vm_module.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch vm module\"\"\"\nimport tempfile\nimport os\nimport logging\nimport torch\nimport numpy as np\nimport tvm\nfrom tvm.contrib.torch.pytorch_tvm import TVM_ASSETS\nimport tvm.testing\nfrom tvm import te, relay\nimport tvm.contrib.torch\nfrom tvm.contrib import graph_runtime\n\nTVM_ASSETS = [\"mod.so\", \"code.ro\"]\n\n\ndef test_use_pt_vm_module():\n    \"\"\"main test function\"\"\"\n\n    def build_export_vm(device):\n        \"\"\"relay build & export graph\"\"\"\n        x = relay.var(\"x\", shape=(10, 5))\n        y = relay.var(\"y\", shape=(1, 5))\n        z = relay.add(x, y)\n        z = relay.exp(z)\n        func = relay.Function([x, y], z)\n        x_data = np.random.rand(10, 5).astype(\"float32\")\n        y_data = np.random.rand(1, 5).astype(\"float32\")\n\n        pt_device = torch.device(device)\n        if pt_device.type == \"cuda\":\n            target = \"cuda\"\n            ctx = tvm.cuda(pt_device.index)\n        else:\n            target = \"llvm\"\n            ctx = tvm.cpu(0)\n        exe = relay.vm.compile(tvm.IRModule.from_expr(func), target=target, params={})\n        code, lib = exe.save()\n        export_dir = tempfile.mkdtemp(\"tvm_export\")\n        # export to tempdir\n        lib.export_library(os.path.join(export_dir, TVM_ASSETS[0]))\n        with open(os.path.join(export_dir, TVM_ASSETS[1]), \"wb\") as fout:\n            fout.write(code)\n        vm = tvm.runtime.vm.VirtualMachine(exe, ctx)\n        res = vm.run(x_data, y_data)\n        ref_res = np.exp(y_data + x_data)\n        tvm.testing.assert_allclose(res.numpy(), ref_res, atol=1e-5, rtol=1e-5)\n        return export_dir\n\n    def test_pt_run(device, trace=True, to_device=None, inp_on_cuda=False):\n        \"\"\"test add lib with Pytorch wrapper\"\"\"\n        print(\"\\n############## Test on device:\", device, \"#################\")\n        export_dir = build_export_vm(device)\n        engine = tvm.contrib.torch.VMModule(num_inputs=2, num_outputs=1).to(device)\n\n        x = np.random.rand(10, 5).astype(\"float32\")\n        y = np.random.rand(1, 5).astype(\"float32\")\n\n        expect = np.exp(y + x)\n\n        def get_inputs_by_device(device):\n            inps = [torch.Tensor(x), torch.Tensor(y)]\n            if device == \"cpu\":\n                return inps\n            else:\n                device_type, device_id = device.split(\":\")\n                assert device_type == \"cuda\"\n                return [inp.cuda(int(device_id)) for inp in inps]\n\n        assets = [os.path.join(export_dir, i) for i in TVM_ASSETS]\n        engine.init((x.shape, y.shape), *assets)\n\n        outputs = engine.forward(get_inputs_by_device(device))\n        tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n\n        if trace:\n            print(\"\\n################ Test trace and load #################\")\n            scripted = torch.jit.script(engine)\n            scripted_dir = tempfile.mkdtemp(\"scripted\")\n            scripted_path = os.path.join(scripted_dir, \"model.pt\")\n            scripted.save(scripted_path)\n            loaded = torch.jit.load(scripted_path)\n            outputs = loaded.forward(get_inputs_by_device(device))\n            tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n            del scripted\n            del loaded\n\n        if to_device:\n            print(\n                \"\\n################ Test move from [{}] to [{}] #################\".format(\n                    device, to_device\n                )\n            )\n            engine = engine.to(to_device)\n            outputs = engine.forward(get_inputs_by_device(to_device))\n            tvm.testing.assert_allclose(outputs[0].cpu(), expect, atol=1e-5, rtol=1e-5)\n        del engine\n\n    test_pt_run(device=\"cuda:0\", trace=True, to_device=\"cuda:1\", inp_on_cuda=True)\n    test_pt_run(device=\"cpu\", trace=True, inp_on_cuda=False)\n\n\nif __name__ == \"__main__\":\n    test_use_pt_vm_module()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/pt_tvmdsoop/tests/test_trace_tvm_module.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for torch module\"\"\"\nimport torch\nimport time\nimport tvm\nfrom tvm.contrib.torch import compile, TraceTvmModule, pytorch_tvm\n\n\nclass Model(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n\n    def forward(self, x: torch.Tensor, y: torch.Tensor):\n        return x * y\n\n\nmodel = Model()\nx = torch.rand([1, 2, 3])\ny = torch.rand([1, 2, 3])\nmodel_jit = torch.jit.script(model)\n\noption = {\n    \"input_infos\": [(\"x\", (1, 2, 3)), (\"y\", (1, 2, 3))],\n    \"default_dtype\": \"float32\",\n    \"export_dir\": \"pytorch_compiled\",\n    \"num_outputs\": 1,\n    \"tuning_n_trials\": 0,  # set zero to skip tuning\n    \"tuning_log_file\": \"tuning.log\",\n    \"target\": \"llvm\",\n    \"device\": tvm.cpu(),\n}\n\n# use TraceTvmModule to convert List[Tensor] input/output\n# to tuple of Tensors\npytorch_tvm_module = compile(model_jit, option)\nscripted = torch.jit.script(pytorch_tvm_module)\ntraced = torch.jit.trace(TraceTvmModule(scripted), (x, y))\n\nres_traced = traced.forward(x, y)\nres_expected = pytorch_tvm_module.forward([x, y])[0]\ntvm.testing.assert_allclose(res_traced, res_expected)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/sgx/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::process::Command;\n\nmacro_rules! mf_dir {\n    ($p:literal) => {\n        concat!(env!(\"CARGO_MANIFEST_DIR\"), $p)\n    };\n}\n\nfn main() {\n    let out_dir = std::env::var(\"OUT_DIR\").unwrap();\n\n    let build_output = Command::new(mf_dir!(\"/src/build_model.py\"))\n        .arg(&out_dir)\n        .env(\n            \"PYTHONPATH\",\n            concat!(\n                mf_dir!(\"/../../python\"),\n                \":\",\n                mf_dir!(\"/../../nnvm/python\")\n            ),\n        )\n        .output()\n        .expect(\"Failed to build model\");\n    assert!(\n        [\"model.o\", \"graph.json\", \"params.bin\"]\n            .iter()\n            .all(|f| { std::path::Path::new(&format!(\"{}/{}\", out_dir, f)).exists() }),\n        \"Could not build tvm lib: STDOUT:\\n\\n{}\\n\\nSTDERR\\n\\n{}\",\n        String::from_utf8(build_output.stdout).unwrap().trim(),\n        String::from_utf8(build_output.stderr).unwrap().trim()\n    );\n\n    let sysroot_output = Command::new(\"rustc\")\n        .args(&[\"--print\", \"sysroot\"])\n        .output()\n        .expect(\"Failed to get sysroot\");\n    let sysroot = String::from_utf8(sysroot_output.stdout).unwrap();\n    let sysroot = sysroot.trim();\n    let mut llvm_tools_path = std::path::PathBuf::from(&sysroot);\n    llvm_tools_path.push(\"lib/rustlib/x86_64-unknown-linux-gnu/bin\");\n\n    Command::new(\"rustup\")\n        .args(&[\"component\", \"add\", \"llvm-tools-preview\"])\n        .output()\n        .expect(\"failed to install llvm tools\");\n\n    std::process::Command::new(llvm_tools_path.join(\"llvm-objcopy\"))\n        .arg(\"--globalize-symbol=__tvm_module_startup\")\n        .arg(\"--remove-section=.ctors\")\n        .arg(&format!(\"{}/model.o\", out_dir))\n        .output()\n        .expect(\"gould not gloablize startup function\");\n\n    std::process::Command::new(llvm_tools_path.join(\"llvm-ar\"))\n        .arg(\"rcs\")\n        .arg(&format!(\"{}/libmodel.a\", out_dir))\n        .arg(&format!(\"{}/model.o\", out_dir))\n        .output()\n        .expect(\"failed to package model archive\");\n\n    println!(\"cargo:rustc-link-lib=static=model\");\n    println!(\"cargo:rustc-link-search=native={}\", out_dir);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/sgx/read_results.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport struct\nimport sys\n\nimport numpy as np\n\n\ndef float_bytes(l):\n    for i in range(0, len(l), 4):\n        yield l[i : i + 4]\n\n\nfloats = [struct.unpack(\"f\", f)[0] for f in float_bytes(sys.stdin.buffer.read())]\nprint(np.array(floats))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/sgx/src/build_model.py",
        "content": "#!/usr/bin/python3\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Creates a simple TVM modules.\"\"\"\n\nimport os\nfrom os import path as osp\nimport sys\n\nfrom tvm import relay, runtime\nfrom tvm.relay import testing\nimport tvm\nfrom tvm import te\n\n\ndef main():\n    dshape = (1, 28, 28)\n    net, params = relay.testing.mlp.get_workload(batch_size=dshape[0], dtype=\"float32\")\n\n    dshape = (1, 3, 224, 224)\n    net, params = relay.testing.resnet.get_workload(\n        layers=18, batch_size=dshape[0], image_shape=dshape[1:]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(\n            net,\n            \"llvm\",\n            params=params,\n            runtime=tvm.relay.backend.Runtime(\"cpp\", {\"system-lib\": True}),\n        )\n\n    build_dir = osp.abspath(sys.argv[1])\n    if not osp.isdir(build_dir):\n        os.makedirs(build_dir, exist_ok=True)\n\n    lib.save(osp.join(build_dir, \"model.o\"))\n    with open(osp.join(build_dir, \"graph.json\"), \"w\") as f_graph_json:\n        f_graph_json.write(graph)\n        with open(osp.join(build_dir, \"params.bin\"), \"wb\") as f_params:\n            f_params.write(runtime.save_param_dict(params))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/sgx/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nextern crate tvm_runtime;\n\nuse std::{\n    convert::TryFrom as _,\n    io::{Read as _, Write as _},\n};\n\nfn main() {\n    let syslib = tvm_runtime::SystemLibModule::default();\n\n    let graph_json = include_str!(concat!(env!(\"OUT_DIR\"), \"/graph.json\"));\n    let params_bytes = include_bytes!(concat!(env!(\"OUT_DIR\"), \"/params.bin\"));\n    let params = tvm_runtime::load_param_dict(params_bytes).unwrap();\n\n    let graph = tvm_runtime::Graph::try_from(graph_json).unwrap();\n    let mut exec = tvm_runtime::GraphExecutor::new(graph, &syslib).unwrap();\n    exec.load_params(params);\n\n    let listener = std::net::TcpListener::bind(\"127.0.0.1:4242\").unwrap();\n    for stream in listener.incoming() {\n        let mut stream = stream.unwrap();\n        if let Err(_) =\n            stream.read_exact(exec.get_input(\"data\").unwrap().data().view().as_mut_slice())\n        {\n            continue;\n        }\n        exec.run();\n        if let Err(_) = stream.write_all(exec.get_output(0).unwrap().data().as_slice()) {\n            continue;\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/tf_tvmdsoop/tests/test_tfop_module.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test script for tf op module\"\"\"\nimport tempfile\nimport os\nimport logging\nimport tensorflow as tf\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import tf_op\n\n\ndef test_use_tvmdso_op():\n    \"\"\"main test function\"\"\"\n\n    def export_cpu_add_lib():\n        \"\"\"create cpu add op lib\"\"\"\n        n = te.var(\"n\")\n        ph_a = te.placeholder((n,), name=\"ph_a\")\n        ph_b = te.placeholder((n,), name=\"ph_b\")\n        ph_c = te.compute(ph_a.shape, lambda i: ph_a[i] + ph_b[i], name=\"ph_c\")\n        sched = te.create_schedule(ph_c.op)\n        fadd_dylib = tvm.build(sched, [ph_a, ph_b, ph_c], \"c\", name=\"vector_add\")\n        lib_path = tempfile.mktemp(\"tvm_add_dll.so\")\n        fadd_dylib.export_library(lib_path)\n        return lib_path\n\n    def export_gpu_add_lib():\n        \"\"\"create gpu add op lib\"\"\"\n        n = te.var(\"n\")\n        ph_a = te.placeholder((n,), name=\"ph_a\")\n        ph_b = te.placeholder((n,), name=\"ph_b\")\n        ph_c = te.compute(ph_a.shape, lambda i: ph_a[i] + ph_b[i], name=\"ph_c\")\n        sched = te.create_schedule(ph_c.op)\n        b_axis, t_axis = sched[ph_c].split(ph_c.op.axis[0], factor=64)\n        sched[ph_c].bind(b_axis, te.thread_axis(\"blockIdx.x\"))\n        sched[ph_c].bind(t_axis, te.thread_axis(\"threadIdx.x\"))\n        fadd_dylib = tvm.build(sched, [ph_a, ph_b, ph_c], \"cuda\", name=\"vector_add\")\n        lib_path = tempfile.mktemp(\"tvm_add_cuda_dll.so\")\n        fadd_dylib.export_library(lib_path)\n        return lib_path\n\n    def test_add(session, lib_path, tf_device):\n        \"\"\"test add lib with TensorFlow wrapper\"\"\"\n        module = tf_op.OpModule(lib_path)\n\n        left = tf.placeholder(\"float32\", shape=[4])\n        right = tf.placeholder(\"float32\", shape=[4])\n\n        feed_dict = {left: [1.0, 2.0, 3.0, 4.0], right: [5.0, 6.0, 7.0, 8.0]}\n        expect = np.asarray([6.0, 8.0, 10.0, 12.0])\n\n        add1 = module.func(\"vector_add\", output_shape=[4], output_dtype=\"float\")\n        add2 = module.func(\"vector_add\", output_shape=tf.shape(left), output_dtype=\"float\")\n        add3 = module.func(\"vector_add\", output_shape=[tf.shape(left)[0]], output_dtype=\"float\")\n\n        with tf.device(tf_device):\n            output1 = session.run(add1(left, right), feed_dict)\n            np.testing.assert_equal(output1, expect)\n\n            output2 = session.run(add2(left, right), feed_dict)\n            np.testing.assert_equal(output2, expect)\n\n            output3 = session.run(add3(left, right), feed_dict)\n            np.testing.assert_equal(output3, expect)\n\n    def cpu_test(session):\n        \"\"\"test function for cpu\"\"\"\n        cpu_lib = None\n        try:\n            cpu_lib = export_cpu_add_lib()\n            test_add(session, cpu_lib, \"/cpu:0\")\n        finally:\n            if cpu_lib is not None:\n                os.remove(cpu_lib)\n\n    def gpu_test(session):\n        \"\"\"test function for gpu\"\"\"\n        gpu_lib = None\n        try:\n            gpu_lib = export_gpu_add_lib()\n            test_add(session, gpu_lib, \"/gpu:0\")\n        finally:\n            if gpu_lib is not None:\n                os.remove(gpu_lib)\n\n    with tf.Session() as session:\n        if tvm.runtime.enabled(\"cpu\"):\n            logging.info(\"Test TensorFlow op on cpu kernel\")\n            cpu_test(session)\n        if tvm.runtime.enabled(\"gpu\"):\n            logging.info(\"Test TensorFlow op on gpu kernel\")\n            gpu_test(session)\n\n\nif __name__ == \"__main__\":\n    test_use_tvmdso_op()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/broadcast/test_broadcast_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import nvcc\nimport numpy as np\n\nfrom tvm import topi\n\n\nTASK = \"reduce_map\"\nUSE_MANUAL_CODE = False\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef test_broadcast_to(in_shape, out_shape):\n    global TASK\n    TASK = (\n        \"bcast_to_i\"\n        + \"_\".join([str(ele) for ele in in_shape])\n        + \"o\"\n        + \"_\".join([str(ele) for ele in out_shape])\n    )\n    # Build the logic and compile the function\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.broadcast_to(A, out_shape)\n    s = topi.cuda.schedule_broadcast(B)\n    fcuda = tvm.build(s, [A, B], \"cuda\", name=\"broadcast_to\")\n\n    data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n    out_npy = np.broadcast_to(data_npy, out_shape)\n\n    data_nd = tvm.nd.array(data_npy, tvm.cuda())\n    out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), tvm.cuda())\n    for _ in range(2):\n        fcuda(data_nd, out_nd)\n    tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n\ndef test_broadcast_binary_op(lhs_shape, rhs_shape, typ=\"add\"):\n    global TASK\n    TASK = (\n        \"bcast_binary_\"\n        + typ\n        + \"_lhs\"\n        + \"_\".join([str(ele) for ele in lhs_shape])\n        + \"rhs\"\n        + \"_\".join([str(ele) for ele in rhs_shape])\n    )\n    A = te.placeholder(shape=lhs_shape, name=\"A\")\n    B = te.placeholder(shape=rhs_shape, name=\"B\")\n    if typ == \"add\":\n        C = topi.broadcast_add(A, B)\n    elif typ == \"sub\":\n        C = topi.broadcast_sub(A, B)\n    elif typ == \"div\":\n        C = topi.broadcast_div(A, B)\n    elif typ == \"mul\":\n        C = topi.broadcast_mul(A, B)\n    elif typ == \"maximum\":\n        C = topi.broadcast_maximum(A, B)\n    elif typ == \"minimum\":\n        C = topi.broadcast_minimum(A, B)\n    else:\n        raise NotImplementedError\n    s = topi.cuda.schedule_broadcast(C)\n    fcuda = tvm.build(s, [A, B, C], \"cuda\", name=\"broadcast_binary\" + \"_\" + typ)\n\n    lhs_npy = np.random.uniform(size=lhs_shape).astype(A.dtype)\n    rhs_npy = np.random.uniform(size=rhs_shape).astype(A.dtype)\n    if typ == \"add\":\n        out_npy = lhs_npy + rhs_npy\n    elif typ == \"sub\":\n        out_npy = lhs_npy - rhs_npy\n    elif typ == \"div\":\n        rhs_npy = np.abs(rhs_npy) + 0.001\n        out_npy = lhs_npy / rhs_npy\n    elif typ == \"mul\":\n        out_npy = lhs_npy * rhs_npy\n    elif typ == \"maximum\":\n        out_npy = np.maximum(lhs_npy, rhs_npy)\n    elif typ == \"minimum\":\n        out_npy = np.minimum(lhs_npy, rhs_npy)\n    lhs_nd = tvm.nd.array(lhs_npy, tvm.cuda())\n    rhs_nd = tvm.nd.array(rhs_npy, tvm.cuda())\n    out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), tvm.cuda())\n    for _ in range(2):\n        fcuda(lhs_nd, rhs_nd, out_nd)\n    tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n\nif __name__ == \"__main__\":\n    test_broadcast_to((1,), (10,))\n    test_broadcast_to((1, 1, 5, 4), (3, 4, 4, 4, 5, 4))\n    test_broadcast_to((1, 128, 1, 32), (64, 128, 64, 32))\n    test_broadcast_binary_op((5, 2, 3), (2, 1), typ=\"add\")\n    test_broadcast_binary_op((5, 64, 128), (2, 5, 64, 1), typ=\"mul\")\n    test_broadcast_binary_op((2, 3, 1, 32), (64, 32), typ=\"div\")\n    test_broadcast_binary_op((1, 32), (64, 32), typ=\"sub\")\n    test_broadcast_binary_op((32,), (64, 32), typ=\"maximum\")\n    test_broadcast_binary_op((1, 2, 2, 1, 32), (64, 32), typ=\"minimum\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/conv/depthwise_conv2d_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom scipy import signal\nfrom tvm.contrib import nvcc\n\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.cuda.depthwise_conv2d import (\n    schedule_depthwise_conv2d_nchw,\n    schedule_depthwise_conv2d_nhwc,\n)\n\nTASK = \"depthwise_conv2d\"\nUSE_MANUAL_CODE = False\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef test_depthwise_conv2d_nchw():\n    \"\"\"You may test different settings.\"\"\"\n    batch = 1\n    in_channel = 256\n    in_height = 96\n    in_width = 96\n\n    filter_channel = in_channel\n    channel_multiplier = 1\n    filter_height = 3\n    filter_width = 3\n\n    stride_h = 1\n    stride_w = 1\n\n    padding = \"SAME\"  # or 'VALID'\n\n    # Placeholder\n    Input = te.placeholder((batch, in_channel, in_height, in_width), name=\"Input\")\n    Filter = te.placeholder(\n        (filter_channel, channel_multiplier, filter_height, filter_width), name=\"Filter\"\n    )\n    Stride = [stride_h, stride_w]\n    Scale = te.placeholder((in_channel * channel_multiplier,), name=\"Scale\")\n    Shift = te.placeholder((in_channel * channel_multiplier,), name=\"Shift\")\n    # Declare\n    DepthwiseConv2d = topi.nn.depthwise_conv2d_nchw(Input, Filter, Stride, padding)\n    ScaleShift = topi.nn.scale_shift_nchw(DepthwiseConv2d, Scale, Shift)\n    Relu = topi.nn.relu(ScaleShift)\n    # Schedule\n    s1 = schedule_depthwise_conv2d_nchw(DepthwiseConv2d)\n    s2 = schedule_depthwise_conv2d_nchw(ScaleShift)\n    s3 = schedule_depthwise_conv2d_nchw(Relu)\n    input_np = np.random.uniform(size=get_const_tuple(Input.shape)).astype(Input.dtype)\n    filter_np = np.random.uniform(size=get_const_tuple(Filter.shape)).astype(Filter.dtype)\n    scale_np = np.random.uniform(size=(in_channel * channel_multiplier)).astype(Scale.dtype)\n    shift_np = np.random.uniform(size=(in_channel * channel_multiplier)).astype(Shift.dtype)\n\n    def check_device(device):\n        if not tvm.runtime.enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        dev = tvm.device(device, 0)\n        # Build the kernel\n        f1 = tvm.build(s1, [Input, Filter, DepthwiseConv2d], device)\n        f2 = tvm.build(s2, [Input, Filter, Scale, Shift, ScaleShift], device)\n        f3 = tvm.build(s3, [Input, Filter, Scale, Shift, Relu], device)\n        # Prepare data\n        input_tvm = tvm.nd.array(input_np, dev)\n        filter_tvm = tvm.nd.array(filter_np, dev)\n        scale_tvm = tvm.nd.array(scale_np, dev)\n        shift_tvm = tvm.nd.array(shift_np, dev)\n\n        depthwise_conv2d_tvm = tvm.nd.array(\n            np.zeros(shape=get_const_tuple(DepthwiseConv2d.shape), dtype=DepthwiseConv2d.dtype), dev\n        )\n        scale_shift_tvm = tvm.nd.array(\n            np.zeros(shape=get_const_tuple(ScaleShift.shape), dtype=ScaleShift.dtype), dev\n        )\n        relu_tvm = tvm.nd.array(np.zeros(shape=get_const_tuple(Relu.shape), dtype=Relu.dtype), dev)\n        # Measure time cost of kernel 1 (depthwise_conv2d)\n        timer_1 = f1.time_evaluator(f1.entry_name, dev, number=1000)\n        tcost_1 = timer_1(input_tvm, filter_tvm, depthwise_conv2d_tvm).mean\n        # Measure time cost of kernel 2 (depthwise_conv2d + scale_shift)\n        timer_2 = f2.time_evaluator(f2.entry_name, dev, number=1000)\n        tcost_2 = timer_2(input_tvm, filter_tvm, scale_tvm, shift_tvm, scale_shift_tvm).mean\n        # Measure time cost of kernel 3 (depthwise_conv2d + scale_shift + relu)\n        timer_3 = f3.time_evaluator(f3.entry_name, dev, number=1000)\n        tcost_3 = timer_3(input_tvm, filter_tvm, scale_tvm, shift_tvm, relu_tvm).mean\n        print(\"Input shape = \" + str(get_const_tuple(Input.shape)))\n        print(\"Filter shape = \" + str(get_const_tuple(Filter.shape)))\n        print(\"Stride = (%d, %d)\" % (stride_h, stride_w))\n        print(\"padding = %s\\n\" % padding)\n        print(\"Output shape = \" + str(get_const_tuple(DepthwiseConv2d.shape)))\n        print(\"average time cost of 1000 runs (depthwise_conv2d) = %g us\" % (tcost_1 * 1e6))\n        print(\n            \"average time cost of 1000 runs (depthwise_conv2d + scale_shift) = %g us\"\n            % (tcost_2 * 1e6)\n        )\n        print(\n            \"average time cost of 1000 runs (depthwise_conv2d + scale_shift + relu) = %g us\"\n            % (tcost_3 * 1e6)\n        )\n        # correctness\n        depthwise_conv2d_scipy = tvm.topi.testing.depthwise_conv2d_python_nchw(\n            input_np, filter_np, stride=[stride_h, stride_w], padding=padding\n        )\n        scale_shift_scipy = np.zeros(shape=get_const_tuple(ScaleShift.shape))\n        for c in range(in_channel * channel_multiplier):\n            scale_shift_scipy[:, c, :, :] = (\n                depthwise_conv2d_scipy[:, c, :, :] * scale_np[c] + shift_np[c]\n            )\n        relu_scipy = np.maximum(scale_shift_scipy, 0)\n        tvm.testing.assert_allclose(depthwise_conv2d_tvm.numpy(), depthwise_conv2d_scipy, rtol=1e-5)\n        tvm.testing.assert_allclose(scale_shift_tvm.numpy(), scale_shift_scipy, rtol=1e-5)\n        tvm.testing.assert_allclose(relu_tvm.numpy(), relu_scipy, rtol=1e-5)\n        print(\"success\")\n\n    for device in [\"cuda\", \"opencl\", \"rocm\"]:\n        with tvm.transform.PassContext(\n            config={\"tir.UnrollLoop\": {\"auto_max_step\": 128, \"explicit_unroll\": device != \"rocm\"}}\n        ):\n            check_device(device)\n\n\ndef test_depthwise_conv2d_nhwc():\n    \"\"\"You may test different settings.\"\"\"\n    batch = 1\n    in_channel = 256\n    in_height = 96\n    in_width = 96\n\n    filter_channel = in_channel\n    channel_multiplier = 1\n    filter_height = 3\n    filter_width = 3\n\n    stride_h = 1\n    stride_w = 1\n\n    padding = \"SAME\"  # or 'VALID'\n\n    # Placeholder\n    Input = te.placeholder((batch, in_height, in_width, in_channel), name=\"Input\")\n    Filter = te.placeholder(\n        (filter_height, filter_width, filter_channel, channel_multiplier), name=\"Filter\"\n    )\n    Stride = [stride_h, stride_w]\n    Scale = te.placeholder((in_channel * channel_multiplier,), name=\"Scale\")\n    Shift = te.placeholder((in_channel * channel_multiplier,), name=\"Shift\")\n    # Declare\n    DepthwiseConv2d = topi.nn.depthwise_conv2d_nhwc(Input, Filter, Stride, padding)\n    ScaleShift = topi.nn.scale_shift_nhwc(DepthwiseConv2d, Scale, Shift)\n    Relu = topi.nn.relu(ScaleShift)\n    # Schedule\n    s1 = schedule_depthwise_conv2d_nhwc(DepthwiseConv2d)\n    s2 = schedule_depthwise_conv2d_nhwc(ScaleShift)\n    s3 = schedule_depthwise_conv2d_nhwc(Relu)\n\n    input_np = np.random.uniform(size=get_const_tuple(Input.shape)).astype(Input.dtype)\n    filter_np = np.random.uniform(size=get_const_tuple(Filter.shape)).astype(Filter.dtype)\n    scale_np = np.random.uniform(size=(in_channel * channel_multiplier)).astype(Scale.dtype)\n    shift_np = np.random.uniform(size=(in_channel * channel_multiplier)).astype(Shift.dtype)\n\n    def check_device(device):\n        if not tvm.runtime.enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        dev = tvm.device(device, 0)\n        # Build the kernel\n        f1 = tvm.build(s1, [Input, Filter, DepthwiseConv2d], device)\n        f2 = tvm.build(s2, [Input, Filter, Scale, Shift, ScaleShift], device)\n        f3 = tvm.build(s3, [Input, Filter, Scale, Shift, Relu], device)\n        # Prepare data\n        input_tvm = tvm.nd.array(input_np, dev)\n        filter_tvm = tvm.nd.array(filter_np, dev)\n        scale_tvm = tvm.nd.array(scale_np, dev)\n        shift_tvm = tvm.nd.array(shift_np, dev)\n        depthwise_conv2d_tvm = tvm.nd.array(\n            np.zeros(shape=get_const_tuple(DepthwiseConv2d.shape), dtype=DepthwiseConv2d.dtype), dev\n        )\n        scale_shift_tvm = tvm.nd.array(\n            np.zeros(shape=get_const_tuple(ScaleShift.shape), dtype=ScaleShift.dtype), dev\n        )\n        relu_tvm = tvm.nd.array(np.zeros(shape=get_const_tuple(Relu.shape), dtype=Relu.dtype), dev)\n        # Measure time cost of kernel 1 (depthwise_conv2d)\n        timer_1 = f1.time_evaluator(f1.entry_name, dev, number=1000)\n        tcost_1 = timer_1(input_tvm, filter_tvm, depthwise_conv2d_tvm).mean\n        # Measure time cost of kernel 2 (depthwise_conv2d + scale_shift)\n        timer_2 = f2.time_evaluator(f2.entry_name, dev, number=1000)\n        tcost_2 = timer_2(input_tvm, filter_tvm, scale_tvm, shift_tvm, scale_shift_tvm).mean\n        # Measure time cost of kernel 3 (depthwise_conv2d + scale_shift + relu)\n        timer_3 = f3.time_evaluator(f3.entry_name, dev, number=1000)\n        tcost_3 = timer_3(input_tvm, filter_tvm, scale_tvm, shift_tvm, relu_tvm).mean\n        print(\"Input shape = \" + str(get_const_tuple(Input.shape)))\n        print(\"Filter shape = \" + str(get_const_tuple(Filter.shape)))\n        print(\"Stride = (%d, %d)\" % (stride_h, stride_w))\n        print(\"padding = %s\\n\" % padding)\n        print(\"Output shape = \" + str(get_const_tuple(DepthwiseConv2d.shape)))\n        print(\"average time cost of 1000 runs (depthwise_conv2d) = %g us\" % (tcost_1 * 1e6))\n        print(\n            \"average time cost of 1000 runs (depthwise_conv2d + scale_shift) = %g us\"\n            % (tcost_2 * 1e6)\n        )\n        print(\n            \"average time cost of 1000 runs (depthwise_conv2d + scale_shift + relu) = %g us\"\n            % (tcost_3 * 1e6)\n        )\n        # correctness\n        depthwise_conv2d_scipy = tvm.topi.testing.depthwise_conv2d_python_nhwc(\n            input_np, filter_np, stride=[stride_h, stride_w], padding=padding\n        )\n        scale_shift_scipy = np.zeros(shape=get_const_tuple(ScaleShift.shape))\n        for c in range(in_channel * channel_multiplier):\n            scale_shift_scipy[:, :, :, c] = (\n                depthwise_conv2d_scipy[:, :, :, c] * scale_np[c] + shift_np[c]\n            )\n        relu_scipy = np.maximum(scale_shift_scipy, 0)\n        tvm.testing.assert_allclose(depthwise_conv2d_tvm.numpy(), depthwise_conv2d_scipy, rtol=1e-5)\n        tvm.testing.assert_allclose(scale_shift_tvm.numpy(), scale_shift_scipy, rtol=1e-5)\n        tvm.testing.assert_allclose(relu_tvm.numpy(), relu_scipy, rtol=1e-5)\n        print(\"success\")\n\n    for device in [\"cuda\", \"opencl\", \"rocm\"]:\n        with tvm.transform.PassContext(\n            config={\"tir.UnrollLoop\": {\"auto_max_step\": 128, \"explicit_unroll\": device != \"cuda\"}}\n        ):\n            check_device(device)\n\n\nif __name__ == \"__main__\":\n    test_depthwise_conv2d_nchw()\n    test_depthwise_conv2d_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/conv/test_conv2d_hwcn_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\nimport os\nimport numpy as np\nimport scipy.signal\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import nvcc\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\n\nTASK = \"conv2d_hwcn_map\"\nUSE_MANUAL_CODE = False\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef test_conv2d_hwcn_map():\n    batch = 64\n    in_channel = 128\n    in_height = 16\n    in_width = 16\n    num_filter = 128\n    kernel = 3\n    stride = 2\n    padding = \"SAME\"\n\n    A = te.placeholder((in_height, in_width, in_channel, batch), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    B = topi.nn.conv2d_hwcn(A, W, stride, padding)\n    C = topi.nn.relu(B)\n    s1 = topi.cuda.schedule_conv2d_hwcn([B])\n    s2 = topi.cuda.schedule_conv2d_hwcn([C])\n\n    a_np = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)\n    w_np = np.random.uniform(size=get_const_tuple(W.shape)).astype(W.dtype)\n    b_np = tvm.topi.testing.conv2d_hwcn_python(a_np, w_np, stride, padding)\n    c_np = np.maximum(b_np, 0)\n\n    def check_device(device):\n        if not tvm.runtime.enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        dev = tvm.device(device, 0)\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.UrollLoop\": {\"auto_unroll_max_step\": 128, \"explicit_unroll\": device == \"rocm\"}\n            }\n        ):\n            func1 = tvm.build(s1, [A, W, B], device)\n            func1(a, w, b)\n            tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n            func2 = tvm.build(s2, [A, W, C], device)\n            func2(a, w, c)\n            tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for device in [\"cuda\", \"opencl\", \"rocm\"]:\n        check_device(device)\n\n\nif __name__ == \"__main__\":\n    test_conv2d_hwcn_map()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/conv/test_conv_int8_arm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable-msg=too-many-arguments, too-many-locals, assignment-from-no-return\n\"\"\" Conv Int8 functional and performance testing\"\"\"\nimport sys\nimport logging\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\nLOGGER = logging.getLogger(\"test_conv_int8_intel\")\nLOGGER.disabled = False\n\n# All the WORKLOADS from Resnet except first layer\n# Workload is ['height', 'width', 'in_filter', 'out_filter',\n#              'hkernel', 'wkernel', 'hpad', 'wpad', 'hstride', 'wstride'])\nWORKLOADS = [\n    (56, 56, 64, 64, 3, 3, 1, 1, 1, 1),\n    (56, 56, 64, 64, 1, 1, 0, 0, 1, 1),\n    (56, 56, 64, 128, 3, 3, 1, 1, 2, 2),\n    (56, 56, 64, 128, 1, 1, 0, 0, 2, 2),\n    (28, 28, 128, 128, 3, 3, 1, 1, 1, 1),\n    (28, 28, 128, 256, 3, 3, 1, 1, 2, 2),\n    (28, 28, 128, 256, 1, 1, 0, 0, 2, 2),\n    (14, 14, 256, 256, 3, 3, 1, 1, 1, 1),\n    (14, 14, 256, 512, 3, 3, 1, 1, 2, 2),\n    (14, 14, 256, 512, 1, 1, 0, 0, 2, 2),\n    (7, 7, 512, 512, 3, 3, 1, 1, 1, 1),\n    (56, 56, 64, 256, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 64, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 128, 1, 1, 0, 0, 2, 2),\n    (28, 28, 128, 512, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 512, 1, 1, 0, 0, 2, 2),\n    (28, 28, 512, 128, 1, 1, 0, 0, 1, 1),\n    (28, 28, 512, 256, 1, 1, 0, 0, 2, 2),\n    (14, 14, 256, 1024, 1, 1, 0, 0, 1, 1),\n    (28, 28, 512, 1024, 1, 1, 0, 0, 2, 2),\n    (14, 14, 1024, 256, 1, 1, 0, 0, 1, 1),\n    (14, 14, 1024, 512, 1, 1, 0, 0, 2, 2),\n    (7, 7, 512, 2048, 1, 1, 0, 0, 1, 1),\n    (14, 14, 1024, 2048, 1, 1, 0, 0, 2, 2),\n    (7, 7, 2048, 512, 1, 1, 0, 0, 1, 1),\n]\n\n\nTARGET_NAME = \"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\"\nNUM_VEC_LANES = 16\nDEV = tvm.device(TARGET_NAME, 0)\n\n\ndef get_shape(\n    im_height, im_width, in_filter, out_filter, k_h, k_w, hpad, wpad, hstride, wstride, out_dtype\n):\n    \"\"\"\n    Finds out the shape of all data structures\n    \"\"\"\n    data_shape = (1, in_filter // NUM_VEC_LANES, im_height, im_width, NUM_VEC_LANES)\n\n    if out_dtype == \"int32\" or out_dtype == \"uint32\":\n        kernel_shape = (\n            out_filter // NUM_VEC_LANES,\n            in_filter // NUM_VEC_LANES,\n            k_h,\n            k_w,\n            NUM_VEC_LANES // 4,\n            NUM_VEC_LANES,\n            4,\n        )\n    elif out_dtype == \"float32\":\n        kernel_shape = (\n            out_filter // NUM_VEC_LANES,\n            in_filter // NUM_VEC_LANES,\n            k_h,\n            k_w,\n            NUM_VEC_LANES,\n            NUM_VEC_LANES,\n        )\n    out_height = (im_height + 2 * hpad - k_h) // hstride + 1\n    out_width = (im_width + 2 * wpad - k_w) // wstride + 1\n    o_shape = (1, out_filter // NUM_VEC_LANES, out_height, out_width, NUM_VEC_LANES)\n    return (data_shape, kernel_shape, o_shape)\n\n\ndef run_inference(\n    data_dtype,\n    kernel_dtype,\n    out_dtype,\n    im_height,\n    im_width,\n    in_filter,\n    out_filter,\n    k_h,\n    k_w,\n    hpad,\n    wpad,\n    hstride,\n    wstride,\n):\n    \"\"\"\n    Runs the inference and checks the functional correctness between\n    compute and schedule outputs\n    \"\"\"\n    (data_shape, kernel_shape, o_shape) = get_shape(\n        im_height,\n        im_width,\n        in_filter,\n        out_filter,\n        k_h,\n        k_w,\n        hpad,\n        wpad,\n        hstride,\n        wstride,\n        out_dtype,\n    )\n\n    # Create TVM placeholders\n    data = te.placeholder(data_shape, name=\"data\", dtype=data_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=kernel_dtype)\n\n    # Create the numpy arrays to be used for executing conv models\n    if data_dtype == \"float32\":\n        data_array = tvm.nd.array(np.random.rand(*data_shape).astype(dtype=data_dtype), DEV)\n        kernel_array = tvm.nd.array(np.random.rand(*kernel_shape).astype(dtype=kernel_dtype), DEV)\n    else:\n        data_array = tvm.nd.array(np.random.randint(100, size=data_shape).astype(data_dtype))\n        kernel_array = tvm.nd.array(np.random.randint(100, size=kernel_shape).astype(kernel_dtype))\n\n    # c_orig will be used for declaration ouptut\n    # c_sch will be used for scheduled computation output\n    c_orig = tvm.nd.array(np.zeros(o_shape, dtype=out_dtype), DEV)\n    c_sch = tvm.nd.array(np.zeros(o_shape, dtype=out_dtype), DEV)\n\n    with tvm.target.Target(TARGET_NAME):\n        if out_dtype == \"float32\":\n            conv = topi.nn.conv2d_NCHWc(\n                data,\n                kernel,\n                stride=hstride,\n                padding=hpad,\n                dilation=(1, 1),\n                layout=\"NCHWc\",\n                out_layout=\"NCHWc\",\n                out_dtype=out_dtype,\n            )\n        else:\n            conv = topi.nn.conv2d_NCHWc_int8(\n                data,\n                kernel,\n                strides=hstride,\n                padding=hpad,\n                dilation=(1, 1),\n                layout=\"NCHWc\",\n                out_layout=\"NCHWc\",\n                out_dtype=out_dtype,\n            )\n        out = topi.nn.relu(conv)\n        sch = te.create_schedule(out.op)\n        func = tvm.build(sch, [data, kernel, out], target=TARGET_NAME, name=\"out\")\n        func(data_array, kernel_array, c_orig)\n        LOGGER.debug(tvm.lower(sch, [data, kernel], simple_mode=True))\n\n        # Generate and run the optimized schedule\n        if out_dtype == \"float32\":\n            sconv = topi.generic.nn.schedule_conv2d_NCHWc(outs=[out])\n        else:\n            sconv = topi.generic.nn.schedule_conv2d_NCHWc_int8(outs=[out])\n        func = tvm.build(sconv, [data, kernel, out], target=TARGET_NAME, name=\"conv\")\n        func(data_array, kernel_array, c_sch)\n\n        # Functional check\n        if data_dtype == \"uint8\":\n            np.testing.assert_equal(c_orig.numpy(), c_sch.numpy())\n        else:\n            assert np.allclose(c_orig.numpy(), c_sch.numpy())\n\n        evaluator = func.time_evaluator(func.entry_name, DEV, number=1000)\n        LOGGER.debug(tvm.lower(sconv, [data, kernel], simple_mode=True))\n        return evaluator(data_array, kernel_array, c_sch).mean\n\n\nif __name__ == \"__main__\":\n    LOGGER.info(\"Workload, Kernel_size, FP32_time, INT8_time, Speedup\")\n    SPEEDUP_ARRAY = []\n    for i, wkl in enumerate(WORKLOADS):\n        for dtype in [\"uint\", \"int\"]:\n            fp32_time = run_inference(\"float32\", \"float32\", \"float32\", *wkl)\n            int8_time = run_inference(\"%s8\" % dtype, \"%s8\" % dtype, \"%s32\" % dtype, *wkl)\n            kernel_h = wkl[4]\n            kernel_w = wkl[5]\n            LOGGER.info(\n                \"[%s] Workload#\" % dtype\n                + str(i)\n                + \", \"\n                + str(kernel_h)\n                + \"x\"\n                + str(kernel_w)\n                + \", \"\n                + str(fp32_time)\n                + \", \"\n                + str(int8_time)\n                + \", \"\n                + str(fp32_time / int8_time)\n            )\n\n            SPEEDUP_ARRAY.append(fp32_time / int8_time)\n    LOGGER.info(\"Average speedup --> %s\" % str(sum(SPEEDUP_ARRAY) / float(len(SPEEDUP_ARRAY))))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/conv/test_conv_int8_intel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable-msg=too-many-arguments, too-many-locals, assignment-from-no-return\n\"\"\" Conv Int8 functional and performance testing\"\"\"\nimport sys\nimport logging\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\nLOGGER = logging.getLogger(\"test_conv_int8_intel\")\nLOGGER.disabled = False\n\n# All the WORKLOADS from Resnet except first layer\n# Workload is ['height', 'width', 'in_filter', 'out_filter',\n#              'hkernel', 'wkernel', 'hpad', 'wpad', 'hstride', 'wstride'])\nWORKLOADS = [\n    (56, 56, 64, 64, 3, 3, 1, 1, 1, 1),\n    (56, 56, 64, 64, 1, 1, 0, 0, 1, 1),\n    (56, 56, 64, 128, 3, 3, 1, 1, 2, 2),\n    (56, 56, 64, 128, 1, 1, 0, 0, 2, 2),\n    (28, 28, 128, 128, 3, 3, 1, 1, 1, 1),\n    (28, 28, 128, 256, 3, 3, 1, 1, 2, 2),\n    (28, 28, 128, 256, 1, 1, 0, 0, 2, 2),\n    (14, 14, 256, 256, 3, 3, 1, 1, 1, 1),\n    (14, 14, 256, 512, 3, 3, 1, 1, 2, 2),\n    (14, 14, 256, 512, 1, 1, 0, 0, 2, 2),\n    (7, 7, 512, 512, 3, 3, 1, 1, 1, 1),\n    (56, 56, 64, 256, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 64, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 128, 1, 1, 0, 0, 2, 2),\n    (28, 28, 128, 512, 1, 1, 0, 0, 1, 1),\n    (56, 56, 256, 512, 1, 1, 0, 0, 2, 2),\n    (28, 28, 512, 128, 1, 1, 0, 0, 1, 1),\n    (28, 28, 512, 256, 1, 1, 0, 0, 2, 2),\n    (14, 14, 256, 1024, 1, 1, 0, 0, 1, 1),\n    (28, 28, 512, 1024, 1, 1, 0, 0, 2, 2),\n    (14, 14, 1024, 256, 1, 1, 0, 0, 1, 1),\n    (14, 14, 1024, 512, 1, 1, 0, 0, 2, 2),\n    (7, 7, 512, 2048, 1, 1, 0, 0, 1, 1),\n    (14, 14, 1024, 2048, 1, 1, 0, 0, 2, 2),\n    (7, 7, 2048, 512, 1, 1, 0, 0, 1, 1),\n]\n\n\nTARGET_NAME = \"llvm -mcpu=skylake-avx512\"\nNUM_VEC_LANES = 16\nDEV = tvm.device(TARGET_NAME, 0)\n\n\ndef get_shape(\n    im_height, im_width, in_filter, out_filter, k_h, k_w, hpad, wpad, hstride, wstride, out_dtype\n):\n    \"\"\"\n    Finds out the shape of all data structures\n    \"\"\"\n    ## Find shapes\n    data_shape = (1, in_filter // NUM_VEC_LANES, im_height, im_width, NUM_VEC_LANES)\n\n    if out_dtype == \"int32\":\n        kernel_shape = (\n            out_filter // NUM_VEC_LANES,\n            in_filter // NUM_VEC_LANES,\n            k_h,\n            k_w,\n            NUM_VEC_LANES // 4,\n            NUM_VEC_LANES,\n            4,\n        )\n    elif out_dtype == \"float32\":\n        kernel_shape = (\n            out_filter // NUM_VEC_LANES,\n            in_filter // NUM_VEC_LANES,\n            k_h,\n            k_w,\n            NUM_VEC_LANES,\n            NUM_VEC_LANES,\n        )\n    out_height = (im_height + 2 * hpad - k_h) // hstride + 1\n    out_width = (im_width + 2 * wpad - k_w) // wstride + 1\n    o_shape = (1, out_filter // NUM_VEC_LANES, out_height, out_width, NUM_VEC_LANES)\n    return (data_shape, kernel_shape, o_shape)\n\n\ndef run_inference(\n    data_dtype,\n    kernel_dtype,\n    out_dtype,\n    im_height,\n    im_width,\n    in_filter,\n    out_filter,\n    k_h,\n    k_w,\n    hpad,\n    wpad,\n    hstride,\n    wstride,\n):\n    \"\"\"\n    Runs the inference and checks the functional correctness between\n    compute and schedule outputs\n    \"\"\"\n    (data_shape, kernel_shape, o_shape) = get_shape(\n        im_height,\n        im_width,\n        in_filter,\n        out_filter,\n        k_h,\n        k_w,\n        hpad,\n        wpad,\n        hstride,\n        wstride,\n        out_dtype,\n    )\n\n    # Create TVM placeholders\n    data = te.placeholder(data_shape, name=\"data\", dtype=data_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=kernel_dtype)\n\n    # Create the numpy arrays to be used for executing conv models\n    if data_dtype == \"float32\":\n        data_array = tvm.nd.array(np.random.rand(*data_shape).astype(dtype=data_dtype), DEV)\n        kernel_array = tvm.nd.array(np.random.rand(*kernel_shape).astype(dtype=kernel_dtype), DEV)\n    else:\n        data_array = tvm.nd.array(np.random.randint(100, size=data_shape).astype(data_dtype))\n        kernel_array = tvm.nd.array(np.random.randint(100, size=kernel_shape).astype(kernel_dtype))\n\n    # c_orig will be used for declaration ouptut\n    # c_sch will be used for scheduled computation output\n    c_orig = tvm.nd.array(np.zeros(o_shape, dtype=out_dtype), DEV)\n    c_sch = tvm.nd.array(np.zeros(o_shape, dtype=out_dtype), DEV)\n\n    with tvm.target.Target(TARGET_NAME):\n        conv = topi.nn.conv2d_NCHWc(\n            data,\n            kernel,\n            stride=hstride,\n            padding=hpad,\n            dilation=(1, 1),\n            layout=\"NCHWc\",\n            out_layout=\"NCHWc\",\n            out_dtype=out_dtype,\n        )\n        out = topi.nn.relu(conv)\n        sch = te.create_schedule(out.op)\n        func = tvm.build(sch, [data, kernel, out], target=TARGET_NAME, name=\"out\")\n        func(data_array, kernel_array, c_orig)\n        LOGGER.debug(tvm.lower(sch, [data, kernel], simple_mode=True))\n\n        # Generate and run the optimized schedule\n        sconv = topi.generic.nn.schedule_conv2d_NCHWc(outs=[out])\n        func = tvm.build(sconv, [data, kernel, out], target=TARGET_NAME, name=\"conv\")\n        func(data_array, kernel_array, c_sch)\n\n        # Functional check\n        if data_dtype == \"uint8\":\n            np.testing.assert_equal(c_orig.numpy(), c_sch.numpy())\n        else:\n            assert np.allclose(c_orig.numpy(), c_sch.numpy())\n\n        evaluator = func.time_evaluator(func.entry_name, DEV, number=1000)\n        LOGGER.debug(tvm.lower(sconv, [data, kernel], simple_mode=True))\n        return evaluator(data_array, kernel_array, c_sch).mean\n\n\nif __name__ == \"__main__\":\n    LOGGER.info(\"Workload, Kernel_size, FP32_time, INT8_time, Speedup\")\n    SPEEDUP_ARRAY = []\n    for i, wkl in enumerate(WORKLOADS):\n        fp32_time = run_inference(\"float32\", \"float32\", \"float32\", *wkl)\n        int8_time = run_inference(\"uint8\", \"int8\", \"int32\", *wkl)\n        kernel_h = wkl[4]\n        kernel_w = wkl[5]\n        LOGGER.info(\n            \"Workload#\"\n            + str(i)\n            + \", \"\n            + str(kernel_h)\n            + \"x\"\n            + str(kernel_w)\n            + \", \"\n            + str(fp32_time)\n            + \", \"\n            + str(int8_time)\n            + \", \"\n            + str(fp32_time / int8_time)\n        )\n\n        SPEEDUP_ARRAY.append(fp32_time / int8_time)\n    LOGGER.info(\"Average speedup --> %s\" % str(sum(SPEEDUP_ARRAY) / float(len(SPEEDUP_ARRAY))))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/gemm/android_gemm_square.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do square matrix multiplication on Android Phone.\"\"\"\nimport tvm\nfrom tvm import te\nimport os\nfrom tvm import rpc\nfrom tvm.contrib import utils, ndk\nimport numpy as np\n\n# Set to be address of tvm proxy.\nproxy_host = os.environ[\"TVM_ANDROID_RPC_PROXY_HOST\"]\nproxy_port = 9090\nkey = \"android\"\n\n# Change target configuration.\n# Run `adb shell cat /proc/cpuinfo` to find the arch.\narch = \"arm64\"\ntarget = \"llvm -mtriple=%s-linux-android\" % arch\n\n\ndef ngflops(N):\n    return 2.0 * float(N * N * N) / (10**9)\n\n\ndtype = \"float32\"\n\n\ndef evaluate(func, dev, N, times):\n    a_np = np.random.uniform(size=(N, N)).astype(dtype)\n    b_np = np.random.uniform(size=(N, N)).astype(dtype)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((N, N), dtype=dtype), dev)\n\n    time_f = func.time_evaluator(func.entry_name, dev, number=times)\n    cost = time_f(a, b, c).mean\n    gf = ngflops(N) / cost\n    print(\"%g secs/op, %g GFLOPS\" % (cost, gf))\n    np.testing.assert_almost_equal(c.numpy(), a_np.dot(b_np), decimal=2)\n\n\ndef test_gemm_gpu(N, times, bn, num_block, num_thread):\n    assert bn <= N\n    assert num_thread * num_thread * 16 <= N\n    assert num_block * num_block * 2 <= N\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"Btmp\")\n    k = te.reduce_axis((0, N), name=\"k\")\n\n    packedB = te.compute((N, N / bn, bn), lambda x, y, z: B[x, y * bn + z], name=\"B\")\n\n    C = te.compute(\n        (N, N), lambda ii, jj: te.sum(A[ii, k] * packedB[k, jj / bn, jj % bn], axis=k), name=\"C\"\n    )\n\n    s = te.create_schedule(C.op)\n    CC = s.cache_write(C, \"local\")\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n\n    thread_xz = te.thread_axis((0, 2), \"vthread\", name=\"vx\")\n    thread_yz = te.thread_axis((0, 2), \"vthread\", name=\"vy\")\n\n    pby, pbi = s[packedB].split(packedB.op.axis[0], nparts=num_thread)\n    pbx, pbj = s[packedB].split(packedB.op.axis[1], nparts=num_thread)\n    s[packedB].bind(pby, thread_y)\n    s[packedB].bind(pbx, thread_x)\n    pbz, pbk = s[packedB].split(packedB.op.axis[2], factor=8)\n    s[packedB].vectorize(pbk)\n\n    by, yi = s[C].split(C.op.axis[0], nparts=num_block)\n    bx, xi = s[C].split(C.op.axis[1], nparts=num_thread)\n\n    s[C].bind(by, block_y)\n    s[C].bind(bx, thread_y)\n    s[C].reorder(by, bx, yi, xi)\n\n    tyz, yi = s[C].split(yi, nparts=2)\n    ty, yi = s[C].split(yi, nparts=num_block)\n    txz, xi = s[C].split(xi, nparts=2)\n    tx, xi = s[C].split(xi, nparts=num_thread)\n\n    s[C].reorder(tyz, txz, ty, tx, yi, xi)\n    s[C].bind(tyz, thread_yz)\n    s[C].bind(txz, thread_xz)\n\n    s[C].bind(ty, block_x)\n    s[C].bind(tx, thread_x)\n\n    xyi, xxi = s[C].split(xi, factor=8)\n    s[C].reorder(tyz, txz, ty, tx, yi, xyi, xxi)\n    s[C].vectorize(xxi)\n\n    s[CC].compute_at(s[C], yi)\n    yo, xo = CC.op.axis\n    s[CC].reorder(k, yo, xo)\n    xo, xi = s[CC].split(xo, factor=8)\n    s[CC].vectorize(xi)\n\n    ko, ki = s[CC].split(k, factor=2)\n    s[CC].unroll(ki)\n\n    print(tvm.lower(s, [A, B, C], simple_mode=True))\n\n    f = tvm.build(s, [A, B, C], tvm.target.Target(\"opencl\", host=target), name=\"gemm_gpu\")\n    temp = utils.tempdir()\n    path_dso = temp.relpath(\"gemm_gpu.so\")\n    f.export_library(path_dso, ndk.create_shared)\n\n    # connect to the proxy\n    remote = rpc.connect(proxy_host, proxy_port, key=key)\n    dev = remote.cl(0)\n    remote.upload(path_dso)\n    f = remote.load_module(\"gemm_gpu.so\")\n\n    evaluate(f, dev, N, times)\n\n\nif __name__ == \"__main__\":\n    test_gemm_gpu(1024, times=5, bn=8, num_block=2, num_thread=8)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/gemm/cuda_gemm_square.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do square matrix multiplication.\"\"\"\nimport tvm\nfrom tvm import te\nimport os\nfrom tvm.contrib import nvcc\nfrom tvm.contrib import spirv\nimport numpy as np\nimport tvm.testing\n\nTASK = \"gemm\"\nUSE_MANUAL_CODE = False\n\n\ndef test_gemm():\n    # graph\n    nn = 2048\n    n = te.var(\"n\")\n    n = tvm.runtime.convert(nn)\n    m, l = n, n\n    A = te.placeholder((l, n), name=\"A\")\n    B = te.placeholder((l, m), name=\"B\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute((m, n), lambda ii, jj: te.sum(A[k, jj] * B[k, ii], axis=k), name=\"C\")\n\n    # schedule\n    s = te.create_schedule(C.op)\n    AA = s.cache_read(A, \"shared\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n    AL = s.cache_read(AA, \"local\", [C])\n    BL = s.cache_read(BB, \"local\", [C])\n    CC = s.cache_write(C, \"local\")\n\n    scale = 8\n    num_thread = 8\n    block_factor = scale * num_thread\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_y = te.thread_axis((0, num_thread), \"threadIdx.y\")\n    thread_xz = te.thread_axis((0, 2), \"vthread\", name=\"vx\")\n    thread_yz = te.thread_axis((0, 2), \"vthread\", name=\"vy\")\n\n    by, yi = s[C].split(C.op.axis[0], factor=block_factor)\n    bx, xi = s[C].split(C.op.axis[1], factor=block_factor)\n    s[C].bind(by, block_y)\n    s[C].bind(bx, block_x)\n    s[C].reorder(by, bx, yi, xi)\n\n    tyz, yi = s[C].split(yi, nparts=2)\n    ty, yi = s[C].split(yi, nparts=num_thread)\n    txz, xi = s[C].split(xi, nparts=2)\n    tx, xi = s[C].split(xi, nparts=num_thread)\n    s[C].bind(tyz, thread_yz)\n    s[C].bind(txz, thread_xz)\n    s[C].bind(ty, thread_y)\n    s[C].bind(tx, thread_x)\n    s[C].reorder(tyz, txz, ty, tx, yi, xi)\n    s[CC].compute_at(s[C], tx)\n\n    yo, xo = CC.op.axis\n    ko, ki = s[CC].split(k, factor=8)\n    kt, ki = s[CC].split(ki, factor=1)\n    s[CC].reorder(ko, kt, ki, yo, xo)\n    s[AA].compute_at(s[CC], ko)\n    s[BB].compute_at(s[CC], ko)\n    s[CC].unroll(kt)\n    s[AL].compute_at(s[CC], kt)\n    s[BL].compute_at(s[CC], kt)\n    # Schedule for A's shared memory load\n    ty, xi = s[AA].split(s[AA].op.axis[0], nparts=num_thread)\n    _, xi = s[AA].split(s[AA].op.axis[1], factor=num_thread * 4)\n    tx, xi = s[AA].split(xi, nparts=num_thread)\n    s[AA].bind(ty, thread_y)\n    s[AA].bind(tx, thread_x)\n    s[AA].vectorize(xi)\n    # Schedule for B' shared memory load\n    ty, xi = s[BB].split(s[BB].op.axis[0], nparts=num_thread)\n    _, xi = s[BB].split(s[BB].op.axis[1], factor=num_thread * 4)\n    tx, xi = s[BB].split(xi, nparts=num_thread)\n    s[BB].bind(ty, thread_y)\n    s[BB].bind(tx, thread_x)\n    s[BB].vectorize(xi)\n    s[AA].double_buffer()\n    s[BB].double_buffer()\n    # correctness\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not dev.exist:\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Device %s\" % device)\n        f = tvm.build(s, [A, B, C], device)\n        # launch the kernel.\n        n, m, l = nn, nn, nn\n        a_np = np.random.uniform(size=(n, l)).astype(A.dtype)\n        b_np = np.random.uniform(size=(m, l)).astype(B.dtype)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), dev)\n        for i in range(2):\n            f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), np.dot(b_np.T, a_np), rtol=1e-5)\n\n        num_flops = 2 * nn * nn * nn\n        num_runs = 10\n        timer_f = f.time_evaluator(f.entry_name, dev, number=num_runs)\n        t = timer_f(a, b, c).mean\n        GFLOPS = num_flops / (t * 1e3) / 1e6\n        print(\"average time cost of %d runs = %g ms, %g GFLOPS.\" % (num_runs, t * 1e3, GFLOPS))\n\n    for device in [\"cuda\", \"opencl\", \"rocm\", \"nvptx\", \"vulkan\"]:\n        with tvm.transform.PassContext(\n            config={\"tir.UnrollLoop\": {\"auto_max_step\": 128, \"explicit_unroll\": device != \"cuda\"}}\n        ):\n            check_device(device)\n\n\nif __name__ == \"__main__\":\n    test_gemm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/gemm/gemm_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"Example code to perform int8 GEMM\"\nimport logging\nimport sys\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.topi.cuda.tensor_intrin import dp4a\n\nDO_TUNING = True\nPRETUNED_INDEX = 75333\n\nintrin_dp4a = dp4a(\"local\", \"local\", \"local\")\n\n\n@autotvm.template\ndef gemm_int8(n, m, l):\n    A = te.placeholder((n, l), name=\"A\", dtype=\"int8\")\n    B = te.placeholder((m, l), name=\"B\", dtype=\"int8\")\n\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute(\n        (n, m),\n        lambda i, j: te.sum(A[i, k].astype(\"int32\") * B[j, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    cfg = autotvm.get_config()\n    s = te.create_schedule(C.op)\n    y, x = C.op.axis\n\n    AA = s.cache_read(A, \"shared\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n    AL = s.cache_read(AA, \"local\", [C])\n    BL = s.cache_read(BB, \"local\", [C])\n    CC = s.cache_write(C, \"local\")\n\n    k = CC.op.reduce_axis[0]\n\n    cfg.define_split(\n        \"tile_k\",\n        cfg.axis(k),\n        num_outputs=3,\n        filter=lambda entity: entity.size[2] == 4 and entity.size[0] * 2 >= entity.size[1],\n    )\n\n    ko, kt, ki = cfg[\"tile_k\"].apply(s, CC, k)\n\n    s[CC].tensorize(ki, intrin_dp4a)\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n\n    def block_size_filter(entity):\n        return (\n            entity.size[0] * 2 >= entity.size[1] * 2\n            and entity.size[1] <= 16\n            and entity.size[3] <= 4\n        )\n\n    cfg.define_split(\"tile_y\", cfg.axis(y), num_outputs=4, filter=block_size_filter)\n    cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4, filter=block_size_filter)\n    by, tyz, ty, yi = cfg[\"tile_y\"].apply(s, C, y)\n    bx, txz, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n\n    s[C].bind(by, block_y)\n    s[C].bind(bx, block_x)\n    s[C].bind(tyz, te.thread_axis(\"vthread\"))\n    s[C].bind(txz, te.thread_axis(\"vthread\"))\n    s[C].bind(ty, thread_y)\n    s[C].bind(tx, thread_x)\n    s[C].reorder(by, bx, tyz, txz, ty, tx, yi, xi)\n\n    s[CC].compute_at(s[C], tx)\n\n    yo, xo = CC.op.axis\n    s[CC].reorder(ko, kt, yo, xo, ki)\n    s[CC].unroll(kt)\n\n    for stage in [AL, BL]:\n        s[stage].compute_at(s[CC], kt)\n        _, xi = s[stage].split(stage.op.axis[1], factor=4)\n        s[stage].vectorize(xi)\n        s[stage].double_buffer()\n\n    cfg.define_knob(\"storage_align\", [16, 48])\n    for stage in [AA, BB]:\n        s[stage].storage_align(s[stage].op.axis[0], cfg[\"storage_align\"].val, 0)\n        s[stage].compute_at(s[CC], ko)\n\n        fused = s[stage].fuse(*s[stage].op.axis)\n        ty, tx = s[stage].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, xi = s[stage].split(tx, nparts=cfg[\"tile_x\"].size[2])\n        _, xi = s[stage].split(xi, factor=16)\n\n        s[stage].bind(ty, thread_y)\n        s[stage].bind(tx, thread_x)\n        s[stage].vectorize(xi)\n\n    cfg.define_knob(\"auto_unroll_max_step\", [512, 1500])\n    s[C].pragma(by, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[C].pragma(by, \"unroll_explicit\", False)\n\n    cfg.add_flop(n * m * l * 2)\n    return s, [A, B, C]\n\n\nif __name__ == \"__main__\":\n    N = 2048\n    n = m = l = N\n\n    logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)\n    task = autotvm.task.create(gemm_int8, args=(n, m, l), target=\"cuda\")\n    print(task.config_space)\n\n    measure_option = autotvm.measure_option(\n        builder=autotvm.LocalBuilder(),\n        runner=autotvm.LocalRunner(repeat=3, min_repeat_ms=100, timeout=4),\n    )\n\n    log_name = \"gemm_int8.log\"\n    if DO_TUNING:\n        tuner = autotvm.tuner.XGBTuner(task)\n        tuner.tune(\n            n_trial=1000,\n            measure_option=measure_option,\n            callbacks=[autotvm.callback.log_to_file(log_name)],\n        )\n\n        dispatch_context = autotvm.apply_history_best(log_name)\n        best_config = dispatch_context.query(task.target, task.workload)\n        print(\"\\nBest config:\")\n        print(best_config)\n    else:\n        config = task.config_space.get(PRETUNED_INDEX)\n        dispatch_context = autotvm.task.ApplyConfig(config)\n        print(\"Using pretuned config:\")\n        print(config)\n\n    with dispatch_context:\n        with tvm.target.Target(\"cuda\"):\n            s, arg_bufs = gemm_int8(n, m, l)\n            f = tvm.build(s, arg_bufs, \"cuda\", name=\"gemm_int8\")\n\n    dev = tvm.device(\"cuda\", 0)\n\n    a_np = np.random.randint(size=(n, l), low=-128, high=127, dtype=\"int8\")\n    b_np = np.random.randint(size=(m, l), low=-128, high=127, dtype=\"int8\")\n\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((n, m), dtype=\"int32\"), dev)\n    f(a, b, c)\n\n    tvm.testing.assert_allclose(\n        c.numpy(), np.dot(a_np.astype(\"int32\"), b_np.T.astype(\"int32\")), rtol=1e-5\n    )\n\n    num_ops = 2 * l * m * n\n    num_runs = 1000\n    timer_f = f.time_evaluator(f.entry_name, dev, number=num_runs)\n    t = timer_f(a, b, c).mean\n    GOPS = num_ops / (t * 1e3) / 1e6\n    print(\"average time cost of %d runs = %g ms, %g GOPS.\" % (num_runs, t * 1e3, GOPS))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/reduce/test_reduce_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import nvcc\nimport numpy as np\n\nfrom tvm import topi\n\n\nTASK = \"reduce_map\"\nUSE_MANUAL_CODE = False\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef test_reduce_map(in_shape, axis, keepdims, type=\"sum\", test_id=0):\n    global TASK\n    # Build the logic and compile the function\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    if type == \"sum\":\n        TASK = \"sum_map_id%d\" % test_id\n        B = topi.sum(A, axis=axis, keepdims=keepdims)\n    elif type == \"max\":\n        TASK = \"max_map_id%d\" % test_id\n        B = topi.max(A, axis=axis, keepdims=keepdims)\n    elif type == \"min\":\n        TASK = \"min_map_id%d\" % test_id\n        B = topi.min(A, axis=axis, keepdims=keepdims)\n    else:\n        raise NotImplementedError\n    s = topi.cuda.schedule_reduce(B)\n    with tvm.transform.PassContext(\n        config={\n            \"tir.UnrollLoop\": {\n                \"auto_max_step\": 16,\n            }\n        }\n    ):\n        fcuda = tvm.build(s, [A, B], \"cuda\", name=\"sum\")\n\n    # Test\n    in_npy = np.random.normal(size=in_shape).astype(np.float32)\n    if type == \"sum\":\n        out_npy = in_npy.sum(axis=axis, keepdims=keepdims)\n    elif type == \"max\":\n        out_npy = in_npy.max(axis=axis, keepdims=keepdims)\n    elif type == \"min\":\n        out_npy = in_npy.min(axis=axis, keepdims=keepdims)\n    else:\n        raise NotImplementedError\n\n    data_tvm = tvm.nd.array(in_npy, device=tvm.cuda())\n    out_tvm = tvm.nd.empty(shape=out_npy.shape, device=tvm.cuda())\n\n    for _ in range(2):\n        fcuda(data_tvm, out_tvm)\n    tvm.testing.assert_allclose(out_tvm.numpy(), out_npy, rtol=4e-4, atol=4e-4)\n\n\nif __name__ == \"__main__\":\n    test_reduce_map(\n        in_shape=(128, 24, 128, 24), axis=(1, 2, 3), keepdims=True, type=\"sum\", test_id=0\n    )\n    test_reduce_map(in_shape=(128, 24 * 128 * 24), axis=(1,), keepdims=False, type=\"max\", test_id=1)\n    test_reduce_map(in_shape=(32, 128, 24), axis=None, keepdims=True, type=\"sum\", test_id=2)\n    test_reduce_map(in_shape=(128, 24, 128, 24), axis=(0, 2), keepdims=False, type=\"min\", test_id=3)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/rnn/lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"LSTM Example, still work in progress..\"\"\"\nimport tvm\nfrom tvm import te\nimport os\nfrom tvm.contrib import nvcc\nimport numpy as np\n\n# Quick knobs\nTASK = \"lstm\"\nUSE_MANUAL_CODE = False\nPERSIST_KERNEL = True\nDETECT_GLOBAL_BARRIER = PERSIST_KERNEL\nSKIP_CHECK = False\nUNROLL_WLOAD = True\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    \"\"\"Use nvcc compiler for better perf.\"\"\"\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef lstm():\n    if not PERSIST_KERNEL:\n        raise ValueError(\"Non persist LSTM not yet supported\")\n    num_thread_y = 8\n    num_thread_x = 16 * 3 // 2\n    num_sm = 24\n    n_num_step = 128\n    num_step = te.var(\"num_step\")\n    num_hidden = 1152 // 2\n    batch_size = 1\n    # Global transition matrix\n    # Input hidden channel can be pre-caculated by a gemm\n    Xi2h = te.placeholder((num_step, batch_size, 4, num_hidden), name=\"Xi2h\")\n    # Only handle hidden transition, saves space.\n    Wh2h = te.placeholder((4, num_hidden, num_hidden), name=\"Wh2h\")\n    # h: output hidden state, c: cell state.\n    s_state_h = te.placeholder((num_step, batch_size, num_hidden))\n    s_state_c = te.placeholder((num_step, batch_size, num_hidden))\n    s_init_c = te.compute((1, batch_size, num_hidden), lambda *i: 0.0, name=\"init_c\")\n    s_init_h = te.compute((1, batch_size, num_hidden), lambda *i: 0.0, name=\"init_h\")\n    # LSTM transition\n    k = te.reduce_axis((0, num_hidden), name=\"ki2h\")\n    s_h2h = te.compute(\n        (num_step, batch_size, 4, num_hidden),\n        lambda t, i, x, j: te.sum(s_state_h[t - 1, i, k] * Wh2h[x, j, k], axis=k),\n        name=\"s_h2h\",\n    )\n    # Gate rules\n    gates = te.compute(Xi2h.shape, lambda *i: Xi2h(*i) + s_h2h(*i), name=\"gates\")\n    gshape = (num_step, batch_size, num_hidden)\n    in_gate = te.compute(gshape, lambda t, i, j: te.sigmoid(gates[t, i, 0, j]), name=\"in_gate\")\n    in_transform = te.compute(\n        gshape, lambda t, i, j: te.tanh(gates[t, i, 1, j]), name=\"in_transform\"\n    )\n    forget_gate = te.compute(\n        gshape, lambda t, i, j: te.sigmoid(gates[t, i, 2, j]), name=\"forget_gate\"\n    )\n    out_gate = te.compute(gshape, lambda t, i, j: te.sigmoid(gates[t, i, 3, j]), name=\"out_gate\")\n    next_c = te.compute(\n        gshape,\n        lambda t, i, j: forget_gate[t, i, j] * s_state_c[t - 1, i, j]\n        + in_gate[t, i, j] * in_transform[t, i, j],\n        name=\"next_c\",\n    )\n    next_h = te.compute(\n        gshape, lambda t, i, j: out_gate[t, i, j] * te.tanh(next_c[t, i, j]), name=\"next_h\"\n    )\n    update_c = te.compute(gshape, lambda *i: next_c(*i), name=\"update_c\")\n    update_h = te.compute(gshape, lambda *i: next_h(*i), name=\"update_h\")\n    # schedule\n    scan_h, scan_c = tvm.te.scan(\n        [s_init_h, s_init_c],\n        [update_h, update_c],\n        [s_state_h, s_state_c],\n        inputs=[Xi2h],\n        name=\"lstm_scan\",\n    )\n    # schedule\n    s = te.create_schedule(scan_h.op)\n    # Inline gate computations\n    s[gates].compute_inline()\n    s[in_gate].compute_inline()\n    s[in_transform].compute_inline()\n    s[forget_gate].compute_inline()\n    s[out_gate].compute_inline()\n\n    block_x = te.thread_axis((0, num_sm), \"blockIdx.x\")\n    thread_x = te.thread_axis((0, num_thread_x), \"threadIdx.x\")\n    thread_y = te.thread_axis((0, num_thread_y), \"threadIdx.y\")\n\n    s_state_h_S = s.cache_read(s_state_h, \"shared\", [s_h2h])\n    s_state_c_S = s.cache_read(s_state_c, \"shared\", [next_c])\n    Wh2hL = s.cache_read(Wh2h, \"local\", [s_h2h])\n\n    ko, ki = s[s_h2h].split(s[s_h2h].op.reduce_axis[0], nparts=num_thread_y)\n    s_h2h_rf = s.rfactor(s_h2h, ko)\n    s[s_h2h].bind(s[s_h2h].op.reduce_axis[0], thread_y)\n    s[s_h2h_rf].compute_at(s[s_h2h], s[s_h2h].op.reduce_axis[0])\n\n    if PERSIST_KERNEL:\n        s[scan_h.op].env_threads([block_x, thread_y, thread_x])\n        s[Wh2hL].compute_at(s[scan_h.op], thread_x)\n    else:\n        s[Wh2hL].compute_at(s[s_h2h], s[s_h2h].op.axis[3])\n\n    if UNROLL_WLOAD:\n        s[Wh2hL].unroll(Wh2hL.op.axis[0])\n        s[Wh2hL].unroll(Wh2hL.op.axis[2])\n\n    s[s_state_h_S].compute_at(s[s_h2h_rf], s[s_h2h_rf].op.axis[3])\n    s[s_state_c_S].compute_at(s[scan_h.op], s[scan_h].op.scan_axis)\n\n    for ss in [s_state_h_S]:\n        xo, xi = s[ss].split(ss.op.axis[2], factor=num_thread_x * num_thread_y)\n        ty, xi = s[ss].split(xi, nparts=num_thread_y)\n        tx, xi = s[ss].split(xi, nparts=num_thread_x)\n        s[ss].bind(ty, thread_y)\n        s[ss].bind(tx, thread_x)\n\n    for init in [s_init_c, s_init_h]:\n        bx, xi = s[init].split(init.op.axis[2], nparts=num_sm)\n        tx, xi = s[init].split(xi, nparts=num_thread_x)\n        s[init].bind(bx, block_x)\n        s[init].bind(tx, thread_x)\n\n    s[next_c].set_store_predicate(thread_y.equal(0))\n    s[next_h].set_store_predicate(thread_y.equal(0))\n\n    for update in [update_c, update_h]:\n        bx, xi = s[update].split(s[update].op.axis[2], nparts=num_sm)\n        tx, xi = s[update].split(xi, nparts=num_thread_x)\n        s[update].bind(bx, block_x)\n        s[update].bind(tx, thread_x)\n        s[update].set_store_predicate(thread_y.equal(0))\n\n    # verify we can lower correctly\n    def check_device(target):\n        num_step = n_num_step\n        flstm = tvm.build(s, [Xi2h, Wh2h, scan_h, scan_c], target)\n        dev = tvm.cuda(0) if target == \"cuda\" else tvm.cl(0)\n        # launch the kernel.\n        scan_h_np = np.zeros((num_step, batch_size, num_hidden)).astype(\"float32\")\n        scan_c_np = np.zeros((num_step, batch_size, num_hidden)).astype(\"float32\")\n        Xi2h_np = np.random.normal(size=(num_step, batch_size, 4, num_hidden)).astype(\"float32\")\n        Wh2h_np = np.random.normal(size=(4, num_hidden, num_hidden)).astype(\"float32\")\n        scan_h_a = tvm.nd.array(scan_h_np, dev)\n        scan_c_a = tvm.nd.array(scan_c_np, dev)\n        Xi2h_a = tvm.nd.array(Xi2h_np, dev)\n        Wh2h_a = tvm.nd.array(Wh2h_np, dev)\n        flstm(Xi2h_a, Wh2h_a, scan_h_a, scan_c_a)\n        dev.sync()\n        # measure time cost of second step.\n        evaluator = flstm.time_evaluator(flstm.entry_name, dev, 1, repeat=1000)\n        eval_result = evaluator(Xi2h_a, Wh2h_a, scan_h_a, scan_c_a)\n        print(\"Time cost=%g\" % eval_result.mean)\n\n    # set unroll_explicit for more readable code.\n    with tvm.transform.PassContext(\n        config={\n            \"tir.UnrollLoop\": {\n                \"auto_max_step\": 128,\n            },\n            \"tir.detect_global_barrier\": DETECT_GLOBAL_BARRIER,\n        }\n    ):\n        check_device(\"cuda\")\n\n\nif __name__ == \"__main__\":\n    lstm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/topi_recipe/rnn/matexp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Matrix exponential example.\n\nThis is an example for matrix exponential,\nwhich calculates the following recursion formula\n\n```math\nX[t] = dot(X[t-1], W)\n```\n\"\"\"\nimport tvm\nfrom tvm import te\nimport time\nimport os\nimport argparse\nfrom tvm.contrib import nvcc\nimport numpy as np\n\n# Quick knobs\nTASK = \"matexp\"\nUSE_MANUAL_CODE = False\nPERSIST_KERNEL = True\nDETECT_GLOBAL_BARRIER = PERSIST_KERNEL\nSKIP_CHECK = False\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    \"\"\"Use nvcc compiler for better perf.\"\"\"\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef write_code(code, fname):\n    with open(fname, \"w\") as f:\n        f.write(code)\n\n\n@tvm.register_func\ndef tvm_callback_cuda_postproc(code):\n    if not os.path.exists(\"perf\"):\n        os.mkdir(\"perf\")\n    write_code(code, \"perf/%s_generated.cu\" % TASK)\n    if USE_MANUAL_CODE:\n        code = open(\"perf/%s_manual.cu\" % TASK).read()\n    return code\n\n\ndef rnn_matexp():\n    n_num_step = 128\n    n_num_hidden = 1152\n    n_batch_size = 4\n    detect_global_barrier = DETECT_GLOBAL_BARRIER\n\n    num_step = te.var(\"num_step\")\n    num_hidden = tvm.runtime.convert(n_num_hidden)\n    batch_size = tvm.runtime.convert(n_batch_size)\n    num_thread_y = 8\n    num_thread_x = 16 * 3\n    num_sm = 24\n\n    Whh = te.placeholder((num_hidden, num_hidden), name=\"Whh\")\n    s_init = te.compute((1, batch_size, num_hidden), lambda _, i, j: 1.0, name=\"init\")\n    s_state = te.placeholder((num_step, batch_size, num_hidden))\n    kh = te.reduce_axis((0, num_hidden), name=\"kh\")\n    s_update = te.compute(\n        (num_step, batch_size, num_hidden),\n        lambda t, i, j: te.sum(s_state[t - 1, i, kh] * Whh[kh, j], axis=kh),\n        name=\"update\",\n    )\n    s_scan = tvm.te.scan(s_init, s_update, s_state)\n    # schedule\n    s = te.create_schedule(s_scan.op)\n    CL = s_update\n    SS = s.cache_read(s_state, \"shared\", [CL])\n    SL = s.cache_read(SS, \"local\", [CL])\n    WhhL = s.cache_read(Whh, \"local\", [CL])\n    ko, ki = s[CL].split(s[CL].op.reduce_axis[0], nparts=num_thread_y)\n    CLF = s.rfactor(CL, ko)\n\n    block_x = te.thread_axis((0, num_sm), \"blockIdx.x\")\n    thread_x = te.thread_axis((0, num_thread_x), \"threadIdx.x\")\n    thread_y = te.thread_axis((0, num_thread_y), \"threadIdx.y\")\n    if PERSIST_KERNEL:\n        s[s_scan.op].env_threads([block_x, thread_y, thread_x])\n\n    bx, xi = s[s_init].split(s_init.op.axis[2], nparts=num_sm)\n    tx, xi = s[s_init].split(xi, nparts=num_thread_x)\n    s[s_init].bind(bx, block_x)\n    s[s_init].bind(tx, thread_x)\n\n    bx, xi = s[s_update].split(s[CL].op.axis[2], nparts=num_sm)\n    tx, xi = s[s_update].split(xi, nparts=num_thread_x)\n    s[s_update].bind(bx, block_x)\n    s[s_update].bind(tx, thread_x)\n    s[CL].bind(s[CL].op.reduce_axis[0], thread_y)\n    s[CLF].compute_at(s[CL], s[CL].op.reduce_axis[0])\n    # Duplicate store predicate.\n    s[CL].set_store_predicate(thread_y.equal(0))\n\n    if PERSIST_KERNEL:\n        s[WhhL].compute_at(s[s_scan], thread_x)\n        s[WhhL].unroll(WhhL.op.axis[0])\n    else:\n        s[WhhL].compute_at(s[CLF], CLF.op.axis[3])\n\n    kr, ki = s[CLF].split(CLF.op.reduce_axis[0], nparts=1)\n    ko, ki = s[CLF].split(ki, factor=4)\n    s[SS].compute_at(s[CLF], kr)\n    s[SL].compute_at(s[CLF], ko)\n\n    xo, xi = s[SS].split(SS.op.axis[2], factor=num_thread_x * num_thread_y * 3)\n    ty, xi = s[SS].split(xi, nparts=num_thread_y)\n    tx, xi = s[SS].split(xi, nparts=num_thread_x)\n    s[SS].bind(ty, thread_y)\n    s[SS].bind(tx, thread_x)\n\n    def check_device(target):\n        with tvm.transform.PassContext(\n            config={\n                \"tir.UnrollLoop\": {\n                    \"auto_max_step\": 128,\n                },\n                \"tir.detect_global_barrier\": detect_global_barrier,\n            }\n        ):\n            f = tvm.build(s, [s_scan, Whh], target)\n        dev = tvm.cuda(0) if target == \"cuda\" else tvm.cl(0)\n        # launch the kernel.\n        res_np = np.zeros((n_num_step, n_batch_size, n_num_hidden)).astype(\"float32\")\n        Whh_np = np.zeros((n_num_hidden, n_num_hidden)).astype(\"float32\")\n        Whh_np[:] = 2.0 / n_num_hidden\n        Whh_np[:, n_num_hidden // 2 :] = 0\n\n        res_a = tvm.nd.array(res_np, dev)\n        Whh_a = tvm.nd.array(Whh_np, dev)\n        # Skip first pass as it is compilation\n        f(res_a, Whh_a)\n        dev.sync()\n        # measure time cost of second step.\n        tstart = time.time()\n        f(res_a, Whh_a)\n        dev.sync()\n        tgap = time.time() - tstart\n        print(\"Time cost=%g\" % tgap)\n        # correctness\n        if not SKIP_CHECK:\n            res_cuda = res_a.numpy()\n            res_cmp = np.ones_like(res_np).astype(\"float64\")\n            Whh_np = Whh_np.astype(\"float64\")\n            for t in range(1, n_num_step):\n                res_cmp[t][:] = np.dot(res_cmp[t - 1], Whh_np)\n            for i in range(n_num_step):\n                for j in range(n_num_hidden):\n                    if abs(res_cmp[i, 0, j] - res_cuda[i, 0, j]) > 1e-5:\n                        print(\"%d, %d: %g vs %g\" % (i, j, res_cmp[i, 0, j], res_cuda[i, 0, j]))\n            tvm.testing.assert_allclose(res_cuda, res_cmp, rtol=1e-3)\n\n    check_device(\"cuda\")\n\n\nif __name__ == \"__main__\":\n    rnn_matexp()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n\nTemplate files for UMA tutorial\n\n\n\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/backend.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"UMA backend for the my_ai_hw accelerator\"\"\"\nfrom passes import MyAiHwConv2dPass\nfrom tvm.relay.backend.contrib.uma.api.utils import PassPhase\nfrom tvm.relay.backend.contrib.uma.backend import UMABackend\nfrom codegen import gen_includes\nfrom patterns import conv2d_pattern\n\n\nclass MyAiHwBackend(UMABackend):\n    \"\"\"UMA backend for the MyAiHw accelerator.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n\n        # Target configuration\n        self._register_target_attr(\"dimension\")\n\n        # Relay Pattern registration\n        self._register_pattern(\"conv2d\", conv2d_pattern())\n\n        # Relay to TIR function registration\n        self._register_tir_pass(PassPhase.TIR_PHASE_0, MyAiHwConv2dPass())\n\n        # TIR to runtime function registration\n        self._register_codegen(fmt=\"c\", includes=gen_includes)\n\n    @property\n    def target_name(self):\n        return \"my_ai_hw\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"UMA codegen for the my_ai_hw accelerator\"\"\"\n\nimport tvm\nimport pathlib\n\n\ndef gen_includes() -> str:\n    topdir = pathlib.Path(__file__).parent.absolute()\n\n    includes = \"\"\n    includes += f'#include \"{topdir}/conv2dnchw.cc\"'\n    return includes\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/passes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Transform passes for the my_ai_hw accelerator\"\"\"\n\nimport tvm\nfrom tvm import tir\nfrom tvm.relay.backend.contrib.uma.api.utils import add_llvm_to_block\n\n\n@tvm.tir.transform.prim_func_pass(opt_level=2)\nclass MyAiHwConv2dPass:\n    _EXTERNAL_FUNCTION_NAME = \"my_ai_hw_conv2dnchw\"\n    _TVM_BLOCK_MATCH_NAME = \"conv2d_nchw\"\n\n    def transform_function(\n        self, func: tvm.tir.PrimFunc, mod: tvm.ir.IRModule, ctx: tvm.ir.transform.PassContext\n    ) -> tvm.tir.PrimFunc:\n        return self._my_ai_hw_conv2d_pass(func, mod, ctx)\n\n    @classmethod\n    def _my_ai_hw_conv2d_pass(cls, func, mod, ctx):\n        _loops = dict()\n        _handles = []\n        _entry_node = None\n\n        def _has_block(name: str, func: tvm.tir.PrimFunc) -> bool:\n            \"\"\"\n            Determine of a tir.block with `name` exists in `func`\n            \"\"\"\n\n            def _hb(op):\n                if isinstance(op, tvm.tir.Block):\n                    _found_blocks.append(op.name_hint)\n\n            _found_blocks = []\n            tvm.tir.stmt_functor.post_order_visit(func.body, _hb)\n            return name in _found_blocks\n\n        def _detect_and_replace_conv2d(\n            func: tvm.tir.PrimFunc, mod: tvm.ir.IRModule, ctx: tvm.ir.transform.PassContext\n        ) -> tvm.tir.PrimFunc:\n            def _replace_conv2d(op):\n                if op == _entry_node:\n                    irb = tvm.tir.ir_builder.create()\n                    # Collection of buffer address\n                    buffers = [b[1].data for b in _handles]\n                    # extraction of loop offsets\n                    for k, v in _loops.items():\n                        assert v.min.value == 0\n                    offset_order = [\"co\", \"w\", \"h\", \"ci\", \"kh\", \"kw\"]\n                    offsets = [_loops[i].extent.value for i in offset_order]\n                    args = buffers + offsets\n                    irb.emit(tir_call(irb, True, cls._EXTERNAL_FUNCTION_NAME, *args))\n                    irb_result = irb.get()\n                    return irb_result\n                elif isinstance(op, tvm.tir.SeqStmt):\n                    # Remove that pad block of TOPI's conv2DNCHW by only returning the 2nd statement\n                    return op.seq[1]\n                return op\n\n            sch = tir.Schedule(func)\n\n            if _has_block(cls._TVM_BLOCK_MATCH_NAME, func):\n                conv2d_block = sch.get_block(cls._TVM_BLOCK_MATCH_NAME)\n                rv_loops = sch.get_loops(conv2d_block)\n                assert len(rv_loops) == 7\n                loops = dict(\n                    n=rv_loops[0],\n                    co=rv_loops[1],\n                    h=rv_loops[2],\n                    w=rv_loops[3],\n                    ci=rv_loops[4],\n                    kh=rv_loops[5],\n                    kw=rv_loops[6],\n                )\n                _entry_node = sch.get(rv_loops[1])\n                _loops = {k: sch.get(v) for k, v in loops.items()}\n                _handles = func.buffer_map.items()\n\n                x = tvm.tir.stmt_functor.ir_transform(\n                    func.body, None, _replace_conv2d, [\"tir.For\", \"tir.SeqStmt\"]\n                )\n                return func.with_body(x)\n            else:\n                return func\n\n        r = _detect_and_replace_conv2d(func, mod, ctx)\n        return r\n\n\ndef tir_call(ib: tvm.tir.ir_builder, extern: bool, name: str, *args):\n    \"\"\"\n    ib: ir_builder\n    extern: bool\n        True  --> tvm.tir.call_extern\n        False --> tvm.tir.call_packed\n    name: str\n        function name\n    *args:\n        arguments for function call\n    \"\"\"\n\n    def buf_from_array(ib, arr, dtype):\n        # Allocate enough memory to store the whole array\n        var = ib.allocate(\"int32\", (len(arr),), scope=\"global\")\n        for i, v in enumerate(arr):\n            var[i] = v\n        # Declare a buffer, which is basically a view on the chunk of memory that we allocated\n        buf = tvm.tir.decl_buffer((len(arr),), dtype, data=var, scope=\"global\")\n        return buf\n\n    if extern:\n        args = [i.data if isinstance(i, tvm.tir.Buffer) else i for i in args]\n        return tvm.tir.call_extern(\"int32\", name, *args)\n    else:\n        args = [\n            buf_from_array(ib, i, \"int32\")\n            if isinstance(i, (tuple, list, tvm.ir.container.Array))\n            else i\n            for i in args\n        ]\n        return tvm.tir.call_packed(name, *args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/patterns.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Relay graph patterns for the my_ai_hw accelerator\"\"\"\n\nfrom tvm.relay.dataflow_pattern import is_op, wildcard\n\n\ndef conv2d_pattern():\n    pattern = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    pattern = pattern.has_attr({\"strides\": [1, 1], \"groups\": 1})\n    return pattern\n\n\ndef dense_pattern():\n    pattern = is_op(\"nn.dense\")(wildcard(), wildcard())\n    return pattern\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/run.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.micro.testing.aot_test_utils import AOT_DEFAULT_RUNNER\nimport tvm\nfrom tvm import relay\nfrom backend import MyAiHwBackend\nfrom tvm.relay import transform\nfrom collections import OrderedDict\nimport numpy as np\n\n\nfrom tvm.testing.aot import (\n    AOTTestModel as AOTModel,\n    AOTTestRunner as AOTRunner,\n    generate_ref_data,\n    compile_and_run,\n)\n\n\ndef create_conv2d(groups=1, runner=AOT_DEFAULT_RUNNER, weight_shape=32):\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, weight_shape, 3, 3)\n    pass_config = {\"tir.usmp.enable\": True}\n    runner = AOTRunner(\n        makefile=runner.makefile,\n        prologue=runner.prologue,\n        epilogue=runner.epilogue,\n        includes=runner.includes,\n        parameters=runner.parameters,\n        pass_config=pass_config,\n    )\n    data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight0 = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=groups)\n    main_f = relay.Function([data0, weight0], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = main_f\n    mod = transform.InferType()(mod)\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, wshape).astype(dtype)\n    inputs = OrderedDict([(\"data\", i_data), (\"weight\", w1_data)])\n    output_list = generate_ref_data(mod, inputs)\n    return mod, inputs, output_list, runner\n\n\ndef main():\n    mod, inputs, output_list, runner = create_conv2d()\n\n    uma_backend = MyAiHwBackend()\n    uma_backend.register()\n    mod = uma_backend.partition(mod)\n    target = tvm.target.Target(\"my_ai_hw\", host=tvm.target.Target(\"c\"))\n\n    export_directory = tvm.contrib.utils.tempdir(keep_for_debug=True).path\n    print(f\"Generated files are in {export_directory}\")\n    compile_and_run(\n        AOTModel(module=mod, inputs=inputs, outputs=output_list),\n        runner,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target=target,\n        test_dir=str(export_directory),\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/_template/strategies.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Strategies for the my_ai_hw accelerator\"\"\"\n\n# Example how to integrate a custom conv1d strategy:\n\n# @relay.op.strategy.override_native_generic_func(\"custom_conv1d_strategy\")\n# def custom_conv1d_strategy(attrs, inputs, out_type, target):\n#     strategy = _op.OpStrategy()\n#     strategy.add_implementation(\n#         wrap_compute_conv1d(custom_conv1d_compute),\n#         wrap_topi_schedule(custom_conv1d_schedule),\n#         name=\"custom_conv1d.generic\",\n#     return strategy\n#\n\n# For further details see:\n# - github.com/apache/tvm-rfcs/blob/main/rfcs/0060_UMA_Unified_Modular_Accelerator_Interface.md\n# - $TVM_HOME/python/tvm/relay/op/strategy/x86.py\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/uma/uma_cli.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\n    UMA Command Line Interface (CLI)\n\n    Tool to create code skeletons for an easy integration of\n    new AI hardware accelerators/libraries into TVM using UMA\n\"\"\"\n\nimport argparse\nimport os\nimport shutil\nimport sys\nimport pathlib\nfrom inflection import camelize, underscore\n\n\ndef _parse_args():\n    parser = argparse.ArgumentParser(description=\"UMA Interface command line interface\")\n    parser.add_argument(\n        \"--add_hardware\",\n        type=str,\n        required=True,\n    )\n    parser.add_argument(\n        \"--tutorial\",\n        type=str,\n    )\n    args = parser.parse_args()\n    return args\n\n\ndef replace_template_name(\n    files: list, template_name: str, add_hw_name: str, template_source: str = \"_template\"\n) -> None:\n    \"\"\"\n    Replace names in template skeleton code by new name\n    \"\"\"\n    for f in files:\n        with open(f) as read_file:\n            data = read_file.read()\n        for case in [underscore, camelize]:\n            data = data.replace(case(template_name), case(add_hw_name))\n        data = data.replace(template_source, underscore(add_hw_name))\n        with open(f, \"w\") as write_file:\n            write_file.write(data)\n\n\ndef main():\n    \"\"\"\n    UMA Command Line Interface (CLI)\n    \"\"\"\n    args = _parse_args()\n    add_hw_name = args.add_hardware\n    uma_template_path = pathlib.Path(os.getcwd(), \"_template\").absolute()\n\n    add_hw_path = os.path.join(uma_template_path.parent, add_hw_name)\n    if os.path.exists(add_hw_path):\n        print(\n            f\"Hardware with name {add_hw_name} already exists in UMA file structure: {add_hw_path}\"\n        )\n        sys.exit(-1)\n    else:\n        os.mkdir(add_hw_path)\n\n    uma_files = [\"backend.py\", \"codegen.py\", \"passes.py\", \"patterns.py\", \"run.py\", \"strategies.py\"]\n    if args.tutorial == \"vanilla\":\n        uma_files.append(\"conv2dnchw.cc\")\n\n    source_files = [os.path.join(uma_template_path, f) for f in uma_files]\n    destination_files = [os.path.join(add_hw_path, f) for f in uma_files]\n\n    for src, dst in zip(source_files, destination_files):\n        shutil.copyfile(src, dst)\n\n    template_name = \"my_ai_hw\"\n    replace_template_name(destination_files, template_name, add_hw_name)\n\n    print(f\"Success: added {add_hw_name} to {add_hw_path}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-graph/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nfn main() {\n    let out_dir = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lib\");\n    println!(\"cargo:rustc-link-search=native={}\", out_dir);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-graph/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#[macro_use]\nextern crate lazy_static;\n#[macro_use]\nextern crate serde_derive;\n\nmod types;\nmod utils;\n\nuse std::{collections::HashMap, convert::TryFrom, env, sync::Mutex};\n\nuse tvm_graph_rt::{Graph, GraphExecutor, SystemLibModule, Tensor as TVMTensor};\n\nuse types::Tensor;\n\nextern \"C\" {\n    fn __wasm_call_ctors();\n}\n\nlazy_static! {\n    static ref SYSLIB: SystemLibModule = SystemLibModule::default();\n    static ref GRAPH_EXECUTOR: Mutex<GraphExecutor<'static, 'static>> = {\n        unsafe {\n            // This is necessary to invoke TVMBackendRegisterSystemLibSymbol\n            // API calls.\n            __wasm_call_ctors();\n        }\n        let graph = Graph::try_from(include_str!(concat!(\n            env!(\"CARGO_MANIFEST_DIR\"),\n            \"/lib/graph.json\"\n        )))\n        .unwrap();\n\n        let params_bytes =\n            include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lib/graph.params\"));\n        let params = tvm_graph_rt::load_param_dict(params_bytes)\n            .unwrap()\n            .into_iter()\n            .map(|(k, v)| (k, v.to_owned()))\n            .collect::<HashMap<String, TVMTensor<'static>>>();\n\n        let mut exec = GraphExecutor::new(graph, &*SYSLIB).unwrap();\n\n        exec.load_params(params);\n\n        Mutex::new(exec)\n    };\n}\n\n#[no_mangle]\npub extern \"C\" fn run(wasm_addr: i32, in_size: i32) -> i32 {\n    let in_tensor = unsafe { utils::load_input(wasm_addr, in_size as usize) };\n    let input: TVMTensor = in_tensor.as_dltensor().into();\n\n    // since this executor is not multi-threaded, we can acquire lock once\n    let mut executor = GRAPH_EXECUTOR.lock().unwrap();\n\n    executor.set_input(\"data\", input);\n\n    executor.run();\n\n    let output = executor.get_output(0).unwrap().as_dltensor(false);\n\n    let out_tensor: Tensor = output.into();\n    let out_size = unsafe { utils::store_output(wasm_addr, out_tensor) };\n    out_size as i32\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-graph/src/types.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    any::TypeId,\n    os::raw::{c_int, c_void},\n    slice,\n};\npub use tvm_sys::ffi::DLTensor;\nuse tvm_sys::ffi::{\n    DLDataType, DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDevice, DLDeviceType_kDLCPU,\n};\n\n#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]\npub enum DataType {\n    FP32,\n    INT32,\n    INT8,\n}\n\nimpl DataType {\n    pub fn as_dldtype(&self) -> DLDataType {\n        match self {\n            DataType::INT32 => DLDataType {\n                code: DLDataTypeCode_kDLInt as u8,\n                bits: 32u8,\n                lanes: 1u16,\n            },\n            DataType::INT8 => DLDataType {\n                code: DLDataTypeCode_kDLInt as u8,\n                bits: 8u8,\n                lanes: 1u16,\n            },\n            DataType::FP32 => DLDataType {\n                code: DLDataTypeCode_kDLFloat as u8,\n                bits: 32u8,\n                lanes: 1u16,\n            },\n        }\n    }\n\n    /// Returns whether this `DataType` represents primitive type `T`.\n    pub fn is_type<T: 'static>(&self) -> bool {\n        let typ = TypeId::of::<T>();\n        typ == TypeId::of::<i32>() || typ == TypeId::of::<i8>() || typ == TypeId::of::<f32>()\n    }\n}\n\nimpl From<DLDataType> for DataType {\n    fn from(dl_dtype: DLDataType) -> Self {\n        if dl_dtype.code == DLDataTypeCode_kDLInt as u8 && dl_dtype.bits == 32u8 {\n            DataType::INT32\n        } else if dl_dtype.code == DLDataTypeCode_kDLInt as u8 && dl_dtype.bits == 8u8 {\n            DataType::INT8\n        } else if dl_dtype.code == DLDataTypeCode_kDLFloat as u8 && dl_dtype.bits == 32u8 {\n            DataType::FP32\n        } else {\n            DataType::FP32\n        }\n    }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct Tensor {\n    pub(crate) dtype: DataType,\n    pub(crate) shape: Vec<i64>,\n    pub(crate) strides: Option<Vec<usize>>,\n    pub(crate) data: Vec<u8>,\n}\n\n#[allow(dead_code)]\nimpl Tensor {\n    pub fn new(dtype: DataType, shape: Vec<i64>, strides: Vec<usize>, data: Vec<u8>) -> Self {\n        Tensor {\n            dtype,\n            shape,\n            strides: Some(strides),\n            data,\n        }\n    }\n\n    pub fn dtype(&self) -> DataType {\n        self.dtype.clone()\n    }\n\n    pub fn ndim(&self) -> usize {\n        self.shape.len()\n    }\n\n    pub fn shape(&self) -> Vec<i64> {\n        self.shape.clone()\n    }\n\n    pub fn data(&self) -> Vec<u8> {\n        self.data.clone()\n    }\n\n    pub fn as_dltensor(&self) -> DLTensor {\n        DLTensor {\n            data: self.data.as_ptr() as *mut c_void,\n            device: DLDevice {\n                device_type: DLDeviceType_kDLCPU,\n                device_id: 0 as c_int,\n            },\n            ndim: self.shape.len() as c_int,\n            dtype: self.dtype().as_dldtype(),\n            shape: self.shape.as_ptr() as *mut i64,\n            strides: self.strides.as_ref().unwrap().as_ptr() as *mut i64,\n            byte_offset: 0,\n            ..Default::default()\n        }\n    }\n\n    /// Returns the data of this `Tensor` as a `Vec`.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the `Tensor` does not contain elements of type `T`.\n    pub fn to_vec<T: 'static + std::fmt::Debug + Clone>(&self) -> Vec<T> {\n        assert!(self.dtype().is_type::<T>());\n\n        unsafe {\n            slice::from_raw_parts(\n                self.data().as_ptr() as *const T,\n                self.shape().iter().map(|v| *v as usize).product::<usize>() as usize,\n            )\n            .to_vec()\n        }\n    }\n}\n\nimpl Default for Tensor {\n    fn default() -> Self {\n        Self {\n            dtype: DataType::FP32,\n            shape: Vec::new(),\n            strides: None,\n            data: Vec::new(),\n        }\n    }\n}\n\nimpl From<DLTensor> for Tensor {\n    fn from(dlt: DLTensor) -> Self {\n        unsafe {\n            let shape = slice::from_raw_parts_mut(dlt.shape, dlt.ndim as usize).to_vec();\n            let size = shape.iter().map(|v| *v as usize).product::<usize>() as usize;\n            let itemsize: usize = (dlt.dtype.bits >> 3).into();\n            let data = slice::from_raw_parts(dlt.data as *const u8, size * itemsize).to_vec();\n\n            Self {\n                dtype: DataType::from(dlt.dtype),\n                shape,\n                strides: if dlt.strides.is_null() {\n                    None\n                } else {\n                    Some(\n                        slice::from_raw_parts_mut(dlt.strides as *mut usize, dlt.ndim as usize)\n                            .to_vec(),\n                    )\n                },\n                data,\n            }\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-graph/src/utils.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse super::types::*;\nuse serde_json;\nuse std::ptr;\n\npub unsafe fn load_input(in_addr: i32, in_size: usize) -> Tensor {\n    let in_addr = in_addr as *mut u8;\n\n    println!(\"DEBUG: in_addr {:?}, in_size {:?}\", in_addr, in_size);\n\n    let data_vec = unsafe { std::slice::from_raw_parts(in_addr, in_size) };\n\n    let input = serde_json::from_slice(&data_vec);\n    match input {\n        Ok(result) => {\n            println!(\"DEBUG: SER SUCCEED!!! and Ok\");\n            result\n        }\n        Err(e) => {\n            panic!(\"DEBUG: SER SUCCEED!!! but Err, {:?}\", &e);\n        }\n    }\n}\n\npub unsafe fn store_output(out_addr: i32, output: Tensor) -> usize {\n    let out_addr = out_addr as *mut u8;\n\n    let data_vec = serde_json::to_vec(&output).unwrap();\n    let data_size = data_vec.len();\n    for i in 0..data_size {\n        ptr::write(out_addr.offset(i as isize), *data_vec.get(i).unwrap());\n    }\n\n    data_size\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-graph/tools/build_graph_lib.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Builds a simple resnet50 graph for testing.\"\"\"\nimport argparse\nimport os\nimport subprocess\nimport sys\n\nimport onnx\nimport tvm\nfrom tvm import relay, runtime\nfrom tvm.contrib.download import download_testdata\nfrom tvm.contrib import graph_executor\n\nfrom PIL import Image\nimport numpy as np\nimport tvm.relay as relay\n\n# This example uses resnet50-v2-7 model\nmodel_url = (\n    \"https://github.com/onnx/models/raw/main/\"\n    \"vision/classification/resnet/model/\"\n    \"resnet50-v2-7.onnx\"\n)\n\n\ndef build_graph_lib(opt_level):\n    \"\"\"Compiles the pre-trained model with TVM\"\"\"\n    out_dir = os.path.join(sys.path[0], \"../lib\")\n    if not os.path.exists(out_dir):\n        os.makedirs(out_dir)\n\n    # Follow the tutorial to download and compile the model\n    model_path = download_testdata(model_url, \"resnet50-v2-7.onnx\", module=\"onnx\")\n    onnx_model = onnx.load(model_path)\n\n    img_url = \"https://s3.amazonaws.com/model-server/inputs/kitten.jpg\"\n    img_path = download_testdata(img_url, \"imagenet_cat.png\", module=\"data\")\n\n    # Resize it to 224x224\n    resized_image = Image.open(img_path).resize((224, 224))\n    img_data = np.asarray(resized_image).astype(\"float32\")\n\n    # Our input image is in HWC layout while ONNX expects CHW input, so convert the array\n    img_data = np.transpose(img_data, (2, 0, 1))\n\n    # Normalize according to the ImageNet input specification\n    imagenet_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))\n    imagenet_stddev = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))\n    norm_img_data = (img_data / 255 - imagenet_mean) / imagenet_stddev\n\n    # Add the batch dimension, as we are expecting 4-dimensional input: NCHW.\n    img_data = np.expand_dims(norm_img_data, axis=0)\n\n    input_name = \"data\"\n    shape_dict = {input_name: img_data.shape}\n\n    mod, params = relay.frontend.from_onnx(onnx_model, shape_dict)\n    target = \"llvm -mtriple=wasm32-unknown-unknown -mattr=+simd128\"\n\n    with tvm.transform.PassContext(opt_level=opt_level):\n        factory = relay.build(\n            mod,\n            target=target,\n            params=params,\n            runtime=tvm.relay.backend.Runtime(\"cpp\", {\"system-lib\": True}),\n        )\n\n    # Save the model artifacts to obj_file\n    obj_file = os.path.join(out_dir, \"graph.o\")\n    factory.get_lib().save(obj_file)\n\n    # Run llvm-ar to archive obj_file into lib_file\n    lib_file = os.path.join(out_dir, \"libgraph_wasm32.a\")\n    cmds = [os.environ.get(\"LLVM_AR\", \"llvm-ar-10\"), \"rcs\", lib_file, obj_file]\n    subprocess.run(cmds)\n\n    # Save the json and params\n    with open(os.path.join(out_dir, \"graph.json\"), \"w\") as f_graph:\n        f_graph.write(factory.get_graph_json())\n    with open(os.path.join(out_dir, \"graph.params\"), \"wb\") as f_params:\n        f_params.write(runtime.save_param_dict(factory.get_params()))\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"ONNX model build example\")\n    parser.add_argument(\n        \"-O\",\n        \"--opt-level\",\n        type=int,\n        default=0,\n        help=\"level of optimization. 0 is non-optimized and 3 is the highest level\",\n    )\n    args = parser.parse_args()\n\n    build_graph_lib(args.opt_level)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-runtime/src/graph.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse anyhow::Result;\nuse wasmtime::*;\nuse wasmtime_wasi::{WasiCtx, WasiCtxBuilder};\n\nuse super::Tensor;\n\npub struct GraphExecutor {\n    pub(crate) wasm_addr: i32,\n    pub(crate) input_size: i32,\n    pub(crate) output_size: i32,\n    pub(crate) store: Option<Store<WasiCtx>>,\n    // None-WASI version:\n    // pub(crate) store: Option<Store<()>>,\n    pub(crate) instance: Option<Instance>,\n}\n\n#[allow(dead_code)]\nimpl GraphExecutor {\n    pub fn new() -> Self {\n        Self {\n            wasm_addr: 0,\n            input_size: 0,\n            output_size: 0,\n            store: None,\n            instance: None,\n        }\n    }\n\n    pub fn instantiate(&mut self, wasm_graph_file: String) -> Result<()> {\n        // It seems WASI in this example is not necessary\n\n        // None WASI version: works with no SIMD\n        // let engine = Engine::new(Config::new().wasm_simd(true)).unwrap();\n        // let mut store = Store::new(&engine, ());\n        // let module = Module::from_file(store.engine(), &wasm_graph_file)?;\n\n        // let instance = Instance::new(&mut store, &module, &[])?;\n\n        // self.instance = Some(instance);\n        // self.store = Some(store);\n\n        // Ok(())\n\n        // WASI version:\n        let engine = Engine::new(Config::new().wasm_simd(true)).unwrap();\n        // First set up our linker which is going to be linking modules together. We\n        // want our linker to have wasi available, so we set that up here as well.\n        let mut linker = Linker::new(&engine);\n        wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;\n        // Create an instance of `Wasi` which contains a `WasiCtx`. Note that\n        // `WasiCtx` provides a number of ways to configure what the target program\n        // will have access to.\n        let wasi = WasiCtxBuilder::new()\n            .inherit_stdio()\n            .inherit_args()?\n            .build();\n        let mut store = Store::new(&engine, wasi);\n\n        let module = Module::from_file(&engine, &wasm_graph_file)?;\n        self.instance = Some(linker.instantiate(&mut store, &module)?);\n        self.store = Some(store);\n\n        Ok(())\n    }\n\n    pub fn set_input(&mut self, input_data: Tensor) -> Result<()> {\n        let memory = self\n            .instance\n            .as_ref()\n            .unwrap()\n            .get_memory(self.store.as_mut().unwrap(), \"memory\")\n            .ok_or_else(|| anyhow::format_err!(\"failed to find `memory` export\"))?;\n\n        // Specify the wasm address to access the wasm memory.\n        let wasm_addr = memory.data_size(self.store.as_mut().unwrap());\n\n        // Serialize the data into a JSON string.\n        let in_data = serde_json::to_vec(&input_data)?;\n        let in_size = in_data.len();\n\n        // Grow up memory size according to in_size to avoid memory leak.\n        memory.grow(self.store.as_mut().unwrap(), (in_size >> 16) as u32 + 1)?;\n\n        memory.write(self.store.as_mut().unwrap(), wasm_addr, &in_data)?;\n\n        self.wasm_addr = wasm_addr as i32;\n        self.input_size = in_size as i32;\n\n        Ok(())\n    }\n\n    pub fn run(&mut self) -> Result<()> {\n        // Invoke `run` export.\n        let run = self\n            .instance\n            .as_ref()\n            .unwrap()\n            .get_func(self.store.as_mut().unwrap(), \"run\")\n            .ok_or_else(|| anyhow::format_err!(\"failed to find `run` function export!\"))?;\n\n        let params = [Val::I32(self.wasm_addr), Val::I32(self.input_size)];\n        let out_size = run.call(self.store.as_mut().unwrap(), &params[..])?;\n        let out_size = (*out_size)[0].unwrap_i32();\n        if out_size == 0 {\n            panic!(\"graph run failed!\");\n        }\n\n        self.output_size = out_size;\n        Ok(())\n    }\n\n    pub fn get_output(&mut self) -> Result<Tensor> {\n        let memory = self\n            .instance\n            .as_ref()\n            .unwrap()\n            .get_memory(self.store.as_mut().unwrap(), \"memory\")\n            .ok_or_else(|| anyhow::format_err!(\"failed to find `memory` export\"))?;\n\n        let mut out_data = vec![0 as u8; self.output_size as _];\n        memory.read(\n            self.store.as_mut().unwrap(),\n            self.wasm_addr as _,\n            &mut out_data,\n        )?;\n\n        let out_vec: Tensor = serde_json::from_slice(&out_data).unwrap();\n        Ok(out_vec)\n    }\n}\n\nimpl Default for GraphExecutor {\n    fn default() -> Self {\n        Self::new()\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-runtime/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#[macro_use]\nextern crate serde_derive;\n\nmod graph;\nmod types;\n\npub use graph::GraphExecutor;\npub use types::Tensor;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-runtime/src/types.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{any::TypeId, mem, slice};\n\n#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]\npub enum DataType {\n    FP32,\n    INT32,\n    INT8,\n}\n\nimpl DataType {\n    /// Returns whether this `DataType` represents primitive type `T`.\n    pub fn is_type<T: 'static>(&self) -> bool {\n        let typ = TypeId::of::<T>();\n        typ == TypeId::of::<i32>() || typ == TypeId::of::<i8>() || typ == TypeId::of::<f32>()\n    }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct Tensor {\n    pub(crate) dtype: DataType,\n    pub(crate) shape: Vec<i64>,\n    pub(crate) strides: Option<Vec<usize>>,\n    pub(crate) data: Vec<u8>,\n}\n\n#[allow(dead_code)]\nimpl Tensor {\n    pub fn new(dtype: DataType, shape: Vec<i64>, strides: Vec<usize>, data: Vec<u8>) -> Self {\n        Tensor {\n            dtype,\n            shape,\n            strides: Some(strides),\n            data,\n        }\n    }\n\n    pub fn dtype(&self) -> DataType {\n        self.dtype.clone()\n    }\n\n    pub fn ndim(&self) -> usize {\n        self.shape.len()\n    }\n\n    pub fn shape(&self) -> Vec<i64> {\n        self.shape.clone()\n    }\n\n    pub fn data(&self) -> Vec<u8> {\n        self.data.clone()\n    }\n\n    /// Returns the data of this `Tensor` as a `Vec`.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the `Tensor` does not contain elements of type `T`.\n    pub fn to_vec<T: 'static + std::fmt::Debug + Clone>(&self) -> Vec<T> {\n        assert!(self.dtype().is_type::<T>());\n\n        unsafe {\n            slice::from_raw_parts(\n                self.data().as_ptr() as *const T,\n                self.shape().iter().map(|v| *v as usize).product::<usize>() as usize,\n            )\n            .to_vec()\n        }\n    }\n}\n\nimpl Default for Tensor {\n    fn default() -> Self {\n        Self {\n            dtype: DataType::FP32,\n            shape: Vec::new(),\n            strides: None,\n            data: Vec::new(),\n        }\n    }\n}\n\n/// `From` conversions to `Tensor` for `ndarray::Array`.\n/// Takes a reference to the `ndarray` since `Tensor` is not owned.\nmacro_rules! impl_tensor_from_ndarray {\n    ($type:ty, $typecode:expr) => {\n        impl<D: ndarray::Dimension> From<ndarray::Array<$type, D>> for Tensor {\n            fn from(arr: ndarray::Array<$type, D>) -> Self {\n                Tensor {\n                    dtype: $typecode,\n                    shape: arr.shape().iter().map(|v| *v as i64).collect(),\n                    strides: Some(arr.strides().iter().map(|v| *v as usize).collect()),\n                    data: unsafe {\n                        slice::from_raw_parts(\n                            arr.as_ptr() as *const u8,\n                            arr.len() * mem::size_of::<$type>(),\n                        )\n                        .to_vec()\n                    },\n                }\n            }\n        }\n    };\n}\n\nimpl_tensor_from_ndarray!(f32, DataType::FP32);\nimpl_tensor_from_ndarray!(i32, DataType::INT32);\nimpl_tensor_from_ndarray!(i8, DataType::INT8);\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "apps/wasm-standalone/wasm-runtime/tests/test_graph_resnet50/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse getopts::Options;\nuse image::{FilterType, GenericImageView};\nuse ndarray::Array;\nuse std::{collections::HashMap, env, fs::File, io::BufReader};\nuse wasm_runtime::{GraphExecutor, Tensor};\n\nconst IMG_HEIGHT: usize = 224;\nconst IMG_WIDTH: usize = 224;\n\nfn print_usage(program: &str, opts: Options) {\n    let brief = format!(\"Usage: {} [options]\", program);\n    print!(\"{}\", opts.usage(&brief));\n}\n\nfn main() {\n    let args: Vec<String> = env::args().collect();\n    let program = args[0].clone();\n\n    let mut opts = Options::new();\n    opts.optopt(\n        \"g\",\n        \"wasm-graph-file\",\n        \"set the path to wasm graph file\",\n        \"FILE_PATH\",\n    );\n    opts.optopt(\n        \"i\",\n        \"input-data-file\",\n        \"set the path to input image file\",\n        \"FILE_PATH\",\n    );\n    opts.optopt(\n        \"l\",\n        \"label-class-file\",\n        \"set the path to label class file\",\n        \"FILE_PATH\",\n    );\n    opts.optflag(\"h\", \"help\", \"print this help menu\");\n    let matches = match opts.parse(&args[1..]) {\n        Ok(m) => m,\n        Err(f) => panic!(f.to_string()),\n    };\n    if matches.opt_present(\"h\") {\n        print_usage(&program, opts);\n        return;\n    }\n    let wasm_graph_file: String = match matches.opt_str(\"g\") {\n        Some(s) => s,\n        None => String::from(\"\"),\n    };\n    let input_data_file: String = match matches.opt_str(\"i\") {\n        Some(s) => s,\n        None => String::from(\"\"),\n    };\n    let label_class_file: String = match matches.opt_str(\"l\") {\n        Some(s) => s,\n        None => String::from(\"\"),\n    };\n    let img = image::open(input_data_file).unwrap();\n    let input = data_preprocess(img);\n\n    let mut graph_exec = GraphExecutor::new();\n    graph_exec.instantiate(wasm_graph_file).unwrap();\n    graph_exec.set_input(input).unwrap();\n    graph_exec.run().unwrap();\n    let output: Tensor = match graph_exec.get_output() {\n        Ok(m) => m,\n        Err(f) => panic!(f.to_string()),\n    };\n    output_assert(output, label_class_file);\n}\n\nfn data_preprocess(img: image::DynamicImage) -> Tensor {\n    println!(\"original image dimensions: {:?}\", img.dimensions());\n    let img = img\n        .resize_exact(IMG_HEIGHT as u32, IMG_WIDTH as u32, FilterType::Nearest)\n        .to_rgb();\n    println!(\"resized image dimensions: {:?}\", img.dimensions());\n    let mut pixels: Vec<f32> = vec![];\n    for pixel in img.pixels() {\n        let tmp = pixel.data;\n        // normalize the RGB channels using mean, std of imagenet1k\n        let tmp = [\n            (tmp[0] as f32 - 123.0) / 58.395, // R\n            (tmp[1] as f32 - 117.0) / 57.12,  // G\n            (tmp[2] as f32 - 104.0) / 57.375, // B\n        ];\n        for e in &tmp {\n            pixels.push(*e);\n        }\n    }\n\n    // (H,W,C) -> (C,H,W)\n    let arr = Array::from_shape_vec((IMG_HEIGHT, IMG_WIDTH, 3), pixels).unwrap();\n    let arr = arr.permuted_axes([2, 0, 1]);\n    let arr = Array::from_iter(arr.into_iter().copied().map(|v| v));\n\n    Tensor::from(arr)\n}\n\nfn output_assert(out_tensor: Tensor, label_class_file: String) {\n    let output = out_tensor.to_vec::<f32>();\n\n    // Find the maximum entry in the output and its index.\n    let mut argmax = -1;\n    let mut max_prob = 0.;\n    for i in 0..output.len() {\n        if output[i] > max_prob {\n            max_prob = output[i];\n            argmax = i as i32;\n        }\n    }\n\n    // Create a hash map of (class id, class name)\n    let mut synset: HashMap<i32, String> = HashMap::new();\n    let mut rdr = csv::ReaderBuilder::new().from_reader(BufReader::new(\n        File::open(label_class_file.as_str()).unwrap(),\n    ));\n\n    for result in rdr.records() {\n        let record = result.unwrap();\n        let id: i32 = record[0].parse().unwrap();\n        let cls = record[1].to_string();\n        synset.insert(id, cls);\n    }\n\n    println!(\n        \"input image belongs to the class `{}`\",\n        synset\n            .get(&argmax)\n            .expect(\"cannot find the class id for argmax\")\n    );\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/jenkins/generate.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport jinja2\nimport argparse\nimport difflib\nimport datetime\nimport re\nimport textwrap\n\nfrom pathlib import Path\nfrom typing import List\n\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\nJENKINSFILE_TEMPLATE = REPO_ROOT / \"ci\" / \"jenkins\" / \"Jenkinsfile.j2\"\nJENKINSFILE = REPO_ROOT / \"Jenkinsfile\"\n\n\nclass Change:\n    IMAGES_ONLY = object()\n    NONE = object()\n    FULL = object()\n\n\ndata = {\n    \"images\": [\n        {\n            \"name\": \"ci_arm\",\n            \"platform\": \"ARM\",\n        },\n        {\n            \"name\": \"ci_cortexm\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_cpu\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_gpu\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_hexagon\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_i386\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_lint\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_minimal\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_riscv\",\n            \"platform\": \"CPU\",\n        },\n        {\n            \"name\": \"ci_wasm\",\n            \"platform\": \"CPU\",\n        },\n    ]\n}\n\n\ndef lines_without_generated_tag(content):\n    return [\n        line for line in content.splitlines(keepends=True) if not line.startswith(\"// Generated at\")\n    ]\n\n\ndef change_type(lines: List[str]) -> Change:\n    \"\"\"\n    Return True if 'line' only edits an image tag or if 'line' is not a changed\n    line in a diff\n    \"\"\"\n    added_images = []\n    removed_images = []\n    diff_lines = []\n\n    for line in lines[2:]:\n        if not line.startswith(\"-\") and not line.startswith(\"+\"):\n            # not a diff line, ignore it\n            continue\n\n        diff_lines.append(line)\n\n    if len(diff_lines) == 0:\n        # no changes made\n        return Change.NONE\n\n    for line in diff_lines:\n        is_add = line.startswith(\"+\")\n        line = line.strip().lstrip(\"+\").lstrip(\"-\")\n        match = re.search(\n            r\"^(ci_[a-zA-Z0-9]+) = \\'.*\\'$\",\n            line.strip().lstrip(\"+\").lstrip(\"-\"),\n            flags=re.MULTILINE,\n        )\n        if match is None:\n            # matched a non-image line, quit early\n            return Change.FULL\n\n        if is_add:\n            added_images.append(match.groups()[0])\n        else:\n            removed_images.append(match.groups()[0])\n\n    # make sure that the added image lines match the removed image lines\n    if len(added_images) > 0 and added_images == removed_images:\n        return Change.IMAGES_ONLY\n    else:\n        return Change.FULL\n\n\nif __name__ == \"__main__\":\n    help = \"Regenerate Jenkinsfile from template\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--force\", action=\"store_true\", help=\"always overwrite timestamp\")\n    parser.add_argument(\"--check\", action=\"store_true\", help=\"just verify the output didn't change\")\n    args = parser.parse_args()\n\n    with open(JENKINSFILE) as f:\n        content = f.read()\n\n    data[\"generated_time\"] = datetime.datetime.now().isoformat()\n    timestamp_match = re.search(r\"^// Generated at (.*)$\", content, flags=re.MULTILINE)\n    if not timestamp_match:\n        raise RuntimeError(\"Could not find timestamp in Jenkinsfile\")\n    original_timestamp = timestamp_match.groups()[0]\n\n    environment = jinja2.Environment(\n        loader=jinja2.FileSystemLoader(REPO_ROOT),\n        undefined=jinja2.StrictUndefined,\n        lstrip_blocks=True,\n        trim_blocks=True,\n        keep_trailing_newline=True,\n    )\n    template = environment.get_template(str(JENKINSFILE_TEMPLATE.relative_to(REPO_ROOT)))\n    new_content = template.render(**data)\n\n    diff = [\n        line\n        for line in difflib.unified_diff(\n            lines_without_generated_tag(content), lines_without_generated_tag(new_content)\n        )\n    ]\n    change = change_type(diff)\n    if not args.force and change == Change.IMAGES_ONLY or change == Change.NONE:\n        if change != Change.NONE:\n            print(\"Detected only Docker-image name changes, skipping timestamp update\")\n        new_content = new_content.replace(data[\"generated_time\"], original_timestamp)\n\n    diff = \"\".join(diff)\n\n    if args.check:\n        if not diff:\n            print(\"Success, the newly generated Jenkinsfile matched the one on disk\")\n            exit(0)\n        else:\n            print(\n                textwrap.dedent(\n                    \"\"\"\n                Newly generated Jenkinsfile did not match the one on disk! If you have made\n                edits to the Jenkinsfile, move them to 'jenkins/Jenkinsfile.j2' and\n                regenerate the Jenkinsfile from the template with\n\n                    python3 -m pip install -r jenkins/requirements.txt\n                    python3 jenkins/generate.py\n\n                Diffed changes:\n            \"\"\"\n                ).strip()\n            )\n            print(diff)\n            exit(1)\n    else:\n        with open(JENKINSFILE, \"w\") as f:\n            f.write(new_content)\n        if not diff:\n            print(f\"Wrote output to {JENKINSFILE.relative_to(REPO_ROOT)}, no changes made\")\n        else:\n            print(f\"Wrote output to {JENKINSFILE.relative_to(REPO_ROOT)}, changes:\")\n            print(diff)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package to enable testing of CI scripts\"\"\"\n\nfrom . import github_skipped_tests_comment, github_pr_comment, github_tag_teams, github_docs_comment\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/check_pr.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport re\nimport os\nimport json\nimport textwrap\nfrom dataclasses import dataclass\nfrom typing import Any, List, Callable\n\n\nfrom git_utils import GitHubRepo, parse_remote, git\nfrom cmd_utils import init_log, tags_from_title\n\n\nGITHUB_USERNAME_REGEX = re.compile(r\"(@[a-zA-Z0-9-]+)\", flags=re.MULTILINE)\nOK = object()\nFAIL = object()\n\n\n@dataclass\nclass Check:\n    # check to run, returning OK means it passed, anything else means it failed\n    check: Callable[[str], Any]\n\n    # function to call to generate the error message\n    error_fn: Callable[[Any], str]\n\n\ndef non_empty(s: str):\n    if len(s) == 0:\n        return FAIL\n    return OK\n\n\ndef usernames(s: str):\n    m = GITHUB_USERNAME_REGEX.findall(s)\n    return m if m else OK\n\n\ndef tags(s: str):\n    items = tags_from_title(s)\n    if len(items) == 0:\n        return FAIL\n    return OK\n\n\ndef trailing_period(s: str):\n    if s.endswith(\".\"):\n        return FAIL\n    return OK\n\n\ntitle_checks = [\n    Check(check=non_empty, error_fn=lambda d: \"PR must have a title but title was empty\"),\n    Check(check=trailing_period, error_fn=lambda d: \"PR must not end in a tailing '.'\"),\n    # TODO(driazati): enable this check once https://github.com/apache/tvm/issues/12637 is done\n    # Check(\n    #     check=usernames,\n    #     error_fn=lambda d: f\"PR title must not tag anyone but found these usernames: {d}\",\n    # ),\n]\nbody_checks = [\n    Check(check=non_empty, error_fn=lambda d: \"PR must have a body but body was empty\"),\n    # TODO(driazati): enable this check once https://github.com/apache/tvm/issues/12637 is done\n    # Check(\n    #     check=usernames,\n    #     error_fn=lambda d: f\"PR body must not tag anyone but found these usernames: {d}\",\n    # ),\n]\n\n\ndef run_checks(checks: List[Check], s: str, name: str) -> bool:\n    print(f\"Running checks for {name}\")\n    print(textwrap.indent(s, prefix=\"    \"))\n    passed = True\n    print(\"    Checks:\")\n    for i, check in enumerate(checks):\n        result = check.check(s)\n        if result == OK:\n            print(f\"        [{i+1}] {check.check.__name__}: PASSED\")\n        else:\n            passed = False\n            msg = check.error_fn(result)\n            print(f\"        [{i+1}] {check.check.__name__}: FAILED: {msg}\")\n\n    return passed\n\n\nif __name__ == \"__main__\":\n    init_log()\n    help = \"Check a PR's title and body for conformance to guidelines\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--pr\", required=True)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\n        \"--pr-data\", help=\"(testing) PR data to use instead of fetching from GitHub\"\n    )\n    args = parser.parse_args()\n\n    try:\n        pr = int(args.pr)\n    except ValueError:\n        print(f\"PR was not a number: {args.pr}\")\n        exit(0)\n\n    if args.pr_data:\n        pr = json.loads(args.pr_data)\n    else:\n        remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n        user, repo = parse_remote(remote)\n\n        github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n        pr = github.get(f\"pulls/{args.pr}\")\n\n    body = \"\" if pr[\"body\"] is None else pr[\"body\"].strip()\n    title = \"\" if pr[\"title\"] is None else pr[\"title\"].strip()\n\n    title_passed = run_checks(checks=title_checks, s=title, name=\"PR title\")\n    print(\"\")\n    body_passed = run_checks(checks=body_checks, s=body, name=\"PR body\")\n\n    if title_passed and body_passed:\n        print(\"All checks passed!\")\n        exit(0)\n    else:\n        print(\n            \"Some checks failed, please review the logs above and edit your PR on GitHub accordingly\"\n        )\n        exit(1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/cmd_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport subprocess\nimport os\nimport logging\nimport sys\nimport re\nfrom pathlib import Path\nfrom typing import List\n\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\n\n\nclass RelativePathFilter(logging.Filter):\n    def filter(self, record):\n        path = Path(record.pathname).resolve()\n        record.relativepath = str(path.relative_to(REPO_ROOT))\n        return True\n\n\ndef init_log():\n    logging.basicConfig(\n        format=\"[%(relativepath)s:%(lineno)d %(levelname)-1s] %(message)s\", level=logging.INFO\n    )\n\n    # Flush on every log call (logging and then calling subprocess.run can make\n    # the output look confusing)\n    logging.root.handlers[0].addFilter(RelativePathFilter())\n    logging.root.handlers[0].flush = sys.stderr.flush\n\n\nclass Sh:\n    def __init__(self, env=None, cwd=None):\n        self.env = os.environ.copy()\n        if env is not None:\n            self.env.update(env)\n        self.cwd = cwd\n\n    def run(self, cmd: str, **kwargs):\n        logging.info(f\"+ {cmd}\")\n        defaults = {\n            \"check\": True,\n            \"shell\": True,\n            \"env\": self.env,\n            \"encoding\": \"utf-8\",\n            \"cwd\": self.cwd,\n        }\n        defaults.update(kwargs)\n\n        return subprocess.run(cmd, **defaults)\n\n\ndef tags_from_title(title: str) -> List[str]:\n    tags = re.findall(r\"\\[(.*?)\\]\", title)\n    tags = [t.strip() for t in tags]\n    return tags\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/determine_docker_images.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport datetime\nimport json\nimport logging\nimport urllib.error\nfrom pathlib import Path\n\nfrom typing import Dict, Any\n\n\nfrom http_utils import get\nfrom cmd_utils import init_log, REPO_ROOT\n\n\nDOCKER_API_BASE = \"https://hub.docker.com/v2/\"\nPAGE_SIZE = 25\nTEST_DATA = None\n\n\ndef docker_api(url: str, use_pagination: bool = False) -> Dict[str, Any]:\n    \"\"\"\n    Run a paginated fetch from the public Docker Hub API\n    \"\"\"\n    if TEST_DATA is not None:\n        if url not in TEST_DATA:\n            raise urllib.error.HTTPError(url, 404, \"Not found\", {}, None)\n        return TEST_DATA[url]\n    pagination = \"\"\n    if use_pagination:\n        pagination = f\"?page_size={PAGE_SIZE}&page=1\"\n    url = DOCKER_API_BASE + url + pagination\n    r, headers = get(url)\n    reset = headers.get(\"x-ratelimit-reset\")\n    if reset is not None:\n        reset = datetime.datetime.fromtimestamp(int(reset))\n        reset = reset.isoformat()\n    logging.info(\n        f\"Docker API Rate Limit: {headers.get('x-ratelimit-remaining')} / {headers.get('x-ratelimit-limit')} (reset at {reset})\"\n    )\n    return r\n\n\ndef image_exists(spec: str) -> bool:\n    name, tag = spec.split(\":\")\n    try:\n        r = docker_api(f\"repositories/{name}/tags/{tag}\")\n        logging.info(f\"Image exists, got response: {json.dumps(r, indent=2)}\")\n        return True\n    except urllib.error.HTTPError as e:\n        # Image was not found\n        logging.exception(e)\n        return False\n\n\nif __name__ == \"__main__\":\n    init_log()\n    parser = argparse.ArgumentParser(\n        description=\"Writes out Docker images names to be used to .docker-image-names/\"\n    )\n    parser.add_argument(\n        \"--testing-docker-data\",\n        help=\"(testing only) JSON data to mock response from Docker Hub API\",\n    )\n    parser.add_argument(\n        \"--base-dir\",\n        default=\".docker-image-names\",\n        help=\"(testing only) Folder to write image names to\",\n    )\n    args, other = parser.parse_known_args()\n    name_dir = Path(args.base_dir)\n\n    images = {}\n    for item in other:\n        name, tag = item.split(\"=\")\n        images[name] = tag\n\n    if args.testing_docker_data is not None:\n        TEST_DATA = json.loads(args.testing_docker_data)\n\n    logging.info(f\"Checking if these images exist in tlcpack: {images}\")\n\n    name_dir.mkdir(exist_ok=True)\n    images_to_use = {}\n    for filename, spec in images.items():\n        if image_exists(spec):\n            logging.info(f\"{spec} found in tlcpack\")\n            images_to_use[filename] = spec\n        else:\n            logging.info(f\"{spec} not found in tlcpack, using tlcpackstaging\")\n            part, tag = spec.split(\":\")\n            user, repo = part.split(\"/\")\n            tlcpackstaging_tag = f\"tlcpackstaging/{repo.replace('-', '_')}:{tag}\"\n            images_to_use[filename] = tlcpackstaging_tag\n\n    for filename, image in images_to_use.items():\n        logging.info(f\"Writing image {image} to {name_dir / filename}\")\n        with open(name_dir / filename, \"w\") as f:\n            f.write(image)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/git_skip_ci.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport logging\nimport argparse\n\nfrom git_utils import git, GitHubRepo, parse_remote\nfrom cmd_utils import tags_from_title, init_log\n\n\nif __name__ == \"__main__\":\n    help = \"Exits with 0 if CI should be skipped, 1 otherwise\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--pr\", required=True)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\n        \"--pr-title\", help=\"(testing) PR title to use instead of fetching from GitHub\"\n    )\n    args = parser.parse_args()\n    init_log()\n\n    branch = git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"])\n    log = git([\"log\", \"--format=%s\", \"-1\"])\n\n    # Check the PR's title (don't check this until everything else passes first)\n    def check_pr_title():\n        remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n        user, repo = parse_remote(remote)\n\n        if args.pr_title:\n            title = args.pr_title\n        else:\n            github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n            pr = github.get(f\"pulls/{args.pr}\")\n            title = pr[\"title\"]\n        logging.info(f\"pr title: {title}\")\n        tags = tags_from_title(title)\n        logging.info(f\"Found title tags: {tags}\")\n        return \"skip ci\" in tags\n\n    if args.pr != \"null\" and args.pr.strip() != \"\" and branch != \"main\" and check_pr_title():\n        logging.info(\"PR title starts with '[skip ci]', skipping...\")\n        exit(0)\n    else:\n        logging.info(f\"Not skipping CI:\\nargs.pr: {args.pr}\\nbranch: {branch}\\ncommit: {log}\")\n        exit(1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/git_skip_ci_globs.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport fnmatch\nfrom typing import Optional\n\nfrom git_utils import git\n\n\nglobs = [\n    \"*.md\",\n    \"conda/*\",\n    \".github/*\",\n    \".asf.yaml\",\n    \".gitignore\",\n    \"LICENSE\",\n    \"NOTICE\",\n    \"KEYS\",\n    # microTVM\n    \"apps/microtvm/poetry.lock\",\n    \"apps/microtvm/pyproject.toml\",\n    \"tests/lint/*\",\n    \"tests/scripts/task_lint.sh\",\n]\n\n\ndef match_any(f: str) -> Optional[str]:\n    for glob in globs:\n        if fnmatch.fnmatch(f, glob):\n            return glob\n    return None\n\n\nif __name__ == \"__main__\":\n    help = \"Exits with code 1 if a change only touched files, indicating that CI could be skipped for this changeset\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--files\", help=\"(testing only) comma separated list of files to check\")\n    args = parser.parse_args()\n    print(args)\n    if args.files is not None:\n        diff = [x for x in args.files.split(\",\") if x.strip() != \"\"]\n    else:\n        diff = git([\"diff\", \"--no-commit-id\", \"--name-only\", \"-r\", \"origin/main\"])\n        diff = diff.split(\"\\n\")\n        diff = [d.strip() for d in diff]\n        diff = [d for d in diff if d != \"\"]\n\n    print(f\"Changed files:\\n{diff}\")\n\n    if len(diff) == 0:\n        print(\"Found no changed files, skipping CI\")\n        exit(0)\n\n    print(f\"Checking with globs:\\n{globs}\")\n\n    for file in diff:\n        match = match_any(file)\n        if match is None:\n            print(f\"{file} did not match any globs, running CI\")\n            exit(1)\n        else:\n            print(f\"{file} matched glob {match}\")\n\n    print(\"All files matched a glob, skipping CI\")\n    exit(0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/git_utils.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport subprocess\nimport re\nimport os\nimport base64\nimport logging\nfrom urllib import request, error\nfrom typing import Dict, Tuple, Any, Optional, List\n\nDRY_RUN = object()\n\n\ndef compress_query(query: str) -> str:\n    query = query.replace(\"\\n\", \"\")\n    query = re.sub(\"\\s+\", \" \", query)\n    return query\n\n\ndef post(url: str, body: Optional[Any] = None, auth: Optional[Tuple[str, str]] = None):\n    logging.info(f\"Requesting POST to\", url, \"with\", body)\n    headers = {}\n    req = request.Request(url, headers=headers, method=\"POST\")\n    if auth is not None:\n        auth_str = base64.b64encode(f\"{auth[0]}:{auth[1]}\".encode())\n        req.add_header(\"Authorization\", f\"Basic {auth_str.decode()}\")\n\n    if body is None:\n        body = \"\"\n\n    req.add_header(\"Content-Type\", \"application/json; charset=utf-8\")\n    data = json.dumps(body)\n    data = data.encode(\"utf-8\")\n    req.add_header(\"Content-Length\", len(data))\n\n    with request.urlopen(req, data) as response:\n        return response.read()\n\n\ndef dry_run_token(is_dry_run: bool) -> Any:\n    if is_dry_run:\n        return DRY_RUN\n    return os.environ[\"GITHUB_TOKEN\"]\n\n\nclass GitHubRepo:\n    GRAPHQL_URL = \"https://api.github.com/graphql\"\n\n    def __init__(self, user, repo, token, test_data=None):\n        self.token = token\n        self.user = user\n        self.repo = repo\n        self.test_data = test_data\n        self.num_calls = 0\n        self.base = f\"https://api.github.com/repos/{user}/{repo}/\"\n\n    def headers(self):\n        return {\n            \"Authorization\": f\"Bearer {self.token}\",\n        }\n\n    def dry_run(self) -> bool:\n        return self.token == DRY_RUN\n\n    def graphql(self, query: str, variables: Optional[Dict[str, str]] = None) -> Dict[str, Any]:\n        query = compress_query(query)\n        if variables is None:\n            variables = {}\n\n        response = self._request(\n            self.GRAPHQL_URL,\n            {\"query\": query, \"variables\": variables},\n            method=\"POST\",\n        )\n        if self.dry_run():\n            return self.testing_response(\"POST\", self.GRAPHQL_URL)\n\n        if \"data\" not in response:\n            msg = f\"Error fetching data with query:\\n{query}\\n\\nvariables:\\n{variables}\\n\\nerror:\\n{json.dumps(response, indent=2)}\"\n            raise RuntimeError(msg)\n        return response\n\n    def testing_response(self, method: str, url: str) -> Any:\n        self.num_calls += 1\n        key = f\"[{self.num_calls}] {method} - {url}\"\n        if self.test_data is not None and key in self.test_data:\n            return self.test_data[key]\n        logging.info(f\"Unknown URL in dry run: {key}\")\n        return {}\n\n    def _request(self, full_url: str, body: Dict[str, Any], method: str) -> Dict[str, Any]:\n        if self.dry_run():\n            logging.info(f\"Dry run, would have requested a {method} to {full_url} with {body}\")\n            return self.testing_response(method, full_url)\n\n        logging.info(f\"Requesting {method} to {full_url} with {body}\")\n        req = request.Request(full_url, headers=self.headers(), method=method.upper())\n        req.add_header(\"Content-Type\", \"application/json; charset=utf-8\")\n        data = json.dumps(body)\n        data = data.encode(\"utf-8\")\n        req.add_header(\"Content-Length\", len(data))\n\n        try:\n            with request.urlopen(req, data) as response:\n                content = response.read()\n        except error.HTTPError as e:\n            msg = str(e)\n            error_data = e.read().decode()\n            raise RuntimeError(f\"Error response: {msg}\\n{error_data}\")\n\n        logging.info(f\"Got response from {full_url}: {content}\")\n        try:\n            response = json.loads(content)\n        except json.decoder.JSONDecodeError as e:\n            return content\n\n        return response\n\n    def put(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]:\n        return self._request(self.base + url, data, method=\"PUT\")\n\n    def patch(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]:\n        return self._request(self.base + url, data, method=\"PATCH\")\n\n    def post(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]:\n        return self._request(self.base + url, data, method=\"POST\")\n\n    def get(self, url: str) -> Dict[str, Any]:\n        if self.dry_run():\n            logging.info(f\"Dry run, would have requested a GET to {url}\")\n            return self.testing_response(\"GET\", url)\n        url = self.base + url\n        logging.info(f\"Requesting GET to {url}\")\n        req = request.Request(url, headers=self.headers())\n        with request.urlopen(req) as response:\n            response = json.loads(response.read())\n        return response\n\n    def delete(self, url: str) -> Dict[str, Any]:\n        if self.dry_run():\n            logging.info(f\"Dry run, would have requested a DELETE to {url}\")\n            return self.testing_response(\"DELETE\", url)\n        url = self.base + url\n        logging.info(f\"Requesting DELETE to {url}\")\n        req = request.Request(url, headers=self.headers(), method=\"DELETE\")\n        with request.urlopen(req) as response:\n            response = json.loads(response.read())\n        return response\n\n\ndef parse_remote(remote: str) -> Tuple[str, str]:\n    \"\"\"\n    Get a GitHub (user, repo) pair out of a git remote\n    \"\"\"\n    if remote.startswith(\"https://\"):\n        # Parse HTTP remote\n        parts = remote.split(\"/\")\n        if len(parts) < 2:\n            raise RuntimeError(f\"Unable to parse remote '{remote}'\")\n        user, repo = parts[-2], parts[-1].replace(\".git\", \"\")\n    else:\n        # Parse SSH remote\n        m = re.search(r\":(.*)/(.*)\\.git\", remote)\n        if m is None or len(m.groups()) != 2:\n            raise RuntimeError(f\"Unable to parse remote '{remote}'\")\n        user, repo = m.groups()\n\n    user = os.getenv(\"DEBUG_USER\", user)\n    repo = os.getenv(\"DEBUG_REPO\", repo)\n    return user, repo\n\n\ndef git(command, **kwargs):\n    command = [\"git\"] + command\n    logging.info(f\"Running {command}\")\n    proc = subprocess.run(command, stdout=subprocess.PIPE, encoding=\"utf-8\", **kwargs)\n    if proc.returncode != 0:\n        raise RuntimeError(f\"Command failed {command}:\\nstdout:\\n{proc.stdout}\")\n    return proc.stdout.strip()\n\n\ndef find_ccs(body: str) -> List[str]:\n    matches = re.findall(r\"(cc( @[-A-Za-z0-9]+)+)\", body, flags=re.MULTILINE)\n    matches = [full for full, last in matches]\n\n    reviewers = []\n    for match in matches:\n        if match.startswith(\"cc \"):\n            match = match.replace(\"cc \", \"\")\n        users = [x.strip() for x in match.split(\"@\")]\n        reviewers += users\n\n    reviewers = set(x for x in reviewers if x != \"\")\n    return list(reviewers)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_cc_reviewers.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport os\nimport json\nimport argparse\nimport re\nfrom urllib import error\nfrom typing import Dict, Any, List\n\n\nfrom git_utils import git, GitHubRepo, parse_remote\n\n\ndef find_reviewers(body: str) -> List[str]:\n    print(f\"Parsing body:\\n{body}\")\n    matches = re.findall(r\"(cc( @[-A-Za-z0-9]+)+)\", body, flags=re.MULTILINE)\n    matches = [full for full, last in matches]\n\n    print(\"Found matches:\", matches)\n    reviewers = []\n    for match in matches:\n        if match.startswith(\"cc \"):\n            match = match.replace(\"cc \", \"\")\n        users = [x.strip() for x in match.split(\"@\")]\n        reviewers += users\n\n    reviewers = set(x for x in reviewers if x != \"\")\n    return sorted(list(reviewers))\n\n\nif __name__ == \"__main__\":\n    help = \"Add @cc'ed people in a PR body as reviewers\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--testing-reviews-json\", help=\"(testing only) reviews as JSON\")\n    parser.add_argument(\n        \"--dry-run\",\n        action=\"store_true\",\n        default=False,\n        help=\"run but don't send any request to GitHub\",\n    )\n    args = parser.parse_args()\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n\n    pr = json.loads(os.environ[\"PR\"])\n\n    number = pr[\"number\"]\n    body = pr[\"body\"]\n    if body is None:\n        body = \"\"\n\n    new_reviewers = find_reviewers(body)\n    print(\"Found these reviewers:\", new_reviewers)\n\n    if args.testing_reviews_json:\n        existing_reviews = json.loads(args.testing_reviews_json)\n    else:\n        github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n        existing_reviews = github.get(f\"pulls/{number}/reviews\")\n\n    existing_review_users = [review[\"user\"][\"login\"] for review in existing_reviews]\n    print(\"PR has reviews from these users:\", existing_review_users)\n    existing_review_users = set(r.lower() for r in existing_review_users)\n\n    existing_reviewers = [review[\"login\"] for review in pr[\"requested_reviewers\"]]\n    print(\"PR already had these reviewers requested:\", existing_reviewers)\n\n    existing_reviewers_lower = {\n        existing_reviewer.lower() for existing_reviewer in existing_reviewers\n    }\n    to_add = []\n    for new_reviewer in new_reviewers:\n        if (\n            new_reviewer.lower() in existing_reviewers_lower\n            or new_reviewer.lower() in existing_review_users\n        ):\n            print(f\"{new_reviewer} is already review requested, skipping\")\n        else:\n            to_add.append(new_reviewer)\n\n    print(f\"After filtering existing reviewers, adding: {to_add}\")\n\n    if not args.dry_run:\n        github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n\n        # Add reviewers 1 by 1 since GitHub will error out if any of the\n        # requested reviewers aren't members / contributors\n        for reviewer in to_add:\n            try:\n                github.post(f\"pulls/{number}/requested_reviewers\", {\"reviewers\": [reviewer]})\n            except KeyboardInterrupt:\n                sys.exit()\n            except (RuntimeError, error.HTTPError) as e:\n                # Catch any exception so other reviewers can be processed\n                print(f\"Failed to add reviewer {reviewer}: {e}\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_commenter.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport re\nimport logging\nfrom typing import Dict, Tuple, Any, Optional, List, Union\n\nfrom git_utils import GitHubRepo\n\nBOT_COMMENT_START = \"<!---bot-comment-->\"\nWELCOME_TEXT = \"Thanks for contributing to TVM! Please refer to the contributing guidelines https://tvm.apache.org/docs/contribute/ for useful information and tips. Please request code reviews from [Reviewers](https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers) by @-ing them in a comment.\"\n\n\nclass BotCommentBuilder:\n    ALLOWLIST_USERS = {\"driazati\", \"gigiblender\", \"areusch\"}\n\n    def __init__(self, github: GitHubRepo, data: Dict[str, Any]):\n        self.github = github\n        self.pr_number = data[\"number\"]\n        self.comment_data = data[\"comments\"][\"nodes\"]\n        self.author = data[\"author\"][\"login\"]\n\n    def find_bot_comment(self) -> Optional[Dict[str, Any]]:\n        \"\"\"\n        Return the existing bot comment or None if it does not exist\n        \"\"\"\n        for comment in self.comment_data:\n            logging.info(f\"Checking comment {comment}\")\n            if (\n                comment[\"author\"][\"login\"] == \"github-actions\"\n                and BOT_COMMENT_START in comment[\"body\"]\n            ):\n                logging.info(\"Found existing comment\")\n                return comment\n        logging.info(\"No existing comment found\")\n        return None\n\n    def find_existing_body(self) -> Dict[str, str]:\n        \"\"\"\n        Find existing dynamic bullet point items\n        \"\"\"\n        existing_comment = self.find_bot_comment()\n        if existing_comment is None:\n            logging.info(f\"No existing comment while searching for body items\")\n            return {}\n\n        matches = re.findall(\n            r\"<!--bot-comment-([a-z][a-z-]+)-start-->([\\S\\s]*?)<!--bot-comment-([a-z-]+)-end-->\",\n            existing_comment[\"body\"],\n            flags=re.MULTILINE,\n        )\n        logging.info(f\"Fetch body item matches: {matches}\")\n\n        items = {}\n        for start, text, end in matches:\n            if start != end:\n                raise RuntimeError(\n                    f\"Malformed comment found: {start} marker did not have matching end, found instead {end}\"\n                )\n            items[start] = text.strip().lstrip(\"* \")\n\n        logging.info(f\"Found body items: {items}\")\n        return items\n\n    def _post_comment(self, body_items: Dict[str, str]):\n        comment = BOT_COMMENT_START + \"\\n\\n\" + WELCOME_TEXT + \"\\n\\n\"\n        for key, content in body_items.items():\n            line = self.start_key(key) + \"\\n * \" + content.strip() + self.end_key(key)\n            logging.info(f\"Adding line {line}\")\n            comment += line\n        comment += \"\\n\\n<sub>Generated by [tvm-bot](https://github.com/apache/tvm/blob/main/ci/README.md#github-actions)</sub>\"\n\n        data = {\"body\": comment}\n        url = f\"issues/{self.pr_number}/comments\"\n\n        logging.info(f\"Commenting {comment} on {url}\")\n\n        if self.author not in self.ALLOWLIST_USERS:\n            logging.info(f\"Skipping comment for author {self.author}\")\n            return\n\n        existing_comment = self.find_bot_comment()\n        if existing_comment is None:\n            # Comment does not exist, post it\n            r = self.github.post(url, data)\n        else:\n            # Comment does exist, update it\n            comment_url = f\"issues/comments/{existing_comment['databaseId']}\"\n            r = self.github.patch(comment_url, data)\n\n        logging.info(f\"Got response from posting comment: {r}\")\n\n    def start_key(self, key: str) -> str:\n        return f\"<!--bot-comment-{key}-start-->\"\n\n    def end_key(self, key: str) -> str:\n        return f\"<!--bot-comment-{key}-end-->\"\n\n    def post_items(self, items: List[Tuple[str, str]]):\n        \"\"\"\n        Update or post bullet points in the PR based on 'items' which is a\n        list of (key, text) pairs\n        \"\"\"\n        # Find the existing bullet points\n        body_items = self.find_existing_body()\n\n        # Add or update the requested items\n        for key, text in items:\n            if text is None or text.strip() == \"\":\n                logging.info(f\"Skipping {key} since it was empty\")\n                continue\n            logging.info(f\"Updating comment items {key} with {text}\")\n            body_items[key] = text.strip()\n\n        # Post or update the comment\n        # print(body_items)\n        self._post_comment(body_items=body_items)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_docs_comment.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom typing import Dict, Any\n\n\ndef build_docs_url(base_url_docs, pr_number, build_number):\n    return f\"{base_url_docs}/PR-{str(pr_number)}/{str(build_number)}/docs/index.html\"\n\n\ndef find_target_url(pr_head: Dict[str, Any]):\n    for status in pr_head[\"statusCheckRollup\"][\"contexts\"][\"nodes\"]:\n        if status.get(\"context\", \"\") == \"tvm-ci/pr-head\":\n            return status[\"targetUrl\"]\n\n    raise RuntimeError(f\"Unable to find tvm-ci/pr-head status in {pr_head}\")\n\n\ndef get_pr_and_build_numbers(target_url):\n    target_url = target_url[target_url.find(\"PR-\") : len(target_url)]\n    split = target_url.split(\"/\")\n    pr_number = split[0].strip(\"PR-\")\n    build_number = split[1]\n    return {\"pr_number\": pr_number, \"build_number\": build_number}\n\n\ndef get_doc_url(pr: Dict[str, Any], base_docs_url: str = \"https://pr-docs.tlcpack.ai\") -> str:\n    pr_head = pr[\"commits\"][\"nodes\"][0][\"commit\"]\n    target_url = find_target_url(pr_head)\n    pr_and_build = get_pr_and_build_numbers(target_url)\n\n    commit_sha = pr_head[\"oid\"]\n\n    docs_url = build_docs_url(\n        base_docs_url, pr_and_build[\"pr_number\"], pr_and_build[\"build_number\"]\n    )\n\n    return f\"Built docs for commit {commit_sha} can be found [here]({docs_url}).\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_pr_comment.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport os\nimport json\n\nfrom git_utils import git, GitHubRepo, parse_remote, DRY_RUN\nfrom cmd_utils import init_log\nfrom github_commenter import BotCommentBuilder\nfrom github_skipped_tests_comment import get_skipped_tests_comment\nfrom github_tag_teams import get_tags\nfrom github_docs_comment import get_doc_url\n\nPR_QUERY = \"\"\"\n    query ($owner: String!, $name: String!, $number: Int!) {\n      repository(owner: $owner, name: $name) {\n        pullRequest(number: $number) {\n          title\n          body\n          state\n          number\n          author {\n            login\n          }\n          labels(first:100) {\n            nodes {\n              name\n            }\n          }\n          comments(last: 100) {\n            pageInfo {\n              hasPreviousPage\n            }\n            nodes {\n              author {\n                login\n              }\n              databaseId\n              body\n            }\n          }\n          commits(last: 1) {\n            nodes {\n              commit {\n                oid\n                statusCheckRollup {\n                  contexts(first: 100) {\n                    pageInfo {\n                      hasNextPage\n                    }\n                    nodes {\n                      ... on StatusContext {\n                        state\n                        context\n                        targetUrl\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n\"\"\"\n\n\nif __name__ == \"__main__\":\n    help = \"Comment a welcome message on PRs\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--pr\", required=True)\n    parser.add_argument(\"--test-data\", help=\"(testing) mock GitHub API data\")\n    parser.add_argument(\"--test-comments\", help=\"(testing) testing comments\")\n    parser.add_argument(\n        \"--dry-run\",\n        action=\"store_true\",\n        default=False,\n        help=\"run but don't send any request to GitHub\",\n    )\n    args = parser.parse_args()\n    init_log()\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n\n    test_data = None\n    if args.test_data is not None:\n        test_data = json.loads(args.test_data)\n\n    github = GitHubRepo(\n        user=user,\n        repo=repo,\n        token=DRY_RUN if args.dry_run else os.environ[\"GITHUB_TOKEN\"],\n        test_data=test_data,\n    )\n\n    pr_data = github.graphql(\n        PR_QUERY,\n        {\n            \"owner\": user,\n            \"name\": repo,\n            \"number\": int(args.pr),\n        },\n    )\n\n    pr_data = pr_data[\"data\"][\"repository\"][\"pullRequest\"]\n    commenter = BotCommentBuilder(github=github, data=pr_data)\n\n    if args.test_comments is not None:\n        test_comments = json.loads(args.test_comments)\n        skipped_tests = test_comments[\"skipped-tests\"]\n        ccs = test_comments[\"ccs\"]\n        docs_info = test_comments[\"docs\"]\n    else:\n        skipped_tests = get_skipped_tests_comment(pr_data, github=github)\n        ccs = get_tags(pr_data, github, team_issue=10317)\n        docs_info = get_doc_url(pr_data)\n\n    items = {\n        \"ccs\": ccs,\n        \"skipped-tests\": skipped_tests,\n        \"docs\": docs_info,\n    }\n    commenter.post_items(items=items.items())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_skipped_tests_comment.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport inspect\nimport json\nimport os\nimport logging\nimport subprocess\nfrom xml.etree import ElementTree\nfrom pathlib import Path\nfrom typing import Dict, Any, Optional\n\n\ndef run_subprocess(command):\n    logging.info(f\"Running command {command}\")\n    proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, encoding=\"utf-8\")\n    if proc.returncode != 0:\n        raise RuntimeError(f\"Command failed {command}:\\nstdout:\\n{proc.stdout}\")\n    return proc\n\n\ndef retrieve_test_report(s3_url, target_dir):\n    command = f\"aws --region us-west-2 s3 cp {s3_url} {target_dir} --recursive --no-sign-request\"\n    run_subprocess(command)\n\n\ndef get_common_commit_sha():\n    command = \"git merge-base origin/main HEAD\"\n    proc = run_subprocess(command)\n    return proc.stdout.strip()\n\n\ndef get_main_jenkins_build_number(github, common_commit):\n    json = github.get(f\"commits/{common_commit}/status\")\n    for status in reversed(json[\"statuses\"]):\n        if status[\"context\"] != \"tvm-ci/branch\":\n            continue\n        state = status[\"state\"]\n        target_url = str(status[\"target_url\"])\n        build_number = (\n            target_url[target_url.find(\"job/main\") : len(target_url)]\n            .strip(\"job/main/\")\n            .strip(\"/display/redirect\")\n        )\n        assert build_number.isdigit()\n        return {\"build_number\": build_number, \"state\": state}\n    raise RuntimeError(f\"Failed to find main build number for commit {common_commit}\")\n\n\ndef retrieve_test_reports(\n    common_main_build, pr_number, build_number, s3_prefix, pr_test_report_dir, main_test_report_dir\n):\n    cur_build_s3_link = (\n        f\"s3://{s3_prefix}/tvm/PR-{str(pr_number)}/{str(build_number)}/pytest-results\"\n    )\n    retrieve_test_report(cur_build_s3_link, pr_test_report_dir)\n\n    common_build_s3_link = f\"s3://{s3_prefix}/tvm/main/{common_main_build}/pytest-results\"\n    retrieve_test_report(common_build_s3_link, main_test_report_dir)\n\n\ndef get_pr_and_build_numbers(target_url):\n    target_url = target_url[target_url.find(\"PR-\") : len(target_url)]\n    split = target_url.split(\"/\")\n    pr_number = split[0].strip(\"PR-\")\n    build_number = split[1]\n    return {\"pr_number\": pr_number, \"build_number\": build_number}\n\n\ndef build_test_set(directory):\n    directory = Path(directory)\n    subdir_to_skipped = {}\n    subdirs = [\n        item for item in os.listdir(directory) if os.path.isdir(os.path.join(directory, item))\n    ]\n    for subdir in subdirs:\n        subdir_to_skipped[subdir] = set()\n        for root, _, files in os.walk(directory / subdir):\n            for file in files:\n                test_report = ElementTree.parse(Path(root) / file)\n                for testcase in test_report.iter(\"testcase\"):\n                    skipped = testcase.find(\"skipped\")\n                    if skipped is not None:\n                        key = testcase.attrib[\"classname\"] + \"#\" + testcase.attrib[\"name\"]\n                        subdir_to_skipped[subdir].add(key)\n    return subdir_to_skipped\n\n\ndef to_node_name(dir_name: str):\n    return dir_name.replace(\"_\", \": \", 1)\n\n\ndef build_diff_comment_with_main(\n    common_commit_sha,\n    skipped_list,\n    commit_sha,\n):\n    if len(skipped_list) == 0:\n        return f\"No diff in skipped tests with main found in this branch for commit {commit_sha}.\\n\"\n\n    text = (\n        f\"The list below shows tests that ran in main {common_commit_sha} but were \"\n        f\"skipped in the CI build of {commit_sha}:\\n\"\n        f\"```\\n\"\n    )\n    for skip in skipped_list:\n        text += skip + \"\\n\"\n    text += f\"```\\n\"\n    return text\n\n\ndef build_comment(\n    common_commit_sha,\n    common_main_build,\n    skipped_list,\n    additional_skipped_list,\n    pr_number,\n    build_number,\n    commit_sha,\n    jenkins_prefix,\n):\n    if common_main_build[\"state\"] != \"success\":\n        return f\"Unable to run tests bot because main failed to pass CI at {common_commit_sha}.\"\n\n    text = build_diff_comment_with_main(common_commit_sha, skipped_list, commit_sha)\n\n    if len(additional_skipped_list) != 0:\n        text += \"\\n\"\n        text += (\n            f\"Additional tests that were skipped in the CI build and present in the [`required_tests_to_run`]\"\n            f\"(https://github.com/apache/tvm/blob/main/ci/scripts/required_tests_to_run.json) file:\"\n            f\"\\n```\\n\"\n        )\n        for skip in additional_skipped_list:\n            text += skip + \"\\n\"\n        text += f\"```\\n\"\n\n    text += (\n        f\"A detailed report of ran tests is [here](https://{jenkins_prefix}/job/tvm/job/PR-{str(pr_number)}\"\n        f\"/{str(build_number)}/testReport/).\"\n    )\n    return text\n\n\ndef find_target_url(pr_head: Dict[str, Any]):\n    for status in pr_head[\"statusCheckRollup\"][\"contexts\"][\"nodes\"]:\n        if status.get(\"context\", \"\") == \"tvm-ci/pr-head\":\n            return status[\"targetUrl\"]\n\n    raise RuntimeError(f\"Unable to find tvm-ci/pr-head status in {pr_head}\")\n\n\ndef get_skipped_tests_comment(\n    pr: Dict[str, Any],\n    github,\n    s3_prefix: str = \"tvm-jenkins-artifacts-prod\",\n    jenkins_prefix: str = \"ci.tlcpack.ai\",\n    pr_test_report_dir: str = \"pr-reports\",\n    main_test_report_dir: str = \"main-reports\",\n    common_commit_sha: Optional[str] = None,\n    common_main_build: Optional[Dict[str, Any]] = None,\n    additional_tests_to_check_file: str = \"required_tests_to_run.json\",\n) -> str:\n    pr_head = pr[\"commits\"][\"nodes\"][0][\"commit\"]\n    target_url = find_target_url(pr_head)\n    pr_and_build = get_pr_and_build_numbers(target_url)\n    logging.info(f\"Getting comment for {pr_head} with target {target_url}\")\n\n    commit_sha = pr_head[\"oid\"]\n\n    is_dry_run = common_commit_sha is not None\n\n    if not is_dry_run:\n        logging.info(\"Fetching common commit sha and build info\")\n        common_commit_sha = get_common_commit_sha()\n        common_main_build = get_main_jenkins_build_number(github, common_commit_sha)\n\n        retrieve_test_reports(\n            common_main_build=common_main_build[\"build_number\"],\n            pr_number=pr_and_build[\"pr_number\"],\n            build_number=pr_and_build[\"build_number\"],\n            s3_prefix=s3_prefix,\n            main_test_report_dir=main_test_report_dir,\n            pr_test_report_dir=pr_test_report_dir,\n        )\n    else:\n        logging.info(\"Dry run, expecting PR and main reports on disk\")\n\n    main_tests = build_test_set(main_test_report_dir)\n    build_tests = build_test_set(pr_test_report_dir)\n\n    skipped_list = []\n    for subdir, skipped_set in build_tests.items():\n        skipped_main = main_tests[subdir]\n        if skipped_main is None:\n            logging.warning(f\"Could not find directory {subdir} in main.\")\n            continue\n\n        diff_set = skipped_set - skipped_main\n        if len(diff_set) != 0:\n            for test in diff_set:\n                skipped_list.append(f\"{to_node_name(subdir)} -> {test}\")\n\n    # Sort the list to maintain an order in the output. Helps when validating the output in tests.\n    skipped_list.sort()\n\n    if len(skipped_list) == 0:\n        logging.info(\"No skipped tests found.\")\n\n    if not is_dry_run:\n        current_file = Path(__file__).resolve()\n        additional_tests_to_check_file = Path(current_file).parent / \"required_tests_to_run.json\"\n\n    logging.info(\n        f\"Checking additional tests in file {additional_tests_to_check_file} are not skipped.\"\n    )\n    try:\n        with open(additional_tests_to_check_file, \"r\") as f:\n            additional_tests_to_check = json.load(f)\n    except IOError:\n        logging.info(\n            f\"Failed to read additional tests from file: {additional_tests_to_check_file}.\"\n        )\n        additional_tests_to_check = {}\n\n    # Assert that tests present in \"required_tests_to_run.json\" are not skipped.\n    additional_skipped_tests = []\n    for subdir, test_set in additional_tests_to_check.items():\n        if subdir not in build_tests.keys():\n            logging.warning(f\"Could not find directory {subdir} in the build test set.\")\n            continue\n\n        for test in test_set:\n            if test in build_tests[subdir]:\n                additional_skipped_tests.append(f\"{to_node_name(subdir)} -> {test}\")\n\n    if len(additional_skipped_tests) == 0:\n        logging.info(\"No skipped tests found in the additional list.\")\n\n    body = build_comment(\n        common_commit_sha,\n        common_main_build,\n        skipped_list,\n        additional_skipped_tests,\n        pr_and_build[\"pr_number\"],\n        pr_and_build[\"build_number\"],\n        commit_sha,\n        jenkins_prefix,\n    )\n\n    return body\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_tag_teams.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport json\nimport argparse\nimport logging\nimport re\nfrom typing import Dict, Any, List, Tuple, Optional\n\n\nfrom git_utils import git, GitHubRepo, parse_remote, find_ccs, dry_run_token\nfrom cmd_utils import tags_from_title, init_log\n\n\nGITHUB_NAME_REGEX = r\"@[a-zA-Z0-9-]+\"\n\n\ndef parse_line(line: str) -> Tuple[str, List[str]]:\n    line = line.lstrip(\" -\")\n    line = line.split()\n\n    # Parse out the name as anything up until the first tagged person\n    tag_items = []\n    tag_end = 0\n    for i, piece in enumerate(line):\n        if piece.startswith(\"@\"):\n            tag_end = i\n            break\n\n        tag_items.append(piece)\n\n    tag = \" \".join(tag_items).rstrip(\":\")\n\n    # From the last word that was part of the tag name, start looking for users\n    # tagged with a '@'\n    users = []\n    for piece in line[tag_end:]:\n        if piece.startswith(\"@\"):\n            users.append(piece.lstrip(\"@\"))\n\n    return (tag, list(sorted(users)))\n\n\ndef fetch_issue(github: GitHubRepo, issue_number: int):\n    query = \"\"\"query($owner: String!, $name: String!, $number: Int!){\n    repository(owner: $owner, name: $name) {\n        issue(number: $number) {\n        body\n        comments(first:100) {\n            nodes {\n            body\n            }\n        }\n        }\n    }\n    }\"\"\"\n    r = github.graphql(\n        query,\n        variables={\n            \"owner\": github.user,\n            \"name\": github.repo,\n            \"number\": issue_number,\n        },\n    )\n    return r\n\n\ndef parse_teams(r: Dict[str, Any], issue_number: int) -> Dict[str, str]:\n    \"\"\"\n    Fetch an issue and parse out series of tagged people from the issue body\n    and comments\n    \"\"\"\n    issue = r[\"data\"][\"repository\"][\"issue\"]\n\n    if issue is None or issue.get(\"body\") is None:\n        raise RuntimeError(f\"Could not find issue #{issue_number}\\n\\n{json.dumps(r, indent=2)}\")\n\n    result = {}\n\n    def add_tag(tag, users):\n        if tag in result:\n            result[tag] += users\n        else:\n            result[tag] = users\n\n    # Parse the issue body (only bullets are looked at)\n    for line in issue[\"body\"].split(\"\\n\"):\n        line = line.strip()\n        if not line.startswith(\"- \"):\n            continue\n        if \"@\" not in line:\n            continue\n\n        tag, users = parse_line(line)\n        add_tag(tag, users)\n\n    # Parse comment bodies\n    for comment in issue[\"comments\"][\"nodes\"]:\n        for line in comment[\"body\"].split(\"\\n\"):\n            if \"@\" not in line:\n                continue\n\n            tag, users = parse_line(line)\n            add_tag(tag, users)\n\n    # De-duplicate users listed twice for the same tag\n    for tag in result:\n        result[tag] = list(set(result[tag]))\n\n    return {k.lower(): v for k, v in result.items() if k.strip()}\n\n\ndef tags_from_labels(labels: List[Dict[str, Any]]) -> List[str]:\n    return [label[\"name\"] for label in labels]\n\n\ndef add_ccs_to_body(body: str, to_cc: List[str]) -> str:\n    lines = body.split(\"\\n\")\n\n    cc_line_idx = None\n    for i, line in enumerate(reversed(lines)):\n        if line.strip() == \"\":\n            continue\n        if line.startswith(\"cc @\"):\n            cc_line_idx = len(lines) - i - 1\n        else:\n            break\n\n    def gen_cc_line(users):\n        users = sorted(users)\n        return \"cc \" + \" \".join([f\"@{user}\" for user in users])\n\n    if cc_line_idx is None:\n        print(\"Did not find existing cc line\")\n        lines.append(\"\")\n        lines.append(gen_cc_line(to_cc))\n    else:\n        # Edit cc line in place\n        line = lines[cc_line_idx]\n        print(f\"Found existing cc line at {cc_line_idx}: {line}\")\n        existing_ccs = find_ccs(line)\n        print(f\"Found cc's: {existing_ccs}\")\n\n        if set(to_cc).issubset(set(existing_ccs)):\n            # Don't do anything if there is no update needed\n            return None\n\n        line = gen_cc_line(set(existing_ccs + to_cc))\n\n        lines[cc_line_idx] = line\n\n    return \"\\n\".join(lines)\n\n\ndef determine_users_to_cc(\n    issue: Dict[str, Any], github: GitHubRepo, team_issue: str, issue_data: Optional[Dict[str, Any]]\n) -> List[str]:\n    if issue_data is None:\n        issue_data = fetch_issue(github, issue_number=int(team_issue))\n\n    # Fetch the list of teams\n    teams = parse_teams(issue_data, issue_number=int(team_issue))\n\n    logging.info(f\"Found these teams in issue #{team_issue}\\n{json.dumps(teams, indent=2)}\")\n\n    title = issue[\"title\"]\n    if \"author\" in issue:\n        author = issue[\"author\"][\"login\"]\n    else:\n        author = issue[\"user\"][\"login\"]\n    tags = tags_from_title(title)\n    if isinstance(issue[\"labels\"], dict):\n        tags += tags_from_labels(issue[\"labels\"][\"nodes\"])\n    else:\n        tags += tags_from_labels(issue[\"labels\"])\n\n    tags = [t.lower() for t in tags]\n    logging.info(f\"Found tags: {tags}\")\n\n    # Update the PR or issue based on tags in the title and GitHub tags\n    to_cc = [teams.get(t, []) for t in tags]\n    to_cc = list(set(item for sublist in to_cc for item in sublist))\n    to_cc = [user for user in to_cc if user != author]\n    return to_cc\n\n\ndef get_tags(pr_data: Dict[str, Any], github: GitHubRepo, team_issue: int) -> str:\n    to_cc = determine_users_to_cc(\n        issue=pr_data, github=github, team_issue=team_issue, issue_data=None\n    )\n\n    logging.info(f\"Users to cc based on labels: {to_cc}\")\n    description = \"<sub>See [#10317](https://github.com/apache/tvm/issues/10317) for details</sub>\"\n    if len(to_cc) == 0:\n        return \"No users to tag found in teams \" + description\n\n    return \"cc \" + \", \".join([f\"@{user}\" for user in to_cc]) + \" \" + description\n\n\nif __name__ == \"__main__\":\n    help = \"Automatically tag people based on PR / issue labels\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--team-issue\", default=\"10317\", help=\"issue number to look at for ccs\")\n    parser.add_argument(\n        \"--team-issue-json\", help=\"(testing only) issue JSON to parse rather than fetch from GitHub\"\n    )\n    parser.add_argument(\n        \"--dry-run\",\n        action=\"store_true\",\n        default=False,\n        help=\"run but don't send any request to GitHub\",\n    )\n    args = parser.parse_args()\n    init_log()\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n\n    github = GitHubRepo(token=dry_run_token(args.dry_run), user=user, repo=repo)\n    if args.team_issue_json:\n        issue_data = json.loads(args.team_issue_json)\n    else:\n        issue_data = fetch_issue(github, issue_number=int(args.team_issue))\n\n    # Extract the payload from GitHub Actions\n    issue = json.loads(os.getenv(\"ISSUE\", \"null\"))\n    pr = json.loads(os.getenv(\"PR\", \"null\"))\n    if (issue is None and pr is None) or (issue is not None and pr is not None):\n        raise RuntimeError(\"Exactly one of $PR or $ISSUE must be set in the environment\")\n\n    if pr is not None:\n        if pr[\"draft\"]:\n            print(f\"Terminating since {pr['number']} is a draft\")\n            exit(0)\n\n    # PRs/issues have the same structure for the fields needed here\n    item = issue if issue is not None else pr\n    title = item[\"title\"]\n    body = item[\"body\"]\n\n    to_cc = determine_users_to_cc(\n        issue=item, github=github, team_issue=args.team_issue, issue_data=issue_data\n    )\n    existing_tags = list(set(re.findall(GITHUB_NAME_REGEX, body)))\n    existing_tags = set(tag.replace(\"@\", \"\") for tag in existing_tags)\n    logging.info(f\"Found existing tags: {existing_tags}\")\n    to_cc = [user for user in to_cc if user not in existing_tags]\n    logging.info(\"Users to cc based on labels\", to_cc)\n\n    # Create the new PR/issue body\n    if len(to_cc) == 0:\n        logging.info(\"No one to cc, exiting\")\n        exit(0)\n\n    new_body = add_ccs_to_body(body, to_cc)\n    if new_body is None:\n        logging.info(f\"Everyone to cc is already cc'ed, no update needed\")\n        exit(0)\n\n    logging.info(f\"Changing body from:\\n----\\n{body}\\n----\\nto:\\n----\\n{new_body}\\n----\")\n\n    # Set the PR/issue body on GitHub\n    data = {\"body\": new_body}\n    if issue is not None:\n        issue_number = issue[\"number\"]\n        url = f\"issues/{issue_number}\"\n    elif pr is not None:\n        pr_number = pr[\"number\"]\n        url = f\"pulls/{pr_number}\"\n    else:\n        raise RuntimeError(\"Unreachable, please report a bug with a link to the failed workflow\")\n\n    if not args.dry_run:\n        github.post(url, data=data)\n    else:\n        logging.info(f\"Dry run, would have updated {url} with {data}\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/github_tvmbot.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport json\nimport argparse\nimport warnings\nimport logging\nimport traceback\nimport re\nfrom typing import Dict, Any, List, Optional, Callable, Union\nfrom pathlib import Path\n\nfrom git_utils import git, GitHubRepo, parse_remote, post\nfrom cmd_utils import init_log\n\n\nReview = Dict[str, Any]\nCIJob = Dict[str, Any]\nComment = Dict[str, Any]\nCommentChecker = Callable[[Comment], bool]\n\nEXPECTED_JOBS = [\"tvm-ci/pr-head\"]\nTVM_BOT_JENKINS_TOKEN = os.environ[\"TVM_BOT_JENKINS_TOKEN\"]\nGH_ACTIONS_TOKEN = os.environ[\"GH_ACTIONS_TOKEN\"]\nJENKINS_URL = \"https://ci.tlcpack.ai/\"\nTHANKS_MESSAGE = r\"(\\s*)Thanks for contributing to TVM!   Please refer to guideline https://tvm.apache.org/docs/contribute/ for useful information and tips. After the pull request is submitted, please request code reviews from \\[Reviewers\\]\\(https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers\\) by  them in the pull request thread.(\\s*)\"\n\n\ndef to_json_str(obj: Any) -> str:\n    return json.dumps(obj, indent=2)\n\n\nCOLLABORATORS_QUERY = \"\"\"\nquery ($owner: String!, $name: String!, $user: String!) {\n  repository(owner: $owner, name: $name) {\n    collaborators(query: $user, first: 100) {\n      nodes {\n        login\n      }\n    }\n  }\n}\n\"\"\"\n\nMENTIONABLE_QUERY = \"\"\"\nquery ($owner: String!, $name: String!, $user: String!) {\n  repository(owner: $owner, name: $name) {\n    mentionableUsers(query: $user, first: 100) {\n      nodes {\n        login\n      }\n    }\n  }\n}\n\"\"\"\n\n\nPR_QUERY = \"\"\"\n    query ($owner: String!, $name: String!, $number: Int!) {\n      repository(owner: $owner, name: $name) {\n        pullRequest(number: $number) {\n          title\n          body\n          state\n          author {\n            login\n          }\n          comments(last: 100) {\n            pageInfo {\n              hasPreviousPage\n            }\n            nodes {\n              authorAssociation\n              author {\n                login\n              }\n              id\n              updatedAt\n              body\n            }\n          }\n          authorCommits:commits(last:100) {\n            nodes {\n              commit {\n                authors(first:100) {\n                  nodes {\n                    name\n                    email\n                  }\n                }\n              }\n            }\n          }\n          commits(last: 1) {\n            nodes {\n              commit {\n                oid\n                statusCheckRollup {\n                  contexts(first: 100) {\n                    pageInfo {\n                      hasNextPage\n                    }\n                    nodes {\n                      ... on CheckRun {\n                        name\n                        databaseId\n                        checkSuite {\n                          workflowRun {\n                            databaseId\n                            workflow {\n                              name\n                            }\n                          }\n                        }\n                        status\n                        conclusion\n                        url\n                      }\n                      ... on StatusContext {\n                        state\n                        context\n                        targetUrl\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n          reviewDecision\n          reviews(last: 100) {\n            pageInfo {\n              hasPreviousPage\n            }\n            nodes {\n              body\n              updatedAt\n              url\n              id\n              authorCanPushToRepository\n              commit {\n                oid\n              }\n              author {\n                login\n              }\n              state\n            }\n          }\n        }\n      }\n    }\n    \"\"\"\n\n\ndef walk(obj, visitor, parent_key=None):\n    \"\"\"\n    Recursively call 'visitor' on all the children of a dictionary\n    \"\"\"\n    visitor(obj, parent_key)\n    if isinstance(obj, dict):\n        for k, v in obj.items():\n            walk(v, visitor, parent_key=k)\n    elif isinstance(obj, list):\n        for v in obj:\n            walk(v, visitor)\n\n\nclass PR:\n    def __init__(\n        self,\n        number: int,\n        owner: str,\n        repo: str,\n        dry_run: bool = False,\n        raw_data: Dict[str, Any] = None,\n    ):\n        self.owner = owner\n        self.number = number\n        self.repo_name = repo\n        self.dry_run = dry_run\n        self.has_error = False\n\n        if dry_run and raw_data:\n            # In test mode there is no need to fetch anything\n            self.raw = raw_data\n            self.github = None\n        else:\n            self.github = GitHubRepo(user=owner, repo=repo, token=os.environ[\"GITHUB_TOKEN\"])\n            if os.getenv(\"DEBUG\", \"0\") == \"1\":\n                # For local runs fill in the requested data but cache it for\n                # later use\n                cached_path = Path(\"pr.json\")\n                if not cached_path.exists():\n                    self.raw = self.fetch_data()\n                    with open(cached_path, \"w\") as f:\n                        json.dump(self.raw, f, indent=2)\n                else:\n                    with open(cached_path) as f:\n                        self.raw = json.load(f)\n            else:\n                # Usual path, fetch the PR's data based on the number from\n                # GitHub\n                self.raw = self.fetch_data()\n\n        def checker(obj, parent_key):\n            \"\"\"\n            Verify that any paged results don't have extra data (if so the bot\n            may still work since most relevant comments will be more recent)\n            \"\"\"\n            if parent_key == \"pageInfo\":\n                if obj.get(\"hasPreviousPage\", False):\n                    warnings.warn(f\"Found {obj} with a previous page, bot may be missing data\")\n                if obj.get(\"hasNextPage\", False):\n                    warnings.warn(f\"Found {obj} with a next page, bot may be missing data\")\n\n        walk(self.raw, checker)\n\n        logging.info(f\"Verified data, running with PR {to_json_str(self.raw)}\")\n\n    def __repr__(self):\n        return json.dumps(self.raw, indent=2)\n\n    def react(self, comment: Dict[str, Any], content: str):\n        \"\"\"\n        React with a thumbs up to a comment\n        \"\"\"\n        url = f\"issues/comments/{comment['id']}/reactions\"\n        data = {\"content\": content}\n        if self.dry_run:\n            logging.info(f\"Dry run, would have +1'ed to {url} with {data}\")\n        else:\n            self.github.post(url, data=data)\n\n    def head_commit(self):\n        return self.raw[\"commits\"][\"nodes\"][0][\"commit\"]\n\n    def co_authors(self) -> List[str]:\n        authors = []\n        for commit in self.raw[\"authorCommits\"][\"nodes\"]:\n            # Co-authors always come after the main author according to the\n            # GitHub docs, so ignore the first item\n            for author in commit[\"commit\"][\"authors\"][\"nodes\"][1:]:\n                name = author[\"name\"]\n                email = author[\"email\"]\n                authors.append(f\"{name} <{email}>\")\n\n        return list(set(authors))\n\n    def head_oid(self):\n        return self.head_commit()[\"oid\"]\n\n    def ci_jobs(self) -> List[CIJob]:\n        \"\"\"\n        Get a list of all CI jobs (GitHub Actions and other) in a unified format\n        \"\"\"\n        jobs = []\n        for item in self.head_commit()[\"statusCheckRollup\"][\"contexts\"][\"nodes\"]:\n            if \"checkSuite\" in item:\n                # GitHub Actions job, parse separately\n                status = item[\"conclusion\"]\n                if status is None:\n                    # If the 'conclusion' isn't filled out the job hasn't\n                    # finished yet\n                    status = \"PENDING\"\n                workflow_name = item[\"checkSuite\"][\"workflowRun\"][\"workflow\"][\"name\"]\n                if workflow_name != \"CI\":\n                    # Ignore all jobs that aren't in the main.yml workflow (these are mostly\n                    # automation jobs that run on PRs for tagging / reviews)\n                    continue\n                check_name = item[\"name\"]\n                jobs.append(\n                    {\n                        \"name\": f\"{workflow_name} / {check_name}\",\n                        \"url\": item[\"url\"],\n                        \"status\": status.upper(),\n                    }\n                )\n            else:\n                # GitHub Status (e.g. from Jenkins)\n                jobs.append(\n                    {\n                        \"name\": item[\"context\"],\n                        \"url\": item[\"targetUrl\"],\n                        \"status\": item[\"state\"].upper(),\n                    }\n                )\n\n        logging.info(f\"Found CI jobs for {self.head_commit()['oid']} {to_json_str(jobs)}\")\n        return jobs\n\n    def reviews(self) -> List[Review]:\n        return self.raw[\"reviews\"][\"nodes\"]\n\n    def head_commit_reviews(self) -> List[Review]:\n        \"\"\"\n        Find reviews associated with the head commit\n        \"\"\"\n        commits_to_review_status: Dict[str, List[Review]] = {}\n\n        for review in self.reviews():\n            if not review[\"authorCanPushToRepository\"]:\n                # ignore reviews from non-committers\n                continue\n\n            oid = review[\"commit\"][\"oid\"]\n            if oid in commits_to_review_status:\n                commits_to_review_status[oid].append(review)\n            else:\n                commits_to_review_status[oid] = [review]\n\n        # Only use the data for the head commit of the PR\n        head_reviews = commits_to_review_status.get(self.head_oid(), [])\n        return head_reviews\n\n    def fetch_data(self):\n        \"\"\"\n        Fetch the data for this PR from GitHub\n        \"\"\"\n        return self.github.graphql(\n            query=PR_QUERY,\n            variables={\n                \"owner\": self.owner,\n                \"name\": self.repo_name,\n                \"number\": self.number,\n            },\n        )[\"data\"][\"repository\"][\"pullRequest\"]\n\n    def search_collaborator(self, user: str) -> List[Dict[str, Any]]:\n        \"\"\"\n        Query GitHub for collaborators matching 'user'\n        \"\"\"\n        return self.search_users(user, COLLABORATORS_QUERY)[\"collaborators\"][\"nodes\"]\n\n    def search_users(self, user: str, query: str) -> List[Dict[str, Any]]:\n        return self.github.graphql(\n            query=query,\n            variables={\n                \"owner\": self.owner,\n                \"name\": self.repo_name,\n                \"user\": user,\n            },\n        )[\"data\"][\"repository\"]\n\n    def search_mentionable_users(self, user: str) -> List[Dict[str, Any]]:\n        return self.search_users(user, MENTIONABLE_QUERY)[\"mentionableUsers\"][\"nodes\"]\n\n    def comment(self, text: str) -> None:\n        \"\"\"\n        Leave the comment 'text' on this PR\n        \"\"\"\n        logging.info(f\"Commenting:\\n{text}\")\n        # TODO: Update latest comment in-place if there has been no activity\n        data = {\"body\": text}\n        url = f\"issues/{self.number}/comments\"\n        if self.dry_run:\n            logging.info(\n                f\"Dry run, would have commented on url={url} commenting with data={to_json_str(data)}\"\n            )\n            return\n\n        self.github.post(url, data=data)\n\n    def state(self) -> str:\n        \"\"\"\n        PR state (OPEN, CLOSED, MERGED, etc)\n        \"\"\"\n        return self.raw[\"state\"]\n\n    def processed_body(self) -> str:\n        body = self.raw[\"body\"].strip().replace(\"\\r\", \"\")\n        # Remove any @-mentions of people\n        body = re.sub(r\"(\\s)@\", \"\\g<1>\", body)\n\n        # Remove the auto-inserted text since it's not useful to have in the commit log\n        body = re.sub(THANKS_MESSAGE, \"\\n\\n\", body)\n        return body.strip()\n\n    def body_with_co_authors(self) -> str:\n        \"\"\"\n        Add 'Co-authored-by' strings to the PR body based on the prior commits\n        in the PR\n        \"\"\"\n        body = self.processed_body()\n        author_lines = self.co_authors()\n        logging.info(f\"Found co-authors: author_lines={author_lines}\")\n        full_author_lines = [f\"Co-authored-by: {author_line}\" for author_line in author_lines]\n\n        authors_to_add = []\n        for author_line in author_lines:\n            if author_line not in body:\n                authors_to_add.append(f\"Co-authored-by: {author_line}\")\n\n        if len(authors_to_add) > 0:\n            # If the line isn't already in the PR body (it could have been\n            # added manually), put it in\n            full_author_text = \"\\n\".join(authors_to_add)\n            body = f\"{body}\\n\\n{full_author_text}\"\n\n        return body\n\n    def merge(self) -> None:\n        \"\"\"\n        Request a merge of this PR via the GitHub API\n        \"\"\"\n        url = f\"pulls/{self.number}/merge\"\n\n        title = self.raw[\"title\"] + f\" (#{self.number})\"\n        body = self.body_with_co_authors()\n        logging.info(f\"Full commit:\\n{title}\\n\\n{body}\")\n\n        data = {\n            \"commit_title\": title,\n            \"commit_message\": body,\n            # The SHA is necessary in case there was an update right when this\n            # script ran, GitHub will sort out who won\n            \"sha\": self.head_oid(),\n            \"merge_method\": \"squash\",\n        }\n        if self.dry_run:\n            logging.info(f\"Dry run, would have merged with url={url} and data={to_json_str(data)}\")\n            return\n\n        r = self.github.put(url, data=data)\n        logging.info(f\"GitHub merge response: {r}\")\n        return r\n\n    def author(self) -> str:\n        return self.raw[\"author\"][\"login\"]\n\n    def find_failed_ci_jobs(self) -> List[CIJob]:\n        # NEUTRAL is GitHub Action's way of saying cancelled\n        return [\n            job\n            for job in self.ci_jobs()\n            if job[\"status\"] not in {\"SUCCESS\", \"SUCCESSFUL\", \"SKIPPED\"}\n        ]\n\n    def find_missing_expected_jobs(self) -> List[str]:\n        # Map of job name: has seen in completed jobs\n        seen_expected_jobs = {name: False for name in EXPECTED_JOBS}\n        logging.info(f\"Expected to see jobs: {seen_expected_jobs}\")\n\n        missing_expected_jobs = []\n        for job in self.ci_jobs():\n            seen_expected_jobs[job[\"name\"]] = True\n\n        for name, seen in seen_expected_jobs.items():\n            if not seen:\n                missing_expected_jobs.append(name)\n\n        return missing_expected_jobs\n\n    def trigger_gha_ci(self, sha: str) -> None:\n        logging.info(f\"POST-ing a workflow_dispatch event to main.yml\")\n        actions_github = GitHubRepo(\n            user=self.github.user, repo=self.github.repo, token=GH_ACTIONS_TOKEN\n        )\n        r = actions_github.post(\n            url=\"actions/workflows/main.yml/dispatches\",\n            data={\n                \"ref\": \"main\",\n            },\n        )\n        logging.info(f\"Successful workflow_dispatch: {r}\")\n\n    def merge_if_passed_checks(self) -> Optional[Dict[str, Any]]:\n        failed_ci_jobs = self.find_failed_ci_jobs()\n        all_ci_passed = len(failed_ci_jobs) == 0\n        has_one_approval = False\n\n        if not all_ci_passed:\n            failed_jobs_msg = \"\\n\".join(\n                [f\" * [{job['name']} (`{job['status']}`)]({job['url']})\" for job in failed_ci_jobs]\n            )\n            self.comment(\n                f\"Cannot merge, these CI jobs are not successful on {self.head_oid()}:\\n{failed_jobs_msg}\"\n            )\n            return None\n\n        missing_expected_jobs = self.find_missing_expected_jobs()\n\n        if len(missing_expected_jobs) > 0:\n            missing_jobs_msg = \"\\n\".join([f\" * `{name}`\" for name in missing_expected_jobs])\n            self.comment(f\"Cannot merge, missing expected jobs:\\n{missing_jobs_msg}\")\n            return None\n\n        head_commit_reviews = self.head_commit_reviews()\n        for review in head_commit_reviews:\n            if review[\"state\"] == \"CHANGES_REQUESTED\":\n                self.comment(\n                    f\"Cannot merge, found [this review]({review['url']}) on {self.head_oid()} with changes requested\"\n                )\n                return None\n\n            if review[\"state\"] == \"APPROVED\":\n                has_one_approval = True\n                logging.info(f\"Found approving review: {to_json_str(review)}\")\n\n        if has_one_approval and all_ci_passed:\n            return self.merge()\n        elif not has_one_approval:\n            self.comment(\n                f\"Cannot merge, did not find any approving reviews from users with write access on {self.head_oid()}\"\n            )\n            return None\n        elif not all_ci_passed:\n            self.comment(f\"Cannot merge, CI did not pass on on {self.head_oid()}\")\n            return None\n\n    def rerun_jenkins_ci(self) -> None:\n        url = JENKINS_URL + f\"job/tvm/job/PR-{self.number}/buildWithParameters\"\n        logging.info(f\"Rerunning ci with URL={url}\")\n        if self.dry_run:\n            logging.info(\"Dry run, not sending POST\")\n        else:\n            post(url, auth=(\"tvm-bot\", TVM_BOT_JENKINS_TOKEN))\n\n    def rerun_github_actions(self) -> None:\n        workflow_ids = []\n        for item in self.head_commit()[\"statusCheckRollup\"][\"contexts\"][\"nodes\"]:\n            if \"checkSuite\" in item and item[\"conclusion\"] == \"FAILURE\":\n                workflow_id = item[\"checkSuite\"][\"workflowRun\"][\"databaseId\"]\n                workflow_ids.append(workflow_id)\n\n        workflow_ids = list(set(workflow_ids))\n        logging.info(f\"Rerunning GitHub Actions workflows with IDs: {workflow_ids}\")\n        if self.dry_run:\n            actions_github = None\n        else:\n            actions_github = GitHubRepo(\n                user=self.github.user, repo=self.github.repo, token=GH_ACTIONS_TOKEN\n            )\n        for workflow_id in workflow_ids:\n            if self.dry_run:\n                logging.info(f\"Dry run, not restarting workflow {workflow_id}\")\n            else:\n                try:\n                    actions_github.post(f\"actions/runs/{workflow_id}/rerun-failed-jobs\", data={})\n                except RuntimeError as e:\n                    logging.exception(e)\n                    # Ignore errors about jobs that are part of the same workflow to avoid\n                    # having to figure out which jobs are in which workflows ahead of time\n                    if \"The workflow run containing this job is already running\" in str(e):\n                        pass\n                    else:\n                        raise e\n\n    def comment_failure(self, msg: str, exceptions: Union[Exception, List[Exception]]):\n        if not isinstance(exceptions, list):\n            exceptions = [exceptions]\n\n        logging.info(f\"Failed, commenting {exceptions}\")\n\n        # Extract all the traceback strings\n        for item in exceptions:\n            try:\n                raise item\n            except Exception:\n                item.exception_msg = traceback.format_exc()\n\n        comment = f\"{msg} in {args.run_url}\\n\\n\"\n        for exception in exceptions:\n            comment += f\"<details>\\n\\n```\\n{exception.exception_msg}\\n```\\n\\n\"\n            if hasattr(exception, \"read\"):\n                comment += f\"with response\\n\\n```\\n{exception.read().decode()}\\n```\\n\\n\"\n            comment += \"</details>\"\n\n        pr.comment(comment)\n        pr.has_error = True\n        return exception\n\n\ndef check_author(pr, triggering_comment, args):\n    comment_author = triggering_comment[\"user\"][\"login\"]\n    if pr.author() == comment_author:\n        logging.info(\"Comment user is PR author, continuing\")\n        return True\n    return False\n\n\ndef search_users(name, triggering_comment, testing_json, search_fn):\n    logging.info(f\"Checking {name}\")\n    commment_author = triggering_comment[\"user\"][\"login\"]\n    if testing_json:\n        matching_users = json.loads(testing_json)\n    else:\n        matching_users = search_fn(commment_author)\n    logging.info(f\"Found {name}: {matching_users}\")\n    user_names = {user[\"login\"] for user in matching_users}\n\n    return len(matching_users) > 0 and commment_author in user_names\n\n\ndef check_collaborator(pr, triggering_comment, args):\n    return search_users(\n        name=\"collaborators\",\n        triggering_comment=triggering_comment,\n        search_fn=pr.search_collaborator,\n        testing_json=args.testing_collaborators_json,\n    )\n\n\ndef check_mentionable_users(pr, triggering_comment, args):\n    return search_users(\n        name=\"mentionable users\",\n        triggering_comment=triggering_comment,\n        search_fn=pr.search_mentionable_users,\n        testing_json=args.testing_mentionable_users_json,\n    )\n\n\nAUTH_CHECKS = {\n    \"metionable_users\": check_mentionable_users,\n    \"collaborators\": check_collaborator,\n    \"author\": check_author,\n}\n# Stash the keys so they're accessible from the values\nAUTH_CHECKS = {k: (k, v) for k, v in AUTH_CHECKS.items()}\n\n\nclass Merge:\n    triggers = [\n        \"merge\",\n        \"merge this\",\n        \"merge this pr\",\n    ]\n\n    auth = [AUTH_CHECKS[\"collaborators\"], AUTH_CHECKS[\"author\"]]\n\n    @staticmethod\n    def run(pr: PR):\n        info = None\n        try:\n            info = pr.merge_if_passed_checks()\n        except Exception as e:\n            pr.comment_failure(\"Failed to process merge request\", e)\n            raise e\n\n        if info is not None:\n            try:\n                pr.trigger_gha_ci(sha=info[\"sha\"])\n            except Exception as e:\n                pr.comment_failure(\"Failed to trigger GitHub Actions\", e)\n                raise e\n\n\nclass Rerun:\n    triggers = [\n        \"rerun\",\n        \"rerun ci\",\n        \"re-run\",\n        \"re-run ci\",\n        \"run\",\n        \"run ci\",\n    ]\n\n    auth = [AUTH_CHECKS[\"metionable_users\"]]\n\n    @staticmethod\n    def run(pr: PR):\n        errors = []\n        try:\n            pr.rerun_jenkins_ci()\n        except Exception as e:\n            errors.append(e)\n\n        try:\n            pr.rerun_github_actions()\n        except Exception as e:\n            errors.append(e)\n\n        if len(errors) > 0:\n            pr.comment_failure(\"Failed to re-run CI\", errors)\n\n\nif __name__ == \"__main__\":\n    help = \"Check if a PR has comments trying to merge it, and do so based on reviews/CI status\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--pr\", required=True, help=\"pr number to check\")\n    parser.add_argument(\"--run-url\", required=True, help=\"workflow run URL\")\n    parser.add_argument(\n        \"--trigger-comment-json\", required=True, help=\"json of the comment that triggered this run\"\n    )\n    parser.add_argument(\"--testing-pr-json\", help=\"(testing only) manual data for testing\")\n    parser.add_argument(\n        \"--testing-collaborators-json\", help=\"(testing only) manual data for testing\"\n    )\n    parser.add_argument(\n        \"--testing-mentionable-users-json\", help=\"(testing only) manual data for testing\"\n    )\n    parser.add_argument(\n        \"--dry-run\",\n        action=\"store_true\",\n        default=False,\n        help=\"run but don't send any request to GitHub\",\n    )\n    args = parser.parse_args()\n    init_log()\n    comment = json.loads(args.trigger_comment_json)\n    body = comment[\"body\"].strip()\n\n    # Check that the comment was addressed to tvm-bot\n    if not body.startswith(\"@tvm-bot \"):\n        logging.info(f\"Not a bot comment, '{body}' does not start with '@tvm-bot'\")\n        exit(0)\n\n    # Find the code to run for the command from the user\n    user_command = body.lstrip(\"@tvm-bot\").strip()\n    command_to_run = None\n    for command in [Merge, Rerun]:\n        if user_command in command.triggers:\n            command_to_run = command\n            break\n\n    if command_to_run is None:\n        logging.info(f\"Command '{user_command}' did not match anything\")\n        exit(0)\n\n    # Find the remote for querying more data about the PR\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    logging.info(f\"Using remote remote={remote}\")\n    owner, repo = parse_remote(remote)\n\n    if args.pr.strip() == \"\":\n        logging.info(\"No PR number passed\")\n        exit(0)\n\n    logging.info(f\"Checking owner={owner} repo={repo}\")\n    if args.testing_pr_json:\n        pr = PR(\n            number=int(args.pr),\n            owner=owner,\n            repo=repo,\n            dry_run=args.dry_run,\n            raw_data=json.loads(args.testing_pr_json),\n        )\n    else:\n        pr = PR(number=int(args.pr), owner=owner, repo=repo, dry_run=args.dry_run)\n\n    for name, check in command_to_run.auth:\n        if check(pr, comment, args):\n            logging.info(f\"Passed auth check '{name}', continuing\")\n            # Only one authorization check needs to pass (e.g. just mentionable\n            # or PR author), not all of them so quit\n            break\n        else:\n            logging.info(f\"Failed auth check '{name}', quitting\")\n            # Add a sad face\n            pr.react(comment, \"confused\")\n            exit(0)\n\n    # Acknowledge the comment with a react\n    pr.react(comment, \"+1\")\n\n    state = pr.state()\n\n    if state != \"OPEN\":\n        logging.info(f\"Ignoring event on PR, state was not OPEN, instead was state={state}\")\n        exit(0)\n\n    # Run the command\n    command_to_run.run(pr)\n\n    if pr.has_error:\n        raise RuntimeError(\"PR commented a failure\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/http_utils.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport logging\nfrom urllib import request\nfrom typing import Dict, Any, Optional\n\n\ndef get(url: str, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:\n    logging.info(f\"Requesting GET to {url}\")\n    if headers is None:\n        headers = {}\n    req = request.Request(url, headers=headers)\n    with request.urlopen(req) as response:\n        response_headers = {k: v for k, v in response.getheaders()}\n        response = json.loads(response.read())\n\n    return response, response_headers\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/open_docker_update_pr.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport re\nimport logging\nimport datetime\nimport os\nimport json\nimport re\nfrom urllib import error\nfrom typing import List, Dict, Any, Optional, Callable\nfrom git_utils import git, parse_remote, GitHubRepo\nfrom cmd_utils import REPO_ROOT, init_log, Sh\nfrom should_rebuild_docker import docker_api\n\nJENKINSFILE = REPO_ROOT / \"ci\" / \"jenkins\" / \"Jenkinsfile.j2\"\nGENERATED_JENKINSFILE = REPO_ROOT / \"Jenkinsfile\"\nGENERATE_SCRIPT = REPO_ROOT / \"ci\" / \"jenkins\" / \"generate.py\"\nGITHUB_TOKEN = os.environ[\"GITHUB_TOKEN\"]\nBRANCH = \"nightly-docker-update\"\n\n\ndef _testing_docker_api(data: Dict[str, Any]) -> Callable[[str], Dict[str, Any]]:\n    \"\"\"Returns a function that can be used in place of docker_api\"\"\"\n\n    def mock(url: str) -> Dict[str, Any]:\n        if url in data:\n            return data[url]\n        else:\n            raise error.HTTPError(url, 404, f\"Not found: {url}\", {}, None)\n\n    return mock\n\n\ndef parse_docker_date(d: str) -> datetime.datetime:\n    \"\"\"Turn a date string from the Docker API into a datetime object\"\"\"\n    return datetime.datetime.strptime(d, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n\n\ndef check_tag(tag: Dict[str, Any]) -> bool:\n    return re.match(r\"^[0-9]+-[0-9]+-[a-z0-9]+$\", tag[\"name\"]) is not None\n\n\ndef latest_tag(user: str, repo: str) -> List[Dict[str, Any]]:\n    \"\"\"\n    Queries Docker Hub and finds the most recent tag for the specified image/repo pair\n    \"\"\"\n    r = docker_api(f\"repositories/{user}/{repo}/tags\")\n    results = r[\"results\"]\n\n    for result in results:\n        result[\"last_updated\"] = parse_docker_date(result[\"last_updated\"])\n\n    results = list(sorted(results, key=lambda d: d[\"last_updated\"]))\n    results = [tag for tag in results if check_tag(tag)]\n    return results[-1]\n\n\ndef latest_tlcpackstaging_image(source: str) -> Optional[str]:\n    \"\"\"\n    Finds the latest full tag to use in the Jenkinsfile or returns None if no\n    update is needed\n    \"\"\"\n    name, current_tag = source.split(\":\")\n    user, repo = name.split(\"/\")\n    logging.info(\n        f\"Running with name: {name}, current_tag: {current_tag}, user: {user}, repo: {repo}\"\n    )\n\n    staging_repo = repo.replace(\"-\", \"_\")\n    latest_tlcpackstaging_tag = latest_tag(user=\"tlcpackstaging\", repo=staging_repo)\n    logging.info(f\"Found latest tlcpackstaging tag:\\n{latest_tlcpackstaging_tag}\")\n\n    if latest_tlcpackstaging_tag[\"name\"] == current_tag:\n        logging.info(f\"tlcpackstaging tag is the same as the one in the Jenkinsfile\")\n\n    latest_tlcpack_tag = latest_tag(user=\"tlcpack\", repo=repo)\n    logging.info(f\"Found latest tlcpack tag:\\n{latest_tlcpack_tag}\")\n\n    if latest_tlcpack_tag[\"name\"] == latest_tlcpackstaging_tag[\"name\"]:\n        logging.info(\"Tag names were the same, no update needed\")\n        return None\n\n    if latest_tlcpack_tag[\"last_updated\"] > latest_tlcpackstaging_tag[\"last_updated\"]:\n        new_spec = f\"tlcpack/{repo}:{latest_tlcpack_tag['name']}\"\n    else:\n        # Even if the image doesn't exist in tlcpack, it will fall back to tlcpackstaging\n        # so hardcode the username here\n        new_spec = f\"tlcpack/{repo}:{latest_tlcpackstaging_tag['name']}\"\n        logging.info(\"Using tlcpackstaging tag on tlcpack\")\n\n    logging.info(f\"Found newer image, using: {new_spec}\")\n    return new_spec\n\n\nif __name__ == \"__main__\":\n    init_log()\n    help = \"Open a PR to update the Docker images to use the latest available in tlcpackstaging\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"don't send PR to GitHub\")\n    parser.add_argument(\"--testing-docker-data\", help=\"JSON data to mock Docker Hub API response\")\n    args = parser.parse_args()\n\n    # Install test mock if necessary\n    if args.testing_docker_data is not None:\n        docker_api = _testing_docker_api(data=json.loads(args.testing_docker_data))\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n\n    # Read the existing images from the Jenkinsfile\n    logging.info(f\"Reading {JENKINSFILE}\")\n    with open(JENKINSFILE) as f:\n        content = f.readlines()\n\n    # Build a new Jenkinsfile with the latest images from tlcpack or tlcpackstaging\n    new_content = []\n    replacements = {}\n    for line in content:\n        m = re.match(r\"^(ci_[a-zA-Z0-9]+) = \\'(.*)\\'\", line.strip())\n        if m is not None:\n            logging.info(f\"Found match on line {line.strip()}\")\n            groups = m.groups()\n            new_image = latest_tlcpackstaging_image(groups[1])\n            if new_image is None:\n                logging.info(f\"No new image found\")\n                new_content.append(line)\n            else:\n                logging.info(f\"Using new image {new_image}\")\n                new_line = f\"{groups[0]} = '{new_image}'\\n\"\n                new_content.append(new_line)\n                replacements[line] = new_line\n        else:\n            new_content.append(line)\n\n    # Write out the new content\n    if args.dry_run:\n        logging.info(f\"Dry run, would have written new content to {JENKINSFILE}\")\n    else:\n        logging.info(f\"Writing new content to {JENKINSFILE}\")\n        with open(JENKINSFILE, \"w\") as f:\n            f.write(\"\".join(new_content))\n\n    # Re-generate the Jenkinsfile\n    logging.info(f\"Editing {GENERATED_JENKINSFILE}\")\n    with open(GENERATED_JENKINSFILE) as f:\n        generated_content = f.read()\n\n    for original_line, new_line in replacements.items():\n        generated_content = generated_content.replace(original_line, new_line)\n\n    if args.dry_run:\n        print(f\"Would have written:\\n{generated_content}\")\n    else:\n        with open(GENERATED_JENKINSFILE, \"w\") as f:\n            f.write(generated_content)\n\n    # Publish the PR\n    title = \"[ci][docker] Nightly Docker image update\"\n    body = \"This bumps the Docker images to the latest versions from Docker Hub.\"\n    message = f\"{title}\\n\\n\\n{body}\"\n\n    if args.dry_run:\n        logging.info(\"Dry run, would have committed Jenkinsfile\")\n    else:\n        logging.info(f\"Creating git commit\")\n        git([\"checkout\", \"-B\", BRANCH])\n        git([\"add\", str(JENKINSFILE.relative_to(REPO_ROOT))])\n        git([\"add\", str(GENERATED_JENKINSFILE.relative_to(REPO_ROOT))])\n        git([\"config\", \"user.name\", \"tvm-bot\"])\n        git([\"config\", \"user.email\", \"95660001+tvm-bot@users.noreply.github.com\"])\n        git([\"commit\", \"-m\", message])\n        git([\"push\", \"--set-upstream\", args.remote, BRANCH, \"--force\"])\n\n    logging.info(f\"Sending PR to GitHub\")\n    github = GitHubRepo(user=user, repo=repo, token=GITHUB_TOKEN)\n    data = {\n        \"title\": title,\n        \"body\": body,\n        \"head\": BRANCH,\n        \"base\": \"main\",\n        \"maintainer_can_modify\": True,\n    }\n    url = \"pulls\"\n    if args.dry_run:\n        logging.info(f\"Dry run, would have sent {data} to {url}\")\n    else:\n        try:\n            github.post(url, data=data)\n        except error.HTTPError as e:\n            # Ignore the exception if the PR already exists (which gives a 422). The\n            # existing PR will have been updated in place\n            if e.code == 422:\n                logging.info(\"PR already exists, ignoring error\")\n                logging.exception(e)\n            else:\n                raise e\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/ping_reviewers.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport argparse\nimport re\nimport datetime\nimport json\nimport textwrap\nfrom typing import Dict, Any, List\n\nfrom git_utils import git, GitHubRepo, parse_remote\n\nGIT_DATE_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\"\n\n\ndef prs_query(user: str, repo: str, cursor: str = None):\n    after = \"\"\n    if cursor is not None:\n        after = f', before:\"{cursor}\"'\n    time_keys = \"createdAt updatedAt lastEditedAt publishedAt\"\n    return f\"\"\"\n        {{\n    repository(name: \"{repo}\", owner: \"{user}\") {{\n        pullRequests(states: [OPEN], last: 10{after}) {{\n        edges {{\n            cursor\n        }}\n        nodes {{\n            number\n            url\n            body\n            {time_keys}\n            isDraft\n            author {{\n                login\n            }}\n            reviews(last:100) {{\n                nodes {{\n                    {time_keys}\n                    bodyText\n                    author {{ login }}\n                    comments(last:100) {{\n                        nodes {{\n                            {time_keys}\n                            bodyText\n                        }}\n                    }}\n                }}\n            }}\n            comments(last:100) {{\n                nodes {{\n                    authorAssociation\n                    bodyText\n                    {time_keys}\n                    author {{\n                        login\n                    }}\n                }}\n            }}\n        }}\n        }}\n    }}\n    }}\n    \"\"\"\n\n\ndef find_reviewers(body: str) -> List[str]:\n    matches = re.findall(r\"(cc( @[-A-Za-z0-9]+)+)\", body, flags=re.MULTILINE)\n    matches = [full for full, last in matches]\n\n    reviewers = []\n    for match in matches:\n        if match.startswith(\"cc \"):\n            match = match.replace(\"cc \", \"\")\n        users = [x.strip() for x in match.split(\"@\")]\n        reviewers += users\n\n    reviewers = set(x for x in reviewers if x != \"\")\n    return list(reviewers)\n\n\ndef check_pr(pr, wait_time, now):\n    last_action = None\n\n    author = pr[\"author\"][\"login\"]\n\n    def update_last(new_time, description):\n        if isinstance(new_time, str):\n            new_time = datetime.datetime.strptime(new_time, GIT_DATE_FORMAT)\n        if new_time is None:\n            print(f\"  time not found: {description}\")\n            return\n        nonlocal last_action\n        if last_action is None or new_time > last_action[0]:\n            last_action = (new_time, description)\n\n    def check_obj(obj, name):\n        update_last(obj[\"publishedAt\"], f\"{name} publishedAt: {obj}\")\n        update_last(obj[\"updatedAt\"], f\"{name} updatedAt: {obj}\")\n        update_last(obj[\"lastEditedAt\"], f\"{name} lastEditedAt: {obj}\")\n        update_last(obj[\"createdAt\"], f\"{name} lastEditedAt: {obj}\")\n\n    check_obj(pr, \"pr\")\n\n    # GitHub counts comments left as part of a review separately than standalone\n    # comments\n    reviews = pr[\"reviews\"][\"nodes\"]\n    review_comments = []\n    for review in reviews:\n        review_comments += review[\"comments\"][\"nodes\"]\n        check_obj(review, \"review\")\n\n    # Collate all comments\n    comments = pr[\"comments\"][\"nodes\"] + review_comments\n\n    # Find the last date of any comment\n    for comment in comments:\n        check_obj(comment, \"comment\")\n\n    time_since_last_action = now - last_action[0]\n\n    # Find reviewers in the PR's body\n    pr_body_reviewers = find_reviewers(pr[\"body\"])\n\n    # Pull out reviewers from any cc @... text in a comment\n    cc_reviewers = [find_reviewers(c[\"bodyText\"]) for c in comments]\n    cc_reviewers = [r for revs in cc_reviewers for r in revs]\n\n    # Anyone that has left a review as a reviewer (this may include the PR\n    # author since their responses count as reviews)\n    review_reviewers = list(set(r[\"author\"][\"login\"] for r in reviews))\n\n    reviewers = cc_reviewers + review_reviewers + pr_body_reviewers\n    reviewers = list(set(reviewers))\n    reviewers = [r for r in reviewers if r != author]\n\n    if time_since_last_action > wait_time:\n        print(\n            \"  Pinging reviewers\",\n            reviewers,\n            \"on\",\n            pr[\"url\"],\n            \"since it has been\",\n            time_since_last_action,\n            f\"since anything happened on that PR (last action: {last_action[1]})\",\n        )\n        return reviewers\n    else:\n        print(\n            f\"  Not pinging PR {pr['number']} since it has been only {time_since_last_action} since the last action: {last_action[1]}\"\n        )\n\n    return None\n\n\ndef make_ping_message(pr, reviewers):\n    reviewers = [f\"@{r}\" for r in reviewers]\n    author = f'@{pr[\"author\"][\"login\"]}'\n    text = (\n        \"It has been a while since this PR was updated, \"\n        + \" \".join(reviewers)\n        + \" please leave a review or address the outstanding comments. \"\n        + f\"{author} if this PR is still a work in progress, please [convert it to a draft](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#converting-a-pull-request-to-a-draft)\"\n        \" until it is ready for review.\"\n    )\n    return text\n\n\nif __name__ == \"__main__\":\n    help = \"Comment on languishing issues and PRs\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--wait-time-minutes\", required=True, type=int, help=\"ssh remote to parse\")\n    parser.add_argument(\"--cutoff-pr-number\", default=0, type=int, help=\"ssh remote to parse\")\n    parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"don't update GitHub\")\n    parser.add_argument(\"--pr-json\", help=\"(testing) data for testing to use instead of GitHub\")\n    parser.add_argument(\"--now\", help=\"(testing) custom string for current time\")\n    args = parser.parse_args()\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n\n    wait_time = datetime.timedelta(minutes=int(args.wait_time_minutes))\n    cutoff_pr_number = int(args.cutoff_pr_number)\n    print(\n        \"Running with:\\n\"\n        f\"  time cutoff: {wait_time}\\n\"\n        f\"  number cutoff: {cutoff_pr_number}\\n\"\n        f\"  dry run: {args.dry_run}\\n\"\n        f\"  user/repo: {user}/{repo}\\n\",\n        end=\"\",\n    )\n\n    if args.pr_json:\n        r = json.loads(args.pr_json)\n    else:\n        q = prs_query(user, repo)\n        r = github.graphql(q)\n\n    now = datetime.datetime.utcnow()\n    if args.now:\n        now = datetime.datetime.strptime(args.now, GIT_DATE_FORMAT)\n\n    # Loop until all PRs have been checked\n    while True:\n        prs = r[\"data\"][\"repository\"][\"pullRequests\"][\"nodes\"]\n\n        # Don't look at draft PRs at all\n        prs_to_check = []\n        for pr in prs:\n            if pr[\"isDraft\"]:\n                print(f\"Skipping #{pr['number']} since it's a draft\")\n            elif pr[\"number\"] <= cutoff_pr_number:\n                print(\n                    f\"Skipping #{pr['number']} since it's too old ({pr['number']} <= {cutoff_pr_number})\"\n                )\n            else:\n                print(f\"Checking #{pr['number']}\")\n                prs_to_check.append(pr)\n\n        print(f\"Summary: Checking {len(prs_to_check)} of {len(prs)} fetched\")\n\n        # Ping reviewers on each PR in the response if necessary\n        for pr in prs_to_check:\n            print(\"Checking\", pr[\"url\"])\n            reviewers = check_pr(pr, wait_time, now)\n            if reviewers is not None:\n                message = make_ping_message(pr, reviewers)\n                if args.dry_run:\n                    print(\n                        f\"Would have commented on #{pr['number']}:\\n{textwrap.indent(message, prefix='  ')}\"\n                    )\n                else:\n                    r = github.post(f\"issues/{pr['number']}/comments\", {\"body\": message})\n                    print(r)\n\n        edges = r[\"data\"][\"repository\"][\"pullRequests\"][\"edges\"]\n        if len(edges) == 0:\n            # No more results to check\n            break\n\n        cursor = edges[0][\"cursor\"]\n        r = github.graphql(prs_query(user, repo, cursor))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/pytest_ids.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport io\nimport argparse\n\nfrom contextlib import redirect_stdout\n\n\nclass NodeidsCollector:\n    def pytest_collection_modifyitems(self, items):\n        self.nodeids = [item.nodeid for item in items]\n\n\ndef main(folder):\n    collector = NodeidsCollector()\n    f = io.StringIO()\n    with redirect_stdout(f):\n        pytest.main([\"-qq\", \"--collect-only\", folder], plugins=[collector])\n    for nodeid in collector.nodeids:\n        print(nodeid)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"List pytest nodeids for a folder\")\n    parser.add_argument(\"--folder\", required=True, help=\"test folder to inspect\")\n    args = parser.parse_args()\n    main(args.folder)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/pytest_wrapper.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport textwrap\nimport junitparser\nimport traceback\nfrom pathlib import Path\nfrom typing import List, Optional\nimport os\nimport urllib.parse\nimport logging\n\nfrom cmd_utils import init_log\n\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\n\n\ndef lstrip(s: str, prefix: str) -> str:\n    if s.startswith(prefix):\n        s = s[len(prefix) :]\n    return s\n\n\ndef classname_to_file(classname: str) -> str:\n    classname = lstrip(classname, \"cython.\")\n    classname = lstrip(classname, \"ctypes.\")\n    return classname.replace(\".\", \"/\") + \".py\"\n\n\ndef failed_test_ids() -> List[str]:\n    FAILURE_TYPES = (junitparser.Failure, junitparser.Error)\n    junit_dir = REPO_ROOT / \"build\" / \"pytest-results\"\n    failed_node_ids = []\n    for junit in junit_dir.glob(\"*.xml\"):\n        xml = junitparser.JUnitXml.fromfile(str(junit))\n        for suite in xml:\n            # handle suites\n            for case in suite:\n                if case.result is None:\n                    logging.warn(f\"Incorrectly formatted JUnit found, result was None on {case}\")\n                    continue\n\n                if len(case.result) > 0 and isinstance(case.result[0], FAILURE_TYPES):\n                    node_id = classname_to_file(case.classname) + \"::\" + case.name\n                    failed_node_ids.append(node_id)\n\n    return list(set(failed_node_ids))\n\n\ndef repro_command(build_type: str, failed_node_ids: List[str]) -> Optional[str]:\n    \"\"\"\n    Parse available JUnit XML files and output a command that users can run to\n    reproduce CI failures locally\n    \"\"\"\n    test_args = [f\"--tests {node_id}\" for node_id in failed_node_ids]\n    test_args_str = \" \".join(test_args)\n    return f\"python3 tests/scripts/ci.py {build_type} {test_args_str}\"\n\n\ndef make_issue_url(failed_node_ids: List[str]) -> str:\n    names = [f\"`{node_id}`\" for node_id in failed_node_ids]\n    run_url = os.getenv(\"RUN_DISPLAY_URL\", \"<insert run URL>\")\n    test_bullets = [f\"  - `{node_id}`\" for node_id in failed_node_ids]\n    params = {\n        \"labels\": \"test: flaky\",\n        \"title\": \"[Flaky Test] \" + \", \".join(names),\n        \"body\": textwrap.dedent(\n            f\"\"\"\n            These tests were found to be flaky (intermittently failing on `main` or failed in a PR with unrelated changes). See [the docs](https://github.com/apache/tvm/blob/main/docs/contribute/ci.rst#handling-flaky-failures) for details.\n\n            ### Tests(s)\\n\n            \"\"\"\n        )\n        + \"\\n\".join(test_bullets)\n        + f\"\\n\\n### Jenkins Links\\n\\n  - {run_url}\",\n    }\n    return \"https://github.com/apache/tvm/issues/new?\" + urllib.parse.urlencode(params)\n\n\ndef show_failure_help(failed_suites: List[str]) -> None:\n    failed_node_ids = failed_test_ids()\n\n    if len(failed_node_ids) == 0:\n        return\n\n    build_type = os.getenv(\"PLATFORM\")\n\n    if build_type is None:\n        raise RuntimeError(\"build type was None, cannot show command\")\n\n    repro = repro_command(build_type=build_type, failed_node_ids=failed_node_ids)\n    if repro is None:\n        print(\"No test failures detected\")\n        return\n\n    print(f\"Report flaky test shortcut: {make_issue_url(failed_node_ids)}\")\n    print(\"=============================== PYTEST FAILURES ================================\")\n    print(\n        \"These pytest suites failed to execute. The results can be found in the \"\n        \"Jenkins 'Tests' tab or by scrolling up through the raw logs here. \"\n        \"If there is no test listed below, the failure likely came from a segmentation \"\n        \"fault which you can find in the logs above.\\n\"\n    )\n    if failed_suites is not None and len(failed_suites) > 0:\n        print(\"\\n\".join([f\"    - {suite}\" for suite in failed_suites]))\n        print(\"\")\n\n    print(\"You can reproduce these specific failures locally with this command:\\n\")\n    print(textwrap.indent(repro, prefix=\"    \"))\n    print(\"\")\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Print information about a failed pytest run\")\n    args, other = parser.parse_known_args()\n    init_log()\n\n    try:\n        show_failure_help(failed_suites=other)\n    except Exception as e:\n        # This script shouldn't ever introduce failures since it's just there to\n        # add extra information, so ignore any errors\n        logging.exception(e)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/should_rebuild_docker.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport datetime\nimport json\nimport logging\nimport subprocess\n\nfrom typing import Dict, Any, List\n\n\nfrom http_utils import get\nfrom cmd_utils import Sh, init_log\n\n\nDOCKER_API_BASE = \"https://hub.docker.com/v2/\"\nPAGE_SIZE = 25\nTEST_DATA = None\n\n\ndef docker_api(url: str) -> Dict[str, Any]:\n    \"\"\"\n    Run a paginated fetch from the public Docker Hub API\n    \"\"\"\n    if TEST_DATA is not None:\n        return TEST_DATA[url]\n    pagination = f\"?page_size={PAGE_SIZE}&page=1\"\n    url = DOCKER_API_BASE + url + pagination\n    r, headers = get(url)\n    reset = headers.get(\"x-ratelimit-reset\")\n    if reset is not None:\n        reset = datetime.datetime.fromtimestamp(int(reset))\n        reset = reset.isoformat()\n    logging.info(\n        f\"Docker API Rate Limit: {headers.get('x-ratelimit-remaining')} / {headers.get('x-ratelimit-limit')} (reset at {reset})\"\n    )\n    if \"results\" not in r:\n        raise RuntimeError(f\"Error fetching data, no results found in: {r}\")\n    return r\n\n\ndef any_docker_changes_since(hash: str) -> bool:\n    \"\"\"\n    Check the docker/ directory, return True if there have been any code changes\n    since the specified hash\n    \"\"\"\n    sh = Sh()\n    cmd = f\"git diff {hash} -- docker/\"\n    proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    stdout = proc.stdout.strip()\n    return stdout != \"\", stdout\n\n\ndef does_commit_exist(hash: str) -> bool:\n    \"\"\"\n    Returns True if the hash exists in the repo\n    \"\"\"\n    sh = Sh()\n    cmd = f\"git rev-parse -q {hash}\"\n    proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)\n    print(proc.stdout)\n    if proc.returncode == 0:\n        return True\n\n    if \"unknown revision or path not in the working tree\" in proc.stdout:\n        return False\n\n    raise RuntimeError(f\"Unexpected failure when running: {cmd}\")\n\n\ndef find_hash_for_tag(tag: Dict[str, Any]) -> str:\n    \"\"\"\n    Split the hash off of a name like <date>-<time>-<hash>\n    \"\"\"\n    name = tag[\"name\"]\n    name_parts = name.split(\"-\")\n    if len(name_parts) != 3:\n        raise RuntimeError(f\"Image {name} is not using new naming scheme\")\n    shorthash = name_parts[2]\n    return shorthash\n\n\ndef find_commit_in_repo(tags: List[Dict[str, Any]]):\n    \"\"\"\n    Look through all the docker tags, find the most recent one which references\n    a commit that is present in the repo\n    \"\"\"\n    for tag in tags[\"results\"]:\n        shorthash = find_hash_for_tag(tag)\n        logging.info(f\"Hash '{shorthash}' does not exist in repo\")\n        if does_commit_exist(shorthash):\n            return shorthash, tag\n\n    raise RuntimeError(f\"No extant hash found in tags:\\n{tags}\")\n\n\ndef main():\n    # Fetch all tlcpack images\n    images = docker_api(\"repositories/tlcpack\")\n\n    # Ignore all non-ci images\n    relevant_images = [image for image in images[\"results\"] if image[\"name\"].startswith(\"ci-\")]\n    image_names = [image[\"name\"] for image in relevant_images]\n    logging.info(f\"Found {len(relevant_images)} images to check: {', '.join(image_names)}\")\n\n    for image in relevant_images:\n        # Check the tags for the image\n        tags = docker_api(f\"repositories/tlcpack/{image['name']}/tags\")\n\n        # Find the hash of the most recent tag\n        shorthash, tag = find_commit_in_repo(tags)\n        name = tag[\"name\"]\n        logging.info(f\"Looking for docker/ changes since {shorthash}\")\n\n        any_docker_changes, diff = any_docker_changes_since(shorthash)\n        if any_docker_changes:\n            logging.info(f\"Found docker changes from {shorthash} when checking {name}\")\n            logging.info(diff)\n            exit(2)\n\n    logging.info(\"Did not find changes, no rebuild necessary\")\n    exit(0)\n\n\nif __name__ == \"__main__\":\n    init_log()\n    parser = argparse.ArgumentParser(\n        description=\"Exits 0 if Docker images don't need to be rebuilt, 1 otherwise\"\n    )\n    parser.add_argument(\n        \"--testing-docker-data\",\n        help=\"(testing only) JSON data to mock response from Docker Hub API\",\n    )\n    args = parser.parse_args()\n\n    if args.testing_docker_data is not None:\n        TEST_DATA = json.loads(args.testing_docker_data)\n\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/should_run_slow_tests.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport json\nimport argparse\nimport subprocess\nimport re\nimport textwrap\nfrom urllib import request\nfrom typing import Dict, Tuple, Any, List, Optional\n\n\nfrom git_utils import GitHubRepo, parse_remote, git\n\n\nSLOW_TEST_TRIGGERS = [\n    \"@tvm-bot run slow tests\",\n    \"@tvm-bot run slow test\",\n    \"@tvm-bot run slow\",\n    \"@tvm-bot slow tests\",\n    \"@tvm-bot slow test\",\n    \"@tvm-bot slow\",\n]\n\n\ndef check_match(s: str, searches: List[str]) -> Tuple[bool, Optional[str]]:\n    for search in searches:\n        if search in s:\n            return True, search\n\n    return False, None\n\n\ndef display(long_str: str) -> str:\n    return textwrap.indent(long_str, \"    \")\n\n\nif __name__ == \"__main__\":\n    help = \"Exits with 1 if CI should run slow tests, 0 otherwise\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--pr\", required=True)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\n        \"--pr-body\", help=\"(testing) PR body to use instead of fetching from GitHub\"\n    )\n    args = parser.parse_args()\n\n    branch = git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"])\n\n    # Don't skip slow tests on main or ci-docker-staging\n    skip_branches = {\"main\", \"ci-docker-staging\"}\n    if branch in skip_branches:\n        print(f\"Branch {branch} is in {skip_branches}, running slow tests\")\n        exit(1)\n    print(f\"Branch {branch} is not in {skip_branches}, checking last commit...\")\n\n    if args.pr_body:\n        body = args.pr_body\n    else:\n        remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n        user, repo = parse_remote(remote)\n\n        github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n        pr = github.get(f\"pulls/{args.pr}\")\n        body = pr[\"body\"]\n\n    body_match, reason = check_match(body, SLOW_TEST_TRIGGERS)\n\n    if body_match:\n        print(f\"Matched {reason} in PR body:\\n{display(body)}, running slow tests\")\n        exit(1)\n\n    print(\n        f\"PR Body:\\n{display(body)}\\ndid not have any of {SLOW_TEST_TRIGGERS}, skipping slow tests\"\n    )\n    exit(0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "ci/scripts/update_branch.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport json\nimport argparse\nimport tempfile\nfrom typing import Any, Dict\n\nfrom git_utils import git, GitHubRepo, parse_remote\n\n\n_commit_query_fields = \"\"\"\n    messageHeadline\n    oid\n    statusCheckRollup {\n        contexts(last:100) {\n            nodes {\n                ... on CheckRun {\n                    conclusion\n                    status\n                    name\n                    checkSuite {\n                        workflowRun {\n                            workflow {\n                                name\n                            }\n                        }\n                    }\n                }\n                ... on StatusContext {\n                    context\n                    state\n                }\n            }\n        }\n    }\n\"\"\"\n\n\ndef commits_query(user: str, repo: str, cursor: str = None):\n    \"\"\"\n    Create a GraphQL query to find the last N commits along with their statuses\n    and some metadata (paginated after 'cursor')\n    \"\"\"\n    after = \"\"\n    if cursor is not None:\n        after = f', after:\"{cursor}\"'\n\n    return f\"\"\"\n    {{\n    repository(name: \"{repo}\", owner: \"{user}\") {{\n        defaultBranchRef {{\n        target {{\n            ... on Commit {{\n            history(first: 15{after}) {{\n                edges {{ cursor }}\n                nodes {{\n                    {_commit_query_fields}\n                }}\n            }}\n            }}\n        }}\n        }}\n    }}\n    }}\n    \"\"\"\n\n\ndef commit_passed_ci(commit: Dict[str, Any]) -> bool:\n    \"\"\"\n    Returns true if all of a commit's statuses are SUCCESS\n    \"\"\"\n    statuses = commit[\"statusCheckRollup\"][\"contexts\"][\"nodes\"]\n\n    # GitHub Actions statuses are different from external GitHub statuses, so\n    # unify them into 1 representation\n    # https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads\n    unified_statuses = []\n    for status in statuses:\n        if \"context\" in status:\n            # Parse non-GHA status\n            unified_statuses.append((status[\"context\"], status[\"state\"] == \"SUCCESS\"))\n        else:\n            # Parse GitHub Actions item\n            workflow = status[\"checkSuite\"][\"workflowRun\"][\"workflow\"][\"name\"]\n            name = f\"{workflow} / {status['name']}\"\n            unified_statuses.append((name, status[\"conclusion\"] == \"SUCCESS\"))\n\n    print(f\"Statuses on {commit['oid']}:\", json.dumps(unified_statuses, indent=2))\n\n    # Assert that specific jobs are present in the commit statuses (i.e. don't\n    # approve if CI was broken and didn't schedule a job)\n    expected_jobs = {\"tvm-ci/branch\"}\n    job_names = {name for name, status in unified_statuses}\n    for job in expected_jobs:\n        if job not in job_names:\n            # Did not find expected job name\n            return False\n\n    passed_ci = all(status for name, status in unified_statuses)\n    return passed_ci\n\n\ndef update_branch(user: str, repo: str, sha: str, branch_name: str) -> None:\n    git([\"fetch\", \"origin\", sha])\n    git([\"reset\", \"--hard\", \"FETCH_HEAD\"])\n    try:\n        git([\"branch\", \"-D\", branch_name])\n    except RuntimeError:\n        # Ignore failures (i.e. the branch did not exist in the first place)\n        pass\n    git([\"checkout\", \"-b\", branch_name])\n\n    # Create and push the branch\n    git([\"push\", \"origin\", \"--force\", branch_name])\n    print(f\"Pushed branch {branch_name} with commit {sha}\")\n\n\nif __name__ == \"__main__\":\n    help = \"Push the a branch to the last commit that passed all CI runs\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--remote\", default=\"origin\", help=\"ssh remote to parse\")\n    parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"don't submit to GitHub\")\n    parser.add_argument(\"--branch\", default=\"last-successful\", help=\"branch name\")\n    parser.add_argument(\n        \"--testonly-json\", help=\"(testing) data to use instead of fetching from GitHub\"\n    )\n    args = parser.parse_args()\n\n    remote = git([\"config\", \"--get\", f\"remote.{args.remote}.url\"])\n    user, repo = parse_remote(remote)\n    # TODO: Remove this before landing\n    user, repo = (\"apache\", \"tvm\")\n\n    if args.testonly_json:\n        r = json.loads(args.testonly_json)\n    else:\n        github = GitHubRepo(token=os.environ[\"GITHUB_TOKEN\"], user=user, repo=repo)\n        q = commits_query(user, repo)\n        r = github.graphql(q)\n\n    commits = r[\"data\"][\"repository\"][\"defaultBranchRef\"][\"target\"][\"history\"][\"nodes\"]\n\n    # Limit GraphQL pagination\n    MAX_COMMITS_TO_CHECK = 50\n    i = 0\n\n    while i < MAX_COMMITS_TO_CHECK:\n        # Check each commit\n        for commit in commits:\n            if commit_passed_ci(commit):\n                print(f\"Found last good commit: {commit['oid']}: {commit['messageHeadline']}\")\n                if not args.dry_run:\n                    update_branch(\n                        user=user,\n                        repo=repo,\n                        sha=commit[\"oid\"],\n                        branch_name=args.branch,\n                    )\n                # Nothing to do after updating the branch, exit early\n                exit(0)\n\n        # No good commit found, proceed to next page of results\n        edges = r[\"data\"][\"repository\"][\"defaultBranchRef\"][\"target\"][\"history\"][\"edges\"]\n        if len(edges) == 0:\n            break\n        else:\n            q = commits_query(user, repo, cursor=edges[-1][\"cursor\"])\n            r = github.graphql(q)\n            commits = r[\"data\"][\"repository\"][\"defaultBranchRef\"][\"target\"][\"history\"][\"nodes\"]\n\n        # Backstop to prevent looking through all the past commits\n        i += len(commits)\n\n    print(f\"No good commits found in the last {len(commits)} commits\")\n    exit(1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "conda/render_cuda_dockerfiles.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport sys\nimport subprocess\n\nfrom jinja2 import Template\n\nCUDA_VERSIONS = [\"10.0\", \"9.0\"]\n\n\n# Make sure that the cudnn version you set here is available\n# for all the cuda versions that you want both from nvidia\n# and from conda.\n\n# These two must be in sync\nCUDNN_FULL_VERSION = \"7.6.0.64\"\nCUDNN_VERSION = \"7.6.0\"\n\n\ncondadir = os.path.dirname(sys.argv[0])\ncondadir = os.path.abspath(condadir)\nsrcdir = os.path.dirname(condadir)\n\n\nwith open(os.path.join(condadir, \"Dockerfile.template\")) as f:\n    docker_template = Template(f.read())\n\n\ndef render_dockerfile(version):\n    txt = docker_template.render(\n        cuda_version=version, cudnn_short_version=CUDNN_VERSION, cudnn_version=CUDNN_FULL_VERSION\n    )\n    fname = os.path.join(condadir, \"../docker/Dockerfile.conda_cuda\" + version.replace(\".\", \"\"))\n    with open(fname, \"w\") as f:\n        f.write(txt + \"\\n\")\n    return fname\n\n\nif __name__ == \"__main__\":\n    build_versions = CUDA_VERSIONS\n    if len(sys.argv) > 1:\n        build_versions = sys.argv[1:]\n    for version in build_versions:\n        render_dockerfile(version)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport hashlib\nimport pytest\nimport sys\nimport os\n\nfrom pathlib import Path\n\npytest_plugins = [\"tvm.testing.plugin\"]\nIS_IN_CI = os.getenv(\"CI\", \"\") == \"true\"\nREPO_ROOT = Path(__file__).resolve().parent\n\n\n# These are long running tests (manually curated and extracted from CI logs)\n# that should be allocated to test shards in a round-robin fashion. These are\n# taken from the 20 (arbitrary number) of tests as from\n# https://ci.tlcpack.ai/job/tvm/job/main/2907/testReport\n_slowest_tests = [\n    \"tests/python/frontend/tensorflow/test_forward.py::test_forward_broadcast_args\",\n    \"tests/python/frontend/tensorflow/test_forward.py::test_forward_broadcast_to\",\n    \"tests/python/topi/python/test_topi_conv2d_int8.py::test_conv2d_nchw[int8]\",\n    \"tests/python/topi/python/test_topi_conv2d_int8.py::test_conv2d_nchw[uint8]\",\n    \"tests/python/topi/python/test_topi_upsampling.py::test_upsampling3d\",\n    \"tests/python/topi/python/test_topi_upsampling.py::test_upsampling3d\",\n    \"tests/python/topi/python/test_topi_conv2d_int8.py::test_conv2d_nchw[int8]\",\n    \"tests/python/frontend/tflite/test_forward.py::test_all_elemwise\",\n    \"tests/python/frontend/pytorch/test_object_detection.py::test_detection_models\",\n    \"tests/python/topi/python/test_topi_conv2d_int8.py::test_conv2d_nchw[uint8]\",\n    \"tests/python/topi/python/test_topi_conv2d_NCHWc.py::test_conv2d_NCHWc\",\n    \"tests/python/topi/python/test_topi_conv2d_hwnc_tensorcore.py::test_conv2d_hwnc_tensorcore\",\n    \"tests/python/contrib/test_tensorrt.py::test_binary[compile]\",\n    \"tests/python/frontend/pytorch/test_forward.py::test_segmentation_models\",\n    \"tests/python/topi/python/test_topi_conv2d_NCHWc.py::test_conv2d_NCHWc\",\n    \"tests/python/relay/test_py_converter.py::test_global_recursion\",\n    \"tests/python/frontend/tensorflow/test_forward.py::test_forward_ptb\",\n    \"tests/python/relay/test_op_level6.py::test_topk\",\n    \"tests/python/topi/python/test_topi_conv2d_winograd.py::test_conv2d_nchw\",\n    \"tests/python/relay/test_py_converter.py::test_global_recursion\",\n]\nHARDCODED_ALLOCATIONS = {}\nfor idx, test in enumerate(_slowest_tests):\n    HARDCODED_ALLOCATIONS[test] = idx\n\n# These rely on running on the same node to pass successfully\nFIXED_ALLOCATION_PREFIXES = {\n    \"tests/python/unittest/test_tvm_testing_features.py\": 0,\n}\n\n\ndef find_shard_index(nodeid: str, num_shards: int) -> int:\n    \"\"\"\n    Return the index of the shard that should run this test\n    \"\"\"\n    for prefix, target_shard_idx in FIXED_ALLOCATION_PREFIXES.items():\n        if nodeid.startswith(prefix):\n            if target_shard_idx >= num_shards:\n                raise RuntimeError(\n                    f\"Cannot collect sharded tests, {nodeid} has hardcoded shard index {target_shard_idx} among only {num_shards} shards\"\n                )\n            return target_shard_idx\n\n    if nodeid in HARDCODED_ALLOCATIONS:\n        hash = HARDCODED_ALLOCATIONS[nodeid]\n    else:\n        hash = hashlib.md5(nodeid.encode())\n        hash = int(hash.hexdigest(), 16)\n\n    return hash % num_shards\n\n\ndef pytest_collection_modifyitems(config, items):\n    if not all(k in os.environ for k in [\"CI\", \"TVM_NUM_SHARDS\", \"TVM_SHARD_INDEX\"]):\n        # Only apportion tests if in CI and in a job that is set up for it\n        return\n\n    num_shards = int(os.environ[\"TVM_NUM_SHARDS\"])\n    shard_index = int(os.environ[\"TVM_SHARD_INDEX\"])\n\n    print(f\"Marking tests for shard {shard_index} of {num_shards}\")\n    items_copy = list(items)\n    for item in items_copy:\n        item_shard_index = find_shard_index(item.nodeid, num_shards=num_shards)\n        if item_shard_index != shard_index:\n            items.remove(item)\n\n\ndef pytest_sessionstart():\n    if IS_IN_CI:\n        hook_script_dir = REPO_ROOT / \"tests\" / \"scripts\" / \"request_hook\"\n        sys.path.append(str(hook_script_dir))\n        import request_hook  # pylint: disable=import-outside-toplevel\n\n        request_hook.init()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "docs/conf.py",
        "content": "# -*- coding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n#\n# documentation build configuration file, created by\n# sphinx-quickstart on Thu Jul 23 19:40:08 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\nimport gc\nimport inspect\nimport os\nfrom pathlib import Path\nimport re\nimport sys\n\nimport sphinx_gallery\n\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\ncurr_path = Path(__file__).expanduser().absolute().parent\nif curr_path.name == \"_staging\":\n    # Can't use curr_path.parent, because sphinx_gallery requires a relative path.\n    tvm_path = Path(os.pardir, os.pardir)\nelse:\n    tvm_path = Path(os.pardir)\n\nsys.path.insert(0, str(tvm_path.resolve() / \"python\"))\nsys.path.insert(0, str(tvm_path.resolve() / \"vta\" / \"python\"))\nsys.path.insert(0, str(tvm_path.resolve() / \"docs\"))\n\n# -- General configuration ------------------------------------------------\n\n# General information about the project.\nproject = \"tvm\"\nauthor = \"Apache Software Foundation\"\ncopyright = \"2020 - 2022, %s\" % author\ngithub_doc_root = \"https://github.com/apache/tvm/tree/main/docs/\"\n\nos.environ[\"TVM_BUILD_DOC\"] = \"1\"\n\n\ndef git_describe_version(original_version):\n    \"\"\"Get git describe version.\"\"\"\n    ver_py = tvm_path.joinpath(\"version.py\")\n    libver = {\"__file__\": ver_py}\n    exec(compile(open(ver_py, \"rb\").read(), ver_py, \"exec\"), libver, libver)\n    _, gd_version = libver[\"git_describe_version\"]()\n    if gd_version != original_version:\n        print(\"Use git describe based version %s\" % gd_version)\n    return gd_version\n\n\n# Version information.\nimport tvm\nfrom tvm import topi\nfrom tvm import te\nfrom tvm import testing\n\nversion = git_describe_version(tvm.__version__)\nrelease = version\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones\nextensions = [\n    \"sphinx.ext.autodoc\",\n    \"sphinx.ext.autosummary\",\n    \"sphinx.ext.intersphinx\",\n    \"sphinx.ext.napoleon\",\n    \"sphinx.ext.mathjax\",\n    \"sphinx_gallery.gen_gallery\",\n    \"autodocsumm\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n# source_suffix = ['.rst', '.md']\nsource_suffix = [\".rst\", \".md\"]\n\n# The encoding of source files.\n# source_encoding = 'utf-8-sig'\n\n# generate autosummary even if no references\nautosummary_generate = True\n\n# The main toctree document.\nmain_doc = \"index\"\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n# today = ''\n# Else, today_fmt is used as the format for a strftime call.\n# today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = [\"_build\", \"_staging\"]\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n# default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n# add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n# add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n# show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n# A list of ignored prefixes for module index sorting.\n# modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n# keep_warnings = False\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme is set by the make target\nhtml_theme = os.environ.get(\"TVM_THEME\", \"rtd\")\n\non_rtd = os.environ.get(\"READTHEDOCS\", None) == \"True\"\n# only import rtd theme and set it if want to build docs locally\nif not on_rtd and html_theme == \"rtd\":\n    import sphinx_rtd_theme\n\n    html_theme = \"sphinx_rtd_theme\"\n    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\nhtml_theme_options = {\n    \"analytics_id\": \"UA-75982049-2\",\n    \"logo_only\": True,\n}\n\nhtml_logo = \"_static/img/tvm-logo-small.png\"\n\nhtml_favicon = \"_static/img/tvm-logo-square.png\"\n\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = project + \"doc\"\n\n# -- Options for LaTeX output ---------------------------------------------\nlatex_elements = {}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (main_doc, \"%s.tex\" % project, project, author, \"manual\"),\n]\n\nintersphinx_mapping = {\n    \"python\": (\"https://docs.python.org/{.major}\".format(sys.version_info), None),\n    # \"numpy\": (\"https://numpy.org/doc/stable\", None),\n    # \"scipy\": (\"https://docs.scipy.org/doc/scipy\", None),\n    # \"matplotlib\": (\"https://matplotlib.org/\", None),\n}\n\nfrom sphinx_gallery.sorting import ExplicitOrder\n\nexamples_dirs = [\n    tvm_path.joinpath(\"gallery\", \"tutorial\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"compile_models\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"deploy_models\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"work_with_relay\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"work_with_schedules\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"optimize_operators\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"tune_with_autotvm\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"tune_with_autoscheduler\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"work_with_microtvm\"),\n    tvm_path.joinpath(\"gallery\", \"how_to\", \"extend_tvm\"),\n    tvm_path.joinpath(\"vta\", \"tutorials\"),\n]\n\ngallery_dirs = [\n    \"tutorial\",\n    \"how_to/compile_models\",\n    \"how_to/deploy_models\",\n    \"how_to/work_with_relay\",\n    \"how_to/work_with_schedules\",\n    \"how_to/optimize_operators\",\n    \"how_to/tune_with_autotvm\",\n    \"how_to/tune_with_autoscheduler\",\n    \"how_to/work_with_microtvm\",\n    \"how_to/extend_tvm\",\n    \"topic/vta/tutorials\",\n]\n\nsubsection_order = ExplicitOrder(\n    str(p)\n    for p in [\n        tvm_path / \"vta\" / \"tutorials\" / \"frontend\",\n        tvm_path / \"vta\" / \"tutorials\" / \"optimize\",\n        tvm_path / \"vta\" / \"tutorials\" / \"autotvm\",\n    ]\n)\n\n# Explicitly define the order within a subsection.\n# The listed files are sorted according to the list.\n# The unlisted files are sorted by filenames.\n# The unlisted files always appear after listed files.\nwithin_subsection_order = {\n    \"tutorial\": [\n        \"introduction.py\",\n        \"install.py\",\n        \"tvmc_command_line_driver.py\",\n        \"tvmc_python.py\",\n        \"autotvm_relay_x86.py\",\n        \"tensor_expr_get_started.py\",\n        \"autotvm_matmul_x86.py\",\n        \"auto_scheduler_matmul_x86.py\",\n        \"tensor_ir_blitz_course.py\",\n        \"topi.pi\",\n        \"cross_compilation_and_rpc.py\",\n        \"relay_quick_start.py\",\n        \"uma.py\",\n    ],\n    \"compile_models\": [\n        \"from_pytorch.py\",\n        \"from_tensorflow.py\",\n        \"from_mxnet.py\",\n        \"from_onnx.py\",\n        \"from_keras.py\",\n        \"from_tflite.py\",\n        \"from_coreml.py\",\n        \"from_darknet.py\",\n        \"from_caffe2.py\",\n        \"from_paddle.py\",\n    ],\n    \"work_with_schedules\": [\n        \"schedule_primitives.py\",\n        \"reduction.py\",\n        \"intrin_math.py\",\n        \"scan.py\",\n        \"extern_op.py\",\n        \"tensorize.py\",\n        \"tuple_inputs.py\",\n        \"tedd.py\",\n    ],\n    \"optimize_operators\": [\n        \"opt_gemm.py\",\n        \"opt_conv_cuda.py\",\n        \"opt_conv_tensorcore.py\",\n    ],\n    \"tune_with_autotvm\": [\n        \"tune_conv2d_cuda.py\",\n        \"tune_relay_cuda.py\",\n        \"tune_relay_x86.py\",\n        \"tune_relay_arm.py\",\n        \"tune_relay_mobile_gpu.py\",\n    ],\n    \"tune_with_autoscheduler\": [\n        \"tune_matmul_x86.py\",\n        \"tune_conv2d_layer_cuda.py\",\n        \"tune_network_x86.py\",\n        \"tune_network_cuda.py\",\n    ],\n    \"extend_tvm\": [\n        \"low_level_custom_pass.py\",\n        \"use_pass_infra.py\",\n        \"use_pass_instrument.py\",\n        \"bring_your_own_datatypes.py\",\n    ],\n    \"micro\": [\n        \"micro_train.py\",\n        \"micro_autotune.py\",\n        \"micro_reference_vm.py\",\n        \"micro_tflite.py\",\n        \"micro_ethosu.py\",\n        \"micro_tvmc.py\",\n        \"micro_aot.py\",\n        \"micro_pytorch.py\",\n    ],\n}\n\n\nclass WithinSubsectionOrder:\n    def __init__(self, src_dir):\n        self.src_dir = src_dir.split(\"/\")[-1]\n\n    def __call__(self, filename):\n        # If the order is provided, use the provided order\n        if (\n            self.src_dir in within_subsection_order\n            and filename in within_subsection_order[self.src_dir]\n        ):\n            index = within_subsection_order[self.src_dir].index(filename)\n            assert index < 1e10\n            return \"\\0%010d\" % index\n\n        # Otherwise, sort by filename\n        return filename\n\n\n# When running the tutorials on GPUs we are dependent on the Python garbage collector\n# collecting TVM packed function closures for any device memory to also be released. This\n# is not a good setup for machines with lots of CPU ram but constrained GPU ram, so force\n# a gc after each example.\ndef force_gc(gallery_conf, fname):\n    gc.collect()\n\n\nsphinx_gallery_conf = {\n    \"backreferences_dir\": \"gen_modules/backreferences\",\n    \"doc_module\": (\"tvm\", \"numpy\"),\n    \"reference_url\": {\n        \"tvm\": None,\n        # \"matplotlib\": \"https://matplotlib.org/\",\n        # \"numpy\": \"https://numpy.org/doc/stable\",\n    },\n    \"examples_dirs\": examples_dirs,\n    \"within_subsection_order\": WithinSubsectionOrder,\n    \"gallery_dirs\": gallery_dirs,\n    \"subsection_order\": subsection_order,\n    \"filename_pattern\": os.environ.get(\"TVM_TUTORIAL_EXEC_PATTERN\", \".py\"),\n    \"download_all_examples\": False,\n    \"min_reported_time\": 60,\n    \"expected_failing_examples\": [],\n    \"reset_modules\": (\"matplotlib\", \"seaborn\", force_gc),\n    \"promote_jupyter_magic\": True,\n}\n\nautodoc_default_options = {\n    \"member-order\": \"bysource\",\n}\n\n# Maps the original namespace to list of potential modules\n# that we can import alias from.\ntvm_alias_check_map = {\n    \"tvm.te\": [\"tvm.tir\"],\n    \"tvm.tir\": [\"tvm.ir\", \"tvm.runtime\"],\n    \"tvm.relay\": [\"tvm.ir\", \"tvm.tir\"],\n}\n\n## Setup header and other configs\nimport tlcpack_sphinx_addon\n\nfooter_copyright = \"\u00a9 2022 Apache Software Foundation | All rights reserved\"\nfooter_note = \" \".join(\n    \"\"\"\nCopyright \u00a9 2022 The Apache Software Foundation. Apache TVM, Apache, the Apache feather,\nand the Apache TVM project logo are either trademarks or registered trademarks of\nthe Apache Software Foundation.\"\"\".split(\n        \"\\n\"\n    )\n).strip()\n\nheader_logo = \"https://tvm.apache.org/assets/images/logo.svg\"\nheader_logo_link = \"https://tvm.apache.org/\"\n\nheader_links = [\n    (\"Community\", \"https://tvm.apache.org/community\"),\n    (\"Download\", \"https://tvm.apache.org/download\"),\n    (\"VTA\", \"https://tvm.apache.org/vta\"),\n    (\"Blog\", \"https://tvm.apache.org/blog\"),\n    (\"Docs\", \"https://tvm.apache.org/docs\"),\n    (\"Conference\", \"https://tvmconf.org\"),\n    (\"Github\", \"https://github.com/apache/tvm/\"),\n]\n\nheader_dropdown = {\n    \"name\": \"ASF\",\n    \"items\": [\n        (\"Apache Homepage\", \"https://apache.org/\"),\n        (\"License\", \"https://www.apache.org/licenses/\"),\n        (\"Sponsorship\", \"https://www.apache.org/foundation/sponsorship.html\"),\n        (\"Security\", \"https://www.apache.org/security/\"),\n        (\"Thanks\", \"https://www.apache.org/foundation/thanks.html\"),\n        (\"Events\", \"https://www.apache.org/events/current-event\"),\n    ],\n}\n\n\ndef fixup_tutorials(original_url: str) -> str:\n    if \"docs/tutorial\" in original_url:\n        # tutorials true source is in Python or .txt files, but Sphinx only sees\n        # the generated .rst files so this maps them back to the source\n        if original_url.endswith(\"index.rst\"):\n            # for index pages, go to the README files\n            return re.sub(\n                r\"docs/tutorial/(.*)index\\.rst\", \"gallery/tutorial/\\\\1README.txt\", original_url\n            )\n        else:\n            # otherwise for tutorials, redirect to python files\n            return re.sub(r\"docs/tutorial/(.*)\\.rst\", \"gallery/tutorial/\\\\1.py\", original_url)\n    else:\n        # do nothing for normal non-tutorial .rst files\n        return original_url\n\n\nhtml_context = {\n    \"footer_copyright\": footer_copyright,\n    \"footer_note\": footer_note,\n    \"header_links\": header_links,\n    \"header_dropdown\": header_dropdown,\n    \"header_logo\": header_logo,\n    \"header_logo_link\": header_logo_link,\n    \"version_prefixes\": [\"main\", \"v0.8.0/\", \"v0.9.0/\", \"v0.10.0/\"],\n    \"display_github\": True,\n    \"github_user\": \"apache\",\n    \"github_repo\": \"tvm\",\n    \"github_version\": \"main/docs/\",\n    \"theme_vcs_pageview_mode\": \"edit\",\n    \"edit_link_hook_fn\": fixup_tutorials,\n}\n\n# add additional overrides\ntemplates_path += [tlcpack_sphinx_addon.get_templates_path()]\nhtml_static_path += [tlcpack_sphinx_addon.get_static_path()]\n\n\ndef update_alias_docstring(name, obj, lines):\n    \"\"\"Update the docstring of alias functions.\n\n    This function checks if the obj is an alias of another documented object\n    in a different module.\n\n    If it is an alias, then it will append the alias information to the docstring.\n\n    Parameters\n    ----------\n    name : str\n        The full name of the object in the doc.\n\n    obj : object\n        The original object.\n\n    lines : list\n        The docstring lines, need to be modified inplace.\n    \"\"\"\n    arr = name.rsplit(\".\", 1)\n    if len(arr) != 2:\n        return\n    target_mod, target_name = arr\n\n    if target_mod not in tvm_alias_check_map:\n        return\n    if not hasattr(obj, \"__module__\"):\n        return\n    obj_mod = obj.__module__\n\n    for amod in tvm_alias_check_map[target_mod]:\n        if not obj_mod.startswith(amod):\n            continue\n\n        if hasattr(sys.modules[amod], target_name):\n            obj_type = \":py:func\" if callable(obj) else \":py:class\"\n            lines.append(\".. rubric:: Alias of %s:`%s.%s`\" % (obj_type, amod, target_name))\n\n\ndef process_docstring(app, what, name, obj, options, lines):\n    \"\"\"Sphinx callback to process docstring\"\"\"\n    if callable(obj) or inspect.isclass(obj):\n        update_alias_docstring(name, obj, lines)\n\n\nfrom legacy_redirect import build_legacy_redirect\n\n\ndef setup(app):\n    app.connect(\"autodoc-process-docstring\", process_docstring)\n    app.connect(\"build-finished\", build_legacy_redirect(tvm_path))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "docs/legacy_redirect.py",
        "content": "# -*- coding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom string import Template\nimport json\nimport os\n\nlegacy_redirects = [\n    [\"dev/benchmark.html\", \"../arch/benchmark.html\"],\n    [\"dev/convert_layout.html\", \"../arch/convert_layout.html\"],\n    [\"dev/debugger.html\", \"../arch/debugger.html\"],\n    [\"dev/device_target_interactions.html\", \"../arch/device_target_interactions.html\"],\n    [\"dev/frontend/tensorflow.html\", \"../../arch/frontend/tensorflow.html\"],\n    [\"dev/hybrid_script.html\", \"../arch/hybrid_script.html\"],\n    [\"dev/index.html\", \"../arch/index.html\"],\n    [\"dev/inferbound.html\", \"../arch/inferbound.html\"],\n    [\n        \"dev/introduction_to_module_serialization.html\",\n        \"../arch/introduction_to_module_serialization.html\",\n    ],\n    [\"dev/microtvm_design.html\", \"../arch/microtvm_design.html\"],\n    [\"dev/model_library_format.html\", \"../arch/model_library_format.html\"],\n    [\"dev/pass_infra.html\", \"../arch/pass_infra.html\"],\n    [\"dev/relay_intro.html\", \"../arch/relay_intro.html\"],\n    [\"dev/relay_op_strategy.html\", \"../arch/relay_op_strategy.html\"],\n    [\"dev/runtime.html\", \"../arch/runtime.html\"],\n    [\"dev/runtimes/vulkan.html\", \"../../arch/runtimes/vulkan.html\"],\n    [\"dev/security.html\", \"../arch/security.html\"],\n    [\"dev/virtual_machine.html\", \"../arch/virtual_machine.html\"],\n    [\"dev/how_to.html\", \"index.html\"],\n    [\"dev/pytest_target_parametrization.html\", \"how_to/pytest_target_parametrization.html\"],\n    [\"dev/relay_add_op.html\", \"how_to/relay_add_op.html\"],\n    [\"dev/relay_add_pass.html\", \"how_to/relay_add_pass.html\"],\n    [\"dev/relay_bring_your_own_codegen.html\", \"how_to/relay_bring_your_own_codegen.html\"],\n    [\"dev/codebase_walkthrough.html\", \"tutorial/codebase_walkthrough.html\"],\n    [\"deploy/android.html\", \"../how_to/deploy/android.html\"],\n    [\"deploy/arm_compute_lib.html\", \"../how_to/deploy/arm_compute_lib.html\"],\n    [\"deploy/bnns.html\", \"../how_to/deploy/bnns.html\"],\n    [\"deploy/cpp_deploy.html\", \"../how_to/deploy/cpp_deploy.html\"],\n    [\"deploy/hls.html\", \"../how_to/deploy/hls.html\"],\n    [\"deploy/index.html\", \"../how_to/deploy/index.html\"],\n    [\"deploy/integrate.html\", \"../how_to/deploy/integrate.html\"],\n    [\"deploy/tensorrt.html\", \"../how_to/deploy/tensorrt.html\"],\n    [\"deploy/vitis_ai.html\", \"../how_to/deploy/vitis_ai.html\"],\n    [\"profiling/index.html\", \"../how_to/profile/index.html\"],\n    [\"profiling/papi.html\", \"../how_to/profile/papi.html\"],\n    [\"api/links.html\", \"../reference/api/links.html\"],\n    [\"api/python/auto_scheduler.html\", \"../../reference/api/python/auto_scheduler.html\"],\n    [\"api/python/autotvm.html\", \"../../reference/api/python/autotvm.html\"],\n    [\"api/python/contrib.html\", \"../../reference/api/python/contrib.html\"],\n    [\"api/python/driver.html\", \"../../reference/api/python/driver.html\"],\n    [\"api/python/error.html\", \"../../reference/api/python/error.html\"],\n    [\"api/python/graph_executor.html\", \"../../reference/api/python/graph_executor.html\"],\n    [\"api/python/index.html\", \"../../reference/api/python/index.html\"],\n    [\"api/python/ir.html\", \"../../reference/api/python/ir.html\"],\n    [\"api/python/micro.html\", \"../../reference/api/python/micro.html\"],\n    [\"api/python/ndarray.html\", \"../../reference/api/python/ndarray.html\"],\n    [\"api/python/relay/analysis.html\", \"../../../reference/api/python/relay/analysis.html\"],\n    [\"api/python/relay/backend.html\", \"../../../reference/api/python/relay/backend.html\"],\n    [\n        \"api/python/relay/dataflow_pattern.html\",\n        \"../../../reference/api/python/relay/dataflow_pattern.html\",\n    ],\n    [\"api/python/relay/frontend.html\", \"../../../reference/api/python/relay/frontend.html\"],\n    [\"api/python/relay/image.html\", \"../../../reference/api/python/relay/image.html\"],\n    [\"api/python/relay/index.html\", \"../../../reference/api/python/relay/index.html\"],\n    [\"api/python/relay/nn.html\", \"../../../reference/api/python/relay/nn.html\"],\n    [\"api/python/relay/testing.html\", \"../../../reference/api/python/relay/testing.html\"],\n    [\"api/python/relay/transform.html\", \"../../../reference/api/python/relay/transform.html\"],\n    [\"api/python/relay/vision.html\", \"../../../reference/api/python/relay/vision.html\"],\n    [\"api/python/rpc.html\", \"../../reference/api/python/rpc.html\"],\n    [\"api/python/runtime.html\", \"../../reference/api/python/runtime.html\"],\n    [\"api/python/target.html\", \"../../reference/api/python/target.html\"],\n    [\"api/python/te.html\", \"../../reference/api/python/te.html\"],\n    [\"api/python/tir.html\", \"../../reference/api/python/tir.html\"],\n    [\"api/python/topi.html\", \"../../reference/api/python/topi.html\"],\n    [\"api/python/vta/index.html\", \"../../../reference/api/python/vta/index.html\"],\n    [\"langref/hybrid_script.html\", \"../reference/langref/hybrid_script.html\"],\n    [\"langref/index.html\", \"../reference/langref/index.html\"],\n    [\"langref/relay_adt.html\", \"../reference/langref/relay_adt.html\"],\n    [\"langref/relay_expr.html\", \"../reference/langref/relay_expr.html\"],\n    [\"langref/relay_op.html\", \"../reference/langref/relay_op.html\"],\n    [\"langref/relay_pattern.html\", \"../reference/langref/relay_pattern.html\"],\n    [\"langref/relay_type.html\", \"../reference/langref/relay_type.html\"],\n    [\"microtvm/index.html\", \"../topic/microtvm/index.html\"],\n    [\"vta/dev/config.html\", \"../../topic/vta/dev/config.html\"],\n    [\"vta/dev/hardware.html\", \"../../topic/vta/dev/hardware.html\"],\n    [\"vta/dev/index.html\", \"../../topic/vta/dev/index.html\"],\n    [\"vta/index.html\", \"../topic/vta/index.html\"],\n    [\"vta/install.html\", \"../topic/vta/install.html\"],\n    [\"tutorials/index.html\", \"../tutorial/index.html\"],\n    [\"tutorials/frontend/from_caffe2.html\", \"../../how_to/compile_models/from_caffe2.html\"],\n    [\"tutorials/frontend/from_coreml.html\", \"../../how_to/compile_models/from_coreml.html\"],\n    [\"tutorials/frontend/from_darknet.html\", \"../../how_to/compile_models/from_darknet.html\"],\n    [\"tutorials/frontend/from_keras.html\", \"../../how_to/compile_models/from_keras.html\"],\n    [\"tutorials/frontend/from_mxnet.html\", \"../../how_to/compile_models/from_mxnet.html\"],\n    [\"tutorials/frontend/from_onnx.html\", \"../../how_to/compile_models/from_onnx.html\"],\n    [\"tutorials/frontend/from_paddle.html\", \"../../how_to/compile_models/from_paddle.html\"],\n    [\"tutorials/frontend/from_pytorch.html\", \"../../how_to/compile_models/from_pytorch.html\"],\n    [\"tutorials/frontend/from_tensorflow.html\", \"../../how_to/compile_models/from_tensorflow.html\"],\n    [\"tutorials/frontend/from_tflite.html\", \"../../how_to/compile_models/from_tflite.html\"],\n    [\n        \"tutorials/frontend/deploy_model_on_android.html\",\n        \"../../how_to/deploy_models/deploy_model_on_android.html\",\n    ],\n    [\n        \"tutorials/frontend/deploy_model_on_rasp.html\",\n        \"../../how_to/deploy_models/deploy_model_on_rasp.html\",\n    ],\n    [\n        \"tutorials/frontend/deploy_object_detection_pytorch.html\",\n        \"../../how_to/deploy_models/deploy_object_detection_pytorch.html\",\n    ],\n    [\n        \"tutorials/frontend/deploy_prequantized.html\",\n        \"../../how_to/deploy_models/deploy_prequantized.html\",\n    ],\n    [\n        \"tutorials/frontend/deploy_prequantized_tflite.html\",\n        \"../../how_to/deploy_models/deploy_prequantized_tflite.html\",\n    ],\n    [\n        \"tutorials/frontend/deploy_quantized.html\",\n        \"../../how_to/deploy_models/deploy_quantized.html\",\n    ],\n    [\"tutorials/frontend/deploy_sparse.html\", \"../../how_to/deploy_models/deploy_sparse.html\"],\n    [\n        \"tutorials/frontend/deploy_ssd_gluoncv.html\",\n        \"../../how_to/deploy_models/deploy_ssd_gluoncv.html\",\n    ],\n    [\n        \"tutorials/dev/bring_your_own_datatypes.html\",\n        \"../../how_to/extend_tvm/bring_your_own_datatypes.html\",\n    ],\n    [\n        \"tutorials/dev/low_level_custom_pass.html\",\n        \"../../how_to/extend_tvm/low_level_custom_pass.html\",\n    ],\n    [\"tutorials/dev/use_pass_infra.html\", \"../../how_to/extend_tvm/use_pass_infra.html\"],\n    [\"tutorials/dev/use_pass_instrument.html\", \"../../how_to/extend_tvm/use_pass_instrument.html\"],\n    [\"tutorials/optimize/opt_conv_cuda.html\", \"../../how_to/optimize_operators/opt_conv_cuda.html\"],\n    [\n        \"tutorials/optimize/opt_conv_tensorcore.html\",\n        \"../../how_to/optimize_operators/opt_conv_tensorcore.html\",\n    ],\n    [\"tutorials/optimize/opt_gemm.html\", \"../../how_to/optimize_operators/opt_gemm.html\"],\n    [\n        \"tutorials/auto_scheduler/tune_conv2d_layer_cuda.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_conv2d_layer_cuda.html\",\n    ],\n    [\n        \"tutorials/auto_scheduler/tune_network_arm.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_network_arm.html\",\n    ],\n    [\n        \"tutorials/auto_scheduler/tune_network_cuda.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_network_cuda.html\",\n    ],\n    [\n        \"tutorials/auto_scheduler/tune_network_mali.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_network_mali.html\",\n    ],\n    [\n        \"tutorials/auto_scheduler/tune_network_x86.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_network_x86.html\",\n    ],\n    [\n        \"tutorials/auto_scheduler/tune_sparse_x86.html\",\n        \"../../how_to/tune_with_autoscheduler/tune_sparse_x86.html\",\n    ],\n    [\n        \"tutorials/autotvm/tune_conv2d_cuda.html\",\n        \"../../how_to/tune_with_autotvm/tune_conv2d_cuda.html\",\n    ],\n    [\"tutorials/autotvm/tune_relay_arm.html\", \"../../how_to/tune_with_autotvm/tune_relay_arm.html\"],\n    [\n        \"tutorials/autotvm/tune_relay_cuda.html\",\n        \"../../how_to/tune_with_autotvm/tune_relay_cuda.html\",\n    ],\n    [\n        \"tutorials/autotvm/tune_relay_mobile_gpu.html\",\n        \"../../how_to/tune_with_autotvm/tune_relay_mobile_gpu.html\",\n    ],\n    [\"tutorials/autotvm/tune_relay_x86.html\", \"../../how_to/tune_with_autotvm/tune_relay_x86.html\"],\n    [\"tutorials/micro/micro_autotune.html\", \"../../how_to/work_with_microtvm/micro_autotune.html\"],\n    [\n        \"tutorials/micro/micro_reference_vm.html\",\n        \"../../how_to/work_with_microtvm/micro_reference_vm.html\",\n    ],\n    [\"tutorials/micro/micro_tflite.html\", \"../../how_to/work_with_microtvm/micro_tflite.html\"],\n    [\"tutorials/frontend/build_gcn.html\", \"../../how_to/work_with_relay/build_gcn.html\"],\n    [\n        \"tutorials/frontend/using_external_lib.html\",\n        \"../../how_to/work_with_relay/using_external_lib.html\",\n    ],\n    [\"tutorials/language/extern_op.html\", \"../../how_to/work_with_schedules/extern_op.html\"],\n    [\"tutorials/language/intrin_math.html\", \"../../how_to/work_with_schedules/intrin_math.html\"],\n    [\"tutorials/language/reduction.html\", \"../../how_to/work_with_schedules/reduction.html\"],\n    [\"tutorials/language/scan.html\", \"../../how_to/work_with_schedules/scan.html\"],\n    [\n        \"tutorials/language/schedule_primitives.html\",\n        \"../../how_to/work_with_schedules/schedule_primitives.html\",\n    ],\n    [\"tutorials/language/tedd.html\", \"../../how_to/work_with_schedules/tedd.html\"],\n    [\"tutorials/language/tensorize.html\", \"../../how_to/work_with_schedules/tensorize.html\"],\n    [\"tutorials/language/tuple_inputs.html\", \"../../how_to/work_with_schedules/tuple_inputs.html\"],\n    [\n        \"tutorials/get_started/auto_scheduler_matmul_x86.html\",\n        \"../../tutorial/auto_scheduler_matmul_x86.html\",\n    ],\n    [\"tutorials/get_started/autotvm_matmul_x86.html\", \"../../tutorial/autotvm_matmul_x86.html\"],\n    [\"tutorials/get_started/autotvm_relay_x86.html\", \"../../tutorial/autotvm_relay_x86.html\"],\n    [\n        \"tutorials/get_started/cross_compilation_and_rpc.html\",\n        \"../../tutorial/cross_compilation_and_rpc.html\",\n    ],\n    [\"tutorials/get_started/install.html\", \"../../tutorial/install.html\"],\n    [\"tutorials/topi/intro_topi.html\", \"../../tutorial/intro_topi.html\"],\n    [\"tutorials/get_started/introduction.html\", \"../../tutorial/introduction.html\"],\n    [\"tutorials/get_started/relay_quick_start.html\", \"../../tutorial/relay_quick_start.html\"],\n    [\n        \"tutorials/get_started/tensor_expr_get_started.html\",\n        \"../../tutorial/tensor_expr_get_started.html\",\n    ],\n    [\n        \"tutorials/get_started/tvmc_command_line_driver.html\",\n        \"../../tutorial/tvmc_command_line_driver.html\",\n    ],\n    [\n        \"tutorials/get_started/tvmc_python.html\",\n        \"../../tutorial/tvmc_python.html\",\n    ],\n]\n\nredirect_template = \"\"\"\n<!DOCTYPE html>\n<html>\n  <head>\n    <meta http-equiv=\"refresh\" content=\"1; url=$to\" />\n    <script>\n      window.location.href = \"$to\"\n    </script>\n  </head>\n</html>\n\"\"\"\n\n\ndef build_legacy_redirect(tvm_path):\n    def legacy_redirect(app, docname):  # Sphinx expects two arguments\n        if app.builder.name == \"html\":\n\n            src = Template(redirect_template)\n\n            for frm, to in legacy_redirects:\n                frm = tvm_path.resolve() / \"docs\" / \"_build\" / \"html\" / frm\n                redirect = src.substitute({\"to\": to})\n                os.makedirs(os.path.dirname(frm), exist_ok=True)\n                with open(frm, \"w\") as f:\n                    f.write(redirect)\n\n    return legacy_redirect\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "docs/script_convert.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport pathlib\n\nBASH = \"# bash\"\nBASH_IGNORE = \"# bash-ignore\"\nBASH_MULTILINE_COMMENT_START = \": '\"\nBASH_MULTILINE_COMMENT_END = \"'\"\n\n\ndef bash_to_python(src_path: pathlib.Path, dest_path: pathlib.Path):\n    \"\"\"Convert a bash script file to a Python format compatible with Sphinx doc.\"\"\"\n    with open(src_path, \"r\") as src_f:\n        with open(dest_path, \"w\") as dest_f:\n            line = src_f.readline()\n            bash_block = []\n            bash_detected = False\n            bash_ignore_detected = False\n            new_line_required = False\n            while line:\n                line = line.strip(\"\\n\").strip(\"\\r\")\n                if bash_detected:\n                    if line == BASH:\n                        # write the bash block to destination\n                        if new_line_required:\n                            dest_f.write(\"\\n\")\n                        python_code = \"# .. code-block:: bash\\n#\\n\"\n                        for bash_line in bash_block:\n                            python_code += f\"#\\t  {bash_line}\\n\"\n                        python_code += \"#\"\n                        dest_f.write(python_code)\n\n                        bash_detected = False\n                        bash_block = []\n                        new_line_required = True\n                    else:\n                        # add new bash command line\n                        bash_block.append(line)\n                elif bash_ignore_detected:\n                    if line == BASH_IGNORE:\n                        bash_ignore_detected = False\n                        new_line_required = True\n                    else:\n                        new_line_required = False\n                        pass\n                else:\n                    if line == BASH:\n                        bash_detected = True\n                    elif line == BASH_IGNORE:\n                        bash_ignore_detected = True\n                    elif line in [BASH_MULTILINE_COMMENT_START, BASH_MULTILINE_COMMENT_END]:\n                        if new_line_required:\n                            dest_f.write(\"\\n\")\n                        dest_f.write('\"\"\"')\n                        new_line_required = True\n                    else:\n                        if new_line_required:\n                            dest_f.write(\"\\n\")\n                        dest_f.write(f\"{line}\")\n                        new_line_required = True\n\n                line = src_f.readline()\n            if new_line_required:\n                dest_f.write(\"\\n\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Convert tutorial script to Python.\")\n    parser.add_argument(\"script\", type=str, help=\"Path to script file.\")\n    args = parser.parse_args()\n\n    src_path = pathlib.Path(args.script)\n    dest_path = src_path.parent / f\"{src_path.stem}.py\"\n    bash_to_python(src_path, dest_path)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_coreml.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile CoreML Models\n=====================\n**Author**: `Joshua Z. Zhang <https://zhreshold.github.io/>`_, \\\n            `Kazutaka Morita <https://github.com/kazum>`_, \\\n            `Zhao Wu <https://github.com/FrozenGene>`_\n\nThis article is an introductory tutorial to deploy CoreML models with Relay.\n\nFor us to begin with, coremltools module is required to be installed.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n    pip install -U coremltools --user\n\nor please refer to official site\nhttps://github.com/apple/coremltools\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm.contrib.download import download_testdata\nimport coremltools as cm\nimport numpy as np\nfrom PIL import Image\n\n######################################################################\n# Load pretrained CoreML model\n# ----------------------------\n# We will download and load a pretrained mobilenet classification network\n# provided by apple in this example\nmodel_url = \"https://docs-assets.developer.apple.com/coreml/models/MobileNet.mlmodel\"\nmodel_file = \"mobilenet.mlmodel\"\nmodel_path = download_testdata(model_url, model_file, module=\"coreml\")\n# Now you have mobilenet.mlmodel on disk\nmlmodel = cm.models.MLModel(model_path)\n\n######################################################################\n# Load a test image\n# ------------------\n# A single cat dominates the examples!\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\n# Mobilenet.mlmodel's input is BGR format\nimg_bgr = np.array(img)[:, :, ::-1]\nx = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :]\n\n######################################################################\n# Compile the model on Relay\n# ---------------------------\n# We should be familiar with the process right now.\ntarget = \"llvm\"\nshape_dict = {\"image\": x.shape}\n\n# Parse CoreML model and convert into Relay computation graph\nmod, params = relay.frontend.from_coreml(mlmodel, shape_dict)\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target, params=params)\n\n######################################################################\n# Execute on TVM\n# -------------------\n# The process is no different from other example\nfrom tvm.contrib import graph_executor\n\ndev = tvm.cpu(0)\ndtype = \"float32\"\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n# set inputs\nm.set_input(\"image\", tvm.nd.array(x.astype(dtype)))\n# execute\nm.run()\n# get outputs\ntvm_output = m.get_output(0)\ntop1 = np.argmax(tvm_output.numpy()[0])\n\n#####################################################################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\n# You should see the following result: Top-1 id 282 class name tiger cat\nprint(\"Top-1 id\", top1, \"class name\", synset[top1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_darknet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile YOLO-V2 and YOLO-V3 in DarkNet Models\n=============================================\n**Author**: `Siju Samuel <https://siju-samuel.github.io/>`_\n\nThis article is an introductory tutorial to deploy darknet models with TVM.\nAll the required models and libraries will be downloaded from the internet by the script.\nThis script runs the YOLO-V2 and YOLO-V3 Model with the bounding boxes\nDarknet parsing have dependancy with CFFI and CV2 library\nPlease install CFFI and CV2 before executing this script\n\n.. code-block:: bash\n\n  pip install cffi\n  pip install opencv-python\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n# numpy and matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n# tvm, relay\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom ctypes import *\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.testing.darknet import __darknetffi__\nimport tvm.relay.testing.yolo_detection\nimport tvm.relay.testing.darknet\n\n######################################################################\n# Choose the model\n# -----------------------\n# Models are: 'yolov2', 'yolov3' or 'yolov3-tiny'\n\n# Model name\nMODEL_NAME = \"yolov3\"\n\n######################################################################\n# Download required files\n# -----------------------\n# Download cfg and weights file if first time.\nCFG_NAME = MODEL_NAME + \".cfg\"\nWEIGHTS_NAME = MODEL_NAME + \".weights\"\nREPO_URL = \"https://github.com/dmlc/web-data/blob/main/darknet/\"\nCFG_URL = REPO_URL + \"cfg/\" + CFG_NAME + \"?raw=true\"\nWEIGHTS_URL = \"https://pjreddie.com/media/files/\" + WEIGHTS_NAME\n\ncfg_path = download_testdata(CFG_URL, CFG_NAME, module=\"darknet\")\nweights_path = download_testdata(WEIGHTS_URL, WEIGHTS_NAME, module=\"darknet\")\n\n# Download and Load darknet library\nif sys.platform in [\"linux\", \"linux2\"]:\n    DARKNET_LIB = \"libdarknet2.0.so\"\n    DARKNET_URL = REPO_URL + \"lib/\" + DARKNET_LIB + \"?raw=true\"\nelif sys.platform == \"darwin\":\n    DARKNET_LIB = \"libdarknet_mac2.0.so\"\n    DARKNET_URL = REPO_URL + \"lib_osx/\" + DARKNET_LIB + \"?raw=true\"\nelse:\n    err = \"Darknet lib is not supported on {} platform\".format(sys.platform)\n    raise NotImplementedError(err)\n\nlib_path = download_testdata(DARKNET_URL, DARKNET_LIB, module=\"darknet\")\n\nDARKNET_LIB = __darknetffi__.dlopen(lib_path)\nnet = DARKNET_LIB.load_network(cfg_path.encode(\"utf-8\"), weights_path.encode(\"utf-8\"), 0)\ndtype = \"float32\"\nbatch_size = 1\n\ndata = np.empty([batch_size, net.c, net.h, net.w], dtype)\nshape_dict = {\"data\": data.shape}\nprint(\"Converting darknet to relay functions...\")\nmod, params = relay.frontend.from_darknet(net, dtype=dtype, shape=data.shape)\n\n######################################################################\n# Import the graph to Relay\n# -------------------------\n# compile the model\ntarget = tvm.target.Target(\"llvm\", host=\"llvm\")\ndev = tvm.cpu(0)\ndata = np.empty([batch_size, net.c, net.h, net.w], dtype)\nshape = {\"data\": data.shape}\nprint(\"Compiling the model...\")\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target=target, params=params)\n\n[neth, netw] = shape[\"data\"][2:]  # Current image shape is 608x608\n######################################################################\n# Load a test image\n# -----------------\ntest_image = \"dog.jpg\"\nprint(\"Loading the test image...\")\nimg_url = REPO_URL + \"data/\" + test_image + \"?raw=true\"\nimg_path = download_testdata(img_url, test_image, \"data\")\n\ndata = tvm.relay.testing.darknet.load_image(img_path, netw, neth)\n######################################################################\n# Execute on TVM Runtime\n# ----------------------\n# The process is no different from other examples.\nfrom tvm.contrib import graph_executor\n\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n\n# set inputs\nm.set_input(\"data\", tvm.nd.array(data.astype(dtype)))\n# execute\nprint(\"Running the test image...\")\n\n# detection\n# thresholds\nthresh = 0.5\nnms_thresh = 0.45\n\nm.run()\n# get outputs\ntvm_out = []\nif MODEL_NAME == \"yolov2\":\n    layer_out = {}\n    layer_out[\"type\"] = \"Region\"\n    # Get the region layer attributes (n, out_c, out_h, out_w, classes, coords, background)\n    layer_attr = m.get_output(2).numpy()\n    layer_out[\"biases\"] = m.get_output(1).numpy()\n    out_shape = (layer_attr[0], layer_attr[1] // layer_attr[0], layer_attr[2], layer_attr[3])\n    layer_out[\"output\"] = m.get_output(0).numpy().reshape(out_shape)\n    layer_out[\"classes\"] = layer_attr[4]\n    layer_out[\"coords\"] = layer_attr[5]\n    layer_out[\"background\"] = layer_attr[6]\n    tvm_out.append(layer_out)\n\nelif MODEL_NAME == \"yolov3\":\n    for i in range(3):\n        layer_out = {}\n        layer_out[\"type\"] = \"Yolo\"\n        # Get the yolo layer attributes (n, out_c, out_h, out_w, classes, total)\n        layer_attr = m.get_output(i * 4 + 3).numpy()\n        layer_out[\"biases\"] = m.get_output(i * 4 + 2).numpy()\n        layer_out[\"mask\"] = m.get_output(i * 4 + 1).numpy()\n        out_shape = (layer_attr[0], layer_attr[1] // layer_attr[0], layer_attr[2], layer_attr[3])\n        layer_out[\"output\"] = m.get_output(i * 4).numpy().reshape(out_shape)\n        layer_out[\"classes\"] = layer_attr[4]\n        tvm_out.append(layer_out)\n\nelif MODEL_NAME == \"yolov3-tiny\":\n    for i in range(2):\n        layer_out = {}\n        layer_out[\"type\"] = \"Yolo\"\n        # Get the yolo layer attributes (n, out_c, out_h, out_w, classes, total)\n        layer_attr = m.get_output(i * 4 + 3).numpy()\n        layer_out[\"biases\"] = m.get_output(i * 4 + 2).numpy()\n        layer_out[\"mask\"] = m.get_output(i * 4 + 1).numpy()\n        out_shape = (layer_attr[0], layer_attr[1] // layer_attr[0], layer_attr[2], layer_attr[3])\n        layer_out[\"output\"] = m.get_output(i * 4).numpy().reshape(out_shape)\n        layer_out[\"classes\"] = layer_attr[4]\n        tvm_out.append(layer_out)\n        thresh = 0.560\n\n# do the detection and bring up the bounding boxes\nimg = tvm.relay.testing.darknet.load_image_color(img_path)\n_, im_h, im_w = img.shape\ndets = tvm.relay.testing.yolo_detection.fill_network_boxes(\n    (netw, neth), (im_w, im_h), thresh, 1, tvm_out\n)\nlast_layer = net.layers[net.n - 1]\ntvm.relay.testing.yolo_detection.do_nms_sort(dets, last_layer.classes, nms_thresh)\n\ncoco_name = \"coco.names\"\ncoco_url = REPO_URL + \"data/\" + coco_name + \"?raw=true\"\nfont_name = \"arial.ttf\"\nfont_url = REPO_URL + \"data/\" + font_name + \"?raw=true\"\ncoco_path = download_testdata(coco_url, coco_name, module=\"data\")\nfont_path = download_testdata(font_url, font_name, module=\"data\")\n\nwith open(coco_path) as f:\n    content = f.readlines()\n\nnames = [x.strip() for x in content]\n\ntvm.relay.testing.yolo_detection.show_detections(img, dets, thresh, names, last_layer.classes)\ntvm.relay.testing.yolo_detection.draw_detections(\n    font_path, img, dets, thresh, names, last_layer.classes\n)\nplt.imshow(img.transpose(1, 2, 0))\nplt.show()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_keras.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile Keras Models\n=====================\n**Author**: `Yuwei Hu <https://Huyuwei.github.io/>`_\n\nThis article is an introductory tutorial to deploy keras models with Relay.\n\nFor us to begin with, keras should be installed.\nTensorflow is also required since it's used as the default backend of keras.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n    pip install -U keras --user\n    pip install -U tensorflow --user\n\nor please refer to official site\nhttps://keras.io/#installation\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm.contrib.download import download_testdata\nimport keras\nimport tensorflow as tf\nimport numpy as np\n\n######################################################################\n# Load pretrained keras model\n# ----------------------------\n# We load a pretrained resnet-50 classification model provided by keras.\n\nif tuple(keras.__version__.split(\".\")) < (\"2\", \"4\", \"0\"):\n    weights_url = \"\".join(\n        [\n            \"https://github.com/fchollet/deep-learning-models/releases/\",\n            \"download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5\",\n        ]\n    )\n    weights_file = \"resnet50_keras_old.h5\"\nelse:\n    weights_url = \"\".join(\n        [\n            \" https://storage.googleapis.com/tensorflow/keras-applications/\",\n            \"resnet/resnet50_weights_tf_dim_ordering_tf_kernels.h5\",\n        ]\n    )\n    weights_file = \"resnet50_keras_new.h5\"\n\n\nweights_path = download_testdata(weights_url, weights_file, module=\"keras\")\nkeras_resnet50 = tf.keras.applications.resnet50.ResNet50(\n    include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000\n)\nkeras_resnet50.load_weights(weights_path)\n\n######################################################################\n# Load a test image\n# ------------------\n# A single cat dominates the examples!\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\nplt.imshow(img)\nplt.show()\n# input preprocess\ndata = np.array(img)[np.newaxis, :].astype(\"float32\")\ndata = preprocess_input(data).transpose([0, 3, 1, 2])\nprint(\"input_1\", data.shape)\n\n######################################################################\n# Compile the model with Relay\n# ----------------------------\n# convert the keras model(NHWC layout) to Relay format(NCHW layout).\nshape_dict = {\"input_1\": data.shape}\nmod, params = relay.frontend.from_keras(keras_resnet50, shape_dict)\n# compile the model\ntarget = \"cuda\"\ndev = tvm.cuda(0)\n\n# TODO(mbs): opt_level=3 causes nn.contrib_conv2d_winograd_weight_transform\n# to end up in the module which fails memory validation on cuda most likely\n# due to a latent bug. Note that the pass context only has an effect within\n# evaluate() and is not captured by create_executor().\nwith tvm.transform.PassContext(opt_level=0):\n    model = relay.build_module.create_executor(\"graph\", mod, dev, target, params).evaluate()\n\n\n######################################################################\n# Execute on TVM\n# ---------------\ndtype = \"float32\"\ntvm_out = model(tvm.nd.array(data.astype(dtype)))\ntop1_tvm = np.argmax(tvm_out.numpy()[0])\n\n#####################################################################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\nprint(\"Relay top-1 id: {}, class name: {}\".format(top1_tvm, synset[top1_tvm]))\n# confirm correctness with keras output\nkeras_out = keras_resnet50.predict(data.transpose([0, 2, 3, 1]))\ntop1_keras = np.argmax(keras_out)\nprint(\"Keras top-1 id: {}, class name: {}\".format(top1_keras, synset[top1_keras]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_mxnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-from-mxnet:\n\nCompile MXNet Models\n====================\n**Author**: `Joshua Z. Zhang <https://zhreshold.github.io/>`_, \\\n            `Kazutaka Morita <https://github.com/kazum>`_\n\nThis article is an introductory tutorial to deploy mxnet models with Relay.\n\nFor us to begin with, mxnet module is required to be installed.\n\nA quick solution is\n\n.. code-block:: bash\n\n    pip install mxnet --user\n\nor please refer to official installation guide.\nhttps://mxnet.apache.org/versions/master/install/index.html\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n# some standard imports\nimport mxnet as mx\nimport tvm\nimport tvm.relay as relay\nimport numpy as np\n\n######################################################################\n# Download Resnet18 model from Gluon Model Zoo\n# ---------------------------------------------\n# In this section, we download a pretrained imagenet model and classify an image.\nfrom tvm.contrib.download import download_testdata\nfrom mxnet.gluon.model_zoo.vision import get_model\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\nblock = get_model(\"resnet18_v1\", pretrained=True)\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_name = \"cat.png\"\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\nimage = Image.open(img_path).resize((224, 224))\nplt.imshow(image)\nplt.show()\n\n\ndef transform_image(image):\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image\n\n\nx = transform_image(image)\nprint(\"x\", x.shape)\n\n######################################################################\n# Compile the Graph\n# -----------------\n# Now we would like to port the Gluon model to a portable computational graph.\n# It's as easy as several lines.\n# We support MXNet static graph(symbol) and HybridBlock in mxnet.gluon\nshape_dict = {\"data\": x.shape}\nmod, params = relay.frontend.from_mxnet(block, shape_dict)\n## we want a probability so add a softmax operator\nfunc = mod[\"main\"]\nfunc = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs)\n\n######################################################################\n# now compile the graph\ntarget = \"cuda\"\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(func, target, params=params)\n\n######################################################################\n# Execute the portable graph on TVM\n# ---------------------------------\n# Now, we would like to reproduce the same forward computation using TVM.\nfrom tvm.contrib import graph_executor\n\ndev = tvm.cuda(0)\ndtype = \"float32\"\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n# set inputs\nm.set_input(\"data\", tvm.nd.array(x.astype(dtype)))\n# execute\nm.run()\n# get outputs\ntvm_output = m.get_output(0)\ntop1 = np.argmax(tvm_output.numpy()[0])\nprint(\"TVM prediction top-1:\", top1, synset[top1])\n\n######################################################################\n# Use MXNet symbol with pretrained weights\n# ----------------------------------------\n# MXNet often use `arg_params` and `aux_params` to store network parameters\n# separately, here we show how to use these weights with existing API\ndef block2symbol(block):\n    data = mx.sym.Variable(\"data\")\n    sym = block(data)\n    args = {}\n    auxs = {}\n    for k, v in block.collect_params().items():\n        args[k] = mx.nd.array(v.data().asnumpy())\n    return sym, args, auxs\n\n\nmx_sym, args, auxs = block2symbol(block)\n# usually we would save/load it as checkpoint\nmx.model.save_checkpoint(\"resnet18_v1\", 0, mx_sym, args, auxs)\n# there are 'resnet18_v1-0000.params' and 'resnet18_v1-symbol.json' on disk\n\n######################################################################\n# for a normal mxnet model, we start from here\nmx_sym, args, auxs = mx.model.load_checkpoint(\"resnet18_v1\", 0)\n# now we use the same API to get Relay computation graph\nmod, relay_params = relay.frontend.from_mxnet(mx_sym, shape_dict, arg_params=args, aux_params=auxs)\n# repeat the same steps to run this model using TVM\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_oneflow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile OneFlow Models\n======================\n**Author**: `Xiaoyu Zhang <https://github.com/BBuf/>`_\n\nThis article is an introductory tutorial to deploy OneFlow models with Relay.\n\nFor us to begin with, OneFlow package should be installed.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n    pip install flowvision==0.1.0\n    python3 -m pip install -f https://release.oneflow.info oneflow==0.7.0+cpu\n\nor please refer to official site:\nhttps://github.com/Oneflow-Inc/oneflow\n\nCurrently, TVM supports OneFlow 0.7.0. Other versions may be unstable.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport os, math\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\n# oneflow imports\nimport flowvision\nimport oneflow as flow\nimport oneflow.nn as nn\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# Load a pretrained OneFlow model and save model\n# ----------------------------------------------\nmodel_name = \"resnet18\"\nmodel = getattr(flowvision.models, model_name)(pretrained=True)\nmodel = model.eval()\n\nmodel_dir = \"resnet18_model\"\nif not os.path.exists(model_dir):\n    flow.save(model.state_dict(), model_dir)\n\n######################################################################\n# Load a test image\n# -----------------\n# Classic cat example!\nfrom PIL import Image\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\n\n# Preprocess the image and convert to tensor\nfrom flowvision import transforms\n\nmy_preprocess = transforms.Compose(\n    [\n        transforms.Resize(256),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n    ]\n)\nimg = my_preprocess(img)\nimg = np.expand_dims(img.numpy(), 0)\n\n######################################################################\n# Import the graph to Relay\n# -------------------------\n# Convert OneFlow graph to Relay graph. The input name can be arbitrary.\nclass Graph(flow.nn.Graph):\n    def __init__(self, module):\n        super().__init__()\n        self.m = module\n\n    def build(self, x):\n        out = self.m(x)\n        return out\n\n\ngraph = Graph(model)\n_ = graph._compile(flow.randn(1, 3, 224, 224))\n\nmod, params = relay.frontend.from_oneflow(graph, model_dir)\n\n######################################################################\n# Relay Build\n# -----------\n# Compile the graph to llvm target with given input specification.\ntarget = tvm.target.Target(\"llvm\", host=\"llvm\")\ndev = tvm.cpu(0)\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target=target, params=params)\n\n######################################################################\n# Execute the portable graph on TVM\n# ---------------------------------\n# Now we can try deploying the compiled model on target.\ntarget = \"cuda\"\nwith tvm.transform.PassContext(opt_level=10):\n    intrp = relay.build_module.create_executor(\"graph\", mod, tvm.cuda(0), target)\n\nprint(type(img))\nprint(img.shape)\ntvm_output = intrp.evaluate()(tvm.nd.array(img.astype(\"float32\")), **params)\n\n#####################################################################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\nsynset_url = \"\".join(\n    [\n        \"https://raw.githubusercontent.com/Cadene/\",\n        \"pretrained-models.pytorch/master/data/\",\n        \"imagenet_synsets.txt\",\n    ]\n)\nsynset_name = \"imagenet_synsets.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synsets = f.readlines()\n\nsynsets = [x.strip() for x in synsets]\nsplits = [line.split(\" \") for line in synsets]\nkey_to_classname = {spl[0]: \" \".join(spl[1:]) for spl in splits}\n\nclass_url = \"\".join(\n    [\n        \"https://raw.githubusercontent.com/Cadene/\",\n        \"pretrained-models.pytorch/master/data/\",\n        \"imagenet_classes.txt\",\n    ]\n)\nclass_name = \"imagenet_classes.txt\"\nclass_path = download_testdata(class_url, class_name, module=\"data\")\nwith open(class_path) as f:\n    class_id_to_key = f.readlines()\n\nclass_id_to_key = [x.strip() for x in class_id_to_key]\n\n# Get top-1 result for TVM\ntop1_tvm = np.argmax(tvm_output.numpy()[0])\ntvm_class_key = class_id_to_key[top1_tvm]\n\n# Convert input to OneFlow variable and get OneFlow result for comparison\nwith flow.no_grad():\n    torch_img = flow.from_numpy(img)\n    output = model(torch_img)\n\n    # Get top-1 result for OneFlow\n    top_oneflow = np.argmax(output.numpy())\n    oneflow_class_key = class_id_to_key[top_oneflow]\n\nprint(\"Relay top-1 id: {}, class name: {}\".format(top1_tvm, key_to_classname[tvm_class_key]))\nprint(\n    \"OneFlow top-1 id: {}, class name: {}\".format(top_oneflow, key_to_classname[oneflow_class_key])\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile ONNX Models\n===================\n**Author**: `Joshua Z. Zhang <https://zhreshold.github.io/>`_\n\nThis article is an introductory tutorial to deploy ONNX models with Relay.\n\nFor us to begin with, ONNX package must be installed.\n\nA quick solution is to install protobuf compiler, and\n\n.. code-block:: bash\n\n    pip install --user onnx onnxoptimizer\n\nor please refer to official site.\nhttps://github.com/onnx/onnx\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport onnx\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# Load pretrained ONNX model\n# ---------------------------------------------\n# The example super resolution model used here is exactly the same model in onnx tutorial\n# http://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html\n# we skip the pytorch model construction part, and download the saved onnx model\nmodel_url = \"\".join(\n    [\n        \"https://gist.github.com/zhreshold/\",\n        \"bcda4716699ac97ea44f791c24310193/raw/\",\n        \"93672b029103648953c4e5ad3ac3aadf346a4cdc/\",\n        \"super_resolution_0.2.onnx\",\n    ]\n)\nmodel_path = download_testdata(model_url, \"super_resolution.onnx\", module=\"onnx\")\n# now you have super_resolution.onnx on disk\nonnx_model = onnx.load(model_path)\n\n######################################################################\n# Load a test image\n# ---------------------------------------------\n# A single cat dominates the examples! This model takes a single input image of size\n# 224x224 and outputs a scaled image that is 3x greater than the input along each\n# axis, a 672x672 image. Re-scale the cat image to fit this input shape then\n# convert to `YCbCr`. The super resolution model will then be applied to the\n# luminance (`Y`) channel.\nfrom PIL import Image\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\nimg_ycbcr = img.convert(\"YCbCr\")  # convert to YCbCr\nimg_y, img_cb, img_cr = img_ycbcr.split()\nx = np.array(img_y)[np.newaxis, np.newaxis, :, :]\n\n######################################################################\n# Compile the model with relay\n# ---------------------------------------------\n# Typically ONNX models mix model input values with parameter values, with\n# the input having the name `1`. This model dependent, and you should check\n# with the documentation for your model to determine the full input and\n# parameter name space.\n#\n# Passing in the shape dictionary to the `relay.frontend.from_onnx` method\n# tells relay which ONNX parameters are inputs, and which are parameters, and\n# provides a static definition of the input size.\ntarget = \"llvm\"\n\ninput_name = \"1\"\nshape_dict = {input_name: x.shape}\nmod, params = relay.frontend.from_onnx(onnx_model, shape_dict)\n\nwith tvm.transform.PassContext(opt_level=1):\n    executor = relay.build_module.create_executor(\n        \"graph\", mod, tvm.cpu(0), target, params\n    ).evaluate()\n\n######################################################################\n# Execute on TVM\n# ---------------------------------------------\ndtype = \"float32\"\ntvm_output = executor(tvm.nd.array(x.astype(dtype))).numpy()\n\n######################################################################\n# Display results\n# ---------------------------------------------\n# We put input and output image neck to neck. The luminance channel, `Y` is the output\n# from the model. The chroma channels `Cb` and `Cr` are resized to match with a simple\n# bicubic algorithm. The image is then recombined and converted back to `RGB`.\nfrom matplotlib import pyplot as plt\n\nout_y = Image.fromarray(np.uint8((tvm_output[0, 0]).clip(0, 255)), mode=\"L\")\nout_cb = img_cb.resize(out_y.size, Image.BICUBIC)\nout_cr = img_cr.resize(out_y.size, Image.BICUBIC)\nresult = Image.merge(\"YCbCr\", [out_y, out_cb, out_cr]).convert(\"RGB\")\ncanvas = np.full((672, 672 * 2, 3), 255)\ncanvas[0:224, 0:224, :] = np.asarray(img)\ncanvas[:, 672:, :] = np.asarray(result)\nplt.imshow(canvas.astype(np.uint8))\nplt.show()\n\n######################################################################\n# Notes\n# ---------------------------------------------\n# By default, ONNX defines models in terms of dynamic shapes. The ONNX importer\n# retains that dynamism upon import, and the compiler attempts to convert the model\n# into a static shapes at compile time. If this fails, there may still be dynamic\n# operations in the model. Not all TVM kernels currently support dynamic shapes,\n# please file an issue on discuss.tvm.apache.org if you hit an error with dynamic kernels.\n#\n# This particular model was build using an older version of ONNX. During the import\n# phase ONNX importer will run the ONNX verifier, which may throw a `Mismatched attribute type`\n# warning. Because TVM supports a number of different ONNX versions, the Relay model\n# will still be valid.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_paddle.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile PaddlePaddle Models\n===========================\n**Author**: `Ziyuan Ma <https://github.com/ZiyuanMa/>`_\n\nThis article is an introductory tutorial to deploy PaddlePaddle models with Relay.\nFor us to begin with, PaddlePaddle>=2.1.3 is required to be installed.\nA quick solution is\n\n.. code-block:: bash\n\n    pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple\n\nor please refer to official site.\nhttps://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/pip/linux-pip.html\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tarfile\nimport paddle\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# Load pretrained ResNet50 model\n# ---------------------------------------------\n# We load a pretrained ResNet50 provided by PaddlePaddle.\nurl = \"https://bj.bcebos.com/x2paddle/models/paddle_resnet50.tar\"\nmodel_path = download_testdata(url, \"paddle_resnet50.tar\", module=\"model\")\n\nwith tarfile.open(model_path) as tar:\n    names = tar.getnames()\n    for name in names:\n        tar.extract(name, \"./\")\n\nmodel = paddle.jit.load(\"./paddle_resnet50/model\")\n\n######################################################################\n# Load a test image\n# ---------------------------------------------\n# A single cat dominates the examples!\n\nfrom PIL import Image\nimport paddle.vision.transforms as T\n\n\ntransforms = T.Compose(\n    [\n        T.Resize((256, 256)),\n        T.CenterCrop(224),\n        T.ToTensor(),\n        T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n    ]\n)\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\n\nimg = transforms(img)\nimg = np.expand_dims(img, axis=0)\n\n######################################################################\n# Compile the model with relay\n# ---------------------------------------------\n\ntarget = \"llvm\"\nshape_dict = {\"inputs\": img.shape}\nmod, params = relay.frontend.from_paddle(model, shape_dict)\n\nwith tvm.transform.PassContext(opt_level=3):\n    executor = relay.build_module.create_executor(\n        \"graph\", mod, tvm.cpu(0), target, params\n    ).evaluate()\n\n######################################################################\n# Execute on TVM\n# ---------------------------------------------\ndtype = \"float32\"\ntvm_output = executor(tvm.nd.array(img.astype(dtype))).numpy()\n\n######################################################################\n# Look up synset name\n# ---------------------------------------------\n# Look up prediction top 1 index in 1000 class synset.\n\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = f.readlines()\n\ntop1 = np.argmax(tvm_output[0])\nprint(f\"TVM prediction top-1 id: {top1}, class name: {synset[top1]}\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_pytorch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile PyTorch Models\n======================\n**Author**: `Alex Wong <https://github.com/alexwong/>`_\n\nThis article is an introductory tutorial to deploy PyTorch models with Relay.\n\nFor us to begin with, PyTorch should be installed.\nTorchVision is also required since we will be using it as our model zoo.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n    pip install torch==1.7.0\n    pip install torchvision==0.8.1\n\nor please refer to official site\nhttps://pytorch.org/get-started/locally/\n\nPyTorch versions should be backwards compatible but should be used\nwith the proper TorchVision version.\n\nCurrently, TVM supports PyTorch 1.7 and 1.4. Other versions may\nbe unstable.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import relay\n\nimport numpy as np\n\nfrom tvm.contrib.download import download_testdata\n\n# PyTorch imports\nimport torch\nimport torchvision\n\n######################################################################\n# Load a pretrained PyTorch model\n# -------------------------------\nmodel_name = \"resnet18\"\nmodel = getattr(torchvision.models, model_name)(pretrained=True)\nmodel = model.eval()\n\n# We grab the TorchScripted model via tracing\ninput_shape = [1, 3, 224, 224]\ninput_data = torch.randn(input_shape)\nscripted_model = torch.jit.trace(model, input_data).eval()\n\n######################################################################\n# Load a test image\n# -----------------\n# Classic cat example!\nfrom PIL import Image\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\n\n# Preprocess the image and convert to tensor\nfrom torchvision import transforms\n\nmy_preprocess = transforms.Compose(\n    [\n        transforms.Resize(256),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n    ]\n)\nimg = my_preprocess(img)\nimg = np.expand_dims(img, 0)\n\n######################################################################\n# Import the graph to Relay\n# -------------------------\n# Convert PyTorch graph to Relay graph. The input name can be arbitrary.\ninput_name = \"input0\"\nshape_list = [(input_name, img.shape)]\nmod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n\n######################################################################\n# Relay Build\n# -----------\n# Compile the graph to llvm target with given input specification.\ntarget = tvm.target.Target(\"llvm\", host=\"llvm\")\ndev = tvm.cpu(0)\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target=target, params=params)\n\n######################################################################\n# Execute the portable graph on TVM\n# ---------------------------------\n# Now we can try deploying the compiled model on target.\nfrom tvm.contrib import graph_executor\n\ndtype = \"float32\"\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n# Set inputs\nm.set_input(input_name, tvm.nd.array(img.astype(dtype)))\n# Execute\nm.run()\n# Get outputs\ntvm_output = m.get_output(0)\n\n#####################################################################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\nsynset_url = \"\".join(\n    [\n        \"https://raw.githubusercontent.com/Cadene/\",\n        \"pretrained-models.pytorch/master/data/\",\n        \"imagenet_synsets.txt\",\n    ]\n)\nsynset_name = \"imagenet_synsets.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synsets = f.readlines()\n\nsynsets = [x.strip() for x in synsets]\nsplits = [line.split(\" \") for line in synsets]\nkey_to_classname = {spl[0]: \" \".join(spl[1:]) for spl in splits}\n\nclass_url = \"\".join(\n    [\n        \"https://raw.githubusercontent.com/Cadene/\",\n        \"pretrained-models.pytorch/master/data/\",\n        \"imagenet_classes.txt\",\n    ]\n)\nclass_name = \"imagenet_classes.txt\"\nclass_path = download_testdata(class_url, class_name, module=\"data\")\nwith open(class_path) as f:\n    class_id_to_key = f.readlines()\n\nclass_id_to_key = [x.strip() for x in class_id_to_key]\n\n# Get top-1 result for TVM\ntop1_tvm = np.argmax(tvm_output.numpy()[0])\ntvm_class_key = class_id_to_key[top1_tvm]\n\n# Convert input to PyTorch variable and get PyTorch result for comparison\nwith torch.no_grad():\n    torch_img = torch.from_numpy(img)\n    output = model(torch_img)\n\n    # Get top-1 result for PyTorch\n    top1_torch = np.argmax(output.numpy())\n    torch_class_key = class_id_to_key[top1_torch]\n\nprint(\"Relay top-1 id: {}, class name: {}\".format(top1_tvm, key_to_classname[tvm_class_key]))\nprint(\"Torch top-1 id: {}, class name: {}\".format(top1_torch, key_to_classname[torch_class_key]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_tensorflow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile Tensorflow Models\n=========================\nThis article is an introductory tutorial to deploy tensorflow models with TVM.\n\nFor us to begin with, tensorflow python module is required to be installed.\n\nPlease refer to https://www.tensorflow.org/install\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n# tvm, relay\nimport tvm\nfrom tvm import te\nfrom tvm import relay\n\n# os and numpy\nimport numpy as np\nimport os.path\n\n# Tensorflow imports\nimport tensorflow as tf\n\n\n# Ask tensorflow to limit its GPU memory to what's actually needed\n# instead of gobbling everything that's available.\n# https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth\n# This way this tutorial is a little more friendly to sphinx-gallery.\ngpus = tf.config.list_physical_devices(\"GPU\")\nif gpus:\n    try:\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        print(\"tensorflow will use experimental.set_memory_growth(True)\")\n    except RuntimeError as e:\n        print(\"experimental.set_memory_growth option is not available: {}\".format(e))\n\n\ntry:\n    tf_compat_v1 = tf.compat.v1\nexcept ImportError:\n    tf_compat_v1 = tf\n\n# Tensorflow utility functions\nimport tvm.relay.testing.tf as tf_testing\n\n# Base location for model related files.\nrepo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n\n# Test image\nimg_name = \"elephant-299.jpg\"\nimage_url = os.path.join(repo_base, img_name)\n\n######################################################################\n# Tutorials\n# ---------\n# Please refer docs/frontend/tensorflow.md for more details for various models\n# from tensorflow.\n\nmodel_name = \"classify_image_graph_def-with_shapes.pb\"\nmodel_url = os.path.join(repo_base, model_name)\n\n# Image label map\nmap_proto = \"imagenet_2012_challenge_label_map_proto.pbtxt\"\nmap_proto_url = os.path.join(repo_base, map_proto)\n\n# Human readable text for labels\nlabel_map = \"imagenet_synset_to_human_label_map.txt\"\nlabel_map_url = os.path.join(repo_base, label_map)\n\n# Target settings\n# Use these commented settings to build for cuda.\n# target = tvm.target.Target(\"cuda\", host=\"llvm\")\n# layout = \"NCHW\"\n# dev = tvm.cuda(0)\ntarget = tvm.target.Target(\"llvm\", host=\"llvm\")\nlayout = None\ndev = tvm.cpu(0)\n\n######################################################################\n# Download required files\n# -----------------------\n# Download files listed above.\nfrom tvm.contrib.download import download_testdata\n\nimg_path = download_testdata(image_url, img_name, module=\"data\")\nmodel_path = download_testdata(model_url, model_name, module=[\"tf\", \"InceptionV1\"])\nmap_proto_path = download_testdata(map_proto_url, map_proto, module=\"data\")\nlabel_path = download_testdata(label_map_url, label_map, module=\"data\")\n\n######################################################################\n# Import model\n# ------------\n# Creates tensorflow graph definition from protobuf file.\n\nwith tf_compat_v1.gfile.GFile(model_path, \"rb\") as f:\n    graph_def = tf_compat_v1.GraphDef()\n    graph_def.ParseFromString(f.read())\n    graph = tf.import_graph_def(graph_def, name=\"\")\n    # Call the utility to import the graph definition into default graph.\n    graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n    # Add shapes to the graph.\n    with tf_compat_v1.Session() as sess:\n        graph_def = tf_testing.AddShapesToGraphDef(sess, \"softmax\")\n\n######################################################################\n# Decode image\n# ------------\n# .. note::\n#\n#   tensorflow frontend import doesn't support preprocessing ops like JpegDecode.\n#   JpegDecode is bypassed (just return source node).\n#   Hence we supply decoded frame to TVM instead.\n#\n\nfrom PIL import Image\n\nimage = Image.open(img_path).resize((299, 299))\n\nx = np.array(image)\n\n######################################################################\n# Import the graph to Relay\n# -------------------------\n# Import tensorflow graph definition to relay frontend.\n#\n# Results:\n#   sym: relay expr for given tensorflow protobuf.\n#   params: params converted from tensorflow params (tensor protobuf).\nshape_dict = {\"DecodeJpeg/contents\": x.shape}\ndtype_dict = {\"DecodeJpeg/contents\": \"uint8\"}\nmod, params = relay.frontend.from_tensorflow(graph_def, layout=layout, shape=shape_dict)\n\nprint(\"Tensorflow protobuf imported to relay frontend.\")\n######################################################################\n# Relay Build\n# -----------\n# Compile the graph to llvm target with given input specification.\n#\n# Results:\n#   graph: Final graph after compilation.\n#   params: final params after compilation.\n#   lib: target library which can be deployed on target with TVM runtime.\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target, params=params)\n\n######################################################################\n# Execute the portable graph on TVM\n# ---------------------------------\n# Now we can try deploying the compiled model on target.\n\nfrom tvm.contrib import graph_executor\n\ndtype = \"uint8\"\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n# set inputs\nm.set_input(\"DecodeJpeg/contents\", tvm.nd.array(x.astype(dtype)))\n# execute\nm.run()\n# get outputs\ntvm_output = m.get_output(0, tvm.nd.empty(((1, 1008)), \"float32\"))\n\n######################################################################\n# Process the output\n# ------------------\n# Process the model output to human readable text for InceptionV1.\npredictions = tvm_output.numpy()\npredictions = np.squeeze(predictions)\n\n# Creates node ID --> English string lookup.\nnode_lookup = tf_testing.NodeLookup(label_lookup_path=map_proto_path, uid_lookup_path=label_path)\n\n# Print top 5 predictions from TVM output.\ntop_k = predictions.argsort()[-5:][::-1]\nfor node_id in top_k:\n    human_string = node_lookup.id_to_string(node_id)\n    score = predictions[node_id]\n    print(\"%s (score = %.5f)\" % (human_string, score))\n\n######################################################################\n# Inference on tensorflow\n# -----------------------\n# Run the corresponding model on tensorflow\n\n\ndef create_graph():\n    \"\"\"Creates a graph from saved GraphDef file and returns a saver.\"\"\"\n    # Creates graph from saved graph_def.pb.\n    with tf_compat_v1.gfile.GFile(model_path, \"rb\") as f:\n        graph_def = tf_compat_v1.GraphDef()\n        graph_def.ParseFromString(f.read())\n        graph = tf.import_graph_def(graph_def, name=\"\")\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n\ndef run_inference_on_image(image):\n    \"\"\"Runs inference on an image.\n\n    Parameters\n    ----------\n    image: String\n        Image file name.\n\n    Returns\n    -------\n        Nothing\n    \"\"\"\n    if not tf_compat_v1.gfile.Exists(image):\n        tf.logging.fatal(\"File does not exist %s\", image)\n    image_data = tf_compat_v1.gfile.GFile(image, \"rb\").read()\n\n    # Creates graph from saved GraphDef.\n    create_graph()\n\n    with tf_compat_v1.Session() as sess:\n        softmax_tensor = sess.graph.get_tensor_by_name(\"softmax:0\")\n        predictions = sess.run(softmax_tensor, {\"DecodeJpeg/contents:0\": image_data})\n\n        predictions = np.squeeze(predictions)\n\n        # Creates node ID --> English string lookup.\n        node_lookup = tf_testing.NodeLookup(\n            label_lookup_path=map_proto_path, uid_lookup_path=label_path\n        )\n\n        # Print top 5 predictions from tensorflow.\n        top_k = predictions.argsort()[-5:][::-1]\n        print(\"===== TENSORFLOW RESULTS =======\")\n        for node_id in top_k:\n            human_string = node_lookup.id_to_string(node_id)\n            score = predictions[node_id]\n            print(\"%s (score = %.5f)\" % (human_string, score))\n\n\nrun_inference_on_image(img_path)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/compile_models/from_tflite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile TFLite Models\n=====================\n**Author**: `Zhao Wu <https://github.com/FrozenGene>`_\n\nThis article is an introductory tutorial to deploy TFLite models with Relay.\n\nTo get started, TFLite package needs to be installed as prerequisite.\n\n.. code-block:: bash\n\n    # install tflite\n    pip install tflite==2.1.0 --user\n\n\nor you could generate TFLite package yourself. The steps are the following:\n\n.. code-block:: bash\n\n    # Get the flatc compiler.\n    # Please refer to https://github.com/google/flatbuffers for details\n    # and make sure it is properly installed.\n    flatc --version\n\n    # Get the TFLite schema.\n    wget https://raw.githubusercontent.com/tensorflow/tensorflow/r1.13/tensorflow/lite/schema/schema.fbs\n\n    # Generate TFLite package.\n    flatc --python schema.fbs\n\n    # Add current folder (which contains generated tflite module) to PYTHONPATH.\n    export PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}$(pwd)\n\n\nNow please check if TFLite package is installed successfully, ``python -c \"import tflite\"``\n\nBelow you can find an example on how to compile TFLite model using TVM.\n\"\"\"\n\n######################################################################\n# Utils for downloading and extracting zip files\n# ----------------------------------------------\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\n\ndef extract(path):\n    import tarfile\n\n    if path.endswith(\"tgz\") or path.endswith(\"gz\"):\n        dir_path = os.path.dirname(path)\n        tar = tarfile.open(path)\n        tar.extractall(path=dir_path)\n        tar.close()\n    else:\n        raise RuntimeError(\"Could not decompress the file: \" + path)\n\n\n######################################################################\n# Load pretrained TFLite model\n# ----------------------------\n# Load mobilenet V1 TFLite model provided by Google\nfrom tvm.contrib.download import download_testdata\n\nmodel_url = \"http://download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz\"\n\n# Download model tar file and extract it to get mobilenet_v1_1.0_224.tflite\nmodel_path = download_testdata(model_url, \"mobilenet_v1_1.0_224.tgz\", module=[\"tf\", \"official\"])\nmodel_dir = os.path.dirname(model_path)\nextract(model_path)\n\n# Now we can open mobilenet_v1_1.0_224.tflite\ntflite_model_file = os.path.join(model_dir, \"mobilenet_v1_1.0_224.tflite\")\ntflite_model_buf = open(tflite_model_file, \"rb\").read()\n\n# Get TFLite model from buffer\ntry:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n######################################################################\n# Load a test image\n# -----------------\n# A single cat dominates the examples!\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nimage_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimage_path = download_testdata(image_url, \"cat.png\", module=\"data\")\nresized_image = Image.open(image_path).resize((224, 224))\nplt.imshow(resized_image)\nplt.show()\nimage_data = np.asarray(resized_image).astype(\"float32\")\n\n# Add a dimension to the image so that we have NHWC format layout\nimage_data = np.expand_dims(image_data, axis=0)\n\n# Preprocess image as described here:\n# https://github.com/tensorflow/models/blob/edb6ed22a801665946c63d650ab9a0b23d98e1b1/research/slim/preprocessing/inception_preprocessing.py#L243\nimage_data[:, :, :, 0] = 2.0 / 255.0 * image_data[:, :, :, 0] - 1\nimage_data[:, :, :, 1] = 2.0 / 255.0 * image_data[:, :, :, 1] - 1\nimage_data[:, :, :, 2] = 2.0 / 255.0 * image_data[:, :, :, 2] - 1\nprint(\"input\", image_data.shape)\n\n######################################################################\n# Compile the model with relay\n# ----------------------------\n\n# TFLite input tensor name, shape and type\ninput_tensor = \"input\"\ninput_shape = (1, 224, 224, 3)\ninput_dtype = \"float32\"\n\n# Parse TFLite model and convert it to a Relay module\nfrom tvm import relay, transform\n\nmod, params = relay.frontend.from_tflite(\n    tflite_model, shape_dict={input_tensor: input_shape}, dtype_dict={input_tensor: input_dtype}\n)\n\n# Build the module against to x86 CPU\ntarget = \"llvm\"\nwith transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target, params=params)\n\n######################################################################\n# Execute on TVM\n# --------------\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import graph_executor as runtime\n\n# Create a runtime executor module\nmodule = runtime.GraphModule(lib[\"default\"](tvm.cpu()))\n\n# Feed input data\nmodule.set_input(input_tensor, tvm.nd.array(image_data))\n\n# Run\nmodule.run()\n\n# Get output\ntvm_output = module.get_output(0).numpy()\n\n######################################################################\n# Display results\n# ---------------\n\n# Load label file\nlabel_file_url = \"\".join(\n    [\n        \"https://raw.githubusercontent.com/\",\n        \"tensorflow/tensorflow/master/tensorflow/lite/java/demo/\",\n        \"app/src/main/assets/\",\n        \"labels_mobilenet_quant_v1_224.txt\",\n    ]\n)\nlabel_file = \"labels_mobilenet_quant_v1_224.txt\"\nlabel_path = download_testdata(label_file_url, label_file, module=\"data\")\n\n# List of 1001 classes\nwith open(label_path) as f:\n    labels = f.readlines()\n\n# Convert result to 1D data\npredictions = np.squeeze(tvm_output)\n\n# Get top 1 prediction\nprediction = np.argmax(predictions)\n\n# Convert id to class name and show the result\nprint(\"The image prediction result is: id \" + str(prediction) + \" name: \" + labels[prediction])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_model_on_android.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\n.. _tutorial-deploy-model-on-android:\n\nDeploy the Pretrained Model on Android\n=======================================\n**Author**: `Tomohiro Kato <https://tkat0.github.io/>`_\n\nThis is an example of using Relay to compile a keras model and deploy it on Android device.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\nimport numpy as np\nfrom PIL import Image\nimport keras\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm import rpc\nfrom tvm.contrib import utils, ndk, graph_executor as runtime\nfrom tvm.contrib.download import download_testdata\n\n\n######################################################################\n# Setup Environment\n# -----------------\n# Since there are many required packages for Android, it is recommended to use the official Docker Image.\n#\n# First, to build and run Docker Image, we can run the following command.\n#\n# .. code-block:: bash\n#\n#   git clone --recursive https://github.com/apache/tvm tvm\n#   cd tvm\n#   docker build -t tvm.demo_android -f docker/Dockerfile.demo_android ./docker\n#   docker run --pid=host -h tvm -v $PWD:/workspace \\\n#          -w /workspace -p 9190:9190 --name tvm -it tvm.demo_android bash\n#\n# You are now inside the container. The cloned TVM directory is mounted on /workspace.\n# At this time, mount the 9190 port used by RPC described later.\n#\n# .. note::\n#\n#   Please execute the following steps in the container.\n#   We can execute :code:`docker exec -it tvm bash` to open a new terminal in the container.\n#\n# Next we build the TVM.\n#\n# .. code-block:: bash\n#\n#   mkdir build\n#   cd build\n#   cmake -DUSE_LLVM=llvm-config-8 \\\n#         -DUSE_RPC=ON \\\n#         -DUSE_SORT=ON \\\n#         -DUSE_VULKAN=ON \\\n#         -DUSE_GRAPH_EXECUTOR=ON \\\n#         ..\n#   make -j10\n#\n# After building TVM successfully, Please set PYTHONPATH.\n#\n# .. code-block:: bash\n#\n#   echo 'export PYTHONPATH=/workspace/python:/workspace/vta/python:${PYTHONPATH}' >> ~/.bashrc\n#   source ~/.bashrc\n\n#################################################################\n# Start RPC Tracker\n# -----------------\n# TVM uses RPC session to communicate with Android device.\n#\n# To start an RPC tracker, run this command in the container. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python3 -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n\n#################################################################\n# Register Android device to RPC Tracker\n# --------------------------------------\n# Now we can register our Android device to the tracker.\n#\n# Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to\n# install TVM RPC APK on the android device.\n#\n# Here is an example of config.mk. I enabled OpenCL and Vulkan.\n#\n#\n# .. code-block:: bash\n#\n#   APP_ABI = arm64-v8a\n#\n#   APP_PLATFORM = android-24\n#\n#   # whether enable OpenCL during compile\n#   USE_OPENCL = 1\n#\n#   # whether to enable Vulkan during compile\n#   USE_VULKAN = 1\n#\n#   ifeq ($(USE_VULKAN), 1)\n#     # Statically linking vulkan requires API Level 24 or higher\n#     APP_PLATFORM = android-24\n#   endif\n#\n#   # the additional include headers you want to add, e.g., SDK_PATH/adrenosdk/Development/Inc\n#   ADD_C_INCLUDES += /work/adrenosdk-linux-5_0/Development/Inc\n#   # downloaded from https://github.com/KhronosGroup/OpenCL-Headers\n#   ADD_C_INCLUDES += /usr/local/OpenCL-Headers/\n#\n#   # the additional link libs you want to add, e.g., ANDROID_LIB_PATH/libOpenCL.so\n#   ADD_LDLIBS = /workspace/pull-from-android-device/libOpenCL.so\n#\n# .. note::\n#\n#   At this time, don't forget to `create a standalone toolchain <https://github.com/apache/tvm/tree/main/apps/android_rpc#architecture-and-android-standalone-toolchain>`_ .\n#\n#   for example\n#\n#   .. code-block:: bash\n#\n#     $ANDROID_NDK_HOME/build/tools/make-standalone-toolchain.sh \\\n#        --platform=android-24 --use-llvm --arch=arm64 --install-dir=/opt/android-toolchain-arm64\n#     export TVM_NDK_CC=/opt/android-toolchain-arm64/bin/aarch64-linux-android-g++\n#\n# Next, start the Android application and enter the IP address and port of RPC Tracker.\n# Then you have already registered your device.\n#\n# After registering devices, we can confirm it by querying rpc_tracker\n#\n# .. code-block:: bash\n#\n#   python3 -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n#\n# For example, if we have 1 Android device.\n# the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    android      1      1     0\n#    ----------------------------------\n#\n# To confirm that you can communicate with Android, we can run following test script.\n# If you use OpenCL and Vulkan, please set :code:`test_opencl` and :code:`test_vulkan` in the script.\n#\n# .. code-block:: bash\n#\n#   export TVM_TRACKER_HOST=0.0.0.0\n#   export TVM_TRACKER_PORT=9190\n#\n# .. code-block:: bash\n#\n#   cd /workspace/apps/android_rpc\n#   python3 tests/android_rpc_test.py\n#\n\n######################################################################\n# Load pretrained keras model\n# ---------------------------\n# We load a pretrained MobileNetV2(alpha=0.5) classification model provided by keras.\nkeras.backend.clear_session()  # Destroys the current TF graph and creates a new one.\nweights_url = \"\".join(\n    [\n        \"https://github.com/JonathanCMitchell/\",\n        \"mobilenet_v2_keras/releases/download/v1.1/\",\n        \"mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5\",\n    ]\n)\nweights_file = \"mobilenet_v2_weights.h5\"\nweights_path = download_testdata(weights_url, weights_file, module=\"keras\")\nkeras_mobilenet_v2 = MobileNetV2(\n    alpha=0.5, include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000\n)\nkeras_mobilenet_v2.load_weights(weights_path)\n\n######################################################################\n# In order to test our model, here we download an image of cat and\n# transform its format.\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_name = \"cat.png\"\nimg_path = download_testdata(img_url, img_name, module=\"data\")\nimage = Image.open(img_path).resize((224, 224))\ndtype = \"float32\"\n\n\ndef transform_image(image):\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image\n\n\nx = transform_image(image)\n\n######################################################################\n# synset is used to transform the label from number of ImageNet class to\n# the word human can understand.\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\n\n\n######################################################################\n# Compile the model with relay\n# ----------------------------\n# If we run the example on our x86 server for demonstration, we can simply\n# set it as :code:`llvm`. If running it on the Android device, we need to\n# specify its instruction set. Set :code:`local_demo` to False if you want\n# to run this tutorial with a real device.\n\nlocal_demo = True\n\n# by default on CPU target will execute.\n# select 'cpu', 'opencl' and 'vulkan'\ntest_target = \"cpu\"\n\n# Change target configuration.\n# Run `adb shell cat /proc/cpuinfo` to find the arch.\narch = \"arm64\"\ntarget = tvm.target.Target(\"llvm -mtriple=%s-linux-android\" % arch)\n\nif local_demo:\n    target = tvm.target.Target(\"llvm\")\nelif test_target == \"opencl\":\n    target = tvm.target.Target(\"opencl\", host=target)\nelif test_target == \"vulkan\":\n    target = tvm.target.Target(\"vulkan\", host=target)\n\ninput_name = \"input_1\"\nshape_dict = {input_name: x.shape}\nmod, params = relay.frontend.from_keras(keras_mobilenet_v2, shape_dict)\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target=target, params=params)\n\n# After `relay.build`, you will get three return values: graph,\n# library and the new parameter, since we do some optimization that will\n# change the parameters but keep the result of model as the same.\n\n# Save the library at local temporary directory.\ntmp = utils.tempdir()\nlib_fname = tmp.relpath(\"net.so\")\nfcompile = ndk.create_shared if not local_demo else None\nlib.export_library(lib_fname, fcompile)\n\n######################################################################\n# Deploy the Model Remotely by RPC\n# --------------------------------\n# With RPC, you can deploy the model remotely from your host machine\n# to the remote android device.\n\ntracker_host = os.environ.get(\"TVM_TRACKER_HOST\", \"127.0.0.1\")\ntracker_port = int(os.environ.get(\"TVM_TRACKER_PORT\", 9190))\nkey = \"android\"\n\nif local_demo:\n    remote = rpc.LocalSession()\nelse:\n    tracker = rpc.connect_tracker(tracker_host, tracker_port)\n    # When running a heavy model, we should increase the `session_timeout`\n    remote = tracker.request(key, priority=0, session_timeout=60)\n\nif local_demo:\n    dev = remote.cpu(0)\nelif test_target == \"opencl\":\n    dev = remote.cl(0)\nelif test_target == \"vulkan\":\n    dev = remote.vulkan(0)\nelse:\n    dev = remote.cpu(0)\n\n# upload the library to remote device and load it\nremote.upload(lib_fname)\nrlib = remote.load_module(\"net.so\")\n\n# create the remote runtime module\nmodule = runtime.GraphModule(rlib[\"default\"](dev))\n\n######################################################################\n# Execute on TVM\n# --------------\n\n# set input data\nmodule.set_input(input_name, tvm.nd.array(x.astype(dtype)))\n# run\nmodule.run()\n# get output\nout = module.get_output(0)\n\n# get top1 result\ntop1 = np.argmax(out.numpy())\nprint(\"TVM prediction top-1: {}\".format(synset[top1]))\n\nprint(\"Evaluate inference time cost...\")\nprint(module.benchmark(dev, number=1, repeat=10))\n\n######################################################################\n# Sample Output\n# -------------\n# The following is the result of 'cpu', 'opencl' and 'vulkan' using Adreno 530 on Snapdragon 820\n#\n# Although we can run on a GPU, it is slower than CPU.\n# To speed up, we need to write and optimize the schedule according to the GPU architecture.\n#\n# .. code-block:: bash\n#\n#    # cpu\n#    TVM prediction top-1: tiger cat\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 37.92 ms (19.67 ms)\n#\n#    # opencl\n#    TVM prediction top-1: tiger cat\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 419.83 ms (7.49 ms)\n#\n#    # vulkan\n#    TVM prediction top-1: tiger cat\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 465.80 ms (4.52 ms)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_model_on_nano.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-deploy-model-on-nano:\n\nDeploy the Pretrained Model on Jetson Nano\n===========================================\n**Author**: `BBuf <https://github.com/BBuf>`_\n\nThis is an example of using Relay to compile a ResNet model and deploy\nit on Jetson Nano.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm import rpc\nfrom tvm.contrib import utils, graph_executor as runtime\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# .. _build-tvm-runtime-on-jetson-nano:\n#\n# Build TVM Runtime on Jetson Nano\n# --------------------------------\n#\n# The first step is to build the TVM runtime on the remote device.\n#\n# .. note::\n#\n#   All instructions in both this section and next section should be\n#   executed on the target device, e.g. Jetson Nano. And we assume it\n#   has Linux running.\n#\n# Since we do compilation on local machine, the remote device is only used\n# for running the generated code. We only need to build tvm runtime on\n# the remote device.\n#\n# .. code-block:: bash\n#\n#   git clone --recursive https://github.com/apache/tvm tvm\n#   cd tvm\n#   mkdir build\n#   cp cmake/config.cmake build\n#   cd build\n#   cmake ..\n#   make runtime -j4\n# .. note::\n#\n#   If we want to use Jetson Nano's GPU for inference,\n#   we need to enable the CUDA option in `config.cmake`,\n#   that is, `set(USE_CUDA ON)`\n#\n# After building runtime successfully, we need to set environment varibles\n# in :code:`~/.bashrc` file. We can edit :code:`~/.bashrc`\n# using :code:`vi ~/.bashrc` and add the line below (Assuming your TVM\n# directory is in :code:`~/tvm`):\n#\n# .. code-block:: bash\n#\n#   export PYTHONPATH=$PYTHONPATH:~/tvm/python\n#\n# To update the environment variables, execute :code:`source ~/.bashrc`.\n\n######################################################################\n# Set Up RPC Server on Device\n# ---------------------------\n# To start an RPC server, run the following command on your remote device\n# (Which is Jetson Nano in our example).\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --host 0.0.0.0 --port=9091\n#\n# If you see the line below, it means the RPC server started\n# successfully on your device.\n#\n#    .. code-block:: bash\n#\n#      INFO:RPCServer:bind to 0.0.0.0:9091\n#\n\n######################################################################\n# Prepare the Pre-trained Model\n# -----------------------------\n# Back to the host machine, which should have a full TVM installed (with LLVM).\n#\n# We will use pre-trained model from\n# `MXNet Gluon model zoo <https://mxnet.apache.org/api/python/gluon/model_zoo.html>`_.\n# You can found more details about this part at tutorial :ref:`tutorial-from-mxnet`.\n\nfrom mxnet.gluon.model_zoo.vision import get_model\nfrom PIL import Image\nimport numpy as np\n\n# one line to get the model\nblock = get_model(\"resnet18_v1\", pretrained=True)\n\n######################################################################\n# In order to test our model, here we download an image of cat and\n# transform its format.\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_name = \"cat.png\"\nimg_path = download_testdata(img_url, img_name, module=\"data\")\nimage = Image.open(img_path).resize((224, 224))\n\n\ndef transform_image(image):\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image\n\n\nx = transform_image(image)\n\n######################################################################\n# synset is used to transform the label from number of ImageNet class to\n# the word human can understand.\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\n\n######################################################################\n# Now we would like to port the Gluon model to a portable computational graph.\n# It's as easy as several lines.\n\n# We support MXNet static graph(symbol) and HybridBlock in mxnet.gluon\nshape_dict = {\"data\": x.shape}\nmod, params = relay.frontend.from_mxnet(block, shape_dict)\n# we want a probability so add a softmax operator\nfunc = mod[\"main\"]\nfunc = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs)\n\n######################################################################\n# Here are some basic data workload configurations.\nbatch_size = 1\nnum_classes = 1000\nimage_shape = (3, 224, 224)\ndata_shape = (batch_size,) + image_shape\n\n######################################################################\n# Compile The Graph\n# -----------------\n# To compile the graph, we call the :py:func:`relay.build` function\n# with the graph configuration and parameters. However, You cannot to\n# deploy a x86 program on a device with ARM instruction set. It means\n# Relay also needs to know the compilation option of target device,\n# apart from arguments :code:`net` and :code:`params` to specify the\n# deep learning workload. Actually, the option matters, different option\n# will lead to very different performance.\n\n######################################################################\n# If we run the example on our x86 server for demonstration, we can simply\n# set it as :code:`llvm`. If running it on the Jetson Nano, we need to\n# set it as :code:`nvidia/jetson-nano`. Set :code:`local_demo` to False\n# if you want to run this tutorial with a real device.\n\nlocal_demo = True\n\nif local_demo:\n    target = tvm.target.Target(\"llvm\")\nelse:\n    target = tvm.target.Target(\"nvidia/jetson-nano\")\n    assert target.kind.name == \"cuda\"\n    assert target.attrs[\"arch\"] == \"sm_53\"\n    assert target.attrs[\"shared_memory_per_block\"] == 49152\n    assert target.attrs[\"max_threads_per_block\"] == 1024\n    assert target.attrs[\"thread_warp_size\"] == 32\n    assert target.attrs[\"registers_per_block\"] == 32768\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(func, target, params=params)\n\n# After `relay.build`, you will get three return values: graph,\n# library and the new parameter, since we do some optimization that will\n# change the parameters but keep the result of model as the same.\n\n# Save the library at local temporary directory.\ntmp = utils.tempdir()\nlib_fname = tmp.relpath(\"net.tar\")\nlib.export_library(lib_fname)\n\n######################################################################\n# Deploy the Model Remotely by RPC\n# --------------------------------\n# With RPC, you can deploy the model remotely from your host machine\n# to the remote device.\n\n# obtain an RPC session from remote device.\nif local_demo:\n    remote = rpc.LocalSession()\nelse:\n    # The following is my environment, change this to the IP address of your target device\n    host = \"192.168.1.11\"\n    port = 9091\n    remote = rpc.connect(host, port)\n\n# upload the library to remote device and load it\nremote.upload(lib_fname)\nrlib = remote.load_module(\"net.tar\")\n\n# create the remote runtime module\nif local_demo:\n    dev = remote.cpu(0)\nelse:\n    dev = remote.cuda(0)\n\nmodule = runtime.GraphModule(rlib[\"default\"](dev))\n# set input data\nmodule.set_input(\"data\", tvm.nd.array(x.astype(\"float32\")))\n# run\nmodule.run()\n# get output\nout = module.get_output(0)\n# get top1 result\ntop1 = np.argmax(out.numpy())\nprint(\"TVM prediction top-1: {}\".format(synset[top1]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_model_on_rasp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-deploy-model-on-rasp:\n\nDeploy the Pretrained Model on Raspberry Pi\n===========================================\n**Author**: `Ziheng Jiang <https://ziheng.org/>`_, \\\n            `Hiroyuki Makino <https://makihiro.github.io/>`_\n\nThis is an example of using Relay to compile a ResNet model and deploy\nit on Raspberry Pi.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nfrom tvm import rpc\nfrom tvm.contrib import utils, graph_executor as runtime\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# .. _build-tvm-runtime-on-device:\n#\n# Build TVM Runtime on Device\n# ---------------------------\n#\n# The first step is to build the TVM runtime on the remote device.\n#\n# .. note::\n#\n#   All instructions in both this section and next section should be\n#   executed on the target device, e.g. Raspberry Pi. And we assume it\n#   has Linux running.\n#\n# Since we do compilation on local machine, the remote device is only used\n# for running the generated code. We only need to build tvm runtime on\n# the remote device.\n#\n# .. code-block:: bash\n#\n#   git clone --recursive https://github.com/apache/tvm tvm\n#   cd tvm\n#   mkdir build\n#   cp cmake/config.cmake build\n#   cd build\n#   cmake ..\n#   make runtime -j4\n#\n# After building runtime successfully, we need to set environment varibles\n# in :code:`~/.bashrc` file. We can edit :code:`~/.bashrc`\n# using :code:`vi ~/.bashrc` and add the line below (Assuming your TVM\n# directory is in :code:`~/tvm`):\n#\n# .. code-block:: bash\n#\n#   export PYTHONPATH=$PYTHONPATH:~/tvm/python\n#\n# To update the environment variables, execute :code:`source ~/.bashrc`.\n\n######################################################################\n# Set Up RPC Server on Device\n# ---------------------------\n# To start an RPC server, run the following command on your remote device\n# (Which is Raspberry Pi in our example).\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --host 0.0.0.0 --port=9090\n#\n# If you see the line below, it means the RPC server started\n# successfully on your device.\n#\n#    .. code-block:: bash\n#\n#      INFO:root:RPCServer: bind to 0.0.0.0:9090\n#\n\n######################################################################\n# Prepare the Pre-trained Model\n# -----------------------------\n# Back to the host machine, which should have a full TVM installed (with LLVM).\n#\n# We will use pre-trained model from\n# `MXNet Gluon model zoo <https://mxnet.apache.org/api/python/gluon/model_zoo.html>`_.\n# You can found more details about this part at tutorial :ref:`tutorial-from-mxnet`.\n\nfrom mxnet.gluon.model_zoo.vision import get_model\nfrom PIL import Image\nimport numpy as np\n\n# one line to get the model\nblock = get_model(\"resnet18_v1\", pretrained=True)\n\n######################################################################\n# In order to test our model, here we download an image of cat and\n# transform its format.\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_name = \"cat.png\"\nimg_path = download_testdata(img_url, img_name, module=\"data\")\nimage = Image.open(img_path).resize((224, 224))\n\n\ndef transform_image(image):\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image\n\n\nx = transform_image(image)\n\n######################################################################\n# synset is used to transform the label from number of ImageNet class to\n# the word human can understand.\nsynset_url = \"\".join(\n    [\n        \"https://gist.githubusercontent.com/zhreshold/\",\n        \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n        \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n        \"imagenet1000_clsid_to_human.txt\",\n    ]\n)\nsynset_name = \"imagenet1000_clsid_to_human.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synset = eval(f.read())\n\n######################################################################\n# Now we would like to port the Gluon model to a portable computational graph.\n# It's as easy as several lines.\n\n# We support MXNet static graph(symbol) and HybridBlock in mxnet.gluon\nshape_dict = {\"data\": x.shape}\nmod, params = relay.frontend.from_mxnet(block, shape_dict)\n# we want a probability so add a softmax operator\nfunc = mod[\"main\"]\nfunc = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs)\n\n######################################################################\n# Here are some basic data workload configurations.\nbatch_size = 1\nnum_classes = 1000\nimage_shape = (3, 224, 224)\ndata_shape = (batch_size,) + image_shape\n\n######################################################################\n# Compile The Graph\n# -----------------\n# To compile the graph, we call the :py:func:`relay.build` function\n# with the graph configuration and parameters. However, You cannot to\n# deploy a x86 program on a device with ARM instruction set. It means\n# Relay also needs to know the compilation option of target device,\n# apart from arguments :code:`net` and :code:`params` to specify the\n# deep learning workload. Actually, the option matters, different option\n# will lead to very different performance.\n\n######################################################################\n# If we run the example on our x86 server for demonstration, we can simply\n# set it as :code:`llvm`. If running it on the Raspberry Pi, we need to\n# specify its instruction set. Set :code:`local_demo` to False if you want\n# to run this tutorial with a real device.\n\nlocal_demo = True\n\nif local_demo:\n    target = tvm.target.Target(\"llvm\")\nelse:\n    target = tvm.target.arm_cpu(\"rasp3b\")\n    # The above line is a simple form of\n    # target = tvm.target.Target('llvm -device=arm_cpu -model=bcm2837 -mtriple=armv7l-linux-gnueabihf -mattr=+neon')\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(func, target, params=params)\n\n# After `relay.build`, you will get three return values: graph,\n# library and the new parameter, since we do some optimization that will\n# change the parameters but keep the result of model as the same.\n\n# Save the library at local temporary directory.\ntmp = utils.tempdir()\nlib_fname = tmp.relpath(\"net.tar\")\nlib.export_library(lib_fname)\n\n######################################################################\n# Deploy the Model Remotely by RPC\n# --------------------------------\n# With RPC, you can deploy the model remotely from your host machine\n# to the remote device.\n\n# obtain an RPC session from remote device.\nif local_demo:\n    remote = rpc.LocalSession()\nelse:\n    # The following is my environment, change this to the IP address of your target device\n    host = \"10.77.1.162\"\n    port = 9090\n    remote = rpc.connect(host, port)\n\n# upload the library to remote device and load it\nremote.upload(lib_fname)\nrlib = remote.load_module(\"net.tar\")\n\n# create the remote runtime module\ndev = remote.cpu(0)\nmodule = runtime.GraphModule(rlib[\"default\"](dev))\n# set input data\nmodule.set_input(\"data\", tvm.nd.array(x.astype(\"float32\")))\n# run\nmodule.run()\n# get output\nout = module.get_output(0)\n# get top1 result\ntop1 = np.argmax(out.numpy())\nprint(\"TVM prediction top-1: {}\".format(synset[top1]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_object_detection_pytorch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile PyTorch Object Detection Models\n=======================================\nThis article is an introductory tutorial to deploy PyTorch object\ndetection models with Relay VM.\n\nFor us to begin with, PyTorch should be installed.\nTorchVision is also required since we will be using it as our model zoo.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n    pip install torch==1.7.0\n    pip install torchvision==0.8.1\n\nor please refer to official site\nhttps://pytorch.org/get-started/locally/\n\nPyTorch versions should be backwards compatible but should be used\nwith the proper TorchVision version.\n\nCurrently, TVM supports PyTorch 1.7 and 1.4. Other versions may\nbe unstable.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import relay\nfrom tvm import relay\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.contrib.download import download_testdata\n\nimport numpy as np\nimport cv2\n\n# PyTorch imports\nimport torch\nimport torchvision\n\n######################################################################\n# Load pre-trained maskrcnn from torchvision and do tracing\n# ---------------------------------------------------------\nin_size = 300\n\ninput_shape = (1, 3, in_size, in_size)\n\n\ndef do_trace(model, inp):\n    model_trace = torch.jit.trace(model, inp)\n    model_trace.eval()\n    return model_trace\n\n\ndef dict_to_tuple(out_dict):\n    if \"masks\" in out_dict.keys():\n        return out_dict[\"boxes\"], out_dict[\"scores\"], out_dict[\"labels\"], out_dict[\"masks\"]\n    return out_dict[\"boxes\"], out_dict[\"scores\"], out_dict[\"labels\"]\n\n\nclass TraceWrapper(torch.nn.Module):\n    def __init__(self, model):\n        super().__init__()\n        self.model = model\n\n    def forward(self, inp):\n        out = self.model(inp)\n        return dict_to_tuple(out[0])\n\n\nmodel_func = torchvision.models.detection.maskrcnn_resnet50_fpn\nmodel = TraceWrapper(model_func(pretrained=True))\n\nmodel.eval()\ninp = torch.Tensor(np.random.uniform(0.0, 250.0, size=(1, 3, in_size, in_size)))\n\nwith torch.no_grad():\n    out = model(inp)\n    script_module = do_trace(model, inp)\n\n######################################################################\n# Download a test image and pre-process\n# -------------------------------------\nimg_url = (\n    \"https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/detection/street_small.jpg\"\n)\nimg_path = download_testdata(img_url, \"test_street_small.jpg\", module=\"data\")\n\nimg = cv2.imread(img_path).astype(\"float32\")\nimg = cv2.resize(img, (in_size, in_size))\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nimg = np.transpose(img / 255.0, [2, 0, 1])\nimg = np.expand_dims(img, axis=0)\n\n######################################################################\n# Import the graph to Relay\n# -------------------------\ninput_name = \"input0\"\nshape_list = [(input_name, input_shape)]\nmod, params = relay.frontend.from_pytorch(script_module, shape_list)\n\n######################################################################\n# Compile with Relay VM\n# ---------------------\n# Note: Currently only CPU target is supported. For x86 target, it is\n# highly recommended to build TVM with Intel MKL and Intel OpenMP to get\n# best performance, due to the existence of large dense operator in\n# torchvision rcnn models.\n\n# Add \"-libs=mkl\" to get best performance on x86 target.\n# For x86 machine supports AVX512, the complete target is\n# \"llvm -mcpu=skylake-avx512 -libs=mkl\"\ntarget = \"llvm\"\n\nwith tvm.transform.PassContext(opt_level=3, disabled_pass=[\"FoldScaleAxis\"]):\n    vm_exec = relay.vm.compile(mod, target=target, params=params)\n\n######################################################################\n# Inference with Relay VM\n# -----------------------\ndev = tvm.cpu()\nvm = VirtualMachine(vm_exec, dev)\nvm.set_input(\"main\", **{input_name: img})\ntvm_res = vm.run()\n\n######################################################################\n# Get boxes with score larger than 0.9\n# ------------------------------------\nscore_threshold = 0.9\nboxes = tvm_res[0].numpy().tolist()\nvalid_boxes = []\nfor i, score in enumerate(tvm_res[1].numpy().tolist()):\n    if score > score_threshold:\n        valid_boxes.append(boxes[i])\n    else:\n        break\n\nprint(\"Get {} valid boxes\".format(len(valid_boxes)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_prequantized.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy a Framework-prequantized Model with TVM\n==============================================\n**Author**: `Masahiro Masuda <https://github.com/masahi>`_\n\nThis is a tutorial on loading models quantized by deep learning frameworks into TVM.\nPre-quantized model import is one of the quantization support we have in TVM. More details on\nthe quantization story in TVM can be found\n`here <https://discuss.tvm.apache.org/t/quantization-story/3920>`_.\n\nHere, we demonstrate how to load and run models quantized by PyTorch, MXNet, and TFLite.\nOnce loaded, we can run compiled, quantized models on any hardware TVM supports.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n#################################################################################\n# First, necessary imports\nfrom PIL import Image\n\nimport numpy as np\n\nimport torch\nfrom torchvision.models.quantization import mobilenet as qmobilenet\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\n\n\n#################################################################################\n# Helper functions to run the demo\ndef get_transform():\n    import torchvision.transforms as transforms\n\n    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n    return transforms.Compose(\n        [\n            transforms.Resize(256),\n            transforms.CenterCrop(224),\n            transforms.ToTensor(),\n            normalize,\n        ]\n    )\n\n\ndef get_real_image(im_height, im_width):\n    img_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\n    img_path = download_testdata(img_url, \"cat.png\", module=\"data\")\n    return Image.open(img_path).resize((im_height, im_width))\n\n\ndef get_imagenet_input():\n    im = get_real_image(224, 224)\n    preprocess = get_transform()\n    pt_tensor = preprocess(im)\n    return np.expand_dims(pt_tensor.numpy(), 0)\n\n\ndef get_synset():\n    synset_url = \"\".join(\n        [\n            \"https://gist.githubusercontent.com/zhreshold/\",\n            \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n            \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n            \"imagenet1000_clsid_to_human.txt\",\n        ]\n    )\n    synset_name = \"imagenet1000_clsid_to_human.txt\"\n    synset_path = download_testdata(synset_url, synset_name, module=\"data\")\n    with open(synset_path) as f:\n        return eval(f.read())\n\n\ndef run_tvm_model(mod, params, input_name, inp, target=\"llvm\"):\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, params=params)\n\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](tvm.device(target, 0)))\n\n    runtime.set_input(input_name, inp)\n    runtime.run()\n    return runtime.get_output(0).numpy(), runtime\n\n\n#################################################################################\n# A mapping from label to class name, to verify that the outputs from models below\n# are reasonable\nsynset = get_synset()\n\n#################################################################################\n# Everyone's favorite cat image for demonstration\ninp = get_imagenet_input()\n\n################################################################################\n# Deploy a quantized PyTorch Model\n# --------------------------------\n# First, we demonstrate how to load deep learning models quantized by PyTorch,\n# using our PyTorch frontend.\n#\n# Please refer to the PyTorch static quantization tutorial below to learn about\n# their quantization workflow.\n# https://pytorch.org/tutorials/advanced/static_quantization_tutorial.html\n#\n# We use this function to quantize PyTorch models.\n# In short, this function takes a floating point model and converts it to uint8.\n# The model is per-channel quantized.\n\n\ndef quantize_model(model, inp):\n    model.fuse_model()\n    model.qconfig = torch.quantization.get_default_qconfig(\"fbgemm\")\n    torch.quantization.prepare(model, inplace=True)\n    # Dummy calibration\n    model(inp)\n    torch.quantization.convert(model, inplace=True)\n\n\n##############################################################################\n# Load quantization-ready, pretrained Mobilenet v2 model from torchvision\n# -----------------------------------------------------------------------\n# We choose mobilenet v2 because this model was trained with quantization aware\n# training. Other models require a full post training calibration.\nqmodel = qmobilenet.mobilenet_v2(pretrained=True).eval()\n\n##############################################################################\n# Quantize, trace and run the PyTorch Mobilenet v2 model\n# ------------------------------------------------------\n# The details are out of scope for this tutorial. Please refer to the tutorials\n# on the PyTorch website to learn about quantization and jit.\npt_inp = torch.from_numpy(inp)\nquantize_model(qmodel, pt_inp)\nscript_module = torch.jit.trace(qmodel, pt_inp).eval()\n\nwith torch.no_grad():\n    pt_result = script_module(pt_inp).numpy()\n\n##############################################################################\n# Convert quantized Mobilenet v2 to Relay-QNN using the PyTorch frontend\n# ----------------------------------------------------------------------\n# The PyTorch frontend has support for converting a quantized PyTorch model to\n# an equivalent Relay module enriched with quantization-aware operators.\n# We call this representation Relay QNN dialect.\n#\n# You can print the output from the frontend to see how quantized models are\n# represented.\n#\n# You would see operators specific to quantization such as\n# qnn.quantize, qnn.dequantize, qnn.requantize, and qnn.conv2d etc.\ninput_name = \"input\"  # the input name can be be arbitrary for PyTorch frontend.\ninput_shapes = [(input_name, (1, 3, 224, 224))]\nmod, params = relay.frontend.from_pytorch(script_module, input_shapes)\n# print(mod) # comment in to see the QNN IR dump\n\n##############################################################################\n# Compile and run the Relay module\n# --------------------------------\n# Once we obtained the quantized Relay module, the rest of the workflow\n# is the same as running floating point models. Please refer to other\n# tutorials for more details.\n#\n# Under the hood, quantization specific operators are lowered to a sequence of\n# standard Relay operators before compilation.\ntarget = \"llvm\"\ntvm_result, rt_mod = run_tvm_model(mod, params, input_name, inp, target=target)\n\n##########################################################################\n# Compare the output labels\n# -------------------------\n# We should see identical labels printed.\npt_top3_labels = np.argsort(pt_result[0])[::-1][:3]\ntvm_top3_labels = np.argsort(tvm_result[0])[::-1][:3]\n\nprint(\"PyTorch top3 labels:\", [synset[label] for label in pt_top3_labels])\nprint(\"TVM top3 labels:\", [synset[label] for label in tvm_top3_labels])\n\n###########################################################################################\n# However, due to the difference in numerics, in general the raw floating point\n# outputs are not expected to be identical. Here, we print how many floating point\n# output values are identical out of 1000 outputs from mobilenet v2.\nprint(\"%d in 1000 raw floating outputs identical.\" % np.sum(tvm_result[0] == pt_result[0]))\n\n##########################################################################\n# Measure performance\n# -------------------------\n# Here we give an example of how to measure performance of TVM compiled models.\nn_repeat = 100  # should be bigger to make the measurement more accurate\ndev = tvm.cpu(0)\nprint(rt_mod.benchmark(dev, number=1, repeat=n_repeat))\n\n######################################################################\n# .. note::\n#\n#   We recommend this method for the following reasons:\n#\n#    * Measurements are done in C++, so there is no Python overhead\n#    * It includes several warm up runs\n#    * The same method can be used to profile on remote devices (android etc.).\n\n\n######################################################################\n# .. note::\n#\n#   Unless the hardware has special support for fast 8 bit instructions, quantized models are\n#   not expected to be any faster than FP32 models. Without fast 8 bit instructions, TVM does\n#   quantized convolution in 16 bit, even if the model itself is 8 bit.\n#\n#   For x86, the best performance can be achieved on CPUs with AVX512 instructions set.\n#   In this case, TVM utilizes the fastest available 8 bit instructions for the given target.\n#   This includes support for the VNNI 8 bit dot product instruction (CascadeLake or newer).\n#\n#   Moreover, the following general tips for CPU performance equally applies:\n#\n#    * Set the environment variable TVM_NUM_THREADS to the number of physical cores\n#    * Choose the best target for your hardware, such as \"llvm -mcpu=skylake-avx512\" or\n#      \"llvm -mcpu=cascadelake\" (more CPUs with AVX512 would come in the future)\n\n\n###############################################################################\n# Deploy a quantized MXNet Model\n# ------------------------------\n# TODO\n\n###############################################################################\n# Deploy a quantized TFLite Model\n# -------------------------------\n# TODO\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_prequantized_tflite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy a Framework-prequantized Model with TVM - Part 3 (TFLite)\n================================================================\n**Author**: `Siju Samuel <https://github.com/siju-samuel>`_\n\nWelcome to part 3 of the Deploy Framework-Prequantized Model with TVM tutorial.\nIn this part, we will start with a Quantized TFLite graph and then compile and execute it via TVM.\n\n\nFor more details on quantizing the model using TFLite, readers are encouraged to\ngo through `Converting Quantized Models\n<https://www.tensorflow.org/lite/convert/quantization>`_.\n\nThe TFLite models can be downloaded from this `link\n<https://www.tensorflow.org/lite/guide/hosted_models>`_.\n\nTo get started, Tensorflow and TFLite package needs to be installed as prerequisite.\n\n.. code-block:: bash\n\n    # install tensorflow and tflite\n    pip install tensorflow==2.1.0\n    pip install tflite==2.1.0\n\nNow please check if TFLite package is installed successfully, ``python -c \"import tflite\"``\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n###############################################################################\n# Necessary imports\n# -----------------\nimport os\n\nimport numpy as np\nimport tflite\n\nimport tvm\nfrom tvm import relay\n\n\n######################################################################\n# Download pretrained Quantized TFLite model\n# ------------------------------------------\n\n# Download mobilenet V2 TFLite model provided by Google\nfrom tvm.contrib.download import download_testdata\n\nmodel_url = (\n    \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n    \"tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz\"\n)\n\n# Download model tar file and extract it to get mobilenet_v2_1.0_224.tflite\nmodel_path = download_testdata(\n    model_url, \"mobilenet_v2_1.0_224_quant.tgz\", module=[\"tf\", \"official\"]\n)\nmodel_dir = os.path.dirname(model_path)\n\n\n######################################################################\n# Utils for downloading and extracting zip files\n# ----------------------------------------------\ndef extract(path):\n    import tarfile\n\n    if path.endswith(\"tgz\") or path.endswith(\"gz\"):\n        dir_path = os.path.dirname(path)\n        tar = tarfile.open(path)\n        tar.extractall(path=dir_path)\n        tar.close()\n    else:\n        raise RuntimeError(\"Could not decompress the file: \" + path)\n\n\nextract(model_path)\n\n\n######################################################################\n# Load a test image\n# -----------------\n\n#######################################################################\n# Get a real image for e2e testing\n# --------------------------------\ndef get_real_image(im_height, im_width):\n    from PIL import Image\n\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    x = np.array(image).astype(\"uint8\")\n    data = np.reshape(x, (1, im_height, im_width, 3))\n    return data\n\n\ndata = get_real_image(224, 224)\n\n######################################################################\n# Load a tflite model\n# -------------------\n\n######################################################################\n# Now we can open mobilenet_v2_1.0_224.tflite\ntflite_model_file = os.path.join(model_dir, \"mobilenet_v2_1.0_224_quant.tflite\")\ntflite_model_buf = open(tflite_model_file, \"rb\").read()\n\n# Get TFLite model from buffer\ntry:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n###############################################################################\n# Lets run TFLite pre-quantized model inference and get the TFLite prediction.\ndef run_tflite_model(tflite_model_buf, input_data):\n    \"\"\"Generic function to execute TFLite\"\"\"\n    try:\n        from tensorflow import lite as interpreter_wrapper\n    except ImportError:\n        from tensorflow.contrib import lite as interpreter_wrapper\n\n    input_data = input_data if isinstance(input_data, list) else [input_data]\n\n    interpreter = interpreter_wrapper.Interpreter(model_content=tflite_model_buf)\n    interpreter.allocate_tensors()\n\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    # set input\n    assert len(input_data) == len(input_details)\n    for i in range(len(input_details)):\n        interpreter.set_tensor(input_details[i][\"index\"], input_data[i])\n\n    # Run\n    interpreter.invoke()\n\n    # get output\n    tflite_output = list()\n    for i in range(len(output_details)):\n        tflite_output.append(interpreter.get_tensor(output_details[i][\"index\"]))\n\n    return tflite_output\n\n\n###############################################################################\n# Lets run TVM compiled pre-quantized model inference and get the TVM prediction.\ndef run_tvm(lib):\n    from tvm.contrib import graph_executor\n\n    rt_mod = graph_executor.GraphModule(lib[\"default\"](tvm.cpu(0)))\n    rt_mod.set_input(\"input\", data)\n    rt_mod.run()\n    tvm_res = rt_mod.get_output(0).numpy()\n    tvm_pred = np.squeeze(tvm_res).argsort()[-5:][::-1]\n    return tvm_pred, rt_mod\n\n\n###############################################################################\n# TFLite inference\n# ----------------\n\n###############################################################################\n# Run TFLite inference on the quantized model.\ntflite_res = run_tflite_model(tflite_model_buf, data)\ntflite_pred = np.squeeze(tflite_res).argsort()[-5:][::-1]\n\n###############################################################################\n# TVM compilation and inference\n# -----------------------------\n\n###############################################################################\n# We use the TFLite-Relay parser to convert the TFLite pre-quantized graph into Relay IR. Note that\n# frontend parser call for a pre-quantized model is exactly same as frontend parser call for a FP32\n# model. We encourage you to remove the comment from print(mod) and inspect the Relay module. You\n# will see many QNN operators, like, Requantize, Quantize and QNN Conv2D.\ndtype_dict = {\"input\": data.dtype.name}\nshape_dict = {\"input\": data.shape}\n\nmod, params = relay.frontend.from_tflite(tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict)\n# print(mod)\n\n###############################################################################\n# Lets now the compile the Relay module. We use the \"llvm\" target here. Please replace it with the\n# target platform that you are interested in.\ntarget = \"llvm\"\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build_module.build(mod, target=target, params=params)\n\n###############################################################################\n# Finally, lets call inference on the TVM compiled module.\ntvm_pred, rt_mod = run_tvm(lib)\n\n###############################################################################\n# Accuracy comparison\n# -------------------\n\n###############################################################################\n# Print the top-5 labels for MXNet and TVM inference.\n# Checking the labels because the requantize implementation is different between\n# TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via labels.\n\nprint(\"TVM Top-5 labels:\", tvm_pred)\nprint(\"TFLite Top-5 labels:\", tflite_pred)\n\n\n##########################################################################\n# Measure performance\n# -------------------\n# Here we give an example of how to measure performance of TVM compiled models.\nn_repeat = 100  # should be bigger to make the measurement more accurate\ndev = tvm.cpu(0)\nprint(rt_mod.benchmark(dev, number=1, repeat=n_repeat))\n\n######################################################################\n# .. note::\n#\n#   Unless the hardware has special support for fast 8 bit instructions, quantized models are\n#   not expected to be any faster than FP32 models. Without fast 8 bit instructions, TVM does\n#   quantized convolution in 16 bit, even if the model itself is 8 bit.\n#\n#   For x86, the best performance can be achieved on CPUs with AVX512 instructions set.\n#   In this case, TVM utilizes the fastest available 8 bit instructions for the given target.\n#   This includes support for the VNNI 8 bit dot product instruction (CascadeLake or newer).\n#   For EC2 C5.12x large instance, TVM latency for this tutorial is ~2 ms.\n#\n#   Intel conv2d NCHWc schedule on ARM gives better end-to-end latency compared to ARM NCHW\n#   conv2d spatial pack schedule for many TFLite networks. ARM winograd performance is higher but\n#   it has a high memory footprint.\n#\n#   Moreover, the following general tips for CPU performance equally applies:\n#\n#    * Set the environment variable TVM_NUM_THREADS to the number of physical cores\n#    * Choose the best target for your hardware, such as \"llvm -mcpu=skylake-avx512\" or\n#      \"llvm -mcpu=cascadelake\" (more CPUs with AVX512 would come in the future)\n#    * Perform autotuning - :ref:`Auto-tuning a convolution network for x86 CPU\n#      <tune_relay_x86>`.\n#    * To get best inference performance on ARM CPU, change target argument\n#      according to your device and follow :ref:`Auto-tuning a convolution\n#      network for ARM CPU <tune_relay_arm>`.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_quantized.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy a Quantized Model on Cuda\n================================\n**Author**: `Wuwei Lin <https://github.com/vinx13>`_\n\nThis article is an introductory tutorial of automatic quantization with TVM.\nAutomatic quantization is one of the quantization modes in TVM. More details on\nthe quantization story in TVM can be found\n`here <https://discuss.tvm.apache.org/t/quantization-story/3920>`_.\nIn this tutorial, we will import a GluonCV pre-trained model on ImageNet to\nRelay, quantize the Relay model and then perform the inference.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nimport mxnet as mx\nfrom tvm.contrib.download import download_testdata\nfrom mxnet import gluon\nimport logging\nimport os\n\nbatch_size = 1\nmodel_name = \"resnet18_v1\"\ntarget = \"cuda\"\ndev = tvm.device(target)\n\n###############################################################################\n# Prepare the Dataset\n# -------------------\n# We will demonstrate how to prepare the calibration dataset for quantization.\n# We first download the validation set of ImageNet and pre-process the dataset.\ncalibration_rec = download_testdata(\n    \"http://data.mxnet.io.s3-website-us-west-1.amazonaws.com/data/val_256_q90.rec\",\n    \"val_256_q90.rec\",\n)\n\n\ndef get_val_data(num_workers=4):\n    mean_rgb = [123.68, 116.779, 103.939]\n    std_rgb = [58.393, 57.12, 57.375]\n\n    def batch_fn(batch):\n        return batch.data[0].asnumpy(), batch.label[0].asnumpy()\n\n    img_size = 299 if model_name == \"inceptionv3\" else 224\n    val_data = mx.io.ImageRecordIter(\n        path_imgrec=calibration_rec,\n        preprocess_threads=num_workers,\n        shuffle=False,\n        batch_size=batch_size,\n        resize=256,\n        data_shape=(3, img_size, img_size),\n        mean_r=mean_rgb[0],\n        mean_g=mean_rgb[1],\n        mean_b=mean_rgb[2],\n        std_r=std_rgb[0],\n        std_g=std_rgb[1],\n        std_b=std_rgb[2],\n    )\n    return val_data, batch_fn\n\n\n###############################################################################\n# The calibration dataset should be an iterable object. We define the\n# calibration dataset as a generator object in Python. In this tutorial, we\n# only use a few samples for calibration.\n\ncalibration_samples = 10\n\n\ndef calibrate_dataset():\n    val_data, batch_fn = get_val_data()\n    val_data.reset()\n    for i, batch in enumerate(val_data):\n        if i * batch_size >= calibration_samples:\n            break\n        data, _ = batch_fn(batch)\n        yield {\"data\": data}\n\n\n###############################################################################\n# Import the model\n# ----------------\n# We use the Relay MxNet frontend to import a model from the Gluon model zoo.\ndef get_model():\n    gluon_model = gluon.model_zoo.vision.get_model(model_name, pretrained=True)\n    img_size = 299 if model_name == \"inceptionv3\" else 224\n    data_shape = (batch_size, 3, img_size, img_size)\n    mod, params = relay.frontend.from_mxnet(gluon_model, {\"data\": data_shape})\n    return mod, params\n\n\n###############################################################################\n# Quantize the Model\n# ------------------\n# In quantization, we need to find the scale for each weight and intermediate\n# feature map tensor of each layer.\n#\n# For weights, the scales are directly calculated based on the value of the\n# weights. Two modes are supported: `power2` and `max`. Both modes find the\n# maximum value within the weight tensor first. In `power2` mode, the maximum\n# is rounded down to power of two. If the scales of both weights and\n# intermediate feature maps are power of two, we can leverage bit shifting for\n# multiplications. This make it computationally more efficient. In `max` mode,\n# the maximum is used as the scale. Without rounding, `max` mode might have\n# better accuracy in some cases. When the scales are not powers of two, fixed\n# point multiplications will be used.\n#\n# For intermediate feature maps, we can find the scales with data-aware\n# quantization. Data-aware quantization takes a calibration dataset as the\n# input argument. Scales are calculated by minimizing the KL divergence between\n# distribution of activation before and after quantization.\n# Alternatively, we can also use pre-defined global scales. This saves the time\n# for calibration. But the accuracy might be impacted.\n\n\ndef quantize(mod, params, data_aware):\n    if data_aware:\n        with relay.quantize.qconfig(calibrate_mode=\"kl_divergence\", weight_scale=\"max\"):\n            mod = relay.quantize.quantize(mod, params, dataset=calibrate_dataset())\n    else:\n        with relay.quantize.qconfig(calibrate_mode=\"global_scale\", global_scale=8.0):\n            mod = relay.quantize.quantize(mod, params)\n    return mod\n\n\n###############################################################################\n# Run Inference\n# -------------\n# We create a Relay VM to build and execute the model.\ndef run_inference(mod):\n    model = relay.create_executor(\"vm\", mod, dev, target).evaluate()\n    val_data, batch_fn = get_val_data()\n    for i, batch in enumerate(val_data):\n        data, label = batch_fn(batch)\n        prediction = model(data)\n        if i > 10:  # only run inference on a few samples in this tutorial\n            break\n\n\ndef main():\n    mod, params = get_model()\n    mod = quantize(mod, params, data_aware=True)\n    run_inference(mod)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy a Hugging Face Pruned Model on CPU\n=========================================\n**Author**: `Josh Fromm <https://github.com/jwfromm>`_\n\nThis tutorial demonstrates how to take any pruned model, in this case `PruneBert\nfrom Hugging Face\n<https://huggingface.co/huggingface/prunebert-base-uncased-6-finepruned-w-distil-squad>`_,\nand use TVM to leverage the model's sparsity support to produce real speedups. Although\nthe primary purpose of this tutorial is to realize speedups on already pruned\nmodels, it may also be useful to estimate how fast a model would be *if* it were\npruned. To this end, we also provide a function that takes an unpruned model and\nreplaces its weights\nwith random and pruned weights at a specified sparsity. This may be a useful\nfeature when trying to decide if a model is worth pruning or not.\n\nBefore we get into the code, it's useful to discuss sparsity and pruning\nand dig into the two\ndifferent types of sparsity: **structured** and **unstructured**.\n\nPruning is a technique primarily used to reduce the parameter size of a model\nby replacing weight values with 0s. Although many methods exist for choosing which\nweights should be set to 0, the most straight forward is by picking the\nweights with the smallest value. Typically, weights are pruned to a desired\nsparsity percentage. For example, a 95% sparse model would have only 5% of\nits weights non-zero. Pruning to very high sparsities often requires\nfine-tuning or full retraining as it tends to be a lossy approximation.\nAlthough parameter size benefits are quite easy to obtain from a pruned model\nthrough simple compression, leveraging sparsity to yield runtime speedups\nis more complicated.\n\nIn structured sparsity weights are pruned with the goal of clustering\npruned weights together. In other words, they are pruned using both their\nvalue and location. The benefit of bunching up pruned weights is that it allows\nan algorithm such as matrix multiplication to skip entire blocks. It turns out\nthat some degree of *block sparsity* is very important to realizing significant\nspeedups on most hardware available today.\nThis is because when loading memory in most CPUs or GPUs,\nit doesn't save any work to skip reading a single value at a time, instead an entire\nchunk or tile is read in and executed using something like vectorized instructions.\n\nUnstructured sparse weights are those that are pruned only on the value of\nthe original weights. They may appear to be scattered randomly throughout\na tensor rather than in chunks like we'd see in block sparse weights.\nAt low sparsities, unstructured pruning techniques are difficult to\naccelerate. However, at high sparsities many blocks of all 0 values\nwill naturally appear, making it possible to accelerate.\n\nThis tutorial interacts with both structured and unstructured sparsity.\nHugging Face's PruneBert model is unstructured but 95% sparse, allowing us\nto apply TVM's block sparse optimizations to it, even if not optimally.\nWhen generating random sparse weights for an unpruned model, we do so with structured\nsparsity. A fun exercise is comparing the real speed of PruneBert with the block\nsparse speed using fake weights to see the benefit of structured sparsity.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n###############################################################################\n# Load Required Modules\n# ---------------------\n# Other than TVM, scipy, the latest transformers, and\n# tensorflow 2.2+ are required.\nimport os\nimport tvm\nimport time\nimport itertools\nimport numpy as np\nimport tensorflow as tf\nfrom tvm import relay, runtime\nfrom tvm.contrib import graph_executor\nfrom tvm.relay import data_dep_optimization as ddo\nfrom tensorflow.python.framework.convert_to_constants import (\n    convert_variables_to_constants_v2,\n)\nimport scipy.sparse as sp\n\n\n# Ask tensorflow to limit its GPU memory to what's actually needed\n# instead of gobbling everything that's available.\n# https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth\n# This way this tutorial is a little more friendly to sphinx-gallery.\ngpus = tf.config.list_physical_devices(\"GPU\")\nif gpus:\n    try:\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        print(\"tensorflow will use experimental.set_memory_growth(True)\")\n    except RuntimeError as e:\n        print(\"experimental.set_memory_growth option is not available: {}\".format(e))\n\n\n###############################################################################\n# Configure Settings\n# ------------------\n# Let's start by defining some parameters that define the type of model\n# and sparsity to run.\n\n# The name of the transformer model to download and run.\nname = \"huggingface/prunebert-base-uncased-6-finepruned-w-distil-squad\"\n# The number of batches in an input.\nbatch_size = 1\n# The length of each input sequence.\nseq_len = 128\n# TVM platform identifier. Note that best cpu performance can be achieved by setting -mcpu\n# appropriately for your specific machine. CUDA and ROCm are also supported.\ntarget = \"llvm\"\n# Which device to run on. Should be one of tvm.cpu() or tvm.cuda().\ndev = tvm.cpu()\n# If true, then a sparse variant of the network will be run and\n# benchmarked.\nmeasure_sparse = True\n# The block size of structured sparsity to convert weight tensors\n# into. Changing this parameter may yield speedups for some platforms.\nbs_r = 1\n# For models besides PruneBert (which is 95% sparse), this parameter\n# determines how sparse the generated weights should be. The higher\n# the sparsity, the faster the result.\nsparsity = 0.85\n\n\n###############################################################################\n# Download and Convert Transformers Model\n# ---------------------------------------\n# Now we'll grab a model from the transformers module, download it,\n# convert it into a TensorFlow graphdef in preperation for converting that graphdef into\n# a relay graph that we can optimize and deploy.\ndef load_keras_model(module, name, seq_len, batch_size, report_runtime=True):\n    model = module.from_pretrained(name)\n    dummy_input = tf.keras.Input(shape=[seq_len], batch_size=batch_size, dtype=\"int32\")\n    dummy_out = model(dummy_input)  # Propagate shapes through the keras model.\n    if report_runtime:\n        np_input = np.random.uniform(size=[batch_size, seq_len], low=0, high=seq_len).astype(\n            \"int32\"\n        )\n        start = time.time()\n        repeats = 50\n        for i in range(repeats):\n            np_out = model(np_input)\n        end = time.time()\n        print(\"Keras Runtime: %f ms.\" % (1000 * ((end - start) / repeats)))\n    return model\n\n\ndef convert_to_graphdef(model, batch_size, seq_len):\n    model_func = tf.function(lambda x: model(x))\n    input_dict = model._saved_model_inputs_spec\n    input_spec = input_dict[list(input_dict.keys())[0]]\n    model_func = model_func.get_concrete_function(\n        tf.TensorSpec([batch_size, seq_len], input_spec.dtype)\n    )\n    frozen_func = convert_variables_to_constants_v2(model_func)\n    return frozen_func.graph.as_graph_def()\n\n\ndef download_model(name, batch_size, seq_len):\n    import transformers\n\n    module = getattr(transformers, \"TFBertForSequenceClassification\")\n    model = load_keras_model(module, name=name, batch_size=batch_size, seq_len=seq_len)\n    return convert_to_graphdef(model, batch_size, seq_len)\n\n\n###############################################################################\n# Convert to Relay Graph\n# ----------------------\n# We now have all the tooling to get a transformers model in the right format\n# for relay conversion. Let's import it! In the following function we\n# save the imported graph in relay's json format so that we dont have\n# to reimport from tensorflow each time this script is run.\ndef import_graphdef(\n    name,\n    batch_size,\n    seq_len,\n    save_relay=True,\n    relay_file=\"model.json\",\n    relay_params=\"model.params\",\n):\n    abs_path = os.path.dirname(os.path.abspath(__file__))\n    shape_dict = {\"input_1\": (batch_size, seq_len)}\n    relay_file = (\"%s_%d_%d_%s\" % (name, batch_size, seq_len, relay_file)).replace(\"/\", \"_\")\n    relay_params = (\"%s_%d_%d_%s\" % (name, batch_size, seq_len, relay_params)).replace(\"/\", \"_\")\n    if os.path.exists(os.path.join(abs_path, relay_file)) and os.path.exists(\n        os.path.join(abs_path, relay_params)\n    ):\n        with open(os.path.join(abs_path, relay_file), \"r\") as fi:\n            mod = tvm.ir.load_json(fi.read())\n        with open(os.path.join(abs_path, relay_params), \"rb\") as fi:\n            params = relay.load_param_dict(fi.read())\n    else:\n        graph_def = download_model(name, batch_size, seq_len)\n\n        mod, params = relay.frontend.from_tensorflow(graph_def, shape=shape_dict)\n\n        if save_relay:\n            with open(os.path.join(abs_path, relay_file), \"w\") as fo:\n                fo.write(tvm.ir.save_json(mod))\n            with open(os.path.join(abs_path, relay_params), \"wb\") as fo:\n                fo.write(runtime.save_param_dict(params))\n\n    return mod, dict(params.items()), shape_dict\n\n\n###############################################################################\n# Run the Dense Graph\n# -------------------\n# Let's run the default version of the imported model. Note that even if\n# the weights are sparse, we won't see any speedup because we are using\n# regular dense matrix multiplications on these dense (but mostly zero)\n# tensors instead of sparse aware kernels.\ndef run_relay_graph(mod, params, shape_dict, target, dev):\n    with relay.build_config(opt_level=3):\n        lib = relay.build(mod, target=target, params=params)\n    input_shape = shape_dict[\"input_1\"]\n    dummy_data = np.random.uniform(size=input_shape, low=0, high=input_shape[1]).astype(\"int32\")\n\n    m = graph_executor.GraphModule(lib[\"default\"](dev))\n    m.set_input(0, dummy_data)\n    m.run()\n    tvm_output = m.get_output(0)\n\n    print(m.benchmark(dev, repeat=5, number=5))\n    return tvm_output\n\n\ndef run_dense(mod, params, shape_dict, target, dev):\n    print(\"Dense Model Benchmark:\")\n    return run_relay_graph(mod, params, shape_dict, target, dev)\n\n\n###############################################################################\n# Run the Sparse Graph\n# --------------------\n# Next we'll convert the graph into a sparse representation and generate\n# fake sparse weights if needed. Then we'll use the same benchmarking\n# script as dense to see how much faster we go! We apply a few relay passes\n# to the graph to get it leveraging sparsity. First we use\n# `simplify_fc_transpose` to use transposes on the weights of dense layers\n# into the parameters. This makes it easier to convert to matrix multiplies\n# to sparse versions. Next we apply `bsr_dense.convert` to identify all\n# weight matrices that can be sparse, and automatically replace them.\n#\n# The `bsr_dense.convert` call below is doing the heavy lifting of identifying\n# which weights in the model can be made sparse by checking if they are\n# at least `sparsity_threshold` percent sparse. If so, it converts those\n# weights into *Block Compressed Row Format (BSR)*. BSR is essentially\n# a representation that indexes into the nonzero chunks of the tensor,\n# making it easy for an algorithm to load those non-zero chunks and ignore\n# the rest of the tensor. Once the sparse weights are in BSR format,\n# `relay.transform.DenseToSparse` is applied to actually replace\n# `relay.dense` operations with `relay.sparse_dense` calls that can be\n# run faster.\ndef random_bsr_matrix(M, N, BS_R, BS_C, density, dtype=\"float32\"):\n    Y = np.zeros((M, N), dtype=dtype)\n    assert M % BS_R == 0\n    assert N % BS_C == 0\n    nnz = int(density * M * N)\n    num_blocks = int(nnz / (BS_R * BS_C)) + 1\n    candidate_blocks = np.asarray(list(itertools.product(range(0, M, BS_R), range(0, N, BS_C))))\n    assert candidate_blocks.shape[0] == M // BS_R * N // BS_C\n    chosen_blocks = candidate_blocks[\n        np.random.choice(candidate_blocks.shape[0], size=num_blocks, replace=False)\n    ]\n    for i in range(len(chosen_blocks)):\n        r, c = chosen_blocks[i]\n        Y[r : r + BS_R, c : c + BS_C] = np.random.uniform(-0.1, 0.1, (BS_R, BS_C))\n    s = sp.bsr_matrix(Y, blocksize=(BS_R, BS_C))\n    assert s.data.shape == (num_blocks, BS_R, BS_C)\n    assert s.data.size >= nnz\n    assert s.indices.shape == (num_blocks,)\n    assert s.indptr.shape == (M // BS_R + 1,)\n    return s.todense()\n\n\ndef random_sparse_bert_params(func, params, density, BS_R, BS_C):\n    def deepcopy(param_dic):\n        ret = {}\n        for k, v in param_dic.items():\n            ret[k] = tvm.nd.array(v.numpy())\n        return ret\n\n    new_params = deepcopy(params)\n    dense_weight_names = relay.analysis.sparse_dense._search_dense_op_weight(func)\n    for item in dense_weight_names:\n        name = str(item)\n        shape = new_params[name].shape\n        if shape[0] % BS_R == 0 and shape[1] % BS_C == 0:\n            new_w = random_bsr_matrix(shape[0], shape[1], BS_R, BS_C, density)\n            new_params[name] = tvm.nd.array(new_w)\n    return new_params\n\n\ndef run_sparse(mod, params, shape_dict, target, dev, bs_r, sparsity, gen_weights):\n    mod, params = ddo.simplify_fc_transpose.convert(mod[\"main\"], params)\n    if gen_weights:\n        params = random_sparse_bert_params(mod, params, BS_R=bs_r, BS_C=1, density=1 - sparsity)\n    mod, params = ddo.bsr_dense.convert(mod, params, (bs_r, 1), sparsity_threshold=0.8)\n    print(\"Block Sparse Model with {blocksize}x1 blocks:\".format(blocksize=bs_r))\n    return run_relay_graph(mod, params, shape_dict, target, dev)\n\n\n###############################################################################\n# Run All the Code!\n# -----------------\n# And that's it! Now we'll simply call all the needed function to benchmark\n# the model according to the set parameters. Note that to run this code\n# you'll need to uncomment the last line first.\ndef benchmark():\n    mod, params, shape_dict = import_graphdef(name, batch_size, seq_len)\n    run_dense(mod, params, shape_dict, target, dev)\n    if measure_sparse:\n        gen_weights = \"prune\" not in name\n        run_sparse(mod, params, shape_dict, target, dev, bs_r, sparsity, gen_weights)\n\n\n# benchmark()\n\n###############################################################################\n# Sample Output\n# -------------\n# For reference, below is the output of the script when run on an AMD CPU\n# and shows about a 2.5X speedup from using sparsity.\n\n# Dense Model Benchmark:\n# Cannot find config for target=llvm, workload=('dense_nopack.x86', ('TENSOR', (1, 768), 'float32'), ('TENSOR', (2, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('dense_nopack.x86', ('TENSOR', (1, 768), 'float32'), ('TENSOR', (768, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('dense_nopack.x86', ('TENSOR', (128, 3072), 'float32'), ('TENSOR', (768, 3072), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('dense_nopack.x86', ('TENSOR', (128, 768), 'float32'), ('TENSOR', (3072, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('dense_nopack.x86', ('TENSOR', (128, 768), 'float32'), ('TENSOR', (768, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('batch_matmul.x86', ('TENSOR', (12, 128, 128), 'float32'), ('TENSOR', (12, 64, 128), 'float32')). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=llvm, workload=('batch_matmul.x86', ('TENSOR', (12, 128, 64), 'float32'), ('TENSOR', (12, 128, 64), 'float32')). A fallback configuration is used, which may bring great performance regression.\n# Runtime:             165.26 ms           (12.83 ms)\n# Block Sparse Model with 1x1 blocks:\n# Runtime:             67.75 ms            (8.83 ms)\n\n# Here is the output of this script on a GPU (GTX 1070) with the target \"cuda -libs=cublas\".\n#\n# Dense Model Benchmark:\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('dense_cublas.cuda', ('TENSOR', (1, 768), 'float32'), ('TENSOR', (2, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('dense_cublas.cuda', ('TENSOR', (1, 768), 'float32'), ('TENSOR', (768, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('dense_cublas.cuda', ('TENSOR', (128, 3072), 'float32'), ('TENSOR', (768, 3072), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('dense_cublas.cuda', ('TENSOR', (128, 768), 'float32'), ('TENSOR', (3072, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('dense_cublas.cuda', ('TENSOR', (128, 768), 'float32'), ('TENSOR', (768, 768), 'float32'), None, 'float32'). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('batch_matmul_cublas.cuda', ('TENSOR', (12, 128, 128), 'float32'), ('TENSOR', (12, 64, 128), 'float32'), (12, 128, 64)). A fallback configuration is used, which may bring great performance regression.\n# Cannot find config for target=cuda -keys=cuda,gpu -libs=cublas -max_num_threads=1024 -thread_warp_size=32, workload=('batch_matmul_cublas.cuda', ('TENSOR', (12, 128, 64), 'float32'), ('TENSOR', (12, 128, 64), 'float32'), (12, 128, 128)). A fallback configuration is used, which may bring great performance regression.\n# Runtime:             10.64 ms            (0.29 ms)\n# Block Sparse Model with 1x1 blocks:\n# Runtime:             6.46 ms             (0.05 ms)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/deploy_models/deploy_ssd_gluoncv.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy Single Shot Multibox Detector(SSD) model\n===============================================\n**Author**: `Yao Wang <https://github.com/kevinthesun>`_\n`Leyuan Wang <https://github.com/Laurawly>`_\n\nThis article is an introductory tutorial to deploy SSD models with TVM.\nWe will use GluonCV pre-trained SSD model and convert it to Relay IR\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\n\nfrom matplotlib import pyplot as plt\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.download import download_testdata\nfrom gluoncv import model_zoo, data, utils\n\n\n######################################################################\n# Preliminary and Set parameters\n# ------------------------------\n# .. note::\n#\n#   We support compiling SSD on both CPUs and GPUs now.\n#\n#   To get best inference performance on CPU, change\n#   target argument according to your device and\n#   follow the :ref:`tune_relay_x86` to tune x86 CPU and\n#   :ref:`tune_relay_arm` for arm CPU.\n#\n#   To get best inference performance on Intel graphics,\n#   change target argument to :code:`opencl -device=intel_graphics`.\n#   But when using Intel graphics on Mac, target needs to\n#   be set to `opencl` only for the reason that Intel subgroup\n#   extension is not supported on Mac.\n#\n#   To get best inference performance on CUDA-based GPUs,\n#   change the target argument to :code:`cuda`; and for\n#   OPENCL-based GPUs, change target argument to\n#   :code:`opencl` followed by device argument according\n#   to your device.\n\nsupported_model = [\n    \"ssd_512_resnet50_v1_voc\",\n    \"ssd_512_resnet50_v1_coco\",\n    \"ssd_512_resnet101_v2_voc\",\n    \"ssd_512_mobilenet1.0_voc\",\n    \"ssd_512_mobilenet1.0_coco\",\n    \"ssd_300_vgg16_atrous_voc\" \"ssd_512_vgg16_atrous_coco\",\n]\n\nmodel_name = supported_model[0]\ndshape = (1, 3, 512, 512)\n\n######################################################################\n# Download and pre-process demo image\n\nim_fname = download_testdata(\n    \"https://github.com/dmlc/web-data/blob/main/\" + \"gluoncv/detection/street_small.jpg?raw=true\",\n    \"street_small.jpg\",\n    module=\"data\",\n)\nx, img = data.transforms.presets.ssd.load_test(im_fname, short=512)\n\n######################################################################\n# Convert and compile model for CPU.\n\nblock = model_zoo.get_model(model_name, pretrained=True)\n\n\ndef build(target):\n    mod, params = relay.frontend.from_mxnet(block, {\"data\": dshape})\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target, params=params)\n    return lib\n\n\n######################################################################\n# Create TVM runtime and do inference\n# .. note::\n#\n#   Use target = \"cuda -libs\" to enable thrust based sort, if you\n#   enabled thrust during cmake by -DUSE_THRUST=ON.\n\n\ndef run(lib, dev):\n    # Build TVM runtime\n    m = graph_executor.GraphModule(lib[\"default\"](dev))\n    tvm_input = tvm.nd.array(x.asnumpy(), device=dev)\n    m.set_input(\"data\", tvm_input)\n    # execute\n    m.run()\n    # get outputs\n    class_IDs, scores, bounding_boxs = m.get_output(0), m.get_output(1), m.get_output(2)\n    return class_IDs, scores, bounding_boxs\n\n\nfor target in [\"llvm\", \"cuda\"]:\n    dev = tvm.device(target, 0)\n    if dev.exist:\n        lib = build(target)\n        class_IDs, scores, bounding_boxs = run(lib, dev)\n\n######################################################################\n# Display result\n\nax = utils.viz.plot_bbox(\n    img,\n    bounding_boxs.numpy()[0],\n    scores.numpy()[0],\n    class_IDs.numpy()[0],\n    class_names=block.classes,\n)\nplt.show()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/extend_tvm/bring_your_own_datatypes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nBring Your Own Datatypes to TVM\n===============================\n**Authors**: `Gus Smith <https://github.com/gussmith23>`_, `Andrew Liu <https://github.com/hypercubestart>`_\n\nIn this tutorial, we will show you how to utilize the Bring Your Own Datatypes framework to use your own custom datatypes in TVM.\nNote that the Bring Your Own Datatypes framework currently only handles **software emulated versions of datatypes**.\nThe framework does not support compiling for custom accelerator datatypes out-of-the-box.\n\nDatatype Libraries\n------------------\n\nThe Bring Your Own Datatypes allows users to register their own datatype implementations alongside TVM's native datatypes (such as ``float``).\nIn the wild, these datatype implementations often appear as libraries.\nFor example:\n\n- `libposit <https://github.com/cjdelisle/libposit>`_, a posit library\n- `Stillwater Universal <https://github.com/stillwater-sc/universal>`_, a library with posits, fixed-point numbers, and other types\n- `SoftFloat <https://github.com/ucb-bar/berkeley-softfloat-3>`_, Berkeley's software implementation of IEEE 754 floating-point\n\nThe Bring Your Own Datatypes enables users to plug these datatype implementations into TVM!\n\nIn this section, we will use an example library we have already implemented, located at ``3rdparty/byodt/myfloat.cc``.\nThis datatype, which we dubbed \"myfloat\", is really just a IEE-754 float under-the-hood, but it serves a useful example\nto show that any datatype can be used in the BYODT framework.\n\nSetup\n-----\n\nSince we do not use any 3rdparty library, there is no setup needed.\n\nIf you would like to try this with your own datatype library, first bring the library's functions into the process space with ``CDLL``:\n\n.. code-block :: python\n\n    ctypes.CDLL('my-datatype-lib.so', ctypes.RTLD_GLOBAL)\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n######################\n# A Simple TVM Program\n# --------------------\n#\n# We'll begin by writing a simple program in TVM; afterwards, we will re-write it to use custom datatypes.\nimport tvm\nfrom tvm import relay\n\n# Our basic program: Z = X + Y\nx = relay.var(\"x\", shape=(3,), dtype=\"float32\")\ny = relay.var(\"y\", shape=(3,), dtype=\"float32\")\nz = x + y\nprogram = relay.Function([x, y], z)\nmodule = tvm.IRModule.from_expr(program)\n\n######################################################################\n# Now, we create random inputs to feed into this program using numpy:\n\nimport numpy as np\n\nnp.random.seed(23)  # for reproducibility\n\nx_input = np.random.rand(3).astype(\"float32\")\ny_input = np.random.rand(3).astype(\"float32\")\nprint(\"x: {}\".format(x_input))\nprint(\"y: {}\".format(y_input))\n\n######################################################################\n# Finally, we're ready to run the program:\n\nz_output = relay.create_executor(mod=module).evaluate()(x_input, y_input)\nprint(\"z: {}\".format(z_output))\n\n######################################################################\n# Adding Custom Datatypes\n# -----------------------\n# Now, we will do the same, but we will use a custom datatype for our intermediate computation.\n#\n# We use the same input variables ``x`` and ``y`` as above, but before adding ``x + y``, we first cast both ``x`` and ``y`` to a custom datatype via the ``relay.cast(...)`` call.\n#\n# Note how we specify the custom datatype: we indicate it using the special ``custom[...]`` syntax.\n# Additionally, note the \"32\" after the datatype: this is the bitwidth of the custom datatype. This tells TVM that each instance of ``myfloat`` is 32 bits wide.\n\ntry:\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        x_myfloat = relay.cast(x, dtype=\"custom[myfloat]32\")\n        y_myfloat = relay.cast(y, dtype=\"custom[myfloat]32\")\n        z_myfloat = x_myfloat + y_myfloat\n        z = relay.cast(z_myfloat, dtype=\"float32\")\nexcept tvm.TVMError as e:\n    # Print last line of error\n    print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# Trying to generate this program throws an error from TVM.\n# TVM does not know how to handle any custom datatype out of the box!\n# We first have to register the custom type with TVM, giving it a name and a type code:\n\ntvm.target.datatype.register(\"myfloat\", 150)\n\n######################################################################\n# Note that the type code, 150, is currently chosen manually by the user.\n# See ``TVMTypeCode::kCustomBegin`` in `include/tvm/runtime/c_runtime_api.h <https://github.com/apache/tvm/blob/main/include/tvm/runtime/data_type.h>`_.\n# Now we can generate our program again:\n\nx_myfloat = relay.cast(x, dtype=\"custom[myfloat]32\")\ny_myfloat = relay.cast(y, dtype=\"custom[myfloat]32\")\nz_myfloat = x_myfloat + y_myfloat\nz = relay.cast(z_myfloat, dtype=\"float32\")\nprogram = relay.Function([x, y], z)\nmodule = tvm.IRModule.from_expr(program)\nmodule = relay.transform.InferType()(module)\n\n######################################################################\n# Now we have a Relay program that uses myfloat!\nprint(program)\n\n######################################################################\n# Now that we can express our program without errors, let's try running it!\ntry:\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        z_output_myfloat = relay.create_executor(\"graph\", mod=module).evaluate()(x_input, y_input)\n        print(\"z: {}\".format(y_myfloat))\nexcept tvm.TVMError as e:\n    # Print last line of error\n    print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# Now, trying to compile this program throws an error.\n# Let's dissect this error.\n#\n# The error is occurring during the process of lowering the custom datatype code to code that TVM can compile and run.\n# TVM is telling us that it cannot find a *lowering function* for the ``Cast`` operation, when casting from source type 2 (``float``, in TVM), to destination type 150 (our custom datatype).\n# When lowering custom datatypes, if TVM encounters an operation over a custom datatype, it looks for a user-registered *lowering function*, which tells it how to lower the operation to an operation over datatypes it understands.\n# We have not told TVM how to lower ``Cast`` operations for our custom datatypes; thus, the source of this error.\n#\n# To fix this error, we simply need to specify a lowering function:\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func(\n        {\n            (32, 32): \"FloatToCustom32\",  # cast from float32 to myfloat32\n        }\n    ),\n    \"Cast\",\n    \"llvm\",\n    \"float\",\n    \"myfloat\",\n)\n\n######################################################################\n# The ``register_op(...)`` call takes a lowering function, and a number of parameters which specify exactly the operation which should be lowered with the provided lowering function.\n# In this case, the arguments we pass specify that this lowering function is for lowering a ``Cast`` from ``float`` to ``myfloat`` for target ``\"llvm\"``.\n#\n# The lowering function passed into this call is very general: it should take an operation of the specified type (in this case, `Cast`) and return another operation which only uses datatypes which TVM understands.\n#\n# In the general case, we expect users to implement operations over their custom datatypes using calls to an external library.\n# In our example, our ``myfloat`` library implements a ``Cast`` from ``float`` to 32-bit ``myfloat`` in the function ``FloatToCustom32``.\n# To provide for the general case, we have made a helper function, ``create_lower_func(...)``,\n# which does just this: given a dictionary, it replaces the given operation with a ``Call`` to the appropriate function name provided based on the op and the bit widths.\n# It additionally removes usages of the custom datatype by storing the custom datatype in an opaque ``uint`` of the appropriate width; in our case, a ``uint32_t``.\n# For more information, see `the source code <https://github.com/apache/tvm/blob/main/python/tvm/target/datatype.py>`_.\n\n# We can now re-try running the program:\ntry:\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        z_output_myfloat = relay.create_executor(\"graph\", mod=module).evaluate()(x_input, y_input)\n        print(\"z: {}\".format(z_output_myfloat))\nexcept tvm.TVMError as e:\n    # Print last line of error\n    print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# This new error tells us that the ``Add`` lowering function is not found, which is good news, as it's no longer complaining about the ``Cast``!\n# We know what to do from here: we just need to register the lowering functions for the other operations in our program.\n#\n# Note that for ``Add``, ``create_lower_func`` takes in a dict where the key is an integer.\n# For ``Cast`` operations, we require a 2-tuple to specify the ``src_bit_length`` and the ``dest_bit_length``,\n# while for all other operations, the bit length is the same between the operands so we only require one integer to specify ``bit_length``.\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Add\"}),\n    \"Add\",\n    \"llvm\",\n    \"myfloat\",\n)\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({(32, 32): \"Custom32ToFloat\"}),\n    \"Cast\",\n    \"llvm\",\n    \"myfloat\",\n    \"float\",\n)\n\n# Now, we can run our program without errors.\nwith tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n    z_output_myfloat = relay.create_executor(mod=module).evaluate()(x_input, y_input)\nprint(\"z: {}\".format(z_output_myfloat))\n\nprint(\"x:\\t\\t{}\".format(x_input))\nprint(\"y:\\t\\t{}\".format(y_input))\nprint(\"z (float32):\\t{}\".format(z_output))\nprint(\"z (myfloat32):\\t{}\".format(z_output_myfloat))\n\n# Perhaps as expected, the ``myfloat32`` results and ``float32`` are exactly the same!\n\n######################################################################\n# Running Models With Custom Datatypes\n# ------------------------------------\n#\n# We will first choose the model which we would like to run with myfloat.\n# In this case we use `Mobilenet <https://arxiv.org/abs/1704.04861>`_.\n# We choose Mobilenet due to its small size.\n# In this alpha state of the Bring Your Own Datatypes framework, we have not implemented any software optimizations for running software emulations of custom datatypes; the result is poor performance due to many calls into our datatype emulation library.\n#\n# First let us define two helper functions to get the mobilenet model and a cat image.\n\n\ndef get_mobilenet():\n    dshape = (1, 3, 224, 224)\n    from mxnet.gluon.model_zoo.vision import get_model\n\n    block = get_model(\"mobilenet0.25\", pretrained=True)\n    shape_dict = {\"data\": dshape}\n    return relay.frontend.from_mxnet(block, shape_dict)\n\n\ndef get_cat_image():\n    from tvm.contrib.download import download_testdata\n    from PIL import Image\n\n    url = \"https://gist.githubusercontent.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png\"\n    dst = \"cat.png\"\n    real_dst = download_testdata(url, dst, module=\"data\")\n    img = Image.open(real_dst).resize((224, 224))\n    # CoreML's standard model image format is BGR\n    img_bgr = np.array(img)[:, :, ::-1]\n    img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :]\n    return np.asarray(img, dtype=\"float32\")\n\n\nmodule, params = get_mobilenet()\n\n######################################################################\n# It's easy to execute MobileNet with native TVM:\n\nex = tvm.relay.create_executor(\"graph\", mod=module, params=params)\ninput = get_cat_image()\nresult = ex.evaluate()(input).numpy()\n# print first 10 elements\nprint(result.flatten()[:10])\n\n######################################################################\n# Now, we would like to change the model to use myfloat internally. To do so, we need to convert the network. To do this, we first define a function which will help us convert tensors:\n\n\ndef convert_ndarray(dst_dtype, array):\n    \"\"\"Converts an NDArray into the specified datatype\"\"\"\n    x = relay.var(\"x\", shape=array.shape, dtype=str(array.dtype))\n    cast = relay.Function([x], x.astype(dst_dtype))\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        return relay.create_executor(\"graph\").evaluate(cast)(array)\n\n\n######################################################################\n# Now, to actually convert the entire network, we have written `a pass in Relay <https://github.com/gussmith23/tvm/blob/ea174c01c54a2529e19ca71e125f5884e728da6e/python/tvm/relay/frontend/change_datatype.py#L21>`_ which simply converts all nodes within the model to use the new datatype.\n\nfrom tvm.relay.frontend.change_datatype import ChangeDatatype\n\nsrc_dtype = \"float32\"\ndst_dtype = \"custom[myfloat]32\"\n\nmodule = relay.transform.InferType()(module)\n\n# Currently, custom datatypes only work if you run simplify_inference beforehand\nmodule = tvm.relay.transform.SimplifyInference()(module)\n\n# Run type inference before changing datatype\nmodule = tvm.relay.transform.InferType()(module)\n\n# Change datatype from float to myfloat and re-infer types\ncdtype = ChangeDatatype(src_dtype, dst_dtype)\nexpr = cdtype.visit(module[\"main\"])\nmodule = tvm.relay.transform.InferType()(module)\n\n# We also convert the parameters:\nparams = {k: convert_ndarray(dst_dtype, v) for k, v in params.items()}\n\n# We also need to convert our input:\ninput = convert_ndarray(dst_dtype, input)\n\n# Finally, we can try to run the converted model:\ntry:\n    # Vectorization is not implemented with custom datatypes.\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        result_myfloat = tvm.relay.create_executor(\"graph\", mod=module).evaluate(expr)(\n            input, **params\n        )\nexcept tvm.TVMError as e:\n    print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# When we attempt to run the model, we get a familiar error telling us that more functions need to be registered for myfloat.\n#\n# Because this is a neural network, many more operations are required.\n# Here, we register all the needed functions:\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"FloatToCustom32\"}),\n    \"FloatImm\",\n    \"llvm\",\n    \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.lower_ite, \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.if_then_else\"\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.lower_call_pure_extern,\n    \"Call\",\n    \"llvm\",\n    \"myfloat\",\n    intrinsic_name=\"tir.call_pure_extern\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Mul\"}),\n    \"Mul\",\n    \"llvm\",\n    \"myfloat\",\n)\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Div\"}),\n    \"Div\",\n    \"llvm\",\n    \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Sqrt\"}),\n    \"Call\",\n    \"llvm\",\n    \"myfloat\",\n    intrinsic_name=\"tir.sqrt\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Sub\"}),\n    \"Sub\",\n    \"llvm\",\n    \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Exp\"}),\n    \"Call\",\n    \"llvm\",\n    \"myfloat\",\n    intrinsic_name=\"tir.exp\",\n)\n\ntvm.target.datatype.register_op(\n    tvm.target.datatype.create_lower_func({32: \"Custom32Max\"}),\n    \"Max\",\n    \"llvm\",\n    \"myfloat\",\n)\n\ntvm.target.datatype.register_min_func(\n    tvm.target.datatype.create_min_lower_func({32: \"MinCustom32\"}, \"myfloat\"),\n    \"myfloat\",\n)\n\n######################################################################\n# Note we are making use of two new functions: ``register_min_func`` and ``create_min_lower_func``.\n#\n# ``register_min_func`` takes in an integer ``num_bits`` for the bit length, and should return an operation\n# representing the minimum finite representable value for the custom data type with the specified bit length.\n#\n# Similar to ``register_op`` and ``create_lower_func``, the ``create_min_lower_func`` handles the general case\n# where the minimum representable custom datatype value is implemented using calls to an external library.\n#\n# Now we can finally run the model:\n\n# Vectorization is not implemented with custom datatypes.\nwith tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n    result_myfloat = relay.create_executor(mod=module).evaluate(expr)(input, **params)\n    result_myfloat = convert_ndarray(src_dtype, result_myfloat).numpy()\n    # print first 10 elements\n    print(result_myfloat.flatten()[:10])\n\n# Again, note that the output using 32-bit myfloat exactly the same as 32-bit floats,\n# because myfloat is exactly a float!\nnp.testing.assert_array_equal(result, result_myfloat)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/extend_tvm/low_level_custom_pass.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nWriting a Customized Pass\n=========================\n**Author**: `Jian Weng <https://were.github.io>`_\n\nTVM is a framework that abstracts away the heterogenity of machine learning accelerators.\nSometimes users may want customize some analysis and IR transformations\nto adapt TVM to their own specialized hardware. This tutorial helps users write\na customized pass in TVM.\n\nPrerequisites\n-------------\n\nBefore reading this tutorial, we assume readers have already known these topics well:\n\n- Writing an algorithm in TVM and schedule it. Otherwise, see example tutorials like\n  :ref:`opt-gemm`.\n- The basic structure of HalideIR. Otherwise, see ``HalideIR/src/ir/IR.h`` to learn what\n  attributes of IR nodes are defined.\n- Visitor design pattern. Otherwise, check the\n  `Python AST module <https://docs.python.org/3/library/ast.html>`_ to see how an AST\n  visitor is implemented.\n- How a Schedule is lowered to either an IRModule class or a LLVM module. Otherwise,\n  take a look at ``python/tvm/build_module.py`` to get some basics.\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n######################################################################\n# We first write a very simple vector add and build it with the default schedule. Then, we use\n# our customized lowering pass to manipulate the IR directly instead of using schedule primitives.\n#\n\nn = tvm.tir.const(128, \"int32\")\na = te.placeholder((n,), name=\"a\")\nb = te.placeholder((n,), name=\"b\")\nc = te.compute((n,), lambda i: a[i] + b[i], name=\"c\")\n\nsch = te.create_schedule(c.op)\nir = tvm.lower(sch, [a, b, c])\nprint(ir)\n\n######################################################################\n# Writing a Pass\n# --------------\n# Essentially, an \"IR transformation pass\" is a function which maps a statement to a new statement.\n# Thus, we define this vectorize function and implement it step by step.\n#\n\n######################################################################\n# TVM already provides two class for users to both analyze and transform IR.\n#\n# IR Visitor\n# ~~~~~~~~~~\n# We can use ``tvm.tir.stmt_functor.post_order_visit(stmt, func)`` to gather information from the Halide IR.\n# ``func`` is a function callback. This function will be called before exiting the current IR node,\n# i.e. post-order visit. Then we leverage side effects to store the result of IR visit, because the\n# return value of ``func`` will be ignored.\n#\n# .. note::\n#\n#     You MUST use some array to store the result of IR visit. Even the value is a single variable.\n#     This is mainly due to the constraints in the Python-C runtime. The variable values will be\n#     refreshed every recursion but the array values will be preserved.\n#\n\nloops = []\n\n\ndef find_width8(op):\n    \"\"\"Find all the 'tir.For' nodes whose extent can be divided by 8.\"\"\"\n    if isinstance(op, tvm.tir.For):\n        if isinstance(op.extent, tvm.tir.IntImm):\n            if op.extent.value % 8 == 0:\n                loops.append(op)\n\n\n#####################################################################\n# IR Transformation\n# ~~~~~~~~~~~~~~~~~\n# The transformation interface is slightly different from the visitor interface. There is only a\n# post-order callback in the visitor, but transformation visitor supports both a pre-order and a\n# post-order callback. If you want to keep the origin IR node, just return None. If you want to\n# change the current node to some node, use TVM IR maker interface to build it and return\n# this value.\n#\n# .. note::\n#\n#     If the pre-order function is called and returns a value which is not None, the post-order\n#     function will be skipped.\n#\n\n\ndef vectorize8(op):\n    \"\"\"Split can vectorize the loops found in `find_width8`.\"\"\"\n    if op in loops:\n        extent = op.extent.value\n        name = op.loop_var.name\n        lo, li = te.var(name + \".outer\"), te.var(name + \".inner\")\n        body = tvm.tir.stmt_functor.substitute(op.body, {op.loop_var: lo * 8 + li})\n        body = tvm.tir.For(li, 0, 8, tvm.tir.ForKind.VECTORIZED, body)\n        body = tvm.tir.For(lo, 0, extent // 8, tvm.tir.ForKind.SERIAL, body)\n        return body\n    return None\n\n\n@tvm.tir.transform.prim_func_pass(opt_level=0)\ndef vectorize(f, mod, ctx):\n    global loops\n\n    tvm.tir.stmt_functor.post_order_visit(f.body, find_width8)\n\n    if not loops:\n        return f\n\n    # The last list arugment indicates what kinds of nodes will be transformed.\n    # Thus, in this case only `For` nodes will call `vectorize8`\n    return f.with_body(tvm.tir.stmt_functor.ir_transform(f.body, None, vectorize8, [\"tir.For\"]))\n\n\n#####################################################################\n# Glue to Lowering\n# ----------------\n# So far, we are done with writing this IR transformation pass. What we need to do next is to glue\n# this pass to TVM's lower pass.\n#\n# In this case, we inject the pass written above into the TVM standard lowering\n# pass by feeding **a list of tuple** as argument to ``tir.add_lower_pass``. \"Tuple\" indicates different\n# phases of lowering. In TVM, there are four phases of lowering and user-customized ones will be\n# called after each phase is done.\n#\n# .. note::\n#     Here are the essential transformations done by each phase:\n#       - Phase 0 generates the raw IR and loop levels.\n#       - Phase 1 flattens the array storage.\n#       - Phase 2 transforms loops, like unroll, vectorization and thread-binding.\n#       - Phase 3 does some cleanup work.\n#\n# Thus, a good place to put this transformation pass is just after Phase 1.\n#\n\nwith tvm.transform.PassContext(config={\"tir.add_lower_pass\": [(1, vectorize)]}):\n    print(tvm.lower(sch, [a, b, c]))\n\n#####################################################################\n# Quick View\n# ----------\n# This tutorial gives a quick view of writing a customized IR transformation pass:\n# - Use ``tvm.tir.stmt_functor.post_order_visit`` to gather information on each IR nodes.\n# - Use ``tvm.tir.stmt_functor.ir_transform`` to transform IR nodes.\n# - Wrap up two above to write an IR-transformation function.\n# - Use ``tvm.transform.PassContext`` to put this function to TVM lowering pass\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/extend_tvm/use_pass_infra.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long\n\"\"\"\n.. _tutorial-use-pass-infra:\n\nHow to Use TVM Pass Infra\n=========================\n**Author**: `Zhi Chen <https://github.com/zhiics>`_\n\nAs the number of optimization passes increases in Relay/tir, it becomes intractable to\nexecute them and maintain their dependencies manually. Therefore, we have\nintroduced an infrastructure to manage the optimization passes and make it\napplicable to different layers of the IR in the TVM stack.\n\nThe optimizations of a Relay/tir program could be applied at various granularity,\nnamely function-level and module-level using :py:class:`tvm.relay.transform.FunctionPass`/\n:py:class:`tvm.tir.transform.PrimFuncPass` and :py:class:`tvm.transform.ModulePass`\nrespectively. Or users can rely on :py:class:`tvm.transform.Sequential` to apply a sequence of passes\non a Relay/tir program where the dependencies between passes can be resolved by the\npass infra. For more details about each type of these passes, please refer to\nthe :ref:`pass-infra`\n\nThis tutorial mainly demonstrates how developers can use the pass infra to perform\na certain optimization and create an optimization pipeline for a Relay program.\nThe same approach can be used for tir as well.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\n\n###############################################################################\n# Create An Example Relay Program\n# -------------------------------\n# First of all, we create a simple Relay program for the tutorial. This program\n# will be used by various optimizations of the examples in this tutorial.\n# Similarly, users can write a tir primitive function and apply the tir passes.\n\n\ndef example():\n    shape = (1, 64, 54, 54)\n    c_data = np.empty(shape).astype(\"float32\")\n    c = relay.const(c_data)\n    weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n    x = relay.var(\"x\", relay.TensorType((1, 64, 56, 56), \"float32\"))\n    conv = relay.nn.conv2d(x, weight)\n    y = relay.add(c, c)\n    y = relay.multiply(y, relay.const(2, \"float32\"))\n    y = relay.add(conv, y)\n    z = relay.add(y, c)\n    z1 = relay.add(y, c)\n    z2 = relay.add(z, z1)\n    return relay.Function([x, weight], z2)\n\n\n###############################################################################\n# Optimize the Program\n# --------------------\n# Now we would like to optimize the program. Relay features a host of\n# optimizations. We will select some of them to apply on this example program.\n#\n# There are multiple ways to optimize a Relay program. Below we will provide\n# examples for each of them.\n#\n# Manually Apply Optimization Passes\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# Let's first create a relay Module which contains one or multiple Relay\n# functions for optimization.\nf = example()\nmod = tvm.IRModule.from_expr(f)\n\n# Now we can apply constant folding on the module.\n# fold_const here is a callback that doesn't take any parameters.\nfold_const = relay.transform.FoldConstant()\n# Then, we can invoke the pass on the given module. Note that the constant\n# folding pass works at the function-level. That being said, each function in\n# the module will be applied with the optimization. Users don't need to iterate\n# through individual functions manually to apply this pass.\nmod = fold_const(mod)\n# We can see from the updated program that the constants are folded.\nprint(mod)\n\n###############################################################################\n# More optimizations can be applied in the similar manner. For instance, we can\n# eliminate the common expressions that used by `z` and `z1`.\nmod = relay.transform.EliminateCommonSubexpr()(mod)\nprint(mod)\n\n###############################################################################\n# Some optimizations, such as fusion, are parametric as well. For example,\n# opt level 0 will not allow operators to be fused together. Users can pass the\n# `fuse_opt_level` to enable this.\nmod = relay.transform.FuseOps(fuse_opt_level=0)(mod)\n\n# We can observe that the optimized module contains functions that only have\n# a signle primitive op.\nprint(mod)\n\n###############################################################################\n# Use Sequential to Apply a Sequence of Passes\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Applying passes as above is actually tedious and it may require users to have\n# better understanding about the dependencies between them. For example, fusion\n# currently doesn't work well on let bindings. Therefore, we would not be able\n# to fuse operators that were fusable if :py:func:`relay.transform.ToANormalForm` is applied before\n# fusion, as this pass generates let bindings for each expression to\n# canonicalize a Relay program.\n#\n# Relay, hence, provides :py:class:`tvm.transform.Sequential` to alleviate developers from handling\n# these issues explicitly by specifying the required passes of each pass and\n# packing them as a whole to execute. For example, the same passes can now be\n# applied using the sequential style as the following. :py:class:`tvm.transform.Sequential` is\n# similar to `torch.nn.sequential <https://pytorch.org/docs/stable/nn.html#torch.nn.Sequential>`_\n# and `mxnet.gluon.block <https://mxnet.apache.org/api/python/docs/_modules/mxnet/gluon/block.html>`_.\n# For example, `torch.nn.sequential` is used to contain a sequence of PyTorch\n# `Modules` that will be added to build a network. It focuses on the network\n# layers. Instead, the :py:class:`tvm.transform.Sequential` in our pass infra works on the optimizing\n# pass.\n\n# Now let's execute some passes through :py:class:`tvm.transform.Sequential`\nf = example()\nmod = tvm.IRModule.from_expr(f)\n# Glob the interested passes.\nseq = tvm.transform.Sequential(\n    [\n        relay.transform.FoldConstant(),\n        relay.transform.EliminateCommonSubexpr(),\n        relay.transform.FuseOps(fuse_opt_level=2),\n    ]\n)\nmod1 = seq(mod)\nprint(mod1)\n\n###############################################################################\n# From the transformed Relay program, we can see that there are still two\n# identical addition operations. This is because ``EliminateCommonSubexpr``\n# was not actually performed. The reason is because only the passes that have\n# optimization level less or equal to 2 will be executed by default under\n# :py:class:`tvm.transform.Sequential`. The pass infra,\n# however, provides a configuration interface\n# for users to customize the optimization level that they want to execute.\n\nwith tvm.transform.PassContext(opt_level=3):\n    mod2 = seq(mod)\nprint(mod2)\n\n###############################################################################\n# Now we can see that only one of the two identical additions is kept.\n#\n# In addition, users can selectively disable some passes using the\n# `disabled_pass` config, which is similar to the `-fno-xxx` option used the\n# general purpose compilers, such as Clang and GCC. For example, we can disable\n# EliminateCommonSubexpr as following. The printed module will again show two\n# identical addition operations.\n\nwith tvm.transform.PassContext(opt_level=3, disabled_pass=[\"EliminateCommonSubexpr\"]):\n    mod3 = seq(mod)\nprint(mod3)\n\n##############################################################################\n# Implement a Pass Using Python Decorator\n# ------------------------------------------\n# The next example illustrates how we can orchestrate a customized optimization\n# pipeline through the pass infra using Python decorators. This functionality\n# greatly eases the implementation of passes. For example, users can simply\n# define a decorated class to do function-level optimizations as the following\n# example shows. `transform_function` wraps a class to replace all constants\n# with a multiple of `c`. Later on, each function in a given module will be\n# visited and each constant in the function will be replaced when we invoke the\n# customized pass.\n\n\n@relay.transform.function_pass(opt_level=1)\nclass CustomPipeline:\n    \"\"\"Simple test function to replace one argument to another.\"\"\"\n\n    def __init__(self, multiplier):\n        self.multiplier = multiplier\n\n    # This function can define a pass.\n    def transform_function(self, func, mod, ctx):\n        obj = self\n\n        class ReplaceConstant(tvm.relay.ExprMutator):\n            def visit_constant(self, c):\n                return relay.multiply(obj.multiplier, c)\n\n        return ReplaceConstant().visit(func)\n\n\nf = example()\nmod = tvm.IRModule.from_expr(f)\ncustom_pass = CustomPipeline(multiplier=relay.const(3, \"float32\"))\nassert custom_pass.info.name == \"CustomPipeline\"\nmod3 = custom_pass(mod)\nprint(mod3)\n\n##############################################################################\n# Debug a Pass\n# ------------\n# TVM provides users a plug-and-play style debugging pass that print the IR\n# after a certain pass is done through a special pass (``PrintIR``) to dump the IR of the\n# whole module. A slightly modified version of the sequential pass example\n# could be like the following to enable IR dumping for ``FoldConstant`` optimization.\n\nf = example()\nmod = tvm.IRModule.from_expr(f)\nseq = tvm.transform.Sequential(\n    [\n        relay.transform.FoldConstant(),\n        tvm.transform.PrintIR(),\n        relay.transform.EliminateCommonSubexpr(),\n        relay.transform.FuseOps(),\n    ]\n)\n\n###############################################################################\n# By inserting the ``PrintIR`` pass after ``FoldConstant``, the pass infra will\n# dump out the module IR when ``FoldConstant`` is done. Users can plug in this\n# pass after any pass they want to debug for viewing the optimization effect.\n#\n# There is a more flexible debugging mechanism. One can implement a ``PassInstrument``\n# class to execute arbitrary code not only before and/or after each pass but also\n# at entering/exiting ``PassContext``. See :ref:`pass_instrument_cpp_backend`\n# for more details.\n#\n# Here we use :py::func`tvm.instrument.pass_instrument` decorator to implement\n# a PassInsturment class printing IR before execution of each passes:\n\n\n@tvm.instrument.pass_instrument\nclass PrintIR:\n    \"\"\"Print the name of the pass, the IR, only before passes execute.\"\"\"\n\n    def run_before_pass(self, mod, info):\n        print(\"Running pass: {}\", info)\n        print(mod)\n\n\nwith tvm.transform.PassContext(opt_level=3, instruments=[PrintIR()]):\n    with tvm.target.Target(\"llvm\"):\n        # Perform the optimizations.\n        mod = seq(mod)\nprint(mod)\n\nprint(\"done\")\n\n##############################################################################\n# Summary\n# -------\n# This tutorial has covered how we can write and invoke passes in TVM more\n# conveniently using the pass infra. Different ways of invoking a pass are also\n# discussed. Using :py:class:`tvm.transform.Sequential` can largely help\n# users to ease the work of handling multiple optimization passes and their\n# dependencies. In addition, an example is provided to illustrate\n# how we can debug a pass using the ``PrintIR`` and tracing.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/extend_tvm/use_pass_instrument.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long\n\"\"\"\n.. _tutorial-use-pass-instrument:\n\nHow to Use TVM Pass Instrument\n==============================\n**Author**: `Chi-Wei Wang <https://github.com/chiwwang>`_\n\nAs more and more passes are implemented, it becomes useful to instrument\npass execution, analyze per-pass effects, and observe various events.\n\nWe can instrument passes by providing a list of :py:class:`tvm.ir.instrument.PassInstrument`\ninstances to :py:class:`tvm.transform.PassContext`. We provide a pass instrument\nfor collecting timing information (:py:class:`tvm.ir.instrument.PassTimingInstrument`),\nbut an extension mechanism is available via the :py:func:`tvm.instrument.pass_instrument` decorator.\n\nThis tutorial demonstrates how developers can use ``PassContext`` to instrument\npasses. Please also refer to the :ref:`pass-infra`.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nimport tvm.relay as relay\nfrom tvm.relay.testing import resnet\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.ir.instrument import (\n    PassTimingInstrument,\n    pass_instrument,\n)\n\n\n###############################################################################\n# Create An Example Relay Program\n# -------------------------------\n# We use pre-defined resnet-18 network in Relay.\nbatch_size = 1\nnum_of_image_class = 1000\nimage_shape = (3, 224, 224)\noutput_shape = (batch_size, num_of_image_class)\nrelay_mod, relay_params = resnet.get_workload(num_layers=18, batch_size=1, image_shape=image_shape)\nprint(\"Printing the IR module...\")\nprint(relay_mod.astext(show_meta_data=False))\n\n\n###############################################################################\n# Create PassContext With Instruments\n# -----------------------------------\n# To run all passes with an instrument, pass it via the ``instruments`` argument to\n# the ``PassContext`` constructor. A built-in ``PassTimingInstrument`` is used to\n# profile the execution time of each passes.\ntiming_inst = PassTimingInstrument()\nwith tvm.transform.PassContext(instruments=[timing_inst]):\n    relay_mod = relay.transform.InferType()(relay_mod)\n    relay_mod = relay.transform.FoldScaleAxis()(relay_mod)\n    # before exiting the context, get profile results.\n    profiles = timing_inst.render()\nprint(\"Printing results of timing profile...\")\nprint(profiles)\n\n\n###############################################################################\n# Use Current PassContext With Instruments\n# ----------------------------------------\n# One can also use the current ``PassContext`` and register\n# ``PassInstrument`` instances by ``override_instruments`` method.\n# Note that ``override_instruments`` executes ``exit_pass_ctx`` method\n# if any instrument already exists. Then it switches to new instruments\n# and calls ``enter_pass_ctx`` method of new instruments.\n# Refer to following sections and :py:func:`tvm.instrument.pass_instrument` for these methods.\ncur_pass_ctx = tvm.transform.PassContext.current()\ncur_pass_ctx.override_instruments([timing_inst])\nrelay_mod = relay.transform.InferType()(relay_mod)\nrelay_mod = relay.transform.FoldScaleAxis()(relay_mod)\nprofiles = timing_inst.render()\nprint(\"Printing results of timing profile...\")\nprint(profiles)\n\n\n###############################################################################\n# Register empty list to clear existing instruments.\n#\n# Note that ``exit_pass_ctx`` of ``PassTimingInstrument`` is called.\n# Profiles are cleared so nothing is printed.\ncur_pass_ctx.override_instruments([])\n# Uncomment the call to .render() to see a warning like:\n# Warning: no passes have been profiled, did you enable pass profiling?\n# profiles = timing_inst.render()\n\n\n###############################################################################\n# Create Customized Instrument Class\n# ----------------------------------\n# A customized instrument class can be created using the\n# :py:func:`tvm.instrument.pass_instrument` decorator.\n#\n# Let's create an instrument class which calculates the change in number of\n# occurrences of each operator caused by each pass. We can look at ``op.name`` to\n# find the name of each operator. And we do this before and after passes to calculate the difference.\n\n\n@pass_instrument\nclass RelayCallNodeDiffer:\n    def __init__(self):\n        self._op_diff = []\n        # Passes can be nested.\n        # Use stack to make sure we get correct before/after pairs.\n        self._op_cnt_before_stack = []\n\n    def enter_pass_ctx(self):\n        self._op_diff = []\n        self._op_cnt_before_stack = []\n\n    def exit_pass_ctx(self):\n        assert len(self._op_cnt_before_stack) == 0, \"The stack is not empty. Something wrong.\"\n\n    def run_before_pass(self, mod, info):\n        self._op_cnt_before_stack.append((info.name, self._count_nodes(mod)))\n\n    def run_after_pass(self, mod, info):\n        # Pop out the latest recorded pass.\n        name_before, op_to_cnt_before = self._op_cnt_before_stack.pop()\n        assert name_before == info.name, \"name_before: {}, info.name: {} doesn't match\".format(\n            name_before, info.name\n        )\n        cur_depth = len(self._op_cnt_before_stack)\n        op_to_cnt_after = self._count_nodes(mod)\n        op_diff = self._diff(op_to_cnt_after, op_to_cnt_before)\n        # only record passes causing differences.\n        if op_diff:\n            self._op_diff.append((cur_depth, info.name, op_diff))\n\n    def get_pass_to_op_diff(self):\n        \"\"\"\n        return [\n          (depth, pass_name, {op_name: diff_num, ...}), ...\n        ]\n        \"\"\"\n        return self._op_diff\n\n    @staticmethod\n    def _count_nodes(mod):\n        \"\"\"Count the number of occurrences of each operator in the module\"\"\"\n        ret = {}\n\n        def visit(node):\n            if isinstance(node, relay.expr.Call):\n                if hasattr(node.op, \"name\"):\n                    op_name = node.op.name\n                else:\n                    # Some CallNode may not have 'name' such as relay.Function\n                    return\n                ret[op_name] = ret.get(op_name, 0) + 1\n\n        relay.analysis.post_order_visit(mod[\"main\"], visit)\n        return ret\n\n    @staticmethod\n    def _diff(d_after, d_before):\n        \"\"\"Calculate the difference of two dictionary along their keys.\n        The result is values in d_after minus values in d_before.\n        \"\"\"\n        ret = {}\n        key_after, key_before = set(d_after), set(d_before)\n        for k in key_before & key_after:\n            tmp = d_after[k] - d_before[k]\n            if tmp:\n                ret[k] = d_after[k] - d_before[k]\n        for k in key_after - key_before:\n            ret[k] = d_after[k]\n        for k in key_before - key_after:\n            ret[k] = -d_before[k]\n        return ret\n\n\n###############################################################################\n# Apply Passes and Multiple Instrument Classes\n# --------------------------------------------\n# We can use multiple instrument classes in a ``PassContext``.\n# However, it should be noted that instrument methods are executed sequentially,\n# obeying the order of ``instruments`` argument.\n# So for instrument classes like ``PassTimingInstrument``, it is inevitable to\n# count-up the execution time of other instrument classes to the final\n# profile result.\ncall_node_inst = RelayCallNodeDiffer()\ndesired_layouts = {\n    \"nn.conv2d\": [\"NHWC\", \"HWIO\"],\n}\npass_seq = tvm.transform.Sequential(\n    [\n        relay.transform.FoldConstant(),\n        relay.transform.ConvertLayout(desired_layouts),\n        relay.transform.FoldConstant(),\n    ]\n)\nrelay_mod[\"main\"] = bind_params_by_name(relay_mod[\"main\"], relay_params)\n# timing_inst is put after call_node_inst.\n# So the execution time of ``call_node.inst.run_after_pass()`` is also counted.\nwith tvm.transform.PassContext(opt_level=3, instruments=[call_node_inst, timing_inst]):\n    relay_mod = pass_seq(relay_mod)\n    profiles = timing_inst.render()\n# Uncomment the next line to see timing-profile results.\n# print(profiles)\n\n\n###############################################################################\n# We can see how many CallNode increase/decrease per op type.\nfrom pprint import pprint\n\nprint(\"Printing the change in number of occurrences of each operator caused by each pass...\")\npprint(call_node_inst.get_pass_to_op_diff())\n\n\n###############################################################################\n# Exception Handling\n# ------------------\n# Let's see what happens if an exception occurs in a method of a ``PassInstrument``.\n#\n# Define ``PassInstrument`` classes which raise exceptions in enter/exit ``PassContext``:\nclass PassExampleBase:\n    def __init__(self, name):\n        self._name = name\n\n    def enter_pass_ctx(self):\n        print(self._name, \"enter_pass_ctx\")\n\n    def exit_pass_ctx(self):\n        print(self._name, \"exit_pass_ctx\")\n\n    def should_run(self, mod, info):\n        print(self._name, \"should_run\")\n        return True\n\n    def run_before_pass(self, mod, pass_info):\n        print(self._name, \"run_before_pass\")\n\n    def run_after_pass(self, mod, pass_info):\n        print(self._name, \"run_after_pass\")\n\n\n@pass_instrument\nclass PassFine(PassExampleBase):\n    pass\n\n\n@pass_instrument\nclass PassBadEnterCtx(PassExampleBase):\n    def enter_pass_ctx(self):\n        print(self._name, \"bad enter_pass_ctx!!!\")\n        raise ValueError(\"{} bad enter_pass_ctx\".format(self._name))\n\n\n@pass_instrument\nclass PassBadExitCtx(PassExampleBase):\n    def exit_pass_ctx(self):\n        print(self._name, \"bad exit_pass_ctx!!!\")\n        raise ValueError(\"{} bad exit_pass_ctx\".format(self._name))\n\n\n###############################################################################\n# If an exception occurs in ``enter_pass_ctx``, ``PassContext`` will disable the pass\n# instrumentation. And it will run the ``exit_pass_ctx`` of each ``PassInstrument``\n# which successfully finished ``enter_pass_ctx``.\n#\n# In following example, we can see ``exit_pass_ctx`` of `PassFine_0` is executed after exception.\ndemo_ctx = tvm.transform.PassContext(\n    instruments=[\n        PassFine(\"PassFine_0\"),\n        PassBadEnterCtx(\"PassBadEnterCtx\"),\n        PassFine(\"PassFine_1\"),\n    ]\n)\ntry:\n    with demo_ctx:\n        relay_mod = relay.transform.InferType()(relay_mod)\nexcept ValueError as ex:\n    print(\"Catching\", str(ex).split(\"\\n\")[-1])\n\n###############################################################################\n# Exceptions in ``PassInstrument`` instances cause all instruments of the current ``PassContext``\n# to be cleared, so nothing is printed when ``override_instruments`` is called.\ndemo_ctx.override_instruments([])  # no PassFine_0 exit_pass_ctx printed....etc\n\n###############################################################################\n# If an exception occurs in ``exit_pass_ctx``, then the pass instrument is disabled.\n# Then exception is propagated. That means ``PassInstrument`` instances registered\n# after the one throwing the exception do not execute ``exit_pass_ctx``.\ndemo_ctx = tvm.transform.PassContext(\n    instruments=[\n        PassFine(\"PassFine_0\"),\n        PassBadExitCtx(\"PassBadExitCtx\"),\n        PassFine(\"PassFine_1\"),\n    ]\n)\ntry:\n    # PassFine_1 execute enter_pass_ctx, but not exit_pass_ctx.\n    with demo_ctx:\n        relay_mod = relay.transform.InferType()(relay_mod)\nexcept ValueError as ex:\n    print(\"Catching\", str(ex).split(\"\\n\")[-1])\n\n###############################################################################\n# Exceptions occurred in ``should_run``, ``run_before_pass``, ``run_after_pass``\n# are not handled explicitly -- we rely on the context manager (the ``with`` syntax)\n# to exit ``PassContext`` safely.\n#\n# We use ``run_before_pass`` as an example:\n@pass_instrument\nclass PassBadRunBefore(PassExampleBase):\n    def run_before_pass(self, mod, pass_info):\n        print(self._name, \"bad run_before_pass!!!\")\n        raise ValueError(\"{} bad run_before_pass\".format(self._name))\n\n\ndemo_ctx = tvm.transform.PassContext(\n    instruments=[\n        PassFine(\"PassFine_0\"),\n        PassBadRunBefore(\"PassBadRunBefore\"),\n        PassFine(\"PassFine_1\"),\n    ]\n)\ntry:\n    # All exit_pass_ctx are called.\n    with demo_ctx:\n        relay_mod = relay.transform.InferType()(relay_mod)\nexcept ValueError as ex:\n    print(\"Catching\", str(ex).split(\"\\n\")[-1])\n\n###############################################################################\n# Also note that pass instrumentation is not disable. So if we call\n# ``override_instruments``, the ``exit_pass_ctx`` of old registered ``PassInstrument``\n# is called.\ndemo_ctx.override_instruments([])\n\n###############################################################################\n# If we don't wrap pass execution with ``with`` syntax, ``exit_pass_ctx`` is not\n# called. Let try this with current ``PassContext``:\ncur_pass_ctx = tvm.transform.PassContext.current()\ncur_pass_ctx.override_instruments(\n    [\n        PassFine(\"PassFine_0\"),\n        PassBadRunBefore(\"PassBadRunBefore\"),\n        PassFine(\"PassFine_1\"),\n    ]\n)\n\n###############################################################################\n# Then call passes. ``exit_pass_ctx`` is not executed after the exception,\n# as expectation.\ntry:\n    # No ``exit_pass_ctx`` got executed.\n    relay_mod = relay.transform.InferType()(relay_mod)\nexcept ValueError as ex:\n    print(\"Catching\", str(ex).split(\"\\n\")[-1])\n\n###############################################################################\n# Clear instruments.\ncur_pass_ctx.override_instruments([])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/optimize_operators/opt_conv_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _opt-conv-gpu:\n\nHow to optimize convolution on GPU\n==================================\n**Author**: `Haichen Shen <https://homes.cs.washington.edu/~haichen/>`_\n\nIn this tutorial, we will demonstrate how to write a high performance\nconvolution implementation in TVM. We use square size input tensors and filters\nas an example, and assume the input to convolution has a large batch. In this\nexample, we use a different layout to store the data in order to achieve better\ndata locality. The buffer layout is HWCN, which stands for height, width,\nchannel, batch.\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################\n# Preparation and Algorithm\n# -------------------------\n#\n# We use the fixed size for input tensors with 256 channels and 14 x 14\n# dimensions. The batch size is 256. Convolution filters contain 512 filters\n# of size 3 x 3.  We use stride size 1 and padding size 1 for the\n# convolution. The following code defines the convolution algorithm in TVM.\n#\n\nimport numpy as np\nimport tvm\nfrom tvm import te\n\n# The sizes of inputs and filters\nbatch = 256\nin_channel = 256\nout_channel = 512\nin_size = 14\nkernel = 3\npad = 1\nstride = 1\n\n# Algorithm\nA = te.placeholder((in_size, in_size, in_channel, batch), name=\"A\")\nW = te.placeholder((kernel, kernel, in_channel, out_channel), name=\"W\")\nout_size = (in_size - kernel + 2 * pad) // stride + 1\n# Pad input\nApad = te.compute(\n    (in_size + 2 * pad, in_size + 2 * pad, in_channel, batch),\n    lambda yy, xx, cc, nn: tvm.tir.if_then_else(\n        tvm.tir.all(yy >= pad, yy - pad < in_size, xx >= pad, xx - pad < in_size),\n        A[yy - pad, xx - pad, cc, nn],\n        tvm.tir.const(0.0, \"float32\"),\n    ),\n    name=\"Apad\",\n)\n# Create reduction variables\nrc = te.reduce_axis((0, in_channel), name=\"rc\")\nry = te.reduce_axis((0, kernel), name=\"ry\")\nrx = te.reduce_axis((0, kernel), name=\"rx\")\n# Compute the convolution\nB = te.compute(\n    (out_size, out_size, out_channel, batch),\n    lambda yy, xx, ff, nn: te.sum(\n        Apad[yy * stride + ry, xx * stride + rx, rc, nn] * W[ry, rx, rc, ff], axis=[ry, rx, rc]\n    ),\n    name=\"B\",\n)\n\n\n###############################################################################\n# Memory Hierarchy\n# ----------------\n#\n# We first specify the memory hierarchy for buffers. The figure below shows the\n# GPU memory hierarchy. One important difference from CPU memory hierarchy is\n# that GPU provides a cache buffer called shared memory, which is managed by\n# programmers. Thus how to maximize the data reuse in the shared memory is\n# critical to achieve high performance in GPU kernels.\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/gpu_memory_hierarchy.png\n#      :align: center\n#      :height: 319px\n#      :width: 271px\n#\n# In this example, we load both Apad and W into buffer AA and WW, which are\n# stored in the shared memory. These buffers will be later shared by all\n# threads within the same thread block to compute the convolution. Each thread\n# then loads its own part from shared buffer into their local registers, AL and\n# WL. BL is a local cache of output B, which is also stored in the thread local\n# registers.\n#\n\n# Designate the memory hierarchy\ns = te.create_schedule(B.op)\ns[Apad].compute_inline()  # compute Apad inline\nAA = s.cache_read(Apad, \"shared\", [B])\nWW = s.cache_read(W, \"shared\", [B])\nAL = s.cache_read(AA, \"local\", [B])\nWL = s.cache_read(WW, \"local\", [B])\nBL = s.cache_write(B, \"local\")\n\n###############################################################################\n# Blocking\n# --------\n#\n# The following code splits the workload into thread blocks and individual\n# threads. We follow the blocking scheme in the matrix multiply. As shown in the\n# figure below, given a pixel coordinate (y, x), a thread block is responsible\n# for computing a region of block_factor x block_factor (64 x 64) for output\n# channels and batch. Due to the limit of shared memory space, we only load step\n# x block_factor (8 x 64) data from Apad and B each time to buffers in the\n# shared memory.\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/conv_gpu_blocking.png\n#      :align: center\n#      :height: 308px\n#      :width: 317px\n#\n\n# tile consts\ntile = 8\nnum_thread = 8\nblock_factor = tile * num_thread\nstep = 8\nvthread = 2\n\n# Get the GPU thread indices\nblock_x = te.thread_axis(\"blockIdx.x\")\nblock_y = te.thread_axis(\"blockIdx.y\")\nblock_z = te.thread_axis(\"blockIdx.z\")\nthread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\nthread_y = te.thread_axis((0, num_thread), \"threadIdx.y\")\nthread_xz = te.thread_axis((0, vthread), \"vthread\", name=\"vx\")\nthread_yz = te.thread_axis((0, vthread), \"vthread\", name=\"vy\")\n\n# Split the workloads\nhi, wi, fi, ni = s[B].op.axis\nbz = s[B].fuse(hi, wi)\nby, fi = s[B].split(fi, factor=block_factor)\nbx, ni = s[B].split(ni, factor=block_factor)\n\n# Bind the iteration variables to GPU thread indices\ns[B].bind(bz, block_z)\ns[B].bind(by, block_y)\ns[B].bind(bx, block_x)\n\n###############################################################################\n# Virtual Thread Split\n# --------------------\n#\n# We further split the workload from a thread block to individual threads. To\n# avoid *memory bank conflict*, we use virtual thread to split the area into 4\n# parts, and then tile into 8x8 grids. Therefore, shown in the figure below,\n# each thread computes 4 strided grids, where size of each grid is 4 x 4.\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/conv_gpu_vthread.png\n#      :align: center\n#      :height: 188px\n#      :width: 268px\n#\n\ntyz, fi = s[B].split(fi, nparts=vthread)  # virtual thread split\ntxz, ni = s[B].split(ni, nparts=vthread)  # virtual thread split\nty, fi = s[B].split(fi, nparts=num_thread)\ntx, ni = s[B].split(ni, nparts=num_thread)\ns[B].reorder(bz, by, bx, tyz, txz, ty, tx, fi, ni)\n\ns[B].bind(tyz, thread_yz)\ns[B].bind(txz, thread_xz)\ns[B].bind(ty, thread_y)\ns[B].bind(tx, thread_x)\n\n###############################################################################\n# Cooperative Fetching\n# --------------------\n#\n# As mentioned before, each time step we need to transfer step x block_factor\n# data from GPU global memory to shared memory. In order to reduce the memory\n# transfer per thread, the following code lets threads in the same thread block\n# coopertively fetch dependent data from global memory.\n#\n\n\n# Schedule BL local write\ns[BL].compute_at(s[B], tx)\nyi, xi, fi, ni = s[BL].op.axis\nry, rx, rc = s[BL].op.reduce_axis\nrco, rci = s[BL].split(rc, factor=step)\ns[BL].reorder(rco, ry, rx, rci, fi, ni)\n\n# Attach computation to iteration variables\ns[AA].compute_at(s[BL], rx)\ns[WW].compute_at(s[BL], rx)\ns[AL].compute_at(s[BL], rci)\ns[WL].compute_at(s[BL], rci)\n\n# Schedule for A's shared memory load\nyi, xi, ci, ni = s[AA].op.axis\nty, ci = s[AA].split(ci, nparts=num_thread)\ntx, ni = s[AA].split(ni, nparts=num_thread)\n_, ni = s[AA].split(ni, factor=4)\ns[AA].reorder(ty, tx, yi, xi, ci, ni)\ns[AA].bind(ty, thread_y)\ns[AA].bind(tx, thread_x)\ns[AA].vectorize(ni)  # vectorize memory load\n\n# Schedule for W's shared memory load\nyi, xi, ci, fi = s[WW].op.axis\nty, ci = s[WW].split(ci, nparts=num_thread)\ntx, fi = s[WW].split(fi, nparts=num_thread)\n_, fi = s[WW].split(fi, factor=4)\ns[WW].reorder(ty, tx, yi, xi, ci, fi)\ns[WW].bind(ty, thread_y)\ns[WW].bind(tx, thread_x)\ns[WW].vectorize(fi)  # vectorize memory load\n\n\n###############################################################################\n# Generate CUDA Kernel\n# --------------------\n#\n# Finally we use TVM to generate and compile the CUDA kernel, and evaluate the\n# latency of convolution.\n#\n\nfunc = tvm.build(s, [A, W, B], \"cuda\")\ndev = tvm.cuda(0)\na_np = np.random.uniform(size=(in_size, in_size, in_channel, batch)).astype(A.dtype)\nw_np = np.random.uniform(size=(kernel, kernel, in_channel, out_channel)).astype(W.dtype)\na = tvm.nd.array(a_np, dev)\nw = tvm.nd.array(w_np, dev)\nb = tvm.nd.array(np.zeros((out_size, out_size, out_channel, batch), dtype=B.dtype), dev)\nfunc(a, w, b)\nevaluator = func.time_evaluator(func.entry_name, dev, number=1)\nprint(\"Convolution: %f ms\" % (evaluator(a, w, b).mean * 1e3))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/optimize_operators/opt_conv_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _opt-conv-tensorcore:\n\nHow to optimize convolution using TensorCores\n=============================================\n**Author**: `Siyuan Feng <https://github.com/Hzfengsy>`_\n\nIn this tutorial, we will demonstrate how to write a high performance convolution\nschedule using TensorCores in TVM. In this example, we assume the input to\nconvolution has a large batch. We strongly recommend covering the :ref:`opt-conv-gpu` tutorial first.\n\n\"\"\"\n\n################################################################\n# TensorCore Introduction\n# -----------------------\n# Each Tensor Core provides a 4x4x4 matrix processing array that operates\n# :code:`D = A * B + C`, where A, B, C and D are 4x4 matrices as Figure shows.\n# The matrix multiplication inputs A and B are FP16 matrices, while the accumulation\n# matrices C and D may be FP16 or FP32 matrices.\n#\n# However, CUDA programmers can only use warp-level primitive\n# :code:`wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag)` to perform\n# 16x16x16 half-precision matrix multiplication on tensor cores. Before invoking\n# the matrix multiplication, programmers must load data from memory into registers\n# with primitive :code:`wmma::load_matrix_sync`, explicitly. The NVCC compiler translates\n# that primitive into multiple memory load instructions. At run time, every thread loads\n# 16 elements from matrix A and 16 elements from B.\n\n################################################################\n# Preparation and Algorithm\n# -------------------------\n# We use the fixed size for input tensors with 256 channels and 14 x 14 dimensions.\n# The batch size is 256. Convolution filters contain 512 filters of size 3 x 3.\n# We use stride size 1 and padding size 1 for the convolution. In the example, we use\n# NHWCnc memory layout.The following code defines the convolution algorithm in TVM.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import nvcc\n\n# The sizes of inputs and filters\nbatch_size = 256\nheight = 14\nwidth = 14\nin_channels = 256\nout_channels = 512\nkernel_h = 3\nkernel_w = 3\npad_h = 1\npad_w = 1\nstride_h = 1\nstride_w = 1\n\n# TensorCore shape\nblock_size = 16\n\nassert batch_size % block_size == 0\nassert in_channels % block_size == 0\nassert out_channels % block_size == 0\n\n# Input feature map: (N, H, W, IC, n, ic)\ndata_shape = (\n    batch_size // block_size,\n    height,\n    width,\n    in_channels // block_size,\n    block_size,\n    block_size,\n)\n# Kernel: (H, W, IC, OC, ic, oc)\nkernel_shape = (\n    kernel_h,\n    kernel_w,\n    in_channels // block_size,\n    out_channels // block_size,\n    block_size,\n    block_size,\n)\n# Output feature map: (N, H, W, OC, n, oc)\noutput_shape = (\n    batch_size // block_size,\n    height,\n    width,\n    out_channels // block_size,\n    block_size,\n    block_size,\n)\n\n# Reduction axes\nkh = te.reduce_axis((0, kernel_h), name=\"kh\")\nkw = te.reduce_axis((0, kernel_w), name=\"kw\")\nic = te.reduce_axis((0, in_channels // block_size), name=\"ic\")\nii = te.reduce_axis((0, block_size), name=\"ii\")\n\n# Algorithm\nA = te.placeholder(data_shape, name=\"A\", dtype=\"float16\")\nW = te.placeholder(kernel_shape, name=\"W\", dtype=\"float16\")\nApad = te.compute(\n    (\n        batch_size // block_size,\n        height + 2 * pad_h,\n        width + 2 * pad_w,\n        in_channels // block_size,\n        block_size,\n        block_size,\n    ),\n    lambda n, h, w, i, nn, ii: tvm.tir.if_then_else(\n        tvm.tir.all(h >= pad_h, h - pad_h < height, w >= pad_w, w - pad_w < width),\n        A[n, h - pad_h, w - pad_w, i, nn, ii],\n        tvm.tir.const(0.0, \"float16\"),\n    ),\n    name=\"Apad\",\n)\nConv = te.compute(\n    output_shape,\n    lambda n, h, w, o, nn, oo: te.sum(\n        Apad[n, h * stride_h + kh, w * stride_w + kw, ic, nn, ii].astype(\"float32\")\n        * W[kh, kw, ic, o, ii, oo].astype(\"float32\"),\n        axis=[ic, kh, kw, ii],\n    ),\n    name=\"Conv\",\n)\n\ns = te.create_schedule(Conv.op)\ns[Apad].compute_inline()\n\n###############################################################################\n# Memory Scope\n# ------------\n# In traditional GPU schedule, we have global, shared and local memory scope.\n# To support TensorCores, we add another three special memory scope: :code:`wmma.matrix_a`,\n# :code:`wmma.matrix_b` and :code:`wmma.accumulator`. On hardware, all fragments scope\n# stores at the on-chip registers level, the same place with local memory.\n\n# Designate the memory hierarchy\nAS = s.cache_read(Apad, \"shared\", [Conv])\nWS = s.cache_read(W, \"shared\", [Conv])\nAF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\nWF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\nConvF = s.cache_write(Conv, \"wmma.accumulator\")\n\n###############################################################################\n# Define Tensor Intrinsic\n# -----------------------\n# In fact, TensorCore is a special hardware operation. So, we can just use tensorize\n# to replace a unit of computation with the TensorCore instruction. The first thing is\n# that we need to define tensor intrinsic.\n#\n# There are four basic operation in TensorCore: :code:`fill_fragment`, :code:`load_matrix`,\n# :code:`mma_sync` and :code:`store_matrix`. Since :code:`fill_fragment` and :code:`mma_sync`\n# are both used in matrix multiplication, so we can just write following three intrinsics.\n\n\ndef intrin_wmma_load_matrix(scope):\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float16\")\n    BA = tvm.tir.decl_buffer(A.shape, A.dtype, scope=\"shared\", data_alignment=32, offset_factor=256)\n    C = te.compute((n, n), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(C.shape, C.dtype, scope=scope, data_alignment=32, offset_factor=256)\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_load_matrix_sync\",\n                BC.data,\n                n,\n                n,\n                n,\n                BC.elem_offset // 256,\n                BA.access_ptr(\"r\"),\n                n,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_gemm():\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((n, n), name=\"B\", dtype=\"float16\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    C = te.compute(\n        (n, n),\n        lambda ii, jj: te.sum(A[ii, k].astype(\"float\") * B[k, jj].astype(\"float\"), axis=k),\n        name=\"C\",\n    )\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, name=\"BA\", scope=\"wmma.matrix_a\", data_alignment=32, offset_factor=256\n    )\n    BB = tvm.tir.decl_buffer(\n        B.shape, B.dtype, name=\"BB\", scope=\"wmma.matrix_b\", data_alignment=32, offset_factor=256\n    )\n    BC = tvm.tir.decl_buffer(\n        C.shape, C.dtype, name=\"BC\", scope=\"wmma.accumulator\", data_alignment=32, offset_factor=256\n    )\n\n    def intrin_func(ins, outs):\n        BA, BB = ins\n        (BC,) = outs\n\n        def init():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\", \"tir.tvm_fill_fragment\", BC.data, n, n, n, BC.elem_offset // 256, 0.0\n                )\n            )\n            return ib.get()\n\n        def update():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_mma_sync\",\n                    BC.data,\n                    BC.elem_offset // 256,\n                    BA.data,\n                    BA.elem_offset // 256,\n                    BB.data,\n                    BB.elem_offset // 256,\n                    BC.data,\n                    BC.elem_offset // 256,\n                )\n            )\n            return ib.get()\n\n        return update(), init(), update()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, B: BB, C: BC})\n\n\ndef intrin_wmma_store_matrix():\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float32\")\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"wmma.accumulator\", data_alignment=32, offset_factor=256\n    )\n    C = te.compute((n, n), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(C.shape, C.dtype, scope=\"global\", data_alignment=32, offset_factor=256)\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_store_matrix_sync\",\n                BA.data,\n                n,\n                n,\n                n,\n                BA.elem_offset // 256,\n                BC.access_ptr(\"w\"),\n                n,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\n###############################################################################\n# Scheduling the Computation\n# --------------------------\n# To use TensorCores in TVM, we must schedule the computation into specific structure\n# to match the tensor intrinsic. The same as traditional GPU programs, we can also use\n# shared memory to boost the speed. If you have any questions about blocking and shared\n# memory, please refer :ref:`opt-conv-gpu`.\n#\n# In this example, each block contains 2x4 warps, and each warp calls 4x2 TensorCore\n# instructions. Thus, the output shape of each warp is 64x32 and each block outputs\n# 128x128 titles. Due to the limit of shared memory space, we only load 2 blocks (2x128x128 tiles)\n# one time.\n#\n# .. note::\n#\n#   *Warp-level Operation*\n#\n#   Note that all TensorCore instructions are warp-level instructions, which means all 32 threads\n#   in a warp should do this instruction simultaneously. Making threadIdx.x extent=32 is one of the\n#   easiest way to solve this. Then We can bind threadIdx.x to any loops except those contain\n#   TensorCore intrinsics directly or indirectly. Also note that it is not the unique solution.\n#   The only thing we should do is to make sure all threads in a warp can call TensorCore at the same time.\n\n# Define tiling sizes\nblock_row_warps = 4\nblock_col_warps = 2\nwarp_row_tiles = 2\nwarp_col_tiles = 4\nwarp_size = 32\nchunk = 2\n\nblock_x = te.thread_axis(\"blockIdx.x\")\nblock_y = te.thread_axis(\"blockIdx.y\")\nblock_z = te.thread_axis(\"blockIdx.z\")\nthread_x = te.thread_axis(\"threadIdx.x\")\nthread_y = te.thread_axis(\"threadIdx.y\")\nthread_z = te.thread_axis(\"threadIdx.z\")\n\nnc, hc, wc, oc, nnc, ooc = Conv.op.axis\nblock_k = s[Conv].fuse(hc, wc)\ns[Conv].bind(block_k, block_z)\nnc, nci = s[Conv].split(nc, factor=warp_row_tiles)\nblock_i, nc = s[Conv].split(nc, factor=block_row_warps)\noc, oci = s[Conv].split(oc, factor=warp_col_tiles)\nblock_j, oc = s[Conv].split(oc, factor=block_col_warps)\ns[Conv].reorder(block_k, block_i, block_j, nc, oc, nci, oci, nnc, ooc)\ns[Conv].bind(block_i, block_x)\ns[Conv].bind(block_j, block_y)\ns[Conv].bind(nc, thread_y)\ns[Conv].bind(oc, thread_z)\n\n# Schedule local computation\ns[ConvF].compute_at(s[Conv], oc)\nn, h, w, o, nnf, oof = ConvF.op.axis\nko, ki = s[ConvF].split(ic, factor=chunk)\ns[ConvF].reorder(ko, kh, ki, kw, n, o, nnf, oof, ii)\n\n# Move intermediate computation into each output compute tile\ns[AF].compute_at(s[ConvF], kw)\ns[WF].compute_at(s[ConvF], kw)\n\n# Schedule for A's share memory\ns[AS].compute_at(s[ConvF], kh)\nn, h, w, i, nn, ii = AS.op.axis\ntx, xo = s[AS].split(n, nparts=block_row_warps)\nty, yo = s[AS].split(xo, nparts=block_col_warps)\nt = s[AS].fuse(nn, ii)\nto, ti = s[AS].split(t, factor=warp_size)\ns[AS].bind(tx, thread_y)\ns[AS].bind(ty, thread_z)\ns[AS].bind(ti, thread_x)\n\n# Schedule for W's share memory\ns[WS].compute_at(s[ConvF], kh)\nkh, kw, ic, o, ii, oo = WS.op.axis\ntx, xo = s[WS].split(o, nparts=block_row_warps)\nty, yo = s[WS].split(xo, nparts=block_col_warps)\nt = s[WS].fuse(ii, oo)\nto, ti = s[WS].split(t, nparts=warp_size)\ns[WS].bind(tx, thread_y)\ns[WS].bind(ty, thread_z)\ns[WS].bind(to, thread_x)\ns[WS].vectorize(ti)\nprint(tvm.lower(s, [A, W, Conv], simple_mode=True))\n\n###############################################################################\n# Lowering Computation to Intrinsics\n# ----------------------------------\n# The last phase is to lower the computation loops down to TensorCore hardware intrinsics\n# by mapping the 2D convolution to tensor intrinsics\n\ns[AF].tensorize(AF.op.axis[-2], intrin_wmma_load_matrix(\"wmma.matrix_a\"))\ns[WF].tensorize(WF.op.axis[-2], intrin_wmma_load_matrix(\"wmma.matrix_b\"))\ns[Conv].tensorize(nnc, intrin_wmma_store_matrix())\ns[ConvF].tensorize(nnf, intrin_wmma_gemm())\nprint(tvm.lower(s, [A, W, Conv], simple_mode=True))\n\n###############################################################################\n# Generate CUDA Kernel\n# --------------------\n# Finally we use TVM to generate and compile the CUDA kernel, and evaluate the latency of convolution.\n# Since TensorCores are only supported in NVIDIA GPU with Compute Capability 7.0 or higher, it may not\n# be able to run on our build server\n\ndev = tvm.cuda(0)\nif nvcc.have_tensorcore(dev.compute_version):\n    with tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"auto_max_step\": 16}}):\n        func = tvm.build(s, [A, W, Conv], \"cuda\")\n    a_np = np.random.uniform(size=data_shape).astype(A.dtype)\n    w_np = np.random.uniform(size=kernel_shape).astype(W.dtype)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    c = tvm.nd.array(np.zeros(output_shape, dtype=Conv.dtype), dev)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=10)\n    print(\"conv2d with tensor core: %f ms\" % (evaluator(a, w, c).mean * 1e3))\n\n###############################################################################\n# Summary\n# -------\n# This tutorial demonstrates how TVM scheduling primitives can be used to\n# call TensorCores on specific GPUs.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/optimize_operators/opt_gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _opt-gemm:\n\nHow to optimize GEMM on CPU\n===========================\n**Author**: `Jian Weng <https://github.com/were>`_, \\\n            `Ruofei Yu <https://github.com/yuruofeifei>`_\n\n(TL;DR) TVM provides abstract interfaces which allows users to depict an algorithm and the\nalgorithm's implementing organization (the so-called schedule) separately. Typically, writing\nalgorithm in high-performance schedule breaks the algorithm's readability and modularity. Also,\ntrying various seemingly promising schedules is time-consuming. With the help of TVM, we can\ntry these schedules efficiently to enhance the performance.\n\nIn this tutorial, we will demonstrate how to use TVM to optimize square matrix multiplication\nand achieve 200 times faster than baseline by simply adding 18 extra lines of code.\n\nThere are two important optimizations on intense computation applications executed on CPU:\n    1. Increase the cache hit rate of memory access. Both complex numerical computation and hot-spot\n       memory access can be accelerated from high cache hit rate. This requires us to transform the\n       origin memory access pattern to the pattern fits the cache policy.\n    2. SIMD (Single instruction multi-data), or we call it vector processing unit. Every time, a\n       small batch of data, rather than a single grid, will be processed. This requires us to\n       transform the data access pattern in the loop body in uniform pattern so that the LLVM\n       backend can lower it to SIMD.\n\nActually, all the methodologies used in this tutorial is a subset of tricks mentioned in this\n`repo <https://github.com/flame/how-to-optimize-gemm>`_. Some of them have been applied by TVM\nabstraction automatically, but some of them cannot be simply applied due to TVM constraints.\n\nAll the experiment results mentioned below, are executed on 2015's 15' MacBook equipped with\nIntel i7-4770HQ CPU. The cache line size should be 64 bytes for all the x86 CPUs.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################################\n# Preparation and Baseline\n# ------------------------\n# In this tutorial, we will demo how to use TVM to optimize matrix multiplication.\n# Before actually demonstrating, we first define these variables.\n# Then we write a baseline implementation, the simplest way to write a matrix multiplication in TVM.\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy\nimport timeit\n\n# The size of the matrix\n# (M, K) x (K, N)\n# You are free to try out different shapes, sometimes TVM optimization outperforms numpy with MKL.\nM = 1024\nK = 1024\nN = 1024\n\n# The default tensor type in tvm\ndtype = \"float32\"\n\n# using Intel AVX2(Advanced Vector Extensions) ISA for SIMD\n# To get the best performance, please change the following line\n# to llvm -mcpu=core-avx2, or specific type of CPU you use\ntarget = \"llvm\"\ndev = tvm.device(target, 0)\n\n# Random generated tensor for testing\na = tvm.nd.array(numpy.random.rand(M, K).astype(dtype), dev)\nb = tvm.nd.array(numpy.random.rand(K, N).astype(dtype), dev)\n\nnp_repeat = 100\nnp_runing_time = timeit.timeit(\n    setup=\"import numpy\\n\"\n    \"M = \" + str(M) + \"\\n\"\n    \"K = \" + str(K) + \"\\n\"\n    \"N = \" + str(N) + \"\\n\"\n    'dtype = \"float32\"\\n'\n    \"a = numpy.random.rand(M, K).astype(dtype)\\n\"\n    \"b = numpy.random.rand(K, N).astype(dtype)\\n\",\n    stmt=\"answer = numpy.dot(a, b)\",\n    number=np_repeat,\n)\nprint(\"Numpy running time: %f\" % (np_runing_time / np_repeat))\n\nanswer = numpy.dot(a.numpy(), b.numpy())\n\n# Algorithm\nk = te.reduce_axis((0, K), \"k\")\nA = te.placeholder((M, K), name=\"A\")\nB = te.placeholder((K, N), name=\"B\")\nC = te.compute((M, N), lambda m, n: te.sum(A[m, k] * B[k, n], axis=k), name=\"C\")\n\n# Default schedule\ns = te.create_schedule(C.op)\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=1)\nprint(\"Baseline: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# In TVM, we can always inspect lower level IR to debug or optimize our schedule.\n# Here is the generated IR using our baseline schedule.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################################\n# Blocking\n# --------\n# A important trick to enhance the cache hit rate is blocking --- data chunk will be computed\n# block by block. The memory access inside the block is a small neighbourhood which is with high\n# memory locality. In this tutorial, I picked up 32 as the blocking factor. So the block will\n# fill 32 * 32 * sizeof(float) which is 4KB in the cache whose total size is 32KB (L1 data cache)\n\nbn = 32\nkfactor = 4\ns = te.create_schedule(C.op)\n\n# Blocking by loop tiling\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(kaxis,) = s[C].op.reduce_axis\nko, ki = s[C].split(kaxis, factor=kfactor)\n\n# Hoist reduction domain outside the blocking loop\ns[C].reorder(mo, no, ko, ki, mi, ni)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\n# By simply tiling the loop 32x32, and hoisting ko, ki outside the blocking loops,\n# we can see big speedup compared with the baseline.\nevaluator = func.time_evaluator(func.entry_name, dev, number=10)\nprint(\"Opt1: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# Here is the generated IR after blocking.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n###################################################################################################\n# Vectorization\n# -------------\n# Another important trick is vectorization. When the memory access pattern is uniform,\n# the compiler can detect this pattern and pass the continuous memory to vector processor. In TVM,\n# we can use `vectorize` interface to hint the compiler this pattern, so that we can accelerate it\n# vastly.\n#\n# In this tutorial, we chose to vectorize the inner loop row data since it is cache friendly.\n\ns = te.create_schedule(C.op)\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(kaxis,) = s[C].op.reduce_axis\nko, ki = s[C].split(kaxis, factor=kfactor)\n\ns[C].reorder(mo, no, ko, ki, mi, ni)\n\n# Vectorization\ns[C].vectorize(ni)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=10)\nprint(\"Opt2: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# Here is the generated IR after vectorization.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n###################################################################################################\n# Loop Permutation\n# ----------------\n# If we look at the above IR, we can see the inner loop row data is vectorized for both B and C.\n# Next we will look at the access pattern of A. In current schedule, A is accessed column by column\n# which is not cache friendly. If we change the nested loop order of ki and inner axes mi,\n# the access pattern for A matrix is more cache friendly.\n\ns = te.create_schedule(C.op)\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(kaxis,) = s[C].op.reduce_axis\nko, ki = s[C].split(kaxis, factor=kfactor)\n\n# re-ordering\ns[C].reorder(mo, no, ko, mi, ki, ni)\ns[C].vectorize(ni)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=10)\nprint(\"Opt3: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# Here is the generated IR after loop permutation.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n###################################################################################################\n# Array Packing\n# -------------\n# Another important trick is array packing. The trick is to reorder the storage of a multi-\n# dimensional array so that it is accessed sequentially after it is flattened and stored in one-\n# dimensional memory.\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/array-packing.png\n#      :align: center\n#\n# NOTE: This figure is a general illustration of how array packing works.\n\n\n###################################################################################################\n# We can use array packing to address the access pattern for B. Observe the array access pattern of\n# B after flattening which is not sequential as we iterate over the K dimension. We can reorder B\n# with dimensions [K][N] so that it has dimensions [N/bn][K][bn] where bn is the blocking factor and\n# also the vector size for B in the inner loop.  This reorder splits N into two dimensions ---\n# bigN (N/bn) and littleN (bn) --- and the new dimensions [N/bn][K][bn] match the indexing of B\n# from outer to inner loops (no, ko, ki, ni) resulting in a sequential access pattern for B after\n# flattening.\n\n\n# We have to re-write the algorithm slightly.\npackedB = te.compute(\n    (N / bn, K, bn), lambda bigN, k, littleN: B[k, bigN * bn + littleN], name=\"packedB\"\n)\nC = te.compute(\n    (M, N),\n    lambda m, n: te.sum(A[m, k] * packedB[n // bn, k, tvm.tir.indexmod(n, bn)], axis=k),\n    name=\"C\",\n)\n\ns = te.create_schedule(C.op)\n\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(kaxis,) = s[C].op.reduce_axis\nko, ki = s[C].split(kaxis, factor=kfactor)\n\ns[C].reorder(mo, no, ko, mi, ki, ni)\ns[C].vectorize(ni)\n\nbigN, _, littleN = s[packedB].op.axis\ns[packedB].vectorize(littleN)\ns[packedB].parallel(bigN)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=10)\nprint(\"Opt4: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# Here is the generated IR after array packing.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################################\n# Write cache for blocks\n# ----------------------\n# After blocking, the program will write result to C block by block, the access pattern\n# is not sequential. So we can use a sequential cache array to hold the block results and\n# write to C when all the block results are ready.\n#\n\ns = te.create_schedule(C.op)\n\n# Allocate write cache\nCC = s.cache_write(C, \"global\")\n\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n\n# Write cache is computed at no\ns[CC].compute_at(s[C], no)\n\n# New inner axes\nmc, nc = s[CC].op.axis\n\n(kaxis,) = s[CC].op.reduce_axis\nko, ki = s[CC].split(kaxis, factor=kfactor)\ns[CC].reorder(ko, mc, ki, nc)\ns[CC].vectorize(nc)\n\n# TODO: Add separate optimization step to discuss loop unrolling\n# unrolling is a loop optimization strategy which can reduce branch\n# prediction failures and increases the chance of concurrent execution\n# unroll kfactor loops\ns[CC].unroll(ki)\n\nbigN, _, littleN = s[packedB].op.axis\ns[packedB].vectorize(littleN)\ns[packedB].parallel(bigN)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=10)\nprint(\"Opt5: %f\" % evaluator(a, b, c).mean)\n\n################################################################################################\n# Here is the generated IR after blocking.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n###################################################################################################\n# Parallel\n# --------\n# Furthermore, we can also utilize multi-core processors to do the thread-level parallelization.\n\ns = te.create_schedule(C.op)\n\nCC = s.cache_write(C, \"global\")\n\nmo, no, mi, ni = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n\ns[CC].compute_at(s[C], no)\n\nmc, nc = s[CC].op.axis\n\n(kaxis,) = s[CC].op.reduce_axis\nko, ki = s[CC].split(kaxis, factor=kfactor)\ns[CC].reorder(ko, mc, ki, nc)\ns[CC].vectorize(nc)\ns[CC].unroll(ki)\n\n# parallel\ns[C].parallel(mo)\n\nbigN, _, littleN = s[packedB].op.axis\ns[packedB].vectorize(littleN)\ns[packedB].parallel(bigN)\n\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\nassert func\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\nevaluator = func.time_evaluator(func.entry_name, dev, number=50)\nopt6_time = evaluator(a, b, c).mean\nprint(\"Opt6: %f\" % opt6_time)\n\n################################################################################################\n# Here is the generated IR after parallelization.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n###################################################################################################\n\n##################################################################################################\n# Summary\n# -------\n# After applying the above simple optimizations with only 18 lines of code,\n# our generated code can achieve 60% of the `numpy` performance with MKL.\n# Note that the outputs on the web page reflect the running times on a non-exclusive\n# Docker container, thereby they are *unreliable*. It is highly encouraged to run the\n# tutorial by yourself to observe the performance gain achieved by TVM.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_conv2d_layer_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _auto-scheduler-conv-gpu:\n\nAuto-scheduling a Convolution Layer for GPU\n===========================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, \\\n            `Chengfan Jia <https://github.com/jcf94/>`_\n\nThis is a tutorial on how to use the auto-scheduler for GPUs.\n\nDifferent from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on\nmanual templates to define the search space, the auto-scheduler does not require any templates.\nUsers only need to write the computation declaration without any schedule commands or templates.\nThe auto-scheduler can automatically generate a large search space and\nfind a good schedule in the space.\n\nWe use a convolution layer as an example in this tutorial.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\nimport numpy as np\nimport tvm\nfrom tvm import te, auto_scheduler, topi\nfrom tvm.topi.testing import conv2d_nchw_python\n\n######################################################################\n# Define the computation\n# ^^^^^^^^^^^^^^^^^^^^^^\n# To begin with, let us define the computation of a convolution layer.\n# The function should return the list of input/output tensors.\n# From these tensors, the auto-scheduler can get the whole computational graph.\n\n\n@auto_scheduler.register_workload\ndef conv2d_layer(N, H, W, CO, CI, KH, KW, stride, padding):\n    data = te.placeholder((N, CI, H, W), name=\"data\")\n    kernel = te.placeholder((CO, CI, KH, KW), name=\"kernel\")\n    bias = te.placeholder((1, CO, 1, 1), name=\"bias\")\n    conv = topi.nn.conv2d_nchw(data, kernel, stride, padding, dilation=1, out_dtype=\"float32\")\n    out = topi.nn.relu(conv + bias)\n    return [data, kernel, bias, out]\n\n\n######################################################################\n# Create the search task\n# ^^^^^^^^^^^^^^^^^^^^^^\n# We then create a search task for the last convolution layer in the resnet.\n\ntarget = tvm.target.Target(\"cuda\")\n\n# Use the last layer in ResNet-50\nN, H, W, CO, CI, KH, KW, strides, padding = 1, 7, 7, 512, 512, 3, 3, (1, 1), (1, 1)\ntask = auto_scheduler.SearchTask(\n    func=conv2d_layer, args=(N, H, W, CO, CI, KH, KW, strides, padding), target=target\n)\n\n# Inspect the computational graph\nprint(\"Computational DAG:\")\nprint(task.compute_dag)\n\n######################################################################\n# Next, we set parameters for the auto-scheduler. These parameters\n# mainly specify how we do the measurement during the search.\n#\n# * :code:`measure_ctx` launches a different process for measurement to\n#   provide isolation. It can protect the main process from GPU crashes\n#   during measurement and avoid other runtime conflicts.\n# * :code:`min_repeat_ms` defines the minimum duration of one \"repeat\" in every measurement.\n#   This can warmup the GPU, which is necessary to get accurate measurement results.\n#   Typically, we recommend a value >= 300 ms.\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the search.\n#   We only make 10 trials in this tutorial for a fast demonstration. In practice, 1000 is a\n#   good value for the search to converge. You can do more trials according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a file `conv2d.json`.\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions`,\n#   :any:`auto_scheduler.LocalRPCMeasureContext` for more parameters.\n\nlog_file = \"conv2d.json\"\nmeasure_ctx = auto_scheduler.LocalRPCMeasureContext(min_repeat_ms=300)\ntune_option = auto_scheduler.TuningOptions(\n    num_measure_trials=10,  # change this to 1000 to achieve the best performance\n    runner=measure_ctx.runner,\n    measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    verbose=2,\n)\n\n######################################################################\n# Run the search\n# ^^^^^^^^^^^^^^\n# Now we get all inputs ready. Pretty simple, isn't it?\n# We can kick off the search and let the auto-scheduler do its magic.\n# After some measurement trials, we can load the best schedule from the log\n# file and apply it.\n\n# Run auto-tuning (search)\ntask.tune(tune_option)\n# Apply the best schedule\nsch, args = task.apply_best(log_file)\n\n# Kill the measurement process\ndel measure_ctx\n\n######################################################################\n# We can lower the schedule to see the IR after auto-scheduling.\n# The auto-scheduler correctly performs optimizations including multi-level tiling,\n# cooperative fetching, unrolling and operator fusion.\n\nprint(\"Lowered TIR:\")\nprint(tvm.lower(sch, args, simple_mode=True))\n\n######################################################################\n# Check correctness and evaluate performance\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# We build the binary and check its correctness and performance.\n\nfunc = tvm.build(sch, args, target)\n\n# Check correctness\ndata_np = np.random.uniform(size=(N, CI, H, W)).astype(np.float32)\nweight_np = np.random.uniform(size=(CO, CI, KH, KW)).astype(np.float32)\nbias_np = np.random.uniform(size=(1, CO, 1, 1)).astype(np.float32)\nconv_np = conv2d_nchw_python(data_np, weight_np, strides, padding)\nout_np = np.maximum(conv_np + bias_np, 0.0)\n\ndev = tvm.cuda()\ndata_tvm = tvm.nd.array(data_np, device=dev)\nweight_tvm = tvm.nd.array(weight_np, device=dev)\nbias_tvm = tvm.nd.array(bias_np, device=dev)\nout_tvm = tvm.nd.empty(out_np.shape, device=dev)\nfunc(data_tvm, weight_tvm, bias_tvm, out_tvm)\n\n# Check results\nnp.testing.assert_allclose(out_np, out_tvm.numpy(), rtol=1e-3)\n\n# Evaluate execution time\nevaluator = func.time_evaluator(func.entry_name, dev, min_repeat_ms=500)\nprint(\n    \"Execution time of this operator: %.3f ms\"\n    % (np.median(evaluator(data_tvm, weight_tvm, bias_tvm, out_tvm).results) * 1000)\n)\n\n######################################################################\n# Using the record file\n# ^^^^^^^^^^^^^^^^^^^^^\n# During the search, all measurement records are dumped into the record\n# file \"conv2d.json\". The measurement records can be used to re-apply search results,\n# resume the search, and perform other analyses.\n\n######################################################################\n# Here is an example where we load the best schedule from a file,\n# print the equivalent python schedule API and CUDA source code.\n# They can be used for debugging and learning the behavior of the auto-scheduler.\n\nprint(\"Equivalent python schedule:\")\nprint(task.print_best(log_file, print_mode=\"schedule\"))\n\nprint(\"CUDA source code:\")\nprint(task.print_best(log_file, print_mode=\"cuda\"))\n\n######################################################################\n# A more complicated example is to resume the search.\n# In this case, we need to create the search policy and cost model by ourselves\n# and resume the status of search policy and cost model with the log file.\n# In the example below we resume the status and do more 5 trials.\n\n\ndef resume_search(task, log_file):\n    print(\"Resume search:\")\n    cost_model = auto_scheduler.XGBModel()\n    cost_model.update_from_file(log_file)\n    search_policy = auto_scheduler.SketchPolicy(\n        task, cost_model, init_search_callbacks=[auto_scheduler.PreloadMeasuredStates(log_file)]\n    )\n    measure_ctx = auto_scheduler.LocalRPCMeasureContext(min_repeat_ms=300)\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=5,\n        runner=measure_ctx.runner,\n        measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    )\n    task.tune(tune_option, search_policy=search_policy)\n\n    # Kill the measurement process\n    del measure_ctx\n\n\nresume_search(task, log_file)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_network_arm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-scheduling a Neural Network for ARM CPU\n=============================================\n**Author**: `Thierry Moreau <https://github.com/tmoreau89>`_, \\\n            `Lianmin Zheng <https://github.com/merrymercy>`_, \\\n            `Chengfan Jia <https://github.com/jcf94/>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole neural\nnetwork for ARM CPU with the auto-scheduler via RPC.\n\nTo auto-tune a neural network, we partition the network into small subgraphs and\ntune them independently. Each subgraph is treated as one search task.\nA task scheduler slices the time and dynamically allocates time resources to\nthese tasks. The task scheduler predicts the impact of each task on the end-to-end\nexecution time and prioritizes the one that can reduce the execution time the most.\n\nFor each subgraph, we use the compute declaration in :code:`tvm/python/topi` to\nget the computational DAG in the tensor expression form.\nWe then use the auto-scheduler to construct a search space of this DAG and search\nfor good schedules (low-level optimizations).\n\nDifferent from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on\nmanual templates to define the search space, the auto-scheduler does not require any\nschedule templates. In other words, the auto-scheduler only uses the compute declarations\nin :code:`tvm/python/topi` and does not use existing schedule templates.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\nimport os\n\nimport tvm\nfrom tvm import relay, auto_scheduler\nfrom tvm.relay import data_dep_optimization as ddo\nimport tvm.relay.testing\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.utils import tempdir\n\n#################################################################\n# Define a Network\n# ----------------\n# First, we need to define the network with relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow\n# (see :ref:`front end tutorials<tutorial-frontend>`).\n#\n# For convolutional neural networks, although auto-scheduler can work correctly\n# with any layout, we found the best performance is typically achieved with NHWC layout.\n# We also implemented more optimizations for NHWC layout with the auto-scheduler.\n# So it is recommended to convert your models to NHWC layout to use the auto-scheduler.\n# You can use :ref:`ConvertLayout <convert-layout-usage>` pass to do the layout conversion in TVM.\n\n\ndef get_network(name, batch_size, layout=\"NHWC\", dtype=\"float32\", use_sparse=False):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n\n    # auto-scheduler prefers NHWC layout\n    if layout == \"NHWC\":\n        image_shape = (224, 224, 3)\n    elif layout == \"NCHW\":\n        image_shape = (3, 224, 224)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    input_shape = (batch_size,) + image_shape\n    output_shape = (batch_size, 1000)\n\n    if name.startswith(\"resnet-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name.startswith(\"resnet3d-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(\n            batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape\n        )\n    elif name == \"squeezenet_v1.1\":\n        assert layout == \"NCHW\", \"squeezenet_v1.1 only supports NCHW layout\"\n        mod, params = relay.testing.squeezenet.get_workload(\n            version=\"1.1\",\n            batch_size=batch_size,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299) if layout == \"NCHW\" else (batch_size, 299, 299, 3)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        assert layout == \"NCHW\"\n\n        block = get_model(\"resnet50_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    elif name == \"mlp\":\n        mod, params = relay.testing.mlp.get_workload(\n            batch_size=batch_size, dtype=dtype, image_shape=image_shape, num_classes=1000\n        )\n    else:\n        raise ValueError(\"Network not found.\")\n\n    if use_sparse:\n        from tvm.topi.sparse.utils import convert_model_dense_to_sparse\n\n        mod, params = convert_model_dense_to_sparse(mod, params, random_params=True)\n\n    return mod, params, input_shape, output_shape\n\n\n#################################################################\n# Start RPC Tracker\n# -----------------\n# TVM uses RPC session to communicate with ARM boards.\n# During tuning, the tuner will send the generated code to the board and\n# measure the speed of code on the board.\n#\n# To scale up the tuning, TVM uses RPC Tracker to manage distributed devices.\n# The RPC Tracker is a centralized controller node. We can register all devices to\n# the tracker. For example, if we have 10 phones, we can register all of them\n# to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n#\n# To start an RPC tracker, run this command on the host machine. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n\n#################################################################\n# Register Devices to RPC Tracker\n# -----------------------------------\n# Now we can register our devices to the tracker. The first step is to\n# build the TVM runtime for the ARM devices.\n#\n# * For Linux:\n#   Follow this section :ref:`build-tvm-runtime-on-device` to build\n#   the TVM runtime on the device. Then register the device to tracker by\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=rasp4b-64\n#\n#   (replace :code:`[HOST_IP]` with the IP address of your host machine)\n#\n# * For Android:\n#   Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to\n#   install the TVM RPC APK on the android device. Make sure you can pass the android rpc test.\n#   Then you have already registered your device. During tuning, you have to go to developer option\n#   and enable \"Keep screen awake during changing\" and charge your phone to make it stable.\n#\n# After registering devices, we can confirm it by querying rpc_tracker\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n#\n# For example, if we have 2 Huawei mate10 pro, 11 Raspberry Pi 4B with 64bit OS, and 2 rk3399,\n# the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    mate10pro    2      2     0\n#    rk3399       2      2     0\n#    rasp4b-64    11     11    0\n#    ----------------------------------\n#\n# You can register multiple devices to the tracker to accelerate the measurement in tuning.\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we should apply some configurations. Here I use a Raspberry Pi 4b 4GB board\n# as example with a 64bit OS (Ubuntu 20.04). In your setting, you should modify the target\n# and device_key accordingly.\n# set :code:`use_ndk` to True if you use android phone.\n\n#### DEVICE CONFIG ####\n\n# Replace \"aarch64-linux-gnu\" with the correct target of your board.\n# This target is used for cross compilation. You can query it by :code:`gcc -v` on your device.\n# FIXME(tmoreau89, merrymercy): We leave '-device=arm_cpu' out of the target string\n#                               because we're sharing x86 op strategy.\ntarget = tvm.target.Target(\"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\")\n\n# Also replace this with the device key, rpc host and rpc port in your tracker\ndevice_key = \"rasp4b-64\"\nrpc_host = \"127.0.0.1\"\nrpc_port = 9190\n\n# Set this to True if you use ndk tools for cross compiling\n# And also set the environment variable below to point to the cross compiler\nuse_ndk = False\n# os.environ[\"TVM_NDK_CC\"] = \"/usr/bin/aarch64-linux-gnu-g++\"\n\n#### TUNING OPTION ####\nnetwork = \"mobilenet\"\nuse_sparse = False\nbatch_size = 1\nlayout = \"NHWC\"\ndtype = \"float32\"\nlog_file = \"%s-%s-B%d-%s.json\" % (network, layout, batch_size, target.kind.name)\n\n#################################################################\n# Extract Search Tasks\n# --------------------\n# Next, we extract the search tasks and their weights from a network.\n# The weight of a task is the number of appearances of the task's subgraph\n# in the whole network.\n# By using the weight, we can approximate the end-to-end latency of the network\n# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the\n# latency of a task and :code:`weight[t]` is the weight of the task.\n# The task scheduler will just optimize this objective.\n\n# Extract tasks from the network\nprint(\"Get model...\")\nmod, params, input_shape, output_shape = get_network(\n    network, batch_size, layout, dtype=dtype, use_sparse=use_sparse\n)\nprint(\"Extract tasks...\")\ntasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n\nfor idx, task in enumerate(tasks):\n    print(\"========== Task %d  (workload key: %s) ==========\" % (idx, task.workload_key))\n    print(task.compute_dag)\n\n\n#################################################################\n# Tuning and Evaluation\n# ---------------------\n# Now, we set some options for tuning and launch the search tasks\n#\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.\n#   You can set it to a small number (e.g., 200) for a fast demonstrative run.\n#   In practice, we recommend setting it around :code:`800 * len(tasks)`,\n#   which is typically enough for the search to converge.\n#   For example, there are 29 tasks in resnet-50, so we can set it as 20000.\n#   You can adjust this parameter according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions`,\n#   :any:`auto_scheduler.LocalRunner` for more parameters.\n#\n# After auto-tuning, we can compile the network with the best schedules we found.\n# All measurement records are dumped into the log file during auto-tuning,\n# so we can read the log file and load the best schedules.\n\n\ndef tune_and_evaluate():\n    print(\"Begin tuning...\")\n    tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=200,  # change this to 20000 to achieve the best performance\n        builder=auto_scheduler.LocalBuilder(build_func=\"ndk\" if use_ndk else \"default\"),\n        runner=auto_scheduler.RPCRunner(\n            device_key,\n            host=rpc_host,\n            port=rpc_port,\n            timeout=30,\n            repeat=1,\n            min_repeat_ms=200,\n            enable_cpu_cache_flush=True,\n        ),\n        measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    )\n\n    tuner.tune(tune_option)\n\n    # Compile with the history best\n    print(\"Compile...\")\n    with auto_scheduler.ApplyHistoryBest(log_file):\n        with tvm.transform.PassContext(\n            opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}\n        ):\n            lib = relay.build(mod, target=target, params=params)\n\n    # Export library\n    tmp = tempdir()\n    if use_ndk:\n        from tvm.contrib import ndk\n\n        filename = \"net.so\"\n        lib.export_library(tmp.relpath(filename), ndk.create_shared)\n    else:\n        filename = \"net.tar\"\n        lib.export_library(tmp.relpath(filename))\n\n    # Upload module to device\n    print(\"Upload...\")\n    remote = auto_scheduler.utils.request_remote(device_key, rpc_host, rpc_port, timeout=10000)\n    remote.upload(tmp.relpath(filename))\n    rlib = remote.load_module(filename)\n\n    # Create graph executor\n    dev = remote.cpu()\n    module = graph_executor.GraphModule(rlib[\"default\"](dev))\n    data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n    module.set_input(\"data\", data_tvm)\n\n    # Evaluate\n    print(\"Evaluate inference time cost...\")\n    print(module.benchmark(dev, repeat=3, min_repeat_ms=500))\n\n\n# We do not run the tuning in our webpage server since the server doesn't have a Raspberry Pi,\n# or device tracker running.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate()\n\n\n######################################################################\n# .. note:: Explaining the printed information during tuning\n#\n#   During the tuning, a lot of information will be printed on the console.\n#   They are used for debugging purposes. The most important info is the output\n#   of the task scheduler. The following table is a sample output.\n#\n#   .. code-block:: c\n#\n#    ----------------------------------------------------------------------\n#    ------------------------------  [ Task Scheduler ]\n#    ----------------------------------------------------------------------\n#    |  ID  | Latency (ms) | Speed (GFLOPS) | Trials |\n#    -------------------------------------------------\n#    |    0 |        0.013 |           0.31 |     64 |\n#    |    1 |        0.845 |           2.43 |    448 |\n#    |    2 |        0.046 |          -0.00 |     64 |\n#    |    3 |        4.194 |          24.53 |   2112 |\n#    |    4 |        0.109 |           9.21 |     64 |\n#    |    5 |        1.759 |          29.27 |    896 |\n#    |    6 |        0.083 |           6.01 |     64 |\n#    |    7 |        3.084 |          33.38 |   7680 |\n#    |    8 |        0.136 |          14.78 |    384 |\n#    |    9 |        1.349 |          38.23 |    768 |\n#    |   10 |        0.133 |           7.55 |    128 |\n#    |   11 |        2.747 |          37.56 |   1536 |\n#    |   12 |        0.338 |          11.87 |    192 |\n#    |   13 |        1.295 |          40.00 |    704 |\n#    |   14 |        0.482 |           4.16 |    256 |\n#    |   15 |        2.686 |          38.56 |   1344 |\n#    |   16 |        0.884 |           9.08 |    448 |\n#    |   17 |        1.332 |          39.18 |    704 |\n#    |   18 |        1.045 |           3.84 |    576 |\n#    |   19 |        1.391 |          38.09 |    704 |\n#    |   20 |        0.777 |          10.34 |    448 |\n#    |   21 |        0.739 |          30.97 |    448 |\n#    -------------------------------------------------\n#     Estimated total latency: 38.347 ms      Trials: 19992   Used time : 19260 s     Next ID: 3\n#\n#   This table lists the latency and (estimated) speed of all tasks.\n#   It also lists the allocation of measurement trials for all tasks.\n#   The last line prints the total weighted latency of these tasks,\n#   which can be a rough estimation of the end-to-end execution time\n#   of the network.\n#   The last line also prints the total number of measurement trials,\n#   total time spent on auto-tuning and the id of the next task to tune.\n#\n#   There will also be some \"dmlc::Error\"s errors, because the\n#   auto-scheduler will try some invalid schedules.\n#   You can safely ignore them if the tuning can continue, because these\n#   errors are isolated from the main process.\n#\n\n######################################################################\n# .. note:: Terminate the tuning earlier\n#\n#   You can terminate the tuning earlier by forcibly killing this process.\n#   As long as you get at least one valid schedule for each task in the log file,\n#   you should be able to do the compilation (the secion below).\n#\n\n#################################################################\n# Other Tips\n# ----------\n# 1. During the tuning, the auto-scheduler needs to compile many programs and\n#    extract feature from them. This part is CPU-intensive,\n#    so a high-performance CPU with many cores is recommended for faster search.\n# 2. You can use :code:`python3 -m tvm.auto_scheduler.measure_record --mode distill -i log.json`\n#    to distill the large log file and only save the best useful records.\n# 3. You can resume a search from the previous log file. You just need to\n#    add a new argument :code:`load_log_file` when creating the task scheduler\n#    in function :code:`run_tuning`. Say,\n#    :code:`tuner = auto_scheduler.TaskScheduler(tasks, task_weights, load_log_file=log_file)`\n# 4. If you have multiple target CPUs, you can use all of them for measurements to\n#    parallelize the measurements. Check this :ref:`section <tutorials-autotvm-scale-up-rpc-tracker>`\n#    to learn how to use the RPC Tracker and RPC Server.\n#    To use the RPC Tracker in auto-scheduler, replace the runner in :code:`TuningOptions`\n#    with :any:`auto_scheduler.RPCRunner`.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_network_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-scheduling a Neural Network for NVIDIA GPU\n===============================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole neural\nnetwork for NVIDIA GPU with the auto-scheduler.\n\nTo auto-tune a neural network, we partition the network into small subgraphs and\ntune them independently. Each subgraph is treated as one search task.\nA task scheduler slices the time and dynamically allocates time resources to\nthese tasks. The task scheduler predicts the impact of each task on the end-to-end\nexecution time and prioritizes the one that can reduce the execution time the most.\n\nFor each subgraph, we use the compute declaration in :code:`tvm/python/topi` to\nget the computational DAG in the tensor expression form.\nWe then use the auto-scheduler to construct a search space of this DAG and search\nfor good schedules (low-level optimizations).\n\nDifferent from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on\nmanual templates to define the search space, the auto-scheduler does not require any\nschedule templates. In other words, the auto-scheduler only uses the compute declarations\nin :code:`tvm/python/topi` and does not use existing schedule templates.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, auto_scheduler\nimport tvm.relay.testing\nfrom tvm.contrib import graph_executor\n\n#################################################################\n# Define a Network\n# ----------------\n# First, we need to define the network with relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow\n# (see :ref:`front end tutorials<tutorial-frontend>`).\n#\n# For convolutional neural networks, although auto-scheduler can work correctly\n# with any layout, we found the best performance is typically achieved with NHWC layout.\n# We also implemented more optimizations for NHWC layout with the auto-scheduler.\n# So it is recommended to convert your models to NHWC layout to use the auto-scheduler.\n# You can use :ref:`ConvertLayout <convert-layout-usage>` pass to do the layout conversion in TVM.\n\n\ndef get_network(name, batch_size, layout=\"NHWC\", dtype=\"float32\"):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n\n    # auto-scheduler prefers NHWC layout\n    if layout == \"NHWC\":\n        image_shape = (224, 224, 3)\n    elif layout == \"NCHW\":\n        image_shape = (3, 224, 224)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    input_shape = (batch_size,) + image_shape\n    output_shape = (batch_size, 1000)\n\n    if name.startswith(\"resnet-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name.startswith(\"resnet3d-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(\n            batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape\n        )\n    elif name == \"squeezenet_v1.1\":\n        assert layout == \"NCHW\", \"squeezenet_v1.1 only supports NCHW layout\"\n        mod, params = relay.testing.squeezenet.get_workload(\n            version=\"1.1\",\n            batch_size=batch_size,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299) if layout == \"NCHW\" else (batch_size, 299, 299, 3)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        assert layout == \"NCHW\"\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n\n    return mod, params, input_shape, output_shape\n\n\n# Define the neural network and compilation target\nnetwork = \"resnet-18\"\nbatch_size = 1\nlayout = \"NHWC\"\ntarget = tvm.target.Target(\"cuda\")\ndtype = \"float32\"\nlog_file = \"%s-%s-B%d-%s.json\" % (network, layout, batch_size, target.kind.name)\n\n#################################################################\n# Extract Search Tasks\n# --------------------\n# Next, we extract the search tasks and their weights from a network.\n# The weight of a task is the number of appearances of the task's subgraph\n# in the whole network.\n# By using the weight, we can approximate the end-to-end latency of the network\n# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the\n# latency of a task and :code:`weight[t]` is the weight of the task.\n# The task scheduler will just optimize this objective.\n\n# Extract tasks from the network\nprint(\"Extract tasks...\")\nmod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)\ntasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n\nfor idx, task in enumerate(tasks):\n    print(\"========== Task %d  (workload key: %s) ==========\" % (idx, task.workload_key))\n    print(task.compute_dag)\n\n#################################################################\n# Begin Tuning\n# ------------\n# Now, we set some options for tuning and launch the search tasks\n#\n# * :code:`measure_ctx` launches a different process for measurement to\n#   provide isolation. It can protect the main process from GPU crashes\n#   during measurement and avoid other runtime conflicts.\n# * :code:`min_repeat_ms` defines the minimum duration of one \"repeat\" in every measurement.\n#   This can warmup the GPU, which is necessary to get accurate measurement results.\n#   Typically, we recommend a value >= 300 ms.\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.\n#   You can set it to a small number (e.g., 200) for a fast demonstrative run.\n#   In practice, we recommend setting it around :code:`900 * len(tasks)`,\n#   which is typically enough for the search to converge.\n#   For example, there are 24 tasks in resnet-18, so we can set it as 20000.\n#   You can adjust this parameter according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions`,\n#   :any:`auto_scheduler.LocalRPCMeasureContext` for more parameters.\n#\n\n\ndef run_tuning():\n    print(\"Begin tuning...\")\n    measure_ctx = auto_scheduler.LocalRPCMeasureContext(repeat=1, min_repeat_ms=300, timeout=10)\n\n    tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=200,  # change this to 20000 to achieve the best performance\n        runner=measure_ctx.runner,\n        measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    )\n\n    tuner.tune(tune_option)\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# run_tuning()\n\n\n######################################################################\n# .. note:: Explain the printed information during tuning\n#\n#   During the tuning, a lot of information will be printed on the console.\n#   They are used for debugging purposes. The most important info is the output\n#   of the task scheduler. The following table is a sample output.\n#\n#   .. code-block:: c\n#\n#     ----------------------------------------------------------------------\n#     ------------------------------  [ Task Scheduler ]\n#     ----------------------------------------------------------------------\n#     |  ID  | Latency (ms) | Speed (GFLOPS) | Trials |\n#     -------------------------------------------------\n#     |    0 |        0.005 |           0.88 |     64 |\n#     |    1 |        0.010 |          99.10 |     64 |\n#     |    2 |        0.006 |           0.00 |     64 |\n#     |    3 |        0.145 |         979.78 |    384 |\n#     |    4 |        0.130 |        1097.02 |    384 |\n#     |    5 |        0.143 |         992.69 |    384 |\n#     |    6 |        0.076 |        1526.86 |    192 |\n#     |    7 |        0.115 |         999.44 |    320 |\n#     |    8 |        0.079 |        1449.39 |    320 |\n#     |    9 |        0.122 |         938.73 |    384 |\n#     |   10 |        0.063 |        1832.98 |    192 |\n#     |   11 |        0.072 |        1763.62 |    256 |\n#     |   12 |        0.062 |        2036.40 |    192 |\n#     |   13 |        0.068 |        1874.44 |    192 |\n#     |   14 |        0.049 |        2346.50 |    128 |\n#     |   15 |        0.076 |        1694.31 |    256 |\n#     |   16 |        0.067 |        1933.30 |    448 |\n#     |   17 |        0.076 |        1680.90 |    256 |\n#     |   18 |        0.022 |          98.43 |     64 |\n#     |   19 |        0.076 |        3112.55 |    192 |\n#     |   20 |        0.013 |        2026.44 |     64 |\n#     |   21 |        0.011 |        1136.69 |     64 |\n#     |   22 |        0.013 |         992.47 |     64 |\n#     |   23 |        0.020 |         627.56 |     64 |\n#     -------------------------------------------------\n#     Estimated total latency: 1.587 ms  Trials: 4992  Used time : 13296 s  Next ID: 3\n#\n#   This table lists the latency and (estimated) speed of all tasks.\n#   It also lists the allocation of measurement trials for all tasks.\n#   The last line prints the total weighted latency of these tasks,\n#   which can be a rough estimation of the end-to-end execution time\n#   of the network.\n#   The last line also prints the total number of measurement trials,\n#   total time spent on auto-tuning and the id of the next task to tune.\n#\n#   There will also be some \"tvm::Error\"s and CUDA errors, because the\n#   auto-scheduler will try some invalid schedules.\n#   You can safely ignore them if the tuning can continue, because these\n#   errors are isolated from the main process.\n#\n\n######################################################################\n# .. note:: Terminate the tuning earlier\n#\n#   You can terminate the tuning earlier by forcibly killing this process.\n#   As long as you get at least one valid schedule for each task in the log file,\n#   you should be able to do the compilation (the secion below).\n#\n\n\n#################################################################\n# Compile and Evaluate\n# --------------------\n# After auto-tuning, we can compile the network with the best schedules we found.\n# All measurement records are dumped into the log file during auto-tuning,\n# so we can read the log file and load the best schedules.\n\n# Compile with the history best\nprint(\"Compile...\")\nwith auto_scheduler.ApplyHistoryBest(log_file):\n    with tvm.transform.PassContext(opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}):\n        lib = relay.build(mod, target=target, params=params)\n\n# Create graph executor\ndev = tvm.device(str(target), 0)\nmodule = graph_executor.GraphModule(lib[\"default\"](dev))\ndata_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\nmodule.set_input(\"data\", data_tvm)\n\n# Evaluate\nprint(\"Evaluate inference time cost...\")\nprint(module.benchmark(dev, repeat=3, min_repeat_ms=500))\n\n\n#################################################################\n# Other Tips\n# ----------\n# 1. During the tuning, the auto-scheduler needs to compile many programs and\n#    extract feature from them. This part is CPU-intensive,\n#    so a high-performance CPU with many cores is recommended for faster search.\n# 2. You can use :code:`python3 -m tvm.auto_scheduler.measure_record --mode distill -i log.json`\n#    to distill the large log file and only save the best useful records.\n# 3. You can resume a search from the previous log file. You just need to\n#    add a new argument :code:`load_log_file` when creating the task scheduler\n#    in function :code:`run_tuning`. Say,\n#    :code:`tuner = auto_scheduler.TaskScheduler(tasks, task_weights, load_log_file=log_file)`\n# 4. If you have multiple target GPUs, you can use all of them for measurements to\n#    parallelize the measurements. Check this :ref:`section <tutorials-autotvm-scale-up-rpc-tracker>`\n#    to learn how to use the RPC Tracker and RPC Server.\n#    To use the RPC Tracker in auto-scheduler, replace the runner in :code:`TuningOptions`\n#    with :any:`auto_scheduler.RPCRunner`.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_network_mali.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-scheduling a Neural Network for mali GPU\n=============================================\n**Author**: `Zhao Wu <https://github.com/FrozenGene>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole neural\nnetwork for mali GPU with the auto-scheduler.\n\nTo auto-tune a neural network, we partition the network into small subgraphs and\ntune them independently. Each subgraph is treated as one search task.\nA task scheduler slices the time and dynamically allocates time resources to\nthese tasks. The task scheduler predicts the impact of each task on the end-to-end\nexecution time and prioritizes the one that can reduce the execution time the most.\n\nFor each subgraph, we use the compute declaration in :code:`tvm/python/topi` to\nget the computational DAG in the tensor expression form.\nWe then use the auto-scheduler to construct a search space of this DAG and search\nfor good schedules (low-level optimizations).\n\nDifferent from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on\nmanual templates to define the search space, the auto-scheduler does not require any\nschedule templates. In other words, the auto-scheduler only uses the compute declarations\nin :code:`tvm/python/topi` and does not use existing schedule templates.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, auto_scheduler\nimport tvm.relay.testing\nfrom tvm.contrib import graph_executor\nimport os\n\n#################################################################\n# Define a Network\n# ----------------\n# First, we need to define the network with relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow\n# (see :ref:`front end tutorials<tutorial-frontend>`).\n#\n# For convolutional neural networks, although auto-scheduler can work correctly\n# with any layout, we found the best performance is typically achieved with NHWC layout.\n# We also implemented more optimizations for NHWC layout with the auto-scheduler.\n# So it is recommended to convert your models to NHWC layout to use the auto-scheduler.\n# You can use :ref:`ConvertLayout <convert-layout-usage>` pass to do the layout conversion in TVM.\n\n\ndef get_network(name, batch_size, layout=\"NHWC\", dtype=\"float32\"):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n\n    # auto-scheduler prefers NHWC layout\n    if layout == \"NHWC\":\n        image_shape = (224, 224, 3)\n    elif layout == \"NCHW\":\n        image_shape = (3, 224, 224)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    input_shape = (batch_size,) + image_shape\n    output_shape = (batch_size, 1000)\n\n    if name.startswith(\"resnet-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name.startswith(\"resnet3d-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(\n            batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape\n        )\n    elif name == \"squeezenet_v1.1\":\n        assert layout == \"NCHW\", \"squeezenet_v1.1 only supports NCHW layout\"\n        mod, params = relay.testing.squeezenet.get_workload(\n            version=\"1.1\",\n            batch_size=batch_size,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299) if layout == \"NCHW\" else (batch_size, 299, 299, 3)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        assert layout == \"NCHW\"\n\n        block = get_model(\"resnet50_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n\n    return mod, params, input_shape, output_shape\n\n\n# Define the neural network and compilation target.\nnetwork = \"mobilenet\"\nbatch_size = 1\nlayout = \"NHWC\"\n# Set this to True if you use ndk tools for cross compiling\nuse_ndk = True\n# Path to cross compiler\nos.environ[\"TVM_NDK_CC\"] = \"/usr/bin/aarch64-linux-gnu-g++\"\ntarget = tvm.target.Target(\"opencl -device=mali\", host=\"llvm -mtriple=aarch64-linux-gnu\")\ndtype = \"float32\"\nlog_file = \"%s-%s-B%d-%s.json\" % (network, layout, batch_size, target.kind.name)\n\n\n#################################################################\n# Start an RPC Tracker and Register Devices to the Tracker\n# --------------------------------------------------------\n# Please refer to the \"Start RPC Tracker\" and \"Register Devices to RPC Tracker\" setions\n# in this :ref:`tutorial <tutorials-autotvm-start-rpc-tracker>` to start an RPC tracker\n# and register devices to the tracker.\n\n# Replace this with the device key in your tracker\ndevice_key = \"rk3399\"\n\n\n#################################################################\n# Extract Search Tasks\n# --------------------\n# Next, we extract the search tasks and their weights from a network.\n# The weight of a task is the number of appearances of the task's subgraph\n# in the whole network.\n# By using the weight, we can approximate the end-to-end latency of the network\n# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the\n# latency of a task and :code:`weight[t]` is the weight of the task.\n# The task scheduler will just optimize this objective.\n\n# Extract tasks from the network\nprint(\"Extract tasks...\")\nmod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)\ntasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n\nfor idx, task in enumerate(tasks):\n    print(\"========== Task %d  (workload key: %s) ==========\" % (idx, task.workload_key))\n    print(task.compute_dag)\n######################################################################\n# .. note:: How to get the hardware parameters from remote device\n#\n#   .. code-block:: python\n#\n#     from tvm.auto_scheduler.utils import request_remote\n#     remote = request_remote(device_key, \"127.0.0.1\", 9190)\n#     dev = remote.cl()\n#     max_shared_memory_per_block = dev.max_shared_memory_per_block\n#     # There is no explicit local memory limition\n#     # so we can use INT32_MAX to disable the check on local_memory.\n#     max_local_memory_per_block = 2147483647 # INT32_MAX\n#     max_threads_per_block = dev.max_threads_per_block\n#     max_vthread_extent = int(dev.warp_size / 4) if int(dev.warp_size / 4) > 1 else dev.warp_size\n#     warp_size = dev.warp_size\n#     hardware_params = auto_scheduler.HardwareParams(-1, 16, 64,\n#                                                     max_shared_memory_per_block, max_local_memory_per_block,\n#                                                     max_threads_per_block, max_vthread_extent, warp_size)\n#\n#  Now you could pass it to search task and tune\n#\n#   .. code-block:: python\n#\n#    tasks, task_weights = auto_scheduler.extract_tasks(\n#        mod[\"main\"], params, target, hardware_params = hardware_params\n#    )\n#\n\n#################################################################\n# Tuning and Evaluate\n# -------------------\n# Now, we set some options for tuning, launch the search tasks and evaluate the end-to-end performance\n#\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.\n#   You can set it to a small number (e.g., 200) for a fast demonstrative run.\n#   In practice, we recommend setting it around :code:`800 * len(tasks)`,\n#   which is typically enough for the search to converge.\n#   For example, there are 29 tasks in resnet-50, so we can set it as 20000.\n#   You can adjust this parameter according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions`,\n#   :any:`auto_scheduler.LocalRunner` for more parameters.\n#\n\n\ndef tune_and_evaluate():\n    print(\"Begin tuning...\")\n    tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=200,  # change this to 20000 to achieve the best performance\n        builder=auto_scheduler.LocalBuilder(build_func=\"ndk\" if use_ndk else \"default\"),\n        runner=auto_scheduler.RPCRunner(\n            device_key, host=\"127.0.0.1\", port=9190, repeat=3, timeout=50\n        ),\n        measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    )\n\n    tuner.tune(tune_option)\n\n    # Compile the whole network\n    print(\"Compile...\")\n    with auto_scheduler.ApplyHistoryBest(log_file):\n        with tvm.transform.PassContext(\n            opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}\n        ):\n            lib = relay.build(mod, target, params=params)\n\n    # Create graph executor\n    print(\"=============== Request Remote ===============\")\n    from tvm.auto_scheduler.utils import request_remote\n\n    remote = request_remote(device_key, \"127.0.0.1\", 9190)\n    dev = remote.cl()\n    from tvm.contrib import utils, ndk\n\n    temp = utils.tempdir()\n    filename = \"deploy_lib.so\"\n    path_lib = temp.relpath(filename)\n    lib.export_library(path_lib, ndk.create_shared)\n    remote.upload(path_lib)\n    loaded_lib = remote.load_module(filename)\n    module = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n    data = (np.random.uniform(size=input_shape)).astype(dtype)\n    data_tvm = tvm.nd.array(data)\n    module.set_input(\"data\", data_tvm)\n\n    # Evaluate\n    print(\"Evaluate inference time cost...\")\n    print(module.benchmark(dev, repeat=3, min_repeat_ms=500))\n\n\n# We do not run the tuning in our webpage server since server doesn't have mali gpu.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate()\n\n######################################################################\n# .. note:: Explain the printed information during tuning\n#\n#   During the tuning, a lot of information will be printed on the console.\n#   They are used for debugging purposes. The most important info is the output\n#   of the task scheduler. The following table is a sample output.\n#\n#   .. code-block:: c\n#\n#     ----------------------------------------------------------------------\n#     ------------------------------  [ Task Scheduler ]\n#     ----------------------------------------------------------------------\n#     |  ID  | Latency (ms) | Speed (GFLOPS) | Trials |\n#     -------------------------------------------------\n#     |    0 |        0.010 |           0.40 |     64 |\n#     |    1 |        0.087 |          47.19 |     64 |\n#     |    2 |        0.008 |          -0.00 |     64 |\n#     |    3 |        0.177 |         582.07 |     64 |\n#     |    4 |        0.268 |         862.37 |    256 |\n#     |    5 |        0.166 |         621.13 |    128 |\n#     |    6 |        0.170 |         605.10 |    128 |\n#     |    7 |        0.128 |         403.20 |     64 |\n#     |    8 |        0.189 |         545.71 |     64 |\n#     |    9 |        0.231 |        1001.01 |    448 |\n#     |   10 |        0.155 |         664.80 |    256 |\n#     |   11 |        0.155 |         662.86 |    256 |\n#     |   12 |        0.119 |         434.08 |     64 |\n#     |   13 |        0.199 |         522.13 |     64 |\n#     |   14 |        0.235 |         986.56 |    320 |\n#     |   15 |        0.149 |         689.13 |    128 |\n#     |   16 |        0.155 |         664.80 |    192 |\n#     |   17 |        0.151 |         340.64 |     64 |\n#     |   18 |        0.176 |         597.55 |    128 |\n#     |   19 |        0.220 |        1054.37 |    192 |\n#     |   20 |        0.150 |         686.01 |    128 |\n#     |   21 |        0.159 |         650.88 |    128 |\n#     |   22 |        0.073 |         358.19 |     64 |\n#     |   23 |        0.031 |          70.63 |     64 |\n#     |   24 |        0.251 |         947.73 |    128 |\n#     |   25 |        0.157 |         652.47 |    128 |\n#     |   26 |        0.215 |         954.84 |    128 |\n#     |   27 |        0.237 |         868.92 |    128 |\n#     |   28 |        0.266 |         774.06 |    128 |\n#     -------------------------------------------------\n#     Estimated total latency: 10.016 ms      Trials: 3992    Used time : 1131 s      Next ID: 15\n#\n#   This table lists the latency and (estimated) speed of all tasks.\n#   It also lists the allocation of measurement trials for all tasks.\n#   The last line prints the total weighted latency of these tasks,\n#   which can be a rough estimation of the end-to-end execution time\n#   of the network.\n#   The last line also prints the total number of measurement trials,\n#   total time spent on auto-tuning and the id of the next task to tune.\n#\n#   There will also be some \"tvm::Error\"s errors, because the\n#   auto-scheduler will try some invalid schedules.\n#   You can safely ignore them if the tuning can continue, because these\n#   errors are isolated from the main process.\n#\n\n######################################################################\n# .. note:: Terminate the tuning earlier\n#\n#   You can terminate the tuning earlier by forcibly killing this process.\n#   As long as you get at least one valid schedule for each task in the log file,\n#   you should be able to do the compilation (the secion below).\n#\n\n#################################################################\n# Other Tips\n# ----------\n# 1. During the tuning, the auto-scheduler needs to compile many programs and\n#    extract feature from them. This part is CPU-intensive,\n#    so a high-performance CPU with many cores is recommended for faster search.\n# 2. You can use :code:`python3 -m tvm.auto_scheduler.measure_record --mode distill -i log.json`\n#    to distill the large log file and only save the best useful records.\n# 3. You can resume a search from the previous log file. You just need to\n#    add a new argument :code:`load_log_file` when creating the task scheduler\n#    in function :code:`run_tuning`. Say,\n#    :code:`tuner = auto_scheduler.TaskScheduler(tasks, task_weights, load_log_file=log_file)`\n# 4. If you have multiple target GPUs, you can use all of them for measurements to\n#    parallelize the measurements. Check this :ref:`section <tutorials-autotvm-scale-up-rpc-tracker>`\n#    to learn how to use the RPC Tracker and RPC Server.\n#    To use the RPC Tracker in auto-scheduler, replace the runner in :code:`TuningOptions`\n#    with :any:`auto_scheduler.RPCRunner`.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_network_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-scheduling a Neural Network for x86 CPU\n============================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, \\\n            `Chengfan Jia <https://github.com/jcf94/>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole neural\nnetwork for x86 CPU with the auto-scheduler.\n\nTo auto-tune a neural network, we partition the network into small subgraphs and\ntune them independently. Each subgraph is treated as one search task.\nA task scheduler slices the time and dynamically allocates time resources to\nthese tasks. The task scheduler predicts the impact of each task on the end-to-end\nexecution time and prioritizes the one that can reduce the execution time the most.\n\nFor each subgraph, we use the compute declaration in :code:`tvm/python/topi` to\nget the computational DAG in the tensor expression form.\nWe then use the auto-scheduler to construct a search space of this DAG and search\nfor good schedules (low-level optimizations).\n\nDifferent from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on\nmanual templates to define the search space, the auto-scheduler does not require any\nschedule templates. In other words, the auto-scheduler only uses the compute declarations\nin :code:`tvm/python/topi` and does not use existing schedule templates.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, auto_scheduler\nfrom tvm.relay import data_dep_optimization as ddo\nimport tvm.relay.testing\nfrom tvm.contrib import graph_executor\n\n#################################################################\n# Define a Network\n# ----------------\n# First, we need to define the network with relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow\n# (see :ref:`front end tutorials<tutorial-frontend>`).\n#\n# For convolutional neural networks, although auto-scheduler can work correctly\n# with any layout, we found the best performance is typically achieved with NHWC layout.\n# We also implemented more optimizations for NHWC layout with the auto-scheduler.\n# So it is recommended to convert your models to NHWC layout to use the auto-scheduler.\n# You can use :ref:`ConvertLayout <convert-layout-usage>` pass to do the layout conversion in TVM.\n\n\ndef get_network(name, batch_size, layout=\"NHWC\", dtype=\"float32\", use_sparse=False):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n\n    # auto-scheduler prefers NHWC layout\n    if layout == \"NHWC\":\n        image_shape = (224, 224, 3)\n    elif layout == \"NCHW\":\n        image_shape = (3, 224, 224)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    input_shape = (batch_size,) + image_shape\n    output_shape = (batch_size, 1000)\n\n    if name.startswith(\"resnet-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name.startswith(\"resnet3d-\"):\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer,\n            batch_size=batch_size,\n            layout=layout,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(\n            batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape\n        )\n    elif name == \"squeezenet_v1.1\":\n        assert layout == \"NCHW\", \"squeezenet_v1.1 only supports NCHW layout\"\n        mod, params = relay.testing.squeezenet.get_workload(\n            version=\"1.1\",\n            batch_size=batch_size,\n            dtype=dtype,\n            image_shape=image_shape,\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299) if layout == \"NCHW\" else (batch_size, 299, 299, 3)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        assert layout == \"NCHW\"\n\n        block = get_model(\"resnet50_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    elif name == \"mlp\":\n        mod, params = relay.testing.mlp.get_workload(\n            batch_size=batch_size, dtype=dtype, image_shape=image_shape, num_classes=1000\n        )\n    else:\n        raise ValueError(\"Network not found.\")\n\n    if use_sparse:\n        from tvm.topi.sparse.utils import convert_model_dense_to_sparse\n\n        mod, params = convert_model_dense_to_sparse(mod, params, bs_r=4, random_params=True)\n\n    return mod, params, input_shape, output_shape\n\n\n# Define the neural network and compilation target.\n# If the target machine supports avx512 instructions, replace the\n# \"llvm -mcpu=core-avx2\" with \"llvm -mcpu=skylake-avx512\"\nnetwork = \"resnet-50\"\nuse_sparse = False\nbatch_size = 1\nlayout = \"NHWC\"\ntarget = tvm.target.Target(\"llvm -mcpu=core-avx2\")\ndtype = \"float32\"\nlog_file = \"%s-%s-B%d-%s.json\" % (network, layout, batch_size, target.kind.name)\n\n#################################################################\n# Extract Search Tasks\n# --------------------\n# Next, we extract the search tasks and their weights from a network.\n# The weight of a task is the number of appearances of the task's subgraph\n# in the whole network.\n# By using the weight, we can approximate the end-to-end latency of the network\n# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the\n# latency of a task and :code:`weight[t]` is the weight of the task.\n# The task scheduler will just optimize this objective.\n\n# Extract tasks from the network\nprint(\"Get model...\")\nmod, params, input_shape, output_shape = get_network(\n    network,\n    batch_size,\n    layout,\n    dtype=dtype,\n    use_sparse=use_sparse,\n)\nprint(\"Extract tasks...\")\ntasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n\nfor idx, task in enumerate(tasks):\n    print(\"========== Task %d  (workload key: %s) ==========\" % (idx, task.workload_key))\n    print(task.compute_dag)\n\n#################################################################\n# Begin Tuning\n# ------------\n# Now, we set some options for tuning and launch the search tasks\n#\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.\n#   You can set it to a small number (e.g., 200) for a fast demonstrative run.\n#   In practice, we recommend setting it around :code:`800 * len(tasks)`,\n#   which is typically enough for the search to converge.\n#   For example, there are 29 tasks in resnet-50, so we can set it as 20000.\n#   You can adjust this parameter according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions`,\n#   :any:`auto_scheduler.LocalRunner` for more parameters.\n#\n\n\ndef run_tuning():\n    print(\"Begin tuning...\")\n    tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=200,  # change this to 20000 to achieve the best performance\n        runner=auto_scheduler.LocalRunner(repeat=10, enable_cpu_cache_flush=True),\n        measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    )\n\n    if use_sparse:\n        from tvm.topi.sparse.utils import sparse_sketch_rules\n\n        search_policy = [\n            auto_scheduler.SketchPolicy(\n                task,\n                program_cost_model=auto_scheduler.XGBModel(),\n                init_search_callbacks=sparse_sketch_rules(),\n            )\n            for task in tasks\n        ]\n\n        tuner.tune(tune_option, search_policy=search_policy)\n    else:\n        tuner.tune(tune_option)\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# run_tuning()\n\n\n######################################################################\n# .. note:: Explain the printed information during tuning\n#\n#   During the tuning, a lot of information will be printed on the console.\n#   They are used for debugging purposes. The most important info is the output\n#   of the task scheduler. The following table is a sample output.\n#\n#   .. code-block:: c\n#\n#     ----------------------------------------------------------------------\n#     ------------------------------  [ Task Scheduler ]\n#     ----------------------------------------------------------------------\n#     |  ID  | Latency (ms) | Speed (GFLOPS) | Trials |\n#     -------------------------------------------------\n#     |    0 |        0.010 |           0.40 |     64 |\n#     |    1 |        0.087 |          47.19 |     64 |\n#     |    2 |        0.008 |          -0.00 |     64 |\n#     |    3 |        0.177 |         582.07 |     64 |\n#     |    4 |        0.268 |         862.37 |    256 |\n#     |    5 |        0.166 |         621.13 |    128 |\n#     |    6 |        0.170 |         605.10 |    128 |\n#     |    7 |        0.128 |         403.20 |     64 |\n#     |    8 |        0.189 |         545.71 |     64 |\n#     |    9 |        0.231 |        1001.01 |    448 |\n#     |   10 |        0.155 |         664.80 |    256 |\n#     |   11 |        0.155 |         662.86 |    256 |\n#     |   12 |        0.119 |         434.08 |     64 |\n#     |   13 |        0.199 |         522.13 |     64 |\n#     |   14 |        0.235 |         986.56 |    320 |\n#     |   15 |        0.149 |         689.13 |    128 |\n#     |   16 |        0.155 |         664.80 |    192 |\n#     |   17 |        0.151 |         340.64 |     64 |\n#     |   18 |        0.176 |         597.55 |    128 |\n#     |   19 |        0.220 |        1054.37 |    192 |\n#     |   20 |        0.150 |         686.01 |    128 |\n#     |   21 |        0.159 |         650.88 |    128 |\n#     |   22 |        0.073 |         358.19 |     64 |\n#     |   23 |        0.031 |          70.63 |     64 |\n#     |   24 |        0.251 |         947.73 |    128 |\n#     |   25 |        0.157 |         652.47 |    128 |\n#     |   26 |        0.215 |         954.84 |    128 |\n#     |   27 |        0.237 |         868.92 |    128 |\n#     |   28 |        0.266 |         774.06 |    128 |\n#     -------------------------------------------------\n#     Estimated total latency: 10.016 ms      Trials: 3992    Used time : 1131 s      Next ID: 15\n#\n#   This table lists the latency and (estimated) speed of all tasks.\n#   It also lists the allocation of measurement trials for all tasks.\n#   The last line prints the total weighted latency of these tasks,\n#   which can be a rough estimation of the end-to-end execution time\n#   of the network.\n#   The last line also prints the total number of measurement trials,\n#   total time spent on auto-tuning and the id of the next task to tune.\n#\n#   There will also be some \"tvm::Error\"s errors, because the\n#   auto-scheduler will try some invalid schedules.\n#   You can safely ignore them if the tuning can continue, because these\n#   errors are isolated from the main process.\n#\n\n######################################################################\n# .. note:: Terminate the tuning earlier\n#\n#   You can terminate the tuning earlier by forcibly killing this process.\n#   As long as you get at least one valid schedule for each task in the log file,\n#   you should be able to do the compilation (the secion below).\n#\n\n\n#################################################################\n# Compile and Evaluate\n# --------------------\n# After auto-tuning, we can compile the network with the best schedules we found.\n# All measurement records are dumped into the log file during auto-tuning,\n# so we can read the log file and load the best schedules.\n\n# Compile with the history best\nprint(\"Compile...\")\nwith auto_scheduler.ApplyHistoryBest(log_file):\n    with tvm.transform.PassContext(opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}):\n        lib = relay.build(mod, target=target, params=params)\n\n# Create graph executor\ndev = tvm.device(str(target), 0)\nmodule = graph_executor.GraphModule(lib[\"default\"](dev))\ndata_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\nmodule.set_input(\"data\", data_tvm)\n\n# Evaluate\nprint(\"Evaluate inference time cost...\")\nprint(module.benchmark(dev, repeat=3, min_repeat_ms=500))\n\n\n#################################################################\n# Other Tips\n# ----------\n# 1. During the tuning, the auto-scheduler needs to compile many programs and\n#    extract feature from them. This part is CPU-intensive,\n#    so a high-performance CPU with many cores is recommended for faster search.\n# 2. You can use :code:`python3 -m tvm.auto_scheduler.measure_record --mode distill -i log.json`\n#    to distill the large log file and only save the best useful records.\n# 3. You can resume a search from the previous log file. You just need to\n#    add a new argument :code:`load_log_file` when creating the task scheduler\n#    in function :code:`run_tuning`. Say,\n#    :code:`tuner = auto_scheduler.TaskScheduler(tasks, task_weights, load_log_file=log_file)`\n# 4. If you have multiple target CPUs, you can use all of them for measurements to\n#    parallelize the measurements. Check this :ref:`section <tutorials-autotvm-scale-up-rpc-tracker>`\n#    to learn how to use the RPC Tracker and RPC Server.\n#    To use the RPC Tracker in auto-scheduler, replace the runner in :code:`TuningOptions`\n#    with :any:`auto_scheduler.RPCRunner`.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autoscheduler/tune_sparse_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-scheduling Sparse Matrix Multiplication on CPU with Custom Sketch Rule\n===========================================================================\n**Author**: `Chengfan Jia <https://github.com/jcf94/>`_\n\nThis is a tutorial on how to use the auto-scheduler to tune a sparse matrix multiplication for\nCPUs.\n\nAuto-scheduler is designed to explore the schedule with best performance for a given computation\ndeclaration automatically. While sometimes, we may have a demand to try some special ops which may\nnot been well-supported by auto-scheduler's default sketch rules and result in poor performance.\nFortunately, auto-scheduler currently allows user to provide a CustomSketch to cover these cases.\n\nWe use sparse matrix multiplication as an example in this tutorial to demonstrate how to implement\nand plug a custom sketch rule to the auto-scheduler's search policy.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te, auto_scheduler, runtime, topi\nfrom tvm.auto_scheduler import _ffi_api\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.sparse.utils import random_bsr_matrix\n\n######################################################################\n# Define the computation\n# ^^^^^^^^^^^^^^^^^^^^^^\n# To begin with, let us define the computation of a sparse matmul with several relu and bias add.\n# The function should return the list of input/output tensors.\n# From these tensors, the auto-scheduler can get the whole computational graph.\n\n\n@auto_scheduler.register_workload\ndef sparse_dense(M, N, K, w_data_shape, w_indices_shape, w_indptr_shape, dtype):\n    X = te.placeholder(shape=(M, K), dtype=dtype)\n    W_data = te.placeholder(shape=w_data_shape, dtype=dtype)\n    W_indices = te.placeholder(shape=w_indices_shape, dtype=\"int32\")\n    W_indptr = te.placeholder(shape=w_indptr_shape, dtype=\"int32\")\n    B = te.placeholder(shape=(M, N), dtype=dtype)\n\n    out = topi.nn.sparse_dense(topi.nn.relu(X), W_data, W_indices, W_indptr)\n    out = te.compute((M, N), lambda i, j: out[i, j] + B[i, j], name=\"BiasAdd\")\n    out = topi.nn.relu(out)\n\n    return [X, W_data, W_indices, W_indptr, B, out]\n\n\n######################################################################\n# Special step for sparse workload\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# During schedule tuning, auto-scheduler will use random inputs to measure the performance of a\n# generated schedule. While we cannot directly use a random array as the input of a sparse op, for\n# the \"indices\" and \"indptr\" array are meaningful for the computation.\n#\n# To solve this problem, we register these as special buffers, and load them when process program\n# measuring.\n# See the `tvm.auto_scheduler.measure.py` for more details.\n\n# Define the basic shapes of this sparse computation\nM = 128\nK = 256\nN = 512\nBS_R = 16\nBS_C = 1\ndensity = 0.6\n\n# Generate the test data with numpy\nX_np = np.random.randn(M, K).astype(\"float32\")\nX_np = np.maximum(np.zeros((M, K), dtype=\"float32\"), X_np)  # Relu\nW_sp_np = random_bsr_matrix(N, K, BS_R, BS_C, density=density, dtype=\"float32\")\nW_np = W_sp_np.todense()\nY_np = X_np @ W_np.T  # Process the matrix multiplication\nB_np = np.random.randn(M, N).astype(\"float32\")\nY_np = Y_np + B_np  # Bias add\nY_np = np.maximum(np.zeros((M, N), dtype=\"float32\"), Y_np)  # Relu\n\n######################################################################\n# Create the search task\n# ^^^^^^^^^^^^^^^^^^^^^^\n# We then create a search task with M=N=K=512 and dtype=\"float32\"\n# If your machine supports avx instructions, you can\n#\n#   - replace \"llvm\" below with \"llvm -mcpu=core-avx2\" to enable AVX2\n#   - replace \"llvm\" below with \"llvm -mcpu=skylake-avx512\" to enable AVX-512\n\ntarget = tvm.target.Target(\"llvm\")\n\n# Register the sparse data to task inputs\nprefix = \"sparse_dense_bsr_%d_%d_%d_%d_%d_%d_\" % (\n    N,\n    K,\n    BS_R,\n    BS_C,\n    W_sp_np.indices.shape[0],\n    W_sp_np.indptr.shape[0],\n)\ntask = tvm.auto_scheduler.SearchTask(\n    func=sparse_dense,\n    args=(M, N, K, W_sp_np.data.shape, W_sp_np.indices.shape, W_sp_np.indptr.shape, \"float32\"),\n    target=target,\n    task_inputs={\n        prefix + \"W_data\": runtime.ndarray.array(W_sp_np.data),\n        prefix + \"W_indices\": runtime.ndarray.array(W_sp_np.indices),\n        prefix + \"W_indptr\": runtime.ndarray.array(W_sp_np.indptr),\n    },\n    task_inputs_save_to_file=True,\n)\n\n# Inspect the computational graph\nprint(\"Computational DAG:\")\nprint(task.compute_dag)\n\n######################################################################\n# Write the custom sketch for sparse dense op\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# Before tuning, we will need to define the CustomSketchRule for the sparse dense op.\n#\n# CustomSketchRule consists of two parts: the condition function and the apply function.\n#\n#   - condition function: describe when to apply this sketch rule. For example, we can only apply\n#     the rule to the sparse ops by matching their name and tag.\n#   - apply function: describe how to generate the initial sketch. You can implement it using\n#     auto-scheduler provided loop state APIs.\n\n\ndef meet_condition_func(search_policy, state, stage_id):\n    state = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if state.stages[stage_id].op.tag in [\n        \"sparse_dense_sp_rhs_bsrmm\",\n        \"sparse_dense_sp_rhs_bsrmm_block\",\n    ]:\n        return auto_scheduler.PreloadCustomSketchRule.APPLY_AND_SKIP_REST\n    else:\n        return auto_scheduler.PreloadCustomSketchRule.PASS\n\n\ndef apply_func(search_policy, state, stage_id):\n    ret = []\n    s0 = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if s0.stages[stage_id].op.tag == \"sparse_dense_sp_rhs_bsrmm_block\":\n        return [s0.state_object, stage_id - 1]\n\n    sparse_dense = s0.stages[stage_id].op\n    sparse_dense_block = s0.stages[stage_id - 1].op\n    assert sparse_dense.tag == \"sparse_dense_sp_rhs_bsrmm\"\n    assert sparse_dense_block.tag == \"sparse_dense_sp_rhs_bsrmm_block\"\n\n    # Set the default consumer of compute block\n    consumer = sparse_dense\n\n    # If sparse dense has a single elementwise consumer\n    # We can compute inline the sparse_dense output stage\n    consumers = _ffi_api.SearchPolicyUtilsGetConsumers(\n        search_policy.search_task, s0.state_object, stage_id\n    )\n    if len(consumers) == 1:\n        consumer_id = int(consumers.items()[0][0])\n        if _ffi_api.SearchPolicyUtilsIsElementwiseMatch(\n            search_policy.search_task, s0.state_object, stage_id, consumer_id\n        ):\n            consumer = s0.stages[consumer_id].op\n            s0.compute_inline(sparse_dense)\n\n    i, nb_j, j, row_offset, c = s0[sparse_dense_block].iters\n    m, n = s0[consumer].iters\n    i0, i1, i2 = s0.split(sparse_dense_block, i, [None, None])\n    m0, m1 = s0.follow_split(consumer, m, len(s0.transform_steps) - 1, 1)\n    j0, j1 = s0.split(sparse_dense_block, nb_j, [None])\n    n0, n1 = s0.follow_split(consumer, n, len(s0.transform_steps) - 1, 1)\n    s0.reorder(sparse_dense_block, [i0, j0, i1, j1, row_offset, i2, j, c])\n    s0.reorder(consumer, [m0, n0, m1, n1])\n    s0.compute_at(sparse_dense_block, consumer, n0)\n\n    ret.append([s0.state_object, stage_id - 2])\n\n    return ret\n\n\n######################################################################\n# Next, we set parameters for the auto-scheduler with the custom sketch plugged in.\n#\n# * :code:`num_measure_trials` is the number of measurement trials we can use during the search.\n#   We only make 10 trials in this tutorial for a fast demonstration. In practice, 1000 is a\n#   good value for the search to converge. You can do more trials according to your time budget.\n# * In addition, we use :code:`RecordToFile` to dump measurement records into a file\n#   `sparse_dense.json`.\n#   The measurement records can be used to query the history best, resume the search,\n#   and do more analyses later.\n# * see :any:`auto_scheduler.TuningOptions` for more parameters\n# * Here, we need to create a :code:`auto_scheduler.SketchPolicy` object, and add the custom sketch\n#   rule as a `init_search_callbacks`.\n\nlog_file = \"sparse_dense.json\"\ntune_option = auto_scheduler.TuningOptions(\n    num_measure_trials=10,\n    measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    verbose=2,\n)\n\nsearch_policy = auto_scheduler.SketchPolicy(\n    task,\n    program_cost_model=auto_scheduler.XGBModel(),\n    init_search_callbacks=[\n        auto_scheduler.PreloadCustomSketchRule(meet_condition_func, apply_func, \"SparseDense\")\n    ],\n)\n\n######################################################################\n# Run the search\n# ^^^^^^^^^^^^^^\n# Now we get all inputs ready.\n# We can kick off the search and let the auto-scheduler do its magic.\n# After some measurement trials, we can load the best schedule from the log\n# file and apply it.\n\n# Run auto-tuning (search)\n# Notice: We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\ntask.tune(tune_option, search_policy)\n\n# Apply the best schedule\nsch, args = task.apply_best(log_file)\n\n######################################################################\n# We can lower the schedule to see the IR after auto-scheduling.\n# The auto-scheduler correctly performs optimizations including multi-level tiling,\n# layout transformation, parallelization, vectorization, unrolling, and operator fusion.\n\nprint(\"Lowered TIR:\")\nprint(tvm.lower(sch, args, simple_mode=True))\n\n######################################################################\n# Check correctness and evaluate performance\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# We build the binary and check its correctness and performance.\n\nfunc = tvm.build(sch, args, target)\n\ndev = tvm.cpu()\n\nX_tvm = tvm.nd.array(X_np, device=dev)\nW_data_tvm = tvm.nd.array(W_sp_np.data, device=dev)\nW_indices_tvm = tvm.nd.array(W_sp_np.indices, device=dev)\nW_indptr_tvm = tvm.nd.array(W_sp_np.indptr, device=dev)\nB_tvm = tvm.nd.array(B_np, device=dev)\nY_tvm = tvm.nd.empty(Y_np.shape, device=dev)\n\nfunc(X_tvm, W_data_tvm, W_indices_tvm, W_indptr_tvm, B_tvm, Y_tvm)\n\n# Check results\ntvm.testing.assert_allclose(Y_np, Y_tvm.numpy(), atol=1e-4, rtol=1e-4)\n\n# Evaluate execution time.\nevaluator = func.time_evaluator(func.entry_name, dev, min_repeat_ms=500)\nprint(\n    \"Execution time of this operator: %.3f ms\"\n    % (\n        np.median(evaluator(X_tvm, W_data_tvm, W_indices_tvm, W_indptr_tvm, B_tvm, Y_tvm).results)\n        * 1000\n    )\n)\n\n######################################################################\n# .. note:: Tuning result example\n#\n#   .. code-block:: c\n#\n#    ----------------------------------------------------------------------\n#    Lowered TIR:\n#    primfn(placeholder_5: handle, placeholder_6: handle, placeholder_7: handle, placeholder_8: handle, placeholder_9: handle, compute_1: handle) -> ()\n#      attr = {\"global_symbol\": \"main\", \"tir.noalias\": True}\n#      buffers = {placeholder_2: Buffer(placeholder_10: Pointer(float32), float32, [9831, 16, 1], []),\n#                 placeholder_4: Buffer(placeholder_11: Pointer(int32), int32, [33], []),\n#                 placeholder_3: Buffer(placeholder_12: Pointer(float32), float32, [512, 512], []),\n#                 compute: Buffer(compute_2: Pointer(float32), float32, [512, 512], []),\n#                 placeholder_1: Buffer(placeholder_13: Pointer(float32), float32, [512, 512], []),\n#                 placeholder: Buffer(placeholder_14: Pointer(int32), int32, [9831], [])}\n#      buffer_map = {placeholder_7: placeholder, placeholder_9: placeholder_1, placeholder_6: placeholder_2, compute_1: compute, placeholder_5: placeholder_3, placeholder_8: placeholder_4} {\n#      for (i0.outer.i1.outer.fused: int32, 0, 1024) \"parallel\" {\n#        attr [compute_3: Pointer(float32)] \"storage_scope\" = \"global\";\n#        allocate(compute_3, float32, [256]) {\n#          for (nb_j.inner: int32, 0, 2) {\n#            for (i.inner.init: int32, 0, 8) {\n#              for (j.init: int32, 0, 16) {\n#                compute_3[(((i.inner.init*32) + (nb_j.inner*16)) + j.init)] = 0f32\n#              }\n#            }\n#            for (elem_idx: int32, 0, ((int32*)placeholder_11[(((floormod(i0.outer.i1.outer.fused, 16)*2) + nb_j.inner) + 1)] - (int32*)placeholder_11[((floormod(i0.outer.i1.outer.fused, 16)*2) + nb_j.inner)])) {\n#              for (i.inner: int32, 0, 8) {\n#                for (j: int32, 0, 16) {\n#                  compute_3[(((i.inner*32) + (nb_j.inner*16)) + j)] = ((float32*)compute_3[(((i.inner*32) + (nb_j.inner*16)) + j)] + ((float32*)placeholder_10[((((int32*)placeholder_11[((floormod(i0.outer.i1.outer.fused, 16)*2) + nb_j.inner)]*16) + (elem_idx*16)) + j)]*max((float32*)placeholder_12[(((floordiv(i0.outer.i1.outer.fused, 16)*4096) + (i.inner*512)) + (int32*)placeholder_14[((int32*)placeholder_11[((floormod(i0.outer.i1.outer.fused, 16)*2) + nb_j.inner)] + elem_idx)])], 0f32)))\n#                }\n#              }\n#            }\n#          }\n#          for (i0.inner: int32, 0, 8) {\n#            compute_2[ramp((((floordiv(i0.outer.i1.outer.fused, 16)*4096) + (i0.inner*512)) + (floormod(i0.outer.i1.outer.fused, 16)*32)), 1, 32)] = max(((float32x32*)compute_3[ramp((i0.inner*32), 1, 32)] + (float32x32*)placeholder_13[ramp((((floordiv(i0.outer.i1.outer.fused, 16)*4096) + (i0.inner*512)) + (floormod(i0.outer.i1.outer.fused, 16)*32)), 1, 32)]), broadcast(0f32, 32))\n#          }\n#        }\n#      }\n#    }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autotvm/tune_conv2d_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTuning High Performance Convolution on NVIDIA GPUs\n=========================================================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_\n\nThis is an advanced tutorial for writing high performance tunable template for\nNVIDIA GPU. By running auto-tuner on this template, we can outperform the\nvendor provided library CuDNN in many cases.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado cloudpickle\n#\n# To make TVM run faster in tuning, it is recommended to use cython\n# as FFI of tvm. In the root directory of tvm, execute\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport logging\nimport sys\nimport numpy as np\n\nimport tvm\nfrom tvm import te, topi, testing\nfrom tvm.topi.testing import conv2d_nchw_python\nimport tvm.testing\n\nfrom tvm import autotvm\n\n######################################################################\n# Step 1:  Define the search space\n# --------------------------------\n# There are plenty of useful schedule primitives in tvm. You can also find\n# some tutorials that describe them in more details, such as\n# (1). :ref:`opt-conv-gpu`\n# (2). `Optimizing DepthwiseConv on NVIDIA GPU <https://tvm.apache.org/2017/08/22/Optimize-Deep-Learning-GPU-Operators-with-TVM-A-Depthwise-Convolution-Example>`_\n#\n# However, their implementations are manually tuned for some special input\n# shapes. In this section, we build a large enough space to cover\n# the techniques used in these tutorials. Then we rely on the efficient auto-tuner\n# to search through this space and pick some good configurations.\n#\n# If you are familiar with writing cuda schedule, you can find the following\n# template is very general. Actually this template can be easily modified\n# to tune other operators such as depthwise convolution and GEMM.\n# In order to fully understand this template, you should be familiar with\n# the schedule primitives and auto tuning API. You can refer to the above\n# tutorials and :ref:`autotvm tutorial <tutorial-autotvm-matmul-x86>`\n#\n# It is worth noting that the search space for a conv2d operator\n# can be very large (at the level of 10^9 for some input shapes)\n#\n\n\n@autotvm.template(\"tutorial/conv2d_no_batching\")\ndef conv2d_no_batching(N, H, W, CO, CI, KH, KW, stride, padding):\n    assert N == 1, \"Only consider batch_size = 1 in this template\"\n\n    data = te.placeholder((N, CI, H, W), name=\"data\")\n    kernel = te.placeholder((CO, CI, KH, KW), name=\"kernel\")\n    conv = topi.nn.conv2d_nchw(data, kernel, stride, padding, dilation=1, out_dtype=\"float32\")\n    s = te.create_schedule([conv.op])\n\n    ##### space definition begin #####\n    n, f, y, x = s[conv].op.axis\n    rc, ry, rx = s[conv].op.reduce_axis\n\n    cfg = autotvm.get_config()\n    cfg.define_split(\"tile_f\", f, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=3)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=3)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=3)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n    ##### space definition end #####\n\n    # inline padding\n    pad_data = s[conv].op.input_tensors[0]\n    s[pad_data].compute_inline()\n    data, raw_data = pad_data, data\n\n    output = conv\n    OL = s.cache_write(conv, \"local\")\n\n    # create cache stage\n    AA = s.cache_read(data, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n    AL = s.cache_read(AA, \"local\", [OL])\n    WL = s.cache_read(WW, \"local\", [OL])\n\n    # tile and bind spatial axes\n    n, f, y, x = s[output].op.axis\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n    kernel_scope = n  # this is the scope to attach global config inside this kernel\n\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(n, bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, f, y, x = s[OL].op.axis\n    rc, ry, rx = s[OL].op.reduce_axis\n    rco, rcm, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    ryo, rym, ryi = cfg[\"tile_rx\"].apply(s, OL, ry)\n    rxo, rxm, rxi = cfg[\"tile_ry\"].apply(s, OL, rx)\n    s[OL].reorder(rco, ryo, rxo, rcm, rym, rxm, rci, ryi, rxi, n, f, y, x)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n    s[AL].compute_at(s[OL], rxm)\n    s[WL].compute_at(s[OL], rxm)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        n, f, y, x = s[load].op.axis\n        fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # tune unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    return s, [raw_data, kernel, conv]\n\n\n######################################################################\n# Step 2:  Search through the space\n# ---------------------------------\n# We pick the last layer on resnet as test case.\n# Since our space is very large, :code:`XGBoostTuner` is most suitable\n# for our case. Here we only do 20 trials for demonstration.\n# In practice, making 1000 trials usually can find some good kernels\n# for this template\n\n# logging config (for printing tuning log to screen)\nlogging.getLogger(\"autotvm\").setLevel(logging.DEBUG)\nlogging.getLogger(\"autotvm\").addHandler(logging.StreamHandler(sys.stdout))\n\n# the last layer in resnet\nN, H, W, CO, CI, KH, KW, strides, padding = 1, 7, 7, 512, 512, 3, 3, (1, 1), (1, 1)\ntask = autotvm.task.create(\n    \"tutorial/conv2d_no_batching\", args=(N, H, W, CO, CI, KH, KW, strides, padding), target=\"cuda\"\n)\nprint(task.config_space)\n\n# Use local gpu, measure 10 times for every config to reduce variance\n# The timeout of compiling a program is 10 seconds, the timeout for running is 4 seconds\nmeasure_option = autotvm.measure_option(\n    builder=autotvm.LocalBuilder(),\n    runner=autotvm.LocalRunner(repeat=3, min_repeat_ms=100, timeout=4),\n)\n\n# Begin tuning, log records to file `conv2d.log`\n# During tuning we will also try many invalid configs, so you are expected to\n# see many error reports. As long as you can see non-zero GFLOPS, it is okay.\ntuner = autotvm.tuner.XGBTuner(task)\ntuner.tune(\n    n_trial=20,\n    measure_option=measure_option,\n    callbacks=[autotvm.callback.log_to_file(\"conv2d.log\")],\n)\n\n#########################################################################\n# Finally we can inspect the best config from log file, check correctness,\n# and measure running time.\n\n# inspect the best config\ndispatch_context = autotvm.apply_history_best(\"conv2d.log\")\nbest_config = dispatch_context.query(task.target, task.workload)\nprint(\"\\nBest config:\")\nprint(best_config)\n\n# apply history best from log file\nwith autotvm.apply_history_best(\"conv2d.log\"):\n    with tvm.target.Target(\"cuda\"):\n        s, arg_bufs = conv2d_no_batching(N, H, W, CO, CI, KH, KW, strides, padding)\n        func = tvm.build(s, arg_bufs)\n\n# check correctness\na_np = np.random.uniform(size=(N, CI, H, W)).astype(np.float32)\nw_np = np.random.uniform(size=(CO, CI, KH, KW)).astype(np.float32)\nc_np = conv2d_nchw_python(a_np, w_np, strides, padding)\n\ndev = tvm.cuda()\na_tvm = tvm.nd.array(a_np, device=dev)\nw_tvm = tvm.nd.array(w_np, device=dev)\nc_tvm = tvm.nd.empty(c_np.shape, device=dev)\nfunc(a_tvm, w_tvm, c_tvm)\n\ntvm.testing.assert_allclose(c_np, c_tvm.numpy(), rtol=1e-2)\n\n# Evaluate running time. Here we choose a large repeat number (400) to reduce the noise\n# and the overhead of kernel launch. You can also use nvprof to validate the result.\nevaluator = func.time_evaluator(func.entry_name, dev, number=400)\nprint(\"Time cost of this operator: %f\" % evaluator(a_tvm, w_tvm, c_tvm).mean)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autotvm/tune_relay_arm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tune_relay_arm:\n\nAuto-tuning a Convolutional Network for ARM CPU\n===============================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Zhao Wu <https://github.com/FrozenGene>`_, `Eddie Yan <https://github.com/eqy>`_\n\nAuto-tuning for a specific ARM device is critical for getting the best\nperformance. This is a tutorial about how to tune a whole convolutional\nnetwork.\n\nThe operator implementation for ARM CPU in TVM is written in template form.\nThe template has many tunable knobs (tile factor, vectorization, unrolling, etc).\nWe will tune all convolution and depthwise convolution operators\nin the neural network. After tuning, we produce a log file which stores\nthe best knob values for all required operators. When the TVM compiler compiles\nthese operators, it will query this log file to get the best knob values.\n\nWe also released pre-tuned parameters for some arm devices. You can go to\n`ARM CPU Benchmark <https://github.com/apache/tvm/wiki/Benchmark#arm-cpu>`_\nto see the results.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado cloudpickle\n#\n# To make TVM run faster during tuning, it is recommended to use cython\n# as FFI of TVM. In the root directory of TVM, execute\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\nimport numpy as np\nimport tvm\nfrom tvm import relay, autotvm\nimport tvm.relay.testing\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.contrib.utils import tempdir\nimport tvm.contrib.graph_executor as runtime\n\n#################################################################\n# Define network\n# --------------\n# First we need to define the network in relay frontend API.\n# We can load some pre-defined network from :code:`relay.testing`.\n# We can also load models from MXNet, ONNX and TensorFlow.\n\n\ndef get_network(name, batch_size):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n    output_shape = (batch_size, 1000)\n\n    if \"resnet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"vgg\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.vgg.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size)\n    elif name == \"squeezenet_v1.1\":\n        mod, params = relay.testing.squeezenet.get_workload(\n            batch_size=batch_size, version=\"1.1\", dtype=dtype\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params, input_shape, output_shape\n\n\n#################################################################\n# Start RPC Tracker\n# -----------------\n# TVM uses RPC session to communicate with ARM boards.\n# During tuning, the tuner will send the generated code to the board and\n# measure the speed of code on the board.\n#\n# To scale up the tuning, TVM uses RPC Tracker to manage distributed devices.\n# The RPC Tracker is a centralized controller node. We can register all devices to\n# the tracker. For example, if we have 10 phones, we can register all of them\n# to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n#\n# To start an RPC tracker, run this command on the host machine. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n\n#################################################################\n# Register Devices to RPC Tracker\n# -----------------------------------\n# Now we can register our devices to the tracker. The first step is to\n# build the TVM runtime for the ARM devices.\n#\n# * For Linux:\n#   Follow this section :ref:`build-tvm-runtime-on-device` to build\n#   the TVM runtime on the device. Then register the device to tracker by\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=rk3399\n#\n#   (replace :code:`[HOST_IP]` with the IP address of your host machine)\n#\n# * For Android:\n#   Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to\n#   install the TVM RPC APK on the android device. Make sure you can pass the android rpc test.\n#   Then you have already registered your device. During tuning, you have to go to developer option\n#   and enable \"Keep screen awake during changing\" and charge your phone to make it stable.\n#\n# After registering devices, we can confirm it by querying rpc_tracker\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n#\n# For example, if we have 2 Huawei mate10 pro, 11 Raspberry Pi 3B and 2 rk3399,\n# the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    mate10pro    2      2     0\n#    rk3399       2      2     0\n#    rpi3b        11     11    0\n#    ----------------------------------\n#\n# You can register multiple devices to the tracker to accelerate the measurement in tuning.\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we should apply some configurations. Here I use an RK3399 board\n# as example. In your setting, you should modify the target and device_key accordingly.\n# set :code:`use_android` to True if you use android phone.\n\n#### DEVICE CONFIG ####\n\n# Replace \"aarch64-linux-gnu\" with the correct target of your board.\n# This target is used for cross compilation. You can query it by :code:`gcc -v` on your device.\ntarget = tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\")\n\n# Also replace this with the device key in your tracker\ndevice_key = \"rk3399\"\n\n# Set this to True if you use android phone\nuse_android = False\n\n#### TUNING OPTION ####\nnetwork = \"resnet-18\"\nlog_file = \"%s.%s.log\" % (device_key, network)\ndtype = \"float32\"\n\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"xgb\",\n    \"n_trial\": 1500,\n    \"early_stopping\": 800,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(build_func=\"ndk\" if use_android else \"default\"),\n        runner=autotvm.RPCRunner(\n            device_key,\n            host=\"127.0.0.1\",\n            port=9190,\n            number=5,\n            timeout=10,\n        ),\n    ),\n}\n\n####################################################################\n#\n# .. note:: How to set tuning options\n#\n#   In general, the default values provided here work well.\n#   If you have enough time budget, you can set :code:`n_trial`, :code:`early_stopping` larger,\n#   which makes the tuning run longer.\n#   If your device runs very slow or your conv2d operators have many GFLOPs, considering to\n#   set timeout larger.\n#\n#   If your model has depthwise convolution, you could consider setting\n#   :code:`try_spatial_pack_depthwise` be :code:`True`, which perform better than default\n#   optimization in general. For example, on ARM CPU A53 2.0GHz, we find it could boost 1.6x\n#   performance of depthwise convolution on Mobilenet V1 model.\n\n###################################################################\n# Begin Tuning\n# ------------\n# Now we can extract tuning tasks from the network and begin tuning.\n# Here, we provide a simple utility function to tune a list of tasks.\n# This function is just an initial implementation which tunes them in sequential order.\n# We will introduce a more sophisticated tuning scheduler in the future.\n\n# You can skip the implementation of this function for this tutorial.\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"xgb_knob\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"knob\")\n        elif tuner == \"xgb_itervar\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"itervar\")\n        elif tuner == \"xgb_curve\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"curve\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # process tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n\n\ndef tune_and_evaluate(tuning_opt):\n    # extract workloads from relay program\n    print(\"Extract tasks...\")\n    mod, params, input_shape, _ = get_network(network, batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(relay.op.get(\"nn.conv2d\"),)\n    )\n\n    # run tuning tasks\n    print(\"Tuning...\")\n    tune_tasks(tasks, **tuning_opt)\n\n    # compile kernels with history best records\n    with autotvm.apply_history_best(log_file):\n        print(\"Compile...\")\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, target=target, params=params)\n\n        # export library\n        tmp = tempdir()\n        if use_android:\n            from tvm.contrib import ndk\n\n            filename = \"net.so\"\n            lib.export_library(tmp.relpath(filename), ndk.create_shared)\n        else:\n            filename = \"net.tar\"\n            lib.export_library(tmp.relpath(filename))\n\n        # upload module to device\n        print(\"Upload...\")\n        remote = autotvm.measure.request_remote(device_key, \"127.0.0.1\", 9190, timeout=10000)\n        remote.upload(tmp.relpath(filename))\n        rlib = remote.load_module(filename)\n\n        # upload parameters to device\n        dev = remote.device(str(target), 0)\n        module = runtime.GraphModule(rlib[\"default\"](dev))\n        data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n        module.set_input(\"data\", data_tvm)\n\n        # evaluate\n        print(\"Evaluate inference time cost...\")\n        print(module.benchmark(dev, number=1, repeat=10))\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate(tuning_option)\n\n######################################################################\n# Sample Output\n# -------------\n# The tuning needs to compile many programs and extract feature from them.\n# So a high performance CPU is recommended.\n# One sample output is listed below.\n# It takes about 2 hours on a 32T AMD Ryzen Threadripper.\n#\n# .. code-block:: bash\n#\n#    Extract tasks...\n#    Tuning...\n#    [Task  1/12]  Current/Best:   22.37/  52.19 GFLOPS | Progress: (544/1000) | 406.59 s Done.\n#    [Task  2/12]  Current/Best:    6.51/  18.77 GFLOPS | Progress: (608/1000) | 325.05 s Done.\n#    [Task  3/12]  Current/Best:    4.67/  24.87 GFLOPS | Progress: (480/1000) | 372.31 s Done.\n#    [Task  4/12]  Current/Best:   11.35/  46.83 GFLOPS | Progress: (736/1000) | 602.39 s Done.\n#    [Task  5/12]  Current/Best:    1.01/  19.80 GFLOPS | Progress: (448/1000) | 262.16 s Done.\n#    [Task  6/12]  Current/Best:    2.47/  23.76 GFLOPS | Progress: (672/1000) | 563.85 s Done.\n#    [Task  7/12]  Current/Best:   14.57/  33.97 GFLOPS | Progress: (544/1000) | 465.15 s Done.\n#    [Task  8/12]  Current/Best:    1.13/  17.65 GFLOPS | Progress: (576/1000) | 365.08 s Done.\n#    [Task  9/12]  Current/Best:   14.45/  22.66 GFLOPS | Progress: (928/1000) | 724.25 s Done.\n#    [Task 10/12]  Current/Best:    3.22/  15.36 GFLOPS | Progress: (864/1000) | 564.27 s Done.\n#    [Task 11/12]  Current/Best:   11.03/  32.23 GFLOPS | Progress: (736/1000) | 635.15 s Done.\n#    [Task 12/12]  Current/Best:    8.00/  21.65 GFLOPS | Progress: (1000/1000) | 1111.81 s Done.\n#    Compile...\n#    Upload...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 162.59 ms (0.06 ms)\n\n######################################################################\n#\n# .. note:: **Experiencing Difficulties?**\n#\n#   The auto tuning module is error-prone. If you always see \" 0.00/ 0.00 GFLOPS\",\n#   then there must be something wrong.\n#\n#   First, make sure you set the correct configuration of your device.\n#   Then, you can print debug information by adding these lines in the beginning\n#   of the script. It will print every measurement result, where you can find useful\n#   error messages.\n#\n#   .. code-block:: python\n#\n#      import logging\n#      logging.getLogger('autotvm').setLevel(logging.DEBUG)\n#\n#   Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autotvm/tune_relay_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-tuning a Convolutional Network for NVIDIA GPU\n==================================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Eddie Yan <https://github.com/eqy/>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole convolutional\nnetwork for NVIDIA GPU.\n\nThe operator implementation for NVIDIA GPU in TVM is written in template form.\nThe template has many tunable knobs (tile factor, unrolling, etc).\nWe will tune all convolution and depthwise convolution operators\nin the neural network. After tuning, we produce a log file which stores\nthe best knob values for all required operators. When the TVM compiler compiles\nthese operators, it will query this log file to get the best knob values.\n\nWe also released pre-tuned parameters for some NVIDIA GPUs. You can go to\n`NVIDIA GPU Benchmark <https://github.com/apache/tvm/wiki/Benchmark#nvidia-gpu>`_\nto see the results.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado cloudpickle\n#\n# To make TVM run faster during tuning, it is recommended to use cython\n# as FFI of tvm. In the root directory of tvm, execute:\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, autotvm\nimport tvm.relay.testing\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nimport tvm.contrib.graph_executor as runtime\n\n#################################################################\n# Define Network\n# --------------\n# First we need to define the network in relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX and TensorFlow.\n\n\ndef get_network(name, batch_size):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n    output_shape = (batch_size, 1000)\n\n    if \"resnet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"vgg\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.vgg.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"squeezenet_v1.1\":\n        mod, params = relay.testing.squeezenet.get_workload(\n            batch_size=batch_size, version=\"1.1\", dtype=dtype\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params, input_shape, output_shape\n\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we apply some configurations.\n\n#### DEVICE CONFIG ####\ntarget = tvm.target.cuda()\n\n#### TUNING OPTION ####\nnetwork = \"resnet-18\"\nlog_file = \"%s.log\" % network\ndtype = \"float32\"\n\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"xgb\",\n    \"n_trial\": 2000,\n    \"early_stopping\": 600,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(timeout=10),\n        runner=autotvm.LocalRunner(number=20, repeat=3, timeout=4, min_repeat_ms=150),\n    ),\n}\n\n####################################################################\n#\n# .. note:: How to set tuning options\n#\n#   In general, the default value provided here works well.\n#\n#   If you have large time budget, you can set :code:`n_trial`, :code:`early_stopping` larger,\n#   which makes the tuning runs longer.\n#\n#   If you have multiple devices, you can use all of them for measurement to\n#   accelerate the tuning process. (see the 'Scale up measurement` section below).\n#\n\n###################################################################\n# Begin Tuning\n# ------------\n# Now we can extract tuning tasks from the network and begin tuning.\n# Here, we provide a simple utility function to tune a list of tasks.\n# This function is just an initial implementation which tunes them in sequential order.\n# We will introduce a more sophisticated tuning scheduler in the future.\n\n# You can skip the implementation of this function for this tutorial.\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=100)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n\n\ndef tune_and_evaluate(tuning_opt):\n    # extract workloads from relay program\n    print(\"Extract tasks...\")\n    mod, params, input_shape, out_shape = get_network(network, batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(relay.op.get(\"nn.conv2d\"),)\n    )\n\n    # run tuning tasks\n    print(\"Tuning...\")\n    tune_tasks(tasks, **tuning_opt)\n\n    # compile kernels with history best records\n    with autotvm.apply_history_best(log_file):\n        print(\"Compile...\")\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, target=target, params=params)\n\n        # load parameters\n        dev = tvm.device(str(target), 0)\n        module = runtime.GraphModule(lib[\"default\"](dev))\n        data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n        module.set_input(\"data\", data_tvm)\n\n        # evaluate\n        print(\"Evaluate inference time cost...\")\n        print(module.benchmark(dev, number=1, repeat=600))\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate(tuning_option)\n\n######################################################################\n# Sample Output\n# -------------\n# The tuning needs to compile many programs and extract feature from them.\n# So a high performance CPU is recommended. One sample output is listed below.\n# It takes about 4 hours to get the following output on a 32T AMD Ryzen Threadripper.\n# The tuning target is NVIDIA 1080 Ti.\n# (You can see some errors during compilation. If the tuning is not stuck, it is okay.)\n#\n# .. code-block:: bash\n#\n#    Extract tasks...\n#    Tuning...\n#    [Task  1/12]  Current/Best:  541.83/3570.66 GFLOPS | Progress: (960/2000) | 1001.31 s Done.\n#    [Task  2/12]  Current/Best:    0.56/ 803.33 GFLOPS | Progress: (704/2000) | 608.08 s Done.\n#    [Task  3/12]  Current/Best:  103.69/1141.25 GFLOPS | Progress: (768/2000) | 702.13 s Done.\n#    [Task  4/12]  Current/Best: 2905.03/3925.15 GFLOPS | Progress: (864/2000) | 745.94 sterminate called without an active exception\n#    [Task  4/12]  Current/Best: 2789.36/3925.15 GFLOPS | Progress: (1056/2000) | 929.40 s Done.\n#    [Task  5/12]  Current/Best:   89.06/1076.24 GFLOPS | Progress: (704/2000) | 601.73 s Done.\n#    [Task  6/12]  Current/Best:   40.39/2129.02 GFLOPS | Progress: (1088/2000) | 1125.76 s Done.\n#    [Task  7/12]  Current/Best: 4090.53/5007.02 GFLOPS | Progress: (800/2000) | 903.90 s Done.\n#    [Task  8/12]  Current/Best:    4.78/1272.28 GFLOPS | Progress: (768/2000) | 749.14 s Done.\n#    [Task  9/12]  Current/Best: 1391.45/2325.08 GFLOPS | Progress: (992/2000) | 1084.87 s Done.\n#    [Task 10/12]  Current/Best: 1995.44/2383.59 GFLOPS | Progress: (864/2000) | 862.60 s Done.\n#    [Task 11/12]  Current/Best: 4093.94/4899.80 GFLOPS | Progress: (224/2000) | 240.92 sterminate called without an active exception\n#    [Task 11/12]  Current/Best: 3487.98/4909.91 GFLOPS | Progress: (480/2000) | 534.96 sterminate called without an active exception\n#    [Task 11/12]  Current/Best: 4636.84/4912.17 GFLOPS | Progress: (1184/2000) | 1381.16 sterminate called without an active exception\n#    [Task 11/12]  Current/Best:   50.12/4912.17 GFLOPS | Progress: (1344/2000) | 1602.81 s Done.\n#    [Task 12/12]  Current/Best: 3581.31/4286.30 GFLOPS | Progress: (736/2000) | 943.52 s Done.\n#    Compile...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 1.07 ms (0.05 ms)\n#\n# As a reference baseline, the time cost of MXNet + TensorRT on resnet-18 is 1.30ms. So we are a little faster.\n\n######################################################################\n#\n# .. note:: **Experiencing Difficulties?**\n#\n#   The auto tuning module is error-prone. If you always see \" 0.00/ 0.00 GFLOPS\",\n#   then there must be something wrong.\n#\n#   First, make sure you set the correct configuration of your device.\n#   Then, you can print debug information by adding these lines in the beginning\n#   of the script. It will print every measurement result, where you can find useful\n#   error messages.\n#\n#   .. code-block:: python\n#\n#      import logging\n#      logging.getLogger('autotvm').setLevel(logging.DEBUG)\n#\n#   Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org\n\n#################################################################\n# .. _tutorials-autotvm-scale-up-rpc-tracker:\n\n#################################################################\n# Scale up measurement by using multiple devices\n# ----------------------------------------------\n# If you have multiple devices, you can use all of them for measurement.\n# TVM uses the RPC Tracker to manage distributed devices.\n# The RPC Tracker is a centralized controller node. We can register all devices to\n# the tracker. For example, if we have 10 GPU cards, we can register all of them\n# to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n#\n# To start an RPC tracker, run this command on the host machine. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n#\n# Then open another new terminal for the RPC server. We need to start one dedicated server\n# for each device. We use a string key to distinguish the types of devices.\n# You can pick a name you like.\n# (Note: For rocm backend, there are some internal errors with the compiler,\n# we need to add `--no-fork` to the argument list.)\n#\n# .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --tracker=127.0.0.1:9190 --key=1080ti\n#\n# After registering devices, we can confirm it by querying rpc_tracker\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.query_rpc_tracker --host=127.0.0.1 --port=9190\n#\n# For example, if we have four 1080ti, two titanx and one gfx900, the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    1080ti       4      4     0\n#    titanx       2      2     0\n#    gfx900       1      1     0\n#    ----------------------------------\n#\n# Finally, we need to change the tuning option to use RPCRunner. Use the code below\n# to replace the corresponding part above.\n\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"xgb\",\n    \"n_trial\": 2000,\n    \"early_stopping\": 600,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(timeout=10),\n        runner=autotvm.RPCRunner(\n            \"1080ti\",  # change the device key to your key\n            \"127.0.0.1\",\n            9190,\n            number=20,\n            repeat=3,\n            timeout=4,\n            min_repeat_ms=150,\n        ),\n    ),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autotvm/tune_relay_mobile_gpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-tuning a Convolutional Network for Mobile GPU\n==================================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Eddie Yan <https://github.com/eqy>`_\n\nAuto-tuning for a specific device is critical for getting the best\nperformance. This is a tutorial about how to tune a whole convolutional\nnetwork.\n\nThe operator implementation for Mobile GPU in TVM is written in template form.\nThe template has many tunable knobs (tile factor, vectorization, unrolling, etc).\nWe will tune all convolution, depthwise convolution and dense operators\nin the neural network. After tuning, we produce a log file which stores\nthe best knob values for all required operators. When the TVM compiler compiles\nthese operators, it will query this log file to get the best knob values.\n\nWe also released pre-tuned parameters for some arm devices. You can go to\n`Mobile GPU Benchmark <https://github.com/apache/tvm/wiki/Benchmark#mobile-gpu>`_\nto see the results.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado cloudpickle\n#\n# To make TVM run faster during tuning, it is recommended to use cython\n# as FFI of tvm. In the root directory of tvm, execute\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, autotvm\nimport tvm.relay.testing\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.contrib.utils import tempdir\nimport tvm.contrib.graph_executor as runtime\n\n#################################################################\n# Define network\n# --------------\n# First we need to define the network in relay frontend API.\n# We can load some pre-defined network from :code:`relay.testing`.\n# We can also load models from MXNet, ONNX and TensorFlow.\n\n\ndef get_network(name, batch_size):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n    output_shape = (batch_size, 1000)\n\n    if \"resnet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"vgg\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.vgg.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"squeezenet_v1.1\":\n        mod, params = relay.testing.squeezenet.get_workload(\n            batch_size=batch_size, version=\"1.1\", dtype=dtype\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={\"data\": input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params, input_shape, output_shape\n\n\n#################################################################\n# .. _tutorials-autotvm-start-rpc-tracker:\n\n#################################################################\n# Start RPC Tracker\n# -----------------\n# TVM uses RPC session to communicate with ARM boards.\n# During tuning, the tuner will send the generated code to the board and\n# measure the speed of code on the board.\n#\n# To scale up the tuning, TVM uses RPC Tracker to manage distributed devices.\n# The RPC Tracker is a centralized controller node. We can register all devices to\n# the tracker. For example, if we have 10 phones, we can register all of them\n# to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n#\n# To start an RPC tracker, run this command on the host machine. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n\n#################################################################\n# Register Devices to RPC Tracker\n# -----------------------------------\n# Now we can register our devices to the tracker. The first step is to\n# build the TVM runtime for the ARM devices.\n#\n# * For Linux:\n#   Follow this section :ref:`build-tvm-runtime-on-device` to build\n#   the TVM runtime on the device. Then register the device to tracker by\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=rk3399\n#\n#   (replace :code:`[HOST_IP]` with the IP address of your host machine)\n#\n# * For Android:\n#   Follow this `readme page <https://github.com/apache/tvm/tree/main/apps/android_rpc>`_ to\n#   install TVM RPC APK on the android device. Make sure you can pass the android RPC test.\n#   Then you have already registered your device. During tuning, you have to go to developer option\n#   and enable \"Keep screen awake during changing\" and charge your phone to make it stable.\n#\n# After registering devices, we can confirm it by querying rpc_tracker\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n#\n# For example, if we have 2 Huawei mate10 pro, 11 Raspberry Pi 3B and 2 rk3399,\n# the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    mate10pro    2      2     0\n#    rk3399       2      2     0\n#    rpi3b        11     11    0\n#    ----------------------------------\n#\n# You can register multiple devices to the tracker to accelerate the measurement in tuning.\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we should apply some configurations. Here I use an RK3399 board\n# as example. In your setting, you should modify the target and device_key accordingly.\n# set :code:`use_android` to True if you use android phone.\n\n#### DEVICE CONFIG ####\n# Replace \"aarch64-linux-gnu\" with the correct target of your board.\n# This target host is used for cross compilation. You can query it by :code:`gcc -v` on your device.\ntarget = tvm.target.Target(\"opencl -device=mali\", host=\"llvm -mtriple=aarch64-linux-gnu\")\n\n# Also replace this with the device key in your tracker\ndevice_key = \"rk3399\"\n\n# Set this to True if you use android phone\nuse_android = False\n\n#### TUNING OPTION ####\nnetwork = \"resnet-18\"\nlog_file = \"%s.%s.log\" % (device_key, network)\ndtype = \"float32\"\n\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"xgb\",\n    \"n_trial\": 1000,\n    \"early_stopping\": 450,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(build_func=\"ndk\" if use_android else \"default\"),\n        runner=autotvm.RPCRunner(\n            device_key,\n            host=\"127.0.0.1\",\n            port=9190,\n            number=10,\n            timeout=5,\n        ),\n    ),\n}\n\n####################################################################\n#\n# .. note:: How to set tuning options\n#\n#   In general, the default values provided here work well.\n#   If you have enough time budget, you can set :code:`n_trial`, :code:`early_stopping` larger,\n#   which makes the tuning run longer.\n#   If your device runs very slow or your conv2d operators have many GFLOPs, considering to\n#   set timeout larger.\n#\n\n###################################################################\n# Begin Tuning\n# ------------\n# Now we can extract tuning tasks from the network and begin tuning.\n# Here, we provide a simple utility function to tune a list of tasks.\n# This function is just an initial implementation which tunes them in sequential order.\n# We will introduce a more sophisticated tuning scheduler in the future.\n\n# You can skip the implementation of this function for this tutorial.\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n\n\ndef tune_and_evaluate(tuning_opt):\n    # extract workloads from relay program\n    print(\"Extract tasks...\")\n    mod, params, input_shape, _ = get_network(network, batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"],\n        target=target,\n        params=params,\n        ops=(relay.op.get(\"nn.conv2d\"),),\n    )\n\n    # run tuning tasks\n    print(\"Tuning...\")\n    tune_tasks(tasks, **tuning_opt)\n\n    # compile kernels with history best records\n    with autotvm.apply_history_best(log_file):\n        print(\"Compile...\")\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, target=target, params=params)\n        # export library\n        tmp = tempdir()\n        if use_android:\n            from tvm.contrib import ndk\n\n            filename = \"net.so\"\n            lib.export_library(tmp.relpath(filename), ndk.create_shared)\n        else:\n            filename = \"net.tar\"\n            lib.export_library(tmp.relpath(filename))\n\n        # upload module to device\n        print(\"Upload...\")\n        remote = autotvm.measure.request_remote(device_key, \"127.0.0.1\", 9190, timeout=10000)\n        remote.upload(tmp.relpath(filename))\n        rlib = remote.load_module(filename)\n\n        # upload parameters to device\n        dev = remote.device(str(target), 0)\n        module = runtime.GraphModule(rlib[\"default\"](dev))\n        data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n        module.set_input(\"data\", data_tvm)\n\n        # evaluate\n        print(\"Evaluate inference time cost...\")\n        print(module.benchmark(dev, number=1, repeat=30))\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate(tuning_option)\n\n######################################################################\n# Sample Output\n# -------------\n# The tuning needs to compile many programs and extract feature from them.\n# So a high performance CPU is recommended.\n# One sample output is listed below. It takes about 3 hours on a 32T AMD Ryzen Threadripper.\n#\n# .. code-block:: bash\n#\n#    Extract tasks...\n#    Tuning...\n#    [Task  1/17]  Current/Best:   25.30/  39.12 GFLOPS | Progress: (992/1000) | 751.22 s Done.\n#    [Task  2/17]  Current/Best:   40.70/  45.50 GFLOPS | Progress: (736/1000) | 545.46 s Done.\n#    [Task  3/17]  Current/Best:   38.83/  42.35 GFLOPS | Progress: (992/1000) | 1549.85 s Done.\n#    [Task  4/17]  Current/Best:   23.31/  31.02 GFLOPS | Progress: (640/1000) | 1059.31 s Done.\n#    [Task  5/17]  Current/Best:    0.06/   2.34 GFLOPS | Progress: (544/1000) | 305.45 s Done.\n#    [Task  6/17]  Current/Best:   10.97/  17.20 GFLOPS | Progress: (992/1000) | 1050.00 s Done.\n#    [Task  7/17]  Current/Best:    8.98/  10.94 GFLOPS | Progress: (928/1000) | 421.36 s Done.\n#    [Task  8/17]  Current/Best:    4.48/  14.86 GFLOPS | Progress: (704/1000) | 582.60 s Done.\n#    [Task  9/17]  Current/Best:   10.30/  25.99 GFLOPS | Progress: (864/1000) | 899.85 s Done.\n#    [Task 10/17]  Current/Best:   11.73/  12.52 GFLOPS | Progress: (608/1000) | 304.85 s Done.\n#    [Task 11/17]  Current/Best:   15.26/  18.68 GFLOPS | Progress: (800/1000) | 747.52 s Done.\n#    [Task 12/17]  Current/Best:   17.48/  26.71 GFLOPS | Progress: (1000/1000) | 1166.40 s Done.\n#    [Task 13/17]  Current/Best:    0.96/  11.43 GFLOPS | Progress: (960/1000) | 611.65 s Done.\n#    [Task 14/17]  Current/Best:   17.88/  20.22 GFLOPS | Progress: (672/1000) | 670.29 s Done.\n#    [Task 15/17]  Current/Best:   11.62/  13.98 GFLOPS | Progress: (736/1000) | 449.25 s Done.\n#    [Task 16/17]  Current/Best:   19.90/  23.83 GFLOPS | Progress: (608/1000) | 708.64 s Done.\n#    [Task 17/17]  Current/Best:   17.98/  22.75 GFLOPS | Progress: (736/1000) | 1122.60 s Done.\n#    Compile...\n#    Upload...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 128.05 ms (7.74 ms)\n#\n\n######################################################################\n#\n# .. note:: **Experiencing Difficulties?**\n#\n#   The auto tuning module is error-prone. If you always see \" 0.00/ 0.00 GFLOPS\",\n#   then there must be something wrong.\n#\n#   First, make sure you set the correct configuration of your device.\n#   Then, you can print debug information by adding these lines in the beginning\n#   of the script. It will print every measurement result, where you can find useful\n#   error messages.\n#\n#   .. code-block:: python\n#\n#      import logging\n#      logging.getLogger('autotvm').setLevel(logging.DEBUG)\n#\n#   Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/tune_with_autotvm/tune_relay_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tune_relay_x86:\n\nAuto-tuning a Convolutional Network for x86 CPU\n===============================================\n**Author**: `Yao Wang <https://github.com/kevinthesun>`_, `Eddie Yan <https://github.com/eqy>`_\n\nThis is a tutorial about how to tune convolution neural network\nfor x86 CPU.\n\nNote that this tutorial will not run on Windows or recent versions of macOS. To\nget it to run, you will need to wrap the body of this tutorial in a :code:`if\n__name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport os\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, autotvm\nfrom tvm.relay import testing\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.autotvm.graph_tuner import DPTuner, PBQPTuner\nimport tvm.contrib.graph_executor as runtime\n\n#################################################################\n# Define network\n# --------------\n# First we need to define the network in relay frontend API.\n# We can either load some pre-defined network from :code:`relay.testing`\n# or building :any:`relay.testing.resnet` with relay.\n# We can also load models from MXNet, ONNX and TensorFlow.\n#\n# In this tutorial, we choose resnet-18 as tuning example.\n\n\ndef get_network(name, batch_size):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n    output_shape = (batch_size, 1000)\n\n    if \"resnet\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif \"vgg\" in name:\n        n_layer = int(name.split(\"-\")[1])\n        mod, params = relay.testing.vgg.get_workload(\n            num_layers=n_layer, batch_size=batch_size, dtype=dtype\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"squeezenet_v1.1\":\n        mod, params = relay.testing.squeezenet.get_workload(\n            batch_size=batch_size, version=\"1.1\", dtype=dtype\n        )\n    elif name == \"inception_v3\":\n        input_shape = (batch_size, 3, 299, 299)\n        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n    elif name == \"mxnet\":\n        # an example for mxnet model\n        from mxnet.gluon.model_zoo.vision import get_model\n\n        block = get_model(\"resnet18_v1\", pretrained=True)\n        mod, params = relay.frontend.from_mxnet(block, shape={input_name: input_shape}, dtype=dtype)\n        net = mod[\"main\"]\n        net = relay.Function(\n            net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs\n        )\n        mod = tvm.IRModule.from_expr(net)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params, input_shape, output_shape\n\n\n# Replace \"llvm\" with the correct target of your CPU.\n# For example, for AWS EC2 c5 instance with Intel Xeon\n# Platinum 8000 series, the target should be \"llvm -mcpu=skylake-avx512\".\n# For AWS EC2 c4 instance with Intel Xeon E5-2666 v3, it should be\n# \"llvm -mcpu=core-avx2\".\ntarget = \"llvm\"\n\nbatch_size = 1\ndtype = \"float32\"\nmodel_name = \"resnet-18\"\nlog_file = \"%s.log\" % model_name\ngraph_opt_sch_file = \"%s_graph_opt.log\" % model_name\n\n# Set the input name of the graph\n# For ONNX models, it is typically \"0\".\ninput_name = \"data\"\n\n# Set number of threads used for tuning based on the number of\n# physical CPU cores on your machine.\nnum_threads = 1\nos.environ[\"TVM_NUM_THREADS\"] = str(num_threads)\n\n\n#################################################################\n# Configure tensor tuning settings and create tasks\n# -------------------------------------------------\n# To get better kernel execution performance on x86 CPU,\n# we need to change data layout of convolution kernel from\n# \"NCHW\" to \"NCHWc\". To deal with this situation, we define\n# conv2d_NCHWc operator in topi. We will tune this operator\n# instead of plain conv2d.\n#\n# We will use local mode for tuning configuration. RPC tracker\n# mode can be setup similarly to the approach in\n# :ref:`tune_relay_arm` tutorial.\n#\n# To perform a precise measurement, we should repeat the measurement several\n# times and use the average of results. In addition, we need to flush the cache\n# for the weight tensors between repeated measurements. This can make the measured\n# latency of one operator closer to its actual latency during end-to-end inference.\n\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"random\",\n    \"early_stopping\": None,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(),\n        runner=autotvm.LocalRunner(\n            number=1, repeat=10, min_repeat_ms=0, enable_cpu_cache_flush=True\n        ),\n    ),\n}\n\n\n# You can skip the implementation of this function for this tutorial.\ndef tune_kernels(\n    tasks, measure_option, tuner=\"gridsearch\", early_stopping=None, log_filename=\"tuning.log\"\n):\n\n    for i, task in enumerate(tasks):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(task, loss_type=\"rank\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(task, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(task)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(task)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        # do tuning\n        n_trial = len(task.config_space)\n        tuner_obj.tune(\n            n_trial=n_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(n_trial, prefix=prefix),\n                autotvm.callback.log_to_file(log_filename),\n            ],\n        )\n\n\n# Use graph tuner to achieve graph level optimal schedules\n# Set use_DP=False if it takes too long to finish.\ndef tune_graph(graph, dshape, records, opt_sch_file, use_DP=True):\n    target_op = [\n        relay.op.get(\"nn.conv2d\"),\n    ]\n    Tuner = DPTuner if use_DP else PBQPTuner\n    executor = Tuner(graph, {input_name: dshape}, records, target_op, target)\n    executor.benchmark_layout_transform(min_exec_num=2000)\n    executor.run()\n    executor.write_opt_sch2record_file(opt_sch_file)\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n\n\ndef evaluate_performance(lib, data_shape):\n    # upload parameters to device\n    dev = tvm.cpu()\n    data_tvm = tvm.nd.array((np.random.uniform(size=data_shape)).astype(dtype))\n    module = runtime.GraphModule(lib[\"default\"](dev))\n    module.set_input(input_name, data_tvm)\n\n    # evaluate\n    print(\"Evaluate inference time cost...\")\n    print(module.benchmark(dev, number=100, repeat=3))\n\n\ndef tune_and_evaluate(tuning_opt):\n    # extract workloads from relay program\n    print(\"Extract tasks...\")\n    mod, params, data_shape, out_shape = get_network(model_name, batch_size)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(relay.op.get(\"nn.conv2d\"),)\n    )\n\n    # run tuning tasks\n    tune_kernels(tasks, **tuning_opt)\n    tune_graph(mod[\"main\"], data_shape, log_file, graph_opt_sch_file)\n\n    # compile kernels in default mode\n    print(\"Evaluation of the network compiled in 'default' mode without auto tune:\")\n    with tvm.transform.PassContext(opt_level=3):\n        print(\"Compile...\")\n        lib = relay.build(mod, target=target, params=params)\n        evaluate_performance(lib, data_shape)\n\n    # compile kernels in kernel tuned only mode\n    print(\"\\nEvaluation of the network been tuned on kernel level:\")\n    with autotvm.apply_history_best(log_file):\n        print(\"Compile...\")\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target, params=params)\n        evaluate_performance(lib, data_shape)\n\n    # compile kernels with graph-level best records\n    print(\"\\nEvaluation of the network been tuned on graph level:\")\n    with autotvm.apply_graph_best(graph_opt_sch_file):\n        print(\"Compile...\")\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, target=target, params=params)\n        evaluate_performance(lib, data_shape)\n\n\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\n# tune_and_evaluate(tuning_option)\n\n######################################################################\n# Sample Output\n# -------------\n# The tuning needs to compile many programs and extract feature from them.\n# So a high performance CPU is recommended.\n# One sample output is listed below.\n#\n# .. code-block:: bash\n#\n#    Extract tasks...\n#    Tuning...\n#    [Task  1/12]  Current/Best:  598.05/2497.63 GFLOPS | Progress: (252/252) | 1357.95 s Done.\n#    [Task  2/12]  Current/Best:  522.63/2279.24 GFLOPS | Progress: (784/784) | 3989.60 s Done.\n#    [Task  3/12]  Current/Best:  447.33/1927.69 GFLOPS | Progress: (784/784) | 3869.14 s Done.\n#    [Task  4/12]  Current/Best:  481.11/1912.34 GFLOPS | Progress: (672/672) | 3274.25 s Done.\n#    [Task  5/12]  Current/Best:  414.09/1598.45 GFLOPS | Progress: (672/672) | 2720.78 s Done.\n#    [Task  6/12]  Current/Best:  508.96/2273.20 GFLOPS | Progress: (768/768) | 3718.75 s Done.\n#    [Task  7/12]  Current/Best:  469.14/1955.79 GFLOPS | Progress: (576/576) | 2665.67 s Done.\n#    [Task  8/12]  Current/Best:  230.91/1658.97 GFLOPS | Progress: (576/576) | 2435.01 s Done.\n#    [Task  9/12]  Current/Best:  487.75/2295.19 GFLOPS | Progress: (648/648) | 3009.95 s Done.\n#    [Task 10/12]  Current/Best:  182.33/1734.45 GFLOPS | Progress: (360/360) | 1755.06 s Done.\n#    [Task 11/12]  Current/Best:  372.18/1745.15 GFLOPS | Progress: (360/360) | 1684.50 s Done.\n#    [Task 12/12]  Current/Best:  215.34/2271.11 GFLOPS | Progress: (400/400) | 2128.74 s Done.\n#    INFO Start to benchmark layout transformation...\n#    INFO Benchmarking layout transformation successful.\n#    INFO Start to run dynamic programming algorithm...\n#    INFO Start forward pass...\n#    INFO Finished forward pass.\n#    INFO Start backward pass...\n#    INFO Finished backward pass...\n#    INFO Finished DPExecutor run.\n#    INFO Writing optimal schedules to resnet-18_graph_opt.log successfully.\n#\n#    Evaluation of the network compiled in 'default' mode without auto tune:\n#    Compile...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 4.5 ms (0.03 ms)\n#\n#    Evaluation of the network been tuned on kernel level:\n#    Compile...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 3.2 ms (0.03 ms)\n#\n#    Evaluation of the network been tuned on graph level:\n#    Compile...\n#    Config for target=llvm -keys=cpu, workload=('dense_nopack.x86', ('TENSOR', (1, 512), 'float32'), ('TENSOR', (1000, 512), 'float32'), None, 'float32') is missing in ApplyGraphBest context. A fallback configuration is used, which may bring great performance regression.\n#    Config for target=llvm -keys=cpu, workload=('dense_pack.x86', ('TENSOR', (1, 512), 'float32'), ('TENSOR', (1000, 512), 'float32'), None, 'float32') is missing in ApplyGraphBest context. A fallback configuration is used, which may bring great performance regression.\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 3.16 ms (0.03 ms)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-micro-AoT:\n\nmicroTVM Host-Driven AoT\n===========================\n**Authors**:\n`Mehrdad Hessar <https://github.com/mehrdadh>`_,\n`Alan MacDonald <https://github.com/alanmacd>`_\n\nThis tutorial is showcasing microTVM host-driven AoT compilation with\na TFLite model. AoTExecutor reduces the overhead of parsing graph at runtime\ncompared to GraphExecutor. Also, we can have better memory management using ahead\nof time compilation. This tutorial can be executed on a x86 CPU using C runtime (CRT)\nor on Zephyr platform on a microcontroller/board supported by Zephyr.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\nimport pathlib\nimport json\nimport os\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.contrib.download import download_testdata\n\n######################################################################\n# Import a TFLite model\n# ---------------------\n#\n# To begin with, download and import a Keyword Spotting TFLite model.\n# This model is originally from `MLPerf Tiny repository <https://github.com/mlcommons/tiny>`_.\n# To test this model, we use samples from `KWS dataset provided by Google <https://ai.googleblog.com/2017/08/launching-speech-commands-dataset.html>`_.\n#\n# **Note:** By default this tutorial runs on x86 CPU using CRT, if you would like to run on Zephyr platform\n# you need to export `TVM_MICRO_USE_HW` environment variable.\n#\nuse_physical_hw = bool(os.getenv(\"TVM_MICRO_USE_HW\"))\nMODEL_URL = \"https://github.com/tlc-pack/web-data/raw/main/testdata/microTVM/model/keyword_spotting_quant.tflite\"\nMODEL_PATH = download_testdata(MODEL_URL, \"keyword_spotting_quant.tflite\", module=\"model\")\nSAMPLE_URL = \"https://github.com/tlc-pack/web-data/raw/main/testdata/microTVM/data/keyword_spotting_int8_6.pyc.npy\"\nSAMPLE_PATH = download_testdata(SAMPLE_URL, \"keyword_spotting_int8_6.pyc.npy\", module=\"data\")\n\ntflite_model_buf = open(MODEL_PATH, \"rb\").read()\ntry:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\ninput_shape = (1, 49, 10, 1)\nINPUT_NAME = \"input_1\"\nrelay_mod, params = relay.frontend.from_tflite(\n    tflite_model, shape_dict={INPUT_NAME: input_shape}, dtype_dict={INPUT_NAME: \"int8\"}\n)\n\n######################################################################\n# Defining the target\n# -------------------\n#\n# Now we need to define the target, runtime and executor. In this tutorial, we focused on\n# using AOT host driven executor. We use the host micro target which is for running a model\n# on x86 CPU using CRT runtime or running a model with Zephyr platform on qemu_x86 simulator\n# board. In the case of a physical microcontroller, we get the target model for the physical\n# board (E.g. nucleo_l4r5zi) and pass it to `tvm.target.target.micro` to create a full\n# micro target.\n#\n\n# Use the C runtime (crt) and enable static linking by setting system-lib to True\nRUNTIME = Runtime(\"crt\", {\"system-lib\": True})\n\n# Simulate a microcontroller on the host machine. Uses the main() from `src/runtime/crt/host/main.cc`.\n# To use physical hardware, replace \"host\" with something matching your hardware.\nTARGET = tvm.target.target.micro(\"host\")\n\n# Use the AOT executor rather than graph or vm executors. Don't use unpacked API or C calling style.\nEXECUTOR = Executor(\"aot\")\n\nif use_physical_hw:\n    boards_file = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\")) / \"boards.json\"\n    with open(boards_file) as f:\n        boards = json.load(f)\n    BOARD = os.getenv(\"TVM_MICRO_BOARD\", default=\"nucleo_l4r5zi\")\n    TARGET = tvm.target.target.micro(boards[BOARD][\"model\"])\n\n######################################################################\n# Compile the model\n# -----------------\n#\n# Now, we compile the model for the target:\n#\nwith tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n    module = tvm.relay.build(\n        relay_mod, target=TARGET, params=params, runtime=RUNTIME, executor=EXECUTOR\n    )\n\n######################################################################\n# Create a microTVM project\n# -------------------------\n#\n# Now that we have the compiled model as an IRModule, we need to create a firmware project\n# to use the compiled model with microTVM. To do this, we use Project API. We have defined\n# CRT and Zephyr microTVM template projects which are used for x86 CPU and Zephyr boards\n# respectively.\n#\ntemplate_project_path = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"crt\"))\nproject_options = {}  # You can use options to provide platform-specific options through TVM.\n\nif use_physical_hw:\n    template_project_path = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\"))\n    project_options = {\"project_type\": \"host_driven\", \"board\": BOARD}\n\ntemp_dir = tvm.contrib.utils.tempdir()\ngenerated_project_dir = temp_dir / \"project\"\nproject = tvm.micro.generate_project(\n    template_project_path, module, generated_project_dir, project_options\n)\n\n######################################################################\n# Build, flash and execute the model\n# ----------------------------------\n# Next, we build the microTVM project and flash it. Flash step is specific to\n# physical microcontrollers and it is skipped if it is simulating a microcontroller\n# via the host main.cc or if a Zephyr emulated board is selected as the target.\n# Next, we define the labels for the model output and execute the model with a\n# sample with expected value of 6 (label: left).\n#\nproject.build()\nproject.flash()\n\nlabels = [\n    \"_silence_\",\n    \"_unknown_\",\n    \"yes\",\n    \"no\",\n    \"up\",\n    \"down\",\n    \"left\",\n    \"right\",\n    \"on\",\n    \"off\",\n    \"stop\",\n    \"go\",\n]\nwith tvm.micro.Session(project.transport()) as session:\n    aot_executor = tvm.runtime.executor.aot_executor.AotModule(session.create_aot_executor())\n    sample = np.load(SAMPLE_PATH)\n    aot_executor.get_input(INPUT_NAME).copyfrom(sample)\n    aot_executor.run()\n    result = aot_executor.get_output(0).numpy()\n    print(f\"Label is `{labels[np.argmax(result)]}` with index `{np.argmax(result)}`\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_autotune.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\n.. _tutorial-micro-autotune:\n\nAutotuning with microTVM\n=========================\n**Authors**:\n`Andrew Reusch <https://github.com/areusch>`_,\n`Mehrdad Hessar <https://github.com/mehrdadh>`_\n\nThis tutorial explains how to autotune a model using the C runtime.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\nimport json\nimport numpy as np\nimport pathlib\n\nimport tvm\nfrom tvm.relay.backend import Runtime\n\nuse_physical_hw = bool(os.getenv(\"TVM_MICRO_USE_HW\"))\n\n####################\n# Defining the model\n####################\n#\n# To begin with, define a model in Relay to be executed on-device. Then create an IRModule from relay model and\n# fill parameters with random numbers.\n#\n\ndata_shape = (1, 3, 10, 10)\nweight_shape = (6, 3, 5, 5)\n\ndata = tvm.relay.var(\"data\", tvm.relay.TensorType(data_shape, \"float32\"))\nweight = tvm.relay.var(\"weight\", tvm.relay.TensorType(weight_shape, \"float32\"))\n\ny = tvm.relay.nn.conv2d(\n    data,\n    weight,\n    padding=(2, 2),\n    kernel_size=(5, 5),\n    kernel_layout=\"OIHW\",\n    out_dtype=\"float32\",\n)\nf = tvm.relay.Function([data, weight], y)\n\nrelay_mod = tvm.IRModule.from_expr(f)\nrelay_mod = tvm.relay.transform.InferType()(relay_mod)\n\nweight_sample = np.random.rand(\n    weight_shape[0], weight_shape[1], weight_shape[2], weight_shape[3]\n).astype(\"float32\")\nparams = {\"weight\": weight_sample}\n\n#######################\n# Defining the target\n#######################\n# Now we define the TVM target that describes the execution environment. This looks very similar\n# to target definitions from other microTVM tutorials. Alongside this we pick the C Runtime to code\n# generate our model against.\n#\n# When running on physical hardware, choose a target and a board that\n# describe the hardware. There are multiple hardware targets that could be selected from\n# PLATFORM list in this tutorial. You can chose the platform by passing --platform argument when running\n# this tutorial.\n#\n\nRUNTIME = Runtime(\"crt\", {\"system-lib\": True})\nTARGET = tvm.target.target.micro(\"host\")\n\n# Compiling for physical hardware\n# --------------------------------------------------------------------------\n#  When running on physical hardware, choose a TARGET and a BOARD that describe the hardware. The\n#  STM32L4R5ZI Nucleo target and board is chosen in the example below.\nif use_physical_hw:\n    boards_file = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\")) / \"boards.json\"\n    with open(boards_file) as f:\n        boards = json.load(f)\n\n    BOARD = os.getenv(\"TVM_MICRO_BOARD\", default=\"nucleo_l4r5zi\")\n    TARGET = tvm.target.target.micro(boards[BOARD][\"model\"])\n\n\n#########################\n# Extracting tuning tasks\n#########################\n# Not all operators in the Relay program printed above can be tuned. Some are so trivial that only\n# a single implementation is defined; others don't make sense as tuning tasks. Using\n# `extract_from_program`, you can produce a list of tunable tasks.\n#\n# Because task extraction involves running the compiler, we first configure the compiler's\n# transformation passes; we'll apply the same configuration later on during autotuning.\n#\n\npass_context = tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True})\nwith pass_context:\n    tasks = tvm.autotvm.task.extract_from_program(relay_mod[\"main\"], {}, TARGET)\nassert len(tasks) > 0\n\n######################\n# Configuring microTVM\n######################\n# Before autotuning, we need to define a module loader and then pass that to\n# a `tvm.autotvm.LocalBuilder`. Then we create a `tvm.autotvm.LocalRunner` and use\n# both builder and runner to generates multiple measurements for auto tunner.\n#\n# In this tutorial, we have the option to use x86 host as an example or use different targets\n# from Zephyr RTOS. If you choose pass `--platform=host` to this tutorial it will uses x86. You can\n# choose other options by choosing from `PLATFORM` list.\n#\n\nmodule_loader = tvm.micro.AutoTvmModuleLoader(\n    template_project_dir=pathlib.Path(tvm.micro.get_microtvm_template_projects(\"crt\")),\n    project_options={\"verbose\": False},\n)\nbuilder = tvm.autotvm.LocalBuilder(\n    n_parallel=1,\n    build_kwargs={\"build_option\": {\"tir.disable_vectorize\": True}},\n    do_fork=True,\n    build_func=tvm.micro.autotvm_build_func,\n    runtime=RUNTIME,\n)\nrunner = tvm.autotvm.LocalRunner(number=1, repeat=1, timeout=100, module_loader=module_loader)\n\nmeasure_option = tvm.autotvm.measure_option(builder=builder, runner=runner)\n\n# Compiling for physical hardware\nif use_physical_hw:\n    module_loader = tvm.micro.AutoTvmModuleLoader(\n        template_project_dir=pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\")),\n        project_options={\n            \"board\": BOARD,\n            \"west_cmd\": \"west\",\n            \"verbose\": False,\n            \"project_type\": \"host_driven\",\n        },\n    )\n    builder = tvm.autotvm.LocalBuilder(\n        n_parallel=1,\n        build_kwargs={\"build_option\": {\"tir.disable_vectorize\": True}},\n        do_fork=False,\n        build_func=tvm.micro.autotvm_build_func,\n        runtime=RUNTIME,\n    )\n    runner = tvm.autotvm.LocalRunner(number=1, repeat=1, timeout=100, module_loader=module_loader)\n\n    measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner)\n\n##########################\n# Run Autotuning\n##########################\n# Now we can run autotuning separately on each extracted task on microTVM device.\n#\n\nautotune_log_file = pathlib.Path(\"microtvm_autotune.log.txt\")\nif os.path.exists(autotune_log_file):\n    os.remove(autotune_log_file)\n\nnum_trials = 10\nfor task in tasks:\n    tuner = tvm.autotvm.tuner.GATuner(task)\n    tuner.tune(\n        n_trial=num_trials,\n        measure_option=measure_option,\n        callbacks=[\n            tvm.autotvm.callback.log_to_file(str(autotune_log_file)),\n            tvm.autotvm.callback.progress_bar(num_trials, si_prefix=\"M\"),\n        ],\n        si_prefix=\"M\",\n    )\n\n############################\n# Timing the untuned program\n############################\n# For comparison, let's compile and run the graph without imposing any autotuning schedules. TVM\n# will select a randomly-tuned implementation for each operator, which should not perform as well as\n# the tuned operator.\n#\n\nwith pass_context:\n    lowered = tvm.relay.build(relay_mod, target=TARGET, runtime=RUNTIME, params=params)\n\ntemp_dir = tvm.contrib.utils.tempdir()\nproject = tvm.micro.generate_project(\n    str(tvm.micro.get_microtvm_template_projects(\"crt\")),\n    lowered,\n    temp_dir / \"project\",\n    {\"verbose\": False},\n)\n\n# Compiling for physical hardware\nif use_physical_hw:\n    temp_dir = tvm.contrib.utils.tempdir()\n    project = tvm.micro.generate_project(\n        str(tvm.micro.get_microtvm_template_projects(\"zephyr\")),\n        lowered,\n        temp_dir / \"project\",\n        {\n            \"board\": BOARD,\n            \"west_cmd\": \"west\",\n            \"verbose\": False,\n            \"project_type\": \"host_driven\",\n        },\n    )\n\nproject.build()\nproject.flash()\nwith tvm.micro.Session(project.transport()) as session:\n    debug_module = tvm.micro.create_local_debug_executor(\n        lowered.get_graph_json(), session.get_system_lib(), session.device\n    )\n    debug_module.set_input(**lowered.get_params())\n    print(\"########## Build without Autotuning ##########\")\n    debug_module.run()\n    del debug_module\n\n##########################\n# Timing the tuned program\n##########################\n# Once autotuning completes, you can time execution of the entire program using the Debug Runtime:\n\nwith tvm.autotvm.apply_history_best(str(autotune_log_file)):\n    with pass_context:\n        lowered_tuned = tvm.relay.build(relay_mod, target=TARGET, runtime=RUNTIME, params=params)\n\ntemp_dir = tvm.contrib.utils.tempdir()\nproject = tvm.micro.generate_project(\n    str(tvm.micro.get_microtvm_template_projects(\"crt\")),\n    lowered_tuned,\n    temp_dir / \"project\",\n    {\"verbose\": False},\n)\n\n# Compiling for physical hardware\nif use_physical_hw:\n    temp_dir = tvm.contrib.utils.tempdir()\n    project = tvm.micro.generate_project(\n        str(tvm.micro.get_microtvm_template_projects(\"zephyr\")),\n        lowered_tuned,\n        temp_dir / \"project\",\n        {\n            \"board\": BOARD,\n            \"west_cmd\": \"west\",\n            \"verbose\": False,\n            \"project_type\": \"host_driven\",\n        },\n    )\n\nproject.build()\nproject.flash()\nwith tvm.micro.Session(project.transport()) as session:\n    debug_module = tvm.micro.create_local_debug_executor(\n        lowered_tuned.get_graph_json(), session.get_system_lib(), session.device\n    )\n    debug_module.set_input(**lowered_tuned.get_params())\n    print(\"########## Build with Autotuning ##########\")\n    debug_module.run()\n    del debug_module\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_ethosu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nRunning TVM on bare metal Arm(R) Cortex(R)-M55 CPU and Ethos(TM)-U55 NPU with CMSIS-NN\n======================================================================================\n**Author**:\n`Grant Watson <https://github.com/grant-arm>`_\n\nThis section contains an example of how to use TVM to run a model\non an Arm(R) Cortex(R)-M55 CPU and Ethos(TM)-U55 NPU with CMSIS-NN, using bare metal.\nThe Cortex(R)-M55 is a small, low-power CPU designed for use in embedded\ndevices. CMSIS-NN is a collection of kernels optimized for Arm(R) Cortex(R)-M CPUs.\nThe Ethos(TM)-U55 is a microNPU, specifically designed to accelerate\nML inference in resource-constrained embedded devices.\n\nIn order to run the demo application without having access to a Cortex(R)-M55\nand Ethos(TM)-U55 development board, we will be running our sample application\non a Fixed Virtual Platform (FVP). The FVP based on Arm(R) Corstone(TM)-300\nsoftware, models a hardware system containing a Cortex(R)-M55 and Ethos(TM)-U55.\nIt provides a programmer's view that is suitable for software development.\n\nIn this tutorial, we will be compiling a MobileNet v1 model and instructing\nTVM to offload operators to the Ethos(TM)-U55 where possible.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# Obtaining TVM\n# -------------\n#\n# To obtain TVM for you platform, please visit https://tlcpack.ai/ and follow the\n# instructions. Once TVM has been installed correctly, you should have access to\n# ``tvmc`` from the command line.\n#\n# Typing ``tvmc`` on the command line should display the following:\n#\n# .. code-block:: text\n#\n#     usage: tvmc [-h] [-v] [--version] {tune,compile,run} ...\n#\n#     TVM compiler driver\n#\n#     optional arguments:\n#       -h, --help          show this help message and exit\n#       -v, --verbose       increase verbosity\n#       --version           print the version and exit\n#\n#     commands:\n#       {tune,compile,run}\n#         tune              auto-tune a model\n#         compile           compile a model.\n#         run               run a compiled module\n#\n#     TVMC - TVM driver command-line interface\n#\n\n################################################################################\n# Installing additional python dependencies\n# -----------------------------------------\n#\n# In order to run the demo, you will need some additional python packages.\n# These can be installed by using the requirements.txt file below:\n#\n# .. code-block:: text\n#    :caption: requirements.txt\n#    :name: requirements.txt\n#\n#     attrs==21.2.0\n#     cloudpickle==2.0.0\n#     decorator==5.1.0\n#     ethos-u-vela==3.2.0\n#     flatbuffers==1.12\n#     lxml==4.6.3\n#     nose==1.3.7\n#     numpy==1.19.5\n#     Pillow==8.3.2\n#     psutil==5.8.0\n#     scipy==1.5.4\n#     synr==0.4\n#     tflite==2.4.0\n#     tornado==6.1\n#\n# These packages can be installed by running the following from the command line:\n#\n# .. code-block:: bash\n#\n#   pip install -r requirements.txt\n#\n\n################################################################################\n# Obtaining the Model\n# -------------------\n#\n# For this tutorial, we will be working with MobileNet v1.\n# MobileNet v1 is a convolutional neural network designed to classify images,\n# that has been optimized for edge devices. The model we will be using has been\n# pre-trained to classify images into one of 1001 different categories.\n# The network has an input image size of 224x224 so any input images will need\n# to be resized to those dimensions before being used.\n#\n# For this tutorial we will be using the model in Tflite format.\n#\n# .. code-block:: bash\n#\n#   mkdir -p ./build\n#   cd build\n#   wget https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\n#   gunzip mobilenet_v1_1.0_224_quant.tgz\n#   tar xvf mobilenet_v1_1.0_224_quant.tar\n#\n\n######################################################################################\n# Compiling the model for Arm(R) Cortex(R)-M55 CPU and Ethos(TM)-U55 NPU with CMSIS-NN\n# ------------------------------------------------------------------------------------\n#\n# Once we've downloaded the MobileNet v1 model, the next step is to compile it.\n# To accomplish that, we are going to use ``tvmc compile``. The output we get from\n# the compilation process is a TAR package of the model compiled to the Model\n# Library Format (MLF) for our target platform. We will be able to run that model\n# on our target device using the TVM runtime.\n#\n# .. code-block:: bash\n#\n#   tvmc compile --target=ethos-u,cmsis-nn,c \\\n#                --target-ethos-u-accelerator_config=ethos-u55-256 \\\n#                --target-cmsis-nn-mcpu=cortex-m55 \\\n#                --target-c-mcpu=cortex-m55 \\\n#                --runtime=crt \\\n#                --executor=aot \\\n#                --executor-aot-interface-api=c \\\n#                --executor-aot-unpacked-api=1 \\\n#                --pass-config tir.usmp.enable=1 \\\n#                --pass-config tir.usmp.algorithm=hill_climb \\\n#                --pass-config tir.disable_storage_rewrite=1 \\\n#                --pass-config tir.disable_vectorize=1 \\\n#                ./mobilenet_v1_1.0_224_quant.tflite \\\n#                --output-format=mlf\n#\n\n################################################################################\n# .. note:: Explanation of tvmc compile arguments:\n#\n#   * ``--target=ethos-u,cmsis-nn,c`` : offload operators to the microNPU where possible, falling back to CMSIS-NN and finally generated C code where an operator is not supported on the microNPU..\n#\n#   * ``--target-ethos-u-accelerator_config=ethos-u55-256`` : specifies the microNPU configuration\n#\n#   * ``--target-c-mcpu=cortex-m55`` : Cross-compile for the Cortex(R)-M55.\n#\n#   * ``--runtime=crt`` : Generate glue code to allow operators to work with C runtime.\n#\n#   * ``--executor=aot`` : Use Ahead Of Time compiltaion instead of the Graph Executor.\n#\n#   * ``--executor-aot-interface-api=c`` : Generate a C-style interface with structures designed for integrating into C apps at the boundary.\n#\n#   * ``--executor-aot-unpacked-api=1`` : Use the unpacked API internally.\n#\n#   * ``--pass-config tir.usmp.enable=1`` : Enable Unified Static Memory Planning\n#\n#   * ``--pass-config tir.usmp.algorithm=hill_climb`` : Use the hill-climb algorithm for USMP\n#\n#   * ``--pass-config tir.disable_storage_rewrite=1`` : Disable storage rewrite\n#\n#   * ``--pass-config tir.disable_vectorize=1`` : Disable vectorize since there are no standard vectorized types in C.\n#\n#   * ``./mobilenet_v1_1.0_224_quant.tflite`` : The TFLite model that is being compiled.\n#\n#   * ``--output-format=mlf`` : Output should be generated in the Model Library Format.\n#\n\n################################################################################\n# .. note:: If you don't want to make use of the microNPU and want to offload\n#    operators to CMSIS-NN only:\n#\n#   * Use ``--target=cmsis-nn,c`` in place of ``--target=ethos-u,cmsis-nn,c``\n#\n#   * Remove the microNPU config parameter ``--target-ethos-u-accelerator_config=ethos-u55-256``\n#\n\n################################################################################\n# Extracting the generated code into the current directory\n# --------------------------------------------------------\n#\n# .. code-block:: bash\n#\n#   tar xvf module.tar\n#\n\n################################################################################\n# Getting ImageNet labels\n# -----------------------\n#\n# When running MobileNet v1 on an image, the result is an index in the range 0 to\n# 1000. In order to make our application a little more user friendly, instead of\n# just displaying the category index, we will display the associated label. We\n# will download these image labels into a text file now and use a python script\n# to include them in our C application later.\n#\n# .. code-block:: bash\n#\n#   curl -sS  https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/lite/java/demo/app/src/main/assets/labels_mobilenet_quant_v1_224.txt \\\n#   -o ./labels_mobilenet_quant_v1_224.txt\n#\n\n################################################################################\n# Getting the input image\n# -----------------------\n#\n# As input for this tutorial, we will use the image of a cat, but you can\n# substitute an image of your choosing.\n#\n# .. image:: https://s3.amazonaws.com/model-server/inputs/kitten.jpg\n#    :height: 224px\n#    :width: 224px\n#    :align: center\n#\n# We download the image into the build directory and we will use a python script\n# in the next step to convert the image into an array of bytes in a C header file.\n#\n# .. code-block:: bash\n#\n#   curl -sS https://s3.amazonaws.com/model-server/inputs/kitten.jpg -o ./kitten.jpg\n#\n\n################################################################################\n# Pre-processing the image\n# ------------------------\n#\n# The following script will create 2 C header files in the src directory:\n#\n# * ``inputs.h`` - The image supplied as an argument to the script will be converted\n#   to an array of integers for input to our MobileNet v1 model.\n# * ``outputs.h`` - An integer array of zeroes will reserve 1001 integer values\n#   for the output of inference.\n#\n# .. code-block:: python\n#    :caption: convert_image.py\n#    :name: convert_image.py\n#\n#     #!python ./convert_image.py\n#     import os\n#     import pathlib\n#     import re\n#     import sys\n#     from PIL import Image\n#     import numpy as np\n#\n#\n#     def create_header_file(name, section, tensor_name, tensor_data, output_path):\n#         \"\"\"\n#         This function generates a header file containing the data from the numpy array provided.\n#         \"\"\"\n#         file_path = pathlib.Path(f\"{output_path}/\" + name).resolve()\n#         # Create header file with npy_data as a C array\n#         raw_path = file_path.with_suffix(\".h\").resolve()\n#         with open(raw_path, \"w\") as header_file:\n#             header_file.write(\n#                 \"#include <tvmgen_default.h>\\n\"\n#                 + f\"const size_t {tensor_name}_len = {tensor_data.size};\\n\"\n#                 + f'uint8_t {tensor_name}[] __attribute__((section(\"{section}\"), aligned(16))) = \"'\n#             )\n#             data_hexstr = tensor_data.tobytes().hex()\n#             for i in range(0, len(data_hexstr), 2):\n#                 header_file.write(f\"\\\\x{data_hexstr[i:i+2]}\")\n#             header_file.write('\";\\n\\n')\n#\n#\n#     def create_headers(image_name):\n#         \"\"\"\n#         This function generates C header files for the input and output arrays required to run inferences\n#         \"\"\"\n#         img_path = os.path.join(\"./\", f\"{image_name}\")\n#\n#         # Resize image to 224x224\n#         resized_image = Image.open(img_path).resize((224, 224))\n#         img_data = np.asarray(resized_image).astype(\"float32\")\n#\n#         # Convert input to NCHW\n#         img_data = np.transpose(img_data, (2, 0, 1))\n#\n#         # Create input header file\n#         input_data = img_data.astype(np.uint8)\n#         create_header_file(\"inputs\", \"ethosu_scratch\", \"input\", input_data, \"./include\")\n#         # Create output header file\n#         output_data = np.zeros([1001], np.uint8)\n#         create_header_file(\n#             \"outputs\",\n#             \"output_data_sec\",\n#             \"output\",\n#             output_data,\n#             \"./include\",\n#         )\n#\n#\n#     if __name__ == \"__main__\":\n#         create_headers(sys.argv[1])\n#\n# Run the script from the command line:\n#\n# .. code-block:: bash\n#\n#   python convert_image.py ./kitten.jpg\n\n################################################################################\n# Pre-processing the labels\n# -------------------------\n#\n# The following script will create a ``labels.h`` header file in the src directory.\n# The labels.txt file that we downloaded previously will be turned\n# into an array of strings. This array will be used to display the label that\n# our image has been classified as.\n#\n# .. code-block:: python\n#    :caption: convert_labels.py\n#    :name: convert_labels.py\n#\n#     #!python ./convert_labels.py\n#     import os\n#     import pathlib\n#     import sys\n#\n#\n#     def create_labels_header(labels_file, section, output_path):\n#         \"\"\"\n#         This function generates a header file containing the ImageNet labels as an array of strings\n#         \"\"\"\n#         labels_path = pathlib.Path(labels_file).resolve()\n#         file_path = pathlib.Path(f\"{output_path}/labels.h\").resolve()\n#\n#         with open(labels_path) as f:\n#             labels = f.readlines()\n#\n#         with open(file_path, \"w\") as header_file:\n#             header_file.write(f'char* labels[] __attribute__((section(\"{section}\"), aligned(16))) = {{')\n#\n#             for _, label in enumerate(labels):\n#                 header_file.write(f'\"{label.rstrip()}\",')\n#\n#             header_file.write(\"};\\n\")\n#\n#\n#     if __name__ == \"__main__\":\n#         create_labels_header(sys.argv[1], \"ethosu_scratch\", \"./include\")\n#\n# Run the script from the command line:\n#\n# .. code-block:: bash\n#\n#   python convert_labels.py\n\n################################################################################\n# Writing the demo application\n# ----------------------------\n#\n# The following C application will run a single inference of the MobileNet v1\n# model on the image that we downloaded and converted to an array of integers\n# previously. Since the model was compiled with a target of \"ethos-u ...\",\n# operators supported by the Ethos(TM)-U55 NPU will be offloaded for acceleration.\n# Once the application is built and run, our test image should be correctly\n# classied as a \"tabby\" and the result should be displayed on the console.\n# This file should be placed in ``./src``\n#\n# .. code-block:: c\n#    :caption: demo.c\n#    :name: demo.c\n#\n#     #include <stdio.h>\n#     #include <tvm_runtime.h>\n#\n#     #include \"ethosu_mod.h\"\n#     #include \"uart.h\"\n#\n#     // Header files generated by convert_image.py and convert_labels.py\n#     #include \"inputs.h\"\n#     #include \"labels.h\"\n#     #include \"outputs.h\"\n#\n#     int abs(int v) { return v * ((v > 0) - (v < 0)); }\n#\n#     int main(int argc, char** argv) {\n#       uart_init();\n#       printf(\"Starting Demo\\n\");\n#       EthosuInit();\n#\n#       printf(\"Allocating memory\\n\");\n#       StackMemoryManager_Init(&app_workspace, g_aot_memory, WORKSPACE_SIZE);\n#\n#       printf(\"Running inference\\n\");\n#       struct tvmgen_default_outputs outputs = {\n#           .output = output,\n#       };\n#       struct tvmgen_default_inputs inputs = {\n#           .input = input,\n#       };\n#       struct ethosu_driver* driver = ethosu_reserve_driver();\n#       struct tvmgen_default_devices devices = {\n#           .ethos_u = driver,\n#       };\n#       tvmgen_default_run(&inputs, &outputs, &devices);\n#       ethosu_release_driver(driver);\n#\n#       // Calculate index of max value\n#       uint8_t max_value = 0;\n#       int32_t max_index = -1;\n#       for (unsigned int i = 0; i < output_len; ++i) {\n#         if (output[i] > max_value) {\n#           max_value = output[i];\n#           max_index = i;\n#         }\n#       }\n#       printf(\"The image has been classified as '%s'\\n\", labels[max_index]);\n#\n#       // The FVP will shut down when it receives \"EXITTHESIM\" on the UART\n#       printf(\"EXITTHESIM\\n\");\n#       while (1 == 1)\n#         ;\n#       return 0;\n#     }\n#\n#\n# In addition, you will need these header files from github in your ``./include`` directory:\n#\n# `include files <https://github.com/apache/tvm/tree/main/apps/microtvm/ethosu/include>`_\n\n################################################################################\n# .. note::\n#\n#   If you'd like to use FreeRTOS for task scheduling and queues, a sample application can be found here\n#   `demo_freertos.c <https://github.com/apache/tvm/blob/main/apps/microtvm/ethosu/src/demo_freertos.c>`\n\n################################################################################\n# Creating the linker script\n# --------------------------\n#\n# We need to create a linker script that will be used when we build our application\n# in the following section. The linker script tells the linker where everything\n# should be placed in memory. The corstone300.ld linker script below should be\n# placed in your working directory.\n#\n# An example linker script for the FVP can be found here\n# `corstone300.ld <https://github.com/apache/tvm/blob/main/apps/microtvm/ethosu/corstone300.ld>`_\n\n################################################################################\n# .. note::\n#\n#   The code generated by TVM will place the model weights and the Arm(R)\n#   Ethos(TM)-U55 command stream in a section named ``ethosu_scratch``.\n#   For a model the size of MobileNet v1, the weights and command stream will not\n#   fit into the limited SRAM available. For this reason it's important that the\n#   linker script places the ``ethosu_scratch`` section into DRAM (DDR).\n\n################################################################################\n# .. note::\n#\n#   Before building and running the application, you will need to update your\n#   PATH environment variable to include the path to cmake 3.19.5 and the FVP.\n#   For example if you've installed these in ``/opt/arm`` , then you would do\n#   the following:\n#\n#   ``export PATH=/opt/arm/FVP_Corstone_SSE-300_Ethos-U55/models/Linux64_GCC-6.4:/opt/arm/cmake/bin:$PATH``\n#\n\n################################################################################\n# Building the demo application using make\n# ----------------------------------------\n#\n# We can now build the demo application using make. The Makefile should be placed\n# in your working directory before running ``make`` on the command line:\n#\n# An example Makefile can be found here:\n# `Makefile <https://github.com/apache/tvm/blob/main/apps/microtvm/ethosu/Makefile>`_\n\n################################################################################\n# .. note::\n#\n#    If you're using FreeRTOS, the Makefile builds it from the specified FREERTOS_PATH:\n#     ``make FREERTOS_PATH=<FreeRTOS directory>``\n#\n\n################################################################################\n# Running the demo application\n# ----------------------------\n#\n# Finally, we can run our demo appliction on the Fixed Virtual Platform (FVP),\n# by using the following command:\n#\n# .. code-block:: bash\n#\n#     FVP_Corstone_SSE-300_Ethos-U55 -C cpu0.CFGDTCMSZ=15 \\\n#     -C cpu0.CFGITCMSZ=15 -C mps3_board.uart0.out_file=\\\"-\\\" -C mps3_board.uart0.shutdown_tag=\\\"EXITTHESIM\\\" \\\n#     -C mps3_board.visualisation.disable-visualisation=1 -C mps3_board.telnetterminal0.start_telnet=0 \\\n#     -C mps3_board.telnetterminal1.start_telnet=0 -C mps3_board.telnetterminal2.start_telnet=0 -C mps3_board.telnetterminal5.start_telnet=0 \\\n#     -C ethosu.extra_args=\"--fast\" \\\n#     -C ethosu.num_macs=256 ./build/demo\n#\n# You should see the following output displayed in your console window:\n#\n# .. code-block:: text\n#\n#     telnetterminal0: Listening for serial connection on port 5000\n#     telnetterminal1: Listening for serial connection on port 5001\n#     telnetterminal2: Listening for serial connection on port 5002\n#     telnetterminal5: Listening for serial connection on port 5003\n#\n#         Ethos-U rev dedfa618 --- Jan 12 2021 23:03:55\n#         (C) COPYRIGHT 2019-2021 Arm Limited\n#         ALL RIGHTS RESERVED\n#\n#     Starting Demo\n#     ethosu_init. base_address=0x48102000, fast_memory=0x0, fast_memory_size=0, secure=1, privileged=1\n#     ethosu_register_driver: New NPU driver at address 0x20000de8 is registered.\n#     CMD=0x00000000\n#     Soft reset NPU\n#     Allocating memory\n#     Running inference\n#     ethosu_find_and_reserve_driver - Driver 0x20000de8 reserved.\n#     ethosu_invoke\n#     CMD=0x00000004\n#     QCONFIG=0x00000002\n#     REGIONCFG0=0x00000003\n#     REGIONCFG1=0x00000003\n#     REGIONCFG2=0x00000013\n#     REGIONCFG3=0x00000053\n#     REGIONCFG4=0x00000153\n#     REGIONCFG5=0x00000553\n#     REGIONCFG6=0x00001553\n#     REGIONCFG7=0x00005553\n#     AXI_LIMIT0=0x0f1f0000\n#     AXI_LIMIT1=0x0f1f0000\n#     AXI_LIMIT2=0x0f1f0000\n#     AXI_LIMIT3=0x0f1f0000\n#     ethosu_invoke OPTIMIZER_CONFIG\n#     handle_optimizer_config:\n#     Optimizer release nbr: 0 patch: 1\n#     Optimizer config cmd_stream_version: 0 macs_per_cc: 8 shram_size: 48 custom_dma: 0\n#     Optimizer config Ethos-U version: 1.0.6\n#     Ethos-U config cmd_stream_version: 0 macs_per_cc: 8 shram_size: 48 custom_dma: 0\n#     Ethos-U version: 1.0.6\n#     ethosu_invoke NOP\n#     ethosu_invoke NOP\n#     ethosu_invoke NOP\n#     ethosu_invoke COMMAND_STREAM\n#     handle_command_stream: cmd_stream=0x61025be0, cms_length 1181\n#     QBASE=0x0000000061025be0, QSIZE=4724, base_pointer_offset=0x00000000\n#     BASEP0=0x0000000061026e60\n#     BASEP1=0x0000000060002f10\n#     BASEP2=0x0000000060002f10\n#     BASEP3=0x0000000061000fb0\n#     BASEP4=0x0000000060000fb0\n#     CMD=0x000Interrupt. status=0xffff0022, qread=4724\n#     CMD=0x00000006\n#     00006\n#     CMD=0x0000000c\n#     ethosu_release_driver - Driver 0x20000de8 released\n#     The image has been classified as 'tabby'\n#     EXITTHESIM\n#     Info: /OSCI/SystemC: Simulation stopped by user.\n#\n# You should see near the end of the output that the image has been correctly\n# classified as 'tabby'.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_pytorch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-micro-Pytorch:\n\nmicroTVM PyTorch Tutorial\n===========================\n**Authors**:\n`Mehrdad Hessar <https://github.com/mehrdadh>`_\n\nThis tutorial is showcasing microTVM host-driven AoT compilation with\na PyTorch model. This tutorial can be executed on a x86 CPU using C runtime (CRT).\n\n**Note:** This tutorial only runs on x86 CPU using CRT and does not run on Zephyr\nsince the model would not fit on our current supported Zephyr boards.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport pathlib\n\nimport torch\nimport torchvision\nfrom torchvision import transforms\nimport numpy as np\nfrom PIL import Image\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.backend import Executor\n\n##################################\n# Load a pre-trained PyTorch model\n# --------------------------------\n#\n# To begin with, load pre-trained MobileNetV2 from torchvision. Then,\n# download a cat image and preprocess it to use as the model input.\n#\n\nmodel = torchvision.models.quantization.mobilenet_v2(weights=\"DEFAULT\", quantize=True)\nmodel = model.eval()\n\ninput_shape = [1, 3, 224, 224]\ninput_data = torch.randn(input_shape)\nscripted_model = torch.jit.trace(model, input_data).eval()\n\nimg_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\nimg_path = download_testdata(img_url, \"cat.png\", module=\"data\")\nimg = Image.open(img_path).resize((224, 224))\n\n# Preprocess the image and convert to tensor\nmy_preprocess = transforms.Compose(\n    [\n        transforms.Resize(256),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n    ]\n)\nimg = my_preprocess(img)\nimg = np.expand_dims(img, 0)\n\ninput_name = \"input0\"\nshape_list = [(input_name, input_shape)]\nrelay_mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n\n#####################################\n# Define Target, Runtime and Executor\n# -----------------------------------\n#\n# In this tutorial we use AOT host-driven executor. To compile the model\n# for an emulated embedded environment on an x86 machine we use C runtime (CRT)\n# and we use `host` micro target. Using this setup, TVM compiles the model\n# for C runtime which can run on a x86 CPU machine with the same flow that\n# would run on a physical microcontroller.\n#\n\n\n# Simulate a microcontroller on the host machine. Uses the main() from `src/runtime/crt/host/main.cc`\n# To use physical hardware, replace \"host\" with another physical micro target, e.g. `nrf52840`\n# or `mps2_an521`. See more more target examples in micro_train.py and micro_tflite.py tutorials.\ntarget = tvm.target.target.micro(\"host\")\n\n# Use the C runtime (crt) and enable static linking by setting system-lib to True\nruntime = tvm.relay.backend.Runtime(\"crt\", {\"system-lib\": True})\n\n# Use the AOT executor rather than graph or vm executors. Don't use unpacked API or C calling style.\nexecutor = Executor(\"aot\")\n\n####################\n# Compile the model\n# ------------------\n#\n# Now, we compile the model for the target:\n#\n\nwith tvm.transform.PassContext(\n    opt_level=3,\n    config={\"tir.disable_vectorize\": True},\n):\n    module = tvm.relay.build(\n        relay_mod, target=target, runtime=runtime, executor=executor, params=params\n    )\n\n###########################\n# Create a microTVM project\n# -------------------------\n#\n# Now that we have the compiled model as an IRModule, we need to create a firmware project\n# to use the compiled model with microTVM. To do this, we use Project API.\n#\n\ntemplate_project_path = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"crt\"))\nproject_options = {\"verbose\": False, \"memory_size_bytes\": 6 * 1024 * 1024}\n\ntemp_dir = tvm.contrib.utils.tempdir() / \"project\"\nproject = tvm.micro.generate_project(\n    str(template_project_path),\n    module,\n    temp_dir,\n    project_options,\n)\n\n####################################\n# Build, flash and execute the model\n# ----------------------------------\n# Next, we build the microTVM project and flash it. Flash step is specific to\n# physical microcontroller and it is skipped if it is simulating a microcontroller\n# via the host `main.cc`` or if a Zephyr emulated board is selected as the target.\n#\n\nproject.build()\nproject.flash()\n\ninput_data = {input_name: tvm.nd.array(img.astype(\"float32\"))}\nwith tvm.micro.Session(project.transport()) as session:\n    aot_executor = tvm.runtime.executor.aot_executor.AotModule(session.create_aot_executor())\n    aot_executor.set_input(**input_data)\n    aot_executor.run()\n    result = aot_executor.get_output(0).numpy()\n\n#####################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\n#\n\nsynset_url = (\n    \"https://raw.githubusercontent.com/Cadene/\"\n    \"pretrained-models.pytorch/master/data/\"\n    \"imagenet_synsets.txt\"\n)\nsynset_name = \"imagenet_synsets.txt\"\nsynset_path = download_testdata(synset_url, synset_name, module=\"data\")\nwith open(synset_path) as f:\n    synsets = f.readlines()\n\nsynsets = [x.strip() for x in synsets]\nsplits = [line.split(\" \") for line in synsets]\nkey_to_classname = {spl[0]: \" \".join(spl[1:]) for spl in splits}\n\nclass_url = (\n    \"https://raw.githubusercontent.com/Cadene/\"\n    \"pretrained-models.pytorch/master/data/\"\n    \"imagenet_classes.txt\"\n)\nclass_path = download_testdata(class_url, \"imagenet_classes.txt\", module=\"data\")\nwith open(class_path) as f:\n    class_id_to_key = f.readlines()\n\nclass_id_to_key = [x.strip() for x in class_id_to_key]\n\n# Get top-1 result for TVM\ntop1_tvm = np.argmax(result)\ntvm_class_key = class_id_to_key[top1_tvm]\n\n# Convert input to PyTorch variable and get PyTorch result for comparison\nwith torch.no_grad():\n    torch_img = torch.from_numpy(img)\n    output = model(torch_img)\n\n    # Get top-1 result for PyTorch\n    top1_torch = np.argmax(output.numpy())\n    torch_class_key = class_id_to_key[top1_torch]\n\nprint(\"Relay top-1 id: {}, class name: {}\".format(top1_tvm, key_to_classname[tvm_class_key]))\nprint(\"Torch top-1 id: {}, class name: {}\".format(top1_torch, key_to_classname[torch_class_key]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_reference_vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-micro-reference-vm:\n\n===================================\nmicroTVM Reference Virtual Machines\n===================================\n**Author**: `Andrew Reusch <areusch@octoml.ai>`_\n\nThis tutorial explains how to launch microTVM Reference Virtual Machines. You can use these to\ndevelop on real physical hardware without needing to individually install the microTVM\ndependencies. These are also particularly useful when trying to reproduce behavior with\nmicroTVM, such as when filing bug reports.\n\nmicroTVM is the effort to allow TVM to build and execute models on bare-metal microcontrollers.\nmicroTVM aims to be compatible with a wide variety of SoCs and runtime environments (i.e. bare metal,\nRTOS, etc). However, some stable software environment is needed to allow developers to share and\nreproduce bugs and results. The microTVM Reference Virtual Machines are intended to provide that\nenvironment.\n\nHow it works\n============\n\nNo Virtual Machines are stored in the TVM repository--instead, the files stored in\n``apps/microtvm/reference-vm`` describe how to build VMs to the Vagrant_ VM builder tool.\n\nThe Reference VMs are split into two parts:\n\n1. A Vagrant Base Box, which contains all of the stable dependencies for that platform. Build\n   scripts are stored in ``apps/microtvm/reference-vm/<platform>/base-box``. TVM committers run\n   these when a platform's \"stable\" dependencies change, and the generated base boxes are stored in\n   `Vagrant Cloud`_.\n2. A per-workspace VM, which users normally build using the Base Box as a starting point. Build\n   scripts are stored in ``apps/microtvm/reference-vm/<platform>`` (everything except ``base-box``).\n\n.. _Vagrant: https://vagrantup.com\n.. _Vagrant Cloud: https://app.vagrantup.com/tlcpack\n\nSetting up the VM\n=================\n\nInstalling prerequisites\n------------------------\n\nA minimal set of prerequisites are needed:\n\n1. `Vagrant <https://vagrantup.com>`__\n2. A supported Virtual Machine hypervisor (**VirtualBox**, **Parallels**, or **VMWare Fusion/Workstation**).\n   `VirtualBox <https://www.virtualbox.org>`__ is a suggested free hypervisor, but please note\n   that the `VirtualBox Extension Pack`_ is required for proper USB forwarding. If using VirtualBox,\n   also consider installing the `vbguest <https://github.com/dotless-de/vagrant-vbguest>`_ plugin.\n\n.. _VirtualBox Extension Pack: https://www.virtualbox.org/wiki/Downloads#VirtualBox6.1.16OracleVMVirtualBoxExtensionPack\n\n3. If required for your hypervisor, the\n   `Vagrant provider plugin <https://github.com/hashicorp/vagrant/wiki/Available-Vagrant-Plugins#providers>`__ (or see `here <https://www.vagrantup.com/vmware>`__ for VMWare).\n\nFirst boot\n----------\n\nThe first time you use a reference VM, you need to create the box locally and then provision it.\n\n.. code-block:: bash\n\n    # Replace zephyr with the name of a different platform, if you are not using Zephyr.\n    ~/.../tvm $ cd apps/microtvm/reference-vm/zephyr\n    # Replace <provider_name> with the name of the hypervisor you wish to use (i.e. virtualbox, parallels, vmware_desktop).\n    ~/.../tvm/apps/microtvm/reference-vm/zephyr $ vagrant up --provider=<provider_name>\n\n\nThis command will take a couple of minutes to run and will require 4 to 5GB of storage on your\nmachine. It does the following:\n\n1. Downloads the `microTVM base box`_ and clones it to form a new VM specific to this TVM directory.\n2. Mounts your TVM directory (and, if using ``git-subtree``, the original ``.git`` repo) into the\n   VM.\n3. Builds TVM and installs a Python virtualenv with the dependencies corresponding with your TVM\n   build.\n\n.. _microTVM base box: https://app.vagrantup.com/tlcpack/boxes/microtvm\n\nConnect Hardware to the VM\n--------------------------\n\nNext, you need to configure USB passthrough to attach your physical development board to the virtual\nmachine (rather than directly to your laptop's host OS).\n\nIt's suggested you setup a device filter, rather than doing a one-time forward, because often the\ndevice may reboot during the programming process and you may, at that time, need to enable\nforwarding again. It may not be obvious to the end user when this occurs. Instructions to do that:\n\n * `VirtualBox <https://www.virtualbox.org/manual/ch03.html#usb-support>`__\n * `Parallels <https://kb.parallels.com/122993>`__\n * `VMWare Workstation <https://docs.vmware.com/en/VMware-Workstation-Pro/15.0/com.vmware.ws.using.doc/GUID-E003456F-EB94-4B53-9082-293D9617CB5A.html>`__\n\nRebuilding TVM inside the Reference VM\n--------------------------------------\n\nAfter the first boot, you'll need to ensure you keep the build, in ``$TVM_HOME/build-microtvm-zephyr``,\nup-to-date when you modify the C++ runtime or checkout a different revision. You can either\nre-provision the machine (``vagrant provision`` in the same directory you ran ``vagrant up`` before)\nor manually rebuild TVM yourself.\n\nRemember: the TVM ``.so`` built inside the VM is different from the one you may use on your host\nmachine. This is why it's built inside the special directory ``build-microtvm-zephyr``.\n\nLogging in to the VM\n--------------------\n\nThe VM should be available to your host only with the hostname ``microtvm``. You can SSH to the VM\nas follows:\n\n.. code-block:: bash\n\n    $ vagrant ssh\n\nThen ``cd`` to the same path used on your host machine for TVM. For example, on Mac:\n\n.. code-block:: bash\n\n    $ cd /Users/yourusername/path/to/tvm\n\nRunning tests\n=============\n\nOnce the VM has been provisioned, tests can be executed using ``poetry``:\n\n.. code-block:: bash\n\n    $ cd apps/microtvm/reference-vm/zephyr\n    $ poetry run python3 ../../../../tests/micro/zephyr/test_zephyr.py --board=stm32f746g_disco\n\nIf you do not have physical hardware attached, but wish to run the tests using the\nlocal QEMU emulator running within the VM, run the following commands instead:\n\n.. code-block:: bash\n\n    $ cd /Users/yourusername/path/to/tvm\n    $ cd apps/microtvm/reference-vm/zephyr/\n    $ poetry run pytest ../../../../tests/micro/zephyr/test_zephyr.py --board=qemu_x86\n\n\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_tflite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _microTVM-with-TFLite:\n\nmicroTVM with TFLite Models\n===========================\n**Author**: `Tom Gall <https://github.com/tom-gall>`_\n\nThis tutorial is an introduction to working with microTVM and a TFLite\nmodel with Relay.\n\"\"\"\n\n######################################################################\n# .. note::\n#     If you want to run this tutorial on the microTVM Reference VM, download the Jupyter\n#     notebook using the link at the bottom of this page and save it into the TVM directory. Then:\n#\n#     #. Login to the reference VM with a modified ``vagrant ssh`` command:\n#\n#         ``$ vagrant ssh -- -L8888:localhost:8888``\n#\n#     #. Install jupyter:  ``pip install jupyterlab``\n#     #. ``cd`` to the TVM directory.\n#     #. Install tflite: poetry install -E importer-tflite\n#     #. Launch Jupyter Notebook: ``jupyter notebook``\n#     #. Copy the localhost URL displayed, and paste it into your browser.\n#     #. Navigate to saved Jupyter Notebook (``.ipynb`` file).\n#\n#\n# Setup\n# -----\n#\n# Install TFLite\n# ^^^^^^^^^^^^^^\n#\n# To get started, TFLite package needs to be installed as prerequisite. You can do this in two ways:\n#\n# 1. Install tflite with ``pip``\n#\n#     .. code-block:: bash\n#\n#       pip install tflite=2.1.0 --user\n#\n# 2. Generate the TFLite package yourself. The steps are the following:\n#\n#     Get the flatc compiler.\n#     Please refer to https://github.com/google/flatbuffers for details\n#     and make sure it is properly installed.\n#\n#     .. code-block:: bash\n#\n#       flatc --version\n#\n#     Get the TFLite schema.\n#\n#     .. code-block:: bash\n#\n#       wget https://raw.githubusercontent.com/tensorflow/tensorflow/r1.13/tensorflow/lite/schema/schema.fbs\n#\n#     Generate TFLite package.\n#\n#     .. code-block:: bash\n#\n#       flatc --python schema.fbs\n#\n#     Add the current folder (which contains generated tflite module) to PYTHONPATH.\n#\n#     .. code-block:: bash\n#\n#       export PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}$(pwd)\n#\n# To validate that the TFLite package was installed successfully, ``python -c \"import tflite\"``\n#\n# Install Zephyr (physical hardware only)\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# When running this tutorial with a host simulation (the default), you can use the host ``gcc`` to\n# build a firmware image that simulates the device. When compiling to run on physical hardware, you\n# need to install a *toolchain* plus some target-specific dependencies. microTVM allows you to\n# supply any compiler and runtime that can launch the TVM RPC server, but to get started, this\n# tutorial relies on the Zephyr RTOS to provide these pieces.\n#\n# You can install Zephyr by following the\n# `Installation Instructions <https://docs.zephyrproject.org/latest/getting_started/index.html>`_.\n#\n# Aside: Recreating your own Pre-Trained TFLite model\n#  The tutorial downloads a pretrained TFLite model. When working with microcontrollers\n#  you need to be mindful these are highly resource constrained devices as such standard\n#  models like MobileNet may not fit into their modest memory.\n#\n#  For this tutorial, we'll make use of one of the TF Micro example models.\n#\n#  If you wish to replicate the training steps see:\n#  https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/hello_world/train\n#\n#    .. note::\n#\n#      If you accidentally download the example pretrained model from:\n#\n#      ``wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/micro/hello_world_2020_04_13.zip``\n#\n#      this will fail due to an unimplemented opcode (114)\n#\n# Load and prepare the Pre-Trained Model\n# --------------------------------------\n#\n# Load the pretrained TFLite model from a file in your current\n# directory into a buffer\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport os\nimport json\nimport tarfile\nimport pathlib\nimport tempfile\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nimport tvm.contrib.utils\nfrom tvm.contrib.download import download_testdata\n\nuse_physical_hw = bool(os.getenv(\"TVM_MICRO_USE_HW\"))\nmodel_url = \"https://people.linaro.org/~tom.gall/sine_model.tflite\"\nmodel_file = \"sine_model.tflite\"\nmodel_path = download_testdata(model_url, model_file, module=\"data\")\n\ntflite_model_buf = open(model_path, \"rb\").read()\n\n######################################################################\n# Using the buffer, transform into a tflite model python object\ntry:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n######################################################################\n# Print out the version of the model\nversion = tflite_model.Version()\nprint(\"Model Version: \" + str(version))\n\n######################################################################\n# Parse the python model object to convert it into a relay module\n# and weights.\n# It is important to note that the input tensor name must match what\n# is contained in the model.\n#\n# If you are unsure what that might be, this can be discovered by using\n# the ``visualize.py`` script within the Tensorflow project.\n# See `How do I inspect a .tflite file? <https://www.tensorflow.org/lite/guide/faq>`_\n\ninput_tensor = \"dense_4_input\"\ninput_shape = (1,)\ninput_dtype = \"float32\"\n\nmod, params = relay.frontend.from_tflite(\n    tflite_model, shape_dict={input_tensor: input_shape}, dtype_dict={input_tensor: input_dtype}\n)\n\n######################################################################\n# Defining the target\n# -------------------\n#\n# Now we create a build config for relay, turning off two options and then calling relay.build which\n# will result in a C source file for the selected TARGET. When running on a simulated target of the\n# same architecture as the host (where this Python script is executed) choose \"host\" below for the\n# TARGET, the C Runtime as the RUNTIME and a proper board/VM to run it (Zephyr will create the right\n# QEMU VM based on BOARD. In the example below the x86 arch is selected and a x86 VM is picked up accordingly:\n#\nRUNTIME = tvm.relay.backend.Runtime(\"crt\", {\"system-lib\": True})\nTARGET = tvm.target.target.micro(\"host\")\n\n#\n# Compiling for physical hardware\n#  When running on physical hardware, choose a TARGET and a BOARD that describe the hardware. The\n#  STM32F746 Nucleo target and board is chosen in the example below. Another option would be to\n#  choose the STM32F746 Discovery board instead. Since that board has the same MCU as the Nucleo\n#  board but a couple of wirings and configs differ, it's necessary to select the \"stm32f746g_disco\"\n#  board to generated the right firmware image.\n#\n\nif use_physical_hw:\n    boards_file = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\")) / \"boards.json\"\n    with open(boards_file) as f:\n        boards = json.load(f)\n\n    BOARD = os.getenv(\"TVM_MICRO_BOARD\", default=\"nucleo_f746zg\")\n    TARGET = tvm.target.target.micro(boards[BOARD][\"model\"])\n\n#\n#  For some boards, Zephyr runs them emulated by default, using QEMU. For example, below is the\n#  TARGET and BOARD used to build a microTVM firmware for the mps2-an521 board. Since that board\n#  runs emulated by default on Zephyr the suffix \"-qemu\" is added to the board name to inform\n#  microTVM that the QEMU transporter must be used to communicate with the board. If the board name\n#  already has the prefix \"qemu_\", like \"qemu_x86\", then it's not necessary to add that suffix.\n#\n#  TARGET = tvm.target.target.micro(\"mps2_an521\")\n#  BOARD = \"mps2_an521-qemu\"\n\n######################################################################\n# Now, compile the model for the target:\n\nwith tvm.transform.PassContext(\n    opt_level=3, config={\"tir.disable_vectorize\": True}, disabled_pass=[\"AlterOpLayout\"]\n):\n    module = relay.build(mod, target=TARGET, runtime=RUNTIME, params=params)\n\n\n# Inspecting the compilation output\n# ---------------------------------\n#\n# The compilation process has produced some C code implementing the operators in this graph. We\n# can inspect it by printing the CSourceModule contents (for the purposes of this tutorial, let's\n# just print the first 10 lines):\n\nc_source_module = module.get_lib().imported_modules[0]\nassert c_source_module.type_key == \"c\", \"tutorial is broken\"\n\nc_source_code = c_source_module.get_source()\nfirst_few_lines = c_source_code.split(\"\\n\")[:10]\nassert any(\n    l.startswith(\"TVM_DLL int32_t tvmgen_default_\") for l in first_few_lines\n), f\"tutorial is broken: {first_few_lines!r}\"\nprint(\"\\n\".join(first_few_lines))\n\n\n# Compiling the generated code\n# ----------------------------\n#\n# Now we need to incorporate the generated C code into a project that allows us to run inference on the\n# device. The simplest way to do this is to integrate it yourself, using microTVM's standard output format\n# (:doc:`Model Library Format` </dev/model_library_format>`). This is a tarball with a standard layout:\n\n# Get a temporary path where we can store the tarball (since this is running as a tutorial).\n\nfd, model_library_format_tar_path = tempfile.mkstemp()\nos.close(fd)\nos.unlink(model_library_format_tar_path)\ntvm.micro.export_model_library_format(module, model_library_format_tar_path)\n\nwith tarfile.open(model_library_format_tar_path, \"r:*\") as tar_f:\n    print(\"\\n\".join(f\" - {m.name}\" for m in tar_f.getmembers()))\n\n# Cleanup for tutorial:\nos.unlink(model_library_format_tar_path)\n\n\n# TVM also provides a standard way for embedded platforms to automatically generate a standalone\n# project, compile and flash it to a target, and communicate with it using the standard TVM RPC\n# protocol. The Model Library Format serves as the model input to this process. When embedded\n# platforms provide such an integration, they can be used directly by TVM for both host-driven\n# inference and autotuning . This integration is provided by the\n# `microTVM Project API` <https://github.com/apache/tvm-rfcs/blob/main/rfcs/0008-microtvm-project-api.md>_,\n#\n# Embedded platforms need to provide a Template Project containing a microTVM API Server (typically,\n# this lives in a file ``microtvm_api_server.py`` in the root directory). Let's use the example ``host``\n# project in this tutorial, which simulates the device using a POSIX subprocess and pipes:\n\ntemplate_project_path = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"crt\"))\nproject_options = {}  # You can use options to provide platform-specific options through TVM.\n\n# Compiling for physical hardware (or an emulated board, like the mps_an521)\n# --------------------------------------------------------------------------\n#  For physical hardware, you can try out the Zephyr platform by using a different template project\n#  and options:\n#\n\nif use_physical_hw:\n    template_project_path = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\"))\n    project_options = {\"project_type\": \"host_driven\", \"board\": BOARD}\n\n# Create a temporary directory\n\ntemp_dir = tvm.contrib.utils.tempdir()\ngenerated_project_dir = temp_dir / \"generated-project\"\ngenerated_project = tvm.micro.generate_project(\n    template_project_path, module, generated_project_dir, project_options\n)\n\n# Build and flash the project\ngenerated_project.build()\ngenerated_project.flash()\n\n\n######################################################################\n# Next, establish a session with the simulated device and run the\n# computation. The `with session` line would typically flash an attached\n# microcontroller, but in this tutorial, it simply launches a subprocess\n# to stand in for an attached microcontroller.\n\nwith tvm.micro.Session(transport_context_manager=generated_project.transport()) as session:\n    graph_mod = tvm.micro.create_local_graph_executor(\n        module.get_graph_json(), session.get_system_lib(), session.device\n    )\n\n    # Set the model parameters using the lowered parameters produced by `relay.build`.\n    graph_mod.set_input(**module.get_params())\n\n    # The model consumes a single float32 value and returns a predicted sine value.  To pass the\n    # input value we construct a tvm.nd.array object with a single contrived number as input. For\n    # this model values of 0 to 2Pi are acceptable.\n    graph_mod.set_input(input_tensor, tvm.nd.array(np.array([0.5], dtype=\"float32\")))\n    graph_mod.run()\n\n    tvm_output = graph_mod.get_output(0).numpy()\n    print(\"result is: \" + str(tvm_output))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_microtvm/micro_train.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _microtvm-train-arduino:\n\nTraining Vision Models for microTVM on Arduino\n==============================================\n**Author**: `Gavin Uberti <https://github.com/guberti>`_\n\nThis tutorial shows how MobileNetV1 models can be trained\nto fit on embedded devices, and how those models can be\ndeployed to Arduino using TVM.\n\"\"\"\n\n######################################################################\n# .. note::\n#\n#   This tutorial is best viewed as a Jupyter Notebook. You can download and run it locally\n#   using the link at the bottom of this page, or open it online for free using Google Colab.\n#   Click the icon below to open in Google Colab.\n#\n# .. image:: https://raw.githubusercontent.com/tlc-pack/web-data/main/images/utilities/colab_button.png\n#      :align: center\n#      :target: https://colab.research.google.com/github/apache/tvm-site/blob/asf-site/docs/_downloads/a7c7ea4b5017ae70db1f51dd8e6dcd82/micro_train.ipynb\n#      :width: 300px\n#\n# Motivation\n# ----------\n# When building IOT devices, we often want them to **see and understand** the world around them.\n# This can take many forms, but often times a device will want to know if a certain **kind of\n# object** is in its field of vision.\n#\n# For example, a security camera might look for **people**, so it can decide whether to save a video\n# to memory. A traffic light might look for **cars**, so it can judge which lights should change\n# first. Or a forest camera might look for a **kind of animal**, so they can estimate how large\n# the animal population is.\n#\n# To make these devices affordable, we would like them to need only a low-cost processor like the\n# `nRF52840 <https://www.nordicsemi.com/Products/nRF52840>`_ (costing five dollars each on Mouser) or the `RP2040 <https://www.raspberrypi.com/products/rp2040/>`_ (just $1.45 each!).\n#\n# These devices have very little memory (~250 KB RAM), meaning that no conventional edge AI\n# vision model (like MobileNet or EfficientNet) will be able to run. In this tutorial, we will\n# show how these models can be modified to work around this requirement. Then, we will use TVM\n# to compile and deploy it for an Arduino that uses one of these processors.\n#\n# Installing the Prerequisites\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# This tutorial will use TensorFlow to train the model - a widely used machine learning library\n# created by Google. TensorFlow is a very low-level library, however, so we will the Keras\n# interface to talk to TensorFlow. We will also use TensorFlow Lite to perform quantization on\n# our model, as TensorFlow by itself does not support this.\n#\n# Once we have our generated model, we will use TVM to compile and test it. To avoid having to\n# build from source, we'll install ``tlcpack`` - a community build of TVM. Lastly, we'll also\n# install ``imagemagick`` and ``curl`` to preprocess data:\n#\n#     .. code-block:: bash\n#\n#       %%bash\n#       pip install -q tensorflow tflite\n#       pip install -q tlcpack-nightly -f https://tlcpack.ai/wheels\n#       apt-get -qq install imagemagick curl\n#\n#       # Install Arduino CLI and library for Nano 33 BLE\n#       curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh\n#       /content/bin/arduino-cli core update-index\n#       /content/bin/arduino-cli core install arduino:mbed_nano\n#\n# Using the GPU\n# ^^^^^^^^^^^^^\n#\n# This tutorial demonstrates training a neural network, which is requires a lot of computing power\n# and will go much faster if you have a GPU. If you are viewing this tutorial on Google Colab, you\n# can enable a GPU by going to **Runtime->Change runtime type** and selecting \"GPU\" as our hardware\n# accelerator. If you are running locally, you can `follow TensorFlow's guide <https://www.tensorflow.org/guide/gpu>`_ instead.\n#\n# We can test our GPU installation with the following code:\n\nimport tensorflow as tf\n\nif not tf.test.gpu_device_name():\n    print(\"No GPU was detected!\")\n    print(\"Model training will take much longer (~30 minutes instead of ~5)\")\nelse:\n    print(\"GPU detected - you're good to go.\")\n\n######################################################################\n# Choosing Our Work Dir\n# ^^^^^^^^^^^^^^^^^^^^^\n# We need to pick a directory where our image datasets, trained model, and eventual Arduino sketch\n# will all live. If running on Google Colab, we'll save everything in ``/root`` (aka ``~``) but you'll\n# probably want to store it elsewhere if running locally. Note that this variable only affects Python\n# scripts - you'll have to adjust the Bash commands too.\n\nimport os\n\nFOLDER = \"/root\"\n# sphinx_gallery_start_ignore\nimport tempfile\n\nFOLDER = tempfile.mkdtemp()\n# sphinx_gallery_end_ignore\n\n######################################################################\n# Downloading the Data\n# --------------------\n# Convolutional neural networks usually learn by looking at many images, along with labels telling\n# the network what those images are. To get these images, we'll need a publicly available dataset\n# with thousands of images of all sorts of objects and labels of what's in each image. We'll also\n# need a bunch of images that **aren't** of cars, as we're trying to distinguish these two classes.\n#\n# In this tutorial, we'll create a model to detect if an image contains a **car**, but you can use\n# whatever category you like! Just change the source URL below to one containing images of another\n# type of object.\n#\n# To get our car images, we'll be downloading the `Stanford Cars dataset <http://ai.stanford.edu/~jkrause/cars/car_dataset.html>`_,\n# which contains 16,185 full color images of cars. We'll also need images of random things that\n# aren't cars, so we'll use the `COCO 2017 <https://cocodataset.org/#home>`_ validation set (it's\n# smaller, and thus faster to download than the full training set. Training on the full data set\n# would yield better results). Note that there are some cars in the COCO 2017 data set, but it's\n# a small enough fraction not to matter - just keep in mind that this will drive down our percieved\n# accuracy slightly.\n#\n# We could use the TensorFlow dataloader utilities, but we'll instead do it manually to make sure\n# it's easy to change the datasets being used. We'll end up with the following file hierarchy:\n#\n#     .. code-block::\n#\n#         /root\n#         \u251c\u2500\u2500 images\n#         \u2502   \u251c\u2500\u2500 object\n#         \u2502   \u2502   \u251c\u2500\u2500 000001.jpg\n#         \u2502   \u2502   \u2502 ...\n#         \u2502   \u2502   \u2514\u2500\u2500 016185.jpg\n#         \u2502   \u251c\u2500\u2500 object.tgz\n#         \u2502   \u251c\u2500\u2500 random\n#         \u2502   \u2502   \u251c\u2500\u2500 000000000139.jpg\n#         \u2502   \u2502   \u2502 ...\n#         \u2502   \u2502   \u2514\u2500\u2500 000000581781.jpg\n#         \u2502   \u2514\u2500\u2500 random.zip\n#\n# We should also note that Stanford cars has 8k images, while the COCO 2017 validation set is 5k\n# images - it is not a 50/50 split! If we wanted to, we could weight these classes differently\n# during training to correct for this, but training will still work if we ignore it. It should\n# take about **2 minutes** to download the Stanford Cars, while COCO 2017 validation will take\n# **1 minute**.\n\nimport os\nimport shutil\nimport urllib.request\n\n# Download datasets\nos.makedirs(f\"{FOLDER}/downloads\")\nos.makedirs(f\"{FOLDER}/images\")\nurllib.request.urlretrieve(\n    \"https://data.deepai.org/stanfordcars.zip\", f\"{FOLDER}/downloads/target.zip\"\n)\nurllib.request.urlretrieve(\n    \"http://images.cocodataset.org/zips/val2017.zip\", f\"{FOLDER}/downloads/random.zip\"\n)\n\n# Extract them and rename their folders\nshutil.unpack_archive(f\"{FOLDER}/downloads/target.zip\", f\"{FOLDER}/downloads\")\nshutil.unpack_archive(f\"{FOLDER}/downloads/random.zip\", f\"{FOLDER}/downloads\")\nshutil.move(f\"{FOLDER}/downloads/cars_train/cars_train\", f\"{FOLDER}/images/target\")\nshutil.move(f\"{FOLDER}/downloads/val2017\", f\"{FOLDER}/images/random\")\n\n######################################################################\n# Loading the Data\n# ----------------\n# Currently, our data is stored on-disk as JPG files of various sizes. To train with it, we'll have\n# to load the images into memory, resize them to be 64x64, and convert them to raw, uncompressed\n# data. Keras's ``image_dataset_from_directory`` will take care of most of this, though it loads\n# images such that each pixel value is a float from 0 to 255.\n#\n# We'll also need to load labels, though Keras will help with this. From our subdirectory structure,\n# it knows the images in ``/objects`` are one class, and those in ``/random`` another. Setting\n# ``label_mode='categorical'`` tells Keras to convert these into **categorical labels** - a 2x1 vector\n# that's either ``[1, 0]`` for an object of our target class, or ``[0, 1]`` vector for anything else.\n# We'll also set ``shuffle=True`` to randomize the order of our examples.\n#\n# We will also **batch** the data - grouping samples into clumps to make our training go faster.\n# Setting ``batch_size = 32`` is a decent number.\n#\n# Lastly, in machine learning we generally want our inputs to be small numbers. We'll thus use a\n# ``Rescaling`` layer to change our images such that each pixel is a float between ``0.0`` and ``1.0``,\n# instead of ``0`` to ``255``. We need to be careful not to rescale our categorical labels though, so\n# we'll use a ``lambda`` function.\n\nIMAGE_SIZE = (64, 64, 3)\nunscaled_dataset = tf.keras.utils.image_dataset_from_directory(\n    f\"{FOLDER}/images\",\n    batch_size=32,\n    shuffle=True,\n    label_mode=\"categorical\",\n    image_size=IMAGE_SIZE[0:2],\n)\nrescale = tf.keras.layers.Rescaling(scale=1.0 / 255)\nfull_dataset = unscaled_dataset.map(lambda im, lbl: (rescale(im), lbl))\n\n######################################################################\n# What's Inside Our Dataset?\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^\n# Before giving this data set to our neural network, we ought to give it a quick visual inspection.\n# Does the data look properly transformed? Do the labels seem appropriate? And what's our ratio of\n# objects to other stuff? We can display some examples from our datasets using ``matplotlib``:\n\nimport matplotlib.pyplot as plt\n\nnum_target_class = len(os.listdir(f\"{FOLDER}/images/target/\"))\nnum_random_class = len(os.listdir(f\"{FOLDER}/images/random/\"))\nprint(f\"{FOLDER}/images/target contains {num_target_class} images\")\nprint(f\"{FOLDER}/images/random contains {num_random_class} images\")\n\n# Show some samples and their labels\nSAMPLES_TO_SHOW = 10\nplt.figure(figsize=(20, 10))\nfor i, (image, label) in enumerate(unscaled_dataset.unbatch()):\n    if i >= SAMPLES_TO_SHOW:\n        break\n    ax = plt.subplot(1, SAMPLES_TO_SHOW, i + 1)\n    plt.imshow(image.numpy().astype(\"uint8\"))\n    plt.title(list(label.numpy()))\n    plt.axis(\"off\")\n\n######################################################################\n# Validating our Accuracy\n# ^^^^^^^^^^^^^^^^^^^^^^^\n# While developing our model, we'll often want to check how accurate it is (e.g. to see if it\n# improves during training). How do we do this? We could just train it on *all* of the data, and\n# then ask it to classify that same data. However, our model could cheat by just memorizing all of\n# the samples, which would make it *appear* to have very high accuracy, but perform very badly in\n# reality. In practice, this \"memorizing\" is called **overfitting**.\n#\n# To prevent this, we will set aside some of the data (we'll use 20%) as a **validation set**. Our\n# model will never be trained on validation data - we'll only use it to check our model's accuracy.\n\nnum_batches = len(full_dataset)\ntrain_dataset = full_dataset.take(int(num_batches * 0.8))\nvalidation_dataset = full_dataset.skip(len(train_dataset))\n\n######################################################################\n# Loading the Data\n# ----------------\n# In the past decade, `convolutional neural networks <https://en.wikipedia.org/wiki/Convolutional_neural_network>`_ have been widely\n# adopted for image classification tasks. State-of-the-art models like `EfficientNet V2 <https://arxiv.org/abs/2104.00298>`_ are able\n# to perform image classification better than even humans! Unfortunately, these models have tens of\n# millions of parameters, and thus won't fit on cheap security camera computers.\n#\n# Our applications generally don't need perfect accuracy - 90% is good enough. We can thus use the\n# older and smaller MobileNet V1 architecture. But this *still* won't be small enough - by default,\n# MobileNet V1 with 224x224 inputs and alpha 1.0 takes ~50 MB to just **store**. To reduce the size\n# of the model, there are three knobs we can turn. First, we can reduce the size of the input images\n# from 224x224 to 96x96 or 64x64, and Keras makes it easy to do this. We can also reduce the **alpha**\n# of the model, from 1.0 to 0.25, which downscales the width of the network (and the number of\n# filters) by a factor of four. And if we were really strapped for space, we could reduce the\n# number of **channels** by making our model take grayscale images instead of RGB ones.\n#\n# In this tutorial, we will use an RGB 64x64 input image and alpha 0.25. This is not quite\n# ideal, but it allows the finished model to fit in 192 KB of RAM, while still letting us perform\n# transfer learning using the official TensorFlow source models (if we used alpha <0.25 or a\n# grayscale input, we wouldn't be able to do this).\n#\n# What is Transfer Learning?\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^\n# Deep learning has `dominated image classification <https://paperswithcode.com/sota/image-classification-on-imagenet>`_ for a long time,\n# but training neural networks takes a lot of time. When a neural network is trained \"from scratch\",\n# its parameters start out randomly initialized, forcing it to learn very slowly how to tell images\n# apart.\n#\n# With transfer learning, we instead start with a neural network that's **already** good at a\n# specific task. In this example, that task is classifying images from `the ImageNet database <https://www.image-net.org/>`_. This\n# means the network already has some object detection capabilities, and is likely closer to what you\n# want then a random model would be.\n#\n# This works especially well with image processing neural networks like MobileNet. In practice, it\n# turns out the convolutional layers of the model (i.e. the first 90% of the layers) are used for\n# identifying low-level features like lines and shapes - only the last few fully connected layers\n# are used to determine how those shapes make up the objects the network is trying to detect.\n#\n# We can take advantage of this by starting training with a MobileNet model that was trained on\n# ImageNet, and already knows how to identify those lines and shapes. We can then just remove the\n# last few layers from this pretrained model, and add our own final layers. We'll then train this\n# conglomerate model for a few epochs on our cars vs non-cars dataset, to adjust the first layers\n# and train from scratch the last layers. This process of training an already-partially-trained\n# model is called *fine-tuning*.\n#\n# Source MobileNets for transfer learning have been `pretrained by the TensorFlow folks <https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md>`_, so we\n# can just download the one closest to what we want (the 128x128 input model with 0.25 depth scale).\n\nos.makedirs(f\"{FOLDER}/models\")\nWEIGHTS_PATH = f\"{FOLDER}/models/mobilenet_2_5_128_tf.h5\"\nurllib.request.urlretrieve(\n    \"https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/mobilenet_2_5_128_tf.h5\",\n    WEIGHTS_PATH,\n)\n\npretrained = tf.keras.applications.MobileNet(\n    input_shape=IMAGE_SIZE, weights=WEIGHTS_PATH, alpha=0.25\n)\n\n######################################################################\n# Modifying Our Network\n# ^^^^^^^^^^^^^^^^^^^^^\n# As mentioned above, our pretrained model is designed to classify the 1,000 ImageNet categories,\n# but we want to convert it to classify cars. Since only the bottom few layers are task-specific,\n# we'll **cut off the last five layers** of our original model. In their place we'll build our own\n# \"tail\" to the model by performing respape, dropout, flatten, and softmax operations.\n\nmodel = tf.keras.models.Sequential()\n\nmodel.add(tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE))\nmodel.add(tf.keras.Model(inputs=pretrained.inputs, outputs=pretrained.layers[-5].output))\n\nmodel.add(tf.keras.layers.Reshape((-1,)))\nmodel.add(tf.keras.layers.Dropout(0.1))\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(2, activation=\"softmax\"))\n\n######################################################################\n# Fine Tuning Our Network\n# ^^^^^^^^^^^^^^^^^^^^^^^\n# When training neural networks, we must set a parameter called the **learning rate** that controls\n# how fast our network learns. It must be set carefully - too slow, and our network will take\n# forever to train; too fast, and our network won't be able to learn some fine details. Generally\n# for Adam (the optimizer we're using), ``0.001`` is a pretty good learning rate (and is what's\n# recommended in the `original paper <https://arxiv.org/abs/1412.6980>`_). However, in this case\n# ``0.0005`` seems to work a little better.\n#\n# We'll also pass the validation set from earlier to ``model.fit``. This will evaluate how good our\n# model is each time we train it, and let us track how our model is improving. Once training is\n# finished, the model should have a validation accuracy around ``0.98`` (meaning it was right 98% of\n# the time on our validation set).\n\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),\n    loss=\"categorical_crossentropy\",\n    metrics=[\"accuracy\"],\n)\nmodel.fit(train_dataset, validation_data=validation_dataset, epochs=3, verbose=2)\n\n######################################################################\n# Quantization\n# ------------\n# We've done a decent job of reducing our model's size so far - changing the input dimension,\n# along with removing the bottom layers reduced the model to just 219k parameters. However, each of\n# these parameters is a ``float32`` that takes four bytes, so our model will take up almost one MB!\n#\n# Additionally, it might be the case that our hardware doesn't have built-in support for floating\n# point numbers. While most high-memory Arduinos (like the Nano 33 BLE) do have hardware support,\n# some others (like the Arduino Due) do not. On any boards *without* dedicated hardware support,\n# floating point multiplication will be extremely slow.\n#\n# To address both issues we will **quantize** the model - representing the weights as eight bit\n# integers. It's more complex than just rounding, though - to get the best performance, TensorFlow\n# tracks how each neuron in our model activates, so we can figure out how most accurately simulate\n# the neuron's original activations with integer operations.\n#\n# We will help TensorFlow do this by creating a representative dataset - a subset of the original\n# that is used for tracking how those neurons activate. We'll then pass this into a ``TFLiteConverter``\n# (Keras itself does not have quantization support) with an ``Optimize`` flag to tell TFLite to perform\n# the conversion. By default, TFLite keeps the inputs and outputs of our model as floats, so we must\n# explicitly tell it to avoid this behavior.\n\n\ndef representative_dataset():\n    for image_batch, label_batch in full_dataset.take(10):\n        yield [image_batch]\n\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\nconverter.representative_dataset = representative_dataset\nconverter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\nconverter.inference_input_type = tf.uint8\nconverter.inference_output_type = tf.uint8\n\nquantized_model = converter.convert()\n\n######################################################################\n# Download the Model if Desired\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# We've now got a finished model that you can use locally or in other tutorials (try autotuning\n# this model or viewing it on `https://netron.app/ <https://netron.app/>`_). But before we do\n# those things, we'll have to write it to a file (``quantized.tflite``). If you're running this\n# tutorial on Google Colab, you'll have to uncomment the last two lines to download the file\n# after writing it.\n\nQUANTIZED_MODEL_PATH = f\"{FOLDER}/models/quantized.tflite\"\nwith open(QUANTIZED_MODEL_PATH, \"wb\") as f:\n    f.write(quantized_model)\n# from google.colab import files\n# files.download(QUANTIZED_MODEL_PATH)\n\n######################################################################\n# Compiling With TVM For Arduino\n# ------------------------------\n# TensorFlow has a built-in framework for deploying to microcontrollers - `TFLite Micro <https://www.tensorflow.org/lite/microcontrollers>`_. However,\n# it's poorly supported by development boards and does not support autotuning. We will use Apache\n# TVM instead.\n#\n# TVM can be used either with its command line interface (``tvmc``) or with its Python interface. The\n# Python interface is fully-featured and more stable, so we'll use it here.\n#\n# TVM is an optimizing compiler, and optimizations to our model are performed in stages via\n# **intermediate representations**. The first of these is `Relay <https://arxiv.org/abs/1810.00952>`_ a high-level intermediate\n# representation emphasizing portability. The conversion from ``.tflite`` to Relay is done without any\n# knowledge of our \"end goal\" - the fact we intend to run this model on an Arduino.\n#\n# Choosing an Arduino Board\n# ^^^^^^^^^^^^^^^^^^^^^^^^^\n# Next, we'll have to decide exactly which Arduino board to use. The Arduino sketch that we\n# ultimately generate should be compatible with any board, but knowing which board we are using in\n# advance allows TVM to adjust its compilation strategy to get better performance.\n#\n# There is one catch - we need enough **memory** (flash and RAM) to be able to run our model. We\n# won't ever be able to run a complex vision model like a MobileNet on an Arduino Uno - that board\n# only has 2 kB of RAM and 32 kB of flash! Our model has ~200,000 parameters, so there is just no\n# way it could fit.\n#\n# For this tutorial, we will use the Nano 33 BLE, which has 1 MB of flash memory and 256 KB of RAM.\n# However, any other Arduino with those specs or better should also work.\n#\n# Generating our project\n# ^^^^^^^^^^^^^^^^^^^^^^\n# Next, we'll compile the model to TVM's MLF (model library format) intermediate representation,\n# which consists of C/C++ code and is designed for autotuning. To improve performance, we'll tell\n# TVM that we're compiling for the ``nrf52840`` microprocessor (the one the Nano 33 BLE uses). We'll\n# also tell it to use the C runtime (abbreviated ``crt``) and to use ahead-of-time memory allocation\n# (abbreviated ``aot``, which helps reduce the model's memory footprint). Lastly, we will disable\n# vectorization with ``\"tir.disable_vectorize\": True``, as C has no native vectorized types.\n#\n# Once we have set these configuration parameters, we will call ``tvm.relay.build`` to compile our\n# Relay model into the MLF intermediate representation. From here, we just need to call\n# ``tvm.micro.generate_project`` and pass in the Arduino template project to finish compilation.\n\nimport shutil\nimport tflite\nimport tvm\n\n# Method to load model is different in TFLite 1 vs 2\ntry:  # TFLite 2.1 and above\n    tflite_model = tflite.Model.GetRootAsModel(quantized_model, 0)\nexcept AttributeError:  # Fall back to TFLite 1.14 method\n    tflite_model = tflite.Model.Model.GetRootAsModel(quantized_model, 0)\n\n# Convert to the Relay intermediate representation\nmod, params = tvm.relay.frontend.from_tflite(tflite_model)\n\n# Set configuration flags to improve performance\ntarget = tvm.target.target.micro(\"nrf52840\")\nruntime = tvm.relay.backend.Runtime(\"crt\")\nexecutor = tvm.relay.backend.Executor(\"aot\", {\"unpacked-api\": True})\n\n# Convert to the MLF intermediate representation\nwith tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n    mod = tvm.relay.build(mod, target, runtime=runtime, executor=executor, params=params)\n\n# Generate an Arduino project from the MLF intermediate representation\nshutil.rmtree(f\"{FOLDER}/models/project\", ignore_errors=True)\narduino_project = tvm.micro.generate_project(\n    tvm.micro.get_microtvm_template_projects(\"arduino\"),\n    mod,\n    f\"{FOLDER}/models/project\",\n    {\n        \"board\": \"nano33ble\",\n        \"arduino_cli_cmd\": \"/content/bin/arduino-cli\",\n        \"project_type\": \"example_project\",\n    },\n)\n\n######################################################################\n# Testing our Arduino Project\n# ---------------------------\n# Consider the following two 224x224 images from the author's camera roll - one of a car, one not.\n# We will test our Arduino project by loading both of these images and executing the compiled model\n# on them.\n#\n# .. image:: https://raw.githubusercontent.com/tlc-pack/web-data/main/testdata/microTVM/data/model_train_images_combined.png\n#      :align: center\n#      :height: 200px\n#      :width: 600px\n#\n# Currently, these are 224x224 PNG images we can download from Imgur. Before we can feed in these\n# images, we'll need to resize and convert them to raw data, which can be done with ``imagemagick``.\n#\n# It's also challenging to load raw data onto an Arduino, as only C/CPP files (and similar) are\n# compiled. We can work around this by embedding our raw data in a hard-coded C array with the\n# built-in utility ``bin2c`` that will output a file like below:\n#\n#     .. code-block:: c\n#\n#       static const unsigned char CAR_IMAGE[] = {\n#         0x22,0x23,0x14,0x22,\n#         ...\n#         0x07,0x0e,0x08,0x08\n#       };\n#\n# We can do both of these things with a few lines of Bash code:\n#\n#     .. code-block:: bash\n#\n#       %%bash\n#       mkdir -p ~/tests\n#       curl \"https://i.imgur.com/JBbEhxN.png\" -o ~/tests/car_224.png\n#       convert ~/tests/car_224.png -resize 64 ~/tests/car_64.png\n#       stream ~/tests/car_64.png ~/tests/car.raw\n#       bin2c -c -st ~/tests/car.raw --name CAR_IMAGE > ~/models/project/car.c\n#\n#       curl \"https://i.imgur.com/wkh7Dx2.png\" -o ~/tests/catan_224.png\n#       convert ~/tests/catan_224.png -resize 64 ~/tests/catan_64.png\n#       stream ~/tests/catan_64.png ~/tests/catan.raw\n#       bin2c -c -st ~/tests/catan.raw --name CATAN_IMAGE > ~/models/project/catan.c\n\n######################################################################\n# Writing our Arduino Script\n# --------------------------\n# We now need a little bit of Arduino code to read the two binary arrays we just generated, run the\n# model on them, and log the output to the serial monitor. This file will replace ``arduino_sketch.ino``\n# as the main file of our sketch. You'll have to copy this code in manually..\n#\n#     .. code-block:: c\n#\n#         %%writefile /root/models/project.ino\n#         #include \"src/model.h\"\n#         #include \"car.c\"\n#         #include \"catan.c\"\n#\n#         void setup() {\n#           Serial.begin(9600);\n#           TVMInitialize();\n#         }\n#\n#         void loop() {\n#           uint8_t result_data[2];\n#           Serial.println(\"Car results:\");\n#           TVMExecute(const_cast<uint8_t*>(CAR_IMAGE), result_data);\n#           Serial.print(result_data[0]); Serial.print(\", \");\n#           Serial.print(result_data[1]); Serial.println();\n#\n#           Serial.println(\"Other object results:\");\n#           TVMExecute(const_cast<uint8_t*>(CATAN_IMAGE), result_data);\n#           Serial.print(result_data[0]); Serial.print(\", \");\n#           Serial.print(result_data[1]); Serial.println();\n#\n#           delay(1000);\n#         }\n#\n# Compiling Our Code\n# ^^^^^^^^^^^^^^^^^^\n# Now that our project has been generated, TVM's job is mostly done! We can still call\n# ``arduino_project.build()`` and ``arduino_project.upload()``, but these just use ``arduino-cli``'s\n# compile and flash commands underneath. We could also begin autotuning our model, but that's a\n# subject for a different tutorial. To finish up, we'll verify no compiler errors are thrown\n# by our project:\n\nshutil.rmtree(f\"{FOLDER}/models/project/build\", ignore_errors=True)\n# sphinx_gallery_start_ignore\nfrom unittest.mock import MagicMock\n\narduino_project = MagicMock()\n# sphinx_gallery_end_ignore\narduino_project.build()\nprint(\"Compilation succeeded!\")\n\n######################################################################\n# Uploading to Our Device\n# -----------------------\n# The very last step is uploading our sketch to an Arduino to make sure our code works properly.\n# Unfortunately, we can't do that from Google Colab, so we'll have to download our sketch. This is\n# simple enough to do - we'll just turn our project into a `.zip` archive, and call `files.download`.\n# If you're running on Google Colab, you'll have to uncomment the last two lines to download the file\n# after writing it.\n\nZIP_FOLDER = f\"{FOLDER}/models/project\"\nshutil.make_archive(ZIP_FOLDER, \"zip\", ZIP_FOLDER)\n# from google.colab import files\n# files.download(f\"{FOLDER}/models/project.zip\")\n# sphinx_gallery_start_ignore\n# Run a few unit tests to make sure the Python code worked\n\n# Ensure transfer learn model was correctly assembled\nassert len(model.layers) == 5\nassert model.count_params() == 219058  # Only 219,058 of these are trainable\n\nassert len(quantized_model) >= 250000  # Quantized model will be 250 KB - 350 KB\nassert len(quantized_model) <= 350000  # Exact value depends on quantization\n\n# Assert .tflite and .zip files were written to disk\nassert os.path.isfile(f\"{FOLDER}/models/quantized.tflite\")\nassert os.path.isfile(f\"{FOLDER}/models/project.zip\")\n\n# Assert MLF file was correctly generated\nassert mod.executor.name == \"aot\"\n\n# Remove the temporary folder we generated at the beginning\nshutil.rmtree(FOLDER)\n# sphinx_gallery_end_ignore\n\n\n######################################################################\n# From here, we'll need to open it in the Arduino IDE. You'll have to download the IDE as well as\n# the SDK for whichever board you are using. For certain boards like the Sony SPRESENSE, you may\n# have to change settings to control how much memory you want the board to use.\n#\n# Expected Results\n# ^^^^^^^^^^^^^^^^\n# If all works as expected, you should see the following output on a Serial monitor:\n#\n#     .. code-block::\n#\n#       Car results:\n#       255, 0\n#       Other object results:\n#       0, 255\n#\n# The first number represents the model's confidence that the object **is** a car and ranges from\n# 0-255. The second number represents the model's confidence that the object **is not** a car and\n# is also 0-255. These results mean the model is very sure that the first image is a car, and the\n# second image is not (which is correct). Hence, our model is working!\n#\n# Summary\n# -------\n# In this tutorial, we used transfer learning to quickly train an image recognition model to\n# identify cars. We modified its input dimensions and last few layers to make it better at this,\n# and to make it faster and smaller. We then quantified the model and compiled it using TVM to\n# create an Arduino sketch. Lastly, we tested the model using two static images to prove it works\n# as intended.\n#\n# Next Steps\n# ^^^^^^^^^^\n# From here, we could modify the model to read live images from the camera - we have another\n# Arduino tutorial for how to do that `on GitHub <https://github.com/guberti/tvm-arduino-demos/tree/master/examples/person_detection>`_. Alternatively, we could also\n# `use TVM's autotuning capabilities <https://tvm.apache.org/docs/how_to/work_with_microtvm/micro_autotune.html>`_ to dramatically improve the model's performance.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_pytorch/using_as_torch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nWrap Your TVMScript as PyTorch Module\n======================\n**Author**:\n`Yaoda Zhou <https://github.com/juda>`_\n\nThis article is a tutorial on wrapping the TVMScript code as the PyTorch module.\nUsing the decorator `as_torch`, users can wrap TVMScript code into a PyTorch nn.Module naturally.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n# Import PyTorch, as well as necessary libraries\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.benchmark as benchmark\n\nimport tvm\nfrom tvm.contrib.torch import as_torch\nfrom tvm.script import tir as T\n\n######################################################################\n# Write your own PyTorch operator by TVMScript\n# -------------------------------\n# PyTorch is a very popular machine learning framework which contains\n# optimized implementations of most commonly used operators.\n# Nevertheless, sometimes you might want to write your own operators in PyTorch.\n# In that case, the performance of such custom operators might not be satisfactory for your needs.\n#\n# For example, suppose that we are going to define a 1-d depthwise convolution operator.\n# Assume the number of in_channel and out_channel are both 70,\n# the width is 80 and the kernel size is 20,\n# then the 1-d depthwise conv could be written in PyTorch in one line:\n\nin_channel = 70\nout_channel = 70\nwidth = 80\nkernel_size = 20\n\n\ndef torch_depthwise(inputs, filters):\n    return F.conv1d(inputs, filters.view(out_channel, 1, kernel_size), groups=out_channel)\n\n\n# We can run this function as:\n\ninputs = torch.randn(in_channel, width)\nfilters = torch.randn(out_channel, kernel_size)\nret_torch = torch_depthwise(inputs, filters)\n\n\n# The `torch_depthwise` function, in a plain Python code, could be written as:\n\n\ndef vanilla_depthwise(input, weight):\n    ret = torch.zeros(out_channel, width - kernel_size + 1)\n    for j in range(out_channel):\n        for i in range(width - kernel_size + 1):\n            for k in range(kernel_size):\n                ret[j, i] += weight[j, k] * input[j, i + k]\n    return ret\n\n\n# Then, we plan to optimize the `depthwise` function by leveraging the power of TVM.\n# TVM community proposes an embedded Domain Specific Language in Python called TVMScript,\n# which serves as the high-level frontend for TVM's Tensor IR.\n# The depthwise 1D convolution code above can be translated to TVMScript as follows.\n# We provide an `as_torch` decorator, which converts the TVMScript code to PyTorch's nn.Module automatically.\n\n\n@as_torch\n@T.prim_func\ndef tvm_depthwise(\n    A: T.Buffer((70, 80), \"float32\"),\n    B: T.Buffer((70, 20), \"float32\"),\n    C: T.Buffer((70, 61), \"float32\"),\n) -> None:\n    for j, i, k in T.grid(70, 61, 20):\n        with T.block():\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vj, vi] = T.float32(0)\n            C[vj, vi] += B[vj, vk] * A[vj, vi + vk]\n\n\n# We can build the TVMScript code by calling the `tune` method in default setting.\n# Without providing extra information, the model will be tuned for CPU.\n\ntvm_depthwise.tune()\n\n# We can print out the tuned TVMScript code to see how the program is transformed, as\n\nprint(tvm_depthwise.script())\n\n# We can verify that the two outputs are the same:\n\nret_tvm = torch.zeros(out_channel, width - kernel_size + 1)\ntvm_depthwise(inputs, filters, ret_tvm)\n\ntesting.assert_allclose(ret_torch.cpu().numpy(), ret_tvm.cpu().numpy(), atol=1e-5, rtol=1e-5)\n\n\n######################################################################\n# Benchmark\n# -------------------------------\n\nresults = []\nfor i in range(5):\n    inputs = torch.randn(out_channel, width)\n    filters = torch.randn(out_channel, kernel_size)\n    res = torch.zeros(out_channel, width - kernel_size + 1)\n    sub_label = f\"[test {i}]\"\n    results.append(\n        benchmark.Timer(\n            stmt=\"tvm_depthwise(inputs, filters, res)\",\n            setup=\"from __main__ import tvm_depthwise\",\n            globals={\"inputs\": inputs, \"filters\": filters, \"res\": res},\n            sub_label=sub_label,\n            description=\"TVMScript\",\n        ).blocked_autorange()\n    )\n    results.append(\n        benchmark.Timer(\n            stmt=\"torch_depthwise(inputs, filters)\",\n            setup=\"from __main__ import torch_depthwise\",\n            globals={\n                \"inputs\": inputs,\n                \"filters\": filters,\n            },\n            sub_label=sub_label,\n            description=\"PyTorch\",\n        ).blocked_autorange()\n    )\ncompare = benchmark.Compare(results)\ncompare.print()\n\n# In author's environment, the average inference time of `tvm_depthwise` is 120.0 us,\n# while the average inference time of `torch_depthwise` is 196.0 us (PyTorch version is 1.11.0),\n# showing the speedup of around 38%.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_pytorch/using_optimized_torch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompile PyTorch Models\n======================\n**Author**:\n`Yaoda Zhou <https://github.com/juda>`_\n\nThis article is a tutorial to optimize PyTorch models by using decorator `optimize_torch`.\nTo follow this tutorial, PyTorch, as well as TorchVision, should be installed.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n# Import PyTorch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# Import library for profiling\nimport torch.utils.benchmark as benchmark\nfrom torchvision.models import resnet18\n\n# Import `optimize_torch` function\nfrom tvm.contrib.torch import optimize_torch\nfrom tvm.meta_schedule import TuneConfig\n\n######################################################################\n# Define a simple module written by PyTorch\n# ------------------------------\n\n\nclass SimpleModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv1 = nn.Conv2d(1, 20, 5)\n        self.conv2 = nn.Conv2d(20, 20, 5)\n\n    def forward(self, x):\n        x = F.relu(self.conv1(x))\n        return F.relu(self.conv2(x))\n\n\n######################################################################\n# Optimize SimpleModel by TVM MetaSchedule\n# ------------------------------\n# We provide the `optimize_torch` function, which has the similar usage as `torch.jit.trace`.\n# The PyTorch model to optimize, along with its example input, are provided by users.\n# The PyTorch module will be tuned by TVM for the target hardware.\n# Without providing extra information, the model will be tuned for CPU.\n\nsimple_model = SimpleModel()\nexample_input = torch.randn(20, 1, 10, 10)\nmodel_optimized_by_tvm = optimize_torch(simple_model, example_input)\n\n######################################################################\n# Save/Load module\n# ------------------------------\n# We can save and load our tuned module like the standard `nn.Module`.\n\n# Let us run our tuned module.\nret1 = model_optimized_by_tvm(example_input)\n\ntorch.save(model_optimized_by_tvm, \"model_optimized.pt\")\nmodel_loaded = torch.load(\"model_optimized.pt\")\n\n# We load the module and run it again.\nret2 = model_loaded(example_input)\n\n# We will show 2 results:\n# (1) we can safely load and save model by showing the result of model\n# after save and load operations is still the same as original one;\n# (2) the model we optimize returns the same result as the original PyTorch model.\n\nret3 = simple_model(example_input)\ntesting.assert_allclose(ret1.detach().numpy(), ret2.detach().numpy(), atol=1e-5, rtol=1e-5)\ntesting.assert_allclose(ret1.detach().numpy(), ret3.detach().numpy(), atol=1e-5, rtol=1e-5)\n\n######################################################################\n# Optimize resnet18\n# ------------------------------\n# In the following, we will show that our approach is able to\n# accelerate common models, such as resnet18.\n\n# We will tune our model for the GPU.\ntarget_cuda = \"nvidia/geforce-rtx-3070\"\n\n# For PyTorch users, the code could be written as usual, except for\n# applying \"optimize_torch\" function on the resnet18 model.\n\nresnet18_tvm = optimize_torch(\n    resnet18().cuda().eval(), [torch.rand(1, 3, 224, 224).cuda()], target=target_cuda\n)\n\n# TorchScript also provides a built-in \"optimize_for_inference\" function to accelerate the inference.\nresnet18_torch = torch.jit.optimize_for_inference(torch.jit.script(resnet18().cuda().eval()))\n\n\n######################################################################\n# Compare the performance between two approaches.\n# ------------------------------\n\nresults = []\nfor i in range(5):\n    test_input = torch.rand(1, 3, 224, 224).cuda()\n    sub_label = f\"[test {i}]\"\n    results.append(\n        benchmark.Timer(\n            stmt=\"resnet18_tvm(test_input)\",\n            setup=\"from __main__ import resnet18_tvm\",\n            globals={\"test_input\": test_input},\n            sub_label=sub_label,\n            description=\"tuning by meta\",\n        ).blocked_autorange()\n    )\n    results.append(\n        benchmark.Timer(\n            stmt=\"resnet18_torch(test_input)\",\n            setup=\"from __main__ import resnet18_torch\",\n            globals={\"test_input\": test_input},\n            sub_label=sub_label,\n            description=\"tuning by jit\",\n        ).blocked_autorange()\n    )\n\ncompare = benchmark.Compare(results)\ncompare.print()\n\n# In author's environment, the average inference time of `resnet18_tvm` is 620.0 us,\n# while the average inference time of `resnet18_torch` is 980.0 us (PyTorch version is 1.11.0),\n# showing the speedup of around 38%.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_relay/build_gcn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nBuilding a Graph Convolutional Network\n======================================\n**Author**: `Yulun Yao <https://yulunyao.io/>`_, \\\n            `Chien-Yu Lin <https://homes.cs.washington.edu/~cyulin/>`_\n\nThis article is an introductory tutorial to build a Graph Convolutional Network (GCN) with Relay.\nIn this tutorial, we will run our GCN on Cora dataset to demonstrate.\nCora dataset is a common benchmark for Graph Neural Networks (GNN) and frameworks that support GNN training and inference.\nWe directly load the dataset from DGL library to do the apples to apples comparison against DGL.\n\nPlease refer to DGL doc for DGL installation at\nhttps://docs.dgl.ai/install/index.html.\n\nPlease refer to PyTorch guide for PyTorch installation at\nhttps://pytorch.org/get-started/locally/.\n\"\"\"\n\n\n######################################################################\n# Define GCN in DGL with PyTorch backend\n# --------------------------------------\n#\n# DGL example: https://github.com/dmlc/dgl/tree/master/examples/pytorch/gcn\n# This part reuses the code from the above example.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport dgl\nimport networkx as nx\nfrom dgl.nn.pytorch import GraphConv\n\n\nclass GCN(nn.Module):\n    def __init__(self, g, n_infeat, n_hidden, n_classes, n_layers, activation):\n        super(GCN, self).__init__()\n        self.g = g\n        self.layers = nn.ModuleList()\n        self.layers.append(GraphConv(n_infeat, n_hidden, activation=activation))\n        for i in range(n_layers - 1):\n            self.layers.append(GraphConv(n_hidden, n_hidden, activation=activation))\n        self.layers.append(GraphConv(n_hidden, n_classes))\n\n    def forward(self, features):\n        h = features\n        for i, layer in enumerate(self.layers):\n            # handle api changes for differnt DGL version\n            if dgl.__version__ > \"0.3\":\n                h = layer(self.g, h)\n            else:\n                h = layer(h, self.g)\n        return h\n\n\n######################################################################\n# Define the functions to load dataset and evaluate accuracy\n# ----------------------------------------------------------\n# You may substitute this part with your own dataset, here we load data from DGL\nfrom dgl.data import load_data\nfrom collections import namedtuple\n\n\ndef load_dataset(dataset=\"cora\"):\n    args = namedtuple(\"args\", [\"dataset\"])\n    data = load_data(args(dataset))\n\n    # Remove self-loops to avoid duplicate passing of a node's feature to itself\n    g = data.graph\n    g.remove_edges_from(nx.selfloop_edges(g))\n    g.add_edges_from(zip(g.nodes, g.nodes))\n\n    return g, data\n\n\ndef evaluate(data, logits):\n    test_mask = data.test_mask  # the test set which isn't included in the training phase\n\n    pred = logits.argmax(axis=1)\n    acc = ((pred == data.labels) * test_mask).sum() / test_mask.sum()\n\n    return acc\n\n\n######################################################################\n# Load the data and set up model parameters\n# -----------------------------------------\n\"\"\"\nParameters\n----------\ndataset: str\n    Name of dataset. You can choose from ['cora', 'citeseer', 'pubmed'].\n\nnum_layer: int\n    number of hidden layers\n\nnum_hidden: int\n    number of the hidden units in the hidden layer\n\ninfeat_dim: int\n    dimension of the input features\n\nnum_classes: int\n    dimension of model output (Number of classes)\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\ndataset = \"cora\"\ng, data = load_dataset(dataset)\n\nnum_layers = 1\nnum_hidden = 16\ninfeat_dim = data.features.shape[1]\nnum_classes = data.num_labels\n\n######################################################################\n# Set up the DGL-PyTorch model and get the golden results\n# -------------------------------------------------------\n#\n# The weights are trained with https://github.com/dmlc/dgl/blob/master/examples/pytorch/gcn/train.py\nfrom tvm.contrib.download import download_testdata\nfrom dgl import DGLGraph\n\nfeatures = torch.FloatTensor(data.features)\ndgl_g = DGLGraph(g)\n\ntorch_model = GCN(dgl_g, infeat_dim, num_hidden, num_classes, num_layers, F.relu)\n\n# Download the pretrained weights\nmodel_url = \"https://homes.cs.washington.edu/~cyulin/media/gnn_model/gcn_%s.torch\" % (dataset)\nmodel_path = download_testdata(model_url, \"gcn_%s.pickle\" % (dataset), module=\"gcn_model\")\n\n# Load the weights into the model\ntorch_model.load_state_dict(torch.load(model_path))\n\n\n######################################################################\n# Run the DGL model and test for accuracy\n# ---------------------------------------\ntorch_model.eval()\nwith torch.no_grad():\n    logits_torch = torch_model(features)\nprint(\"Print the first five outputs from DGL-PyTorch execution\\n\", logits_torch[:5])\n\nacc = evaluate(data, logits_torch.numpy())\nprint(\"Test accuracy of DGL results: {:.2%}\".format(acc))\n\n\n######################################################################\n# Define Graph Convolution Layer in Relay\n# ---------------------------------------\n# To run GCN on TVM, we first need to implement Graph Convolution Layer.\n# You may refer to https://github.com/dmlc/dgl/blob/master/python/dgl/nn/mxnet/conv/graphconv.py for a GraphConv Layer implemented in DGL with MXNet Backend\n#\n# The layer is defined with below operations, note that we apply two transposes to keep adjacency matrix on right hand side of sparse_dense operator,\n# this method is temporary and will be updated in next few weeks when we have sparse matrix transpose and support for left sparse operator.\n#\n#  .. math::\n#\n#            \\mbox{GraphConv}(A, H, W)   = A * H * W\n#                                        = ((H * W)^t * A^t)^t\n#                                        = ((W^t * H^t) * A^t)^t\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nimport tvm\nfrom tvm import te\n\n\ndef GraphConv(layer_name, input_dim, output_dim, adj, input, norm=None, bias=True, activation=None):\n    \"\"\"\n    Parameters\n    ----------\n    layer_name: str\n    Name of layer\n\n    input_dim: int\n    Input dimension per node feature\n\n    output_dim: int,\n    Output dimension per node feature\n\n    adj: namedtuple,\n    Graph representation (Adjacency Matrix) in Sparse Format (`data`, `indices`, `indptr`),\n    where `data` has shape [num_nonzeros], indices` has shape [num_nonzeros], `indptr` has shape [num_nodes + 1]\n\n    input: relay.Expr,\n    Input feature to current layer with shape [num_nodes, input_dim]\n\n    norm: relay.Expr,\n    Norm passed to this layer to normalize features before and after Convolution.\n\n    bias: bool\n    Set bias to True to add bias when doing GCN layer\n\n    activation: <function relay.op.nn>,\n    Activation function applies to the output. e.g. relay.nn.{relu, sigmoid, log_softmax, softmax, leaky_relu}\n\n    Returns\n    ----------\n    output: tvm.relay.Expr\n    The Output Tensor for this layer [num_nodes, output_dim]\n    \"\"\"\n    if norm is not None:\n        input = relay.multiply(input, norm)\n\n    weight = relay.var(layer_name + \".weight\", shape=(input_dim, output_dim))\n    weight_t = relay.transpose(weight)\n    dense = relay.nn.dense(weight_t, input)\n    output = relay.nn.sparse_dense(dense, adj)\n    output_t = relay.transpose(output)\n    if norm is not None:\n        output_t = relay.multiply(output_t, norm)\n    if bias is True:\n        _bias = relay.var(layer_name + \".bias\", shape=(output_dim, 1))\n        output_t = relay.nn.bias_add(output_t, _bias, axis=-1)\n    if activation is not None:\n        output_t = activation(output_t)\n    return output_t\n\n\n######################################################################\n# Prepare the parameters needed in the GraphConv layers\n# -----------------------------------------------------\n#\nimport numpy as np\nimport networkx as nx\n\n\ndef prepare_params(g, data):\n    params = {}\n    params[\"infeats\"] = data.features.numpy().astype(\n        \"float32\"\n    )  # Only support float32 as feature for now\n\n    # Generate adjacency matrix\n    adjacency = nx.to_scipy_sparse_matrix(g)\n    params[\"g_data\"] = adjacency.data.astype(\"float32\")\n    params[\"indices\"] = adjacency.indices.astype(\"int32\")\n    params[\"indptr\"] = adjacency.indptr.astype(\"int32\")\n\n    # Normalization w.r.t. node degrees\n    degs = [g.in_degree[i] for i in range(g.number_of_nodes())]\n    params[\"norm\"] = np.power(degs, -0.5).astype(\"float32\")\n    params[\"norm\"] = params[\"norm\"].reshape((params[\"norm\"].shape[0], 1))\n\n    return params\n\n\nparams = prepare_params(g, data)\n\n# Check shape of features and the validity of adjacency matrix\nassert len(params[\"infeats\"].shape) == 2\nassert (\n    params[\"g_data\"] is not None and params[\"indices\"] is not None and params[\"indptr\"] is not None\n)\nassert params[\"infeats\"].shape[0] == params[\"indptr\"].shape[0] - 1\n\n######################################################################\n# Put layers together\n# -------------------\n\n# Define input features, norms, adjacency matrix in Relay\ninfeats = relay.var(\"infeats\", shape=data.features.shape)\nnorm = relay.Constant(tvm.nd.array(params[\"norm\"]))\ng_data = relay.Constant(tvm.nd.array(params[\"g_data\"]))\nindices = relay.Constant(tvm.nd.array(params[\"indices\"]))\nindptr = relay.Constant(tvm.nd.array(params[\"indptr\"]))\n\nAdjacency = namedtuple(\"Adjacency\", [\"data\", \"indices\", \"indptr\"])\nadj = Adjacency(g_data, indices, indptr)\n\n# Construct the 2-layer GCN\nlayers = []\nlayers.append(\n    GraphConv(\n        layer_name=\"layers.0\",\n        input_dim=infeat_dim,\n        output_dim=num_hidden,\n        adj=adj,\n        input=infeats,\n        norm=norm,\n        activation=relay.nn.relu,\n    )\n)\nlayers.append(\n    GraphConv(\n        layer_name=\"layers.1\",\n        input_dim=num_hidden,\n        output_dim=num_classes,\n        adj=adj,\n        input=layers[-1],\n        norm=norm,\n        activation=None,\n    )\n)\n\n# Analyze free variables and generate Relay function\noutput = layers[-1]\n\n######################################################################\n# Compile and run with TVM\n# ------------------------\n#\n# Export the weights from PyTorch model to Python Dict\nmodel_params = {}\nfor param_tensor in torch_model.state_dict():\n    model_params[param_tensor] = torch_model.state_dict()[param_tensor].numpy()\n\nfor i in range(num_layers + 1):\n    params[\"layers.%d.weight\" % (i)] = model_params[\"layers.%d.weight\" % (i)]\n    params[\"layers.%d.bias\" % (i)] = model_params[\"layers.%d.bias\" % (i)]\n\n# Set the TVM build target\ntarget = \"llvm\"  # Currently only support `llvm` as target\n\nfunc = relay.Function(relay.analysis.free_vars(output), output)\nfunc = relay.build_module.bind_params_by_name(func, params)\nmod = tvm.IRModule()\nmod[\"main\"] = func\n# Build with Relay\nwith tvm.transform.PassContext(opt_level=0):  # Currently only support opt_level=0\n    lib = relay.build(mod, target, params=params)\n\n# Generate graph executor\ndev = tvm.device(target, 0)\nm = graph_executor.GraphModule(lib[\"default\"](dev))\n\n######################################################################\n# Run the TVM model, test for accuracy and verify with DGL\n# --------------------------------------------------------\nm.run()\nlogits_tvm = m.get_output(0).numpy()\nprint(\"Print the first five outputs from TVM execution\\n\", logits_tvm[:5])\n\nlabels = data.labels\ntest_mask = data.test_mask\n\nacc = evaluate(data, logits_tvm)\nprint(\"Test accuracy of TVM results: {:.2%}\".format(acc))\n\nimport tvm.testing\n\n# Verify the results with the DGL model\ntvm.testing.assert_allclose(logits_torch, logits_tvm, atol=1e-3)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_relay/using_external_lib.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nUsing External Libraries in Relay\n=================================\n**Author**: `Masahiro Masuda <https://github.com/masahi>`_, `Truman Tian <https://github.com/SiNZeRo>`_\n\nThis is a short tutorial on how to use external libraries such as cuDNN, or cuBLAS with Relay.\n\nRelay uses TVM internally to generate target specific code. For example, with cuda backend TVM generates cuda kernels for all layers in the user provided network.\nBut sometimes it is also helpful to incorporate external libraries developed by various vendors into Relay.\nLuckily, TVM has a mechanism to transparently call into these libraries.\nFor Relay users, all we need to do is just to set a target string appropriately.\n\nBefore we can use external libraries from Relay, your TVM needs to be built with libraries you want to use.\nFor example, to use cuDNN, USE_CUDNN option in `cmake/config.cmake` needs to be enabled, and cuDNN include and library directories need to be specified if necessary.\n\nTo begin with, we import Relay and TVM.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import graph_executor as runtime\nfrom tvm import relay\nfrom tvm.relay import testing\nimport tvm.testing\n\n######################################################################\n# Create a simple network\n# -----------------------\n# Let's create a very simple network for demonstration.\n# It consists of convolution, batch normalization, and ReLU activation.\n\nout_channels = 16\nbatch_size = 1\n\ndata = relay.var(\"data\", relay.TensorType((batch_size, 3, 224, 224), \"float32\"))\nweight = relay.var(\"weight\")\nbn_gamma = relay.var(\"bn_gamma\")\nbn_beta = relay.var(\"bn_beta\")\nbn_mmean = relay.var(\"bn_mean\")\nbn_mvar = relay.var(\"bn_var\")\n\nsimple_net = relay.nn.conv2d(\n    data=data, weight=weight, kernel_size=(3, 3), channels=out_channels, padding=(1, 1)\n)\nsimple_net = relay.nn.batch_norm(simple_net, bn_gamma, bn_beta, bn_mmean, bn_mvar)[0]\nsimple_net = relay.nn.relu(simple_net)\nsimple_net = relay.Function(relay.analysis.free_vars(simple_net), simple_net)\n\ndata_shape = (batch_size, 3, 224, 224)\nnet, params = testing.create_workload(simple_net)\n\n######################################################################\n# Build and run with cuda backend\n# -------------------------------\n# We build and run this network with cuda backend, as usual.\n# By setting the logging level to DEBUG, the result of Relay graph compilation will be dumped as pseudo code.\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)  # to dump TVM IR after fusion\n\ntarget = \"cuda\"\nlib = relay.build_module.build(net, target, params=params)\n\ndev = tvm.device(target, 0)\ndata = np.random.uniform(-1, 1, size=data_shape).astype(\"float32\")\nmodule = runtime.GraphModule(lib[\"default\"](dev))\nmodule.set_input(\"data\", data)\nmodule.run()\nout_shape = (batch_size, out_channels, 224, 224)\nout = module.get_output(0, tvm.nd.empty(out_shape))\nout_cuda = out.numpy()\n######################################################################\n# The generated pseudo code should look something like below.\n# Note how bias add, batch normalization, and ReLU activation are fused into the convolution kernel.\n# TVM generates a single, fused kernel from this representation.\n#\n# .. code-block:: text\n#\n#       produce tensor {\n#         // attr [iter_var(blockIdx.z, , blockIdx.z)] thread_extent = 1\n#         // attr [compute] storage_scope = \"local\"\n#         allocate compute[float32 * 32]\n#         // attr [pad_temp.shared] storage_scope = \"shared\"\n#         allocate pad_temp.shared[float32 * 180]\n#         // attr [placeholder.shared] storage_scope = \"shared\"\n#         allocate placeholder.shared[float32 * 144]\n#         // attr [iter_var(blockIdx.y, , blockIdx.y)] thread_extent = 28\n#         // attr [iter_var(blockIdx.x, , blockIdx.x)] thread_extent = 14\n#         // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 4\n#         // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 1\n#         // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 16\n#         produce compute {\n#           compute[0] = 0.000000f\n#           compute[1] = 0.000000f\n#           compute[2] = 0.000000f\n#           compute[3] = 0.000000f\n#           compute[4] = 0.000000f\n#           compute[5] = 0.000000f\n#           compute[6] = 0.000000f\n#           compute[7] = 0.000000f\n#           compute[8] = 0.000000f\n#           compute[9] = 0.000000f\n#           compute[10] = 0.000000f\n#           compute[11] = 0.000000f\n#           compute[12] = 0.000000f\n#           compute[13] = 0.000000f\n#           compute[14] = 0.000000f\n#           compute[15] = 0.000000f\n#           compute[16] = 0.000000f\n#           compute[17] = 0.000000f\n#           compute[18] = 0.000000f\n#           compute[19] = 0.000000f\n#           compute[20] = 0.000000f\n#           compute[21] = 0.000000f\n#           compute[22] = 0.000000f\n#           compute[23] = 0.000000f\n#           compute[24] = 0.000000f\n#           compute[25] = 0.000000f\n#           compute[26] = 0.000000f\n#           compute[27] = 0.000000f\n#           compute[28] = 0.000000f\n#           compute[29] = 0.000000f\n#           compute[30] = 0.000000f\n#           compute[31] = 0.000000f\n#           for (rc.outer, 0, 3) {\n#             produce pad_temp.shared {\n#               // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 4\n#               // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 1\n#               // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 16\n#               if (likely(((threadIdx.z*15) < (60 - threadIdx.x)))) {\n#                 if (likely((threadIdx.x < 15))) {\n#                   pad_temp.shared[(((((threadIdx.z*15) + threadIdx.x)/60)*180) + ((((((threadIdx.z*15) + threadIdx.x)/6) % 10)*18) + ((((threadIdx.z*3) + threadIdx.x)*3) % 18)))] = tvm_if_then_else((((((1 - ((((threadIdx.z*15) + threadIdx.x)/6) % 10)) <= (blockIdx.y*8)) && ((blockIdx.y*8) < (225 - ((((threadIdx.z*15) + threadIdx.x)/6) % 10)))) && ((1 - ((((threadIdx.z*3) + threadIdx.x)*3) % 18)) <= (blockIdx.x*16))) && ((blockIdx.x*16) < (225 - ((((threadIdx.z*3) + threadIdx.x)*3) % 18)))), placeholder[((((((((blockIdx.y*112) + blockIdx.x) + (rc.outer*3136)) + ((((threadIdx.z*15) + threadIdx.x)/60)*9408))*16) + ((((threadIdx.z*3) + threadIdx.x)*3) % 18)) + (((((threadIdx.z*15) + threadIdx.x)/6) % 10)*224)) + -225)], 0.000000f)\n#                   pad_temp.shared[(((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/180)*180) + ((((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/18) % 10)*18) + (((((threadIdx.z*3) + threadIdx.x)*3) + 1) % 18)))] = tvm_if_then_else((((((1 - ((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/18) % 10)) <= (blockIdx.y*8)) && ((blockIdx.y*8) < (225 - ((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/18) % 10)))) && ((1 - (((((threadIdx.z*3) + threadIdx.x)*3) + 1) % 18)) <= (blockIdx.x*16))) && ((blockIdx.x*16) < (225 - (((((threadIdx.z*3) + threadIdx.x)*3) + 1) % 18)))), placeholder[((((((((blockIdx.y*112) + blockIdx.x) + (rc.outer*3136)) + ((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/180)*9408))*16) + (((((threadIdx.z*3) + threadIdx.x)*3) + 1) % 18)) + (((((((threadIdx.z*15) + threadIdx.x)*3) + 1)/18) % 10)*224)) + -225)], 0.000000f)\n#                   pad_temp.shared[(((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/180)*180) + ((((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/18) % 10)*18) + (((((threadIdx.z*3) + threadIdx.x)*3) + 2) % 18)))] = tvm_if_then_else((((((1 - ((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/18) % 10)) <= (blockIdx.y*8)) && ((blockIdx.y*8) < (225 - ((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/18) % 10)))) && ((1 - (((((threadIdx.z*3) + threadIdx.x)*3) + 2) % 18)) <= (blockIdx.x*16))) && ((blockIdx.x*16) < (225 - (((((threadIdx.z*3) + threadIdx.x)*3) + 2) % 18)))), placeholder[((((((((blockIdx.y*112) + blockIdx.x) + (rc.outer*3136)) + ((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/180)*9408))*16) + (((((threadIdx.z*3) + threadIdx.x)*3) + 2) % 18)) + (((((((threadIdx.z*15) + threadIdx.x)*3) + 2)/18) % 10)*224)) + -225)], 0.000000f)\n#                 }\n#               }\n#             }\n#             produce placeholder.shared {\n#               // attr [iter_var(threadIdx.z, , threadIdx.z)] thread_extent = 4\n#               // attr [iter_var(threadIdx.y, , threadIdx.y)] thread_extent = 1\n#               // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 16\n#               if (likely(((threadIdx.z*4) < (16 - (threadIdx.x/3))))) {\n#                 if (likely(((threadIdx.z*12) < (48 - threadIdx.x)))) {\n#                   if (likely((threadIdx.x < 12))) {\n#                     placeholder.shared[(((((threadIdx.z*4) + (threadIdx.x/3))*3) + (threadIdx.x % 3))*3)] = placeholder[(((((rc.outer + (threadIdx.z*12)) + ((threadIdx.x/3)*3))*3) + (threadIdx.x % 3))*3)]\n#                     placeholder.shared[((((((threadIdx.z*4) + (threadIdx.x/3))*3) + (threadIdx.x % 3))*3) + 1)] = placeholder[((((((rc.outer + (threadIdx.z*12)) + ((threadIdx.x/3)*3))*3) + (threadIdx.x % 3))*3) + 1)]\n#                     placeholder.shared[((((((threadIdx.z*4) + (threadIdx.x/3))*3) + (threadIdx.x % 3))*3) + 2)] = placeholder[((((((rc.outer + (threadIdx.z*12)) + ((threadIdx.x/3)*3))*3) + (threadIdx.x % 3))*3) + 2)]\n#                   }\n#                 }\n#               }\n#             }\n#             compute[0] = (compute[0] + (pad_temp.shared[threadIdx.x]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[(threadIdx.z*36)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[threadIdx.x]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 9)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[threadIdx.x]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 18)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[threadIdx.x]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 27)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 1)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 1)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 1)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 10)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 1)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 19)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 1)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 28)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 2)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 2)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 2)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 11)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 2)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 20)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 2)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 29)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 3)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 12)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 21)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 18)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 30)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 4)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 13)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 22)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 19)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 31)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 5)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 14)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 23)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 20)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 32)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 162)]*placeholder.shared[((threadIdx.z*36) + 6)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 162)]*placeholder.shared[((threadIdx.z*36) + 15)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 162)]*placeholder.shared[((threadIdx.z*36) + 24)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 36)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 54)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 72)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 90)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 108)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 126)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 144)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 162)]*placeholder.shared[((threadIdx.z*36) + 33)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 163)]*placeholder.shared[((threadIdx.z*36) + 7)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 163)]*placeholder.shared[((threadIdx.z*36) + 16)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 163)]*placeholder.shared[((threadIdx.z*36) + 25)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 37)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 55)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 73)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 91)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 109)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 127)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 145)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 163)]*placeholder.shared[((threadIdx.z*36) + 34)]))\n#             compute[0] = (compute[0] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[1] = (compute[1] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[2] = (compute[2] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[3] = (compute[3] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[4] = (compute[4] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[5] = (compute[5] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[6] = (compute[6] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[7] = (compute[7] + (pad_temp.shared[(threadIdx.x + 164)]*placeholder.shared[((threadIdx.z*36) + 8)]))\n#             compute[8] = (compute[8] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[9] = (compute[9] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[10] = (compute[10] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[11] = (compute[11] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[12] = (compute[12] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[13] = (compute[13] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[14] = (compute[14] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[15] = (compute[15] + (pad_temp.shared[(threadIdx.x + 164)]*placeholder.shared[((threadIdx.z*36) + 17)]))\n#             compute[16] = (compute[16] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[17] = (compute[17] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[18] = (compute[18] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[19] = (compute[19] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[20] = (compute[20] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[21] = (compute[21] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[22] = (compute[22] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[23] = (compute[23] + (pad_temp.shared[(threadIdx.x + 164)]*placeholder.shared[((threadIdx.z*36) + 26)]))\n#             compute[24] = (compute[24] + (pad_temp.shared[(threadIdx.x + 38)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[25] = (compute[25] + (pad_temp.shared[(threadIdx.x + 56)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[26] = (compute[26] + (pad_temp.shared[(threadIdx.x + 74)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[27] = (compute[27] + (pad_temp.shared[(threadIdx.x + 92)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[28] = (compute[28] + (pad_temp.shared[(threadIdx.x + 110)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[29] = (compute[29] + (pad_temp.shared[(threadIdx.x + 128)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[30] = (compute[30] + (pad_temp.shared[(threadIdx.x + 146)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#             compute[31] = (compute[31] + (pad_temp.shared[(threadIdx.x + 164)]*placeholder.shared[((threadIdx.z*36) + 35)]))\n#           }\n#         }\n#         tensor[(((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x)] = max(((compute[0]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 224)] = max(((compute[1]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 448)] = max(((compute[2]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 672)] = max(((compute[3]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 896)] = max(((compute[4]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 1120)] = max(((compute[5]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 1344)] = max(((compute[6]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 1568)] = max(((compute[7]*placeholder[(threadIdx.z*4)]) + placeholder[(threadIdx.z*4)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 50176)] = max(((compute[8]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 50400)] = max(((compute[9]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 50624)] = max(((compute[10]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 50848)] = max(((compute[11]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 51072)] = max(((compute[12]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 51296)] = max(((compute[13]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 51520)] = max(((compute[14]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 51744)] = max(((compute[15]*placeholder[((threadIdx.z*4) + 1)]) + placeholder[((threadIdx.z*4) + 1)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 100352)] = max(((compute[16]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 100576)] = max(((compute[17]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 100800)] = max(((compute[18]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 101024)] = max(((compute[19]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 101248)] = max(((compute[20]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 101472)] = max(((compute[21]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 101696)] = max(((compute[22]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 101920)] = max(((compute[23]*placeholder[((threadIdx.z*4) + 2)]) + placeholder[((threadIdx.z*4) + 2)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 150528)] = max(((compute[24]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 150752)] = max(((compute[25]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 150976)] = max(((compute[26]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 151200)] = max(((compute[27]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 151424)] = max(((compute[28]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 151648)] = max(((compute[29]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 151872)] = max(((compute[30]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#         tensor[((((((blockIdx.y*112) + blockIdx.x) + (threadIdx.z*12544))*16) + threadIdx.x) + 152096)] = max(((compute[31]*placeholder[((threadIdx.z*4) + 3)]) + placeholder[((threadIdx.z*4) + 3)]), 0.000000f)\n#       }\n\n######################################################################\n# Use cuDNN for a convolutional layer\n# -----------------------------------\n# We can use cuDNN to replace convolution kernels with cuDNN ones.\n# To do that, all we need to do is to append the option \" -libs=cudnn\" to the target string.\nnet, params = testing.create_workload(simple_net)\ntarget = \"cuda -libs=cudnn\"  # use cudnn for convolution\nlib = relay.build_module.build(net, target, params=params)\n\ndev = tvm.device(target, 0)\ndata = np.random.uniform(-1, 1, size=data_shape).astype(\"float32\")\nmodule = runtime.GraphModule(lib[\"default\"](dev))\nmodule.set_input(\"data\", data)\nmodule.run()\nout_shape = (batch_size, out_channels, 224, 224)\nout = module.get_output(0, tvm.nd.empty(out_shape))\nout_cudnn = out.numpy()\n\n######################################################################\n# Note that if you use cuDNN, Relay cannot fuse convolution with layers following it.\n# This is because layer fusion happens at the level of TVM internal representation(IR).\n# Relay treats external libraries as black box, so there is no way to fuse them with TVM IR.\n#\n# The pseudo code below shows that cuDNN convolution + bias add + batch norm + ReLU turned into two stages of computation, one for cuDNN call and the other for the rest of operations.\n#\n# .. code-block:: text\n#\n#      // attr [y] storage_scope = \"global\"\n#      allocate y[float32 * 802816]\n#      produce y {\n#        // attr [0] extern_scope = 0\n#        tvm_call_packed(\"tvm.contrib.cudnn.conv2d.forward\", 1, 0, 1, 1, 1, 1, 1, 1, 1, tvm_stack_make_array(placeholder, tvm_stack_make_shape(1, 3, 224, 224), 0, 4, 0.000000f, 0), tvm_stack_make_array(placeholder, tvm_stack_make_shape(16, 3, 3, 3), 0, 4, 0.000000f, 0), tvm_stack_make_array(y, tvm_stack_make_shape(1, 16, 224, 224), 0, 4, 0.000000f, 0))\n#      }\n#      produce tensor {\n#        // attr [iter_var(blockIdx.x, , blockIdx.x)] thread_extent = 256\n#        // attr [iter_var(threadIdx.x, , threadIdx.x)] thread_extent = 512\n#        for (ax0.ax1.fused.ax2.fused.ax3.fused.outer, 0, 7) {\n#          if (likely(((blockIdx.x*512) < ((802816 - (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072)) - threadIdx.x)))) {\n#            tensor[(((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/802816)*802816) + (((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/224) % 224)*224) + ((((blockIdx.x*64) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*32)) % 224))) + ((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/50176) % 16)*50176))] = max(((y[(((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/802816)*802816) + (((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/224) % 224)*224) + ((((blockIdx.x*64) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*32)) % 224))) + ((((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/50176) % 16)*50176))]*placeholder[(((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/50176) % 16)]) + placeholder[(((((blockIdx.x*512) + threadIdx.x) + (ax0.ax1.fused.ax2.fused.ax3.fused.outer*131072))/50176) % 16)]), 0.000000f)\n#          }\n#        }\n#      }\n\n\n######################################################################\n# Verify the result\n# -----------------\n# We can check that the results of two runs match.\n\ntvm.testing.assert_allclose(out_cuda, out_cudnn, rtol=1e-5)\n\n#####################################################################\n# Conclusion\n# ----------\n# This tutorial covered the usage of cuDNN with Relay.\n# We also have support for cuBLAS. If cuBLAS is enabled, it will be used inside a fully connected layer (relay.dense).\n# To use cuBLAS, set a target string as \"cuda -libs=cublas\".\n# You can use both cuDNN and cuBLAS with \"cuda -libs=cudnn,cublas\".\n#\n# For ROCm backend, we have support for MIOpen and rocBLAS.\n# They can be enabled with target \"rocm -libs=miopen,rocblas\".\n#\n# Being able to use external libraries is great, but we need to keep in mind some cautions.\n#\n# First, the use of external libraries may restrict your usage of TVM and Relay.\n# For example, MIOpen only supports NCHW layout and fp32 data type at the moment, so you cannot use other layouts or data type in TVM.\n#\n# Second, and more importantly, external libraries restrict the possibility of operator fusion during graph compilation, as shown above.\n# TVM and Relay aim to achieve the best performance on a variety of hardwares, with joint operator level and graph level optimization.\n# To achieve this goal, we should continue developing better optimizations for TVM and Relay, while using external libraries as a nice way to fall back to existing implementation when necessary.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_relay/using_pipeline_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nUsing Pipeline Executor in Relay\n=================================\n**Author**: `Hua Jiang <https://github.com/huajsj>`_\n\nThis is a short tutorial on how to use \"Pipeline Executor\" with Relay.\n\"\"\"\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import graph_executor as runtime\nfrom tvm.relay.op.contrib.cutlass import partition_for_cutlass\nfrom tvm import relay\nfrom tvm.relay import testing\nimport tvm.testing\nfrom tvm.contrib.cutlass import (\n    has_cutlass,\n    num_cutlass_partitions,\n    finalize_modules,\n    finalize_modules_vm,\n)\n\nimg_size = 8\n#######################################################################\n# Create a simple network, this network can be a pre-trained model too.\n# ---------------------------------------------------------------------\n# Let's create a very simple network for demonstration.\n# It consists of convolution, batch normalization, dense, and ReLU activation.\ndef get_network():\n    out_channels = 16\n    batch_size = 1\n    data = relay.var(\"data\", relay.TensorType((batch_size, 3, img_size, img_size), \"float16\"))\n    dense_weight = relay.var(\n        \"dweight\", relay.TensorType((batch_size, 16 * img_size * img_size), \"float16\")\n    )\n    weight = relay.var(\"weight\")\n    second_weight = relay.var(\"second_weight\")\n    bn_gamma = relay.var(\"bn_gamma\")\n    bn_beta = relay.var(\"bn_beta\")\n    bn_mmean = relay.var(\"bn_mean\")\n    bn_mvar = relay.var(\"bn_var\")\n    simple_net = relay.nn.conv2d(\n        data=data, weight=weight, kernel_size=(3, 3), channels=out_channels, padding=(1, 1)\n    )\n    simple_net = relay.nn.batch_norm(simple_net, bn_gamma, bn_beta, bn_mmean, bn_mvar)[0]\n    simple_net = relay.nn.relu(simple_net)\n    simple_net = relay.nn.batch_flatten(simple_net)\n    simple_net = relay.nn.dense(simple_net, dense_weight)\n    simple_net = relay.Function(relay.analysis.free_vars(simple_net), simple_net)\n    data_shape = (batch_size, 3, img_size, img_size)\n    net, params = testing.create_workload(simple_net)\n    return net, params, data_shape\n\n\nnet, params, data_shape = get_network()\n###########################################\n# Splitting the network into two subgraphs.\n# -----------------------------------------\n# This function called 'graph_split' from a unit test is just an example. User can create a customized logic\n# to split the graph.\nimport inspect\nimport os\n\ntutorial_dir = os.path.dirname(inspect.getfile(lambda: None))\nos.sys.path.append(os.path.join(tutorial_dir, \"../../../tests/python/relay\"))\nfrom test_pipeline_executor import graph_split\n\n###########################################\n# Splitting the network into two subgraphs.\nsplit_config = [{\"op_name\": \"nn.relu\", \"op_index\": 0}]\nsubgraphs = graph_split(net[\"main\"], split_config, params)\n###########################################################\n# The generated subgraphs should look something like below.\n\n\"\"\"\n#subgraphs[0])\n\n def @main(%data: Tensor[(1, 3, img_size, img_size), float16]) {\n  %0 = nn.conv2d(%data, meta[relay.Constant][0] /* ty=Tensor[(16, 3, 3, 3), float16] */, padding=[1, 1, 1, 1], channels=16, kernel_size=[3, 3]) /* ty=Tensor[(1, 16, img_size, img_size), float16] */;\n  %1 = nn.batch_norm(%0, meta[relay.Constant][1] /* ty=Tensor[(16), float16] */, meta[relay.Constant][2] /* ty=Tensor[(16), float16]*/, meta[relay.Constant][3] /* ty=Tensor[(16), float16] */, meta[relay.Constant][4] /* ty=Tensor[(16), float16] */) /* ty=(Tensor[(1,16, img_size, img_size), float16], Tensor[(16), float16], Tensor[(16), float16]) */;\n  %2 = %1.0;\n  nn.relu(%2) /* ty=Tensor[(1, 16, img_size, img_size), float16] */\n }\n\n#subgraphs[1]\n\n def @main(%data_n_0: Tensor[(1, 16, 8, 8), float16] /* ty=Tensor[(1, 16, 8, 8), float16] */) {\n  %0 = nn.batch_flatten(%data_n_0) /* ty=Tensor[(1, 1024), float16] */;\n  nn.dense(%0, meta[relay.Constant][0] /* ty=Tensor[(1, 1024), float16] */, units=None) /* ty=Tensor[(1, 1), float16] */\n }\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n#########################################\n# Build the subgraph with cutlass target.\n# ---------------------------------------\n\ncutlass = tvm.target.Target(\n    {\n        \"kind\": \"cutlass\",\n        \"sm\": int(tvm.target.Target(\"cuda\").arch.split(\"_\")[1]),\n        \"use_3xtf32\": True,\n        \"split_k_slices\": [1],\n        \"profile_all_alignments\": False,\n        \"find_first_valid\": True,\n        \"use_multiprocessing\": True,\n        \"use_fast_math\": False,\n        \"tmp_dir\": \"./tmp\",\n    },\n    host=tvm.target.Target(\"llvm\"),\n)\n\n\ndef cutlass_build(mod, target, params=None, target_host=None, mod_name=\"default\"):\n    target = [target, cutlass]\n    lib = relay.build_module.build(\n        mod, target=target, params=params, target_host=target_host, mod_name=mod_name\n    )\n    return lib\n\n\n###########################################################\n# Run the two subgraphs in pipeline with pipeline executor.\n# ---------------------------------------------------------\n# Set 'USE_PIPELINE_EXECUTOR' as ON, and set USE_CUTLASS' as ON  in cmake.\nfrom tvm.contrib import graph_executor, pipeline_executor, pipeline_executor_build\n\n#########################################\n# Create subgraph pipeline configuration.\n# Associate a subgraph module with a target.\n# Use CUTLASS BYOC to build the second subgraph module.\nmod0, mod1 = subgraphs[0], subgraphs[1]\n# Use cutlass as the codegen.\nmod1 = partition_for_cutlass(mod1)\n#################################################\n# Get the pipeline executor configuration object.\npipe_config = pipeline_executor_build.PipelineConfig()\n###########################################################################\n# Set the compile target of the subgraph module.\npipe_config[mod0].target = \"llvm\"\npipe_config[mod0].dev = tvm.cpu(0)\n##############################################################\n# Set the compile target of the second subgraph module as cuda.\npipe_config[mod1].target = \"cuda\"\npipe_config[mod1].dev = tvm.device(\"cuda\", 0)\npipe_config[mod1].build_func = cutlass_build\npipe_config[mod1].export_cc = \"nvcc\"\n# Create the pipeline by connecting the subgraph modules.\n# The global input will be forwarded to the input interface of the first module named mod0\npipe_config[\"input\"][\"data\"].connect(pipe_config[mod0][\"input\"][\"data\"])\n# The first output of mod0 will be forwarded to the input interface of mod1\npipe_config[mod0][\"output\"][0].connect(pipe_config[mod1][\"input\"][\"data_n_0\"])\n# The first output of mod1 will be the first global output.\npipe_config[mod1][\"output\"][0].connect(pipe_config[\"output\"][0])\n######################################\n# The pipeline configuration as below.\n\"\"\"\nprint(pipe_config)\n Inputs\n  |data: mod0:data\n\n output\n  |output(0) : mod1.output(0)\n\n connections\n  |mod0.output(0)-> mod1.data_n_0\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\n# testing.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n##############################\n# Build the pipeline executor.\n# ----------------------------\nwith tvm.transform.PassContext(opt_level=3):\n    pipeline_mod_factory = pipeline_executor_build.build(pipe_config)\n###############################################\n# Export the parameter configuration to a file.\ndirectory_path = tvm.contrib.utils.tempdir().temp_dir\nos.makedirs(directory_path, exist_ok=True)\nconfig_file_name = pipeline_mod_factory.export_library(directory_path)\n################################################################\n# Use the load function to create and initialize PipelineModule.\n# --------------------------------------------------------------\npipeline_module = pipeline_executor.PipelineModule.load_library(config_file_name)\n\n############################\n# Run the pipeline executor.\n# --------------------------\n# Allocate input data.\ndata = np.random.uniform(-1, 1, size=data_shape).astype(\"float16\")\npipeline_module.set_input(\"data\", tvm.nd.array(data))\n##########################################################################\n# Run the two subgraph in the pipeline mode to get the output asynchronously\n# or synchronously. In the following example, it is synchronous.\npipeline_module.run()\noutputs = pipeline_module.get_output()\n######################################\n# Use graph_executor for verification.\n# ------------------------------------\n# Run these two subgraphs in sequence with graph_executor to get the output.\ntarget = \"llvm\"\ndev0 = tvm.device(target, 0)\nlib0 = relay.build_module.build(mod0, target, params=params)\nmodule0 = runtime.GraphModule(lib0[\"default\"](dev0))\ncuda = tvm.target.Target(\"cuda\", host=tvm.target.Target(\"llvm\"))\nlib1 = relay.build_module.build(mod1, [cuda, cutlass], params=params)\nlib1 = finalize_modules(lib1, \"compile.so\", \"./tmp\")\n\ndev1 = tvm.device(\"cuda\", 0)\n\nmodule1 = runtime.GraphModule(lib1[\"default\"](dev1))\n\nmodule0.set_input(\"data\", data)\nmodule0.run()\nout_shape = (1, 16, img_size, img_size)\nout = module0.get_output(0, tvm.nd.empty(out_shape, \"float16\"))\nmodule1.set_input(\"data_n_0\", out)\nmodule1.run()\nout_shape = (1, 1)\nout = module1.get_output(0, tvm.nd.empty(out_shape, \"float16\"))\n####################\n# Verify the result.\ntvm.testing.assert_allclose(outputs[0].numpy(), out.numpy())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_relay/using_relay_viz.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long\n\"\"\"\nUse Relay Visualizer to Visualize Relay\n============================================================\n**Author**: `Chi-Wei Wang <https://github.com/chiwwang>`_\n\nRelay IR module can contain lots of operations. Although an individual\noperation is usually easy to understand, putting them together can cause\na complicated, hard-to-read graph. Things can get even worse with optimization-passes\ncoming into play.\n\nThis utility visualizes an IR module as nodes and edges. It defines a set of interfaces including\nparser, plotter(renderer), graph, node, and edges.\nA default parser is provided. Users can implement their own renderers to render the graph.\n\nHere we use a renderer rendering graph in the text-form.\nIt is a lightweight, AST-like visualizer, inspired by `clang ast-dump <https://clang.llvm.org/docs/IntroductionToTheClangAST.html>`_.\nWe will introduce how to implement customized parsers and renderers through interface classes.\n\nFor more details, please refer to :py:mod:`tvm.contrib.relay_viz`.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nfrom typing import (\n    Dict,\n    Union,\n    Tuple,\n    List,\n)\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib import relay_viz\nfrom tvm.contrib.relay_viz.interface import (\n    VizEdge,\n    VizNode,\n    VizParser,\n)\nfrom tvm.contrib.relay_viz.terminal import (\n    TermGraph,\n    TermPlotter,\n    TermVizParser,\n)\n\n######################################################################\n# Define a Relay IR Module with multiple GlobalVar\n# ------------------------------------------------\n# Let's build an example Relay IR Module containing multiple ``GlobalVar``.\n# We define an ``add`` function and call it in the main function.\ndata = relay.var(\"data\")\nbias = relay.var(\"bias\")\nadd_op = relay.add(data, bias)\nadd_func = relay.Function([data, bias], add_op)\nadd_gvar = relay.GlobalVar(\"AddFunc\")\n\ninput0 = relay.var(\"input0\")\ninput1 = relay.var(\"input1\")\ninput2 = relay.var(\"input2\")\nadd_01 = relay.Call(add_gvar, [input0, input1])\nadd_012 = relay.Call(add_gvar, [input2, add_01])\nmain_func = relay.Function([input0, input1, input2], add_012)\nmain_gvar = relay.GlobalVar(\"main\")\n\nmod = tvm.IRModule({main_gvar: main_func, add_gvar: add_func})\n\n######################################################################\n# Render the graph with Relay Visualizer on the terminal\n# ------------------------------------------------------\n# The terminal can show a Relay IR module in text similar to clang AST-dump.\n# We should see ``main`` and ``AddFunc`` function. ``AddFunc`` is called twice in the ``main`` function.\nviz = relay_viz.RelayVisualizer(mod)\nviz.render()\n\n######################################################################\n# Customize Parser for Interested Relay Types\n# -------------------------------------------\n# Sometimes we want to emphasize interested information, or parse things differently for a specific usage.\n# It is possible to provide customized parsers as long as it obeys the interface.\n# Here demonstrate how to customize parsers for ``relay.var``.\n# We need to implement abstract interface :py:class:`tvm.contrib.relay_viz.interface.VizParser`.\nclass YourAwesomeParser(VizParser):\n    def __init__(self):\n        self._delegate = TermVizParser()\n\n    def get_node_edges(\n        self,\n        node: relay.Expr,\n        relay_param: Dict[str, tvm.runtime.NDArray],\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n\n        if isinstance(node, relay.Var):\n            node = VizNode(node_to_id[node], \"AwesomeVar\", f\"name_hint {node.name_hint}\")\n            # no edge is introduced. So return an empty list.\n            return node, []\n\n        # delegate other types to the other parser.\n        return self._delegate.get_node_edges(node, relay_param, node_to_id)\n\n\n######################################################################\n# Pass the parser and an interested renderer to visualizer.\n# Here we just the terminal renderer.\nviz = relay_viz.RelayVisualizer(mod, {}, TermPlotter(), YourAwesomeParser())\nviz.render()\n\n######################################################################\n# Customization around Graph and Plotter\n# -------------------------------------------\n# Besides parsers, we can also customize graph and renderers by implementing\n# abstract class :py:class:`tvm.contrib.relay_viz.interface.VizGraph` and\n# :py:class:`tvm.contrib.relay_viz.interface.Plotter`.\n# Here we override the ``TermGraph`` defined in ``terminal.py`` for easier demo.\n# We add a hook duplicating above ``AwesomeVar``, and make ``TermPlotter`` use the new class.\nclass AwesomeGraph(TermGraph):\n    def node(self, viz_node):\n        # add the node first\n        super().node(viz_node)\n        # if it's AwesomeVar, duplicate it.\n        if viz_node.type_name == \"AwesomeVar\":\n            duplicated_id = f\"duplicated_{viz_node.identity}\"\n            duplicated_type = \"double AwesomeVar\"\n            super().node(VizNode(duplicated_id, duplicated_type, \"\"))\n            # connect the duplicated var to the original one\n            super().edge(VizEdge(duplicated_id, viz_node.identity))\n\n\n# override TermPlotter to use `AwesomeGraph` instead\nclass AwesomePlotter(TermPlotter):\n    def create_graph(self, name):\n        self._name_to_graph[name] = AwesomeGraph(name)\n        return self._name_to_graph[name]\n\n\nviz = relay_viz.RelayVisualizer(mod, {}, AwesomePlotter(), YourAwesomeParser())\nviz.render()\n\n######################################################################\n# Summary\n# -------\n# This tutorial demonstrates the usage of Relay Visualizer and customization.\n# The class :py:class:`tvm.contrib.relay_viz.RelayVisualizer` is composed of interfaces\n# defined in ``interface.py``.\n#\n# It is aimed for quick look-then-fix iterations.\n# The constructor arguments are intended to be simple, while the customization is still\n# possible through a set of interface classes.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/extern_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nExternal Tensor Functions\n=========================\n**Author**: `Tianqi Chen <https://tqchen.github.io>`_\n\nWhile TVM supports transparent code generation, sometimes\nit is also helpful to incorporate manual written code into\nthe pipeline. For example, we might want to use cuDNN for\nsome of the convolution kernels and define the rest of the stages.\n\nTVM supports these black box function calls natively.\nSpecifically, TVM support all the tensor functions that are DLPack compatible.\nWhich means we can call any function with POD types(pointer, int, float)\nor pointer to DLTensor as argument.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import cblas\nimport tvm.testing\n\nif not tvm.get_global_func(\"tvm.contrib.cblas.matmul\", allow_missing=True):\n    raise Exception(\"Not compiled with cblas support; can't build this tutorial\")\n\n######################################################################\n# Use Extern Tensor Function\n# --------------------------\n# In the example below, we use :any:`te.extern` to add an extern\n# array function call. In the extern call, we declare the shape\n# of output tensors. In the second argument we provide the list of inputs.\n#\n# User will need to provide a function describing how to compute the result.\n# The compute function takes list of symbolic placeholder for the inputs,\n# list of symbolic placeholder for the outputs and returns the executing statement.\n#\n# In this case we simply call a registered TVM function, which invokes a CBLAS call.\n# TVM does not control internal of the extern array function and treats it as black-box.\n# We can further mix schedulable TVM calls that add a bias term to the result.\n#\nn = 1024\nl = 128\nm = 235\nbias = te.var(\"bias\", dtype=\"float32\")\nA = te.placeholder((n, l), name=\"A\")\nB = te.placeholder((l, m), name=\"B\")\nC = te.extern(\n    (n, m),\n    [A, B],\n    lambda ins, outs: tvm.tir.call_packed(\n        \"tvm.contrib.cblas.matmul\", ins[0], ins[1], outs[0], False, False\n    ),\n    name=\"C\",\n)\nD = te.compute(C.shape, lambda i, j: C[i, j] + bias, name=\"D\")\ns = te.create_schedule(D.op)\n\n######################################################################\n# Verify the Result\n# -----------------\n# We can verify that the result matches what we expected.\n#\ndev = tvm.cpu(0)\nf = tvm.build(s, [A, B, D, bias], \"llvm\")\na = tvm.nd.array(np.random.uniform(size=(n, l)).astype(A.dtype), dev)\nb = tvm.nd.array(np.random.uniform(size=(l, m)).astype(B.dtype), dev)\nd = tvm.nd.array(np.zeros((n, m), dtype=D.dtype), dev)\nbb = 10.0\nf(a, b, d, bb)\ntvm.testing.assert_allclose(d.numpy(), np.dot(a.numpy(), b.numpy()) + 10, rtol=1e-5)\n\n######################################################################\n# Extern Contrib Wrappers\n# -----------------------\n# TVM also provide extern contrib wrappers to useful extern calls,\n# the following line is equivalent to the previous example.\n#\nfrom tvm.contrib import cblas\n\nC = cblas.matmul(A, B)\nD = te.compute(C.shape, lambda i, j: C[i, j] + bias, name=\"D\")\ns = te.create_schedule(D.op)\n\n######################################################################\n# Hook Python Function as Extern\n# ------------------------------\n# Since we can call into any PackedFunc in TVM. We can use the extern\n# function to callback into python.\n#\n# The following example registers a python function into TVM runtime system\n# and use it to complete one stage of the computation.\n# This makes TVM much more flexible. For example, we can insert front-end\n# callbacks to inspect the intermediate results or mix customized code\n# with TVM.\n#\n@tvm.register_func(\"tvm.contrib.my_tvm_addone\")\ndef my_tvm_addone(x, y):\n    print(\"my_tvm_addone signatures: %s, %s\" % (type(x), type(y)))\n    tvm.nd.array(x.numpy() + 1).copyto(y)\n\n\nA = te.placeholder((n,), name=\"A\")\nB = te.extern(\n    A.shape,\n    [A],\n    lambda ins, outs: tvm.tir.call_packed(\"tvm.contrib.my_tvm_addone\", ins[0], outs[0]),\n    name=\"C\",\n)\ns = te.create_schedule(B.op)\nf = tvm.build(s, [A, B], \"llvm\")\na = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev)\nb = tvm.nd.array(np.random.uniform(size=(n,)).astype(B.dtype), dev)\nf(a, b)\ntvm.testing.assert_allclose(b.numpy(), a.numpy() + 1, rtol=1e-5)\n\n######################################################################\n# Summary\n# -------\n# - TVM calls extern tensor function via :any:`te.extern`\n# - Use contrib wrappers for short sugars of extern tensor calls.\n# - We can hook front-end function as extern tensor callbacks.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/intrin_math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nIntrinsics and Math Functions\n=============================\n**Author**: `Tianqi Chen <https://tqchen.github.io>`_\n\nWhile TVM supports basic arithmetic operations. In many cases\nusually we will need more complicated builtin functions.\nFor example :code:`exp` to take the exponential of the function.\n\nThese functions are target system dependent and may have different\nnames of different target platforms. In this tutorial, we will learn\nhow we can invoke these target specific functions, and how we can unify\nthe interface via TVM's intrinsic API.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignoreimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.ir import register_op_attr, register_intrin_lowering\n\n######################################################################\n# Direct Declare Extern Math Call\n# -------------------------------\n# The most straight-forward way to call target specific function is via\n# extern function call construct in tvm.\n# In the following example, we use :any:`tvm.tir.call_pure_extern` to call\n# :code:`__expf` function, which is only available under CUDA.\n#\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.compute(A.shape, lambda i: tvm.tir.call_pure_extern(\"float32\", \"__expf\", A[i]), name=\"B\")\ns = te.create_schedule(B.op)\nnum_thread = 64\nbx, tx = s[B].split(B.op.axis[0], factor=num_thread)\ns[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\nf = tvm.build(s, [A, B], \"cuda\", name=\"myexp\")\nprint(f.imported_modules[0].get_source())\n\n######################################################################\n# Unified Intrinsic Call\n# ----------------------\n# The above code verifies that direct external call can be used to\n# call into device specific functions.\n# However, the above way only works for CUDA target with float type.\n# Ideally, we want to write same code for any device and any data type.\n#\n# TVM intrinsic provides the user a mechanism to achieve this, and this\n# is the recommended way to solve the problem.\n# The following code use te.exp instead, which create an intrinsic call\n# :py::func:`tvm.te.exp` to do the exponential.\n#\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.compute(A.shape, lambda i: te.exp(A[i]), name=\"B\")\ns = te.create_schedule(B.op)\nnum_thread = 64\nbx, tx = s[B].split(B.op.axis[0], factor=num_thread)\ns[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\nfcuda = tvm.build(s, [A, B], \"cuda\", name=\"myexp\")\nprint(fcuda.imported_modules[0].get_source())\n######################################################################\n# We can find that the code works for both CUDA and opencl.\n# The same te.exp can also be used for float64 data types.\n#\nfopencl = tvm.build(s, [A, B], \"opencl\", name=\"myexp\")\nprint(fopencl.imported_modules[0].get_source())\n\n######################################################################\n# Intrinsic Lowering Rule\n# -----------------------\n# When :py:func:`tvm.te.exp` is called, TVM creates an intrinsic Call Expr.\n# TVM uses transformation rules to transform the intrinsic\n# call to device specific extern calls.\n#\n# TVM also allows user to customize the rules during runtime.\n# The following example customizes CUDA lowering rule for :code:`exp`.\n#\n\n\ndef my_cuda_math_rule(op):\n    \"\"\"Customized CUDA intrinsic lowering rule\"\"\"\n    assert isinstance(op, tvm.tir.Call)\n    name = op.op.name\n    assert name.startswith(\"tir.\")\n    dispatch_name = name[4:]\n    if op.dtype == \"float32\":\n        # call float function\n        return tvm.tir.call_pure_extern(\"float32\", \"%sf\" % dispatch_name, op.args[0])\n    elif op.dtype == \"float64\":\n        # call double function\n        return tvm.tir.call_pure_extern(\"float32\", dispatch_name, op.args[0])\n    else:\n        # cannot do translation, return self.\n        return op\n\n\nregister_intrin_lowering(\"tir.exp\", target=\"cuda\", f=my_cuda_math_rule, level=99)\n######################################################################\n# Register the rule to TVM with override option to override existing rule.\n# Notice the difference between the printed code from previous one:\n# our new rule uses math function :code:`expf` instead of\n# fast math version :code:`__expf`.\n#\nfcuda = tvm.build(s, [A, B], \"cuda\", name=\"myexp\")\nprint(fcuda.imported_modules[0].get_source())\n\n######################################################################\n# Add Your Own Intrinsic\n# ----------------------\n# If there is an intrinsic that is not provided by TVM.\n# User can easily add new intrinsic by using the intrinsic rule system.\n# The following example add an intrinsic :code:`mylog` to the system.\n#\n\n\ndef mylog(x):\n    \"\"\"customized log intrinsic function\"\"\"\n    return tvm.tir.call_intrin(x.dtype, \"tir.mylog\", x)\n\n\ndef my_cuda_mylog_rule(op):\n    \"\"\"CUDA lowering rule for log\"\"\"\n    if op.dtype == \"float32\":\n        return tvm.tir.call_pure_extern(\"float32\", \"logf\", op.args[0])\n    elif op.dtype == \"float64\":\n        return tvm.tir.call_pure_extern(\"float64\", \"log\", op.args[0])\n    else:\n        return op\n\n\n# new op registration is triggered by registering an attribute of the op\nregister_op_attr(\"tir.mylog\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Pure)\nregister_intrin_lowering(\"tir.mylog\", target=\"cuda\", f=my_cuda_mylog_rule, level=99)\n\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.compute(A.shape, lambda i: mylog(A[i]), name=\"B\")\ns = te.create_schedule(B.op)\nnum_thread = 64\nbx, tx = s[B].split(B.op.axis[0], factor=num_thread)\ns[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\nfcuda = tvm.build(s, [A, B], \"cuda\", name=\"mylog\")\nprint(fcuda.imported_modules[0].get_source())\n\n######################################################################\n# Summary\n# -------\n# - TVM can call extern target dependent math function.\n# - Use intrinsic to defined a unified interface for the functions.\n# - For more intrinsics available in tvm, take a look at :any:`tvm.tir`\n# - You can customize the intrinsic behavior by defining your own rules.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nReduction\n=========\n**Author**: `Tianqi Chen <https://tqchen.github.io>`_\n\nThis is an introduction material on how to do reduction in TVM.\nAssociative reduction operators like sum/max/min are typical\nconstruction blocks of linear algebra operations.\n\nIn this tutorial, we will demonstrate how to do reduction in TVM.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n######################################################################\n# Describe Sum of Rows\n# --------------------\n# Assume we want to compute sum of rows as our example.\n# In numpy semantics this can be written as :code:`B = numpy.sum(A, axis=1)`\n#\n# The following lines describe the row sum operation.\n# To create a reduction formula, we declare a reduction axis using\n# :any:`te.reduce_axis`. :any:`te.reduce_axis` takes in the range of reductions.\n# :any:`te.sum` takes in the expression to be reduced as well as the reduction\n# axis and compute the sum of value over all k in the declared range.\n#\n# The equivalent C code is as follows:\n#\n# .. code-block:: c\n#\n#   for (int i = 0; i < n; ++i) {\n#     B[i] = 0;\n#     for (int k = 0; k < m; ++k) {\n#       B[i] = B[i] + A[i][k];\n#     }\n#   }\n#\nn = te.var(\"n\")\nm = te.var(\"m\")\nA = te.placeholder((n, m), name=\"A\")\nk = te.reduce_axis((0, m), \"k\")\nB = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n\n######################################################################\n# Schedule the Reduction\n# ----------------------\n# There are several ways to schedule a reduction.\n# Before doing anything, let us print out the IR code of default schedule.\n#\ns = te.create_schedule(B.op)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# You can find that the IR code is quite like the C code.\n# The reduction axis is similar to a normal axis, it can be splitted.\n#\n# In the following code we split both the row axis of B as well\n# axis by different factors. The result is a nested reduction.\n#\nko, ki = s[B].split(B.op.reduce_axis[0], factor=16)\nxo, xi = s[B].split(B.op.axis[0], factor=32)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# If we are building a GPU kernel, we can bind the rows of B to GPU threads.\ns[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# Reduction Factoring and Parallelization\n# ---------------------------------------\n# One problem of building a reduction is that we cannot simply\n# parallelize over the reduction axis. We need to divide the computation\n# of the reduction, store the local reduction result in a temporal array\n# before doing a reduction over the temp array.\n#\n# The rfactor primitive does such rewrite of the computation.\n# In the following schedule, the result of B is written to a temporary\n# result B.rf. The factored dimension becomes the first dimension of B.rf.\n#\ns = te.create_schedule(B.op)\nko, ki = s[B].split(B.op.reduce_axis[0], factor=16)\nBF = s.rfactor(B, ki)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# The scheduled operator of B also get rewritten to be sum over\n# the first axis of reduced result of B.f\n#\nprint(s[B].op.body)\n\n######################################################################\n# Cross Thread Reduction\n# ----------------------\n# We can now parallelize over the factored axis.\n# Here the reduction axis of B is marked to be a thread.\n# TVM allows reduction axis to be marked as thread if it is the only\n# axis in reduction and cross thread reduction is possible in the device.\n#\n# This is indeed the case after the factoring.\n# We can directly compute BF at the reduction axis as well.\n# The final generated kernel will divide the rows by blockIdx.x and threadIdx.y\n# columns by threadIdx.x and finally do a cross thread reduction over threadIdx.x\n#\nxo, xi = s[B].split(s[B].op.axis[0], factor=32)\ns[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(xi, te.thread_axis(\"threadIdx.y\"))\ntx = te.thread_axis(\"threadIdx.x\")\ns[B].bind(s[B].op.reduce_axis[0], tx)\ns[BF].compute_at(s[B], s[B].op.reduce_axis[0])\ns[B].set_store_predicate(tx.var.equal(0))\nfcuda = tvm.build(s, [A, B], \"cuda\")\nprint(fcuda.imported_modules[0].get_source())\n\n######################################################################\n# Verify the correctness of result kernel by comparing it to numpy.\n#\nnn = 128\ndev = tvm.cuda(0)\na = tvm.nd.array(np.random.uniform(size=(nn, nn)).astype(A.dtype), dev)\nb = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev)\nfcuda(a, b)\ntvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=1), rtol=1e-4)\n\n######################################################################\n# Describe Convolution via 2D Reduction\n# -------------------------------------\n# In TVM, we can describe convolution via 2D reduction in a simple way.\n# Here is an example for 2D convolution with filter size = [3, 3] and strides = [1, 1].\n#\nn = te.var(\"n\")\nInput = te.placeholder((n, n), name=\"Input\")\nFilter = te.placeholder((3, 3), name=\"Filter\")\ndi = te.reduce_axis((0, 3), name=\"di\")\ndj = te.reduce_axis((0, 3), name=\"dj\")\nOutput = te.compute(\n    (n - 2, n - 2),\n    lambda i, j: te.sum(Input[i + di, j + dj] * Filter[di, dj], axis=[di, dj]),\n    name=\"Output\",\n)\ns = te.create_schedule(Output.op)\nprint(tvm.lower(s, [Input, Filter, Output], simple_mode=True))\n\n######################################################################\n# .. _general-reduction:\n#\n# Define General Commutative Reduction Operation\n# ----------------------------------------------\n# Besides the built-in reduction operations like :any:`te.sum`,\n# :any:`tvm.te.min` and :any:`tvm.te.max`, you can also define your\n# commutative reduction operation by :any:`te.comm_reducer`.\n#\n\nn = te.var(\"n\")\nm = te.var(\"m\")\nproduct = te.comm_reducer(lambda x, y: x * y, lambda t: tvm.tir.const(1, dtype=t), name=\"product\")\nA = te.placeholder((n, m), name=\"A\")\nk = te.reduce_axis((0, m), name=\"k\")\nB = te.compute((n,), lambda i: product(A[i, k], axis=k), name=\"B\")\n\n######################################################################\n# .. note::\n#\n#   Sometimes we would like to perform reduction that involves multiple\n#   values like :code:`argmax`, which can be done by tuple inputs.\n#   See :ref:`reduction-with-tuple-inputs` for more detail.\n\n######################################################################\n# Summary\n# -------\n# This tutorial provides a walk through of reduction schedule.\n#\n# - Describe reduction with reduce_axis.\n# - Use rfactor to factor out axis if we need parallelism.\n# - Define new reduction operation by :any:`te.comm_reducer`\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/scan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nScan and Recurrent Kernel\n=========================\n**Author**: `Tianqi Chen <https://tqchen.github.io>`_\n\nThis is an introduction material on how to do recurrent computing in TVM.\nRecurrent computing is a typical pattern in neural networks.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n######################################################################\n# TVM supports a scan operator to describe symbolic loop.\n# The following scan op computes cumsum over columns of X.\n#\n# The scan is carried over the highest dimension of the tensor.\n# :code:`s_state` is a placeholder that describes the transition state of the scan.\n# :code:`s_init` describes how we can initialize the first k timesteps.\n# Here since s_init's first dimension is 1, it describes how we initialize\n# The state at first timestep.\n#\n# :code:`s_update` describes how to update the value at timestep t. The update\n# value can refer back to the values of previous timestep via state placeholder.\n# Note that while it is invalid to refer to :code:`s_state` at current or later timestep.\n#\n# The scan takes in state placeholder, initial value and update description.\n# It is also recommended(although not necessary) to list the inputs to the scan cell.\n# The result of the scan is a tensor, giving the result of :code:`s_state` after the\n# update over the time domain.\n#\nm = te.var(\"m\")\nn = te.var(\"n\")\nX = te.placeholder((m, n), name=\"X\")\ns_state = te.placeholder((m, n))\ns_init = te.compute((1, n), lambda _, i: X[0, i])\ns_update = te.compute((m, n), lambda t, i: s_state[t - 1, i] + X[t, i])\ns_scan = tvm.te.scan(s_init, s_update, s_state, inputs=[X])\n\n######################################################################\n# Schedule the Scan Cell\n# ----------------------\n# We can schedule the body of the scan by scheduling the update and\n# init part separately. Note that it is invalid to schedule the\n# first iteration dimension of the update part.\n# To split on the time iteration, user can schedule on scan_op.scan_axis instead.\n#\ns = te.create_schedule(s_scan.op)\nnum_thread = 256\nblock_x = te.thread_axis(\"blockIdx.x\")\nthread_x = te.thread_axis(\"threadIdx.x\")\nxo, xi = s[s_init].split(s_init.op.axis[1], factor=num_thread)\ns[s_init].bind(xo, block_x)\ns[s_init].bind(xi, thread_x)\nxo, xi = s[s_update].split(s_update.op.axis[1], factor=num_thread)\ns[s_update].bind(xo, block_x)\ns[s_update].bind(xi, thread_x)\nprint(tvm.lower(s, [X, s_scan], simple_mode=True))\n\n######################################################################\n# Build and Verify\n# ----------------\n# We can build the scan kernel like other TVM kernels, here we use\n# numpy to verify the correctness of the result.\n#\nfscan = tvm.build(s, [X, s_scan], \"cuda\", name=\"myscan\")\ndev = tvm.cuda(0)\nn = 1024\nm = 10\na_np = np.random.uniform(size=(m, n)).astype(s_scan.dtype)\na = tvm.nd.array(a_np, dev)\nb = tvm.nd.array(np.zeros((m, n), dtype=s_scan.dtype), dev)\nfscan(a, b)\ntvm.testing.assert_allclose(b.numpy(), np.cumsum(a_np, axis=0))\n\n######################################################################\n# Multi-Stage Scan Cell\n# ---------------------\n# In the above example we described the scan cell using one Tensor\n# computation stage in s_update. It is possible to use multiple\n# Tensor stages in the scan cell.\n#\n# The following lines demonstrate a scan with two stage operations\n# in the scan cell.\n#\nm = te.var(\"m\")\nn = te.var(\"n\")\nX = te.placeholder((m, n), name=\"X\")\ns_state = te.placeholder((m, n))\ns_init = te.compute((1, n), lambda _, i: X[0, i])\ns_update_s1 = te.compute((m, n), lambda t, i: s_state[t - 1, i] * 2, name=\"s1\")\ns_update_s2 = te.compute((m, n), lambda t, i: s_update_s1[t, i] + X[t, i], name=\"s2\")\ns_scan = tvm.te.scan(s_init, s_update_s2, s_state, inputs=[X])\n\n######################################################################\n# These intermediate tensors can also be scheduled normally.\n# To ensure correctness, TVM creates a group constraint to forbid\n# the body of scan to be compute_at locations outside the scan loop.\n#\ns = te.create_schedule(s_scan.op)\nxo, xi = s[s_update_s2].split(s_update_s2.op.axis[1], factor=32)\ns[s_update_s1].compute_at(s[s_update_s2], xo)\nprint(tvm.lower(s, [X, s_scan], simple_mode=True))\n\n######################################################################\n# Multiple States\n# ---------------\n# For complicated applications like RNN, we might need more than one\n# recurrent state. Scan support multiple recurrent states.\n# The following example demonstrates how we can build recurrence with two states.\n#\nm = te.var(\"m\")\nn = te.var(\"n\")\nl = te.var(\"l\")\nX = te.placeholder((m, n), name=\"X\")\ns_state1 = te.placeholder((m, n))\ns_state2 = te.placeholder((m, l))\ns_init1 = te.compute((1, n), lambda _, i: X[0, i])\ns_init2 = te.compute((1, l), lambda _, i: 0.0)\ns_update1 = te.compute((m, n), lambda t, i: s_state1[t - 1, i] + X[t, i])\ns_update2 = te.compute((m, l), lambda t, i: s_state2[t - 1, i] + s_state1[t - 1, 0])\ns_scan1, s_scan2 = tvm.te.scan(\n    [s_init1, s_init2], [s_update1, s_update2], [s_state1, s_state2], inputs=[X]\n)\ns = te.create_schedule(s_scan1.op)\nprint(tvm.lower(s, [X, s_scan1, s_scan2], simple_mode=True))\n\n######################################################################\n# Summary\n# -------\n# This tutorial provides a walk through of scan primitive.\n#\n# - Describe scan with init and update.\n# - Schedule the scan cells as normal schedule.\n# - For complicated workload, use multiple states and steps in scan cell.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/schedule_primitives.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _schedule_primitives:\n\nSchedule Primitives in TVM\n==========================\n**Author**: `Ziheng Jiang <https://github.com/ZihengJiang>`_\n\nTVM is a domain specific language for efficient kernel construction.\n\nIn this tutorial, we will show you how to schedule the computation by\nvarious primitives provided by TVM.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n######################################################################\n#\n# There often exist several methods to compute the same result,\n# however, different methods will result in different locality and\n# performance. So TVM asks user to provide how to execute the\n# computation called **Schedule**.\n#\n# A **Schedule** is a set of transformation of computation that\n# transforms the loop of computations in the program.\n#\n\n# declare some variables for use later\nn = te.var(\"n\")\nm = te.var(\"m\")\n\n######################################################################\n# A schedule can be created from a list of ops, by default the\n# schedule computes tensor in a serial manner in a row-major order.\n\n# declare a matrix element-wise multiply\nA = te.placeholder((m, n), name=\"A\")\nB = te.placeholder((m, n), name=\"B\")\nC = te.compute((m, n), lambda i, j: A[i, j] * B[i, j], name=\"C\")\n\ns = te.create_schedule([C.op])\n# lower will transform the computation from definition to the real\n# callable function. With argument `simple_mode=True`, it will\n# return you a readable C like statement, we use it here to print the\n# schedule result.\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# One schedule is composed by multiple stages, and one\n# **Stage** represents schedule for one operation. We provide various\n# methods to schedule every stage.\n\n######################################################################\n# split\n# -----\n# :code:`split` can split a specified axis into two axes by\n# :code:`factor`.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i] * 2, name=\"B\")\n\ns = te.create_schedule(B.op)\nxo, xi = s[B].split(B.op.axis[0], factor=32)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# You can also split a axis by :code:`nparts`, which splits the axis\n# contrary with :code:`factor`.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i], name=\"B\")\n\ns = te.create_schedule(B.op)\nbx, tx = s[B].split(B.op.axis[0], nparts=32)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# tile\n# ----\n# :code:`tile` help you execute the computation tile by tile over two\n# axes.\nA = te.placeholder((m, n), name=\"A\")\nB = te.compute((m, n), lambda i, j: A[i, j], name=\"B\")\n\ns = te.create_schedule(B.op)\nxo, yo, xi, yi = s[B].tile(B.op.axis[0], B.op.axis[1], x_factor=10, y_factor=5)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# fuse\n# ----\n# :code:`fuse` can fuse two consecutive axes of one computation.\nA = te.placeholder((m, n), name=\"A\")\nB = te.compute((m, n), lambda i, j: A[i, j], name=\"B\")\n\ns = te.create_schedule(B.op)\n# tile to four axes first: (i.outer, j.outer, i.inner, j.inner)\nxo, yo, xi, yi = s[B].tile(B.op.axis[0], B.op.axis[1], x_factor=10, y_factor=5)\n# then fuse (i.inner, j.inner) into one axis: (i.inner.j.inner.fused)\nfused = s[B].fuse(xi, yi)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# reorder\n# -------\n# :code:`reorder` can reorder the axes in the specified order.\nA = te.placeholder((m, n), name=\"A\")\nB = te.compute((m, n), lambda i, j: A[i, j], name=\"B\")\n\ns = te.create_schedule(B.op)\n# tile to four axes first: (i.outer, j.outer, i.inner, j.inner)\nxo, yo, xi, yi = s[B].tile(B.op.axis[0], B.op.axis[1], x_factor=10, y_factor=5)\n# then reorder the axes: (i.inner, j.outer, i.outer, j.inner)\ns[B].reorder(xi, yo, xo, yi)\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# bind\n# ----\n# :code:`bind` can bind a specified axis with a thread axis, often used\n# in gpu programming.\nA = te.placeholder((n,), name=\"A\")\nB = te.compute(A.shape, lambda i: A[i] * 2, name=\"B\")\n\ns = te.create_schedule(B.op)\nbx, tx = s[B].split(B.op.axis[0], factor=64)\ns[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\ns[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\nprint(tvm.lower(s, [A, B], simple_mode=True))\n\n######################################################################\n# compute_at\n# ----------\n# For a schedule that consists of multiple operators, TVM will compute\n# tensors at the root separately by default.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\nC = te.compute((m,), lambda i: B[i] * 2, name=\"C\")\n\ns = te.create_schedule(C.op)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# :code:`compute_at` can move computation of `B` into the first axis\n# of computation of `C`.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\nC = te.compute((m,), lambda i: B[i] * 2, name=\"C\")\n\ns = te.create_schedule(C.op)\ns[B].compute_at(s[C], C.op.axis[0])\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# compute_inline\n# --------------\n# :code:`compute_inline` can mark one stage as inline, then the body of\n# computation will be expanded and inserted at the address where the\n# tensor is required.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\nC = te.compute((m,), lambda i: B[i] * 2, name=\"C\")\n\ns = te.create_schedule(C.op)\ns[B].compute_inline()\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# compute_root\n# ------------\n# :code:`compute_root` can move computation of one stage to the root.\nA = te.placeholder((m,), name=\"A\")\nB = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\nC = te.compute((m,), lambda i: B[i] * 2, name=\"C\")\n\ns = te.create_schedule(C.op)\ns[B].compute_at(s[C], C.op.axis[0])\ns[B].compute_root()\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Summary\n# -------\n# This tutorial provides an introduction to schedule primitives in\n# tvm, which permits users schedule the computation easily and\n# flexibly.\n#\n# In order to get a good performance kernel implementation, the\n# general workflow often is:\n#\n# - Describe your computation via series of operations.\n# - Try to schedule the computation with primitives.\n# - Compile and run to see the performance difference.\n# - Adjust your schedule according the running result.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/tedd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nUse Tensor Expression Debug Display (TEDD) for Visualization\n============================================================\n**Author**: `Yongfeng Gu <https://github.com/yongfeng-nv>`_\n\nThis is an introduction about using TEDD to visualize tensor expressions.\n\nTensor Expressions are scheduled with primitives.  Although individual\nprimitives are usually easy to understand, they become complicated quickly\nwhen you put them together. We have introduced an operational model of\nschedule primitives in Tensor Expression.\n\n* the interactions between different schedule primitives,\n* the impact of the schedule primitives on the final code generation.\n\nThe operational model is based on a Dataflow Graph, a Schedule Tree and an\nIterVar Relationship Graph. Schedule primitives perform operations on these\ngraphs.\n\nTEDD renders these three graphs from a given schedule.  This tutorial demonstrates\nhow to use TEDD and how to interpret the rendered graphs.\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.contrib import tedd\n\n######################################################################\n# Define and Schedule Convolution with Bias and ReLU\n# --------------------------------------------------\n# Let's build an example Tensor Expression for a convolution followed by Bias and ReLU.\n# We first connect conv2d, add, and relu TOPIs.  Then, we create a TOPI generic schedule.\n#\n\nbatch = 1\nin_channel = 256\nin_size = 32\nnum_filter = 256\nkernel = 3\nstride = 1\npadding = \"SAME\"\ndilation = 1\n\nA = te.placeholder((in_size, in_size, in_channel, batch), name=\"A\")\nW = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\nB = te.placeholder((1, num_filter, 1), name=\"bias\")\n\nwith tvm.target.Target(\"llvm\"):\n    t_conv = topi.nn.conv2d_hwcn(A, W, stride, padding, dilation)\n    t_bias = topi.add(t_conv, B)\n    t_relu = topi.nn.relu(t_bias)\n    s = topi.generic.schedule_conv2d_hwcn([t_relu])\n\n######################################################################\n# Render Graphs with TEDD\n# -----------------------\n# We render graphs to see the computation\n# and how it is scheduled.\n# If you run the tutorial in a Jupyter notebook, you can use the following commented lines\n# to render SVG figures showing in notebook directly.\n#\n\ntedd.viz_dataflow_graph(s, dot_file_path=\"/tmp/dfg.dot\")\n# tedd.viz_dataflow_graph(s, show_svg = True)\n\n######################################################################\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/tedd_dfg.png\n#      :align: center\n#\n# The first one is a dataflow graph.  Every node represents a stage with name and memory\n# scope shown in the middle and inputs/outputs information on the sides.\n# Edges show nodes' dependency.\n#\n\ntedd.viz_schedule_tree(s, dot_file_path=\"/tmp/scheduletree.dot\")\n# tedd.viz_schedule_tree(s, show_svg = True)\n\n######################################################################\n# We just rendered the schedule tree graph.  You may notice an warning about ranges not\n# available.\n# The message also suggests to call normalize() to infer range information.  We will\n# skip inspecting the first schedule tree and encourage you to compare the graphs before\n# and after normalize() for its impact.\n#\n\ns = s.normalize()\ntedd.viz_schedule_tree(s, dot_file_path=\"/tmp/scheduletree2.dot\")\n# tedd.viz_schedule_tree(s, show_svg = True)\n\n######################################################################\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/tedd_st.png\n#      :align: center\n#\n# Now, let us take a close look at the second schedule tree.  Every block under ROOT\n# represents a\n# stage.  Stage name shows in the top row and compute shows in the bottom row.\n# The middle rows are for IterVars, the higher the outer, the lower the inner.\n# An IterVar row contains its index, name, type, and other optional information.\n# Let's use the W.shared stage as an example.  The top row tells\n# its name, \"W.shared\", and memory scope, \"Shared\".  Its compute is\n# :code:`W(ax0, ax1, ax2, ax3)`.\n# Its outer most loop IterVar is ax0.ax1.fused.ax2.fused.ax3.fused.outer,\n# indexed with 0, of kDataPar, bound to threadIdx.y, and with range(min=0, ext=8).\n# You can also tell\n# IterVar type with the index box color, shown in the legend.\n#\n# If a stage doesn't compute_at any other stage, it has an edge directly to the\n# ROOT node.  Otherwise, it has an edge pointing to the IterVar it attaches to,\n# such as W.shared attaches to rx.outer in the middle compute stage.\n#\n\n######################################################################\n# .. note::\n#\n#   By definition, IterVars are internal nodes and computes are leaf nodes in\n#   a schedule tree.   The edges among IterVars and compute within one stage are\n#   omitted, making every stage a block, for better readability.\n#\n\ntedd.viz_itervar_relationship_graph(s, dot_file_path=\"/tmp/itervar.dot\")\n# tedd.viz_itervar_relationship_graph(s, show_svg = True)\n\n######################################################################\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/tedd_itervar_rel.png\n#      :align: center\n#\n# The last one is an IterVar Relationship Graph.  Every subgraph represents a\n# stage and contains IterVar nodes and transformation nodes.  For example,\n# W.shared has three split nodes and three fuse nodes.  The rest are IterVar\n# nodes of the same format as the IterVar rows in Schedule Trees.  Root\n# IterVars are those not driven by any transformation node, such as ax0; leaf\n# IterVars don't drive any transformation node and have non-negative indices,\n# such as ax0.ax1.fused.ax2.fused.ax3.fused.outer with index of 0.\n#\n\n\n######################################################################\n# Summary\n# -------\n# This tutorial demonstrates the usage of TEDD.  We use an example built\n# with TOPI to show the schedules under the hood.  You can also use\n# it before and after any schedule primitive to inspect its effect.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorials-tensorize:\n\nUse Tensorize to Leverage Hardware Intrinsics\n=============================================\n**Author**: `Yizhi Liu <https://github.com/yzhliu>`_\n\nThis is an introduction material on how to perform tensorization in TVM.\n\nBy using schedule primitive :code:`tensorize`,\npeople can replace a unit of computation with the corresponding intrinsics,\nmaking it easy to leverage handcrafted micro-kernels,\nas well as extend TVM to support new hardware architectures.\n\nThe purpose of this tutorial is to show the functionality\nand usage of tensorize instead of providing an efficient solution.\n\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport tvm.testing\nimport numpy as np\n\n######################################################################\n# Define Matrix Multiplication\n# ----------------------------\n# Take matrix multiplication as our example.\n# Matmul first multiply the corresponding elements between two matrix,\n# then accumulate across a certain axis.\n# The following lines describe the computation :code:`A * B^T` in TVM.\n#\nN, M, L = 1024, 512, 64\nA = te.placeholder((N, L), name=\"A\")\nB = te.placeholder((M, L), name=\"B\")\nk = te.reduce_axis((0, L), name=\"k\")\nC = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[j, k], axis=k), name=\"C\")\ns = te.create_schedule(C.op)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Schedule the Matmul\n# -------------------\n# Now, suppose we have an accelerator that supports\n# matrix-vector multiplication (GEMV) as a hardware primitive,\n# which can take arbitrary size of reduce axis,\n# but another axis needs to be no larger than 16.\n# Thus we break down the matmul loops to make the innermost loops a (16x64) GEMV.\n#\nfactor = 16\nx, y = C.op.axis\n(z,) = C.op.reduce_axis\nyo, yi = s[C].split(y, factor=factor)\ns[C].reorder(x, yo, yi, z)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# As showed in the IR printed above,\n# the inner loops :code:`j.inner` along with :code:`k` together form a computation of GEMV\n# - within the inner most two loops, the index :code:`i` is fixed,\n# the access to the matrix :code:`A` only varies by :code:`k`,\n# which makes the access pattern of :code:`A` a \"vector\".\n# In order to leverage our hypothetical hardware's GEMV instruction,\n# we can tensorize over :code:`j.inner`.\n#\n# Define GEMV Tensorization Intrinsic\n# -----------------------------------\n# Before scheduling the tensorization, we need to first define the intrinsic function for GEMV.\n# It includes two parts, the first is a compute definition of GEMV.\n# TVM uses it to match the computing pattern in the original Matmul schedule.\n# The second is to specify how to execute GEMV on the device,\n# which is done in :code:`intrin_func` below.\n#\ndef intrin_gemv(m, l):\n    a = te.placeholder((l,), name=\"a\")\n    b = te.placeholder((m, l), name=\"b\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    c = te.compute((m,), lambda i: te.sum(a[k] * b[i, k], axis=k), name=\"c\")\n    Ab = tvm.tir.decl_buffer(a.shape, a.dtype, name=\"A\", offset_factor=1, strides=[1])\n    Bb = tvm.tir.decl_buffer(b.shape, b.dtype, name=\"B\", offset_factor=1, strides=[te.var(\"s1\"), 1])\n    Cb = tvm.tir.decl_buffer(c.shape, c.dtype, name=\"C\", offset_factor=1, strides=[1])\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        aa, bb = ins\n        cc = outs[0]\n        ib.emit(\n            tvm.tir.call_extern(\n                \"int32\",\n                \"gemv_update\",\n                cc.access_ptr(\"w\"),\n                aa.access_ptr(\"r\"),\n                bb.access_ptr(\"r\"),\n                m,\n                l,\n                bb.strides[0],\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(c.op, intrin_func, binds={a: Ab, b: Bb, c: Cb})\n\n\n######################################################################\n# Here :code:`te.decl_tensor_intrin` declares how to execute the computation :code:`c.op`.\n# Our implementation simply takes the inputs and outputs,\n# converts them to pointers and emit an external function call.\n# Note that tensorization requires user to specify :code:`offset_factor`,\n# with this information, TVM has knowledge of whether the data is aligned\n# between the start address of the original data structure\n# and the offset being passed to tensorize,\n# so that it has chance to optimize with vectorized loading.\n# We set the factor to 1 for simplification.\n#\n# Buffers are also declared for inputs and outputs, though this is not required,\n# we benefit from the extra information provided by buffers. For example, we pass\n# :code:`bb.strides[0]` as an argument to the external function :code:`gemv_update`.\n# For now :code:`bb.strides[0] == l`,\n# but later we will see how they can differ with more complicated schedules.\n#\n# Note that we use :code:`te.var(\"s1\")` as the first stride dimension for :code:`B`.\n# If the strides can be inferred\n# - in this case, TVM knows tensor B is compact thus the strides are :code:`[L, 1]` -\n# such placeholder can be put to let TVM automatically bind the inferred value for us.\n#\ngemv = intrin_gemv(factor, L)\ns[C].tensorize(yi, gemv)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# By tensorizing over :code:`yi`, the inner most two loops are\n# now replaced by the intrinsic function we defined before.\n# In order to build and run the module, let's define the external function :code:`gemv_update`,\n# it is a naive implementation of GEMV, just for demonstration.\n#\ndef gemv_impl():\n    cc_code = \"\"\"\n      extern \"C\" int gemv_update(float *cc, float *aa, float *bb, int m, int l, int stride) {\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < l; ++j) {\n                cc[i] += aa[j] * bb[i * stride + j];\n            }\n        }\n        return 0;\n      }\n    \"\"\"\n    from tvm.contrib import utils, clang\n\n    temp = utils.tempdir()\n    ll_path = temp.relpath(\"temp.ll\")\n    # Create LLVM ir from c source code\n    ll_code = clang.create_llvm(cc_code, output=ll_path)\n    return ll_code\n\n\n######################################################################\n# Now we leverage the pragma attribute :code:`import_llvm` to import llvm asm inline.\n# The importing needs to happen before the tensorized GEMV being executed.\n#\ns[C].pragma(x, \"import_llvm\", gemv_impl())\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Finally we compare the tensorize version with that :code:`numpy.dot` produces,\n# ensure our implementation is correct.\n#\nfunc = tvm.build(s, [A, B, C], target=\"llvm\", name=\"gemv\")\n\nfrom tvm.topi.utils import get_const_tuple\n\ndtype = A.dtype\ndev = tvm.device(\"cpu\", 0)\na = np.random.uniform(size=get_const_tuple(A.shape)).astype(dtype)\nb = np.random.uniform(size=get_const_tuple(B.shape)).astype(dtype)\nc = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=dtype), dev)\nfunc(tvm.nd.array(a, dev), tvm.nd.array(b, dev), c)\ntvm.testing.assert_allclose(c.numpy(), np.dot(a, b.T), rtol=1e-3)\n\n######################################################################\n# Reduce-update for Tensorize\n# ---------------------------\n# So far you have learned the basic idea of tensorize,\n# now let's move one step forward to a more complicated case.\n#\n# Assume our accelerator could only multiply a vector by a square matrix,\n# in which the vector size needs to be no larger than 16.\n# Given such hardware constrain, now we need to split the reduce axis as following,\n#\nzo, zi = s[C].split(z, factor=factor)\ns[C].reorder(x, yo, zo, yi, zi)\n\n######################################################################\n# However, since the tensorize intrinsic now only covers a part of the reduce axis,\n# instead of using one \"body\" function, TVM requires a :code:`reduce_reset` function,\n# which will be invoked before the reduce for-loop, and a :code:`reduce_update` function,\n# which defines the \"update\" computing strategy.\n#\ndef gemv_impl():\n    cc_code = \"\"\"\n      extern \"C\" int gemv_update(float *cc, float *aa, float *bb, int m, int l, int stride) {\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < l; ++j) {\n                cc[i] += aa[j] * bb[i * stride + j];\n            }\n        }\n        return 0;\n      }\n      extern \"C\" int gemv_reset(float *cc, int m) {\n        for (int i = 0; i < m; ++i) {\n            cc[i] = 0.0;\n        }\n        return 0;\n      }\n    \"\"\"\n    from tvm.contrib import utils, clang\n\n    temp = utils.tempdir()\n    ll_path = temp.relpath(\"temp.ll\")\n    # Create LLVM ir from c source code\n    ll_code = clang.create_llvm(cc_code, output=ll_path)\n    return ll_code\n\n\ndef intrin_gemv(m, l):\n    a = te.placeholder((l,), name=\"a\")\n    b = te.placeholder((m, l), name=\"b\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    c = te.compute((m,), lambda i: te.sum(a[k] * b[i, k], axis=k), name=\"c\")\n    Ab = tvm.tir.decl_buffer(a.shape, a.dtype, name=\"A\", offset_factor=1, strides=[1])\n    Bb = tvm.tir.decl_buffer(b.shape, b.dtype, name=\"B\", offset_factor=1, strides=[te.var(\"s1\"), 1])\n    Cb = tvm.tir.decl_buffer(c.shape, c.dtype, name=\"C\", offset_factor=1, strides=[1])\n\n    def intrin_func(ins, outs):\n        aa, bb = ins\n        cc = outs[0]\n\n        def _body():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"gemv_update\",\n                    cc.access_ptr(\"w\"),\n                    aa.access_ptr(\"r\"),\n                    bb.access_ptr(\"r\"),\n                    m,\n                    l,\n                    bb.strides[0],\n                )\n            )\n            return ib.get()\n\n        def _reduce_reset():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(tvm.tir.call_extern(\"int32\", \"gemv_reset\", cc.access_ptr(\"w\"), m))\n            return ib.get()\n\n        def _reduce_update():\n            return _body()\n\n        return _body(), _reduce_reset(), _reduce_update()\n\n    return te.decl_tensor_intrin(c.op, intrin_func, binds={a: Ab, b: Bb, c: Cb})\n\n\n######################################################################\n# Note that :code:`intrin_func` now returns a triplet:\n# :code:`(body, reduce_reset, reduce_update)`.\n# If tensorization includes all the reduce axes, function :code:`body()` will be invoked,\n# otherwise :code:`reduce_reset()` and :code:`reduce_update()` together will be used.\n# In our example :code:`body()` and :code:`reduce_update()`\n# share the same implementation,\n# while in other cases, hardware may have different instructions for these two functions.\n# Moreover, we can see now :code:`bb.strides[0]` is different from :code:`l`\n# due to the tiling.\n#\n# Tensorize for squared GEMV, build and check the results,\n#\ngemv = intrin_gemv(factor, factor)\ns[C].tensorize(yi, gemv)\ns[C].pragma(yo, \"import_llvm\", gemv_impl())\n\nfunc = tvm.build(s, [A, B, C], target=\"llvm\", name=\"gemv\")\na = np.random.uniform(size=get_const_tuple(A.shape)).astype(dtype)\nb = np.random.uniform(size=get_const_tuple(B.shape)).astype(dtype)\nc = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=dtype), dev)\nfunc(tvm.nd.array(a, dev), tvm.nd.array(b, dev), c)\ntvm.testing.assert_allclose(c.numpy(), np.dot(a, b.T), rtol=1e-3)\n\n######################################################################\n# Summary\n# -------\n# This tutorial demonstrates the usage of tensorize intrinsic in TVM.\n# Tensorize provides a way for users to get fully optimized schedule via micro-kernels.\n# For example, INT8 quantization on Intel CPUs uses tensorization\n# to invoke AVX instruction directly.\n# It also enables TVM to compile to ASICs -\n# checkout :ref:`vta-index` for details.\n# We also demonstrates how to use inline assembly importing,\n# which helps users inject asm easily into the schedule.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/how_to/work_with_schedules/tuple_inputs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompute and Reduce with Tuple Inputs\n=======================================\n**Author**: `Ziheng Jiang <https://github.com/ZihengJiang>`_\n\nOften we want to compute multiple outputs with the same shape within\na single loop or perform reduction that involves multiple values like\n:code:`argmax`. These problems can be addressed by tuple inputs.\n\nIn this tutorial, we will introduce the usage of tuple inputs in TVM.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n######################################################################\n# Describe Batchwise Computation\n# ------------------------------\n# For operators which have the same shape, we can put them together as\n# the inputs of :any:`te.compute`, if we want them to be scheduled\n# together in the next schedule procedure.\n#\nn = te.var(\"n\")\nm = te.var(\"m\")\nA0 = te.placeholder((m, n), name=\"A0\")\nA1 = te.placeholder((m, n), name=\"A1\")\nB0, B1 = te.compute((m, n), lambda i, j: (A0[i, j] + 2, A1[i, j] * 3), name=\"B\")\n\n# The generated IR code would be:\ns = te.create_schedule(B0.op)\nprint(tvm.lower(s, [A0, A1, B0, B1], simple_mode=True))\n\n######################################################################\n# .. _reduction-with-tuple-inputs:\n#\n# Describe Reduction with Collaborative Inputs\n# --------------------------------------------\n# Sometimes, we require multiple inputs to express some reduction\n# operators, and the inputs will collaborate together, e.g. :code:`argmax`.\n# In the reduction procedure, :code:`argmax` need to compare the value of\n# operands, also need to keep the index of operand. It can be expressed\n# with :py:func:`te.comm_reducer` as below:\n\n# x and y are the operands of reduction, both of them is a tuple of index\n# and value.\ndef fcombine(x, y):\n    lhs = tvm.tir.Select((x[1] >= y[1]), x[0], y[0])\n    rhs = tvm.tir.Select((x[1] >= y[1]), x[1], y[1])\n    return lhs, rhs\n\n\n# our identity element also need to be a tuple, so `fidentity` accepts\n# two types as inputs.\ndef fidentity(t0, t1):\n    return tvm.tir.const(-1, t0), tvm.te.min_value(t1)\n\n\nargmax = te.comm_reducer(fcombine, fidentity, name=\"argmax\")\n\n# describe the reduction computation\nm = te.var(\"m\")\nn = te.var(\"n\")\nidx = te.placeholder((m, n), name=\"idx\", dtype=\"int32\")\nval = te.placeholder((m, n), name=\"val\", dtype=\"int32\")\nk = te.reduce_axis((0, n), \"k\")\nT0, T1 = te.compute((m,), lambda i: argmax((idx[i, k], val[i, k]), axis=k), name=\"T\")\n\n# the generated IR code would be:\ns = te.create_schedule(T0.op)\nprint(tvm.lower(s, [idx, val, T0, T1], simple_mode=True))\n\n######################################################################\n# .. note::\n#\n#   For ones who are not familiar with reduction, please refer to\n#   :ref:`general-reduction`.\n\n######################################################################\n# Schedule Operation with Tuple Inputs\n# ------------------------------------\n# It is worth mentioning that although you will get multiple outputs\n# with one batch operation, but they can only be scheduled together\n# in terms of operation.\n\nn = te.var(\"n\")\nm = te.var(\"m\")\nA0 = te.placeholder((m, n), name=\"A0\")\nB0, B1 = te.compute((m, n), lambda i, j: (A0[i, j] + 2, A0[i, j] * 3), name=\"B\")\nA1 = te.placeholder((m, n), name=\"A1\")\nC = te.compute((m, n), lambda i, j: A1[i, j] + B0[i, j], name=\"C\")\n\ns = te.create_schedule(C.op)\ns[B0].compute_at(s[C], C.op.axis[0])\n# as you can see in the below generated IR code:\nprint(tvm.lower(s, [A0, A1, C], simple_mode=True))\n\n######################################################################\n# Summary\n# -------\n# This tutorial introduces the usage of tuple inputs operation.\n#\n# - Describe normal batchwise computation.\n# - Describe reduction operation with tuple inputs.\n# - Notice that you can only schedule computation in terms of operation instead of tensor.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/auto_scheduler_matmul_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nOptimizing Operators with Auto-scheduling\n=========================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, \\\n            `Chengfan Jia <https://github.com/jcf94/>`_\n\nIn this tutorial, we will show how TVM's Auto Scheduling feature can find\noptimal schedules without the need for writing a custom template.\n\nDifferent from the template-based :doc:`AutoTVM <autotvm_matmul_x86>` which relies on\nmanual templates to define the search space, the auto-scheduler does not\nrequire any templates.  Users only need to write the computation declaration\nwithout any schedule commands or templates.  The auto-scheduler can\nautomatically generate a large search space and find a good schedule in the\nspace.\n\nWe use matrix multiplication as an example in this tutorial.\n\n.. note::\n  Note that this tutorial will not run on Windows or recent versions of macOS. To\n  get it to run, you will need to wrap the body of this tutorial in a :code:`if\n  __name__ == \"__main__\":` block.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\nimport tvm\nfrom tvm import te, auto_scheduler\n\n################################################################################\n# Defining the Matrix Multiplication\n# ----------------------------------\n# To start, we define a matrix multiplication with a bias addition.  Note that\n# this uses standard operations available in TVMs Tensor Expression language.\n# The major difference is the use of the :any:`register_workload` decorator at the top\n# of the function definition.  The function should return a list of\n# input/output tensors.  From these tensors, the auto-scheduler can get the\n# whole computational graph.\n\n\n@auto_scheduler.register_workload  # Note the auto_scheduler decorator\ndef matmul_add(N, L, M, dtype):\n    A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n    B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n    C = te.placeholder((N, M), name=\"C\", dtype=dtype)\n\n    k = te.reduce_axis((0, L), name=\"k\")\n    matmul = te.compute(\n        (N, M),\n        lambda i, j: te.sum(A[i, k] * B[k, j], axis=k),\n        name=\"matmul\",\n        attrs={\"layout_free_placeholders\": [B]},  # enable automatic layout transform for tensor B\n    )\n    out = te.compute((N, M), lambda i, j: matmul[i, j] + C[i, j], name=\"out\")\n\n    return [A, B, C, out]\n\n\n################################################################################\n# Create the search task\n# ----------------------\n# With the function defined, we can now create the task for the auto_scheduler\n# to search against. We specify the particular parameters for this matrix\n# multiplication, in this case a multiplication of two square matrices of size\n# 1024x1024. We then create a search task with N=L=M=1024 and dtype=\"float32\"\n#\n# .. admonition:: Improve performance with custom targets\n#\n#   In order for TVM to take full advantage of specific hardware platforms,\n#   you will want to manually specify your CPU capabilities. For example:\n#\n#     - replace ``llvm`` below with ``llvm -mcpu=core-avx2`` to enable AVX2\n#     - replace ``llvm`` below with ``llvm -mcpu=skylake-avx512`` to enable AVX-512\n\ntarget = tvm.target.Target(\"llvm\")\nN = L = M = 1024\ntask = tvm.auto_scheduler.SearchTask(func=matmul_add, args=(N, L, M, \"float32\"), target=target)\n\n# Inspect the computational graph\nprint(\"Computational DAG:\")\nprint(task.compute_dag)\n\n################################################################################\n# Set Parameters for Auto-Scheduler\n# ---------------------------------\n# Next, we set parameters for the auto-scheduler.\n#\n# * :code:`num_measure_trials` is the number of measurement trials we can use\n#   during the search.  We only make 10 trials in this tutorial for a fast\n#   demonstration. In practice, 1000 is a good value for the search to converge.\n#   You can do more trials according to your time budget.\n# * In addition, we use :any:`RecordToFile <auto_scheduler.RecordToFile>` to log measurement records into a\n#   file ``matmul.json``.  The measurement records can be used to query the history\n#   best, resume the search, and do more analyses later.\n# * see :any:`TuningOptions <auto_scheduler.TuningOptions>` for more parameters\n\nlog_file = \"matmul.json\"\ntune_option = auto_scheduler.TuningOptions(\n    num_measure_trials=10,\n    measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n    verbose=2,\n)\n\n################################################################################\n# Run the search\n# --------------\n# Now we get all inputs ready. Pretty simple, isn't it?  We can kick off the\n# search and let the auto-scheduler do its magic.  After some measurement\n# trials, we can load the best schedule from the log file and apply it.\n\n# Run auto-tuning (search)\ntask.tune(tune_option)\n# Apply the best schedule\nsch, args = task.apply_best(log_file)\n\n################################################################################\n# Inspecting the Optimized Schedule\n# ---------------------------------\n# We can lower the schedule to see the IR after auto-scheduling.  The\n# auto-scheduler correctly performs optimizations including multi-level tiling,\n# layout transformation, parallelization, vectorization, unrolling, and\n# operator fusion.\n\nprint(\"Lowered TIR:\")\nprint(tvm.lower(sch, args, simple_mode=True))\n\n################################################################################\n# Check correctness and evaluate performance\n# ------------------------------------------\n# We build the binary and check its correctness and performance.\n\nfunc = tvm.build(sch, args, target)\na_np = np.random.uniform(size=(N, L)).astype(np.float32)\nb_np = np.random.uniform(size=(L, M)).astype(np.float32)\nc_np = np.random.uniform(size=(N, M)).astype(np.float32)\nout_np = a_np.dot(b_np) + c_np\n\ndev = tvm.cpu()\na_tvm = tvm.nd.array(a_np, device=dev)\nb_tvm = tvm.nd.array(b_np, device=dev)\nc_tvm = tvm.nd.array(c_np, device=dev)\nout_tvm = tvm.nd.empty(out_np.shape, device=dev)\nfunc(a_tvm, b_tvm, c_tvm, out_tvm)\n\n# Check results\nnp.testing.assert_allclose(out_np, out_tvm.numpy(), rtol=1e-3)\n\n# Evaluate execution time.\nevaluator = func.time_evaluator(func.entry_name, dev, min_repeat_ms=500)\nprint(\n    \"Execution time of this operator: %.3f ms\"\n    % (np.median(evaluator(a_tvm, b_tvm, c_tvm, out_tvm).results) * 1000)\n)\n\n\n################################################################################\n# Using the record file\n# ---------------------\n# During the search, all measurement records are logged into the record file\n# ``matmul.json```. The measurement records can be used to re-apply search\n# results, resume the search, and perform other analyses.\n#\n# Here is an example where we load the best schedule from a file, and print the\n# equivalent python schedule API. This can be used for debugging and learning\n# the behavior of the auto-scheduler.\n\nprint(\"Equivalent python schedule:\")\nprint(task.print_best(log_file))\n\n################################################################################\n# A more complicated example is to resume the search.  In this case, we need to\n# create the search policy and cost model by ourselves and resume the status of\n# search policy and cost model with the log file.  In the example below we\n# resume the status and do more 5 trials.\n\n\ndef resume_search(task, log_file):\n    print(\"Resume search:\")\n    cost_model = auto_scheduler.XGBModel()\n    cost_model.update_from_file(log_file)\n    search_policy = auto_scheduler.SketchPolicy(\n        task, cost_model, init_search_callbacks=[auto_scheduler.PreloadMeasuredStates(log_file)]\n    )\n    tune_option = auto_scheduler.TuningOptions(\n        num_measure_trials=5, measure_callbacks=[auto_scheduler.RecordToFile(log_file)]\n    )\n    task.tune(tune_option, search_policy=search_policy)\n\n\nresume_search(task, log_file)\n\n################################################################################\n# Final Notes and Summary\n# -----------------------\n# In this tutorial, we have shown how to use the TVM Auto-Scheduler to\n# automatically optimize a matrix multiplication, without the need to specify a\n# search template.  It ends a series of examples that starts from the Tensor\n# Expression (TE) language that demonstrates how TVM can optimize computational\n# operations.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/autotvm_matmul_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-autotvm-matmul-x86:\n\nOptimizing Operators with Schedule Templates and AutoTVM\n========================================================\n**Authors**:\n`Lianmin Zheng <https://github.com/merrymercy>`_,\n`Chris Hoge <https://github.com/hogepodge>`_\n\nIn this tutorial, we show how the TVM Tensor Expression (TE) language\ncan be used to write schedule templates that can be searched by AutoTVM to\nfind the optimal schedule. This process is called Auto-Tuning, which helps\nautomate the process of optimizing tensor computation.\n\nThis tutorial builds on the previous :doc:`tutorial on how to write a matrix\nmultiplication using TE <tensor_expr_get_started>`.\n\nThere are two steps in auto-tuning.\n\n- The first step is defining a search space.\n- The second step is running a search algorithm to explore through this space.\n\nIn this tutorial, you can learn how to perform these two steps in TVM. The whole\nworkflow is illustrated by a matrix multiplication example.\n\n.. note::\n  Note that this tutorial will not run on Windows or recent versions of macOS.\n  To get it to run, you will need to wrap the body of this tutorial in a\n  :code:`if __name__ == \"__main__\":` block.\n\"\"\"\n\n################################################################################\n# Install dependencies\n# --------------------\n# To use autotvm package in TVM, we need to install some extra dependencies.\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost cloudpickle\n#\n# To make TVM run faster in tuning, it is recommended to use cython as FFI of\n# TVM. In the root directory of TVM, execute:\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Begin by importing the required packages.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport logging\nimport sys\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.testing\n\n# the module is called `autotvm`\nfrom tvm import autotvm\n\n################################################################################\n# Basic Matrix Multiplication with TE\n# -----------------------------------\n# Recall the basic implementation of matrix multiplication using TE. We write\n# it down here with a few changes. We will wrap the multiplication in a python\n# function definition. For simplicity, we will focus our attention on a split\n# optimization, using a fixed value that defines the block size of the\n# reordering.\n\n\ndef matmul_basic(N, L, M, dtype):\n\n    A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n    B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n\n    k = te.reduce_axis((0, L), name=\"k\")\n    C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    # schedule\n    y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    yo, yi = s[C].split(y, 8)\n    xo, xi = s[C].split(x, 8)\n\n    s[C].reorder(yo, xo, k, yi, xi)\n\n    return s, [A, B, C]\n\n\n################################################################################\n# Matrix Multiplication with AutoTVM\n# ----------------------------------\n# In the previous schedule code, we use a constant \"8\" as the tiling factor.\n# However, it might not be the best one because the best tiling factor depends\n# on real hardware environment and input shape.\n#\n# If you want the schedule code to be portable across a wider range of input\n# shapes and target hardware, it is better to define a set of candidate values\n# and pick the best one according to the measurement results on target\n# hardware.\n#\n# In autotvm, we can define a tunable parameter, or a \"knob\" for such kind of\n# value.\n\n################################################################################\n# A Basic Matrix Multiplication Template\n# --------------------------------------\n# We begin with an example of how to create a tunable parameter set for the\n# block size of the `split` scheduling operation.\n\n# Matmul V1: List candidate values\n@autotvm.template(\"tutorial/matmul_v1\")  # 1. use a decorator\ndef matmul_v1(N, L, M, dtype):\n    A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n    B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n\n    k = te.reduce_axis((0, L), name=\"k\")\n    C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    # schedule\n    y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    # 2. get the config object\n    cfg = autotvm.get_config()\n\n    # 3. define search space\n    cfg.define_knob(\"tile_y\", [1, 2, 4, 8, 16])\n    cfg.define_knob(\"tile_x\", [1, 2, 4, 8, 16])\n\n    # 4. schedule according to config\n    yo, yi = s[C].split(y, cfg[\"tile_y\"].val)\n    xo, xi = s[C].split(x, cfg[\"tile_x\"].val)\n\n    s[C].reorder(yo, xo, k, yi, xi)\n\n    return s, [A, B, C]\n\n\n################################################################################\n# Here we make four modifications to the previous schedule code and get a\n# tunable \"template\". We can explain the modifications one by one.\n#\n# 1. Use a decorator to mark this function as a simple template.\n# 2. Get a config object: You can regard this :code:`cfg` as an argument of\n#    this function but we obtain it in a different way. With this argument, this\n#    function is no longer a deterministic schedule. Instead, we can pass\n#    different configurations to this function and get different schedules. A\n#    function that uses a configuration object like this is called a \"template\".\n#\n#    To make the template function more compact, we can do two things to define\n#    the parameter search space within a single function.\n#\n#    1. Define a search space across a set values. This is done by making\n#       :code:`cfg` a :any:`ConfigSpace` object. It will collect all of the\n#       tunable knobs in this function and build a search space from it.\n#    2. Schedule according to an entity in this space. This is done by making\n#       :code:`cfg` a :any:`ConfigEntity` object. When it is a\n#       :any:`ConfigEntity`, it will ignore all space definition API (namely,\n#       :code:`cfg.define_XXXXX(...)`). Instead, it will store deterministic\n#       values for all tunable knobs, and we schedule according to these values.\n#\n#    During auto-tuning, we will first call this template with a\n#    :any:`ConfigSpace` object to build the search space. Then we call this\n#    template with different :any:`ConfigEntity` in the built space to get\n#    different schedules. Finally we will measure the code generated by\n#    different schedules and pick the best one.\n#\n# 3. Define two tunable knobs. The first one is :code:`tile_y` with 5 possible\n#    values. The second one is :code:`tile_x` with a same list of possible values.\n#    These two knobs are independent, so they span a search space with size 25 =\n#    5x5.\n# 4. The configuration knobs are passed to the :code:`split` schedule\n#    operation, allowing us to schedule according to the 5x5 deterministic values\n#    we previously defined in :code:`cfg`.\n\n################################################################################\n# A Matrix Multiplication Template with the Advanced Parameter API\n# ----------------------------------------------------------------\n# In the previous template, we manually listed all of the possible values for a\n# knob. This is the lowest level API to define the space, and gives an explicit\n# enumeration of the parameter space to search. However, we also provide\n# another set of APIs that can make the definition of the search space easier\n# and smarter. Where possible, we recommend you use this higher-level API\n#\n# In the following example, we use :any:`ConfigSpace.define_split` to define a\n# split knob. It will enumerate all the possible ways to split an axis and\n# construct the space.\n#\n# We also have :any:`ConfigSpace.define_reorder` for reorder knob and\n# :any:`ConfigSpace.define_annotate` for annotation like unroll, vectorization,\n# thread binding. When the high level API cannot meet your requirements, you\n# can always fall back to using the low level API.\n\n\n@autotvm.template(\"tutorial/matmul\")\ndef matmul(N, L, M, dtype):\n    A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n    B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n\n    k = te.reduce_axis((0, L), name=\"k\")\n    C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    # schedule\n    y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    ##### define space begin #####\n    cfg = autotvm.get_config()\n    cfg.define_split(\"tile_y\", y, num_outputs=2)\n    cfg.define_split(\"tile_x\", x, num_outputs=2)\n    ##### define space end #####\n\n    # schedule according to config\n    yo, yi = cfg[\"tile_y\"].apply(s, C, y)\n    xo, xi = cfg[\"tile_x\"].apply(s, C, x)\n\n    s[C].reorder(yo, xo, k, yi, xi)\n\n    return s, [A, B, C]\n\n\n################################################################################\n# .. admonition:: More Explanation on :code:`cfg.define_split`\n#\n#  In this template, :code:`cfg.define_split(\"tile_y\", y, num_outputs=2)` will\n#  enumerate all possible combinations that can split axis y into two axes with\n#  factors of the length of y. For example, if the length of y is 32 and we\n#  want to split it into two axes using factors of 32, then there are 6\n#  possible values for (length of outer axis, length of inner axis) pair,\n#  namely (32, 1), (16, 2), (8, 4), (4, 8), (2, 16) or (1, 32). These are all 6\n#  possible values of `tile_y`.\n#\n#  During scheduling, :code:`cfg[\"tile_y\"]` is a :code:`SplitEntity` object.\n#  We stores the lengths of outer axes and inner axes in\n#  :code:`cfg['tile_y'].size` (a tuple with two elements).  In this template,\n#  we apply it by using :code:`yo, yi = cfg['tile_y'].apply(s, C, y)`.\n#  Actually, this is equivalent to :code:`yo, yi = s[C].split(y,\n#  cfg[\"tile_y\"].size[1])` or  :code:`yo, yi = s[C].split(y,\n#  nparts=cfg['tile_y\"].size[0])`\n#\n#  The advantage of using cfg.apply API is that it makes multi-level splits\n#  (that is, when num_outputs >= 3) easier.\n\n################################################################################\n# Step 2: Use AutoTVM to Optimize the Matrix Multiplication\n# ---------------------------------------------------------\n# In Step 1, we wrote a matrix multiplication template that allowed us to\n# parameterize the block size used in the `split` schedule. We can now conduct\n# a search over this parameter space. The next step is to pick a tuner to guide\n# the exploration of this space.\n#\n# Auto-tuners in TVM\n# ~~~~~~~~~~~~~~~~~~\n# The job for a tuner can be described by following pseudo code\n#\n#   .. code-block:: c\n#\n#    ct = 0\n#    while ct < max_number_of_trials:\n#        propose a batch of configs\n#        measure this batch of configs on real hardware and get results\n#        ct += batch_size\n#\n# When proposing the next batch of configs, the tuner can take different\n# strategies. Some of the tuner strategies provided by TVM include:\n#\n# * :any:`tvm.autotvm.tuner.RandomTuner`: Enumerate the space in a random order\n# * :any:`tvm.autotvm.tuner.GridSearchTuner`: Enumerate the space in a grid search order\n# * :any:`tvm.autotvm.tuner.GATuner`: Using genetic algorithm to search through the space\n# * :any:`tvm.autotvm.tuner.XGBTuner`: Uses a model based method. Train a XGBoost model to\n#   predict the speed of lowered IR and pick the next batch according to the\n#   prediction.\n#\n# You can choose the tuner according to the size of your space, your time\n# budget and other factors.  For example, if your space is very small (less\n# than 1000), a grid-search tuner or a random tuner is good enough. If your\n# space is at the level of 10^9 (this is the space size of a conv2d operator on\n# CUDA GPU), XGBoostTuner can explore more efficiently and find better configs.\n\n################################################################################\n# Begin tuning\n# ~~~~~~~~~~~~\n# Here we continue our matrix multiplication example. First we create a tuning\n# task. We can also inspect the initialized search space. In this case, for a\n# 512x512 square matrix multiplication, the space size is 10x10=100 Note that\n# the task and search space are independent of the tuner picked.\n\nN, L, M = 512, 512, 512\ntask = autotvm.task.create(\"tutorial/matmul\", args=(N, L, M, \"float32\"), target=\"llvm\")\nprint(task.config_space)\n\n################################################################################\n# Then we need to define how to measure the generated code and pick a tuner.\n# Since our space is small, a random tuner is just okay.\n#\n# We only make 10 trials in this tutorial for demonstration. In practice, you\n# can do more trials according to your time budget. We will log the tuning\n# results into a log file. This file can be used to choose the best\n# configuration discovered by the tuner later.\n\n# logging config (for printing tuning log to the screen)\nlogging.getLogger(\"autotvm\").setLevel(logging.DEBUG)\nlogging.getLogger(\"autotvm\").addHandler(logging.StreamHandler(sys.stdout))\n\n################################################################################\n# There are two steps for measuring a config: build and run. By default, we use\n# all CPU cores to compile program. We then measure them sequentially. To help\n# reduce variance, we take 5 measurements and average them.\nmeasure_option = autotvm.measure_option(builder=\"local\", runner=autotvm.LocalRunner(number=5))\n\n# Begin tuning with RandomTuner, log records to file `matmul.log`\n# You can use alternatives like XGBTuner.\ntuner = autotvm.tuner.RandomTuner(task)\ntuner.tune(\n    n_trial=10,\n    measure_option=measure_option,\n    callbacks=[autotvm.callback.log_to_file(\"matmul.log\")],\n)\n\n################################################################################\n# With tuning completed, we can choose the configuration from the log file that\n# has the best measured performance and compile the schedule with the\n# corresponding parameters. We also do a quick verification that the schedule is\n# producing correct answers.  We can call the function :code:`matmul` directly\n# under the :any:`autotvm.apply_history_best` context. When we call this\n# function, it will query the dispatch context with its argument and get the\n# best config with the same argument.\n\n# apply history best from log file\nwith autotvm.apply_history_best(\"matmul.log\"):\n    with tvm.target.Target(\"llvm\"):\n        s, arg_bufs = matmul(N, L, M, \"float32\")\n        func = tvm.build(s, arg_bufs)\n\n# check correctness\na_np = np.random.uniform(size=(N, L)).astype(np.float32)\nb_np = np.random.uniform(size=(L, M)).astype(np.float32)\nc_np = a_np.dot(b_np)\n\nc_tvm = tvm.nd.empty(c_np.shape)\nfunc(tvm.nd.array(a_np), tvm.nd.array(b_np), c_tvm)\n\ntvm.testing.assert_allclose(c_np, c_tvm.numpy(), rtol=1e-4)\n\n################################################################################\n# Final Notes and Summary\n# -----------------------\n# In this tutorial, we have shown how to build operator templates that allow\n# TVM to search a parameter space and choose optimized schedule configurations.\n# To gain a deeper understanding of how this works, we recommend expanding on\n# this example by adding new search parameters to the schedule based on\n# schedule operations demonstrated in the :ref: `Getting Started With Tensor\n# Expressions <tensor_expr_get_started>_` tutorial. In the upcoming sections, we\n# will demonstrate the AutoScheduler, a method for TVM to optimize common\n# operators without the need for the user to provide a user-defined template.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/autotvm_relay_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompiling and Optimizing a Model with the Python Interface (AutoTVM)\n====================================================================\n**Author**:\n`Chris Hoge <https://github.com/hogepodge>`_\n\nIn the `TVMC Tutorial <tvmc_command_line_driver>`_, we covered how to compile, run, and tune a\npre-trained vision model, ResNet-50 v2 using the command line interface for\nTVM, TVMC. TVM is more that just a command-line tool though, it is an\noptimizing framework with APIs available for a number of different languages\nthat gives you tremendous flexibility in working with machine learning models.\n\nIn this tutorial we will cover the same ground we did with TVMC, but show how\nit is done with the Python API. Upon completion of this section, we will have\nused the Python API for TVM to accomplish the following tasks:\n\n* Compile a pre-trained ResNet-50 v2 model for the TVM runtime.\n* Run a real image through the compiled model, and interpret the output and model\n  performance.\n* Tune the model that model on a CPU using TVM.\n* Re-compile an optimized model using the tuning data collected by TVM.\n* Run the image through the optimized model, and compare the output and model\n  performance.\n\nThe goal of this section is to give you an overview of TVM's capabilites and\nhow to use them through the Python API.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# TVM is a deep learning compiler framework, with a number of different modules\n# available for working with deep learning models and operators. In this\n# tutorial we will work through how to load, compile, and optimize a model\n# using the Python API.\n#\n# We begin by importing a number of dependencies, including ``onnx`` for\n# loading and converting the model, helper utilities for downloading test data,\n# the Python Image Library for working with the image data, ``numpy`` for pre\n# and post-processing of the image data, the TVM Relay framework, and the TVM\n# Graph Executor.\n\nimport onnx\nfrom tvm.contrib.download import download_testdata\nfrom PIL import Image\nimport numpy as np\nimport tvm.relay as relay\nimport tvm\nfrom tvm.contrib import graph_executor\n\n################################################################################\n# Downloading and Loading the ONNX Model\n# --------------------------------------\n#\n# For this tutorial, we will be working with ResNet-50 v2. ResNet-50 is a\n# convolutional neural network that is 50 layers deep and designed to classify\n# images. The model we will be using has been pre-trained on more than a\n# million images with 1000 different classifications. The network has an input\n# image size of 224x224. If you are interested exploring more of how the\n# ResNet-50 model is structured, we recommend downloading\n# `Netron <https://netron.app>`_, a freely available ML model viewer.\n#\n# TVM provides a helper library to download pre-trained models. By providing a\n# model URL, file name, and model type through the module, TVM will download\n# the model and save it to disk. For the instance of an ONNX model, you can\n# then load it into memory using the ONNX runtime.\n#\n# .. admonition:: Working with Other Model Formats\n#\n#   TVM supports many popular model formats. A list can be found in the\n#   :ref:`Compile Deep Learning Models <tutorial-frontend>` section of the TVM\n#   Documentation.\n\nmodel_url = (\n    \"https://github.com/onnx/models/raw/main/\"\n    \"vision/classification/resnet/model/\"\n    \"resnet50-v2-7.onnx\"\n)\n\nmodel_path = download_testdata(model_url, \"resnet50-v2-7.onnx\", module=\"onnx\")\nonnx_model = onnx.load(model_path)\n\n# Seed numpy's RNG to get consistent results\nnp.random.seed(0)\n\n################################################################################\n# Downloading, Preprocessing, and Loading the Test Image\n# ------------------------------------------------------\n#\n# Each model is particular when it comes to expected tensor shapes, formats and\n# data types. For this reason, most models require some pre and\n# post-processing, to ensure the input is valid and to interpret the output.\n# TVMC has adopted NumPy's ``.npz`` format for both input and output data.\n#\n# As input for this tutorial, we will use the image of a cat, but you can feel\n# free to substitute this image for any of your choosing.\n#\n# .. image:: https://s3.amazonaws.com/model-server/inputs/kitten.jpg\n#    :height: 224px\n#    :width: 224px\n#    :align: center\n#\n# Download the image data, then convert it to a numpy array to use as an input to the model.\n\nimg_url = \"https://s3.amazonaws.com/model-server/inputs/kitten.jpg\"\nimg_path = download_testdata(img_url, \"imagenet_cat.png\", module=\"data\")\n\n# Resize it to 224x224\nresized_image = Image.open(img_path).resize((224, 224))\nimg_data = np.asarray(resized_image).astype(\"float32\")\n\n# Our input image is in HWC layout while ONNX expects CHW input, so convert the array\nimg_data = np.transpose(img_data, (2, 0, 1))\n\n# Normalize according to the ImageNet input specification\nimagenet_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))\nimagenet_stddev = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))\nnorm_img_data = (img_data / 255 - imagenet_mean) / imagenet_stddev\n\n# Add the batch dimension, as we are expecting 4-dimensional input: NCHW.\nimg_data = np.expand_dims(norm_img_data, axis=0)\n\n###############################################################################\n# Compile the Model With Relay\n# ----------------------------\n#\n# The next step is to compile the ResNet model. We begin by importing the model\n# to relay using the `from_onnx` importer. We then build the model, with\n# standard optimizations, into a TVM library.  Finally, we create a TVM graph\n# runtime module from the library.\n\ntarget = \"llvm\"\n\n######################################################################\n# .. admonition:: Defining the Correct Target\n#\n#   Specifying the correct target can have a huge impact on the performance of\n#   the compiled module, as it can take advantage of hardware features\n#   available on the target. For more information, please refer to\n#   :ref:`Auto-tuning a convolutional network for x86 CPU <tune_relay_x86>`.\n#   We recommend identifying which CPU you are running, along with optional\n#   features, and set the target appropriately. For example, for some\n#   processors ``target = \"llvm -mcpu=skylake\"``, or ``target = \"llvm\n#   -mcpu=skylake-avx512\"`` for processors with the AVX-512 vector instruction\n#   set.\n#\n\n# The input name may vary across model types. You can use a tool\n# like Netron to check input names\ninput_name = \"data\"\nshape_dict = {input_name: img_data.shape}\n\nmod, params = relay.frontend.from_onnx(onnx_model, shape_dict)\n\nwith tvm.transform.PassContext(opt_level=3):\n    lib = relay.build(mod, target=target, params=params)\n\ndev = tvm.device(str(target), 0)\nmodule = graph_executor.GraphModule(lib[\"default\"](dev))\n\n######################################################################\n# Execute on the TVM Runtime\n# --------------------------\n# Now that we've compiled the model, we can use the TVM runtime to make\n# predictions with it. To use TVM to run the model and make predictions, we\n# need two things:\n#\n# - The compiled model, which we just produced.\n# - Valid input to the model to make predictions on.\n\ndtype = \"float32\"\nmodule.set_input(input_name, img_data)\nmodule.run()\noutput_shape = (1, 1000)\ntvm_output = module.get_output(0, tvm.nd.empty(output_shape)).numpy()\n\n################################################################################\n# Collect Basic Performance Data\n# ------------------------------\n# We want to collect some basic performance data associated with this\n# unoptimized model and compare it to a tuned model later. To help account for\n# CPU noise, we run the computation in multiple batches in multiple\n# repetitions, then gather some basis statistics on the mean, median, and\n# standard deviation.\nimport timeit\n\ntiming_number = 10\ntiming_repeat = 10\nunoptimized = (\n    np.array(timeit.Timer(lambda: module.run()).repeat(repeat=timing_repeat, number=timing_number))\n    * 1000\n    / timing_number\n)\nunoptimized = {\n    \"mean\": np.mean(unoptimized),\n    \"median\": np.median(unoptimized),\n    \"std\": np.std(unoptimized),\n}\n\nprint(unoptimized)\n\n################################################################################\n# Postprocess the output\n# ----------------------\n#\n# As previously mentioned, each model will have its own particular way of\n# providing output tensors.\n#\n# In our case, we need to run some post-processing to render the outputs from\n# ResNet-50 v2 into a more human-readable form, using the lookup-table provided\n# for the model.\n\nfrom scipy.special import softmax\n\n# Download a list of labels\nlabels_url = \"https://s3.amazonaws.com/onnx-model-zoo/synset.txt\"\nlabels_path = download_testdata(labels_url, \"synset.txt\", module=\"data\")\n\nwith open(labels_path, \"r\") as f:\n    labels = [l.rstrip() for l in f]\n\n# Open the output and read the output tensor\nscores = softmax(tvm_output)\nscores = np.squeeze(scores)\nranks = np.argsort(scores)[::-1]\nfor rank in ranks[0:5]:\n    print(\"class='%s' with probability=%f\" % (labels[rank], scores[rank]))\n\n################################################################################\n# This should produce the following output:\n#\n# .. code-block:: bash\n#\n#     # class='n02123045 tabby, tabby cat' with probability=0.610553\n#     # class='n02123159 tiger cat' with probability=0.367179\n#     # class='n02124075 Egyptian cat' with probability=0.019365\n#     # class='n02129604 tiger, Panthera tigris' with probability=0.001273\n#     # class='n04040759 radiator' with probability=0.000261\n\n################################################################################\n# Tune the model\n# --------------\n# The previous model was compiled to work on the TVM runtime, but did not\n# include any platform specific optimization. In this section, we will show you\n# how to build an optimized model using TVM to target your working platform.\n#\n# In some cases, we might not get the expected performance when running\n# inferences using our compiled module. In cases like this, we can make use of\n# the auto-tuner, to find a better configuration for our model and get a boost\n# in performance. Tuning in TVM refers to the process by which a model is\n# optimized to run faster on a given target. This differs from training or\n# fine-tuning in that it does not affect the accuracy of the model, but only\n# the runtime performance. As part of the tuning process, TVM will try running\n# many different operator implementation variants to see which perform best.\n# The results of these runs are stored in a tuning records file.\n#\n# In the simplest form, tuning requires you to provide three things:\n#\n# - the target specification of the device you intend to run this model on\n# - the path to an output file in which the tuning records will be stored\n# - a path to the model to be tuned.\n#\n\nimport tvm.auto_scheduler as auto_scheduler\nfrom tvm.autotvm.tuner import XGBTuner\nfrom tvm import autotvm\n\n################################################################################\n# Set up some basic parameters for the runner. The runner takes compiled code\n# that is generated with a specific set of parameters and measures the\n# performance of it. ``number`` specifies the number of different\n# configurations that we will test, while ``repeat`` specifies how many\n# measurements we will take of each configuration. ``min_repeat_ms`` is a value\n# that specifies how long need to run configuration test. If the number of\n# repeats falls under this time, it will be increased. This option is necessary\n# for accurate tuning on GPUs, and is not required for CPU tuning. Setting this\n# value to 0 disables it. The ``timeout`` places an upper limit on how long to\n# run training code for each tested configuration.\n\nnumber = 10\nrepeat = 1\nmin_repeat_ms = 0  # since we're tuning on a CPU, can be set to 0\ntimeout = 10  # in seconds\n\n# create a TVM runner\nrunner = autotvm.LocalRunner(\n    number=number,\n    repeat=repeat,\n    timeout=timeout,\n    min_repeat_ms=min_repeat_ms,\n    enable_cpu_cache_flush=True,\n)\n\n################################################################################\n# Create a simple structure for holding tuning options. We use an XGBoost\n# algorithim for guiding the search. For a production job, you will want to set\n# the number of trials to be larger than the value of 20 used here. For CPU we\n# recommend 1500, for GPU 3000-4000. The number of trials required can depend\n# on the particular model and processor, so it's worth spending some time\n# evaluating performance across a range of values to find the best balance\n# between tuning time and model optimization. Because running tuning is time\n# intensive we set number of trials to 10, but do not recommend a value this\n# small. The ``early_stopping`` parameter is the minimum number of trails to\n# run before a condition that stops the search early can be applied. The\n# measure option indicates where trial code will be built, and where it will be\n# run. In this case, we're using the ``LocalRunner`` we just created and a\n# ``LocalBuilder``. The ``tuning_records`` option specifies a file to write\n# the tuning data to.\n\ntuning_option = {\n    \"tuner\": \"xgb\",\n    \"trials\": 20,\n    \"early_stopping\": 100,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(build_func=\"default\"), runner=runner\n    ),\n    \"tuning_records\": \"resnet-50-v2-autotuning.json\",\n}\n\n################################################################################\n# .. admonition:: Defining the Tuning Search Algorithm\n#\n#   By default this search is guided using an `XGBoost Grid` algorithm.\n#   Depending on your model complexity and amount of time available, you might\n#   want to choose a different algorithm.\n\n\n################################################################################\n# .. admonition:: Setting Tuning Parameters\n#\n#   In this example, in the interest of time, we set the number of trials and\n#   early stopping to 10. You will likely see more performance improvements if\n#   you set these values to be higher but this comes at the expense of time\n#   spent tuning. The number of trials required for convergence will vary\n#   depending on the specifics of the model and the target platform.\n\n# begin by extracting the tasks from the onnx model\ntasks = autotvm.task.extract_from_program(mod[\"main\"], target=target, params=params)\n\n# Tune the extracted tasks sequentially.\nfor i, task in enumerate(tasks):\n    prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n    tuner_obj = XGBTuner(task, loss_type=\"rank\")\n    tuner_obj.tune(\n        n_trial=min(tuning_option[\"trials\"], len(task.config_space)),\n        early_stopping=tuning_option[\"early_stopping\"],\n        measure_option=tuning_option[\"measure_option\"],\n        callbacks=[\n            autotvm.callback.progress_bar(tuning_option[\"trials\"], prefix=prefix),\n            autotvm.callback.log_to_file(tuning_option[\"tuning_records\"]),\n        ],\n    )\n\n################################################################################\n# The output from this tuning process will look something like this:\n#\n# .. code-block:: bash\n#\n#   # [Task  1/24]  Current/Best:   10.71/  21.08 GFLOPS | Progress: (60/1000) | 111.77 s Done.\n#   # [Task  1/24]  Current/Best:    9.32/  24.18 GFLOPS | Progress: (192/1000) | 365.02 s Done.\n#   # [Task  2/24]  Current/Best:   22.39/ 177.59 GFLOPS | Progress: (960/1000) | 976.17 s Done.\n#   # [Task  3/24]  Current/Best:   32.03/ 153.34 GFLOPS | Progress: (800/1000) | 776.84 s Done.\n#   # [Task  4/24]  Current/Best:   11.96/ 156.49 GFLOPS | Progress: (960/1000) | 632.26 s Done.\n#   # [Task  5/24]  Current/Best:   23.75/ 130.78 GFLOPS | Progress: (800/1000) | 739.29 s Done.\n#   # [Task  6/24]  Current/Best:   38.29/ 198.31 GFLOPS | Progress: (1000/1000) | 624.51 s Done.\n#   # [Task  7/24]  Current/Best:    4.31/ 210.78 GFLOPS | Progress: (1000/1000) | 701.03 s Done.\n#   # [Task  8/24]  Current/Best:   50.25/ 185.35 GFLOPS | Progress: (972/1000) | 538.55 s Done.\n#   # [Task  9/24]  Current/Best:   50.19/ 194.42 GFLOPS | Progress: (1000/1000) | 487.30 s Done.\n#   # [Task 10/24]  Current/Best:   12.90/ 172.60 GFLOPS | Progress: (972/1000) | 607.32 s Done.\n#   # [Task 11/24]  Current/Best:   62.71/ 203.46 GFLOPS | Progress: (1000/1000) | 581.92 s Done.\n#   # [Task 12/24]  Current/Best:   36.79/ 224.71 GFLOPS | Progress: (1000/1000) | 675.13 s Done.\n#   # [Task 13/24]  Current/Best:    7.76/ 219.72 GFLOPS | Progress: (1000/1000) | 519.06 s Done.\n#   # [Task 14/24]  Current/Best:   12.26/ 202.42 GFLOPS | Progress: (1000/1000) | 514.30 s Done.\n#   # [Task 15/24]  Current/Best:   31.59/ 197.61 GFLOPS | Progress: (1000/1000) | 558.54 s Done.\n#   # [Task 16/24]  Current/Best:   31.63/ 206.08 GFLOPS | Progress: (1000/1000) | 708.36 s Done.\n#   # [Task 17/24]  Current/Best:   41.18/ 204.45 GFLOPS | Progress: (1000/1000) | 736.08 s Done.\n#   # [Task 18/24]  Current/Best:   15.85/ 222.38 GFLOPS | Progress: (980/1000) | 516.73 s Done.\n#   # [Task 19/24]  Current/Best:   15.78/ 203.41 GFLOPS | Progress: (1000/1000) | 587.13 s Done.\n#   # [Task 20/24]  Current/Best:   30.47/ 205.92 GFLOPS | Progress: (980/1000) | 471.00 s Done.\n#   # [Task 21/24]  Current/Best:   46.91/ 227.99 GFLOPS | Progress: (308/1000) | 219.18 s Done.\n#   # [Task 22/24]  Current/Best:   13.33/ 207.66 GFLOPS | Progress: (1000/1000) | 761.74 s Done.\n#   # [Task 23/24]  Current/Best:   53.29/ 192.98 GFLOPS | Progress: (1000/1000) | 799.90 s Done.\n#   # [Task 24/24]  Current/Best:   25.03/ 146.14 GFLOPS | Progress: (1000/1000) | 1112.55 s Done.\n\n################################################################################\n# Compiling an Optimized Model with Tuning Data\n# ----------------------------------------------\n#\n# As an output of the tuning process above, we obtained the tuning records\n# stored in ``resnet-50-v2-autotuning.json``. The compiler will use the results to\n# generate high performance code for the model on your specified target.\n#\n# Now that tuning data for the model has been collected, we can re-compile the\n# model using optimized operators to speed up our computations.\n\nwith autotvm.apply_history_best(tuning_option[\"tuning_records\"]):\n    with tvm.transform.PassContext(opt_level=3, config={}):\n        lib = relay.build(mod, target=target, params=params)\n\ndev = tvm.device(str(target), 0)\nmodule = graph_executor.GraphModule(lib[\"default\"](dev))\n\n################################################################################\n# Verify that the optimized model runs and produces the same results:\n\ndtype = \"float32\"\nmodule.set_input(input_name, img_data)\nmodule.run()\noutput_shape = (1, 1000)\ntvm_output = module.get_output(0, tvm.nd.empty(output_shape)).numpy()\n\nscores = softmax(tvm_output)\nscores = np.squeeze(scores)\nranks = np.argsort(scores)[::-1]\nfor rank in ranks[0:5]:\n    print(\"class='%s' with probability=%f\" % (labels[rank], scores[rank]))\n\n################################################################################\n# Verifying that the predictions are the same:\n#\n# .. code-block:: bash\n#\n#   # class='n02123045 tabby, tabby cat' with probability=0.610550\n#   # class='n02123159 tiger cat' with probability=0.367181\n#   # class='n02124075 Egyptian cat' with probability=0.019365\n#   # class='n02129604 tiger, Panthera tigris' with probability=0.001273\n#   # class='n04040759 radiator' with probability=0.000261\n\n################################################################################\n# Comparing the Tuned and Untuned Models\n# --------------------------------------\n# We want to collect some basic performance data associated with this optimized\n# model to compare it to the unoptimized model. Depending on your underlying\n# hardware, number of iterations, and other factors, you should see a performance\n# improvement in comparing the optimized model to the unoptimized model.\n\nimport timeit\n\ntiming_number = 10\ntiming_repeat = 10\noptimized = (\n    np.array(timeit.Timer(lambda: module.run()).repeat(repeat=timing_repeat, number=timing_number))\n    * 1000\n    / timing_number\n)\noptimized = {\"mean\": np.mean(optimized), \"median\": np.median(optimized), \"std\": np.std(optimized)}\n\n\nprint(\"optimized: %s\" % (optimized))\nprint(\"unoptimized: %s\" % (unoptimized))\n\n################################################################################\n# Final Remarks\n# -------------\n#\n# In this tutorial, we gave a short example of how to use the TVM Python API\n# to compile, run, and tune a model. We also discussed the need for pre and\n# post-processing of inputs and outputs. After the tuning process, we\n# demonstrated how to compare the performance of the unoptimized and optimize\n# models.\n#\n# Here we presented a simple example using ResNet-50 v2 locally. However, TVM\n# supports many more features including cross-compilation, remote execution and\n# profiling/benchmarking.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/cross_compilation_and_rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-cross-compilation-and-rpc:\n\nCross Compilation and RPC\n=========================\n**Author**: `Ziheng Jiang <https://github.com/ZihengJiang/>`_, `Lianmin Zheng <https://github.com/merrymercy/>`_\n\nThis tutorial introduces cross compilation and remote device\nexecution with RPC in TVM.\n\nWith cross compilation and RPC, you can **compile a program on your\nlocal machine then run it on the remote device**. It is useful when\nthe remote device resource are limited, like Raspberry Pi and mobile\nplatforms. In this tutorial, we will use the Raspberry Pi for a CPU example\nand the Firefly-RK3399 for an OpenCL example.\n\"\"\"\n\n######################################################################\n# Build TVM Runtime on Device\n# ---------------------------\n#\n# The first step is to build the TVM runtime on the remote device.\n#\n# .. note::\n#\n#   All instructions in both this section and the next section should be\n#   executed on the target device, e.g. Raspberry Pi.  We assume the target\n#   is running Linux.\n#\n# Since we do compilation on the local machine, the remote device is only used\n# for running the generated code. We only need to build the TVM runtime on\n# the remote device.\n#\n# .. code-block:: bash\n#\n#   git clone --recursive https://github.com/apache/tvm tvm\n#   cd tvm\n#   make runtime -j2\n#\n# After building the runtime successfully, we need to set environment variables\n# in :code:`~/.bashrc` file. We can edit :code:`~/.bashrc`\n# using :code:`vi ~/.bashrc` and add the line below (Assuming your TVM\n# directory is in :code:`~/tvm`):\n#\n# .. code-block:: bash\n#\n#   export PYTHONPATH=$PYTHONPATH:~/tvm/python\n#\n# To update the environment variables, execute :code:`source ~/.bashrc`.\n\n######################################################################\n# Set Up RPC Server on Device\n# ---------------------------\n# To start an RPC server, run the following command on your remote device\n# (Which is Raspberry Pi in this example).\n#\n#   .. code-block:: bash\n#\n#     python -m tvm.exec.rpc_server --host 0.0.0.0 --port=9090\n#\n# If you see the line below, it means the RPC server started\n# successfully on your device.\n#\n#    .. code-block:: bash\n#\n#      INFO:root:RPCServer: bind to 0.0.0.0:9090\n#\n\n######################################################################\n# Declare and Cross Compile Kernel on Local Machine\n# -------------------------------------------------\n#\n# .. note::\n#\n#   Now we go back to the local machine, which has a full TVM installed\n#   (with LLVM).\n#\n# Here we will declare a simple kernel on the local machine:\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import rpc\nfrom tvm.contrib import utils\n\nn = tvm.runtime.convert(1024)\nA = te.placeholder((n,), name=\"A\")\nB = te.compute((n,), lambda i: A[i] + 1.0, name=\"B\")\ns = te.create_schedule(B.op)\n\n######################################################################\n# Then we cross compile the kernel.\n# The target should be 'llvm -mtriple=armv7l-linux-gnueabihf' for\n# Raspberry Pi 3B, but we use 'llvm' here to make this tutorial runnable\n# on our webpage building server. See the detailed note in the following block.\n\nlocal_demo = True\n\nif local_demo:\n    target = \"llvm\"\nelse:\n    target = \"llvm -mtriple=armv7l-linux-gnueabihf\"\n\nfunc = tvm.build(s, [A, B], target=target, name=\"add_one\")\n# save the lib at a local temp folder\ntemp = utils.tempdir()\npath = temp.relpath(\"lib.tar\")\nfunc.export_library(path)\n\n######################################################################\n# .. note::\n#\n#   To run this tutorial with a real remote device, change :code:`local_demo`\n#   to False and replace :code:`target` in :code:`build` with the appropriate\n#   target triple for your device. The target triple which might be\n#   different for different devices. For example, it is\n#   :code:`'llvm -mtriple=armv7l-linux-gnueabihf'` for Raspberry Pi 3B and\n#   :code:`'llvm -mtriple=aarch64-linux-gnu'` for RK3399.\n#\n#   Usually, you can query the target by running :code:`gcc -v` on your\n#   device, and looking for the line starting with :code:`Target:`\n#   (Though it may still be a loose configuration.)\n#\n#   Besides :code:`-mtriple`, you can also set other compilation options\n#   like:\n#\n#   * -mcpu=<cpuname>\n#       Specify a specific chip in the current architecture to generate code for. By default this is inferred from the target triple and autodetected to the current architecture.\n#   * -mattr=a1,+a2,-a3,...\n#       Override or control specific attributes of the target, such as whether SIMD operations are enabled or not. The default set of attributes is set by the current CPU.\n#       To get the list of available attributes, you can do:\n#\n#       .. code-block:: bash\n#\n#         llc -mtriple=<your device target triple> -mattr=help\n#\n#   These options are consistent with `llc <http://llvm.org/docs/CommandGuide/llc.html>`_.\n#   It is recommended to set target triple and feature set to contain specific\n#   feature available, so we can take full advantage of the features of the\n#   board.\n#   You can find more details about cross compilation attributes from\n#   `LLVM guide of cross compilation <https://clang.llvm.org/docs/CrossCompilation.html>`_.\n\n######################################################################\n# Run CPU Kernel Remotely by RPC\n# ------------------------------\n# We show how to run the generated CPU kernel on the remote device.\n# First we obtain an RPC session from remote device.\n\nif local_demo:\n    remote = rpc.LocalSession()\nelse:\n    # The following is my environment, change this to the IP address of your target device\n    host = \"10.77.1.162\"\n    port = 9090\n    remote = rpc.connect(host, port)\n\n######################################################################\n# Upload the lib to the remote device, then invoke a device local\n# compiler to relink them. Now `func` is a remote module object.\n\nremote.upload(path)\nfunc = remote.load_module(\"lib.tar\")\n\n# create arrays on the remote device\ndev = remote.cpu()\na = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\nb = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n# the function will run on the remote device\nfunc(a, b)\nnp.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n######################################################################\n# When you want to evaluate the performance of the kernel on the remote\n# device, it is important to avoid the overhead of network.\n# :code:`time_evaluator` will returns a remote function that runs the\n# function over number times, measures the cost per run on the remote\n# device and returns the measured cost. Network overhead is excluded.\n\ntime_f = func.time_evaluator(func.entry_name, dev, number=10)\ncost = time_f(a, b).mean\nprint(\"%g secs/op\" % cost)\n\n#########################################################################\n# Run OpenCL Kernel Remotely by RPC\n# ---------------------------------\n# For remote OpenCL devices, the workflow is almost the same as above.\n# You can define the kernel, upload files, and run via RPC.\n#\n# .. note::\n#\n#    Raspberry Pi does not support OpenCL, the following code is tested on\n#    Firefly-RK3399. You may follow this `tutorial <https://gist.github.com/mli/585aed2cec0b5178b1a510f9f236afa2>`_\n#    to setup the OS and OpenCL driver for RK3399.\n#\n#    Also we need to build the runtime with OpenCL enabled on rk3399 board. In the TVM\n#    root directory, execute\n#\n# .. code-block:: bash\n#\n#    cp cmake/config.cmake .\n#    sed -i \"s/USE_OPENCL OFF/USE_OPENCL ON/\" config.cmake\n#    make runtime -j4\n#\n# The following function shows how we run an OpenCL kernel remotely\n\n\ndef run_opencl():\n    # NOTE: This is the setting for my rk3399 board. You need to modify\n    # them according to your environment.\n    opencl_device_host = \"10.77.1.145\"\n    opencl_device_port = 9090\n    target = tvm.target.Target(\"opencl\", host=\"llvm -mtriple=aarch64-linux-gnu\")\n\n    # create schedule for the above \"add one\" compute declaration\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=32)\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    func = tvm.build(s, [A, B], target=target)\n\n    remote = rpc.connect(opencl_device_host, opencl_device_port)\n\n    # export and upload\n    path = temp.relpath(\"lib_cl.tar\")\n    func.export_library(path)\n    remote.upload(path)\n    func = remote.load_module(\"lib_cl.tar\")\n\n    # run\n    dev = remote.cl()\n    a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n    b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n    func(a, b)\n    np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n    print(\"OpenCL test passed!\")\n\n\n######################################################################\n# Summary\n# -------\n# This tutorial provides a walk through of cross compilation and RPC\n# features in TVM.\n#\n# - Set up an RPC server on the remote device.\n# - Set up the target device configuration to cross compile the kernels on the\n#   local machine.\n# - Upload and run the kernels remotely via the RPC API.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/install.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nInstalling TVM\n==============\n**Authors**:\n`Jocelyn Shiue <https://github.com/>`_,\n`Chris Hoge <https://github.com/hogepodge>`_\n\nDepending on your needs and your working environment, there are a few different\nmethods for installing TVM. These include:\n\n* Installing from source\n* Installing from third-party binary package.\n\"\"\"\n\n################################################################################\n# Installing From Source\n# ----------------------\n# Installing from source is the recommended method for installing TVM. It will\n# allow you to enable specific features such as GPU support, microcontroller\n# support (microTVM), and a debugging runtime, and other features. You will also\n# want to install from source if you want to actively contribute to the TVM\n# project. The full instructions are on the :ref:`Install TVM From Source\n# <install-from-source>` page.\n\n################################################################################\n# Installing From Binary Packages\n# --------------------------------\n# You may install convenient third party binary package distributions to\n# quickly try things out. TLCPack is a third party volunteer community that\n# builds binary packages from TVM source. It offers a support matrix with\n# instructions to install on different platforms, with different features.\n# Check out  `TLCPack <https://tlcpack.ai>`_ to learn more. Note that the\n# third party binary packages could contain additional licensing terms for\n# the hardware drivers that are bundled with it.\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/intro_topi.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-topi:\n\nIntroduction to TOPI\n====================\n**Author**: `Ehsan M. Kermani <https://github.com/ehsanmok>`_\n\nThis is an introductory tutorial to TVM Operator Inventory (TOPI).\nTOPI provides numpy-style generic operations and schedules with higher abstractions than TVM.\nIn this tutorial, we will see how TOPI can save us from writing boilerplate code in TVM.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nimport numpy as np\n\n######################################################################\n# Basic example\n# -------------\n# Let's revisit the sum of rows operation (equivalent to :code:`B = numpy.sum(A, axis=1)`') \\\n# To compute the sum of rows of a two dimensional TVM tensor A, we should\n# specify the symbolic operation as well as schedule as follows\n#\nn = te.var(\"n\")\nm = te.var(\"m\")\nA = te.placeholder((n, m), name=\"A\")\nk = te.reduce_axis((0, m), \"k\")\nB = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\ns = te.create_schedule(B.op)\n\n######################################################################\n# and to examine the IR code in human readable format, we can do\n#\nprint(tvm.lower(s, [A], simple_mode=True))\n\n######################################################################\n# However, for such a common operation we had to define the reduce axis ourselves as well as explicit computation with\n# :code:`te.compute`. Imagine for more complicated operations how much details we need to provide.\n# Fortunately, we can replace those two lines with simple :code:`topi.sum` much like :code:`numpy.sum`\n#\nC = topi.sum(A, axis=1)\nts = te.create_schedule(C.op)\nprint(tvm.lower(ts, [A], simple_mode=True))\n\n######################################################################\n# Numpy-style operator overloading\n# --------------------------------\n# We can add two tensors using :code:`topi.broadcast_add` that have correct (broadcastable with specific) shapes.\n# Even shorter, TOPI provides operator overloading for such common operations. For example,\n#\nx, y = 100, 10\na = te.placeholder((x, y, y), name=\"a\")\nb = te.placeholder((y, y), name=\"b\")\nc = a + b  # same as topi.broadcast_add\nd = a * b  # same as topi.broadcast_mul\n\n######################################################################\n# Overloaded with the same syntax, TOPI handles broadcasting a primitive (`int`, `float`) to a tensor :code:`d - 3.14`.\n\n######################################################################\n# Generic schedules and fusing operations\n# ---------------------------------------\n# Up to now, we have seen an example of how TOPI can save us from writing explicit computations in lower level API.\n# But it doesn't stop here. Still we did the scheduling as before. TOPI also provides higher level\n# scheduling recipes depending on a given context. For example, for CUDA,\n# we can schedule the following series of operations ending with :code:`topi.sum` using only\n# :code:`topi.generic.schedule_reduce`\n#\ne = topi.elemwise_sum([c, d])\nf = e / 2.0\ng = topi.sum(f)\nwith tvm.target.cuda():\n    sg = topi.cuda.schedule_reduce(g)\n    print(tvm.lower(sg, [a, b], simple_mode=True))\n\n######################################################################\n# As you can see, scheduled stages of computation have been accumulated and we can examine them by\n#\nprint(sg.stages)\n\n######################################################################\n# We can test the correctness by comparing with :code:`numpy` result as follows\n#\nfunc = tvm.build(sg, [a, b, g], \"cuda\")\ndev = tvm.cuda(0)\na_np = np.random.uniform(size=(x, y, y)).astype(a.dtype)\nb_np = np.random.uniform(size=(y, y)).astype(b.dtype)\ng_np = np.sum(np.add(a_np + b_np, a_np * b_np) / 2.0)\na_nd = tvm.nd.array(a_np, dev)\nb_nd = tvm.nd.array(b_np, dev)\ng_nd = tvm.nd.array(np.zeros(g_np.shape, dtype=g_np.dtype), dev)\nfunc(a_nd, b_nd, g_nd)\ntvm.testing.assert_allclose(g_nd.numpy(), g_np, rtol=1e-5)\n\n######################################################################\n# TOPI also provides common neural nets operations such as _softmax_ with optimized schedule\n#\ntarray = te.placeholder((512, 512), name=\"tarray\")\nsoftmax_topi = topi.nn.softmax(tarray)\nwith tvm.target.Target(\"cuda\"):\n    sst = topi.cuda.schedule_softmax(softmax_topi)\n    print(tvm.lower(sst, [tarray], simple_mode=True))\n\n######################################################################\n# Fusing convolutions\n# -------------------\n# We can fuse :code:`topi.nn.conv2d` and :code:`topi.nn.relu` together.\n#\n# .. note::\n#\n#    TOPI functions are all generic functions. They have different implementations\n#    for different backends to optimize for performance.\n#    For each backend, it is necessary to call them under a target scope for both\n#    compute declaration and schedule. TVM will choose the right function to call with\n#    the target information.\n\ndata = te.placeholder((1, 3, 224, 224))\nkernel = te.placeholder((10, 3, 5, 5))\n\nwith tvm.target.Target(\"cuda\"):\n    conv = topi.cuda.conv2d_nchw(data, kernel, 1, 2, 1)\n    out = topi.nn.relu(conv)\n    sconv = topi.cuda.schedule_conv2d_nchw([out])\n    print(tvm.lower(sconv, [data, kernel], simple_mode=True))\n\n######################################################################\n# Summary\n# -------\n# In this tutorial, we have seen\n#\n# - How to use TOPI API for common operations with numpy-style operators.\n# - How TOPI facilitates generic schedules and operator fusion for a context, to generate optimized kernel codes.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/introduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nIntroduction\n============\n**Authors**:\n`Jocelyn Shiue <https://github.com/>`_,\n`Chris Hoge <https://github.com/hogepodge>`_,\n`Lianmin Zheng <https://github.com/merrymercy>`_\n\nApache TVM is an open source machine learning compiler framework for CPUs,\nGPUs, and machine learning accelerators. It aims to enable machine learning\nengineers to optimize and run computations efficiently on any hardware backend.\nThe purpose of this tutorial is to take a guided tour through all of the major\nfeatures of TVM by defining and demonstrating key concepts. A new user should\nbe able to work through the tutorial from start to finish and be able to\noperate TVM for automatic model optimization, while having a basic\nunderstanding of the TVM architecture and how it works.\n\nContents\n--------\n\n#. :doc:`Introduction <introduction>`\n#. :doc:`Installing TVM <install>`\n#. :doc:`Compiling and Optimizing a Model with the Command Line Interface <tvmc_command_line_driver>`\n#. :doc:`Compiling and Optimizing a Model with the Python Interface <autotvm_relay_x86>`\n#. :doc:`Working with Operators Using Tensor Expression <tensor_expr_get_started>`\n#. :doc:`Optimizing Operators with Templates and AutoTVM <autotvm_matmul_x86>`\n#. :doc:`Optimizing Operators with Template-free AutoScheduler <auto_scheduler_matmul_x86>`\n#. :doc:`Cross Compilation and Remote Procedure Calls (RPC) <cross_compilation_and_rpc>`\n#. :doc:`Compiling Deep Learning Models for GPUs <relay_quick_start>`\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# An Overview of TVM and Model Optimization\n# =========================================\n#\n# The diagram below illustrates the steps a machine model takes as it is\n# transformed with the TVM optimizing compiler framework.\n#\n# .. image:: https://raw.githubusercontent.com/apache/tvm-site/main/images/tutorial/overview.png\n#   :width: 100%\n#   :alt: A High Level View of TVM\n#\n# 1. Import the model from a framework like *Tensorflow*, *PyTorch*, or *Onnx*.\n#    The importer layer is where TVM can ingest models from other frameworks, like\n#    Tensorflow, PyTorch, or ONNX. The level of support that TVM offers for each\n#    frontend varies as we are constantly improving the open source project. If\n#    you're having issues importing your model into TVM, you may want to try\n#    converting it to ONNX.\n#\n# 2. Translate to *Relay*, TVM's high-level model language.\n#    A model that has been imported into TVM is represented in Relay. Relay is a\n#    functional language and intermediate representation (IR) for neural networks.\n#    It has support for:\n#\n#    - Traditional data flow-style representations\n#    - Functional-style scoping, let-binding which makes it a fully featured\n#      differentiable language\n#    - Ability to allow the user to mix the two programming styles\n#\n#    Relay applies graph-level optimization passes to optimize the model.\n#\n# 3. Lower to *Tensor Expression* (TE) representation. Lowering is when a\n#    higher-level representation is transformed into a lower-level\n#    representation. After applying the high-level optimizations, Relay\n#    runs FuseOps pass to partition the model into many small subgraphs and lowers\n#    the subgraphs to TE representation. Tensor Expression (TE) is a\n#    domain-specific language for describing tensor computations.\n#    TE also provides several *schedule* primitives to specify low-level loop\n#    optimizations, such as tiling, vectorization, parallelization,\n#    unrolling, and fusion.\n#    To aid in the process of converting Relay representation into TE representation,\n#    TVM includes a Tensor Operator Inventory (TOPI) that has pre-defined\n#    templates of common tensor operators (e.g., conv2d, transpose).\n#\n# 4. Search for the best schedule using the auto-tuning module *AutoTVM* or *AutoScheduler*.\n#    A schedule specifies the low-level loop optimizations for an operator or\n#    subgraph defined in TE. Auto-tuning modules search for the best schedule\n#    and compare them with cost models and on-device measurements.\n#    There are two auto-tuning modules in TVM.\n#\n#    - **AutoTVM**: A template-based auto-tuning module. It runs search algorithms\n#      to find the best values for the tunable knobs in a user-defined template.\n#      For common operators, their templates are already provided in TOPI.\n#    - **AutoScheduler (a.k.a. Ansor)**: A template-free auto-tuning module.\n#      It does not require pre-defined schedule templates. Instead, it generates\n#      the search space automatically by analyzing the computation definition.\n#      It then searches for the best schedule in the generated search space.\n#\n# 5. Choose the optimal configurations for model compilation. After tuning, the\n#    auto-tuning module generates tuning records in JSON format. This step\n#    picks the best schedule for each subgraph.\n#\n# 6. Lower to Tensor Intermediate Representation (TIR), TVM's low-level\n#    intermediate representation. After selecting the optimal configurations\n#    based on the tuning step, each TE subgraph is lowered to TIR and be\n#    optimized by low-level optimization passes. Next, the optimized TIR is\n#    lowered to the target compiler of the hardware platform.\n#    This is the final code generation phase to produce an optimized model\n#    that can be deployed into production. TVM supports several different\n#    compiler backends including:\n#\n#    - LLVM, which can target arbitrary microprocessor architecture including\n#      standard x86 and ARM processors, AMDGPU and NVPTX code generation, and any\n#      other platform supported by LLVM.\n#    - Specialized compilers, such as NVCC, NVIDIA's compiler.\n#    - Embedded and specialized targets, which are implemented through TVM's\n#      Bring Your Own Codegen (BYOC) framework.\n#\n# 7. Compile down to machine code. At the end of this process, the\n#    compiler-specific generated code can be lowered to machine code.\n#\n#    TVM can compile models down to a linkable object module, which can then be\n#    run with a lightweight TVM runtime that provides C APIs to dynamically\n#    load the model, and entry points for other languages such as Python and\n#    Rust. TVM can also build a bundled deployment in which the runtime is\n#    combined with the model in a single package.\n#\n# The remainder of the tutorial will cover these aspects of TVM in more detail.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/relay_quick_start.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-relay-quick-start:\n\nQuick Start Tutorial for Compiling Deep Learning Models\n=======================================================\n**Author**: `Yao Wang <https://github.com/kevinthesun>`_, `Truman Tian <https://github.com/SiNZeRo>`_\n\nThis example shows how to build a neural network with Relay python frontend and\ngenerates a runtime library for Nvidia GPU with TVM.\nNotice that you need to build TVM with cuda and llvm enabled.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n######################################################################\n# Overview for Supported Hardware Backend of TVM\n# ----------------------------------------------\n# The image below shows hardware backend currently supported by TVM:\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/tvm_support_list.png\n#      :align: center\n#\n# In this tutorial, we'll choose cuda and llvm as target backends.\n# To begin with, let's import Relay and TVM.\n\nimport numpy as np\n\nfrom tvm import relay\nfrom tvm.relay import testing\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import graph_executor\nimport tvm.testing\n\n######################################################################\n# Define Neural Network in Relay\n# ------------------------------\n# First, let's define a neural network with relay python frontend.\n# For simplicity, we'll use pre-defined resnet-18 network in Relay.\n# Parameters are initialized with Xavier initializer.\n# Relay also supports other model formats such as MXNet, CoreML, ONNX and\n# Tensorflow.\n#\n# In this tutorial, we assume we will do inference on our device and\n# the batch size is set to be 1. Input images are RGB color images of\n# size 224 * 224. We can call the\n# :py:meth:`tvm.relay.expr.TupleWrapper.astext()` to show the network\n# structure.\n\nbatch_size = 1\nnum_class = 1000\nimage_shape = (3, 224, 224)\ndata_shape = (batch_size,) + image_shape\nout_shape = (batch_size, num_class)\n\nmod, params = relay.testing.resnet.get_workload(\n    num_layers=18, batch_size=batch_size, image_shape=image_shape\n)\n\n# set show_meta_data=True if you want to show meta data\nprint(mod.astext(show_meta_data=False))\n\n######################################################################\n# Compilation\n# -----------\n# Next step is to compile the model using the Relay/TVM pipeline.\n# Users can specify the optimization level of the compilation.\n# Currently this value can be 0 to 3. The optimization passes include\n# operator fusion, pre-computation, layout transformation and so on.\n#\n# :py:func:`relay.build` returns three components: the execution graph in\n# json format, the TVM module library of compiled functions specifically\n# for this graph on the target hardware, and the parameter blobs of\n# the model. During the compilation, Relay does the graph-level\n# optimization while TVM does the tensor-level optimization, resulting\n# in an optimized runtime module for model serving.\n#\n# We'll first compile for Nvidia GPU. Behind the scene, :py:func:`relay.build`\n# first does a number of graph-level optimizations, e.g. pruning, fusing, etc.,\n# then registers the operators (i.e. the nodes of the optimized graphs) to\n# TVM implementations to generate a `tvm.module`.\n# To generate the module library, TVM will first transfer the high level IR\n# into the lower intrinsic IR of the specified target backend, which is CUDA\n# in this example. Then the machine code will be generated as the module library.\n\nopt_level = 3\ntarget = tvm.target.cuda()\nwith tvm.transform.PassContext(opt_level=opt_level):\n    lib = relay.build(mod, target, params=params)\n\n#####################################################################\n# Run the generate library\n# ------------------------\n# Now we can create graph executor and run the module on Nvidia GPU.\n\n# create random input\ndev = tvm.cuda()\ndata = np.random.uniform(-1, 1, size=data_shape).astype(\"float32\")\n# create module\nmodule = graph_executor.GraphModule(lib[\"default\"](dev))\n# set input and parameters\nmodule.set_input(\"data\", data)\n# run\nmodule.run()\n# get output\nout = module.get_output(0, tvm.nd.empty(out_shape)).numpy()\n\n# Print first 10 elements of output\nprint(out.flatten()[0:10])\n\n######################################################################\n# Save and Load Compiled Module\n# -----------------------------\n# We can also save the graph, lib and parameters into files and load them\n# back in deploy environment.\n\n####################################################\n\n# save the graph, lib and params into separate files\nfrom tvm.contrib import utils\n\ntemp = utils.tempdir()\npath_lib = temp.relpath(\"deploy_lib.tar\")\nlib.export_library(path_lib)\nprint(temp.listdir())\n\n####################################################\n\n# load the module back.\nloaded_lib = tvm.runtime.load_module(path_lib)\ninput_data = tvm.nd.array(data)\n\nmodule = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\nmodule.run(data=input_data)\nout_deploy = module.get_output(0).numpy()\n\n# Print first 10 elements of output\nprint(out_deploy.flatten()[0:10])\n\n# check whether the output from deployed module is consistent with original one\ntvm.testing.assert_allclose(out_deploy, out, atol=1e-5)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/tensor_expr_get_started.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-tensor-expr-get-started:\n\nWorking with Operators Using Tensor Expression\n==============================================\n**Author**: `Tianqi Chen <https://tqchen.github.io>`_\n\nIn this tutorial we will turn our attention to how TVM works with Tensor\nExpression (TE) to define tensor computations and apply loop optimizations. TE\ndescribes tensor computations in a pure functional language (that is each\nexpression has no side effects). When viewed in context of the TVM as a whole,\nRelay describes a computation as a set of operators, and each of these\noperators can be represented as a TE expression where each TE expression takes\ninput tensors and produces an output tensor.\n\nThis is an introductory tutorial to the Tensor Expression language in TVM. TVM\nuses a domain specific tensor expression for efficient kernel construction. We\nwill demonstrate the basic workflow with two examples of using the tensor expression\nlanguage. The first example introduces TE and scheduling with vector\naddition. The second expands on these concepts with a step-by-step optimization\nof a matrix multiplication with TE. This matrix multiplication example will\nserve as the comparative basis for future tutorials covering more advanced\nfeatures of TVM.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# Example 1: Writing and Scheduling Vector Addition in TE for CPU\n# ---------------------------------------------------------------\n#\n# Let's look at an example in Python in which we will implement a TE for\n# vector addition, followed by a schedule targeted towards a CPU.\n# We begin by initializing a TVM environment.\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n################################################################################\n# You will get better performance if you can identify the CPU you are targeting\n# and specify it. If you're using LLVM, you can get this information from the\n# command ``llc --version`` to get the CPU type, and you can check\n# ``/proc/cpuinfo`` for additional extensions that your processor might\n# support. For example, you can use ``llvm -mcpu=skylake-avx512`` for CPUs with\n# AVX-512 instructions.\n\ntgt = tvm.target.Target(target=\"llvm\", host=\"llvm\")\n\n################################################################################\n# Describing the Vector Computation\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# We describe a vector addition computation. TVM adopts tensor semantics, with\n# each intermediate result represented as a multi-dimensional array. The user\n# needs to describe the computation rule that generates the tensors. We first\n# define a symbolic variable ``n`` to represent the shape. We then define two\n# placeholder Tensors, ``A`` and ``B``, with given shape ``(n,)``. We then\n# describe the result tensor ``C``, with a ``compute`` operation. The\n# ``compute`` defines a computation, with the output conforming to the\n# specified tensor shape and the computation to be performed at each position\n# in the tensor defined by the lambda function. Note that while ``n`` is a\n# variable, it defines a consistent shape between the ``A``, ``B`` and ``C``\n# tensors. Remember, no actual computation happens during this phase, as we\n# are only declaring how the computation should be done.\n\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.placeholder((n,), name=\"B\")\nC = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n\n################################################################################\n# .. admonition:: Lambda Functions\n#\n#   The second argument to the ``te.compute`` method is the function that\n#   performs the computation. In this example, we're using an anonymous function,\n#   also known as a ``lambda`` function, to define the computation, in this case\n#   addition on the ``i``\\th element of ``A`` and ``B``.\n\n################################################################################\n# Create a Default Schedule for the Computation\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# While the above lines describe the computation rule, we can compute ``C`` in\n# many different ways to fit different devices. For a tensor with multiple\n# axes, you can choose which axis to iterate over first, or computations can be\n# split across different threads. TVM requires that the user to provide a\n# schedule, which is a description of how the computation should be performed.\n# Scheduling operations within TE can change loop orders, split computations\n# across different threads, and group blocks of data together, amongst other\n# operations. An important concept behind schedules is that they only describe\n# how the computation is performed, so different schedules for the same TE will\n# produce the same result.\n#\n# TVM allows you to create a naive schedule that will compute ``C`` in by\n# iterating in row major order.\n#\n# .. code-block:: c\n#\n#   for (int i = 0; i < n; ++i) {\n#     C[i] = A[i] + B[i];\n#   }\n\ns = te.create_schedule(C.op)\n\n######################################################################\n# Compile and Evaluate the Default Schedule\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# With the TE expression and a schedule, we can produce runnable code for our\n# target language and architecture, in this case LLVM and a CPU. We provide\n# TVM with the schedule, a list of the TE expressions that are in the schedule,\n# the target and host, and the name of the function we are producing. The result\n# of the output is a type-erased function that can be called directly from Python.\n#\n# In the following line, we use ``tvm.build`` to create a function. The build\n# function takes the schedule, the desired signature of the function (including\n# the inputs and outputs) as well as target language we want to compile to.\n\nfadd = tvm.build(s, [A, B, C], tgt, name=\"myadd\")\n\n################################################################################\n# Let's run the function, and compare the output to the same computation in\n# numpy. The compiled TVM function exposes a concise C API that can be invoked\n# from any language. We begin by creating a device, which is a device (CPU in this\n# example) that TVM can compile the schedule to. In this case the device is an\n# LLVM CPU target. We can then initialize the tensors in our device and\n# perform the custom addition operation. To verify that the computation is\n# correct, we can compare the result of the output of the c tensor to the same\n# computation performed by numpy.\n\ndev = tvm.device(tgt.kind.name, 0)\n\nn = 1024\na = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\nb = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\nc = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\nfadd(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n################################################################################\n# To get a comparison of how fast this version is compared to numpy, create a\n# helper function to run a profile of the TVM generated code.\nimport timeit\n\nnp_repeat = 100\nnp_running_time = timeit.timeit(\n    setup=\"import numpy\\n\"\n    \"n = 32768\\n\"\n    'dtype = \"float32\"\\n'\n    \"a = numpy.random.rand(n, 1).astype(dtype)\\n\"\n    \"b = numpy.random.rand(n, 1).astype(dtype)\\n\",\n    stmt=\"answer = a + b\",\n    number=np_repeat,\n)\nprint(\"Numpy running time: %f\" % (np_running_time / np_repeat))\n\n\ndef evaluate_addition(func, target, optimization, log):\n    dev = tvm.device(target.kind.name, 0)\n    n = 32768\n    a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n    c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n\n    evaluator = func.time_evaluator(func.entry_name, dev, number=10)\n    mean_time = evaluator(a, b, c).mean\n    print(\"%s: %f\" % (optimization, mean_time))\n\n    log.append((optimization, mean_time))\n\n\nlog = [(\"numpy\", np_running_time / np_repeat)]\nevaluate_addition(fadd, tgt, \"naive\", log=log)\n\n################################################################################\n# Updating the Schedule to Use Parallelism\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Now that we've illustrated the fundamentals of TE, let's go deeper into what\n# schedules do, and how they can be used to optimize tensor expressions for\n# different architectures. A schedule is a series of steps that are applied to\n# an expression to transform it in a number of different ways. When a schedule\n# is applied to an expression in TE, the inputs and outputs remain the same,\n# but when compiled the implementation of the expression can change. This\n# tensor addition, in the default schedule, is run serially but is easy to\n# parallelize across all of the processor threads. We can apply the parallel\n# schedule operation to our computation.\n\ns[C].parallel(C.op.axis[0])\n\n################################################################################\n# The ``tvm.lower`` command will generate the Intermediate Representation (IR)\n# of the TE, with the corresponding schedule. By lowering the expression as we\n# apply different schedule operations, we can see the effect of scheduling on\n# the ordering of the computation. We use the flag ``simple_mode=True`` to\n# return a readable C-style statement.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# It's now possible for TVM to run these blocks on independent threads. Let's\n# compile and run this new schedule with the parallel operation applied:\n\nfadd_parallel = tvm.build(s, [A, B, C], tgt, name=\"myadd_parallel\")\nfadd_parallel(a, b, c)\n\ntvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\nevaluate_addition(fadd_parallel, tgt, \"parallel\", log=log)\n\n################################################################################\n# Updating the Schedule to Use Vectorization\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Modern CPUs also have the ability to perform SIMD operations on floating\n# point values, and we can apply another schedule to our computation expression\n# to take advantage of this. Accomplishing this requires multiple steps: first\n# we have to split the schedule into inner and outer loops using the split\n# scheduling primitive. The inner loops can use vectorization to use SIMD\n# instructions using the vectorize scheduling primitive, then the outer loops\n# can be parallelized using the parallel scheduling primitive. Choose the split\n# factor to be the number of threads on your CPU.\n\n# Recreate the schedule, since we modified it with the parallel operation in\n# the previous example\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.placeholder((n,), name=\"B\")\nC = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n\ns = te.create_schedule(C.op)\n\n# This factor should be chosen to match the number of threads appropriate for\n# your CPU. This will vary depending on architecture, but a good rule is\n# setting this factor to equal the number of available CPU cores.\nfactor = 4\n\nouter, inner = s[C].split(C.op.axis[0], factor=factor)\ns[C].parallel(outer)\ns[C].vectorize(inner)\n\nfadd_vector = tvm.build(s, [A, B, C], tgt, name=\"myadd_parallel\")\n\nevaluate_addition(fadd_vector, tgt, \"vector\", log=log)\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Comparing the Different Schedules\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# We can now compare the different schedules\n\nbaseline = log[0][1]\nprint(\"%s\\t%s\\t%s\" % (\"Operator\".rjust(20), \"Timing\".rjust(20), \"Performance\".rjust(20)))\nfor result in log:\n    print(\n        \"%s\\t%s\\t%s\"\n        % (result[0].rjust(20), str(result[1]).rjust(20), str(result[1] / baseline).rjust(20))\n    )\n\n\n################################################################################\n# .. admonition:: Code Specialization\n#\n#   As you may have noticed, the declarations of ``A``, ``B`` and ``C`` all\n#   take the same shape argument, ``n``. TVM will take advantage of this to\n#   pass only a single shape argument to the kernel, as you will find in the\n#   printed device code. This is one form of specialization.\n#\n#   On the host side, TVM will automatically generate check code that checks\n#   the constraints in the parameters. So if you pass arrays with different\n#   shapes into fadd, an error will be raised.\n#\n#   We can do more specializations. For example, we can write :code:`n =\n#   tvm.runtime.convert(1024)` instead of :code:`n = te.var(\"n\")`, in the\n#   computation declaration. The generated function will only take vectors with\n#   length 1024.\n\n################################################################################\n# We've defined, scheduled, and compiled a vector addition operator, which we\n# were then able to execute on the TVM runtime. We can save the operator as a\n# library, which we can then load later using the TVM runtime.\n\n################################################################################\n# Targeting Vector Addition for GPUs (Optional)\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# TVM is capable of targeting multiple architectures. In the next example, we\n# will target compilation of the vector addition to GPUs.\n\n# If you want to run this code, change ``run_cuda = True``\n# Note that by default this example is not run in the docs CI.\n\nrun_cuda = False\nif run_cuda:\n    # Change this target to the correct backend for you gpu. For example: cuda (NVIDIA GPUs),\n    # rocm (Radeon GPUS), OpenCL (opencl).\n    tgt_gpu = tvm.target.Target(target=\"cuda\", host=\"llvm\")\n\n    # Recreate the schedule\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    print(type(C))\n\n    s = te.create_schedule(C.op)\n\n    bx, tx = s[C].split(C.op.axis[0], factor=64)\n\n    ################################################################################\n    # Finally we must bind the iteration axis bx and tx to threads in the GPU\n    # compute grid. The naive schedule is not valid for GPUs, and these are\n    # specific constructs that allow us to generate code that runs on a GPU.\n\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    ######################################################################\n    # Compilation\n    # -----------\n    # After we have finished specifying the schedule, we can compile it\n    # into a TVM function. By default TVM compiles into a type-erased\n    # function that can be directly called from the python side.\n    #\n    # In the following line, we use tvm.build to create a function.\n    # The build function takes the schedule, the desired signature of the\n    # function (including the inputs and outputs) as well as target language\n    # we want to compile to.\n    #\n    # The result of compilation fadd is a GPU device function (if GPU is\n    # involved) as well as a host wrapper that calls into the GPU\n    # function. fadd is the generated host wrapper function, it contains\n    # a reference to the generated device function internally.\n\n    fadd = tvm.build(s, [A, B, C], target=tgt_gpu, name=\"myadd\")\n\n    ################################################################################\n    # The compiled TVM function exposes a concise C API that can be invoked from\n    # any language.\n    #\n    # We provide a minimal array API in python to aid quick testing and prototyping.\n    # The array API is based on the `DLPack <https://github.com/dmlc/dlpack>`_ standard.\n    #\n    # - We first create a GPU device.\n    # - Then tvm.nd.array copies the data to the GPU.\n    # - ``fadd`` runs the actual computation\n    # - ``numpy()`` copies the GPU array back to the CPU (so we can verify correctness).\n    #\n    # Note that copying the data to and from the memory on the GPU is a required step.\n\n    dev = tvm.device(tgt_gpu.kind.name, 0)\n\n    n = 1024\n    a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n    c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n    fadd(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    ################################################################################\n    # Inspect the Generated GPU Code\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    # You can inspect the generated code in TVM. The result of tvm.build is a TVM\n    # Module. fadd is the host module that contains the host wrapper, it also\n    # contains a device module for the CUDA (GPU) function.\n    #\n    # The following code fetches the device module and prints the content code.\n\n    if (\n        tgt_gpu.kind.name == \"cuda\"\n        or tgt_gpu.kind.name == \"rocm\"\n        or tgt_gpu.kind.name.startswith(\"opencl\")\n    ):\n        dev_module = fadd.imported_modules[0]\n        print(\"-----GPU code-----\")\n        print(dev_module.get_source())\n    else:\n        print(fadd.get_source())\n\n################################################################################\n# Saving and Loading Compiled Modules\n# -----------------------------------\n# Besides runtime compilation, we can save the compiled modules into a file and\n# load them back later.\n#\n# The following code first performs the following steps:\n#\n# - It saves the compiled host module into an object file.\n# - Then it saves the device module into a ptx file.\n# - cc.create_shared calls a compiler (gcc) to create a shared library\n\nfrom tvm.contrib import cc\nfrom tvm.contrib import utils\n\ntemp = utils.tempdir()\nfadd.save(temp.relpath(\"myadd.o\"))\nif tgt.kind.name == \"cuda\":\n    fadd.imported_modules[0].save(temp.relpath(\"myadd.ptx\"))\nif tgt.kind.name == \"rocm\":\n    fadd.imported_modules[0].save(temp.relpath(\"myadd.hsaco\"))\nif tgt.kind.name.startswith(\"opencl\"):\n    fadd.imported_modules[0].save(temp.relpath(\"myadd.cl\"))\ncc.create_shared(temp.relpath(\"myadd.so\"), [temp.relpath(\"myadd.o\")])\nprint(temp.listdir())\n\n################################################################################\n# .. admonition:: Module Storage Format\n#\n#   The CPU (host) module is directly saved as a shared library (.so). There\n#   can be multiple customized formats of the device code. In our example, the\n#   device code is stored in ptx, as well as a meta data json file. They can be\n#   loaded and linked separately via import.\n\n################################################################################\n# Load Compiled Module\n# ~~~~~~~~~~~~~~~~~~~~\n# We can load the compiled module from the file system and run the code. The\n# following code loads the host and device module separately and links them\n# together. We can verify that the newly loaded function works.\n\nfadd1 = tvm.runtime.load_module(temp.relpath(\"myadd.so\"))\nif tgt.kind.name == \"cuda\":\n    fadd1_dev = tvm.runtime.load_module(temp.relpath(\"myadd.ptx\"))\n    fadd1.import_module(fadd1_dev)\n\nif tgt.kind.name == \"rocm\":\n    fadd1_dev = tvm.runtime.load_module(temp.relpath(\"myadd.hsaco\"))\n    fadd1.import_module(fadd1_dev)\n\nif tgt.kind.name.startswith(\"opencl\"):\n    fadd1_dev = tvm.runtime.load_module(temp.relpath(\"myadd.cl\"))\n    fadd1.import_module(fadd1_dev)\n\nfadd1(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n################################################################################\n# Pack Everything into One Library\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# In the above example, we store the device and host code separately. TVM also\n# supports export everything as one shared library. Under the hood, we pack\n# the device modules into binary blobs and link them together with the host\n# code. Currently we support packing of Metal, OpenCL and CUDA modules.\n\nfadd.export_library(temp.relpath(\"myadd_pack.so\"))\nfadd2 = tvm.runtime.load_module(temp.relpath(\"myadd_pack.so\"))\nfadd2(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n################################################################################\n# .. admonition:: Runtime API and Thread-Safety\n#\n#   The compiled modules of TVM do not depend on the TVM compiler. Instead,\n#   they only depend on a minimum runtime library. The TVM runtime library\n#   wraps the device drivers and provides thread-safe and device agnostic calls\n#   into the compiled functions.\n#\n#   This means that you can call the compiled TVM functions from any thread, on\n#   any GPUs, provided that you have compiled the code for that GPU.\n\n################################################################################\n# Generate OpenCL Code\n# --------------------\n# TVM provides code generation features into multiple backends. We can also\n# generate OpenCL code or LLVM code that runs on CPU backends.\n#\n# The following code blocks generate OpenCL code, creates array on an OpenCL\n# device, and verifies the correctness of the code.\n\nif tgt.kind.name.startswith(\"opencl\"):\n    fadd_cl = tvm.build(s, [A, B, C], tgt, name=\"myadd\")\n    print(\"------opencl code------\")\n    print(fadd_cl.imported_modules[0].get_source())\n    dev = tvm.cl(0)\n    n = 1024\n    a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n    c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n    fadd_cl(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n################################################################################\n# .. admonition:: TE Scheduling Primitives\n#\n#   TVM includes a number of different scheduling primitives:\n#\n#   - split: splits a specified axis into two axises by the defined factor.\n#   - tile: tiles will split a computation across two axes by the defined factors.\n#   - fuse: fuses two consecutive axises of one computation.\n#   - reorder: can reorder the axises of a computation into a defined order.\n#   - bind: can bind a computation to a specific thread, useful in GPU programming.\n#   - compute_at: by default, TVM will compute tensors at the outermost level\n#     of the function, or the root, by default. compute_at specifies that one\n#     tensor should be computed at the first axis of computation for another\n#     operator.\n#   - compute_inline: when marked inline, a computation will be expanded then\n#     inserted into the address where the tensor is required.\n#   - compute_root: moves a computation to the outermost layer, or root, of the\n#     function. This means that stage of the computation will be fully computed\n#     before it moves on to the next stage.\n#\n#   A complete description of these primitives can be found in the\n#   :ref:`Schedule Primitives <schedule_primitives>` docs page.\n\n################################################################################\n# Example 2: Manually Optimizing Matrix Multiplication with TE\n# ------------------------------------------------------------\n#\n# Now we will consider a second, more advanced example, demonstrating how with\n# just 18 lines of python code TVM speeds up a common matrix multiplication operation by 18x.\n#\n# **Matrix multiplication is a compute intensive operation. There are\n# two important optimizations for good CPU performance:**\n#\n# 1. Increase the cache hit rate of memory access. Both complex\n#    numerical computation and hot-spot memory access can be\n#    accelerated by a high cache hit rate. This requires us to\n#    transform the origin memory access pattern to a pattern that fits\n#    the cache policy.\n#\n# 2. SIMD (Single instruction multi-data), also known as the vector\n#    processing unit. On each cycle instead of processing a single\n#    value, SIMD can process a small batch of data.  This requires us\n#    to transform the data access pattern in the loop body in uniform\n#    pattern so that the LLVM backend can lower it to SIMD.\n#\n# The techniques used in this tutorial are a subset of tricks mentioned in this\n# `repository <https://github.com/flame/how-to-optimize-gemm>`_. Some of them\n# have been applied by TVM abstraction automatically, but some of them cannot\n# be automatically applied due to TVM constraints.\n\n################################################################################\n# Preparation and Performance Baseline\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# We begin by collecting performance data on the `numpy` implementation of\n# matrix multiplication.\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy\n\n# The size of the matrix\n# (M, K) x (K, N)\n# You are free to try out different shapes, sometimes TVM optimization outperforms numpy with MKL.\nM = 1024\nK = 1024\nN = 1024\n\n# The default tensor data type in tvm\ndtype = \"float32\"\n\n# You will want to adjust the target to match any CPU vector extensions you\n# might have. For example, if you're using using Intel AVX2 (Advanced Vector\n# Extensions) ISA for SIMD, you can get the best performance by changing the\n# following line to ``llvm -mcpu=core-avx2``, or specific type of CPU you use.\n# Recall that you're using llvm, you can get this information from the command\n# ``llc --version`` to get the CPU type, and you can check ``/proc/cpuinfo``\n# for additional extensions that your processor might support.\n\ntarget = tvm.target.Target(target=\"llvm\", host=\"llvm\")\ndev = tvm.device(target.kind.name, 0)\n\n# Random generated tensor for testing\na = tvm.nd.array(numpy.random.rand(M, K).astype(dtype), dev)\nb = tvm.nd.array(numpy.random.rand(K, N).astype(dtype), dev)\n\n# Repeatedly perform a matrix multiplication to get a performance baseline\n# for the default numpy implementation\nnp_repeat = 100\nnp_running_time = timeit.timeit(\n    setup=\"import numpy\\n\"\n    \"M = \" + str(M) + \"\\n\"\n    \"K = \" + str(K) + \"\\n\"\n    \"N = \" + str(N) + \"\\n\"\n    'dtype = \"float32\"\\n'\n    \"a = numpy.random.rand(M, K).astype(dtype)\\n\"\n    \"b = numpy.random.rand(K, N).astype(dtype)\\n\",\n    stmt=\"answer = numpy.dot(a, b)\",\n    number=np_repeat,\n)\nprint(\"Numpy running time: %f\" % (np_running_time / np_repeat))\n\nanswer = numpy.dot(a.numpy(), b.numpy())\n\n################################################################################\n# Now we write a basic matrix multiplication using TVM TE and verify that it\n# produces the same results as the numpy implementation. We also write a\n# function that will help us measure the performance of the schedule\n# optimizations.\n\n# TVM Matrix Multiplication using TE\nk = te.reduce_axis((0, K), \"k\")\nA = te.placeholder((M, K), name=\"A\")\nB = te.placeholder((K, N), name=\"B\")\nC = te.compute((M, N), lambda x, y: te.sum(A[x, k] * B[k, y], axis=k), name=\"C\")\n\n# Default schedule\ns = te.create_schedule(C.op)\nfunc = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\n\nc = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\nfunc(a, b, c)\ntvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\n\ndef evaluate_operation(s, vars, target, name, optimization, log):\n    func = tvm.build(s, [A, B, C], target=target, name=\"mmult\")\n    assert func\n\n    c = tvm.nd.array(numpy.zeros((M, N), dtype=dtype), dev)\n    func(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), answer, rtol=1e-5)\n\n    evaluator = func.time_evaluator(func.entry_name, dev, number=10)\n    mean_time = evaluator(a, b, c).mean\n    print(\"%s: %f\" % (optimization, mean_time))\n    log.append((optimization, mean_time))\n\n\nlog = []\n\nevaluate_operation(s, [A, B, C], target=target, name=\"mmult\", optimization=\"none\", log=log)\n\n################################################################################\n# Let's take a look at the intermediate representation of the operator and\n# default schedule using the TVM lower function. Note how the implementation is\n# essentially a naive implementation of a matrix multiplication, using three\n# nested loops over the indices of the A and B matrices.\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 1: Blocking\n# ~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# A important trick to enhance the cache hit rate is blocking, where you\n# structure memory access such that the inside a block is a small neighborhood\n# that has high memory locality. In this tutorial, we pick a block factor of\n# 32. This will result in a block that will fill a 32 * 32 * sizeof(float) area\n# of memory. This corresponds to a cache size of 4KB, in relation to a\n# reference cache size of 32 KB for L1 cache.\n#\n# We begin by creating a default schedule for the ``C`` operation, then apply a\n# ``tile`` scheduling primitive to it with the specified block factor, with the\n# scheduling primitive returning the resulting loop order from outermost to\n# innermost, as a vector ``[x_outer, y_outer, x_inner, y_inner]``. We then get\n# the reduction axis for output of the operation, and perform a split operation\n# on it using a factor of 4. This factor doesn't directly impact the blocking\n# optimization we're working on right now, but will be useful later when we\n# apply vectorization.\n#\n# Now that the operation has been blocked, we can reorder the computation to\n# put the reduction operation into the outermost loop of the computation,\n# helping to guarantee that the blocked data remains in cache. This completes\n# the schedule, and we can build and test the performance compared to the naive\n# schedule.\n\nbn = 32\n\n# Blocking by loop tiling\nxo, yo, xi, yi = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(k,) = s[C].op.reduce_axis\nko, ki = s[C].split(k, factor=4)\n\n# Hoist reduction domain outside the blocking loop\ns[C].reorder(xo, yo, ko, ki, xi, yi)\n\nevaluate_operation(s, [A, B, C], target=target, name=\"mmult\", optimization=\"blocking\", log=log)\n\n################################################################################\n# By reordering the computation to take advantage of caching, you should see a\n# significant improvement in the performance of the computation. Now, print the\n# internal representation and compare it to the original:\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 2: Vectorization\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Another important optimization trick is vectorization. When the memory access\n# pattern is uniform, the compiler can detect this pattern and pass the\n# continuous memory to the SIMD vector processor. In TVM, we can use the\n# ``vectorize`` interface to hint the compiler this pattern, taking advantage\n# of this hardware feature.\n#\n# In this tutorial, we chose to vectorize the inner loop row data since it is\n# already cache friendly from our previous optimizations.\n\n# Apply the vectorization optimization\ns[C].vectorize(yi)\n\nevaluate_operation(s, [A, B, C], target=target, name=\"mmult\", optimization=\"vectorization\", log=log)\n\n# The generalized IR after vectorization\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 3: Loop Permutation\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# If we look at the above IR, we can see the inner loop row data is vectorized\n# and B is transformed into PackedB (this is evident by the `(float32x32*)B2`\n# portion of the inner loop). The traversal of PackedB is sequential now. So we\n# will look at the access pattern of A. In current schedule, A is accessed\n# column by column which is not cache friendly. If we change the nested loop\n# order of `ki` and inner axes `xi`, the access pattern for A matrix will be\n# more cache friendly.\n\ns = te.create_schedule(C.op)\nxo, yo, xi, yi = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(k,) = s[C].op.reduce_axis\nko, ki = s[C].split(k, factor=4)\n\n# re-ordering\ns[C].reorder(xo, yo, ko, xi, ki, yi)\ns[C].vectorize(yi)\n\nevaluate_operation(\n    s, [A, B, C], target=target, name=\"mmult\", optimization=\"loop permutation\", log=log\n)\n\n# Again, print the new generalized IR\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 4: Array Packing\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Another important trick is array packing. This trick is to reorder the\n# storage dimension of the array to convert the continuous access pattern on\n# certain dimension to a sequential pattern after flattening.\n#\n# .. image:: https://github.com/dmlc/web-data/raw/main/tvm/tutorial/array-packing.png\n#    :align: center\n#\n# Just as it is shown in the figure above, after blocking the computations, we\n# can observe the array access pattern of B (after flattening), which is\n# regular but discontinuous. We expect that after some transformation we can\n# get a continuous access pattern. By reordering a ``[16][16]`` array to a\n# ``[16/4][16][4]`` array the access pattern of B will be sequential when\n# grabbing the corresponding value from the packed array.\n#\n# To accomplish this, we are going to have to start with a new default\n# schedule, taking into account the new packing of B. It's worth taking a\n# moment to comment on this: TE is a powerful and expressive language for\n# writing optimized operators, but it often requires some knowledge of the\n# underlying algorithm, data structures, and hardware target that you are\n# writing for. Later in the tutorial, we will discuss some of the options for\n# letting TVM take that burden. Regardless, let's move on with the new\n# optimized schedule.\n\n# We have to re-write the algorithm slightly.\npackedB = te.compute((N / bn, K, bn), lambda x, y, z: B[y, x * bn + z], name=\"packedB\")\nC = te.compute(\n    (M, N),\n    lambda x, y: te.sum(A[x, k] * packedB[y // bn, k, tvm.tir.indexmod(y, bn)], axis=k),\n    name=\"C\",\n)\n\ns = te.create_schedule(C.op)\n\nxo, yo, xi, yi = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n(k,) = s[C].op.reduce_axis\nko, ki = s[C].split(k, factor=4)\n\ns[C].reorder(xo, yo, ko, xi, ki, yi)\ns[C].vectorize(yi)\n\nx, y, z = s[packedB].op.axis\ns[packedB].vectorize(z)\ns[packedB].parallel(x)\n\nevaluate_operation(s, [A, B, C], target=target, name=\"mmult\", optimization=\"array packing\", log=log)\n\n# Here is the generated IR after array packing.\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 5: Optimizing Block Writing Through Caching\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Up to this point all of our optimizations have focused on efficiently\n# accessing and computing the data from the `A` and `B` matrices to compute the\n# `C` matrix. After the blocking optimization, the operator will write result\n# to `C` block by block, and the access pattern is not sequential. We can\n# address this by using a sequential cache array, using a combination of\n# `cache_write`, `compute_at`, and `unroll`to hold the block results and write\n# to `C` when all the block results are ready.\n\ns = te.create_schedule(C.op)\n\n# Allocate write cache\nCC = s.cache_write(C, \"global\")\n\nxo, yo, xi, yi = s[C].tile(C.op.axis[0], C.op.axis[1], bn, bn)\n\n# Write cache is computed at yo\ns[CC].compute_at(s[C], yo)\n\n# New inner axes\nxc, yc = s[CC].op.axis\n\n(k,) = s[CC].op.reduce_axis\nko, ki = s[CC].split(k, factor=4)\ns[CC].reorder(ko, xc, ki, yc)\ns[CC].unroll(ki)\ns[CC].vectorize(yc)\n\nx, y, z = s[packedB].op.axis\ns[packedB].vectorize(z)\ns[packedB].parallel(x)\n\nevaluate_operation(s, [A, B, C], target=target, name=\"mmult\", optimization=\"block caching\", log=log)\n\n# Here is the generated IR after write cache blocking.\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Optimization 6: Parallelization\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# So far, our computation is only designed to use a single core. Nearly all\n# modern processors have multiple cores, and computation can benefit from\n# running computations in parallel. The final optimization is to take advantage\n# of thread-level parallelization.\n\n# parallel\ns[C].parallel(xo)\n\nx, y, z = s[packedB].op.axis\ns[packedB].vectorize(z)\ns[packedB].parallel(x)\n\nevaluate_operation(\n    s, [A, B, C], target=target, name=\"mmult\", optimization=\"parallelization\", log=log\n)\n\n# Here is the generated IR after parallelization.\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n################################################################################\n# Summary of Matrix Multiplication Example\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# After applying the above simple optimizations with only 18 lines of code, our\n# generated code can begin to approach the performance of `numpy` with the Math\n# Kernel Library (MKL). Since we've been logging the performance as we've been\n# working, we can compare the results.\n\nbaseline = log[0][1]\nprint(\"%s\\t%s\\t%s\" % (\"Operator\".rjust(20), \"Timing\".rjust(20), \"Performance\".rjust(20)))\nfor result in log:\n    print(\n        \"%s\\t%s\\t%s\"\n        % (result[0].rjust(20), str(result[1]).rjust(20), str(result[1] / baseline).rjust(20))\n    )\n\n################################################################################\n# Note that the outputs on the web page reflect the running times on a\n# non-exclusive Docker container, and should be considered unreliable. It is\n# highly encouraged to run the tutorial by yourself to observe the performance\n# gain achieved by TVM, and to carefully work through each example to\n# understand the iterative improvements that are made to the matrix\n# multiplication operation.\n\n################################################################################\n# Final Notes and Summary\n# -----------------------\n# As mentioned earlier, how to apply optimizations using TE and scheduling\n# primitives can require some knowledge of the underlying architecture and\n# algorithms. However, TE was designed to act as a foundation for more complex\n# algorithms that can search the potential optimization. With the knowledge you\n# have from this introduction to TE, we can now begin to explore how TVM can\n# automate the schedule optimization process.\n#\n# This tutorial provided a walk-through of TVM Tensor Expression (TE) workflow\n# using a vector add and a matrix multiplication examples. The general workflow\n# is\n#\n# - Describe your computation via a series of operations.\n# - Describe how we want to compute use schedule primitives.\n# - Compile to the target function we want.\n# - Optionally, save the function to be loaded later.\n#\n# Upcoming tutorials expand on the matrix multiplication example, and show how\n# you can build generic templates of the matrix multiplication and other\n# operations with tunable parameters that allows you to automatically optimize\n# the computation for specific platforms.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/tensor_ir_blitz_course.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tir_blitz:\n\nBlitz Course to TensorIR\n========================\n**Author**: `Siyuan Feng <https://github.com/Hzfengsy>`_\n\nTensorIR is a domain specific language for deep learning programs serving two broad purposes:\n\n- An implementation for transforming and optimizing programs on various hardware backends.\n\n- An abstraction for automatic _tensorized_ program optimization.\n\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\nimport tvm\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nimport numpy as np\n\n################################################################################################\n# IRModule\n# --------\n# An IRModule is the central data structure in TVM, which contains deep learning programs.\n# It is the basic object of interest of IR transformation and model building.\n#\n# .. image:: https://raw.githubusercontent.com/tlc-pack/web-data/main/images/design/tvm_life_of_irmodule.png\n#    :align: center\n#    :width: 85%\n#\n# This is the life cycle of an IRModule, which can be created from TVMScript. TensorIR schedule\n# primitives and passes are two major ways to transform an IRModule. Also, a sequence of\n# transformations on an IRModule is acceptable. Note that we can print an IRModule at **ANY** stage\n# to TVMScript. After all transformations and optimizations are complete, we can build the IRModule\n# to a runnable module to deploy on target devices.\n#\n# Based on the design of TensorIR and IRModule, we are able to create a new programming method:\n#\n# 1. Write a program by TVMScript in a python-AST based syntax.\n#\n# 2. Transform and optimize a program with python api.\n#\n# 3. Interactively inspect and try the performance with an imperative style transformation API.\n\n\n################################################################################################\n# Create an IRModule\n# ------------------\n# IRModule can be created by writing TVMScript, which is a round-trippable syntax for TVM IR.\n#\n# Different than creating a computational expression by Tensor Expression\n# (:ref:`tutorial-tensor-expr-get-started`), TensorIR allow users to program through TVMScript,\n# a language embedded in python AST. The new method makes it possible to write complex programs\n# and further schedule and optimize it.\n#\n# Following is a simple example for vector addition.\n#\n\n\n@tvm.script.ir_module\nclass MyModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle):\n        # We exchange data between function by handles, which are similar to pointer.\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # Create buffer from handles.\n        A = T.match_buffer(a, (8,), dtype=\"float32\")\n        B = T.match_buffer(b, (8,), dtype=\"float32\")\n        for i in range(8):\n            # A block is an abstraction for computation.\n            with T.block(\"B\"):\n                # Define a spatial block iterator and bind it to value i.\n                vi = T.axis.spatial(8, i)\n                B[vi] = A[vi] + 1.0\n\n\nir_module = MyModule\nprint(type(ir_module))\nprint(ir_module.script())\n\n################################################################################################\n# Besides, we can also use tensor expression DSL to write simple operators, and convert them\n# to an IRModule.\n#\n\nfrom tvm import te\n\nA = te.placeholder((8,), dtype=\"float32\", name=\"A\")\nB = te.compute((8,), lambda *i: A(*i) + 1.0, name=\"B\")\nfunc = te.create_prim_func([A, B])\nir_module_from_te = IRModule({\"main\": func})\nprint(ir_module_from_te.script())\n\n\n################################################################################################\n# Build and Run an IRModule\n# -------------------------\n# We can build the IRModule into a runnable module with specific target backends.\n#\n\nmod = tvm.build(ir_module, target=\"llvm\")  # The module for CPU backends.\nprint(type(mod))\n\n################################################################################################\n# Prepare the input array and output array, then run the module.\n#\n\na = tvm.nd.array(np.arange(8).astype(\"float32\"))\nb = tvm.nd.array(np.zeros((8,)).astype(\"float32\"))\nmod(a, b)\nprint(a)\nprint(b)\n\n\n################################################################################################\n# Transform an IRModule\n# ---------------------\n# The IRModule is the central data structure for program optimization, which can be transformed\n# by :code:`Schedule`.\n# A schedule contains multiple primitive methods to interactively transform the program.\n# Each primitive transforms the program in certain ways to bring additional performance optimizations.\n#\n# .. image:: https://raw.githubusercontent.com/tlc-pack/web-data/main/images/design/tvm_tensor_ir_opt_flow.png\n#    :align: center\n#    :width: 100%\n#\n# The image above is a typical workflow for optimizing a tensor program. First, we need to create a\n# schedule on the initial IRModule created from either TVMScript or Tensor Expression. Then, a\n# sequence of schedule primitives will help to improve the performance. And at last, we can lower\n# and build it into a runnable module.\n#\n# Here we just demonstrate a very simple transformation. First we create schedule on the input `ir_module`.\n\nsch = tvm.tir.Schedule(ir_module)\nprint(type(sch))\n\n################################################################################################\n# Tile the loop into 3 loops and print the result.\n\n# Get block by its name\nblock_b = sch.get_block(\"B\")\n# Get loops surrounding the block\n(i,) = sch.get_loops(block_b)\n# Tile the loop nesting.\ni_0, i_1, i_2 = sch.split(i, factors=[2, 2, 2])\nprint(sch.mod.script())\n\n\n################################################################################################\n# We can also reorder the loops. Now we move loop `i_2` to outside of `i_1`.\nsch.reorder(i_0, i_2, i_1)\nprint(sch.mod.script())\n\n\n################################################################################################\n# Transform to a GPU program\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n# If we want to deploy models on GPUs, thread binding is necessary. Fortunately, we can\n# also use primitives and do incrementally transformation.\n#\n\nsch.bind(i_0, \"blockIdx.x\")\nsch.bind(i_2, \"threadIdx.x\")\nprint(sch.mod.script())\n\n\n################################################################################################\n# After binding the threads, now build the IRModule with :code:`cuda` backends.\nctx = tvm.cuda(0)\ncuda_mod = tvm.build(sch.mod, target=\"cuda\")\ncuda_a = tvm.nd.array(np.arange(8).astype(\"float32\"), ctx)\ncuda_b = tvm.nd.array(np.zeros((8,)).astype(\"float32\"), ctx)\ncuda_mod(cuda_a, cuda_b)\nprint(cuda_a)\nprint(cuda_b)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/tvmc_command_line_driver.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCompiling and Optimizing a Model with TVMC\n==========================================\n**Authors**:\n`Leandro Nunes <https://github.com/leandron>`_,\n`Matthew Barrett <https://github.com/mbaret>`_,\n`Chris Hoge <https://github.com/hogepodge>`_\n\nIn this section, we will work with TVMC, the TVM command line driver. TVMC is a\ntool that exposes TVM features such as auto-tuning, compiling, profiling and\nexecution of models through a command line interface.\n\nUpon completion of this section, we will have used TVMC to accomplish the\nfollowing tasks:\n\n* Compile a pre-trained ResNet-50 v2 model for the TVM runtime.\n* Run a real image through the compiled model, and interpret the output and\n  model performance.\n* Tune the model on a CPU using TVM.\n* Re-compile an optimized model using the tuning data collected by TVM.\n* Run the image through the optimized model, and compare the output and model\n  performance.\n\nThe goal of this section is to give you an overview of TVM and TVMC's\ncapabilities, and set the stage for understanding how TVM works.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# Using TVMC\n# ----------\n#\n# TVMC is a Python application, part of the TVM Python package.\n# When you install TVM using a Python package, you will get TVMC as\n# as a command line application called ``tvmc``. The location of this command\n# will vary depending on your platform and installation method.\n#\n# Alternatively, if you have TVM as a Python module on your\n# ``$PYTHONPATH``,you can access the command line driver functionality\n# via the executable python module, ``python -m tvm.driver.tvmc``.\n#\n# For simplicity, this tutorial will mention TVMC command line using\n# ``tvmc <options>``, but the same results can be obtained with\n# ``python -m tvm.driver.tvmc <options>``.\n#\n# You can check the help page using:\n#\n# .. code-block:: bash\n#\n#   tvmc --help\n#\n# The main features of TVM available to ``tvmc`` are from subcommands\n# ``compile``, and ``run``, and ``tune``.  To read about specific options under\n# a given subcommand, use ``tvmc <subcommand> --help``. We will cover each of\n# these commands in this tutorial, but first we need to download a pre-trained\n# model to work with.\n#\n\n\n################################################################################\n# Obtaining the Model\n# -------------------\n#\n# For this tutorial, we will be working with ResNet-50 v2. ResNet-50 is a\n# convolutional neural network that is 50 layers deep and designed to classify\n# images. The model we will be using has been pre-trained on more than a\n# million images with 1000 different classifications. The network has an input\n# image size of 224x224. If you are interested exploring more of how the\n# ResNet-50 model is structured, we recommend downloading `Netron\n# <https://netron.app>`_, a freely available ML model viewer.\n#\n# For this tutorial we will be using the model in ONNX format.\n#\n# .. code-block:: bash\n#\n#   wget https://github.com/onnx/models/raw/b9a54e89508f101a1611cd64f4ef56b9cb62c7cf/vision/classification/resnet/model/resnet50-v2-7.onnx\n#\n\n################################################################################\n# .. admonition:: Supported model formats\n#\n#   TVMC supports models created with Keras, ONNX, TensorFlow, TFLite\n#   and Torch. Use the option ``--model-format`` if you need to\n#   explicitly provide the model format you are using. See ``tvmc\n#   compile --help`` for more information.\n#\n\n################################################################################\n# .. admonition:: Adding ONNX Support to TVM\n#\n#    TVM relies on the ONNX python library being available on your system. You can\n#    install ONNX using the command ``pip3 install --user onnx onnxoptimizer``. You\n#    may remove the ``--user`` option if you have root access and want to install\n#    ONNX globally.  The ``onnxoptimizer`` dependency is optional, and is only used\n#    for ``onnx>=1.9``.\n#\n\n################################################################################\n# Compiling an ONNX Model to the TVM Runtime\n# ------------------------------------------\n#\n# Once we've downloaded the ResNet-50 model, the next step is to compile it. To\n# accomplish that, we are going to use ``tvmc compile``. The output we get from\n# the compilation process is a TAR package of the model compiled to a dynamic\n# library for our target platform. We can run that model on our target device\n# using the TVM runtime.\n#\n# .. code-block:: bash\n#\n#   # This may take several minutes depending on your machine\n#   tvmc compile \\\n#   --target \"llvm\" \\\n#   --input-shapes \"data:[1,3,224,224]\" \\\n#   --output resnet50-v2-7-tvm.tar \\\n#   resnet50-v2-7.onnx\n#\n# Let's take a look at the files that ``tvmc compile`` creates in the module:\n#\n# .. code-block:: bash\n#\n# \tmkdir model\n# \ttar -xvf resnet50-v2-7-tvm.tar -C model\n# \tls model\n#\n# You will see three files listed.\n#\n# * ``mod.so`` is the model, represented as a C++ library, that can be loaded\n#   by the TVM runtime.\n# * ``mod.json`` is a text representation of the TVM Relay computation graph.\n# * ``mod.params`` is a file containing the parameters for the pre-trained\n#   model.\n#\n# This module can be directly loaded by your application, and the model can be\n# run via the TVM runtime APIs.\n\n\n################################################################################\n# .. admonition:: Defining the Correct Target\n#\n#   Specifying the correct target (option ``--target``) can have a huge\n#   impact on the performance of the compiled module, as it can take\n#   advantage of hardware features available on the target. For more\n#   information, please refer to :ref:`Auto-tuning a convolutional network for\n#   x86 CPU <tune_relay_x86>`. We recommend identifying which CPU you are\n#   running, along with optional features, and set the target appropriately.\n\n################################################################################\n# Running the Model from The Compiled Module with TVMC\n# ----------------------------------------------------\n#\n# Now that we've compiled the model to this module, we can use the TVM runtime\n# to make predictions with it. TVMC has the TVM runtime built in to it,\n# allowing you to run compiled TVM models. To use TVMC to run the model and\n# make predictions, we need two things:\n#\n# - The compiled module, which we just produced.\n# - Valid input to the model to make predictions on.\n#\n# Each model is particular when it comes to expected tensor shapes, formats and\n# data types. For this reason, most models require some pre and\n# post-processing, to ensure the input is valid and to interpret the output.\n# TVMC has adopted NumPy's ``.npz`` format for both input and output data. This\n# is a well-supported NumPy format to serialize multiple arrays into a file.\n#\n# As input for this tutorial, we will use the image of a cat, but you can feel\n# free to substitute this image for any of your choosing.\n#\n# .. image:: https://s3.amazonaws.com/model-server/inputs/kitten.jpg\n#    :height: 224px\n#    :width: 224px\n#    :align: center\n\n\n################################################################################\n# Input pre-processing\n# ~~~~~~~~~~~~~~~~~~~~\n#\n# For our ResNet-50 v2 model, the input is expected to be in ImageNet format.\n# Here is an example of a script to pre-process an image for ResNet-50 v2.\n#\n# You will need to have a supported version of the Python Image Library\n# installed. You can use ``pip3 install --user pillow`` to satisfy this\n# requirement for the script.\n#\n# .. code-block:: python\n#     :caption: preprocess.py\n#     :name: preprocess.py\n#\n#     #!python ./preprocess.py\n#     from tvm.contrib.download import download_testdata\n#     from PIL import Image\n#     import numpy as np\n#\n#     img_url = \"https://s3.amazonaws.com/model-server/inputs/kitten.jpg\"\n#     img_path = download_testdata(img_url, \"imagenet_cat.png\", module=\"data\")\n#\n#     # Resize it to 224x224\n#     resized_image = Image.open(img_path).resize((224, 224))\n#     img_data = np.asarray(resized_image).astype(\"float32\")\n#\n#     # ONNX expects NCHW input, so convert the array\n#     img_data = np.transpose(img_data, (2, 0, 1))\n#\n#     # Normalize according to ImageNet\n#     imagenet_mean = np.array([0.485, 0.456, 0.406])\n#     imagenet_stddev = np.array([0.229, 0.224, 0.225])\n#     norm_img_data = np.zeros(img_data.shape).astype(\"float32\")\n#     for i in range(img_data.shape[0]):\n#    \t  norm_img_data[i, :, :] = (img_data[i, :, :] / 255 - imagenet_mean[i]) / imagenet_stddev[i]\n#\n#     # Add batch dimension\n#     img_data = np.expand_dims(norm_img_data, axis=0)\n#\n#     # Save to .npz (outputs imagenet_cat.npz)\n#     np.savez(\"imagenet_cat\", data=img_data)\n#\n\n################################################################################\n# Running the Compiled Module\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# With both the model and input data in hand, we can now run TVMC to make a\n# prediction:\n#\n# .. code-block:: bash\n#\n#     tvmc run \\\n#     --inputs imagenet_cat.npz \\\n#     --output predictions.npz \\\n#     resnet50-v2-7-tvm.tar\n#\n# Recall that the ``.tar`` model file includes a C++ library, a description of\n# the Relay model, and the parameters for the model. TVMC includes the TVM\n# runtime, which can load the model and make predictions against input. When\n# running the above command, TVMC outputs a new file, ``predictions.npz``, that\n# contains the model output tensors in NumPy format.\n#\n# In this example, we are running the model on the same machine that we used\n# for compilation. In some cases we might want to run it remotely via an RPC\n# Tracker. To read more about these options please check ``tvmc run --help``.\n\n################################################################################\n# Output Post-Processing\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# As previously mentioned, each model will have its own particular way of\n# providing output tensors.\n#\n# In our case, we need to run some post-processing to render the outputs from\n# ResNet-50 v2 into a more human-readable form, using the lookup-table provided\n# for the model.\n#\n# The script below shows an example of the post-processing to extract labels\n# from the output of our compiled module.\n#\n# .. code-block:: python\n#     :caption: postprocess.py\n#     :name: postprocess.py\n#\n#     #!python ./postprocess.py\n#     import os.path\n#     import numpy as np\n#\n#     from scipy.special import softmax\n#\n#     from tvm.contrib.download import download_testdata\n#\n#     # Download a list of labels\n#     labels_url = \"https://s3.amazonaws.com/onnx-model-zoo/synset.txt\"\n#     labels_path = download_testdata(labels_url, \"synset.txt\", module=\"data\")\n#\n#     with open(labels_path, \"r\") as f:\n#         labels = [l.rstrip() for l in f]\n#\n#     output_file = \"predictions.npz\"\n#\n#     # Open the output and read the output tensor\n#     if os.path.exists(output_file):\n#         with np.load(output_file) as data:\n#             scores = softmax(data[\"output_0\"])\n#             scores = np.squeeze(scores)\n#             ranks = np.argsort(scores)[::-1]\n#\n#             for rank in ranks[0:5]:\n#                 print(\"class='%s' with probability=%f\" % (labels[rank], scores[rank]))\n#\n# Running this script should produce the following output:\n#\n# .. code-block:: bash\n#\n#     python postprocess.py\n#     # class='n02123045 tabby, tabby cat' with probability=0.610553\n#     # class='n02123159 tiger cat' with probability=0.367179\n#     # class='n02124075 Egyptian cat' with probability=0.019365\n#     # class='n02129604 tiger, Panthera tigris' with probability=0.001273\n#     # class='n04040759 radiator' with probability=0.000261\n#\n# Try replacing the cat image with other images, and see what sort of\n# predictions the ResNet model makes.\n\n################################################################################\n# Automatically Tuning the ResNet Model\n# -------------------------------------\n#\n# The previous model was compiled to work on the TVM runtime, but did not\n# include any platform specific optimization. In this section, we will show you\n# how to build an optimized model using TVMC to target your working platform.\n#\n# In some cases, we might not get the expected performance when running\n# inferences using our compiled module.  In cases like this, we can make use of\n# the auto-tuner, to find a better configuration for our model and get a boost\n# in performance. Tuning in TVM refers to the process by which a model is\n# optimized to run faster on a given target. This differs from training or\n# fine-tuning in that it does not affect the accuracy of the model, but only\n# the runtime performance. As part of the tuning process, TVM will try running\n# many different operator implementation variants to see which perform best.\n# The results of these runs are stored in a tuning records file, which is\n# ultimately the output of the ``tune`` subcommand.\n#\n# In the simplest form, tuning requires you to provide three things:\n#\n# - the target specification of the device you intend to run this model on\n# - the path to an output file in which the tuning records will be stored, and\n#   finally\n# - a path to the model to be tuned.\n#\n# The example below demonstrates how that works in practice:\n#\n# .. code-block:: bash\n#\n#     # The default search algorithm requires xgboost, see below for further\n#     # details on tuning search algorithms\n#     pip install xgboost\n#\n#     tvmc tune \\\n#     --target \"llvm\" \\\n#     --output resnet50-v2-7-autotuner_records.json \\\n#     resnet50-v2-7.onnx\n#\n# In this example, you will see better results if you indicate a more specific\n# target for the ``--target`` flag.  For example, on an Intel i7 processor you\n# could use ``--target llvm -mcpu=skylake``. For this tuning example, we are\n# tuning locally on the CPU using LLVM as the compiler for the specified\n# achitecture.\n#\n# TVMC will perform a search against the parameter space for the model, trying\n# out different configurations for operators and choosing the one that runs\n# fastest on your platform. Although this is a guided search based on the CPU\n# and model operations, it can still take several hours to complete the search.\n# The output of this search will be saved to the\n# ``resnet50-v2-7-autotuner_records.json`` file, which will later be used to\n# compile an optimized model.\n#\n# .. admonition:: Defining the Tuning Search Algorithm\n#\n#   By default this search is guided using an ``XGBoost Grid`` algorithm.\n#   Depending on your model complexity and amount of time avilable, you might\n#   want to choose a different algorithm. A full list is available by\n#   consulting ``tvmc tune --help``.\n#\n# The output will look something like this for a consumer-level Skylake CPU:\n#\n# .. code-block:: bash\n#\n#   tvmc tune \\\n#   --target \"llvm -mcpu=broadwell\" \\\n#   --output resnet50-v2-7-autotuner_records.json \\\n#   resnet50-v2-7.onnx\n#   # [Task  1/24]  Current/Best:    9.65/  23.16 GFLOPS | Progress: (60/1000) | 130.74 s Done.\n#   # [Task  1/24]  Current/Best:    3.56/  23.16 GFLOPS | Progress: (192/1000) | 381.32 s Done.\n#   # [Task  2/24]  Current/Best:   13.13/  58.61 GFLOPS | Progress: (960/1000) | 1190.59 s Done.\n#   # [Task  3/24]  Current/Best:   31.93/  59.52 GFLOPS | Progress: (800/1000) | 727.85 s Done.\n#   # [Task  4/24]  Current/Best:   16.42/  57.80 GFLOPS | Progress: (960/1000) | 559.74 s Done.\n#   # [Task  5/24]  Current/Best:   12.42/  57.92 GFLOPS | Progress: (800/1000) | 766.63 s Done.\n#   # [Task  6/24]  Current/Best:   20.66/  59.25 GFLOPS | Progress: (1000/1000) | 673.61 s Done.\n#   # [Task  7/24]  Current/Best:   15.48/  59.60 GFLOPS | Progress: (1000/1000) | 953.04 s Done.\n#   # [Task  8/24]  Current/Best:   31.97/  59.33 GFLOPS | Progress: (972/1000) | 559.57 s Done.\n#   # [Task  9/24]  Current/Best:   34.14/  60.09 GFLOPS | Progress: (1000/1000) | 479.32 s Done.\n#   # [Task 10/24]  Current/Best:   12.53/  58.97 GFLOPS | Progress: (972/1000) | 642.34 s Done.\n#   # [Task 11/24]  Current/Best:   30.94/  58.47 GFLOPS | Progress: (1000/1000) | 648.26 s Done.\n#   # [Task 12/24]  Current/Best:   23.66/  58.63 GFLOPS | Progress: (1000/1000) | 851.59 s Done.\n#   # [Task 13/24]  Current/Best:   25.44/  59.76 GFLOPS | Progress: (1000/1000) | 534.58 s Done.\n#   # [Task 14/24]  Current/Best:   26.83/  58.51 GFLOPS | Progress: (1000/1000) | 491.67 s Done.\n#   # [Task 15/24]  Current/Best:   33.64/  58.55 GFLOPS | Progress: (1000/1000) | 529.85 s Done.\n#   # [Task 16/24]  Current/Best:   14.93/  57.94 GFLOPS | Progress: (1000/1000) | 645.55 s Done.\n#   # [Task 17/24]  Current/Best:   28.70/  58.19 GFLOPS | Progress: (1000/1000) | 756.88 s Done.\n#   # [Task 18/24]  Current/Best:   19.01/  60.43 GFLOPS | Progress: (980/1000) | 514.69 s Done.\n#   # [Task 19/24]  Current/Best:   14.61/  57.30 GFLOPS | Progress: (1000/1000) | 614.44 s Done.\n#   # [Task 20/24]  Current/Best:   10.47/  57.68 GFLOPS | Progress: (980/1000) | 479.80 s Done.\n#   # [Task 21/24]  Current/Best:   34.37/  58.28 GFLOPS | Progress: (308/1000) | 225.37 s Done.\n#   # [Task 22/24]  Current/Best:   15.75/  57.71 GFLOPS | Progress: (1000/1000) | 1024.05 s Done.\n#   # [Task 23/24]  Current/Best:   23.23/  58.92 GFLOPS | Progress: (1000/1000) | 999.34 s Done.\n#   # [Task 24/24]  Current/Best:   17.27/  55.25 GFLOPS | Progress: (1000/1000) | 1428.74 s Done.\n#\n# Tuning sessions can take a long time, so ``tvmc tune`` offers many options to customize your tuning\n# process, in terms of number of repetitions (``--repeat`` and ``--number``, for example), the tuning\n# algorithm to be used, and so on. Check ``tvmc tune --help`` for more information.\n#\n\n################################################################################\n# Compiling an Optimized Model with Tuning Data\n# ----------------------------------------------\n#\n# As an output of the tuning process above, we obtained the tuning records\n# stored in ``resnet50-v2-7-autotuner_records.json``. This file can be used in\n# two ways:\n#\n# - As input to further tuning (via ``tvmc tune --tuning-records``).\n# - As input to the compiler\n#\n# The compiler will use the results to generate high performance code for the\n# model on your specified target. To do that we can use ``tvmc compile\n# --tuning-records``. Check ``tvmc compile --help`` for more information.\n#\n# Now that tuning data for the model has been collected, we can re-compile the\n# model using optimized operators to speed up our computations.\n#\n# .. code-block:: bash\n#\n#   tvmc compile \\\n#   --target \"llvm\" \\\n#   --tuning-records resnet50-v2-7-autotuner_records.json  \\\n#   --output resnet50-v2-7-tvm_autotuned.tar \\\n#   resnet50-v2-7.onnx\n#\n# Verify that the optimized model runs and produces the same results:\n#\n# .. code-block:: bash\n#\n#   tvmc run \\\n#   --inputs imagenet_cat.npz \\\n#   --output predictions.npz \\\n#   resnet50-v2-7-tvm_autotuned.tar\n#\n#   python postprocess.py\n#\n# Verifying that the predictions are the same:\n#\n# .. code-block:: bash\n#\n#   # class='n02123045 tabby, tabby cat' with probability=0.610550\n#   # class='n02123159 tiger cat' with probability=0.367181\n#   # class='n02124075 Egyptian cat' with probability=0.019365\n#   # class='n02129604 tiger, Panthera tigris' with probability=0.001273\n#   # class='n04040759 radiator' with probability=0.000261\n\n################################################################################\n# Comparing the Tuned and Untuned Models\n# --------------------------------------\n#\n# TVMC gives you tools for basic performance benchmarking between the models.\n# You can specify a number of repetitions and that TVMC report on the model run\n# time (independent of runtime startup). We can get a rough idea of how much\n# tuning has improved the model performance. For example, on a test Intel i7\n# system, we see that the tuned model runs 47% faster than the untuned model:\n#\n# .. code-block:: bash\n#\n#   tvmc run \\\n#   --inputs imagenet_cat.npz \\\n#   --output predictions.npz  \\\n#   --print-time \\\n#   --repeat 100 \\\n#   resnet50-v2-7-tvm_autotuned.tar\n#\n#   # Execution time summary:\n#   # mean (ms)   max (ms)    min (ms)    std (ms)\n#   #     92.19     115.73       89.85        3.15\n#\n#   tvmc run \\\n#   --inputs imagenet_cat.npz \\\n#   --output predictions.npz  \\\n#   --print-time \\\n#   --repeat 100 \\\n#   resnet50-v2-7-tvm.tar\n#\n#   # Execution time summary:\n#   # mean (ms)   max (ms)    min (ms)    std (ms)\n#   #    193.32     219.97      185.04        7.11\n#\n\n\n################################################################################\n# Final Remarks\n# -------------\n#\n# In this tutorial, we presented TVMC, a command line driver for TVM. We\n# demonstrated how to compile, run, and tune a model. We also discussed the\n# need for pre and post-processing of inputs and outputs. After the tuning\n# process, we demonstrated how to compare the performance of the unoptimized\n# and optimize models.\n#\n# Here we presented a simple example using ResNet-50 v2 locally. However, TVMC\n# supports many more features including cross-compilation, remote execution and\n# profiling/benchmarking.\n#\n# To see what other options are available, please have a look at ``tvmc\n# --help``.\n#\n# In the next tutorial, `Compiling and Optimizing a Model with the Python\n# Interface <auto_tuning_with_pyton>`_, we will cover the same compilation\n# and optimization steps using the Python interface.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/tvmc_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nGetting Starting using TVMC Python: a high-level API for TVM\n=============================================================\n**Author**:\n`Jocelyn Shiue <https://github.com/CircleSpin>`_\n\nHi! Here we explain the scripting tool designed for the complete TVM beginner. \ud83d\ude42\n\nBefore we get started let's get an example model if you don't already have one.\nFollow the steps to download a resnet model via the terminal:\n\n .. code-block:: python\n\n     mkdir myscripts\n     cd myscripts\n     wget https://github.com/onnx/models/raw/b9a54e89508f101a1611cd64f4ef56b9cb62c7cf/vision/classification/resnet/model/resnet50-v2-7.onnx\n     mv resnet50-v2-7.onnx my_model.onnx\n     touch tvmcpythonintro.py\n\nLet's start editing the python file in your favorite text editor.\n\"\"\"\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n################################################################################\n# Step 0: Imports\n# ~~~~~~~~~~~~~~~\n#\n#  .. code-block:: python\n#\n#     from tvm.driver import tvmc\n#\n#\n\n################################################################################\n# Step 1: Load a model\n# ~~~~~~~~~~~~~~~~~~~~\n#\n# Let's import our model into tvmc. This step converts a machine learning model from\n# a supported framework into TVM's high level graph representation language called Relay.\n# This is to have a unified starting point for all models in tvm. The frameworks we currently\n# support are: Keras, ONNX, Tensorflow, TFLite, and PyTorch.\n#\n# .. code-block:: python\n#\n#   model = tvmc.load('my_model.onnx') #Step 1: Load\n#\n# If you'd like to see the Relay, you can run:\n# ``model.summary()``\n#\n# All frameworks support overwriting the input shapes with a shape_dict argument.\n# For most frameworks this is optional, but for Pytorch this is necessary as\n# TVM cannot automatically search for it.\n#\n# .. code-block:: python\n#\n#   #model = tvmc.load('my_model.onnx', shape_dict={'input1' : [1, 2, 3, 4], 'input2' : [1, 2, 3, 4]}) #Step 1: Load + shape_dict\n#\n# A suggested way to see the model's input/shape_dict is via `netron <https://netron.app/>`_. After opening the model,\n# click the first node to see the name(s) and shape(s) in the inputs section.\n\n\n################################################################################\n# Step 2: Compile\n# ~~~~~~~~~~~~~~~\n#\n# Now that our model is in Relay, our next step is to compile it to a desired\n# hardware to run on. We refer to this hardware as a target. This compilation process\n# translates the model from Relay into a lower-level language that the\n# target machine can understand.\n#\n# In order to compile a model a tvm.target string is required.\n# To learn more about tvm.targets and their options look at the `documentation <https://tvm.apache.org/docs/api/python/target.html>`_.\n# Some examples include:\n#\n#    1. cuda (Nvidia GPU)\n#    2. llvm (CPU)\n#    3. llvm -mcpu=cascadelake (Intel CPU)\n#\n# .. code-block:: python\n#\n#   package = tvmc.compile(model, target=\"llvm\") #Step 2: Compile\n#\n#\n# The compilation step returns a package.\n#\n\n################################################################################\n# Step 3: Run\n# ~~~~~~~~~~~\n#\n# The compiled package can now be run on the hardware target. The device\n# input options are: CPU, Cuda, CL, Metal, and Vulkan.\n#\n# .. code-block:: python\n#\n#   result = tvmc.run(package, device=\"cpu\") #Step 3: Run\n#\n# And you can print the results:\n# ``print(result)``\n#\n\n################################################################################\n# Step 1.5: Tune [Optional & Recommended]\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Run speed can further be improved by tuning. This optional step uses\n# machine learning to look at each operation within a model (a function) and\n# tries to find a faster way to run it. We do this through a cost model, and\n# benchmarking possible schedules.\n#\n# The target is the same as compile.\n#\n# .. code-block:: python\n#\n#   tvmc.tune(model, target=\"llvm\") #Step 1.5: Optional Tune\n#\n# The terminal output should look like:\n#\n# .. code-block:: python\n#\n#    [Task  1/13]  Current/Best:   82.00/ 106.29 GFLOPS | Progress: (48/769) | 18.56 s\n#    [Task  1/13]  Current/Best:   54.47/ 113.50 GFLOPS | Progress: (240/769) | 85.36 s\n#    .....\n#\n# There may be UserWarnings that can be ignored.\n# This should make the end result faster, but it can take hours to tune.\n#\n# See the section 'Saving the Tuning Results' below. Be sure to pass the tuning\n# results into compile if you want the results to apply.\n#\n# .. code-block:: python\n#\n#     #tvmc.compile(model, target=\"llvm\", tuning_records = \"records.log\") #Step 2: Compile\n\n################################################################################\n# Save and then start the process in the terminal:\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# .. code-block:: python\n#\n#   python my_tvmc_script.py\n#\n# Note: Your fans may become very active\n#\n\n################################################################################\n# Example results:\n# ~~~~~~~~~~~~~~~~\n#\n# .. code-block:: python\n#\n#   Time elapsed for training: 18.99 s\n#   Execution time summary:\n#   mean (ms)   max (ms)   min (ms)   std (ms)\n#     25.24      26.12      24.89       0.38\n#\n#\n#   Output Names:\n#   ['output_0']\n#\n\n\n################################################################################\n# Additional TVMC Functionalities\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\n################################################################################\n# Saving the model\n# ~~~~~~~~~~~~~~~~\n#\n# To make things faster for later, after loading the model (Step 1) save the Relay version.\n# The model will then appear where you saved it for later in the coverted syntax.\n#\n# .. code-block:: python\n#\n#   model = tvmc.load('my_model.onnx') #Step 1: Load\n#   model.save(desired_model_path)\n#\n#\n\n################################################################################\n# Saving the package\n# ~~~~~~~~~~~~~~~~~~\n#\n# After the model has been compiled (Step 2) the package also is also saveable.\n#\n# .. code-block:: python\n#\n#   tvmc.compile(model, target=\"llvm\", package_path=\"whatever\") #Step 2: Compile\n#\n#   new_package = tvmc.TVMCPackage(package_path=\"whatever\")\n#   result = tvmc.run(new_package, device=\"cpu\") #Step 3: Run\n#\n#\n\n################################################################################\n# Using Autoscheduler\n# ~~~~~~~~~~~~~~~~~~~\n#\n# Use the next generation of tvm to enable potentially faster run speed results.\n# The search space of the schedules is automatically generated unlike\n# previously where they needed to be hand written. (Learn more:\n# `1 <https://tvm.apache.org/2021/03/03/intro-auto-scheduler>`_,\n# `2 <https://arxiv.org/abs/2006.06762>`_)\n#\n# .. code-block:: python\n#\n#   tvmc.tune(model, target=\"llvm\", enable_autoscheduler = True)\n#\n#\n\n################################################################################\n# Saving the tuning results\n# ~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# The tuning results can be saved in a file for later reuse.\n#\n# Method 1:\n#    .. code-block:: python\n#\n#      log_file = \"hello.json\"\n#\n#      # Run tuning\n#      tvmc.tune(model, target=\"llvm\", tuning_records=log_file)\n#\n#      ...\n#\n#      # Later run tuning and reuse tuning results\n#      tvmc.tune(model, target=\"llvm\", prior_records=log_file)\n#\n# Method 2:\n#    .. code-block:: python\n#\n#      # Run tuning\n#      tuning_records = tvmc.tune(model, target=\"llvm\")\n#\n#      ...\n#\n#      # Later run tuning and reuse tuning results\n#      tvmc.tune(model, target=\"llvm\", prior_records=tuning_records)\n#\n\n################################################################################\n# Tuning a more complex model:\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# If you notice T's printing that look like ``.........T.T..T..T..T.T.T.T.T.T.``\n# increase the searching time frame:\n#\n#    .. code-block:: python\n#\n#      tvmc.tune(model,trials=10000,timeout=10,)\n#\n\n################################################################################\n# Compiling a model for a remote device:\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# A remote procedural call (RPC) is useful when you would like to compile for hardware\n# that is not on your local machine. The tvmc methods support this.\n# To set up the RPC server take a look at the 'Set up RPC Server on Device'\n# section in this `document <https://tvm.apache.org/docs/tutorials/get_started/cross_compilation_and_rpc.html>`_.\n#\n# Within the TVMC Script include the following and adjust accordingly:\n#\n#    .. code-block:: python\n#\n#      tvmc.tune(\n#           model,\n#           target=target, # Compilation target as string // Device to compile for\n#           target_host=target_host, # Host processor\n#           hostname=host_ip_address, # The IP address of an RPC tracker, used when benchmarking remotely.\n#           port=port_number, # The port of the RPC tracker to connect to. Defaults to 9090.\n#           rpc_key=your_key, # The RPC tracker key of the target device. Required when rpc_tracker is provided\n#      )\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "gallery/tutorial/uma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _tutorial-uma:\n\nMaking your Hardware Accelerator TVM-ready with UMA\n===================================================\n**Authors**: `Michael J. Klaiber <https://github.com/MichaelJKlaiber>`_, `Christoph Gerum <https://github.com/cgerum>`_,\n`Paul Palomero Bernardo <https://github.com/PaulPalomeroBernardo/>`_\n\n\"\"\"\n\n\n######################################################################\n# This is an introductory tutorial to the **Universal Modular Accelerator Interface** (UMA).\n# UMA provides an easy-to-use API to integrate new hardware accelerators into TVM.\n#\n# This tutorial gives you step-by-step guidance how to use UMA to\n# make your hardware accelerator TVM-ready.\n# While there is no one-fits-all solution for this problem, UMA targets to provide a stable and Python-only\n# API to integrate a number of hardware accelerator classes into TVM.\n#\n#\n# In this tutorial you will get to know the UMA API in three use cases of increasing complexity.\n# In these use case the three mock-accelerators\n# **Vanilla**, **Strawberry** and **Chocolate** are introduced and\n# integrated into TVM using UMA.\n#\n\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\n\n######################################################################\n# Vanilla\n# -------------\n# **Vanilla** is a simple accelerator consisting of a MAC array and has no internal memory.\n# It is can ONLY process Conv2D layers, all other layers are executed on a CPU, that also orchestrates **Vanilla**.\n# Both the CPU and Vanilla use a shared memory.\n#\n\n######################################################################\n# .. image:: https://raw.githubusercontent.com/apache/tvm-site/main/images/tutorial/uma_vanilla_block_diagram.png\n#   :width: 100%\n#   :alt: A block diagram of Vanilla\n#\n\n######################################################################\n# **Vanilla** has a C interface ``vanilla_conv2dnchw(...)``` for carrying out a Conv2D operation (including same-padding),\n# that accepts pointers to input feature map, weights and result,\n# as well as the dimensions of `Conv2D`: `oc`, `iw`, `ih`, `ic`, `kh`, `kw`.\n#\n# .. code-block:: c++\n#\n#   int vanilla_conv2dnchw(float* ifmap, float*  weights, float*  result, int oc, int iw, int ih, int ic, int kh, int kw);\n\n\n################################################################################\n# The script `uma_cli` creates code skeletons with API-calls into the UMA-API for new accelerators.\n#\n# For **Vanilla** we use it as follows: (``--tutorial vanilla`` adds all the additional files required for this part of the tutorial)\n#\n# .. code-block:: bash\n#\n#   pip install inflection\n#   cd $TVM_HOME/apps/uma\n#   python uma_cli.py --add_hardware vanilla_accelerator --tutorial vanilla\n#\n\n################################################################################\n# uma_cli.py generates these files in the directory ``vanilla_accelerator`` which we are going to revist.\n#\n# .. code-block:: bash\n#\n#   backend.py\n#   codegen.py\n#   conv2dnchw.cc\n#   passes.py\n#   patterns.py\n#   run.py\n#   strategies.py\n\n\n################################################################################\n# Vanilla backend\n#\n#  The generated backend for vanilla is found in `vanilla_accelerator/backend.py`:\n\n######################################################################\n#\n# .. code-block:: python\n#\n#  class VanillaAcceleratorBackend(UMABackend):\n#      \"\"\"UMA backend for VanillaAccelerator.\"\"\"\n#\n#      def __init__(self):\n#          super().__init__()\n#\n#          self._register_pattern(\"conv2d\", conv2d_pattern())\n#          self._register_tir_pass(PassPhase.TIR_PHASE_0, VanillaAcceleratorConv2DPass())\n#          self._register_codegen(fmt=\"c\", includes=gen_includes)\n#\n#      @property\n#      def target_name(self):\n#          return \"vanilla_accelerator\"\n\n\n################################################################################\n# Define offloaded patterns\n#\n# To specify that `Conv2D` is offloaded to **Vanilla**, it is described as Relay dataflow pattern\n# (`DFPattern <https://tvm.apache.org/docs/reference/langref/relay_pattern.html>`_) in `vanilla_accelerator/patterns.py`\n\n\n################################################################################\n#\n# .. code-block:: python\n#\n#  def conv2d_pattern():\n#      pattern = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n#      pattern = pattern.has_attr({\"strides\": [1, 1]})\n#      return pattern\n\n\n################################################################################\n# To map **Conv2D** operations from the input graph  to **Vanilla**'s\n# low level function call ``vanilla_conv2dnchw(...)``, the TIR pass\n# *VanillaAcceleratorConv2DPass* (that will be discussed later in this tutorial)\n# is registered in `VanillaAcceleratorBackend`.\n\n\n################################################################################\n# Codegen\n\n################################################################################\n# The file ``vanilla_accelerator/codegen.py`` defines static  C-code that is added to the\n# resulting C-Code generated by TVM\u015b C-Codegen in ``gen_includes``.\n# Here C-code is added to include **Vanilla**'s low level library``vanilla_conv2dnchw()``.\n#\n# .. code-block:: python\n#\n#  def gen_includes() -> str:\n#      topdir = pathlib.Path(__file__).parent.absolute()\n#\n#      includes = \"\"\n#      includes += f'#include \"{topdir}/conv2dnchw.cc\"'\n#      return includes\n\n\n################################################################################\n# As shown above in `VanillaAcceleratorBackend` it is registered to UMA with\n# the `self._register_codegen`\n#\n# .. code-block:: python\n#\n#   self._register_codegen(fmt=\"c\", includes=gen_includes)\n\n\n###########################################################\n# Building the Neural Network and run it on Vanilla\n#\n# To demonstrate UMA's functionality, we will generate C code for a single Conv2D layer and run it on\n# the Vanilla accelerator.\n# The file ``vanilla_accelerator/run.py`` provides a demo running a Conv2D layer\n# making use of Vanilla's C-API.\n#\n#\n# .. code-block:: python\n#\n#  def main():\n#      mod, inputs, output_list, runner = create_conv2d()\n#\n#      uma_backend = VanillaAcceleratorBackend()\n#      uma_backend.register()\n#      mod = uma_backend.partition(mod)\n#      target = tvm.target.Target(\"vanilla_accelerator\", host=tvm.target.Target(\"c\"))\n#\n#      export_directory = tvm.contrib.utils.tempdir(keep_for_debug=True).path\n#      print(f\"Generated files are in {export_directory}\")\n#      compile_and_run(\n#          AOTModel(module=mod, inputs=inputs, outputs=output_list),\n#          runner,\n#          interface_api=\"c\",\n#          use_unpacked_api=True,\n#          target=target,\n#          test_dir=str(export_directory),\n#      )\n#\n#\n#  main()\n\n############################################################\n# By running ``vanilla_accelerator/run.py`` the output files are generated in the model library format (MLF).\n#\n\n###########################################################\n# Output:\n#\n# .. code-block:: bash\n#\n#   Generated files are in /tmp/tvm-debug-mode-tempdirs/2022-07-13T13-26-22___x5u76h0p/00000\n\n###########################################################\n# Let's examine the generated files:\n#\n#\n# Output:\n#\n# .. code-block:: bash\n#\n#   cd /tmp/tvm-debug-mode-tempdirs/2022-07-13T13-26-22___x5u76h0p/00000\n#   cd build/\n#   ls -1\n#\n#   codegen\n#   lib.tar\n#   metadata.json\n#   parameters\n#   runtime\n#   src\n\n###########################################################\n# To evaluate the generated C code go to ``codegen/host/src/default_lib2.c``\n#\n# .. code-block:: bash\n#\n#   cd codegen/host/src/\n#   ls -1\n#\n#   default_lib0.c\n#   default_lib1.c\n#   default_lib2.c\n#\n\n###########################################################\n# In `default_lib2.c` you can now see that the generated code calls\n# into Vanilla's C-API and executes a Conv2D layer:\n#\n# .. code-block:: c++\n#\n#   TVM_DLL int32_t tvmgen_default_vanilla_accelerator_main_0(float* placeholder, float* placeholder1, float* conv2d_nchw, uint8_t* global_workspace_1_var) {\n#        vanilla_accelerator_conv2dnchw(placeholder, placeholder1, conv2d_nchw, 32, 14, 14, 32, 3, 3);\n#        return 0;\n#   }\n#\n\n\n###########################################################\n# Strawberry\n# ---------------\n# Coming soon ...\n\n###########################################################\n# Chocolate\n# --------------\n# Coming soon ...\n#\n\n######################################################################\n# Request for Community Input\n# -----------------------------\n# If this tutorial **did not** fit to your accelerator, lease add your requirements to the UMA thread in\n# the TVM discuss forum: `Link <https://discuss.tvm.apache.org/t/rfc-uma-universal-modular-accelerator-interface/12039>`_.\n# We are eager to extend this tutorial to provide guidance on making further classes of AI hardware\n# accelerators TVM-ready using the UMA interface.\n#\n\n######################################################################\n# References\n# -----------\n# [UMA-RFC] `UMA: Universal Modular Accelerator Interface <https://github.com/apache/tvm-rfcs/blob/main/rfcs/0060_UMA_Unified_Modular_Accelerator_Interface.md>`_,\n# TVM RFC, June 2022.\n#\n# [DFPattern] `Pattern Matching in Relay <https://tvm.apache.org/docs/reference/langref/relay_pattern.html>`_\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "golang/sample/deploy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nGet Started with TVM Go\n=======================\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n# Global declarations of environment.\n\ntgt = \"llvm\"\n\n######################################################################\n# Describe the Computation\n# ------------------------\nn = te.var(\"n\")\nA = te.placeholder((n,), name=\"A\")\nB = te.placeholder((n,), name=\"B\")\nC = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n\n######################################################################\n# Schedule the Computation\n# ------------------------\ns = te.create_schedule(C.op)\n\n######################################################################\n# Compilation\n# -----------\nfadd = tvm.build(s, [A, B, C], tgt, name=\"myadd\")\n\n######################################################################\n# Save Compiled Module\n# --------------------\nfrom tvm.contrib import cc\nfrom tvm.contrib import utils\n\nfadd.save(\"deploy.o\")\ncc.create_shared(\"deploy.so\", [\"deploy.o\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "golang/sample/gen_mobilenet_lib.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nfrom tvm import relay, transform, runtime\nfrom tvm.contrib.download import download_testdata\n\n\n################################################\n# Utils for downloading and extracting zip files\n# ----------------------------------------------\ndef extract(path):\n    import tarfile\n\n    if path.endswith(\"tgz\") or path.endswith(\"gz\"):\n        dir_path = os.path.dirname(path)\n        tar = tarfile.open(path)\n        tar.extractall(path=dir_path)\n        tar.close()\n    else:\n        raise RuntimeError(\"Could not decompress the file: \" + path)\n\n\n###################################\n# Download TFLite pre-trained model\n# ---------------------------------\n\nmodel_url = \"https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.4_224.tgz\"\nmodel_path = download_testdata(model_url, \"mobilenet_v2_1.4_224.tgz\", module=[\"tf\", \"official\"])\nmodel_dir = os.path.dirname(model_path)\nextract(model_path)\n\n# now we have mobilenet_v2_1.4_224.tflite on disk\nmodel_file = os.path.join(model_dir, \"mobilenet_v2_1.4_224.tflite\")\n\n# get TFLite model from buffer\ntflite_model_buf = open(model_file, \"rb\").read()\ntry:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n\n##############################\n# Load Neural Network in Relay\n# ----------------------------\n\n# TFLite input tensor name, shape and type\ninput_tensor = \"input\"\ninput_shape = (1, 224, 224, 3)\ninput_dtype = \"float32\"\n\n# parse TFLite model and convert into Relay computation graph\nmod, params = relay.frontend.from_tflite(\n    tflite_model, shape_dict={input_tensor: input_shape}, dtype_dict={input_tensor: input_dtype}\n)\n\n#############\n# Compilation\n# -----------\n\ntarget = \"llvm\"\n\n# Build with Relay\nwith transform.PassContext(opt_level=3):\n    graph, lib, params = relay.build_module.build(mod, target, params=params)\n\n###############################################\n# Save the graph, lib and parameters into files\n# ---------------------------------------------\n\nlib.export_library(\"./mobilenet.so\")\nprint(\"lib export succeefully\")\n\nwith open(\"./mobilenet.json\", \"w\") as fo:\n    fo.write(graph)\n\nwith open(\"./mobilenet.params\", \"wb\") as fo:\n    fo.write(runtime.save_param_dict(params))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "golang/src/gotvm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief gotvm native interface declaration.\n * \\file gotvm.h\n *\n * These declarations are in cgo interface definition while calling API\n * across golang and native C boundaries.\n */\n\n#ifndef GOTVM_GOTVM_H_\n#define GOTVM_GOTVM_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <dlpack/dlpack.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n// Some type definitions for golang \"C\"\ntypedef void* native_voidp;\n\n// Version\nextern char* _TVM_VERSION(void);\n\n// Wrappers : For incompatible cgo API.\n// To handle array of strings wrapped into __gostring__\nextern int _TVMFuncListGlobalNames(void*);\n// To handle TVMValue slice to/from native sequential TVMValue array.\nextern void _TVMValueNativeSet(void* to, void* from, int index);\nextern void _TVMValueNativeGet(void* to, void* from, int index);\n\n// Callbacks\nextern int _ConvertFunction(void* fptr, void* funp);\n\n#ifdef __cplusplus\n}\n#endif\n#endif  // GOTVM_GOTVM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/analyzer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arith/analyzer.h\n * \\brief Algebra expression simplifications.\n */\n#ifndef TVM_ARITH_ANALYZER_H_\n#define TVM_ARITH_ANALYZER_H_\n\n#include <tvm/arith/int_set.h>\n#include <tvm/ir/expr.h>\n#include <tvm/support/with.h>\n\n#include <limits>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\n/*! \\brief namespace of arithmetic analysis. */\nnamespace arith {\n//-------------------------------------------------------\n// Base integer analysis API.\n//\n// We have multiple type of analyzers to do relaxed\n// integer set analysis(bound analysis, modulo) and\n// equivalence checking and simplification.\n//\n// Importantly, each analyzer may need result from\n// another analyzer.\n//-------------------------------------------------------\n\n// Forward declare Analyzer\nclass Analyzer;\n\nusing tir::Var;\n\nenum DivMode {\n  /*! \\brief Truncated division. */\n  kTruncDiv,\n  /*! \\brief Floor division. */\n  kFloorDiv\n};\n\n/*!\n * \\brief Constant integer up and lower bound(inclusive).\n *  Useful for value bound analysis.\n *\n *  set = [min_value, max_value]\n */\nclass ConstIntBoundNode : public Object {\n public:\n  int64_t min_value;\n  int64_t max_value;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"min_value\", &min_value);\n    v->Visit(\"max_value\", &max_value);\n  }\n\n  bool SEqualReduce(const ConstIntBoundNode* other, SEqualReducer equal) const {\n    return equal(min_value, other->min_value) && equal(max_value, other->max_value);\n  }\n\n  /*! \\brief Number to represent +inf */\n  static const constexpr int64_t kPosInf = std::numeric_limits<int64_t>::max();\n  /*!\n   * \\brief Number to represent -inf\n   * \\note We can make use the of fact that -kPosInf == kNegInf in the project.\n   */\n  static const constexpr int64_t kNegInf = -kPosInf;\n\n  static constexpr const char* _type_key = \"arith.ConstIntBound\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstIntBoundNode, Object);\n};\n\n/*!\n * \\brief reference class to ConstIntBoundNode\n * \\sa ConstIntBoundNode\n */\nclass ConstIntBound : public ObjectRef {\n public:\n  /*!\n   * \\brief constructor by fields.\n   * \\param min_value The mininum value.\n   * \\param max_value The maximum value.\n   */\n  TVM_DLL ConstIntBound(int64_t min_value, int64_t max_value);\n\n  static const constexpr int64_t kPosInf = ConstIntBoundNode::kPosInf;\n  static const constexpr int64_t kNegInf = ConstIntBoundNode::kNegInf;\n  TVM_DEFINE_OBJECT_REF_METHODS(ConstIntBound, ObjectRef, ConstIntBoundNode);\n};\n\n/*!\n * \\brief Analyzer to get constant integer bound over expression.\n */\nclass ConstIntBoundAnalyzer {\n public:\n  using BoundMapType = std::unordered_map<PrimExpr, ConstIntBound, ObjectPtrHash, ObjectPtrEqual>;\n  /*!\n   * \\brief analyze the expr\n   * \\param expr The expression of interest.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL ConstIntBound operator()(const PrimExpr& expr) const;\n\n  /*!\n   * \\brief analyze the expr with the intermediate memorized to avoid redundant computation\n   * \\param expr The expression of interest.\n   * \\param bound The lookup table to store the intermediate results\n   * \\return the result of the analysis.\n   */\n  TVM_DLL ConstIntBound operator()(const PrimExpr& expr, BoundMapType* bound);\n\n  /*!\n   * \\brief Update constant int bound information of var.\n   *\n   * \\param var The variable of interest.\n   * \\param info The bound information.\n   * \\param allow_override whether we allow override of existing information.\n   */\n  TVM_DLL void Update(const Var& var, const ConstIntBound& info, bool allow_override = false);\n  /*!\n   * \\brief Bind variable to a range.\n   *\n   * \\param var The variable.\n   * \\param range The range we bind to.\n   * \\param allow_override Whether we allow overriding an existing var's range.\n   */\n  TVM_DLL void Bind(const Var& var, const Range& range, bool allow_override = false);\n\n private:\n  friend class Analyzer;\n  friend class ConstraintContext;\n  explicit ConstIntBoundAnalyzer(Analyzer* parent);\n  TVM_DLL ~ConstIntBoundAnalyzer();\n  /*!\n   * \\brief Update the internal state to enter constraint.\n   * \\param constraint A constraint expression.\n   *\n   * \\return an exit function that must be called to cleanup the constraint can be nullptr.\n   */\n  std::function<void()> EnterConstraint(const PrimExpr& constraint);\n  struct Entry;\n  class Impl;\n  /*! \\brief Internal impl */\n  Impl* impl_;\n};\n\n/*!\n * \\brief Range of a linear integer function.\n *  Use to do specify the possible index values.\n *\n *  set = { coeff * x + base | x in Z }\n *\n *  When coeff != 0, it can also be written as\n *  set = { n | n % coeff == base }\n *\n *  This is useful to decide if the index is dividable by certain value.\n *  For example, if index = 0 + 4 x, then we know it can be divided by 4.\n */\nclass ModularSetNode : public Object {\n public:\n  /*! \\brief linear co-efficient */\n  int64_t coeff;\n  /*! \\brief The base */\n  int64_t base;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"coeff\", &coeff);\n    v->Visit(\"base\", &base);\n  }\n\n  bool SEqualReduce(const ModularSetNode* other, SEqualReducer equal) const {\n    return equal(coeff, other->coeff) && equal(base, other->base);\n  }\n\n  static constexpr const char* _type_key = \"arith.ModularSet\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ModularSetNode, Object);\n};\n\n/*!\n * \\brief reference of ModularSetNode\n * \\sa ModularSetNode\n */\nclass ModularSet : public ObjectRef {\n public:\n  TVM_DLL ModularSet(int64_t coeff, int64_t base);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ModularSet, ObjectRef, ModularSetNode);\n};\n\n/*!\n * \\brief Analyzer to get modular information over expression.\n */\nclass ModularSetAnalyzer {\n public:\n  /*!\n   * \\brief analyze the expr\n   * \\param expr The expression of interest.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL ModularSet operator()(const PrimExpr& expr);\n  /*!\n   * \\brief Update constant int bound information of var.\n   *\n   * \\param var The variable of interest.\n   * \\param info The bound information.\n   * \\param allow_override whether we allow override of existing information.\n   */\n  TVM_DLL void Update(const Var& var, const ModularSet& info, bool allow_override = false);\n\n private:\n  friend class Analyzer;\n  friend class ConstraintContext;\n  explicit ModularSetAnalyzer(Analyzer* parent);\n  TVM_DLL ~ModularSetAnalyzer();\n  /*!\n   * \\brief Update the internal state to enter constraint.\n   * \\param constraint A constraint expression.\n   *\n   * \\return an exit function that must be called to cleanup the constraint can be nullptr.\n   */\n  std::function<void()> EnterConstraint(const PrimExpr& constraint);\n  struct Entry;\n  class Impl;\n  /*! \\brief Internal impl */\n  Impl* impl_;\n};\n\n/*!\n * \\brief Rewrite-rule based simplifier.\n */\nclass RewriteSimplifier {\n public:\n  /*!\n   * \\brief analyze the expr\n   * \\param expr The expression of interest.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL PrimExpr operator()(const PrimExpr& expr);\n\n  /*!\n   * \\brief Update binding of var to a new expression.\n   *\n   * \\param var The variable of interest.\n   * \\param new_expr\n   * \\param allow_override Whether we allow override of existing information.\n   */\n  TVM_DLL void Update(const Var& var, const PrimExpr& new_expr, bool allow_override = false);\n\n  /*!\n   * \\brief Update the internal state to enter constraint.\n   * \\param constraint A constraint expression.\n   *\n   * \\return an exit function that must be called to cleanup the constraint can be nullptr.\n   */\n  TVM_DLL std::function<void()> EnterConstraint(const PrimExpr& constraint);\n\n  /*! \\brief Flags to enable more computationally-intensive simplifications\n   *\n   * These simplifications may be required for specific schedules, but\n   * would impose too high a compile-time cost to enable by default.\n   * They can be enabled on an as-needed basis by calling\n   * `RewriteSimplifier::SetEnabledExtensions` prior to using\n   * `RewriteSimplifier::operator()`.\n   *\n   * Flags are defined as powers of two to allow future expansion.  To\n   * enable multiple extensions, a user should pass a bitwise OR of the\n   * flags for each desired extension.\n   */\n  enum Extension {\n    // No extensions enabled\n    kNone = 0,\n\n    /* When simplifying an inequality, attempt to use scope-based knowns.\n     *\n     * Example:\n     * if_then_else(i<j && j<k, i<k, false) => if_then_else(i<j && j<k, true, false)\n     */\n    kTransitivelyProveInequalities = (1 << 0),\n\n    /* When simplifying a boolean expression, convert to an AND of ORs\n     * (conjunctive normal form).\n     *\n     * Example:\n     *   (a && b) || c => (a || c) && (b || c)\n     */\n    kConvertBooleanToAndOfOrs = (1 << 1),\n\n    /* When simplifying a boolean AND or a boolean OR, simplify each\n     * branch under the assumption that the other branch does not\n     * already dominate the result.  That is, simplify each branch of\n     * (A && B) under the assumption that the other branch is true,\n     * and simplify each branch of (A || B) under the assumption that\n     * the other branch is false.\n     *\n     * Example:\n     *   (n < 10) && (n < 5) => (n < 10)\n     *   (n < 10) || (n < 5) => (n < 5)\n     */\n    kApplyConstraintsToBooleanBranches = (1 << 2),\n  };\n\n  /*! \\brief Enable an optional extension or extensions\n   *\n   * \\param flags A bitwise OR of all optional extensions that should\n   * be enabled.\n   */\n  TVM_DLL void SetEnabledExtensions(Extension flags);\n\n  /*! \\brief Return the currently enabled extensions */\n  TVM_DLL Extension GetEnabledExtensions() const;\n\n private:\n  friend class Analyzer;\n  friend class ConstraintContext;\n  friend class CanonicalSimplifier;\n  explicit RewriteSimplifier(Analyzer* parent);\n  TVM_DLL ~RewriteSimplifier();\n  class Impl;\n  /*! \\brief Internal impl */\n  Impl* impl_;\n};\n\n/*!\n * \\brief Canonical-form based simplifier.\n */\nclass CanonicalSimplifier {\n public:\n  /*!\n   * \\brief analyze the expr\n   * \\param expr The expression of interest.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL PrimExpr operator()(const PrimExpr& expr);\n\n  /*!\n   * \\brief Update binding of var to a new expression.\n   *\n   * \\param var The variable of interest.\n   * \\param new_expr\n   * \\param allow_override whether we allow override of existing information.\n   */\n  TVM_DLL void Update(const Var& var, const PrimExpr& new_expr, bool allow_override = false);\n\n private:\n  friend class Analyzer;\n  friend class ConstraintContext;\n  explicit CanonicalSimplifier(Analyzer* parent);\n  TVM_DLL ~CanonicalSimplifier();\n  class Impl;\n  /*! \\brief Internal impl */\n  Impl* impl_;\n};\n\n/*! \\brief Structure for representing result of known\n *\n * Values are assigned to allow these flags to be used in bitwise\n * operations.\n */\nenum class CompareResult : int {\n  kInconsistent = 0,\n  kEQ = 1,\n  kLT = 2,\n  kLE = 3,\n  kGT = 4,\n  kGE = 5,\n  kNE = 6,\n  kUnknown = 7\n};\n\ninline constexpr CompareResult operator&(CompareResult lhs, CompareResult rhs) {\n  return CompareResult(static_cast<int>(lhs) & static_cast<int>(rhs));\n}\ninline constexpr CompareResult operator|(CompareResult lhs, CompareResult rhs) {\n  return CompareResult(static_cast<int>(lhs) | static_cast<int>(rhs));\n}\n\n/*!\n * \\brief Using previously specified knowns, compare the expressions provided\n *\n * Given known expressions [(a OP b), (b OP c), ..., (y OP z)], search\n * for a known result for `(a OP z)`.\n */\nclass TransitiveComparisonAnalyzer {\n public:\n  /* \\brief Using previously specified knowns, compare the expressions provided\n   *\n   * \\param lhs The left-hand side of the comparison\n   *\n   * \\param rhs The right-hand side of the comparison\n   *\n   * \\param propagate_inequalities If true, attempt to find a sequence\n   * of transitive inequalities that allow the lhs and rhs to be\n   * compared.  If false, only use the known comparison that have been\n   * directly provided.  Using `propagate_inequalities = false` is\n   * roughly equivalent to comparing against all known inequality\n   * expressions using `ExprDeepEqual`, but also allows for constant\n   * offsets on either side of the inequality.\n   *\n   * \\return The most specific result that can be proven about the\n   * comparison.  If nothing can be proven, returns kUnknown.\n   */\n  TVM_DLL CompareResult TryCompare(const PrimExpr& lhs, const PrimExpr& rhs,\n                                   bool propagate_inequalities = true);\n\n  /*! \\brief Bind a variable as being equal to a known expression\n   *\n   * \\param var The variable of interest.\n   * \\param expr The bound expression\n   * \\param allow_override Whether to allow override of existing information.\n   */\n  TVM_DLL void Bind(const Var& var, const PrimExpr& expr, bool allow_override = false);\n\n  /*! \\brief Bind a variable as being within a specified range\n   *\n   * \\param var The variable of interest.\n   * \\param range The known range\n   * \\param allow_override Whether to allow override of existing information.\n   */\n  TVM_DLL void Bind(const Var& var, const Range& range, bool allow_override = false);\n\n  /*!\n   * \\brief Update the internal state to enter constraint.\n   * \\param constraint A constraint expression.\n   *\n   * \\return an exit function that must be called to cleanup the constraint can be nullptr.\n   */\n  TVM_DLL std::function<void()> EnterConstraint(const PrimExpr& constraint);\n\n private:\n  friend class Analyzer;\n  friend class ConstraintContext;\n  TransitiveComparisonAnalyzer();\n  TVM_DLL ~TransitiveComparisonAnalyzer();\n  class Impl;\n  /*! \\brief Internal impl */\n  std::unique_ptr<Impl> impl_;\n};\n\n/*!\n * \\brief Constraint context.\n *\n * \\code\n *\n *  Var(\"x\");\n *  arith::Analyzer analyzer;\n *  {\n *    With<arith::ConstraintContext> scope(&analyzer, x % 3 == 0);\n *    ICHECK_EQ(analyzer.modular_set(x)->coeff, 3);\n *  }\n *  // constraint no longer in effect.\n *  ICHECK_NE(analyzer.modular_set(x)->coeff, 3);\n *\n * \\endcode\n */\nclass ConstraintContext {\n private:\n  // declare friend to enable with.\n  friend class With<ConstraintContext>;\n  /*!\n   * \\brief Construct a constraint context.\n   * \\param analyzer The analyzer.\n   * \\param constraint The constraint to be applied.\n   */\n  ConstraintContext(Analyzer* analyzer, PrimExpr constraint)\n      : analyzer_(analyzer), constraint_(constraint) {}\n  // enter the scope.\n  void EnterWithScope();\n  // exit the scope.\n  void ExitWithScope();\n  /*! \\brief The analyzer */\n  Analyzer* analyzer_;\n  /*! \\brief The constraint */\n  PrimExpr constraint_;\n  /*! \\brief function to be called in recovery */\n  std::vector<std::function<void()>> recovery_functions_;\n};\n\n/*!\n * \\brief Integer set analyzer.\n */\nclass IntSetAnalyzer {\n public:\n  /*!\n   * \\brief Find a symbolic integer set that contains all possible values of\n   *        expr given the domain of each variables.\n   *\n   * \\param expr The expression of interest.\n   * \\param dom_map The domain map to indicate which variable to relax.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL IntSet operator()(const PrimExpr& expr, const Map<Var, IntSet>& dom_map);\n\n  /*!\n   * \\brief Find a symbolic integer set that contains all possible\n   *        values of expr given the domain of each variables, using\n   *        the domain map defined by bound variables.\n   *\n   * \\param expr The expression of interest.\n   * \\return the result of the analysis.\n   */\n  TVM_DLL IntSet operator()(const PrimExpr& expr);\n\n  /*!\n   * \\brief Update binding of var to a new expression.\n   *\n   * \\param var The variable of interest.\n   * \\param new_interval_set The set of allowed values for this var.\n   * \\param allow_override whether we allow override of existing information.\n   */\n  TVM_DLL void Update(const Var& var, const IntSet& new_interval_set, bool allow_override = false);\n\n  /*!\n   * \\brief Update binding of var to a new expression.\n   *\n   * \\param var The variable of interest.\n   * \\param new_range The range of allowed values for this var.\n   * \\param allow_override whether we allow override of existing information.\n   */\n  TVM_DLL void Bind(const Var& var, const Range& new_range, bool allow_override = false);\n\n  std::function<void()> EnterConstraint(const PrimExpr& constraint);\n\n private:\n  friend class Analyzer;\n  explicit IntSetAnalyzer(Analyzer* parent);\n  TVM_DLL ~IntSetAnalyzer();\n  class Impl;\n  /*! \\brief Internal impl */\n  Impl* impl_;\n};\n\n/*!\n * \\brief Analyzer that contains bunch of sub-analyzers.\n *\n * Each sub-analyzer can make use of another sub-analyzer\n * by weak reference of this.\n *\n * NOTE for sub-analyzer developers:\n * If the analyzer uses memoization, we need to clear the internal\n * cache when information about a Var has been overridden.\n */\nclass TVM_DLL Analyzer {\n public:\n  /*\n   * Disable copy constructor.\n   */\n  Analyzer(const Analyzer&) = delete;\n  Analyzer& operator=(const Analyzer&) = delete;\n  /*! \\brief sub-analyzer: const integer bound */\n  ConstIntBoundAnalyzer const_int_bound;\n  /*! \\brief sub-analyzer: modular set */\n  ModularSetAnalyzer modular_set;\n  /*! \\brief sub-analyzer rewrite simplify */\n  RewriteSimplifier rewrite_simplify;\n  /*! \\brief sub-analyzer canonical simplify */\n  CanonicalSimplifier canonical_simplify;\n  /*! \\brief sub-analyzer: int set */\n  IntSetAnalyzer int_set;\n  /*! \\brief sub-analyzer transitive comparisons */\n  TransitiveComparisonAnalyzer transitive_comparisons;\n  /*! \\brief constructor */\n  Analyzer();\n  /*!\n   * \\brief Notify all the sub-analyzers that var\n   *        is created and binded to expr.\n   *\n   *  Each var can only be bound once.\n   *\n   * \\param var The variable.\n   * \\param expr The expression we bind to.\n   * \\param allow_override Whether we allow overriding an existing var's\n   *        expression. This option should not be used if there is any dependency\n   *        between variables.\n   */\n  void Bind(const Var& var, const PrimExpr& expr, bool allow_override = false);\n  /*!\n   * \\brief Notify all the sub-analyzers that var\n   *        is created and binded to a range.\n   *\n   *  Each var can only be binded once.\n   *\n   * \\param var The variable.\n   * \\param range The range we bind to.\n   * \\param allow_override Whether we allow overriding an existing var's\n   *        expression. This option should not be used if there is any dependency\n   *        between variables.\n   */\n  void Bind(const Var& var, const Range& range, bool allow_override = false);\n  /*!\n   * \\brief Bind all the vars in the Map\n   *\n   * \\param variables The {variable -> range} map.\n   * \\param allow_override Whether we allow overriding an existing var's\n   *        expression. This option should not be used if there is any dependency\n   *        between variables.\n   */\n  void Bind(const Map<Var, Range>& variables, bool allow_override = false);\n  /*!\n   * \\brief Whether can we prove expr >= val.\n\n   *  Non-negative proof is very useful in integer analysis\n   *  to lower divisions and mods given difference in trunc and ceil mode.\n   *\n   * \\param expr The expression.\n   * \\param lower_bound The lower bound.\n   * \\return Whether we can prove it.\n   *\n   * \\note Analyzer will call into sub-analyzers to get the result.\n   */\n  bool CanProveGreaterEqual(const PrimExpr& expr, int64_t lower_bound);\n  /*!\n   * \\brief Whether can we prove expr < val.\n\n   *  Non-negative proof is very useful in integer analysis\n   *  to lower divisions and mods given difference in trunc and ceil mode.\n   *\n   * \\param expr The expression.\n   * \\param upper_bound The upper bound.\n   * \\return Whether we can prove it.\n   *\n   * \\note Analyzer will call into sub-analyzers to get the result.\n   */\n  bool CanProveLess(const PrimExpr& expr, int64_t upper_bound);\n  /*!\n   * \\brief Whether can we prove lhs == rhs.\n   *\n   * \\param lhs The input lhs.\n   * \\param rhs The input rhs.\n   * \\return Whether we can prove lhs == rhs.\n   *\n   * \\note Analyzer will call into sub-analyzers to get the result.\n   */\n  bool CanProveEqual(const PrimExpr& lhs, const PrimExpr& rhs);\n  /*!\n   * \\brief Whether can we prove condition.\n   *\n   * \\param cond The expression to be proved.\n   * \\return The result.\n   *\n   * \\note Analyzer will call into sub-analyzers to get the result.\n   */\n  bool CanProve(const PrimExpr& cond);\n  /*!\n   * \\brief Simplify expr.\n   *\n   * \\param expr The expression to be simplified.\n   * \\param steps The simplification runs in the order of\n   *        rewrite_simplify (step 1) -> canonical_simplify (step 2) ->\n   *        rewrite_simplify (step 3) -> canonical_simplify (step 4) -> ...\n   *        param steps controls how many steps to run.\n   *        Default is 2, i.e., rewrite_simplify + canonical_simplify.\n   * \\return The result.\n   *\n   * \\note Analyzer will call into sub-analyzers to get the result.\n   */\n  PrimExpr Simplify(const PrimExpr& expr, int steps = 2);\n};\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_ANALYZER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/bound.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/arith/bound.h\n * \\brief Bound deducers.\n */\n#ifndef TVM_ARITH_BOUND_H_\n#define TVM_ARITH_BOUND_H_\n\n#include <tvm/arith/int_set.h>\n#include <tvm/ir/expr.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt.h>\n\n#include <unordered_map>\n\nnamespace tvm {\nnamespace arith {\n\nusing tir::Region;\nusing tir::Stmt;\nusing tir::Var;\nusing tir::VarNode;\n\n/*!\n * \\brief Deduce the bound of the target variable in a expression,\n *  give the domain of each variables. Return undefined IntSet to\n *  represent failure.\n *\n * \\note The returned set may be smaller than set that\n *       contains all possible values of v that satisfies the bound.\n *\n * \\param v The target variable to be deduced.\n * \\param cond The conditional expression.\n * \\param hint_map The domain of variable, used to help deduce.\n * \\param relax_map The domain of each variable, used to relax the domain,\n *        The deduce bound must implies e for all value in relax_map\n * \\return An integer set that always satisfies the condition.\n */\nIntSet DeduceBound(PrimExpr v, PrimExpr cond, const Map<Var, IntSet>& hint_map,\n                   const Map<Var, IntSet>& relax_map);\n/*!\n * \\brief Same as DeduceBound with  unordered_map signature.\n *\n * \\param v The target variable to be deduced.\n * \\param cond The conditional expression.\n * \\param hint_map The domain of variable, used to help deduce.\n * \\param relax_map The domain of each variable, used to relax the domain,\n *        The deduce bound mush implies e for all value in relax_map\n * \\return An integer set that always satisfies the condition.\n */\nIntSet DeduceBound(PrimExpr v, PrimExpr cond,\n                   const std::unordered_map<const VarNode*, IntSet>& hint_map,\n                   const std::unordered_map<const VarNode*, IntSet>& relax_map);\n\n/*!\n * \\brief Infer a regular domain that covers all the calls or provides within the given statement.\n * \\param body The given statement.\n * \\param buffer The buffer to check the access info.\n * \\param consider_loads If loads are considered.\n * \\param consider_stores If stores are considered.\n * \\return The domain that covers all the calls or provides within the given statement.\n */\nRegion DomainTouched(const Stmt& body, const tir::Buffer& buffer, bool consider_loads,\n                     bool consider_stores);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_BOUND_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/int_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arith/int_set.h\n * \\brief Integer set\n */\n#ifndef TVM_ARITH_INT_SET_H_\n#define TVM_ARITH_INT_SET_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n\nnamespace tvm {\nnamespace arith {\n\nusing tir::IterVar;\nusing tir::Var;\nusing tir::VarNode;\n\nclass Analyzer;\n\n//-----------------------------------------------\n// Integer set data structure.\n//\n// This is a API build on top of the base\n// integer analysis API to provide set analysis.\n//------------------------------------------------\n/*!\n * \\brief Sign type of an integer expression.\n */\nenum SignType { kPositive, kNegative, kZero, kUnknown };\n\n/*!\n * \\brief Base class of all Integer set containers.\n *        represent a set of integers in one dimension.\n * \\sa IntSet\n */\nclass IntSetNode : public Object {\n public:\n  static constexpr const char* _type_key = \"IntSet\";\n  static constexpr bool _type_has_method_sequal_reduce = false;\n  TVM_DECLARE_BASE_OBJECT_INFO(IntSetNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IntSetNode.\n * \\sa IntSetNode\n */\nclass IntSet : public ObjectRef {\n public:\n  /*!\n   * \\brief Find a range that covers the region.\n   * \\param max_range The range to be covered.\n   * \\return The covering range.\n   */\n  Range CoverRange(Range max_range) const;\n  /*! \\return Lower bound of the set */\n  PrimExpr min() const;\n  /*! \\return upper bound of the set */\n  PrimExpr max() const;\n  /*! \\return The sign of the elements in the integer set */\n  SignType GetSignType() const;\n  /*! \\return Whether the set represent nothing  */\n  bool IsNothing() const;\n  /*! \\return Whether the set represent everything  */\n  bool IsEverything() const;\n  /*! \\return Whether the set is a single point */\n  bool IsSinglePoint() const;\n  /*! \\return Whether the set is proved to be bigger than 0 */\n  bool CanProvePositive() const;\n  /*! \\return Whether the set is proved to be smaller than 0 */\n  bool CanProveNegative() const;\n  /*! \\return Whether the set is proved to be smaller than or equal to 0 */\n  bool CanProveNonPositive() const;\n  /*! \\return Whether the set is proved to be larger than or equal to 0 */\n  bool CanProveNonNegative() const;\n  /*! \\return Whether the set has upper bound. */\n  bool HasUpperBound() const;\n  /*! \\return Whether the set has lower bound. */\n  bool HasLowerBound() const;\n\n  /*!\n   * \\brief The single point value, call only if IsSinglePoint is true\n   * \\return The point value.\n   */\n  PrimExpr PointValue() const;\n  /*!\n   * \\brief Try to match IntSet with range r.\n   *\n   * \\note It is guanrateed that IntSet::FromRange(r).MatchRange(r) == true\n   * \\return true if we can prove they are the same.\n   */\n  bool MatchRange(const tvm::Range& r) const;\n  /*! \\return The set contains nothing */\n  static IntSet Nothing();\n  /*! \\return The set contains everything */\n  static IntSet Everything();\n  /*!\n   * \\brief construct a point set.\n   * \\param point The point in the set.\n   * \\return construct a single point set\n   */\n  static IntSet SinglePoint(PrimExpr point);\n  /*!\n   * \\brief construct a integer set from vector expression.\n   * \\param vec The vector expression, can also be single point.\n   * \\return The result set containing the indices in the vector.\n   */\n  static IntSet Vector(PrimExpr vec);\n  /*!\n   * \\brief Construct a set representing a range [min, min + extent).\n   * \\param min The minimum of the range range\n   * \\param extent The extent of the range.\n   * \\return The constructed set.\n   */\n  static IntSet FromMinExtent(PrimExpr min, PrimExpr extent);\n  /*!\n   * \\brief Construct a set representing a range.\n   * \\param r The range\n   * \\return The constructed set.\n   */\n  static IntSet FromRange(tvm::Range r);\n  /*!\n   * \\brief Construct a set representing a interval.\n   * \\param min The minimum value of the interval.\n   * \\param max The maximum value of the interval.\n   * \\return The constructed set.\n   */\n  static IntSet Interval(PrimExpr min, PrimExpr max);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IntSet, ObjectRef, IntSetNode);\n};\n\n//-----------------------------------------------\n// Integer set legacy API.\n//------------------------------------------------\n/*!\n * \\brief Convert std::unordered_map<const VarNode*, IntSet> to Map<Var, IntSet>\n *\n * \\param dom_map The domain map to convert.\n * \\return The converted map.\n */\nMap<Var, IntSet> ConvertDomMap(const std::unordered_map<const VarNode*, IntSet>& dom_map);\n/*!\n * \\brief Find an symbolic integer set that contains all possible values of\n *  e given the domain of each iteration variables.\n *\n * \\param e The expression to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values of e.\n */\nIntSet EvalSet(PrimExpr e, const Map<IterVar, IntSet>& dom_map);\n/*!\n * \\brief Find an symbolic integer set that contains all possible values of\n *  e given the domain of each variables.\n *\n * \\param e The expression to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values of e.\n */\nIntSet EvalSet(PrimExpr e, const Map<Var, IntSet>& dom_map);\n/*!\n * \\brief Same as EvalSet, but takes unordered_map\n *\n * \\param e The expression to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values of e.\n */\nIntSet EvalSet(PrimExpr e, const std::unordered_map<const tir::VarNode*, IntSet>& dom_map);\n/*!\n * \\brief Find an symbolic integer set that contains is union over\n *  all the possible conditional values in dom_map.\n *\n * \\param r The initial range.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values.\n */\nIntSet EvalSet(Range r, const Map<IterVar, IntSet>& dom_map);\n\n/*!\n * \\brief Find an symbolic integer set that contains is union over\n *  all the possible conditional values in dom_map.\n *\n * \\param s The initial set.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values.\n */\nIntSet EvalSet(IntSet s, const std::unordered_map<const VarNode*, IntSet>& dom_map);\n/*!\n * \\brief Same as EvalSet, but takes unordered_map\n *\n * \\param r The range to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An integer set that can cover all the possible values of e.\n */\nIntSet EvalSet(Range r, const std::unordered_map<const VarNode*, IntSet>& dom_map);\n/*!\n * \\brief Same as EvalSet, but takes Array<Range>\n *\n * \\param region The range to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An array of integer sets that can cover all the possible values.\n */\nArray<IntSet> EvalSet(const Array<Range>& region, const Map<Var, IntSet>& dom_map);\n/*! \\brief Map from Expr to IntSet */\nusing ExprIntSetMap = std::unordered_map<PrimExpr, IntSet, ObjectPtrHash, ObjectPtrEqual>;\n/*!\n * \\brief Find the integer set of every sub-expression, given the\n *  domain of each iteration variables.\n *\n * \\param e The expression to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return the map from the expression to its possible value.\n */\nExprIntSetMap EvalSetForEachSubExpr(PrimExpr e,\n                                    const std::unordered_map<const VarNode*, IntSet>& dom_map);\n\n/*!\n * \\brief Create a union set of all sets, possibly relaxed\n * \\param sets The sets to be combined\n * \\return the set after union\n */\nIntSet Union(const Array<IntSet>& sets);\n\n/*!\n * \\brief The union of N-dimensional integer sets\n * \\param nd_int_sets A list of N-dimensional integer sets\n * \\return An N-dimensional integer set as the result of union\n */\nArray<IntSet> UnionRegion(const Array<Array<IntSet>>& nd_int_sets);\n\n/*!\n * \\brief Create a lower-bound of union set, where some of the segments may be dropped\n * \\param sets The sets to be combined\n * \\return the set after union\n */\nIntSet UnionLowerBound(const Array<IntSet>& sets);\n\n/*!\n * \\brief The union of N-dimensional integer sets\n * \\param nd_int_sets A list of N-dimensional integer sets\n * \\return An N-dimensional integer set as the result of union\n */\nArray<IntSet> UnionRegionLowerBound(const Array<Array<IntSet>>& nd_int_sets);\n\n/*!\n * \\brief Create an intersected set of all sets\n * \\param sets The sets to be intersected\n * \\return the set after intersected\n */\nIntSet Intersect(const Array<IntSet>& sets);\n\n/*!\n * \\brief Converts the Ranges to IntSets\n * \\param var_dom The ranges of variables\n * \\return The integer sets of the variables\n */\nMap<Var, arith::IntSet> AsIntSet(const Map<Var, Range>& var_dom);\n\n/*!\n * \\brief Analyze the region with affine map, given the domain of variables and their predicate.\n * The result should be strict, i.e. no region is discarded or relaxed.\n * \\param region The region to be analyzed\n * \\param var_dom The ranges of the variables\n * \\param predicate The predicate for the affine map\n * \\param analyzer The analyzer used\n * \\return NullOpt if the detection fails, or an array of arith::IntSet as the result of analysis\n */\nTVM_DLL Optional<Array<IntSet>> EstimateRegionStrictBound(const Array<Range>& region,\n                                                          const Map<Var, Range>& var_dom,\n                                                          const PrimExpr& predicate,\n                                                          arith::Analyzer* analyzer);\n\n/*!\n * \\brief Analyze the region with affine map, given the domain of variables and their predicate.\n * Some subregion may be discarded during the lower-bound analysis.\n * \\param region The region to be analyzed\n * \\param var_dom The ranges of the variables\n * \\param predicate The predicate for the affine map\n * \\param analyzer The analyzer used\n * \\return NullOpt if the detection fails, or an array of arith::IntSet as the result of analysis\n */\nTVM_DLL Optional<Array<IntSet>> EstimateRegionLowerBound(const Array<Range>& region,\n                                                         const Map<Var, Range>& var_dom,\n                                                         const PrimExpr& predicate,\n                                                         arith::Analyzer* analyzer);\n\n/*!\n * \\brief Analyze the region with affine map, given the domain of variables and their predicate\n * Relaxation of the region may be used in upper-bound analysis, i.e. some extra region may be added\n * to the result.\n * \\param region The region to be analyzed\n * \\param var_dom The ranges of the variables\n * \\param predicate The predicate for the affine map\n * \\param analyzer The analyzer used\n * \\return an array of arith::IntSet as the result of analysis\n */\nTVM_DLL Array<IntSet> EstimateRegionUpperBound(const Array<Range>& region,\n                                               const Map<Var, Range>& var_dom,\n                                               const PrimExpr& predicate,\n                                               arith::Analyzer* analyzer);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_INT_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/int_solver.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arith/int_solver.h\n * \\brief integer constraints data structures and solvers\n */\n#ifndef TVM_ARITH_INT_SOLVER_H_\n#define TVM_ARITH_INT_SOLVER_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"analyzer.h\"\n\nnamespace tvm {\nnamespace arith {\n\nusing tir::IterVar;\nusing tir::Var;\nusing tir::VarNode;\n\n// According to experiments two best simplifications orders were can->rw and rw->can->rw,\n// but rw->can->rw is better for a couple of cases.\n// Also we should end with rw because it factors multipliers out.\nconstexpr int kSimplifyRewriteCanonicalRewrite = 3;\n\n/*!\n * \\brief Represent integer grouped bounds which are classified into\n *        lower bounds (inclusive), upper bounds (inclusive) and equalities.\n *        It also contains coefficient as a multiplier for the bounds, i.e.,\n *        coef * var >= lower\n *        coef * var == equal\n *        coef * var <= upper\n * \\sa IntGroupBounds\n */\nclass IntGroupBoundsNode : public Object {\n public:\n  PrimExpr coef;\n  Array<PrimExpr> lower;\n  Array<PrimExpr> equal;\n  Array<PrimExpr> upper;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"coef\", &coef);\n    v->Visit(\"lower\", &lower);\n    v->Visit(\"equal\", &equal);\n    v->Visit(\"upper\", &upper);\n  }\n\n  bool SEqualReduce(const IntGroupBoundsNode* other, SEqualReducer eq) const {\n    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&\n           eq(upper, other->upper);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(coef);\n    hash_reduce(lower);\n    hash_reduce(equal);\n    hash_reduce(upper);\n  }\n\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const char* _type_key = \"arith.IntGroupBounds\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IntGroupBoundsNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IntGroupBoundsNode.\n * \\sa IntGroupBoundsNode\n */\nclass IntGroupBounds : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor by fields\n   * \\param coef The coefficient. Must be integer.\n   *        coef * var >= lower\n   *        coef * var == equal\n   *        coef * var >= upper\n   * \\param lower the lower bounds (include)\n   * \\param equal equalities\n   * \\param upper the upper bounds (include)\n   */\n  TVM_DLL IntGroupBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,\n                         Array<PrimExpr> upper);\n\n  /*!\n   * \\brief Construct bounds from a range.\n   * \\param r The range\n   * \\return constructed bounds.\n   */\n  static IntGroupBounds FromRange(const Range& r);\n\n  /*!\n   * \\brief Perform substitution on all components of the struct.\n   */\n  IntGroupBounds Substitute(const Map<Var, PrimExpr>& subst) const;\n\n  /*!\n   * \\brief Find the best range from the grouped bounds.\n   * \\param vranges_addl additional variable ranges that help infer the best range.\n   * \\return The best range (has the least difference between the lower bound and upper bound).\n   *         undefined if (-inf, +inf).\n   */\n  Range FindBestRange(const Map<Var, Range>& vranges_addl = {}) const;\n\n  /*!\n   * \\brief Combine the bounds with another range.\n   * \\param r range to be combined.\n   * \\return combined bounds.\n   */\n  IntGroupBounds operator+(const Range& r);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IntGroupBounds, ObjectRef, IntGroupBoundsNode);\n};\n\n/*!\n * \\brief Represent integer constrains including (integer) variables, their ranges and\n *        the relations between them (either equations or inequalities).\n * \\sa LinearSystem\n */\nclass IntConstraintsNode : public Object {\n public:\n  // e.g., \\alpha, \\beta, must be integers\n  Array<Var> variables;\n  // e.g., 1 <= \\alpha <= N, etc.\n  // it is absolutely ok to include ranges for parameters\n  // (variables that are not in this->variables) in this map\n  Map<Var, Range> ranges;\n  // linear equalities or inequalities\n  // e.g., A \\alpha = \\beta or A \\alpha <= \\beta\n  Array<PrimExpr> relations;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"variables\", &variables);\n    v->Visit(\"ranges\", &ranges);\n    v->Visit(\"relations\", &relations);\n  }\n\n  bool SEqualReduce(const IntConstraintsNode* other, SEqualReducer equal) const {\n    return equal(variables, other->variables) && equal(ranges, other->ranges) &&\n           equal(relations, other->relations);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(variables);\n    hash_reduce(ranges);\n    hash_reduce(relations);\n  }\n\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const char* _type_key = \"arith.IntConstraints\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IntConstraintsNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IntConstraintsNode.\n * \\sa IntConstraintsNode\n */\nclass IntConstraints : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor by fields\n   * \\param variables The variables in the constraints, must be integers.\n   * \\param ranges    The ranges of the variables.\n   * \\param relations The linear relations between the variables\n   *                  (either equations or inequalities)\n   */\n  TVM_DLL IntConstraints(Array<Var> variables, Map<Var, Range> ranges, Array<PrimExpr> relations);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IntConstraints, ObjectRef, IntConstraintsNode);\n};\n\n/*!\n * \\brief We can have different set of variables to represent the same constraints.\n *        For example, the following two systems are equivalent,\n *        {a + b = 0 | a >= 0, b >= 0} and\n *        {m - n = 0 | m >= 0, n <= 0}\n *        This data structure represents the transformation\n *        between two equivalent linear systems.\n *        In the above example,\n *        src        : {a + b = 0 | a >= 0, b >= 0}\n *        dst        : {m - n = 0 | m >= 0, n <= 0}\n *        src_to_dst : {a -> m, b -> -n}\n *        dst_to_src : {m -> a, n -> -b}\n * \\sa IntConstraintsTransform\n */\nclass IntConstraintsTransformNode : public Object {\n public:\n  IntConstraints src;\n  IntConstraints dst;\n  Map<Var, PrimExpr> src_to_dst;\n  Map<Var, PrimExpr> dst_to_src;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"src\", &src);\n    v->Visit(\"dst\", &dst);\n    v->Visit(\"src_to_dst\", &src_to_dst);\n    v->Visit(\"dst_to_src\", &dst_to_src);\n  }\n\n  bool SEqualReduce(const IntConstraintsTransformNode* other, SEqualReducer equal) const {\n    return equal(src, other->src) && equal(dst, other->dst) &&\n           equal(src_to_dst, other->src_to_dst) && equal(dst_to_src, other->dst_to_src);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(src);\n    hash_reduce(dst);\n    hash_reduce(src_to_dst);\n    hash_reduce(dst_to_src);\n  }\n\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const char* _type_key = \"arith.IntConstraintsTransform\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IntConstraintsTransformNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IntConstraintsTransformNode.\n * \\sa IntConstraintsTransformNode\n */\nclass IntConstraintsTransform : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor by fields\n   * \\param src        source integer constraints, e.g., {a + b = 0 | a >= 0, b >= 0}\n   * \\param dst        integer constraints equivalent to the source,\n   *                   e.g., {m - n = 0 | m >= 0, n <= 0}\n   * \\param src_to_dst mapping from variables in the \\p src to the variables in the \\p dst,\n   *                   e.g., {a -> m, b -> -n}\n   * \\param dst_to_src mapping from variables in the \\p dst to the variables in the \\p src,\n   *                   e.g., {m -> a, n -> -b}\n   */\n  TVM_DLL IntConstraintsTransform(IntConstraints src, IntConstraints dst,\n                                  Map<Var, PrimExpr> src_to_dst, Map<Var, PrimExpr> dst_to_src);\n\n  /*!\n   * \\brief Chain-compose two IntConstraintsTransform together.\n   *        this->dst must be the same as other->src.\n   * @param other another IntConstraintsTransform whose src is same as this->dst.\n   * @return composed IntConstraintsTransform(this->src, other->dst)\n   *         with its variables and ranges are properly modified.\n   */\n  IntConstraintsTransform operator+(const IntConstraintsTransform& other) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IntConstraintsTransform, ObjectRef, IntConstraintsTransformNode);\n};\n\ntypedef std::pair<Map<Var, IntGroupBounds>, Array<PrimExpr>> PartialSolvedInequalities;\n\n/*!\n * \\brief Obtain Smith Normal Form of linear equation A x = y.\n *        Smith Normal Form of matrix A_{mxn} is S_{mxn} = U_{mxm} A_{mxn} V_{nxn},\n *        in which S_{mxn} is diag(s1, s2, ..., sr, 0, ..., 0) and r is the rank of A.\n *        NOTE: Although in standard Smith Normal Form the diagonal elements satisfy\n *              s_i | s_{i+1} (| means divides), the implement here does not guarantee it.\n *        TODO(yzhliu): From sergei-grechanik:\n *          computing the proper Smith normal form may improve stability of automatic\n * differentiation (generating the same gradient code for slightly different but equivalent input\n * code U_{mxm} and V_{nxn} are invertible matrices. This function modifies \\p S to be S_{mxn}, \\p V\n * to be V_{nxn}, \\p y to be U_{mxm} y_{mx1} and \\p x to be V^{-1} x. \\param S  the original\n * A_{mxn}, it will be modified to S_{mxn} \\param V  an identity matrix, it will be modified to\n * V_{nxn} \\param x  the x in A x = y. it will be modified to V^{-1}_{nxn} x_{nx1} \\param y  the y\n * in A x = y. it will be modified to U_{mxm} y_{mx1}\n */\nvoid SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::vector<int64_t>>* V,\n                         std::vector<PrimExpr>* x, std::vector<PrimExpr>* y);\n\n/*!\n * \\brief Solve linear equations.\n * \\param system_to_solve the variables to solve, their ranges, and a list of equations.\n * \\return  A new linear system, with less variables (if \\p system_to_solve is NOT of full rank),\n *          or no variable (if \\p system_to_solve is of full rank),\n *          or an empty linear system (if \\p system_to_solve is unsolvable).\n *          It also provides the ranges of the variables in the new system,\n *          as well as inequalities inferred from the \\p system_to_solve.\n *          You can get the mapping from the original variables to the solution via ret->src_to_dst.\n */\nIntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);\n\n/*!\n * \\brief Solve linear inequalities.\n * \\param system_to_solve the variables to solve, their ranges, and a list of inequalities.\n *        The inequalities are rewritten using Fourier-Motzkin elimination.\n *        This function takes an array of (in)equalities and an array of variables, and essentially\n *        rewrites the (in)equalities into an array of (in)equalities of the following form,\n *\n *        x0 >= f0(x1, x2, ..., xn)\n *        x0 <= g0(x1, x2, ..., xn)\n *        x1 >= f1(x2, ..., xn)\n *        x1 <= g1(x2, ..., xn)\n *        ...\n *        xn >= fn()  // just a constant\n *        xn <= gn()  // just a constant\n *\n * \\return A map of variables and their solved bounds,\n *         and constrains that cannot be solved to bounds.\n */\nPartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);\n\n/*!\n * \\brief Combine the information into an array of (in)equalities.\n * \\param variables The variables in \\p bounds.\n *        It is used to determine the iteration order to avoid indeterministic results.\n * \\param bounds grouped boundary of the variables.\n * \\param relations other relations.\n */\nArray<PrimExpr> AsConditions(const Array<Var>& variables, const Map<Var, IntGroupBounds>& bounds,\n                             const Array<PrimExpr>& relations);\n\n/*!\n * \\brief Solve linear inequalities and infer the range of each variable.\n * \\param system_to_solve the variables to solve, their ranges, and a list of inequalities.\n * \\return The result ranges for each variables.\n *         The returned IntConstraints(variables, ranges, relations) contains,\n *         1. variables  - the variables that have been solved.\n *         2. ranges     - the best range of each variable.\n *         3. relations  - constraints that cannot be transformed to\n *                         Range will be stored in relations.\n */\nIntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);\n\n/*!\n * \\brief Solve linear inequalities and deskew the ranges towards zero.\n * \\param system_to_solve the variables to solve, their ranges, and a list of inequalities.\n * \\return A transform (src IntConstraints -> dst IntConstraints)\n *         from original variables to a set of new variables.\n *         The ranges of new variables always start from zero,\n *         their extents are solved from \\p system_to_solve.\n *         src IntConstraints is the same as \\p system_to_solve.\n *         dst IntConstraints(variables, ranges, relations) contains,\n *         1. variables  - the variables that have been solved.\n *         2. ranges     - the best range (start from zero) of each variable.\n *         3. relations  - constraints that cannot be transformed to\n *                         Range will be stored in relations.\n *         Variable mapping can be obtained from\n *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.\n */\nIntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_INT_SOLVER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/iter_affine_map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arith/iter_affine_map.h\n * \\brief Iterator quasi-affine mapping patterns.\n *\n *  This file defines a collection of mapping patterns\n *  maps a collection of independent iterators to another\n *  collection of independent iterators.\n *\n *  There are two main kinds of mapping patterns:\n *\n *  - Fuse: fuse a collection of iterators into a single one\n *\n *    domain(x0) = [0, 4), domain(x1) = [0, 3), domain(x2) = [0, 2)\n *    fuse(x0, x1, x2): y = x2 * 12 + x1 * 4 + x0\n *    domain(y) = [0, 24)\n *\n *  - Split: split an iterator into multiple ones\n *\n *    domain(x) = [0, 24)\n *    split(x, 3, 12): [y0, y1, y2] = [x % 3, (x % 12) / 3, x / 12]\n *    domain(y0) = [0, 3), domain(y1) = [0, 4), domain(y2) = [0, 2)\n *\n *  We use the name \"(quasi)affine\" to be consistent with\n *  the terminology used in the polyhedral compilation.\n *  Notably, fuse is an affine transformation,\n *  while split corresponds to additional floordiv/mod operations\n *  that can appear in quasi-affine transformations.\n */\n#ifndef TVM_ARITH_ITER_AFFINE_MAP_H_\n#define TVM_ARITH_ITER_AFFINE_MAP_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/ir/diagnostic.h>\n#include <tvm/ir/expr.h>\n#include <tvm/tir/var.h>\n\nnamespace tvm {\nnamespace arith {\n\n/*!\n * \\brief Base class of all iter map expressions.\n *\n *  An IterMapExpr is a special expression to store\n *  the result of IterMapDetection.\n *  It should not appear in a legal TIR PrimFunc.\n */\nclass IterMapExprNode : public PrimExprNode {\n public:\n  // overrides\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"arith.IterMapExpr\";\n  static constexpr const uint32_t _type_child_slots = 3;\n  TVM_DECLARE_BASE_OBJECT_INFO(IterMapExprNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to IterMapExprNode.\n * \\sa IterMapExprNode\n */\nclass IterMapExpr : public PrimExpr {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(IterMapExpr, PrimExpr, IterMapExprNode);\n};\n\n/*!\n * \\brief Mark the source as an iterator in [0, extent).\n *\n *  IterMark is used to mark source expression as a valid\n *  iterator to make future analysis easy.\n */\nclass IterMarkNode : public Object {\n public:\n  /*!\n   * \\brief The source expression, can either be\n   *  a IterSumExpr or a Var.\n   */\n  PrimExpr source;\n  /*!\n   * \\brief The extent of the iteration.\n   */\n  PrimExpr extent;\n\n  // overrides\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"source\", &source);\n    v->Visit(\"extent\", &extent);\n  }\n\n  bool SEqualReduce(const IterMarkNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(source, other->source) && equal(extent, other->extent);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(source);\n    hash_reduce(extent);\n  }\n\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  static constexpr const char* _type_key = \"arith.IterMark\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterMarkNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IterMarkExprNode.\n * \\sa IterMarkExprNode\n */\nclass IterMark : public ObjectRef {\n public:\n  /*!\n   * \\brief constructor.\n   * \\param source The source expression.\n   * \\param extent The extent of the iterator.\n   */\n  TVM_DLL IterMark(PrimExpr source, PrimExpr extent);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IterMark, ObjectRef, IterMarkNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IterMarkNode);\n};\n\n/*!\n * \\brief Split of an iterator.\n *\n *  result = floormod(floordiv(source, lower_factor), extent) * scale\n */\nclass IterSplitExprNode : public IterMapExprNode {\n public:\n  /*! \\brief The source marked iterator. */\n  IterMark source;\n  /*! \\brief The lower factor to split the source. */\n  PrimExpr lower_factor;\n  /*! \\brief The extent of the split. */\n  PrimExpr extent;\n  /*! \\brief Additional scale. */\n  PrimExpr scale;\n\n  // overrides\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"source\", &source);\n    v->Visit(\"lower_factor\", &lower_factor);\n    v->Visit(\"extent\", &extent);\n    v->Visit(\"scale\", &scale);\n  }\n\n  bool SEqualReduce(const IterSplitExprNode* other, SEqualReducer equal) const {\n    return equal(source, other->source) && equal(lower_factor, other->lower_factor) &&\n           equal(extent, other->extent) && equal(scale, other->scale);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(source);\n    hash_reduce(lower_factor);\n    hash_reduce(extent);\n    hash_reduce(scale);\n  }\n\n  static constexpr const char* _type_key = \"arith.IterSplitExpr\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterSplitExprNode, IterMapExprNode);\n};\n\n/*!\n * \\brief Managed reference to IterSplitExprNode.\n * \\sa IterSplitExprNode\n */\nclass IterSplitExpr : public IterMapExpr {\n public:\n  /*!\n   * \\brief constructor from just source.\n   * \\param source The source expression.\n   */\n  TVM_DLL explicit IterSplitExpr(IterMark source);\n  /*!\n   * \\brief constructor from just source.\n   * \\param source The source expression.\n   * \\param scale The additional scaling factor.\n   */\n  TVM_DLL explicit IterSplitExpr(IterMark source, PrimExpr scale);\n  /*!\n   * \\brief constructor\n   * \\param source The source expression.\n   * \\param lower_factor The lower factor to split the source.\n   * \\param extent The extent of the split.\n   * \\param scale The additional scaling factor.\n   */\n  TVM_DLL explicit IterSplitExpr(IterMark source, PrimExpr lower_factor, PrimExpr extent,\n                                 PrimExpr scale);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IterSplitExpr, IterMapExpr, IterSplitExprNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IterSplitExprNode);\n};\n\n/*!\n * \\brief Fuse multiple iterators by summing them with scaling.\n *\n *  result = sum(args) + base\n */\nclass IterSumExprNode : public IterMapExprNode {\n public:\n  /*! \\brief The args to the sum. */\n  Array<IterSplitExpr> args;\n  /*! \\brief The base offset. */\n  PrimExpr base;\n\n  // overrides\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"args\", &args);\n    v->Visit(\"base\", &base);\n  }\n\n  bool SEqualReduce(const IterSumExprNode* other, SEqualReducer equal) const {\n    return equal(args, other->args) && equal(base, other->base);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(args);\n    hash_reduce(base);\n  }\n\n  static constexpr const char* _type_key = \"arith.IterSumExpr\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterSumExprNode, IterMapExprNode);\n};\n\n/*!\n * \\brief Managed reference to IterSumExprNode.\n * \\sa IterSumExprNode\n */\nclass IterSumExpr : public IterMapExpr {\n public:\n  /*!\n   * \\brief constructor.\n   * \\param args The args to the sum.\n   * \\param base The base offset.\n   */\n  TVM_DLL IterSumExpr(Array<IterSplitExpr> args, PrimExpr base);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IterSumExpr, IterMapExpr, IterSumExprNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IterSumExprNode);\n};\n\n/*! \\brief Mapping level for iterators. */\nenum IterMapLevel {\n  // Require the mapping to be bijective.\n  Bijective = 0,\n  // Require the mapping to be surjective.\n  Surjective = 1,\n  // No mapping safety check.\n  NoCheck = 3\n};\n\n/*!\n * \\brief Result of DetectIterMap.\n */\nclass IterMapResultNode : public Object {\n public:\n  // The detected pattern if a match exists.\n  Array<IterSumExpr> indices;\n\n  // Any errors that occurred while converting the input indices.  If\n  // the array is empty, the conversion was successful.\n  Array<String> errors;\n\n  /*! \\brief Boolean expression indicating if a specific value w\n   *\n   * `padding_predicate` evaluates to true for a set of indices that\n   * are outside the bounds of the provided index iterators, but\n   * inside the bounds of the returned index iterators.  This\n   * expression is in terms of the variables provided in\n   * `input_iters`.\n   */\n  PrimExpr padding_predicate;\n\n  // overrides\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"errors\", &errors);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"padding_predicate\", &padding_predicate);\n  }\n\n  static constexpr const char* _type_key = \"arith.IterMapResult\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterMapResultNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IterMapResultNode.\n * \\sa IterMapResultNode\n */\nclass IterMapResult : public ObjectRef {\n public:\n  // constructor\n  IterMapResult() { data_ = make_object<IterMapResultNode>(); }\n\n  /*! \\return mutable pointers to the node. */\n  IterMapResultNode* operator->() const { return static_cast<IterMapResultNode*>(get_mutable()); }\n};\n\n/*!\n * \\brief Detect if indices can be written as\n *  [y_0 + c_0, y_1 + c_1, ..., y_n + c_n]\n *\n *  Here y = some-quasi-affine-iter-map(input_iters)\n *  and c are symbolic constants.\n *\n *  We also requires that y_i and y_j to be independent for i != j.\n *\n *  For returned value rv, the following is always true:\n *  - rv[i]->args.size() <=1: only one iterator per element.\n *\n * \\param indices The indices to detect pattern for.\n * \\param input_iters Map from variable to iterator's range.\n * \\param predicate The predicate constraints on the input iterators\n * \\param check_level The iter mapping checking level.\n * \\param analyzer Analyzer used to get context information.\n * \\param simplify_trivial_iterators If true, iterators with extent of\n *           1 will be replaced with a constant value.\n *\n * \\return The detected iteration result.\n * The return object's .indices is empty on failure.\n */\nIterMapResult DetectIterMap(const Array<PrimExpr>& indices, const Map<Var, Range>& input_iters,\n                            const PrimExpr& predicate, IterMapLevel check_level,\n                            arith::Analyzer* analyzer, bool simplify_trivial_iterators = true);\n\n/*!\n * \\brief Use IterVarMap detector to rewrite and simplify the indices\n *\n * \\param indices The indices to detect pattern for.\n * \\param input_iters Map from variable to iterator's range.\n * \\param input_pred The predicate constraints on the input iterators\n * \\param check_level The iter mapping checking level.\n * \\param simplify_trivial_iterators If true, iterators with unit extents are simplified\n * \\return The indices after rewrite\n */\nArray<PrimExpr> IterMapSimplify(const Array<PrimExpr>& indices, const Map<Var, Range>& input_iters,\n                                const PrimExpr& input_pred, IterMapLevel check_level,\n                                bool simplify_trivial_iterators = true);\n\n/*!\n * \\brief Apply the inverse of the affine transformation to the outputs.\n *\n * Similar to the back-propagation, starting from the outputs, it visits the DAG of the expressions\n * in reverse topology order and applies the inverse of the affine transformation until it reaches\n * the input. The affine iter map is required to be bijective.\n *\n * For example, iter_map = [l0 // 16, l0 % 16], outputs = [output_0, output_1],\n * the affine transformation specified by `iter_map` will be applied to `outputs` and the result\n * will be {l0: ((output_0*16) + output_1)}.\n *\n * The range of `outputs` should be the same as the output range of the affine transmation.\n *\n * \\sa DetectIterMap\n *\n * \\param iter_map The bijective affine iter map.\n * \\param outputs The outputs of the affine transformation.\n *\n * \\return The map from the input to the transformed result.\n */\nMap<Var, PrimExpr> InverseAffineIterMap(const Array<IterSumExpr>& iter_map,\n                                        const Array<PrimExpr> outputs);\n\n/*!\n * \\brief Detect if bindings can be written as\n * [a_0*e_0 + b_0 + c_0, a_1*e_1 + b_1, ..., a_n*e_n + b_n]\n *\n * where a = some-quasi-affine-iter-map(input_iters set_minus sub_iters)\n *       b = some-quasi-affine-iter-map(sub_iters)\n *       c is constant symbols\n *       e is the extent of b\n *\n * For example, z*12 + y*3 + x + c = (z*4+y)*3 + x, if sub_iters={x}\n *\n * \\param bindings The input bindings\n * \\param input_iters Map from variable to iterator's range.\n * \\param sub_iters Iterators of subspace.\n * \\param predicate The predicate constraints on the input iterators\n * \\param check_level The iter mapping checking level.\n * \\param analyzer Analyzer used to get context information.\n *\n * \\return The result list has length len(bindings) + 1\n        [0, len(bindings)): The iter map matching result. The inner list is of length 2.\n                            The first expr is the basis of the quotient space.\n                            The second expr is the basis of the subspace.\n        len(bindings): the predicate of outer space and inner space\n        Empty array if no match can be found.\n */\nArray<Array<IterMark>> SubspaceDivide(const Array<PrimExpr>& bindings,\n                                      const Map<Var, Range>& input_iters,\n                                      const Array<Var>& sub_iters, const PrimExpr& predicate,\n                                      IterMapLevel check_level, arith::Analyzer* analyzer);\n\n/*!\n * \\brief Given an expression that may contain IterMapExpr, transform it to normal PrimExpr.\n * \\param expr The input expression, which may contain IterMapExpr.\n * \\return The corresponding normal PrimExpr.\n */\nPrimExpr NormalizeIterMapToExpr(const PrimExpr& expr);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_ITER_AFFINE_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/arith/pattern.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arith/pattern.h\n * \\brief Expression pattern detectors.\n */\n#ifndef TVM_ARITH_PATTERN_H_\n#define TVM_ARITH_PATTERN_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/tir/expr.h>\n\nnamespace tvm {\nnamespace arith {\n/*!\n * \\brief Detect if e can be rewritten as e = sum_{i=0}^{n-1} var[i] * coeff[i] + coeff[n]\n *  Where coeff[i] and base are invariant of var[j] for all i and j.\n *\n * \\param e The expression to be detected.\n * \\param vars List of variables to be used in detection.\n * \\return [coeff[i]] if it is possible, empty array if it is not.\n */\nArray<PrimExpr> DetectLinearEquation(const PrimExpr& e, const Array<tir::Var>& vars);\n\n/*!\n * \\brief Detect if expression corresponds to clip bound of the vars\n *\n * \\param e The expression to be detected.\n * \\param vars List of variables to be used in detection.\n * \\return concat([min_value[i], max_value[i]]), None is returned if there is no min or max value\n *          return empty if the e does not match the pattern.\n */\nArray<PrimExpr> DetectClipBound(const PrimExpr& e, const Array<tir::Var>& vars);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_PATTERN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/auto_schedule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/auto_scheduler/auto_schedule.h\n * \\brief The user interface of the auto scheduler.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_AUTO_SCHEDULE_H_\n#define TVM_AUTO_SCHEDULER_AUTO_SCHEDULE_H_\n\n#include <tvm/auto_scheduler/measure.h>\n#include <tvm/auto_scheduler/search_policy.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*! \\brief Tuning and measurement options. */\nclass TuningOptionsNode : public Object {\n public:\n  /*! \\brief The number of total measurement trials. */\n  int num_measure_trials;\n  /*! \\brief Stops the tuning early if no improvement after n measurements. */\n  int early_stopping;\n  /*! \\brief The number of programs to be measured at each search round. */\n  int num_measures_per_round;\n  /*! \\brief Verbosity level. 0 for silent, 1 to output information during schedule searching. */\n  int verbose;\n  /*! \\brief ProgramBuilder which builds the program */\n  ProgramBuilder builder;\n  /*! \\brief ProgramRunner which runs the program and measures time costs */\n  ProgramRunner runner;\n  /*! \\brief MeasureCallback functions to be called after each measure batch */\n  Optional<Array<MeasureCallback>> measure_callbacks;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"num_measure_trials\", &num_measure_trials);\n    v->Visit(\"early_stopping\", &early_stopping);\n    v->Visit(\"num_measures_per_round\", &num_measures_per_round);\n    v->Visit(\"verbose\", &verbose);\n    v->Visit(\"builder\", &builder);\n    v->Visit(\"runner\", &runner);\n    v->Visit(\"measure_callbacks\", &measure_callbacks);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.TuningOptions\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TuningOptionsNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TuningOptionsNode.\n * \\sa TuningOptionsNode\n */\nclass TuningOptions : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param num_measure_trials The number of total measurement trials.\n   * \\param early_stopping Stops the tuning early if no improvement after n measurements.\n   * \\param num_measures_per_round The number of programs to be measured at each search round.\n   * \\param verbose Verbosity level. 0 for silent, 1 to output information during schedule\n   * search.\n   * \\param builder ProgramBuilder which builds the program.\n   * \\param runner ProgramRunner which runs the program and measure time costs.\n   * \\param measure_callbacks MeasureCallback functions to be called after each measure batch.\n   */\n  TuningOptions(int num_measure_trials, int early_stopping, int num_measures_per_round, int verbose,\n                ProgramBuilder builder, ProgramRunner runner,\n                Optional<Array<MeasureCallback>> measure_callbacks);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TuningOptions, ObjectRef, TuningOptionsNode);\n};\n\n/*!\n * \\brief Run schedule search for a given compute declaration.\n * \\param search_policy The search policy.\n * \\param tuning_options Tuning and measurement options.\n * \\return A `te::schedule` and an Array of `te::Tensor` to be used in `tvm.lower` or\n * `tvm.build`.\n */\nTVM_DLL std::pair<te::Schedule, Array<te::Tensor>> AutoSchedule(SearchPolicy search_policy,\n                                                                TuningOptions tuning_options);\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_AUTO_SCHEDULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/compute_dag.h",
        "content": "/*r\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/auto_scheduler/compute_dag.h\n * \\brief The auto-scheduler's computational graph and related program analyses.\n *\n * We convert a compute declaration described by `tvm.compute` (could be a single operator or a\n * subgraph) to a ComputeDAG. It keeps the input/output tensors, all operations in the DAG, and\n * some static analysis results for the DAG (e.g. the total float operation count, consumer/producer\n * relations of operations, whether an operation stage should be tiled/compute inlined ...).\n * These analyses can help the search policy to make decisions during the search.\n * ComputeDAG is also responsible for the interaction between auto-scheduler's `LoopState` and\n * TVM schedule (e.g. applying the `LoopState` transform steps to a TVM schedule, providing\n * `LoopState` with extra information got from TVM schedule ...).\n */\n\n#ifndef TVM_AUTO_SCHEDULER_COMPUTE_DAG_H_\n#define TVM_AUTO_SCHEDULER_COMPUTE_DAG_H_\n\n#include <tvm/auto_scheduler/loop_state.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/te/schedule.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*! \\brief Static analyzer for a ComputeDAG */\nclass AccessAnalyzerNode : public Object {\n public:\n  template <class T>\n  using OperationMap = std::unordered_map<te::Operation, T, ObjectPtrHash, ObjectPtrEqual>;\n\n  /*! \\brief Map an operation to all operations it reads from.\n   * For each operation pair, use a two-dimensional array for multiple multi-dimensional accesses\n   * The inner vector represents the indices of multi-dimensional access.*/\n  OperationMap<OperationMap<std::vector<std::vector<PrimExpr>>>> read_from;\n  /*! \\brief Map an operation to all operations it is read by.\n   * For each operation pair, use a two-dimensional array for multiple multi-dimensional accesses\n   * The inner vector represents the indices of multi-dimensional access.*/\n  OperationMap<OperationMap<std::vector<std::vector<PrimExpr>>>> read_by;\n  /*! \\brief Store the number of common outer iterators for operation pairs that have\n   * read-write relations. */\n  OperationMap<OperationMap<int>> num_common_outer_iterators;\n  /*! \\brief Store whether the operation is an op with only simple access.\n   *  (e.g., injective, broadcast and elementwise ops without reduction) */\n  OperationMap<bool> is_simple_access;\n  /*! \\brief Store whether the operation is strictly inlineable\n   * (e.g., injective, broadcast and elementwise without reduction, branch or expensive operations)\n   */\n  OperationMap<bool> is_strictly_inlineable;\n  /*! \\brief Store whether the operation needs multi-level tiling\n   * (e.g., computation-intensive ops with data reuse opportunity like matmul, conv2d) */\n  OperationMap<bool> needs_multi_level_tiling;\n  /*! \\brief Store whether the operation is an output operation */\n  OperationMap<bool> is_output;\n  /*! \\brief Store the topological order of operations */\n  Array<te::Operation> ops_topo_order;\n\n  static constexpr const char* _type_key = \"auto_scheduler.AccessAnalyzer\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AccessAnalyzerNode, Object);\n};\n\n/*!\n * \\brief Managed reference to AccessAnalyzerNode.\n * \\sa AccessAnalyzerNode\n */\nclass AccessAnalyzer : public ObjectRef {\n public:\n  explicit AccessAnalyzer(const Array<te::Tensor>& tensors);\n\n  /*!\n   * \\brief Return whether this operation is an op with simple access\n   * (e.g., injective, broadcast and elementwise ops without reduction)\n   * \\param op The operation\n   */\n  TVM_DLL bool IsSimpleAccess(const te::Operation& op) const;\n\n  /*!\n   * \\brief Return whether this operation is strictly inlineable\n   * (e.g., injective, broadcast and elementwise without reduction, branch or expensive operations)\n   * \\param op The operation\n   */\n  TVM_DLL bool IsStrictlyInlineable(const te::Operation& op) const;\n\n  /*!\n   * \\brief Return whether this operation needs multi-level tiling\n   * (e.g., computation-intensive ops with data reuse opportunity like matmul, conv2d)\n   * \\param op The operation\n   */\n  TVM_DLL bool NeedsMultiLevelTiling(const te::Operation& op) const;\n\n  /*!\n   * \\brief Return whether this operation is an output operation\n   * \\param op The operation\n   */\n  TVM_DLL bool IsOutput(const te::Operation& op) const;\n\n  /*!\n   * \\brief Get all consumers of an operation\n   * \\param state The current loop state\n   * \\param op The operation\n   * \\return The set of consumers\n   * \\note This function propagates the relation for inlined ops\n   */\n  TVM_DLL std::unordered_set<te::Operation, ObjectHash, ObjectEqual> GetConsumers(\n      const State& state, const te::Operation& op) const;\n\n  /*!\n   * \\brief Get all producers of an operation\n   * \\param state The current loop state\n   * \\param op The operation\n   * \\return The set of producers\n   * \\note This function propagates the relation for inlined ops\n   */\n  TVM_DLL std::unordered_set<te::Operation, ObjectHash, ObjectEqual> GetProducers(\n      const State& state, const te::Operation& op) const;\n\n  /*!\n   * \\brief Get all direct producers of an operation\n   * \\param op The operation\n   * \\return The set of direct producers\n   * \\note This function DOES NOT propagate the relation for inlined ops\n   */\n  TVM_DLL std::unordered_set<te::Operation, ObjectHash, ObjectEqual> GetDirectProducers(\n      const te::Operation& op) const;\n\n  /*!\n   * \\brief Get the number of common outer iterators.\n   * \\param op The operation\n   * \\param target_op The target operation\n   * \\note This function propagates the relation for chains with multiple ops.\n   */\n  TVM_DLL int GetNumCommonOuterIterator(const te::Operation& op,\n                                        const te::Operation& target_op) const;\n\n  /*!\n   * \\brief Return whether two operations are elementwise-matched\n   *  (e.g. conv2d and relu are elementwise-matched)\n   * \\note This function propagates the relation for chains with multiple ops.\n   */\n  TVM_DLL bool ElementWiseMatch(const te::Operation& op, const te::Operation& target_op) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AccessAnalyzer, ObjectRef, AccessAnalyzerNode);\n};\n\n/*! \\brief The auto-scheduler's computational graph and related program analyses. */\nclass ComputeDAGNode : public Object {\n public:\n  /*!\n   * \\brief Input and output tensors.\n   * This is used as the input of `tvm.lower` or `tvm.build`.\n   */\n  Array<te::Tensor> tensors;\n  /*! \\brief All used operations in topo order. */\n  Array<te::Operation> ops;\n  /*! \\brief The number of float operations in this ComputeDAG. */\n  double flop_ct;\n  /*! \\brief The initial state without any transform steps. */\n  State init_state;\n  /*! \\brief The static read-write access analyzer. */\n  AccessAnalyzer access_analyzer;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"tensors\", &tensors);\n    v->Visit(\"ops\", &ops);\n    v->Visit(\"flop_ct\", &flop_ct);\n    v->Visit(\"init_state\", &init_state);\n    v->Visit(\"access_analyzer\", &access_analyzer);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.ComputeDAG\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ComputeDAGNode, Object);\n};\n\n/*!\n * \\brief Options for applying layout rewrite.\n * This is an optimization to rewrite the layout of input tensors according to the schedule we get.\n */\nenum class LayoutRewriteOption : int {\n  /*! \\brief Do not perform layout rewrite. */\n  NoRewrite = 0,\n  /*! \\brief Insert layout transformation stages for input placeholders in the compute DAG */\n  InsertTransformStage = 1,\n  /*!\n   * \\brief Do not insert layout transformation stages and assume the input placeholders\n   * are pre-transformed.\n   * \\note The lowered function with this option does not accept the origial input shapes,\n   * so this option must be used along with `AutoSchedulerLayoutRewrite` pass in Relay.\n   */\n  RewriteForPreTransformed = 2,\n};\n\n/*!\n * \\brief Managed reference to ComputeDAGNode.\n * \\sa ComputeDAGNode\n */\nclass ComputeDAG : public ObjectRef {\n public:\n  /*! \\brief Construct a DAG from a list of output tensors.\n   * \\param tensors `te::Tensor`s for a compute declaration.\n   */\n  TVM_DLL explicit ComputeDAG(Array<te::Tensor> tensors);\n\n  /*! \\brief Construct a DAG based on a schedule.\n   * \\param sch `te::Schedule`s for a compute declaration.\n   */\n  TVM_DLL explicit ComputeDAG(const te::Schedule& sch);\n\n  /*!\n   * \\brief Rewrite the layout of placeholder specified by attr `layout_free_placeholders`\n   * according to the loop nest derived with `transform_steps`.\n   * \\param transform_steps Transform steps of a state.\n   * \\param layout_rewrite Different options in layout rewrite.\n   * \\return The updated ComputeDAG after layout rewrite.\n   */\n  ComputeDAG RewriteLayout(Array<Step>* transform_steps, LayoutRewriteOption layout_rewrite) const;\n\n  /*!\n   * \\brief Apply the history transform steps to get a TVM schedule.\n   * \\param transform_steps Transform steps of a state.\n   * \\param stages The list of stages after applying the steps.\n   * Pass a valid pointer if this information needs to be used outside this function.\n   * \\param stage_to_axes The map that stores all axes for one stage.\n   * Pass a valid pointer if this information needs to be used outside this function.\n   * \\param layout_rewrite Rewrite the layout of placeholders specified by\n   * attr `layout_free_placeholders`.\n   * \\return A `te.schedule` and the an Array of `te.Tensor` to be used in `tvm.lower`\n   * or `tvm.build`.\n   */\n  std::pair<te::Schedule, Array<te::Tensor>> ApplySteps(\n      const Array<Step>& transform_steps, Array<te::Stage>* stages = nullptr,\n      StageToAxesMap* stage_to_axes = nullptr,\n      LayoutRewriteOption layout_rewrite = LayoutRewriteOption::NoRewrite) const;\n\n  /*!\n   * \\brief Print transform steps as equivalent python schedule API.\n   * This can be used for debugging.\n   * \\param transform_steps Transform steps of a state.\n   * \\return The Python schedule code.\n   */\n  String PrintStepsAsPython(const Array<Step>& transform_steps) const;\n\n  /*!\n   * \\brief Print the compute DAG to a string. This is also used to generate the ComputeDAG hash.\n   * \\param simple_mode Simple mode will only include the op names and brief compute.\n   * \\return The ComputeDAG in a string.\n   */\n  String PrintDAG(bool simple_mode = false) const;\n\n  /*!\n   * \\brief Fill the correct bound information for a given state by calling ir_pass::InferBound.\n   * The states can lose complete bound information after some transform steps (e.g., compute_at).\n   * We can call this function to infer and fill all the bound information.\n   * This function calls TVM InferBound pass internally to get the bound.\n   * The returned state of this function is guaranteed to have complete bound information.\n   * \\param state The input state.\n   * \\return The State with complete bound information\n   */\n  State InferBound(const State& state) const;\n\n  /*!\n   * \\brief Fill the correct bound information for the given states by calling ir_pass::InferBound.\n   * The states can lose complete bound information after some transform steps (e.g., compute_at).\n   * We can call this function to infer and fill all the bound information.\n   * This function calls TVM InferBound pass internally to get the bound.\n   * The returned state of this function is guaranteed to have complete bound information.\n   * \\param states The input states.\n   * \\return The States with complete bound information.\n   * \\note The returned array will contains empty State, if there're infer bound failure on some\n   * states.\n   */\n  Array<State> InferBound(const Array<State>& states) const;\n\n  /*!\n   * \\brief Since some steps may change the ComputeDAG (e.g. CacheRead/CacheWrite), the initial\n   * ComputeDAG may not be up-to-date. This function replays the given transform steps from the\n   * initial state and returns an up-to-date ComputeDAG.\n   * \\param steps The steps to be replayed. Usually we'll filter out the unused steps to speed up\n   * the replay process, since we only intend to get a ComputeDAG with the up-to-date op stage\n   * structure.\n   * \\return The up-to-date ComputeDAG.\n   */\n  ComputeDAG ReplayAndGetDAG(const Array<Step>& steps) const;\n\n  static constexpr const char* layout_free_placeholders_key = \"layout_free_placeholders\";\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ComputeDAG, ObjectRef, ComputeDAGNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ComputeDAGNode);\n};\n\n/*!\n *  \\brief Get the orginal shape from a rewritten layout string.\n *  \\param rewritten_layout The layout after auto-scheduler's layout rewrite.\n *  \\param axis_names Specifiy the names of axes.\n *  \\return shape The original shape.\n */\nArray<PrimExpr> GetShapeFromRewrittenLayout(String rewritten_layout, Array<String> axis_names);\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_COMPUTE_DAG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/cost_model.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/cost_model.h\n * \\brief Cost models that estimate the performance of programs\n */\n\n#ifndef TVM_AUTO_SCHEDULER_COST_MODEL_H_\n#define TVM_AUTO_SCHEDULER_COST_MODEL_H_\n\n#include <tvm/auto_scheduler/compute_dag.h>\n#include <tvm/auto_scheduler/measure.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nusing runtime::PackedFunc;\nusing runtime::TypedPackedFunc;\n\n/*! \\brief The base class for cost model */\nclass CostModelNode : public Object {\n public:\n  /*!\n   * \\brief Update the cost model according to new measurement results (training data).\n   * \\param inputs The measure inputs\n   * \\param results The measure results\n   */\n  virtual void Update(const Array<MeasureInput>& inputs, const Array<MeasureResult>& results) = 0;\n\n  /*!\n   * \\brief Predict the scores of states\n   * \\param task The search task of states\n   * \\param states The input states\n   * \\param scores The predicted scores for all states\n   */\n  virtual void Predict(const SearchTask& task, const Array<State>& states,\n                       std::vector<float>* scores) = 0;\n\n  /*!\n   * \\brief Predict the scores of all stages in states. This is the breakdown version of `Predict`\n   * \\param task The search task\n   * \\param states The input states\n   * \\param state_scores The predicted scores for all states\n   * \\param stage_scores The predicted scores for all stages in all stages\n   */\n  virtual void PredictStages(const SearchTask& task, const Array<State>& states,\n                             std::vector<float>* state_scores,\n                             std::vector<std::vector<float>>* stage_scores) {\n    LOG(FATAL) << \"Not implemented\";\n  }\n\n  /*!\n   * \\brief Default virtual destructor\n   */\n  virtual ~CostModelNode() {}\n\n  static constexpr const char* _type_key = \"auto_scheduler.CostModel\";\n  TVM_DECLARE_BASE_OBJECT_INFO(CostModelNode, Object);\n};\n\n/*!\n * \\brief Managed reference to CostModelNode.\n * \\sa CostModelNode\n */\nclass CostModel : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(CostModel, ObjectRef, CostModelNode);\n};\n\n/*! \\brief The cost model returning random value for all predictions */\nclass RandomModelNode : public CostModelNode {\n public:\n  /*! \\brief Pointer to a random number generator function */\n  const TypedPackedFunc<void(size_t, void*)>* random_number_func;\n\n  void Update(const Array<MeasureInput>& inputs, const Array<MeasureResult>& results) final;\n\n  void Predict(const SearchTask& task, const Array<State>& states,\n               std::vector<float>* scores) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.RandomModel\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RandomModelNode, CostModelNode);\n};\n\n/*!\n * \\brief Managed reference to RandomModelNode.\n * \\sa RandomModelNode\n */\nclass RandomModel : public CostModel {\n public:\n  RandomModel();\n  explicit RandomModel(::tvm::runtime::ObjectPtr<::tvm::runtime::Object> n) : CostModel(n) {}\n\n  RandomModelNode* operator->() const { return static_cast<RandomModelNode*>(data_.get()); }\n\n  TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(RandomModel);\n  using ContainerType = RandomModelNode;\n};\n\n/*! \\brief A wrapper for cost model defined by python code\n *  This class will call functions defined in the python */\nclass PythonBasedModelNode : public CostModelNode {\n public:\n  /*! \\brief Pointer to the update function in python */\n  PackedFunc update_func;\n  /*! \\brief Pointer to the predict function in python */\n  PackedFunc predict_func;\n  /*! \\brief Pointer to the predict function in python */\n  PackedFunc predict_stage_func;\n\n  void Update(const Array<MeasureInput>& inputs, const Array<MeasureResult>& results) final;\n\n  void Predict(const SearchTask& task, const Array<State>& states,\n               std::vector<float>* scores) final;\n\n  void PredictStages(const SearchTask& task, const Array<State>& states,\n                     std::vector<float>* state_scores,\n                     std::vector<std::vector<float>>* stage_scores) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.PythonBasedModel\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PythonBasedModelNode, CostModelNode);\n};\n\n/*!\n * \\brief Managed reference to PythonBasedModelNode.\n * \\sa PythonBasedModelNode\n */\nclass PythonBasedModel : public CostModel {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param update_func The pointer to the update function defined in python\n   * \\param predict_func The pointer to the prediction function defined in python\n   * \\param predict_stage_func The pointer to the prediction function defined in python\n   */\n  PythonBasedModel(PackedFunc update_func, PackedFunc predict_func, PackedFunc predict_stage_func);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PythonBasedModel, CostModel, PythonBasedModelNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_COST_MODEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/feature.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/feature.h\n * \\brief Feature extraction for the cost model.\n * We extract one feature vector per BufferStoreNode statement in a TIR Stmt,\n * so we call this feature as \"per-store\" feature.\n * The cost model also does prediction for each BufferStoreNode statement and aggregates\n * the predictions as the whole score for a TVM IR (Stmt).\n *\n * The feature specification is defined by `src/auto_scheduler/feature.cc:: FeatureSet`\n */\n\n#ifndef TVM_AUTO_SCHEDULER_FEATURE_H_\n#define TVM_AUTO_SCHEDULER_FEATURE_H_\n\n#include <tvm/auto_scheduler/compute_dag.h>\n#include <tvm/auto_scheduler/measure.h>\n#include <tvm/tir/function.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*!\n * \\brief Get per-store features from a TIR PrimFunc\n * \\param func The input lowered TIR PrimFunc\n * \\param cache_line_size The size of cache line in bytes\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param ret The returned feature vector\n * \\param log_scale Should the outputs be scaled by log2(1+x).\n */\nvoid GetPerStoreFeature(const PrimFunc& func, int cache_line_size, int max_n_bufs,\n                        std::vector<float>* ret, bool log_scale = true);\n\n/*\n * \\brief Get the names of elements in the feature vector. Use this for debug and inspection.\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param ret The returned names.\n */\nvoid GetPerStoreFeatureName(int max_n_bufs, std::vector<std::string>* ret);\n\n/*!\n * \\brief Get per-store feature from states of the same task\n * \\param states The input states\n * \\param task The same search task for all states\n * \\param skip_first_n_feature_extraction Skip feature extraction for the first n states\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param features The returned feature vector. The innermost vector contains the\n * feature vectors for all BufferStoreNode statements\n */\nvoid GetPerStoreFeaturesFromStates(const Array<State>& states, const SearchTask& task,\n                                   int skip_first_n_feature_extraction, int max_n_bufs,\n                                   std::vector<std::vector<float>>* features);\n\n/*!\n * \\brief Get per-store feature from states of different tasks\n * \\param states The input states\n * \\param tasks The search tasks corresponding to the input states\n * \\param skip_first_n_feature_extraction Skip feature extraction for the first n states\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param features The returned feature vector. The innermost vector contains the\n * feature vectors for all BufferStoreNode statements\n */\nvoid GetPerStoreFeaturesFromStates(const Array<State>& states, const std::vector<SearchTask>& tasks,\n                                   int skip_first_n_feature_extraction, int max_n_bufs,\n                                   std::vector<std::vector<float>>* features);\n\n/*!\n * \\brief Get per-store features from a log file\n * \\param filename The name of log file\n * \\param max_lines Only read the first n lines of the file\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param features The returned feature vector. The innermost vector contains the\n * feature vectors for all BufferStoreNode statements\n * \\param normalized_throughputs The normalized throughputs for all states\n * \\param task_ids The task ids for all states\n */\nvoid GetPerStoreFeaturesFromFile(const std::string& filename, int max_lines, int max_n_bufs,\n                                 std::vector<std::vector<float>>* features,\n                                 std::vector<float>* normalized_throughputs,\n                                 std::vector<int>* task_ids);\n\n/*!\n * \\brief Get per-store features from measurement input/result pairs\n * \\param inputs The measurement inputs\n * \\param results The measurement results\n * \\param skip_first_n_feature_extraction Skip feature extraction for the first n measurement pairs\n * \\param max_n_bufs The maximum number of extracted buffers for one statement\n * \\param features The returned feature vector. The innermost vector contains the\n * feature vectors for all BufferStoreNode statements\n * \\param normalized_throughputs The normalized throughputs for all states\n * \\param task_ids The task ids for all states\n */\nvoid GetPerStoreFeaturesFromMeasurePairs(const Array<MeasureInput>& inputs,\n                                         const Array<MeasureResult>& results,\n                                         int skip_first_n_feature_extraction, int max_n_bufs,\n                                         std::vector<std::vector<float>>* features,\n                                         std::vector<float>* normalized_throughputs,\n                                         std::vector<int>* task_ids);\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_FEATURE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/loop_state.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/loop_state.h\n * \\brief The definition of the \"state\" in the search.\n *\n * Each LoopState corresponds to a schedule for its ComputeDAG.\n * A LoopState consists of: 1. a current loop structure; 2. a list of transformation steps used to\n * construct the loop structure.\n * The loop structure keeps a preview of how the schedule will finally look like after lowering the\n * current state (e.g. number of iterators, the extent of each iterator, the compute_at locations\n * ...).\n * During the schedule search process, the loop structure can provide search policy with necessary\n * information on how to manipulate the current state.\n * The transform history is a sequence of `TransformStep` which will finally be mapped to TVM\n * schedule primitives. The steps are also used for the serialization of a state.\n *\n * The LoopState can be seen as a lightweight loop structure IR specifically for schedule search.\n * We don't use the existing TVM IR but to extend a new structure on it is because:\n * 1. We want fast incremental change to the loop structures. The search policy needs to get the\n * immediate loop structures update rather than after TVM lowering;\n * 2. We want serializable transform history for replay, backtracking, and mutation;\n * 3. We may create some macro schedule primitives that represent the combination of several\n * TVM schedule primitives.\n *\n * When the search is finished, we will lower the state to TVM IR with TVM's schedule primitives.\n * Since we share a lot of common objects during search, the transformation is implemented in\n * copy on write style. All objects are immutable, which is similar to TVM IR.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_LOOP_STATE_H_\n#define TVM_AUTO_SCHEDULER_LOOP_STATE_H_\n\n#include <dmlc/common.h>\n#include <tvm/auto_scheduler/transform_step.h>\n\n#include <functional>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nusing namespace tvm::tir;\n\nclass ComputeDAG;\n\n/*! \\brief The type of a stage. */\nenum class StageKind : int {\n  /*! \\brief A placeholder stage. */\n  kPlaceholder = 0,\n  /*! \\brief A compute stage. */\n  kCompute = 1\n};\n\n/*! \\brief The type of compute location. */\nenum class ComputeAtKind : int {\n  /*! \\brief Compute at root. */\n  kRoot = 0,\n  /*! \\brief Compute inlined. */\n  kInlined = 1,\n  /*! \\brief Compute at some iterator. */\n  kIter = 2,\n};\n\n/*! \\brief Stage-level attributes. */\nstruct StageAttributes {\n  /*! \\brief The maximum steps for the pragma `auto_unroll_max_step`. */\n  int auto_unroll_max_step;\n  /*! \\brief The storage offset for the schedule primitive `storage_align`. */\n  int storage_offset;\n};\n\n/*!\n * \\brief A op stage in the compute declaration.\n * Similar to te::Stage in `include/tvm/te/schedule.h`.\n */\nclass StageNode : public Object {\n public:\n  /*! \\brief The operator of this stage */\n  te::Operation op;\n  /*! \\brief The iterators in this stage. */\n  Array<Iterator> iters;\n  /*! \\brief The type of this stage. */\n  StageKind op_type;\n  /*! \\brief The compute location of this stage. */\n  ComputeAtKind compute_at;\n  /*! \\brief Other stage-level attributes. */\n  StageAttributes attrs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"op\", &op);\n    v->Visit(\"iters\", &iters);\n    v->Visit(\"op_type\", &op_type);\n    v->Visit(\"compute_at\", &compute_at);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.Stage\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StageNode, Object);\n};\n\n/*!\n * \\brief Managed reference to StageNode.\n * \\sa StageNode\n */\nclass Stage : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param op A `te::Operation`.\n   */\n  explicit Stage(te::Operation op);\n  /*!\n   * \\brief The constructor.\n   * \\param op The source operation\n   * \\param op_type The stage type of this op.\n   * \\param iters The iterators of this op.\n   * \\param compute_at The compute at type of this op.\n   * \\param attrs Other stage-level attributes.\n   */\n  Stage(te::Operation op, StageKind op_type, const Array<Iterator>& iters, ComputeAtKind compute_at,\n        StageAttributes attrs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Stage, ObjectRef, StageNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(StageNode);\n};\n\n/*! \\brief Use stage_id to represent a stage. */\nusing StageKey = int;\n/*! \\brief Use stage_id and iter_id to represent a iterator. */\nusing IterKey = std::pair<int, int>;\n\n/*!\n * \\brief stores the compute_at relation between stages\n * This stores a bi-directional mapping from stages and iter:\n * 1. Stage to its attached iterator\n * 2. Iterator to the stage attached to it\n * You can use AttachMapNode::stage_to_attach_iter and AttachMapNode::iter_to_attached_stages\n * to query the relations\n */\nclass AttachMapNode : public Object {\n public:\n  struct IterKeyHash {\n    std::size_t operator()(const IterKey& k) const {\n      return ::dmlc::HashCombine(std::hash<int>()(k.first), std::hash<int>()(k.second));\n    }\n  };\n\n  /*! \\brief A Map to store the mapping of stage to its attached iterator. */\n  std::unordered_map<StageKey, IterKey> stage_to_attach_iter;\n  /*! \\brief A Map to store the mapping of iterator to the stages attached to it. */\n  std::unordered_map<IterKey, std::vector<StageKey>, IterKeyHash> iter_to_attached_stages;\n\n  static constexpr const char* _type_key = \"auto_scheduler.AttachMap\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttachMapNode, Object);\n};\n\n/*!\n * \\brief Managed reference to AttachMapNode.\n * \\sa AttachMapNode\n */\nclass AttachMap : public ObjectRef {\n public:\n  /*!\n   * \\brief Process the stage/iterator mapping after compute at.\n   * \\param stage_id The index of the source stage of computed at.\n   * \\param target_stage_id The index of stage that this step will compute at to.\n   * \\param target_iter_id The index of target iterator in the target stage.\n   */\n  void SetComputeAtIter(int stage_id, int target_stage_id, int target_iter_id);\n\n  /*!\n   * \\brief Delete the entry of a specific stage. This is a public wrapper of `DeleteStageEntry`.\n   * \\param stage_id The index of the stage to be deleted.\n   */\n  void DeleteStage(int stage_id);\n\n  /*!\n   * \\brief Find the relations of original iterators in AttachMap, and update them with the new\n   * iterators. Both `stage_to_attach_iter` and `iter_to_attached_stages` will be updated.\n   * \\param original_iters The original IterKey.\n   * \\param new_iters The new IterKey for replacing the old ones.\n   */\n  void UpdateIters(const std::vector<IterKey>& original_iters,\n                   const std::vector<IterKey>& new_iters);\n\n  /*!\n   * \\brief Traverse through `stage_to_attach_iter` and `iter_to_attached_stages` map, add offset\n   * to stage indexes that are larger than the start_id. Used for steps that insert new stages to\n   * ComputeDAG (e.g., CacheRead/CacheWrite step).\n   * \\param start_id The index threshold. This function only adds offset for stages\n   * with indices larger then this threshold.\n   * \\param offset The index offset to be added to the stage index.\n   * \\return The updated AttachMap after applying stage index offset.\n   */\n  AttachMap ApplyStageIdOffset(int start_id, int offset = 1) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AttachMap, ObjectRef, AttachMapNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(AttachMapNode);\n\n private:\n  /*!\n   * \\brief Delete the entry of a specific stage. This will remove the items related to this\n   * stage in both `stage_to_attach_iter` and `iter_to_attached_stages` map.\n   * \\param pnode A mutable pointer to AttachMapNode.\n   * \\param stage_id The index of stage that will be removed from the map.\n   */\n  static void DeleteStageEntry(AttachMapNode* pnode, int stage_id);\n};\n\n/*!\n * \\brief A state in the search process.\n * It consists of the current loop structure and a list of transformation steps used to construct\n * it.\n * Each State corresponds to a specific schedule for its ComputeDAG.\n */\nclass StateNode : public Object {\n public:\n  /*! \\brief Current stages and loop structures. */\n  Array<Stage> stages;\n  /*! \\brief History transformation steps. */\n  Array<Step> transform_steps;\n  /*!\n   * \\brief The attach relations of stages and iterators. This is used to track the compute at\n   * operation.\n   */\n  AttachMap attach_map;\n  /*! \\brief The up-to-date ComputeDAG of this state. The default value is an empty NullOpt,\n   * meaning the dag of this state is the same as the original ComputeDAG in the SearchTask.\n   * Otherwise, the stored value is the up-to-date ComputeDAG for this state, meaning some steps\n   * (e.g., CacheReadStep/CacheWriteStep) have modified the ComputeDAG.\n   */\n  Optional<ObjectRef> current_compute_dag;\n  /*!\n   * \\brief Indicate whether this state has unfilled tile sizes. A concrete state means that all\n   * tile sizes of the state is filled. Only concrete state can be apply to TVM schedule.\n   */\n  bool concrete;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"stages\", &stages);\n    v->Visit(\"transform_steps\", &transform_steps);\n    v->Visit(\"concrete\", &concrete);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.State\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StateNode, Object);\n};\n\n/*!\n * \\brief Managed reference to StateNode.\n * \\sa StateNode\n */\nclass State : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param ops `te::Operation`s for a compute declaration.\n   */\n  explicit State(const Array<te::Operation>& ops);\n\n  /*!\n   * \\brief Pretty-print the state to a human readable string.\n   * \\param delete_trivial_loop True for skipping the trivial loops.\n   * (undefined or extent == 1, default set to True)\n   * \\return The human readable string.\n   */\n  String ToStr(bool delete_trivial_loop = true) const;\n\n  /********** Step APIs working on a single stage **********/\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::bind`.\n   * \\param stage_id The index of the stage to be binded.\n   * \\param it The iterator to be binded.\n   * \\param thread_type The thread type.\n   * \\return The new iterator after binding.\n   */\n  TVM_DLL Iterator bind(int stage_id, const Iterator& it, IteratorAnnotation thread_type);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::parallel`.\n   * \\param stage_id The index of the stage to be paralleled.\n   * \\param it The iterator to be paralleled.\n   * \\return The new iterator after parallel.\n   */\n  TVM_DLL Iterator parallel(int stage_id, const Iterator& it);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::unroll`.\n   * \\param stage_id The index of the stage to be unrolled.\n   * \\param it The iterator to be unrolled.\n   * \\param max_unroll The max unroll limit. Iterator with extent larger than this limit will be\n   * skipped.\n   * \\return The new iterator after unroll.\n   */\n  TVM_DLL Iterator unroll(int stage_id, const Iterator& it, int max_unroll = -1);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::vectorize`.\n   * \\param stage_id The index of the stage to be vectorized.\n   * \\param it The iterator to be vectorized.\n   * \\return The new iterator after vectorization.\n   */\n  TVM_DLL Iterator vectorize(int stage_id, const Iterator& it);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::fuse`.\n   * \\param stage_id The index of the stage to be fused.\n   * \\param iters The iterators to be fused.\n   * \\return The iterator result after fuse.\n   * \\note If the iterators to be fused have stages attached at them(by compute_at), the fused\n   * result will become the new attach point.\n   */\n  TVM_DLL Iterator fuse(int stage_id, const Array<Iterator>& iters);\n  /*!\n   * \\brief The schedule primitive corresponding to `te.Stage.pragma`.\n   * \\param stage_id The index of the stage to add pragma.\n   * \\param it The iterator to add pragma.\n   * \\param pragma_type The pragma string.\n   */\n  TVM_DLL void pragma(int stage_id, const Iterator& it, const String& pragma_type);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::reorder`.\n   * \\param stage_id The index of the stage to be reordered.\n   * \\param order The expected iterator order.\n   */\n  TVM_DLL void reorder(int stage_id, const Array<Iterator>& order);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::split`.\n   * \\param stage_id The index of the stage to be split.\n   * \\param it The iterator to be split.\n   * \\param lengths The multiple split factors. Can be None to be filled by search policy.\n   * \\param inner_to_outer Whether the factors go from inner to outer, or from outer to inner.\n   * \\return The new iterator after splitting.\n   * \\note If we do split on an iterator which has stages attached at it(by compute_at), the inner\n   * most iterator of split results will become the new attach point.\n   */\n  TVM_DLL Array<Iterator> split(int stage_id, const Iterator& it,\n                                const Array<Optional<Integer>>& lengths,\n                                bool inner_to_outer = true);\n  /*!\n   * \\brief The schedule primitive similar to split, but uses split factors from previous steps.\n   * \\param stage_id The index of the stage to be split.\n   * \\param it The iterator to be split.\n   * \\param src_step_id The index of the split step to be followed in the history.\n   * \\param n_split The number of split level.\n   * \\return The split new Iterators.\n   */\n  TVM_DLL Array<Iterator> follow_split(int stage_id, const Iterator& it, int src_step_id,\n                                       int n_split);\n  /*!\n   * \\brief The schedule primitive similar to split, but uses split factors from\n   * fused previous steps.\n   * \\param stage_id The index of the stage to be split.\n   * \\param it The iterator to be split.\n   * \\param src_step_ids The indices of the split steps to be followed in the history.\n   * \\param level Use the length in this split level.\n   * \\param factor_or_nparts True to use `factor` for split from inner to outer,\n      False to use `nparts` for split from outer to inner.\n   * \\return The split new Iterators.\n   */\n  TVM_DLL Array<Iterator> follow_fused_split(int stage_id, const Iterator& it,\n                                             const Array<Integer>& src_step_ids, int level,\n                                             bool factor_or_nparts);\n  /*!\n   * \\brief The schedule primitive corresponding to `te.Stage.storage_align`.\n   * \\param stage_id The index of the stage to be aligned.\n   * \\param it The iterator to be aligned.\n   * \\param factor The factor in alignment specification.\n   * \\param offset The offset in the alignment specification.\n   */\n  TVM_DLL void storage_align(int stage_id, const Iterator& it, int factor, int offset);\n\n  /********** Step APIs working on multiple stages **********/\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::compute_at`.\n   * \\param stage_id The index of the source stage of computed at.\n   * \\param target_stage_id The index of stage that this step will compute at to.\n   * \\param target_iter The indiex of the target iterator in the target stage.\n   * \\note After compute_at, we need careful dependency analysis to compute the accurate bound\n   * information. However, it is relatively expensive and complicated, so we just fill \"None\" as\n   * bound for the newly created iterators.\n   * Call ComputeDAG::InferBound on the updated state if you need the complete bound information.\n   */\n  TVM_DLL void compute_at(int stage_id, int target_stage_id, const Iterator& target_iter);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::compute_inline`.\n   * \\param stage_id The index of the stage to be marked compute inlined.\n   */\n  TVM_DLL void compute_inline(int stage_id);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Stage::compute_root`.\n   * \\param stage_id The index of the stage to be marked compute at root.\n   * \\note After compute_root, we need careful dependency analysis to compute the accurate bound\n   * information. However, it is relatively expensive and complicated, so we just fill \"None\" as\n   * bound for the newly created iterators.\n   * Call ComputeDAG::InferBound on the updated state if you need the complete bound information.\n   */\n  TVM_DLL void compute_root(int stage_id);\n\n  /********** Step APIs adding new stages **********/\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Schedule::cache_read`.\n   * \\param stage_id The index of the stage to be cache_read.\n   * \\param scope_name The scope name of the newly added stage.\n   * \\param reader_stage_ids The indices of reader stages.\n   * \\param dag The original ComputeDAG of this state.\n   * \\note Cache read step will add an extra stage to the original ComputeDAG (at the back of the\n   * target stage), an up-to-date ComputeDAG is stored in State's `current_compute_dag`.\n   */\n  TVM_DLL int cache_read(int stage_id, const String& scope_name,\n                         const Array<Integer>& reader_stage_ids, const ComputeDAG& dag);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Schedule::cache_write`.\n   * \\param stage_id The index of the stage to be cache_write.\n   * \\param scope_name The scope name of the newly added stage.\n   * \\param dag The original ComputeDAG of this state.\n   * \\note Cache write step will add an extra stage to the original ComputeDAG (in the front of the\n   * target stage), an up-to-date ComputeDAG is stored in State's `current_compute_dag`.\n   * This step will cache write all output tensors of the target stage.\n   */\n  TVM_DLL int cache_write(int stage_id, const String& scope_name, const ComputeDAG& dag);\n  /*!\n   * \\brief The schedule primitive corresponding to `te::Schedule::rfactor`.\n   * \\param stage_id The index of the iterator to be factored.\n   * \\param it The iterator to be factored.\n   * \\param factor_iter_id The position where the new iterator is placed.\n   * \\param dag The original ComputeDAG of this state.\n   * \\note Rfactor step will add an extra stage to the original ComputeDAG (in the front of the\n   * target stage), an up-to-date ComputeDAG is stored in State's `current_compute_dag`.\n   */\n  TVM_DLL int rfactor(int stage_id, const Iterator& it, int factor_iter_id, const ComputeDAG& dag);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(State, ObjectRef, StateNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(StateNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n// Hash and equal function for State\nnamespace std {\n\n/*!\n * \\brief The equal_to function for auto_scheduler::State.\n * This function checks the equality by looking at the lowered string format of states.\n * If two states with different transform history have the same lowered string format,\n * they will be considered being equal.\n */\ntemplate <>\nstruct equal_to<::tvm::auto_scheduler::State> {\n  bool operator()(const ::tvm::auto_scheduler::State& lhs,\n                  const ::tvm::auto_scheduler::State& rhs) const {\n    return lhs.ToStr() == rhs.ToStr();\n  }\n};\n\n/*! \\brief The hash function for auto_scheduler::State. */\ntemplate <>\nstruct hash<::tvm::auto_scheduler::State> {\n  std::size_t operator()(const ::tvm::auto_scheduler::State& state) const {\n    return tvm::runtime::ObjectHash()(state.ToStr());\n  }\n};\n\n}  // namespace std\n\n#endif  // TVM_AUTO_SCHEDULER_LOOP_STATE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/measure.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/measure.h\n * \\brief Distributed measurement infrastructure to measure the runtime costs of tensor programs.\n * These functions are responsible for building the tvm module, uploading it to remote devices,\n * recording the running time costs, and checking the correctness of the output.\n *\n * The measurement is separated into two steps: build and run.\n * A builder builds the executable binary files and a runner runs the binary files to get the\n * measurement results. The flow of data structures is\n *\n *                 `ProgramBuilder`                 `ProgramRunner`\n * `MeasureInput` -----------------> `BuildResult` ----------------> `MeasureResult`\n *\n * The core functions is implemented in python to utilize python's multiprocessing\n * and error handling (see also `python/tvm/auto_scheduler/measure.py`).\n * This c++ file is just a wrapper for the python functions.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_MEASURE_H_\n#define TVM_AUTO_SCHEDULER_MEASURE_H_\n\n#include <tvm/auto_scheduler/loop_state.h>\n#include <tvm/auto_scheduler/search_task.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nclass SearchPolicy;\nclass MeasureInput;\nclass MeasureResult;\n\n/*! \\brief The error code of one measurement */\nenum class MeasureErrorNO : int {\n  /*! \\brief No error. */\n  kNoError = 0,\n  /*! \\brief Errors happen when apply transform steps from init state. */\n  kInstantiationError = 1,\n  /*! \\brief Errors happen when compiling code on host. (when build module) */\n  kCompileHostError = 2,\n  /*! \\brief Errors happen when compiling code on device. (when load module) */\n  kCompileDeviceError = 3,\n  /*! \\brief Errors happen when run program on device. */\n  kRuntimeDeviceError = 4,\n  /*! \\brief Answer is wrong when compared to a reference output. */\n  kWrongAnswerError = 5,\n  /*! \\brief Timeout during compilation. */\n  kBuildTimeoutError = 6,\n  /*! \\brief Timeout during run. */\n  kRunTimeoutError = 7,\n  /*! \\brief Unknown error. */\n  kUnknownError = 8,\n};\n\n// Inputs and results of one measurement\n\n/*! \\brief Store the input of a measurement */\nclass MeasureInputNode : public Object {\n public:\n  /*! \\brief The search task. */\n  SearchTask task;\n  /*! \\brief The program state to be measured. */\n  State state;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"task\", &task);\n    v->Visit(\"state\", &state);\n  }\n\n  /*! \\brief Do shallow copy. */\n  MeasureInput copy() const;\n\n  static constexpr const char* _type_key = \"auto_scheduler.MeasureInput\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MeasureInputNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MeasureInputNode.\n * \\sa MeasureInputNode\n */\nclass MeasureInput : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param task The SearchTask of this measure.\n   * \\param state The State to be measured.\n   */\n  MeasureInput(SearchTask task, State state);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(MeasureInput, ObjectRef, MeasureInputNode);\n};\n\n/*! \\brief Store the result of a build. */\nclass BuildResultNode : public Object {\n public:\n  /*! \\brief The filename of built binary file. */\n  String filename;\n  /*! \\brief The arguments. */\n  Array<te::Tensor> args;\n  /*! \\brief The error code. (0 means no error, see MeasureErrorNO) */\n  int error_no;\n  /*! \\brief The error message if there is any error. */\n  String error_msg;\n  /*! \\brief The time cost of build. */\n  double time_cost;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"filename\", &filename);\n    v->Visit(\"args\", &args);\n    v->Visit(\"error_no\", &error_no);\n    v->Visit(\"error_msg\", &error_msg);\n    v->Visit(\"time_cost\", &time_cost);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.BuildResult\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BuildResultNode, Object);\n};\n\n/*!\n * \\brief Managed reference to BuildResultNode.\n * \\sa BuildResultNode\n */\nclass BuildResult : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param filename The filename of built binary file.\n   * \\param args The arguments.\n   * \\param error_no The error code.\n   * \\param error_msg The error message if there is any error.\n   * \\param time_cost The time cost of build.\n   */\n  BuildResult(String filename, Array<te::Tensor> args, int error_no, String error_msg,\n              double time_cost);\n  TVM_DEFINE_OBJECT_REF_METHODS(BuildResult, ObjectRef, BuildResultNode);\n};\n\n/*! \\brief Store the results of a measurement. */\nclass MeasureResultNode : public Object {\n public:\n  /*! \\brief The time costs of execution. */\n  Array<PrimExpr> costs;\n  /*! \\brief The error code. (0 means no error, see MeasureErrorNO) */\n  int error_no;\n  /*! \\brief The error message if there is any error. */\n  String error_msg;\n  /*! \\brief The time cost of build and run. */\n  double all_cost;\n  /*! \\brief The time stamps of this measurement. */\n  double timestamp;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"costs\", &costs);\n    v->Visit(\"error_no\", &error_no);\n    v->Visit(\"error_msg\", &error_msg);\n    v->Visit(\"all_cost\", &all_cost);\n    v->Visit(\"timestamp\", &timestamp);\n  }\n\n  /*! \\brief Do shallow copy. */\n  MeasureResult copy() const;\n\n  static constexpr const char* _type_key = \"auto_scheduler.MeasureResult\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MeasureResultNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MeasureResultNode.\n * \\sa MeasureResultNode\n */\nclass MeasureResult : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param costs The time costs of execution.\n   * \\param error_no The error code.\n   * \\param error_msg The error message if there is any error.\n   * \\param all_cost The time cost of build and run.\n   * \\param timestamp The time stamps of this measurement.\n   */\n  MeasureResult(Array<PrimExpr> costs, int error_no, String error_msg, double all_cost,\n                double timestamp);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(MeasureResult, ObjectRef, MeasureResultNode);\n};\n\n/*! \\brief Bass class of measurement callbacks */\nclass MeasureCallbackNode : public Object {\n public:\n  /*!\n   * \\brief Callback function that will be called on measurement input/result pairs\n   * after each measurement batch.\n   * \\param policy The current search policy.\n   * \\param inputs An Array of MeasureInput.\n   * \\param results An Array of MeasureResult.\n   */\n  virtual void Callback(const SearchPolicy& policy, const Array<MeasureInput>& inputs,\n                        const Array<MeasureResult>& results) = 0;\n  static constexpr const char* _type_key = \"auto_scheduler.MeasureCallback\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MeasureCallbackNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MeasureCallbackNode.\n * \\sa MeasureCallbackNode\n */\nclass MeasureCallback : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MeasureCallback, ObjectRef, MeasureCallbackNode);\n};\n\n/*! \\brief A wrapper for measure callback defined by python code\n *  This class will call functions defined in the python */\nclass PythonBasedMeasureCallbackNode : public MeasureCallbackNode {\n public:\n  /*! \\brief Pointer to the callback function in python */\n  PackedFunc callback_func;\n\n  void Callback(const SearchPolicy& policy, const Array<MeasureInput>& inputs,\n                const Array<MeasureResult>& results) final;\n  static constexpr const char* _type_key = \"auto_scheduler.PythonBasedMeasureCallback\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PythonBasedMeasureCallbackNode, MeasureCallbackNode);\n};\n\n/*!\n * \\brief Managed reference to PythonBasedMeasureCallbackNode.\n * \\sa PythonBasedMeasureCallbackNode\n */\nclass PythonBasedMeasureCallback : public MeasureCallback {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param callback_func The pointer to the callback function defined in python\n   */\n  explicit PythonBasedMeasureCallback(PackedFunc callback_func);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PythonBasedMeasureCallback, MeasureCallback,\n                                        PythonBasedMeasureCallbackNode);\n};\n\n// The base class of ProgramBuilders and ProgramRunners.\n\n/*! \\brief ProgramBuilder that builds the programs */\nclass ProgramBuilderNode : public Object {\n public:\n  /*! \\brief The number of build processes to run in parallel */\n  int n_parallel;\n  /*! \\brief Timeout of a build */\n  int timeout;\n\n  /*!\n   * \\brief Build programs and return results.\n   * \\param inputs An Array of MeasureInput.\n   * \\param verbose Verbosity level. 0 for silent, 1 to output information during program\n   * building.\n   * \\return An Array of MeasureResult.\n   */\n  virtual Array<BuildResult> Build(const Array<MeasureInput>& inputs, int verbose) = 0;\n\n  static constexpr const char* _type_key = \"auto_scheduler.ProgramBuilder\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ProgramBuilderNode, Object);\n};\n\n/*!\n * \\brief Managed reference to ProgramBuilderNode.\n * \\sa ProgramBuilderNode\n */\nclass ProgramBuilder : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ProgramBuilder, ObjectRef, ProgramBuilderNode);\n};\n\n/*! \\brief ProgramRunner that runs the built programs and measure the time cost. */\nclass ProgramRunnerNode : public Object {\n public:\n  /*! \\brief Timeout of a run. */\n  int timeout;\n  /*! \\brief The number of times to run the generated code for taking average. */\n  int number;\n  /*! \\brief The number of times to repeat the measurement. */\n  int repeat;\n  /*! \\brief The minimum duration of one repeat in milliseconds. */\n  int min_repeat_ms;\n  /*! \\brief The cool down interval between two measurements. */\n  double cooldown_interval;\n  /*! \\brief Whether to flush cache on CPU between repeated measurements. */\n  bool enable_cpu_cache_flush;\n  /*! \\brief Which device to run on if multiple are avaialble. */\n  int device;\n\n  /*!\n   * \\brief Run measurement and return results.\n   * \\param inputs An Array of MeasureInput.\n   * \\param build_results An Array of BuildResult.\n   * \\param verbose Verbosity level. 0 for silent, 1 to output information during program\n   * running.\n   * \\return An Array of MeasureResult.\n   */\n  virtual Array<MeasureResult> Run(const Array<MeasureInput>& inputs,\n                                   const Array<BuildResult>& build_results, int verbose) = 0;\n\n  static constexpr const char* _type_key = \"auto_scheduler.ProgramRunner\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ProgramRunnerNode, Object);\n};\n\n/*!\n * \\brief Managed reference to ProgramRunnerNode.\n * \\sa ProgramRunnerNode\n */\nclass ProgramRunner : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ProgramRunner, ObjectRef, ProgramRunnerNode);\n};\n\n// Implementation of various builders and runners\n\n/*! \\brief LocalBuilder use local CPU cores to build programs in parallel */\nclass LocalBuilderNode : public ProgramBuilderNode {\n public:\n  /*! \\brief Build function. */\n  String build_func;\n\n  Array<BuildResult> Build(const Array<MeasureInput>& inputs, int verbose) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.LocalBuilder\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LocalBuilderNode, ProgramBuilderNode);\n};\n\n/*!\n * \\brief Managed reference to LocalBuilderNode.\n * \\sa LocalBuilderNode\n */\nclass LocalBuilder : public ProgramBuilder {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param timeout The timeout limit (in second) for each build thread.\n   * This will be used in a wrapper of the multiprocessing.Process.join().\n   * \\param n_parallel The number of threads used to build in parallel.\n   * \\param build_func The name of the registered build function.\n   */\n  LocalBuilder(int timeout, int n_parallel, const String& build_func);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(LocalBuilder, ProgramBuilder, LocalBuilderNode);\n};\n\n/*! \\brief LocalRunner that uses local CPU/GPU to measure the time cost of programs */\nclass LocalRunnerNode : public ProgramRunnerNode {\n public:\n  Array<MeasureResult> Run(const Array<MeasureInput>& inputs,\n                           const Array<BuildResult>& build_results, int verbose) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.LocalRunner\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LocalRunnerNode, ProgramRunnerNode);\n};\n\n/*!\n * \\brief Managed reference to LocalRunnerNode.\n * \\sa LocalRunnerNode\n */\nclass LocalRunner : public ProgramRunner {\n public:\n  /*!\n   * \\brief The constructor. See the corresponding class in python/tvm/auto_scheduler/measure.py\n   * for more detailed parameter explanation.\n   * \\param timeout The timeout limit (in second) for each run.\n   * This is used in a wrapper of the multiprocessing.Process.join().\n   * \\param number The number of times to run the generated code for taking average.\n   * \\param repeat The number of times to repeat the measurement.\n   * \\param min_repeat_ms The minimum duration of one repeat in milliseconds.\n   * \\param cooldown_interval The cool down interval between two measurements.\n   * \\param enable_cpu_cache_flush Whether to flush cache on CPU between repeated measurements.\n   * \\param device Which device to run on if multiple are available.\n   */\n  LocalRunner(int timeout, int number, int repeat, int min_repeat_ms, double cooldown_interval,\n              bool enable_cpu_cache_flush, int device);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(LocalRunner, ProgramRunner, LocalRunnerNode);\n};\n\n/*!\n * \\brief RPCRunner that uses RPC call to measures the time cost of programs on remote devices.\n * Or sometime we may need to use RPC even in local running to insulate the thread environment.\n * (e.g. running CUDA programs)\n */\nclass RPCRunnerNode : public ProgramRunnerNode {\n public:\n  /*! \\brief The key of the device registered in the RPC tracker. */\n  String key;\n  /*! \\brief The host address of the RPC Tracker. */\n  String host;\n  /*! \\brief The port of the RPC Tracker. */\n  int port;\n  /*! \\brief The priority of this run request, larger is more prior. */\n  int priority;\n  /*! \\brief The number of tasks run in parallel. */\n  int n_parallel;\n\n  Array<MeasureResult> Run(const Array<MeasureInput>& inputs,\n                           const Array<BuildResult>& build_results, int verbose) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.RPCRunner\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RPCRunnerNode, ProgramRunnerNode);\n};\n\n/*!\n * \\brief Managed reference to RPCRunnerNode.\n * \\sa RPCRunnerNode\n */\nclass RPCRunner : public ProgramRunner {\n public:\n  /*!\n   * \\brief The constructor. See the corresponding class in python/tvm/auto_scheduler/measure.py\n   * for more detailed parameter explanation.\n   * \\param key The key of the device registered in the RPC tracker.\n   * \\param host The host address of the RPC Tracker.\n   * \\param port The port of RPC Tracker.\n   * \\param priority The priority of this run request, larger is more prior.\n   * \\param n_parallel The number of tasks run in parallel.\n   * \\param timeout Timeout of a run.\n   * \\param number The number of times to run the generated code for taking average.\n   * \\param repeat The number of times to repeat the measurement.\n   * \\param min_repeat_ms The minimum duration of one repeat in milliseconds.\n   * \\param cooldown_interval The cool down interval between two measurements.\n   * \\param enable_cpu_cache_flush Whether to flush cache on CPU between repeated measurements.\n   * \\param device Which device to run on if multiple are available.\n   */\n  RPCRunner(const String& key, const String& host, int port, int priority, int n_parallel,\n            int timeout, int number, int repeat, int min_repeat_ms, double cooldown_interval,\n            bool enable_cpu_cache_flush, int device);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(RPCRunner, ProgramRunner, RPCRunnerNode);\n};\n\n/*!\n * \\brief Measurer that measures the time costs of tvm programs\n * This class combines ProgramBuilder and ProgramRunner, and provides a simpler API */\nclass ProgramMeasurerNode : public Object {\n public:\n  /*! \\brief Measured programs counter. */\n  int ct;\n  /*! \\brief Continuous error counter. */\n  int error_ct;\n  /*! \\brief Workload key to best flops map. */\n  std::unordered_map<std::string, double> best_flops;\n  /*! \\brief Workload key to best state map. */\n  std::unordered_map<std::string, State> best_state;\n  /*! \\brief Workload key to best state's count index map. */\n  std::unordered_map<std::string, int> best_ct;\n  /*! \\brief The set of workloads that have at least one valid schedule */\n  std::unordered_set<std::string> has_valid;\n  /*! \\brief The ProgramBuilder to build each program. */\n  ProgramBuilder builder;\n  /*! \\brief The ProgramRunner to measure each program. */\n  ProgramRunner runner;\n  /*! \\brief MeasureCallback to be called after each measure batch. */\n  Optional<Array<MeasureCallback>> callbacks;\n  /*! \\brief Verbosity level. 0 for silent, 1 to output information during program measuring. */\n  int verbose;\n  /*! \\brief The number of allowed maximum continuous error before forcely stopping the tuning */\n  int max_continuous_error;\n\n  /*! \\brief Reset book keeping variables */\n  void Reset();\n\n  /*!\n   * \\brief Do measurement.\n   * \\param task The current SearchTask.\n   * \\param policy The current SearchPolicy.\n   * \\param inputs The inputs of measurement.\n   * \\param batch_size Number of programs to be measured in one batch.\n   * \\return results The results of measurement.\n   */\n  Array<MeasureResult> Measure(const SearchTask& task, const SearchPolicy& policy,\n                               const Array<MeasureInput>& inputs, int batch_size = -1);\n  /*!\n   * \\brief Do measurement silently.\n   * This API will not print the measure results to screen.\n   * \\param task The current SearchTask.\n   * \\param inputs The MeasureInputs.\n   * \\param results A pointer to a MeasureResult Array, this is used as output.\n   */\n  void SilentMeasure(const SearchTask& task, const Array<MeasureInput>& inputs,\n                     Array<MeasureResult>* results);\n\n  /*! \\brief The default max continuous error setting. */\n  static const int DEFAULT_MAX_CONTINUOUS_ERROR = 150;\n\n  static constexpr const char* _type_key = \"auto_scheduler.ProgramMeasurer\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProgramMeasurerNode, Object);\n};\n\n/*!\n * \\brief Managed reference to ProgramMeasurerNode.\n * \\sa ProgramMeasurerNode\n */\nclass ProgramMeasurer : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param builder The ProgramBuilder to build programs.\n   * \\param runner The ProgramRunner to measure programs.\n   * \\param callbacks MeasureCallback to be called after each measurement batch.\n   * \\param verbose Verbosity level. 0 for silent, 1 to output information during program\n   * measuring.\n   * \\param max_continuous_error The number of allowed maximum continuous error before\n   * forcely stopping the tuning.\n   */\n  ProgramMeasurer(ProgramBuilder builder, ProgramRunner runner,\n                  Optional<Array<MeasureCallback>> callbacks, int verbose,\n                  int max_continuous_error = -1);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ProgramMeasurer, ObjectRef, ProgramMeasurerNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_MEASURE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/measure_record.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/auto_scheduler/measure_record.h\n * \\brief Json serialization format for dumping and loading measurement records.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_MEASURE_RECORD_H_\n#define TVM_AUTO_SCHEDULER_MEASURE_RECORD_H_\n\n#include <tvm/auto_scheduler/measure.h>\n\n#include <fstream>\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nconst std::string AUTO_SCHEDULER_LOG_VERSION = \"v0.6\";  // NOLINT(*)\n\n/*! \\brief Callback for logging the input and results of measurements to file */\nclass RecordToFileNode : public MeasureCallbackNode {\n public:\n  /*! \\brief The name of output file. */\n  String filename;\n\n  void Callback(const SearchPolicy& policy, const Array<MeasureInput>& inputs,\n                const Array<MeasureResult>& results) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.RecordToFile\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RecordToFileNode, MeasureCallbackNode);\n};\n\n/*!\n * \\brief Managed reference to RecordToFileNode.\n * \\sa RecordToFileNode\n */\nclass RecordToFile : public MeasureCallback {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param filename The name of output file\n   */\n  explicit RecordToFile(String filename);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(RecordToFile, MeasureCallback, RecordToFileNode);\n};\n\n/*! \\brief Log reader to load step logs from a file.*/\nclass RecordReaderNode : public Object {\n public:\n  /*! \\brief The name of input file. */\n  String filename;\n  /*! \\brief The reading file stream. */\n  std::ifstream infile;\n\n  ~RecordReaderNode();\n\n  /*!\n   * \\brief Read next line in the log file.\n   * \\param inp A pointer to a MeasureInputNode, this is used as output.\n   * \\param res A pointer to a MeasureResultNode, this is used as output.\n   * \\return Whether the read is successful. */\n  bool ReadNext(MeasureInputNode* inp, MeasureResultNode* res);\n\n  /*!\n   * \\brief Read multiple lines from the log file.\n   * \\param max_size The maximum number of lines. -1 means read all lines.\n   * \\param skip_size Skip the first n lines.\n   * \\return The MeasureInputs and MeasureResults loaded from the log file.\n   */\n  std::pair<Array<MeasureInput>, Array<MeasureResult>> ReadLines(int max_size = -1,\n                                                                 int skip_size = 0);\n\n  static constexpr const char* _type_key = \"auto_scheduler.RecordReader\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RecordReaderNode, Object);\n\n private:\n  /*! \\brief A string storing the current line. */\n  std::string cur_line_;\n};\n\n/*!\n * \\brief Managed reference to RecordReaderNode.\n * \\sa RecordReaderNode\n */\nclass RecordReader : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param filename The name of input file\n   */\n  explicit RecordReader(String filename);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(RecordReader, ObjectRef, RecordReaderNode);\n};\n\n/*!\n * \\brief Append measure records to an output stream.\n * \\param os A pointer to a output stream.\n * \\param inputs The MeasureInputs to be written.\n * \\param results The MeasureResults to be written.\n * \\param log_version The log version for the given record.\n */\nvoid WriteMeasureRecords(std::ostream* os, const Array<MeasureInput>& inputs,\n                         const Array<MeasureResult>& results,\n                         const std::string log_version = AUTO_SCHEDULER_LOG_VERSION);\n\n/*!\n * \\brief Read one measure record from a string.\n * \\param str The record string to be parsed.\n * \\param inp A pointer to a MeasureInputNode used to store the return value.\n * \\param res A pointer to a MeasureResultNode used to store the return value.\n * \\param log_version A pointer to a string used to store the log version.\n */\nvoid ReadMeasureRecord(const std::string& str, MeasureInputNode* inp, MeasureResultNode* res,\n                       std::string* log_version);\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_MEASURE_RECORD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/search_policy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/auto_scheduler/search_policy.h\n * \\brief The base class of search policies, including the abstract definition of search policy and\n * other supporting data structures.\n *\n * \\note How to add a new search policy.\n * In design, there's no need for users to implement their own search policy, our formal search\n * policy(will be brought later) should be enough to cover most use cases. Meanwhile, a custom rule\n * mechanism will be provided to enable user-defined template search to serve the same functionality\n * as the current AutoTVM template.\n *\n * This guide is for advanced uses who have special requirements.\n * 1. The only function that must be implemented is Search(), which takes a task as input and\n * returns the best states found.\n * 2. Information about the compute declaration of ops/subgraphs can be acquired from SearchTask.\n * This structure also contains some information about the target device. (e.g. knowing the width\n * of the device vector unit, we can limit the max vectorize size during schedule search)\n * 3. SearchCallback provides more flexibility to do extra affairs before/after the search process.\n * 4. ProgramMeasurer provides a simple but useful api to help check the performance of states got\n * during the search process.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_POLICY_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_POLICY_H_\n\n#include <tvm/auto_scheduler/measure.h>\n#include <tvm/auto_scheduler/search_task.h>\n#include <tvm/node/node.h>\n\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nclass ProgramMeasurer;\nclass SearchPolicyNode;\n\n/*!\n * \\brief Callback function to be called by the search process.\n * This interface allows to do extra initializations before schedule search or extra\n * check during/after the schedule search.\n */\nclass SearchCallbackNode : public Object {\n public:\n  /*!\n   * \\brief Run the registered callback function.\n   * \\param policy A pointer to a SearchPolicyNode.\n   */\n  virtual void Callback(SearchPolicyNode* policy) = 0;\n\n  static constexpr const char* _type_key = \"auto_scheduler.SearchCallback\";\n  TVM_DECLARE_BASE_OBJECT_INFO(SearchCallbackNode, Object);\n};\n\n/*!\n * \\brief Managed reference to SearchCallbackNode.\n * \\sa SearchCallbackNode\n */\nclass SearchCallback : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(SearchCallback, ObjectRef, SearchCallbackNode);\n};\n\n/*! \\brief Preload measured states from a log file.\n * This can resume the state of the search policy */\nclass PreloadMeasuredStatesNode : public SearchCallbackNode {\n public:\n  /*! \\brief The name of the record log file. */\n  String filename;\n\n  void Callback(SearchPolicyNode* policy) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.PreloadMeasuredStates\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PreloadMeasuredStatesNode, SearchCallbackNode);\n};\n\n/*!\n * \\brief Managed reference to PreloadMeasuredStatesNode.\n * \\sa PreloadMeasuredStatesNode\n */\nclass PreloadMeasuredStates : public SearchCallback {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param filename The name of the record log file.\n   */\n  explicit PreloadMeasuredStates(String filename);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PreloadMeasuredStates, SearchCallback,\n                                        PreloadMeasuredStatesNode);\n};\n\n/*! \\brief Attribute keys of ops used for SearchPolicy. */\nstruct SearchPolicyKey {\n  /*! \\brief Always apply unroll to the inner most iterator of the specificed iterators. */\n  static constexpr const char* always_unroll_inner = \"auto_scheduler_always_unroll_inner\";\n  /*! \\brief The specified iterators will be placed in the inner most tile without split. */\n  static constexpr const char* no_split_at_inner = \"auto_scheduler_no_split_at_inner\";\n  /*! \\brief The specified iterators are indices of const tensors in \"fake reduction\". */\n  static constexpr const char* simplify_const_tensor_indices =\n      \"auto_scheduler_simplify_const_tensor_indices\";\n};\n\n/*!\n * \\brief The base class of search policies.\n */\nclass SearchPolicyNode : public Object {\n public:\n  /*! \\brief The current search task. */\n  SearchTask search_task;\n  /*!\n   * \\brief Verbose level to control the screen output during schedule search.\n   * 0 for silent, 1 to output state & measure information during search process.\n   */\n  int verbose;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"search_task\", &search_task);\n    v->Visit(\"verbose\", &verbose);\n  }\n\n  /*!\n   * \\brief Do schedule search for a task. Takes the SearchTask as input and returns the best state\n   * found during the search.\n   * \\param num_measure_trials The number of total measurement trials.\n   * \\param early_stopping Stops the tuning early if no improvement after n measurements.\n   * \\param num_measures_per_round  The number of programs to be measured at each search round.\n   * \\param measurer A ProgramMeasurer to build and measure programs\n   * \\return The best state found.\n   */\n  virtual State Search(int num_measure_trials, int early_stopping, int num_measures_per_round,\n                       ProgramMeasurer measurer) = 0;\n\n  /*!\n   * \\brief Continue the search by doing an additional search round.\n   * \\param num_measure The number of measurements\n   * \\param measurer The measurer to measure programs\n   * \\return The measurement records for measurements in this search round\n   */\n  virtual std::pair<Array<MeasureInput>, Array<MeasureResult>> ContinueSearchOneRound(\n      int num_measure, ProgramMeasurer measurer) = 0;\n\n  /*!\n   * \\brief Preload measured states from a log file to resume the state of the search policy.\n   * \\param log_file The name of the record log file.\n   */\n  void PreloadMeasuredStates(const String& log_file);\n\n  /*!\n   * \\brief Call SearchCallback with the current SearchPolicyNode\n   * \\param callbacks SearchCallback to be called.\n   */\n  void RunCallbacks(const Array<SearchCallback>& callbacks);\n\n  static constexpr const char* _type_key = \"auto_scheduler.SearchPolicy\";\n  TVM_DECLARE_BASE_OBJECT_INFO(SearchPolicyNode, Object);\n\n protected:\n  /*!\n   * \\brief The set of already measured states.\n   * We store the string format of a state for redundancy check. This is used to make sure a\n   * measured state will never be measured again.\n   */\n  std::unordered_set<std::string> measured_states_set_;\n  /*! \\brief The array of already measured states.\n   *  The good states can be used as the initial population in evolutionary search. */\n  std::vector<State> measured_states_vector_;\n  /*! \\brief The throughputs of already measured states */\n  std::vector<float> measured_states_throughputs_;\n};\n\n/*!\n * \\brief Managed reference to SearchPolicyNode.\n * \\sa SearchPolicyNode\n */\nclass SearchPolicy : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(SearchPolicy, ObjectRef, SearchPolicyNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_POLICY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/search_task.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/search_task.h\n * \\brief Meta information and hardware parameters for a search task.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_TASK_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_TASK_H_\n\n#include <tvm/auto_scheduler/compute_dag.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nclass HardwareParams;\n\n/*! \\brief The parameters of target hardware used to guide the SearchPolicy. */\nclass HardwareParamsNode : public Object {\n public:\n  /*! \\brief The number of cores. */\n  int num_cores;\n  /*! \\brief The width of vector units in bytes. */\n  int vector_unit_bytes;\n  /*! \\brief The size of cache line in bytes. */\n  int cache_line_bytes;\n\n  // GPU related parameters got from device query API\n  /*! \\brief The max shared memory per block in bytes. */\n  int max_shared_memory_per_block;\n  /*! \\brief The max local memory per block in bytes. */\n  int max_local_memory_per_block;\n  /*! \\brief The max number of threads per block. */\n  int max_threads_per_block;\n  /*! \\brief The max vthread extent. */\n  int max_vthread_extent;\n  /*! \\brief The thread numbers of a warp. */\n  int warp_size;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"num_cores\", &num_cores);\n    v->Visit(\"vector_unit_bytes\", &vector_unit_bytes);\n    v->Visit(\"cache_line_bytes\", &cache_line_bytes);\n    v->Visit(\"max_shared_memory_per_block\", &max_shared_memory_per_block);\n    v->Visit(\"max_local_memory_per_block\", &max_local_memory_per_block);\n    v->Visit(\"max_threads_per_block\", &max_threads_per_block);\n    v->Visit(\"max_vthread_extent\", &max_vthread_extent);\n    v->Visit(\"warp_size\", &warp_size);\n  }\n\n  /*!\n   * \\brief Get the default hardware params.\n   * \\param target A `tvm.target`.\n   * \\param target_host A `tvm.target` for host device.\n   * \\return A HardwareParams object.\n   */\n  static HardwareParams GetDefaultHardwareParams(const Target& target, const Target& target_host);\n\n  static constexpr const char* _type_key = \"auto_scheduler.HardwareParams\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(HardwareParamsNode, Object);\n};\n\n/*!\n * \\brief Managed reference to HardwareParamsNode.\n * \\sa HardwareParamsNode\n */\nclass HardwareParams : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param num_cores The number of cores.\n   * \\param vector_unit_bytes The width of vector units in bytes.\n   * \\param cache_line_bytes The size of cache line in bytes.\n   * \\param max_shared_memory_per_block The max amount of shared memory per block for GPU.\n   * \\param max_local_memory_per_block The max amount of local memory per block for GPU.\n   * \\param max_threads_per_block The max number of threads per block for GPU.\n   * \\param max_vthread_extent The max extent of vthread for GPU.\n   * \\param warp_size The warp size for GPU\n   */\n  HardwareParams(int num_cores, int vector_unit_bytes, int cache_line_bytes,\n                 int max_shared_memory_per_block, int max_local_memory_per_block,\n                 int max_threads_per_block, int max_vthread_extent, int warp_size);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(HardwareParams, ObjectRef, HardwareParamsNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(HardwareParamsNode);\n};\n\n/*!\n * \\brief The computation information and hardware parameters for a specific schedule search task.\n */\nclass SearchTaskNode : public Object {\n public:\n  /*! \\brief The ComputeDAG for the compute declaration. */\n  ComputeDAG compute_dag;\n  /*! \\brief The workload key for the compute declaration. */\n  String workload_key;\n  /*! \\brief The description string of this task. */\n  String desc;\n  /*! \\brief The target device of this search task. */\n  Target target;\n  /*! \\brief The target host device of this search task. */\n  Target target_host;\n  /*! \\brief Hardware parameters used in this search task. */\n  HardwareParams hardware_params;\n  /*! \\brief The layout rewrite option used for measuring programs. */\n  LayoutRewriteOption layout_rewrite_option;\n  /*! \\brief Names of some user defined input data used in program measuring. */\n  Array<String> task_input_names;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"compute_dag\", &compute_dag);\n    v->Visit(\"workload_key\", &workload_key);\n    v->Visit(\"desc\", &desc);\n    v->Visit(\"target\", &target);\n    v->Visit(\"target_host\", &target_host);\n    v->Visit(\"hardware_params\", &hardware_params);\n    v->Visit(\"layout_rewrite_option\", &layout_rewrite_option);\n    v->Visit(\"task_input_names\", &task_input_names);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.SearchTask\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SearchTaskNode, Object);\n};\n\n/*!\n * \\brief Managed reference to SearchTaskNode.\n * \\sa SearchTaskNode\n */\nclass SearchTask : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param compute_dag The ComputeDAG for the compute declaration.\n   * \\param workload_key The workload key for the compute declaration.\n   * \\param target The target device of this search task.\n   * \\param target_host The target host device of this search task.\n   * \\param hardware_params Hardware parameters used in this search task.\n   * \\param layout_rewrite_option The layout rewrite option used for measuring programs.\n   * \\param task_input_names Names of some user defined input data used in program measuring.\n   * \\param desc The description string of this task.\n   */\n  SearchTask(ComputeDAG compute_dag, String workload_key, Target target, Target target_host,\n             Optional<HardwareParams> hardware_params, LayoutRewriteOption layout_rewrite_option,\n             Array<String> task_input_names, String desc = \"\");\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SearchTask, ObjectRef, SearchTaskNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_TASK_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/auto_scheduler/transform_step.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/transform_step.h\n * \\brief Transformation steps. These steps are used to manipulate `LoopState`.\n *        They are similar to the schedule primitives in te::Stage.\n *\n * \\note How to add a new transform step:\n * Take fuse step for example:\n * 1. Define class `FuseStepNode`, `FuseStep` in `transform_steps.h`, and implement its first\n *    construction function `FuseStep::FuseStep()` in `transform_steps.cc`.\n * 2. Implement `FuseStepNode::ApplyToSchedule()` and `FuseStepNode::PrintAsPythonAPI()`.\n *    - In these two functions you need to lower this step with tvm's te schedule API\n * 3. Implement `FuseStepNode::ApplyToState` and the state API `State::fuse`.\n *    - In these two functions you need to incrementally update all data structures in State with\n *      CopyOnWrite style.\n * 4. Add your step to `StepApplyToState`, `StepApplyToSchedule`, and `StepPrintAsPythonAPI`.\n * 5. Log record serialization support:\n *    - Add `FuseStepNode::WriteToRecord` which takes a mutable JSONWriter pointer as input and\n *      output the record to it.\n *    - Add another construction function that takes a mutable JSONReader as input, this will get a\n *      step record from the reader and create the step.\n *    - Add the step implementation to `StepReadFromRecord`.\n * 6. Add its corresponding Python API to `loop_state.py` with necessary unit tests. The test should\n *    at lease cover two parts: the functional test and the record serialization test.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_TRANSFORM_STEP_H_\n#define TVM_AUTO_SCHEDULER_TRANSFORM_STEP_H_\n\n#include <dmlc/common.h>\n#include <dmlc/json.h>\n#include <tvm/node/node.h>\n#include <tvm/te/schedule.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\ntypedef Map<tvm::te::Stage, Array<tir::IterVar>, ObjectHash, ObjectEqual> StageToAxesMap;\n\n/*!\n * \\brief Update the current stage IterVar information to StageToAxesMap.\n * \\param stage The stage to be updated.\n * \\param stage_to_axes The map to be updated.\n */\nvoid UpdateStageToAxesMap(const te::Stage& stage, StageToAxesMap* stage_to_axes);\n\n/*! \\brief The type of an iterator. */\nenum class IteratorKind : int {\n  /*! \\brief Spatial iterator. */\n  kSpatial = 0,\n  /*! \\brief Reduction iterator. */\n  kReduction = 1,\n  /*! \\brief Fused spatial and reduction iterator. */\n  kMixed = 2,\n  /*! \\brief Special iterator. (e.g. virtual root iterator) */\n  kSpecial = 3\n};\n\n/*! \\brief The type of an iterator's annotation. */\nenum class IteratorAnnotation : int {\n  /*! \\brief This iterator has no annotation. */\n  kNone = 0,\n  /*! \\brief This iterator has been unrolled. */\n  kUnroll = 1,\n  /*! \\brief This iterator has been vectorized. */\n  kVectorize = 2,\n  /*! \\brief This iterator has been paralleld. */\n  kParallel = 3,\n  /*! \\brief This iterator has been bind to vthread. */\n  kVThread = 4,\n  /*! \\brief This iterator has been bind to blockIdx.x. */\n  kBlockX = 5,\n  /*! \\brief This iterator has been bind to threadIdx.x. */\n  kThreadX = 6,\n  /*! \\brief This iterator has been bind to blockIdx.y. */\n  kBlockY = 7,\n  /*! \\brief This iterator has been bind to threadIdx.y. */\n  kThreadY = 8,\n  /*! \\brief This iterator has been bind to blockIdx.y. */\n  kBlockZ = 9,\n  /*! \\brief This iterator has been bind to threadIdx.y. */\n  kThreadZ = 10,\n  /*! \\brief This iterator has been mapped with a tensorize intrinsic. */\n  kTensorize = 11\n};\n\nextern const char* IteratorAnnotationString[];\n\n// forward declaration\nclass Iterator;\n\n/*!\n * \\brief An iterator of a for-loop\n * Similar to tvm::IterVar in `include/tvm/tir/expr.h`\n */\nclass IteratorNode : public Object {\n public:\n  /*! \\brief The name of this iterator. */\n  String name;\n  /*! \\brief The range of this iterator. */\n  Range range;\n  /*! \\brief The iterator type of this iterator. */\n  IteratorKind iter_kind;\n  /*! \\brief The annotation type of this iterator. */\n  IteratorAnnotation annotation;\n  /*! The original iterators before fusion. */\n  std::vector<Iterator> orig_iters;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"range\", &range);\n    v->Visit(\"iter_kind\", &iter_kind);\n    v->Visit(\"annotation\", &annotation);\n  }\n\n  static constexpr const char* _type_key = \"auto_scheduler.Iterator\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IteratorNode, Object);\n};\n\n/*!\n * \\brief Managed reference to IteratorNode.\n * \\sa IteratorNode\n */\nclass Iterator : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param name The name of this iterator.\n   * \\param range The range of this iterator.\n   * \\param iter_kind The iterator type of this iterator.\n   * \\param annotation The annotation type of this iterator.\n   * \\param orig_iters The original iterators before fusion\n   */\n  Iterator(String name, Range range, IteratorKind iter_kind, IteratorAnnotation annotation,\n           const std::vector<Iterator>* orig_iters = nullptr);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Iterator, ObjectRef, IteratorNode);\n};\n\n/*!\n * \\brief The base class of transformation steps. Each step has its corresponding tvm.te\n * schedule primitives.\n */\nclass StepNode : public Object {\n public:\n  /*! \\brief The index of the stage. */\n  int stage_id;\n\n  /*!\n   * \\brief Serialize the current step record to JSONWriter.\n   * \\param writer The output JSONWriter.\n   */\n  virtual void WriteToRecord(dmlc::JSONWriter* writer) const = 0;\n\n  static constexpr const char* _type_key = \"auto_scheduler.Step\";\n  TVM_DECLARE_BASE_OBJECT_INFO(StepNode, Object);\n};\n\n/*!\n * \\brief Managed reference to StepNode.\n * \\sa StepNode\n */\nclass Step : public ObjectRef {\n public:\n  /*!\n   * \\brief CopyOnWrite function for Step.\n   * This works almost the same as a normal ObjectRef.CopyOnWrite(), but can dispatch to different\n   * steps.\n   * \\return A base StepNode pointer, need to cast to its real StepNode type before doing any\n   * modifications.\n   * \\code\n   *\n   *  SplitStep ref;\n   *  StepNode* mutable_ref = ref.CopyOnWrite();\n   *  dynamic_cast<SplitStepNode*>(mutable_ref)->... = ...;\n   *\n   * \\endcode\n   */\n  StepNode* CopyOnWrite();\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Step, ObjectRef, StepNode);\n};\n\n// Forward declaration\nclass State;\nclass ComputeDAG;\n\n/*!\n * \\brief Read a step record from JSONReader and create the corresponding step.\n * \\param reader The input JSONReader.\n */\nStep StepReadFromRecord(dmlc::JSONReader* reader);\n\n/*!\n * \\brief Apply a general step to a State with runtime dynamic dispatching.\n * \\param step The step to be applied to State.\n * \\param state A mutable pointer to state, which will be updated.\n * \\param dag The original ComputeDAG of this state.\n */\nvoid StepApplyToState(const Step& step, State* state, const ComputeDAG& dag);\n\n/*!\n * \\brief Apply a general step to tvm.schedule with runtime dynamic dispatching.\n * \\param step The step to be applied to tvm.schedule.\n * \\param stages The list of current stages\n * \\param stage_to_axes A map that maps stage ot all its iterators.\n * \\param schedule A mutable point to the current schedule\n * \\param transform_steps An array of all history transform steps.\n */\nvoid StepApplyToSchedule(const Step& step, Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                         te::Schedule* schedule, const Array<Step>& transform_steps);\n\n/*!\n * \\brief Print a general step as equivalent python schedule API with runtime dynamic dispatching.\n * \\param step The step to be printed as python API.\n * \\param stages The list of current stages\n * \\param stage_to_axes A map that maps stage ot all its iterators.\n * \\param schedule A mutable point to the current schedule\n * \\param transform_steps An array of all history transform steps.\n * \\return Python schedule code.\n */\nString StepPrintAsPythonAPI(const Step& step, Array<te::Stage>* stages,\n                            StageToAxesMap* stage_to_axes, te::Schedule* schedule,\n                            const Array<Step>& transform_steps);\n\n/********** Steps working on single stage **********/\n\n/*!\n * \\brief Annotation step that corresponds to vectorize, parallel, unroll and thread binding.\n * (i.e. te::Stage::vectorize, te::Stage::parallel, te::Stage::vectorize, te::Stage::bind)\n */\nclass AnnotationStepNode : public StepNode {\n public:\n  /*! \\brief The index of the iterator to add annotation. */\n  int iter_id;\n  /*! \\brief The annotation type of this step. */\n  IteratorAnnotation annotation;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\return The iterator result after annotate.\n   */\n  Iterator ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"AN\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.AnnotationStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AnnotationStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to AnnotationStepNode.\n * \\sa AnnotationStepNode\n */\nclass AnnotationStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to add annotation.\n   * \\param iter_id The index of the iterator to add annotation.\n   * \\param ann The annotation type of this step.\n   */\n  AnnotationStep(int stage_id, int iter_id, IteratorAnnotation ann);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit AnnotationStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AnnotationStep, Step, AnnotationStepNode);\n};\n\n/*! \\brief Fuse step that corresponds to te::Stage::fuse */\nclass FuseStepNode : public StepNode {\n public:\n  /*! \\brief The ids of iterators to fuse. */\n  Array<Integer> fused_ids;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\return The iterator result after fuse.\n   * \\note If the iterators to be fused have stages attached at them(by compute_at), the fused\n   * result will become the new attach point.\n   */\n  Iterator ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return The iterator result after fuse.\n   */\n  tir::IterVar ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"FU\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.FuseStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FuseStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to FuseStepNode.\n * \\sa FuseStepNode\n */\nclass FuseStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be fused.\n   * \\param fused_ids The index of the iterators to be fused.\n   */\n  FuseStep(int stage_id, const Array<Integer>& fused_ids);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit FuseStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FuseStep, Step, FuseStepNode);\n};\n\n/*! \\brief Pragma step that corresponds to te::Stage::pragma */\nclass PragmaStepNode : public StepNode {\n public:\n  /*! \\brief The index of the iterator to add pragma. */\n  int iter_id;\n  /*! \\brief The pragma string. */\n  String pragma_type;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"PR\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.PragmaStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PragmaStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to PragmaStepNode.\n * \\sa PragmaStepNode\n */\nclass PragmaStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be fused.\n   * \\param iter_id The index of the iterator to add pragma.\n   * \\param pragma_type The pragma string.\n   */\n  PragmaStep(int stage_id, int iter_id, String pragma_type);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit PragmaStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PragmaStep, Step, PragmaStepNode);\n};\n\n/*! \\brief Reorder step that corresponds to te::Stage::reorder */\nclass ReorderStepNode : public StepNode {\n public:\n  /*!\n   * \\brief The iterator ids after reorder.\n   * This array should specify the order of all iterators.\n   */\n  Array<Integer> after_ids;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"RE\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.ReorderStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ReorderStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to ReorderStepNode.\n * \\sa ReorderStepNode\n */\nclass ReorderStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be reordered.\n   * \\param after_ids The expected indexes of the iterators after reorder.\n   */\n  ReorderStep(int stage_id, const Array<Integer>& after_ids);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit ReorderStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ReorderStep, Step, ReorderStepNode);\n};\n\n/*!\n * \\brief Split step that corresponds to te::Stage::split with additional\n *  support of multiple-level of factors\n */\nclass SplitStepNode : public StepNode {\n public:\n  /*! \\brief The id of the iter to split. */\n  int iter_id;\n  /*! \\brief The extent length of the axis to split. */\n  Optional<PrimExpr> extent;\n  /*! \\brief The split factors. */\n  Array<Optional<Integer>> lengths;\n  /*!\n   * \\brief If true, the `lengths` denote the lengths of iterators\n   * from inner level to outer level\n   */\n  bool inner_to_outer;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\return The iterator results after split.\n   * \\note If we do split on an iterator which has stages attached at it(by compute_at), the inner\n   * most iterator of split results will become the new attach point.\n   */\n  Array<Iterator> ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return The iterator results after split.\n   */\n  Array<tir::IterVar> ApplyToSchedule(Array<te::Stage>* stages,\n                                      StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"SP\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.SplitStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SplitStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to SplitStepNode.\n * \\sa SplitStepNode\n */\nclass SplitStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be split.\n   * \\param iter_id The index of the iterator to be split.\n   * \\param extent The extent length of the axis to split.\n   * \\param lengths The multiple split factors. Can be None to be filled by search policy.\n   * \\param inner_to_outer The split direction.\n   */\n  SplitStep(int stage_id, int iter_id, Optional<PrimExpr> extent,\n            const Array<Optional<Integer>>& lengths, bool inner_to_outer);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit SplitStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SplitStep, Step, SplitStepNode);\n};\n\n/*! \\brief Similar to SplitStepNode, but uses split factors from another step\n * (i.e. Follow another split step) */\nclass FollowSplitStepNode : public StepNode {\n public:\n  /*! \\brief The id of the iter to be split. */\n  int iter_id;\n  /*! \\brief The index of the split step to be followed in the history. */\n  int src_step_id;\n  /*! \\brief The number of split level. */\n  int n_split;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Extract split lengths.\n   * \\param transform_steps An array of history transform steps.\n   * \\return The multiple split factors.\n   */\n  Array<Optional<Integer>> ExtractSplitLengths(const Array<Step>& transform_steps) const;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\return The iterator results after split.\n   */\n  Array<Iterator> ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param transform_steps An array of history transform steps.\n   * \\return The iterator results after split.\n   */\n  Array<tir::IterVar> ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                                      const Array<Step>& transform_steps) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param transform_steps An array of history transform steps.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                          const Array<Step>& transform_steps) const;\n\n  static constexpr const char* record_prefix_str = \"FSP\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.FollowSplitStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FollowSplitStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to FollowSplitStepNode.\n * \\sa FollowSplitStepNode\n */\nclass FollowSplitStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be split.\n   * \\param iter_id The index of the iterator to be split.\n   * \\param src_step_id The index of the split step to be followed in the history.\n   * \\param n_split The number of split level.\n   */\n  FollowSplitStep(int stage_id, int iter_id, int src_step_id, int n_split);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit FollowSplitStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FollowSplitStep, Step, FollowSplitStepNode);\n};\n\n/*! \\brief Similar to FollowSplitStep, but uses split factors from multiple steps.\n *  \\note This can be used for the split in cooperative fetching.\n */\nclass FollowFusedSplitStepNode : public StepNode {\n public:\n  /*! \\brief The id of the iter to split. */\n  int iter_id;\n  /*! \\brief The indices of the split steps to be followed in the history. */\n  Array<Integer> src_step_ids;\n  /*! \\brief  Use the length in this split level. */\n  int level;\n  /*! \\brief If this is true, use factor. Otherwise, use nparts. */\n  bool factor_or_nparts;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Extract split length.\n   * \\param transform_steps An array of history transform steps.\n   * \\return Split factor.\n   */\n  Optional<Integer> ExtractSplitLength(const Array<Step>& transform_steps) const;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\return The iterator results after split.\n   */\n  Array<Iterator> ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param transform_steps An array of history transform steps.\n   * \\return The iterator results after split.\n   */\n  Array<tir::IterVar> ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                                      const Array<Step>& transform_steps) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param transform_steps An array of history transform steps.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                          const Array<Step>& transform_steps) const;\n\n  static constexpr const char* record_prefix_str = \"FFSP\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.FollowFusedSplitStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FollowFusedSplitStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to FollowFusedSplitStepNode.\n * \\sa FollowFusedSplitStepNode\n */\nclass FollowFusedSplitStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be split.\n   * \\param iter_id The index of the iterator to be split.\n   * \\param src_step_ids An array of index for split step to be followed in the history.\n   * \\param level Use the length in this split level.\n   * \\param factor_or_nparts If this is true, use factor. Otherwise, use nparts.\n   */\n  FollowFusedSplitStep(int stage_id, int iter_id, const Array<Integer>& src_step_ids, int level,\n                       bool factor_or_nparts);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit FollowFusedSplitStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FollowFusedSplitStep, Step, FollowFusedSplitStepNode);\n};\n\n/*! \\brief Storage align step that corresponds to te::Stage::storage_align */\nclass StorageAlignStepNode : public StepNode {\n public:\n  /*! \\brief The iterator to be aligned. */\n  int iter_id;\n  /*! \\brief The factor in alignment specification. */\n  int factor;\n  /*! \\brief The offset in the alignment specification. */\n  int offset;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to State, which will be updated.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"SA\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.StorageAlignStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StorageAlignStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to StorageAlignStepNode.\n * \\sa StorageAlignStepNode\n */\nclass StorageAlignStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be aligned.\n   * \\param iter_id The index of the iterator to be aligned.\n   * \\param factor The factor in alignment specification.\n   * \\param offset The offset in the alignment specification.\n   */\n  StorageAlignStep(int stage_id, int iter_id, int factor, int offset);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit StorageAlignStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(StorageAlignStep, Step, StorageAlignStepNode);\n};\n\n/********** Steps working on multiple stages **********/\n\n/*! \\brief Compute at step that corresponds to te::Stage::compute_at */\nclass ComputeAtStepNode : public StepNode {\n public:\n  /*! \\brief The index of stage that this step will compute at to. */\n  int target_stage_id;\n  /*! \\brief The index of iterator in target stage that this step will compute at to. */\n  int target_iter_id;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\note After compute_at, we need careful dependency analysis to compute the accurate bound\n   * information. However, it is relatively expensive and complicated, so we just fill \"None\" as\n   * bound for the newly created iterators.\n   * Call ComputeDAG::InferBound on the updated state if you need the complete bound information.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"CA\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.ComputeAtStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ComputeAtStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to ComputeAtStepNode.\n * \\sa ComputeAtStepNode\n */\nclass ComputeAtStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the source stage.\n   * \\param target_stage_id The index of stage that this step will compute at to.\n   * \\param target_iter_id The index of iterator in target stage that this step will compute at to.\n   */\n  ComputeAtStep(int stage_id, int target_stage_id, int target_iter_id);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit ComputeAtStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ComputeAtStep, Step, ComputeAtStepNode);\n};\n\n/*! \\brief Compute inline step that corresponds to te::Stage::compute_inline */\nclass ComputeInlineStepNode : public StepNode {\n public:\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return The iterator result after fuse.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"CI\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.ComputeInlineStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ComputeInlineStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to ComputeInlineStepNode.\n * \\sa ComputeInlineStepNode\n */\nclass ComputeInlineStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be marked compute inlined.\n   */\n  explicit ComputeInlineStep(int stage_id);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit ComputeInlineStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ComputeInlineStep, Step, ComputeInlineStepNode);\n};\n\n/*! \\brief Compute root step that corresponds to te::Stage::compute_root */\nclass ComputeRootStepNode : public StepNode {\n public:\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\note After compute_root, we need careful dependency analysis to compute the accurate bound\n   * information. However, it is relatively expensive and complicated, so we just fill \"None\" as\n   * bound for the newly created iterators.\n   * Call ComputeDAG::InferBound on the updated state if you need the complete bound information.\n   */\n  void ApplyToState(State* state) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return The iterator result after fuse.\n   */\n  void ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes) const;\n\n  static constexpr const char* record_prefix_str = \"CR\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.ComputeRootStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ComputeRootStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to ComputeRootStepNode.\n * \\sa ComputeRootStepNode\n */\nclass ComputeRootStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be marked compute at root.\n   */\n  explicit ComputeRootStep(int stage_id);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit ComputeRootStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ComputeRootStep, Step, ComputeRootStepNode);\n};\n\n/********** Steps adding new stages **********/\n\n/*!\n * \\brief Cache read step that corresponds to te::Schedule::cache_read.\n * \\note Cache read step adds an extra stage to the original ComputeDAG,\n * an up-to-date ComputeDAG will be stored in State's `current_compute_dag`.\n */\nclass CacheReadStepNode : public StepNode {\n public:\n  /*! \\brief The scope name of the newly added read stage. (e.g., local, shared, global) */\n  String scope_name;\n  /*! \\brief The indices of read stages. */\n  Array<Integer> reader_stage_ids;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\param dag The original ComputeDAG of this state.\n   * \\return The index of the new added stage.\n   */\n  int ApplyToState(State* state, const ComputeDAG& dag) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return The output Tensor of the new added stage.\n   */\n  te::Tensor ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                             te::Schedule* schedule) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                          te::Schedule* schedule) const;\n\n  static constexpr const char* record_prefix_str = \"CHR\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.CacheReadStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CacheReadStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to CacheReadStepNode.\n * \\sa CacheReadStepNode\n */\nclass CacheReadStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be cache_read.\n   * \\param scope_name The scope name of the newly added stage.\n   * \\param reader_stage_ids The indices of reader stages.\n   */\n  CacheReadStep(int stage_id, String scope_name, const Array<Integer>& reader_stage_ids);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit CacheReadStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CacheReadStep, Step, CacheReadStepNode);\n};\n\n/*!\n * \\brief Cache write step that corresponds to te::Schedule::cache_write.\n * \\note Cache write step will add an extra stage to the original ComputeDAG, a up-to-date\n * ComputeDAG is stored in State's `current_compute_dag`.\n * This step will cache write all output tensors of the target stage.\n */\nclass CacheWriteStepNode : public StepNode {\n public:\n  /*! \\brief The scope name of the newly added compute stage. (e.g. local, shared, global) */\n  String scope_name;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to state, which will be updated.\n   * \\param dag The original ComputeDAG of this state.\n   * \\return The index of the new added stage.\n   */\n  int ApplyToState(State* state, const ComputeDAG& dag) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return The output Tensors of the new added stage.\n   */\n  Array<te::Tensor> ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                                    te::Schedule* schedule) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                          te::Schedule* schedule) const;\n\n  static constexpr const char* record_prefix_str = \"CHW\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.CacheWriteStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CacheWriteStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to CacheWriteStepNode.\n * \\sa CacheWriteStepNode\n */\nclass CacheWriteStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be cache_write.\n   * \\param scope_name The scope name of the newly added stage.\n   */\n  CacheWriteStep(int stage_id, String scope_name);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit CacheWriteStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CacheWriteStep, Step, CacheWriteStepNode);\n};\n\n/*! \\brief Reduction factor step that corresponds to te::Schedule::rfactor */\nclass RfactorStepNode : public StepNode {\n public:\n  /*! \\brief The index of the iterator to be factored. */\n  int iter_id;\n  /*! \\brief The position where the new iterator is placed. */\n  int factor_iter_id;\n\n  void WriteToRecord(dmlc::JSONWriter* writer) const final;\n\n  /*!\n   * \\brief Apply the current step to State.\n   * \\param state A mutable pointer to State, which will be updated.\n   * \\param dag The original ComputeDAG of this state.\n   * \\return The index of the new added stage.\n   */\n  int ApplyToState(State* state, const ComputeDAG& dag) const;\n\n  /*!\n   * \\brief Apply the current step to tvm.schedule.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return The output Tensors of the new added stage.\n   */\n  Array<te::Tensor> ApplyToSchedule(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                                    te::Schedule* schedule) const;\n\n  /*!\n   * \\brief Print the current step as equivalent python schedule API.\n   * \\param stages The list of current stages\n   * \\param stage_to_axes A map that maps stage ot all its iterators.\n   * \\param schedule A mutable pointer to a te::Schedule.\n   * \\return Python schedule code.\n   */\n  String PrintAsPythonAPI(Array<te::Stage>* stages, StageToAxesMap* stage_to_axes,\n                          te::Schedule* schedule) const;\n\n  static constexpr const char* record_prefix_str = \"RF\";\n\n  static constexpr const char* _type_key = \"auto_scheduler.RfactorStep\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RfactorStepNode, StepNode);\n};\n\n/*!\n * \\brief Managed reference to RfactorStepNode.\n * \\sa RfactorStepNode\n */\nclass RfactorStep : public Step {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param stage_id The index of the stage to be factored.\n   * \\param iter_id The index of the iterator to be factored.\n   * \\param factor_iter_id The position where the new iterator is placed.\n   */\n  RfactorStep(int stage_id, int iter_id, int factor_iter_id);\n\n  /*!\n   * \\brief The constructor used to read a step record from JSONReader and create the\n   * corresponding step.\n   * \\param reader The input JSONReader.\n   */\n  explicit RfactorStep(dmlc::JSONReader* reader);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(RfactorStep, Step, RfactorStepNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_TRANSFORM_STEP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/driver/driver_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/driver/driver_api.h\n * \\brief Compiler driver APIs to drive the compilation.\n *\n * This module provides end-to-end utils to drive the compilation process.\n * We adopt the term \"compiler driver\" in common compiler infrastructures.\n * Note that a compiler driver is different from \"runtime drivers\".\n * Most of runtime related code are defined in the runtime folder instead.\n */\n#ifndef TVM_DRIVER_DRIVER_API_H_\n#define TVM_DRIVER_DRIVER_API_H_\n\n#include <tvm/ir/global_var_supply.h>\n#include <tvm/ir/module.h>\n#include <tvm/ir/transform.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/support/with.h>\n#include <tvm/target/target.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/tir/function.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nusing tvm::transform::Pass;\n\n/*!\n * \\brief Configures and returns the composite Pass for the fused module (pre split) that contains\n * device and host code.\n * \\param mixed_mod The original mixed module.\n * \\param target The device Target.\n * \\return The composite Pass for the fused module.\n//  */\nTVM_DLL transform::Sequential MixedModulePassManager(IRModule mixed_mod, Target target);\n\n/*!\n * \\brief Configures and returns the composite Pass for the device Target after device/host from\n * mixed module.\n * \\param mixed_mod The optimized mixed module.\n * \\param target The device Target.\n * \\return The composite Pass for the device module.\n */\nTVM_DLL transform::Sequential DeviceModulePassManager(IRModule mixed_mod, Target target);\n\n/*!\n * \\brief Configures and returns the composite Pass for the host Target after device/host from mixed\n * module.\n * \\param mixed_mod The optimized mixed module.\n * \\param target_host The host Target.\n * \\return The composite Pass for the host module.\n */\nTVM_DLL transform::Sequential HostModulePassManager(IRModule mixed_mod, Target target_host);\n\n/*!\n * \\brief Lower an IRModule (optimize with it with the pass list defined in CreatePassList)\n * \\param mod The IRmodule to lower\n * \\param simple_mode Disables the loop partition pass. Defaults to false.\n * \\return The result module.\n */\nTVM_DLL IRModule LowerModule(IRModule mod, bool simple_mode = false);\n\n/*!\n * \\brief Lower a primfunc and name (convert to IRModule, and optimize it with the pass list\n * defined in CreatePassList)\n * \\param func The PrimFunc to lower\n * \\param name The name of the lowered function.\n * \\param simple_mode Disables the loop partition pass. Defaults to false.\n * \\return The result module.\n */\nTVM_DLL IRModule LowerPrimFunc(tvm::tir::PrimFunc func, const std::string& name,\n                               bool simple_mode = false);\n\n/*!\n * \\brief Build an IRModule given a TE schedule, args and binds. This function also applies\n * the lowering passes defined in CreatePassList.\n * \\param sch The TE schedule to lower.\n * \\param args The arguments to the function.\n * \\param name The name of the lowered function.\n * \\param binds Buffer assignments.\n * \\param global_var_supply The GlobalVarSupply to be used in the module.\n * \\param simple_mode Disables the loop partition pass. Defaults to false.\n * \\return The result module.\n */\n\nTVM_DLL IRModule LowerSchedule(te::Schedule sch, const Array<te::Tensor>& args,\n                               const std::string& name,\n                               const std::unordered_map<te::Tensor, tir::Buffer>& binds,\n                               GlobalVarSupply global_var_supply, bool simple_mode = false);\n\n/*!\n * \\brief Build an IRModule given a TE schedule, args and binds. This function also applies\n * the lowering passes defined in CreatePassList.\n * \\param sch The TE schedule to lower.\n * \\param args The arguments to the function (Array of Tensor, Buffer and Vars)\n * \\param name The name of the lowered function.\n * \\param binds Buffer assignments.\n * \\param global_var_supply The GlobalVarSupply to be used in the module.\n * \\param simple_mode Disables the loop partition pass. Defaults to false.\n * \\return The result module.\n */\nTVM_DLL IRModule LowerSchedule(te::Schedule sch, const Array<ObjectRef>& args,\n                               const std::string& name,\n                               const std::unordered_map<te::Tensor, tir::Buffer>& binds,\n                               GlobalVarSupply global_var_supply, bool simple_mode = false);\n\n/*!\n * \\brief Create an IRModule out of a TE Schedule. It does not apply lowering passes. If you want\n * to apply lowering passes as well, use LowerSchedule.\n * \\param sch The schedule\n * \\param args The arguments to the function.\n * \\param name The name of the lowered function.\n * \\param binds Buffer assignments.\n * \\param global_var_supply The GlobalVarSupply to be used in the module and when creating\n * GlobalVars.\n * \\return The result module.\n */\nIRModule ScheduleToModule(te::Schedule sch, const Array<ObjectRef>& args, const std::string& name,\n                          const std::unordered_map<te::Tensor, tir::Buffer>& binds,\n                          GlobalVarSupply global_var_supply);\n/*!\n * \\brief Build a device and host module for a specific target from an IRModule.\n * \\param funcs The functions to be built.\n * \\param target The target device to build for.\n * \\param target_host The target for building host code. To use the default, pass Target()\n * \\return The built module.\n */\nTVM_DLL runtime::Module build(const IRModule& funcs, const Target& target,\n                              const Target& target_host);\n\n/*!\n * \\brief Build a device and host module for a specific target from a map\n * contains target to IRModule. This function is used\n * for heterogeneous build.\n * \\param input The map contains target to an IRModule.\n * \\param target_host The target for building host code. To use the default,\n *        pass Target().\n * \\return The built module that contains code for different processors.\n */\nTVM_DLL runtime::Module build(const Map<Target, IRModule>& input, const Target& target_host);\n\n/*!\n * \\brief Build a device and host module for a specific target from a map\n * contains target to IRModule. This function is used\n * for heterogeneous build.\n * \\param input The map contains target string to an  IRModule.\n * \\param target_host The target for building host code. To use the default,\n *        pass Target().\n * \\return The built module that contains code for different processors.\n */\nTVM_DLL runtime::Module build(const Map<String, IRModule>& input, const Target& target_host);\n}  // namespace tvm\n\n#endif  // TVM_DRIVER_DRIVER_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/adt.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/adt.h\n * \\brief Algebraic data type definitions.\n *\n * We adopt relay's ADT definition as a unified class\n * for decripting structured data.\n */\n#ifndef TVM_IR_ADT_H_\n#define TVM_IR_ADT_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/container/adt.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief ADT constructor.\n * Constructors compare by pointer equality.\n * \\sa Constructor\n */\nclass ConstructorNode : public RelayExprNode {\n public:\n  /*! \\brief The name (only a hint) */\n  String name_hint;\n  /*! \\brief Input to the constructor. */\n  Array<Type> inputs;\n  /*! \\brief The datatype the constructor will construct. */\n  GlobalTypeVar belong_to;\n  /*! \\brief Index in the table of constructors (set when the type is registered). */\n  mutable int32_t tag = -1;\n\n  ConstructorNode() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"belong_to\", &belong_to);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const ConstructorNode* other, SEqualReducer equal) const {\n    // Use namehint for now to be consistent with the legacy relay impl\n    // TODO(tvm-team) revisit, need to check the type var.\n    return equal(name_hint, other->name_hint) && equal(inputs, other->inputs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name_hint);\n    hash_reduce(inputs);\n  }\n\n  static constexpr const char* _type_key = \"relay.Constructor\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstructorNode, RelayExprNode);\n};\n\n/*!\n * \\brief Managed reference to ConstructorNode\n * \\sa ConstructorNode\n */\nclass Constructor : public RelayExpr {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param name_hint the name of the constructor.\n   * \\param inputs The input types.\n   * \\param belong_to The data type var the constructor will construct.\n   */\n  TVM_DLL Constructor(String name_hint, Array<Type> inputs, GlobalTypeVar belong_to);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Constructor, RelayExpr, ConstructorNode);\n};\n\n/*! \\brief TypeData container node */\nclass TypeDataNode : public TypeNode {\n public:\n  /*!\n   * \\brief The header is simply the name of the ADT.\n   * We adopt nominal typing for ADT definitions;\n   * that is, differently-named ADT definitions with same constructors\n   * have different types.\n   */\n  GlobalTypeVar header;\n  /*! \\brief The type variables (to allow for polymorphism). */\n  Array<TypeVar> type_vars;\n  /*! \\brief The constructors. */\n  Array<Constructor> constructors;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"header\", &header);\n    v->Visit(\"type_vars\", &type_vars);\n    v->Visit(\"constructors\", &constructors);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TypeDataNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(header, other->header) && equal.DefEqual(type_vars, other->type_vars) &&\n           equal(constructors, other->constructors);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(header);\n    hash_reduce.DefHash(type_vars);\n    hash_reduce(constructors);\n  }\n\n  static constexpr const char* _type_key = \"relay.TypeData\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypeDataNode, TypeNode);\n};\n\n/*!\n * \\brief Stores all data for an Algebraic Data Type (ADT).\n *\n * In particular, it stores the handle (global type var) for an ADT\n * and the constructors used to build it and is kept in the module. Note\n * that type parameters are also indicated in the type data: this means that\n * for any instance of an ADT, the type parameters must be indicated. That is,\n * an ADT definition is treated as a type-level function, so an ADT handle\n * must be wrapped in a TypeCall node that instantiates the type-level arguments.\n * The kind checker enforces this.\n */\nclass TypeData : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param header the name of ADT.\n   * \\param type_vars type variables.\n   * \\param constructors constructors field.\n   */\n  TVM_DLL TypeData(GlobalTypeVar header, Array<TypeVar> type_vars, Array<Constructor> constructors);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TypeData, Type, TypeDataNode);\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_ADT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/affine_type.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/affine_type.h\n * \\brief Quantized Tensor Types.\n */\n#ifndef TVM_IR_AFFINE_TYPE_H_\n#define TVM_IR_AFFINE_TYPE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n\nnamespace tvm {\n\n/*!\n * \\brief AffineType representation\n * \\sa AffineType\n */\nclass AffineTypeNode : public Object {\n public:\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  static constexpr const char* _type_key = \"AffineType\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_BASE_OBJECT_INFO(AffineTypeNode, Object);\n};\n\n/*!\n * \\brief Managed reference to AffineTypeNode.\n * \\sa AffineTypeNode\n */\nclass AffineType : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(AffineType, ObjectRef, AffineTypeNode);\n};\n\n/*!\n * \\brief TensorAffineType representation\n * \\sa TensorAffineType\n *\n *  This Type represents a quantized integer tensor that can be converted\n *  back to real space via the x_real = scale * (x_quant - zero_point)\n */\nclass TensorAffineTypeNode : public AffineTypeNode {\n public:\n  /*! \\brief The scale of this type */\n  RelayExpr scale;\n  /*! \\brief The zero point of this type */\n  RelayExpr zero_point;\n  /*! \\brief The data type of this type */\n  DataType dtype;\n  /*! \\brief The axis for per-channel quantization */\n  int axis;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"scale\", &scale);\n    v->Visit(\"zero_point\", &zero_point);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"axis\", &axis);\n  }\n\n  bool SEqualReduce(const TensorAffineTypeNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(scale, other->scale) && equal(zero_point, other->zero_point) &&\n           equal(dtype, other->dtype) && equal(axis, other->axis);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(scale);\n    hash_reduce(zero_point);\n    hash_reduce(dtype);\n    hash_reduce(axis);\n  }\n\n  static constexpr const char* _type_key = \"TensorAffineType\";\n  TVM_DECLARE_BASE_OBJECT_INFO(TensorAffineTypeNode, AffineTypeNode);\n};\n\n/*!\n * \\brief Managed reference to AffineTypes.\n * \\sa AffineTypeNode\n */\nclass TensorAffineType : public AffineType {\n public:\n  TVM_DLL TensorAffineType(RelayExpr scale, RelayExpr zero_point, DataType dtype, int axis);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorAffineType, AffineType, TensorAffineTypeNode);\n};\n\n/*!\n * \\brief TupleAffineType representation\n * \\sa TupleAffineType\n */\nclass TupleAffineTypeNode : public AffineTypeNode {\n public:\n  /*! \\brief The types of this tuple*/\n  Array<TensorAffineType> types;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"types\", &types); }\n\n  bool SEqualReduce(const TupleAffineTypeNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(types, other->types);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(types);\n  }\n\n  static constexpr const char* _type_key = \"TupleAffineType\";\n  TVM_DECLARE_BASE_OBJECT_INFO(TupleAffineTypeNode, AffineTypeNode);\n};\n\n/*!\n * \\brief Managed reference to TupleAffineTypes.\n * \\sa TupleAffineType\n */\nclass TupleAffineType : public AffineType {\n public:\n  TVM_DLL TupleAffineType(Array<TensorAffineType> types);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleAffineType, AffineType, TupleAffineTypeNode);\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_AFFINE_TYPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/attrs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/ir/attrs.h\n * \\brief Helpers for attribute objects.\n *\n *  This module enables declaration of named attributes\n *  which support default value setup and bound checking.\n *\n * \\code\n *   struct MyAttrs : public tvm::AttrsNode<MyAttrs> {\n *     float learning_rate;\n *     int num_hidden;\n *     String name;\n *     // declare attribute fields in header file\n *     TVM_DECLARE_ATTRS(MyAttrs, \"attrs.MyAttrs\") {\n *       TVM_ATTR_FIELD(num_hidden).set_lower_bound(1);\n *       TVM_ATTR_FIELD(learning_rate).set_default(0.01f);\n *       TVM_ATTR_FIELD(name).set_default(\"hello\");\n *     }\n *   };\n *   // register it in cc file\n *   TVM_REGISTER_NODE_TYPE(MyAttrs);\n * \\endcode\n *\n * \\sa AttrsNode, TVM_DECLARE_ATTRS, TVM_ATTR_FIELD\n */\n#ifndef TVM_IR_ATTRS_H_\n#define TVM_IR_ATTRS_H_\n\n#include <dmlc/common.h>\n#include <tvm/ir/expr.h>\n#include <tvm/node/structural_equal.h>\n#include <tvm/node/structural_hash.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <functional>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n/*!\n * \\brief Declare an attribute function.\n * \\param ClassName The name of the class.\n * \\param TypeKey The type key to be used by the TVM node system.\n */\n#define TVM_DECLARE_ATTRS(ClassName, TypeKey)                    \\\n  static constexpr const char* _type_key = TypeKey;              \\\n  TVM_DECLARE_FINAL_OBJECT_INFO(ClassName, ::tvm::BaseAttrsNode) \\\n  template <typename FVisit>                                     \\\n  void _tvm_VisitAttrs(FVisit& _tvm_fvisit)  // NOLINT(*)\n\n/*!\n * \\brief Declare an attribute field.\n * \\param FieldName The field name.\n */\n#define TVM_ATTR_FIELD(FieldName) _tvm_fvisit(#FieldName, &FieldName)\n\n/*!\n * \\brief Create a NodeRef type that represents null.\n * \\tparam TNodeRef the type to be created.\n * \\return A instance that will represent None.\n */\ntemplate <typename TObjectRef>\ninline TObjectRef NullValue() {\n  static_assert(TObjectRef::_type_is_nullable, \"Can only get NullValue for nullable types\");\n  return TObjectRef(ObjectPtr<Object>(nullptr));\n}\n\ntemplate <>\ninline DataType NullValue<DataType>() {\n  return DataType(DataType::kHandle, 0, 0);\n}\n\n/*! \\brief Error thrown during attribute checking. */\nstruct AttrError : public Error {\n  /*!\n   * \\brief constructor\n   * \\param msg error message\n   */\n  explicit AttrError(std::string msg) : Error(\"AttributeError:\" + msg) {}\n};\n\n/*!\n * \\brief Information about attribute fields in string representations.\n */\nclass AttrFieldInfoNode : public Object {\n public:\n  /*! \\brief name of the field */\n  String name;\n  /*! \\brief type docstring information in str. */\n  String type_info;\n  /*! \\brief detailed description of the type */\n  String description;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"type_info\", &type_info);\n    v->Visit(\"description\", &description);\n  }\n\n  static constexpr const char* _type_key = \"AttrFieldInfo\";\n  static constexpr bool _type_has_method_sequal_reduce = false;\n  static constexpr bool _type_has_method_shash_reduce = false;\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttrFieldInfoNode, Object);\n};\n\n/*! \\brief AttrFieldInfo */\nclass AttrFieldInfo : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(AttrFieldInfo, ObjectRef, AttrFieldInfoNode);\n};\n\n/*!\n * \\brief Base class of all attribute class\n * \\note Do not subclass AttrBaseNode directly,\n *       subclass AttrsNode instead.\n * \\sa AttrsNode\n */\nclass BaseAttrsNode : public Object {\n public:\n  using TVMArgs = runtime::TVMArgs;\n  using TVMRetValue = runtime::TVMRetValue;\n  /*! \\brief virtual destructor */\n  virtual ~BaseAttrsNode() {}\n  // visit function\n  virtual void VisitAttrs(AttrVisitor* v) {}\n  /*!\n   * \\brief Initialize the attributes by sequence of arguments\n   * \\param args The positional arguments in the form\n   *        [key0, value0, key1, value1, ..., key_n, value_n]\n   */\n  template <typename... Args>\n  inline void InitBySeq(Args&&... args);\n  /*!\n   * \\brief Print readible docstring to ostream, add newline.\n   * \\param os the stream to print the docstring to.\n   */\n  inline void PrintDocString(std::ostream& os) const;  // NOLINT(*)\n  /*!\n   * \\brief Visit attributes that do not equal the default value.\n   *\n   * \\note This is useful to extract fields for concise printing.\n   * \\param v The visitor\n   */\n  TVM_DLL virtual void VisitNonDefaultAttrs(AttrVisitor* v) = 0;\n  /*!\n   * \\brief Get the field information\n   * \\return The fields in the Attrs.\n   */\n  TVM_DLL virtual Array<AttrFieldInfo> ListFieldInfo() const = 0;\n  /*!\n   * \\brief Initialize the attributes by arguments.\n   * \\param kwargs The key value pairs for initialization.\n   *        [key0, value0, key1, value1, ..., key_n, value_n]\n   * \\param allow_unknown Whether allow additional unknown fields.\n   * \\note This function throws when the required field is not present.\n   */\n  TVM_DLL virtual void InitByPackedArgs(const TVMArgs& kwargs, bool allow_unknown = false) = 0;\n\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  static constexpr const char* _type_key = \"Attrs\";\n  TVM_DECLARE_BASE_OBJECT_INFO(BaseAttrsNode, Object);\n};\n\n/*!\n * \\brief Managed reference to BaseAttrsNode.\n * \\sa AttrsNode, BaseAttrsNode\n */\nclass Attrs : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(Attrs, ObjectRef, BaseAttrsNode);\n};\n\n/*!\n * \\brief Specialized attribute type that is backed by a map.\n *  The DictAttrsNode implements the Attrs behavior,\n *  its fields are directly accessible via object.field_name\n *  like other normal nodes.\n */\nclass DictAttrsNode : public BaseAttrsNode {\n public:\n  /*! \\brief internal attrs map */\n  Map<String, ObjectRef> dict;\n\n  bool SEqualReduce(const DictAttrsNode* other, SEqualReducer equal) const {\n    return equal(dict, other->dict);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(dict); }\n\n  // implementations\n  void VisitAttrs(AttrVisitor* v) final;\n  void VisitNonDefaultAttrs(AttrVisitor* v) final;\n  void InitByPackedArgs(const runtime::TVMArgs& args, bool allow_unknown) final;\n  Array<AttrFieldInfo> ListFieldInfo() const final;\n\n  // type info\n  static constexpr const char* _type_key = \"DictAttrs\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DictAttrsNode, BaseAttrsNode);\n};\n\n/*!\n * \\brief Managed reference to DictAttrsNode\n * \\sa DictAttrsNode.\n */\nclass DictAttrs : public Attrs {\n public:\n  /*!\n   * \\brief Consruct a Attrs backed by DictAttrsNode.\n   * \\param dict The attributes.\n   * \\return The dict attributes.\n   */\n  TVM_DLL explicit DictAttrs(Map<String, ObjectRef> dict);\n\n  // Utils for accessing attributes\n  // This needs to be on DictAttrs, not DictAttrsNode because we return the default\n  // value if DictAttrsNode is not defined.\n  /*!\n   * \\brief Get a function attribute.\n   *\n   * \\param attr_key The attribute key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TOBjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetAttrExample(const BaseFunc& f) {\n   *    auto value = f->attrs.GetAttr<Integer>(\"AttrKey\", 0);\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    static_assert(std::is_base_of<ObjectRef, TObjectRef>::value,\n                  \"Can only call GetAttr with ObjectRef types.\");\n    if (!defined()) return default_value;\n    const DictAttrsNode* node = this->as<DictAttrsNode>();\n\n    auto it = node->dict.find(attr_key);\n    if (it != node->dict.end()) {\n      return Downcast<Optional<TObjectRef>>((*it).second);\n    } else {\n      return default_value;\n    }\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n  /*!\n   * \\brief Check whether the function has an non-zero integer attr.\n   *\n   * This function can be used to check whether an optional\n   * attribute mark(e.g. inline) exists.\n   *\n   * \\param attr_key The key to the attribute.\n   * \\return The check result.\n   *\n   * \\code\n   *\n   *  void HasNonzeroAttrExample(const BaseFunc& f) {\n   *    if (f->HasNonzeroAttr(attr::kInline)) {\n   *      // inline the function.\n   *    }\n   *  }\n   *\n   * \\endcode\n   */\n  bool HasNonzeroAttr(const std::string& attr_key) const {\n    return GetAttr<Integer>(attr_key, 0).value_or(0).IntValue() != 0;\n  }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(DictAttrs, Attrs, DictAttrsNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(DictAttrsNode);\n};\n\n/*!\n * \\brief Create an Attr object with all default values.\n * \\tparam TAttrNode the type to be created.\n * \\return A instance that will represent None.\n */\ntemplate <typename TAttrs>\ninline TAttrs AttrsWithDefaultValues() {\n  static_assert(std::is_base_of<Attrs, TAttrs>::value, \"Can only take attr nodes\");\n  auto n = make_object<typename TAttrs::ContainerType>();\n  n->InitByPackedArgs(runtime::TVMArgs(nullptr, nullptr, 0), false);\n  return TAttrs(n);\n}\n\n/*!\n * \\brief Copy the function or module, but overrides\n *        the attribute value key with the value.\n *\n * \\param input The thing to annotate (BaseFunc or IRModule)\n * \\param attr_key The attribute key.\n * \\param attr_value The value attribute value.\n *\n * \\tparam TFunc The corresponding function or module type.\n *\n * \\returns The new function or module with updated attributes.\n *\n * \\note This function performs copy on write optimization for func and module.\n *       If we move a uniquely referenced func or module into WithAttr,\n *       then no additional copy will be performed.\n *\n *       This is also why we make it as a function instead of a member function\n *       and why we pass by value in the first argument.\n *\n * \\code\n *\n *  // Recommended way to trigger copy on write\n *  func = WithAttr(std::move(func), \"key1\", value1);\n *  func = WithAttr(std::move(func), \"key2\", value2);\n *\n * \\endcode\n */\ntemplate <typename TFunc>\ninline TFunc WithAttr(TFunc input, const std::string& attr_key, ObjectRef attr_value) {\n  using TNode = typename TFunc::ContainerType;\n  static_assert(TNode::_type_final, \"Can only operate on the leaf nodes\");\n  TNode* node = input.CopyOnWrite();\n  if (node->attrs.defined()) {\n    node->attrs.CopyOnWrite()->dict.Set(attr_key, attr_value);\n  } else {\n    Map<String, ObjectRef> dict = {{attr_key, attr_value}};\n    node->attrs = DictAttrs(dict);\n  }\n  return input;\n}\n\n/*!\n * \\brief Copy the function or module, but overrides the attributes with the entries from \\p attrs.\n *\n * \\param input The thing to annotate (BaseFunc or IRModule)\n * \\param attrs Key/values attributes to add to \\p input.\n *\n * \\tparam TFunc The corresponding function or module type.\n *\n * \\returns The new function or module with updated attributes.\n */\ntemplate <typename TFunc>\ninline TFunc WithAttrs(TFunc input, Map<String, ObjectRef> attrs) {\n  using TNode = typename TFunc::ContainerType;\n  static_assert(TNode::_type_final, \"Can only operate on the leaf nodes\");\n  TNode* node = input.CopyOnWrite();\n  if (node->attrs.defined()) {\n    for (const auto& pair : attrs) {\n      node->attrs.CopyOnWrite()->dict.Set(pair.first, pair.second);\n    }\n  } else {\n    node->attrs = DictAttrs(std::move(attrs));\n  }\n  return input;\n}\n\n/*!\n * \\brief Copy the function or module, but removes the specified\n *        attribute.\n *\n * \\param input The thing to annotate (BaseFunc or IRModule)\n * \\param attr_key The attribute key.\n *\n * \\tparam TFunc The corresponding function or module type.\n *\n * \\returns The new function or module with removed attribute.\n *\n * \\note This function performs copy on write optimization for func and module.\n *       If we move a uniquely referenced func or module into WithoutAttr,\n *       then no additional copy will be performed.\n *\n *       This is also why we make it as a function instead of a member function\n *       and why we pass by value in the first argument.\n *\n * \\code\n *\n *  // Recommended way to trigger copy on write\n *  func = WithoutAttr(std::move(func), \"key1\");\n *  func = WithoutAttr(std::move(func), \"key2\");\n *\n * \\endcode\n */\ntemplate <typename TFunc>\ninline TFunc WithoutAttr(TFunc input, const std::string& attr_key) {\n  using TNode = typename TFunc::ContainerType;\n  static_assert(TNode::_type_final, \"Can only operate on the leaf nodes\");\n\n  if (input->attrs.defined()) {\n    TNode* node = input.CopyOnWrite();\n    node->attrs.CopyOnWrite()->dict.erase(attr_key);\n    if (node->attrs->dict.size() == 0) {\n      node->attrs = NullValue<DictAttrs>();\n    }\n  }\n  return input;\n}\n\n// Namespace containing detail implementations\nnamespace detail {\nusing runtime::TVMArgValue;\n\n// helper entry that does nothing in set_default/bound/describe calls.\nstruct AttrNopEntry {\n  using TSelf = AttrNopEntry;\n\n  TSelf& describe(DMLC_ATTRIBUTE_UNUSED const char* str) { return *this; }\n  template <typename T>\n  TSelf& set_default(DMLC_ATTRIBUTE_UNUSED const T& value) {\n    return *this;\n  }\n  template <typename T>\n  TSelf& set_lower_bound(DMLC_ATTRIBUTE_UNUSED const T& begin) {\n    return *this;\n  }\n  template <typename T>\n  TSelf& set_upper_bound(DMLC_ATTRIBUTE_UNUSED const T& end) {\n    return *this;\n  }\n};\n\n// Wrapper for normal visitor.\nclass AttrNormalVisitor {\n public:\n  explicit AttrNormalVisitor(AttrVisitor* visitor) : visitor_(visitor) {}\n  template <typename T>\n  AttrNopEntry operator()(const char* key, T* value) {\n    visitor_->Visit(key, value);\n    return AttrNopEntry();\n  }\n\n private:\n  AttrVisitor* visitor_;\n};\n\nclass AttrsSEqualVisitor {\n public:\n  bool result_{true};\n  // constructor\n  AttrsSEqualVisitor(const Object* lhs, const Object* rhs, const SEqualReducer& equal)\n      : lhs_(lhs), rhs_(rhs), equal_(equal) {}\n  template <typename T>\n  AttrNopEntry operator()(const char* key, T* lhs_value) {\n    if (!result_) return AttrNopEntry();\n    const T* rhs_value = reinterpret_cast<const T*>(\n        reinterpret_cast<const char*>(rhs_) +\n        (reinterpret_cast<const char*>(lhs_value) - reinterpret_cast<const char*>(lhs_)));\n    if (!equal_(*lhs_value, *rhs_value)) {\n      result_ = false;\n    }\n    return AttrNopEntry();\n  }\n\n private:\n  const Object* lhs_;\n  const Object* rhs_;\n  const SEqualReducer& equal_;\n};\n\nclass AttrsSHashVisitor {\n public:\n  explicit AttrsSHashVisitor(const SHashReducer& hash_reducer) : hash_reducer_(hash_reducer) {}\n\n  template <typename T>\n  AttrNopEntry operator()(const char* key, T* value) {\n    hash_reducer_(*value);\n    return AttrNopEntry();\n  }\n\n private:\n  const SHashReducer& hash_reducer_;\n};\n\n// helper entry that does initialization, set default.\ntemplate <typename T>\nstruct AttrInitEntry {\n  // The attributes\n  using TSelf = AttrInitEntry<T>;\n  // The type key\n  const char* type_key_;\n  // field name\n  const char* key_;\n  // internal value.\n  T* value_;\n  // whether the value is missing.\n  // NOTE: initialize to false so that the destructor does not throw unless\n  // AttrInitVisitor::operator() is committed to returning an instance of this class.\n  // It is expected not to set this to true until that is true.\n  bool value_missing_{false};\n\n  AttrInitEntry() = default;\n\n  AttrInitEntry(AttrInitEntry&& other) {\n    type_key_ = other.type_key_;\n    key_ = other.key_;\n    value_ = other.value_;\n    value_missing_ = other.value_missing_;\n    // avoid unexpected throw\n    other.value_missing_ = false;\n  }\n\n  // If the value is still missing in destruction time throw an error.\n  ~AttrInitEntry() DMLC_THROW_EXCEPTION {\n    if (value_missing_) {\n      std::ostringstream os;\n      os << type_key_ << \": Cannot find required field \\'\" << key_ << \"\\' during initialization. \"\n         << \"If the key is defined check that its type matches the declared type.\";\n      throw AttrError(os.str());\n    }\n  }\n  // override fields.\n  // This function sets the lower bound of the attribute\n  TSelf& set_lower_bound(const T& begin) {\n    if (this->value_missing_) return *this;\n    const T& val = *value_;\n    if (begin > val) {\n      std::ostringstream os;\n      os << type_key_ << \".\" << key_ << \": \"\n         << \"value \" << val << \" is smaller than the lower bound \" << begin;\n      throw AttrError(os.str());\n    }\n    return *this;\n  }\n  // This function sets the upper bound of the attribute\n  TSelf& set_upper_bound(const T& end) {\n    if (this->value_missing_) return *this;\n    const T& val = *value_;\n    if (val > end) {\n      std::ostringstream os;\n      os << type_key_ << \".\" << key_ << \": \"\n         << \"value \" << val << \" is bigger than the upper bound \" << end;\n      throw AttrError(os.str());\n    }\n    return *this;\n  }\n  // set default when\n  TSelf& set_default(const T& value) {\n    if (!value_missing_) return *this;\n    *value_ = value;\n    value_missing_ = false;\n    return *this;\n  }\n  TSelf& describe(DMLC_ATTRIBUTE_UNUSED const char* str) { return *this; }\n};\n\n// Template function to allow smart conversion\n// from Expr types into the constants.\ntemplate <typename T>\ninline void SetValue(T* ptr, const TVMArgValue& val) {\n  *ptr = val.operator T();\n}\n\ntemplate <typename T>\ninline void SetIntValue(T* ptr, const TVMArgValue& val) {\n  if (val.type_code() == kDLInt) {\n    *ptr = static_cast<T>(val.value().v_int64);\n  } else {\n    IntImm expr = val;\n    *ptr = static_cast<T>(expr->value);\n  }\n}\n\n// Workaround for GCC8.1 / GCC8.2\ntemplate <>\ninline void SetValue<DataType>(DataType* ptr, const TVMArgValue& val) {\n  *ptr = val.operator DataType();\n}\n\ntemplate <>\ninline void SetValue<std::string>(std::string* ptr, const TVMArgValue& val) {\n  if (String::CanConvertFrom(val)) {\n    *ptr = val.operator std::string();\n  } else {\n    LOG(FATAL) << \"Expect str\";\n  }\n}\n\ntemplate <>\ninline void SetValue<double>(double* ptr, const TVMArgValue& val) {\n  if (val.type_code() == kDLFloat || val.type_code() == kDLInt) {\n    *ptr = val.operator double();\n  } else {\n    ObjectRef expr = val;\n    ICHECK(expr.defined());\n    if (const IntImmNode* op = expr.as<IntImmNode>()) {\n      *ptr = static_cast<double>(op->value);\n    } else if (const FloatImmNode* op = expr.as<FloatImmNode>()) {\n      *ptr = static_cast<double>(op->value);\n    } else {\n      LOG(FATAL) << \"Expect float value, but get \" << expr->GetTypeKey();\n    }\n  }\n}\ntemplate <>\ninline void SetValue<int>(int* ptr, const TVMArgValue& val) {\n  SetIntValue(ptr, val);\n}\ntemplate <>\ninline void SetValue<int64_t>(int64_t* ptr, const TVMArgValue& val) {\n  SetIntValue(ptr, val);\n}\ntemplate <>\ninline void SetValue<uint64_t>(uint64_t* ptr, const TVMArgValue& val) {\n  SetIntValue(ptr, val);\n}\ntemplate <>\ninline void SetValue<bool>(bool* ptr, const TVMArgValue& val) {\n  SetIntValue(ptr, val);\n}\n\n// Visitor for value initialization\ntemplate <typename FFind>\nclass AttrInitVisitor {\n public:\n  // Counter of number of matched attributes during visit.\n  // This is used to decide if there is additional unmatched attributes.\n  size_t hit_count_{0};\n  // constructor\n  AttrInitVisitor(const char* type_key, FFind ffind) : type_key_(type_key), ffind_(ffind) {}\n\n  template <typename T>\n  AttrInitEntry<T> operator()(const char* key, T* value) {\n    TVMArgValue val;\n    AttrInitEntry<T> opt;\n    opt.type_key_ = type_key_;\n    opt.key_ = key;\n    opt.value_ = value;\n    if (ffind_(key, &val)) {\n      SetValue(value, val);\n      opt.value_missing_ = false;\n      ++hit_count_;\n    } else {\n      opt.value_missing_ = true;\n    }\n#if defined(__GNUC__)\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#pragma GCC diagnostic ignored \"-Wpessimizing-move\"\n#endif\n    return std::move(opt);\n  }\n\n private:\n  // the type key\n  const char* type_key_;\n  FFind ffind_;\n};\n\ntemplate <typename FFind>\ninline AttrInitVisitor<FFind> CreateInitVisitor(const char* type_key, FFind ffind) {\n  return AttrInitVisitor<FFind>(type_key, ffind);\n}\n\n/*!\n * \\brief Helper struct to get the type name known to tvm.\n * \\tparam T the type we are interested in.\n */\ntemplate <typename T>\nstruct TypeName {\n  static constexpr const char* value = T::ContainerType::_type_key;\n};\n\ntemplate <>\nstruct TypeName<int> {\n  static constexpr const char* value = \"int\";\n};\n\ntemplate <>\nstruct TypeName<int64_t> {\n  static constexpr const char* value = \"int64\";\n};\n\ntemplate <>\nstruct TypeName<uint64_t> {\n  static constexpr const char* value = \"uint64_t\";\n};\n\ntemplate <>\nstruct TypeName<DataType> {\n  static constexpr const char* value = \"DataType\";\n};\n\ntemplate <>\nstruct TypeName<std::string> {\n  static constexpr const char* value = \"str\";\n};\n\ntemplate <>\nstruct TypeName<bool> {\n  static constexpr const char* value = \"bool\";\n};\n\ntemplate <>\nstruct TypeName<void*> {\n  static constexpr const char* value = \"handle\";\n};\n\ntemplate <>\nstruct TypeName<double> {\n  static constexpr const char* value = \"double\";\n};\n\nclass AttrDocEntry {\n public:\n  using TSelf = AttrDocEntry;\n\n  explicit AttrDocEntry(ObjectPtr<AttrFieldInfoNode> info) : info_(info) {}\n  TSelf& describe(const char* str) {\n    info_->description = str;\n    return *this;\n  }\n  template <typename T>\n  TSelf& set_default(const T& value) {\n    std::ostringstream os;\n    os << info_->type_info << \", default=\" << value;\n    info_->type_info = os.str();\n    return *this;\n  }\n  template <typename T>\n  TSelf& set_lower_bound(DMLC_ATTRIBUTE_UNUSED T begin) {\n    return *this;\n  }\n  template <typename T>\n  TSelf& set_upper_bound(DMLC_ATTRIBUTE_UNUSED T end) {\n    return *this;\n  }\n\n private:\n  ObjectPtr<AttrFieldInfoNode> info_;\n};\n\nclass AttrDocVisitor {\n public:\n  template <typename T>\n  AttrDocEntry operator()(const char* key, T* v) {\n    ObjectPtr<AttrFieldInfoNode> info = make_object<AttrFieldInfoNode>();\n    info->name = key;\n    info->type_info = TypeName<T>::value;\n    fields_.push_back(AttrFieldInfo(info));\n    return AttrDocEntry(info);\n  }\n\n  Array<AttrFieldInfo> fields_;\n};\n\nclass AttrExistVisitor {\n public:\n  std::string key_;\n  bool exist_{false};\n\n  template <typename T>\n  AttrNopEntry operator()(const char* key, T* v) {\n    if (exist_) return AttrNopEntry();\n    if (key == key_) exist_ = true;\n    return AttrNopEntry();\n  }\n};\n\ntemplate <typename T>\nstruct AttrTriggerNonDefaultEntry {\n  using TSelf = AttrTriggerNonDefaultEntry<T>;\n  // constructor\n  AttrTriggerNonDefaultEntry(AttrVisitor* visitor, const char* key, T* data)\n      : visitor_(visitor), key_(key), data_(data) {}\n\n  ~AttrTriggerNonDefaultEntry() DMLC_THROW_EXCEPTION {\n    if (trigger_) {\n      visitor_->Visit(key_, data_);\n    }\n  }\n  TSelf& describe(DMLC_ATTRIBUTE_UNUSED const char* str) { return *this; }\n  TSelf& set_default(const T& value) {\n    if (tvm::StructuralEqual()(value, *data_)) {\n      trigger_ = false;\n    }\n    return *this;\n  }\n  TSelf& set_lower_bound(DMLC_ATTRIBUTE_UNUSED const T& begin) { return *this; }\n  TSelf& set_upper_bound(DMLC_ATTRIBUTE_UNUSED const T& end) { return *this; }\n\n private:\n  AttrVisitor* visitor_;\n  const char* key_;\n  T* data_;\n  bool trigger_{true};\n};\n\nclass AttrNonDefaultVisitor {\n public:\n  explicit AttrNonDefaultVisitor(AttrVisitor* visitor) : visitor_(visitor) {}\n  template <typename T>\n  AttrTriggerNonDefaultEntry<T> operator()(const char* key, T* value) {\n    return AttrTriggerNonDefaultEntry<T>(visitor_, key, value);\n  }\n\n private:\n  AttrVisitor* visitor_;\n};\n}  // namespace detail\n\n/*!\n * \\brief The base class of the all the\n *  Use \"curiously recurring template pattern\".\n *\n * \\tparam DerivedType The final attribute type.\n */\ntemplate <typename DerivedType>\nclass AttrsNode : public BaseAttrsNode {\n public:\n  void VisitAttrs(AttrVisitor* v) {\n    ::tvm::detail::AttrNormalVisitor vis(v);\n    self()->_tvm_VisitAttrs(vis);\n  }\n\n  void VisitNonDefaultAttrs(AttrVisitor* v) {\n    ::tvm::detail::AttrNonDefaultVisitor vis(v);\n    self()->_tvm_VisitAttrs(vis);\n  }\n\n  void InitByPackedArgs(const runtime::TVMArgs& args, bool allow_unknown) final {\n    ICHECK_EQ(args.size() % 2, 0);\n    const int kLinearSearchBound = 16;\n    int hit_count = 0;\n    // applies two strategies to lookup\n    if (args.size() < kLinearSearchBound) {\n      // linear search.\n      auto ffind = [&args](const char* key, runtime::TVMArgValue* val) {\n        for (int i = 0; i < args.size(); i += 2) {\n          ICHECK_EQ(args.type_codes[i], kTVMStr);\n          if (!std::strcmp(key, args.values[i].v_str)) {\n            *val = args[i + 1];\n            return true;\n          }\n        }\n        return false;\n      };\n      auto vis = ::tvm::detail::CreateInitVisitor(DerivedType::_type_key, ffind);\n      self()->_tvm_VisitAttrs(vis);\n      hit_count = vis.hit_count_;\n    } else {\n      // construct a map then do lookup.\n      std::unordered_map<std::string, runtime::TVMArgValue> kwargs;\n      for (int i = 0; i < args.size(); i += 2) {\n        ICHECK_EQ(args.type_codes[i], kTVMStr);\n        kwargs[args[i].operator std::string()] = args[i + 1];\n      }\n      auto ffind = [&kwargs](const char* key, runtime::TVMArgValue* val) {\n        auto it = kwargs.find(key);\n        if (it != kwargs.end()) {\n          *val = it->second;\n          return true;\n        }\n        return false;\n      };\n      auto vis = ::tvm::detail::CreateInitVisitor(DerivedType::_type_key, ffind);\n      self()->_tvm_VisitAttrs(vis);\n      hit_count = vis.hit_count_;\n    }\n    // error handling, slow path\n    if (hit_count * 2 != args.size() && !allow_unknown) {\n      for (int i = 0; i < args.size(); i += 2) {\n        ::tvm::detail::AttrExistVisitor visitor;\n        visitor.key_ = args[i].operator std::string();\n        self()->_tvm_VisitAttrs(visitor);\n        if (!visitor.exist_) {\n          std::ostringstream os;\n          os << DerivedType::_type_key << \": does not have field \\'\" << visitor.key_\n             << \"\\', Possible fields:\\n\";\n          os << \"----------------\\n\";\n          this->PrintDocString(os);\n          throw AttrError(os.str());\n        }\n      }\n    }\n  }\n\n  bool SEqualReduce(const DerivedType* other, SEqualReducer equal) const {\n    DerivedType* pself = self();\n    ::tvm::detail::AttrsSEqualVisitor visitor(pself, other, equal);\n    self()->_tvm_VisitAttrs(visitor);\n    return visitor.result_;\n  }\n\n  void SHashReduce(SHashReducer hash_reducer) const {\n    ::tvm::detail::AttrsSHashVisitor visitor(hash_reducer);\n    self()->_tvm_VisitAttrs(visitor);\n  }\n\n  Array<AttrFieldInfo> ListFieldInfo() const final {\n    ::tvm::detail::AttrDocVisitor visitor;\n    self()->_tvm_VisitAttrs(visitor);\n    return visitor.fields_;\n  }\n\n private:\n  DerivedType* self() const {\n    return const_cast<DerivedType*>(static_cast<const DerivedType*>(this));\n  }\n};\n\ntemplate <typename... Args>\ninline void BaseAttrsNode::InitBySeq(Args&&... args) {\n  runtime::PackedFunc pf(\n      [this](const TVMArgs& args, TVMRetValue* rv) { this->InitByPackedArgs(args); });\n  pf(std::forward<Args>(args)...);\n}\n\ninline void BaseAttrsNode::PrintDocString(std::ostream& os) const {  // NOLINT(*)\n  Array<AttrFieldInfo> entry = this->ListFieldInfo();\n  for (AttrFieldInfo info : entry) {\n    os << info->name << \" : \" << info->type_info << '\\n';\n    if (info->description.length() != 0) {\n      os << \"    \" << info->description << '\\n';\n    }\n  }\n}\n\n}  // namespace tvm\n#endif  // TVM_IR_ATTRS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/diagnostic.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file diagnostic.h\n * \\brief A new diagnostic interface for TVM error reporting.\n *\n */\n\n#ifndef TVM_IR_DIAGNOSTIC_H_\n#define TVM_IR_DIAGNOSTIC_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/parser/source_map.h>\n\n#include <sstream>\n#include <string>\n\nnamespace tvm {\n\nusing tvm::parser::SourceMap;\nusing tvm::runtime::TypedPackedFunc;\n\n/*! \\brief The diagnostic level, controls the printing of the message. */\nenum class DiagnosticLevel : int {\n  kBug = 10,\n  kError = 20,\n  kWarning = 30,\n  kNote = 40,\n  kHelp = 50,\n};\n\nclass DiagnosticBuilder;\n\n/*! \\brief A compiler diagnostic. */\nclass Diagnostic;\n\n/*! \\brief A compiler diagnostic message. */\nclass DiagnosticNode : public Object {\n public:\n  /*! \\brief The level. */\n  DiagnosticLevel level;\n  /*! \\brief The span at which to report an error. */\n  Span span;\n  /*! \\brief The diagnostic message. */\n  String message;\n\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"level\", &level);\n    v->Visit(\"span\", &span);\n    v->Visit(\"message\", &message);\n  }\n\n  bool SEqualReduce(const DiagnosticNode* other, SEqualReducer equal) const {\n    return equal(this->level, other->level) && equal(this->span, other->span) &&\n           equal(this->message, other->message);\n  }\n\n  static constexpr const char* _type_key = \"Diagnostic\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DiagnosticNode, Object);\n};\n\nclass Diagnostic : public ObjectRef {\n public:\n  TVM_DLL Diagnostic(DiagnosticLevel level, Span span, const std::string& message);\n\n  static DiagnosticBuilder Bug(Span span);\n  static DiagnosticBuilder Error(Span span);\n  static DiagnosticBuilder Warning(Span span);\n  static DiagnosticBuilder Note(Span span);\n  static DiagnosticBuilder Help(Span span);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Diagnostic, ObjectRef, DiagnosticNode);\n};\n\n/*!\n * \\brief A wrapper around std::stringstream to build a diagnostic.\n */\nclass DiagnosticBuilder {\n public:\n  /*! \\brief The level. */\n  DiagnosticLevel level;\n\n  /*! \\brief The source name. */\n  SourceName source_name;\n\n  /*! \\brief The span of the diagnostic. */\n  Span span;\n\n  template <typename T>\n  DiagnosticBuilder& operator<<(const T& val) {  // NOLINT(*)\n    stream_ << val;\n    return *this;\n  }\n\n  DiagnosticBuilder() : level(DiagnosticLevel::kError), source_name(), span(Span()) {}\n\n  DiagnosticBuilder(const DiagnosticBuilder& builder)\n      : level(builder.level), source_name(builder.source_name), span(builder.span) {}\n\n  DiagnosticBuilder(DiagnosticLevel level, Span span) : level(level), span(span) {}\n\n  operator Diagnostic() { return Diagnostic(this->level, this->span, this->stream_.str()); }\n\n private:\n  std::stringstream stream_;\n  friend class Diagnostic;\n};\n\n/*!\n * \\brief A diagnostic context for recording errors against a source file.\n */\nclass DiagnosticContext;\n\n/*! \\brief Display diagnostics in a given display format.\n *\n * A diagnostic renderer is responsible for converting the\n * raw diagnostics into consumable output.\n *\n * For example the terminal renderer will render a sequence\n * of compiler diagnostics to std::out and std::err in\n * a human readable form.\n */\nclass DiagnosticRendererNode : public Object {\n public:\n  TypedPackedFunc<void(DiagnosticContext ctx)> renderer;\n\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"DiagnosticRenderer\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DiagnosticRendererNode, Object);\n};\n\nclass DiagnosticRenderer : public ObjectRef {\n public:\n  TVM_DLL DiagnosticRenderer(TypedPackedFunc<void(DiagnosticContext ctx)> render);\n  TVM_DLL DiagnosticRenderer()\n      : DiagnosticRenderer(TypedPackedFunc<void(DiagnosticContext ctx)>()) {}\n\n  void Render(const DiagnosticContext& ctx);\n\n  DiagnosticRendererNode* operator->() {\n    ICHECK(get() != nullptr);\n    return static_cast<DiagnosticRendererNode*>(get_mutable());\n  }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(DiagnosticRenderer, ObjectRef, DiagnosticRendererNode);\n};\n\nclass DiagnosticContextNode : public Object {\n public:\n  /*! \\brief The Module to report against. */\n  IRModule module;\n\n  /*! \\brief The set of diagnostics to report. */\n  Array<Diagnostic> diagnostics;\n\n  /*! \\brief The renderer set for the context. */\n  DiagnosticRenderer renderer;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"module\", &module);\n    v->Visit(\"diagnostics\", &diagnostics);\n  }\n\n  bool SEqualReduce(const DiagnosticContextNode* other, SEqualReducer equal) const {\n    return equal(module, other->module) && equal(diagnostics, other->diagnostics);\n  }\n\n  static constexpr const char* _type_key = \"DiagnosticContext\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DiagnosticContextNode, Object);\n};\n\nclass DiagnosticContext : public ObjectRef {\n public:\n  TVM_DLL DiagnosticContext(const IRModule& module, const DiagnosticRenderer& renderer);\n  TVM_DLL static DiagnosticContext Default(const IRModule& source_map);\n\n  /*! \\brief Emit a diagnostic.\n   * \\param diagnostic The diagnostic to emit.\n   */\n  void Emit(const Diagnostic& diagnostic);\n\n  /*! \\brief Emit a diagnostic and then immediately attempt to render all errors.\n   *\n   * \\param diagnostic The diagnostic to emit.\n   *\n   * Note: this will raise an exception if you would like to instead continue execution\n   * use the Emit method instead.\n   */\n  void EmitFatal(const Diagnostic& diagnostic);\n\n  /*! \\brief Render the errors and raise a DiagnosticError exception. */\n  void Render();\n\n  DiagnosticContextNode* operator->() {\n    ICHECK(get() != nullptr);\n    return static_cast<DiagnosticContextNode*>(get_mutable());\n  }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(DiagnosticContext, ObjectRef, DiagnosticContextNode);\n};\n\nDiagnosticRenderer TerminalRenderer(std::ostream& ostream);\n\n}  // namespace tvm\n#endif  // TVM_IR_DIAGNOSTIC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/env_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/env_func.h\n * \\brief Serializable global function used in IR.\n */\n#ifndef TVM_IR_ENV_FUNC_H_\n#define TVM_IR_ENV_FUNC_H_\n\n#include <tvm/node/reflection.h>\n\n#include <string>\n#include <utility>\n\nnamespace tvm {\n/*!\n * \\brief A serializable function backed by TVM's global environment.\n *\n * This is a wrapper to enable serializable global PackedFunc.\n * An EnvFunc is saved by its name in the global registry\n * under the assumption that the same function is registered during load.\n * \\sa EnvFunc\n */\nclass EnvFuncNode : public Object {\n public:\n  /*! \\brief Unique name of the global function */\n  String name;\n  /*! \\brief The internal packed function */\n  runtime::PackedFunc func;\n  /*! \\brief constructor */\n  EnvFuncNode() {}\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"name\", &name); }\n\n  bool SEqualReduce(const EnvFuncNode* other, SEqualReducer equal) const {\n    // name uniquely identifies the env function.\n    return name == other->name;\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    // Name uniquely identifies the env function.\n    hash_reduce(name);\n  }\n\n  static constexpr const char* _type_key = \"EnvFunc\";\n  static constexpr bool _type_has_method_sequal_reduce = true;\n  static constexpr bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(EnvFuncNode, Object);\n};\n\n/*!\n * \\brief Managed reference to EnvFuncNode.\n * \\sa EnvFuncNode\n */\nclass EnvFunc : public ObjectRef {\n public:\n  EnvFunc() {}\n  explicit EnvFunc(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*! \\return The internal global function pointer */\n  const EnvFuncNode* operator->() const { return static_cast<const EnvFuncNode*>(get()); }\n  /*!\n   * \\brief Invoke the function.\n   * \\param args The arguments\n   * \\returns The return value.\n   */\n  template <typename... Args>\n  runtime::TVMRetValue operator()(Args&&... args) const {\n    const EnvFuncNode* n = operator->();\n    ICHECK(n != nullptr);\n    return n->func(std::forward<Args>(args)...);\n  }\n  /*!\n   * \\brief Get a global function based on the name.\n   * \\param name The name of the global function.\n   * \\return The created global function.\n   * \\note The function can be unique\n   */\n  TVM_DLL static EnvFunc Get(const String& name);\n  /*! \\brief specify container node */\n  using ContainerType = EnvFuncNode;\n};\n\n/*!\n * \\brief Please refer to \\ref TypedEnvFuncAnchor \"TypedEnvFunc<R(Args..)>\"\n */\ntemplate <typename FType>\nclass TypedEnvFunc;\n\n/*!\n * \\anchor TypedEnvFuncAnchor\n * \\brief A typed version of EnvFunc.\n * It is backed by a GlobalFuncNode internally.\n *\n * \\tparam R The return value of the function.\n * \\tparam Args The argument signature of the function.\n * \\sa EnvFunc\n */\ntemplate <typename R, typename... Args>\nclass TypedEnvFunc<R(Args...)> : public ObjectRef {\n public:\n  /*! \\brief short hand for this function type */\n  using TSelf = TypedEnvFunc<R(Args...)>;\n  TypedEnvFunc() {}\n  explicit TypedEnvFunc(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief Assign global function to a TypedEnvFunc\n   * \\param other Another global function.\n   * \\return reference to self.\n   */\n  TSelf& operator=(const EnvFunc& other) {\n    ObjectRef::operator=(other);\n    return *this;\n  }\n  /*! \\return The internal global function pointer */\n  const EnvFuncNode* operator->() const { return static_cast<const EnvFuncNode*>(get()); }\n  /*!\n   * \\brief Invoke the function.\n   * \\param args The arguments\n   * \\returns The return value.\n   */\n  R operator()(Args... args) const {\n    const EnvFuncNode* n = operator->();\n    ICHECK(n != nullptr);\n    return runtime::detail::typed_packed_call_dispatcher<R>::run(n->func,\n                                                                 std::forward<Args>(args)...);\n  }\n  /*! \\brief specify container node */\n  using ContainerType = EnvFuncNode;\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_ENV_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/error.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/error.h\n * \\brief Utilities for error tracking and reporting.\n */\n#ifndef TVM_IR_ERROR_H_\n#define TVM_IR_ERROR_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/ir/span.h>\n\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\n/*!\n * \\brief A wrapper around std::stringstream to build error.\n *\n * Can be consumed by CompileError to construct an error.\n *\n * \\code\n *\n * void ReportError(const CompileError& err);\n *\n * void Test(int number) {\n *   // Use error reporter to construct an error.\n *   ReportError(ErrorBuilder() << \"This is an error number=\" << number);\n * }\n *\n * \\endcode\n */\nstruct ErrorBuilder {\n public:\n  template <typename T>\n  ErrorBuilder& operator<<(const T& val) {  // NOLINT(*)\n    stream_ << val;\n    return *this;\n  }\n\n private:\n  std::stringstream stream_;\n  friend class CompileError;\n};\n\n/*!\n * \\brief Custom Error class to be thrown during compilation.\n */\nclass CompileError : public Error {\n public:\n  /*! \\brief Location of the error */\n  Span span;\n  /*!\n   * \\brief construct error from message.\n   * \\param msg The message\n   */\n  explicit CompileError(const std::string& msg) : Error(msg), span(nullptr) {}\n  /*!\n   * \\brief construct error from error builder.\n   * \\param err The error builder\n   */\n  CompileError(const ErrorBuilder& err) : Error(err.stream_.str()), span(nullptr) {}  // NOLINT(*)\n  /*!\n   * \\brief copy constructor.\n   * \\param other The other ereor.\n   */\n  CompileError(const CompileError& other) : Error(other.what()), span(other.span) {}  // NOLINT(*)\n  /*!\n   * \\brief default constructor. */\n  CompileError() : Error(\"\"), span(nullptr) {}\n};\n\n/*!\n * \\brief An abstraction around how errors are stored and reported.\n * Designed to be opaque to users, so we can support a robust and simpler\n * error reporting mode, as well as a more complex mode.\n *\n * The first mode is the most accurate: we report a Relay error at a specific\n * Span, and then render the error message directly against a textual representation\n * of the program, highlighting the exact lines in which it occurs. This mode is not\n * implemented in this PR and will not work.\n *\n * The second mode is a general-purpose mode, which attempts to annotate the program's\n * textual format with errors.\n *\n * The final mode represents the old mode, if we report an error that has no span or\n * expression, we will default to throwing an exception with a textual representation\n * of the error and no indication of where it occurred in the original program.\n *\n * The latter mode is not ideal, and the goal of the new error reporting machinery is\n * to avoid ever reporting errors in this style.\n */\nclass ErrorReporter {\n public:\n  /*! \\brief default constructor. */\n  ErrorReporter() : errors_(), node_to_error_() {}\n\n  /*!\n   * \\brief Report a CompileError.\n   *\n   * This API is useful for reporting spanned errors.\n   *\n   * \\param err The error to report.\n   */\n  void Report(const CompileError& err) {\n    if (!err.span.defined()) {\n      throw err;\n    }\n\n    this->errors_.push_back(err);\n  }\n\n  /*!\n   * \\brief Report an error against a program, using the full program\n   * error reporting strategy.\n   *\n   * This error reporting method requires the global function in which\n   * to report an error, the expression to report the error on,\n   * and the error object.\n   *\n   * \\param global The global function in which the expression is contained.\n   * \\param node The expression or type to report the error at.\n   * \\param err The error message to report.\n   */\n  void ReportAt(const GlobalVar& global, const ObjectRef& node, std::stringstream& err) {\n    std::string err_msg = err.str();\n    this->ReportAt(global, node, CompileError(err_msg));\n  }\n\n  /*!\n   * \\brief Report an error against a program, using the full program\n   * error reporting strategy.\n   *\n   * This error reporting method requires the global function in which\n   * to report an error, the expression to report the error on,\n   * and the error object.\n   *\n   * \\param global The global function in which the expression is contained.\n   * \\param node The expression or type to report the error at.\n   * \\param err The error to report.\n   */\n  void ReportAt(const GlobalVar& global, const ObjectRef& node, const CompileError& err);\n\n  /*!\n   * \\brief Render all reported errors and exit the program.\n   *\n   * This function should be used after executing a pass to render reported errors.\n   *\n   * It will build an error message from the set of errors, depending on the error\n   * reporting strategy.\n   *\n   * \\param module The module to report errors on.\n   * \\param use_color Controls whether to colorize the output.\n   */\n  void RenderErrors(const IRModule& module, bool use_color = true);\n\n  inline bool AnyErrors() { return errors_.size() != 0; }\n\n private:\n  std::vector<CompileError> errors_;\n  std::unordered_map<ObjectRef, std::vector<size_t>, ObjectPtrHash, ObjectPtrEqual> node_to_error_;\n  std::unordered_map<ObjectRef, GlobalVar, ObjectPtrHash, ObjectPtrEqual> node_to_gv_;\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_ERROR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/expr.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/expr.h\n * \\brief Base expr nodes in TVM.\n */\n#ifndef TVM_IR_EXPR_H_\n#define TVM_IR_EXPR_H_\n\n#include <tvm/ir/span.h>\n#include <tvm/ir/type.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <type_traits>\n\nnamespace tvm {\n\nusing tvm::runtime::String;\n\n// Forward-declare VirtualDevice to avoid circular imports.\nclass VirtualDevice;\n\n/*!\n * \\brief Base type of all the expressions.\n * \\sa Expr\n */\nclass BaseExprNode : public Object {\n public:\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  static constexpr const char* _type_key = \"BaseExpr\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  static constexpr const uint32_t _type_child_slots = 62;\n  TVM_DECLARE_BASE_OBJECT_INFO(BaseExprNode, Object);\n};\n\n/*!\n * \\brief Managed reference to BaseExprNode.\n * \\sa BaseExprNode\n */\nclass BaseExpr : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(BaseExpr, ObjectRef, BaseExprNode);\n};\n\n/*!\n * \\brief Base node of all primitive expressions.\n *\n *  A primitive expression deals with low-level\n *  POD data types and handles without\n *  doing life-cycle management for objects.\n *\n *  PrimExpr is used in the low-level code\n *  optimizations and integer analysis.\n *\n * \\sa PrimExpr\n */\nclass PrimExprNode : public BaseExprNode {\n public:\n  /*!\n   * \\brief The runtime data type of the primitive expression.\n   *\n   * runtime::DataType(dtype) provides coarse grained type information\n   * during compile time and runtime. It is eagerly built in\n   * PrimExpr expression construction and can be used for\n   * quick type checking.\n   *\n   * dtype is sufficient to decide the Type of the PrimExpr\n   * when it corresponds to POD value types such as i32.\n   *\n   * When dtype is DataType::Handle(), the expression could corresponds to\n   * a more fine-grained Type, and we can get the type by running lazy type inference.\n   */\n  DataType dtype;\n\n  static constexpr const char* _type_key = \"PrimExpr\";\n  static constexpr const uint32_t _type_child_slots = 38;\n  TVM_DECLARE_BASE_OBJECT_INFO(PrimExprNode, BaseExprNode);\n};\n\n/*!\n * \\brief Reference to PrimExprNode.\n * \\sa PrimExprNode\n */\nclass PrimExpr : public BaseExpr {\n public:\n  /*!\n   * \\brief construct from integer.\n   * \\param value The value to be constructed.\n   */\n  TVM_DLL PrimExpr(int32_t value);  // NOLINT(*)\n  /*!\n   * \\brief construct from float.\n   * \\param value The value to be constructed.\n   */\n  TVM_DLL PrimExpr(float value);  // NOLINT(*)\n\n  /*! \\return the data type of this expression. */\n  DataType dtype() const { return static_cast<const PrimExprNode*>(get())->dtype; }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PrimExpr, BaseExpr, PrimExprNode);\n\n private:\n  // Internal function for conversion.\n  friend struct runtime::PackedFuncValueConverter<PrimExpr>;\n  TVM_DLL static PrimExpr FromObject_(ObjectRef ref);\n};\n\n/*!\n * \\brief add operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator+(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief subtraction operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator-(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief negation.\n *\n * \\param a input.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator-(PrimExpr a);\n\n/*!\n * \\brief multiplication operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator*(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief division operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator/(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief left shift operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator<<(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief right shift operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator>>(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief greater\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator>(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief greater_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator>=(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief less\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator<(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief less_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator<=(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator==(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief not_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator!=(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief and\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr operator&&(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief or\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr operator||(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief not\n *\n * \\param a left operand\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr operator!(PrimExpr a);\n\n/*!\n * \\brief take bitwise and of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator&(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief take bitwise or of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator|(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief take bitwise xor of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator^(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief take bitwise negation of two values\n *\n * \\param a the input expression.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr operator~(PrimExpr a);\n\n/*!\n * \\brief Base node of all non-primitive expressions.\n *\n * RelayExpr supports tensor types, functions and ADT as\n * first class citizens. The life-cycle of the corresponding\n * objects are implicitly managed by the language.\n *\n * \\sa RelayExpr\n */\nclass RelayExprNode : public BaseExprNode {\n public:\n  /*!\n   * \\brief Stores the result of type inference(type checking).\n   *\n   * \\note This can be undefined before type inference.\n   *       This value is discarded during serialization.\n   */\n  mutable Type checked_type_ = Type(nullptr);\n  /*!\n   * \\return The checked_type\n   */\n  inline const Type& checked_type() const;\n  /*!\n   * \\brief Check if the inferred(checked) type of the Expr\n   *  is backed by a TTypeNode and return it.\n   *\n   * \\note This function will thrown an error if the node type\n   *       of this Expr is not TTypeNode.\n   *\n   * \\return The corresponding TTypeNode pointer.\n   * \\tparam The specific TypeNode we look for.\n   */\n  template <typename TTypeNode>\n  inline const TTypeNode* type_as() const;\n\n  /*!\n   * \\brief The virtual device (VirtualDevice) for this node (the result of device planning).\n   * For first-order expressions (non functions), this describes where the result of evaluating the\n   * expression should be stored. Note that currently, all composite first-order values (tuples,\n   * references, ADTs) must be stored on the same virtual device. This means that it is not possible\n   * to store two tuple fields on different devices, so we only need one virtual device for these\n   * types.\n   *\n   * For expressions that have the function type, the virtual device describes where the result of\n   * the call to the function or closure is stored (instead of where the function itself is stored).\n   * For example, the virtual device of f = fn(x) { body } is the virtual device of f(y), not where\n   * the function itself is stored. Note that f(y)'s virtual device will be the same as the virtual\n   * device of body. For more details, see the documentation in\n   * src/relay/transforms/device_planner.cc.\n   *\n   * The VirtualDevice's Target field describes how the body of the function should be compiled.\n   *\n   * Set to VirtualDevice::FullyUnconstrained by default.\n   *\n   * \\note Unfortunately, the type of virtual_device_ needs to be ObjectRef to avoid a circular\n   * import.\n   */\n  mutable ObjectRef virtual_device_;\n\n  /*!\n   * \\return The virtual device (VirtualDevice).\n   * If the virtual device is not defined, returns VirtualDevice::FullyUnconstrained().\n   * Note that for function types, the virtual device is the device where the result of a\n   * call to the function is stored, not where the function itself lives.\n   * For example, the virtual device of f = fn(x) { body } is the virtual device of f(y), not where\n   * the function itself is stored. Note that f(y)'s virtual device will be the same as the virtual\n   * device of body.\n   *\n   * See the documentation of the virtual_device_ field (above) for more details.\n   */\n  VirtualDevice virtual_device() const;\n\n  static constexpr const char* _type_key = \"RelayExpr\";\n  static constexpr const uint32_t _type_child_slots = 22;\n  TVM_DECLARE_BASE_OBJECT_INFO(RelayExprNode, BaseExprNode);\n};\n\n/*!\n * \\brief Managed reference to RelayExprNode.\n * \\sa RelayExprNode\n */\nclass RelayExpr : public BaseExpr {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(RelayExpr, BaseExpr, RelayExprNode);\n};\n\nclass GlobalVar;\n/*!\n * \\brief Global variable that lives in the top-level module.\n *\n * A GlobalVar only refers to function definitions.\n * This is used to enable recursive calls between function.\n *\n * \\sa GlobalVarNode\n */\nclass GlobalVarNode : public RelayExprNode {\n public:\n  /*! \\brief The name of the variable, this only acts as a hint. */\n  String name_hint;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const GlobalVarNode* other, SEqualReducer equal) const {\n    // name matters for global var.\n    return equal(name_hint, other->name_hint) && equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name_hint);\n    hash_reduce.FreeVarHashImpl(this);\n  }\n\n  static constexpr const char* _type_key = \"GlobalVar\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(GlobalVarNode, RelayExprNode);\n};\n\n/*!\n * \\brief Managed reference to GlobalVarNode.\n * \\sa GlobalVarNode\n */\nclass GlobalVar : public RelayExpr {\n public:\n  TVM_DLL explicit GlobalVar(String name_hint, Type type = {}, Span span = {});\n\n  TVM_DEFINE_OBJECT_REF_METHODS(GlobalVar, RelayExpr, GlobalVarNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(GlobalVarNode);\n};\n\n// PrimExprs that are useful as runtime containers.\n//\n/*!\n * \\brief Constant integer literals in the program.\n * \\sa IntImm\n */\nclass IntImmNode : public PrimExprNode {\n public:\n  /*! \\brief the Internal value. */\n  int64_t value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const IntImmNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(value);\n  }\n\n  static constexpr const char* _type_key = \"IntImm\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IntImmNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference class to IntImmNode.\n *\n * \\sa IntImmNode\n */\nclass IntImm : public PrimExpr {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param dtype The data type of the value.\n   * \\param value The internal value.\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL IntImm(DataType dtype, int64_t value, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IntImm, PrimExpr, IntImmNode);\n};\n\n/*!\n * \\brief Constant floating point literals in the program.\n * \\sa FloatImm\n */\nclass FloatImmNode : public PrimExprNode {\n public:\n  /*! \\brief The constant value content. */\n  double value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const FloatImmNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(value);\n  }\n\n  static constexpr const char* _type_key = \"FloatImm\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FloatImmNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference class to FloatImmNode.\n *\n * \\sa FloatImmNode\n */\nclass FloatImm : public PrimExpr {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param dtype The data type of the value.\n   * \\param value The internal value.\n   * \\param span The location in the source code.\n   */\n  TVM_DLL FloatImm(DataType dtype, double value, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FloatImm, PrimExpr, FloatImmNode);\n};\n\n/*!\n * \\brief Boolean constant.\n *\n *  This reference type is useful to add additional compile-time\n *  type checks and helper functions for Integer equal comparisons.\n */\nclass Bool : public IntImm {\n public:\n  explicit Bool(bool value, Span span = Span()) : IntImm(DataType::Bool(), value, span) {}\n  Bool operator!() const { return Bool((*this)->value == 0); }\n  operator bool() const { return (*this)->value != 0; }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Bool, IntImm, IntImmNode);\n};\n\n// Overload operators to make sure we have the most fine grained types.\ninline Bool operator||(const Bool& a, bool b) { return Bool(a.operator bool() || b); }\ninline Bool operator||(bool a, const Bool& b) { return Bool(a || b.operator bool()); }\ninline Bool operator||(const Bool& a, const Bool& b) {\n  return Bool(a.operator bool() || b.operator bool());\n}\ninline Bool operator&&(const Bool& a, bool b) { return Bool(a.operator bool() && b); }\ninline Bool operator&&(bool a, const Bool& b) { return Bool(a && b.operator bool()); }\ninline Bool operator&&(const Bool& a, const Bool& b) {\n  return Bool(a.operator bool() && b.operator bool());\n}\n\ninline bool operator==(const Bool& a, bool b) { return a.operator bool() == b; }\ninline bool operator==(bool a, const Bool& b) { return a == b.operator bool(); }\ninline bool operator==(const Bool& a, const Bool& b) {\n  return a.operator bool() == b.operator bool();\n}\n\n/*!\n * \\brief Container of constant int that adds more constructors.\n *\n * This is used to store and automate type check\n * attributes that must be constant integer.\n *\n * \\sa IntImm\n */\nclass Integer : public IntImm {\n public:\n  Integer() {}\n  /*!\n   * \\brief constructor from node.\n   */\n  explicit Integer(ObjectPtr<Object> node) : IntImm(node) {}\n  /*!\n   * \\brief Construct integer from int value.\n   */\n  Integer(int value, Span span = Span()) : IntImm(DataType::Int(32), value, span) {}  // NOLINT(*)\n  /*!\n   * \\brief Construct integer from int imm.\n   * \\param other The other value.\n   */\n  Integer(IntImm other) : IntImm(std::move(other)) {}  // NOLINT(*)\n  /*!\n   * \\brief Constructor from enum\n   * \\tparam Enum The enum type.\n   * \\param value The enum value.\n   */\n  template <typename Enum, typename = typename std::enable_if<std::is_enum<Enum>::value>::type>\n  explicit Integer(Enum value) : Integer(static_cast<int>(value)) {\n    static_assert(std::is_same<int, typename std::underlying_type<Enum>::type>::value,\n                  \"declare enum to be enum int to use visitor\");\n  }\n  /*!\n   * \\brief Assign an expression to integer.\n   * \\param other another expression.\n   */\n  Integer& operator=(const IntImm& other) {\n    data_ = ObjectRef::GetDataPtr<Object>(other);\n    return *this;\n  }\n  /*!\n   * \\brief convert to int64_t\n   */\n  int64_t IntValue() const {\n    ICHECK(data_ != nullptr) << \" Trying to reference a null Integer\";\n    return (*this)->value;\n  }\n  // comparators\n  Bool operator==(int other) const {\n    if (data_ == nullptr) return Bool(false);\n    return Bool((*this)->value == other);\n  }\n  Bool operator!=(int other) const { return !(*this == other); }\n  template <typename Enum, typename = typename std::enable_if<std::is_enum<Enum>::value>::type>\n  Bool operator==(Enum other) const {\n    return *this == static_cast<int>(other);\n  }\n  template <typename Enum, typename = typename std::enable_if<std::is_enum<Enum>::value>::type>\n  Bool operator!=(Enum other) const {\n    return *this != static_cast<int>(other);\n  }\n};\n\n/*! \\brief range over one dimension */\nclass RangeNode : public Object {\n public:\n  /*! \\brief beginning of the node */\n  PrimExpr min;\n  /*! \\brief the extend of range */\n  PrimExpr extent;\n  /*! \\brief the location of this range in the source */\n  mutable Span span;\n  /*! \\brief constructor */\n  RangeNode() {}\n  RangeNode(PrimExpr min, PrimExpr extent, Span span = Span())\n      : min(min), extent(extent), span(span) {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"min\", &min);\n    v->Visit(\"extent\", &extent);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const RangeNode* other, SEqualReducer equal) const {\n    return equal(min, other->min) && equal(extent, other->extent);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(min);\n    hash_reduce(extent);\n  }\n\n  static constexpr const char* _type_key = \"Range\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(RangeNode, Object);\n};\n\n/*! \\brief Range constainer  */\nclass Range : public ObjectRef {\n public:\n  /*!\n   * \\brief constructor by begin and end\n   * \\param begin The begin of the range.\n   * \\param end The end of the range.\n   * \\param span The location of the Range in the source.\n   */\n  TVM_DLL Range(PrimExpr begin, PrimExpr end, Span span = Span());\n  /*!\n   * \\brief construct a new range with min and extent\n   *  The corresponding constructor is removed,\n   *  because that is counter convention of tradition meaning\n   *  of range(begin, end)\n   *\n   * \\param min The minimum range.\n   * \\param extent The extent of the range.\n   * \\param span The location of the Range in the source.\n   */\n  static Range FromMinExtent(PrimExpr min, PrimExpr extent, Span span = Span());\n  // declare range.\n  TVM_DEFINE_OBJECT_REF_METHODS(Range, ObjectRef, RangeNode);\n};\n\n// implementataions\ninline const Type& RelayExprNode::checked_type() const {\n  ICHECK(checked_type_.defined()) << \"internal error: the type checker has \"\n                                  << \"not populated the checked_type \"\n                                  << \"field for \" << GetRef<RelayExpr>(this);\n  return this->checked_type_;\n}\n\ntemplate <typename TTypeNode>\ninline const TTypeNode* RelayExprNode::type_as() const {\n  static_assert(std::is_base_of<TypeNode, TTypeNode>::value,\n                \"TType must be a special case of type\");\n  ICHECK(checked_type_.defined())\n      << \"Type inference for this Expr has not completed. Try to call infer_type pass.\";\n  const TTypeNode* node = checked_type_.as<TTypeNode>();\n  ICHECK(node != nullptr) << \"Expected type to be \" << TTypeNode::_type_key << \", but get \"\n                          << checked_type_->GetTypeKey();\n  return node;\n}\n\n}  // namespace tvm\n\nnamespace tvm {\nnamespace runtime {\n// common rule for RetValue and ArgValue\ntemplate <>\nstruct PackedFuncValueConverter<PrimExpr> {\n  static PrimExpr From(const TVMPODValue_& val) {\n    if (val.type_code() == kTVMNullptr) {\n      return PrimExpr(ObjectPtr<Object>(nullptr));\n    }\n    if (val.type_code() == kDLInt) {\n      int64_t value = val.operator int64_t();\n      if (value > std::numeric_limits<int>::max() || value < std::numeric_limits<int>::min()) {\n        return IntImm(runtime::DataType::Int(64), value);\n      }\n      return IntImm(runtime::DataType::Int(32), val.operator int());\n    }\n    if (val.type_code() == kDLFloat) {\n      return FloatImm(runtime::DataType::Float(32), val.operator double());\n    }\n\n    return PrimExpr::FromObject_(val.AsObjectRef<ObjectRef>());\n  }\n};\n\ntemplate <>\nstruct PackedFuncValueConverter<tvm::Integer> {\n  static tvm::Integer From(const TVMPODValue_& val) {\n    if (val.type_code() == kTVMNullptr) {\n      return Integer(ObjectPtr<Object>(nullptr));\n    }\n    if (val.type_code() == kTVMArgInt) {\n      return Integer(val.operator int());\n    }\n    return val.AsObjectRef<tvm::Integer>();\n  }\n};\n\ntemplate <>\nstruct PackedFuncValueConverter<tvm::Bool> {\n  static tvm::Bool From(const TVMPODValue_& val) {\n    if (val.type_code() == kTVMNullptr) {\n      return Bool(ObjectPtr<Object>(nullptr));\n    }\n    if (val.type_code() == kTVMArgInt) {\n      int v = val.operator int();\n      ICHECK(v == 0 || v == 1) << \"ValueError: boolean value can only be 0 or 1, but get \" << v;\n      return Bool(static_cast<bool>(v));\n    }\n    return val.AsObjectRef<tvm::Bool>();\n  }\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_IR_EXPR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/function.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/function.h\n * \\brief Function nodes.\n */\n#ifndef TVM_IR_FUNCTION_H_\n#define TVM_IR_FUNCTION_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n\n#include <string>\n#include <type_traits>\n\nnamespace tvm {\n\n/*!\n * \\brief Possible Calling conventions.\n *\n *  NOTE: The calling convention also implies\n *  the way we implement the function during lowering.\n */\nenum class CallingConv : int {\n  /*!\n   * \\brief Default calling convention.\n   *\n   * - Uses the native calling convention of the target.\n   * - Implementation: specified by the native target.\n   */\n  kDefault = 0,\n  /*!\n   * \\brief PackedFunc that exposes a CPackedFunc signature.\n   *\n   * - Calling by PackedFunc calling convention.\n   * - Implementation: Expose a function with the CPackedFunc signature.\n   */\n  kCPackedFunc = 1,\n  /*!\n   * \\brief Device kernel launch\n   *\n   * - Call by PackedFunc calling convention.\n   * - Implementation: defined by device runtime(e.g. runtime/cuda)\n   */\n  kDeviceKernelLaunch = 2,\n};\n\n/*!\n * \\brief Base node of all functions.\n *\n * We support several variants of functions throughout the stack.\n * All of the functions share the same type system(via checked_type)\n * to support cross variant calls.\n *\n * \\sa BaseFunc\n */\nclass BaseFuncNode : public RelayExprNode {\n public:\n  /*! \\brief Additional attributes storing the meta-data */\n  DictAttrs attrs;\n\n  /*!\n   * \\brief Get a function attribute.\n   *\n   * \\param attr_key The attribute key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TOBjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetAttrExample(const BaseFunc& f) {\n   *    auto value = f->GetAttr<Integer>(\"AttrKey\", 0);\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    return attrs.GetAttr(attr_key, default_value);\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  /*!\n   * \\brief Check whether the function has an non-zero integer attr.\n   *\n   * This function can be used to check whether an optional\n   * attribute mark(e.g. inline) exists.\n   *\n   * \\param attr_key The key to the attribute.\n   * \\return The check result.\n   *\n   * \\code\n   *\n   *  void HasNonzeroAttrExample(const BaseFunc& f) {\n   *    if (f->HasNonzeroAttr(attr::kInline)) {\n   *      // inline the function.\n   *    }\n   *  }\n   *\n   * \\endcode\n   */\n  bool HasNonzeroAttr(const std::string& attr_key) const { return attrs.HasNonzeroAttr(attr_key); }\n\n  static constexpr const char* _type_key = \"BaseFunc\";\n  static constexpr const uint32_t _type_child_slots = 2;\n  TVM_DECLARE_BASE_OBJECT_INFO(BaseFuncNode, RelayExprNode);\n};\n\n/*!\n * \\brief Managed reference to BaseFuncNode.\n * \\sa BaseFuncNode\n */\nclass BaseFunc : public RelayExpr {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(BaseFunc, RelayExpr, BaseFuncNode);\n};\n\n/*!\n * \\brief Generic attribute names that can be attached to any function.\n *\n * \\sa tvm::tir::attr, tvm::relay::attr\n */\nnamespace attr {\n/*!\n * \\brief Indicates the special calling convention.\n *\n * Type: Integer\n *\n * \\sa tvm::CallingConv\n */\nconstexpr const char* kCallingConv = \"calling_conv\";\n\n/*!\n * \\brief Compilation target of the function.\n *\n * Type: Target\n *\n * \\sa tvm::Target\n */\nconstexpr const char* kTarget = \"target\";\n\n/*!\n * \\brief Global linker symbol of the function in generated code.\n *\n *  This option forces the code generator to name the\n *  function with the given.\n *\n *  For example, we could set a global_symbol of a function\n *  early to make sure that we can always refer to it by\n *  the symbol name in the generated DLL.\n *\n *  We should not set the attribute for local functions,\n *  so that the compiler can freely rename them.\n *\n *  A unique global symbol will be automatically assigned\n *  to each function in the module before the target code\n *  generation phase.\n *\n * Type: String\n */\nconstexpr const char* kGlobalSymbol = \"global_symbol\";\n\n}  // namespace attr\n}  // namespace tvm\n#endif  // TVM_IR_FUNCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/global_var_supply.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/global_var_supply.h\n * \\brief GlobalVarSupply that can be used to generate unique \\class GlobalVar.\n */\n#ifndef TVM_IR_GLOBAL_VAR_SUPPLY_H_\n#define TVM_IR_GLOBAL_VAR_SUPPLY_H_\n\n#include <string>\n#include <unordered_map>\n\n#include \"tvm/ir/expr.h\"\n#include \"tvm/ir/module.h\"\n#include \"tvm/ir/name_supply.h\"\n\nnamespace tvm {\n\n/*!\n * \\brief GlobalVarSupply can be used to generate unique GlobalVars.\n */\nclass GlobalVarSupplyNode : public Object {\n public:\n  /*!\n   * \\brief Empty constructor. Will use an empty NameSupply.\n   */\n  GlobalVarSupplyNode() : GlobalVarSupplyNode(NameSupply(\"\")) {}\n\n  /*!\n   * \\brief Constructor.\n   * \\param name_supply The NameSupply to use for generating the names of fresh GlobalVars.\n   * \\param name_to_var_map An optional map.\n   */\n  explicit GlobalVarSupplyNode(NameSupply name_supply,\n                               std::unordered_map<std::string, GlobalVar> name_to_var_map = {});\n\n  /*!\n   * \\brief Generates a unique GlobalVar from this supply.\n   * \\param name The name from which the name of the GlobalVar is derived.\n   * \\param add_prefix If set to true, then the prefix of the contained NameSupply will be prepended\n   * to the name. \\return A unique GlobalVar.\n   */\n  GlobalVar FreshGlobal(String name, bool add_prefix = true);\n\n  /*!\n   * \\brief Looks up for a GlobalVar with the given name in this supply.\n   * If no entry is found, creates one, places it in the cache and returns it.\n   * \\param name The name of the GlobalVar to search for.\n   * \\param add_prefix If set to true, the prefix of the contained NameSupply will be prepended to\n   * the name before performing the search. \\return A cached GlobalVar.\n   */\n  GlobalVar UniqueGlobalFor(const String& name, bool add_prefix = true);\n\n  /*!\n   * \\brief Reserves an existing GlobalVar with this supply.\n   * \\param var The GlobalVar to be registered.\n   * \\param allow_conflict Allow conflict with other GlobalVars that have the same name.\n   */\n  void ReserveGlobalVar(const GlobalVar& var, bool allow_conflict = false);\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  /*! \\brief The NameSupply used to generate unique name hints to GlobalVars. */\n  NameSupply name_supply_;\n\n  static constexpr const char* _type_key = \"GlobalVarSupply\";\n  static constexpr const bool _type_has_method_sequal_reduce = false;\n  static constexpr const bool _type_has_method_shash_reduce = false;\n  TVM_DECLARE_FINAL_OBJECT_INFO(GlobalVarSupplyNode, Object);\n\n private:\n  std::unordered_map<std::string, GlobalVar> name_to_var_map_;\n};\n\n/*!\n * \\brief Managed reference class to GlobalVarSupplyNode.\n * \\sa GlobalVarSupplyNode\n */\nclass GlobalVarSupply : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param name_supply The NameSupply to be used when generating new GlobalVars.\n   * \\param name_to_var_map An optional map.\n   */\n  TVM_DLL explicit GlobalVarSupply(const NameSupply& name_supply,\n                                   std::unordered_map<std::string, GlobalVar> name_to_var_map = {});\n\n  /*!\n   * \\brief Constructs a supply from an array of IRModules. GlobalVars generated by this supply are\n   * guaranteed not to conflict with any GlobalVars that belong to the modules. \\param modules Array\n   * of IRModules.\n   */\n  TVM_DLL explicit GlobalVarSupply(const Array<IRModule>& modules);\n\n  /*!\n   * \\brief Constructs a GlobalVarSupply from an IRModule. GlobalVars generated by this supply are\n   * guaranteed not to conflict with GlobalVars that belong to the modules. \\param module The\n   * IRModule.\n   */\n  TVM_DLL explicit GlobalVarSupply(const IRModule module);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(GlobalVarSupply, ObjectRef, GlobalVarSupplyNode);\n};\n\n}  // namespace tvm\n\n#endif  // TVM_IR_GLOBAL_VAR_SUPPLY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/instrument.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/instrument.h\n *\n * This file introduces a pass instrument infrastructure, inspired by LLVM and MLIR.\n * It inserts instrumentation points around passes.\n */\n#ifndef TVM_IR_INSTRUMENT_H_\n#define TVM_IR_INSTRUMENT_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/string.h>\n\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nclass IRModule;\n\n// Forward class for PassInstrumentNode methods\nnamespace transform {\nclass PassInfo;\n}  // namespace transform\n\nnamespace instrument {\n\n/*!\n * \\brief PassInstrumentNode forms an instrument implementation.\n * It provides API for users to register callbacks at different instrumentation points.\n *\n * Within a PassContext, call sequence of a PassInstrument implementation is like:\n *\n *   with PassContext(instruments=[pi]):  # pi = a PassInstrument implementation\n *       pi.EnterPassContext()\n *\n *       if pi.ShouldRun(Pass1):\n *           pi.RunBeforePass()\n *           Pass1()\n *           pi.RunAfterPass()\n *\n *       if pi.ShouldRun(Pass2):\n *           pi.RunBeforePass()\n *           Pass2()\n *           pi.RunAfterPass()\n *\n *       pi.ExitPassContext()\n *\n * `EnterPassContext` and `ExitPassContext` are only called once when entering/exiting a\n * PassContext. `ShouldRun`, `RunBeforePass` and `RunAfterPass` are called multiple times depending\n * on how many passes.\n *\n * If there are multiple pass instrumentations provided, the instrument points are the same.\n * PassInstrument implementations' callbacks are called in order:\n *\n *   with PassContext(instruments=[pi1, pi2]):  # pi1, pi2 = two distinct PassInstrument impls\n *       pi.EnterPassContext() for pi in instruments\n *\n *       should_run = all([pi.ShoudRun(Pass1) for pi in instruments)])\n *       if (should_run)\n *           pi.RunBeforePass() for pi in instruments\n *           Pass1()\n *           pi.RunAfterPass()  for pi in instruments\n *\n *       should_run = all([pi.ShouldRun(Pass2) for pi in instruments)])\n *       if (should_run)\n *           pi.RunBeforePass() for pi in instruments\n *           Pass2()\n *           pi.RunAfterPass() for pi in instruments\n *\n *       pi.ExitPassContext() for pi in instruments\n *\n * Note:\n *   1. Assume there is no dependency between PassInstrument implementations in `instruments` .\n *   2. `EnterPassContext` and `ExitPassContext` have `with` behavior (see PassContext and its FFI):\n *        If there is any exception raised in `ShouldRun()`, `RunBeforePass()`, `RunAfterPass()` and\n *        `Pass()`, `ExitPassContext()` is still called.\n *   3. In mutiple PassInstrument instances scenario, callbacks are called in order:\n *        If one throws exceptions, remainings will not be called.\n *\n * \\sa PassInstrument\n * \\sa src/ir/transform.cc\n */\nclass PassInstrumentNode : public Object {\n public:\n  /*! \\brief Name of this pass instrument object. */\n  String name;\n\n  virtual ~PassInstrumentNode() {}\n\n  /*! \\brief Instrument when entering PassContext. Called once within a PassContext. */\n  virtual void EnterPassContext() const = 0;\n\n  /*! \\brief Instrument when exiting PassContext. Called once within a PassContext. */\n  virtual void ExitPassContext() const = 0;\n\n  /*!\n   * \\brief Determine whether to run the pass or not. Called multiple times depend on number of\n   *        passes.\n   * \\param mod The module that an optimization pass runs on.\n   * \\param info The pass information.\n   *\n   * \\return true to run the pass; false to skip the pass.\n   */\n  virtual bool ShouldRun(const IRModule& mod, const transform::PassInfo& info) const = 0;\n\n  /*!\n   * \\brief Instrument before pass run. Called multiple times depend on number of passes.\n   * \\param mod The module that an optimization pass runs on.\n   * \\param info The pass information.\n   */\n  virtual void RunBeforePass(const IRModule& mod, const transform::PassInfo& info) const = 0;\n\n  /*!\n   * \\brief Instrument after pass run. Called multiple time depend on number of passes.\n   * \\param mod The module that an optimization pass runs on.\n   * \\param info The pass information.\n   */\n  virtual void RunAfterPass(const IRModule& mod, const transform::PassInfo& info) const = 0;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"name\", &name); }\n\n  static constexpr const char* _type_key = \"instrument.PassInstrument\";\n  TVM_DECLARE_BASE_OBJECT_INFO(PassInstrumentNode, Object);\n};\n\n/*!\n * \\brief Managed reference class for PassInstrumentNode\n * \\sa PassInstrumentNode\n */\nclass PassInstrument : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(PassInstrument, ObjectRef, PassInstrumentNode);\n};\n\n}  // namespace instrument\n}  // namespace tvm\n\n#endif  // TVM_IR_INSTRUMENT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/memory_pools.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/memory_pools.h\n * \\brief The object definition for relay.build argument type of memory pools\n */\n#ifndef TVM_IR_MEMORY_POOLS_H_\n#define TVM_IR_MEMORY_POOLS_H_\n\n#include <tvm/runtime/registry.h>\n#include <tvm/target/target.h>\n\nstruct TVMConstantInfo;\nnamespace tvm {\n\n/*!\n * \\brief Describes a pool of memory accessible by one or more targets.\n */\nstruct PoolInfoNode : public Object {\n public:\n  /*! \\brief The name of the memory pool */\n  String pool_name;\n  /*! \\brief The expected size hint to be used by the allocator.\n   * The size_hint_bytes is set to kUnrestrictedPoolSizeHint\n   * to indicate the pool is not size restricted.\n   */\n  Integer size_hint_bytes;\n  /*! \\brief The clock frequency of the memory in Hz */\n  Integer clock_frequency_hz;\n  /*! \\brief The read bandwidth in bytes/cycle */\n  Integer read_bandwidth_bytes_per_cycle;\n  /*! \\brief The write bandwidth in bytes/cycle */\n  Integer write_bandwidth_bytes_per_cycle;\n  /*! \\brief The read latency in cycles */\n  Integer read_latency_cycles;\n  /*! \\brief The write latency in cycles */\n  Integer write_latency_cycles;\n  /*! \\brief The burst length in bytes for each Target */\n  Map<Target, Integer> target_burst_bytes;\n  /*! \\brief Whether pool is internally generated.\n   * The internal pools will be generated as part of\n   * the entry point code generation of the executor\n   */\n  bool is_internal = false;\n\n  /*! \\brief The targets linked to the pool */\n  Array<Target> targets;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pool_name\", &pool_name);\n    v->Visit(\"targets\", &targets);\n    v->Visit(\"size_hint_bytes\", &size_hint_bytes);\n    v->Visit(\"clock_frequency_hz\", &clock_frequency_hz);\n    v->Visit(\"read_bandwidth_bytes_per_cycle\", &read_bandwidth_bytes_per_cycle);\n    v->Visit(\"write_bandwidth_bytes_per_cycle\", &write_bandwidth_bytes_per_cycle);\n    v->Visit(\"read_latency_cycles\", &read_latency_cycles);\n    v->Visit(\"write_latency_cycles\", &write_latency_cycles);\n    v->Visit(\"target_burst_bytes\", &target_burst_bytes);\n    v->Visit(\"is_internal\", &is_internal);\n  }\n\n  bool SEqualReduce(const PoolInfoNode* other, SEqualReducer equal) const {\n    return equal(pool_name, other->pool_name) && equal(size_hint_bytes, other->size_hint_bytes) &&\n           equal(clock_frequency_hz, other->clock_frequency_hz) &&\n           equal(read_bandwidth_bytes_per_cycle, other->read_bandwidth_bytes_per_cycle) &&\n           equal(write_bandwidth_bytes_per_cycle, other->write_bandwidth_bytes_per_cycle) &&\n           equal(read_latency_cycles, other->read_latency_cycles) &&\n           equal(write_latency_cycles, other->write_latency_cycles) &&\n           equal(target_burst_bytes, other->target_burst_bytes) &&\n           equal(is_internal, other->is_internal);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(pool_name);\n    hash_reduce(size_hint_bytes);\n    hash_reduce(clock_frequency_hz);\n    hash_reduce(read_bandwidth_bytes_per_cycle);\n    hash_reduce(write_bandwidth_bytes_per_cycle);\n    hash_reduce(read_latency_cycles);\n    hash_reduce(write_latency_cycles);\n    hash_reduce(target_burst_bytes);\n    hash_reduce(is_internal);\n  }\n\n  static constexpr const char* _type_key = \"ir.PoolInfo\";\n  TVM_DECLARE_BASE_OBJECT_INFO(PoolInfoNode, Object);\n};\n\n/*!\n * \\brief The string parameter to indicate read and write access to a pool\n * This needs to be kept in sync with PoolInfo.READ_WRITE_ACCESS in\n * python/tvm/ir/memory_pools.py\n */\nstatic constexpr const char* kTargetPoolReadWriteAccess = \"rw\";\n\n/*!\n * \\brief The string parameter to indicate read only access to a pool\n * This needs to be kept in sync with PoolInfo.READ_ONLY_ACCESS in\n * python/tvm/ir/memory_pools.py\n */\nstatic constexpr const char* kTargetPoolReadOnlyAccess = \"ro\";\n\n/*! \\brief The PoolSize is unrestricted for the memory planner */\nstatic const int kUnrestrictedPoolSizeHint = -1;\n\n/*! \\brief The clock frequency is not known */\nstatic const int kUnknownClockFrequency = -1;\n\n/*! \\brief The read bandwidth is not known */\nstatic const int kUnknownReadBandwidth = -1;\n\n/*! \\brief The write bandwidth is not known */\nstatic const int kUnknownWriteBandwidth = -1;\n\n/*! \\brief Base class for WorkspacePoolInfo and ConstantPoolInfo */\nclass PoolInfo : public ObjectRef {\n protected:\n  TVM_DLL PoolInfo(String pool_name, Integer size_hint_bytes = kUnrestrictedPoolSizeHint,\n                   Integer clock_frequency_hz = kUnknownClockFrequency,\n                   Integer read_bandwidth_bytes_per_cycle = kUnknownReadBandwidth,\n                   Integer write_bandwidth_bytes_per_cycle = kUnknownWriteBandwidth,\n                   Integer read_latency_cycles = 0, Integer write_latency_cycles = 0,\n                   Map<Target, Integer> target_burst_bytes = {}, Bool is_internal = Bool(false));\n\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(PoolInfo, ObjectRef, PoolInfoNode);\n};\n\n/*!\n * \\brief Describes a pool of memory properties\n */\nstruct PoolInfoPropertiesNode : public Object {\n  /*! \\brief The expected size hint to be used by the allocator.\n   * The size_hint_bytes is set to kUnrestrictedPoolSizeHint\n   * to indicate the pool is not size restricted.\n   */\n  Integer size_hint_bytes = kUnrestrictedPoolSizeHint;\n  /*! \\brief The clock frequency of the memory in Hz */\n  Integer clock_frequency_hz = kUnknownClockFrequency;\n  /*! \\brief The read bandwidth in bytes/cycle */\n  Integer read_bandwidth_bytes_per_cycle = kUnknownReadBandwidth;\n  /*! \\brief The write bandwidth in bytes/cycle */\n  Integer write_bandwidth_bytes_per_cycle = kUnknownWriteBandwidth;\n  /*! \\brief The read latency in cycles */\n  Integer read_latency_cycles = 0;\n  /*! \\brief The write latency in cycles */\n  Integer write_latency_cycles = 0;\n  /*! \\brief The burst length in bytes for each Target */\n  Map<Target, Integer> target_burst_bytes{};\n  /*! \\brief Whether pool is internally generated.\n   * The internal pools will be generated as part of\n   * the entry point code generation of the executor\n   */\n  bool is_internal = false;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"size_hint_bytes\", &size_hint_bytes);\n    v->Visit(\"clock_frequency_hz\", &clock_frequency_hz);\n    v->Visit(\"read_bandwidth_bytes_per_cycle\", &read_bandwidth_bytes_per_cycle);\n    v->Visit(\"write_bandwidth_bytes_per_cycle\", &write_bandwidth_bytes_per_cycle);\n    v->Visit(\"read_latency_cycles\", &read_latency_cycles);\n    v->Visit(\"write_latency_cycles\", &write_latency_cycles);\n    v->Visit(\"target_burst_bytes\", &target_burst_bytes);\n    v->Visit(\"is_internal\", &is_internal);\n  }\n\n  bool SEqualReduce(const PoolInfoPropertiesNode* other, SEqualReducer equal) const {\n    return equal(size_hint_bytes, other->size_hint_bytes) &&\n           equal(clock_frequency_hz, other->clock_frequency_hz) &&\n           equal(read_bandwidth_bytes_per_cycle, other->read_bandwidth_bytes_per_cycle) &&\n           equal(write_bandwidth_bytes_per_cycle, other->write_bandwidth_bytes_per_cycle) &&\n           equal(read_latency_cycles, other->read_latency_cycles) &&\n           equal(write_latency_cycles, other->write_latency_cycles) &&\n           equal(target_burst_bytes, other->target_burst_bytes) &&\n           equal(is_internal, other->is_internal);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(size_hint_bytes);\n    hash_reduce(clock_frequency_hz);\n    hash_reduce(read_bandwidth_bytes_per_cycle);\n    hash_reduce(write_bandwidth_bytes_per_cycle);\n    hash_reduce(read_latency_cycles);\n    hash_reduce(write_latency_cycles);\n    hash_reduce(target_burst_bytes);\n    hash_reduce(is_internal);\n  }\n\n  static constexpr const char* _type_key = \"ir.PoolInfoProperties\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PoolInfoPropertiesNode, Object);\n};\n\nclass PoolInfoProperties : public ObjectRef {\n public:\n  TVM_DLL PoolInfoProperties(Integer size_hint_bytes,\n                             Integer clock_frequency_hz = kUnknownClockFrequency,\n                             Integer read_bandwidth_bytes_per_cycle = kUnknownReadBandwidth,\n                             Integer write_bandwidth_bytes_per_cycle = kUnknownWriteBandwidth,\n                             Integer read_latency_cycles = 0, Integer write_latency_cycles = 0,\n                             Map<Target, Integer> target_burst_bytes = {},\n                             Bool is_internal = Bool(false));\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PoolInfoProperties, ObjectRef, PoolInfoPropertiesNode);\n};\n\n/* \\brief Represents RW memory area */\nstruct WorkspacePoolInfoNode : public PoolInfoNode {\n  void VisitAttrs(tvm::AttrVisitor* v) { PoolInfoNode::VisitAttrs(v); }\n\n  bool SEqualReduce(const WorkspacePoolInfoNode* other, SEqualReducer equal) const {\n    return PoolInfoNode::SEqualReduce(other, equal);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { PoolInfoNode::SHashReduce(hash_reduce); }\n\n  static constexpr const char* _type_key = \"ir.WorkspacePoolInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WorkspacePoolInfoNode, PoolInfoNode);\n};\n\nclass WorkspacePoolInfo : public PoolInfo {\n public:\n  TVM_DLL WorkspacePoolInfo(\n      String pool_name, Array<Target> targets,\n      PoolInfoProperties properties = PoolInfoProperties(kUnrestrictedPoolSizeHint));\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(WorkspacePoolInfo, PoolInfo, WorkspacePoolInfoNode);\n};\n\n/*\n * \\brief The ConstantInfoNode contains numeric literal in RO pool\n * Used to initialise RO memory in ConstantPoolInfo\n */\nstruct ConstantInfoNode : public Object {\n  String name_hint;\n  Integer byte_offset;\n  runtime::NDArray data;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"byte_offset\", &byte_offset);\n    v->Visit(\"data\", &data);\n  }\n\n  bool SEqualReduce(const ConstantInfoNode* other, SEqualReducer equal) const {\n    return equal(name_hint, other->name_hint) && equal(byte_offset, other->byte_offset) &&\n           equal(data, other->data);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name_hint);\n    hash_reduce(byte_offset);\n    hash_reduce(data);\n  }\n\n  static constexpr const char* _type_key = \"ir.ConstantInfo\";\n  static constexpr bool _type_has_method_sequal_reduce = true;\n  static constexpr bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantInfoNode, Object);\n};\n\nclass ConstantInfo : public ObjectRef {\n public:\n  TVM_DLL ConstantInfo(const struct ::TVMConstantInfo* data);\n  ConstantInfo(String name, Integer byte_offset, runtime::NDArray data);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ConstantInfo, ObjectRef, ConstantInfoNode);\n};\n\n/* \\brief ConstantPoolInfoNode represents an RO memory area initialized with\n * data from constant_info_array */\nstruct ConstantPoolInfoNode : public PoolInfoNode {\n  Array<ConstantInfo> constant_info_array;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    PoolInfoNode::VisitAttrs(v);\n    v->Visit(\"constant_info_array\", &constant_info_array);\n  }\n\n  bool SEqualReduce(const ConstantPoolInfoNode* other, SEqualReducer equal) const {\n    return PoolInfoNode::SEqualReduce(other, equal) &&\n           equal(constant_info_array, other->constant_info_array);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    PoolInfoNode::SHashReduce(hash_reduce);\n    hash_reduce(constant_info_array);\n  }\n\n  static constexpr const char* _type_key = \"ir.ConstantPoolInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantPoolInfoNode, PoolInfoNode);\n};\n\nclass ConstantPoolInfo : public PoolInfo {\n public:\n  TVM_DLL ConstantPoolInfo(\n      String pool_name, Array<Target> targets, Array<ConstantInfo> constant_info_array,\n      PoolInfoProperties properties = PoolInfoProperties(kUnrestrictedPoolSizeHint));\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ConstantPoolInfo, PoolInfo, ConstantPoolInfoNode);\n};\n\n/* \\brief A container for WorkspacePoolInfo objects */\nstruct WorkspaceMemoryPoolsNode : public Object {\n  Array<PoolInfo> pools;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"pools\", &pools); }\n\n  bool SEqualReduce(const WorkspaceMemoryPoolsNode* other, SEqualReducer equal) const {\n    return equal(pools, other->pools);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(pools); }\n\n  static constexpr const char* _type_key = \"ir.WorkspaceMemoryPools\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WorkspaceMemoryPoolsNode, Object);\n};\n\nclass WorkspaceMemoryPools : public ObjectRef {\n public:\n  TVM_DLL WorkspaceMemoryPools(Array<PoolInfo> pools);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(WorkspaceMemoryPools, ObjectRef, WorkspaceMemoryPoolsNode);\n};\n\n/* \\brief A container for ConstantPoolInfo objects */\nstruct ConstantMemoryPoolsNode : public Object {\n  Array<ConstantPoolInfo> pools;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"pools\", &pools); }\n\n  bool SEqualReduce(const ConstantMemoryPoolsNode* other, SEqualReducer equal) const {\n    return equal(pools, other->pools);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(pools); }\n\n  static constexpr const char* _type_key = \"ir.ConstantMemoryPools\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantMemoryPoolsNode, Object);\n};\n\nclass ConstantMemoryPools : public ObjectRef {\n public:\n  TVM_DLL ConstantMemoryPools(Array<ConstantPoolInfo> pools);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ConstantMemoryPools, ObjectRef, ConstantMemoryPoolsNode);\n};\n\n}  // namespace tvm\n\n#endif  // TVM_IR_MEMORY_POOLS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/module.h\n * \\brief IRModule that holds the functions and type definitions.\n */\n#ifndef TVM_IR_MODULE_H_\n#define TVM_IR_MODULE_H_\n\n#include <tvm/ir/adt.h>\n#include <tvm/ir/expr.h>\n#include <tvm/ir/function.h>\n#include <tvm/ir/type.h>\n#include <tvm/parser/source_map.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nclass IRModule;\n\n/*!\n * \\brief IRModule that holds functions and type definitions.\n *\n *  IRModule is the basic unit for all IR transformations across the stack.\n *\n *  Many operations require access to the global IRModule.\n *  We pass the IRModule by value in a functional style as an explicit argument,\n *  but we mutate the Module while optimizing programs.\n * \\sa IRModule\n */\nclass IRModuleNode : public Object {\n public:\n  /*! \\brief A map from ids to all global functions. */\n  Map<GlobalVar, BaseFunc> functions;\n  /*! \\brief A map from global type vars to ADT type data. */\n  Map<GlobalTypeVar, TypeData> type_definitions;\n  /*! \\brief The source map for the module. */\n  parser::SourceMap source_map;\n  /* \\brief Additional attributes storing meta-data about the module. */\n  DictAttrs attrs;\n\n  /*!\n   * \\brief Get a module attribute.\n   *\n   * \\param attr_key The attribute key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TOBjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetAttrExample(const IRModule& mod) {\n   *    auto value = f->GetAttr<Integer>(\"AttrKey\", 0);\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    return attrs.GetAttr(attr_key, default_value);\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  /*!\n   * \\brief Check whether the module has an non-zero integer attr.\n   *\n   * This function can be used to check whether an optional\n   * attribute mark(e.g. inline) exists.\n   *\n   * \\param attr_key The key to the attribute.\n   * \\return The check result.\n   *\n   * \\code\n   *\n   *  void HasNonzeroAttrExample(const IRModule& mod) {\n   *    if (mod->HasNonzeroAttr(attr::kInline)) {\n   *      // inline the function.\n   *    }\n   *  }\n   *\n   * \\endcode\n   */\n  bool HasNonzeroAttr(const std::string& attr_key) const { return attrs.HasNonzeroAttr(attr_key); }\n\n  IRModuleNode() : source_map() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"functions\", &functions);\n    v->Visit(\"type_definitions\", &type_definitions);\n    v->Visit(\"global_var_map_\", &global_var_map_);\n    v->Visit(\"global_type_var_map_\", &global_type_var_map_);\n    v->Visit(\"source_map\", &source_map);\n    v->Visit(\"attrs\", &attrs);\n  }\n\n  TVM_DLL bool SEqualReduce(const IRModuleNode* other, SEqualReducer equal) const;\n\n  TVM_DLL void SHashReduce(SHashReducer hash_reduce) const;\n\n  /*!\n   * \\brief Add a function to the global environment.\n   * \\param var The var of the global function.\n   * \\param func The function.\n   * \\param update Controls whether you can replace a definition in the\n   * environment.\n   */\n  TVM_DLL void Add(const GlobalVar& var, const BaseFunc& func, bool update = false);\n\n  /*!\n   * \\brief Add a function to the global environment.\n   * \\param var The name of the global function.\n   * \\param func The function.\n   *\n   * It does not do type inference as Add does.\n   */\n  TVM_DLL void AddUnchecked(const GlobalVar& var, const BaseFunc& func);\n\n  /*!\n   * \\brief Add a type-level definition to the global environment.\n   * \\param var The var of the global type definition.\n   * \\param type The ADT.\n   * \\param update Controls whether you can replace a definition in the\n   * environment.\n   */\n  TVM_DLL void AddTypeDef(const GlobalTypeVar& var, const TypeData& type, bool update = false);\n\n  /*!\n   * \\brief Add a type-level definition to the global environment.\n   * \\param var The var of the global type definition.\n   * \\param type The ADT.\n   * \\param update Controls whether you can replace a definition in the\n   * environment.\n   *\n   * It does not do type checking as AddTypeDef does.\n   */\n  TVM_DLL void AddTypeDefUnchecked(const GlobalTypeVar& var, const TypeData& type,\n                                   bool update = false);\n\n  /*!\n   * \\brief Update a function in the global environment.\n   * \\param var The name of the global function to update.\n   * \\param func The new function.\n   */\n  TVM_DLL void Update(const GlobalVar& var, const BaseFunc& func);\n\n  /*!\n   * \\brief Update a type definition in the global environment.\n   * \\param var The name of the global type definition to update.\n   * \\param type The new ADT.\n   */\n  TVM_DLL void UpdateTypeDef(const GlobalTypeVar& var, const TypeData& type);\n\n  /*!\n   * \\brief Remove a function from the global environment.\n   * \\param var The name of the global function to update.\n   */\n  TVM_DLL void Remove(const GlobalVar& var);\n\n  /*!\n   * \\brief Check if the global_var_map_ contains a global variable.\n   * \\param name The variable name.\n   * \\returns true if contains, otherise false.\n   */\n  TVM_DLL bool ContainGlobalVar(const String& name) const;\n\n  /*!\n   * \\brief Check if the global_type_var_map_ contains a global type variable.\n   * \\param name The variable name.\n   * \\returns true if contains, otherise false.\n   */\n  TVM_DLL bool ContainGlobalTypeVar(const String& name) const;\n\n  /*!\n   * \\brief Lookup a global function by its variable.\n   * \\param str The unique string specifying the global variable.\n   * \\returns The global variable.\n   */\n  TVM_DLL GlobalVar GetGlobalVar(const String& str) const;\n\n  /*!\n   * \\brief Collect all global vars defined in this module.\n   * \\returns An array of global vars\n   */\n  TVM_DLL Array<GlobalVar> GetGlobalVars() const;\n\n  /*!\n   * \\brief Look up a global function by its name.\n   * \\param str The unique string specifying the global variable.\n   * \\returns The global variable.\n   */\n  TVM_DLL GlobalTypeVar GetGlobalTypeVar(const String& str) const;\n\n  /*!\n   * \\brief Collect all global type vars defined in this module.\n   * \\returns An array of global type vars\n   */\n  TVM_DLL Array<GlobalTypeVar> GetGlobalTypeVars() const;\n\n  /*!\n   * \\brief Find constructor of ADT using name\n   * \\param adt name of the ADT the constructor belongs to\n   * \\param cons name of the constructor\n   * \\returns Constructor of ADT, error if not found\n   */\n  TVM_DLL Constructor GetConstructor(const String& adt, const String& cons) const;\n\n  /*!\n   * \\brief Look up a global function by its variable.\n   * \\param var The global var to lookup.\n   * \\returns The function named by the variable argument.\n   */\n  TVM_DLL BaseFunc Lookup(const GlobalVar& var) const;\n\n  /*!\n   * \\brief Look up a global function by its string name\n   * \\param name The name of the function.\n   * \\returns The function named by the argument.\n   */\n  TVM_DLL BaseFunc Lookup(const String& name) const;\n\n  /*!\n   * \\brief Look up a global type definition by its variable.\n   * \\param var The var of the global type definition.\n   * \\return The type definition.\n   */\n  TVM_DLL TypeData LookupTypeDef(const GlobalTypeVar& var) const;\n\n  /*!\n   * \\brief Look up a global type definition by its name.\n   * \\param var The name of the global type definition.\n   * \\return The type definition.\n   */\n  TVM_DLL TypeData LookupTypeDef(const String& var) const;\n\n  /*!\n   * \\brief Look up a constructor by its tag.\n   * \\param tag The tag for the constructor.\n   * \\return The constructor object.\n   */\n  TVM_DLL Constructor LookupTag(const int32_t tag);\n\n  /*!\n   * \\brief Update the functions inside this environment by\n   *        functions in another environment.\n   * \\param other The other environment.\n   */\n  TVM_DLL void Update(const IRModule& other);\n\n  /*!\n   * \\brief Create a shallow copy of this IRModule.\n   * \\returns The shallow copy of the IRModule.\n   */\n  TVM_DLL IRModule ShallowCopy();\n\n  /*!\n   * \\brief Import Relay code from the file at path.\n   * \\param path The path of the Relay code to import.\n   *\n   * \\note The path resolution behavior is standard,\n   * if abosolute will be the absolute file, if\n   * relative it will be resovled against the current\n   * working directory.\n   */\n  TVM_DLL void Import(const String& path);\n\n  /*!\n   * \\brief Import Relay code from the file at path, relative to the standard library.\n   * \\param path The path of the Relay code to import.\n   */\n  TVM_DLL void ImportFromStd(const String& path);\n\n  /*!\n   * \\brief Should Link Parameters into the module\n   * \\return Whether the Executor is configured to execute with linked parameters (Default: false)\n   */\n  TVM_DLL Bool ShouldLinkParameters() const;\n\n  /*!\n   * \\brief The set of imported files.\n   */\n  TVM_DLL std::unordered_set<String> Imports() const;\n\n  static constexpr const char* _type_key = \"IRModule\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(IRModuleNode, Object);\n\n private:\n  /*! \\brief Helper function for registering a typedef's constructors */\n  void RegisterConstructors(const GlobalTypeVar& var, const TypeData& type);\n\n  /*! \\brief A map from string names to global variables that\n   * ensures global uniqueness.\n   */\n  Map<String, GlobalVar> global_var_map_;\n\n  /*! \\brief A map from string names to global type variables (ADT names)\n   * that ensures global uniqueness.\n   */\n  Map<String, GlobalTypeVar> global_type_var_map_;\n\n  /*! \\brief A map from constructor tags to constructor objects\n   * for convenient access\n   */\n  std::unordered_map<int32_t, Constructor> constructor_tag_map_;\n\n  /*! \\brief The files previously imported, required to ensure\n      importing is idempotent for each module.\n   */\n  std::unordered_set<String> import_set_;\n  friend class IRModule;\n};\n\n/*!\n * \\brief Managed reference class to IRModuleNode.\n * \\sa IRModuleNode\n */\nclass IRModule : public ObjectRef {\n public:\n  /*!\n   * \\brief constructor\n   * \\param functions Functions in the module.\n   * \\param type_definitions Type definitions in the module.\n   * \\param import_set Set of imported files in the module.\n   * \\param map The module source map.\n   * \\param attrs The module attributes.\n   */\n  TVM_DLL explicit IRModule(Map<GlobalVar, BaseFunc> functions,\n                            Map<GlobalTypeVar, TypeData> type_definitions = {},\n                            std::unordered_set<String> import_set = {}, parser::SourceMap map = {},\n                            DictAttrs attrs = {});\n\n  /*! \\brief default constructor */\n  IRModule() : IRModule(Map<GlobalVar, BaseFunc>({})) {}\n  /*!\n   * \\brief constructor\n   * \\param n The object pointer.\n   */\n  explicit IRModule(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*! \\return mutable pointers to the node. */\n  IRModuleNode* operator->() const {\n    auto* ptr = get_mutable();\n    ICHECK(ptr != nullptr);\n    return static_cast<IRModuleNode*>(ptr);\n  }\n\n  /*!\n   * \\brief Constructs a module from a standalone expression \\p expr.\n   *\n   * If \\p expr is a function it will be bound directly. Otherwise a function over the free\n   * variables of \\p expr (possibly none) with \\p expr as body is created and bound.\n   *\n   * The function is bound to, in preference order:\n   *  - The \"global_symbol\" attribute of \\p expr, if it is a function with that attribute.\n   *  - 'main'\n   *  - A unique name derived from 'main' if 'main' is already bound in \\p global_funcs.\n   *\n   * Additional global functions and type definitions may be included in the result module.\n   *\n   * See also \\p FromExpr.\n   *\n   * \\param expr The expression to set as the main function to the module.\n   * \\param global_funcs The global function map. Default empty.\n   * \\param type_definitions The global type definition map. Default empty.\n   * \\param import_set Set of external modules already imported. Default empty.\n   *\n   * \\returns A module with \\p expr set as the main function, and the global var to which\n   * \\p expr was bound (typcially 'main').\n   *\n   * TODO(mbs): Does import_set and the bound global var need to be exposed via ffi?\n   */\n  static std::pair<IRModule, GlobalVar> FromExprInContext(\n      const RelayExpr& expr, const Map<GlobalVar, BaseFunc>& global_funcs = {},\n      const Map<GlobalTypeVar, TypeData>& type_definitions = {},\n      std::unordered_set<String> import_set = {});\n\n  /*!\n   * \\brief As for \\p FromExprInContext, but assuming \\p expr is bound to 'main' and no\n   * imports.\n   */\n  TVM_DLL static IRModule FromExpr(const RelayExpr& expr,\n                                   const Map<GlobalVar, BaseFunc>& global_funcs = {},\n                                   const Map<GlobalTypeVar, TypeData>& type_definitions = {});\n\n  /*!\n   * \\brief Parse text format source file into an IRModule.\n   * \\param text A string of Relay source code.\n   * \\param source_path The path to the source file.\n   * \\return A Relay module.\n   */\n  TVM_DLL static IRModule FromText(const String& text, const String& source_path);\n\n  /*!\n   * \\brief Create a shallow copy of an IRModule.\n   * \\param mod The module to copy.\n   * \\return The copied module.\n   */\n  IRModule ShallowCopyIRModule(IRModule mod);\n\n  /*! \\brief Declare the container type. */\n  using ContainerType = IRModuleNode;\n\n  /*! \\brief Declare whether Ref is nullable. */\n  static constexpr bool _type_is_nullable = false;\n\n  // allow copy on write.\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IRModuleNode);\n};\n\n/*!\n * \\brief Pretty print a node for debug purposes.\n *\n * \\param node The node to be printed.\n * \\return The text reperesentation.\n * \\note This function does not show version or meta-data.\n *       Use AsText if you want to store the text.\n * \\sa AsText.\n */\nTVM_DLL String PrettyPrint(const ObjectRef& node);\n\n/*!\n * \\brief Render the node as a string in the text format.\n *\n * \\param node The node to be rendered.\n * \\param show_meta_data Whether to print meta data section.\n * \\param annotate An optional callback function for attaching\n *        additional comment block to an expr.\n *\n * \\note We support a limited set of IR nodes that are part of\n *       relay IR and\n *\n * \\sa PrettyPrint.\n * \\return The text representation.\n */\nTVM_DLL String AsText(const ObjectRef& node, bool show_meta_data = true,\n                      runtime::TypedPackedFunc<String(ObjectRef)> annotate = nullptr);\n\nnamespace attr {\n\n// Following are attributes for IRModule only.\n\n/*!\n * \\brief Name of the module\n *\n * Type: String\n *\n * \\sa tvm::runtime::String\n */\nconstexpr const char* kModuleName = \"mod_name\";\n\n/*!\n * \\brief Executor targeted by the module\n *\n * Type: Executor\n *\n * \\sa tvm::relay::Executor\n */\nconstexpr const char* kExecutor = \"executor\";\n\n/*!\n * \\brief Runtime target of the module\n *\n * Type: Runtime\n *\n * \\sa tvm::relay::Runtime\n */\nconstexpr const char* kRuntime = \"runtime\";\n\n/*!\n * \\brief workspace memory pools of the module\n *\n * Type: WorkspaceMemoryPools\n *\n * \\sa tvm::WorkspaceMemoryPools\n */\nconstexpr const char* kWorkspaceMemoryPools = \"workspace_memory_pools\";\n\n/*!\n * \\brief constant memory pools of the module\n *\n * Type: ConstantMemoryPools\n *\n * \\sa tvm::ConstantMemoryPools\n */\nconstexpr const char* kConstantMemoryPools = \"constant_memory_pools\";\n\n/*\n * \\brief All the runtime::NDArrays extracted from PrimFunc tir::AllocateConst nodes. The\n * node will record the index into this array. See also kConstNameToConstant below, which is\n * the analog for Realy Functions.\n *\n * Type: Array<runtime::NDArray>\n */\nconstexpr const char* kConstants = \"constants\";\n\n/*!\n * \\brief All the runtime::Modules accumulated during compilation by external codegen. These\n * modules must be either directly linked or captured in the final compilation artifact.\n *\n * Type: Array<runtime::Module>\n */\nconstexpr const char* kExternalMods = \"external_mods\";\n\n/*!\n * \\brief All the named runtime::NDArrays accumulated during compilation by external codegen.\n * Generally the associated runtime::Module will indicate it requires bindings for these names,\n * and during module initialization these bindings will be recovered from a ConstLoaderModule.\n * See also kConstantsArray above, which is the analog for PrimFuncs.\n *\n * Type: Map<String, runtime::NDArray>\n */\nconstexpr const char* kConstNameToConstant = \"const_name_to_constant\";\n\n}  // namespace attr\n}  // namespace tvm\n#endif  // TVM_IR_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/name_supply.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/name_supply.h\n * \\brief NameSupply that can be used to generate unique variable names.\n */\n#ifndef TVM_IR_NAME_SUPPLY_H_\n#define TVM_IR_NAME_SUPPLY_H_\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include \"tvm/ir/expr.h\"\n\nnamespace tvm {\n\n/*!\n * \\brief NameSupply can be used to generate unique names.\n */\nclass NameSupplyNode : public Object {\n public:\n  /*!\n   * \\brief Empty constructor. Needed by the TVM_REGISTER_NODE_TYPE macro.\n   */\n  NameSupplyNode() = default;\n\n  /*!\n   * \\brief Constructor.\n   * \\param prefix The prefix to be used with this NameSupply.\n   * \\param name_map The map used to guarantee uniqueness.\n   */\n  NameSupplyNode(const String& prefix, std::unordered_map<std::string, int> name_map)\n      : prefix_(prefix), name_map(std::move(name_map)) {}\n\n  /*!\n   * \\brief Generates a unique name from this NameSupply.\n   * \\param name The name from which the generated name is derived.\n   * \\param add_prefix If set to true, then the prefix of this NameSupply will be prepended to the\n   * name. \\return A unique name.\n   */\n  String FreshName(const String& name, bool add_prefix = true);\n\n  /*!\n   * \\brief Reserves an existing name with this NameSupply.\n   * \\param name The name to be reserved.\n   * \\param add_prefix If set to true, then the prefix of this NameSupply will be prepended to the\n   * name before reserving it. \\return The name that was reserved with the NameSupply. It can be\n   * different if a prefix is added.\n   */\n  String ReserveName(const String& name, bool add_prefix = true);\n\n  /*!\n   * \\brief Checks if this NameSupply already generated a name.\n   * \\param name The name to check.\n   * \\param add_prefix If set to true, then the prefix of this NameSupply will be prepended to the\n   * name before checking for it. \\return True if the name has already been generated. False\n   * otherwise.\n   */\n  bool ContainsName(const String& name, bool add_prefix = true);\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  // Prefix for all GlobalVar names. It can be empty.\n  std::string prefix_;\n\n  static constexpr const char* _type_key = \"NameSupply\";\n  static constexpr const bool _type_has_method_sequal_reduce = false;\n  static constexpr const bool _type_has_method_shash_reduce = false;\n  TVM_DECLARE_FINAL_OBJECT_INFO(NameSupplyNode, Object);\n\n private:\n  /*! \\brief Helper function to add the NameSupply prefix to the name. */\n  String add_prefix_to_name(const String& name);\n\n  /*!\n   * \\brief Function that will generate a unique name.\n   * \\param name The name to be used as a base.\n   * \\return A unique name.\n   */\n  std::string GetUniqueName(std::string name);\n\n  /*! \\brief A map that is used to generate unique names. */\n  std::unordered_map<std::string, int> name_map;\n};\n\n/*!\n * \\brief Managed reference class to NameSupplyNode.\n * \\sa NameSupplyNode\n */\nclass NameSupply : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param prefix The prefix to be used with this NameSupply.\n   * \\param name_map An optional map.\n   */\n  TVM_DLL explicit NameSupply(const String& prefix,\n                              std::unordered_map<std::string, int> name_map = {});\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(NameSupply, ObjectRef, NameSupplyNode);\n};\n\n}  // namespace tvm\n\n#endif  // TVM_IR_NAME_SUPPLY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/op.h\n * \\brief Primitive operators(builtin intrinsics)\n *        and registry for them.\n */\n#ifndef TVM_IR_OP_H_\n#define TVM_IR_OP_H_\n\n#include <dmlc/registry.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n#include <tvm/ir/type_relation.h>\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/runtime/registry.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\n// forward declare name.\ntemplate <typename>\nclass OpAttrMap;\n\n// TODO(tvm-team): migrate low-level intrinsics to use Op\n/*!\n * \\brief Primitive Op(builtin intrinsics)\n *\n * This data structure stores the meta-data\n * about primitive operators that can be invoked via Call.\n *\n * Low-level IR intrinsics(such as libc.expf) are also\n * implemented via Op.\n *\n * \\sa Op\n */\nclass OpNode : public RelayExprNode {\n public:\n  /*! \\brief name of the operator */\n  String name;\n  /*! \\brief the type of the operator */\n  mutable FuncType op_type;\n  /*!\n   * \\brief detailed description of the operator\n   *  This can be used to generate docstring automatically for the operator.\n   */\n  String description;\n  /* \\brief Information of input arguments to the operator */\n  Array<AttrFieldInfo> arguments;\n  /*!\n   * \\brief The type key of the attribute field\n   *  This can be empty, in which case it defaults to anything.\n   */\n  String attrs_type_key;\n  /*!\n   * \\brief attribute type index,\n   * this field varies in each run and is not exposed to frontend.\n   */\n  uint32_t attrs_type_index{0};\n  /*!\n   * \\brief number of input arguments to the operator,\n   * -1 means it is variable length\n   */\n  int32_t num_inputs = -1;\n  /*!\n   * \\brief support level of the operator,\n   *  The lower the more priority it contains.\n   *  This is in analogies to BLAS levels.\n   */\n  int32_t support_level = 10;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"op_type\", &op_type);\n    v->Visit(\"description\", &description);\n    v->Visit(\"arguments\", &arguments);\n    v->Visit(\"attrs_type_key\", &attrs_type_key);\n    v->Visit(\"num_inputs\", &num_inputs);\n    v->Visit(\"support_level\", &support_level);\n  }\n\n  bool SEqualReduce(const OpNode* other, SEqualReducer equal) const {\n    // pointer equality is fine as there is only one op with the same name.\n    return this == other;\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    // Name uniquely identifies an Op.\n    hash_reduce(name);\n  }\n\n  /*!\n   * \\brief Check that if current op is a \"primtive operator\".\n   * That is the arguments are all type variables, and there is a single\n   * type relation applied to the input and output types.\n   */\n  bool IsPrimitiveOp() const {\n    if (is_primitive_ != -1) return is_primitive_ != 0;\n    is_primitive_ = this->IsPrimitiveOp_() ? 1 : 0;\n    return is_primitive_ != 0;\n  }\n\n  static constexpr const char* _type_key = \"Op\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpNode, RelayExprNode);\n\n private:\n  /*! \\return the internal attr registry index. */\n  uint32_t AttrRegistryIndex() const { return index_; }\n  /*! \\brief repr to be printed in registry*/\n  std::string AttrRegistryName() const { return name; }\n\n  // friend class\n  template <typename>\n  friend class AttrRegistryMapContainerMap;\n  template <typename, typename>\n  friend class AttrRegistry;\n  friend class OpRegEntry;\n\n  friend bool IsPrimitiveOp(const RelayExpr&);\n  // Program internal unique index of operator.\n  // Used to help index the program.\n  uint32_t index_{0};\n  // whether this is a primitive op. -1 means unknown.\n  mutable int is_primitive_{-1};\n  // Internal function to compute if it is primitive op\n  bool IsPrimitiveOp_() const {\n    const auto& fn_ty = this->op_type;\n    ICHECK(fn_ty.get() != nullptr) << \"op_type of \" << this->name << \" is not registered\";\n    if (fn_ty->type_constraints.size() != 1) return false;\n    const TypeRelationNode* rel = fn_ty->type_constraints[0].as<TypeRelationNode>();\n    if (rel == nullptr) return false;\n    // validate if the type parameter matches up\n    for (size_t i = 0; i < fn_ty->type_params.size(); ++i) {\n      if (!fn_ty->type_params[i].same_as(rel->args[i])) return false;\n    }\n    return true;\n  }\n};\n\n/*!\n * \\brief Managed reference class to OpNode.\n * \\sa OpNode\n */\nclass Op : public RelayExpr {\n public:\n  /*!\n   * \\brief Get additional registered attribute about operators.\n   *  If nothing has been registered, an empty OpAttrMap will be returned.\n   * \\param attr_name The name of the attribute.\n   * \\return An OpAttrMap of specified attr_name.\n   * \\tparam ValueType The type of the attribute.\n   */\n  template <typename ValueType>\n  inline static OpAttrMap<ValueType> GetAttrMap(const String& attr_name);\n  /*!\n   * \\brief Checks if an attr map is present in the registry.\n   * \\param attr_name The name of the attribute.\n   * \\return bool True if the attr is present.\n   */\n  TVM_DLL static bool HasAttrMap(const String& attr_name);\n  /*!\n   * \\brief Get an Op for a given operator name.\n   *  Will raise an error if the op has not been registered.\n   * \\param op_name Name of the operator.\n   * \\return Pointer to a Op, valid throughout program lifetime.\n   */\n  TVM_DLL static const Op& Get(const String& op_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Op, RelayExpr, OpNode)\n\n private:\n  /*!\n   * \\brief Get generic attrmap given attr name\n   * \\param key The attribute key\n   * \\return The attr map.\n   */\n  TVM_DLL static const AttrRegistryMapContainerMap<Op>& GetAttrMapContainer(const String& key);\n};\n\n/*!\n * \\brief Helper structure to register operators\n * \\sa TVM_REGISTER_OP\n */\nclass OpRegEntry {\n public:\n  /*! \\return the operator */\n  const Op& op() const { return op_; }\n  /*!\n   * \\brief setter function during registration\n   *  Set the description of operator\n   * \\param descr the description string.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& describe(const std::string& descr);  // NOLINT(*)\n  /*!\n   * \\brief Add argument information to the function.\n   * \\param name Name of the argument.\n   * \\param type Type of the argument.\n   * \\param description Description of the argument.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& add_argument(const std::string& name, const std::string& type,\n                                  const std::string& description);\n  /*!\n   * \\brief Attach the type function corresponding to the return type.\n   * \\param rel_name The type relation name to register.\n   * \\param type_rel_func The backing relation function which can solve an arbitrary\n   * relation on variables.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& add_type_rel(\n      const std::string& rel_name,\n      runtime::TypedPackedFunc<bool(const Array<Type>&, int, const Attrs&, const TypeReporter&)>\n          type_rel_func);\n  /*!\n   * \\brief Set the attrs type key and index to be AttrsType.\n   * \\tparam AttrsType the attribute type to b set.\n   * \\return reference to self.\n   */\n  template <typename AttrsType>\n  inline OpRegEntry& set_attrs_type();\n  /*!\n   * \\brief Set the attrs type key and index to be AttrsType.\n   * \\param key The attribute type key to be set.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& set_attrs_type_key(const String& key);\n  /*!\n   * \\brief Set the num_inputs\n   * \\param n The number of inputs to be set.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& set_num_inputs(int32_t n);  // NOLINT(*)\n  /*!\n   * \\brief Set the support level of op.\n   * \\param level The support level.\n   * \\return reference to self.\n   */\n  inline OpRegEntry& set_support_level(int32_t level);  // NOLINT(*)\n  /*!\n   * \\brief Register additional attributes to operator.\n   * \\param attr_name The name of the attribute.\n   * \\param value The value to be set.\n   * \\param plevel The priority level of this set,\n   *  an higher priority level attribute\n   *  will replace lower priority level attribute.\n   *  Must be bigger than 0.\n   *\n   *  Cannot set with same plevel twice in the code.\n   *\n   * \\tparam ValueType The type of the value to be set.\n   */\n  template <typename ValueType>\n  inline OpRegEntry& set_attr(const std::string& attr_name,  // NOLINT(*)\n                              const ValueType& value, int plevel = 10);\n\n  /*!\n   * \\brief Resets an attr of the registry.\n   * \\param attr_name The name of the attribute.\n   */\n  inline void reset_attr(const std::string& attr_name);\n\n  // set the name of the op to be the same as registry\n  inline OpRegEntry& set_name() {  // NOLINT(*)\n    if (get()->name.length() == 0) {\n      get()->name = name;\n    }\n    return *this;\n  }\n  /*!\n   * \\brief Register or get a new entry.\n   * \\param name The name of the operator.\n   * \\return the corresponding entry.\n   */\n  TVM_DLL static OpRegEntry& RegisterOrGet(const String& name);\n\n private:\n  template <typename, typename>\n  friend class AttrRegistry;\n  // the name\n  std::string name;\n  /*! \\brief The operator */\n  Op op_;\n  // private constructor\n  TVM_DLL OpRegEntry(uint32_t reg_index);\n  // return internal pointer to op.\n  inline OpNode* get();\n  // update the attribute OpAttrMap\n  TVM_DLL void UpdateAttr(const String& key, runtime::TVMRetValue value, int plevel);\n};\n\n/*!\n * \\brief Map<Op,ValueType> used to store meta-information about Op.\n * \\tparam ValueType The type of the value stored in map.\n */\ntemplate <typename ValueType>\nclass OpAttrMap : public AttrRegistryMap<Op, ValueType> {\n public:\n  /*!\n   * \\brief get the corresponding value element at op with default value.\n   * \\param expr The key to the map\n   * \\param def_value The default value when the key does not exist\n   *         or if expr is not an Op.\n   * \\return the const reference to the content value.\n   */\n  inline ValueType get(const RelayExpr& expr, ValueType def_value) const;\n\n  using TParent = AttrRegistryMap<Op, ValueType>;\n  using TParent::count;\n  using TParent::get;\n  using TParent::operator[];\n\n private:\n  friend class Op;\n  // constructor\n  explicit OpAttrMap(const AttrRegistryMapContainerMap<Op>& map) : TParent(map) {}\n};\n\n// internal macros to make\n#define TVM_OP_REGISTER_VAR_DEF static DMLC_ATTRIBUTE_UNUSED ::tvm::OpRegEntry& __make_##Op\n\n/*!\n * \\def TVM_REGISTER_OP\n * \\brief Register a new operator, or set attribute of the corresponding op.\n *\n * \\param OpName The name of registry\n *\n * \\code\n *\n *  TVM_REGISTER_OP(\"add\")\n *  .describe(\"add two inputs together\")\n *  .set_num_inputs(2)\n *  .set_attr<OpKernel>(\"gpu_kernel\", AddKernel);\n *\n * \\endcode\n */\n#define TVM_REGISTER_OP(OpName)                          \\\n  TVM_STR_CONCAT(TVM_OP_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::OpRegEntry::RegisterOrGet(OpName).set_name()\n\n// implementations\n\ntemplate <typename ValueType>\ninline OpAttrMap<ValueType> Op::GetAttrMap(const String& key) {\n  return OpAttrMap<ValueType>(Op::GetAttrMapContainer(key));\n}\n\ninline OpNode* OpRegEntry::get() { return const_cast<OpNode*>(op_.operator->()); }\n\ninline OpRegEntry& OpRegEntry::describe(const std::string& descr) {  // NOLINT(*)\n  get()->description = descr;\n  return *this;\n}\n\ninline OpRegEntry& OpRegEntry::add_argument(const std::string& name, const std::string& type,\n                                            const std::string& description) {\n  auto n = make_object<AttrFieldInfoNode>();\n  n->name = name;\n  n->type_info = type;\n  n->description = description;\n  get()->arguments.push_back(AttrFieldInfo(n));\n  return *this;\n}\n\ninline OpRegEntry& OpRegEntry::add_type_rel(\n    const std::string& rel_name,\n    runtime::TypedPackedFunc<bool(const Array<Type>&, int, const Attrs&, const TypeReporter&)>\n        type_rel_func) {\n  auto func_name = std::string(\"tvm.relay.type_relation.\") + rel_name;\n  TypeRelationFn env_type_rel_func;\n\n  if (runtime::Registry::Get(func_name)) {\n    auto env_func = EnvFunc::Get(func_name);\n    env_type_rel_func = env_func;\n  } else {\n    runtime::Registry::Register(func_name).set_body(type_rel_func.packed());\n    auto env_func = EnvFunc::Get(func_name);\n    env_type_rel_func = env_func;\n  }\n\n  Array<TypeVar> type_params;\n  Array<Type> arg_types;\n\n  // Add inputs.\n  std::string input_name_prefix = \"in\";\n  for (int i = 0; i < get()->num_inputs; i++) {\n    auto name = input_name_prefix + std::to_string(i);\n    auto param = TypeVar(name, TypeKind::kType);\n    type_params.push_back(param);\n    arg_types.push_back(param);\n  }\n\n  Array<Type> ty_call_args = arg_types;\n\n  // Add output type.\n  auto out_param = TypeVar(\"out\", TypeKind::kType);\n  type_params.push_back(out_param);\n  // this will trigger copy on write.\n  ty_call_args.push_back(out_param);\n\n  // The attributes of primitive op is nullptr\n  //\n  // The attributes of primitive operator can vary at the call site.\n  // The type of sum is also dependent on Attrs being passed.\n  // So puting nullptr in the Attrs means that the operator is polymorphic on Attrs.\n  //\n  // A common example is sum(x, axis), where the choice of axis\n  // can affect the type of the function.\n  TypeConstraint type_rel =\n      TypeRelation(env_type_rel_func, ty_call_args, arg_types.size(), Attrs());\n\n  auto func_type = FuncType(arg_types, out_param, type_params, {type_rel});\n\n  get()->op_type = func_type;\n\n  return *this;\n}\n\ninline OpRegEntry& OpRegEntry::set_num_inputs(int32_t n) {  // NOLINT(*)\n  get()->num_inputs = n;\n  return *this;\n}\n\ntemplate <typename AttrsType>\ninline OpRegEntry& OpRegEntry::set_attrs_type() {  // NOLINT(*)\n  get()->attrs_type_key = AttrsType::_type_key;\n  get()->attrs_type_index = AttrsType::RuntimeTypeIndex();\n  return *this;\n}\n\ninline OpRegEntry& OpRegEntry::set_attrs_type_key(const String& key) {  // NOLINT(*)\n  get()->attrs_type_key = key;\n  get()->attrs_type_index = Object::TypeKey2Index(key);\n  return *this;\n}\n\ninline OpRegEntry& OpRegEntry::set_support_level(int32_t n) {  // NOLINT(*)\n  get()->support_level = n;\n  return *this;\n}\n\ntemplate <typename ValueType>\ninline OpRegEntry& OpRegEntry::set_attr(  // NOLINT(*)\n    const std::string& attr_name, const ValueType& value, int plevel) {\n  ICHECK_GT(plevel, 0) << \"plevel in set_attr must be greater than 0\";\n  runtime::TVMRetValue rv;\n  rv = value;\n  UpdateAttr(attr_name, rv, plevel);\n  return *this;\n}\n\n// member functions of OpAttrMap\n\ntemplate <typename ValueType>\ninline ValueType OpAttrMap<ValueType>::get(const RelayExpr& expr, ValueType def_value) const {\n  ICHECK(expr.defined());\n  if (const OpNode* op = expr.as<OpNode>()) {\n    return this->map_.get(GetRef<Op>(op), def_value);\n  } else {\n    return def_value;\n  }\n}\n\n/*!\n * \\brief Check that an expression is a \"primitive operator\".\n *\n * Will return true if the expression is an operator which\n * matches the form of primitive operators registered directly\n * by the Relay codebase.\n *\n * That is the arguments are all type variables, and there is a single\n * type relation applied to the input and output types.\n *\n * \\param expr An expression.\n * \\return Whether the expression is primitive op.\n */\ninline bool IsPrimitiveOp(const RelayExpr& expr) {\n  const auto* op = expr.as<OpNode>();\n  return op != nullptr && op->IsPrimitiveOp();\n}\n\n}  // namespace tvm\n#endif  // TVM_IR_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/span.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/span.h\n * \\brief Span information for debugging purposes.\n */\n#ifndef TVM_IR_SPAN_H_\n#define TVM_IR_SPAN_H_\n\n#include <tvm/node/node.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n\nnamespace tvm {\n/*!\n * \\brief The source name in the Span\n * \\sa SourceNameNode, Span\n */\nclass SourceName;\n/*!\n * \\brief The name of a source fragment.\n */\nclass SourceNameNode : public Object {\n public:\n  /*! \\brief The source name. */\n  String name;\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"name\", &name); }\n\n  static constexpr bool _type_has_method_sequal_reduce = true;\n\n  bool SEqualReduce(const SourceNameNode* other, SEqualReducer equal) const {\n    return equal(name, other->name);\n  }\n\n  static constexpr const char* _type_key = \"SourceName\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SourceNameNode, Object);\n};\n\n/*!\n * \\brief The source name of a file span.\n * \\sa SourceNameNode, Span\n */\nclass SourceName : public ObjectRef {\n public:\n  /*!\n   * \\brief Get an SourceName for a given operator name.\n   *  Will raise an error if the source name has not been registered.\n   * \\param name Name of the operator.\n   * \\return SourceName valid throughout program lifetime.\n   */\n  TVM_DLL static SourceName Get(const String& name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SourceName, ObjectRef, SourceNameNode);\n};\n\n/*!\n * \\brief Span information for debugging purposes\n */\nclass Span;\n/*!\n * \\brief Stores locations in frontend source that generated a node.\n */\nclass SpanNode : public Object {\n public:\n  /*! \\brief The source name. */\n  SourceName source_name;\n  /*! \\brief The line number. */\n  int line;\n  /*! \\brief The column offset. */\n  int column;\n  /*! \\brief The end line number. */\n  int end_line;\n  /*! \\brief The end column number. */\n  int end_column;\n\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"source_name\", &source_name);\n    v->Visit(\"line\", &line);\n    v->Visit(\"column\", &column);\n    v->Visit(\"end_line\", &end_line);\n    v->Visit(\"end_column\", &end_column);\n  }\n  static constexpr bool _type_has_method_sequal_reduce = true;\n\n  bool SEqualReduce(const SpanNode* other, SEqualReducer equal) const {\n    return equal(source_name, other->source_name) && equal(line, other->line) &&\n           equal(column, other->column) && equal(end_line, other->end_line) &&\n           equal(end_column, other->end_column);\n  }\n\n  static constexpr const char* _type_key = \"Span\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SpanNode, Object);\n};\n\nclass Span : public ObjectRef {\n public:\n  TVM_DLL Span(SourceName source_name, int line, int end_line, int column, int end_column);\n\n  /*! \\brief Merge two spans into one which captures the combined regions. */\n  TVM_DLL Span Merge(const Span& other) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Span, ObjectRef, SpanNode);\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_SPAN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/tensor_type.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/tensor_type.h\n * \\brief Polymorphic tensor types.\n */\n#ifndef TVM_IR_TENSOR_TYPE_H_\n#define TVM_IR_TENSOR_TYPE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n\nnamespace tvm {\n/*!\n * \\brief Base of all Tensor types\n *  This container can hold TensorType or GenericTensorType.\n * \\sa BaseTensorType, TensorTypeNode\n */\nclass BaseTensorTypeNode : public TypeNode {\n public:\n  static constexpr const char* _type_key = \"relay.BaseTensorType\";\n  static constexpr const uint32_t _type_child_slots = 1;\n  TVM_DECLARE_BASE_OBJECT_INFO(BaseTensorTypeNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to BaseTensorTypeNode.\n * \\sa BaseTensorTypeNode.\n */\nclass BaseTensorType : public Type {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(BaseTensorType, Type, BaseTensorTypeNode);\n};\n\n/*!\n * \\brief This is the most commonly used type in relay.\n *  TensorType have a fixed dimension, data type.\n *\n *  The elements of shape can be either IntImm(constant integer),\n *  or any symbolic integer expression.\n *  The symbolic integer allows generic shape inference in certain cases.\n * \\sa TensorType\n */\nclass TensorTypeNode : public BaseTensorTypeNode {\n public:\n  /*!\n   * \\brief The shape of the tensor,\n   *  represented by PrimExpr(tvm::Expr).\n   */\n  Array<PrimExpr> shape;\n  /*! \\brief The content data type */\n  DataType dtype;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"shape\", &shape);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TensorTypeNode* other, SEqualReducer equal) const {\n    return equal(shape, other->shape) && equal(dtype, other->dtype);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(shape);\n    hash_reduce(dtype);\n  }\n\n  /*! \\brief Return product of elements in the shape.\n   *  \\return (d1 * d_2 ... * d_n) if shape is (d_1, d_2, ..., d_n) and 1 if shape size is zero.\n   */\n  TVM_DLL PrimExpr Size() const;\n\n  static constexpr const char* _type_key = \"relay.TensorType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorTypeNode, BaseTensorTypeNode);\n};\n\n/*!\n * \\brief Managed reference to TensorTypeNode.\n * \\sa TensorTypeNode.\n */\nclass TensorType : public Type {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param shape The shape of the tensor.\n   * \\param dtype The runtime dtype of the tensor's elements.\n   */\n  TVM_DLL TensorType(Array<PrimExpr> shape, DataType dtype);\n\n  /*!\n   * \\brief Construct an scalar containing elements of dtype.\n   * \\param dtype The runtime dtype of the tensor's elements.\n   * \\return THe constructed type.\n   */\n  TVM_DLL static TensorType Scalar(DataType dtype);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorType, Type, TensorTypeNode);\n};\n\n// The following fields contains advanced typing\n// Only keep the class name and reserved for future usage.\nclass GenericTensorType;\n// stores a DataType.\nclass GenericDataType;\n// stores a DataType.\nclass GenericShape;\n\n}  // namespace tvm\n#endif  // TVM_IR_TENSOR_TYPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/transform.h\n *\n * This file implements a pass manager. The pass manager manages a sequence\n * of IRModule -> IRModule transformation passes over a particlar unit of AST. The\n * design is largely inspired from LLVM's pass manager and modern deep learning\n * frameworks that perform tensor->tensor transformations.\n *\n * The responsibilities of a traditional compiler pass manager usually involves:\n *  - Organizing the execution order of optimization passes though not\n * necessarily in the optimal sequence.\n *  - Collecting required analysis information and keep them up-to-date.\n *  - Reducing the effort required to implement new passes for compiler\n * developers, etc.\n *\n * Similar to LLVM's pass manager, we designed the Relay pass manager to work\n * different granularity, i.e. module level, function level, and even sequential\n * passe that contains a host of passes.\n *\n * However, we also extend the functionality of the traditional pass manager\n * with the consideration of requirements/convention from deep learning\n * frameworks, such as Pytorch and Gluon, etc. Each pass in the Relay pass\n * manager performs the IRModule -> IRModule transformation. All\n * different types of passes, including the sequential-level pass object, are\n * essentially pass objects. This design, therefore, effectively provides users\n * a consistent and convenient interface, i.e. Pass, to play with. It offers a\n * means to ease the development and testing of Relay passes. For example, with\n * the pass manager, external users will be able to have custom passes correctly\n * scheduled without having to modify a single handcrafted pass order.\n *\n * In the future we need to describe constraints between passes. For example,\n * we may want to preserve dependencies between different passes and validate\n * them on the completion of a certain pass.\n *\n * We also need to store side information and import the error reporting system.\n */\n#ifndef TVM_IR_TRANSFORM_H_\n#define TVM_IR_TRANSFORM_H_\n\n#include <tvm/ir/diagnostic.h>\n#include <tvm/ir/error.h>\n#include <tvm/ir/instrument.h>\n#include <tvm/ir/module.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/support/with.h>\n\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace transform {\n\n/*!\n * \\brief PassContextNode contains the information that a pass can rely on,\n * such as analysis results.\n * \\sa PassContext\n */\nclass PassContextNode : public Object {\n public:\n  /*! \\brief The default optimization level. */\n  int opt_level{2};\n\n  /*! \\brief The list of required passes. */\n  Array<String> required_pass;\n  /*! \\brief The list of disabled passes. */\n  Array<String> disabled_pass;\n  /*! \\brief The diagnostic context. */\n  mutable Optional<DiagnosticContext> diag_ctx;\n  /*! \\brief Pass specific configurations. */\n  Map<String, ObjectRef> config;\n\n  /*! \\brief A list of pass instrument implementations. */\n  Array<instrument::PassInstrument> instruments;\n\n  PassContextNode() = default;\n\n  /*!\n   * \\brief Get a config value from the pass context.\n   *\n   * \\param key The config key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TOBjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef.\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetConfig(const std::string& key, Optional<TObjectRef> default_value =\n                                                             Optional<TObjectRef>(nullptr)) const {\n    static_assert(std::is_base_of<ObjectRef, TObjectRef>::value,\n                  \"Can only call GetAttr with ObjectRef types.\");\n    if (!config.defined()) return default_value;\n    auto it = config.find(key);\n    if (it != config.end()) {\n      return Downcast<Optional<TObjectRef>>((*it).second);\n    } else {\n      return default_value;\n    }\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetConfig(const std::string& key, TObjectRef default_value) const {\n    return GetConfig<TObjectRef>(key, Optional<TObjectRef>(default_value));\n  }\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"opt_level\", &opt_level);\n    v->Visit(\"required_pass\", &required_pass);\n    v->Visit(\"disabled_pass\", &disabled_pass);\n    v->Visit(\"instruments\", &instruments);\n    v->Visit(\"config\", &config);\n    v->Visit(\"diag_ctx\", &diag_ctx);\n  }\n\n  static constexpr const char* _type_key = \"transform.PassContext\";\n  static constexpr bool _type_has_method_sequal_reduce = false;\n  TVM_DECLARE_FINAL_OBJECT_INFO(PassContextNode, Object);\n};\n\n/*!\n * \\brief PassContext that is used to configure the pass behavior.\n *\n * \\code\n *\n *  auto new_ctx = PassContext::Create();\n *  ctx->opt_level = 2;\n *  With<PassContext> scope(ctx);\n *  // pass context in effect.\n *\n * \\endcode\n * \\sa PassContextNode\n */\nclass PassContext : public ObjectRef {\n public:\n  PassContext() {}\n  explicit PassContext(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief const accessor.\n   * \\return const access pointer.\n   */\n  const PassContextNode* operator->() const {\n    ICHECK(get() != nullptr);\n    return static_cast<const PassContextNode*>(get());\n  }\n  /*!\n   * \\brief mutable accessor.\n   * \\return mutable access pointer.\n   */\n  PassContextNode* operator->() {\n    ICHECK(get() != nullptr);\n    return static_cast<PassContextNode*>(get_mutable());\n  }\n\n  /*!\n   * \\brief Construct a PassContext containing the default configurations.\n   * \\return The new PassContext.\n   */\n  TVM_DLL static PassContext Create();\n  /*!\n   * \\brief Get the default pass context in the current scope.\n   * \\return The pass context.\n   */\n  TVM_DLL static PassContext Current();\n\n  /*!\n   * \\brief Get all supported configuration names and metadata, registered within the PassContext.\n   * \\return Map indexed by the config name, pointing to the metadata map as key-value\n   */\n  TVM_DLL static Map<String, Map<String, String>> ListConfigs();\n\n  /*!\n   * \\brief Call instrument implementations' callbacks when entering PassContext.\n   *        The callbacks are called in order, and if one raises an exception, the rest will not be\n   *        called.\n   */\n  TVM_DLL void InstrumentEnterPassContext();\n\n  /*!\n   * \\brief Call instrument implementations' callbacks when exiting PassContext.\n   *        The callbacks are called in order, and if one raises an exception, the rest will not be\n   *        called.\n   */\n  TVM_DLL void InstrumentExitPassContext();\n\n  /*!\n   * \\brief Call instrument implementations' callbacks before a pass run.\n   *        The callbacks are called in order, and if one raises an exception, the rest will not be\n   *        called.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   * \\param info The pass information.\n   *\n   * \\return false: the pass is skipped; true: the pass runs.\n   */\n  TVM_DLL bool InstrumentBeforePass(const IRModule& mod, const PassInfo& info) const;\n\n  /*!\n   * \\brief Call instrument implementations callbacks after a pass run.\n   *        The callbacks are called in order, and if one raises an exception, the rest will not be\n   *        called.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   * \\param info The pass information.\n   */\n  TVM_DLL void InstrumentAfterPass(const IRModule& mod, const PassInfo& info) const;\n\n  /*!\n   * \\brief Check whether a pass is enabled.\n   * \\param info The pass information.\n   * \\return true if the pass is enabled. Otherwise, false.\n   */\n  TVM_DLL bool PassEnabled(const PassInfo& info) const;\n\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation.\n   *\n   * \\param key The configuration key.\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  static uint32_t RegisterConfigOption(const char* key) {\n    using ValueNodeType = typename ValueType::ContainerType;\n    // NOTE: we could further update the function later.\n    uint32_t tindex = ValueNodeType::_GetOrAllocRuntimeTypeIndex();\n    RegisterConfigOption(key, tindex);\n    return tindex;\n  }\n\n  // accessor.\n  using ContainerType = PassContextNode;\n  class Internal;\n\n private:\n  // The entry of a pass context scope.\n  TVM_DLL void EnterWithScope();\n  // The exit of a pass context scope.\n  TVM_DLL void ExitWithScope();\n  // Register configuration key value type.\n  TVM_DLL static void RegisterConfigOption(const char* key, uint32_t value_type_index);\n\n  // Classes to get the Python `with` like syntax.\n  friend class Internal;\n  friend class With<PassContext>;\n};\n\n#define TVM_PASS_CTX_CONFIG_VAR_DEF static TVM_ATTRIBUTE_UNUSED uint32_t __make_PassContext_tid\n\n/*!\n * \\brief Helper macro to register the object type to runtime.\n *  Makes sure that the runtime type table is correctly populated.\n *\n *  Use this macro in the cc file for each terminal class.\n */\n#define TVM_REGISTER_PASS_CONFIG_OPTION(Key, ValueType)      \\\n  TVM_STR_CONCAT(TVM_PASS_CTX_CONFIG_VAR_DEF, __COUNTER__) = \\\n      ::tvm::transform::PassContext::RegisterConfigOption<ValueType>(Key)\n\n/*!\n * \\brief Meta data that will be used to help optimization and analysis.\n * \\sa PassInfo\n */\nclass PassInfoNode : public Object {\n public:\n  /*! \\brief The minimal optimization level that this pass will be enabled. */\n  int opt_level;\n\n  /*! \\brief The name of an optimization/analysis pass. */\n  String name;\n\n  /*! \\brief The passes that are required to perform the current pass. */\n  Array<String> required;\n\n  PassInfoNode() = default;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"opt_level\", &opt_level);\n    v->Visit(\"name\", &name);\n    v->Visit(\"required\", &required);\n  }\n\n  static constexpr const char* _type_key = \"transform.PassInfo\";\n  static constexpr bool _type_has_method_sequal_reduce = false;\n  TVM_DECLARE_FINAL_OBJECT_INFO(PassInfoNode, Object);\n};\n\n/*!\n * \\brief Managed reference class for PassInfoNode\n * \\sa PassInfoNode\n */\nclass PassInfo : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param opt_level The optimization level\n   * \\param name Name of the pass.\n   * \\param required  The passes that are required to perform the current pass.\n   */\n  TVM_DLL PassInfo(int opt_level, String name, Array<runtime::String> required);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PassInfo, ObjectRef, PassInfoNode);\n};\n\n/*!\n * \\brief PassNode is the base type of differnt types of optimization passes.\n * It is designed as a pure class and implemented by different pass subclasses\n * at different granularity of Relay nodes.\n */\nclass PassNode : public Object {\n public:\n  virtual ~PassNode() {}\n  /*!\n   * \\brief Get the pass information/meta data. */\n  virtual PassInfo Info() const = 0;\n\n  /*!\n   * \\brief Transform mod using the default PassContext in the current scope.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   *\n   * \\return The transformed module.\n   */\n  IRModule operator()(IRModule mod) const {\n    return this->operator()(std::move(mod), PassContext::Current());\n  }\n\n  /*!\n   * \\brief Transform mod using a functor under a given pass context.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   * \\param pass_ctx The pass context that can provide information for the optimization.\n   *\n   * \\return The transformed module.\n   */\n  virtual IRModule operator()(IRModule mod, const PassContext& pass_ctx) const = 0;\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"transform.Pass\";\n  TVM_DECLARE_BASE_OBJECT_INFO(PassNode, Object);\n};\n\nclass Pass : public ObjectRef {\n public:\n  /*!\n   * \\brief Transform mod using the default PassContext in the current scope.\n   *\n   * \\code\n   *\n   * // If you do no longer need the input module\n   * // it is recommended to use std::move to move your input module.\n   * mod = pass(std::move(mod));\n   *\n   * \\endcode\n   *\n   * \\param mod The module that an optimization pass runs on.\n   *\n   * \\return The transformed module.\n   */\n  IRModule operator()(IRModule mod) const;\n\n  /*!\n   * \\brief Transform mod using a functor under a given pass context.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   * \\param pass_ctx The pass context that can provide information for the optimization.\n   *\n   * \\return The transformed module.\n   */\n  IRModule operator()(IRModule mod, const PassContext& pass_ctx) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Pass, ObjectRef, PassNode);\n\n private:\n  IRModule static AssertImmutableModule(const IRModule& mod, const PassNode* node,\n                                        const PassContext& pass_ctx);\n};\n\n/*!\n * \\brief The SequentialNode contains a set of passes that transform Relay\n * programs from one AST to another semantically equivalent one.\n *\n * One example of this level of pass is that the pass manager needs to correctly\n * perform a host of optimizations with a given optimization level and disabled\n * passes.\n */\nclass SequentialNode : public PassNode {\n public:\n  /* \\brief The pass meta data.*/\n  PassInfo pass_info;\n\n  /*! \\brief A list of passes that used to compose a sequential pass. */\n  tvm::Array<Pass> passes;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pass_info\", &pass_info);\n    v->Visit(\"passes\", &passes);\n  }\n\n  /*!\n   * \\brief Get the pass information/meta data.\n   */\n  PassInfo Info() const override { return pass_info; }\n\n  /*!\n   * \\brief Resolve the pass dependency. It globs all required passes by\n   *        a given pass and executes them.\n   *\n   * \\param mod The module that an optimization pass runs on.\n   *\n   * \\return The updated module after resolving pass dependencies.\n   *\n   * TODO(zhiics) Build a dependency graph among the passes using provided\n   * metadata, i.e. required_passes. Likely, we can have a data structure, i.e.\n   * PassInfo, to store the relevant information including the parent passes.\n   */\n  void ResolveDependency(const IRModule& mod);\n\n  /*!\n   * \\brief Perform optimizations on a series of passes. The aforementioned\n   *        typical pass manager jobs could be done by it. This function could\n   *        be overloaded to focus on different metrics, i.e. performance,\n   *        memory footprint, etc.\n   *\n   * \\param mod The module that these passes are applied on.\n   * \\param pass_ctx The context that these passes execute on.\n   *\n   * \\return Return the updated module.\n   */\n  IRModule operator()(IRModule mod, const PassContext& pass_ctx) const final;\n\n  static constexpr const char* _type_key = \"transform.Sequential\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SequentialNode, PassNode);\n};\n\nclass Sequential : public Pass {\n public:\n  /*!\n   * \\brief The constructor of `Sequential`.\n   *\n   * \\param passes The passes to apply.\n   * \\param pass_info The pass metadata.\n   */\n  TVM_DLL Sequential(Array<Pass> passes, PassInfo pass_info);\n\n  /*!\n   * \\brief The constructor of `Sequential`.\n   *\n   * \\param passes The passes to apply.\n   * \\param name The name of a sequential pass. It's defaulted to \"sequential\".\n   *        This allows users to only provide a list of passes and execute them\n   *        under a given context.\n   */\n  TVM_DLL Sequential(Array<Pass> passes, String name = \"sequential\");\n\n  Sequential() = default;\n  explicit Sequential(ObjectPtr<Object> n) : Pass(n) {}\n\n  const SequentialNode* operator->() const;\n  using ContainerType = SequentialNode;\n};\n\n/*\n * \\brief Create a module pass.\n *\n * \\param pass_func The packed function that contains the optimization.\n * \\param opt_level The optimization level of the module pass.\n * \\param name The name of the module pass.\n * \\param required The list of the passes that the module pass is dependent on.\n *\n * \\return The created module pass.\n */\nTVM_DLL Pass\nCreateModulePass(const runtime::TypedPackedFunc<IRModule(IRModule, PassContext)>& pass_func,\n                 int opt_level, String name, Array<runtime::String> required);\n\n/*!\n * \\brief A special trace pass that prints the header and IR to LOG(INFO).\n * \\param header The header to be attached to the output.\n * \\param show_meta_data Whether should we show meta data.\n * \\return The pass.\n */\nTVM_DLL Pass PrintIR(String header = \"\", bool show_meta_data = false);\n\n}  // namespace transform\n}  // namespace tvm\n\n#endif  // TVM_IR_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/type.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/type.h\n * \\brief IR/AST nodes for the unified type system in TVM.\n *\n * We use Relay's type system as the unified type system\n * throughout the stack.\n *\n * This file contains types that are common across IR variants.\n *\n * ## Relation between Type and runtime::DataType\n *\n * Besides Type, we also store a dtype field in the low-level PrimExpr.\n * runtime::DataType(dtype) provides coarse grained type information\n * during compile time and runtime. It is eagerly built in\n * low-level expression construction and can be used for\n * quick type checking in the low-level IR.\n * For example, when an Expr's dtype is int32,\n * we know for sure that its type is also int32.\n *\n * On the other hand, Type provides more fine grained information.\n * For example, a low level expression can have DataType::Handle() as\n * its dtype and MemRef[float32] as its type.\n * Types are usually lazily constructed via type checking,\n * so they may not readily be available during IR construction.\n *\n * The unified Type serves as a common bridge across IR dialects.\n * For example, we require all the functions to have a type signature,\n * which allow us to build cross dialect function calls.\n */\n#ifndef TVM_IR_TYPE_H_\n#define TVM_IR_TYPE_H_\n\n#include <tvm/ir/span.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief Type is the base type of all types.\n *\n * Relay's type system contains following subclasses:\n *\n * - PrimType: type of primitive type values used in the low-level IR.\n * - FuncType: type of a function.\n * - TensorType: type of certain Tensor values in the expression.\n *\n * There are also advanced types to support generic(polymorphic types).\n * \\sa Type\n */\nclass TypeNode : public Object {\n public:\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  static constexpr const char* _type_key = \"Type\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  static constexpr const uint32_t _type_child_slots = 14;\n  TVM_DECLARE_BASE_OBJECT_INFO(TypeNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TypeNode.\n * \\sa TypeNode\n */\nclass Type : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(Type, ObjectRef, TypeNode);\n};\n\n/*!\n * \\brief Primitive data types used in the low-level IR.\n *\n * PrimType represents POD-values and handles that are\n * not automatically managed by the runtime.\n *\n * \\sa PrimType\n */\nclass PrimTypeNode : public TypeNode {\n public:\n  /*!\n   * \\brief The corresponding dtype field.\n   */\n  runtime::DataType dtype;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"dtype\", &dtype); }\n\n  bool SEqualReduce(const PrimTypeNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(dtype); }\n\n  static constexpr const char* _type_key = \"PrimType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PrimTypeNode, TypeNode);\n};\n\n/*\n * \\brief Managed reference to PrimTypeNode.\n * \\sa PrimTypeNode\n */\nclass PrimType : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param dtype The corresponding dtype.\n   */\n  TVM_DLL explicit PrimType(runtime::DataType dtype);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PrimType, Type, PrimTypeNode);\n};\n\n/*!\n * \\brief Low-level raw pointer type.\n *\n *  PointerType represents type hints in the TIR to be\n *  passed to the final code generator.\n *\n *  PointerType should not occur in the high-level analysis.\n *\n * \\sa PointerType\n */\nclass PointerTypeNode : public TypeNode {\n public:\n  /*!\n   * \\brief The type of the element which the pointer points to.\n   */\n  Type element_type;\n  /*!\n   * \\brief The storage scope of the pointer\n   */\n  String storage_scope;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"element_type\", &element_type);\n    v->Visit(\"storage_scope\", &storage_scope);\n  }\n\n  bool SEqualReduce(const PointerTypeNode* other, SEqualReducer equal) const {\n    // Make \"global\" equal to \"\"\n    String lhs_scope = storage_scope.empty() ? \"global\" : storage_scope;\n    String rhs_scope = other->storage_scope.empty() ? \"global\" : other->storage_scope;\n    return equal(element_type, other->element_type) && equal(lhs_scope, rhs_scope);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(element_type);\n    // Make \"global\" equal to \"\"\n    hash_reduce(storage_scope.empty() ? \"global\" : storage_scope);\n  }\n\n  static constexpr const char* _type_key = \"PointerType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PointerTypeNode, TypeNode);\n};\n\n/*\n * \\brief Managed reference to PointerTypeNode.\n * \\sa PointerTypeNode\n */\nclass PointerType : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param element_type The type of the element which the pointer points to.\n   * \\param storage_scope The storage scope into which the pointer addresses\n   */\n  TVM_DLL explicit PointerType(Type element_type, String storage_scope = \"\");\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PointerType, Type, PointerTypeNode);\n};\n\n/*! \\brief Possible kinds of TypeVars. */\nenum TypeKind : int {\n  kType = 0,\n  /*! \\brief Template variable in shape expression. */\n  kShapeVar = 1,\n  kBaseType = 2,\n  kConstraint = 4,\n  kAdtHandle = 5,\n  kTypeData = 6\n};\n\n/*!\n * \\brief Type parameter in functions.\n *\n * A type variable can be viewed as template parameter in c++ template function.\n *\n * For example, in the following pesudo code,\n * the TypeVar of f is TypeVar(\"n\", kind=kShapeVar).\n * This function can take in a Tensor with shape=(3, 3) and\n * returns a Tensor with shape=(9,)\n *\n * \\code\n *\n *  template<i32 n>\n *  f(x : Tensor[i32, (n, n)]) -> Tensor[i32, (n * n)]\n *\n * \\endcode\n * \\sa TypeVar, TypeKind\n */\nclass TypeVarNode : public TypeNode {\n public:\n  /*!\n   * \\brief The name of the variable,\n   *  this only acts as a hint to the user,\n   *  and is not used for equality.\n   */\n  String name_hint;\n  /*! \\brief The kind of type parameter */\n  TypeKind kind;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TypeVarNode* other, SEqualReducer equal) const {\n    return equal(kind, other->kind) && equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(kind);\n    hash_reduce.FreeVarHashImpl(this);\n  }\n\n  static constexpr const char* _type_key = \"TypeVar\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypeVarNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to TypeVarNode\n * \\sa TypeVarNode\n */\nclass TypeVar : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param name_hint The name of the type var.\n   * \\param kind The kind of the type var.\n   * \\param span The span information.\n   */\n  TVM_DLL TypeVar(String name_hint, TypeKind kind, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TypeVar, Type, TypeVarNode);\n};\n\n/*!\n * \\brief A global type variable that is used for defining new types or type aliases.\n * \\sa GlobalTypeVar\n */\nclass GlobalTypeVarNode : public TypeNode {\n public:\n  /*!\n   * \\brief The name of the variable,\n   *  this only acts as a hint to the user,\n   *  and is not used for equality.\n   */\n  String name_hint;\n  /*! \\brief The kind of type parameter */\n  TypeKind kind;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"kind\", &kind);\n  }\n\n  bool SEqualReduce(const GlobalTypeVarNode* other, SEqualReducer equal) const {\n    // name matters for now in global type var.\n    return equal(name_hint, other->name_hint) && equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name_hint);\n    hash_reduce.FreeVarHashImpl(this);\n  }\n\n  static constexpr const char* _type_key = \"GlobalTypeVar\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(GlobalTypeVarNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to GlobalTypeVarNode\n * \\sa GlobalTypeVarNode\n */\nclass GlobalTypeVar : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param name_hint The name of the type var.\n   * \\param kind The kind of the type var.\n   * \\param span The span of the type.\n   */\n  TVM_DLL GlobalTypeVar(String name_hint, TypeKind kind, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(GlobalTypeVar, Type, GlobalTypeVarNode);\n};\n\n/*!\n * \\brief The type of tuple values.\n * \\sa TupleType\n */\nclass TupleTypeNode : public TypeNode {\n public:\n  /*! \\brief The type of each field in the tuple. */\n  Array<Type> fields;\n\n  TupleTypeNode() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"fields\", &fields);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TupleTypeNode* other, SEqualReducer equal) const {\n    return equal(fields, other->fields);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(fields); }\n\n  static constexpr const char* _type_key = \"TupleType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleTypeNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to TupleTypeNode.\n * \\sa TupleTypeNode.\n */\nclass TupleType : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param fields Fields in the tuple.\n   * \\param span The span of the type.\n   */\n  TVM_DLL explicit TupleType(Array<Type> fields, Span span = Span());\n\n  /*!\n   * \\brief Create an empty tuple type that constains nothing.\n   * \\return A empty tuple type.\n   */\n  TVM_DLL TupleType static Empty();\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleType, Type, TupleTypeNode);\n};\n\n/*!\n * \\return a type that represents void.\n */\ninline Type VoidType() { return TupleType::Empty(); }\n\n/*!\n * \\brief Check whether the tyep represents void.\n * \\return The check result.\n */\ninline bool IsVoidType(const Type& type) {\n  auto* n = type.as<TupleTypeNode>();\n  return n && n->fields.size() == 0;\n}\n\n/*!\n * \\brief Potential Constraints in a function.\n * \\sa TypeConstraint\n */\nclass TypeConstraintNode : public TypeNode {\n public:\n  static constexpr const char* _type_key = \"TypeConstraint\";\n  static constexpr const uint32_t _type_child_slots = 1;\n  TVM_DECLARE_BASE_OBJECT_INFO(TypeConstraintNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to TypeConstraintNode.\n * \\sa TypeConstraintNode, TypeRelation\n */\nclass TypeConstraint : public Type {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(TypeConstraint, Type, TypeConstraintNode);\n};\n\n/*!\n * \\brief Function type.\n *\n * We support polymorphic function type.\n * This can be roughly viewed as template function in C++.\n *\n * \\sa FuncType, TypeVar, TypeConstraint\n */\nclass FuncTypeNode : public TypeNode {\n public:\n  /*! \\brief type type of arguments */\n  Array<Type> arg_types;\n  /*! \\brief The type of return value. */\n  Type ret_type;\n  // The following fields are used in polymorphic(template) functions\n  // For normal functions, the following two fields will be empty.\n  /*! \\brief The type parameters of the function */\n  Array<TypeVar> type_params;\n  /*!\n   * \\brief potential constraint the type need to obey\n   * \\note this field is reserved for further purposes.\n   */\n  Array<TypeConstraint> type_constraints;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"arg_types\", &arg_types);\n    v->Visit(\"ret_type\", &ret_type);\n    v->Visit(\"type_params\", &type_params);\n    v->Visit(\"type_constraints\", &type_constraints);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const FuncTypeNode* other, SEqualReducer equal) const {\n    // type params first as they defines type vars.\n    return equal.DefEqual(type_params, other->type_params) && equal(arg_types, other->arg_types) &&\n           equal(ret_type, other->ret_type) && equal(type_constraints, other->type_constraints);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(type_params);\n    hash_reduce(arg_types);\n    hash_reduce(ret_type);\n    hash_reduce(type_constraints);\n  }\n\n  static constexpr const char* _type_key = \"FuncType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FuncTypeNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to FuncTypeNode.\n * \\sa FuncTypeNode\n */\nclass FuncType : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param arg_types The types of the arguments.\n   * \\param ret_type The type of the return value.\n   * \\param type_params The type parameters.\n   * \\param type_constraints The type constraints.\n   * \\param span The span information.\n   * \\sa FuncTypeNode for more docs about these fields.\n   */\n  TVM_DLL FuncType(Array<Type> arg_types, Type ret_type, Array<TypeVar> type_params,\n                   Array<TypeConstraint> type_constraints, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FuncType, Type, FuncTypeNode);\n};\n\n/*!\n * \\brief Intermediate values that is used to indicate incomplete type\n *         during type inference.\n *\n * If we view the type relations as \"computational graph of types\",\n * then IncompleteType represents intermediate values of the graph,\n * TypeVar represents the input to the graph.\n *\n * \\sa IncompleteType\n */\nclass IncompleteTypeNode : public TypeNode {\n public:\n  /*! \\brief kind of the type. */\n  TypeKind kind;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const IncompleteTypeNode* other, SEqualReducer equal) const {\n    return equal(kind, other->kind) && equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(kind); }\n\n  static constexpr const char* _type_key = \"IncompleteType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IncompleteTypeNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to IncompleteTypeNode.\n * \\sa IncompleteTypeNode\n */\nclass IncompleteType : public Type {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param kind kind of the type.\n   * \\param span The span information.\n   */\n  TVM_DLL explicit IncompleteType(TypeKind kind, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IncompleteType, Type, IncompleteTypeNode);\n};\n\n/*!\n * \\brief Reference Type High-level Relay IR.\n *\n * \\sa RelayRefType.\n */\nclass RelayRefTypeNode : public TypeNode {\n public:\n  /*! \\brief The type of value in the Reference. */\n  Type value;\n\n  RelayRefTypeNode() {}\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const RelayRefTypeNode* other, SEqualReducer equal) const {\n    return equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(value); }\n\n  // Keep the relay prefix in the type as this type is specific\n  // to the relay itself.\n  static constexpr const char* _type_key = \"relay.RefType\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RelayRefTypeNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to RelayRefTypeNode.\n * \\sa RelayRefTypeNode.\n */\nclass RelayRefType : public Type {\n public:\n  TVM_DLL explicit RelayRefType(Type value, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(RelayRefType, Type, RelayRefTypeNode);\n};\n}  // namespace tvm\n#endif  // TVM_IR_TYPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/type_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/type_functor.h\n * \\brief A way to defined arbitrary function signature with dispatch on types.\n */\n#ifndef TVM_IR_TYPE_FUNCTOR_H_\n#define TVM_IR_TYPE_FUNCTOR_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/relay/adt.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\ntemplate <typename FType>\nclass TypeFunctor;\n\n// functions to be overriden.\n#define TYPE_FUNCTOR_DEFAULT \\\n  { return VisitTypeDefault_(op, std::forward<Args>(args)...); }\n\n#define TVM_TYPE_FUNCTOR_DISPATCH(OP)                                                      \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {     \\\n    return self->VisitType_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass TypeFunctor<R(const Type& n, Args...)> {\n private:\n  using TSelf = TypeFunctor<R(const Type& n, Args...)>;\n  using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~TypeFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const Type& n, Args... args) { return VisitType(n, std::forward<Args>(args)...); }\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitType(const Type& n, Args... args) {\n    ICHECK(n.defined());\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitType_(const TensorTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TypeVarNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TypeConstraintNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const FuncTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TypeRelationNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TupleTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const IncompleteTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const RelayRefTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const GlobalTypeVarNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TypeCallNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const TypeDataNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const PrimTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitType_(const PointerTypeNode* op, Args... args) TYPE_FUNCTOR_DEFAULT;\n  virtual R VisitTypeDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    throw;  // unreachable, written to stop compiler warning\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    TVM_TYPE_FUNCTOR_DISPATCH(TensorTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TypeVarNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TypeConstraintNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(FuncTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TypeRelationNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TupleTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(IncompleteTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(RelayRefTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(GlobalTypeVarNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TypeCallNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(TypeDataNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(PrimTypeNode);\n    TVM_TYPE_FUNCTOR_DISPATCH(PointerTypeNode);\n    return vtable;\n  }\n};\n\n#undef TVM_TYPE_FUNCTOR_DISPATCH\n\n/*!\n * \\brief A type visitor that recursively visit types.\n */\nclass TVM_DLL TypeVisitor : public TypeFunctor<void(const Type& n)> {\n public:\n  void VisitType_(const TypeVarNode* op) override;\n  void VisitType_(const IncompleteTypeNode* op) override;\n  void VisitType_(const TensorTypeNode* op) override;\n  void VisitType_(const FuncTypeNode* op) override;\n  void VisitType_(const TupleTypeNode* op) override;\n  void VisitType_(const TypeRelationNode* op) override;\n  void VisitType_(const RelayRefTypeNode* op) override;\n  void VisitType_(const GlobalTypeVarNode* op) override;\n  void VisitType_(const TypeCallNode* op) override;\n  void VisitType_(const TypeDataNode* op) override;\n  void VisitType_(const PrimTypeNode* op) override;\n  void VisitType_(const PointerTypeNode* op) override;\n};\n\n/*!\n * \\brief TypeMutator that mutates expressions.\n */\nclass TVM_DLL TypeMutator : public TypeFunctor<Type(const Type& n)> {\n public:\n  Type VisitType(const Type& t) override;\n  Type VisitType_(const TypeVarNode* op) override;\n  Type VisitType_(const TensorTypeNode* op) override;\n  Type VisitType_(const IncompleteTypeNode* op) override;\n  Type VisitType_(const FuncTypeNode* op) override;\n  Type VisitType_(const TupleTypeNode* op) override;\n  Type VisitType_(const TypeRelationNode* type_rel) override;\n  Type VisitType_(const RelayRefTypeNode* op) override;\n  Type VisitType_(const GlobalTypeVarNode* op) override;\n  Type VisitType_(const TypeCallNode* op) override;\n  Type VisitType_(const TypeDataNode* op) override;\n  Type VisitType_(const PrimTypeNode* op) override;\n  Type VisitType_(const PointerTypeNode* op) override;\n\n private:\n  Array<Type> MutateArray(Array<Type> arr);\n};\n\n/*!\n * \\brief Bind free type variables in the type.\n * \\param type The type to be updated.\n * \\param args_map The binding map.\n */\nType Bind(const Type& type, const Map<TypeVar, Type>& args_map);\n\n}  // namespace tvm\n#endif  // TVM_IR_TYPE_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/ir/type_relation.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/ir/type_relation.h\n * \\brief Type relation and function for type inference(checking).\n */\n#ifndef TVM_IR_TYPE_RELATION_H_\n#define TVM_IR_TYPE_RELATION_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/diagnostic.h>\n#include <tvm/ir/env_func.h>\n#include <tvm/ir/module.h>\n#include <tvm/ir/type.h>\n#include <tvm/runtime/logging.h>\n\nnamespace tvm {\n\n/*!\n * \\brief Type function application.\n * \\sa TypeCall\n */\nclass TypeCallNode : public TypeNode {\n public:\n  /*!\n   * \\brief The type-level function (ADT that takes type params).\n   */\n  Type func;\n  /*! \\brief The arguments. */\n  Array<Type> args;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"func\", &func);\n    v->Visit(\"args\", &args);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TypeCallNode* other, SEqualReducer equal) const {\n    return equal(func, other->func) && equal(args, other->args);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(func);\n    hash_reduce(args);\n  }\n\n  static constexpr const char* _type_key = \"TypeCall\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypeCallNode, TypeNode);\n};\n\n/*!\n * \\brief Managed reference to TypeCallNode.\n * \\sa TypeCallNode\n */\nclass TypeCall : public Type {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param func The type function to apply.\n   * \\param args The arguments to the type function.\n   */\n  TVM_DLL TypeCall(Type func, Array<Type> args);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TypeCall, Type, TypeCallNode);\n};\n\n/*!\n * \\brief reporter that reports back to the\n *  type resolution information.\n */\nclass TypeReporterNode : public Object {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~TypeReporterNode() {}\n  /*!\n   * \\brief Create a type equality constraint.\n   *\n   *  The \"assign direction\" acts as a hint to the solver\n   *  showing that it is more likely to resolve dst by src.\n   *  But it is possible for the solver to resolve src by dst as well.\n   */\n  TVM_DLL virtual void Assign(const Type& dst, const Type& src) = 0;\n\n  /*!\n   * \\brief assert shape expression comparison.\n   * \\note Use assert only if any of the condition input is symbolic.\n   * \\param cond The condition of operation.\n   * \\return false if assertion can be proven to have failed\n   *      true if solver can still proceed.\n   */\n  TVM_DLL virtual bool Assert(const PrimExpr& cond) = 0;\n  /*!\n   * \\brief assert shape expression equals each other.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return false if assertion can be proven to have failed\n   *      true if solver can still proceed.\n   */\n  TVM_DLL virtual bool AssertEQ(const PrimExpr& lhs, const PrimExpr& rhs) = 0;\n\n  /*!\n   * \\brief Set the location at which to report unification errors.\n   * \\param span The span at which to report the error.\n   */\n  TVM_DLL virtual void SetSpan(const Span& span) = 0;\n\n  TVM_DLL virtual Span GetSpan() = 0;\n\n  TVM_DLL virtual DiagnosticContext GetDiagCtx() = 0;\n\n  /*!\n   * \\brief Retrieve the current global module.\n   * \\return The global module.\n   */\n  TVM_DLL virtual IRModule GetModule() = 0;\n\n  // solver is not serializable.\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"TypeReporter\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypeReporterNode, Object);\n};\n\n/*!\n * \\brief Container class of TypeReporter.\n * \\sa TypeReporterNode\n */\nclass TypeReporter : public ObjectRef {\n public:\n  TypeReporter() {}\n  explicit TypeReporter(ObjectPtr<Object> n) : ObjectRef(n) {}\n  TypeReporterNode* operator->() const {\n    return const_cast<TypeReporterNode*>(static_cast<const TypeReporterNode*>(get()));\n  }\n  using ContainerType = TypeReporterNode;\n};\n\n/*!\n * \\brief User defined type constraint function.\n *\n * If the input type information can be used to fully decide\n * the IncompleteTypes, then the function should call\n * reporter.Assign to report the new types, and return true.\n * Otherwise, the function should return false.\n *\n * \\param args The arguments to the relation.\n *   The types are stored in the form of\n *   [input_type_0, input_type_1, ... input_type_n,\n *    output_type_0, output_type_1, ... output_type_m]\n *\n * \\param num_inputs Number of input types in the args.\n * \\param attrs The additional attributes of the operator.\n * \\param reporter The reporter to report solution to.\n * \\return false if This relation cannot be resolved.\n *   true if this relation has been resolved.\n */\nusing TypeRelationFn = TypedEnvFunc<bool(const Array<Type>& args, int num_inputs,\n                                         const Attrs& attrs, const TypeReporter& reporter)>;\n\n/*!\n * \\brief User defined type relation, it is an input-output relation on types.\n *\n * TypeRelation is more generalized than type call as it allows inference\n * of both inputs and outputs.\n *\n * \\sa TypeRelation\n */\nclass TypeRelationNode : public TypeConstraintNode {\n public:\n  /*!\n   * \\brief The function on input and output variables which\n   *  this is not directly serializable,\n   *  need to be looked-up in the module.\n   */\n  TypeRelationFn func;\n  /*! \\brief The type arguments to the type function. */\n  Array<Type> args;\n  /*! \\brief Number of inputs arguments */\n  int num_inputs;\n  /*! \\brief Attributes to the relation function */\n  Attrs attrs;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"func\", &func);\n    v->Visit(\"args\", &args);\n    v->Visit(\"num_inputs\", &num_inputs);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const TypeRelationNode* other, SEqualReducer equal) const {\n    return equal(func, other->func) && equal(args, other->args) &&\n           equal(num_inputs, other->num_inputs) && equal(attrs, other->attrs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(func);\n    hash_reduce(args);\n    hash_reduce(num_inputs);\n    hash_reduce(attrs);\n  }\n\n  static constexpr const char* _type_key = \"TypeRelation\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypeRelationNode, TypeConstraintNode);\n};\n\n/*!\n * \\brief Managed reference to TypeRelationNode.\n * \\sa TypeRelationNode\n */\nclass TypeRelation : public TypeConstraint {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param func The relation function.\n   * \\param args The arguments to the type relation.\n   * \\param num_inputs Number of inputs.\n   * \\param attrs Attributes to the relation function.\n   * \\sa TypeRelationNode for more docs about these fields.\n   */\n  TVM_DLL TypeRelation(TypeRelationFn func, Array<Type> args, int num_inputs, Attrs attrs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TypeRelation, TypeConstraint, TypeRelationNode);\n};\n}  // namespace tvm\n#endif  // TVM_IR_TYPE_RELATION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/arg_info.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_ARG_INFO_H_\n#define TVM_META_SCHEDULE_ARG_INFO_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/node/node.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/shape_tuple.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/object.h>\n#include <tvm/tir/function.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief The argument information. */\nclass ArgInfoNode : public runtime::Object {\n public:\n  static constexpr const char* _type_key = \"meta_schedule.ArgInfo\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ArgInfoNode, runtime::Object);\n\n public:\n  /*! \\brief Default destructor. */\n  virtual ~ArgInfoNode() = default;\n  /*! \\brief Converts the ArgInfo to its corresponding JSON representation. */\n  virtual ObjectRef AsJSON() const = 0;\n};\n\n/*!\n * \\brief Managed reference to ArgInfoNode\n * \\sa ArgInfoNode\n */\nclass ArgInfo : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Parse the argument information from a JSON object.\n   * \\param json_obj The json object to parse.\n   * \\return The argument information parsed.\n   */\n  TVM_DLL static ArgInfo FromJSON(const ObjectRef& json_obj);\n  /*!\n   * \\brief Extract a list of the argument information from PrimFunc.\n   * \\param func The PrimFunc to get argument information from.\n   * \\return An array of the argument information derived.\n   */\n  TVM_DLL static Array<ArgInfo, void> FromPrimFunc(const tir::PrimFunc& func);\n  /*!\n   * \\brief Extract a list of the argument information from the entry func of an IRModule\n   * \\param mod The IRModule to extract argument information from.\n   * \\param remove_preproc Whether to remove the preprocessing blocks.\n   * \\return An array of the argument information derived.\n   */\n  TVM_DLL static Array<ArgInfo, void> FromEntryFunc(const IRModule& mod, bool remove_preproc);\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(ArgInfo, runtime::ObjectRef, ArgInfoNode);\n\n protected:\n  ArgInfo() = default;\n};\n\n/*! \\brief The tensor argument information. */\nclass TensorInfoNode : public ArgInfoNode {\n public:\n  /*! \\brief The data type of the tensor. */\n  runtime::DataType dtype;\n  /*! \\brief The shape of the tensor. */\n  runtime::ShapeTuple shape;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"shape\", &shape);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.TensorInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorInfoNode, ArgInfoNode);\n\n public:\n  ObjectRef AsJSON() const;\n};\n\n/*!\n * \\brief Managed reference to TensorInfoNode\n * \\sa TensorInfoNode\n */\nclass TensorInfo : public ArgInfo {\n public:\n  /*!\n   * \\brief Constructor of TensorInfo.\n   * \\param dtype The data type of the tensor argument.\n   * \\param shape The shape tuple of the tensor argument.\n   */\n  TVM_DLL explicit TensorInfo(runtime::DataType dtype, runtime::ShapeTuple shape);\n  /*!\n   * \\brief Parse the argument information from a JSON object.\n   * \\param json_obj The json object to parse.\n   * \\return The argument information parsed.\n   */\n  TVM_DLL static TensorInfo FromJSON(const ObjectRef& json_obj);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TensorInfo, ArgInfo, TensorInfoNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_ARG_INFO_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/builder.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_BUILDER_H_\n#define TVM_META_SCHEDULE_BUILDER_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief The builder's input, containing an IRModule and the target. */\nclass BuilderInputNode : public runtime::Object {\n public:\n  /*! \\brief The IRModule to be built. */\n  IRModule mod;\n  /*! \\brief The target to be built for. */\n  Target target;\n  /*! \\brief Parameters for Relay build module. */\n  Optional<Map<String, runtime::NDArray>> params;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"mod\", &mod);\n    v->Visit(\"target\", &target);\n    v->Visit(\"params\", &params);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.BuilderInput\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BuilderInputNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to BuilderInputNode\n * \\sa BuilderInputNode\n */\nclass BuilderInput : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor of BuilderInput.\n   * \\param mod The IRModule to be built.\n   * \\param target The target to be built for.\n   * \\param params Parameters for Relay build module.\n   */\n  TVM_DLL explicit BuilderInput(IRModule mod, Target target,\n                                Optional<Map<String, runtime::NDArray>> params = NullOpt);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(BuilderInput, runtime::ObjectRef, BuilderInputNode);\n};\n\n/*! \\brief The builder's output, containing the artifact path or error message if any. */\nclass BuilderResultNode : public runtime::Object {\n public:\n  /*! \\brief The path to the built artifact. */\n  Optional<String> artifact_path;\n  /*! \\brief The error message if any. */\n  Optional<String> error_msg;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"artifact_path\", &artifact_path);\n    v->Visit(\"error_msg\", &error_msg);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.BuilderResult\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BuilderResultNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to BuilderResultNode\n * \\sa BuilderResultNode\n */\nclass BuilderResult : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor of BuilderResult.\n   * \\param artifact_path The path to the built artifact.\n   * \\param error_msg The error message if any.\n   */\n  TVM_DLL explicit BuilderResult(Optional<String> artifact_path, Optional<String> error_msg);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(BuilderResult, runtime::ObjectRef, BuilderResultNode);\n};\n\n/*! \\brief The abstract builder interface. */\nclass BuilderNode : public runtime::Object {\n public:\n  /*! \\brief Default destructor */\n  virtual ~BuilderNode() = default;\n  /*!\n   * \\brief Generate the build results from build inputs.\n   * \\param build_inputs The inputs to be built.\n   * \\return The build results.\n   */\n  virtual Array<BuilderResult> Build(const Array<BuilderInput>& build_inputs) = 0;\n  /*!\n   * \\brief The function type of `Build` method.\n   * \\param build_inputs The inputs to be built.\n   * \\return The build results.\n   */\n  using FBuild = runtime::TypedPackedFunc<Array<BuilderResult>(const Array<BuilderInput>&)>;\n\n  static constexpr const char* _type_key = \"meta_schedule.Builder\";\n  TVM_DECLARE_BASE_OBJECT_INFO(BuilderNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to BuilderNode\n * \\sa BuilderNode\n */\nclass Builder : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Create a builder with customized build method on the python-side.\n   * \\param f_build The packed function to the `Build` function..\n   * \\return The Builder created.\n   */\n  static Builder PyBuilder(BuilderNode::FBuild f_build);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Builder, runtime::ObjectRef, BuilderNode);\n};\n\n/*! \\brief An abstract builder with customized build method on the python-side. */\nclass PyBuilderNode : public BuilderNode {\n public:\n  /*! \\brief The packed function to the `Build` function. */\n  FBuild f_build;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_build` is not visited\n  }\n\n  Array<BuilderResult> Build(const Array<BuilderInput>& build_inputs) final {\n    ICHECK(f_build != nullptr) << \"PyBuilder's Build method not implemented!\";\n    return f_build(build_inputs);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.PyBuilder\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyBuilderNode, BuilderNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_BUILDER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/cost_model.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_COST_MODEL_H_\n#define TVM_META_SCHEDULE_COST_MODEL_H_\n\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/meta_schedule/measure_candidate.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/schedule/schedule.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TuneContext;\n\n/*! \\brief Cost model. */\nclass CostModelNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~CostModelNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Load the cost model from given file location.\n   * \\param path The file path.\n   */\n  virtual void Load(const String& path) = 0;\n\n  /*!\n   * \\brief Save the cost model to given file location.\n   * \\param path The file path.\n   */\n  virtual void Save(const String& path) = 0;\n\n  /*!\n   * \\brief Update the cost model given running results.\n   * \\param context The tuning context.\n   * \\param candidates The measure candidates.\n   * \\param results The running results of the measure candidates.\n   */\n  virtual void Update(const TuneContext& context, const Array<MeasureCandidate>& candidates,\n                      const Array<RunnerResult>& results) = 0;\n\n  /*!\n   * \\brief Predict the normalized score (the larger the better) of given measure candidates.\n   * \\param context The tuning context.\n   * \\param candidates The measure candidates.\n   * \\return The predicted normalized score.\n   */\n  virtual std::vector<double> Predict(const TuneContext& context,\n                                      const Array<MeasureCandidate>& candidates) = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.CostModel\";\n  TVM_DECLARE_BASE_OBJECT_INFO(CostModelNode, Object);\n};\n\n/*! \\brief The cost model with customized methods on the python-side. */\nclass PyCostModelNode : public CostModelNode {\n public:\n  /*!\n   * \\brief Load the cost model from given file location.\n   * \\param path The file path.\n   */\n  using FLoad = runtime::TypedPackedFunc<void(String)>;\n  /*!\n   * \\brief Save the cost model to given file location.\n   * \\param path The file path.\n   */\n  using FSave = runtime::TypedPackedFunc<void(String)>;\n  /*!\n   * \\brief Update the cost model given running results.\n   * \\param context The tuning context.\n   * \\param candidates The measure candidates.\n   * \\param results The running results of the measure candidates.\n   * \\return Whether cost model was updated successfully.\n   */\n  using FUpdate = runtime::TypedPackedFunc<void(const TuneContext&, const Array<MeasureCandidate>&,\n                                                const Array<RunnerResult>&)>;\n  /*!\n   * \\brief Predict the running results of given measure candidates.\n   * \\param context The tuning context.\n   * \\param candidates The measure candidates.\n   * \\param p_addr The address to save the estimated running results.\n   */\n  using FPredict = runtime::TypedPackedFunc<void(const TuneContext&, const Array<MeasureCandidate>&,\n                                                 void* p_addr)>;\n  /*!\n   * \\brief Get the cost model as string with name.\n   * \\return The string representation of the cost model.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n\n  /*! \\brief The packed function to the `Load` function. */\n  FLoad f_load;\n  /*! \\brief The packed function to the `Save` function. */\n  FSave f_save;\n  /*! \\brief The packed function to the `Update` function. */\n  FUpdate f_update;\n  /*! \\brief The packed function to the `Predict` function. */\n  FPredict f_predict;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_load` is not visited\n    // `f_save` is not visited\n    // `f_update` is not visited\n    // `f_predict` is not visited\n    // `f_as_string` is not visited\n  }\n\n  void Load(const String& path);\n  void Save(const String& path);\n  void Update(const TuneContext& context, const Array<MeasureCandidate>& candidates,\n              const Array<RunnerResult>& results);\n  std::vector<double> Predict(const TuneContext& context,\n                              const Array<MeasureCandidate>& candidates);\n\n  static constexpr const char* _type_key = \"meta_schedule.PyCostModel\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyCostModelNode, CostModelNode);\n};\n\n/*!\n * \\brief Managed reference to CostModelNode\n * \\sa CostModelNode\n */\nclass CostModel : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Create a feature extractor with customized methods on the python-side.\n   * \\param f_load The packed function of `Load`.\n   * \\param f_save The packed function of `Save`.\n   * \\param f_update The packed function of `Update`.\n   * \\param f_predict The packed function of `Predict`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The feature extractor created.\n   */\n  TVM_DLL static CostModel PyCostModel(PyCostModelNode::FLoad f_load,        //\n                                       PyCostModelNode::FSave f_save,        //\n                                       PyCostModelNode::FUpdate f_update,    //\n                                       PyCostModelNode::FPredict f_predict,  //\n                                       PyCostModelNode::FAsString f_as_string);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(CostModel, ObjectRef, CostModelNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_COST_MODEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/database.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_DATABASE_H_\n#define TVM_META_SCHEDULE_DATABASE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/module.h>\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/trace.h>\n\n#include <memory>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass ModuleEquality;\n\n/*! \\brief A workload, i.e. an IRModule and its structural hash. */\nclass WorkloadNode : public runtime::Object {\n public:\n  /*! \\brief The type of structural hash */\n  using THashCode = size_t;\n  /*! \\brief The workload's IRModule. */\n  IRModule mod;\n  /*! \\brief The workload's structural hash. */\n  THashCode shash;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"mod\", &mod);\n    // `shash` is not visited because TVM FFI doesn't support uint64_t\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.Workload\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WorkloadNode, runtime::Object);\n\n  /*!\n   * \\brief Export the workload to a JSON string.\n   * \\return An array containing the structural hash and the base64 json string.\n   */\n  ObjectRef AsJSON() const;\n};\n\n/*!\n * \\brief Managed reference to WorkloadNode.\n *  \\sa WorkloadNode\n */\nclass Workload : public runtime::ObjectRef {\n public:\n  using THashCode = WorkloadNode::THashCode;\n  /*!\n   * \\brief Constructor of Workload.\n   * \\param mod The workload's IRModule.\n   */\n  TVM_DLL explicit Workload(IRModule mod);\n  /*!\n   * \\brief Constructor of Workload.\n   * \\param mod The workload's IRModule.\n   * \\param shash The workload's structural hash.\n   */\n  TVM_DLL explicit Workload(IRModule mod, THashCode shash);\n  /*!\n   * \\brief Create a workload from a json object.\n   * \\param json_obj The json object.\n   * \\return The created workload.\n   */\n  TVM_DLL static Workload FromJSON(const ObjectRef& json_obj);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Workload, runtime::ObjectRef, WorkloadNode);\n};\n\n/*! \\brief The hash method for Workload */\nstruct WorkloadHash {\n  size_t operator()(const Workload& a) const { return a->shash; }\n};\n\n/*! \\brief The equality check for Workload */\nstruct WorkloadEqual {\n  explicit WorkloadEqual(const ModuleEquality& mod_eq) : mod_eq_(mod_eq) {}\n\n  bool operator()(const Workload& a, const Workload& b) const;\n\n private:\n  /*! \\brief The module equality testing and hashing method */\n  const ModuleEquality& mod_eq_;\n};\n\n/*! \\brief The class of measure candidates. */\nclass MeasureCandidate;\n\n/*! \\brief The class of tuning records. */\nclass TuningRecordNode : public runtime::Object {\n public:\n  /*! \\brief The trace tuned. */\n  tir::Trace trace;\n  /*! \\brief The workload. */\n  Workload workload{nullptr};\n  /*! \\brief The profiling result in seconds. */\n  Optional<Array<FloatImm>> run_secs;\n  /*! \\brief The target for tuning. */\n  Optional<Target> target;\n  /*! \\brief The argument information. */\n  Optional<Array<ArgInfo>> args_info;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"trace\", &trace);\n    v->Visit(\"workload\", &workload);\n    v->Visit(\"run_secs\", &run_secs);\n    v->Visit(\"target\", &target);\n    v->Visit(\"args_info\", &args_info);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.TuningRecord\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TuningRecordNode, runtime::Object);\n\n  /*! \\brief Construct the measure candidate given the initial IR module and trace\n   * stored in the tuning record. */\n  MeasureCandidate AsMeasureCandidate() const;\n  /*!\n   * \\brief Export the tuning record to a JSON string.\n   * \\return An array containing the trace, running secs, serialized target, and\n   * argument information.\n   */\n  ObjectRef AsJSON() const;\n};\n\n/*!\n * \\brief The managed reference of TuningRecordNode.\n * \\sa TuningRecordNode\n */\nclass TuningRecord : public runtime::ObjectRef {\n public:\n  /*!\n   \\brief Constructor of a tuning record.\n   \\param trace The trace of the tuning record.\n   \\param workload The workload of the tuning record.\n   \\param run_secs The running time of the tuning record.\n   \\param target The target of the tuning record.\n   \\param args_info The argument information of the tuning record.\n  */\n  TVM_DLL explicit TuningRecord(tir::Trace trace, Workload workload,\n                                Optional<Array<FloatImm>> run_secs, Optional<Target> target,\n                                Optional<Array<ArgInfo>> args_info);\n  /*!\n   * \\brief Create a tuning record from a json object.\n   * \\param json_obj The json object.\n   * \\param workload The workload.\n   * \\return The tuning record created.\n   */\n  TVM_DLL static TuningRecord FromJSON(const ObjectRef& json_obj, const Workload& workload);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TuningRecord, runtime::ObjectRef, TuningRecordNode);\n};\n\n/* \\brief The abstract interface of database. */\nclass DatabaseNode : public runtime::Object {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   *  It must be one of the followings:\n   *    - \"structural\": Use StructuralEqual/Hash\n   *    - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n   *                        equality testing and hashing.\n   *    - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n   *                      given module. The \"ignore-ndarray\" varint is used for the extracted blocks\n   *                      or in case no anchor block is found.\n   *                      For the definition of the anchor block, see tvm/tir/analysis.h.\n   */\n  explicit DatabaseNode(String mod_eq_name = \"structural\");\n\n  /*! \\brief Default destructor */\n  virtual ~DatabaseNode();\n  /*!\n   * \\brief Check if the database has the given workload.\n   * \\param mod The IRModule to be searched for.\n   * \\return Whether the database has the given workload.\n   */\n  virtual bool HasWorkload(const IRModule& mod) = 0;\n  /*!\n   * \\brief Look up or add workload to the database if missing.\n   * \\param mod The IRModule to be searched for or added.\n   * \\return The workload corresponding to the given IRModule.\n   */\n  virtual Workload CommitWorkload(const IRModule& mod) = 0;\n  /*!\n   * \\brief Add a tuning record to the database.\n   * \\param record The tuning record to be added.\n   */\n  virtual void CommitTuningRecord(const TuningRecord& record) = 0;\n  /*!\n   * \\brief Get the top K tuning records of given workload from the database.\n   * \\param workload The workload to be searched for.\n   * \\param top_k The number of top records to be returned.\n   * \\return An array of top K tuning records for the given workload.\n   */\n  virtual Array<TuningRecord> GetTopK(const Workload& workload, int top_k) = 0;\n  /*!\n   * \\brief Get all tuning records from the database.\n   * \\return An Array of all the tuning records in the database.\n   */\n  virtual Array<TuningRecord> GetAllTuningRecords() = 0;\n  /*!\n   * \\brief Get the size of the database.\n   * \\return The size of the database.\n   */\n  virtual int64_t Size() = 0;\n  /*!\n   * \\brief Query the best record of the given workload from the database.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The best record of the given workload; NullOpt if not found.\n   */\n  virtual Optional<TuningRecord> QueryTuningRecord(const IRModule& mod, const Target& target,\n                                                   const String& workload_name);\n  /*!\n   * \\brief Query the best schedule of the given workload from the database.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The schedule in the best schedule of the given workload; NullOpt if not found.\n   */\n  virtual Optional<tir::Schedule> QuerySchedule(const IRModule& mod, const Target& target,\n                                                const String& workload_name);\n  /*!\n   * \\brief Query the best IRModule of the given workload from the database.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The IRModule in the best IRModule of the given workload; NullOpt if not found.\n   */\n  virtual Optional<IRModule> QueryIRModule(const IRModule& mod, const Target& target,\n                                           const String& workload_name);\n\n  /*! \\brief Return a reference to the owned module equality method instance. */\n  const ModuleEquality& GetModuleEquality() const {\n    ICHECK(mod_eq_);\n    return *mod_eq_;\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.Database\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DatabaseNode, runtime::Object);\n\n private:\n  /*! \\brief The module equality testing and hashing method */\n  std::unique_ptr<ModuleEquality> mod_eq_;\n};\n\n/*! \\brief The database with customized methods on the python-side. */\nclass PyDatabaseNode : public DatabaseNode {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   *  It must be one of the followings:\n   *    - \"structural\": Use StructuralEqual/Hash\n   *    - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n   *                        equality testing and hashing.\n   *    - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n   *                      given module. The \"ignore-ndarray\" varint is used for the extracted blocks\n   *                      or in case no anchor block is found.\n   *                      For the definition of the anchor block, see tvm/tir/analysis.h.\n   */\n  explicit PyDatabaseNode(String mod_eq_name = \"structural\");\n\n  /*!\n   * \\brief The function type of `HasWorkload` method.\n   * \\param mod The IRModule to be searched for.\n   * \\return Whether the database has the given workload.\n   */\n  using FHasWorkload = runtime::TypedPackedFunc<bool(const IRModule&)>;\n  /*!\n   * \\brief The function type of `CommitWorkload` method.\n   * \\param mod The IRModule to be searched for or added.\n   * \\return The workload corresponding to the given IRModule.\n   */\n  using FCommitWorkload = runtime::TypedPackedFunc<Workload(const IRModule&)>;\n  /*!\n   * \\brief The function type of `CommitTuningRecord` method.\n   * \\param record The tuning record to be added.\n   */\n  using FCommitTuningRecord = runtime::TypedPackedFunc<void(const TuningRecord&)>;\n  /*!\n   * \\brief The function type of `GetTopK` method.\n   * \\param workload The workload to be searched for.\n   * \\param top_k The number of top records to be returned.\n   * \\return An array of top K tuning records for the given workload.\n   */\n  using FGetTopK = runtime::TypedPackedFunc<Array<TuningRecord>(const Workload&, int)>;\n  /*!\n   * \\brief The function type of `GetAllTuningRecords` method.\n   * \\return An Array of all the tuning records in the database.\n   */\n  using FGetAllTuningRecords = runtime::TypedPackedFunc<Array<TuningRecord>()>;\n  /*!\n   * \\brief The function type of `QueryTuningRecord` method.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The best record of the given workload; NullOpt if not found.\n   */\n  using FQueryTuningRecord = runtime::TypedPackedFunc<Optional<TuningRecord>(\n      const IRModule&, const Target&, const String&)>;\n  /*!\n   * \\brief The function type of `QuerySchedule` method.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The schedule in the best schedule of the given workload; NullOpt if not found.\n   */\n  using FQuerySchedule = runtime::TypedPackedFunc<Optional<tir::Schedule>(\n      const IRModule&, const Target&, const String&)>;\n  /*!\n   * \\brief The function type of `QueryIRModule` method.\n   * \\param mod The IRModule to be searched for.\n   * \\param target The target to be searched for.\n   * \\param workload_name The name of the workload to be searched for.\n   * \\return The IRModule in the best IRModule of the given workload; NullOpt if not found.\n   */\n  using FQueryIRModule =\n      runtime::TypedPackedFunc<Optional<IRModule>(const IRModule&, const Target&, const String&)>;\n  /*!\n   * \\brief The function type of `Size` method.\n   * \\return The size of the database.\n   */\n  using FSize = runtime::TypedPackedFunc<int64_t()>;\n\n  /*! \\brief The packed function to the `HasWorkload` function. */\n  FHasWorkload f_has_workload;\n  /*! \\brief The packed function to the `CommitWorkload` function. */\n  FCommitWorkload f_commit_workload;\n  /*! \\brief The packed function to the `CommitTuningRecord` function. */\n  FCommitTuningRecord f_commit_tuning_record;\n  /*! \\brief The packed function to the `GetTopK` function. */\n  FGetTopK f_get_top_k;\n  /*! \\brief The packed function to the `GetAllTuningRecords` function. */\n  FGetAllTuningRecords f_get_all_tuning_records;\n  /*! \\brief The packed function to the `QueryTuningRecord` function. */\n  FQueryTuningRecord f_query_tuning_record;\n  /*! \\brief The packed function to the `QuerySchedule` function. */\n  FQuerySchedule f_query_schedule;\n  /*! \\brief The packed function to the `QueryIRModule` function. */\n  FQueryIRModule f_query_ir_module;\n  /*! \\brief The packed function to the `Size` function. */\n  FSize f_size;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // PackedFuncs are all not visited, because the reflection system doesn't take care of them,\n    // so it cannot be accessible on the python side. If there is such need from the future,\n    // we can then add corresponding accessor methods to help access on python.\n    // `f_has_workload` is not visited\n    // `f_commit_workload` is not visited\n    // `f_commit_tuning_record` is not visited\n    // `f_get_top_k` is not visited\n    // `f_get_all_tuning_records` is not visited\n    // `f_query_tuning_record` is not visited\n    // `f_query_schedule` is not visited\n    // `f_query_ir_module` is not visited\n    // `f_size` is not visited\n  }\n\n  bool HasWorkload(const IRModule& mod) final {\n    ICHECK(f_has_workload != nullptr) << \"PyDatabase's HasWorkload method not implemented!\";\n    return f_has_workload(mod);\n  }\n\n  Workload CommitWorkload(const IRModule& mod) final {\n    ICHECK(f_commit_workload != nullptr) << \"PyDatabase's CommitWorkload method not implemented!\";\n    return f_commit_workload(mod);\n  }\n\n  void CommitTuningRecord(const TuningRecord& record) final {\n    ICHECK(f_commit_tuning_record != nullptr)\n        << \"PyDatabase's CommitTuningRecord method not implemented!\";\n    f_commit_tuning_record(record);\n  }\n\n  Array<TuningRecord> GetTopK(const Workload& workload, int top_k) final {\n    ICHECK(f_get_top_k != nullptr) << \"PyDatabase's GetTopK method not implemented!\";\n    return f_get_top_k(workload, top_k);\n  }\n\n  Array<TuningRecord> GetAllTuningRecords() final {\n    ICHECK(f_get_all_tuning_records != nullptr)\n        << \"PyDatabase's GetAllTuningRecords method not implemented!\";\n    return f_get_all_tuning_records();\n  }\n\n  Optional<TuningRecord> QueryTuningRecord(const IRModule& mod, const Target& target,\n                                           const String& workload_name) final {\n    if (f_query_tuning_record == nullptr) {\n      return DatabaseNode::QueryTuningRecord(mod, target, workload_name);\n    } else {\n      return f_query_tuning_record(mod, target, workload_name);\n    }\n  }\n\n  Optional<tir::Schedule> QuerySchedule(const IRModule& mod, const Target& target,\n                                        const String& workload_name) final {\n    if (f_query_schedule == nullptr) {\n      return DatabaseNode::QuerySchedule(mod, target, workload_name);\n    } else {\n      return f_query_schedule(mod, target, workload_name);\n    }\n  }\n\n  Optional<IRModule> QueryIRModule(const IRModule& mod, const Target& target,\n                                   const String& workload_name) final {\n    if (f_query_ir_module == nullptr) {\n      return DatabaseNode::QueryIRModule(mod, target, workload_name);\n    } else {\n      return f_query_ir_module(mod, target, workload_name);\n    }\n  }\n\n  int64_t Size() final {\n    ICHECK(f_size != nullptr) << \"PyDatabase's Size method not implemented!\";\n    return f_size();\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.PyDatabase\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyDatabaseNode, DatabaseNode);\n};\n\n/*!\n * \\brief Managed reference to DatabaseNode.\n * \\sa DatabaseNode\n */\nclass Database : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief An in-memory database.\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   */\n  TVM_DLL static Database MemoryDatabase(String mod_eq_name = \"structural\");\n  /*!\n   * \\brief A database for injecting handcrafted schedule functions.\n   * \\param schedule_fn The function to do scheduling, which takes a TIR schedule,\n   * and returns a boolean indicating if the schedule is successful.\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   */\n  TVM_DLL static Database ScheduleFnDatabase(\n      runtime::TypedPackedFunc<bool(tir::Schedule)> schedule_fn, String mod_eq_name = \"structural\");\n  /*!\n   * \\brief Create a default database that uses JSON file for tuning records.\n   * \\param path_workload The path to the workload table.\n   * \\param path_tuning_record The path to the database table.\n   * \\param allow_missing Whether to create new file when the given path is not found.\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   */\n  TVM_DLL static Database JSONDatabase(String path_workload, String path_tuning_record,\n                                       bool allow_missing, String mod_eq_name = \"structural\");\n  /*!\n   * \\brief A database composed of multiple databases, allowing users to guide IR rewriting using\n   * combined knowledge of those databases. To each query, it returns the best record among all the\n   * databases given.\n   * \\param databases The list of databases to be combined.\n   * \\return The combined database.\n   */\n  TVM_DLL static Database UnionDatabase(Array<Database, void> databases);\n  /*!\n   * \\brief A database composed of multiple databases, allowing users to guide IR rewriting using\n   * combined knowledge of those databases. To each query, it returns the record from the first\n   * database that responds to the query.\n   * \\param databases The database to be subsetted.\n   * \\return The subsetted database.\n   */\n  TVM_DLL static Database OrderedUnionDatabase(Array<Database, void> databases);\n  /*!\n   * \\brief Create a database with customized methods on the python-side.\n   * \\param f_has_workload The packed function of `HasWorkload`.\n   * \\param f_commit_workload The packed function of `CommitWorkload`.\n   * \\param f_commit_tuning_record The packed function of `CommitTuningRecord`.\n   * \\param f_get_top_k The packed function of `GetTopK`.\n   * \\param f_get_all_tuning_records The packed function of `GetAllTuningRecords`.\n   * \\param f_query_tuning_record The packed function of `QueryTuningRecord`.\n   * \\param f_query_schedule The packed function of `QuerySchedule`.\n   * \\param f_query_ir_module The packed function of `QueryIRModule`.\n   * \\param f_size The packed function of `Size`.\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   * \\return The created database.\n   */\n  TVM_DLL static Database PyDatabase(PyDatabaseNode::FHasWorkload f_has_workload,\n                                     PyDatabaseNode::FCommitWorkload f_commit_workload,\n                                     PyDatabaseNode::FCommitTuningRecord f_commit_tuning_record,\n                                     PyDatabaseNode::FGetTopK f_get_top_k,\n                                     PyDatabaseNode::FGetAllTuningRecords f_get_all_tuning_records,\n                                     PyDatabaseNode::FQueryTuningRecord f_query_tuning_record,\n                                     PyDatabaseNode::FQuerySchedule f_query_schedule,\n                                     PyDatabaseNode::FQueryIRModule f_query_ir_module,\n                                     PyDatabaseNode::FSize f_size,\n                                     String mod_eq_name = \"structural\");\n  /*! \\return The current Database in the scope. */\n  static Optional<Database> Current();\n  /*! \\brief Entering the scope of the context manager */\n  void EnterWithScope();\n  /*! \\brief Exiting the scope of the context manager */\n  void ExitWithScope();\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Database, runtime::ObjectRef, DatabaseNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_DATABASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/extracted_task.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_EXTRACTED_TASK_H_\n#define TVM_META_SCHEDULE_EXTRACTED_TASK_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace tir {\nclass PrimFunc;\n}  // namespace tir\nnamespace te {\nclass Tensor;\n}  // namespace te\n}  // namespace tvm\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief A tuning task extracted from the high-level IR */\nclass ExtractedTaskNode : public runtime::Object {\n public:\n  /*! \\brief The name of the task extracted */\n  String task_name;\n  /*! \\brief The high-level IR */\n  IRModule mod;\n  /*! \\brief Target */\n  Target target;\n  /*! \\brief A list of low-level IRs that the high-level IR could potentially dispatch to */\n  Array<IRModule> dispatched;\n  /*! \\brief Weight of the task */\n  int weight;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"task_name\", &task_name);\n    v->Visit(\"mod\", &mod);\n    v->Visit(\"target\", &target);\n    v->Visit(\"dispatched\", &dispatched);\n    v->Visit(\"weight\", &weight);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.ExtractedTask\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExtractedTaskNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to ExtractedTaskNode\n * \\sa ExtractedTaskNode\n */\nclass ExtractedTask : public runtime::ObjectRef {\n public:\n  explicit ExtractedTask(String task_name, IRModule mod, Target target, Array<IRModule> dispatched,\n                         int weight);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(ExtractedTask, runtime::ObjectRef,\n                                                    ExtractedTaskNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_EXTRACTED_TASK_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/feature_extractor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_FEATURE_EXTRACTOR_H_\n#define TVM_META_SCHEDULE_FEATURE_EXTRACTOR_H_\n\n#include <tvm/meta_schedule/measure_candidate.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TuneContext;\n\n/*! \\brief Extractor for features from measure candidates for use in cost model. */\nclass FeatureExtractorNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~FeatureExtractorNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Extract features from the given measure candidate.\n   * \\param context The tuning context for feature extraction.\n   * \\param candidates The measure candidates to extract features from.\n   * \\return The feature ndarray extracted.\n   */\n  virtual Array<tvm::runtime::NDArray> ExtractFrom(const TuneContext& context,\n                                                   const Array<MeasureCandidate>& candidates) = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.FeatureExtractor\";\n  TVM_DECLARE_BASE_OBJECT_INFO(FeatureExtractorNode, Object);\n};\n\n/*! \\brief The feature extractor with customized methods on the python-side. */\nclass PyFeatureExtractorNode : public FeatureExtractorNode {\n public:\n  /*!\n   * \\brief Extract features from the given measure candidate.\n   * \\param context The tuning context for feature extraction.\n   * \\param candidates The measure candidates to extract features from.\n   * \\return The feature ndarray extracted.\n   */\n  using FExtractFrom = runtime::TypedPackedFunc<Array<tvm::runtime::NDArray>(\n      const TuneContext& context, const Array<MeasureCandidate>& candidates)>;\n  /*!\n   * \\brief Get the feature extractor as string with name.\n   * \\return The string of the feature extractor.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n\n  /*! \\brief The packed function to the `ExtractFrom` function. */\n  FExtractFrom f_extract_from;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_extract_from` is not visited\n    // `f_as_string` is not visited\n  }\n\n  Array<tvm::runtime::NDArray> ExtractFrom(const TuneContext& context,\n                                           const Array<MeasureCandidate>& candidates) final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PyFeatureExtractor\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyFeatureExtractorNode, FeatureExtractorNode);\n};\n\n/*!\n * \\brief Managed reference to FeatureExtractorNode\n * \\sa FeatureExtractorNode\n */\nclass FeatureExtractor : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Create a feature extractor that extracts features from each BufferStore\n   * \\param buffers_per_store The number of buffers in each BufferStore; Pad or truncate if\n   * necessary.\n   * \\param arith_intensity_curve_num_samples The number of samples used in the arithmetic intensity\n   * curve.\n   * \\param cache_line_bytes The number of bytes in a cache line.\n   * \\param extract_workload Whether to extract features in the workload in tuning context or not.\n   * \\return The feature extractor created.\n   */\n  TVM_DLL static FeatureExtractor PerStoreFeature(int buffers_per_store = 5,\n                                                  int arith_intensity_curve_num_samples = 10,\n                                                  int cache_line_bytes = 64,\n                                                  bool extract_workload = false);\n  /*!\n   * \\brief Create a feature extractor with customized methods on the python-side.\n   * \\param f_extract_from The packed function of `ExtractFrom`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The feature extractor created.\n   */\n  TVM_DLL static FeatureExtractor PyFeatureExtractor(\n      PyFeatureExtractorNode::FExtractFrom f_extract_from,\n      PyFeatureExtractorNode::FAsString f_as_string);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(FeatureExtractor, ObjectRef, FeatureExtractorNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_FEATURE_EXTRACTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/measure_callback.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_MEASURE_CALLBACK_H_\n#define TVM_META_SCHEDULE_MEASURE_CALLBACK_H_\n\n#include <tvm/meta_schedule/builder.h>\n#include <tvm/meta_schedule/measure_candidate.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/meta_schedule/search_strategy.h>\n#include <tvm/meta_schedule/tune_context.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TaskScheduler;\n\n/*! \\brief Rules to apply after measure results is available. */\nclass MeasureCallbackNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~MeasureCallbackNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Apply a measure callback rule with given arguments.\n   * \\param task_scheduler The task scheduler.\n   * \\param task_id The id of the task (tune context) to apply measure callbacks.\n   * \\param measure_candidates The measure candidates.\n   * \\param builder_results The builder results by building the measure candidates.\n   * \\param runner_results The runner results by running the built measure candidates.\n   */\n  virtual void Apply(const TaskScheduler& task_scheduler,                //\n                     int task_id,                                        //\n                     const Array<MeasureCandidate>& measure_candidates,  //\n                     const Array<BuilderResult>& builder_results,        //\n                     const Array<RunnerResult>& runner_results) = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.MeasureCallback\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MeasureCallbackNode, Object);\n};\n\n/*! \\brief The measure callback with customized methods on the python-side. */\nclass PyMeasureCallbackNode : public MeasureCallbackNode {\n public:\n  /*!\n   * \\brief Apply a measure callback to the given schedule.\n   * \\param task_scheduler The task scheduler.\n   * \\param tasks The list of tune context to process.\n   * \\param measure_candidates The measure candidates.\n   * \\param builds The builder results by building the measure candidates.\n   * \\param results The runner results by running the built measure candidates.\n   * \\return Whether the measure callback was successfully applied.\n   */\n  using FApply =\n      runtime::TypedPackedFunc<void(const TaskScheduler& task_scheduler,                //\n                                    int task_id,                                        //\n                                    const Array<MeasureCandidate>& measure_candidates,  //\n                                    const Array<BuilderResult>& builds,                 //\n                                    const Array<RunnerResult>& results)>;\n  /*!\n   * \\brief Get the measure callback function as string with name.\n   * \\return The string of the measure callback function.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n\n  /*! \\brief The packed function to the `Apply` function. */\n  FApply f_apply;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_apply` is not visited\n    // `f_as_string` is not visited\n  }\n\n  void Apply(const TaskScheduler& task_scheduler,                //\n             int task_id,                                        //\n             const Array<MeasureCandidate>& measure_candidates,  //\n             const Array<BuilderResult>& builds,                 //\n             const Array<RunnerResult>& results);\n\n  static constexpr const char* _type_key = \"meta_schedule.PyMeasureCallback\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyMeasureCallbackNode, MeasureCallbackNode);\n};\n\n/*!\n * \\brief Managed reference to MeasureCallbackNode\n * \\sa MeasureCallbackNode\n */\nclass MeasureCallback : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Create a measure callback that adds the measurement results into the database\n   * \\return The measure callback created.\n   */\n  TVM_DLL static MeasureCallback AddToDatabase();\n  /*!\n   * \\brief Create a measure callback that removes the build artifacts from the disk\n   * \\return The measure callback created.\n   */\n  TVM_DLL static MeasureCallback RemoveBuildArtifact();\n  /*!\n   * \\brief Create a measure callback that updates the cost model with measurement result.\n   * \\return The measure callback created.\n   */\n  TVM_DLL static MeasureCallback UpdateCostModel();\n  /*!\n   * \\brief Create a measure callback with customized methods on the python-side.\n   * \\param f_apply The packed function of `Apply`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The measure callback created.\n   */\n  TVM_DLL static MeasureCallback PyMeasureCallback(PyMeasureCallbackNode::FApply f_apply,\n                                                   PyMeasureCallbackNode::FAsString f_as_string);\n  /*! \\brief The default list of measure callbacks. */\n  TVM_DLL static Array<MeasureCallback, void> Default();\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MeasureCallback, ObjectRef, MeasureCallbackNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_MEASURE_CALLBACK_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/measure_candidate.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_MEASURE_CANDIDATE_H_\n#define TVM_META_SCHEDULE_MEASURE_CANDIDATE_H_\n\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/object.h>\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief The schedule (with input shapes) to be measured. */\nclass MeasureCandidateNode : public runtime::Object {\n public:\n  /*! \\brief The schedule for measurement. */\n  tir::Schedule sch;\n  /*! \\brief The argument information, e.g., (shape, dtype) for tensors. */\n  Array<ArgInfo> args_info;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"sch\", &sch);\n    v->Visit(\"args_info\", &args_info);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.MeasureCandidate\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MeasureCandidateNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MeasureCandidateNode.\n * \\sa MeasureCandidateNode\n */\nclass MeasureCandidate : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor of MeasureCandidate.\n   * \\param sch The schedule for measurement.\n   * \\param args_info The argument information, e.g., (shape, dtype) for tensors.\n   */\n  TVM_DLL MeasureCandidate(tir::Schedule sch, Array<ArgInfo> args_info);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(MeasureCandidate, ObjectRef, MeasureCandidateNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_MEASURE_CANDIDATE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/mutator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_MUTATOR_H_\n#define TVM_META_SCHEDULE_MUTATOR_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/support/random_engine.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/trace.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TuneContext;\nclass Mutator;\n\n/*! \\brief Mutator is designed to mutate the trace to explore the design space. */\nclass MutatorNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~MutatorNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Initialize the design space generator with tuning context.\n   * \\param context The tuning context for initialization.\n   * \\note This method is supposed to be called only once before every other method.\n   */\n  virtual void InitializeWithTuneContext(const TuneContext& context) = 0;\n\n  /*!\n   * \\brief Apply the mutator function to the given trace.\n   * \\param trace The given trace for mutation.\n   * \\param rand_state The random state for mutation.\n   * \\return None if mutator failed, otherwise return the mutated trace.\n   */\n  virtual Optional<tir::Trace> Apply(const tir::Trace& trace,\n                                     support::LinearCongruentialEngine::TRandState* rand_state) = 0;\n\n  /*!\n   * \\brief Clone the mutator.\n   * \\return The cloned mutator.\n   */\n  virtual Mutator Clone() const = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.Mutator\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MutatorNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MutatorNode\n * \\sa MutatorNode\n */\nclass Mutator : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief The function type of `InitializeWithTuneContext` method.\n   * \\param context The tuning context for initialization.\n   */\n  using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;\n  /*!\n   * \\brief Apply the mutator function to the given trace.\n   * \\param trace The given trace for mutation.\n   * \\return None if mutator failed, otherwise return the mutated trace.\n   */\n  using FApply = runtime::TypedPackedFunc<Optional<tir::Trace>(\n      const tir::Trace&, support::LinearCongruentialEngine::TRandState rand_state)>;\n  /*!\n   * \\brief Clone the mutator.\n   * \\return The cloned mutator.\n   */\n  using FClone = runtime::TypedPackedFunc<Mutator()>;\n  /*!\n   * \\brief Get the mutator as string with name.\n   * \\return The string of the mutator.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n  /*! \\brief Create a Mutator that mutates the decision of instruction Sample-Perfect-Tile */\n  TVM_DLL static Mutator MutateTileSize();\n  /*!\n   * \\brief Create a Mutator that mutates the parallel extent\n   * \\param max_jobs_per_core The maximum number of parallel jobs per core.\n   * \\return The created mutator.\n   */\n  TVM_DLL static Mutator MutateParallel(int64_t max_jobs_per_core);\n  /*!\n   * \\brief Create a Mutator that mutates auto unroll step\n   * \\return The mutator created\n   */\n  TVM_DLL static Mutator MutateUnroll();\n  /*!\n   * \\brief Create a Mutator that mutates the outcome of SampleComputeLocation\n   * \\return The mutator created\n   */\n  TVM_DLL static Mutator MutateComputeLocation();\n  /*!\n   * \\brief Create a Mutator that mutates auto thread binding.\n   * \\return The mutator created\n   */\n  TVM_DLL static Mutator MutateThreadBinding();\n  /*!\n   * \\brief Create a mutator with customized methods on the python-side.\n   * \\param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.\n   * \\param f_apply The packed function of `Apply`.\n   * \\param f_clone The packed function of `Clone`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The mutator created.\n   */\n  TVM_DLL static Mutator PyMutator(FInitializeWithTuneContext f_initialize_with_tune_context,\n                                   FApply f_apply, FClone f_clone, FAsString f_as_string);\n  /*! \\brief Create default mutators for LLVM */\n  TVM_DLL static Map<Mutator, FloatImm, void> DefaultLLVM();\n  /*! \\brief Create default mutators for CUDA */\n  TVM_DLL static Map<Mutator, FloatImm, void> DefaultCUDA();\n  /*! \\brief Create default mutators for CUDA with TensorCore */\n  TVM_DLL static Map<Mutator, FloatImm, void> DefaultCUDATensorCore();\n  /*! \\brief Create default mutators for Hexagon */\n  TVM_DLL static Map<Mutator, FloatImm, void> DefaultHexagon();\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Mutator, ObjectRef, MutatorNode);\n};\n\n/*! \\brief The mutator with customized methods on the python-side. */\nclass PyMutatorNode : public MutatorNode {\n public:\n  using FInitializeWithTuneContext = Mutator::FInitializeWithTuneContext;\n  using FApply = Mutator::FApply;\n  using FClone = Mutator::FClone;\n  using FAsString = Mutator::FAsString;\n  /*! \\brief The packed function to the `InitializeWithTuneContext` function. */\n  FInitializeWithTuneContext f_initialize_with_tune_context;\n  /*! \\brief The packed function to the `Apply` function. */\n  FApply f_apply;\n  /*! \\brief The packed function to the `Clone` function. */\n  FClone f_clone;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_initialize_with_tune_context` is not visited\n    // `f_apply` is not visited\n    // `f_clone` is not visited\n    // `f_as_string` is not visited\n  }\n\n  void InitializeWithTuneContext(const TuneContext& context) final;\n  Optional<tir::Trace> Apply(const tir::Trace& trace,\n                             support::LinearCongruentialEngine::TRandState* rand_state) final;\n  Mutator Clone() const final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PyMutator\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyMutatorNode, MutatorNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_MUTATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/postproc.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_POSTPROC_H_\n#define TVM_META_SCHEDULE_POSTPROC_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TuneContext;\nclass Postproc;\n\n/*!\n * \\brief Rules to apply a postprocessor to a schedule.\n */\nclass PostprocNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~PostprocNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Initialize the design space generator with tuning context.\n   * \\param context The tuning context for initialization.\n   * \\note This method is supposed to be called only once before every other method.\n   */\n  virtual void InitializeWithTuneContext(const TuneContext& context) = 0;\n\n  /*!\n   * \\brief Apply a postprocessor to the given schedule.\n   * \\param sch The schedule to be post processed.\n   * \\return Whether the postprocessor was successfully applied.\n   */\n  virtual bool Apply(const tir::Schedule& sch) = 0;\n\n  /*!\n   * \\brief Clone the postprocessor.\n   * \\return The cloned postprocessor.\n   */\n  virtual Postproc Clone() const = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.Postproc\";\n  TVM_DECLARE_BASE_OBJECT_INFO(PostprocNode, Object);\n};\n\n/*!\n * \\brief Managed reference to PostprocNode\n * \\sa PostprocNode\n */\nclass Postproc : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief The function type of `InitializeWithTuneContext` method.\n   * \\param context The tuning context for initialization.\n   */\n  using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;\n  /*!\n   * \\brief Apply a postprocessor to the given schedule.\n   * \\param sch The schedule to be post processed.\n   * \\return Whether the postprocessor was successfully applied.\n   */\n  using FApply = runtime::TypedPackedFunc<bool(const tir::Schedule&)>;\n  /*!\n   * \\brief Clone the postprocessor.\n   * \\return The cloned postprocessor.\n   */\n  using FClone = runtime::TypedPackedFunc<Postproc()>;\n  /*!\n   * \\brief Get the postprocessor function as string with name.\n   * \\return The string of the postprocessor function.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n  /*!\n   * \\brief Create a postprocessor with customized methods on the python-side.\n   * \\param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.\n   * \\param f_apply The packed function of `Apply`.\n   * \\param f_clone The packed function of `Clone`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The postprocessor created.\n   */\n  TVM_DLL static Postproc PyPostproc(FInitializeWithTuneContext f_initialize_with_tune_context,  //\n                                     FApply f_apply,                                             //\n                                     FClone f_clone,                                             //\n                                     FAsString f_as_string);\n  /*!\n   * \\brief Create a postprocessor that checks if all loops are static\n   * \\return The postprocessor created\n   */\n  TVM_DLL static Postproc DisallowDynamicLoop();\n  /*!\n   * \\brief Create a postprocessor that rewrites the cooperative fetch annotation to\n   * actual vectorized cooperative fetching in loop bindings.\n   * \\return The postprocessor created.\n   */\n  TVM_DLL static Postproc RewriteCooperativeFetch();\n  /*!\n   * \\brief Creates a postprocessor that applies parallelization, vectorization and auto unrolling\n   * according to the annotation of each block\n   * \\return The postprocessor created\n   */\n  TVM_DLL static Postproc RewriteParallelVectorizeUnroll();\n  /*!\n   * \\brief Create a postprocessor that rewrites reduction block by moving the init block out.\n   * \\return The postprocessor created.\n   */\n  TVM_DLL static Postproc RewriteReductionBlock();\n  /*!\n   * \\brief Create a postprocessor that adds thread binding to unbound blocks\n   * \\param max_threadblocks The max number of threadblocks in the cuda device.\n   * \\return The postprocessor created.\n   */\n  TVM_DLL static Postproc RewriteUnboundBlock(int max_threadblocks);\n  /*!\n   * \\brief Create a postprocessor that applies tensorization to annotated blocks\n   * \\param vectorize_init_loop Whether or not vectorize the initialization loop produced by\n   * DecomposeReduction\n   * \\return The postprocessor created.\n   */\n  TVM_DLL static Postproc RewriteTensorize(bool vectorize_init_loop = false);\n  /*!\n   * \\brief Creates a postprocessor that verifies if the GPU code is correct\n   * \\return The postprocessor created\n   */\n  TVM_DLL static Postproc VerifyGPUCode();\n  /*!\n   * \\brief Creates a postprocessor that rewrites the layout of input tensor\n   * \\note Weight layout rewrite is supported so far, activation layout rewrite will be added.\n   * \\return The postprocessor created\n   */\n  TVM_DLL static Postproc RewriteLayout();\n  /*! \\brief Create default postprocessors for LLVM */\n  TVM_DLL static Array<Postproc, void> DefaultLLVM();\n  /*! \\brief Create default postprocessors for CUDA */\n  TVM_DLL static Array<Postproc, void> DefaultCUDA();\n  /*! \\brief Create default postprocessors for CUDA with TensorCore */\n  TVM_DLL static Array<Postproc, void> DefaultCUDATensorCore();\n  /*! \\brief Create default postprocessors for Hexagon */\n  TVM_DLL static Array<Postproc, void> DefaultHexagon();\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Postproc, ObjectRef, PostprocNode);\n};\n\n/*! \\brief The postprocessor with customized methods on the python-side. */\nclass PyPostprocNode : public PostprocNode {\n public:\n  using FInitializeWithTuneContext = Postproc::FInitializeWithTuneContext;\n  using FApply = Postproc::FApply;\n  using FClone = Postproc::FClone;\n  using FAsString = Postproc::FAsString;\n  /*! \\brief The packed function to the `InitializeWithTuneContext` function. */\n  FInitializeWithTuneContext f_initialize_with_tune_context;\n  /*! \\brief The packed function to the `Apply` function. */\n  FApply f_apply;\n  /*! \\brief The packed function to the `Clone` function. */\n  FClone f_clone;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_initialize_with_tune_context` is not visited\n    // `f_apply` is not visited\n    // `f_clone` is not visited\n    // `f_as_string` is not visited\n  }\n\n  void InitializeWithTuneContext(const TuneContext& context) final;\n  bool Apply(const tir::Schedule& sch) final;\n  Postproc Clone() const final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PyPostproc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyPostprocNode, PostprocNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_POSTPROC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/profiler.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_PROFILER_H_\n#define TVM_META_SCHEDULE_PROFILER_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/target/target.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass ScopedTimer {\n public:\n  ~ScopedTimer() {\n    if (deferred_ != nullptr) {\n      deferred_();\n    }\n  }\n\n private:\n  friend class Profiler;\n\n  explicit ScopedTimer(runtime::TypedPackedFunc<void()> deferred) : deferred_(deferred) {}\n  runtime::TypedPackedFunc<void()> deferred_;\n};\n\n/*! \\brief A generic profiler */\nclass ProfilerNode : public runtime::Object {\n public:\n  /*! \\brief The segments that are already profiled */\n  std::unordered_map<std::string, double> stats_sec;\n  /*! \\brief Counter for the total time used */\n  runtime::PackedFunc total_timer;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `stats_sec` is not visited.\n    // `total_timer` is not visited.\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.Profiler\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProfilerNode, runtime::Object);\n\n public:\n  /*! \\brief Get the internal stats of the running time */\n  Map<String, FloatImm> Get() const;\n  /*! \\brief Return a summary of profiling results as table format */\n  String Table() const;\n};\n\n/*!\n * \\brief Managed reference to ProfilerNode\n * \\sa ProfilerNode\n */\nclass Profiler : public runtime::ObjectRef {\n public:\n  Profiler();\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Profiler, runtime::ObjectRef, ProfilerNode);\n\n  /*! \\brief Entering the scope of the context manager */\n  void EnterWithScope();\n  /*! \\brief Exiting the scope of the context manager */\n  void ExitWithScope();\n  /*! \\brief Returns the current profiler */\n  static Optional<Profiler> Current();\n  /*!\n   * \\brief Profile the time usage in the given scope in the given name.\n   * \\param name Name for the scope.\n   * \\return A scope timer for time profiling.\n   */\n  static ScopedTimer TimedScope(String name);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_PROFILER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/runner.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_RUNNER_H_\n#define TVM_META_SCHEDULE_RUNNER_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief Runner's input containing path of artifact, type of device and argument info. */\nclass RunnerInputNode : public runtime::Object {\n public:\n  /*! \\brief The path to the built artifact. */\n  String artifact_path;\n  /*! \\brief The type of device. */\n  String device_type;\n  /*! \\brief The argument information. */\n  Array<ArgInfo> args_info;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"artifact_path\", &artifact_path);\n    v->Visit(\"device_type\", &device_type);\n    v->Visit(\"args_info\", &args_info);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.RunnerInput\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RunnerInputNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to RunnerInputNode\n * \\sa RunnerInputNode\n */\nclass RunnerInput : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor of RunnerInput\n   * \\param artifact_path The path to the built artifact.\n   * \\param device_type The type of device.\n   * \\param args_info The argument information.\n   */\n  TVM_DLL explicit RunnerInput(String artifact_path, String device_type, Array<ArgInfo> args_info);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(RunnerInput, runtime::ObjectRef, RunnerInputNode);\n};\n\n/*! \\brief Runner's output containing measurement result of MeasureCandidate or error msg if any. */\nclass RunnerResultNode : public runtime::Object {\n public:\n  /*! \\brief The run time in seconds.*/\n  Optional<Array<FloatImm>> run_secs;\n  /*! \\brief The error message, if any. */\n  Optional<String> error_msg;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"run_secs\", &run_secs);\n    v->Visit(\"error_msg\", &error_msg);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.RunnerResult\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RunnerResultNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to RunnerResultNode\n * \\sa RunnerResultNode\n */\nclass RunnerResult : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor\n   * \\brief The run time in seconds.\n   * \\brief The error message, if any.\n   */\n  TVM_DLL explicit RunnerResult(Optional<Array<FloatImm>> run_secs, Optional<String> error_msg);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(RunnerResult, runtime::ObjectRef, RunnerResultNode);\n};\n\n/*!\n * \\brief A class to asynchronously fetch runner's output.\n * \\note The API design is consistent with python's concurrent.futures.Future:\n *  https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future\n */\nclass RunnerFutureNode : public runtime::Object {\n public:\n  /*!\n   * \\brief The function type to check whether the runner has finished.\n   * \\return Whether the runner's output is ready.\n   */\n  using FDone = runtime::TypedPackedFunc<bool()>;\n  /*!\n   * \\brief The function type to fetch runner output if it is ready.\n   * \\return The runner's output.\n   */\n  using FResult = runtime::TypedPackedFunc<RunnerResult()>;\n\n  /*! \\brief The packed function to check whether the runner has finished. */\n  FDone f_done;\n  /*! \\brief The packed function to fetch runner output if it is ready. */\n  FResult f_result;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_done` is not visited\n    // `f_result` is not visited\n  }\n\n  /*!\n   * \\brief Check whether the runner has finished.\n   * \\return A boolean indicating whether the runner has finished.\n   */\n  bool Done() const {\n    ICHECK(f_done != nullptr) << \"PyRunnerFuture's Done method not implemented!\";\n    return f_done();\n  }\n  /*!\n   * \\brief Fetch the runner's output if it is ready.\n   * \\return The runner's output.\n   */\n  RunnerResult Result() const {\n    ICHECK(f_result != nullptr) << \"PyRunnerFuture's Result method not implemented!\";\n    return f_result();\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.RunnerFuture\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RunnerFutureNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to RunnerFutureNode\n * \\sa RunnerFutureNode\n */\nclass RunnerFuture : public runtime::ObjectRef {\n public:\n  using FDone = RunnerFutureNode::FDone;\n  using FResult = RunnerFutureNode::FResult;\n\n  /*!\n   * \\brief Constructor of RunnerFuture\n   * \\param f_done The packed function to check whether the runner has finished.\n   * \\param f_result The packed function to fetch runner output if it is ready.\n   */\n  TVM_DLL explicit RunnerFuture(FDone f_done, FResult f_result);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(RunnerFuture, runtime::ObjectRef,\n                                                    RunnerFutureNode);\n};\n\n/*! \\brief The abstract runner interface. */\nclass RunnerNode : public runtime::Object {\n public:\n  /*!\n   * \\brief The function type to run the built artifacts and get runner futures.\n   * \\param input The runner's inputs.\n   * \\return The runner futures.\n   * \\sa RunnerFuture\n   */\n  using FRun = runtime::TypedPackedFunc<Array<RunnerFuture>(Array<RunnerInput>)>;\n\n  /*! \\brief Default destructor */\n  virtual ~RunnerNode() = default;\n\n  /*!\n   * \\brief Run the built artifact and get runner futures.\n   * \\param runner_inputs The runner's inputs.\n   * \\return The runner futures.\n   */\n  virtual Array<RunnerFuture> Run(Array<RunnerInput> runner_inputs) = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.Runner\";\n  TVM_DECLARE_BASE_OBJECT_INFO(RunnerNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to RunnerNode\n * \\sa RunnerNode\n */\nclass Runner : public runtime::ObjectRef {\n public:\n  using FRun = RunnerNode::FRun;\n\n  /*!\n   * \\brief Create a runner with customized build method on the python-side.\n   * \\param f_run The packed function to run the built artifacts and get runner futures.\n   * \\return The runner created.\n   */\n  TVM_DLL static Runner PyRunner(FRun f_run);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Runner, runtime::ObjectRef, RunnerNode);\n};\n\n/*! \\brief An abstract runner with customized build method on the python-side. */\nclass PyRunnerNode : public RunnerNode {\n public:\n  /*! \\brief The packed function to run the built artifacts and get runner futures. */\n  FRun f_run;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_run` is not visited\n  }\n\n  Array<RunnerFuture> Run(Array<RunnerInput> runner_inputs) final {\n    ICHECK(f_run != nullptr) << \"PyRunner's Run method not implemented!\";\n    return f_run(runner_inputs);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.PyRunner\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyRunnerNode, RunnerNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_RUNNER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/schedule/cuda/thread_bind.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_SCHEDULE_CUDA_THREAD_BIND_H_\n#define TVM_META_SCHEDULE_SCHEDULE_CUDA_THREAD_BIND_H_\n\n#include <tvm/tir/schedule/schedule.h>\n\n#include <algorithm>\n#include <limits>\n#include <utility>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*!\n * \\brief Given candidates of thread_extents, make a sampler that use `sch->SampleCategorical`\n * to return a random thread extent.\n * \\param sch The schedule\n * \\param thread_extents The candidate thread extents.\n * \\return A sampler that returns a random thread extent.\n */\nstd::function<tir::ExprRV(int64_t)> MakeFactorSampler(tir::Schedule sch,\n                                                      Array<Integer> thread_extents);\n\n/*!\n * \\brief Bind blockIdx.x and threadIdx.x to the given loop\n * \\param sch The schedule.\n * \\param loop The loop to be bound.\n * \\param max_threadblocks The maximum number of threadblocks allowed.\n * \\param max_threads_per_block The maximum number of threads allowed.\n * \\param get_factor A function that returns the tiling factor.\n */\nArray<tir::LoopRV> BindSpatialLoop(tir::Schedule sch, tir::LoopRV loop,  //\n                                   int64_t max_threadblocks, int64_t max_threads_per_block,\n                                   std::function<tir::ExprRV(int64_t)> get_factor = nullptr);\n\n/*!\n * \\brief Bind the given block if it is not bound to blockIdx or threadIdx.\n * \\param sch The schedule.\n * \\param block The block to be bound.\n * \\param max_threadblocks The maximum number of threadblocks allowed.\n * \\param max_threads_per_block The maximum number of threads allowed.\n * \\param get_factor A function that returns the tiling factor.\n */\nvoid BindBlockThreadIdx(tir::Schedule sch, tir::BlockRV block,  //\n                        int64_t max_threadblocks, int64_t max_threads_per_block,\n                        std::function<tir::ExprRV(int64_t max_extent)> get_factor = nullptr);\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SCHEDULE_CUDA_THREAD_BIND_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/schedule/generic/winograd.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_SCHEDULE_GENERIC_WINOGRAD_H_\n#define TVM_META_SCHEDULE_SCHEDULE_GENERIC_WINOGRAD_H_\n\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*!\n * \\brief Get the producer block of a given block.\n * If there is a constant winograd transform matrix, inline it.\n * \\return The only producer block.\n */\ntir::BlockRV GetWinogradProducerAndInlineConst(tir::Schedule sch, tir::BlockRV block);\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SCHEDULE_GENERIC_WINOGRAD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/schedule_rule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_META_SCHEDULE_SCHEDULE_RULE_H_\n#define TVM_META_SCHEDULE_SCHEDULE_RULE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TuneContext;\nclass ScheduleRule;\n\n/*! \\brief Rules to modify a block in a schedule. */\nclass ScheduleRuleNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor. */\n  virtual ~ScheduleRuleNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  /*!\n   * \\brief Initialize the design space generator with tuning context.\n   * \\param context The tuning context for initialization.\n   * \\note This method is supposed to be called only once before every other method.\n   */\n  virtual void InitializeWithTuneContext(const TuneContext& context) = 0;\n\n  /*!\n   * \\brief Apply a schedule rule to the specific block in the given schedule.\n   * \\param sch The schedule to be modified.\n   * \\param block The specific block to apply the schedule rule.\n   * \\return The list of schedules generated by applying the schedule rule.\n   */\n  virtual runtime::Array<tir::Schedule> Apply(const tir::Schedule& sch,\n                                              const tir::BlockRV& block) = 0;\n\n  /*!\n   * \\brief Deep clone the schedule rule.\n   * \\return The cloned schedule rule.\n   */\n  virtual ScheduleRule Clone() const = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.ScheduleRule\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ScheduleRuleNode, Object);\n};\n\n/*!\n * \\brief Managed reference to ScheduleRuleNode\n * \\sa ScheduleRuleNode\n */\nclass ScheduleRule : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief The function type of `InitializeWithTuneContext` method.\n   * \\param context The tuning context for initialization.\n   */\n  using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;\n  /*!\n   * \\brief The function type of `Apply` method.\n   * \\param sch The schedule to be modified.\n   * \\param block The specific block to apply the schedule rule.\n   * \\return The list of schedules generated by applying the schedule rule.\n   */\n  using FApply =\n      runtime::TypedPackedFunc<Array<tir::Schedule>(const tir::Schedule&, const tir::BlockRV&)>;\n  /*!\n   * \\brief Get the schedule rule as string with name.\n   * \\return The string of the schedule rule.\n   */\n  using FAsString = runtime::TypedPackedFunc<String()>;\n  /*!\n   * \\brief The function type of `Clone` method.\n   * \\return The cloned schedule rule.\n   */\n  using FClone = runtime::TypedPackedFunc<ScheduleRule()>;\n  /*!\n   * \\brief Create a rule that applies customized rules registered using block attribute\n   * `schedule_rule`. The rule will be dispatched according to target keys.\n   * \\return The created schedule rule.\n   */\n  TVM_DLL static ScheduleRule ApplyCustomRule();\n  /*! \\brief Check if the rule is `ApplyCustomRule` */\n  TVM_DLL static bool IsApplyCustomRule(const ScheduleRule& rule);\n  /*!\n   * \\brief Create an auto-inline rule that inlines spatial blocks if it satisfies some conditions\n   * \\param into_producer If allows to inline a block into its producer\n   * \\param into_consumer If allows to inline a block into its consumer\n   * \\param inline_const_tensor Always inline constant tensors\n   * \\param disallow_if_then_else Always disallow if-then-else-like constructs\n   * \\param require_ordered Always require the read-to-write mapping to be ordered\n   * \\param require_injective Always require the read-to-write mapping to be injective\n   * \\param disallow_op The operators that are disallowed in auto inline\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule AutoInline(bool into_producer,          //\n                                         bool into_consumer,          //\n                                         bool inline_const_tensor,    //\n                                         bool disallow_if_then_else,  //\n                                         bool require_injective,      //\n                                         bool require_ordered,        //\n                                         Optional<Array<String>> disallow_op);\n\n  /*!\n   * \\brief Inline blocks that produce a constant scalar. Such blocks get in the way of\n   * ReverseComputeInline during AutoInline, since they are also counted as a producer block\n   * unless they are inlined first. So it is recommended to run InlineConstantScalars before\n   * AutoInline.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule InlineConstantScalars();\n\n  /*!\n   * \\brief Create a mega rule: multi-level tiling with data reuse\n   * \\param structure The tiling structure. Recommended:\n   * - 'SSRSRS' on CPU\n   * - 'SSSRRSRS' on GPU\n   * \\param tile_binds For each level of tiles, which thread axis it is bound to. Recommended:\n   * - NullOpt on CPU\n   * - [blockIdx.x, vthread.x, threadIdx.x] on GPU\n   * \\param max_innermost_factor The maximum size of the innermost factor. NullOpt means no limit\n   * \\param vector_load_lens The length of vector lane in vectorized cooperative fetching.\n   * NullOpt means disable vectorization\n   * \\param reuse_read Data reuse configuration for reading. NullOpt means no reuse.\n   * \\param reuse_write Data reuse configuration for writing. NullOpt means no reuse.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule MultiLevelTiling(String structure,                             //\n                                               Optional<Array<String>> tile_binds,           //\n                                               Optional<Integer> max_innermost_factor,       //\n                                               Optional<Array<Integer>> vector_load_lens,    //\n                                               Optional<Map<String, ObjectRef>> reuse_read,  //\n                                               Optional<Map<String, ObjectRef>> reuse_write);\n\n  /*!\n   * \\brief Extension of MultiLevelTiling for auto-tensorization with a single intrinsic.\n   * \\param intrin_name The name of a tensor intrinsic, must be registered via\n   * TensorIntrin.register(...) beforehand\n   * \\param structure The tiling structure. Recommended:\n   * - 'SSRSRS' on CPU\n   * - 'SSSRRSRS' on GPU\n   * \\param tile_binds For each level of tiles, which thread axis it is bound to. Recommended:\n   * - NullOpt on CPU\n   * - [blockIdx.x, vthread.x, threadIdx.x] on GPU\n   * \\param max_innermost_factor The maximum size of the innermost factor. NullOpt means no limit\n   * \\param vector_load_lens The length of vector lane in vectorized cooperative fetching.\n   * NullOpt means disable vectorization\n   * \\param reuse_read Data reuse configuration for reading. NullOpt means no reuse.\n   * \\param reuse_write Data reuse configuration for writing. NullOpt means no reuse.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule MultiLevelTilingWithIntrin(\n      String intrin_name, String structure, Optional<Array<String>> tile_binds,\n      Optional<Integer> max_innermost_factor, Optional<Array<Integer>> vector_load_lens,\n      Optional<Map<String, ObjectRef>> reuse_read, Optional<Map<String, ObjectRef>> reuse_write);\n\n  /*!\n   * \\brief Extension of MultiLevelTiling for auto-tensorization with multiple groups of candidate\n   * tensor core intrinsics\n   * \\param intrin_groups A list of groups of tensor core intrinsics. The map should contains key\n   * \"init\", \"load_a\", \"load_b\", \"compute\", \"store\", which represent the tensor intrin for\n   * initialization, loading operand A, loading operand B, tensor core computation, storing the\n   * result. The value of the map should be names of tensor intrinsics, must be registered via\n   * TensorIntrin.register(...) beforehand\n   * \\param structure The tiling structure. Recommended:\n   * - 'SSSRRSRS' on GPU\n   * \\param tile_binds For each level of tiles, which thread axis it is bound to. Recommended:\n   * - [blockIdx.y, blockIdx.x, threadIdx.y] on GPU\n   * \\param max_innermost_factor The maximum size of the innermost factor. NullOpt means no limit\n   * \\param vector_load_lens The length of vector lane in vectorized cooperative fetching.\n   * NullOpt means disable vectorization\n   * \\param reuse_read Data reuse configuration for reading. NullOpt means no reuse.\n   * \\param reuse_write Data reuse configuration for writing. NullOpt means no reuse.\n   * \\param use_software_pipeline Whether use the software pipeline.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule MultiLevelTilingTensorCore(\n      Array<Map<String, String>> intrin_groups, String structure,\n      Optional<Array<String>> tile_binds, Optional<Integer> max_innermost_factor,\n      Optional<Array<Integer>> vector_load_lens, Optional<Map<String, ObjectRef>> reuse_read,\n      Optional<Map<String, ObjectRef>> reuse_write, bool use_software_pipeline);\n\n  /*!\n   * \\brief Extension of MultiLevelTiling for backends with wide vectors.\n   * The loop over the innermost spatial axis of the output buffer is always vectorized with the\n   * maximum vector length.\n   * \\param structure The tiling structure. 'SSRSRS' is recommended.\n   * \\param vector_length_in_bits The length of a vector register in bits.\n   * \\param max_innermost_factor The maximum size of the innermost factor. NullOpt means no limit\n   * \\param reuse_read Data reuse configuration for reading. NullOpt means no reuse.\n   * \\param reuse_write Data reuse configuration for writing. NullOpt means no reuse.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule MultiLevelTilingWideVector(\n      String structure, Integer vector_length_in_bits, Optional<Integer> max_innermost_factor,\n      Optional<Map<String, ObjectRef>> reuse_read, Optional<Map<String, ObjectRef>> reuse_write);\n\n  /*!\n   * \\brief Create a rule: add-rfactor to some blocks if needed\n   * \\param max_jobs_per_core The maximum number of jobs to be launched per CPU core. It sets the\n   * uplimit of CPU parallelism, i.e. `num_cores * max_jobs_per_core`. Use -1 to disable\n   * parallelism.\n   * \\param max_innermost_factor The maximum size of the innermost factor. NullOpt means no limit\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule AddRFactor(int max_jobs_per_core,  //\n                                         Optional<Integer> max_innermost_factor);\n  /*!\n   * \\brief Create a schedule rule which applies cross-thread reduction to some reduction blocks\n   * correspondingly when needed\n   * \\param thread_extents Candidates of thread axis extent (values are required to be positive).\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule CrossThreadReduction(Array<Integer> thread_extents);\n  /*!\n   * \\brief A rule that randomly select a compute-at location for a free block\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule RandomComputeLocation();\n  /*!\n   * \\brief Mark parallelize, vectorize and unroll to the root block. The mark will be applied to\n   * each block in a follow-up post processor\n   * \\param max_jobs_per_core The maximum number of jobs to be launched per CPU core. It sets the\n   * upper limit of CPU parallelism, i.e. `num_cores * max_jobs_per_core`. Use -1 to disable\n   * parallelism.\n   * \\param max_vectorize_extent The maximum extent to be vectorized.\n   * It sets the upper limit of the hardware target vectorization. Use -1 to disable vectorization.\n   * \\param unroll_max_steps The options of the maximum number of unroll steps to be done.\n   * Use an empty array to disable unroll.\n   * \\param unroll_explicit Whether to explicitly unroll the loop, or just add an \"unroll\" pragma.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule ParallelizeVectorizeUnroll(int max_jobs_per_core,            //\n                                                         int max_vectorize_extent,         //\n                                                         Array<Integer> unroll_max_steps,  //\n                                                         bool unroll_explicit);\n  /*!\n   * \\brief Auto bind loops around the block to BlockIdx and ThreadIdx\n   * \\param max_threadblocks The maximum number of threadblock on GPU\n   * \\param thread_extents Candidates of thread axis extent.\n   * \\param max_threads_per_block The maximum number of threads per block, if it is known\n   * when this schedule rule is created.\n   * \\return The schedule rule created\n   */\n  TVM_DLL static ScheduleRule AutoBind(int max_threadblocks, Array<Integer> thread_extents,\n                                       int max_threads_per_block = -1);\n  /*!\n   * \\brief Create a schedule rule with customized methods on the python-side.\n   * \\param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.\n   * \\param f_apply The packed function of `Apply`.\n   * \\param f_clone The packed function of `Clone`.\n   * \\param f_as_string The packed function of `AsString`.\n   * \\return The schedule rule created.\n   */\n  TVM_DLL static ScheduleRule PyScheduleRule(\n      FInitializeWithTuneContext f_initialize_with_tune_context,  //\n      FApply f_apply,                                             //\n      FClone f_clone,                                             //\n      FAsString f_as_string);\n\n  /*! \\brief Create default schedule rules for LLVM */\n  TVM_DLL static Array<ScheduleRule, void> DefaultLLVM();\n  /*! \\brief Create default schedule rules for CUDA */\n  TVM_DLL static Array<ScheduleRule, void> DefaultCUDA();\n  /*! \\brief Create default postprocessors for CUDA with TensorCore */\n  TVM_DLL static Array<ScheduleRule, void> DefaultCUDATensorCore();\n  /*! \\brief Create default schedule rules for Hexagon */\n  TVM_DLL static Array<ScheduleRule, void> DefaultHexagon();\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ScheduleRule, ObjectRef, ScheduleRuleNode);\n};\n\n/*! \\brief The schedule rule with customized methods on the python-side. */\nclass PyScheduleRuleNode : public ScheduleRuleNode {\n public:\n  using FInitializeWithTuneContext = ScheduleRule::FInitializeWithTuneContext;\n  using FApply = ScheduleRule::FApply;\n  using FClone = ScheduleRule::FClone;\n  using FAsString = ScheduleRule::FAsString;\n\n  /*! \\brief The packed function to the `InitializeWithTuneContext` function. */\n  FInitializeWithTuneContext f_initialize_with_tune_context;\n  /*! \\brief The packed function to the `Apply` function. */\n  FApply f_apply;\n  /*! \\brief The packed function to the `AsString` function. */\n  FAsString f_as_string;\n  /*! \\brief The packed function to the `Clone` function. */\n  FClone f_clone;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_initialize_with_tune_context` is not visited\n    // `f_apply` is not visited\n    // `f_as_string` is not visited\n    // `f_clone` is not visited\n  }\n\n  void InitializeWithTuneContext(const TuneContext& context) final;\n  Array<tir::Schedule> Apply(const tir::Schedule& sch, const tir::BlockRV& block) final;\n  ScheduleRule Clone() const final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PyScheduleRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyScheduleRuleNode, ScheduleRuleNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SCHEDULE_RULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/search_strategy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_SEARCH_STRATEGY_H_\n#define TVM_META_SCHEDULE_SEARCH_STRATEGY_H_\n\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/meta_schedule/cost_model.h>\n#include <tvm/meta_schedule/database.h>\n#include <tvm/meta_schedule/measure_candidate.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n// Forward declaration\nclass TuneContext;\nclass SearchStrategy;\n\n/*!\n * \\brief The search strategy for measure candidates generation.\n * \\note The relationship between SearchStrategy and other classes are as follows:\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n   \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502\n\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Tune Context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                       \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502   Generate            \u2502  \u2502  \u2502\n\u2502                \u2502   Space Generator   \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502              \u2502        \u2502  \u2502  \u2502\n\u2502                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \u25bc        \u2502  \u2502  \u2502\n\u2502                                                Design Space  \u2502  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \u2502        \u2502  \u2502  \u2502\n\u2502      Generate  \u2502                     \u2502   Pretuning  \u2502        \u2502  \u2502  \u2502\n\u2502    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524   Search Strategy   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \u2502  \u2502  \u2502\n\u2502    \u2502           \u2502                     \u2502                       \u2502  \u251c\u2500\u2500\u2518\n\u2502    \u2502           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                       \u251c\u2500\u2500\u2518\n\u2514\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n     \u2502\n     \u2502\n\u250c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Managed By Task Scheduler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502    \u2502                                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                  \u2502\n\u2502    \u2502                      Send to    \u2502           \u2502  Send to         \u2502\n\u2502    \u25bc                  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502  Builder  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \u2502\n\u2502 Measure Candidate     \u2502   Builder    \u2502           \u2502  Runner  \u2502       \u2502\n\u2502    \u2502                  \u2502              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2502       \u2502\n\u2502    \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                            \u2502       \u2502\n\u2502    \u2502     \u2502                     \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u2502       \u2502\n\u2502    \u2514\u2500\u2500\u2500\u2500\u25ba\u2502   Task Scheduler    \u2502     \u2502           \u2502          \u2502       \u2502\n\u2502          \u2502                     \u2502     \u2502  Runner   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \u2502\n\u2502          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2502           \u2502                  \u2502\n\u2502                   \u25b2                  \u2514\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2518                  \u2502\n\u2502                   \u2502                        \u2502                        \u2502\n\u2502                   \u2514\u2500\u2500\u2500  Runner Future \u25c4\u2500\u2500\u2500\u2500\u2518                        \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n*/\nclass SearchStrategyNode : public runtime::Object {\n public:\n  /*! \\brief Virtual destructor */\n  virtual ~SearchStrategyNode() = default;\n\n  /*!\n   * \\brief Initialize the search strategy with tuning context.\n   * \\param context The tuning context for initialization.\n   * \\note This method is supposed to be called only once before every other method.\n   */\n  virtual void InitializeWithTuneContext(const TuneContext& context) = 0;\n\n  /*!\n   * \\brief Pre-tuning for the search strategy.\n   * \\param max_trials The maximum number of trials.\n   * \\param num_trials_per_iter The number of trials per iteration.\n   * \\param design_spaces The design spaces used during tuning process.\n   * \\param database The database used during tuning process.\n   * \\param cost_model The cost model used during tuning process.\n   * \\note Pre-tuning is supposed to be called before the tuning process and after the\n   *  initialization. Because the search strategy is stateful, we can always call pretuning\n   *  and reset the search strategy.\n   */\n  virtual void PreTuning(int max_trials, int num_trials_per_iter,\n                         const Array<tir::Schedule>& design_spaces,\n                         const Optional<Database>& database,\n                         const Optional<CostModel>& cost_model) = 0;\n\n  /*!\n   * \\brief Post-tuning for the search strategy.\n   * \\note Post-tuning is supposed to be called after the tuning process and before we reset the\n   *  search strategy with another pre-tuning. Post-tuning can be empty.\n   */\n  virtual void PostTuning() = 0;\n\n  /*!\n   * \\brief Generate measure candidates from design spaces for measurement.\n   * \\return The measure candidates generated, nullptr if finished.\n   */\n  virtual Optional<Array<MeasureCandidate>> GenerateMeasureCandidates() = 0;\n\n  /*!\n   * \\brief Update the search strategy with measurement results.\n   * \\param measure_candidates The candidates to be measured.\n   * \\param results The measurement results from the runner.\n   */\n  virtual void NotifyRunnerResults(const Array<MeasureCandidate>& measure_candidates,\n                                   const Array<RunnerResult>& results) = 0;\n\n  /*!\n   * \\brief Clone the search strategy.\n   * \\return The cloned search strategy.\n   */\n  virtual SearchStrategy Clone() const = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.SearchStrategy\";\n  TVM_DECLARE_BASE_OBJECT_INFO(SearchStrategyNode, Object);\n};\n\n/*!\n * \\brief Managed reference to SearchStrategyNode.\n * \\sa SearchStrategyNode\n */\nclass SearchStrategy : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief The function type of `InitializeWithTuneContext` method.\n   * \\param context The tuning context for initialization.\n   */\n  using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;\n  /*!\n   * \\brief The function type of `PreTuning` method.\n   */\n  using FPreTuning = runtime::TypedPackedFunc<void(\n      int max_trials, int num_trials_per_iter, const Array<tir::Schedule>&,\n      const Optional<Database>&, const Optional<CostModel>&)>;\n  /*! \\brief The function type of `PostTuning` method. */\n  using FPostTuning = runtime::TypedPackedFunc<void()>;\n  /*!\n   * \\brief The function type of `GenerateMeasureCandidates` method.\n   * \\return The measure candidates generated, nullptr if finished.\n   */\n  using FGenerateMeasureCandidates = runtime::TypedPackedFunc<Optional<Array<MeasureCandidate>>()>;\n  /*!\n   * \\brief The function type of `NotifyRunnerResults` method.\n   * \\param results The measurement results from the runner.\n   */\n  using FNotifyRunnerResults =\n      runtime::TypedPackedFunc<void(const Array<MeasureCandidate>&, const Array<RunnerResult>&)>;\n  /*!\n   * \\brief The function type of `Clone` method.\n   * \\return The cloned search strategy.\n   */\n  using FClone = runtime::TypedPackedFunc<SearchStrategy()>;\n  /*!\n   * \\brief Create a search strategy with customized methods on the python-side.\n   * \\param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.\n   * \\param f_pre_tuning The packed function of `PreTuning`.\n   * \\param f_post_tuning The packed function of `PostTuning`.\n   * \\param f_generate_measure_candidates The packed function of `GenerateMeasureCandidates`.\n   * \\param f_notify_runner_results The packed function of `NotifyRunnerResults`.\n   * \\param f_clone The packed function of `Clone`.\n   * \\return The search strategy created.\n   */\n  TVM_DLL static SearchStrategy PySearchStrategy(\n      FInitializeWithTuneContext f_initialize_with_tune_context,  //\n      FPreTuning f_pre_tuning,                                    //\n      FPostTuning f_post_tuning,                                  //\n      FGenerateMeasureCandidates f_generate_measure_candidates,   //\n      FNotifyRunnerResults f_notify_runner_results,               //\n      FClone f_clone);\n\n  /*!\n   * \\brief Constructor of replay trace search strategy.\n   * \\param max_fail_count The max number of failures during trace replaying.\n   */\n  TVM_DLL static SearchStrategy ReplayTrace(int max_fail_count);\n\n  /*! \\brief Constructor of replay func search strategy. */\n  TVM_DLL static SearchStrategy ReplayFunc();\n\n  /*!\n   * \\brief Constructor of evolutionary search strategy.\n   * \\param population_size The initial sample population.\n   * \\param init_measured_ratio The ratio of measures samples in initial population.\n   * \\param init_min_unmeasured The minimal size of unmeasured population in the initial sampling.\n   * \\param max_fail_count The max number of failure during initial sampling.\n   * \\param genetic_num_iters The iterations to run the genetic algorithm.\n   * \\param genetic_mutate_prob The probability of mutation.\n   * \\param genetic_max_fail_count The maximum number to try evolving the given trace.\n   * \\param eps_greedy The ratio to select samples in a greedy fashion via their predicted score.\n   */\n  TVM_DLL static SearchStrategy EvolutionarySearch(int population_size,         //\n                                                   double init_measured_ratio,  //\n                                                   int init_min_unmeasured,     //\n                                                   int max_fail_count,          //\n                                                   int genetic_num_iters,       //\n                                                   double genetic_mutate_prob,  //\n                                                   int genetic_max_fail_count,  //\n                                                   double eps_greedy);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(SearchStrategy, ObjectRef, SearchStrategyNode);\n};\n\n/*! \\brief The python side customizable class for measure candidate generation */\nclass PySearchStrategyNode : public SearchStrategyNode {\n public:\n  using FInitializeWithTuneContext = SearchStrategy::FInitializeWithTuneContext;\n  using FPreTuning = SearchStrategy::FPreTuning;\n  using FPostTuning = SearchStrategy::FPostTuning;\n  using FGenerateMeasureCandidates = SearchStrategy::FGenerateMeasureCandidates;\n  using FNotifyRunnerResults = SearchStrategy::FNotifyRunnerResults;\n  using FClone = SearchStrategy::FClone;\n\n  /*! \\brief The packed function to the `InitializeWithTuneContext` method. */\n  FInitializeWithTuneContext f_initialize_with_tune_context;\n  /*! \\brief The packed function to the `PreTuning` method. */\n  FPreTuning f_pre_tuning;\n  /*! \\brief The packed function to the `PostTuning` method. */\n  FPostTuning f_post_tuning;\n  /*! \\brief The packed function to the `GenerateMeasureCandidates` method. */\n  FGenerateMeasureCandidates f_generate_measure_candidates;\n  /*! \\brief The packed function to the `NotifyRunnerResults` method. */\n  FNotifyRunnerResults f_notify_runner_results;\n  /*! \\brief The packed function to the `Clone` method. */\n  FClone f_clone;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `f_initialize_with_tune_context` is not visited\n    // `f_pre_tuning` is not visited\n    // `f_post_tuning` is not visited\n    // `f_generate_measure_candidates` is not visited\n    // `f_notify_runner_results` is not visited\n    // `f_clone` is not visited\n  }\n\n  void InitializeWithTuneContext(const TuneContext& context) final;\n  void PreTuning(int max_trials, int num_trials_per_iter, const Array<tir::Schedule>& design_spaces,\n                 const Optional<Database>& database, const Optional<CostModel>& cost_model) final;\n  void PostTuning() final;\n  Optional<Array<MeasureCandidate>> GenerateMeasureCandidates() final;\n  void NotifyRunnerResults(const Array<MeasureCandidate>& measure_candidates,\n                           const Array<RunnerResult>& results);\n  SearchStrategy Clone() const final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PySearchStrategy\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PySearchStrategyNode, SearchStrategyNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SEARCH_STRATEGY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/space_generator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_SPACE_GENERATOR_H_\n#define TVM_META_SCHEDULE_SPACE_GENERATOR_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/meta_schedule/mutator.h>\n#include <tvm/meta_schedule/postproc.h>\n#include <tvm/meta_schedule/schedule_rule.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/schedule/schedule.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n// Forward declaration\nclass TuneContext;\nclass SpaceGenerator;\n\n/*!\n * \\brief The abstract class for design space generation.\n * \\note The relationship between SpaceGenerator and other classes are as follows:\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n   \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502\n\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Tune Context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                       \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502   Generate            \u2502  \u2502  \u2502\n\u2502                \u2502   Space Generator   \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502              \u2502        \u2502  \u2502  \u2502\n\u2502                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \u25bc        \u2502  \u2502  \u2502\n\u2502                                                Design Space  \u2502  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \u2502        \u2502  \u2502  \u2502\n\u2502      Generate  \u2502                     \u2502   Pretuning  \u2502        \u2502  \u2502  \u2502\n\u2502    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524   Search Strategy   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \u2502  \u2502  \u2502\n\u2502    \u2502           \u2502                     \u2502                       \u2502  \u251c\u2500\u2500\u2518\n\u2502    \u2502           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                       \u251c\u2500\u2500\u2518\n\u2514\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n     \u2502\n     \u2502\n\u250c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Managed By Task Scheduler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502    \u2502                                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                  \u2502\n\u2502    \u2502                      Send to    \u2502           \u2502  Send to         \u2502\n\u2502    \u25bc                  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502  Builder  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \u2502\n\u2502 Measure Candidate     \u2502   Builder    \u2502           \u2502  Runner  \u2502       \u2502\n\u2502    \u2502                  \u2502              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2502       \u2502\n\u2502    \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                            \u2502       \u2502\n\u2502    \u2502     \u2502                     \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u2502       \u2502\n\u2502    \u2514\u2500\u2500\u2500\u2500\u25ba\u2502   Task Scheduler    \u2502     \u2502           \u2502          \u2502       \u2502\n\u2502          \u2502                     \u2502     \u2502  Runner   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \u2502\n\u2502          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2502           \u2502                  \u2502\n\u2502                   \u25b2                  \u2514\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2518                  \u2502\n\u2502                   \u2502                        \u2502                        \u2502\n\u2502                   \u2514\u2500\u2500\u2500  Runner Future \u25c4\u2500\u2500\u2500\u2500\u2518                        \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n*/\nclass SpaceGeneratorNode : public runtime::Object {\n public:\n  /*! \\brief The schedule rules. */\n  Optional<Array<ScheduleRule>> sch_rules;\n  /*! \\brief The postprocessors. */\n  Optional<Array<Postproc>> postprocs;\n  /*! \\brief The probability of using certain mutator. */\n  Optional<Map<Mutator, FloatImm>> mutator_probs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"sch_rules\", &sch_rules);\n    v->Visit(\"postprocs\", &postprocs);\n    v->Visit(\"mutator_probs\", &mutator_probs);\n  }\n\n  /*! \\brief Default destructor */\n  virtual ~SpaceGeneratorNode() = default;\n\n  /*!\n   * \\brief Initialize the design space generator with tuning context.\n   * \\param context The tuning context for initialization.\n   * \\note This method is supposed to be called only once before every other method.\n   */\n  virtual void InitializeWithTuneContext(const TuneContext& context);\n\n  /*!\n   * \\brief Generate design spaces given a module.\n   * \\param mod The module used for design space generation.\n   * \\return The generated design spaces, i.e., schedules.\n   */\n  virtual Array<tir::Schedule> GenerateDesignSpace(const IRModule& mod) = 0;\n\n  /*!\n   * \\brief Clone the space generator.\n   * \\return The cloned space generator.\n   */\n  virtual SpaceGenerator Clone() const = 0;\n\n  static constexpr const char* _type_key = \"meta_schedule.SpaceGenerator\";\n  TVM_DECLARE_BASE_OBJECT_INFO(SpaceGeneratorNode, Object);\n};\n\n/*!\n * \\brief Managed reference to SpaceGeneratorNode.\n * \\sa SpaceGeneratorNode\n */\nclass SpaceGenerator : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief The function type of `InitializeWithTuneContext` method.\n   * \\param context The tuning context for initialization.\n   */\n  using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;\n  /*!\n   * \\brief The function type of `GenerateDesignSpace` method.\n   * \\param mod The module used for design space generation.\n   * \\return The generated design spaces, i.e., schedules.\n   */\n  using FGenerateDesignSpace = runtime::TypedPackedFunc<Array<tir::Schedule>(const IRModule&)>;\n  /*!\n   * \\brief The function type of `Clone` method.\n   * \\return The cloned space generator.\n   */\n  using FClone = runtime::TypedPackedFunc<SpaceGenerator()>;\n\n protected:\n  SpaceGenerator() = default;\n\n public:\n  /*!\n   * \\brief Create a design space generator with customized methods on the python-side.\n   * \\param sch_rules The schedule rules.\n   * \\param postprocs The postprocessors.\n   * \\param mutator_probs The probability of using certain mutator.\n   * \\param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.\n   * \\param f_generate_design_space The packed function of `GenerateDesignSpace`.\n   * \\param f_clone The packed function of `Clone`.\n   * \\return The design space generator created.\n   */\n  TVM_DLL static SpaceGenerator PySpaceGenerator(\n      Optional<Array<ScheduleRule>> sch_rules, Optional<Array<Postproc>> postprocs,\n      Optional<Map<Mutator, FloatImm>> mutator_probs,\n      FInitializeWithTuneContext f_initialize_with_tune_context,\n      FGenerateDesignSpace f_generate_design_space, FClone f_clone);\n  /*!\n   * \\brief Create a design space generator with customized schedule function.\n   * \\param schedule_fn The schedule function, which can have the following signatures:\n   * 1) void(Schedule)\n   * 2) Schedule(Schedule)\n   * 3) Array<Schedule>(Schedule)\n   * \\param sch_rules The schedule rules.\n   * \\param postprocs The postprocessors.\n   * \\param mutator_probs The probability of using certain mutator.\n   */\n  TVM_DLL static SpaceGenerator ScheduleFn(PackedFunc schedule_fn,\n                                           Optional<Array<ScheduleRule>> sch_rules,\n                                           Optional<Array<Postproc>> postprocs,\n                                           Optional<Map<Mutator, FloatImm>> mutator_probs);\n  /*!\n   * \\brief Create a design space generator that is union of multiple design space generators.\n   * \\param space_generators An array of design space generators to be unioned.\n   * \\param sch_rules The schedule rules.\n   * \\param postprocs The postprocessors.\n   * \\param mutator_probs The probability of using certain mutator.\n   * \\return The design space generator created.\n   */\n  TVM_DLL static SpaceGenerator SpaceGeneratorUnion(Array<SpaceGenerator, void> space_generators,\n                                                    Optional<Array<ScheduleRule>> sch_rules,\n                                                    Optional<Array<Postproc>> postprocs,\n                                                    Optional<Map<Mutator, FloatImm>> mutator_probs);\n  /*!\n   * \\brief Create a design space generator that generates design spaces by applying schedule\n   * rules to blocks in post-DFS order.\n   * \\param f_block_filter The filter function to filter blocks to be applied with schedule rules.\n   * \\param sch_rules The schedule rules.\n   * \\param postprocs The postprocessors.\n   * \\param mutator_probs The probability of using certain mutator.\n   * \\return The design space generator created.\n   */\n  TVM_DLL static SpaceGenerator PostOrderApply(runtime::PackedFunc f_block_filter,\n                                               Optional<Array<ScheduleRule>> sch_rules,\n                                               Optional<Array<Postproc>> postprocs,\n                                               Optional<Map<Mutator, FloatImm>> mutator_probs);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(SpaceGenerator, ObjectRef, SpaceGeneratorNode);\n};\n\n/*! \\brief The design space generator with customized methods on the python-side. */\nclass PySpaceGeneratorNode : public SpaceGeneratorNode {\n public:\n  using FInitializeWithTuneContext = SpaceGenerator::FInitializeWithTuneContext;\n  using FGenerateDesignSpace = SpaceGenerator::FGenerateDesignSpace;\n  using FClone = SpaceGenerator::FClone;\n  /*! \\brief The packed function to the `InitializeWithTuneContext` function. */\n  FInitializeWithTuneContext f_initialize_with_tune_context;\n  /*! \\brief The packed function to the `GenerateDesignSpace` function. */\n  FGenerateDesignSpace f_generate_design_space;\n  /*! \\brief The packed function to the `Clone` function. */\n  FClone f_clone;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    SpaceGeneratorNode::VisitAttrs(v);\n    // `f_initialize_with_tune_context` is not visited\n    // `f_generate_design_space` is not visited\n    // `f_clone` is not visited\n  }\n\n  void InitializeWithTuneContext(const TuneContext& context) final;\n  Array<tir::Schedule> GenerateDesignSpace(const IRModule& mod) final;\n  SpaceGenerator Clone() const final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PySpaceGenerator\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PySpaceGeneratorNode, SpaceGeneratorNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SPACE_GENERATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/task_scheduler.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_TASK_SCHEDULER_H_\n#define TVM_META_SCHEDULE_TASK_SCHEDULER_H_\n\n#include <tvm/meta_schedule/builder.h>\n#include <tvm/meta_schedule/cost_model.h>\n#include <tvm/meta_schedule/measure_callback.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/meta_schedule/tune_context.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/support/random_engine.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TaskRecordNode : public runtime::Object {\n public:\n  /*! \\brief The tune context of the task. */\n  TuneContext ctx{nullptr};\n  /*! \\brief The weight of the task */\n  double task_weight{1.0};\n  /*! \\brief The FLOP count of the task */\n  double flop{1.0};\n  /*! \\brief Whether the tuning task has been stopped or finished. */\n  bool is_terminated = false;\n  /*! \\brief Builder errors happens in the task */\n  int build_error_count = 0;\n  /*! \\brief Runner errors happens in the task */\n  int run_error_count = 0;\n  /*! \\brief The latency of each run, in milliseconds. */\n  std::vector<double> latency_ms = {};\n  /*! \\brief The measure candidates. */\n  Optional<Array<MeasureCandidate>> measure_candidates = NullOpt;\n  /*! \\brief The building results. */\n  Optional<Array<BuilderResult>> builder_results = NullOpt;\n  /*! \\brief Packed functions to fetch the runner results asynchronously. */\n  Optional<Array<RunnerFuture>> runner_futures = NullOpt;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"ctx\", &ctx);\n    v->Visit(\"task_weight\", &task_weight);\n    v->Visit(\"flop\", &flop);\n    v->Visit(\"is_terminated\", &is_terminated);\n    v->Visit(\"build_error_count\", &build_error_count);\n    v->Visit(\"run_error_count\", &run_error_count);\n    // `latency_ms` is not visited\n    v->Visit(\"measure_candidates\", &measure_candidates);\n    v->Visit(\"builder_results\", &builder_results);\n    v->Visit(\"runner_futures\", &runner_futures);\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.TaskRecord\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TaskRecordNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TaskRecordNode.\n * \\sa TaskRecordNode\n */\nclass TaskRecord : public runtime::ObjectRef {\n public:\n  /*! \\brief Constructor */\n  explicit TaskRecord(TuneContext task, double task_weight);\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(TaskRecord, ObjectRef, TaskRecordNode);\n};\n\n/*!\n * \\brief The abstract interface of task schedulers.\n * \\note The relationship between SpaceGenerator and other classes are as follows:\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n   \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502\n\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Tune Context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                       \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502   Generate            \u2502  \u2502  \u2502\n\u2502                \u2502   Space Generator   \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u2502  \u2502  \u2502\n\u2502                \u2502                     \u2502              \u2502        \u2502  \u2502  \u2502\n\u2502                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \u25bc        \u2502  \u2502  \u2502\n\u2502                                                Design Space  \u2502  \u2502  \u2502\n\u2502                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \u2502        \u2502  \u2502  \u2502\n\u2502      Generate  \u2502                     \u2502   Pretuning  \u2502        \u2502  \u2502  \u2502\n\u2502    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524   Search Strategy   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \u2502  \u2502  \u2502\n\u2502    \u2502           \u2502                     \u2502                       \u2502  \u251c\u2500\u2500\u2518\n\u2502    \u2502           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                       \u251c\u2500\u2500\u2518\n\u2514\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n     \u2502\n     \u2502\n\u250c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Managed By Task Scheduler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502    \u2502                                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                  \u2502\n\u2502    \u2502                      Send to    \u2502           \u2502  Send to         \u2502\n\u2502    \u25bc                  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba\u2502  Builder  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \u2502\n\u2502 Measure Candidate     \u2502   Builder    \u2502           \u2502  Runner  \u2502       \u2502\n\u2502    \u2502                  \u2502              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2502       \u2502\n\u2502    \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                            \u2502       \u2502\n\u2502    \u2502     \u2502                     \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u2502       \u2502\n\u2502    \u2514\u2500\u2500\u2500\u2500\u25ba\u2502   Task Scheduler    \u2502     \u2502           \u2502          \u2502       \u2502\n\u2502          \u2502                     \u2502     \u2502  Runner   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \u2502\n\u2502          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2502           \u2502                  \u2502\n\u2502                   \u25b2                  \u2514\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2518                  \u2502\n\u2502                   \u2502                        \u2502                        \u2502\n\u2502                   \u2514\u2500\u2500\u2500  Runner Future \u25c4\u2500\u2500\u2500\u2500\u2518                        \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n*/\nclass TaskSchedulerNode : public runtime::Object {\n public:\n  /*! \\brief The tuning task's logging function. */\n  PackedFunc logger;\n  /*! \\brief Records for each task */\n  Array<TaskRecord> tasks_;\n  /*! \\brief The list of measure callbacks of the scheduler. */\n  Array<MeasureCallback> measure_callbacks_;\n  /*! \\brief The database used in tuning */\n  Optional<Database> database_;\n  /*! \\brief The cost model used in tuning */\n  Optional<CostModel> cost_model_;\n  /*! \\brief The number of remaining tasks to be tuned. */\n  int remaining_tasks_;\n\n  /*! \\brief The default destructor. */\n  virtual ~TaskSchedulerNode() = default;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `logger` is not visited\n    v->Visit(\"tasks_\", &tasks_);\n    v->Visit(\"measure_callbacks_\", &measure_callbacks_);\n    v->Visit(\"database_\", &database_);\n    v->Visit(\"cost_model_\", &cost_model_);\n    v->Visit(\"remaining_tasks_\", &remaining_tasks_);\n  }\n\n  /*!\n   * \\brief Fetch the next task id.\n   * \\return The next task id.\n   */\n  virtual int NextTaskId() = 0;\n  /*!\n   * \\brief Wait until the task is finished.\n   * \\param task_id The task id to be joined.\n   * \\return The results from the runner.\n   */\n  virtual Array<RunnerResult> JoinRunningTask(int task_id);\n  /*!\n   * \\brief Jointly tune a given list of tasks.\n   * \\param tasks The tasks to be tuned\n   * \\param task_weights The weight of each task\n   * \\param max_trials_global The maximum number of trials to be performed globally\n   * \\param max_trials_per_task The maximum number of trials to be performed for each task\n   * \\param num_trials_per_iter The number of trials to be performed in each iteration\n   * \\param builder The MetaSchedule builder\n   * \\param runner The MetaSchedule runner\n   * \\param measure_callbacks The callbacks to be called after each measurement\n   * \\param database The database used in tuning\n   * \\param cost_model The cost model used in tuning\n   */\n  virtual void Tune(Array<TuneContext> tasks,                  //\n                    Array<FloatImm> task_weights,              //\n                    int max_trials_global,                     //\n                    int max_trials_per_task,                   //\n                    int num_trials_per_iter,                   //\n                    Builder builder,                           //\n                    Runner runner,                             //\n                    Array<MeasureCallback> measure_callbacks,  //\n                    Optional<Database> database,               //\n                    Optional<CostModel> cost_model);\n  /*!\n   * \\brief Terminate a task\n   * \\param task_id The id of the task to be terminated\n   */\n  void TerminateTask(int task_id);\n  /*!\n   * \\brief Touch the task and update its status\n   * \\param task_id The task id to be checked.\n   */\n  void TouchTask(int task_id);\n  /*! \\brief Print out a human-readable format of the tuning statistics. */\n  void PrintTuningStatistics();\n\n  static constexpr const char* _type_key = \"meta_schedule.TaskScheduler\";\n  TVM_DECLARE_BASE_OBJECT_INFO(TaskSchedulerNode, Object);\n};\n\nclass TaskScheduler;\n\n/*! \\brief The task scheduler with customized methods on the python-side. */\nclass PyTaskSchedulerNode : public TaskSchedulerNode {\n public:\n  /*!\n   * \\brief The function type of `NextTaskId` method.\n   * \\return The next task id.\n   */\n  using FNextTaskId = runtime::TypedPackedFunc<int()>;\n  /*!\n   * \\brief The function type of `JoinRunningTask` method.\n   * \\param task_id The task id to be joined.\n   */\n  using FJoinRunningTask = runtime::TypedPackedFunc<Array<RunnerResult>(int)>;\n  /*! \\brief The function type of `Tune` method. */\n  using FTune = runtime::TypedPackedFunc<void(Array<TuneContext> tasks,                  //\n                                              Array<FloatImm> task_weights,              //\n                                              int max_trials_global,                     //\n                                              int max_trials_per_task,                   //\n                                              int num_trials_per_iter,                   //\n                                              Builder builder,                           //\n                                              Runner runner,                             //\n                                              Array<MeasureCallback> measure_callbacks,  //\n                                              Optional<Database> database,               //\n                                              Optional<CostModel> cost_model)>;\n\n  /*! \\brief The packed function to the `NextTaskId` function. */\n  FNextTaskId f_next_task_id;\n  /*! \\brief The packed function to the `JoinRunningTask` function. */\n  FJoinRunningTask f_join_running_task;\n  /*! \\brief The packed function to the `Tune` function. */\n  FTune f_tune;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TaskSchedulerNode::VisitAttrs(v);\n    // `f_next_task_id` is not visited\n    // `f_join_running_task` is not visited\n    // `f_tune` is not visited\n  }\n\n  int NextTaskId() final;\n  Array<RunnerResult> JoinRunningTask(int task_id) final;\n  void Tune(Array<TuneContext> tasks, Array<FloatImm> task_weights, int max_trials_global,\n            int max_trials_per_task, int num_trials_per_iter, Builder builder, Runner runner,\n            Array<MeasureCallback> measure_callbacks, Optional<Database> database,\n            Optional<CostModel> cost_model) final;\n\n  static constexpr const char* _type_key = \"meta_schedule.PyTaskScheduler\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PyTaskSchedulerNode, TaskSchedulerNode);\n};\n\n/*!\n * \\brief Managed reference to TaskSchedulerNode.\n * \\sa TaskSchedulerNode\n */\nclass TaskScheduler : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Create a task scheduler that fetches tasks in a round-robin fashion.\n   * \\param logger The tuning task's logging function.\n   * \\return The task scheduler created.\n   */\n  TVM_DLL static TaskScheduler RoundRobin(PackedFunc logger);\n  /*!\n   * \\brief Create a task scheduler that fetches tasks in a gradient based fashion.\n   * \\param logger The tuning task's logging function.\n   * \\param alpha The parameter alpha to control gradient computation.\n   * \\param window_size The parameter to control backward window size.\n   * \\param seed The random seed.\n   * \\return The task scheduler created.\n   */\n  TVM_DLL static TaskScheduler GradientBased(PackedFunc logger, double alpha, int window_size,\n                                             support::LinearCongruentialEngine::TRandState seed);\n  /*!\n   * \\brief Create a task scheduler with customized methods on the python-side.\n   * \\param logger The tuning task's logging function.\n   * \\param f_next_task_id The packed function of `NextTaskId`.\n   * \\param f_join_running_task The packed function of `JoinRunningTask`.\n   * \\param f_tune The packed function of `Tune`.\n   * \\return The task scheduler created.\n   */\n  TVM_DLL static TaskScheduler PyTaskScheduler(\n      PackedFunc logger, PyTaskSchedulerNode::FNextTaskId f_next_task_id,\n      PyTaskSchedulerNode::FJoinRunningTask f_join_running_task, PyTaskSchedulerNode::FTune f_tune);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(TaskScheduler, ObjectRef, TaskSchedulerNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_TASK_SCHEDULER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/meta_schedule/tune_context.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_TUNE_CONTEXT_H_\n#define TVM_META_SCHEDULE_TUNE_CONTEXT_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/module.h>\n#include <tvm/meta_schedule/builder.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/meta_schedule/search_strategy.h>\n#include <tvm/meta_schedule/space_generator.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/support/random_engine.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace meta_schedule {\n\nclass TaskSchedulerNode;\nclass MeasureCallback;\nclass TuneContext;\n\n/*! \\brief The auto tuning context. */\nclass TuneContextNode : public runtime::Object {\n public:\n  using TRandState = support::LinearCongruentialEngine::TRandState;\n\n  /*! \\brief The workload to be tuned. */\n  Optional<IRModule> mod;\n  /*! \\brief The target to be tuned for. */\n  Optional<Target> target;\n  /*! \\brief The design space generator. */\n  Optional<SpaceGenerator> space_generator;\n  /*! \\brief The search strategy. */\n  Optional<SearchStrategy> search_strategy;\n  /*! \\brief The name of the tuning task. */\n  Optional<String> task_name;\n  /*! \\brief The number of threads to be used. */\n  int num_threads;\n  /*! \\brief The random state. */\n  TRandState rand_state;\n  /*! \\brief The tuning task's logging function. t*/\n  PackedFunc logger;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"mod\", &mod);\n    v->Visit(\"target\", &target);\n    v->Visit(\"space_generator\", &space_generator);\n    v->Visit(\"search_strategy\", &search_strategy);\n    v->Visit(\"task_name\", &task_name);\n    v->Visit(\"num_threads\", &num_threads);\n    v->Visit(\"rand_state\", &rand_state);\n    // `logger` is not visited\n  }\n  /*!\n   * \\brief Initialize members that needs initialization with tune context.\n   */\n  void Initialize();\n  /*!\n   * \\brief Clone the tune context.\n   * \\return The cloned tune context.\n   */\n  TuneContext Clone() const;\n\n  static constexpr const char* _type_key = \"meta_schedule.TuneContext\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TuneContextNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TuneContextNode.\n * \\sa TuneContextNode\n */\nclass TuneContext : public runtime::ObjectRef {\n public:\n  using TRandState = support::LinearCongruentialEngine::TRandState;\n  /*!\n   * \\brief Constructor.\n   * \\param mod The workload to be tuned.\n   * \\param target The target to be tuned for.\n   * \\param space_generator The design space generator.\n   * \\param search_strategy The search strategy.\n   * \\param task_name The name of the tuning task.\n   * \\param num_threads The number of threads to be used.\n   * \\param rand_state The random state.\n   * \\param logger The tuning task's logging function.\n   */\n  TVM_DLL explicit TuneContext(Optional<IRModule> mod, Optional<Target> target,\n                               Optional<SpaceGenerator> space_generator,\n                               Optional<SearchStrategy> search_strategy, Optional<String> task_name,\n                               int num_threads, TRandState rand_state, PackedFunc logger);\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(TuneContext, ObjectRef, TuneContextNode);\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_TUNE_CONTEXT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/attr_registry_map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/attr_registry_map.h\n * \\brief Attribute map used in registry.\n */\n#ifndef TVM_NODE_ATTR_REGISTRY_MAP_H_\n#define TVM_NODE_ATTR_REGISTRY_MAP_H_\n\n#include <tvm/runtime/container/string.h>\n\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\n/*!\n * \\brief Generic attribute map.\n * \\tparam KeyType the type of the key.\n */\ntemplate <typename KeyType>\nclass AttrRegistryMapContainerMap {\n public:\n  /*!\n   * \\brief Check if the map has key.\n   * \\param key The key to the map\n   * \\return 1 if key is contained in map, 0 otherwise.\n   */\n  int count(const KeyType& key) const {\n    if (key.defined()) {\n      const uint32_t idx = key->AttrRegistryIndex();\n      return idx < data_.size() ? (data_[idx].second != 0) : 0;\n    } else {\n      return 0;\n    }\n  }\n  /*!\n   * \\brief get the corresponding value element at key.\n   * \\param key The key to the map\n   * \\return the const reference to the content value.\n   */\n  const runtime::TVMRetValue& operator[](const KeyType& key) const {\n    ICHECK(key.defined());\n    const uint32_t idx = key->AttrRegistryIndex();\n    ICHECK(idx < data_.size() && data_[idx].second != 0)\n        << \"Attribute \" << attr_name_ << \" has not been registered for \" << key->name;\n    return data_[idx].first;\n  }\n  /*!\n   * \\brief get the corresponding value element at key with default value.\n   * \\param key The key to the map\n   * \\param def_value The default value when the key does not exist.\n   * \\return the const reference to the content value.\n   * \\tparam ValueType The content value type.\n   */\n  template <typename ValueType>\n  ValueType get(const KeyType& key, ValueType def_value) const {\n    ICHECK(key.defined());\n    const uint32_t idx = key->AttrRegistryIndex();\n    if (idx < data_.size() && data_[idx].second != 0) {\n      return data_[idx].first;\n    } else {\n      return def_value;\n    }\n  }\n\n private:\n  /*! \\brief The name of the attr field */\n  String attr_name_;\n  /*! \\brief The internal data. */\n  std::vector<std::pair<runtime::TVMRetValue, int>> data_;\n  /*! \\brief The constructor */\n  AttrRegistryMapContainerMap() = default;\n  template <typename, typename>\n  friend class AttrRegistry;\n  friend class OpRegEntry;\n};\n\n/*!\n * \\brief Map<Key, ValueType> used to store meta-data.\n * \\tparam KeyType The type of the key\n * \\tparam ValueType The type of the value stored in map.\n */\ntemplate <typename KeyType, typename ValueType>\nclass AttrRegistryMap {\n public:\n  /*!\n   * \\brief constructor\n   * \\param map The internal map.\n   */\n  explicit AttrRegistryMap(const AttrRegistryMapContainerMap<KeyType>& map) : map_(map) {}\n  /*!\n   * \\brief Check if the map has op as key.\n   * \\param key The key to the map\n   * \\return 1 if op is contained in map, 0 otherwise.\n   */\n  int count(const KeyType& key) const { return map_.count(key); }\n  /*!\n   * \\brief get the corresponding value element at key.\n   * \\param key The key to the map\n   * \\return the const reference to the content value.\n   */\n  ValueType operator[](const KeyType& key) const { return map_[key]; }\n  /*!\n   * \\brief get the corresponding value element at key with default value.\n   * \\param key The key to the map\n   * \\param def_value The default value when the key does not exist.\n   * \\return the const reference to the content value.\n   */\n  ValueType get(const KeyType& key, ValueType def_value) const { return map_.get(key, def_value); }\n\n protected:\n  /*! \\brief The internal map field */\n  const AttrRegistryMapContainerMap<KeyType>& map_;\n};\n\n}  // namespace tvm\n#endif  // TVM_NODE_ATTR_REGISTRY_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/functor.h\n * \\brief Defines the Functor data structures.\n */\n#ifndef TVM_NODE_FUNCTOR_H_\n#define TVM_NODE_FUNCTOR_H_\n\n#include <dmlc/logging.h>\n#include <tvm/runtime/object.h>\n\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nusing runtime::ObjectRef;\n\n/*!\n * \\brief A dynamically dispatched functor on the type of the first argument.\n *\n * This is a class that is useful to construct polymorphic dispatching\n * base on the AST/IR node's type.\n *\n * \\code\n *   NodeFunctor<std::string (const ObjectRef& n, std::string prefix)> tostr;\n *   tostr.set_dispatch<Add>([](const ObjectRef& op, std::string prefix) {\n *     return prefix + \"Add\";\n *   });\n *   tostr.set_dispatch<IntImm>([](const ObjectRef& op, std::string prefix) {\n *     return prefix + \"IntImm\"\n *   });\n *\n *   Expr x = make_const(1);\n *   Expr y = x + x;\n *   // dispatch to IntImm, outputs \"MyIntImm\"\n *   LOG(INFO) << tostr(x, \"My\");\n *   // dispatch to IntImm, outputs \"MyAdd\"\n *   LOG(INFO) << tostr(y, \"My\");\n * \\endcode\n *\n * \\tparam FType function signiture\n *  This type if only defined for FType with function signature\n */\ntemplate <typename FType>\nclass NodeFunctor;\n\ntemplate <typename R, typename... Args>\nclass NodeFunctor<R(const ObjectRef& n, Args...)> {\n private:\n  /*! \\brief internal function pointer type */\n  typedef R (*FPointer)(const ObjectRef& n, Args...);\n  /*! \\brief refer to itself. */\n  using TSelf = NodeFunctor<R(const ObjectRef& n, Args...)>;\n  /*! \\brief internal function table */\n  std::vector<FPointer> func_;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*!\n   * \\brief Whether the functor can dispatch the corresponding Node\n   * \\param n The node to be dispatched\n   * \\return Whether dispatching function is registered for n's type.\n   */\n  bool can_dispatch(const ObjectRef& n) const {\n    uint32_t type_index = n->type_index();\n    return type_index < func_.size() && func_[type_index] != nullptr;\n  }\n  /*!\n   * \\brief invoke the functor, dispatch on type of n\n   * \\param n The Node argument\n   * \\param args The additional arguments\n   * \\return The result.\n   */\n  R operator()(const ObjectRef& n, Args... args) const {\n    ICHECK(can_dispatch(n)) << \"NodeFunctor calls un-registered function on type \"\n                            << n->GetTypeKey();\n    return (*func_[n->type_index()])(n, std::forward<Args>(args)...);\n  }\n  /*!\n   * \\brief set the dispatcher for type TNode\n   * \\param f The function to be set.\n   * \\tparam TNode the type of Node to be dispatched.\n   * \\return reference to self.\n   */\n  template <typename TNode>\n  TSelf& set_dispatch(FPointer f) {  // NOLINT(*)\n    uint32_t tindex = TNode::RuntimeTypeIndex();\n    if (func_.size() <= tindex) {\n      func_.resize(tindex + 1, nullptr);\n    }\n    ICHECK(func_[tindex] == nullptr) << \"Dispatch for \" << TNode::_type_key << \" is already set\";\n    func_[tindex] = f;\n    return *this;\n  }\n  /*!\n   * \\brief unset the dispatcher for type TNode\n   *\n   * \\tparam TNode the type of Node to be dispatched.\n   * \\return reference to self.\n   */\n  template <typename TNode>\n  TSelf& clear_dispatch() {  // NOLINT(*)\n    uint32_t tindex = TNode::RuntimeTypeIndex();\n    ICHECK_LT(tindex, func_.size()) << \"clear_dispatch: index out of range\";\n    func_[tindex] = nullptr;\n    return *this;\n  }\n};\n\n#define TVM_REG_FUNC_VAR_DEF(ClsName) static TVM_ATTRIBUTE_UNUSED auto& __make_functor##_##ClsName\n\n/*!\n * \\brief Useful macro to set NodeFunctor dispatch in a global static field.\n *\n * \\code\n *  // Use NodeFunctor to implement ReprPrinter similar to Visitor Pattern.\n *  // vtable allows easy patch of new Node types, without changing\n *  // interface of ReprPrinter.\n *\n *  class ReprPrinter {\n *   public:\n *    std::ostream& stream;\n *    // the dispatch function.\n *    void print(Expr e) {\n *      const static FType& f = *vtable();\n *      f(e, this);\n *    }\n *\n *    using FType = NodeFunctor<void (const ObjectRef&, ReprPrinter* )>;\n *    // function to return global function table\n *    static FType& vtable();\n *  };\n *\n *  // in cpp/cc file\n *  ReprPrinter::FType& ReprPrinter::vtable() { // NOLINT(*)\n *    static FType inst; return inst;\n *  }\n *\n *  TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)\n *  .set_dispatch<Add>([](const ObjectRef& ref, ReprPrinter* p) {\n *    auto* n = static_cast<const Add*>(ref.get());\n *    p->print(n->a);\n *    p->stream << '+'\n *    p->print(n->b);\n *  });\n *\n *\n * \\endcode\n *\n * \\param ClsName The name of the class\n * \\param FField The static function that returns a singleton of NodeFunctor.\n */\n#define TVM_STATIC_IR_FUNCTOR(ClsName, FField) \\\n  TVM_STR_CONCAT(TVM_REG_FUNC_VAR_DEF(ClsName), __COUNTER__) = ClsName::FField()\n}  // namespace tvm\n#endif  // TVM_NODE_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/node.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/node.h\n * \\brief Definitions and helper macros for IR/AST nodes.\n *\n *  The node folder contains base utilities for IR/AST nodes,\n *  invariant of which specific language dialect.\n *\n *  We implement AST/IR nodes as sub-classes of runtime::Object.\n *  The base class Node is just an alias of runtime::Object.\n *\n *  Besides the runtime type checking provided by Object,\n *  node folder contains additional functionalities such as\n *  reflection and serialization, which are important features\n *  for building a compiler infra.\n */\n#ifndef TVM_NODE_NODE_H_\n#define TVM_NODE_NODE_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/node/repr_printer.h>\n#include <tvm/node/structural_equal.h>\n#include <tvm/node/structural_hash.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/memory.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nusing runtime::Downcast;\nusing runtime::GetRef;\nusing runtime::make_object;\nusing runtime::Object;\nusing runtime::ObjectPtr;\nusing runtime::ObjectPtrEqual;\nusing runtime::ObjectPtrHash;\nusing runtime::ObjectRef;\nusing runtime::PackedFunc;\nusing runtime::TVMArgs;\nusing runtime::TVMRetValue;\nusing runtime::TypeIndex;\n\n}  // namespace tvm\n#endif  // TVM_NODE_NODE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/object_path.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/node/object_path.h\n * ObjectPath class that represents a path from a root object to one of its descendants\n * via attribute access, array indexing etc.\n */\n\n#ifndef TVM_NODE_OBJECT_PATH_H_\n#define TVM_NODE_OBJECT_PATH_H_\n\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n\nnamespace tvm {\n\nusing runtime::Object;\nusing runtime::ObjectPtr;\nusing runtime::ObjectRef;\n\nclass ObjectPath;\n\n/*!\n * \\brief Path to an object from some root object.\n *\n * Motivation:\n *\n * Same IR node object can be referenced in several different contexts inside a larger IR object.\n * For example, a variable could be referenced in several statements within a block.\n *\n * This makes it impossible to use an object pointer to uniquely identify a \"location\" within\n * the larger IR object for error reporting purposes. The ObjectPath class addresses this problem\n * by serving as a unique \"locator\".\n */\nclass ObjectPathNode : public Object {\n public:\n  /*! \\brief Get the parent path */\n  Optional<ObjectPath> GetParent() const;\n  /*!\n   * \\brief Get the length of the path.\n   *\n   * For example, the path returned by `ObjectPath::Root()` has length 1.\n   */\n  int32_t Length() const;\n\n  /*!\n   * \\brief Get a path prefix of the given length.\n   *\n   * Provided `length` must not exceed the `Length()` of this path.\n   */\n  ObjectPath GetPrefix(int32_t length) const;\n\n  /*!\n   * \\brief Check if this path is a prefix of another path.\n   *\n   * The prefix is not strict, i.e. a path is considered a prefix of itself.\n   */\n  bool IsPrefixOf(const ObjectPath& other) const;\n\n  /*! \\brief Check if two paths are equal. */\n  bool PathsEqual(const ObjectPath& other) const;\n\n  /*! \\brief Extend this path with access to an object attribute. */\n  ObjectPath Attr(const char* attr_key) const;\n\n  /*! \\brief Extend this path with access to an object attribute. */\n  ObjectPath Attr(Optional<String> attr_key) const;\n\n  /*! \\brief Extend this path with access to an array element. */\n  ObjectPath ArrayIndex(int32_t index) const;\n\n  /*! \\brief Extend this path with access to a missing array element. */\n  ObjectPath MissingArrayElement(int32_t index) const;\n\n  /*! \\brief Extend this path with access to a map value. */\n  ObjectPath MapValue(ObjectRef key) const;\n\n  /*! \\brief Extend this path with access to a missing map entry. */\n  ObjectPath MissingMapEntry() const;\n\n  static constexpr const char* _type_key = \"ObjectPath\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ObjectPathNode, Object);\n\n protected:\n  explicit ObjectPathNode(const ObjectPathNode* parent);\n\n  friend class ObjectPath;\n  friend std::string GetObjectPathRepr(const ObjectPathNode* node);\n\n  const ObjectPathNode* ParentNode() const;\n\n  /*! Compares just the last node of the path, without comparing the whole path. */\n  virtual bool LastNodeEqual(const ObjectPathNode* other) const = 0;\n\n  virtual std::string LastNodeString() const = 0;\n\n private:\n  Optional<ObjectRef> parent_;\n  int32_t length_;\n};\n\nclass ObjectPath : public ObjectRef {\n public:\n  /*! \\brief Create a path that represents the root object itself. */\n  static ObjectPath Root();\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ObjectPath, ObjectRef, ObjectPathNode);\n};\n\n//-------------------------------------------------------------------------\n//-----   Concrete object path nodes   ------------------------------------\n//-------------------------------------------------------------------------\n\n// ----- Root -----\n\nclass RootPathNode final : public ObjectPathNode {\n public:\n  explicit RootPathNode();\n\n  static constexpr const char* _type_key = \"RootPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RootPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass RootPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(RootPath, ObjectPath, RootPathNode);\n};\n\n// ----- Attribute access -----\n\nclass AttributeAccessPathNode final : public ObjectPathNode {\n public:\n  /*! \\brief Name of the attribute being accessed. Must be a static string. */\n  String attr_key;\n\n  explicit AttributeAccessPathNode(const ObjectPathNode* parent, String attr_key);\n\n  static constexpr const char* _type_key = \"AttributeAccessPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttributeAccessPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass AttributeAccessPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(AttributeAccessPath, ObjectPath,\n                                            AttributeAccessPathNode);\n};\n\n// ----- Unknown attribute access -----\n\nclass UnknownAttributeAccessPathNode final : public ObjectPathNode {\n public:\n  explicit UnknownAttributeAccessPathNode(const ObjectPathNode* parent);\n\n  static constexpr const char* _type_key = \"UnknownAttributeAccessPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(UnknownAttributeAccessPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass UnknownAttributeAccessPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(UnknownAttributeAccessPath, ObjectPath,\n                                            UnknownAttributeAccessPathNode);\n};\n\n// ----- Array element access by index -----\n\nclass ArrayIndexPathNode : public ObjectPathNode {\n public:\n  /*! \\brief Index of the array element that is being accessed. */\n  int32_t index;\n\n  explicit ArrayIndexPathNode(const ObjectPathNode* parent, int32_t index);\n\n  static constexpr const char* _type_key = \"ArrayIndexPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ArrayIndexPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass ArrayIndexPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ArrayIndexPath, ObjectPath, ArrayIndexPathNode);\n};\n\n// ----- Missing array element -----\n\nclass MissingArrayElementPathNode : public ObjectPathNode {\n public:\n  /*! \\brief Index of the array element that is missing. */\n  int32_t index;\n\n  explicit MissingArrayElementPathNode(const ObjectPathNode* parent, int32_t index);\n\n  static constexpr const char* _type_key = \"MissingArrayElementPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MissingArrayElementPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass MissingArrayElementPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(MissingArrayElementPath, ObjectPath,\n                                            MissingArrayElementPathNode);\n};\n\n// ----- Map value -----\n\nclass MapValuePathNode : public ObjectPathNode {\n public:\n  /*! \\brief Key of the map entry that is being accessed */\n  ObjectRef key;\n\n  explicit MapValuePathNode(const ObjectPathNode* parent, ObjectRef key);\n\n  static constexpr const char* _type_key = \"MapValuePath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MapValuePathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass MapValuePath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(MapValuePath, ObjectPath, MapValuePathNode);\n};\n\n// ----- Missing map entry -----\n\nclass MissingMapEntryPathNode : public ObjectPathNode {\n public:\n  explicit MissingMapEntryPathNode(const ObjectPathNode* parent);\n\n  static constexpr const char* _type_key = \"MissingMapEntryPath\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MissingMapEntryPathNode, ObjectPathNode);\n\n protected:\n  bool LastNodeEqual(const ObjectPathNode* other) const final;\n  std::string LastNodeString() const final;\n};\n\nclass MissingMapEntryPath : public ObjectPath {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(MissingMapEntryPath, ObjectPath,\n                                            MissingMapEntryPathNode);\n};\n\n}  // namespace tvm\n\n#endif  // TVM_NODE_OBJECT_PATH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/reflection.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/reflection.h\n * \\brief Reflection and serialization of compiler IR/AST nodes.\n */\n#ifndef TVM_NODE_REFLECTION_H_\n#define TVM_NODE_REFLECTION_H_\n\n#include <tvm/node/structural_equal.h>\n#include <tvm/node/structural_hash.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/memory.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <type_traits>\n#include <vector>\n\nnamespace tvm {\n\nusing runtime::Object;\nusing runtime::ObjectPtr;\nusing runtime::ObjectRef;\n\n/*!\n * \\brief Visitor class to get the attributes of an AST/IR node.\n *  The content is going to be called for each field.\n *\n *  Each objects that wants reflection will need to implement\n *  a VisitAttrs function and call visitor->Visit on each of its field.\n */\nclass AttrVisitor {\n public:\n  //! \\cond Doxygen_Suppress\n  TVM_DLL virtual ~AttrVisitor() = default;\n  TVM_DLL virtual void Visit(const char* key, double* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, int64_t* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, uint64_t* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, int* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, bool* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, std::string* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, void** value) = 0;\n  TVM_DLL virtual void Visit(const char* key, DataType* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, runtime::NDArray* value) = 0;\n  TVM_DLL virtual void Visit(const char* key, runtime::ObjectRef* value) = 0;\n  template <typename ENum, typename = typename std::enable_if<std::is_enum<ENum>::value>::type>\n  void Visit(const char* key, ENum* ptr) {\n    static_assert(std::is_same<int, typename std::underlying_type<ENum>::type>::value,\n                  \"declare enum to be enum int to use visitor\");\n    this->Visit(key, reinterpret_cast<int*>(ptr));\n  }\n  //! \\endcond\n};\n\n/*!\n * \\brief Virtual function table to support IR/AST node reflection.\n *\n * Functions are stored in columnar manner.\n * Each column is a vector indexed by Object's type_index.\n */\nclass ReflectionVTable {\n public:\n  /*!\n   * \\brief Visitor function.\n   * \\note We use function pointer, instead of std::function\n   *       to reduce the dispatch overhead as field visit\n   *       does not need as much customization.\n   */\n  typedef void (*FVisitAttrs)(Object* self, AttrVisitor* visitor);\n  /*!\n   * \\brief Equality comparison function.\n   */\n  typedef bool (*FSEqualReduce)(const Object* self, const Object* other, SEqualReducer equal);\n  /*!\n   * \\brief Structural hash reduction function.\n   */\n  typedef void (*FSHashReduce)(const Object* self, SHashReducer hash_reduce);\n  /*!\n   * \\brief creator function.\n   * \\param repr_bytes Repr bytes to create the object.\n   *        If this is not empty then FReprBytes must be defined for the object.\n   * \\return The created function.\n   */\n  typedef ObjectPtr<Object> (*FCreate)(const std::string& repr_bytes);\n  /*!\n   * \\brief Function to get a byte representation that can be used to recover the object.\n   * \\param node The node pointer.\n   * \\return bytes The bytes that can be used to recover the object.\n   */\n  typedef std::string (*FReprBytes)(const Object* self);\n  /*!\n   * \\brief Dispatch the VisitAttrs function.\n   * \\param self The pointer to the object.\n   * \\param visitor The attribute visitor.\n   */\n  inline void VisitAttrs(Object* self, AttrVisitor* visitor) const;\n  /*!\n   * \\brief Get repr bytes if any.\n   * \\param self The pointer to the object.\n   * \\param repr_bytes The output repr bytes, can be null, in which case the function\n   *                   simply queries if the ReprBytes function exists for the type.\n   * \\return Whether repr bytes exists\n   */\n  inline bool GetReprBytes(const Object* self, std::string* repr_bytes) const;\n  /*!\n   * \\brief Dispatch the SEqualReduce function.\n   * \\param self The pointer to the object.\n   * \\param other The pointer to another object to be compared.\n   * \\param equal The equality comparator.\n   * \\return the result.\n   */\n  bool SEqualReduce(const Object* self, const Object* other, SEqualReducer equal) const;\n  /*!\n   * \\brief Dispatch the SHashReduce function.\n   * \\param self The pointer to the object.\n   * \\param hash_reduce The hash reducer.\n   * \\return the result.\n   */\n  void SHashReduce(const Object* self, SHashReducer hash_reduce) const;\n  /*!\n   * \\brief Create an initial object using default constructor\n   *        by type_key and global key.\n   *\n   * \\param type_key The type key of the object.\n   * \\param repr_bytes Bytes representation of the object if any.\n   */\n  TVM_DLL ObjectPtr<Object> CreateInitObject(const std::string& type_key,\n                                             const std::string& repr_bytes = \"\") const;\n  /*!\n   * \\brief Create an object by giving kwargs about its fields.\n   *\n   * \\param type_key The type key.\n   * \\param kwargs the arguments in format key1, value1, ..., key_n, value_n.\n   * \\return The created object.\n   */\n  TVM_DLL ObjectRef CreateObject(const std::string& type_key, const runtime::TVMArgs& kwargs);\n  /*!\n   * \\brief Create an object by giving kwargs about its fields.\n   *\n   * \\param type_key The type key.\n   * \\param kwargs The field arguments.\n   * \\return The created object.\n   */\n  TVM_DLL ObjectRef CreateObject(const std::string& type_key, const Map<String, ObjectRef>& kwargs);\n  /*!\n   * \\brief Get an field object by the attr name.\n   * \\param self The pointer to the object.\n   * \\param attr_name The name of the field.\n   * \\return The corresponding attribute value.\n   * \\note This function will throw an exception if the object does not contain the field.\n   */\n  TVM_DLL runtime::TVMRetValue GetAttr(Object* self, const String& attr_name) const;\n\n  /*!\n   * \\brief List all the fields in the object.\n   * \\return All the fields.\n   */\n  TVM_DLL std::vector<std::string> ListAttrNames(Object* self) const;\n\n  /*! \\return The global singleton. */\n  TVM_DLL static ReflectionVTable* Global();\n\n  class Registry;\n  template <typename T, typename TraitName>\n  inline Registry Register();\n\n private:\n  /*! \\brief Attribute visitor. */\n  std::vector<FVisitAttrs> fvisit_attrs_;\n  /*! \\brief Structural equal function. */\n  std::vector<FSEqualReduce> fsequal_reduce_;\n  /*! \\brief Structural hash function. */\n  std::vector<FSHashReduce> fshash_reduce_;\n  /*! \\brief Creation function. */\n  std::vector<FCreate> fcreate_;\n  /*! \\brief ReprBytes function. */\n  std::vector<FReprBytes> frepr_bytes_;\n};\n\n/*! \\brief Registry of a reflection table. */\nclass ReflectionVTable::Registry {\n public:\n  Registry(ReflectionVTable* parent, uint32_t type_index)\n      : parent_(parent), type_index_(type_index) {}\n  /*!\n   * \\brief Set fcreate function.\n   * \\param f The creator function.\n   * \\return Reference to self.\n   */\n  Registry& set_creator(FCreate f) {  // NOLINT(*)\n    ICHECK_LT(type_index_, parent_->fcreate_.size());\n    parent_->fcreate_[type_index_] = f;\n    return *this;\n  }\n  /*!\n   * \\brief Set bytes repr function.\n   * \\param f The ReprBytes function.\n   * \\return Reference to self.\n   */\n  Registry& set_repr_bytes(FReprBytes f) {  // NOLINT(*)\n    ICHECK_LT(type_index_, parent_->frepr_bytes_.size());\n    parent_->frepr_bytes_[type_index_] = f;\n    return *this;\n  }\n\n private:\n  ReflectionVTable* parent_;\n  uint32_t type_index_;\n};\n\n#define TVM_REFLECTION_REG_VAR_DEF \\\n  static TVM_ATTRIBUTE_UNUSED ::tvm::ReflectionVTable::Registry __make_reflection\n\n/*!\n * \\brief Directly register reflection VTable.\n * \\param TypeName The name of the type.\n * \\param TraitName A trait class that implements functions like VisitAttrs and SEqualReduce.\n *\n * \\code\n *\n *  // Example SEQualReduce traits for runtime StringObj.\n *\n *  struct StringObjTrait {\n *    static constexpr const std::nullptr_t VisitAttrs = nullptr;\n *\n *    static void SHashReduce(const runtime::StringObj* key, SHashReducer hash_reduce) {\n *      hash_reduce->SHashReduceHashedValue(runtime::String::HashBytes(key->data, key->size));\n *    }\n *\n *    static bool SEqualReduce(const runtime::StringObj* lhs,\n *                             const runtime::StringObj* rhs,\n *                             SEqualReducer equal) {\n *      if (lhs == rhs) return true;\n *      if (lhs->size != rhs->size) return false;\n *      if (lhs->data != rhs->data) return true;\n *      return std::memcmp(lhs->data, rhs->data, lhs->size) != 0;\n *    }\n *  };\n *\n *  TVM_REGISTER_REFLECTION_VTABLE(runtime::StringObj, StringObjTrait);\n *\n * \\endcode\n *\n * \\note This macro can be called in different place as TVM_REGISTER_OBJECT_TYPE.\n *       And can be used to register the related reflection functions for runtime objects.\n */\n#define TVM_REGISTER_REFLECTION_VTABLE(TypeName, TraitName) \\\n  TVM_STR_CONCAT(TVM_REFLECTION_REG_VAR_DEF, __COUNTER__) = \\\n      ::tvm::ReflectionVTable::Global()->Register<TypeName, TraitName>()\n\n/*!\n * \\brief Register a node type to object registry and reflection registry.\n * \\param TypeName The name of the type.\n * \\note This macro will call TVM_REGISTER_OBJECT_TYPE for the type as well.\n */\n#define TVM_REGISTER_NODE_TYPE(TypeName)                                             \\\n  TVM_REGISTER_OBJECT_TYPE(TypeName);                                                \\\n  TVM_REGISTER_REFLECTION_VTABLE(TypeName, ::tvm::detail::ReflectionTrait<TypeName>) \\\n      .set_creator([](const std::string&) -> ObjectPtr<Object> {                     \\\n        return ::tvm::runtime::make_object<TypeName>();                              \\\n      })\n\n// Implementation details\nnamespace detail {\n\ntemplate <typename T, bool = T::_type_has_method_visit_attrs>\nstruct ImplVisitAttrs {\n  static constexpr const std::nullptr_t VisitAttrs = nullptr;\n};\n\ntemplate <typename T>\nstruct ImplVisitAttrs<T, true> {\n  static void VisitAttrs(T* self, AttrVisitor* v) { self->VisitAttrs(v); }\n};\n\ntemplate <typename T, bool = T::_type_has_method_sequal_reduce>\nstruct ImplSEqualReduce {\n  static constexpr const std::nullptr_t SEqualReduce = nullptr;\n};\n\ntemplate <typename T>\nstruct ImplSEqualReduce<T, true> {\n  static bool SEqualReduce(const T* self, const T* other, SEqualReducer equal) {\n    return self->SEqualReduce(other, equal);\n  }\n};\n\ntemplate <typename T, bool = T::_type_has_method_shash_reduce>\nstruct ImplSHashReduce {\n  static constexpr const std::nullptr_t SHashReduce = nullptr;\n};\n\ntemplate <typename T>\nstruct ImplSHashReduce<T, true> {\n  static void SHashReduce(const T* self, SHashReducer hash_reduce) {\n    self->SHashReduce(hash_reduce);\n  }\n};\n\ntemplate <typename T>\nstruct ReflectionTrait : public ImplVisitAttrs<T>,\n                         public ImplSEqualReduce<T>,\n                         public ImplSHashReduce<T> {};\n\ntemplate <typename T, typename TraitName,\n          bool = std::is_null_pointer<decltype(TraitName::VisitAttrs)>::value>\nstruct SelectVisitAttrs {\n  static constexpr const std::nullptr_t VisitAttrs = nullptr;\n};\n\ntemplate <typename T, typename TraitName>\nstruct SelectVisitAttrs<T, TraitName, false> {\n  static void VisitAttrs(Object* self, AttrVisitor* v) {\n    TraitName::VisitAttrs(static_cast<T*>(self), v);\n  }\n};\n\ntemplate <typename T, typename TraitName,\n          bool = std::is_null_pointer<decltype(TraitName::SEqualReduce)>::value>\nstruct SelectSEqualReduce {\n  static constexpr const std::nullptr_t SEqualReduce = nullptr;\n};\n\ntemplate <typename T, typename TraitName>\nstruct SelectSEqualReduce<T, TraitName, false> {\n  static bool SEqualReduce(const Object* self, const Object* other, SEqualReducer equal) {\n    return TraitName::SEqualReduce(static_cast<const T*>(self), static_cast<const T*>(other),\n                                   equal);\n  }\n};\n\ntemplate <typename T, typename TraitName,\n          bool = std::is_null_pointer<decltype(TraitName::SHashReduce)>::value>\nstruct SelectSHashReduce {\n  static constexpr const std::nullptr_t SHashReduce = nullptr;\n};\n\ntemplate <typename T, typename TraitName>\nstruct SelectSHashReduce<T, TraitName, false> {\n  static void SHashReduce(const Object* self, SHashReducer hash_reduce) {\n    return TraitName::SHashReduce(static_cast<const T*>(self), hash_reduce);\n  }\n};\n\n}  // namespace detail\n\ntemplate <typename T, typename TraitName>\ninline ReflectionVTable::Registry ReflectionVTable::Register() {\n  uint32_t tindex = T::RuntimeTypeIndex();\n  if (tindex >= fvisit_attrs_.size()) {\n    fvisit_attrs_.resize(tindex + 1, nullptr);\n    fcreate_.resize(tindex + 1, nullptr);\n    frepr_bytes_.resize(tindex + 1, nullptr);\n    fsequal_reduce_.resize(tindex + 1, nullptr);\n    fshash_reduce_.resize(tindex + 1, nullptr);\n  }\n  // functor that implements the redirection.\n  fvisit_attrs_[tindex] = ::tvm::detail::SelectVisitAttrs<T, TraitName>::VisitAttrs;\n\n  fsequal_reduce_[tindex] = ::tvm::detail::SelectSEqualReduce<T, TraitName>::SEqualReduce;\n\n  fshash_reduce_[tindex] = ::tvm::detail::SelectSHashReduce<T, TraitName>::SHashReduce;\n\n  return Registry(this, tindex);\n}\n\ninline void ReflectionVTable::VisitAttrs(Object* self, AttrVisitor* visitor) const {\n  uint32_t tindex = self->type_index();\n  if (tindex >= fvisit_attrs_.size() || fvisit_attrs_[tindex] == nullptr) {\n    return;\n  }\n  fvisit_attrs_[tindex](self, visitor);\n}\n\ninline bool ReflectionVTable::GetReprBytes(const Object* self, std::string* repr_bytes) const {\n  uint32_t tindex = self->type_index();\n  if (tindex < frepr_bytes_.size() && frepr_bytes_[tindex] != nullptr) {\n    if (repr_bytes != nullptr) {\n      *repr_bytes = frepr_bytes_[tindex](self);\n    }\n    return true;\n  } else {\n    return false;\n  }\n}\n\n/*!\n * \\brief Given an object and an address of its attribute, return the key of the attribute.\n * \\return nullptr if no attribute with the given address exists.\n */\nOptional<String> GetAttrKeyByAddress(const Object* object, const void* attr_address);\n\n}  // namespace tvm\n#endif  // TVM_NODE_REFLECTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/repr_printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/repr_printer.h\n * \\brief Printer class to print repr string of each AST/IR nodes.\n */\n#ifndef TVM_NODE_REPR_PRINTER_H_\n#define TVM_NODE_REPR_PRINTER_H_\n\n#include <tvm/node/functor.h>\n\n#include <iostream>\n\nnamespace tvm {\n/*! \\brief A printer class to print the AST/IR nodes. */\nclass ReprPrinter {\n public:\n  /*! \\brief The output stream */\n  std::ostream& stream;\n  /*! \\brief The indentation level. */\n  int indent{0};\n\n  explicit ReprPrinter(std::ostream& stream)  // NOLINT(*)\n      : stream(stream) {}\n\n  /*! \\brief The node to be printed. */\n  TVM_DLL void Print(const ObjectRef& node);\n  /*! \\brief Print indent to the stream */\n  TVM_DLL void PrintIndent();\n  // Allow registration to be printer.\n  using FType = NodeFunctor<void(const ObjectRef&, ReprPrinter*)>;\n  TVM_DLL static FType& vtable();\n};\n\n/*!\n * \\brief Dump the node to stderr, used for debug purposes.\n * \\param node The input node\n */\nTVM_DLL void Dump(const runtime::ObjectRef& node);\n\n/*!\n * \\brief Dump the node to stderr, used for debug purposes.\n * \\param node The input node\n */\nTVM_DLL void Dump(const runtime::Object* node);\n\n}  // namespace tvm\n\nnamespace tvm {\nnamespace runtime {\n// default print function for all objects\n// provide in the runtime namespace as this is where objectref originally comes from.\ninline std::ostream& operator<<(std::ostream& os, const ObjectRef& n) {  // NOLINT(*)\n  ReprPrinter(os).Print(n);\n  return os;\n}\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_NODE_REPR_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/serialization.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * Utility functions for serialization.\n * \\file tvm/node/serialization.h\n */\n#ifndef TVM_NODE_SERIALIZATION_H_\n#define TVM_NODE_SERIALIZATION_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n\nnamespace tvm {\n/*!\n * \\brief save the node as well as all the node it depends on as json.\n *  This can be used to serialize any TVM object\n *\n * \\return the string representation of the node.\n */\nTVM_DLL std::string SaveJSON(const runtime::ObjectRef& node);\n\n/*!\n * \\brief Internal implementation of LoadJSON\n * Load tvm Node object from json and return a shared_ptr of Node.\n * \\param json_str The json string to load from.\n *\n * \\return The shared_ptr of the Node.\n */\nTVM_DLL runtime::ObjectRef LoadJSON(std::string json_str);\n\n}  // namespace tvm\n#endif  // TVM_NODE_SERIALIZATION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/structural_equal.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/structural_equal.h\n * \\brief Structural equality comparison.\n */\n#ifndef TVM_NODE_STRUCTURAL_EQUAL_H_\n#define TVM_NODE_STRUCTURAL_EQUAL_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/node/object_path.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/data_type.h>\n\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief Equality definition of base value class.\n */\nclass BaseValueEqual {\n public:\n  bool operator()(const double& lhs, const double& rhs) const {\n    // fuzzy float pt comparison\n    constexpr double atol = 1e-9;\n    if (lhs == rhs) return true;\n    double diff = lhs - rhs;\n    return diff > -atol && diff < atol;\n  }\n\n  bool operator()(const int64_t& lhs, const int64_t& rhs) const { return lhs == rhs; }\n  bool operator()(const uint64_t& lhs, const uint64_t& rhs) const { return lhs == rhs; }\n  bool operator()(const int& lhs, const int& rhs) const { return lhs == rhs; }\n  bool operator()(const bool& lhs, const bool& rhs) const { return lhs == rhs; }\n  bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs == rhs; }\n  bool operator()(const DataType& lhs, const DataType& rhs) const { return lhs == rhs; }\n  template <typename ENum, typename = typename std::enable_if<std::is_enum<ENum>::value>::type>\n  bool operator()(const ENum& lhs, const ENum& rhs) const {\n    return lhs == rhs;\n  }\n};\n\n/*!\n * \\brief Pair of `ObjectPath`s, one for each object being tested for structural equality.\n */\nclass ObjectPathPairNode : public Object {\n public:\n  ObjectPath lhs_path;\n  ObjectPath rhs_path;\n\n  ObjectPathPairNode(ObjectPath lhs_path, ObjectPath rhs_path);\n\n  static constexpr const char* _type_key = \"ObjectPathPair\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ObjectPathPairNode, Object);\n};\n\nclass ObjectPathPair : public ObjectRef {\n public:\n  ObjectPathPair(ObjectPath lhs_path, ObjectPath rhs_path);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ObjectPathPair, ObjectRef, ObjectPathPairNode);\n};\n\n/*!\n * \\brief Content-aware structural equality comparator for objects.\n *\n *  The structural equality is recursively defined in the DAG of IR nodes via SEqual.\n *  There are two kinds of nodes:\n *\n *  - Graph node: a graph node in lhs can only be mapped as equal to\n *    one and only one graph node in rhs.\n *  - Normal node: equality is recursively defined without the restriction\n *    of graph nodes.\n *\n *  Vars(tir::Var, TypeVar) and non-constant relay expression nodes are graph nodes.\n *  For example, it means that `%1 = %x + %y; %1 + %1` is not structurally equal\n *  to `%1 = %x + %y; %2 = %x + %y; %1 + %2` in relay.\n *\n *  A var-type node(e.g. tir::Var, TypeVar) can be mapped as equal to another var\n *  with the same type if one of the following condition holds:\n *\n *  - They appear in a same definition point(e.g. function argument).\n *  - They points to the same VarNode via the same_as relation.\n *  - They appear in a same usage point, and map_free_vars is set to be True.\n */\nclass StructuralEqual : public BaseValueEqual {\n public:\n  // inheritate operator()\n  using BaseValueEqual::operator();\n  /*!\n   * \\brief Compare objects via strutural equal.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return The comparison result.\n   */\n  TVM_DLL bool operator()(const ObjectRef& lhs, const ObjectRef& rhs) const;\n};\n\n/*!\n * \\brief A Reducer class to reduce the structural equality result of two objects.\n *\n * The reducer will call the SEqualReduce function of each objects recursively.\n * Importantly, the reducer may not directly use recursive calls to resolve the\n * equality checking. Instead, it can store the necessary equality conditions\n * and check later via an internally managed stack.\n */\nclass SEqualReducer {\n private:\n  struct PathTracingData;\n\n public:\n  /*! \\brief Internal handler that defines custom behaviors.. */\n  class Handler {\n   public:\n    /*!\n     * \\brief Reduce condition to equality of lhs and rhs.\n     *\n     * \\param lhs The left operand.\n     * \\param rhs The right operand.\n     * \\param map_free_vars Whether do we allow remap variables if possible.\n     * \\param current_paths Optional paths to `lhs` and `rhs` objects, for error traceability.\n     *\n     * \\return false if there is an immediate failure, true otherwise.\n     * \\note This function may save the equality condition of (lhs == rhs) in an internal\n     *       stack and try to resolve later.\n     */\n    virtual bool SEqualReduce(const ObjectRef& lhs, const ObjectRef& rhs, bool map_free_vars,\n                              const Optional<ObjectPathPair>& current_paths) = 0;\n\n    /*!\n     * \\brief Mark the comparison as failed, but don't fail immediately.\n     *\n     * This is useful for producing better error messages when comparing containers.\n     * For example, if two array sizes mismatch, it's better to mark the comparison as failed\n     * but compare array elements anyway, so that we could find the true first mismatch.\n     */\n    virtual void DeferFail(const ObjectPathPair& mismatch_paths) = 0;\n\n    /*!\n     * \\brief Lookup the graph node equal map for vars that are already mapped.\n     *\n     *  This is an auxiliary method to check the Map<Var, Value> equality.\n     * \\param lhs an lhs value.\n     *\n     * \\return The corresponding rhs value if any, nullptr if not available.\n     */\n    virtual ObjectRef MapLhsToRhs(const ObjectRef& lhs) = 0;\n    /*!\n     * \\brief Mark current comparison as graph node equal comparison.\n     */\n    virtual void MarkGraphNode() = 0;\n\n   protected:\n    using PathTracingData = SEqualReducer::PathTracingData;\n  };\n\n  /*! \\brief default constructor */\n  SEqualReducer() = default;\n  /*!\n   * \\brief Constructor with a specific handler.\n   * \\param handler The equal handler for objects.\n   * \\param tracing_data Optional pointer to the path tracing data.\n   * \\param map_free_vars Whether or not to map free variables.\n   */\n  explicit SEqualReducer(Handler* handler, const PathTracingData* tracing_data, bool map_free_vars)\n      : handler_(handler), tracing_data_(tracing_data), map_free_vars_(map_free_vars) {}\n\n  /*!\n   * \\brief Reduce condition to comparison of two attribute values.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return the immediate check result.\n   */\n  bool operator()(const double& lhs, const double& rhs) const;\n  bool operator()(const int64_t& lhs, const int64_t& rhs) const;\n  bool operator()(const uint64_t& lhs, const uint64_t& rhs) const;\n  bool operator()(const int& lhs, const int& rhs) const;\n  bool operator()(const bool& lhs, const bool& rhs) const;\n  bool operator()(const std::string& lhs, const std::string& rhs) const;\n  bool operator()(const DataType& lhs, const DataType& rhs) const;\n\n  template <typename ENum, typename = typename std::enable_if<std::is_enum<ENum>::value>::type>\n  bool operator()(const ENum& lhs, const ENum& rhs) const {\n    using Underlying = typename std::underlying_type<ENum>::type;\n    static_assert(std::is_same<Underlying, int>::value,\n                  \"Enum must have `int` as the underlying type\");\n    return EnumAttrsEqual(static_cast<int>(lhs), static_cast<int>(rhs), &lhs, &rhs);\n  }\n\n  /*!\n   * \\brief Reduce condition to comparison of two objects.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return the immediate check result.\n   */\n  bool operator()(const ObjectRef& lhs, const ObjectRef& rhs) const;\n\n  /*!\n   * \\brief Reduce condition to comparison of two objects.\n   *\n   * Like `operator()`, but with an additional `paths` parameter that specifies explicit object\n   * paths for `lhs` and `rhs`. This is useful for implementing SEqualReduce() methods for container\n   * objects like Array and Map, or other custom objects that store nested objects that are not\n   * simply attributes.\n   *\n   * Can only be called when `IsPathTracingEnabled()` is `true`.\n   *\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\param paths Object paths for `lhs` and `rhs`.\n   * \\return the immediate check result.\n   */\n  bool operator()(const ObjectRef& lhs, const ObjectRef& rhs, const ObjectPathPair& paths) const {\n    ICHECK(IsPathTracingEnabled()) << \"Path tracing must be enabled when calling this function\";\n    return ObjectAttrsEqual(lhs, rhs, map_free_vars_, &paths);\n  }\n\n  /*!\n   * \\brief Reduce condition to comparison of two definitions,\n   *        where free vars can be mapped.\n   *\n   *  Call this function to compare definition points such as function params\n   *  and var in a let-binding.\n   *\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return the immediate check result.\n   */\n  bool DefEqual(const ObjectRef& lhs, const ObjectRef& rhs);\n\n  /*!\n   * \\brief Reduce condition to comparison of two arrays.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return the immediate check result.\n   */\n  template <typename T>\n  bool operator()(const Array<T>& lhs, const Array<T>& rhs) const {\n    if (tracing_data_ == nullptr) {\n      // quick specialization for Array to reduce amount of recursion\n      // depth as array comparison is pretty common.\n      if (lhs.size() != rhs.size()) return false;\n      for (size_t i = 0; i < lhs.size(); ++i) {\n        if (!(operator()(lhs[i], rhs[i]))) return false;\n      }\n      return true;\n    }\n\n    // If tracing is enabled, fall back to the regular path\n    const ObjectRef& lhs_obj = lhs;\n    const ObjectRef& rhs_obj = rhs;\n    return (*this)(lhs_obj, rhs_obj);\n  }\n  /*!\n   * \\brief Implementation for equality rule of var type objects(e.g. TypeVar, tir::Var).\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\return the result.\n   */\n  bool FreeVarEqualImpl(const runtime::Object* lhs, const runtime::Object* rhs) const {\n    // var need to be remapped, so it belongs to graph node.\n    handler_->MarkGraphNode();\n    // We only map free vars if they corresponds to the same address\n    // or map free_var option is set to be true.\n    return lhs == rhs || map_free_vars_;\n  }\n\n  /*! \\return Get the internal handler. */\n  Handler* operator->() const { return handler_; }\n\n  /*! \\brief Check if this reducer is tracing paths to the first mismatch. */\n  bool IsPathTracingEnabled() const { return tracing_data_ != nullptr; }\n\n  /*!\n   * \\brief Get the paths of the currently compared objects.\n   *\n   * Can only be called when `IsPathTracingEnabled()` is true.\n   */\n  const ObjectPathPair& GetCurrentObjectPaths() const;\n\n  /*!\n   * \\brief Specify the object paths of a detected mismatch.\n   *\n   * Can only be called when `IsPathTracingEnabled()` is true.\n   */\n  void RecordMismatchPaths(const ObjectPathPair& paths) const;\n\n private:\n  bool EnumAttrsEqual(int lhs, int rhs, const void* lhs_address, const void* rhs_address) const;\n\n  bool ObjectAttrsEqual(const ObjectRef& lhs, const ObjectRef& rhs, bool map_free_vars,\n                        const ObjectPathPair* paths) const;\n\n  static void GetPathsFromAttrAddressesAndStoreMismatch(const void* lhs_address,\n                                                        const void* rhs_address,\n                                                        const PathTracingData* tracing_data);\n\n  template <typename T>\n  static bool CompareAttributeValues(const T& lhs, const T& rhs,\n                                     const PathTracingData* tracing_data);\n\n  /*! \\brief Internal class pointer. */\n  Handler* handler_ = nullptr;\n  /*! \\brief Pointer to the current path tracing context, or nullptr if path tracing is disabled. */\n  const PathTracingData* tracing_data_ = nullptr;\n  /*! \\brief Whether or not to map free vars. */\n  bool map_free_vars_ = false;\n};\n\n/*! \\brief The default handler for equality testing.\n *\n * Users can derive from this class and override the DispatchSEqualReduce method,\n * to customize equality testing.\n */\nclass SEqualHandlerDefault : public SEqualReducer::Handler {\n public:\n  SEqualHandlerDefault(bool assert_mode, Optional<ObjectPathPair>* first_mismatch);\n  virtual ~SEqualHandlerDefault();\n\n  bool SEqualReduce(const ObjectRef& lhs, const ObjectRef& rhs, bool map_free_vars,\n                    const Optional<ObjectPathPair>& current_paths) override;\n  void DeferFail(const ObjectPathPair& mismatch_paths) override;\n  ObjectRef MapLhsToRhs(const ObjectRef& lhs) override;\n  void MarkGraphNode() override;\n\n  /*!\n   * \\brief The entry point for equality testing\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\param map_free_vars Whether or not to remap variables if possible.\n   * \\return The equality result.\n   */\n  virtual bool Equal(const ObjectRef& lhs, const ObjectRef& rhs, bool map_free_vars);\n\n protected:\n  /*!\n   * \\brief The dispatcher for equality testing of intermediate objects\n   * \\param lhs The left operand.\n   * \\param rhs The right operand.\n   * \\param map_free_vars Whether or not to remap variables if possible.\n   * \\param current_paths Optional paths to `lhs` and `rhs` objects, for error traceability.\n   * \\return The equality result.\n   */\n  virtual bool DispatchSEqualReduce(const ObjectRef& lhs, const ObjectRef& rhs, bool map_free_vars,\n                                    const Optional<ObjectPathPair>& current_paths);\n\n private:\n  class Impl;\n  Impl* impl;\n};\n\n}  // namespace tvm\n#endif  // TVM_NODE_STRUCTURAL_EQUAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/node/structural_hash.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/node/structural_equal.h\n * \\brief Structural hash class.\n */\n#ifndef TVM_NODE_STRUCTURAL_HASH_H_\n#define TVM_NODE_STRUCTURAL_HASH_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/ndarray.h>\n\n#include <functional>\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief Hash definition of base value classes.\n */\nclass BaseValueHash {\n public:\n  size_t operator()(const double& key) const { return std::hash<double>()(key); }\n\n  size_t operator()(const int64_t& key) const { return std::hash<int64_t>()(key); }\n\n  size_t operator()(const uint64_t& key) const { return std::hash<uint64_t>()(key); }\n\n  size_t operator()(const int& key) const { return std::hash<int>()(key); }\n\n  size_t operator()(const bool& key) const { return std::hash<bool>()(key); }\n\n  size_t operator()(const std::string& key) const { return std::hash<std::string>()(key); }\n\n  size_t operator()(const runtime::DataType& key) const {\n    return std::hash<int32_t>()(static_cast<int32_t>(key.code()) |\n                                (static_cast<int32_t>(key.bits()) << 8) |\n                                (static_cast<int32_t>(key.lanes()) << 16));\n  }\n\n  template <typename ENum, typename = typename std::enable_if<std::is_enum<ENum>::value>::type>\n  bool operator()(const ENum& key) const {\n    return std::hash<size_t>()(static_cast<size_t>(key));\n  }\n};\n\n/*!\n * \\brief Content-aware structural hasing.\n *\n *  The structural hash value is recursively defined in the DAG of IRNodes.\n *  There are two kinds of nodes:\n *\n *  - Normal node: the hash value is defined by its content and type only.\n *  - Graph node: each graph node will be assigned a unique index ordered by the\n *    first occurence during the visit. The hash value of a graph node is\n *    combined from the hash values of its contents and the index.\n */\nclass StructuralHash : public BaseValueHash {\n public:\n  // inheritate operator()\n  using BaseValueHash::operator();\n  /*!\n   * \\brief Compute structural hashing value for an object.\n   * \\param key The left operand.\n   * \\return The hash value.\n   */\n  TVM_DLL size_t operator()(const ObjectRef& key) const;\n};\n\n/*!\n * \\brief A Reducer class to reduce the structural hash value.\n *\n *  The reducer will call the SEqualHash function of each objects recursively.\n *\n *  A SEqualHash function will make a sequence of calls to the reducer to\n *  indicate a sequence of child hash values that the reducer need to combine\n *  inorder to obtain the hash value of the hash value of the parent object.\n *\n *  Importantly, the reducer may not directly use recursive calls\n *  to compute the hash values of child objects directly.\n *\n *  Instead, it can store the necessary hash computing task into a stack\n *  and reduce the result later.\n */\nclass SHashReducer {\n public:\n  /*! \\brief Internal handler that defines custom behaviors. */\n  class Handler {\n   public:\n    /*!\n     * \\brief Append hashed_value to the current sequence of hashes.\n     *\n     * \\param hashed_value The hashed value\n     */\n    virtual void SHashReduceHashedValue(size_t hashed_value) = 0;\n    /*!\n     * \\brief Append hash value of key to the current sequence of hashes.\n     *\n     * \\param key The object to compute hash from.\n     * \\param map_free_vars Whether to map free variables by their occurence number.\n     */\n    virtual void SHashReduce(const ObjectRef& key, bool map_free_vars) = 0;\n    /*!\n     * \\brief Apppend a hash value of free variable to the current sequence of hashes.\n     *\n     * \\param var The var of interest.\n     * \\param map_free_vars Whether to map free variables by their occurence number.\n     *\n     * \\note If map_free_vars is set to be true,\n     *       internally the handler can maintain a counter to encode free variables\n     *       by their order of occurence. This helps to resolve variable\n     *       mapping of function parameters and let binding variables.\n     *\n     *       If map_free_vars is set to be false, the address of the variable will be used.\n     */\n    virtual void SHashReduceFreeVar(const runtime::Object* var, bool map_free_vars) = 0;\n    /*!\n     * \\brief Lookup a hash value for key\n     *\n     * \\param key The hash key.\n     * \\param hashed_value the result hash value\n     *\n     * \\return Whether there is already a pre-computed hash value.\n     */\n    virtual bool LookupHashedValue(const ObjectRef& key, size_t* hashed_value) = 0;\n    /*!\n     * \\brief Mark current comparison as graph node in hashing.\n     *        Graph node hash will depends on the graph structure.\n     */\n    virtual void MarkGraphNode() = 0;\n  };\n\n  /*! \\brief default constructor */\n  SHashReducer() = default;\n  /*!\n   * \\brief Constructor with a specific handler.\n   * \\param handler The equal handler for objects.\n   * \\param map_free_vars Whether to map free variables.\n   */\n  explicit SHashReducer(Handler* handler, bool map_free_vars)\n      : handler_(handler), map_free_vars_(map_free_vars) {}\n  /*!\n   * \\brief Push hash of key to the current sequence of hash values.\n   * \\param key The key to be hashed.\n   */\n  template <typename T,\n            typename = typename std::enable_if<!std::is_base_of<ObjectRef, T>::value>::type>\n  void operator()(const T& key) const {\n    // handle normal values.\n    handler_->SHashReduceHashedValue(BaseValueHash()(key));\n  }\n  /*!\n   * \\brief Push hash of key to the current sequence of hash values.\n   * \\param key The key to be hashed.\n   */\n  void operator()(const ObjectRef& key) const { return handler_->SHashReduce(key, map_free_vars_); }\n  /*!\n   * \\brief Push hash of key to the current sequence of hash values.\n   * \\param key The key to be hashed.\n   * \\note This function indicate key could contain var defintions.\n   */\n  void DefHash(const ObjectRef& key) const { return handler_->SHashReduce(key, true); }\n  /*!\n   * \\brief Implementation for hash for a free var.\n   * \\param var The variable.\n   * \\return the result.\n   */\n  void FreeVarHashImpl(const runtime::Object* var) const {\n    handler_->SHashReduceFreeVar(var, map_free_vars_);\n  }\n\n  /*! \\return Get the internal handler. */\n  Handler* operator->() const { return handler_; }\n\n private:\n  /*! \\brief Internal class pointer. */\n  Handler* handler_;\n  /*!\n   * \\brief Whether or not to map free variables by their occurence\n   *        If the flag is false, then free variables will be mapped\n   *        by their in-memory address.\n   */\n  bool map_free_vars_;\n};\n\n/*! \\brief The default handler for hash key computation\n *\n * Users can derive from this class and override the DispatchSHash method,\n * to customize hashing.\n */\nclass SHashHandlerDefault : public SHashReducer::Handler {\n public:\n  SHashHandlerDefault();\n  virtual ~SHashHandlerDefault();\n\n  void SHashReduceHashedValue(size_t hashed_value) override;\n  void SHashReduce(const ObjectRef& key, bool map_free_vars) override;\n  void SHashReduceFreeVar(const runtime::Object* var, bool map_free_vars) override;\n  bool LookupHashedValue(const ObjectRef& key, size_t* hashed_value) override;\n  void MarkGraphNode() override;\n\n  /*!\n   * \\brief The entry point for hashing\n   * \\param object The object to be hashed.\n   * \\param map_free_vars Whether or not to remap variables if possible.\n   * \\return The hash result.\n   */\n  virtual size_t Hash(const ObjectRef& object, bool map_free_vars);\n\n protected:\n  /*!\n   * \\brief The dispatcher for hashing of intermediate objects\n   * \\param object An intermediate object to be hashed.\n   * \\param map_free_vars Whether or not to remap variables if possible.\n   * \\return The hash result.\n   */\n  virtual void DispatchSHash(const ObjectRef& object, bool map_free_vars);\n\n private:\n  class Impl;\n  Impl* impl;\n};\n\nclass SEqualReducer;\nstruct NDArrayContainerTrait {\n  static constexpr const std::nullptr_t VisitAttrs = nullptr;\n  static void SHashReduce(const runtime::NDArray::Container* key, SHashReducer hash_reduce);\n  static bool SEqualReduce(const runtime::NDArray::Container* lhs,\n                           const runtime::NDArray::Container* rhs, SEqualReducer equal);\n};\n\n}  // namespace tvm\n#endif  // TVM_NODE_STRUCTURAL_HASH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/parser/parser.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_PARSER_PARSER_H_\n#define TVM_PARSER_PARSER_H_\n/*!\n * \\file include/tvm/parser/parser.h\n * \\brief A parser for TVM IR.\n */\n#include <tvm/ir/module.h>\n#include <tvm/ir/transform.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n\n#include <fstream>\n#include <string>\n\nnamespace tvm {\nnamespace parser {\n\nusing MetaTable = Map<String, Array<ObjectRef>>;\n\nIRModule ParseModule(const std::string& file_name, const std::string& file_content,\n                     const Optional<IRModule>& init_module = Optional<IRModule>(),\n                     const MetaTable& init_meta_table = MetaTable());\n\n/*!\n * \\brief This pass pretty-prints mod then parses it back so as to establish spans and sources\n * for all Relay sub-expressions. This improves error and debugging diagnostics downstream for\n * modules constructed programaticaly rather than textually.\n */\ntransform::Pass AnnotateSpans();\n\n}  // namespace parser\n}  // namespace tvm\n\n#endif  // TVM_PARSER_PARSER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/parser/source_map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file source_map.h\n * \\brief A map from source names to source code.\n */\n#ifndef TVM_PARSER_SOURCE_MAP_H_\n#define TVM_PARSER_SOURCE_MAP_H_\n\n#include <tvm/ir/span.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n\n#include <fstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace parser {\n\n/*! \\brief A program source in any language.\n *\n * Could represent the source from an ML framework or a source\n * representing a tvm::IRModule.\n */\nclass Source;\n\nclass SourceNode : public Object {\n public:\n  /*! \\brief The source name. */\n  SourceName source_name;\n\n  /*! \\brief The raw source. */\n  String source;\n\n  /*! \\brief A mapping of line breaks into the raw source. */\n  std::vector<std::pair<int, int>> line_map;\n\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"source_name\", &source_name);\n    v->Visit(\"source\", &source);\n  }\n\n  static constexpr const char* _type_key = \"Source\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SourceNode, Object);\n};\n\nclass Source : public ObjectRef {\n public:\n  TVM_DLL Source(SourceName src_name, std::string source);\n  TVM_DLL tvm::String GetLine(int line);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Source, ObjectRef, SourceNode);\n};\n\n/*!\n * \\brief A mapping from a unique source name to source fragment.\n */\nclass SourceMap;\n/*!\n * \\brief Stores locations in frontend source that generated a node.\n */\nclass SourceMapNode : public Object {\n public:\n  /*! \\brief The source mapping. */\n  Map<SourceName, Source> source_map;\n\n  // override attr visitor\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"source_map\", &source_map); }\n\n  bool SEqualReduce(const SourceMapNode* other, SEqualReducer equal) const {\n    return equal(source_map, other->source_map);\n  }\n\n  static constexpr const char* _type_key = \"SourceMap\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SourceMapNode, Object);\n};\n\nclass SourceMap : public ObjectRef {\n public:\n  TVM_DLL SourceMap(Map<SourceName, Source> source_map);\n\n  TVM_DLL SourceMap(std::initializer_list<std::pair<SourceName, Source>> source_map)\n      : SourceMap(Map<SourceName, Source>(source_map)) {}\n\n  TVM_DLL SourceMap() : SourceMap(Map<SourceName, Source>()) {}\n\n  void Add(const Source& source);\n\n  SourceMapNode* operator->() {\n    ICHECK(get() != nullptr);\n    return static_cast<SourceMapNode*>(get_mutable());\n  }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(SourceMap, ObjectRef, SourceMapNode);\n};\n\n}  // namespace parser\n}  // namespace tvm\n\n#endif  // TVM_PARSER_SOURCE_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/adt.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/adt.h\n * \\brief Algebraic data types for Relay\n */\n#ifndef TVM_RELAY_ADT_H_\n#define TVM_RELAY_ADT_H_\n\n#include <tvm/ir/adt.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n\n#include <functional>\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\n\nusing Constructor = tvm::Constructor;\nusing ConstructorNode = tvm::ConstructorNode;\n\nusing TypeData = tvm::TypeData;\nusing TypeDataNode = tvm::TypeDataNode;\n\n/*! \\brief Base type for declaring relay pattern. */\nclass PatternNode : public RelayNode {\n public:\n  static constexpr const char* _type_key = \"relay.Pattern\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_BASE_OBJECT_INFO(PatternNode, Object);\n};\n\n/*!\n * \\brief Pattern is the base type for an ADT match pattern in Relay.\n *\n * Given an ADT value, a pattern might accept it and bind the pattern variable to some value\n * (typically a subnode of the input or the input). Otherwise, the pattern rejects the value.\n *\n * ADT pattern matching thus takes a list of values and binds to the first that accepts the value.\n */\nclass Pattern : public ObjectRef {\n public:\n  Pattern() {}\n  explicit Pattern(ObjectPtr<tvm::Object> p) : ObjectRef(p) {}\n\n  using ContainerType = PatternNode;\n};\n\n/*! \\brief A wildcard pattern: Accepts all input and binds nothing. */\nclass PatternWildcard;\n/*! \\brief PatternWildcard container node */\nclass PatternWildcardNode : public PatternNode {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"span\", &span); }\n\n  bool SEqualReduce(const PatternNode* other, SEqualReducer equal) const { return true; }\n\n  void SHashReduce(SHashReducer hash_reduce) const {}\n\n  static constexpr const char* _type_key = \"relay.PatternWildcard\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PatternWildcardNode, PatternNode);\n};\n\nclass PatternWildcard : public Pattern {\n public:\n  /* \\brief Overload the default constructors. */\n  TVM_DLL PatternWildcard();\n  explicit PatternWildcard(ObjectPtr<Object> n) : Pattern(n) {}\n  /* \\brief Copy constructor. */\n  PatternWildcard(const PatternWildcard& pat) : PatternWildcard(pat.data_) {}\n  /* \\brief Move constructor. */\n  PatternWildcard(PatternWildcard&& pat) : PatternWildcard(std::move(pat.data_)) {}\n  /* \\brief Copy assignment. */\n  PatternWildcard& operator=(const PatternWildcard& other) {\n    (*this).data_ = other.data_;\n    return *this;\n  }\n  /* \\brief Move assignment. */\n  PatternWildcard& operator=(PatternWildcard&& other) {\n    (*this).data_ = std::move(other.data_);\n    return *this;\n  }\n\n  const PatternWildcardNode* operator->() const {\n    return static_cast<const PatternWildcardNode*>(get());\n  }\n\n  using ContainerType = PatternWildcardNode;\n};\n\n/*! \\brief A var pattern. Accept all input and bind to a var. */\nclass PatternVar;\n/*! \\brief PatternVar container node */\nclass PatternVarNode : public PatternNode {\n public:\n  /*! \\brief Variable that stores the matched value. */\n  tvm::relay::Var var;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"var\", &var);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const PatternVarNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(var, other->var);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce.DefHash(var); }\n\n  static constexpr const char* _type_key = \"relay.PatternVar\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PatternVarNode, PatternNode);\n};\n\nclass PatternVar : public Pattern {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param var The var to construct a pattern\n   */\n  TVM_DLL explicit PatternVar(tvm::relay::Var var);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PatternVar, Pattern, PatternVarNode);\n};\n\n/*! \\brief A constructor pattern. Matches a value with the given constructor, binds recursively. */\nclass PatternConstructor;\n/*! \\brief PatternVar container node */\nclass PatternConstructorNode : public PatternNode {\n public:\n  /*! Constructor matched by the pattern. */\n  Constructor constructor;\n  /*! Sub-patterns to match against each input to the constructor. */\n  tvm::Array<Pattern> patterns;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"constructor\", &constructor);\n    v->Visit(\"patterns\", &patterns);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const PatternConstructorNode* other, SEqualReducer equal) const {\n    return equal(constructor, other->constructor) && equal(patterns, other->patterns);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(constructor);\n    hash_reduce(patterns);\n  }\n\n  static constexpr const char* _type_key = \"relay.PatternConstructor\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PatternConstructorNode, PatternNode);\n};\n\nclass PatternConstructor : public Pattern {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param constructor The constructor of a pattern\n   * \\param patterns The sub-patterns for matching\n   */\n  TVM_DLL PatternConstructor(Constructor constructor, tvm::Array<Pattern> patterns);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PatternConstructor, Pattern, PatternConstructorNode);\n};\n\n/*! \\brief A tuple pattern. Matches a tuple, binds recursively. */\nclass PatternTuple;\n/*! \\brief PatternVar container node */\nclass PatternTupleNode : public PatternNode {\n public:\n  /* TODO(@jroesch): rename to field_pats */\n  /*! Sub-patterns to match against each value of the tuple. */\n  tvm::Array<Pattern> patterns;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"patterns\", &patterns);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const PatternTupleNode* other, SEqualReducer equal) const {\n    return equal(patterns, other->patterns);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(patterns); }\n\n  static constexpr const char* _type_key = \"relay.PatternTuple\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PatternTupleNode, PatternNode);\n};\n\nclass PatternTuple : public Pattern {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param patterns The sub-patterns to match against each value of the tuple\n   */\n  TVM_DLL explicit PatternTuple(tvm::Array<Pattern> patterns);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PatternTuple, Pattern, PatternTupleNode);\n};\n\n/*! \\brief A clause in a match expression. */\nclass Clause;\n/*! \\brief Clause container node. */\nclass ClauseNode : public Object {\n public:\n  /*! \\brief The pattern the clause matches. */\n  Pattern lhs;\n  /*! \\brief The resulting value. */\n  Expr rhs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"lhs\", &lhs);\n    v->Visit(\"rhs\", &rhs);\n  }\n\n  bool SEqualReduce(const ClauseNode* other, SEqualReducer equal) const {\n    return equal(lhs, other->lhs) && equal(rhs, other->rhs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(lhs);\n    hash_reduce(rhs);\n  }\n\n  static constexpr const char* _type_key = \"relay.Clause\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(ClauseNode, Object);\n};\n\nclass Clause : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param lhs The pattern matched by the clause.\n   * \\param rhs The resulting value\n   */\n  TVM_DLL explicit Clause(Pattern lhs, Expr rhs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Clause, ObjectRef, ClauseNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ClauseNode);\n};\n\n/*!\n * \\brief Returns \\p clause with the given properties. A null property denotes 'no change'.\n * Returns \\p clause if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nClause WithFields(Clause clause, Optional<Pattern> opt_lhs = Optional<Pattern>(),\n                  Optional<Expr> opt_rhs = Optional<Expr>());\n\n/*! \\brief ADT pattern matching exression. */\nclass Match;\n/*! \\brief Match container node. */\nclass MatchNode : public ExprNode {\n public:\n  /*! \\brief The input being deconstructed. */\n  Expr data;\n\n  /*! \\brief The match node clauses. */\n  tvm::Array<Clause> clauses;\n\n  /*! \\brief Should this match be complete (cover all cases)?\n   *  If yes, the type checker will generate an error if there are any missing cases.\n   */\n  bool complete;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"data\", &data);\n    v->Visit(\"clauses\", &clauses);\n    v->Visit(\"complete\", &complete);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const MatchNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(data, other->data) && equal(clauses, other->clauses) &&\n           equal(complete, other->complete);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(data);\n    hash_reduce(clauses);\n    hash_reduce(complete);\n  }\n\n  static constexpr const char* _type_key = \"relay.Match\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MatchNode, ExprNode);\n};\n\nclass Match : public Expr {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param data the input being deconstructed.\n   * \\param clauses The clauses for matching.\n   * \\param complete Indicate if this match is complete.\n   * \\param span The span of the expression.\n   */\n  TVM_DLL Match(Expr data, tvm::Array<Clause> clauses, bool complete = true, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Match, RelayExpr, MatchNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(MatchNode);\n};\n\n/*!\n * \\brief Returns \\p match with the given properties. A null property denotes 'no change'.\n * Returns \\p match if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nMatch WithFields(Match match, Optional<Expr> opt_data = Optional<Expr>(),\n                 Optional<Array<Clause>> opt_clauses = Optional<Array<Clause>>(),\n                 Optional<Bool> opt_complete = Optional<Bool>(),\n                 Optional<Span> opt_span = Optional<Span>());\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_ADT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/analysis.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/analysis.h\n * \\brief The set of Relay analysis passes written in C++.\n */\n#ifndef TVM_RELAY_ANALYSIS_H_\n#define TVM_RELAY_ANALYSIS_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/relay/adt.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/relay/type.h>\n#include <tvm/runtime/logging.h>\n\n#include <string>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Check that types are well kinded by applying \"kinding rules\".\n *\n * This pass ensures we do not do things that violate the design of the\n * type system when writing down types.\n *\n * For example tensors are not allowed to contain functions in Relay.\n *\n * We check this by ensuring the `dtype` field of a Tensor always contains\n * a data type such as `int`, `float`, `uint`.\n *\n * \\param t The type to check.\n * \\param mod The global module.\n * \\param diag_ctx The Diagnostic context.\n *\n * \\return The kind of the passed type.\n */\nTVM_DLL Kind KindCheck(const Type& t, const IRModule& mod,\n                       Optional<DiagnosticContext> diag_ctx = Optional<DiagnosticContext>());\n\n/*!\n * \\brief Check whether an expression is constant.\n *\n * If the inputs of an expression are all constant, it means the expression\n * itself is constant also.\n *\n * \\param e the expression.\n *\n * \\return whether the expression is constant.\n */\nTVM_DLL bool ConstantCheck(const Expr& e);\n\n/*!\n * \\brief Check whether an expression is in the basic block normal form.\n *\n * \\param e the expression.\n *\n * \\return whether the expression is in the basic block normal form.\n */\nTVM_DLL bool BasicBlockNormalFormCheck(const Expr& e);\n\n/*!\n * \\brief Check that each Var is only bound once.\n *\n * For example, the expression `let x = 1 in let x = 2 in 3` bound x twice.\n *\n * `let f = (x -> x) in let g = (x -> x + 1) in f(g(2))` also bound x twice,\n * although x is not shadowed.\n *\n * \\param expr the expression to check.\n * \\param diag_ctx the diagnostic context\n *\n * \\return true iff all Var in expr is bound at most once.\n */\nTVM_DLL bool WellFormed(const Expr& expr,\n                        Optional<DiagnosticContext> diag_ctx = Optional<DiagnosticContext>());\n\n/*!\n * \\brief Get all bound variables from expression expr.\n *\n * Bound variables are all variables that are declared in the expr.\n * They only have meaning inside that expr, and can only be used in it.\n *\n * \\param expr the expression.\n *\n * \\return List of bound vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<Var> BoundVars(const Expr& expr);\n\n/*!\n * \\brief Get all bound variables from pattern pat.\n *\n * Bound variables are all variables that got bound by the pat.\n * They only have meaning inside that expr, and can only be used in it.\n *\n * \\param pat the Pattern.\n *\n * \\return List of bound vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<Var> BoundVars(const Pattern& pat);\n\n/*!\n * \\brief Get free type parameters from expression expr.\n *\n * Free variables are variables that are not bound by a\n * let or a function parameter in the context.\n *\n * \\param expr the expression.\n *\n * \\return List of free vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<Var> FreeVars(const Expr& expr);\n\n/*!\n * \\brief Get all variables from expression expr.\n *\n * \\param expr the expression.\n *\n * \\return List of all vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<Var> AllVars(const Expr& expr);\n\n/*!\n * \\brief Get free TypeVars from expression expr.\n *\n * Free type parameters are type parameters that are not bound by a function\n * type in the context.\n *\n * \\param expr the expression.\n * \\param mod the module.\n *\n * \\return List of free vars, in the PostDFS order visited by expr.\n */\nTVM_DLL tvm::Array<TypeVar> FreeTypeVars(const Expr& expr, const IRModule& mod);\n\n/*!\n * \\brief Get free TypeVars from type t.\n *\n * Free type parameters are type parameters that are not bound by a function\n * type in the context.\n *\n * \\param t the type.\n * \\param mod the module.\n *\n * \\return List of free type vars, in the PostDFS order visited by type.\n */\nTVM_DLL tvm::Array<TypeVar> FreeTypeVars(const Type& t, const IRModule& mod);\n\n/*!\n * \\brief Get all bound type variables from expression expr.\n *\n * Bound variables are all type variables that are declared in the expr.\n * They only have meaning inside that expr, and can only be used in it.\n *\n * \\param expr the expression.\n * \\param mod the module.\n *\n * \\return List of bound type vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<TypeVar> BoundTypeVars(const Expr& expr, const IRModule& mod);\n\n/*!\n * \\brief Get all bound type variables from type t.\n *\n * Bound variables are all type variables that are declared in the type.\n * They only have meaning inside that type, and can only be used in it.\n *\n * \\param t the type\n * \\param mod the module.\n *\n * \\return List of bound type vars, in the PostDFS order visited by type.\n */\nTVM_DLL tvm::Array<TypeVar> BoundTypeVars(const Type& t, const IRModule& mod);\n\n/*!\n * \\brief Get all type variables in expression expr.\n *\n * \\param expr the expression.\n * \\param mod the module.\n *\n * \\return List of type vars, in the PostDFS order in the expression.\n */\nTVM_DLL tvm::Array<TypeVar> AllTypeVars(const Expr& expr, const IRModule& mod);\n\n/*!\n * \\brief Get all type variables in type t.\n *\n * \\param t the type.\n * \\param mod the module.\n *\n * \\return List of type vars, in the PostDFS order visited by type.\n */\nTVM_DLL tvm::Array<TypeVar> AllTypeVars(const Type& t, const IRModule& mod);\n\n/*!\n * \\brief Finds cases that the given match expression does not catch, if any.\n *\n * \\param match the match expression to test\n *\n * \\param mod The module used for accessing global type var definitions, can be None.\n *\n * \\return Returns a list of cases (as patterns) that are not handled by the match\n * expression.\n */\nTVM_DLL Array<Pattern> UnmatchedCases(const Match& match, const IRModule& mod);\n\n/*!\n * \\brief Get reference counter of each internal ExprNode in body.\n *\n * \\param body The body expression.\n *\n * \\return The reference count mapping.\n */\nTVM_DLL std::unordered_map<const Object*, size_t> GetExprRefCount(const Expr& body);\n\n/*!\n * \\brief Get the updated module for collecting calibration data.\n *\n * \\param mod The module to be updated.\n *\n * \\return The updated module.\n */\nTVM_DLL IRModule GetCalibrateModule(IRModule mod);\n\n/*!\n * \\brief Get the output map between subgrpahs and its inputs/output.\n *\n * \\param mod The module for running calibration.\n *\n * \\return The mapping between a subgraph name and its postition in the output tuple.\n */\nTVM_DLL Map<GlobalVar, Array<Integer>> GetCalibrateOutputMap(const IRModule& mod);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_ANALYSIS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/algorithm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/vision.h\n * \\brief Auxiliary attributes for vision operators.\n */\n#ifndef TVM_RELAY_ATTRS_ALGORITHM_H_\n#define TVM_RELAY_ATTRS_ALGORITHM_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes used in argsort operators */\nstruct ArgsortAttrs : public tvm::AttrsNode<ArgsortAttrs> {\n  int axis;\n  bool is_ascend;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(ArgsortAttrs, \"relay.attrs.ArgsortAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(-1).describe(\n        \"Axis along which to sort the input tensor.\"\n        \"If not given, the flattened array is used.\");\n    TVM_ATTR_FIELD(is_ascend).set_default(true).describe(\n        \"Whether to sort in ascending or descending order.\"\n        \"By default, sort in ascending order\");\n    TVM_ATTR_FIELD(dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"DType of the output indices.\");\n  }\n};\n\nstruct TopKAttrs : public tvm::AttrsNode<TopKAttrs> {\n  Optional<Integer> k;\n  int axis;\n  bool is_ascend;\n  std::string ret_type;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(TopKAttrs, \"relay.attrs.TopkAttrs\") {\n    TVM_ATTR_FIELD(k).describe(\"Number of top elements to select\");\n    TVM_ATTR_FIELD(axis).set_default(-1).describe(\"Axis along which to sort the input tensor.\");\n    TVM_ATTR_FIELD(ret_type).set_default(\"both\").describe(\n        \"The return type [both, values, indices].\"\n        \"both - return both top k data and indices.\"\n        \"values - return top k data only.\"\n        \"indices - return top k indices only.\");\n    TVM_ATTR_FIELD(is_ascend).set_default(false).describe(\n        \"Whether to sort in ascending or descending order.\"\n        \"By default, sort in descending order\");\n    TVM_ATTR_FIELD(dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Data type of the output indices.\");\n  }\n};\n\nstruct SearchSortedAttrs : public tvm::AttrsNode<SearchSortedAttrs> {\n  bool right;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(SearchSortedAttrs, \"relay.attrs.SearchSortedAttrs\") {\n    TVM_ATTR_FIELD(right).set_default(false).describe(\n        \"Controls which index is returned if a value lands exactly on one of sorted values. If \"\n        \" false, the index of the first suitable location found is given. If true, return the \"\n        \"last such index. If there is no suitable index, return either 0 or N (where N is the \"\n        \"size of the innermost dimension).\");\n    TVM_ATTR_FIELD(dtype)\n        .set_default(DataType::Int(32))\n        .describe(\"Data type of the output indices.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_ALGORITHM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/annotation.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/annotation.h\n * \\brief Attribute for annotation operators.\n */\n#ifndef TVM_RELAY_ATTRS_ANNOTATION_H_\n#define TVM_RELAY_ATTRS_ANNOTATION_H_\n\n#include <tvm/ir/attrs.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Annotate an expression to be cast into specific data type.\n */\nstruct CastHintAttrs : public tvm::AttrsNode<CastHintAttrs> {\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(CastHintAttrs, \"relay.attrs.CastHintAttrs\") {\n    TVM_ATTR_FIELD(dtype).describe(\"The data type denoted to be cast.\");\n  }\n};\n\n/*!\n * \\brief Options for the operators used to annotate a compiler.\n */\nstruct CompilerAttrs : public tvm::AttrsNode<CompilerAttrs> {\n  /*! \\brief A 3rd party compiler for code generation. */\n  std::string compiler;\n\n  TVM_DECLARE_ATTRS(CompilerAttrs, \"relay.attrs.CompilerAttrs\") {\n    TVM_ATTR_FIELD(compiler).describe(\"A 3rd party compiler used for code generation.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_ANNOTATION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/bitserial.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/bitserial.h\n * \\brief Auxiliary attributes for bitserial operators.\n */\n\n#ifndef TVM_RELAY_ATTRS_BITSERIAL_H_\n#define TVM_RELAY_ATTRS_BITSERIAL_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes used in bitpack operators */\nstruct BitPackAttrs : public tvm::AttrsNode<BitPackAttrs> {\n  int bits;\n  int pack_axis;\n  int bit_axis;\n  DataType pack_type;\n  std::string name;\n\n  TVM_DECLARE_ATTRS(BitPackAttrs, \"relay.attrs.BitPackAttrs\") {\n    TVM_ATTR_FIELD(bits).set_default(1).describe(\"Number of bits to quantize with.\");\n    TVM_ATTR_FIELD(pack_axis).set_default(1).describe(\n        \"Axis that should be compressed, typically channels.\");\n    TVM_ATTR_FIELD(bit_axis).set_default(-1).describe(\"New axis for packed bits.\");\n    TVM_ATTR_FIELD(pack_type)\n        .set_default(NullValue<DataType>())\n        .describe(\"Type of int to pack bits into.\");\n    TVM_ATTR_FIELD(name).set_default(\"BitPack\").describe(\"Name of operation.\");\n  }\n};\n\n/*! \\brief Attribues used in bitserial convolution operators */\nstruct BinaryConv2DAttrs : public tvm::AttrsNode<BinaryConv2DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  int activation_bits;\n  int weight_bits;\n  std::string data_layout;\n  std::string kernel_layout;\n  DataType pack_dtype;\n  DataType out_dtype;\n  bool unipolar;\n\n  TVM_DECLARE_ATTRS(BinaryConv2DAttrs, \"relay.attrs.BinaryConv2DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero the input is implicitly zero-padded\"\n            \"on both sides for padding number of points.\");\n    TVM_ATTR_FIELD(kernel_size)\n        .set_default(Array<IndexExpr>({3, 3}))\n        .describe(\"Specifies the dimensions of the convolution window.\");\n    TVM_ATTR_FIELD(channels)\n        .set_default(NullValue<IndexExpr>())\n        .describe(\"Number of output channels, needed for shape inference.\");\n    TVM_ATTR_FIELD(activation_bits)\n        .set_default(1)\n        .describe(\"Number of bits activation should be packed with.\");\n    TVM_ATTR_FIELD(weight_bits)\n        .set_default(1)\n        .describe(\"Number of bits kernel should be packed with.\");\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\"Dimension ordering of input data, can be 'NCHW' or NHWC'.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIHW\")\n        .describe(\"Dimension ordering of kernel data, can be 'OIHW' or HWIO'.\");\n    TVM_ATTR_FIELD(pack_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Datatype to pack bits into.\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output datatype.\");\n    TVM_ATTR_FIELD(unipolar).set_default(true).describe(\n        \"Whether to use unipolar or bipolar quantization.\");\n  }\n};\n\n/*~ \\brief Attributes for bitserial dense operator */\nstruct BinaryDenseAttrs : public tvm::AttrsNode<BinaryDenseAttrs> {\n  IndexExpr units;\n  int data_bits;\n  int weight_bits;\n  DataType pack_dtype;\n  DataType out_dtype;\n  bool unipolar;\n\n  TVM_DECLARE_ATTRS(BinaryDenseAttrs, \"relay.attrs.BinaryDenseAttrs\") {\n    TVM_ATTR_FIELD(units).describe(\"Number of hidden units of the dense transformation.\");\n    TVM_ATTR_FIELD(data_bits).set_default(1).describe(\n        \"Number of bits to pack for incoming tensor.\");\n    TVM_ATTR_FIELD(weight_bits)\n        .set_default(1)\n        .describe(\"Number of bits to pack for weight tensor.\");\n    TVM_ATTR_FIELD(pack_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Datatype to pack bits into before computation.\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n    TVM_ATTR_FIELD(unipolar).set_default(true).describe(\n        \"Whether to use unipolar or bipolar quantization for inputs.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_BITSERIAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/call.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/call.h\n * \\brief Attribute for call_lowered operator.\n */\n#ifndef TVM_RELAY_ATTRS_CALL_H_\n#define TVM_RELAY_ATTRS_CALL_H_\n\n#include <tvm/ir/attrs.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Metadata for calls to TIR functions, useful for program analysis crossing Relay and TIR.\n */\nstruct CallLoweredAttrs : public tvm::AttrsNode<CallLoweredAttrs> {\n  /*! \\brief Additional metadata attached to the call node. Should be replaced by explict fields. */\n  Map<String, ObjectRef> metadata;\n\n  TVM_DECLARE_ATTRS(CallLoweredAttrs, \"relay.attrs.CallLoweredAttrs\") {\n    TVM_ATTR_FIELD(metadata)\n        .describe(\"Metadata attached to the lowered function call.\")\n        .set_default(Map<String, ObjectRef>());\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_CALL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/debug.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/debug.h\n * \\brief Auxiliary attributes for debug operators.\n */\n#ifndef TVM_RELAY_ATTRS_DEBUG_H_\n#define TVM_RELAY_ATTRS_DEBUG_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/env_func.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Options for the debug operators.\n */\nstruct DebugAttrs : public tvm::AttrsNode<DebugAttrs> {\n  EnvFunc debug_func;\n\n  TVM_DECLARE_ATTRS(DebugAttrs, \"relay.attrs.DebugAttrs\") {\n    TVM_ATTR_FIELD(debug_func).describe(\"The function to use when debugging.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_DEBUG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/device_copy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/device_copy.h\n * \\brief Attribute for the device copy operator.\n */\n#ifndef TVM_RELAY_ATTRS_DEVICE_COPY_H_\n#define TVM_RELAY_ATTRS_DEVICE_COPY_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/target/virtual_device.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Options for the device copy operators.\n */\nstruct DeviceCopyAttrs : public tvm::AttrsNode<DeviceCopyAttrs> {\n  VirtualDevice src_virtual_device = VirtualDevice::FullyUnconstrained();\n  VirtualDevice dst_virtual_device = VirtualDevice::FullyUnconstrained();\n\n  TVM_DECLARE_ATTRS(DeviceCopyAttrs, \"relay.attrs.DeviceCopyAttrs\") {\n    TVM_ATTR_FIELD(src_virtual_device)\n        .describe(\"The (virtual) device and scope where the op copies data from.\");\n    TVM_ATTR_FIELD(dst_virtual_device)\n        .describe(\"The (virtual) device and scope where the op copies data to.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_DEVICE_COPY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/image.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/image.h\n * \\brief Auxiliary attributes for image operators.\n */\n#ifndef TVM_RELAY_ATTRS_IMAGE_H_\n#define TVM_RELAY_ATTRS_IMAGE_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes used in image resize1d operator */\nstruct Resize1DAttrs : public tvm::AttrsNode<Resize1DAttrs> {\n  Array<IndexExpr> size;\n  Array<FloatImm> roi;\n  std::string layout;\n  std::string method;\n  std::string coordinate_transformation_mode;\n  std::string rounding_method;\n  double cubic_alpha;\n  int cubic_exclude;\n  double extrapolation_value;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Resize1DAttrs, \"relay.attrs.Resize1DAttrs\") {\n    TVM_ATTR_FIELD(size).set_default(NullValue<Array<IndexExpr>>()).describe(\"Output Size.\");\n    TVM_ATTR_FIELD(roi)\n        .set_default(NullValue<Array<FloatImm>>())\n        .describe(\"Region of Interest for coordinate transformation mode 'tf_crop_and_resize'\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCW\").describe(\n        \"Dimension ordering of input data. Can be 'NCW', 'NWC', etc.\"\n        \"'N', 'C', 'W' stands for batch, channel and width\"\n        \"dimensions respectively. Resize is applied on the\"\n        \"'W' dimension.\");\n    TVM_ATTR_FIELD(method).set_default(\"linear\").describe(\n        \"Specify the mode to use for scaling.\"\n        \"nearest_neighbor -  Nearest Neighbor\"\n        \"linear - Linear Interpolation\"\n        \"cubic - Cubic Interpolation\");\n    TVM_ATTR_FIELD(coordinate_transformation_mode)\n        .set_default(\"half_pixel\")\n        .describe(\n            \"Describes how to transform the coordinate in the resized tensor\"\n            \"to the coordinate in the original tensor.\"\n            \"Refer to the ONNX Resize operator specification for details\"\n            \"Available options are half_pixel, align_corners and asymmetric\");\n    TVM_ATTR_FIELD(rounding_method)\n        .set_default(\"round\")\n        .describe(\n            \"indicates how to find the \\\"nearest\\\" pixel in nearest_neighbor method\"\n            \"Available options are round, floor, and ceil.\");\n    TVM_ATTR_FIELD(cubic_alpha)\n        .set_default(-0.5)\n        .describe(\"Spline Coefficient for cubic interpolation\");\n    TVM_ATTR_FIELD(cubic_exclude)\n        .set_default(0)\n        .describe(\"Flag to exclude exterior of the image during cubic interpolation\");\n    TVM_ATTR_FIELD(extrapolation_value)\n        .set_default(0.0)\n        .describe(\"Value to return when roi is outside of the image\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n  }\n};\n\n/*! \\brief Attributes used in image resize2d operator */\nstruct Resize2DAttrs : public tvm::AttrsNode<Resize2DAttrs> {\n  Array<IndexExpr> size;\n  Array<FloatImm> roi;\n  std::string layout;\n  std::string method;\n  std::string coordinate_transformation_mode;\n  std::string rounding_method;\n  double cubic_alpha;\n  int cubic_exclude;\n  double extrapolation_value;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Resize2DAttrs, \"relay.attrs.Resize2DAttrs\") {\n    TVM_ATTR_FIELD(size).set_default(NullValue<Array<IndexExpr>>()).describe(\"Output Size.\");\n    TVM_ATTR_FIELD(roi)\n        .set_default(NullValue<Array<FloatImm>>())\n        .describe(\"Region of Interest for coordinate transformation mode 'tf_crop_and_resize'\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Resize is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(method).set_default(\"linear\").describe(\n        \"Specify the mode to use for scaling.\"\n        \"nearest_neighbor -  Nearest Neighbor\"\n        \"linear - Bilinear Interpolation\"\n        \"cubic - Bicubic Interpolation\");\n    TVM_ATTR_FIELD(coordinate_transformation_mode)\n        .set_default(\"half_pixel\")\n        .describe(\n            \"Describes how to transform the coordinate in the resized tensor\"\n            \"to the coordinate in the original tensor.\"\n            \"Refer to the ONNX Resize operator specification for details\"\n            \"Available options are half_pixel, align_corners and asymmetric\");\n    TVM_ATTR_FIELD(rounding_method)\n        .set_default(\"round\")\n        .describe(\n            \"indicates how to find the \\\"nearest\\\" pixel in nearest_neighbor method\"\n            \"Available options are round, floor, and ceil.\");\n    TVM_ATTR_FIELD(cubic_alpha)\n        .set_default(-0.5)\n        .describe(\"Spline Coefficient for Bicubic Interpolation\");\n    TVM_ATTR_FIELD(cubic_exclude)\n        .set_default(0)\n        .describe(\"Flag to exclude exterior of the image during bicubic interpolation\");\n    TVM_ATTR_FIELD(extrapolation_value)\n        .set_default(0.0)\n        .describe(\"Value to return when roi is outside of the image\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n  }\n};\n\n/*! \\brief Attributes used in image resize3d operator */\nstruct Resize3DAttrs : public tvm::AttrsNode<Resize3DAttrs> {\n  Array<IndexExpr> size;\n  Array<FloatImm> roi;\n  std::string layout;\n  std::string method;\n  std::string coordinate_transformation_mode;\n  std::string rounding_method;\n  double cubic_alpha;\n  int cubic_exclude;\n  double extrapolation_value;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Resize3DAttrs, \"relay.attrs.Resize3DAttrs\") {\n    TVM_ATTR_FIELD(size).set_default(NullValue<Array<IndexExpr>>()).describe(\"Output Size.\");\n    TVM_ATTR_FIELD(roi)\n        .set_default(NullValue<Array<FloatImm>>())\n        .describe(\"Region of Interest for coordinate transformation mode 'tf_crop_and_resize'\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCDHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively. Resize3d is applied on the 'D', 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(method).set_default(\"linear\").describe(\n        \"Specify the mode to use for scaling.\"\n        \"nearest_neighbor -  Nearest Neighbor\"\n        \"linear - Trilinear Interpolation\"\n        \"cubic - Tricubic Interpolation\");\n    TVM_ATTR_FIELD(coordinate_transformation_mode)\n        .set_default(\"half_pixel\")\n        .describe(\n            \"Describes how to transform the coordinate in the resized tensor\"\n            \"to the coordinate in the original tensor.\"\n            \"Refer to the ONNX Resize operator specification for details\"\n            \"Available options are half_pixel, align_corners and asymmetric\");\n    TVM_ATTR_FIELD(rounding_method)\n        .set_default(\"round\")\n        .describe(\n            \"indicates how to find the \\\"nearest\\\" pixel in nearest_neighbor method\"\n            \"Available options are round, floor, and ceil.\");\n    TVM_ATTR_FIELD(cubic_alpha)\n        .set_default(-0.5)\n        .describe(\"Spline Coefficient for Tricubic Interpolation\");\n    TVM_ATTR_FIELD(cubic_exclude)\n        .set_default(0)\n        .describe(\"Flag to exclude exterior of the image during tricubic interpolation\");\n    TVM_ATTR_FIELD(extrapolation_value)\n        .set_default(0.0)\n        .describe(\"Value to return when roi is outside of the image\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n  }\n};\n\n/*! \\brief Attributes used in image crop_and_resize operator */\nstruct CropAndResizeAttrs : public tvm::AttrsNode<CropAndResizeAttrs> {\n  Array<IndexExpr> crop_size;\n  std::string layout;\n  std::string method;\n  double extrapolation_value;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(CropAndResizeAttrs, \"relay.attrs.CropAndResizeAttrs\") {\n    TVM_ATTR_FIELD(crop_size).set_default(NullValue<Array<IndexExpr>>()).describe(\"Target Size.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Resize is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(method)\n        .set_default(\"bilinear\")\n        .describe(\n            \"Specify the mode to use for scaling.\"\n            \"nearest_neighbor -  Nearest Neighbor\"\n            \"bilinear - Bilinear Interpolation\");\n    TVM_ATTR_FIELD(extrapolation_value)\n        .set_default(0.0)\n        .describe(\"Specify value for extrapolation.\");\n    TVM_ATTR_FIELD(out_dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n  }\n};\n\n/*! \\brief Attributes used in dilation operators */\nstruct Dilation2DAttrs : public tvm::AttrsNode<Dilation2DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilations;\n  std::string data_layout;\n  std::string kernel_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Dilation2DAttrs, \"relay.attrs.Dilation2DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the sliding window. [stride_height, stride_width].\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(dilations)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation rate to use. [dilation_height, dilation_width]\");\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"IHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'IHW', 'HWI', etc.\"\n            \"'I', 'H', 'W' stands for input_channel, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in image affine_grid operator */\nstruct AffineGridAttrs : public tvm::AttrsNode<AffineGridAttrs> {\n  Array<IndexExpr> target_shape;\n\n  TVM_DECLARE_ATTRS(AffineGridAttrs, \"relay.attrs.AffineGridAttrs\") {\n    TVM_ATTR_FIELD(target_shape).describe(\"Specifies the output shape (H, W).\");\n  }\n};\n\n/*! \\brief Attributes used in image grid_sample operator */\nstruct GridSampleAttrs : public tvm::AttrsNode<GridSampleAttrs> {\n  String method;\n  String layout;\n  String padding_mode;\n  bool align_corners;\n\n  TVM_DECLARE_ATTRS(GridSampleAttrs, \"relay.attrs.GridSampleAttrs\") {\n    TVM_ATTR_FIELD(method)\n        .set_default(\"bilinear\")\n        .describe(\n            \"Specify the mode to use for scaling.\"\n            \"nearest - 2D or 3D Nearest Interpolation.\"\n            \"bilinear - '2D Bilinear' or '3D Trilinear' Interpolation.\"\n            \"bicubic - 2D Bicubic Interpolation.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NCDHW', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively.\"\n        \"2D Resize is applied on the 'H' and 'W' dimensions.\"\n        \"3D Resize is applied on the 'D' and 'H' and 'W' dimensions.\");\n    TVM_ATTR_FIELD(padding_mode)\n        .set_default(\"zeros\")\n        .describe(\n            \"If :attr:'grid' has values outside the range of '[-1, 1]', the corresponding\"\n            \"outputs are handled as defined by padding_mode. Options are\"\n            \"padding_mode='zeros': use '0' for out-of-bound grid locations,\"\n            \"padding_mode='border': use border values for out-of-bound grid locations\"\n            \"padding_mode='reflection': use values at locations reflected by\"\n            \"the border for out-of-bound grid locations. For location far away\"\n            \"from the border, it will keep being reflected until becoming in bound,\"\n            \"e.g., (normalized) pixel location 'x = -3.5' reflects by border '-1'\"\n            \"and becomes 'x' = 1.5, then reflects by border '1' and becomes\"\n            \"'x' = -0.5\");\n    TVM_ATTR_FIELD(align_corners)\n        .set_default(true)\n        .describe(\n            \"Geometrically, we consider the pixels of the\"\n            \"input as squares rather than points.\"\n            \"If set to True, the extrema (-1 and 1) are considered as referring\"\n            \"to the center points of the input's corner pixels. If set to False, they\"\n            \"are instead considered as referring to the corner points of the input's corner\"\n            \"pixels, making the sampling more resolution agnostic.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_IMAGE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/memory.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/memory.h\n * \\brief Attributes for memory operators.\n */\n#ifndef TVM_RELAY_ATTRS_MEMORY_H_\n#define TVM_RELAY_ATTRS_MEMORY_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/expr.h>\n#include <tvm/target/virtual_device.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\nstd::vector<TensorType> FlattenTupleType(const Type& type);\nstd::vector<Expr> FromTupleType(const Type& type, const Expr& expr);\nExpr ToTupleType(const Type& t, const std::vector<Expr>& exprs);\n\n/*!\n * \\brief Options for allocating storage.\n */\nstruct AllocStorageAttrs : public tvm::AttrsNode<AllocStorageAttrs> {\n  DataType dtype;\n  VirtualDevice virtual_device = VirtualDevice::FullyUnconstrained();\n\n  TVM_DECLARE_ATTRS(AllocStorageAttrs, \"relay.attrs.AllocStorageAttrs\") {\n    TVM_ATTR_FIELD(dtype)\n        .describe(\"The dtype of the tensor to allocate.\")\n        .set_default(DataType::Float(32, 1));\n    TVM_ATTR_FIELD(virtual_device).describe(\"The virtual device on which to allocate memory.\");\n  }\n};\n\n/*!\n * \\brief Options for allocating tensors.\n */\nstruct AllocTensorAttrs : public tvm::AttrsNode<AllocTensorAttrs> {\n  Constant const_shape;\n  Array<IndexExpr> assert_shape;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(AllocTensorAttrs, \"relay.attrs.AllocTensorAttrs\") {\n    TVM_ATTR_FIELD(dtype)\n        .describe(\"The dtype of the tensor to allocate.\")\n        .set_default(DataType::Float(32, 1));\n    TVM_ATTR_FIELD(const_shape).describe(\"The shape of constant used to aid in type inference.\");\n    TVM_ATTR_FIELD(assert_shape)\n        .describe(\n            \"The shape to cast the return type of the allocation to, \"\n            \"used to specify the shape obtained via further analysis.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_MEMORY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/nn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/nn.h\n * \\brief Auxiliary attributes for nn operators.\n */\n#ifndef TVM_RELAY_ATTRS_NN_H_\n#define TVM_RELAY_ATTRS_NN_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Add a 1D Tensor to an axis of a data.\n *\n * \\note bias_add is a special add operator that is in nn\n *   and enables automatic derivation of bias's shape.\n *   You can directly use add for more generalized case.\n */\nstruct BiasAddAttrs : public tvm::AttrsNode<BiasAddAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(BiasAddAttrs, \"relay.attrs.BiasAddAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\"The axis to add the bias\").set_default(1);\n  }\n};\n\n/*! \\brief Attributes used in 1D convolution operators */\nstruct Conv1DAttrs : public tvm::AttrsNode<Conv1DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  tvm::String data_layout;\n  tvm::String kernel_layout;\n  tvm::String out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv1DAttrs, \"relay.attrs.Conv1DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({\n            1,\n        }))\n        .describe(\"Specifies the stride of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"on both sides for padding number of points\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({\n            1,\n        }))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Currently unused but may be added in the future.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Convolution is applied on the 'W'\"\n            \"dimension.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIW', or 'WIO', etc.\"\n            \"'O', 'I', 'W' stands for num_filter, input_channel, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in convolution operators */\nstruct Conv2DAttrs : public tvm::AttrsNode<Conv2DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  tvm::String data_layout;\n  tvm::String kernel_layout;\n  tvm::String out_layout;\n  tvm::String auto_scheduler_rewritten_layout;   // The layout after auto-scheduler's layout rewrite\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv2DAttrs, \"relay.attrs.Conv2DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc.\"\n            \"'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in winograd weight transformation operators */\nstruct ConvWinogradWeightTransformAttrs : public tvm::AttrsNode<ConvWinogradWeightTransformAttrs> {\n  int tile_size;\n\n  TVM_DECLARE_ATTRS(ConvWinogradWeightTransformAttrs,\n                    \"relay.attrs.ConvWinogradWeightTransformAttrs\") {\n    TVM_ATTR_FIELD(tile_size).describe(\n        \"Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\");\n  }\n};\n\n/*! \\brief Attributes used in gemm weight transformation operators */\nstruct ConvGemmWeightTransformAttrs : public tvm::AttrsNode<ConvGemmWeightTransformAttrs> {\n  int tile_rows;\n  int tile_cols;\n\n  TVM_DECLARE_ATTRS(ConvGemmWeightTransformAttrs, \"relay.attrs.ConvGemmWeightTransformAttrs\") {\n    TVM_ATTR_FIELD(tile_rows).describe(\"Tile rows of the weight transformation for ConvGemm.\");\n    TVM_ATTR_FIELD(tile_cols).describe(\"Tile columns of the weight transformation for ConvGemm.\");\n  }\n};\n\n/*! \\brief Attributes used in convolution operators with winograd algorithm */\nstruct Conv2DWinogradAttrs : public tvm::AttrsNode<Conv2DWinogradAttrs> {\n  int tile_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  tvm::String data_layout;\n  tvm::String kernel_layout;\n  tvm::String out_layout;\n  tvm::String auto_scheduler_rewritten_layout;   // The layout after auto-scheduler's layout rewrite\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv2DWinogradAttrs, \"relay.attrs.Conv2DWinogradAttrs\") {\n    TVM_ATTR_FIELD(tile_size).describe(\n        \"The tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc.\"\n            \"'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in winograd weight transformation operators */\nstruct Conv2DWinogradNNPACKWeightTransformAttrs\n    : public tvm::AttrsNode<Conv2DWinogradNNPACKWeightTransformAttrs> {\n  int convolution_algorithm;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv2DWinogradNNPACKWeightTransformAttrs,\n                    \"relay.attrs.Conv2DWinogradNNPACKWeightTransformAttrs\") {\n    TVM_ATTR_FIELD(convolution_algorithm)\n        .describe(\n            \"The convolution algorithm for Winograd NNPACK. \"\n            \"E.g. tvm.contrib.nnpack.ConvolutionAlgorithm.WT_8x8 for WT_8x8, \"\n            \"tvm.contrib.nnpack.ConvolutionAlgorithm.WT_8x8_FP16 for WT_8x8_FP16\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in convolution operators */\nstruct Conv3DAttrs : public tvm::AttrsNode<Conv3DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  tvm::String data_layout;\n  tvm::String kernel_layout;\n  tvm::String out_layout;\n  tvm::String auto_scheduler_rewritten_layout;   // The layout after auto-scheduler's layout rewrite\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv3DAttrs, \"relay.attrs.Conv3DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : back, bottom, right will use same padding as front, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom,\"\n            \"right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCDHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'D', 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIDHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIDHW', 'OIDHW16o16i', etc.\"\n            \"'O', 'I', 'D', 'H', 'W' stands for num_filter, input_channel, depth, height,\"\n            \"and width dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in transposed convolution operator */\nstruct Conv3DTransposeAttrs : public tvm::AttrsNode<Conv3DTransposeAttrs> {\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> output_padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  tvm::String data_layout;\n  tvm::String kernel_layout;\n  tvm::String out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv3DTransposeAttrs, \"relay.attrs.Conv3DTransposeAttrs\") {\n    TVM_ATTR_FIELD(channels)\n        .set_default(NullValue<IndexExpr>())\n        .describe(\n            \"The dimensionality of the output space\"\n            \"i.e. the number of output channels in the convolution.\");\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"The dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"The strides of the convolution.\");\n    TVM_ATTR_FIELD(output_padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"Zero-padding added to one side of the output.\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : front, bottom, right will use same padding as back, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom, right)\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : front, bottom, right will use same padding as back, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom, right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCDHW\")\n        .describe(\n            \"Dimension ordering of data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'D', 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIDHW\")\n        .describe(\n            \"Dimension ordering of data and weight. Can be 'OIDHW', 'OIDHW16o16i', etc.\"\n            \"'O', 'I', 'D', 'H', 'W' stands for num_filter, input_channel, depth, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in 3d winograd convolution operators */\nstruct Conv3DWinogradAttrs : public tvm::AttrsNode<Conv3DWinogradAttrs> {\n  int tile_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  std::string data_layout;\n  std::string kernel_layout;\n  std::string out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv3DWinogradAttrs, \"relay.attrs.Conv3DWinogradAttrs\") {\n    TVM_ATTR_FIELD(tile_size).describe(\n        \"The tile size of winograd. E.g. 2 for F(2x2x2, 3x3x3) and 4 for F(4x4x4, 3x3x3)\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : back, bottom, right will use same padding as front, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom,\"\n            \"right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCDHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'D', 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIDHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIDHW', 'OIDHW16o16i', etc.\"\n            \"'O', 'I', 'D', 'H', 'W' stands for num_filter, input_channel, depth, height,\"\n            \"and width dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in softmax operators */\nstruct SoftmaxAttrs : public tvm::AttrsNode<SoftmaxAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(SoftmaxAttrs, \"relay.attrs.SoftmaxAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(-1).describe(\"The axis to sum over when computing softmax.\");\n  }\n};\n\n/*! \\brief Attributes used in transposed convolution operator */\nstruct Conv2DTransposeAttrs : public tvm::AttrsNode<Conv2DTransposeAttrs> {\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> output_padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  std::string data_layout;\n  std::string kernel_layout;\n  std::string out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv2DTransposeAttrs, \"relay.attrs.Conv2DTransposeAttrs\") {\n    TVM_ATTR_FIELD(channels)\n        .set_default(NullValue<IndexExpr>())\n        .describe(\n            \"The dimensionality of the output space\"\n            \"i.e. the number of output channels in the convolution.\");\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"The dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"The strides of the convolution.\");\n    TVM_ATTR_FIELD(output_padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"Zero-padding added to one side of the output.\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\n            \"Dimension ordering of data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIHW\")\n        .describe(\n            \"Dimension ordering of data and weight. Can be 'OIHW', 'OIHW16o16i', etc.\"\n            \"'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in dilate operator */\nstruct DilateAttrs : public tvm::AttrsNode<DilateAttrs> {\n  Array<IndexExpr> strides;\n  double dilation_value;\n\n  TVM_DECLARE_ATTRS(DilateAttrs, \"relay.attrs.DilateAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Dilation stride on each dimension, 1 means no dilation.\");\n    TVM_ATTR_FIELD(dilation_value).set_default(0.0).describe(\"Value used to dilate the input.\");\n  }\n};\n\n/*! \\brief Attributes used in 1D transposed convolution operator */\nstruct Conv1DTransposeAttrs : public tvm::AttrsNode<Conv1DTransposeAttrs> {\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> output_padding;\n  Array<IndexExpr> dilation;\n  int groups;\n  std::string data_layout;\n  std::string kernel_layout;\n  std::string out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(Conv1DTransposeAttrs, \"relay.attrs.Conv1DTransposeAttrs\") {\n    TVM_ATTR_FIELD(channels)\n        .set_default(NullValue<IndexExpr>())\n        .describe(\n            \"The dimensionality of the output space\"\n            \"i.e. the number of output channels in the convolution.\");\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"The dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"The strides of the convolution.\");\n    TVM_ATTR_FIELD(output_padding)\n        .set_default(Array<IndexExpr>({0}))\n        .describe(\"Zero-padding added to one side of the output.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0}))\n        .describe(\n            \"Symmetric or asymmetric padding.\"\n            \"Single value: the input is implicitly zero-padded on both sides.\"\n            \"Two values: padding[0] is used for left input padding, \"\n            \"padding[1] is used for right input padding,\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCW\")\n        .describe(\n            \"Dimension ordering of data. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Convolution is applied on the\"\n            \"'W' dimension.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIW\")\n        .describe(\n            \"Dimension ordering of data and weight. Can be 'OIW', 'OIW16o16i', etc.\"\n            \"'O', 'I', 'W' stands for num_filter, input_channel, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes for max pool operator */\nstruct MaxPool2DAttrs : public tvm::AttrsNode<MaxPool2DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  tvm::String layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n\n  TVM_DECLARE_ATTRS(MaxPool2DAttrs, \"relay.attrs.MaxPool2DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n  }\n};\n\n/*! \\brief Attributes for avg pool operator */\nstruct AvgPool2DAttrs : public tvm::AttrsNode<AvgPool2DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  tvm::String layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n  bool count_include_pad;\n\n  TVM_DECLARE_ATTRS(AvgPool2DAttrs, \"relay.attrs.AvgPool2DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n    TVM_ATTR_FIELD(count_include_pad)\n        .set_default(false)\n        .describe(\"When true, will include padding to compute the average\");\n  }\n};\n\n/*! \\brief Attributes for global pool operator */\nstruct GlobalPool2DAttrs : public tvm::AttrsNode<GlobalPool2DAttrs> {\n  tvm::String layout;\n  tvm::String out_layout;\n\n  TVM_DECLARE_ATTRS(GlobalPool2DAttrs, \"relay.attrs.GlobalPool2DAttrs\") {\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'H' and\"\n            \"'W' dimensions.\");\n  }\n};\n\n/*! \\brief Attributes for 1d adaptive pool operator */\nstruct AdaptivePool1DAttrs : public tvm::AttrsNode<AdaptivePool1DAttrs> {\n  Array<IndexExpr> output_size;\n  std::string layout;\n  tvm::String out_layout;\n\n  TVM_DECLARE_ATTRS(AdaptivePool1DAttrs, \"relay.attrs.AdaptivePool1DAttrs\") {\n    TVM_ATTR_FIELD(output_size).set_default(Array<IndexExpr>({})).describe(\"Output width.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCW\").describe(\n        \"Dimension ordering of input data. Can be 'NCW', 'NWC', etc.\"\n        \"'N', 'C', 'W' stands for batch, channel, and width\"\n        \"dimensions respectively. Pooling is applied on the\"\n        \"'W' dimension.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Pooling is applied on the\"\n            \"'W' dimension.\");\n  }\n};\n\n/*! \\brief Attributes for 2d adaptive pool operator */\nstruct AdaptivePool2DAttrs : public tvm::AttrsNode<AdaptivePool2DAttrs> {\n  Array<IndexExpr> output_size;\n  std::string layout;\n  tvm::String out_layout;\n\n  TVM_DECLARE_ATTRS(AdaptivePool2DAttrs, \"relay.attrs.AdaptivePool2DAttrs\") {\n    TVM_ATTR_FIELD(output_size)\n        .set_default(Array<IndexExpr>({}))\n        .describe(\"Output height and width.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'H' and\"\n            \"'W' dimensions.\");\n  }\n};\n\n/*! \\brief Attributes for 3d adaptive pool operator */\nstruct AdaptivePool3DAttrs : public tvm::AttrsNode<AdaptivePool3DAttrs> {\n  Array<IndexExpr> output_size;\n  std::string layout;\n  tvm::String out_layout;\n\n  TVM_DECLARE_ATTRS(AdaptivePool3DAttrs, \"relay.attrs.AdaptivePool3DAttrs\") {\n    TVM_ATTR_FIELD(output_size)\n        .set_default(Array<IndexExpr>({}))\n        .describe(\"Output depth, height and width.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCDHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively. Pooling is applied on 'D', 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Pooling is applied on 'D', 'H' and\"\n            \"'W' dimensions.\");\n  }\n};\n\n/*! \\brief Attributes for 1D max pool operator */\nstruct MaxPool1DAttrs : public tvm::AttrsNode<MaxPool1DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> dilation;\n  Array<IndexExpr> padding;\n  std::string layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n\n  TVM_DECLARE_ATTRS(MaxPool1DAttrs, \"relay.attrs.MaxPool1DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding supports both symmetric and asymmetric as\"\n            \"one int : same padding used on each side\"\n            \"two int : indicates left padding, right padding\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCW\").describe(\n        \"Dimension ordering of input data. Can be 'NCW', 'NWC', etc.\"\n        \"'N', 'C', 'W' stands for batch, channel, and width\"\n        \"dimensions respectively. Pooling is applied on the 'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCW', 'NWC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Pooling is applied on the 'W' dimensions.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n  }\n};\n\n/*! \\brief Attributes for 1D avg pool operator */\nstruct AvgPool1DAttrs : public tvm::AttrsNode<AvgPool1DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> dilation;\n  Array<IndexExpr> padding;\n  std::string layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n  bool count_include_pad;\n\n  TVM_DECLARE_ATTRS(AvgPool1DAttrs, \"relay.attrs.AvgPool1DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding supports both symmetric and asymmetric as\"\n            \"one int : same padding used on each side\"\n            \"two int : indicates left padding, right padding\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCW\").describe(\n        \"Dimension ordering of input data. Can be 'NCW', 'NHC', etc.\"\n        \"'N', 'C', 'W' stands for batch, channel, and width\"\n        \"dimensions respectively. Pooling is applied on the 'W' dimension.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCW', 'NHC', etc.\"\n            \"'N', 'C', 'W' stands for batch, channel, and width\"\n            \"dimensions respectively. Pooling is applied on the 'W' dimension.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n    TVM_ATTR_FIELD(count_include_pad)\n        .set_default(false)\n        .describe(\"When true, will include padding to compute the average\");\n  }\n};\n\n/*! \\brief Attributes for 3D max pool operator */\nstruct MaxPool3DAttrs : public tvm::AttrsNode<MaxPool3DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> dilation;\n  Array<IndexExpr> padding;\n  std::string layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n\n  TVM_DECLARE_ATTRS(MaxPool3DAttrs, \"relay.attrs.MaxPool3DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : back, bottom, right will use same padding as front, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom, right)\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCDHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'D', 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'D', 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n  }\n};\n\n/*! \\brief Attributes for 3D avg pool operator */\nstruct AvgPool3DAttrs : public tvm::AttrsNode<AvgPool3DAttrs> {\n  Array<IndexExpr> pool_size;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> dilation;\n  Array<IndexExpr> padding;\n  std::string layout;\n  tvm::String out_layout;\n  bool ceil_mode;\n  bool count_include_pad;\n\n  TVM_DECLARE_ATTRS(AvgPool3DAttrs, \"relay.attrs.AvgPool3DAttrs\") {\n    TVM_ATTR_FIELD(pool_size).describe(\"Size of the pooling windows.\");\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1, 1}))\n        .describe(\"Specifies the dilation of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"three int : back, bottom, right will use same padding as front, top, left\"\n            \"six int : padding width in the order of (front, top, left, back, bottom, right)\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCDHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively. Pooling is applied on the 'D', 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output data. Can be 'NCDHW', 'NDHWC', etc.\"\n            \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n            \"dimensions respectively. Pooling is applied on the 'D', 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(ceil_mode).set_default(false).describe(\n        \"When true, will use ceil instead of floor to compute the output shape.\");\n    TVM_ATTR_FIELD(count_include_pad)\n        .set_default(false)\n        .describe(\"When true, will include padding to compute the average\");\n  }\n};\n\n/*! \\brief Attributes for matmul operator */\nstruct MatmulAttrs : public tvm::AttrsNode<MatmulAttrs> {\n  IndexExpr units;\n  DataType out_dtype;\n  bool transpose_a;\n  bool transpose_b;\n  // layout of B after auto-scheduler's layout rewrite\n  tvm::String auto_scheduler_rewritten_layout;\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n\n  TVM_DECLARE_ATTRS(MatmulAttrs, \"relay.attrs.MatmulAttrs\") {\n    TVM_ATTR_FIELD(units).describe(\"Number of hidden units of the dense transformation.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n\n    TVM_ATTR_FIELD(transpose_a)\n        .set_default(false)\n        .describe(\"Whether the first input tensor is in transposed format.\");\n\n    TVM_ATTR_FIELD(transpose_b)\n        .set_default(false)\n        .describe(\"Whether the second input tensor is in transposed format.\");\n  }\n};\n\n/*! \\brief Attributes for dense operator */\nstruct DenseAttrs : public tvm::AttrsNode<DenseAttrs> {\n  IndexExpr units;\n  // layout of B after auto-scheduler's layout rewrite\n  tvm::String auto_scheduler_rewritten_layout;\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(DenseAttrs, \"relay.attrs.DenseAttrs\") {\n    TVM_ATTR_FIELD(units).describe(\"Number of hidden units of the dense transformation.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes for dense_pack operator */\nstruct DensePackAttrs : public tvm::AttrsNode<DensePackAttrs> {\n  IndexExpr units;\n  DataType out_dtype;\n  tvm::String weight_layout;\n\n  TVM_DECLARE_ATTRS(DensePackAttrs, \"relay.attrs.DensePackAttrs\") {\n    TVM_ATTR_FIELD(units).describe(\"Number of hidden units of the dense transformation.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n    TVM_ATTR_FIELD(weight_layout)\n        .set_default(\"NC\")\n        .describe(\"Dimension ordering of weight. Packed layouts, such as NC8n, are possible.\");\n  }\n};\n\n/*! \\brief Attributes for batch matmul operator. */\nstruct BatchMatmulAttrs : public tvm::AttrsNode<BatchMatmulAttrs> {\n  DataType out_dtype;\n  bool transpose_a;\n  bool transpose_b;\n  tvm::String auto_scheduler_rewritten_layout;   // The layout after auto-scheduler's layout rewrite\n  Array<PrimExpr> meta_schedule_original_shape;  // The original shape of the weights\n\n  TVM_DECLARE_ATTRS(BatchMatmulAttrs, \"relay.attrs.BatchMatmulAttrs\") {\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n\n    TVM_ATTR_FIELD(transpose_a)\n        .set_default(false)\n        .describe(\"Whether the first input tensor is in transposed format.\");\n\n    TVM_ATTR_FIELD(transpose_b)\n        .set_default(false)\n        .describe(\"Whether the second input tensor is in transposed format.\");\n  }\n};\n\n/*! \\brief Attributes for sparse_dense operator */\nstruct SparseDenseAttrs : public tvm::AttrsNode<SparseDenseAttrs> {\n  bool sparse_lhs;\n\n  TVM_DECLARE_ATTRS(SparseDenseAttrs, \"relay.attrs.SparseDenseAttrs\") {\n    TVM_ATTR_FIELD(sparse_lhs)\n        .set_default(false)\n        .describe(\n            \"Indicate whether sparse matrix is multiplied on the right or the left. If true, then \"\n            \"the operation is S * D^T (D dense, S sparse). If false, the operation is D * S^T\");\n  }\n};\n\n/*! \\brief Attributes for sparse_transpose operator */\nstruct SparseTransposeAttrs : public tvm::AttrsNode<SparseTransposeAttrs> {\n  TVM_DECLARE_ATTRS(SparseTransposeAttrs, \"relay.attrs.SparseTransposeAttrs\") {}\n};\n\n/*! \\brief Attributes for sparse_dense operator */\nstruct SparseConv2DAttrs : public tvm::AttrsNode<SparseConv2DAttrs> {\n  std::string layout;\n  Array<IndexExpr> kernel_size;\n\n  TVM_DECLARE_ATTRS(SparseConv2DAttrs, \"relay.attrs.SparseConv2DAttrs\") {\n    TVM_ATTR_FIELD(layout).set_default(\"NHWC\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC'\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively.\");\n    TVM_ATTR_FIELD(kernel_size)\n        .set_default(Array<IndexExpr>{1, 1})\n        .describe(\"Kernel size for SparseConv2D, 1x1 or 3x3. \");\n  }\n};\n\n/*! \\brief Attributes for FIFO buffer operator */\nstruct FIFOBufferAttrs : public tvm::AttrsNode<FIFOBufferAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(FIFOBufferAttrs, \"relay.attrs.FIFOBufferAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(0);\n  }\n};\n\n/*! \\brief Attributes for upsampling operator */\nstruct UpSamplingAttrs : public tvm::AttrsNode<UpSamplingAttrs> {\n  double scale_h;\n  double scale_w;\n  tvm::String layout;\n  tvm::String method;\n  bool align_corners;\n\n  TVM_DECLARE_ATTRS(UpSamplingAttrs, \"relay.attrs.UpSamplingAttrs\") {\n    TVM_ATTR_FIELD(scale_h).describe(\"The upsampling factor for height\");\n    TVM_ATTR_FIELD(scale_w).describe(\"The upsampling factor for width\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Upsampling is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(method)\n        .set_default(\"nearest_neighbor\")\n        .describe(\n            \"Specify the mode to use for scaling.\"\n            \"nearest_neighbor -  Nearest Neighbor\"\n            \"bilinear - Bilinear Interpolation\"\n            \"bicubic - Bicubic Interpolation\");\n    TVM_ATTR_FIELD(align_corners)\n        .set_default(false)\n        .describe(\"Should be true to preserve the values at the corner pixels\");\n  }\n};\n\n/*! \\brief Attributes for upsampling3d operator */\nstruct UpSampling3DAttrs : public tvm::AttrsNode<UpSampling3DAttrs> {\n  double scale_d;\n  double scale_h;\n  double scale_w;\n  std::string layout;\n  std::string method;\n  std::string coordinate_transformation_mode;\n\n  TVM_DECLARE_ATTRS(UpSampling3DAttrs, \"relay.attrs.UpSampling3DAttrs\") {\n    TVM_ATTR_FIELD(scale_d).describe(\"The upsampling factor for depth\");\n    TVM_ATTR_FIELD(scale_h).describe(\"The upsampling factor for height\");\n    TVM_ATTR_FIELD(scale_w).describe(\"The upsampling factor for width\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCDHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCDHW', 'NDHWC', etc.\"\n        \"'N', 'C', 'D', 'H', 'W' stands for batch, channel, depth, height, and width\"\n        \"dimensions respectively. Upsampling is applied on the 'D', 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(method)\n        .set_default(\"nearest_neighbor\")\n        .describe(\n            \"Specify the mode to use for scaling.\"\n            \"nearest_neighbor -  Nearest Neighbor\"\n            \"trilinear - Trilinear Interpolation\");\n    TVM_ATTR_FIELD(coordinate_transformation_mode)\n        .set_default(\"half_pixel\")\n        .describe(\n            \"Describes how to transform the coordinate in the resized tensor\"\n            \"to the coordinate in the original tensor.\"\n            \"Refer to the ONNX Resize operator specification for details\"\n            \"Available options are half_pixel, align_corners and asymmetric\");\n  }\n};\n\n/*! \\brief Attributes used for the padding operator */\nstruct PadAttrs : public tvm::AttrsNode<PadAttrs> {\n  Array<Array<Integer>> pad_width;\n  tvm::String pad_mode;\n\n  TVM_DECLARE_ATTRS(PadAttrs, \"relay.attrs.PadAttrs\") {\n    TVM_ATTR_FIELD(pad_width).describe(\n        \"Number of values padded to the edges of each axis, \"\n        \"in the format of ((before_1, after_1), ..., (before_N, after_N))\");\n    TVM_ATTR_FIELD(pad_mode)\n        .set_default(\"constant\")\n        .describe(\n            \"Padding type to use. \\\"constant\\\" pads with constant_value, \"\n            \"\\\"edge\\\" pads using the edge values of the input array, \"\n            \"\\\"reflect\\\" pads by reflecting values with respect to the edges.\");\n  }\n};\n\n/*! \\brief Attributes used for the MirrorPadding operator */\nstruct MirrorPadAttrs : public tvm::AttrsNode<MirrorPadAttrs> {\n  std::string mode;\n  Array<Array<IndexExpr>> pad_width;\n\n  TVM_DECLARE_ATTRS(MirrorPadAttrs, \"relay.attrs.MirrorPadAttrs\") {\n    TVM_ATTR_FIELD(mode)\n        .set_default(\"SYMMETRIC\")\n        .describe(\"Specifies how mirroring should be performed.\");\n    TVM_ATTR_FIELD(pad_width).describe(\n        \"Number of values padded to the edges of each axis, \"\n        \"in the format of ((before_1, after_1), ..., (before_N, after_N))\");\n  }\n};\n\n/*! \\brief Attributes for leaky relu operator */\nstruct LeakyReluAttrs : public tvm::AttrsNode<LeakyReluAttrs> {\n  double alpha;\n\n  TVM_DECLARE_ATTRS(LeakyReluAttrs, \"relay.attrs.LeakyReluAttrs\") {\n    TVM_ATTR_FIELD(alpha).set_lower_bound(0.0).set_default(0.25).describe(\n        \"Slope coefficient for the negative half axis.\");\n  }\n};\n\n/*! \\brief Attributes for prelu operator */\nstruct PReluAttrs : public tvm::AttrsNode<PReluAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(PReluAttrs, \"relay.attrs.PReluAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(1).describe(\n        \"Specify which shape axis the channel is specified.\");\n  }\n};\n\n/*! \\brief Attributes used in dropout operator */\nstruct DropoutAttrs : public tvm::AttrsNode<DropoutAttrs> {\n  double rate;\n  TVM_DECLARE_ATTRS(DropoutAttrs, \"relay.attrs.DropoutAttrs\") {\n    TVM_ATTR_FIELD(rate)\n        .describe(\"Fraction of the input that gets dropped out during training time\")\n        .set_default(0.5);\n  }\n};  // struct DropoutAttrs\n\n/*! \\brief Attributes used in batch_norm operator */\nstruct BatchNormAttrs : public tvm::AttrsNode<BatchNormAttrs> {\n  int axis;\n  double epsilon;\n  bool center;\n  bool scale;\n\n  TVM_DECLARE_ATTRS(BatchNormAttrs, \"relay.attrs.BatchNormAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\"Specify which shape axis denotes the channel.\").set_default(1);\n    TVM_ATTR_FIELD(epsilon)\n        .describe(\"Small float added to variance to avoid dividing by zero\")\n        .set_default(1e-5);\n    TVM_ATTR_FIELD(center)\n        .describe(\"If True, add offset of beta to normalized tensor. If False, beta is ignored\")\n        .set_default(true);\n    TVM_ATTR_FIELD(scale)\n        .describe(\n            \"If True, multiply by gamma. If False, gamma is not used. \"\n            \"When the next layer is piecewise linear (also, e.g., nn.relu), \"\n            \"this can be disabled since the scaling will be done by the next layer.\")\n        .set_default(true);\n  }\n};  // struct BatchNormAttrs\n\n/*! \\brief Attributes used in instance_norm operator */\nstruct InstanceNormAttrs : public tvm::AttrsNode<InstanceNormAttrs> {\n  int axis;\n  double epsilon;\n  bool center;\n  bool scale;\n\n  TVM_DECLARE_ATTRS(InstanceNormAttrs, \"relay.attrs.InstanceNormAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\"Specify which shape axis denotes the channel.\").set_default(1);\n    TVM_ATTR_FIELD(epsilon)\n        .describe(\"Small float added to variance to avoid dividing by zero\")\n        .set_default(1e-5);\n    TVM_ATTR_FIELD(center).set_default(true).describe(\n        \"If true, add offset of beta to normalized tensor; \"\n        \"otherwise, beta is ignored.\");\n    TVM_ATTR_FIELD(scale).set_default(true).describe(\n        \"If true, multiply by gamma; otherwise, gamma is ignored.\");\n  }\n};  // struct InstanceNormAttrs\n\n/*! \\brief Attributes used in layer_norm operator */\nstruct LayerNormAttrs : public tvm::AttrsNode<LayerNormAttrs> {\n  int axis;\n  double epsilon;\n  bool center;\n  bool scale;\n\n  TVM_DECLARE_ATTRS(LayerNormAttrs, \"relay.attrs.LayerNormAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(-1).describe(\"Specify which shape axis denotes the channel.\");\n    TVM_ATTR_FIELD(epsilon).set_default(1e-5).describe(\n        \"Small float added to variance to avoid dividing by zero\");\n    TVM_ATTR_FIELD(center).set_default(true).describe(\n        \"If true, add offset of beta to normalized tensor; \"\n        \"otherwise, beta is ignored.\");\n    TVM_ATTR_FIELD(scale).set_default(true).describe(\n        \"If true, multiply by gamma; otherwise, gamma is ignored.\");\n  }\n};  // struct LayerNormAttrs\n\n/*! \\brief Attributes used in group_norm operator */\nstruct GroupNormAttrs : public tvm::AttrsNode<GroupNormAttrs> {\n  int num_groups;\n  int axis;\n  double epsilon;\n  bool center;\n  bool scale;\n\n  TVM_DECLARE_ATTRS(GroupNormAttrs, \"relay.attrs.GroupNormAttrs\") {\n    TVM_ATTR_FIELD(num_groups)\n        .set_default(0)\n        .describe(\"Specify number of groups to separate the channels into.\");\n    TVM_ATTR_FIELD(axis).set_default(1).describe(\"Specify which shape axis denotes the channel.\");\n    TVM_ATTR_FIELD(epsilon).set_default(1e-5).describe(\n        \"Small float added to variance to avoid dividing by zero\");\n    TVM_ATTR_FIELD(center).set_default(true).describe(\n        \"If true, add offset of beta to normalized tensor; \"\n        \"otherwise, beta is ignored.\");\n    TVM_ATTR_FIELD(scale).set_default(true).describe(\n        \"If true, multiply by gamma; otherwise, gamma is ignored.\");\n  }\n};  // struct GroupNormAttrs\n\n/*! \\brief Attributes for LRN operator */\nstruct LRNAttrs : public tvm::AttrsNode<LRNAttrs> {\n  int size;\n  int axis;\n  double bias;\n  double alpha;\n  double beta;\n\n  TVM_DECLARE_ATTRS(LRNAttrs, \"relay.attrs.LRNAttrs\") {\n    TVM_ATTR_FIELD(size).set_default(5).describe(\n        \"The size of the local region to be considered for normalization.\");\n    TVM_ATTR_FIELD(axis).set_default(1).describe(\"Axis of input data layout channel.\");\n    TVM_ATTR_FIELD(bias).set_default(2).describe(\"The offset parameter to avoid division by 0.\");\n    TVM_ATTR_FIELD(alpha).set_default(0.0001).describe(\"The scaling parameter.\");\n    TVM_ATTR_FIELD(beta).set_default(0.75).describe(\"The exponent parameter.\");\n  }\n};\n\n/*! \\brief Attributes for L2Normalize operator */\nstruct L2NormalizeAttrs : public tvm::AttrsNode<L2NormalizeAttrs> {\n  double eps;\n  Array<Integer> axis;\n\n  TVM_DECLARE_ATTRS(L2NormalizeAttrs, \"relay.attrs.L2NormalizeAttrs\") {\n    TVM_ATTR_FIELD(eps).describe(\"A lower bound value for the norm, to avoid division by 0.\");\n    TVM_ATTR_FIELD(axis).describe(\"Axis over the normalization applied.\");\n  }\n};\n\n/*! \\brief Attributes for DeformableConv2D operator */\nstruct DeformableConv2DAttrs : public tvm::AttrsNode<DeformableConv2DAttrs> {\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  int deformable_groups;\n  int groups;\n  IndexExpr channels;\n  Array<IndexExpr> kernel_size;\n  std::string data_layout;\n  std::string kernel_layout;\n  std::string out_layout;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(DeformableConv2DAttrs, \"relay.attrs.DeformableConv2DAttrs\") {\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the strides of the convolution.\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0}))\n        .describe(\n            \"If padding is non-zero, then the input is implicitly zero-padded\"\n            \"Padding support both symmetric and asymmetric as\"\n            \"one int : same padding used on all sides\"\n            \"two int : bottom, right will use same padding as top, left\"\n            \"four int : padding width in the order of (top, left, bottom, right)\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"Specifies the dilation rate to use for dilated convolution.\");\n    TVM_ATTR_FIELD(deformable_groups)\n        .set_default(1)\n        .describe(\n            \"Controls the connections between inputs and offsets.\"\n            \"Input channels are partitioned into multiple deformable groups. Offsets\"\n            \"are shared across input channels in the same deformable group.\");\n    TVM_ATTR_FIELD(groups).set_default(1).describe(\n        \"Controls the connections between inputs and outputs.\"\n        \"At groups=1, all inputs are convolved to all outputs.\"\n        \"At groups=2, the operation becomes equivalent to having two convolution\"\n        \"layers side by side, each seeing half the input channels, and producing\"\n        \"half the output channels, and both subsequently concatenated.\");\n    TVM_ATTR_FIELD(channels)\n        .describe(\n            \"The number of output channels in the convolution.\"\n            \" If it is not set, inferred by shape of the weight.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Specifies the dimensions of the convolution window.\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(data_layout)\n        .set_default(\"NCHW\")\n        .describe(\n            \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Convolution is applied on the 'H' and\"\n            \"'W' dimensions.\");\n    TVM_ATTR_FIELD(kernel_layout)\n        .set_default(\"OIHW\")\n        .describe(\n            \"Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc.\"\n            \"'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width\"\n            \"dimensions respectively.\");\n    TVM_ATTR_FIELD(out_layout)\n        .set_default(\"\")\n        .describe(\n            \"Dimension ordering of output. Can be 'NCHW', 'NHWC', etc.\"\n            \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n            \"dimensions respectively. Default to be same as input layout.\");\n\n    // use 0 bits to indicate none.\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attributes used in subpixel operators */\nstruct SubPixelAttrs : public tvm::AttrsNode<SubPixelAttrs> {\n  int block_size;\n  std::string layout;\n  std::string mode;\n\n  TVM_DECLARE_ATTRS(SubPixelAttrs, \"relay.attrs.SubPixelAttrs\") {\n    TVM_ATTR_FIELD(block_size)\n        .describe(\"The size of subpixel blocks to compose or decompose.\")\n        .set_default(1);\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively.\");\n    TVM_ATTR_FIELD(mode).set_default(\"DCR\").describe(\n        \"Indicates order in which channels are accessed. Must be one of\"\n        \"DCR or CDR.\");\n  }\n};  // struct SubPixelAttrs\n\n/*! \\brief Attributes used in correlation operators */\nstruct CorrelationAttrs : public tvm::AttrsNode<CorrelationAttrs> {\n  int kernel_size;\n  int max_displacement;\n  int stride1;\n  int stride2;\n  Array<IndexExpr> padding;\n  bool is_multiply;\n  String layout;\n\n  TVM_DECLARE_ATTRS(CorrelationAttrs, \"relay.attrs.CorrelationAttrs\") {\n    TVM_ATTR_FIELD(kernel_size)\n        .describe(\"Kernel size for correlation, must be an odd number.\")\n        .set_default(1);\n    TVM_ATTR_FIELD(max_displacement).describe(\"Max displacement of Correlation.\").set_default(1);\n    TVM_ATTR_FIELD(stride1).describe(\"Stride for data1.\").set_default(1);\n    TVM_ATTR_FIELD(stride2).describe(\"Stride for data2.\").set_default(1);\n    TVM_ATTR_FIELD(padding)\n        .describe(\"Padding for data1 and data2.\")\n        .set_default(Array<IndexExpr>{0, 0});\n    TVM_ATTR_FIELD(is_multiply)\n        .describe(\"Operation type is either multiplication or substraction.\")\n        .set_default(true);\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively.\");\n  }\n};  // struct CorrelationAttrs\n\n/*! \\brief Attributes used in SpaceToBatchND operator */\nstruct SpaceToBatchNDAttrs : public tvm::AttrsNode<SpaceToBatchNDAttrs> {\n  Array<Integer> block_shape;\n  Array<Array<IndexExpr>> paddings;\n  double pad_value;\n\n  TVM_DECLARE_ATTRS(SpaceToBatchNDAttrs, \"relay.attrs.SpaceToBatchNDAttrs\") {\n    TVM_ATTR_FIELD(block_shape)\n        .set_default(Array<Integer>({1, 1}))\n        .describe(\"1-D containing block size for each spatial dimension.\");\n    TVM_ATTR_FIELD(paddings).describe(\"2-D containing paddings for each spatial dimension.\");\n    TVM_ATTR_FIELD(pad_value).set_default(0.0).describe(\"The value used for padding.\");\n  }\n};  // struct SpaceToBatchNDAttrs\n\n/*! \\brief Attributes used in BatchToSpaceND operator */\nstruct BatchToSpaceNDAttrs : public tvm::AttrsNode<BatchToSpaceNDAttrs> {\n  Array<Integer> block_shape;\n  Array<Array<IndexExpr>> crops;\n\n  TVM_DECLARE_ATTRS(BatchToSpaceNDAttrs, \"relay.attrs.BatchToSpaceNDAttrs\") {\n    TVM_ATTR_FIELD(block_shape)\n        .set_default(Array<Integer>({1, 1}))\n        .describe(\"1-D containing block size for each spatial dimension.\");\n    TVM_ATTR_FIELD(crops).describe(\"2-D containing amount to crop from spatial dimension.\");\n  }\n};  // struct BatchToSpaceNDAttrs\n\n/*! \\brief Attributes used in NLLLoss operator */\nstruct NLLLossAttrs : public tvm::AttrsNode<NLLLossAttrs> {\n  std::string reduction;\n  int ignore_index;\n\n  TVM_DECLARE_ATTRS(NLLLossAttrs, \"relay.attrs.NLLLossAttrs\") {\n    TVM_ATTR_FIELD(reduction).set_default(\"mean\").describe(\n        \"The reduction method to apply to the output. Can be\"\n        \"'none', 'mean' or 'sum'.\");\n    TVM_ATTR_FIELD(ignore_index).describe(\"The target value to ignore.\");\n  }\n};  // struct NLLLossAttrs\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_NN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/on_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/on_device.h\n * \\brief Attribute for the \"on_device\" annotation (ie operator).\n */\n#ifndef TVM_RELAY_ATTRS_ON_DEVICE_H_\n#define TVM_RELAY_ATTRS_ON_DEVICE_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/target/virtual_device.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Attributes for the \"on_device\" annotation (ie operator).\n *\n * The Relay call:\n * \\code\n *   on_device(sub_expr, virtual_device=S)\n * \\endcode\n * constrains \\p sub_expr to execute and store its result on the \\p VirtualDevice \\p S.\n * However the annotation itself may appear in an expression to be executed and stored on a\n * different \\p VirtualDevice. If so the compiler will automatically insert a \"device_copy\" call to\n * mediate the transition between \\p VirtualDevices.\n *\n * E.g.: Assuming %x and %y reside on the GPU and %z on the CPU then:\n * \\code\n *   multiply(on_device(add(%x, %y), virtual_device=GPU), %z)\n * \\endcode\n * indicates the \\p add should execute on the GPU but the \\p multiply should execute on the CPU.\n * The compiler will rewrite this to:\n * \\code\n *   multiply(device_copy(add(%x, %y), src_virtual_device=GPU, dst_virtual_device=CPU), %z)\n * \\endcode\n *\n * The \\p constraint_body (default true) and \\p constraint_result (default false) fields can be\n * used by passes for finer-grained control over how the \\p VirtualDevice constraint should be\n * applied.\n */\nstruct OnDeviceAttrs : public tvm::AttrsNode<OnDeviceAttrs> {\n  /*!\n   * \\brief The \\p VirtualDevice to constraint to apply to the body, result, or both body and result\n   * of the \"on_device\" call.\n   */\n  VirtualDevice virtual_device = VirtualDevice::FullyUnconstrained();\n\n  /*!\n   * \\brief If false (the default), the result of the \"on_device\" call is not constrained to be\n   * \\p virtual_device.\n   */\n  bool constrain_result = false;\n\n  /*!\n   * \\brief If true (the default), the body of the \"on_device\" call is constrained to be \\p\n   * virtual_device.\n   */\n  bool constrain_body = true;\n\n  /*!\n   * \\brief Returns true if both the body and result are constrained.\n   */\n  bool is_fixed() const { return constrain_result && constrain_body; }\n\n  /*!\n   * \\brief Returns true only the body is constrained (the 'normal' case).\n   */\n  bool is_normal() const { return !constrain_result && constrain_body; }\n\n  TVM_DECLARE_ATTRS(OnDeviceAttrs, \"relay.attrs.OnDeviceAttrs\") {\n    TVM_ATTR_FIELD(virtual_device)\n        .describe(\"The (virtual) device to constrain to.\")\n        .set_default(VirtualDevice::FullyUnconstrained());\n    TVM_ATTR_FIELD(constrain_result)\n        .describe(\"Whether the constraint applies to the overall expression\")\n        .set_default(false);\n    TVM_ATTR_FIELD(constrain_body)\n        .describe(\"Whether the constraint applies to the body sub-expression.\")\n        .set_default(true);\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_ATTRS_ON_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/random.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/vision.h\n * \\brief Auxiliary attributes for random operators.\n */\n#ifndef TVM_RELAY_ATTRS_RANDOM_H_\n#define TVM_RELAY_ATTRS_RANDOM_H_\n\n#include <tvm/ir/attrs.h>\n\nnamespace tvm {\nnamespace relay {\n\nstruct ThreefryGenerateAttrs : public tvm::AttrsNode<ThreefryGenerateAttrs> {\n  Array<Integer> out_shape;\n\n  TVM_DECLARE_ATTRS(ThreefryGenerateAttrs, \"relay.attrs.ThreefryGenerateAttrs\") {\n    TVM_ATTR_FIELD(out_shape).describe(\"Shape of random numbers to generate\");\n  }\n};\n\nstruct UniformAttrs : public tvm::AttrsNode<UniformAttrs> {\n  Array<Integer> out_shape;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(UniformAttrs, \"relay.attrs.UniformAttrs\") {\n    TVM_ATTR_FIELD(out_shape).describe(\"Shape of random numbers to generate\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Data type of the generated numbers\");\n  }\n};\n\nstruct NormalAttrs : public tvm::AttrsNode<NormalAttrs> {\n  Array<Integer> out_shape;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(NormalAttrs, \"relay.attrs.NormalAttrs\") {\n    TVM_ATTR_FIELD(out_shape).describe(\"Shape of random numbers to generate\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Data type of the generated numbers\");\n  }\n};\n\nstruct MultinomialAttrs : public tvm::AttrsNode<MultinomialAttrs> {\n  Integer num_samples;\n\n  TVM_DECLARE_ATTRS(MultinomialAttrs, \"relay.attrs.MultinomialAttrs\") {\n    TVM_ATTR_FIELD(num_samples)\n        .set_default(1)\n        .describe(\"Number of samples to draw from the distribution.\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_RANDOM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/reduce.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/reduce.h\n * \\brief Auxiliary attributes for reduce operators.\n */\n#ifndef TVM_RELAY_ATTRS_REDUCE_H_\n#define TVM_RELAY_ATTRS_REDUCE_H_\n\n#include <tvm/ir/attrs.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes for Reduce operators */\nstruct ReduceAttrs : public tvm::AttrsNode<ReduceAttrs> {\n  Array<Integer> axis;\n  bool keepdims;\n  bool exclude;\n\n  TVM_DECLARE_ATTRS(ReduceAttrs, \"relay.attrs.ReduceAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Array<Integer>>())\n        .describe(R\"code(The axis or axes along which to perform the reduction.\n\n      The default, `axis=()`, will compute over all elements into a\n      scalar array with shape `(1,)`.\n\n      If `axis` is int, a reduction is performed on a particular axis.\n\n      If `axis` is a tuple of ints, a reduction is performed on all the axes\n      specified in the tuple.\n\n      If `exclude` is true, reduction will be performed on the axes that are\n      NOT in axis instead.)code\");\n\n    TVM_ATTR_FIELD(keepdims).set_default(false).describe(\n        \"If this is set to `True`, the reduced axes are left \"\n        \"in the result as dimension with size one.\");\n    TVM_ATTR_FIELD(exclude).set_default(false).describe(\n        \"Whether to perform reduction on axis that are NOT in axis instead.\");\n  }\n};\n\n/*! \\brief Attributes for Reduce operators which reduce by finding a single element. E.g. argmin */\nstruct ArgReduceAttrs : public tvm::AttrsNode<ArgReduceAttrs> {\n  Array<Integer> axis;\n  bool keepdims;\n  bool select_last_index;\n  bool exclude;\n\n  TVM_DECLARE_ATTRS(ArgReduceAttrs, \"relay.attrs.ArgReduceAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Array<Integer>>())\n        .describe(R\"code(The axis or axes along which to perform the reduction.\n\n      The default, `axis=()`, will compute over all elements into a\n      scalar array with shape `(1,)`.\n\n      If `axis` is int, a reduction is performed on a particular axis.\n\n      If `axis` is a tuple of ints, a reduction is performed on all the axes\n      specified in the tuple.\n\n      If `exclude` is true, reduction will be performed on the axes that are\n      NOT in axis instead.)code\");\n\n    TVM_ATTR_FIELD(keepdims).set_default(false).describe(\n        \"If this is set to `True`, the reduced axes are left \"\n        \"in the result as dimension with size one.\");\n    TVM_ATTR_FIELD(select_last_index)\n        .set_default(false)\n        .describe(\n            \"Whether to select the last index if the target element appears multiple times, else \"\n            \"select the first index which the target element appears\");\n    TVM_ATTR_FIELD(exclude).set_default(false).describe(\n        \"Whether to perform reduction on axis that are NOT in axis instead.\");\n  }\n};\n\nstruct VarianceAttrs : public tvm::AttrsNode<VarianceAttrs> {\n  Array<Integer> axis;\n  bool keepdims;\n  bool exclude;\n  bool unbiased;\n\n  TVM_DECLARE_ATTRS(VarianceAttrs, \"relay.attrs.VarianceAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Array<Integer>>())\n        .describe(R\"code(The axis or axes along which to perform the reduction.\n\n      The default, `axis=()`, will compute over all elements into a\n      scalar array with shape `(1,)`.\n\n      If `axis` is int, a reduction is performed on a particular axis.\n\n      If `axis` is a tuple of ints, a reduction is performed on all the axes\n      specified in the tuple.\n\n      If `exclude` is true, reduction will be performed on the axes that are\n      NOT in axis instead.)code\");\n\n    TVM_ATTR_FIELD(keepdims).set_default(false).describe(\n        \"If this is set to `True`, the reduced axes are left \"\n        \"in the result as dimension with size one.\");\n    TVM_ATTR_FIELD(exclude).set_default(false).describe(\n        \"Whether to perform reduction on axis that are NOT in axis instead.\");\n    TVM_ATTR_FIELD(unbiased).set_default(false).describe(\"Whether to use the unbiased estimation.\");\n  }\n};\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_REDUCE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/transform.h\n * \\brief Transform operators.\n */\n#ifndef TVM_RELAY_ATTRS_TRANSFORM_H_\n#define TVM_RELAY_ATTRS_TRANSFORM_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n#include <tvm/relay/expr.h>\n#include <tvm/tir/index_map.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes used for the sliding_window operator */\nstruct SlidingWindowAttrs : public tvm::AttrsNode<SlidingWindowAttrs> {\n  int axis;\n  Array<Integer> window_shape;\n  Array<Integer> strides;\n  TVM_DECLARE_ATTRS(SlidingWindowAttrs, \"relay.attrs.SlidingWindowAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\n        \"What axis the sliding window begin forming over.\"\n        \"Window will be slid over this axis and all following axes.\"\n        \"The axis value determines the window shape (and thus, the\"\n        \"number of strides):\"\n        \"window shape and strides must both be of length\"\n        \"`data.ndim-axis`.\");\n    TVM_ATTR_FIELD(window_shape)\n        .describe(\n            \"The window shape to form over the input.\"\n            \"Window shape must be of length `data.ndim-axis`.\");\n    TVM_ATTR_FIELD(strides).describe(\n        \"How to stride the window along each dimension.\"\n        \"Strides must be of length `data.ndim-axis`.\");\n  }\n};  // struct SlidingWindowAttrs\n\n/*! \\brief data type cast */\nstruct CastAttrs : public tvm::AttrsNode<CastAttrs> {\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(CastAttrs, \"relay.attrs.CastAttrs\") {\n    TVM_ATTR_FIELD(dtype).describe(\"Target data type\");\n  }\n};  // struct CastAttrs.\n\n/*! \\brief Attributes used in expand_dims operators */\nstruct ExpandDimsAttrs : public tvm::AttrsNode<ExpandDimsAttrs> {\n  int axis;\n  int num_newaxis;\n\n  TVM_DECLARE_ATTRS(ExpandDimsAttrs, \"relay.attrs.ExpandDimsAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\n        \"The axis at which the input array is expanded.\"\n        \"Should lie in range `[-data.ndim - 1, data.ndim]`.\"\n        \"If `axis < 0`, it is the first axis inserted;\"\n        \"If `axis >= 0`, it is the last axis inserted in Python's negative indexing.\");\n    TVM_ATTR_FIELD(num_newaxis)\n        .describe(\"Number of axes to be inserted. Should be >= 0.\")\n        .set_lower_bound(0)\n        .set_default(1);\n  }\n};  // struct ExpandDimsAttrs\n\n/*! \\brief Attributes used in dynamic expand_dims operators */\nstruct DynExpandDimsAttrs : public tvm::AttrsNode<DynExpandDimsAttrs> {\n  int num_newaxis;\n\n  TVM_DECLARE_ATTRS(DynExpandDimsAttrs, \"relay.attrs.DynExpandDimsAttrs\") {\n    TVM_ATTR_FIELD(num_newaxis)\n        .describe(\"Number of axes to be inserted. Should be >= 0.\")\n        .set_lower_bound(0)\n        .set_default(1);\n  }\n};  // struct ExpandDimsAttrs\n\n/*! \\brief Attributes used in concatenate operators */\nstruct ConcatenateAttrs : public tvm::AttrsNode<ConcatenateAttrs> {\n  int axis;\n  TVM_DECLARE_ATTRS(ConcatenateAttrs, \"relay.attrs.ConcatenateAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The axis at which the input arrays are concatenated.\"\n            \"Should lie in range `[-ndim, ndim)`.\")\n        .set_default(0);\n  }\n};  // struct ConcatenateAttrs\n\n/*! \\brief Attributes used in transpose operators */\nstruct TransposeAttrs : public tvm::AttrsNode<TransposeAttrs> {\n  Array<Integer> axes;\n  TVM_DECLARE_ATTRS(TransposeAttrs, \"relay.attrs.TransposeAttrs\") {\n    TVM_ATTR_FIELD(axes).describe(\"The target axes order, reverse order if not specified.\");\n  }\n};  // struct TransposeAttrs\n\n/*! \\brief Attributes used in reshape operators */\nstruct ReshapeAttrs : public tvm::AttrsNode<ReshapeAttrs> {\n  Array<Integer> newshape;\n  bool allowzero;\n  TVM_DECLARE_ATTRS(ReshapeAttrs, \"relay.attrs.ReshapeAttrs\") {\n    TVM_ATTR_FIELD(newshape).describe(\n        \"The new shape. Should be compatible with the original shape.\");\n    TVM_ATTR_FIELD(allowzero).set_default(0).describe(\n        \"Whether to honor the value of zero in newshape.\");\n  }\n};  // struct ReshapeAttrs\n\n/*! \\brief Attributes used in MXNet-style reshape_like operators */\nstruct ReshapeLikeAttrs : public tvm::AttrsNode<ReshapeLikeAttrs> {\n  int lhs_begin;\n  Integer lhs_end;  // can be None\n  int rhs_begin;\n  Integer rhs_end;  // can be None\n  TVM_DECLARE_ATTRS(ReshapeLikeAttrs, \"relay.attrs.ReshapeLikeAttrs\") {\n    TVM_ATTR_FIELD(lhs_begin).set_default(0).describe(\n        \"The axis of the input where reshaping should begin.\");\n    TVM_ATTR_FIELD(lhs_end)\n        .set_default(NullValue<Integer>())\n        .describe(\"The axis of the input where reshaping should end, exclusive.\");\n    TVM_ATTR_FIELD(rhs_begin).set_default(0).describe(\n        \"The axis of the shape_like tensor to begin taking dimensions from.\");\n    TVM_ATTR_FIELD(rhs_end)\n        .set_default(NullValue<Integer>())\n        .describe(\"The axis of the shape_like tensor to end taking dimensions from, exclusive.\");\n  }\n};  // struct ReshapeLikeAttrs\n\nstruct ScatterAttrs : public tvm::AttrsNode<ScatterAttrs> {\n  Integer axis;\n\n  TVM_DECLARE_ATTRS(ScatterAttrs, \"relay.attrs.ScatterAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(0).describe(\"The axis over which to select values.\");\n  }\n};\n\nstruct ScatterAddAttrs : public tvm::AttrsNode<ScatterAddAttrs> {\n  Integer axis;\n\n  TVM_DECLARE_ATTRS(ScatterAddAttrs, \"relay.attrs.ScatterAddAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(0).describe(\"The axis over which to select values.\");\n  }\n};\n\nstruct ScatterNDAttrs : public tvm::AttrsNode<ScatterNDAttrs> {\n  String mode;\n\n  TVM_DECLARE_ATTRS(ScatterNDAttrs, \"relay.attrs.ScatterNDAttrs\") {\n    TVM_ATTR_FIELD(mode).describe(\n        \"Accumulation mode of the scatter, either \\\"update\\\" or \\\"add\\\".\");\n  }\n};\n\nstruct GatherAttrs : public tvm::AttrsNode<GatherAttrs> {\n  Integer axis;\n\n  TVM_DECLARE_ATTRS(GatherAttrs, \"relay.attrs.GatherAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Integer>())\n        .describe(\"The axis over which to select values.\");\n  }\n};\n\nstruct GatherNDAttrs : public tvm::AttrsNode<GatherNDAttrs> {\n  Integer batch_dims;\n  Optional<Integer> index_rank;\n\n  TVM_DECLARE_ATTRS(GatherNDAttrs, \"relay.attrs.GatherNDAttrs\") {\n    TVM_ATTR_FIELD(batch_dims).set_default(Integer(0)).describe(\"The number of batch dimensions.\");\n    TVM_ATTR_FIELD(index_rank)\n        .set_default(NullValue<Integer>())\n        .describe(\n            \"The size of an indexing tuple, which is a fixed value. Only needed when the number of \"\n            \"indexting tuples is dynamic.\");\n  }\n};\n\nstruct TakeAttrs : public tvm::AttrsNode<TakeAttrs> {\n  Integer batch_dims;\n  Integer axis;\n  tvm::String mode;\n\n  TVM_DECLARE_ATTRS(TakeAttrs, \"relay.attrs.TakeAttrs\") {\n    TVM_ATTR_FIELD(batch_dims)\n        .set_default(0)\n        .describe(\"The batch_dims over which to select values.\");\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Integer>())\n        .describe(\"The axis over which to select values.\");\n    TVM_ATTR_FIELD(mode).set_default(\"clip\").describe(\n        \"Specify how out-of-bound indices will behave.\"\n        \"clip - clip to the range (default)\"\n        \"wrap - wrap around the indices\"\n        \"fast - no clip or wrap around (user must make sure indices are in-bound)\");\n  }\n};\n\n/*! \\brief Attributes that specify a tensor */\nstruct InitOpAttrs : public tvm::AttrsNode<InitOpAttrs> {\n  Optional<Array<Integer>> shape;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(InitOpAttrs, \"relay.attrs.InitOpAttrs\") {\n    TVM_ATTR_FIELD(shape).describe(\"Target shape.\");\n    TVM_ATTR_FIELD(dtype).describe(\"Target data type.\").set_default(NullValue<DataType>());\n  }\n};  // struct InitOpAttrs\n\n/*! \\brief Attributes used in arange operators */\nstruct ArangeAttrs : public tvm::AttrsNode<ArangeAttrs> {\n  Expr start;\n  Expr stop;\n  Expr step;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(ArangeAttrs, \"relay.attrs.ArangeAttrs\") {\n    TVM_ATTR_FIELD(start).describe(\"Start of interval. The interval includes this value.\");\n    TVM_ATTR_FIELD(stop).describe(\"Stop of interval. The interval does not include this value.\");\n    TVM_ATTR_FIELD(step).describe(\"Spacing between values.\");\n    TVM_ATTR_FIELD(dtype).describe(\"Target data type.\");\n  }\n};  // struct ArangeAttrs\n\n/*! \\brief Attributes used in meshgrid operators */\nstruct MeshgridAttrs : public tvm::AttrsNode<MeshgridAttrs> {\n  std::string indexing;\n\n  TVM_DECLARE_ATTRS(MeshgridAttrs, \"relay.attrs.MeshgridAttrs\") {\n    TVM_ATTR_FIELD(indexing)\n        .describe(\n            \"Indexing mode, either \\\"ij\\\" for matrix or \\\"xy\\\" for cartesian in which first two\"\n            \"dimensions are swapped.\")\n        .set_default(\"ij\");\n  }\n};  // struct MeshgridAttrs\n\n/*! \\brief Attributes used in stack operators */\nstruct StackAttrs : public tvm::AttrsNode<StackAttrs> {\n  Integer axis;\n  TVM_DECLARE_ATTRS(StackAttrs, \"relay.attrs.StackAttrs\") {\n    TVM_ATTR_FIELD(axis).set_default(0).describe(\n        \"The axis in the result array along which the input arrays are stacked.\");\n  }\n};  // struct StackAttrs\n\n/*! \\brief Attributes used in repeat operators */\nstruct RepeatAttrs : public tvm::AttrsNode<RepeatAttrs> {\n  Integer repeats;\n  Integer axis;\n  TVM_DECLARE_ATTRS(RepeatAttrs, \"relay.attrs.RepeatAttrs\") {\n    TVM_ATTR_FIELD(repeats).describe(\"The number of repetitions for each element.\");\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Integer>())\n        .describe(\" The axis along which to repeat values.\");\n  }\n};  // struct RepeatAttrs\n\n/*! \\brief Attributes used in tile operators */\nstruct TileAttrs : public tvm::AttrsNode<TileAttrs> {\n  Array<Integer> reps;\n  TVM_DECLARE_ATTRS(TileAttrs, \"relay.attrs.TileAttrs\") {\n    TVM_ATTR_FIELD(reps).describe(\n        \"The number of times for repeating the tensor a.\"\n        \"Each dim sizeof reps must be a positive integer.\");\n  }\n};  // struct TileAttrs\n\n/*! \\brief Attributes used in reverse operators */\nstruct ReverseAttrs : public tvm::AttrsNode<ReverseAttrs> {\n  Integer axis;\n  TVM_DECLARE_ATTRS(ReverseAttrs, \"relay.attrs.ReverseAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .set_default(NullValue<Integer>())\n        .describe(\"The axis along which to reverse elements.\");\n  }\n};  // struct ReverseAttrs\n\n/*! \\brief Attributes used in reverse_sequence operators */\nstruct ReverseSequenceAttrs : public tvm::AttrsNode<ReverseSequenceAttrs> {\n  Integer seq_axis;\n  Integer batch_axis;\n\n  TVM_DECLARE_ATTRS(ReverseSequenceAttrs, \"relay.attrs.ReverseSequenceAttrs\") {\n    TVM_ATTR_FIELD(seq_axis).set_default(1).describe(\n        \"The seq axis along which to reverse elements.\");\n    TVM_ATTR_FIELD(batch_axis)\n        .set_default(0)\n        .describe(\"The batch axis along which to slice the tensor.\");\n  }\n};  // struct ReverseSequenceAttrs\n\n/*! \\brief Attributes used in squeeze operators */\nstruct SqueezeAttrs : public tvm::AttrsNode<SqueezeAttrs> {\n  // use axis to make the name numpy compatible.\n  Array<Integer> axis;\n\n  TVM_DECLARE_ATTRS(SqueezeAttrs, \"relay.attrs.SqueezeAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The axis to squeeze in the input tensor.\"\n            \"If `axis = None`, all axis of dimension 1 get squeezed;\"\n            \"Else, the dimension in axes get squeezed.\"\n            \"It is an error if an axis does not has dimension 1.\")\n        .set_default(NullValue<Array<Integer>>());\n  }\n};  // struct SqueezeAttrs\n\nstruct SplitAttrs : public tvm::AttrsNode<SplitAttrs> {\n  ObjectRef indices_or_sections;\n  int axis;\n\n  TVM_DECLARE_ATTRS(SplitAttrs, \"relay.attrs.SplitAttrs\") {\n    TVM_ATTR_FIELD(indices_or_sections)\n        .describe(\n            \"Indices or sections to split into. Accepts an int or a tuple\"\n            \"If indices_or_sections is an integer, the input will be divided equally\"\n            \"along given axis. If such a split is not possible, an error is raised.\"\n            \"If indices_or_sections is a tuple of sorted integers,\"\n            \"the entries indicate where along axis the array is split.\");\n    TVM_ATTR_FIELD(axis).set_default(0).describe(\"the axis to be splitted.\");\n  }\n};\n\n/*! \\brief Attributes for StridedSlice operator */\nstruct StridedSliceAttrs : public tvm::AttrsNode<StridedSliceAttrs> {\n  Optional<Array<Integer>> begin;\n  Optional<Array<Integer>> end;\n  Optional<Array<Integer>> strides;\n  tvm::String slice_mode;\n  Optional<Array<Integer>> axes;\n\n  TVM_DECLARE_ATTRS(StridedSliceAttrs, \"relay.attrs.StridedSliceAttrs\") {\n    TVM_ATTR_FIELD(begin).describe(\"Indices for begin of slice, begin index is also inclusive\");\n    TVM_ATTR_FIELD(end).describe(\"Indices for end of slice, end index is exclusive\");\n    TVM_ATTR_FIELD(strides).describe(\n        \"Stride values of the slice, a stride can be negative, which causes a reverse slice.\");\n    TVM_ATTR_FIELD(slice_mode)\n        .set_default(\"end\")\n        .describe(\n            \"The slice mode [end, size].\"\n            \"end - The default slice mode, ending indices for the slice.\"\n            \"size - The input strides will be ignored, input end in this mode indicates the size\"\n            \"of a slice starting at the location specified by begin. If end[i] is -1,\"\n            \"all remaining elements in that dimension are included in the slice\");\n    TVM_ATTR_FIELD(axes).describe(\n        \"Axes along which slicing is applied. When it is specified, the length of begin, end, \"\n        \"strides, and axes must be equal.\");\n  }\n};\n\nstruct SliceLikeAttrs : public tvm::AttrsNode<SliceLikeAttrs> {\n  Array<Integer> axes;\n\n  TVM_DECLARE_ATTRS(SliceLikeAttrs, \"relay.attrs.SliceLikeAttrs\") {\n    TVM_ATTR_FIELD(axes).describe(\n        \"List of axes on which input data will be sliced according to the \"\n        \"corresponding size of the second input. By default will slice \"\n        \"on all axes. Negative axes mean counting in reverse.\");\n  }\n};\n\n/*! \\brief Attributes for Clip operator */\nstruct ClipAttrs : public tvm::AttrsNode<ClipAttrs> {\n  double a_min;\n  double a_max;\n\n  TVM_DECLARE_ATTRS(ClipAttrs, \"relay.attrs.ClipAttrs\") {\n    TVM_ATTR_FIELD(a_min).describe(\"The minimum clip value.\");\n    TVM_ATTR_FIELD(a_max).describe(\"The maximum clip value.\");\n  }\n};\n\n/*! \\brief Attributes for FixedPointMultiply operator */\nstruct FixedPointMultiplyAttrs : public tvm::AttrsNode<FixedPointMultiplyAttrs> {\n  int32_t multiplier;\n  int32_t shift;\n\n  TVM_DECLARE_ATTRS(FixedPointMultiplyAttrs, \"relay.attrs.FixedPointMultiplyAttrs\") {\n    TVM_ATTR_FIELD(multiplier)\n        .describe(\"Multiplier of a fixed floating point number described as multiplier*2^(shift)\");\n    TVM_ATTR_FIELD(shift).describe(\n        \"Shift of a fixed floating point number described as multiplier*2^(shift)\");\n  }\n};\n\n/*! \\brief Attributes for per channel/per axes FixedPointMultiply operator */\nstruct FixedPointMultiplyPerAxisAttrs : public tvm::AttrsNode<FixedPointMultiplyPerAxisAttrs> {\n  bool is_lshift_required;\n  bool is_rshift_required;\n  Array<Integer> axes;\n\n  TVM_DECLARE_ATTRS(FixedPointMultiplyPerAxisAttrs, \"relay.attrs.FixedPointMultiplyPerAxisAttrs\") {\n    TVM_ATTR_FIELD(is_lshift_required)\n        .describe(\"Whether left shift is required in fixed point multiplication.\")\n        .set_default(false);\n    TVM_ATTR_FIELD(is_rshift_required)\n        .describe(\"Whether right shift is required in fixed point multiplication.\")\n        .set_default(false);\n    TVM_ATTR_FIELD(axes).describe(\"List of axes on which input data was quantized.\");\n  }\n};\n\n/*! \\brief Attributes for LayoutTransform operator */\nstruct LayoutTransformAttrs : public tvm::AttrsNode<LayoutTransformAttrs> {\n  std::string src_layout;\n  std::string dst_layout;\n\n  TVM_DECLARE_ATTRS(LayoutTransformAttrs, \"relay.attrs.LayoutTransformAttrs\") {\n    TVM_ATTR_FIELD(src_layout).describe(\"The source layout of the tensor. (e.g. NCHW)\");\n    TVM_ATTR_FIELD(dst_layout).describe(\"The destination layout of the tensor. (e.g. NCHW16c)\");\n  }\n};\n\n/*! \\brief Attributes for AutoSchedulerLayoutTransform operator */\nstruct AutoSchedulerLayoutTransformAttrs\n    : public tvm::AttrsNode<AutoSchedulerLayoutTransformAttrs> {\n  std::string src_layout;\n  std::string dst_layout;\n\n  TVM_DECLARE_ATTRS(AutoSchedulerLayoutTransformAttrs,\n                    \"relay.attrs.AutoSchedulerLayoutTransformAttrs\") {\n    TVM_ATTR_FIELD(src_layout).describe(\"The source layout of the tensor. (e.g. 1N32C112H112W)\");\n    TVM_ATTR_FIELD(dst_layout)\n        .describe(\"The destination layout of the tensor. (e.g. 1N2C112H112W16c)\");\n  }\n};\n\n/*! \\brief Attributes for MetaScheduleLayoutTransform operator */\nstruct MetaScheduleLayoutTransformAttrs : public tvm::AttrsNode<MetaScheduleLayoutTransformAttrs> {\n  tir::IndexMap index_map;\n\n  TVM_DECLARE_ATTRS(MetaScheduleLayoutTransformAttrs,\n                    \"relay.attrs.MetaScheduleLayoutTransformAttrs\") {\n    TVM_ATTR_FIELD(index_map).describe(\n        \"The order of the extents, for example, \"\n        \"let extents = [2, 3, 4], reorder = [0, 2, 1], and the shape of buffer A is (4, 6)\"\n        \"then A[i, j] will be first rewritten to \"\n        \"A[(6 * i + j) / 12, (6 * i + j) / 4 % 3 , (6 * i + j) % 4] according to the `extents`,\"\n        \"and then reordered to A[(6 * i + j) / 12, (6 * i + j) % 4 , (6 * i + j) / 4 % 3]\"\n        \"according to `reorder`\");\n  }\n};\n\n/*! \\brief Attributes for ShapeOf operator */\nstruct ShapeOfAttrs : public tvm::AttrsNode<ShapeOfAttrs> {\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(ShapeOfAttrs, \"relay.attrs.ShapeOfAttrs\") {\n    TVM_ATTR_FIELD(dtype).describe(\"Target data type\").set_default(NullValue<DataType>());\n  }\n};\n\nstruct SequenceMaskAttrs : public tvm::AttrsNode<SequenceMaskAttrs> {\n  double mask_value;\n  int axis;\n\n  TVM_DECLARE_ATTRS(SequenceMaskAttrs, \"relay.attrs.SequenceMaskAttrs\") {\n    TVM_ATTR_FIELD(mask_value).set_default(0).describe(\"The masking value.\");\n    TVM_ATTR_FIELD(axis).set_default(0).describe(\n        \"The axis of the length dimension. Can only be 0 or 1.\");\n  }\n};  // struct SequenceMaskAttrs.\n\n/*! \\brief Attributes used in sparse_to_dense operator */\nstruct SparseToDenseAttrs : public tvm::AttrsNode<SparseToDenseAttrs> {\n  Array<Integer> output_shape;\n\n  TVM_DECLARE_ATTRS(SparseToDenseAttrs, \"relay.attrs.SparseToDenseAttrs\") {\n    TVM_ATTR_FIELD(output_shape).describe(\"Shape of the dense output tensor\");\n  }\n};  // struct SparseToDenseAttrs\n\n/*! \\brief Attributes for ndarray_size operator */\nstruct NdarraySizeAttrs : public tvm::AttrsNode<NdarraySizeAttrs> {\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(NdarraySizeAttrs, \"relay.attrs.NdarraySizeAttrs\") {\n    TVM_ATTR_FIELD(dtype).describe(\"Target data type\").set_default(NullValue<DataType>());\n  }\n};\n\n/*! \\brief Attributes used in one-hot operator */\nstruct OneHotAttrs : public tvm::AttrsNode<OneHotAttrs> {\n  int depth;\n  int axis;\n  DataType dtype;\n\n  TVM_DECLARE_ATTRS(OneHotAttrs, \"relay.attrs.OneHotAttrs\") {\n    TVM_ATTR_FIELD(depth).set_default(1).describe(\"Depth of the one hot dimension.\");\n    TVM_ATTR_FIELD(axis).set_default(-1).describe(\"Axis to fill.\");\n    TVM_ATTR_FIELD(dtype).set_default(NullValue<DataType>()).describe(\"Output data type.\");\n  }\n};  // struct OneHotAttrs\n\n/*! \\brief Attributes used in matrix_set_diag operator */\nstruct MatrixSetDiagAttrs : public tvm::AttrsNode<MatrixSetDiagAttrs> {\n  int k1;\n  int k2;\n  bool super_diag_right_align;\n  bool sub_diag_right_align;\n\n  TVM_DECLARE_ATTRS(MatrixSetDiagAttrs, \"relay.attrs.MatrixSetDiagAttrs\") {\n    TVM_ATTR_FIELD(k1).set_default(0).describe(\"Lower limit (included) of the range of diagonals.\");\n    TVM_ATTR_FIELD(k2).set_default(0).describe(\"Upper limit (included) of the range of diagonals.\");\n    TVM_ATTR_FIELD(super_diag_right_align)\n        .set_default(true)\n        .describe(\"Bool, true iff super-diagonal is right aligned (left-padded).\");\n    TVM_ATTR_FIELD(sub_diag_right_align)\n        .set_default(false)\n        .describe(\"Bool, true iff sub-diagonal is right aligned (left-padded).\");\n  }\n};  // struct MatrixSetDiagAttrs\n\n/*! \\brief Attributes used in cumsum and cumprod operator */\nstruct ScanopAttrs : public tvm::AttrsNode<ScanopAttrs> {\n  Integer axis;\n  DataType dtype;\n  Bool exclusive = Bool(false);\n  TVM_DECLARE_ATTRS(ScanopAttrs, \"relay.attrs.ScanopAttrs\") {\n    TVM_ATTR_FIELD(axis).describe(\"The axis to operate over\").set_default(NullValue<Integer>());\n    TVM_ATTR_FIELD(dtype).describe(\"Output data type\").set_default(NullValue<DataType>());\n\n    // Default is 0 which is \"false\"\n    TVM_ATTR_FIELD(exclusive)\n        .describe(\"The first element is not included\")\n        .set_default(Bool(false));\n  }\n};  // struct ScanopAttrs\n\n/*! \\brief Attributes used in unique operator */\nstruct UniqueAttrs : public tvm::AttrsNode<UniqueAttrs> {\n  bool sorted;\n  bool return_counts;\n  TVM_DECLARE_ATTRS(UniqueAttrs, \"relay.attrs.UniqueAttrs\") {\n    TVM_ATTR_FIELD(sorted).describe(\"Whether the unique elements are sorted\").set_default(true);\n    TVM_ATTR_FIELD(return_counts)\n        .describe(\"Whether to return an additional tensor with counts of each unique elements\")\n        .set_default(false);\n  }\n};  // struct UniqueAttrs\n\n/*! \\brief Attributes used in einsum operator */\nstruct EinsumAttrs : public tvm::AttrsNode<EinsumAttrs> {\n  String equation;\n\n  TVM_DECLARE_ATTRS(EinsumAttrs, \"relay.attrs.EinsumAttrs\") {\n    TVM_ATTR_FIELD(equation).describe(\"The einsum expression string\");\n  }\n};  // struct EinsumAttrs\n\n/*! \\brief Attributes used in stft operator */\nstruct StftAttrs : public tvm::AttrsNode<StftAttrs> {\n  int n_fft;\n  int hop_length;\n  int win_length;\n  bool normalized;\n  bool onesided;\n\n  TVM_DECLARE_ATTRS(StftAttrs, \"relay.attrs.StftAttrs\") {\n    TVM_ATTR_FIELD(n_fft).set_default(-1).describe(\"The size of Fourier transform\");\n    TVM_ATTR_FIELD(hop_length)\n        .set_default(-1)\n        .describe(\"The distance between neighboring sliding window frames\");\n    TVM_ATTR_FIELD(win_length).set_default(-1).describe(\"The size of window frame and STFT filter\");\n    TVM_ATTR_FIELD(normalized)\n        .set_default(false)\n        .describe(\"Whether to return the normalized STFT results\");\n    TVM_ATTR_FIELD(onesided).set_default(true).describe(\n        \"Whether to return onesided result or fill with conjugate symmetry\");\n  }\n};  // struct StftAttrs\n\nstruct TriluAttrs : public tvm::AttrsNode<TriluAttrs> {\n  bool upper;\n\n  TVM_DECLARE_ATTRS(TriluAttrs, \"relay.attrs.TriluAttrs\") {\n    TVM_ATTR_FIELD(upper).set_default(true).describe(\n        \"Whether to keep the upper or lower half of the diagonal.\");\n  }\n};  // struct TriluAttrs\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/vision.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/vision.h\n * \\brief Auxiliary attributes for vision operators.\n */\n#ifndef TVM_RELAY_ATTRS_VISION_H_\n#define TVM_RELAY_ATTRS_VISION_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/relay/base.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Attributes used in multibox_prior operators */\nstruct MultiBoxPriorAttrs : public tvm::AttrsNode<MultiBoxPriorAttrs> {\n  Array<IndexExpr> sizes;\n  Array<IndexExpr> ratios;\n  Array<IndexExpr> steps;\n  Array<IndexExpr> offsets;\n  bool clip;\n\n  TVM_DECLARE_ATTRS(MultiBoxPriorAttrs, \"relay.attrs.MultiBoxPriorAttrs\") {\n    TVM_ATTR_FIELD(sizes)\n        .set_default(Array<IndexExpr>({static_cast<float>(1.0)}))\n        .describe(\"List of sizes of generated MultiBoxPriores.\");\n    TVM_ATTR_FIELD(ratios)\n        .set_default(Array<IndexExpr>({static_cast<float>(1.0)}))\n        .describe(\"List of aspect ratios of generated MultiBoxPriores.\");\n    TVM_ATTR_FIELD(steps)\n        .set_default(Array<IndexExpr>({static_cast<float>(-1.0), static_cast<float>(-1.0)}))\n        .describe(\"Priorbox step across y and x, -1 for auto calculation.\");\n    TVM_ATTR_FIELD(offsets)\n        .set_default(Array<IndexExpr>({static_cast<float>(0.5), static_cast<float>(0.5)}))\n        .describe(\"Priorbox center offsets, y and x respectively.\");\n    TVM_ATTR_FIELD(clip).set_default(false).describe(\"Whether to clip out-of-boundary boxes.\");\n  }\n};\n\nstruct MultiBoxTransformLocAttrs : public tvm::AttrsNode<MultiBoxTransformLocAttrs> {\n  bool clip;\n  double threshold;\n  Array<IndexExpr> variances;\n\n  TVM_DECLARE_ATTRS(MultiBoxTransformLocAttrs, \"relay.attrs.MultiBoxTransformLocAttrs\") {\n    TVM_ATTR_FIELD(clip).set_default(true).describe(\"Clip out-of-boundary boxes.\");\n    TVM_ATTR_FIELD(threshold).set_default(0.01).describe(\"Threshold to be a positive prediction.\");\n    TVM_ATTR_FIELD(variances)\n        .set_default(Array<IndexExpr>({0.1f, 0.1f, 0.2f, 0.2f}))\n        .describe(\"Variances to be decoded from box regression output.\");\n  }\n};\n\n/*! \\brief Attributes used in get_valid_counts operator */\nstruct GetValidCountsAttrs : public tvm::AttrsNode<GetValidCountsAttrs> {\n  Optional<FloatImm> score_threshold;\n  int id_index;\n  int score_index;\n\n  TVM_DECLARE_ATTRS(GetValidCountsAttrs, \"relay.attrs.GetValidCountsAttrs\") {\n    TVM_ATTR_FIELD(score_threshold).describe(\"Lower limit of score for valid bounding boxes.\");\n    TVM_ATTR_FIELD(id_index).set_default(0).describe(\"Axis index of id.\");\n    TVM_ATTR_FIELD(score_index).set_default(1).describe(\"Index of the scores/confidence of boxes.\");\n  }\n};\n\n/*! \\brief Attributes used in non_maximum_suppression operator */\nstruct NonMaximumSuppressionAttrs : public tvm::AttrsNode<NonMaximumSuppressionAttrs> {\n  bool force_suppress;\n  int top_k;\n  int coord_start;\n  int score_index;\n  int id_index;\n  bool return_indices;\n  bool invalid_to_bottom;\n\n  TVM_DECLARE_ATTRS(NonMaximumSuppressionAttrs, \"relay.attrs.NonMaximumSuppressionAttrs\") {\n    TVM_ATTR_FIELD(force_suppress)\n        .set_default(false)\n        .describe(\"Suppress all detections regardless of class_id.\");\n    TVM_ATTR_FIELD(top_k).set_default(-1).describe(\n        \"Keep maximum top k detections before nms, -1 for no limit.\");\n    TVM_ATTR_FIELD(coord_start)\n        .set_default(2)\n        .describe(\"Start index of the consecutive 4 coordinates.\");\n    TVM_ATTR_FIELD(score_index).set_default(1).describe(\"Index of the scores/confidence of boxes.\");\n    TVM_ATTR_FIELD(id_index).set_default(0).describe(\"Axis index of id.\");\n    TVM_ATTR_FIELD(return_indices)\n        .set_default(true)\n        .describe(\"Whether to return box indices in input data.\");\n    TVM_ATTR_FIELD(invalid_to_bottom)\n        .set_default(false)\n        .describe(\"Whether to move all invalid bounding boxes to the bottom.\");\n  }\n};\n\n/*! \\brief Attributes used in all_class_non_maximum_suppression operator */\nstruct AllClassNonMaximumSuppressionAttrs\n    : public tvm::AttrsNode<AllClassNonMaximumSuppressionAttrs> {\n  std::string output_format;\n\n  TVM_DECLARE_ATTRS(AllClassNonMaximumSuppressionAttrs,\n                    \"relay.attrs.AllClassNonMaximumSuppressionAttrs\") {\n    TVM_ATTR_FIELD(output_format)\n        .set_default(\"onnx\")\n        .describe(\n            \"Output format, onnx or tensorflow. Returns outputs in a way that can be easily \"\n            \"consumed by each frontend.\");\n  }\n};\n\n/*! \\brief Attributes used in roi_align operators */\nstruct ROIAlignAttrs : public tvm::AttrsNode<ROIAlignAttrs> {\n  Array<IndexExpr> pooled_size;\n  double spatial_scale;\n  int sample_ratio;\n  std::string layout;\n  std::string mode;\n  TVM_DECLARE_ATTRS(ROIAlignAttrs, \"relay.attrs.ROIAlignAttrs\") {\n    TVM_ATTR_FIELD(pooled_size).describe(\"Output size of roi align.\");\n    TVM_ATTR_FIELD(spatial_scale)\n        .describe(\n            \"Ratio of input feature map height (or w) to raw image height (or w). \"\n            \"Equals the reciprocal of total stride in convolutional layers, which should be \"\n            \"in range (0.0, 1.0]\");\n    TVM_ATTR_FIELD(sample_ratio)\n        .set_default(-1)\n        .describe(\"Optional sampling ratio of ROI align, using adaptive size by default.\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Convolution is applied on the 'H' and\"\n        \"'W' dimensions.\");\n    TVM_ATTR_FIELD(mode).set_default(\"avg\").describe(\n        \"Mode for ROI Align. Can be 'avg' or 'max'. The default mode is 'avg'.\");\n  }\n};\n\n/*! \\brief Attributes used in roi_pool operators */\nstruct ROIPoolAttrs : public tvm::AttrsNode<ROIPoolAttrs> {\n  Array<IndexExpr> pooled_size;\n  double spatial_scale;\n  std::string layout;\n  TVM_DECLARE_ATTRS(ROIPoolAttrs, \"relay.attrs.ROIPoolAttrs\") {\n    TVM_ATTR_FIELD(pooled_size).describe(\"Output size of roi pool.\");\n    TVM_ATTR_FIELD(spatial_scale)\n        .describe(\n            \"Ratio of input feature map height (or w) to raw image height (or w). \"\n            \"Equals the reciprocal of total stride in convolutional layers, which should be \"\n            \"in range (0.0, 1.0]\");\n    TVM_ATTR_FIELD(layout).set_default(\"NCHW\").describe(\n        \"Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc.\"\n        \"'N', 'C', 'H', 'W' stands for batch, channel, height, and width\"\n        \"dimensions respectively. Convolution is applied on the 'H' and\"\n        \"'W' dimensions.\");\n  }\n};\n\n/*! \\brief Attributes used in yolo reorg operators */\nstruct YoloReorgAttrs : public tvm::AttrsNode<YoloReorgAttrs> {\n  Integer stride;\n\n  TVM_DECLARE_ATTRS(YoloReorgAttrs, \"relay.attrs.YoloReorgAttrs\") {\n    TVM_ATTR_FIELD(stride).set_default(1).describe(\"Stride value for yolo reorg\");\n  }\n};\n\n/*! \\brief Attributes used in proposal operators */\nstruct ProposalAttrs : public tvm::AttrsNode<ProposalAttrs> {\n  Array<IndexExpr> scales;\n  Array<IndexExpr> ratios;\n  int feature_stride;\n  double threshold;\n  int rpn_pre_nms_top_n;\n  int rpn_post_nms_top_n;\n  int rpn_min_size;\n  bool iou_loss;\n\n  TVM_DECLARE_ATTRS(ProposalAttrs, \"relay.attrs.ProposalAttrs\") {\n    TVM_ATTR_FIELD(scales)\n        .set_default(Array<IndexExpr>({4.0f, 8.0f, 16.0f, 32.0f}))\n        .describe(\"Used to generate anchor windows by enumerating scales\");\n    TVM_ATTR_FIELD(ratios)\n        .set_default(Array<IndexExpr>({0.5f, 1.0f, 2.0f}))\n        .describe(\"Used to generate anchor windows by enumerating ratios\");\n    TVM_ATTR_FIELD(feature_stride)\n        .set_default(16)\n        .describe(\n            \"The size of the receptive field each unit in the convolution layer of the rpn,\"\n            \"for example the product of all stride's prior to this layer.\");\n    TVM_ATTR_FIELD(threshold).set_default(0.7).describe(\n        \"IoU threshold of non-maximum suppresion (suppress boxes with IoU >= this threshold)\");\n    TVM_ATTR_FIELD(rpn_pre_nms_top_n)\n        .set_default(6000)\n        .describe(\"Number of top scoring boxes to apply NMS. -1 to use all boxes\");\n    TVM_ATTR_FIELD(rpn_post_nms_top_n)\n        .set_default(300)\n        .describe(\"Number of top scoring boxes to keep after applying NMS to RPN proposals\");\n    TVM_ATTR_FIELD(rpn_min_size).set_default(16).describe(\"Minimum height or width in proposal\");\n    TVM_ATTR_FIELD(iou_loss).set_default(false).describe(\"Usage of IoU Loss\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_VISION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/attrs/vm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/attrs/vm.h\n * \\brief Attributes for Relay vm operators.\n */\n#ifndef TVM_RELAY_ATTRS_VM_H_\n#define TVM_RELAY_ATTRS_VM_H_\n\n#include <tvm/ir/attrs.h>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Options for the shape function operator.\n */\nstruct ShapeFuncAttrs : public tvm::AttrsNode<ShapeFuncAttrs> {\n  Array<Integer> is_input;\n\n  TVM_DECLARE_ATTRS(ShapeFuncAttrs, \"relay.attrs.ShapeFuncAttrs\") {\n    TVM_ATTR_FIELD(is_input).describe(\n        \"A bool indicating whether the shape function should\"\n        \"expect shape or input in each position.\");\n  }\n};\n\n/*!\n * \\brief Attributes for VM reshape_tensor operator.\n */\nstruct ReshapeTensorAttrs : public tvm::AttrsNode<ReshapeTensorAttrs> {\n  Array<PrimExpr> newshape;\n\n  TVM_DECLARE_ATTRS(ReshapeTensorAttrs, \"relay.attrs.ReshapeTensorAttrs\") {\n    TVM_ATTR_FIELD(newshape).describe(\"The new shape of output tensor\");\n  }\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ATTRS_VM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/base.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/base.h\n * \\brief Base classes for the Relay IR.\n */\n#ifndef TVM_RELAY_BASE_H_\n#define TVM_RELAY_BASE_H_\n\n#include <tvm/ir/span.h>\n#include <tvm/node/node.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\n/*!\n * \\brief Relay: a high level functional IR for TVM.\n *\n * This namespace contains the abstract syntax tree, and other\n * essential data structures for the Relay IR.\n *\n * You can find more about Relay by reading the language reference.\n */\nnamespace relay {\n\n#define RELAY_DEBUG(...)                                                \\\n  {                                                                     \\\n    auto fdebug = runtime::Registry::Get(\"relay.debug\");                \\\n    ICHECK(fdebug) << \"Could not find Relay Python debugger function.\"; \\\n    (*fdebug)(\"RELAY_DEBUG\", __FILE__, __LINE__, __VA_ARGS__);          \\\n  }\n\n#define RELAY_DEBUG_INTERP(...)                                         \\\n  {                                                                     \\\n    auto fdebug = runtime::Registry::Get(\"relay.debug_interp\");         \\\n    ICHECK(fdebug) << \"Could not find Relay Python debugger function.\"; \\\n    (*fdebug)(\"RELAY_DEBUG\", __FILE__, __LINE__, __VA_ARGS__);          \\\n  }\n\n/*!\n * \\brief Symbolic expression for tensor shape.\n */\nusing IndexExpr = ::tvm::PrimExpr;\n\nusing SourceName = tvm::SourceName;\nusing Span = tvm::Span;\nusing SpanNode = tvm::SpanNode;\n\n/*!\n * \\brief This is the base node container of all relay structures.\n */\nclass RelayNode : public Object {\n public:\n  /*! \\brief The location of the program in a SourceFragment can be null,\n   * check with span.defined() */\n  mutable Span span;\n\n  static constexpr const char* _type_key = \"relay.Node\";\n  TVM_DECLARE_BASE_OBJECT_INFO(RelayNode, Object);\n};\n\n/*!\n * \\brief The unique identifier of variables.\n *\n * Id is like name to the variables,\n * except that id is unique for each Var.\n *\n * \\note Do not create Id directly, they are created in Var.\n */\nclass IdNode : public Object {\n public:\n  /*!\n   * \\brief The name of the variable,\n   *  this only acts as a hint to the user,\n   *  and is not used for equality.\n   */\n  String name_hint;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"name_hint\", &name_hint); }\n\n  bool SEqualReduce(const IdNode* other, SEqualReducer equal) const {\n    return equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce.FreeVarHashImpl(this); }\n\n  static constexpr const char* _type_key = \"relay.Id\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(IdNode, Object);\n};\n\nclass Id : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param name_hint The name of the variable.\n   */\n  TVM_DLL explicit Id(String name_hint);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Id, ObjectRef, IdNode);\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/dataflow_matcher.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/dataflow_matcher.h\n * \\brief A pattern matcher for matching dataflow properties.\n */\n#ifndef TVM_RELAY_DATAFLOW_MATCHER_H_\n#define TVM_RELAY_DATAFLOW_MATCHER_H_\n\n#include <tvm/relay/dataflow_pattern.h>\n#include <tvm/relay/dataflow_pattern_functor.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\n\nclass DFPatternCallback;\n/*!\n * \\brief Base type of all dataflow pattern callbacks.\n * \\sa DFPatternCallback\n */\nclass DFPatternCallbackNode : public Object {\n public:\n  /*! \\brief Pattern this callback matches */\n  DFPattern pattern;\n  /*! \\brief Function to call when finding a matched expression */\n  PackedFunc function;\n  /*! \\brief Require InferType to be run before the callback */\n  bool require_type;\n  /*! \\brief Run the callback only once */\n  bool rewrite_once;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pattern\", &pattern);\n    v->Visit(\"require_type\", &require_type);\n    v->Visit(\"rewrite_once\", &rewrite_once);\n  }\n\n  static constexpr const char* _type_key = \"DFPatternCallbackNode\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DFPatternCallbackNode, Object);\n};\n\n/*!\n * \\brief Managed reference to dataflow pattern callbacks.\n * \\sa DFPatternCallbackNode\n */\nclass DFPatternCallback : public ObjectRef {\n public:\n  TVM_DLL DFPatternCallback(DFPattern pattern, PackedFunc callback, bool require_type,\n                            bool rewrite_once = false);\n  TVM_DEFINE_OBJECT_REF_METHODS(DFPatternCallback, ObjectRef, DFPatternCallbackNode);\n};\n\n/*!\n * \\brief Determine if a pattern matches an expression\n *\n * \\param pattern The pattern to match\n * \\param expr The expression to match\n *\n * \\return Return true if the pattern and the expression match, return false otherwise.\n */\nbool MatchPattern(DFPattern pattern, Expr expr);\n\n/*!\n * \\brief Rewrite an expression based on some number of DFPatternCallbacks\n *\n * \\param callbacks An array of DFPatternCallback Nodes\n * \\param expr The expression to rewrite\n * \\param mod The module that associates with the expr\n *\n * \\return Return An Expr with every match of the pattern inside the callbacks rewritten by the\n * functions inside the callbacks\n */\nExpr RewritePatterns(Array<DFPatternCallback> callbacks, Expr expr, IRModule mod = IRModule());\n\n/*!\n * \\brief Partition all matches of a DFPattern inside an Expr into separate Function calls\n *\n * \\param pattern The pattern to match\n * \\param expr The expression to patition\n * \\param attrs A set of parameter names and values to apply to the partitioned function\n * \\param check A callback function for checking more complicated properties of the matched\n * expressions, returns true if the match is accepted and false otherwise\n *\n * \\return Return the paritioned Expr.\n */\nExpr PartitionPattern(DFPattern pattern, Expr expr, Map<String, ObjectRef> attrs, PackedFunc check);\n\n/*!\n * \\brief Infer the type of an expression.\n *\n * \\param expr The expression to rewrite\n *\n * \\return Return An Expr with unambiguous type information filled in, as well as it's\n * checked type field populated with the result type.\n *\n */\nExpr InferType(const Expr& expr);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_DATAFLOW_MATCHER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/dataflow_pattern.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/dataflow_pattern.h\n * \\brief A pattern language for matching dataflow properties.\n */\n#ifndef TVM_RELAY_DATAFLOW_PATTERN_H_\n#define TVM_RELAY_DATAFLOW_PATTERN_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Base type of all dataflow patterns.\n * \\sa DFPattern\n */\nclass DFPatternNode : public Object {\n public:\n  static constexpr const char* _type_key = \"DFPatternNode\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DFPatternNode, Object);\n};\n\n/*!\n * \\brief Managed reference to dataflow patterns.\n * \\sa DFPatternNode\n */\nclass DFPattern : public ObjectRef {\n public:\n  /*! \\brief Syntatic Sugar for creating a CallPattern */\n  DFPattern operator()(const std::vector<DFPattern>& args) const;\n  /*! \\brief Syntatic Sugar for creating a CallPattern with an \"add\" op */\n  DFPattern operator+(const DFPattern& other) const;\n  /*! \\brief Syntatic Sugar for creating a CallPattern with a \"subtract\" op */\n  DFPattern operator-(const DFPattern& other) const;\n  /*! \\brief Syntatic Sugar for creating a CallPattern with a \"multiply\" op */\n  DFPattern operator*(const DFPattern& other) const;\n  /*! \\brief Syntatic Sugar for creating a CallPattern with a \"divide\" op */\n  DFPattern operator/(const DFPattern& other) const;\n  /*! \\brief Syntatic Sugar for creating an AltPattern */\n  DFPattern operator||(const DFPattern& other) const;\n  /*! \\brief Syntatic Sugar for creating an Optional Pattern */\n  DFPattern Optional(const std::function<DFPattern(const DFPattern&)>& func) const;\n  /*! \\brief Syntatic Sugar for creating an AttrPattern */\n  DFPattern HasAttr(const Map<String, ObjectRef>& attrs) const;\n  /*! \\brief Syntatic Sugar for creating a TypePattern */\n  DFPattern HasType(const Type& type) const;\n  /*! \\brief Syntatic Sugar for creating a DataTypePattern with a DataType */\n  DFPattern HasDtype(const DataType& dtype) const;\n  /*! \\brief Syntatic Sugar for creating a DataTypePattern with a data type's name */\n  DFPattern HasDtype(const std::string& dtype) const;\n  /*! \\brief Syntatic Sugar for creating a ShapePattern */\n  DFPattern HasShape(const Array<PrimExpr> shape) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(DFPattern, ObjectRef, DFPatternNode);\n};\n\n/*!\n * \\brief Pattern for Relay Expression.\n */\nclass ExprPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The expression to match. */\n  Expr expr;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"expr\", &expr); }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.ExprPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExprPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches a literal expression.\n *\n * \\note Uses structural equality on expressions to check equality.\n *\n */\nclass ExprPattern : public DFPattern {\n public:\n  TVM_DLL explicit ExprPattern(Expr expr);\n  TVM_DEFINE_OBJECT_REF_METHODS(ExprPattern, DFPattern, ExprPatternNode);\n};\n\n/*!\n * \\brief A Pattern to Match a Relay Variable\n */\nclass VarPattern;\n/*! \\brief Container for Var */\nclass VarPatternNode : public DFPatternNode {\n public:\n  /*!\n   * \\brief The name of the Var (optional).\n   */\n  String name;\n\n  /*! \\return The name hint of the variable */\n  const String& name_hint() const { return name; }\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"name\", &name); }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.VarPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(VarPatternNode, DFPatternNode);\n};\n\nclass VarPattern : public DFPattern {\n public:\n  TVM_DLL VarPattern(String name_hint);\n  TVM_DEFINE_OBJECT_REF_METHODS(VarPattern, DFPattern, VarPatternNode);\n};\n\n/*!\n * \\brief A Pattern to Match a Relay Constant\n */\nclass ConstantPattern;\n/*! \\brief Container for Constant */\nclass ConstantPatternNode : public DFPatternNode {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.ConstantPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantPatternNode, DFPatternNode);\n};\n\nclass ConstantPattern : public DFPattern {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(ConstantPattern, DFPattern, ConstantPatternNode);\n};\n\n/*!\n * \\brief Call corresponds to operator invocation.\n *  Corresponds to the operator in computational graph terminology.\n */\nclass CallPattern;\n/*! \\brief CallPattern container. */\nclass CallPatternNode : public DFPatternNode {\n public:\n  /*!\n   * \\brief The operator(function) being invoked\n   *\n   *  - It can be relay::Op which corresponds to the primitive operators.\n   *  - It can also be user defined functions (Function, GlobalVar, Var).\n   */\n  DFPattern op;\n\n  /*! \\brief The arguments(inputs) of the call */\n  tvm::Array<relay::DFPattern> args;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"op\", &op);\n    v->Visit(\"args\", &args);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.CallPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CallPatternNode, DFPatternNode);\n};\n\nclass CallPattern : public DFPattern {\n public:\n  TVM_DLL CallPattern(DFPattern op, Array<DFPattern> args);\n  TVM_DEFINE_OBJECT_REF_METHODS(CallPattern, DFPattern, CallPatternNode);\n};\n\n/*!\n * \\brief Relay Function container\n * \\sa Function\n */\nclass FunctionPatternNode : public DFPatternNode {\n public:\n  /*! \\brief Function parameters */\n  tvm::Array<DFPattern> params;\n  /*!\n   * \\brief\n   * The expression which represents the computation of the function,\n   * the expression may reference the parameters, and the type of it\n   * or sub-expressions may reference the type variables.\n   */\n  DFPattern body;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"params\", &params);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.FunctionPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FunctionPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief Managed reference to FunctionNode.\n * \\sa FunctionNode\n */\nclass FunctionPattern : public DFPattern {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param params The parameters of the function.\n   * \\param body The body of the function.\n   */\n  TVM_DLL FunctionPattern(tvm::Array<DFPattern> params, DFPattern body);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(FunctionPattern, DFPattern, FunctionPatternNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(FunctionPatternNode);\n};\n\n/*! \\brief A binding of a sub-network. */\nclass LetPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The variable we bind to */\n  DFPattern var;\n  /*! \\brief The value we bind var to */\n  DFPattern value;\n  /*! \\brief The body of the let binding */\n  DFPattern body;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"var\", &var);\n    v->Visit(\"value\", &value);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.LetPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LetPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief Let binding that binds a local var\n */\nclass LetPattern : public DFPattern {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param var The variable that is bound to.\n   * \\param value The value used to bind to the variable.\n   * \\param body The body of the let binding.\n   */\n  TVM_DLL LetPattern(DFPattern var, DFPattern value, DFPattern body);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(LetPattern, DFPattern, LetPatternNode);\n};\n\n/*! \\brief Tuple of multiple Exprs */\nclass TuplePattern;\n/*! \\brief Tuple container */\nclass TuplePatternNode : public DFPatternNode {\n public:\n  /*! \\brief the fields of the tuple */\n  tvm::Array<DFPattern> fields;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"fields\", &fields); }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.TuplePattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TuplePatternNode, DFPatternNode);\n};\n\nclass TuplePattern : public DFPattern {\n public:\n  TVM_DLL explicit TuplePattern(tvm::Array<DFPattern> fields);\n  TVM_DEFINE_OBJECT_REF_METHODS(TuplePattern, DFPattern, TuplePatternNode);\n};\n\n/*! \\brief Get index-th field out of a tuple. */\nclass TupleGetItemPattern;\nclass TupleGetItemPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The tuple Expression */\n  DFPattern tuple;\n  /*! \\brief which value to get */\n  int index;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"tuple\", &tuple);\n    v->Visit(\"index\", &index);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.TupleGetItemPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleGetItemPatternNode, DFPatternNode);\n};\n\nclass IfPatternNode : public DFPatternNode {\n public:\n  DFPattern cond, true_branch, false_branch;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"cond\", &cond);\n    v->Visit(\"true_branch\", &true_branch);\n    v->Visit(\"false_branch\", &false_branch);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.IfPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IfPatternNode, DFPatternNode);\n};\n\nclass IfPattern : public DFPattern {\n public:\n  TVM_DLL IfPattern(DFPattern cond, DFPattern then_clause, DFPattern else_clause);\n  TVM_DEFINE_OBJECT_REF_METHODS(IfPattern, DFPattern, IfPatternNode);\n};\n\nclass TupleGetItemPattern : public DFPattern {\n public:\n  TVM_DLL TupleGetItemPattern(DFPattern tuple, int index);\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleGetItemPattern, DFPattern, TupleGetItemPatternNode);\n};\n\nclass AltPattern;\n/*!\n * \\brief Pattern for Alternate Expressions.\n */\nclass AltPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The left optional pattern. */\n  DFPattern left;\n  /*! \\brief The right optional pattern. */\n  DFPattern right;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"left\", &left);\n    v->Visit(\"right\", &right);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.AltPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AltPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches either of two patterns\n */\nclass AltPattern : public DFPattern {\n public:\n  TVM_DLL AltPattern(DFPattern left, DFPattern right);\n  TVM_DEFINE_OBJECT_REF_METHODS(AltPattern, DFPattern, AltPatternNode);\n};\n\n/*!\n * \\brief Wildcard Pattern.\n */\nclass WildcardPatternNode : public DFPatternNode {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.WildcardPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WildcardPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches anything.\n */\nclass WildcardPattern : public DFPattern {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(WildcardPattern, DFPattern, WildcardPatternNode);\n};\n\nclass TypePattern;\n/*!\n * \\brief Pattern for Types.\n */\nclass TypePatternNode : public DFPatternNode {\n public:\n  /*! \\brief The pattern. */\n  DFPattern pattern;\n  /*! \\brief The type to match */\n  Type type;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pattern\", &pattern);\n    v->Visit(\"type\", &type);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.TypePattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TypePatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches a type in another pattern\n */\nclass TypePattern : public DFPattern {\n public:\n  TVM_DLL TypePattern(DFPattern pattern, Type type);\n  TVM_DEFINE_OBJECT_REF_METHODS(TypePattern, DFPattern, TypePatternNode);\n};\n\nclass ShapePattern;\n/*!\n * \\brief Pattern for Shapes.\n */\nclass ShapePatternNode : public DFPatternNode {\n public:\n  /*! \\brief The pattern. */\n  DFPattern pattern;\n  /*! \\brief The type to match */\n  Array<PrimExpr> shape;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pattern\", &pattern);\n    v->Visit(\"shape\", &shape);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.ShapePattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ShapePatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches a type in another pattern\n */\nclass ShapePattern : public DFPattern {\n public:\n  TVM_DLL ShapePattern(DFPattern pattern, Array<PrimExpr> type);\n  TVM_DEFINE_OBJECT_REF_METHODS(ShapePattern, DFPattern, ShapePatternNode);\n};\n\nclass DataTypePattern;\n/*!\n * \\brief Pattern for Types.\n */\nclass DataTypePatternNode : public DFPatternNode {\n public:\n  /*! \\brief The pattern. */\n  DFPattern pattern;\n  /*! \\brief The type to match */\n  DataType dtype;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pattern\", &pattern);\n    v->Visit(\"dtype\", &dtype);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.DataTypePattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DataTypePatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches a type in another pattern\n */\nclass DataTypePattern : public DFPattern {\n public:\n  TVM_DLL DataTypePattern(DFPattern pattern, DataType dtype);\n  TVM_DEFINE_OBJECT_REF_METHODS(DataTypePattern, DFPattern, DataTypePatternNode);\n};\n\nclass AttrPattern;\n/*!\n * \\brief Pattern for Attributes.\n */\nclass AttrPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The pattern. */\n  DFPattern pattern;\n  /*! \\brief The attribute to match */\n  DictAttrs attrs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pattern\", &pattern);\n    v->Visit(\"attrs\", &attrs);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.AttrPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttrPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches attributes in another pattern\n */\nclass AttrPattern : public DFPattern {\n public:\n  TVM_DLL AttrPattern(DFPattern pattern, DictAttrs attrs);\n  TVM_DEFINE_OBJECT_REF_METHODS(AttrPattern, DFPattern, AttrPatternNode);\n};\n\nclass DominatorPattern;\n/*!\n * \\brief Dominated Graph Pattern\n * Pattern for fuzzy subgraphs where all outputs of the parent are used finally by the child, and\n * every operation between the parent and the child matches the path.\n */\nclass DominatorPatternNode : public DFPatternNode {\n public:\n  /*! \\brief The parent. */\n  DFPattern parent;\n  /*! \\brief The path. */\n  DFPattern path;\n  /*! \\brief The child. */\n  DFPattern child;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"parent\", &parent);\n    v->Visit(\"path\", &path);\n    v->Visit(\"child\", &child);\n  }\n\n  static constexpr const char* _type_key = \"relay.dataflow_pattern.DominatorPattern\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DominatorPatternNode, DFPatternNode);\n};\n\n/*!\n * \\brief A pattern which matches a variable length dominator path\n */\nclass DominatorPattern : public DFPattern {\n public:\n  TVM_DLL DominatorPattern(DFPattern parent, DFPattern path, DFPattern child);\n  TVM_DEFINE_OBJECT_REF_METHODS(DominatorPattern, DFPattern, DominatorPatternNode);\n};\n\n/*! \\brief Syntatic Sugar for creating a VarPattern with a name */\nDFPattern IsVar(const String& name);\n/*! \\brief Syntatic Sugar for creating a ConstantPattern */\nDFPattern IsConstant();\n/*! \\brief Syntatic Sugar for creating a WildcardPattern */\nDFPattern IsWildcard();\n/*! \\brief Syntatic Sugar for creating a ExprPattern */\nDFPattern IsExpr(const Expr& expr);\n/*! \\brief Syntatic Sugar for creating a ExprPattern base on an Op*/\nDFPattern IsOp(const String& op_name);\n/*! \\brief Syntatic Sugar for creating a TuplePattern*/\nDFPattern IsTuple(const Array<DFPattern>& fields);\n/*! \\brief Syntatic Sugar for creating a TupleGetItemPattern*/\nDFPattern IsTupleGetItem(const DFPattern tuple, int index = -1);\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_DATAFLOW_PATTERN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/dataflow_pattern_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/dataflow_pattern_functor.h\n * \\brief A set of passes for operating on pattern graphs.\n */\n#ifndef TVM_RELAY_DATAFLOW_PATTERN_FUNCTOR_H_\n#define TVM_RELAY_DATAFLOW_PATTERN_FUNCTOR_H_\n\n#include <tvm/relay/dataflow_pattern.h>\n\n#include <unordered_set>\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief A dynamical functor that dispatches on in the first DFPattern argument.\n *\n * \\tparam FType function signature\n *  This type is only defined for FType with function signature R(const DFPattern&,\n * Args...)\n */\ntemplate <typename FType>\nclass DFPatternFunctor;\n\n// functions to be overriden.\n#define DFPATTERN_FUNCTOR_DEFAULT \\\n  { return VisitDFPatternDefault_(op, std::forward<Args>(args)...); }\n\n#define RELAY_DFPATTERN_FUNCTOR_DISPATCH(OP)                                                    \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {          \\\n    return self->VisitDFPattern_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass DFPatternFunctor<R(const DFPattern& n, Args...)> {\n private:\n  using TSelf = DFPatternFunctor<R(const DFPattern& n, Args...)>;\n  using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief virtual destructor */\n  virtual ~DFPatternFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const DFPattern& n, Args... args) {\n    return VisitDFPattern(n, std::forward<Args>(args)...);\n  }\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitDFPattern(const DFPattern& n, Args... args) {\n    ICHECK(n.defined());\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitDFPattern_(const AltPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const AttrPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const CallPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const ConstantPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const DataTypePatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const DominatorPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const ExprPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const FunctionPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const IfPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const LetPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const ShapePatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const TupleGetItemPatternNode* op,\n                            Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const TuplePatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const TypePatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const VarPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPattern_(const WildcardPatternNode* op, Args... args) DFPATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitDFPatternDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    throw;\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(AltPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(AttrPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(CallPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(ConstantPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(DataTypePatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(DominatorPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(ExprPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(FunctionPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(IfPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(LetPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(ShapePatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(TupleGetItemPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(TuplePatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(TypePatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(VarPatternNode);\n    RELAY_DFPATTERN_FUNCTOR_DISPATCH(WildcardPatternNode);\n    return vtable;\n  }\n};\n\n/*!\n * \\brief A simple visitor wrapper around DFPatternFunctor.\n *  Recursively visit the content.\n *\n *  DFPatternVisitor treats the Pattern as dataflow graph,and only visit each Expr node once.\n */\nclass DFPatternVisitor : public DFPatternFunctor<void(const DFPattern&)> {\n public:\n  void VisitDFPattern(const DFPattern& pattern) override;\n  void VisitDFPattern_(const AltPatternNode* op) override;\n  void VisitDFPattern_(const AttrPatternNode* op) override;\n  void VisitDFPattern_(const CallPatternNode* op) override;\n  void VisitDFPattern_(const ConstantPatternNode* op) override;\n  void VisitDFPattern_(const DataTypePatternNode* op) override;\n  void VisitDFPattern_(const DominatorPatternNode* op) override;\n  void VisitDFPattern_(const ExprPatternNode* op) override;\n  void VisitDFPattern_(const FunctionPatternNode* op) override;\n  void VisitDFPattern_(const IfPatternNode* op) override;\n  void VisitDFPattern_(const LetPatternNode* op) override;\n  void VisitDFPattern_(const ShapePatternNode* op) override;\n  void VisitDFPattern_(const TupleGetItemPatternNode* op) override;\n  void VisitDFPattern_(const TuplePatternNode* op) override;\n  void VisitDFPattern_(const TypePatternNode* op) override;\n  void VisitDFPattern_(const VarPatternNode* op) override;\n  void VisitDFPattern_(const WildcardPatternNode* op) override;\n\n protected:\n  // set of already-visited nodes\n  std::unordered_set<const Object*> visited_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_DATAFLOW_PATTERN_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/executor.h\n * \\brief Object representation of Executor configuration and registry\n */\n#ifndef TVM_RELAY_EXECUTOR_H_\n#define TVM_RELAY_EXECUTOR_H_\n\n#include <dmlc/registry.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n#include <tvm/ir/type_relation.h>\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/runtime/registry.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\ntemplate <typename, typename>\nclass AttrRegistry;\n\nnamespace relay {\n\n/*!\n * \\brief Executor information.\n *\n * This data structure stores the meta-data\n * about executors which can be used to pass around information.\n *\n * \\sa Executor\n */\nclass ExecutorNode : public Object {\n public:\n  /*! \\brief name of the Executor */\n  String name;\n  /* \\brief Additional attributes storing meta-data about the Executor. */\n  DictAttrs attrs;\n\n  /*!\n   * \\brief Should Link Parameters into the module\n   * \\return Whether the Executor is configured to execute modules with linked parameters\n   */\n  Bool ShouldLinkParameters() const {\n    return name == \"aot\" || GetAttr<Bool>(\"link-params\").value_or(Bool(false));\n  }\n\n  /*!\n   * \\brief Get an attribute.\n   *\n   * \\param attr_key The attribute key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TObjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetAttrExample(const Executor& executor) {\n   *    auto value = executor->GetAttr<Integer>(\"AttrKey\", 0);\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    return attrs.GetAttr(attr_key, default_value);\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"attrs\", &attrs);\n  }\n\n  bool SEqualReduce(const ExecutorNode* other, SEqualReducer equal) const {\n    return name == other->name && equal.DefEqual(attrs, other->attrs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name);\n    hash_reduce(attrs);\n  }\n\n  static constexpr const char* _type_key = \"Executor\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExecutorNode, Object);\n};\n\n/*!\n * \\brief Managed reference class to ExecutorNode.\n * \\sa ExecutorNode\n */\nclass Executor : public ObjectRef {\n public:\n  /*!\n   * \\brief Create a new Executor object using the registry\n   * \\throws Error if name is not registered\n   * \\param name The name of the executor.\n   * \\param attrs Attributes for the executor.\n   * \\return the new Executor object.\n   */\n  TVM_DLL static Executor Create(String name, Map<String, ObjectRef> attrs = {});\n\n  /*!\n   * \\brief List all registered Executors\n   * \\return the list of Executors\n   */\n  TVM_DLL static Array<String> ListExecutors();\n\n  /*!\n   * \\brief List all options for a specific Executor\n   * \\param name The name of the Executor\n   * \\return Map of option name to type\n   */\n  TVM_DLL static Map<String, String> ListExecutorOptions(const String& name);\n\n  /*! \\brief specify container node */\n  TVM_DEFINE_OBJECT_REF_METHODS(Executor, ObjectRef, ExecutorNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ExecutorNode)\n\n private:\n  /*!\n   * \\brief Private Constructor\n   * \\param name The executor name\n   * \\param attrs Attributes to apply to this Executor node\n   */\n  TVM_DLL Executor(String name, DictAttrs attrs) {\n    auto n = make_object<ExecutorNode>();\n    n->name = std::move(name);\n    n->attrs = std::move(attrs);\n    data_ = std::move(n);\n  }\n};\n\n/*!\n * \\brief Helper structure to register Executors\n * \\sa TVM_REGISTER_EXECUTOR\n */\nclass ExecutorRegEntry {\n public:\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline ExecutorRegEntry& add_attr_option(const String& key);\n\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\param default_value The default value of the key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline ExecutorRegEntry& add_attr_option(const String& key, ObjectRef default_value);\n\n  /*!\n   * \\brief Register or get a new entry.\n   * \\param name The name of the operator.\n   * \\return the corresponding entry.\n   */\n  TVM_DLL static ExecutorRegEntry& RegisterOrGet(const String& name);\n\n private:\n  /*! \\brief Internal storage of value types */\n  struct ValueTypeInfo {\n    std::string type_key;\n    uint32_t type_index;\n  };\n  std::unordered_map<std::string, ValueTypeInfo> key2vtype_;\n  /*! \\brief A hash table that stores the default value of each attr */\n  std::unordered_map<String, ObjectRef> key2default_;\n\n  /*! \\brief Index used for internal lookup of attribute registry */\n  uint32_t index_;\n\n  // the name\n  std::string name;\n\n  /*! \\brief Return the index stored in attr registry */\n  uint32_t AttrRegistryIndex() const { return index_; }\n  /*! \\brief Return the name stored in attr registry */\n  String AttrRegistryName() const { return name; }\n\n  /*! \\brief private constructor */\n  explicit ExecutorRegEntry(uint32_t reg_index) : index_(reg_index) {}\n\n  // friend class\n  template <typename>\n  friend class AttrRegistryMapContainerMap;\n  template <typename, typename>\n  friend class tvm::AttrRegistry;\n  friend class Executor;\n};\n\ntemplate <typename ValueType>\ninline ExecutorRegEntry& ExecutorRegEntry::add_attr_option(const String& key) {\n  ICHECK(!key2vtype_.count(key)) << \"AttributeError: add_attr_option failed because '\" << key\n                                 << \"' has been set once\";\n\n  using ValueNodeType = typename ValueType::ContainerType;\n  // NOTE: we could further update the function later.\n  uint32_t value_type_index = ValueNodeType::_GetOrAllocRuntimeTypeIndex();\n\n  ValueTypeInfo info;\n  info.type_index = value_type_index;\n  info.type_key = runtime::Object::TypeIndex2Key(value_type_index);\n  key2vtype_[key] = info;\n  return *this;\n}\n\ntemplate <typename ValueType>\ninline ExecutorRegEntry& ExecutorRegEntry::add_attr_option(const String& key,\n                                                           ObjectRef default_value) {\n  add_attr_option<ValueType>(key);\n  key2default_[key] = default_value;\n  return *this;\n}\n\n// internal macros to make executor entries\n#define TVM_EXECUTOR_REGISTER_VAR_DEF \\\n  static DMLC_ATTRIBUTE_UNUSED ::tvm::relay::ExecutorRegEntry& __make_##Executor\n\n/*!\n * \\def TVM_REGISTER_EXECUTOR\n * \\brief Register a new executor, or set attribute of the corresponding executor.\n *\n * \\param ExecutorName The name of registry\n *\n * \\code\n *\n *  TVM_REGISTER_EXECUTOR(\"aot\")\n *  .add_attr_option<String>(\"my_option\");\n *  .add_attr_option<String>(\"my_option_default\", String(\"default\"));\n *\n * \\endcode\n */\n#define TVM_REGISTER_EXECUTOR(ExecutorName)                    \\\n  TVM_STR_CONCAT(TVM_EXECUTOR_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::relay::ExecutorRegEntry::RegisterOrGet(ExecutorName)\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/expr.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/expr.h\n * \\brief Relay expression language.\n */\n#ifndef TVM_RELAY_EXPR_H_\n#define TVM_RELAY_EXPR_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/ir/module.h>\n#include <tvm/ir/op.h>\n#include <tvm/target/virtual_device.h>\n\n#include <functional>\n#include <stack>\n#include <string>\n#include <utility>\n\n#include \"./base.h\"\n#include \"./type.h\"\n\nnamespace tvm {\n\n/*!\n * \\brief Returns \\p global_var with the given properties. A null property denotes 'no change'.\n * Returns \\p global_var if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nGlobalVar WithFields(GlobalVar global_var, Optional<String> opt_name_hint = {},\n                     Optional<Type> opt_type = {}, Optional<VirtualDevice> opt_virtual_device = {},\n                     Optional<Span> opt_span = {});\n\nnamespace relay {\n\nusing Expr = tvm::RelayExpr;\nusing ExprNode = tvm::RelayExprNode;\nusing BaseFunc = tvm::BaseFunc;\nusing BaseFuncNode = tvm::BaseFuncNode;\nusing GlobalVar = tvm::GlobalVar;\nusing GlobalVarNode = tvm::GlobalVarNode;\nusing tvm::PrettyPrint;\n\n/*!\n * \\brief Constant tensor, backed by an NDArray on the cpu(0) device.\n *\n * \\note Scalar constants are represented by rank-0 const tensor.\n *  Constant folding are handled uniformly via Tensor types.\n */\nclass Constant;\n/*!\n * \\brief Constant tensor type.\n */\nclass ConstantNode : public ExprNode {\n public:\n  /*! \\brief The data of the tensor */\n  runtime::NDArray data;\n\n  /*! \\return The corresponding tensor type of the data */\n  TensorType tensor_type() const;\n\n  /*! \\return Whether it is scalar(rank-0 tensor) */\n  bool is_scalar() const { return data->ndim == 0; }\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"data\", &data);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const ConstantNode* other, SEqualReducer equal) const {\n    return equal(data, other->data);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(data); }\n\n  static constexpr const char* _type_key = \"relay.Constant\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantNode, ExprNode);\n};\n\nclass Constant : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param data The data of the constant tensor.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL explicit Constant(runtime::NDArray data, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Constant, RelayExpr, ConstantNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ConstantNode);\n};\n\n/*!\n * \\brief Returns \\p constant with the given properties. A null property denotes 'no change'.\n * Returns \\p constant if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nConstant WithFields(Constant constant, Optional<runtime::NDArray> opt_data = {},\n                    Optional<VirtualDevice> opt_virtual_device = {}, Optional<Span> opt_span = {});\n\n/*! \\brief Tuple of multiple Exprs */\nclass Tuple;\n/*! \\brief Tuple container */\nclass TupleNode : public ExprNode {\n public:\n  /*! \\brief the fields of the tuple */\n  tvm::Array<relay::Expr> fields;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"fields\", &fields);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const TupleNode* other, SEqualReducer equal) const {\n    // specially handle empty tuple as a constant is not a graph node.\n    if (fields.size() == other->fields.size() && fields.size() == 0) {\n      return true;\n    } else {\n      equal->MarkGraphNode();\n      return equal(fields, other->fields);\n    }\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    if (fields.size() != 0) {\n      hash_reduce->MarkGraphNode();\n      hash_reduce(fields);\n    }\n  }\n\n  static constexpr const char* _type_key = \"relay.Tuple\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleNode, ExprNode);\n};\n\nclass Tuple : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param fields The fields of a tuple.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL explicit Tuple(tvm::Array<relay::Expr> fields, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Tuple, RelayExpr, TupleNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(TupleNode);\n};\n\n/*!\n * \\brief Returns \\p tuple with the given properties. A null property denotes 'no change'.\n * Returns \\p tuple if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nTuple WithFields(Tuple tuple, Optional<Array<Expr>> opt_fields = Optional<Array<Expr>>(),\n                 Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                 Optional<Span> opt_span = Optional<Span>());\n\n/*!\n * \\brief Local variables used in the let expression.\n *\n * Its semantics are similar to tvm.Var node used in TVM's low level\n * tensor expression language.\n *\n * \\note Each Var is bind only once and is immutable.\n */\nclass Var;\n/*! \\brief Container for Var */\nclass VarNode : public ExprNode {\n public:\n  /*!\n   * \\brief The unique identifier of the Var.\n   *\n   * vid will be preserved for the same Var during type inference\n   * and other rewritings, while the VarNode might be recreated\n   * to attach additional information.\n   * This property can be used to keep track of parameter Var\n   * information across passes.\n   */\n  Id vid;\n  /*!\n   * \\brief type annotaion of the variable.\n   * This field records user provided type annotation of the Var.\n   * This field is optional and can be None.\n   */\n  Type type_annotation;\n\n  /*! \\return The name hint of the variable */\n  const String& name_hint() const { return vid->name_hint; }\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"vid\", &vid);\n    v->Visit(\"type_annotation\", &type_annotation);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const VarNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(type_annotation, other->type_annotation) && equal(vid, other->vid) &&\n           equal(virtual_device_, other->virtual_device_);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(type_annotation);\n    hash_reduce(vid);\n  }\n\n  static constexpr const char* _type_key = \"relay.Var\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(VarNode, ExprNode);\n};\n\nclass Var : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param name_hint The name hint of a variable.\n   * \\param type_annotation The type annotation of a variable.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL Var(String name_hint, Type type_annotation, Span span = Span())\n      : Var(Id(name_hint), type_annotation, span) {}\n\n  /*!\n   * \\brief The constructor\n   * \\param vid The unique id of a variable.\n   * \\param type_annotation The type annotation of a variable.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL Var(Id vid, Type type_annotation, Span span = Span());\n\n  /*!\n   * \\brief Return a globally fresh name. Helps with debugging to follow the same\n   * variable between passes and sub-expressions.\n   *\n   * TODO(mbs): Replace with name creation w.r.t. scopes once available as part of\n   * name gen overhaul.\n   */\n  static Var GenSym(Type type_annotation = {}, Span span = {});\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Var, RelayExpr, VarNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(VarNode);\n};\n\n/*!\n * \\brief Returns \\p vor with the given properties. A null property denotes 'no change'.\n * Returns \\p var if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nVar WithFields(Var var, Optional<Id> opt_vid = Optional<Id>(),\n               Optional<Type> opt_type_annotation = Optional<Type>(),\n               Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n               Optional<Span> opt_span = Optional<Span>());\n\n/*!\n * \\brief Call corresponds to operator invocation.\n *  Corresponds to the operator in computational graph terminology.\n */\nclass Call;\n/*! \\brief Call container. */\nclass CallNode : public ExprNode {\n protected:\n  // CallNode uses own deleter to indirectly call non-recursive destructor\n  Object::FDeleter saved_deleter_;\n  static void Deleter_(Object* ptr);\n\n public:\n  /*!\n   * \\brief The operator(function) being invoked\n   *\n   *  - It can be tvm::Op which corresponds to the primitive operators.\n   *  - It can also be user defined functions (Function, GlobalVar, Var).\n   */\n  Expr op;\n\n  /*! \\brief The arguments(inputs) of the call */\n  tvm::Array<relay::Expr> args;\n\n  /*! \\brief The additional attributes */\n  Attrs attrs;\n\n  /*!\n   * \\brief The type arguments passed to polymorphic(template) function.\n   *\n   * This is the advance feature that is only used when the function is\n   * polymorphic. It is safe to be ignored in most cases. For example, in the\n   * following code, the type_args of addone call is [int].\n   *\n   * \\code\n   *\n   * template<typename T>\n   * T addone(T a) { return a + 1; }\n   *\n   * void main() {\n   *   int x = addone<int>(10);\n   * }\n   *\n   * \\endcode\n   */\n  tvm::Array<Type> type_args;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"op\", &op);\n    v->Visit(\"args\", &args);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"type_args\", &type_args);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const CallNode* other, SEqualReducer equal) const {\n    // skip type_args check for primitive ops.\n    equal->MarkGraphNode();\n    return equal(op, other->op) && equal(args, other->args) && equal(attrs, other->attrs) &&\n           (IsPrimitiveOp(op) || equal(type_args, other->type_args));\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(op);\n    hash_reduce(args);\n    hash_reduce(attrs);\n    if (!IsPrimitiveOp(op)) {\n      hash_reduce(type_args);\n    }\n  }\n\n  static constexpr const char* _type_key = \"relay.Call\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CallNode, ExprNode);\n  template <typename>\n  friend class runtime::ObjAllocatorBase;\n  friend class Call;\n};\n\nclass Call : public Expr {\n public:\n  /*!\n   * \\brief The destructor\n   */\n  ~Call();\n\n  /*!\n   * \\brief The constructor\n   * \\param op The operator will be invoked.\n   * \\param args The arguments of the call.\n   * \\param attrs The attributes of the call node.\n   * \\param type_args The type arguments passed to a polymorphic function.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL Call(Expr op, Array<Expr> args, Attrs attrs = Attrs(),\n               Array<Type> type_args = Array<Type>(), Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Call, RelayExpr, CallNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(CallNode);\n};\n\n/*!\n * \\brief Returns \\p call with the given properties. A null property denotes 'no change'.\n * Returns \\p call if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nCall WithFields(Call call, Optional<Expr> opt_op = Optional<Expr>(),\n                Optional<Array<Expr>> opt_args = Optional<Array<Expr>>(),\n                Optional<Attrs> opt_attrs = Optional<Attrs>(),\n                Optional<Array<Type>> opt_type_args = Optional<Array<Type>>(),\n                Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                Optional<Span> opt_span = Optional<Span>());\n\n/*!\n * \\brief Let binding that binds a local var and optionally a type annotation.\n *\n * \\note Let is useful to transform the program to be A-normal form.\n *  where each of the expression corresponds to a let binding.\n *\n *  For developers who are familar with the computational graph.\n *  Each of the let can be viewed as a operator node in the computational graph.\n *  Traversing the list of let bindings is similar to running\n * PostDFS-order(topo-order) traversal on the computational graph.\n */\nclass Let;\n/*! \\brief A binding of a sub-network. */\nclass LetNode : public ExprNode {\n protected:\n  // LetNode uses own deleter to indirectly call non-recursive destructor\n  Object::FDeleter saved_deleter_;\n  static void Deleter_(Object* ptr);\n\n public:\n  /*! \\brief The variable we bind to */\n  Var var;\n  /*! \\brief The value we bind var to */\n  Expr value;\n  /*! \\brief The body of the let binding */\n  Expr body;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"var\", &var);\n    v->Visit(\"value\", &value);\n    v->Visit(\"body\", &body);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const LetNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal.DefEqual(var, other->var) && equal(value, other->value) &&\n           equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce.DefHash(var);\n    hash_reduce(value);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"relay.Let\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LetNode, ExprNode);\n  template <typename>\n  friend class runtime::ObjAllocatorBase;\n  friend class Let;\n};\n\nclass Let : public Expr {\n public:\n  /*!\n   * \\brief The destructor\n   */\n  ~Let();\n\n  /*!\n   * \\brief The constructor\n   * \\param var The variable that is bound to.\n   * \\param value The value used to bind to the variable.\n   * \\param body The body of the let binding.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL Let(Var var, Expr value, Expr body, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Let, RelayExpr, LetNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(LetNode);\n};\n\n/*!\n * \\brief Returns \\p let with the given properties. A null property denotes 'no change'.\n * Returns \\p let if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nLet WithFields(Let let, Optional<Var> opt_var = Optional<Var>(),\n               Optional<Expr> opt_value = Optional<Expr>(),\n               Optional<Expr> opt_body = Optional<Expr>(),\n               Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n               Optional<Span> opt_span = Optional<Span>());\n\n/*!\n * \\brief Condition expression\n *\n * Unlike traditional statement `if`s, the if evalutes\n * to the result of the branch taken.\n *\n * let x = if (true) { 1 } else { 0 }; // x is 1\n * let y = if (false) { 1 } else { 0 }; // y is 0\n *\n * \\note This is similar to C's ternary operator.\n */\nclass If;\n/*! \\brief container of If */\nclass IfNode : public ExprNode {\n public:\n  /*! \\brief The condition */\n  Expr cond;\n  /*! \\brief The expression evaluated when condition is true. */\n  Expr true_branch;\n  /*! \\brief The expression evaluated when condition is false */\n  Expr false_branch;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"cond\", &cond);\n    v->Visit(\"true_branch\", &true_branch);\n    v->Visit(\"false_branch\", &false_branch);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const IfNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(cond, other->cond) && equal(true_branch, other->true_branch) &&\n           equal(false_branch, other->false_branch);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(cond);\n    hash_reduce(true_branch);\n    hash_reduce(false_branch);\n  }\n\n  static constexpr const char* _type_key = \"relay.If\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IfNode, ExprNode);\n};\n\nclass If : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param cond The condition of a if node.\n   * \\param true_branch The fall through branch\n   * \\param false_branch The branch for execution when condition is false.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL If(Expr cond, Expr true_branch, Expr false_branch, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(If, RelayExpr, IfNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IfNode);\n};\n\n/*!\n * \\brief Returns \\p if_expr with the given properties. A null property denotes 'no change'.\n * Returns \\p if_expr if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nIf WithFields(If if_expr, Optional<Expr> opt_cond = Optional<Expr>(),\n              Optional<Expr> opt_true_branch = Optional<Expr>(),\n              Optional<Expr> opt_false_branch = Optional<Expr>(),\n              Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n              Optional<Span> opt_span = Optional<Span>());\n\n/*! \\brief Get index-th field out of a tuple. */\nclass TupleGetItem;\nclass TupleGetItemNode : public ExprNode {\n public:\n  /*! \\brief The tuple Expression */\n  Expr tuple;\n  /*! \\brief which value to get */\n  int index;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"tuple_value\", &tuple);\n    v->Visit(\"index\", &index);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const TupleGetItemNode* other, SEqualReducer equal) const {\n    return equal(tuple, other->tuple) && equal(index, other->index);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(tuple);\n    hash_reduce(index);\n  }\n\n  static constexpr const char* _type_key = \"relay.TupleGetItem\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleGetItemNode, ExprNode);\n};\n\nclass TupleGetItem : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param tuple The tuple to get an element from.\n   * \\param index The index for extracting a value in the tuple.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL TupleGetItem(Expr tuple, int index, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleGetItem, RelayExpr, TupleGetItemNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(TupleGetItemNode);\n};\n\n/*!\n * \\brief Returns \\p tuple_get_item with the given properties. A null property denotes 'no change'.\n * Returns \\p tuple_get_item if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nTupleGetItem WithFields(TupleGetItem tuple_get_item, Optional<Expr> opt_tuple = Optional<Expr>(),\n                        Optional<Integer> opt_index = Optional<Integer>(),\n                        Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                        Optional<Span> opt_span = Optional<Span>());\n\n/*! \\brief Create a new Reference out of initial value. */\nclass RefCreate;\nclass RefCreateNode : public ExprNode {\n public:\n  /*! \\brief The initial value of the Reference. */\n  Expr value;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"value\", &value);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const RefCreateNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(value);\n  }\n\n  static constexpr const char* _type_key = \"relay.RefCreate\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RefCreateNode, ExprNode);\n};\n\nclass RefCreate : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param value The initial value of the reference.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL explicit RefCreate(Expr value, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(RefCreate, RelayExpr, RefCreateNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(RefCreateNode);\n};\n\n/*!\n * \\brief Returns \\p ref_create with the given properties. A null property denotes 'no change'.\n * Returns \\p ref_crete if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nRefCreate WithFields(RefCreate ref_create, Optional<Expr> opt_value = Optional<Expr>(),\n                     Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                     Optional<Span> opt_span = Optional<Span>());\n\n/*! \\brief Get value out of Reference. */\nclass RefRead;\nclass RefReadNode : public ExprNode {\n public:\n  /*! \\brief The Reference Expression. */\n  Expr ref;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"ref\", &ref);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const RefReadNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(ref, other->ref);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(ref);\n  }\n\n  static constexpr const char* _type_key = \"relay.RefRead\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RefReadNode, ExprNode);\n};\n\nclass RefRead : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param ref The reference where to read data.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL explicit RefRead(Expr ref, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(RefRead, RelayExpr, RefReadNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(RefReadNode);\n};\n\n/*!\n * \\brief Returns \\p ref_read with the given properties. A null property denotes 'no change'.\n * Returns \\p ref_read if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nRefRead WithFields(RefRead ref_read, Optional<Expr> opt_ref = Optional<Expr>(),\n                   Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                   Optional<Span> opt_span = Optional<Span>());\n\n/*! \\brief Set value of Reference. The whole expression evaluates to an Empty Tuple. */\nclass RefWrite;\nclass RefWriteNode : public ExprNode {\n public:\n  /*! \\brief The Reference Expression. */\n  Expr ref;\n  /*! \\brief The value to write into. */\n  Expr value;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"ref\", &ref);\n    v->Visit(\"value\", &value);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const RefWriteNode* other, SEqualReducer equal) const {\n    equal->MarkGraphNode();\n    return equal(ref, other->ref) && equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce(ref);\n    hash_reduce(value);\n  }\n\n  static constexpr const char* _type_key = \"relay.RefWrite\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RefWriteNode, ExprNode);\n};\n\nclass RefWrite : public Expr {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param ref The reference where data is write to.\n   * \\param value The value to write.\n   * \\param span The source span of the expression.\n   */\n  TVM_DLL RefWrite(Expr ref, Expr value, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(RefWrite, RelayExpr, RefWriteNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(RefWriteNode);\n};\n\n/*!\n * \\brief Returns \\p ref_write with the given properties. A null property denotes 'no change'.\n * Returns \\p ref_write if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nRefWrite WithFields(RefWrite ref_write, Optional<Expr> opt_ref = Optional<Expr>(),\n                    Optional<Expr> opt_value = Optional<Expr>(),\n                    Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                    Optional<Span> opt_span = Optional<Span>());\n\n/*!\n * \\brief Base class of the temporary expression.\n *\n * TempExprs are pass specific expression that can be\n * useful to define intermediate result in the\n * rewriting pass such as layout or type transformation.\n *\n * Subclass TempExprNode allows us to pattern match on\n * specific kind of TempExpr and use them for expression rewriting.\n *\n * TempExpr should only be used within a pass,\n */\nclass TempExprNode : public ExprNode {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~TempExprNode() {}\n  /*!\n   * \\brief Convert the expression to a normal(non-temp) Expr.\n   * \\return The corresponding normal(non-temp) expression.\n   */\n  virtual Expr Realize() const = 0;\n\n  static constexpr const char* _type_key = \"relay.TempExpr\";\n  static constexpr const bool _type_has_method_sequal_reduce = false;\n  static constexpr const bool _type_has_method_shash_reduce = false;\n  static constexpr const uint32_t _type_child_slots = 0;\n  TVM_DECLARE_BASE_OBJECT_INFO(TempExprNode, ExprNode);\n};\n\nclass TempExpr : public Expr {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(TempExpr, RelayExpr, TempExprNode);\n};\n\n}  // namespace relay\n\nnamespace runtime {\n\ntemplate <>\ntemplate <>\ninline ObjectPtr<relay::LetNode>\nObjAllocatorBase<SimpleObjAllocator>::make_object<relay::LetNode>() {\n  using Derived = SimpleObjAllocator;\n  using T = relay::LetNode;\n  using Handler = typename Derived::template Handler<T>;\n  static_assert(std::is_base_of<Object, T>::value, \"make can only be used to create Object\");\n  T* ptr = Handler::New(static_cast<Derived*>(this));\n  ptr->type_index_ = T::RuntimeTypeIndex();\n  ptr->saved_deleter_ = Handler::Deleter();\n  ptr->deleter_ = relay::LetNode::Deleter_;\n  return ObjectPtr<T>(ptr);\n}\n\ntemplate <>\ntemplate <>\ninline ObjectPtr<relay::CallNode>\nObjAllocatorBase<SimpleObjAllocator>::make_object<relay::CallNode>() {\n  using Derived = SimpleObjAllocator;\n  using T = relay::CallNode;\n  using Handler = typename Derived::template Handler<T>;\n  static_assert(std::is_base_of<Object, T>::value, \"make can only be used to create Object\");\n  T* ptr = Handler::New(static_cast<Derived*>(this));\n  ptr->type_index_ = T::RuntimeTypeIndex();\n  ptr->saved_deleter_ = Handler::Deleter();\n  ptr->deleter_ = relay::CallNode::Deleter_;\n  return ObjectPtr<T>(ptr);\n}\n\n}  // namespace runtime\n\n}  // namespace tvm\n#endif  // TVM_RELAY_EXPR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/expr_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/expr_functor.h\n * \\brief A more powerful visitor which enables defining arbitrary function\n * signatures with type based dispatch on first argument.\n */\n#ifndef TVM_RELAY_EXPR_FUNCTOR_H_\n#define TVM_RELAY_EXPR_FUNCTOR_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/node/functor.h>\n#include <tvm/relay/adt.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/relay/op.h>\n\n#include <deque>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief A dynamical functor that dispatches on in the first Expr argument.\n *  You can use this as a more powerful Visitor, since it allows you to\n *  define function signatures of Visit Function.\n *\n * \\sa tvm/ir_functor.h\n *\n * \\tparam FType function signiture\n *  This type is only defined for FType with function signature R(const Expr&,\n * Args...)\n */\ntemplate <typename FType>\nclass ExprFunctor;\n\n// functions to be overriden.\n#define EXPR_FUNCTOR_DEFAULT \\\n  { return VisitExprDefault_(op, std::forward<Args>(args)...); }\n\n#define RELAY_EXPR_FUNCTOR_DISPATCH(OP)                                                    \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {     \\\n    return self->VisitExpr_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass ExprFunctor<R(const Expr& n, Args...)> {\n private:\n  using TSelf = ExprFunctor<R(const Expr& n, Args...)>;\n  using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~ExprFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const Expr& n, Args... args) { return VisitExpr(n, std::forward<Args>(args)...); }\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitExpr(const Expr& n, Args... args) {\n    ICHECK(n.defined()) << \"Found null pointer node while traversing AST. The previous pass may \"\n                           \"have generated invalid data.\";\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitExpr_(const ConstantNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const TupleNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const VarNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const GlobalVarNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const FunctionNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const CallNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const LetNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const IfNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const OpNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const TupleGetItemNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const RefCreateNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const RefReadNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const RefWriteNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const ConstructorNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const MatchNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExprDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    throw;\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    RELAY_EXPR_FUNCTOR_DISPATCH(ConstantNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(TupleNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(VarNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(GlobalVarNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(FunctionNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(CallNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(LetNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(IfNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(OpNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(TupleGetItemNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(RefCreateNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(RefReadNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(RefWriteNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(ConstructorNode);\n    RELAY_EXPR_FUNCTOR_DISPATCH(MatchNode);\n    return vtable;\n  }\n};\n\n/*!\n * \\brief A simple visitor wrapper around ExprFunctor.\n *  Recursively visit the content.\n *\n * ExprVisitor treats Expr as dataflow graph,\n * and only visit each Expr node once.\n */\nclass ExprVisitor : public ::tvm::relay::ExprFunctor<void(const Expr& n)> {\n public:\n  void VisitExpr(const Expr& expr) override;\n  void VisitExpr_(const VarNode* op) override;\n  void VisitExpr_(const GlobalVarNode* op) override;\n  void VisitExpr_(const ConstantNode* op) override;\n  void VisitExpr_(const TupleNode* op) override;\n  void VisitExpr_(const FunctionNode* op) override;\n  void VisitExpr_(const CallNode* op) override;\n  void VisitExpr_(const LetNode* op) override;\n  void VisitExpr_(const IfNode* op) override;\n  void VisitExpr_(const OpNode* op) override;\n  void VisitExpr_(const TupleGetItemNode* op) override;\n  void VisitExpr_(const RefCreateNode* op) override;\n  void VisitExpr_(const RefReadNode* op) override;\n  void VisitExpr_(const RefWriteNode* op) override;\n  void VisitExpr_(const ConstructorNode* op) override;\n  void VisitExpr_(const MatchNode* op) override;\n  virtual void VisitType(const Type& t);\n  virtual void VisitClause(const Clause& c);\n  virtual void VisitPattern(const Pattern& c);\n  virtual void VisitSpan(const Span& span);\n\n protected:\n  // Internal visiting counter\n  std::unordered_map<const Object*, size_t> visit_counter_;\n};\n\n/*!\n * \\brief A wrapper around ExprFunctor which functionally updates the AST.\n *\n * ExprMutator treats Expr as dataflow graph, and only Mutate each Expr once.\n * The mutated results are memoized in a map and reused so that\n * local transformation on the dataflow preserves the graph structure.\n */\nclass ExprMutator : public ::tvm::relay::ExprFunctor<Expr(const Expr&)> {\n public:\n  /*!\n   * \\brief Mutate is alias for VisitExpr\n   * \\return expr.\n   */\n  Expr Mutate(const Expr& expr) { return this->VisitExpr(expr); }\n  Expr VisitExpr(const Expr& expr) override;\n  Expr VisitExpr_(const VarNode* op) override;\n  Expr VisitExpr_(const ConstantNode* op) override;\n  Expr VisitExpr_(const GlobalVarNode* op) override;\n  Expr VisitExpr_(const OpNode* op) override;\n  Expr VisitExpr_(const TupleNode* op) override;\n  Expr VisitExpr_(const FunctionNode* op) override;\n  Expr VisitExpr_(const CallNode* call_node) override;\n  Expr VisitExpr_(const LetNode* op) override;\n  Expr VisitExpr_(const IfNode* op) override;\n  Expr VisitExpr_(const TupleGetItemNode* op) override;\n  Expr VisitExpr_(const RefCreateNode* op) override;\n  Expr VisitExpr_(const RefReadNode* op) override;\n  Expr VisitExpr_(const RefWriteNode* op) override;\n  Expr VisitExpr_(const ConstructorNode* op) override;\n  Expr VisitExpr_(const MatchNode* op) override;\n\n  /*!\n   * \\brief Used to visit the types inside of expressions.\n   *\n   * Can be overloaded to transform the types in arbitrary\n   * ways, one way would be to define a sub-class of type\n   * visitor for types which transform them appropriately.\n   */\n  virtual Type VisitType(const Type& t);\n  virtual Clause VisitClause(const Clause& c);\n  virtual Pattern VisitPattern(const Pattern& c);\n\n protected:\n  /*! \\brief Internal map used for memoization. */\n  std::unordered_map<Expr, Expr, ObjectPtrHash, ObjectPtrEqual> memo_;\n};\n\n/*!\n * \\brief A wrapper around ExprVisitor which traverses the Dataflow Normal AST.\n *\n * MixedModeVisitor treats Expr as dataflow graph, and visits in post-DFS order\n *\n * MixedModeVisitor provides the same recursive API as ExprVisitor, and uses\n * recursion to traverse most forms of the IR, but under the hood it expands nested dataflow regions\n * of the graph and processes them iteratively to prevent stack overflows\n */\nclass MixedModeVisitor : public ::tvm::relay::ExprVisitor {\n public:\n  using ::tvm::relay::ExprFunctor<void(const Expr& n)>::VisitExpr_;\n\n  /*! \\brief The constructor of MixedModeVisitor\n   *  \\param visit_limit The number of times to allow visitation to a node. Usually 1, ocassionally\n   * higher (i.e., 2 for dead code elimiation), limited to 10 as a sanity check.\n   */\n  explicit MixedModeVisitor(int visit_limit = 1);\n\n  using ExprVisitor::VisitExpr_;\n\n  /*!\n   * \\brief VisitExpr is finalized to preserve call expansion of dataflow regions\n   */\n  void VisitExpr(const Expr& expr) final;\n  void VisitExpr_(const CallNode* op) override;\n  void VisitExpr_(const TupleNode* op) override;\n  void VisitExpr_(const TupleGetItemNode* op) override;\n\n protected:\n  /*!\n   * \\brief A function to apply when reaching a leaf of the graph non-recursively\n   */\n  virtual void VisitLeaf(const Expr& expr);\n  /*!\n   * \\brief A function to determine if an expression has already been visited or needs to be\n   * re-visited\n   */\n  virtual bool CheckVisited(const Expr& expr);\n  /*!\n   * \\brief The max number of times to visit a node\n   */\n  size_t visit_limit_;\n};\n\n/*! \\brief Non-recursive DFS Graph Traversal for Custom Rewriting Passes\n *\n * MixedModeMutator treats Expr as dataflow graph, and only Rewrites each Expr once.\n * The mutated results are memoized in a map and reused so that\n * local transformation on the dataflow preserves the graph structure.\n *\n * MixedModeMutator provides the same recursive API as ExprMutator, and uses\n * recursion to traverse most forms of the IR, but under the hood it expands nested dataflow regions\n * of the graph and processes them iteratatively to prevent stack overflows\n *\n * Uses Rewrite_ API of ExprRewriter for a cleaner split between recrusive and non-recursive\n * behavior.\n */\nclass MixedModeMutator : public ::tvm::relay::ExprMutator {\n public:\n  using ::tvm::relay::ExprFunctor<Expr(const Expr&)>::VisitExpr_;\n\n  MixedModeMutator(bool pre = false) : pre_{pre} {};\n  Expr VisitExpr(const Expr& expr) final;\n\n  virtual Expr DispatchVisitExpr(const Expr& expr);\n  Expr VisitExpr_(const TupleNode* op) final { return Rewrite(op); };\n  Expr VisitExpr_(const CallNode* call_node) final { return Rewrite(call_node); };\n  Expr VisitExpr_(const TupleGetItemNode* op) final { return Rewrite(op); };\n  /*!\n   *  \\brief Users should override Rewrite_ methods to implement their pass. Rewrite_ functions will\n   * be able to rewrite the op only with data about the original node `pre` and the same node with\n   * modified inputs `post` and should not recurse.\n   *\n   * \\param pre The expression node before rewriting.\n   * \\param post The expression with rewritten inputs.\n   */\n  virtual Expr Rewrite_(const TupleNode* pre, const Expr& post) { return post; }\n  virtual Expr Rewrite_(const CallNode* pre, const Expr& post) { return post; }\n  virtual Expr Rewrite_(const TupleGetItemNode* pre, const Expr& post) { return post; }\n\n protected:\n  bool pre_;\n  /*! \\brief Implement Rewrite API by calling ExprMutator's VisitExpr_(op) to get a `post` node with\n   * changed inputs.\n   */\n  template <typename T>\n  Expr Rewrite(const T* op) {\n    Expr post = ExprMutator::VisitExpr_(op);\n    return Rewrite_(op, post);\n  }\n\n  virtual void VisitLeaf(const Expr& expr);\n  virtual bool CheckVisited(const Expr& expr);\n};\n\n#define RELAY_EXPR_REWRITER_DISPATCH(OP)                                                   \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, const Expr& post) { \\\n    return self->Rewrite_(static_cast<const OP*>(n.get()), post);                          \\\n  });\n\n#define EXPR_REWRITER_REWRITE_DEFAULT \\\n  { return post; }\n\n/*! \\brief A non-iterating Expression Rewriter\n *\n *  ExprRewriter provides a Rewrite interface for modifying graphs in Post-DFS order.\n *\n * The expectation is that ExprRewriter objects will be passed to PostOrderRewrite, which will\n * non-recursively unroll the graph and call Rewriting on inputs. It will then pass the original\n * node, called `pre`, and a node recreated with any alterned inputs, called `post`, to the\n * ExprRewriter. The ExprRewriter can then use the information in those two nodes to do more complex\n * graph rewriting.\n */\nclass ExprRewriter {\n private:\n  using TSelf = ExprRewriter;\n  using FType = tvm::NodeFunctor<Expr(const ObjectRef& n, TSelf* self, const Expr& post)>;\n\n public:\n  /*! \\brief virtual destructor */\n  virtual ~ExprRewriter() {}\n  /*!\n   * \\brief Same as call.\n   * \\param pre The expression node before rewriting.\n   * \\param post The expression node with rewritten inputs.\n   * \\return The result of the call\n   */\n  Expr operator()(const Expr& pre, const Expr& post) { return Rewrite(pre, post); }\n  /*!\n   * \\brief The functor call.\n   * \\param pre The expression node before rewriting.\n   * \\param post The expression node with rewritten inputs.\n   * \\return The result of the call\n   */\n  virtual Expr Rewrite(const Expr& pre, const Expr& post) {\n    ICHECK(pre.defined());\n    static FType vtable = InitVTable();\n    return vtable(pre, this, post);\n  }\n  // Functions that can be overriden by subclass, should not recurse\n  virtual Expr Rewrite_(const VarNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const GlobalVarNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const ConstantNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const TupleNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const FunctionNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const CallNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const LetNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const IfNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const OpNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const TupleGetItemNode* pre,\n                        const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const RefCreateNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const RefReadNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const RefWriteNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const ConstructorNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n  virtual Expr Rewrite_(const MatchNode* pre, const Expr& post) EXPR_REWRITER_REWRITE_DEFAULT;\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    RELAY_EXPR_REWRITER_DISPATCH(ConstantNode);\n    RELAY_EXPR_REWRITER_DISPATCH(TupleNode);\n    RELAY_EXPR_REWRITER_DISPATCH(VarNode);\n    RELAY_EXPR_REWRITER_DISPATCH(GlobalVarNode);\n    RELAY_EXPR_REWRITER_DISPATCH(FunctionNode);\n    RELAY_EXPR_REWRITER_DISPATCH(CallNode);\n    RELAY_EXPR_REWRITER_DISPATCH(LetNode);\n    RELAY_EXPR_REWRITER_DISPATCH(IfNode);\n    RELAY_EXPR_REWRITER_DISPATCH(OpNode);\n    RELAY_EXPR_REWRITER_DISPATCH(TupleGetItemNode);\n    RELAY_EXPR_REWRITER_DISPATCH(RefCreateNode);\n    RELAY_EXPR_REWRITER_DISPATCH(RefReadNode);\n    RELAY_EXPR_REWRITER_DISPATCH(RefWriteNode);\n    RELAY_EXPR_REWRITER_DISPATCH(ConstructorNode);\n    RELAY_EXPR_REWRITER_DISPATCH(MatchNode);\n    return vtable;\n  }\n};\n\n/*! \\brief Non-recursive DFS Graph Traversal for Custom Rewriting Passes\n *\n * PostOrderRewrite does a non-recursive traversal of the graph in Post-DFS order and calls the\n * ExprRewriter's Rewrite functions on nodes once their inputs are rewritten. At each rewrite call,\n * PostOrderRewrite provides the original node and the node with altered inputs for use by the\n * ExprRewriter.\n */\nExpr PostOrderRewrite(const Expr& expr, ExprRewriter* rewriter);\n\n/*!\n * \\brief recursively visit the ir in post DFS order node, apply fvisit\n * Each node is guaranteed to be visited only once.\n * \\param node The ir to be visited.\n * \\param fvisit The visitor function to be applied.\n */\nvoid PostOrderVisit(const Expr& node, std::function<void(const Expr&)> fvisit);\n\n/*!\n * \\brief A struct to keep info of traversed expr in ExpandDataflow function\n */\nstruct v_info {\n  explicit v_info(Expr node_) : node{node_} {}\n  v_info(Expr node_, bool children_expanded_)\n      : node{node_}, children_expanded{children_expanded_} {};\n  Expr node{};\n  bool children_expanded{false};\n};\n\n/*!\n * \\brief A function to iteratively traverse dataflow regions of a graph\n *\n * ExpandDataflow manually manages a stack and performs DFS to determine the processing\n * order of nodes in an input graph.\n *\n * By default fexpand_expr implemented in a way that if it finds a dataflow node (Call, Tuple,\n * TupleGetItem), it checks if the arguments to that node need to be processed via fcheck_visited.\n * If so, the function pushes those arguments to the stack and continues iteratively to process\n * the top of the stack. When it finds a node that doesn't match the dataflow types, or a node who's\n * inputs have all been processed, it visits the current leaf via fvisit_leaf.\n *\n * This function should be used internally to other classes to implement mixed-mode traversals. The\n * expectation is that fvisit_leaf will perform recursive analysis within mixed-mode traversal if it\n * hits a non-dataflow node.\n *\n * fcheck_visited, fvisit_leaf and fexpand_expr are templated to encourage reusing.\n */\ntemplate <typename FCheckVisited, typename FVisitLeaf, typename FExpandExpr>\nvoid ExpandDataflow(Expr expr, FCheckVisited fcheck_visited, FVisitLeaf fvisit_leaf,\n                    FExpandExpr fexpand_expr) {\n  std::deque<v_info> stack;\n  auto fpush_to_stack = [&fcheck_visited, &stack](const Expr& expr) {\n    if (!fcheck_visited(expr)) {\n      stack.emplace_front(v_info(expr));\n    }\n  };\n\n  fpush_to_stack(expr);\n  while (stack.size() > 0) {\n    v_info* front = &stack.front();\n    if (fcheck_visited(front->node)) {\n      stack.pop_front();\n    } else if (front->children_expanded) {\n      fvisit_leaf(front->node);\n      // TODO(d-smirnov): this is for compatibility with current implementation of MixedModeVisitor\n      stack.pop_front();\n    } else {\n      front->children_expanded = true;\n      for (auto e : fexpand_expr(front->node)) {\n        fpush_to_stack(e);\n      }\n    }\n  }\n}\n\ntemplate <typename FCheckVisited, typename FVisitLeaf>\nvoid ExpandDataflow(Expr expr, FCheckVisited fcheck_visited, FVisitLeaf fvisit_leaf) {\n  auto fexpand_expr = [](const Expr& expr) {\n    std::vector<Expr> result;\n    if (const CallNode* op = expr.as<CallNode>()) {\n      if (op->op == Op::Get(\"call_lowered\")) {\n        // Ignore the intermediate tuple since this is purely a calling-convention detail\n        const auto* tuple_args = op->args[1].as<TupleNode>();\n        ICHECK(tuple_args)\n            << \"Expected second arg to call_lowered to be a Tuple of input arguments.\";\n        for (auto it = tuple_args->fields.rbegin(); it != tuple_args->fields.rend(); ++it) {\n          result.push_back(*it);\n        }\n        result.push_back(op->args[0]);\n      } else {\n        for (auto it = op->args.rbegin(); it != op->args.rend(); ++it) {\n          result.push_back(*it);\n        }\n      }\n      result.push_back(op->op);\n    } else if (const TupleNode* op = expr.as<TupleNode>()) {\n      for (auto it = op->fields.rbegin(); it != op->fields.rend(); ++it) {\n        result.push_back(*it);\n      }\n    } else if (const TupleGetItemNode* op = expr.as<TupleGetItemNode>()) {\n      result.push_back(op->tuple);\n    }\n    return result;\n  };\n  ExpandDataflow(expr, fcheck_visited, fvisit_leaf, fexpand_expr);\n}\n\nvoid ExpandANormalForm(const LetNode* op, std::function<void(const LetNode*)> pre_visit,\n                       std::function<void(const LetNode*)> post_visit);\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_EXPR_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/feature.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/feature.h\n * \\brief Detect features used in Expr/Module.\n */\n#ifndef TVM_RELAY_FEATURE_H_\n#define TVM_RELAY_FEATURE_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/relay/expr.h>\n\n#include <bitset>\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Different kinds of relay feature a program might use. */\nenum Feature : int {\n  fVar = 0,\n  fGlobalVar = 1,\n  fConstant = 2,\n  fTuple = 3,\n  fTupleGetItem = 4,\n  fFunction = 5,\n  fOp = 6,\n  fCall = 7,\n  fLet = 8,\n  fIf = 9,\n  fRefCreate = 10,\n  fRefRead = 11,\n  fRefWrite = 12,\n  fConstructor = 13,\n  fMatch = 14,\n  /*! \\brief Whether any non-atom fragment of the program is shared, making the program a graph. */\n  fGraph = 15,\n  /*! \\brief Whether there is local fixpoint in the program. */\n  fLetRec = 16\n};\n\nconstexpr size_t feature_count = 17;\n\n/*!\n * \\brief A finite set of Feature.\n */\nclass FeatureSet {\n public:\n  FeatureSet(const FeatureSet&) = default;\n  /*! \\brief A singleton set containing a single Feature. */\n  explicit FeatureSet(Feature ft) { bs_.set(static_cast<size_t>(ft)); }\n  explicit FeatureSet(const tvm::Array<tvm::Integer>& ft) {\n    for (Integer i : ft) {\n      *this += Feature(i.IntValue());\n    }\n  }\n  explicit operator Array<Integer>() const {\n    Array<Integer> ret;\n    for (size_t i = 0; i < feature_count; ++i) {\n      if (bs_[i]) {\n        ret.push_back(Integer(i));\n      }\n    }\n    return ret;\n  }\n  /*! \\brief A set that contain all the Feature. */\n  static FeatureSet All() {\n    FeatureSet fs;\n    fs.bs_.flip();\n    return fs;\n  }\n  /*! \\brief The empty set. Contain no Feature. */\n  static FeatureSet No() {\n    FeatureSet fs;\n    return fs;\n  }\n  template <typename T>\n  FeatureSet& operator+=(const T& rhs) {\n    bs_ |= FeatureSet(rhs).bs_;\n    return *this;\n  }\n  /*! \\brief Set union. */\n  template <typename T>\n  FeatureSet operator+(const T& rhs) const {\n    FeatureSet fs(*this);\n    fs += rhs;\n    return fs;\n  }\n  template <typename T>\n  FeatureSet& operator-=(const T& rhs) {\n    bs_ &= ~(FeatureSet(rhs)).bs_;\n    return *this;\n  }\n  /*! \\brief Set difference. */\n  template <typename T>\n  FeatureSet operator-(const T& rhs) const {\n    FeatureSet fs(*this);\n    fs -= rhs;\n    return fs;\n  }\n  /*!\n   * \\brief Is this a subset of rhs?\n   *\n   * \\param rhs another FeatureSet.\n   *\n   * \\return true only if this is a subset of rhs.\n   */\n  bool is_subset_of(const FeatureSet& rhs) const { return ((*this) - rhs).bs_.none(); }\n\n  /*!\n   * \\brief return a string representation.\n   */\n  std::string ToString() const;\n\n private:\n  std::bitset<feature_count> bs_;\n  FeatureSet() = default;\n  explicit FeatureSet(const std::bitset<feature_count>& bs) : bs_(bs) {}\n};\n\n/*!\n * \\brief Calculate the feature of the program.\n *\n * \\param expr The expression.\n *\n * \\return The FeatureSet.\n */\nFeatureSet DetectFeature(const RelayExpr& expr);\n\n/*!\n * \\brief Calculate the feature of the program.\n *\n * \\param mod The module.\n *\n * \\return The FeatureSet.\n */\nFeatureSet DetectFeature(const IRModule& mod);\n\n/*!\n * \\brief Calculate the feature of the program.\n *\n * \\param expr The expression.\n * \\param mod The module.\n *\n * \\return The FeatureSet.\n */\ninline FeatureSet DetectFeature(const Expr& expr, const IRModule& mod) {\n  return DetectFeature(expr) + DetectFeature(mod);\n}\n\n/*!\n * \\brief Check the feature of the program.\n *\n * \\param expr The expression.\n * \\param fs The feature set of the program.\n */\nvoid CheckFeature(const RelayExpr& expr, const FeatureSet& fs);\n\n/*!\n * \\brief Check the feature of the program.\n *\n * \\param mod The module.\n * \\param fs The feature set of the program.\n */\nvoid CheckFeature(const IRModule& mod, const FeatureSet& fs);\n\n/*!\n * \\brief Check the feature of the program.\n *\n * \\param expr The expression.\n * \\param mod The module.\n * \\param fs The feature set of the program.\n */\ninline void CheckFeature(const RelayExpr& expr, const IRModule& mod, const FeatureSet& fs) {\n  CheckFeature(expr, fs);\n  CheckFeature(mod, fs);\n}\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_FEATURE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/function.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/function.h\n * \\brief Relay Function.\n */\n#ifndef TVM_RELAY_FUNCTION_H_\n#define TVM_RELAY_FUNCTION_H_\n\n#include <tvm/ir/function.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Relay Function container\n * \\sa Function\n */\nclass FunctionNode : public BaseFuncNode {\n public:\n  /*! \\brief Function parameters */\n  tvm::Array<Var> params;\n  /*!\n   * \\brief\n   * The expression which represents the computation of the function,\n   * the expression may reference the parameters, and the type of it\n   * or sub-expressions may reference the type variables.\n   */\n  Expr body;\n  /*! \\brief User annotated return type of the function. */\n  Type ret_type;\n  /*!\n   * \\brief Type parameters of the function.\n   *  Enables the function to vary its type based on these.\n   *  This corresponds to template paramaters in c++'s terminology.\n   *\n   * \\note This can be usually empty for non-polymorphic functions.\n   */\n  tvm::Array<TypeVar> type_params;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"params\", &params);\n    v->Visit(\"body\", &body);\n    v->Visit(\"ret_type\", &ret_type);\n    v->Visit(\"type_params\", &type_params);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"virtual_device_\", &virtual_device_);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const FunctionNode* other, SEqualReducer equal) const {\n    // Important to make def equal first.\n    equal->MarkGraphNode();\n    return equal.DefEqual(params, other->params) &&\n           equal.DefEqual(type_params, other->type_params) && equal(ret_type, other->ret_type) &&\n           equal(attrs, other->attrs) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce->MarkGraphNode();\n    hash_reduce.DefHash(params);\n    hash_reduce.DefHash(type_params);\n    hash_reduce(ret_type);\n    hash_reduce(attrs);\n    hash_reduce(body);\n  }\n\n  /*!\n   * \\brief Return the derived function annotation of this expression.\n   *\n   * \\return The function type annotation.\n   * \\note The function type annotation can contain IncompleteType.\n   */\n  TVM_DLL FuncType func_type_annotation() const;\n\n  static constexpr const char* _type_key = \"relay.Function\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FunctionNode, BaseFuncNode);\n};\n\n/*!\n * \\brief Managed reference to FunctionNode.\n * \\sa FunctionNode\n */\nclass Function : public BaseFunc {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param params The parameters of the function.\n   * \\param body The body of the function.\n   * \\param ret_type The return type of the function.\n   * \\param ty_params The type parameters.\n   * \\param attrs Additional function attributes.\n   * \\param span The span of the function.\n   */\n  TVM_DLL Function(tvm::Array<Var> params, Expr body, Type ret_type, tvm::Array<TypeVar> ty_params,\n                   tvm::DictAttrs attrs = NullValue<DictAttrs>(), Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Function, BaseFunc, FunctionNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(FunctionNode);\n};\n\n/*!\n * \\brief Returns \\p function with the given properties. A null property denotes 'no change'.\n * Returns \\p function if all properties are unchanged. Otherwise, returns a copy with the new\n * fields.\n */\nFunction WithFields(Function function, Optional<Array<Var>> opt_params = Optional<Array<Var>>(),\n                    Optional<Expr> opt_body = Optional<Expr>(),\n                    Optional<Type> opt_ret_type = Optional<Type>(),\n                    Optional<Array<TypeVar>> opt_ty_params = Optional<Array<TypeVar>>(),\n                    Optional<DictAttrs> opt_attrs = Optional<DictAttrs>(),\n                    Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),\n                    Optional<Span> opt_span = Optional<Span>());\n\n/*\n * \\brief Returns the Relay FunctionNode represented by base_func if it should be optimized,\n * otherwise returns nullptr.\n *\n * This means returns nullptr:\n *  - For PrimFuncs, since not Relay Functions.\n *  - For Functions marked for external compilation (with \"Compiler\").\n *  - For Functions marked as already having an external definition (with \"ExternalSymbol\").\n *  - For Functions marked as not to be optimized (with \"SkipOptimization\").\n *\n * TODO(mbs): Audit all enumerations of IRModule::functions to use this or some family of such.\n */\nconst FunctionNode* AsOptimizableFunctionNode(const BaseFunc& base_func);\n\n/*!\n * \\brief namespace of the attributes that can be attached to a relay::Function.\n */\nnamespace attr {\n\n/*!\n * \\brief Mark the function as representing a sub-graph which is to be lowered or compiled as\n * a unit. For example, the function may represent a kernel which TVM will lower to a PrimFunc.\n * If present should be bound to \\p Integer(1). May be accompanied by \"Compiler\", see below.\n * The function body should be considered opaque by Relay, and many passes simply ignore these\n * functions.\n *\n * Type: Integer\n */\nconstexpr const char* kPrimitive = \"Primitive\";\n\n/*!\n * \\brief Mark the function as externally implemented, ie bound in a runtime::Module within the\n * IRModule's \"external_mods\" attribute. If present should be bound to \\p Integer(1). Generally\n * the only attribute when present.\n *\n * Type: Integer\n */\nconstexpr const char* kExtern = \"Extern\";\n\n/*!\n * \\brief Indicates the name of the external codegen 'compiler' that should be used to lower\n * or compile the function other than TVM's default lowering pipeline. The name may correspond\n * to a TargetKind name. There may be a global function registered under 'relay.ext.{name}'.\n *\n * Type: String\n */\nconstexpr const char* kCompiler = \"Compiler\";\n\n/*! \\brief Indicate if the function is a closure. */\nconstexpr const char* kClosure = \"Closure\";\n/*! \\brief Store a Var to parameter/Constant mapping on a Function. */\nconstexpr const char* kParams = \"__params__\";\n/*! \\brief Mark if the function should be avoided being optimized. */\nconstexpr const char* kSkipOptimization = \"SkipOptimization\";\n/*! \\brief Treat the function as a composite operator. */\nconstexpr const char* kComposite = \"Composite\";\n/*! \\brief Mark the function to be inlined. */\nconstexpr const char* kInline = \"Inline\";\n/*! \\brief Indicate the function was created by the Pattern Partitioning Pass. */\nconstexpr const char* kPartitionedFromPattern = \"PartitionedFromPattern\";\n/*! \\brief Mark the function as only composed of reshape operations. */\nconstexpr const char* kReshapeOnly = \"relay.reshape_only\";\n\n}  // namespace attr\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_FUNCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/interpreter.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/interpreter.h\n * \\brief An interpreter for Relay.\n *\n * This file implements a simple reference interpreter for Relay programs.\n * Given a Relay module, and a Relay expression it produces a value.\n *\n * The interpreter's values are a naive representation of the values that\n * can be produced by a Relay program and are exposed via TVM's object\n * protocol to Python for introspection and debugging.\n *\n * The interpreter's intent is to serve as a reference semantics for the Relay IR,\n * as well as for debugging and testing.\n */\n#ifndef TVM_RELAY_INTERPRETER_H_\n#define TVM_RELAY_INTERPRETER_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/relay/expr.h>\n#include <tvm/runtime/container/closure.h>\n#include <tvm/runtime/object.h>\n#include <tvm/target/target.h>\n\n#include <unordered_set>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief The container type of Closures used by the interpreter. */\nclass InterpreterClosureObj : public runtime::ClosureObj {\n public:\n  /*! \\brief The set of free variables in the closure.\n   *\n   * These are the captured variables which are required for\n   * evaluation when we call the closure.\n   */\n  tvm::Map<Var, ObjectRef> env;\n  /*! \\brief The function which implements the closure.\n   *\n   * \\note May reference the variables contained in the env.\n   */\n  Function func;\n\n  InterpreterClosureObj() {}\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"env\", &env);\n    v->Visit(\"func\", &func);\n  }\n\n  static constexpr const char* _type_key = \"interpreter.Closure\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(InterpreterClosureObj, runtime::ClosureObj);\n};\n\nclass InterpreterClosure : public runtime::Closure {\n public:\n  TVM_DLL InterpreterClosure(tvm::Map<Var, ObjectRef> env, Function func);\n  TVM_DEFINE_OBJECT_REF_METHODS(InterpreterClosure, runtime::Closure, InterpreterClosureObj);\n};\n\n/*! \\brief The container type of RecClosure. */\nclass RecClosureObj : public Object {\n public:\n  /*! \\brief The closure. */\n  InterpreterClosure clos;\n  /*! \\brief variable the closure bind to. */\n  Var bind;\n\n  RecClosureObj() {}\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"clos\", &clos);\n    v->Visit(\"bind\", &bind);\n  }\n\n  static constexpr const char* _type_key = \"interpreter.RecClosure\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RecClosureObj, Object);\n};\n\nclass RecClosure : public ObjectRef {\n public:\n  TVM_DLL RecClosure(InterpreterClosure clos, Var bind);\n  TVM_DEFINE_OBJECT_REF_METHODS(RecClosure, ObjectRef, RecClosureObj);\n};\n\nstruct RefValueObj : Object {\n  mutable ObjectRef value;\n\n  RefValueObj() {}\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"value\", &value); }\n\n  static constexpr const char* _type_key = \"relay.RefValue\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RefValueObj, Object);\n};\n\nclass RefValue : public ObjectRef {\n public:\n  TVM_DLL RefValue(ObjectRef val);\n  TVM_DEFINE_OBJECT_REF_METHODS(RefValue, ObjectRef, RefValueObj);\n};\n\nstruct ConstructorValueObj : Object {\n  int32_t tag;\n\n  tvm::Array<ObjectRef> fields;\n\n  /*! \\brief Optional field tracking ADT constructor. */\n  Constructor constructor;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"fields\", &fields);\n    v->Visit(\"constructor\", &constructor);\n  }\n\n  static constexpr const char* _type_key = \"relay.ConstructorValue\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstructorValueObj, Object);\n};\n\nclass ConstructorValue : public ObjectRef {\n public:\n  TVM_DLL ConstructorValue(int32_t tag, tvm::Array<ObjectRef> fields, Constructor construtor = {});\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ConstructorValue, ObjectRef, ConstructorValueObj);\n};\n\n/*!\n * \\brief Returns a packed function over Relay expressions which will evaluate \\p expr\n * applied to those arguments, where \\p expr is w.r.t. the definitions in \\p mod.\n *\n * This function is intended to support the Python 'debug' executor.\n *\n * The given \\p expr should have function type. The given \\p mod may be empty or\n * undefined if \\p expr is self-contained. Relay arguments passed to the result\n * packed function must be constants, references, or constructors/tuples over such.\n * As much work as possible is done while constructing the result packed function, and\n * that function may be reasonably efficiently applied multiple times without redoing\n * unnecessary work.\n *\n * Primitives are lowered and compiled to packed functions for execution on \\p device\n * with properties given by \\p target. All other Relay constructs are interpreted.\n *\n * The interpreter is intended to be a 'reference' implementation of the Relay semantics\n * for testing and interactive use. It is not intended to be particularly efficient.\n *\n * \\param mod A module containing definitions which can be referenced from\n * \\p expr. May be empty or undefined.\n * \\param expr An expression of function type to evaluate. May reference definitions from \\p mod.\n * \\param device The device on which all primitives will be executed.\n * \\param target The compiler target flag for compiling primitives.\n * \\return A packed function that takes an array of Relay expressions and returns the\n * result of applying \\p expr to those arguments.\n */\nTypedPackedFunc<ObjectRef(Array<Expr>)> EvalFunction(IRModule mod, Expr expr, Device device,\n                                                     Target target);\n\n/*!\n * \\brief Evaluates \\p expr and returns its result.\n *\n * This function is intended to support TVM constant evaluation.\n *\n * \\param expr An expression to evaluate.\n * \\param type_definitions Global type definitions which \\p expr may references.\n * \\param import_set Already imported external modules.\n * \\param device The device on which all primitives will be executed.\n * \\param target The compiler target flag for compiling primitives.\n * \\param attrs Attributes for the expression to be evaluated with\n * @return The object representing the result.\n */\nObjectRef Eval(Expr expr, Map<GlobalTypeVar, TypeData> type_definitions,\n               std::unordered_set<String> import_set, Device device, Target target,\n               Map<String, ObjectRef> attrs = {});\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_INTERPRETER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/op.h\n * \\brief Primitive operators(builtin intrinsics).\n */\n#ifndef TVM_RELAY_OP_H_\n#define TVM_RELAY_OP_H_\n\n#include <tvm/ir/op.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n\nnamespace tvm {\nnamespace relay {\n\nusing Op = tvm::Op;\nusing OpNode = tvm::OpNode;\n\n#define RELAY_REGISTER_OP(OpName) TVM_REGISTER_OP(OpName)\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/op_attr_types.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/op_attr_types.h\n * \\brief The Expr and related elements in DataFlow construction.\n */\n#ifndef TVM_RELAY_OP_ATTR_TYPES_H_\n#define TVM_RELAY_OP_ATTR_TYPES_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n#include <tvm/target/generic_func.h>\n#include <tvm/target/target.h>\n#include <tvm/te/schedule.h>\n#include <tvm/te/tensor.h>\n#include <tvm/tir/data_layout.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\nusing tir::BijectiveLayoutNode;\nusing tir::Layout;\nusing tir::LayoutAxis;\n\n/*! \\brief operator pattern used in graph fusion */\nenum OpPatternKind {\n  // Elementwise operation\n  kElemWise = 0,\n  // Broadcasting operator, can always map output axis to the input in order.\n  // for example :code:`out[i, ax1, j, ax2] = input[i, j]`.\n  // Note that the axis need to be in order so transpose is not a bcast operator.\n  kBroadcast = 1,\n  // Injective operator, can always injectively map output axis to a single input axis.\n  // All injective operator can still be safely fused to injective and reduction.\n  kInjective = 2,\n  // Communicative reduction operator.\n  kCommReduce = 3,\n  // Complex operation, can still fuse elemwise operations into its output.\n  // but cannot chain another complex op\n  kOutEWiseFusable = 4,\n  // The pattern for tuple nodes. Can fuse into subsequent injective ops,\n  // but treated specially\n  kTuple = 7,\n  // Opaque operation, cannot fuse anything.\n  kOpaque = 8\n};\n\n/*! \\brief the operator pattern */\nusing TOpPattern = int;\n\n/*!\n * \\brief Whether operator is stateful or contain internal state.\n *\n * All the primitive ops we registered so far are pure.\n * This attribute is left for potential future compatible reasons.\n * We can always work around the stateful ops by adding an additional\n * handle argument and return it.\n */\nusing TOpIsStateful = bool;\n\n/*!\n * \\brief Mark the operator as non-computational.\n */\nusing TNonComputational = bool;\n\n/*!\n * \\brief Mark the operator as reshape op of its first input\n *        and can be turned into a nop when the first input and output\n *        shares the same piece of memory.\n */\nusing TReshapeOp = bool;\n\n/*!\n * \\brief Mark the operator whether output shape is data dependent.\n */\nusing TShapeDataDependent = Array<Integer>;\n\n/*!\n * \\brief Computation description interface.\n *\n * \\note This function have a special convention\n *  for functions with tuple input/output.\n *\n *  So far we restrict tuple support to the following case:\n *  - Function which takes a single tuple as input.\n *  - Function which outputs a single tuple.\n *\n *  In both cases, the tuple is flattened as array.\n *\n * \\param attrs The attribute of the primitive\n * \\param inputs The input tensors.\n * \\param out_type The output type information\n &                 these are always placeholders.\n * \\return The output compute description of the operator.\n */\nusing FTVMCompute = runtime::TypedPackedFunc<Array<te::Tensor>(\n    const Attrs& attrs, const Array<te::Tensor>& inputs, const Type& out_type)>;\n\n/*!\n * \\brief Build the computation schedule for\n *  op whose root is at current op.\n *\n * \\param attrs The attribute of the node.\n * \\param outs The output tensors.\n * \\param target The build target.\n * \\return schedule The computation schedule.\n */\nusing FTVMSchedule = runtime::TypedPackedFunc<te::Schedule(\n    const Attrs& attrs, const Array<te::Tensor>& outs, const Target& target)>;\n\n/*!\n * \\brief Generate the strategy of operators. This function is a generic\n * function and can be re-defined for different targets.\n *\n * The function signature of generic function is:\n *   OpStrategy(const Attrs& attrs, const Array<Tensor>& inputs,\n *              const Type& out_type, const Target& target)\n */\nusing FTVMStrategy = GenericFunc;\n\n/*!\n * \\brief Alternate the layout of operators or replace the\n *  operator with other expressions. This function will be invoked\n *  in AlterOpLayout pass.\n * \\param attrs The attribute of the original node.\n * \\param args The input symbols of the original node.\n * \\param tinfos An array of placeholders, use for getting the inferred shape\n *               and dtype of the inputs.\n * \\return new_expr The modified expression.\n */\nusing FTVMAlterOpLayout =\n    runtime::TypedPackedFunc<Expr(const Attrs& attrs, const Array<Expr>& args,\n                                  const Array<te::Tensor>& tinfos, const Type& out_type)>;\n\n/*!\n * \\brief Convert the layout of operators or replace the\n *  operator with other expressions. This function will be invoked\n *  in ConvertLayout pass.\n * \\param attrs The attribute of the original node.\n * \\param inputs The input symbols of the original node.\n * \\param tinfos An array of placeholders, use for getting the inferred shape\n *               and dtype of the inputs.\n * \\param desired_layouts Specify an array of desired layouts for each input.\n *                        For example a conv2d op: Array(\"NHWC\", \"OHWI\"), this\n *                        specifies the desired layout for data then kernel.\n * \\return new_expr The modified expression.\n */\nusing FTVMConvertOpLayout = runtime::TypedPackedFunc<Expr(\n    const Attrs& attrs, const Array<Expr>& args, const Array<te::Tensor>& tinfos,\n    const Array<String>& desired_layouts)>;\n/*!\n * \\brief Legalizes an expression with another expression. This function will be\n *  invoked in Legalize pass. It is a target-dependent pass.\n * \\param attrs The attribute of the original node.\n * \\param args The input symbols of the original node.\n * \\param arg_types An array of placeholders, use for getting the inferred shape\n *               and dtype of the inputs.\n * \\return new_expr The modified expression.\n */\nusing FTVMLegalize = runtime::TypedPackedFunc<Expr(const Attrs& attrs, const Array<Expr>& args,\n                                                   const Array<tvm::relay::Type>& arg_types)>;\n\n/*!\n * \\brief Annotates an expression to indicate if an op should be compiled using\n * the given compiler/target.\n * \\param expr The original expr.\n * \\return true if this op should be registered to invoke a specific compiler\n * for codegen, otherwise, false.\n */\nusing FTVMAnnotateTarget = runtime::TypedPackedFunc<bool(const Expr& expr)>;\n\n/*!\n * \\brief Forward rewriting rule for a specific op.\n *\n * \\param ref_call The reference old call type to be rewritten.\n *                 We can make use of the op and type information.\n * \\param new_args The new arguments (some of them could be TempExpr).\n * \\param ctx  Optional context information about ref_call.\n * \\return The rewriten result call, can also return nullptr,\n *         which indicate the rewriter should use the default fallback\n *         rule that realizes all its input and compose the call.\n *\n * \\note When we register the function, we can register\n *       a different signature with ctx to be a specific node type.\n */\nusing FForwardRewrite = runtime::TypedPackedFunc<Expr(\n    const Call& ref_call, const Array<Expr>& new_args, const ObjectRef& ctx)>;\n\n/*!\n * \\brief Gradient for a specific op.\n *\n * \\param orig_call the original Expr.\n * \\param output_grad the gradient of the Expr.\n * \\return the gradient for each parameters.\n */\nusing FPrimalGradient =\n    runtime::TypedPackedFunc<tvm::Array<Expr>(const Expr& orig_call, const Expr& output_grad)>;\n\n/*!\n * \\brief The codegeneration strategy for dynamic dimensions.\n */\nenum AnyCodegenStrategy {\n  /*! \\brief The default strategy of using completely variable dimensions. */\n  kVariableDimensions\n};\n\n/*! \\brief A runtime representation of shape. */\nusing Shape = Array<IndexExpr>;\n\nusing FShapeFunc = runtime::TypedPackedFunc<Array<te::Tensor>(\n    const Attrs& attrs, const Array<te::Tensor>& inputs, const Array<IndexExpr>& out_ndims)>;\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_ATTR_TYPES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/op_strategy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/op_strategy.h\n * \\brief The Relay operator Strategy and related data structure.\n */\n\n#ifndef TVM_RELAY_OP_STRATEGY_H_\n#define TVM_RELAY_OP_STRATEGY_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/target/target.h>\n#include <tvm/te/schedule.h>\n#include <tvm/te/tensor.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Operator implementation that includes compute and schedule function.\n */\nclass OpImplementationNode : public Object {\n public:\n  /*! \\brief Compute function */\n  FTVMCompute fcompute;\n  /*! \\brief Schedule function */\n  FTVMSchedule fschedule;\n  /*! \\brief Name of the implementation */\n  String name;\n  /*! \\brief Priority level */\n  int plevel;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"plevel\", &plevel);\n  }\n\n  static constexpr const char* _type_key = \"relay.OpImplementation\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpImplementationNode, Object);\n};\n\n/*!\n * \\brief Operator implementation class.\n */\nclass OpImplementation : public ObjectRef {\n public:\n  /*!\n   * \\brief Invoke the operator compute function.\n   * \\param attrs The attribute of the primitive\n   * \\param inputs The input tensors.\n   * \\param out_type The output type information.\n   * \\return The output compute description of the operator.\n   */\n  TVM_DLL Array<te::Tensor> Compute(const Attrs& attrs, const Array<te::Tensor>& inputs,\n                                    const Type& out_type);\n  /*!\n   * \\brief Build the computation schedule.\n   * \\param attrs The attribute of the node.\n   * \\param outs The output tensors.\n   * \\param target The build target.\n   * \\return The computation schedule.\n   */\n  TVM_DLL te::Schedule Schedule(const Attrs& attrs, const Array<te::Tensor>& outs,\n                                const Target& target);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(OpImplementation, ObjectRef, OpImplementationNode);\n};\n\n/*!\n * \\brief Specialized implementations for operators under certain conditions.\n */\nclass OpSpecializationNode : public Object {\n public:\n  /*! \\brief List of implementations. */\n  Array<OpImplementation> implementations;\n  /*! \\brief Condition to enable the specialization.\n   *    Could be undefined to represent generic case. */\n  te::SpecializedCondition condition;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"implementations\", &implementations);\n  }\n\n  static constexpr const char* _type_key = \"relay.OpSpecialization\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpSpecializationNode, ExprNode);\n};\n\n/*!\n * \\brief Operator specialization class.\n */\nclass OpSpecialization : public ObjectRef {\n public:\n  /*!\n   * \\brief Add an implementation.\n   * \\param fcompute Compute function\n   * \\param fschedule Schedule function\n   * \\param name Name of the implementation\n   * \\param plevel Priority level of the implementation\n   */\n  TVM_DLL void AddImplementation(FTVMCompute fcompute, FTVMSchedule fschedule, String name,\n                                 int plevel);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(OpSpecialization, ObjectRef, OpSpecializationNode);\n};\n\n/*!\n * \\brief Operator strategy to choose implementation.\n */\nclass OpStrategyNode : public Object {\n public:\n  /*! \\brief List of operator specializations. */\n  Array<OpSpecialization> specializations;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"specializations\", &specializations); }\n\n  static constexpr const char* _type_key = \"relay.OpStrategy\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpStrategyNode, ExprNode);\n};\n\n/*!\n * \\brief Operator strategy class.\n */\nclass OpStrategy : public ObjectRef {\n public:\n  /*!\n   * \\brief Add an implementation.\n   * \\param fcompute Compute function\n   * \\param fschedule Schedule function\n   * \\param name Name of the implementation\n   * \\param plevel Priority level of the implementation\n   */\n  TVM_DLL void AddImplementation(FTVMCompute fcompute, FTVMSchedule fschedule, String name,\n                                 int plevel);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(OpStrategy, ObjectRef, OpStrategyNode);\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_STRATEGY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/pattern_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/pattern_functor.h\n * \\brief A more powerful visitor on ADT patterns that enables defining\n * arbitrary function signatures with type-based dispatch on first argument.\n */\n#ifndef TVM_RELAY_PATTERN_FUNCTOR_H_\n#define TVM_RELAY_PATTERN_FUNCTOR_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/node/functor.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include \"./adt.h\"\n#include \"./expr.h\"\n#include \"./op.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief A dynamical functor on ADT patterns that dispatches on its first argument.\n *  You can use this as a more powerful visitor, since it allows you to\n *  define the types of further arguments to VisitPattern.\n *\n * \\sa tvm/ir_functor.h\n *\n * \\tparam FType function signiture\n *  This type is only defined for FType with function signature R(const Pattern&,\n * Args...)\n */\ntemplate <typename FType>\nclass PatternFunctor;\n\n// functions to be overriden.\n#define PATTERN_FUNCTOR_DEFAULT \\\n  { return VisitPatternDefault_(op, std::forward<Args>(args)...); }\n\n#define RELAY_PATTERN_FUNCTOR_DISPATCH(OP)                                                    \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {        \\\n    return self->VisitPattern_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass PatternFunctor<R(const Pattern& n, Args...)> {\n private:\n  using TSelf = PatternFunctor<R(const Pattern& n, Args...)>;\n  using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~PatternFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const Pattern& n, Args... args) {\n    return VisitPattern(n, std::forward<Args>(args)...);\n  }\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitPattern(const Pattern& n, Args... args) {\n    ICHECK(n.defined());\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitPattern_(const PatternWildcardNode* op, Args... args) PATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitPattern_(const PatternVarNode* op, Args... args) PATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitPattern_(const PatternConstructorNode* op, Args... args) PATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitPattern_(const PatternTupleNode* op, Args... args) PATTERN_FUNCTOR_DEFAULT;\n  virtual R VisitPatternDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    throw;\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternWildcardNode);\n    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternVarNode);\n    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternConstructorNode);\n    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternTupleNode);\n    return vtable;\n  }\n};\n\n/*! \\brief A simple visitor wrapper around PatternFunctor.\n *\n * Exposes two visitors with default traversal strategies, one\n * which doesn't compute a result but can mutate internal state,\n * and another which functionally builds a new pattern.\n */\nclass PatternVisitor : public ::tvm::relay::PatternFunctor<void(const Pattern& n)> {\n public:\n  void VisitPattern_(const PatternWildcardNode* op) override;\n  void VisitPattern_(const PatternVarNode* op) override;\n  void VisitPattern_(const PatternConstructorNode* op) override;\n  void VisitPattern_(const PatternTupleNode* op) override;\n  virtual void VisitType(const Type& t);\n  virtual void VisitVar(const Var& v);\n  virtual void VisitConstructor(const Constructor& c);\n};\n\n/*! \\brief A wrapper around ExprFunctor which functionally updates the AST.\n *\n * ExprMutator uses memoization and self return in order to amortize\n * the cost of using functional updates.\n */\nclass PatternMutator : public ::tvm::relay::PatternFunctor<Pattern(const Pattern&)> {\n public:\n  Pattern Mutate(const Pattern& pat);\n  Pattern VisitPattern_(const PatternWildcardNode* op) override;\n  Pattern VisitPattern_(const PatternVarNode* op) override;\n  Pattern VisitPattern_(const PatternConstructorNode* op) override;\n  Pattern VisitPattern_(const PatternTupleNode* op) override;\n  /*! \\brief Used to visit the types inside of patterns.\n   *\n   * Can be overloaded to transform the types in arbitrary\n   * ways, one way would be to define a sub-class of type\n   * visitor for types which transform them appropriately.\n   */\n  virtual Type VisitType(const Type& t);\n  /*! \\brief Used to visit the vars inside of patterns. */\n  virtual Var VisitVar(const Var& v);\n  /*! \\brief Used to visit the vars inside of patterns. */\n  virtual Constructor VisitConstructor(const Constructor& c);\n\n private:\n  std::unordered_map<Var, Var, ObjectPtrHash, ObjectPtrEqual> var_map_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_PATTERN_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/qnn/attrs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/qnn/attrs.h\n * \\brief Auxiliary attributes for qnn operators.\n */\n#ifndef TVM_RELAY_QNN_ATTRS_H_\n#define TVM_RELAY_QNN_ATTRS_H_\n\n#include <tvm/ir/attrs.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\nnamespace qnn {\n\n/*! \\brief Attribute for requantize operator */\nstruct RequantizeAttrs : public tvm::AttrsNode<RequantizeAttrs> {\n  int axis;\n  std::string rounding;\n  std::string compute_dtype;\n  DataType out_dtype;\n\n  TVM_DECLARE_ATTRS(RequantizeAttrs, \"relay.attrs.RequantizeAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The output channel axis for channel wise quantization. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n    TVM_ATTR_FIELD(rounding).set_default(\"None\").describe(\n        \"Defines the rounding direction when the value is midway between\"\n        \"two representable values. There are two supported modes - UPWARD\"\n        \"or TONEAREST. Both modes behave exactly same except at the\"\n        \"midpoints between the two representable values. At the midpoint,\"\n        \"UPWARD rounds towards positive infinity (for example -1.5 will be\"\n        \"rounded to -1). TONEAREST is the standard rounding where the\"\n        \"value is rounded away from zero at midpoints (for example, -1.5\"\n        \"rounds to -2). More context can be found at following gblic manual\"\n        \"https://www.gnu.org/software/libc/manual/html_node/Rounding.html.\");\n    TVM_ATTR_FIELD(compute_dtype)\n        .set_default(\"None\")\n        .describe(\n            \"Specifies the data type used during requantize. Supported \"\n            \"options: \\\"int64\\\", \\\"float32\\\", \\\"float64\\\"\");\n    TVM_ATTR_FIELD(out_dtype)\n        .set_default(NullValue<DataType>())\n        .describe(\"Output data type, set to explicit type under mixed precision setting\");\n  }\n};\n\n/*! \\brief Attribute for quantize operator */\nstruct QuantizeAttrs : public tvm::AttrsNode<QuantizeAttrs> {\n  DataType out_dtype;\n  int axis;\n\n  TVM_DECLARE_ATTRS(QuantizeAttrs, \"relay.attrs.QuantizeAttrs\") {\n    TVM_ATTR_FIELD(out_dtype).describe(\"Output data type, can be one of [int8 or uint8].\");\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The output channel axis for channel wise quantization. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n  }\n};\n\nstruct SimulatedQuantizeAttrs : public tvm::AttrsNode<SimulatedQuantizeAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(SimulatedQuantizeAttrs, \"relay.attrs.SimulatedQuantizeAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The output channel axis for channel wise quantization. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n  }\n};\n\n/*! \\brief Attribute for dequantize operator */\nstruct DequantizeAttrs : public tvm::AttrsNode<DequantizeAttrs> {\n  int axis;\n\n  TVM_DECLARE_ATTRS(DequantizeAttrs, \"relay.attrs.DequantizeAttrs\") {\n    TVM_ATTR_FIELD(axis)\n        .describe(\n            \"The channel axis for channel wise dequantization. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n  }\n};\n\n/*! \\brief Attribute for broadcast operator */\nstruct BroadcastAttrs : public tvm::AttrsNode<BroadcastAttrs> {\n  int lhs_axis;\n  int rhs_axis;\n\n  TVM_DECLARE_ATTRS(BroadcastAttrs, \"relay.attrs.BroadcastAttrs\") {\n    TVM_ATTR_FIELD(lhs_axis)\n        .describe(\n            \"The channel axis for channel wise broadcast. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n    TVM_ATTR_FIELD(rhs_axis)\n        .describe(\n            \"The channel axis for channel wise broadcast. Default value is -1,\"\n            \"which corresponds to the last axis.\")\n        .set_default(-1);\n  }\n};\n\n}  // namespace qnn\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_QNN_ATTRS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/qnn/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/qnn/transform.h\n *\n * This file implements a pass manager for QNN ops using Relay Pass manager.\n */\n#ifndef TVM_RELAY_QNN_TRANSFORM_H_\n#define TVM_RELAY_QNN_TRANSFORM_H_\n\n#include <tvm/relay/transform.h>\n#include <tvm/runtime/c_runtime_api.h>\n\nnamespace tvm {\nnamespace relay {\n\nusing relay::transform::Pass;\n\nnamespace qnn {\nnamespace transform {\n\n/*!\n * \\brief Legalizes a QNN expr. Contains specifically two types of Legalizations. First,\n * converts/Lowers an expression containing QNN ops to an expression containing only core Relay ops.\n * Each QNN op is lowered to a sequence of exisiting Relay ops. This is a target-independent pass.\n * One can register the lowering/transformation function for this op using FTVMQnnCanonicalize\n * attr_name for FTVMLegalize op attribute. Second, as opposed to Relay Legalize, this one legalizes\n * only QNN ops. One can register a transformation/legalization function for an op by using the\n * FTVMQnnLegalize attr_name for FTVMLegalize op attribute. The isolation of QNN and Relay Legalize\n * gives us separation of concerns, leading to a better software practice. The legalization can be\n * configured to happen per target.\n *\n * \\return The pass.\n */\nTVM_DLL Pass Legalize();\n\n}  // namespace transform\n\n}  // namespace qnn\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_QNN_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/runtime.h\n * \\brief Object representation of Runtime configuration and registry\n */\n#ifndef TVM_RELAY_RUNTIME_H_\n#define TVM_RELAY_RUNTIME_H_\n\n#include <dmlc/registry.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/ir/type.h>\n#include <tvm/ir/type_relation.h>\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/runtime/registry.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\ntemplate <typename, typename>\nclass AttrRegistry;\n\nnamespace relay {\n\n/*! \\brief Value used with Runtime::name to indicate the C++ runtime. */\nstatic constexpr const char* kTvmRuntimeCpp = \"cpp\";\n\n/*! \\brief Value used with Runtime::name to indicate the C runtime. */\nstatic constexpr const char* kTvmRuntimeCrt = \"crt\";\n\n/*!\n * \\brief Runtime information.\n *\n * This data structure stores the meta-data\n * about Runtimes which can be used to pass around information.\n *\n * \\sa Runtime\n */\nclass RuntimeNode : public Object {\n public:\n  /*! \\brief name of the Runtime */\n  String name;\n  /* \\brief Additional attributes storing meta-data about the Runtime. */\n  DictAttrs attrs;\n\n  /*!\n   * \\brief Get an attribute.\n   *\n   * \\param attr_key The attribute key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TObjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetAttrExample(const Runtime& runtime) {\n   *    auto value = runtime->GetAttr<Integer>(\"AttrKey\", 0);\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    return attrs.GetAttr(attr_key, default_value);\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"attrs\", &attrs);\n  }\n\n  bool SEqualReduce(const RuntimeNode* other, SEqualReducer equal) const {\n    return name == other->name && equal.DefEqual(attrs, other->attrs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name);\n    hash_reduce(attrs);\n  }\n\n  static constexpr const char* _type_key = \"Runtime\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(RuntimeNode, Object);\n};\n\n/*!\n * \\brief Managed reference class to RuntimeNode.\n * \\sa RuntimeNode\n */\nclass Runtime : public ObjectRef {\n public:\n  Runtime() = default;\n\n  /*!\n   * \\brief Create a new Runtime object using the registry\n   * \\throws Error if name is not registered\n   * \\param name The name of the Runtime.\n   * \\param attrs Attributes for the Runtime.\n   * \\return the new Runtime object.\n   */\n  TVM_DLL static Runtime Create(String name, Map<String, ObjectRef> attrs = {});\n\n  /*!\n   * \\brief List all registered Runtimes\n   * \\return the list of Runtimes\n   */\n  TVM_DLL static Array<String> ListRuntimes();\n\n  /*!\n   * \\brief List all options for a specific Runtime\n   * \\param name The name of the Runtime\n   * \\return Map of option name to type\n   */\n  TVM_DLL static Map<String, String> ListRuntimeOptions(const String& name);\n\n  /*! \\brief specify container node */\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Runtime, ObjectRef, RuntimeNode);\n\n private:\n  /*!\n   * \\brief Private Constructor\n   * \\param name The Runtime name\n   * \\param attrs Attributes to apply to this Runtime node\n   */\n  TVM_DLL Runtime(String name, DictAttrs attrs) {\n    auto n = make_object<RuntimeNode>();\n    n->name = std::move(name);\n    n->attrs = std::move(attrs);\n    data_ = std::move(n);\n  }\n};\n\n/*!\n * \\brief Helper structure to register Runtimes\n * \\sa TVM_REGISTER_Runtime\n */\nclass RuntimeRegEntry {\n public:\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline RuntimeRegEntry& add_attr_option(const String& key);\n\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\param default_value The default value of the key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline RuntimeRegEntry& add_attr_option(const String& key, ObjectRef default_value);\n\n  /*!\n   * \\brief Register or get a new entry.\n   * \\param name The name of the operator.\n   * \\return the corresponding entry.\n   */\n  TVM_DLL static RuntimeRegEntry& RegisterOrGet(const String& name);\n\n private:\n  /*! \\brief Internal storage of value types */\n  struct ValueTypeInfo {\n    std::string type_key;\n    uint32_t type_index;\n  };\n  std::unordered_map<std::string, ValueTypeInfo> key2vtype_;\n  /*! \\brief A hash table that stores the default value of each attr */\n  std::unordered_map<String, ObjectRef> key2default_;\n\n  /*! \\brief Index used for internal lookup of attribute registry */\n  uint32_t index_;\n\n  // the name\n  std::string name;\n\n  /*! \\brief Return the index stored in attr registry */\n  uint32_t AttrRegistryIndex() const { return index_; }\n  /*! \\brief Return the name stored in attr registry */\n  String AttrRegistryName() const { return name; }\n\n  /*! \\brief private constructor */\n  explicit RuntimeRegEntry(uint32_t reg_index) : index_(reg_index) {}\n\n  // friend class\n  template <typename>\n  friend class AttrRegistryMapContainerMap;\n  template <typename, typename>\n  friend class tvm::AttrRegistry;\n  friend class Runtime;\n};\n\ntemplate <typename ValueType>\ninline RuntimeRegEntry& RuntimeRegEntry::add_attr_option(const String& key) {\n  ICHECK(!key2vtype_.count(key)) << \"AttributeError: add_attr_option failed because '\" << key\n                                 << \"' has been set once\";\n\n  using ValueNodeType = typename ValueType::ContainerType;\n  // NOTE: we could further update the function later.\n  uint32_t value_type_index = ValueNodeType::_GetOrAllocRuntimeTypeIndex();\n\n  ValueTypeInfo info;\n  info.type_index = value_type_index;\n  info.type_key = runtime::Object::TypeIndex2Key(value_type_index);\n  key2vtype_[key] = info;\n  return *this;\n}\n\ntemplate <typename ValueType>\ninline RuntimeRegEntry& RuntimeRegEntry::add_attr_option(const String& key,\n                                                         ObjectRef default_value) {\n  add_attr_option<ValueType>(key);\n  key2default_[key] = default_value;\n  return *this;\n}\n\n// internal macros to make Runtime entries\n#define TVM_RUNTIME_REGISTER_VAR_DEF \\\n  static DMLC_ATTRIBUTE_UNUSED ::tvm::relay::RuntimeRegEntry& __make_##Runtime\n\n/*!\n * \\def TVM_REGISTER_RUNTIME\n * \\brief Register a new Runtime, or set attribute of the corresponding Runtime.\n *\n * \\param RuntimeName The name of registry\n *\n * \\code\n *\n *  TVM_REGISTER_RUNTIME(\"c\")\n *  .add_attr_option<String>(\"my_option\");\n *  .add_attr_option<String>(\"my_option_default\", String(\"default\"));\n *\n * \\endcode\n */\n#define TVM_REGISTER_RUNTIME(RuntimeName)                     \\\n  TVM_STR_CONCAT(TVM_RUNTIME_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::relay::RuntimeRegEntry::RegisterOrGet(RuntimeName)\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/transform.h\n * \\brief Relay specific transformation passes.\n */\n#ifndef TVM_RELAY_TRANSFORM_H_\n#define TVM_RELAY_TRANSFORM_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/relay/op.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/target/compilation_config.h>\n#include <tvm/target/target.h>\n#include <tvm/target/virtual_device.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\nusing Pass = tvm::transform::Pass;\nusing PassNode = tvm::transform::PassNode;\nusing PassInfo = tvm::transform::PassInfo;\nusing PassInfoNode = tvm::transform::PassInfoNode;\nusing PassContext = tvm::transform::PassContext;\nusing PassContextNode = tvm::transform::PassContextNode;\nusing Sequential = tvm::transform::Sequential;\n\n/*\n * \\brief Create a function pass.\n *\n * \\param pass_func The packed function that contains the optimization.\n * \\param opt_level The optimization level of the function pass.\n * \\param name The name of the function pass.\n * \\param required The list of the passes that the function pass is dependent on.\n *\n * \\return The created function pass.\n */\nTVM_DLL Pass CreateFunctionPass(\n    const runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)>& pass_func,\n    int opt_level, String name, tvm::Array<String> required);\n\n/*! \\brief Remove let-bound expressions which do not effect the program result.\n *\n * This pass will remove let bindings which are not referenced. If inline_once is True,\n * let bindings which are only referenced once will also be inlined.\n *\n * For example, this pass should turn `let a = 1; 2` into `2`,\n * as the value of the expression does not depend on a.\n *\n * As another example, `let a = 1; a` will be optimized into 1 if inline_once is True.\n *\n * If ignore_purity is False, possibly side-effecting expressions (such as memory allocation,\n * random number generation, reading/writing references, or calls to primitive or external\n * functions) are never elided or inlined. This is sound, but ignore_purity can be set to True\n * to suppress this check.\n *\n * The analysis is fairly conservative, for example it assumes all local functions\n * may be called more than once, any functions passed as arguments have side effects,\n * and so on.\n *\n * \\param inline_once whether or not to inline bindings used exactly once.\n * \\param ignore_purity whether to ignore whether expressions have side-effects\n *\n * \\return the pass.\n */\nTVM_DLL Pass DeadCodeElimination(bool inline_once = false, bool ignore_purity = false);\n\n/*!\n * \\brief Convert all expressions of TensorType into GradCell,\n * an algebraic data type defined in gradient.rly.\n *\n * This will delay or decrease memory usage. All calls to\n * ones, ones_like, zeros, zeros_like will not immediately instantiate a tensor in memory,\n * rather only instantiate if needed. It also defines + and * operation\n * between GradCell types which can increase performance when using\n * zero-filled or one-filled tensors, which is the case in reverse mode ad.\n *\n * \\return the pass\n */\nTVM_DLL Pass LazyGradientInit();\n\n/*!\n * \\brief Fold constant expressions.\n *\n *  Because of backward compatibility reason it skips QNN primitives from folding by default.\n *  There are some transformation passes like FakeQuantizationToInteger, which requires to keep QNN\n *  primitives for constant subgraphs. Uncontrolled constant folding of QNN primitives may break\n *  applicability of FakeQuantizationToInteger. We suggest to use FoldConstant pass with none\n *  default fold_qnn=True value only when all other QNN sensitive passes were already applied.\n *\n * \\param fold_qnn Whether to fold constants for QNN operations.\n *\n * \\return The pass.\n */\nTVM_DLL Pass FoldConstant(bool fold_qnn = false);\n\n/*!\n * \\brief Split function with huge number of arguments to smaller pieces.\n *\n * \\return The pass.\n */\nTVM_DLL Pass SplitArgs(int max_function_args);\n\n/*!\n * \\brief Fuse operations into expr into separate functions.\n *\n * \\param fuse_opt_level Optimization level. If it is -1 it will be inferred from pass context.\n *\n * \\return The pass.\n */\nTVM_DLL Pass FuseOps(int fuse_opt_level = -1);\n\n/*!\n * \\brief The inverse operation of FuseOps. It transforms a fused program returned by\n * FuseOps into the program before FuseOps. (i.e. x == DefuseOps(FuseOps(x)))\n *\n * \\return The pass.\n */\nTVM_DLL Pass DefuseOps();\n\n/*!\n * \\brief Rewrite the annotated program.\n *\n * \\param fallback_device The fallback device which is the default device for\n *                        operators without annotation.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RewriteAnnotatedOps(int fallback_device);\n\n/*!\n * \\brief Turn an expression to Basic Block Normal Form.\n *\n * We define a block as a group of expressions implied by the scope structure.\n *\n * Each graph node can only belong to a single block.\n *\n * For any value that is being used in multiple blocks, it has to be referred\n * by a Var which is defined in a block, whose scope is the least common ancestor\n * of blocks this value is used.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ToBasicBlockNormalForm();\n\n/*!\n * \\brief turn a dataflow graph into Administrative Normal Form, or A-Normal Form (ANF).\n *\n * It will turn an expression that is in a graph form (with sharing implicit),\n * to an expression with explicit sharing (A-Normal Form).\n *\n * The scope of the root expression is the global scope.\n *\n * The scope of any non root expression is the least common ancestor of all it's scope.\n *\n * Values are ordered by post-DFS order in each scope.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ToANormalForm();\n\n/*!\n * \\brief ToANormalForm but on incomplete graph.\n *\n * \\param expr the graph.\n *\n * \\return The transformed program.\n */\nTVM_DLL Expr ToANormalForm(const Expr& expr);\n\n/*!\n * \\brief Turn an expression into continuation passing style(CPS).\n *\n * CPS mean that every function will, instead of returning the result directly,\n * be passed down an extra function (called the continuation) as argument,\n * and pass the result to the continuation instead.\n *\n * Thus, every function call has to be passed an extra argument\n * that represent the rest of the computation (Hence the name of continuation).\n *\n * Similarly, all other compute will be wrapped and call the continuation as well.\n *\n * \\return the pass.\n */\nTVM_DLL Pass ToCPS();\n\n/*!\n * \\brief Remove let binding and directly share via pointer instead.\n *\n * It will remove all let binding,\n * and turn all of the variable bound by let into direct pointer reference.\n *\n * \\return the expression in graph normal form.\n */\nTVM_DLL Pass ToGraphNormalForm();\n\n/*!\n * \\brief Aggressive constant propagation/constant folding/inlining.\n *\n * It will do as much computation in compile time as possible.\n * It has two benefit: remove runtime overhead, and allow more optimization (typically fusion).\n * As a side effect, code size will explode.\n *\n * \\return the optimized expression.\n */\nTVM_DLL Pass PartialEval();\n\n/*!\n * \\brief Simplify certain operators during inference. For example, the result\n * of a batch norm which is indexed at tuple index 0 will be unpacked into a\n * number of simplified operators.\n *\n * \\return The Pass.\n */\nTVM_DLL Pass SimplifyInference();\n\n/*!\n * \\brief Replaces non linear activation functions with their fast but approximate counterparts.\n *\n * \\return The Pass.\n */\nTVM_DLL Pass FastMath();\n\n/*!\n * \\brief Find Dynamic ops and make them static\n *\n * Searches the graph for dynamic ops. If the dynamic inputs to those ops are constants, it replaces\n * them with static ops and re-performs type inference and constant folding. The pass repeats\n * itself until the graph stops changing or we run too many iterations.\n *\n * \\return The pass.\n */\nTVM_DLL Pass DynamicToStatic();\n\n/*!\n * \\brief Infer the type of an expression.\n *\n * The result of type checking is a new expression with unambiguous\n * type information filled in, as well as it's checked type field\n * populated with the result type.\n *\n * \\return The pass.\n */\nTVM_DLL Pass InferType();\n\n/*!\n * \\brief Infer the type of an expression, reusing existing type information.\n *\n * The result of type checking is a new expression with unambiguous\n * type information filled in for the given node only. The local\n * version can use existing type information populated throughout\n * the expression and assumes this information is correct. The local\n * version also avoids examining large amounts of the graph assuming\n * type information is filled in properly which makes it much faster if we\n * iteratively call type inference.\n *\n * \\return The type of the expression.\n */\nTVM_DLL Type InferTypeLocal(const Expr& expr);\n\n/*!\n * \\brief Search and eliminate common subexpression. For example, if there are\n * two expressions evaluated to an identical value, a single variable is created\n * and these two expressions are replaced by this variable.\n *\n * \\param fskip The callback argument that allows to skip certain expressions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass EliminateCommonSubexpr(runtime::PackedFunc fskip = nullptr);\n\n/*!\n * \\brief Combine parallel 2d convolutions into a single convolution if the\n * number of branches of this conv2d operator is not less than\n * `min_num_branch`.\n *\n * \\param min_num_branches The minimun number of branches.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CombineParallelConv2D(uint64_t min_num_branches = 3);\n\n/*!\n * \\brief Combine parallel dense ops into a single batch_matmul if the\n * number of branches of this dense operator is not less than\n * `min_num_branch`.\n *\n * \\param min_num_branches The minimun number of branches.\n * \\param to_batch_matmul Whether to combine parallel dense ops to batch matmul.\n *                        If set false, combine dense ops to single dense op.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CombineParallelDense(uint64_t min_num_branches = 3, bool to_batch_matmul = true);\n\n/*!\n * \\brief Combine parallel batch_matmul ops into a single batch_matmul\n *  if the number of branches of this dense operator is not less than\n * `min_num_branch`.\n *\n * \\param min_num_branches The minimun number of branches.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CombineParallelBatchMatmul(uint64_t min_num_branches = 3);\n\n/*!\n * \\brief Backward fold axis scaling into weights of conv/dense operators.\n *\n * \\return The pass.\n */\nTVM_DLL Pass BackwardFoldScaleAxis();\n\n/*!\n * \\brief Forward fold axis scaling into weights of conv/dense operators.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ForwardFoldScaleAxis();\n\n/*!\n * \\brief A sequential pass that executes ForwardFoldScaleAxis and\n * BackwardFoldScaleAxis passes.\n *\n * \\return The pass.\n */\nTVM_DLL Pass FoldScaleAxis();\n\n/*!\n * \\brief Canonicalize some operators to the simplified operators. For example,\n * bias_add can be canonicalized to expand_dims and broadcast_add.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CanonicalizeOps();\n\n/*!\n * \\brief Alternate the layouts of operators or replace primitive operators\n * with other expressions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass AlterOpLayout();\n\n/*!\n * \\brief Do layout rewrite according to the tile structure created by auto-scheduler.\n * \\return The pass\n */\nTVM_DLL Pass AutoSchedulerLayoutRewrite();\n\n/*!\n * \\brief Do layout rewrite according to the tile structure created by meta-schedule.\n * \\return The pass\n */\nTVM_DLL Pass MetaScheduleLayoutRewrite();\n\n/*!\n * \\brief Given a dest layout, this pass transforms the expr such that most of the ops input data\n * layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms, one\n * at the start and one at the end.\n *\n * This pass is not a part of relay.build and is expected to be called between framework-relay\n * parser and relay.build call. This is very helpful for hardware backends that support/prefer only\n * type of data layout.\n *\n * RFC - https://discuss.tvm.ai/t/layout-conversion-pass/4009\n *\n * This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define new\n * layouts for conv2d ops for now. Most of the other operators try to adapt to their input layout\n * using the InferCorrectLayout infrastructure.\n *\n * \\param desired_layouts Specify mapping of op_name to array of desired layouts for each input.\n *                        For example: Map(\"nn.conv2d\", Array(\"NHWC\", \"OHWI\")),\n *                        this specifies the desired layout for data then kernel for nn.conv2d.\n * \\return The pass.\n */\nTVM_DLL Pass ConvertLayout(const Map<String, Array<String>>& desired_layouts);\n\n/*!\n * \\brief Legalizes an expr with another expression.\n * \\param legalize_map_attr_name The Op's attr name which corresponds to the legalize rule function.\n * One can collect and isolate similar type of legalize transformations using this param. For\n * example, transformations that only apply to Dialects can be isolated into a FTVMDialectLegalize\n * string. This pass calls only those transformations that have been registered using the supplied\n * legalize_map_attr_name.\n *\n * \\return The pass.\n */\nTVM_DLL Pass Legalize(const String& legalize_map_attr_name = \"FTVMLegalize\");\n\n/*!\n * \\brief Canonicalize cast expressions to make operator fusion more efficient.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CanonicalizeCast();\n\n/*!\n * \\brief Add abstraction over a constructor or global variable bound to a function.\n *\n * For example: `square` is transformed to\n * `fn (%x: int32) -> int32 { square(x) }`.\n *\n * See https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B7-conversion\n * for more details.\n *\n * \\param expand_constructor Whether to expand constructors.\n * \\param expand_global_var Whether to expand global variables.\n *\n * \\return The pass.\n */\nTVM_DLL Pass EtaExpand(bool expand_constructor, bool expand_global_var);\n\n/*!\n * \\brief Partition a Relay program into regions that can be executed on\n * different backends.\n *\n * \\return The pass.\n */\nTVM_DLL Pass PartitionGraph();\n\n/*!\n * \\brief Inline the global functions marked as `inline` in a given Relay\n * IRModule.\n *\n * \\return The pass.\n */\nTVM_DLL Pass Inline();\n\n/*!\n * \\brief Remove the unused functions in the Relay IRModule.\n *\n * \\param entry_functions The entry functions used to search the functions that\n *        are being used.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RemoveUnusedFunctions(Array<runtime::String> entry_functions);\n\n/*!\n * \\brief Simplify the Relay expression.\n *\n * \\return The pass.\n */\nTVM_DLL Pass SimplifyExpr();\n\n/*!\n * \\brief Run any custom passes registered under \"RelayToTIR\" attributes on TargetKinds.\n *\n * This pass looks for inline, let-bound or global functions which have a \"Compiler\" attribute.\n * If the attribute value corresponds to a TargetKind with a \"RelayToTIR\" attribute, then the\n * 'custom' pass bound to that attribute is run (at most once) on the IRModule as a whole.\n *\n * If, in addition, the \\p config has a Target with a matching TargetKind, that Target is set\n * as the 'current' target before the custom pass is executed. In this way it is possible\n * for custom passes to pick up target options which may guide how they transform the IRModule.\n * (Those targets are referred to as 'extern codegen targets' elsewhere).\n *\n * A typical custom pass will:\n *  - Find calls to \"Compiler\" attributes functions with matching compiler name.\n *  - Lower those function to TIR PrimFuncs.\n *  - Bind those functions into the IRModule under the the functions' \"global_symbol\" attribute.\n *  - Replace all calls to those functions with 'call_lowered' to the matching global.\n * Care should be taken to handle multiple calls to the same function.\n * See src/relay/backend/contrib/example_target_hooks/relay_to_tir.cc for an example custom pass.\n *\n * It is also possible (despite the pass and attribute names!) for the custom pass to proceed\n * directly to a runtime::Module, which can be attached to the output IRModules \"external_mods\"\n * attribute (taking care not to clobber any existing modules). In this case the flow is as above,\n * except:\n *  - The runtime::Module must contain a binding for each compiled function under their\n *    \"global_symbol\" (ie runtime::Module::ImplementsFunction should return true).\n *  - A Relay Function must be bound (or re-bound) into the result IRModule, again with the same\n *    \"global_symbol\", but with only the \"Extern\" attribute set to Integer(1). The function body\n *    should be the original function body. In this way we always have a TVM definition matching\n *    every global function name.\n *\n * There are many existing runtime::Modules, ranging from source to object to dynamic libaries to\n * entirely custom implementations. Some of those may require additional compilation using\n * 'export_library' on the final build artifact.\n *\n * The OutlineCompilerFunctionsWithExistingGlobalSymbols and MarkCompilerFunctionsAsExtern utility\n * passes can be used by custom passes to take care of some of the boilerplate.\n *\n * TODO(mbs): Rename PreLoweringTargetHooks?\n *\n * \\param config All available targets.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RelayToTIRTargetHook(CompilationConfig config);\n\n/*!\n * \\brief A pass for manifesting explicit memory allocations and rewriting\n * specific dialects.\n *\n * \\param cpu_virtual_device VirtualDevice for computations and data which must reside on a CPU,\n * such as shapes and shape functions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ManifestAlloc(VirtualDevice cpu_virtual_device);\n\n/*!\n * \\brief A pass for manifesting variable lifetimes by inserting kill operations when variables\n * become dead. This pass should be run after ManifestAlloc, and should not be run more than once.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ManifestLifetimes();\n\n/*!\n * \\brief Uses existing \"on_device\" and \"device_copy\" CallNodes to infer the \\p VirtualDevice on\n * which every Relay sub-expression should run and the result stored. Captures the result of that\n * analysis using new \"on_device\" and \"device_copy\" CallNodes.\n *\n * See tvm::relay::transform::{LexicalOnDeviceMixin,DeviceAwareExprVisitor,DeviceAwareExprMutator}\n * for help recovering the device for an arbitrary sub-expression in downstream transformations.\n *\n * \\param config Describes the targets and default \\p VirtualDevice for all primitive operators and\n * host sub-expressions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass PlanDevices(CompilationConfig config);\n\n/*!\n * \\brief This transform flattens atrous convolution, which corresponds to the sequence of\n * operations: \"space_to_batch_nd\"->\"conv2d\"->\"batch_to_space_nd\" and convert them into subgraphs\n * with a convolution with the modified \"dilation\" and recalculated \"padding\" parameters.\n *\n * \\return The pass.\n */\nTVM_DLL Pass FlattenAtrousConv();\n\n/*!\n * \\brief Annotates the minimum required memory of each primitive function callsite by analyzing\n * the liveness of the input/output tensors at each function callsite and calculating the total\n * amount of memory these tensors require. This is added as a \"used_memory\" annotation to the\n * function in question as a list of the number of bytes for each callsite. In addition, the\n * containing function is annotated with an \"io_used_memory\" annotation which refers to the total\n * memory required for the IO tensors.\n *\n * Note: This pass does not support dynamic shapes, it is the users responsibility to check this\n * pass isn't applied where dynamic shapes may be input.\n */\nTVM_DLL Pass AnnotateUsedMemory();\n\n/*!\n * \\brief Captures the post-dfs index and dominator post-dfs index of (most) expression nodes in\n * their span, in the form \"index:<post-dfs index>:<dominator post-dfs index>\". This is useful for\n * debugging since a) it helps identify pretty-printed sub-expressions within the overall model\n * and b) the indexes are heavily used by Collage for its compact representation of sub-graphs.\n *\n * Note that Op and Constructor nodes are not changed even though they are assigned an\n * post-dfs index.\n */\nTVM_DLL Pass CapturePostDfsIndexInSpans();\n\n/*!\n * \\brief Calls device dependent memory scope analysis pass, collects mapping of desirable\n * expr->memory_scope and annotates expressions by VirtualDevice with required memory_scope\n */\nTVM_DLL Pass AnnotateMemoryScope(CompilationConfig config);\n\n/*!\n * \\brief Removes non-fused reshapes after lowering the graph.\n * InferType() cannot be invoked after calling this pass as it removes reshapes from the call\n * graph. Many targets only need buffer addresses irrespective of the shapes of them. This makes\n * reshapes symbolic once the graph has been lowered. Reshape removal results into smaller code\n * size and reduced buffer allocations. It opens up opportunities of operator fusion in the target\n * backend. Thus, consequently, it improves the performance of the inference.\n */\nTVM_DLL Pass RemoveStandaloneReshapes();\n\n}  // namespace transform\n\n/*!\n * \\brief Bind the free variables to a Relay expression. This is a helper\n * function usually called by other pass functions to help optimizations.\n * If any free variables are introduced into a function, those are added\n * to the functoin parameters.\n * Additionally this may change the order of parameters if you map a variable\n * to a variable.\n *\n * \\param expr The input expression.\n * \\param binds The variable to expression map that will be used to help the\n *        binding.\n *\n * \\return The updated expression.\n */\nTVM_DLL Expr Bind(const Expr& expr, const tvm::Map<Var, Expr>& binds);\n\n/*!\n * \\brief Substitute variables with new variables (including function parameters) in a function.\n * This is a helper function usually called by other pass functions to help optimizations.\n * Expects all values in the bind map to be Vars.\n *\n * \\param func The input function.\n * \\param binds The variable to expression map that will be used to help the\n *        binding.\n *\n * \\return The updated expression.\n */\nTVM_DLL Function SubstituteBoundVars(const Function& func, const tvm::Map<Var, Expr>& binds);\n\n/*!\n * \\brief Apply rewrite rules to rewrite the expr in post DFS order. This\n * function is used as a helper function to rewrtie an expression in a pass.\n *\n * \\param expr The expression.\n * \\param rewrite_map_attr_name The Op's attr name which corresponds to the rewrite\n *                              rule function.\n * \\param fcontext Additional callback to provide context argument for each call node.\n * \\param fmulti_ref_trigger Transformation function to be called when\n *                           an Expr consumed by multiple callers.\n * \\return The rewritten expression.\n */\nTVM_DLL Expr ForwardRewrite(const Expr& expr, const String& rewrite_map_attr_name,\n                            std::function<ObjectRef(const Call&)> fcontext = nullptr,\n                            std::function<Expr(const Expr&)> fmulti_ref_trigger = nullptr);\n\n/*!\n * \\brief Apply rewrite rules to rewrite the expr in post DFS order. This\n * function is used as a helper function to rewrtie an expression in a pass.\n *\n * \\param expr The expression.\n * \\param rewrite_func The rewrite func that will apply to all operators.\n * \\param fcontext Additional callback to provide context argument for each call node.\n * \\param fmulti_ref_trigger Transformation function to be called when\n *                           an Expr consumed by multiple callers.\n *\n * \\return The rewritten expression.\n */\nTVM_DLL Expr ForwardRewrite(const Expr& expr, const FForwardRewrite& rewrite_func,\n                            std::function<ObjectRef(const Call&)> fcontext = nullptr,\n                            std::function<Expr(const Expr&)> fmulti_ref_trigger = nullptr);\n\n/*!\n * \\brief Rewrite the annotated program.\n *\n * \\param expr The expression.\n * \\param fallback_device The fallback device which is the default device for\n *                        operators without annotation.\n *\n * \\return The updated program.\n */\nTVM_DLL Expr RewriteAnnotatedOps(const Expr& expr, int fallback_device);\n\n/*!\n * \\brief Turn an expression into continuation passing style(CPS).\n *\n * CPS mean that every function will, instead of returning the result directly,\n * be passed down an extra function (called the continuation) as argument,\n * and pass the result to the continuation instead.\n *\n * Thus, every function call has to be passed an extra argument\n * that represent the rest of the computation (Hence the name of continuation).\n *\n * Similarly, all other compute will be wrapped and call the continuation as well.\n *\n * \\param f the function.\n * \\param mod the module.\n *\n * \\return the converted Function.\n */\nTVM_DLL Function ToCPS(const Function& f, const IRModule& mod);\n\n/*!\n * \\brief Remove the continuation argument of a CPS function.\n *\n * Note that this only transform the type back into un-CPS form\n * when there is no higher order input/output.\n *\n * \\param f the function.\n *\n * \\return the converted Function.\n */\nTVM_DLL Function UnCPS(const Function& f);\n\n/*!\n * \\brief Deduplicate the bound variables and type variables in the expression.\n *\n * \\param e the expression.\n *\n * \\return the deduplicated expression.\n */\nTVM_DLL Expr DeDup(const Expr& e);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/relay/type.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/type.h\n * \\brief Relay typed AST nodes.\n */\n#ifndef TVM_RELAY_TYPE_H_\n#define TVM_RELAY_TYPE_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/env_func.h>\n#include <tvm/ir/tensor_type.h>\n#include <tvm/ir/type.h>\n#include <tvm/ir/type_relation.h>\n#include <tvm/runtime/registry.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n\n#include \"base.h\"\n\nnamespace tvm {\nnamespace relay {\n\n// namespace update for backward compact\n// will be removed later.\nusing AnyNode = tvm::tir::AnyNode;\nusing Any = tvm::tir::Any;\nusing Kind = TypeKind;\nusing Type = tvm::Type;\nusing TypeNode = tvm::TypeNode;\nusing TypeVar = tvm::TypeVar;\nusing TypeVarNode = tvm::TypeVarNode;\nusing GlobalTypeVar = tvm::GlobalTypeVar;\nusing GlobalTypeVarNode = tvm::GlobalTypeVarNode;\nusing TupleType = tvm::TupleType;\nusing TupleTypeNode = tvm::TupleTypeNode;\nusing TypeConstraint = tvm::TypeConstraint;\nusing TypeConstraintNode = tvm::TypeConstraintNode;\nusing FuncType = tvm::FuncType;\nusing FuncTypeNode = tvm::FuncTypeNode;\nusing IncompleteType = tvm::IncompleteType;\nusing IncompleteTypeNode = tvm::IncompleteTypeNode;\nusing RelayRefType = tvm::RelayRefType;\nusing RelayRefTypeNode = tvm::RelayRefTypeNode;\nusing TensorType = tvm::TensorType;\nusing TensorTypeNode = tvm::TensorTypeNode;\nusing TypeCall = tvm::TypeCall;\nusing TypeCallNode = tvm::TypeCallNode;\nusing TypeRelation = tvm::TypeRelation;\nusing TypeRelationNode = tvm::TypeRelationNode;\nusing TypeRelationFn = tvm::TypeRelationFn;\nusing TypeReporter = tvm::TypeReporter;\nusing TypeReporterNode = tvm::TypeReporterNode;\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TYPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/builtin_fp16.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file builtin_fp16.h\n * \\brief Functions for conversion between fp32 and fp16\n */\n#ifndef TVM_RUNTIME_BUILTIN_FP16_H_\n#define TVM_RUNTIME_BUILTIN_FP16_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <cstdint>\n\nextern \"C\" {\nTVM_DLL uint16_t __gnu_f2h_ieee(float);\nTVM_DLL float __gnu_h2f_ieee(uint16_t);\nTVM_DLL uint16_t __truncsfhf2(float v);\nTVM_DLL float __extendhfsf2(uint16_t v);\n}\n\n#endif  // TVM_RUNTIME_BUILTIN_FP16_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/c_backend_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/c_backend_api.h\n * \\brief TVM runtime backend API.\n *\n *  The functions defined in this header are intended to be\n *  used by compiled tvm operators, usually user do not need to use these\n *  function directly.\n */\n#ifndef TVM_RUNTIME_C_BACKEND_API_H_\n#define TVM_RUNTIME_C_BACKEND_API_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*!\n * \\brief Signature for backend functions exported as DLL.\n *\n * \\param args The arguments\n * \\param type_codes The type codes of the arguments\n * \\param num_args Number of arguments.\n * \\param out_ret_value The output value of the return value.\n * \\param out_ret_tcode The output type code of the return value.\n * \\param resource_handle Pointer to associated resource.\n *\n * \\return 0 if success, -1 if failure happens, set error via TVMAPISetLastError.\n */\ntypedef int (*TVMBackendPackedCFunc)(TVMValue* args, int* type_codes, int num_args,\n                                     TVMValue* out_ret_value, int* out_ret_tcode,\n                                     void* resource_handle);\n\n/*!\n * \\brief Backend function for modules to get function\n *  from its environment mod_node (its imports and global function).\n *  The user do should not call TVMFuncFree on func.\n *\n * \\param mod_node The module handle.\n * \\param func_name The name of the function.\n * \\param out The result function.\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendGetFuncFromEnv(void* mod_node, const char* func_name, TVMFunctionHandle* out);\n\n/*!\n * \\brief Backend function to register system-wide library symbol.\n *\n * \\param name The name of the symbol\n * \\param ptr The symbol address.\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendRegisterSystemLibSymbol(const char* name, void* ptr);\n\n/*!\n * \\brief Backend function to allocate temporal workspace.\n *\n * \\note The result allocated space is ensured to be aligned to kTempAllocaAlignment.\n *\n * \\param nbytes The size of the space requested.\n * \\param device_type The device type which the space will be allocated.\n * \\param device_id The device id which the space will be allocated.\n * \\param dtype_code_hint The type code of the array elements. Only used in\n * certain backends such as OpenGL.\n * \\param dtype_bits_hint The type bits of the array elements. Only used in\n * certain backends such as OpenGL.\n * \\return nullptr when error is thrown, a valid ptr if success\n */\nTVM_DLL void* TVMBackendAllocWorkspace(int device_type, int device_id, uint64_t nbytes,\n                                       int dtype_code_hint, int dtype_bits_hint);\n\n/*!\n * \\brief Backend function to free temporal workspace.\n *\n * \\param ptr The result allocated space pointer.\n * \\param device_type The device type which the space will be allocated.\n * \\param device_id The device id which the space will be allocated.\n * \\return 0 when no error is thrown, -1 when failure happens\n *\n * \\sa TVMBackendAllocWorkspace\n */\nTVM_DLL int TVMBackendFreeWorkspace(int device_type, int device_id, void* ptr);\n\n/*!\n * \\brief Backend function to register execution environment(e.g. python)\n *        specific C APIs.\n *\n * \\note  We only register the C API function when absolutely necessary (e.g. when signal handler\n *  cannot trap back into python). In most cases we should use the PackedFunc FFI.\n *\n * \\param name The name of the symbol\n * \\param ptr The symbol address.\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendRegisterEnvCAPI(const char* name, void* ptr);\n\n/*!\n * \\brief Environment for TVM parallel task.\n */\ntypedef struct {\n  /*!\n   * \\brief Auxiliary used for synchronization\n   */\n  void* sync_handle;\n  /*! \\brief total amount of task */\n  int32_t num_task;\n} TVMParallelGroupEnv;\n\n/*!\n * \\brief The callback function to execute a parallel lambda\n * \\param task_id the task id of the function.\n * \\param penv The parallel environment backs the execution.\n * \\param cdata The supporting closure data.\n */\ntypedef int (*FTVMParallelLambda)(int task_id, TVMParallelGroupEnv* penv, void* cdata);\n\n/*!\n * \\brief Backend function for running parallel jobs.\n *\n * \\param flambda The parallel function to be launched.\n * \\param cdata The closure data.\n * \\param num_task Number of tasks to launch, can be 0, means launch\n *           with all available threads.\n *\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendParallelLaunch(FTVMParallelLambda flambda, void* cdata, int num_task);\n\n/*!\n * \\brief BSP barrrier between parallel threads\n * \\param task_id the task id of the function.\n * \\param penv The parallel environment backs the execution.\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendParallelBarrier(int task_id, TVMParallelGroupEnv* penv);\n\n/*!\n * \\brief Simple static initialization function.\n *  Run f once and set handle to be not null.\n *  This function is mainly used for test purpose.\n *\n * \\param handle A global address to indicate f\n * \\param f The function to be run\n * \\param cdata The closure data to pass to the function.\n * \\param nbytes Number of bytes in the closure data.\n * \\return 0 when no error is thrown, -1 when failure happens\n */\nTVM_DLL int TVMBackendRunOnce(void** handle, int (*f)(void*), void* cdata, int nbytes);\n\n#ifdef __cplusplus\n}  // TVM_EXTERN_C\n#endif\n#endif  // TVM_RUNTIME_C_BACKEND_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/c_runtime_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*\n * \\file tvm/runtime/c_runtime_api.h\n * \\brief TVM runtime library.\n *\n *  The philosophy of TVM project is to customize the compilation\n *  stage to generate code that can used by other projects transparently.\n *  So this is a minimum runtime code gluing, and some limited\n *  memory management code to enable quick testing.\n *\n *  The runtime API is independent from TVM compilation stack and can\n *  be linked via libtvm_runtime.\n *\n *  The common flow is:\n *   - Use TVMFuncListGlobalNames to get global function name\n *   - Use TVMFuncCall to call these functions.\n *\n *  Possible return values of the API functions:\n *  * 0: success\n *  * -1: the error can be retrieved through TVMGetLastError.\n *  * -2: a frontend error occurred and recorded in the frontend.\n */\n#ifndef TVM_RUNTIME_C_RUNTIME_API_H_\n#define TVM_RUNTIME_C_RUNTIME_API_H_\n\n// Macros to do weak linking\n#ifdef _MSC_VER\n#define TVM_WEAK __declspec(selectany)\n#else\n#define TVM_WEAK __attribute__((weak))\n#endif\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten/emscripten.h>\n#define TVM_DLL EMSCRIPTEN_KEEPALIVE\n#endif\n\n#ifndef TVM_DLL\n#ifdef _WIN32\n#ifdef TVM_EXPORTS\n#define TVM_DLL __declspec(dllexport)\n#else\n#define TVM_DLL __declspec(dllimport)\n#endif\n#else\n#define TVM_DLL __attribute__((visibility(\"default\")))\n#endif\n#endif\n\n// TVM version\n#define TVM_VERSION \"0.11.dev0\"\n\n// TVM Runtime is DLPack compatible.\n#include <dlpack/dlpack.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include <stddef.h>\n#include <stdint.h>\n\n/*! \\brief type of array index. */\ntypedef int64_t tvm_index_t;\n\n/*! \\brief Extension device types in TVM\n *\n * Additional enumerators to supplement those provided by\n * DLPack's `DLDeviceType` enumeration.\n *\n * MAINTAINERS NOTE #1: We need to ensure that the two devices\n * are identified by the same integer.\n * Currently this requires manual verification.\n * Discussed here: https://github.com/dmlc/dlpack/issues/111\n * As of DLPack v0.7, the highest-valued enumerator in\n * `DLDeviceType` is kDLHexagon = 16.\n *\n * MAINTAINERS NOTE #2: As of DLPack v0.7, the definition for\n * `DLDeviceType` specifies an underlying storage type of\n * `int32_t`.  That guarantees a variable of type\n * `DLDeviceType` is capable of holding any integers provided\n * by *either* of these enumerations.\n *\n * However, the `int32_t` specification only applies when the\n * header file is compiled as C++, and this header file is also\n * meant to work as C code.  So the unspecified storage type\n * could be a latent bug when compiled as C.\n */\n#ifdef __cplusplus\ntypedef enum : int32_t {\n#else\ntypedef enum {\n#endif\n  // To help avoid accidental conflicts between `DLDeviceType`\n  // and this enumeration, start numbering the new enumerators\n  // a little higher than (currently) seems necessary.\n  kDLAOCL = 32,\n  kDLSDAccel,\n  kOpenGL,\n  kDLMicroDev,\n  TVMDeviceExtType_End,  // sentinel value\n} TVMDeviceExtType;\n\n#ifdef __cplusplus\n// Some other parts of TVM hardcode the integer identifier for\n// some DLPack / TVM devices, rather then using the symbolic\n// enumerator.   E.g., `2` rather than `kDLCUDA`.\n// These asserts should alert us when that mapping breaks.\n#define TVM_HARCODED_INTEGER_CHANGED_MSG                                                          \\\n  \"Change in compile-time integer.  Make sure hardcoded uses of this integer throughout TVM are \" \\\n  \"updated.\"\nstatic_assert(kDLCPU == 1, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLCUDA == 2, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLCUDAHost == 3, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLOpenCL == 4, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLVulkan == 7, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLMetal == 8, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLVPI == 9, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLROCM == 10, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLROCMHost == 11, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLExtDev == 12, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLCUDAManaged == 13, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLOneAPI == 14, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLWebGPU == 15, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLHexagon == 16, TVM_HARCODED_INTEGER_CHANGED_MSG);\n\nstatic_assert(kDLAOCL == 32, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLSDAccel == 33, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kOpenGL == 34, TVM_HARCODED_INTEGER_CHANGED_MSG);\nstatic_assert(kDLMicroDev == 35, TVM_HARCODED_INTEGER_CHANGED_MSG);\n#undef TVM_HARCODED_INTEGER_CHANGED_MSG\n#endif\n\n/*!\n * \\brief The type code in used and only used in TVM FFI for argument passing.\n *\n * DLPack consistency:\n * 1) kTVMArgInt is compatible with kDLInt\n * 2) kTVMArgFloat is compatible with kDLFloat\n * 3) kDLUInt is not in ArgTypeCode, but has a spared slot\n *\n * Downstream consistency:\n * The kDLInt, kDLUInt, kDLFloat are kept consistent with the original ArgType code\n *\n * It is only used in argument passing, and should not be confused with\n * DataType::TypeCode, which is DLPack-compatible.\n *\n * \\sa tvm::runtime::DataType::TypeCode\n */\ntypedef enum {\n  kTVMArgInt = kDLInt,\n  kTVMArgFloat = kDLFloat,\n  kTVMOpaqueHandle = 3U,\n  kTVMNullptr = 4U,\n  kTVMDataType = 5U,\n  kDLDevice = 6U,\n  kTVMDLTensorHandle = 7U,\n  kTVMObjectHandle = 8U,\n  kTVMModuleHandle = 9U,\n  kTVMPackedFuncHandle = 10U,\n  kTVMStr = 11U,\n  kTVMBytes = 12U,\n  kTVMNDArrayHandle = 13U,\n  kTVMObjectRValueRefArg = 14U,\n  // Extension codes for other frameworks to integrate TVM PackedFunc.\n  // To make sure each framework's id do not conflict, use first and\n  // last sections to mark ranges.\n  // Open an issue at the repo if you need a section of code.\n  kTVMExtBegin = 15U,\n  kTVMNNVMFirst = 16U,\n  kTVMNNVMLast = 20U,\n  // The following section of code is used for non-reserved types.\n  kTVMExtReserveEnd = 64U,\n  kTVMExtEnd = 128U,\n} TVMArgTypeCode;\n\n/*! \\brief the array handle */\ntypedef DLTensor* TVMArrayHandle;\n\n/*!\n * \\brief Union type of values\n *  being passed through API and function calls.\n */\ntypedef union {\n  int64_t v_int64;\n  double v_float64;\n  void* v_handle;\n  const char* v_str;\n  DLDataType v_type;\n  DLDevice v_device;\n} TVMValue;\n\n/*!\n * \\brief Byte array type used to pass in byte array\n *  When kTVMBytes is used as data type.\n */\ntypedef struct {\n  const char* data;\n  size_t size;\n} TVMByteArray;\n\n/*! \\brief Handle to TVM runtime modules. */\ntypedef void* TVMModuleHandle;\n/*! \\brief Handle to packed function handle. */\ntypedef void* TVMFunctionHandle;\n/*! \\brief Handle to hold return value. */\ntypedef void* TVMRetValueHandle;\n/*!\n * \\brief The stream that is specific to device\n * can be NULL, which indicates the default one.\n */\ntypedef void* TVMStreamHandle;\n/*! \\brief Handle to Object. */\ntypedef void* TVMObjectHandle;\n\n/*!\n * \\brief Used for implementing C API function.\n *  Set last error message before return.\n * \\param msg The error message to be set.\n */\nTVM_DLL void TVMAPISetLastError(const char* msg);\n\n/*!\n * \\brief return str message of the last error\n *  all function in this file will return 0 when success\n *  and nonzero when an error occurred,\n *  TVMGetLastError can be called to retrieve the error\n *\n *  this function is threadsafe and can be called by different thread\n *  \\return error info\n */\nTVM_DLL const char* TVMGetLastError(void);\n/*!\n * \\brief Load module from file.\n * \\param file_name The file name to load the module from.\n * \\param format The format of the module.\n * \\param out The result module\n *\n * \\return 0 when success, nonzero when failure happens\n * \\note The resulting module do not contain import relation.\n *  It can be reconstructed by TVMModImport.\n */\nTVM_DLL int TVMModLoadFromFile(const char* file_name, const char* format, TVMModuleHandle* out);\n\n/*!\n * \\brief Add dep to mod's dependency.\n *  This allows functions in this module to use modules.\n *\n * \\param mod The module handle.\n * \\param dep The dependent module to be imported.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMModImport(TVMModuleHandle mod, TVMModuleHandle dep);\n\n/*!\n * \\brief Get function from the module.\n * \\param mod The module handle.\n * \\param func_name The name of the function.\n * \\param query_imports Whether to query imported modules\n * \\param out The result function, can be NULL if it is not available.\n * \\return 0 when no error is thrown, nonzero when failure happens\n */\nTVM_DLL int TVMModGetFunction(TVMModuleHandle mod, const char* func_name, int query_imports,\n                              TVMFunctionHandle* out);\n\n/*!\n * \\brief Free the Module\n * \\param mod The module to be freed.\n *\n * \\note This may not free up the module's resources.\n *  If there is active TVMFunctionHandle uses the module\n *  Or if this module is imported by another active module.\n *\n *  The all functions remains valid until TVMFuncFree is called.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMModFree(TVMModuleHandle mod);\n\n/*!\n * \\brief Free the function when it is no longer needed.\n * \\param func The function handle\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMFuncFree(TVMFunctionHandle func);\n\n/*!\n * \\brief Call a Packed TVM Function.\n *\n * \\param func node handle of the function.\n * \\param arg_values The arguments\n * \\param type_codes The type codes of the arguments\n * \\param num_args Number of arguments.\n *\n * \\param ret_val The return value.\n * \\param ret_type_code the type code of return value.\n *\n * \\return 0 when success, nonzero when failure happens\n * \\note TVM calls always exchanges with type bits=64, lanes=1\n *\n * \\note API calls always exchanges with type bits=64, lanes=1\n *   If API call returns container handles (e.g. FunctionHandle)\n *   these handles should be managed by the front-end.\n *   The front-end need to call free function (e.g. TVMFuncFree)\n *   to free these handles.\n */\nTVM_DLL int TVMFuncCall(TVMFunctionHandle func, TVMValue* arg_values, int* type_codes, int num_args,\n                        TVMValue* ret_val, int* ret_type_code);\n\n/*!\n * \\brief Set the return value of TVMPackedCFunc.\n *\n *  This function is called by TVMPackedCFunc to set the return value.\n *  When this function is not called, the function returns null by default.\n *\n * \\param ret The return value handle, pass by ret in TVMPackedCFunc\n * \\param value The value to be returned.\n * \\param type_code The type of the value to be returned.\n * \\param num_ret Number of return values, for now only 1 is supported.\n */\nTVM_DLL int TVMCFuncSetReturn(TVMRetValueHandle ret, TVMValue* value, int* type_code, int num_ret);\n\n/*!\n * \\brief Inplace translate callback argument value to return value.\n *  This is only needed for non-POD arguments.\n *\n * \\param value The value to be translated.\n * \\param code The type code to be translated.\n * \\note This function will do a shallow copy when necessary.\n *\n * \\return 0 when success, nonzero when failure happens.\n */\nTVM_DLL int TVMCbArgToReturn(TVMValue* value, int* code);\n\n/*!\n * \\brief C type of packed function.\n *\n * \\param args The arguments\n * \\param type_codes The type codes of the arguments\n * \\param num_args Number of arguments.\n * \\param ret The return value handle.\n * \\param resource_handle The handle additional resouce handle from front-end.\n * \\return 0 if success, -1 if failure happens, set error via TVMAPISetLastError.\n * \\sa TVMCFuncSetReturn\n */\ntypedef int (*TVMPackedCFunc)(TVMValue* args, int* type_codes, int num_args, TVMRetValueHandle ret,\n                              void* resource_handle);\n\n/*!\n * \\brief C callback to free the resource handle in C packed function.\n * \\param resource_handle The handle additional resouce handle from front-end.\n */\ntypedef void (*TVMPackedCFuncFinalizer)(void* resource_handle);\n\n/*!\n * \\brief Signature for extension function declarer.\n *\n *  TVM call this function to get the extension functions\n *  The declarer will call register_func to register function and their name.\n *\n * \\param register_func_handle The register function\n * \\return 0 if success, -1 if failure happens\n */\ntypedef int (*TVMExtensionFuncDeclarer)(TVMFunctionHandle register_func_handle);\n\n/*!\n * \\brief Wrap a TVMPackedCFunc to become a FunctionHandle.\n *\n * The resource_handle will be managed by TVM API, until the function is no longer used.\n *\n * \\param func The packed C function.\n * \\param resource_handle The resource handle from front-end, can be NULL.\n * \\param fin The finalizer on resource handle when the FunctionHandle get freed, can be NULL\n * \\param out the result function handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMFuncCreateFromCFunc(TVMPackedCFunc func, void* resource_handle,\n                                   TVMPackedCFuncFinalizer fin, TVMFunctionHandle* out);\n\n/*!\n * \\brief Register the function to runtime's global table.\n *\n * The registered function then can be pulled by the backend by the name.\n *\n * \\param name The name of the function.\n * \\param f The function to be registered.\n * \\param override Whether allow override already registered function.\n */\nTVM_DLL int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override);\n\n/*!\n * \\brief Get a global function.\n *\n * \\param name The name of the function.\n * \\param out the result function pointer, NULL if it does not exist.\n *\n * \\note The function handle of global function is managed by TVM runtime,\n *  So TVMFuncFree is should not be called when it get deleted.\n */\nTVM_DLL int TVMFuncGetGlobal(const char* name, TVMFunctionHandle* out);\n\n/*!\n * \\brief List all the globally registered function name\n * \\param out_size The number of functions\n * \\param out_array The array of function names.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMFuncListGlobalNames(int* out_size, const char*** out_array);\n\n/*!\n * \\brief Remove a global function.\n * \\param name The name of the function.\n */\nTVM_DLL int TVMFuncRemoveGlobal(const char* name);\n\n// Array related apis for quick proptyping\n/*!\n * \\brief Allocate a nd-array's memory,\n *  including space of shape, of given spec.\n *\n * \\param shape The shape of the array, the data content will be copied to out\n * \\param ndim The number of dimension of the array.\n * \\param dtype_code The type code of the dtype\n * \\param dtype_bits The number of bits of dtype\n * \\param dtype_lanes The number of lanes in the dtype.\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param out The output handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayAlloc(const tvm_index_t* shape, int ndim, int dtype_code, int dtype_bits,\n                          int dtype_lanes, int device_type, int device_id, TVMArrayHandle* out);\n\n/*!\n * \\brief Free the TVM Array.\n * \\param handle The array handle to be freed.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayFree(TVMArrayHandle handle);\n\n/*!\n * \\brief Copy array data from CPU byte array.\n * \\param handle The array handle.\n * \\param data the data pointer\n * \\param nbytes The number of bytes to copy.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayCopyFromBytes(TVMArrayHandle handle, void* data, size_t nbytes);\n\n/*!\n * \\brief Copy array data to CPU byte array.\n * \\param handle The array handle.\n * \\param data the data pointer\n * \\param nbytes The number of bytes to copy.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayCopyToBytes(TVMArrayHandle handle, void* data, size_t nbytes);\n\n/*!\n * \\brief Copy the array, both from and to must be valid during the copy.\n * \\param from The array to be copied from.\n * \\param to The target space.\n * \\param stream The stream where the copy happens, can be NULL.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayCopyFromTo(TVMArrayHandle from, TVMArrayHandle to, TVMStreamHandle stream);\n\n/*!\n * \\brief Produce an array from the DLManagedTensor that shares data memory\n * with the DLManagedTensor.\n * \\param from The source DLManagedTensor.\n * \\param out The output array handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayFromDLPack(DLManagedTensor* from, TVMArrayHandle* out);\n\n/*!\n * \\brief Produce a DLMangedTensor from the array that shares data memory with\n * the array.\n * \\param from The source array.\n * \\param out The DLManagedTensor handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMArrayToDLPack(TVMArrayHandle from, DLManagedTensor** out);\n\n/*!\n * \\brief Delete (free) a DLManagedTensor's data.\n * \\param dltensor Pointer to the DLManagedTensor.\n */\nTVM_DLL void TVMDLManagedTensorCallDeleter(DLManagedTensor* dltensor);\n\n/*!\n * \\brief Create a new runtime stream.\n *\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param out The new stream handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMStreamCreate(int device_type, int device_id, TVMStreamHandle* out);\n\n/*!\n * \\brief Free a created stream handle.\n *\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param stream The stream to be freed.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMStreamFree(int device_type, int device_id, TVMStreamHandle stream);\n\n/*!\n * \\brief Set the runtime stream of current thread to be stream.\n *  The subsequent calls to the same device_type\n *  will use the setted stream handle.\n *  The specific type of stream is runtime device dependent.\n *\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param handle The stream handle.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMSetStream(int device_type, int device_id, TVMStreamHandle handle);\n\n/*!\n * \\brief Wait until all computations on stream completes.\n *\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param stream The stream to be synchronized.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMSynchronize(int device_type, int device_id, TVMStreamHandle stream);\n\n/*!\n * \\brief Synchronize two streams of execution.\n *\n * \\param device_type The device type.\n * \\param device_id The device id.\n * \\param src The source stream to synchronize.\n * \\param dst The destination stream to synchronize.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMStreamStreamSynchronize(int device_type, int device_id, TVMStreamHandle src,\n                                       TVMStreamHandle dst);\n\n/*!\n * \\brief Get the type_index from an object.\n *\n * \\param obj The object handle.\n * \\param out_tindex the output type index.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMObjectGetTypeIndex(TVMObjectHandle obj, unsigned* out_tindex);\n\n/*!\n * \\brief Convert type key to type index.\n * \\param type_key The key of the type.\n * \\param out_tindex the corresponding type index.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMObjectTypeKey2Index(const char* type_key, unsigned* out_tindex);\n\n/*!\n * \\brief Convert type index to type key.\n * \\param tindex The type index.\n * \\param out_type_key The output type key.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMObjectTypeIndex2Key(unsigned tindex, char** out_type_key);\n\n/*!\n * \\brief Increase the reference count of an object.\n *\n * \\param obj The object handle.\n * \\note Internally we increase the reference counter of the object.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMObjectRetain(TVMObjectHandle obj);\n\n/*!\n * \\brief Free the object.\n *\n * \\param obj The object handle.\n * \\note Internally we decrease the reference counter of the object.\n *       The object will be freed when every reference to the object are removed.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMObjectFree(TVMObjectHandle obj);\n\n/*!\n * \\brief Free a TVMByteArray returned from TVMFuncCall, and associated memory.\n * \\param arr The TVMByteArray instance.\n * \\return 0 on success, -1 on failure.\n */\nTVM_DLL int TVMByteArrayFree(TVMByteArray* arr);\n\n/*!\n * \\brief Allocate a data space on device.\n * \\param dev The device to perform operation.\n * \\param nbytes The number of bytes in memory.\n * \\param alignment The alignment of the memory.\n * \\param type_hint The type of elements. Only needed by certain backends such\n *                   as nbytes & alignment are sufficient for most backends.\n * \\param out_data The allocated device pointer.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMDeviceAllocDataSpace(DLDevice dev, size_t nbytes, size_t alignment,\n                                    DLDataType type_hint, void** out_data);\n\n/*!\n * \\brief Allocate a data space on device with special memory scope.\n * \\note The memory could use a special multi-dimensional memory layout.\n *       That is why we pass shape and dtype instead of raw number of bytes.\n * \\param dev The device to perform operation.\n * \\param ndim The number of dimension of the tensor.\n * \\param shape The shape of the tensor.\n * \\param dtype The type of elements.\n * \\param mem_scope The memory scope of the tensor,\n *        can be nullptr, which indicate the default global DRAM\n * \\param out_data The allocated device pointer.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMDeviceAllocDataSpaceWithScope(DLDevice dev, int ndim, const int64_t* shape,\n                                             DLDataType dtype, const char* mem_scope,\n                                             void** out_data);\n\n/*!\n * \\brief Free a data space on device.\n * \\param dev The device to perform operation.\n * \\param ptr The data space.\n * \\return 0 when success, nonzero when failure happens\n */\nTVM_DLL int TVMDeviceFreeDataSpace(DLDevice dev, void* ptr);\n\n/*!\n * \\brief Copy data from one place to another.\n * \\note This API is designed to support special memory with shape dependent layout.\n *       We pass in DLTensor* with shape information to support these cases.\n * \\param from The source tensor.\n * \\param to The target tensor.\n * \\param stream Optional stream object.\n * \\return 0 when success, nonzero when failure happens.\n */\nTVM_DLL int TVMDeviceCopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream);\n\n/*!\n * \\brief Check that an object is derived from another.\n * \\param child_type_index The type index of the derived type.\n * \\param parent_type_index The type index of the parent type.\n * \\param is_derived A boolean representing whether this predicate holds.\n * \\return 0 when success, nonzero when failure happens.\n */\nTVM_DLL int TVMObjectDerivedFrom(uint32_t child_type_index, uint32_t parent_type_index,\n                                 int* is_derived);\n\n#ifdef __cplusplus\n}  // TVM_EXTERN_C\n#endif\n#endif  // TVM_RUNTIME_C_RUNTIME_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/adt.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/adt.h\n * \\brief Runtime ADT container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_ADT_H_\n#define TVM_RUNTIME_CONTAINER_ADT_H_\n\n#include <utility>\n#include <vector>\n\n#include \"./base.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief An object representing a structure or enumeration. */\nclass ADTObj : public Object, public InplaceArrayBase<ADTObj, ObjectRef> {\n public:\n  /*! \\brief The tag representing the constructor used. */\n  int32_t tag;\n  /*! \\brief Number of fields in the ADT object. */\n  uint32_t size;\n  // The fields of the structure follows directly in memory.\n\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeADT;\n  static constexpr const char* _type_key = \"runtime.ADT\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ADTObj, Object);\n\n private:\n  /*!\n   * \\return The number of elements in the array.\n   */\n  size_t GetSize() const { return size; }\n\n  /*!\n   * \\brief Initialize the elements in the array.\n   *\n   * \\tparam Iterator Iterator type of the array.\n   * \\param begin The begin iterator.\n   * \\param end The end iterator.\n   */\n  template <typename Iterator>\n  void Init(Iterator begin, Iterator end) {\n    size_t num_elems = std::distance(begin, end);\n    this->size = 0;\n    auto it = begin;\n    for (size_t i = 0; i < num_elems; ++i) {\n      InplaceArrayBase::EmplaceInit(i, *it++);\n      // Only increment size after the initialization succeeds\n      this->size++;\n    }\n  }\n\n  friend class ADT;\n  friend InplaceArrayBase<ADTObj, ObjectRef>;\n};\n\n/*! \\brief reference to algebraic data type objects. */\nclass ADT : public ObjectRef {\n public:\n  /*!\n   * \\brief construct an ADT object reference.\n   * \\param tag The tag of the ADT object.\n   * \\param fields The fields of the ADT object.\n   * \\return The constructed ADT object reference.\n   */\n  ADT(int32_t tag, std::vector<ObjectRef> fields) : ADT(tag, fields.begin(), fields.end()){};\n\n  /*!\n   * \\brief construct an ADT object reference.\n   * \\param tag The tag of the ADT object.\n   * \\param begin The begin iterator to the start of the fields array.\n   * \\param end The end iterator to the end of the fields array.\n   * \\return The constructed ADT object reference.\n   */\n  template <typename Iterator>\n  ADT(int32_t tag, Iterator begin, Iterator end) {\n    size_t num_elems = std::distance(begin, end);\n    auto ptr = make_inplace_array_object<ADTObj, ObjectRef>(num_elems);\n    ptr->tag = tag;\n    ptr->Init(begin, end);\n    data_ = std::move(ptr);\n  }\n\n  /*!\n   * \\brief construct an ADT object reference.\n   * \\param tag The tag of the ADT object.\n   * \\param init The initializer list of fields.\n   * \\return The constructed ADT object reference.\n   */\n  ADT(int32_t tag, std::initializer_list<ObjectRef> init) : ADT(tag, init.begin(), init.end()){};\n\n  /*!\n   * \\brief Access element at index.\n   *\n   * \\param idx The array index\n   * \\return const ObjectRef\n   */\n  const ObjectRef& operator[](size_t idx) const { return operator->()->operator[](idx); }\n\n  /*!\n   * \\brief Return the ADT tag.\n   */\n  int32_t tag() const { return operator->()->tag; }\n\n  /*!\n   * \\brief Return the number of fields.\n   */\n  size_t size() const { return operator->()->size; }\n\n  /*!\n   * \\brief Construct a tuple object.\n   *\n   * \\tparam Args Type params of tuple feilds.\n   * \\param args Tuple fields.\n   * \\return ADT The tuple object reference.\n   */\n  template <typename... Args>\n  static ADT Tuple(Args&&... args) {\n    return ADT(0, std::forward<Args>(args)...);\n  }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ADT, ObjectRef, ADTObj);\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTAINER_ADT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/array.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/array.h\n * \\brief Runtime Array container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_ARRAY_H_\n#define TVM_RUNTIME_CONTAINER_ARRAY_H_\n\n#include <algorithm>\n#include <memory>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"./base.h\"\n#include \"./optional.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief array node content in array */\nclass ArrayNode : public Object, public InplaceArrayBase<ArrayNode, ObjectRef> {\n public:\n  /*! \\return The size of the array */\n  size_t size() const { return this->size_; }\n\n  /*!\n   * \\brief Read i-th element from array.\n   * \\param i The index\n   * \\return the i-th element.\n   */\n  const ObjectRef at(int64_t i) const { return this->operator[](i); }\n\n  /*! \\return begin constant iterator */\n  const ObjectRef* begin() const { return static_cast<ObjectRef*>(InplaceArrayBase::AddressOf(0)); }\n\n  /*! \\return end constant iterator */\n  const ObjectRef* end() const { return begin() + size_; }\n\n  /*! \\brief Release reference to all the elements */\n  void clear() { ShrinkBy(size_); }\n\n  /*!\n   * \\brief Set i-th element of the array in-place\n   * \\param i The index\n   * \\param item The value to be set\n   */\n  void SetItem(int64_t i, ObjectRef item) { this->operator[](i) = std::move(item); }\n\n  /*!\n   * \\brief Constructs a container and copy from another\n   * \\param cap The capacity of the container\n   * \\param from Source of the copy\n   * \\return Ref-counted ArrayNode requested\n   */\n  static ObjectPtr<ArrayNode> CopyFrom(int64_t cap, ArrayNode* from) {\n    int64_t size = from->size_;\n    ICHECK_GE(cap, size) << \"ValueError: not enough capacity\";\n    ObjectPtr<ArrayNode> p = ArrayNode::Empty(cap);\n    ObjectRef* write = p->MutableBegin();\n    ObjectRef* read = from->MutableBegin();\n    // To ensure exception safety, size is only incremented after the initialization succeeds\n    for (int64_t& i = p->size_ = 0; i < size; ++i) {\n      new (write++) ObjectRef(*read++);\n    }\n    return p;\n  }\n\n  /*!\n   * \\brief Constructs a container and move from another\n   * \\param cap The capacity of the container\n   * \\param from Source of the move\n   * \\return Ref-counted ArrayNode requested\n   */\n  static ObjectPtr<ArrayNode> MoveFrom(int64_t cap, ArrayNode* from) {\n    int64_t size = from->size_;\n    ICHECK_GE(cap, size) << \"ValueError: not enough capacity\";\n    ObjectPtr<ArrayNode> p = ArrayNode::Empty(cap);\n    ObjectRef* write = p->MutableBegin();\n    ObjectRef* read = from->MutableBegin();\n    // To ensure exception safety, size is only incremented after the initialization succeeds\n    for (int64_t& i = p->size_ = 0; i < size; ++i) {\n      new (write++) ObjectRef(std::move(*read++));\n    }\n    from->size_ = 0;\n    return p;\n  }\n\n  /*!\n   * \\brief Constructs a container with n elements. Each element is a copy of val\n   * \\param n The size of the container\n   * \\param val The init value\n   * \\return Ref-counted ArrayNode requested\n   */\n  static ObjectPtr<ArrayNode> CreateRepeated(int64_t n, const ObjectRef& val) {\n    ObjectPtr<ArrayNode> p = ArrayNode::Empty(n);\n    ObjectRef* itr = p->MutableBegin();\n    for (int64_t& i = p->size_ = 0; i < n; ++i) {\n      new (itr++) ObjectRef(val);\n    }\n    return p;\n  }\n\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeArray;\n  static constexpr const char* _type_key = \"Array\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ArrayNode, Object);\n\n private:\n  /*! \\return Size of initialized memory, used by InplaceArrayBase. */\n  size_t GetSize() const { return this->size_; }\n\n  /*! \\return begin mutable iterator */\n  ObjectRef* MutableBegin() const {\n    return static_cast<ObjectRef*>(InplaceArrayBase::AddressOf(0));\n  }\n\n  /*! \\return end mutable iterator */\n  ObjectRef* MutableEnd() const { return MutableBegin() + size_; }\n\n  /*!\n   * \\brief Create an ArrayNode with the given capacity.\n   * \\param n Required capacity\n   * \\return Ref-counted ArrayNode requested\n   */\n  static ObjectPtr<ArrayNode> Empty(int64_t n = kInitSize) {\n    ICHECK_GE(n, 0);\n    ObjectPtr<ArrayNode> p = make_inplace_array_object<ArrayNode, ObjectRef>(n);\n    p->capacity_ = n;\n    p->size_ = 0;\n    return p;\n  }\n\n  /*!\n   * \\brief Inplace-initialize the elements starting idx from [first, last)\n   * \\param idx The starting point\n   * \\param first Begin of iterator\n   * \\param last End of iterator\n   * \\tparam IterType The type of iterator\n   * \\return Self\n   */\n  template <typename IterType>\n  ArrayNode* InitRange(int64_t idx, IterType first, IterType last) {\n    ObjectRef* itr = MutableBegin() + idx;\n    for (; first != last; ++first) {\n      ObjectRef ref = *first;\n      new (itr++) ObjectRef(std::move(ref));\n    }\n    return this;\n  }\n\n  /*!\n   * \\brief Move elements from right to left, requires src_begin > dst\n   * \\param dst Destination\n   * \\param src_begin The start point of copy (inclusive)\n   * \\param src_end The end point of copy (exclusive)\n   * \\return Self\n   */\n  ArrayNode* MoveElementsLeft(int64_t dst, int64_t src_begin, int64_t src_end) {\n    ObjectRef* from = MutableBegin() + src_begin;\n    ObjectRef* to = MutableBegin() + dst;\n    while (src_begin++ != src_end) {\n      *to++ = std::move(*from++);\n    }\n    return this;\n  }\n\n  /*!\n   * \\brief Move elements from left to right, requires src_begin < dst\n   * \\param dst Destination\n   * \\param src_begin The start point of move (inclusive)\n   * \\param src_end The end point of move (exclusive)\n   * \\return Self\n   */\n  ArrayNode* MoveElementsRight(int64_t dst, int64_t src_begin, int64_t src_end) {\n    ObjectRef* from = MutableBegin() + src_end;\n    ObjectRef* to = MutableBegin() + (src_end - src_begin + dst);\n    while (src_begin++ != src_end) {\n      *--to = std::move(*--from);\n    }\n    return this;\n  }\n\n  /*!\n   * \\brief Enlarges the size of the array\n   * \\param delta Size enlarged, should be positive\n   * \\param val Default value\n   * \\return Self\n   */\n  ArrayNode* EnlargeBy(int64_t delta, const ObjectRef& val = ObjectRef(nullptr)) {\n    ObjectRef* itr = MutableEnd();\n    while (delta-- > 0) {\n      new (itr++) ObjectRef(val);\n      ++size_;\n    }\n    return this;\n  }\n\n  /*!\n   * \\brief Shrinks the size of the array\n   * \\param delta Size shrinked, should be positive\n   * \\return Self\n   */\n  ArrayNode* ShrinkBy(int64_t delta) {\n    ObjectRef* itr = MutableEnd();\n    while (delta-- > 0) {\n      (--itr)->ObjectRef::~ObjectRef();\n      --size_;\n    }\n    return this;\n  }\n\n  /*! \\brief Number of elements used */\n  int64_t size_;\n\n  /*! \\brief Number of elements allocated */\n  int64_t capacity_;\n\n  /*! \\brief Initial size of ArrayNode */\n  static constexpr int64_t kInitSize = 4;\n\n  /*! \\brief Expansion factor of the Array */\n  static constexpr int64_t kIncFactor = 2;\n\n  // CRTP parent class\n  friend InplaceArrayBase<ArrayNode, ObjectRef>;\n\n  // Reference class\n  template <typename, typename>\n  friend class Array;\n\n  // To specialize make_object<ArrayNode>\n  friend ObjectPtr<ArrayNode> make_object<>();\n};\n\n/*! \\brief Helper struct for type-checking\n *\n * is_valid_iterator<T,IterType>::value will be true if IterType can\n * be dereferenced into a type that can be stored in an Array<T>, and\n * false otherwise.\n */\ntemplate <typename T, typename IterType>\nstruct is_valid_iterator\n    : std::bool_constant<std::is_base_of_v<\n          T, std::remove_cv_t<std::remove_reference_t<decltype(*std::declval<IterType>())>>>> {};\n\ntemplate <typename T, typename IterType>\nstruct is_valid_iterator<Optional<T>, IterType> : is_valid_iterator<T, IterType> {};\n\ntemplate <typename T, typename IterType>\ninline constexpr bool is_valid_iterator_v = is_valid_iterator<T, IterType>::value;\n\n/*!\n * \\brief Array, container representing a contiguous sequence of ObjectRefs.\n *\n *  Array implements in-place copy-on-write semantics.\n *\n * As in typical copy-on-write, a method which would typically mutate the array\n * instead opaquely copies the underlying container, and then acts on its copy.\n *\n * If the array has reference count equal to one, we directly update the\n * container in place without copying. This is optimization is sound because\n * when the reference count is equal to one this reference is guranteed to be\n * the sole pointer to the container.\n *\n *\n * operator[] only provides const access, use Set to mutate the content.\n * \\tparam T The content ObjectRef type.\n */\ntemplate <typename T,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, T>::value>::type>\nclass Array : public ObjectRef {\n public:\n  using value_type = T;\n  // constructors\n  /*!\n   * \\brief default constructor\n   */\n  Array() { data_ = ArrayNode::Empty(); }\n\n  /*!\n   * \\brief move constructor\n   * \\param other source\n   */\n  Array(Array<T>&& other) : ObjectRef() {  // NOLINT(*)\n    data_ = std::move(other.data_);\n  }\n\n  /*!\n   * \\brief copy constructor\n   * \\param other source\n   */\n  Array(const Array<T>& other) : ObjectRef() {  // NOLINT(*)\n    data_ = other.data_;\n  }\n\n  /*!\n   * \\brief constructor from pointer\n   * \\param n the container pointer\n   */\n  explicit Array(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*!\n   * \\brief Constructor from iterator\n   * \\param first begin of iterator\n   * \\param last end of iterator\n   * \\tparam IterType The type of iterator\n   */\n  template <typename IterType>\n  Array(IterType first, IterType last) {\n    static_assert(is_valid_iterator_v<T, IterType>,\n                  \"IterType cannot be inserted into a tvm::Array<T>\");\n    Assign(first, last);\n  }\n\n  /*!\n   * \\brief constructor from initializer list\n   * \\param init The initializer list\n   */\n  Array(std::initializer_list<T> init) {  // NOLINT(*)\n    Assign(init.begin(), init.end());\n  }\n\n  /*!\n   * \\brief constructor from vector\n   * \\param init The vector\n   */\n  Array(const std::vector<T>& init) {  // NOLINT(*)\n    Assign(init.begin(), init.end());\n  }\n\n  /*!\n   * \\brief Constructs a container with n elements. Each element is a copy of val\n   * \\param n The size of the container\n   * \\param val The init value\n   */\n  explicit Array(const size_t n, const T& val) { data_ = ArrayNode::CreateRepeated(n, val); }\n\n  /*!\n   * \\brief move assign operator\n   * \\param other The source of assignment\n   * \\return reference to self.\n   */\n  Array<T>& operator=(Array<T>&& other) {\n    data_ = std::move(other.data_);\n    return *this;\n  }\n\n  /*!\n   * \\brief copy assign operator\n   * \\param other The source of assignment\n   * \\return reference to self.\n   */\n  Array<T>& operator=(const Array<T>& other) {\n    data_ = other.data_;\n    return *this;\n  }\n\n public:\n  // iterators\n  struct ValueConverter {\n    using ResultType = T;\n    static T convert(const ObjectRef& n) { return DowncastNoCheck<T>(n); }\n  };\n\n  using iterator = IterAdapter<ValueConverter, const ObjectRef*>;\n  using reverse_iterator = ReverseIterAdapter<ValueConverter, const ObjectRef*>;\n\n  /*! \\return begin iterator */\n  iterator begin() const { return iterator(GetArrayNode()->begin()); }\n\n  /*! \\return end iterator */\n  iterator end() const { return iterator(GetArrayNode()->end()); }\n\n  /*! \\return rbegin iterator */\n  reverse_iterator rbegin() const {\n    // ArrayNode::end() is never nullptr\n    return reverse_iterator(GetArrayNode()->end() - 1);\n  }\n\n  /*! \\return rend iterator */\n  reverse_iterator rend() const {\n    // ArrayNode::begin() is never nullptr\n    return reverse_iterator(GetArrayNode()->begin() - 1);\n  }\n\n public:\n  // const methods in std::vector\n  /*!\n   * \\brief Immutably read i-th element from array.\n   * \\param i The index\n   * \\return the i-th element.\n   */\n  const T operator[](int64_t i) const {\n    ArrayNode* p = GetArrayNode();\n    ICHECK(p != nullptr) << \"ValueError: cannot index a null array\";\n    ICHECK(0 <= i && i < p->size_)\n        << \"IndexError: indexing \" << i << \" on an array of size \" << p->size_;\n    return DowncastNoCheck<T>(*(p->begin() + i));\n  }\n\n  /*! \\return The size of the array */\n  size_t size() const {\n    ArrayNode* p = GetArrayNode();\n    return p == nullptr ? 0 : GetArrayNode()->size_;\n  }\n\n  /*! \\return The capacity of the array */\n  size_t capacity() const {\n    ArrayNode* p = GetArrayNode();\n    return p == nullptr ? 0 : GetArrayNode()->capacity_;\n  }\n\n  /*! \\return Whether array is empty */\n  bool empty() const { return size() == 0; }\n\n  /*! \\return The first element of the array */\n  const T front() const {\n    ArrayNode* p = GetArrayNode();\n    ICHECK(p != nullptr) << \"ValueError: cannot index a null array\";\n    ICHECK_GT(p->size_, 0) << \"IndexError: cannot index an empty array\";\n    return DowncastNoCheck<T>(*(p->begin()));\n  }\n\n  /*! \\return The last element of the array */\n  const T back() const {\n    ArrayNode* p = GetArrayNode();\n    ICHECK(p != nullptr) << \"ValueError: cannot index a null array\";\n    ICHECK_GT(p->size_, 0) << \"IndexError: cannot index an empty array\";\n    return DowncastNoCheck<T>(*(p->end() - 1));\n  }\n\n public:\n  // mutation in std::vector, implements copy-on-write\n\n  /*!\n   * \\brief push a new item to the back of the list\n   * \\param item The item to be pushed.\n   */\n  void push_back(const T& item) {\n    ArrayNode* p = CopyOnWrite(1);\n    p->EmplaceInit(p->size_++, item);\n  }\n\n  /*!\n   * \\brief Insert an element into the given position\n   * \\param position An iterator pointing to the insertion point\n   * \\param val The element to insert\n   */\n  void insert(iterator position, const T& val) {\n    ICHECK(data_ != nullptr) << \"ValueError: cannot insert a null array\";\n    int64_t idx = std::distance(begin(), position);\n    int64_t size = GetArrayNode()->size_;\n    auto addr = CopyOnWrite(1)                               //\n                    ->EnlargeBy(1)                           //\n                    ->MoveElementsRight(idx + 1, idx, size)  //\n                    ->MutableBegin();\n    new (addr + idx) ObjectRef(val);\n  }\n\n  /*!\n   * \\brief Insert a range of elements into the given position\n   * \\param position An iterator pointing to the insertion point\n   * \\param first The begin iterator of the range\n   * \\param last The end iterator of the range\n   */\n  template <typename IterType>\n  void insert(iterator position, IterType first, IterType last) {\n    static_assert(is_valid_iterator_v<T, IterType>,\n                  \"IterType cannot be inserted into a tvm::Array<T>\");\n\n    if (first == last) {\n      return;\n    }\n    ICHECK(data_ != nullptr) << \"ValueError: cannot insert a null array\";\n    int64_t idx = std::distance(begin(), position);\n    int64_t size = GetArrayNode()->size_;\n    int64_t numel = std::distance(first, last);\n    CopyOnWrite(numel)\n        ->EnlargeBy(numel)\n        ->MoveElementsRight(idx + numel, idx, size)\n        ->InitRange(idx, first, last);\n  }\n\n  /*! \\brief Remove the last item of the list */\n  void pop_back() {\n    ICHECK(data_ != nullptr) << \"ValueError: cannot pop_back because array is null\";\n    int64_t size = GetArrayNode()->size_;\n    ICHECK_GT(size, 0) << \"ValueError: cannot pop_back because array is empty\";\n    CopyOnWrite()->ShrinkBy(1);\n  }\n\n  /*!\n   * \\brief Erase an element on the given position\n   * \\param position An iterator pointing to the element to be erased\n   */\n  void erase(iterator position) {\n    ICHECK(data_ != nullptr) << \"ValueError: cannot erase a null array\";\n    int64_t st = std::distance(begin(), position);\n    int64_t size = GetArrayNode()->size_;\n    ICHECK(0 <= st && st < size) << \"ValueError: cannot erase at index \" << st\n                                 << \", because Array size is \" << size;\n    CopyOnWrite()                             //\n        ->MoveElementsLeft(st, st + 1, size)  //\n        ->ShrinkBy(1);\n  }\n\n  /*!\n   * \\brief Erase a given range of elements\n   * \\param first The begin iterator of the range\n   * \\param last The end iterator of the range\n   */\n  void erase(iterator first, iterator last) {\n    if (first == last) {\n      return;\n    }\n    ICHECK(data_ != nullptr) << \"ValueError: cannot erase a null array\";\n    int64_t size = GetArrayNode()->size_;\n    int64_t st = std::distance(begin(), first);\n    int64_t ed = std::distance(begin(), last);\n    ICHECK_LT(st, ed) << \"ValueError: cannot erase array in range [\" << st << \", \" << ed << \")\";\n    ICHECK(0 <= st && st <= size && 0 <= ed && ed <= size)\n        << \"ValueError: cannot erase array in range [\" << st << \", \" << ed << \")\"\n        << \", because array size is \" << size;\n    CopyOnWrite()                         //\n        ->MoveElementsLeft(st, ed, size)  //\n        ->ShrinkBy(ed - st);\n  }\n\n  /*!\n   * \\brief Resize the array.\n   * \\param n The new size.\n   */\n  void resize(int64_t n) {\n    ICHECK_GE(n, 0) << \"ValueError: cannot resize an Array to negative size\";\n    if (data_ == nullptr) {\n      SwitchContainer(n);\n      return;\n    }\n    int64_t size = GetArrayNode()->size_;\n    if (size < n) {\n      CopyOnWrite(n - size)->EnlargeBy(n - size);\n    } else if (size > n) {\n      CopyOnWrite()->ShrinkBy(size - n);\n    }\n  }\n\n  /*!\n   * \\brief Make sure the list has the capacity of at least n\n   * \\param n lower bound of the capacity\n   */\n  void reserve(int64_t n) {\n    if (data_ == nullptr || n > GetArrayNode()->capacity_) {\n      SwitchContainer(n);\n    }\n  }\n\n  /*! \\brief Release reference to all the elements */\n  void clear() {\n    if (data_ != nullptr) {\n      ArrayNode* p = CopyOnWrite();\n      p->clear();\n    }\n  }\n\n public:\n  // Array's own methods\n\n  /*!\n   * \\brief set i-th element of the array.\n   * \\param i The index\n   * \\param value The value to be setted.\n   */\n  void Set(int64_t i, T value) {\n    ArrayNode* p = this->CopyOnWrite();\n    ICHECK(0 <= i && i < p->size_)\n        << \"IndexError: indexing \" << i << \" on an array of size \" << p->size_;\n    *(p->MutableBegin() + i) = std::move(value);\n  }\n\n  /*! \\return The underlying ArrayNode */\n  ArrayNode* GetArrayNode() const { return static_cast<ArrayNode*>(data_.get()); }\n\n  /*!\n   * \\brief Helper function to apply a map function onto the array.\n   *\n   * \\param fmap The transformation function T -> U.\n   *\n   * \\tparam F The type of the mutation function.\n   *\n   * \\tparam U The type of the returned array, inferred from the\n   * return type of F.  If overridden by the user, must be something\n   * that is convertible from the return type of F.\n   *\n   * \\note This function performs copy on write optimization.  If\n   * `fmap` returns an object of type `T`, and all elements of the\n   * array are mapped to themselves, then the returned array will be\n   * the same as the original, and reference counts of the elements in\n   * the array will not be incremented.\n   *\n   * \\return The transformed array.\n   */\n  template <typename F, typename U = std::invoke_result_t<F, T>>\n  Array<U> Map(F fmap) const {\n    return Array<U>(MapHelper(data_, fmap));\n  }\n\n  /*!\n   * \\brief Helper function to apply fmutate to mutate an array.\n   * \\param fmutate The transformation function T -> T.\n   * \\tparam F the type of the mutation function.\n   * \\note This function performs copy on write optimization.\n   */\n  template <typename F, typename = std::enable_if_t<std::is_same_v<T, std::invoke_result_t<F, T>>>>\n  void MutateByApply(F fmutate) {\n    data_ = MapHelper(std::move(data_), fmutate);\n  }\n\n  /*!\n   * \\brief reset the array to content from iterator.\n   * \\param first begin of iterator\n   * \\param last end of iterator\n   * \\tparam IterType The type of iterator\n   */\n  template <typename IterType>\n  void Assign(IterType first, IterType last) {\n    int64_t cap = std::distance(first, last);\n    ICHECK_GE(cap, 0) << \"ValueError: cannot construct an Array of negative size\";\n    ArrayNode* p = GetArrayNode();\n    if (p != nullptr && data_.unique() && p->capacity_ >= cap) {\n      // do not have to make new space\n      p->clear();\n    } else {\n      // create new space\n      data_ = ArrayNode::Empty(cap);\n      p = GetArrayNode();\n    }\n    // To ensure exception safety, size is only incremented after the initialization succeeds\n    ObjectRef* itr = p->MutableBegin();\n    for (int64_t& i = p->size_ = 0; i < cap; ++i, ++first, ++itr) {\n      new (itr) ObjectRef(*first);\n    }\n  }\n\n  /*!\n   * \\brief Copy on write semantics\n   *  Do nothing if current handle is the unique copy of the array.\n   *  Otherwise make a new copy of the array to ensure the current handle\n   *  hold a unique copy.\n   *\n   * \\return Handle to the internal node container(which ganrantees to be unique)\n   */\n  ArrayNode* CopyOnWrite() {\n    if (data_ == nullptr) {\n      return SwitchContainer(ArrayNode::kInitSize);\n    }\n    if (!data_.unique()) {\n      return SwitchContainer(capacity());\n    }\n    return static_cast<ArrayNode*>(data_.get());\n  }\n\n  /*! \\brief specify container node */\n  using ContainerType = ArrayNode;\n\n private:\n  /*!\n   * \\brief Implement copy-on-write semantics, and ensures capacity is enough for extra elements.\n   * \\param reserve_extra Number of extra slots needed\n   * \\return ArrayNode pointer to the unique copy\n   */\n  ArrayNode* CopyOnWrite(int64_t reserve_extra) {\n    ArrayNode* p = GetArrayNode();\n    if (p == nullptr) {\n      // necessary to get around the constexpr address issue before c++17\n      const int64_t kInitSize = ArrayNode::kInitSize;\n      return SwitchContainer(std::max(kInitSize, reserve_extra));\n    }\n    if (p->capacity_ >= p->size_ + reserve_extra) {\n      return CopyOnWrite();\n    }\n    int64_t cap = p->capacity_ * ArrayNode::kIncFactor;\n    cap = std::max(cap, p->size_ + reserve_extra);\n    return SwitchContainer(cap);\n  }\n\n  /*!\n   * \\brief Move or copy the ArrayNode to new address with the given capacity\n   * \\param capacity The capacity requirement of the new address\n   */\n  ArrayNode* SwitchContainer(int64_t capacity) {\n    if (data_ == nullptr) {\n      data_ = ArrayNode::Empty(capacity);\n    } else if (data_.unique()) {\n      data_ = ArrayNode::MoveFrom(capacity, GetArrayNode());\n    } else {\n      data_ = ArrayNode::CopyFrom(capacity, GetArrayNode());\n    }\n    return static_cast<ArrayNode*>(data_.get());\n  }\n\n  /*! \\brief Helper method for mutate/map\n   *\n   * A helper function used internally by both `Array::Map` and\n   * `Array::MutateInPlace`.  Given an array of data, apply the\n   * mapping function to each element, returning the collected array.\n   * Applies both mutate-in-place and copy-on-write optimizations, if\n   * possible.\n   *\n   * \\param data A pointer to the ArrayNode containing input data.\n   * Passed by value to allow for mutate-in-place optimizations.\n   *\n   * \\param fmap The mapping function\n   *\n   * \\tparam F The type of the mutation function.\n   *\n   * \\tparam U The output type of the mutation function.  Inferred\n   * from the callable type given.  Must inherit from ObjectRef.\n   *\n   * \\return The mapped array.  Depending on whether mutate-in-place\n   * or copy-on-write optimizations were applicable, may be the same\n   * underlying array as the `data` parameter.\n   */\n  template <typename F, typename U = std::invoke_result_t<F, T>>\n  static ObjectPtr<Object> MapHelper(ObjectPtr<Object> data, F fmap) {\n    if (data == nullptr) {\n      return nullptr;\n    }\n\n    ICHECK(data->IsInstance<ArrayNode>());\n\n    constexpr bool is_same_output_type = std::is_same_v<T, U>;\n\n    if constexpr (is_same_output_type) {\n      if (data.unique()) {\n        // Mutate-in-place path.  Only allowed if the output type U is\n        // the same as type T, we have a mutable this*, and there are\n        // no other shared copies of the array.\n        auto arr = static_cast<ArrayNode*>(data.get());\n        for (auto it = arr->MutableBegin(); it != arr->MutableEnd(); it++) {\n          T mapped = fmap(DowncastNoCheck<T>(std::move(*it)));\n          *it = std::move(mapped);\n        }\n        return data;\n      }\n    }\n\n    constexpr bool compatible_types = is_valid_iterator_v<T, U*> || is_valid_iterator_v<U, T*>;\n\n    ObjectPtr<ArrayNode> output = nullptr;\n    auto arr = static_cast<ArrayNode*>(data.get());\n\n    auto it = arr->begin();\n    if constexpr (compatible_types) {\n      // Copy-on-write path, if the output Array<U> might be\n      // represented by the same underlying array as the existing\n      // Array<T>.  Typically, this is for functions that map `T` to\n      // `T`, but can also apply to functions that map `T` to\n      // `Optional<T>`, or that map `T` to a subclass or superclass of\n      // `T`.\n      bool all_identical = true;\n      for (; it != arr->end(); it++) {\n        U mapped = fmap(DowncastNoCheck<T>(*it));\n        if (!mapped.same_as(*it)) {\n          // At least one mapped element is different than the\n          // original.  Therefore, prepare the output array,\n          // consisting of any previous elements that had mapped to\n          // themselves (if any), and the element that didn't map to\n          // itself.\n          all_identical = false;\n          output = ArrayNode::CreateRepeated(arr->size(), U());\n          output->InitRange(0, arr->begin(), it);\n          output->SetItem(it - arr->begin(), std::move(mapped));\n          it++;\n          break;\n        }\n      }\n      if (all_identical) {\n        return data;\n      }\n    } else {\n      // Path for incompatible types.  The constexpr check for\n      // compatible types isn't strictly necessary, as the first\n      // mapped.same_as(*it) would return false, but we might as well\n      // avoid it altogether.\n      output = ArrayNode::CreateRepeated(arr->size(), U());\n    }\n\n    // Normal path for incompatible types, or post-copy path for\n    // copy-on-write instances.\n    //\n    // If the types are incompatible, then at this point `output` is\n    // empty, and `it` points to the first element of the input.\n    //\n    // If the types were compatible, then at this point `output`\n    // contains zero or more elements that mapped to themselves\n    // followed by the first element that does not map to itself, and\n    // `it` points to the element just after the first element that\n    // does not map to itself.  Because at least one element has been\n    // changed, we no longer have the opportunity to avoid a copy, so\n    // we don't need to check the result.\n    //\n    // In both cases, `it` points to the next element to be processed,\n    // so we can either start or resume the iteration from that point,\n    // with no further checks on the result.\n    for (; it != arr->end(); it++) {\n      U mapped = fmap(DowncastNoCheck<T>(*it));\n      output->SetItem(it - arr->begin(), std::move(mapped));\n    }\n\n    return output;\n  }\n};\n\n/*!\n * \\brief Concat two Arrays.\n * \\param lhs first Array to be concatenated.\n * \\param rhs second Array to be concatenated.\n * \\return The concatenated Array. Original Arrays are kept unchanged.\n */\ntemplate <typename T,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, T>::value>::type>\ninline Array<T> Concat(Array<T> lhs, const Array<T>& rhs) {\n  for (const auto& x : rhs) {\n    lhs.push_back(x);\n  }\n  return std::move(lhs);\n}\n\n// Specialize make_object<ArrayNode> to make sure it is correct.\ntemplate <>\ninline ObjectPtr<ArrayNode> make_object() {\n  return ArrayNode::Empty();\n}\n\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::Array;\nusing runtime::ArrayNode;\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_ARRAY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/base.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/base.h\n * \\brief Base utilities for common POD(plain old data) container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_BASE_H_\n#define TVM_RUNTIME_CONTAINER_BASE_H_\n\n#include <dmlc/logging.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/memory.h>\n#include <tvm/runtime/object.h>\n\n#include <algorithm>\n#include <initializer_list>\n#include <utility>\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief String-aware ObjectRef equal functor */\nstruct ObjectHash {\n  /*!\n   * \\brief Calculate the hash code of an ObjectRef\n   * \\param a The given ObjectRef\n   * \\return Hash code of a, string hash for strings and pointer address otherwise.\n   */\n  size_t operator()(const ObjectRef& a) const;\n};\n\n/*! \\brief String-aware ObjectRef hash functor */\nstruct ObjectEqual {\n  /*!\n   * \\brief Check if the two ObjectRef are equal\n   * \\param a One ObjectRef\n   * \\param b The other ObjectRef\n   * \\return String equality if both are strings, pointer address equality otherwise.\n   */\n  bool operator()(const ObjectRef& a, const ObjectRef& b) const;\n};\n\n/*!\n * \\brief Base template for classes with array like memory layout.\n *\n *        It provides general methods to access the memory. The memory\n *        layout is ArrayType + [ElemType]. The alignment of ArrayType\n *        and ElemType is handled by the memory allocator.\n *\n * \\tparam ArrayType The array header type, contains object specific metadata.\n * \\tparam ElemType The type of objects stored in the array right after\n * ArrayType.\n *\n * \\code\n * // Example usage of the template to define a simple array wrapper\n * class ArrayObj : public InplaceArrayBase<ArrayObj, Elem> {\n * public:\n *  // Wrap EmplaceInit to initialize the elements\n *  template <typename Iterator>\n *  void Init(Iterator begin, Iterator end) {\n *   size_t num_elems = std::distance(begin, end);\n *   auto it = begin;\n *   this->size = 0;\n *   for (size_t i = 0; i < num_elems; ++i) {\n *     InplaceArrayBase::EmplaceInit(i, *it++);\n *     this->size++;\n *   }\n *  }\n * }\n *\n * void test_function() {\n *   vector<Elem> fields;\n *   auto ptr = make_inplace_array_object<ArrayObj, Elem>(fields.size());\n *   ptr->Init(fields.begin(), fields.end());\n *\n *   // Access the 0th element in the array.\n *   assert(ptr->operator[](0) == fields[0]);\n * }\n *\n * \\endcode\n */\ntemplate <typename ArrayType, typename ElemType>\nclass InplaceArrayBase {\n public:\n  /*!\n   * \\brief Access element at index\n   * \\param idx The index of the element.\n   * \\return Const reference to ElemType at the index.\n   */\n  const ElemType& operator[](size_t idx) const {\n    size_t size = Self()->GetSize();\n    ICHECK_LT(idx, size) << \"Index \" << idx << \" out of bounds \" << size << \"\\n\";\n    return *(reinterpret_cast<ElemType*>(AddressOf(idx)));\n  }\n\n  /*!\n   * \\brief Access element at index\n   * \\param idx The index of the element.\n   * \\return Reference to ElemType at the index.\n   */\n  ElemType& operator[](size_t idx) {\n    size_t size = Self()->GetSize();\n    ICHECK_LT(idx, size) << \"Index \" << idx << \" out of bounds \" << size << \"\\n\";\n    return *(reinterpret_cast<ElemType*>(AddressOf(idx)));\n  }\n\n  /*!\n   * \\brief Destroy the Inplace Array Base object\n   */\n  ~InplaceArrayBase() {\n    if (!(std::is_standard_layout<ElemType>::value && std::is_trivial<ElemType>::value)) {\n      size_t size = Self()->GetSize();\n      for (size_t i = 0; i < size; ++i) {\n        ElemType* fp = reinterpret_cast<ElemType*>(AddressOf(i));\n        fp->ElemType::~ElemType();\n      }\n    }\n  }\n\n protected:\n  /*!\n   * \\brief Construct a value in place with the arguments.\n   *\n   * \\tparam Args Type parameters of the arguments.\n   * \\param idx Index of the element.\n   * \\param args Arguments to construct the new value.\n   *\n   * \\note Please make sure ArrayType::GetSize returns 0 before first call of\n   * EmplaceInit, and increment GetSize by 1 each time EmplaceInit succeeds.\n   */\n  template <typename... Args>\n  void EmplaceInit(size_t idx, Args&&... args) {\n    void* field_ptr = AddressOf(idx);\n    new (field_ptr) ElemType(std::forward<Args>(args)...);\n  }\n\n  /*!\n   * \\brief Return the self object for the array.\n   *\n   * \\return Pointer to ArrayType.\n   */\n  inline ArrayType* Self() const {\n    return static_cast<ArrayType*>(const_cast<InplaceArrayBase*>(this));\n  }\n\n  /*!\n   * \\brief Return the raw pointer to the element at idx.\n   *\n   * \\param idx The index of the element.\n   * \\return Raw pointer to the element.\n   */\n  void* AddressOf(size_t idx) const {\n    static_assert(\n        alignof(ArrayType) % alignof(ElemType) == 0 && sizeof(ArrayType) % alignof(ElemType) == 0,\n        \"The size and alignment of ArrayType should respect \"\n        \"ElemType's alignment.\");\n\n    size_t kDataStart = sizeof(ArrayType);\n    ArrayType* self = Self();\n    char* data_start = reinterpret_cast<char*>(self) + kDataStart;\n    return data_start + idx * sizeof(ElemType);\n  }\n};\n\n/*!\n * \\brief iterator adapter that adapts TIter to return another type.\n * \\tparam Converter a struct that contains converting function\n * \\tparam TIter the content iterator type.\n */\ntemplate <typename Converter, typename TIter>\nclass IterAdapter {\n public:\n  using difference_type = typename std::iterator_traits<TIter>::difference_type;\n  using value_type = typename Converter::ResultType;\n  using pointer = typename Converter::ResultType*;\n  using reference = typename Converter::ResultType&;\n  using iterator_category = typename std::iterator_traits<TIter>::iterator_category;\n\n  explicit IterAdapter(TIter iter) : iter_(iter) {}\n  IterAdapter& operator++() {\n    ++iter_;\n    return *this;\n  }\n  IterAdapter& operator--() {\n    --iter_;\n    return *this;\n  }\n  IterAdapter operator++(int) {\n    IterAdapter copy = *this;\n    ++iter_;\n    return copy;\n  }\n  IterAdapter operator--(int) {\n    IterAdapter copy = *this;\n    --iter_;\n    return copy;\n  }\n\n  IterAdapter operator+(difference_type offset) const { return IterAdapter(iter_ + offset); }\n\n  IterAdapter operator-(difference_type offset) const { return IterAdapter(iter_ - offset); }\n\n  template <typename T = IterAdapter>\n  typename std::enable_if<std::is_same<iterator_category, std::random_access_iterator_tag>::value,\n                          typename T::difference_type>::type inline\n  operator-(const IterAdapter& rhs) const {\n    return iter_ - rhs.iter_;\n  }\n\n  bool operator==(IterAdapter other) const { return iter_ == other.iter_; }\n  bool operator!=(IterAdapter other) const { return !(*this == other); }\n  const value_type operator*() const { return Converter::convert(*iter_); }\n\n private:\n  TIter iter_;\n};\n\n/*!\n * \\brief iterator adapter that adapts TIter to return another type.\n * \\tparam Converter a struct that contains converting function\n * \\tparam TIter the content iterator type.\n */\ntemplate <typename Converter, typename TIter>\nclass ReverseIterAdapter {\n public:\n  using difference_type = typename std::iterator_traits<TIter>::difference_type;\n  using value_type = typename Converter::ResultType;\n  using pointer = typename Converter::ResultType*;\n  using reference = typename Converter::ResultType&;  // NOLINT(*)\n  using iterator_category = typename std::iterator_traits<TIter>::iterator_category;\n\n  explicit ReverseIterAdapter(TIter iter) : iter_(iter) {}\n  ReverseIterAdapter& operator++() {\n    --iter_;\n    return *this;\n  }\n  ReverseIterAdapter& operator--() {\n    ++iter_;\n    return *this;\n  }\n  ReverseIterAdapter operator++(int) {\n    ReverseIterAdapter copy = *this;\n    --iter_;\n    return copy;\n  }\n  ReverseIterAdapter operator--(int) {\n    ReverseIterAdapter copy = *this;\n    ++iter_;\n    return copy;\n  }\n  ReverseIterAdapter operator+(difference_type offset) const {\n    return ReverseIterAdapter(iter_ - offset);\n  }\n\n  template <typename T = ReverseIterAdapter>\n  typename std::enable_if<std::is_same<iterator_category, std::random_access_iterator_tag>::value,\n                          typename T::difference_type>::type inline\n  operator-(const ReverseIterAdapter& rhs) const {\n    return rhs.iter_ - iter_;\n  }\n\n  bool operator==(ReverseIterAdapter other) const { return iter_ == other.iter_; }\n  bool operator!=(ReverseIterAdapter other) const { return !(*this == other); }\n  const value_type operator*() const { return Converter::convert(*iter_); }\n\n private:\n  TIter iter_;\n};\n\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::Downcast;\nusing runtime::IterAdapter;\nusing runtime::make_object;\nusing runtime::Object;\nusing runtime::ObjectEqual;\nusing runtime::ObjectHash;\nusing runtime::ObjectPtr;\nusing runtime::ObjectPtrEqual;\nusing runtime::ObjectPtrHash;\nusing runtime::ObjectRef;\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/closure.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/closure.h\n * \\brief Runtime Closure container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_CLOSURE_H_\n#define TVM_RUNTIME_CONTAINER_CLOSURE_H_\n\n#include \"./base.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief An object representing a closure. This object is used by both the\n * Relay VM and interpreter.\n */\nclass ClosureObj : public Object {\n public:\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeClosure;\n  static constexpr const char* _type_key = \"runtime.Closure\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ClosureObj, Object);\n};\n\n/*! \\brief reference to closure. */\nclass Closure : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(Closure, ObjectRef, ClosureObj);\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_CLOSURE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/map.h\n * \\brief Runtime Map container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_MAP_H_\n#define TVM_RUNTIME_CONTAINER_MAP_H_\n\n#ifndef USE_FALLBACK_STL_MAP\n#define USE_FALLBACK_STL_MAP 0\n#endif\n\n#include <algorithm>\n#include <unordered_map>\n#include <utility>\n\n#include \"./base.h\"\n#include \"./optional.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n#if TVM_LOG_DEBUG\n#define TVM_MAP_FAIL_IF_CHANGED() \\\n  ICHECK(state_marker == self->state_marker) << \"Concurrent modification of the Map\";\n#else\n#define TVM_MAP_FAIL_IF_CHANGED()\n#endif  // TVM_LOG_DEBUG\n\n#if (USE_FALLBACK_STL_MAP != 0)\n\n/*! \\brief Shared content of all specializations of hash map */\nclass MapNode : public Object {\n public:\n  /*! \\brief Type of the keys in the hash map */\n  using key_type = ObjectRef;\n  /*! \\brief Type of the values in the hash map */\n  using mapped_type = ObjectRef;\n  /*! \\brief Type of the actual underlying container */\n  using ContainerType = std::unordered_map<ObjectRef, ObjectRef, ObjectHash, ObjectEqual>;\n  /*! \\brief Iterator class */\n  using iterator = ContainerType::iterator;\n  /*! \\brief Iterator class */\n  using const_iterator = ContainerType::const_iterator;\n  /*! \\brief Type of value stored in the hash map */\n  using KVType = ContainerType::value_type;\n\n  static_assert(std::is_standard_layout<KVType>::value, \"KVType is not standard layout\");\n  static_assert(sizeof(KVType) == 16 || sizeof(KVType) == 8, \"sizeof(KVType) incorrect\");\n\n  static constexpr const uint32_t _type_index = runtime::TypeIndex::kRuntimeMap;\n  static constexpr const char* _type_key = \"Map\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MapNode, Object);\n\n  /*!\n   * \\brief Number of elements in the SmallMapNode\n   * \\return The result\n   */\n  size_t size() const { return data_.size(); }\n  /*!\n   * \\brief Count the number of times a key exists in the hash map\n   * \\param key The indexing key\n   * \\return The result, 0 or 1\n   */\n  size_t count(const key_type& key) const { return data_.count(key); }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The const reference to the value\n   */\n  const mapped_type& at(const key_type& key) const { return data_.at(key); }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The mutable reference to the value\n   */\n  mapped_type& at(const key_type& key) { return data_.at(key); }\n  /*! \\return begin iterator */\n  iterator begin() { return data_.begin(); }\n  /*! \\return const begin iterator */\n  const_iterator begin() const { return data_.begin(); }\n  /*! \\return end iterator */\n  iterator end() { return data_.end(); }\n  /*! \\return end iterator */\n  const_iterator end() const { return data_.end(); }\n  /*!\n   * \\brief Index value associated with a key\n   * \\param key The indexing key\n   * \\return The iterator of the entry associated with the key, end iterator if not exists\n   */\n  const_iterator find(const key_type& key) const { return data_.find(key); }\n  /*!\n   * \\brief Index value associated with a key\n   * \\param key The indexing key\n   * \\return The iterator of the entry associated with the key, end iterator if not exists\n   */\n  iterator find(const key_type& key) { return data_.find(key); }\n  /*!\n   * \\brief Erase the entry associated with the iterator\n   * \\param position The iterator\n   */\n  void erase(const iterator& position) { data_.erase(position); }\n  /*!\n   * \\brief Erase the entry associated with the key, do nothing if not exists\n   * \\param key The indexing key\n   */\n  void erase(const key_type& key) { data_.erase(key); }\n  /*!\n   * \\brief Create an empty container\n   * \\return The object created\n   */\n  static ObjectPtr<MapNode> Empty() { return make_object<MapNode>(); }\n\n protected:\n  /*!\n   * \\brief Create the map using contents from the given iterators.\n   * \\param first Begin of iterator\n   * \\param last End of iterator\n   * \\tparam IterType The type of iterator\n   * \\return ObjectPtr to the map created\n   */\n  template <typename IterType>\n  static ObjectPtr<Object> CreateFromRange(IterType first, IterType last) {\n    ObjectPtr<MapNode> p = make_object<MapNode>();\n    p->data_ = ContainerType(first, last);\n    return p;\n  }\n  /*!\n   * \\brief InsertMaybeReHash an entry into the given hash map\n   * \\param kv The entry to be inserted\n   * \\param map The pointer to the map, can be changed if re-hashing happens\n   */\n  static void InsertMaybeReHash(const KVType& kv, ObjectPtr<Object>* map) {\n    MapNode* map_node = static_cast<MapNode*>(map->get());\n    map_node->data_[kv.first] = kv.second;\n  }\n  /*!\n   * \\brief Create an empty container with elements copying from another MapNode\n   * \\param from The source container\n   * \\return The object created\n   */\n  static ObjectPtr<MapNode> CopyFrom(MapNode* from) {\n    ObjectPtr<MapNode> p = make_object<MapNode>();\n    p->data_ = ContainerType(from->data_.begin(), from->data_.end());\n    return p;\n  }\n  /*! \\brief The real container storing data */\n  ContainerType data_;\n  template <typename, typename, typename, typename>\n  friend class Map;\n};\n\n#else\n\n/*! \\brief Shared content of all specializations of hash map */\nclass MapNode : public Object {\n public:\n  /*! \\brief Type of the keys in the hash map */\n  using key_type = ObjectRef;\n  /*! \\brief Type of the values in the hash map */\n  using mapped_type = ObjectRef;\n  /*! \\brief Type of value stored in the hash map */\n  using KVType = std::pair<ObjectRef, ObjectRef>;\n  /*! \\brief Iterator class */\n  class iterator;\n\n  static_assert(std::is_standard_layout<KVType>::value, \"KVType is not standard layout\");\n  static_assert(sizeof(KVType) == 16 || sizeof(KVType) == 8, \"sizeof(KVType) incorrect\");\n\n  static constexpr const uint32_t _type_index = runtime::TypeIndex::kRuntimeMap;\n  static constexpr const char* _type_key = \"Map\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MapNode, Object);\n\n  /*!\n   * \\brief Number of elements in the SmallMapNode\n   * \\return The result\n   */\n  size_t size() const { return size_; }\n  /*!\n   * \\brief Count the number of times a key exists in the hash map\n   * \\param key The indexing key\n   * \\return The result, 0 or 1\n   */\n  size_t count(const key_type& key) const;\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The const reference to the value\n   */\n  const mapped_type& at(const key_type& key) const;\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The mutable reference to the value\n   */\n  mapped_type& at(const key_type& key);\n  /*! \\return begin iterator */\n  iterator begin() const;\n  /*! \\return end iterator */\n  iterator end() const;\n  /*!\n   * \\brief Index value associated with a key\n   * \\param key The indexing key\n   * \\return The iterator of the entry associated with the key, end iterator if not exists\n   */\n  iterator find(const key_type& key) const;\n  /*!\n   * \\brief Erase the entry associated with the iterator\n   * \\param position The iterator\n   */\n  void erase(const iterator& position);\n  /*!\n   * \\brief Erase the entry associated with the key, do nothing if not exists\n   * \\param key The indexing key\n   */\n  void erase(const key_type& key) { erase(find(key)); }\n\n  class iterator {\n   public:\n    using iterator_category = std::forward_iterator_tag;\n    using difference_type = int64_t;\n    using value_type = KVType;\n    using pointer = KVType*;\n    using reference = KVType&;\n/*! \\brief Default constructor */\n#if TVM_LOG_DEBUG\n    iterator() : state_marker(0), index(0), self(nullptr) {}\n#else\n    iterator() : index(0), self(nullptr) {}\n#endif  // TVM_LOG_DEBUG\n    /*! \\brief Compare iterators */\n    bool operator==(const iterator& other) const {\n      TVM_MAP_FAIL_IF_CHANGED()\n      return index == other.index && self == other.self;\n    }\n    /*! \\brief Compare iterators */\n    bool operator!=(const iterator& other) const { return !(*this == other); }\n    /*! \\brief De-reference iterators */\n    pointer operator->() const;\n    /*! \\brief De-reference iterators */\n    reference operator*() const {\n      TVM_MAP_FAIL_IF_CHANGED()\n      return *((*this).operator->());\n    }\n    /*! \\brief Prefix self increment, e.g. ++iter */\n    iterator& operator++();\n    /*! \\brief Prefix self decrement, e.g. --iter */\n    iterator& operator--();\n    /*! \\brief Suffix self increment */\n    iterator operator++(int) {\n      TVM_MAP_FAIL_IF_CHANGED()\n      iterator copy = *this;\n      ++(*this);\n      return copy;\n    }\n    /*! \\brief Suffix self decrement */\n    iterator operator--(int) {\n      TVM_MAP_FAIL_IF_CHANGED()\n      iterator copy = *this;\n      --(*this);\n      return copy;\n    }\n\n   protected:\n#if TVM_LOG_DEBUG\n    uint64_t state_marker;\n    /*! \\brief Construct by value */\n    iterator(uint64_t index, const MapNode* self)\n        : state_marker(self->state_marker), index(index), self(self) {}\n\n#else\n    iterator(uint64_t index, const MapNode* self) : index(index), self(self) {}\n#endif  // TVM_LOG_DEBUG\n    /*! \\brief The position on the array */\n    uint64_t index;\n    /*! \\brief The container it points to */\n    const MapNode* self;\n\n    friend class DenseMapNode;\n    friend class SmallMapNode;\n  };\n  /*!\n   * \\brief Create an empty container\n   * \\return The object created\n   */\n  static inline ObjectPtr<MapNode> Empty();\n\n protected:\n#if TVM_LOG_DEBUG\n  uint64_t state_marker;\n#endif  // TVM_LOG_DEBUG\n  /*!\n   * \\brief Create the map using contents from the given iterators.\n   * \\param first Begin of iterator\n   * \\param last End of iterator\n   * \\tparam IterType The type of iterator\n   * \\return ObjectPtr to the map created\n   */\n  template <typename IterType>\n  static inline ObjectPtr<Object> CreateFromRange(IterType first, IterType last);\n  /*!\n   * \\brief InsertMaybeReHash an entry into the given hash map\n   * \\param kv The entry to be inserted\n   * \\param map The pointer to the map, can be changed if re-hashing happens\n   */\n  static inline void InsertMaybeReHash(const KVType& kv, ObjectPtr<Object>* map);\n  /*!\n   * \\brief Create an empty container with elements copying from another SmallMapNode\n   * \\param from The source container\n   * \\return The object created\n   */\n  static inline ObjectPtr<MapNode> CopyFrom(MapNode* from);\n  /*! \\brief number of slots minus 1 */\n  uint64_t slots_;\n  /*! \\brief number of entries in the container */\n  uint64_t size_;\n  // Reference class\n  template <typename, typename, typename, typename>\n  friend class Map;\n};\n\n/*! \\brief A specialization of small-sized hash map */\nclass SmallMapNode : public MapNode,\n                     public runtime::InplaceArrayBase<SmallMapNode, MapNode::KVType> {\n private:\n  static constexpr uint64_t kInitSize = 2;\n  static constexpr uint64_t kMaxSize = 4;\n\n public:\n  using MapNode::iterator;\n  using MapNode::KVType;\n\n  /*! \\brief Defaults to the destructor of InplaceArrayBase */\n  ~SmallMapNode() = default;\n  /*!\n   * \\brief Count the number of times a key exists in the SmallMapNode\n   * \\param key The indexing key\n   * \\return The result, 0 or 1\n   */\n  size_t count(const key_type& key) const { return find(key).index < size_; }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The const reference to the value\n   */\n  const mapped_type& at(const key_type& key) const {\n    iterator itr = find(key);\n    ICHECK(itr.index < size_) << \"IndexError: key is not in Map\";\n    return itr->second;\n  }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The mutable reference to the value\n   */\n  mapped_type& at(const key_type& key) {\n    iterator itr = find(key);\n    ICHECK(itr.index < size_) << \"IndexError: key is not in Map\";\n    return itr->second;\n  }\n  /*! \\return begin iterator */\n  iterator begin() const { return iterator(0, this); }\n  /*! \\return end iterator */\n  iterator end() const { return iterator(size_, this); }\n  /*!\n   * \\brief Index value associated with a key\n   * \\param key The indexing key\n   * \\return The iterator of the entry associated with the key, end iterator if not exists\n   */\n  iterator find(const key_type& key) const {\n    KVType* ptr = static_cast<KVType*>(AddressOf(0));\n    for (uint64_t i = 0; i < size_; ++i, ++ptr) {\n      if (ObjectEqual()(ptr->first, key)) {\n        return iterator(i, this);\n      }\n    }\n    return iterator(size_, this);\n  }\n  /*!\n   * \\brief Erase the entry associated with the iterator\n   * \\param position The iterator\n   */\n  void erase(const iterator& position) { Erase(position.index); }\n\n private:\n  /*!\n   * \\brief Remove a position in SmallMapNode\n   * \\param index The position to be removed\n   */\n  void Erase(const uint64_t index) {\n    if (index >= size_) {\n      return;\n    }\n    KVType* begin = static_cast<KVType*>(AddressOf(0));\n    KVType* last = begin + (size_ - 1);\n    if (index + 1 == size_) {\n      last->first.ObjectRef::~ObjectRef();\n      last->second.ObjectRef::~ObjectRef();\n    } else {\n      *(begin + index) = std::move(*last);\n    }\n    size_ -= 1;\n  }\n  /*!\n   * \\brief Create an empty container\n   * \\param n Number of empty slots\n   * \\return The object created\n   */\n  static ObjectPtr<SmallMapNode> Empty(uint64_t n = kInitSize) {\n    using ::tvm::runtime::make_inplace_array_object;\n    ObjectPtr<SmallMapNode> p = make_inplace_array_object<SmallMapNode, KVType>(n);\n    p->size_ = 0;\n    p->slots_ = n;\n    return p;\n  }\n  /*!\n   * \\brief Create an empty container initialized with a given range\n   * \\param n Number of empty slots\n   * \\param first begin of iterator\n   * \\param last end of iterator\n   * \\tparam IterType The type of iterator\n   * \\return The object created\n   */\n  template <typename IterType>\n  static ObjectPtr<SmallMapNode> CreateFromRange(uint64_t n, IterType first, IterType last) {\n    ObjectPtr<SmallMapNode> p = Empty(n);\n    KVType* ptr = static_cast<KVType*>(p->AddressOf(0));\n    for (; first != last; ++first, ++p->size_) {\n      new (ptr++) KVType(*first);\n    }\n    return p;\n  }\n  /*!\n   * \\brief Create an empty container with elements copying from another SmallMapNode\n   * \\param from The source container\n   * \\return The object created\n   */\n  static ObjectPtr<SmallMapNode> CopyFrom(SmallMapNode* from) {\n    KVType* first = static_cast<KVType*>(from->AddressOf(0));\n    KVType* last = first + from->size_;\n    return CreateFromRange(from->size_, first, last);\n  }\n  /*!\n   * \\brief InsertMaybeReHash an entry into the given hash map\n   * \\param kv The entry to be inserted\n   * \\param map The pointer to the map, can be changed if re-hashing happens\n   */\n  static void InsertMaybeReHash(const KVType& kv, ObjectPtr<Object>* map) {\n    SmallMapNode* map_node = static_cast<SmallMapNode*>(map->get());\n    iterator itr = map_node->find(kv.first);\n    if (itr.index < map_node->size_) {\n      itr->second = kv.second;\n      return;\n    }\n    if (map_node->size_ < map_node->slots_) {\n      KVType* ptr = static_cast<KVType*>(map_node->AddressOf(map_node->size_));\n      new (ptr) KVType(kv);\n      ++map_node->size_;\n      return;\n    }\n    uint64_t next_size = std::max(map_node->slots_ * 2, uint64_t(kInitSize));\n    next_size = std::min(next_size, uint64_t(kMaxSize));\n    ICHECK_GT(next_size, map_node->slots_);\n    ObjectPtr<Object> new_map = CreateFromRange(next_size, map_node->begin(), map_node->end());\n    InsertMaybeReHash(kv, &new_map);\n    *map = std::move(new_map);\n  }\n  /*!\n   * \\brief Increment the pointer\n   * \\param index The pointer to be incremented\n   * \\return The increased pointer\n   */\n  uint64_t IncItr(uint64_t index) const { return index + 1 < size_ ? index + 1 : size_; }\n  /*!\n   * \\brief Decrement the pointer\n   * \\param index The pointer to be decremented\n   * \\return The decreased pointer\n   */\n  uint64_t DecItr(uint64_t index) const { return index > 0 ? index - 1 : size_; }\n  /*!\n   * \\brief De-reference the pointer\n   * \\param index The pointer to be dereferenced\n   * \\return The result\n   */\n  KVType* DeRefItr(uint64_t index) const { return static_cast<KVType*>(AddressOf(index)); }\n  /*! \\brief A size function used by InplaceArrayBase */\n  uint64_t GetSize() const { return size_; }\n\n protected:\n  friend class MapNode;\n  friend class DenseMapNode;\n  friend class runtime::InplaceArrayBase<SmallMapNode, MapNode::KVType>;\n};\n\n/*! \\brief A specialization of hash map that implements the idea of array-based hash map.\n * Another reference implementation can be found [1].\n *\n * A. Overview\n *\n * DenseMapNode did several improvements over traditional separate chaining hash,\n * in terms of cache locality, memory footprints and data organization.\n *\n * A1. Implicit linked list. For better cache locality, instead of using linked list\n * explicitly for each bucket, we store list data into a single array that spans contiguously\n * in memory, and then carefully design access patterns to make sure most of them fall into\n * a single cache line.\n *\n * A2. 1-byte metadata. There is only 1 byte overhead for each slot in the array to indexing and\n * traversal. This can be divided in 3 parts.\n * 1) Reserved code: (0b11111111)_2 indicates a slot is empty; (0b11111110)_2 indicates protected,\n * which means the slot is empty but not allowed to be written.\n * 2) If not empty or protected, the highest bit is used to indicate whether data in the slot is\n * head of a linked list.\n * 3) The rest 7 bits are used as the \"next pointer\" (i.e. pointer to the next element). On 64-bit\n * architecture, an ordinary pointer can take up to 8 bytes, which is not acceptable overhead when\n * dealing with 16-byte ObjectRef pairs. Based on a commonly noticed fact that the lists are\n * relatively short (length <= 3) in hash maps, we follow [1]'s idea that only allows the pointer to\n * be one of the 126 possible values, i.e. if the next element of i-th slot is (i + x)-th element,\n * then x must be one of the 126 pre-defined values.\n *\n * A3. Data blocking. We organize the array in the way that every 16 elements forms a data block.\n * The 16-byte metadata of those 16 elements are stored together, followed by the real data, i.e.\n * 16 key-value pairs.\n *\n * B. Implementation details\n *\n * B1. Power-of-2 table size and Fibonacci Hashing. We use power-of-two as table size to avoid\n * modulo for more efficient arithmetics. To make the hash-to-slot mapping distribute more evenly,\n * we use the Fibonacci Hashing [2] trick.\n *\n * B2. Traverse a linked list in the array.\n * 1) List head. Assume Fibonacci Hashing maps a given key to slot i, if metadata at slot i\n * indicates that it is list head, then we found the head; otherwise the list is empty. No probing\n * is done in this procedure. 2) Next element. To find the next element of a non-empty slot i, we\n * look at the last 7 bits of the metadata at slot i. If they are all zeros, then it is the end of\n * list; otherwise, we know that the next element is (i + candidates[the-last-7-bits]).\n *\n * B3. InsertMaybeReHash an element. Following B2, we first traverse the linked list to see if this\n * element is in the linked list, and if not, we put it at the end by probing the next empty\n * position in one of the 126 candidate positions. If the linked list does not even exist, but the\n * slot for list head has been occupied by another linked list, we should find this intruder another\n * place.\n *\n * B4. Quadratic probing with triangle numbers. In open address hashing, it is provable that probing\n * with triangle numbers can traverse power-of-2-sized table [3]. In our algorithm, we follow the\n * suggestion in [1] that also use triangle numbers for \"next pointer\" as well as sparing for list\n * head.\n *\n * [1] https://github.com/skarupke/flat_hash_map\n * [2] https://programmingpraxis.com/2018/06/19/fibonacci-hash/\n * [3] https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/\n */\nclass DenseMapNode : public MapNode {\n private:\n  /*! \\brief The number of elements in a memory block */\n  static constexpr int kBlockCap = 16;\n  /*! \\brief Maximum load factor of the hash map */\n  static constexpr double kMaxLoadFactor = 0.99;\n  /*! \\brief Binary representation of the metadata of an empty slot */\n  static constexpr uint8_t kEmptySlot = uint8_t(0b11111111);\n  /*! \\brief Binary representation of the metadata of a protected slot */\n  static constexpr uint8_t kProtectedSlot = uint8_t(0b11111110);\n  /*! \\brief Number of probing choices available */\n  static constexpr int kNumJumpDists = 126;\n  /*! \\brief Head of the implicit linked list */\n  struct ListNode;\n  /*! \\brief POD type of a block of memory */\n  struct Block {\n    uint8_t bytes[kBlockCap + kBlockCap * sizeof(KVType)];\n  };\n  static_assert(sizeof(Block) == kBlockCap * (sizeof(KVType) + 1), \"sizeof(Block) incorrect\");\n  static_assert(std::is_standard_layout<Block>::value, \"Block is not standard layout\");\n\n public:\n  using MapNode::iterator;\n\n  /*!\n   * \\brief Destroy the DenseMapNode\n   */\n  ~DenseMapNode() { this->Reset(); }\n  /*! \\return The number of elements of the key */\n  size_t count(const key_type& key) const { return !Search(key).IsNone(); }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The const reference to the value\n   */\n  const mapped_type& at(const key_type& key) const { return At(key); }\n  /*!\n   * \\brief Index value associated with a key, throw exception if the key does not exist\n   * \\param key The indexing key\n   * \\return The mutable reference to the value\n   */\n  mapped_type& at(const key_type& key) { return At(key); }\n  /*!\n   * \\brief Index value associated with a key\n   * \\param key The indexing key\n   * \\return The iterator of the entry associated with the key, end iterator if not exists\n   */\n  iterator find(const key_type& key) const {\n    ListNode node = Search(key);\n    return node.IsNone() ? end() : iterator(node.index, this);\n  }\n  /*!\n   * \\brief Erase the entry associated with the iterator\n   * \\param position The iterator\n   */\n  void erase(const iterator& position) {\n    uint64_t index = position.index;\n    if (position.self != nullptr && index <= this->slots_) {\n      Erase(ListNode(index, this));\n    }\n  }\n  /*! \\return begin iterator */\n  iterator begin() const {\n    if (slots_ == 0) {\n      return iterator(0, this);\n    }\n    for (uint64_t index = 0; index <= slots_; ++index) {\n      if (!ListNode(index, this).IsEmpty()) {\n        return iterator(index, this);\n      }\n    }\n    return iterator(slots_ + 1, this);\n  }\n  /*! \\return end iterator */\n  iterator end() const { return slots_ == 0 ? iterator(0, this) : iterator(slots_ + 1, this); }\n\n private:\n  /*!\n   * \\brief Search for the given key\n   * \\param key The key\n   * \\return ListNode that associated with the key\n   */\n  ListNode Search(const key_type& key) const {\n    if (this->size_ == 0) {\n      return ListNode();\n    }\n    for (ListNode iter = GetListHead(ObjectHash()(key)); !iter.IsNone(); iter.MoveToNext(this)) {\n      if (ObjectEqual()(key, iter.Key())) {\n        return iter;\n      }\n    }\n    return ListNode();\n  }\n  /*!\n   * \\brief Search for the given key, throw exception if not exists\n   * \\param key The key\n   * \\return ListNode that associated with the key\n   */\n  mapped_type& At(const key_type& key) const {\n    ListNode iter = Search(key);\n    ICHECK(!iter.IsNone()) << \"IndexError: key is not in Map\";\n    return iter.Val();\n  }\n  /*!\n   * \\brief Try to insert a key, or do nothing if already exists\n   * \\param key The indexing key\n   * \\param result The linked-list entry found or just constructed\n   * \\return A boolean, indicating if actual insertion happens\n   */\n  bool TryInsert(const key_type& key, ListNode* result) {\n    if (slots_ == 0) {\n      return false;\n    }\n    // required that `iter` to be the head of a linked list through which we can iterator\n    ListNode iter = IndexFromHash(ObjectHash()(key));\n    // `iter` can be: 1) empty; 2) body of an irrelevant list; 3) head of the relevant list\n    // Case 1: empty\n    if (iter.IsEmpty()) {\n      iter.NewHead(KVType(key, ObjectRef(nullptr)));\n      this->size_ += 1;\n      *result = iter;\n      return true;\n    }\n    // Case 2: body of an irrelevant list\n    if (!iter.IsHead()) {\n      // we move the elements around and construct the single-element linked list\n      return IsFull() ? false : TrySpareListHead(iter, key, result);\n    }\n    // Case 3: head of the relevant list\n    // we iterate through the linked list until the end\n    // make sure `iter` is the previous element of `next`\n    ListNode next = iter;\n    do {\n      // find equal item, do not insert\n      if (ObjectEqual()(key, next.Key())) {\n        *result = next;\n        return true;\n      }\n      // make sure `iter` is the previous element of `next`\n      iter = next;\n    } while (next.MoveToNext(this));\n    // `iter` is the tail of the linked list\n    // always check capacity before insertion\n    if (IsFull()) {\n      return false;\n    }\n    // find the next empty slot\n    uint8_t jump;\n    if (!iter.GetNextEmpty(this, &jump, result)) {\n      return false;\n    }\n    result->NewTail(KVType(key, ObjectRef(nullptr)));\n    // link `iter` to `empty`, and move forward\n    iter.SetJump(jump);\n    this->size_ += 1;\n    return true;\n  }\n  /*!\n   * \\brief Spare an entry to be the head of a linked list.\n   * As described in B3, during insertion, it is possible that the entire linked list does not\n   * exist, but the slot of its head has been occupied by other linked lists. In this case, we need\n   * to spare the slot by moving away the elements to another valid empty one to make insertion\n   * possible.\n   * \\param target The given entry to be spared\n   * \\param key The indexing key\n   * \\param result The linked-list entry constructed as the head\n   * \\return A boolean, if actual insertion happens\n   */\n  bool TrySpareListHead(ListNode target, const key_type& key, ListNode* result) {\n    // `target` is not the head of the linked list\n    // move the original item of `target` (if any)\n    // and construct new item on the position `target`\n    // To make `target` empty, we\n    // 1) find `w` the previous element of `target` in the linked list\n    // 2) copy the linked list starting from `r = target`\n    // 3) paste them after `w`\n    // read from the linked list after `r`\n    ListNode r = target;\n    // write to the tail of `w`\n    ListNode w = target.FindPrev(this);\n    // after `target` is moved, we disallow writing to the slot\n    bool is_first = true;\n    uint8_t r_meta, jump;\n    ListNode empty;\n    do {\n      // `jump` describes how `w` is jumped to `empty`\n      // rehash if there is no empty space after `w`\n      if (!w.GetNextEmpty(this, &jump, &empty)) {\n        return false;\n      }\n      // move `r` to `empty`\n      empty.NewTail(std::move(r.Data()));\n      // clear the metadata of `r`\n      r_meta = r.Meta();\n      if (is_first) {\n        is_first = false;\n        r.SetProtected();\n      } else {\n        r.SetEmpty();\n      }\n      // link `w` to `empty`, and move forward\n      w.SetJump(jump);\n      w = empty;\n      // move `r` forward as well\n    } while (r.MoveToNext(this, r_meta));\n    // finally we have done moving the linked list\n    // fill data_ into `target`\n    target.NewHead(KVType(key, ObjectRef(nullptr)));\n    this->size_ += 1;\n    *result = target;\n    return true;\n  }\n  /*!\n   * \\brief Remove a ListNode\n   * \\param iter The node to be removed\n   */\n  void Erase(const ListNode& iter) {\n    this->size_ -= 1;\n    if (!iter.HasNext()) {\n      // `iter` is the last\n      if (!iter.IsHead()) {\n        // cut the link if there is any\n        iter.FindPrev(this).SetJump(0);\n      }\n      iter.Data().KVType::~KVType();\n      iter.SetEmpty();\n    } else {\n      ListNode last = iter, prev = iter;\n      for (last.MoveToNext(this); last.HasNext(); prev = last, last.MoveToNext(this)) {\n      }\n      iter.Data() = std::move(last.Data());\n      last.SetEmpty();\n      prev.SetJump(0);\n    }\n  }\n  /*! \\brief Clear the container to empty, release all entries and memory acquired */\n  void Reset() {\n    uint64_t n_blocks = CalcNumBlocks(this->slots_);\n    for (uint64_t bi = 0; bi < n_blocks; ++bi) {\n      uint8_t* meta_ptr = data_[bi].bytes;\n      KVType* data_ptr = reinterpret_cast<KVType*>(data_[bi].bytes + kBlockCap);\n      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {\n        uint8_t& meta = *meta_ptr;\n        if (meta != uint8_t(kProtectedSlot) && meta != uint8_t(kEmptySlot)) {\n          meta = uint8_t(kEmptySlot);\n          data_ptr->KVType::~KVType();\n        }\n      }\n    }\n    ReleaseMemory();\n  }\n  /*! \\brief Release the memory acquired by the container without deleting its entries stored inside\n   */\n  void ReleaseMemory() {\n    delete[] data_;\n    data_ = nullptr;\n    slots_ = 0;\n    size_ = 0;\n    fib_shift_ = 63;\n  }\n  /*!\n   * \\brief Create an empty container\n   * \\param fib_shift The fib shift provided\n   * \\param n_slots Number of slots required, should be power-of-two\n   * \\return The object created\n   */\n  static ObjectPtr<DenseMapNode> Empty(uint32_t fib_shift, uint64_t n_slots) {\n    ICHECK_GT(n_slots, uint64_t(SmallMapNode::kMaxSize));\n    ObjectPtr<DenseMapNode> p = make_object<DenseMapNode>();\n    uint64_t n_blocks = CalcNumBlocks(n_slots - 1);\n    Block* block = p->data_ = new Block[n_blocks];\n    p->slots_ = n_slots - 1;\n    p->size_ = 0;\n    p->fib_shift_ = fib_shift;\n    for (uint64_t i = 0; i < n_blocks; ++i, ++block) {\n      std::fill(block->bytes, block->bytes + kBlockCap, uint8_t(kEmptySlot));\n    }\n    return p;\n  }\n  /*!\n   * \\brief Create an empty container with elements copying from another DenseMapNode\n   * \\param from The source container\n   * \\return The object created\n   */\n  static ObjectPtr<DenseMapNode> CopyFrom(DenseMapNode* from) {\n    ObjectPtr<DenseMapNode> p = make_object<DenseMapNode>();\n    uint64_t n_blocks = CalcNumBlocks(from->slots_);\n    p->data_ = new Block[n_blocks];\n    p->slots_ = from->slots_;\n    p->size_ = from->size_;\n    p->fib_shift_ = from->fib_shift_;\n    for (uint64_t bi = 0; bi < n_blocks; ++bi) {\n      uint8_t* meta_ptr_from = from->data_[bi].bytes;\n      KVType* data_ptr_from = reinterpret_cast<KVType*>(from->data_[bi].bytes + kBlockCap);\n      uint8_t* meta_ptr_to = p->data_[bi].bytes;\n      KVType* data_ptr_to = reinterpret_cast<KVType*>(p->data_[bi].bytes + kBlockCap);\n      for (int j = 0; j < kBlockCap;\n           ++j, ++meta_ptr_from, ++data_ptr_from, ++meta_ptr_to, ++data_ptr_to) {\n        uint8_t& meta = *meta_ptr_to = *meta_ptr_from;\n        ICHECK(meta != kProtectedSlot);\n        if (meta != uint8_t(kEmptySlot)) {\n          new (data_ptr_to) KVType(*data_ptr_from);\n        }\n      }\n    }\n    return p;\n  }\n  /*!\n   * \\brief InsertMaybeReHash an entry into the given hash map\n   * \\param kv The entry to be inserted\n   * \\param map The pointer to the map, can be changed if re-hashing happens\n   */\n  static void InsertMaybeReHash(const KVType& kv, ObjectPtr<Object>* map) {\n    DenseMapNode* map_node = static_cast<DenseMapNode*>(map->get());\n    ListNode iter;\n    // Try to insert. If succeed, we simply return\n    if (map_node->TryInsert(kv.first, &iter)) {\n      iter.Val() = kv.second;\n      return;\n    }\n    ICHECK_GT(map_node->slots_, uint64_t(SmallMapNode::kMaxSize));\n    // Otherwise, start rehash\n    ObjectPtr<Object> p = Empty(map_node->fib_shift_ - 1, map_node->slots_ * 2 + 2);\n    // Insert the given `kv` into the new hash map\n    InsertMaybeReHash(kv, &p);\n    uint64_t n_blocks = CalcNumBlocks(map_node->slots_);\n    // Then Insert data from the original block.\n    for (uint64_t bi = 0; bi < n_blocks; ++bi) {\n      uint8_t* meta_ptr = map_node->data_[bi].bytes;\n      KVType* data_ptr = reinterpret_cast<KVType*>(map_node->data_[bi].bytes + kBlockCap);\n      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {\n        uint8_t& meta = *meta_ptr;\n        if (meta != uint8_t(kProtectedSlot) && meta != uint8_t(kEmptySlot)) {\n          meta = uint8_t(kEmptySlot);\n          KVType kv = std::move(*data_ptr);\n          InsertMaybeReHash(kv, &p);\n        }\n      }\n    }\n    map_node->ReleaseMemory();\n    *map = p;\n  }\n  /*!\n   * \\brief Check whether the hash table is full\n   * \\return A boolean indicating whether hash table is full\n   */\n  bool IsFull() const { return size_ + 1 > (slots_ + 1) * kMaxLoadFactor; }\n  /*!\n   * \\brief Increment the pointer\n   * \\param index The pointer to be incremented\n   * \\return The increased pointer\n   */\n  uint64_t IncItr(uint64_t index) const {\n    for (++index; index <= slots_; ++index) {\n      if (!ListNode(index, this).IsEmpty()) {\n        return index;\n      }\n    }\n    return slots_ + 1;\n  }\n  /*!\n   * \\brief Decrement the pointer\n   * \\param index The pointer to be decremented\n   * \\return The decreased pointer\n   */\n  uint64_t DecItr(uint64_t index) const {\n    while (index != 0) {\n      index -= 1;\n      if (!ListNode(index, this).IsEmpty()) {\n        return index;\n      }\n    }\n    return slots_ + 1;\n  }\n  /*!\n   * \\brief De-reference the pointer\n   * \\param index The pointer to be dereferenced\n   * \\return The result\n   */\n  KVType* DeRefItr(uint64_t index) const { return &ListNode(index, this).Data(); }\n  /*! \\brief Construct from hash code */\n  ListNode IndexFromHash(uint64_t hash_value) const {\n    return ListNode(FibHash(hash_value, fib_shift_), this);\n  }\n  /*! \\brief Construct from hash code if the position is head of list */\n  ListNode GetListHead(uint64_t hash_value) const {\n    ListNode node = IndexFromHash(hash_value);\n    return node.IsHead() ? node : ListNode();\n  }\n  /*! \\brief Construct the number of blocks in the hash table */\n  static uint64_t CalcNumBlocks(uint64_t n_slots_m1) {\n    uint64_t n_slots = n_slots_m1 > 0 ? n_slots_m1 + 1 : 0;\n    return (n_slots + kBlockCap - 1) / kBlockCap;\n  }\n  /*!\n   * \\brief Calculate the power-of-2 table size given the lower-bound of required capacity.\n   * \\param cap The lower-bound of the required capacity\n   * \\param fib_shift The result shift for Fibonacci Hashing\n   * \\param n_slots The result number of slots\n   */\n  static void CalcTableSize(uint64_t cap, uint32_t* fib_shift, uint64_t* n_slots) {\n    uint32_t shift = 64;\n    uint64_t slots = 1;\n    for (uint64_t c = cap; c; c >>= 1) {\n      shift -= 1;\n      slots <<= 1;\n    }\n    ICHECK_GT(slots, cap);\n    if (slots < cap * 2) {\n      *fib_shift = shift - 1;\n      *n_slots = slots << 1;\n    } else {\n      *fib_shift = shift;\n      *n_slots = slots;\n    }\n  }\n  /*!\n   * \\brief Fibonacci Hashing, maps a hash code to an index in a power-of-2-sized table.\n   * See also: https://programmingpraxis.com/2018/06/19/fibonacci-hash/.\n   * \\param hash_value The raw hash value\n   * \\param fib_shift The shift in Fibonacci Hashing\n   * \\return An index calculated using Fibonacci Hashing\n   */\n  static uint64_t FibHash(uint64_t hash_value, uint32_t fib_shift) {\n    constexpr uint64_t coeff = 11400714819323198485ull;\n    return (coeff * hash_value) >> fib_shift;\n  }\n  /*! \\brief The implicit in-place linked list used to index a chain */\n  struct ListNode {\n    /*! \\brief Construct None */\n    ListNode() : index(0), block(nullptr) {}\n    /*! \\brief Construct from position */\n    ListNode(uint64_t index, const DenseMapNode* self)\n        : index(index), block(self->data_ + (index / kBlockCap)) {}\n    /*! \\brief Metadata on the entry */\n    uint8_t& Meta() const { return *(block->bytes + index % kBlockCap); }\n    /*! \\brief Data on the entry */\n    KVType& Data() const {\n      return *(reinterpret_cast<KVType*>(block->bytes + kBlockCap +\n                                         (index % kBlockCap) * sizeof(KVType)));\n    }\n    /*! \\brief Key on the entry */\n    key_type& Key() const { return Data().first; }\n    /*! \\brief Value on the entry */\n    mapped_type& Val() const { return Data().second; }\n    /*! \\brief If the entry is head of linked list */\n    bool IsHead() const { return (Meta() & 0b10000000) == 0b00000000; }\n    /*! \\brief If the entry is none */\n    bool IsNone() const { return block == nullptr; }\n    /*! \\brief If the entry is empty slot */\n    bool IsEmpty() const { return Meta() == uint8_t(kEmptySlot); }\n    /*! \\brief If the entry is protected slot */\n    bool IsProtected() const { return Meta() == uint8_t(kProtectedSlot); }\n    /*! \\brief Set the entry to be empty */\n    void SetEmpty() const { Meta() = uint8_t(kEmptySlot); }\n    /*! \\brief Set the entry to be protected */\n    void SetProtected() const { Meta() = uint8_t(kProtectedSlot); }\n    /*! \\brief Set the entry's jump to its next entry */\n    void SetJump(uint8_t jump) const { (Meta() &= 0b10000000) |= jump; }\n    /*! \\brief Construct a head of linked list in-place */\n    void NewHead(KVType v) const {\n      Meta() = 0b00000000;\n      new (&Data()) KVType(std::move(v));\n    }\n    /*! \\brief Construct a tail of linked list in-place */\n    void NewTail(KVType v) const {\n      Meta() = 0b10000000;\n      new (&Data()) KVType(std::move(v));\n    }\n    /*! \\brief If the entry has next entry on the linked list */\n    bool HasNext() const { return NextProbeLocation(Meta() & 0b01111111) != 0; }\n    /*! \\brief Move the entry to the next entry on the linked list */\n    bool MoveToNext(const DenseMapNode* self, uint8_t meta) {\n      uint64_t offset = NextProbeLocation(meta & 0b01111111);\n      if (offset == 0) {\n        index = 0;\n        block = nullptr;\n        return false;\n      }\n      index = (index + offset) & (self->slots_);\n      block = self->data_ + (index / kBlockCap);\n      return true;\n    }\n    /*! \\brief Move the entry to the next entry on the linked list */\n    bool MoveToNext(const DenseMapNode* self) { return MoveToNext(self, Meta()); }\n    /*! \\brief Get the previous entry on the linked list */\n    ListNode FindPrev(const DenseMapNode* self) const {\n      // start from the head of the linked list, which must exist\n      ListNode next = self->IndexFromHash(ObjectHash()(Key()));\n      // `prev` is always the previous item of `next`\n      ListNode prev = next;\n      for (next.MoveToNext(self); index != next.index; prev = next, next.MoveToNext(self)) {\n      }\n      return prev;\n    }\n    /*! \\brief Get the next empty jump */\n    bool GetNextEmpty(const DenseMapNode* self, uint8_t* jump, ListNode* result) const {\n      for (uint8_t idx = 1; idx < kNumJumpDists; ++idx) {\n        ListNode candidate((index + NextProbeLocation(idx)) & (self->slots_), self);\n        if (candidate.IsEmpty()) {\n          *jump = idx;\n          *result = candidate;\n          return true;\n        }\n      }\n      return false;\n    }\n    /*! \\brief Index on the real array */\n    uint64_t index;\n    /*! \\brief Pointer to the actual block */\n    Block* block;\n  };\n\n protected:\n  /*! \\brief fib shift in Fibonacci Hashing */\n  uint32_t fib_shift_;\n  /*! \\brief array of data blocks */\n  Block* data_;\n  static uint64_t NextProbeLocation(size_t index) {\n    /* clang-format off */\n    /*! \\brief Candidates of probing distance */\n    static const uint64_t kNextProbeLocation[kNumJumpDists] {\n      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n      // Quadratic probing with triangle numbers. See also:\n      // 1) https://en.wikipedia.org/wiki/Quadratic_probing\n      // 2) https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/\n      // 3) https://github.com/skarupke/flat_hash_map\n      21, 28, 36, 45, 55, 66, 78, 91, 105, 120,\n      136, 153, 171, 190, 210, 231, 253, 276, 300, 325,\n      351, 378, 406, 435, 465, 496, 528, 561, 595, 630,\n      666, 703, 741, 780, 820, 861, 903, 946, 990, 1035,\n      1081, 1128, 1176, 1225, 1275, 1326, 1378, 1431, 1485, 1540,\n      1596, 1653, 1711, 1770, 1830, 1891, 1953, 2016, 2080, 2145,\n      2211, 2278, 2346, 2415, 2485, 2556, 2628,\n      // larger triangle numbers\n      8515, 19110, 42778, 96141, 216153,\n      486591, 1092981, 2458653, 5532801, 12442566,\n      27993903, 62983476, 141717030, 318844378, 717352503,\n      1614057336, 3631522476, 8170957530, 18384510628, 41364789378,\n      93070452520, 209408356380, 471168559170, 1060128894105, 2385289465695,\n      5366898840628, 12075518705635, 27169915244790, 61132312065111, 137547689707000,\n      309482283181501, 696335127828753, 1566753995631385, 3525196511162271, 7931691992677701,\n      17846306936293605, 40154190677507445, 90346928918121501, 203280589587557251,\n      457381325854679626, 1029107982097042876, 2315492959180353330, 5209859154120846435,\n    };\n    /* clang-format on */\n    return kNextProbeLocation[index];\n  }\n  friend class MapNode;\n};\n\n#define TVM_DISPATCH_MAP(base, var, body)     \\\n  {                                           \\\n    using TSmall = SmallMapNode*;             \\\n    using TDense = DenseMapNode*;             \\\n    uint64_t slots = base->slots_;            \\\n    if (slots <= SmallMapNode::kMaxSize) {    \\\n      TSmall var = static_cast<TSmall>(base); \\\n      body;                                   \\\n    } else {                                  \\\n      TDense var = static_cast<TDense>(base); \\\n      body;                                   \\\n    }                                         \\\n  }\n\n#define TVM_DISPATCH_MAP_CONST(base, var, body) \\\n  {                                             \\\n    using TSmall = const SmallMapNode*;         \\\n    using TDense = const DenseMapNode*;         \\\n    uint64_t slots = base->slots_;              \\\n    if (slots <= SmallMapNode::kMaxSize) {      \\\n      TSmall var = static_cast<TSmall>(base);   \\\n      body;                                     \\\n    } else {                                    \\\n      TDense var = static_cast<TDense>(base);   \\\n      body;                                     \\\n    }                                           \\\n  }\n\ninline MapNode::iterator::pointer MapNode::iterator::operator->() const {\n  TVM_MAP_FAIL_IF_CHANGED()\n  TVM_DISPATCH_MAP_CONST(self, p, { return p->DeRefItr(index); });\n}\n\ninline MapNode::iterator& MapNode::iterator::operator++() {\n  TVM_MAP_FAIL_IF_CHANGED()\n  TVM_DISPATCH_MAP_CONST(self, p, {\n    index = p->IncItr(index);\n    return *this;\n  });\n}\n\ninline MapNode::iterator& MapNode::iterator::operator--() {\n  TVM_MAP_FAIL_IF_CHANGED()\n  TVM_DISPATCH_MAP_CONST(self, p, {\n    index = p->DecItr(index);\n    return *this;\n  });\n}\n\ninline size_t MapNode::count(const key_type& key) const {\n  TVM_DISPATCH_MAP_CONST(this, p, { return p->count(key); });\n}\n\ninline const MapNode::mapped_type& MapNode::at(const MapNode::key_type& key) const {\n  TVM_DISPATCH_MAP_CONST(this, p, { return p->at(key); });\n}\n\ninline MapNode::mapped_type& MapNode::at(const MapNode::key_type& key) {\n  TVM_DISPATCH_MAP(this, p, { return p->at(key); });\n}\n\ninline MapNode::iterator MapNode::begin() const {\n  TVM_DISPATCH_MAP_CONST(this, p, { return p->begin(); });\n}\n\ninline MapNode::iterator MapNode::end() const {\n  TVM_DISPATCH_MAP_CONST(this, p, { return p->end(); });\n}\n\ninline MapNode::iterator MapNode::find(const MapNode::key_type& key) const {\n  TVM_DISPATCH_MAP_CONST(this, p, { return p->find(key); });\n}\n\ninline void MapNode::erase(const MapNode::iterator& position) {\n  TVM_DISPATCH_MAP(this, p, { return p->erase(position); });\n}\n\n#undef TVM_DISPATCH_MAP\n#undef TVM_DISPATCH_MAP_CONST\n\ninline ObjectPtr<MapNode> MapNode::Empty() { return SmallMapNode::Empty(); }\n\ninline ObjectPtr<MapNode> MapNode::CopyFrom(MapNode* from) {\n  if (from->slots_ <= SmallMapNode::kMaxSize) {\n    return SmallMapNode::CopyFrom(static_cast<SmallMapNode*>(from));\n  } else {\n    return DenseMapNode::CopyFrom(static_cast<DenseMapNode*>(from));\n  }\n}\n\ntemplate <typename IterType>\ninline ObjectPtr<Object> MapNode::CreateFromRange(IterType first, IterType last) {\n  int64_t _cap = std::distance(first, last);\n  if (_cap < 0) {\n    return SmallMapNode::Empty();\n  }\n  uint64_t cap = static_cast<uint64_t>(_cap);\n  if (cap < SmallMapNode::kMaxSize) {\n    return SmallMapNode::CreateFromRange(cap, first, last);\n  }\n  uint32_t fib_shift;\n  uint64_t n_slots;\n  DenseMapNode::CalcTableSize(cap, &fib_shift, &n_slots);\n  ObjectPtr<Object> obj = DenseMapNode::Empty(fib_shift, n_slots);\n  for (; first != last; ++first) {\n    KVType kv(*first);\n    DenseMapNode::InsertMaybeReHash(kv, &obj);\n  }\n  return obj;\n}\n\ninline void MapNode::InsertMaybeReHash(const KVType& kv, ObjectPtr<Object>* map) {\n  constexpr uint64_t kSmallMapMaxSize = SmallMapNode::kMaxSize;\n  MapNode* base = static_cast<MapNode*>(map->get());\n#if TVM_LOG_DEBUG\n  base->state_marker++;\n#endif  // TVM_LOG_DEBUG\n  if (base->slots_ < kSmallMapMaxSize) {\n    SmallMapNode::InsertMaybeReHash(kv, map);\n  } else if (base->slots_ == kSmallMapMaxSize) {\n    if (base->size_ < base->slots_) {\n      SmallMapNode::InsertMaybeReHash(kv, map);\n    } else {\n      ObjectPtr<Object> new_map = MapNode::CreateFromRange(base->begin(), base->end());\n      DenseMapNode::InsertMaybeReHash(kv, &new_map);\n      *map = std::move(new_map);\n    }\n  } else {\n    DenseMapNode::InsertMaybeReHash(kv, map);\n  }\n}\n\ntemplate <>\ninline ObjectPtr<MapNode> make_object<>() = delete;\n\n#endif\n\n/*!\n * \\brief Map container of NodeRef->NodeRef in DSL graph.\n *  Map implements copy on write semantics, which means map is mutable\n *  but copy will happen when array is referenced in more than two places.\n *\n * operator[] only provide const acces, use Set to mutate the content.\n * \\tparam K The key NodeRef type.\n * \\tparam V The value NodeRef type.\n */\ntemplate <typename K, typename V,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, K>::value>::type,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, V>::value>::type>\nclass Map : public ObjectRef {\n public:\n  using key_type = K;\n  using mapped_type = V;\n  class iterator;\n  /*!\n   * \\brief default constructor\n   */\n  Map() { data_ = MapNode::Empty(); }\n  /*!\n   * \\brief move constructor\n   * \\param other source\n   */\n  Map(Map<K, V>&& other) { data_ = std::move(other.data_); }\n  /*!\n   * \\brief copy constructor\n   * \\param other source\n   */\n  Map(const Map<K, V>& other) : ObjectRef(other.data_) {}\n  /*!\n   * \\brief copy assign operator\n   * \\param other The source of assignment\n   * \\return reference to self.\n   */\n  Map<K, V>& operator=(Map<K, V>&& other) {\n    data_ = std::move(other.data_);\n    return *this;\n  }\n  /*!\n   * \\brief move assign operator\n   * \\param other The source of assignment\n   * \\return reference to self.\n   */\n  Map<K, V>& operator=(const Map<K, V>& other) {\n    data_ = other.data_;\n    return *this;\n  }\n  /*!\n   * \\brief constructor from pointer\n   * \\param n the container pointer\n   */\n  explicit Map(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief constructor from iterator\n   * \\param begin begin of iterator\n   * \\param end end of iterator\n   * \\tparam IterType The type of iterator\n   */\n  template <typename IterType>\n  Map(IterType begin, IterType end) {\n    data_ = MapNode::CreateFromRange(begin, end);\n  }\n  /*!\n   * \\brief constructor from initializer list\n   * \\param init The initalizer list\n   */\n  Map(std::initializer_list<std::pair<K, V>> init) {\n    data_ = MapNode::CreateFromRange(init.begin(), init.end());\n  }\n  /*!\n   * \\brief constructor from unordered_map\n   * \\param init The unordered_map\n   */\n  template <typename Hash, typename Equal>\n  Map(const std::unordered_map<K, V, Hash, Equal>& init) {  // NOLINT(*)\n    data_ = MapNode::CreateFromRange(init.begin(), init.end());\n  }\n  /*!\n   * \\brief Read element from map.\n   * \\param key The key\n   * \\return the corresonding element.\n   */\n  const V at(const K& key) const { return DowncastNoCheck<V>(GetMapNode()->at(key)); }\n  /*!\n   * \\brief Read element from map.\n   * \\param key The key\n   * \\return the corresonding element.\n   */\n  const V operator[](const K& key) const { return this->at(key); }\n  /*! \\return The size of the array */\n  size_t size() const {\n    MapNode* n = GetMapNode();\n    return n == nullptr ? 0 : n->size();\n  }\n  /*! \\return The number of elements of the key */\n  size_t count(const K& key) const {\n    MapNode* n = GetMapNode();\n    return n == nullptr ? 0 : GetMapNode()->count(key);\n  }\n  /*! \\return whether array is empty */\n  bool empty() const { return size() == 0; }\n  /*! \\brief Release reference to all the elements */\n  void clear() {\n    MapNode* n = GetMapNode();\n    if (n != nullptr) {\n      data_ = MapNode::Empty();\n    }\n  }\n  /*!\n   * \\brief set the Map.\n   * \\param key The index key.\n   * \\param value The value to be setted.\n   */\n  void Set(const K& key, const V& value) {\n    CopyOnWrite();\n    MapNode::InsertMaybeReHash(MapNode::KVType(key, value), &data_);\n  }\n  /*! \\return begin iterator */\n  iterator begin() const { return iterator(GetMapNode()->begin()); }\n  /*! \\return end iterator */\n  iterator end() const { return iterator(GetMapNode()->end()); }\n  /*! \\return find the key and returns the associated iterator */\n  iterator find(const K& key) const { return iterator(GetMapNode()->find(key)); }\n  /*! \\return The value associated with the key, NullOpt if not found */\n  Optional<V> Get(const K& key) const {\n    MapNode::iterator iter = GetMapNode()->find(key);\n    if (iter == GetMapNode()->end()) {\n      return NullOptType{};\n    }\n    return DowncastNoCheck<V>(iter->second);\n  }\n  void erase(const K& key) { CopyOnWrite()->erase(key); }\n\n  /*!\n   * \\brief copy on write semantics\n   *  Do nothing if current handle is the unique copy of the array.\n   *  Otherwise make a new copy of the array to ensure the current handle\n   *  hold a unique copy.\n   *\n   * \\return Handle to the internal node container(which guarantees to be unique)\n   */\n  MapNode* CopyOnWrite() {\n    if (data_.get() == nullptr) {\n      data_ = MapNode::Empty();\n    } else if (!data_.unique()) {\n      data_ = MapNode::CopyFrom(GetMapNode());\n    }\n    return GetMapNode();\n  }\n  /*! \\brief specify container node */\n  using ContainerType = MapNode;\n\n  /*! \\brief Iterator of the hash map */\n  class iterator {\n   public:\n    using iterator_category = std::bidirectional_iterator_tag;\n    using difference_type = int64_t;\n    using value_type = const std::pair<K, V>;\n    using pointer = value_type*;\n    using reference = value_type;\n\n    iterator() : itr() {}\n\n    /*! \\brief Compare iterators */\n    bool operator==(const iterator& other) const { return itr == other.itr; }\n    /*! \\brief Compare iterators */\n    bool operator!=(const iterator& other) const { return itr != other.itr; }\n    /*! \\brief De-reference iterators is not allowed */\n    pointer operator->() const = delete;\n    /*! \\brief De-reference iterators */\n    reference operator*() const {\n      auto& kv = *itr;\n      return std::make_pair(DowncastNoCheck<K>(kv.first), DowncastNoCheck<V>(kv.second));\n    }\n    /*! \\brief Prefix self increment, e.g. ++iter */\n    iterator& operator++() {\n      ++itr;\n      return *this;\n    }\n    /*! \\brief Suffix self increment */\n    iterator operator++(int) {\n      iterator copy = *this;\n      ++(*this);\n      return copy;\n    }\n\n   private:\n    iterator(const MapNode::iterator& itr)  // NOLINT(*)\n        : itr(itr) {}\n\n    template <typename, typename, typename, typename>\n    friend class Map;\n\n    MapNode::iterator itr;\n  };\n\n private:\n  /*! \\brief Return data_ as type of pointer of MapNode */\n  MapNode* GetMapNode() const { return static_cast<MapNode*>(data_.get()); }\n};\n\n/*!\n * \\brief Merge two Maps.\n * \\param lhs the first Map to merge.\n * \\param rhs the second Map to merge.\n * @return The merged Array. Original Maps are kept unchanged.\n */\ntemplate <typename K, typename V,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, K>::value>::type,\n          typename = typename std::enable_if<std::is_base_of<ObjectRef, V>::value>::type>\ninline Map<K, V> Merge(Map<K, V> lhs, const Map<K, V>& rhs) {\n  for (const auto& p : rhs) {\n    lhs.Set(p.first, p.second);\n  }\n  return std::move(lhs);\n}\n\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::Map;\nusing runtime::MapNode;\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/optional.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/optional.h\n * \\brief Runtime Optional container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_OPTIONAL_H_\n#define TVM_RUNTIME_CONTAINER_OPTIONAL_H_\n\n#include <utility>\n\n#include \"./base.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Helper to represent nullptr for optional. */\nstruct NullOptType {};\n\n/*!\n * \\brief Optional container that to represent to a Nullable variant of T.\n * \\tparam T The original ObjectRef.\n *\n * \\code\n *\n *  Optional<String> opt0 = nullptr;\n *  Optional<String> opt1 = String(\"xyz\");\n *  ICHECK(opt0 == nullptr);\n *  ICHECK(opt1 == \"xyz\");\n *\n * \\endcode\n */\ntemplate <typename T>\nclass Optional : public ObjectRef {\n public:\n  using ContainerType = typename T::ContainerType;\n  static_assert(std::is_base_of<ObjectRef, T>::value, \"Optional is only defined for ObjectRef.\");\n  // default constructors.\n  Optional() = default;\n  Optional(const Optional<T>&) = default;\n  Optional(Optional<T>&&) = default;\n  Optional<T>& operator=(const Optional<T>&) = default;\n  Optional<T>& operator=(Optional<T>&&) = default;\n  /*!\n   * \\brief Construct from an ObjectPtr\n   *        whose type already matches the ContainerType.\n   * \\param ptr\n   */\n  explicit Optional(ObjectPtr<Object> ptr) : ObjectRef(ptr) {}\n  /*! \\brief Nullopt handling */\n  Optional(NullOptType) {}  // NOLINT(*)\n  // nullptr handling.\n  // disallow implicit conversion as 0 can be implicitly converted to nullptr_t\n  explicit Optional(std::nullptr_t) {}\n  Optional<T>& operator=(std::nullptr_t) {\n    data_ = nullptr;\n    return *this;\n  }\n  // normal value handling.\n  Optional(T other)  // NOLINT(*)\n      : ObjectRef(std::move(other)) {}\n  Optional<T>& operator=(T other) {\n    ObjectRef::operator=(std::move(other));\n    return *this;\n  }\n  // delete the int constructor\n  // since Optional<Integer>(0) is ambiguious\n  // 0 can be implicitly casted to nullptr_t\n  explicit Optional(int val) = delete;\n  Optional<T>& operator=(int val) = delete;\n  /*!\n   * \\return A not-null container value in the optional.\n   * \\note This function performs not-null checking.\n   */\n  T value() const {\n    ICHECK(data_ != nullptr);\n    return T(data_);\n  }\n  /*!\n   * \\return The internal object pointer with container type of T.\n   * \\note This function do not perform not-null checking.\n   */\n  const ContainerType* get() const { return static_cast<ContainerType*>(data_.get()); }\n  /*!\n   * \\return The contained value if the Optional is not null\n   *         otherwise return the default_value.\n   */\n  T value_or(T default_value) const { return data_ != nullptr ? T(data_) : default_value; }\n\n  /*! \\return Whether the container is not nullptr.*/\n  explicit operator bool() const { return *this != nullptr; }\n  // operator overloadings\n  bool operator==(std::nullptr_t) const { return data_ == nullptr; }\n  bool operator!=(std::nullptr_t) const { return data_ != nullptr; }\n  auto operator==(const Optional<T>& other) const {\n    // support case where sub-class returns a symbolic ref type.\n    using RetType = decltype(value() == other.value());\n    if (same_as(other)) return RetType(true);\n    if (*this != nullptr && other != nullptr) {\n      return value() == other.value();\n    } else {\n      // one of them is nullptr.\n      return RetType(false);\n    }\n  }\n  auto operator!=(const Optional<T>& other) const {\n    // support case where sub-class returns a symbolic ref type.\n    using RetType = decltype(value() != other.value());\n    if (same_as(other)) return RetType(false);\n    if (*this != nullptr && other != nullptr) {\n      return value() != other.value();\n    } else {\n      // one of them is nullptr.\n      return RetType(true);\n    }\n  }\n  auto operator==(const T& other) const {\n    using RetType = decltype(value() == other);\n    if (same_as(other)) return RetType(true);\n    if (*this != nullptr) return value() == other;\n    return RetType(false);\n  }\n  auto operator!=(const T& other) const { return !(*this == other); }\n  template <typename U>\n  auto operator==(const U& other) const {\n    using RetType = decltype(value() == other);\n    if (*this == nullptr) return RetType(false);\n    return value() == other;\n  }\n  template <typename U>\n  auto operator!=(const U& other) const {\n    using RetType = decltype(value() != other);\n    if (*this == nullptr) return RetType(true);\n    return value() != other;\n  }\n  static constexpr bool _type_is_nullable = true;\n};\n\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::Optional;\nconstexpr runtime::NullOptType NullOpt{};\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_OPTIONAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/shape_tuple.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/shape_tuple.h\n * \\brief Runtime ShapeTuple container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_SHAPE_TUPLE_H_\n#define TVM_RUNTIME_CONTAINER_SHAPE_TUPLE_H_\n\n#include <utility>\n#include <vector>\n\n#include \"./base.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief An object representing a shape tuple. */\nclass ShapeTupleObj : public Object {\n public:\n  /*! \\brief The type of shape index element. */\n  using index_type = int64_t;\n  /*! \\brief The pointer to shape tuple data. */\n  index_type* data;\n  /*! \\brief The size of the shape tuple object. */\n  uint64_t size;\n\n  static constexpr const uint32_t _type_index = runtime::TypeIndex::kRuntimeShapeTuple;\n  static constexpr const char* _type_key = \"runtime.ShapeTuple\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ShapeTupleObj, Object);\n\n private:\n  /*! \\brief ShapeTuple object which is moved from std::vector container. */\n  class FromStd;\n\n  friend class ShapeTuple;\n};\n\n/*! \\brief An object representing shape tuple moved from std::vector. */\nclass ShapeTupleObj::FromStd : public ShapeTupleObj {\n public:\n  /*! \\brief The type of shape index element. */\n  using index_type = ShapeTupleObj::index_type;\n  /*!\n   * \\brief Construct a new FromStd object\n   *\n   * \\param other The moved/copied std::vector object\n   *\n   * \\note If user passes const reference, it will trigger copy. If it's rvalue,\n   * it will be moved into other.\n   */\n  explicit FromStd(std::vector<index_type> other) : data_container{other} {}\n\n private:\n  /*! \\brief Container that holds the memory. */\n  std::vector<index_type> data_container;\n\n  friend class ShapeTuple;\n};\n\n/*!\n * \\brief Reference to shape tuple objects.\n */\nclass ShapeTuple : public ObjectRef {\n public:\n  /*! \\brief The type of shape index element. */\n  using index_type = ShapeTupleObj::index_type;\n\n  /*!\n   * \\brief Construct an empty shape tuple.\n   */\n  ShapeTuple() : ShapeTuple(std::vector<index_type>()) {}\n\n  /*!\n   * \\brief Constructor from iterator\n   * \\param begin begin of iterator\n   * \\param end end of iterator\n   * \\tparam IterType The type of iterator\n   */\n  template <typename IterType>\n  ShapeTuple(IterType begin, IterType end) : ShapeTuple(std::vector<index_type>(begin, end)) {}\n\n  /*!\n   * \\brief constructor from initializer list\n   * \\param shape The initializer list\n   */\n  ShapeTuple(std::initializer_list<index_type> shape) : ShapeTuple(shape.begin(), shape.end()) {}\n\n  /*!\n   * \\brief Construct a new ShapeTuple object\n   *\n   * \\param shape The moved/copied std::vector object\n   *\n   * \\note If user passes const reference, it will trigger copy. If it's rvalue,\n   * it will be moved into other.\n   */\n  ShapeTuple(std::vector<index_type> shape);  // NOLINT(*)\n\n  /*!\n   * \\brief Return the data pointer\n   *\n   * \\return const index_type* data pointer\n   */\n  const index_type* data() const { return get()->data; }\n\n  /*!\n   * \\brief Return the size of the shape tuple\n   *\n   * \\return size_t shape tuple size\n   */\n  size_t size() const { return get()->size; }\n\n  /*!\n   * \\brief Immutably read i-th element from the shape tuple.\n   * \\param idx The index\n   * \\return the i-th element.\n   */\n  index_type operator[](size_t idx) const {\n    ICHECK(idx < this->size()) << \"IndexError: indexing \" << idx << \" on an array of size \"\n                               << this->size();\n    return this->data()[idx];\n  }\n\n  /*!\n   * \\brief Immutably read i-th element from the shape tuple.\n   * \\param idx The index\n   * \\return the i-th element.\n   */\n  index_type at(size_t idx) const { return this->operator[](idx); }\n\n  /*! \\return Whether shape tuple is empty */\n  bool empty() const { return size() == 0; }\n\n  /*! \\return The first element of the shape tuple */\n  index_type front() const { return this->at(0); }\n\n  /*! \\return The last element of the shape tuple */\n  index_type back() const { return this->at(this->size() - 1); }\n\n  /*! \\return begin iterator */\n  const index_type* begin() const { return get()->data; }\n\n  /*! \\return end iterator */\n  const index_type* end() const { return (get()->data + size()); }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ShapeTuple, ObjectRef, ShapeTupleObj);\n};\n\ninline ShapeTuple::ShapeTuple(std::vector<index_type> shape) {\n  auto ptr = make_object<ShapeTupleObj::FromStd>(std::move(shape));\n  ptr->size = ptr->data_container.size();\n  ptr->data = ptr->data_container.data();\n  data_ = std::move(ptr);\n}\n\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::ShapeTuple;\nusing runtime::ShapeTupleObj;\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTAINER_SHAPE_TUPLE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/container/string.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/container/string.h\n * \\brief Runtime String container types.\n */\n#ifndef TVM_RUNTIME_CONTAINER_STRING_H_\n#define TVM_RUNTIME_CONTAINER_STRING_H_\n\n#include <dmlc/logging.h>\n#include <tvm/runtime/container/base.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/memory.h>\n#include <tvm/runtime/object.h>\n\n#include <algorithm>\n#include <cstddef>\n#include <cstring>\n#include <initializer_list>\n#include <memory>\n#include <string>\n#include <string_view>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n// Forward declare TVMArgValue\nclass TVMArgValue;\n\n/*! \\brief An object representing string. It's POD type. */\nclass StringObj : public Object {\n public:\n  /*! \\brief The pointer to string data. */\n  const char* data;\n\n  /*! \\brief The length of the string object. */\n  uint64_t size;\n\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeString;\n  static constexpr const char* _type_key = \"runtime.String\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StringObj, Object);\n\n private:\n  /*! \\brief String object which is moved from std::string container. */\n  class FromStd;\n\n  friend class String;\n};\n\n/*!\n * \\brief Reference to string objects.\n *\n * \\code\n *\n * // Example to create runtime String reference object from std::string\n * std::string s = \"hello world\";\n *\n * // You can create the reference from existing std::string\n * String ref{std::move(s)};\n *\n * // You can rebind the reference to another string.\n * ref = std::string{\"hello world2\"};\n *\n * // You can use the reference as hash map key\n * std::unordered_map<String, int32_t> m;\n * m[ref] = 1;\n *\n * // You can compare the reference object with other string objects\n * assert(ref == \"hello world\", true);\n *\n * // You can convert the reference to std::string again\n * string s2 = (string)ref;\n *\n * \\endcode\n */\nclass String : public ObjectRef {\n public:\n  /*!\n   * \\brief Construct an empty string.\n   */\n  String() : String(std::string()) {}\n  /*!\n   * \\brief Construct a new String object\n   *\n   * \\param other The moved/copied std::string object\n   *\n   * \\note If user passes const reference, it will trigger copy. If it's rvalue,\n   * it will be moved into other.\n   */\n  String(std::string other);  // NOLINT(*)\n\n  /*!\n   * \\brief Construct a new String object\n   *\n   * \\param other a char array.\n   */\n  String(const char* other)  // NOLINT(*)\n      : String(std::string(other)) {}\n\n  /*!\n   * \\brief Construct a new null object\n   */\n  String(std::nullptr_t)  // NOLINT(*)\n      : ObjectRef(nullptr) {}\n\n  /*!\n   * \\brief Change the value the reference object points to.\n   *\n   * \\param other The value for the new String\n   *\n   */\n  inline String& operator=(std::string other);\n\n  /*!\n   * \\brief Change the value the reference object points to.\n   *\n   * \\param other The value for the new String\n   */\n  inline String& operator=(const char* other);\n\n  /*!\n   * \\brief Compares this String object to other\n   *\n   * \\param other The String to compare with.\n   *\n   * \\return zero if both char sequences compare equal. negative if this appear\n   * before other, positive otherwise.\n   */\n  int compare(const String& other) const {\n    return memncmp(data(), other.data(), size(), other.size());\n  }\n\n  /*!\n   * \\brief Compares this String object to other\n   *\n   * \\param other The string to compare with.\n   *\n   * \\return zero if both char sequences compare equal. negative if this appear\n   * before other, positive otherwise.\n   */\n  int compare(const std::string& other) const {\n    return memncmp(data(), other.data(), size(), other.size());\n  }\n\n  /*!\n   * \\brief Compares this to other\n   *\n   * \\param other The character array to compare with.\n   *\n   * \\return zero if both char sequences compare equal. negative if this appear\n   * before other, positive otherwise.\n   */\n  int compare(const char* other) const {\n    return memncmp(data(), other, size(), std::strlen(other));\n  }\n\n  /*!\n   * \\brief Returns a pointer to the char array in the string.\n   *\n   * \\return const char*\n   */\n  const char* c_str() const { return get()->data; }\n\n  /*!\n   * \\brief Return the length of the string\n   *\n   * \\return size_t string length\n   */\n  size_t size() const {\n    const auto* ptr = get();\n    return ptr->size;\n  }\n\n  /*!\n   * \\brief Return the length of the string\n   *\n   * \\return size_t string length\n   */\n  size_t length() const { return size(); }\n\n  /*!\n   * \\brief Retun if the string is empty\n   *\n   * \\return true if empty, false otherwise.\n   */\n  bool empty() const { return size() == 0; }\n\n  /*!\n   * \\brief Read an element.\n   * \\param pos The position at which to read the character.\n   *\n   * \\return The char at position\n   */\n  char at(size_t pos) const {\n    if (pos < size()) {\n      return data()[pos];\n    } else {\n      throw std::out_of_range(\"tvm::String index out of bounds\");\n    }\n  }\n\n  /*!\n   * \\brief Return the data pointer\n   *\n   * \\return const char* data pointer\n   */\n  const char* data() const { return get()->data; }\n\n  /*!\n   * \\brief Convert String to an std::string object\n   *\n   * \\return std::string\n   */\n  operator std::string() const { return std::string{get()->data, size()}; }\n\n  /*!\n   * \\brief Check if a TVMArgValue can be converted to String, i.e. it can be std::string or String\n   * \\param val The value to be checked\n   * \\return A boolean indicating if val can be converted to String\n   */\n  inline static bool CanConvertFrom(const TVMArgValue& val);\n\n  /*!\n   * \\brief Hash the binary bytes\n   * \\param data The data pointer\n   * \\param size The size of the bytes.\n   * \\return the hash value.\n   */\n  static size_t HashBytes(const char* data, size_t size) {\n    // This function falls back to string copy with c++11 compiler and is\n    // recommended to be compiled with c++14\n    return std::hash<std::string_view>()(std::string_view(data, size));\n  }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(String, ObjectRef, StringObj);\n\n private:\n  /*!\n   * \\brief Compare two char sequence\n   *\n   * \\param lhs Pointers to the char array to compare\n   * \\param rhs Pointers to the char array to compare\n   * \\param lhs_count Length of the char array to compare\n   * \\param rhs_count Length of the char array to compare\n   * \\return int zero if both char sequences compare equal. negative if this\n   * appear before other, positive otherwise.\n   */\n  static int memncmp(const char* lhs, const char* rhs, size_t lhs_count, size_t rhs_count);\n\n  /*!\n   * \\brief Concatenate two char sequences\n   *\n   * \\param lhs Pointers to the lhs char array\n   * \\param lhs_size The size of the lhs char array\n   * \\param rhs Pointers to the rhs char array\n   * \\param rhs_size The size of the rhs char array\n   *\n   * \\return The concatenated char sequence\n   */\n  static String Concat(const char* lhs, size_t lhs_size, const char* rhs, size_t rhs_size) {\n    std::string ret(lhs, lhs_size);\n    ret.append(rhs, rhs_size);\n    return String(ret);\n  }\n\n  // Overload + operator\n  friend String operator+(const String& lhs, const String& rhs);\n  friend String operator+(const String& lhs, const std::string& rhs);\n  friend String operator+(const std::string& lhs, const String& rhs);\n  friend String operator+(const String& lhs, const char* rhs);\n  friend String operator+(const char* lhs, const String& rhs);\n\n  friend struct tvm::runtime::ObjectEqual;\n};\n\n/*! \\brief An object representing string moved from std::string. */\nclass StringObj::FromStd : public StringObj {\n public:\n  /*!\n   * \\brief Construct a new FromStd object\n   *\n   * \\param other The moved/copied std::string object\n   *\n   * \\note If user passes const reference, it will trigger copy. If it's rvalue,\n   * it will be moved into other.\n   */\n  explicit FromStd(std::string other) : data_container{other} {}\n\n private:\n  /*! \\brief Container that holds the memory. */\n  std::string data_container;\n\n  friend class String;\n};\n\ninline String::String(std::string other) {\n  auto ptr = make_object<StringObj::FromStd>(std::move(other));\n  ptr->size = ptr->data_container.size();\n  ptr->data = ptr->data_container.data();\n  data_ = std::move(ptr);\n}\n\ninline String& String::operator=(std::string other) {\n  String replace{std::move(other)};\n  data_.swap(replace.data_);\n  return *this;\n}\n\ninline String& String::operator=(const char* other) { return operator=(std::string(other)); }\n\ninline String operator+(const String& lhs, const String& rhs) {\n  size_t lhs_size = lhs.size();\n  size_t rhs_size = rhs.size();\n  return String::Concat(lhs.data(), lhs_size, rhs.data(), rhs_size);\n}\n\ninline String operator+(const String& lhs, const std::string& rhs) {\n  size_t lhs_size = lhs.size();\n  size_t rhs_size = rhs.size();\n  return String::Concat(lhs.data(), lhs_size, rhs.data(), rhs_size);\n}\n\ninline String operator+(const std::string& lhs, const String& rhs) {\n  size_t lhs_size = lhs.size();\n  size_t rhs_size = rhs.size();\n  return String::Concat(lhs.data(), lhs_size, rhs.data(), rhs_size);\n}\n\ninline String operator+(const char* lhs, const String& rhs) {\n  size_t lhs_size = std::strlen(lhs);\n  size_t rhs_size = rhs.size();\n  return String::Concat(lhs, lhs_size, rhs.data(), rhs_size);\n}\n\ninline String operator+(const String& lhs, const char* rhs) {\n  size_t lhs_size = lhs.size();\n  size_t rhs_size = std::strlen(rhs);\n  return String::Concat(lhs.data(), lhs_size, rhs, rhs_size);\n}\n\n// Overload < operator\ninline bool operator<(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) < 0; }\n\ninline bool operator<(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) > 0; }\n\ninline bool operator<(const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; }\n\ninline bool operator<(const String& lhs, const char* rhs) { return lhs.compare(rhs) < 0; }\n\ninline bool operator<(const char* lhs, const String& rhs) { return rhs.compare(lhs) > 0; }\n\n// Overload > operator\ninline bool operator>(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) > 0; }\n\ninline bool operator>(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) < 0; }\n\ninline bool operator>(const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; }\n\ninline bool operator>(const String& lhs, const char* rhs) { return lhs.compare(rhs) > 0; }\n\ninline bool operator>(const char* lhs, const String& rhs) { return rhs.compare(lhs) < 0; }\n\n// Overload <= operator\ninline bool operator<=(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) <= 0; }\n\ninline bool operator<=(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) >= 0; }\n\ninline bool operator<=(const String& lhs, const String& rhs) { return lhs.compare(rhs) <= 0; }\n\ninline bool operator<=(const String& lhs, const char* rhs) { return lhs.compare(rhs) <= 0; }\n\ninline bool operator<=(const char* lhs, const String& rhs) { return rhs.compare(lhs) >= 0; }\n\n// Overload >= operator\ninline bool operator>=(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) >= 0; }\n\ninline bool operator>=(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) <= 0; }\n\ninline bool operator>=(const String& lhs, const String& rhs) { return lhs.compare(rhs) >= 0; }\n\ninline bool operator>=(const String& lhs, const char* rhs) { return lhs.compare(rhs) >= 0; }\n\ninline bool operator>=(const char* lhs, const String& rhs) { return rhs.compare(rhs) <= 0; }\n\n// Overload == operator\ninline bool operator==(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) == 0; }\n\ninline bool operator==(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) == 0; }\n\ninline bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; }\n\ninline bool operator==(const String& lhs, const char* rhs) { return lhs.compare(rhs) == 0; }\n\ninline bool operator==(const char* lhs, const String& rhs) { return rhs.compare(lhs) == 0; }\n\n// Overload != operator\ninline bool operator!=(const String& lhs, const std::string& rhs) { return lhs.compare(rhs) != 0; }\n\ninline bool operator!=(const std::string& lhs, const String& rhs) { return rhs.compare(lhs) != 0; }\n\ninline bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; }\n\ninline bool operator!=(const String& lhs, const char* rhs) { return lhs.compare(rhs) != 0; }\n\ninline bool operator!=(const char* lhs, const String& rhs) { return rhs.compare(lhs) != 0; }\n\ninline std::ostream& operator<<(std::ostream& out, const String& input) {\n  out.write(input.data(), input.size());\n  return out;\n}\n\ninline int String::memncmp(const char* lhs, const char* rhs, size_t lhs_count, size_t rhs_count) {\n  if (lhs == rhs && lhs_count == rhs_count) return 0;\n\n  for (size_t i = 0; i < lhs_count && i < rhs_count; ++i) {\n    if (lhs[i] < rhs[i]) return -1;\n    if (lhs[i] > rhs[i]) return 1;\n  }\n  if (lhs_count < rhs_count) {\n    return -1;\n  } else if (lhs_count > rhs_count) {\n    return 1;\n  } else {\n    return 0;\n  }\n}\n\ninline size_t ObjectHash::operator()(const ObjectRef& a) const {\n  if (const auto* str = a.as<StringObj>()) {\n    return String::HashBytes(str->data, str->size);\n  }\n  return ObjectPtrHash()(a);\n}\n\ninline bool ObjectEqual::operator()(const ObjectRef& a, const ObjectRef& b) const {\n  if (a.same_as(b)) {\n    return true;\n  }\n  if (const auto* str_a = a.as<StringObj>()) {\n    if (const auto* str_b = b.as<StringObj>()) {\n      return String::memncmp(str_a->data, str_b->data, str_a->size, str_b->size) == 0;\n    }\n  }\n  return false;\n}\n}  // namespace runtime\n\n// expose the functions to the root namespace.\nusing runtime::String;\nusing runtime::StringObj;\n}  // namespace tvm\n\nnamespace std {\n\ntemplate <>\nstruct hash<::tvm::runtime::String> {\n  std::size_t operator()(const ::tvm::runtime::String& str) const {\n    return ::tvm::runtime::String::HashBytes(str.data(), str.size());\n  }\n};\n}  // namespace std\n\n#endif  // TVM_RUNTIME_CONTAINER_STRING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/contrib/libtorch_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief runtime implementation for LibTorch/TorchScript.\n */\n#ifndef TVM_RUNTIME_CONTRIB_LIBTORCH_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_LIBTORCH_RUNTIME_H_\n#include <tvm/runtime/module.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nruntime::Module TorchRuntimeCreate(const String& symbol_name,\n                                   const std::string& serialized_function);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_LIBTORCH_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/contrib/papi.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\brief Performance counters for profiling via the PAPI library.\n */\n#ifndef TVM_RUNTIME_CONTRIB_PAPI_H_\n#define TVM_RUNTIME_CONTRIB_PAPI_H_\n\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/profiling.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace profiling {\n\n/*! \\brief Construct a metric collector that collects data from hardware\n * performance counters using the Performance Application Programming Interface\n * (PAPI).\n *\n * \\param metrics A mapping from a device type to the metrics that should be\n * collected on that device. You can find the names of available metrics by\n * running `papi_native_avail`.\n */\nTVM_DLL MetricCollector CreatePAPIMetricCollector(Map<DeviceWrapper, Array<String>> metrics);\n}  // namespace profiling\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_PAPI_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/aot_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file aot_executor.h\n * \\brief AoT Executor\n */\n#ifndef TVM_RUNTIME_CRT_AOT_EXECUTOR_H_\n#define TVM_RUNTIME_CRT_AOT_EXECUTOR_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/crt/internal/common/ndarray.h>\n#include <tvm/runtime/metadata_types.h>\n\ntypedef struct TVMMetadata TVMMetadata;\n\ntypedef struct TVMAotExecutor {\n  /*! \\brief The top-level metadata structure supplied by the generated code */\n  const TVMMetadata* metadata;\n  /*! \\brief The code module that contains the compiled model */\n  TVMModuleHandle module_handle;\n  /*! \\brief The device type */\n  DLDevice device;\n  /*! \\brief List of allocated arguments, input(s), output(s), and pool(s)*/\n  TVMNDArray* args;\n  int64_t num_args;\n} TVMAotExecutor;\n\n/*!\n * \\brief Allocate a new AotExecutor with TVMPlatformMemoryAllocate and initialize it.\n *\n * \\param module_handle TVM Module that exposes the functions to call.\n * \\param device Runtime execution device, only supports device type kDLCPU, index 0.\n * \\param executor Pointer which receives a pointer to the newly-created instance.\n * \\param module_name TVM Module name prefix, typically \"default\".\n * \\return 0 if successful.\n */\nint TVMAotExecutor_Create(TVMModuleHandle module_handle, const DLDevice device,\n                          TVMAotExecutor** executor, const char* module_name);\n\n/*!\n * \\brief Release the AoT executor created by TVMAotExecutor_Create().\n *\n * \\param executor Pointer to executor instance, created by TVMAotExecutor_Create().\n * \\param device Runtime execution device, only supports device type kDLCPU, index 0.\n * \\return 0 if successful.\n */\nint TVMAotExecutor_Release(TVMAotExecutor* executor, const DLDevice device);\n\n/*!\n * \\brief Return the number of inputs.\n *\n * \\param executor Pointer to executor instance, created by TVMAotExecutor_Create().\n * \\return Number of inputs.\n */\nint TVMAotExecutor_GetNumInputs(TVMAotExecutor* executor);\n\n/*!\n * \\brief Return the number of outputs.\n *\n * \\param executor Pointer to executor instance, created by TVMAotExecutor_Create().\n * \\return Number of outputs.\n */\nint TVMAotExecutor_GetNumOutputs(TVMAotExecutor* executor);\n\n/*!\n * \\brief Return the input index of the specified input name\n *\n * \\param executor Pointer to executor instance, created by TVMAotExecutor_Create().\n * \\param name Input name for retrieving index.\n * \\return Input index.\n */\nint TVMAotExecutor_GetInputIndex(TVMAotExecutor* executor, const char* name);\n\n/*!\n * \\brief Run the generated program.\n *\n * \\param executor Pointer to executor instance, created by TVMAotExecutor_Create().\n * \\return 0 if successful.\n */\nint TVMAotExecutor_Run(TVMAotExecutor* executor);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_AOT_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/aot_executor_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file graph_executor.h\n * \\brief Tiny AoT executor\n */\n#ifndef TVM_RUNTIME_CRT_AOT_EXECUTOR_MODULE_H_\n#define TVM_RUNTIME_CRT_AOT_EXECUTOR_MODULE_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <tvm/runtime/crt/error_codes.h>\n\n/*!\n * \\brief Register the \"tvm.aot_executor.create\" constructor PackedFunc.\n */\ntvm_crt_error_t TVMAotExecutorModule_Register();\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_AOT_EXECUTOR_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/crt.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/crt.h\n * \\brief Defines core life cycle functions used by CRT.\n */\n\n#ifndef TVM_RUNTIME_CRT_CRT_H_\n#define TVM_RUNTIME_CRT_CRT_H_\n\n#include <inttypes.h>\n#include <tvm/runtime/crt/error_codes.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*!\n * \\brief Initialize various data structures used by the runtime.\n * Prior to calling this, any initialization needed to support TVMPlatformMemory* functions should\n * be completed.\n * \\return An error code describing the outcome of initialization. Generally, initialization\n *     is only expected to fail due to a misconfiguration.\n */\ntvm_crt_error_t TVMInitializeRuntime();\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_CRT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/error_codes.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/tvm/runtime/crt/error_codes.h\n * \\brief Defines integral error codes returned by the CRT.\n */\n#ifndef TVM_RUNTIME_CRT_ERROR_CODES_H_\n#define TVM_RUNTIME_CRT_ERROR_CODES_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define TVM_CRT_ERROR_CATEGORY_Pos 8\n#define TVM_CRT_ERROR_CATEGORY_Msk (0xff << TVM_CRT_ERROR_CATEGORY_Pos)\n#define TVM_CRT_ERROR_CODE_Pos 0\n#define TVM_CRT_ERROR_CODE_Msk (0xff << TVM_CRT_ERROR_CODE_Pos)\n\n#define DEFINE_TVM_CRT_ERROR(category, code) \\\n  (((category) << TVM_CRT_ERROR_CATEGORY_Pos) | ((code) << TVM_CRT_ERROR_CODE_Pos))\ntypedef enum {\n  kTvmErrorCategoryFunctionRegistry = 1,\n  kTvmErrorCategoryFraming = 2,\n  kTvmErrorCategoryWriteStream = 3,\n  kTvmErrorCategorySession = 4,\n  kTvmErrorCategoryPlatform = 5,\n  kTvmErrorCategoryGenerated = 6,\n  kTvmErrorCategoryExecutor = 7,\n  kTvmErrorCategoryFunctionCall = 8,\n  kTvmErrorCategoryTimeEvaluator = 9,\n} tvm_crt_error_category_t;\n\ntypedef enum {\n  kTvmErrorNoError = 0,\n\n  // Function Registry\n  kTvmErrorFunctionNameNotFound = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionRegistry, 0),\n  kTvmErrorFunctionIndexInvalid = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionRegistry, 1),\n  kTvmErrorFunctionRegistryFull = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionRegistry, 2),\n  kTvmErrorFunctionAlreadyDefined = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionRegistry, 3),\n  kTvmErrorBufferTooSmall = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionRegistry, 4),\n\n  // Framing\n  kTvmErrorFramingInvalidState = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFraming, 0),\n  kTvmErrorFramingShortPacket = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFraming, 1),\n  kTvmErrorFramingInvalidEscape = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFraming, 2),\n  kTvmErrorFramingPayloadOverflow = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFraming, 3),\n  kTvmErrorFramingPayloadIncomplete = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFraming, 4),\n\n  // Write stream\n  kTvmErrorWriteStreamShortWrite = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryWriteStream, 0),\n  kTvmErrorWriteStreamLongWrite = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryWriteStream, 1),\n\n  // Session\n  kTvmErrorSessionInvalidState = DEFINE_TVM_CRT_ERROR(kTvmErrorCategorySession, 0),\n  kTvmErrorSessionReceiveBufferBusy = DEFINE_TVM_CRT_ERROR(kTvmErrorCategorySession, 1),\n  kTvmErrorSessionReceiveBufferShortWrite = DEFINE_TVM_CRT_ERROR(kTvmErrorCategorySession, 2),\n\n  // Platform\n  kTvmErrorPlatformCheckFailure = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 0),\n  kTvmErrorPlatformMemoryManagerInitialized = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 1),\n  kTvmErrorPlatformShutdown = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 2),\n  kTvmErrorPlatformNoMemory = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 3),\n  kTvmErrorPlatformTimerBadState = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 4),\n  kTvmErrorPlatformStackAllocBadFree = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryPlatform, 5),\n\n  // Common error codes returned from generated functions.\n  kTvmErrorGeneratedInvalidStorageId = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryGenerated, 0),\n\n  // Graph or AoT executor\n  kTvmErrorExecutorModuleAlreadyCreated = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryExecutor, 0),\n  kTvmErrorExecutorModuleBadContext = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryExecutor, 1),\n  kTvmErrorExecutorModuleNoSuchInput = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryExecutor, 2),\n\n  // Function Calls - common problems encountered calling functions.\n  kTvmErrorFunctionCallNumArguments = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionCall, 0),\n  kTvmErrorFunctionCallWrongArgType = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionCall, 1),\n  kTvmErrorFunctionCallNotImplemented = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionCall, 2),\n  kTvmErrorFunctionCallInvalidArg = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryFunctionCall, 3),\n\n  // Time Evaluator - times functions for use with debug runtime.\n  kTvmErrorTimeEvaluatorBadHandle = DEFINE_TVM_CRT_ERROR(kTvmErrorCategoryTimeEvaluator, 0),\n\n  // System errors are always negative integers; this mask indicates presence of a system error.\n  // Cast tvm_crt_error_t to a signed integer to interpret the negative error code.\n  kTvmErrorSystemErrorMask = (1 << (sizeof(int) * 8 - 1)),\n} tvm_crt_error_t;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // TVM_RUNTIME_CRT_ERROR_CODES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/func_registry.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/tvm/runtime/crt/func_registry.h\n * \\brief Defines generic string-based function lookup structs\n */\n#ifndef TVM_RUNTIME_CRT_FUNC_REGISTRY_H_\n#define TVM_RUNTIME_CRT_FUNC_REGISTRY_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n\ntypedef uint16_t tvm_function_index_t;\n\ntypedef uint16_t tvm_module_index_t;\n\n/*!\n * \\brief A data structure that facilitates function lookup by C-string name.\n */\ntypedef struct TVMFuncRegistry {\n  /*! \\brief Names of registered functions, concatenated together and separated by \\0.\n   * An additional \\0 is present at the end of the concatenated blob to mark the end.\n   *\n   * Byte 0 and 1 are the number of functions in `funcs`.\n   */\n  const char* names;\n\n  /*! \\brief Function pointers, in the same order as their names in `names`. */\n  const TVMBackendPackedCFunc* funcs;\n} TVMFuncRegistry;\n\n/*!\n * \\brief Get the of the number of functions from registry.\n *\n * \\param reg TVMFunctionRegistry instance that contains the function.\n * \\return The number of functions from registry.\n */\nuint16_t TVMFuncRegistry_GetNumFuncs(const TVMFuncRegistry* reg);\n\n/*!\n * \\brief Set the number of functions to registry.\n *\n * \\param reg TVMFunctionRegistry instance that contains the function.\n * \\param num_funcs The number of functions\n * \\return 0 when successful.\n */\nint TVMFuncRegistry_SetNumFuncs(const TVMFuncRegistry* reg, const uint16_t num_funcs);\n\n/*!\n * \\brief Get the address of 0th function from registry.\n *\n * \\param reg TVMFunctionRegistry instance that contains the function.\n * \\return the address of 0th function from registry\n */\nconst char* TVMFuncRegistry_Get0thFunctionName(const TVMFuncRegistry* reg);\n\n/*!\n * \\brief Get packed function from registry by name.\n *\n * \\param reg TVMFunctionRegistry instance that contains the function.\n, * \\param name The function name\n * \\param function_index Pointer to receive the 0-based index of the function in the registry, if it\n *     was found. Unmodified otherwise.\n * \\return kTvmErrorNoError when successful. kTvmErrorFunctionNameNotFound when no function matched\n`name`.\n */\ntvm_crt_error_t TVMFuncRegistry_Lookup(const TVMFuncRegistry* reg, const char* name,\n                                       tvm_function_index_t* function_index);\n\n/*!\n * \\brief Fetch TVMBackendPackedCFunc given a function index\n *\n * \\param reg TVMFunctionRegistry instance that contains the function.\n * \\param index Index of the function.\n * \\param out_func Pointer which receives the function pointer at `index`, if a valid\n *      index was given. Unmodified otherwise.\n * \\return kTvmErrorNoError when successful. kTvmErrorFunctionIndexInvalid when index was out of\n * range.\n */\ntvm_crt_error_t TVMFuncRegistry_GetByIndex(const TVMFuncRegistry* reg, tvm_function_index_t index,\n                                           TVMBackendPackedCFunc* out_func);\n\n/*!\n * \\brief A TVMFuncRegistry that supports adding and changing the functions.\n */\ntypedef struct TVMMutableFuncRegistry {\n  TVMFuncRegistry registry;\n\n  /*! \\brief maximum number of functions in this registry. */\n  size_t max_functions;\n} TVMMutableFuncRegistry;\n\n// Defined to work around compiler limitations.\n#define TVM_AVERAGE_FUNCTION_NAME_STRLEN_BYTES 10\n\n/*!\n * \\brief Size of an average function name in a TVMMutableFuncRegistry, in bytes.\n *\n * This is just an assumption made by the runtime for ease of use.\n */\nstatic const size_t kTvmAverageFunctionNameStrlenBytes = TVM_AVERAGE_FUNCTION_NAME_STRLEN_BYTES;\n\n/*!\n * \\brief Size of an average entry in a TVMMutableFuncRegistry, in bytes.\n *\n * Assumes a constant average function name length.\n */\nstatic const size_t kTvmAverageFuncEntrySizeBytes =\n    TVM_AVERAGE_FUNCTION_NAME_STRLEN_BYTES + 1 + sizeof(void*);\n\n/*!\n * \\brief Create a new mutable function registry from a block of memory.\n *\n * \\param reg TVMMutableFuncRegistry to create.\n * \\param buffer Backing memory available for this function registry.\n * \\param buffer_size_bytes Number of bytes available in buffer.\n * \\return kTvmErrorNoError when successful. kTvmErrorBufferTooSmall when buffer_size_bytes is so\n *      small that a single function cannot be registered.\n */\ntvm_crt_error_t TVMMutableFuncRegistry_Create(TVMMutableFuncRegistry* reg, uint8_t* buffer,\n                                              size_t buffer_size_bytes);\n\n/*!\n * \\brief Add or set a function in the registry.\n *\n * \\param reg The mutable function registry to affect.\n * \\param name Name of the function.\n * \\param func The function pointer.\n * \\param override non-zero if an existing entry should be overridden.\n * \\return kTvmErrorNoError when successful. kTvmErrorRegistryFull when `reg` already contains\n *     `max_functions` entries. kTvmErrorFunctionAlreadyDefined when a function named `name` is\n * already present in the registry, and `override` == 0.\n */\ntvm_crt_error_t TVMMutableFuncRegistry_Set(TVMMutableFuncRegistry* reg, const char* name,\n                                           TVMBackendPackedCFunc func, int override);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // TVM_RUNTIME_CRT_FUNC_REGISTRY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/graph_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file graph_executor.h\n * \\brief Tiny graph executor that can run graph containing only tvm PackedFunc.\n */\n#ifndef TVM_RUNTIME_CRT_GRAPH_EXECUTOR_H_\n#define TVM_RUNTIME_CRT_GRAPH_EXECUTOR_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/packed_func.h>\n\nstruct TVMModule;\n\n/*! \\brief operator attributes about tvm op */\ntypedef struct TVMOpParam {\n  char func_name[TVM_CRT_MAX_STRLEN_FUNCTION_NAME];\n  uint32_t num_inputs;\n  uint32_t num_outputs;\n  uint32_t flatten_data;\n} TVMOpParam;\n\n// Graph attribute\ntypedef struct TVMGraphExecutorGraphAttr {\n  uint32_t storage_num_not_alloctaed;\n  uint32_t* storage_id;\n  uint32_t* device_index;\n  char* dltype;  // \"int8\", \"int16\", \"float32\"\n  uint32_t dltype_count;\n  int64_t* shape;\n  uint32_t* ndim;\n  uint32_t shape_count;\n} TVMGraphExecutorGraphAttr;\n\ntypedef struct TVMGraphExecutor TVMGraphExecutor;\n\n// public functions\n/*!\n * \\brief Allocate a new GraphExecutor with TVMPlatformMemoryAllocate and initialize it.\n *\n * \\param sym_json JSON-encoded graph.\n * \\param module_handle TVM Module that exposes the functions to call.\n * \\param devices runtime execution device.\n * \\param executor Pointer which receives a pointer to the newly-created instance.\n * \\return 0 if successful.\n */\nint TVMGraphExecutor_Create(const char* sym_json, TVMModuleHandle module_handle,\n                            const DLDevice* devices, TVMGraphExecutor** executor);\n\nint TVMGraphExecutor_GetInputIndex(TVMGraphExecutor* executor, const char* name);\n\n/*!\n * \\brief get number of input tensors allocated.\n * \\return integer number of tensors available to use.\n */\nint TVMGraphExecutor_GetNumInputs();\n\n/*!\n * \\brief set input to the graph based on name.\n * \\param executor The graph executor.\n * \\param name The name of the input.\n * \\param data_in The input data.\n */\nvoid TVMGraphExecutor_SetInput(TVMGraphExecutor* executor, const char* name, DLTensor* data_in);\n\n/*!\n * \\brief get number of output tensors allocated.\n * \\return integer number of output tensors allocated.\n */\nint TVMGraphExecutor_GetNumOutputs();\n\n/*!\n * \\brief Return NDArray for given output index.\n * \\param executor The graph executor.\n * \\param index The output index.\n * \\param out The DLTensor corresponding to given output node index.\n * \\return The result of this function execution.\n */\nint TVMGraphExecutor_GetOutput(TVMGraphExecutor* executor, const int32_t index, DLTensor* out);\n\n/*!\n * \\brief Load parameters from parameter blob.\n * \\param executor The graph executor.\n * \\param param_blob A binary blob of parameter.\n * \\param param_size The parameter size.\n * \\return The result of this function execution.\n */\nint TVMGraphExecutor_LoadParams(TVMGraphExecutor* executor, const char* param_blob,\n                                const uint32_t param_size);\n\n/*!\n * \\brief Execute the graph.\n * \\param executor The graph executor.\n */\nvoid TVMGraphExecutor_Run(TVMGraphExecutor* executor);\n\n/*!\n * \\brief Release memory associated with the graph executor.\n * \\param executor Pointer to graph executor.\n * \\return 0 if successful\n */\nint TVMGraphExecutor_Release(TVMGraphExecutor** executor);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_GRAPH_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/graph_executor_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file graph_executor_module.h\n * \\brief Tiny graph executor that can run graph containing only tvm PackedFunc.\n */\n#ifndef TVM_RUNTIME_CRT_GRAPH_EXECUTOR_MODULE_H_\n#define TVM_RUNTIME_CRT_GRAPH_EXECUTOR_MODULE_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <tvm/runtime/crt/error_codes.h>\n\n/*!\n * \\brief Register the \"tvm.graph_executor.create\" constructor PackedFunc.\n */\ntvm_crt_error_t TVMGraphExecutorModule_Register();\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_GRAPH_EXECUTOR_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/logging.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/crt/logging.h\n * \\brief A replacement of the dmlc logging system that avoids\n *  the usage of GLOG and C++ headers\n */\n\n#ifndef TVM_RUNTIME_CRT_LOGGING_H_\n#define TVM_RUNTIME_CRT_LOGGING_H_\n\n#include <tvm/runtime/crt/platform.h>\n\n#define TVM_CRT_LOG_LEVEL_DEBUG 3\n#define TVM_CRT_LOG_LEVEL_INFO 2\n#define TVM_CRT_LOG_LEVEL_WARN 1\n#define TVM_CRT_LOG_LEVEL_ERROR 0\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(_MSC_VER)\nvoid TVMLogf(const char* fmt, ...);\n#else\nvoid __attribute__((format(printf, 1, 2))) TVMLogf(const char* fmt, ...);\n#endif\n\n#define LOG(level, x, ...)          \\\n  if (TVM_CRT_LOG_LEVEL >= level) { \\\n    TVMLogf(x, ##__VA_ARGS__);      \\\n  }\n\n#define LOG_ERROR(x, ...) LOG(TVM_CRT_LOG_LEVEL_ERROR, x, ##__VA_ARGS__)\n#define LOG_WARN(x, ...) LOG(TVM_CRT_LOG_LEVEL_WARN, x, ##__VA_ARGS__)\n#define LOG_INFO(x, ...) LOG(TVM_CRT_LOG_LEVEL_INFO, x, ##__VA_ARGS__)\n#define LOG_DEBUG(x, ...) LOG(TVM_CRT_LOG_LEVEL_DEBUG, x, ##__VA_ARGS__)\n\n#ifndef CHECK\n#define CHECK(x)                                                   \\\n  do {                                                             \\\n    if (!(x)) {                                                    \\\n      LOG_ERROR(__FILE__ \":%d: Check failed: %s\\n\", __LINE__, #x); \\\n      TVMPlatformAbort(kTvmErrorPlatformCheckFailure);             \\\n    }                                                              \\\n  } while (0)\n#endif\n\n#ifndef CHECK_BINARY_OP\n#define CHECK_BINARY_OP(op, x, y, fmt, ...)                                               \\\n  do {                                                                                    \\\n    if (!(x op y)) {                                                                      \\\n      LOG_ERROR(__FILE__ \":%d: Check failed: %s %s %s: \" fmt \"\\n\", __LINE__, #x, #op, #y, \\\n                ##__VA_ARGS__);                                                           \\\n      TVMPlatformAbort(kTvmErrorPlatformCheckFailure);                                    \\\n    }                                                                                     \\\n  } while (0)\n#endif\n\n#ifndef CHECK_LT\n#define CHECK_LT(x, y, fmt, ...) CHECK_BINARY_OP(<, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifndef CHECK_GT\n#define CHECK_GT(x, y, fmt, ...) CHECK_BINARY_OP(>, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifndef CHECK_LE\n#define CHECK_LE(x, y, fmt, ...) CHECK_BINARY_OP(<=, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifndef CHECK_GE\n#define CHECK_GE(x, y, fmt, ...) CHECK_BINARY_OP(>=, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifndef CHECK_EQ\n#define CHECK_EQ(x, y, fmt, ...) CHECK_BINARY_OP(==, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifndef CHECK_NE\n#define CHECK_NE(x, y, fmt, ...) CHECK_BINARY_OP(!=, x, y, fmt, ##__VA_ARGS__)\n#endif\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_LOGGING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/microtvm_rpc_server.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file microtvm_rpc_server.h\n * \\brief MicroTVM RPC Server\n */\n\n#ifndef TVM_RUNTIME_CRT_MICROTVM_RPC_SERVER_H_\n#define TVM_RUNTIME_CRT_MICROTVM_RPC_SERVER_H_\n\n#include <stdlib.h>\n#include <sys/types.h>\n#include <tvm/runtime/crt/error_codes.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*! \\brief TVM RPC channel write function.\n *\n * Tries to write `num_bytes` from `data` to the underlying channel.\n * \\param data Pointer to data to write.\n * \\param num_bytes Number of bytes avaiable in data.\n * \\return The number of bytes written.\n */\ntypedef ssize_t (*microtvm_rpc_channel_write_t)(void* context, const uint8_t* data,\n                                                size_t num_bytes);\n\n/*! \\brief Opaque pointer type to TVM RPC Server. */\ntypedef void* microtvm_rpc_server_t;\n\n/*! \\brief Initialize the TVM RPC Server.\n *\n * Call this on device startup before calling anyother microtvm_rpc_server_ functions.\n *\n * \\param write_func A callback function invoked by the TVM RPC Server to write data back to the\n *                   host. Internally, the TVM RPC Server will block until all data in a reply\n *                   packet has been written.\n * \\param write_func_ctx An opaque pointer passed to write_func when it is called.\n * \\return A pointer to the TVM RPC Server. The pointer is allocated in the same memory space as\n *         the TVM workspace.\n */\nmicrotvm_rpc_server_t MicroTVMRpcServerInit(microtvm_rpc_channel_write_t write_func,\n                                            void* write_func_ctx);\n\n/*! \\brief Do any tasks suitable for the main thread, and maybe process new incoming data.\n *\n * \\param server The TVM RPC Server pointer.\n * \\param new_data If not nullptr, a pointer to a buffer pointer, which should point at new input\n *     data to process. On return, updated to point past data that has been consumed.\n * \\param new_data_size_bytes Points to the number of valid bytes in `new_data`. On return,\n *     updated to the number of unprocessed bytes remaining in `new_data` (usually 0).\n * \\return An error code indicating the outcome of the server main loop iteration.\n */\ntvm_crt_error_t MicroTVMRpcServerLoop(microtvm_rpc_server_t server, uint8_t** new_data,\n                                      size_t* new_data_size_bytes);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // TVM_RUNTIME_CRT_MICROTVM_RPC_SERVER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/tvm/runtime/crt/module.h\n * \\brief Runtime container of the functions\n */\n#ifndef TVM_RUNTIME_CRT_MODULE_H_\n#define TVM_RUNTIME_CRT_MODULE_H_\n\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/crt/func_registry.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*!\n * \\brief Module container of TVM.\n */\ntypedef struct TVMModule {\n  /*! \\brief The function registry associated with this module. */\n  const TVMFuncRegistry* registry;\n} TVMModule;\n\n/*!\n * \\brief Create a new module handle from the given TVMModule instance.\n * \\param mod The module instance to register.\n * \\param out_handle Pointer to receive the newly-minted handle for this module.\n * \\return 0 on success, non-zero on error.\n */\nint TVMModCreateFromCModule(const TVMModule* mod, TVMModuleHandle* out_handle);\n\n/*! \\brief Entry point for the system lib module. */\nconst TVMModule* TVMSystemLibEntryPoint(void);\n\n#ifdef __cplusplus\n}\n#endif\n#endif  // TVM_RUNTIME_CRT_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/packed_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/packed_func.h\n * \\brief Type-erased function used across TVM API.\n */\n#ifndef TVM_RUNTIME_CRT_PACKED_FUNC_H_\n#define TVM_RUNTIME_CRT_PACKED_FUNC_H_\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/module.h>\n#include <tvm/runtime/crt/platform.h>\n\n#include \"crt_config.h\"\n\nDLDataType String2DLDataType(const char* s);\n\ntypedef struct TVMArgs {\n  TVMValue values[TVM_CRT_MAX_ARGS];\n  int tcodes[TVM_CRT_MAX_ARGS]; /* Data type should be identical to type_codes in TVMPackedCFunc */\n  uint32_t values_count;\n} TVMArgs;\n\nTVMArgs TVMArgs_Create(TVMValue* values, uint32_t* tcodes, uint32_t values_count);\n\ntypedef struct TVMPackedFunc {\n  char name[200];\n  TVMFunctionHandle fexec;\n  TVMArgs args;\n  TVMArgs ret_value;\n  int (*Call)(struct TVMPackedFunc* pf);\n  void (*SetArgs)(struct TVMPackedFunc* pf, const struct TVMArgs* args);\n} TVMPackedFunc;\n\nint TVMPackedFunc_InitGlobalFunc(TVMPackedFunc* pf, const char* name, const TVMArgs* args);\nint TVMPackedFunc_InitModuleFunc(TVMPackedFunc* pf, TVMModuleHandle module, const char* name,\n                                 const TVMArgs* args);\n\nint TVMPackedFunc_Call(TVMPackedFunc* pf);\n\nvoid TVMPackedFunc_SetArgs(TVMPackedFunc* pf, const TVMArgs* args);\n\ninline TVMModuleHandle TVMArgs_AsModuleHandle(const TVMArgs* args, size_t index) {\n  if (index >= args->values_count) {\n    TVMPlatformAbort((tvm_crt_error_t)-1);\n  }\n\n  if (args->tcodes[index] != kTVMModuleHandle) {\n    TVMPlatformAbort((tvm_crt_error_t)-1);\n  }\n\n  return args->values[index].v_handle;\n}\n\nextern TVMPackedFunc* g_fexecs;\nextern uint32_t g_fexecs_count;\n\n#endif  // TVM_RUNTIME_CRT_PACKED_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/page_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/page_allocator.h\n * \\brief An implementation of a dynamic memory allocator for microcontrollers.\n */\n\n#ifndef TVM_RUNTIME_CRT_PAGE_ALLOCATOR_H_\n#define TVM_RUNTIME_CRT_PAGE_ALLOCATOR_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdlib.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n\nextern int vleak_size;\n\ntypedef struct MemoryManagerInterface MemoryManagerInterface;\n\nstruct MemoryManagerInterface {\n  /*!\n   * \\brief Allocate a chunk of memory.\n   * \\param interface Pointer to this structure.\n   * \\param num_bytes Number of bytes requested.\n   * \\param dev Execution device that will be used with the allocated memory. Must be {kDLCPU, 0}.\n   * \\param out_ptr A pointer to which is written a pointer to the newly-allocated memory.\n   * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n   */\n  tvm_crt_error_t (*Allocate)(MemoryManagerInterface* interface, size_t num_bytes, DLDevice dev,\n                              void** out_ptr);\n\n  /*!\n   * \\brief Free a chunk of previously-used memory.\n   *\n   * \\param interface Pointer to this structure.\n   * \\param ptr A pointer returned from TVMPlatformMemoryAllocate which should be free'd.\n   * \\param dev Execution device passed to TVMPlatformMemoryAllocate. Fixed to {kDLCPU, 0}.\n   * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n   */\n  tvm_crt_error_t (*Free)(MemoryManagerInterface* interface, void* ptr, DLDevice dev);\n\n  /*! \\brief Used in testing; the number of allocated objects. */\n  int vleak_size;\n};\n\n/*!\n * Exposed for testing.\n *\n * \\param manager Pointer, initialized with the new MemoryManager.\n * \\param memory_pool Pointer to the global memory pool used by the CRT.\n * \\param memory_pool_size_bytes Size of `memory_pool`, in bytes.\n * \\param page_size_bytes_log2 log2 of the page size, in bytes.\n * \\return kTvmErrorNoError on success.\n */\ntvm_crt_error_t PageMemoryManagerCreate(MemoryManagerInterface** manager, uint8_t* memory_pool,\n                                        size_t memory_pool_size_bytes, size_t page_size_bytes_log2);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_PAGE_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/platform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/platform.h\n * \\brief The virtual memory manager for micro-controllers\n */\n\n#ifndef TVM_RUNTIME_CRT_PLATFORM_H_\n#define TVM_RUNTIME_CRT_PLATFORM_H_\n\n#include <stdarg.h>\n#include <stddef.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*! \\brief Called when an internal error occurs and execution cannot continue.\n *\n * The platform should ideally restart or hang at this point.\n *\n * \\param code An error code.\n */\n#if defined(_MSC_VER)\n__declspec(noreturn) void TVMPlatformAbort(tvm_crt_error_t code);\n#else\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t code);\n#endif\n\n/*! \\brief Called by the microTVM RPC server to implement TVMLogf.\n *\n * Not required to be implemented when the RPC server is not linked into the binary. This\n * function's signature matches that of vsnprintf, so trivial implementations can just call\n * vsnprintf.\n *\n * \\param out_buf A char buffer where the formatted string should be written.\n * \\param out_buf_size_bytes Number of bytes available for writing in out_buf.\n * \\param fmt The printf-style formatstring.\n * \\param args extra arguments to be formatted.\n * \\return number of bytes written.\n */\nsize_t TVMPlatformFormatMessage(char* out_buf, size_t out_buf_size_bytes, const char* fmt,\n                                va_list args);\n\n/*!\n * \\brief Allocate memory for use by TVM.\n *\n * When this function returns something other than kTvmErrorNoError, *out_ptr should not be modified\n * and the caller is not obligated to call TVMPlatformMemoryFree in order to avoid a memory leak.\n *\n * \\param num_bytes Number of bytes requested.\n * \\param dev Execution device that will be used with the allocated memory. Fixed to {kDLCPU, 0}.\n * \\param out_ptr A pointer to which is written a pointer to the newly-allocated memory.\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr);\n\n/*!\n * \\brief Free memory used by TVM.\n *\n * \\param ptr A pointer returned from TVMPlatformMemoryAllocate which should be free'd.\n * \\param dev Execution device passed to TVMPlatformMemoryAllocate. Fixed to {kDLCPU, 0}.\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev);\n\n/*! \\brief Start a device timer.\n *\n * The device timer used must not be running.\n *\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformTimerStart();\n\n/*! \\brief Stop the running device timer and get the elapsed time (in microseconds).\n *\n * The device timer used must be running.\n *\n * \\param elapsed_time_seconds Pointer to write elapsed time into.\n *\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformTimerStop(double* elapsed_time_seconds);\n\n/*! \\brief Platform-specific before measurement call.\n *\n * A function which is called before calling TVMFuncCall in the TimeEvaluator.\n * Can be used, for example, to initialize reset global state which may affect the results of\n * measurement.\n *\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformBeforeMeasurement();\n\n/*! \\brief Platform-specific after measurement call.\n *\n * A function which is called after calling TVMFuncCall in the TimeEvaluator.\n * It is the counterpart of the TVMPlatformBeforeMeasurement function.\n *\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformAfterMeasurement();\n\n/*! \\brief Fill a buffer with random data.\n *\n * Cryptographically-secure random data is NOT required. This function is intended for use\n * cases such as filling autotuning input tensors and choosing the nonce used for microTVM RPC.\n *\n * This function does not need to be implemented for inference tasks. It is used only by\n * AutoTVM and the RPC server. When not implemented, an internal weak-linked stub is provided.\n *\n * Please take care that across successive resets, this function returns different sequences of\n * values. If e.g. the random number generator is seeded with the same value, it may make it\n * difficult for a host to detect device resets during autotuning or host-driven inference.\n *\n * \\param buffer Pointer to the 0th byte to write with random data. `num_bytes` of random data\n * should be written here.\n * \\param num_bytes Number of bytes to write.\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t TVMPlatformGenerateRandom(uint8_t* buffer, size_t num_bytes);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_PLATFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/rpc_common/frame_buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/rpc_common/frame_buffer.h\n * \\brief Defines a buffer for use by the RPC framing layer.\n */\n\n#ifndef TVM_RUNTIME_CRT_RPC_COMMON_FRAME_BUFFER_H_\n#define TVM_RUNTIME_CRT_RPC_COMMON_FRAME_BUFFER_H_\n\n#include <inttypes.h>\n#include <stdlib.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace micro_rpc {\n\nclass FrameBuffer {\n public:\n  FrameBuffer(uint8_t* data, size_t data_size_bytes)\n      : data_{data}, capacity_{data_size_bytes}, num_valid_bytes_{0}, read_cursor_{0} {}\n\n  size_t Write(const uint8_t* data, size_t data_size_bytes);\n\n  size_t Read(uint8_t* data, size_t data_size_bytes);\n\n  size_t Peek(uint8_t* data, size_t data_size_bytes);\n\n  void Clear();\n\n  size_t ReadAvailable() const { return num_valid_bytes_ - read_cursor_; }\n\n  size_t Size() const { return num_valid_bytes_; }\n\n private:\n  /*! \\brief pointer to data buffer. */\n  uint8_t* data_;\n\n  /*! \\brief The total number of bytes available in data_. Always a power of 2. */\n  size_t capacity_;\n\n  /*! \\brief index into data_ of the next potentially-available byte in the buffer.\n   * The byte is available when tail_ != data_ + capacity_.\n   */\n  size_t num_valid_bytes_;\n\n  /*! \\brief Read cursor position. */\n  size_t read_cursor_;\n};\n\n}  // namespace micro_rpc\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CRT_RPC_COMMON_FRAME_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/rpc_common/framing.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file framing.h\n * \\brief Framing for RPC.\n */\n\n#ifndef TVM_RUNTIME_CRT_RPC_COMMON_FRAMING_H_\n#define TVM_RUNTIME_CRT_RPC_COMMON_FRAMING_H_\n\n#include <inttypes.h>\n#include <stddef.h>\n#include <tvm/runtime/crt/error_codes.h>\n#include <tvm/runtime/crt/rpc_common/write_stream.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace micro_rpc {\n\nuint16_t crc16_compute(const uint8_t* data, size_t data_size_bytes, uint16_t* previous_crc);\n\nenum class Escape : uint8_t { kEscapeStart = 0xff, kEscapeNop = 0xfe, kPacketStart = 0xfd };\n\nclass PacketFieldSizeBytes {\n public:\n  static constexpr const size_t kPayloadLength = sizeof(uint32_t);\n  static constexpr const size_t kCrc = sizeof(uint16_t);\n};\n\nclass Unframer {\n public:\n  explicit Unframer(WriteStream* stream)\n      : stream_{stream},\n        state_{State::kFindPacketStart},\n        saw_escape_start_{false},\n        num_buffer_bytes_valid_{0} {}\n\n  /*!\n   * \\brief Push data into unframer and try to decode one packet.\n   *\n   * This function will return when exactly one packet has been decoded. It may not consume all of\n   * `data` in this case, and valid bytes may remain at the end of data.\n   *\n   * \\param data The new data to unframe and send downstream.\n   * \\param data_size_bytes The number of valid bytes in data.\n   * \\param bytes_consumed Pointer written with the number of bytes consumed from data.\n   * \\return\n   *     - kTvmErrorNoError when successful -- continue writing data.\n   *     - kTvmErrorFramingInvalidState when the Unframer was in or enters an invalid state\n   *       (probably indicates memory corruption).\n   *     - kTvmErrorFramingShortPacket when a new packet started before the current one ended.\n   *     - kTvmErrorFramingInvalidEscape when an invalid escape sequence was seen\n   */\n  tvm_crt_error_t Write(const uint8_t* data, size_t data_size_bytes, size_t* bytes_consumed);\n\n  /*! \\brief Reset unframer to initial state. */\n  void Reset();\n\n  /*! \\brief Return an underestimate of the number of bytes needed from the wire. */\n  size_t BytesNeeded();\n\n private:\n  tvm_crt_error_t FindPacketStart();\n  tvm_crt_error_t FindPacketLength();\n  tvm_crt_error_t FindPacketCrc();\n  tvm_crt_error_t FindCrcEnd();\n\n  bool IsBufferFull(size_t buffer_full_bytes) {\n    return num_buffer_bytes_valid_ >= buffer_full_bytes;\n  }\n\n  /*! \\brief Consume input into buffer_ until buffer_ has buffer_full_bytes. */\n  tvm_crt_error_t AddToBuffer(size_t buffer_full_bytes, bool update_crc);\n\n  void ClearBuffer();\n\n  /*! \\brief Unescape and consume input bytes, storing into buffer.\n   *\n   * \\param buffer A buffer to fill with consumed, unescaped bytes.\n   * \\param buffer_size_bytes Size of buffer, in bytes.\n   * \\param bytes_filled A pointer to an accumulator to which is added the number of bytes written\n   *      to `buffer`.\n   * \\param update_crc true when the CRC should be updated with the escaped bytes.\n   * \\return\n   *     - kTvmErrorNoError if successful\n   *     - kTvmErrorFramingShortPacket if a start-of-packet escape code was encountered. If so,\n   *       *bytes_filled indicates the number of bytes before the Escape::kEscapeStart byte.\n   *     - kTvmErrorFramingInvalidEscape if an invalid escape sequence was seen.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns 0.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns an invalid positive number.\n   *     - Any negative value (i.e. with bits in kTvmErrorSystemErrorMask set) returned by the\n   *       WriteStream's Write() function.\n   */\n  tvm_crt_error_t ConsumeInput(uint8_t* buffer, size_t buffer_size_bytes, size_t* bytes_filled,\n                               bool update_crc);\n\n  WriteStream* stream_;\n\n  enum class State : uint8_t {\n    kFindPacketStart = 0,\n    kFindPacketLength = 1,\n    kFindPacketCrc = 2,\n    kFindCrcEnd = 3,\n  };\n  State state_;\n\n  const uint8_t* input_;\n  size_t input_size_bytes_;\n\n  bool saw_escape_start_;\n\n  /*! \\brief unframe buffer, sized to the longest framing field. */\n  uint8_t buffer_[128];\n\n  /*! \\brief number of bytes in buffer that are currently valid. */\n  size_t num_buffer_bytes_valid_;\n\n  /*! \\brief number of payload bytes left to receive before the CRC begins. */\n  size_t num_payload_bytes_remaining_;\n\n  /*! \\brief Running CRC value. */\n  uint16_t crc_;\n};\n\nclass Framer {\n public:\n  typedef ssize_t (*WriteFunc)(const uint8_t* data, size_t data_size_bytes);\n\n  explicit Framer(WriteStream* stream)\n      : stream_{stream}, state_{State::kReset}, num_payload_bytes_remaining_{0} {}\n\n  /*! \\brief Frame and write a full packet.\n   * \\param payload The entire packet payload.\n   * \\param payload_size_bytes Number of bytes in the packet.\n   * \\return\n   *     - kTvmErrorNoError when no error occurs\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns 0.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns an invalid positive number.\n   *     - Any negative value (i.e. with bits in kTvmErrorSystemErrorMask set) returned by the\n   *       WriteStream's Write() function.\n   */\n  tvm_crt_error_t Write(const uint8_t* payload, size_t payload_size_bytes);\n\n  /*! \\brief Start framing and writing a new packet to the wire.\n   *\n   * When transmitting payloads that are too large to be buffered, call this function first to send\n   * the packet header and length fields.\n   *\n   * \\param payload_size_bytes Number of payload bytes included as part of this packet.\n   * \\return\n   *     - kTvmErrorNoError when no error occurs\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns 0.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns an invalid positive number.\n   *     - Any negative value (i.e. with bits in kTvmErrorSystemErrorMask set) returned by the\n   *       WriteStream's Write() function.\n   */\n  tvm_crt_error_t StartPacket(size_t payload_size_bytes);\n\n  /*! \\brief Write payload data to the wire.\n   *\n   * When transmitting payloads that are too large to be buffered, call this function after calling\n   * StartPacket to escape and transmit framed payloads. This function can be called multiple times\n   * for a single packet.\n   *\n   * \\param payload_chunk A piece of the packet payload.\n   * \\param payload_chunk_size_bytes Number of valid bytes in payload_chunk.\n   * \\return\n   *     - kTvmErrorNoError when no error occurs\n   *     - kTvmErrorFramingInvalidState when StartPacket() has not been called.\n   *     - kTvmErrorFramingPayloadOverflow when more bytes were requested to be written than were\n   *       declared in the payload_size_bytes parameter given to StartPacket().\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns 0.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns an invalid positive number.\n   *     - Any negative value (i.e. with bits in kTvmErrorSystemErrorMask set) returned by the\n   *       WriteStream's Write() function.\n   */\n  tvm_crt_error_t WritePayloadChunk(const uint8_t* payload_chunk, size_t payload_chunk_size_bytes);\n\n  /* \\brief Finish writing one packet by sending the CRC.\n   *\n   * When transmitting paylaods that are too large to be buffered, call this function after sending\n   * the entire payload using WritePayloadChunk.\n   *\n   * \\return\n   *     - kTvmErrorNoError when no error occurs\n   *     - kTvmErrorFramingInvalidState when StartPacket() has not been called.\n   *     - kTvmErrorFramingPayloadIncomplete when less bytes were written using WritePayloadChunk()\n   *       than were declared in the payload_size_bytes parameter given to StartPacket().\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns 0.\n   *     - kTvmErrorWriteStreamShortWrite if the WriteStream passed to constructor's Write()\n   *       function returns an invalid positive number.\n   *     - Any negative value (i.e. with bits in kTvmErrorSystemErrorMask set) returned by the\n   *       WriteStream's Write() function.\n   */\n  tvm_crt_error_t FinishPacket();\n\n  /* \\brief Reset state of the Framer. */\n  void Reset();\n\n private:\n  /*! \\brief Maximum size of stack-based buffer. */\n  static constexpr const size_t kMaxStackBufferSizeBytes = 128;\n\n  enum class State : uint8_t {\n    /*! \\brief State entered at construction time or after write error, before first packet sent. */\n    kReset = 0,\n\n    /*! \\brief State entered after a packet has successfully finished transmitting. */\n    kIdle = 1,\n\n    /*! \\brief State entered when a packet payload or CRC needs to be transmitted. */\n    kTransmitPacketPayload = 2,\n  };\n\n  /*!\n   * \\brief Escape data and write the result to wire, and update crc_.\n   *\n   * \\param data Unescaped data to write.\n   * \\param data_size_bytes Number of valid bytes in data.\n   * \\param escape true if escaping should be applied.\n   * \\param update_crc true if escaping should be applied.\n   * \\return kTvmErrorNoError on success, negative value on error.\n   */\n  tvm_crt_error_t WriteAndCrc(const uint8_t* data, size_t data_size_bytes, bool escape,\n                              bool update_crc);\n\n  /*! \\brief Called to write framed data to the transport. */\n  WriteStream* stream_;\n\n  /*! \\brief State fo the Framer. */\n  State state_;\n\n  /*! \\brief When state_ == kTransmitPacketPayload, number of payload bytes left to transmit. */\n  size_t num_payload_bytes_remaining_;\n\n  /*! \\brief Running CRC value. */\n  uint16_t crc_;\n};\n\n}  // namespace micro_rpc\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CRT_RPC_COMMON_FRAMING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/rpc_common/session.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file session.h\n * \\brief RPC Session\n */\n\n#ifndef TVM_RUNTIME_CRT_RPC_COMMON_SESSION_H_\n#define TVM_RUNTIME_CRT_RPC_COMMON_SESSION_H_\n\n#include <inttypes.h>\n#include <tvm/runtime/crt/error_codes.h>\n#include <tvm/runtime/crt/rpc_common/frame_buffer.h>\n#include <tvm/runtime/crt/rpc_common/framing.h>\n#include <tvm/runtime/crt/rpc_common/write_stream.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace micro_rpc {\n\nenum class MessageType : uint8_t {\n  kStartSessionInit = 0x00,\n  kStartSessionReply = 0x01,\n  kTerminateSession = 0x02,\n  kLog = 0x03,\n  kNormal = 0x10,\n};\n\n#if defined(_MSC_VER)\n\n#pragma pack(push, 1)\ntypedef struct SessionHeader {\n  uint16_t session_id;\n  MessageType message_type;\n} SessionHeader;\n#pragma pack(pop)\n\n#else\n\ntypedef struct SessionHeader {\n  uint16_t session_id;\n  MessageType message_type;\n} __attribute__((packed)) SessionHeader;\n\n#endif\n\n/*!\n * \\brief CRT communication session management class.\n * Assumes the following properties provided by the underlying transport:\n *  - in-order delivery.\n *  - reliable delivery.\n *\n * Specifically, designed for use with UARTs. Will probably work over semihosting, USB, and TCP;\n * will probably not work reliably enough over UDP.\n */\nclass Session {\n public:\n  /*! \\brief Callback invoked when a full message is received.\n   *\n   * This function is called in the following situations:\n   *  - When a new session is established (this typically indicates the remote end reset).\n   *    In this case, buf is NULL.\n   *  - When a log message or normal traffic is received. In this case, buf points to a\n   *    valid buffer containing the message content.\n   *\n   * \\param context The value of `message_received_func_context` passed to the constructor.\n   * \\param message_type The type of session message received. Currently, this is always\n   *      either kNormal or kLog.\n   * \\param buf When message_type is not kStartSessionMessage, a FrameBuffer whose read cursor is\n   *      at the first byte of the message payload. Otherwise, NULL.\n   */\n  typedef void (*MessageReceivedFunc)(void* context, MessageType message_type, FrameBuffer* buf);\n\n  /*! \\brief An invalid nonce value that typically indicates an unknown nonce. */\n  static constexpr const uint8_t kInvalidNonce = 0;\n\n  Session(Framer* framer, FrameBuffer* receive_buffer, MessageReceivedFunc message_received_func,\n          void* message_received_func_context)\n      : local_nonce_{kInvalidNonce},\n        session_id_{0},\n        state_{State::kReset},\n        receiver_{this},\n        framer_{framer},\n        receive_buffer_{receive_buffer},\n        receive_buffer_has_complete_message_{false},\n        message_received_func_{message_received_func},\n        message_received_func_context_{message_received_func_context} {\n    // Session can be used for system startup logging, before the RPC server is instantiated. In\n    // this case, allow receive_buffer_ to be nullptr. The instantiator agrees not to use\n    // Receiver().\n    if (receive_buffer_ != nullptr) {\n      receive_buffer_->Clear();\n    }\n  }\n\n  /*!\n   * \\brief Send a session terminate message, usually done at startup to interrupt a hanging remote.\n   * \\param initial_session_nonce Initial nonce that should be used on the first session start\n   *      message. Callers should ensure this is different across device resets.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t Initialize(uint8_t initial_session_nonce);\n\n  /*!\n   * \\brief Terminate any previously-established session.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t TerminateSession();\n\n  /*!\n   * \\brief Start a new session regardless of state. Sends kStartSessionMessage.\n   *\n   * Generally speaking, this function should be called once per device reset by exactly one side\n   * in the system. No traffic can flow until this function is called.\n   *\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t StartSession();\n\n  /*!\n   * \\brief Obtain a WriteStream implementation for use by the framing layer.\n   * \\return A WriteStream to which received data should be written. Owned by this class.\n   */\n  WriteStream* Receiver() { return &receiver_; }\n\n  /*!\n   * \\brief Send a full message including header, payload, and CRC footer.\n   * \\param message_type One of MessageType; distinguishes the type of traffic at the session layer.\n   * \\param message_data The data contained in the message.\n   * \\param message_size_bytes The number of valid bytes in message_data.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t SendMessage(MessageType message_type, const uint8_t* message_data,\n                              size_t message_size_bytes);\n\n  /*!\n   * \\brief Send the framing and session layer headers.\n   *\n   * This function allows messages to be sent in pieces.\n   *\n   * \\param message_type One of MessageType; distinguishes the type of traffic at the session layer.\n   * \\param message_size_bytes The size of the message body, in bytes. Excludes the framing and\n   * session layer headers. \\return 0 on success, negative error code on failure.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t StartMessage(MessageType message_type, size_t message_size_bytes);\n\n  /*!\n   * \\brief Send a part of the message body.\n   *\n   * This function allows messages to be sent in pieces.\n   *\n   * \\param chunk_data The data contained in this message body chunk.\n   * \\param chunk_size_bytes The number of valid bytes in chunk_data.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t SendBodyChunk(const uint8_t* chunk_data, size_t chunk_size_bytes);\n\n  /*!\n   * \\brief Finish sending the message by sending the framing layer footer.\n   * \\return kTvmErrorNoError on success, or an error code otherwise.\n   */\n  tvm_crt_error_t FinishMessage();\n\n  /*! \\brief Returns true if the session is in the established state. */\n  bool IsEstablished() const { return state_ == State::kSessionEstablished; }\n\n  /*!\n   * \\brief Clear the receive buffer and prepare to receive next message.\n   *\n   * Call this function after MessageReceivedFunc is invoked. Any SessionReceiver::Write() calls\n   * made will return errors until this function is called to prevent them from corrupting the\n   * valid message in the receive buffer.\n   */\n  void ClearReceiveBuffer();\n\n  /*! \\brief A version number used to check compatibility of the remote session implementation. */\n  static const constexpr uint8_t kVersion = 0x01;\n\n private:\n  class SessionReceiver : public WriteStream {\n   public:\n    explicit SessionReceiver(Session* session) : session_{session} {}\n    virtual ~SessionReceiver() {}\n\n    ssize_t Write(const uint8_t* data, size_t data_size_bytes) override;\n    void PacketDone(bool is_valid) override;\n\n   private:\n    void operator delete(void*) noexcept {}  // NOLINT(readability/casting)\n    Session* session_;\n  };\n\n  enum class State : uint8_t {\n    kReset = 0,\n    kNoSessionEstablished = 1,\n    kStartSessionSent = 2,\n    kSessionEstablished = 3,\n  };\n\n  void RegenerateNonce();\n\n  tvm_crt_error_t SendInternal(MessageType message_type, const uint8_t* message_data,\n                               size_t message_size_bytes);\n\n  void SendSessionStartReply(const SessionHeader& header);\n\n  void ProcessStartSessionInit(const SessionHeader& header);\n\n  void ProcessStartSessionReply(const SessionHeader& header);\n\n  void OnSessionEstablishedMessage();\n\n  void OnSessionTerminatedMessage();\n\n  void SetSessionId(uint8_t initiator_nonce, uint8_t responder_nonce) {\n    session_id_ = initiator_nonce | (((uint16_t)responder_nonce) << 8);\n  }\n\n  uint8_t InitiatorNonce(uint16_t session_id) { return session_id & 0xff; }\n\n  uint8_t ResponderNonce(uint16_t session_id) { return (session_id >> 8) & 0xff; }\n\n  uint8_t local_nonce_;\n  uint16_t session_id_;\n  State state_;\n  SessionReceiver receiver_;\n  Framer* framer_;\n  FrameBuffer* receive_buffer_;\n  bool receive_buffer_has_complete_message_;\n  MessageReceivedFunc message_received_func_;\n  void* message_received_func_context_;\n};\n\n}  // namespace micro_rpc\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CRT_RPC_COMMON_SESSION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/rpc_common/write_stream.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file framing.h\n * \\brief Framing for RPC.\n */\n\n#ifndef TVM_RUNTIME_CRT_RPC_COMMON_WRITE_STREAM_H_\n#define TVM_RUNTIME_CRT_RPC_COMMON_WRITE_STREAM_H_\n\n#include <inttypes.h>\n#include <stddef.h>\n#include <sys/types.h>\n#include <tvm/runtime/crt/error_codes.h>\n\n#include \"../../../../../src/support/ssize.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace micro_rpc {\n\nclass WriteStream {\n public:\n  virtual ~WriteStream();\n  virtual ssize_t Write(const uint8_t* data, size_t data_size_bytes) = 0;\n  virtual void PacketDone(bool is_valid) = 0;\n\n  tvm_crt_error_t WriteAll(uint8_t* data, size_t data_size_bytes, size_t* bytes_consumed);\n};\n\n}  // namespace micro_rpc\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CRT_RPC_COMMON_WRITE_STREAM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/crt/stack_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n#ifndef TVM_RUNTIME_CRT_STACK_ALLOCATOR_H_\n#define TVM_RUNTIME_CRT_STACK_ALLOCATOR_H_\n#include <stddef.h>\n#include <stdint.h>\n\n#include \"crt_config.h\"\n#include \"error_codes.h\"\n\n#define STACK_ALLOCATOR_TAG 0xabcd1234\n#define STACK_ALLOCATOR_TAG_SIZE_BYTES 4\n\n/*! Memory alignment for allocator */\n\n#ifndef TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES\n#define TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES 16\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct {\n  uint8_t* next_alloc;    // Pointer to the next block of TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES\n  uint8_t* workspace;     // Pointer to start of the workspace\n  size_t workspace_size;  // Total number of bytes in the workspace\n} tvm_workspace_t;\n\n/*!\n * \\brief Initialize the stack-based memory manager\n *\n * \\param tvm_runtime_workspace The tvm_workspace_t struct containing state\n * \\param g_aot_memory The memory buffer used to allocate within\n * \\param workspace_size The total size of the workspace buffer workspace\n */\ntvm_crt_error_t StackMemoryManager_Init(tvm_workspace_t* tvm_runtime_workspace,\n                                        uint8_t* g_aot_memory, size_t workspace_size);\n\n/*!\n * \\brief The intended user-facing function to allocate within the buffer. It wraps\n * StackMemoryManager_Allocate_Body enable and disable the LIFO check that is useful for debugging\n * the AoT codegen.\n *\n * \\param tvm_runtime_workspace The tvm_workspace_t struct containing state\n * \\param nbytes The number of bytes required for the allocation\n * \\param current_alloc The pointer-to-pointer to be populated with the allocated address\n */\ntvm_crt_error_t StackMemoryManager_Allocate(tvm_workspace_t* tvm_runtime_workspace, int32_t nbytes,\n                                            void** current_alloc);\n\n/*!\n * \\brief The internal function that accepts allocate inputs and an extra byte to say to enable the\n * LIFO check that is useful in debugging for debugging the AoT codegen.\n *\n * \\param tvm_runtime_workspace The tvm_workspace_t struct containing state\n * \\param nbytes The number of bytes required for the allocation\n * \\param current_alloc The pointer-to-pointer to be populated with the allocated address\n * \\param do_lifo_check This being non-zero indicates to perform a check LIFO pattern Allocs/Frees\n */\ntvm_crt_error_t StackMemoryManager_Allocate_Body(tvm_workspace_t* tvm_runtime_workspace,\n                                                 int32_t nbytes, void** current_alloc,\n                                                 uint8_t do_lifo_check);\n\n/*!\n * \\brief The intended user-facing function to free the tensor within the buffer. It wraps\n * StackMemoryManager_Free_Body enable and disable the stack allocator\n *\n * \\param tvm_runtime_workspace The tvm_workspace_t struct containing state\n * \\param ptr The base pointer of the tensor to be free'd\n */\ntvm_crt_error_t StackMemoryManager_Free(tvm_workspace_t* tvm_runtime_workspace, void* ptr);\n\n/*!\n * \\brief The internal function that accepts free inputs and an extra byte to say to enable the LIFO\n * check that is useful in debugging for debugging the AoT codegen.\n *\n * \\param tvm_runtime_workspace The tvm_workspace_t struct containing state\n * \\param ptr The base pointer of tensor to be free'd within the workspace buffer\n * \\param do_lifo_check This being non-zero indicates to perform a check LIFO pattern Allocs/Frees\n */\ntvm_crt_error_t StackMemoryManager_Free_Body(tvm_workspace_t* tvm_runtime_workspace, void* ptr,\n                                             uint8_t do_lifo_check);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_STACK_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/data_type.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*\n * \\file tvm/runtime/data_type.h\n * \\brief Primitive runtime data type.\n */\n// Acknowledgement: DataType structure design originates from Halide.\n#ifndef TVM_RUNTIME_DATA_TYPE_H_\n#define TVM_RUNTIME_DATA_TYPE_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/logging.h>\n\n#include <string>\n#include <type_traits>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief Runtime primitive data type.\n *\n *  This class is a thin wrapper of DLDataType.\n *  We also make use of DataType in compiler to store quick hint\n */\nclass DataType {\n public:\n  /*!\n   * \\brief Type code for the DataType.\n   *\n   * DLPack consistency:\n   * 1) kInt is consistent with kDLInt\n   * 2) kUInt is consistent with kDLUInt\n   * 3) kFloat is consistent with kDLFloat\n   */\n  enum TypeCode {\n    kInt = kDLInt,\n    kUInt = kDLUInt,\n    kFloat = kDLFloat,\n    kHandle = TVMArgTypeCode::kTVMOpaqueHandle,\n    kBFloat = kDLBfloat,\n    kCustomBegin = 129\n  };\n  /*! \\brief default constructor */\n  DataType() { data_ = DataType::Void(); }\n  /*!\n   * \\brief Constructor\n   * \\param dtype The DLDataType\n   */\n  explicit DataType(DLDataType dtype) : data_(dtype) {}\n  /*!\n   * \\brief Constructor\n   * \\param code The type code.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes.\n   */\n  DataType(int code, int bits, int lanes) {\n    data_.code = static_cast<uint8_t>(code);\n    data_.bits = static_cast<uint8_t>(bits);\n    data_.lanes = static_cast<uint16_t>(lanes);\n    if (code == kBFloat) {\n      ICHECK_EQ(bits, 16);\n    }\n  }\n  /*! \\return The type code. */\n  int code() const { return static_cast<int>(data_.code); }\n  /*! \\return number of bits in the data. */\n  int bits() const { return static_cast<int>(data_.bits); }\n  /*! \\return number of bytes to store each scalar. */\n  int bytes() const { return (bits() + 7) / 8; }\n  /*! \\return number of lanes in the data. */\n  int lanes() const { return static_cast<int>(data_.lanes); }\n  /*! \\return whether type is a scalar type. */\n  bool is_scalar() const { return lanes() == 1; }\n  /*! \\return whether type is a scalar type. */\n  bool is_bool() const { return code() == DataType::kUInt && bits() == 1; }\n  /*! \\return whether type is a float type. */\n  bool is_float() const { return code() == DataType::kFloat; }\n  /*! \\return whether type is a float16 type. */\n  bool is_float16() const { return is_float() && bits() == 16; }\n  /*! \\return whether type is a bfloat16 type. */\n  bool is_bfloat16() const { return code() == DataType::kBFloat && bits() == 16; }\n  /*! \\return whether type is an int type. */\n  bool is_int() const { return code() == DataType::kInt; }\n  /*! \\return whether type is an uint type. */\n  bool is_uint() const { return code() == DataType::kUInt; }\n  /*! \\return whether type is a handle type. */\n  bool is_handle() const { return code() == DataType::kHandle && !is_void(); }\n  /*! \\return whether type is a vector type. */\n  bool is_vector() const { return lanes() > 1; }\n  /*! \\return whether type is a bool vector type. */\n  bool is_vector_bool() const { return is_vector() && bits() == 1; }\n  /*! \\return whether type is a Void type. */\n  bool is_void() const { return code() == DataType::kHandle && bits() == 0 && lanes() == 0; }\n  /*!\n   * \\brief Create a new data type by change lanes to a specified value.\n   * \\param lanes The target number of lanes.\n   * \\return the result type.\n   */\n  DataType with_lanes(int lanes) const { return DataType(data_.code, data_.bits, lanes); }\n  /*!\n   * \\brief Create a new data type by change bits to a specified value.\n   * \\param bits The target number of bits.\n   * \\return the result type.\n   */\n  DataType with_bits(int bits) const { return DataType(data_.code, bits, data_.lanes); }\n  /*!\n   * \\brief Get the scalar version of the type.\n   * \\return the result type.\n   */\n  DataType element_of() const { return with_lanes(1); }\n  /*!\n   * \\brief Assignment operator.\n   */\n  DataType& operator=(const DataType& rhs) {\n    if (this == &rhs) {\n      return *this;\n    }\n    data_ = rhs.data_;\n    return *this;\n  }\n  /*!\n   * \\brief Equal comparator.\n   * \\param other The data type to compare against.\n   * \\return The comparison result.\n   */\n  bool operator==(const DataType& other) const {\n    return data_.code == other.data_.code && data_.bits == other.data_.bits &&\n           data_.lanes == other.data_.lanes;\n  }\n  /*!\n   * \\brief NotEqual comparator.\n   * \\param other The data type to compare against.\n   * \\return The comparison result.\n   */\n  bool operator!=(const DataType& other) const { return !operator==(other); }\n  /*!\n   * \\brief Converter to DLDataType\n   * \\return the result.\n   */\n  operator DLDataType() const { return data_; }\n\n  /*!\n   * \\brief Construct an int type.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes.\n   * \\return The constructed data type.\n   */\n  static DataType Int(int bits, int lanes = 1) { return DataType(kDLInt, bits, lanes); }\n  /*!\n   * \\brief Construct an uint type.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes\n   * \\return The constructed data type.\n   */\n  static DataType UInt(int bits, int lanes = 1) { return DataType(kDLUInt, bits, lanes); }\n  /*!\n   * \\brief Construct an float type.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes\n   * \\return The constructed data type.\n   */\n  static DataType Float(int bits, int lanes = 1) { return DataType(kDLFloat, bits, lanes); }\n  /*!\n   * \\brief Construct an bfloat type.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes\n   * \\return The constructed data type.\n   */\n  static DataType BFloat(int bits, int lanes = 1) { return DataType(kDLBfloat, bits, lanes); }\n  /*!\n   * \\brief Construct a bool type.\n   * \\param lanes The number of lanes\n   * \\return The constructed data type.\n   */\n  static DataType Bool(int lanes = 1) { return DataType::UInt(1, lanes); }\n  /*!\n   * \\brief Construct a handle type.\n   * \\param bits The number of bits in the type.\n   * \\param lanes The number of lanes\n   * \\return The constructed data type.\n   */\n  static DataType Handle(int bits = 64, int lanes = 1) { return DataType(kHandle, bits, lanes); }\n  /*!\n   * \\brief Construct a Void type.\n   * \\return The constructed data type.\n   */\n  static DataType Void() { return DataType(kHandle, 0, 0); }\n  /*!\n   * \\brief Get the corresponding type of TVMShapeIndex.\n   * \\return The type of TVM shape index.\n   */\n  static DataType ShapeIndex() {\n    if (std::is_signed<tvm_index_t>::value) {\n      return DataType::Int(sizeof(tvm_index_t) * 8);\n    } else {\n      return DataType::UInt(sizeof(tvm_index_t) * 8);\n    }\n  }\n\n private:\n  DLDataType data_;\n};\n\n/*!\n * \\brief Get the number of bytes needed in a vector.\n * \\param dtype The data type.\n * \\return Number of bytes needed.\n */\ninline int GetVectorBytes(DataType dtype) {\n  int data_bits = dtype.bits() * dtype.lanes();\n  // allow bool to exist\n  if (dtype == DataType::Bool() || dtype == DataType::Int(4) || dtype == DataType::UInt(4) ||\n      dtype == DataType::Int(1)) {\n    return 1;\n  }\n  ICHECK_EQ(data_bits % 8, 0U) << \"Need to load/store by multiple of bytes\";\n  return data_bits / 8;\n}\n\n/*!\n * \\brief Check whether type matches the given spec.\n * \\param t The type\n * \\param code The type code.\n * \\param bits The number of bits to be matched.\n * \\param lanes The number of lanes in the type.\n */\ninline bool TypeMatch(DLDataType t, int code, int bits, int lanes = 1) {\n  return t.code == code && t.bits == bits && t.lanes == lanes;\n}\n/*!\n * \\brief Check whether two types are equal .\n * \\param lhs The left operand.\n * \\param rhs The right operand.\n */\ninline bool TypeEqual(DLDataType lhs, DLDataType rhs) {\n  return lhs.code == rhs.code && lhs.bits == rhs.bits && lhs.lanes == rhs.lanes;\n}\n\n/*!\n * \\brief Runtime utility for getting custom type name from code\n * \\param type_code Custom type code\n * \\return Custom type name\n */\nTVM_DLL std::string GetCustomTypeName(uint8_t type_code);\n\n/*!\n * \\brief Runtime utility for checking whether custom type is registered\n * \\param type_code Custom type code\n * \\return Bool representing whether type is registered\n */\nTVM_DLL bool GetCustomTypeRegistered(uint8_t type_code);\n\n/*!\n * \\brief Runtime utility for parsing string of the form \"custom[<typename>]\"\n * \\param s String to parse\n * \\param scan pointer to parsing pointer, which is scanning across s\n * \\return type code of custom type parsed\n */\nTVM_DLL uint8_t ParseCustomDatatype(const std::string& s, const char** scan);\n\n/*!\n * \\brief Convert type code to its name\n * \\param type_code The type code .\n * \\return The name of type code.\n */\ninline const char* DLDataTypeCode2Str(DLDataTypeCode type_code);\n\n/*!\n * \\brief convert a string to TVM type.\n * \\param s The string to be converted.\n * \\return The corresponding tvm type.\n */\ninline DLDataType String2DLDataType(std::string s);\n\n/*!\n * \\brief convert a TVM type to string.\n * \\param t The type to be converted.\n * \\return The corresponding tvm type in string.\n */\ninline std::string DLDataType2String(DLDataType t);\n\n// implementation details\ninline const char* DLDataTypeCode2Str(DLDataTypeCode type_code) {\n  switch (static_cast<int>(type_code)) {\n    case kDLInt:\n      return \"int\";\n    case kDLUInt:\n      return \"uint\";\n    case kDLFloat:\n      return \"float\";\n    case DataType::kHandle:\n      return \"handle\";\n    case kDLBfloat:\n      return \"bfloat\";\n    default:\n      LOG(FATAL) << \"unknown type_code=\" << static_cast<int>(type_code);\n      return \"\";\n  }\n}\n\ninline std::ostream& operator<<(std::ostream& os, DLDataType t) {  // NOLINT(*)\n  if (t.bits == 1 && t.lanes == 1 && t.code == kDLUInt) {\n    os << \"bool\";\n    return os;\n  }\n  if (DataType(t).is_void()) {\n    return os << \"void\";\n  }\n  if (t.code < DataType::kCustomBegin) {\n    os << DLDataTypeCode2Str(static_cast<DLDataTypeCode>(t.code));\n  } else {\n    os << \"custom[\" << GetCustomTypeName(t.code) << \"]\";\n  }\n  if (t.code == kTVMOpaqueHandle) return os;\n  os << static_cast<int>(t.bits);\n  if (t.lanes != 1) {\n    os << 'x' << static_cast<int>(t.lanes);\n  }\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const DataType& dtype) {  // NOLINT(*)\n  return os << dtype.operator DLDataType();\n}\n\ninline std::string DLDataType2String(DLDataType t) {\n  if (t.bits == 0) return \"\";\n  std::ostringstream os;\n  os << t;\n  return os.str();\n}\n\ninline DLDataType String2DLDataType(std::string s) {\n  DLDataType t;\n  // handle void type\n  if (s.length() == 0) {\n    t = DataType::Void();\n    return t;\n  }\n  t.bits = 32;\n  t.lanes = 1;\n  const char* scan;\n  if (s.substr(0, 3) == \"int\") {\n    t.code = kDLInt;\n    scan = s.c_str() + 3;\n  } else if (s.substr(0, 4) == \"uint\") {\n    t.code = kDLUInt;\n    scan = s.c_str() + 4;\n  } else if (s.substr(0, 5) == \"float\") {\n    t.code = kDLFloat;\n    scan = s.c_str() + 5;\n  } else if (s.substr(0, 6) == \"handle\") {\n    t.code = kTVMOpaqueHandle;\n    t.bits = 64;  // handle uses 64 bit by default.\n    scan = s.c_str() + 6;\n  } else if (s == \"bool\") {\n    t.code = kDLUInt;\n    t.bits = 1;\n    t.lanes = 1;\n    return t;\n  } else if (s.substr(0, 6) == \"bfloat\") {\n    t.code = DataType::kBFloat;\n    scan = s.c_str() + 6;\n  } else if (s.substr(0, 6) == \"custom\") {\n    t.code = ParseCustomDatatype(s, &scan);\n  } else {\n    scan = s.c_str();\n    LOG(FATAL) << \"unknown type \" << s;\n  }\n  char* xdelim;  // emulate sscanf(\"%ux%u\", bits, lanes)\n  uint8_t bits = static_cast<uint8_t>(strtoul(scan, &xdelim, 10));\n  if (bits != 0) t.bits = bits;\n  char* endpt = xdelim;\n  if (*xdelim == 'x') {\n    t.lanes = static_cast<uint16_t>(strtoul(xdelim + 1, &endpt, 10));\n  }\n  ICHECK(endpt == s.c_str() + s.length()) << \"unknown type \" << s;\n  return t;\n}\n\n}  // namespace runtime\n\nusing DataType = runtime::DataType;\n\n}  // namespace tvm\n\nnamespace std {\ntemplate <>\nstruct hash<tvm::DataType> {\n  inline int cantor_pairing_function(int a, int b) const { return (a + b) * (a + b + 1) / 2 + b; }\n  std::size_t operator()(tvm::DataType const& dtype) const {\n    int a = dtype.code();\n    int b = dtype.bits();\n    int c = dtype.lanes();\n    int d = cantor_pairing_function(a, b);\n    return cantor_pairing_function(c, d);\n  }\n};\n}  // namespace std\n\n#endif  //  TVM_RUNTIME_DATA_TYPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/debug.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/debug.h\n * \\brief Helpers for debugging at runtime.\n */\n#ifndef TVM_RUNTIME_DEBUG_H_\n#define TVM_RUNTIME_DEBUG_H_\n\n#include <tvm/runtime/container/adt.h>\n#include <tvm/runtime/ndarray.h>\n\n#include <ostream>\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Helpers to describe runtime objects in human-friendly form. For \\p nd_arrays we show their\n * shapes and dtypes, but also their contents if 'small' and on the \\p host_device (mostly so that\n * we can see dynamic shapes as they are computed). For \\p adts we show the ADT fields. For\n * \\p objects we dispatch to one of the above as appropriate.\n */\nvoid AppendNDArray(std::ostream& os, const NDArray& nd_array, const DLDevice& host_device,\n                   bool show_content = true);\nvoid AppendADT(std::ostream& os, const ADT& adt, const DLDevice& host_device,\n               bool show_content = true);\nvoid AppendRuntimeObject(std::ostream& os, const ObjectRef& object, const DLDevice& host_device,\n                         bool show_content = true);\nstd::string RuntimeObject2String(const ObjectRef& object, const DLDevice& host_device,\n                                 bool show_content = true);\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_DEBUG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/device_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/device_api.h\n * \\brief Abstract device memory management API\n */\n#ifndef TVM_RUNTIME_DEVICE_API_H_\n#define TVM_RUNTIME_DEVICE_API_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief the query type into GetAttr\n */\nenum DeviceAttrKind : int {\n  kExist = 0,\n  kMaxThreadsPerBlock = 1,\n  kWarpSize = 2,\n  kMaxSharedMemoryPerBlock = 3,\n  kComputeVersion = 4,\n  kDeviceName = 5,\n  kMaxClockRate = 6,\n  kMultiProcessorCount = 7,\n  kMaxThreadDimensions = 8,\n  kMaxRegistersPerBlock = 9,\n  kGcnArch = 10,\n  kApiVersion = 11,\n  kDriverVersion = 12\n};\n\n/*! \\brief Number of bytes each allocation must align to */\nconstexpr int kAllocAlignment = 64;\n\n/*! \\brief Number of bytes each allocation must align to in temporary allocation */\nconstexpr int kTempAllocaAlignment = 64;\n\n/*! \\brief Maximum size that can be allocated on stack */\nconstexpr int kMaxStackAlloca = 1024;\n\n/*! \\brief Number of bytes each allocation must align to by default in the workspace buffer to\n * service intermediate tensors */\nconstexpr int kDefaultWorkspaceAlignment = 1;\n\n/*!\n *  \\brief TVM Runtime Device API, abstracts the device\n *  specific interface for memory management.\n */\nclass TVM_DLL DeviceAPI {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~DeviceAPI() {}\n  /*!\n   * \\brief Set the environment device id to device\n   * \\param dev The device to be set.\n   */\n  virtual void SetDevice(Device dev) = 0;\n  /*!\n   * \\brief Get attribute of specified device.\n   * \\param dev The device device\n   * \\param kind The result kind\n   * \\param rv The return value.\n   * \\sa DeviceAttrKind\n   */\n  virtual void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) = 0;\n\n  /*!\n   * \\brief Query the device for specified properties.\n   *\n   * This is used to expand \"-from_device=N\" in the target string to\n   * all properties that can be determined from that device.\n   */\n  virtual void GetTargetProperty(Device dev, const std::string& property, TVMRetValue* rv) {}\n\n  /*!\n   * \\brief Allocate a data space on device.\n   * \\param dev The device device to perform operation.\n   * \\param nbytes The number of bytes in memory.\n   * \\param alignment The alignment of the memory.\n   * \\param type_hint The type of elements. Only needed by certain backends such\n   * as OpenGL, as nbytes & alignment are sufficient for most backends.\n   * \\return The allocated device pointer.\n   */\n  virtual void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment,\n                               DLDataType type_hint) = 0;\n  /*!\n   * \\brief Allocate a data space on device with memory scope support.\n   * \\param dev The device device to perform operation.\n   * \\param ndim The number of dimension of allocated tensor.\n   * \\param shape The shape of allocated tensor.\n   * \\param dtype The type of elements.\n   * \\param mem_scope The memory scope of allocated tensor.\n   * \\return The allocated device pointer.\n   */\n  virtual void* AllocDataSpace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,\n                               Optional<String> mem_scope = NullOpt);\n  /*!\n   * \\brief Free a data space on device.\n   * \\param dev The device device to perform operation.\n   * \\param ptr The data space.\n   */\n  virtual void FreeDataSpace(Device dev, void* ptr) = 0;\n  /*!\n   * \\brief copy data from one place to another\n   * \\note This API is designed to support special memory with shape dependent layout.\n   *       We pass in DLTensor* with shape information to support these cases.\n   * \\param from The source array.\n   * \\param to The target array.\n   * \\param stream Optional stream object.\n   */\n  virtual void CopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream);\n  /*!\n   * \\brief Create a new stream of execution.\n   *\n   * \\param dev The device of allocation.\n   */\n  virtual TVMStreamHandle CreateStream(Device dev);\n\n  /*!\n   * \\brief Free a stream of execution\n   *\n   * \\param dev The device of the stream\n   * \\param stream The pointer to be freed.\n   */\n  virtual void FreeStream(Device dev, TVMStreamHandle stream);\n\n  /*!\n   * \\brief Synchronize the stream\n   * \\param dev The device to perform operation.\n   * \\param stream The stream to be sync.\n   */\n  virtual void StreamSync(Device dev, TVMStreamHandle stream) = 0;\n  /*!\n   * \\brief Set the stream\n   * \\param dev The device to set stream.\n   * \\param stream The stream to be set.\n   */\n  virtual void SetStream(Device dev, TVMStreamHandle stream) {}\n  /*!\n   * \\brief Synchronize 2 streams of execution.\n   *\n   * An event is created in event_src stream that the second then\n   * stream waits on.  Neither event_src or event_dst need to be of\n   * the same device ID as the device, but they must be of the same\n   * device type.\n   *\n   * \\param dev The device of the streams.\n   * \\param event_src The source stream to synchronize.\n   * \\param event_dst The destination stream to synchronize.\n   */\n  virtual void SyncStreamFromTo(Device dev, TVMStreamHandle event_src, TVMStreamHandle event_dst);\n  /*!\n   * \\brief Allocate temporal workspace for backend execution.\n   *\n   *  \\note We have the following assumption about backend temporal\n   *   workspace allocation, and backend will optimize for such assumption:\n   *\n   *  - Only a few allocation will happen, and space will be released after use.\n   *  - The release order is usually in reverse order of allocate (stack style).\n   *  - Repeative pattern of same allocations over different runs.\n   *  - Workspace should not overlap between different threads(i.e. be threadlocal)\n   *\n   * \\param dev The device of allocation.\n   * \\param nbytes The size to be allocated.\n   * \\param type_hint The type of elements. Only needed by certain backends such\n   * as OpenGL, as nbytes is sufficient for most backends.\n   */\n  virtual void* AllocWorkspace(Device dev, size_t nbytes, DLDataType type_hint = {});\n  /*!\n   * \\brief Free temporal workspace in backend execution.\n   *\n   * \\param dev The device of allocation.\n   * \\param ptr The pointer to be freed.\n   */\n  virtual void FreeWorkspace(Device dev, void* ptr);\n\n  /*!\n   * \\brief Get device API based on device.\n   * \\param dev The device\n   * \\param allow_missing Whether allow missing\n   * \\return The corresponding device API.\n   */\n  static DeviceAPI* Get(Device dev, bool allow_missing = false);\n\n  /*!\n   * \\brief Whether a certian device type requires set device device\n   *        before launching the kernel function.\n   * \\param device_type The device type.\n   */\n  static bool NeedSetDevice(int device_type) {\n    return device_type != kDLCPU && device_type != kDLMicroDev;\n  }\n\n protected:\n  /*!\n   * \\brief copy data from one place to another\n   * \\param from The source array.\n   * \\param from_offset The byte offeset in the from.\n   * \\param to The target array.\n   * \\param to_offset The byte offset in the to.\n   * \\param num_bytes The size of the memory in bytes\n   * \\param dev_from The source device\n   * \\param dev_to The target device\n   * \\param type_hint The type of elements, only neded by certain backends.\n   *                  can be useful for cross device endian converison.\n   * \\param stream Optional stream object.\n   */\n  virtual void CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset,\n                              size_t num_bytes, Device dev_from, Device dev_to,\n                              DLDataType type_hint, TVMStreamHandle stream);\n};\n\n/*! \\brief The device type bigger than this is RPC device */\nconstexpr int kRPCSessMask = 128;\nstatic_assert(kRPCSessMask >= TVMDeviceExtType_End);\n\n/*!\n * \\brief The name of Device API factory.\n * \\param type The device type.\n * \\return the device name.\n */\ninline const char* DeviceName(int type) {\n  switch (type) {\n    case kDLCPU:\n      return \"cpu\";\n    case kDLCUDA:\n      return \"cuda\";\n    case kDLCUDAHost:\n      return \"cuda_host\";\n    case kDLCUDAManaged:\n      return \"cuda_managed\";\n    case kDLOpenCL:\n      return \"opencl\";\n    case kDLSDAccel:\n      return \"sdaccel\";\n    case kDLAOCL:\n      return \"aocl\";\n    case kDLVulkan:\n      return \"vulkan\";\n    case kDLMetal:\n      return \"metal\";\n    case kDLVPI:\n      return \"vpi\";\n    case kDLROCM:\n      return \"rocm\";\n    case kDLROCMHost:\n      return \"rocm_host\";\n    case kDLExtDev:\n      return \"ext_dev\";\n    case kDLOneAPI:\n      return \"oneapi\";\n    case kDLWebGPU:\n      return \"webgpu\";\n    case kDLHexagon:\n      return \"hexagon\";\n    case kOpenGL:\n      return \"opengl\";\n    case kDLMicroDev:\n      return \"microdev\";\n    default:\n      LOG(FATAL) << \"unknown type =\" << type;\n      return \"Unknown\";\n  }\n}\n\n/*!\n * \\brief Return true if a Device is owned by an RPC session.\n */\ninline bool IsRPCSessionDevice(Device dev) { return (dev.device_type / kRPCSessMask) > 0; }\n\n/*!\n * \\brief Return the RPCSessTable index of the RPC Session that owns this device.\n * \\return the table index.\n */\ninline int GetRPCSessionIndex(Device dev) {\n  ICHECK(IsRPCSessionDevice(dev)) << \"GetRPCSessionIndex: dev has no RPC session\";\n  return dev.device_type / kRPCSessMask - 1;\n}\n\n/*!\n * \\brief Remove the RPC session mask from a Device.\n * RPC clients typically do this when encoding a Device for transmission to an RPC remote.\n * On the wire, RPCdevice are expected to be valid on the server without interpretation.\n * \\param dev A Device with non-zero RPC Session mask, valid on the RPC client.\n * \\return A Device without any RPC Session mask, valid on the RPC server.\n */\ninline Device RemoveRPCSessionMask(Device dev) {\n  dev.device_type = static_cast<DLDeviceType>(dev.device_type % kRPCSessMask);\n  return dev;\n}\n\ninline std::ostream& operator<<(std::ostream& os, DLDevice dev) {  // NOLINT(*)\n  if (tvm::runtime::IsRPCSessionDevice(dev)) {\n    os << \"remote[\" << tvm::runtime::GetRPCSessionIndex(dev) << \"]-\";\n    dev = tvm::runtime::RemoveRPCSessionMask(dev);\n  }\n  os << tvm::runtime::DeviceName(static_cast<int>(dev.device_type)) << \"(\" << dev.device_id << \")\";\n  return os;\n}\n\n/*!\n * \\brief Add a RPC session mask to a Device.\n * RPC clients typically do this when decoding a Device received from a RPC remote.\n * \\param dev A Device without any RPC Session mask, valid on the RPC server.\n * \\param session_table_index Numeric index of the RPC session in the session table.\n * \\return A Device with RPC session mask added, valid on the RPC client.\n */\ninline Device AddRPCSessionMask(Device dev, int session_table_index) {\n  CHECK(!IsRPCSessionDevice(dev)) << \"AddRPCSessionMask: dev already non-zero RPCSessionIndex: \"\n                                  << dev;\n  dev.device_type =\n      static_cast<DLDeviceType>(dev.device_type | (kRPCSessMask * (session_table_index + 1)));\n  return dev;\n}\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_DEVICE_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/executor_info.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file executor_info.h\n * \\brief Executor information\n */\n#ifndef TVM_RUNTIME_EXECUTOR_INFO_H_\n#define TVM_RUNTIME_EXECUTOR_INFO_H_\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Value used to indicate the graph executor. */\nstatic constexpr const char* kTvmExecutorGraph = \"graph\";\n\n/*! \\brief Value used to indicate the aot executor. */\nstatic constexpr const char* kTvmExecutorAot = \"aot\";\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_EXECUTOR_INFO_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/hexagon/ops/conv2d.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n\n#include <cassert>\n\n#ifndef TVM_RUNTIME_HEXAGON_OPS_CONV2D_H_\n#define TVM_RUNTIME_HEXAGON_OPS_CONV2D_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\nstatic constexpr auto hexagon_device = DLDevice{static_cast<DLDeviceType>(kDLHexagon), 0};\n\n// Standalone DLTensor: the standalone-ness means that this object owns the shape\n// (as opposed to a DLTensor).\ntemplate <size_t NDIM>\nclass SDLTensor : public DLTensor {\n public:\n  SDLTensor(void* data_ptr, DLDataType data_type, void* data_space, const int64_t* data_dims)\n      : SDLTensor(data_ptr, data_type, data_space) {\n    for (size_t i = 0; i < NDIM; ++i) dims[i] = data_dims[i];\n  }\n\n  SDLTensor(void* data_ptr, DLDataType data_type, void* data_space,\n            std::initializer_list<int64_t> data_dims)\n      : SDLTensor(data_ptr, data_type, data_space, data_dims.begin()) {}\n\n  void* GetDataSpace() const { return data_space; }\n\n private:\n  /**\n   * @brief Construct SDLTensor\n   *\n   * @param data_ptr Either points to the same memory as data_space or an array of pointers to the\n   * start of each chunk of weight. Since weights can be of varying sizes, this array could contain\n   * the pointer to each chunk of memory\n   * @param data_type data type of the elements in Tensor\n   * @param data_space is meant to store the pointer returned from AllocDataSpace and can be freed\n   * by passing it to FreeDataSpace\n   */\n  SDLTensor(void* data_ptr, DLDataType data_type, void* data_space) : data_space(data_space) {\n    data = data_ptr;\n    device = hexagon_device;\n    ndim = NDIM;\n    dtype = data_type;\n    shape = dims;\n    strides = nullptr;\n    byte_offset = 0;\n  }\n\n  void* data_space = nullptr;\n  int64_t dims[NDIM];\n};\n\ninline void* to_ptr(uintptr_t v) { return reinterpret_cast<void*>(v); }\n\ninline uintptr_t to_uint(void* ptr) { return reinterpret_cast<uintptr_t>(ptr); }\n\nconstexpr int xyc_to_sm_16b(int y, int x, int c) {\n  // Map y,x,c coordinates within a block to the offset (in 16-bit elements)\n  // from the beginning of the block in spatial-major layout.\n  // 10-bit spatial mask: yyyxcccccx\n  assert(y >= 0 && x >= 0 && c >= 0);\n  return y << 7 | (x & 2) << 5 | c << 1 | (x & 1);\n}\n\nconstexpr int hwio_to_sm_16b(int width, int y, int x, int i, int o) {\n  // Map y,x,i,o coordinates within a chunk (assuming the origin at the\n  // top-left spatial corner) to the offset (in 16-bit elements) from the\n  // beginning of the chunk in spatial-major layout.\n  // Spatial mask: p..piiiioooooi, where p..p are position bits.\n  assert(width >= 1);\n  assert(y >= 0 && x >= 0 && i >= 0 && o >= 0);\n  int p = y * width + (width - 1 - x);\n  return p << 10 | (i & 0x1e) << 5 | o << 1 | (i & 1);\n}\n\ninline constexpr int round_up(int v, int p2) { return (v + p2 - 1) & -p2; }\n\n// Returns the block address at the given index\n// Assumptions\n// - The data type of tensor is fp16\n// - There is only one batch, and hence n==0\ninline uintptr_t nhwc_at(const DLTensor& a, int n, int y, int x, int c) {\n  if (y < 0 || y >= a.shape[1]) return uintptr_t(0);\n  auto p = static_cast<uintptr_t*>(a.data);\n  assert(n == 0);\n  return p[y * a.shape[2] * a.shape[3] + x * a.shape[3] + c];\n}\n\n// Returns the address of the chunk stored at given index\n// Assumptions\n// - The data type of tensor is fp16\ninline uintptr_t hwio_at(const DLTensor& f, int y, int x, int i, int o) {\n  auto p = static_cast<uintptr_t*>(f.data);\n  return p[y * f.shape[1] * f.shape[2] * f.shape[3] + x * f.shape[2] * f.shape[3] + i * f.shape[3] +\n           o];\n}\n\n/**\n * @brief Function to \"blockize\" the flat input data\n * The term \"blockize\" is used to mention that the data is stored in non-contiguous blocks\n *\n * The input is mapped into the below mentioned layout (notation similar to index map used for\n * transform layout):\n *\n * lambda n, h, w, c: n, h//8, w//4, c//32, AXIS_SEPARATOR, h%8, (w%4)//2, c%32, w%2\n *\n * where AXIS_SEPARATOR represents split up in the physical layout\n *\n * @param out Pre-allocated output memory pointer\n * @param inp_flat Flat input data pointer\n * @param height\n * @param width\n * @param depth\n */\nvoid blockize_hwc_16b(void* out, void* inp_flat, int height, int width, int depth);\n\n/**\n * @brief Convert back from non-contguous layout to a flat layout\n *\n * @param out_flat Pre-allocated output memory pointer\n * @param inp Blockized input data pointer\n * @param height\n * @param width\n * @param depth\n */\nvoid deblockize_hwc_16b(void* out_flat, void* inp, int height, int width, int depth);\n\n/**\n * @brief Convert the layout of weights from flat to \"chunked\". The term chunked is explained below:\n *\n * Weights are packed into the below mentioned layout (notation similar to index map):\n * Since weights cannot be exactly represented into a index map notation, the\n * base split up is mentioned below with a few gotchas\n *\n * lambda h, w, i, o: h//8, w//4, o//32, i//32, h%8, w%4, (i%32)//2, o%32, i%2\n *\n * The gotchas are:\n *  - (w%4) is actually stored in the right to left order, as in 3,2,1,0 instead of 0,1,2,3\n *  - The h%8 and (w%4) dimensions are not padded up, leading to chunks of different sizes\n *    (thereby the name \"chunked\" instead of packed)\n *  - The thinnest chunk of width is stored first. For example, if a kernel is 5x5, the first\n *    chunk along the width has size 1 (representing index 0) and then next one has size 4\n *    representing indices (1,2,3,4)\n *\n * @param out_ptr Base pointer table to be filled with the list of pointers to the first addresses\n * of the \"chunked\" weights\n * @param out_ptr_size The number of chunks\n * @param out Pointer to pre-allocated output memory\n * @param inp Pointer to flat input data\n * @param height\n * @param width\n * @param idepth\n * @param odepth\n */\nvoid chunkify_hwio_16b(void** out_ptr, int out_ptr_size, void* out, void* inp, int height,\n                       int width, int idepth, int odepth);\n\nSDLTensor<4> prepare_nhwc(tvm::runtime::DeviceAPI* device_api, const DLTensor* nhwc_flat,\n                          bool copy_data);\n\nint calculate_num_weight_chunks(int64_t* shape_hwio);\n\nSDLTensor<4> prepare_hwio(tvm::runtime::DeviceAPI* device_api, const DLTensor* hwio_flat,\n                          int num_chunks, void** ptr_table);\n\ntemplate <size_t N>\nvoid release(tvm::runtime::DeviceAPI* device_api, const SDLTensor<N>& tensor) {\n  if (auto* data_space = tensor.GetDataSpace()) {\n    device_api->FreeDataSpace(hexagon_device, data_space);\n  }\n}\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_OPS_CONV2D_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/logging.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/logging.h\n * \\brief logging utilities\n *\n * We define our own CHECK and LOG macros to replace those from dmlc-core.\n * These macros are then injected into dmlc-core via the\n * DMLC_USE_LOGGING_LIBRARY define. dmlc-core will #include this file wherever\n * it needs logging.\n */\n#ifndef TVM_RUNTIME_LOGGING_H_\n#define TVM_RUNTIME_LOGGING_H_\n\n#include <dmlc/common.h>\n#include <dmlc/thread_local.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n/*!\n * \\brief Macro helper to force a function not to be inlined.\n * It is only used in places that we know not inlining is good,\n * e.g. some logging functions.\n */\n#if defined(_MSC_VER)\n#define TVM_NO_INLINE __declspec(noinline)\n#else\n#define TVM_NO_INLINE __attribute__((noinline))\n#endif\n\n/*!\n * \\brief Macro helper to force a function to be inlined.\n * It is only used in places that we know inline is important,\n * e.g. some template expansion cases.\n */\n#ifdef _MSC_VER\n#define TVM_ALWAYS_INLINE __forceinline\n#else\n#define TVM_ALWAYS_INLINE inline __attribute__((always_inline))\n#endif\n\n/*!\n * \\brief Macro helper for exception throwing.\n */\n#define TVM_THROW_EXCEPTION noexcept(false)\n\n/*!\n * \\brief Whether or not enable backtrace logging during a\n *        fatal error.\n *\n * \\note TVM won't depend on LIBBACKTRACE or other exec_info\n *       library when this option is disabled.\n */\n#ifndef TVM_LOG_STACK_TRACE\n#define TVM_LOG_STACK_TRACE 1\n#endif\n\n/*!\n * \\brief Whether or not use libbacktrace library\n *        for getting backtrace information\n */\n#ifndef TVM_USE_LIBBACKTRACE\n#define TVM_USE_LIBBACKTRACE 0\n#endif\n\n/*!\n * \\brief Whether or not customize the logging output.\n *  If log customize is enabled, the user must implement\n *  tvm::runtime::detail::LogFatalImpl and tvm::runtime::detail::LogMessageImpl.\n */\n#ifndef TVM_LOG_CUSTOMIZE\n#define TVM_LOG_CUSTOMIZE 0\n#endif\n\n// a technique that enables overriding macro names on the number of parameters. This is used\n// to define other macros below\n#define GET_MACRO(_1, _2, _3, _4, _5, NAME, ...) NAME\n\n/*!\n * \\brief COND_X calls COND_X_N where N is the number of parameters passed to COND_X\n * X can be any of CHECK_GE, CHECK_EQ, CHECK, or LOG COND_X (but not COND_X_N)\n * are supposed to be used outside this file.\n * The first parameter of COND_X (and therefore, COND_X_N), which we call 'quit_on_assert',\n * is a boolean. The rest of the parameters of COND_X is the same as the parameters of X.\n * quit_on_assert determines the overall behavior of COND_X. If it's true COND_X\n * quits the program on assertion failure. If it's false, then it moves on and somehow reports\n * the assertion failure back to the macro caller in an appropriate manner (e.g, 'return false'\n * in a function, or 'continue' or 'break' in a loop)\n * The default behavior when quit_on_assertion is false, is to 'return false'. If this is not\n * desirable, the macro caller can pass one more last parameter to COND_X to tell COND_X what\n * to do when when quit_on_assertion is false and the assertion fails.\n *\n * Rationale: These macros were designed to implement functions that have two behaviors\n * in a concise way. Those behaviors are quitting on assertion failures, or trying to\n * move on from assertion failures. Note that these macros hide lots of control flow in them,\n * and therefore, makes the logic of the whole code slightly harder to understand. However,\n * in pieces of code that use these macros frequently, it will significantly shorten the\n * amount of code needed to be read, and we won't need to clutter the main logic of the\n * function by repetitive control flow structure. The first problem\n * mentioned will be improved over time as the developer gets used to the macro.\n *\n * Here is an example of how to use it\n * \\code\n * bool f(..., bool quit_on_assertion) {\n *   int a = 0, b = 0;\n *   ...\n *   a = ...\n *   b = ...\n *   // if quit_on_assertion is true, if a==b, continue, otherwise quit.\n *   // if quit_on_assertion is false, if a==b, continue, otherwise 'return false'\n *   //   (default behaviour)\n *   COND_CHECK_EQ(quit_on_assertion, a, b) << \"some error message when  quiting\"\n *   ...\n *   for (int i = 0; i < N; i++) {\n *     a = ...\n *     b = ...\n *     // if quit_on_assertion is true, if a==b, continue, otherwise quit.\n *     // if quit_on_assertion is false, if a==b, continue, otherwise 'break'\n *     //   (non-default behaviour, therefore, has to be explicitly specified)\n *     COND_CHECK_EQ(quit_on_assertion, a, b, break) << \"some error message when  quiting\"\n *   }\n * }\n * \\endcode\n */\n#define COND_CHECK_GE(...) \\\n  GET_MACRO(__VA_ARGS__, COND_CHECK_GE_5, COND_CHECK_GE_4, COND_CHECK_GE_3)(__VA_ARGS__)\n#define COND_CHECK_EQ(...) \\\n  GET_MACRO(__VA_ARGS__, COND_CHECK_EQ_5, COND_CHECK_EQ_4, COND_CHECK_EQ_3)(__VA_ARGS__)\n#define COND_CHECK(...) \\\n  GET_MACRO(__VA_ARGS__, COND_CHECK_5, COND_CHECK_4, COND_CHECK_3, COND_CHECK_2)(__VA_ARGS__)\n#define COND_LOG(...) \\\n  GET_MACRO(__VA_ARGS__, COND_LOG_5, COND_LOG_4, COND_LOG_3, COND_LOG_2)(__VA_ARGS__)\n\n// Not supposed to be used by users directly.\n#define COND_CHECK_OP(quit_on_assert, x, y, what, op) \\\n  if (!quit_on_assert) {                              \\\n    if (!((x)op(y))) what;                            \\\n  } else /* NOLINT(*) */                              \\\n    CHECK_##op(x, y)\n\n#define COND_CHECK_EQ_4(quit_on_assert, x, y, what) COND_CHECK_OP(quit_on_assert, x, y, what, ==)\n#define COND_CHECK_GE_4(quit_on_assert, x, y, what) COND_CHECK_OP(quit_on_assert, x, y, what, >=)\n\n#define COND_CHECK_3(quit_on_assert, x, what) \\\n  if (!quit_on_assert) {                      \\\n    if (!(x)) what;                           \\\n  } else /* NOLINT(*) */                      \\\n    CHECK(x)\n\n#define COND_LOG_3(quit_on_assert, x, what) \\\n  if (!quit_on_assert) {                    \\\n    what;                                   \\\n  } else /* NOLINT(*) */                    \\\n    LOG(x)\n\n#define COND_CHECK_EQ_3(quit_on_assert, x, y) COND_CHECK_EQ_4(quit_on_assert, x, y, return false)\n#define COND_CHECK_GE_3(quit_on_assert, x, y) COND_CHECK_GE_4(quit_on_assert, x, y, return false)\n#define COND_CHECK_2(quit_on_assert, x) COND_CHECK_3(quit_on_assert, x, return false)\n#define COND_LOG_2(quit_on_assert, x) COND_LOG_3(quit_on_assert, x, return false)\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Generate a backtrace when called.\n * \\return A multiline string of the backtrace. There will be either one or two lines per frame.\n */\nTVM_DLL std::string Backtrace();\n\n/*! \\brief Base error type for TVM. Wraps a string message. */\nclass Error : public ::dmlc::Error {  // for backwards compatibility\n public:\n  /*!\n   * \\brief Construct an error.\n   * \\param s The message to be displayed with the error.\n   */\n  explicit Error(const std::string& s) : ::dmlc::Error(s) {}\n};\n\n/*!\n * \\brief Error message already set in frontend env.\n *\n *  This error can be thrown by EnvCheckSignals to indicate\n *  that there is an error set in the frontend environment(e.g.\n *  python interpreter). The TVM FFI should catch this error\n *  and return a proper code tell the frontend caller about\n *  this fact.\n */\nclass EnvErrorAlreadySet : public ::dmlc::Error {\n public:\n  /*!\n   * \\brief Construct an error.\n   * \\param s The message to be displayed with the error.\n   */\n  explicit EnvErrorAlreadySet(const std::string& s) : ::dmlc::Error(s) {}\n};\n\n/*!\n * \\brief Error type for errors from CHECK, ICHECK, and LOG(FATAL). This error\n * contains a backtrace of where it occurred.\n */\nclass InternalError : public Error {\n public:\n  /*! \\brief Construct an error. Not recommended to use directly. Instead use LOG(FATAL).\n   *\n   * \\param file The file where the error occurred.\n   * \\param lineno The line number where the error occurred.\n   * \\param message The error message to display.\n   * \\param time The time at which the error occurred. This should be in local time.\n   * \\param backtrace Backtrace from when the error occurred.\n   */\n  InternalError(std::string file, int lineno, std::string message,\n                std::time_t time = std::time(nullptr), std::string backtrace = Backtrace())\n      : Error(\"\"),\n        file_(file),\n        lineno_(lineno),\n        message_(message),\n        time_(time),\n        backtrace_(backtrace) {\n    std::ostringstream s;\n    // XXX: Do not change this format, otherwise all error handling in python will break (because it\n    // parses the message to reconstruct the error type).\n    // TODO(tkonolige): Convert errors to Objects, so we can avoid the mess of formatting/parsing\n    // error messages correctly.\n    s << \"[\" << std::put_time(std::localtime(&time), \"%H:%M:%S\") << \"] \" << file << \":\" << lineno\n      << \": \" << message << std::endl;\n    if (backtrace.size() > 0) {\n      s << backtrace << std::endl;\n    }\n    full_message_ = s.str();\n  }\n  /*! \\return The file in which the error occurred. */\n  const std::string& file() const { return file_; }\n  /*! \\return The message associated with this error. */\n  const std::string& message() const { return message_; }\n  /*! \\return Formatted error message including file, linenumber, backtrace, and message. */\n  const std::string& full_message() const { return full_message_; }\n  /*! \\return The backtrace from where this error occurred. */\n  const std::string& backtrace() const { return backtrace_; }\n  /*! \\return The time at which this error occurred. */\n  const std::time_t& time() const { return time_; }\n  /*! \\return The line number at which this error occurred. */\n  int lineno() const { return lineno_; }\n  virtual const char* what() const noexcept { return full_message_.c_str(); }\n\n private:\n  std::string file_;\n  int lineno_;\n  std::string message_;\n  std::time_t time_;\n  std::string backtrace_;\n  std::string full_message_;  // holds the full error string\n};\n\n/*! \\brief Internal implementation */\nnamespace detail {\n// Provide support for customized logging.\n#if TVM_LOG_CUSTOMIZE\n/*!\n * \\brief Custom implementations of LogFatal.\n *\n * \\sa TVM_LOG_CUSTOMIZE\n */\n[[noreturn]] TVM_DLL void LogFatalImpl(const std::string& file, int lineno,\n                                       const std::string& message);\n\n/*!\n * \\brief Custom implementations of LogMessage.\n *\n * \\sa TVM_LOG_CUSTOMIZE\n */\nTVM_DLL void LogMessageImpl(const std::string& file, int lineno, int level,\n                            const std::string& message);\n\n/*!\n * \\brief Class to accumulate an error message and throw it. Do not use\n * directly, instead use LOG(FATAL).\n */\nclass LogFatal {\n public:\n  LogFatal(const std::string& file, int lineno) : file_(file), lineno_(lineno) {}\n#ifdef _MSC_VER\n#pragma disagnostic push\n#pragma warning(disable : 4722)\n#endif\n  [[noreturn]] ~LogFatal() TVM_THROW_EXCEPTION { LogFatalImpl(file_, lineno_, stream_.str()); }\n#ifdef _MSC_VER\n#pragma disagnostic pop\n#endif\n  std::ostringstream& stream() { return stream_; }\n\n private:\n  std::ostringstream stream_;\n  std::string file_;\n  int lineno_;\n};\n\n/*!\n * \\brief Class to accumulate an log message. Do not use directly, instead use\n * LOG(INFO), LOG(WARNING), LOG(ERROR).\n */\nclass LogMessage {\n public:\n  LogMessage(const std::string& file, int lineno, int level)\n      : file_(file), lineno_(lineno), level_(level) {}\n  ~LogMessage() { LogMessageImpl(file_, lineno_, level_, stream_.str()); }\n  std::ostringstream& stream() { return stream_; }\n\n private:\n  std::string file_;\n  int lineno_;\n  int level_;\n  std::ostringstream stream_;\n};\n\n#else\n\n/*!\n * \\brief Class to accumulate an error message and throw it. Do not use\n * directly, instead use LOG(FATAL).\n * \\note The `LogFatal` class is designed to be an empty class to reduce stack size usage.\n * To play this trick, we use the thread-local storage to store its internal data.\n */\nclass LogFatal {\n public:\n  TVM_NO_INLINE LogFatal(const char* file, int lineno) { GetEntry().Init(file, lineno); }\n#ifdef _MSC_VER\n#pragma disagnostic push\n#pragma warning(disable : 4722)\n#endif\n  ~LogFatal() TVM_THROW_EXCEPTION { GetEntry().Finalize(); }\n#ifdef _MSC_VER\n#pragma disagnostic pop\n#endif\n  std::ostringstream& stream() { return GetEntry().stream_; }\n\n private:\n  struct Entry {\n    void Init(const char* file, int lineno) {\n      this->stream_.str(\"\");\n      this->file_ = file;\n      this->lineno_ = lineno;\n    }\n    TVM_NO_INLINE dmlc::Error Finalize() { throw InternalError(file_, lineno_, stream_.str()); }\n    std::ostringstream stream_;\n    std::string file_;\n    int lineno_;\n  };\n\n  TVM_DLL TVM_NO_INLINE static Entry& GetEntry();\n};\n\n/*!\n * \\brief Class to accumulate an log message. Do not use directly, instead use\n * LOG(INFO), LOG(WARNING), LOG(ERROR).\n */\nclass LogMessage {\n public:\n  LogMessage(const std::string& file, int lineno, int level) {\n    std::time_t t = std::time(nullptr);\n    stream_ << \"[\" << std::put_time(std::localtime(&t), \"%H:%M:%S\") << \"] \" << file << \":\" << lineno\n            << level_strings_[level];\n  }\n  TVM_NO_INLINE ~LogMessage() { std::cerr << stream_.str() << std::endl; }\n  std::ostringstream& stream() { return stream_; }\n\n private:\n  std::ostringstream stream_;\n  TVM_DLL static const char* level_strings_[];\n};\n\n#endif\n\n// Below is from dmlc-core\n// This class is used to explicitly ignore values in the conditional\n// logging macros.  This avoids compiler warnings like \"value computed\n// is not used\" and \"statement has no effect\".\nclass LogMessageVoidify {\n public:\n  LogMessageVoidify() {}\n  // This has to be an operator with a precedence lower than << but\n  // higher than \"?:\". See its usage.\n  void operator&(std::ostream&) {}\n};\n\n/*! \\brief Captures the state of the \\p TVM_LOG_DEBUG environment flag. */\nclass TvmLogDebugSettings {\n public:\n  /*!\n   * \\brief Parses the \\p TVM_LOG_DEBUG environment flag as per the specification given by\n   * \\p DebugLoggingEnabled and \\p VerboseLoggingEnabled, and caches the result.\n   */\n  inline static const TvmLogDebugSettings& FromFlag() {\n    // Parse and cache the verbosity level map.\n    static const auto* settings =\n        new TvmLogDebugSettings(TvmLogDebugSettings::ParseSpec(std::getenv(\"TVM_LOG_DEBUG\")));\n    return *settings;\n  }\n\n  /*!\n   * \\brief Parses \\p opt_spec as per specification for \\p TVM_LOG_DEBUG given by\n   * \\p DebugLoggingEnabled and \\p VerboseLoggingEnabled. Throws if specification is ill-formed.\n   */\n  static TvmLogDebugSettings ParseSpec(const char* opt_spec);\n\n  /*!\n   * \\brief Implements \\p VerboseLoggingEnabled below w.r.t. the already parsed \\p TVM_LOG_DEBUG\n   * environment variable.\n   */\n  inline bool VerboseEnabled(const char* opt_filename, int level) const {\n    if (opt_filename == nullptr || level < 0 || vlog_level_map_.empty()) {\n      return false;\n    }\n    return VerboseEnabledImpl(opt_filename, level);\n  }\n\n  /*! \\brief Returns true if \\p DLOG statements should be executed. */\n  bool dlog_enabled() const { return dlog_enabled_; }\n\n private:\n  // Slow path for VerboseEnabled.\n  bool VerboseEnabledImpl(const std::string& filename, int level) const;\n\n  /*! \\brief If true, DLOG statements are enabled. */\n  bool dlog_enabled_ = false;\n  /*!\n   * \\brief A map from canonicalized filenames to the maximum VLOG verbosity level for that file.\n   * May also contain the 'wildcard' entry \\p \"DEFAULT\" representing the level for all other files.\n   */\n  std::unordered_map<std::string, int> vlog_level_map_;\n};\n\n/*!\n * \\brief Returns true if a DLOG statement is enabled by the \\p TVM_LOG_DEBUG environment\n * variable. Requires:\n * \\code\n *   TVM_LOG_DEBUG=1\n * \\endcode\n * or a valid setting as described by \\p VerboseLoggingEnabled below.\n */\n// Also from dmlc-core\ninline bool DebugLoggingEnabled() {\n  static int state = 0;\n  if (state == 0) {\n    state = TvmLogDebugSettings::FromFlag().dlog_enabled() ? 1 : -1;\n  }\n  return state == 1;\n}\n\n/*!\n * \\brief Returns true if a VLOG statement in \\p filename is enabled by the \\p TVM_LOG_DEBUG\n * environment variable for logging at verbosity \\p level. Levels should be non-negative.\n *\n * Filenames are canonicalized to be w.r.t. the src/ dir of the TVM tree. (VLOG's should not\n * appear under include/).\n *\n * To enable file \\p relay/foo.cc up to level 2 and \\p ir/bar.cc for level 0 only set:\n * \\code\n * TVM_LOG_DEBUG=\"relay/foo.cc=2,ir/bar.cc=0\"\n * \\endcode\n *\n * To enable all files up to level 3 but disable \\p ir/bar.cc set:\n * \\code\n * TVM_LOG_DEBUG=\"DEFAULT=2,ir/bar.cc=-1\"\n * \\endcode\n *\n * Any of these settings will also enable DLOG statements.\n */\ninline bool VerboseLoggingEnabled(const char* opt_filename, int level) {\n  return TvmLogDebugSettings::FromFlag().VerboseEnabled(opt_filename, level);\n}\n\n/*!\n * \\brief A stack of VLOG context messages.\n *\n * For use by \\p VLOG_CONTEXT macro only.\n */\nclass VLogContext {\n public:\n  void Push(std::stringstream* stream) { context_stack_.push_back(stream); }\n  void Pop() {\n    if (!context_stack_.empty()) {\n      context_stack_.pop_back();\n    }\n  }\n\n  std::string str() const;\n\n private:\n  std::vector<std::stringstream*> context_stack_;\n};\n\n/*! \\brief Thread local \\p VLogContext for tracking a stack of VLOG context messages. */\nusing ThreadLocalVLogContext = dmlc::ThreadLocalStore<VLogContext>;\n\n/*!\n * \\brief A RAII class to push/pos a VLOG context message onto the thread-local stack.\n *\n * For use by \\p VLOG_CONTEXT macro only.\n */\nclass VLogContextEntry {\n public:\n  VLogContextEntry() { ThreadLocalVLogContext::Get()->Push(&sstream_); }\n  ~VLogContextEntry() { ThreadLocalVLogContext::Get()->Pop(); }\n  std::ostream& stream() { return sstream_; }\n\n private:\n  std::stringstream sstream_;\n};\n\nconstexpr const char* kTVM_INTERNAL_ERROR_MESSAGE =\n    \"\\n\"\n    \"---------------------------------------------------------------\\n\"\n    \"An error occurred during the execution of TVM.\\n\"\n    \"For more information, please see: https://tvm.apache.org/docs/errors.html\\n\"\n    \"---------------------------------------------------------------\\n\";\n\ntemplate <typename X, typename Y>\nstd::unique_ptr<std::string> LogCheckFormat(const X& x, const Y& y) {\n  std::ostringstream os;\n  os << \" (\" << x << \" vs. \" << y << \") \";  // CHECK_XX(x, y) requires x and y can be serialized to\n                                            // string. Use CHECK(x OP y) otherwise.\n  return std::make_unique<std::string>(os.str());\n}\n\n// Inline _Pragma in macros does not work reliably on old version of MSVC and\n// GCC. We wrap all comparisons in a function so that we can use #pragma to\n// silence bad comparison warnings.\n#define TVM_CHECK_FUNC(name, op)                                                          \\\n  template <typename X, typename Y>                                                       \\\n  TVM_ALWAYS_INLINE std::unique_ptr<std::string> LogCheck##name(const X& x, const Y& y) { \\\n    if (x op y) return nullptr;                                                           \\\n    return LogCheckFormat(x, y);                                                          \\\n  }                                                                                       \\\n  TVM_ALWAYS_INLINE std::unique_ptr<std::string> LogCheck##name(int x, int y) {           \\\n    return LogCheck##name<int, int>(x, y);                                                \\\n  }\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\nTVM_CHECK_FUNC(_LT, <)\nTVM_CHECK_FUNC(_GT, >)\nTVM_CHECK_FUNC(_LE, <=)\nTVM_CHECK_FUNC(_GE, >=)\nTVM_CHECK_FUNC(_EQ, ==)\nTVM_CHECK_FUNC(_NE, !=)\n#pragma GCC diagnostic pop\n\n}  // namespace detail\n\n#define TVM_LOG_LEVEL_DEBUG 0\n#define TVM_LOG_LEVEL_INFO 1\n#define TVM_LOG_LEVEL_WARNING 2\n#define TVM_LOG_LEVEL_ERROR 3\n#define TVM_LOG_LEVEL_FATAL 4\n#define LOG(level) LOG_##level\n#define LOG_DEBUG \\\n  ::tvm::runtime::detail::LogMessage(__FILE__, __LINE__, TVM_LOG_LEVEL_DEBUG).stream()\n#define LOG_FATAL ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream()\n#define LOG_INFO ::tvm::runtime::detail::LogMessage(__FILE__, __LINE__, TVM_LOG_LEVEL_INFO).stream()\n#define LOG_ERROR \\\n  ::tvm::runtime::detail::LogMessage(__FILE__, __LINE__, TVM_LOG_LEVEL_ERROR).stream()\n#define LOG_WARNING \\\n  ::tvm::runtime::detail::LogMessage(__FILE__, __LINE__, TVM_LOG_LEVEL_WARNING).stream()\n\n#define TVM_CHECK_BINARY_OP(name, op, x, y)                                \\\n  if (auto __tvm__log__err = ::tvm::runtime::detail::LogCheck##name(x, y)) \\\n  ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream()            \\\n      << \"Check failed: \" << #x \" \" #op \" \" #y << *__tvm__log__err << \": \"\n\n#define CHECK(x)                                                \\\n  if (!(x))                                                     \\\n  ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream() \\\n      << \"Check failed: (\" #x << \") is false: \"\n\n#define CHECK_LT(x, y) TVM_CHECK_BINARY_OP(_LT, <, x, y)\n#define CHECK_GT(x, y) TVM_CHECK_BINARY_OP(_GT, >, x, y)\n#define CHECK_LE(x, y) TVM_CHECK_BINARY_OP(_LE, <=, x, y)\n#define CHECK_GE(x, y) TVM_CHECK_BINARY_OP(_GE, >=, x, y)\n#define CHECK_EQ(x, y) TVM_CHECK_BINARY_OP(_EQ, ==, x, y)\n#define CHECK_NE(x, y) TVM_CHECK_BINARY_OP(_NE, !=, x, y)\n#define CHECK_NOTNULL(x)                                                          \\\n  ((x) == nullptr ? ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream() \\\n                        << \"Check not null: \" #x << ' ',                          \\\n   (x) : (x))  // NOLINT(*)\n\n#define LOG_IF(severity, condition) \\\n  !(condition) ? (void)0 : ::tvm::runtime::detail::LogMessageVoidify() & LOG(severity)\n\n#if TVM_LOG_DEBUG\n\n#define LOG_DFATAL LOG_FATAL\n#define DFATAL FATAL\n#define DLOG(severity) LOG_IF(severity, ::tvm::runtime::detail::DebugLoggingEnabled())\n#define DLOG_IF(severity, condition) \\\n  LOG_IF(severity, ::tvm::runtime::detail::DebugLoggingEnabled() && (condition))\n\n/*!\n * \\brief If the \\p TVM_LOG_DEBUG build flag is enabled, push a context message onto an internal\n * stack. All VLOG messages will include this stack in their prefix to help with debugging. E.g.:\n * \\code\n *   VLOG_CONTEXT << \"my context\";\n *   VLOG(1) << \"my log message\";\n * \\endcode\n * Thread safe. No-op with no execution overhead if the \\p TVM_LOG_DEBUG build flag is not enabled.\n */\n#define VLOG_CONTEXT                                    \\\n  ::tvm::runtime::detail::VLogContextEntry vlog_entry_; \\\n  vlog_entry_.stream()\n\n#else\n\n#define LOG_DFATAL LOG_ERROR\n#define DFATAL ERROR\n#define DLOG(severity) true ? (void)0 : ::tvm::runtime::detail::LogMessageVoidify() & LOG(severity)\n#define DLOG_IF(severity, condition) \\\n  (true || !(condition)) ? (void)0 : ::tvm::runtime::detail::LogMessageVoidify() & LOG(severity)\n#define VLOG_CONTEXT true ? (void)0 : ::tvm::runtime::detail::LogMessageVoidify() & LOG(INFO)\n\n#endif\n\n/*!\n * \\brief If the \\p TVM_LOG_DEBUG build flag is enabled, and the containing file has been enabled\n * at \\p level or greater in the \\p TVM_LOG_DEBUG environment variable, then log a message at\n * \\p INFO severity.\n *\n * See \\p VerboseLoggingEnabled for the format of the \\p TVM_LOG_DEBUG environment variable.\n * Thread safe. No-op with no execution overhead if the \\p TVM_LOG_DEBUG build flag is not enabled.\n * No-op with some execution overhead if the \\p TVM_LOG_DEBUG build flag is enabled but the\n * containing file is not enabled.\n */\n#define VLOG(level)                                                               \\\n  DLOG_IF(INFO, ::tvm::runtime::detail::VerboseLoggingEnabled(__FILE__, (level))) \\\n      << ::tvm::runtime::detail::ThreadLocalVLogContext::Get()->str()\n\n#if TVM_LOG_DEBUG\n#define DCHECK(x) CHECK(x)\n#define DCHECK_LT(x, y) CHECK((x) < (y))\n#define DCHECK_GT(x, y) CHECK((x) > (y))\n#define DCHECK_LE(x, y) CHECK((x) <= (y))\n#define DCHECK_GE(x, y) CHECK((x) >= (y))\n#define DCHECK_EQ(x, y) CHECK((x) == (y))\n#define DCHECK_NE(x, y) CHECK((x) != (y))\n#else\n#define DCHECK(x) \\\n  while (false) CHECK(x)\n#define DCHECK_LT(x, y) \\\n  while (false) CHECK((x) < (y))\n#define DCHECK_GT(x, y) \\\n  while (false) CHECK((x) > (y))\n#define DCHECK_LE(x, y) \\\n  while (false) CHECK((x) <= (y))\n#define DCHECK_GE(x, y) \\\n  while (false) CHECK((x) >= (y))\n#define DCHECK_EQ(x, y) \\\n  while (false) CHECK((x) == (y))\n#define DCHECK_NE(x, y) \\\n  while (false) CHECK((x) != (y))\n#endif\n\n#define TVM_ICHECK_INDENT \"  \"\n\n#define ICHECK_BINARY_OP(name, op, x, y)                                   \\\n  if (auto __tvm__log__err = ::tvm::runtime::detail::LogCheck##name(x, y)) \\\n  ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream()            \\\n      << ::tvm::runtime::detail::kTVM_INTERNAL_ERROR_MESSAGE << std::endl  \\\n      << TVM_ICHECK_INDENT << \"Check failed: \" << #x \" \" #op \" \" #y << *__tvm__log__err << \": \"\n\n#define ICHECK(x)                                                                 \\\n  if (!(x))                                                                       \\\n  ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream()                   \\\n      << ::tvm::runtime::detail::kTVM_INTERNAL_ERROR_MESSAGE << TVM_ICHECK_INDENT \\\n      << \"Check failed: (\" #x << \") is false: \"\n\n#define ICHECK_LT(x, y) ICHECK_BINARY_OP(_LT, <, x, y)\n#define ICHECK_GT(x, y) ICHECK_BINARY_OP(_GT, >, x, y)\n#define ICHECK_LE(x, y) ICHECK_BINARY_OP(_LE, <=, x, y)\n#define ICHECK_GE(x, y) ICHECK_BINARY_OP(_GE, >=, x, y)\n#define ICHECK_EQ(x, y) ICHECK_BINARY_OP(_EQ, ==, x, y)\n#define ICHECK_NE(x, y) ICHECK_BINARY_OP(_NE, !=, x, y)\n#define ICHECK_NOTNULL(x)                                                         \\\n  ((x) == nullptr ? ::tvm::runtime::detail::LogFatal(__FILE__, __LINE__).stream() \\\n                        << ::tvm::runtime::detail::kTVM_INTERNAL_ERROR_MESSAGE    \\\n                        << TVM_ICHECK_INDENT << \"Check not null: \" #x << ' ',     \\\n   (x) : (x))  // NOLINT(*)\n\n}  // namespace runtime\n// Re-export error types\nusing runtime::Error;\nusing runtime::InternalError;\n\n}  // namespace tvm\n#endif  // TVM_RUNTIME_LOGGING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/memory.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/runtime/memory.h\n * \\brief Runtime memory management.\n */\n#ifndef TVM_RUNTIME_MEMORY_H_\n#define TVM_RUNTIME_MEMORY_H_\n\n#include <tvm/runtime/object.h>\n\n#include <cstdlib>\n#include <type_traits>\n#include <utility>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief Allocate an object using default allocator.\n * \\param args arguments to the constructor.\n * \\tparam T the node type.\n * \\return The ObjectPtr to the allocated object.\n */\ntemplate <typename T, typename... Args>\ninline ObjectPtr<T> make_object(Args&&... args);\n\n// Detail implementations after this\n//\n// The current design allows swapping the\n// allocator pattern when necessary.\n//\n// Possible future allocator optimizations:\n// - Arena allocator that gives ownership of memory to arena (deleter_= nullptr)\n// - Thread-local object pools: one pool per size and alignment requirement.\n// - Can specialize by type of object to give the specific allocator to each object.\n\n/*!\n * \\brief Base class of object allocators that implements make.\n *  Use curiously recurring template pattern.\n *\n * \\tparam Derived The derived class.\n */\ntemplate <typename Derived>\nclass ObjAllocatorBase {\n public:\n  /*!\n   * \\brief Make a new object using the allocator.\n   * \\tparam T The type to be allocated.\n   * \\tparam Args The constructor signature.\n   * \\param args The arguments.\n   */\n  template <typename T, typename... Args>\n  inline ObjectPtr<T> make_object(Args&&... args) {\n    using Handler = typename Derived::template Handler<T>;\n    static_assert(std::is_base_of<Object, T>::value, \"make can only be used to create Object\");\n    T* ptr = Handler::New(static_cast<Derived*>(this), std::forward<Args>(args)...);\n    ptr->type_index_ = T::RuntimeTypeIndex();\n    ptr->deleter_ = Handler::Deleter();\n    return ObjectPtr<T>(ptr);\n  }\n\n  /*!\n   * \\tparam ArrayType The type to be allocated.\n   * \\tparam ElemType The type of array element.\n   * \\tparam Args The constructor signature.\n   * \\param num_elems The number of array elements.\n   * \\param args The arguments.\n   */\n  template <typename ArrayType, typename ElemType, typename... Args>\n  inline ObjectPtr<ArrayType> make_inplace_array(size_t num_elems, Args&&... args) {\n    using Handler = typename Derived::template ArrayHandler<ArrayType, ElemType>;\n    static_assert(std::is_base_of<Object, ArrayType>::value,\n                  \"make_inplace_array can only be used to create Object\");\n    ArrayType* ptr =\n        Handler::New(static_cast<Derived*>(this), num_elems, std::forward<Args>(args)...);\n    ptr->type_index_ = ArrayType::RuntimeTypeIndex();\n    ptr->deleter_ = Handler::Deleter();\n    return ObjectPtr<ArrayType>(ptr);\n  }\n};\n\n// Simple allocator that uses new/delete.\nclass SimpleObjAllocator : public ObjAllocatorBase<SimpleObjAllocator> {\n public:\n  template <typename T>\n  class Handler {\n   public:\n    using StorageType = typename std::aligned_storage<sizeof(T), alignof(T)>::type;\n\n    template <typename... Args>\n    static T* New(SimpleObjAllocator*, Args&&... args) {\n      // NOTE: the first argument is not needed for SimpleObjAllocator\n      // It is reserved for special allocators that needs to recycle\n      // the object to itself (e.g. in the case of object pool).\n      //\n      // In the case of an object pool, an allocator needs to create\n      // a special chunk memory that hides reference to the allocator\n      // and call allocator's release function in the deleter.\n\n      // NOTE2: Use inplace new to allocate\n      // This is used to get rid of warning when deleting a virtual\n      // class with non-virtual destructor.\n      // We are fine here as we captured the right deleter during construction.\n      // This is also the right way to get storage type for an object pool.\n      StorageType* data = new StorageType();\n      new (data) T(std::forward<Args>(args)...);\n      return reinterpret_cast<T*>(data);\n    }\n\n    static Object::FDeleter Deleter() { return Deleter_; }\n\n   private:\n    static void Deleter_(Object* objptr) {\n      // NOTE: this is important to cast back to T*\n      // because objptr and tptr may not be the same\n      // depending on how sub-class allocates the space.\n      T* tptr = static_cast<T*>(objptr);\n      // It is important to do tptr->T::~T(),\n      // so that we explicitly call the specific destructor\n      // instead of tptr->~T(), which could mean the intention\n      // call a virtual destructor(which may not be available and is not required).\n      tptr->T::~T();\n      delete reinterpret_cast<StorageType*>(tptr);\n    }\n  };\n\n  // Array handler that uses new/delete.\n  template <typename ArrayType, typename ElemType>\n  class ArrayHandler {\n   public:\n    using StorageType = typename std::aligned_storage<sizeof(ArrayType), alignof(ArrayType)>::type;\n    // for now only support elements that aligns with array header.\n    static_assert(alignof(ArrayType) % alignof(ElemType) == 0 &&\n                      sizeof(ArrayType) % alignof(ElemType) == 0,\n                  \"element alignment constraint\");\n\n    template <typename... Args>\n    static ArrayType* New(SimpleObjAllocator*, size_t num_elems, Args&&... args) {\n      // NOTE: the first argument is not needed for ArrayObjAllocator\n      // It is reserved for special allocators that needs to recycle\n      // the object to itself (e.g. in the case of object pool).\n      //\n      // In the case of an object pool, an allocator needs to create\n      // a special chunk memory that hides reference to the allocator\n      // and call allocator's release function in the deleter.\n      // NOTE2: Use inplace new to allocate\n      // This is used to get rid of warning when deleting a virtual\n      // class with non-virtual destructor.\n      // We are fine here as we captured the right deleter during construction.\n      // This is also the right way to get storage type for an object pool.\n      size_t unit = sizeof(StorageType);\n      size_t requested_size = num_elems * sizeof(ElemType) + sizeof(ArrayType);\n      size_t num_storage_slots = (requested_size + unit - 1) / unit;\n      StorageType* data = new StorageType[num_storage_slots];\n      new (data) ArrayType(std::forward<Args>(args)...);\n      return reinterpret_cast<ArrayType*>(data);\n    }\n\n    static Object::FDeleter Deleter() { return Deleter_; }\n\n   private:\n    static void Deleter_(Object* objptr) {\n      // NOTE: this is important to cast back to ArrayType*\n      // because objptr and tptr may not be the same\n      // depending on how sub-class allocates the space.\n      ArrayType* tptr = static_cast<ArrayType*>(objptr);\n      // It is important to do tptr->ArrayType::~ArrayType(),\n      // so that we explicitly call the specific destructor\n      // instead of tptr->~ArrayType(), which could mean the intention\n      // call a virtual destructor(which may not be available and is not required).\n      tptr->ArrayType::~ArrayType();\n      StorageType* p = reinterpret_cast<StorageType*>(tptr);\n      delete[] p;\n    }\n  };\n};\n\ntemplate <typename T, typename... Args>\ninline ObjectPtr<T> make_object(Args&&... args) {\n  return SimpleObjAllocator().make_object<T>(std::forward<Args>(args)...);\n}\n\ntemplate <typename ArrayType, typename ElemType, typename... Args>\ninline ObjectPtr<ArrayType> make_inplace_array_object(size_t num_elems, Args&&... args) {\n  return SimpleObjAllocator().make_inplace_array<ArrayType, ElemType>(num_elems,\n                                                                      std::forward<Args>(args)...);\n}\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_MEMORY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/metadata.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/metadata.h\n * \\brief Defines types which can be used in Metadata.\n */\n#ifndef TVM_RUNTIME_METADATA_H_\n#define TVM_RUNTIME_METADATA_H_\n\n#include <dmlc/memory_io.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/metadata_base.h>\n#include <tvm/runtime/metadata_types.h>\n#include <tvm/runtime/object.h>\n#include <tvm/support/span.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\n// Version number recorded in emitted artifacts for runtime checking.\n#define TVM_METADATA_VERSION 1\n\nnamespace tvm {\nnamespace runtime {\nnamespace metadata {\n/*!\n * \\brief Version of metadata emitted and understood by this compiler/runtime.\n * Should be populated into the `version` field of all TVMMetadata.\n */\nstatic const constexpr int64_t kMetadataVersion = TVM_METADATA_VERSION;\n\nclass Metadata;\nclass TensorInfo;\nclass ConstantInfoMetadata;\n\nclass MetadataNode : public MetadataBaseNode {\n public:\n  explicit MetadataNode(const struct ::TVMMetadata* data) : data_{data} {}\n  static constexpr const char* _type_key = \"metadata.MetadataNode\";\n  const char* get_c_struct_name() const override;\n  inline int64_t version() const { return int64_t(data_->version); }\n  inline int64_t num_inputs() const { return data_->num_inputs; }\n  ArrayAccessor<struct TVMTensorInfo, TensorInfo> inputs();\n  inline int64_t num_outputs() const { return data_->num_outputs; }\n  ArrayAccessor<struct TVMTensorInfo, TensorInfo> outputs();\n  inline int64_t num_workspace_pools() const { return data_->num_workspace_pools; }\n  ArrayAccessor<struct TVMTensorInfo, TensorInfo> workspace_pools();\n  inline ::tvm::runtime::String mod_name() const { return ::tvm::runtime::String(data_->mod_name); }\n  const struct ::TVMMetadata* data() const { return data_; }\n  ArrayAccessor<struct TVMConstantInfo, ConstantInfoMetadata> constant_pools();\n  inline int64_t num_constant_pools() const { return data_->num_constant_pools; }\n  TVM_DECLARE_FINAL_OBJECT_INFO(MetadataNode, MetadataBaseNode);\n\n private:\n  const struct ::TVMMetadata* data_;\n};\n\nclass Metadata : public MetadataBase {\n public:\n  explicit Metadata(const struct ::TVMMetadata* data);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Metadata, MetadataBase, MetadataNode);\n};\n\nclass TensorInfoNode : public MetadataBaseNode {\n public:\n  explicit TensorInfoNode(const struct ::TVMTensorInfo* data) : data_{data} {}\n  static constexpr const char* _type_key = \"metadata.TensorInfoNode\";\n  const char* get_c_struct_name() const override;\n  inline ::tvm::runtime::String name() const { return ::tvm::runtime::String(data_->name); }\n  inline int64_t num_shape() const { return data_->num_shape; }\n  inline ::tvm::support::Span<const int64_t, int64_t> shape() const {\n    return ::tvm::support::Span<const int64_t, int64_t>(data_->shape,\n                                                        data_->shape + data_->num_shape);\n  }\n  inline ::tvm::runtime::DataType dtype() const { return ::tvm::runtime::DataType(data_->dtype); }\n  const struct ::TVMTensorInfo* data() const { return data_; }\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorInfoNode, MetadataBaseNode);\n\n private:\n  const struct ::TVMTensorInfo* data_;\n};\n\nclass TensorInfo : public MetadataBase {\n public:\n  explicit TensorInfo(const struct ::TVMTensorInfo* data);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(TensorInfo, MetadataBase, TensorInfoNode);\n};\n\nclass ConstantInfoMetadataNode : public MetadataBaseNode {\n public:\n  explicit ConstantInfoMetadataNode(const struct ::TVMConstantInfo* data) : data_{data} {}\n  // This name should match TVMConstantInfo after processing\n  static constexpr const char* _type_key = \"metadata.ConstantInfoNode\";\n  const char* get_c_struct_name() const override;\n  inline ::tvm::runtime::String name_hint() const {\n    return ::tvm::runtime::String(data_->name_hint);\n  }\n  inline size_t byte_offset() const { return data_->byte_offset; }\n  inline ::tvm::runtime::NDArray data() const {\n    ::tvm::runtime::NDArray ndarray;\n    if (data_->data_len) {\n      dmlc::MemoryFixedSizeStream bytes(const_cast<void*>(data_->data_bytes), data_->data_len);\n      ndarray.Load(&bytes);\n    }\n    return ndarray;\n  }\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantInfoMetadataNode, MetadataBaseNode);\n\n protected:\n  const struct ::TVMConstantInfo* data_;\n};\n\nclass ConstantInfoMetadata : public MetadataBase {\n public:\n  explicit ConstantInfoMetadata(const struct ::TVMConstantInfo* data);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ConstantInfoMetadata, MetadataBase,\n                                        ConstantInfoMetadataNode);\n};\n\n}  // namespace metadata\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_METADATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/metadata_base.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/metadata_base.h\n * \\brief Defines types which can be used in Metadata.\n */\n#ifndef TVM_RUNTIME_METADATA_BASE_H_\n#define TVM_RUNTIME_METADATA_BASE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/object.h>\n\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace metadata {\n\n/*!\n * \\brief Common base class for all Metadata.\n *\n * This class is used in the visitor classes as a internal check to ensure that verify that all\n * parts of the Metadata struct used in codegen are Metadata objects.\n */\nclass MetadataBaseNode : public ::tvm::runtime::Object {\n public:\n  virtual const char* get_c_struct_name() const = 0;\n\n  static constexpr const char* _type_key = \"metadata.MetadataBaseNode\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MetadataBaseNode, ::tvm::runtime::Object);\n};\n\n/*! \\brief Reference class for the common MetadataBaseNode class. */\nclass MetadataBase : public ::tvm::runtime::ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MetadataBase, ::tvm::runtime::ObjectRef, MetadataBaseNode);\n};\n\ntemplate <typename C, class Ref>\nclass ArrayAccessor;\n\n/*! \\brief An iterator implementation that lazily instantiates the C++ wrapping Metadata class. */\ntemplate <typename C, class Ref>\nclass ArrayIterator {\n public:\n  ArrayIterator(size_t index, const ArrayAccessor<C, Ref>* parent)\n      : index_{index}, parent_{parent} {}\n\n  inline Ref operator*() { return (*parent_)[index_]; }\n\n  inline ArrayIterator<C, Ref>& operator++() {\n    if (index_ < parent_->size()) {\n      index_++;\n    }\n\n    return *this;\n  }\n\n  inline bool operator==(const ArrayIterator<C, Ref>& other) const {\n    return parent_ == other.parent_ && index_ == other.index_;\n  }\n\n  inline bool operator!=(const ArrayIterator<C, Ref>& other) const { return !operator==(other); }\n\n private:\n  size_t index_;\n  const ArrayAccessor<C, Ref>* parent_;\n};\n\n/*! \\brief A span-like class which permits access to Array fields with complex elements.\n * These array fields should be accessed from C++ using the Metadata wrapper classes. This class\n * lazily instantiates those wrappers as they are accessed.\n */\ntemplate <typename C, class Ref>\nclass ArrayAccessor {\n public:\n  using value_type = Ref;\n  using iterator = ArrayIterator<C, Ref>;\n  using const_iterator = iterator;\n\n  template <typename T = typename std::enable_if<std::is_base_of<ObjectRef, Ref>::value>::type>\n  ArrayAccessor(const C* data, size_t num_data) : data_{data}, num_data_{num_data} {}\n\n  inline size_t size() const { return num_data_; }\n\n  inline Ref operator[](size_t index) const {\n    if (index >= num_data_) {\n      throw std::runtime_error(\"Index out of range\");\n    }\n\n    return Ref(&data_[index]);\n  }\n\n  inline ArrayIterator<C, Ref> begin() const { return ArrayIterator<C, Ref>{0, this}; }\n\n  inline ArrayIterator<C, Ref> end() const { return ArrayIterator<C, Ref>{num_data_, this}; }\n\n private:\n  const C* data_;\n  size_t num_data_;\n};\n\n/*! \\brief A specialization of ArrayAccessor for String.\n * This class is needed because the String constructor signature is different from the typical\n * Metadata subclass.\n */\ntemplate <>\nclass ArrayAccessor<const char*, ::tvm::runtime::String> {\n public:\n  using value_type = ::tvm::runtime::String;\n  using iterator = ArrayIterator<const char*, ::tvm::runtime::String>;\n  using const_iterator = iterator;\n\n  ArrayAccessor(const char** data, size_t num_data) : data_{data}, num_data_{num_data} {}\n\n  inline size_t size() const { return num_data_; }\n\n  inline ::tvm::runtime::String operator[](size_t index) const {\n    if (index >= num_data_) {\n      throw std::runtime_error(\"Index out of range\");\n    }\n    return ::tvm::runtime::String(data_[index]);\n  }\n\n  inline ArrayIterator<const char*, ::tvm::runtime::String> begin() const {\n    return ArrayIterator<const char*, ::tvm::runtime::String>{0, this};\n  }\n\n  inline ArrayIterator<const char*, ::tvm::runtime::String> end() const {\n    return ArrayIterator<const char*, ::tvm::runtime::String>{num_data_, this};\n  }\n\n private:\n  const char** data_;\n  size_t num_data_;\n};\n\n/*! \\brief Enumerates the primitive types which can be part of a Metadata instance.\n *\n * These are separate from TIR DataType because TIR does not model structs.\n */\nenum MetadataKind : uint8_t {\n  kUint64 = 0,\n  kInt64 = 1,\n  kBool = 2,\n  kString = 3,\n  kHandle = 4,\n  kMetadata = 5,\n};\n\n/*! \\brief Container for arrays in the metadata.\n *\n * Type information is needed when emitting arrays. This container augments the data field with\n * the necessary typing information.\n */\nclass MetadataArrayNode : public MetadataBaseNode {\n public:\n  MetadataArrayNode(Array<ObjectRef> array, MetadataKind kind, const char* type_key)\n      : array(::std::move(array)), kind{kind}, type_key{type_key} {}\n\n  const char* get_c_struct_name() const final;\n\n  std::string get_element_c_struct_name() const {\n    CHECK(kind == MetadataKind::kMetadata)\n        << \"cannot get struct name for MetadataArray with kind=\" << kind;\n    constexpr int prefix_size = sizeof(\"metadata.\") - 1;\n    constexpr int suffix_size = sizeof(\"Node\") - 1;\n    std::string type_key_str(type_key);\n    return std::string(\"TVM\") +\n           type_key_str.substr(prefix_size, type_key_str.size() - prefix_size - suffix_size);\n  }\n\n  Array<ObjectRef> array;\n\n  /*! \\brief Describes the storage class of the emitted struct member. */\n  MetadataKind kind;\n\n  /*! \\brief When `kind` is Metadata, type_key of the MetadataBaseNode used with this array. */\n  const char* type_key;\n\n  static constexpr const char* _type_key = \"metadata.MetadataArrayNode\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MetadataArrayNode, MetadataBaseNode);\n};\n\n/*! \\brief Reference class for MetadataArray. */\nclass MetadataArray : public MetadataBase {\n public:\n  MetadataArray(Array<ObjectRef> array, MetadataKind kind, const char* struct_name);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MetadataArray, MetadataBase, MetadataArrayNode);\n};\n\n}  // namespace metadata\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_METADATA_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/metadata_types.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file tvm/runtime/metadata_types.h\n * \\brief Defines types which can be used in metadata here which\n * are also shared between C and C++ code bases.\n */\n#ifndef TVM_RUNTIME_METADATA_TYPES_H_\n#define TVM_RUNTIME_METADATA_TYPES_H_\n\n#include <inttypes.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*!\n * \\brief Top-level metadata structure. Holds all other metadata types.\n */\nstruct TVMMetadata {\n  /*! \\brief Version identifier for this metadata. */\n  int64_t version;\n  /*! \\brief Inputs to the AOT run_model function.\n   * The order of the elements is the same as in the arguments to run_model. That is to say,\n   * this array specifies the first `num_inputs` arguments to run_model.\n   */\n  const struct TVMTensorInfo* inputs;\n  /*! \\brief Number of elements in `inputs` array. */\n  int64_t num_inputs;\n  /*! \\brief Outputs of the AOT run_model function.\n   * The order of the elements is the same as in the arguments to run_model. That is to say,\n   * this array specifies the last `num_outputs` arguments to run_model.\n   */\n  const struct TVMTensorInfo* outputs;\n  /*! \\brief Number of elements in `outputs` array. */\n  int64_t num_outputs;\n  /*! \\brief Workspace Memory Pools needed by the AOT main function.\n   * The order of the elements is the same as in the arguments to run_model. That is to say,\n   * this array specifies the last `num_workspace_pools` arguments to run_model.\n   */\n  const struct TVMTensorInfo* workspace_pools;\n  /*! \\brief Number of elements in `workspace_pools` array. */\n  int64_t num_workspace_pools;\n  /*! \\brief Constant pools needed by the AOT main function.\n   */\n  const struct TVMConstantInfo* constant_pools;\n  /*! \\brief Number of elements in `constant_pools` array. */\n  int64_t num_constant_pools;\n  /*! \\brief Name of the model, as passed to tvm.relay.build. */\n  const char* mod_name;\n};\n\n/*!\n * \\brief Describes one tensor argument to `run_model`.\n * NOTE: while TIR allows for other types of arguments, such as scalars, the AOT run_model\n * function does not currently accept these. Therefore it's not possible to express those\n * in this metadata. A future patch may modify this.\n */\nstruct TVMTensorInfo {\n  /*! \\brief Name of the tensor, as specified in the Relay program. */\n  const char* name;\n  /*! \\brief Shape of the tensor. */\n  const int64_t* shape;\n  /*! \\brief Rank of this tensor. */\n  int64_t num_shape;\n  /*! \\brief Data type of one element of this tensor. */\n  DLDataType dtype;\n};\n\n/*!\n * \\brief Describes one constant argument to `run_model`.\n *\n */\nstruct TVMConstantInfo {\n  /*! \\brief Name of the constant */\n  const char* name_hint;\n  /*! \\brief Offset in bytes of the constant */\n  int64_t byte_offset;\n  /*! \\brief length of the data_bytes field */\n  int64_t data_len;\n  /*! \\brief data bytes of serialized NDArray */\n  const void* data_bytes;\n};\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_METADATA_TYPES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/micro/standalone/microtvm_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_H_\n#define TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define TVM_MICRO_RUNTIME_API_API extern \"C\" __attribute__((visibility(\"default\")))\n\nTVM_MICRO_RUNTIME_API_API void* MicroTVMRuntimeCreate(const char* json, size_t json_len,\n                                                      void* module);\n\nTVM_MICRO_RUNTIME_API_API void MicroTVMRuntimeDestroy(void* handle);\n\nTVM_MICRO_RUNTIME_API_API void MicroTVMRuntimeSetInput(void* handle, int index, void* tensor);\n\nTVM_MICRO_RUNTIME_API_API void MicroTVMRuntimeRun(void* handle);\n\nTVM_MICRO_RUNTIME_API_API void MicroTVMRuntimeGetOutput(void* handle, int index, void* tensor);\n\nTVM_MICRO_RUNTIME_API_API void* MicroTVMRuntimeDSOModuleCreate(const char* so, size_t so_len);\n\nTVM_MICRO_RUNTIME_API_API void MicroTVMRuntimeDSOModuleDestroy(void* module);\n\n#undef TVM_MICRO_RUNTIME_API_API\n\n#endif  // TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/module.h\n * \\brief Runtime container of the functions generated by TVM,\n *  This is used to support dynamically link, load and save\n *  functions from different convention under unified API.\n */\n#ifndef TVM_RUNTIME_MODULE_H_\n#define TVM_RUNTIME_MODULE_H_\n\n#include <dmlc/io.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/memory.h>\n#include <tvm/runtime/object.h>\n\n#include <memory>\n#include <mutex>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\nclass ModuleNode;\nclass PackedFunc;\n\n/*!\n * \\brief Module container of TVM.\n */\nclass Module : public ObjectRef {\n public:\n  Module() {}\n  // constructor from container.\n  explicit Module(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief Get packed function from current module by name.\n   *\n   * \\param name The name of the function.\n   * \\param query_imports Whether also query dependency modules.\n   * \\return The result function.\n   *  This function will return PackedFunc(nullptr) if function do not exist.\n   * \\note Implemented in packed_func.cc\n   */\n  inline PackedFunc GetFunction(const std::string& name, bool query_imports = false);\n  // The following functions requires link with runtime.\n  /*!\n   * \\brief Import another module into this module.\n   * \\param other The module to be imported.\n   *\n   * \\note Cyclic dependency is not allowed among modules,\n   *  An error will be thrown when cyclic dependency is detected.\n   */\n  inline void Import(Module other);\n  /*! \\return internal container */\n  inline ModuleNode* operator->();\n  /*! \\return internal container */\n  inline const ModuleNode* operator->() const;\n  /*!\n   * \\brief Load a module from file.\n   * \\param file_name The name of the host function module.\n   * \\param format The format of the file.\n   * \\note This function won't load the import relationship.\n   *  Re-create import relationship by calling Import.\n   */\n  TVM_DLL static Module LoadFromFile(const std::string& file_name, const std::string& format = \"\");\n  // refer to the corresponding container.\n  using ContainerType = ModuleNode;\n  friend class ModuleNode;\n};\n\n/*!\n * \\brief Base container of module.\n *\n * Please subclass ModuleNode to create a specific runtime module.\n *\n * \\code\n *\n *  class MyModuleNode : public ModuleNode {\n *   public:\n *    // implement the interface\n *  };\n *\n *  // use make_object to create a specific\n *  // instace of MyModuleNode.\n *  Module CreateMyModule() {\n *    ObjectPtr<MyModuleNode> n =\n *      tvm::runtime::make_object<MyModuleNode>();\n *    return Module(n);\n *  }\n *\n * \\endcode\n */\nclass TVM_DLL ModuleNode : public Object {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~ModuleNode() = default;\n  /*!\n   * \\return The per module type key.\n   * \\note This key is used to for serializing custom modules.\n   */\n  virtual const char* type_key() const = 0;\n  /*!\n   * \\brief Get a PackedFunc from module.\n   *\n   *  The PackedFunc may not be fully initialized,\n   *  there might still be first time running overhead when\n   *  executing the function on certain devices.\n   *  For benchmarking, use prepare to eliminate\n   *\n   * \\param name the name of the function.\n   * \\param sptr_to_self The ObjectPtr that points to this module node.\n   *\n   * \\return PackedFunc(nullptr) when it is not available.\n   *\n   * \\note The function will always remain valid.\n   *   If the function need resource from the module(e.g. late linking),\n   *   it should capture sptr_to_self.\n   */\n  virtual PackedFunc GetFunction(const std::string& name,\n                                 const ObjectPtr<Object>& sptr_to_self) = 0;\n  /*!\n   * \\brief Save the module to file.\n   * \\param file_name The file to be saved to.\n   * \\param format The format of the file.\n   */\n  virtual void SaveToFile(const std::string& file_name, const std::string& format);\n  /*!\n   * \\brief Save the module to binary stream.\n   * \\param stream The binary stream to save to.\n   * \\note It is recommended to implement this for device modules,\n   *   but not necessarily host modules.\n   *   We can use this to do AOT loading of bundled device functions.\n   */\n  virtual void SaveToBinary(dmlc::Stream* stream);\n  /*!\n   * \\brief Get the source code of module, when available.\n   * \\param format Format of the source code, can be empty by default.\n   * \\return Possible source code when available.\n   */\n  virtual std::string GetSource(const std::string& format = \"\");\n  /*!\n   * \\brief Get the format of the module, when available.\n   * \\return Possible format when available.\n   */\n  virtual std::string GetFormat();\n  /*!\n   * \\brief Get packed function from current module by name.\n   *\n   * \\param name The name of the function.\n   * \\param query_imports Whether also query dependency modules.\n   * \\return The result function.\n   *  This function will return PackedFunc(nullptr) if function do not exist.\n   * \\note Implemented in packed_func.cc\n   */\n  PackedFunc GetFunction(const std::string& name, bool query_imports = false);\n  /*!\n   * \\brief Import another module into this module.\n   * \\param other The module to be imported.\n   *\n   * \\note Cyclic dependency is not allowed among modules,\n   *  An error will be thrown when cyclic dependency is detected.\n   */\n  void Import(Module other);\n  /*!\n   * \\brief Get a function from current environment\n   *  The environment includes all the imports as well as Global functions.\n   *\n   * \\param name name of the function.\n   * \\return The corresponding function.\n   */\n  const PackedFunc* GetFuncFromEnv(const std::string& name);\n  /*! \\return The module it imports from */\n  const std::vector<Module>& imports() const { return imports_; }\n\n  /*!\n   * \\brief Returns true if this module is 'DSO exportable'.\n   *\n   * A DSO exportable module (eg a CSourceModuleNode of type_key 'c') can be incorporated into the\n   * final runtime artifact (ie shared library) by compilation and/or linking using the external\n   * compiler (llvm, nvcc, etc). DSO exportable modules must implement SaveToFile.\n   *\n   * By contrast, non-DSO exportable modules (eg CUDAModuleNode of type_key 'cuda') typically must\n   * be incorporated into the final runtime artifact by being serialized as data into the\n   * artifact, then deserialized at runtime. Non-DSO exportable modules must implement SaveToBinary,\n   * and have a matching deserializer registered as 'runtime.module.loadbinary_<type_key>'.\n   *\n   * The default implementation returns false.\n   */\n  virtual bool IsDSOExportable() const;\n\n  /*!\n   * \\brief Returns true if this module has a definition for a function of \\p name. If\n   * \\p query_imports is true, also search in any imported modules.\n   *\n   * Note that even if this function returns true the corresponding \\p GetFunction result may be\n   * nullptr if the function is not yet callable without further compilation.\n   *\n   * The default implementation just checkis if \\p GetFunction is non-null.\n   */\n  virtual bool ImplementsFunction(const String& name, bool query_imports = false);\n\n  // integration with the existing components.\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeModule;\n  static constexpr const char* _type_key = \"runtime.Module\";\n  // NOTE: ModuleNode can still be sub-classed\n  //\n  TVM_DECLARE_FINAL_OBJECT_INFO(ModuleNode, Object);\n\n protected:\n  friend class Module;\n  friend class ModuleInternal;\n  /*! \\brief The modules this module depend on */\n  std::vector<Module> imports_;\n\n private:\n  /*! \\brief Cache used by GetImport */\n  std::unordered_map<std::string, std::shared_ptr<PackedFunc>> import_cache_;\n  std::mutex mutex_;\n};\n\n/*!\n * \\brief Check if runtime module is enabled for target.\n * \\param target The target module name.\n * \\return Whether runtime is enabled.\n */\nTVM_DLL bool RuntimeEnabled(const std::string& target);\n\n/*! \\brief namespace for constant symbols */\nnamespace symbol {\n/*! \\brief A PackedFunc that retrieves exported metadata. */\nconstexpr const char* tvm_get_c_metadata = \"get_c_metadata\";\n/*! \\brief Global variable to store module context. */\nconstexpr const char* tvm_module_ctx = \"__tvm_module_ctx\";\n/*! \\brief Global variable to store device module blob */\nconstexpr const char* tvm_dev_mblob = \"__tvm_dev_mblob\";\n/*! \\brief Number of bytes of device module blob. */\nconstexpr const char* tvm_dev_mblob_nbytes = \"__tvm_dev_mblob_nbytes\";\n/*! \\brief global function to set device */\nconstexpr const char* tvm_set_device = \"__tvm_set_device\";\n/*! \\brief Auxiliary counter to global barrier. */\nconstexpr const char* tvm_global_barrier_state = \"__tvm_global_barrier_state\";\n/*! \\brief Prepare the global barrier before kernels that uses global barrier. */\nconstexpr const char* tvm_prepare_global_barrier = \"__tvm_prepare_global_barrier\";\n/*! \\brief Placeholder for the module's entry function. */\nconstexpr const char* tvm_module_main = \"__tvm_main__\";\n/*! \\brief Prefix for parameter symbols emitted into the main program. */\nconstexpr const char* tvm_param_prefix = \"__tvm_param__\";\n/*! \\brief A PackedFunc that looks up linked parameters by storage_id. */\nconstexpr const char* tvm_lookup_linked_param = \"_lookup_linked_param\";\n/*! \\brief Model entrypoint generated as an interface to the AOT function outside of TIR */\nconstexpr const char* tvm_entrypoint_suffix = \"run\";\n}  // namespace symbol\n\n// implementations of inline functions.\n\ninline void Module::Import(Module other) { return (*this)->Import(other); }\n\ninline ModuleNode* Module::operator->() { return static_cast<ModuleNode*>(get_mutable()); }\n\ninline const ModuleNode* Module::operator->() const {\n  return static_cast<const ModuleNode*>(get());\n}\n\ninline std::ostream& operator<<(std::ostream& out, const Module& module) {\n  out << \"Module(type_key= \";\n  out << module->type_key();\n  out << \")\";\n\n  return out;\n}\n\n}  // namespace runtime\n}  // namespace tvm\n\n#include <tvm/runtime/packed_func.h>  // NOLINT(*)\n#endif                                // TVM_RUNTIME_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/name_transforms.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/name_transforms.h\n * \\brief Transformations which are applied on names to generate appropriately named.\n *  These functions are used in both Runtime and Backend.\n */\n#ifndef TVM_RUNTIME_NAME_TRANSFORMS_H_\n#define TVM_RUNTIME_NAME_TRANSFORMS_H_\n\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Sanitize name for output into compiler artifacts\n * \\param name Original name\n * \\return Sanitized name\n */\nstd::string SanitizeName(const std::string& name);\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_NAME_TRANSFORMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/ndarray.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/ndarray.h\n * \\brief A device-independent managed NDArray abstraction.\n */\n#ifndef TVM_RUNTIME_NDARRAY_H_\n#define TVM_RUNTIME_NDARRAY_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/shape_tuple.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/serializer.h>\n\n#include <atomic>\n#include <functional>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\n// alias DLDevice\nusing Device = DLDevice;\n\n// A 'null' device type, does not correspond to any DLDeviceType enum.\n// TODO(mbs): This is to help us as we transition away from representing the 'homogenous' case\n// as a singleton target map indexed by the invalid DLDeviceType '0'.\nconstexpr DLDeviceType kNullDeviceType = static_cast<DLDeviceType>(0);\n\n// An 'invalid' device type, does not correspond to any DLDeviceType enum.\nconstexpr DLDeviceType kInvalidDeviceType = static_cast<DLDeviceType>(-1);\n\nnamespace runtime {\n\n/*!\n * \\brief Managed NDArray.\n *  The array is backed by reference counted blocks.\n */\nclass NDArray : public ObjectRef {\n public:\n  /*! \\brief ContainerBase used to back the TVMArrayHandle */\n  class ContainerBase;\n  /*! \\brief NDArray internal container type */\n  class Container;\n  /*! \\brief Container type for Object system. */\n  using ContainerType = Container;\n  /*! \\brief default constructor */\n  NDArray() {}\n  /*!\n   * \\brief constructor.\n   * \\param data ObjectPtr to the data container.\n   */\n  explicit NDArray(ObjectPtr<Object> data) : ObjectRef(data) {}\n\n  /*! \\brief reset the content of NDArray to be nullptr */\n  inline void reset();\n  /*!\n   * \\return the reference counter\n   * \\note this number is approximate in multi-threaded setting.\n   */\n  inline int use_count() const;\n  /*! \\return Pointer to content of DLTensor */\n  inline const DLTensor* operator->() const;\n  /*! \\return Whether the tensor is contiguous */\n  inline bool IsContiguous() const;\n  /*!\n   * \\brief Copy data content from another array.\n   * \\param other The source array to be copied from.\n   * \\note The copy may happen asynchronously if it involves a GPU context.\n   *       TVMSynchronize is necessary.\n   */\n  inline void CopyFrom(const DLTensor* other);\n  inline void CopyFrom(const NDArray& other);\n  /*!\n   * \\brief Copy data content from a byte buffer.\n   * \\param data The source bytes to be copied from.\n   * \\param nbytes The size of the buffer in bytes\n   *        Must be equal to the size of the NDArray.\n   * \\note The copy always triggers a TVMSynchronize.\n   */\n  TVM_DLL void CopyFromBytes(const void* data, size_t nbytes);\n  /*!\n   * \\brief Copy data content into another array.\n   * \\param other The source array to be copied from.\n   * \\note The copy may happen asynchronously if it involves a GPU context.\n   *       TVMSynchronize is necessary.\n   */\n  inline void CopyTo(DLTensor* other) const;\n  inline void CopyTo(const NDArray& other) const;\n  /*!\n   * \\brief Copy data content into another array.\n   * \\param data The source bytes to be copied from.\n   * \\param nbytes The size of the data buffer.\n   *        Must be equal to the size of the NDArray.\n   * \\note The copy always triggers a TVMSynchronize.\n   */\n  TVM_DLL void CopyToBytes(void* data, size_t nbytes) const;\n  /*!\n   * \\brief Copy the data to another device.\n   * \\param dev The target device.\n   * \\return The array under another device.\n   */\n  inline NDArray CopyTo(const Device& dev) const;\n  /*!\n   * \\brief Load NDArray from stream\n   * \\param stream The input data stream\n   * \\return Whether load is successful\n   */\n  inline bool Load(dmlc::Stream* stream);\n  /*!\n   * \\brief Save NDArray to stream\n   * \\param stream The output data stream\n   */\n  inline void Save(dmlc::Stream* stream) const;\n  /*!\n   * \\brief Create a NDArray that shares the data memory with the current one.\n   * \\param shape The shape of the new array.\n   * \\param dtype The data type of the new array.\n   * \\note The memory size of new array must be smaller than the current one.\n   */\n  TVM_DLL NDArray CreateView(ShapeTuple shape, DLDataType dtype);\n  /*!\n   * \\brief Create a reference view of NDArray that\n   *  represents as DLManagedTensor.\n   * \\return A DLManagedTensor\n   */\n  TVM_DLL DLManagedTensor* ToDLPack() const;\n  /*!\n   * \\brief Create an empty NDArray.\n   * \\param shape The shape of the new array.\n   * \\param dtype The data type of the new array.\n   * \\param dev The device of the array.\n   * \\param mem_scope The memory scope of the array.\n   * \\return The created Array\n   */\n  TVM_DLL static NDArray Empty(ShapeTuple shape, DLDataType dtype, Device dev,\n                               Optional<String> mem_scope = NullOpt);\n  /*!\n   * \\brief Create a NDArray backed by an external DLTensor without memory copying.\n   *\n   * If DLTensor is not contiguous or has bad aligned data, It fails.\n   * This allows us to create a NDArray using the memory\n   * allocated by an external source. Responsibility for memory\n   * retaining lies with the external source.\n   * \\param dl_tensor The DLTensor for NDArray base.\n   * \\return The created NDArray view.\n   */\n  TVM_DLL static NDArray FromExternalDLTensor(const DLTensor& dl_tensor);\n  /*!\n   * \\brief Create new NDArray, data is copied from DLTensor.\n   *\n   * \\param dl_tensor The DLTensor to copy from.\n   * \\param dev device location of the created NDArray.\n   * \\return The created NDArray view.\n   */\n  TVM_DLL static NDArray NewFromDLTensor(DLTensor* dl_tensor, const Device& dev);\n  /*!\n   * \\brief Create a NDArray backed by a dlpack tensor.\n   *\n   * This allows us to create a NDArray using the memory\n   * allocated by an external deep learning framework\n   * that is DLPack compatible.\n   *\n   * The memory is retained until the NDArray went out of scope.\n   * \\param tensor The DLPack tensor to copy from.\n   * \\return The created NDArray view.\n   */\n  TVM_DLL static NDArray FromDLPack(DLManagedTensor* tensor);\n  /*!\n   * \\brief Function to copy data from one array to another.\n   * \\param from The source array.\n   * \\param to The target array.\n   * \\param stream The stream used in copy.\n   */\n  TVM_DLL static void CopyFromTo(const DLTensor* from, DLTensor* to,\n                                 TVMStreamHandle stream = nullptr);\n\n  TVM_DLL ShapeTuple Shape() const;\n  TVM_DLL runtime::DataType DataType() const;\n  /*!\n   * \\brief Check conditions for construction NDArray over DLTensor without copying.\n   * There are three conditions to check:\n   * 1. Destination device is the same as DLTensor device\n   * 2. Destination device id is the same as DLTensor device id\n   * 3. Memory in DLTensor is aligned as expected for NDArray\n   * \\param tensor the DLTensor.\n   * \\param dev destination device.\n   * \\return true if all conditions are satisfied.\n   */\n  TVM_DLL static bool AbilityOfZeroCopyForDLTensor(DLTensor* tensor, const Device& dev);\n  // internal namespace\n  struct Internal;\n\n private:\n  TVM_DLL static bool IsAligned(const DLTensor& tensor);\n\n protected:\n  friend class TVMPODValue_;\n  friend class TVMRetValue;\n  friend class TVMArgsSetter;\n  /*!\n   * \\brief Get mutable internal container pointer.\n   * \\return a mutable container pointer.\n   */\n  inline Container* get_mutable() const;\n  // Helper functions for FFI handling.\n  /*!\n   * \\brief Construct NDArray's Data field from array handle in FFI.\n   * \\param handle The array handle.\n   * \\return The corresponding ObjectPtr to the constructed container object.\n   *\n   * \\note We keep a special calling convention for NDArray by passing\n   *       ContainerBase pointer in FFI.\n   *       As a result, the argument is compatible to DLTensor*.\n   */\n  inline static ObjectPtr<Object> FFIDataFromHandle(TVMArrayHandle handle);\n  /*!\n   * \\brief DecRef resource managed by an FFI array handle.\n   * \\param handle The array handle.\n   */\n  inline static void FFIDecRef(TVMArrayHandle handle);\n  /*!\n   * \\brief Get FFI Array handle from ndarray.\n   * \\param nd The object with ndarray type.\n   * \\return The result array handle.\n   */\n  inline static TVMArrayHandle FFIGetHandle(const ObjectRef& nd);\n};\n\n/*!\n * \\brief Save a DLTensor to stream\n * \\param strm The output stream\n * \\param tensor The tensor to be saved.\n */\ninline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor);\n\n/*!\n * \\brief The container base structure\n *        contains all the fields except for the Object header.\n *\n * \\note We explicitly declare this structure in order to pass\n *       PackedFunc argument using ContainerBase*.\n */\nclass NDArray::ContainerBase {\n public:\n  /*!\n   * \\brief The corresponding dl_tensor field.\n   * \\note it is important that the first field is DLTensor\n   *  So that this data structure is DLTensor compatible.\n   *  The head ptr of this struct can be viewed as DLTensor*.\n   */\n  DLTensor dl_tensor;\n\n  /*!\n   * \\brief additional context, reserved for recycling\n   * \\note We can attach additional content here\n   *  which the current container depend on\n   *  (e.g. reference to original memory when creating views).\n   */\n  void* manager_ctx{nullptr};\n\n protected:\n  /*!\n   * \\brief The shape container,\n   *  can be used used for shape data.\n   */\n  ShapeTuple shape_;\n};\n\n/*!\n * \\brief Object container class that backs NDArray.\n * \\note do not use this function directly, use NDArray.\n */\nclass NDArray::Container : public Object, public NDArray::ContainerBase {\n public:\n  /*! \\brief default constructor */\n  Container() {\n    // Initialize the type index.\n    type_index_ = Container::RuntimeTypeIndex();\n    dl_tensor.data = nullptr;\n    dl_tensor.ndim = 0;\n    dl_tensor.shape = nullptr;\n    dl_tensor.strides = nullptr;\n    dl_tensor.byte_offset = 0;\n  }\n\n  Container(void* data, ShapeTuple shape, DLDataType dtype, Device dev) {\n    // Initialize the type index.\n    type_index_ = Container::RuntimeTypeIndex();\n    dl_tensor.data = data;\n    shape_ = std::move(shape);\n    dl_tensor.ndim = static_cast<int>(shape_.size());\n    dl_tensor.shape = const_cast<ShapeTuple::index_type*>(shape_.data());\n    dl_tensor.dtype = dtype;\n    dl_tensor.strides = nullptr;\n    dl_tensor.byte_offset = 0;\n    dl_tensor.device = dev;\n  }\n  /*!\n   * \\brief Set the deleter field.\n   * \\param deleter The deleter.\n   */\n  void SetDeleter(FDeleter deleter) { deleter_ = deleter; }\n\n  // Expose DecRef and IncRef as public function\n  // NOTE: they are only for developer purposes only.\n  using Object::DecRef;\n  using Object::IncRef;\n\n  // Information for object protocol.\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimeNDArray;\n  static constexpr const uint32_t _type_child_slots = 0;\n  static constexpr const uint32_t _type_child_slots_can_overflow = true;\n  static constexpr const char* _type_key = \"runtime.NDArray\";\n  TVM_DECLARE_BASE_OBJECT_INFO(NDArray::Container, Object);\n\n protected:\n  friend class RPCWrappedFunc;\n  friend class NDArray;\n};\n\n// implementations of inline functions\n/*!\n * \\brief return the size of data the DLTensor hold, in term of number of bytes\n *\n *  \\param arr the input DLTensor\n *  \\return number of  bytes of data in the DLTensor.\n */\ninline size_t GetDataSize(const DLTensor& arr) {\n  size_t size = 1;\n  for (tvm_index_t i = 0; i < arr.ndim; ++i) {\n    size *= static_cast<size_t>(arr.shape[i]);\n  }\n  size *= (arr.dtype.bits * arr.dtype.lanes + 7) / 8;\n  return size;\n}\n\n/*!\n * \\brief check if a DLTensor is contiguous.\n * \\param arr The input DLTensor.\n * \\return The check result.\n */\nstatic inline bool IsContiguous(const DLTensor& arr) {\n  if (arr.strides == nullptr) return true;\n  int64_t expected_stride = 1;\n  for (int32_t i = arr.ndim; i != 0; --i) {\n    int32_t k = i - 1;\n    if (arr.shape[k] == 1) {\n      // Skip stride check if shape[k] is 1, where the dimension is contiguous\n      // regardless of the value of stride.\n      //\n      // For example, PyTorch will normalize stride to 1 if shape is 1 when exporting\n      // to DLPack.\n      // More context: https://github.com/pytorch/pytorch/pull/83158\n      continue;\n    }\n    if (arr.strides[k] != expected_stride) return false;\n    expected_stride *= arr.shape[k];\n  }\n  return true;\n}\n\ninline bool NDArray::IsContiguous() const {\n  return ::tvm::runtime::IsContiguous(get_mutable()->dl_tensor);\n}\n\ninline void NDArray::CopyFrom(const DLTensor* other) {\n  ICHECK(data_ != nullptr);\n  CopyFromTo(other, &(get_mutable()->dl_tensor));\n}\n\ninline void NDArray::CopyFrom(const NDArray& other) {\n  ICHECK(data_ != nullptr);\n  ICHECK(other.data_ != nullptr);\n  CopyFromTo(&(other.get_mutable()->dl_tensor), &(get_mutable()->dl_tensor));\n}\n\ninline void NDArray::CopyTo(DLTensor* other) const {\n  ICHECK(data_ != nullptr);\n  CopyFromTo(&(get_mutable()->dl_tensor), other);\n}\n\ninline void NDArray::CopyTo(const NDArray& other) const {\n  ICHECK(data_ != nullptr);\n  ICHECK(other.data_ != nullptr);\n  CopyFromTo(&(get_mutable()->dl_tensor), &(other.get_mutable()->dl_tensor));\n}\n\ninline NDArray NDArray::CopyTo(const Device& dev) const {\n  ICHECK(data_ != nullptr);\n  const DLTensor* dptr = operator->();\n  NDArray ret = Empty(ShapeTuple(dptr->shape, dptr->shape + dptr->ndim), dptr->dtype, dev);\n  this->CopyTo(ret);\n  return ret;\n}\n\ninline int NDArray::use_count() const { return data_.use_count(); }\n\ninline const DLTensor* NDArray::operator->() const { return &(get_mutable()->dl_tensor); }\n\ninline NDArray::Container* NDArray::get_mutable() const {\n  return static_cast<NDArray::Container*>(data_.get());\n}\n\ninline ObjectPtr<Object> NDArray::FFIDataFromHandle(TVMArrayHandle handle) {\n  return GetObjectPtr<Object>(\n      static_cast<NDArray::Container*>(reinterpret_cast<NDArray::ContainerBase*>(handle)));\n}\n\ninline TVMArrayHandle NDArray::FFIGetHandle(const ObjectRef& nd) {\n  // NOTE: it is necessary to cast to container then to base\n  //       so that the FFI handle uses the ContainerBase address.\n  auto ptr = reinterpret_cast<TVMArrayHandle>(static_cast<NDArray::ContainerBase*>(\n      static_cast<NDArray::Container*>(const_cast<Object*>(nd.get()))));\n  return ptr;\n}\n\ninline void NDArray::FFIDecRef(TVMArrayHandle handle) {\n  static_cast<NDArray::Container*>(reinterpret_cast<NDArray::ContainerBase*>(handle))->DecRef();\n}\n\ninline Object* TVMArrayHandleToObjectHandle(TVMArrayHandle handle) {\n  return static_cast<NDArray::Container*>(reinterpret_cast<NDArray::ContainerBase*>(handle));\n}\n\n/*! \\brief Magic number for NDArray file */\nconstexpr uint64_t kTVMNDArrayMagic = 0xDD5E40F096B4A13F;\n\ninline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {\n  uint64_t header = kTVMNDArrayMagic, reserved = 0;\n  strm->Write(header);\n  strm->Write(reserved);\n  // Always save data as CPU context\n  //\n  // Parameters that get serialized should be in CPU by default.\n  // So even the array's context is GPU, it will be stored as CPU array.\n  // This is used to prevent case when another user loads the parameters\n  // back on machine that do not have GPU or related context.\n  //\n  // We can always do array.CopyTo(target_dev) to get a corresponding\n  // array in the target context.\n  Device cpu_dev;\n  cpu_dev.device_type = kDLCPU;\n  cpu_dev.device_id = 0;\n  strm->Write(cpu_dev);\n  strm->Write(tensor->ndim);\n  strm->Write(tensor->dtype);\n  int ndim = tensor->ndim;\n  strm->WriteArray(tensor->shape, ndim);\n  int type_bytes = (tensor->dtype.bits + 7) / 8;\n  int64_t num_elems = 1;\n  for (int i = 0; i < ndim; ++i) {\n    num_elems *= tensor->shape[i];\n  }\n  int64_t data_byte_size = type_bytes * num_elems;\n  strm->Write(data_byte_size);\n\n  if (DMLC_IO_NO_ENDIAN_SWAP && tensor->device.device_type == kDLCPU &&\n      tensor->strides == nullptr && tensor->byte_offset == 0) {\n    // quick path\n    strm->Write(tensor->data, data_byte_size);\n  } else {\n    std::vector<uint8_t> bytes(data_byte_size);\n    ICHECK_EQ(\n        TVMArrayCopyToBytes(const_cast<DLTensor*>(tensor), dmlc::BeginPtr(bytes), data_byte_size),\n        0)\n        << TVMGetLastError();\n    if (!DMLC_IO_NO_ENDIAN_SWAP) {\n      dmlc::ByteSwap(dmlc::BeginPtr(bytes), type_bytes, num_elems);\n    }\n    strm->Write(dmlc::BeginPtr(bytes), data_byte_size);\n  }\n  return true;\n}\n\ninline void NDArray::Save(dmlc::Stream* strm) const { SaveDLTensor(strm, operator->()); }\n\ninline bool NDArray::Load(dmlc::Stream* strm) {\n  uint64_t header, reserved;\n  ICHECK(strm->Read(&header)) << \"Invalid DLTensor file format\";\n  ICHECK(strm->Read(&reserved)) << \"Invalid DLTensor file format\";\n  ICHECK(header == kTVMNDArrayMagic) << \"Invalid DLTensor file format\";\n  Device dev;\n  int ndim;\n  DLDataType dtype;\n  ICHECK(strm->Read(&dev)) << \"Invalid DLTensor file format\";\n  ICHECK(strm->Read(&ndim)) << \"Invalid DLTensor file format\";\n  ICHECK(strm->Read(&dtype)) << \"Invalid DLTensor file format\";\n  ICHECK_EQ(dev.device_type, kDLCPU) << \"Invalid DLTensor device: can only save as CPU tensor\";\n  std::vector<int64_t> shape(ndim);\n  if (ndim != 0) {\n    ICHECK(strm->ReadArray(&shape[0], ndim)) << \"Invalid DLTensor file format\";\n  }\n  NDArray ret = NDArray::Empty(ShapeTuple(shape), dtype, dev);\n  int64_t num_elems = 1;\n  int elem_bytes = (ret->dtype.bits + 7) / 8;\n  for (int i = 0; i < ret->ndim; ++i) {\n    num_elems *= ret->shape[i];\n  }\n  int64_t data_byte_size;\n  ICHECK(strm->Read(&data_byte_size)) << \"Invalid DLTensor file format\";\n  ICHECK(data_byte_size == num_elems * elem_bytes) << \"Invalid DLTensor file format\";\n  auto read_ret = strm->Read(ret->data, data_byte_size);\n  // Only check non-empty data\n  if (ndim > 0 && shape[0] != 0) {\n    ICHECK(read_ret) << \"Invalid DLTensor file format\";\n  }\n  if (!DMLC_IO_NO_ENDIAN_SWAP) {\n    dmlc::ByteSwap(ret->data, elem_bytes, num_elems);\n  }\n  *this = ret;\n  return true;\n}\n\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace std {\ntemplate <>\nstruct hash<tvm::Device> {\n  std::size_t operator()(const tvm::Device& dev) const {\n    return ((dev.device_id << 8) | dev.device_type);\n  }\n};\n\ntemplate <>\nstruct equal_to<tvm::Device> {\n  bool operator()(const tvm::Device& lhs, const tvm::Device& rhs) const {\n    return (lhs.device_type == rhs.device_type && lhs.device_id == rhs.device_id);\n  }\n};\n}  // namespace std\n\n#endif  // TVM_RUNTIME_NDARRAY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/object.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/runtime/object.h\n * \\brief A managed object in the TVM runtime.\n */\n#ifndef TVM_RUNTIME_OBJECT_H_\n#define TVM_RUNTIME_OBJECT_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/logging.h>\n\n#include <string>\n#include <type_traits>\n#include <utility>\n\n/*!\n * \\brief Whether or not use atomic reference counter.\n *  If the reference counter is not atomic,\n *  an object cannot be owned by multiple threads.\n *  We can, however, move an object across threads\n */\n#ifndef TVM_OBJECT_ATOMIC_REF_COUNTER\n#define TVM_OBJECT_ATOMIC_REF_COUNTER 1\n#endif\n\n#if TVM_OBJECT_ATOMIC_REF_COUNTER\n#include <atomic>\n#endif  // TVM_OBJECT_ATOMIC_REF_COUNTER\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Namespace for the list of type index.\n * \\note Use struct so that we have to use TypeIndex::ENumName to refer to\n *       the constant, but still able to use enum.\n */\nstruct TypeIndex {\n  enum {\n    /*! \\brief Root object type. */\n    kRoot = 0,\n    // Standard static index assignments,\n    // Frontends can take benefit of these constants.\n    /*! \\brief runtime::Module. */\n    kRuntimeModule = 1,\n    /*! \\brief runtime::NDArray. */\n    kRuntimeNDArray = 2,\n    /*! \\brief runtime::String. */\n    kRuntimeString = 3,\n    /*! \\brief runtime::Array. */\n    kRuntimeArray = 4,\n    /*! \\brief runtime::Map. */\n    kRuntimeMap = 5,\n    /*! \\brief runtime::ShapeTuple. */\n    kRuntimeShapeTuple = 6,\n    /*! \\brief runtime::PackedFunc. */\n    kRuntimePackedFunc = 7,\n    // static assignments that may subject to change.\n    kRuntimeClosure,\n    kRuntimeADT,\n    kStaticIndexEnd,\n    /*! \\brief Type index is allocated during runtime. */\n    kDynamic = kStaticIndexEnd\n  };\n};  // namespace TypeIndex\n\n/*!\n * \\brief base class of all object containers.\n *\n * Sub-class of objects should declare the following static constexpr fields:\n *\n * - _type_index:\n *      Static type index of the object, if assigned to TypeIndex::kDynamic\n *      the type index will be assigned during runtime.\n *      Runtime type index can be accessed by ObjectType::TypeIndex();\n * - _type_key:\n *       The unique string identifier of the type.\n * - _type_final:\n *       Whether the type is terminal type(there is no subclass of the type in the object system).\n *       This field is automatically set by macro TVM_DECLARE_FINAL_OBJECT_INFO\n *       It is still OK to sub-class a terminal object type T and construct it using make_object.\n *       But IsInstance check will only show that the object type is T(instead of the sub-class).\n *\n * The following two fields are necessary for base classes that can be sub-classed.\n *\n * - _type_child_slots:\n *       Number of reserved type index slots for child classes.\n *       Used for runtime optimization for type checking in IsInstance.\n *       If an object's type_index is within range of [type_index, type_index + _type_child_slots]\n *       Then the object can be quickly decided as sub-class of the current object class.\n *       If not, a fallback mechanism is used to check the global type table.\n *       Recommendation: set to estimate number of children needed.\n * - _type_child_slots_can_overflow:\n *       Whether we can add additional child classes even if the number of child classes\n *       exceeds the _type_child_slots. A fallback mechanism to check global type table will be\n * used. Recommendation: set to false for optimal runtime speed if we know exact number of children.\n *\n * Two macros are used to declare helper functions in the object:\n * - Use TVM_DECLARE_BASE_OBJECT_INFO for object classes that can be sub-classed.\n * - Use TVM_DECLARE_FINAL_OBJECT_INFO for object classes that cannot be sub-classed.\n *\n * New objects can be created using make_object function.\n * Which will automatically populate the type_index and deleter of the object.\n *\n * \\sa make_object\n * \\sa ObjectPtr\n * \\sa ObjectRef\n *\n * \\code\n *\n *  // Create a base object\n *  class BaseObj : public Object {\n *   public:\n *    // object fields\n *    int field0;\n *\n *    // object properties\n *    static constexpr const uint32_t _type_index = TypeIndex::kDynamic;\n *    static constexpr const char* _type_key = \"test.BaseObj\";\n *    TVM_DECLARE_BASE_OBJECT_INFO(BaseObj, Object);\n *  };\n *\n *  class LeafObj : public BaseObj {\n *   public:\n *    // fields\n *    int child_field0;\n *    // object properties\n *    static constexpr const uint32_t _type_index = TypeIndex::kDynamic;\n *    static constexpr const char* _type_key = \"test.LeafObj\";\n *    TVM_DECLARE_BASE_OBJECT_INFO(LeafObj, Object);\n *  };\n *\n *  // The following code should be put into a cc file.\n *  TVM_REGISTER_OBJECT_TYPE(BaseObj);\n *  TVM_REGISTER_OBJECT_TYPE(LeafObj);\n *\n *  // Usage example.\n *  void TestObjects() {\n *    // create an object\n *    ObjectRef leaf_ref(make_object<LeafObj>());\n *    // cast to a specific instance\n *    const LeafObj* leaf_ptr = leaf_ref.as<LeafObj>();\n *    ICHECK(leaf_ptr != nullptr);\n *    // can also cast to the base class.\n *    ICHECK(leaf_ref.as<BaseObj>() != nullptr);\n *  }\n *\n * \\endcode\n */\nclass TVM_DLL Object {\n public:\n  /*!\n   * \\brief Object deleter\n   * \\param self pointer to the Object.\n   */\n  typedef void (*FDeleter)(Object* self);\n  /*! \\return The internal runtime type index of the object. */\n  uint32_t type_index() const { return type_index_; }\n  /*!\n   * \\return the type key of the object.\n   * \\note this operation is expensive, can be used for error reporting.\n   */\n  std::string GetTypeKey() const { return TypeIndex2Key(type_index_); }\n  /*!\n   * \\return A hash value of the return of GetTypeKey.\n   */\n  size_t GetTypeKeyHash() const { return TypeIndex2KeyHash(type_index_); }\n  /*!\n   * Check if the object is an instance of TargetType.\n   * \\tparam TargetType The target type to be checked.\n   * \\return Whether the target type is true.\n   */\n  template <typename TargetType>\n  inline bool IsInstance() const;\n  /*!\n   * \\return Whether the cell has only one reference\n   * \\note We use stl style naming to be consistent with known API in shared_ptr.\n   */\n  inline bool unique() const;\n  /*!\n   * \\brief Get the type key of the corresponding index from runtime.\n   * \\param tindex The type index.\n   * \\return the result.\n   */\n  static std::string TypeIndex2Key(uint32_t tindex);\n  /*!\n   * \\brief Get the type key hash of the corresponding index from runtime.\n   * \\param tindex The type index.\n   * \\return the related key-hash.\n   */\n  static size_t TypeIndex2KeyHash(uint32_t tindex);\n  /*!\n   * \\brief Get the type index of the corresponding key from runtime.\n   * \\param key The type key.\n   * \\return the result.\n   */\n  static uint32_t TypeKey2Index(const std::string& key);\n\n#if TVM_OBJECT_ATOMIC_REF_COUNTER\n  using RefCounterType = std::atomic<int32_t>;\n#else\n  using RefCounterType = int32_t;\n#endif\n\n  static constexpr const char* _type_key = \"runtime.Object\";\n\n  static uint32_t _GetOrAllocRuntimeTypeIndex() { return TypeIndex::kRoot; }\n  static uint32_t RuntimeTypeIndex() { return TypeIndex::kRoot; }\n\n  // Default object type properties for sub-classes\n  static constexpr bool _type_final = false;\n  static constexpr uint32_t _type_child_slots = 0;\n  static constexpr bool _type_child_slots_can_overflow = true;\n  // member information\n  static constexpr bool _type_has_method_visit_attrs = true;\n  static constexpr bool _type_has_method_sequal_reduce = false;\n  static constexpr bool _type_has_method_shash_reduce = false;\n  // NOTE: the following field is not type index of Object\n  // but was intended to be used by sub-classes as default value.\n  // The type index of Object is TypeIndex::kRoot\n  static constexpr uint32_t _type_index = TypeIndex::kDynamic;\n\n  // Default constructor and copy constructor\n  Object() {}\n  // Override the copy and assign constructors to do nothing.\n  // This is to make sure only contents, but not deleter and ref_counter\n  // are copied when a child class copies itself.\n  // This will enable us to use make_object<ObjectClass>(*obj_ptr)\n  // to copy an existing object.\n  Object(const Object& other) {  // NOLINT(*)\n  }\n  Object(Object&& other) {  // NOLINT(*)\n  }\n  Object& operator=(const Object& other) {  // NOLINT(*)\n    return *this;\n  }\n  Object& operator=(Object&& other) {  // NOLINT(*)\n    return *this;\n  }\n\n protected:\n  // The fields of the base object cell.\n  /*! \\brief Type index(tag) that indicates the type of the object. */\n  uint32_t type_index_{0};\n  /*! \\brief The internal reference counter */\n  RefCounterType ref_counter_{0};\n  /*!\n   * \\brief deleter of this object to enable customized allocation.\n   * If the deleter is nullptr, no deletion will be performed.\n   * The creator of the object must always set the deleter field properly.\n   */\n  FDeleter deleter_ = nullptr;\n  // Invariant checks.\n  static_assert(sizeof(int32_t) == sizeof(RefCounterType) &&\n                    alignof(int32_t) == sizeof(RefCounterType),\n                \"RefCounter ABI check.\");\n\n  /*!\n   * \\brief Get the type index using type key.\n   *\n   *  When the function is first time called for a type,\n   *  it will register the type to the type table in the runtime.\n   *  If the static_tindex is TypeIndex::kDynamic, the function will\n   *  allocate a runtime type index.\n   *  Otherwise, we will populate the type table and return the static index.\n   *\n   * \\param key the type key.\n   * \\param static_tindex The current _type_index field.\n   *                      can be TypeIndex::kDynamic.\n   * \\param parent_tindex The index of the parent.\n   * \\param type_child_slots Number of slots reserved for its children.\n   * \\param type_child_slots_can_overflow Whether to allow child to overflow the slots.\n   * \\return The allocated type index.\n   */\n  static uint32_t GetOrAllocRuntimeTypeIndex(const std::string& key, uint32_t static_tindex,\n                                             uint32_t parent_tindex, uint32_t type_child_slots,\n                                             bool type_child_slots_can_overflow);\n\n  // reference counter related operations\n  /*! \\brief developer function, increases reference counter. */\n  inline void IncRef();\n  /*!\n   * \\brief developer function, decrease reference counter.\n   * \\note The deleter will be called when ref_counter_ becomes zero.\n   */\n  inline void DecRef();\n\n private:\n  /*!\n   * \\return The usage count of the cell.\n   * \\note We use stl style naming to be consistent with known API in shared_ptr.\n   */\n  inline int use_count() const;\n  /*!\n   * \\brief Check of this object is derived from the parent.\n   * \\param parent_tindex The parent type index.\n   * \\return The derivation results.\n   */\n  bool DerivedFrom(uint32_t parent_tindex) const;\n  // friend classes\n  template <typename>\n  friend class ObjAllocatorBase;\n  template <typename>\n  friend class ObjectPtr;\n  friend class TVMRetValue;\n  friend class ObjectInternal;\n};\n\n/*!\n * \\brief Get a reference type from a raw object ptr type\n *\n *  It is always important to get a reference type\n *  if we want to return a value as reference or keep\n *  the object alive beyond the scope of the function.\n *\n * \\param ptr The object pointer\n * \\tparam RefType The reference type\n * \\tparam ObjectType The object type\n * \\return The corresponding RefType\n */\ntemplate <typename RelayRefType, typename ObjectType>\ninline RelayRefType GetRef(const ObjectType* ptr);\n\n/*!\n * \\brief Downcast a base reference type to a more specific type.\n *\n * \\param ref The input reference\n * \\return The corresponding SubRef.\n * \\tparam SubRef The target specific reference type.\n * \\tparam BaseRef the current reference type.\n */\ntemplate <typename SubRef, typename BaseRef>\ninline SubRef Downcast(BaseRef ref);\n\n/*!\n * \\brief A custom smart pointer for Object.\n * \\tparam T the content data type.\n * \\sa make_object\n */\ntemplate <typename T>\nclass ObjectPtr {\n public:\n  /*! \\brief default constructor */\n  ObjectPtr() {}\n  /*! \\brief default constructor */\n  ObjectPtr(std::nullptr_t) {}  // NOLINT(*)\n  /*!\n   * \\brief copy constructor\n   * \\param other The value to be moved\n   */\n  ObjectPtr(const ObjectPtr<T>& other)  // NOLINT(*)\n      : ObjectPtr(other.data_) {}\n  /*!\n   * \\brief copy constructor\n   * \\param other The value to be moved\n   */\n  template <typename U>\n  ObjectPtr(const ObjectPtr<U>& other)  // NOLINT(*)\n      : ObjectPtr(other.data_) {\n    static_assert(std::is_base_of<T, U>::value,\n                  \"can only assign of child class ObjectPtr to parent\");\n  }\n  /*!\n   * \\brief move constructor\n   * \\param other The value to be moved\n   */\n  ObjectPtr(ObjectPtr<T>&& other)  // NOLINT(*)\n      : data_(other.data_) {\n    other.data_ = nullptr;\n  }\n  /*!\n   * \\brief move constructor\n   * \\param other The value to be moved\n   */\n  template <typename Y>\n  ObjectPtr(ObjectPtr<Y>&& other)  // NOLINT(*)\n      : data_(other.data_) {\n    static_assert(std::is_base_of<T, Y>::value,\n                  \"can only assign of child class ObjectPtr to parent\");\n    other.data_ = nullptr;\n  }\n  /*! \\brief destructor */\n  ~ObjectPtr() { this->reset(); }\n  /*!\n   * \\brief Swap this array with another Object\n   * \\param other The other Object\n   */\n  void swap(ObjectPtr<T>& other) {  // NOLINT(*)\n    std::swap(data_, other.data_);\n  }\n  /*!\n   * \\return Get the content of the pointer\n   */\n  T* get() const { return static_cast<T*>(data_); }\n  /*!\n   * \\return The pointer\n   */\n  T* operator->() const { return get(); }\n  /*!\n   * \\return The reference\n   */\n  T& operator*() const {  // NOLINT(*)\n    return *get();\n  }\n  /*!\n   * \\brief copy assignment\n   * \\param other The value to be assigned.\n   * \\return reference to self.\n   */\n  ObjectPtr<T>& operator=(const ObjectPtr<T>& other) {  // NOLINT(*)\n    // takes in plane operator to enable copy elison.\n    // copy-and-swap idiom\n    ObjectPtr(other).swap(*this);  // NOLINT(*)\n    return *this;\n  }\n  /*!\n   * \\brief move assignment\n   * \\param other The value to be assigned.\n   * \\return reference to self.\n   */\n  ObjectPtr<T>& operator=(ObjectPtr<T>&& other) {  // NOLINT(*)\n    // copy-and-swap idiom\n    ObjectPtr(std::move(other)).swap(*this);  // NOLINT(*)\n    return *this;\n  }\n  /*!\n   * \\brief nullptr check\n   * \\return result of comparison of internal pointer with nullptr.\n   */\n  explicit operator bool() const { return get() != nullptr; }\n  /*! \\brief reset the content of ptr to be nullptr */\n  void reset() {\n    if (data_ != nullptr) {\n      data_->DecRef();\n      data_ = nullptr;\n    }\n  }\n  /*! \\return The use count of the ptr, for debug purposes */\n  int use_count() const { return data_ != nullptr ? data_->use_count() : 0; }\n  /*! \\return whether the reference is unique */\n  bool unique() const { return data_ != nullptr && data_->use_count() == 1; }\n  /*! \\return Whether two ObjectPtr do not equal each other */\n  bool operator==(const ObjectPtr<T>& other) const { return data_ == other.data_; }\n  /*! \\return Whether two ObjectPtr equals each other */\n  bool operator!=(const ObjectPtr<T>& other) const { return data_ != other.data_; }\n  /*! \\return Whether the pointer is nullptr */\n  bool operator==(std::nullptr_t null) const { return data_ == nullptr; }\n  /*! \\return Whether the pointer is not nullptr */\n  bool operator!=(std::nullptr_t null) const { return data_ != nullptr; }\n\n private:\n  /*! \\brief internal pointer field */\n  Object* data_{nullptr};\n  /*!\n   * \\brief constructor from Object\n   * \\param data The data pointer\n   */\n  explicit ObjectPtr(Object* data) : data_(data) {\n    if (data != nullptr) {\n      data_->IncRef();\n    }\n  }\n  /*!\n   * \\brief Move an ObjectPtr from an RValueRef argument.\n   * \\param ref The rvalue reference.\n   * \\return the moved result.\n   */\n  static ObjectPtr<T> MoveFromRValueRefArg(Object** ref) {\n    ObjectPtr<T> ptr;\n    ptr.data_ = *ref;\n    *ref = nullptr;\n    return ptr;\n  }\n  // friend classes\n  friend class Object;\n  friend class ObjectRef;\n  friend struct ObjectPtrHash;\n  template <typename>\n  friend class ObjectPtr;\n  template <typename>\n  friend class ObjAllocatorBase;\n  friend class TVMPODValue_;\n  friend class TVMArgsSetter;\n  friend class TVMRetValue;\n  friend class TVMArgValue;\n  friend class TVMMovableArgValue_;\n  template <typename RelayRefType, typename ObjType>\n  friend RelayRefType GetRef(const ObjType* ptr);\n  template <typename BaseType, typename ObjType>\n  friend ObjectPtr<BaseType> GetObjectPtr(ObjType* ptr);\n};\n\n/*! \\brief Base class of all object reference */\nclass ObjectRef {\n public:\n  /*! \\brief default constructor */\n  ObjectRef() = default;\n  /*! \\brief Constructor from existing object ptr */\n  explicit ObjectRef(ObjectPtr<Object> data) : data_(data) {}\n  /*!\n   * \\brief Comparator\n   * \\param other Another object ref.\n   * \\return the compare result.\n   */\n  bool same_as(const ObjectRef& other) const { return data_ == other.data_; }\n  /*!\n   * \\brief Comparator\n   * \\param other Another object ref.\n   * \\return the compare result.\n   */\n  bool operator==(const ObjectRef& other) const { return data_ == other.data_; }\n  /*!\n   * \\brief Comparator\n   * \\param other Another object ref.\n   * \\return the compare result.\n   */\n  bool operator!=(const ObjectRef& other) const { return data_ != other.data_; }\n  /*!\n   * \\brief Comparator\n   * \\param other Another object ref by address.\n   * \\return the compare result.\n   */\n  bool operator<(const ObjectRef& other) const { return data_.get() < other.data_.get(); }\n  /*!\n   * \\return whether the object is defined(not null).\n   */\n  bool defined() const { return data_ != nullptr; }\n  /*! \\return the internal object pointer */\n  const Object* get() const { return data_.get(); }\n  /*! \\return the internal object pointer */\n  const Object* operator->() const { return get(); }\n  /*! \\return whether the reference is unique */\n  bool unique() const { return data_.unique(); }\n  /*! \\return The use count of the ptr, for debug purposes */\n  int use_count() const { return data_.use_count(); }\n  /*!\n   * \\brief Try to downcast the internal Object to a\n   *  raw pointer of a corresponding type.\n   *\n   *  The function will return a nullptr if the cast failed.\n   *\n   * if (const Add *add = node_ref.As<Add>()) {\n   *   // This is an add node\n   * }\n   * \\tparam ObjectType the target type, must be a subtype of Object/\n   */\n  template <typename ObjectType>\n  inline const ObjectType* as() const;\n\n  /*! \\brief type indicate the container type. */\n  using ContainerType = Object;\n  // Default type properties for the reference class.\n  static constexpr bool _type_is_nullable = true;\n\n protected:\n  /*! \\brief Internal pointer that backs the reference. */\n  ObjectPtr<Object> data_;\n  /*! \\return return a mutable internal ptr, can be used by sub-classes. */\n  Object* get_mutable() const { return data_.get(); }\n  /*!\n   * \\brief Internal helper function downcast a ref without check.\n   * \\note Only used for internal dev purposes.\n   * \\tparam T The target reference type.\n   * \\return The casted result.\n   */\n  template <typename T>\n  static T DowncastNoCheck(ObjectRef ref) {\n    return T(std::move(ref.data_));\n  }\n  /*!\n   * \\brief Clear the object ref data field without DecRef\n   *        after we successfully moved the field.\n   * \\param ref The reference data.\n   */\n  static void FFIClearAfterMove(ObjectRef* ref) { ref->data_.data_ = nullptr; }\n  /*!\n   * \\brief Internal helper function get data_ as ObjectPtr of ObjectType.\n   * \\note only used for internal dev purpose.\n   * \\tparam ObjectType The corresponding object type.\n   * \\return the corresponding type.\n   */\n  template <typename ObjectType>\n  static ObjectPtr<ObjectType> GetDataPtr(const ObjectRef& ref) {\n    return ObjectPtr<ObjectType>(ref.data_.data_);\n  }\n  // friend classes.\n  friend struct ObjectPtrHash;\n  friend class TVMRetValue;\n  friend class TVMArgsSetter;\n  friend class ObjectInternal;\n  template <typename SubRef, typename BaseRef>\n  friend SubRef Downcast(BaseRef ref);\n};\n\n/*!\n * \\brief Get an object ptr type from a raw object ptr.\n *\n * \\param ptr The object pointer\n * \\tparam BaseType The reference type\n * \\tparam ObjectType The object type\n * \\return The corresponding RefType\n */\ntemplate <typename BaseType, typename ObjectType>\ninline ObjectPtr<BaseType> GetObjectPtr(ObjectType* ptr);\n\n/*! \\brief ObjectRef hash functor */\nstruct ObjectPtrHash {\n  size_t operator()(const ObjectRef& a) const { return operator()(a.data_); }\n\n  template <typename T>\n  size_t operator()(const ObjectPtr<T>& a) const {\n    return std::hash<Object*>()(a.get());\n  }\n};\n\n/*! \\brief ObjectRef equal functor */\nstruct ObjectPtrEqual {\n  bool operator()(const ObjectRef& a, const ObjectRef& b) const { return a.same_as(b); }\n\n  template <typename T>\n  size_t operator()(const ObjectPtr<T>& a, const ObjectPtr<T>& b) const {\n    return a == b;\n  }\n};\n\n/*!\n * \\brief helper macro to declare a base object type that can be inherited.\n * \\param TypeName The name of the current type.\n * \\param ParentType The name of the ParentType\n */\n#define TVM_DECLARE_BASE_OBJECT_INFO(TypeName, ParentType)                                     \\\n  static_assert(!ParentType::_type_final, \"ParentObj marked as final\");                        \\\n  static uint32_t RuntimeTypeIndex() {                                                         \\\n    static_assert(TypeName::_type_child_slots == 0 || ParentType::_type_child_slots == 0 ||    \\\n                      TypeName::_type_child_slots < ParentType::_type_child_slots,             \\\n                  \"Need to set _type_child_slots when parent specifies it.\");                  \\\n    if (TypeName::_type_index != ::tvm::runtime::TypeIndex::kDynamic) {                        \\\n      return TypeName::_type_index;                                                            \\\n    }                                                                                          \\\n    return _GetOrAllocRuntimeTypeIndex();                                                      \\\n  }                                                                                            \\\n  static uint32_t _GetOrAllocRuntimeTypeIndex() {                                              \\\n    static uint32_t tindex = Object::GetOrAllocRuntimeTypeIndex(                               \\\n        TypeName::_type_key, TypeName::_type_index, ParentType::_GetOrAllocRuntimeTypeIndex(), \\\n        TypeName::_type_child_slots, TypeName::_type_child_slots_can_overflow);                \\\n    return tindex;                                                                             \\\n  }\n\n/*!\n * \\brief helper macro to declare type information in a final class.\n * \\param TypeName The name of the current type.\n * \\param ParentType The name of the ParentType\n */\n#define TVM_DECLARE_FINAL_OBJECT_INFO(TypeName, ParentType) \\\n  static const constexpr bool _type_final = true;           \\\n  static const constexpr int _type_child_slots = 0;         \\\n  TVM_DECLARE_BASE_OBJECT_INFO(TypeName, ParentType)\n\n/*! \\brief helper macro to suppress unused warning */\n#if defined(__GNUC__)\n#define TVM_ATTRIBUTE_UNUSED __attribute__((unused))\n#else\n#define TVM_ATTRIBUTE_UNUSED\n#endif\n\n#define TVM_STR_CONCAT_(__x, __y) __x##__y\n#define TVM_STR_CONCAT(__x, __y) TVM_STR_CONCAT_(__x, __y)\n\n#define TVM_OBJECT_REG_VAR_DEF static TVM_ATTRIBUTE_UNUSED uint32_t __make_Object_tid\n\n/*!\n * \\brief Helper macro to register the object type to runtime.\n *  Makes sure that the runtime type table is correctly populated.\n *\n *  Use this macro in the cc file for each terminal class.\n */\n#define TVM_REGISTER_OBJECT_TYPE(TypeName) \\\n  TVM_STR_CONCAT(TVM_OBJECT_REG_VAR_DEF, __COUNTER__) = TypeName::_GetOrAllocRuntimeTypeIndex()\n\n/*\n * \\brief Define the default copy/move constructor and assign operator\n * \\param TypeName The class typename.\n */\n#define TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(TypeName) \\\n  TypeName(const TypeName& other) = default;              \\\n  TypeName(TypeName&& other) = default;                   \\\n  TypeName& operator=(const TypeName& other) = default;   \\\n  TypeName& operator=(TypeName&& other) = default;\n\n/*\n * \\brief Define object reference methods.\n * \\param TypeName The object type name\n * \\param ParentType The parent type of the objectref\n * \\param ObjectName The type name of the object.\n */\n#define TVM_DEFINE_OBJECT_REF_METHODS(TypeName, ParentType, ObjectName)                        \\\n  TypeName() = default;                                                                        \\\n  explicit TypeName(::tvm::runtime::ObjectPtr<::tvm::runtime::Object> n) : ParentType(n) {}    \\\n  TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(TypeName);                                           \\\n  const ObjectName* operator->() const { return static_cast<const ObjectName*>(data_.get()); } \\\n  const ObjectName* get() const { return operator->(); }                                       \\\n  using ContainerType = ObjectName;\n\n/*\n * \\brief Define object reference methods that is not nullable.\n *\n * \\param TypeName The object type name\n * \\param ParentType The parent type of the objectref\n * \\param ObjectName The type name of the object.\n */\n#define TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TypeName, ParentType, ObjectName)            \\\n  explicit TypeName(::tvm::runtime::ObjectPtr<::tvm::runtime::Object> n) : ParentType(n) {}    \\\n  TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(TypeName);                                           \\\n  const ObjectName* operator->() const { return static_cast<const ObjectName*>(data_.get()); } \\\n  const ObjectName* get() const { return operator->(); }                                       \\\n  static constexpr bool _type_is_nullable = false;                                             \\\n  using ContainerType = ObjectName;\n\n/*\n * \\brief Define object reference methods of whose content is mutable.\n * \\param TypeName The object type name\n * \\param ParentType The parent type of the objectref\n * \\param ObjectName The type name of the object.\n * \\note We recommend making objects immutable when possible.\n *       This macro is only reserved for objects that stores runtime states.\n */\n#define TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(TypeName, ParentType, ObjectName)             \\\n  TypeName() = default;                                                                     \\\n  TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(TypeName);                                        \\\n  explicit TypeName(::tvm::runtime::ObjectPtr<::tvm::runtime::Object> n) : ParentType(n) {} \\\n  ObjectName* operator->() const { return static_cast<ObjectName*>(data_.get()); }          \\\n  using ContainerType = ObjectName;\n\n/*\n * \\brief Define object reference methods that is both not nullable and mutable.\n *\n * \\param TypeName The object type name\n * \\param ParentType The parent type of the objectref\n * \\param ObjectName The type name of the object.\n */\n#define TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(TypeName, ParentType, ObjectName) \\\n  explicit TypeName(::tvm::runtime::ObjectPtr<::tvm::runtime::Object> n) : ParentType(n) {} \\\n  TVM_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN(TypeName);                                        \\\n  ObjectName* operator->() const { return static_cast<ObjectName*>(data_.get()); }          \\\n  ObjectName* get() const { return operator->(); }                                          \\\n  static constexpr bool _type_is_nullable = false;                                          \\\n  using ContainerType = ObjectName;\n\n/*!\n * \\brief Define CopyOnWrite function in an ObjectRef.\n * \\param ObjectName The Type of the Node.\n *\n *  CopyOnWrite will generate a unique copy of the internal node.\n *  The node will be copied if it is referenced by multiple places.\n *  The function returns the raw pointer to the node to allow modification\n *  of the content.\n *\n * \\code\n *\n *  MyCOWObjectRef ref, ref2;\n *  ref2 = ref;\n *  ref.CopyOnWrite()->value = new_value;\n *  assert(ref2->value == old_value);\n *  assert(ref->value == new_value);\n *\n * \\endcode\n */\n#define TVM_DEFINE_OBJECT_REF_COW_METHOD(ObjectName)     \\\n  ObjectName* CopyOnWrite() {                            \\\n    ICHECK(data_ != nullptr);                            \\\n    if (!data_.unique()) {                               \\\n      auto n = make_object<ObjectName>(*(operator->())); \\\n      ObjectPtr<Object>(std::move(n)).swap(data_);       \\\n    }                                                    \\\n    return static_cast<ObjectName*>(data_.get());        \\\n  }\n\n// Implementations details below\n// Object reference counting.\n#if TVM_OBJECT_ATOMIC_REF_COUNTER\n\ninline void Object::IncRef() { ref_counter_.fetch_add(1, std::memory_order_relaxed); }\n\ninline void Object::DecRef() {\n  if (ref_counter_.fetch_sub(1, std::memory_order_release) == 1) {\n    std::atomic_thread_fence(std::memory_order_acquire);\n    if (this->deleter_ != nullptr) {\n      (*this->deleter_)(this);\n    }\n  }\n}\n\ninline int Object::use_count() const { return ref_counter_.load(std::memory_order_relaxed); }\n\n#else\n\ninline void Object::IncRef() { ++ref_counter_; }\n\ninline void Object::DecRef() {\n  if (--ref_counter_ == 0) {\n    if (this->deleter_ != nullptr) {\n      (*this->deleter_)(this);\n    }\n  }\n}\n\ninline int Object::use_count() const { return ref_counter_; }\n\n#endif  // TVM_OBJECT_ATOMIC_REF_COUNTER\n\ntemplate <typename TargetType>\ninline bool Object::IsInstance() const {\n  const Object* self = this;\n  // NOTE: the following code can be optimized by\n  // compiler dead-code elimination for already known constants.\n  if (self != nullptr) {\n    // Everything is a subclass of object.\n    if (std::is_same<TargetType, Object>::value) return true;\n    if (TargetType::_type_final) {\n      // if the target type is a final type\n      // then we only need to check the equivalence.\n      return self->type_index_ == TargetType::RuntimeTypeIndex();\n    } else {\n      // if target type is a non-leaf type\n      // Check if type index falls into the range of reserved slots.\n      uint32_t begin = TargetType::RuntimeTypeIndex();\n      // The condition will be optimized by constant-folding.\n      if (TargetType::_type_child_slots != 0) {\n        uint32_t end = begin + TargetType::_type_child_slots;\n        if (self->type_index_ >= begin && self->type_index_ < end) return true;\n      } else {\n        if (self->type_index_ == begin) return true;\n      }\n      if (!TargetType::_type_child_slots_can_overflow) return false;\n      // Invariance: parent index is always smaller than the child.\n      if (self->type_index_ < TargetType::RuntimeTypeIndex()) return false;\n      // The rare slower-path, check type hierarchy.\n      return self->DerivedFrom(TargetType::RuntimeTypeIndex());\n    }\n  } else {\n    return false;\n  }\n}\n\ninline bool Object::unique() const { return use_count() == 1; }\n\ntemplate <typename ObjectType>\ninline const ObjectType* ObjectRef::as() const {\n  if (data_ != nullptr && data_->IsInstance<ObjectType>()) {\n    return static_cast<ObjectType*>(data_.get());\n  } else {\n    return nullptr;\n  }\n}\n\ntemplate <typename RefType, typename ObjType>\ninline RefType GetRef(const ObjType* ptr) {\n  static_assert(std::is_base_of<typename RefType::ContainerType, ObjType>::value,\n                \"Can only cast to the ref of same container type\");\n  if (!RefType::_type_is_nullable) {\n    ICHECK(ptr != nullptr);\n  }\n  return RefType(ObjectPtr<Object>(const_cast<Object*>(static_cast<const Object*>(ptr))));\n}\n\ntemplate <typename BaseType, typename ObjType>\ninline ObjectPtr<BaseType> GetObjectPtr(ObjType* ptr) {\n  static_assert(std::is_base_of<BaseType, ObjType>::value,\n                \"Can only cast to the ref of same container type\");\n  return ObjectPtr<BaseType>(static_cast<Object*>(ptr));\n}\n\ntemplate <typename SubRef, typename BaseRef>\ninline SubRef Downcast(BaseRef ref) {\n  if (ref.defined()) {\n    ICHECK(ref->template IsInstance<typename SubRef::ContainerType>())\n        << \"Downcast from \" << ref->GetTypeKey() << \" to \" << SubRef::ContainerType::_type_key\n        << \" failed.\";\n  } else {\n    ICHECK(SubRef::_type_is_nullable) << \"Downcast from nullptr to not nullable reference of \"\n                                      << SubRef::ContainerType::_type_key;\n  }\n  return SubRef(std::move(ref.data_));\n}\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_OBJECT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/packed_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/packed_func.h\n * \\brief Type-erased function used across TVM API.\n */\n#ifndef TVM_RUNTIME_PACKED_FUNC_H_\n#define TVM_RUNTIME_PACKED_FUNC_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <limits>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n// Whether use TVM runtime in header only mode.\n#ifndef TVM_RUNTIME_HEADER_ONLY\n#define TVM_RUNTIME_HEADER_ONLY 0\n#endif\n\nnamespace tvm {\nnamespace runtime {\n\n// forward declarations\nclass TVMArgs;\nclass TVMArgValue;\nclass TVMMovableArgValueWithContext_;\nclass TVMRetValue;\nclass TVMArgsSetter;\ntemplate <typename FType>\nclass TypedPackedFunc;\ntemplate <typename TSignature>\nstruct SignaturePrinter;\n\n/*!\n * \\brief Object container class that backs PackedFunc.\n * \\note Do not use this function directly, use PackedFunc.\n */\nclass PackedFuncObj : public Object {\n public:\n  /*!\n   * \\brief Call the function in packed format.\n   * \\param args The arguments\n   * \\param rv The return value.\n   */\n  TVM_ALWAYS_INLINE void CallPacked(TVMArgs args, TVMRetValue* rv) const;\n\n  static constexpr const uint32_t _type_index = TypeIndex::kRuntimePackedFunc;\n  static constexpr const char* _type_key = \"runtime.PackedFunc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PackedFuncObj, Object);\n\n protected:\n  /*!\n   * \\brief Internal struct for extracting the callable method from callable type.\n   */\n  template <class TPackedFuncSubObj>\n  struct Extractor {\n    /*!\n     * \\brief Extracting the callable method from callable type.\n     * \\param obj The base packed function object class.\n     * \\param args The arguments\n     * \\param rv The return value.\n     */\n    static void Call(const PackedFuncObj* obj, TVMArgs args, TVMRetValue* rv);\n  };\n\n  /*! \\brief The internal callable function type. */\n  using FCallPacked = void(const PackedFuncObj*, TVMArgs, TVMRetValue*);\n\n  /*!\n   * \\brief Constructing a packed function object from a function pointer.\n   * \\param f_call_pack The function pointer used to call the packed function.\n   */\n  explicit PackedFuncObj(FCallPacked* f_call_pack) : f_call_packed_(f_call_pack) {}\n\n  /*! \\brief Delete the default constructor explicitly. */\n  PackedFuncObj() = delete;\n\n  /*! \\brief Internal callable function pointer used to call the packed function. */\n  FCallPacked* f_call_packed_;\n};\n\n/*! \\brief Derived object class for constructing PackedFuncObj. */\ntemplate <class TCallable>\nclass PackedFuncSubObj : public PackedFuncObj {\n  using TStorage = typename std::remove_cv<typename std::remove_reference<TCallable>::type>::type;\n\n public:\n  /*! \\brief The type of derived object class */\n  using TSelf = PackedFuncSubObj<TCallable>;\n  /*!\n   * \\brief Derived object class for constructing PackedFuncObj.\n   * \\param callable The type-erased callable object.\n   */\n  explicit PackedFuncSubObj(TCallable callable)\n      : PackedFuncObj(Extractor<TSelf>::Call), callable_(callable) {}\n  /*! \\brief Type-erased filed for storing callable object*/\n  mutable TStorage callable_;\n};\n\n/*!\n * \\brief Packed function is a type-erased function.\n *  The arguments are passed by packed format.\n *\n *  This is an useful unified interface to call generated functions,\n *  It is the unified function function type of TVM.\n *  It corresponds to TVMFunctionHandle in C runtime API.\n */\nclass PackedFunc : public ObjectRef {\n public:\n  /*! \\brief Constructor from null */\n  PackedFunc(std::nullptr_t null) : ObjectRef(nullptr) {}  // NOLINT(*)\n  /*!\n   * \\brief Constructing a packed function from a callable type\n   *        whose signature is consistent with `PackedFunc`\n   * \\param data the internal container of packed function.\n   */\n  template <typename TCallable,\n            typename = std::enable_if_t<\n                std::is_convertible<TCallable, std::function<void(TVMArgs, TVMRetValue*)>>::value &&\n                !std::is_base_of<TCallable, PackedFunc>::value>>\n  explicit PackedFunc(TCallable data) {\n    using ObjType = PackedFuncSubObj<TCallable>;\n    data_ = make_object<ObjType>(std::forward<TCallable>(data));\n  }\n  /*!\n   * \\brief Call packed function by directly passing in unpacked format.\n   * \\param args Arguments to be passed.\n   * \\tparam Args arguments to be passed.\n   *\n   * \\code\n   *   // Example code on how to call packed function\n   *   void CallPacked(PackedFunc f) {\n   *     // call like normal functions by pass in arguments\n   *     // return value is automatically converted back\n   *     int rvalue = f(1, 2.0);\n   *   }\n   * \\endcode\n   */\n  template <typename... Args>\n  inline TVMRetValue operator()(Args&&... args) const;\n  /*!\n   * \\brief Call the function in packed format.\n   * \\param args The arguments\n   * \\param rv The return value.\n   */\n  TVM_ALWAYS_INLINE void CallPacked(TVMArgs args, TVMRetValue* rv) const;\n  /*! \\return Whether the packed function is nullptr */\n  bool operator==(std::nullptr_t null) const { return data_ == nullptr; }\n  /*! \\return Whether the packed function is not nullptr */\n  bool operator!=(std::nullptr_t null) const { return data_ != nullptr; }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PackedFunc, ObjectRef, PackedFuncObj);\n};\n\n/*! \\brief Using static function to output TypedPackedFunc signature */\nusing FSig = std::string();\n\n/*!\n * \\brief Please refer to \\ref TypedPackedFuncAnchor \"TypedPackedFunc<R(Args..)>\"\n */\ntemplate <typename FType>\nclass TypedPackedFunc;\n\n/*!\n * \\anchor TypedPackedFuncAnchor\n * \\brief A PackedFunc wrapper to provide typed function signature.\n * It is backed by a PackedFunc internally.\n *\n * TypedPackedFunc enables compile time type checking.\n * TypedPackedFunc works with the runtime system:\n * - It can be passed as an argument of PackedFunc.\n * - It can be assigned to TVMRetValue.\n * - It can be directly converted to a type-erased PackedFunc.\n *\n * Developers should prefer TypedPackedFunc over PackedFunc in C++ code\n * as it enables compile time checking.\n * We can construct a TypedPackedFunc from a lambda function\n * with the same signature.\n *\n * \\code\n *  // user defined lambda function.\n *  auto addone = [](int x)->int {\n *    return x + 1;\n *  };\n *  // We can directly convert\n *  // lambda function to TypedPackedFunc\n *  TypedPackedFunc<int(int)> ftyped(addone);\n *  // invoke the function.\n *  int y = ftyped(1);\n *  // Can be directly converted to PackedFunc\n *  PackedFunc packed = ftype;\n * \\endcode\n * \\tparam R The return value of the function.\n * \\tparam Args The argument signature of the function.\n */\ntemplate <typename R, typename... Args>\nclass TypedPackedFunc<R(Args...)> {\n public:\n  /*! \\brief short hand for this function type */\n  using TSelf = TypedPackedFunc<R(Args...)>;\n  /*! \\brief default constructor */\n  TypedPackedFunc() {}\n  /*! \\brief constructor from null */\n  TypedPackedFunc(std::nullptr_t null) {}  // NOLINT(*)\n  /*!\n   * \\brief construct by wrap a PackedFunc\n   *\n   * Example usage:\n   * \\code\n   * PackedFunc packed([](TVMArgs args, TVMRetValue *rv) {\n   *   int x = args[0];\n   *   *rv = x + 1;\n   *  });\n   * // construct from packed function\n   * TypedPackedFunc<int(int)> ftyped(packed);\n   * // call the typed version.\n   * ICHECK_EQ(ftyped(1), 2);\n   * \\endcode\n   *\n   * \\param packed The packed function\n   */\n  inline TypedPackedFunc(PackedFunc packed);  // NOLINT(*)\n  /*!\n   * \\brief constructor from TVMRetValue\n   * \\param value The TVMRetValue\n   */\n  inline TypedPackedFunc(const TVMRetValue& value);  // NOLINT(*)\n  /*!\n   * \\brief constructor from TVMArgValue\n   * \\param value The TVMArgValue\n   */\n  inline TypedPackedFunc(const TVMArgValue& value);  // NOLINT(*)\n  /*!\n   * \\brief constructor from TVMMovableArgValue_\n   * \\param value The TVMMovableArgValue_\n   */\n  inline TypedPackedFunc(TVMMovableArgValueWithContext_&& value);  // NOLINT(*)\n  /*!\n   * \\brief construct from a lambda function with the same signature.\n   *\n   * Example usage:\n   * \\code\n   * auto typed_lambda = [](int x)->int { return x + 1; }\n   * // construct from packed function\n   * TypedPackedFunc<int(int)> ftyped(typed_lambda, \"add_one\");\n   * // call the typed version.\n   * ICHECK_EQ(ftyped(1), 2);\n   * \\endcode\n   *\n   * \\param typed_lambda typed lambda function.\n   * \\param name the name of the lambda function.\n   * \\tparam FLambda the type of the lambda function.\n   */\n  template <typename FLambda, typename = typename std::enable_if<std::is_convertible<\n                                  FLambda, std::function<R(Args...)>>::value>::type>\n  TypedPackedFunc(const FLambda& typed_lambda, std::string name) {  // NOLINT(*)\n    this->AssignTypedLambda(typed_lambda, name);\n  }\n  /*!\n   * \\brief construct from a lambda function with the same signature.\n   *\n   * This version does not take a name. It is highly recommend you use the\n   * version that takes a name for the lambda.\n   *\n   * Example usage:\n   * \\code\n   * auto typed_lambda = [](int x)->int { return x + 1; }\n   * // construct from packed function\n   * TypedPackedFunc<int(int)> ftyped(typed_lambda);\n   * // call the typed version.\n   * ICHECK_EQ(ftyped(1), 2);\n   * \\endcode\n   *\n   * \\param typed_lambda typed lambda function.\n   * \\tparam FLambda the type of the lambda function.\n   */\n  template <typename FLambda, typename = typename std::enable_if<std::is_convertible<\n                                  FLambda, std::function<R(Args...)>>::value>::type>\n  TypedPackedFunc(const FLambda& typed_lambda) {  // NOLINT(*)\n    this->AssignTypedLambda(typed_lambda);\n  }\n  /*!\n   * \\brief copy assignment operator from typed lambda\n   *\n   * Example usage:\n   * \\code\n   * // construct from packed function\n   * TypedPackedFunc<int(int)> ftyped;\n   * ftyped = [](int x) { return x + 1; }\n   * // call the typed version.\n   * ICHECK_EQ(ftyped(1), 2);\n   * \\endcode\n   *\n   * \\param typed_lambda typed lambda function.\n   * \\tparam FLambda the type of the lambda function.\n   * \\returns reference to self.\n   */\n  template <typename FLambda, typename = typename std::enable_if<\n                                  std::is_convertible<FLambda,\n                                                      std::function<R(Args...)>>::value>::type>\n  TSelf& operator=(FLambda typed_lambda) {  // NOLINT(*)\n    this->AssignTypedLambda(typed_lambda);\n    return *this;\n  }\n  /*!\n   * \\brief copy assignment operator from PackedFunc.\n   * \\param packed The packed function.\n   * \\returns reference to self.\n   */\n  TSelf& operator=(PackedFunc packed) {\n    packed_ = packed;\n    return *this;\n  }\n  /*!\n   * \\brief Invoke the operator.\n   * \\param args The arguments\n   * \\returns The return value.\n   */\n  TVM_ALWAYS_INLINE R operator()(Args... args) const;\n  /*!\n   * \\brief convert to PackedFunc\n   * \\return the internal PackedFunc\n   */\n  operator PackedFunc() const { return packed(); }\n  /*!\n   * \\return reference the internal PackedFunc\n   */\n  const PackedFunc& packed() const { return packed_; }\n  /*! \\return Whether the packed function is nullptr */\n  bool operator==(std::nullptr_t null) const { return packed_ == nullptr; }\n  /*! \\return Whether the packed function is not nullptr */\n  bool operator!=(std::nullptr_t null) const { return packed_ != nullptr; }\n\n private:\n  friend class TVMRetValue;\n  /*! \\brief The internal packed function */\n  PackedFunc packed_;\n  /*!\n   * \\brief Assign the packed field using a typed lambda function.\n   *\n   * \\param flambda The lambda function.\n   * \\param name The name associated with this lambda.\n   * \\tparam FLambda The lambda function type.\n   * \\note We capture the lambda when possible for maximum efficiency.\n   */\n  template <typename FLambda>\n  inline void AssignTypedLambda(FLambda flambda, std::string name);\n  /*!\n   * \\brief Assign the packed field using a typed lambda function. This variant is for functions\n   * without names.\n   *\n   * \\param flambda The lambda function.\n   * \\tparam FLambda The lambda function type.\n   * \\note We capture the lambda when possible for maximum efficiency.\n   */\n  template <typename FLambda>\n  inline void AssignTypedLambda(FLambda flambda);\n};\n\n/*! \\brief Arguments into TVM functions. */\nclass TVMArgs {\n public:\n  const TVMValue* values;\n  const int* type_codes;\n  int num_args;\n  /*!\n   * \\brief constructor\n   * \\param values The argument values\n   * \\param type_codes The argument type codes\n   * \\param num_args number of arguments.\n   */\n  TVMArgs(const TVMValue* values, const int* type_codes, int num_args)\n      : values(values), type_codes(type_codes), num_args(num_args) {}\n  /*! \\return size of the arguments */\n  inline int size() const;\n  /*!\n   * \\brief Get i-th argument\n   * \\param i the index.\n   * \\return the ith argument.\n   */\n  inline TVMArgValue operator[](int i) const;\n};\n\n/*!\n * \\brief Convert argument type code to string.\n * \\param type_code The input type code.\n * \\return The corresponding string repr.\n */\ninline const char* ArgTypeCode2Str(int type_code);\n\n// macro to check type code.\n#define TVM_CHECK_TYPE_CODE(CODE, T) \\\n  ICHECK_EQ(CODE, T) << \"expected \" << ArgTypeCode2Str(T) << \" but got \" << ArgTypeCode2Str(CODE)\n\n/*!\n * \\brief Type traits for runtime type check during FFI conversion.\n * \\tparam T the type to be checked.\n */\ntemplate <typename T>\nstruct ObjectTypeChecker {\n  /*!\n   * \\brief Check if an object matches the template type and return the\n   *        mismatched type if it exists.\n   * \\param ptr The object to check the type of.\n   * \\return An Optional containing the actual type of the pointer if it does not match the\n   *         template type. If the Optional does not contain a value, then the types match.\n   */\n  static Optional<String> CheckAndGetMismatch(const Object* ptr) {\n    using ContainerType = typename T::ContainerType;\n    if (ptr == nullptr) {\n      if (T::_type_is_nullable) {\n        return NullOpt;\n      } else {\n        return String(\"nullptr\");\n      }\n    }\n    if (ptr->IsInstance<ContainerType>()) {\n      return NullOpt;\n    } else {\n      return String(ptr->GetTypeKey());\n    }\n  }\n  /*!\n   * \\brief Check if an object matches the template type.\n   * \\param ptr The object to check the type of.\n   * \\return Whether or not the template type matches the objects type.\n   */\n  static bool Check(const Object* ptr) {\n    using ContainerType = typename T::ContainerType;\n    if (ptr == nullptr) return T::_type_is_nullable;\n    return ptr->IsInstance<ContainerType>();\n  }\n  static std::string TypeName() {\n    using ContainerType = typename T::ContainerType;\n    return ContainerType::_type_key;\n  }\n};\n\n// Additional overloads for PackedFunc checking.\ntemplate <typename T>\nstruct ObjectTypeChecker<Array<T>> {\n  static Optional<String> CheckAndGetMismatch(const Object* ptr) {\n    if (ptr == nullptr) {\n      return NullOpt;\n    }\n    if (!ptr->IsInstance<ArrayNode>()) {\n      return String(ptr->GetTypeKey());\n    }\n    const ArrayNode* n = static_cast<const ArrayNode*>(ptr);\n    for (size_t i = 0; i < n->size(); i++) {\n      const ObjectRef& p = (*n)[i];\n      Optional<String> check_subtype = ObjectTypeChecker<T>::CheckAndGetMismatch(p.get());\n      if (check_subtype.defined()) {\n        return String(\"Array[index \" + std::to_string(i) + \": \" + check_subtype.value() + \"]\");\n      }\n    }\n    return NullOpt;\n  }\n  static bool Check(const Object* ptr) {\n    if (ptr == nullptr) return true;\n    if (!ptr->IsInstance<ArrayNode>()) return false;\n    const ArrayNode* n = static_cast<const ArrayNode*>(ptr);\n    for (const ObjectRef& p : *n) {\n      if (!ObjectTypeChecker<T>::Check(p.get())) {\n        return false;\n      }\n    }\n    return true;\n  }\n  static std::string TypeName() { return \"Array[\" + ObjectTypeChecker<T>::TypeName() + \"]\"; }\n};\ntemplate <typename K, typename V>\nstruct ObjectTypeChecker<Map<K, V>> {\n  static Optional<String> CheckAndGetMismatch(const Object* ptr) {\n    if (ptr == nullptr) return NullOpt;\n    if (!ptr->IsInstance<MapNode>()) return String(ptr->GetTypeKey());\n    const MapNode* n = static_cast<const MapNode*>(ptr);\n    for (const auto& kv : *n) {\n      Optional<String> key_type = ObjectTypeChecker<K>::CheckAndGetMismatch(kv.first.get());\n      Optional<String> value_type = ObjectTypeChecker<K>::CheckAndGetMismatch(kv.first.get());\n      if (key_type.defined() || value_type.defined()) {\n        std::string key_name =\n            key_type.defined() ? std::string(key_type.value()) : ObjectTypeChecker<K>::TypeName();\n        std::string value_name = value_type.defined() ? std::string(value_type.value())\n                                                      : ObjectTypeChecker<V>::TypeName();\n        return String(\"Map[\" + key_name + \", \" + value_name + \"]\");\n      }\n    }\n    return NullOpt;\n  }\n  static bool Check(const Object* ptr) {\n    if (ptr == nullptr) return true;\n    if (!ptr->IsInstance<MapNode>()) return false;\n    const MapNode* n = static_cast<const MapNode*>(ptr);\n    for (const auto& kv : *n) {\n      if (!ObjectTypeChecker<K>::Check(kv.first.get())) return false;\n      if (!ObjectTypeChecker<V>::Check(kv.second.get())) return false;\n    }\n    return true;\n  }\n  static std::string TypeName() {\n    return \"Map[\" + ObjectTypeChecker<K>::TypeName() + \", \" + ObjectTypeChecker<V>::TypeName() +\n           ']';\n  }\n};\n\n/*!\n * \\brief Internal base class to\n *  handle conversion to POD values.\n */\nclass TVMPODValue_ {\n public:\n  operator double() const {\n    // Allow automatic conversion from int to float\n    // This avoids errors when user pass in int from\n    // the frontend while the API expects a float.\n    if (type_code_ == kDLInt) {\n      return static_cast<double>(value_.v_int64);\n    }\n    TVM_CHECK_TYPE_CODE(type_code_, kDLFloat);\n    return value_.v_float64;\n  }\n  operator int64_t() const {\n    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);\n    return value_.v_int64;\n  }\n  operator uint64_t() const {\n    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);\n    return value_.v_int64;\n  }\n  operator int() const {\n    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);\n    ICHECK_LE(value_.v_int64, std::numeric_limits<int>::max());\n    ICHECK_GE(value_.v_int64, std::numeric_limits<int>::min());\n    return static_cast<int>(value_.v_int64);\n  }\n  operator bool() const {\n    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);\n    return value_.v_int64 != 0;\n  }\n  operator void*() const {\n    if (type_code_ == kTVMNullptr) return nullptr;\n    if (type_code_ == kTVMDLTensorHandle) return value_.v_handle;\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMOpaqueHandle);\n    return value_.v_handle;\n  }\n  operator DLTensor*() const {\n    if (type_code_ == kTVMDLTensorHandle || type_code_ == kTVMNDArrayHandle) {\n      return static_cast<DLTensor*>(value_.v_handle);\n    } else {\n      if (type_code_ == kTVMNullptr) return nullptr;\n      LOG(FATAL) << \"Expected \"\n                 << \"DLTensor* or NDArray but got \" << ArgTypeCode2Str(type_code_);\n      return nullptr;\n    }\n  }\n  operator NDArray() const {\n    if (type_code_ == kTVMNullptr) return NDArray(ObjectPtr<Object>(nullptr));\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMNDArrayHandle);\n    return NDArray(NDArray::FFIDataFromHandle(static_cast<TVMArrayHandle>(value_.v_handle)));\n  }\n  operator Module() const {\n    if (type_code_ == kTVMNullptr) {\n      return Module(ObjectPtr<Object>(nullptr));\n    }\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMModuleHandle);\n    return Module(ObjectPtr<Object>(static_cast<Object*>(value_.v_handle)));\n  }\n  operator PackedFunc() const {\n    if (type_code_ == kTVMNullptr) {\n      return PackedFunc(ObjectPtr<Object>(nullptr));\n    }\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMPackedFuncHandle);\n    return PackedFunc(ObjectPtr<Object>(static_cast<Object*>(value_.v_handle)));\n  }\n  operator Device() const {\n    TVM_CHECK_TYPE_CODE(type_code_, kDLDevice);\n    return value_.v_device;\n  }\n  int type_code() const { return type_code_; }\n  /*!\n   * \\brief return handle as specific pointer type.\n   * \\tparam T the data type.\n   * \\return The pointer type.\n   */\n  template <typename T>\n  T* ptr() const {\n    return static_cast<T*>(value_.v_handle);\n  }\n  // ObjectRef handling\n  template <typename TObjectRef,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>\n  inline bool IsObjectRef() const;\n  template <typename TObjectRef>\n  inline TObjectRef AsObjectRef() const;\n\n protected:\n  friend class TVMArgsSetter;\n  friend class TVMRetValue;\n  friend class TVMMovableArgValue_;\n  TVMPODValue_() : type_code_(kTVMNullptr) {}\n  TVMPODValue_(TVMValue value, int type_code) : value_(value), type_code_(type_code) {}\n\n  /*! \\brief The value */\n  TVMValue value_;\n  /*! \\brief the type code */\n  int type_code_;\n};\n\n/*!\n * \\brief A single argument value to PackedFunc.\n *  Containing both type_code and TVMValue\n *\n *  Provides utilities to do type cast into other types.\n */\nclass TVMArgValue : public TVMPODValue_ {\n public:\n  /*! \\brief default constructor */\n  TVMArgValue() {}\n  /*!\n   * \\brief constructor\n   * \\param value of the function\n   * \\param type_code The type code.\n   */\n  TVMArgValue(TVMValue value, int type_code) : TVMPODValue_(value, type_code) {}\n  // reuse converter from parent\n  using TVMPODValue_::operator double;\n  using TVMPODValue_::operator int64_t;\n  using TVMPODValue_::operator uint64_t;\n  using TVMPODValue_::operator int;\n  using TVMPODValue_::operator bool;\n  using TVMPODValue_::operator void*;\n  using TVMPODValue_::operator DLTensor*;\n  using TVMPODValue_::operator NDArray;\n  using TVMPODValue_::operator Device;\n  using TVMPODValue_::operator Module;\n  using TVMPODValue_::operator PackedFunc;\n  using TVMPODValue_::AsObjectRef;\n  using TVMPODValue_::IsObjectRef;\n\n  // conversion operator.\n  operator std::string() const {\n    if (type_code_ == kTVMDataType) {\n      return DLDataType2String(operator DLDataType());\n    } else if (type_code_ == kTVMBytes) {\n      TVMByteArray* arr = static_cast<TVMByteArray*>(value_.v_handle);\n      return std::string(arr->data, arr->size);\n    } else if (type_code_ == kTVMStr) {\n      return std::string(value_.v_str);\n    } else {\n      ICHECK(IsObjectRef<tvm::runtime::String>())\n          << \"Could not convert TVM object of type \" << runtime::Object::TypeIndex2Key(type_code_)\n          << \" to a string.\";\n      return AsObjectRef<tvm::runtime::String>().operator std::string();\n    }\n  }\n  template <typename FType>\n  operator TypedPackedFunc<FType>() const {\n    return TypedPackedFunc<FType>(operator PackedFunc());\n  }\n  const TVMValue& value() const { return value_; }\n\n  template <typename T, typename = typename std::enable_if<std::is_class<T>::value>::type>\n  inline operator T() const;\n  inline operator DLDataType() const;\n  inline operator DataType() const;\n};\n\n/*!\n * \\brief Internal auxiliary struct for TypedPackedFunc to indicate a movable argument.\n *\n *  We can only construct a movable argument once from a single argument position.\n *  If the argument is passed as RValue reference, the result will be moved.\n *  We should only construct a MovableArg from an argument once,\n *  as the result will can moved.\n *\n * \\note For internal development purpose only.\n */\nclass TVMMovableArgValue_ : public TVMPODValue_ {\n public:\n  TVMMovableArgValue_(TVMValue value, int type_code) : TVMPODValue_(value, type_code) {}\n  // reuse converter from parent\n  using TVMPODValue_::operator double;\n  using TVMPODValue_::operator int64_t;\n  using TVMPODValue_::operator uint64_t;\n  using TVMPODValue_::operator int;\n  using TVMPODValue_::operator bool;\n  using TVMPODValue_::operator void*;\n  using TVMPODValue_::operator DLTensor*;\n  using TVMPODValue_::operator NDArray;\n  using TVMPODValue_::operator Device;\n  using TVMPODValue_::operator Module;\n  using TVMPODValue_::operator PackedFunc;\n  // reuse conversion rule from ArgValue.\n  operator std::string() const { return AsArgValue().operator std::string(); }\n  template <typename FType>\n  operator TypedPackedFunc<FType>() const {\n    return TypedPackedFunc<FType>(operator PackedFunc());\n  }\n  operator DLDataType() const { return AsArgValue().operator DLDataType(); }\n  operator DataType() const { return AsArgValue().operator DataType(); }\n  operator TVMArgValue() const { return AsArgValue(); }\n  /*!\n   * \\brief Helper converter function.\n   *  Try to move out an argument if possible,\n   *  fall back to normal argument conversion rule otherwise.\n   */\n  template <typename T,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, T>::value>::type>\n  inline operator T() const;\n\n private:\n  /*! \\return The arg value repr of the value. */\n  TVMArgValue AsArgValue() const { return TVMArgValue(value_, type_code_); }\n};\n\n/*!\n * \\brief Internal auxiliary struct for TypedPackedFunc to indicate a movable argument with\n * additional context information (function name and argument index) for better error reporting.\n *\n * \\sa MovableArgValue_\n * \\note For internal development purpose only.\n */\nclass TVMMovableArgValueWithContext_ {\n public:\n  /*!\n   * \\brief move constructor from another return value.\n   * \\param value The other return value.\n   * \\param type_code The code associated with the type of the value.\n   * \\param arg_index In a function call, this argument is at index arg_index (0-indexed).\n   * \\param optional_name Name of the function being called. Can be nullptr if the function is not.\n   * \\param f_sig Pointer to static function outputting signature of the function being called.\n   * named.\n   */\n  TVMMovableArgValueWithContext_(TVMValue value, int type_code, int arg_index,\n                                 const std::string* optional_name, FSig* f_sig)\n      : value_(value, type_code),\n        arg_index_(arg_index),\n        optional_name_(optional_name),\n        f_sig_(f_sig) {}\n\n  template <typename T>\n  operator T() const {\n    try {\n      return value_;  // implicit conversion happens here\n    } catch (dmlc::Error& e) {\n      LOG(FATAL) << \"In function \" << (optional_name_ == nullptr ? \"<anonymous>\" : *optional_name_)\n                 << (f_sig_ == nullptr ? \"\" : (*f_sig_)()) << \": error while converting argument \"\n                 << arg_index_ << \": \" << e.what();\n      throw;  // never reached, LOG(FATAL) throws, but this silences a warning.\n    }\n  }\n\n private:\n  TVMMovableArgValue_ value_;\n  int arg_index_;\n  const std::string* optional_name_;\n  FSig* f_sig_;\n};\n\n/*!\n * \\brief Return Value container,\n *  Unlike TVMArgValue, which only holds reference and do not delete\n *  the underlying container during destruction.\n *\n *  TVMRetValue holds value and will manage the underlying containers\n *  when it stores a complicated data type.\n */\nclass TVMRetValue : public TVMPODValue_ {\n public:\n  /*! \\brief default constructor */\n  TVMRetValue() {}\n  /*!\n   * \\brief move constructor from another return value.\n   * \\param other The other return value.\n   */\n  TVMRetValue(TVMRetValue&& other) : TVMPODValue_(other.value_, other.type_code_) {\n    other.value_.v_handle = nullptr;\n    other.type_code_ = kTVMNullptr;\n  }\n  /*! \\brief destructor */\n  ~TVMRetValue() { this->Clear(); }\n  // reuse converter from parent\n  using TVMPODValue_::operator double;\n  using TVMPODValue_::operator int64_t;\n  using TVMPODValue_::operator uint64_t;\n  using TVMPODValue_::operator int;\n  using TVMPODValue_::operator bool;\n  using TVMPODValue_::operator void*;\n  using TVMPODValue_::operator DLTensor*;\n  using TVMPODValue_::operator Device;\n  using TVMPODValue_::operator NDArray;\n  using TVMPODValue_::operator Module;\n  using TVMPODValue_::operator PackedFunc;\n  using TVMPODValue_::AsObjectRef;\n  using TVMPODValue_::IsObjectRef;\n\n  TVMRetValue(const TVMRetValue& other) : TVMPODValue_() { this->Assign(other); }\n  // conversion operators\n  operator std::string() const {\n    if (type_code_ == kTVMDataType) {\n      return DLDataType2String(operator DLDataType());\n    } else if (type_code_ == kTVMBytes) {\n      return *ptr<std::string>();\n    }\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMStr);\n    return *ptr<std::string>();\n  }\n  operator DLDataType() const {\n    if (type_code_ == kTVMStr) {\n      return String2DLDataType(operator std::string());\n    }\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMDataType);\n    return value_.v_type;\n  }\n  operator DataType() const { return DataType(operator DLDataType()); }\n  template <typename FType>\n  operator TypedPackedFunc<FType>() const {\n    return TypedPackedFunc<FType>(operator PackedFunc());\n  }\n  // Assign operators\n  TVMRetValue& operator=(TVMRetValue&& other) {\n    this->Clear();\n    value_ = other.value_;\n    type_code_ = other.type_code_;\n    other.type_code_ = kTVMNullptr;\n    return *this;\n  }\n  TVMRetValue& operator=(double value) {\n    this->SwitchToPOD(kDLFloat);\n    value_.v_float64 = value;\n    return *this;\n  }\n  TVMRetValue& operator=(std::nullptr_t value) {\n    this->SwitchToPOD(kTVMNullptr);\n    value_.v_handle = value;\n    return *this;\n  }\n  TVMRetValue& operator=(void* value) {\n    this->SwitchToPOD(kTVMOpaqueHandle);\n    value_.v_handle = value;\n    return *this;\n  }\n  TVMRetValue& operator=(int64_t value) {\n    this->SwitchToPOD(kDLInt);\n    value_.v_int64 = value;\n    return *this;\n  }\n  TVMRetValue& operator=(int value) {\n    this->SwitchToPOD(kDLInt);\n    value_.v_int64 = value;\n    return *this;\n  }\n  TVMRetValue& operator=(DLDevice value) {\n    this->SwitchToPOD(kDLDevice);\n    value_.v_device = value;\n    return *this;\n  }\n  TVMRetValue& operator=(DLDataType t) {\n    this->SwitchToPOD(kTVMDataType);\n    value_.v_type = t;\n    return *this;\n  }\n  TVMRetValue& operator=(const DataType& other) { return operator=(other.operator DLDataType()); }\n  TVMRetValue& operator=(bool value) {\n    this->SwitchToPOD(kDLInt);\n    value_.v_int64 = value;\n    return *this;\n  }\n  TVMRetValue& operator=(std::string value) {\n    this->SwitchToClass(kTVMStr, value);\n    return *this;\n  }\n  TVMRetValue& operator=(TVMByteArray value) {\n    this->SwitchToClass(kTVMBytes, std::string(value.data, value.size));\n    return *this;\n  }\n  TVMRetValue& operator=(NDArray other) {\n    if (other.data_ != nullptr) {\n      this->Clear();\n      type_code_ = kTVMNDArrayHandle;\n      value_.v_handle = NDArray::FFIGetHandle(other);\n      ObjectRef::FFIClearAfterMove(&other);\n    } else {\n      SwitchToPOD(kTVMNullptr);\n      value_.v_handle = nullptr;\n    }\n    return *this;\n  }\n  TVMRetValue& operator=(Module m) {\n    SwitchToObject(kTVMModuleHandle, std::move(m.data_));\n    return *this;\n  }\n  TVMRetValue& operator=(PackedFunc f) {\n    this->SwitchToObject(kTVMPackedFuncHandle, std::move(f.data_));\n    return *this;\n  }\n  template <typename FType>\n  TVMRetValue& operator=(const TypedPackedFunc<FType>& f) {\n    return operator=(f.packed());\n  }\n  TVMRetValue& operator=(const TVMRetValue& other) {  // NOLINT(*0\n    this->Assign(other);\n    return *this;\n  }\n  TVMRetValue& operator=(const TVMArgValue& other) {\n    this->Assign(other);\n    return *this;\n  }\n  TVMRetValue& operator=(TVMMovableArgValue_&& other) {\n    this->Assign(other);\n    return *this;\n  }\n  /*!\n   * \\brief Move the value back to front-end via C API.\n   *  This marks the current container as null.\n   *  The managed resources are moved to the front-end.\n   *  The front end should take charge in managing them.\n   *\n   * \\param ret_value The return value.\n   * \\param ret_type_code The return type code.\n   */\n  void MoveToCHost(TVMValue* ret_value, int* ret_type_code) {\n    // cannot move str; need specially handle.\n    ICHECK(type_code_ != kTVMStr && type_code_ != kTVMBytes);\n    *ret_value = value_;\n    *ret_type_code = type_code_;\n    type_code_ = kTVMNullptr;\n  }\n  /*!\n   * \\brief Construct a new TVMRetValue by\n   *        moving from return value stored via C API.\n   * \\param value the value.\n   * \\param type_code The type code.\n   * \\return The created TVMRetValue.\n   */\n  static TVMRetValue MoveFromCHost(TVMValue value, int type_code) {\n    // Can move POD and everything under the object system.\n    ICHECK(type_code <= kTVMPackedFuncHandle || type_code == kTVMNDArrayHandle);\n    TVMRetValue ret;\n    ret.value_ = value;\n    ret.type_code_ = type_code;\n    return ret;\n  }\n  /*! \\return The value field, if the data is POD */\n  const TVMValue& value() const {\n    ICHECK(type_code_ != kTVMObjectHandle && type_code_ != kTVMPackedFuncHandle &&\n           type_code_ != kTVMModuleHandle && type_code_ != kTVMStr)\n        << \"TVMRetValue.value can only be used for POD data\";\n    return value_;\n  }\n  // ObjectRef handling\n  template <typename TObjectRef,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>\n  inline TVMRetValue& operator=(TObjectRef other);\n  template <typename T, typename = typename std::enable_if<std::is_class<T>::value>::type>\n  inline operator T() const;\n\n private:\n  template <typename T>\n  void Assign(const T& other) {\n    switch (other.type_code()) {\n      case kTVMStr: {\n        SwitchToClass<std::string>(kTVMStr, other);\n        break;\n      }\n      case kTVMBytes: {\n        SwitchToClass<std::string>(kTVMBytes, other);\n        break;\n      }\n      case kTVMPackedFuncHandle: {\n        *this = other.operator PackedFunc();\n        break;\n      }\n      case kTVMModuleHandle: {\n        *this = other.operator Module();\n        break;\n      }\n      case kTVMNDArrayHandle: {\n        *this = other.operator NDArray();\n        break;\n      }\n      case kTVMObjectHandle: {\n        // Avoid operator ObjectRef as we already know it is not NDArray/Module\n        SwitchToObject(kTVMObjectHandle,\n                       GetObjectPtr<Object>(static_cast<Object*>(other.value_.v_handle)));\n        break;\n      }\n      case kTVMObjectRValueRefArg: {\n        operator=(other.operator ObjectRef());\n        break;\n      }\n      default: {\n        SwitchToPOD(other.type_code());\n        value_ = other.value_;\n        break;\n      }\n    }\n  }\n  // get the internal container.\n  void SwitchToPOD(int type_code) {\n    if (type_code_ != type_code) {\n      this->Clear();\n      type_code_ = type_code;\n    }\n  }\n  template <typename T>\n  void SwitchToClass(int type_code, T v) {\n    if (type_code_ != type_code) {\n      this->Clear();\n      type_code_ = type_code;\n      value_.v_handle = new T(v);\n    } else {\n      *static_cast<T*>(value_.v_handle) = v;\n    }\n  }\n  void SwitchToObject(int type_code, ObjectPtr<Object> other) {\n    if (other.data_ != nullptr) {\n      this->Clear();\n      type_code_ = type_code;\n      // move the handle out\n      value_.v_handle = other.data_;\n      other.data_ = nullptr;\n    } else {\n      SwitchToPOD(kTVMNullptr);\n      value_.v_handle = nullptr;\n    }\n  }\n  void Clear() {\n    if (type_code_ == kTVMNullptr) return;\n    switch (type_code_) {\n      case kTVMStr:\n      case kTVMBytes:\n        delete ptr<std::string>();\n        break;\n      case kTVMPackedFuncHandle:\n        static_cast<Object*>(value_.v_handle)->DecRef();\n        break;\n      case kTVMNDArrayHandle: {\n        NDArray::FFIDecRef(static_cast<TVMArrayHandle>(value_.v_handle));\n        break;\n      }\n      case kTVMModuleHandle: {\n        static_cast<Object*>(value_.v_handle)->DecRef();\n        break;\n      }\n      case kTVMObjectHandle: {\n        static_cast<Object*>(value_.v_handle)->DecRef();\n        break;\n      }\n    }\n    type_code_ = kTVMNullptr;\n  }\n};\n\n/*!\n * \\brief Type trait to specify special value conversion rules from\n *        TVMArgValue and TVMRetValue.\n *\n *  The trait can be specialized to add type specific conversion logic\n *  from the TVMArgvalue and TVMRetValue.\n *\n * \\tparam TObjectRef the specific ObjectRefType.\n */\ntemplate <typename TObjectRef>\nstruct PackedFuncValueConverter {\n  /*!\n   * \\brief Convert a TObjectRef from an argument value.\n   * \\param val The argument value.\n   * \\return the converted result.\n   */\n  static TObjectRef From(const TVMArgValue& val) { return val.AsObjectRef<TObjectRef>(); }\n  /*!\n   * \\brief Convert a TObjectRef from a return value.\n   * \\param val The argument value.\n   * \\return the converted result.\n   */\n  static TObjectRef From(const TVMRetValue& val) { return val.AsObjectRef<TObjectRef>(); }\n};\n\n/*!\n * \\brief Export a function with the PackedFunc signature\n *        as a PackedFunc that can be loaded by LibraryModule.\n *\n * \\param ExportName The symbol name to be exported.\n * \\param Function The function with PackedFunc signature.\n * \\sa PackedFunc\n *\n * \\code\n *\n * void AddOne_(TVMArgs args, TVMRetValue* rv) {\n *   int value = args[0];\n *   *rv = value + 1;\n * }\n * // Expose the function as \"AddOne\"\n * TVM_DLL_EXPORT_PACKED_FUNC(AddOne, AddOne_);\n *\n * \\endcode\n */\n#define TVM_DLL_EXPORT_PACKED_FUNC(ExportName, Function)                                    \\\n  extern \"C\" {                                                                              \\\n  TVM_DLL int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value, \\\n                         int* out_type_code, void* resource_handle);                        \\\n  int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value,         \\\n                 int* out_type_code, void* resource_handle) {                               \\\n    try {                                                                                   \\\n      ::tvm::runtime::TVMRetValue rv;                                                       \\\n      Function(::tvm::runtime::TVMArgs(args, type_code, num_args), &rv);                    \\\n      rv.MoveToCHost(out_value, out_type_code);                                             \\\n      return 0;                                                                             \\\n    } catch (const ::std::exception& _except_) {                                            \\\n      TVMAPISetLastError(_except_.what());                                                  \\\n      return -1;                                                                            \\\n    }                                                                                       \\\n  }                                                                                         \\\n  }\n\n/*!\n * \\brief Export typed function as a PackedFunc\n *        that can be loaded by LibraryModule.\n *\n * \\param ExportName The symbol name to be exported.\n * \\param Function The typed function.\n * \\note ExportName and Function must be different,\n *       see code examples below.\n *\n * \\sa TypedPackedFunc\n *\n * \\code\n *\n * int AddOne_(int x) {\n *   return x + 1;\n * }\n *\n * // Expose the function as \"AddOne\"\n * TVM_DLL_EXPORT_TYPED_FUNC(AddOne, AddOne_);\n *\n * // Expose the function as \"SubOne\"\n * TVM_DLL_EXPORT_TYPED_FUNC(SubOne, [](int x) {\n *   return x - 1;\n * });\n *\n * // The following code will cause compilation error.\n * // Because the same Function and ExportName\n * // TVM_DLL_EXPORT_TYPED_FUNC(AddOne_, AddOne_);\n *\n * // The following code is OK, assuming the macro\n * // is in a different namespace from xyz\n * // TVM_DLL_EXPORT_TYPED_FUNC(AddOne_, xyz::AddOne_);\n *\n * \\endcode\n */\n#define TVM_DLL_EXPORT_TYPED_FUNC(ExportName, Function)                                     \\\n  extern \"C\" {                                                                              \\\n  TVM_DLL int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value, \\\n                         int* out_type_code, void* resource_handle) {                       \\\n    try {                                                                                   \\\n      auto f = Function;                                                                    \\\n      using FType = ::tvm::runtime::detail::function_signature<decltype(f)>::FType;         \\\n      ::tvm::runtime::TVMRetValue rv;                                                       \\\n      ::tvm::runtime::detail::unpack_call_by_signature<FType>::run(                         \\\n          f, ::tvm::runtime::TVMArgs(args, type_code, num_args), &rv);                      \\\n      rv.MoveToCHost(out_value, out_type_code);                                             \\\n      return 0;                                                                             \\\n    } catch (const ::std::exception& _except_) {                                            \\\n      TVMAPISetLastError(_except_.what());                                                  \\\n      return -1;                                                                            \\\n    }                                                                                       \\\n  }                                                                                         \\\n  }\n\ninline TVMArgValue TVMArgs::operator[](int i) const {\n  ICHECK_LT(i, num_args) << \"not enough argument passed, \" << num_args << \" passed\"\n                         << \" but request arg[\" << i << \"].\";\n  return TVMArgValue(values[i], type_codes[i]);\n}\n\ninline int TVMArgs::size() const { return num_args; }\n\ntemplate <class TPackedFuncSubObj>\nvoid PackedFuncObj::Extractor<TPackedFuncSubObj>::Call(const PackedFuncObj* obj, TVMArgs args,\n                                                       TVMRetValue* rv) {\n  (static_cast<const TPackedFuncSubObj*>(obj))->callable_(args, rv);\n}\n\nTVM_ALWAYS_INLINE void PackedFuncObj::CallPacked(TVMArgs args, TVMRetValue* rv) const {\n  (*f_call_packed_)(this, args, rv);\n}\n\nTVM_ALWAYS_INLINE void PackedFunc::CallPacked(TVMArgs args, TVMRetValue* rv) const {\n  (static_cast<PackedFuncObj*>(data_.get()))->CallPacked(args, rv);\n}\n\n// internal namespace\ninline const char* ArgTypeCode2Str(int type_code) {\n  switch (type_code) {\n    case kDLInt:\n      return \"int\";\n    case kDLUInt:\n      return \"uint\";\n    case kDLFloat:\n      return \"float\";\n    case kTVMStr:\n      return \"str\";\n    case kTVMBytes:\n      return \"bytes\";\n    case kTVMOpaqueHandle:\n      return \"handle\";\n    case kTVMNullptr:\n      return \"NULL\";\n    case kTVMDLTensorHandle:\n      return \"ArrayHandle\";\n    case kTVMDataType:\n      return \"DLDataType\";\n    case kDLDevice:\n      return \"DLDevice\";\n    case kTVMPackedFuncHandle:\n      return \"FunctionHandle\";\n    case kTVMModuleHandle:\n      return \"ModuleHandle\";\n    case kTVMNDArrayHandle:\n      return \"NDArrayContainer\";\n    case kTVMObjectHandle:\n      return \"Object\";\n    case kTVMObjectRValueRefArg:\n      return \"ObjectRValueRefArg\";\n    default:\n      LOG(FATAL) << \"unknown type_code=\" << static_cast<int>(type_code);\n      return \"\";\n  }\n}\n\nnamespace detail {\n\ntemplate <bool stop, std::size_t I, typename F>\nstruct for_each_dispatcher {\n  template <typename T, typename... Args>\n  static void run(const F& f, T&& value, Args&&... args) {  // NOLINT(*)\n    f(I, std::forward<T>(value));\n    for_each_dispatcher<sizeof...(Args) == 0, (I + 1), F>::run(f, std::forward<Args>(args)...);\n  }\n};\n\ntemplate <std::size_t I, typename F>\nstruct for_each_dispatcher<true, I, F> {\n  static void run(const F& f) {}  // NOLINT(*)\n};\n\ntemplate <typename F, typename... Args>\ninline void for_each(const F& f, Args&&... args) {  // NOLINT(*)\n  for_each_dispatcher<sizeof...(Args) == 0, 0, F>::run(f, std::forward<Args>(args)...);\n}\n\nnamespace parameter_pack {\n\ntemplate <typename... EnumArgs>\nstruct EnumeratedParamPack {\n  struct Invoke {\n    template <template <size_t i, typename TArgument> class Functor, typename... ExtraParams>\n    static void F(ExtraParams&&... extra_params) {\n      using TExpander = int[];\n      (void)TExpander{\n          0,\n          (Functor<EnumArgs::i, typename EnumArgs::T>::F(extra_params...), 0)...,\n      };\n    }\n  };\n};\n\ntemplate <typename... Args>\nstruct EnumerateImpl {\n private:\n  template <size_t _i, typename _T>\n  struct Item {\n    static const constexpr size_t i = _i;\n    using T = _T;\n  };\n\n  template <typename...>\n  struct Zipper;\n\n  template <std::size_t... id>\n  struct Zipper<std::integer_sequence<std::size_t, id...>> {\n    using T = EnumeratedParamPack<Item<id, Args>...>;\n  };\n\n public:\n  using T = typename Zipper<std::index_sequence_for<Args...>>::T;\n};\n\ntemplate <typename... Args>\nusing Enumerate = typename EnumerateImpl<Args...>::T;\n\ntemplate <typename... Args>\nstruct ParamPack {\n  template <template <size_t i, typename TArgument> class Functor, typename... ExtraParams>\n  static void InvokeWithoutArg(ExtraParams&&... extra_params) {\n    Enumerate<Args...>::Invoke::template F<Functor, ExtraParams...>(\n        std::forward<ExtraParams>(extra_params)...);\n  }\n};\n\n}  // namespace parameter_pack\n\n/*!\n * \\brief Template class to get function signature of a function or functor.\n * \\tparam T The function/functor type.\n */\ntemplate <typename T>\nstruct func_signature_helper {\n  using FType = void;\n};\n\ntemplate <typename T, typename R, typename... Args>\nstruct func_signature_helper<R (T::*)(Args...)> {\n  using FType = R(Args...);\n  using ParamType = parameter_pack::ParamPack<Args...>;\n  using RetType = R;\n  static_assert(!std::is_reference<R>::value, \"TypedPackedFunc return reference\");\n};\n\ntemplate <typename T, typename R, typename... Args>\nstruct func_signature_helper<R (T::*)(Args...) const> {\n  using FType = R(Args...);\n  using ParamType = parameter_pack::ParamPack<Args...>;\n  using RetType = R;\n  static_assert(!std::is_reference<R>::value, \"TypedPackedFunc return reference\");\n};\n\n/*!\n * \\brief Template class to get function signature of a function or functor.\n * \\tparam T The function/functor type.\n */\ntemplate <typename T>\nstruct function_signature {\n  using FType = typename func_signature_helper<decltype(&T::operator())>::FType;\n  using ParamType = typename func_signature_helper<decltype(&T::operator())>::ParamType;\n  using RetType = typename func_signature_helper<decltype(&T::operator())>::RetType;\n};\n\n// handle case of function.\ntemplate <typename R, typename... Args>\nstruct function_signature<R(Args...)> {\n  using FType = R(Args...);\n  using ParamType = parameter_pack::ParamPack<Args...>;\n  using RetType = R;\n  static_assert(!std::is_reference<R>::value, \"TypedPackedFunc return reference\");\n};\n\n// handle case of function ptr.\ntemplate <typename R, typename... Args>\nstruct function_signature<R (*)(Args...)> {\n  using FType = R(Args...);\n  using ParamType = detail::parameter_pack::ParamPack<Args...>;\n  using RetType = R;\n  static_assert(!std::is_reference<R>::value, \"TypedPackedFunc return reference\");\n};\n\ntemplate <typename TSignature>\nstruct SignaturePrinter;\n\nnamespace type2str {\n\ntemplate <typename T>\nstruct TypeSimplifier;\n\ntemplate <typename T>\nstruct Type2Str {\n  template <typename = std::enable_if_t<std::is_base_of<ObjectRef, T>::value>>\n  static std::string v() {\n    return T::ContainerType::_type_key;\n  }\n};\ntemplate <>\nstruct Type2Str<int> {\n  static std::string v() { return \"int\"; }\n};\ntemplate <>\nstruct Type2Str<double> {\n  static std::string v() { return \"double\"; }\n};\ntemplate <>\nstruct Type2Str<int64_t> {\n  static std::string v() { return \"int64_t\"; }\n};\ntemplate <>\nstruct Type2Str<uint64_t> {\n  static std::string v() { return \"uint64_t\"; }\n};\ntemplate <>\nstruct Type2Str<bool> {\n  static std::string v() { return \"bool\"; }\n};\ntemplate <>\nstruct Type2Str<void> {\n  static std::string v() { return \"void\"; }\n};\ntemplate <>\nstruct Type2Str<std::basic_string<char>> {\n  static std::string v() { return \"basic_string<char>\"; }\n};\ntemplate <typename K, typename V>\nstruct Type2Str<Map<K, V>> {\n  static std::string v() {\n    return \"Map<\" + TypeSimplifier<K>::v() + \", \" + TypeSimplifier<V>::v() + \">\";\n  }\n};\ntemplate <>\nstruct Type2Str<DLDevice> {\n  static std::string v() { return \"DLDevice\"; }\n};\ntemplate <>\nstruct Type2Str<DLTensor> {\n  static std::string v() { return \"DLTensor\"; }\n};\ntemplate <>\nstruct Type2Str<DataType> {\n  static std::string v() { return \"DataType\"; }\n};\ntemplate <>\nstruct Type2Str<DLDataType> {\n  static std::string v() { return \"DLDataType\"; }\n};\ntemplate <>\nstruct Type2Str<TVMRetValue> {\n  static std::string v() { return \"TVMRetValue\"; }\n};\ntemplate <>\nstruct Type2Str<TVMArgValue> {\n  static std::string v() { return \"TVMArgValue\"; }\n};\ntemplate <typename FType>\nstruct Type2Str<TypedPackedFunc<FType>> {\n  static std::string v() { return SignaturePrinter<function_signature<FType>>::F(); }\n};\ntemplate <typename T>\nstruct Type2Str<Array<T>> {\n  static std::string v() { return \"Array<\" + TypeSimplifier<T>::v() + \">\"; }\n};\n\n/*!\n * \\brief Template class to remove const, pointer and reference of original type.\n * \\tparam T The original type.\n */\ntemplate <typename T>\nstruct TypeSimplifier {\n  static std::string v() {\n    using U = typename std::remove_cv<\n        typename std::remove_reference<typename std::remove_pointer<T>::type>::type>::type;\n    return (std::is_const<T>::value ? \"const \" : \"\") + Type2Str<U>::v() +\n           (std::is_pointer<T>::value ? \"*\" : \"\") + (std::is_reference<T>::value ? \"&\" : \"\");\n  }\n};\n\n}  // namespace type2str\n\n/*!\n * \\brief Template class to generate static function outputting signature of a function or functor.\n * \\tparam TSignature The function/functor signature type generated by `function_signature`.\n */\ntemplate <typename TSignature>\nstruct SignaturePrinter {\n  using ParamType = typename TSignature::ParamType;\n  using RetType = typename TSignature::RetType;\n\n  template <size_t i, typename TArgument>\n  struct PrintParamType {\n    static void F(std::ostream& os) {\n      os << (i == 0 ? \"\" : \", \") << i << \": \" << type2str::TypeSimplifier<TArgument>::v();\n    }\n  };\n\n  static std::string F() {\n    std::ostringstream oss;\n    oss << \"(\";\n    ParamType::template InvokeWithoutArg<PrintParamType>(oss);\n    oss << \") -> \" << type2str::TypeSimplifier<RetType>::v();\n    return oss.str();\n  }\n};\n}  // namespace detail\n\n/* \\brief argument settter to PackedFunc */\nclass TVMArgsSetter {\n public:\n  TVMArgsSetter(TVMValue* values, int* type_codes) : values_(values), type_codes_(type_codes) {}\n  // setters for POD types\n  template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>\n  TVM_ALWAYS_INLINE void operator()(size_t i, T value) const {\n    values_[i].v_int64 = static_cast<int64_t>(value);\n    type_codes_[i] = kDLInt;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, uint64_t value) const {\n    values_[i].v_int64 = static_cast<int64_t>(value);\n    ICHECK_LE(value, static_cast<uint64_t>(std::numeric_limits<int64_t>::max()));\n    type_codes_[i] = kDLInt;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, double value) const {\n    values_[i].v_float64 = value;\n    type_codes_[i] = kDLFloat;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, std::nullptr_t value) const {\n    values_[i].v_handle = value;\n    type_codes_[i] = kTVMNullptr;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, const TVMArgValue& value) const {\n    values_[i] = value.value_;\n    type_codes_[i] = value.type_code_;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, void* value) const {\n    values_[i].v_handle = value;\n    type_codes_[i] = kTVMOpaqueHandle;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, DLTensor* value) const {\n    values_[i].v_handle = value;\n    type_codes_[i] = kTVMDLTensorHandle;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, Device value) const {\n    values_[i].v_device = value;\n    type_codes_[i] = kDLDevice;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, DLDataType value) const {\n    values_[i].v_type = value;\n    type_codes_[i] = kTVMDataType;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, DataType dtype) const {\n    operator()(i, dtype.operator DLDataType());\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, const char* value) const {\n    values_[i].v_str = value;\n    type_codes_[i] = kTVMStr;\n  }\n  // setters for container types\n  TVM_ALWAYS_INLINE void operator()(size_t i, const std::string& value) const {\n    values_[i].v_str = value.c_str();\n    type_codes_[i] = kTVMStr;\n  }\n  TVM_ALWAYS_INLINE void operator()(size_t i, const TVMByteArray& value) const {\n    values_[i].v_handle = const_cast<TVMByteArray*>(&value);\n    type_codes_[i] = kTVMBytes;\n  }\n  template <typename FType>\n  TVM_ALWAYS_INLINE void operator()(size_t i, const TypedPackedFunc<FType>& value) const {\n    operator()(i, value.packed());\n  }\n  void operator()(size_t i, const TVMRetValue& value) const {\n    if (value.type_code() == kTVMStr) {\n      values_[i].v_str = value.ptr<std::string>()->c_str();\n      type_codes_[i] = kTVMStr;\n    } else {\n      ICHECK_NE(value.type_code(), kTVMBytes) << \"not handled.\";\n      values_[i] = value.value_;\n      type_codes_[i] = value.type_code();\n    }\n  }\n  // ObjectRef handling\n  template <typename TObjectRef,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>\n  TVM_ALWAYS_INLINE void operator()(size_t i, const TObjectRef& value) const {\n    this->SetObject(i, value);\n  }\n\n  template <typename TObjectRef,\n            typename = typename std::enable_if<std::is_base_of<\n                ObjectRef, typename std::remove_reference<TObjectRef>::type>::value>::type>\n  TVM_ALWAYS_INLINE void operator()(size_t i, TObjectRef&& value) const {\n    this->SetObject(i, std::forward<TObjectRef>(value));\n  }\n\n private:\n  template <typename TObjectRef>\n  inline void SetObject(size_t i, TObjectRef&& value) const;\n  /*! \\brief The values fields */\n  TVMValue* values_;\n  /*! \\brief The type code fields */\n  int* type_codes_;\n};\n\ntemplate <typename... Args>\ninline TVMRetValue PackedFunc::operator()(Args&&... args) const {\n  const int kNumArgs = sizeof...(Args);\n  const int kArraySize = kNumArgs > 0 ? kNumArgs : 1;\n  TVMValue values[kArraySize];\n  int type_codes[kArraySize];\n  detail::for_each(TVMArgsSetter(values, type_codes), std::forward<Args>(args)...);\n  TVMRetValue rv;\n  (static_cast<PackedFuncObj*>(data_.get()))\n      ->CallPacked(TVMArgs(values, type_codes, kNumArgs), &rv);\n  return rv;\n}\n\nnamespace detail {\ntemplate <typename R, int nleft, int index, typename F>\nstruct unpack_call_dispatcher {\n  template <typename... Args>\n  TVM_ALWAYS_INLINE static void run(const std::string* optional_name, FSig* f_sig, const F& f,\n                                    const TVMArgs& args_pack, TVMRetValue* rv,\n                                    Args&&... unpacked_args) {\n    // construct a movable argument value\n    // which allows potential move of argument to the input of F.\n    unpack_call_dispatcher<R, nleft - 1, index + 1, F>::run(\n        optional_name, f_sig, f, args_pack, rv, std::forward<Args>(unpacked_args)...,\n        TVMMovableArgValueWithContext_(args_pack.values[index], args_pack.type_codes[index], index,\n                                       optional_name, f_sig));\n  }\n};\n\ntemplate <typename R, int index, typename F>\nstruct unpack_call_dispatcher<R, 0, index, F> {\n  template <typename... Args>\n  TVM_ALWAYS_INLINE static void run(const std::string* optional_name, FSig* f_sig, const F& f,\n                                    const TVMArgs& args_pack, TVMRetValue* rv,\n                                    Args&&... unpacked_args) {\n    using RetType = decltype(f(std::forward<Args>(unpacked_args)...));\n    if (std::is_same<RetType, R>::value) {\n      *rv = f(std::forward<Args>(unpacked_args)...);\n    } else {\n      *rv = R(f(std::forward<Args>(unpacked_args)...));\n    }\n  }\n};\n\ntemplate <int index, typename F>\nstruct unpack_call_dispatcher<void, 0, index, F> {\n  template <typename... Args>\n  TVM_ALWAYS_INLINE static void run(const std::string* optional_name, FSig* f_sig, const F& f,\n                                    const TVMArgs& args_pack, TVMRetValue* rv,\n                                    Args&&... unpacked_args) {\n    f(std::forward<Args>(unpacked_args)...);\n  }\n};\n\ntemplate <typename R, int nargs, typename F>\nTVM_ALWAYS_INLINE void unpack_call(const std::string* optional_name, const F& f,\n                                   const TVMArgs& args, TVMRetValue* rv) {\n  FSig* f_sig = detail::SignaturePrinter<detail::function_signature<F>>::F;\n  CHECK_EQ(nargs, args.size()) << \"Function \"\n                               << (optional_name == nullptr ? \"<anonymous>\" : *optional_name)\n                               << (f_sig == nullptr ? \"\" : (*f_sig)()) << \" expects \" << nargs\n                               << \" arguments but \" << args.size() << \" were provided\";\n  unpack_call_dispatcher<R, nargs, 0, F>::run(optional_name, f_sig, f, args, rv);\n}\n\ntemplate <typename FType>\nstruct unpack_call_by_signature {};\n\ntemplate <typename R, typename... Args>\nstruct unpack_call_by_signature<R(Args...)> {\n  template <typename F>\n  TVM_ALWAYS_INLINE static void run(const F& f, const TVMArgs& args, TVMRetValue* rv) {\n    unpack_call<R, sizeof...(Args)>(nullptr, f, args, rv);\n  }\n};\n\ntemplate <typename R, typename... Args>\nTVM_ALWAYS_INLINE R call_packed(const PackedFunc& pf, Args&&... args) {\n  return R(pf(std::forward<Args>(args)...));\n}\n\ntemplate <typename R>\nstruct typed_packed_call_dispatcher {\n  template <typename... Args>\n  TVM_ALWAYS_INLINE static R run(const PackedFunc& pf, Args&&... args) {\n    return pf(std::forward<Args>(args)...);\n  }\n};\n\ntemplate <>\nstruct typed_packed_call_dispatcher<void> {\n  template <typename... Args>\n  TVM_ALWAYS_INLINE static void run(const PackedFunc& pf, Args&&... args) {\n    pf(std::forward<Args>(args)...);\n  }\n};\n}  // namespace detail\n\ntemplate <typename R, typename... Args>\nTypedPackedFunc<R(Args...)>::TypedPackedFunc(PackedFunc packed) : packed_(packed) {}\n\ntemplate <typename R, typename... Args>\nTypedPackedFunc<R(Args...)>::TypedPackedFunc(const TVMRetValue& value)\n    : packed_(value.operator PackedFunc()) {}\n\ntemplate <typename R, typename... Args>\nTypedPackedFunc<R(Args...)>::TypedPackedFunc(const TVMArgValue& value)\n    : packed_(value.operator PackedFunc()) {}\n\ntemplate <typename R, typename... Args>\nTypedPackedFunc<R(Args...)>::TypedPackedFunc(TVMMovableArgValueWithContext_&& value)\n    : packed_(value.operator PackedFunc()) {}\n\ntemplate <typename R, typename... Args>\ntemplate <typename FType>\ninline void TypedPackedFunc<R(Args...)>::AssignTypedLambda(FType flambda, std::string name) {\n  FSig* f_sig = detail::SignaturePrinter<detail::function_signature<FType>>::F;\n  packed_ = PackedFunc([flambda, name, f_sig](const TVMArgs& args, TVMRetValue* rv) {\n    if (args.size() != sizeof...(Args)) {\n      LOG(FATAL) << \"Function \" << name << (f_sig == nullptr ? \"\" : (*f_sig)()) << \" expects \"\n                 << sizeof...(Args) << \" arguments, but \" << args.size() << \" were provided.\";\n    }\n    detail::unpack_call<R, sizeof...(Args)>(&name, flambda, args, rv);\n  });\n}\n\ntemplate <typename R, typename... Args>\ntemplate <typename FType>\ninline void TypedPackedFunc<R(Args...)>::AssignTypedLambda(FType flambda) {\n  FSig* f_sig = detail::SignaturePrinter<detail::function_signature<FType>>::F;\n  packed_ = PackedFunc([flambda, f_sig](const TVMArgs& args, TVMRetValue* rv) {\n    if (args.size() != sizeof...(Args)) {\n      LOG(FATAL) << \"Function <anonymous> \" << (*f_sig)() << \" expects \" << sizeof...(Args)\n                 << \" arguments, but \" << args.size() << \" were provided.\";\n    }\n    detail::unpack_call<R, sizeof...(Args)>(nullptr, flambda, args, rv);\n  });\n}\n\ntemplate <typename R, typename... Args>\nTVM_ALWAYS_INLINE R TypedPackedFunc<R(Args...)>::operator()(Args... args) const {\n  return detail::typed_packed_call_dispatcher<R>::run(packed_, std::forward<Args>(args)...);\n}\n\n// ObjectRef related conversion handling\n// Object can have three possible type codes:\n//      kTVMNDArrayHandle, kTVMModuleHandle, kTVMObjectHandle\n//\n// We use type traits to eliminate un-necessary checks.\ntemplate <typename T>\ninline void TVMArgsSetter::SetObject(size_t i, T&& value) const {\n  using ContainerType = typename std::remove_reference<T>::type::ContainerType;\n  if (value.defined()) {\n    Object* ptr = value.data_.data_;\n    if (std::is_base_of<NDArray::ContainerType, ContainerType>::value ||\n        (std::is_base_of<ContainerType, NDArray::ContainerType>::value &&\n         ptr->IsInstance<NDArray::ContainerType>())) {\n      values_[i].v_handle = NDArray::FFIGetHandle(value);\n      type_codes_[i] = kTVMNDArrayHandle;\n    } else if (std::is_base_of<Module::ContainerType, ContainerType>::value ||\n               (std::is_base_of<ContainerType, Module::ContainerType>::value &&\n                ptr->IsInstance<Module::ContainerType>())) {\n      values_[i].v_handle = ptr;\n      type_codes_[i] = kTVMModuleHandle;\n    } else if (std::is_base_of<PackedFunc::ContainerType, ContainerType>::value ||\n               (std::is_base_of<ContainerType, PackedFunc::ContainerType>::value &&\n                ptr->IsInstance<PackedFunc::ContainerType>())) {\n      values_[i].v_handle = ptr;\n      type_codes_[i] = kTVMPackedFuncHandle;\n    } else if (std::is_rvalue_reference<decltype(value)>::value) {\n      values_[i].v_handle = const_cast<Object**>(&(value.data_.data_));\n      type_codes_[i] = kTVMObjectRValueRefArg;\n    } else {\n      values_[i].v_handle = value.data_.data_;\n      type_codes_[i] = kTVMObjectHandle;\n    }\n  } else {\n    type_codes_[i] = kTVMNullptr;\n    values_[i].v_handle = nullptr;\n  }\n}\n\ntemplate <typename TObjectRef, typename>\ninline bool TVMPODValue_::IsObjectRef() const {\n  using ContainerType = typename TObjectRef::ContainerType;\n  // NOTE: the following code can be optimized by constant folding.\n  if (std::is_base_of<NDArray::ContainerType, ContainerType>::value) {\n    return type_code_ == kTVMNDArrayHandle &&\n           TVMArrayHandleToObjectHandle(static_cast<TVMArrayHandle>(value_.v_handle))\n               ->IsInstance<ContainerType>();\n  }\n  if (std::is_base_of<Module::ContainerType, ContainerType>::value) {\n    return type_code_ == kTVMModuleHandle &&\n           static_cast<Object*>(value_.v_handle)->IsInstance<ContainerType>();\n  }\n  if (std::is_base_of<PackedFunc::ContainerType, ContainerType>::value) {\n    return type_code_ == kTVMPackedFuncHandle &&\n           static_cast<Object*>(value_.v_handle)->IsInstance<ContainerType>();\n  }\n  // NOTE: we don't pass NDArray and runtime::Module as RValue ref.\n  if (type_code_ == kTVMObjectRValueRefArg) {\n    return ObjectTypeChecker<TObjectRef>::Check(*static_cast<Object**>(value_.v_handle));\n  }\n  return (std::is_base_of<ContainerType, NDArray::ContainerType>::value &&\n          type_code_ == kTVMNDArrayHandle) ||\n         (std::is_base_of<ContainerType, Module::ContainerType>::value &&\n          type_code_ == kTVMModuleHandle) ||\n         (std::is_base_of<ContainerType, PackedFunc::ContainerType>::value &&\n          type_code_ == kTVMPackedFuncHandle) ||\n         (type_code_ == kTVMObjectHandle &&\n          ObjectTypeChecker<TObjectRef>::Check(static_cast<Object*>(value_.v_handle)));\n}\n\ntemplate <typename TObjectRef>\ninline TObjectRef TVMPODValue_::AsObjectRef() const {\n  static_assert(std::is_base_of<ObjectRef, TObjectRef>::value,\n                \"Conversion only works for ObjectRef\");\n  using ContainerType = typename TObjectRef::ContainerType;\n\n  if (type_code_ == kTVMNullptr) {\n    CHECK(TObjectRef::_type_is_nullable)\n        << \"Expect a not null value of \" << ContainerType::_type_key;\n    return TObjectRef(ObjectPtr<Object>(nullptr));\n  }\n  // NOTE: the following code can be optimized by constant folding.\n  if (std::is_base_of<NDArray::ContainerType, ContainerType>::value) {\n    // Casting to a sub-class of NDArray\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMNDArrayHandle);\n    ObjectPtr<Object> data =\n        NDArray::FFIDataFromHandle(static_cast<TVMArrayHandle>(value_.v_handle));\n    CHECK(data->IsInstance<ContainerType>())\n        << \"Expected \" << ContainerType::_type_key << \" but got \" << data->GetTypeKey();\n    return TObjectRef(data);\n  }\n  if (std::is_base_of<Module::ContainerType, ContainerType>::value) {\n    // Casting to a sub-class of Module\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMModuleHandle);\n    ObjectPtr<Object> data = GetObjectPtr<Object>(static_cast<Object*>(value_.v_handle));\n    CHECK(data->IsInstance<ContainerType>())\n        << \"Expected \" << ContainerType::_type_key << \" but got \" << data->GetTypeKey();\n    return TObjectRef(data);\n  }\n  if (std::is_base_of<PackedFunc::ContainerType, ContainerType>::value) {\n    // Casting to a sub-class of PackedFunc\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMPackedFuncHandle);\n    ObjectPtr<Object> data = GetObjectPtr<Object>(static_cast<Object*>(value_.v_handle));\n    CHECK(data->IsInstance<ContainerType>())\n        << \"Expected \" << ContainerType::_type_key << \" but got \" << data->GetTypeKey();\n    return TObjectRef(data);\n  }\n  if (type_code_ == kTVMObjectHandle) {\n    // normal object type check.\n    Object* ptr = static_cast<Object*>(value_.v_handle);\n    Optional<String> checked_type = ObjectTypeChecker<TObjectRef>::CheckAndGetMismatch(ptr);\n    ICHECK(!checked_type.defined()) << \"Expected \" << ObjectTypeChecker<TObjectRef>::TypeName()\n                                    << \", but got \" << checked_type.value();\n    return TObjectRef(GetObjectPtr<Object>(ptr));\n  } else if (type_code_ == kTVMObjectRValueRefArg) {\n    Object* ptr = *static_cast<Object**>(value_.v_handle);\n    Optional<String> checked_type = ObjectTypeChecker<TObjectRef>::CheckAndGetMismatch(ptr);\n    ICHECK(!checked_type.defined()) << \"Expected \" << ObjectTypeChecker<TObjectRef>::TypeName()\n                                    << \", but got \" << checked_type.value();\n    return TObjectRef(GetObjectPtr<Object>(ptr));\n  } else if (std::is_base_of<ContainerType, NDArray::ContainerType>::value &&\n             type_code_ == kTVMNDArrayHandle) {\n    // Casting to a base class that NDArray can sub-class\n    ObjectPtr<Object> data =\n        NDArray::FFIDataFromHandle(static_cast<TVMArrayHandle>(value_.v_handle));\n    return TObjectRef(data);\n  } else if (std::is_base_of<ContainerType, Module::ContainerType>::value &&\n             type_code_ == kTVMModuleHandle) {\n    // Casting to a base class that Module can sub-class\n    return TObjectRef(GetObjectPtr<Object>(static_cast<Object*>(value_.v_handle)));\n  } else if (std::is_base_of<ContainerType, PackedFunc::ContainerType>::value &&\n             type_code_ == kTVMPackedFuncHandle) {\n    // Casting to a base class that PackedFunc can sub-class\n    return TObjectRef(GetObjectPtr<Object>(static_cast<Object*>(value_.v_handle)));\n  } else {\n    TVM_CHECK_TYPE_CODE(type_code_, kTVMObjectHandle);\n    return TObjectRef(ObjectPtr<Object>(nullptr));\n  }\n}\n\ntemplate <typename TObjectRef, typename>\ninline TVMRetValue& TVMRetValue::operator=(TObjectRef other) {\n  using ContainerType = typename TObjectRef::ContainerType;\n  const Object* ptr = other.get();\n  if (ptr != nullptr) {\n    if (std::is_base_of<NDArray::ContainerType, ContainerType>::value ||\n        (std::is_base_of<ContainerType, NDArray::ContainerType>::value &&\n         ptr->IsInstance<NDArray::ContainerType>())) {\n      return operator=(NDArray(std::move(other.data_)));\n    }\n    if (std::is_base_of<Module::ContainerType, ContainerType>::value ||\n        (std::is_base_of<ContainerType, Module::ContainerType>::value &&\n         ptr->IsInstance<Module::ContainerType>())) {\n      return operator=(Module(std::move(other.data_)));\n    }\n    SwitchToObject(kTVMObjectHandle, std::move(other.data_));\n  } else {\n    SwitchToPOD(kTVMNullptr);\n    value_.v_handle = nullptr;\n  }\n  return *this;\n}\n\ntemplate <typename T, typename>\ninline TVMArgValue::operator T() const {\n  return PackedFuncValueConverter<T>::From(*this);\n}\n\ntemplate <typename T, typename>\ninline TVMMovableArgValue_::operator T() const {\n  if (type_code_ == kTVMObjectRValueRefArg) {\n    auto** ref = static_cast<Object**>(value_.v_handle);\n    if (ObjectTypeChecker<T>::Check(*ref)) {\n      return T(ObjectPtr<Object>::MoveFromRValueRefArg(ref));\n    }\n  }\n  // fallback\n  return PackedFuncValueConverter<T>::From(AsArgValue());\n}\n\ntemplate <typename T, typename>\ninline TVMRetValue::operator T() const {\n  return PackedFuncValueConverter<T>::From(*this);\n}\n\ninline PackedFunc Module::GetFunction(const std::string& name, bool query_imports) {\n  return (*this)->GetFunction(name, query_imports);\n}\n\n// specializations of PackedFuncValueConverter\ntemplate <>\nstruct PackedFuncValueConverter<::tvm::runtime::String> {\n  static String From(const TVMArgValue& val) {\n    if (val.IsObjectRef<tvm::runtime::String>()) {\n      return val.AsObjectRef<tvm::runtime::String>();\n    } else {\n      return tvm::runtime::String(val.operator std::string());\n    }\n  }\n\n  static String From(const TVMRetValue& val) {\n    if (val.IsObjectRef<tvm::runtime::String>()) {\n      return val.AsObjectRef<tvm::runtime::String>();\n    } else {\n      return tvm::runtime::String(val.operator std::string());\n    }\n  }\n};\n\ntemplate <typename T>\nstruct PackedFuncValueConverter<Optional<T>> {\n  static Optional<T> From(const TVMArgValue& val) {\n    if (val.type_code() == kTVMNullptr) return Optional<T>(nullptr);\n    return PackedFuncValueConverter<T>::From(val);\n  }\n  static Optional<T> From(const TVMRetValue& val) {\n    if (val.type_code() == kTVMNullptr) return Optional<T>(nullptr);\n    return PackedFuncValueConverter<T>::From(val);\n  }\n};\n\ninline bool String::CanConvertFrom(const TVMArgValue& val) {\n  return val.type_code() == kTVMStr || val.IsObjectRef<tvm::runtime::String>();\n}\n\ninline TVMArgValue::operator DLDataType() const {\n  if (String::CanConvertFrom(*this)) {\n    return String2DLDataType(PackedFuncValueConverter<String>::From(*this).operator std::string());\n  }\n  // None type\n  if (type_code_ == kTVMNullptr) {\n    DLDataType t;\n    t.code = kTVMOpaqueHandle;\n    t.bits = 0;\n    t.lanes = 0;\n    return t;\n  }\n  TVM_CHECK_TYPE_CODE(type_code_, kTVMDataType);\n  return value_.v_type;\n}\n\ninline TVMArgValue::operator DataType() const { return DataType(operator DLDataType()); }\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_PACKED_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/profiling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/tvm/runtime/profiling.h\n * \\brief Runtime profiling including timers.\n */\n#ifndef TVM_RUNTIME_PROFILING_H_\n#define TVM_RUNTIME_PROFILING_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nnamespace runtime {\n\n/*! \\brief Base class for all implementations.\n *\n * New implementations of this interface should make sure that `Start` and `Stop`\n * are as lightweight as possible. Expensive state synchronization should be\n * done in `SyncAndGetElapsedNanos`.\n */\nclass TimerNode : public Object {\n public:\n  /*! \\brief Start the timer.\n   *\n   * Note: this function should only be called once per object.\n   */\n  virtual void Start() = 0;\n  /*! \\brief Stop the timer.\n   *\n   * Note: this function should only be called once per object.\n   */\n  virtual void Stop() = 0;\n  /*! \\brief Synchronize timer state and return elapsed time between `Start` and `Stop`.\n   * \\return The time in nanoseconds between `Start` and `Stop`.\n   *\n   * This function is necessary because we want to avoid timing the overhead of\n   * doing timing. When using multiple timers, it is recommended to stop all of\n   * them before calling `SyncAndGetElapsedNanos` on any of them.\n   *\n   * Note: this function should be only called once per object. It may incur\n   * a large synchronization overhead (for example, with GPUs).\n   */\n  virtual int64_t SyncAndGetElapsedNanos() = 0;\n\n  virtual ~TimerNode() {}\n\n  static constexpr const char* _type_key = \"TimerNode\";\n  TVM_DECLARE_BASE_OBJECT_INFO(TimerNode, Object);\n};\n\n/*! \\brief Timer for a specific device.\n *\n * This is a managed reference to a TimerNode.\n *\n * \\sa TimerNode\n */\nclass Timer : public ObjectRef {\n public:\n  /*!\n   * \\brief Get a device specific timer.\n   * \\param dev The device to time.\n   * \\return A `Timer` that has already been started.\n   *\n   * Use this function to time runtime of arbitrary regions of code on a specific\n   * device. The code that you want to time should be running on the device\n   * otherwise the timer will not return correct results. This is a lower level\n   * interface than TimeEvaluator and only runs the timed code once\n   * (TimeEvaluator runs the code multiple times).\n   *\n   * A default timer is used if a device specific one does not exist. This\n   * timer performs synchronization between the device and CPU, which can lead\n   * to overhead in the reported results.\n   *\n   * Example usage:\n   * \\code{.cpp}\n   * Timer t = Timer::Start(Device::cpu());\n   * my_long_running_function();\n   * t->Stop();\n   * ... // some more computation\n   * int64_t nanosecs = t->SyncAndGetElapsedNanos() // elapsed time in nanoseconds\n   * \\endcode\n   *\n   * To add a new device-specific timer, register a new function\n   * \"profiler.timer.my_device\" (where `my_device` is the `DeviceName` of your\n   * device). This function should accept a `Device` and return a new `Timer`\n   * that has already been started.\n   *\n   * For example, this is how the CPU timer is implemented:\n   * \\code{.cpp}\n   *  class CPUTimerNode : public TimerNode {\n   *   public:\n   *    virtual void Start() { start_ = std::chrono::high_resolution_clock::now(); }\n   *    virtual void Stop() { duration_ = std::chrono::high_resolution_clock::now() - start_; }\n   *    virtual int64_t SyncAndGetElapsedNanos() { return duration_.count(); }\n   *    virtual ~CPUTimerNode() {}\n   *\n   *    static constexpr const char* _type_key = \"CPUTimerNode\";\n   *    TVM_DECLARE_FINAL_OBJECT_INFO(CPUTimerNode, TimerNode);\n   *\n   *   private:\n   *    std::chrono::high_resolution_clock::time_point start_;\n   *    std::chrono::duration<int64_t, std::nano> duration_;\n   *  };\n   *  TVM_REGISTER_OBJECT_TYPE(CPUTimerNode);\n   *\n   *  TVM_REGISTER_GLOBAL(\"profiling.timer.cpu\").set_body_typed([](Device dev) {\n   *    return Timer(make_object<CPUTimerNode>());\n   *  });\n   * \\endcode\n   */\n  static TVM_DLL Timer Start(Device dev);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Timer, ObjectRef, TimerNode);\n};\n\n/*!\n * \\brief Default timer if one does not exist for the device.\n * \\param dev The device to time on.\n *\n * Note that this timer performs synchronization between the device and CPU,\n * which can lead to overhead in the reported results.\n */\nTimer DefaultTimer(Device dev);\n\nnamespace profiling {\n/*! \\brief Wrapper for `Device` because `Device` is not passable across the\n * PackedFunc interface.\n */\nstruct DeviceWrapperNode : public Object {\n  /*! The device */\n  Device device;\n\n  /*! Constructor */\n  explicit DeviceWrapperNode(Device device) : device(device) {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.DeviceWrapper\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DeviceWrapperNode, Object);\n};\n\n/*! \\brief Wrapper for `Device`. */\nclass DeviceWrapper : public ObjectRef {\n public:\n  explicit DeviceWrapper(Device dev) { data_ = make_object<DeviceWrapperNode>(dev); }\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(DeviceWrapper, ObjectRef, DeviceWrapperNode);\n};\n\n/*! \\brief Data collected from a profiling run. Includes per-call metrics and per-device metrics.\n */\nclass ReportNode : public Object {\n public:\n  /*! \\brief A list of function calls and the metrics recorded for that call.\n   *\n   * Each element is a mapping from metric name to value. Some metrics that\n   * appear in every call are \"Name\" (the function name), \"Argument Shapes\",\n   * and \"Duration (us)\". Values are one of `String`, `PercentNode`,\n   * `DurationNode`, or `CountNode`.\n   */\n  Array<Map<String, ObjectRef>> calls;\n  /*! \\brief Metrics collected for the entire run of the model on a per-device basis.\n   *\n   * `device_metrics` is indexed by device name then metric.\n   *\n   * These metrics may be larger than the sum of the same metric in `calls`\n   * because these metrics include the overhead of the executor.\n   */\n  Map<String, Map<String, ObjectRef>> device_metrics;\n  /*! Configuration used for this profiling run. Includes number of threads, executor.\n   *\n   * Values must be an object type that can be used with device_metrics.\n   */\n  Map<String, ObjectRef> configuration;\n  /*! \\brief Output `calls` in CSV format.\n   *\n   * Note that this does not include `device_metrics`, it only includes per-call metrics.\n   */\n  String AsCSV() const;\n  /*! \\brief Create a human readable table of profiling metrics.\n   *\n   *  \\param aggregate Whether or not to join multiple calls to the\n   *      same op into a single line.\n   *\n   *  \\param sort Whether or not to sort call frames by descending\n   *      duration. If false and if `aggregate` is false, frames will\n   *      be sorted by order of appearance in the program. Order is\n   *      undefined if `sort` is false and `aggregate` is true.\n   *\n   *  \\param compute_col_sums Whether or not to include sum totals for\n   *      the Count, Duation, and Percent columns.\n   *\n   */\n  String AsTable(bool sort = true, bool aggregate = true, bool compute_col_sums = true) const;\n  /*! \\brief Convert this report to JSON.\n   *\n   * Output JSON will be of this format:\n   * \\code\n   *  {\n   *    \"calls\": [\n   *      {\n   *        \"Duration (us)\": {\n   *          \"microseconds\": 12.3\n   *        },\n   *        \"Name\": \"fused_dense\",\n   *        \"Count\": {\n   *          \"count\": 1\n   *        },\n   *        \"Percent\": {\n   *          \"percent\": 10.3\n   *        }\n   *      }\n   *    ],\n   *    \"device_metrics\": {\n   *      \"cpu\": {\n   *        \"Duration (us)\": {\n   *          \"microseconds\": 334.2\n   *        },\n   *        \"Percent\": {\n   *          \"percent\": 100\n   *        }\n   *      }\n   *    }\n   *  }\n   * \\endcode\n   */\n  String AsJSON() const;\n\n  static constexpr const char* _type_key = \"runtime.profiling.Report\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ReportNode, Object);\n};\n\nclass Report : public ObjectRef {\n public:\n  /*! Construct a Report from a set of calls (with associated metrics) and per-device metrics.\n   * \\param calls Function calls and associated metrics.\n   * \\param device_metrics Per-device metrics for overall execution.\n   * \\param configuration Configuration data specific to this profiling run.\n   */\n  explicit Report(Array<Map<String, ObjectRef>> calls,\n                  Map<String, Map<String, ObjectRef>> device_metrics,\n                  Map<String, ObjectRef> configuration);\n\n  /*! Deserialize a Report from a JSON object. Needed for sending the report over RPC.\n   * \\param json Serialized json report from `ReportNode::AsJSON`.\n   * \\returns A Report.\n   */\n  static Report FromJSON(String json);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Report, ObjectRef, ReportNode);\n};\n\n/*! \\brief Interface for user defined profiling metric collection.\n *\n * Users can register their own collector by registering a packed function with\n * the name \"runtime.profiling.metrics.my_collector_name\" where\n * \"my_collector_name\" is the name of their collector. This function should\n * take an Array of Device as input which contains the devices the collector\n * will be run on.\n *\n * `MetricCollectorNode`s will be called in the following fashion.\n * \\code\n * MetricCollector mc;\n * for (auto op : model) {\n *   auto o = mc.Start();\n *   op();\n *   auto metrics = mc.Stop(o); // metrics are added the profiling report\n * }\n * \\endcode\n */\nclass MetricCollectorNode : public Object {\n public:\n  /*! \\brief Initialization call. Called before profiling has started. Any\n   * expensive precomputation should happen here.\n   * \\param devs The list of devices this collector will be run on.\n   */\n  virtual void Init(Array<DeviceWrapper> devs) = 0;\n  /*! \\brief Start colling metrics for a function call.\n   * \\param dev The device the call will be run on.\n   * \\returns An object used to maintain state of the metric collection. This\n   * object will be passed to the corresponding `Stop` call. If the device is\n   * not supported, this function will return a nullptr ObjectRef.\n   */\n  virtual ObjectRef Start(Device dev) = 0;\n  /*! \\brief Stop collecting metrics.\n   * \\param obj The object created by the corresponding `Start` call.\n   * \\returns A set of metric names and the associated values. Values must be\n   * one of DurationNode, PercentNode, CountNode, or StringObj.\n   */\n  virtual Map<String, ObjectRef> Stop(ObjectRef obj) = 0;\n\n  virtual ~MetricCollectorNode() {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.MetricCollector\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MetricCollectorNode, Object);\n};\n\n/*! \\brief Wrapper for `MetricCollectorNode`. */\nclass MetricCollector : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MetricCollector, ObjectRef, MetricCollectorNode);\n};\n\n/*! Information about a single function or operator call. */\nstruct CallFrame {\n  /*! Device on which the call was made */\n  Device dev;\n  /*! Name of the function or op */\n  String name;\n  /*! Runtime of the function or op */\n  Timer timer;\n  /*! Extra performance metrics */\n  std::unordered_map<std::string, ObjectRef> extra_metrics;\n  /*! User defined metric collectors. Each pair is the MetricCollector and its\n   * associated data (returned from MetricCollector.Start).\n   */\n  std::vector<std::pair<MetricCollector, ObjectRef>> extra_collectors;\n};\n\n/*! Runtime profiler for function and/or operator calls. Used in the graph\n * runtime and VM to provide profiling information for all operators.\n *\n * Example usage:\n * \\code{.cpp}\n * Device cpu, gpu;\n * Profiler prof({cpu, gpu});\n * my_gpu_kernel(); // do a warmup iteration\n * prof.Start();\n * prof.StartCall(\"my_gpu_kernel\", gpu);\n * my_gpu_kernel();\n * prof.StopCall();\n * prof.StartCall(\"my_cpu_function\", cpu);\n * my_cpu_function();\n * prof.StopCall();\n * prof.Stop();\n * std::cout << prof.Report << std::endl; // print profiling report\n * \\endcode\n */\nclass Profiler {\n public:\n  /*! Constructor.\n   *\n   * The profiler should be constructed before you do any warmup iterations.\n   *\n   * \\note\n   * Calling this constructor will reset the TVM threadpool. It is necessary in\n   * order to install thread handlers required by certain collectors.\n   *\n   * \\param devs The list of devices the profiler will be running on. Should\n   *             include all devices used by profiled operators.\n   * \\param metric_collectors Additional `MetricCollector`s to use with this profiler.\n   * \\param configuration Additional configuration data to add to the outputted profiling report.\n   */\n  explicit Profiler(std::vector<Device> devs, std::vector<MetricCollector> metric_collectors,\n                    std::unordered_map<String, ObjectRef> configuration = {});\n  /*! \\brief Start the profiler.\n   *\n   * This function should only be called once per object.\n   */\n  void Start();\n  /*! \\brief Stop the profiler.\n   *\n   * This function should only be called once per object after start has been called.\n   */\n  void Stop();\n  /*! \\brief Start a function call.\n   * \\param name The name of the function being called.\n   * \\param dev The device on which the function is running.\n   * \\param extra_metrics Optional additional profiling information to add to\n   * the frame (input sizes, allocations).\n   *\n   * `StartCall` may be nested, but each `StartCall` needs a matching\n   * `StopCall`. Function calls are stopped in LIFO order, so calls to\n   * `StartCall` and `StopCall` must be nested properly.\n   */\n  void StartCall(String name, Device dev,\n                 std::unordered_map<std::string, ObjectRef> extra_metrics = {});\n  /*! \\brief Stop the last `StartCall`.\n   * \\param extra_metrics Optional additional profiling information to add to\n   * the frame (input sizes, allocations).\n   */\n  void StopCall(std::unordered_map<std::string, ObjectRef> extra_metrics = {});\n  /*! \\brief A report of total runtime between `Start` and `Stop` as\n   *        well as individual statistics for each `StartCall`-`StopCall` pair.\n   *  \\returns A `Report` that can either be formatted as CSV (with `.AsCSV`)\n   *  or as a human readable table (with `.AsTable`).\n   */\n  profiling::Report Report();\n  /*! \\brief Check if the profiler is currently running.\n   * \\returns Whether or not the profiler is running.\n   */\n  bool IsRunning() const { return is_running_; }\n\n private:\n  std::vector<Device> devs_;\n  bool is_running_{false};\n  std::vector<CallFrame> calls_;\n  std::stack<CallFrame> in_flight_;\n  std::vector<MetricCollector> collectors_;\n  std::unordered_map<String, ObjectRef> configuration_;\n};\n\n/* \\brief A duration in time. */\nclass DurationNode : public Object {\n public:\n  /* The duration as a floating point number of microseconds. */\n  double microseconds;\n\n  /* \\brief Construct a new duration.\n   * \\param a The duration in microseconds.\n   */\n  explicit DurationNode(double a) : microseconds(a) {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.Duration\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DurationNode, Object);\n};\n\n/* A percentage of something */\nclass PercentNode : public Object {\n public:\n  /* The percent as a floating point value out of 100%. i.e. if `percent` is 10 then we have 10%. */\n  double percent;\n\n  /* \\brief Construct a new percentage.\n   * \\param a The percentage out of 100.\n   */\n  explicit PercentNode(double a) : percent(a) {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.Percent\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PercentNode, Object);\n};\n\n/* A count of something */\nclass CountNode : public Object {\n public:\n  /* The actual count */\n  int64_t value;\n\n  /* \\brief Construct a new count.\n   * \\param a The count.\n   */\n  explicit CountNode(int64_t a) : value(a) {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.Count\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CountNode, Object);\n};\n\n/* \\brief A ratio of two things. */\nclass RatioNode : public Object {\n public:\n  /* The ratio as a double precision floating point number. */\n  double ratio;\n\n  /* \\brief Construct a new ratio.\n   * \\param a The ratio.\n   */\n  explicit RatioNode(double a) : ratio(a) {}\n\n  static constexpr const char* _type_key = \"runtime.profiling.Ratio\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RatioNode, Object);\n};\n\n/*! \\brief String representation of an array of NDArray shapes\n *  \\param shapes Array of NDArrays to get the shapes of.\n *  \\return A textual representation of the shapes. For example: `float32[2], int64[1, 2]`.\n */\nString ShapeString(const std::vector<NDArray>& shapes);\n/*! \\brief String representation of shape encoded as an NDArray\n *  \\param shape NDArray containing the shape.\n *  \\param dtype The dtype of the shape.\n *  \\return A textual representation of the shape. For example: `float32[2]`.\n */\nString ShapeString(NDArray shape, DLDataType dtype);\n/*! \\brief String representation of a shape encoded as a vector\n *  \\param shape Shape as a vector of integers.\n *  \\param dtype The dtype of the shape.\n *  \\return A textual representation of the shape. For example: `float32[2]`.\n */\nString ShapeString(const std::vector<int64_t>& shape, DLDataType dtype);\n\n/*! \\brief Collect performance information of a function execution. Usually\n * used with a compiled PrimFunc (via tvm.build).\n *\n * This information can include performance counters like cache hits and FLOPs\n * that are useful in debugging performance issues of individual PrimFuncs.\n * Different metrics can be collected depending on which MetricCollector is\n * used.\n *\n * Example usage:\n * \\code{.cpp}\n * // Use PAPI to measure the number of floating point operations.\n * PackedFunc profiler = ProfileModule(\n *     mod, \"main\", kDLCPU, 0, {CreatePAPIMetricCollector({{kDLCPU, 0}, {\"PAPI_FP_OPS\"}})});\n * Report r = profiler(arg1, arg2, arg);\n * std::cout << r << std::endl;\n * \\endcode\n *\n * \\param mod Module to profile. Usually a PrimFunc that has been compiled to machine code.\n * \\param func_name Name of function to run in the module.\n * \\param device_type Device type to run on. Profiling will include performance\n *                    metrics specific to this device type.\n * \\param device_id Id of device to run on.\n * \\param warmup_iters Number of iterations of the function to run before collecting\n *                     performance information. Recommend to set this larger\n *                     than 0 so that cache effects are consistent.\n * \\param collectors List of different\n *                   ways to collect metrics. See MetricCollector.\n * \\returns A PackedFunc which takes the same arguments as the `mod[func_name]`\n *          and returns performance metrics as a `Map<String, ObjectRef>` where\n *          values can be `CountNode`, `DurationNode`, `PercentNode`.\n */\nPackedFunc ProfileFunction(Module mod, std::string func_name, int device_type, int device_id,\n                           int warmup_iters, Array<MetricCollector> collectors);\n\n/*!\n * \\brief Wrap a timer function to measure the time cost of a given packed function.\n *\n * Approximate implementation:\n * \\code{.py}\n * f() // warmup\n * for i in range(repeat)\n *   f_preproc()\n *   while True:\n *     start = time()\n *     for j in range(number):\n *       f()\n *     duration_ms = time() - start\n *     if duration_ms >= min_repeat_ms:\n *       break\n *     else:\n *        number = (min_repeat_ms / (duration_ms / number) + 1\n *   if cooldown_interval_ms and i % repeats_to_cooldown == 0:\n *     sleep(cooldown_interval_ms)\n * \\endcode\n *\n * \\param f The function argument.\n * \\param dev The device.\n * \\param number The number of times to run this function for taking average.\n *        We call these runs as one `repeat` of measurement.\n * \\param repeat The number of times to repeat the measurement.\n *        In total, the function will be invoked (1 + number x repeat) times,\n *        where the first one is warm up and will be discarded.\n *        The returned result contains `repeat` costs,\n *        each of which is an average of `number` costs.\n * \\param min_repeat_ms The minimum duration of one `repeat` in milliseconds.\n *        By default, one `repeat` contains `number` runs. If this parameter is set,\n *        the parameters `number` will be dynamically adjusted to meet the\n *        minimum duration requirement of one `repeat`.\n *        i.e., When the run time of one `repeat` falls below this time,\n *        the `number` parameter will be automatically increased.\n * \\param limit_zero_time_iterations The maximum number of repeats when\n *        measured time is equal to 0.  It helps to avoid hanging during measurements.\n * \\param cooldown_interval_ms The cooldown interval in milliseconds between the number of repeats\n *        defined by `repeats_to_cooldown`.\n * \\param repeats_to_cooldown The number of repeats before the\n *        cooldown is activated.\n * \\param f_preproc The function to be executed before we execute time\n *        evaluator.\n * \\return f_timer A timer function.\n */\nPackedFunc WrapTimeEvaluator(PackedFunc f, Device dev, int number, int repeat, int min_repeat_ms,\n                             int limit_zero_time_iterations, int cooldown_interval_ms,\n                             int repeats_to_cooldown, PackedFunc f_preproc = nullptr);\n\n}  // namespace profiling\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_PROFILING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/registry.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/registry.h\n * \\brief This file defines the TVM global function registry.\n *\n *  The registered functions will be made available to front-end\n *  as well as backend users.\n *\n *  The registry stores type-erased functions.\n *  Each registered function is automatically exposed\n *  to front-end language(e.g. python).\n *\n *  Front-end can also pass callbacks as PackedFunc, or register\n *  then into the same global registry in C++.\n *  The goal is to mix the front-end language and the TVM back-end.\n *\n * \\code\n *   // register the function as MyAPIFuncName\n *   TVM_REGISTER_GLOBAL(MyAPIFuncName)\n *   .set_body([](TVMArgs args, TVMRetValue* rv) {\n *     // my code.\n *   });\n * \\endcode\n */\n#ifndef TVM_RUNTIME_REGISTRY_H_\n#define TVM_RUNTIME_REGISTRY_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Check if signals have been sent to the process and if so\n *  invoke the registered signal handler in the frontend environment.\n *\n *  When running TVM in another language (Python), the signal handler\n *  may not be immediately executed, but instead the signal is marked\n *  in the interpreter state (to ensure non-blocking of the signal handler).\n *\n *  This function can be explicitly invoked to check the cached signal\n *  and run the related processing if a signal is marked.\n *\n *  On Linux, when siginterrupt() is set, invoke this function whenever a syscall returns EINTR.\n *  When it is not set, invoke it between long-running syscalls when you will not immediately\n *  return to the frontend. On Windows, the same rules apply, but due to differences in signal\n *  processing, these are likely to only make a difference when used with Ctrl+C and socket calls.\n *\n *  Not inserting this function will not cause any correctness\n *  issue, but will delay invoking the Python-side signal handler until the function returns to\n *  the Python side. This means that the effect of e.g. pressing Ctrl+C or sending signals the\n *  process will be delayed until function return. When a C function is blocked on a syscall\n *  such as accept(), it needs to be called when EINTR is received.\n *  So this function is not needed in most API functions, which can finish quickly in a\n *  reasonable, deterministic amount of time.\n *\n * \\code\n *\n * int check_signal_every_k_iter = 10;\n *\n * for (int iter = 0; iter < very_large_number; ++iter) {\n *   if (iter % check_signal_every_k_iter == 0) {\n *     tvm::runtime::EnvCheckSignals();\n *   }\n *   // do work here\n * }\n *\n * \\endcode\n *\n * \\note This function is a nop when no PyErr_CheckSignals is registered.\n *\n * \\throws This function throws an exception when the frontend signal handler\n *         indicate an error happens, otherwise it returns normally.\n */\nTVM_DLL void EnvCheckSignals();\n\n/*! \\brief Registry for global function */\nclass Registry {\n public:\n  /*!\n   * \\brief set the body of the function to be f\n   * \\param f The body of the function.\n   */\n  TVM_DLL Registry& set_body(PackedFunc f);  // NOLINT(*)\n  /*!\n   * \\brief set the body of the function to be f\n   * \\param f The body of the function.\n   */\n  template <typename TCallable,\n            typename = typename std::enable_if_t<\n                std::is_convertible<TCallable, std::function<void(TVMArgs, TVMRetValue*)>>::value &&\n                !std::is_base_of<PackedFunc, TCallable>::value>>\n  Registry& set_body(TCallable f) {  // NOLINT(*)\n    return set_body(PackedFunc(f));\n  }\n  /*!\n   * \\brief set the body of the function to the given function.\n   *        Note that this will ignore default arg values and always require all arguments to be\n   * provided.\n   *\n   * \\code\n   *\n   * int multiply(int x, int y) {\n   *   return x * y;\n   * }\n   *\n   * TVM_REGISTER_GLOBAL(\"multiply\")\n   * .set_body_typed(multiply); // will have type int(int, int)\n   *\n   * // will have type int(int, int)\n   * TVM_REGISTER_GLOBAL(\"sub\")\n   * .set_body_typed([](int a, int b) -> int { return a - b; });\n   *\n   * \\endcode\n   *\n   * \\param f The function to forward to.\n   * \\tparam FLambda The signature of the function.\n   */\n  template <typename FLambda>\n  Registry& set_body_typed(FLambda f) {\n    using FType = typename detail::function_signature<FLambda>::FType;\n    return set_body(TypedPackedFunc<FType>(std::move(f), name_).packed());\n  }\n  /*!\n   * \\brief set the body of the function to be the passed method pointer.\n   *        Note that this will ignore default arg values and always require all arguments to be\n   * provided.\n   *\n   * \\code\n   *\n   * // node subclass:\n   * struct Example {\n   *    int doThing(int x);\n   * }\n   * TVM_REGISTER_GLOBAL(\"Example_doThing\")\n   * .set_body_method(&Example::doThing); // will have type int(Example, int)\n   *\n   * \\endcode\n   *\n   * \\param f the method pointer to forward to.\n   * \\tparam T the type containing the method (inferred).\n   * \\tparam R the return type of the function (inferred).\n   * \\tparam Args the argument types of the function (inferred).\n   */\n  template <typename T, typename R, typename... Args>\n  Registry& set_body_method(R (T::*f)(Args...)) {\n    using R_ = typename std::remove_reference<R>::type;\n    auto fwrap = [f](T target, Args... params) -> R_ {\n      // call method pointer\n      return (target.*f)(params...);\n    };\n    return set_body(TypedPackedFunc<R_(T, Args...)>(fwrap, name_));\n  }\n\n  /*!\n   * \\brief set the body of the function to be the passed method pointer.\n   *        Note that this will ignore default arg values and always require all arguments to be\n   * provided.\n   *\n   * \\code\n   *\n   * // node subclass:\n   * struct Example {\n   *    int doThing(int x);\n   * }\n   * TVM_REGISTER_GLOBAL(\"Example_doThing\")\n   * .set_body_method(&Example::doThing); // will have type int(Example, int)\n   *\n   * \\endcode\n   *\n   * \\param f the method pointer to forward to.\n   * \\tparam T the type containing the method (inferred).\n   * \\tparam R the return type of the function (inferred).\n   * \\tparam Args the argument types of the function (inferred).\n   */\n  template <typename T, typename R, typename... Args>\n  Registry& set_body_method(R (T::*f)(Args...) const) {\n    auto fwrap = [f](const T target, Args... params) -> R {\n      // call method pointer\n      return (target.*f)(params...);\n    };\n    return set_body(TypedPackedFunc<R(const T, Args...)>(fwrap, name_));\n  }\n\n  /*!\n   * \\brief set the body of the function to be the passed method pointer.\n   *        Used when calling a method on a Node subclass through a ObjectRef subclass.\n   *        Note that this will ignore default arg values and always require all arguments to be\n   * provided.\n   *\n   * \\code\n   *\n   * // node subclass:\n   * struct ExampleNode: BaseNode {\n   *    int doThing(int x);\n   * }\n   *\n   * // noderef subclass\n   * struct Example;\n   *\n   * TVM_REGISTER_GLOBAL(\"Example_doThing\")\n   * .set_body_method<Example>(&ExampleNode::doThing); // will have type int(Example, int)\n   *\n   * // note that just doing:\n   * // .set_body_method(&ExampleNode::doThing);\n   * // wouldn't work, because ExampleNode can't be taken from a TVMArgValue.\n   *\n   * \\endcode\n   *\n   * \\param f the method pointer to forward to.\n   * \\tparam TObjectRef the node reference type to call the method on\n   * \\tparam TNode the node type containing the method (inferred).\n   * \\tparam R the return type of the function (inferred).\n   * \\tparam Args the argument types of the function (inferred).\n   */\n  template <typename TObjectRef, typename TNode, typename R, typename... Args,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>\n  Registry& set_body_method(R (TNode::*f)(Args...)) {\n    auto fwrap = [f](TObjectRef ref, Args... params) {\n      TNode* target = ref.operator->();\n      // call method pointer\n      return (target->*f)(params...);\n    };\n    return set_body(TypedPackedFunc<R(TObjectRef, Args...)>(fwrap, name_));\n  }\n\n  /*!\n   * \\brief set the body of the function to be the passed method pointer.\n   *        Used when calling a method on a Node subclass through a ObjectRef subclass.\n   *        Note that this will ignore default arg values and always require all arguments to be\n   * provided.\n   *\n   * \\code\n   *\n   * // node subclass:\n   * struct ExampleNode: BaseNode {\n   *    int doThing(int x);\n   * }\n   *\n   * // noderef subclass\n   * struct Example;\n   *\n   * TVM_REGISTER_GLOBAL(\"Example_doThing\")\n   * .set_body_method<Example>(&ExampleNode::doThing); // will have type int(Example, int)\n   *\n   * // note that just doing:\n   * // .set_body_method(&ExampleNode::doThing);\n   * // wouldn't work, because ExampleNode can't be taken from a TVMArgValue.\n   *\n   * \\endcode\n   *\n   * \\param f the method pointer to forward to.\n   * \\tparam TObjectRef the node reference type to call the method on\n   * \\tparam TNode the node type containing the method (inferred).\n   * \\tparam R the return type of the function (inferred).\n   * \\tparam Args the argument types of the function (inferred).\n   */\n  template <typename TObjectRef, typename TNode, typename R, typename... Args,\n            typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>\n  Registry& set_body_method(R (TNode::*f)(Args...) const) {\n    auto fwrap = [f](TObjectRef ref, Args... params) {\n      const TNode* target = ref.operator->();\n      // call method pointer\n      return (target->*f)(params...);\n    };\n    return set_body(TypedPackedFunc<R(TObjectRef, Args...)>(fwrap, name_));\n  }\n\n  /*!\n   * \\brief Register a function with given name\n   * \\param name The name of the function.\n   * \\param override Whether allow override existing function.\n   * \\return Reference to the registry.\n   */\n  TVM_DLL static Registry& Register(const std::string& name, bool override = false);  // NOLINT(*)\n  /*!\n   * \\brief Erase global function from registry, if exist.\n   * \\param name The name of the function.\n   * \\return Whether function exist.\n   */\n  TVM_DLL static bool Remove(const std::string& name);\n  /*!\n   * \\brief Get the global function by name.\n   * \\param name The name of the function.\n   * \\return pointer to the registered function,\n   *   nullptr if it does not exist.\n   */\n  TVM_DLL static const PackedFunc* Get(const std::string& name);  // NOLINT(*)\n  /*!\n   * \\brief Get the names of currently registered global function.\n   * \\return The names\n   */\n  TVM_DLL static std::vector<std::string> ListNames();\n\n  // Internal class.\n  struct Manager;\n\n protected:\n  /*! \\brief name of the function */\n  std::string name_;\n  /*! \\brief internal packed function */\n  PackedFunc func_;\n  friend struct Manager;\n};\n\n#define TVM_FUNC_REG_VAR_DEF static TVM_ATTRIBUTE_UNUSED ::tvm::runtime::Registry& __mk_##TVM\n\n/*!\n * \\brief Register a function globally.\n * \\code\n *   TVM_REGISTER_GLOBAL(\"MyPrint\")\n *   .set_body([](TVMArgs args, TVMRetValue* rv) {\n *   });\n * \\endcode\n */\n#define TVM_REGISTER_GLOBAL(OpName) \\\n  TVM_STR_CONCAT(TVM_FUNC_REG_VAR_DEF, __COUNTER__) = ::tvm::runtime::Registry::Register(OpName)\n\n#define TVM_STRINGIZE_DETAIL(x) #x\n#define TVM_STRINGIZE(x) TVM_STRINGIZE_DETAIL(x)\n#define TVM_DESCRIBE(...) describe(__VA_ARGS__ \"\\n\\nFrom:\" __FILE__ \":\" TVM_STRINGIZE(__LINE__))\n/*!\n * \\brief Macro to include current line as string\n */\n#define TVM_ADD_FILELINE \"\\n\\nDefined in \" __FILE__ \":L\" TVM_STRINGIZE(__LINE__)\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_REGISTRY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/serializer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/serializer.h\n * \\brief Serializer extension to support TVM data types\n *  Include this file to enable serialization of DLDataType, DLDevice\n */\n#ifndef TVM_RUNTIME_SERIALIZER_H_\n#define TVM_RUNTIME_SERIALIZER_H_\n\n#include <dmlc/io.h>\n#include <dmlc/serializer.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/ndarray.h>\n\nnamespace dmlc {\nnamespace serializer {\n\ntemplate <>\nstruct Handler<DLDataType> {\n  inline static void Write(Stream* strm, const DLDataType& dtype) {\n    Handler<uint8_t>::Write(strm, dtype.code);\n    Handler<uint8_t>::Write(strm, dtype.bits);\n    Handler<uint16_t>::Write(strm, dtype.lanes);\n  }\n  inline static bool Read(Stream* strm, DLDataType* dtype) {\n    if (!Handler<uint8_t>::Read(strm, &(dtype->code))) return false;\n    if (!Handler<uint8_t>::Read(strm, &(dtype->bits))) return false;\n    if (!Handler<uint16_t>::Read(strm, &(dtype->lanes))) return false;\n    return true;\n  }\n};\n\ntemplate <>\nstruct Handler<DLDevice> {\n  inline static void Write(Stream* strm, const DLDevice& dev) {\n    int32_t device_type = static_cast<int32_t>(dev.device_type);\n    Handler<int32_t>::Write(strm, device_type);\n    Handler<int32_t>::Write(strm, dev.device_id);\n  }\n  inline static bool Read(Stream* strm, DLDevice* dev) {\n    int32_t device_type = 0;\n    if (!Handler<int32_t>::Read(strm, &(device_type))) return false;\n    dev->device_type = static_cast<DLDeviceType>(device_type);\n    if (!Handler<int32_t>::Read(strm, &(dev->device_id))) return false;\n    return true;\n  }\n};\n\n}  // namespace serializer\n}  // namespace dmlc\n#endif  // TVM_RUNTIME_SERIALIZER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/threading_backend.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/threading_backend.h\n * \\brief Utilities for manipulating thread pool threads.\n */\n#ifndef TVM_RUNTIME_THREADING_BACKEND_H_\n#define TVM_RUNTIME_THREADING_BACKEND_H_\n\n#include <functional>\n#include <memory>\n#include <vector>\n\n#if defined(__linux__) || defined(__ANDROID__)\n#if defined(__ANDROID__)\n#ifndef CPU_SET\n#define CPU_SETSIZE 1024\n#define __NCPUBITS (8 * sizeof(uint64_t))\ntypedef struct {\n  uint64_t __bits[CPU_SETSIZE / __NCPUBITS];\n} cpu_set_t;\n\n#define CPU_SET(cpu, cpusetp) \\\n  ((cpusetp)->__bits[(cpu) / __NCPUBITS] |= (1UL << ((cpu) % __NCPUBITS)))\n#define CPU_ZERO(cpusetp) memset((cpusetp), 0, sizeof(cpu_set_t))\n#define CPU_ISSET(cpu, cpusetp)    \\\n  (1UL << ((cpu) % __NCPUBITS)) == \\\n      ((cpusetp)->__bits[(cpu) / __NCPUBITS] & (1UL << ((cpu) % __NCPUBITS)))\n#define CPU_EQUAL(left, right) (memcmp(&left, &right, sizeof(cpu_set_t)) == 0)\n\n#endif\n#endif\n#endif\n\nnamespace tvm {\nnamespace runtime {\nnamespace threading {\n\n/*!\n * \\brief A platform-agnostic abstraction for managing a collection of\n *        thread pool threads.\n */\nclass ThreadGroup {\n public:\n  class Impl;\n\n  /*!\n   * \\brief Creates a collection of threads which run a provided function.\n   *\n   * \\param num_workers The total number of worker threads in this group.\n            Includes main thread if `exclude_worker0 = true`\n   * \\param worker_callback A callback which is run in its own thread.\n            Receives the worker_id as an argument.\n   * \\param exclude_worker0 Whether to use the main thread as a worker.\n   *        If  `true`, worker0 will not be launched in a new thread and\n   *        `worker_callback` will only be called for values >= 1. This\n   *        allows use of the main thread as a worker.\n   */\n  ThreadGroup(int num_workers, std::function<void(int)> worker_callback,\n              bool exclude_worker0 = false);\n  ~ThreadGroup();\n\n  /*!\n   * \\brief Blocks until all non-main threads in the pool finish.\n   */\n  void Join();\n\n  enum AffinityMode : int {\n    kBig = 1,\n    kLittle = -1,\n    /*Different threads will get different affinities.*/\n    kSpecifyOneCorePerThread = -2,\n    /*All threads will get the same core group affinity.*/\n    kSpecifyThreadShareAllCore = -3,\n  };\n  /*!\n   * \\brief configure the CPU id affinity\n   *\n   * \\param mode The preferred CPU type (1 = big, -1 = little ...).\n   * \\param nthreads The number of threads to use (0 = use all).\n   * \\param exclude_worker0 Whether to use the main thread as a worker.\n   *        If  `true`, worker0 will not be launched in a new thread and\n   *        `worker_callback` will only be called for values >= 1. This\n   *        allows use of the main thread as a worker.\n   * \\param cpus A list of CPU used to set 'cpu affinity'.\n   *\n   * \\return The number of workers to use.\n   */\n  int Configure(AffinityMode mode, int nthreads, bool exclude_worker0,\n                std::vector<unsigned int> cpus = {});\n\n private:\n  Impl* impl_;\n};\n\n/*!\n * \\brief Platform-agnostic no-op.\n */\nvoid Yield();\n/*!\n * \\return the maximum number of effective workers for this system.\n */\nint MaxConcurrency();\n/*!\n * \\brief Setting the maximum number of available cores.\n */\nvoid SetMaxConcurrency(int value);\n/*!\n * \\brief Reset the threads in the pool. All current threads are destroyed and\n * new ones are created.\n *\n * Note that this does nothing when openmp is used.\n */\nvoid ResetThreadPool();\n\n/*!\n * \\brief Configuring the CPU affinity mode for the working threads.\n * \\param mode The preferred CPU type (1 = big, -1 = little, -2 = kSpecifyOneCorePerThread,\n *  -3 = kSpecifyThreadShareAllCore).\n * \\param nthreads The number of threads to use (0 = use all).\n * \\param cpus A list of CPUs is used to set the 'cpu affinity' for the worker threads.\n */\nTVM_DLL void Configure(tvm::runtime::threading::ThreadGroup::AffinityMode mode, int nthreads,\n                       std::vector<unsigned int> cpus);\n\n/*!\n * \\brief Get the number of threads being used by the TVM runtime\n * \\returns The number of threads used.\n */\nint32_t NumThreads();\n\n}  // namespace threading\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_THREADING_BACKEND_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/vm/bytecode.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/vm/bytecode.h\n * \\brief The bytecode for Relay virtual machine.\n */\n#ifndef TVM_RUNTIME_VM_BYTECODE_H_\n#define TVM_RUNTIME_VM_BYTECODE_H_\n\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/logging.h>\n\n#include <iostream>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\n/*! \\brief A register name. */\nusing RegName = int64_t;\n\n/*! \\brief An alias for the integer type used ubiquitously\n * in the VM.\n */\nusing Index = int64_t;\n\n/*! \\brief An enumeration of Relay's opcodes.\n *\n * The opcode is used to implement instruction\n * as a tagged union.\n */\nenum class Opcode {\n  Move = 0U,\n  Ret = 1U,\n  Invoke = 2U,\n  InvokeClosure = 3U,\n  InvokePacked = 4U,\n  AllocTensor = 5U,\n  AllocTensorReg = 6U,\n  AllocADT = 7U,\n  AllocClosure = 8U,\n  GetField = 9U,\n  If = 10U,\n  LoadConst = 11U,\n  Goto = 12U,\n  GetTag = 13U,\n  LoadConsti = 14U,\n  Fatal = 15U,\n  AllocStorage = 16U,\n  ShapeOf = 17U,\n  ReshapeTensor = 18U,\n  DeviceCopy = 19U,\n  KillRegister = 20U,\n};\n\n/*! \\brief A single virtual machine instruction.\n *\n * The representation of the instruction is as\n * a tagged union.\n *\n * The first field represents which instruction,\n * and by extension which field of the union\n * is active.\n */\nstruct Instruction {\n  /*! \\brief The instruction opcode. */\n  Opcode op;\n\n  /*! \\brief The destination register. */\n  RegName dst;\n\n  union {\n    struct /* AllocTensor Operands */ {\n      /*! \\brief The storage to allocate from. */\n      RegName storage;\n      /*! \\brief The offset into the storage to allocate from. */\n      Index offset;\n      /*! \\brief The number of dimensions. */\n      uint32_t ndim;\n      /*! \\brief The shape of tensor. */\n      int64_t* shape;\n      /*! \\brief The datatype of tensor to be allocated. */\n      DLDataType dtype;\n    } alloc_tensor;\n    struct /* AllocTensorReg Operands */ {\n      /*! \\brief The storage to allocate from. */\n      RegName storage;\n      /*! \\brief The offset into the storage to allocate from. */\n      Index offset;\n      /*! \\brief The register to read the shape out of. */\n      RegName shape_register;\n      /*! \\brief The datatype of tensor to be allocated. */\n      DLDataType dtype;\n    } alloc_tensor_reg;\n    struct /* InvokeClosure Operands */ {\n      /*! \\brief The register containing the closure. */\n      RegName closure;\n      /*! \\brief The number of arguments to the closure. */\n      Index num_closure_args;\n      /*! \\brief The closure arguments as an array. */\n      RegName* closure_args;\n    };\n    struct /* Return Operands */ {\n      /*! \\brief The register to return. */\n      RegName result;\n    };\n    struct /* Move Operands */ {\n      /*! \\brief The source register for a move operation. */\n      RegName from;\n    };\n    struct /* InvokePacked Operands */ {\n      /*! \\brief The index into the packed function table. */\n      Index packed_index;\n      /*! \\brief The arity of the packed function. */\n      Index arity;\n      /*! \\brief The number of outputs produced by the packed function. */\n      Index output_size;\n      /*! \\brief The arguments to pass to the packed function. */\n      RegName* packed_args;\n    };\n    struct /* If Operands */ {\n      /*! \\brief The register containing the test value. */\n      RegName test;\n      /*! \\brief The register containing the target value. */\n      RegName target;\n      /*! \\brief The program counter offset for the true branch. */\n      Index true_offset;\n      /*! \\brief The program counter offset for the false branch. */\n      Index false_offset;\n    } if_op;\n    struct /* Invoke Operands */ {\n      /*! \\brief The function to call. */\n      Index func_index;\n      /*! \\brief The number of arguments to the function. */\n      Index num_args;\n      /*! \\brief The registers containing the arguments. */\n      RegName* invoke_args_registers;\n    };\n    struct /* LoadConst Operands */ {\n      /* \\brief The index into the constant pool. */\n      Index const_index;\n    };\n    struct /* LoadConsti Operands */ {\n      /* \\brief The index into the constant pool. */\n      Index val;\n    } load_consti;\n    struct /* Jump Operands */ {\n      /*! \\brief The jump offset. */\n      Index pc_offset;\n    };\n    struct /* Proj Operands */ {\n      /*! \\brief The register to project from. */\n      RegName object;\n      /*! \\brief The field to read out. */\n      Index field_index;\n    };\n    struct /* GetTag Operands */ {\n      /*! \\brief The register to project from. */\n      RegName object;\n    } get_tag;\n    struct /* AllocADT Operands */ {\n      // TODO(mbs): Needs a DeviceAndScope.\n      /*! \\brief The datatype's constructor tag. */\n      Index constructor_tag;\n      /*! \\brief The number of fields to store in the datatype. */\n      Index num_fields;\n      /*! \\brief The fields as an array. */\n      RegName* datatype_fields;\n    };\n    struct /* AllocClosure Operands */ {\n      // TODO(mbs): Needs a DeviceAndScope.\n      /*! \\brief The index into the function table. */\n      Index clo_index;\n      /*! \\brief The number of free variables to capture. */\n      Index num_freevar;\n      /*! \\brief The free variables as an array. */\n      RegName* free_vars;\n    };\n    struct /* AllocStorage Operands */ {\n      /*! \\brief The size of the allocation. */\n      RegName allocation_size;\n      /*! \\brief The alignment of the allocation. */\n      Index alignment;\n      /*! \\brief The hint of the dtype. */\n      DLDataType dtype_hint;\n      /*! \\brief The index of the device on which the allocation will be made. */\n      Index device_index;\n    } alloc_storage;\n    struct /* ShapeOf Operands */ {\n      RegName tensor;\n    } shape_of;\n    struct /* ReshapeTensor Operands */ {\n      RegName tensor;\n      RegName newshape;\n    } reshape_tensor;\n    struct /* DeviceCopy Operands */ {\n      RegName src;\n      /*! \\brief The index of the source device to copy from. */\n      Index src_device_index;\n      /*! \\brief The index of the destination deviceto copy to. */\n      Index dst_device_index;\n    } device_copy;\n  };\n\n  /*!\n   * \\brief Construct a return instruction.\n   * \\param return_reg The register containing the return value.\n   * \\return The return instruction.\n   */\n  static Instruction Ret(RegName return_reg);\n  /*!\n   * \\brief Construct a fatal instruction.\n   * \\return The fatal instruction.\n   */\n  static Instruction Fatal();\n  /*!\n   * \\brief Construct a invoke packed instruction.\n   * \\param packed_index The index of the packed function.\n   * \\param arity The arity of the function.\n   * \\param output_size The number of outputs of the packed function.\n   * \\param args The argument registers.\n   * \\return The invoke packed instruction.\n   */\n  static Instruction InvokePacked(Index packed_index, Index arity, Index output_size,\n                                  const std::vector<RegName>& args);\n  /*!\n   * \\brief Construct an allocate tensor instruction with constant shape.\n   * \\param storage The storage to allocate out of.\n   * \\param offset The offset to allocate at.\n   * \\param shape The shape of the tensor.\n   * \\param dtype The dtype of the tensor.\n   * \\param dst The destination register.\n   * \\return The allocate tensor instruction.\n   */\n  static Instruction AllocTensor(RegName storage, Index offset, const std::vector<int64_t>& shape,\n                                 DLDataType dtype, RegName dst);\n  /*!\n   * \\brief Construct an allocate tensor instruction with register.\n   * \\param storage The storage to allocate out of.\n   * \\param offset The offset into the storage to allocate from.\n   * \\param shape_register The register containing the shape.\n   * \\param dtype The dtype of the tensor.\n   * \\param dst The destination register.\n   * \\return The allocate tensor instruction.\n   */\n  static Instruction AllocTensorReg(RegName storage, Index offset, RegName shape_register,\n                                    DLDataType dtype, RegName dst);\n  /*!\n   * \\brief Construct an allocate datatype instruction.\n   * \\param tag The datatype tag.\n   * \\param num_fields The number of fields for the datatype.\n   * \\param fields The registers containing the fields.\n   * \\param dst The register name of the destination.\n   * \\return The allocate instruction tensor.\n   */\n  static Instruction AllocADT(Index tag, Index num_fields, const std::vector<RegName>& fields,\n                              RegName dst);\n  /*!\n   * \\brief Construct an allocate closure instruction.\n   * \\param func_index The index of the function table.\n   * \\param num_freevar The number of free variables.\n   * \\param free_vars The registers of the free variables.\n   * \\param dst The destination register.\n   * \\return The allocate closure instruction.\n   */\n  static Instruction AllocClosure(Index func_index, Index num_freevar,\n                                  const std::vector<RegName>& free_vars, RegName dst);\n  /*!\n   * \\brief Construct a get field instruction.\n   * \\param object_reg The register containing the object to project from.\n   * \\param field_index The field to read out of the object.\n   * \\param dst The destination register.\n   * \\return The get field instruction.\n   */\n  static Instruction GetField(RegName object_reg, Index field_index, RegName dst);\n  /*!\n   * \\brief Construct a get_tag instruction.\n   * \\param object_reg The register containing the object to project from.\n   * \\param dst The destination register.\n   * \\return The get_tag instruction.\n   */\n  static Instruction GetTag(RegName object_reg, RegName dst);\n  /*!\n   * \\brief Construct an if instruction.\n   * \\param test The register containing the test value.\n   * \\param target The register containing the target value.\n   * \\param true_branch The offset to the true branch.\n   * \\param false_branch The offset to the false branch.\n   * \\return The if instruction.\n   */\n  static Instruction If(RegName test, RegName target, Index true_branch, Index false_branch);\n  /*!\n   * \\brief Construct a goto instruction.\n   * \\param pc_offset The offset from the current pc.\n   * \\return The goto instruction.\n   */\n  static Instruction Goto(Index pc_offset);\n  /*!\n   * \\brief Construct an invoke instruction.\n   * \\param func_index The index of the function to invoke.\n   * \\param args The registers containing the arguments.\n   * \\param dst The destination register.\n   * \\return The invoke instruction.\n   */\n  static Instruction Invoke(Index func_index, const std::vector<RegName>& args, RegName dst);\n  /*!\n   * \\brief Construct an invoke closure instruction.\n   * \\param closure The register of the closure to invoke.\n   * \\param args The registers containing the arguments.\n   * \\param dst The destination register.\n   * \\return The invoke closure instruction.\n   */\n  static Instruction InvokeClosure(RegName closure, const std::vector<RegName>& args, RegName dst);\n  /*!\n   * \\brief Construct a load constant instruction.\n   * \\param const_index The index of the constant.\n   * \\param dst The destination register.\n   * \\return The load constant instruction.\n   */\n  static Instruction LoadConst(Index const_index, RegName dst);\n  /*!\n   * \\brief Construct a load_constanti instruction.\n   * \\param val The interger constant value.\n   * \\param dst The destination register.\n   * \\return The load_constanti instruction.\n   */\n  static Instruction LoadConsti(Index val, RegName dst);\n  /*!\n   * \\brief Construct a move instruction.\n   * \\param src The source register.\n   * \\param dst The destination register.\n   * \\return The move instruction.\n   */\n  static Instruction Move(RegName src, RegName dst);\n  /*!\n   * \\brief Allocate a storage block.\n   * \\param size The size of the allocation.\n   * \\param alignment The allocation's alignment.\n   * \\param dtype_hint The data type hint for the allocator.\n   * \\param device_index The index of the device to allocate on.\n   * \\param dst The destination to place the storage.\n   * \\return The alloc storage instruction.\n   */\n  static Instruction AllocStorage(RegName size, Index alignment, DLDataType dtype_hint,\n                                  Index device_index, RegName dst);\n  /*!\n   * \\brief Get the shape of an input tensor.\n   * \\param tensor The input tensor.\n   * \\param dst The destination to store the shape of the given tensor.\n   * \\return The shape of instruction.\n   */\n  static Instruction ShapeOf(RegName tensor, RegName dst);\n  /*!\n   * \\brief Reshape the tensor given the new shape.\n   * \\param tensor The input tensor.\n   * \\param newshape The shape tensor.\n   * \\param dst The destination to store the output tensor with new shape.\n   * \\return The reshape tensor instruction.\n   */\n  static Instruction ReshapeTensor(RegName tensor, RegName newshape, RegName dst);\n  /*!\n   * \\brief Copy tensor cross different devices.\n   * \\param src The source register.\n   * \\param src_device_index The index of the device holding the tensor in the source register.\n   * \\param dst_device_index The index of the device to hold the tensor in the destination register.\n   * \\param dst The destination register to store the copied tensor.\n   * \\return The device copy instruction.\n   */\n  static Instruction DeviceCopy(RegName src, Index src_device_index, Index dst_device_index,\n                                RegName dst);\n\n  static Instruction KillRegister(RegName dst);\n\n  Instruction();\n  Instruction(const Instruction& instr);\n  Instruction& operator=(const Instruction& instr);\n  ~Instruction();\n\n  friend std::ostream& operator<<(std::ostream& os, const Instruction&);\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_BYTECODE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/vm/executable.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/vm/executable.h\n * \\brief The Relay virtual machine executable.\n */\n#ifndef TVM_RUNTIME_VM_EXECUTABLE_H_\n#define TVM_RUNTIME_VM_EXECUTABLE_H_\n\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/vm/bytecode.h>\n\n#include <map>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\nstruct VMFunction;\n\n/*!\n * \\brief The executable emitted by the VM compiler.\n *\n * The executable contains information (e.g. data in different memory regions)\n * to run in a virtual machine.\n *\n *  - Global section, containing all globals.\n *  - Constant section, storing the constant pool.\n *  - Primitive name section, containing the function name of the primitive ops\n *  used by the virtual machine.\n *  - Code section, handling the VM functions and bytecode.\n */\nclass TVM_DLL Executable : public ModuleNode {\n public:\n  /*!\n   * \\brief Get a PackedFunc from an executable module.\n   *\n   * \\param name the name of the function.\n   * \\param sptr_to_self The shared_ptr that points to this module node.\n   *\n   * \\return PackedFunc or nullptr when it is not available.\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n\n  /*!\n   * \\brief Write the Executable to the binary stream in serialized form.\n   *\n   * Late-bound constants (if any) must have already been saved by \\p\n   * MoveLateBoundConstantsToBinary.\n   *\n   * \\param stream The binary stream to save the executable to.\n   */\n  void SaveToBinary(dmlc::Stream* stream) final;\n\n  /*!\n   * \\brief Write the Executable to the provided path as a file containing its serialized content.\n   *\n   * Late-bound constants (if any) must have already been saved by \\p\n   * MoveLateBoundConstantsToBinary.\n   *\n   * \\param path The path to write the serialized data to.\n   * \\param format The format of the serialized blob.\n   */\n  void SaveToFile(const std::string& path, const std::string& format) final;\n\n  /*!\n   * \\brief Serialize the executable into global section, constant section, and\n   * code section. This object must outlive the returned byte array.\n   *\n   * Late-bound constants (if any) must have already been saved by \\p\n   * MoveLateBoundConstantsToBinary.\n   *\n   * \\return The binary representation of the VM.\n   */\n  TVMByteArray Save();\n\n  /*!\n   * \\brief Load the saved VM executable.\n   *\n   * Late-bound constants (if any) must then be loaded by \\p LoadLateBoundConstantsFromBinary.\n   *\n   * \\param code The bytecode in string.\n   * \\param lib The compiled runtime library.\n   *\n   * \\return exe The constructed executable.\n   */\n  static runtime::Module Load(const std::string& code, const runtime::Module lib);\n\n  /*!\n   * \\brief Returns the late-bound constants for the executable (if any) as a byte-stream.\n   * Leaves the executable's late-bound constants map empty. Only constants who's byte\n   * tensor size is greater than or equal to \\p byte_limit are marked as late-bound. \\p byte_limit\n   * may be zero.\n   *\n   * Must be called before \\p SaveToBinary and friends if late-bound constants are\n   * desired. Otherwise can be ignore.\n   */\n  void MoveLateBoundConstantsToStream(dmlc::Stream* stream, size_t byte_limit);\n\n  /*!\n   * \\brief As for \\p MoveLateBoundConstantsToStream, but save to file at \\p path.\n   */\n  void MoveLateBoundConstantsToFile(const std::string& path, size_t byte_limit);\n\n  /*!\n   * \\brief Get a map of all constants with larger that byte_limit in size.\n   */\n  Map<String, NDArray> GetLateBoundConstants(size_t byte_limit);\n\n  /*!\n   * \\brief Restores the late-bound constants for the executable (if any) from given byte-stream.\n   *\n   * Must be called after \\p Load but before any other methods if \\p MoveLateBoundConstantsToBinary\n   * was used when saving. Otherwise can be ignored.\n   */\n  void LoadLateBoundConstantsFromStream(dmlc::Stream* stream);\n\n  /*!\n   * \\brief Restores the late-bound constants for the executable (if any) from given map.\n   *\n   * Must be called after \\p Load but before any other methods if \\p MoveLateBoundConstantsToBinary\n   * was used when saving. Otherwise can be ignored.\n   */\n  void LoadLateBoundConstantsFromMap(Map<String, NDArray> map);\n\n  /*!\n   * \\brief As for \\p LoadLateBoundConstantsFromStream, but load from file at \\p path.\n   */\n  void LoadLateBoundConstantsFromFile(const std::string& path);\n\n  /*!\n   * \\brief Get the serialized form of the `functions`. This is\n   * essentially bytecode serialization.\n   *\n   * \\return The serialized vm bytecode.\n   *\n   * \\note The bytecode is in the following format:\n   *   func_name reg_file_size num_instructions\n   *   param1 param2 ... paramM\n   *   instruction1\n   *   instruction2\n   *   ...\n   *   instructionN\n   *\n   * Each instruction is printed in the following format:\n   *   opcode num_fields field1 ... fieldX # The text format.\n   *\n   * Serializing an `Instruction` requires us to deal with the bytecode. Each line\n   * of the instructions could be serialized as the following format:\n   *   hash, opcode, f1, f2, ..., fX, field with variable length\n   *   1. hash: the hash of the instruction. This number will be used to help us\n   * validate if an instruction is well-formed during deserialization.\n   *   2. opcode: the opcode code of the instruction.\n   *   3. f1, f2, ..., fX. These fields together represent the fixed fields in\n   * an instruction, e.g., `from` and `dst` fields of a `Move` instruction. For\n   * example, `DLDataType` will be unpacked into three fields (code, bits, lanes).\n   *   4. The rest of the line indicates the field with variable length, e.g.,\n   * the shape of a tensor, the args used by an `InvokPacked` instruction, etc.\n   *\n   * The field starting from # is only used for debugging. The serialized code\n   * doesn't contain it, therefore the deserializer doens't need to handle it.\n   */\n  std::string GetBytecode() const;\n\n  /*!\n   * \\brief Returns a description of all the constants in the executable in human-readable\n   * format. Intended for debugging and diff-testing.\n   */\n  std::string GetConstants() const;\n\n  /*!\n   * \\brief Returns a description of all the (virtual) devices in the executable in human-readable\n   * format. Intended for debugging and diff-testing.\n   */\n  std::string GetVirtualDevices() const;\n\n  /*!\n   * \\brief Returns a description of all the 'primitive' (ie PackedFuncs) in the executable in\n   * human-readable format. These correspond either to PrimFuncs we've compiled locally, or\n   * functions compiled by a BYOC external codegen. Intended for debugging and diff-testing.\n   */\n  std::string GetPrimitives() const;\n\n  /*!\n   * \\brief Print the detailed statistics of the given code, i.e. number of\n   * globls and constants, etc.\n   */\n  std::string Stats() const;\n\n  /*!\n   * \\brief Get the `lib` module in an executable. Users have the flexibility to call\n   * `export_library` from the frontend to save the library to disk.\n   *\n   * \\return The runtime module that contains the hardware dependent code.\n   */\n  runtime::Module GetLib() const;\n\n  /*!\n   * \\brief Set the `lib` module in an executable.\n   *\n   * This allows us to do partial initialization in the case of (de|ser)ialization cases.\n   * This method also ensures correct initialization of library ensuring we only Import a\n   * single library.\n   *\n   * NB: This also provides some abstraction over how libraries are stored as there are plans\n   * to iterate on the way runtime::Module works in the backend of the compiler.\n   */\n  void SetLib(const runtime::Module& lib);\n\n  /*!\n   * \\brief Get VMFunction.\n   * \\param func_name The function's name.\n   * \\return VMFunction.\n   */\n  const VMFunction& GetVMFunctionWithName(const std::string& func_name) const;\n\n  /*!\n   * \\brief Get the arity of the VMFunction.\n   * \\param func Function name.\n   * \\return The number of parameters.\n   */\n  int GetFunctionArity(std::string func) const;\n\n  /*!\n   * \\brief Get the parameter name given the function name and parameter index.\n   * \\param func Function name.\n   * \\param index Parameter index.\n   * \\return The parameter name.\n   */\n  std::string GetFunctionParameterName(std::string func, uint32_t index) const;\n\n  virtual ~Executable() {}\n\n  const char* type_key() const final { return \"VMExecutable\"; }\n\n  /*!\n   * \\brief The (compile-time, virtual) devices corresponding to each device index.\n   * Currently we only support at most one device per device type.\n   */\n  std::vector<Device> virtual_devices;\n  /*!\n   * \\brief The device index corresponding to the 'host' device. That will hold and evaluate\n   * shape-related data and code.\n   */\n  int host_device_index = -1;\n  /*!\n   * \\brief The global constant array.\n   *\n   * LoadConst instructions indexes are w.r.t. this vector. Late-bound constants are removed\n   * from this table after saving late-bound constants.\n   */\n  std::vector<ObjectRef> constants;\n  /*!\n   * \\brief For each constant index the name of the late-bound constant, or null if constant is\n   * immediate. Only populated after loading executable but before loading late-bound constants.\n   */\n  std::vector<String> late_bound_constant_names;\n\n  /*! \\brief A map from globals (as strings) to their index in the Relay function map. */\n  std::unordered_map<std::string, Index> global_map;\n  /*! \\brief A mapping from the packed function's global name (as string) to the index that\n   * corresponds to the position of the `packed_funcs` list in a `VirtualMachine` object.\n   */\n  std::unordered_map<std::string, Index> primitive_map;\n  /*! \\brief The structural hashes of the operators in this function. */\n  std::map<Index, Map<String, ObjectRef>> op_attrs;\n  /*! \\brief The virtual machine's function table. */\n  std::vector<VMFunction> functions;\n  /*! \\brief The index of the device holding each constant. */\n  std::vector<Index> const_device_indexes;\n\n private:\n  /*!\n   * \\brief Save the virtual devices\n   *\n   * /param strm The output stream.\n   */\n  void SaveVirtualDevicesSection(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Save the globals.\n   *\n   * \\param strm The output stream.\n   */\n  void SaveGlobalSection(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Save the constant pool.\n   *\n   * \\param stream The output stream.\n   */\n  void SaveConstantSection(dmlc::Stream* stream);\n\n  /*!\n   * \\brief Load the constant pool.\n   *\n   * \\param stream The input stream.\n   */\n  void LoadConstantSection(dmlc::Stream* stream);\n\n  /*!\n   * \\brief Save primitive op names.\n   *\n   *  \\param strm The output stream.\n   */\n  void SavePrimitiveOpNames(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Save the vm functions.\n   *\n   * \\param strm The output stream.\n   */\n  void SaveCodeSection(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Load the virtual devices\n   *\n   * /param strm The input stream.\n   */\n  void LoadVirtualDevicesSection(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Load the globals.\n   *\n   * \\param strm The input stream.\n   */\n  void LoadGlobalSection(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Load primitive op names.\n   *\n   * \\param strm The input stream.\n   */\n  void LoadPrimitiveOpNames(dmlc::Stream* strm);\n\n  /*!\n   * \\brief Load the vm functions.\n   *\n   * \\param strm The input stream.\n   */\n  void LoadCodeSection(dmlc::Stream* strm);\n\n  /*! \\brief The serialized bytecode. */\n  std::string code_;\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_EXECUTABLE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/vm/memory_manager.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/vm/memory_manager.h\n * \\brief Abstract device memory management API\n */\n#ifndef TVM_RUNTIME_VM_MEMORY_MANAGER_H_\n#define TVM_RUNTIME_VM_MEMORY_MANAGER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\nstruct Buffer {\n  /*! \\brief The pointer to the allocated block of memory. */\n  void* data{nullptr};\n  /*! \\brief The size of the block. */\n  size_t size{0};\n  /*! \\brief The context of the allocated buffers. */\n  Device device;\n};\n\nenum AllocatorType {\n  kNaive = 1,\n  kPooled,\n};\n\nclass Allocator {\n public:\n  explicit Allocator(AllocatorType type) : type_(type) {}\n  virtual ~Allocator() = default;\n  /*! \\brief Allocate an empty NDArray using from the allocator.\n   *  \\param shape The shape of the NDArray.\n   *  \\param dtype The datatype of the NDArray.\n   *  \\param dev The device where the array is allocated.\n   *  \\return The empty NDArray.\n   */\n  NDArray Empty(std::vector<int64_t> shape, DLDataType dtype, Device dev);\n  /*! \\brief Return the allocator type. */\n  inline AllocatorType type() const { return type_; }\n  /*! \\brief Allocate a buffer given a size, alignment and type.\n   *  \\param nbytes The size of the buffer.\n   *  \\param alignment The alignment of the buffer.\n   *  \\param type_hint A type hint to the allocator.\n   *  \\return A sized allocation in the form of a buffer.\n   */\n  virtual Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) = 0;\n  /*! \\brief Free a buffer allocated by the allocator.\n   *  \\param buffer The buffer to free.\n   */\n  virtual void Free(const Buffer& buffer) = 0;\n  /*! \\brief The amount of memory currently allocated.\n   *  \\return The amount of memory currently allocated.\n   */\n  virtual size_t UsedMemory() const = 0;\n\n private:\n  AllocatorType type_;\n};\n\nclass MemoryManager {\n public:\n  static MemoryManager* Global();\n  /*!\n   * \\brief Get or create an allocator given the context and allocator type.\n   * \\param dev The TVM device\n   * \\param type The allocator type\n   * \\return The memory allocator.\n   */\n  static Allocator* GetOrCreateAllocator(Device dev, AllocatorType type);\n  /*!\n   * \\brief Get an allocator given the context.\n   * \\param dev The TVM device\n   * \\return The memory allocator.\n   */\n  static Allocator* GetAllocator(Device dev);\n\n private:\n  MemoryManager() {}\n\n private:\n  std::mutex mu_;\n  std::unordered_map<Device, std::unique_ptr<Allocator>> allocators_;\n};\n\n/*! \\brief An object representing a storage allocation. */\nclass StorageObj : public Object {\n public:\n  /*! \\brief The index into the VM function table. */\n  Buffer buffer;\n\n  /*! \\brief Allocate an NDArray from a given piece of storage. */\n  NDArray AllocNDArray(size_t offset, std::vector<int64_t> shape, DLDataType dtype);\n\n  /*! \\brief The deleter for an NDArray when allocated from underlying storage. */\n  static void Deleter(Object* ptr);\n\n  ~StorageObj() {\n    auto alloc = MemoryManager::Global()->GetAllocator(buffer.device);\n    alloc->Free(buffer);\n  }\n\n  static constexpr const uint32_t _type_index = TypeIndex::kDynamic;\n  static constexpr const char* _type_key = \"vm.Storage\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StorageObj, Object);\n};\n\n/*! \\brief reference to storage. */\nclass Storage : public ObjectRef {\n public:\n  explicit Storage(Buffer buffer);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Storage, ObjectRef, StorageObj);\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_MEMORY_MANAGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/runtime/vm/vm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/vm/vm.h\n * \\brief The Relay virtual machine runtime.\n */\n#ifndef TVM_RUNTIME_VM_VM_H_\n#define TVM_RUNTIME_VM_VM_H_\n\n#include <tvm/runtime/container/closure.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n#include <tvm/runtime/vm/bytecode.h>\n#include <tvm/runtime/vm/executable.h>\n#include <tvm/runtime/vm/memory_manager.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\n/*!\n * \\brief An object representing a vm closure.\n */\nclass VMClosureObj : public ClosureObj {\n public:\n  /*!\n   * \\brief The index into the function list. The function could be any\n   * function object that is compatible to the VM runtime.\n   */\n  size_t func_index;\n  /*! \\brief The free variables of the closure. */\n  std::vector<ObjectRef> free_vars;\n\n  static constexpr const uint32_t _type_index = TypeIndex::kDynamic;\n  static constexpr const char* _type_key = \"vm.Closure\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(VMClosureObj, ClosureObj);\n};\n\n/*! \\brief reference to closure. */\nclass VMClosure : public Closure {\n public:\n  VMClosure(size_t func_index, std::vector<ObjectRef> free_vars);\n  TVM_DEFINE_OBJECT_REF_METHODS(VMClosure, Closure, VMClosureObj);\n};\n\n/*!\n * \\brief A representation of a Relay function in the VM.\n *\n * Contains metadata about the compiled function, as\n * well as the compiled VM instructions.\n */\nstruct VMFunction {\n  /*! \\brief The function's name. */\n  std::string name;\n  /*! \\brief The function parameter names. */\n  std::vector<std::string> params;\n  /*! \\brief The instructions representing the function. */\n  std::vector<Instruction> instructions;\n  /*! \\brief The size of the frame for this function */\n  Index register_file_size = 0;\n  /*! \\brief The indexes for the device holding each function parameter. */\n  std::vector<Index> param_device_indexes;\n\n  VMFunction(std::string name, std::vector<std::string> params,\n             std::vector<Instruction> instructions, Index register_file_size,\n             std::vector<Index> param_device_indexes)\n      : name(std::move(name)),\n        params(std::move(params)),\n        instructions(std::move(instructions)),\n        register_file_size(register_file_size),\n        param_device_indexes(std::move(param_device_indexes)) {\n    ICHECK_EQ(this->params.size(), this->param_device_indexes.size());\n  }\n\n  VMFunction() = default;\n\n  friend std::ostream& operator<<(std::ostream& os, const VMFunction&);\n};\n\n/*!\n * \\brief A representation of a stack frame.\n *\n * A stack frame is a record containing the information needed\n * to restore the caller's virtual machine state after returning\n * from a function call.\n */\nstruct VMFrame {\n  /*! \\brief The return program counter. */\n  Index pc;\n  /*! \\brief The index into the function table, points to the caller. */\n  Index func_index;\n  /*! \\brief The number of arguments. */\n  Index args;\n  /*! \\brief A pointer into the caller function's instructions. */\n  const Instruction* code;\n\n  /*! \\brief Statically allocated space for objects */\n  std::vector<ObjectRef> register_file;\n\n  /*! \\brief Register in caller's frame to put return value */\n  RegName caller_return_register;\n\n  VMFrame(Index pc, Index func_index, Index args, const Instruction* code, Index register_file_size)\n      : pc(pc),\n        func_index(func_index),\n        args(args),\n        code(code),\n        register_file(register_file_size),\n        caller_return_register(0) {}\n};\n\n/*!\n * \\brief The virtual machine.\n *\n * The virtual machine contains all the current execution state,\n * as well as the executable.\n *\n * The goal is to have a single self-contained object,\n * enabling one to easily pass around VMs, execute them on\n * multiple threads, or serialize them to disk or over the\n * wire.\n */\nclass TVM_DLL VirtualMachine : public runtime::ModuleNode {\n public:\n  /*!\n   * \\brief Get a PackedFunc from module.\n   *\n   *  The PackedFunc may not be fully initialized,\n   *  there might still be first time running overhead when\n   *  executing the function on certain devices.\n   *  For benchmarking, use prepare to eliminate\n   *\n   * \\param name the name of the function.\n   * \\param sptr_to_self The shared_ptr that points to this module node.\n   *\n   * \\return PackedFunc(nullptr) when it is not available.\n   *\n   * \\note The function will always remain valid.\n   *   If the function needs resource from the module(e.g. late linking),\n   *   it should capture sptr_to_self.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  virtual ~VirtualMachine() {}\n\n  const char* type_key() const final { return \"VirtualMachine\"; }\n\n  VirtualMachine() : frames_(), func_index_(0), code_(nullptr), pc_(0), exec_(nullptr) {}\n\n  /*!\n   * \\brief load the executable for the virtual machine.\n   * \\param exec The executable.\n   */\n  virtual void LoadExecutable(const ObjectPtr<Executable>& exec);\n\n protected:\n  /*! \\brief Push a call frame on to the call stack. */\n  void PushFrame(Index arg_count, Index ret_pc, const VMFunction& vm_func);\n\n  /*!\n   * \\brief Pop a frame off the call stack.\n   * \\return The number of frames left.\n   */\n  Index PopFrame();\n\n  /*!\n   * \\brief Write to a VM register.\n   * \\param reg The register to write to.\n   * \\param obj The object to write to.\n   */\n  inline void WriteRegister(RegName reg, const ObjectRef& obj);\n\n  /*!\n   * \\brief Read a VM register.\n   * \\param reg The register to read from.\n   * \\return The read object.\n   */\n  ObjectRef ReadRegister(RegName reg) const;\n\n  /*!\n   * \\brief Read a VM register and cast it to int32_t\n   * \\param reg The register to read from.\n   * \\return The read scalar.\n   */\n  int64_t LoadScalarInt(RegName reg) const;\n\n  /*!\n   * \\brief Invoke a VM function.\n   * \\param func The function.\n   * \\param args The arguments to the function.\n   * \\return The object representing the result.\n   */\n  ObjectRef Invoke(const VMFunction& func, const std::vector<ObjectRef>& args);\n\n  // TODO(@jroesch): I really would like this to be a global variable.\n  /*!\n   * \\brief Invoke a VM function by name.\n   * \\param name The function's name.\n   * \\param args The arguments to the function.\n   * \\return The object representing the result.\n   */\n  ObjectRef Invoke(const std::string& name, const std::vector<ObjectRef>& args);\n\n  /*!\n   * \\brief Invoke a VM function.\n   * \\param func The function.\n   * \\param input_args The input arguments to the function.\n   * \\param output_args The pre-allocated output arguments of the function.\n   * \\return The object(s) representing the result.\n   */\n  ObjectRef Invoke(const VMFunction& func, const std::vector<ObjectRef>& input_args,\n                   const std::vector<ObjectRef>& output_args);\n\n  /*!\n   * \\brief Invoke a PackedFunction\n   *\n   * \\param packed_index The offset of the PackedFunction in all functions.\n   * \\param func The PackedFunction to be invoked.\n   * \\param arg_count The number of arguments to the PackedFunction.\n   * \\param output_size The number of outputs of the PackedFunction.\n   * \\param args Arguments to the PackedFunction.\n   *\n   * \\note The return value will be stored in the last output_size slots of args.\n   */\n  virtual void InvokePacked(Index packed_index, const PackedFunc& func, Index arg_count,\n                            Index output_size, const std::vector<ObjectRef>& args);\n\n  /*!\n   * \\brief Initialize the virtual machine for a set of (physical) devices.\n   * \\param physical_devices The set of TVM devices.\n   * \\param alloc_types The allocator types for each device.\n   */\n  void Init(const std::vector<Device>& physical_devices,\n            const std::vector<AllocatorType>& alloc_types);\n\n  /*! \\brief Run VM dispatch loop. */\n  void RunLoop(const std::vector<Index>& output_tensor_reg_indices = {});\n\n  /*! \\brief Get device from the device list based on a given device index. */\n  Device GetDevice(Index device_index) const;\n  Allocator* GetAllocator(Index device_index) const;\n\n  /*!\n   * \\brief Invoke a global setting up the VM state to execute.\n   *\n   * This does not begin execution of the VM.\n   */\n  void InvokeGlobal(const VMFunction& func, const std::vector<ObjectRef>& args);\n\n  /*!\n   * \\brief Set inputs to a function.\n   * \\param name The function name\n   * \\param args args[offset:] are arguments to the\n   * function. If the arguments are not of the correct device for the function,\n   * they will be copied to the device.\n   * \\param offset Starting offset of the arguments in `args`.\n   */\n  void SetInput(std::string name, TVMArgs args, int offset);\n\n  /*!\n   * \\brief Set one input tensor with index or name to a function.\n   * \\param name The function name.\n   * \\param tag index or name of the input tensor .\n   * \\param tensor the input tensor. If the tensor is not of the correct device for the function,\n   * they will be copied to the device.\n   */\n  void SetOneInput(std::string name, const TVMArgValue& tag, const TVMArgValue& tensor);\n\n  /*!\n   * \\brief Set pre-allocated output tensors to a function.\n   * It is native implementation of 'set_outputs' python method.\n   * It is used in scenario when output tensors are allocated outside each invocation.\n   * Note: it sets set_outputs_enabled_[name] true and fill outputs_[name]\n   * but after invocation the first is switched off and the second is cleared\n   * \\param name The function name\n   * \\param args outputs to the function.\n   */\n  void SetOutputs(std::string name, TVMArgs args);\n\n  /*!\n   * \\brief Preparation part of Invoke method before RunLoop.\n   * \\param func the function.\n   * \\param args input args\n   */\n  void PrintInfoAndSetInputArgs(const VMFunction& func, const std::vector<ObjectRef>& args);\n\n  /*!\n   * \\brief Set pre-allocated outputs to register for specified function.\n   * \\param func_name The function's name.\n   * \\param outputs set of output tensors.\n   */\n  void SetOutputTensorsToRegister(const std::string& func_name,\n                                  const std::vector<ObjectRef>& outputs);\n\n  /*!\n   * \\brief Internal hook for profiling the start of an op.\n   *\n   * This hook is only called on certain ops that are likely to take a\n   * significant amount of runtime (normally because they alloc or transfer to\n   * device).\n   *\n   * \\param instr Instruction that will be executed after this hook fires\n   */\n  virtual void OpStartHook(Instruction instr);\n\n  /*!\n   * \\brief Internal hook for profiling the end of an op.\n   */\n  virtual void OpStopHook();\n\n private:\n  /*!\n   * \\brief Get index of input tensor from its name.\n   * \\param func_name The function's name.\n   * \\param input_name The input tensor name.\n   * \\return The input tensor index.\n   */\n  int64_t GetInputIndexFromVMFunction(const std::string& func_name,\n                                      const std::string& input_name) const;\n\n  /*!\n   * \\brief Get index of input tensor from its name.\n   * \\param params parameter names.\n   * \\param input_name The input tensor name.\n   * \\return The input tensor index.\n   */\n  int64_t GetInputIndexFromName(const std::vector<std::string>& params,\n                                const std::string& input_name) const;\n\n  /*!\n   * \\brief Check executable exists and get VM function from it.\n   * \\param func_name The function's name.\n   * \\return VM function.\n   */\n  const VMFunction& CheckAndGetVMFunction(const std::string& func_name) const;\n\n  /*!\n   * \\brief Creats inputs_ field, if it exists check its size.\n   * \\param func_name The function's name.\n   * \\param size inputs_ field size.\n   * \\return VM function.\n   */\n  void CreateInputsOrCheckSize(const std::string& func_name, size_t size);\n\n  /*!\n   * \\brief Set one input tensor with given index to set of input tensors if need copy to given\n   * device. \\param tensors the input tensors set (destination) \\param tensor some tensor (not\n   * necessary DLTensor). \\param index The input tensor index. \\param dev device to copy if need.\n   */\n  void SetInputTensorWithIndex(std::vector<ObjectRef>& tensors,  // NOLINT(*)\n                               const TVMArgValue& tensor, int index, Device dev);\n\n  /*!\n   * \\brief Convert tensor from TVMArgValue to ObjectRef.\n   * DLTensor and NDArray types are supported.\n   * \\param tensor given arg value containing tensor.\n   * \\return tensor in ObjectRef format\n   */\n  ObjectRef TensorFromTVMArgValueToObjectRef(const TVMArgValue& tensor) const;\n\n  /*!\n   * \\brief Get index of outputs in register_file from func code\n   * \\return result register index\n   */\n  Index GetResultRegisterIndex() const;\n\n  /*!\n   * \\brief Calculate the index of operation which destination is result\n   * \\param res_index is the index of op returning result\n   */\n  void CalculatePreResultOpIndex(Index res_index);\n\n  /*!\n   * \\brief Get indices from register_file for output tensors.\n   * It helps to replace output tensors allocated in RunLoop by\n   * tensors pre-allocated outside. Scenario is when `set_output` is used\n   * \\return indices from register_file for output tensors.\n   */\n  std::vector<Index> GetOutputTensorRegIndices();\n\n  /*!\n   * \\brief Write new allocated tensor to register_file of frame.\n   * \\param instr current instruction containing shape and storage info.\n   */\n  void WriteAllocatedTensor(const Instruction& instr);\n\n  /*!\n   * \\brief 'set_outputs_enabled' is assumed true for using this method.\n   * It is expected that result register has already contained tensor from outside,\n   * new memory is not allocated and write, but expected shape and data type are checked.\n   * For other register WriteAllocatedTensor method is used.\n   * \\param instr current instruction containing shape and storage info.\n   */\n  void WriteAllocatedTensorFromOutside(const Instruction& instr);\n\n  bool FindIndex(const std::vector<Index>& indices, Index val) const;\n\n protected:\n  /*! \\brief The virtual machine's packed function table. */\n  std::vector<PackedFunc> packed_funcs_;\n  /*! \\brief The current stack of call frames. */\n  std::vector<VMFrame> frames_;\n  /*! \\brief The fuction table index of the current function. */\n  Index func_index_;\n  /*! \\brief The current pointer to the code section. */\n  const Instruction* code_;\n  /*! \\brief The virtual machine PC. */\n  Index pc_;\n  /*! \\brief The special return register. */\n  ObjectRef return_register_;\n  /*! \\brief The executable the VM will operate on. */\n  ObjectPtr<Executable> exec_;\n  /*! \\brief The function name to inputs mapping. */\n  std::unordered_map<std::string, std::vector<ObjectRef>> inputs_;\n  /*! \\brief The function name to flag enabling scenario with set outputs. */\n  std::unordered_map<std::string, bool> set_outputs_enabled_;\n  /*! \\brief The index of operation which destination is result. */\n  Index preresult_op_index_ = -1;\n  /*! \\brief The function name to indices of output tensors in register file. */\n  std::unordered_map<std::string, std::vector<Index>> output_tensor_reg_indices_;\n  /*! \\brief The function name to pre-allocated outputs mapping. */\n  std::unordered_map<std::string, std::vector<ObjectRef>> outputs_;\n  /*!\n   * \\brief The \"physical\" devices the VM can execute primitives on. All \"device indexes\"\n   * are w.r.t. this vector. Each entry in this vector must match the corresponding entry\n   * in the executable's \"virtual\" devices vector.\n   */\n  std::vector<Device> devices_;\n  /*! \\brief The cached memory allocators, one per device. */\n  std::vector<Allocator*> allocators_;\n  /*!\n   * \\brief The constant pool for runtime. It caches the device dependent\n   * object to avoid rellocation of constants during inference.\n   */\n  std::vector<ObjectRef> const_pool_;\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_VM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/ir_builder/base.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_BASE_H_\n#define TVM_SCRIPT_IR_BUILDER_BASE_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/function.h>\n#include <tvm/node/node.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\n\n////////////////////////////// IRBuilderFrame //////////////////////////////\n\n/*!\n * \\brief A stack frame of the IRBuilder used to keep track of the current scope.\n * Furthermore, the information stored in each stack frame can be useful for context-dependent\n * IR construction.\n *\n * \\example\n *\n * The `T::MatchBuffer` below adds an element in `PrimFuncNode::buffer_map`:\n *\n * \\code {.cpp}\n *\n * using T = tvm::script::ir_builder::tir;\n * With <PrimFuncFrame> _(...);\n * Buffer buffer = T::MatchBuffer(...);\n *\n * \\endcode\n *\n * The `T::MatchBuffer` below instead generates `MatchBufferRegion` in a TIR block:\n *\n * \\code {.cpp}\n *\n * using T = tvm::script::ir_builder::tir;\n * With <PrimFuncFrame> _(...);\n * {\n *   With<BlockFrame> _2(...);\n *   Buffer buffer = T::MatchBuffer(...);\n * }\n *\n * \\endcode\n */\nclass IRBuilderFrameNode : public runtime::Object {\n public:\n  /*! \\brief A list of callbacks used when exiting the frame. */\n  std::vector<runtime::TypedPackedFunc<void()>> callbacks;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `callbacks` is not visited.\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.IRBuilderFrame\";\n  TVM_DECLARE_BASE_OBJECT_INFO(IRBuilderFrameNode, runtime::Object);\n\n public:\n  /*! \\brief Default destructor. */\n  virtual ~IRBuilderFrameNode() = default;\n  /*!\n   * \\brief The method called when entering RAII scope.\n   * \\sa tvm::support::With\n   */\n  virtual void EnterWithScope();\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  virtual void ExitWithScope();\n  /*!\n   * \\brief Add a callback method invoked when exiting the RAII scope.\n   * \\param callback The callback to be added.\n   */\n  void AddCallback(runtime::TypedPackedFunc<void()> callback);\n};\n\n/*!\n * \\brief Managed reference to an IRBuilderFrameNode.\n * \\sa IRBuilderFrameNode\n */\nclass IRBuilderFrame : public runtime::ObjectRef {\n public:\n  /*! \\brief Default destructor. */\n  virtual ~IRBuilderFrame() = default;\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(IRBuilderFrame, ObjectRef, IRBuilderFrameNode);\n\n protected:\n  /*! \\brief Disallow direct construction of this object. */\n  IRBuilderFrame() = default;\n\n public:\n  /*!\n   * \\brief Redirected to `IRBuilderFrameNode::EnterWithScope`.\n   * \\sa IRBuilderFrameNode::EnterWithScope\n   */\n  inline void EnterWithScope() {\n    ICHECK(data_ != nullptr);\n    static_cast<IRBuilderFrameNode*>(data_.get())->EnterWithScope();\n  }\n  /*!\n   * \\brief Redirected to `IRBuilderFrameNode::ExitWithScope`.\n   * \\sa IRBuilderFrameNode::ExitWithScope\n   */\n  inline void ExitWithScope() {\n    ICHECK(data_ != nullptr);\n    static_cast<IRBuilderFrameNode*>(data_.get())->ExitWithScope();\n    data_.reset();\n  }\n};\n\n////////////////////////////// IRBuilder //////////////////////////////\n\n/*!\n * \\brief A dialect-agnostic IRBuilder that constructs any IR of TVM.\n * An idiomatic use of this class is to put this inside the RAII with-scope,\n * call dialect-specific methods accordingly. Upon exiting the scope.\n *\n * \\code\n *\n * PrimFunc ConstructPrimFunc() {\n *   using tvm::script::ir_builder::IRBuilder;\n *   using T = tvm::script::ir_builder::tir;\n *   IRBuilder builder;\n *   // Step 1. Place IRBuilder inside the with-scope.\n *   {\n *     With<IRBuilder> _(builder);\n *     // Step 2. Call dialect-specific methods.\n *     With<T::PrimFuncFrame> _2(...);\n *     T::MatchBuffer(...);\n *   }\n *   // Step 3. Return the constructed PrimFunc.\n *   return builder->Get<PrimFunc>();\n * }\n *\n * \\endcode\n */\nclass IRBuilderNode : public runtime::Object {\n public:\n  /*! \\brief A stack of context frames in the IRBuilder */\n  runtime::Array<IRBuilderFrame> frames;\n  /*! \\brief The outcome of IR construction */\n  Optional<ObjectRef> result;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"frames\", &frames);\n    v->Visit(\"result\", &result);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.IRBuilder\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IRBuilderNode, runtime::Object);\n\n public:\n  /*!\n   * \\brief Find a frame of the given type in the stack `this->frames` from top to bottom.\n   * \\tparam T The type of the frame to find.\n   * \\return The frame if found, otherwise NullOpt.\n   */\n  template <typename TFrame>\n  inline Optional<TFrame> FindFrame() const;\n  /*!\n   * \\brief Get the frame on top of the stack `this->frames` if its type is `TFrame`.\n   * \\tparam TFrame The assumed type of the last frame on stack.\n   * \\return The frame if the stack is non-empty and the top of the stack is of type `TFrame`.\n   * Otherwise NullOpt.\n   */\n  template <typename TFrame>\n  inline Optional<TFrame> GetLastFrame() const;\n  /*!\n   * \\brief Get the IR being constructed.\n   * \\tparam TObjectRef The type of the IR being constructed.\n   * \\return The resulting IR. Throw an exception if the IR is not constructed yet.\n   */\n  template <typename TObjectRef>\n  inline TObjectRef Get() const;\n};\n\n/*!\n * \\brief Managed reference to an IRBuilderNode.\n * \\sa IRBuilderNode\n */\nclass IRBuilder : public runtime::ObjectRef {\n public:\n  /*! \\brief Creates an IRBuilder. */\n  IRBuilder();\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(IRBuilder, ObjectRef, IRBuilderNode);\n\n public:\n  /*!\n   * \\brief Puts the current IRBuilder into a thread-local scope, which can be retrieved using\n   * `IRBuilder::Current()`.\n   *\n   * \\code {.cpp}\n   * IRBuilder builder;\n   * {\n   *   With<IRBuilder> _(builder);\n   *   // IRBuilder::Current() == builder\n   * }\n   * // IRBuilder::Current() == nullptr\n   * \\endcode\n   *\n   * \\sa IRBuilder::Current\n   * \\sa IRBuilder::ExitWithScope\n   * \\sa tvm::support::With\n   */\n  void EnterWithScope();\n  /*!\n   * \\brief Exit the RAII scope.\n   * \\sa IRBuilder::EnterWithScope\n   * \\sa IRBuilder::Current\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope();\n  /*!\n   * \\brief Get the current IRBuilder in the current thread-local scope.\n   * \\return The current IRBuilder.\n   * \\sa IRBuilder::EnterWithScope\n   * \\sa IRBuilder::ExitWithScope\n   * \\sa tvm::support::With\n   */\n  static IRBuilder Current();\n  /*!\n   * \\brief Give a string name to the `obj`\n   * \\tparam TObjectRef The type of the object to name.\n   * \\param name The name to give to the object.\n   * \\param obj The object to name.\n   */\n  template <class TObjectRef>\n  inline static TObjectRef Name(String name, TObjectRef obj);\n};\n\n////////////////////////////// Details //////////////////////////////\n\nnamespace details {\n\nclass Namer {\n public:\n  using FType = NodeFunctor<void(const ObjectRef&, String)>;\n  static FType& vtable();\n  static void Name(ObjectRef node, String name);\n};\n\n}  // namespace details\n\ntemplate <class TObjectRef>\ninline TObjectRef IRBuilder::Name(String name, TObjectRef obj) {\n  details::Namer::Name(obj, name);\n  return Downcast<TObjectRef>(obj);\n}\n\ntemplate <typename TFrame>\ninline Optional<TFrame> IRBuilderNode::FindFrame() const {\n  using TFrameNode = typename TFrame::ContainerType;\n  for (auto it = frames.rbegin(); it != frames.rend(); ++it) {\n    if (const TFrameNode* p = (*it).template as<TFrameNode>()) {\n      return GetRef<TFrame>(p);\n    }\n  }\n  return NullOpt;\n}\n\ntemplate <typename TFrame>\ninline Optional<TFrame> IRBuilderNode::GetLastFrame() const {\n  using TFrameNode = typename TFrame::ContainerType;\n  if (!frames.empty() && frames.back()->IsInstance<TFrameNode>()) {\n    return Downcast<TFrame>(frames.back());\n  }\n  return NullOpt;\n}\n\ntemplate <typename TObjectRef>\ninline TObjectRef IRBuilderNode::Get() const {\n  using TObject = typename TObjectRef::ContainerType;\n  CHECK(result.defined()) << \"IndexError: No result exists in IRBuilder yet\";\n  const auto* n = result.as<TObject>();\n  CHECK(n != nullptr) << \"TypeError: IRBuilder result is not of type: \" << TObject::_type_key;\n  return GetRef<TObjectRef>(n);\n}\n\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/ir_builder/ir/frame.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_IR_FRAME_H_\n#define TVM_SCRIPT_IR_BUILDER_IR_FRAME_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/function.h>\n#include <tvm/node/node.h>\n#include <tvm/script/ir_builder/base.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\nnamespace ir {\n\n/*!\n * \\brief A frame that represents the IRModule frame with functions and global variables.\n *\n * \\sa IRModuleFrame\n */\nclass IRModuleFrameNode : public IRBuilderFrameNode {\n public:\n  Array<GlobalVar> global_vars;\n  Array<BaseFunc> functions;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    IRBuilderFrameNode::VisitAttrs(v);\n    v->Visit(\"global_vars\", &global_vars);\n    v->Visit(\"functions\", &functions);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.IRModuleFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IRModuleFrameNode, IRBuilderFrameNode);\n\n public:\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to IRModuleFrameNode.\n *\n * \\sa IRModuleFrameNode\n */\nclass IRModuleFrame : public IRBuilderFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(IRModuleFrame, IRBuilderFrame,\n                                                    IRModuleFrameNode);\n};\n\n}  // namespace ir\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_IR_FRAME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/ir_builder/ir/ir.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_IR_IR_H_\n#define TVM_SCRIPT_IR_BUILDER_IR_IR_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/function.h>\n#include <tvm/node/node.h>\n#include <tvm/script/ir_builder/ir/frame.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\nnamespace ir {\n\n/*!\n * \\brief The IRModule declaration statement.\n * \\return The IRModuleFrame.\n */\nTVM_DLL IRModuleFrame IRModule();\n\n}  // namespace ir\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_IR_IR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/ir_builder/tir/frame.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_TIR_FRAME_H_\n#define TVM_SCRIPT_IR_BUILDER_TIR_FRAME_H_\n\n#include <tvm/script/ir_builder/base.h>\n#include <tvm/script/ir_builder/ir/frame.h>\n#include <tvm/tir/stmt.h>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\nnamespace tir {\n\n/*!\n * \\brief A base frame that represents the TIR fame with body of statements.\n *\n * \\sa TIRFrame\n */\nclass TIRFrameNode : public IRBuilderFrameNode {\n public:\n  /*! \\brief The Stmt within in this frame. */\n  Array<tvm::tir::Stmt> stmts;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    IRBuilderFrameNode::VisitAttrs(v);\n    v->Visit(\"stmts\", &stmts);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.TIRFrame\";\n  TVM_DECLARE_BASE_OBJECT_INFO(TIRFrameNode, IRBuilderFrameNode);\n};\n\n/*!\n * \\brief Managed reference to TIRFrameNode.\n *\n * \\sa TIRFrameNode\n */\nclass TIRFrame : public IRBuilderFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(TIRFrame, IRBuilderFrame, TIRFrameNode);\n\n protected:\n  TIRFrame() = default;\n};\n\n/*!\n * \\brief A frame that represents the PrimFunc containing TIR statements.\n *\n * \\sa PrimFuncFrame\n */\nclass PrimFuncFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The name of the block. */\n  Optional<String> name;\n  /*! \\brief Function parameters. */\n  Array<tvm::tir::Var> args;\n  /*! \\brief The return type of the function. */\n  Optional<Type> ret_type;\n  /*! \\brief Maps some parameters to specific Buffer data structures. */\n  Map<tvm::tir::Var, tvm::tir::Buffer> buffer_map;\n  /*! \\brief The buffer map prior to flattening. */\n  Map<tvm::tir::Var, tvm::tir::Buffer> preflattened_buffer_map;\n  /*! \\brief Additional attributes storing the meta-data */\n  Optional<Map<String, ObjectRef>> attrs;\n  /*! \\brief The variable map bound to thread env. */\n  Map<tvm::tir::Var, tvm::tir::IterVar> env_threads;\n  /*! \\brief The buffer allocated in root block. */\n  Array<tvm::tir::Buffer> root_alloc_buffers;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"name\", &name);\n    v->Visit(\"args\", &args);\n    v->Visit(\"ret_type\", &ret_type);\n    v->Visit(\"buffer_map\", &buffer_map);\n    v->Visit(\"preflattened_buffer_map\", &preflattened_buffer_map);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"env_threads\", &env_threads);\n    v->Visit(\"root_alloc_buffers\", &root_alloc_buffers);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.PrimFuncFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PrimFuncFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to PrimFuncFrameNode.\n *\n * \\sa PrimFuncFrameNode\n */\nclass PrimFuncFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(PrimFuncFrame, TIRFrame, PrimFuncFrameNode);\n};\n\n/*!\n * \\brief A frame that represents the block.\n *\n * \\sa BlockFrame\n */\nclass BlockFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The name of the block. */\n  String name;\n  /*! \\brief The variables of the block. */\n  Array<tvm::tir::IterVar> iter_vars;\n  /*! \\brief The read buffer regions of the block. */\n  Optional<Array<tvm::tir::BufferRegion>> reads;\n  /*! \\brief The write buffer regions of the block. */\n  Optional<Array<tvm::tir::BufferRegion>> writes;\n  /*! \\brief The init statement of the bolck. */\n  Optional<tvm::tir::Stmt> init;\n  /*! \\brief The buffer allocated in the block. */\n  Array<tvm::tir::Buffer> alloc_buffers;\n  /*! \\brief The match buffer regions. */\n  Array<tvm::tir::MatchBufferRegion> match_buffers;\n  /*! \\brief The annotation of the block. */\n  Optional<Map<String, ObjectRef>> annotations;\n  /*! \\brief The corresponding values of the iter vars. */\n  Array<PrimExpr> iter_values;\n  /*!\n   * \\brief The predicate of the block realization, the block will only be executed when the\n   * predicate is true.\n   */\n  Optional<PrimExpr> predicate;\n  /*! \\brief The flag whether to construct BlockRealize or Block. */\n  bool no_realize;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"name\", &name);\n    v->Visit(\"iter_vars\", &iter_vars);\n    v->Visit(\"reads\", &reads);\n    v->Visit(\"writes\", &writes);\n    v->Visit(\"init\", &init);\n    v->Visit(\"alloc_buffers\", &alloc_buffers);\n    v->Visit(\"match_buffers\", &match_buffers);\n    v->Visit(\"annotations\", &annotations);\n    v->Visit(\"iter_values\", &iter_values);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"no_realize\", &no_realize);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.BlockFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to BlockFrameNode.\n *\n * \\sa BlockFrameNode\n */\n\nclass BlockFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(BlockFrame, TIRFrame, BlockFrameNode);\n};\n\n/*!\n * \\brief A frame that represents the block initialization statment.\n *\n * \\sa BlockInitFrame\n */\nclass BlockInitFrameNode : public TIRFrameNode {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) { TIRFrameNode::VisitAttrs(v); }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.BlockInitFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockInitFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when entering RAII scope.\n   * \\sa tvm::support::With\n   */\n  void EnterWithScope() final;\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to BlockInitFrameNode.\n *\n * \\sa BlockInitFrameNode\n */\nclass BlockInitFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(BlockInitFrame, TIRFrame, BlockInitFrameNode);\n};\n\n/*!\n * \\brief A frame that represents the for loop.\n *\n * \\sa ForFrame\n */\nclass ForFrameNode : public TIRFrameNode {\n public:\n  /*!\n   * \\brief Functions that generate loop nests.\n   * \\param loop_vars The loop variables, from outer to inner\n   * \\param loop_extents The loop extents that correspond to loop variables\n   * \\param loop_body The loop body\n   * \\return A stmt, the loop nest\n   */\n  using FMakeForLoop = runtime::TypedPackedFunc<tvm::tir::Stmt(\n      Array<tvm::tir::Var> loop_vars, Array<Range> loop_extents, tvm::tir::Stmt loop_body)>;\n  /*! \\brief The loop variable. */\n  Array<tvm::tir::Var> vars;\n  /*! \\brief The domains of iteration. */\n  Array<Range> doms;\n  /*! \\brief The for loop generating function. */\n  FMakeForLoop f_make_for_loop;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"vars\", &vars);\n    v->Visit(\"doms\", &doms);\n    // `f_make_for_loop` is not visited.\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.ForFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ForFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to ForFrameNode.\n *\n * \\sa ForFrameNode\n */\nclass ForFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(ForFrame, TIRFrame, ForFrameNode);\n};\n\n/*!\n * \\brief A frame that represents the assert statement. Proceeds if the condition is true,\n * otherwise aborts with the message.\n *\n * \\sa AssertFrame\n */\nclass AssertFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The PrimExpr to test. */\n  PrimExpr condition;\n  /*! \\brief The output error message when the assertion failed. */\n  PrimExpr message;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"message\", &message);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.AssertFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AssertFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to AssertFrameNode.\n *\n * \\sa AssertFrameNode\n */\nclass AssertFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(AssertFrame, TIRFrame, AssertFrameNode);\n};\n\n/*!\n * \\brief A frame represents the let binding expression, which binds a var.\n *\n * \\sa LetFrameNode\n */\nclass LetFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The variable we bind to */\n  tvm::tir::Var var;\n  /*! \\brief The value we bind var to */\n  PrimExpr value;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"var\", &var);\n    v->Visit(\"value\", &value);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.LetFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LetFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to LetFrameNode.\n *\n * \\sa LetFrameNode\n */\nclass LetFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(LetFrame, TIRFrame, LetFrameNode);\n};\n\n/*!\n * \\brief The LaunchThreadFrameNode.\n * \\note It is used only inside a PrimFunc.\n */\nclass LaunchThreadFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The extent of environment thread. */\n  PrimExpr extent;\n  /*! \\brief The attribute key, could be either virtual_thread or thread_extent. */\n  String attr_key;\n  /*! \\brief The iteration variable. */\n  tvm::tir::IterVar iter_var;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"extent\", &extent);\n    v->Visit(\"attr_key\", &attr_key);\n    v->Visit(\"iter_var\", &iter_var);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.LaunchThreadFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LaunchThreadFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to LaunchThreadFrameNode.\n *\n * \\sa LaunchThreadFrameNode\n */\nclass LaunchThreadFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(LaunchThreadFrame, TIRFrame,\n                                                    LaunchThreadFrameNode);\n};\n\n/*!\n * \\brief A frame that represents realization.\n *\n * \\sa RealizeFrame\n */\nclass RealizeFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The region of buffer access. */\n  tvm::tir::BufferRegion buffer_slice;\n  /*! \\brief The storage scope associated with this realization. */\n  String storage_scope;\n  /*! \\brief The condition expression. */\n  PrimExpr condition;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"buffer_slice\", &buffer_slice);\n    v->Visit(\"storage_scope\", &storage_scope);\n    v->Visit(\"condition\", &condition);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.RealizeFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RealizeFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to RealizeFrameNode.\n *\n * \\sa RealizeFrameNode\n */\nclass RealizeFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(RealizeFrame, TIRFrame, RealizeFrameNode);\n};\n\n/*!\n * \\brief A frame represents the allocate.\n *\n * \\sa AllocateFrame\n */\nclass AllocateFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The extents of the allocate. */\n  Array<PrimExpr> extents;\n  /*! \\brief The data type of the buffer. */\n  DataType dtype;\n  /*! \\brief The storage scope. */\n  String storage_scope;\n  /*! \\brief The condition. */\n  PrimExpr condition;\n  /*! \\brief Additional annotation hints. */\n  Map<String, ObjectRef> annotations;\n  /*! \\brief The buffer var. */\n  tvm::tir::Var buffer_var;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"extents\", &extents);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"storage_scope\", &storage_scope);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"annotations\", &annotations);\n    v->Visit(\"buffer_var\", &buffer_var);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.AllocateFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllocateFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to AllocateFrameNode.\n *\n * \\sa AllocateFrameNode\n */\nclass AllocateFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(AllocateFrame, TIRFrame, AllocateFrameNode);\n};\n\n/*!\n * \\brief A frame represents the allocate constant.\n *\n * \\sa AllocateConstFrame\n */\nclass AllocateConstFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The data type of the buffer. */\n  DataType dtype;\n  /*! \\brief The extents of the allocate. */\n  Array<PrimExpr> extents;\n  /*! \\brief The data associated with the constant. */\n  tvm::runtime::NDArray data;\n  /*! \\brief The buffer var */\n  tvm::tir::Var buffer_var;\n  /*! \\brief Additional annotations about the allocation. */\n  Map<String, ObjectRef> annotations;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"extents\", &extents);\n    v->Visit(\"data\", &data);\n    v->Visit(\"buffer_var\", &buffer_var);\n    v->Visit(\"annotations\", &annotations);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.AllocateConstFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllocateConstFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to AllocateConstFrameNode.\n *\n * \\sa AllocateConstFrameNode\n */\nclass AllocateConstFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(AllocateConstFrame, TIRFrame,\n                                                    AllocateConstFrameNode);\n};\n/*!\n * \\brief A frame that represents attribute node.\n *\n * \\sa AttrFrame\n */\nclass AttrFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The node to annotate the attribute. */\n  ObjectRef node;\n  /*! \\brief Attribute type key. */\n  String attr_key;\n  /*! \\brief The value of the attribute. */\n  PrimExpr value;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"node\", &node);\n    v->Visit(\"attr_key\", &attr_key);\n    v->Visit(\"value\", &value);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.AttrFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttrFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to AttrFrameNode.\n *\n * \\sa AttrFrameNode\n */\nclass AttrFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(AttrFrame, TIRFrame, AttrFrameNode);\n};\n\n/*!\n * \\brief A frame that represents while loop.\n *\n * \\sa WhileFrame\n */\nclass WhileFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The termination condition of while. */\n  PrimExpr condition;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"condition\", &condition);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.WhileFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WhileFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to WhileFrameNode.\n *\n * \\sa WhileFrameNode\n */\nclass WhileFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(WhileFrame, TIRFrame, WhileFrameNode);\n};\n\n/*!\n * \\brief A frame that represents if statement.\n *\n * \\sa IfFrame\n */\nclass IfFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The condition of the if statement. */\n  PrimExpr condition;\n  /*! \\brief The statements in the true branch. */\n  Optional<Array<tvm::tir::Stmt>> then_stmts;\n  /*! \\brief The stetements in the false branch. */\n  Optional<Array<tvm::tir::Stmt>> else_stmts;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"then_stmts\", &then_stmts);\n    v->Visit(\"else_stmts\", &else_stmts);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.IfFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IfFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to IfFrameNode.\n *\n * \\sa IfFrameNode\n */\nclass IfFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(IfFrame, TIRFrame, IfFrameNode);\n};\n\n/*!\n * \\brief A frame that represents then.\n *\n * \\sa ThenFrame\n */\nclass ThenFrameNode : public TIRFrameNode {\n public:\n  static constexpr const char* _type_key = \"script.ir_builder.tir.ThenFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ThenFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when entering RAII scope.\n   * \\sa tvm::support::With\n   */\n  void EnterWithScope() final;\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to ThenFrameNode.\n *\n * \\sa ThenFrameNode\n */\nclass ThenFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(ThenFrame, TIRFrame, ThenFrameNode);\n};\n\n/*!\n * \\brief A frame that represents else.\n *\n * \\sa ElseFrame\n */\nclass ElseFrameNode : public TIRFrameNode {\n public:\n  static constexpr const char* _type_key = \"script.ir_builder.tir.ElseFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ElseFrameNode, TIRFrameNode);\n\n public:\n  /*!\n   * \\brief The method called when entering RAII scope.\n   * \\sa tvm::support::With\n   */\n  void EnterWithScope() final;\n  /*!\n   * \\brief The method called when exiting RAII scope.\n   * \\sa tvm::support::With\n   */\n  void ExitWithScope() final;\n};\n\n/*!\n * \\brief Managed reference to ElseFrameNode.\n *\n * \\sa ElseFrameNode\n */\nclass ElseFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(ElseFrame, TIRFrame, ElseFrameNode);\n};\n\nclass DeclBufferFrameNode : public TIRFrameNode {\n public:\n  /*! \\brief The declared buffer. */\n  tvm::tir::Buffer buffer;\n  /*! \\brief The buffer allocated or not. */\n  bool allocated;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    TIRFrameNode::VisitAttrs(v);\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"allocated\", &allocated);\n  }\n\n  static constexpr const char* _type_key = \"script.ir_builder.tir.DeclBufferFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferFrameNode, TIRFrameNode);\n\n public:\n  void ExitWithScope() final;\n};\n\nclass DeclBufferFrame : public TIRFrame {\n public:\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(DeclBufferFrame, TIRFrame, DeclBufferFrameNode);\n};\n\n}  // namespace tir\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_TIR_FRAME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/ir_builder/tir/ir.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_TIR_IR_H_\n#define TVM_SCRIPT_IR_BUILDER_TIR_IR_H_\n\n#include <tvm/script/ir_builder/base.h>\n#include <tvm/script/ir_builder/tir/frame.h>\n#include <tvm/tir/op.h>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\nnamespace tir {\n\nusing tvm::runtime::NDArray;\nusing tvm::tir::Buffer;\nusing tvm::tir::Var;\n\n/*!\n * \\brief The buffer declaration function.\n * \\param shape The type of the buffer prior to flattening.\n * \\param dtype The data type in the content of the buffer.\n * \\param buffer_name The name of the buffer.\n * \\param data The pointer to the head of the data.\n * \\param strides The strides of each dimension.\n * \\param elem_offset The offset in terms of number of dtype elements (including lanes).\n * \\param storage_scope The optional storage scope of buffer data pointer.\n * \\param align The alignment requirement of data pointer in bytes.\n * \\param offset_factor The factor of elem_offset field.\n * \\param buffer_type The buffer type.\n * \\param axis_separators The separators between input axes when generating flattened output axes.\n * \\return The declared buffer.\n */\nBuffer BufferDecl(Array<PrimExpr> shape, DataType dtype, String buffer_name, Optional<Var> data,\n                  Optional<Array<PrimExpr>> strides, Optional<PrimExpr> elem_offset,\n                  String storage_scope, int align, int offset_factor, String buffer_type,\n                  Optional<Array<IntImm>> axis_separators);\n\n/*!\n * \\brief The primitive function statement.\n * \\return The PrimFuncFrame.\n */\nPrimFuncFrame PrimFunc();\n\n/*!\n * \\brief The PrimFunc variable arguments adding function.\n * \\param name The name of the variable.\n * \\param var The variable argument.\n * \\return The variable.\n */\nVar Arg(String name, Var var);\n\n/*!\n * \\brief The PrimFunc buffer arguments adding function.\n * \\param name The name of the buffer.\n * \\param buffer The buffer argument.\n * \\return The buffer.\n */\nBuffer Arg(String name, Buffer buffer);\n\n/*!\n * \\brief The PrimFunc naming statement.\n * \\param name The name of the PrimFunc.\n */\nvoid FuncName(String name);\n\n/*!\n * \\brief The PrimFunc annotation statement.\n * \\param attrs The annotations of the PrimFunc.\n */\nvoid FuncAttrs(Map<String, ObjectRef> attrs);\n\n/*!\n * \\brief The PrimFunc return type statement.\n * \\param ret_type The return type of the PrimFunc.\n * \\return The return type.\n */\nType FuncRet(Type ret_type);\n\n/*!\n * \\brief The buffer match statement.\n * \\param param The parameter of the PrimFunc to match.\n * \\param shape The type of the buffer prior to flattening.\n * \\param dtype The data type in the content of the buffer.\n * \\param data The pointer to the head of the data.\n * \\param strides The strides of each dimension.\n * \\param elem_offset The offset in terms of number of dtype elements (including lanes).\n * \\param storage_scope The optional storage scope of buffer data pointer.\n * \\param align The alignment requirement of data pointer in bytes.\n * \\param offset_factor The factor of elem_offset field.\n * \\param buffer_type The buffer type.\n * \\param axis_separators The separators between input axes when generating flattened output axes.\n * \\return The matched buffer.\n */\nBuffer MatchBuffer(ObjectRef param, Array<PrimExpr> shape, DataType dtype = DataType::Float(32),\n                   Optional<Var> data = NullOpt, Array<PrimExpr> strides = {},\n                   PrimExpr elem_offset = PrimExpr(), String storage_scope = \"global\",\n                   int align = -1, int offset_factor = 0, String buffer_type = \"default\",\n                   Array<IntImm> axis_separators = {});\n\n/*!\n * \\brief The pre-flattened buffer statement.\n * \\param postflattened_buffer The original buffer to be flattened.\n * \\param shape The type of the buffer prior to flattening.\n * \\param dtype The data type in the content of the buffer.\n * \\param data The pointer to the head of the data.\n * \\param strides The strides of each dimension.\n * \\param elem_offset The offset in terms of number of dtype elements (including lanes).\n * \\param storage_scope The optional storage scope of buffer data pointer.\n * \\param align The alignment requirement of data pointer in bytes.\n * \\param offset_factor The factor of elem_offset field.\n * \\param buffer_type The buffer type.\n * \\param axis_separators The separators between input axes when generating flattened output axes.\n */\nvoid PreflattenedBuffer(Buffer postflattened_buffer, Array<PrimExpr> shape,\n                        DataType dtype = DataType::Float(32), Optional<Var> data = NullOpt,\n                        Array<PrimExpr> strides = {}, PrimExpr elem_offset = PrimExpr(),\n                        String storage_scope = \"global\", int align = -1, int offset_factor = 0,\n                        String buffer_type = \"default\", Array<IntImm> axis_separators = {});\n\n/*!\n * \\brief The block declaration statement.\n * \\param name The name of the block.\n * \\param no_realize The flag whether to construct BlockRealize or Block.\n * \\return The BlockFrame.\n */\nBlockFrame Block(String name, bool no_realize = false);\n\n/*!\n * \\brief The block initialization statement.\n * \\return The BlockInitFrame.\n */\nBlockInitFrame Init();\n\n/*!\n * \\brief The block predicate statement.\n * \\param predicate The predicate condition.\n */\nvoid Where(PrimExpr predicate);\n\n/*!\n * \\brief The block buffer region reading statement.\n * \\param buffer_slices The array of buffer regions to read.\n */\nvoid Reads(Array<ObjectRef> buffer_slices);\n\n/*!\n * \\brief The block buffer region writing statement.\n * \\param buffer_slices The array of buffer regions to write.\n */\nvoid Writes(Array<ObjectRef> buffer_slices);\n\n/*!\n * \\brief The block annotation statement.\n * \\param attrs The annotation of the block.\n */\nvoid BlockAttrs(Map<String, ObjectRef> attrs);\n\n/*!\n * \\brief The buffer allocation function.\n * \\param shape The type of the buffer prior to flattening.\n * \\param dtype The data type in the content of the buffer.\n * \\param data The pointer to the head of the data.\n * \\param strides The strides of each dimension.\n * \\param elem_offset The offset in terms of number of dtype elements (including lanes).\n * \\param storage_scope The optional storage scope of buffer data pointer.\n * \\param align The alignment requirement of data pointer in bytes.\n * \\param offset_factor The factor of elem_offset field.\n * \\param buffer_type The buffer type.\n * \\param axis_separators The separators between input axes when generating flattened output axes.\n * \\return The allocated buffer.\n */\nBuffer AllocBuffer(Array<PrimExpr> shape, DataType dtype = DataType::Float(32),\n                   Optional<Var> data = NullOpt, Array<PrimExpr> strides = {},\n                   PrimExpr elem_offset = PrimExpr(), String storage_scope = \"\", int align = -1,\n                   int offset_factor = 0, String buffer_type = \"default\",\n                   Array<IntImm> axis_separators = {});\nnamespace axis {\n\n/*!\n * \\brief The spatial block axis defining function.\n * \\param dom The domain of the iteration variable.\n * \\param binding The binding value of the iteration variable.\n * \\param dtype The data type of the iteration variable.\n * \\return The iteration variable.\n */\nVar Spatial(Range dom, PrimExpr binding, DataType dtype = DataType::Int(32));\n\n/*!\n * \\brief The reduced block axis defining function.\n * \\param dom The domain of the iteration variable.\n * \\param binding The binding value of the iteration variable.\n * \\param dtype The data type of the iteration variable.\n * \\return The iteration variable.\n */\nVar Reduce(Range dom, PrimExpr binding, DataType dtype = DataType::Int(32));\n\n/*!\n * \\brief The scanning block axis defining function.\n * \\param dom The domain of the iteration variable.\n * \\param binding The binding value of the iteration variable.\n * \\param dtype The data type of the iteration variable.\n * \\return The iteration variable.\n */\nVar Scan(Range dom, PrimExpr binding, DataType dtype = DataType::Int(32));\n\n/*!\n * \\brief The opaque block axis defining function.\n * \\param dom The domain of the iteration variable.\n * \\param binding The binding value of the iteration variable.\n * \\param dtype The data type of the iteration variable.\n * \\return The iteration variable.\n */\nVar Opaque(Range dom, PrimExpr binding, DataType dtype = DataType::Int(32));\n\n/*!\n * \\brief The block axis remapping function.\n * \\param kinds The types of the iteration variables.\n * \\param bindings The binding values of the iteration variables.\n * \\param dtype The data types of the iteration variables.\n * \\return The iteration variables.\n */\nArray<Var> Remap(String kinds, Array<PrimExpr> bindings, DataType dtype = DataType::Int(32));\n\n}  // namespace axis\n\n/*!\n * \\brief The serial For statement.\n * \\param start The minimum value of iteration.\n * \\param stop The maximum value of iteration.\n * \\param annotations The optional annotations of the For statement.\n * \\return The ForFrame.\n */\nForFrame Serial(PrimExpr start, PrimExpr stop,\n                Optional<Map<String, ObjectRef>> annotations = NullOpt);\n/*!\n * \\brief The parallel For statement.\n * \\param start The minimum value of iteration.\n * \\param stop The maximum value of iteration.\n * \\param annotations The optional annotations of the For statement.\n * \\return The ForFrame.\n */\nForFrame Parallel(PrimExpr start, PrimExpr stop,\n                  Optional<Map<String, ObjectRef>> annotations = NullOpt);\n/*!\n * \\brief The vectorized For statement.\n * \\param start The minimum value of iteration.\n * \\param stop The maximum value of iteration.\n * \\param annotations The optional annotations of the For statement.\n * \\return The ForFrame.\n */\nForFrame Vectorized(PrimExpr start, PrimExpr stop,\n                    Optional<Map<String, ObjectRef>> annotations = NullOpt);\n/*!\n * \\brief The unrolled For statement.\n * \\param start The minimum value of iteration.\n * \\param stop The maximum value of iteration.\n * \\param annotations The optional annotations of the For statement.\n * \\return The ForFrame.\n */\nForFrame Unroll(PrimExpr start, PrimExpr stop,\n                Optional<Map<String, ObjectRef>> annotations = NullOpt);\n/*!\n * \\brief The thread-binding For statement.\n * \\param start The minimum value of iteration.\n * \\param stop The maximum value of iteration.\n * \\param thread The thread for loop variable to bind.\n * \\param annotations The optional annotations of the For statement.\n * \\return The ForFrame.\n */\nForFrame ThreadBinding(PrimExpr start, PrimExpr stop, String thread,\n                       Optional<Map<String, ObjectRef>> annotations = NullOpt);\n/*!\n * \\brief The grid For statement.\n * \\param extents The extents of the iteration.\n * \\return The ForFrame.\n */\nForFrame Grid(Array<PrimExpr> extents);\n\n/*!\n * \\brief The assertion statement.\n * \\param condition The assertion condition.\n * \\param message The error message when the assertion fails.\n * \\return The AssertFrame.\n */\nAssertFrame Assert(PrimExpr condition, String message);\n\n/*!\n * \\brief The let binding.\n * \\param var The variable to bind.\n * \\param value The value to be bound.\n * \\return The created LetFrame.\n */\nLetFrame Let(Var var, PrimExpr value);\n\n/*!\n * \\brief The realization.\n * \\param buffer_slice The region of buffer access.\n * \\param storage_scope The storage scope associated with this realization.\n * \\param condition The condition expression.\n * \\return The result RealizeFrame.\n */\nRealizeFrame Realize(tvm::tir::BufferRegion buffer_slice, String storage_scope, PrimExpr condition);\n\n/*!\n * \\brief The allocate node.\n * \\param extents The extents of the allocate.\n * \\param dtype The data type of the buffer.\n * \\param storage_scope The storage scope.\n * \\param condition The condition.\n * \\param annotations Additional annotation hints.\n * \\return The created AllocateFrame.\n */\nAllocateFrame Allocate(Array<PrimExpr> extents, DataType dtype, String storage_scope = \"\",\n                       Optional<PrimExpr> condition = NullOpt,\n                       Optional<Map<String, ObjectRef>> annotations = NullOpt);\n\n/*!\n * \\brief The allocate constant node.\n * \\param data The data associated with the constant.\n * \\param dtype The data type of the buffer.\n * \\param extents The extents of the allocate.\n * \\param annotations Additional annotation hints.\n * \\return The created AllocateConstFrame.\n */\nAllocateConstFrame AllocateConst(NDArray data, DataType dtype, Array<PrimExpr> extents,\n                                 Optional<Map<String, ObjectRef>> annotations = NullOpt);\n\n/*!\n * \\brief Create an attribute.\n * \\param node The node to annotate the attribute.\n * \\param attr_key Attribute type key.\n * \\param value The value of the attribute.\n * \\return The result AttrFrame.\n */\nAttrFrame Attr(ObjectRef node, String attr_key, PrimExpr value);\n\n/*!\n * \\brief Create a while loop.\n * \\param condition The termination condition of the loop.\n * \\return The result WhileFrame.\n */\nWhileFrame While(PrimExpr condition);\n\n/*!\n * \\brief Create an if statement.\n * \\param condition The condition of if statement.\n * \\return The result IfFrame.\n */\nIfFrame If(PrimExpr condition);\n\n/*!\n * \\brief Create a then.\n * \\return The result ThenFrame.\n */\nThenFrame Then();\n\n/*!\n * \\brief Create an else.\n * \\return The result ElseFrame.\n */\nElseFrame Else();\n\n/*!\n * \\brief The buffer declaration frame.\n * \\param shape The type of the buffer prior to flattening.\n * \\param dtype The data type in the content of the buffer.\n * \\param buffer_name The name of the buffer.\n * \\param data The pointer to the head of the data.\n * \\param strides The strides of each dimension.\n * \\param elem_offset The offset in terms of number of dtype elements (including lanes).\n * \\param storage_scope The optional storage scope of buffer data pointer.\n * \\param align The alignment requirement of data pointer in bytes.\n * \\param offset_factor The factor of elem_offset field.\n * \\param buffer_type The buffer type.\n * \\param axis_separators The separators between input axes when generating flattened output axes.\n * \\return The declared buffer.\n */\nDeclBufferFrame DeclBuffer(Array<PrimExpr> shape, DataType dtype, String buffer_name,\n                           Optional<Var> data, Optional<Array<PrimExpr>> strides,\n                           Optional<PrimExpr> elem_offset, String storage_scope, int align,\n                           int offset_factor, String buffer_type,\n                           Optional<Array<IntImm>> axis_separators);\n\n/*!\n * \\brief Launch a thread.\n * \\param var The iteration variable.\n * \\param extent The extent of environment thread.\n * \\return The result LaunchThreadFrame.\n */\nLaunchThreadFrame LaunchThread(Var var, PrimExpr extent);\n\n/*!\n * \\brief Bind a var to thread env.\n * \\param thread_tag The thread type tag.\n * \\return The result variable which gets bound to the thread env.\n */\nVar EnvThread(String thread_tag);\n\n/*!\n * \\brief Store data in a buffer.\n * \\param buffer The buffer.\n * \\param value The value to be stored.\n * \\param indices The indices location to be stored.\n */\nvoid BufferStore(Buffer buffer, PrimExpr value, Array<PrimExpr> indices);\n\n/*!\n * \\brief The prefetch hint for a buffer\n * \\param buffer The buffer to be prefetched.\n * \\param bounds The bounds to be prefetched.\n */\nvoid Prefetch(Buffer buffer, Array<Range> bounds);\n\n/*!\n * \\brief Evaluate the input expression.\n * \\param value The input expression to evaluate.\n */\nvoid Evaluate(PrimExpr value);\n\n/*!\n * \\brief The pointer declaration function.\n * \\param dtype The data type of the pointer.\n * \\param storage_scope The storage scope of the pointer.\n * \\return The pointer.\n */\nPrimExpr Ptr(runtime::DataType dtype, String storage_scope = \"global\");\n\n#define TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName, DType)                             \\\n  inline PrimExpr FuncName(Optional<PrimExpr> expr = NullOpt) {                        \\\n    DataType dtype = DType;                                                            \\\n    return expr.defined() ? tvm::cast(dtype, expr.value()) : tvm::tir::Var(\"\", dtype); \\\n  }\n\n#define TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES(DType, FDType) \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(DType##8, FDType(8));      \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(DType##16, FDType(16));    \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(DType##32, FDType(32));    \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(DType##64, FDType(64));\n\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES(Float, DataType::Float);\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES(UInt, DataType::UInt);\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES(Int, DataType::Int);\n\n#define TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_LANES(FuncName, FDType, Size) \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName##x4, FDType(Size, 4));     \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName##x8, FDType(Size, 8));     \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName##x16, FDType(Size, 16));   \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName##x32, FDType(Size, 32));   \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(FuncName##x64, FDType(Size, 64));\n\n#define TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES_LANES(DType, FDType) \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_LANES(DType##8, FDType, 8);      \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_LANES(DType##16, FDType, 16);    \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_LANES(DType##32, FDType, 32);    \\\n  TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_LANES(DType##64, FDType, 64);\n\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES_LANES(Float, DataType::Float);\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES_LANES(UInt, DataType::UInt);\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST_SIZES_LANES(Int, DataType::Int);\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(Boolean, DataType::Bool());\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(Handle, DataType::Handle());\nTVM_TIR_IR_BUILDER_DEF_DTYPE_CAST(Void, DataType::Void());\n\n#undef TVM_TIR_IR_BUILDER_DEF_DTYPE_CAST\n\n}  // namespace tir\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_TIR_IR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_H_\n#define TVM_SCRIPT_PRINTER_H_\n\n#include <tvm/node/node.h>\n#include <tvm/node/object_path.h>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*!\n * \\brief Print IR graph as TVMScript code\n *\n * \\param root_node The root node to print.\n * \\param ir_name The dispatch token of the target IR, e.g., \"tir\", \"relax\".\n * \\param ir_prefix The symbol name for TVMScript IR namespaces. For example, {\"tir\": \"T\"}.\n * \\param indent_spaces Number of spaces used for indentation\n * \\param print_line_numbers Whether to print line numbers\n * \\param num_context_lines Number of context lines to print around the underlined text\n * \\param path_to_underline Object path to be underlined\n *\n * \\return the TVMScript code as string.\n */\nString Script(                                        //\n    const ObjectRef& root_node,                       //\n    String ir_name,                                   //\n    Map<String, String> ir_prefix,                    //\n    int indent_spaces = 4,                            //\n    bool print_line_numbers = false,                  //\n    int num_context_lines = -1,                       //\n    Optional<ObjectPath> path_to_underline = NullOpt  //\n);\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/doc.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_DOC_H_\n#define TVM_SCRIPT_PRINTER_DOC_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/script/printer/traced_object.h>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*!\n * \\brief The base class of all Doc.\n *\n * Doc is an intermediate representation between IR from TVM\n * and the TVMScript code.\n * During printing, IR graph is first translated into Doc tree,\n * then the Doc tree is translated to the target language in\n * text format.\n *\n * \\sa Doc\n */\nclass DocNode : public Object {\n public:\n  /*!\n   * \\brief The list of object paths of the source IR node.\n   *\n   * This is used to trace back to the IR node position where\n   * this Doc is generated, in order to position the diagnostic\n   * message.\n   */\n  mutable Array<ObjectPath> source_paths;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"source_paths\", &source_paths); }\n\n  static constexpr const char* _type_key = \"script.printer.Doc\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DocNode, Object);\n\n public:\n  virtual ~DocNode() = default;\n};\n\n/*!\n * \\brief Reference type of DocNode.\n *\n * \\sa DocNode\n */\nclass Doc : public ObjectRef {\n protected:\n  Doc() = default;\n\n public:\n  virtual ~Doc() = default;\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Doc, ObjectRef, DocNode);\n};\n\nclass ExprDoc;\n\n/*!\n * \\brief The base class of expression doc.\n *\n * \\sa ExprDoc\n */\nclass ExprDocNode : public DocNode {\n public:\n  /*!\n   * \\brief Create a doc representing attribute access on the current ExprDoc\n   * \\param attr The attribute to access.\n   */\n  ExprDoc Attr(String attr) const;\n\n  /*!\n   * \\brief Create a doc representing attribute access on the current ExprDoc\n   * \\param attr The attribute to access.\n   *\n   * The ObjectPath of attr will be pushed to the source_path of the returned\n   * doc.\n   */\n  ExprDoc Attr(TracedObject<String> attr) const;\n\n  /*!\n   * \\brief Create a doc representing index access on the current ExprDoc\n   * \\param indices The indices to access.\n   */\n  ExprDoc operator[](Array<Doc> indices) const;\n\n  /*!\n   * \\brief Create a doc representing calling the current ExprDoc\n   * \\param args The positional arguments of the function call.\n   */\n  ExprDoc Call(Array<ExprDoc, void> args) const;\n\n  /*!\n   * \\brief Create a doc representing attribute access on the current ExprDoc\n   * \\param args The positional arguments of the function call.\n   * \\param kwargs_keys Keys of keywords arguments of the function call.\n   * \\param kwargs_values Values of keywords arguments of the function call.\n   */\n  ExprDoc Call(Array<ExprDoc, void> args,  //\n               Array<String> kwargs_keys,  //\n               Array<ExprDoc, void> kwargs_values) const;\n\n  void VisitAttrs(AttrVisitor* v) { DocNode::VisitAttrs(v); }\n\n  static constexpr const char* _type_key = \"script.printer.ExprDoc\";\n  TVM_DECLARE_BASE_OBJECT_INFO(ExprDocNode, DocNode);\n};\n\n/*!\n * \\brief Reference type of ExprDocNode.\n *\n * \\sa ExprDocNode\n */\nclass ExprDoc : public Doc {\n protected:\n  ExprDoc() = default;\n\n public:\n  /*!\n   * \\brief Create a doc representing index access on the current ExprDoc\n   * \\param indices The indices to access.\n   */\n  ExprDoc operator[](Array<Doc> indices) const;\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ExprDoc, Doc, ExprDocNode);\n};\n\n/*!\n * \\brief The base class of statement doc.\n *\n * \\sa StmtDoc\n */\nclass StmtDocNode : public DocNode {\n public:\n  /*!\n   * \\brief The comment of this doc.\n   *\n   * The actual position of the comment depends on the type of Doc\n   * and also the DocPrinter implementation. It could be on the same\n   * line as the statement, or the line above, or inside the statement\n   * if it spans over multiple lines.\n   * */\n  mutable Optional<String> comment{NullOpt};\n\n  void VisitAttrs(AttrVisitor* v) {\n    DocNode::VisitAttrs(v);\n    v->Visit(\"comment\", &comment);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.StmtDoc\";\n  TVM_DECLARE_BASE_OBJECT_INFO(StmtDocNode, DocNode);\n};\n\n/*!\n * \\brief Reference type of StmtDocNode.\n *\n * \\sa StmtDocNode\n */\nclass StmtDoc : public Doc {\n protected:\n  StmtDoc() = default;\n\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(StmtDoc, Doc, StmtDocNode);\n};\n\n/*!\n * \\brief The container doc that holds a list of StmtDoc.\n * \\note `StmtBlockDoc` is never used in the IR, but a temporary container that allows holding a\n * list of StmtDoc.\n * \\sa StmtBlockDoc\n */\nclass StmtBlockDocNode : public DocNode {\n public:\n  /*! \\brief The list of statements. */\n  Array<StmtDoc> stmts;\n\n  void VisitAttrs(AttrVisitor* v) {\n    DocNode::VisitAttrs(v);\n    v->Visit(\"stmts\", &stmts);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.StmtBlockDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StmtBlockDocNode, DocNode);\n};\n\n/*!\n * \\brief Reference type of StmtBlockDocNode.\n * \\sa StmtBlockDocNode\n */\nclass StmtBlockDoc : public Doc {\n public:\n  /*!\n   * \\brief Constructor of StmtBlockDoc.\n   * \\param stmts The list of statements.\n   */\n  explicit StmtBlockDoc(Array<StmtDoc> stmts);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(StmtBlockDoc, Doc, StmtBlockDocNode);\n};\n\n/*!\n * \\brief Doc that represents literal value.\n *\n * \\sa LiteralDoc\n */\nclass LiteralDocNode : public ExprDocNode {\n public:\n  /*!\n   * \\brief the internal representation of the literal value.\n   *\n   * Possible actual types:\n   * - IntImm (integer or boolean)\n   * - FloatImm\n   * - String\n   * - null\n   */\n  ObjectRef value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"value\", &value);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.LiteralDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LiteralDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of LiteralDocNode.\n *\n * \\sa LiteralDocNode\n */\nclass LiteralDoc : public ExprDoc {\n protected:\n  explicit LiteralDoc(ObjectRef value);\n  LiteralDoc(ObjectRef value, ObjectPath object_path);\n\n public:\n  /*!\n   * \\brief Create a LiteralDoc to represent None/null/empty value.\n   */\n  static LiteralDoc None() { return LiteralDoc(ObjectRef(nullptr)); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent None/null/empty value.\n   * \\param object_path The source path of the returned Doc.\n   */\n  static LiteralDoc None(ObjectPath object_path) {\n    return LiteralDoc(ObjectRef(nullptr), object_path);\n  }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent integer.\n   * \\param v The integer value.\n   */\n  static LiteralDoc Int(int v) { return LiteralDoc(IntImm(DataType::Int(64), v)); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent integer.\n   * \\param v The integer value.\n   *\n   * The ObjectPath of v will be pushed to the source_path of the returned doc.\n   */\n  static LiteralDoc Int(const TracedObject<IntImm>& v) { return LiteralDoc(v.Get(), v.GetPath()); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent integer.\n   * \\param v The integer value.\n   *\n   * The ObjectPath of v will be pushed to the source_path of the returned doc.\n   */\n  static LiteralDoc Int(const TracedBasicValue<int>& v) {\n    return LiteralDoc(IntImm(DataType::Int(64), v.Get()), v.GetPath());\n  }\n  /*!\n   * \\brief Create a LiteralDoc to represent boolean.\n   * \\param v The boolean value.\n   */\n  static LiteralDoc Boolean(bool v) { return LiteralDoc(IntImm(DataType::Bool(), v)); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent boolean.\n   * \\param v The boolean value.\n   *\n   * The ObjectPath of v will be pushed to the source_path of the returned doc.\n   */\n  static LiteralDoc Boolean(const TracedBasicValue<bool>& v) {\n    return LiteralDoc(IntImm(DataType::Bool(), v.Get()), v.GetPath());\n  }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent float.\n   * \\param v The float value.\n   */\n  static LiteralDoc Float(double v) { return LiteralDoc(FloatImm(DataType::Float(64), v)); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent float.\n   * \\param v The float value.\n   *\n   * The ObjectPath of v will be pushed to the source_path of the returned doc.\n   */\n  static LiteralDoc Float(const TracedObject<FloatImm>& v) {\n    return LiteralDoc(v.Get(), v.GetPath());\n  }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent string.\n   * \\param v The string value.\n   */\n  static LiteralDoc Str(const String& v) { return LiteralDoc(v); }\n\n  /*!\n   * \\brief Create a LiteralDoc to represent string.\n   * \\param v The string value.\n   *\n   * The ObjectPath of v will be pushed to the source_path of the returned doc.\n   */\n  static LiteralDoc Str(const TracedObject<String>& v) { return LiteralDoc(v.Get(), v.GetPath()); }\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(LiteralDoc, ExprDoc, LiteralDocNode);\n};\n\n/*!\n * \\brief Doc that represents identifier.\n *\n * \\sa IdDoc\n */\nclass IdDocNode : public ExprDocNode {\n public:\n  /*! \\brief The name of the identifier */\n  String name;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"name\", &name);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.IdDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IdDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of IdDocNode.\n *\n * \\sa IdDocNode\n */\nclass IdDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of IdDoc.\n   * \\param name The name of identifier.\n   */\n  explicit IdDoc(String name);\n  explicit IdDoc(std::nullptr_t) : ExprDoc(nullptr) {}\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(IdDoc, ExprDoc, IdDocNode);\n};\n\n/*!\n * \\brief Doc that represents attribute access on another expression.\n *\n * \\sa AttrAccessDoc\n */\nclass AttrAccessDocNode : public ExprDocNode {\n public:\n  /*! \\brief The target expression to be accessed */\n  ExprDoc value{nullptr};\n  /*! \\brief The attribute to be accessed */\n  String name;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"value\", &value);\n    v->Visit(\"name\", &name);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.AttrAccessDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttrAccessDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of AttrAccessDocNode.\n *\n * \\sa AttrAccessDocNode\n */\nclass AttrAccessDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of AttrAccessDoc\n   * \\param value The target expression of attribute access.\n   * \\param name The name of attribute to access.\n   */\n  explicit AttrAccessDoc(ExprDoc value, String name);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(AttrAccessDoc, ExprDoc, AttrAccessDocNode);\n};\n\n/*!\n * \\brief Doc that represents index access on another expression.\n *\n * \\sa IndexDoc\n */\nclass IndexDocNode : public ExprDocNode {\n public:\n  /*! \\brief The container value to be accessed */\n  ExprDoc value{nullptr};\n  /*!\n   * \\brief The indices to access\n   *\n   * Possible actual types:\n   * - ExprDoc (single point access like a[1, 2])\n   * - SliceDoc (slice access like a[1:5, 2])\n   */\n  Array<Doc> indices;  // Each element is union of: Slice / ExprDoc\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"value\", &value);\n    v->Visit(\"indices\", &indices);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.IndexDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IndexDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of IndexDocNode.\n *\n * \\sa IndexDocNode\n */\nclass IndexDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of IndexDoc\n   * \\param value The target expression of index access.\n   * \\param indices The indices to access.\n   */\n  explicit IndexDoc(ExprDoc value, Array<Doc> indices);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(IndexDoc, ExprDoc, IndexDocNode);\n};\n\n/*!\n * \\brief Doc that represents function call.\n *\n * \\sa CallDoc\n */\nclass CallDocNode : public ExprDocNode {\n public:\n  /*! \\brief The callee of this function call */\n  ExprDoc callee{nullptr};\n  /*! \\brief The positional arguments */\n  Array<ExprDoc> args;\n  /*! \\brief The keys of keyword arguments */\n  Array<String> kwargs_keys;\n  /*!\n   * \\brief The values of keyword arguments.\n   *\n   * The i-th element is the value of the i-th key in `kwargs_keys`.\n   * It must have the same length as `kwargs_keys`.\n   */\n  Array<ExprDoc> kwargs_values;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"callee\", &callee);\n    v->Visit(\"args\", &args);\n    v->Visit(\"kwargs_keys\", &kwargs_keys);\n    v->Visit(\"kwargs_values\", &kwargs_values);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.CallDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CallDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of CallDocNode.\n *\n * \\sa CallDocNode\n */\nclass CallDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of CallDoc\n   * \\param callee The callee of this function call.\n   * \\param args The positional arguments.\n   * \\param kwargs_keys Keys of keyword arguments.\n   * \\param kwargs_values Values of keyword arguments, must have the same length as `kwargs_keys.\n   */\n  CallDoc(ExprDoc callee, Array<ExprDoc> args, Array<String> kwargs_keys,\n          Array<ExprDoc> kwargs_values);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(CallDoc, ExprDoc, CallDocNode);\n};\n\n/*!\n * \\brief Doc that represents operation.\n *\n * It can be unary, binary and other special operators (for example,\n * the if-then-else expression).\n *\n * \\sa OperationDoc\n */\nclass OperationDocNode : public ExprDocNode {\n public:\n  enum class Kind : int32_t {\n    // Unary operators\n    kUnaryStart = 0,\n    kUSub = 1,    // -x\n    kInvert = 2,  // ~x\n    kNot = 3,     // not x\n    kUnaryEnd = 4,\n\n    // Binary operators\n    kBinaryStart = 5,\n    kAdd = 6,        // +\n    kSub = 7,        // -\n    kMult = 8,       // *\n    kDiv = 9,        // /\n    kFloorDiv = 10,  // // in Python\n    kMod = 11,       // % in Python\n    kPow = 12,       // ** in Python\n    kLShift = 13,    // <<\n    kRShift = 14,    // >>\n    kBitAnd = 15,    // &\n    kBitOr = 16,     // |\n    kBitXor = 17,    // ^\n    kLt = 18,        // <\n    kLtE = 19,       // <=\n    kEq = 20,        // ==\n    kNotEq = 21,     // !=\n    kGt = 22,        // >\n    kGtE = 23,       // >=\n    kAnd = 24,       // and\n    kOr = 25,        // or\n    kBinaryEnd = 26,\n\n    // Special\n    kSpecialStart = 27,\n    kIfThenElse = 28,  // <operands[1]> if <operands[0]> else <operands[2]>\n    kSpecialEnd = 29\n  };\n\n  /*! \\brief The kind of operation (operator) */\n  Kind kind;\n  /*! \\brief Operands of this expression */\n  Array<ExprDoc> operands;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"operands\", &operands);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.OperationDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OperationDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of OperationDocNode.\n *\n * \\sa OperationDocNode\n */\nclass OperationDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of OperationDoc\n   * \\param kind The kind of operation.\n   * \\param operands Operands of this expression.\n   */\n  explicit OperationDoc(OperationDocNode::Kind kind, Array<ExprDoc> operands);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(OperationDoc, ExprDoc, OperationDocNode);\n};\n\n/*!\n * \\brief Doc that represents anonymous function.\n *\n * LambdaDoc can only have positional arguments without type annotation,\n * and a single expression as body.\n *\n * \\sa LambdaDoc\n */\nclass LambdaDocNode : public ExprDocNode {\n public:\n  /*! \\brief The arguments of this anonymous function */\n  Array<IdDoc> args;\n  /*! \\brief The body of this anonymous function */\n  ExprDoc body{nullptr};\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"args\", &args);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.LambdaDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LambdaDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of LambdaDocNode.\n *\n * \\sa LambdaDocNode\n */\nclass LambdaDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Constructor of LambdaDoc\n   * \\param args Arguments of this function.\n   * \\param body Body expression of this function.\n   */\n  explicit LambdaDoc(Array<IdDoc> args, ExprDoc body);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(LambdaDoc, ExprDoc, LambdaDocNode);\n};\n\n/*!\n * \\brief Doc that represents tuple literal.\n *\n * \\sa TupleDoc\n */\nclass TupleDocNode : public ExprDocNode {\n public:\n  /*! \\brief Elements of tuple */\n  Array<ExprDoc> elements;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"elements\", &elements);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.TupleDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of TupleDocNode.\n *\n * \\sa TupleDocNode\n */\nclass TupleDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Create an empty TupleDoc\n   */\n  TupleDoc() : TupleDoc(runtime::make_object<TupleDocNode>()) {}\n  /*!\n   * \\brief Constructor of TupleDoc\n   * \\param elements Elements of tuple.\n   */\n  explicit TupleDoc(Array<ExprDoc> elements);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TupleDoc, ExprDoc, TupleDocNode);\n};\n\n/*!\n * \\brief Doc that represents list literal.\n *\n * \\sa AttrAccessDoc\n */\nclass ListDocNode : public ExprDocNode {\n public:\n  /*! \\brief Elements of list */\n  Array<ExprDoc> elements;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"elements\", &elements);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ListDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ListDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of ListDocNode.\n *\n * \\sa ListDocNode\n */\nclass ListDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Create an empty ListDoc\n   */\n  ListDoc() : ListDoc(runtime::make_object<ListDocNode>()) {}\n  /*!\n   * \\brief Constructor of ListDoc\n   * \\param elements Elements of list.\n   */\n  explicit ListDoc(Array<ExprDoc> elements);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ListDoc, ExprDoc, ListDocNode);\n};\n\n/*!\n * \\brief Doc that represents dictionary literal.\n *\n * \\sa AttrAccessDoc\n */\nclass DictDocNode : public ExprDocNode {\n public:\n  /*! \\brief keys of dictionary */\n  Array<ExprDoc> keys;\n  /*!\n   * \\brief Values of dictionary\n   *\n   * The i-th element is the value of the i-th element of `keys`.\n   * It must have the same length as `keys`.\n   */\n  Array<ExprDoc> values;\n\n  void VisitAttrs(AttrVisitor* v) {\n    ExprDocNode::VisitAttrs(v);\n    v->Visit(\"keys\", &keys);\n    v->Visit(\"values\", &values);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.DictDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DictDocNode, ExprDocNode);\n};\n\n/*!\n * \\brief Reference type of DictDocNode.\n *\n * \\sa DictDocNode\n */\nclass DictDoc : public ExprDoc {\n public:\n  /*!\n   * \\brief Create an empty dictionary\n   */\n  DictDoc() : DictDoc(runtime::make_object<DictDocNode>()) {}\n  /*!\n   * \\brief Constructor of DictDoc\n   * \\param keys Keys of dictionary.\n   * \\param values Values of dictionary, must have same length as `keys`.\n   */\n  explicit DictDoc(Array<ExprDoc> keys, Array<ExprDoc> values);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(DictDoc, ExprDoc, DictDocNode);\n};\n\n/*!\n * \\brief Doc that represents slice in Index expression.\n *\n * This doc can only appear in IndexDoc::indices.\n *\n * \\sa AttrAccessDoc\n */\nclass SliceDocNode : public DocNode {\n public:\n  /*! \\brief The start of slice */\n  Optional<ExprDoc> start;\n  /*! \\brief The exclusive end of slice */\n  Optional<ExprDoc> stop;\n  /*! \\brief The step of slice */\n  Optional<ExprDoc> step;\n\n  void VisitAttrs(AttrVisitor* v) {\n    DocNode::VisitAttrs(v);\n    v->Visit(\"start\", &start);\n    v->Visit(\"stop\", &stop);\n    v->Visit(\"step\", &step);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.SliceDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SliceDocNode, DocNode);\n};\n\n/*!\n * \\brief Reference type of SliceDocNode.\n *\n * \\sa SliceDocNode\n */\nclass SliceDoc : public Doc {\n public:\n  /*!\n   * \\brief Constructor of SliceDoc\n   * \\param start The start of slice.\n   * \\param stop The exclusive end of slice.\n   * \\param step The step of slice.\n   */\n  explicit SliceDoc(Optional<ExprDoc> start, Optional<ExprDoc> stop, Optional<ExprDoc> step);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(SliceDoc, Doc, SliceDocNode);\n};\n\n/*!\n * \\brief Doc that represents assign statement.\n *\n * \\sa AssignDoc\n */\nclass AssignDocNode : public StmtDocNode {\n public:\n  /*! \\brief The left hand side of the assignment */\n  ExprDoc lhs{nullptr};\n  /*!\n   * \\brief The right hand side of the assignment.\n   *\n   * If null, this doc represents declaration, e.g. `A: T.Buffer[(1,2)]`\n   * */\n  Optional<ExprDoc> rhs;\n  /*! \\brief The type annotation of this assignment. */\n  Optional<ExprDoc> annotation;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"lhs\", &lhs);\n    v->Visit(\"rhs\", &rhs);\n    v->Visit(\"annotation\", &annotation);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.AssignDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AssignDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of AssignDocNode.\n *\n * \\sa AssignDoc\n */\nclass AssignDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of AssignDoc.\n   * \\param lhs The left hand side of the assignment.\n   * \\param rhs The right hand side of the assignment.\n   * \\param annotation The type annotation of this assignment.\n   */\n  explicit AssignDoc(ExprDoc lhs, Optional<ExprDoc> rhs, Optional<ExprDoc> annotation);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(AssignDoc, StmtDoc, AssignDocNode);\n};\n\n/*!\n * \\brief Doc that represent if-then-else statement.\n *\n * \\sa IfDoc\n */\nclass IfDocNode : public StmtDocNode {\n public:\n  /*! \\brief The predicate of the if-then-else statement. */\n  ExprDoc predicate{nullptr};\n  /*! \\brief The then branch of the if-then-else statement. */\n  Array<StmtDoc> then_branch;\n  /*! \\brief The else branch of the if-then-else statement. */\n  Array<StmtDoc> else_branch;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"then_branch\", &then_branch);\n    v->Visit(\"else_branch\", &else_branch);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.IfDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IfDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of IfDocNode.\n *\n * \\sa IfDocNode\n */\nclass IfDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of IfDoc.\n   * \\param predicate The predicate of the if-then-else statement.\n   * \\param then_branch The then branch of the if-then-else statement.\n   * \\param else_branch The else branch of the if-then-else statement.\n   */\n  explicit IfDoc(ExprDoc predicate, Array<StmtDoc> then_branch, Array<StmtDoc> else_branch);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(IfDoc, StmtDoc, IfDocNode);\n};\n\n/*!\n * \\brief Doc that represents while statement.\n *\n * \\sa WhileDoc\n */\nclass WhileDocNode : public StmtDocNode {\n public:\n  /*! \\brief The predicate of the while statement. */\n  ExprDoc predicate{nullptr};\n  /*! \\brief The body of the while statement. */\n  Array<StmtDoc> body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.WhileDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WhileDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of WhileDocNode.\n *\n * \\sa WhileDocNode\n */\nclass WhileDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of WhileDoc.\n   * \\param predicate The predicate of the while statement.\n   * \\param body The body of the while statement.\n   */\n  explicit WhileDoc(ExprDoc predicate, Array<StmtDoc> body);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(WhileDoc, StmtDoc, WhileDocNode);\n};\n\n/*!\n * \\brief Doc that represents for statement.\n *\n * Example:\n * for 'lhs' in 'rhs':\n *   'body...'\n *\n * \\sa ForDoc\n */\nclass ForDocNode : public StmtDocNode {\n public:\n  /*! \\brief The left hand side of the assignment of iterating variable. */\n  ExprDoc lhs{nullptr};\n  /*! \\brief The right hand side of the assignment of iterating variable. */\n  ExprDoc rhs{nullptr};\n  /*! \\brief The body of the for statement. */\n  Array<StmtDoc> body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"lhs\", &lhs);\n    v->Visit(\"rhs\", &rhs);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ForDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ForDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of ForDocNode.\n *\n * \\sa ForDocNode\n */\nclass ForDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of ForDoc.\n   * \\param lhs The left hand side of the assignment of iterating variable.\n   * \\param rhs The right hand side of the assignment of iterating variable.\n   * \\param body The body of the for statement.\n   */\n  explicit ForDoc(ExprDoc lhs, ExprDoc rhs, Array<StmtDoc> body);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ForDoc, StmtDoc, ForDocNode);\n};\n\n/*!\n * \\brief Doc that represents special scopes.\n *\n * Specifically, this means the with statement in Python:\n *\n * with 'rhs' as 'lhs':\n *   'body...'\n *\n * \\sa ScopeDoc\n */\nclass ScopeDocNode : public StmtDocNode {\n public:\n  /*! \\brief The name of the scoped variable. */\n  Optional<ExprDoc> lhs{NullOpt};\n  /*! \\brief The value of the scoped variable. */\n  ExprDoc rhs{nullptr};\n  /*! \\brief The body of the scope doc. */\n  Array<StmtDoc> body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"lhs\", &lhs);\n    v->Visit(\"rhs\", &rhs);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ScopeDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ScopeDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of ScopeDocNode.\n *\n * \\sa ScopeDocNode\n */\nclass ScopeDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of ScopeDoc.\n   * \\param lhs The name of the scoped variable.\n   * \\param rhs The value of the scoped variable.\n   * \\param body The body of the scope doc.\n   */\n  explicit ScopeDoc(Optional<ExprDoc> lhs, ExprDoc rhs, Array<StmtDoc> body);\n\n  /*!\n   * \\brief Constructor of ScopeDoc.\n   * \\param rhs The value of the scoped variable.\n   * \\param body The body of the scope doc.\n   */\n  explicit ScopeDoc(ExprDoc rhs, Array<StmtDoc> body);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ScopeDoc, StmtDoc, ScopeDocNode);\n};\n\n/*!\n * \\brief Doc that represents an expression as statement.\n *\n * \\sa ExprStmtDoc\n */\nclass ExprStmtDocNode : public StmtDocNode {\n public:\n  /*! \\brief The expression represented by this doc. */\n  ExprDoc expr{nullptr};\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"expr\", &expr);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ExprStmtDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExprStmtDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of ExprStmtDocNode.\n *\n * \\sa ExprStmtDocNode\n */\nclass ExprStmtDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of ExprStmtDoc.\n   * \\param expr The expression represented by this doc.\n   */\n  explicit ExprStmtDoc(ExprDoc expr);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ExprStmtDoc, StmtDoc, ExprStmtDocNode);\n};\n\n/*!\n * \\brief Doc that represents assert statement.\n *\n * \\sa AssertDoc\n */\nclass AssertDocNode : public StmtDocNode {\n public:\n  /*! \\brief The expression to test. */\n  ExprDoc test{nullptr};\n  /*! \\brief The optional error message when assertion failed. */\n  Optional<ExprDoc> msg{NullOpt};\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"test\", &test);\n    v->Visit(\"msg\", &msg);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.AssertDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AssertDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of AssertDocNode.\n *\n * \\sa AssertDocNode\n */\nclass AssertDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of AssertDoc.\n   * \\param test The expression to test.\n   * \\param msg The optional error message when assertion failed.\n   */\n  explicit AssertDoc(ExprDoc test, Optional<ExprDoc> msg = NullOpt);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(AssertDoc, StmtDoc, AssertDocNode);\n};\n\n/*!\n * \\brief Doc that represents return statement.\n *\n * \\sa ReturnDoc\n */\nclass ReturnDocNode : public StmtDocNode {\n public:\n  /*! \\brief The value to return. */\n  ExprDoc value{nullptr};\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"value\", &value);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ReturnDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ReturnDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of ReturnDocNode.\n *\n * \\sa ReturnDocNode\n */\nclass ReturnDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of ReturnDoc.\n   * \\param value The value to return.\n   */\n  explicit ReturnDoc(ExprDoc value);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ReturnDoc, StmtDoc, ReturnDocNode);\n};\n\n/*!\n * \\brief Doc that represents function definition.\n *\n * \\sa FunctionDoc\n */\nclass FunctionDocNode : public StmtDocNode {\n public:\n  /*! \\brief The name of function. */\n  IdDoc name{nullptr};\n  /*!\n   * \\brief The arguments of function.\n   *\n   * The `lhs` means argument name,\n   * `annotation` means argument type,\n   * and `rhs` means default value.\n   */\n  Array<AssignDoc> args;\n  /*! \\brief Decorators of function. */\n  Array<ExprDoc> decorators;\n  /*! \\brief The return type of function. */\n  Optional<ExprDoc> return_type{NullOpt};\n  /*! \\brief The body of function. */\n  Array<StmtDoc> body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"name\", &name);\n    v->Visit(\"args\", &args);\n    v->Visit(\"decorators\", &decorators);\n    v->Visit(\"return_type\", &return_type);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.FunctionDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FunctionDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of FunctionDocNode.\n *\n * \\sa FunctionDocNode\n */\nclass FunctionDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of FunctionDoc.\n   * \\param name The name of function..\n   * \\param args The arguments of function.\n   * \\param decorators The decorator of function.\n   * \\param return_type The return type of function.\n   * \\param body The body of function.\n   */\n  explicit FunctionDoc(IdDoc name, Array<AssignDoc> args, Array<ExprDoc> decorators,\n                       Optional<ExprDoc> return_type, Array<StmtDoc> body);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(FunctionDoc, StmtDoc, FunctionDocNode);\n};\n\n/*!\n * \\brief Doc that represents class definition.\n *\n * \\sa ClassDoc\n */\nclass ClassDocNode : public StmtDocNode {\n public:\n  /*! \\brief The name of class. */\n  IdDoc name{nullptr};\n  /*! \\brief Decorators of class. */\n  Array<ExprDoc> decorators;\n  /*! \\brief The body of class. */\n  Array<StmtDoc> body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    StmtDocNode::VisitAttrs(v);\n    v->Visit(\"name\", &name);\n    v->Visit(\"decorators\", &decorators);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.ClassDoc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ClassDocNode, StmtDocNode);\n};\n\n/*!\n * \\brief Reference type of ClassDocNode.\n *\n * \\sa ClassDocNode\n */\nclass ClassDoc : public StmtDoc {\n public:\n  /*!\n   * \\brief Constructor of ClassDoc.\n   * \\param name The name of class.\n   * \\param decorators The decorator of class.\n   * \\param body The body of class.\n   */\n  explicit ClassDoc(IdDoc name, Array<ExprDoc> decorators, Array<StmtDoc> body);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(ClassDoc, StmtDoc, ClassDocNode);\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_DOC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/doc_printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_DOC_PRINTER_H_\n#define TVM_SCRIPT_PRINTER_DOC_PRINTER_H_\n\n#include <tvm/script/printer/doc.h>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*!\n * \\brief Convert Doc into Python script.\n *\n * This function unpacks the DocPrinterOptions into function arguments\n * to be FFI friendly.\n *\n * \\param doc Doc to be converted\n * \\param indent_spaces Number of spaces used for indentation\n * \\param print_line_numbers Whether to print line numbers\n * \\param num_context_lines Number of context lines to print around the underlined text\n * \\param path_to_underline Object path to be underlined\n */\nString DocToPythonScript(Doc doc, int indent_spaces = 4, bool print_line_numbers = false,\n                         int num_context_lines = -1,\n                         Optional<ObjectPath> path_to_underline = NullOpt);\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_DOC_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/frame.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_FRAME_H_\n#define TVM_SCRIPT_PRINTER_FRAME_H_\n\n#include <tvm/node/node.h>\n#include <tvm/script/printer/doc.h>\n\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*!\n * Frame is the core data structure for semantic information\n * when printing IR graph into TVMScript code.\n */\nclass FrameNode : public Object {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n\n  virtual ~FrameNode() = default;\n\n  /*!\n   * \\brief Add a callback function to be called when this frame exits.\n   * \\param cb The callback function. It should have signature void().\n   */\n  template <typename TCallback>\n  void AddExitCallback(TCallback&& cb) {\n    callbacks_.emplace_back(std::forward<TCallback>(cb));\n  }\n\n  /*!\n   * \\brief Method that's called when Frame enters the scope.\n   */\n  virtual void EnterWithScope() {}\n\n  /*!\n   * \\brief Method that's called when Frame exits the scope.\n   */\n  virtual void ExitWithScope() {\n    for (const std::function<void()>& callback : callbacks_) {\n      callback();\n    }\n    callbacks_.clear();\n  }\n\n  static constexpr const char* _type_key = \"script.printer.Frame\";\n  TVM_DECLARE_BASE_OBJECT_INFO(FrameNode, Object);\n\n private:\n  std::vector<std::function<void()>> callbacks_;\n};\n\n/*!\n * \\brief Reference type of FrameNode\n */\nclass Frame : public ObjectRef {\n protected:\n  Frame() = default;\n\n public:\n  virtual ~Frame() = default;\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Frame, ObjectRef, FrameNode);\n};\n\n/*!\n * \\brief MetadataFrame contains information like contant parameter array.\n */\nclass MetadataFrameNode : public FrameNode {\n public:\n  Array<ObjectRef> metadata;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    FrameNode::VisitAttrs(v);\n    v->Visit(\"metadata\", &metadata);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.MetadataFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MetadataFrameNode, FrameNode);\n};\n\n/*!\n * \\brief Reference type of MetadataFrameNode\n */\nclass MetadataFrame : public Frame {\n public:\n  MetadataFrame();\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(MetadataFrame, Frame, MetadataFrameNode);\n};\n\n/*!\n * \\brief VarDefFrame contains information about the free variables that needs to be defined\n * at the beginning of the printed snippet.\n */\nclass VarDefFrameNode : public FrameNode {\n public:\n  Array<StmtDoc> stmts;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    FrameNode::VisitAttrs(v);\n    v->Visit(\"stmts\", &stmts);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.VarDefFrame\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(VarDefFrameNode, FrameNode);\n};\n\n/*!\n * \\brief Reference type of VarDefFrameNode\n */\nclass VarDefFrame : public Frame {\n public:\n  VarDefFrame();\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(VarDefFrame, Frame, VarDefFrameNode);\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_FRAME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/ir_docsifier.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_IR_DOCSIFIER_H_\n#define TVM_SCRIPT_PRINTER_IR_DOCSIFIER_H_\n\n#include <tvm/node/node.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/script/printer/doc.h>\n#include <tvm/script/printer/frame.h>\n#include <tvm/script/printer/traced_object.h>\n#include <tvm/script/printer/traced_object_functor.h>\n#include <tvm/script/printer/var_table.h>\n#include <tvm/support/with.h>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\nusing WithCtx = With<ContextManager>;\n\n/*!\n * \\brief IRDocsifier is the top-level interface in the IR->Doc process.\n *\n * It provides methods to convert IR node object to Doc, operate on Frame\n * objects and change dispatch tokens.\n *\n * Example usage:\n * \\code\n * TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable)\n *    .set_dispatch([](TracedObject<tir::Var> obj, IRDocsifier p) { return IdDoc(\"x\"); });\n *\n * TracedObject<tir::Var> var = ...;\n * IRDocsifier p;\n * p->AsDoc(var); // returns an IdDoc(\"x\")\n * \\endcode\n *\n */\nclass IRDocsifierNode : public Object {\n public:\n  /*!\n   * \\brief The var table to use during the printing process.\n   * \\sa VarTableNode\n   */\n  VarTable vars;\n  /*!\n   * \\brief The stack of frames.\n   * \\sa FrameNode\n   */\n  Array<Frame> frames;\n  /*!\n   * \\brief The stack of dispatch tokens.\n   *\n   * The dispatch token on the top decides which dispatch function to use\n   * when converting IR node object to Doc.\n   */\n  Array<String> dispatch_tokens;\n  /*!\n   * \\brief This map connects IR dipatch token to the name of identifier.\n   */\n  Map<String, String> ir_prefix;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"vars\", &vars);\n    v->Visit(\"frames\", &frames);\n    v->Visit(\"dispatch_tokens\", &dispatch_tokens);\n    v->Visit(\"ir_prefix\", &ir_prefix);\n  }\n\n  static constexpr const char* _type_key = \"script.printer.IRDocsifier\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IRDocsifierNode, Object);\n\n public:\n  /*!\n   * \\brief Transform the input object into TDoc.\n   * \\param obj The object to be transformed.\n   *\n   * \\return The Doc object.\n   */\n  template <class TDoc>\n  TDoc AsDoc(const TracedObject<ObjectRef>& obj) const {\n    auto result = Downcast<TDoc>(AsDocImpl(obj));\n    result->source_paths.push_back(obj.GetPath());\n    return result;\n  }\n\n  /*!\n   * \\brief Helper method to transform object into ExprDoc.\n   * \\param obj The object to be transformed.\n   *\n   * \\return The ExprDoc object.\n   */\n  ExprDoc AsExprDoc(const TracedObject<ObjectRef>& obj) { return AsDoc<ExprDoc>(obj); }\n\n  /*!\n   * \\brief Push a new dispatch token into the stack\n   * \\details The top dispatch token decides which dispatch table to use\n   *          when printing Object. This method returns a RAII guard which\n   *          pops the token when going out of the scope.\n   *\n   * \\param token The dispatch token to push.\n   *\n   * \\return A RAII guard to pop dispatch token when going out of scope.\n   */\n  WithCtx WithDispatchToken(const String& token) {\n    this->dispatch_tokens.push_back(token);\n    return WithCtx(nullptr, [this]() { this->dispatch_tokens.pop_back(); });\n  }\n\n  /*!\n   * \\brief Push a new frame the stack\n   * \\details Frame contains the contextual information that's needed during printing,\n   *          for example, variables in the scope. This method returns a RAII guard which\n   *          pops the frame and call the cleanup method of frame when going out of the scope.\n   *\n   * \\param frame The frame to push.\n   *\n   * \\return A RAII guard to pop frame and call the exit method of frame\n   *          when going out of scope\n   */\n  WithCtx WithFrame(const Frame& frame) {\n    frame->EnterWithScope();\n    this->frames.push_back(frame);\n    return WithCtx(nullptr, [this, pushed_frame = frame]() {\n      Frame last_frame = this->frames.back();\n      ICHECK_EQ(last_frame, pushed_frame);\n      this->frames.pop_back();\n      last_frame->ExitWithScope();\n    });\n  }\n\n  /*!\n   * \\brief Get the top frame with type FrameType\n   * \\tparam FrameType The type of frame to get.\n   */\n  template <typename FrameType>\n  Optional<FrameType> GetFrame() const {\n    for (auto it = frames.rbegin(); it != frames.rend(); ++it) {\n      if (const auto* f = (*it).as<typename FrameType::ContainerType>()) {\n        return GetRef<FrameType>(f);\n      }\n    }\n    return NullOpt;\n  }\n\n private:\n  Doc AsDocImpl(const TracedObject<ObjectRef>& obj) const;\n};\n\n/*!\n * \\brief Reference type of IRDocsifierNode.\n */\nclass IRDocsifier : public ObjectRef {\n public:\n  /*!\n   * \\brief Create a IRDocsifier.\n   * \\param ir_prefix The ir_prefix to use for this IRDocsifier.\n   */\n  explicit IRDocsifier(Map<String, String> ir_prefix);\n\n  using FType = TracedObjectFunctor<printer::Doc, IRDocsifier>;\n  /*!\n   * \\brief The registration table for IRDocsifier.\n   */\n  TVM_DLL static FType& vtable();\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(IRDocsifier, ObjectRef, IRDocsifierNode);\n};\n\n/*!\n * \\brief A wrapper object to provide injection point for printer of each IR.\n *\n * For any IR node to be transformed by IRDocsifier, it will be wrapped by RootNodeContainer\n * and be dispatched to the corresponding function first. This provides an injection point for\n * each IR's printer implemention to add specialized logic, for example, pushing a special\n * Frame to the IRDocsifier before doing any IR->Doc transformation.\n *\n * \\code\n * TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable)\n *     .set_dispatch(\"relax\", [](TracedObject<RootNodeContainer> obj, IRDocsifier p) {\n *       const ObjectRef& root_node = obj.Get()->root_node;\n *       // For example, relax printer can create a Frame specialized to Relax here\n *       RelaxGeneralFrame frame;\n *       auto ctx = p->WithFrame(frame);\n *       // More specialized logic for your IR.\n *       return p->AsDoc<Doc>(MakeTraced(root_node));\n *     });\n * \\endcode\n */\nclass RootNodeContainerNode : public Object {\n public:\n  /*! \\brief The root node to print. */\n  ObjectRef root_node;\n\n  void VisitAttrs(tvm::AttrVisitor* v) { v->Visit(\"root_node\", &root_node); }\n\n  static constexpr const char* _type_key = \"script.printer.RootNodeContainer\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RootNodeContainerNode, Object);\n};\n\nclass RootNodeContainer : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor of RootNodeContainer.\n   * \\param root_node The root node to print.\n   * */\n  explicit RootNodeContainer(ObjectRef root_node);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(RootNodeContainer, ObjectRef, RootNodeContainerNode);\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_IR_DOCSIFIER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/traced_object.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/script/printer/traced_object.h\n * Wrappers around TVM objects that also store an ObjectPath from some \"root\" object\n * to the wrapper object.\n */\n\n#ifndef TVM_SCRIPT_PRINTER_TRACED_OBJECT_H_\n#define TVM_SCRIPT_PRINTER_TRACED_OBJECT_H_\n\n#include <tvm/node/object_path.h>\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n#include <utility>\n\nnamespace tvm {\n\ntemplate <typename RefT>\nclass TracedObject;\ntemplate <typename K, typename V>\nclass TracedMap;\ntemplate <typename T>\nclass TracedArray;\ntemplate <typename T>\nclass TracedOptional;\ntemplate <typename T>\nclass TracedBasicValue;\n\nnamespace detail {\n\ntemplate <typename T, bool IsObject = std::is_base_of<ObjectRef, T>::value>\nstruct TracedObjectWrapperSelector;\n\ntemplate <typename T>\nstruct TracedObjectWrapperSelector<T, false> {\n  using Type = TracedBasicValue<T>;\n};\n\ntemplate <typename T>\nstruct TracedObjectWrapperSelector<T, true> {\n  using Type = TracedObject<T>;\n};\n\ntemplate <typename K, typename V>\nstruct TracedObjectWrapperSelector<Map<K, V>, true> {\n  using Type = TracedMap<K, V>;\n};\n\ntemplate <typename T>\nstruct TracedObjectWrapperSelector<Array<T>, true> {\n  using Type = TracedArray<T>;\n};\n\ntemplate <typename T>\nstruct TracedObjectWrapperSelector<Optional<T>, true> {\n  using Type = TracedOptional<T>;\n};\n\n}  // namespace detail\n\n/*!\n * \\brief Traced wrapper for regular (non-container) TVM objects.\n */\ntemplate <typename RefT>\nclass TracedObject {\n  using ObjectType = typename RefT::ContainerType;\n\n public:\n  using ObjectRefType = RefT;\n\n  // Don't use this direcly. For convenience, call MakeTraced() instead.\n  explicit TracedObject(const RefT& object_ref, ObjectPath path)\n      : ref_(object_ref), path_(std::move(path)) {}\n\n  // Implicit conversion from a derived reference class\n  template <typename DerivedRef>\n  TracedObject(const TracedObject<DerivedRef>& derived)\n      : ref_(derived.Get()), path_(derived.GetPath()) {}\n\n  /*!\n   * \\brief Get a traced wrapper for an attribute of the wrapped object.\n   */\n  template <typename T, typename BaseType>\n  typename detail::TracedObjectWrapperSelector<T>::Type GetAttr(T BaseType::*member_ptr) const {\n    using WrapperType = typename detail::TracedObjectWrapperSelector<T>::Type;\n    const ObjectType* node = static_cast<const ObjectType*>(ref_.get());\n    const T& attr = node->*member_ptr;\n    Optional<String> attr_key = ICHECK_NOTNULL(GetAttrKeyByAddress(node, &attr));\n    return WrapperType(attr, path_->Attr(attr_key));\n  }\n\n  /*!\n   * \\brief Access the wrapped object.\n   */\n  const RefT& Get() const { return ref_; }\n\n  /*!\n   * \\brief Check if the reference to the wrapped object can be converted to `RefU`.\n   */\n  template <typename RefU>\n  bool IsInstance() const {\n    return ref_->template IsInstance<typename RefU::ContainerType>();\n  }\n\n  /*!\n   * \\brief Same as Get().defined().\n   */\n  bool defined() const { return ref_.defined(); }\n\n  /*!\n   * \\brief Convert the wrapped reference type to a subtype.\n   *\n   * Throws an exception if IsInstance<RefU>() is false.\n   */\n  template <typename RefU>\n  TracedObject<RefU> Downcast() const {\n    return TracedObject<RefU>(tvm::runtime::Downcast<RefU>(ref_), path_);\n  }\n\n  /*!\n   * \\brief Convert the wrapped reference type to a subtype.\n   *\n   * Returns an empty optional if IsInstance<RefU>() is false.\n   */\n  template <typename RefU>\n  TracedOptional<RefU> TryDowncast() const {\n    if (ref_->template IsInstance<typename RefU::ContainerType>()) {\n      return Downcast<RefU>();\n    } else {\n      return TracedOptional<RefU>(NullOpt, path_);\n    }\n  }\n\n  /*!\n   * \\brief Get the path of the wrapped object.\n   */\n  const ObjectPath& GetPath() const { return path_; }\n\n private:\n  RefT ref_;\n  ObjectPath path_;\n};\n\n/*!\n * \\brief Iterator class for TracedMap<K, V>\n */\ntemplate <typename K, typename V>\nclass TracedMapIterator {\n public:\n  using WrappedV = typename detail::TracedObjectWrapperSelector<V>::Type;\n  using MapIter = typename Map<K, V>::iterator;\n\n  using iterator_category = std::bidirectional_iterator_tag;\n  using difference_type = ptrdiff_t;\n  using value_type = const std::pair<K, WrappedV>;\n  using pointer = value_type*;\n  using reference = value_type;\n\n  explicit TracedMapIterator(MapIter iter, ObjectPath map_path)\n      : iter_(iter), map_path_(std::move(map_path)) {}\n\n  bool operator==(const TracedMapIterator& other) const { return iter_ == other.iter_; }\n\n  bool operator!=(const TracedMapIterator& other) const { return iter_ != other.iter_; }\n\n  pointer operator->() const = delete;\n\n  reference operator*() const {\n    auto kv = *iter_;\n    return std::make_pair(kv.first, WrappedV(kv.second, map_path_->MapValue(kv.first)));\n  }\n\n  TracedMapIterator& operator++() {\n    ++iter_;\n    return *this;\n  }\n\n  TracedMapIterator operator++(int) {\n    TracedMapIterator copy = *this;\n    ++(*this);\n    return copy;\n  }\n\n private:\n  MapIter iter_;\n  ObjectPath map_path_;\n};\n\n/*!\n * \\brief Traced wrapper for Map objects.\n */\ntemplate <typename K, typename V>\nclass TracedMap {\n public:\n  using WrappedV = typename detail::TracedObjectWrapperSelector<V>::Type;\n\n  using iterator = TracedMapIterator<K, V>;\n\n  // Don't use this direcly. For convenience, call MakeTraced() instead.\n  explicit TracedMap(Map<K, V> map, ObjectPath path)\n      : map_(std::move(map)), path_(std::move(path)) {}\n\n  /*!\n   * \\brief Get a value by its key, wrapped in a traced wrapper.\n   */\n  WrappedV at(const K& key) const {\n    auto it = map_.find(key);\n    ICHECK(it != map_.end()) << \"No such key in Map\";\n    auto kv = *it;\n    return WrappedV(kv.second, path_->MapValue(kv.first));\n  }\n\n  /*!\n   * \\brief Access the wrapped map object.\n   */\n  const Map<K, V>& Get() const { return map_; }\n\n  /*!\n   * \\brief Get the path of the wrapped object.\n   */\n  const ObjectPath& GetPath() const { return path_; }\n\n  /*!\n   * \\brief Get an iterator to the first item of the map.\n   */\n  iterator begin() const { return iterator(map_.begin(), path_); }\n\n  /*!\n   * \\brief Get an iterator to the end of the map.\n   */\n  iterator end() const { return iterator(map_.end(), path_); }\n\n  /*!\n   * \\brief Returns true iff the wrapped map is empty.\n   */\n  bool empty() const { return map_.empty(); }\n\n private:\n  Map<K, V> map_;\n  ObjectPath path_;\n};\n\n/*!\n * \\brief Iterator class for TracedArray<T>\n */\ntemplate <typename T>\nclass TracedArrayIterator {\n public:\n  using WrappedT = typename detail::TracedObjectWrapperSelector<T>::Type;\n\n  using difference_type = ptrdiff_t;\n  using value_type = WrappedT;\n  using pointer = WrappedT*;\n  using reference = WrappedT&;\n  using iterator_category = std::random_access_iterator_tag;\n\n  explicit TracedArrayIterator(Array<T> array, size_t index, ObjectPath array_path)\n      : array_(array), index_(index), array_path_(array_path) {}\n\n  TracedArrayIterator& operator++() {\n    ++index_;\n    return *this;\n  }\n  TracedArrayIterator& operator--() {\n    --index_;\n    return *this;\n  }\n  TracedArrayIterator operator++(int) {\n    TracedArrayIterator copy = *this;\n    ++index_;\n    return copy;\n  }\n  TracedArrayIterator operator--(int) {\n    TracedArrayIterator copy = *this;\n    --index_;\n    return copy;\n  }\n\n  TracedArrayIterator operator+(difference_type offset) const {\n    return TracedArrayIterator(array_, index_ + offset, array_path_);\n  }\n\n  TracedArrayIterator operator-(difference_type offset) const {\n    return TracedArrayIterator(array_, index_ - offset, array_path_);\n  }\n\n  difference_type operator-(const TracedArrayIterator& rhs) const { return index_ - rhs.index_; }\n\n  bool operator==(TracedArrayIterator other) const {\n    return array_.get() == other.array_.get() && index_ == other.index_;\n  }\n  bool operator!=(TracedArrayIterator other) const { return !(*this == other); }\n  value_type operator*() const { return WrappedT(array_[index_], array_path_->ArrayIndex(index_)); }\n\n private:\n  Array<T> array_;\n  size_t index_;\n  ObjectPath array_path_;\n};\n\n/*!\n * \\brief Traced wrapper for Array objects.\n */\ntemplate <typename T>\nclass TracedArray {\n public:\n  using WrappedT = typename detail::TracedObjectWrapperSelector<T>::Type;\n\n  using iterator = TracedArrayIterator<T>;\n\n  // Don't use this direcly. For convenience, call MakeTraced() instead.\n  explicit TracedArray(Array<T> array, ObjectPath path)\n      : array_(std::move(array)), path_(std::move(path)) {}\n\n  /*!\n   * \\brief Access the wrapped array object.\n   */\n  const Array<T>& Get() const { return array_; }\n\n  /*!\n   * \\brief Get the path of the wrapped array object.\n   */\n  const ObjectPath& GetPath() const { return path_; }\n\n  /*!\n   * \\brief Get an element by index, wrapped in a traced wrapper.\n   */\n  WrappedT operator[](size_t index) const {\n    return WrappedT(array_[index], path_->ArrayIndex(index));\n  }\n\n  /*!\n   * \\brief Get an iterator to the first array element.\n   *\n   * The iterator's dereference operator will automatically wrap each element in a traced wrapper.\n   */\n  iterator begin() const { return iterator(array_, 0, path_); }\n\n  /*!\n   * \\brief Get an iterator to the end of the array.\n   *\n   * The iterator's dereference operator will automatically wrap each element in a traced wrapper.\n   */\n  iterator end() const { return iterator(array_, array_.size(), path_); }\n\n  /*!\n   * \\brief Returns true iff the wrapped array is empty.\n   */\n  bool empty() const { return array_.empty(); }\n\n  /*!\n   * \\brief Get the size of the wrapped array.\n   */\n  size_t size() const { return array_.size(); }\n\n private:\n  Array<T> array_;\n  ObjectPath path_;\n};\n\n/*!\n * \\brief Traced wrapper for Optional objects.\n */\ntemplate <typename T>\nclass TracedOptional {\n public:\n  using WrappedT = typename detail::TracedObjectWrapperSelector<T>::Type;\n\n  /*!\n   * \\brief Implicit conversion from the corresponding non-optional traced wrapper.\n   */\n  TracedOptional(const WrappedT& value)  // NOLINT(runtime/explicit)\n      : optional_(value.Get().defined() ? value.Get() : Optional<T>(NullOpt)),\n        path_(value.GetPath()) {}\n\n  // Don't use this direcly. For convenience, call MakeTraced() instead.\n  explicit TracedOptional(Optional<T> optional, ObjectPath path)\n      : optional_(std::move(optional)), path_(std::move(path)) {}\n\n  /*!\n   * \\brief Access the wrapped optional object.\n   */\n  const Optional<T>& Get() const { return optional_; }\n\n  /*!\n   * \\brief Get the path of the wrapped optional object.\n   */\n  const ObjectPath& GetPath() const { return path_; }\n\n  /*!\n   * \\brief Returns true iff the object is present.\n   */\n  bool defined() const { return optional_.defined(); }\n\n  /*!\n   * \\brief Returns a non-optional traced wrapper, throws if defined() is false.\n   */\n  WrappedT value() const { return WrappedT(optional_.value(), path_); }\n\n  /*!\n   * \\brief Same as defined().\n   */\n  explicit operator bool() const { return optional_.defined(); }\n\n private:\n  Optional<T> optional_;\n  ObjectPath path_;\n};\n\n/*!\n * \\brief Traced wrapper for basic values (i.e. non-TVM objects)\n */\ntemplate <typename T>\nclass TracedBasicValue {\n public:\n  explicit TracedBasicValue(const T& value, ObjectPath path)\n      : value_(value), path_(std::move(path)) {}\n\n  /*!\n   * \\brief Access the wrapped value.\n   */\n  const T& Get() const { return value_; }\n\n  /*!\n   * \\brief Get the path of the wrapped value.\n   */\n  const ObjectPath& GetPath() const { return path_; }\n\n  /*!\n   * \\brief Transform the wrapped value without changing its path.\n   */\n  template <typename F>\n  typename detail::TracedObjectWrapperSelector<typename std::invoke_result<F, const T&>::type>::Type\n  ApplyFunc(F&& f) const {\n    return MakeTraced(f(value_), path_);\n  }\n\n private:\n  T value_;\n  ObjectPath path_;\n};\n\n/*!\n * \\brief Wrap the given root object in an appropriate traced wrapper class.\n */\ntemplate <typename RefT>\ntypename detail::TracedObjectWrapperSelector<RefT>::Type MakeTraced(const RefT& object) {\n  using WrappedT = typename detail::TracedObjectWrapperSelector<RefT>::Type;\n  return WrappedT(object, ObjectPath::Root());\n}\n\n/*!\n * \\brief Wrap the given object with the given path in an appropriate traced wrapper class.\n */\ntemplate <typename RefT>\ntypename detail::TracedObjectWrapperSelector<RefT>::Type MakeTraced(const RefT& object,\n                                                                    ObjectPath path) {\n  using WrappedT = typename detail::TracedObjectWrapperSelector<RefT>::Type;\n  return WrappedT(object, std::move(path));\n}\n\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_TRACED_OBJECT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/traced_object_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_TRACED_OBJECT_FUNCTOR_H_\n#define TVM_SCRIPT_PRINTER_TRACED_OBJECT_FUNCTOR_H_\n\n#include <tvm/node/node.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/script/printer/traced_object.h>\n\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*\n * This type alias and the following free functions are created to reduce the binary bloat\n * from template and also hide implementation details from this header\n */\nusing DispatchTable = std::unordered_map<std::string, std::vector<runtime::PackedFunc>>;\n\n/*!\n * \\brief Get function from dispatch table.\n * \\param dispatch_table The dispatch table.\n * \\param token The dispatch token.\n * \\param type_index The type index of the Object type to be dispatched.\n *\n * \\return The dispatch function.\n */\nconst runtime::PackedFunc& GetDispatchFunction(const DispatchTable& dispatch_table,\n                                               const String& token, uint32_t type_index);\n\n/*!\n * \\brief Set function in dispatch table.\n * \\param dispatch_table The dispatch table.\n * \\param token The dispatch token.\n * \\param type_index The type index of the Object type to be dispatched.\n * \\param f The dispatch function.\n */\nvoid SetDispatchFunction(DispatchTable* dispatch_table, const String& token, uint32_t type_index,\n                         runtime::PackedFunc f);\n\n/*!\n * \\brief Remove function from dispatch table.\n * \\param dispatch_table The dispatch table.\n * \\param token The dispatch token.\n * \\param type_index The TVM object type index for the dispatch function to be removed.\n */\nvoid RemoveDispatchFunction(DispatchTable* dispatch_table, const String& token,\n                            uint32_t type_index);\n\nconstexpr const char* kDefaultDispatchToken = \"\";\n\n/*!\n * \\brief Dynamic dispatch functor based on TracedObject.\n *\n * This functor dispatches based on the type of object ref inside the input TracedObject,\n * and the input dispatch token.\n */\ntemplate <typename R, typename... Args>\nclass TracedObjectFunctor {\n private:\n  using TSelf = TracedObjectFunctor<R, Args...>;\n\n  template <class TObjectRef, class TCallable>\n  using IsDispatchFunction =\n      typename std::is_convertible<TCallable, std::function<R(TracedObject<TObjectRef>, Args...)>>;\n\n public:\n  /*!\n   * \\brief Call the dispatch function.\n   * \\param token The dispatch token.\n   * \\param traced_object The traced object.\n   * \\param args Other args.\n   *\n   * \\return The return value of the dispatch function\n   *\n   * If the TObjectRef isn't registered with the token, it will try to find\n   * dispatch function for TObjectRef with kDefaultDispatchToken.\n   */\n  template <class TObjectRef>\n  R operator()(const String& token, TracedObject<TObjectRef> traced_object, Args... args) const {\n    const runtime::PackedFunc& dispatch_function =\n        GetDispatchFunction(dispatch_table_, token, traced_object.Get()->type_index());\n    return dispatch_function(traced_object.Get(), traced_object.GetPath(), args...);\n  }\n\n  /*!\n   * \\brief Set the dispatch function\n   * \\param token The dispatch token.\n   * \\param type_index The TVM object type index for this dispatch function.\n   * \\param f The dispatch function.\n   *\n   * This takes a type-erased packed function as input. It should be used\n   * through FFI boundary, for example, registering dispatch function from Python.\n   */\n  TSelf& set_dispatch(String token, uint32_t type_index, runtime::PackedFunc f) {\n    SetDispatchFunction(&dispatch_table_, token, type_index, std::move(f));\n    return *this;\n  }\n\n  /*!\n   * \\brief Set the dispatch function\n   * \\param token The dispatch token.\n   * \\param f The dispatch function.\n   *\n   * The diaptch function should have signature `R(TracedObject<TObjectRef>, Args...)`.\n   */\n  template <typename TObjectRef, typename TCallable,\n            typename = std::enable_if_t<IsDispatchFunction<TObjectRef, TCallable>::value>>\n  TSelf& set_dispatch(String token, TCallable f) {\n    return set_dispatch(\n        token,                                          //\n        TObjectRef::ContainerType::RuntimeTypeIndex(),  //\n        runtime::TypedPackedFunc<R(TObjectRef, ObjectPath, Args...)>(\n            [f = std::move(f)](TObjectRef object, ObjectPath path, Args... args) -> R {\n              return f(MakeTraced(object, path), args...);\n            }));\n  }\n  /*!\n   * \\brief Set the default dispatch function\n   * \\param f The dispatch function.\n   *\n   * Default dispatch function will be used if there is no function registered\n   * with the requested dispatch token.\n   *\n   * Default dispatch function has an empty string as dispatch token.\n   */\n  template <typename TObjectRef, typename TCallable,\n            typename = std::enable_if_t<IsDispatchFunction<TObjectRef, TCallable>::value>>\n  TSelf& set_dispatch(TCallable&& f) {\n    return set_dispatch<TObjectRef>(kDefaultDispatchToken, std::forward<TCallable>(f));\n  }\n\n  /*!\n   * \\brief Remove dispatch function\n   * \\param token The dispatch token.\n   * \\param type_index The TVM object type index for the dispatch function to be removed.\n   *\n   * This is useful when dispatch function comes from other language's runtime, and\n   * those function should be removed before that language runtime shuts down.\n   */\n  void remove_dispatch(String token, uint32_t type_index) {\n    RemoveDispatchFunction(&dispatch_table_, token, type_index);\n  }\n\n private:\n  DispatchTable dispatch_table_;\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n#endif  // TVM_SCRIPT_PRINTER_TRACED_OBJECT_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/script/printer/var_table.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_VAR_TABLE_H_\n#define TVM_SCRIPT_PRINTER_VAR_TABLE_H_\n\n#include <tvm/node/node.h>\n#include <tvm/node/object_path.h>\n#include <tvm/script/printer/doc.h>\n#include <tvm/script/printer/frame.h>\n#include <tvm/script/printer/traced_object.h>\n\n#include <unordered_map>\n#include <unordered_set>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*!\n * \\brief Variable Table manages mapping from variable object to ExprDoc during\n * the process of printing TVMScript.\n *\n * The value type of this map is ExprDoc rather than IdDoc or String. It's\n * because variables can be implicitly defined. For example in TIR buffer (tir::Buffer),\n * `buf->data` is a variable, while its representation in TVMScript should be an\n * expression `x.data`, where `x` is the variable for the buffer itself.\n */\nclass VarTableNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor*) {}\n\n  /*!\n   * \\brief Define variable by name.\n   * \\param obj The variable object.\n   * \\param name_hint The hint for variable name.\n   * \\param object_path The object_path for the returned ExprDoc.\n   * \\param frame The frame that this variable is defined in.\n   *\n   * \\return The id doc for this variable.\n   *\n   * This function will rename the variable to avoid name conflict with other variables\n   * in the table.\n   */\n  IdDoc Define(const ObjectRef& obj, const String& name_hint, const ObjectPath& object_path,\n               const Frame& frame);\n\n  /*!\n   * \\brief Define variable by name.\n   * \\param obj The variable object.\n   * \\param name_hint The hint for variable name.\n   * \\param frame The frame that this variable is defined in.\n   *\n   * \\return The id doc for this variable.\n   *\n   * This is a shortcut version of `Define` which accepts a traced string.\n   */\n  IdDoc Define(const ObjectRef& obj, const TracedObject<String>& name_hint, const Frame& frame) {\n    return Define(obj, name_hint.Get(), name_hint.GetPath(), frame);\n  }\n\n  using DocFactory = std::function<ExprDoc()>;\n\n  /*!\n   * \\brief Define variable by doc factory.\n   * \\param obj The variable object.\n   * \\param doc_factory The function to return an ExprDoc object for this variable.\n   * \\param frame The frame that this variable is defined in.\n   *\n   * This function is a special form of `Define`. Variable is mapped to ExprDoc rather\n   * than IdDoc. It's useful when a variable is implicitly defined without a name, like\n   * the buf->data in TIR, which should be mapped to `AttrDoc(IdDoc(\"<buffer_name>\"), \"data\")`.\n   *\n   * This function takes a DocFactory instead of Doc. It's because GetVarDoc needs to\n   * return a new Doc object every time it's called, as the returned doc will have\n   * different `soruce_path`. Currently there isn't a good way to deep copy a TVMObject\n   * so VarTable needs to call a factory function to get a freshly-constructed Doc object\n   * every time GetVarDoc is called.\n   */\n  void DefineByDoc(const ObjectRef& obj, DocFactory doc_factory, const Frame& frame);\n\n  /*!\n   * \\brief Get the doc for variable.\n   * \\param obj The variable object.\n   * \\param object_path The object path for the variable.\n   *\n   * \\return The doc for variable, if it exists in the table. Otherwise it returns NullOpt.\n   */\n  Optional<ExprDoc> GetVarDoc(const ObjectRef& obj, const ObjectPath& object_path) const;\n\n  /*!\n   * \\brief Get the doc for variable.\n   * \\param obj The traced variable object.\n   *\n   * \\return The doc for variable, if it exists in the table. Otherwise it returns NullOpt.\n   */\n  template <typename TObjectRef>\n  Optional<ExprDoc> GetVarDoc(const TracedObject<TObjectRef> obj) const {\n    return GetVarDoc(obj.Get(), obj.GetPath());\n  }\n\n  /*!\n   * \\brief Check if a variable exists in the table.\n   * \\param obj The variable object.\n   *\n   * \\return a boolean for whether variable exists.\n   */\n  bool IsVarDefined(const ObjectRef& obj) const;\n\n  static constexpr const char* _type_key = \"script.printer.VarTable\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(VarTableNode, Object);\n\n private:\n  void RemoveVar(const ObjectRef& obj);\n\n  struct VariableInfo {\n    DocFactory doc_factory;\n    Optional<String> name;\n  };\n  std::unordered_map<ObjectRef, VariableInfo, ObjectPtrHash, ObjectPtrEqual> obj2info;\n  std::unordered_set<String> defined_names;\n};\n\n/*!\n * \\brief Reference type of VarTableNode.\n */\nclass VarTable : public ObjectRef {\n public:\n  /*!\n   * \\brief Create an empty VarTable.\n   */\n  VarTable();\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(VarTable, ObjectRef, VarTableNode);\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_VAR_TABLE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/support/parallel_for.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file parallel_for.h\n * \\brief An implementation to run loop in parallel.\n */\n#ifndef TVM_SUPPORT_PARALLEL_FOR_H_\n#define TVM_SUPPORT_PARALLEL_FOR_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <functional>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n\nusing PartitionerFuncType = std::function<std::vector<std::vector<int>>(int, int, int, int)>;\n\n/*!\n * \\brief A partitioner to split the task to each thread in Round-robin manner.\n * \\param begin The start index of this parallel loop(inclusive).\n * \\param end The end index of this parallel loop(exclusive).\n * \\param step The traversal step to the index.\n * \\param num_threads The number of threads(the number of tasks to be partitioned to).\n * \\return A list with `num_threads` elements, and each is a list of integers indicating the loop\n * indexes for the corresponding thread to process.\n */\nTVM_DLL std::vector<std::vector<int>> rr_partitioner(int begin, int end, int step, int num_threads);\n\n/*!\n * \\brief A runtime api provided to run the task function in parallel.\n * e.g. A for loop:\n *   for (int i = 0; i < 10; i++) {\n *     a[i] = i;\n *   }\n * should work the same as:\n *   parallel_for(0, 10, [&a](int index) {\n *     a[i] = i;\n *   });\n * \\param begin The start index of this parallel loop(inclusive).\n * \\param end The end index of this parallel loop(exclusive).\n * \\param f The task function to be executed. Assert to take an int index as input with no output.\n * \\param step The traversal step to the index.\n * \\param partitioner A partition function to split tasks to different threads. Use Round-robin\n * partitioner by default.\n * \\note 1. Currently do not support nested parallel_for; 2. The order of execution in each thread\n * is not guaranteed, the for loop task should be thread independent and thread safe.\n */\nTVM_DLL void parallel_for(int begin, int end, const std::function<void(int)>& f, int step = 1,\n                          const PartitionerFuncType partitioner = rr_partitioner);\n\n/*!\n * \\brief An API to launch fix amount of threads to run the specific functor in parallel.\n * Different from `parallel_for`, the partition is determined dynamically on the fly,\n * i.e. any time when a thread is idle, it fetches the next task to run.\n * The behavior is similar to dynamic scheduling in OpenMP:\n *\n *   \\#pragma omp parallel for schedule(dynamic) num_threads(num_threads)\n *   for (int i = 0; i < 10; i++) {\n *     a[i] = i;\n *   }\n *\n * \\param begin The start index of this parallel loop (inclusive).\n * \\param end The end index of this parallel loop (exclusive).\n * \\param num_threads The number of threads to be used.\n * \\param f The task function to be executed. Takes the thread index and the task index as\n * input with no output.\n * \\note `step` support is left for future work.\n */\nTVM_DLL void parallel_for_dynamic(int begin, int end, int num_threads,\n                                  const std::function<void(int thread_id, int task_id)>& f);\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_PARALLEL_FOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/support/random_engine.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file random_engine.h\n * \\brief Random number generator. It provides a generic interface consistent with\n * `std::uniform_random_bit_generator`\n */\n#ifndef TVM_SUPPORT_RANDOM_ENGINE_H_\n#define TVM_SUPPORT_RANDOM_ENGINE_H_\n#include <tvm/runtime/logging.h>\n\n#include <cstdint>\n#include <random>\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief This linear congruential engine is a drop-in replacement for std::minstd_rand. It strictly\n *  corresponds to std::minstd_rand and is designed to be platform-independent.\n * \\note Our linear congruential engine is a complete implementation of\n *  std::uniform_random_bit_generator so it can be used as generator for any STL random number\n *  distribution. However, parts of std::linear_congruential_engine's member functions are not\n *  included for simplification. For full member functions of std::minstd_rand, please check out the\n *  following link: https://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine\n */\n\nclass LinearCongruentialEngine {\n public:\n  using TRandState = int64_t;\n  /*! \\brief The result type. */\n  using result_type = uint64_t;\n  /*! \\brief The multiplier */\n  static constexpr TRandState multiplier = 48271;\n  /*! \\brief The increment */\n  static constexpr TRandState increment = 0;\n  /*! \\brief The modulus */\n  static constexpr TRandState modulus = 2147483647;\n  /*! \\brief The minimum possible value of random state here. */\n  static constexpr result_type min() { return 0; }\n  /*! \\brief The maximum possible value of random state here. */\n  static constexpr result_type max() { return modulus - 1; }\n\n  /*!\n   * \\brief Get a device random state\n   * \\return The random state\n   */\n  static TRandState DeviceRandom() { return (std::random_device()()) % modulus; }\n\n  /*!\n   * \\brief Operator to move the random state to the next and return the new random state. According\n   *  to definition of linear congruential engine, the new random state value is computed as\n   *  new_random_state = (current_random_state * multiplier + increment) % modulus.\n   * \\return The next current random state value in the type of result_type.\n   * \\note In order for better efficiency, the implementation here has a few assumptions:\n   *  1. The multiplication and addition won't overflow.\n   *  2. The given random state pointer `rand_state_ptr` is not nullptr.\n   *  3. The given random state `*(rand_state_ptr)` is in the range of [0, modulus - 1].\n   */\n  result_type operator()() {\n    (*rand_state_ptr_) = ((*rand_state_ptr_) * multiplier + increment) % modulus;\n    return *rand_state_ptr_;\n  }\n  /*!\n   * \\brief Normalize the random seed to the range of [1, modulus - 1].\n   * \\param rand_state The random seed.\n   * \\return The normalized random seed.\n   */\n  static TRandState NormalizeSeed(TRandState rand_state) {\n    if (rand_state == -1) {\n      rand_state = DeviceRandom();\n    } else {\n      rand_state %= modulus;\n    }\n    if (rand_state == 0) {\n      rand_state = 1;\n    }\n    if (rand_state < 0) {\n      LOG(FATAL) << \"ValueError: Random seed must be non-negative\";\n    }\n    return rand_state;\n  }\n  /*!\n   * \\brief Change the start random state of RNG with the seed of a new random state value.\n   * \\param rand_state The random state given in result_type.\n   */\n  void Seed(TRandState rand_state) {\n    ICHECK(rand_state_ptr_ != nullptr);\n    *rand_state_ptr_ = NormalizeSeed(rand_state);\n  }\n\n  /*!\n   * \\brief Fork a new seed for another RNG from current random state.\n   * \\return The forked seed.\n   */\n  TRandState ForkSeed() {\n    // In order for reproducibility, we compute the new seed using RNG's random state and a\n    // different set of parameters. Note that both 32767 and 1999999973 are prime numbers.\n    return ((*this)() * 32767) % 1999999973;\n  }\n\n  /*!\n   * \\brief Construct a random number generator with a random state pointer.\n   * \\param rand_state_ptr The random state pointer given in result_type*.\n   * \\note The random state is not checked for whether it's nullptr and whether it's in the range of\n   *  [0, modulus-1]. We assume the given random state is valid or the Seed function would be\n   *  called right after the constructor before any usage.\n   */\n  explicit LinearCongruentialEngine(TRandState* rand_state_ptr) {\n    rand_state_ptr_ = rand_state_ptr;\n  }\n\n private:\n  TRandState* rand_state_ptr_;\n};\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_RANDOM_ENGINE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/support/span.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file tvm/support/span.h\n * \\brief Reimplementation of part of C++-20 style span.\n */\n#ifndef TVM_SUPPORT_SPAN_H_\n#define TVM_SUPPORT_SPAN_H_\n\n#include <cstddef>\n#include <iterator>\n#include <type_traits>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief A partial implementation of the C++20 std::span.\n *\n * At the time of writing, TVM must compile against C++17.\n */\ntemplate <class T, class W>\nclass Span {\n public:\n  using value_type = W;\n  using const_W = typename std::add_const<W>::type;\n\n  template <class W1>\n  class iterator_base {\n   public:\n    using iterator_category = std::input_iterator_tag;\n    using value_type = W;\n    using difference_type = std::ptrdiff_t;\n    using pointer = const W*;\n    using reference = const W&;\n\n    inline iterator_base(T* ptr, T* end) : ptr_{ptr}, end_{end} { CHECK_GE(end, ptr); }\n\n    inline W1 operator*() { return W1(*ptr_); }\n\n    inline iterator_base<W1>& operator++() {\n      if (ptr_ != end_) ptr_++;\n      return *this;\n    }\n\n    inline bool operator==(iterator_base<W1> other) {\n      return ptr_ == other.ptr_ && end_ == other.end_;\n    }\n\n    inline bool operator!=(iterator_base<W1> other) { return !(*this == other); }\n\n    template <class X = W1, typename = std::enable_if_t<!std::is_const<X>::value>>\n    inline operator iterator_base<const_W>() const {\n      return iterator_base<const_W>(ptr_, end_);\n    }\n\n   private:\n    T* ptr_;\n    T* end_;\n  };\n\n  using iterator = iterator_base<W>;\n  using const_iterator = iterator_base<const_W>;\n\n  inline Span(T* begin, int num_elements) : begin_{begin}, end_{begin + num_elements} {}\n  inline Span(T* begin, T* end) : begin_{begin}, end_{end} {}\n\n  inline iterator begin() const { return iterator(begin_, end_); }\n\n  inline iterator end() const { return iterator(end_, end_); }\n\n  size_t size() const { return end_ - begin_; }\n\n  inline W operator[](int i) {\n    T* to_return = begin_ + i;\n    ICHECK_LT(to_return, end_) << \"Span access out of bounds: \" << i;\n    return W(*to_return);\n  }\n\n  inline operator std::vector<W>() { return std::vector<W>(begin(), end()); }\n\n protected:\n  T* begin_;\n  T* end_;\n};\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_SPAN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/support/with.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/support/with.h\n * \\brief RAII wrapper function to enter and exit a context object\n *        similar to python's with syntax.\n */\n#ifndef TVM_SUPPORT_WITH_H_\n#define TVM_SUPPORT_WITH_H_\n\n#include <dmlc/common.h>\n\n#include <functional>\n#include <utility>\n\nnamespace tvm {\n\n/*!\n * \\brief RAII wrapper function to enter and exit a context object\n *        similar to python's with syntax.\n *\n * \\code\n * // context class\n * class MyContext {\n *  private:\n *    friend class With<MyContext>;\n      MyContext(arguments);\n *    void EnterWithScope();\n *    void ExitWithScope();\n * };\n *\n * {\n *   With<MyContext> scope(arguments);\n *   // effect take place.\n * }\n * \\endcode\n *\n * \\tparam ContextType Type of the context object.\n */\ntemplate <typename ContextType>\nclass With {\n public:\n  /*!\n   * \\brief constructor.\n   *  Enter the scope of the context.\n   */\n  template <typename... Args>\n  explicit With(Args&&... args) : ctx_(std::forward<Args>(args)...) {\n    ctx_.EnterWithScope();\n  }\n  /*! \\brief destructor, leaves the scope of the context. */\n  ~With() DMLC_THROW_EXCEPTION { ctx_.ExitWithScope(); }\n\n  // Disable copy and move construction.  `With` is intended only for\n  // use in nested contexts that are exited in the reverse order of\n  // entry.  Allowing context to be copied or moved would break this\n  // expectation.\n  With(const With& other) = delete;\n  With& operator=(const With& other) = delete;\n  With(With&& other) = delete;\n  With& operator=(With&& other) = delete;\n\n  ContextType* get() { return &ctx_; }\n  const ContextType* get() const { return &ctx_; }\n\n  ContextType* operator->() { return get(); }\n  const ContextType* operator->() const { return get(); }\n  ContextType& operator*() { return *get(); }\n  const ContextType* operator*() const { return *get(); }\n\n  ContextType operator()() { return ctx_; }\n\n private:\n  /*! \\brief internal context type. */\n  ContextType ctx_;\n};\n\n/*!\n * \\brief A context type that delegates EnterWithScope and ExitWithScope\n *        to user-provided functions.\n */\nclass ContextManager {\n public:\n  /*!\n   * \\brief Constructor of ContextManager.\n   * \\param f_enter The function to call when entering scope. If it's nullptr, do nothing when\n   *                entering.\n   * \\param f_exit The function to call when exiting scope. If it's nullptr, do nothing\n   *               when exiting.\n   */\n  template <class FEnter, class FExit>\n  explicit ContextManager(FEnter f_enter, FExit f_exit) : f_enter_(f_enter), f_exit_(f_exit) {}\n\n private:\n  void EnterWithScope() {\n    if (f_enter_) f_enter_();\n  }\n  void ExitWithScope() {\n    if (f_exit_) f_exit_();\n  }\n  std::function<void()> f_enter_;\n  std::function<void()> f_exit_;\n  template <typename>\n  friend class With;\n};\n\n}  // namespace tvm\n#endif  // TVM_SUPPORT_WITH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/codegen.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/codegen.h\n * \\brief Translates IRModule to runtime::Module.\n */\n#ifndef TVM_TARGET_CODEGEN_H_\n#define TVM_TARGET_CODEGEN_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n\nnamespace tvm {\n/*! \\brief namespace for target translation and codegen. */\nnamespace codegen {\n// use packed function from runtime.\nusing runtime::PackedFunc;\nusing runtime::TVMArgs;\nusing runtime::TVMRetValue;\n\n/*!\n * \\brief Build a module from array of lowered function.\n * \\param mod The Module to be built\n * \\param target The target to be built.\n * \\return The result runtime::Module.\n */\nruntime::Module Build(IRModule mod, Target target);\n\n/*!\n * \\brief Pack imported device library to a C file.\n *  Compile the C file and link with the host library\n *  will allow the DSO loader to automatically discover and import\n *  the dependency from the shared library.\n *\n * \\param m The host module with the imports.\n * \\param system_lib Whether expose as system library.\n * \\return cstr The C string representation of the file.\n */\nstd::string PackImportsToC(const runtime::Module& m, bool system_lib);\n\n/*!\n * \\brief Pack imported device library to a LLVM module.\n *  Compile the LLVM module and link with the host library\n *  will allow the DSO loader to automatically discover and import\n *  the dependency from the shared library.\n *\n * \\param m The host module with the imports.\n * \\param system_lib Whether expose as system library.\n * \\param target_triple LLVM target triple\n * \\return runtime::Module The generated LLVM module.\n */\nruntime::Module PackImportsToLLVM(const runtime::Module& m, bool system_lib,\n                                  const std::string& target_triple);\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_CODEGEN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/compilation_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/compilation_config.h\n * \\brief A helper class to collect all the targets in canonical form necessary for compilation.\n */\n\n#ifndef TVM_TARGET_COMPILATION_CONFIG_H_\n#define TVM_TARGET_COMPILATION_CONFIG_H_\n\n#include <tvm/target/virtual_device.h>\n\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief Gathers the \\p Targets and distinguished \\p VirtualDevices in canonical form needed to\n * compile a Relay module for execution over possibly heterogeneous devices. Centralizes the\n * validation and canonicalization logic needed to transition from targets supplied by the Python\n * APIs to a single internal representation. Also holds a cache of canonical \\p VirtualDevices\n * so that structural equal virtual devices have pointer equal canonical virtual devices.\n *\n * The construction of \\p CompilationConfig is idempotent, in that given the same \\p PassContext\n * \\p ctx and an arbitrary \\p Array<Target> \\p raw_targets:\n *\n * \\code\n *   CompilationConfig(ctxt, raw_targets)\n *      is structurally equal to\n *   CompilationConfig(ctxt, CompilationConfig(ctxt, raw_targets)->primitive_targets)\n * \\endcode\n *\n * TODO(mbs): This is subject to change as we rework compilation options in general. This class\n * is probably better called a 'CompositeTarget', and may be better made a sub-class of Target or\n * some other common-target-root class.\n */\nclass CompilationConfigNode : public Object {\n public:\n  /*!\n   * \\brief The host target. Used for 'scalar' data and code (such as shapes and shape\n   * functions) and residual Relay expressions and data (such as conditionals and ADTs).\n   * Each \\p primitive_target below will have this exact target object as its 'host'.\n   *\n   * Note that it is possible for a \\p Target used for primitive operations to be structurally\n   * equal to the host \\p Target (up to the \\p host field.) However the \\p Target objects will\n   * be distinct, and can be used as keys within a \\p Map without collision.\n   */\n  Target host_target;\n\n  /*!\n   * \\brief Vector of all available \\p Targets for partitioning or compiling primitive tensor\n   * operators (kernels). May contain a \\p Target for the same device type as for the\n   * \\p host_target, however the \\p host_target should be used for all host computations and data.\n   * Each \\p Target will have \\p host_target as its 'host'.\n   *\n   * Primitive targets must be unique by their kind name. In this way the\n   * \\p FindPrimitiveTargetForKind method will find the unique target for the given kind name.\n   * This method is used when transitioning from an external codegen \"Compiler\" attribute value\n   * to the external codegen target representing that compiler.\n   *\n   * It is possible to have multiple primitive targets for the same device type. However given\n   * primitive targets left and right where:\n   *  - left appears before right in the array\n   *  - left->GetTargetDeviceType() == right->GetTargetDeviceType()\n   * then:\n   *  - right.IsExternalCodegenFor(left) must be true\n   * In this way the \\p FindPrimitiveTargetForDeviceOrFail method will find the 'most general'\n   * target for the requested device type. This method is used when transitioning from a device\n   * constraint to the target needed to compile for that device.\n   *\n   * In the homogeneous case primitive_targets will have just one entry, which will be pointer equal\n   * to optional_homogeneous_target.\n   *\n   * In the homogenous case where the 'host' is the same device as used for compiling kernels it\n   * is *not* the case that optional_homogenous_target == host_target. This is because all\n   * primitive always have their host field set to the host_target. Ie, it is valid to have:\n   * \\code\n   *   host_target=Target(\"llvm\")\n   *   optional_homogenous_target=Target(\"llvm\", host=host_target)\n   * \\endcode\n   */\n  Array<Target> primitive_targets;\n\n  /*!\n   * \\brief \\p VirtualDevice for primitive operators which are not otherwise constrained to a\n   * particular device. Used by the PlanDevices pass to determine a virtual device for every\n   * sub-expression.\n   */\n  VirtualDevice default_primitive_virtual_device = VirtualDevice::FullyUnconstrained();\n\n  /*! \\brief VirtualDevice for the host. */\n  VirtualDevice host_virtual_device = VirtualDevice::FullyUnconstrained();\n\n  /*!\n   * \\brief If defined then compile and/or run in 'homogenous execution mode'. In this mode all\n   * primitives are compiled for this target only.\n   *\n   * This is to support legacy passes which have not been adapted to heterogeneous execution and\n   * rely on an implicit global \\p Target to be in scope.\n   *\n   * TODO(mbs): Remove once all passes are 'heterogeneous aware'.\n   */\n  Target optional_homogeneous_target;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Returns the unique \\p Target to use for \\p device_type. Fail if no such target exists.\n   *\n   * This will be the first primitive target with matching device type.\n   */\n  Target FindPrimitiveTargetForDeviceOrFail(DLDeviceType device_type) const;\n\n  /*!\n   * \\brief Returns the unique \\p Target to use for \\p kind_name. Returns null if none such.\n   */\n  Optional<Target> FindPrimitiveTargetForKind(const std::string& kind_name) const;\n\n  /*!\n   * \\brief Returns a \\p Target structurally equal to \\p target, however prefer a structually equal\n   * known host or primitive target if the configuration has one.\n   */\n  Target CanonicalTarget(const Target& target) const;\n\n  /*!\n   * \\brief Returns a \\p VirtualDevice which is structurally equal to \\p virtual_device on all its\n   * constrained fields, however:\n   * - If \\p virtual_device has a device type but not a target, fill in a target using\n   *   \\p FindPrimitiveTargetOrFail. This is the one place we allow targets to be defaulted\n   *   from device types alone.\n   * - If \\p virtual_device has a target, also canonicalize it using \\p CanonicalTarget.\n   * The returned object will be unique for the adjusted virtual device w.r.t. all other\n   * \\p VirtualDevices returned by this method.\n   *\n   * We call the result the 'canonical' \\p VirtualDevice. Two canonical \\p VirtualDevices are\n   * structurally equal if and only if they are pointer equal. In this way we can build maps\n   * from virtual devices using just pointer equality.\n   */\n  VirtualDevice CanonicalVirtualDevice(const VirtualDevice& virtual_device) const;\n\n  static constexpr const char* _type_key = \"CompilationConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CompilationConfigNode, Object)\n\n private:\n  /*!\n   * \\brief Sets the primitive targets, the host target, the default primitive virtual device, and\n   * the host virtual device given:\n   *  - the vector of 'raw' targets (in any order) supplied by one of the TVM entry points.\n   *  - any \"relay.fallback_device_type\" attribute on \\p pass_ctx.\n   *  - whether the LLVM backend is available.\n   * Will look for a suitable host target in the given primitive targets, but if none found may\n   * reuse a raw target or create a default CPU target.\n   */\n  void Init(const transform::PassContext& pass_ctx, const Array<Target>& raw_targets);\n\n  /*!\n   * \\brief Returns a freshly constructed CPU \\p Target.\n   */\n  static Target MakeDefaultCPUTarget();\n\n  /*!\n   * \\brief A cache of constructed virtual devices.\n   */\n  mutable VirtualDeviceCache virtual_device_cache_;\n\n  friend class CompilationConfig;\n};\n\n/*!\n * \\brief Managed reference class to \\p CompilationConfig\n *\n * \\sa CompilationConfig\n */\nclass CompilationConfig : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructs the compilation config given the settings in \\p pass_ctx and supplied\n   * \\p raw_targets. See \\p CompilationConfigNode::Init for details.\n   */\n  TVM_DLL CompilationConfig(const transform::PassContext& pass_ctx,\n                            const Array<Target>& raw_targets);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CompilationConfig, ObjectRef, CompilationConfigNode);\n};\n\n}  // namespace tvm\n\n#endif  // TVM_TARGET_COMPILATION_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/generic_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/generic_func.h\n * \\brief Generic function that can be specialzied on a per target basis.\n */\n#ifndef TVM_TARGET_GENERIC_FUNC_H_\n#define TVM_TARGET_GENERIC_FUNC_H_\n\n#include <tvm/runtime/packed_func.h>\n#include <tvm/support/with.h>\n#include <tvm/target/target.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nclass GenericFuncNode;\n\n/*!\n * \\brief Generic function that can be specialized on a per-target basis.\n */\nclass GenericFunc : public ObjectRef {\n public:\n  GenericFunc() {}\n  explicit GenericFunc(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*!\n   * \\brief Set the default function implementaiton.\n   * \\param value The default function\n   * \\param allow_override If true, this call may override a previously registered function. If\n   * false, an error will be logged if the call would override a previously registered function.\n   * \\return reference to self.\n   */\n  TVM_DLL GenericFunc& set_default(const runtime::PackedFunc value, bool allow_override = false);\n  /*!\n   * \\brief Register a specialized function\n   * \\param tags The tags for this specialization\n   * \\param value The specialized function\n   * \\param allow_override If true, this call may override previously registered tags. If false,\n   * an error will be logged if the call would override previously registered tags.\n   * \\return reference to self.\n   */\n  TVM_DLL GenericFunc& register_func(const std::vector<std::string>& tags,\n                                     const runtime::PackedFunc value, bool allow_override = false);\n  /*!\n   * \\brief Call generic function by directly passing in unpacked format.\n   * \\param args Arguments to be passed.\n   * \\tparam Args arguments to be passed.\n   *\n   * \\code\n   *   // Example code on how to call generic function\n   *   void CallGeneric(GenericFunc f) {\n   *     // call like normal functions by pass in arguments\n   *     // return value is automatically converted back\n   *     int rvalue = f(1, 2.0);\n   *   }\n   * \\endcode\n   */\n  template <typename... Args>\n  inline runtime::TVMRetValue operator()(Args&&... args) const;\n  /*!\n   * \\brief Invoke the relevant function for the current target context, set by set_target_context.\n   * Arguments are passed in packed format.\n   * \\param args The arguments to pass to the function.\n   * \\param ret The return value\n   */\n  TVM_DLL void CallPacked(runtime::TVMArgs args, runtime::TVMRetValue* ret) const;\n  /*!\n   * \\brief Get the packed function specified for the current target context.\n   */\n  TVM_DLL PackedFunc GetPacked() const;\n  /*!\n   * \\brief Find or register the GenericFunc instance corresponding to the give name\n   * \\param name The name of the registered GenericFunc\n   * \\return The GenericFunc instance\n   */\n  TVM_DLL static GenericFunc Get(const std::string& name);\n\n  /*!\n   * \\brief Add a GenericFunc instance to the registry\n   * \\param func The GenericFunc instance\n   * \\param name The name of the registered GenericFunc\n   */\n  TVM_DLL static void RegisterGenericFunc(GenericFunc func, const std::string& name);\n\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline GenericFuncNode* operator->();\n\n  // declare container type\n  using ContainerType = GenericFuncNode;\n\n  // Internal class.\n  struct Manager;\n\n private:\n  friend struct Manager;\n};\n\ntemplate <typename... Args>\ninline runtime::TVMRetValue GenericFunc::operator()(Args&&... args) const {\n  const int kNumArgs = sizeof...(Args);\n  const int kArraySize = kNumArgs > 0 ? kNumArgs : 1;\n  TVMValue values[kArraySize];\n  int type_codes[kArraySize];\n  runtime::detail::for_each(runtime::TVMArgsSetter(values, type_codes),\n                            std::forward<Args>(args)...);\n  runtime::TVMRetValue rv;\n  CallPacked(runtime::TVMArgs(values, type_codes, kNumArgs), &rv);\n  return rv;\n}\n\n/*!\n * \\brief Represents a generic function that can be specialized on a per-target basis.\n */\nclass GenericFuncNode : public Object {\n public:\n  /*! \\brief name of the function */\n  std::string name_;\n  /* \\brief the generic builder */\n  runtime::PackedFunc generic_func_;\n  /* \\brief map from keys to registered functions */\n  std::unordered_map<std::string, runtime::PackedFunc> dispatch_dict_;\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"GenericFunc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(GenericFuncNode, Object);\n};\n\ninline GenericFuncNode* GenericFunc::operator->() {\n  return static_cast<GenericFuncNode*>(get_mutable());\n}\n\n#define TVM_GENERIC_FUNC_REG_VAR_DEF static TVM_ATTRIBUTE_UNUSED ::tvm::GenericFunc& __mk_##TVM\n\n/*!\n * \\def TVM_REGISTER_GENERIC_FUNC\n * \\brief Register a new generic function, or set a device-specific variant\n * of the corresponding function.\n *\n * \\param name The name of the function\n */\n#define TVM_REGISTER_GENERIC_FUNC(name) \\\n  TVM_STR_CONCAT(TVM_GENERIC_FUNC_REG_VAR_DEF, __COUNTER__) = ::tvm::GenericFunc::Get(#name)\n\n}  // namespace tvm\n#endif  // TVM_TARGET_GENERIC_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/tag.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/tag.h\n * \\brief Target tag registry\n */\n#ifndef TVM_TARGET_TAG_H_\n#define TVM_TARGET_TAG_H_\n\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/node/node.h>\n#include <tvm/target/target.h>\n\n#include <utility>\n\nnamespace tvm {\n\n/*! \\brief A target tag */\nclass TargetTagNode : public Object {\n public:\n  /*! \\brief Name of the target */\n  String name;\n  /*! \\brief Config map to generate the target */\n  Map<String, ObjectRef> config;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"config\", &config);\n  }\n\n  static constexpr const char* _type_key = \"TargetTag\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TargetTagNode, Object);\n\n private:\n  /*! \\brief Return the index stored in attr registry */\n  uint32_t AttrRegistryIndex() const { return index_; }\n  /*! \\brief Return the name stored in attr registry */\n  String AttrRegistryName() const { return name; }\n  /*! \\brief Index used for internal lookup of attribute registry */\n  uint32_t index_;\n\n  template <typename, typename>\n  friend class AttrRegistry;\n  template <typename>\n  friend class AttrRegistryMapContainerMap;\n  friend class TargetTagRegEntry;\n};\n\n/*!\n * \\brief Managed reference class to TargetTagNode\n * \\sa TargetTagNode\n */\nclass TargetTag : public ObjectRef {\n public:\n  /*!\n   * \\brief Retrieve the Target given it the name of target tag\n   * \\param target_tag_name Name of the target tag\n   * \\return The Target requested\n   */\n  TVM_DLL static Optional<Target> Get(const String& target_tag_name);\n  /*!\n   * \\brief List all names of the existing target tags\n   * \\return A dictionary that maps tag name to the concrete target it corresponds to\n   */\n  TVM_DLL static Map<String, Target> ListTags();\n  /*!\n   * \\brief Add a tag into the registry\n   * \\param name Name of the tag\n   * \\param config The target config corresponding to the tag\n   * \\param override Allow overriding existing tags\n   * \\return Target created with the tag\n   */\n  TVM_DLL static Target AddTag(String name, Map<String, ObjectRef> config, bool override);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TargetTag, ObjectRef, TargetTagNode);\n\n private:\n  /*! \\brief Mutable access to the container class  */\n  TargetTagNode* operator->() { return static_cast<TargetTagNode*>(data_.get()); }\n  friend class TargetTagRegEntry;\n};\n\nclass TargetTagRegEntry {\n public:\n  /*!\n   * \\brief Set the config dict corresponding to the target tag\n   * \\param config The config dict for target creation\n   */\n  inline TargetTagRegEntry& set_config(Map<String, ObjectRef> config);\n  /*! \\brief Set name of the TargetTag to be the same as registry if it is empty */\n  inline TargetTagRegEntry& set_name();\n  /*!\n   * \\brief Register or get a new entry.\n   * \\param target_tag_name The name of the TargetTag.\n   * \\return the corresponding entry.\n   */\n  TVM_DLL static TargetTagRegEntry& RegisterOrGet(const String& target_tag_name);\n\n private:\n  TargetTag tag_;\n  String name;\n\n  /*! \\brief private constructor */\n  explicit TargetTagRegEntry(uint32_t reg_index) : tag_(make_object<TargetTagNode>()) {\n    tag_->index_ = reg_index;\n  }\n  template <typename, typename>\n  friend class AttrRegistry;\n  friend class TargetTag;\n};\n\ninline TargetTagRegEntry& TargetTagRegEntry::set_config(Map<String, ObjectRef> config) {\n  tag_->config = std::move(config);\n  return *this;\n}\n\ninline TargetTagRegEntry& TargetTagRegEntry::set_name() {\n  if (tag_->name.empty()) {\n    tag_->name = name;\n  }\n  return *this;\n}\n\n#define TVM_TARGET_TAG_REGISTER_VAR_DEF \\\n  static DMLC_ATTRIBUTE_UNUSED ::tvm::TargetTagRegEntry& __make_##TargetTag\n\n/*!\n * \\def TVM_REGISTER_TARGET_TAG\n * \\brief Register a new target tag, or set attribute of the corresponding target tag.\n * \\param TargetTagName The name of target tag\n */\n#define TVM_REGISTER_TARGET_TAG(TargetTagName)                   \\\n  TVM_STR_CONCAT(TVM_TARGET_TAG_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::TargetTagRegEntry::RegisterOrGet(TargetTagName).set_name()\n\n}  // namespace tvm\n\n#endif  // TVM_TARGET_TAG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/target.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/target.h\n * \\brief Compilation target object.\n */\n#ifndef TVM_TARGET_TARGET_H_\n#define TVM_TARGET_TARGET_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/module.h>\n#include <tvm/node/node.h>\n#include <tvm/support/with.h>\n#include <tvm/target/target_kind.h>\n\n#include <string>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\n\nclass TargetInternal;\nclass Target;\n\n/*!\n * \\brief Compilation target.\n * \\sa Target\n */\nclass TargetNode : public Object {\n public:\n  /*! \\brief The kind of the target device */\n  TargetKind kind;\n  /*! \\brief Target host information, must be Target type */\n  Optional<ObjectRef> host;\n  /*! \\brief Tag of the target, can be empty */\n  String tag;\n  /*! \\brief Keys for this target */\n  Array<String> keys;\n  /*! \\brief Collection of attributes */\n  Map<String, ObjectRef> attrs;\n  /*! \\brief Target features */\n  Map<String, ObjectRef> features;\n\n  /*!\n   * \\brief The raw string representation of the target\n   * \\return the full device string to pass to codegen::Build\n   * \\note It will be deprecated after the Target RFC is fully landed.\n   */\n  TVM_DLL const std::string& str() const;\n  /*! \\return Export target to JSON-like configuration */\n  TVM_DLL Map<String, ObjectRef> Export() const;\n  /*! \\return The Optional<Target> typed target host of the TargetNode */\n  TVM_DLL Optional<Target> GetHost() const;\n  /*! \\return The device type for this target */\n  TVM_DLL int GetTargetDeviceType() const;\n\n  /*!\n   * \\brief Returns a human readable representation of \\p Target which includes all fields,\n   * especially the host. Useful for diagnostic messages and debugging.\n   *\n   * TODO(mbs): The ReprPrinter version should perhaps switch to this form, however currently\n   * code depends on str() and << being the same.\n   */\n  String ToDebugString() const;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"keys\", &keys);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"features\", &features);\n    v->Visit(\"host\", &host);\n  }\n\n  /*!\n   * \\brief Get an entry from attrs of the target\n   * \\tparam TObjectRef Type of the attribute\n   * \\param attr_key The name of the attribute key\n   * \\param default_value The value returned if the key is not present\n   * \\return An optional, NullOpt if not found, otherwise the value found\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(\n      const std::string& attr_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    static_assert(std::is_base_of<ObjectRef, TObjectRef>::value,\n                  \"Can only call GetAttr with ObjectRef types.\");\n    auto it = attrs.find(attr_key);\n    if (it != attrs.end()) {\n      return Downcast<Optional<TObjectRef>>((*it).second);\n    } else {\n      return default_value;\n    }\n  }\n  /*!\n   * \\brief Get an entry from attrs of the target\n   * \\tparam TObjectRef Type of the attribute\n   * \\param attr_key The name of the attribute key\n   * \\param default_value The value returned if the key is not present\n   * \\return An optional, NullOpt if not found, otherwise the value found\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {\n    return GetAttr<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  /*!\n   * \\brief Get a Target feature\n   *\n   * \\param feature_key The feature key.\n   * \\param default_value The default value if the key does not exist, defaults to nullptr.\n   *\n   * \\return The result\n   *\n   * \\tparam TOBjectRef the expected object type.\n   * \\throw Error if the key exists but the value does not match TObjectRef\n   *\n   * \\code\n   *\n   *  void GetTargetFeature(const Target& target) {\n   *    Bool has_feature = target->GetFeature<Bool>(\"has_feature\", false).value();\n   *  }\n   *\n   * \\endcode\n   */\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetFeature(\n      const std::string& feature_key,\n      Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) const {\n    Optional<TObjectRef> feature = Downcast<Optional<TObjectRef>>(features.Get(feature_key));\n    if (!feature) {\n      return default_value;\n    }\n    return feature;\n  }\n  // variant that uses TObjectRef to enable implicit conversion to default value.\n  template <typename TObjectRef>\n  Optional<TObjectRef> GetFeature(const std::string& attr_key, TObjectRef default_value) const {\n    return GetFeature<TObjectRef>(attr_key, Optional<TObjectRef>(default_value));\n  }\n\n  /*! \\brief Get the keys for this target as a vector of string */\n  TVM_DLL std::vector<std::string> GetKeys() const;\n  /*! \\brief Get the keys for this target as an unordered_set of string */\n  TVM_DLL std::unordered_set<std::string> GetLibs() const;\n\n  bool SEqualReduce(const TargetNode* other, SEqualReducer equal) const;\n  void SHashReduce(SHashReducer hash_reduce) const;\n\n  static constexpr const char* _type_key = \"Target\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(TargetNode, Object);\n\n private:\n  /*! \\brief Internal string repr. */\n  mutable std::string str_repr_;\n\n  friend class TargetInternal;\n};\n\n/*!\n * \\brief Managed reference class to TargetNode.\n * \\sa TargetNode\n */\nclass Target : public ObjectRef {\n public:\n  /*! \\brief Construct a null Target */\n  TVM_DLL explicit Target(std::nullptr_t) { data_ = nullptr; }\n  /*!\n   * \\brief Construct a Target given a string\n   * \\param tag_or_config_or_target_str the string to parse for target\n   */\n  TVM_DLL explicit Target(const String& tag_or_config_or_target_str);\n  /*!\n   * \\brief Construct a Target using a JSON-like configuration\n   * \\param config The JSON-like configuration for target\n   */\n  TVM_DLL explicit Target(const Map<String, ObjectRef>& config);\n  /*!\n   * \\brief Get the current target context from thread local storage.\n   * \\param allow_not_defined If the context stack is empty and this is set to true, an\n   *   undefined Target will be returned. Otherwise, an empty context stack will cause a\n   *   runtime error.\n   * \\return The target that is the current context. The target may not be defined if\n   * allow_not_defined is true.\n   */\n  TVM_DLL static tvm::Target Current(bool allow_not_defined = true);\n  /*!\n   * \\brief Construct a Target given target and host\n   * \\param target The Target typed object with host field undefined for target\n   * \\param host The Target typed object for target host\n   * \\return The Target with given target and host context information\n   */\n  TVM_DLL explicit Target(Target target, Target host);\n  TVM_DEFINE_OBJECT_REF_METHODS(Target, ObjectRef, TargetNode);\n  /*!\n   * \\brief Create a new Target object with given target (w.o host) and target host.\n   * \\param target The current Target typed object target, with or without host field.\n   * \\param host The given Target typed object target host\n   * \\return The new Target object with the given target and host field of given host.\n   */\n  static Target WithHost(const Target& target, const Target& host);\n\n  /*!\n   * \\brief Returns true if \\p this target represents an external codegen. If so,\n   * \\p this->kind->name can be used as the \"Compiler\" attribute on partitioned functions,\n   * and can be used to retrieve a partitioning pattern table using\n   * \\p get_pattern_table.\n   */\n  bool IsExternalCodegen() const;\n\n  /*!\n   * \\brief Returns true if \\p this target represents an external codegen which is compatible\n   * with \\p that target. In particular:\n   *  - \\p this has a true ::tvm::attr::kIsExternalCodegen attribute\n   *  - \\p that does not have a true ::tvm::attr::kIsExternalCodegen attribute\n   *  - \\p this and \\p that have the same GetTargetDeviceType()\n   *\n   * After partitioning, the external codegen compilation path may use \\p that to guide it's\n   * compilation to a \\p runtime::Module. Given \\p this, an appropriate \\p that can be\n   * found using \\p CompilationConfig::FindPrimitiveTargetOrFail(this->GetTargetDeviceType()).\n   *\n   * The \\p CollagePartition pass uses this method to guide it's search over candidate partitions\n   * using external codegen.\n   */\n  bool IsExternalCodegenFor(const Target& that) const;\n\n private:\n  Target(TargetKind kind, Optional<ObjectRef> host, String tag, Array<String> keys,\n         Map<String, ObjectRef> attrs);\n\n  // enable with syntax.\n  friend class TargetInternal;\n  friend class With<Target>;\n  /*!\n   * \\brief Push a new target context onto the thread local stack.\n   *  The Target on top of the stack is used to determine which\n   *  specialization to use when invoking a GenericFunc.\n   */\n  TVM_DLL void EnterWithScope();\n  /*!\n   * \\brief Pop a target off the thread local context stack,\n   *  restoring the previous target as the current context.\n   */\n  TVM_DLL void ExitWithScope();\n};\n\n/*!\n * \\brief Check and update host field of the given legacy target and target host pair.\n *  Note that this function is for legacy target api compatibility issue only, not\n *  recommended for other use.\n * \\param target The pointer to a Target typed object with host field to be updated\n * \\param host The pointer to a Target typed object for target host to be updated\n */\nvoid CheckAndUpdateHostConsistency(Target* target, Target* host);\n\n/*!\n * \\brief Check and update host field of the given legacy heterogeneous targets and\n *  target host.Note that this function is for legacy target api compatibility issue only,\n *  not recommended for other use.\n * \\param ir_modules The pointer to a Map objects with keys being Target objects\n * \\param host The Target typed object for target host to be updated\n */\nvoid CheckAndUpdateHostConsistency(Map<Target, IRModule>* ir_modules, Target* host);\n\n}  // namespace tvm\n#endif  // TVM_TARGET_TARGET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/target_info.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/target_info.h\n * \\brief Various information about target.\n */\n#ifndef TVM_TARGET_TARGET_INFO_H_\n#define TVM_TARGET_TARGET_INFO_H_\n\n#include <tvm/ir/expr.h>\n\n#include <string>\n\nnamespace tvm {\n\n/*!\n * \\brief Memory information of special memory region.\n *  Use MemoryInfo as its container type\n */\nclass MemoryInfoNode : public Object {\n public:\n  /*! \\brief The addressable unit */\n  int64_t unit_bits;\n  /*! \\brief Maximum number of bits supported in the memory */\n  int64_t max_num_bits;\n  /*! \\brief maximum number of bits to be used in simd op */\n  int64_t max_simd_bits;\n  /*!\n   * \\brief head address of the buffer, if visible to CPU\n   *  This address can be None.\n   */\n  PrimExpr head_address;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"unit_bits\", &unit_bits);\n    v->Visit(\"max_num_bits\", &max_num_bits);\n    v->Visit(\"max_simd_bits\", &max_simd_bits);\n    v->Visit(\"head_address\", &head_address);\n  }\n\n  static constexpr const char* _type_key = \"MemoryInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MemoryInfoNode, Object);\n};\n\n/*! \\brief Defines memory info */\nclass MemoryInfo : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(MemoryInfo, ObjectRef, MemoryInfoNode);\n};\n\n/*!\n * \\brief get memory info given scope\n * \\param scope The scope name.\n * \\return info The memory info.\n */\nTVM_DLL MemoryInfo GetMemoryInfo(const std::string& scope);\n\n}  // namespace tvm\n#endif  // TVM_TARGET_TARGET_INFO_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/target_kind.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/target_kind.h\n * \\brief Target kind registry\n */\n#ifndef TVM_TARGET_TARGET_KIND_H_\n#define TVM_TARGET_TARGET_KIND_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/node/node.h>\n\n#include <memory>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\nclass Target;\n\n/*!\n * \\brief Map containing parsed features of a specific Target\n */\nusing TargetFeatures = Map<String, ObjectRef>;\n\n/*!\n * \\brief TargetParser to apply on instantiation of a given TargetKind\n *\n * \\param target_json Target in JSON format to be transformed during parsing.\n *\n * \\return The transformed Target JSON object.\n */\nusing TargetJSON = Map<String, ObjectRef>;\nusing FTVMTargetParser = TypedPackedFunc<TargetJSON(TargetJSON)>;\n\n/*!\n * \\brief RelayToTIR tvm::transform::Pass specific to a TargetKind\n *\n * Called before the default lowering passes.\n *\n * \\param mod The module that an optimization pass runs on.\n * \\param pass_ctx The pass context that can provide information for the optimization.\n *\n * \\return The transformed module.\n */\nusing FTVMRelayToTIR = transform::Pass;\n\n/*!\n * \\brief TIRToRuntime conversion specific to a TargetKind\n *\n * This function is responsible for scanning an IRModule for appropriate Target-specific functions\n and generating a Runtime module representing the compiled output\n *\n * \\param ir_module Unified IRModule\n * \\param target Target to filter on or retrieve arguments from\n * \\return Runtime Module containing compiled functions\n */\nusing FTVMTIRToRuntime = runtime::TypedPackedFunc<runtime::Module(IRModule, Target)>;\n\nnamespace detail {\ntemplate <typename, typename, typename>\nstruct ValueTypeInfoMaker;\n}\n\nclass TargetInternal;\n\ntemplate <typename>\nclass TargetKindAttrMap;\n\n/*! \\brief Target kind, specifies the kind of the target */\nclass TargetKindNode : public Object {\n public:\n  /*! \\brief Name of the target kind */\n  String name;\n  /*! \\brief Device type of target kind */\n  int default_device_type;\n  /*! \\brief Default keys of the target */\n  Array<String> default_keys;\n  /*! \\brief Function used to preprocess on target creation */\n  PackedFunc preprocessor;\n  /*! \\brief Function used to parse a JSON target during creation */\n  FTVMTargetParser target_parser;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"default_device_type\", &default_device_type);\n    v->Visit(\"default_keys\", &default_keys);\n  }\n\n  static constexpr const char* _type_key = \"TargetKind\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TargetKindNode, Object);\n\n private:\n  /*! \\brief Return the index stored in attr registry */\n  uint32_t AttrRegistryIndex() const { return index_; }\n  /*! \\brief Return the name stored in attr registry */\n  String AttrRegistryName() const { return name; }\n  /*! \\brief Stores the required type_key and type_index of a specific attr of a target */\n  struct ValueTypeInfo {\n    String type_key;\n    uint32_t type_index;\n    std::unique_ptr<ValueTypeInfo> key;\n    std::unique_ptr<ValueTypeInfo> val;\n  };\n  /*! \\brief A hash table that stores the type information of each attr of the target key */\n  std::unordered_map<String, ValueTypeInfo> key2vtype_;\n  /*! \\brief A hash table that stores the default value of each attr of the target key */\n  std::unordered_map<String, ObjectRef> key2default_;\n  /*! \\brief Index used for internal lookup of attribute registry */\n  uint32_t index_;\n\n  template <typename, typename, typename>\n  friend struct detail::ValueTypeInfoMaker;\n  template <typename, typename>\n  friend class AttrRegistry;\n  template <typename>\n  friend class AttrRegistryMapContainerMap;\n  friend class TargetKindRegEntry;\n  friend class TargetInternal;\n};\n\n/*!\n * \\brief Managed reference class to TargetKindNode\n * \\sa TargetKindNode\n */\nclass TargetKind : public ObjectRef {\n public:\n  TargetKind() = default;\n  /*! \\brief Get the attribute map given the attribute name */\n  template <typename ValueType>\n  static inline TargetKindAttrMap<ValueType> GetAttrMap(const String& attr_name);\n  /*!\n   * \\brief Retrieve the TargetKind given its name\n   * \\param target_kind_name Name of the target kind\n   * \\return The TargetKind requested\n   */\n  TVM_DLL static Optional<TargetKind> Get(const String& target_kind_name);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TargetKind, ObjectRef, TargetKindNode);\n\n private:\n  /*! \\brief Mutable access to the container class  */\n  TargetKindNode* operator->() { return static_cast<TargetKindNode*>(data_.get()); }\n  TVM_DLL static const AttrRegistryMapContainerMap<TargetKind>& GetAttrMapContainer(\n      const String& attr_name);\n  friend class TargetKindRegEntry;\n  friend class TargetInternal;\n};\n\n/*!\n * \\brief Map<TargetKind, ValueType> used to store meta-information about TargetKind\n * \\tparam ValueType The type of the value stored in map\n */\ntemplate <typename ValueType>\nclass TargetKindAttrMap : public AttrRegistryMap<TargetKind, ValueType> {\n public:\n  using TParent = AttrRegistryMap<TargetKind, ValueType>;\n  using TParent::count;\n  using TParent::get;\n  using TParent::operator[];\n  explicit TargetKindAttrMap(const AttrRegistryMapContainerMap<TargetKind>& map) : TParent(map) {}\n};\n\n/*! \\brief Value used with --runtime in target specs to indicate the C++ runtime. */\nstatic constexpr const char* kTvmRuntimeCpp = \"c++\";\n\n/*! \\brief Value used with --runtime in target specs to indicate the C runtime. */\nstatic constexpr const char* kTvmRuntimeCrt = \"c\";\n\n/*!\n * \\brief Helper structure to register TargetKind\n * \\sa TVM_REGISTER_TARGET_KIND\n */\nclass TargetKindRegEntry {\n public:\n  /*!\n   * \\brief Register additional attributes to target_kind.\n   * \\param attr_name The name of the attribute.\n   * \\param value The value to be set.\n   * \\param plevel The priority level of this attribute,\n   *  an higher priority level attribute\n   *  will replace lower priority level attribute.\n   *  Must be bigger than 0.\n   *\n   *  Cannot set with same plevel twice in the code.\n   *\n   * \\tparam ValueType The type of the value to be set.\n   */\n  template <typename ValueType>\n  inline TargetKindRegEntry& set_attr(const String& attr_name, const ValueType& value,\n                                      int plevel = 10);\n  /*!\n   * \\brief Set DLPack's device_type the target\n   * \\param device_type Device type\n   */\n  inline TargetKindRegEntry& set_default_device_type(int device_type);\n  /*!\n   * \\brief Set DLPack's device_type the target\n   * \\param keys The default keys\n   */\n  inline TargetKindRegEntry& set_default_keys(std::vector<String> keys);\n  /*!\n   * \\brief Set the pre-processing function applied upon target creation\n   * \\tparam FLambda Type of the function\n   * \\param f The pre-processing function\n   */\n  template <typename FLambda>\n  inline TargetKindRegEntry& set_attrs_preprocessor(FLambda f);\n  /*!\n   * \\brief Set the parsing function applied upon target creation\n   * \\param parser The Target parsing function\n   */\n  inline TargetKindRegEntry& set_target_parser(FTVMTargetParser parser);\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline TargetKindRegEntry& add_attr_option(const String& key);\n  /*!\n   * \\brief Register a valid configuration option and its ValueType for validation\n   * \\param key The configuration key\n   * \\param default_value The default value of the key\n   * \\tparam ValueType The value type to be registered\n   */\n  template <typename ValueType>\n  inline TargetKindRegEntry& add_attr_option(const String& key, ObjectRef default_value);\n  /*! \\brief Set name of the TargetKind to be the same as registry if it is empty */\n  inline TargetKindRegEntry& set_name();\n  /*!\n   * \\brief List all the entry names in the registry.\n   * \\return The entry names.\n   */\n  TVM_DLL static Array<String> ListTargetKinds();\n  /*!\n   * \\brief Get all supported option names and types for a given Target kind.\n   * \\return Map of option name to type\n   */\n  TVM_DLL static Map<String, String> ListTargetKindOptions(const TargetKind& kind);\n\n  /*!\n   * \\brief Register or get a new entry.\n   * \\param target_kind_name The name of the TargetKind.\n   * \\return the corresponding entry.\n   */\n  TVM_DLL static TargetKindRegEntry& RegisterOrGet(const String& target_kind_name);\n\n private:\n  TargetKind kind_;\n  String name;\n\n  /*! \\brief private constructor */\n  explicit TargetKindRegEntry(uint32_t reg_index) : kind_(make_object<TargetKindNode>()) {\n    kind_->index_ = reg_index;\n  }\n  /*!\n   * \\brief update the attribute TargetKindAttrMap\n   * \\param key The name of the attribute\n   * \\param value The value to be set\n   * \\param plevel The priority level\n   */\n  TVM_DLL void UpdateAttr(const String& key, TVMRetValue value, int plevel);\n  template <typename, typename>\n  friend class AttrRegistry;\n  friend class TargetKind;\n};\n\nnamespace detail {\ntemplate <typename Type, template <typename...> class Container>\nstruct is_specialized : std::false_type {\n  using type = std::false_type;\n};\n\ntemplate <template <typename...> class Container, typename... Args>\nstruct is_specialized<Container<Args...>, Container> : std::true_type {\n  using type = std::true_type;\n};\n\ntemplate <typename ValueType, typename IsArray = typename is_specialized<ValueType, Array>::type,\n          typename IsMap = typename is_specialized<ValueType, Map>::type>\nstruct ValueTypeInfoMaker {};\n\ntemplate <typename ValueType>\nstruct ValueTypeInfoMaker<ValueType, std::false_type, std::false_type> {\n  using ValueTypeInfo = TargetKindNode::ValueTypeInfo;\n\n  ValueTypeInfo operator()() const {\n    uint32_t tindex = ValueType::ContainerType::_GetOrAllocRuntimeTypeIndex();\n    ValueTypeInfo info;\n    info.type_index = tindex;\n    info.type_key = runtime::Object::TypeIndex2Key(tindex);\n    info.key = nullptr;\n    info.val = nullptr;\n    return info;\n  }\n};\n\ntemplate <typename ValueType>\nstruct ValueTypeInfoMaker<ValueType, std::true_type, std::false_type> {\n  using ValueTypeInfo = TargetKindNode::ValueTypeInfo;\n\n  ValueTypeInfo operator()() const {\n    using key_type = ValueTypeInfoMaker<typename ValueType::value_type>;\n    uint32_t tindex = ValueType::ContainerType::_GetOrAllocRuntimeTypeIndex();\n    ValueTypeInfo info;\n    info.type_index = tindex;\n    info.type_key = runtime::Object::TypeIndex2Key(tindex);\n    info.key = std::make_unique<ValueTypeInfo>(key_type()());\n    info.val = nullptr;\n    return info;\n  }\n};\n\ntemplate <typename ValueType>\nstruct ValueTypeInfoMaker<ValueType, std::false_type, std::true_type> {\n  using ValueTypeInfo = TargetKindNode::ValueTypeInfo;\n  ValueTypeInfo operator()() const {\n    using key_type = ValueTypeInfoMaker<typename ValueType::key_type>;\n    using val_type = ValueTypeInfoMaker<typename ValueType::mapped_type>;\n    uint32_t tindex = ValueType::ContainerType::_GetOrAllocRuntimeTypeIndex();\n    ValueTypeInfo info;\n    info.type_index = tindex;\n    info.type_key = runtime::Object::TypeIndex2Key(tindex);\n    info.key = std::make_unique<ValueTypeInfo>(key_type()());\n    info.val = std::make_unique<ValueTypeInfo>(val_type()());\n    return info;\n  }\n};\n\n}  // namespace detail\n\ntemplate <typename ValueType>\ninline TargetKindAttrMap<ValueType> TargetKind::GetAttrMap(const String& attr_name) {\n  return TargetKindAttrMap<ValueType>(GetAttrMapContainer(attr_name));\n}\n\ntemplate <typename ValueType>\ninline TargetKindRegEntry& TargetKindRegEntry::set_attr(const String& attr_name,\n                                                        const ValueType& value, int plevel) {\n  ICHECK_GT(plevel, 0) << \"plevel in set_attr must be greater than 0\";\n  runtime::TVMRetValue rv;\n  rv = value;\n  UpdateAttr(attr_name, rv, plevel);\n  return *this;\n}\n\ninline TargetKindRegEntry& TargetKindRegEntry::set_default_device_type(int device_type) {\n  kind_->default_device_type = device_type;\n  return *this;\n}\n\ninline TargetKindRegEntry& TargetKindRegEntry::set_default_keys(std::vector<String> keys) {\n  kind_->default_keys = keys;\n  return *this;\n}\n\ntemplate <typename FLambda>\ninline TargetKindRegEntry& TargetKindRegEntry::set_attrs_preprocessor(FLambda f) {\n  LOG(WARNING) << \"set_attrs_preprocessor is deprecated please use set_target_parser instead\";\n  using FType = typename tvm::runtime::detail::function_signature<FLambda>::FType;\n  kind_->preprocessor = tvm::runtime::TypedPackedFunc<FType>(std::move(f)).packed();\n  return *this;\n}\n\ninline TargetKindRegEntry& TargetKindRegEntry::set_target_parser(FTVMTargetParser parser) {\n  kind_->target_parser = parser;\n  return *this;\n}\n\ntemplate <typename ValueType>\ninline TargetKindRegEntry& TargetKindRegEntry::add_attr_option(const String& key) {\n  ICHECK(!kind_->key2vtype_.count(key))\n      << \"AttributeError: add_attr_option failed because '\" << key << \"' has been set once\";\n  kind_->key2vtype_[key] = detail::ValueTypeInfoMaker<ValueType>()();\n  return *this;\n}\n\ntemplate <typename ValueType>\ninline TargetKindRegEntry& TargetKindRegEntry::add_attr_option(const String& key,\n                                                               ObjectRef default_value) {\n  add_attr_option<ValueType>(key);\n  kind_->key2default_[key] = default_value;\n  return *this;\n}\n\ninline TargetKindRegEntry& TargetKindRegEntry::set_name() {\n  if (kind_->name.empty()) {\n    kind_->name = name;\n  }\n  return *this;\n}\n\n#define TVM_TARGET_KIND_REGISTER_VAR_DEF \\\n  static DMLC_ATTRIBUTE_UNUSED ::tvm::TargetKindRegEntry& __make_##TargetKind\n\nnamespace attr {\n//\n// Distinguished TargetKind attribute names.\n//\n\n/*!\n * \\brief A \\p TargetKind attribute of type \\p Bool. If true, then the target kind name also\n * corresponds to an external codegen 'compiler' name. That name may be used:\n *  - To retrieve partitioning rules using \\p get_partition_table.\n *  - To attach to Relay Functions under the \\p attr::kCompiler attribute to indicate\n *    the function is to be compiled by the external codegen path.\n *\n * The \\p CollagePartition pass uses this attribute to guide it's search over candidate partitions\n * using external codegen.\n *\n * See also \\p Target::IsExternalCodegenFor\n */\nconstexpr const char* kIsExternalCodegen = \"is_external_codegen\";\n\n/*!\n * \\brief A \\p TargetKind attribute of type \\p FTVMRelayToTIR. If set, then the target kind name\n * also corresponds to an external codegen 'compiler' name, and the bound value is a \\p Pass\n * to apply before the TVM lowering.\n *\n * See also \\p Target::IsExternalCodegenFor\n */\nconstexpr const char* kRelayToTIR = \"RelayToTIR\";\n\n}  // namespace attr\n\n/*!\n * \\def TVM_REGISTER_TARGET_KIND\n * \\brief Register a new target kind, or set attribute of the corresponding target kind.\n *\n * \\param TargetKindName The name of target kind\n * \\param DeviceType The DLDeviceType of the target kind\n *\n * \\code\n *\n *  TVM_REGISTER_TARGET_KIND(\"llvm\")\n *  .set_attr<TPreCodegenPass>(\"TPreCodegenPass\", a-pre-codegen-pass)\n *  .add_attr_option<Bool>(\"system_lib\")\n *  .add_attr_option<String>(\"mtriple\")\n *  .add_attr_option<String>(\"mattr\");\n *\n * \\endcode\n */\n#define TVM_REGISTER_TARGET_KIND(TargetKindName, DeviceType)      \\\n  TVM_STR_CONCAT(TVM_TARGET_KIND_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::TargetKindRegEntry::RegisterOrGet(TargetKindName)    \\\n          .set_name()                                             \\\n          .set_default_device_type(DeviceType)                    \\\n          .add_attr_option<Array<String>>(\"keys\")                 \\\n          .add_attr_option<String>(\"tag\")                         \\\n          .add_attr_option<String>(\"device\")                      \\\n          .add_attr_option<String>(\"model\")                       \\\n          .add_attr_option<Array<String>>(\"libs\")                 \\\n          .add_attr_option<Target>(\"host\")                        \\\n          .add_attr_option<Integer>(\"from_device\")                \\\n          .add_attr_option<Integer>(\"target_device_type\")\n\n}  // namespace tvm\n\n#endif  // TVM_TARGET_TARGET_KIND_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/target/virtual_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/virtual_device.h\n * \\brief A compile time representation for where data is to be stored at runtime, and how to\n * compile code to compute it.\n */\n\n#ifndef TVM_TARGET_VIRTUAL_DEVICE_H_\n#define TVM_TARGET_VIRTUAL_DEVICE_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/target/target.h>\n\n#include <string>\n#include <unordered_set>\n#include <utility>\n\nnamespace tvm {\n\n/*!\n * Abstract label for an area of memory.\n *\n * Currently uninterpreted and arbitrary. Likely to be replaced by a structured representation\n * of a memory pool in the future. Please try to use this alias instead of String to aid future\n * code migration.\n */\nusing MemoryScope = String;\n\n/*!\n * \\brief Describes at compile time the constraints on where data is to be stored at runtime\n * down to the (virtual) device and memory scope level, and how to compile code to compute that\n * data. Used by the \\p PlanDevices pass to collect and solve (virtual) device constraints for\n * the whole Relay program.\n *\n * Is a quadruple of:\n * - A \\p device_type (\\p DLDeviceType). May be \\p kInvalidDeviceType if unconstrained.\n * - A \\p virtual_device_id (\\p int). This allows us to distinguish distinct devices\n *   with the same \\p Target, for example in a multi-GPU system. May be -1 if unconstrained.\n *   See \"Virtual Devices\" below.\n * - A \\p target (\\p Target) describing how to compile code for the intended device. May be null\n *   if unconstrained.\n * - A \\p memory_scope (\\p MemoryScope, which is currently just \\p String) describing which memory\n *   area is to be used to hold data. May be \"\" if unconstrained. See \"Memory Scopes and Devices\"\n *   below.\n *\n * Some or all of these fields may be unconstrained, signaling that device planning is free to\n * choose a value consistent with the whole program. However if a \\p target is given then the \\p\n * device_type must equal \\p target->GetTargetDeviceType().\n *\n * Note that currently we assume if a function returns its result on a particular (virtual) device\n * then the function body is also executed on that device. See the overview comment in\n * src/relay/transforms/device_planner.cc for more details.\n *\n * By 'data' we include both tensors and additional supporting datastructures such as shapes,\n * Relay ADT items (including tuples), Relay references, and Relay closures. Typically non-tensor\n * data must reside on a 'CPU'-like host device with good support for scalars.\n *\n * By 'execution' we include both (fused) primitive operators, and all the Relay expressions\n * surrounding them which coordinates data and control flow. Again, typically non-primitive\n * operators must be executed on a 'CPU'-like device with good support for control flow.\n *\n * Since TVM targets such a wide range of systems it is not possible for \\p VirtualDevice to impose\n * much semantics on these fields, particularly for \\p virtual_device_id and \\p memory_scope.\n * Instead we assume downstream passes and codegen will interpret an validate these fields\n * appropriately.\n *\n * Targets vs Devices\n * ------------------\n * Generally \\p Targets (a compile-time only datastructue) describe compiler options for a specific\n * microarchitecture and toolchain, while \\p Devices (a runtime datastructure also available at\n * compile time) describe a physical device on the target system. Obviously the target must agree\n * with the device's microarchitecture, but we otherwise don't impose any constraints between them:\n *  - It's ok to use different \\p Targets for the same \\p Device, eg to squeeze some extra perf\n *    out of a particular primitive using particular compiler flags.\n *  - It's ok to use the same \\p Target for multiple \\p Devices, eg if we have multiple CPUs.\n *\n * Traditionally TVM assumes at most one \\p Target per \\p DLDeviceType. We are moving away from that\n * assumption.\n *\n * Virtual vs Physical Devices\n * ---------------------------\n * The \\p virtual_device_id may be used by downstream passes or the runtime to help decide which\n * \\p device_id to use for a particular physical runtime \\p Device. For example:\n *  - Some runtimes may support passing in an array of actual `device` specifications, and the\n *    \\p virtual_device_id can be used at runtime as an index into that array.\n *  - Some runtimes may support dynamically allocating computations to physical devices. On these\n *    systems a large space of \\p virtual_device_ids could be used at compile time, even though\n *    at runtime only a few physical devices will be present.\n *\n * The \\p virtual_device_id may also be left unconstrained if not needed.\n *\n * Memory Scopes and Devices\n * -------------------------\n * Multi-device systems can have complex memory hierarchies. For example\n * \\code\n * (kDLCPU, 0, \"llvm\", \"global\")\n * \\endcode\n * and\n * \\code\n * (kDLCPU, 1, \"llvm\", \"global\")\n * \\endcode\n * could denote:\n * - The same memory area accessible from two separate CPUs without any CPU affinity;\n * - Distinct memory areas in a NUMA architecture for which cross-device access is handled\n *   by the memory system;\n * - Outright distinct memory areas, where one device cannot directly address the memory of\n *   another.\n *\n * Similarly:\n * \\code\n * (kDLCPU, 0, \"llvm\", \"global\")\n * \\endcode\n * and\n * \\code\n * (kDLCUDA, 0, \"cuda\", \"host\")\n * \\endcode\n * could denote the same memory area, but with very different access costs.\n *\n * Furthermore, not all memory scopes are accessible to all devices, and it is possible for\n * a memory scope to only be accessible to a device when code is compiled with particular\n * \\p Target options.\n *\n * \\p VirtualDevices themselves have no system-level understanding. Currently the \\p PlanDevices\n * pass will simply insert \"device_copy\" operators wherever \\p VirtualDevices are not exactly\n * pointwise equal. We may revisit this in the future as the work on memory pools matures.\n *\n * Joining and Defaulting\n * ----------------------\n * It is possible to 'join' two \\p VirtualDevices to yield the most constrained \\p VirtualDevice\n * which agrees with both join arguments. Eg:\n * \\code\n * Join((kDLCPU, -1, \"llvm\", \"\"), (kInvalidDeviceType, 3, null, \"global))\n *   => (kDLCPU, 3, \"llvm\", \"global\")\n * Join((kDLCPU, -1, \"llvm\", \"\"), (kInvalidDeviceType, 3, null, \"local))\n *   => null (no join possible)\n * \\endcode\n *\n * Related to 'join' is 'default', which only takes constrained fields from the rhs when the\n * lhs is unconstrained:\n * \\code\n * Default(kDLCPU, -1, \"llvm\", \"local\"), (kDLCPU, 3, null, \"global\"))\n *   => (kDLCPU, 3, \"llvm\", \"local\")\n * \\endcode\n *\n * These operations are needed during device planning.\n */\n\nclass VirtualDeviceNode : public AttrsNode<VirtualDeviceNode> {\n private:\n  /*!\n   * \\brief The \\p DLDeviceType (represented as an int) of the virtual device. If \\p target is\n   * known then this will be equal to \\p target->GetTargetDeviceType(). If \\p target is null then\n   * the target is to be determined later.\n   *\n   * This is needed to support the legacy \"on_device\" and \"device_copy\" calls which only allow\n   * a \\p DLDeviceTypes (as an integer) to be given.\n   *\n   * kInvalidDeviceType denotes unconstrained. An int since the DLDeviceType enum representation\n   * is not fixed. Private to discourage further int vs DLDeviceType confusion.\n   */\n  int /* actually DLDeviceType */ device_type_int;\n\n public:\n  DLDeviceType device_type() const { return static_cast<DLDeviceType>(device_type_int); }\n\n  /*!\n   * \\brief The device identifier for the virtual device. This must be resolved to a physical\n   * device identifier either during compilation or at runtime.\n   *\n   * -1 denotes unconstrained.\n   */\n  int virtual_device_id;\n\n  /*!\n   * \\brief The \\p Target describing how to compile for the virtual device.\n   *\n   * Null denotes unconstrained. Note that if a target later becomes known for this \\p VirtualDevice\n   * then it must be consistent with the \\p device_type if already known. This is enforced by the\n   * Join and Default methods.\n   */\n  Target target;\n\n  /*!\n   * \\brief The scope of memory w.r.t. the virtual device which holds data.\n   *\n   * Empty denotes unconstrained.\n   */\n  MemoryScope memory_scope;\n\n  /*!\n   * \\brief Returns true if virtual device is 'fully unconstrained', ie no target/device type,\n   * device id or memory scope is specified.\n   */\n  bool IsFullyUnconstrained() const {\n    return !target.defined() && device_type() == kInvalidDeviceType && virtual_device_id == -1 &&\n           memory_scope.empty();\n  }\n\n  /*!\n   * \\brief Returns true if virtual device is 'fully constrained', ie target, device id and memory\n   * scope are all specified.\n   */\n  bool IsFullyConstrained() const {\n    return target.defined() && virtual_device_id != -1 && !memory_scope.empty();\n  }\n\n  /*!\n   * \\brief Returns the (virtual) \\p Device implied by this \\p VirtualDevice. Both the \\p\n   * device_type and \\p virtual_device_must be constrained. The returned \\p Device may not\n   * correspond to any physical device available at compile time or even runtime: see \"Virtual vs\n   * Physical Devices\" above.\n   */\n  Device ToDevice() const {\n    ICHECK(device_type() != kInvalidDeviceType);\n    ICHECK(virtual_device_id != -1);\n    Device device;\n    device.device_type = device_type();\n    device.device_id = virtual_device_id;\n    return device;\n  }\n\n  TVM_DECLARE_ATTRS(VirtualDeviceNode, \"VirtualDevice\") {\n    TVM_ATTR_FIELD(device_type_int)\n        .describe(\"The type of the virtual device.\")\n        .set_default(kInvalidDeviceType);\n    TVM_ATTR_FIELD(virtual_device_id)\n        .describe(\"The device id of the virtual device.\")\n        .set_default(-1);\n    TVM_ATTR_FIELD(target)\n        .describe(\"The target describing how to compile for the virtual device.\")\n        .set_default(Target());\n    TVM_ATTR_FIELD(memory_scope)\n        .describe(\"The area of memory w.r.t. the virtual device where data is stored.\")\n        .set_default(\"\");\n  }\n\n  friend class VirtualDevice;\n};\n\n/*!\n * \\brief Managed reference class to \\p VirtualDeviceNode.\n */\nclass VirtualDevice : public ObjectRef {\n public:\n  /*!\n   * \\brief Construct a virtual device.\n   * \\param device_type The device type for the virtual device, or \\p kInvalidDeviceType if\n   * unconstrained.  If \\p target is defined then must match its \\p target->GetTargetDeviceType().\n   * \\param virtual_device_id The device id for the virtual device, or -1 if unconstrained.\n   * \\param target The target describing how to compile for the virtual device, or null if\n   * unconstrained.\n   * \\param memory_scope The memory scope w.r.t. the virtual device which holds data, or \"\" if\n   * unconstrained.\n   * \\return The virtual device.\n   */\n  explicit VirtualDevice(DLDeviceType device_type = kInvalidDeviceType, int virtual_device_id = -1,\n                         Target target = {}, MemoryScope memory_scope = {});\n\n  /*! \\brief Returns the unique fully unconstrained \\p VirtualDevice. */\n  static VirtualDevice FullyUnconstrained();\n\n  /*!\n   * \\brief Returns the \\p VirtualDevice for \\p device_type and (if not -1) \\p virtual_device_id.\n   * The target and memory scope will be unconstrained.\n   */\n  static VirtualDevice ForDeviceType(DLDeviceType device_type, int virtual_device_id = -1) {\n    ICHECK_GT(device_type, 0);\n    return VirtualDevice(device_type, virtual_device_id);\n  }\n  static VirtualDevice ForDeviceType(int device_type, int virtual_device_id = -1) {\n    return ForDeviceType(static_cast<DLDeviceType>(device_type), virtual_device_id);\n  }\n  static VirtualDevice ForDeviceType(const Integer& device_type, int virtual_device_id = -1) {\n    return ForDeviceType(static_cast<int>(device_type->value), virtual_device_id);\n  }\n\n  /*! \\brief Returns the \\p VirtualDevice for \\p device. */\n  static VirtualDevice ForDevice(const Device& device) {\n    return ForDeviceType(device.device_type, device.device_id);\n  }\n\n  /*! \\brief Returns the \\p VirtualDevice for \\p device and \\p target. */\n  static VirtualDevice ForDeviceAndTarget(const Device& device, Target target) {\n    return VirtualDevice(device.device_type, device.device_id, std::move(target));\n  }\n\n  /*! \\brief Returns the \\p VirtualDevice for \\p target. */\n  static VirtualDevice ForTarget(Target target) {\n    DLDeviceType device_type = static_cast<DLDeviceType>(target->GetTargetDeviceType());\n    return VirtualDevice(device_type, /*virtual_device_id=*/0, std::move(target));\n  }\n\n  /*! \\brief Returns the \\p VirtualDevice for \\p memory_scope alone. */\n  static VirtualDevice ForMemoryScope(MemoryScope memory_scope) {\n    return VirtualDevice(kInvalidDeviceType, -1, {}, std::move(memory_scope));\n  }\n\n  /*! \\brief Returns the \\p VirtualDevice for \\p device, \\p target and \\p memory_scope. */\n  TVM_DLL static VirtualDevice ForDeviceTargetAndMemoryScope(const Device& device, Target target,\n                                                             MemoryScope memory_scope) {\n    return VirtualDevice(device.device_type, device.device_id, std::move(target),\n                         std::move(memory_scope));\n  }\n\n  /*!\n   * \\brief Returns the 'join' of \\p lhs and \\p rhs. The result will agree pointwise with\n   * \\p lhs and \\p rhs on all their constrained fields. Returns the null optional if no such\n   * join exists, ie there's disagreement on at least one constrained field.\n   */\n  static Optional<VirtualDevice> Join(const VirtualDevice& lhs, const VirtualDevice& rhs);\n\n  /*!\n   * \\brief Returns the 'default' of \\p lhs and \\p rhs. The result will be \\p lhs, except any\n   * unconstrained fields in \\p lhs will take their value from \\p rhs. Always well-defined.\n   */\n  static VirtualDevice Default(const VirtualDevice& lhs, const VirtualDevice& rhs);\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(VirtualDevice, ObjectRef, VirtualDeviceNode);\n\n  friend class VirtualDeviceCache;  // Private implementation helper.\n};\n\n/*!\n * \\brief A cache of \\p VirtualDevices. This can be used:\n *  - To avoid ending up with lots of identical instances, since the space of VirtualDevices for any\n *    one compilation is very small but the number of points they need to be constructed can\n *    be very large (eg during device planning).\n *  - So we can assume \\p VirtualDevices are pointer equal if and only if they are structurally\n * equal. This simplifies the unification of 'device domains' which are built on \\p VirtualDevices.\n */\nclass VirtualDeviceCache {\n public:\n  /*! \\brief Returns the unique \\p VirtualDevice representing given fields. */\n  VirtualDevice Make(DLDeviceType device_type = kInvalidDeviceType, int virtual_device_id = -1,\n                     Target target = {}, MemoryScope memory_scope = {});\n\n  /*!\n   * \\brief Returns the unique \\p VirtualDevice structurally equal to the given \\p virtual_device.\n   */\n  VirtualDevice Unique(const VirtualDevice& virtual_device);\n\n private:\n  /*! \\brief Already constructed VirtualDevices. */\n  std::unordered_set<VirtualDevice, StructuralHash, StructuralEqual> cache_;\n};\n\n/*! brief The attribute key for the virtual device. This key will be promoted to first class on\n * functions. For use in the parser and printer only.\n *\n * Type: VirtualDevice\n */\nconstexpr const char* kVirtualDevice = \"virtual_device\";\n\n}  // namespace tvm\n\n#endif  //  TVM_TARGET_VIRTUAL_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/autodiff.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/autodiff.h\n * \\brief Automatic differentiation of tensor expressions.\n */\n\n#ifndef TVM_TE_AUTODIFF_H_\n#define TVM_TE_AUTODIFF_H_\n\n#include <tvm/runtime/object.h>\n#include <tvm/tir/expr.h>\n\n#include \"tensor.h\"\n\nnamespace tvm {\n/*! \\brief Tensor expression language DSL. */\nnamespace te {\n\n/*!\n * \\brief Take the derivative of the expression with respect to the given variable.\n * \\param expr The expression to differentiate.\n * \\param var The variable to differentiate with respect to.\n * \\return The expression for the derivative.\n */\nPrimExpr Derivative(const PrimExpr& expr, const Var& var);\n\n/*!\n * \\brief Get the tensor representing the Jacobian of the output with respect to the input.\n *\n *  Note that if \\p output depends on \\p input indirectly (by using some other tensor\n *  depending on \\p input), this dependency won't contribute to the resulting Jacobian.\n *  For such cases use the function ::Gradient.\n *\n * \\param output The tensor to differentiate.\n * \\param input The input tensor, which \\p output should directly use.\n * \\return The tensor representing the Jacobian of shape `output.shape + input.shape`.\n */\nTensor Jacobian(const Tensor& output, const Tensor& input);\n\n/*!\n * \\brief The building block for reverse-mode AD.\n *\n *  Differentiate \\p output wrt \\p input and multiply the result by \\p head on the left using tensor\n *  dot product. \\p input must be an immediate dependency of \\p output (must be called from within\n *  the body of \\p output). That is, the function will compute one summand of the adjoint for \\p\n * input given the adjoint for \\p output (which is called \\p head here).\n *\n * \\param output The tensor to differentiate.\n * \\param input The input tensor, which \\p output should directly use.\n * \\param head The adjoint of \\p output. Must be of shape `prefix + output.shape`\n * \\return The tensor of shape `prefix + input.shape`\n *         representing the partial adjoint of \\p input wrt one of its consumers (output)\n */\nTensor VectorJacobianProduct(const Tensor& output, const Tensor& input, const Tensor& head);\n\n/*!\n * \\brief Perform reverse mode automatic differentiation.\n *\n *  Each item of the `result` field of the result is an adjoint for the corresponding item of\n *  \\p inputs, i.e. \\p head multiplied by the Jacobian of \\p output with respect to the\n *  corresponding item of \\p inputs.\n *\n * \\param output The tensor to differentiate.\n * \\param inputs The array of input tensors. When the array is empty, will perform differentiation\n *               wrt all tensors the output depends on.\n * \\param head The adjoint of the output, in other words, some tensor, by which the Jacobians\n *             will be multiplied (using tensordot axes=`output.shape`).\n *             Its shape must be of the form `prefix + output.shape`. If the null pointer is\n * provided, the identity tensor of shape `output.shape + output.shape` will be used. \\return An\n * array of adjoints corresponding to \\p inputs.\n */\nTVM_DLL Array<Tensor> Gradient(const Tensor& output, const Array<Tensor>& inputs,\n                               const Tensor& head = Tensor());\n\n}  // namespace te\n}  // namespace tvm\n\n#endif  // TVM_TE_AUTODIFF_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/operation.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/operation.h\n * \\brief Operation node can generate one or multiple Tensors\n */\n#ifndef TVM_TE_OPERATION_H_\n#define TVM_TE_OPERATION_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/schedule.h>\n#include <tvm/te/tensor.h>\n#include <tvm/tir/buffer.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\n/*! \\brief Tensor expression language DSL. */\nnamespace te {\n\n/*!\n * \\brief Temporary data structure to store union\n *  of bounds of each axis of Tensor.\n */\nstruct TensorDom {\n  // constructor\n  explicit TensorDom(int ndim) : data(ndim) {}\n  /*! \\brief The domain data */\n  std::vector<std::vector<IntSet>> data;\n};\n\n/*!\n * \\brief Base class of all operation nodes\n */\nclass TVM_DLL OperationNode : public Object {\n public:\n  /*! \\brief optional name of the operation */\n  std::string name;\n  /*! \\brief optional tag of the operation */\n  std::string tag;\n  /*! \\brief additional attributes of the operation*/\n  Map<String, ObjectRef> attrs;\n  // virtual destructor.\n  virtual ~OperationNode() {}\n  /*! \\return number of outputs */\n  virtual int num_outputs() const = 0;\n  /*!\n   * \\return The list of iteration variable at root\n   * \\note root_iter_vars decides the shape of the outputs.\n   */\n  virtual Array<IterVar> root_iter_vars() const = 0;\n  /*!\n   * \\brief Get data type. i-th output tensor.\n   * \\param i The output index.\n   * \\return type of i-th output.\n   */\n  virtual DataType output_dtype(size_t i) const = 0;\n  /*!\n   * \\brief Get shape of i-th output tensor.\n   * \\param i The output index.\n   * \\return shape of i-th output.\n   */\n  virtual Array<PrimExpr> output_shape(size_t i) const = 0;\n  /*!\n   * \\brief List all the input Tensors.\n   * \\return List of input tensors.\n   */\n  virtual Array<Tensor> InputTensors() const = 0;\n  /*!\n   * \\brief Replace the input of the operation by pattern specified by rmap.\n   *\n   * \\param self The reference to self.\n   * \\param rmap The replacement map.\n   * \\return self if nothing is replaced, otherwise return replaced op.\n   */\n  virtual Operation ReplaceInputs(const Operation& self,\n                                  const std::unordered_map<Tensor, Tensor>& rmap) const = 0;\n  /*!\n   * \\brief Propagate the bounds to inputs\n   * \\param self The reference to self.\n   * \\param analyzer The analyzer to be used in the function.\n   * \\param dom_map the domain map of Variables(corresponds to root_iter_vars)\n   * \\param out_dom_map The output domain.\n   *  The function is only asked to fill the bounds for Tensors that\n   *  is already in the out_dom_map\n   */\n  virtual void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                                 const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                                 std::unordered_map<Tensor, TensorDom>* out_dom_map) const = 0;\n  /*!\n   * \\brief Gather the bound from output tensor.\n   *  Set the range of each root_iter_vars in the op to out_dom_map\n   *\n   * \\param self The reference to self.\n   * \\param tensor_dom Domain map of Tensor->access set of each dimension.\n   * \\param out_dom_map The output domain map of each IterVar to be setted.\n   */\n  virtual void GatherBound(const Operation& self,\n                           const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                           std::unordered_map<IterVar, Range>* out_dom_map) const = 0;\n  /*!\n   * \\brief Build the Realize statement that realizes\n   *   the op's output tensors.\n   * \\param stage the op's stage.\n   * \\param realize_map The realization domain map of the operators.\n   * \\param body The body that is going to get\n   * \\param storage_scope The storage scope associated with this realization\n   * \\return A realization statement that wraps body.\n   */\n  virtual Stmt BuildRealize(const Stage& stage,\n                            const std::unordered_map<IterVar, Range>& realize_map, const Stmt& body,\n                            String storage_scope = \"\") const = 0;\n  /*!\n   * \\brief Build the statement that provide the output tensors.\n   * \\param stage The schedule stage of the op.\n   * \\param dom_map The domain map of all iteration domains.\n   * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1\n   * \\return A statement that add production and wraps consumer.\n   */\n  virtual Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                            bool debug_keep_trivial_loop) const = 0;\n\n  static constexpr const char* _type_key = \"Operation\";\n\n  TVM_DECLARE_BASE_OBJECT_INFO(OperationNode, Object);\n};\n\n/*!\n * \\brief A placeholder op represents an input placeholder.\n */\nclass PlaceholderOpNode : public OperationNode {\n public:\n  /*! \\brief The shape of the input */\n  Array<PrimExpr> shape;\n  /*! \\brief The data type of the input. */\n  DataType dtype;\n  // override behavior.\n  int num_outputs() const final;\n  Array<IterVar> root_iter_vars() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<PrimExpr> output_shape(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  void GatherBound(const Operation& self, const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                   std::unordered_map<IterVar, Range>* out_dom_map) const final;\n  Stmt BuildRealize(const Stage& stage, const std::unordered_map<IterVar, Range>& realize_map,\n                    const Stmt& body, String storage_scope = \"\") const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"shape\", &shape);\n    v->Visit(\"dtype\", &dtype);\n  }\n\n  static constexpr const char* _type_key = \"PlaceholderOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PlaceholderOpNode, OperationNode);\n};\n\n/*!\n * \\brief Managed reference to PlaceholderOpNode\n * \\sa PlaceholderOpNode\n */\nclass PlaceholderOp : public Operation {\n public:\n  TVM_DLL PlaceholderOp(std::string name, Array<PrimExpr> shape, DataType dtype);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PlaceholderOp, Operation, PlaceholderOpNode);\n};\n\n/*!\n * \\brief A Compute op that compute a tensor on certain domain.\n * This is the base class for ComputeOp (operating on a scalar at a time) and\n * TensorComputeOp (operating on a TensorSlice at a time)\n */\nclass TVM_DLL BaseComputeOpNode : public OperationNode {\n public:\n  /*! \\brief IterVar on each axis */\n  Array<IterVar> axis;\n  /*! \\brief IterVar on each reduction axis, if the body is a Reduce */\n  Array<IterVar> reduce_axis;\n  // override functions\n  Array<IterVar> root_iter_vars() const final;\n  Array<PrimExpr> output_shape(size_t idx) const final;\n  void GatherBound(const Operation& self, const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                   std::unordered_map<IterVar, Range>* out_dom_map) const final;\n  Stmt BuildRealize(const Stage& stage, const std::unordered_map<IterVar, Range>& realize_map,\n                    const Stmt& body, String storage_scope = \"\") const final;\n  virtual size_t num_schedulable_dims() const = 0;\n\n  static constexpr const char* _type_key = \"BaseComputeOp\";\n  TVM_DECLARE_BASE_OBJECT_INFO(BaseComputeOpNode, OperationNode);\n};\n\n/*!\n * \\brief A Compute op that compute a tensor on certain domain.\n */\nclass TVM_DLL ComputeOpNode : public BaseComputeOpNode {\n public:\n  /*! \\brief the compute expression */\n  Array<PrimExpr> body;\n  /*! \\brief constructor */\n  ComputeOpNode() {}\n  // override functions\n  int num_outputs() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n  size_t num_schedulable_dims() const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"axis\", &axis);\n    v->Visit(\"reduce_axis\", &reduce_axis);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"ComputeOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ComputeOpNode, BaseComputeOpNode);\n};\n\n/*!\n * \\brief Managed reference to ComputeOpNode\n * \\sa ComputeOpNode\n */\nclass ComputeOp : public Operation {\n public:\n  TVM_DLL ComputeOp(std::string name, std::string tag, Map<String, ObjectRef> attrs,\n                    Array<IterVar> axis, Array<PrimExpr> body);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ComputeOp, Operation, ComputeOpNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ComputeOpNode);\n};\n\n/*!\n * \\brief A TenorCompute op that compute a tensor with an tensor intrinsic.\n */\nclass TensorComputeOpNode : public BaseComputeOpNode {\n public:\n  /*! \\brief number of axes that can be scheduled */\n  int schedulable_ndim;\n  /*! \\brief TensorIntrin used to compute */\n  TensorIntrin intrin;\n  /*! \\brief input tensors of intrin */\n  Array<Tensor> inputs;\n  /*! \\brief region of input tensors */\n  Array<Region> input_regions;\n  /*! \\brief scalar expression inputs */\n  Array<PrimExpr> scalar_inputs;\n  /*! \\brief constructor */\n  TensorComputeOpNode() {}\n  // override functions\n  int num_outputs() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n  size_t num_schedulable_dims() const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"axis\", &axis);\n    v->Visit(\"reduce_axis\", &reduce_axis);\n    v->Visit(\"schedulable_ndim\", &schedulable_ndim);\n    v->Visit(\"intrin\", &intrin);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"input_regions\", &input_regions);\n    v->Visit(\"scalar_inputs\", &scalar_inputs);\n  }\n\n  static constexpr const char* _type_key = \"TensorComputeOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorComputeOpNode, BaseComputeOpNode);\n};\n\n/*!\n * \\brief Managed reference to TensorComputeOpNode\n * \\sa TensorComputeOpNode\n */\nclass TensorComputeOp : public Operation {\n public:\n  TVM_DLL TensorComputeOp(std::string name, std::string tag, Array<IterVar> axis,\n                          Array<IterVar> reduce_axis, int schedulable_ndim, TensorIntrin intrin,\n                          Array<Tensor> tensors, Array<Region> regions,\n                          Array<PrimExpr> scalar_inputs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorComputeOp, Operation, TensorComputeOpNode);\n};\n\n/*!\n * \\brief Symbolic scan.\n */\nclass ScanOpNode : public OperationNode {\n public:\n  /*! \\brief IterVar to scan over */\n  IterVar scan_axis;\n  /*! \\brief the initialization tensors */\n  Array<Tensor> init;\n  /*! \\brief the update function represented by tensor */\n  Array<Tensor> update;\n  /*! \\brief The placeholder to refer as states in update. */\n  Array<Tensor> state_placeholder;\n  /*!\n   * \\brief the inputs to the scan, these are optionally provided\n   *  But they can be helpful to provide hints to speedup get of scan body.\n   */\n  Array<Tensor> inputs;\n  /*!\n   * \\brief Spatial axis to indicate spatial dimension of each output.\n   *  They corresponds to flattened spatial axis of the outputs.\n   *\n   *  [output[0].axis[1], output[0].axis[2]... output[k].axis[j]...]\n   *  These are auxiliary data structure for storing result of bound inference.\n   *  They do not corresponds to splittable iterations, thus the name comes\n   *  with underscore.\n   */\n  Array<IterVar> spatial_axis_;\n  /*! \\brief constructor */\n  ScanOpNode() {}\n  // override behavior.\n  int num_outputs() const final;\n  Array<IterVar> root_iter_vars() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<PrimExpr> output_shape(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  void GatherBound(const Operation& self, const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                   std::unordered_map<IterVar, Range>* out_dom_map) const final;\n  Stmt BuildRealize(const Stage& stage, const std::unordered_map<IterVar, Range>& realize_map,\n                    const Stmt& body, String storage_scope = \"\") const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"scan_axis\", &scan_axis);\n    v->Visit(\"init\", &init);\n    v->Visit(\"update\", &update);\n    v->Visit(\"state_placeholder\", &state_placeholder);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"spatial_axis_\", &spatial_axis_);\n  }\n\n  static constexpr const char* _type_key = \"ScanOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ScanOpNode, OperationNode);\n};\n\n/*!\n * \\brief Managed reference to ScanOpNode\n * \\sa ScanOpNode\n */\nclass ScanOp : public Operation {\n public:\n  TVM_DLL ScanOp(std::string name, std::string tag, Map<String, ObjectRef> attrs, IterVar axis,\n                 Array<Tensor> init, Array<Tensor> update, Array<Tensor> state_placeholder,\n                 Array<Tensor> input);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ScanOp, Operation, ScanOpNode);\n};\n\n/*!\n * \\brief External computation that cannot be splitted.\n */\nclass ExternOpNode : public OperationNode {\n public:\n  /*! \\brief The input tensors */\n  Array<Tensor> inputs;\n  /*! \\brief Symbolic placeholder representation of inputs */\n  Array<Buffer> input_placeholders;\n  /*! \\brief Symbolic placeholder representation of outputs */\n  Array<Buffer> output_placeholders;\n  /*! \\brief the statement that generates the computation. */\n  Stmt body;\n\n  /*! \\brief constructor */\n  ExternOpNode() {}\n  // override functions\n  int num_outputs() const final;\n  Array<IterVar> root_iter_vars() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<PrimExpr> output_shape(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  void GatherBound(const Operation& self, const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                   std::unordered_map<IterVar, Range>* out_dom_map) const final;\n  Stmt BuildRealize(const Stage& stage, const std::unordered_map<IterVar, Range>& realize_map,\n                    const Stmt& body, String storage_scope = \"\") const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"input_placeholders\", &input_placeholders);\n    v->Visit(\"output_placeholders\", &output_placeholders);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"ExternOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExternOpNode, OperationNode);\n};\n\n/*!\n * \\brief Managed reference to ExternOpNode\n * \\sa ExternOpNode\n */\nclass ExternOp : public Operation {\n public:\n  TVM_DLL ExternOp(std::string name, std::string tag, Map<String, ObjectRef> attrs,\n                   Array<Tensor> inputs, Array<Buffer> input_placeholders,\n                   Array<Buffer> output_placeholders, Stmt body);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ExternOp, Operation, ExternOpNode);\n};\n\n/*!\n * \\brief A computation operator that generated by hybrid script.\n */\nclass HybridOpNode : public OperationNode {\n public:\n  /*! \\brief The input tensors */\n  Array<Tensor> inputs;\n  /*! \\brief Symbolic placeholder representation of outputs */\n  Array<Tensor> outputs;\n  /*! \\brief The axis of iterations */\n  Array<IterVar> axis;\n  /*! \\brief the statement that generates the computation. This is\n   * slightly different from the body in ExternOpNode. All the output\n   * tensors keep its own name specified by users in the script.\n   * However, when compilation, these tensors will be placed by those\n   * actual output tensors. */\n  Stmt body;\n\n  /*! \\brief constructor */\n  HybridOpNode() {}\n  // override functions\n  int num_outputs() const final;\n  Array<IterVar> root_iter_vars() const final;\n  DataType output_dtype(size_t i) const final;\n  Array<PrimExpr> output_shape(size_t i) const final;\n  Array<Tensor> InputTensors() const final;\n  Operation ReplaceInputs(const Operation& self,\n                          const std::unordered_map<Tensor, Tensor>& rmap) const final;\n  void PropBoundToInputs(const Operation& self, arith::Analyzer* analyzer,\n                         const std::unordered_map<const VarNode*, IntSet>& dom_map,\n                         std::unordered_map<Tensor, TensorDom>* out_dom_map) const final;\n  void GatherBound(const Operation& self, const std::unordered_map<Tensor, TensorDom>& tensor_dom,\n                   std::unordered_map<IterVar, Range>* out_dom_map) const final;\n  Stmt BuildRealize(const Stage& stage, const std::unordered_map<IterVar, Range>& realize_map,\n                    const Stmt& body, String storage_scope = \"\") const final;\n  Stmt BuildProvide(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    bool debug_keep_trivial_loop) const final;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"tag\", &tag);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"outputs\", &outputs);\n    v->Visit(\"axis\", &axis);\n    v->Visit(\"body\", &body);\n  }\n\n  static constexpr const char* _type_key = \"HybridOp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(HybridOpNode, OperationNode);\n};\n\n/*!\n * \\brief Managed reference to HybridOpNode\n * \\sa HybridOpNode\n */\nclass HybridOp : public Operation {\n public:\n  TVM_DLL HybridOp(std::string name, std::string tag, Map<String, ObjectRef> attrs,\n                   Array<Tensor> inputs, Array<Tensor> outputs, Stmt body);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(HybridOp, Operation, HybridOpNode);\n};\n\n/*!\n * \\brief Construct a new Var expression\n * \\param name_hint The name hint for the expression\n * \\param t The type of the expression\n */\nTVM_DLL Var var(std::string name_hint, DataType t = DataType::Int(32));\n\n/*!\n * \\brief Create a new IterVar that represents an axis in thread.\n *\n * \\param dom Optional, domain of the thread axis.\n * \\param tag The thread tag of the axis.\n */\nTVM_DLL IterVar thread_axis(Range dom, std::string tag);\n\n/*!\n * \\brief Create a new IterVar for reduction operations.\n *\n * \\param dom The domain of the reduction axis.\n * \\param name The name of the reduction axis.\n */\nTVM_DLL IterVar reduce_axis(Range dom, std::string name = \"rv\");\n\n/*! \\brief The compute function to specify the input source of a Tensor */\nusing FCompute = std::function<PrimExpr(const Array<Var>& i)>;\n\n/*! \\brief The compute function to specify the inputs source of Tensors */\nusing FBatchCompute = std::function<Array<PrimExpr>(const Array<Var>& i)>;\n\n/*!\n * \\brief create a place holder tensor.\n * \\param shape The shape of the tensor.\n * \\param dtype the data type of the tensor.\n * \\param name The name of the Tensor.\n */\nTVM_DLL Tensor placeholder(Array<PrimExpr> shape, DataType dtype = DataType::Float(32),\n                           std::string name = \"placeholder\");\n\n/*!\n * \\brief Construct a new tensor by computing over shape,\n *  using the computation rule: result_tensor[axis] = fcompute(axis)\n * \\param shape Shape of the tensor.\n * \\param fcompute The compute function to create the tensor.\n * \\param name The optional name of the tensor.\n * \\param tag The optional tag of the tensor.\n * \\param attrs Optional additional attributes of the compute.\n */\nTVM_DLL Tensor compute(Array<PrimExpr> shape, FCompute fcompute, std::string name = \"tensor\",\n                       std::string tag = \"\", Map<String, ObjectRef> attrs = {});\n\n/*!\n * \\brief Construct a new tensor by computing over shape,\n *  using the computation rule: result_tensor[axis] = fcompute(axis)\n * \\param shape Shape of the tensor.\n * \\param fcompute The compute function to create the tensors.\n * \\param name The optional name of the tensor.\n * \\param tag The optional tag of the tensor.\n * \\param attrs Optional additional attributes of the compute.\n */\nTVM_DLL Array<Tensor> compute(Array<PrimExpr> shape, FBatchCompute fcompute,\n                              std::string name = \"tensor\", std::string tag = \"\",\n                              Map<String, ObjectRef> attrs = {});\n\n/*!\n * \\brief Construct new tensors by scan.\n *\n * \\param init The intialize tensor of first K steps.\n * \\param update The update tensor indicated the updated result after each timestamp.\n * \\param state_placeholder The placeholder for the states.\n * \\param inputs The inputs to the scan body, this is optional,\n *    but recommended to provide concrete information about scan body.\n * \\param name The optional name of the tensor.\n * \\param tag The optional tag of the tensor.\n * \\param attrs Optional additional attributes of the compute.\n */\nTVM_DLL Array<Tensor> scan(Array<Tensor> init, Array<Tensor> update,\n                           Array<Tensor> state_placeholder, Array<Tensor> inputs = Array<Tensor>(),\n                           std::string name = \"scan\", std::string tag = \"\",\n                           Map<String, ObjectRef> attrs = {});\n\n// same as compute, specialized for different fcompute function\ninline Tensor compute(Array<PrimExpr> shape, std::function<PrimExpr(Var)> f,\n                      std::string name = \"tensor\", std::string tag = \"\",\n                      Map<String, ObjectRef> attrs = {}) {\n  FCompute fc = [f](const Array<Var>& i) { return f(i[0]); };\n  return compute(shape, fc, name, tag, attrs);\n}\ninline Tensor compute(Array<PrimExpr> shape, std::function<PrimExpr(Var, Var)> f,\n                      std::string name = \"tensor\", std::string tag = \"\",\n                      Map<String, ObjectRef> attrs = {}) {\n  FCompute fc = [f](const Array<Var>& i) { return f(i[0], i[1]); };\n  return compute(shape, fc, name, tag, attrs);\n}\ninline Tensor compute(Array<PrimExpr> shape, std::function<PrimExpr(Var, Var, Var)> f,\n                      std::string name = \"tensor\", std::string tag = \"\",\n                      Map<String, ObjectRef> attrs = {}) {\n  FCompute fc = [f](const Array<Var>& i) { return f(i[0], i[1], i[2]); };\n  return compute(shape, fc, name, tag, attrs);\n}\ninline Tensor compute(Array<PrimExpr> shape, std::function<PrimExpr(Var, Var, Var, Var)> f,\n                      std::string name = \"tensor\", std::string tag = \"\",\n                      Map<String, ObjectRef> attrs = {}) {\n  FCompute fc = [f](const Array<Var>& i) { return f(i[0], i[1], i[2], i[3]); };\n  return compute(shape, fc, name, tag, attrs);\n}\n\n// inline function.\ninline const OperationNode* Operation::operator->() const {\n  return static_cast<const OperationNode*>(get());\n}\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_OPERATION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/schedule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/schedule.h\n * \\brief Define a schedule.\n */\n// Acknowledgement: Many schedule primitives originate from Halide and Loopy.\n#ifndef TVM_TE_SCHEDULE_H_\n#define TVM_TE_SCHEDULE_H_\n\n#include <tvm/support/with.h>\n#include <tvm/te/tensor.h>\n#include <tvm/te/tensor_intrin.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/index_map.h>\n\n#include <string>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace te {\n// Node container for Stage\nclass StageNode;\n// Node container for Schedule\nclass ScheduleNode;\n// Node container for IterVarRelation\nclass IterVarRelationNode;\n// Attribute of itervar.\nclass IterVarAttrNode;\n\n/*! \\brief the attachment type */\nenum AttachType : int {\n  kGroupRoot = 1,\n  kInline = 2,\n  kInlinedAlready = 3,\n  kScope = 4,\n  kScanUpdate = 5\n};\n\n/*! \\brief Stage, contains scheduling for a stage of computation. */\nclass Stage : public ObjectRef {\n public:\n  Stage() {}\n  explicit Stage(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief create a new schedule for op.\n   * \\param op The operator in the schedule\n   */\n  explicit Stage(Operation op);\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline const StageNode* operator->() const;\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline StageNode* operator->();\n  /*!\n   * \\brief set the memory scope of the stage\n   * \\param scope The memory scope.\n   */\n  TVM_DLL Stage& set_scope(std::string scope);  // NOLINT(*)\n  /*!\n   * \\brief specify the schedule to be computed at the parent schedule's scope.\n   * \\param parent The parent schedule.\n   * \\param scope The iteration point to carry the schedule.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& compute_at(Stage parent, IterVar scope);  // NOLINT(*)\n  /*!\n   * \\brief Compute the function inline.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& compute_inline();  // NOLINT(*)\n  /*!\n   * \\brief Compute the function at group root.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& compute_root();  // NOLINT(*)\n  /*!\n   * \\brief Bind the IterVar to thread index.\n   *\n   * \\param ivar The IterVar to be bound.\n   * \\param thread_ivar The thread axis to be bound.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& bind(IterVar ivar, IterVar thread_ivar);\n  /*!\n   * \\brief Set the predicate to determine whether a store to the array should be performed.\n   *  Use this when there are multiple threads performing the same store and we only\n   *  need one of them to do the store.\n   *\n   * \\note This is a dangerous scheduling primitive that can change behavior of program.\n   *    Only do when we are certain that thare are duplicated stores.\n   * \\param predicate The condition to be checked.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& set_store_predicate(PrimExpr predicate);\n  /*!\n   * \\brief Specify environment threads that launched around the group's scope.\n   *  This can only be used in group stage.\n   * \\param threads The threads to be launched around the scope.\n   * \\note Each thread can only appear in one env_threads.\n   *    This is a beta feature.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& env_threads(Array<IterVar> threads);\n  /*!\n   * \\brief Split the parent by factor, generate\n   * \\param parent The parent iteration domain.\n   * \\param factor The split factor of the loop.\n   * \\param p_outer The result outer domain\n   * \\param p_inner The result inner domain.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& split(IterVar parent, PrimExpr factor, IterVar* p_outer,\n                       IterVar* p_inner);  // NOLINT(*)\n  /*!\n   * \\brief Split the iteration with given number of parts.\n   *\n   * \\param parent The parent domain.\n   * \\param nparts The number of parts in the outer domain.\n   * \\param p_outer The result outer domain.\n   * \\param p_inner The result inner domain.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& split_by_nparts(IterVar parent, PrimExpr nparts, IterVar* p_outer,\n                                 IterVar* p_inner);  // NOLINT(*)\n  /*!\n   * \\brief Fuse the inner outer domain to the target\n   * \\param outer The outer domain to be fused.\n   * \\param inner The inner domain to be fused\n   * \\param p_target The result target domain.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& fuse(IterVar outer, IterVar inner, IterVar* p_target);  // NOLINT(*)\n  /*!\n   * \\brief Fuse all the axes together into a single axis.\n   *\n   * \\param axes All the axes to be fused.\n   * \\param p_target The result target domain.\n   *\n   * \\note axes can be an empty array,\n   *       in that case, a singleton IterVar is created and\n   *       inserted to the outermost loop.\n   *       The fuse of empty array is used to support zero-dimension tensors.\n   *\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& fuse(const Array<IterVar>& axes, IterVar* p_target);  // NOLINT(*)\n  /*!\n   * \\brief Reorder the iteration\n   * \\param order The order of iteration variable.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& reorder(const Array<IterVar>& order);  // NOLINT(*)\n  /*!\n   * \\brief Perform tiling on two dimensions\n   *  The final loop order from outmost to inner most are\n   *  [x_outer, y_outer, x_inner, y_inner]\n   *\n   * \\param x_parent The original x dimension\n   * \\param y_parent The original y dimension\n   * \\param x_factor The stride factor on x axis\n   * \\param y_factor The stride factor on y axis\n   * \\param p_x_outer Outer axis of x dimension\n   * \\param p_y_outer Outer axis of y dimension\n   * \\param p_x_inner Inner axis of x dimension\n   * \\param p_y_inner Inner axis of y dimension\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& tile(IterVar x_parent, IterVar y_parent,  // NOLINT(*)\n                      PrimExpr x_factor, PrimExpr y_factor, IterVar* p_x_outer, IterVar* p_y_outer,\n                      IterVar* p_x_inner, IterVar* p_y_inner);\n  /*!\n   * \\brief Vectorize iteration.\n   * \\param var The axis to be vectorized.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& vectorize(IterVar var);  // NOLINT(*)\n  /*!\n   * \\brief Replace computation of the current stage by tensor intrinsic f.\n   * \\param var The axis marks beginning of tensorization.\n   *  Every operations inside the axis(include axis itself is tensorized).\n   * \\param f The Tensor compute intrinsics.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& tensorize(IterVar var, TensorIntrin f);  // NOLINT(*)\n  /*!\n   * \\brief Unroll iteration.\n   * \\param var The axis to be unrolled.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& unroll(IterVar var);  // NOLINT(*)\n  /*!\n   * \\brief Parallelize iteration.\n   * \\param var The axis to be parallelized.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& parallel(IterVar var);  // NOLINT(*)\n  /*!\n   * \\brief Annotate the iteration with pragma\n   *\n   * \\param var The axis to be parallelized.\n   * \\param pragma_type The pragma type.\n   * \\param pragma_value The pragma value\n   *\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& pragma(IterVar var, const std::string& pragma_type,\n                        const PrimExpr& pragma_value = PrimExpr());  // NOLINT(*)\n  /*!\n   * \\brief Fetch data in advance.\n   * \\param domain the tensor to be prefetched\n   * \\param var the iteration point at which to apply prefetching\n   * \\param offset the number of iterations be to fetched in advance\n   * \\return reference to self\n   */\n  TVM_DLL Stage& prefetch(const Tensor& domain, IterVar var, PrimExpr offset);  // NOLINT(*)\n  /*!\n   * \\brief Set alignment requirement for specific dimension.\n   *\n   *  Such that stride[axis] == k * factor + offset for some k.\n   *\n   * \\param axis The dimension to be specified for alignment.\n   * \\param factor The factor multiple of alignment\n   * \\param offset The required offset factor.\n   * \\return reference to self\n   */\n  TVM_DLL Stage& storage_align(IterVar axis, int factor, int offset);  // NOLINT(*)\n  /*!\n   * \\brief Compute current stage with double buffering.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& double_buffer();  // NOLINT(*)\n  /*!\n   * \\brief Compute current stage with rolling buffering.\n   * \\return reference to self.\n   */\n  TVM_DLL Stage& rolling_buffer();  // NOLINT(*)\n  /*!\n   * \\brief Defines a layout transformation to be applied to the buffer.\n   *\n   * The map from initial_index to final_index must be an\n   * invertible affine transformation.\n   *\n   * \\param initial_indices An array of variables to represent a\n   * value's location in the tensor, using the pre-transformation\n   * layout.  These variables are used as binding occurrences to\n   * represent the initial indices when applying the initial->final\n   * mapping, and should not occur elsewhere in the\n   * Schedule. (i.e. Pass in newly constructed variables, not the\n   * initial IterVar::var)\n   *\n   * \\param final_indices An array of expressions, giving the\n   * value's location in the tensor, using the post-transformation layout.\n   * Expressions should be in terms of the variables given in\n   * initial_indices.\n   *\n   * \\param out_iter_vars An optional output location for the updated\n   * loop iteration variables.\n   *\n   * \\return reference to self\n   */\n  TVM_DLL Stage& transform_layout(const Array<Var>& initial_indices,\n                                  const Array<PrimExpr>& final_indices,\n                                  Array<IterVar>* out_iter_vars = nullptr);\n  /*! \\brief Defines separators between groups of axes.\n   *\n   * Used to define `BufferNode::axis_separators`, which has\n   * additional details.\n   *\n   * \\param axis_separators A list of axis separators.\n   */\n  TVM_DLL Stage& set_axis_separators(const Array<IntImm>& axis_separators);\n  /*!\n   * \\brief whether the stage has been scheduled.\n   * \\return whether the stage has been scheduled.\n   */\n  bool is_scheduled() const;\n  /*!\n   * \\brief Get attachment spec of current stage.\n   *  If the stage compute at Group root, this function\n   *  will traverse the group function to get the\n   *  final spec from the group.\n   * \\return A stage representing the attach spec of the group.\n   */\n  Stage GetAttachSpec() const;\n  // declare container type\n  using ContainerType = StageNode;\n};\n\n/*!\n * \\brief Global schedule container\n *  For operations and all the operations they depend on.\n *  The schedule per Operation is named as stage.\n */\nclass Schedule : public ObjectRef {\n public:\n  Schedule() {}\n  explicit Schedule(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief Create a schedule for array of ops(and their dependencies).\n   * \\param ops The ops to be scheduled.\n   * \\return sch The created Schedule.\n   */\n  TVM_DLL explicit Schedule(Array<Operation> ops);\n  /*!\n   * \\brief Get a copy of current schedule.\n   * \\return The copied schedule.\n   */\n  Schedule copy() const;\n  /*!\n   * \\brief Get the stage corresponds to the op\n   * \\param op The operation.\n   */\n  TVM_DLL Stage operator[](const Operation& op);\n  /*!\n   * \\brief Short hand for getting the stage of tensor's operation.\n   * \\param tensor The tensor\n   * \\return The stage corresponding to the tensor's op\n   */\n  TVM_DLL Stage operator[](const Tensor& tensor) { return this->operator[](tensor->op); }\n  /*!\n   * \\brief Create a new stage group for all intermediate\n   *  operations between inputs and outputs.\n   *\n   * \\param outputs The output boundary of the group.\n   * \\param inputs The input boundary of the group.\n   * \\param include_inputs Whether include inputs if they are reachable from outputs.\n   * \\return The new grouped stage.\n   */\n  TVM_DLL Stage create_group(const Array<Tensor>& outputs, const Array<Tensor>& inputs,\n                             bool include_inputs = false);\n  /*!\n   * \\brief create a cache read of original tensor for readers.\n   *  This will mutate the body of the readers.\n   *  A new stage will be created for the tensor.\n   * \\param tensor The tensor cached.\n   * \\param scope The scope of the cache.\n   * \\param readers The readers to redirect to the tensor.\n   * \\return The created tensor.\n   */\n  TVM_DLL Tensor cache_read(const Tensor& tensor, const std::string& scope,\n                            const Array<Operation>& readers);\n  /*!\n   * \\brief Create a cache write tensor for producing tensor.\n   *  The tensor will take over body of original tensor op.\n   *\n   *  This function can be used to do data layout transformation.\n   *  If there is a split/fuse/reorder on the data parallel axis of tensor\n   *  before cache_write is called. The intermediate cache stores\n   *  the data in the layout as the iteration order of leave axis.\n   *  The data will be transformed back to the original layout in the original tensor.\n   *  User can further call compute_inline to inline the original layout and keep\n   *  the data stored in the transformed layout.\n   *\n   * \\param tensor The tensors to be produced.\n   * \\param scope The scope of the storage.\n   * \\return The created tensor.\n   */\n  TVM_DLL Array<Tensor> cache_write(const Array<Tensor>& tensor, const std::string& scope);\n  /*!\n   * \\brief Create a cache write tensor for producing tensor.\n   *  The tensor will take over body of original tensor op.\n   *\n   *  This function can be used to do data layout transformation.\n   *  If there is a split/fuse/reorder on the data parallel axis of tensor\n   *  before cache_write is called. The intermediate cache stores\n   *  the data in the layout as the iteration order of leave axis.\n   *  The data will be transformed back to the original layout in the original tensor.\n   *  User can further call compute_inline to inline the original layout and keep\n   *  the data stored in the transformed layout.\n   *\n   * \\param tensor The tensor to be produced.\n   * \\param scope The scope of the storage.\n   * \\return The created tensor.\n   */\n  TVM_DLL Tensor cache_write(const Tensor& tensor, const std::string& scope);\n  /*!\n   * \\brief Factor a reduction axis in tensor's schedule to be an explicit axis.\n   * This will create a new stage that generated the new tensor with axis\n   * as the first dimension. The tensor's body will be rewritten as a reduction\n   * over the factored tensor.\n   *\n   *  P. Suriana, A. Adams and S. Kamil. Parallel associative reductions in halide. CGO'17\n   *\n   * \\param tensor The tensor to be factored.\n   * \\param axis The reduction axis in tensor's schedule to be factored.\n   * \\param factor_axis The position where the new axis is placed.\n   * \\return The created factored tensors.\n   */\n  TVM_DLL Array<Tensor> rfactor(const Tensor& tensor, const IterVar& axis, int factor_axis = 0);\n  /*!\n   * \\brief Normalize the schedule.\n   *  This is needed before bound inference.\n   *  Insert necessary RebaseNode to make sure all leaf_iter_vars\n   *  are in form [0, extent)\n   *\n   * \\return A normalized schedule, can be same as current one.\n   */\n  Schedule normalize();\n\n  /*!\n   * \\brief Normalize the schedule for feature extraction in auto-scheduler.\n   * This is similar to `Schedule::normalize`, but we do aggressive simplification\n   * to the TE compute with const_matrix=True for faster compilation and feature extraction.\n   * The resulted schedule may be wrong, but it is good enough for feature extraction\n   * purposes.\n   *\n   * \\return A normalized schedule, can be same as current one.\n   */\n  Schedule normalize_for_feature_extraction();\n\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline const ScheduleNode* operator->() const;\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline ScheduleNode* operator->();\n  // declare container type\n  using ContainerType = ScheduleNode;\n};\n\n/*!\n * \\brief The schedule relation between IterVars\n *  can be Split, Fuse.\n */\nclass IterVarRelation : public ObjectRef {\n public:\n  IterVarRelation() {}\n  explicit IterVarRelation(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline const IterVarRelationNode* operator->() const;\n};\n\n/*!\n * \\brief Additional scheduable attributes about IterVar.\n */\nclass IterVarAttr : public ObjectRef {\n public:\n  IterVarAttr() {}\n  explicit IterVarAttr(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline const IterVarAttrNode* operator->() const;\n};\n\n/*!\n * \\brief represents a stage.\n *\n *  relations form a Directed acylic hypergraph in bipartite manner.\n *  With each node is represented by a IterVar,\n *  and each hyper-edge is represented by a IterVarRelation.\n *  The relations connects the IterVars in the graph.\n *\n *  Besides typical stage that corresponds to operations.\n *  There is also group stage, which groups stages together.\n *  Each stage's group(given by group) represent an constraint,\n *  the stage can only be attached to stages within the group.\n *\n *  The group stage node can be attached to IterVars as in normal stage.\n */\nclass StageNode : public Object {\n public:\n  /*!\n   * \\brief The operation of stage, can be different from original op.\n   *  If it is null, then this stage is a group stage.\n   */\n  Operation op;\n  /*!\n   * \\brief The original operator.\n   *  The op field can change during schedule to alternate the dataflow,\n   *  while origin_op remains fixed.\n   */\n  Operation origin_op;\n  /*! \\brief All the nodes in the iter var\n   *\n   * Each element of all_iter_vars represents an iteration variable\n   * that may appear within this stage's computation.  Any element\n   * of `all_iter_vars` that is in `leaf_iter_vars` represents a\n   * variable that is directly defined and usable within the stage's\n   * computation.  All other elements of `all_iter_vars` represent\n   * variables whose value must be computed from the variables in\n   * `leaf_iter_vars`.  (e.g. Support index k has been split by\n   * ``ko, ki = s.split(k, factor=4)``.  ko and ki will appear in\n   * `leaf_iter_vars`, while k will not, and must be computed as\n   * `4*ko + ki`.\n   */\n  Array<IterVar> all_iter_vars;\n  /*! \\brief The current active leaf iter vars in the stage.\n   *\n   * Each element of leaf_iter_vars will either be replaced with the\n   * bound index (e.g. threadIdx.x), or will be expanded into a loop\n   * over the variable's extent.  `leaf_iter_vars` is a subset of\n   * `all_iter_vars`.\n   */\n  Array<IterVar> leaf_iter_vars;\n  /*!\n   * \\brief Specify threads to be launched at the stage.\n   *  This is only valid for composite ops such as Scan.\n   * \\note Experimental primitive: used for thread persistence.\n   */\n  Array<IterVar> env_threads;\n  /*!\n   * \\brief The predicate under which store can happen\n   *  Use this when there can be duplicated threads doing the same store.\n   * \\note Experimental primitive: used by cross thread-reduction.\n   */\n  PrimExpr store_predicate;\n  /*! \\brief The relation bwteen of IterVars */\n  Array<IterVarRelation> relations;\n  /*! \\brief additional attributes about iter var. */\n  Map<IterVar, IterVarAttr> iter_var_attrs;\n  /*! \\brief The attachment type of the schedule */\n  AttachType attach_type{kGroupRoot};\n  /*! \\brief The attach point of this schedule. */\n  IterVar attach_ivar;\n  /*! \\brief The stage this node attaches to */\n  Stage attach_stage;\n  /*! \\brief The thread storage scope level of the stage */\n  std::string scope;\n  /*! \\brief Whether this is an output stage */\n  bool is_output{false};\n  /*! \\brief Whether apply double buffer optimization to this stage */\n  bool double_buffer{false};\n  /*! \\brief Whether apply rolling buffer optimization to this stage */\n  bool rolling_buffer{false};\n  /*! \\brief Layout transformations to be applied onto the stage's tensors. */\n  Array<IndexMap> layout_transforms;\n  /*! \\brief List of axes after which to divide physical axes.\n   *\n   * Used to populate `BufferNode::axis_separators`, which has\n   * additional details.\n   */\n  Array<IntImm> axis_separators;\n  /*!\n   * \\brief The parent group of the current stage.\n   *  The stage cannot be assigned to stages outside the group.\n   */\n  Stage group;\n  /*! \\brief Number of direct child stages, only used for group stage.*/\n  int num_child_stages{0};\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"op\", &op);\n    v->Visit(\"origin_op\", &origin_op);\n    v->Visit(\"all_iter_vars\", &all_iter_vars);\n    v->Visit(\"leaf_iter_vars\", &leaf_iter_vars);\n    v->Visit(\"env_threads\", &env_threads);\n    v->Visit(\"relations\", &relations);\n    v->Visit(\"iter_var_attrs\", &iter_var_attrs);\n    v->Visit(\"attach_type\", &attach_type);\n    v->Visit(\"attach_ivar\", &attach_ivar);\n    v->Visit(\"attach_stage\", &attach_stage);\n    v->Visit(\"scope\", &scope);\n    v->Visit(\"is_output\", &is_output);\n    v->Visit(\"double_buffer\", &double_buffer);\n    v->Visit(\"layout_transforms\", &layout_transforms);\n    v->Visit(\"axis_separators\", &axis_separators);\n    v->Visit(\"group\", &group);\n    v->Visit(\"num_child_stages\", &num_child_stages);\n  }\n\n  static constexpr const char* _type_key = \"Stage\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StageNode, Object);\n};\n\n/*! \\brief node container for schedule */\nclass ScheduleNode : public Object {\n public:\n  /*! \\brief The output operations in original data flow graph */\n  Array<Operation> outputs;\n  /*!\n   * \\brief list of all stages for ops.\n   * The stages are sorted in dependency order.\n   */\n  Array<Stage> stages;\n  /*!\n   * \\brief List of all stage groups.\n   */\n  Array<Stage> groups;\n  /*! \\brief map of original operation to the stages */\n  Map<Operation, Stage> stage_map;\n  /*!\n   * \\brief Internal stage map to map internal ops to stages.\n   *  This is created on demand and can be invalidated.\n   */\n  std::unordered_map<const Object*, Stage> op2stage_cache_;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"outputs\", &outputs);\n    v->Visit(\"stages\", &stages);\n    v->Visit(\"groups\", &groups);\n    v->Visit(\"stage_map\", &stage_map);\n  }\n\n  /*! \\brief Initialize temp cache. */\n  void InitCache();\n  /*! \\brief Invalidate temp cache. */\n  void InvalidateCache();\n\n  /*!\n   * \\brief Check if the schedule contains an Operation.\n   * \\param op The candidate Operation.\n   * \\return true if the schedule has the Operation. Otherwise, false.\n   */\n  TVM_DLL bool Contain(const Operation& op) const;\n\n  /*!\n   * \\brief Check if the schedule contains a Tensor.\n   * \\param tensor The candidate tensor.\n   * \\return true if the schedule has the tensor. Otherwise, false.\n   */\n  TVM_DLL bool Contain(const Tensor& tensor) const { return Contain(tensor->op); }\n\n  static constexpr const char* _type_key = \"Schedule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ScheduleNode, Object);\n};\n\n/*!\n * \\brief Create a schedule for array of ops(and their dependencies).\n * \\param ops The ops to be scheduled.\n * \\return sch The created Schedule.\n */\ninline Schedule create_schedule(Array<Operation> ops) { return Schedule(ops); }\n\n/*! \\brief node container for IterVar attr */\nclass IterVarAttrNode : public Object {\n public:\n  /*! \\brief The iteration type. */\n  IterVarType iter_type{kDataPar};\n  /*! \\brief The thread this iter Var binds, can be null */\n  IterVar bind_thread;\n  /*! \\brief List of tensor to be prefetched in this loop */\n  Array<Tensor> prefetch_data;\n  /*! \\brief The offset used in each prefetch */\n  Array<PrimExpr> prefetch_offset;\n  /*!\n   * \\brief Tensor intrinsic used in tensorization,\n   *   when the axis is marked as Tensorized\n   */\n  TensorIntrin tensor_intrin;\n  /*! \\brief Alignment factor of buffer dimension */\n  int dim_align_factor{0};\n  /*! \\brief Alignment offset of buffer dimension */\n  int dim_align_offset{0};\n  /*!\n   * \\brief Additional pragma keys, array of StringImm\n   */\n  Array<PrimExpr> pragma_keys;\n  /*!\n   * \\brief Additional values of pragma, if any\n   */\n  Array<PrimExpr> pragma_values;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"iter_type\", &iter_type);\n    v->Visit(\"bind_thread\", &bind_thread);\n    v->Visit(\"prefetch_data\", &prefetch_data);\n    v->Visit(\"prefetch_offset\", &prefetch_offset);\n    v->Visit(\"tensor_intrin\", &tensor_intrin);\n    v->Visit(\"dim_align_factor\", &dim_align_factor);\n    v->Visit(\"dim_align_offset\", &dim_align_offset);\n    v->Visit(\"pragma_keys\", &pragma_keys);\n    v->Visit(\"pragma_values\", &pragma_values);\n  }\n\n  static constexpr const char* _type_key = \"IterVarAttr\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterVarAttrNode, Object);\n};\n\n/*! \\brief base node of iteration var */\nclass IterVarRelationNode : public Object {\n public:\n  static constexpr const char* _type_key = \"IterVarRelation\";\n  TVM_DECLARE_BASE_OBJECT_INFO(IterVarRelationNode, Object);\n};\n\n/*!\n * \\brief Split the parent domain into product of\n *  outer and iter.\n */\nclass SplitNode : public IterVarRelationNode {\n public:\n  /*! \\brief The parent domain */\n  IterVar parent;\n  /*! \\brief The outer domain */\n  IterVar outer;\n  /*! \\brief The inner domain */\n  IterVar inner;\n  /*! \\brief The split factor */\n  PrimExpr factor;\n  /*! \\brief Number of parts, only factor or nparts can be given */\n  PrimExpr nparts;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"parent\", &parent);\n    v->Visit(\"outer\", &outer);\n    v->Visit(\"inner\", &inner);\n    v->Visit(\"factor\", &factor);\n    v->Visit(\"nparts\", &nparts);\n  }\n\n  static constexpr const char* _type_key = \"Split\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SplitNode, IterVarRelationNode);\n};\n\n/*!\n * \\brief Managed reference to SplitNode\n * \\sa SplitNode\n */\nclass Split : public IterVarRelation {\n public:\n  TVM_DLL Split(IterVar parent, IterVar outer, IterVar inner, PrimExpr factor, PrimExpr nparts);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Split, IterVarRelation, SplitNode);\n};\n\n/*!\n * \\brief Fuse two domains into one domain.\n */\nclass FuseNode : public IterVarRelationNode {\n public:\n  /*! \\brief The outer domain */\n  IterVar outer;\n  /*! \\brief The inner domain */\n  IterVar inner;\n  /*! \\brief The target domain */\n  IterVar fused;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"outer\", &outer);\n    v->Visit(\"inner\", &inner);\n    v->Visit(\"fused\", &fused);\n  }\n\n  static constexpr const char* _type_key = \"Fuse\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FuseNode, IterVarRelationNode);\n};\n\n/*!\n * \\brief Managed reference to FuseNode\n * \\sa FuseNode\n */\nclass Fuse : public IterVarRelation {\n public:\n  TVM_DLL Fuse(IterVar outer, IterVar inner, IterVar fused);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Fuse, IterVarRelation, FuseNode);\n};\n\n/*!\n * \\brief Rebase the iteration to make min to be 0.\n *  This is useful to normalize the Schedule\n *  to make every leaf variable's min to be 0.\n */\nclass RebaseNode : public IterVarRelationNode {\n public:\n  /*! \\brief The parent domain */\n  IterVar parent;\n  /*! \\brief The inner domain */\n  IterVar rebased;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"parent\", &parent);\n    v->Visit(\"rebased\", &rebased);\n  }\n\n  static constexpr const char* _type_key = \"Rebase\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RebaseNode, IterVarRelationNode);\n};\n\n/*!\n * \\brief Managed reference to RebaseNode\n * \\sa RebaseNode\n */\nclass Rebase : public IterVarRelation {\n public:\n  TVM_DLL Rebase(IterVar parent, IterVar rebased);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Rebase, IterVarRelation, RebaseNode);\n};\n\n/*!\n * \\brief Singleton iterator [0, 1)\n */\nclass SingletonNode : public IterVarRelationNode {\n public:\n  /*! \\brief The singleton iterator */\n  IterVar iter;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"iter\", &iter); }\n\n  static constexpr const char* _type_key = \"Singleton\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SingletonNode, IterVarRelationNode);\n};\n\n/*!\n * \\brief Managed reference to SingletonNode\n * \\sa SingletonNode\n */\nclass Singleton : public IterVarRelation {\n public:\n  TVM_DLL explicit Singleton(IterVar iter);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Singleton, IterVarRelation, SingletonNode);\n};\n\n/*!\n * \\brief Transform iterator according to some arbitrary expression.\n */\nclass TransformNode : public IterVarRelationNode {\n public:\n  /*! \\brief The loop variables that were replaced by the transformation.\n   *\n   * Prior to applying a layout transformation, these represent the\n   * loops to iterate over a tensor as it is being computed, following\n   * a row-major traversal of the tensor's original shape in the\n   * compute definition.\n   */\n  Array<IterVar> original_variables;\n\n  /*! \\brief The variables generated by the transformation.\n   *\n   * After to applying a layout transformation, these represent the\n   * loops to iterate over a tensor as it is being computed, following\n   * a row-major traversal of the transformed shape of the tensor.\n   */\n  Array<IterVar> transformed_variables;\n\n  /*! \\brief Map from the original variables to the transformed variables.\n   *\n   * Used to determine iterator ranges over the transformed variables.\n   */\n  IndexMap forward_transformation;\n\n  /*! \\brief Map from transformed variables to the original variables\n   *\n   * Used to rewrite expressions containing the original loop iterators\n   * in terms of the transformed loop iterators.\n   */\n  IndexMap inverse_transformation;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"original_variables\", &original_variables);\n    v->Visit(\"transformed_variables\", &transformed_variables);\n    v->Visit(\"forward_transformation\", &forward_transformation);\n    v->Visit(\"inverse_transformation\", &inverse_transformation);\n  }\n\n  static constexpr const char* _type_key = \"Transform\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TransformNode, IterVarRelationNode);\n};\n\nclass Transform : public IterVarRelation {\n public:\n  TVM_DLL explicit Transform(Array<IterVar> original_variables,\n                             Array<IterVar> transformed_variables, IndexMap forward_transformation,\n                             IndexMap inverse_transformation);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Transform, IterVarRelation, TransformNode);\n};\n\n/*! \\brief Container for specialization conditions. */\nclass SpecializedConditionNode : public Object {\n public:\n  /*!\n   * \\brief List of conditions in conjunctive joint form (CNF).\n   *   Each condition should be a simple expression, e.g., n > 16, m % 8 == 0, etc.,\n   *   where n, m are tvm::Var that represents a dimension in the tensor shape.\n   */\n  Array<PrimExpr> clauses;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"clauses\", &clauses); }\n\n  static constexpr const char* _type_key = \"SpecializedCondition\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SpecializedConditionNode, Object);\n};\n\n/*!\n * \\brief Specialized condition to enable op specialization\n */\nclass SpecializedCondition : public ObjectRef {\n public:\n  /*!\n   * \\brief construct from conditions\n   * \\param conditions The clauses in the specialized condition.\n   */\n  TVM_DLL SpecializedCondition(Array<PrimExpr> conditions);  // NOLINT(*)\n\n  /*!\n   * \\brief Get the current specialized condition.\n   * \\return the current specialized condition.\n   */\n  TVM_DLL static SpecializedCondition Current();\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SpecializedCondition, ObjectRef, SpecializedConditionNode);\n  class Internal;\n\n private:\n  // enable with syntax.\n  friend class Internal;\n  friend class With<SpecializedCondition>;\n  /*! \\brief Push a new specialized condition onto the thread local stack. */\n  TVM_DLL void EnterWithScope();\n  /*! \\brief Pop a specialized condition off the thread local context stack. */\n  TVM_DLL void ExitWithScope();\n};\n\n// implementations\ninline const StageNode* Stage::operator->() const { return static_cast<const StageNode*>(get()); }\ninline StageNode* Stage::operator->() { return static_cast<StageNode*>(get_mutable()); }\n\ninline const ScheduleNode* Schedule::operator->() const {\n  return static_cast<const ScheduleNode*>(get());\n}\ninline ScheduleNode* Schedule::operator->() { return static_cast<ScheduleNode*>(get_mutable()); }\n\ninline const IterVarRelationNode* IterVarRelation::operator->() const {\n  return static_cast<const IterVarRelationNode*>(get());\n}\n\ninline const IterVarAttrNode* IterVarAttr::operator->() const {\n  return static_cast<const IterVarAttrNode*>(get());\n}\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_SCHEDULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/schedule_pass.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/schedule_pass.h\n * \\brief  Collection of Schedule pass functions.\n *\n *  These passes works on the schedule hyper-graph\n *  and infers information such as bounds, check conditions\n *  read/write dependencies between the IterVar\n */\n#ifndef TVM_TE_SCHEDULE_PASS_H_\n#define TVM_TE_SCHEDULE_PASS_H_\n\n#include <tvm/te/schedule.h>\n#include <tvm/tir/function.h>\n\nnamespace tvm {\nnamespace te {\n\n/*!\n * \\brief To automatically inline the element-wise operations.\n *\n * \\param sch The schedule to be inlined.\n */\nvoid AutoInlineElemWise(Schedule sch);\n\n/*!\n * \\brief To automatically inline the broadcast operations.\n *\n * \\param sch The schedule to be inlined.\n */\nvoid AutoInlineBroarcast(Schedule sch);\n\n/*!\n * \\brief To automatically inline operations with injective writes\n *   (i.e. writes without reduction or sequential loops). Note\n *   that in this case, guarantees about contiguity, transpose, stride,\n *   alignemnt and memory footprint in general do not hold.\n *\n * \\param sch The schedule to be inlined.\n */\nTVM_DLL void AutoInlineInjective(Schedule sch);\n\n/*!\n * \\brief Infer the bound of all iteration variables relates to the schedule.\n *\n * \\param sch The root schedule to infer all the bounds.\n * \\return the result bound of the iteration Variable\n */\nMap<IterVar, Range> InferBound(const Schedule& sch);\n\n/*!\n * \\brief Verify if there is any argument bound to compact buffer.\n *\n * \\param stmt The stmt to be verified.\n * \\return true if there is any buffer_bind_scope attribute found,\n *        otherwise, false.\n */\nbool VerifyCompactBuffer(const Stmt& stmt);\n\n/*!\n * \\brief Schedule s' dependent operations.\n *\n * \\param s The schedule to be realized\n * \\param dom_map The domain of each iter vars.\n * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1 during lowering.\n *                                This is a debug feature for dataflow/axis analysis.\n *                                Note: If this is true, The lowered IR may be incorrect,\n *                                because we will also delete the init part of reduction\n * \\return the result Stmt\n */\nStmt ScheduleOps(Schedule s, Map<IterVar, Range> dom_map, bool debug_keep_trivial_loop);\n\n/*!\n * \\brief Postprocessing the Stmt generated by ScheduleOps to create\n *        a PrimFunc that can then be used for further TIR optimizations.\n *\n *  Perform this translation before running any TIR optimizations.\n *\n *  List of actions taken by the function:\n *  - Remove occurrences of te::Tensor, te::Operation in the IR\n *    and replace them by corresponding IR nodes via tir::Buffer.\n *  - Add annotation of extern buffers using the buffer_map field\n *    in the PrimFunc type.\n *\n * \\param arg_list Array of Tensor/Var/Buffer arguments to the function.\n * \\param body The body of the function.\n * \\param bindings potential Tensor to Buffer bindings for the Tensors in the body.\n */\nPrimFunc SchedulePostProcToPrimFunc(Array<ObjectRef> arg_list, Stmt body,\n                                    Optional<Map<Tensor, Buffer>> bindings);\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_SCHEDULE_PASS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/tensor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/tensor.h\n * \\brief Dataflow tensor object\n */\n#ifndef TVM_TE_TENSOR_H_\n#define TVM_TE_TENSOR_H_\n\n#include <tvm/arith/bound.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace te {\n\nusing arith::IntSet;\nusing namespace tvm::tir;\n\n// internal node container for Operation\nclass OperationNode;\nclass Tensor;\n\n/*! \\brief Operation that produces tensors */\nclass Operation : public ObjectRef {\n public:\n  /*! \\brief default constructor  */\n  Operation() {}\n  explicit Operation(ObjectPtr<Object> n) : ObjectRef(n) {}\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  inline const OperationNode* operator->() const;\n  /*!\n   * \\brief get the i-th output of the operation.\n   * \\param i the output index.\n   * \\return The i-th output.\n   */\n  TVM_DLL Tensor output(size_t i) const;\n  /*! \\brief specify container node */\n  using ContainerType = OperationNode;\n};\n\n/*! \\brief Node to represent a tensor */\nclass TensorNode : public DataProducerNode {\n public:\n  /*! \\brief The shape of the tensor */\n  Array<PrimExpr> shape;\n  /*! \\brief data type in the content of the tensor */\n  DataType dtype;\n  /*! \\brief the source operation, can be None */\n  Operation op;\n  /*! \\brief the output index from source operation */\n  int value_index{0};\n  /*! \\brief constructor */\n  TensorNode() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"shape\", &shape);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"op\", &op);\n    v->Visit(\"value_index\", &value_index);\n  }\n\n  Array<PrimExpr> GetShape() const final { return shape; }\n\n  DataType GetDataType() const final { return dtype; }\n\n  TVM_DLL String GetNameHint() const final;\n\n  static constexpr const char* _type_key = \"Tensor\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorNode, DataProducerNode);\n};\n\n/*!\n * \\brief Tensor structure representing a possible input,\n *  or intermediate computation result.\n */\nclass Tensor : public DataProducer {\n private:\n  /*!\n   * \\brief Helper for indexing operations into tensors\n   * \\param indices The indices\n   * \\param support_negative_indices Whether to normalize indices in the case of negative indices.\n   * \\return the result expression representing tensor read.\n   */\n  inline PrimExpr IndexTensor(Array<PrimExpr> indices, bool support_negative_indices) const;\n\n public:\n  TVM_DLL Tensor(Array<PrimExpr> shape, DataType dtype, Operation op, int value_index);\n  /*!\n   * \\brief check if two tensors equals each other.\n   * \\param other tensor to be checked.\n   * \\return whether the two tensors equals each other.\n   */\n  inline bool operator==(const Tensor& other) const;\n  /*!\n   * \\brief check if two tensors are different.\n   * \\param other tensor to be checked.\n   * \\return whether the two tensors are different.\n   */\n  inline bool operator!=(const Tensor& other) const;\n  /*! \\return The dimension of the tensor */\n  inline size_t ndim() const;\n  /*!\n   * \\brief Take elements from the tensor\n   * \\param args The indices\n   * \\return the result expression representing tensor read.\n   */\n  template <typename... Args>\n  inline PrimExpr operator()(Args&&... args) const {\n    Array<PrimExpr> indices{std::forward<Args>(args)...};\n    return operator()(indices);\n  }\n  /*!\n   * \\brief Take elements from the tensor\n   * \\param indices the indices.\n   * \\return the result expression representing tensor read.\n   */\n  TVM_DLL PrimExpr operator()(Array<PrimExpr> indices) const;\n  /*!\n   * \\brief Take elements from the tensor\n   * \\param indices the indices.\n   * \\return the result expression representing tensor read.\n   */\n  TVM_DLL PrimExpr operator()(Array<Var> indices) const;\n  /*!\n   * \\brief Take elements from the tensor with support for negative indices.\n   * \\param args The indices\n   * \\return the result expression representing tensor read.\n   */\n  template <typename... Args>\n  TVM_DLL PrimExpr IndexWithNegativeIndices(Args&&... args) const {\n    Array<PrimExpr> indices{std::forward<Args>(args)...};\n    return IndexWithNegativeIndices(indices);\n  }\n  /*!\n   * \\brief Take elements from the tensor with support for negative indices.\n   * \\param indices the indices.\n   * \\return the result expression representing tensor read.\n   */\n  TVM_DLL PrimExpr IndexWithNegativeIndices(Array<PrimExpr> indices) const;\n  /*!\n   * \\brief Take elements from the tensor with support for negative indices.\n   * \\param indices the indices.\n   * \\return the result expression representing tensor read.\n   */\n  TVM_DLL PrimExpr IndexWithNegativeIndices(Array<Var> indices) const;\n\n  /*!\n   * \\brief data structure to represent a slice that fixes first k coordinates.\n   *  This is used to enable syntax sugar of Tensor[x][y][z] to get the element.\n   */\n  class Slice {\n   public:\n    // construct via tensor and indices\n    Slice(const Tensor& tensor, std::vector<PrimExpr> indices)\n        : tensor_(tensor), indices_(indices) {}\n    /*!\n     * \\brief get i-th slice from the current slice.\n     * \\param i the index of the coordinate\n     * \\return the subsequent slice.\n     */\n    inline Slice operator[](PrimExpr i) {\n      std::vector<PrimExpr> other = indices_;\n      other.emplace_back(i);\n      return Slice(tensor_, other);\n    }\n    /*!\n     * \\brief Convert slice to expression.\n     *  This is only valid when all the coordinates are fully specified.\n     * \\return the corresponding expression of this slice.\n     */\n    inline operator PrimExpr() const { return tensor_(indices_); }\n\n   private:\n    const Tensor& tensor_;\n    std::vector<PrimExpr> indices_;\n  };\n  /*!\n   * \\brief get i-th slice from the current Tensor.\n   * \\param i the index of the coordinate\n   * \\return the subsequent slice.\n   */\n  inline Slice operator[](PrimExpr i) const { return Slice(*this, {i}); }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Tensor, DataProducer, TensorNode);\n};\n\n// Implementations of inline functions\ninline size_t Tensor::ndim() const { return (*this)->shape.size(); }\n\ninline bool Tensor::operator==(const Tensor& other) const {\n  if (get() == other.get()) return true;\n  if (get() == nullptr || other.get() == nullptr) return false;\n  if ((*this)->op.defined() || other->op.defined()) {\n    return (*this)->op == other->op && (*this)->value_index == other->value_index;\n  } else {\n    return false;\n  }\n}\n\ninline bool Tensor::operator!=(const Tensor& other) const { return !(*this == other); }\n\n// macro to turn every operation of slice to expression\n#define DEFINE_OVERLOAD_SLICE_UNARY_OP(Op) \\\n  inline PrimExpr operator Op(const Tensor::Slice& a) { return Op a.operator PrimExpr(); }\n\n#define DEFINE_OVERLOAD_SLICE_BINARY_OP(Op)                                     \\\n  template <typename T>                                                         \\\n  inline PrimExpr operator Op(const Tensor::Slice& a, const T& b) {             \\\n    return a.operator PrimExpr() Op b;                                          \\\n  }                                                                             \\\n  template <typename T>                                                         \\\n  inline PrimExpr operator Op(const T& a, const Tensor::Slice& b) {             \\\n    return a Op b.operator PrimExpr();                                          \\\n  }                                                                             \\\n  inline PrimExpr operator Op(const Tensor::Slice& a, const Tensor::Slice& b) { \\\n    return a.operator PrimExpr() Op b.operator PrimExpr();                      \\\n  }\n\nDEFINE_OVERLOAD_SLICE_UNARY_OP(!);\nDEFINE_OVERLOAD_SLICE_UNARY_OP(-);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(+);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(-);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(*);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(==);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(<=);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(>=);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(!=);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(&&);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(||);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(>>);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(<<);\nDEFINE_OVERLOAD_SLICE_BINARY_OP(>);  // NOLINT(*)\nDEFINE_OVERLOAD_SLICE_BINARY_OP(<);  // NOLINT(*)\n\n}  // namespace te\n}  // namespace tvm\n\nnamespace std {\ntemplate <>\nstruct hash<::tvm::te::Operation> : public ::tvm::ObjectPtrHash {};\n\ntemplate <>\nstruct hash<::tvm::te::Tensor> {\n  std::size_t operator()(const ::tvm::te::Tensor& k) const {\n    ::tvm::ObjectPtrHash hasher;\n    if (k.defined() && k->op.defined()) {\n      return hasher(k->op);\n    } else {\n      return hasher(k);\n    }\n  }\n};\n}  // namespace std\n#endif  // TVM_TE_TENSOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/te/tensor_intrin.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/te/tensor_intrin.h\n * \\brief Tensor intrinsic operations.\n */\n#ifndef TVM_TE_TENSOR_INTRIN_H_\n#define TVM_TE_TENSOR_INTRIN_H_\n\n#include <tvm/te/tensor.h>\n#include <tvm/tir/buffer.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace te {\n\n/*! \\brief Node to represent a Tensor intrinsic operator */\nclass TensorIntrinNode : public Object {\n public:\n  /*! \\brief The name of the intrinsic */\n  std::string name;\n  /*! \\brief The operation this intrinsics is carrying out */\n  Operation op;\n  /*! \\brief List of inputs of operator, placeholder in postdfs order */\n  Array<Tensor> inputs;\n  /*!\n   * \\brief Symbolic buffers of each output/input tensor\n   *  buffers[0:len(inputs)] are buffers of the inputs.\n   *  buffers[len(inputs):] are buffers of each output.\n   *\n   * \\note When a field in Buffer is Var, it means we can be flexible\n   *  wrt that field and Var can occur in body.\n   *  When it is a constant, it means we can only take data in that shape.\n   */\n  Array<Buffer> buffers;\n  /*! \\brief List of scalar variables, used in body. These placeholders\n   *  will be bound to expressions passed in when the TensorIntrin is called\n   * from a TensorComputeOp.\n   */\n  Array<Var> scalar_params;\n  /*! \\brief The normal statement to execute the intrinsic */\n  Stmt body;\n  /*!\n   * \\brief Special statement for reduction op, can be None\n   *  reset the value of output buffer to identity value.\n   */\n  Stmt reduce_init;\n  /*!\n   * \\brief Special statement for reduction op, can be None\n   *  Reduce: do a reduction of current output buffer with the result.\n   */\n  Stmt reduce_update;\n  /*! \\brief constructor */\n  TensorIntrinNode() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"op\", &op);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"buffers\", &buffers);\n    v->Visit(\"scalar_params\", &scalar_params);\n    v->Visit(\"body\", &body);\n    v->Visit(\"reduce_init\", &reduce_init);\n    v->Visit(\"reduce_update\", &reduce_update);\n  }\n\n  static constexpr const char* _type_key = \"TensorIntrin\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorIntrinNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TensorIntrinNode\n * \\sa TensorIntrinNode\n */\nclass TensorIntrin : public ObjectRef {\n public:\n  TVM_DLL TensorIntrin(std::string name, Operation op, Array<Tensor> inputs, Array<Buffer> buffers,\n                       Array<Var> scalar_params, Stmt body, Stmt reduce_init, Stmt reduce_update);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorIntrin, ObjectRef, TensorIntrinNode);\n};\n\nclass TensorIntrinCallNode : public Object {\n public:\n  /*! \\brief the tensor intrinsic */\n  TensorIntrin intrin;\n  /*! \\brief input tensors of the intrinsic */\n  Array<Tensor> tensors;\n  /*! \\brief regions of input tensors */\n  Array<Region> regions;\n\n  /*!\n   * \\brief IterVar on each reduction axis, if the\n   * intrin will use the reduce axis\n   */\n  Array<IterVar> reduce_axis;\n\n  /*! \\brief scalar expression inputs */\n  Array<PrimExpr> scalar_inputs;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"intrin\", &intrin);\n    v->Visit(\"tensors\", &tensors);\n    v->Visit(\"regions\", &regions);\n    v->Visit(\"reduce_axis\", &reduce_axis);\n    v->Visit(\"scalar_inputs\", &scalar_inputs);\n  }\n\n  static constexpr const char* _type_key = \"TensorIntrinCall\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorIntrinCallNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TensorIntrinCallNode\n * \\sa TensorIntrinCallNode\n */\nclass TensorIntrinCall : public ObjectRef {\n public:\n  TVM_DLL TensorIntrinCall(TensorIntrin intrin, Array<Tensor> tensors, Array<Region> regions,\n                           Array<IterVar> reduce_axis, Array<PrimExpr> scalar_inputs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorIntrinCall, ObjectRef, TensorIntrinCallNode);\n};\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_TENSOR_INTRIN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/analysis.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/analysis.h\n * \\brief Analysis utilities and passes for TIR.\n */\n#ifndef TVM_TIR_ANALYSIS_H_\n#define TVM_TIR_ANALYSIS_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/ir/transform.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op_attr_types.h>\n#include <tvm/tir/stmt.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Compare two expressions recursively and check if they are equal\n *        to each other without var remapping.\n *\n *  This function does not remap variable bindings, it will not\n *  return true for (let x = 1 in x + 1) vs (let y = 1 in y + 1), unless x.same_as(y).\n *\n *  Use StructuralEqual for such cases.\n *\n *  Due to the restriction of not remapping variables, this function can run\n *  faster than StructuralEqual and can be used as a utility function during arithmetic\n *  simplifications.\n *\n * \\sa StructuralEqual\n */\nstruct ExprDeepEqual {\n public:\n  TVM_DLL bool operator()(const PrimExpr& lhs, const PrimExpr& rhs) const;\n};\n\n/*!\n * \\brief Visit the PrimFuncs in the IRModule\n * \\tparam FLambda The type of the PrimFunc visitor\n * \\param mod The IRModule to be visited\n * \\param fvisit The visitor to the PrimFuncs in the IRModule\n */\ntemplate <class FLambda>\ninline void VisitPrimFuncs(const IRModule& mod, FLambda fvisit) {\n  for (const auto& kv : mod->functions) {\n    const BaseFunc& base_func = kv.second;\n    if (const auto* prim_func = base_func.as<PrimFuncNode>()) {\n      fvisit(prim_func);\n    }\n  }\n}\n\n/*!\n * \\brief Estimate the FLOPs of a TIR fragment.\n * \\param stmt The TIR fragment to be estimated.\n * \\return The estimated FLOPs.\n */\nTVM_DLL double EstimateTIRFlops(const Stmt& stmt);\n\n/*!\n * \\brief Estimate the FLOPs of TIRs in an IRModule.\n * \\param mod The IRModule to be estimated.\n * \\return The estimated FLOPs.\n */\nTVM_DLL double EstimateTIRFlops(const IRModule& mod);\n\n/*!\n * \\brief Find undefined vars in the statement.\n * \\param stmt The function to be checked.\n * \\param defs The vars that is defined.\n * \\return Array of undefined vars.\n */\nTVM_DLL Array<Var> UndefinedVars(const Stmt& stmt, const Array<Var>& defs);\n\n/*!\n * \\brief Find undefined vars in the expression.\n * \\param expr The expression to be checked.\n * \\return Array of undefined vars.\n */\nTVM_DLL Array<Var> UndefinedVars(const PrimExpr& expr);\n\n/*!\n * \\brief Analyze the side effect\n * \\param expr The expression to be checked.\n *\n * \\return CallEffectKind, can be kPure, kReadState or kUpdateState\n */\nTVM_DLL CallEffectKind SideEffect(const PrimExpr& expr);\n\n/*!\n * \\brief Whether the given Stmt uses any var in the given variable set.\n * \\param stmt The Stmt to be checked.\n * \\param vset_contains The check function to see if a var is in the variable set.\n * \\return Whether `stmt` uses any var in the given variable set.\n */\nTVM_DLL bool UsesVar(const Stmt& stmt, std::function<bool(const VarNode*)> vset_contains);\n\n/*!\n * \\brief Whether the given PrimExpr uses any var in the given variable set.\n * \\param expr The PrimExpr to be checked.\n * \\param vset_contains The check function to see if var is in the variable set.\n * \\return Whether `expr` uses any var in the given variable set.\n */\nTVM_DLL bool UsesVar(const PrimExpr& expr, std::function<bool(const VarNode*)> vset_contains);\n\n/*!\n * \\brief Verifies whether the IR stmt or Expr is in SSA form.\n *  That is: each Var is defined and assigned once(in Let/For)\n *\n * \\param func The function to be verified.\n * \\return Whether IR is in SSA form.\n *\n * \\note All passes in TIR consume and produce SSA form.\n */\nTVM_DLL bool VerifySSA(const PrimFunc& func);\n\n/*!\n * \\brief Verify if memory accesses are legal for a specific target device type.\n *\n *  In the case that tgt is cuda, if not all workload is bound with\n *  threads, CPU code is generated that tries to access GPU memory,\n *  which is illegal. This pass performs verification for this case.\n *\n * \\param func The function to be verified.\n * \\return Success of memory verification.\n */\nTVM_DLL bool VerifyMemory(const PrimFunc& func);\n\n/*!\n * \\brief Verify the correctness of a GPU code\n *        It will check the whether the amount of memory usage or the number of threads\n *        in a block exceeds the limit\n * \\param func The function to be checked\n * \\param constraints The dict to specify constraints to check.\n *        Possible keys are\n *\n *        \"max_local_memory_per_block\": Total amount of local memory per block (in bytes).\n *        \"max_shared_memory_per_block\": Total amount of shared memory per block (in bytes).\n *        \"max_threads_per_block\": Maximum number of threads per block.\n *        \"max_thread_x\": Maximum length of threadIdx.x.\n *        \"max_thread_y\": Maximum length of threadIdx.y.\n *        \"max_thread_z\": Maximum length of threadIdx.z.\n *\n *        If one key is missing in this argument, the pass won't check for that item.\n * \\return valid Whether it is a valid GPU code\n *\n */\nTVM_DLL bool VerifyGPUCode(const PrimFunc& func, Map<String, PrimExpr> constraints);\n\n/*!\n * \\brief Auto detect the block access region according to its body stmt\n *        It will detect the access region as an array in order of appearance in AST\n * \\param block The block to be detected\n * \\param buffer_var_map The outside buffers which may be accessed the block.\n *                       It is a map from buffer var to the buffer.\n * \\return Array of access regions.\n *         There are three arrays of BufferRegion:\n *           - first: read regions\n *           - second: write regions\n *           - third: opaque regions\n */\nTVM_DLL Array<Array<BufferRegion>> GetBlockAccessRegion(const Block& block,\n                                                        const Map<Var, Buffer>& buffer_var_map);\n\n/*!\n * \\brief Auto detect the block read/write region according to its body stmt. An opaque access will\n *        be counted as both a read and a write access\n * \\param block The block to be detected\n * \\param buffer_var_map The outside buffers which may be accessed the block.\n *                       It is a map from buffer var to the buffer\n * \\return An array only consisting of the read regions and write regions of the input block\n */\nTVM_DLL Array<Array<BufferRegion>> GetBlockReadWriteRegion(const Block& block,\n                                                           const Map<Var, Buffer>& buffer_var_map);\n\n/*!\n * \\brief Calculate the expresion complexity based on number of symbols it contains.\n * \\param expr The expr to be calculated.\n */\nTVM_DLL size_t CalculateExprComplexity(const PrimExpr& expr);\n\n/*!\n * \\brief Calculate the constants size in bytes needed by the TIR allocates inside the TIR PrimFunc\n * \\param func The TIR PrimFunc for which the constants size to be calculated\n * \\param constant_byte_alignment The byte alignment required for each constant allocated\n */\nTVM_DLL size_t CalculateConstantBytes(const PrimFunc& func, const Integer& constant_byte_alignment);\n\n/*!\n * \\brief Calculate the workspace size in bytes needed by the TIR allocates inside the TIR PrimFunc\n * \\param func The TIR PrimFunc for which the workspace size to be calculated\n * \\param workspace_byte_alignment The byte alignment required for each tensor allocated in this\n * workspace\n */\nTVM_DLL size_t CalculateWorkspaceBytes(const PrimFunc& func,\n                                       const Integer& workspace_byte_alignment);\n\n/*!\n * \\brief Detect the lowest common ancestor(LCA) of buffer access, including both high-level\n *        access(BufferLoad, BufferStore) and low-level access(Load, Store and opaque access).\n *        The LCA may be a For loop or a Block.\n * \\param func The PrimFunc to be detected.\n * \\return The Map from buffer to the LCA of all access to it. The lca is function root if the\n *         return stmt is NullOpt.\n */\nTVM_DLL Map<Buffer, Optional<Stmt>> DetectBufferAccessLCA(const PrimFunc& func);\n\n/*!\n * \\brief Verify if the given TIR is well-formed. The verification includes:\n *        - Check if expressions not contain vars that is defined outside the block.\n * \\param func The PrimFunc to be verified.\n * \\param assert_mode The indicator if it raises an error when the function is not well-formed.\n * \\return Whether it is a well-formed TIR function.\n */\nTVM_DLL bool VerifyWellFormed(const PrimFunc& func, bool assert_mode = true);\n\n/*!\n * \\brief Find the entry function of the given IRModule, i.e, functions marked by\n * `tir::attr::kIsEntryFunc`, whose name is `main` or being the only PrimeFunc.\n * \\param mod The IRModule to find the entry function.\n * \\param result_g_var The result GlobalVar of the entry function.\n * \\return The entry function.\n */\nconst PrimFuncNode* FindEntryFunc(const IRModule& mod, GlobalVar* result_g_var);\n\n/*!\n * \\brief Find the \"anchor block\" of the given module.\n * We define the anchor block to be the block with (1) an init statement and (2) having\n * the biggest flops count. The latter condition is only used when there are multiple blocks\n * with an init statement.\n * For example, if the input module is conv2d + fused spatial blocks, conv2d is the anchor block.\n * The input module may not contain more than one such block. For example, a module having\n * two conv2d is not allowed as an input.\n * However, a module created from winograd convolution has multiple blocks with an init statement\n * (input transform, batched GEMM, and output transform). We use the second condition, the flops\n * count, to determine that the batched GEMM block is the anchor block.\n * \\param mod The input TIR module.\n * \\return The anchor block if found, nullptr otherwise.\n */\nconst tir::BlockNode* FindAnchorBlock(const IRModule& mod);\n\n// Pass variants of verification analysis\n// directly throws RuntimeError when verification fails.\nnamespace transform {\n\nusing tvm::transform::Pass;\nusing tvm::transform::PassContext;\n\n/*!\n * \\brief Pass variant of VerifySSA.\n *\n * \\returns The pass.\n * \\sa tvm::tir::VerifySSA\n */\nTVM_DLL Pass VerifySSA();\n\n/*!\n * \\brief Pass variant of VerifyMemory.\n *\n * \\returns The pass.\n * \\sa tvm::tir::VerifyMemory\n */\nTVM_DLL Pass VerifyMemory();\n\n/*!\n * \\brief Pass variant of VerifyGPUCode.\n *\n * \\param constraints The dict to specify constraints to check.\n *\n * \\returns The pass.\n * \\sa tvm::tir::VerifyGPUCode\n */\nTVM_DLL Pass VerifyGPUCode(Map<String, PrimExpr> constraints);\n\n/*!\n * \\brief Statically check TIR code for out of bounds array access.\n *\n * This analysis is conservative: it will only raise errors if it can prove\n * that out of bounds access occurs. Cases that are uncertain do not raise\n * errors.\n *\n * \\returns The pass.\n */\nTVM_DLL Pass OOBChecker();\n\n}  // namespace transform\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_ANALYSIS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/buffer.h\n * \\brief Symbolic n-dimensional array, to represent a memory buffer.\n */\n#ifndef TVM_TIR_BUFFER_H_\n#define TVM_TIR_BUFFER_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/tir/var.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace tir {\n\n// forward declare Stmt\nclass Stmt;\n\n/*! \\brief buffer type */\nenum BufferType : int {\n  kDefault = 1,\n  // Maps buffer[i][j][k] -> buffer[i][0][k] if dimension i's shape equals 1.\n  kAutoBroadcast = 2,\n};\n\n/*! \\brief Node to represent a buffer */\nclass BufferNode : public Object {\n public:\n  // Data fields.\n  /*!\n   * \\brief The pointer to the head of the data\n   * \\sa data_alignment The alignment of data in bytes.\n   */\n  Var data;\n  /*! \\brief data type in the content of the tensor */\n  DataType dtype;\n  /*! \\brief The type of the buffer prior to flattening\n   *\n   * This contains the shape as it is accessed by\n   * BufferLoad/BufferStore nodes, and used by the low-level code\n   * generators.\n   */\n  Array<PrimExpr> shape;\n  /*!\n   * \\brief Separators between input axes when generating flattened output axes\n   *\n   * For buffers representing flat 1-d memory (e.g. any buffer in\n   * RAM), this should be an empty array.  For buffers representing\n   * non-flat memory, each entry in axis_separators should be the\n   * first input axis that is part of a new flattened axis.\n   */\n  Array<IntImm> axis_separators;\n  /*!\n   * \\brief The strides of each dimension\n   *  This can be an empty array, indicating array is contiguous\n   */\n  Array<PrimExpr> strides;\n  /*! \\brief The offset in terms of number of dtype elements (including lanes) */\n  PrimExpr elem_offset;\n  // Meta data\n  /*! \\brief optional name of the buffer */\n  String name;\n  /*! \\brief Alignment requirement of data pointer in bytes. */\n  int data_alignment;\n  /*!\n   * \\brief Factor of elem_offset field,\n   *  elem_offset is guaranteed to be multiple of offset_factor.\n   */\n  int offset_factor;\n  /*! \\brief buffer type */\n  BufferType buffer_type;\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n  /*! \\brief constructor */\n  BufferNode() {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"data\", &data);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"shape\", &shape);\n    v->Visit(\"strides\", &strides);\n    v->Visit(\"axis_separators\", &axis_separators);\n    v->Visit(\"elem_offset\", &elem_offset);\n    v->Visit(\"name\", &name);\n    v->Visit(\"data_alignment\", &data_alignment);\n    v->Visit(\"offset_factor\", &offset_factor);\n    v->Visit(\"buffer_type\", &buffer_type);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const BufferNode* other, SEqualReducer equal) const {\n    // Use DefEqual as buffer can define variables in its semantics,\n    // skip name as name is not important.\n    return equal.DefEqual(data, other->data) && equal(dtype, other->dtype) &&\n           equal.DefEqual(shape, other->shape) && equal.DefEqual(strides, other->strides) &&\n           equal.DefEqual(axis_separators, other->axis_separators) &&\n           equal.DefEqual(elem_offset, other->elem_offset) &&\n           equal(data_alignment, other->data_alignment) && equal(buffer_type, other->buffer_type);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(data);\n    hash_reduce(dtype);\n    hash_reduce.DefHash(shape);\n    hash_reduce.DefHash(strides);\n    hash_reduce.DefHash(elem_offset);\n    hash_reduce.DefHash(axis_separators);\n    hash_reduce(data_alignment);\n    hash_reduce(buffer_type);\n  }\n\n  /*! \\return preferred index type for this buffer node */\n  DataType DefaultIndexType() const {\n    return shape.size() != 0 ? shape[0].dtype() : DataType::Int(32);\n  }\n\n  /*! \\brief Determine the offset in the buffer of the given index.\n   *\n   * Returns the buffer offset, in number of elements of type dtype,\n   * without adjusting for number of lanes.  (e.g. The number of\n   * float16x4 elements in a buffer of type float16x4.)\n   */\n  Array<PrimExpr> ElemOffset(Array<PrimExpr> index) const;\n\n  static constexpr const char* _type_key = \"tir.Buffer\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferNode, Object);\n};\n\n/*!\n * \\brief Buffer is a symbolic n-darray structure.\n *  It is a composition of primitive symbolic types,\n *  used to specify the memory layout of the Tensor used in program input.\n */\nclass Buffer : public ObjectRef {\n public:\n  // User can specify data_alignment and offset_factor to be 0\n  // A default value will be picked.\n  TVM_DLL Buffer(Var data, DataType dtype, Array<PrimExpr> shape, Array<PrimExpr> strides,\n                 PrimExpr elem_offset, String name, int data_alignment, int offset_factor,\n                 BufferType buffer_type, Array<IntImm> axis_separators = {}, Span span = Span());\n\n  /*!\n   * \\brief Return a new buffer that is equivalent with current one\n   *  but always add stride field.\n   * \\return The strided version of the buffer.\n   */\n  TVM_DLL Buffer MakeStrideView() const;\n  /*!\n   * \\brief Make a new symbolic buffer representing a slice of the buffer.\n   * \\param begins The beginning position of each dimension.\n   * \\param extents The extent of each dimension.\n   * \\note This function will make target buffer as compact as possible.\n   *  If stride is not needed in the slice, it won't be presented\n   * \\return the result buffer.\n   */\n  TVM_DLL Buffer MakeSlice(Array<PrimExpr> begins, Array<PrimExpr> extents) const;\n  /*!\n   * \\brief Get access ptr to the entire buffer.\n   * \\param access_mask The access mask\n   * \\param ptr_type The type of the pointer.\n   * \\param content_lanes The number of lanes for the (data) type.\n   * \\param offset The offset of ptr.\n   * \\param input_extent The extent of ptr.\n   */\n  TVM_DLL PrimExpr access_ptr(int access_mask, DataType ptr_type = DataType::Handle(),\n                              int content_lanes = 1, PrimExpr offset = IntImm(DataType::Int(32), 0),\n                              Optional<PrimExpr> input_extent = NullOpt) const;\n  /*!\n   * \\brief Create an Expr that does a vector load at begin index.\n   * \\param begin The beginning index\n   * \\param dtype The data type to be loaded.\n   */\n  TVM_DLL PrimExpr vload(Array<PrimExpr> begin, DataType dtype) const;\n  /*!\n   * \\brief Create a Stmt that does a vector store at begin index.\n   * \\param begin The beginning index\n   * \\param value The value to be stored.\n   */\n  TVM_DLL Stmt vstore(Array<PrimExpr> begin, PrimExpr value) const;\n\n  /*!\n   * \\brief Get a flattened version of the buffer\n   */\n  Buffer GetFlattenedBuffer() const;\n\n  /*! \\brief Determine the offset in the buffer of the given index.\n   *\n   * Returns the buffer offset, in number of elements of type dtype,\n   * without adjusting for number of lanes.  (e.g. The number of\n   * float16x4 elements in a buffer of type float16x4.)\n   */\n  Array<PrimExpr> OffsetOf(Array<PrimExpr> index) const;\n\n  /*!\n   * \\brief Return the storage scope associated with this buffer.\n   */\n  TVM_DLL String scope() const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Buffer, ObjectRef, BufferNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BufferNode);\n};\n\n/*!\n * \\brief Construct a new buffer given shape, and dtype.\n * \\param shape The shape of the buffer,\n * \\param dtype The content data type.\n * \\param name The name of the buffer\n * \\param storage_scope The storage scope associated with this buffer\n * \\param axis_separators Divisions defining the groups of axes that will be flattened together.\n * \\param span The location of this object in the source code.\n * \\return The created buffer.\n * \\sa Buffer for complete constructor.\n */\nTVM_DLL Buffer decl_buffer(Array<PrimExpr> shape, DataType dtype = DataType::Float(32),\n                           String name = \"buffer\", String storage_scope = \"\",\n                           Array<IntImm> axis_separators = {}, Span span = Span());\n\n/*!\n * \\brief Base node for data producers.\n *\n *  A DataProducer stores necessary information(e.g. a tensor expression) to produce\n *  a multi-dimensional array. The stored information is opaque to the TIR.\n *  DataProducer can appear in high-level DSLs that are built on top of the TIR.\n *\n *  A valid TIR PrimFunc should not contain any DataProducer, high level DSLs should lower\n *  all DataProducers to Buffers before TIR transformations.\n *\n * \\sa tvm::te::Tensor\n */\nclass DataProducerNode : public Object {\n public:\n  /*! \\brief destructor. */\n  virtual ~DataProducerNode() {}\n  /*!\n   * \\brief Get the shape of the result.\n   * \\return The shape.\n   */\n  virtual Array<PrimExpr> GetShape() const = 0;\n  /*!\n   * \\brief Get the data type of the result.\n   * \\return The data type.\n   */\n  virtual DataType GetDataType() const = 0;\n  /*!\n   * \\brief Get the name hint of the data producer.\n   * \\return The data type.\n   */\n  virtual String GetNameHint() const = 0;\n\n  bool SEqualReduce(const DataProducerNode* other, SEqualReducer equal) const {\n    // because buffer producer is opaque, we just do pointer equality.\n    return this == other;\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {}\n\n  static constexpr const char* _type_key = \"tir.DataProducer\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_BASE_OBJECT_INFO(DataProducerNode, Object);\n};\n\n/*!\n * \\brief Managed reference to DataProducerNode.\n * \\sa DataProducerNode\n */\nclass DataProducer : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(DataProducer, ObjectRef, DataProducerNode);\n};\n\n/*!\n * \\brief Creates TIR Buffer for provided parameters\n * \\param shape shape of the buffer\n * \\param dtype data type\n * \\param name buffer name\n * \\param data_alignment alignment requirement of data pointer in bytes\n * \\param offset_factor Factor of elem_offset field, elem_offset is guaranteed to be\n *                      multiple of offset_factor\n                        User can specify data_alignment and offset_factor to be 0\n *                      A default value will be picked.\n * \\param compact If the statement has already bound to a compact buffer.\n * \\param memory_scope memory scope of the buffer\n */\nTVM_DLL tir::Buffer BufferWithOffsetAlignment(Array<PrimExpr> shape, DataType dtype,\n                                              std::string name, int data_alignment,\n                                              int offset_factor, bool compact,\n                                              std::string memory_scope = \"\");\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/builtin.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/builtin.h\n * \\brief TIR builtin intrinsics.\n *\n * TIR builtin intrinsics are stored as tvm:Op.\n * They are processed in the same way as we process Ops.\n *\n * It is not necessary to create a function for every Op,\n * as we can obtain them through Op::Get.\n *\n * This file contains the most commonly used intrinsics or\n * those that have special semantics and need compiler support.\n */\n#ifndef TVM_TIR_BUILTIN_H_\n#define TVM_TIR_BUILTIN_H_\n\n#include <tvm/ir/op.h>\n#include <tvm/tir/expr.h>\n\nnamespace tvm {\nnamespace tir {\n\n/*! \\brief Collection of builtin intrinsics as ops */\nnamespace builtin {\n/*!\n * \\brief Return value.\n */\nTVM_DLL const Op& ret();\n/*!\n * \\brief Reinterpret the value using the target type.\n */\nTVM_DLL const Op& reinterpret();\n\n/*!\n * \\brief Marks a condition is likely going to happen.\n */\nTVM_DLL const Op& likely();\n\n/*!\n * \\brief Bitwise and operator.\n */\nTVM_DLL const Op& bitwise_and();\n\n/*!\n * \\brief Bitwise or operator.\n */\nTVM_DLL const Op& bitwise_or();\n\n/*!\n * \\brief Bitwise xor operator.\n */\nTVM_DLL const Op& bitwise_xor();\n\n/*!\n * \\brief Bitwise not operator.\n */\nTVM_DLL const Op& bitwise_not();\n\n/*!\n * \\brief Left shift\n */\nTVM_DLL const Op& shift_left();\n\n/*!\n * \\brief Right shift\n */\nTVM_DLL const Op& shift_right();\n\n/*!\n * \\brief See pesudo code\n *\n *  Construct a big uint that may not be representable by int64\n *\n *  Expr large_uint_imm(uint32_t v0, uin32_t v1) {\n *    return (v1 << 32) | v0;\n *  }\n */\nTVM_DLL const Op& large_uint_imm();\n\n/*!\n * \\brief Execute a multiplication between two Q-numbers x and y\n * followed by a right shift s\n * The default rounding rule is to the nearest value, rounding half up\n * (i.e., round(x.1) = x and round (x.5) = x+1)\n */\nTVM_DLL const Op& q_multiply_shift();\n\n/*!\n * \\brief Returns the address of an element in the buffer (see pseudocode below).\n *\n * The number of indices should match the dimensionality of the buffer\n * being accessed.  If this operation occurs after buffer flattening,\n * the number of indices must be supported by the target (i.e. N>1\n * only on targets that support non-flat memory buffers).\n *\n *  Handle address_of(BufferLoad *op) {\n *     return &op->buffer_var[op->indices[0], op->indices[1], ..., op->indices[N-1]];\n *  }\n */\nTVM_DLL const Op& address_of();\n\n/*!\n * \\brief Same as select, used for unsafe memory access.\n *\n *  Type tvm_if_then_else(cond, a, b) {\n *    return cond ? a : b;\n *  }\n */\nTVM_DLL const Op& if_then_else();\n\n/*!\n * \\brief See pesudo code\n *\n *  bool isnullptr(void* handle) {\n *     return handle == nullptr\n *  }\n */\nTVM_DLL const Op& isnullptr();\n\n/*!\n * \\brief Check if value is nan\n */\nTVM_DLL const Op& isnan();\n\n/*!\n * \\brief Popcount\n */\nTVM_DLL const Op& popcount();\n\n/*!\n * \\brief Fused multiply add\n *\n *  Type fma(a, b, c) {\n *    return a * b + c;\n *  }\n */\nTVM_DLL const Op& fma();\n\n/*!\n * \\brief Call an extern C function with given name\n *        and signature from the types of args in the runtime environment.\n *\n *  Type call_extern(name, args...) {\n *     return dlsym(name)(args...);\n *  }\n *\n * \\note This intrinsic does not provide any type checking,\n *       and is main used for backward compatibility reasons.\n *       Always consider use pre-registered and typed tvm::Op first.\n */\nTVM_DLL const Op& call_extern();\n\n/*!\n * \\brief Call an pure extern C function with given name\n *        and signature from the types of args in the runtime environment.\n *\n *  Type call_pure_extern(name, args...) {\n *     return dlsym(name)(args...);\n *  }\n *\n * \\note This intrinsic does not provide any type checking,\n *       and is main used for backward compatibility reasons.\n *       Always consider use pre-registered and typed tvm::Op first.\n */\nTVM_DLL const Op& call_pure_extern();\n\n/*!\n * \\brief Call an LLVM intrinsic with a given intrinsic id\n *        and signature from the types of args in the runtime environment.\n *\n *  Type call_llvm_pure_intrin(intrin_id, args...) {\n *     return dlsym(name)(args...);\n *  }\n *\n * \\note This op does not provide any type checking.\n */\nTVM_DLL const Op& call_llvm_intrin();\n\n/*!\n * \\brief Call an LLVM pure intrinsic with a given intrinsic id\n *        and signature from the types of args in the runtime environment.\n *\n *  Type call_llvm_pure_intrin(intrin_id, args...) {\n *     return dlsym(name)(args...);\n *  }\n *\n * \\note This op does not provide any type checking.\n */\nTVM_DLL const Op& call_llvm_pure_intrin();\n\n/*!\n * \\brief Call an SPIRV pure GLSL450 intrinsic.\n *\n *  Type call_spirv_pure_glsl450(intrin_id, args...) {\n *     return dlsym(name)(args...);\n *  }\n *\n * \\note This op does not provide any type checking.\n */\nTVM_DLL const Op& call_spirv_pure_glsl450();\n\n// TODO(tvm-team) revisit the builtins below\n// some of them can simply become ops with special codegen attr.\n/*!\n * \\brief Prefetch a cacheline\n */\nTVM_DLL const Op& prefetch();\n\n/*!\n * \\brief Get head access address with memory access pattern info.\n *\n *  This operator also marks range of the memory access\n *  The offset and extent are in unit of the DType(including vectorization factor).\n *  rw_mask is a bit_mask setting whether the access is a read(1) or write(2).\n *  The access is assume to happen in the current expression.\n *\n *  PtrType tvm_access_ptr(Expr dtype, DType* data,\n *                         int offset, int extent,\n *                         int rw_mask) {\n *    // DType == dtype.type();\n *    return &data[offset];\n *  }\n */\nTVM_DLL const Op& tvm_access_ptr();\n\n/*!\n * \\brief Create a function local static handle that iniitalizes to nullptr.\n *  can be used to cache function local static resources.\n */\nTVM_DLL const Op& tvm_static_handle();\n\n/*!\n * \\brief Return a unique context id, used for hint of workspace separation.\n *  Different context id ganrantees not having overlapping workspace.\n */\nTVM_DLL const Op& tvm_context_id();\n\n/*!\n * \\brief tvm_tuple is not an actual function and cannot codegen.\n *  It is used to represent tuple structure in value field of AttrStmt,\n *  for the sake of giving hint to optimization.\n *\n *  Handle tvm_tuple(value0, value1, ..., value_n);\n */\nTVM_DLL const Op& tvm_tuple();\n\n/*!\n * \\brief See pesudo code\n *\n *  Type tvm_struct_get(StructType* arr, int index, int field_id) {\n *     return arr[index]->field;\n *  }\n * \\sa TVMStructFieldKind\n */\nTVM_DLL const Op& tvm_struct_get();\n\n/*!\n * \\brief See pesudo code\n *\n *  Handle tvm_struct_set(StructType* arr, int index, int field_id, value) {\n *     arr[index]->field = value;\n *  }\n * \\sa TVMStructFieldKind\n */\nTVM_DLL const Op& tvm_struct_set();\n\n/*!\n * \\brief See pseudo code\n * Type lookup_param(String param_name) {\n *     return __tvm_param__param_name;\n * }\n */\nTVM_DLL const Op& lookup_param();\n\n/*!\n * \\brief See pesudo code\n *\n *  void tvm_throw_last_error() {\n *    throw TVMGetLastError();\n *  }\n */\nTVM_DLL const Op& tvm_throw_last_error();\n\n/*!\n * \\brief See pesudo code\n *\n *  dtype in {shape, array, arg_value, arg_tcode}\n *\n *  Handle tvm_stack_alloca(string dtype, int num) {\n *     return new on stack dtype[num];\n *  }\n */\nTVM_DLL const Op& tvm_stack_alloca();\n\n/*!\n * \\brief Allocate a shape tuple on stack, return the handle.\n *\n *  Handle tvm_stack_make_shape(list args) {\n *     ret = alloca stack int64_t[len(args)];\n *     for i in range(len(args)):\n *        ret[i] = args[i]\n *     return &ret[0];\n *  }\n */\nTVM_DLL const Op& tvm_stack_make_shape();\n\n/*!\n * \\brief Allocate a NDArray(DLTensor) on stack, return the handle.\n *\n *  Type tvm_stack_make_array(Expr data,\n *                            Expr shape,\n *                            Expr strides,\n *                            Expr ndim,\n *                            Expr dtype,\n *                            Expr elem_offset) {\n *     ret = alloca stack DLTensor();\n *     ret->data = data;\n *     ret->shape = shape;\n *     ret->strides = strides != 0 ? strides : nullptr;\n *     ret->ndim = ndim;\n *     ret->dtype = dtype.type();\n *     ret->byte_offset = elem_offset * sizeof(dtype);\n *     return ret;\n *  }\n */\nTVM_DLL const Op& tvm_stack_make_array();\n\n/*!\n * \\brief See pesudo code\n *\n *  return_type tvm_call_packed(name, TVMValue* args) {\n *     TVMValue ret_value;\n *     int ret_code;\n *     ModuleNode* env = GetCurrentEnv();\n *     const PackedFunc* f = env->GetFuncFromEnv(name);\n *     (*f)(args, type_code_of(args), len(args), &ret_value, &ret_code);\n *     // return type can be int, float, handle.\n *     return cast(return_type, ret_value.v_return_type);\n *  }\n */\nTVM_DLL const Op& tvm_call_packed();\n\n/*!\n * \\brief See pesudo code\n *\n * return_type tvm_call_packed(fname, TVMValue* args) {\n * \t   int ret_code;\n *     TVMValue ret_value;\n *     (*fname)(args, type_code_of(args), len(args), &ret_value, &ret_code);\n *     return cast(return_type, ret_value.v_return_type);\n *  }\n */\nTVM_DLL const Op& tvm_call_cpacked();\n\n/*!\n * \\brief See pesudo code\n *\n *  return_type tvm_call_trace_packed(name, TVMValue* args) {\n *     ModuleNode* env = GetCurrentEnv();\n *     const PackedFunc* f = env->GetFuncFromEnv(name);\n *     (*f)(args, type_code_of(args), len(args));\n *     // return type can be int, float, handle.\n *     return cast(return_type, ret_value.v_return_type);\n *  }\n */\nTVM_DLL const Op& tvm_call_trace_packed();\n\n/*!\n * \\brief Checks the return value of another call is correct or returns a given value.\n *\n * \\note  This is meant to serve a specific case for AOT code generator whilst this\n *        cannot be fully represented in TIR.\n *\n *  Type tvm_check_return(expected, return_unexpected, nested_call) {\n *     if (nested_call() != expected) {\n *         return return_unexpected;\n *     }\n *  }\n */\nTVM_DLL const Op& tvm_check_return();\n\n/*!\n * \\brief See pesudo code\n *  Mark the content as thread local context, can get optimized\n *  by only call the call once at thread start.\n *\n *  Do not allow nesting(getting a thread context from another).\n *\n *  Handle tvm_thread_context(Expr call) {\n *     return call;\n *  }\n */\nTVM_DLL const Op& tvm_thread_context();\n\n/*!\n * \\brief Lowered version of call packed, the space of value and\n *  type codes are explicitly allocated.\n *\n *  return_type tvm_call_packed_lowered(name,\n *                                      TVMValue* value_stack,\n *                                      int* tcode_stack,\n *                                      int begin,\n *                                      int end) {\n *     ModuleNode* env = GetCurrentEnv();\n *     const PackedFunc* f = env->GetFuncFromEnv(name);\n *     f->CallPacked(TVMArgs(value_stack[begin:end],\n *                           tcode_stack[begin:end]),\n *                   TVMRetValue(value_stack + end, tcode_stack + end));\n *     // return type can be int, float, handle.\n *     return cast(return_type, load_return_from(tcode_stack + end))\n *  }\n */\nTVM_DLL const Op& tvm_call_packed_lowered();\n\n/*!\n * \\brief Lowered version of call c-packed, the space of value and\n *  type codes are explicitly allocated.\n *\n *  int tvm_call_packed_lowered(fname,\n *                              TVMValue* value_stack,\n *                              int* tcode_stack,\n *                              int begin,\n *                              int end) {\n *     fname(TVMArgs(value_stack[begin:end], tcode_stack[begin:end]),\n *                   TVMRetValue(value_stack + end, tcode_stack + end));\n *  }\n */\nTVM_DLL const Op& tvm_call_cpacked_lowered();\n\n/*!\n * \\brief Lowered version of trace intrinsic, the space of value and\n *  type codes are explicitly allocated. The return value is the\n *  (end - 1) value on the stack.\n *\n *  return_type tvm_call_trace_packed_lowered(name,\n *                                            TVMValue* value_stack,\n *                                            int* tcode_stack,\n *                                            int begin,\n *                                            int end) {\n *     ModuleNode* env = GetCurrentEnv();\n *     const PackedFunc* f = env->GetFuncFromEnv(name);\n *     f->CallPacked(TVMArgs(value_stack[begin:end],\n *                           tcode_stack[begin:end]),\n *                   TVMRetValue(value_stack + end, tcode_stack + end));\n *     // return type can be int, float, handle.\n *     return cast(return_type, load_return_from(tcode_stack + end))\n *  }\n */\nTVM_DLL const Op& tvm_call_trace_packed_lowered();\n\n/*!\n * \\brief See pseudo code\n *\n *  int tvm_storage_sync(std::string storage_scope) {\n *     __sync(storage_scope);\n *     return 0;\n *  }\n */\nTVM_DLL const Op& tvm_storage_sync();\n\n/*!\n * \\brief See pseudo code\n *\n *  Type tvm_warp_shuffle(mask, Type value, warp_id, width, warp_size) {\n *    return (value passed in by warp indicated by this_warp_id);\n *  }\n *\n *  Type tvm_warp_shuffle_up(mask, Type value, offset, width, warp_size) {\n *    return (value passed in by warp indicated by this_warp_id - offset);\n *  }\n *\n *  Type tvm_warp_shuffle_down(mask, Type value, offset, width, warp_size) {\n *    return (value passed in by warp indicated by this_warp_id + offset);\n *  }\n *\n *  unsigned tvm_warp_activemask() {\n *    return (32-bit mask of currently active threads in the calling warp);\n *  }\n *\n *  Parameter warp_id indicates the source thread ID in a warp.\n *\n *  Parameter offset indicates the relative distance to this_warp_id.\n *\n *  Parameter width indicates the number of threads involved in one\n *  shuffle. See CUDA document for __shfl_sync, __shfl_up_sync,\n *  __shfl_down_sync and __activemask.\n *\n *  Parameter warp_size is the size of a warp, which helps a backend\n *  to determine wheter the width paramter is legal.\n *\n */\nTVM_DLL const Op& tvm_warp_shuffle();\nTVM_DLL const Op& tvm_warp_shuffle_up();\nTVM_DLL const Op& tvm_warp_shuffle_down();\nTVM_DLL const Op& tvm_warp_activemask();\n\n/*!\n * \\brief Initialize the global barrier.\n *  Call this at beginning of kernel that need global barrier.\n */\nTVM_DLL const Op& tvm_global_barrier_kinit();\n\n/*!\n * \\brief See pesudo code\n *\n *  void tvm_thread_allreduce(UIntImm size, Expr source0, ..., Expr cond,\n *                            Var reduce_temp0, .., Var thread_idx1, ...) {\n *     // constraint by the other thread_idx remain the same.\n *     // reduce_temp is used to save intermediate result.\n *     reduce_temp0, ... = reduce(combiner, source0, ..., cond\n *       over [thread_idx1, thread_idx2] passed by any caller)\n *  }\n */\nTVM_DLL const Op& tvm_thread_allreduce();\n\n// TODO(tvm-team) TensorCore specific intrinsics should be directly registered under\n//                cuda. namespace and used through op.\n/*!\n * \\brief tvm intrinsic for tensor core load operators.\n *\n *  void tvm_load_matrix_sync(Var fragment, UIntImm m, UIntImm, n, UIntImm k,\n *                            Expr index, Expr buffer_ptr, Expr stride,\n *                            StringImm layout) {\n *    // m, n, k are the shape of wmma fragment.\n *    // Determine fragment layout(column-major or row major) by layout.\n *    // fragments must be in 'wmma.matrix_a' or 'wmma.matrix_b' scope.\n *    nvcuda::wmma::load_matrix_sync(fragment[index], buffer_ptr, stride);\n *  }\n */\nTVM_DLL const Op& tvm_load_matrix_sync();\n\n/*!\n * \\brief tvm intrinsic for tensor core mma_sync operators.\n *\n *  void tvm_mma_sync(Var fragment_d, Expr index_d,\n *                    Var fragment_a, Expr index_a,\n *                    Var fragment_b, Expr index_b,\n *                    Var fragment_c, Expr index_c) {\n *    nvcuda::wmma::mma_sync(fragment_d[index_d], fragment_a[index_a],\n *                           fragment_b[index_b], fragment_c[index_c]);\n *  }\n */\nTVM_DLL const Op& tvm_mma_sync();\n\n/*!\n * \\brief tvm intrinsic for tensor core bmma_sync operators.\n *\n *  void tvm_bmma_sync(Var fragment_d, Expr index_d,\n *                     Var fragment_a, Expr index_a,\n *                     Var fragment_b, Expr index_b,\n *                     Var fragment_c, Expr index_c) {\n *    nvcuda::wmma::bmma_sync(fragment_d[index_d], fragment_a[index_a],\n *                           fragment_b[index_b], fragment_c[index_c]);\n *  }\n */\nTVM_DLL const Op& tvm_bmma_sync();\n\n/*!\n * \\brief tvm intrinsic for tensor core fill_fragment operators.\n *\n *  void tvm_fill_fragment(Var fragment, UIntImm m, UIntImm, n, UIntImm k,\n *                         Expr index, Expr value) {\n *    // m, n, k are the shape of wmma fragment\n *    // fragments must be in 'wmma.accumulator' scope.\n *    nvcuda::wmma::fill_fragment(fragment[index], value);\n *  }\n */\nTVM_DLL const Op& tvm_fill_fragment();\n\n/*!\n * \\brief tvm intrinsic for tensor core store operators.\n *\n *  void tvm_store_matrix_sync(Var fragment, UIntImm m, UIntImm, n, UIntImm k,\n *                             Expr index, Expr buffer_ptr, Expr stride,\n *                             StringImm layout) {\n *    // m, n, k are the shape of wmma fragment\n *    // fragments must be in 'wmma.accumulator' scope.\n *    nvcuda::wmma::store_matrix_sync(fragment[index], buffer_ptr, stride, layout);\n *  }\n */\nTVM_DLL const Op& tvm_store_matrix_sync();\n\n/*!\n * \\brief tvm intrinsic for ptx tensor core mma instructions.\n *\n *  void ptx_mma(StringImm shape, StringImm A_layout, StringImm B_layout,\n *               StringImm A_dtype, StringImm B_dtype, StringImm C_dtype,\n *               Var multiplicand_a, Expr a_index,\n *               Var multiplicand_b, Expr b_index,\n *               Var accumulator, Expr c_index, bool saturate);\n */\nTVM_DLL const Op& ptx_mma();\n\n/*!\n * \\brief tvm intrinsic for sparse tensor core ptx instructions.\n *\n * void ptx_mma_sp(StringImm shape, StringImm A_layout, StringImm B_layout,\n *                 StringImm A_dtype, StringImm B_dtype, StringImm C_dtype,\n *                 Var multiplicand_a, Expr a_index,\n *                 Var multiplicand_b, Expr b_index,\n *                 Var accumulator, Expr c_index,\n *                 Var metadata, Expr meta_index,\n *                 Var sparse_selector, bool saturate);\n */\nTVM_DLL const Op& ptx_mma_sp();\n\n/*!\n * \\brief tvm intrinsic for ptx load matrix from shared memory.\n *\n * void ptx_ldmatrix(Bool trans, IntImm num, StringImm type,\n *                   Var local_ptr, Expr local_offset,\n *                   Var smem_ptr, Expr smem_offset);\n */\nTVM_DLL const Op& ptx_ldmatrix();\n\n/*!\n * \\brief tvm intrinsics for ptx async copy from global to shared memory\n *\n * void ptx_cp_async(Var shared_ptr, Expr shared_offset, Var global_ptr, Expr global_offset, size_t\n * bytes);\n *\n */\nTVM_DLL const Op& ptx_cp_async();\n\n/*!\n * \\brief tvm intrinsics for ptx async copy commit and wait.\n *\n * void ptx_commit_group();\n * void ptx_wait_group(int num);\n *\n */\nTVM_DLL const Op& ptx_commit_group();\nTVM_DLL const Op& ptx_wait_group();\n\n/*!\n * \\brief tvm intrinsic for storing the result of PTX MMA into a destination pointer.\n *        For example, if each thread in a warp of size 32 has 4 elements from the result of\n *        m16xn8xk16 MMA in its registers, this intrinsic can be used to store the result in a\n *        16x8 region in shared or global memory.\n *\n *        There is no real PTX instruction that does that, but we want to hide details of\n *        complex index manipulation behind this intrinsic to simplify TIR lowering passes (e.g.\n *        LowerWarpMemory).\n *\n * void mma_store(IntImm m, IntImm n, Var dst_ptr, Var src_ptr, Expr src_offset, Var dst_stride);\n */\nTVM_DLL const Op& mma_store();\n\n/*!\n * \\brief tvm intrinsic for zero-initalizing an MMA accumulation registor.\n *        For example, if each thread in a warp of size 32 has 8 elements from the A matrix in\n *        m16xn8xk16 MMA in its registers, this intrinsic can be used to zero-initialize its\n *        4 accumulation registers.\n *\n *        There is no real PTX instruction that does that, but we introduce this intrinsic for the\n *        same reason as mma_store above.\n *\n * void mma_fill(IntImm local_size, Var local_ptr, Expr offset);\n */\nTVM_DLL const Op& mma_fill();\n\n// TODO(tvm-team) replace the usage of the vector operations by Shuffle.\n/*!\n * \\brief Get the high level half of the vector\n */\nTVM_DLL const Op& vectorhigh();\n\n/*!\n * \\brief Get the low-level half of the vector\n */\nTVM_DLL const Op& vectorlow();\n\n/*!\n * \\brief Concat two vectors.\n */\nTVM_DLL const Op& vectorcombine();\n\n/*!\n * \\brief atomic add instruction, corresponding e.g. to atomicAdd in CUDA\n */\nTVM_DLL const Op& atomic_add();\n/*!\n * \\brief Create an Nd memory allocation with storage scope\n */\nTVM_DLL const Op& nd_mem_alloc_with_scope();\n\n/*!\n * \\brief Store to texture 2d memory\n */\nTVM_DLL const Op& texture2d_store();\n\n/*!\n * \\brief Load from texture 2d memory\n */\nTVM_DLL const Op& texture2d_load();\n\n/*!\n * \\brief Copy 1d memory from source to destination\n * Same semantics as memcpy(destination, source, size)\n * Allows for device specific implementations e.g. direct memory access (DMA)\n */\nTVM_DLL const Op& mem_copy();\n\n/*!\n * \\brief Initiate a non-blocking DMA copy from source to destination\n */\nTVM_DLL const Op& dma_copy();\n\n/*!\n * \\brief Wait until the number of DMAs in flight is less than or equal to some maximum\n */\nTVM_DLL const Op& dma_wait();\n\n/*!\n * \\brief Provide a true statement that can be used for simplifications\n *\n * Compile-time representation of known constraints about function\n * inputs.  This assumption is removed when lowering, and does not\n * occur in codegen.\n */\nTVM_DLL const Op& assume();\n\n/*!\n * \\brief Returns an initialized but arbitrary value\n *\n * Compile-time representation of memory locations whose values may be\n * altered as a result of optimizations.\n */\nTVM_DLL const Op& undef();\n\n/*!\n * \\brief Profiling intrinsic\n */\nTVM_DLL const Op& start_profile_intrinsic();\n\n/*!\n * \\brief Profiling intrinsic\n */\nTVM_DLL const Op& end_profile_intrinsic();\n\n/*! \\brief The kind of structure field info used in intrinsic */\nenum TVMStructFieldKind : int {\n  // array head address\n  kArrAddr,\n  kArrData,\n  kArrShape,\n  kArrStrides,\n  kArrNDim,\n  kArrTypeCode,\n  kArrTypeBits,\n  kArrTypeLanes,\n  kArrByteOffset,\n  kArrDeviceId,\n  kArrDeviceType,\n  kArrKindBound_,\n  // TVMValue field\n  kTVMValueContent,\n  kTVMValueKindBound_\n};\n}  // namespace builtin\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_BUILTIN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/data_layout.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/data_layout.h\n * \\brief Layout expression to describe the data organization of a tensor.\n *  And BijectiveLayout to mapping two data layouts between each other.\n */\n#ifndef TVM_TIR_DATA_LAYOUT_H_\n#define TVM_TIR_DATA_LAYOUT_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <algorithm>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\nclass Layout;\n\nclass LayoutAxis {\n public:\n  static const LayoutAxis& Get(const char name);\n\n  // Get the singleton LayoutAxis using itvar->var->name_hint\n  static const LayoutAxis& Get(const tir::IterVar& itvar);\n\n  // Get the singleton LayoutAxis using name[0] (size of name must be 1).\n  static const LayoutAxis& Get(const std::string& name);\n\n  inline bool IsPrimal() const { return name_ >= 'A' && name_ <= 'Z'; }\n  inline std::string name() const { return std::string(1, name_); }\n\n  // if current axis is primal, switch the axis to its subordinate one,\n  // else switch to the primal.\n  inline const LayoutAxis& ToDual() const {\n    if (name_ >= 'A' && name_ <= 'Z') {\n      return LayoutAxis::Get(name_ - 'A' + 'a');\n    } else {\n      return LayoutAxis::Get(name_ - 'a' + 'A');\n    }\n  }\n\n  // return the primal axis. If it is already primal, return itself.\n  const LayoutAxis& ToPrimal() const { return IsPrimal() ? *this : ToDual(); }\n\n  // return the subordinate axis. If it is already subordinate, return itself.\n  const LayoutAxis& ToSubordinate() const { return IsPrimal() ? ToDual() : *this; }\n\n  inline bool operator==(const LayoutAxis& rhs) const { return name_ == rhs.name_; }\n\n  friend std::ostream& operator<<(std::ostream& os, const LayoutAxis& l) {\n    os << l.name();\n    return os;\n  }\n\n private:\n  static const LayoutAxis UPPER_CASE[];\n  static const LayoutAxis LOWER_CASE[];\n  LayoutAxis(const LayoutAxis&);\n  LayoutAxis& operator=(const LayoutAxis&);\n  explicit LayoutAxis(const char name) : name_(name) {}\n\n  const char name_;\n};\n\n/*!\n * \\brief Layout is to describe how data is organized within an N-dimention tensor.\n *  It is composed of upper cases, lower cases and numbers,\n *  where upper case indicates a primal axis and\n *  the corresponding lower case with factor size indicates the subordinate axis.\n *  For example, NCHW16c can describe a 5-D tensor of\n *  [batch_size, channel, height, width, channel_block].\n *  Here subordinate axis channel_block=16 is the factor size of the primal axis C (channel).\n *  Layout for scalar is defined, while both its name and axes have size 0.\n */\nclass LayoutNode : public Object {\n public:\n  /*! \\brief string representation of layout, \"\" for scalar. */\n  String name;\n  /*! \\brief specify each axis of the layout,\n   *   in which the variable name is the name of the axis.\n   *   The IterVar's extent indicates the size of the axis,\n   *   it is a variable for a primal axis, but a constant for a subordinate axis.\n   *   Empty for scalar's layout.\n   */\n  Array<tir::IterVar> axes;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"axes\", &axes);\n  }\n\n  static constexpr const char* _type_key = \"tir.Layout\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LayoutNode, Object);\n};\n\n/*!\n * \\brief Managed reference to LayoutNode\n * \\sa LayoutNode\n */\nclass Layout : public ObjectRef {\n public:\n  explicit Layout(const Array<tir::IterVar>& axes);\n\n  /*! \\brief construct from a string */\n  Layout(const tvm::String& name) : Layout(name.operator std::string()) {}  // NOLINT(*)\n\n  /*! \\brief construct from a string */\n  Layout(const char* name) : Layout(std::string(name)) {}  // NOLINT(*)\n\n  /*!\n   * \\brief construct from a string.\n   * \\param name input in layout convention:\n   *        upper case indicates a dimension and\n   *        the corresponding lower case with factor size\n   *        indicates the split dimension.\n   *        return undefined layout if \"__undef__\" is passed.\n   */\n  TVM_DLL Layout(const std::string& name);  // NOLINT(*)\n\n  /*!\n   * \\brief access the internal node container\n   * \\return the pointer to the internal node container\n   */\n  LayoutNode* operator->() { return static_cast<LayoutNode*>(get_mutable()); }\n\n  /*!\n   * \\brief Return an undefined layout.\n   * \\return a (global) undefined layout.\n   */\n  static const Layout& Undef() {\n    static Layout undef;\n    return undef;\n  }\n\n  /*!\n   * \\brief Returns a sub-layout which is the portion of the object\n   *        that starts at dimension \\p pos and spans \\p len dimensions\n   *        (or until the end of the layout, whichever comes first).\n   * \\param pos The start position.\n   * \\param len The length of the sub-layout. if 0, return layout of scalar\n   * \\return A newly constructed Layout object.\n   */\n  Layout SubLayout(size_t pos, size_t len) const;\n\n  /*!\n   * \\brief Split \\p axis by \\p size and put the sub-axis to position \\p target_pos.\n   * \\param axis The source axis to be split. It must be a primal-axis;\n   * \\param target_pos The target position of the newly split subordinate-axis.\n   * \\param factor size of the sub-dimension.\n   * \\return A newly constructed Layout object.\n   */\n  Layout Split(const LayoutAxis& axis, size_t target_pos, int32_t factor) const;\n\n  /*! \\return number of dimensions */\n  inline size_t ndim() const {\n    if (!defined()) return 0;\n    return operator->()->axes.size();\n  }\n\n  /*! \\return number of super dimensions */\n  inline size_t ndim_primal() const {\n    if (!defined()) return 0;\n    size_t ct = 0;\n    for (auto x : operator->()->axes) {\n      if (LayoutAxis::Get(x).IsPrimal()) {\n        ct++;\n      }\n    }\n    return ct;\n  }\n\n  /*!\n   * \\brief Returns a new layout where the dims have been expanded to match the primal dimensions.\n   * \\param dst_layout The dst layout to which current layout has to be expanded.\n   * \\return The expanded Layout.\n   */\n  inline Layout ExpandPrimal(const Layout& dst_layout) {\n    Layout new_src_layout;\n    // 1) Find the axis which are missing in the current layout. Make them the prefix.\n    std::string new_src_layout_str = \"\";\n    for (auto dst_axis : dst_layout->axes) {\n      if (LayoutAxis::Get(dst_axis).IsPrimal()) {\n        if (!this->Contains(LayoutAxis::Get(dst_axis))) {\n          new_src_layout_str += dst_axis->var->name_hint;\n        }\n      }\n    }\n    // 2) Now, add the primal axis of the current layout.\n    new_src_layout_str += this->name();\n    new_src_layout = Layout(new_src_layout_str);\n    return new_src_layout;\n  }\n\n  /*!\n   * \\brief return the index of the input axis.\n   *        If it is not found in the layout or the layout is undefined,\n   *        return -1.\n   * \\param axis the input axis.\n   * \\return the index or -1 if not found.\n   */\n  inline int32_t IndexOf(const LayoutAxis& axis) const {\n    if (!this->defined()) return -1;\n    const auto axes = operator->()->axes;\n    for (size_t i = 0; i < axes.size(); ++i) {\n      if (axes[i]->var->name_hint == axis.name()) return static_cast<int32_t>(i);\n    }\n    return -1;\n  }\n\n  /*!\n   * \\brief Get the factor size of the subordinate axis.\n   * \\param axis the input primal-axis or subordinate-axis.\n   * \\return the size of the subordinate-axis of \\p axis (if \\p axis is a primal-axis),\n   *         or the size of \\p axis itself (if \\p axis is a subordinate-axis).\n   *         Return -1 if \\p axis is not in the layout the layout is undefined.\n   */\n  int32_t FactorOf(const LayoutAxis& axis) const;\n\n  /*!\n   * \\brief Whether the layout contains an axis.\n   * \\param axis axis to be checked.\n   * \\return Whether the layout contains the axis.\n   */\n  bool Contains(const LayoutAxis& axis) const {\n    if (!defined()) return false;\n    for (const tir::IterVar var : operator->()->axes) {\n      if (var->var->name_hint == axis.name()) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  const LayoutAxis& operator[](int32_t i) const {\n    ICHECK(defined()) << \"Try to access axis from an undefined layout.\";\n    int32_t index = i < 0 ? static_cast<int32_t>(ndim() + i) : i;\n    ICHECK(index >= 0 && static_cast<size_t>(index) < ndim()) << \"Invalid index \" << i;\n    const tir::IterVar axis = operator->()->axes[index];\n    return LayoutAxis::Get(axis);\n  }\n\n  /*! \\return the string description of the layout */\n  inline std::string name() const {\n    if (!defined()) return \"__undef__\";\n    return operator->()->name;\n  }\n\n  /*!\n   * \\brief Whether the two layouts are equal.\n   * \\param rhs Another layout.\n   * \\return whether the two layouts are equal.\n   */\n  inline bool Equals(const Layout& rhs) const { return name() == rhs.name(); }\n\n  /*!\n   * \\brief allow output string of layout to ostream\n   * \\param os the output stream\n   * \\param l the layout\n   * \\return the ostream\n   */\n  friend std::ostream& operator<<(std::ostream& os, const Layout& l) {\n    os << l.name();\n    return os;\n  }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Layout, ObjectRef, LayoutNode);\n};\n\n// Internal node container BijectiveLayout\nclass BijectiveLayoutNode : public Object {\n public:\n  /*! \\brief Describes how source axes can be mapped to the destination axes,\n   *   e.g., [i0 / 16, i1, i0 % 16] can describe NC -> NC16n\n   */\n  Array<PrimExpr> index_forward_rule;\n  /*! \\brief Describes how destination axes can be mapped to the source axes */\n  Array<PrimExpr> index_backward_rule;\n  /*! \\brief Describes how source shapes can be mapped to the destination shapes */\n  Array<PrimExpr> shape_forward_rule;\n  /*! \\brief Describes how destination shapes can be mapped to the source shapes */\n  Array<PrimExpr> shape_backward_rule;\n\n  /*! \\brief The source layout */\n  Layout src_layout;\n  /*! \\brief The destination layout */\n  Layout dst_layout;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"src_layout\", &src_layout);\n    v->Visit(\"dst_layout\", &dst_layout);\n    v->Visit(\"index_forward_rule\", &index_forward_rule);\n    v->Visit(\"index_backward_rule\", &index_backward_rule);\n    v->Visit(\"shape_forward_rule\", &shape_forward_rule);\n    v->Visit(\"shape_backward_rule\", &shape_backward_rule);\n  }\n\n  static constexpr const char* _type_key = \"tir.BijectiveLayout\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BijectiveLayoutNode, Object);\n};\n\n/*!\n * \\brief Bijective function mapping for data layout transformation.\n *   Given two Layout, BijectiveLayout build and store the mapping rules,\n *   provides API to transform N-dimention tensor from the source indices (i0, i1, .., im)\n *   to the destination indices (j0, j1, .., jm).\n */\nclass BijectiveLayout : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param src_layout The source layout\n   * \\param dst_layout The destination layout\n   */\n  TVM_DLL BijectiveLayout(Layout src_layout, Layout dst_layout);\n\n  // Given the source shape, infer the destination shape.\n  TVM_DLL Array<PrimExpr> ForwardShape(const Array<PrimExpr>& shape) const;\n  // Given the destination shape, recover the source shape.\n  TVM_DLL Array<PrimExpr> BackwardShape(const Array<PrimExpr>& dst_shape) const;\n  // Given the destination indices, infer the destination indices.\n  TVM_DLL Array<PrimExpr> ForwardIndex(const Array<PrimExpr>& index) const;\n  // Given the destination indices, recover the source indices.\n  TVM_DLL Array<PrimExpr> BackwardIndex(const Array<PrimExpr>& dst_index) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(BijectiveLayout, ObjectRef, BijectiveLayoutNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_DATA_LAYOUT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/expr.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/expr.h\n * \\brief TIR expressions.\n */\n// Acknowledgement: Many low-level IR nodes originate from Halide.\n#ifndef TVM_TIR_EXPR_H_\n#define TVM_TIR_EXPR_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/node/functor.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/tir/buffer.h>\n#include <tvm/tir/var.h>\n\n#include <algorithm>\n#include <iostream>\n#include <limits>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace tir {\n\nusing IntImmNode = tvm::IntImmNode;\nusing FloatImmNode = tvm::FloatImmNode;\n\n/*! \\brief String constants, only used in asserts. */\nclass StringImmNode : public PrimExprNode {\n public:\n  /*! \\brief The constant value content. */\n  String value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const StringImmNode* other, SEqualReducer equal) const {\n    return equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(value); }\n\n  static constexpr const char* _type_key = \"tir.StringImm\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StringImmNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to StringImmNode.\n * \\sa StringImmNode\n */\nclass StringImm : public PrimExpr {\n public:\n  TVM_DLL StringImm(String value, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(StringImm, PrimExpr, StringImmNode);\n};\n\n/*!\n * \\brief Cast value from one data type to another.\n * \\note The lanes of value should keep fixed.\n */\nclass CastNode : public PrimExprNode {\n public:\n  /*! \\brief Original data type. */\n  PrimExpr value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const CastNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(value);\n  }\n\n  static constexpr const char* _type_key = \"tir.Cast\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CastNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to CastNode\n * \\sa CastNode\n */\nclass Cast : public PrimExpr {\n public:\n  TVM_DLL Cast(DataType dtype, PrimExpr value, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Cast, PrimExpr, CastNode);\n};\n\n/*!\n * \\brief Base template to implement binary ops.\n * \\tparam T The type of the child class.\n */\ntemplate <typename T>\nclass BinaryOpNode : public PrimExprNode {\n public:\n  /*! \\brief The left operand. */\n  PrimExpr a;\n  /*! \\brief The right operand. */\n  PrimExpr b;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &(this->dtype));\n    v->Visit(\"a\", &a);\n    v->Visit(\"b\", &b);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const T* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(a, other->a) && equal(b, other->b);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(a);\n    hash_reduce(b);\n  }\n\n  TVM_DECLARE_FINAL_OBJECT_INFO(T, PrimExprNode);\n};\n\n/*! \\brief a + b */\nclass AddNode : public BinaryOpNode<AddNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Add\";\n};\n\n/*!\n * \\brief Managed reference to AddNode\n * \\sa AddNode\n */\nclass Add : public PrimExpr {\n public:\n  TVM_DLL Add(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Add, PrimExpr, AddNode);\n};\n\n/*! \\brief a - b */\nclass SubNode : public BinaryOpNode<SubNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Sub\";\n};\n\n/*!\n * \\brief Managed reference to SubNode\n * \\sa SubNode\n */\nclass Sub : public PrimExpr {\n public:\n  TVM_DLL Sub(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Sub, PrimExpr, SubNode);\n};\n\n/*! \\brief a * b */\nclass MulNode : public BinaryOpNode<MulNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Mul\";\n};\n\n/*!\n * \\brief Managed reference to MulNode\n * \\sa MulNode\n */\nclass Mul : public PrimExpr {\n public:\n  TVM_DLL Mul(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Mul, PrimExpr, MulNode);\n};\n\n/*!\n * \\brief a / b in the C semnatics.\n * \\note For integer division, C standard uses trunc div.\n */\nclass DivNode : public BinaryOpNode<DivNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Div\";\n};\n\n/*!\n * \\brief Managed reference to DivNode\n * \\sa DivNode\n */\nclass Div : public PrimExpr {\n public:\n  TVM_DLL Div(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Div, PrimExpr, DivNode);\n};\n\n/*!\n * \\brief a % b in the C semnatics.\n * \\note For integer division, C standard uses trunc div.\n */\nclass ModNode : public BinaryOpNode<ModNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Mod\";\n};\n\n/*!\n * \\brief Managed reference to ModNode\n * \\sa ModNode\n */\nclass Mod : public PrimExpr {\n public:\n  TVM_DLL Mod(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Mod, PrimExpr, ModNode);\n};\n\n/*! \\brief Floor division, floor(a/b) */\nclass FloorDivNode : public BinaryOpNode<FloorDivNode> {\n public:\n  static constexpr const char* _type_key = \"tir.FloorDiv\";\n};\n\n/*!\n * \\brief Managed reference to FloorDivNode\n * \\sa FloorDivNode\n */\nclass FloorDiv : public PrimExpr {\n public:\n  TVM_DLL FloorDiv(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(FloorDiv, PrimExpr, FloorDivNode);\n};\n\n/*! \\brief The remainder of the floordiv */\nclass FloorModNode : public BinaryOpNode<FloorModNode> {\n public:\n  static constexpr const char* _type_key = \"tir.FloorMod\";\n};\n\n/*!\n * \\brief Managed reference to FloorModNode\n * \\sa FloorModNode\n */\nclass FloorMod : public PrimExpr {\n public:\n  TVM_DLL FloorMod(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(FloorMod, PrimExpr, FloorModNode);\n};\n\n/*! \\brief min(a, b) */\nclass MinNode : public BinaryOpNode<MinNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Min\";\n};\n\n/*!\n * \\brief Managed reference to MinNode\n * \\sa MinNode\n */\nclass Min : public PrimExpr {\n public:\n  TVM_DLL Min(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Min, PrimExpr, MinNode);\n};\n\n/*! \\brief max(a, b) */\nclass MaxNode : public BinaryOpNode<MaxNode> {\n public:\n  static constexpr const char* _type_key = \"tir.Max\";\n};\n\n/*!\n * \\brief Managed reference to MaxNode\n * \\sa MaxNode\n */\nclass Max : public PrimExpr {\n public:\n  TVM_DLL Max(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Max, PrimExpr, MaxNode);\n};\n\n/*!\n * \\brief Base template to implement comparison ops.\n * \\tparam T The type of the child class.\n */\ntemplate <typename T>\nclass CmpOpNode : public PrimExprNode {\n public:\n  /*! \\brief The left operand. */\n  PrimExpr a;\n  /*! \\brief The right operand. */\n  PrimExpr b;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &(this->dtype));\n    v->Visit(\"a\", &a);\n    v->Visit(\"b\", &b);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const T* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(a, other->a) && equal(b, other->b);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(a);\n    hash_reduce(b);\n  }\n\n  TVM_DECLARE_FINAL_OBJECT_INFO(T, PrimExprNode);\n};\n\n/*! \\brief a == b */\nclass EQNode : public CmpOpNode<EQNode> {\n public:\n  static constexpr const char* _type_key = \"tir.EQ\";\n};\n\n/*!\n * \\brief Managed reference to EQNode\n * \\sa EQNode\n */\nclass EQ : public PrimExpr {\n public:\n  TVM_DLL EQ(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(EQ, PrimExpr, EQNode);\n};\n\n/*! \\brief a != b */\nclass NENode : public CmpOpNode<NENode> {\n public:\n  static constexpr const char* _type_key = \"tir.NE\";\n};\n\n/*!\n * \\brief Managed reference to NENode\n * \\sa NENode\n */\nclass NE : public PrimExpr {\n public:\n  TVM_DLL NE(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(NE, PrimExpr, NENode);\n};\n\n/*! \\brief a < b */\nclass LTNode : public CmpOpNode<LTNode> {\n public:\n  static constexpr const char* _type_key = \"tir.LT\";\n};\n\n/*!\n * \\brief Managed reference to LTNode\n * \\sa LTNode\n */\nclass LT : public PrimExpr {\n public:\n  TVM_DLL LT(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(LT, PrimExpr, LTNode);\n};\n\n/*! \\brief a <= b */\nstruct LENode : public CmpOpNode<LENode> {\n public:\n  static constexpr const char* _type_key = \"tir.LE\";\n};\n\n/*!\n * \\brief Managed reference to LENode\n * \\sa LENode\n */\nclass LE : public PrimExpr {\n public:\n  TVM_DLL LE(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(LE, PrimExpr, LENode);\n};\n\n/*! \\brief a > b */\nclass GTNode : public CmpOpNode<GTNode> {\n public:\n  static constexpr const char* _type_key = \"tir.GT\";\n};\n\n/*!\n * \\brief Managed reference to GTNode\n * \\sa GTNode\n */\nclass GT : public PrimExpr {\n public:\n  TVM_DLL GT(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(GT, PrimExpr, GTNode);\n};\n\n/*! \\brief a >= b */\nclass GENode : public CmpOpNode<GENode> {\n public:\n  static constexpr const char* _type_key = \"tir.GE\";\n};\n\n/*!\n * \\brief Managed reference to GENode\n * \\sa GENode\n */\nclass GE : public PrimExpr {\n public:\n  TVM_DLL GE(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(GE, PrimExpr, GENode);\n};\n\n/*! \\brief a && b */\nclass AndNode : public PrimExprNode {\n public:\n  /*! \\brief The left operand. */\n  PrimExpr a;\n  /*! \\brief The right operand. */\n  PrimExpr b;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &(this->dtype));\n    v->Visit(\"a\", &a);\n    v->Visit(\"b\", &b);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AndNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(a, other->a) && equal(b, other->b);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(a);\n    hash_reduce(b);\n  }\n\n  static constexpr const char* _type_key = \"tir.And\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AndNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to AndNode\n * \\sa AndNode\n */\nclass And : public PrimExpr {\n public:\n  TVM_DLL And(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(And, PrimExpr, AndNode);\n};\n\n/*! \\brief a || b */\nclass OrNode : public PrimExprNode {\n public:\n  /*! \\brief The left operand. */\n  PrimExpr a;\n  /*! \\brief The right operand. */\n  PrimExpr b;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"a\", &a);\n    v->Visit(\"b\", &b);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const OrNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(a, other->a) && equal(b, other->b);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(a);\n    hash_reduce(b);\n  }\n\n  static constexpr const char* _type_key = \"tir.Or\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OrNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to OrNode\n * \\sa OrNode\n */\nclass Or : public PrimExpr {\n public:\n  TVM_DLL Or(PrimExpr a, PrimExpr b, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Or, PrimExpr, OrNode);\n};\n\n/*! \\brief !a */\nclass NotNode : public PrimExprNode {\n public:\n  /*! \\brief The input operand. */\n  PrimExpr a;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"a\", &a);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const NotNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(a, other->a);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(a);\n  }\n\n  static constexpr const char* _type_key = \"tir.Not\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(NotNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to NotNode\n * \\sa NotNode\n */\nclass Not : public PrimExpr {\n public:\n  TVM_DLL Not(PrimExpr a, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Not, PrimExpr, NotNode);\n};\n\n/*!\n * \\brief return true_value if condition is true, otherwise return false_value.\n * \\note Both true_value and false_value could be evaluated\n *       regardless of the condition value.\n *       Do not use it to guard against out of bound access,\n *       please use if_then_else instead.\n */\nclass SelectNode : public PrimExprNode {\n public:\n  /*! \\brief The condition */\n  PrimExpr condition;\n  /*! \\brief value to be returned when condition is true. */\n  PrimExpr true_value;\n  /*! \\brief value to be returned when condition is false. */\n  PrimExpr false_value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"true_value\", &true_value);\n    v->Visit(\"false_value\", &false_value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const SelectNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(condition, other->condition) &&\n           equal(true_value, other->true_value) && equal(false_value, other->false_value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(condition);\n    hash_reduce(true_value);\n    hash_reduce(false_value);\n  }\n\n  static constexpr const char* _type_key = \"tir.Select\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SelectNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to SelectNode\n * \\sa SelectNode\n */\nclass Select : public PrimExpr {\n public:\n  TVM_DLL Select(PrimExpr condition, PrimExpr true_value, PrimExpr false_value, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Select, PrimExpr, SelectNode);\n};\n\n/*!\n * \\brief Load value from the high dimension buffer.\n *\n * \\code\n *\n *  value = buffer[i, j];\n *\n * \\endcode\n * \\sa BufferStore\n */\nclass BufferLoadNode : public PrimExprNode {\n public:\n  /*! \\brief The buffer variable. */\n  Buffer buffer;\n  /*! \\brief The indices location to be loaded. */\n  Array<PrimExpr> indices;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &(this->dtype));\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const BufferLoadNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(buffer, other->buffer) &&\n           equal(indices, other->indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(buffer);\n    hash_reduce(indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.BufferLoad\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferLoadNode, PrimExprNode);\n\n private:\n  /*! \\brief Set the dtype based on the buffer/indices\n   *\n   * Usually, the BufferLoad's dtype will be the same dtype as the\n   * buffer.  This may have a different number of lanes than the\n   * buffer's dtype if index values have more than 1 lane.\n   *\n   * This function should only be called during construction and after\n   * CopyOnWrite.  Friend class used here to restrict usage.\n   */\n  void LegalizeDType();\n  friend class BufferLoad;\n  friend class CustomDatatypesLowerer;\n  friend class VectorTypeRewriter;\n  friend class Vectorizer;\n};\n\n/*!\n * \\brief Managed reference to BufferLoadNode.\n * \\sa BufferLoadNode\n */\nclass BufferLoad : public PrimExpr {\n public:\n  TVM_DLL explicit BufferLoad(Buffer buffer, Array<PrimExpr> indices, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(BufferLoad, PrimExpr, BufferLoadNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BufferLoadNode);\n};\n\n/*!\n * \\brief Load value from the result produced by the producer.\n *\n * \\note This node only appears in high-level DSLs that are built on top of the TIR.\n *       It should not appear in a valid TIR PrimFunc. A high-level DSL needs to lower\n *       this node before TIR transformations.\n *\n * \\sa ProducerLoad, DataProducerNode\n */\nclass ProducerLoadNode : public PrimExprNode {\n public:\n  /*! \\brief The buffer producer. */\n  DataProducer producer;\n  /*! \\brief The location arguments. */\n  Array<PrimExpr> indices;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &(this->dtype));\n    v->Visit(\"producer\", &producer);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ProducerLoadNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(producer, other->producer) &&\n           equal(indices, other->indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(producer);\n    hash_reduce(indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.ProducerLoad\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProducerLoadNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to ProducerLoadNode.\n * \\sa ProducerLoadNode\n */\nclass ProducerLoad : public PrimExpr {\n public:\n  TVM_DLL explicit ProducerLoad(DataProducer producer, Array<PrimExpr> indices, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ProducerLoad, PrimExpr, ProducerLoadNode);\n};\n\n/*!\n * \\brief Load the value from buffer_var.\n *\n *  Equivalent to ((DType*)buffer_var)[index]\n *  where DType is the type specified by type().element_of().\n *\n *  For example, if type = float32x3, then the load will corresponds to\n *\n * \\code\n *\n *  auto buffer = static_cast<float*>(buffer_var);\n *  auto loaded_val = float32x3(buffer[index.v0], buffer[index.v1], buffer[index.v2]);\n *\n * \\endcode\n */\nclass LoadNode : public PrimExprNode {\n public:\n  /*! \\brief The buffer variable. */\n  Var buffer_var;\n  /*! \\brief The index locations to be loaded. */\n  PrimExpr index;\n  /*! \\brief The predicate to mask which lanes would be loaded. */\n  PrimExpr predicate;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"buffer_var\", &buffer_var);\n    v->Visit(\"index\", &index);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const LoadNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(buffer_var, other->buffer_var) &&\n           equal(index, other->index) && equal(predicate, other->predicate);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(buffer_var);\n    hash_reduce(index);\n    hash_reduce(predicate);\n  }\n\n  static constexpr const char* _type_key = \"tir.Load\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LoadNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to LoadNode\n * \\sa LoadNode\n */\nclass Load : public PrimExpr {\n public:\n  TVM_DLL Load(DataType dtype, Var buffer_var, PrimExpr index, PrimExpr predicate,\n               Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Load, PrimExpr, LoadNode);\n};\n\n/*!\n * \\brief Construct a vector with lanes elements\n *        where its i-th element equals base + i * stride.\n *  This is useful to construct a index for a continuous vector load.\n *\n *  Examples:\n *  - ramp(0, 1, 3) = [0, 1, 2]\n *  - ramp(1, 2, 4) = [1, 3, 5, 7]\n */\nclass RampNode : public PrimExprNode {\n public:\n  /*! \\brief The base value. */\n  PrimExpr base;\n  /*! \\brief The stride of each step. */\n  PrimExpr stride;\n  /*! \\brief Total number of lanes. */\n  int lanes;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"base\", &base);\n    v->Visit(\"stride\", &stride);\n    v->Visit(\"lanes\", &lanes);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const RampNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(base, other->base) && equal(stride, other->stride) &&\n           equal(lanes, other->lanes);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(base);\n    hash_reduce(stride);\n    hash_reduce(lanes);\n  }\n\n  static constexpr const char* _type_key = \"tir.Ramp\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RampNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to RampNode\n * \\sa RampNode\n */\nclass Ramp : public PrimExpr {\n public:\n  TVM_DLL Ramp(PrimExpr base, PrimExpr stride, int lanes, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Ramp, PrimExpr, RampNode);\n};\n\n/*! \\brief Create a vector where all the elements are value. */\nclass BroadcastNode : public PrimExprNode {\n public:\n  /*! \\brief The base value. */\n  PrimExpr value;\n  /*! \\brief The number of lanes. */\n  int lanes;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"value\", &value);\n    v->Visit(\"lanes\", &lanes);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const BroadcastNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(value, other->value) && equal(lanes, other->lanes);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(value);\n    hash_reduce(lanes);\n  }\n\n  static constexpr const char* _type_key = \"tir.Broadcast\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BroadcastNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to BroadcastNode\n * \\sa BroadcastNode\n */\nclass Broadcast : public PrimExpr {\n public:\n  TVM_DLL Broadcast(PrimExpr value, int lanes, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Broadcast, PrimExpr, BroadcastNode);\n};\n\n/*!\n * \\brief Let binding. Bind var to value then evaluate body.\n */\nclass LetNode : public PrimExprNode {\n public:\n  /*! \\brief The variable. */\n  Var var;\n  /*! \\brief The value to be binded. */\n  PrimExpr value;\n  /*! \\brief The result expression. */\n  PrimExpr body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"var\", &var);\n    v->Visit(\"value\", &value);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const LetNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal.DefEqual(var, other->var) &&\n           equal(value, other->value) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce.DefHash(var);\n    hash_reduce(value);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.Let\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LetNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to LetNode\n * \\sa LetNode\n */\nclass Let : public PrimExpr {\n public:\n  TVM_DLL Let(Var var, PrimExpr value, PrimExpr body, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Let, PrimExpr, LetNode);\n};\n\n/*!\n * \\brief Call node.\n */\nclass CallNode : public PrimExprNode {\n public:\n  /*!\n   * \\brief The operator(function) being invoked\n   *\n   *  - It can be tvm::Op which corresponds to the primitive operators(intrinsics).\n   *  - It can also be another function in the IRModule (GlobalVar).\n   */\n  RelayExpr op;\n\n  /*! \\brief The arguments. */\n  Array<PrimExpr> args;\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"op\", &op);\n    v->Visit(\"args\", &args);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const CallNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(op, other->op) && equal(args, other->args);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(op);\n    hash_reduce(args);\n  }\n\n  static constexpr const char* _type_key = \"tir.Call\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CallNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to CallNode\n * \\sa CallNode\n */\nclass Call : public PrimExpr {\n public:\n  TVM_DLL Call(DataType dtype, RelayExpr op, Array<PrimExpr> args, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(Call, PrimExpr, CallNode);\n};\n\n/*!\n * \\brief Shuffle instruction.\n *  vec = concat(vectors)\n *  result = (vec[indices[0]], vec[indices[1]] ...)\n */\nclass ShuffleNode : public PrimExprNode {\n public:\n  /*! \\brief the input vectors. */\n  Array<PrimExpr> vectors;\n  /*! \\brief The indices of each element. */\n  Array<PrimExpr> indices;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"vectors\", &vectors);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ShuffleNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype) && equal(vectors, other->vectors) &&\n           equal(indices, other->indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(vectors);\n    hash_reduce(indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.Shuffle\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ShuffleNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to ShuffleNode\n * \\sa ShuffleNode\n */\nclass Shuffle : public PrimExpr {\n public:\n  TVM_DLL Shuffle(Array<PrimExpr> vectors, Array<PrimExpr> indices, Span span = Span());\n  TVM_DLL static PrimExpr Concat(Array<PrimExpr> vectors, Span span = Span());\n  TVM_DLL static PrimExpr ExtractElement(PrimExpr vector, int index, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Shuffle, PrimExpr, ShuffleNode);\n};\n\n// Reduce operator\n/*!\n * \\brief A commutative reducer node to represent a commutative\n *  binary operator with identity element\n */\nclass CommReducerNode : public Object {\n public:\n  /*! \\brief The left argument of reducer */\n  Array<Var> lhs;\n  /*! \\brief The right argument of reducer */\n  Array<Var> rhs;\n  /*! \\brief The result of reducer */\n  Array<PrimExpr> result;\n  /*!\n   * \\brief The identity element of reducer, which leaves other\n   *  elements unchanged when combined with it, with respect to\n   *  the binary operation of this reducer uses.\n   */\n  Array<PrimExpr> identity_element;\n  /*! \\brief Function call operator to combine a and b */\n  Array<PrimExpr> operator()(Array<PrimExpr> a, Array<PrimExpr> b) const;\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"lhs\", &lhs);\n    v->Visit(\"rhs\", &rhs);\n    v->Visit(\"result\", &result);\n    v->Visit(\"identity_element\", &identity_element);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const CommReducerNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(lhs, other->lhs) && equal.DefEqual(rhs, other->rhs) &&\n           equal(result, other->result) && equal(identity_element, other->identity_element);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(lhs);\n    hash_reduce.DefHash(rhs);\n    hash_reduce(result);\n    hash_reduce(identity_element);\n  }\n\n  static constexpr const char* _type_key = \"tir.CommReducer\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(CommReducerNode, Object);\n};\n\n/*!\n * \\brief Managed reference to CommReducerNode\n * \\sa CommReducerNode\n */\nclass CommReducer : public ObjectRef {\n public:\n  TVM_DLL CommReducer(Array<Var> lhs, Array<Var> rhs, Array<PrimExpr> result,\n                      Array<PrimExpr> identity_element, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CommReducer, ObjectRef, CommReducerNode);\n};\n\n/*! \\brief Reduction operator operator */\nclass ReduceNode : public PrimExprNode {\n public:\n  /*! \\brief The commutative combiner */\n  CommReducer combiner;\n  /*! \\brief The source operand */\n  Array<PrimExpr> source;\n  /*! \\brief The init operand */\n  Array<PrimExpr> init;\n  /*! \\brief The reduction axis */\n  Array<IterVar> axis;\n  /*!\n   * \\brief Predicate on the reduction\n   *  Only add the body to reduction if condition is true.\n   */\n  PrimExpr condition;\n  /*! \\brief the index of this reduce node */\n  int value_index;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"combiner\", &combiner);\n    v->Visit(\"source\", &source);\n    v->Visit(\"init\", &init);\n    v->Visit(\"axis\", &axis);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"value_index\", &value_index);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ReduceNode* other, SEqualReducer equal) const {\n    // check axis first so IterVars can define the necessary variables.\n    return equal(dtype, other->dtype) && equal(axis, other->axis) &&\n           equal(combiner, other->combiner) && equal(source, other->source) &&\n           equal(init, other->init) && equal(condition, other->condition) &&\n           equal(value_index, other->value_index);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(axis);\n    hash_reduce(combiner);\n    hash_reduce(source);\n    hash_reduce(init);\n    hash_reduce(condition);\n    hash_reduce(value_index);\n  }\n\n  static constexpr const char* _type_key = \"tir.Reduce\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ReduceNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to ReduceNode\n * \\sa ReduceNode\n */\nclass Reduce : public PrimExpr {\n public:\n  TVM_DLL Reduce(CommReducer combiner, Array<PrimExpr> src, Array<IterVar> rdom, PrimExpr condition,\n                 int value_index, Array<PrimExpr> init, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Reduce, PrimExpr, ReduceNode);\n};\n\n/*! \\brief Any shape. */\nclass AnyNode : public PrimExprNode {\n public:\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AnyNode* other, SEqualReducer equal) const {\n    return equal(dtype, other->dtype);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {}\n\n  /*! \\brief Convert to var. */\n  Var ToVar() const { return Var(\"any_dim\", DataType::Int(32)); }\n\n  /*! \\brief Convert to SizeVar. */\n  SizeVar ToSizeVar() const { return SizeVar(\"any_dim\", DataType::Int(32)); }\n\n  static constexpr const char* _type_key = \"tir.Any\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AnyNode, PrimExprNode);\n};\n\n/*!\n * \\brief Managed reference to AnyNode\n * \\sa AnyNode\n */\nclass Any : public PrimExpr {\n public:\n  TVM_DLL Any(Span span = Span());\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Any, PrimExpr, AnyNode);\n};\n\n/*\n * \\brief Template function to convert Map to unordered_map\n *  Sometimes useful for API gluing when internal uses unordered_map\n * \\param dmap The container map\n * \\return The corresponding unordered_map.\n * \\tparam K the key of the Map.\n * \\tparam V the value of the Map.\n */\ntemplate <typename K, typename V>\ninline std::unordered_map<K, V> as_unordered_map(const Map<K, V>& dmap) {\n  std::unordered_map<K, V> ret;\n  for (auto kv : dmap) {\n    ret[kv.first] = kv.second;\n  }\n  return ret;\n}\n}  // namespace tir\n}  // namespace tvm\n\nnamespace std {\ntemplate <>\nstruct hash<::tvm::tir::IterVar> : public ::tvm::ObjectPtrHash {};\n}  // namespace std\n#endif  // TVM_TIR_EXPR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/expr_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/expr_functor.h\n *\n * \\brief Functors for tir expressions.\n */\n#ifndef TVM_TIR_EXPR_FUNCTOR_H_\n#define TVM_TIR_EXPR_FUNCTOR_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/tir/expr.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief A dynamical functor that dispatches on in the first Expr argument.\n *  You can use this as a more powerful Visitor, since it allows you to\n *  define function signatures of Visit Function.\n *\n *  This helps you to avoid to book-keep return value of Visitor via state,\n *  which can cause bugs easily when state is incorrectly maintained.\n *\n * \\code\n *  // A functor that set variable to b. and calculate results.\n *  class MyExprFunctor\n *    : public tir::ExprFunctor<int(const Expr&, int)> {\n *   public:\n *    int VisitExpr_(const Variable* op, int b) final {\n *     return b;\n *    }\n *    int VisitExpr_(const IntImm* op, int b) final {\n *      return op->value;\n *    }\n *    int VisitExpr_(const Add* op, int b) final {\n *     return Visit(op->a, b) + Visit(op->b, b);\n *    }\n *  };\n *  MyExprFunctor f;\n *  Var x(\"x\");\n *  ICHECK_EQ(f(x + 1, 2), 3);\n * \\endcode\n *\n * \\note Why do we need this more powerful Functor:\n *\n *  We often need to implement a transformer tasks.\n *  Say we want to take Expr and transform it to some analysis result,\n *  This easily be done incorrectly using plain Visitor. See IRVisitor's\n *  document for possible error cases.\n *\n * \\tparam FType function signiture\n *  This type if only defined for FType with function signiture R(const Expr&, Args...)\n */\ntemplate <typename FType>\nclass ExprFunctor;\n\n// functions to be overriden.\n#define EXPR_FUNCTOR_DEFAULT \\\n  { return VisitExprDefault_(op, std::forward<Args>(args)...); }\n\n#define IR_EXPR_FUNCTOR_DISPATCH(OP)                                                       \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {     \\\n    return self->VisitExpr_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass ExprFunctor<R(const PrimExpr& n, Args...)> {\n private:\n  using TSelf = ExprFunctor<R(const PrimExpr& n, Args...)>;\n  using FType = NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~ExprFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const PrimExpr& n, Args... args) {\n    return VisitExpr(n, std::forward<Args>(args)...);\n  }\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitExpr(const PrimExpr& n, Args... args) {\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitExpr_(const VarNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const SizeVarNode* op, Args... args) {\n    return VisitExpr_(static_cast<const VarNode*>(op), std::forward<Args>(args)...);\n  }\n  virtual R VisitExpr_(const BufferLoadNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const ProducerLoadNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const LoadNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const LetNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const CallNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const AddNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const SubNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const MulNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const DivNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const ModNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const FloorDivNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const FloorModNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const MinNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const MaxNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const EQNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const NENode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const LTNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const LENode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const GTNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const GENode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const AndNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const OrNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const ReduceNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const CastNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const NotNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const SelectNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const RampNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const BroadcastNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const ShuffleNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const IntImmNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const FloatImmNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const StringImmNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExpr_(const AnyNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;\n  virtual R VisitExprDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    return R();\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    // Set dispatch\n    IR_EXPR_FUNCTOR_DISPATCH(VarNode);\n    IR_EXPR_FUNCTOR_DISPATCH(SizeVarNode);\n    IR_EXPR_FUNCTOR_DISPATCH(LoadNode);\n    IR_EXPR_FUNCTOR_DISPATCH(BufferLoadNode);\n    IR_EXPR_FUNCTOR_DISPATCH(ProducerLoadNode);\n    IR_EXPR_FUNCTOR_DISPATCH(LetNode);\n    IR_EXPR_FUNCTOR_DISPATCH(CallNode);\n    IR_EXPR_FUNCTOR_DISPATCH(AddNode);\n    IR_EXPR_FUNCTOR_DISPATCH(SubNode);\n    IR_EXPR_FUNCTOR_DISPATCH(MulNode);\n    IR_EXPR_FUNCTOR_DISPATCH(DivNode);\n    IR_EXPR_FUNCTOR_DISPATCH(ModNode);\n    IR_EXPR_FUNCTOR_DISPATCH(FloorDivNode);\n    IR_EXPR_FUNCTOR_DISPATCH(FloorModNode);\n    IR_EXPR_FUNCTOR_DISPATCH(MinNode);\n    IR_EXPR_FUNCTOR_DISPATCH(MaxNode);\n    IR_EXPR_FUNCTOR_DISPATCH(EQNode);\n    IR_EXPR_FUNCTOR_DISPATCH(NENode);\n    IR_EXPR_FUNCTOR_DISPATCH(LTNode);\n    IR_EXPR_FUNCTOR_DISPATCH(LENode);\n    IR_EXPR_FUNCTOR_DISPATCH(GTNode);\n    IR_EXPR_FUNCTOR_DISPATCH(GENode);\n    IR_EXPR_FUNCTOR_DISPATCH(AndNode);\n    IR_EXPR_FUNCTOR_DISPATCH(OrNode);\n    IR_EXPR_FUNCTOR_DISPATCH(ReduceNode);\n    IR_EXPR_FUNCTOR_DISPATCH(CastNode);\n    IR_EXPR_FUNCTOR_DISPATCH(NotNode);\n    IR_EXPR_FUNCTOR_DISPATCH(SelectNode);\n    IR_EXPR_FUNCTOR_DISPATCH(RampNode);\n    IR_EXPR_FUNCTOR_DISPATCH(ShuffleNode);\n    IR_EXPR_FUNCTOR_DISPATCH(BroadcastNode);\n    IR_EXPR_FUNCTOR_DISPATCH(IntImmNode);\n    IR_EXPR_FUNCTOR_DISPATCH(FloatImmNode);\n    IR_EXPR_FUNCTOR_DISPATCH(StringImmNode);\n    IR_EXPR_FUNCTOR_DISPATCH(AnyNode);\n    return vtable;\n  }\n};\n\n#undef IR_EXPR_FUNCTOR_DISPATCH\n#undef EXPR_FUNCTOR_DEFAULT\n\n/*!\n * \\brief ExprVisitor\n */\nclass TVM_DLL ExprVisitor : public ExprFunctor<void(const PrimExpr&)> {\n public:\n  using ExprFunctor::operator();\n\n protected:\n  using ExprFunctor::VisitExpr;\n  // list of functions to override.\n  void VisitExpr_(const VarNode* op) override;\n  void VisitExpr_(const SizeVarNode* op) override;\n  void VisitExpr_(const LoadNode* op) override;\n  void VisitExpr_(const BufferLoadNode* op) override;\n  void VisitExpr_(const ProducerLoadNode* op) override;\n  void VisitExpr_(const LetNode* op) override;\n  void VisitExpr_(const CallNode* op) override;\n  void VisitExpr_(const AddNode* op) override;\n  void VisitExpr_(const SubNode* op) override;\n  void VisitExpr_(const MulNode* op) override;\n  void VisitExpr_(const DivNode* op) override;\n  void VisitExpr_(const ModNode* op) override;\n  void VisitExpr_(const FloorDivNode* op) override;\n  void VisitExpr_(const FloorModNode* op) override;\n  void VisitExpr_(const MinNode* op) override;\n  void VisitExpr_(const MaxNode* op) override;\n  void VisitExpr_(const EQNode* op) override;\n  void VisitExpr_(const NENode* op) override;\n  void VisitExpr_(const LTNode* op) override;\n  void VisitExpr_(const LENode* op) override;\n  void VisitExpr_(const GTNode* op) override;\n  void VisitExpr_(const GENode* op) override;\n  void VisitExpr_(const AndNode* op) override;\n  void VisitExpr_(const OrNode* op) override;\n  void VisitExpr_(const ReduceNode* op) override;\n  void VisitExpr_(const CastNode* op) override;\n  void VisitExpr_(const NotNode* op) override;\n  void VisitExpr_(const SelectNode* op) override;\n  void VisitExpr_(const RampNode* op) override;\n  void VisitExpr_(const BroadcastNode* op) override;\n  void VisitExpr_(const ShuffleNode* op) override;\n  void VisitExpr_(const IntImmNode* op) override;\n  void VisitExpr_(const FloatImmNode* op) override;\n  void VisitExpr_(const StringImmNode* op) override;\n  void VisitExpr_(const AnyNode* op) override;\n};\n\n/*!\n * \\brief ExprMutator that mutates expressions.\n */\nclass TVM_DLL ExprMutator : protected ExprFunctor<PrimExpr(const PrimExpr&)> {\n public:\n  using ExprFunctor::operator();\n\n protected:\n  using ExprFunctor::VisitExpr;\n  // list of functions to override.\n  PrimExpr VisitExpr_(const VarNode* op) override;\n  PrimExpr VisitExpr_(const SizeVarNode* op) override;\n  PrimExpr VisitExpr_(const LoadNode* op) override;\n  PrimExpr VisitExpr_(const BufferLoadNode* op) override;\n  PrimExpr VisitExpr_(const ProducerLoadNode* op) override;\n  PrimExpr VisitExpr_(const LetNode* op) override;\n  PrimExpr VisitExpr_(const CallNode* op) override;\n  PrimExpr VisitExpr_(const AddNode* op) override;\n  PrimExpr VisitExpr_(const SubNode* op) override;\n  PrimExpr VisitExpr_(const MulNode* op) override;\n  PrimExpr VisitExpr_(const DivNode* op) override;\n  PrimExpr VisitExpr_(const ModNode* op) override;\n  PrimExpr VisitExpr_(const FloorDivNode* op) override;\n  PrimExpr VisitExpr_(const FloorModNode* op) override;\n  PrimExpr VisitExpr_(const MinNode* op) override;\n  PrimExpr VisitExpr_(const MaxNode* op) override;\n  PrimExpr VisitExpr_(const EQNode* op) override;\n  PrimExpr VisitExpr_(const NENode* op) override;\n  PrimExpr VisitExpr_(const LTNode* op) override;\n  PrimExpr VisitExpr_(const LENode* op) override;\n  PrimExpr VisitExpr_(const GTNode* op) override;\n  PrimExpr VisitExpr_(const GENode* op) override;\n  PrimExpr VisitExpr_(const AndNode* op) override;\n  PrimExpr VisitExpr_(const OrNode* op) override;\n  PrimExpr VisitExpr_(const ReduceNode* op) override;\n  PrimExpr VisitExpr_(const CastNode* op) override;\n  PrimExpr VisitExpr_(const NotNode* op) override;\n  PrimExpr VisitExpr_(const SelectNode* op) override;\n  PrimExpr VisitExpr_(const RampNode* op) override;\n  PrimExpr VisitExpr_(const BroadcastNode* op) override;\n  PrimExpr VisitExpr_(const ShuffleNode* op) override;\n  PrimExpr VisitExpr_(const IntImmNode* op) override;\n  PrimExpr VisitExpr_(const FloatImmNode* op) override;\n  PrimExpr VisitExpr_(const StringImmNode* op) override;\n  PrimExpr VisitExpr_(const AnyNode* op) override;\n};\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_EXPR_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/function.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/function.h\n * \\brief TIR Function.\n */\n#ifndef TVM_TIR_FUNCTION_H_\n#define TVM_TIR_FUNCTION_H_\n\n#include <tvm/ir/function.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/tir/buffer.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Primitive functions that contains TIR statements.\n *\n * The PrimFunc provides low-level code representation does not\n * automatically manage\n *\n * \\sa PrimFunc\n */\nclass PrimFuncNode : public BaseFuncNode {\n public:\n  /*! \\brief Function parameters */\n  Array<tir::Var> params;\n  /*! \\brief The body of the function */\n  tir::Stmt body;\n  /*! \\brief The return type of the function. */\n  Type ret_type;\n  /*!\n   * \\brief Maps some parameters to specific Buffer data structures.\n   *\n   *  buffer_map provides a way to express data structure's field and shape\n   *  constraints. The provided information is used in the program analysis\n   *  and the code generation.\n   *\n   *  - It defines the vars in the Buffer (m, n) in the cases below when\n   *    they appears in the buffer_map for the first time.\n   *  - When a var appears multiple times, they translate into runtime\n   *    assertion to check the field constraint.\n   *\n   *  \\code\n   *\n   *   # The corresponding fields of f are as follows\n   *   #\n   *   # - f.params = [a, b]\n   *   # - f.buffer_map = {a: A, b: B}\n   *   # - A = decl_buffer(shape=[m, n])\n   *   # - B = decl_buffer(shape=[m, n])\n   *\n   *   def f(a, b):\n   *       m, n = var(), var()\n   *       A = bind_buffer(a, shape=[m, n])\n   *       B = bind_buffer(b, shape=[m, n])\n   *       # body\n   *\n   *  \\endcode\n   *\n   *  buffer_map is a sugar to express:\n   *  - Parameter unpacking: e.g. I can load a.shape[0] to get value of m\n   *  - Constraint checking: a.shape[0] must equal b.shape[0] because they\n   *    both corresponds to m.\n\n   *  While we could have express parameter unpacking and constraint using\n   *  normal statements, making buffer_map as first class citizen of PrimFunc\n   *  will make program analysis much easier.\n   */\n  Map<tir::Var, Buffer> buffer_map;\n\n  /*! \\brief The buffer map prior to flattening.\n   *\n   * This contains the buffers as they exists prior to flattening, and\n   * is used for validating an input tensor passed into the packed\n   * API.  Any buffer that is present in `buffer_map` but not present\n   * in `preflattened_buffer_map` is assumed to be the same before\n   * and after flattening (e.g. a 1-d tensor that is backed by 1-d\n   * flat memory).\n   *\n   * TODO(Lunderberg): Remove preflattened_buffer_map, and instead\n   * declare each flattened buffer as aliasing the original tensor\n   * shape.  This should include improving the StmtExprMutator to\n   * provide easier interactions with Buffer objects, so that the\n   * bookkeeping of relationships between buffers doesn't need to be\n   * repeated across several transforms.\n   */\n  Map<tir::Var, Buffer> preflattened_buffer_map;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"params\", &params);\n    v->Visit(\"body\", &body);\n    v->Visit(\"ret_type\", &ret_type);\n    v->Visit(\"buffer_map\", &buffer_map);\n    v->Visit(\"preflattened_buffer_map\", &preflattened_buffer_map);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"span\", &span);\n    v->Visit(\"_checked_type_\", &checked_type_);\n  }\n\n  bool SEqualReduce(const PrimFuncNode* other, SEqualReducer equal) const {\n    // visit params and buffer_map first as they contains defs.\n    return equal.DefEqual(params, other->params) && equal(buffer_map, other->buffer_map) &&\n           equal(preflattened_buffer_map, other->preflattened_buffer_map) &&\n           equal(ret_type, other->ret_type) && equal(body, other->body) &&\n           equal(attrs, other->attrs);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(params);\n    hash_reduce(buffer_map);\n    hash_reduce(preflattened_buffer_map);\n    hash_reduce(ret_type);\n    hash_reduce(body);\n    hash_reduce(attrs);\n  }\n  /*!\n   * \\brief Return the derived function annotation of this function.\n   *\n   * \\return The function type annotation.\n   * \\note The function type annotation of PrimExpr is\n   *       directly derived from the Vars without the need of type inference.\n   */\n  TVM_DLL FuncType func_type_annotation() const;\n\n  static constexpr const char* _type_key = \"tir.PrimFunc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PrimFuncNode, BaseFuncNode);\n};\n\n/*!\n * \\brief Managed reference to PrimFuncNode.\n * \\sa PrimFuncNode\n */\nclass PrimFunc : public BaseFunc {\n public:\n  /*!\n   * \\brief Constructor\n   *\n   * \\param params The parameters of the function.\n   *\n   * \\param body The body of the function.\n   *\n   * \\param ret_type The return type of the function.\n   *\n   * \\param buffer_map The buffer map for parameter buffer unpacking.\n   * This contains buffer objects as they appear in the body of the\n   * PrimFunc.  (e.g. a buffer of shape ``[1024]`` originally\n   * generated as a tensor of shape ``[32, 32]``)\n   *\n   * \\param preflattened_buffer_map The buffer map for\n   * parameter buffer unpacking.  This contains buffer\n   * objects as they are expected to be passed in by the\n   * callee.  (e.g. a buffer of shape ``[32, 32]`` originally\n   * generated as a tensor of shape ``[32, 32]``)\n   *\n   * \\param attrs Additional function attributes.\n   *\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL PrimFunc(\n      Array<tir::Var> params, Stmt body, Type ret_type = VoidType(),\n      Map<tir::Var, Buffer> buffer_map = Map<tir::Var, Buffer>(),\n      Optional<Map<tir::Var, Buffer>> preflattened_buffer_map = Optional<Map<tir::Var, Buffer>>(),\n      DictAttrs attrs = NullValue<DictAttrs>(), Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PrimFunc, BaseFunc, PrimFuncNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(PrimFuncNode);\n};\n\n/*!\n * \\brief Tensor intrinsics for tensorization\n */\nclass TensorIntrinNode : public Object {\n public:\n  /*! \\brief The function to describe the computation. */\n  PrimFunc desc;\n  /*! \\brief The function of the implementation for the execution. */\n  PrimFunc impl;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"desc\", &desc);\n    v->Visit(\"impl\", &impl);\n  }\n\n  static constexpr const char* _type_key = \"tir.TensorIntrin\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorIntrinNode, Object);\n};\n\n/*!\n * \\brief Managed reference to TensorIntrinNode.\n */\nclass TensorIntrin : public ObjectRef {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param desc The function to describe the computation.\n   * \\param impl The function of the implementation for the execution.\n   */\n  TVM_DLL explicit TensorIntrin(PrimFunc desc, PrimFunc impl);\n\n  /*!\n   * \\brief Create and register a TensorIntrin. After registration, the TensorIntrin can be looked\n   * up with its name.\n   * \\param name The name of the TensorIntrin to register\n   * \\param intrin The TensorIntrin to register.\n   * \\param override Whether override existing intrinsic.\n   * \\throws This method throws an exception if the TensorIntrin with the specified name already\n   *         exists.\n   */\n  TVM_DLL static void Register(String name, TensorIntrin intrin, bool override = false);\n\n  /*!\n   * \\brief Look up TensorIntrin by name. Raises an exception if not found.\n   * \\param name The name of the TensorIntrin.\n   * \\param allow_missing Whether to allow missing tensor intrin. If false, an exception is raised\n   *    if the tensor intrin is not found.\n   * \\return The TensorIntrin with the specified name.\n   * \\throws This method throws an exception if the TensorIntrin does not exist and allow_missing is\n   * false.\n   */\n  TVM_DLL static Optional<TensorIntrin> Get(String name, bool allow_missing = false);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TensorIntrin, ObjectRef, TensorIntrinNode)\n};\n\n/*\n * \\brief Specialize parameters of PrimFunc.\n * \\param func The PrimFunc to be specialized.\n * \\param param_map The mapping from function params to the instance.\n * \\return The new function with parameter specialized.\n * \\note We can define a Meta TIR function with symbolic shape:\n *\n * \\code\n *  @T.prim_func\n *  def mem_copy(a: T.handle, b: T.handle, m: T.int32, n: T.int32) -> None:\n *      A = T.match_buffer(a, (m, n), \"float32\")\n *      B = T.match_buffer(b, (m, n), \"float32\")\n *      for i, j in T.grid(m, n):\n *          with T.block():\n *              vi, vj = T.axis.remap(\"SS\", [i, j])\n *              B[vi, vj] = A[vi, vj]\n * \\endcode\n *\n * Then we can make it specialized with given shapes or buffers.\n *\n * \\code\n *  a, _, m, n = mem_copy.params\n *  func = mem_copy.specialize({a: tir.decl_buffer((16, 16))})\n *  # or\n *  func = mem_copy.specialize({n: 16, m: 16})\n * \\endcode\n *\n * \\code {.language-id}\n *  @T.prim_func\n *  def mem_copy_16_16(a: T.handle, b: T.handle) -> None:\n *      A = T.match_buffer(a, (16, 16), \"float32\")\n *      B = T.match_buffer(b, (16, 16), \"float32\")\n *      for i, j in T.grid(16, 16):\n *          with T.block():\n *              vi, vj = T.axis.remap(\"SS\", [i, j])\n *              B[vi, vj] = A[vi, vj]\n * \\endcode\n */\nPrimFunc Specialize(PrimFunc func, const Map<Var, ObjectRef>& param_map);\n\n/*!\n * \\brief PrimFunc specific attribute names.\n *\n * \\sa tvm::attr\n */\nnamespace attr {\n/*!\n * \\brief List of thread IterVar that a DeviceLaunch function corresponds to.\n *\n * Type: Array<tir::IterVar>\n *\n * We call a device kernel launch function f using the following convention:\n *\n * Call(f,\n *      [arg1, arg2, ..., arg_n,\n *       work_size_1, work_size_2, ... work_size_m, dyn_shmem_size])\n *\n * Here n = len(arg), m = len(work_size) = len(device_thread_axis).\n *\n * When kDeviceUseDynSharedMemory is not set, dyn_shmem_size argument is omitted.\n *\n * The list of device_thread_axis indicates how can be bind the\n * work_size arguments to the corresponding threads.\n *\n * \\sa tvm::CallingConv::kDeviceKernelLaunch\n */\nconstexpr const char* kDeviceThreadAxis = \"tir.device_thread_axis\";\n\n/*!\n * \\brief Whether or not use dynamic shared memory.\n *\n * Type: Integer\n */\nconstexpr const char* kDeviceUseDynSharedMemory = \"tir.device_use_dyn_shared_memory\";\n\n/*!\n * \\brief Whether to set noalias rule on the function arguments.\n *\n * Type: Integer\n */\nconstexpr const char* kNoAlias = \"tir.noalias\";\n\n/*!\n * \\brief Mark the function as the entry function of\n *        the final generated runtime module.\n *\n * Type: Integer\n *\n * \\note There can only be one entry function per module.\n */\nconstexpr const char* kIsEntryFunc = \"tir.is_entry_func\";\n\n/*!\n * \\brief Mark the function as the global function called from the host.\n *\n * Type: Integer\n */\nconstexpr const char* kIsGlobalFunc = \"tir.is_global_func\";\n\n}  // namespace attr\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_FUNCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/index_map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/index_map.h\n * \\brief Defines a remapping of buffer indices\n *\n * For use with tvm::tir::Buffer.\n */\n#ifndef TVM_TIR_INDEX_MAP_H_\n#define TVM_TIR_INDEX_MAP_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/object.h>\n#include <tvm/tir/var.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace arith {\nclass Analyzer;\n}\n}  // namespace tvm\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Defines a mapping between two representations of indices\n * into a buffer.\n *\n * This is primarily used for layout transformations of Buffer\n * objects.\n */\nclass IndexMapNode : public Object {\n public:\n  /*! \\brief Variables representing the indices prior to remapping.\n   *\n   * If initial_indices is empty, then final_indices should also be\n   * empty, and no mapping is applied.\n   */\n  Array<Var> initial_indices;\n\n  /*!\n   * \\brief Expressions defining the indices after remapping.\n   *\n   * These expressions should only be in terms of the initial_indices,\n   * and must be expressible as an IterSumExpr.  The mapping from\n   * initial_indices to final_indices must be injective.\n   *\n   * If final_indices is empty, then initial_indices should also be\n   * empty, and the map is an identity function.\n   */\n  Array<PrimExpr> final_indices;\n\n  /*!\n   * \\brief The inverse index map.\n   *\n   * When this is defined, IndexMap::Inverse will return the\n   * pre-defined inverse index map.  Otherwise, the inverse index map\n   * will be computed on the fly.  It is the user's responsibility to\n   * ensure the correctness of the pre-defined inverse index map.\n   *\n   * \\note ObjectRef is used here instead of IndexMap to avoid circular reference.\n   */\n  Optional<ObjectRef> inverse_index_map;\n\n  /*!\n   * \\brief Default constructor\n   *\n   * Defines the mapping as an identity function, with initial_indices\n   * equal to the final indices.\n   */\n  IndexMapNode() {}\n\n  /*!\n   * \\brief Map indices to the output space\n   *\n   * \\param indices The indices in the input space.  Should contain\n   * one value for each variable in `initial_indices`.\n   *\n   * \\param analyzer An optional analyzer to be used to simplify the\n   * resulting expressions.  If null, will use a fresh analyzer.\n   *\n   * \\returns The indices in the output space.  Contains one value for\n   * each expression in `final_indices`.\n   */\n  Array<PrimExpr> MapIndices(const Array<PrimExpr>& indices,\n                             arith::Analyzer* analyzer = nullptr) const;\n\n  /*! \\brief Map a memory range to the output space\n   *\n   * If contiguous memory locations in the input space are not\n   * necessarily contiguous in the output space (e.g. `lambda i:\n   * [8*(i%8) + (i//8)]`), then this will return the smallest range\n   * such that all valid indices are contained within the given range.\n   *\n   * \\param ranges The ranges in the input space.  Should contain one\n   * value for each variable in `initial_indices`.\n   *\n   * \\param analyzer An optional analyzer to be used to simplify the\n   * resulting expressions.  If null, will use a fresh analyzer.\n   *\n   * \\returns The ranges in the output space.  Contains one value for\n   * each expression in `final_indices`.\n   */\n  Array<Range> MapRanges(const Array<Range>& ranges, arith::Analyzer* analyzer = nullptr) const;\n\n  /*! \\brief Map a buffer shape to the output space\n   *\n   * \\param shape The buffer shape in the input space.  Should contain\n   * one value for each variable in `initial_indices`.\n   *\n   * \\param analyzer An optional analyzer to be used to simplify the\n   * resulting expressions.  If null, will use a fresh analyzer.\n   *\n   * \\returns The buffer shape in the output space.  Contains one\n   * value for each expression in `final_indices`.\n   */\n  Array<PrimExpr> MapShape(const Array<PrimExpr>& shape, arith::Analyzer* analyzer = nullptr) const;\n\n  /* \\brief Map an NDArray according to this index map\n   *\n   * \\param arr_src The NDArray whose layout is transformed by this index map.\n   *\n   * \\returns The transformed NDArray.\n   */\n  runtime::NDArray MapNDArray(runtime::NDArray arr_src) const;\n\n  /*!\n   * \\brief Convert to string representation in Python.\n   * \\return The stringified lambda expression in Python.\n   */\n  String ToPythonString() const;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"initial_indices\", &initial_indices);\n    v->Visit(\"final_indices\", &final_indices);\n    v->Visit(\"inverse_index_map\", &inverse_index_map);\n  }\n\n  bool SEqualReduce(const IndexMapNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(initial_indices, other->initial_indices) &&\n           equal(final_indices, other->final_indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(initial_indices);\n    hash_reduce(final_indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.IndexMap\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(IndexMapNode, Object);\n};\n\nclass IndexMap : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param initial_indices Variables representing the indices prior to remapping\n   * \\param final_indices Expressions defining the indices after remapping.\n   * \\param inverse_index_map The optional pre-defined inverse index map\n   */\n  IndexMap(Array<Var> initial_indices, Array<PrimExpr> final_indices,\n           Optional<IndexMap> inverse_index_map = NullOpt);\n\n  /*!\n   * \\brief Create an index map from a packed function\n   * \\param ndim The number of dimensions\n   * \\param func The function to be applied\n   * \\param inverse_index_map The optional pre-defined inverse index map\n   * \\return The created index map\n   */\n  static IndexMap FromFunc(int ndim, runtime::TypedPackedFunc<Array<PrimExpr>(Array<Var>)> func,\n                           Optional<IndexMap> inverse_index_map = NullOpt);\n\n  /*! \\brief Generate the inverse mapping.\n   *\n   * The range of the input indices is required in order to ensure\n   * that the transformation is bijective over the input domain.\n   *\n   * If the user has supplied an `inverse_index_map`, that map is\n   * assumed to be correct and bijective, and is returned.\n   */\n  IndexMap Inverse(Array<Range> initial_ranges) const;\n\n  /*! \\brief Generate the inverse mapping.\n   *\n   * Determine the inverse, where the output range may contain\n   * addresses that do not correspond to an address in the input\n   * range.\n   *\n   * \\return The inverted index map, along with the predicate for\n   * which the inverse maps to a valid range.\n   */\n  std::pair<IndexMap, PrimExpr> NonSurjectiveInverse(Array<Range> initial_ranges) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IndexMap, ObjectRef, IndexMapNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_INDEX_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/op.h\n * \\brief Common operators defined for Expr.\n *\n * \\note Most of the operator defined here perform simple constant folding\n *   when the type is int32 or int64 for simplifying the index expressions.\n */\n// Acknowledgement: Most operator APIs originate from Halide.\n#ifndef TVM_TIR_OP_H_\n#define TVM_TIR_OP_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/op.h>\n#include <tvm/ir/type.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt.h>\n\n#include <algorithm>\n#include <limits>\n#include <type_traits>\n\nnamespace tvm {\n\n// Most common operators can be overloaded by argument type(PrimExpr).\n// So we put them under the root namespace.\n//\n// We put more developer oriented APIs -- make_const and is_const under tir\n// as they are more specific to the tir namespace.\n\n/*!\n * \\brief Get the type of the expression under the unified type system.\n *\n * This function could return a more refined type than\n * the runtime type provided by expr->dtype\n *\n * \\param expr The input parameter.\n * \\return The result type.\n *\n * \\sa tvm/ir/type.h for discussion about the relation between Type and runtime::DataType.\n */\nTVM_DLL Type GetType(const PrimExpr& expr);\n\n/*!\n * \\brief Get the type corresponding to DataType\n * \\param dtype The data type\n * \\return The result type\n *\n * \\sa tvm/ir/type.h for discussion about the relation between Type and runtime::DataType.\n */\nTVM_DLL Type GetTypeFromRuntimeDataType(const DataType& dtype);\n\n/*!\n * \\brief Get the implied DataType for storing values with type during runtime.\n *\n * \\param type The input type.\n * \\return The result runtime::DataType.\n *\n * \\sa tvm/ir/type.h for discussion about the relation between Type and runtime::DataType.\n */\nTVM_DLL runtime::DataType GetRuntimeDataType(const Type& type);\n\n/*!\n * \\brief Return the value.\n *\n * \\param value The returned value.\n * \\param span The location of this operation in the source.\n * \\return The return expression.\n */\nTVM_DLL PrimExpr ret(PrimExpr value, Span span = Span());\n\n/*!\n * Query the maximum possible value of dtype.\n * \\param dtype The data type.\n * \\param span The location of this operation in the source.\n * \\return the maximum possible value in this format.\n */\nTVM_DLL PrimExpr max_value(const DataType& dtype, Span span = Span());\n\n/*!\n * Query the minimum possible value of dtype.\n * \\param dtype The data type.\n * \\param span The location of this operation in the source.\n * \\return the minimum possible value in this format.\n */\nTVM_DLL PrimExpr min_value(const DataType& dtype, Span span = Span());\n\n/*!\n * Get the value of infinity.\n * \\param dtype The data type.\n * \\param span The location of this operation in the source.\n * \\return the infinity value in this format.\n */\nTVM_DLL PrimExpr infinity(const DataType& dtype, Span span = Span());\n\n/*!\n * \\brief cast value to type.\n *\n * \\param t the target type.\n * \\param value The value\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note This function may return value if the type is the same.\n */\nTVM_DLL PrimExpr cast(const DataType& t, PrimExpr value, Span span = Span());\n/*!\n * \\brief perform reinterpret cast value to type.\n *\n * \\param t the target type.\n * \\param value The value\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note This function may return value if the type is the same.\n */\nTVM_DLL PrimExpr reinterpret(const DataType& t, PrimExpr value, Span span = Span());\n/*!\n * \\brief add operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr add(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief subtraction operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr sub(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief negation.\n *\n * \\param a input.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr neg(PrimExpr a, Span span = Span());\n/*!\n * \\brief multiplication operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr mul(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief left shift operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr left_shift(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief right shift operator\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr right_shift(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief greater\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr greater(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief greater_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr greater_equal(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief less\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr less(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief less_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr less_equal(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr equal(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief not_equal\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr not_equal(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief and\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr logical_and(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief or\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr logical_or(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief not\n *\n * \\param a left operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note This operator does eager constant folding.\n */\nTVM_DLL PrimExpr logical_not(PrimExpr a, Span span = Span());\n/*!\n * \\brief compute division in C semantics.\n *\n * a / b as in C/C++.\n *\n * When operands are integers, it directly corresponds to truncdiv.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr div(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute trunc(a / b)\n *\n * This is the default integer division behavior in C.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr truncdiv(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute the remainder of truncdiv\n *\n * This is the default integer division behavior in C.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr truncmod(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute floor(a / b) where a and b are non-negative.\n *\n * Use this function for index split calculation.\n *\n * This function might take advantage of the fact\n * that a and b are non-negative.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr indexdiv(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute ceil(a / b) where a and b are non-negative.\n *\n * Use this function for shape split calculation.\n *\n * This function might take advantage of the fact\n * that a and b are non-negative.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       shape types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr shapediv(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute the remainder floor(a / b) where a and b are non-negative.\n *\n * Use this function for index split calculation.\n * This function might take advantage of the fact\n * that a and b are non-negative.\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr indexmod(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute floor(a / b)\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr floordiv(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute ceil(a / b)\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr ceildiv(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief compute the remainder of floordiv\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr floormod(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take maximum of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr max(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take minimum of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr min(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take bitwise and of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr bitwise_and(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take bitwise or of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr bitwise_or(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take bitwise xor of two values\n *\n * \\param a left operand\n * \\param b right operand\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr bitwise_xor(PrimExpr a, PrimExpr b, Span span = Span());\n/*!\n * \\brief take bitwise negation of two values\n *\n * \\param a the input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr bitwise_neg(PrimExpr a, Span span = Span());\n/*!\n * \\brief Conditional expression.\n *\n * \\param cond The condition\n * \\param true_value The value when results are true.\n * \\param false_value The value when results are false.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * \\note this function does eager constant folding for\n *       index types(int32, int64) when possible.\n */\nTVM_DLL PrimExpr if_then_else(PrimExpr cond, PrimExpr true_value, PrimExpr false_value,\n                              Span span = Span());\n/*!\n * \\brief Mark condition as likely.\n * \\param cond The condition\n * \\param span The location of this operation in the source.\n * \\return The marked expression.\n */\nTVM_DLL PrimExpr likely(PrimExpr cond, Span span = Span());\n/*!\n * \\brief Calculate power(x, y)\n * \\param x The left operand.\n * \\param y The right operand.\n * \\param span The location of this operation in the source.\n */\nTVM_DLL PrimExpr pow(PrimExpr x, PrimExpr y, Span span = Span());\n/*!\n * \\brief Calculate absolute value of x.\n * \\param x The input data\n * \\param span The location of this operation in the source.\n *\n * \\return The aboslute value of input data x\n */\nTVM_DLL PrimExpr abs(PrimExpr x, Span span = Span());\n/*!\n * \\brief Check if x is NaN.\n * \\param x The input data\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr isnan(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Check if x is finite.\n * \\param x The input data\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr isfinite(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Check if x is infinite.\n * \\param x The input data\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr isinf(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief sum of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n * \\return The result.\n */\nTVM_DLL PrimExpr sum(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                     Span span = Span());\n\n/*!\n * \\brief logical And of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n */\nTVM_DLL PrimExpr all(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                     Span span = Span());\n\n/*!\n * \\brief logical Or of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n * \\return The result.\n */\nTVM_DLL PrimExpr any(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                     Span span = Span());\n\n/*!\n * \\brief max of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n * \\return The result.\n */\nTVM_DLL PrimExpr max(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                     Span span = Span());\n\n/*!\n * \\brief max of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n * \\return The result.\n */\nTVM_DLL PrimExpr min(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                     Span span = Span());\n\n/*!\n * \\brief product of source expression over axis\n * \\param source The source expression.\n * \\param axis List of iteration variables that will be used for reduction.\n * \\param init The value with which to initialize the output.\n * \\param span The location of this operation in the source.\n * \\return The result.\n */\nTVM_DLL PrimExpr prod(PrimExpr source, Array<tir::IterVar> axis, Array<PrimExpr> init = {},\n                      Span span = Span());\n\n/*!\n * \\brief Calculate floor(x)\n * \\param x The input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr floor(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Calculate ceil(x)\n * \\param x The input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr ceil(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Calculate round(x)\n * \\param x The input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr round(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Calculates std::nearbyint(x)\n * \\param x The input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n * This is a faster alternate to round.\n */\nTVM_DLL PrimExpr nearbyint(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Calculate trunc(x)\n * \\param x The input expression.\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\nTVM_DLL PrimExpr trunc(PrimExpr x, Span span = Span());\n\n/*!\n * \\brief Construct a large uint constant by its low 32 bits and high 32bits.\n * \\param dtype The final data type.\n * \\param low The lower 32 bits.\n * \\param high The higher 32 bits.\n * \\param span The location of this operation in the source.\n * \\return The constructed expression.\n */\nTVM_DLL PrimExpr LargeUIntImm(DataType dtype, int64_t low, int64_t high, Span span = Span());\n\n/*!\n * \\brief Execute a multiplication between two Q-numbers x and y\n * followed by a right shift s. The mathematical expression is:\n *\n *    out = round(x*y*2^-s)\n *\n * Please note that the two Q-numbers x and y are supposed to have\n * the same number of fractional bits q.\n *\n * More about Q-numbers here: https://en.wikipedia.org/wiki/Q_(number_format)\n *\n * The rounding rule is to the nearest value, rounding half up\n * (i.e., round(x.1) = x and round (x.5) = x+1)\n * \\param x first Q-number\n * \\param y second Q-number\n * \\param q number of fractional bits in x and y. Needs to be > 0\n * \\param s integer right shift\n * \\param span The location of this operation in the source.\n * \\return The constructed expression.\n */\nTVM_DLL PrimExpr q_multiply_shift(PrimExpr x, PrimExpr y, PrimExpr q, PrimExpr s,\n                                  Span span = Span());\n\n// Intrinsic operators\n#define TVM_DECLARE_INTRIN_UNARY(OpName)                                \\\n  inline PrimExpr OpName(PrimExpr x, Span span = Span()) {              \\\n    static const Op& op = Op::Get(\"tir.\" #OpName);                      \\\n    if (x.dtype().is_bfloat16()) {                                      \\\n      DataType bf16_dtype = x.dtype();                                  \\\n      DataType fp32_dtype(kDLFloat, 32, bf16_dtype.lanes());            \\\n      PrimExpr x_fp32 = tir::Cast(fp32_dtype, {x}, span);               \\\n      PrimExpr result_fp32 = tir::Call(fp32_dtype, op, {x_fp32}, span); \\\n      return tir::Cast(bf16_dtype, {result_fp32}, span);                \\\n    } else {                                                            \\\n      return tir::Call(x.dtype(), op, {x}, span);                       \\\n    }                                                                   \\\n  }\n\nTVM_DECLARE_INTRIN_UNARY(exp);\nTVM_DECLARE_INTRIN_UNARY(exp2);\nTVM_DECLARE_INTRIN_UNARY(exp10);\nTVM_DECLARE_INTRIN_UNARY(erf);\nTVM_DECLARE_INTRIN_UNARY(tanh);\nTVM_DECLARE_INTRIN_UNARY(sigmoid);\nTVM_DECLARE_INTRIN_UNARY(sqrt);\nTVM_DECLARE_INTRIN_UNARY(rsqrt);\nTVM_DECLARE_INTRIN_UNARY(log);\nTVM_DECLARE_INTRIN_UNARY(log2);\nTVM_DECLARE_INTRIN_UNARY(log10);\nTVM_DECLARE_INTRIN_UNARY(log1p);\nTVM_DECLARE_INTRIN_UNARY(popcount);\nTVM_DECLARE_INTRIN_UNARY(tan);\nTVM_DECLARE_INTRIN_UNARY(cos);\nTVM_DECLARE_INTRIN_UNARY(cosh);\nTVM_DECLARE_INTRIN_UNARY(sin);\nTVM_DECLARE_INTRIN_UNARY(sinh);\nTVM_DECLARE_INTRIN_UNARY(asin);\nTVM_DECLARE_INTRIN_UNARY(acos);\nTVM_DECLARE_INTRIN_UNARY(atan);\nTVM_DECLARE_INTRIN_UNARY(acosh);\nTVM_DECLARE_INTRIN_UNARY(asinh);\nTVM_DECLARE_INTRIN_UNARY(atanh);\nTVM_DECLARE_INTRIN_UNARY(clz);\n\n#define TVM_DECLARE_INTRIN_BINARY(OpName)                              \\\n  inline PrimExpr OpName(PrimExpr x, PrimExpr y, Span span = Span()) { \\\n    static const Op& op = Op::Get(\"tir.\" #OpName);                     \\\n    return tir::Call(x.dtype(), op, {x, y}, span);                     \\\n  }\n\nTVM_DECLARE_INTRIN_BINARY(atan2);\nTVM_DECLARE_INTRIN_BINARY(nextafter);\nTVM_DECLARE_INTRIN_BINARY(copysign);\nTVM_DECLARE_INTRIN_BINARY(hypot);\nTVM_DECLARE_INTRIN_BINARY(ldexp);\n\nnamespace tir {\n\n/*!\n * \\brief Check if type is a pointer to a runtime element type.\n * \\param type The type to be checked.\n * \\param element_type The corresponding element type.\n * \\return The check results\n */\ninline bool IsPointerType(const Type& type, const DataType& element_type) {\n  if (!type.defined()) return false;\n  if (const auto* ptr_type = type.as<PointerTypeNode>()) {\n    if (const auto* prim_type = ptr_type->element_type.as<PrimTypeNode>()) {\n      return prim_type->dtype == element_type;\n    }\n  }\n  return false;\n}\n\n/*!\n * \\brief Make a const value with certain data type.\n * \\param t The target type.\n * \\param value The input value\n * \\return the result expression.\n * \\tparam ValueType The constant value type\n * \\param span The location of this operation in the source.\n */\ntemplate <typename ValueType,\n          typename = typename std::enable_if<std::is_pod<ValueType>::value>::type>\ninline PrimExpr make_const(DataType t, ValueType value, Span span = Span());\n/*!\n * \\brief Make a const zero expr.\n * \\param t The target type.\n * \\param span The location of this operation in the source.\n * \\return the result expression.\n */\ninline PrimExpr make_zero(DataType t, Span span = Span());\n/*!\n * \\brief Make a constant true expression.\n * \\param lanes The number of lanes in the bool\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\ninline PrimExpr const_true(int lanes = 1, Span span = Span()) {\n  return make_const(DataType::UInt(1, lanes), 1);\n}\n/*!\n * \\brief Make a constant false expression.\n * \\param lanes The number of lanes in the bool\n * \\param span The location of this operation in the source.\n * \\return The result expression.\n */\ninline PrimExpr const_false(int lanes = 1, Span span = Span()) {\n  return make_const(DataType::UInt(1, lanes), 0);\n}\n/*!\n * \\brief Get x as constant int expression.\n * \\param x The expression\n * \\return the address to the int expression,\n *         return nullptr, if x is not IntImm.\n */\ninline const int64_t* as_const_int(const PrimExpr& x) {\n  if (!x.defined()) return nullptr;\n  if (const tir::IntImmNode* op = x.as<tir::IntImmNode>()) {\n    return &(op->value);\n  }\n\n  return nullptr;\n}\n\n/*!\n * \\brief Check whether x is a constant integer expression.\n * \\param x The input argument\n * \\param value the value to be compared against.\n * \\return whether x is constant expression.\n */\ninline bool is_const_int(const PrimExpr& x, int64_t value);\n\n/*!\n * \\brief Check whether stmt is nop.\n * \\param stmt The input statement\n * \\return whether stmt is nop\n */\ninline bool is_no_op(const tir::Stmt& stmt);\n\n/*!\n * \\brief Check whether x is a constant integer 1\n * \\param x The input argument.\n * \\note This only return true for integer types.\n * \\return whether x is constant 1\n */\ninline bool is_one(const PrimExpr& x) { return is_const_int(x, 1); }\n\n/*!\n * \\brief Check whether x is a constant integer 0\n * \\param x The input argument\n * \\return whether x is constant 0\n * \\note This only return true for integer types.\n */\ninline bool is_zero(const PrimExpr& x) { return is_const_int(x, 0); }\n\n/*!\n * \\brief Check whether x is an integer constant.\n * \\note This only return true for integer types.\n * \\return whether x is constant\n */\ninline bool is_const_int(const PrimExpr& x);\n\n/*!\n * \\brief Check whether x is an integer/float constant.\n * \\note This only return true for integer types.\n * \\return whether x is constant\n */\ninline bool is_const_number(const PrimExpr& x);\n\n/*!\n * \\brief Left fold.\n * \\param freduce The reduction function.\n * \\param init_value The initial value.\n * \\param values The values to be folded.\n * \\param span The location of the fold in the source.\n * \\return The result.\n * \\tparam FReduce The type of the reduction.\n */\ntemplate <typename FReduce>\ninline PrimExpr foldl(FReduce freduce, PrimExpr init_value, const Array<PrimExpr>& values,\n                      Span span = Span());\n\n/*!\n * \\brief Check whether x is a constant power of two\n * If x is power of two, write the power to the shift.\n *\n * \\param x The input expression.\n * \\param shift The output shift if x is power of two.\n * \\return whether x is constant power of two\n */\nTVM_DLL bool is_const_power_of_two_integer(const PrimExpr& x, int* shift);\n\n// Implementation details after this\ninline bool is_const_int(const PrimExpr& x) { return as_const_int(x); }\n\ninline bool is_const_number(const PrimExpr& x) {\n  if (x.as<tir::IntImmNode>()) {\n    return true;\n  } else if (x.as<tir::FloatImmNode>()) {\n    return true;\n  } else if (const auto* op = x.as<tir::BroadcastNode>()) {\n    return (op->value->IsInstance<tir::IntImmNode>() || op->value->IsInstance<tir::FloatImmNode>());\n  }\n  return false;\n}\n\ninline bool is_positive_const(const PrimExpr& a) {\n  const int64_t* as_int = as_const_int(a);\n  return as_int && (*as_int > 0);\n}\n\ninline bool is_negative_const(const PrimExpr& a) {\n  const int64_t* as_int = as_const_int(a);\n  return as_int && (*as_int < 0);\n}\n\ninline bool is_const_int(const PrimExpr& x, int64_t value) {\n  const int64_t* as_int = as_const_int(x);\n  return as_int && (*as_int == value);\n}\n\ninline bool is_no_op(const tir::Stmt& stmt) {\n  if (!stmt.defined()) return true;\n  if (const auto* op = stmt.as<tir::EvaluateNode>()) {\n    return is_const_int(op->value);\n  }\n  if (const auto* op = stmt.as<tir::SeqStmtNode>()) {\n    return op->seq.size() == 0;\n  }\n  return false;\n}\n\ntemplate <typename ValueType>\ninline PrimExpr MakeConstScalar(DataType t, ValueType value, Span span = Span()) {\n  if (t.is_int()) return IntImm(t, static_cast<int64_t>(value), span);\n  if (t.is_uint()) {\n    // Use IntImm if it is a small integer\n    uint64_t uval = static_cast<uint64_t>(value);\n    if (value < static_cast<ValueType>(0)) {\n      LOG(FATAL) << \"cannot make uint from negative value \" << value;\n    } else if (uval <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {\n      return IntImm(t, static_cast<int64_t>(value), span);\n    } else {\n      uint64_t mask = (static_cast<uint64_t>(1) << 32U) - 1U;\n      uint64_t low = uval & mask;\n      uint64_t high = uval >> 32U;\n      return LargeUIntImm(t, static_cast<int64_t>(low), static_cast<int64_t>(high), span);\n    }\n  }\n  if (t.is_float() || t.is_bfloat16()) return FloatImm(t, static_cast<double>(value), span);\n  // For now, we store const scalar values of custom datatypes within doubles; later, during the\n  // datatypes lowering pass, we will lower the value to its true representation in the format\n  // specified by the datatype.\n  // TODO(gus) when do we need to start worrying about doubles not being precise enough?\n  if (static_cast<uint8_t>(t.code()) >= static_cast<uint8_t>(DataType::kCustomBegin)) {\n    return FloatImm(t, static_cast<double>(value), span);\n  }\n  LOG(FATAL) << \"cannot make const for type \" << t;\n  return PrimExpr();\n}\n\ntemplate <>\ninline PrimExpr MakeConstScalar(DataType t, bool value, Span span) {\n  return MakeConstScalar(t, static_cast<int>(value), span);\n}\n\ntemplate <typename ValueType, typename>\ninline PrimExpr make_const(DataType t, ValueType value, Span span) {\n  if (t.lanes() == 1) {\n    return MakeConstScalar(t, value, span);\n  } else {\n    return tir::Broadcast(MakeConstScalar(t.element_of(), value, span), t.lanes(), span);\n  }\n}\n\ninline PrimExpr make_zero(DataType t, Span span) {\n  if (t.is_handle()) {\n    return reinterpret(t, make_const(DataType::UInt(64), 0, span));\n  }\n  return make_const(t, 0, span);\n}\n\ntemplate <typename FReduce>\ninline PrimExpr foldl(FReduce freduce, PrimExpr init_value, const Array<PrimExpr>& values,\n                      Span span) {\n  for (PrimExpr val : values) {\n    init_value = freduce(init_value, val, span);\n  }\n  return init_value;\n}\n\n}  // namespace tir\n\n// additional const expression overloading\n#define TVM_DEFINE_ASSIGN_OP_OVERLOAD(Name, OpFunc) \\\n  inline PrimExpr Name(PrimExpr& a, PrimExpr b) {   \\\n    a = OpFunc(a, b);                               \\\n    return a;                                       \\\n  }\n\n#define TVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(Name)                                   \\\n  inline PrimExpr Name(const PrimExpr& a, float b) { return Name(a, PrimExpr(b)); } \\\n  inline PrimExpr Name(float a, const PrimExpr& b) { return Name(PrimExpr(a), b); } \\\n  inline PrimExpr Name(int a, const PrimExpr& b) {                                  \\\n    return Name(tir::make_const(b.dtype(), a), b);                                  \\\n  }                                                                                 \\\n  inline PrimExpr Name(const PrimExpr& a, int b) {                                  \\\n    return Name(a, tir::make_const(a.dtype(), b));                                  \\\n  }                                                                                 \\\n  inline PrimExpr Name(const PrimExpr& a, double b) {                               \\\n    return Name(a, tir::make_const(DataType::Float(64), b));                        \\\n  }\n\n#define TVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(Name)                 \\\n  inline PrimExpr Name(const PrimExpr& a, float b, Span span = Span()) {  \\\n    return Name(a, PrimExpr(b), span);                                    \\\n  }                                                                       \\\n  inline PrimExpr Name(float a, const PrimExpr& b, Span span = Span()) {  \\\n    return Name(PrimExpr(a), b, span);                                    \\\n  }                                                                       \\\n  inline PrimExpr Name(int a, const PrimExpr& b, Span span = Span()) {    \\\n    return Name(tir::make_const(b.dtype(), a), b, span);                  \\\n  }                                                                       \\\n  inline PrimExpr Name(const PrimExpr& a, int b, Span span = Span()) {    \\\n    return Name(a, tir::make_const(a.dtype(), b), span);                  \\\n  }                                                                       \\\n  inline PrimExpr Name(const PrimExpr& a, double b, Span span = Span()) { \\\n    return Name(a, tir::make_const(DataType::Float(64), b), span);        \\\n  }\n\n#define TVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD(Name)                             \\\n  inline PrimExpr Name(const PrimExpr& a, bool b) { return Name(a, PrimExpr(b)); } \\\n  inline PrimExpr Name(bool a, const PrimExpr& b) { return Name(PrimExpr(a), b); }\n\n#define TVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD_SPANNED(Name)          \\\n  inline PrimExpr Name(const PrimExpr& a, bool b, Span span = Span()) { \\\n    return Name(a, PrimExpr(b), span);                                  \\\n  }                                                                     \\\n  inline PrimExpr Name(bool a, const PrimExpr& b, Span span = Span()) { \\\n    return Name(PrimExpr(a), b, span);                                  \\\n  }\n\n#define TVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(Name) \\\n  inline PrimExpr Name(const PrimExpr& a, int b) { \\\n    return Name(a, tir::make_const(a.dtype(), b)); \\\n  }                                                \\\n  inline PrimExpr Name(int a, const PrimExpr& b) { return Name(tir::make_const(b.dtype(), a), b); }\n\n#define TVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(Name)             \\\n  inline PrimExpr Name(const PrimExpr& a, int b, Span span = Span()) { \\\n    return Name(a, tir::make_const(a.dtype(), b), span);               \\\n  }                                                                    \\\n  inline PrimExpr Name(int a, const PrimExpr& b, Span span = Span()) { \\\n    return Name(tir::make_const(b.dtype(), a), b, span);               \\\n  }\n\nTVM_DEFINE_ASSIGN_OP_OVERLOAD(operator+=, operator+);\nTVM_DEFINE_ASSIGN_OP_OVERLOAD(operator-=, operator-);\nTVM_DEFINE_ASSIGN_OP_OVERLOAD(operator*=, operator*);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator+);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator-);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator*);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator>);  // NOLINT(*)\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator>=);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator<);  // NOLINT(*)\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD(operator<=);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(max);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(min);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(div);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(add);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(sub);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(mul);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(greater);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(greater_equal);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(less);\nTVM_DEFINE_BINOP_CONST_VAL_OVERLOAD_SPANNED(less_equal);\n// integer related ops\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(indexdiv);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(indexmod);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(truncdiv);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(truncmod);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(floordiv);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(floormod);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(right_shift);  // NOLINT(*)\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(left_shift);   // NOLINT(*)\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(bitwise_and);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(bitwise_or);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD_SPANNED(bitwise_xor);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(operator>>);  // NOLINT(*)\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(operator<<);  // NOLINT(*)\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(operator&);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(operator|);\nTVM_DEFINE_INT_OP_CONST_VAL_OVERLOAD(operator^);\n// logical ops\nTVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD(operator&&);\nTVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD(operator||);\nTVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD_SPANNED(logical_and);\nTVM_DEFINE_LOGICAL_OP_CONST_VAL_OVERLOAD_SPANNED(logical_or);\n\n/*!\n * \\brief Helper function to raise a compiler error about division ambiguity.\n * \\note The call to this function will always results in a compiler error.\n * \\tparam TA Any class type.\n */\ntemplate <typename TA>\ninline void DivAmbiguityError(const TA& a) {\n  constexpr bool div_ambiguity = !std::is_class<TA>::value;\n  static_assert(div_ambiguity,\n                \"TVM supports multiple types of integer divisions, \"\n                \"please call div, indexdiv/indexmod, \"\n                \"floordiv/floormod or truncdiv/truncmod directly \"\n                \"to avoid ambiguity in the code. \"\n                \"Checkout these functions in tir/op.h.\");\n}\n\n// The following code are not intended to be used in the codebase.\n// Instead, they generate clear compiler errors that ask developers\n// to use the specific division function.\n// The second template argument is necessary to make sure the\n// code compiles lazily by the compiler during invocation.\ntemplate <typename TB>\ninline PrimExpr operator/(const PrimExpr& a, const TB& b) {\n  DivAmbiguityError(a);\n  return a;\n}\n\ntemplate <typename TB>\ninline PrimExpr operator/=(const PrimExpr& a, const TB& b) {\n  DivAmbiguityError(a);\n  return a;\n}\n\ntemplate <typename TB>\ninline PrimExpr operator%(const PrimExpr& a, const TB& b) {\n  DivAmbiguityError(a);\n  return a;\n}\n}  // namespace tvm\n#endif  // TVM_TIR_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/op_attr_types.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/op_attr_types.h\n * \\brief Attribute types in the Op registry for TIR ops.\n *\n * These attributes can be set via OpRegEntry::set_attr\n *\n * \\sa tvm/ir/op.h\n */\n#ifndef TVM_TIR_OP_ATTR_TYPES_H_\n#define TVM_TIR_OP_ATTR_TYPES_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/packed_func.h>\n\nnamespace tvm {\nnamespace tir {\n/*!\n * \\brief Global symbol of the op after lowering.\n */\nusing TGlobalSymbol = String;\n\n/*!\n * \\brief Whether the op is overloaded for vector form.\n */\nusing TVectorizable = bool;\n\n/*!\n * \\brief The intrinsic lowering function for given op.\n */\nusing FLowerIntrinsic = runtime::TypedPackedFunc<PrimExpr(PrimExpr)>;\n\n/*!\n * \\brief The legalization function for given tir op.\n */\nusing FLegalize = runtime::TypedPackedFunc<PrimExpr(PrimExpr)>;\n\n/*!\n * \\brief The effect type of the call.\n */\nenum class CallEffectKind : int {\n  /*! \\brief Function corresponds to an annotation(e.g. likely) and can translate to identity. */\n  kExprAnnotation = 0,\n  /*!\n   * \\brief Pure function that do not interacts\n   *        with any external state.\n   */\n  kPure = 1,\n  /*!\n   * \\brief Function's that may read from states(e.g. RAM)\n   */\n  kReadState = 2,\n  /*!\n   * \\brief Function that may read/write from states(e.g. RAM).\n   */\n  kUpdateState = 3,\n  /*!\n   * \\brief Opaque function, cannot make any assumption\n   */\n  kOpaque = kUpdateState,\n  /*!\n   * \\brief Special intrinsic to annotate call arguments info\n   *        only valid as a direct argument to a call.\n   */\n  kSpecialCallArg = 4,\n  /*!\n   * \\brief Embed opaque information in the Expr, cannot be codegen.\n   */\n  kEmbedInfo = 5,\n  /*!\n   * \\brief Function that changes control flow\n   */\n  kControlJump = 6,\n};\n\n/*! \\brief Use integer to record the kind. */\nusing TCallEffectKind = Integer;\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_OP_ATTR_TYPES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/schedule/block_scope.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/tir/schedule/block_scope.h\n * \\brief Definition of two pillar data structure for TensorIR scheduling: StmtSRef, BlockScope.\n * \\sa StmtSRefNode\n * \\sa BlockScopeNode\n */\n#ifndef TVM_TIR_SCHEDULE_BLOCK_SCOPE_H_\n#define TVM_TIR_SCHEDULE_BLOCK_SCOPE_H_\n\n#include <tvm/tir/stmt.h>\n\n#include <unordered_map>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief An object that refers to schedulable elements (block/for-loop) in TensorIR, aka \"sref\".\n *\n * Glossary\n * - Block sref: A StmtSRef that points to a TensorIR block.\n * - Loop sref: A StmtSRef that points to a TensorIR for loop.\n * - Parent sref: The parent reference of an sref is the block or loop reference to the closest\n schedulable statement. We define closest to be the nearest schedulable statement of an ancestor in\n the AST.\n * schedulable statement of its ancestors on the TensorIR AST.\n * - Root sref: Sref to the root block. Every sref has exactly one parent sref except for root sref.\n * - Sref tree: The parent-children-relationship of srefs that forms a tree, uniquely determined by\n * the TensorIR AST.\n */\nclass StmtSRefNode : public Object {\n public:\n  /*!\n   * \\brief The block or `for` stmt the object refers to\n   * \\note Non-owned reference (raw pointer) is used here, so that we can perform copy-on-write\n   * optimization on statements when possible. The strong reference is held in the ScheduleState.\n   */\n  const StmtNode* stmt;\n  /*! \\brief The parent sref. */\n  StmtSRefNode* parent;\n  /*!\n   * \\brief If the statement the sref points to is an element of a SeqStmt in the AST,\n   * then `seq_index` is set to its index; otherwise `seq_index` is -1\n   */\n  int64_t seq_index;\n\n  void VisitAttrs(AttrVisitor* v) {\n    // `stmt` is not visited\n    // `parent` is not visited\n    v->Visit(\"seq_index\", &seq_index);\n  }\n\n  static constexpr const char* _type_key = \"tir.StmtSRef\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StmtSRefNode, Object);\n\n  /*! \\brief Reset the object inplace to the invalid state */\n  void Reset() {\n    this->stmt = nullptr;\n    this->parent = nullptr;\n    this->seq_index = -1;\n  }\n\n  /*!\n   * \\brief Get the referenced statement with proper type checking.\n   * It serves the same purpose as `ObjectRef::as`, but does not acquire strong reference to `stmt`\n   * \\tparam StmtType The type that `this->stmt` to be downcasted to. Presumably\n   * tvm::tir::BlockNode or tvm::tir::ForNode\n   * \\return nullptr if type check fails, otherwise the casted result for `this->stmt`\n   */\n  template <typename StmtType>\n  const StmtType* StmtAs() const {\n    if (stmt != nullptr && stmt->IsInstance<StmtType>()) {\n      return static_cast<const StmtType*>(stmt);\n    } else {\n      return nullptr;\n    }\n  }\n};\n\n/*!\n * \\brief Managed reference to StmtSRefNode\n * \\sa StmtSRefNode\n */\nclass StmtSRef : public ObjectRef {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param stmt The corresponding stmt node, can be either block or for loop.\n   * \\param parent The parent sref.\n   * \\param seq_index The location in an array if the parent of the stmt contains multiple children.\n   * -1 if the parent does not contain multiple children.\n   */\n  TVM_DLL explicit StmtSRef(const StmtNode* stmt, StmtSRefNode* parent, int64_t seq_index);\n\n  /*! \\return The mutable pointer to the StmtSRefNode */\n  StmtSRefNode* get() const { return static_cast<StmtSRefNode*>(data_.get()); }\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(StmtSRef, ObjectRef, StmtSRefNode);\n\n public:\n  /*!\n   * \\return A special StmtSRef, which doesn't point to any stmt in the AST,\n   * only serving as a \"mark\" to hint compute-at to do the work of compute-inline\n   * \\note This is only as a faked loop sref for compute-at and reverse-compute-at,\n   * i.e.\n   *\n   * compute-at(block, loop_sref):\n   *   compute-inline(block)                if loop_sref.same_as(InlineMark())\n   *   no-op                                if loop_sref.same_as(RootMark())\n   *   compute-at-impl(block, loop_sref)    otherwise\n   */\n  TVM_DLL static StmtSRef InlineMark();\n  /*!\n   * \\return A special StmtSRef, which doesn't point to any stmt in the AST,\n   * only serving as a \"mark\" to hint compute-at to do nothing\n   * \\note This is only as a faked loop sref for compute-at and reverse-compute-at,\n   * i.e.\n   *\n   * compute-at(block, loop_sref):\n   *   compute-inline(block)                if loop_sref.same_as(InlineMark())\n   *   no-op                                if loop_sref.same_as(RootMark())\n   *   compute-at-impl(block, loop_sref)    otherwise\n   */\n  TVM_DLL static StmtSRef RootMark();\n};\n\n/*!\n * \\brief Type of dependency. Right now we have 4 types of dependencies\n * 1) Read-after-write (kRAW)\n * 2) Write-after-write (kWAW)\n * 3) Write-after-read (kWAR)\n * 4) Opaque dependency (kOpaque)\n */\nenum class DepKind : int32_t {\n  kRAW = 0,\n  kWAW = 1,\n  kWAR = 2,\n  kOpaque = 3,\n};\n\n/*!\n * \\brief A tuple (src, dst, kind) representing certain types of dependency.\n * For example, (A, B, kRAW) means block B depends on block A, and the dependency kind is\n * read-after-write, which means block B reads the result written by block A.\n */\nclass DependencyNode : public Object {\n public:\n  /*! \\brief The source of the dependency relation */\n  StmtSRef src;\n  /*! \\brief The destination of the dependency relation */\n  StmtSRef dst;\n  /*! \\brief The dependency kind */\n  DepKind kind;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"src\", &src);\n    v->Visit(\"dst\", &dst);\n    v->Visit(\"kind\", &kind);\n  }\n\n  static constexpr const char* _type_key = \"tir.Dependency\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DependencyNode, Object);\n};\n\n/*!\n * \\brief Managed reference to DependencyNode\n * \\sa DependencyNode\n */\nclass Dependency : public ObjectRef {\n public:\n  /*! \\brief Constructor */\n  TVM_DLL explicit Dependency(StmtSRef src, StmtSRef dst, DepKind kind);\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Dependency, ObjectRef, DependencyNode);\n};\n\n/*!\n * \\brief An object with 1-to-1 correspondence with each block reference in the sref tree.\n * This data structure is used to track the producer-consumer dependencies between blocks.\n * For example even leaf nodes have a scope node, even though they have no dependencies.\n *\n * Glossary:\n * - Block scope: A contiguous subtree of the sref tree, rooted at each block sref,\n * whose components are:\n *   - scope root: a block sref\n *   - internal srefs: loop srefs\n *   - scope leaves: block srefs\n * - Child block: The scope leaf blocks under the scope root or a specific internal sref\n */\nclass BlockScopeNode : public Object {\n public:\n  /*!\n   * \\brief Lookup table for the `src` of dependencies\n   * \\note We intentionally didn't use tvm::Map as the data structure, because we need the values\n   * inside to be mutable so that they could be further maintained properly during transformations.\n   */\n  std::unordered_map<StmtSRef, Array<Dependency>, ObjectPtrHash, ObjectPtrEqual> src2deps;\n  /*! \\brief Lookup table for the `dst` of dependencies */\n  std::unordered_map<StmtSRef, Array<Dependency>, ObjectPtrHash, ObjectPtrEqual> dst2deps;\n  /*! \\brief The mapping from the buffer to the blocks who write it */\n  std::unordered_map<Buffer, Array<StmtSRef>, ObjectPtrHash, ObjectPtrEqual> buffer_writers;\n  /*!\n   * \\brief This property indicates that the block scope (rooted at its corresponding block) is\n   * equivalent to of a stage pipeline. Under the following conditions:\n   *\n   * 1) The region cover property holds for every of its child blocks\n   * 2) No write-after-read dependency or opaque dependency, only read-after-write and\n   * write-after-write are allowed\n   * 3) All the statements in the scope are schedulable statements, i.e. Block and For\n   */\n  bool stage_pipeline{false};\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"tir.BlockScope\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockScopeNode, Object);\n\n public:\n  /******** Dependency ********/\n  /*!\n   * \\brief Get all dependencies whose `src` equals `src`\n   * \\param src The queried block\n   * \\return The dependencies\n   */\n  TVM_DLL Array<Dependency> GetDepsBySrc(const StmtSRef& src) const;\n  /*!\n   * \\brief Get all dependencies whose `dst` equals `dst`\n   * \\param dst The queried block\n   * \\return The dependencies\n   */\n  TVM_DLL Array<Dependency> GetDepsByDst(const StmtSRef& dst) const;\n};\n\n/*!\n * \\brief Managed reference to BlockScopeNode\n * \\sa BlockScopeNode\n */\nclass BlockScope : public ObjectRef {\n public:\n  /*! \\brief The constructor creating an empty block scope with on dependency information */\n  TVM_DLL BlockScope();\n  /*!\n   * \\brief Create the object with the specific leaf blocks, and compute the dependency information\n   * between the leaf blocks.\n   * \\param child_block_srefs The srefs to the leaf blocks\n   * \\note We assume the leaf blocks are given in pre-DFS order\n   */\n  TVM_DLL explicit BlockScope(const Array<StmtSRef>& child_block_srefs);\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(BlockScope, ObjectRef, BlockScopeNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_BLOCK_SCOPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/schedule/instruction.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_INSTRUCTION_H_\n#define TVM_TIR_SCHEDULE_INSTRUCTION_H_\n\n#include <tvm/node/reflection.h>\n\n#include <utility>\n\nnamespace tvm {\n\n// Forward declaration\ntemplate <typename, typename>\nclass AttrRegistry;\n\nnamespace tir {\n\n// Forward declaration\nclass Schedule;\n\n/*!\n * \\brief Type of the functor that applies the instruction to a TensorIR schedule\n * \\param sch The schedule to be applied on\n * \\param inputs The input random variables\n * \\param attrs Instruction attributes\n * \\param decision Decisions made on the instruction\n * \\return The functor returns an array of output random variables\n */\nusing FInstructionApply = runtime::TypedPackedFunc<Array<ObjectRef>(\n    Schedule sch, const Array<ObjectRef>& inputs, const Array<ObjectRef>& attrs,\n    const Optional<ObjectRef>& decision)>;\n\n/*!\n * \\brief Type of the functor that converts the instruction to a statement in python syntax\n * \\param inputs Names of the input random variables\n * \\param attrs Instruction attributes\n * \\param decisions Decisions made on the instruction\n * \\param outputs Names of the output random variables\n * \\return A string representing the python api call\n */\nusing FInstructionAsPython = runtime::TypedPackedFunc<String(\n    const Array<ObjectRef>& inputs, const Array<ObjectRef>& attrs,\n    const Optional<ObjectRef>& decision, const Array<String>& outputs)>;\n\n/*!\n * \\brief Type of the functor that serialize its attributes to JSON\n * \\param attrs The attributes to be serialized\n * \\return An array, serialized attributes\n * \\note This functor is nullable\n */\nusing FInstructionAttrsAsJSON = runtime::TypedPackedFunc<ObjectRef(Array<ObjectRef> attrs)>;\n\n/*!\n * \\brief Type of the functor that deserialize its attributes from JSON\n * \\param json_attrs The attributes to be serialized\n * \\return An array, deserialized attributes\n * \\note This functor is nullable\n */\nusing FInstructionAttrsFromJSON = runtime::TypedPackedFunc<Array<ObjectRef>(ObjectRef json_attrs)>;\n\n/*!\n * \\brief Kind of an instruction, e.g. Split, Reorder, etc.\n * Besides the name, every kind of instruction has its own properties, including:\n * 1) A boolean indicating if the instruction is pure, i.e. change nothing in the schedule state\n * 2) A functor that applies the instruction to a TensorIR schedule\n * 3) A functor that converts the instruction to a statement in python syntax\n * 4) A functor that serialize its attributes to JSON\n * 5) A functor that deserialize its attributes from JSON\n *\n * Unlike `tvm::OpNode`, `InstructionKindNode` doesn't support unstructured properties,\n * mainly because there is no such usecase yet to add any other property.\n */\nclass InstructionKindNode : public runtime::Object {\n public:\n  /*! \\brief The name of a kind of instructions */\n  String name;\n  /*!\n   * \\brief Indicates if the instruction is pure, i.e. removing it alone doesn't mutate the schedule\n   * state. For example, the instruction `GetBlock` is pure because it changes\n   * nothing, while `ComputeInline` is not because removing it leads to a different resulting\n   * schedule.\n   */\n  bool is_pure{false};\n  /*! \\brief A functor that applies the instruction to a TensorIR schedule */\n  FInstructionApply f_apply_to_schedule{nullptr};\n  /*! \\brief A functor that converts the instruction to a statement in python syntax */\n  FInstructionAsPython f_as_python{nullptr};\n  /*!\n   * \\brief A functor that serialize its attributes to JSON\n   * \\note If the functor is null, it means no conversion is needed\n   */\n  FInstructionAttrsAsJSON f_attrs_as_json{nullptr};\n  /*!\n   * \\brief A functor that deserialize its attributes from JSON\n   * \\note If the functor is null, it means no conversion is needed\n   */\n  FInstructionAttrsFromJSON f_attrs_from_json{nullptr};\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"_is_pure\", &is_pure);\n    // not visited: f_apply_to_schedule\n    // not visited: f_as_python\n    // not visited: f_attrs_as_json\n    // not visited: f_attrs_from_json\n  }\n\n  /*! \\brief Checks if the instruction kind is EnterPostproc */\n  bool IsPostproc() const;\n\n  static constexpr const char* _type_key = \"tir.InstructionKind\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(InstructionKindNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to InstructionKindNode\n * \\sa InstructionKindNode\n */\nclass InstructionKind : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Retrieve an InstructionKind using its name\n   * \\param name The registered name of the InstructionKind\n   * \\return The InstructionKind retrieved\n   */\n  static InstructionKind Get(const String& name);\n  TVM_DEFINE_OBJECT_REF_METHODS(InstructionKind, runtime::ObjectRef, InstructionKindNode);\n};\n\n/*! \\brief Schedule instructions each corresponds to a schedule primitive */\nclass InstructionNode : public runtime::Object {\n public:\n  /*! \\brief The kind of the instruction */\n  InstructionKind kind;\n  /*!\n   * \\brief The input random variables of the instruction, and the type of each element can be one\n   * of the following:\n   * - BlockRV\n   * - LoopRV\n   * - ExprRV\n   * - FloatImm\n   * - IntImm\n   * - String\n   * - null pointer\n   */\n  Array<ObjectRef> inputs;\n  /*!\n   * \\brief The attributes of the instruction. Similar to attributes of an operator,\n   * attributes of an instruction are arbitrary constant metadata required by the instructions.\n   * For example, the name of the block to be retrieved in `GetBlock`.\n   */\n  Array<ObjectRef> attrs;\n  /*! \\brief The output random variables of the instruction, and the type of each element can be one\n   * of the following:\n   * - BlockRV\n   * - LoopRV\n   * - ExprRV, atomic variables only, won't be constants or composite PrimExpr\n   */\n  Array<ObjectRef> outputs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"attrs\", &attrs);\n    v->Visit(\"outputs\", &outputs);\n  }\n\n  static constexpr const char* _type_key = \"tir.Instruction\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(InstructionNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to InstructionNode\n * \\sa InstructionNode\n */\nclass Instruction : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param kind The kind of the instruction\n   * \\param inputs The input random variables of the instruction\n   * \\param attrs The attributes of the instruction\n   * \\param outputs The output random variables of the instruction\n   */\n  explicit Instruction(InstructionKind kind, Array<ObjectRef> inputs, Array<ObjectRef> attrs,\n                       Array<ObjectRef> outputs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Instruction, runtime::ObjectRef, InstructionNode);\n};\n\n/*!\n * \\brief A helper macro to register InstructionKind, only used in `TVM_REGISTER_INST_KIND`\n * \\note This macro is not user-facing.\n * \\sa TVM_REGISTER_INST_KIND\n */\n#define TVM_INST_KIND_REGISTER_VAR_DEF \\\n  static DMLC_ATTRIBUTE_UNUSED ::tvm::tir::InstructionKindRegEntry& __make_##InstructionKind\n\n/*!\n * \\brief Register an InstructionKind\n * \\param InstructionKindName The name of the InstructionKind\n *\n * Example:\n *\n * \\code\n *\n * TVM_REGISTER_INST_KIND(\"ComputeInline\")\n *     .set_is_pure(false)\n *     .set_apply_to_schedule(ApplyToSchedule)\n *     .set_attrs_as_json(AttrsAsJSON)\n *     .set_attrs_from_json(AttrsFromJSON)\n *     .set_as_python(AsPython);\n *\n * \\endcode\n */\n#define TVM_REGISTER_INST_KIND(InstructionKindName)             \\\n  TVM_STR_CONCAT(TVM_INST_KIND_REGISTER_VAR_DEF, __COUNTER__) = \\\n      ::tvm::tir::InstructionKindRegEntry::RegisterOrGet(InstructionKindName).set_name()\n\n/*! \\brief An entry in the registry of InstructionKind */\nclass InstructionKindRegEntry {\n public:\n  static InstructionKindRegEntry& RegisterOrGet(const String& name);\n\n  InstructionKindRegEntry& set_name() {\n    get_mutable()->name = this->name;\n    return *this;\n  }\n\n  InstructionKindRegEntry& set_is_pure(bool is_pure) {\n    get_mutable()->is_pure = is_pure;\n    return *this;\n  }\n\n  InstructionKindRegEntry& set_apply_to_schedule(FInstructionApply f_apply_to_schedule) {\n    get_mutable()->f_apply_to_schedule = std::move(f_apply_to_schedule);\n    return *this;\n  }\n\n  InstructionKindRegEntry& set_as_python(FInstructionAsPython f_as_python) {\n    get_mutable()->f_as_python = std::move(f_as_python);\n    return *this;\n  }\n\n  InstructionKindRegEntry& set_attrs_as_json(FInstructionAttrsAsJSON f_attrs_as_json) {\n    get_mutable()->f_attrs_as_json = std::move(f_attrs_as_json);\n    return *this;\n  }\n\n  InstructionKindRegEntry& set_attrs_from_json(FInstructionAttrsFromJSON f_attrs_from_json) {\n    get_mutable()->f_attrs_from_json = std::move(f_attrs_from_json);\n    return *this;\n  }\n\n private:\n  /*! \\brief Private constructor, used only by AttrRegistry */\n  explicit InstructionKindRegEntry(uint32_t reg_index);\n  /*! \\brief Get the mutable reference to the internal InstructionKind */\n  InstructionKindNode* get_mutable() const {\n    return const_cast<InstructionKindNode*>(inst_kind_.get());\n  }\n\n  /*! \\brief The name of the registry entry */\n  String name;\n  /*! \\brief The instruction kind */\n  InstructionKind inst_kind_;\n  template <typename, typename>\n  friend class ::tvm::AttrRegistry;\n  friend class InstructionKind;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  //  TVM_TIR_SCHEDULE_INSTRUCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/schedule/schedule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_SCHEDULE_H_\n#define TVM_TIR_SCHEDULE_SCHEDULE_H_\n\n#include <tvm/support/random_engine.h>\n#include <tvm/tir/index_map.h>\n#include <tvm/tir/schedule/state.h>\n#include <tvm/tir/schedule/trace.h>\n\nnamespace tvm {\nnamespace tir {\n\n/*! \\brief The level of detailed error message rendering */\nenum class ScheduleErrorRenderLevel : int32_t {\n  /*! \\brief Render a detailed error message */\n  kDetail = 0,\n  /*! \\brief Render the error in fast mode */\n  kFast = 1,\n  /*! \\brief No error message at all */\n  kNone = 2,\n};\n\n/*! \\brief Type of buffer index */\nenum class BufferIndexType : int32_t {\n  /*! \\brief Index of a read buffer */\n  kRead = 0,\n  /*! \\brief Index of a written buffer */\n  kWrite = 1,\n};\n\n/**************** Random variable: BlockRV ****************/\n\n/*! \\brief A random variable that evaluates to a TensorIR block */\nclass BlockRVNode : public runtime::Object {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n  static constexpr const char* _type_key = \"tir.BlockRV\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockRVNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to BlockRVNode\n * \\sa BlockRVNode\n */\nclass BlockRV : public runtime::ObjectRef {\n public:\n  /*! \\brief Constructor */\n  TVM_DLL BlockRV();\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(BlockRV, runtime::ObjectRef, BlockRVNode);\n};\n\n/**************** Random variable: LoopRV ****************/\n\n/*! \\brief A random variable that evaluates to a TensorIR for loop */\nclass LoopRVNode : public runtime::Object {\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {}\n  static constexpr const char* _type_key = \"tir.LoopRV\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LoopRVNode, runtime::Object);\n};\n\n/*!\n * \\brief Managed reference to LoopRVNode\n * \\sa LoopRVNode\n */\nclass LoopRV : public runtime::ObjectRef {\n public:\n  /*! \\brief Constructor */\n  TVM_DLL LoopRV();\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(LoopRV, runtime::ObjectRef, LoopRVNode);\n};\n\n/**************** Random variable: ExprRV ****************/\n\n/*! \\brief An expr random variable */\nusing ExprRV = PrimExpr;\n\nusing ExprRVNode = PrimExprNode;\n\n/**************** The Schedule class ****************/\n\nclass Schedule;\n\n/*! \\brief The user-facing schedule class */\nclass ScheduleNode : public runtime::Object {\n  friend class Schedule;\n\n public:\n  virtual ~ScheduleNode() = default;\n\n  static constexpr const char* _type_key = \"tir.Schedule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ScheduleNode, runtime::Object);\n\n public:\n  /*! \\brief Get the IRModule associated with this schedule. */\n  virtual IRModule mod() const { return state()->mod; }\n  /*! \\return The internal state of scheduling */\n  virtual ScheduleState state() const = 0;\n  /*! \\return The internally maintained trace of scheduling program execution */\n  virtual Optional<Trace> trace() const = 0;\n  /*!\n   * \\brief Instruct the schedule to work on a function in the IRModule.\n   *\n   * By default, the schedule works on the function with the name \"main\", or the only function in\n   * the IRModule if there is only one. If there is multiple functions in the IRModule, and none of\n   * their names are \"main\", users will have to call this method to explicitly specify which\n   * function to work on.\n   *\n   * This sugar function will guide the `GetBlock` method if its `func_name` is not specified.\n   *\n   * \\param func_name The name of the function to be working on\n   *\n   * \\sa GetBlock\n   */\n  virtual void WorkOn(const String& func_name) = 0;\n  /*!\n   * \\brief Returns a copy of the schedule, including both its state and its symbol table,\n   * guaranteeing that\n   * 1) SRef tree is completely reconstructed;\n   * 2) The IRModule being scheduled is not modified;\n   * 3) All the random variables are valid in the copy, pointing to the corresponding sref\n   * reconstructed\n   */\n  virtual Schedule Copy() = 0;\n  /*!\n   * \\brief Seed the randomness\n   * \\param seed The new random seed, -1 if use device random, otherwise non-negative\n   */\n  virtual void Seed(support::LinearCongruentialEngine::TRandState seed) = 0;\n  /*! \\brief Fork the random state */\n  virtual support::LinearCongruentialEngine::TRandState ForkSeed() = 0;\n\n public:\n  /******** Lookup/Remove random variables ********/\n  /*!\n   * \\brief Get the block corresponding to the specific BlockRV\n   * \\param block_rv The BlockRV to be looked up\n   * \\return The corresponding block\n   */\n  virtual Block Get(const BlockRV& block_rv) const = 0;\n  /*!\n   * \\brief Get the for loop corresponding to the specific LoopRV\n   * \\param loop_rv The LoopRV to be looked up\n   * \\return The corresponding for loop\n   */\n  virtual For Get(const LoopRV& loop_rv) const = 0;\n  /*!\n   * \\brief Get the expr corresponding to the specific random variable\n   * \\param expr_rv The random variable to be looked up\n   * \\return The corresponding expr\n   */\n  virtual PrimExpr Get(const ExprRV& expr_rv) const = 0;\n  /*!\n   * \\brief Get the block sref corresponding to the specific BlockRV\n   * \\param block_rv The BlockRV to be looked up\n   * \\return The corresponding block sref\n   */\n  virtual StmtSRef GetSRef(const BlockRV& block_rv) const = 0;\n  /*!\n   * \\brief Get the loop sref corresponding to the specific LoopRV\n   * \\param loop_rv The LoopRV to be looked up\n   * \\return The corresponding loop sref\n   */\n  virtual StmtSRef GetSRef(const LoopRV& loop_rv) const = 0;\n  /*!\n   * \\brief Check the existance of a specific BlockRV\n   * \\param block_rv The BlockRV to be looked up\n   * \\return Whether the corresponding block exists\n   */\n  virtual bool HasBlock(const BlockRV& block_rv) const = 0;\n  /*!\n   * \\brief Get the block/loop sref corresponding to the specific statement\n   * \\param stmt The statement to be looked up\n   * \\return The corresponding block/loop sref\n   */\n  virtual StmtSRef GetSRef(const StmtNode* stmt) const;\n  /*!\n   * \\brief Get the block/loop sref corresponding to the specific statement\n   * \\param stmt The statement to be looked up\n   * \\return The corresponding block/loop sref\n   */\n  StmtSRef GetSRef(const Stmt& stmt) const { return this->GetSRef(stmt.get()); }\n  /*!\n   * \\brief Remove a block random variable from the symbol table\n   * \\param block_rv The random variable to be removed\n   */\n  virtual void RemoveRV(const BlockRV& block_rv) = 0;\n  /*!\n   * \\brief Remove a loop random variable from the symbol table\n   * \\param loop_rv The random variable to be removed\n   */\n  virtual void RemoveRV(const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Remove an integer random variable from the symbol table\n   * \\param expr_rv The random variable to be removed\n   */\n  virtual void RemoveRV(const ExprRV& expr_rv) = 0;\n\n public:\n  /******** Schedule: Sampling ********/\n  /*!\n   * \\brief Sample an integer given the probability distribution\n   * \\param candidates The candidates\n   * \\param probs The probability distribution of the candidates\n   * \\param decision The sampling decision\n   * \\return The random variable sampled from candidates\n   */\n  virtual ExprRV SampleCategorical(const Array<Integer>& candidates, const Array<FloatImm>& probs,\n                                   Optional<Integer> decision = NullOpt) = 0;\n  /*!\n   * \\brief Sample the factors to perfect tile a specific loop\n   * \\param loop_rv The loop to be tiled\n   * \\param n The number of tiles to be sampled\n   * \\param max_innermost_factor The maximum tile size allowed to be sampled in the innermost loop\n   * \\param decision The sampling decision\n   * \\return A list of length `n`, the random perfect tile sizes sampled\n   */\n  virtual Array<ExprRV> SamplePerfectTile(const LoopRV& loop_rv, int n, int max_innermost_factor,\n                                          Optional<Array<Integer>> decision = NullOpt) = 0;\n  /*!\n   * \\brief Sample a compute-at location of the given block\n   * \\param block_rv The block whose compute-at location is to be sampled\n   * \\param decision The sampling decision\n   * \\return The sampled loop where the input block is to be computed at\n   */\n  virtual LoopRV SampleComputeLocation(const BlockRV& block_rv,\n                                       Optional<Integer> decision = NullOpt) = 0;\n\n  /******** Schedule: Get blocks & loops ********/\n  /*!\n   * \\brief Retrieve a block in a specific function with its name\n   *\n   * By default, if `func_name` is not specified, the schedule will search for the block in the\n   * function that is currently being \"worked on\". To switch the function to be worked on, use\n   * `WorkOn` before calling this method.\n   *\n   * \\param name The name of the block to be retrieved\n   * \\param func_name The name of the function\n   * \\return The block retrieved\n   * \\note Indexing error is raised if 0 or multiple blocks exist with the specific name\n   *\n   * \\sa WorkOn\n   */\n  virtual BlockRV GetBlock(const String& name, const Optional<String>& func_name = NullOpt) = 0;\n  /*!\n   * \\brief Get the parent loops of the block in its scope, from outer to inner\n   * \\param block_rv The query block\n   * \\return A list of loops above the given block in its scope, from outer to inner\n   */\n  virtual Array<LoopRV> GetLoops(const BlockRV& block_rv) = 0;\n  /*!\n   * \\brief Get the leaf blocks of a specific scope\n   * \\param block_rv The block where the scope is rooted\n   * \\return A list of child blocks\n   */\n  virtual Array<BlockRV> GetChildBlocks(const BlockRV& block_rv) = 0;\n  /*!\n   * \\brief Get the leaf blocks of under a specific loop\n   * \\param loop_rv The loop under which collecting is conducted\n   * \\return A list of child blocks\n   */\n  virtual Array<BlockRV> GetChildBlocks(const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Get the producer of a specific block, under the same block scope\n   * \\param block_rv The block in the query\n   * \\return A list of blocks, the producers of the given block under the same scope of the given\n   * block\n   */\n  virtual Array<BlockRV> GetProducers(const BlockRV& block_rv) = 0;\n  /*!\n   * \\brief Get the consumers of a specific block, under the same block scope\n   * \\param block_rv The block to be queried\n   * \\return A list of blocks, the consumers of the given block under the same scope of the given\n   * block\n   */\n  virtual Array<BlockRV> GetConsumers(const BlockRV& block_rv) = 0;\n  /******** Schedule: Transform loops ********/\n  /*!\n   * \\brief Fuse a list of consecutive loops into one. It requires:\n   * 1) The loops can't have annotations or thread bindings.\n   * 2) The (i+1)-th loop must be the only child of the i-th loop.\n   * 3) All loops must start with 0.\n   * 4) The domain of a loop to be fused cannot depend on another loop to be fused.\n   * \\param loop_rvs The loops to be fused\n   * \\param preserve_unit_iters Whether or not to preserve unit iterators in block bindings\n   * \\return The new loop after fusion\n   */\n  virtual LoopRV Fuse(const Array<LoopRV>& loop_rvs, bool preserve_unit_iters = true) = 0;\n  /*!\n   * \\brief Split a loop into a list of consecutive loops. It requires:\n   * 1) The loop can't have annotation or thread binding.\n   * 2) The loop must start with 0.\n   * \\param loop_rv The loop to be split\n   * \\param factors The positive tiling factors, and at most one of which is `NullOpt`, which means\n   * that factor is inferred.\n   * \\param preserve_unit_iters Whether or not to preserve unit iterators in block bindings\n   * \\return The new loops after split\n   */\n  virtual Array<LoopRV> Split(const LoopRV& loop_rv, const Array<Optional<ExprRV>>& factors,\n                              bool preserve_unit_iters = true) = 0;\n  /*!\n   * \\brief Reorder a list of loops. It doesn't require the loops to be consecutive.\n   * It requires:\n   * 1) The loops are in the same chain. That means: the loops can be ordered to [l_1, l_2, ... ,\n   *     l_n] where l_i is an ancestor of l_{i+1} and there are only single-branch loops between\n   *     l_1 and l_n (which also indicates they are under the same scope).\n   * 2) After reordering, the domain of an outer loop cannot depend on any of the inner loops.\n   * 3) For every block under the loop nests, its block binding must be affine, and the block\n   *    variables must be either data parallel or reduction.\n   * 4) No duplicated loops are allowed in the arguments.\n   * \\param ordered_loop_rvs The loops in the new order\n   */\n  virtual void Reorder(const Array<LoopRV>& ordered_loop_rvs) = 0;\n  /*!\n   * \\brief Create a new unit loop on top of the specific block.\n   * \\param block_rv The block above which the new loop is created\n   * \\return The new loop created\n   */\n  virtual LoopRV AddUnitLoop(const BlockRV& block_rv) = 0;\n  /*!\n   * \\brief Create a new unit loop on top of the specific loop.\n   * \\param loop_rv The loop above which the new loop is created\n   * \\return The new loop created\n   */\n  virtual LoopRV AddUnitLoop(const LoopRV& loop_rv) = 0;\n  /******** Schedule: Manipulate ForKind ********/\n  /*!\n   * \\brief Parallelize the input loop. It requires:\n   * 1) The scope block that the loop is in should have stage-pipeline property\n   * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n   * bindings\n   * 3) For each block under the loop, the loop can only be contained in data-parallel block iters'\n   * bindings\n   * \\param loop_rv The loop to be parallelized\n   */\n  virtual void Parallel(const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Vectorize the input loop. It requires:\n   * 1) The scope block that the loop is in should have stage-pipeline property\n   * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n   * bindings\n   * 3) For each block under the loop, the loop can only be contained in data-parallel block iters'\n   * bindings\n   * \\param loop_rv The loop to be vectorized\n   */\n  virtual void Vectorize(const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Bind the input loop to the given thread axis. It requires:\n   * 1) The scope block that the loop is in should have stage-pipeline property\n   * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n   * bindings\n   * 3) For each block under the loop, if the thread axis starts with \"threadIdx`, the loop can only\n   * be contained in data-parallel block iter and reduction block iters' bindings. Otherwise the\n   * loop can only be contained in data-parallel block iters' bindings\n   * \\param loop_rv The loop to be bound to the thread axis\n   * \\param thread_axis The thread axis to be bound to the loop\n   */\n  virtual void Bind(const LoopRV& loop_rv, const String& thread_axis) = 0;\n  /*!\n   * \\brief Unroll the input loop. It requires nothing\n   * \\param loop_rv The loop to be unrolled\n   */\n  virtual void Unroll(const LoopRV& loop_rv) = 0;\n  /******** Schedule: Insert cache stages ********/\n  /*!\n   * \\brief Create a block that reads a buffer region into a read cache. It requires:\n   * 1) There is at most one block who writes the buffer in the scope.\n   * 2) The scope block have stage-pipeline property.\n   * \\param block_rv The consumer block of the target buffer.\n   * \\param read_buffer_index The index of the buffer in block's read region.\n   * \\param storage_scope The target storage scope.\n   * \\param consumer_blocks An optional list of consumers of the cache to rewrite.\n   * \\return The cache stage block.\n   */\n  virtual BlockRV CacheRead(const BlockRV& block_rv, int read_buffer_index,\n                            const String& storage_scope,\n                            const Array<BlockRV> consumer_blocks = {}) = 0;\n  /*!\n   * \\brief Create a block that writes a buffer region into a write cache. It requires:\n   * 1) There is only one block who writes the target buffer.\n   * 2) The scope block have stage-pipeline property.\n   * \\param block_rv The producer of the buffer\n   * \\param write_buffer_index The index of the buffer in block's write region\n   * \\param storage_scope The target storage scope\n   * \\return The cache stage block.\n   */\n  virtual BlockRV CacheWrite(const BlockRV& block_rv, int write_buffer_index,\n                             const String& storage_scope) = 0;\n  /*!\n   * \\brief Create 2 blocks that read&write a buffer region into a read/write cache.\n   * It requires the the target block both read & write the target buffer.\n   * \\param block_rv The target block operates on the target buffer.\n   * \\param read_buffer_index The index of the buffer in block's read region.\n   * \\param storage_scope The target storage scope\n   * \\return The cache stage blocks, cache read block together with cache write block.\n   */\n  virtual Array<BlockRV> CacheInplace(const BlockRV& block_rv, int read_buffer_index,\n                                      const String& storage_scope) = 0;\n  /*!\n   * \\brief Create a block to cache precomputed index for later use.\n   * if there is no index computation, keep unchanged.\n   * \\param block_rv The target block\n   * \\param buffer_index The index of the target buffer in block's read region\n   * \\return The cache stage blocks.\n   */\n  virtual Array<BlockRV> CacheIndex(const BlockRV& block_rv, int buffer_index) = 0;\n  /*!\n   * \\brief Create a block that read/write a buffer region into a read/write cache with reindexing.\n   * The layout of the cache will be the same as by the iterators of the block that reads/writes the\n   * buffer. It requires:\n   * 1) There is only one block who reads/writes the target buffer\n   * 2) There is only one buffer load/store of this buffer in the block\n   * \\param block_rv The block operates on the target buffer.\n   * \\param buffer_index The index of the buffer in block's read or write region.\n   * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n   * \\return The reindex stage block.\n   */\n  virtual BlockRV ReIndex(const BlockRV& block_rv, int buffer_index,\n                          BufferIndexType buffer_index_type) = 0;\n  /******** Schedule: Compute location ********/\n  /*!\n   * \\brief Move a producer block under the specific loop, and regenerate the\n   * loops induced by the block so that the buffer region produced by the producer block could\n   * cover those regions consumed by its consumer blocks under the given loop. It requires:\n   * 1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n   * 2) The scope block has stage-pipeline property\n   * 3) The subtree of the scope block, where the given block is in, satisfies the compact dataflow\n   * condition. i.e. all the blocks in the scope block's subtree must be either complete block or\n   * reduction block\n   * 4) The block is not an output block with regard to the scope block, i.e. the buffers written by\n   * the block are allocated under the scope block\n   * 5) All the consumers of the block are under the given loop\n   * \\param block_rv The block to be moved\n   * \\param loop_rv The loop where the block to be moved under\n   * \\param preserve_unit_loops Whether to keep the trivial loops whose extents are 1\n   * \\param index The block index of the loop body subtree blocks:\n   * - `index = -1` means inserted into the last possible insertion point;\n   * - `index = -2` means inserted into the first possible insertion point;\n   * - Otherwise, `index` is a nonnegative number that indicates the insertion point\n   */\n  virtual void ComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv, bool preserve_unit_loops,\n                         int index = -1) = 0;\n  /*!\n   * \\brief Move a consumer block under the specific loop, and regenerate the\n   * loops induced by the block so that the buffer region consumed by the consumer block could\n   * cover those regions produced by its producer blocks under the given loop. It requires:\n   * 1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n   * 2) The scope block has stage-pipeline property\n   * 3) The subtree of the scope block, where the given block is in, satisfies the compact dataflow\n   * condition. i.e. all the blocks in the scope block's subtree must be either complete block or\n   * reduction block\n   * 4) All the producers of the block are under the given loop\n   *\n   * \\param block_rv The block to be moved\n   * \\param loop_rv The loop where the block to be moved under\n   * \\param preserve_unit_loops Whether to keep the trivial loops whose extents are 1\n   * \\param index The block index of the loop body subtree blocks:\n   * - `index = -1` means inserted into the last possible insertion point;\n   * - `index = -2` means inserted into the first possible insertion point;\n   * - Otherwise, `index` is a nonnegative number that indicates the insertion point\n   */\n  virtual void ReverseComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv,\n                                bool preserve_unit_loops, int index = -1) = 0;\n  /*!\n   * \\brief Inline a block into its consumer(s). It requires:\n   * 1) The block is a complete non-root block, which only produces one buffer\n   * 2) The block must not be the only leaf in the scope.\n   * 3) The body of the block must be a BufferStore statement in the form of,\n   *    A[i, j, k, ...] = ...\n   * where the indices of the LHS are all distinct atomic variables,\n   * and no variables other than those indexing variables are allowed in the statement.\n   * \\param block The block to be inlined to its consumer(s)\n   */\n  virtual void ComputeInline(const BlockRV& block) = 0;\n  /*!\n   * \\brief Inline a block into its only producer. It requires:\n   * 1) The block is a complete non-root block, which only produces and consumers one buffer\n   * 2) The block must not be the only leaf in the scope.\n   * 3) The only producer of the block is a read-after-write producer and a complete non-root block\n   * 4) The body of the block must be a BufferStore statement in the form of,\n   *    B[f(i, j, k, ...)] = g(i, j, k, A[i, j, k, ...] ...)\n   * where the indices of each `BufferLoad` on the RHS are all distinct atomic variables,\n   * and no variables other than those indexing variables are allowed in the statement.\n   * \\param block The block to be inlined to its producer\n   */\n  virtual void ReverseComputeInline(const BlockRV& block) = 0;\n  /******** Schedule: Reduction ********/\n  /*!\n   * \\brief Decompose a reduction block into two separate blocks.\n   * a) The init block, which is translated from the init statement of the reduction block;\n   * b) The update block, which is the original block without init statement.\n   *\n   * The init block is inserted right before the given loop.\n   *\n   * The schedule primitive requires:\n   * 1) The input block is a reduction block.\n   * 2) The input loop is the ancestor of the block.\n   * 3) The input loop is not lower than all the loops related to reduce block var.\n   * \\param block_rv The reduction block to be decomposed\n   * \\param loop_rv The loop above which the init block is inserted before.\n   * \\return The init block\n   */\n  virtual BlockRV DecomposeReduction(const BlockRV& block_rv, const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Factorize an associative reduction block by the specified loop.\n   * \\details An associative reduction cannot be parallelized directly,\n   * because it leads to potential race condition during accumulation.\n   * Alternatively, the reduction could be factorized on a loop with the following steps:\n   * - Step 1: evenly slice the reduction into `n` separate chunks, where `n` is the loop extent\n   * - Step 2: compute the chunks separately and write the result into `n` intermediate buffers;\n   * - Step 3: accumulate the `n` separate buffer into the result buffer.\n   * Note that the Step 2 above introduces opportunities for parallelization.\n   * RFactor is a schedule primitive that implements the transformation described above.\n   * \\param loop_rv The loop outside block we want to do rfactor\n   * \\param factor_axis The position where the new dimension is placed in the new introduced rfactor\n   *                    buffer. Suppose the original reduction block writes to buffer `B` with\n   *                    ndim(B) dimensions, then `factor_axis` should be in range `[-ndim(B) - 1,\n   *                    ndim(B)]`, and the negative index will be normalized to a non-negative one\n   * \\return The rfactor block\n   */\n  virtual BlockRV RFactor(const LoopRV& loop_rv, int factor_axis) = 0;\n  /******** Schedule: Block annotation ********/\n  /*!\n   * \\brief Set alignment requirement for specific dimension such that\n   *        stride[axis] == k * factor + offset for some k. This is useful to set memory layout for\n   *        more friendly memory access pattern. For example, we can set alignment to be factor=2,\n   *        offset=1 to avoid bank conflict for thread access on higher dimension in GPU shared\n   *        memory.\n   * \\param block_rv The producer block of the buffer\n   * \\param buffer_index The index of the buffer in block's write region\n   * \\param axis The dimension to be specified for alignment\n   * \\param factor The factor multiple of alignment\n   * \\param offset The required offset factor\n   */\n  virtual void StorageAlign(const BlockRV& block_rv, int buffer_index, int axis, int factor,\n                            int offset) = 0;\n  /*!\n   * \\brief Set the storage scope of a buffer, where the buffer is specified by the a block and a\n   * write-index\n   * \\param block_rv The producer block of the buffer\n   * \\param buffer_index The index of the buffer in block's write region\n   * \\param storage_scope The storage scope to be set\n   */\n  virtual void SetScope(const BlockRV& block_rv, int buffer_index, const String& storage_scope) = 0;\n  /******** Schedule: Blockize & Tensorize ********/\n  /*!\n   * \\brief Convert the subtree rooted at a specific loop into a block.\n   * \\param loop_rv the root of the subtree\n   * \\return the new block\n   */\n  virtual BlockRV Blockize(const LoopRV& loop_rv) = 0;\n  /*!\n   * \\brief Tensorize the computation enclosed by loop with the tensor intrin.\n   * \\param loop_rv The loop to be tensorized\n   * \\param intrin Name of the tensor intrinsic\n   */\n  virtual void Tensorize(const LoopRV& loop_rv, const String& intrin) = 0;\n  /*!\n   * \\brief Tensorize the computation enclosed by loop with the tensor intrin.\n   * \\param block_rv The block to be tensorized\n   * \\param intrin Name of the tensor intrinsic\n   */\n  virtual void Tensorize(const BlockRV& block_rv, const String& intrin) = 0;\n\n  /******** Schedule: Annotation ********/\n  /*!\n   * \\brief Annotate a loop with a key value pair\n   * \\param loop_rv The loop to be annotated\n   * \\param ann_key The annotation key\n   * \\param ann_val The annotation value, a string or a ExprRV\n   */\n  virtual void Annotate(const LoopRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) = 0;\n  /*!\n   * \\brief Annotate a block with a key value pair\n   * \\param block_rv The block to be annotated\n   * \\param ann_key The annotation key\n   * \\param ann_val The annotation value, a string or a ExprRV\n   */\n  virtual void Annotate(const BlockRV& block_rv, const String& ann_key,\n                        const ObjectRef& ann_val) = 0;\n  /*!\n   * \\brief Unannotate a loop's annotation with key ann_key\n   * \\param loop_rv The loop to be unannotated\n   * \\param ann_key The annotation key\n   */\n  virtual void Unannotate(const LoopRV& loop_rv, const String& ann_key) = 0;\n  /*!\n   * \\brief Unannotate a block's annotation with key ann_key\n   * \\param block_rv The block to be unannotated\n   * \\param ann_key The annotation key\n   */\n  virtual void Unannotate(const BlockRV& block_rv, const String& ann_key) = 0;\n\n  /******** Schedule: Layout transformation ********/\n  /*!\n   * \\brief Apply a transformation represented by IndexMap to buffer\n   * \\details The indices and the access region to the target buffer is transformed by the given\n   * index_map. The index_map is used to infer the new shape of the buffer. Buffer must be either\n   * a function parameter, or allocated in a block (it cannot be a buffer subregion created via\n   * 'match_buffer').\n   * \\param block_rv The block that accesses the target buffer.\n   * \\param buffer_index The index of the buffer in block's read or write region.\n   * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n   * \\param index_map The transformation to apply.\n   *\n   * \\param pad_value The value to write into padding introduced by\n   *    the transformation.  If the schedule contains a producer block\n   *    for the specified buffer, the pad value will be written as\n   *    part of the producer block if possible, or after the producer\n   *    block otherwise.  Otherwise, if the buffer is an input, will\n   *    insert an annotation block to state that the padding contains\n   *    the known value.\n   *\n   *    Note: If applied to an input buffer, the calling scope is\n   *    responsible for ensuring that the pad_value is present.\n   *    Algebraic symplifications, branch elimination, and other\n   *    optimizations may assume that this precondition is met, and\n   *    may result in incorrect results being returned.\n   */\n  virtual void TransformLayout(const BlockRV& block_rv, int buffer_index,\n                               BufferIndexType buffer_index_type, const IndexMap& index_map,\n                               const Optional<IndexMap>& pad_value = NullOpt) = 0;\n\n  /*!\n   * \\brief Apply a transformation represented by IndexMap to block\n   * \\details The block iters and the block body are transformed by the given index_map.\n   * Outer loops corresponding to each new block iter are regenerated.\n   * The index_map is required to be bijective affine since we need its inverse mapping.\n   * \\param block_rv The block to be transformed\n   * \\param index_map The transformation to apply.\n   */\n  virtual void TransformBlockLayout(const BlockRV& block_rv, const IndexMap& index_map) = 0;\n\n  /*!\n   * \\brief Set the axis separator of a buffer, where the buffer is specified by a block and a read\n   * or write index\n   * \\param block_rv The block that accesses the target buffer.\n   * \\param buffer_index The index of the buffer in block's read or write region.\n   * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n   * \\param axis_separators The axis separator of the buffer\n   */\n  virtual void SetAxisSeparator(const BlockRV& block_rv, int buffer_index,\n                                BufferIndexType buffer_index_type,\n                                const Array<IntImm>& axis_separators) = 0;\n\n  /******** Schedule: Padding ********/\n  /*!\n   * \\brief Decompose a padding block into a block filling const pad values and a block\n   * writing in-bound values.\n   * \\param block_rv The block that match the padding pattern.\n   * \\param loop_rv The loop above which the const filling block is inserted before.\n   * \\return The const pad value filling block.\n   */\n  virtual BlockRV DecomposePadding(const BlockRV& block_rv, const LoopRV& loop_rv) = 0;\n\n  /*!\n   * \\brief Pad the computation of Einsum.\n   * \\param block_rv The block that matches the Einsum pattern.\n   * \\param padding The padding for each block iter.\n   * \\details This schedule primitives identifies the Einsum pattern in the block body, and find its\n   * producer blocks. It then pads the computation of the Einsum pattern and its producer blocks.\n   * The output buffer and the producer buffer is resized according to the padding size. It requires\n   * the output buffer and the producer buffer to be allocated inside the PrimFunc.\n   *\n   * The padding is a list of non-negative integers, each element corresponds to the padding for\n   * each block iter in the order of block iters. The block and its producer blocks should have\n   * trivial bindings, i.e. each block iter is bound to a single loop variable. After padding, the\n   * block iter extent and the corresponding outer loop is extended by the padding size.\n   *\n   * The size of the producer buffers are infered from the padding size of the Einsum computation.\n   * The producer buffers are padded by the initial value of the corresponding reduction.\n   */\n  virtual void PadEinsum(const BlockRV& block_rv, const Array<Integer>& padding) = 0;\n\n  /******** Schedule: Buffer transformation ********/\n  /*!\n   * \\brief Compute the target buffer via rolling buffering.\n   * \\details This primitive selects the outermost rollable axis with a positive bound overlap that\n   * appears in the block's ancestor loops as `rolling axis`, fold and circularize the buffer along\n   * the rolling dimension, append block predicate to avoid recomputing overlapping elements.\n   * It requires:\n   * 1) The buffer to be an intermediate buffer defined via `alloc_buffer`.\n   * 2) The LCA of the producer and consumer of the buffer is a for loop, typically,\n   *    the producer and consumer of the buffer are cascaded through compute_at.\n   * 3) The access region of the buffer has at least one dimension that contains\n   *    a positive bound overlap.\n   * \\param block_rv The producer block of the buffer.\n   * \\param write_buffer_index The index of the buffer in block's write region.\n   */\n  virtual void RollingBuffer(const BlockRV& block_rv, int write_buffer_index) = 0;\n\n  /******** Schedule: Misc ********/\n  /*! \\brief A no-op that marks the start of postprocessing phase of scheduling */\n  virtual void EnterPostproc() = 0;\n};\n\n/*!\n * \\brief Managed reference to ScheduleNode\n *\n * A schedule is a set of transformations that change the order of computation but\n * preserve the semantics of computation. Some example of schedules:\n * 1) Split a loop into two;\n * 2) Reorder two loops;\n * 3) Inline the computation of a specific buffer into its consumer\n *\n * The schedule class stores auxiliary information to schedule correctly and efficiently.\n *\n * Link to tutorial: https://tvm.apache.org/docs/tutorials/language/schedule_primitives.html\n *\n * \\sa ScheduleNode\n */\nclass Schedule : public runtime::ObjectRef {\n public:\n  /*!\n   * \\brief Construct a concrete TensorIR schedule from an IRModule\n   * \\param mod The IRModule to be scheduled\n   * \\param seed The seed value for schedule's random state\n   * \\param debug_mask Do extra correctness checking after the class creation\n   * and each time after calling the Replace method.\n   * \\param error_render_level The level of error rendering\n   * \\return The concrete schedule created\n   * \\sa ScheduleDebugMask\n   * \\note The checks performed includes:\n   * 1) VerifySRefTree\n   * 2) VerifyCachedFlags\n   */\n  TVM_DLL static Schedule Concrete(IRModule mod, support::LinearCongruentialEngine::TRandState seed,\n                                   int debug_mask, ScheduleErrorRenderLevel error_render_level);\n  /*!\n   * \\brief Construct a traced concrete TensorIR schedule from an IRModule\n   * \\param mod The IRModule to be scheduled\n   * \\param seed The seed value for schedule's random state\n   * \\param debug_mask Do extra correctness checking after the class creation\n   * and each time after calling the Replace method.\n   * \\param error_render_level The level of error rendering\n   * \\return The concrete schedule created\n   * \\sa ScheduleDebugMask\n   * \\note The checks performed include:\n   * 1) VerifySRefTree\n   * 2) VerifyCachedFlags\n   */\n  TVM_DLL static Schedule Traced(IRModule mod, support::LinearCongruentialEngine::TRandState seed,\n                                 int debug_mask, ScheduleErrorRenderLevel error_render_level);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Schedule, runtime::ObjectRef, ScheduleNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_SCHEDULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/schedule/state.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/tir/schedule/state.h\n * \\brief This file defines ScheduleState, the core data structure of TensorIR scheduling.\n */\n#ifndef TVM_TIR_SCHEDULE_STATE_H_\n#define TVM_TIR_SCHEDULE_STATE_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/schedule/block_scope.h>\n\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief The information about a TensorIR block, it contains two categories of information\n * 1) Info on the block scope rooted at a specific block, including dependency tracking,\n * flags indicating if the scope is a stage pipeline, etc.\n * 2) Info on the block itself, including if the block has a quasi-affine binding, if the regions it\n * reads are completely covered by their producers, etc.\n */\nstruct BlockInfo {\n  /*! \\brief Property of a block scope rooted at the block, storing dependencies in the scope */\n  BlockScope scope{nullptr};\n  // The properties below are information about the current block realization under its parent scope\n  /*! \\brief Property of a block, indicating the block realization binding is quasi-affine */\n  bool affine_binding{false};\n  /*!\n   * \\brief Property of a block, indicating each of the block's read regions is fully\n   * produced by its producers\n   */\n  bool region_cover{false};\n\n  BlockInfo() = default;\n\n  explicit BlockInfo(BlockScope scope, bool affine_binding = false, bool region_cover = false)\n      : scope(std::move(scope)),         //\n        affine_binding(affine_binding),  //\n        region_cover(region_cover) {}\n};\n\n/*!\n * \\brief The bitmask of the debug flag in the ScheduleStateNode.\n * \\sa ScheduleStateNode\n */\nenum ScheduleDebugMask : uint32_t {\n  /*! \\brief Verify the correctness of the sref tree */\n  kVerifySRefTree = 1,\n  /*! \\brief Verify the correctness of affine_binding, region_cover and stage_pipeline */\n  kVerifyCachedFlags = 2,\n};\n\n/*!\n * \\brief The state of scheduling, which exposes a `Replace` method as\n * the primary interface for all the scheduling primitives to manipulate the TensorIR.\n *\n * The data structure contains the following information\n * 1) The AST being scheduled (mod)\n * 2) The sref tree of schedulable statements (indicated by the srefs)\n * 3) The dependency information of each block scope (block_info)\n * 4) A reverse mapping from the AST nodes to that in the sref tree (stmt2ref)\n * 5) A debug flag, if set, extra checking is enabled (debug_mask)\n */\nclass ScheduleStateNode : public Object {\n public:\n  /*! \\brief The AST of the module being scheduled */\n  IRModule mod;\n  /*!\n   * \\brief Mapping from a block sref to its correpsonding BlockInfo,\n   * tracking the dependency inside the block scope,\n   * and storing necessary information flags for scheduling\n   */\n  std::unordered_map<StmtSRef, BlockInfo, ObjectPtrHash, ObjectPtrEqual> block_info;\n  /*! \\brief The reverse mapping from block/for-loop to their corresponding srefs */\n  std::unordered_map<const StmtNode*, StmtSRef> stmt2ref;\n  /*!\n   * \\brief Do extra correctness checking after the class creation\n   * and each time after calling the Replace method.\n   * \\sa ScheduleDebugMask\n   */\n  int debug_mask;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"mod\", &mod);\n    // `block_info` is not visited\n    // `stmt2ref` is not visited\n    v->Visit(\"debug_mask\", &debug_mask);\n  }\n  /*!\n   * \\brief Replace the part of the AST, as being pointed to by `src_sref`,\n   * with a specific statement `tgt_stmt`, and maintain the sref tree accordingly.\n   * Replace will try to perform copy on write as much as possible when the ScheduleState holds\n   * the only copy to the IRModule and IR nodes.\n   *\n   * Only 3 types of replacements are allowed: from `src_sref->stmt` to `tgt_stmt`.\n   * 1) Block -> Block\n   * 2) Loop -> Loop\n   * 3) Loop -> BlockRealize\n   *\n   * \\param src_sref The sref to the statement to be replaced\n   * \\param tgt_stmt The statement to be replaced in\n   * \\param block_sref_reuse Maps an old block (to be replaced in the subtree under\n   * `src_sref->stmt`) to a new block (replaced to, in the subtree under `tgt_stmt`), and enforces\n   * reuse of srefs between them (rather than create new srefs) i.e. after being replaced, the sref\n   * that points to the old block will point to the new one\n   * \\note The reuse of loop srefs are detected automatically according to the reuse of loop vars.\n   */\n  TVM_DLL void Replace(const tir::StmtSRef& src_sref, const Stmt& tgt_stmt,\n                       const Map<Block, Block>& block_sref_reuse);\n  /*!\n   * \\brief Trigger the verification according to the `debug_mask` bitmask.\n   * 1) If the bitmask `kVerifySRefTree` is on, verify the correctness of the sref tree.\n   * 2) If the bitmask `kVerifyCachedFlags` is on, verify the correctness of `affine_binding`,\n   * `region_cover` and `stage_pipeline`\n   */\n  TVM_DLL void DebugVerify() const;\n\n  static constexpr const char* _type_key = \"tir.ScheduleState\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ScheduleStateNode, Object);\n\n  /******** Property of blocks ********/\n  /*! \\brief Returns the BlockInfo correpsonding to the block sref */\n  TVM_DLL BlockInfo GetBlockInfo(const StmtSRef& block_sref) const;\n  /*!\n   * \\brief Recalculate the BlockInfo recursively under stmt.\n   * If stmt is a Block itself, we will not reset its affine binding flag unless it doesn't\n   * have block vars, since the affine flag depends on the outer scope of stmt.\n   */\n  TVM_DLL void UpdateScopeBlockInfo(const Stmt& stmt);\n  /*!\n   * \\brief Get the BlockScope correpsonding to the sref of scope root block\n   * \\param scope_root The block sref to be retrieved\n   * \\return The corresponding BlockScope\n   */\n  BlockScope GetBlockScope(const StmtSRef& scope_root) const {\n    return GetBlockInfo(scope_root).scope;\n  }\n  /*!\n   * \\brief Check a cached flag indicating if the specific block has quasi-affine bindings\n   * \\param block_sref The block sref to be checked\n   * \\return A boolean flag indicating if the block has quasi-affine bindings\n   */\n  bool IsAffineBlockBinding(const StmtSRef& block_sref) const {\n    return GetBlockInfo(block_sref).affine_binding;\n  }\n  /*!\n   * \\brief Check a cached flag indicating if each of the specific consumer block's read region\n   * is fully produced by its producers\n   * \\param consumer_block_sref The specific consumer block\n   * \\return A boolean flag indicating if the block has quasi-affine bindings\n   */\n  bool IsRegionCoveredConsumer(const StmtSRef& consumer_block_sref) const {\n    return GetBlockInfo(consumer_block_sref).region_cover;\n  }\n  /*!\n   * \\brief Check a cached flag indicating if a block scope is an equivalence of a stage pipeline\n   * \\param scope_root The block sref to be retrieved\n   * \\return The corresponding BlockScope\n   */\n  bool IsStagePipeline(const StmtSRef& scope_root) const {\n    return GetBlockScope(scope_root)->stage_pipeline;\n  }\n};\n\n/*!\n * \\brief Managed reference to ScheduleStateNode\n * \\sa ScheduleStateNode\n */\nclass ScheduleState : public ObjectRef {\n public:\n  /*!\n   * \\brief Construct a schedule state from an IRModule\n   * \\param mod The IRModule to be scheduled\n   * \\param debug_mask Do extra correctness checking after the class creation\n   * and each time after calling the Replace method.\n   */\n  TVM_DLL explicit ScheduleState(IRModule mod, int debug_mask = 0);\n\n  /*! \\return The mutable pointer to the ScheduleStateNode */\n  ScheduleStateNode* get() const { return static_cast<ScheduleStateNode*>(data_.get()); }\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ScheduleState, ObjectRef, ScheduleStateNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_STATE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/schedule/trace.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_TRACE_H_\n#define TVM_TIR_SCHEDULE_TRACE_H_\n\n#include <tvm/tir/schedule/instruction.h>\n\nnamespace tvm {\nnamespace tir {\n\n// Forward declaration\nclass Trace;\n\n/*!\n * \\brief A callback that allows users to mutate decisions on the fly\n * when applying instructions. The signature of the callback is:\n * \\param inst The instruction\n * \\param inputs The input random variables\n * \\param attrs The attributes\n * \\param decision The original decision\n * \\return A new decision\n */\nusing FTraceDecisionProvider = runtime::TypedPackedFunc<ObjectRef(\n    const Instruction& inst, const Array<ObjectRef>& inputs, const Array<ObjectRef>& attrs,\n    const Optional<ObjectRef>& decision)>;\n\n/*!\n * \\brief An execution trace of a scheduling program\n *\n * A trace has two parts:\n * 1) The instructions invoked so far in the program execution\n * 2) The random decisions made upon those instructions, if any\n *\n * A trace can be serialized to:\n * 1) Roundtrippable JSON format: can be saved to file and loaded back\n * 2) Python syntax: allows users to copy-paste the trace to reproduce the scheduling process\n *\n * A trace can be applied to a TensorIR schedule by re-applying all its instructions possibly with\n * their decisions accordingly. Re-sampling is invoked if a sampling instruction doesn't have its\n * corresponding decision; Otherwise the existing decision will be reused accordingly.\n */\nclass TraceNode : public runtime::Object {\n public:\n  /*! \\brief The instructions invoked so far in the program execution */\n  Array<Instruction> insts;\n  /*! \\brief The random decisions made upon those instructions */\n  Map<Instruction, ObjectRef> decisions;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"insts\", &insts);\n    v->Visit(\"decisions\", &decisions);\n  }\n\n  static constexpr const char* _type_key = \"tir.Trace\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TraceNode, runtime::Object);\n\n public:\n  /*!\n   * \\brief Retrieve the decision made on a specific instruction\n   * \\param inst The instruction whose decision is to be retrieved\n   * \\return The corresponding decision; NullOpt if there is no decision made on the instruction\n   */\n  Optional<ObjectRef> GetDecision(const Instruction& inst) const;\n  /*!\n   * \\brief Append a new instruction to the trace\n   * \\param inst The new instruction to be appended\n   */\n  void Append(Instruction inst);\n  /*!\n   * \\brief Append a new instruction with a random decision to the trace\n   * \\param inst The new instruction to be appended\n   * \\param decision The random decision made on this instruction\n   * The type of `decision` depends on the instruction, e.g.\n   * the decision of `SamplePerfectTile` has type `Array<IntImm>`\n   */\n  void Append(Instruction inst, ObjectRef decision);\n  /*!\n   * \\brief Remove the last instruction, along with the decision made on that instruction, if any\n   * \\return The instruction removed; NullOpt if the trace is empty\n   */\n  Optional<Instruction> Pop();\n  /*!\n   * \\brief Apply the trace to a TensorIR schedule\n   * \\param sch The schedule to be applied onto\n   * \\param remove_postproc If postprocessing instructions are removed\n   * \\param decision_provider A callback that allows users to mutate decisions on the fly\n   * when applying instructions.\n   * \\sa FTraceDecisionProvider\n   */\n  void ApplyToSchedule(Schedule sch, bool remove_postproc,\n                       FTraceDecisionProvider decision_provider = nullptr) const;\n  /*!\n   * \\brief Serialize the trace as a JSON-style object\n   * \\param remove_postproc If postprocessing instructions are removed\n   * \\return The JSON-style object\n   */\n  ObjectRef AsJSON(bool remove_postproc) const;\n  /*!\n   * \\brief Serialize the trace as a sequence of python statements\n   * \\param remove_postproc If postprocessing instructions are removed\n   * \\return A sequence of python statements\n   */\n  Array<String> AsPython(bool remove_postproc) const;\n  /*!\n   * \\brief Create a new trace with an instruction whose decision is changed,\n   * assuming this instruction exists in the resulting trace\n   * \\param inst The instruction whose decision is to be changed\n   * \\param decision The decision to be changed to\n   * \\param remove_postproc If postprocessing instructions are removed\n   * \\return The new trace with the decision changed\n   */\n  Trace WithDecision(Instruction inst, ObjectRef decision, bool remove_postproc) const;\n  /*!\n   * \\brief Simplify the trace with dead-code elimination\n   * \\param remove_postproc If postprocessing instructions are removed\n   * \\return A simplified trace\n   */\n  Trace Simplified(bool remove_postproc) const;\n};\n\n/*!\n * \\brief Managed reference to TraceNode\n * \\sa TraceNode\n */\nclass Trace : public runtime::ObjectRef {\n public:\n  /*! \\brief Default constructor. Creating an empty trace. */\n  Trace();\n  /*!\n   * \\brief Constructor. Creating a trace from existing instructions and their decisions\n   * \\param insts The instructions used\n   * \\param decisions The decisions made in sampling\n   */\n  explicit Trace(Array<Instruction> insts, Map<Instruction, ObjectRef> decisions);\n  /*!\n   * \\brief Apply a JSON-serialized trace to a TensorIR schedule\n   * \\param json The JSON-serialized trace\n   * \\param sch The TensorIR schedule\n   */\n  static void ApplyJSONToSchedule(ObjectRef json, Schedule sch);\n\n  TVM_DEFINE_MUTABLE_NOTNULLABLE_OBJECT_REF_METHODS(Trace, runtime::ObjectRef, TraceNode);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_TRACE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/stmt.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tvm/tir/stmt.h\n * \\brief TIR statements.\n */\n// Acknowledgement: Many low-level stmts originate from Halide.\n#ifndef TVM_TIR_STMT_H_\n#define TVM_TIR_STMT_H_\n\n#include <tvm/tir/expr.h>\n\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\n/*! \\brief Base node of all statements. */\nclass StmtNode : public Object {\n public:\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  StmtNode() = default;\n  explicit StmtNode(Span span) : span(span) {}\n\n  static constexpr const char* _type_key = \"tir.Stmt\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  static constexpr const uint32_t _type_child_slots = 15;\n  TVM_DECLARE_BASE_OBJECT_INFO(StmtNode, Object);\n};\n\n/*! \\brief Container of all statements */\nclass Stmt : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(Stmt, ObjectRef, StmtNode);\n};\n\n/*!\n * \\brief Let binding, bind var to value, then run body.\n */\nclass LetStmtNode : public StmtNode {\n public:\n  /*! \\brief The variable. */\n  Var var;\n  /*! \\brief The value to be binded. */\n  PrimExpr value;\n  /*! \\brief The body block. */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"var\", &var);\n    v->Visit(\"value\", &value);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const LetStmtNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(var, other->var) && equal(value, other->value) &&\n           equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(var);\n    hash_reduce(value);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.LetStmt\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LetStmtNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to LetStmtNode.\n * \\sa LetStmtNode\n */\nclass LetStmt : public Stmt {\n public:\n  TVM_DLL LetStmt(Var var, PrimExpr value, Stmt body, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(LetStmt, Stmt, LetStmtNode);\n};\n\n/*!\n * \\brief Define certain auxiliary attribute for the body to be a symbolic value.\n *  This provide auxiliary information for IR passes that transforms body.\n *\n *  In terms of effect, this is equivalent to Block(Evaluate(value), body).\n *\n *  Examples of possible usage:\n *    - Bound of function, variables.\n *    - Hint which block corresponds to a parallel region.\n */\nclass AttrStmtNode : public StmtNode {\n public:\n  /*! \\brief this is attribute about certain node */\n  ObjectRef node;\n  /*! \\brief the type key of the attribute */\n  String attr_key;\n  /*! \\brief The attribute value, value is well defined at current scope. */\n  PrimExpr value;\n  /*! \\brief The body statement to be executed */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"node\", &node);\n    v->Visit(\"attr_key\", &attr_key);\n    v->Visit(\"value\", &value);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AttrStmtNode* other, SEqualReducer equal) const {\n    return equal(node, other->node) && equal(attr_key, other->attr_key) &&\n           equal(value, other->value) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(node);\n    hash_reduce(attr_key);\n    hash_reduce(value);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.AttrStmt\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AttrStmtNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to AttrStmtNode.\n * \\sa AttrStmtNode\n */\nclass AttrStmt : public Stmt {\n public:\n  TVM_DLL AttrStmt(ObjectRef node, String attr_key, PrimExpr value, Stmt body, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AttrStmt, Stmt, AttrStmtNode);\n};\n\n/*!\n * \\brief Assert condition, if an error occurs, return the error message.\n */\nclass AssertStmtNode : public StmtNode {\n public:\n  /*! \\brief Condition to be checked. */\n  PrimExpr condition;\n  /*! \\brief Error message when assertion failed. */\n  PrimExpr message;\n  /*!\n   * \\brief Body which this assertion holds true.\n   *  Will be executed after the assertion.\n   */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"message\", &message);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AssertStmtNode* other, SEqualReducer equal) const {\n    return equal(condition, other->condition) && equal(message, other->message) &&\n           equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(condition);\n    hash_reduce(message);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.AssertStmt\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AssertStmtNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to AssertStmtNode.\n * \\sa AssertStmtNode\n */\nclass AssertStmt : public Stmt {\n public:\n  TVM_DLL AssertStmt(PrimExpr condition, PrimExpr message, Stmt body, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AssertStmt, Stmt, AssertStmtNode);\n};\n\n/*!\n * \\brief Store value to the buffer.\n *\n *  Equivalent to ((DType*)buffer_var)[index] = value.\n *  where DType is the type specified by type().element_of().\n *\n *  For example, if type = float32x3, then the store will corresponds to\n *\n * \\code\n *\n *  auto buffer = static_cast<float*>(buffer_var);\n *  buffer[index.v0] = value.v0;\n *  buffer[index.v1] = value.v1;\n *  buffer[index.v2] = value.v2;\n *\n * \\endcode\n * \\sa LoadNode\n */\nclass StoreNode : public StmtNode {\n public:\n  /*! \\brief The buffer variable. */\n  Var buffer_var;\n  /*! \\brief The value to be stored. */\n  PrimExpr value;\n  /*! \\brief The index locations to be stored. */\n  PrimExpr index;\n  /*! \\brief The predicate to mask which lanes would be stored. */\n  PrimExpr predicate;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer_var\", &buffer_var);\n    v->Visit(\"value\", &value);\n    v->Visit(\"index\", &index);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const StoreNode* other, SEqualReducer equal) const {\n    return equal(buffer_var, other->buffer_var) && equal(value, other->value) &&\n           equal(index, other->index) && equal(predicate, other->predicate);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer_var);\n    hash_reduce(value);\n    hash_reduce(index);\n    hash_reduce(predicate);\n  }\n\n  static constexpr const char* _type_key = \"tir.Store\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StoreNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to StoreNode.\n * \\sa StoreNode\n */\nclass Store : public Stmt {\n public:\n  TVM_DLL Store(Var buffer_var, PrimExpr value, PrimExpr index, PrimExpr predicate,\n                Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Store, Stmt, StoreNode);\n};\n\n/*!\n * \\brief Store value to the high dimension buffer.\n *\n * \\code\n *\n *  buffer[i, j] = value;\n *\n * \\endcode\n * \\sa BufferLoad\n */\nclass BufferStoreNode : public StmtNode {\n public:\n  /*! \\brief The buffer variable. */\n  Buffer buffer;\n  /*! \\brief The value to be stored. */\n  PrimExpr value;\n  /*! \\brief The indices location to be stored. */\n  Array<PrimExpr> indices;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"value\", &value);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const BufferStoreNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(value, other->value) &&\n           equal(indices, other->indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(value);\n    hash_reduce(indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.BufferStore\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferStoreNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to BufferStoreNode.\n * \\sa BufferStoreNode\n */\nclass BufferStore : public Stmt {\n public:\n  TVM_DLL explicit BufferStore(Buffer buffer, PrimExpr value, Array<PrimExpr> indices,\n                               Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(BufferStore, Stmt, BufferStoreNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BufferStoreNode);\n};\n\n/*!\n * \\brief Annotate the region where the buffer need to\n *  be read and write in the body.\n *  We only need to allocate the space for the corresponding region.\n *\n * \\note There should be at most one BufferRealize for each buffer.\n *       BufferRealize is not necessary for external buffers,\n *       since they are assumed to be fully allocated.\n *\n * \\sa BufferLoad, BufferStore\n */\nclass BufferRealizeNode : public StmtNode {\n public:\n  /*! \\brief The buffer variable. */\n  Buffer buffer;\n  /*! \\brief Bounds to be realized */\n  Array<Range> bounds;\n  /*! \\brief Only realize if condition holds. */\n  PrimExpr condition;\n  /*! \\brief The body of realization. */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"bounds\", &bounds);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const BufferRealizeNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(bounds, other->bounds) &&\n           equal(condition, other->condition) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(bounds);\n    hash_reduce(condition);\n    hash_reduce(body);\n  }\n\n  BufferRealizeNode() = default;\n  BufferRealizeNode(Buffer buffer, Array<Range> bounds, PrimExpr condition, Stmt body,\n                    Span span = Span())\n      : StmtNode(span), buffer(buffer), bounds(bounds), condition(condition), body(body) {}\n\n  static constexpr const char* _type_key = \"tir.BufferRealize\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferRealizeNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to BufferRealizeNode.\n * \\sa BufferRealizeNode\n */\nclass BufferRealize : public Stmt {\n public:\n  TVM_DLL explicit BufferRealize(Buffer buffer, Array<Range> bounds, PrimExpr condition, Stmt body,\n                                 Span span = Span());\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(BufferRealize, Stmt, BufferRealizeNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BufferRealizeNode);\n};\n\n/*!\n * \\brief Store value into mult-dimensional array that will be read by the consumer\n *        of the producer.\n *\n * \\note This node only appears in high-level DSLs that are built on top of the TIR.\n *       It should not appear in a valid TIR PrimFunc. A high-level DSL needs to lower\n *       this node before TIR transformations.\n *\n * \\sa DataProducer\n */\nclass ProducerStoreNode : public StmtNode {\n public:\n  /*! \\brief The producer to store the results into. */\n  DataProducer producer;\n  /*! \\brief The value to be stored. */\n  PrimExpr value;\n  /*! \\brief The index arguments of the function. */\n  Array<PrimExpr> indices;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"producer\", &producer);\n    v->Visit(\"value\", &value);\n    v->Visit(\"indices\", &indices);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ProducerStoreNode* other, SEqualReducer equal) const {\n    return equal(producer, other->producer) && equal(value, other->value) &&\n           equal(indices, other->indices);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(producer);\n    hash_reduce(value);\n    hash_reduce(indices);\n  }\n\n  static constexpr const char* _type_key = \"tir.ProducerStore\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProducerStoreNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to ProducerStoreNode.\n * \\sa ProducerStoreNode\n */\nclass ProducerStore : public Stmt {\n public:\n  TVM_DLL ProducerStore(DataProducer producer, PrimExpr value, Array<PrimExpr> indices,\n                        Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ProducerStore, Stmt, ProducerStoreNode);\n};\n\n/*!\n * \\brief Annotate the bounds where the data produced by the producer\n *  need to be written and read in body.\n *  We will need to allocate space for the corresponding regions.\n *\n * \\note This node only appears in high-level DSLs that are built on top of the TIR.\n *       It should not appear in a valid TIR PrimFunc. A high-level DSL needs to lower\n *       this node before TIR transformations.\n *\n * \\sa DataProducer\n */\nclass ProducerRealizeNode : public StmtNode {\n public:\n  /*! \\brief The producer that produces the data. */\n  DataProducer producer;\n  /*! \\brief Bounds to be realized. */\n  Region bounds;\n  /*! \\brief Only realize if condition holds. */\n  PrimExpr condition;\n  /*! \\brief The body of realization. */\n  Stmt body;\n  /*! \\brief The storage scope associated with this realization. */\n  String storage_scope;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"producer\", &producer);\n    v->Visit(\"bounds\", &bounds);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"body\", &body);\n    v->Visit(\"storage_scope\", &storage_scope);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ProducerRealizeNode* other, SEqualReducer equal) const {\n    return equal(producer, other->producer) && equal(bounds, other->bounds) &&\n           equal(condition, other->condition) && equal(body, other->body) &&\n           equal(storage_scope, other->storage_scope);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(producer);\n    hash_reduce(bounds);\n    hash_reduce(condition);\n    hash_reduce(body);\n    hash_reduce(storage_scope);\n  }\n\n  static constexpr const char* _type_key = \"tir.ProducerRealize\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProducerRealizeNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to ProducerRealizeNode.\n * \\sa ProducerRealizeNode\n */\nclass ProducerRealize : public Stmt {\n public:\n  TVM_DLL ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition, Stmt body,\n                          String storage_scope = \"\", Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ProducerRealize, Stmt, ProducerRealizeNode);\n};\n\n/*!\n * \\brief Allocate a buffer that can be used in body.\n */\nclass AllocateNode : public StmtNode {\n public:\n  /*! \\brief The buffer variable. */\n  Var buffer_var;\n  /*! \\brief The type of the buffer. */\n  DataType dtype;\n  /*! \\brief The extents of the buffer. */\n  Array<PrimExpr> extents;\n  /*! \\brief Only allocate buffer when condition is satisfied. */\n  PrimExpr condition;\n  /*! \\brief The body to be executed. */\n  Stmt body;\n  /*!\n   * \\brief Additional annotations about the allocation.\n   *\n   *  These annotations can be used as auxiliary hint\n   *  to future transformations.\n   */\n  Map<String, ObjectRef> annotations;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer_var\", &buffer_var);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"extents\", &extents);\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"body\", &body);\n    v->Visit(\"annotations\", &annotations);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AllocateNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(buffer_var, other->buffer_var) && equal(dtype, other->dtype) &&\n           equal(extents, other->extents) && equal(condition, other->condition) &&\n           equal(body, other->body) && equal(annotations, other->annotations);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(buffer_var);\n    hash_reduce(dtype);\n    hash_reduce(extents);\n    hash_reduce(condition);\n    hash_reduce(body);\n    hash_reduce(annotations);\n  }\n\n  /*!\n   * \\brief If the buffer size is constant, return the size.\n   *        Otherwise return 0.\n   * \\return The result.\n   */\n  int64_t ConstantAllocationSize() const { return ConstantAllocationSize(extents); }\n  /*!\n   * \\brief If the buffer size is constant, return the size.\n   *        Otherwise return 0.\n   * \\param extents The extents of the buffer.\n   * \\return The result.\n   */\n  TVM_DLL static int64_t ConstantAllocationSize(const Array<PrimExpr>& extents);\n\n  static constexpr const char* _type_key = \"tir.Allocate\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllocateNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to AllocateNode.\n * \\sa AllocateNode\n */\nclass Allocate : public Stmt {\n public:\n  TVM_DLL Allocate(Var buffer_var, DataType dtype, Array<PrimExpr> extents, PrimExpr condition,\n                   Stmt body, Map<String, ObjectRef> annotations = Map<String, ObjectRef>(),\n                   Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Allocate, Stmt, AllocateNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(AllocateNode);\n};\n\n/*!\n * \\brief Allocate a buffer that can be used in body.\n */\nclass AllocateConstNode : public StmtNode {\n public:\n  /*! \\brief The buffer variable. */\n  Var buffer_var;\n  /*! \\brief The optional data associated to the constant.\n   */\n  Optional<runtime::NDArray> data;\n  /*!\n   * \\brief If the PrimFunc containing the Stmt is added to IRModule, this is an optional index\n   * to indicate the index within \"constants\" attribute, that is a Array<NDArray> of IRModule.\n   */\n  Optional<Integer> irmod_storage_idx;\n  /*! \\brief The type of the buffer. */\n  DataType dtype;\n  /*! \\brief The extents of the buffer. */\n  Array<PrimExpr> extents;\n  /*! \\brief The body to be executed. */\n  Stmt body;\n  /*!\n   * \\brief Additional annotations about the allocation.\n   *\n   *  These annotations can be used as auxiliary hint\n   *  to future transformations.\n   */\n  Map<String, ObjectRef> annotations;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer_var\", &buffer_var);\n    v->Visit(\"data\", &data);\n    v->Visit(\"irmod_storage_idx\", &irmod_storage_idx);\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"extents\", &extents);\n    v->Visit(\"body\", &body);\n    v->Visit(\"annotations\", &annotations);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const AllocateConstNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(buffer_var, other->buffer_var) && equal(dtype, other->dtype) &&\n           equal(extents, other->extents) && equal(data, other->data) && equal(body, other->body) &&\n           equal(annotations, other->annotations);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(buffer_var);\n    hash_reduce(dtype);\n    hash_reduce(extents);\n    hash_reduce(body);\n    hash_reduce(annotations);\n    hash_reduce(data);\n  }\n\n  /*!\n   * \\brief If the buffer size is constant, return the size.\n   *        Otherwise return 0.\n   * \\return The result.\n   */\n  int64_t ConstantAllocationSize() const { return ConstantAllocationSize(extents); }\n  /*!\n   * \\brief If the buffer size is constant, return the size.\n   *        Otherwise return 0.\n   * \\param extents The extents of the buffer.\n   * \\return The result.\n   */\n  TVM_DLL static int64_t ConstantAllocationSize(const Array<PrimExpr>& extents);\n\n  static constexpr const char* _type_key = \"tir.AllocateConst\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllocateConstNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to AllocateConstNode.\n * \\sa AllocateConstNode\n */\nclass AllocateConst : public Stmt {\n public:\n  /* The constructor to create a IRNode with constant data\n   * depending on the type of ObjectRef, it will either\n   * create AllocateConstNode with irmod_storage_idx or data\n   */\n  TVM_DLL AllocateConst(Var buffer_var, DataType dtype, Array<PrimExpr> extents,\n                        ObjectRef data_or_idx, Stmt body,\n                        Map<String, ObjectRef> annotations = Map<String, ObjectRef>(),\n                        Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);\n};\n\n/*! \\brief Declare a buffer that can be used in the body */\nclass DeclBufferNode : public StmtNode {\n public:\n  /*! \\brief The buffer being declared */\n  Buffer buffer;\n  /*! \\brief The body to be executed */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.DeclBuffer\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);\n};\n\n/*! \\brief Managed reference to DeclBufferNode */\nclass DeclBuffer : public Stmt {\n public:\n  TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());\n  TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(DeclBufferNode);\n};\n\n/*!\n * \\brief The container of seq statement.\n *        Represent a sequence of statements.\n */\nclass SeqStmtNode : public StmtNode {\n public:\n  /*! \\brief internal sequence content. */\n  Array<Stmt> seq;\n\n  /*! \\return get the size of the sequence */\n  size_t size() const { return seq.size(); }\n  /*!\n   * \\brief Get the index-th element in the sequence.\n   */\n  Stmt operator[](size_t index) const { return seq[index]; }\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"seq\", &seq);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const SeqStmtNode* other, SEqualReducer equal) const {\n    return equal(seq, other->seq);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(seq); }\n\n  static constexpr const char* _type_key = \"tir.SeqStmt\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SeqStmtNode, StmtNode);\n};\n\n/*! \\brief Sequence statement. */\nclass SeqStmt : public Stmt {\n public:\n  /*!\n   * \\brief Construct SeqStmt.\n   * \\param seq The sequence.\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL explicit SeqStmt(Array<Stmt> seq, Span span = Span());\n\n  /*! \\return get the size of the sequence */\n  size_t size() const { return operator->()->size(); }\n  /*!\n   * \\brief Get the index-th element in the sequence.\n   */\n  Stmt operator[](size_t index) const { return (*(operator->()))[index]; }\n  /*!\n   * \\brief Construct a sequence statement by flattening\n   *        all the arrays and sequences in the arguments\n   *        recursively.\n   *\n   * - When an argument is nullptr, it will be ignored.\n   * - When an argument is an array or a SeqStmt, it will be flattened recursively.\n   * - A normal Stmt will be appended to the end of the sequence.\n   *\n   * \\note This function can directly return an element\n   *       if it is the only element in the sequence.\n   *\n   * \\param seq_args The list of arguments to be flattened.\n   * \\tparam Args arguments\n   * \\return The constructed statement\n   */\n  template <typename... Args>\n  static Stmt Flatten(Args&&... seq_args) {\n    Array<Stmt> seq;\n    runtime::detail::for_each(Flattener(&seq), std::forward<Args>(seq_args)...);\n    if (seq.size() == 1) return seq[0];\n    return SeqStmt(seq);\n  }\n  /*! \\brief Helper class to flatten sequence of arguments into Array. */\n  class Flattener {\n   public:\n    explicit Flattener(Array<Stmt>* seq) : seq_(seq) {}\n\n    void operator()(size_t i, const Stmt& stmt) const {\n      if (!stmt.defined()) return;\n      if (auto* op = stmt.as<SeqStmtNode>()) {\n        operator()(0, op->seq);\n      } else {\n        seq_->push_back(stmt);\n      }\n    }\n\n    template <typename T>\n    void operator()(size_t i, const T& seq) const {\n      for (auto v : seq) {\n        this->operator()(0, v);\n      }\n    }\n\n   private:\n    Array<Stmt>* seq_;\n  };\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SeqStmt, Stmt, SeqStmtNode);\n};\n\n/*!\n * \\brief IfThenElse statment.\n */\nclass IfThenElseNode : public StmtNode {\n public:\n  /*! \\brief The condition. */\n  PrimExpr condition;\n  /*! \\brief The branch to be executed when condition is true. */\n  Stmt then_case;\n  /*! \\brief The branch to be executed when condition is false, can be null. */\n  Optional<Stmt> else_case;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"then_case\", &then_case);\n    v->Visit(\"else_case\", &else_case);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const IfThenElseNode* other, SEqualReducer equal) const {\n    return equal(condition, other->condition) && equal(then_case, other->then_case) &&\n           equal(else_case, other->else_case);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(condition);\n    hash_reduce(then_case);\n    hash_reduce(else_case);\n  }\n\n  static constexpr const char* _type_key = \"tir.IfThenElse\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IfThenElseNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to IfThenElseNode.\n * \\sa IfThenElseNode\n */\nclass IfThenElse : public Stmt {\n public:\n  TVM_DLL IfThenElse(PrimExpr condition, Stmt then_case, Optional<Stmt> else_case = NullOpt,\n                     Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IfThenElse, Stmt, IfThenElseNode);\n};\n\n/*!\n * \\brief Evaluates an expression.\n *  This is mostly used for putting a Call node into Stmt.\n *\n *  If value do not have side-effect, this node can be safely removed.\n */\nclass EvaluateNode : public StmtNode {\n public:\n  /*! \\brief The expression to be evaluated. */\n  PrimExpr value;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"value\", &value);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const EvaluateNode* other, SEqualReducer equal) const {\n    return equal(value, other->value);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const { hash_reduce(value); }\n\n  static constexpr const char* _type_key = \"tir.Evaluate\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(EvaluateNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to EvaluateNode.\n * \\sa EvaluateNode\n */\nclass Evaluate : public Stmt {\n public:\n  TVM_DLL explicit Evaluate(PrimExpr value, Span span = Span());\n\n  explicit Evaluate(int value, Span span = Span()) : Evaluate(PrimExpr(value), span) {}\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Evaluate, Stmt, EvaluateNode);\n};\n\n/*!\n * \\brief The kind of the loop.\n *\n *  ForKind can change the control flow semantics\n *  of the loop. So the kind field needs to be considered\n *  in all TIR passes.\n */\nenum class ForKind : int {\n  /*! \\brief default semantics -- serial execution. */\n  kSerial = 0,\n  /*! \\brief Parallel execution on CPU. */\n  kParallel = 1,\n  /*!\n   * \\brief Vector SIMD loop.\n   *  The loop body will be vectorized.\n   */\n  kVectorized = 2,\n  /*! \\brief The loop body must be unrolled. */\n  kUnrolled = 3,\n  /*!\n   * \\brief The loop variable is bound to a thread in\n   * an environment. In the final stage of lowering,\n   * the loop is simply removed and the loop variable is\n   * mapped to the corresponding context thread.\n   */\n  kThreadBinding = 4\n};\n\n/*!\n * \\brief A for loop, with poissible type annotations.\n *\n * \\code\n *\n *  for (loop_var = min; loop_var < min + extent; ++loop_var) {\n *    // body\n *  }\n * \\endcode\n */\nclass ForNode : public StmtNode {\n public:\n  /*! \\brief The loop variable. */\n  Var loop_var;\n  /*! \\brief The minimum value of iteration. */\n  PrimExpr min;\n  /*! \\brief The extent of the iteration. */\n  PrimExpr extent;\n  /*! \\brief The kind of the for loop. */\n  ForKind kind;\n  /*! \\brief The body of the for loop. */\n  Stmt body;\n  /*!\n   * \\brief Only valid when kind == ForKind::kThreadBinding\n   * The context thread that this loop variable bounds to.\n   */\n  Optional<IterVar> thread_binding;\n  /*!\n   * \\brief Additional annotations about the loop.\n   *\n   *  These annotations can be used as auxiliary hint\n   *  to future transformations. An annotation should\n   *  not change the control flow semantics of the loop\n   *  and can be ignored in most passes.\n   */\n  Map<String, ObjectRef> annotations;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"loop_var\", &loop_var);\n    v->Visit(\"min\", &min);\n    v->Visit(\"extent\", &extent);\n    v->Visit(\"kind\", &kind);\n    v->Visit(\"body\", &body);\n    v->Visit(\"thread_binding\", &thread_binding);\n    v->Visit(\"annotations\", &annotations);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const ForNode* other, SEqualReducer equal) const {\n    return equal.DefEqual(loop_var, other->loop_var) && equal(min, other->min) &&\n           equal(extent, other->extent) && equal(kind, other->kind) && equal(body, other->body) &&\n           equal(thread_binding, other->thread_binding) && equal(annotations, other->annotations);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(loop_var);\n    hash_reduce(min);\n    hash_reduce(extent);\n    hash_reduce(kind);\n    hash_reduce(body);\n    hash_reduce(thread_binding);\n    hash_reduce(annotations);\n  }\n\n  static constexpr const char* _type_key = \"tir.For\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ForNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to ForNode.\n * \\sa ForNode\n */\nclass For : public Stmt {\n public:\n  TVM_DLL For(Var loop_var, PrimExpr min, PrimExpr extent, ForKind kind, Stmt body,\n              Optional<IterVar> thread_binding = NullOpt,\n              Map<String, ObjectRef> annotations = Map<String, ObjectRef>(), Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(For, Stmt, ForNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(ForNode);\n};\n\n/*!\n * \\brief A While loop\n *\n * \\code\n *\n *  while (condition)\n *    body\n *\n * \\endcode\n */\nclass WhileNode : public StmtNode {\n public:\n  /*! \\brief The termination condition. */\n  PrimExpr condition;\n  /*! \\brief The body of the while loop. */\n  Stmt body;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"condition\", &condition);\n    v->Visit(\"body\", &body);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const WhileNode* other, SEqualReducer equal) const {\n    return equal(condition, other->condition) && equal(body, other->body);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(condition);\n    hash_reduce(body);\n  }\n\n  static constexpr const char* _type_key = \"tir.While\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(WhileNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to WhileNode.\n * \\sa WhileNode\n */\nclass While : public Stmt {\n public:\n  TVM_DLL While(PrimExpr condition, Stmt body, Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(While, Stmt, WhileNode);\n};\n\n/*!\n * \\brief A prefetch hint for a buffer\n */\nclass PrefetchNode : public StmtNode {\n public:\n  /*! \\brief The function to be prefetched. */\n  Buffer buffer;\n  /*! \\brief Bounds to be prefetched. */\n  Array<Range> bounds;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"bounds\", &bounds);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const PrefetchNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(bounds, other->bounds);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(bounds);\n  }\n\n  PrefetchNode() = default;\n  PrefetchNode(Buffer buffer, Array<Range> bounds, Span span = Span())\n      : StmtNode(span), buffer(buffer), bounds(bounds) {}\n\n  static constexpr const char* _type_key = \"tir.Prefetch\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PrefetchNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to PrefetchNode.\n * \\sa PrefetchNode\n */\nclass Prefetch : public Stmt {\n public:\n  TVM_DLL explicit Prefetch(Buffer buffer, Array<Range> bounds, Span span = Span());\n\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Prefetch, Stmt, PrefetchNode);\n};\n\n/*!\n * \\brief Representing the region of multi-dimensional buffer access.\n */\nclass BufferRegionNode : public Object {\n public:\n  /*! \\brief The buffer of the buffer region. */\n  Buffer buffer;\n  /*! \\brief The region array of the buffer region. */\n  Array<Range> region;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"region\", &region);\n  }\n\n  bool SEqualReduce(const BufferRegionNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(region, other->region);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(region);\n  }\n\n  static constexpr const char* _type_key = \"tir.BufferRegion\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferRegionNode, Object);\n};\n\n/*!\n * \\brief Managed reference to BufferRegionNode.\n * \\sa BufferRegionNode\n */\nclass BufferRegion : public ObjectRef {\n public:\n  TVM_DLL explicit BufferRegion(Buffer buffer, Array<Range> region);\n\n  /*!\n   * \\brief Create a BufferRegion which is full region of the given buffer.\n   * \\param buffer The buffer to generate full BufferRegion.\n   * \\return The BufferRegion which covers all region of the given buffer\n   */\n  TVM_DLL static BufferRegion FullRegion(Buffer buffer);\n\n  /*!\n   * \\brief Create a BufferRegion which is a single point of the given buffer.\n   * \\param buffer The buffer to generate single point BufferRegion.\n   * \\param indices The access point indices of the buffer\n   * \\return The BufferRegion which is the single point of the given buffer.\n   */\n  TVM_DLL static BufferRegion FromPoint(Buffer buffer, Array<PrimExpr> indices);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(BufferRegion, ObjectRef, BufferRegionNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BufferRegionNode);\n};\n\n/*!\n * \\brief Match introduces a constraint that the source buffer region can be remapped to the data\n * layout specified by the buffer field. The constraint can be checked in later part of lowering (or\n * optionally during runtime).\n *\n * MatchBufferRegion provides a mechanism to represent data layout and compactness constraints in\n * low-level hardware primitives in the IR and defer the check after the sequence of\n * transformations.\n */\nclass MatchBufferRegionNode : public Object {\n public:\n  /*! \\brief The target buffer. */\n  Buffer buffer;\n  /*! \\brief The source buffer region. */\n  BufferRegion source;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"buffer\", &buffer);\n    v->Visit(\"source\", &source);\n  }\n\n  bool SEqualReduce(const MatchBufferRegionNode* other, SEqualReducer equal) const {\n    return equal(buffer, other->buffer) && equal(source, other->source);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer);\n    hash_reduce(source);\n  }\n\n  static constexpr const char* _type_key = \"tir.MatchBufferRegion\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(MatchBufferRegionNode, Object);\n};\n\n/*!\n * \\brief Managed reference to MatchBufferRegionNode.\n * \\sa MatchBufferRegionNode\n */\nclass MatchBufferRegion : public ObjectRef {\n public:\n  TVM_DLL explicit MatchBufferRegion(Buffer buffer, BufferRegion source);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(MatchBufferRegion, ObjectRef, MatchBufferRegionNode);\n};\n\n/*!\n * \\brief A block is a basic schedule unit in TIR.\n * \\note Block's body is parameterized by iter vars.\n * \\code\n *\n *  with T.block(name):\n *      v0 = T.axis.S(domain, value0)\n *      v1 = T.axis.R(domain, value1)\n *      ...\n *      T.reads([buffer0[start:end, ...], ...])\n *      T.writes([buffer1[start:end, ...], ...])\n *      T.where(predicate)\n *      buffer2 = T.alloc_buffer(shape, dtype)\n *      buffer3 = T.match_buffer(source_buffer[start:end, ...])\n *      T.attr({attr_key: attr_value, ...})\n *      with T.init():\n *          // init body\n *      // body\n *\n * \\endcode\n */\nclass BlockNode : public StmtNode {\n public:\n  /*! \\brief The variables of the block. */\n  Array<IterVar> iter_vars;\n  /*! \\brief The read buffer regions of the block. */\n  Array<BufferRegion> reads;\n  /*! \\brief The write buffer regions of the block. */\n  Array<BufferRegion> writes;\n  /*! \\brief The name_hint of the block. */\n  String name_hint;\n  /*! \\brief The body of the block. */\n  Stmt body;\n  /*!\n   * \\brief The init statement is executed during the first iteration of reduction loops in a\n   *  reduction block. The optional init field allows us to represent initialization and\n   *  reduction update in a single block and transform them collectively.\n   *  We also provide primitives to decompose the init into a separate block during scheduling.\n   *  Init field is `NullOpt` if there is no reduction iter_vars\n   */\n  Optional<Stmt> init;\n  /*! \\brief The buffer allocated in the block. */\n  Array<Buffer> alloc_buffers;\n  /*! \\brief The match buffer regions. */\n  Array<MatchBufferRegion> match_buffers;\n  /*! \\brief The annotation of the block. */\n  Map<String, ObjectRef> annotations;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"iter_vars\", &iter_vars);\n    v->Visit(\"reads\", &reads);\n    v->Visit(\"writes\", &writes);\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"body\", &body);\n    v->Visit(\"init\", &init);\n    v->Visit(\"alloc_buffers\", &alloc_buffers);\n    v->Visit(\"match_buffers\", &match_buffers);\n    v->Visit(\"annotations\", &annotations);\n  }\n\n  bool SEqualReduce(const BlockNode* other, SEqualReducer equal) const {\n    // Need first reduce iter_vars, alloc_buffers and match_buffers to define new vars\n    return equal.DefEqual(iter_vars, other->iter_vars) &&\n           equal(alloc_buffers, other->alloc_buffers) &&\n           equal(match_buffers, other->match_buffers) && equal(reads, other->reads) &&\n           equal(writes, other->writes) && equal(body, other->body) && equal(init, other->init) &&\n           equal(annotations, other->annotations);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce.DefHash(iter_vars);\n    hash_reduce(alloc_buffers);\n    hash_reduce(match_buffers);\n    hash_reduce(reads);\n    hash_reduce(writes);\n    hash_reduce(body);\n    hash_reduce(init);\n    hash_reduce(annotations);\n  }\n\n  static constexpr const char* _type_key = \"tir.Block\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to BlockNode.\n * \\sa BlockNode\n */\nclass Block : public Stmt {\n public:\n  TVM_DLL explicit Block(Array<IterVar> iter_vars, Array<BufferRegion> reads,\n                         Array<BufferRegion> writes, String name_hint, Stmt body,\n                         Optional<Stmt> init = NullOpt,\n                         Array<Buffer> alloc_buffers = Array<Buffer>(),\n                         Array<MatchBufferRegion> match_buffers = Array<MatchBufferRegion>(),\n                         Map<String, ObjectRef> annotations = Map<String, ObjectRef>(),\n                         Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Block, Stmt, BlockNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BlockNode);\n};\n\n/*!\n * \\brief A block realization node represents execution of the block at the binding values.\n */\nclass BlockRealizeNode : public StmtNode {\n public:\n  /*! \\brief The corresponding values of the iter vars. */\n  Array<PrimExpr> iter_values;\n  /*!\n   * \\brief The predicate of the block realization, the block will only be executed when the\n   * predicate is true.\n   */\n  PrimExpr predicate;\n  /*! \\brief The block to be realized. */\n  Block block;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"iter_values\", &iter_values);\n    v->Visit(\"predicate\", &predicate);\n    v->Visit(\"block\", &block);\n  }\n\n  bool SEqualReduce(const BlockRealizeNode* other, SEqualReducer equal) const {\n    return equal(iter_values, other->iter_values) && equal(predicate, other->predicate) &&\n           equal(block, other->block);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(iter_values);\n    hash_reduce(predicate);\n    hash_reduce(block);\n  }\n\n  static constexpr const char* _type_key = \"tir.BlockRealize\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockRealizeNode, StmtNode);\n};\n\n/*!\n * \\brief Managed reference to BlockRealizeNode\n * \\sa BlockRealizeNode\n */\nclass BlockRealize : public Stmt {\n public:\n  TVM_DLL explicit BlockRealize(Array<PrimExpr> iter_values, PrimExpr predicate, Block block,\n                                Span span = Span());\n\n  TVM_DEFINE_OBJECT_REF_METHODS(BlockRealize, Stmt, BlockRealizeNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(BlockRealizeNode);\n};\n\n/*! \\brief namespace of possible attributes in AttrStmt.attr_key */\nnamespace attr {\n// The above attr does not pass to ir stage.\n/*! \\brief Mark launching extent of thread, used by device API. */\nconstexpr const char* thread_extent = \"thread_extent\";\n/*! \\brief Mark launching of a virtual thread. */\nconstexpr const char* virtual_thread = \"virtual_thread\";\n/*! \\brief Mark region is processed by a co-proccesor */\nconstexpr const char* coproc_scope = \"coproc_scope\";\n/*!\n * \\brief Mark region creates coprocessor micro ops,\n *  can be reused if corresponding variable is independent.\n */\nconstexpr const char* coproc_uop_scope = \"coproc_uop_scope\";\n/*! \\brief Mark the scope as volatile access for certain handle. */\nconstexpr const char* volatile_scope = \"volatile_scope\";\n/*!\n * \\brief Mark the scope as generated by extern primitive.\n *  such scope can contain arbitrary ir program and we need to be careful\n *  when make certain assumptions about the structure of the program.\n */\nconstexpr const char* extern_scope = \"extern_scope\";\n/*!\n * \\brief Mark the scope as when computation start to happen\n *  This can hint some code generator to create a new function for compute.\n */\nconstexpr const char* compute_scope = \"compute_scope\";\n/*! \\brief Mark storage alignment requirement of buffers */\nconstexpr const char* storage_alignment = \"storage_alignment\";\n/*! \\brief Mark storage scope of realization */\nconstexpr const char* realize_scope = \"realize_scope\";\n/*! \\brief The allocation device for global malloc in host. */\nconstexpr const char* device_id = \"device_id\";\n/*! \\brief The device type. */\nconstexpr const char* device_type = \"device_type\";\n/*! \\brief Mark of loop scope */\nconstexpr const char* loop_scope = \"loop_scope\";\n/*! \\brief Mark of reduce scope */\nconstexpr const char* reduce_scope = \"reduce_scope\";\n/*! \\brief Pragma: auto-unroll, max_step */\nconstexpr const char* pragma_auto_unroll_max_step = \"pragma_auto_unroll_max_step\";\n/*! \\brief Pragma: unroll explicit */\nconstexpr const char* pragma_unroll_explicit = \"pragma_unroll_explicit\";\n/*! \\brief Mark region is guarded by the pragma extension */\nconstexpr const char* pragma_scope_prefix = \"pragma_\";\n/*! \\brief Import C source or file into the final code gen module */\nconstexpr const char* pragma_import_c = \"pragma_import_c\";\n/*! \\brief Import llvm source or file into the final code gen module */\nconstexpr const char* pragma_import_llvm = \"pragma_import_llvm\";\n/*! \\brief Try to modify the AST to support Tensor Core */\nconstexpr const char* pragma_tensor_core = \"pragma_tensor_core\";\n/*!\n * \\brief Mark of prefetch scope, value=offset,\n *  run prefetch of Tensor on the current loop scope\n */\nconstexpr const char* prefetch_scope = \"prefetch_scope\";\n/*!\n * \\brief Marks the layout transforms to be used for a tensor.\n *\n * Only applies to a DataProducer, as it should be made part of the\n * PrimFunc attributes for TIR.\n */\nconstexpr const char* layout_transforms = \"layout_transforms\";\n/*!\n * \\brief Marks the physical axis separators\n *\n * Only applies to a DataProducer, as it should be made part of the\n * Buffer definition in a PrimFunc.  See `BufferNode::axis_separators`\n * for more details.\n */\nconstexpr const char* axis_separators = \"axis_separators\";\n/*!\n * \\brief Marks production of double buffer data\n */\nconstexpr const char* double_buffer_scope = \"double_buffer_scope\";\n/*!\n * \\brief Marks region used by double buffer write\n */\nconstexpr const char* double_buffer_write = \"double_buffer_write\";\n/*! \\brief Mark realization for rolling buffer optimization */\nconstexpr const char* rolling_buffer_scope = \"rolling_buffer_scope\";\n/*! \\brief Mark of scan update scope */\nconstexpr const char* scan_update_scope = \"scan_update_scope\";\n/*! \\brief Mark of scan init scope */\nconstexpr const char* scan_init_scope = \"scan_init_scope\";\n/*!\n * \\brief Mark alignment of buffer dimension\n *  stmt.node is Tensor\n *  stmt.value is tvm_tuple(dim, align, offset)\n *  This gives hint to require stride of dim to be k * align + offset.\n */\nconstexpr const char* buffer_dim_align = \"buffer_dim_align\";\n/*! \\brief Mark stores/loads with theirs bounds.  */\nconstexpr const char* buffer_bound = \"buffer_bound\";\n/*!\n * \\brief Bind the buffer specification to the region of the op\n *  When this scope occurs, the stmt.node is a Array<NodeRef> = [buffer, tensor]\n *  stmt.value is a tvm_tuple(min0, extent0, min1, extent1, ...).\n *  The scope represents that we need to bind the storage region of tensor to buffer.\n *  This will affect replacement of some variables inside the scope that\n *  corresponds to field of buffer to be the actual expressions of tensor during\n *  storage flattening phase.\n */\nconstexpr const char* buffer_bind_scope = \"buffer_bind_scope\";\n// Pipeline related attributes\n/*! \\brief channel read scope */\nconstexpr const char* channel_read_scope = \"channel_read_scope\";\n/*! \\brief Advance step of channel after end of scope */\nconstexpr const char* channel_read_advance = \"channel_read_advance\";\n/*! \\brief channel write scope */\nconstexpr const char* channel_write_scope = \"channel_write_scope\";\n/*! \\brief Advance step of channel after end of scope */\nconstexpr const char* channel_write_advance = \"channel_write_advance\";\n/*! \\brief pipeline stage scope, implies always execution */\nconstexpr const char* pipeline_stage_scope = \"pipeline_stage_scope\";\n/*! \\brief pipeline execution scope, implies the scope can be pipelined. */\nconstexpr const char* pipeline_exec_scope = \"pipeline_exec_scope\";\n\n/*!\n * \\brief Mark that it is in the device scope.\n */\nconstexpr const char* device_scope = \"device_scope\";\n\n/*!\n * \\brief Mark that the attached statement runs asynchronously.\n */\nconstexpr const char* async_scope = \"async_scope\";\n\n/*!\n * \\brief Annotations for invoking and synchronizing asynchronous operations.\n\n * Synchronization is done in terms of \"queue\": It is an abstract entity associated\n * with each asynchronous unit, and it tracks invocations and completions of asynchronous\n * operations in the FIFO order.\n *\n * Similarly to PTX instructions commit_group and wait_group, these annotations express\n * synchronization by \"counting\":\n *\n * async_commit_queue(i): Group one or more invocations of async operations in the given scope,\n * and \"commit\" (or push) them to the queue i. A group of operations committed together is\n * awaited as one chunk. Groups committed to the same queue complete in the FIFO order.\n *\n * async_wait_queue(i, N): Block until only N most recent committed groups are still in-flight at\n * the queue i. N does not have to be a constant, but some backends may require a constant count.\n*/\nconstexpr const char* async_commit_queue_scope = \"async_commit_queue_scope\";\nconstexpr const char* async_wait_queue_scope = \"async_wait_queue_scope\";\nconstexpr const char* async_wait_inflight_count = \"async_wait_inflight_count\";\n\n/*!\n * \\brief Mark that the shape of TensorCore fragment\n */\nconstexpr const char* fragment_shape = \"fragment_shape\";\n\n/*!\n * \\brief Mark that the layout of TensorCore fragment\n */\nconstexpr const char* fragment_layout = \"fragment_layout\";\n\n/*!\n * \\brief Mark that the kernel is hand threaded and doesn't need syncs inserted\n */\nconstexpr const char* hand_threaded = \"hand_threaded\";\n\n/*!\n * \\brief Mark whether the script-completer need to fill in missing access region\n *        during script parsing.\n * \\note The result should be a integer mask with range [0, 4).\n *       if (mask & 1) the read region should be detected,\n *       if (mask & 2) the write region should be detected.\n */\nconstexpr const char* script_parsing_detect_access = \"tir.script_parsing_detect_access\";\n\n/*!\n * \\brief Mark that the loop should be partitioned.\n */\nconstexpr const char* pragma_loop_partition_hint = \"pragma_loop_partition_hint\";\n\n/*! \\brief Mark the stage of a statement in the software pipeline */\nconstexpr const char* software_pipeline_stage = \"software_pipeline_stage\";\n\n/*! \\brief Mark the order of a statement in the software pipeline */\nconstexpr const char* software_pipeline_order = \"software_pipeline_order\";\n\n/*! \\brief List stages in the software pipeline that should run asynchronously\n * \\note All statements in the provided stages are assumed to have asynchronous\n *       semantics (e.g. CUDA async global to shared memory copy).\n */\nconstexpr const char* software_pipeline_async_stages = \"software_pipeline_async_stages\";\n\n/*! \\brief Mark the buffers which is const access and can be transformed layout. */\nconstexpr const char* layout_free_buffers = \"layout_free_buffers\";\n\n/*! \\brief Mark the local stage for the shared memory access should be added. */\nconstexpr const char* manifest_shared_memory_local_stage = \"tir.manifest_shared_memory_local_stage\";\n\n/*! \\brief Mark the tiling structure of blocks that are applied by rule Multi-Level-Tiling */\nconstexpr const char* meta_schedule_tiling_structure = \"meta_schedule.tiling_structure\";\n\n/*!\n * \\brief Mark that the loop should be further skip and bound to environment threads to enable\n * cooperative fetching.\n */\nconstexpr const char* meta_schedule_cooperative_fetch = \"meta_schedule.cooperative_fetch\";\n\n/*! \\brief The allowed range of thread extent in thread bindings */\nconstexpr const char* meta_schedule_thread_extent_low_inclusive =\n    \"meta_schedule.thread_extent_low_inclusive\";\n\n/*! \\brief The allowed range of thread extent in thread bindings */\nconstexpr const char* meta_schedule_thread_extent_high_inclusive =\n    \"meta_schedule.thread_extent_high_inclusive\";\n\n/*! \\brief Mark the block whose producer needs to be applied by rule Random-Compute-Location */\nconstexpr const char* meta_schedule_random_compute_producer =\n    \"meta_schedule.random_compute_producer\";\n\n/*! \\brief Mark auto-parallel setting on the block. */\nconstexpr const char* meta_schedule_parallel = \"meta_schedule.parallel\";\n\n/*! \\brief Mark auto-vectorize setting on the block. */\nconstexpr const char* meta_schedule_vectorize = \"meta_schedule.vectorize\";\n\n/*! \\brief Mark auto-unroll setting on the block. */\nconstexpr const char* meta_schedule_unroll_explicit = \"meta_schedule.unroll_explicit\";\n\n/*! \\brief Mark auto-unroll setting on the block. */\nconstexpr const char* meta_schedule_unroll_implicit = \"meta_schedule.unroll_implicit\";\n\n/*! \\brief Mark that a block should be further rewritten using tensorization. */\nconstexpr const char* meta_schedule_auto_tensorize = \"meta_schedule.auto_tensorize\";\n\n/*! \\brief Mark that a block is a preprocessor block for layout rewrite. */\nconstexpr const char* meta_schedule_layout_rewrite_preproc = \"meta_schedule.layout_rewrite_preproc\";\n/*!\n * \\brief Mark that the init statement of a block should be further rewritten using tensorization.\n */\nconstexpr const char* meta_schedule_auto_tensorize_init = \"meta_schedule.auto_tensorize_init\";\n\n/*!\n * \\brief Mark that a block is executed by a warp. This implies the extend of threadIdx.x is\n * warp size.\n */\nconstexpr const char* warp_execution = \"warp_execution\";\n\n/*!\n * \\brief Check if attr_key is a pragma key extension\n * \\param attr_key The attr key to be compared\n * \\return true if it is a pragma key\n */\ninline bool IsPragmaKey(const std::string& attr_key) {\n  return attr_key.compare(0, 7, \"pragma_\") == 0;\n}\n\n}  // namespace attr\n/*!\n * \\brief Create a type annotation expression\n * \\param dtype The data type\n * \\param span The location of this object in the source code.\n * \\return Expr a expression with dtype.\n */\nTVM_DLL PrimExpr TypeAnnotation(DataType dtype, Span span = Span());\n\n// overload printing of for type.\nTVM_DLL std::ostream& operator<<(std::ostream& os, ForKind kind);\n\n// inline implementations\ninline const char* ForKind2String(ForKind t) {\n  switch (t) {\n    case ForKind::kSerial:\n      return \"serial\";\n    case ForKind::kParallel:\n      return \"parallel\";\n    case ForKind::kVectorized:\n      return \"vectorized\";\n    case ForKind::kUnrolled:\n      return \"unroll\";\n    case ForKind::kThreadBinding:\n      return \"thread_binding\";\n  }\n  LOG(FATAL) << \"Unknown ForKind\" << t;\n  return \"Unknown\";\n}\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_STMT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/stmt_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/stmt_functor.h\n *\n * \\brief Functors for tir stmts\n *        utility functions to call common functors.\n */\n#ifndef TVM_TIR_STMT_FUNCTOR_H_\n#define TVM_TIR_STMT_FUNCTOR_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/expr_functor.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/stmt.h>\n\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace tir {\n/*!\n * \\brief Same as ExprFunctor except it is applied on statements\n * \\tparam FType The function signature.\n * \\sa ExprFunctor\n */\ntemplate <typename FType>\nclass StmtFunctor;\n\n#define STMT_FUNCTOR_DEFAULT \\\n  { return VisitStmtDefault_(op, std::forward<Args>(args)...); }\n\n#define IR_STMT_FUNCTOR_DISPATCH(OP)                                                       \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {     \\\n    return self->VisitStmt_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\ntemplate <typename R, typename... Args>\nclass StmtFunctor<R(const Stmt& n, Args... args)> {\n private:\n  using TSelf = StmtFunctor<R(const Stmt& n, Args... args)>;\n  using FType = NodeFunctor<R(const ObjectRef& n, TSelf* self, Args... args)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~StmtFunctor() {}\n  /*!\n   * \\brief Same as call.\n   * \\param n The stmt node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  R operator()(const Stmt& n, Args... args) { return VisitStmt(n, std::forward<Args>(args)...); }\n  /*!\n   * \\brief The functor call.\n   * \\param n The stmt node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitStmt(const Stmt& n, Args... args) {\n    static FType vtable = InitVTable();\n    return vtable(n, this, std::forward<Args>(args)...);\n  }\n  // Functions that can be overriden by subclass\n  virtual R VisitStmt_(const LetStmtNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const AttrStmtNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const IfThenElseNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const ForNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const AssertStmtNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const ProducerStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const ProducerRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const PrefetchNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const SeqStmtNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const EvaluateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const BlockNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmt_(const BlockRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;\n  virtual R VisitStmtDefault_(const Object* op, Args...) {\n    LOG(FATAL) << \"Do not have a default for \" << op->GetTypeKey();\n    return R();\n  }\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    FType vtable;\n    IR_STMT_FUNCTOR_DISPATCH(LetStmtNode);\n    IR_STMT_FUNCTOR_DISPATCH(AttrStmtNode);\n    IR_STMT_FUNCTOR_DISPATCH(IfThenElseNode);\n    IR_STMT_FUNCTOR_DISPATCH(ForNode);\n    IR_STMT_FUNCTOR_DISPATCH(WhileNode);\n    IR_STMT_FUNCTOR_DISPATCH(AllocateNode);\n    IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);\n    IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);\n    IR_STMT_FUNCTOR_DISPATCH(StoreNode);\n    IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);\n    IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);\n    IR_STMT_FUNCTOR_DISPATCH(ProducerRealizeNode);\n    IR_STMT_FUNCTOR_DISPATCH(PrefetchNode);\n    IR_STMT_FUNCTOR_DISPATCH(SeqStmtNode);\n    IR_STMT_FUNCTOR_DISPATCH(EvaluateNode);\n    IR_STMT_FUNCTOR_DISPATCH(BufferStoreNode);\n    IR_STMT_FUNCTOR_DISPATCH(BufferRealizeNode);\n    IR_STMT_FUNCTOR_DISPATCH(BlockNode);\n    IR_STMT_FUNCTOR_DISPATCH(BlockRealizeNode);\n    return vtable;\n  }\n};\n\n#undef IR_STMT_FUNCTOR_DISPATCH\n#undef STMT_FUNCTOR_DEFAULT\n\n/*!\n * \\brief StmtVisitor.\n */\nclass TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {\n public:\n  using StmtFunctor::operator();\n\n protected:\n  using StmtFunctor::VisitStmt;\n  /*!\n   * \\brief Visitor to Exprs, can be overriden\n   *        to do recursive changes to Exprs.\n   * \\note A common pattern is to call ExprVisitor here,\n   *       or have a class sub-class both StmtVisitor and ExprVisitor\n   *       and redirect Visit to ExprMutator::VisitExpr(Expr)\n   */\n  virtual void VisitExpr(const PrimExpr& e) {}\n  // statement visitor\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const LetStmtNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const WhileNode* op) override;\n  void VisitStmt_(const AllocateNode* op) override;\n  void VisitStmt_(const AllocateConstNode* op) override;\n  void VisitStmt_(const DeclBufferNode* op) override;\n  void VisitStmt_(const StoreNode* op) override;\n  void VisitStmt_(const BufferStoreNode* op) override;\n  void VisitStmt_(const BufferRealizeNode* op) override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const ProducerStoreNode* op) override;\n  void VisitStmt_(const ProducerRealizeNode* op) override;\n  void VisitStmt_(const PrefetchNode* op) override;\n  void VisitStmt_(const SeqStmtNode* op) override;\n  void VisitStmt_(const EvaluateNode* op) override;\n  void VisitStmt_(const BlockNode* op) override;\n  void VisitStmt_(const BlockRealizeNode* op) override;\n};\n\n/*!\n * \\brief StmtMutator that mutates the statements.\n */\nclass TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {\n public:\n  /*!\n   * \\brief Mutate stmt.\n   * \\param stmt The input statement to be mutated.\n   * \\return The result of the call\n   * \\note It is important that stmt is passed by value.\n   *       so copy on write can be triggered correctly.\n   *       do mutator(std::move(stmt)) or when copy elison is triggered.\n   */\n  Stmt operator()(Stmt stmt) {\n    allow_copy_on_write_ = true;\n    return VisitStmt(stmt);\n  }\n\n protected:\n  // We perform copy on write optimizations on the StmtMutator\n  // so that an unique copy of parent can be mutated inplace\n  // when some of its children changed.\n  // We only do such optimization for Stmt nests(instead of Exprs) for now\n  // as Stmt's parent state is more likely remain unchanged when one of\n  // its child block changes.\n  /*!\n   * \\brief Internal state to indicate whether copy on write is enabled.\n   *  COW is enabled iff all the parents of the node are unique.\n   */\n  bool allow_copy_on_write_{false};\n  /*!\n   * \\brief Perform copy on write on node.\n   *\n   *  If CopyOnWrite is allowed, directly return\n   *  a strong reference to the node container.\n   *  Otherwise, return a copy of the node.\n   *\n   * \\return The result object pointer.\n   */\n  template <typename TNode>\n  ObjectPtr<TNode> CopyOnWrite(const TNode* node) {\n    static_assert(std::is_base_of<StmtNode, TNode>::value,\n                  \"StmtMutator:: CopyOnWrite requires us to track uniqueness of all parent \"\n                  \"nodes during the recursion. Because the child classes do not necessarily \"\n                  \"check the Array, Expr and other structures during the visit, it is only safe to \"\n                  \"call this function with StmtNodes for now. \"\n                  \"Please create a new node directly in other cases.\");\n    if (allow_copy_on_write_) {\n      // return the old node.\n      return runtime::GetObjectPtr<TNode>(const_cast<TNode*>(node));\n    } else {\n      // Make a new copy of the node.\n      // need to rely on the default copy constructor\n      return runtime::make_object<TNode>(*node);\n    }\n  }\n  /*!\n   * \\brief Internal mutator that everyone calls.\n   * \\note To override mutate's behavior, override VisitExpr instead.\n   * \\param stmt The input stmt.\n   * \\return The mutated results.\n   */\n  Stmt VisitStmt(const Stmt& stmt) override {\n    if (allow_copy_on_write_ && !stmt.unique()) {\n      allow_copy_on_write_ = false;\n      Stmt ret = StmtFunctor::VisitStmt(stmt);\n      allow_copy_on_write_ = true;\n      return ret;\n    } else {\n      return StmtFunctor::VisitStmt(stmt);\n    }\n  }\n  /*!\n   * \\brief Visitor to Exprs, can be overriden\n   *        to do recursive changes to Exprs.\n   * \\note A common pattern is to call ExprMutator here,\n   *       or have a class sub-class both StmtMutator and ExprMutator\n   *       and redirect Mutate to ExprMutator::Mutate(Expr)\n   */\n  virtual PrimExpr VisitExpr(const PrimExpr& e) { return e; }\n  // statement visitor\n  Stmt VisitStmt_(const AttrStmtNode* op) override;\n  Stmt VisitStmt_(const IfThenElseNode* op) override;\n  Stmt VisitStmt_(const LetStmtNode* op) override;\n  Stmt VisitStmt_(const ForNode* op) override;\n  Stmt VisitStmt_(const WhileNode* op) override;\n  Stmt VisitStmt_(const AllocateNode* op) override;\n  Stmt VisitStmt_(const AllocateConstNode* op) override;\n  Stmt VisitStmt_(const DeclBufferNode* op) override;\n  Stmt VisitStmt_(const StoreNode* op) override;\n  Stmt VisitStmt_(const BufferStoreNode* op) override;\n  Stmt VisitStmt_(const BufferRealizeNode* op) override;\n  Stmt VisitStmt_(const AssertStmtNode* op) override;\n  Stmt VisitStmt_(const ProducerStoreNode* op) override;\n  Stmt VisitStmt_(const ProducerRealizeNode* op) override;\n  Stmt VisitStmt_(const PrefetchNode* op) override;\n  Stmt VisitStmt_(const SeqStmtNode* op) override;\n  Stmt VisitStmt_(const EvaluateNode* op) override;\n  Stmt VisitStmt_(const BlockNode* op) override;\n  Stmt VisitStmt_(const BlockRealizeNode* op) override;\n  /*!\n   * \\brief Alternative advance method for SeqStmtNode.\n   *\n   *  This function can be called when a child class override\n   *  VisitStmt_(const SeqStmtNode*) to introduce\n   *  the special behavior to visit\n   *\n   * \\param op The sequence.\n   * \\param flatten_before_visit Whether to flatten the sequence before visit.\n   * \\param fmutate The mutate function, can be nullptr, which defaults to Visit.\n   * \\return The mutated result.\n   */\n  Stmt VisitSeqStmt_(const SeqStmtNode* op, bool flatten_before_visit,\n                     std::function<Stmt(const Stmt&)> fmutate = nullptr);\n\n  // internal helper.\n  class Internal;\n};\n\n/*!\n * \\brief Visitor that recursively visit stmts and exprs on them.\n */\nclass StmtExprVisitor : public StmtVisitor, public ExprVisitor {\n public:\n  using StmtVisitor::operator();\n  using ExprVisitor::operator();\n\n protected:\n  using ExprVisitor::VisitExpr;\n  using StmtVisitor::VisitStmt;\n\n  void VisitExpr(const PrimExpr& e) override { return ExprVisitor::VisitExpr(e); }\n};\n\n/*!\n * \\brief Mutator that recursively mutates stmts and exprs on them.\n */\nclass StmtExprMutator : public StmtMutator, public ExprMutator {\n public:\n  using StmtMutator::operator();\n  using ExprMutator::operator();\n\n protected:\n  using ExprMutator::VisitExpr;\n  using StmtMutator::VisitExpr;\n\n  PrimExpr VisitExpr(const PrimExpr& e) override { return ExprMutator::VisitExpr(e); }\n};\n\n/*!\n * \\brief recursively visit the ir nodes in post DFS order, and transform it\n *\n * \\param stmt The ir to be transformed.\n * \\param preorder The function called in before recursive mutation\n *          If preorder returns None, then the transform will proceed to recursive call.\n *          If preorder returns a not None Stmt/Expr, the transformer will simply return it and\n *          won't do further recursion.\n * \\param postorder The function called after recursive mutation.\n *          The recursive mutation result is passed to postorder for further mutation.\n * \\param only_enable List of runtime::String.\n *          If it is null, all IRNode will call preorder/postorder\n *          If it is not null, preorder/postorder will only be called\n *          when the IRNode's type key is in the list.\n */\nTVM_DLL Stmt IRTransform(Stmt stmt, const runtime::PackedFunc& preorder,\n                         const runtime::PackedFunc& postorder,\n                         Optional<Array<String>> only_enable = NullOpt);\n\n/*!\n * \\brief Recursively visit the ir in post DFS order node, apply fvisit\n * Each node is guaranteed to be visited only once.\n * \\param node The ir to be visited.\n * \\param fvisit The visitor function to be applied.\n */\nTVM_DLL void PostOrderVisit(const ObjectRef& node, std::function<void(const ObjectRef&)> fvisit);\n\n/*!\n * \\brief Substitute the var specified by vmap.\n * \\param stmt The source statement to be substituted\n * \\param vmap returns a new value if re-mapping is needed, otherwise returns nullptr.\n * \\return The converted form.\n */\nTVM_DLL Stmt Substitute(Stmt stmt, std::function<Optional<PrimExpr>(const Var& var)> vmap);\n\n/*!\n * \\brief Substitute the var specified by vmap.\n * \\param expr The source statement to be substituted\n * \\param vmap returns a new value if re-mapping is needed, otherwise returns nullptr.\n * \\return The result.\n */\nTVM_DLL PrimExpr Substitute(PrimExpr expr, std::function<Optional<PrimExpr>(const Var& var)> vmap);\n\n/*!\n * \\brief Substitute the var specified by vmap.\n * \\param region The object whose vars are to be substituted\n * \\param vmap The map of new values.\n * \\return The result.\n */\nTVM_DLL Array<Range> Substitute(const Array<Range>& region, const Map<Var, PrimExpr>& vmap);\n\n/*!\n * \\brief Sugar for substitute via a given map.\n * \\param input The input to be updated.\n * \\param value_map The map of new values.\n * \\return The result.\n * \\tparam T the input type, can be PrimExpr or Stmt.\n */\ntemplate <typename T>\ninline auto Substitute(T input, const Map<Var, PrimExpr>& value_map) {\n  auto vmap = [&](const Var& var) -> Optional<PrimExpr> {\n    auto it = value_map.find(var);\n    if (it != value_map.end()) return (*it).second;\n    return Optional<PrimExpr>(nullptr);\n  };\n  return Substitute(std::move(input), vmap);\n}\n\n/*!\n * \\brief Sugar for substitute via a given map.\n * \\param input The input to be updated.\n * \\param value_map The map of new values.\n * \\return The result.\n * \\tparam T the input type, can be PrimExpr or Stmt.\n */\ntemplate <typename T>\ninline T Substitute(T input, const std::unordered_map<const VarNode*, PrimExpr>& value_map) {\n  auto vmap = [&](const Var& var) -> Optional<PrimExpr> {\n    auto it = value_map.find(var.get());\n    if (it != value_map.end()) return (*it).second;\n    return Optional<PrimExpr>(nullptr);\n  };\n  return Substitute(std::move(input), vmap);\n}\n\n/*!\n * \\brief Substitute the var specified by vmap and legalize data types after substitution.\n * \\param stmt The source statement to be substituted\n * \\param vmap returns a new value if re-mapping is needed, otherwise returns nullptr.\n *\n * Unlike `Substitute`, this allows the substitution to change the data type of the expression.\n *\n * \\sa Substitute\n * \\return The result.\n */\nTVM_DLL Stmt SubstituteWithDataTypeLegalization(Stmt stmt,\n                                                std::function<Optional<PrimExpr>(const Var&)> vmap);\n\n/*!\n * \\brief Substitute the var specified by vmap and legalize data types after substitution.\n * \\param expr The source statement to be substituted\n * \\param vmap returns a new value if re-mapping is needed, otherwise returns nullptr.\n *\n * Unlike `Substitute`, this allows the substitution to change the data type of the expression.\n *\n * \\sa Substitute\n * \\return The result.\n */\nTVM_DLL PrimExpr SubstituteWithDataTypeLegalization(\n    PrimExpr expr, std::function<Optional<PrimExpr>(const Var&)> vmap);\n\n/*!\n * \\brief Recursively visit the IR in pre DFS order node, apply fvisit.\n * If fvisit returns false, it won't visit the children of the node.\n * \\param stmt_or_expr The ir to be visited.\n * \\param fvisit The visitor function to be applied. If fvisit returns false, it won't visit the\n * children of the node\n */\nTVM_DLL void PreOrderVisit(const ObjectRef& stmt_or_expr,\n                           const std::function<bool(const ObjectRef&)>& fvisit);\n\n/*!\n * \\brief Renew the definition nodes for a TIR, including Var, Buffer and IterVar.\n *        This pass works as a simple DeepCopy to duplicate a function with different Vars and\n *        Buffers but the same behavior\n * \\param func The input PrimFunc.\n * \\return The renewed func.\n */\nTVM_DLL PrimFunc RenewDefs(const PrimFunc& func);\n\n/*!\n * \\brief Check if the statement contains the specified node type.\n *\n * This utility potentially walks the entire statement, and should\n * therefore not be used if it could otherwise be merged with another\n * pass.\n *\n * \\param stmt The statement to be searched\n * \\return Whether stmt contains Node\n */\ntemplate <typename Node, typename = std::enable_if_t<std::is_base_of_v<StmtNode, Node>>>\nbool ContainsNode(const Stmt& stmt) {\n  struct Visitor : StmtVisitor {\n    // Early bail-out, if we already found the node.\n    void VisitStmt(const Stmt& stmt) final {\n      if (contains_node) {\n        return;\n      }\n      StmtVisitor::VisitStmt(stmt);\n    }\n\n    void VisitStmt_(const Node* block) override { contains_node = true; }\n\n    bool contains_node{false};\n  };\n\n  Visitor visitor;\n  visitor(stmt);\n  return visitor.contains_node;\n}\n\n/*!\n * \\brief Legalize the data types of expressions to make sure they are consistent with other\n * parts of the program.\n *\n * It enforces the following rules:\n * - The data type of the index variable in a loop must be consistent with the data type of the loop\n *  bounds.\n * - The data type of the binary and ternary expressions must be consistent with the data types of\n * each of their operands.\n * - The data type of the bounds and binding values of block iter vars must be consistent with the\n * data type of the block iter vars.\n *\n * Usually we enforce the consistency of data types when constructing the IR nodes. However, such\n * inconsistency may happen as a result of IR mutation in some passes. This class can be used as\n * base class of such passes to ensure the consistency of data types.\n */\nclass DataTypeLegalizer : public StmtExprMutator {\n protected:\n  Stmt VisitStmt_(const ForNode* op) override;\n\n  Stmt VisitStmt_(const AttrStmtNode* op) override;\n  Stmt VisitStmt_(const BlockRealizeNode* op) override;\n  Stmt VisitStmt_(const BlockNode* op) override;\n  PrimExpr VisitExpr_(const SelectNode* op) override;\n  PrimExpr VisitExpr_(const RampNode* op) override;\n  PrimExpr VisitExpr_(const AddNode* op) override;\n  PrimExpr VisitExpr_(const SubNode* op) override;\n  PrimExpr VisitExpr_(const MulNode* op) override;\n  PrimExpr VisitExpr_(const DivNode* op) override;\n  PrimExpr VisitExpr_(const ModNode* op) override;\n  PrimExpr VisitExpr_(const FloorDivNode* op) override;\n  PrimExpr VisitExpr_(const FloorModNode* op) override;\n  PrimExpr VisitExpr_(const MinNode* op) override;\n  PrimExpr VisitExpr_(const MaxNode* op) override;\n  PrimExpr VisitExpr_(const EQNode* op) override;\n  PrimExpr VisitExpr_(const NENode* op) override;\n  PrimExpr VisitExpr_(const LTNode* op) override;\n  PrimExpr VisitExpr_(const LENode* op) override;\n  PrimExpr VisitExpr_(const GTNode* op) override;\n  PrimExpr VisitExpr_(const GENode* op) override;\n  PrimExpr VisitExpr_(const CallNode* op) override;\n\n  using StmtExprMutator::VisitExpr_;\n  using StmtExprMutator::VisitStmt_;\n\n  // a map from IterVar before rewrite to that after rewrite,\n  // ensures one old IterVar maps to exactly one new IterVar\n  std::unordered_map<const IterVarNode*, IterVar> ivmap_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_STMT_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/transform.h\n * \\brief TIR specific transformation passes.\n */\n#ifndef TVM_TIR_TRANSFORM_H_\n#define TVM_TIR_TRANSFORM_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\nnamespace transform {\n\nusing tvm::transform::Pass;\nusing tvm::transform::PassContext;\nusing tvm::transform::PassContextNode;\nusing tvm::transform::PassInfo;\nusing tvm::transform::PassInfoNode;\nusing tvm::transform::PassNode;\nusing tvm::transform::Sequential;\n\n/*\n * \\brief Create a function pass that optimizes PrimFuncs.\n *\n * \\param pass_func The packed function that contains the optimization.\n * \\param opt_level The optimization level of the function pass.\n * \\param name The name of the function pass.\n * \\param required The list of the passes that the function pass is dependent on.\n *\n * \\return The created function pass.\n */\nTVM_DLL Pass CreatePrimFuncPass(\n    const runtime::TypedPackedFunc<PrimFunc(PrimFunc, IRModule, PassContext)>& pass_func,\n    int opt_level, String name, tvm::Array<String> required);\n\n/*!\n * \\brief Inject prefetch instructions into stmt.\n *\n * \\return The pass.\n */\nTVM_DLL Pass InjectPrefetch();\n\n// TODO(tvm-team): consolidate configs to the PassContext\n/*!\n * \\brief Flatten the multi-dimensional read/write\n *  to single dimensional Load/Store\n *\n * \\param cache_line_size The size of CPU cache line.\n * \\param create_bound_attribute Whether to create bound attributes.\n *\n * \\return The Pass\n */\nTVM_DLL Pass StorageFlatten(int cache_line_size, bool create_bound_attribute = false);\n\n/*!\n * \\brief Inject copy intrinsics with optional pad.\n *\n * \\param pragma_key The pragma key for hint of copy.\n * \\param fintrin The function with signature\n *\n *   Stmt fintrin(Buffer src,\n *                Buffer dst,\n *                Array<Expr> pad_before,\n *                Array<Expr> pad_after,\n *                Expr pad_value)\n * \\return The pass.\n */\nTVM_DLL Pass InjectCopyIntrin(String pragma_key, runtime::PackedFunc fintrin);\n\n/*!\n * \\brief Detect and insert sync points to co-processor.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CoProcSync();\n\n/*!\n * \\brief Lift common attrs with attr_key to outer scope.\n *\n * \\param attr_key The attribute key to be checked.\n * \\return The pass.\n */\nTVM_DLL Pass LiftAttrScope(String attr_key);\n\n/*!\n * \\brief partition loops in the stmt.\n *\n * \\return The pass.\n */\nTVM_DLL Pass LoopPartition();\n\n/*!\n * \\brief Lower vectorization loops.\n *\n * \\param enable_vectorize Whether vectorization is enabled.\n *\n * \\return The pass.\n */\nTVM_DLL Pass VectorizeLoop(bool enable_vectorize = true);\n\n/*!\n * \\brief Inject virtual thread loops.\n *\n * \\return The pass.\n */\nTVM_DLL Pass InjectVirtualThread();\n\n/*!\n * \\brief Inject double buffer statements.\n *\n * \\return The pass.\n */\nTVM_DLL Pass InjectDoubleBuffer();\n\n/*!\n * \\brief Rewrite storage allocation pattern.\n *  Moves the allocation to outer most possible scope.\n *  Trying to share space between allocations to make\n *  a static allocation plan when possible.\n *\n * \\return The pass.\n */\nTVM_DLL Pass StorageRewrite();\n\n/*!\n * \\brief unroll the constant loop marked by unroll.\n * This pass also automatically attach pragma unroll tag to loops which meets the standard.\n *\n * \\return The pass.\n */\nTVM_DLL Pass UnrollLoop();\n\n/*!\n * \\brief Remove No Op from the Stmt.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RemoveNoOp();\n\n/*!\n * \\brief Detect and rewrite unsafe select that contains memory access.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RewriteUnsafeSelect();\n\n/*!\n * \\brief Run arithmetic simplifications on the statements and expressions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass Simplify();\n\n/*!\n * \\brief Instruments bound checkers.\n *\n * \\return The pass.\n */\nTVM_DLL Pass InstrumentBoundCheckers();\n\n/*!\n * \\brief Transform the high-level PrimFunc to a low-level version\n *        that can be used as an API function.\n *\n *\n *  The main task of this function is to create code to :\n *   - Map the values in the api_args to Var that is required by body.\n *   - Insert assertions to check type/value of the passed arguments.\n *\n * \\note\n *  The function signature have two cases\n *\n *  let num_packed_args = len(api_args);\n *\n *  if num_packed_args is zero:\n *     f()\n *\n *  if num_packed_args is not zero:\n *       f(TVMArg* packed_args, int* packed_arg_type_ids, int num_packed_args,\n *         api_arg_k, api_arg_k+1, ... api_arg_n,\n *         TVMValue* out_ret_val, int* out_ret_tcode)\n *\n *       where n == len(api_args), k == num_packed_args\n *\n * \\return The pass.\n */\nTVM_DLL Pass MakePackedAPI();\n\n/*!\n * \\brief Transform the high-level PrimFunc to a C signature that can be used\n *   to call the operator directly.\n *\n *  The main task of this function is to create code that maps the values in the\n *  api_args to Var that is required by body\n *\n * \\return The pass.\n */\nTVM_DLL Pass MakeUnpackedAPI();\n\n/*!\n * \\brief Remap the thread axis\n *\n *  This can be used to get equivalent program which uses\n *  threadIdx.y in place of threadIdx.x by passing\n *  {\"threadIdx.x\": thread_axis(\"threadIdx.y\")}\n *\n *\n * \\return The pass.\n */\nTVM_DLL Pass RemapThreadAxis(Map<String, IterVar> axis_map);\n\n/*!\n * \\brief Lower custom datatypes.\n *\n * See tvm::datatypes::Registry for more information on adding custom datatypes.\n *\n * \\return The pass.\n */\nTVM_DLL Pass LowerCustomDatatypes();\n\n/*!\n * \\brief Decorate all the function's body as device function.\n *\n * \\return The pass.\n */\nTVM_DLL Pass DecorateDeviceScope();\n\n/*!\n * \\brief Split the function into a host function and device functions.\n *\n * \\return The pass.\n */\nTVM_DLL Pass SplitHostDevice();\n\n/*!\n * \\brief skip assert stmt.\n *\n * \\return The pass.\n */\nTVM_DLL Pass SkipAssert();\n\n/*!\n * \\brief Insert sync between parallel read/write of shared buffers.\n *\n * \\param storage_scope The storage scope considered.\n * \\return The pass.\n */\nTVM_DLL Pass ThreadSync(String storage_scope);\n\n/*!\n * \\brief Lower cross thread alleduce.\n *\n * \\return The pass.\n */\nTVM_DLL Pass LowerThreadAllreduce();\n\n/*!\n * \\brief Infer the TensorCore fragment infomation using tensor intrinsics\n *\n * \\return The pass.\n */\nTVM_DLL Pass InferFragment();\n\n/*!\n * \\brief This annotation is for nodes to be disabled for builtin lowering\n */\nstatic constexpr const char* kDisableLowerTVMBuiltin = \"disable_lower_builtin\";\n\n/*!\n * \\brief Lower builtin intrinsics.\n * \\return The pass.\n */\nTVM_DLL Pass LowerTVMBuiltin();\n\n/*!\n * \\brief Lower the target specific function intrinsics in each of the function.\n *\n * \\return The pass.\n */\nTVM_DLL Pass LowerIntrin();\n\n/*!\n * \\brief Lower warp memory access to low-level device related function calls.\n * \\return The pass.\n */\nTVM_DLL Pass LowerWarpMemory();\n\n/*!\n * \\brief Lower attached storage access information on device.\n *\n * \\note Run this pass after all storage access analysis finish.\n *\n * \\return The pass.\n */\nTVM_DLL Pass LowerDeviceStorageAccessInfo();\n\n/*!\n * \\brief Combine context calls in the host function.\n *\n * \\return The pass.\n */\nTVM_DLL Pass CombineContextCall();\n\n/*!\n * \\brief Narrow down PrimExpr datatype in stmt to target_bits.\n *\n * \\param target_bits The target bits\n *\n * \\note Run this pass after storage flatten.\n * \\return The pass.\n */\nTVM_DLL Pass NarrowDataType(int target_bits);\n\n/*!\n * \\brief Legalize bf16 typed Ops. Add a cast to fp32\n *   before Ops, then add a cast back to bf16.\n * \\return The pass.\n */\nTVM_DLL Pass BF16Legalize();\n\n/*!\n * \\brief Rewrite the pointer content type of arguments,\n *  as well as Alloc internal to the function to use\n *  the most frequently accessed type for load/store\n *  to avoid pointer casting in backend when possible.\n *\n * \\return The pass.\n */\nTVM_DLL Pass PointerValueTypeRewrite();\n\n/*!\n * \\brief Hoist loop-invariant IfThenElse nodes to\n * outside the elligible loops.\n *\n * \\return The pass.\n */\nTVM_DLL Pass HoistIfThenElse();\n\n/*!\n * \\brief Hoist loop-invariant expressions nodes to\n * outside the elligible loops.\n *\n * Can hoist conditionals used in IfThenElse statements and\n * expressions, bindings of variables in Let statements and\n * expressions, or boolean expressions, configurable to enable/disable\n * each hoistable type.\n *\n * \\return The pass.\n */\nTVM_DLL Pass HoistExpression();\n\n/*!\n * \\brief Lower cross-thread reduction from thread\n * bindings to intrinsic function calls.\n * \\return The pass.\n */\nTVM_DLL Pass LowerCrossThreadReduction();\n\n/*!\n * \\brief Lower block init stmt into IfThenElse stmts\n * \\return The pass.\n */\nTVM_DLL Pass LowerInitBlock();\n\n/*!\n * \\brief Locate the buffer allocation to the exact position (usually is\n *        the lca of buffer access). This pass will inject opaque block\n *        with alloc_buffers at the allocation site.\n * \\return The pass.\n */\nTVM_DLL Pass PlanAndUpdateBufferAllocationLocation();\n\n/*!\n * \\brief Substitute all the block vars with the PrimExprs they are bound to, indicated by the\n *        corresponding iter_values in BlockRealize, for opaque blocks by removing all\n *.        the iter_values in BlockRealize and iter_vars in Block.\n * \\return The pass.\n */\nTVM_DLL Pass ConvertBlocksToOpaque();\n\n/*!\n * \\brief Compact the buffer access region by removing the buffer regions that are not accessed,\n *        i.e. narrowing the buffer shape and adjust the access region if necessary.\n *\n * Before narrowing, `B` is a `[16, 16]` buffer, but only a skinny vector `B[i, 0:16]` is accessed.\n *\n *  \\code\n *\n *  for i in range(0, 16):\n *      with T.block():\n *          B = T.alloc_buffer(16, 16)\n *          for j in range(0, 16):\n *              B[i, j] = A[i, j] + 1\n *          for j in range(0, 16):\n *              C[i, j] = B[i, j] + 1\n *\n *  \\endcode\n *\n * This pass narrows the buffer shape and adjust its accessed region accordingly.\n * In this particular case, because only a `1 * 16` vector of `B` is accessed,\n * the pass narrows `B` to shape `[1, 16]`, and changes the access to `B[i, j]` to `B[0, j]`.\n *\n *  \\code\n *\n *  for i in range(0, 16):\n *      with T.block():\n *          B = T.alloc_buffer(1, 16)\n *          for j in range(0, 16):\n *              B[0, j] = A[i, j] + 1\n *          for j in range(0, 16):\n *              C[i, j] = B[0, j] + 1\n *\n *  \\endcode\n *\n *\n * \\return The pass.\n */\nTVM_DLL Pass CompactBufferAllocation();\n\n/*!\n * This pass legalizes packed calls by wrapping their arguments into TVMValues\n */\nTVM_DLL Pass LegalizePackedCalls();\n\n/*!\n * \\brief Remove match buffers inside the block. Also, it will validate the binding.\n * \\return The pass.\n */\nTVM_DLL Pass LowerMatchBuffer();\n\n/*!\n * \\brief Remove the block to ensure that the TIR can not be scheduled again.\n * \\return The pass.\n */\nTVM_DLL Pass LowerOpaqueBlock();\n\n/*!\n * \\brief Flatten the multi-dimensional BufferLoad and BufferStore to single dimensional\n *        BufferLoad/BufferStore for the TIR not contains opaque block.\n * \\return The pass.\n */\nTVM_DLL Pass FlattenBuffer();\n\n/*\n * \\brief Flatten the multi-dimensional read/write\n *  to two dimensional texture Load/Store and realize\n *  texture buffer allocations.\n *\n * \\return The Pass\n */\nTVM_DLL Pass TextureFlatten();\n\n/*\n * \\brief Lower VTCM allocations\n *\n * \\return The Pass\n */\nTVM_DLL Pass LowerVtcmAlloc();\n\n/*!\n * \\brief Lower Async TIR primitives to DMA copy and wait builtins\n */\nTVM_DLL Pass LowerAsyncDMA();\n\n/*!\n * \\brief Implements a Common Subexpression Elimination (CSE) for TIR\n *        which introduces let-in bindings for duplicated sub-expressions.\n * \\param enable_cse_tir Whether common subexpression elimination is enabled.\n * \\param identify_equiv_terms Whether equivalent terms should be identified.\n * \\return The pass.\n */\nTVM_DLL Pass CommonSubexprElimTIR(bool enable_cse_tir = true, bool identify_equiv_terms = false);\n\n/*!\n * \\brief Unify all the thread bindings for \"blockIdx.x/y/z\", \"threadIdx.x/y/z\", and\n *        \"vthread.x/y/z\". Before the unification, two vars that are bound to a thread axis (e.g.,\n *        \"threadIdx.x\") use different IterVars and variables in their AttrStmts. After the\n *        unification, we use a consolidated IterVar and a variable for them.\n * \\return The pass.\n * \\note `vthread` is a legacy behavior that will be deprecated, though thread bindings of `vthread`\n *       are still also unified in this pass. Please use `vthread.x`, `vthread.y` and `vthread.z`\n *       instead.\n */\nTVM_DLL Pass UnifyThreadBinding();\n\n/*!\n *  A pass to merge multiple TIR-level dynamic shared memory allocations into one\n */\nTVM_DLL Pass MergeDynamicSharedMemoryAllocations();\n\n/*!\n * \\brief This pass is post-scheduling pass to convert all\n *        Parallel For loops to Serial ones. This is run\n *        to attain lesser memory and/or executor/backend\n *        does not support parallel launch of For loops.\n * \\return The pass.\n */\nTVM_DLL Pass ConvertForLoopsToSerial();\n\n/*!\n * \\brief This is the unified static memory planner pass that will\n * plan for memory intra- and inter- PrimFuncs together. The pass\n * requires all the function to be PrimFuncs including the main.\n * \\return The pass.\n */\nTVM_DLL Pass UnifiedStaticMemoryPlanner();\n\n/*!\n * \\brief This pass transforms annotated loops into pipelined ones where producers and consumers\n * are overlapped with the information provided in loop annotations, which enables optimization\n * techniques like prefetching and pipeline parallelism.\n *\n * The pipeline scope consists of the direct children of the annotated loop (ignoring BlockRealize,\n * Block, SeqStmt), and the number of children is denoted by `n` in the documentation.\n *\n * The following annotations are used to guide the loop transformation:\n *\n * 1) Loop annotation `software_pipeline_stage` defines the pipeline stage.\n * An array of `n` integers, and each element should be in range [0, max_stage],\n * where max_stage is the maximum (inclusive) stage.\n * 2) Loop annotation `software_pipeline_order` defines the pipeline order.\n * An array of `n` integers, a permutation of [0, 1, ..., num_components - 1];\n * 3) Block annotation `double_buffer_scope` controls certain buffer sizes to allow decoupling of\n * read/write dependency. It's an integer index of the write regions of the block.\n *\n * Every annotated loop is transformed into a loop with three blocks as its direct children:\n *\n * 1) Prologue block, where components whose stage is less than `max_stage` is executed;\n *\n * 2) Body block, where all the components are executed;\n *\n * 3) Epilogue block, where only components whose stage is greater than 0 will be executed.\n * The execution order is controlled by the annotation `software_pipeline_order`,\n * and thus could be different than the original order.\n *\n * Note: For nested software pipelines, the inner software pipeline will be generated first,\n * which may affect the number of the direct children of the outer loop.\n * In this case, the annotations for the outer software\n * pipeline should include the result of the inner software pipeline,\n * which is the three blocks as discussed above.\n * Example:\n *\n * Before this pass, the TIR is:\n *\n * \\code{.py}\n * @T.prim_func\n * def before_transform(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]) -> None:\n *     for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n *         for i in T.serial(0, 16,\n *                           annotations={\"software_pipeline_stage\": [0, 1],\n *                                        \"software_pipeline_order\": [0, 1]}\n *                          ):\n *             with T.block():\n *                 T.reads(A[tx, i])\n *                 T.writes(C[tx, i])\n *                 B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n *                 with T.block(\"B\"):\n *                     T.reads(A[tx, i])\n *                     T.writes(B[tx, 0])\n *                     B[tx, 0] = A[tx, i] * T.float32(2)\n *                 with T.block(\"C\"):\n *                     T.reads(B[tx, 0])\n *                     T.writes(C[tx, i])\n *                     C[tx, i] = B[tx, 0] + T.float32(1)\n * \\endcode\n *\n * The TIR above annotates the loop as a two-stage pipeline with no reordering.\n * After applying this pass, the TIR is transformed into:\n *\n * \\code{.py}\n * @T.prim_func\n * def after_transform(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]) -> None:\n *     for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n *         with T.block():\n *             T.reads([A[tx, 0:16]])\n *             T.writes([C[tx, 0:16]])\n *             B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n *             with T.block(\"prologue\"):\n *                 T.reads([A[tx, 0]])\n *                 T.writes([B[0, tx, 0]])\n *                 B[0, tx, 0] = A[tx, 0] * T.float32(2)\n *             with T.block(\"body\"):\n *                 T.reads([A[tx, 1:16], B[0:2, tx, 0]])\n *                 T.writes([B[0:2, tx, 0], C[tx, 0:15]])\n *                 for i in T.serial(0, 15):\n *                     with T.block(\"B\"):\n *                         T.reads([A[tx, i + 1]])\n *                         T.writes([B[(i + 1) % 2, tx, 0]])\n *                         B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2)\n *                     with T.block(\"C\"):\n *                         T.reads([B[i % 2, tx, 0]])\n *                         T.writes([C[tx, i]])\n *                         C[tx, i] = B[i % 2, tx, 0] + T.float32(1)\n *             with T.block(\"epilogue\"):\n *                 T.reads([B[1, tx, 0]])\n *                 T.writes([C[tx, 15]])\n *                 C[tx, 15] = B[1, tx, 0] + T.float32(1)\n * \\endcode\n *\n * The original loop has two blocks, B and C, as its direct children. The loop annotations indicate\n * that block B has stage == 0, order == 0, block C has stage == 1, order == 1. Therefore, block B\n * should be executed in advance of block C by one iteration. The order 0 and 1 specifies the order\n * of block B and C inside the body block inside the result TIR.\n *\n * \\return The IR transform pass.\n */\nTVM_DLL Pass InjectSoftwarePipeline();\n\nTVM_DLL Pass BindParams(const Array<runtime::NDArray>& constants);\n\n/*!\n * \\brief Pass to collect tir non-scalar constants into module's 'Constants' attribute.\n *\n * \\return The pass.\n */\nTVM_DLL Pass ExtractPrimFuncConstants();\n\n/*!\n * \\brief Renormalize the split pattern from floordiv(floormod()) to floormod(floordiv())\n * \\return The pass.\n */\nTVM_DLL Pass RenormalizeSplitPattern();\n\n/*!\n * \\brief Annotate a PrimFunc with a given target.\n * \\return The pass.\n */\nTVM_DLL Pass BindTarget(Target target);\n\n/*!\n * \\brief Set a PrimFunc as the entry point if it is only function in IRModule.\n * \\return The pass.\n */\nTVM_DLL Pass AnnotateEntryFunc();\n\n/*!\n * \\brief Filter PrimFuncs with a given condition.\n * \\return The pass.\n */\nTVM_DLL Pass Filter(runtime::TypedPackedFunc<bool(PrimFunc)> fcond);\n\n/*!\n * \\brief Pass to rewrite global to shared memory copy on CUDA with asyncronous copy.\n * \\return The pass.\n */\nTVM_DLL Pass InjectPTXAsyncCopy();\n\n/*!\n * \\brief Remove the weight layout rewrite block\n * \\param skip_ndarray_rewrite If True, exact rewrite of NDArray, according to the given index map,\n *  will be skipped. Only the shape of the NDArray is transformed correctly, and the content of\n *  the destination array will be filled with random values.\n *\n *  When this pass is called many times during MetaSchedule tuning, the raw data of NDArray,\n *  before and after rewrite, does not matter. Since NDArray layout rewrite, using IndexMap's\n *  MapNDArray, is currently slow, skipping the exact rewrite is sometimes necessary.\n *\n * \\return The pass.\n */\nTVM_DLL Pass RemoveWeightLayoutRewriteBlock(bool skip_ndarray_rewrite = false);\n\n/*!\n * \\brief Add the explicit local stage for the shared memory access on GPU.\n * \\return The pass.\n */\nTVM_DLL Pass ManifestSharedMemoryLocalStage();\n\n/*!\n * \\brief Insert intrinsic calls to instrument function and loop level profiling.\n * \\return The pass.\n */\nTVM_DLL Pass InstrumentProfileIntrinsics();\n\n}  // namespace transform\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/usmp/algo/greedy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file include/tvm/tir/usmp/algo/greedy.h\n * \\brief This header file contains helper methods used in greedy algorithms\n * for planning  memory for USMP\n */\n#pragma once\n#include <tvm/arith/analyzer.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/stmt_functor.h>\n#include <tvm/tir/usmp/utils.h>\n\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\nnamespace usmp {\nnamespace algo {\n\n/*!\n * \\brief This is the base class for Greedy Algorithms where the sorting\n * is specialized in the extended classes based on the greedy criteria.\n */\nclass GreedyBase {\n public:\n  GreedyBase() {}\n  /*!\n   * \\brief This function should be implemented by the extended classes to sort the BufferInfo\n   * objects based on a criteria and then calling PostSortAllocation.\n   */\n  virtual Map<BufferInfo, PoolAllocation> PlanMemory(const Array<BufferInfo>& buffer_info_arr) = 0;\n\n protected:\n  /*!\n   * \\brief Rounds up the offset to satisfy the alignement requirement\n   */\n  size_t round_up_to_byte_alignment(const size_t& non_aligned_byte_offset,\n                                    const int& byte_alignment);\n\n  /*!\n   * \\brief A helper function check whether a offset is valid given the constraints\n   */\n  bool IsValidPlacement(const PoolInfo& candidate_pool, const size_t& next_offset,\n                        const size_t& size_bytes);\n\n  /*!\n   * \\brief Selects a pool for placement in the given set of ordered pool candidates\n   */\n  PoolInfo SelectPlacementPool(\n      const BufferInfo& buf_info,\n      const std::unordered_map<PoolInfo, size_t, ObjectPtrHash, ObjectPtrEqual>& pool_offsets);\n\n  /*!\n   * \\brief This is the base allocation function that works on sorted BufferInfo objects based\n   * on the greedy heuristic. The sorting algorithm has to be called before calling this.\n   */\n  Map<BufferInfo, PoolAllocation> PostSortAllocation(\n      const std::vector<BufferInfo>& buffer_info_vec);\n};\n\n}  // namespace algo\n}  // namespace usmp\n}  // namespace tir\n}  // namespace tvm\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/usmp/algorithms.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/usmp/algorithms.h\n * \\brief The memory planning algorithm for USMP\n */\n\n#ifndef TVM_TIR_USMP_ALGORITHMS_H_\n#define TVM_TIR_USMP_ALGORITHMS_H_\n\n#include <tvm/tir/usmp/utils.h>\n\nnamespace tvm {\nnamespace tir {\nnamespace usmp {\nnamespace algo {\n\n/*!\n * \\brief The Greedy-by-Size algorithm to plan memory\n *\n * This will perform a greedy algorithm in deciding the offsets\n * within provided Pools, using the size of the buffer.\n *\n * \\return A Map of BufferInfo objects and their associated PoolAllocation\n */\nMap<BufferInfo, PoolAllocation> GreedyBySize(const Array<BufferInfo>& buffer_info_arr,\n                                             const Integer& memory_pressure);\n\n/*!\n * \\brief The Greedy-by-Conflicts algorithm to plan memory\n *\n * This will perform a greedy algorithm in deciding the offsets\n * within provided Pools, using the number of liveness conflicts of the buffer.\n *\n * \\return A Map of BufferInfo objects and their associated PoolAllocation\n */\nMap<BufferInfo, PoolAllocation> GreedyByConflicts(const Array<BufferInfo>& buffer_info_arr,\n                                                  const Integer& memory_pressure);\n/*!\n *\\brief The Hill-Climb algoritm to plan memory\n *\n * This will perform an attempt to utilize probabalistic approach to memory\n * allocation. Typically better than greedy family, but quite slow due to large\n * number of iterations.\n *\n * \\return A Map of BufferInfo objects and their associated PoolAllocation\n */\nMap<BufferInfo, PoolAllocation> HillClimb(const Array<BufferInfo>& buffer_info_arr,\n                                          const Integer& memory_pressure);\n\n/*!\n * \\brief The Hill-Climb algorithm to plan memory\n *\n * This will perform a hill climbing algorithm in deciding the offsets\n * within provided Pools.\n *\n * \\return A Map of BufferInfo objects and their associated PoolAllocation\n */\nMap<BufferInfo, PoolAllocation> HillClimb(const Array<BufferInfo>& buffer_info_arr,\n                                          const Integer& memory_pressure);\n\n}  // namespace algo\n}  // namespace usmp\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_USMP_ALGORITHMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/usmp/analysis.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/usmp/analysis.h\n * \\brief The analysis passes for TIR-based Unified Static Memory Planner\n */\n\n#ifndef TVM_TIR_USMP_ANALYSIS_H_\n#define TVM_TIR_USMP_ANALYSIS_H_\n\n#include <tvm/tir/function.h>\n#include <tvm/tir/usmp/utils.h>\n\nnamespace tvm {\nnamespace tir {\nnamespace usmp {\n\n/*!\n * \\brief Extract BufferInfo objects from a TIR IRModule\n *\n * This pass would extract the buffer information of allocate nodes\n * including liveness conflict with other buffer info objects.\n *\n * \\return A Map of BufferInfo objects and their associated Stmts\n */\nBufferInfoAnalysis ExtractBufferInfo(const PrimFunc& main_func, const IRModule& mod);\n\n}  // namespace usmp\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_USMP_ANALYSIS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/usmp/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/usmp/transform.h\n * \\brief The transform passes for TIR-based Unified Static Memory Planner\n */\n\n#ifndef TVM_TIR_USMP_TRANSFORM_H_\n#define TVM_TIR_USMP_TRANSFORM_H_\n\n#include <tvm/tir/usmp/utils.h>\n\nnamespace tvm {\nnamespace tir {\nnamespace usmp {\nnamespace transform {\n\nusing Pass = tvm::transform::Pass;\n\n/*!\n * \\brief Convert the analyzed PoolAllocation to offsets from pool variables\n *\n * This pass would convert the main function to accept pool variables as an input\n * that get passed onto the operator PrimFuncs. Furthermore, the static allocations\n * will be converted to offsets within the pool variable.\n *\n * \\return the pass\n */\nTVM_DLL Pass ConvertPoolAllocationsToOffsets(const Map<tir::Stmt, PoolAllocation>& pool_allocations,\n                                             Bool emit_tvmscript_printable = Bool(false));\n\n/*!\n * \\brief Assign PoolInfo objects to tir.allocate nodes depending on the PrimFunc's target\n *\n * This pass would assign default PoolInfo objects to allocate nodes that are not otherwise\n * annotated, depending on pool info supplied for each target.\n *\n * \\return the pass\n */\nTVM_DLL Pass AssignPoolInfo();\n\n/*!\n * \\brief This pass creates Allocate nodes for I/O tensors\n *\n * If the user wants to place the I/O tensors in the workspace, this pass is required to be\n * run. In doing so, it will create Allocate nodes for I/O tensors to be planned, and be removed\n * from function arguments.\n *\n * \\return the pass\n */\nTVM_DLL Pass CreateAllocatesForIO();\n\n}  // namespace transform\n}  // namespace usmp\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_USMP_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/usmp/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/usmp/utils.h\n * \\brief Utilities for Unified Static Memory Planner\n */\n\n#ifndef TVM_TIR_USMP_UTILS_H_\n#define TVM_TIR_USMP_UTILS_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/ir/memory_pools.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/stmt.h>\n\nnamespace tvm {\n\n/*!\n * \\brief PassContext option to enable the USMP\n */\nconstexpr const char* kUSMPEnableOption = \"tir.usmp.enable\";\n/*!\n * \\brief PassContext option to select the memory planning algorithm in USMP\n */\nconstexpr const char* kUSMPAlgorithmOption = \"tir.usmp.algorithm\";\n/*!\n * \\brief PassContext option to enable placing I/O tensors in the workspace\n */\nconstexpr const char* kUSMPUseWorkspaceIO = \"tir.usmp.use_workspace_io\";\n/*!\n * \\brief PassContext option to specify a custom memory planning algorithm in USMP.\n * The algorithm should be provided as registered PackedFunc with the name tir.usmp.algorithm.NAME\n */\nconstexpr const char* kUSMPCustomAlgorithmOption = \"tir.usmp.custom_algorithm\";\n\nnamespace tir {\nnamespace usmp {\n/*!\n * \\brief A special kind to distinguish between I/O tensors to the model\n * and intermediate tensors of the model\n */\nenum class BufferInfoKind { kIntermediate = 0, kInput = 1, kOutput = 2 };\n\n/*!\n * \\brief Describes an abstract memory buffer that will get allocated inside a pool.\n * The actual memory buffer in represented by PoolAllocationNode after static memory planning.\n *\n * See also for relay-level counterparts:\n * relay::StorageToken (graph_plan_memory.cc)\n * relay::backend::StorageInfoNode (relay/backend/utils.h)\n * Region (python/tvm/relay/transform/memory_plan.py)\n */\nstruct BufferInfoNode : public Object {\n  /*! \\brief The name of the buffer var */\n  String name_hint;\n  /*! \\brief The size in terms of bytes */\n  Integer size_bytes;\n  /*! \\brief The pool candidates that this buffer can get pooled to*/\n  Array<PoolInfo> pool_candidates;\n  /*! \\brief The byte alignment required for buffers that will placed within the pool */\n  Integer alignment;\n  /*! \\brief The liveness conflicting other buffer info objects */\n  Array<ObjectRef> conflicts;\n  /*! \\brief Whether BufferInfo object retains info about IO tensors or intermediaries */\n  BufferInfoKind kind;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name_hint\", &name_hint);\n    v->Visit(\"size_bytes\", &size_bytes);\n    v->Visit(\"pool_candidates\", &pool_candidates);\n    v->Visit(\"alignment\", &alignment);\n    v->Visit(\"conflicts\", &conflicts);\n    v->Visit(\"kind\", &kind);\n  }\n\n  bool SEqualReduce(const BufferInfoNode* other, SEqualReducer equal) const {\n    return equal(name_hint, other->name_hint) && equal(size_bytes, other->size_bytes) &&\n           equal(pool_candidates, other->pool_candidates) && equal(alignment, other->alignment) &&\n           equal(conflicts, other->conflicts) && equal(kind, other->kind);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name_hint);\n    hash_reduce(size_bytes);\n    hash_reduce(alignment);\n    hash_reduce(conflicts);\n    hash_reduce(pool_candidates);\n    hash_reduce(kind);\n  }\n  /*!\n   * \\brief Set the liveness conflicts of this BufferInfo\n   *\n   * \\param conflicting_buffer_info_objs An array of BufferInfo that conflicts in liveness\n   */\n  TVM_DLL void SetConflicts(Array<ObjectRef> conflicting_buffer_info_objs);\n\n  static constexpr const char* _type_key = \"tir.usmp.BufferInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BufferInfoNode, Object);\n};\n\nclass BufferInfo : public ObjectRef {\n public:\n  TVM_DLL BufferInfo(String name_hint, Integer size_bytes, Array<PoolInfo> pool_candidates,\n                     Integer alignment = runtime::kDefaultWorkspaceAlignment,\n                     BufferInfoKind kind = BufferInfoKind::kIntermediate);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(BufferInfo, ObjectRef, BufferInfoNode);\n};\n\n/*!\n * \\brief This is a composite node that is produced by extract_buffer_info\n * analysis pass that contains useful global information that could be useful\n * for memory planning algorithms.\n */\nstruct BufferInfoAnalysisNode : public Object {\n  /*! \\brief The BufferInfo object and its associated TIR statement */\n  Map<BufferInfo, tir::Stmt> buffer_info_stmts;\n  /*! \\brief This represent maximum amount of memory being used at\n   * any point of time in the inference. This value is largely the\n   * best allocation an algorithm could achieve. Due to\n   * the complexities of conflict graphs, it would not be feasible\n   * to achieve this value, practically. However, it can be useful\n   * for iterative algorithms to know this value to define termination\n   * criteria.*/\n  Integer memory_pressure;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"buffer_info_stmts\", &buffer_info_stmts);\n    v->Visit(\"memory_pressure\", &memory_pressure);\n  }\n\n  bool SEqualReduce(const BufferInfoAnalysisNode* other, SEqualReducer equal) const {\n    return equal(buffer_info_stmts, other->buffer_info_stmts) &&\n           equal(memory_pressure, other->memory_pressure);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(buffer_info_stmts);\n    hash_reduce(memory_pressure);\n  }\n};\n\nclass BufferInfoAnalysis : public ObjectRef {\n public:\n  TVM_DLL BufferInfoAnalysis(Map<BufferInfo, tir::Stmt> buffer_info_stmts, Integer memory_pressure);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(BufferInfoAnalysis, ObjectRef, BufferInfoAnalysisNode);\n};\n\n/*!\n * \\brief The pool allocation produced after the USMP algorithm\n */\nstruct PoolAllocationNode : public Object {\n  /*! \\brief The assigned WorkspacePoolInfo or ConstantPoolInfo object */\n  PoolInfo pool_info;\n  /*! \\brief The byte offset within the pool*/\n  Integer byte_offset;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pool_info\", &pool_info);\n    v->Visit(\"byte_offset\", &byte_offset);\n  }\n\n  bool SEqualReduce(const PoolAllocationNode* other, SEqualReducer equal) const {\n    return equal(pool_info, other->pool_info) && equal(byte_offset, other->byte_offset);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(pool_info);\n    hash_reduce(byte_offset);\n  }\n\n  static constexpr const char* _type_key = \"tir.usmp.PoolAllocation\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PoolAllocationNode, Object);\n};\n\nclass PoolAllocation : public ObjectRef {\n public:\n  TVM_DLL PoolAllocation(PoolInfo pool_info, Integer byte_offset);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PoolAllocation, ObjectRef, PoolAllocationNode);\n};\n\n/*!\n * \\brief This object contains information post-allocation for PoolInfo objects\n */\nstruct AllocatedPoolInfoNode : public Object {\n  /*! \\brief The assigned PoolInfo object */\n  PoolInfo pool_info;\n  /*! \\brief The allocated size into this pool */\n  Integer allocated_size;\n  /*! \\brief An optional associated pool Var index of PrimFunc params*/\n  Optional<Integer> pool_var_idx;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"pool_info\", &pool_info);\n    v->Visit(\"allocated_size\", &allocated_size);\n    v->Visit(\"pool_var_idx\", &pool_var_idx);\n  }\n\n  bool SEqualReduce(const AllocatedPoolInfoNode* other, SEqualReducer equal) const {\n    return equal(pool_info, other->pool_info) && equal(allocated_size, other->allocated_size) &&\n           equal(pool_var_idx, other->pool_var_idx);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(pool_info);\n    hash_reduce(allocated_size);\n    hash_reduce(pool_var_idx);\n  }\n\n  static constexpr const char* _type_key = \"tir.usmp.AllocatedPoolInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllocatedPoolInfoNode, Object);\n};\n\nclass AllocatedPoolInfo : public ObjectRef {\n public:\n  TVM_DLL AllocatedPoolInfo(PoolInfo pool_info, Integer allocated_size,\n                            Integer pool_var_idx = Integer());\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(AllocatedPoolInfo, ObjectRef, AllocatedPoolInfoNode);\n};\n\n/*!\n * \\brief Convert the IR-bound BufferInfo map to an array of BufferInfo\n *\n * \\param buffer_info_map IR-bound BufferInfo map\n */\nArray<BufferInfo> ConvertToArrayOfBufferInfo(const Map<BufferInfo, Stmt>& buffer_info_map);\n\n/*!\n * \\brief Calculate workspace required to execute a IRModule with main expressed in TIR\n *\n * \\param mod the IRModule with TIR-based main function\n */\nInteger CalculateModuleWorkspaceSize(const IRModule& mod);\n\n/*!\n * \\brief The allocate node attribute to indicate candidate memory pools.\n * This needs to be kept in sync with CANDIDATE_MEMORY_POOL_ATTR in\n * python/tvm/tir/usmp/utils.py.\n */\nstatic constexpr const char* kPoolCandidatesAllocateAttr = \"candidate_memory_pools\";\n\n/*!\n * \\brief The allocate node attribute to indicate it is being used to hold\n * an input tensor, that needs to be initialized with.\n */\nstatic constexpr const char* kInputTensorAllocate = \"input_tensor\";\n\n/*!\n * \\brief The allocate node attribute to indicate it is being used to hold\n * an output tensor.\n */\nstatic constexpr const char* kOutputTensorAllocate = \"output_tensor\";\n\n/*!\n * \\brief Calculate the size of the extents in bytes\n *\n * \\param op the allocate node\n */\nInteger CalculateExtentsSize(const AllocateNode* op);\n\n/*!\n * \\brief Calculate the size of the extents in bytes\n *\n * \\param op the allocate const node\n */\nInteger CalculateExtentsSize(const AllocateConstNode* op);\n\n/*!\n * \\brief Joins the Stmt nodes with PoolAllocation objects\n *\n * \\param buffer_info_to_stmt the map of BufferInfo objects to Stmt nodes\n * \\param buffer_info_to_pool_allocation the map of BufferInfo objects to PoolAllocation objects\n */\nMap<Stmt, PoolAllocation> AssignStmtPoolAllocations(\n    const Map<BufferInfo, Stmt>& buffer_info_to_stmt,\n    const Map<BufferInfo, PoolAllocation>& buffer_info_to_pool_allocation);\n\n/*!\n * \\brief Obtains I/O tensor names to their PoolAllocation objects\n *\n * \\param buffer_info_to_pool_allocation the map of BufferInfo objects to PoolAllocation objects\n *\n * This function will obtain pool allocations for I/O tensors if that had been planned\n */\nMap<String, PoolAllocation> GetIOPoolAllocations(\n    const Map<BufferInfo, PoolAllocation>& buffer_info_to_pool_allocation);\n\n}  // namespace usmp\n}  // namespace tir\n\nnamespace attr {\n/*!\n * \\brief This is a BaseFunc attribute to indicate which input var represent\n * a PoolInfo Object in the form of a Map<Var, PoolInfo>.\n */\nstatic constexpr const char* kPoolArgs = \"pool_args\";\n\n/*!\n * \\brief This is a IRModule attribute that contains I/O Tensor names to pool\n * allocations.\n */\nstatic constexpr const char* kIOTensorPoolAllocations = \"io_tensor_pool_allocations\";\n\n}  // namespace attr\n\n}  // namespace tvm\n\n#endif  // TVM_TIR_USMP_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/tir/var.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/tir/var.h\n * \\brief Variables in the TIR.\n */\n#ifndef TVM_TIR_VAR_H_\n#define TVM_TIR_VAR_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/node/node.h>\n#include <tvm/runtime/data_type.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief A variable node in the IR.\n *\n * A variable is uniquely identified by its address.\n *\n * Each variable is only bound once in the following nodes:\n * - Allocate\n * - For\n * - Let\n * - LetStmt\n */\nclass VarNode : public PrimExprNode {\n public:\n  /*!\n   * \\brief The hint to the variable name.\n   * \\note Each variable is uniquely identified by its address.\n   */\n  String name_hint;\n  /*!\n   * \\brief type annotation of the variable.\n   *\n   * It is an optional field that provides a refined type of the variable than dtype.\n   *\n   * \\sa tvm/ir/type.h for discussion of relations between runtime::DataType and Type.\n   */\n  Type type_annotation;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dtype\", &dtype);\n    v->Visit(\"name\", &name_hint);\n    v->Visit(\"type_annotation\", &type_annotation);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const VarNode* other, SEqualReducer equal) const {\n    if (!equal(dtype, other->dtype)) return false;\n    if (!equal(type_annotation, other->type_annotation)) return false;\n    return equal.FreeVarEqualImpl(this, other);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dtype);\n    hash_reduce(type_annotation);\n    hash_reduce.FreeVarHashImpl(this);\n  }\n\n  static constexpr const char* _type_key = \"tir.Var\";\n  static constexpr const uint32_t _type_child_slots = 1;\n  TVM_DECLARE_BASE_OBJECT_INFO(VarNode, PrimExprNode);\n};\n\n/*! \\brief a named variable in TIR */\nclass Var : public PrimExpr {\n public:\n  explicit Var(ObjectPtr<Object> n) : PrimExpr(n) {}\n  /*!\n   * \\brief Constructor\n   * \\param name_hint variable name\n   * \\param dtype data type\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL explicit Var(String name_hint = \"v\", DataType dtype = DataType::Int(32),\n                       Span span = Span());\n  /*!\n   * \\brief Constructor which provides a more detailed type annotation.\n   * \\param name_hint variable name.\n   * \\param type_annotation The type annotation.\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL explicit Var(String name_hint, Type type_annotation, Span span = Span());\n  /*!\n   * \\brief Make a new copy of var with same type, append suffix\n   * \\param suffix The suffix to be appended.\n   * \\return the new Var copy\n   */\n  TVM_DLL Var copy_with_suffix(const String& suffix) const;\n  /*!\n   * \\brief Make a new copy of the variable with specified dtype\n   * \\param dtype The specified dtype\n   * \\return The new variable\n   */\n  TVM_DLL Var copy_with_dtype(DataType dtype) const;\n\n  /*!\n   * \\brief Get pointer to the internal value.\n   * \\return the corresponding Variable.\n   */\n  const VarNode* operator->() const { return get(); }\n  /*!\n   * \\brief Get pointer to the internal value.\n   * \\return the corresponding Variable.\n   */\n  const VarNode* get() const { return static_cast<const VarNode*>(data_.get()); }\n  /*! \\brief type indicate the container type */\n  using ContainerType = VarNode;\n};\n\n/*!\n * \\brief A variable node represent a tensor index size,\n * whose value must be non-negative.\n */\nclass SizeVarNode : public VarNode {\n public:\n  static constexpr const char* _type_key = \"tir.SizeVar\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SizeVarNode, VarNode);\n};\n\n/*! \\brief a named variable represents a tensor index size */\nclass SizeVar : public Var {\n public:\n  explicit SizeVar(ObjectPtr<Object> n) : Var(n) {}\n  /*!\n   * \\brief constructor\n   * \\param name_hint variable name\n   * \\param t data type\n   * \\param span The location of this object in the source code.\n   */\n  TVM_DLL explicit SizeVar(String name_hint = \"s\", DataType t = DataType::Int(32),\n                           Span span = Span());\n  /*!\n   * \\brief Get pointer to the internal value.\n   * \\return the corresponding Variable.\n   */\n  const SizeVarNode* operator->() const { return get(); }\n  /*!\n   * \\brief Get pointer to the internal value.\n   * \\return the corresponding Variable.\n   */\n  const SizeVarNode* get() const { return static_cast<const SizeVarNode*>(data_.get()); }\n  /*! \\brief type indicate the container type */\n  using ContainerType = SizeVarNode;\n};\n\nusing Region = Array<Range>;\n\n/*!\n * \\brief Type of iteration variable.\n *  Each IterVar have a specific type.\n *\n *  The type of iter var can be overriden via\n *  stage.iter_var_attrs given they are compatible.\n */\nenum IterVarType : int {\n  /*!\n   * \\brief Data parallel iteration.\n   *  This normally corresponds to axis of Tensor.\n   *  Allow all IterVar manipulations.\n   *\n   * \\note This does not mean the loop\n   *  have to be executed in parallel fashion.\n   */\n  kDataPar = 0,\n  /*!\n   * \\brief The IterVar itself is a thread-index\n   *  of a fixed thread launching group.\n   *  Note that this is already assumed to be parallelized.\n   *\n   *  Disallow: split/fuse/vectorize/parallel\n   */\n  kThreadIndex = 1,\n  /*!\n   * \\brief Communicative reduction.\n   *  Cannot be directly parallelized.\n   *\n   *  Disallow: parallel/vectorize\n   */\n  kCommReduce = 2,\n  /*!\n   * \\brief Serial loops with loop carry dependency,\n   *  the iteration must execute in order.\n   *  Cannot be re-ordered.\n   *\n   *  Disallow: reorder/parallel/vectorize\n   */\n  kOrdered = 3,\n  /*!\n   * \\brief IterVar is opaque,\n   *\n   *  May not corresponds to any generated loop\n   *  Disallow all IterVar manipulations and compute_at\n   *\n   * \\note This is usually used to implement composite op\n   *  or external op, where the\n   */\n  kOpaque = 4,\n  // The following are possible additional\n  // types that are provided during schedule\n  /*!\n   * \\brief The execution is unrolled.\n   */\n  kUnrolled = 5,\n  /*!\n   * \\brief The loop is vectorized.\n   */\n  kVectorized = 6,\n  /*!\n   * \\brief The loop is parallelized.\n   */\n  kParallelized = 7,\n  /*!\n   * \\brief Marks boundary of tensorization intrinsic.\n   */\n  kTensorized = 8\n};\n\n/*!\n * \\brief An iteration variable representing an iteration\n *  over a one dimensional interval.\n *\n *  The dtype of the extent of the `dom` of the IterVar must match the dtype of the internal Var.\n */\nclass IterVarNode : public Object {\n public:\n  /*!\n   * \\brief the domain of iteration, if known, can be None\n   *  For the intermediate schedule node, before schedule.\n   */\n  Range dom;\n  /*! \\brief The looping variable */\n  Var var;\n  /*! \\brief The type of the IterVar */\n  IterVarType iter_type;\n  /*!\n   * \\brief additional tag on the iteration variable,\n   *  set this if this is binded already to a known thread tag.\n   */\n  String thread_tag;\n  /*!\n   * \\brief Span that points to the original source code.\n   *        Reserved debug information.\n   */\n  mutable Span span;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"dom\", &dom);\n    v->Visit(\"var\", &var);\n    v->Visit(\"iter_type\", &iter_type);\n    v->Visit(\"thread_tag\", &thread_tag);\n    v->Visit(\"span\", &span);\n  }\n\n  bool SEqualReduce(const IterVarNode* other, SEqualReducer equal) const {\n    return equal(dom, other->dom) && equal.DefEqual(var, other->var) &&\n           equal(iter_type, other->iter_type) && equal(thread_tag, other->thread_tag);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(dom);\n    hash_reduce.DefHash(var);\n    hash_reduce(iter_type);\n    hash_reduce(thread_tag);\n  }\n\n  static constexpr const char* _type_key = \"tir.IterVar\";\n  static constexpr const bool _type_has_method_sequal_reduce = true;\n  static constexpr const bool _type_has_method_shash_reduce = true;\n  TVM_DECLARE_FINAL_OBJECT_INFO(IterVarNode, Object);\n};\n\n/*!\n * \\brief Iteration Variable,\n *  represents an iteration over an integer interval.\n *\n *  The dtype of the extent of the `dom` of the IterVar must match the dtype of the internal Var.\n */\nclass IterVar : public ObjectRef {\n public:\n  TVM_DLL IterVar(Range dom, Var var, IterVarType iter_type, String thread_tag = \"\",\n                  Span span = Span());\n  /*!\n   * \\return the corresponding var in the IterVar.\n   */\n  inline operator PrimExpr() const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(IterVar, ObjectRef, IterVarNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IterVarNode);\n};\n\n// inline implementations\ninline IterVar::operator PrimExpr() const { return (*this)->var; }\n\ninline const char* IterVarType2String(IterVarType t) {\n  switch (t) {\n    case kDataPar:\n      return \"DataPar\";\n    case kThreadIndex:\n      return \"ThreadIndex\";\n    case kCommReduce:\n      return \"CommReduce\";\n    case kOrdered:\n      return \"Ordered\";\n    case kOpaque:\n      return \"Opaque\";\n    case kUnrolled:\n      return \"Unrolled\";\n    case kVectorized:\n      return \"Vectorized\";\n    case kParallelized:\n      return \"Parallelized\";\n    case kTensorized:\n      return \"Tensorized\";\n  }\n  return \"Unknown\";\n}\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_VAR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/broadcast.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Broadcast op constructions\n * \\file topi/broadcast.h\n */\n#ifndef TVM_TOPI_BROADCAST_H_\n#define TVM_TOPI_BROADCAST_H_\n\n#include <tvm/topi/detail/broadcast.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <string>\n\nnamespace tvm {\nnamespace topi {\n\n/*!\n * \\brief Creates an operation that broadcasts a tensor into a compatible\n * shape according to numpy's rules\n *\n * \\param t The input tensor\n * \\param output_shape The target output shape, must be compatible\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is a broadcast operation\n */\ninline tvm::te::Tensor broadcast_to(const tvm::te::Tensor& t,\n                                    const tvm::Array<tvm::PrimExpr>& output_shape,\n                                    std::string name = \"T_broadcast_to\",\n                                    std::string tag = kBroadcast) {\n  ICHECK_GE(output_shape.size(), t->shape.size())\n      << \"Not a broadcast, output dimensionality smaller than input.\\noutput: \" << output_shape\n      << \"\\nvs\\ninput: \" << t;\n  auto bh = detail::BroadcastShape(output_shape, t->shape);\n  ICHECK_EQ(output_shape.size(), bh.common_shape.size());\n  Array<PrimExpr> oshape;\n  for (size_t i = 0; i < output_shape.size(); ++i) {\n    if (output_shape[i].as<tir::IntImmNode>() == nullptr) {\n      oshape.push_back(output_shape[i]);\n    } else {\n      ICHECK(topi::detail::EqualCheck(output_shape[i], bh.common_shape[i]));\n      oshape.push_back(bh.common_shape[i]);\n    }\n  }\n  auto l = [&](tvm::Array<tvm::tir::Var> ovars) {\n    return t(detail::InputIndexFromBroadcast(ovars, t, bh.vars2, bh.all_vars));\n  };\n  return tvm::te::compute(oshape, l, name, tag);\n}\n\n#define TOPI_DEFINE_BCAST_OP(Name, ComputeRule)                                                   \\\n  inline tvm::PrimExpr Name(const tvm::PrimExpr& a, const tvm::PrimExpr& b) { ComputeRule; }      \\\n  inline tvm::te::Tensor Name(const tvm::te::Tensor& A, const tvm::te::Tensor& B,                 \\\n                              std::string name = \"T_\" #Name, std::string tag = kBroadcast) {      \\\n    auto l = [](tvm::PrimExpr a, tvm::PrimExpr b) { ComputeRule; };                               \\\n    return detail::WithBroadcast(l, A, B, name, tag);                                             \\\n  }                                                                                               \\\n  inline tvm::te::Tensor Name(const tvm::te::Tensor& A, const tvm::PrimExpr& B,                   \\\n                              std::string name = \"T_\" #Name, std::string tag = kElementWise) {    \\\n    auto l = [](tvm::PrimExpr a, tvm::PrimExpr b) { ComputeRule; };                               \\\n    return tvm::te::compute(                                                                      \\\n        A->shape, [&](const ::tvm::Array<::tvm::tir::Var>& i) { return l(A(i), B); }, name, tag); \\\n  }                                                                                               \\\n  inline tvm::te::Tensor Name(const tvm::PrimExpr& A, const tvm::te::Tensor& B,                   \\\n                              std::string name = \"T_\" #Name, std::string tag = kElementWise) {    \\\n    auto l = [&](tvm::PrimExpr a, tvm::PrimExpr b) { ComputeRule; };                              \\\n    return tvm::te::compute(                                                                      \\\n        B->shape, [&](const ::tvm::Array<::tvm::tir::Var>& i) { return l(A, B(i)); }, name, tag); \\\n  }\n\n#define TOPI_DEFINE_OP_OVERLOAD(Name, OpName)                                       \\\n  inline tvm::te::Tensor Name(const tvm::te::Tensor& A, const tvm::te::Tensor& B) { \\\n    return topi::OpName(A, B);                                                      \\\n  }                                                                                 \\\n  inline tvm::te::Tensor Name(const tvm::PrimExpr& A, const tvm::te::Tensor& B) {   \\\n    return topi::OpName(A, B);                                                      \\\n  }                                                                                 \\\n  inline tvm::te::Tensor Name(const tvm::te::Tensor& A, const tvm::PrimExpr& B) {   \\\n    return topi::OpName(A, B);                                                      \\\n  }\n\n/*!\n * \\fn logical_and\n * \\brief Compute A && B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(logical_and, { return a && b; });\nTOPI_DEFINE_OP_OVERLOAD(operator&&, logical_and);\n\n/*!\n * \\fn logical_or\n * \\brief Compute A || B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(logical_or, { return a || b; });\nTOPI_DEFINE_OP_OVERLOAD(operator||, logical_or);\n\n/*!\n * \\fn logical_xor\n * \\brief Compute A ^ B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(logical_xor, { return a ^ b; });\n\n/*!\n * \\fn bitwise_and\n * \\brief Compute A & B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(bitwise_and, { return a & b; });\nTOPI_DEFINE_OP_OVERLOAD(operator&, bitwise_and);\n\n/*!\n * \\fn bitwise_or\n * \\brief Compute A | B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(bitwise_or, { return a | b; });\nTOPI_DEFINE_OP_OVERLOAD(operator|, bitwise_or);\n\n/*!\n * \\fn bitwise_xor\n * \\brief Compute A ^ B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(bitwise_xor, { return a ^ b; });\nTOPI_DEFINE_OP_OVERLOAD(operator^, bitwise_xor);\n\n/*!\n * \\fn add\n * \\brief Compute A + B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(add, { return a + b; });\nTOPI_DEFINE_OP_OVERLOAD(operator+, add);\n\n/*!\n * \\fn subtract\n * \\brief Compute A - B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(subtract, { return a - b; });\nTOPI_DEFINE_OP_OVERLOAD(operator-, subtract);\n\n/*!\n * \\fn multiply\n * \\brief Compute A * B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(multiply, { return a * b; });\nTOPI_DEFINE_OP_OVERLOAD(operator*, multiply);\n\n/*!\n * \\fn divide\n * \\brief Compute A / B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(divide, { return div(a, b); });\n\n/*!\n * \\fn floor divide\n * \\brief Compute floor(A / B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(floor_divide, {\n  if (a.dtype().is_int() || a.dtype().is_uint()) {\n    return floordiv(a, b);\n  } else {\n    return floor(div(a, b));\n  }\n});\n\n/*!\n * \\fn trunc divide\n * \\brief Compute trunc(A / B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(trunc_divide, {\n  if (a.dtype().is_int() || a.dtype().is_uint()) {\n    return truncdiv(a, b);\n  } else {\n    return trunc(div(a, b));\n  }\n});\n\n/*!\n * \\fn mod\n * \\brief Compute A % B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(mod, { return truncmod(a, b); });\n\n/*!\n * \\fn floor mod\n * \\brief Compute A - floor_div(A, B) * B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(floor_mod, {\n  if (a.dtype().is_int() || a.dtype().is_uint()) {\n    return floormod(a, b);\n  } else {\n    return a - floor_divide(a, b) * b;\n  }\n});\n\n/*!\n * \\fn trunc mod\n * \\brief Compute A - trunc_div(A, B) * B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(trunc_mod, {\n  if (a.dtype().is_int() || a.dtype().is_uint()) {\n    return truncmod(a, b);\n  } else {\n    return a - trunc_divide(a, b) * b;\n  }\n});\n\n/*!\n * \\fn maximum\n * \\brief Compute maximum(A, B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(maximum, { return tvm::max(a, b); });\n\n/*!\n * \\fn minimum\n * \\brief Compute minimum(A, B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(minimum, { return tvm::min(a, b); });\n\n/*!\n * \\fn power\n * \\brief Compute power(A, B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(power, { return tvm::pow(a, b); });\n\n/*!\n * \\fn left_shift\n * \\brief Compute A << B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(left_shift, { return a << b; });\nTOPI_DEFINE_OP_OVERLOAD(operator<<, left_shift);\n\n/*!\n * \\fn right_shift\n * \\brief Compute A >> B with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(right_shift, { return a >> b; });\nTOPI_DEFINE_OP_OVERLOAD(operator>>, right_shift);\n\n/*!\n * \\fn greater\n * \\brief Compute (A > B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(greater, { return (a > b); });\n\n/*!\n * \\fn less\n * \\brief Compute (A < B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(less, { return (a < b); });\n\n/*!\n * \\fn equal\n * \\brief Compute (A == B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(equal, { return (a == b); });\n\n/*!\n * \\fn not_equal\n * \\brief Compute (A != B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(not_equal, { return (a != b); });\n\n/*!\n * \\fn greater_equal\n * \\brief Compute (A >= B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(greater_equal, { return (a >= b); });\n\n/*!\n * \\fn less_equal\n * \\brief Compute (A <= B) with auto-broadcasting.\n *\n * \\param A The first tensor, or Expr\n * \\param B The second tensor, or Expr\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The result.\n */\nTOPI_DEFINE_BCAST_OP(less_equal, { return (a <= b); });\n\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_BROADCAST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/contrib/cublas.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief External function interface to cuBLAS libraries\n * \\file cublas.h\n */\n#ifndef TVM_TOPI_CONTRIB_CUBLAS_H_\n#define TVM_TOPI_CONTRIB_CUBLAS_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/extern.h>\n\nnamespace tvm {\nnamespace topi {\nnamespace contrib {\n\nusing namespace tvm::te;\nusing namespace topi::detail;\n/*!\n * \\brief Create an op that multiplies lhs and rhs with cuBLAS\n *\n * \\param lhs The left matrix operand\n * \\param rhs The right matrix operand\n * \\param transa Whether to transpose lhs\n * \\param transb Whether to transpose rhs\n *\n * \\return The output tensor\n */\ninline Tensor cublas_matmul(const Tensor& lhs, const Tensor& rhs, bool transa, bool transb) {\n  auto n = transa ? lhs->shape[1] : lhs->shape[0];\n  auto m = transb ? rhs->shape[0] : rhs->shape[1];\n\n  return make_extern(\n      {{n, m}}, {lhs->dtype}, {lhs, rhs},\n      [&](Array<Buffer> ins, Array<Buffer> outs) {\n        return call_packed({StringImm(\"tvm.contrib.cublas.matmul\"), pack_buffer(ins[0]),\n                            pack_buffer(ins[1]), pack_buffer(outs[0]), transa, transb});\n      },\n      \"C\", \"\", {})[0];\n}\n\n/*!\n * \\brief Create an op that multiplies batch matrices\n *        lhs and rhs with cuBLAS\n *\n * \\param lhs The left matrix operand\n * \\param rhs The right matrix operand\n * \\param transa Whether to transpose lhs\n * \\param transb Whether to transpose rhs\n *\n * \\return The output tensor\n */\ninline Tensor cublas_batch_matmul(const Tensor& lhs, const Tensor& rhs, bool transa, bool transb) {\n  auto b = lhs->shape[0];\n  auto n = transa ? lhs->shape[2] : lhs->shape[1];\n  auto m = transb ? rhs->shape[1] : rhs->shape[2];\n\n  return make_extern(\n      {{b, n, m}}, {lhs->dtype}, {lhs, rhs},\n      [&](Array<Buffer> ins, Array<Buffer> outs) {\n        return call_packed({StringImm(\"tvm.contrib.cublas.batch_matmul\"), pack_buffer(ins[0]),\n                            pack_buffer(ins[1]), pack_buffer(outs[0]), transa, transb});\n      },\n      \"C\", \"\", {})[0];\n}\n\n}  // namespace contrib\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_CONTRIB_CUBLAS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/contrib/rocblas.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief External function interface to rocBLAS libraries\n * \\file tags.h\n */\n#ifndef TVM_TOPI_CONTRIB_ROCBLAS_H_\n#define TVM_TOPI_CONTRIB_ROCBLAS_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/extern.h>\n\nnamespace tvm {\nnamespace topi {\nnamespace contrib {\n\nusing namespace tvm::te;\n/*!\n * \\brief Create an op that multiplies lhs and rhs with rocBLAS\n *\n * \\param lhs The left matrix operand\n * \\param rhs The right matrix operand\n * \\param transa Whether to transpose lhs\n * \\param transb Whether to transpose rhs\n *\n * \\return The output tensor\n */\ninline Tensor rocblas_matmul(const Tensor& lhs, const Tensor& rhs, bool transa, bool transb) {\n  auto n = transa ? lhs->shape[1] : lhs->shape[0];\n  auto m = transb ? rhs->shape[0] : rhs->shape[1];\n\n  return make_extern(\n      {{n, m}}, {lhs->dtype}, {lhs, rhs},\n      [&](Array<Buffer> ins, Array<Buffer> outs) {\n        return call_packed({StringImm(\"tvm.contrib.rocblas.matmul\"), pack_buffer(ins[0]),\n                            pack_buffer(ins[1]), pack_buffer(outs[0]), transa, transb});\n      },\n      \"C\", \"\", {})[0];\n}\n/*!\n * \\brief Create an op that batch multiplies lhs and rhs with rocBLAS\n *\n * \\param lhs The left matrix operand  e.g. (batch_size, M, K)\n * \\param rhs The right matrix operand e.g. (batch_size, K, N)\n * \\param transa Whether to transpose lhs\n * \\param transb Whether to transpose rhs\n *\n * \\return The output tensor\n */\ninline Tensor rocblas_batch_matmul(const Tensor& lhs, const Tensor& rhs, bool transa, bool transb) {\n  auto batch_size = lhs->shape[0];\n  auto n = transa ? lhs->shape[2] : lhs->shape[1];\n  auto m = transb ? rhs->shape[1] : rhs->shape[2];\n\n  return make_extern(\n      {{batch_size, n, m}}, {lhs->dtype}, {lhs, rhs},\n      [&](Array<Buffer> ins, Array<Buffer> outs) {\n        return call_packed({StringImm(\"tvm.contrib.rocblas.batch_matmul\"), pack_buffer(ins[0]),\n                            pack_buffer(ins[1]), pack_buffer(outs[0]), transa, transb});\n      },\n      \"C\", \"\", {})[0];\n}\n\n}  // namespace contrib\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_CONTRIB_ROCBLAS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/cuda/dense.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda/dense.h\n * \\brief CUDA schedule for dense operation\n */\n#ifndef TVM_TOPI_CUDA_DENSE_H_\n#define TVM_TOPI_CUDA_DENSE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/contrib/cublas.h>\n#include <tvm/topi/detail/array_utils.h>\n#include <tvm/topi/generic/extern.h>\n#include <tvm/topi/nn/dense.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace cuda {\n/*!\n * \\brief Implementation of dense for CUDA backend\n *\n * \\param target The target device\n * \\param data Tensor with shape [batch, in_dim]\n * \\param weight Tensor with shape [out_dim, in_dim]\n * \\param bias Tensor with shape [out_dim]. Optional; to omit bias, pass Tensor()\n * \\param out_dtype Output data type. Used for mixed precision.\n *\n * \\return Tensor with shape [batch, out_dim]\n */\ninline tvm::te::Tensor dense_cuda(const Target& target, const tvm::te::Tensor& data,\n                                  const tvm::te::Tensor& weight, const tvm::te::Tensor& bias,\n                                  const DataType& out_dtype) {\n  ICHECK_EQ(data->shape.size(), 2) << \"dense requires 2-D data\";\n  ICHECK_EQ(weight->shape.size(), 2) << \"dense requires 2-D weight\";\n  if (bias.defined()) {\n    ICHECK_EQ(bias->shape.size(), 1) << \"dense requires 1-D bias\";\n  }\n\n  auto batch = data->shape[0];\n  auto in_dim = data->shape[1];\n  auto out_dim = weight->shape[0];\n\n  if (target->GetLibs().count(\"cublas\")) {\n    ICHECK_EQ(data->dtype, out_dtype) << \"Mixed precision not supported.\";\n    auto mm = topi::contrib::cublas_matmul(data, weight, false, true);\n    if (bias.defined()) {\n      mm = tvm::te::compute(\n          {batch, out_dim}, [&](Var i, Var j) { return mm(i, j) + bias(j); }, \"tensor\", kBroadcast);\n    }\n\n    return mm;\n  } else {\n    return topi::nn::dense(data, weight, bias, out_dtype);\n  }\n}\n\n/*!\n * \\brief Create a CUDA schedule for dense\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_dense(const Target& target, const Array<Tensor>& outs) {\n  if (target->kind->name == \"cuda\" && target->GetLibs().count(\"cublas\")) {\n    return topi::generic::schedule_extern(target, outs);\n  }\n\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto _schedule = [&](const Tensor& dense) {\n    auto num_thread = 64;\n    auto k = dense->op.as<ComputeOpNode>()->reduce_axis[0];\n    IterVar ko, kf;\n    s[dense].split(k, num_thread, &ko, &kf);\n    auto dense_f = s.rfactor(dense, kf)[0];\n\n    Tensor out;\n    if (detail::contains(s->outputs, dense->op)) {\n      out = dense;\n    } else {\n      out = outs[0]->op.output(0);\n      s[dense].compute_at(s[out], s[out]->op.as<ComputeOpNode>()->axis[1]);\n    }\n    s[out].bind(s[out]->op.as<ComputeOpNode>()->axis[0],\n                tvm::te::thread_axis(Range(), \"blockIdx.y\"));\n    s[out].bind(s[out]->op.as<ComputeOpNode>()->axis[1],\n                tvm::te::thread_axis(Range(), \"blockIdx.x\"));\n\n    auto tx = s[dense]->op.as<ComputeOpNode>()->reduce_axis[0];\n    auto thread_x = tvm::te::thread_axis(Range(), \"threadIdx.x\");\n    s[dense].bind(tx, thread_x);\n    s[dense_f].compute_at(s[dense], tx);\n    s[dense].set_store_predicate(static_cast<PrimExpr>(thread_x) == 0);\n    s[out].set_store_predicate(static_cast<PrimExpr>(thread_x) == 0);\n  };\n\n  std::function<void(Operation)> traverse;\n  traverse = [&](const Operation& op) {\n    // Inline all one-to-one-mapping operators except the last stage (output)\n    if (is_broadcast(op->tag)) {\n      if (!detail::contains(s->outputs, op)) {\n        s[op].compute_inline();\n      }\n      for (auto tensor : op->InputTensors()) {\n        if (tensor->op->InputTensors().size() > 0) {\n          traverse(tensor->op);\n        }\n      }\n    } else if (op->tag == \"dense\") {\n      // If tag starts with global_pool\n      auto dense = op.output(0);\n      _schedule(dense);\n    } else {\n      LOG(ERROR) << \"Unsupported operator \" << op->tag;\n    }\n  };\n\n  traverse(outs[0]->op);\n  return s;\n}\n\n}  // namespace cuda\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_CUDA_DENSE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/cuda/injective.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda/injective.h\n * \\brief CUDA schedule for injective operations\n */\n#ifndef TVM_TOPI_CUDA_INJECTIVE_H_\n#define TVM_TOPI_CUDA_INJECTIVE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace cuda {\n\n/*!\n * \\brief Updates an existing schedule for the given injective ops.\n *\n * \\param sch The schedule to update.\n * \\param out The tensor representing the injective op.\n *\n * \\return The updated schedule.\n */\ninline Schedule schedule_injective_from_existing(Schedule sch, const Tensor& out) {\n  auto fused = detail::Fuse(sch[out], sch[out]->op.as<ComputeOpNode>()->axis);\n  auto target = Target::Current(false);\n  int num_thread = target->GetAttr<Integer>(\"max_num_threads\").value().IntValue();\n  IterVar bx, tx;\n  sch[out].split(fused, num_thread, &bx, &tx);\n  sch[out].bind(bx, thread_axis(Range(), \"blockIdx.x\"));\n  sch[out].bind(tx, thread_axis(Range(), \"threadIdx.x\"));\n  return sch;\n}\n\n/*!\n * \\brief Create a CUDA schedule for the given output tensors.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_injective(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  tvm::te::AutoInlineInjective(s);\n  for (auto out : outs) {\n    schedule_injective_from_existing(s, out);\n  }\n  return s;\n}\n\n}  // namespace cuda\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_CUDA_INJECTIVE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/cuda/pooling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda/pooling.h\n * \\brief CUDA schedule for pooling operations\n */\n#ifndef TVM_TOPI_CUDA_POOLING_H_\n#define TVM_TOPI_CUDA_POOLING_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/array_utils.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace cuda {\n\n/*!\n * \\brief Create a CUDA schedule for pool\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_pool(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto _schedule = [&](const Tensor& padded_input, const Tensor& pool) {\n    if (padded_input->op->IsInstance<ComputeOpNode>()) {\n      s[padded_input].compute_inline();\n    }\n    int num_thread = target->GetAttr<Integer>(\"max_num_threads\").value().IntValue();\n    Tensor out;\n    Tensor OL;\n    if (detail::contains(s->outputs, pool->op)) {\n      out = pool;\n      OL = s.cache_write(pool, \"local\");\n    } else {\n      out = outs[0]->op.output(0);\n      s[pool].set_scope(\"local\");\n    }\n    auto fused = detail::Fuse(s[out], s[out]->op.as<ComputeOpNode>()->axis);\n    IterVar bx, tx;\n    s[out].split(fused, num_thread, &bx, &tx);\n    s[out].bind(bx, tvm::te::thread_axis(Range(), \"blockIdx.x\"));\n    s[out].bind(tx, tvm::te::thread_axis(Range(), \"threadIdx.x\"));\n    if (detail::contains(s->outputs, pool->op)) {\n      s[OL].compute_at(s[out], tx);\n    } else {\n      s[pool].compute_at(s[out], tx);\n    }\n  };\n\n  std::function<void(Operation)> traverse;\n  traverse = [&](const Operation& op) {\n    // Inline all one-to-one-mapping operators except the last stage (output)\n    if (is_broadcast(op->tag)) {\n      if (!detail::contains(s->outputs, op)) {\n        s[op].compute_inline();\n      }\n      for (auto tensor : op->InputTensors()) {\n        if (tensor->op->InputTensors().size() > 0) {\n          traverse(tensor->op);\n        }\n      }\n    } else if (op->tag.rfind(\"pool\", 0) == 0) {\n      // If tag starts with pool\n      auto padded_input = op->InputTensors()[0];\n      auto pool = op.output(0);\n      _schedule(padded_input, pool);\n    } else {\n      LOG(ERROR) << \"Unsupported operator \" << op->tag;\n    }\n  };\n\n  traverse(outs[0]->op);\n  return s;\n}\n\n/*!\n * \\brief Create a CUDA schedule for global_pool\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_global_pool(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto _schedule = [&](const Tensor& pool) {\n    auto num_thread = 8;\n    auto block_x = tvm::te::thread_axis(Range(), \"blockIdx.x\");\n    auto block_y = tvm::te::thread_axis(Range(), \"blockIdx.y\");\n    auto thread_x = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.x\");\n    auto thread_y = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.y\");\n    Tensor out;\n    Tensor OL;\n    if (detail::contains(s->outputs, pool->op)) {\n      out = pool;\n      OL = s.cache_write(pool, \"local\");\n    } else {\n      out = outs[0]->op.output(0);\n      s[pool].set_scope(\"local\");\n    }\n\n    auto i = s[out]->op.as<ComputeOpNode>()->axis[0];\n    auto c = s[out]->op.as<ComputeOpNode>()->axis[1];\n\n    IterVar by, ty;\n    s[out].split(i, num_thread, &by, &ty);\n    IterVar bx, tx;\n    s[out].split(c, num_thread, &bx, &tx);\n    s[out].reorder({by, bx, ty, tx});\n    s[out].bind(ty, thread_y);\n    s[out].bind(tx, thread_x);\n    s[out].bind(by, block_y);\n    s[out].bind(bx, block_x);\n\n    if (detail::contains(s->outputs, pool->op)) {\n      s[OL].compute_at(s[out], tx);\n    } else {\n      s[pool].compute_at(s[out], tx);\n    }\n  };\n\n  std::function<void(Operation)> traverse;\n  traverse = [&](const Operation& op) {\n    // Inline all one-to-one-mapping operators except the last stage (output)\n    if (is_broadcast(op->tag)) {\n      if (!detail::contains(s->outputs, op)) {\n        s[op].compute_inline();\n      }\n      for (auto tensor : op->InputTensors()) {\n        if (tensor->op->InputTensors().size() > 0) {\n          traverse(tensor->op);\n        }\n      }\n    } else if (op->tag.rfind(\"global_pool\", 0) == 0) {\n      // If tag starts with global_pool\n      auto pool = op.output(0);\n      _schedule(pool);\n    } else {\n      LOG(ERROR) << \"Unsupported operator \" << op->tag;\n    }\n  };\n\n  traverse(outs[0]->op);\n  return s;\n}\n\n}  // namespace cuda\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_CUDA_POOLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/cuda/reduction.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda/reduction.h\n * \\brief CUDA schedule for reduction operations\n */\n#ifndef TVM_TOPI_CUDA_REDUCTION_H_\n#define TVM_TOPI_CUDA_REDUCTION_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace cuda {\n/*!\n * \\brief Schedule a given reduce operation.\n *\n * \\param target The target to generate a schedule for.\n * \\param op The operation representing the injective operation.\n * \\param sch The schedule to apply this scheduling to\n * \\param is_idx_reduce Pass true to schedule a reduce op that returns\n * an index, such as argmax or argmin.\n *\n * \\return The schedule given by sch\n */\nSchedule ScheduleReduce(const Target& target, Operation op, Schedule sch,\n                        bool is_idx_reduce = false) {\n  Tensor data_out;\n  Tensor data_in;\n\n  if (!is_idx_reduce) {\n    data_in = op->InputTensors()[0];\n    data_out = op.output(0);\n  } else {\n    data_out = op->InputTensors()[0];\n  }\n\n  auto out_stage = sch[data_out];\n  ICHECK_GT(out_stage->op.as<ComputeOpNode>()->reduce_axis.size(), 0)\n      << \"reduce_axis must be greater than zero\";\n\n  bool all_reduce;\n  int num_thread;\n  IterVar block_x, thread_x, thread_y;\n\n  if (out_stage->op.as<ComputeOpNode>()->axis.size() > 0) {\n    all_reduce = false;\n    num_thread = 32;\n    if (target->kind->name == \"opencl\" || target->kind->name == \"metal\") {\n      // Without this, CL_INVALID_WORK_GROUP_SIZE occurs with python tests.\n      // Don't know why.\n      num_thread = 16;\n    }\n    block_x = tvm::te::thread_axis(Range(), \"blockIdx.x\");\n    thread_x = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.x\");\n    thread_y = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.y\");\n  } else {\n    all_reduce = true;\n    num_thread = target->GetAttr<Integer>(\"max_num_threads\").value().IntValue();\n    thread_x = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.x\");\n  }\n\n  auto fused_reduce = detail::Fuse(out_stage, out_stage->op.as<ComputeOpNode>()->reduce_axis);\n\n  IterVar ko, ki;\n  out_stage.split(fused_reduce, num_thread, &ko, &ki);\n  auto data_out_rf = sch.rfactor(data_out, ki)[0];\n  auto tx = out_stage->op.as<ComputeOpNode>()->reduce_axis[0];\n  out_stage.bind(tx, thread_x);\n  sch[data_out_rf].compute_at(out_stage, tx);\n\n  Tensor real_output;\n  Tensor temp_idx_input, temp_val_input;\n  if (is_idx_reduce) {\n    real_output = op.output(0);\n    temp_idx_input = data_out->op.output(0);\n    temp_val_input = data_out->op.output(1);\n  } else {\n    real_output = data_out;\n  }\n\n  auto stage_real = sch[real_output];\n  if (!all_reduce) {\n    // Fuse and split the axis\n    auto fused_outer = detail::Fuse(stage_real, stage_real->op.as<ComputeOpNode>()->axis);\n    IterVar bx, outer_in;\n    stage_real.split(fused_outer, num_thread, &bx, &outer_in);\n\n    // Bind the axes to threads and blocks\n    stage_real.bind(outer_in, thread_y);\n    stage_real.bind(bx, block_x);\n    if (is_idx_reduce) {\n      sch[temp_idx_input].compute_at(stage_real, outer_in);\n      sch[temp_val_input].compute_at(stage_real, outer_in);\n    }\n  } else {\n    if (is_idx_reduce) {\n      sch[temp_idx_input].compute_at(stage_real, stage_real->op.as<ComputeOpNode>()->axis[0]);\n      sch[temp_val_input].compute_at(stage_real, stage_real->op.as<ComputeOpNode>()->axis[0]);\n    }\n  }\n\n  stage_real.set_store_predicate(static_cast<PrimExpr>(thread_x) == 0);\n  return sch;\n}\n\n/*!\n * \\brief Recursively traverse operator inputs, setting injective inputs\n * to be computed inline.\n *\n * \\param s The schedule we are building\n * \\param op The current op in the traversal\n */\nvoid TraverseBeforeReduce(Schedule s, Operation op) {\n  if (op->IsInstance<PlaceholderOpNode>()) {\n    return;\n  } else if (is_injective(op->tag)) {\n    s[op].compute_inline();\n    for (auto tensor : op->InputTensors()) {\n      TraverseBeforeReduce(s, tensor->op);\n    }\n  } else {\n    LOG(ERROR) << \"Unsupported operator \" << op->tag;\n  }\n}\n\n/*!\n * \\brief Schedule a reduce op, then invoke TraverseBeforeReduce on each\n * of the op's inputs.\n *\n * \\param target The target to generate a schedule for.\n * \\param s The schedule we are building\n * \\param op The reduce op\n */\nvoid TraverseAfterReduce(const Target& target, Schedule s, Operation op) {\n  if (is_broadcast(op->tag)) {\n    LOG(ERROR) << \"Elementwise op after reduce is not yet supported\";\n  } else if (op->tag == kCommReduce) {\n    ScheduleReduce(target, op, s, false);\n    for (auto tensor : op->InputTensors()) {\n      TraverseBeforeReduce(s, tensor->op);\n    }\n  } else if (op->tag == kCommReduceIdx) {\n    ScheduleReduce(target, op, s, true);\n    for (auto tensor : op->InputTensors()[0]->op->InputTensors()) {\n      TraverseBeforeReduce(s, tensor->op);\n    }\n  } else {\n    LOG(ERROR) << \"Unsupported operator \" << op->tag;\n  }\n}\n\n/*!\n * \\brief Create a CUDA schedule for a reduce operation.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\nSchedule schedule_reduce(const Target& target, Array<Tensor> outs) {\n  ICHECK_EQ(outs.size(), 1) << \"outs must have size 1\";\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  TraverseAfterReduce(target, s, outs[0]->op);\n  return s;\n}\n\n}  // namespace cuda\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_CUDA_REDUCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/cuda/softmax.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda/injective.h\n * \\brief CUDA schedule for injective operations\n */\n#ifndef TVM_TOPI_CUDA_SOFTMAX_H_\n#define TVM_TOPI_CUDA_SOFTMAX_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace cuda {\n\n/*!\n * \\brief Create a CUDA schedule for the given softmax output tensors.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_softmax(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto softmax = outs[0];\n  tvm::te::Tensor max_elem;\n  tvm::te::Tensor expsum;\n  tvm::te::Tensor exp;\n  bool has_exp = false;\n\n  auto tag = softmax->op.as<ComputeOpNode>()->tag;\n  if (tag == \"softmax_output\") {\n    expsum = softmax->op->InputTensors()[1];\n    exp = softmax->op->InputTensors()[0];\n    max_elem = s[exp]->op->InputTensors()[1];\n    has_exp = true;\n  } else if (tag == \"log_softmax_output\") {\n    max_elem = softmax->op->InputTensors()[1];\n    expsum = softmax->op->InputTensors()[2];\n  } else {\n    LOG(ERROR) << \"Tag is expected to be softmax_output or log_softmax_output. Got \" << tag;\n  }\n\n  int num_thread = 64;\n  auto block_x = tvm::te::thread_axis(Range(), \"blockIdx.x\");\n  auto thread_x = tvm::te::thread_axis(Range(0, num_thread), \"threadIdx.x\");\n\n  if (has_exp) {\n    s[exp].bind(exp->op.as<ComputeOpNode>()->axis[0], block_x);\n  }\n\n  s[max_elem].bind(max_elem->op.as<ComputeOpNode>()->axis[0], block_x);\n\n  auto k = expsum->op.as<ComputeOpNode>()->reduce_axis[0];\n  IterVar ko, ki;\n  s[expsum].split(k, num_thread, &ko, &ki);\n  auto EF = s.rfactor(expsum, ki)[0];\n  s[expsum].bind(s[expsum]->op.as<ComputeOpNode>()->axis[0], block_x);\n  s[expsum].bind(s[expsum]->op.as<ComputeOpNode>()->reduce_axis[0], thread_x);\n  s[EF].compute_at(s[expsum], s[expsum]->op.as<ComputeOpNode>()->reduce_axis[0]);\n  s[expsum].set_store_predicate(thread_x->var == 0);\n\n  IterVar tx, xi;\n  s[softmax].split_by_nparts(softmax->op.as<ComputeOpNode>()->axis[1], num_thread, &tx, &xi);\n  s[softmax].bind(tx, thread_x);\n\n  return s;\n}\n\n}  // namespace cuda\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_CUDA_SOFTMAX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/array_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file array_utils.h\n * \\brief Utility functions for handling arrays\n */\n#ifndef TVM_TOPI_DETAIL_ARRAY_UTILS_H_\n#define TVM_TOPI_DETAIL_ARRAY_UTILS_H_\n\n#include <tvm/te/operation.h>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Search an array for a specific item\n *\n * \\param array The array to search\n * \\param item The item to search for\n *\n * \\return True iff the given array contains the given item.\n */\ntemplate <typename T>\ninline bool contains(Array<T> array, T item) {\n  for (auto& i : array) {\n    if (i == item) {\n      return true;\n    }\n  }\n  return false;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_ARRAY_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/broadcast.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Detail broadcast.\n * \\file topi/detail/broadcast.h\n */\n#ifndef TVM_TOPI_DETAIL_BROADCAST_H_\n#define TVM_TOPI_DETAIL_BROADCAST_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/constant_utils.h>\n\n#include <algorithm>\n#include <deque>\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nstruct BroadcastHelper {\n  std::deque<tvm::PrimExpr> common_shape;\n  std::deque<tvm::tir::Var> all_vars;\n  std::deque<tvm::tir::Var> vars1;\n  std::deque<tvm::tir::Var> vars2;\n};\n\nstatic inline DataType CommonType(DataType type1, DataType type2) {\n  ICHECK(type1.is_scalar() && type2.is_scalar());\n  ICHECK(type1.code() == type2.code());\n  return DataType(type1.code(), std::max(type1.bits(), type2.bits()), /*lanes=*/1);\n}\n\ninline BroadcastHelper BroadcastShape(const tvm::Array<tvm::PrimExpr>& shape1,\n                                      const tvm::Array<tvm::PrimExpr>& shape2) {\n  BroadcastHelper bh;\n  int s1_size = shape1.size();\n  int s2_size = shape2.size();\n  tvm::PrimExpr one(1);\n  int i;\n\n  auto cast_if_needed = [](DataType to_type, PrimExpr expr) {\n    return to_type != expr.dtype() ? cast(to_type, expr) : expr;\n  };\n\n  for (i = 1; i <= std::min(s1_size, s2_size); ++i) {\n    // TODO(@icemelon9): Need to revisit this part\n    const IntImmNode* static_size1 = shape1[s1_size - i].as<IntImmNode>();\n    const IntImmNode* static_size2 = shape2[s2_size - i].as<IntImmNode>();\n    DataType common_type = CommonType(shape1[s1_size - i].dtype(), shape2[s2_size - i].dtype());\n\n    bh.all_vars.push_front(tvm::tir::Var(\"dim\", common_type));\n    if (topi::detail::EqualCheck(shape1[s1_size - i], shape2[s2_size - i])) {\n      bh.common_shape.push_front(cast_if_needed(common_type, shape1[s1_size - i]));\n      bh.vars1.push_front(bh.all_vars[0]);\n      bh.vars2.push_front(bh.all_vars[0]);\n    } else if (topi::detail::EqualCheck(one, shape1[s1_size - i])) {\n      ICHECK(!topi::detail::EqualCheck(one, shape2[s2_size - i]));\n      bh.common_shape.push_front(cast_if_needed(common_type, shape2[s2_size - i]));\n      bh.vars2.push_front(bh.all_vars[0]);\n    } else if (topi::detail::EqualCheck(one, shape2[s2_size - i])) {\n      bh.common_shape.push_front(cast_if_needed(common_type, shape1[s1_size - i]));\n      bh.vars1.push_front(bh.all_vars[0]);\n    } else if (!static_size1 && !static_size2) {\n      bh.common_shape.push_front(\n          cast_if_needed(common_type, max(shape1[s1_size - i], shape2[s2_size - i])));\n      bh.vars1.push_front(bh.all_vars[0]);\n      bh.vars2.push_front(bh.all_vars[0]);\n    } else if (!static_size1) {\n      bh.common_shape.push_front(cast_if_needed(common_type, shape2[s2_size - i]));\n      bh.vars2.push_front(bh.all_vars[0]);\n      bh.vars1.push_front(bh.all_vars[0]);\n    } else if (!static_size2) {\n      bh.common_shape.push_front(cast_if_needed(common_type, shape1[s1_size - i]));\n      bh.vars1.push_front(bh.all_vars[0]);\n      bh.vars2.push_front(bh.all_vars[0]);\n    } else {\n      ICHECK(false) << \"Incompatible broadcast dims: \" << shape1[s1_size - i] << \" and \"\n                    << shape2[s2_size - i]\n                    << \" in: \" << tvm::Array<tvm::PrimExpr>(shape1.begin(), shape1.end()) << \" and \"\n                    << tvm::Array<tvm::PrimExpr>(shape2.begin(), shape2.end());\n    }\n  }\n  // Remaining dimensions whether on shape1 or shape2 can always be completed\n  auto max_size = std::max(s1_size, s2_size);\n  auto& shape = (s1_size > s2_size) ? shape1 : shape2;\n  auto& vars = (s1_size > s2_size) ? bh.vars1 : bh.vars2;\n  for (; i <= max_size; ++i) {\n    bh.all_vars.push_front(tvm::tir::Var(\"v\", shape[max_size - 1].dtype()));\n    bh.common_shape.push_front(shape[max_size - i]);\n    vars.push_front(bh.all_vars[0]);\n  }\n  return bh;\n}\n\ninline tvm::Array<tvm::PrimExpr> InputIndexFromBroadcast(\n    const tvm::Array<tvm::tir::Var>& ovars, const tvm::te::Tensor& T,\n    const std::deque<tvm::tir::Var>& my_vars, const std::deque<tvm::tir::Var>& all_vars) {\n  tvm::Array<tvm::PrimExpr> ivars;\n  ICHECK_EQ(ovars.size(), all_vars.size());\n  // N^2, could use a map but NBD.\n  size_t expected_dims = T->shape.size();\n  for (size_t i = 0; i < ovars.size(); ++i) {\n    bool found = false;\n    for (size_t j = 0; j < my_vars.size(); ++j) {\n      if (all_vars[i].same_as(my_vars[j])) {\n        ivars.push_back(ovars[i]);\n        found = true;\n        break;\n      }\n    }\n    // Only inject 0 here if we have not yet reached the dimension of I\n    // (i.e. this must be a 1)\n    if (!found && (ovars.size() - i) <= expected_dims) {\n      ivars.push_back(tvm::tir::make_zero(ovars[i].dtype()));\n    }\n  }\n  ICHECK(expected_dims == ivars.size());\n  return ivars;\n}\n\ntemplate <typename FBinaryExpr>\ninline tvm::te::Tensor WithBroadcast(FBinaryExpr op, const tvm::te::Tensor& A,\n                                     const tvm::te::Tensor& B, const std::string& name = \"tensor\",\n                                     const std::string& tag = \"\") {\n  auto bh = BroadcastShape(A->shape, B->shape);\n  auto l = [&](tvm::Array<tvm::tir::Var> ovars) {\n    return op(A(InputIndexFromBroadcast(ovars, A, bh.vars1, bh.all_vars)),\n              B(InputIndexFromBroadcast(ovars, B, bh.vars2, bh.all_vars)));\n  };\n  return tvm::te::compute(tvm::Array<tvm::PrimExpr>(bh.common_shape.begin(), bh.common_shape.end()),\n                          l, name, tag);\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_DETAIL_BROADCAST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/constant_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file constant_utils.h\n * \\brief Utility functions for handling constants in TVM expressions\n */\n#ifndef TVM_TOPI_DETAIL_CONSTANT_UTILS_H_\n#define TVM_TOPI_DETAIL_CONSTANT_UTILS_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/operation.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Test whether the given Expr is a constant integer\n *\n * \\param expr the Expr to query\n *\n * \\return true if the given expr is a constant int or uint, false otherwise.\n */\ninline bool IsConstInt(PrimExpr expr) { return expr->IsInstance<tvm::tir::IntImmNode>(); }\n\n/*!\n * \\brief Test whether the given Array has every element as constant integer.\n * Undefined elements are also treat as constants.\n *\n * \\param array the array to query\n *\n * \\return true if every element in array is constant int or uint, false otherwise.\n */\ninline bool IsConstIntArray(Array<PrimExpr> array) {\n  bool is_const_int = true;\n  for (auto const& elem : array) {\n    is_const_int &= !elem.defined() || elem->IsInstance<tvm::tir::IntImmNode>();\n  }\n  return is_const_int;\n}\n\n/*!\n * \\brief Get the value of the given constant integer expression. An error\n * is logged if the given expression is not a constant integer.\n *\n * \\param expr The expression to get the value of\n *\n * \\return The integer value.\n */\ninline int64_t GetConstInt(PrimExpr expr) {\n  if (expr->IsInstance<tvm::IntImmNode>()) {\n    return expr.as<tvm::IntImmNode>()->value;\n  }\n  LOG(ERROR) << \"expr must be a constant integer\";\n  return -1;\n}\n\n/*!\n * \\brief Get the value of all the constant integer expressions in the given array\n *\n * \\param exprs The array of expressions to get the values of\n * \\param var_name The name to be used when logging an error in the event that any\n * of the expressions are not constant integers.\n *\n * \\return A vector of the integer values\n */\ninline std::vector<int> GetConstIntValues(Array<PrimExpr> exprs, const std::string& var_name) {\n  std::vector<int> result;\n  if (!exprs.defined()) return result;\n  for (auto expr : exprs) {\n    ICHECK(IsConstInt(expr)) << \"All elements of \" << var_name << \" must be constant integers\";\n    result.push_back(GetConstInt(expr));\n  }\n  return result;\n}\n\n/*!\n * \\brief Get the value of all the constant integer expressions in the given array\n *\n * \\param exprs The array of expressions to get the values of\n * \\param var_name The name to be used when logging an error in the event that any\n * of the expressions are not constant integers.\n *\n * \\return A vector of the int64_t values\n */\ninline std::vector<int64_t> GetConstInt64Values(Array<PrimExpr> exprs,\n                                                const std::string& var_name) {\n  std::vector<int64_t> result;\n  if (!exprs.defined()) return result;\n  for (auto expr : exprs) {\n    ICHECK(IsConstInt(expr)) << \"All elements of \" << var_name << \" must be constant integers\";\n    result.push_back(GetConstInt(expr));\n  }\n  return result;\n}\n\n/*!\n * \\brief Check whether the two expressions are equal or not, if not simplify the expressions and\n * check again\n * \\note This is stronger equality check than tvm::tir::Equal\n * \\param lhs First expression\n * \\param rhs Second expression\n * \\return result True if both expressions are equal, else false\n */\ninline bool EqualCheck(PrimExpr lhs, PrimExpr rhs) {\n  tvm::tir::ExprDeepEqual expr_equal;\n  bool result = expr_equal(lhs, rhs);\n  if (!result) {\n    PrimExpr t = tvm::arith::Analyzer().Simplify(lhs - rhs);\n    if (const IntImmNode* i = t.as<IntImmNode>()) {\n      result = i->value == 0;\n    }\n  }\n  return result;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_CONSTANT_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/extern.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file detail/extern.h\n * \\brief Helpers for using external functions\n */\n#ifndef TVM_TOPI_DETAIL_EXTERN_H_\n#define TVM_TOPI_DETAIL_EXTERN_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/tir/builtin.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Construct a buffer to pass to an external function\n *\n * \\param shape The shape of the buffer\n * \\param dtype The type of the buffer elements\n * \\param name The name of the buffer\n *\n * \\return The Buffer object\n */\ninline Buffer DeclExternBuffer(Array<PrimExpr> shape, DataType dtype, std::string name) {\n  auto data = var(name, DataType::Handle());\n  auto elem_offset = PrimExpr();\n  return Buffer(data, dtype, shape, Array<PrimExpr>(), elem_offset, name, -1, 0, kDefault);\n}\n\n/*!\n * \\brief A function which constructs an Expr representing the invocation of an external\n * function. The function expects two arguments: an array of Buffers holding the input\n * tensor values, and a pre-allocated array of Buffers to be filled with the outputs.\n */\nusing FExtern = std::function<PrimExpr(Array<Buffer>, Array<Buffer>)>;\n\n/*!\n * \\brief Create tensors representing the result of invoking an external function.\n * This function will create the necessary buffers to hold input and output tensor values.\n *\n * \\param out_shapes An array where each element is the shape of the corresponding output tensor.\n * \\param out_types An array where each element is the dtype of the corresponding output tensor.\n * \\param inputs An array of input Tensors\n * \\param fextern A function that constructs an Expr representing the invocation of\n * the external function given the input and output buffers.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n * \\param attrs The additional auxiliary attributes of the operation.\n *\n * \\return An array of Tensors representing the outputs of the function invocation. There will\n * be one output Tensor for each element of out_shapes, with dtype equal to the corresponding\n * element of out_types.\n */\ninline Array<Tensor> make_extern(const Array<Array<PrimExpr>>& out_shapes,\n                                 const std::vector<DataType>& out_types,\n                                 const Array<Tensor>& inputs, FExtern fextern, std::string name,\n                                 std::string tag, ::tvm::Map<String, ObjectRef> attrs) {\n  ICHECK_EQ(out_shapes.size(), out_types.size())\n      << \"make_extern: out_shapes and out_types must have equal size\";\n\n  Array<Buffer> input_placeholders;\n  for (auto t : inputs) {\n    input_placeholders.push_back(DeclExternBuffer(t->shape, t->dtype, t->op->name));\n  }\n  Array<Buffer> output_placeholders;\n  for (size_t i = 0; i < out_shapes.size(); ++i) {\n    output_placeholders.push_back(DeclExternBuffer(out_shapes[i], out_types[i], name));\n  }\n\n  auto body = fextern(input_placeholders, output_placeholders);\n  auto body_stmt = tvm::tir::Evaluate(body);\n\n  auto op = ExternOp(name, tag, attrs, inputs, input_placeholders, output_placeholders, body_stmt);\n\n  Array<Tensor> outputs;\n  for (size_t i = 0; i < output_placeholders.size(); ++i) {\n    outputs.push_back(op.output(i));\n  }\n  return outputs;\n}\n\n/*!\n * \\brief This function is used to create a DLTensor structure on the stack to\n * be able to pass a symbolic buffer as arguments to TVM PackedFunc\n *\n * \\param buf The buffer to pack\n *\n * \\return An expression representing the pack operation\n */\ninline PrimExpr pack_buffer(Buffer buf) {\n  ICHECK_GT(buf->shape.size(), 0) << \"buf shape must have at least one element\";\n  auto shape =\n      tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::tvm_stack_make_shape(), buf->shape);\n  PrimExpr strides;\n  if (buf->strides.size() > 0) {\n    strides =\n        tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::tvm_stack_make_shape(), buf->shape);\n  } else {\n    strides = 0;\n  }\n  Array<PrimExpr> pack_args{buf->data,\n                            shape,\n                            strides,\n                            make_const(DataType::Int(32), static_cast<int64_t>(buf->shape.size())),\n                            make_const(buf->dtype, 0),\n                            buf->elem_offset};\n  return tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::tvm_stack_make_array(), pack_args);\n}\n\n/*!\n * \\brief Construct an Expr representing the invocation of a PackedFunc\n *\n * \\param args An array containing the registered name of the PackedFunc followed\n * by the arguments to pass to the PackedFunc when called. The first element of the\n * array must be a constant string expression.\n *\n * \\return An expression representing the invocation\n */\ninline PrimExpr call_packed(Array<PrimExpr> args) {\n  return tvm::tir::Call(DataType::Int(32), tvm::tir::builtin::tvm_call_packed(), args);\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_EXTERN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/fuse.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file fuse.h\n * \\brief Fuse operation\n */\n#ifndef TVM_TOPI_DETAIL_FUSE_H_\n#define TVM_TOPI_DETAIL_FUSE_H_\n\n#include <tvm/te/operation.h>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Fuse all of the given args\n *\n * \\param stage The stage in which to apply the fuse\n * \\param args The iteration variables to be fused\n *\n * \\return The fused iteration variable\n */\ninline IterVar Fuse(Stage stage, const Array<IterVar>& args) {\n  IterVar res;\n  stage.fuse(args, &res);\n  return res;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_FUSE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/pad_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file pad_utils.h\n * \\brief Padding helpers\n */\n#ifndef TVM_TOPI_DETAIL_PAD_UTILS_H_\n#define TVM_TOPI_DETAIL_PAD_UTILS_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Get padding size for each side given padding height and width\n *\n * \\param pad_h The amount to pad each of the top and bottom sides\n * \\param pad_w The amount to pad each of the left and right sides\n *\n * \\return An array of 4 elements, representing padding sizes for\n * each individual side. The array is in the order { top, left, bottom, right }\n */\ninline Array<PrimExpr> GetPadTuple(PrimExpr pad_h, PrimExpr pad_w) {\n  pad_h *= 2;\n  pad_w *= 2;\n\n  auto pad_top = indexdiv(pad_h + 1, 2);\n  auto pad_left = indexdiv(pad_w + 1, 2);\n\n  return {pad_top, pad_left, pad_h - pad_top, pad_w - pad_left};\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_PAD_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/ravel_unravel.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ravel_unravel.h\n * \\brief Index ravel and unraval operations\n */\n#ifndef TVM_TOPI_DETAIL_RAVEL_UNRAVEL_H_\n#define TVM_TOPI_DETAIL_RAVEL_UNRAVEL_H_\n\n#include <tvm/te/operation.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Flatten the indices to 1D\n *\n * \\param indices The input coordinates\n * \\param shape Shape of the tensor\n *\n * \\return The index after flattening\n */\ninline PrimExpr RavelIndex(Array<PrimExpr> indices, Array<PrimExpr> shape) {\n  ICHECK_EQ(indices.size(), shape.size()) << \"indices and shape must have equal size\";\n  if (indices.size() == 0U) {\n    return 0;\n  }\n  PrimExpr idx;\n  for (size_t i = 0; i < indices.size(); ++i) {\n    if (i == 0) {\n      idx = indices[i];\n    } else {\n      idx = idx * shape[i] + indices[i];\n    }\n  }\n  return idx;\n}\n\n/*!\n * \\brief Convert flattened index to coordinate array\n *\n * \\param idx The 1D index\n * \\param shape Shape of the tensor\n *\n * \\return The coordinate corresponding to the 1D index\n */\ninline Array<PrimExpr> UnravelIndex(PrimExpr idx, Array<PrimExpr> shape) {\n  std::vector<PrimExpr> indices;\n\n  for (int i = static_cast<int>(shape.size()) - 1; i >= 0; --i) {\n    indices.push_back(indexmod(idx, shape[i]));\n    idx = indexdiv(idx, shape[i]);\n  }\n  std::reverse(indices.begin(), indices.end());\n  return indices;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_RAVEL_UNRAVEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/strided_slice.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file strided_slice.h\n * \\brief Utility functions for strided_slice op\n */\n#ifndef TVM_TOPI_DETAIL_STRIDED_SLICE_H_\n#define TVM_TOPI_DETAIL_STRIDED_SLICE_H_\n\n#include <tvm/tir/expr.h>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"constant_utils.h\"\n\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\ninline int64_t CanonicalizeIndex(int64_t index, int64_t extent, int64_t stride) {\n  int64_t begin_range = stride < 0 ? -1 : 0;\n  int64_t end_range = stride < 0 ? extent - 1 : extent;\n  if (index < 0) {\n    index += extent;\n  }\n  return std::min(std::max(index, begin_range), end_range);\n}\n\ninline std::tuple<std::vector<int64_t>, std::vector<int64_t>, std::vector<int64_t>> ConvertToVec(\n    const Array<Integer>& begin, const Array<Integer>& end, const Array<Integer>& strides,\n    std::string slice_mode) {\n  std::vector<int64_t> stride_vec(strides.size(), 1);\n  if (slice_mode == \"end\") {\n    for (size_t i = 0; i < strides.size(); ++i) {\n      ICHECK(strides[i].defined());\n      stride_vec[i] = GetConstInt(strides[i]);\n    }\n  }\n  const int64_t max_range = std::numeric_limits<int64_t>::max();\n  std::vector<int64_t> begin_vec;\n  for (size_t i = 0; i < begin.size(); ++i) {\n    if (!begin[i].defined()) {\n      // value=None\n      begin_vec.push_back(stride_vec[i] > 0 ? 0 : max_range);\n    } else {\n      begin_vec.push_back(GetConstInt(begin[i]));\n    }\n  }\n  std::vector<int64_t> end_vec;\n  for (size_t i = 0; i < end.size(); ++i) {\n    // allow end to be None\n    if (!end[i].defined()) {\n      end_vec.push_back(stride_vec[i] < 0 ? 0 : max_range);\n    } else if (slice_mode == \"size\") {\n      int64_t end_val = GetConstInt(end[i]);\n      if (end_val < 0) {\n        end_vec.push_back(stride_vec[i] < 0 ? 0 : max_range);\n      } else {\n        end_vec.push_back(begin_vec[i] + end_val);\n      }\n    } else {\n      end_vec.push_back(GetConstInt(end[i]));\n    }\n  }\n  return std::make_tuple(begin_vec, end_vec, stride_vec);\n}\n\ninline Array<PrimExpr> StridedSliceCanonicalizeBegin(const Array<PrimExpr>& ishape,\n                                                     const std::vector<int64_t>& begin,\n                                                     const std::vector<int64_t>& strides,\n                                                     const Array<Integer>& axes, DataType dtype,\n                                                     std::string slice_mode = \"end\") {\n  Array<PrimExpr> begin_expr;\n  for (size_t i = 0; i < axes.size(); ++i) {\n    if (ishape[axes[i].IntValue()]->IsInstance<tvm::IntImmNode>()) {\n      int64_t dim_i = GetConstInt(ishape[axes[i].IntValue()]);\n      int64_t begin_i = CanonicalizeIndex(begin[i], dim_i, strides[i]);\n      begin_expr.push_back(make_const(dtype, begin_i));\n    } else {\n      auto idim = ishape[axes[i].IntValue()];\n      auto b_expr = make_const(dtype, begin[i]);\n      PrimExpr b = begin[i] < 0 ? b_expr + idim : b_expr;\n      auto s = strides[i];\n      if (s < 0) {\n        b = tvm::min(b, idim - 1);\n      } else {\n        b = tvm::if_then_else(b < 0, 0, b);\n      }\n      begin_expr.push_back(b);\n    }\n  }\n  return begin_expr;\n}\n\ninline Array<PrimExpr> StridedSliceOutputShape(const Array<PrimExpr>& ishape,\n                                               const std::vector<int64_t>& begin,\n                                               const std::vector<int64_t>& end,\n                                               const std::vector<int64_t>& strides,\n                                               const Array<Integer>& axes, std::string slice_mode,\n                                               const Array<PrimExpr>& begin_canonicalized,\n                                               bool use_any = false) {\n  const size_t src_tensor_dim = ishape.size();\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < src_tensor_dim; ++i) {\n    out_shape.push_back(ishape[i]);\n  }\n\n  for (size_t i = 0; i < axes.size(); ++i) {\n    if (ishape[axes[i].IntValue()]->IsInstance<tvm::IntImmNode>()) {\n      const int64_t dim_i = GetConstInt(ishape[axes[i].IntValue()]);\n      ICHECK(begin_canonicalized[i]->IsInstance<tvm::IntImmNode>());\n      int64_t begin_i = GetConstInt(begin_canonicalized[i]);\n      int64_t end_i = CanonicalizeIndex(end[i], dim_i, strides[i]);\n      int interval = std::abs(end_i - begin_i);\n      int slice_size =\n          static_cast<int>((interval + std::abs(strides[i]) - 1) / std::abs(strides[i]));\n      ICHECK(strides[i] < 0 ? (end_i <= begin_i) : (begin_i <= end_i))\n          << \": Input [Begin=\" << begin[i] << \", End=\" << end[i] << \"] is invalid for axis=\" << i;\n      out_shape.Set(axes[i].IntValue(), cast(out_shape[i].dtype(), PrimExpr(slice_size)));\n    } else if (use_any) {\n      out_shape.Set(axes[i].IntValue(), tvm::tir::Any());\n    } else {\n      out_shape.Set(axes[i].IntValue(), tvm::tir::Var(\"dim\", out_shape[i]->dtype));\n    }\n  }\n\n  return out_shape;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_STRIDED_SLICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/detail/tensor_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tensor_utils.h\n * \\brief Utility functions for handling tensor\n */\n#ifndef TVM_TOPI_DETAIL_TENSOR_UTILS_H_\n#define TVM_TOPI_DETAIL_TENSOR_UTILS_H_\n\n#include <tvm/te/operation.h>\n\n#include <vector>\nnamespace tvm {\nnamespace topi {\nnamespace detail {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Check whether input shape has dimension of size 0;\n *\n * \\param x Input shape\n *\n * \\return True if the input shape is empty.\n */\ninline bool is_empty_shape(const Array<PrimExpr>& x) {\n  bool is_empty = false;\n  for (const auto& dim : x) {\n    if (auto int_dim = dim.as<IntImmNode>()) {\n      if (int_dim->value == 0) {\n        is_empty = true;\n        break;\n      }\n    }\n  }\n  return is_empty;\n}\n\n/*!\n * \\brief Sample a point in a tensor using bilinear interpolation.\n *\n * \\param input The input tensor.\n * \\param indices The index of the target point, which can be fractional\n * \\param max_y The maximum of y dimension\n * \\param max_x The maximum of x dimension\n *\n * \\return The interpolated value in the given index.\n */\ninline PrimExpr bilinear_sample_nchw(const Tensor& input, const Array<PrimExpr>& indices,\n                                     const PrimExpr max_y, const PrimExpr max_x) {\n  auto batch_id = indices[0];\n  auto channel_id = indices[1];\n  auto in_y = indices[2];\n  auto in_x = indices[3];\n\n  auto y_low = tvm::cast(DataType::Int(32), tvm::floor(in_y));\n  auto y_high = y_low + 1;\n\n  auto x_low = tvm::cast(DataType::Int(32), tvm::floor(in_x));\n  auto x_high = x_low + 1;\n\n  auto wy_h = in_y - y_low;\n  auto wx_h = in_x - x_low;\n  auto wy_l = 1 - wy_h;\n  auto wx_l = 1 - wx_h;\n\n  PrimExpr val = 0;\n  std::vector<std::vector<PrimExpr>> wx_xp{{wx_l, x_low}, {wx_h, x_high}};\n  std::vector<std::vector<PrimExpr>> wy_yp{{wy_l, y_low}, {wy_h, y_high}};\n  for (auto wx_xp_ele : wx_xp) {\n    for (auto wy_yp_ele : wy_yp) {\n      auto wx = wx_xp_ele[0];\n      auto xp = wx_xp_ele[1];\n      auto wy = wy_yp_ele[0];\n      auto yp = wy_yp_ele[1];\n      val += tvm::if_then_else(0 <= yp && yp <= max_y && 0 <= xp && xp <= max_x,\n                               wx * wy * input(batch_id, channel_id, yp, xp), 0);\n    }\n  }\n  return val;\n}\n\n/*!\n * \\brief Sample a point in a tensor using bilinear interpolation.\n *\n * \\param input The input tensor.\n * \\param indices The index of the target point, which can be fractional\n * \\param max_y The maximum of y dimension\n * \\param max_x The maximum of x dimension\n *\n * \\return The interpolated value in the given index.\n */\ninline PrimExpr bilinear_sample_nhwc(const Tensor& input, const Array<PrimExpr>& indices,\n                                     const PrimExpr max_y, const PrimExpr max_x) {\n  auto batch_id = indices[0];\n  auto channel_id = indices[3];\n  auto in_y = indices[1];\n  auto in_x = indices[2];\n\n  auto y_low = tvm::cast(DataType::Int(32), tvm::floor(in_y));\n  auto y_high = y_low + 1;\n\n  auto x_low = tvm::cast(DataType::Int(32), tvm::floor(in_x));\n  auto x_high = x_low + 1;\n\n  auto wy_h = in_y - y_low;\n  auto wx_h = in_x - x_low;\n  auto wy_l = 1 - wy_h;\n  auto wx_l = 1 - wx_h;\n\n  PrimExpr val = 0;\n  std::vector<std::vector<PrimExpr>> wx_xp{{wx_l, x_low}, {wx_h, x_high}};\n  std::vector<std::vector<PrimExpr>> wy_yp{{wy_l, y_low}, {wy_h, y_high}};\n  for (auto wx_xp_ele : wx_xp) {\n    for (auto wy_yp_ele : wy_yp) {\n      auto wx = wx_xp_ele[0];\n      auto xp = wx_xp_ele[1];\n      auto wy = wy_yp_ele[0];\n      auto yp = wy_yp_ele[1];\n      val += tvm::if_then_else(0 <= yp && yp <= max_y && 0 <= xp && xp <= max_x,\n                               wx * wy * input(batch_id, yp, xp, channel_id), 0);\n    }\n  }\n  return val;\n}\n\n}  // namespace detail\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_DETAIL_TENSOR_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/einsum.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file topi/einsum.h\n * \\brief Einstein summation op\n */\n#ifndef TVM_TOPI_EINSUM_H_\n#define TVM_TOPI_EINSUM_H_\n\n#define LABELRANGE 128\n#define NPY_MAXDIMS 16\n#define NPY_MAXARGS 16\n\n#include <tvm/te/operation.h>\n#include <tvm/tir/data_layout.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/detail/ravel_unravel.h>\n#include <tvm/topi/detail/tensor_utils.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <bitset>\n#include <iterator>\n#include <string>\n#include <tuple>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\nusing namespace topi::detail;\n\n/*!\n * \\brief Compute the shape of the output.\n * \\param subscripts input subscripts.\n * \\param operands operand tensors.\n *\n * \\return the shape of the output.\n */\nArray<PrimExpr> InferEinsumShape(const std::string& subscripts,\n                                 const std::vector<Array<PrimExpr>>& operands);\n\n/*!\n * \\brief Evaluates the Einstein summation convention on the operands.\n *\n * \\param subscripts_str Specifies the subscripts for summation as comma separated list of\n * subscript labels.\n * \\param inputs Arrays for the operation.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return The calculation based on the Einstein summation convention.\n */\nTensor einsum(const std::string& subscripts_str, const Array<Tensor> inputs,\n              std::string name = \"T_einsum\", std::string tag = kEinsum);\n\nstruct EinsumEquation {\n  /*!\n   * \\brief Create EinsumEquation from a string.\n   * The result will be converted to the explicit mode of Einsum if it is in implicit mode.\n   * \\return The created EinsumEquation.\n   */\n  static EinsumEquation FromString(const std::string& equation);\n  using Label = char;\n  using Subscript = std::vector<Label>;\n  // Special label value for ellipsis. The value is chosen to be less than any other letters so make\n  // sorting easier.\n  static constexpr Label kEllipsis = '\\0';\n  // The input subscripts for each operand of the Einsum operator.\n  std::vector<Subscript> inputs;\n  // The output subscript of the Einsum equation.\n  Subscript output;\n};\n\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_EINSUM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/elemwise.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file elemwise.h\n * \\brief Elementwise op constructions\n */\n#ifndef TVM_TOPI_ELEMWISE_H_\n#define TVM_TOPI_ELEMWISE_H_\n\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <string>\n\n#include \"broadcast.h\"\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\n// Unary intrinsic operators\n#define TOPI_DECLARE_UNARY_OP(OpName)                                                   \\\n  inline Tensor OpName(const Tensor& x, std::string name = \"T_\" #OpName,                \\\n                       std::string tag = kElementWise) {                                \\\n    return compute(                                                                     \\\n        x->shape, [&](const Array<Var>& i) { return ::tvm::OpName(x(i)); }, name, tag); \\\n  }\n\nTOPI_DECLARE_UNARY_OP(exp);\nTOPI_DECLARE_UNARY_OP(erf);\nTOPI_DECLARE_UNARY_OP(sigmoid);\nTOPI_DECLARE_UNARY_OP(sqrt);\nTOPI_DECLARE_UNARY_OP(log);\nTOPI_DECLARE_UNARY_OP(log2);\nTOPI_DECLARE_UNARY_OP(log10);\nTOPI_DECLARE_UNARY_OP(floor);\nTOPI_DECLARE_UNARY_OP(ceil);\nTOPI_DECLARE_UNARY_OP(round);\nTOPI_DECLARE_UNARY_OP(trunc);\nTOPI_DECLARE_UNARY_OP(abs);\nTOPI_DECLARE_UNARY_OP(cos);\nTOPI_DECLARE_UNARY_OP(cosh);\nTOPI_DECLARE_UNARY_OP(tan);\nTOPI_DECLARE_UNARY_OP(sin);\nTOPI_DECLARE_UNARY_OP(sinh);\nTOPI_DECLARE_UNARY_OP(acos);\nTOPI_DECLARE_UNARY_OP(acosh);\nTOPI_DECLARE_UNARY_OP(asin);\nTOPI_DECLARE_UNARY_OP(asinh);\nTOPI_DECLARE_UNARY_OP(atan);\nTOPI_DECLARE_UNARY_OP(atanh);\nTOPI_DECLARE_UNARY_OP(isnan);\nTOPI_DECLARE_UNARY_OP(tanh);\nTOPI_DECLARE_UNARY_OP(isfinite);\nTOPI_DECLARE_UNARY_OP(isinf);\n\n/*!\n * \\brief Fast_tanh_float implementation from Eigen\n * https://github.com/eigenteam/eigen-git-mirror/blob/master/Eigen/src/Core/MathFunctionsImpl.h#L26\n */\ninline Tensor fast_tanh_float(const Tensor& in, std::string name, std::string tag) {\n  // Clamp the inputs to the range [-9, 9] since anything outside\n  // this range is +/-1.0f in single-precision.\n  auto x = maximum(make_const(in->dtype, -9.0), minimum(make_const(in->dtype, 9.0), in));\n\n  // The monomial coefficients of the numerator polynomial (odd).\n  auto alpha_1 = make_const(in->dtype, 4.89352455891786e-03);\n  auto alpha_3 = make_const(in->dtype, 6.37261928875436e-04);\n  auto alpha_5 = make_const(in->dtype, 1.48572235717979e-05);\n  auto alpha_7 = make_const(in->dtype, 5.12229709037114e-08);\n  auto alpha_9 = make_const(in->dtype, -8.60467152213735e-11);\n  auto alpha_11 = make_const(in->dtype, 2.00018790482477e-13);\n  auto alpha_13 = make_const(in->dtype, -2.76076847742355e-16);\n\n  // The monomial coefficients of the denominator polynomial (even).\n  auto beta_0 = make_const(in->dtype, 4.89352518554385e-03);\n  auto beta_2 = make_const(in->dtype, 2.26843463243900e-03);\n  auto beta_4 = make_const(in->dtype, 1.18534705686654e-04);\n  auto beta_6 = make_const(in->dtype, 1.19825839466702e-06);\n\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) {\n        auto x2 = x(i) * x(i);\n        auto p = x2 * alpha_13 + alpha_11;\n        p = x2 * p + alpha_9;\n        p = x2 * p + alpha_7;\n        p = x2 * p + alpha_5;\n        p = x2 * p + alpha_3;\n        p = x2 * p + alpha_1;\n        p = x(i) * p;\n\n        auto q = x2 * beta_6 + beta_4;\n        q = x2 * q + beta_2;\n        q = x2 * q + beta_0;\n        return p / q;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that returns hyperbolic tanh of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is tanh\n */\ninline Tensor fast_tanh(const Tensor& x, std::string name = \"T_fast_tanh\",\n                        std::string tag = kElementWise) {\n  if (x->dtype == DataType::Float(32)) {\n    // invoke fast_tanh_float implementation\n    return fast_tanh_float(x, name, tag);\n  } else {\n    // fallback to default implementation\n    return compute(\n        x->shape, [&](const Array<Var>& i) { return ::tvm::tanh(x(i)); }, name, tag);\n  }\n}\n\n/*!\n * \\brief Creates an operation that returns identity of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the identity operation\n */\ninline Tensor identity(const Tensor& x, std::string name = \"T_identity\",\n                       std::string tag = kElementWise) {\n  return compute(\n      x->shape, [&](const Array<Var>& i) { return x(i); }, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that returns the negation of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the negation operation\n */\ninline Tensor negative(const Tensor& x, std::string name = \"T_negative\",\n                       std::string tag = kElementWise) {\n  return compute(\n      x->shape, [&](const Array<Var>& i) { return -x(i); }, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that returns the logical NOT of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the logical NOT operation\n */\ninline Tensor logical_not(const Tensor& x, std::string name = \"T_logical_not\",\n                          std::string tag = kElementWise) {\n  return compute(\n      x->shape, [&](const Array<Var>& i) { return !x(i); }, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that returns the bitwise NOT of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the bitwise NOT operation\n */\ninline Tensor bitwise_not(const Tensor& x, std::string name = \"T_bitwise_not\",\n                          std::string tag = kElementWise) {\n  return compute(\n      x->shape, [&](const Array<Var>& i) { return ~x(i); }, name, tag);\n}\n\n/*!\n * \\brief Returns the sign of the tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the sign\n */\ninline Tensor sign(const Tensor& x, std::string name = \"T_sign\", std::string tag = kElementWise) {\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) {\n        PrimExpr zero = make_zero(x->dtype);\n        PrimExpr one = make_const(x->dtype, 1);\n        PrimExpr minus_one = make_const(x->dtype, -1);\n        auto s1 = tvm::tir::Select((x(i) < zero), minus_one, zero);\n        auto s2 = tvm::tir::Select((x(i) > zero), one, s1);\n        return s2;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that returns rsqrt of a given tensor\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the rsqrt operation\n */\ninline Tensor rsqrt(const Tensor& x, std::string name = \"tensor\", std::string tag = kElementWise) {\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) {\n        PrimExpr one = make_const(x->dtype, 1);\n        return one / tvm::sqrt(x(i));\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that clips each element of a tensor to\n * the interval [a_min, a_max]\n *\n * \\param x The input tensor\n * \\param a_min The inclusive lower bound of the interval\n * \\param a_max The inclusive upper bound of the interval\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the clip operation\n */\ninline Tensor clip(const Tensor& x, const PrimExpr& a_min, const PrimExpr& a_max,\n                   std::string name = \"T_clip\", std::string tag = kElementWise) {\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) {\n        auto min_val = tvm::cast(x->dtype, a_min);\n        auto max_val = tvm::cast(x->dtype, a_max);\n        return tvm::max(tvm::min(x(i), max_val), min_val);  // NOLINT(*)\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Cast each element of x to the given type. If expr is\n * scalar and type is a corresponding vector type, a\n * Broadcast is generated, otherwise a Cast is generated.\n *\n * \\param x The input tensor\n * \\param type The type to cast to\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the cast operation\n */\ninline Tensor cast(const Tensor& x, DataType type, std::string name = \"T_cast\",\n                   std::string tag = kElementWise) {\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) -> PrimExpr {\n        auto expr = x(i);\n        if (expr.dtype().code() == type.code() && expr.dtype().bits() == type.bits()) {\n          if (expr.dtype().lanes() == type.lanes()) {\n            return expr;\n          } else if (expr.dtype().lanes() == 1 && type.lanes() > 1) {\n            return tvm::tir::Broadcast(expr, type.lanes());\n          }\n        }\n\n        return tvm::cast(type, x(i));\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Reinterpret each element of x to the given type.\n\n * \\param x The input tensor\n * \\param type The type to cast to\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the reinterpret operation\n */\ninline Tensor reinterpret(const Tensor& x, DataType type, std::string name = \"tensor\",\n                          std::string tag = kElementWise) {\n  return compute(\n      x->shape,\n      [&](const Array<Var>& i) {\n        return tvm::tir::Call(type, tvm::tir::builtin::reinterpret(), {x(i)});\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that sum each element of a tensor\n *\n * \\param xs The input tensor array\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the sum operation\n */\ninline Tensor elemwise_sum(const Array<Tensor>& xs, std::string name = \"T_elemwise_sum\",\n                           std::string tag = kElementWise) {\n  ICHECK_GT(xs.size(), 0) << \"elemwise sum must have at least one input tensor.\";\n  return compute(\n      xs[0]->shape,\n      [&](const Array<Var>& i) {\n        auto sum_expr = xs[0](i);\n        for (size_t j = 1; j < xs.size(); j++) {\n          sum_expr = sum_expr + xs[j](i);\n        }\n        return sum_expr;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that fill a tensor with fill_value\n *\n * \\param shape The shape of a tensor\n * \\param dtype The Type of fill_value\n * \\param fill_value The value to be filled\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the full operation\n */\ninline Tensor full(const Array<PrimExpr>& shape, DataType dtype, const PrimExpr fill_value,\n                   std::string name = \"T_full\", std::string tag = kElementWise) {\n  PrimExpr ev = cast(dtype, fill_value);\n  if (!ev.defined()) {\n    LOG(ERROR) << \"Can't cast fill_value to \" << dtype;\n  }\n  return compute(\n      shape, [&](const Array<Var>& i) { return ev; }, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that construct a tensor with same shape as input tensor,\n * then fill a tensor with fill_value\n *\n * \\param x The input tensor\n * \\param fill_value The value to be filled\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op memeber is the full_like operation\n */\ninline Tensor full_like(const Tensor& x, const PrimExpr fill_value,\n                        std::string name = \"T_full_like\", std::string tag = kElementWise) {\n  PrimExpr ev = cast(x->dtype, fill_value);\n  return compute(\n      x->shape, [&](const Array<Var>& i) { return ev; }, name, tag);\n}\n\n/*!\n * \\brief Fast exponential function implementation\n *\n * \\param _x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is exponent operation\n *\n * \\note Function computes:\n * log2(e^x) = x * log2(e) * log2(2) =>\n * log2(e^x) = log2(2^(x*log2(e))) =>\n * e^x = 2^(x*log2(e))\n * Splitting power x*log2(e) into integer and fractional parts:\n * e^(n+f) = e^n * e^f\n * n = floor(x*log2(e) + 1/2)\n * f = x - n * ln(2)\n * exp(x) = 2^n * exp(y)\n * Approximation for fractional part:\n * y = exp(f) = 1 + 2 * P(x**2)/(Q(x**2) - P(x**2))\n */\ninline Tensor fast_exp_float32(const Tensor& _x, std::string name, std::string tag) {\n  auto x_hi = make_const(DataType::Float(32), 88.3762626647950f);\n  auto x_lo = make_const(DataType::Float(32), -88.3762626647949f);\n  auto log2e = make_const(DataType::Float(32), 1.44269504088896341f);\n  auto ln2 = make_const(DataType::Float(32), 0.6931471805599453f);\n  PrimExpr p[6] = {make_const(DataType::Float(32), 1.9875691500E-4f),\n                   make_const(DataType::Float(32), 1.3981999507E-3f),\n                   make_const(DataType::Float(32), 8.3334519073E-3f),\n                   make_const(DataType::Float(32), 4.1665795894E-2f),\n                   make_const(DataType::Float(32), 1.6666665459E-1f),\n                   make_const(DataType::Float(32), 5.0000001201E-1f)};\n  auto one = make_const(DataType::Float(32), 1.0f);\n  auto one_half = make_const(DataType::Float(32), 0.5f);\n  auto b = make_const(DataType::Float(32), 127.0f);\n\n  return compute(\n      _x->shape,\n      [&](const Array<Var>& i) {\n        // clamp x\n        auto x = ::tvm::max(::tvm::min(_x(i), x_hi), x_lo);\n        // integer part\n        auto n = ::tvm::floor(x * log2e + one_half);\n        // fractional part\n        auto f = x - n * ln2;\n        auto y =\n            (((((p[0] * f + p[1]) * f + p[2]) * f + p[3]) * f + p[4]) * f + p[5]) * f * f + f + one;\n        // Return 2^m * exp(r).\n        auto ef =\n            tvm::reinterpret(DataType::Float(32), ::tvm::cast(DataType::Int(32), n + b) << 23);\n        return ::tvm::max(ef * y, _x(i));  // NOLINT(*)\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Fast exponential function implementation\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is exponent operation\n *\n */\ninline Tensor fast_exp(const Tensor& x, std::string name = \"T_fast_exp\",\n                       std::string tag = kElementWise) {\n  if (x->dtype == DataType::Float(32)) {\n    auto ret = fast_exp_float32(x, name, tag);\n    return ret;\n  } else {\n    return compute(\n        x->shape, [&](const Array<Var>& i) { return ::tvm::exp(x(i)); }, name, tag);\n  }\n}\n\n/*!\n * \\brief Fast_erf_float expression from Eigen\n * https://github.com/eigenteam/eigen-git-mirror/blob/master/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h#L290\n * \\param arg The input expression.\n * \\param bits The number of bits in the type.\n */\ninline PrimExpr fast_erf_float_expr(PrimExpr arg, int bits) {\n  auto plus_4 = make_const(DataType::Float(bits), 4.f);\n  auto minus_4 = make_const(DataType::Float(bits), -4.f);\n\n  // The monomial coefficients of the numerator polynomial (odd).\n  auto alpha_1 = make_const(DataType::Float(bits), -1.60960333262415e-02f);\n  auto alpha_3 = make_const(DataType::Float(bits), -2.95459980854025e-03f);\n  auto alpha_5 = make_const(DataType::Float(bits), -7.34990630326855e-04f);\n  auto alpha_7 = make_const(DataType::Float(bits), -5.69250639462346e-05f);\n  auto alpha_9 = make_const(DataType::Float(bits), -2.10102402082508e-06f);\n  auto alpha_11 = make_const(DataType::Float(bits), 2.77068142495902e-08f);\n  auto alpha_13 = make_const(DataType::Float(bits), -2.72614225801306e-10f);\n\n  // The monomial coefficients of the denominator polynomial (even).\n  auto beta_0 = make_const(DataType::Float(bits), -1.42647390514189e-02f);\n  auto beta_2 = make_const(DataType::Float(bits), -7.37332916720468e-03f);\n  auto beta_4 = make_const(DataType::Float(bits), -1.68282697438203e-03f);\n  auto beta_6 = make_const(DataType::Float(bits), -2.13374055278905e-04f);\n  auto beta_8 = make_const(DataType::Float(bits), -1.45660718464996e-05f);\n\n  // clamp x\n  auto x = tvm::max(tvm::min(arg, plus_4), minus_4);\n  auto x2 = x * x;\n\n  // Evaluate the numerator polynomial p.\n  auto p = x2 * alpha_13 + alpha_11;\n  p = x2 * p + alpha_9;\n  p = x2 * p + alpha_7;\n  p = x2 * p + alpha_5;\n  p = x2 * p + alpha_3;\n  p = x2 * p + alpha_1;\n  p = x * p;\n\n  // Evaluate the denominator polynomial p.\n  auto q = x2 * beta_8 + beta_6;\n  q = x2 * q + beta_4;\n  q = x2 * q + beta_2;\n  q = x2 * q + beta_0;\n\n  return p / q;\n}\n\n/*!\n * \\brief Fast_erf_float expression from Eigen\n */\ninline Tensor fast_erf_float32(const Tensor& data, std::string name, std::string tag) {\n  return compute(\n      data->shape, [&](const Array<Var>& i) { return fast_erf_float_expr(data(i), 32); }, name,\n      tag);\n}\n\n/*!\n * \\brief Fast_erf_float expression from Eigen for float16.\n */\ninline Tensor fast_erf_float16(const Tensor& data, std::string name, std::string tag) {\n  return compute(\n      data->shape, [&](const Array<Var>& i) { return fast_erf_float_expr(data(i), 16); }, name,\n      tag);\n}\n\n/*!\n * \\brief Fast erf implementation\n *\n * \\param x The input tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is erf operation\n */\ninline Tensor fast_erf(const Tensor& x, std::string name = \"T_fast_erf\",\n                       std::string tag = kElementWise) {\n  if (x->dtype == DataType::Float(32)) {\n    auto ret = fast_erf_float32(x, name, tag);\n    return ret;\n  } else if (x->dtype == DataType::Float(16)) {\n    auto ret = fast_erf_float16(x, name, tag);\n    return ret;\n  } else {\n    return topi::erf(x);\n  }\n}\n\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ELEMWISE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/generic/default.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file generic/default.h\n * \\brief Generic default schedule\n */\n#ifndef TVM_TOPI_GENERIC_DEFAULT_H_\n#define TVM_TOPI_GENERIC_DEFAULT_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace generic {\n/*!\n * \\brief Create a generic default schedule for the given output tensors.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule default_schedule(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  return s;\n}\n\n/*!\n * \\brief Create a generic default schedule for the given output tensors, and apply\n * auto inline\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule default_schedule_auto_inline(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  auto x = outs[0];\n  tvm::te::AutoInlineInjective(s);\n  auto axis = s[x]->op.as<ComputeOpNode>()->axis;\n  if (axis.size() > 0) {\n    detail::Fuse(s[x], axis);\n  }\n  return s;\n}\n\n}  // namespace generic\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_GENERIC_DEFAULT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/generic/extern.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file generic/extern.h\n * \\brief Schedule for extern followed by injective ops\n */\n#ifndef TVM_TOPI_GENERIC_EXTERN_H_\n#define TVM_TOPI_GENERIC_EXTERN_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/generic/injective.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace generic {\n/*!\n * \\brief Schedule an extern op followed by injective operations\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the op.\n */\ninline Schedule schedule_extern(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  tvm::te::AutoInlineInjective(s);\n  for (auto out : outs) {\n    if (out->op->IsInstance<ExternOpNode>()) {\n      continue;\n    }\n    tvm::GenericFunc::Get(\"schedule_injective_from_existing\")(s, out);\n  }\n\n  return s;\n}\n\n}  // namespace generic\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_GENERIC_EXTERN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/generic/injective.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file generic/injective.h\n * \\brief Generic schedule for injective operations\n */\n#ifndef TVM_TOPI_GENERIC_INJECTIVE_H_\n#define TVM_TOPI_GENERIC_INJECTIVE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace generic {\n\n/*!\n * \\brief Updates an existing schedule for the given injective ops.\n *\n * \\param sch The schedule to update.\n * \\param out The tensor representing the injective op.\n *\n * \\return The updated schedule.\n */\ninline Schedule schedule_injective_from_existing(Schedule sch, const Tensor& out) {\n  detail::Fuse(sch[out], sch[out]->op.as<ComputeOpNode>()->axis);\n  return sch;\n}\n\n/*!\n * \\brief Create a generic schedule for the given injective ops.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_injective(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  tvm::te::AutoInlineInjective(s);\n  auto x = outs[0];\n  schedule_injective_from_existing(s, x);\n\n  return s;\n}\n\n}  // namespace generic\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_GENERIC_INJECTIVE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief NN op constructions\n * \\file topi/nn.h\n */\n#ifndef TVM_TOPI_NN_H_\n#define TVM_TOPI_NN_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/operation.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/reduction.h>\n#include <tvm/topi/tags.h>\n#include <tvm/topi/transform.h>\n\n#include <algorithm>\n#include <string>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Creates an operation that performs a rectified linear unit\n *\n * \\param t The input tensor\n * \\param threshold The relu threshold (default 0)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the relu operation\n */\ntemplate <typename T>\ninline tvm::te::Tensor relu(const tvm::te::Tensor& t, T threshold = static_cast<T>(0),\n                            std::string name = \"T_relu\", std::string tag = kElementWise) {\n  return tvm::te::compute(\n      t->shape,\n      [&](const tvm::Array<tvm::tir::Var>& i) {\n        auto threshold_const = tvm::tir::make_const(t->dtype, threshold);\n        return tvm::max(t(i), threshold_const);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs a leaky rectified linear unit\n *\n * \\param t The input tensor\n * \\param alpha The slope for the small gradient when t < 0\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the leaky relu operation\n */\ninline tvm::te::Tensor leaky_relu(const tvm::te::Tensor& t, double alpha = 0.1,\n                                  std::string name = \"T_leaky_relu\",\n                                  std::string tag = kElementWise) {\n  return tvm::te::compute(\n      t->shape,\n      [&](const tvm::Array<tvm::tir::Var>& i) {\n        auto value = t(i);\n        auto calpha = tvm::tir::make_const(value.dtype(), alpha);\n        return tvm::tir::Select(value > 0, value, value * calpha);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs a parametric rectified linear unit\n *\n * \\param x The input data tensor\n * \\param slope The channel-wise slope tensor\n * \\param axis The axis where the channel data needs to be applied\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the parametric relu operation\n */\ninline tvm::te::Tensor prelu(const tvm::te::Tensor& x, const tvm::te::Tensor& slope,\n                             const int axis = 1, std::string name = \"T_prelu\",\n                             std::string tag = kBroadcast) {\n  ICHECK((size_t)axis < x->shape.size()) << \"Wrong axis (\" << axis << \")value. \";\n  ICHECK(topi::detail::GetConstInt(slope->shape[0]) == topi::detail::GetConstInt(x->shape[axis]))\n      << \"Wrong slope shape received.\";\n\n  return tvm::te::compute(\n      x->shape,\n      [&](const tvm::Array<tvm::tir::Var>& indices) {\n        auto xval = x(indices);\n        return tvm::tir::Select(xval > 0, xval, xval * slope(indices[axis]));\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs padding\n *\n * \\param t The input tensor\n * \\param pad_before An Array of Expr describing the padding before the\n * respective iterator\n * \\param pad_after An Array of Expr describing the padding after the\n * respective iterator\n * \\param pad_value The value to fill padding elements with\n * \\param pad_mode Padding type to use.\n * \"constant\" pads with constant_value;\n * \"edge\" pads using the edge values of the input array;\n * \"reflect\" pads by reflecting values with respect to the edges.\n * \\param dyn_output_shape Output shape of the pad op, default nullptr.\n * You only need to pass this in if the shape was evaluated dynamically.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the padding operation\n *\n * \\note\n *  The pad_after Array must either be empty or have the same length as\n *  pad_before\n *  When pad_after is empty, it takes the same values as pad_before (symmetric\n *  padding)\n *  The pad Array applies from the leading dimensions and skips missing\n *  trailing dimensions:\n *\n *      pad(t(i, j, k), {1}, {0}) returns the equivalent operation for\n *          the following pseudocode:\n *              for i in [1, t.shape[0] + 2]:\n *                  for i in [1, t.shape[0] + 2]:\n *                      for i in [1, t.shape[0] + 2]:\n *                         name(i,j,k) =\n *                             (1 <= i <= t.shape[0] + 1) ?\n *                                 t(i-1, j, k) : 0;\n *\n *\n */\ninline tvm::te::Tensor pad(const tvm::te::Tensor& t, const tvm::Array<tvm::PrimExpr>& pad_before,\n                           tvm::Array<tvm::PrimExpr> pad_after = tvm::Array<tvm::PrimExpr>(),\n                           PrimExpr pad_value = PrimExpr(), std::string name = \"T_pad\",\n                           std::string tag = kElementWise, std::string pad_mode = \"constant\",\n                           const Array<PrimExpr>* dyn_output_shape = nullptr) {\n  if (pad_after.size() < pad_before.size()) {\n    for (size_t i = pad_after.size(); i < pad_before.size(); ++i) {\n      pad_after.push_back(pad_before[i]);\n    }\n  }\n\n  arith::Analyzer analyzer;\n  ICHECK_GE(pad_before.size(), 1);\n  ICHECK_EQ(pad_before.size(), pad_after.size());\n  tvm::Array<tvm::PrimExpr> pad_before_int32;\n  tvm::Array<tvm::PrimExpr> pad_after_int32;\n\n  for (const auto& ele : pad_before) {\n    pad_before_int32.push_back(tvm::cast(tvm::DataType::Int(32), ele));\n  }\n  for (const auto& ele : pad_after) {\n    pad_after_int32.push_back(tvm::cast(tvm::DataType::Int(32), ele));\n  }\n\n  tvm::Array<tvm::PrimExpr> output_shape;\n  if (dyn_output_shape == nullptr) {\n    for (size_t i = 0; i < t->shape.size(); ++i) {\n      if (i >= pad_before.size()) {\n        output_shape.push_back(t->shape[i]);\n      } else {\n        output_shape.push_back(\n            analyzer.Simplify(t->shape[i] + pad_before_int32[i] + pad_after_int32[i]));\n      }\n    }\n  } else {\n    for (size_t i = 0; i < dyn_output_shape->size(); i++) {\n      output_shape.push_back((*dyn_output_shape)[i]);\n    }\n  }\n\n  if (!pad_value.defined()) {\n    pad_value = tvm::tir::make_const(t->dtype, 0);\n  }\n\n  auto l = [&](tvm::Array<tvm::tir::Var> ovars) {\n    tvm::Array<tvm::PrimExpr> indices;\n    tvm::Array<tvm::PrimExpr> sel;\n    tvm::Array<tvm::PrimExpr> pad_idx;\n    for (size_t i = 0; i < t->shape.size(); ++i) {\n      if (i >= pad_before_int32.size()) {\n        indices.push_back(ovars[i]);\n        continue;\n      }\n      if (!topi::detail::EqualCheck(pad_before_int32[i], 0)) {\n        sel.push_back(ovars[i] >= pad_before_int32[i]);\n        indices.push_back(ovars[i] - pad_before_int32[i]);\n      } else {\n        indices.push_back(ovars[i]);\n      }\n      if (!topi::detail::EqualCheck(pad_after_int32[i], 0)) {\n        sel.push_back(analyzer.Simplify(ovars[i] < pad_before_int32[i] + t->shape[i]));\n      }\n      if (pad_mode == \"edge\") {\n        pad_idx.push_back(\n            tvm::if_then_else(ovars[i] < pad_before[i], 0,\n                              tvm::if_then_else(ovars[i] >= pad_before[i] + t->shape[i],\n                                                t->shape[i] - 1, ovars[i] - pad_before[i])));\n      } else if (pad_mode == \"reflect\") {\n        pad_idx.push_back(\n            tvm::if_then_else(ovars[i] < pad_before[i], pad_before[i] - ovars[i],\n                              tvm::if_then_else(ovars[i] >= pad_before[i] + t->shape[i],\n                                                t->shape[i] * 2 - ovars[i] + pad_before[i] - 2,\n                                                ovars[i] - pad_before[i])));\n      }\n    }\n    if (sel.size() != 0) {\n      if (pad_mode == \"constant\") {\n        return tvm::if_then_else(\n            foldl([](PrimExpr a, PrimExpr b, Span span) { return tvm::logical_and(a, b, span); },\n                  const_true(1), sel),\n            t(indices), pad_value);\n      } else if (pad_mode == \"edge\" || pad_mode == \"reflect\") {\n        return tvm::if_then_else(\n            foldl([](PrimExpr a, PrimExpr b, Span span) { return tvm::logical_and(a, b, span); },\n                  const_true(1), sel),\n            t(indices), t(pad_idx));\n      }\n    }\n    return t(indices);\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs a 2-D convolution with an\n * NCHW-layout\n *\n * \\param I The 4-D input tensor\n * \\param W The 4-D weight tensor\n * \\param pad_h A static constant padding amount applied to the height of the\n * image, before and after (symmetric padding)\n * \\param pad_w A static constant padding amount applied to the width of the\n * image, before and after (symmetric padding)\n * \\param stride_h A static constant striding amount applied to the height of\n * the image, before and after (symmetric padding)\n * \\param stride_w A static constant strindingamount applied to the width of\n * the image, before and after (symmetric padding)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the 2-D convolution operation (NCHW\n * layout)\n */\ninline tvm::te::Tensor conv2d_nchw(const tvm::te::Tensor& I, const tvm::te::Tensor& W,\n                                   int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1,\n                                   std::string name = \"T_conv2d_nchw\",\n                                   std::string tag = kConv2dNCHW) {\n  ICHECK_EQ(4, I->shape.size());\n  ICHECK_EQ(4, W->shape.size());\n  auto pH = I->shape[2];\n  auto pW = I->shape[3];\n  tvm::Array<tvm::PrimExpr> output_shape{\n      I->shape[0],                                                    // B\n      W->shape[0],                                                    // O\n      indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,  // H\n      indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1   // W\n  };\n  auto i = tvm::te::reduce_axis(tvm::Range{0, I->shape[1]}, \"i\");\n  auto kh = tvm::te::reduce_axis(tvm::Range{0, W->shape[2]}, \"kh\");\n  auto kw = tvm::te::reduce_axis(tvm::Range{0, W->shape[3]}, \"kw\");\n  auto T =\n      (pad_h == 0 && pad_w == 0) ? I : pad(I, {tvm::PrimExpr(0), tvm::PrimExpr(0), pad_h, pad_w});\n  auto l = [&](tvm::tir::Var b, tvm::tir::Var o, tvm::tir::Var h, tvm::tir::Var w) {\n    return tvm::sum(T(b, i, stride_h * h + kh, stride_w * w + kw) * W(o, i, kh, kw), {i, kh, kw});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief Creates an operation for 2-D convolution layer with an HWCN-layout\n *\n * \\param I The 4-D input tensor\n * \\param W The 4-D weight tensor\n * \\param pad_h A static constant padding amount applied to the height of the\n * image, before and after (symmetric padding)\n * \\param pad_w A static constant padding amount applied to the width of the\n * image, before and after (symmetric padding)\n * \\param stride_h A static constant striding amount applied to the height of\n * the image, before and after (symmetric padding)\n * \\param stride_w A static constant strindingamount applied to the width of\n * the image, before and after (symmetric padding)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the 2-D convolution operation\n * (HWCN layout)\n */\ninline tvm::te::Tensor conv2d_hwcn(const tvm::te::Tensor& I, const tvm::te::Tensor& W,\n                                   int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1,\n                                   std::string name = \"T_conv2d_hwcn\",\n                                   std::string tag = kConv2dHWCN) {\n  ICHECK_EQ(4, I->shape.size());\n  ICHECK_EQ(4, W->shape.size());\n  auto pH = I->shape[2];\n  auto pW = I->shape[3];\n  tvm::Array<tvm::PrimExpr> output_shape{\n      indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,  // H\n      indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1,  // W\n      I->shape[2],                                                    // B\n      W->shape[3]                                                     // O\n  };\n  auto i = tvm::te::reduce_axis(tvm::Range{0, I->shape[3]}, \"i\");\n  auto kh = tvm::te::reduce_axis(tvm::Range{0, W->shape[0]}, \"kh\");\n  auto kw = tvm::te::reduce_axis(tvm::Range{0, W->shape[1]}, \"kw\");\n  auto T = (pad_h == 0 && pad_w == 0) ? I : pad(I, {pad_h, pad_w});\n  auto l = [&](tvm::tir::Var b, tvm::tir::Var o, tvm::tir::Var h, tvm::tir::Var w) {\n    return tvm::sum(T(stride_h * h + kh, stride_w * w + kw, i, b) * W(kh, kw, i, o), {i, kh, kw});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs a 2-D depthwise convolution with\n * an NCHW-layout\n *\n * \\param I The 4-D input tensor\n * \\param W The 4-D weight tensor\n * \\param pad_h A static constant padding amount applied to the height of the\n * image, before and after (symmetric padding)\n * \\param pad_w A static constant padding amount applied to the width of the\n * image, before and after (symmetric padding)\n * \\param stride_h A static constant striding amount applied to the height of\n * the image, before and after (symmetric padding)\n * \\param stride_w A static constant strindingamount applied to the width of\n * the image, before and after (symmetric padding)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the 2-D depthwise convolution operation\n * (NCHW layout)\n */\ninline tvm::te::Tensor depthwise_conv2d_nchw(const tvm::te::Tensor& I, const tvm::te::Tensor& W,\n                                             int pad_h = 0, int pad_w = 0, int stride_h = 1,\n                                             int stride_w = 1,\n                                             std::string name = \"T_depthwise_conv2d_nchw\",\n                                             std::string tag = kDepthwiseConv2dNCHW) {\n  ICHECK_EQ(4, I->shape.size());\n  ICHECK_EQ(4, W->shape.size());\n  auto pH = I->shape[2];\n  auto pW = I->shape[3];\n  auto pCM = W->shape[1];  // channel_multiplier\n  tvm::Array<tvm::PrimExpr> output_shape{\n      I->shape[0],                                                    // B\n      W->shape[1],                                                    // O\n      indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,  // H\n      indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1   // W\n  };\n  auto i = tvm::te::reduce_axis(tvm::Range{0, I->shape[1]}, \"i\");\n  auto kh = tvm::te::reduce_axis(tvm::Range{0, W->shape[2]}, \"kh\");\n  auto kw = tvm::te::reduce_axis(tvm::Range{0, W->shape[3]}, \"kw\");\n  auto T =\n      (pad_h == 0 && pad_w == 0) ? I : pad(I, {tvm::PrimExpr(0), tvm::PrimExpr(0), pad_h, pad_w});\n  auto l = [&](tvm::tir::Var b, tvm::tir::Var o, tvm::tir::Var h, tvm::tir::Var w) {\n    return tvm::sum(T(b, indexdiv(i, pCM), stride_h * h + kh, stride_w * w + kw) *\n                        W(indexdiv(i, pCM), indexmod(o, pCM), kh, kw),\n                    {i, kh, kw});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\ninline tvm::te::Tensor depthwise_conv2d_nhwc(const tvm::te::Tensor& I, const tvm::te::Tensor& W,\n                                             int pad_h = 0, int pad_w = 0, int stride_h = 1,\n                                             int stride_w = 1,\n                                             std::string name = \"T_depthwise_conv2d_nhwc\",\n                                             std::string tag = kDepthwiseConv2dNHWC) {\n  ICHECK_EQ(4, I->shape.size());\n  ICHECK_EQ(4, W->shape.size());\n  auto pH = I->shape[1];\n  auto pW = I->shape[2];\n  auto pCM = W->shape[1];  // channel_multiplier\n  tvm::Array<tvm::PrimExpr> output_shape{\n      I->shape[0],                                                    // B\n      indexdiv(I->shape[1] - W->shape[1] + 2 * pad_h, stride_h) + 1,  // H\n      indexdiv(I->shape[2] - W->shape[2] + 2 * pad_w, stride_w) + 1,  // W\n      W->shape[3],                                                    // O\n  };\n  auto i = tvm::te::reduce_axis(tvm::Range{0, I->shape[3]}, \"i\");\n  auto kh = tvm::te::reduce_axis(tvm::Range{0, W->shape[0]}, \"kh\");\n  auto kw = tvm::te::reduce_axis(tvm::Range{0, W->shape[1]}, \"kw\");\n  auto T =\n      (pad_h == 0 && pad_w == 0) ? I : pad(I, {tvm::PrimExpr(0), pad_h, pad_w, tvm::PrimExpr(0)});\n  auto l = [&](tvm::tir::Var b, tvm::tir::Var h, tvm::tir::Var w, tvm::tir::Var o) {\n    return tvm::sum(T(b, stride_h * h + kh, stride_w * w + kw, indexdiv(i, pCM)) *\n                        W(kh, kw, indexdiv(i, pCM), indexmod(o, pCM)),\n                    {kh, kw, i});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief Creates an operation that performs a 2-D group convolution with\n * an NGCHW-layout\n *\n * \\param I The 5-D input tensor\n * \\param W The 5-D weight tensor\n * \\param pad_h A static constant padding amount applied to the height of the\n * image, before and after (symmetric padding)\n * \\param pad_w A static constant padding amount applied to the width of the\n * image, before and after (symmetric padding)\n * \\param stride_h A static constant striding amount applied to the height of\n * the image, before and after (symmetric padding)\n * \\param stride_w A static constant strindingamount applied to the width of\n * the image, before and after (symmetric padding)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the 2-D groupconvolution operation\n * (NCHW layout)\n */\ninline tvm::te::Tensor group_conv2d_ngchw(const tvm::te::Tensor& I, const tvm::te::Tensor& W,\n                                          int pad_h = 0, int pad_w = 0, int stride_h = 1,\n                                          int stride_w = 1,\n                                          std::string name = \"T_group_conv2d_ngchw\",\n                                          std::string tag = kGroupConv2d) {\n  ICHECK_EQ(5, I->shape.size());\n  ICHECK_EQ(5, W->shape.size());\n  auto pH = I->shape[2];\n  auto pW = I->shape[3];\n  tvm::Array<tvm::PrimExpr> output_shape{\n      I->shape[0],                                                    // B\n      I->shape[1],                                                    // G\n      W->shape[2],                                                    // O\n      indexdiv(I->shape[3] - W->shape[3] + 2 * pad_h, stride_h) + 1,  // H\n      indexdiv(I->shape[4] - W->shape[4] + 2 * pad_w, stride_w) + 1   // W\n  };\n  auto i = tvm::te::reduce_axis(tvm::Range{0, I->shape[2]}, \"i\");\n  auto kh = tvm::te::reduce_axis(tvm::Range{0, W->shape[3]}, \"kh\");\n  auto kw = tvm::te::reduce_axis(tvm::Range{0, W->shape[4]}, \"kw\");\n\n  auto T = (pad_h == 0 && pad_w == 0)\n               ? I\n               : pad(I, {tvm::PrimExpr(0), tvm::PrimExpr(0), tvm::PrimExpr(0), pad_h, pad_w});\n  auto l = [&](tvm::Array<tvm::tir::Var> args) {\n    tvm::tir::Var b = args[0];\n    tvm::tir::Var g = args[1];\n    tvm::tir::Var o = args[2];\n    tvm::tir::Var h = args[3];\n    tvm::tir::Var w = args[4];\n    return tvm::sum(I(b, g, i, stride_h * h + kh, stride_w * w + kw) * W(g, i, o, kh, kw),\n                    {i, kh, kw});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief Divide spatial dimensions of the input into a grid of blocks.\n *\n * \\param data The input tensor.\n * \\param block_shape The size of the spatial block.\n * \\param pad_before The zero-padding size before each spatial dimension.\n * \\param pad_after The zero-padding size after each spatial dimension.\n * \\param pad_value The value used for padding.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the space_to_batch_nd operation\n */\ninline tvm::te::Tensor space_to_batch_nd(const tvm::te::Tensor& data,\n                                         const tvm::Array<Integer>& block_shape,\n                                         const tvm::Array<tvm::PrimExpr>& pad_before,\n                                         const tvm::Array<tvm::PrimExpr>& pad_after,\n                                         PrimExpr pad_value = PrimExpr(),\n                                         std::string name = \"space_to_batch_nd\",\n                                         std::string tag = kInjective) {\n  tvm::te::Tensor padded_t;\n  CHECK_EQ(pad_before.size(), pad_after.size());\n  CHECK_EQ(block_shape.size(), pad_before.size())\n      << \"Paddings must be provided for each spatial dimension\";\n  tvm::Array<tvm::PrimExpr> pad_before_int32;\n  tvm::Array<tvm::PrimExpr> pad_after_int32;\n\n  // pad size for batch dimension is 0\n  pad_before_int32.push_back(tvm::cast(tvm::DataType::Int(32), 0));\n  pad_after_int32.push_back(tvm::cast(tvm::DataType::Int(32), 0));\n  // insert pad sizes given for spatial dimensions\n  for (const auto& ele : pad_before) {\n    pad_before_int32.push_back(tvm::cast(tvm::DataType::Int(32), ele));\n  }\n  for (const auto& ele : pad_after) {\n    pad_after_int32.push_back(tvm::cast(tvm::DataType::Int(32), ele));\n  }\n\n  // pad the input with paddings provided\n  if (!pad_value.defined()) {\n    pad_value = tvm::tir::make_const(data->dtype, 0);\n  }\n  padded_t = pad(data, pad_before_int32, pad_after_int32, pad_value);\n\n  auto input_shape = data->shape;\n  auto padded_shape = padded_t->shape;\n\n  // infer shapes\n  tvm::Array<PrimExpr> r_shape;\n  tvm::Array<Integer> axis;\n  tvm::Array<PrimExpr> o_shape;\n\n  size_t num_block_dims = block_shape.size();\n  int batch = static_cast<int>(GetConstInt(input_shape[0]));\n  tvm::PrimExpr block_shape_prod(1);\n  r_shape.push_back(batch);\n\n  for (size_t i = 1; i <= num_block_dims; i++) {\n    int padded_input = static_cast<int>(GetConstInt(padded_shape[i]));\n    int block_size = static_cast<int>(GetConstInt(block_shape[i - 1]));\n    CHECK_EQ((padded_input % block_size), 0)\n        << \"(\" << i\n        << \")th \"\n           \"Input dimension after padding (\"\n        << padded_input << \")\"\n        << \" must be divisible by its block size (\" << block_size << \")\";\n\n    r_shape.push_back(div(padded_shape[i], block_shape[i - 1]));\n    r_shape.push_back(block_shape[i - 1]);\n    block_shape_prod *= block_shape[i - 1];\n    axis.push_back(Integer(r_shape.size() - 1));  // index of block_shape[i - 1]\n  }\n\n  size_t n = axis.size();\n  axis.push_back(0);  // batch is at index 0\n  // index of (padded_shape[i] / block_shape[i - 1]) in r_shape\n  for (size_t i = 0; i < n; i++) {\n    axis.push_back(static_cast<int>(GetConstInt(axis[i] - 1)));\n  }\n  o_shape.push_back(tvm::PrimExpr(batch) * block_shape_prod);\n  for (size_t i = 1; i <= num_block_dims; i++) {\n    o_shape.push_back(div(padded_shape[i], block_shape[i - 1]));\n  }\n  // append remaining shape\n  for (size_t i = num_block_dims + 1; i < input_shape.size(); i++) {\n    r_shape.push_back(input_shape[i]);\n    axis.push_back(Integer(r_shape.size() - 1));  // index of remaining shape in r_shape\n    o_shape.push_back(input_shape[i]);\n  }\n\n  tvm::te::Tensor output = reshape(padded_t, r_shape);\n  output = transpose(output, axis);\n  output = reshape(output, o_shape);\n\n  return output;\n}\n\n/*!\n * \\brief Reshape the batch dimension into spatial dimensions.\n *\n * \\param data The input tensor.\n * \\param block_shape The size of the spatial block.\n * \\param crop_begin_list The begin crop size for each spatial dimension.\n * \\param crop_end_list The end crop size for each spatial dimension.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the batch_to_space_nd operation\n */\ninline tvm::te::Tensor batch_to_space_nd(const tvm::te::Tensor& data,\n                                         const tvm::Array<Integer>& block_shape,\n                                         const tvm::Array<tvm::PrimExpr>& crop_begin_list,\n                                         const tvm::Array<tvm::PrimExpr>& crop_end_list,\n                                         std::string name = \"batch_to_space_nd\",\n                                         std::string tag = kInjective) {\n  // Construct shapes for reshape and transpose operation\n  Array<PrimExpr> in_shape = data->shape;\n  Array<PrimExpr> r_shape;\n  Array<Integer> axis;\n  size_t num_block_dims = block_shape.size();\n  size_t num_input_dims = in_shape.size();\n  tvm::PrimExpr block_shape_prod(1);\n  int batch = static_cast<int>(GetConstInt(in_shape[0]));\n\n  for (size_t i = 0; i < num_block_dims; i++) {\n    r_shape.push_back(block_shape[i]);\n    block_shape_prod *= block_shape[i];\n  }\n  axis.push_back(Integer(r_shape.size()));  // axis of (batch / block_shape_prod)\n  r_shape.push_back(batch / block_shape_prod);\n\n  for (size_t i = 1; i < num_input_dims; i++) {\n    axis.push_back(Integer(r_shape.size()));  // axis of in_shape[i]\n    if (axis.size() < (num_block_dims + num_input_dims)) {\n      axis.push_back(Integer(r_shape.size() - (num_block_dims + 1)));  // axis of block_shape[i]\n    }\n    r_shape.push_back(in_shape[i]);\n  }\n\n  Array<PrimExpr> r_p_shape;\n  r_p_shape.push_back(batch / block_shape_prod);\n  for (size_t i = 1; i <= num_block_dims; i++) {\n    r_p_shape.push_back(in_shape[i] * block_shape[i - 1]);\n  }\n  for (size_t i = num_block_dims + 1; i < num_input_dims; i++) {\n    r_p_shape.push_back(in_shape[i]);\n  }\n\n  tvm::te::Tensor out;\n  out = reshape(data, r_shape);\n  out = transpose(out, axis);\n  out = reshape(out, r_p_shape);\n\n  // Crop the start and end of dimensions of out\n  Array<Integer> begin_idx, end_idx, strides;\n  for (size_t i = 0; i < r_p_shape.size(); ++i) {\n    strides.push_back(Integer(1));\n    if (i > 0 && i <= num_block_dims) {\n      // prepare begin and end index for spatial dimensions\n      int begin_i = static_cast<int>(GetConstInt(crop_begin_list[i - 1]));\n      int end_i = static_cast<int>(GetConstInt(crop_end_list[i - 1]));\n      int out_i = static_cast<int>(GetConstInt(r_p_shape[i]));\n      CHECK_GT(out_i, (begin_i + end_i))\n          << \"Incorrect crop sizes for (\" << i << \")th dim, can not crop more than\"\n          << \" output size\" << out_i << \" vs \" << (begin_i + end_i);\n      begin_idx.push_back(begin_i);\n      end_idx.push_back(out_i - end_i);\n    } else {\n      // ignore the batch and remaining dimension\n      begin_idx.push_back(Integer(0));\n      end_idx.push_back(static_cast<int>(GetConstInt(r_p_shape[i])));\n    }\n  }\n\n  out = strided_slice(out, begin_idx, end_idx, strides);\n  return out;\n}\n\n/*!\n * \\brief Negative log likelihood loss.\n *\n * \\param predictions The prediction tensor.\n * \\param targets The target tensor.\n * \\param weights A manual rescaling weight given to each class.\n * \\param reduction The reduction method to apply to the output.\n * \\param ignore_index The target value to ignore.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return The negative log likelihood loss of the predictions and targets.\n */\ninline Tensor nll_loss(const Tensor& predictions, const Tensor& targets, const Tensor& weights,\n                       std::string reduction = \"mean\", int ignore_index = -100,\n                       const std::string name = \"nll_loss\", const std::string tag = kBroadcast) {\n  auto T = tvm::te::compute(\n      targets->shape,\n      [&](const tvm::Array<tvm::tir::Var>& target_indices) {\n        auto c = targets(target_indices);\n        tvm::Array<tvm::PrimExpr> pred_indices;\n        pred_indices.push_back(target_indices[0]);  // batch index\n        pred_indices.push_back(c);                  // class index\n        for (size_t i = 1; i < target_indices.size(); i++) {\n          pred_indices.push_back(target_indices[i]);  // indices for multidimensional loss\n        }\n        return tvm::tir::Select(c != ignore_index, -predictions(pred_indices) * weights(c),\n                                tvm::tir::make_const(predictions->dtype, 0));\n      },\n      name, tag);\n  if (reduction == \"mean\") {\n    auto W = tvm::te::compute(\n        targets->shape,\n        [&](const tvm::Array<tvm::tir::Var>& target_indices) {\n          auto c = targets(target_indices);\n          return tvm::tir::Select(c != ignore_index, weights(c),\n                                  tvm::tir::make_const(predictions->dtype, 0));\n        },\n        name, tag);\n    return topi::divide(topi::sum(T, {}), topi::sum(W, {}));\n  } else if (reduction == \"sum\") {\n    return topi::sum(T, {});\n  } else {  // reduction == \"none\"\n    return T;\n  }\n}\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/bias_add.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief bias_add op constructions\n * \\file nn/bias_add.h\n */\n#ifndef TVM_TOPI_NN_BIAS_ADD_H_\n#define TVM_TOPI_NN_BIAS_ADD_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/broadcast.h>\n#include <tvm/topi/tags.h>\n#include <tvm/topi/transform.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\n/*!\n * \\brief Creates an operation that calculates data + bias\n *\n * \\param data Tensor with shape [batch, in_dim]\n * \\param bias Tensor with shape [batch].\n * \\param axis The axis to add the bias to.\n * \\return Tensor with shape [batch, in_dim]\n */\ninline tvm::te::Tensor bias_add(const tvm::te::Tensor& data, const tvm::te::Tensor& bias,\n                                int axis) {\n  int data_ndim = data->shape.size();\n  if (axis < 0) {\n    axis += data_ndim;\n  }\n  int num_newaxis = data_ndim - axis - 1;\n  return add(data, (num_newaxis ? expand_dims(bias, 1, num_newaxis) : bias));\n}\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_BIAS_ADD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/bnn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Binary op constructions\n * \\file nn/bnn.h\n */\n#ifndef TVM_TOPI_NN_BNN_H_\n#define TVM_TOPI_NN_BNN_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Binarization and bit-packing along a certain axis.\n *\n * \\param data N-D tensor, can be any layout\n * \\param axis The axis along which to do binarization and bit-packing. This axis\n * must have a size equal to an integer multiple of 32.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return Output tensor with dtype uint32\n */\ninline tvm::te::Tensor binarize_pack(const tvm::te::Tensor& data, int axis,\n                                     std::string name = \"PackedInput\",\n                                     std::string tag = \"binarize_pack\") {\n  auto ishape = data->shape;\n  ICHECK_EQ(GetConstInt(ishape[axis]) % 32, 0)\n      << \"binarize_pack: axis size must be a multiple of 32\";\n\n  arith::Analyzer analyzer;\n  auto n = ishape.size();\n  Array<PrimExpr> oshape;\n  for (size_t i = 0; i < n; ++i) {\n    oshape.push_back(i == static_cast<size_t>(axis) ? analyzer.Simplify(indexdiv(ishape[i], 32))\n                                                    : ishape[i]);\n  }\n\n  return tvm::te::compute(\n      oshape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> start_idx;\n        for (size_t i = 0; i < n; ++i) {\n          start_idx.push_back(i == static_cast<size_t>(axis) ? indices[i] * 32\n                                                             : static_cast<PrimExpr>(indices[i]));\n        }\n        auto packed = make_const(DataType::UInt(32), 0);\n        for (size_t j = 0; j < 32; ++j) {\n          Array<PrimExpr> idx;\n          for (size_t i = 0; i < n; ++i) {\n            idx.push_back(i == static_cast<size_t>(axis) ? start_idx[i] + static_cast<int>(j)\n                                                         : start_idx[i]);\n          }\n          auto sign = tvm::cast(DataType::UInt(32), data(idx) >= 0);\n          packed = (packed | sign);\n          if (j == 31) {\n            return packed;\n          }\n          packed = packed << 1;\n        }\n        return packed;  // never reached, but suppress compiler warning\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Binary matrix multiplication using xor and bit-count\n *\n * \\param data Tensor with shape [batch, in_dim], dtype is uint32\n * \\param weight Tensor with shape [out_dim, in_dim], dtype is uint32\n *\n * \\return Tensor with shape [batch, out_dim], dtype is float32\n */\ninline tvm::te::Tensor binary_dense(const tvm::te::Tensor& data, const tvm::te::Tensor& weight) {\n  ICHECK_EQ(data->shape.size(), 2) << \"binary_dense requires 2-D data\";\n  ICHECK_EQ(weight->shape.size(), 2) << \"binary_dense requires 2-D weight\";\n  ICHECK_EQ(data->dtype, DataType::UInt(32)) << \"binary_dense requires uint32 data\";\n  ICHECK_EQ(weight->dtype, DataType::UInt(32)) << \"binary_dense requires uint32 weight\";\n\n  auto batch = data->shape[0];\n  auto in_dim = data->shape[1];\n  auto out_dim = weight->shape[0];\n\n  auto k = tvm::te::reduce_axis(Range(0, in_dim), \"k\");\n  auto matmul = tvm::te::compute(\n      {batch, out_dim},\n      [&](Var i, Var j) { return tvm::sum(popcount(data(i, k) ^ weight(j, k)), {k}); }, \"tensor\",\n      \"binary_dense\");\n\n  return tvm::te::compute(\n      {batch, out_dim}, [&](Var i, Var j) { return 32 * in_dim - 2.0f * matmul(i, j); }, \"tensor\",\n      kElementWise);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_BNN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/dense.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Dense op constructions\n * \\file nn/dense.h\n */\n#ifndef TVM_TOPI_NN_DENSE_H_\n#define TVM_TOPI_NN_DENSE_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Creates an operation that calculates data * weight^T + bias\n *\n * \\param data Tensor with shape [batch, in_dim]\n * \\param weight Tensor with shape [out_dim, in_dim]\n * \\param bias Tensor with shape [out_dim]. Optional; to omit bias, pass Tensor()\n * \\param out_dtype Output data type. Used for mixed precision.\n *\n * \\return Tensor with shape [batch, out_dim]\n */\ninline tvm::te::Tensor dense(const tvm::te::Tensor& data, const tvm::te::Tensor& weight,\n                             const tvm::te::Tensor& bias, const DataType& out_dtype) {\n  ICHECK_EQ(data->shape.size(), 2) << \"dense requires 2-D data\";\n  ICHECK_EQ(weight->shape.size(), 2) << \"dense requires 2-D weight\";\n  if (bias.defined()) {\n    ICHECK_EQ(bias->shape.size(), 1) << \"dense requires 1-D bias\";\n  }\n\n  auto batch = data->shape[0];\n  auto in_dim = data->shape[1];\n  auto out_dim = weight->shape[0];\n\n  auto k = tvm::te::reduce_axis(Range(0, in_dim), \"k\");\n  auto matmul = tvm::te::compute(\n      {batch, out_dim},\n      [&](Var i, Var j) {\n        return tvm::sum(tvm::cast(out_dtype, data(i, k)) * tvm::cast(out_dtype, weight(j, k)), {k});\n      },\n      \"tensor\", \"dense\");\n\n  if (bias.defined()) {\n    matmul = tvm::te::compute(\n        {batch, out_dim},\n        [&](Var i, Var j) { return matmul(i, j) + tvm::cast(out_dtype, bias(j)); }, \"tensor\",\n        kBroadcast);\n  }\n\n  return matmul;\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_DENSE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/dilate.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Dilate op constructions\n * \\file nn/dilate.h\n */\n#ifndef TVM_TOPI_NN_DILATE_H_\n#define TVM_TOPI_NN_DILATE_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Create a new expression of the logical and of all\n * conditions in the arguments.\n *\n * \\param args The arguments to find the logical conjunction of\n *\n * \\return The logical conjunction expression\n */\nPrimExpr all(Array<PrimExpr> args) {\n  ICHECK_GT(args.size(), 0) << \"all requires at least one argument\";\n\n  PrimExpr ret = args[0];\n  for (size_t i = 1; i < args.size(); ++i) {\n    ret = ret && args[i];\n  }\n  return ret;\n}\n\n/*!\n * \\brief Dilate data with given dilation value (0 by default).\n *\n * \\param x The input tensor, this can have any number of\n * dimensions and any layout.\n * \\param strides Dilation stride for each dimension. Stride 1\n * means no dilation.\n * \\param dilation_value Value used to dilate the input.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return The output tensor.\n */\ninline Tensor dilate(const Tensor& x, Array<PrimExpr> strides, double dilation_value,\n                     std::string name = \"tensor\", std::string tag = kInjective) {\n  auto n = x->shape.size();\n  ICHECK_EQ(n, strides.size()) << \"strides size (\" << strides.size()\n                               << \") must match dimension of x (\" << n << \")\";\n\n  Array<PrimExpr> out_shape;\n  arith::Analyzer analyzer;\n  for (size_t i = 0; i < n; ++i) {\n    out_shape.push_back(\n        analyzer.Simplify((x->shape[i] - 1) * cast(DataType::Int(32), strides[i] + 1)));\n  }\n\n  return tvm::te::compute(\n      out_shape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> not_zero;\n        Array<PrimExpr> index_tuple;\n        for (size_t i = 0; i < n; ++i) {\n          if (IsConstInt(strides[i]) && GetConstInt(strides[i]) == 1) {\n            index_tuple.push_back(indices[i]);\n          } else {\n            index_tuple.push_back(indexdiv(indices[i], strides[i]));\n            not_zero.push_back((indexmod(indices[i], strides[i])) == 0);\n          }\n        }\n        if (not_zero.size() > 0) {\n          auto all_not_zero = all(not_zero);\n          return tvm::if_then_else(all_not_zero, x(index_tuple),\n                                   make_const(x->dtype, dilation_value));\n        }\n        return x(index_tuple);\n      },\n      name, tag);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_DILATE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/flatten.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Softmax op constructions\n * \\file nn/flatten.h\n */\n#ifndef TVM_TOPI_NN_FLATTEN_H_\n#define TVM_TOPI_NN_FLATTEN_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Flattens the input tensor into a 2-D tensor by collapsing higher dimensions.\n * This requires the input tensor to have constant sized dimensions.\n *\n * \\param x The input tensor.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A 2-D tensor.\n */\ninline Tensor flatten(const Tensor& x, std::string name = \"tensor\", std::string tag = kInjective) {\n  auto ishape = x->shape;\n  PrimExpr dim = 1;\n  for (size_t i = 1; i < ishape.size(); ++i) {\n    dim = dim * ishape[i];\n  }\n\n  Array<PrimExpr> oshape({ishape[0], dim});\n\n  std::vector<PrimExpr> extra_shape;\n  for (size_t i = 1; i < ishape.size(); ++i) {\n    extra_shape.push_back(ishape[i]);\n  }\n  std::reverse(extra_shape.begin(), extra_shape.end());\n\n  return tvm::te::compute(\n      oshape,\n      [&](Var i, Var j) {\n        PrimExpr idx = j;\n        std::vector<PrimExpr> index;\n        for (auto s : extra_shape) {\n          index.push_back(indexmod(idx, s));\n          idx = indexdiv(idx, s);\n        }\n        index.push_back(i);\n        std::reverse(index.begin(), index.end());\n        return x(index);\n      },\n      name, tag);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_FLATTEN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/layer_norm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief layer normalization op constructions\n * \\file nn/layer_norm.h\n */\n#ifndef TVM_TOPI_NN_LAYER_NORM_H_\n#define TVM_TOPI_NN_LAYER_NORM_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Layer normalization.\n * \\param data N-D tensor with shape [d_0, d_1, ..., d_{N-1}]\n * \\param gamma K-D tensor with shape [r_0, r_1, ..., r_{K-1}] where K == len(axis) and\n *              d_{axis_k} == r_k\n * \\param beta Optional, K-D tensor with shape [r_0, r_1, ..., r_{K-1}] where\n *             d_{axis_k} == r_k\n * \\param axis The axis to normalize over.\n * \\param epsilon The epsilon value to avoid division by zero.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n * \\return The normalized tensor, with the same shape as data.\n */\ninline Tensor layer_norm(const Tensor& data, const Tensor& gamma, const Tensor& beta,\n                         const Array<Integer>& axis, double epsilon,\n                         std::string name = \"T_layer_norm\", std::string tag = kInjective) {\n  // sum x and x^2\n  auto ndim = data->shape.size();\n  ICHECK_NE(ndim, 0) << \"Cannot reduce a 0 dim Tensor\";\n  auto real_axis = GetRealAxis(static_cast<int>(ndim), axis);\n  auto reduce_axes = MakeReduceAxes(real_axis, data);\n  auto target_shape =\n      MakeReduceTargetShape(real_axis, data, /*keepdims=*/false, /*atleast1d=*/true);\n  auto func = MakeTupleSumReducer();\n\n  auto compute = [ndim, &real_axis, &reduce_axes, &func, &data](const Array<Var>& indices) {\n    Array<PrimExpr> eval_range;\n    int arg_counter = 0;\n    int red_counter = 0;\n\n    for (size_t i = 0; i < ndim; ++i) {\n      if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {\n        // real_axis contains i\n        eval_range.push_back(reduce_axes[red_counter]);\n        red_counter++;\n      } else {\n        eval_range.push_back(indices[arg_counter]);\n        arg_counter++;\n      }\n    }\n    auto square = [](const PrimExpr& x) { return x * x; };\n    return func({data(eval_range), square(data(eval_range))}, reduce_axes, nullptr);\n  };\n\n  auto temp_x_x2 =\n      tvm::te::compute(target_shape, compute, data->op->name + \"_red_temp\", kCommReduce);\n\n  auto temp_x = temp_x_x2[0];\n  auto temp_x2 = temp_x_x2[1];\n\n  auto reduce_extent = make_const(data->dtype, 1);\n  for (int i : real_axis) {\n    reduce_extent *= data->shape[i];\n  }\n  auto layer_norm_func = [&](const Array<Var>& indices) {\n    Array<Var> reduce_indices, non_reduce_indices;\n    for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {\n      if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {\n        reduce_indices.push_back(indices[i]);\n      } else {\n        non_reduce_indices.push_back(indices[i]);\n      }\n    }\n    auto mean = temp_x(non_reduce_indices) / reduce_extent;\n    auto var = temp_x2(non_reduce_indices) / reduce_extent - mean * mean;\n    auto layer_norm = (data(indices) - mean) * tvm::rsqrt(var + make_const(var->dtype, epsilon));\n    layer_norm = topi::multiply(layer_norm, gamma(reduce_indices));\n    if (beta.defined()) {\n      layer_norm = topi::add(layer_norm, beta(reduce_indices));\n    }\n    return layer_norm;\n  };\n  return tvm::te::compute(data->shape, layer_norm_func, name, tag);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_NN_LAYER_NORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/local_response_norm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief local response normalization op constructions\n * \\file nn/local_response_norm.h\n */\n#ifndef TVM_TOPI_NN_LOCAL_RESPONSE_NORM_H_\n#define TVM_TOPI_NN_LOCAL_RESPONSE_NORM_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Local response normalization inference operator\n *\n * \\param data The input tensor. 4-D shape NCHW or NHWC\n * \\param size Integer to define normalisation window size\n * \\param axis Input data layout channel axis\n * \\param alpha Float scaling factor\n * \\param beta Exponent value\n * \\param bias Offset to avoid dividing by zero\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the Local response normalization operation\n */\ninline Tensor lrn(const Tensor& data, int size, int axis = 1, float alpha = 0.0001,\n                  float beta = 0.75, float bias = 2, std::string name = \"tensor\",\n                  std::string tag = kBroadcast) {\n  ICHECK_EQ(data->shape.size(), 4) << \"LRN requires 4-D input\";\n  ICHECK_EQ(size % 2, 1) << \"size should be odd number\";\n  ICHECK(axis == 1 || axis == 3) << \"axis should be 1 or 3 for NCHW and NHWC\";\n  ICHECK(data->dtype.is_float()) << \"datatype should be float\";\n  auto input_shape = data->shape;\n  Array<PrimExpr> pad_before{0, 0, 0, 0};\n  Array<PrimExpr> pad_after{0, 0, 0, 0};\n  pad_before.Set(axis, static_cast<PrimExpr>(size / 2));\n  pad_after.Set(axis, static_cast<PrimExpr>(size / 2));\n  auto pad_data = pad(data, pad_before, pad_after, 0, \"pad_data\");\n  auto rxs = tvm::te::reduce_axis(Range(0, size), \"rxs\");\n  Tensor sqr_sum;\n  if (axis == 1) {\n    sqr_sum = tvm::te::compute(\n        input_shape,\n        [&](Var i, Var l, Var j, Var k) {\n          return tvm::sum(pad_data(i, l + rxs, j, k) * pad_data(i, l + rxs, j, k), {rxs});\n        },\n        \"tensor\", \"sqr_sum\");\n  } else if (axis == 3) {\n    sqr_sum = tvm::te::compute(\n        input_shape,\n        [&](Var i, Var l, Var j, Var k) {\n          return tvm::sum(pad_data(i, l, j, k + rxs) * pad_data(i, l, j, k + rxs), {rxs});\n        },\n        \"tensor\", \"sqr_sum\");\n  }\n  PrimExpr alpha_imm = tvm::te::make_const(data->dtype, alpha);\n  PrimExpr beta_imm = tvm::te::make_const(data->dtype, beta);\n  PrimExpr bias_imm = tvm::te::make_const(data->dtype, bias);\n  auto sqrt_sum_up = tvm::te::compute(\n      input_shape,\n      [&](Var i, Var j, Var k, Var l) {\n        return tvm::pow(bias_imm + (div(alpha_imm * sqr_sum(i, j, k, l), size)), beta_imm);\n      },\n      \"tensor\", kElementWise);\n  return topi::divide(data, sqrt_sum_up);\n}\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_LOCAL_RESPONSE_NORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/mapping.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Mapping op constructions\n * \\file nn/mapping.h\n */\n#ifndef TVM_TOPI_NN_MAPPING_H_\n#define TVM_TOPI_NN_MAPPING_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/tags.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Scale and shift with NCHW order\n *\n * \\param x The input tensor.\n * \\param scale Scale tensor, 1-D of size channel\n * \\param shift Shift tensor, 1-D of size channel\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the scale shift operation\n */\ninline Tensor scale_shift_nchw(const Tensor& x, const Tensor& scale, const Tensor& shift,\n                               std::string name = \"ScaleShift\", std::string tag = kBroadcast) {\n  return tvm::te::compute(\n      x->shape, [&](Var b, Var c, Var h, Var w) { return x(b, c, h, w) * scale(c) + shift(c); },\n      name, tag);\n}\n\n/*!\n * \\brief Scale and shift with NHWC order\n *\n * \\param x The input tensor.\n * \\param scale Scale tensor, 1-D of size channel\n * \\param shift Shift tensor, 1-D of size channel\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the scale shift operation\n */\ninline Tensor scale_shift_nhwc(const Tensor& x, const Tensor& scale, const Tensor& shift,\n                               std::string name = \"ScaleShift\", std::string tag = kBroadcast) {\n  return tvm::te::compute(\n      x->shape, [&](Var b, Var h, Var w, Var c) { return x(b, h, w, c) * scale(c) + shift(c); },\n      name, tag);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_MAPPING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/pooling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Pooling op constructions\n * \\file nn/pooling.h\n */\n#ifndef TVM_TOPI_NN_POOLING_H_\n#define TVM_TOPI_NN_POOLING_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/topi/detail/pad_utils.h>\n#include <tvm/topi/nn.h>\n#include <tvm/topi/reduction.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*! \\brief Pooling type */\nenum PoolType : int {\n  kAvgPool,\n  kMaxPool,\n};\n\ninline Tensor pool_grad_impl(const Tensor& out_grad, const Tensor& x,\n                             const Array<PrimExpr>& kernel_size, const Array<PrimExpr>& stride_size,\n                             const Array<PrimExpr>& padding_size, PoolType pool_type,\n                             bool ceil_mode, const size_t height_axis, const size_t width_axis,\n                             bool count_include_pad) {\n  ICHECK(out_grad->shape.size() >= 2) << \"Pooling grad output must >= 2-D (H, W)\";\n  ICHECK(x->shape.size() >= 2) << \"Pooling input must >= 2-D (H, W)\";\n  ICHECK_EQ(kernel_size.size(), 2) << \"Pooling kernel_size must have 2 elements\";\n  ICHECK_EQ(stride_size.size(), 2) << \"Pooling stride_size must have 2 elements\";\n  ICHECK_EQ(padding_size.size(), 4) << \"Pooling padding_size must have 4 elements\";\n\n  auto kernel_height = cast(DataType::DataType::Int(32), kernel_size[0]);\n  auto kernel_width = cast(DataType::DataType::Int(32), kernel_size[1]);\n  auto stride_height = cast(DataType::DataType::Int(32), stride_size[0]);\n  auto stride_width = cast(DataType::DataType::Int(32), stride_size[1]);\n\n  auto height = cast(DataType::DataType::Int(32), x->shape[height_axis]);\n  auto width = cast(DataType::DataType::Int(32), x->shape[width_axis]);\n\n  auto pad_top = cast(DataType::DataType::Int(32), padding_size[0]);\n  auto pad_left = cast(DataType::DataType::Int(32), padding_size[1]);\n  auto pad_bottom = cast(DataType::DataType::Int(32), padding_size[2]);\n  auto pad_right = cast(DataType::DataType::Int(32), padding_size[3]);\n\n  if (ceil_mode) {\n    // Additional padding to ensure we do ceil instead of floor when\n    // dividing by stride.\n    pad_bottom += stride_height - 1;\n    pad_right += stride_width - 1;\n  }\n\n  Array<PrimExpr> pad_before(std::vector<PrimExpr>(x->shape.size(), 0));\n  pad_before.Set(height_axis, pad_top);\n  pad_before.Set(width_axis, pad_left);\n\n  Array<PrimExpr> pad_after(std::vector<PrimExpr>(x->shape.size(), 0));\n  pad_after.Set(height_axis, pad_bottom);\n  pad_after.Set(width_axis, pad_right);\n  arith::Analyzer analyzer;\n  auto out_height =\n      analyzer.Simplify((height - kernel_height + pad_top + pad_bottom) / stride_height + 1);\n  auto out_width =\n      analyzer.Simplify((width - kernel_width + pad_left + pad_right) / stride_width + 1);\n\n  auto dheight = tvm::te::reduce_axis(Range(0, kernel_height), \"dh\");\n  auto dwidth = tvm::te::reduce_axis(Range(0, kernel_width), \"dw\");\n\n  Array<PrimExpr> data_shape = x->shape;\n  for (size_t i = 0; i < data_shape.size(); ++i) {\n    data_shape.Set(i, cast(DataType::DataType::Int(32), data_shape[i]));\n  }\n\n  Array<PrimExpr> out_shape = data_shape;\n  out_shape.Set(height_axis, out_height);\n  out_shape.Set(width_axis, out_width);\n\n  const int64_t* padding_h0 = as_const_int(pad_top);\n  const int64_t* padding_w0 = as_const_int(pad_left);\n  const int64_t* padding_h1 = as_const_int(pad_bottom);\n  const int64_t* padding_w1 = as_const_int(pad_right);\n  const bool do_pad = ((padding_h0 && *padding_h0) || (padding_w0 && *padding_w0)) ||\n                      ((padding_h1 && *padding_h1) || (padding_w1 && *padding_w1));\n\n  if (pool_type == kMaxPool) {\n    Array<PrimExpr> ravel_shape{data_shape.begin(), data_shape.end()};\n    ravel_shape.Set(height_axis, ravel_shape[height_axis] + pad_top + pad_bottom);\n    ravel_shape.Set(width_axis, ravel_shape[width_axis] + pad_left + pad_right);\n\n    auto windowh =\n        tvm::te::reduce_axis(Range(0, (kernel_height + stride_height - 1) / stride_height), \"wh\");\n    auto windoww =\n        tvm::te::reduce_axis(Range(0, (kernel_width + stride_width - 1) / stride_width), \"ww\");\n\n    auto argmax = MakeArgmaxReducer();\n    auto pad_x = do_pad ? pad(x, pad_before, pad_after, tvm::min_value(x->dtype), \"pad_temp\") : x;\n\n    auto mp_argmax = tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& inds) {\n          Array<PrimExpr> window_inds{inds.begin(), inds.end()};\n          window_inds.Set(height_axis, inds[height_axis] * stride_height + dheight);\n          window_inds.Set(width_axis, inds[width_axis] * stride_width + dwidth);\n          auto idx = detail::RavelIndex(window_inds, ravel_shape);\n          return argmax({idx, pad_x(window_inds)}, {dheight, dwidth}, nullptr);\n        },\n        \"maxpool_grad_argmax\", kCommReduceIdx);\n\n    auto mp_inds = mp_argmax[0];\n\n    return tvm::te::compute(\n        data_shape,\n        [&](const Array<Var>& inds) {\n          Array<PrimExpr> pad_inds{inds.begin(), inds.end()};\n          pad_inds.Set(height_axis, pad_inds[height_axis] + pad_top);\n          pad_inds.Set(width_axis, pad_inds[width_axis] + pad_left);\n          auto idx = detail::RavelIndex(pad_inds, ravel_shape);\n\n          Array<PrimExpr> out_idx{inds.begin(), inds.end()};\n          out_idx.Set(height_axis, (inds[height_axis] + pad_top) / stride_height - windowh);\n          out_idx.Set(width_axis, (inds[width_axis] + pad_left) / stride_width - windoww);\n\n          PrimExpr out_idx_lower_h = tir::Select(\n              pad_inds[height_axis] < kernel_height, make_const(DataType::DataType::Int(32), 0),\n              (pad_inds[height_axis] - kernel_height) / stride_height + 1);\n          PrimExpr out_idx_lower_w = tir::Select(\n              pad_inds[width_axis] < kernel_width, make_const(DataType::DataType::Int(32), 0),\n              (pad_inds[width_axis] - kernel_width) / stride_width + 1);\n\n          return tvm::sum(\n              tvm::if_then_else(tir::And(tir::And(out_idx[height_axis] >= out_idx_lower_h,\n                                                  out_idx[width_axis] >= out_idx_lower_w),\n                                         mp_inds(out_idx) == idx),\n                                out_grad(out_idx), make_const(x->dtype, 0)),\n              {windowh, windoww});\n        },\n        \"T_pool_grad\", \"pool_grad_max\");\n  } else if (pool_type == kAvgPool) {\n    auto windowh =\n        tvm::te::reduce_axis(Range(0, (kernel_height + stride_height - 1) / stride_height), \"wh\");\n    auto windoww =\n        tvm::te::reduce_axis(Range(0, (kernel_width + stride_width - 1) / stride_width), \"ww\");\n    return tvm::te::compute(\n        data_shape,\n        [&](const Array<Var>& inds) {\n          PrimExpr pad_h_idx = inds[height_axis] + pad_top;\n          PrimExpr pad_w_idx = inds[width_axis] + pad_left;\n\n          // output indices whose pooling windows cover current input element (can be out-of-bound)\n          Array<PrimExpr> out_idx{inds.begin(), inds.end()};\n          out_idx.Set(height_axis, (pad_h_idx / stride_height - windowh));\n          out_idx.Set(width_axis, (pad_w_idx / stride_width - windoww));\n\n          PrimExpr out_idx_lower_h =\n              tir::Select(pad_h_idx < kernel_height, make_const(DataType::Int(32), 0),\n                          (pad_h_idx - kernel_height) / stride_height + 1);\n          PrimExpr out_idx_lower_w =\n              tir::Select(pad_w_idx < kernel_width, make_const(DataType::Int(32), 0),\n                          (pad_w_idx - kernel_width) / stride_width + 1);\n\n          PrimExpr divide_factor;  // number of pooled elements\n          if (count_include_pad) {\n            divide_factor = kernel_height * kernel_width;\n          } else {\n            PrimExpr h_start = out_idx[height_axis] * stride_height - pad_top;\n            PrimExpr w_start = out_idx[width_axis] * stride_width - pad_left;\n\n            PrimExpr h_end = min(h_start + kernel_height, height);\n            PrimExpr w_end = min(w_start + kernel_width, width);\n            h_start = max(h_start, make_const(DataType::Int(32), 0));\n            w_start = max(w_start, make_const(DataType::Int(32), 0));\n            divide_factor =\n                max((h_end - h_start) * (w_end - w_start), make_const(DataType::Int(32), 1));\n          }\n          return tvm::sum(\n              tvm::if_then_else(tir::And(tir::And(out_idx[height_axis] >= out_idx_lower_h,\n                                                  out_idx[height_axis] < out_height),\n                                         tir::And(out_idx[width_axis] >= out_idx_lower_w,\n                                                  out_idx[width_axis] < out_width)),\n                                out_grad(out_idx) / divide_factor, make_const(out_grad->dtype, 0)),\n              {windowh, windoww});\n        },\n        \"T_pool_grad\", \"pool_grad_avg\");\n  } else {\n    LOG(ERROR) << \"Unrecognized pool_type: \" << pool_type;\n    return Tensor();\n  }\n}\n\ninline bool find_depth_height_width(const std::string& layout, int* depth_axis, int* height_axis,\n                                    int* width_axis) {\n  *depth_axis = -1;\n  *height_axis = -1;\n  *width_axis = -1;\n  int curr_idx = 0;\n  for (size_t i = 0; i < layout.size(); ++i) {\n    if ((layout[i] >= 'A' && layout[i] <= 'Z') || (layout[i] >= 'a' && layout[i] <= 'z')) {\n      if (layout[i] == 'D') {\n        if (*depth_axis != -1) return false;\n        *depth_axis = curr_idx;\n      } else if (layout[i] == 'H') {\n        if (*height_axis != -1) return false;\n        *height_axis = curr_idx;\n      } else if (layout[i] == 'W') {\n        if (*width_axis != -1) return false;\n        *width_axis = curr_idx;\n      } else if (layout[i] == 'd' || layout[i] == 'h' || layout[i] == 'w') {\n        // do not support split on height or width, e.g., NCHW16w\n        return false;\n      }\n      ++curr_idx;\n    }\n  }\n  if (*depth_axis == -1 || *height_axis == -1 || *width_axis == -1) return false;\n  return true;\n}\n\ninline bool find_height_width(const std::string& layout, int* height_axis, int* width_axis) {\n  int dummy;\n  ICHECK_EQ(find_depth_height_width(layout, &dummy, height_axis, width_axis), false);\n  if (*height_axis != -1 && *width_axis != -1) {\n    return true;\n  }\n  return false;\n}\n\ninline bool find_width(const std::string& layout, int* width_axis) {\n  int dummy;\n  ICHECK_EQ(find_depth_height_width(layout, &dummy, &dummy, width_axis), false);\n  if (*width_axis != -1) {\n    return true;\n  }\n  return false;\n}\n\n/*!\n * \\brief Calculate gradient of pooling on height and width dimension of data.\n *        It decides the height and width dimension according to the layout string,\n *        in which 'W' and 'H' means width and height respectively.\n *        Width and height dimension cannot be split.\n *        For example, NCHW, NCHW16c, etc. are valid for pool,\n *        while NCHW16w, NCHW16h are not.\n *        See \\a layout for more information of the layout string convention.\n * \\param out_grad The output gradient tensor.\n * \\param x The input tensor.\n * \\param kernel_size Vector of two ints: {kernel_height, kernel_width}\n * \\param stride_size Vector of two ints: {stride_height, stride_width}\n * \\param padding_size Vector of two ints: {padding_height, padding_width}\n * \\param pool_type The type of pooling operator\n * \\param ceil_mode Whether to use ceil when calculating the output size\n * \\param layout The input layout. Pooling supports any layout as long as 'H' and 'W' appear.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the split dimension.\n *        For example, NCHW16c can describe a 5-D tensor of\n *        [batch_size, channel, height, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of dimensions\n *        other than `H` and `W`, one can pass `NCHWc` as well.\n * \\param  count_include_pad Whether include padding in the calculation when pool_type is 'avg'\n *\n *\n * \\return The output tensor in the same layout\n */\ninline Tensor pool_grad(const Tensor& out_grad, const Tensor& x, const Array<PrimExpr>& kernel_size,\n                        const Array<PrimExpr>& stride_size, const Array<PrimExpr>& padding_size,\n                        PoolType pool_type, bool ceil_mode, const std::string& layout = \"NCHW\",\n                        bool count_include_pad = true) {\n  int height_axis = -1, width_axis = -1;\n  ICHECK(find_height_width(layout, &height_axis, &width_axis)) << \"Unsupported layout \" << layout;\n  return pool_grad_impl(out_grad, x, kernel_size, stride_size, padding_size, pool_type, ceil_mode,\n                        height_axis, width_axis, count_include_pad);\n}\n\ninline PrimExpr start_index(const Var& out_index, const PrimExpr& odim, const PrimExpr& idim) {\n  return indexdiv(out_index * idim, odim);\n}\n\ninline PrimExpr end_index(const Var& out_index, const PrimExpr& odim, const PrimExpr& idim) {\n  PrimExpr tmp = indexdiv((out_index + 1) * idim, odim);\n  return tvm::tir::Select(indexmod((out_index + 1) * idim, odim) == 0, tmp, tmp + 1);\n}\n\n/*!\n * \\brief Perform adaptive pooling on N dimensional data\n *\n * \\param x The input tensor\n * \\param output_size int vector of size in each dimension\n * \\param pool_type The type of pooling operator\n * \\param axes indices of each dimension\n *\n * \\return The output tensor in same layout order\n */\ninline Tensor adaptive_pool_impl(const Tensor& x, const Array<PrimExpr>& output_size,\n                                 PoolType pool_type, const std::vector<int>& axes) {\n  const auto n_dim = output_size.size();\n  ICHECK_EQ(axes.size(), n_dim) << \"The number of axes not equal to the in/out dimension\";\n\n  Array<PrimExpr> data_shape = x->shape;\n  for (size_t i = 0; i < data_shape.size(); ++i) {\n    data_shape.Set(i, cast(DataType::DataType::Int(32), data_shape[i]));\n  }\n  Array<PrimExpr> out_shape = data_shape;\n  Array<PrimExpr> in_size, out_size;\n  for (size_t i = 0; i < n_dim; ++i) {\n    in_size.push_back(data_shape[axes[i]]);\n    out_size.push_back(cast(DataType::Int(32), output_size[i]));\n    out_shape.Set(axes[i], out_size[i]);\n  }\n\n  auto get_iter_vars = [=](const Array<Var>& output, bool reduce_indices) {\n    Array<PrimExpr> indices;\n    for (size_t i = 0; i < output.size(); ++i) indices.push_back(output[i]);\n    Array<tir::IterVar> reduce_axes;\n    for (size_t i = 0; i < n_dim; ++i) {\n      auto i_start = start_index(output[axes[i]], out_size[i], in_size[i]);\n      auto i_end = end_index(output[axes[i]], out_size[i], in_size[i]);\n      auto rv_name = \"rv\" + std::to_string(i);\n      auto rv_axis = tvm::te::reduce_axis(Range(0, i_end - i_start), rv_name);\n      reduce_axes.push_back(rv_axis);\n      if (reduce_indices) {\n        indices.Set(axes[i], i_start + rv_axis);\n      }\n    }\n    return std::make_tuple(indices, reduce_axes);\n  };\n\n  if (pool_type == kMaxPool) {\n    return tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          Array<tir::IterVar> reduce_axes;\n          std::tie(indices, reduce_axes) = get_iter_vars(output, true);\n          return tvm::max(x(indices), reduce_axes);  // NOLINT(*)\n        },\n        \"tensor\", \"adaptive_pool_max\");\n  } else if (pool_type == kAvgPool) {\n    auto pool_sum = tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          Array<tir::IterVar> reduce_axes;\n          std::tie(indices, reduce_axes) = get_iter_vars(output, true);\n          return tvm::sum(x(indices), reduce_axes);\n        },\n        \"tensor\", \"adaptive_pool_sum\");\n\n    return tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          Array<tir::IterVar> reduce_axes;\n          std::tie(indices, reduce_axes) = get_iter_vars(output, false);\n\n          PrimExpr divide_factor = tvm::cast(x->dtype, 1);\n          for (size_t i = 0; i < n_dim; ++i) {\n            divide_factor *= tvm::cast(x->dtype, reduce_axes[i]->dom->extent);\n          }\n\n          return div(pool_sum(indices), divide_factor);\n        },\n        \"tensor\", kElementWise);\n  } else {\n    LOG(ERROR) << \"Unrecognized pool_type: \" << pool_type;\n    return x;\n  }\n}\n\n/*!\n * \\brief Adaptively perform pooling on height and width dimension of data.\n *        The pooling kernel and stride sizes are automatically chosen for desired output sizes.\n *        It decides the height and width dimension according to the layout string,\n *        in which 'W' and 'H' means width and height respectively.\n *        Width and height dimension cannot be split.\n *        For example, NCHW, NCHW16c, etc. are valid for pool,\n *        while NCHW16w, NCHW16h are not.\n *        See \\a layout for more information of the layout string convention.\n *\n * \\param x The input tensor\n * \\param output_size Vector of two ints: {output_height, output_width}\n * \\param pool_type The type of pooling operator\n * \\param layout The input layout. Pooling supports any layout as long as 'H' and 'W' appear.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the split dimension.\n *        For example, NCHW16c can describe a 5-D tensor of\n *        [batch_size, channel, height, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of dimensions\n *        other than `H` and `W`, one can pass `NCHWc` as well.\n *\n * \\return The output tensor in same layout order\n */\ninline Tensor adaptive_pool(const Tensor& x, const Array<PrimExpr>& output_size, PoolType pool_type,\n                            const std::string& layout = \"NCHW\") {\n  int height_axis = -1, width_axis = -1;\n  ICHECK(find_height_width(layout, &height_axis, &width_axis)) << \"Unsupported layout \" << layout;\n  return adaptive_pool_impl(x, output_size, pool_type, {height_axis, width_axis});\n}\n\n/*!\n * \\brief Adaptively perform pooling on three dimensional data.\n *        See the two dimensional version above for details.\n * \\param x The input tensor\n * \\param output_size Vector of three ints: {output_depth, output_height, output_width}\n * \\param pool_type The type of pooling operator\n * \\param layout The input layout. The default is \"NCDHW\".\n */\ninline Tensor adaptive_pool3d(const Tensor& x, const Array<PrimExpr>& output_size,\n                              PoolType pool_type, const std::string& layout = \"NCDHW\") {\n  int depth_axis = -1, height_axis = -1, width_axis = -1;\n  ICHECK(find_depth_height_width(layout, &depth_axis, &height_axis, &width_axis))\n      << \"Unsupported layout \" << layout;\n  return adaptive_pool_impl(x, output_size, pool_type, {depth_axis, height_axis, width_axis});\n}\n\n/*!\n * \\brief Adaptively perform pooling on one dimensional data.\n *        See the two dimensional version above for details.\n * \\param x The input tensor\n * \\param output_size Vector of one int: {output_width}\n * \\param pool_type The type of pooling operator\n * \\param layout The input layout. The default is \"NCW\".\n */\ninline Tensor adaptive_pool1d(const Tensor& x, const Array<PrimExpr>& output_size,\n                              PoolType pool_type, const std::string& layout = \"NCW\") {\n  int width_axis = -1;\n  ICHECK(find_width(layout, &width_axis)) << \"Unsupported layout \" << layout;\n  return adaptive_pool_impl(x, output_size, pool_type, {width_axis});\n}\n\n/*!\n * \\brief Perform global pooling on height and width dimension of data.\n *        It decides the height and width dimension according to the layout string,\n *        in which 'W' and 'H' means width and height respectively.\n *        Width and height dimension cannot be split.\n *        For example, NCHW, NCHW16c, ... are valid for global_pool,\n *        while NCHW16w, NCHW16h are not.\n *        See \\a layout for more information of the layout string convention.\n *\n * \\param x The input tensor represent as layout\n * \\param pool_type The type of pooling operator\n * \\param layout The input layout. global-pooling supports any layout as long as 'H' and 'W' appear.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the sub-dimension.\n *        For example, `NCHW16c` can describe a 5-D tensor of\n *        [batch_size, channel, height, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of\n *        dimensions other than `H` and `W`, one can pass `NCHWc` as well.\n *\n * \\return The output tensor in same layout with height and width dimension size of 1.\n *         e.g., for NCHW, the output shape will be [batch, channel, 1, 1]\n */\ninline Tensor global_pool(const Tensor& x, PoolType pool_type, const std::string& layout = \"NCHW\") {\n  return adaptive_pool(x, Array<PrimExpr>{1, 1}, pool_type, layout);\n}\n\n/*!\n * \\brief Perform pooling on N-dimension of data.\n *\n * \\param x The input tensor\n * \\param kernel_size Vector of N ints\n * \\param stride_size Vector of N ints\n * \\param dilation_size Vector of N ints\n * \\param padding_size Vector of N*2 ints [head_pad_d1, head_pad_d2, ...,\n *        head_pad_dN, tail_pad_d1, tail_pad_d2, ..., tail_pad_dN]\n * \\param pool_type The type of pooling operator\n * \\param ceil_mode Whether to use ceil when calculating the output size\n * \\param axis Vector of indices for the N dimensions\n * \\param count_include_pad Whether include padding in the calculation\n *\n * \\return The output tensor in same layout order\n */\ninline Tensor pool_impl_nd(const Tensor& x, const Array<PrimExpr>& kernel_size,\n                           const Array<PrimExpr>& stride_size, const Array<PrimExpr>& dilation_size,\n                           const Array<PrimExpr>& padding_size, PoolType pool_type, bool ceil_mode,\n                           const std::vector<int>& axis, bool count_include_pad) {\n  int k_size = kernel_size.size();\n  int x_size = x->shape.size();\n  ICHECK_EQ(stride_size.size(), k_size) << \"Pooling stride_size must have same elements as kernel\";\n  ICHECK_EQ(padding_size.size(), k_size * 2) << \"Pooling padding_size must has double elements of\"\n                                                \" kernel\";\n  ICHECK_EQ(axis.size(), k_size) << \"axis must have same elements as kernel\";\n\n  Array<IterVar> daxis;\n  std::vector<PrimExpr> kernel(k_size);\n  std::vector<PrimExpr> stride(k_size);\n  std::vector<PrimExpr> dilation(k_size);\n  std::vector<PrimExpr> pad_head(k_size);\n  std::vector<PrimExpr> pad_tail(k_size);\n  std::vector<PrimExpr> offset(k_size, 0);\n  Array<PrimExpr> pad_before(std::vector<PrimExpr>(x_size, 0));\n  Array<PrimExpr> pad_after(std::vector<PrimExpr>(x_size, 0));\n  Array<PrimExpr> data_shape = x->shape;\n  for (size_t i = 0; i < data_shape.size(); ++i) {\n    data_shape.Set(i, cast(DataType::DataType::Int(32), data_shape[i]));\n  }\n  Array<PrimExpr> out_shape = data_shape;\n\n  bool do_pad = false;\n  for (int i = 0; i < k_size; i++) {\n    int ii = axis[i];\n    kernel[i] = cast(DataType::Int(32), kernel_size[i]);\n    stride[i] = cast(DataType::Int(32), stride_size[i]);\n    dilation[i] = cast(DataType::Int(32), dilation_size[i]);\n    pad_head[i] = cast(DataType::Int(32), padding_size[i]);\n    pad_tail[i] = cast(DataType::Int(32), padding_size[i + k_size]);\n\n    if (ceil_mode) {\n      // The offset[i] is an additional padding to ensure we do ceil instead of floor when\n      // dividing by stride.\n      // In the case of ceil_mode=True and count_include_pad=True,\n      // in order to obtain the correct boundary,\n      // we also need to use the offset[i] to eliminate this extra padding.\n      offset[i] = stride[i] - 1;\n      pad_tail[i] += offset[i];\n    }\n\n    const int64_t* padding0 = as_const_int(pad_head[i]);\n    const int64_t* padding1 = as_const_int(pad_tail[i]);\n    do_pad = do_pad || (padding0 && *padding0) || (padding1 && *padding1);\n\n    daxis.push_back(tvm::te::reduce_axis(Range(0, kernel[i]), \"rv\" + std::to_string(i)));\n\n    pad_before.Set(ii, pad_head[i]);\n    pad_after.Set(ii, pad_tail[i]);\n\n    arith::Analyzer analyzer;\n\n    PrimExpr numerator =\n        data_shape[ii] - (kernel[i] - 1) * dilation[i] - 1 + pad_head[i] + pad_tail[i];\n    auto out_dim = analyzer.Simplify(indexdiv(numerator, stride[i]) + 1);\n    out_shape.Set(ii, out_dim);\n  }\n\n  if (pool_type == kMaxPool) {\n    auto temp = do_pad ? pad(x, pad_before, pad_after, tvm::min_value(x->dtype), \"pad_temp\") : x;\n    return tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          for (const Var& var : output) indices.push_back(var);\n\n          for (int i = 0; i < k_size; i++) {\n            int ii = axis[i];\n            indices.Set(ii, output[ii] * stride[i] + daxis[i] * dilation[i]);\n          }\n          return tvm::max(temp(indices), daxis);\n        },\n        \"tensor\", \"pool_max\");\n  } else if (pool_type == kAvgPool) {\n    // Pad the inputs\n    auto temp = do_pad ? pad(x, pad_before, pad_after, 0, \"pad_temp\") : x;\n\n    // TVM compute for summing the pooling window.\n    auto pool_sum = tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          for (const Var& var : output) indices.push_back(var);\n\n          for (int i = 0; i < k_size; i++) {\n            int ii = axis[i];\n            indices.Set(ii, output[ii] * stride[i] + daxis[i] * dilation[i]);\n          }\n          return tvm::sum(temp(indices), daxis);\n        },\n        \"tensor\", \"pool_sum\");\n\n    // TVM compute for dividing the reduced window sum by kernel size.\n    return tvm::te::compute(\n        out_shape,\n        [&](const Array<Var>& output) {\n          Array<PrimExpr> indices;\n          for (const Var& var : output) indices.push_back(var);\n          if (count_include_pad) {\n            std::vector<PrimExpr> start(k_size);\n            std::vector<PrimExpr> end(k_size);\n            auto num_el = make_const(DataType::Int(32), 1);\n            for (int i = 0; i < k_size; i++) {\n              int ii = axis[i];\n              start[i] = output[ii] * stride[i] - pad_head[i];\n              // When computing the output shape in ceil_mode,\n              // we have added the extra padding of offset[i],\n              // so now in order to calculate the correct boundary ,\n              // we need to substract the offset[i].\n              end[i] = start[i] + (kernel[i] - 1) * dilation[i];\n              end[i] = min(end[i], data_shape[ii] + pad_tail[i] - 1 - offset[i]);\n              num_el *= (end[i] - start[i]) / dilation[i] + 1;\n            }\n            return div(pool_sum(indices), num_el);\n          } else {\n            std::vector<PrimExpr> start(k_size);\n            std::vector<PrimExpr> end(k_size);\n            auto num_el = make_const(DataType::Int(32), 1);\n            for (int i = 0; i < k_size; i++) {\n              int ii = axis[i];\n\n              // Let start and end contain the first and last index of our Tensor\n              // along the relevant dimension we use in our calculation.\n              // Assume indices -1, -2 represent the padding before (tail) and\n              // len(arr), len(arr) + 1 represent the padding after (head).\n              start[i] = output[ii] * stride[i] - pad_head[i];\n              end[i] = start[i] + (kernel[i] - 1) * dilation[i];\n\n              // if start[i] < 0, e.g. we start on a tail padded number this will be a positive\n              // number that represents the number of steps along the dilated kernel to reach a\n              // non-padded value. Otherwise this should be 0.\n              PrimExpr jumps_to_non_pad = (dilation[i] - 1 - start[i]) / dilation[i];\n              jumps_to_non_pad = max(jumps_to_non_pad, make_const(DataType::Int(32), 0));\n\n              end[i] = min(end[i], data_shape[ii] - 1);\n              num_el *= (end[i] - (start[i] + dilation[i] * jumps_to_non_pad)) / dilation[i] + 1;\n            }\n\n            PrimExpr divide_factor = max(num_el, make_const(DataType::Int(32), 1));\n            return div(pool_sum(indices), divide_factor);\n          }\n        },\n        \"tensor\", kElementWise);\n  } else {\n    LOG(ERROR) << \"Unrecognized pool_type: \" << pool_type;\n    return x;\n  }\n}\n\n/*!\n * \\brief Perform pooling on the width dimension of data.\n *        Width axis is determined by the layout string\n *        in which 'W' means width.\n *        Width dimension cannot be split.\n *        For example, NCW, NCW16c, etc. are valid for pool,\n *        while NCW16w is not.\n *        See \\a layout for more information of the layout string convention.\n * \\param x The input tensor.\n * \\param kernel_size Vector of one int: {kernel_width}\n * \\param stride_size Vector of one int: {stride_width}\n * \\param dilation_size Vector of one int: {dilation_width}\n * \\param padding_size Vector of two ints: {head_pad_width, tail_pad_width}\n * \\param pool_type The type of pooling operator\n * \\param ceil_mode Whether to use ceil when calculating the output size\n * \\param layout The input layout. Pooling supports any layout as long as 'W' appears.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the split dimension.\n *        For example, NCW16c can describe a 4-D tensor of\n *        [batch_size, channel, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of dimensions\n *        other than `W`, one can pass `NCWc` as well.\n * \\param  count_include_pad Whether include padding in the calculation when pool_type is 'avg'\n *\n *\n * \\return The output tensor in the same layout\n */\ninline Tensor pool1d(const Tensor& x, const Array<PrimExpr>& kernel_size,\n                     const Array<PrimExpr>& stride_size, const Array<PrimExpr>& dilation_size,\n                     const Array<PrimExpr>& padding_size, PoolType pool_type, bool ceil_mode,\n                     const std::string& layout = \"NCW\", bool count_include_pad = true) {\n  int width_axis = -1;\n  ICHECK(find_width(layout, &width_axis)) << \"Unsupported layout \" << layout;\n  std::vector<int> axis = {width_axis};\n  return pool_impl_nd(x, kernel_size, stride_size, dilation_size, padding_size, pool_type,\n                      ceil_mode, axis, count_include_pad);\n}\n\n/*!\n * \\brief Perform pooling on height and width dimension of data.\n *        It decides the height and width dimension according to the layout string,\n *        in which 'W' and 'H' means width and height respectively.\n *        Width and height dimension cannot be split.\n *        For example, NCHW, NCHW16c, etc. are valid for pool,\n *        while NCHW16w, NCHW16h are not.\n *        See \\a layout for more information of the layout string convention.\n * \\param x The input tensor.\n * \\param kernel_size Vector of two ints: {kernel_height, kernel_width}\n * \\param stride_size Vector of two ints: {stride_height, stride_width}\n * \\param dilation_size Vector of two ints: {dilation_height, dilation_width}\n * \\param padding_size Vector of two ints: {padding_height, padding_width}\n * \\param pool_type The type of pooling operator\n * \\param ceil_mode Whether to use ceil when calculating the output size\n * \\param layout The input layout. Pooling supports any layout as long as 'H' and 'W' appear.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the split dimension.\n *        For example, NCHW16c can describe a 5-D tensor of\n *        [batch_size, channel, height, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of dimensions\n *        other than `H` and `W`, one can pass `NCHWc` as well.\n * \\param  count_include_pad Whether include padding in the calculation when pool_type is 'avg'\n *\n *\n * \\return The output tensor in the same layout\n */\ninline Tensor pool2d(const Tensor& x, const Array<PrimExpr>& kernel_size,\n                     const Array<PrimExpr>& stride_size, const Array<PrimExpr>& dilation_size,\n                     const Array<PrimExpr>& padding_size, PoolType pool_type, bool ceil_mode,\n                     const std::string& layout = \"NCHW\", bool count_include_pad = true) {\n  int height_axis = -1, width_axis = -1;\n  ICHECK(find_height_width(layout, &height_axis, &width_axis)) << \"Unsupported layout \" << layout;\n  std::vector<int> axis = {height_axis, width_axis};\n  return pool_impl_nd(x, kernel_size, stride_size, dilation_size, padding_size, pool_type,\n                      ceil_mode, axis, count_include_pad);\n}\n\n/*!\n * \\brief Perform pooling on depth, height and width dimension of data.\n *        It decides the depth, height and width dimension according to the layout string,\n *        in which 'D', 'W' and 'H' means depth, width and height respectively.\n *        Depth, Width and height dimension cannot be split.\n *        For example, NCDHW, NCDHW16c, etc. are valid for pool,\n *        while NCDHW16d, NCDHW16w or NCDHW16h are not.\n *        See \\a layout for more information of the layout string convention.\n * \\param x The input tensor.\n * \\param kernel_size Vector of three ints: {kernel_depth, kernel_height, kernel_width}\n * \\param stride_size Vector of three ints: {stride_depth, stride_height, stride_width}\n * \\param dilation_size Vector of three ints: {dilation_depth, dilation_height, dilation_width}\n * \\param padding_size Vector of six ints: {head_pad_depth, head_pad_height, head_pad_width,\n *        tail_pad_depth, tail_pad_height, tail_pad_width}\n * \\param pool_type The type of pooling operator\n * \\param ceil_mode Whether to use ceil when calculating the output size\n * \\param layout The input layout. Pooling supports any layout as long as 'D', 'H' and 'W' appear.\n *        The layout is supposed to be composed of upper cases, lower cases and (optional) numbers,\n *        where upper case indicates a dimension and\n *        the corresponding lower case (with factor size) indicates the split dimension.\n *        For example, NCDHW16c can describe a 6-D tensor of\n *        [batch_size, channel, depth, height, width, channel_block].\n *        (in which factor size `16` will not be used in pooling but for other operators,\n *        it can be used to decide the output shape).\n *        Since pooling does not care about the factor size of dimensions\n *        other than `D`, `H` and `W`, one can pass `NCDHWc` as well.\n * \\param  count_include_pad Whether include padding in the calculation when pool_type is 'avg'\n *\n *\n * \\return The output tensor in the same layout\n */\ninline Tensor pool3d(const Tensor& x, const Array<PrimExpr>& kernel_size,\n                     const Array<PrimExpr>& stride_size, const Array<PrimExpr>& dilation_size,\n                     const Array<PrimExpr>& padding_size, PoolType pool_type, bool ceil_mode,\n                     const std::string& layout = \"NCDHW\", bool count_include_pad = true) {\n  int depth_axis = -1, height_axis = -1, width_axis = -1;\n  ICHECK(find_depth_height_width(layout, &depth_axis, &height_axis, &width_axis))\n      << \"Unsupported layout \" << layout;\n  std::vector<int> axis = {depth_axis, height_axis, width_axis};\n  return pool_impl_nd(x, kernel_size, stride_size, dilation_size, padding_size, pool_type,\n                      ceil_mode, axis, count_include_pad);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_POOLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/nn/softmax.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Softmax op constructions\n * \\file nn/softmax.h\n */\n#ifndef TVM_TOPI_NN_SOFTMAX_H_\n#define TVM_TOPI_NN_SOFTMAX_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/reduction.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace nn {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Softmax activation\n *\n * \\param x The input tensor. Can be any dimension\n * \\param axis The channel axis along which softmax is performed\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the softmax operation\n */\ninline Tensor softmax(const Tensor& x, int axis = -1, std::string name = \"tensor\",\n                      std::string tag = \"softmax_output\") {\n  auto input_shape = x->shape;\n  auto ndim = input_shape.size();\n  if (axis < 0) {\n    axis = ndim + axis;\n  }\n  ICHECK_LT(axis, ndim) << \"axis parameter should be less than input dim\";\n\n  auto k1 = tvm::te::reduce_axis(Range(0, input_shape[axis]), \"k1\");\n  auto k2 = tvm::te::reduce_axis(Range(0, input_shape[axis]), \"k2\");\n  auto reduced_shape = MakeReduceTargetShape({axis}, x, false, false);\n\n  tvm::Map<String, ObjectRef> attrs;\n  attrs.Set(\"axis\", Integer(axis));\n\n  auto insert_reduce_index = [axis, ndim](const Array<Var>& indices, const IterVar& reduce_index) {\n    Array<PrimExpr> eval_range;\n    int arg_counter = 0;\n    for (size_t i = 0; i < ndim; ++i) {\n      if (static_cast<int>(i) == axis) {\n        eval_range.push_back(reduce_index);\n      } else {\n        eval_range.push_back(indices[arg_counter++]);\n      }\n    }\n    return eval_range;\n  };\n\n  auto get_non_reduce_indices = [axis, ndim](const Array<Var>& indices) {\n    Array<PrimExpr> non_reduce_indices;\n    for (size_t i = 0; i < ndim; ++i) {\n      if (static_cast<int>(i) != axis) non_reduce_indices.push_back(indices[i]);\n    }\n    return non_reduce_indices;\n  };\n\n  auto _compute_max = [&](const Array<Var>& indices) {\n    auto eval_range = insert_reduce_index(indices, k1);\n    return topi::MaxOp(x(eval_range), {k1});\n  };\n\n  auto _compute_exp = [&](const Tensor& max_elem, const Array<Var>& indices) {\n    auto non_reduce_indices = get_non_reduce_indices(indices);\n    return tvm::exp(x(indices) - max_elem(non_reduce_indices));\n  };\n\n  auto _compute_expsum = [&](const Tensor& exp, const Array<Var>& indices) {\n    auto eval_range = insert_reduce_index(indices, k2);\n    return tvm::sum(exp(eval_range), {k2});\n  };\n\n  auto _normalize = [&](const Tensor& exp, const Tensor& expsum, const Array<Var>& indices) {\n    auto non_reduce_indices = get_non_reduce_indices(indices);\n    return exp(indices) / expsum(non_reduce_indices);\n  };\n\n  auto max_elem = tvm::te::compute(reduced_shape, _compute_max);\n  auto exp = tvm::te::compute(\n      input_shape, [&](const Array<Var>& indices) { return _compute_exp(max_elem, indices); });\n  auto expsum = tvm::te::compute(\n      reduced_shape, [&](const Array<Var>& indices) { return _compute_expsum(exp, indices); });\n  return tvm::te::compute(\n      input_shape, [&](const Array<Var>& indices) { return _normalize(exp, expsum, indices); },\n      name, tag, attrs);\n}\n\n/*!\n * \\brief Log softmax activation\n *\n * \\param x The input tensor. 2-D where log softmax is performed along the second dimension\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the log softmax operation\n */\ninline Tensor log_softmax(const Tensor& x, std::string name = \"tensor\",\n                          std::string tag = \"log_softmax_output\") {\n  ICHECK_EQ(x->shape.size(), 2) << \"Log softmax requires 2-D input\";\n\n  PrimExpr m = x->shape[0];\n  PrimExpr n = x->shape[1];\n\n  auto k = tvm::te::reduce_axis(Range(0, n), \"k\");\n  auto max_elem =\n      tvm::te::compute({m}, [&](Var i) { return tvm::max(x(i, k), Array<IterVar>{k}); });\n  k = tvm::te::reduce_axis(Range(0, n), \"k\");\n\n  auto expsum =\n      tvm::te::compute({m}, [&](Var i) { return tvm::sum(tvm::exp(x(i, k) - max_elem(i)), {k}); });\n\n  return tvm::te::compute(\n      x->shape, [&](Var i, Var j) { return x(i, j) - max_elem(i) - tvm::log(expsum(i)); }, name,\n      tag);\n}\n\n}  // namespace nn\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_NN_SOFTMAX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/reduction.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file topi/reduction.h\n * \\brief Reduction op constructors\n */\n#ifndef TVM_TOPI_REDUCTION_H_\n#define TVM_TOPI_REDUCTION_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/broadcast.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/detail/ravel_unravel.h>\n#include <tvm/topi/elemwise.h>\n#include <tvm/topi/tags.h>\n#include <tvm/topi/transform.h>\n\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\n/*! \\brief The operation to use for CommReduce */\nusing FReduce = std::function<PrimExpr(PrimExpr source, const Array<IterVar>& axis,\n                                       Array<PrimExpr> init, Span span)>;\n\n/*! \\brief The operation to use for CommReduceIdx */\nusing FCommReduce = std::function<Array<PrimExpr>(Array<PrimExpr> exprs, const Array<IterVar>& axis,\n                                                  PrimExpr* condition)>;\n\n/*!\n * \\brief Convert a reduction axis which could be empty or have negative\n * elements into a real axis with valid dimension indices.\n *\n * \\param ndim Number of dimensions in the target.\n * \\param axis The axis parameter.\n *\n * \\return A non-empty sorted array of valid dimension indices, with no duplicates.\n * If the input axis is empty, the result will be an axis including all dimensions.\n * If any input element is negative, it will be treated as an offset from the\n * last dimension (same as python indexing rules).\n */\ninline std::vector<int> GetRealAxis(int ndim, const Array<Integer>& axis) {\n  std::vector<int> real_axis;\n  if (!axis.defined() || axis.size() == 0) {\n    for (int i = 0; i < ndim; ++i) {\n      real_axis.push_back(i);\n    }\n  } else {\n    // Use a set so duplicates are removed and the dims are sorted\n    for (auto elem : axis) {\n      int64_t val = elem->value;\n      if (val < 0) {\n        val += ndim;\n      }\n      ICHECK_LE(val, ndim) << \" exceeds the maximum dimension \" << ndim;\n      ICHECK_GE(val, 0);\n      real_axis.push_back(static_cast<int>(val));\n    }\n    std::sort(real_axis.begin(), real_axis.end());\n    real_axis.resize(std::unique(real_axis.begin(), real_axis.end()) - real_axis.begin());\n  }\n  return real_axis;\n}\n\n/*! \\brief Enumerate the axes for a reduce op */\ninline Array<IterVar> MakeReduceAxes(const std::vector<int>& real_axis, const Tensor& data) {\n  Array<IterVar> reduce_axes;\n  for (auto i : real_axis) {\n    std::string name = \"k\" + std::to_string(i);\n    reduce_axes.push_back(tvm::te::reduce_axis(Range(0, data->shape[i]), name));\n  }\n  return reduce_axes;\n}\n\n/*! \\brief Calculate the target shape for a reduce op */\ninline Array<PrimExpr> MakeReduceTargetShape(const std::vector<int>& real_axis, const Tensor& data,\n                                             bool keepdims, bool atleast1d) {\n  auto ndim = data->shape.size();\n  Array<PrimExpr> target_shape;\n  if (keepdims) {\n    for (size_t i = 0; i < ndim; ++i) {\n      if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {\n        // real_axis contains i\n        target_shape.push_back(1);\n      } else {\n        target_shape.push_back(data->shape[i]);\n      }\n    }\n  } else {\n    for (size_t i = 0; i < ndim; ++i) {\n      if (std::find(real_axis.begin(), real_axis.end(), i) == real_axis.end()) {\n        // real_axis does not contain i\n        target_shape.push_back(data->shape[i]);\n      }\n    }\n  }\n  if (target_shape.size() == 0 && atleast1d) {\n    target_shape.push_back(1);\n  }\n  return target_shape;\n}\n\n/*!\n * \\brief Create a reduction operation.\n *\n * \\param data The input tensor.\n * \\param func The reduction function eg. tvm::sum\n * \\param target_shape The output Tensor shape.\n * \\param reduce_axes The real axes along which the reduction is performed.\n * \\param squeeze_axes The real axes to squeeze. Unsqueezed, reduced axes will\n *                     have shape 1 in the output tensor.\n * \\param span The location of this reducer in the source.\n *\n * \\return The result tensor.\n */\ninline Tensor DoCommReduce(const Tensor& data, FReduce func, const Array<PrimExpr>& target_shape,\n                           const std::vector<int>& reduce_axes,\n                           const std::vector<int>& squeeze_axes, Span span = Span()) {\n  auto r_axes = MakeReduceAxes(reduce_axes, data);\n  auto compute = [&](const Array<Var>& indices) {\n    Array<PrimExpr> eval_range;\n    Array<Var> eval_indices;\n    int arg_counter = 0;\n    int red_counter = 0;\n\n    for (size_t i = 0; i < data->shape.size(); ++i) {\n      bool squeeze_i = std::find(squeeze_axes.begin(), squeeze_axes.end(), i) != squeeze_axes.end();\n      if (std::find(reduce_axes.begin(), reduce_axes.end(), i) != reduce_axes.end()) {\n        // real_axis contains i\n        eval_range.push_back(r_axes[red_counter]);\n        eval_indices.push_back(r_axes[red_counter]->var);\n        red_counter++;\n        arg_counter += !squeeze_i;\n        continue;\n      }\n      eval_range.push_back(indices[arg_counter]);\n      arg_counter++;\n    }\n\n    return func(data(eval_range), r_axes, {}, span);\n  };\n\n  return tvm::te::compute(target_shape, compute, data->op->name + \"_red\", kCommReduce);\n}\n\n/*!\n * \\brief Create a reduction operation.\n *\n * \\param data The input tensor.\n * \\param axis The axes along which the reduction is performed.\n * \\param func The reduction function eg. tvm::sum\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return The result tensor.\n */\ninline Tensor CommReduce(const Tensor& data, const Array<Integer>& axis, FReduce func,\n                         bool keepdims, bool atleast1d) {\n  auto ndim = data->shape.size();\n  ICHECK_NE(ndim, 0) << \"Cannot reduce a 0 dim Tensor\";\n  auto real_axis = GetRealAxis(static_cast<int>(ndim), axis);\n  auto target_shape = MakeReduceTargetShape(real_axis, data, keepdims, atleast1d);\n  return DoCommReduce(data, func, target_shape, real_axis,\n                      keepdims ? std::vector<int>() : real_axis);\n}\n\n/*!\n * \\brief Create an index reduction operation.\n *\n * \\param data The input tensor.\n * \\param axis The axes along which the reduction is performed.\n * \\param func The reduction function\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return The result tensor.\n */\ninline Tensor CommReduceIdx(const Tensor& data, const Array<Integer>& axis, FCommReduce func,\n                            bool keepdims, bool atleast1d) {\n  auto ndim = data->shape.size();\n  ICHECK_NE(ndim, 0) << \"Cannot reduce a 0 dim Tensor\";\n  auto real_axis = GetRealAxis(static_cast<int>(ndim), axis);\n  auto reduce_axes = MakeReduceAxes(real_axis, data);\n  auto target_shape = MakeReduceTargetShape(real_axis, data, keepdims, atleast1d);\n\n  auto compute = [ndim, keepdims, &real_axis, &reduce_axes, &func,\n                  &data](const Array<Var>& indices) {\n    Array<PrimExpr> eval_range;\n    Array<PrimExpr> eval_indices;\n    int arg_counter = 0;\n    int red_counter = 0;\n\n    for (size_t i = 0; i < ndim; ++i) {\n      if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {\n        // real_axis contains i\n        eval_range.push_back(reduce_axes[red_counter]);\n        eval_indices.push_back(reduce_axes[red_counter]->var);\n        red_counter++;\n      } else {\n        if (!keepdims) {\n          eval_range.push_back(indices[arg_counter]);\n          arg_counter++;\n        } else {\n          eval_range.push_back(indices[i]);\n        }\n      }\n    }\n\n    Array<PrimExpr> ravel_shape;\n    for (auto i : real_axis) {\n      ravel_shape.push_back(data->shape[i]);\n    }\n    auto idx = detail::RavelIndex(eval_indices, ravel_shape);\n    return func({idx, data(eval_range)}, reduce_axes, nullptr);\n  };\n\n  auto temp_idx_val =\n      tvm::te::compute(target_shape, compute, data->op->name + \"_red_temp\", kCommReduceIdx);\n  auto temp_idx = temp_idx_val[0];\n  auto temp_val = temp_idx_val[1];\n  return tvm::te::compute(\n      target_shape, [&temp_idx](const Array<Var>& indices) { return temp_idx(indices); },\n      data->op->name + \"_red\", kCommReduceIdx);\n}\n\n/*! \\brief A combiner function for a reduction */\nusing FCombine = std::function<Array<PrimExpr>(Array<Var> lhs, Array<Var> rhs)>;\n\n/*! \\brief An initializer function for a reduction */\nusing FIdentity = std::function<Array<PrimExpr>(std::vector<DataType> types)>;\n\n/*!\n * \\brief Create a commutative reducer for a reduction\n *\n * \\param fcombine A function to combine exprs\n * \\param fidentity A function to initialize elements\n * \\param name The name of the operation\n *\n * \\return A reducer function which creates a reduce expression over an axis.\n */\ninline FCommReduce MakeCommReducer(FCombine fcombine, FIdentity fidentity,\n                                   std::string name = \"reduce\") {\n  return [fcombine, fidentity, name](Array<PrimExpr> exprs, const Array<IterVar>& axis,\n                                     PrimExpr* condition) {\n    Array<Var> lhs, rhs;\n    std::vector<DataType> dtypes;\n\n    for (size_t i = 0; i < exprs.size(); ++i) {\n      auto dtype = exprs[i].dtype();\n      dtypes.push_back(dtype);\n      lhs.push_back(var(name + \"_lhs_\" + std::to_string(i), dtype));\n      rhs.push_back(var(name + \"_rhs_\" + std::to_string(i), dtype));\n    }\n\n    auto result = fcombine(lhs, rhs);\n    auto id_elem = fidentity(dtypes);\n    auto cond = condition != nullptr ? *condition : tir::const_true();\n\n    auto combiner = tvm::tir::CommReducer(lhs, rhs, result, id_elem);\n    Array<PrimExpr> outputs;\n    for (size_t i = 0; i < exprs.size(); ++i) {\n      outputs.push_back(tvm::tir::Reduce(combiner, exprs, axis, cond, static_cast<int>(i), {}));\n    }\n    return outputs;\n  };\n}\n\n/*! \\brief Wrap tvm::min to ensure we get the correct overload */\ninline PrimExpr MinOp(PrimExpr source, Array<IterVar> axis, Array<PrimExpr> init = {},\n                      Span span = Span()) {\n  return tvm::min(source, axis, init, span);\n}\n\n/*! \\brief Wrap tvm::max to ensure we get the correct overload */\ninline PrimExpr MaxOp(PrimExpr source, Array<IterVar> axis, Array<PrimExpr> init = {},\n                      Span span = Span()) {\n  return tvm::max(source, axis, init, span);  // NOLINT(*)\n}\n\n/*! \\brief Wrap tvm::prod to ensure we get the correct overload */\ninline PrimExpr ProdOp(PrimExpr source, Array<IterVar> axis, Array<PrimExpr> init = {},\n                       Span span = Span()) {\n  return tvm::prod(source, axis, init, span);  // NOLINT(*)\n}\n\n/*!\n * \\brief Creates an operation that sums array elements over a given axis\n *\n * \\param data The input tensor\n * \\param axis The axis to sum over. If axis is empty, the operation will\n * sum over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the sum operation\n */\ninline Tensor sum(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                  bool atleast1d = false) {\n  return CommReduce(data, axis, tvm::sum, keepdims, atleast1d);\n}\n\ninline Tensor collapse_sum(const Tensor& data, Array<PrimExpr> target_shape) {\n  ICHECK_GE(data->shape.size(), target_shape.size());\n  auto ishape = detail::GetConstIntValues(data->shape, \"ishape\");\n  auto oshape = detail::GetConstIntValues(target_shape, \"oshape\");\n\n  std::vector<int> reduce_axes;\n  std::vector<int> squeeze_axes;\n  for (int i_ax = ishape.size() - 1, o_ax = oshape.size() - 1; i_ax >= 0; --i_ax) {\n    if (o_ax >= 0 && ishape[i_ax] == oshape[o_ax]) {\n      --o_ax;\n      continue;\n    }\n    reduce_axes.push_back(i_ax);\n    if (o_ax < 0) {  // squeeze o_ax if was added during expansion\n      squeeze_axes.push_back(i_ax);\n    } else if (oshape[o_ax] == 1) {\n      --o_ax;\n    }\n  }\n\n  if (reduce_axes.size() == 0) return topi::identity(data, \"tensor\", kCommReduce);\n\n  std::reverse(reduce_axes.begin(), reduce_axes.end());\n  std::reverse(squeeze_axes.begin(), squeeze_axes.end());\n  return DoCommReduce(data, tvm::sum, target_shape, reduce_axes, squeeze_axes);\n}\n\n/*!\n * \\brief Creates an operation that computes the logical AND of elements\n * over a given axis\n *\n * \\param data The input boolean tensor\n * \\param axis The axes to reduce. If axis is empty, the operation will\n * perform logical AND over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the all operation\n */\ninline Tensor all(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                  bool atleast1d = false) {\n  return CommReduce(data, axis, tvm::all, keepdims, atleast1d);\n}\n\n/*!\n * \\brief Creates an operation that computes the logical OR of elements\n * over a given axis\n *\n * \\param data The input boolean tensor\n * \\param axis The axes to reduce. If axis is empty, the operation will\n * perform logical OR over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the all operation\n */\ninline Tensor any(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                  bool atleast1d = false) {\n  return CommReduce(data, axis, tvm::any, keepdims, atleast1d);\n}\n\n/*!\n * \\brief Creates an operation that finds the minimum of elements over\n * a given axis.\n *\n * \\param data The input tensor\n * \\param axis The axis to find the minimum over. If axis is empty, the\n * operation will find the minimum over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the min operation\n */\ninline Tensor min(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                  bool atleast1d = false) {\n  return CommReduce(data, axis, MinOp, keepdims, atleast1d);\n}\n\n/*!\n * \\brief Creates an operation that finds the maximum of elements over\n * a given axis.\n *\n * \\param data The input tensor\n * \\param axis The axis to find the maximum over. If axis is empty, the\n * operation will find the maximum over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the max operation\n */\ninline Tensor max(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                  bool atleast1d = false) {\n  return CommReduce(data, axis, MaxOp, keepdims, atleast1d);\n}\n\ninline FCommReduce MakeArgminReducer(bool select_last_index = false) {\n  // Create a Commutative Reducer with a comparison operation, and method to get the initial value.\n  auto fcombine = [=](Array<Var> lhs, Array<Var> rhs) {\n    Array<PrimExpr> result;\n\n    // Casting to avoid operator ambiguity\n    PrimExpr lhs_idx = static_cast<PrimExpr>(lhs[0]);\n    PrimExpr rhs_idx = static_cast<PrimExpr>(rhs[0]);\n    PrimExpr lhs_val = static_cast<PrimExpr>(lhs[1]);\n    PrimExpr rhs_val = static_cast<PrimExpr>(rhs[1]);\n\n    // These variables compare the actual values of the array\n    auto is_smaller = lhs_val < rhs_val;\n    auto is_same = lhs_val == rhs_val;\n\n    // This checks if the indices are correct for the reduction. E.g. for select_last_index\n    // it gives precedence for later indices of the same element and precedence for sooner\n    // indices if not select_last_index;\n    PrimExpr proper_index;\n    if (select_last_index) {\n      proper_index = lhs_idx > rhs_idx;\n    } else {\n      proper_index = lhs_idx < rhs_idx;\n    }\n\n    PrimExpr update_index = is_smaller || (is_same && proper_index);\n    result.push_back(tvm::tir::Select(update_index, lhs[0], rhs[0]));  // idx\n    result.push_back(tvm::tir::Select(is_smaller, lhs[1], rhs[1]));    // val\n    return result;\n  };\n  auto fidentity = [&](std::vector<DataType> types) {\n    Array<PrimExpr> result;\n    result.push_back(tvm::tir::make_const(types[0], -1));  // idx\n    result.push_back(tvm::max_value(types[1]));            // val\n    return result;\n  };\n  return MakeCommReducer(fcombine, fidentity, \"argmin\");\n}\n\n/*!\n * \\brief Creates an operation that finds the indices of the minimum\n * values over a given axis.\n *\n * \\param data The input tensor\n * \\param axis The axis along which the argmin is performed. If axis is empty,\n * the operation will find the minimum index over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n * \\param select_last_index Whether to select the last index if the minimum element\n * appears multiple times, else select the first index.\n *\n * \\return A Tensor whose op member is the argmin operation\n */\ninline Tensor argmin(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                     bool atleast1d = false, bool select_last_index = false) {\n  auto reducer = MakeArgminReducer(select_last_index);\n  return CommReduceIdx(data, axis, reducer, keepdims, atleast1d);\n}\n\ninline FCommReduce MakeArgmaxReducer(bool select_last_index = false) {\n  // Create a Commutative Reducer with a comparison operation, and method to get the initial value.\n  auto fcombine = [=](Array<Var> lhs, Array<Var> rhs) {\n    Array<PrimExpr> result;\n\n    // Casting to avoid operator ambiguity\n    PrimExpr lhs_idx = static_cast<PrimExpr>(lhs[0]);\n    PrimExpr rhs_idx = static_cast<PrimExpr>(rhs[0]);\n    PrimExpr lhs_val = static_cast<PrimExpr>(lhs[1]);\n    PrimExpr rhs_val = static_cast<PrimExpr>(rhs[1]);\n\n    // These variables compare the actual values of the array\n    auto is_bigger = lhs_val > rhs_val;\n    auto is_same = lhs_val == rhs_val;\n\n    // This checks if the indices are correct for the reduction. E.g. for select_last_index\n    // it gives precedence for later indices of the same element and precedence for sooner\n    // indices if not select_last_index;\n    PrimExpr proper_index;\n    if (select_last_index) {\n      proper_index = lhs_idx > rhs_idx;\n    } else {\n      proper_index = lhs_idx < rhs_idx;\n    }\n\n    PrimExpr update_index = is_bigger || (is_same && proper_index);\n    result.push_back(tvm::tir::Select(update_index, lhs[0], rhs[0]));  // idx\n    result.push_back(tvm::tir::Select(is_bigger, lhs[1], rhs[1]));     // val\n    return result;\n  };\n  auto fidentity = [&](std::vector<DataType> types) {\n    Array<PrimExpr> result;\n    result.push_back(tvm::tir::make_const(types[0], -1));  // idx\n    result.push_back(tvm::min_value(types[1]));            // val\n    return result;\n  };\n  return MakeCommReducer(fcombine, fidentity, \"argmax\");\n}\n\n/*!\n * \\brief Creates an operation that finds the indices of the maximum\n * values over a given axis.\n *\n * \\param data The input tensor\n * \\param axis The axis along which the argmax is performed. If axis is empty,\n * the operation will find the maximum index over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n * \\param select_last_index Whether to select the last index if the maximum element\n * appears multiple times, else select the first index.\n * \\return A Tensor whose op member is the argmax operation\n */\ninline Tensor argmax(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                     bool atleast1d = false, bool select_last_index = false) {\n  auto reducer = MakeArgmaxReducer(select_last_index);\n  return CommReduceIdx(data, axis, reducer, keepdims, atleast1d);\n}\n\n/*!\n * \\brief Creates product operation over given axis.\n *\n * \\param data The input tensor\n * \\param axis The axis to do product over. If axis is empty, the\n * operation will do the product over all elements of the array.\n * \\param keepdims If this is set to true, the axes which are reduced are\n * left in the result as dimensions with size one. This enables the result\n * to broadcast correctly against the input array.\n * \\param atleast1d Whether the output need to be atleast1d.\n *\n * \\return A Tensor whose op member is the prod operation\n */\ninline Tensor prod(const Tensor& data, const Array<Integer>& axis, bool keepdims = false,\n                   bool atleast1d = false) {\n  return CommReduce(data, axis, ProdOp, keepdims, atleast1d);\n}\n\n/*!\n * \\brief Create communitive reducer summing over tuples\n */\ninline FCommReduce MakeTupleSumReducer() {\n  auto fcombine = [](Array<Var> lhs, Array<Var> rhs) {\n    Array<PrimExpr> result;\n    ICHECK_EQ(lhs.size(), rhs.size());\n    result.reserve(lhs.size());\n    for (size_t i = 0; i < lhs.size(); ++i) {\n      result.push_back(lhs[i] + rhs[i]);\n    }\n    return result;\n  };\n  auto fidentity = [](std::vector<DataType> types) {\n    Array<PrimExpr> result;\n    for (size_t i = 0; i < types.size(); ++i) {\n      result.push_back(tvm::tir::make_const(types[i], 0));\n    }\n    return result;\n  };\n  return MakeCommReducer(fcombine, fidentity, \"tuple_sum\");\n}\n\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_REDUCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/rocm/dense.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm/dense.h\n * \\brief rocm schedule for dense operation\n */\n#ifndef TVM_TOPI_ROCM_DENSE_H_\n#define TVM_TOPI_ROCM_DENSE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/contrib/rocblas.h>\n#include <tvm/topi/cuda/dense.h>\n#include <tvm/topi/detail/array_utils.h>\n#include <tvm/topi/generic/extern.h>\n#include <tvm/topi/nn/dense.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace rocm {\n/*!\n * \\brief Implementation of dense for rocm backend\n *\n * \\param target The target device\n * \\param data Tensor with shape [batch, in_dim]\n * \\param weight Tensor with shape [out_dim, in_dim]\n * \\param bias Tensor with shape [out_dim]. Optional; to omit bias, pass Tensor()\n * \\param out_dtype Output data type. Used for mixed precision.\n *\n * \\return Tensor with shape [batch, out_dim]\n */\ninline tvm::te::Tensor dense_rocm(const Target& target, const tvm::te::Tensor& data,\n                                  const tvm::te::Tensor& weight, const tvm::te::Tensor& bias,\n                                  const DataType& out_dtype) {\n  ICHECK_EQ(data->shape.size(), 2) << \"dense requires 2-D data\";\n  ICHECK_EQ(weight->shape.size(), 2) << \"dense requires 2-D weight\";\n  if (bias.defined()) {\n    ICHECK_EQ(bias->shape.size(), 1) << \"dense requires 1-D bias\";\n  }\n\n  auto batch = data->shape[0];\n  auto in_dim = data->shape[1];\n  auto out_dim = weight->shape[0];\n\n  if (target->GetLibs().count(\"rocblas\")) {\n    ICHECK_EQ(data->dtype, out_dtype) << \"Mixed precision not supported.\";\n    auto mm = topi::contrib::rocblas_matmul(data, weight, false, true);\n    if (bias.defined()) {\n      mm = tvm::te::compute(\n          {batch, out_dim}, [&](Var i, Var j) { return mm(i, j) + bias(j); }, \"tensor\", kBroadcast);\n    }\n\n    return mm;\n  } else {\n    return topi::nn::dense(data, weight, bias, out_dtype);\n  }\n}\n\n/*!\n * \\brief Create a rocm schedule for dense\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_dense(const Target& target, const Array<Tensor>& outs) {\n  if (target->kind->name == \"rocm\" && target->GetLibs().count(\"rocblas\")) {\n    return topi::generic::schedule_extern(target, outs);\n  }\n\n  return topi::cuda::schedule_dense(target, outs);\n}\n\n}  // namespace rocm\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ROCM_DENSE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/rocm/injective.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm/injective.h\n * \\brief rocm schedule for injective operations\n */\n#ifndef TVM_TOPI_ROCM_INJECTIVE_H_\n#define TVM_TOPI_ROCM_INJECTIVE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/cuda/injective.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace rocm {\n\n/*!\n * \\brief Updates an existing schedule for the given injective ops.\n *\n * \\param sch The schedule to update.\n * \\param out The tensor representing the injective op.\n *\n * \\return The updated schedule.\n */\ninline Schedule schedule_injective_from_existing(Schedule sch, const Tensor& out) {\n  return topi::cuda::schedule_injective_from_existing(sch, out);\n}\n\n/*!\n * \\brief Create a rocm schedule for the given output tensors.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_injective(const Target& target, const Array<Tensor>& outs) {\n  return topi::cuda::schedule_injective(target, outs);\n}\n\n}  // namespace rocm\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ROCM_INJECTIVE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/rocm/pooling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm/pooling.h\n * \\brief rocm schedule for pooling operations\n */\n#ifndef TVM_TOPI_ROCM_POOLING_H_\n#define TVM_TOPI_ROCM_POOLING_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/cuda/pooling.h>\n#include <tvm/topi/detail/array_utils.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace rocm {\n\n/*!\n * \\brief Create a rocm schedule for pool\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_pool(const Target& target, const Array<Tensor>& outs) {\n  return topi::cuda::schedule_pool(target, outs);\n}\n\n/*!\n * \\brief Create a rocm schedule for global_pool\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_global_pool(const Target& target, const Array<Tensor>& outs) {\n  return topi::cuda::schedule_global_pool(target, outs);\n}\n\n}  // namespace rocm\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ROCM_POOLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/rocm/reduction.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm/reduction.h\n * \\brief rocm schedule for reduction operations\n */\n#ifndef TVM_TOPI_ROCM_REDUCTION_H_\n#define TVM_TOPI_ROCM_REDUCTION_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/cuda/reduction.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace rocm {\n/*!\n * \\brief Create a rocm schedule for a reduce operation.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\nSchedule schedule_reduce(const Target& target, Array<Tensor> outs) {\n  return topi::cuda::schedule_reduce(target, outs);\n}\n\n}  // namespace rocm\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ROCM_REDUCTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/rocm/softmax.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm/injective.h\n * \\brief ROCM schedule for injective operations\n */\n#ifndef TVM_TOPI_ROCM_SOFTMAX_H_\n#define TVM_TOPI_ROCM_SOFTMAX_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/cuda/softmax.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace rocm {\n\n/*!\n * \\brief Create a rocm schedule for the given softmax output tensors.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_softmax(const Target& target, const Array<Tensor>& outs) {\n  return topi::cuda::schedule_softmax(target, outs);\n}\n\n}  // namespace rocm\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_ROCM_SOFTMAX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/tags.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Tag definitions\n * \\file tags.h\n */\n#ifndef TVM_TOPI_TAGS_H_\n#define TVM_TOPI_TAGS_H_\n\n#include <string>\n\nnamespace tvm {\nnamespace topi {\n\nconstexpr auto kElementWise = \"elemwise\";\nconstexpr auto kInjective = \"injective\";\nconstexpr auto kCommReduce = \"comm_reduce\";\nconstexpr auto kCommReduceIdx = \"comm_reduce_idx\";\nconstexpr auto kBroadcast = \"broadcast\";\nconstexpr auto kMatMul = \"matmul\";\nconstexpr auto kConv2dNCHW = \"conv2d_nchw\";\nconstexpr auto kConv2dHWCN = \"conv2d_hwcn\";\nconstexpr auto kDepthwiseConv2dNCHW = \"depthwise_conv2d_nchw\";\nconstexpr auto kDepthwiseConv2dNHWC = \"depthwise_conv2d_nhwc\";\nconstexpr auto kDepthwiseConv2dBackInputNHWC = \"depthwise_conv2d_back_input_nhwc\";\nconstexpr auto kDepthwiseConv2dBackWeightNHWC = \"depthwise_conv2d_back_weight_nhwc\";\nconstexpr auto kEinsum = \"einsum\";\nconstexpr auto kGroupConv2d = \"group_conv2d\";\n\ninline bool is_broadcast(std::string tag) {\n  return tag.rfind(kElementWise, 0) == 0 || tag.rfind(kBroadcast, 0) == 0;\n}\n\ninline bool is_injective(std::string tag) {\n  return tag.rfind(kElementWise, 0) == 0 || tag.rfind(kBroadcast, 0) == 0 ||\n         tag.rfind(kInjective, 0) == 0;\n}\n\n}  // namespace topi\n}  // namespace tvm\n\n#endif  // TVM_TOPI_TAGS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file topi/transform.h\n * \\brief Transform op constructors\n */\n#ifndef TVM_TOPI_TRANSFORM_H_\n#define TVM_TOPI_TRANSFORM_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/tir/data_layout.h>\n#include <tvm/tir/index_map.h>\n#include <tvm/topi/broadcast.h>\n#include <tvm/topi/detail/broadcast.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/detail/ravel_unravel.h>\n#include <tvm/topi/detail/strided_slice.h>\n#include <tvm/topi/detail/tensor_utils.h>\n#include <tvm/topi/tags.h>\n\n#include <algorithm>\n#include <iterator>\n#include <limits>\n#include <string>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\nusing namespace topi::detail;\n\n/*!\n * \\brief Creates an operation to slide a window over the input x.\n *\n * \\param x The input tensor.\n * \\param axis What axis the window begins sliding over. Window will be slid\n * over this axis and all following axes. The axis value determines the window\n * shape (and thus, the number of strides): window shape and strides must both\n * be of length `data.ndim-axis`.\n * \\param window_shape The window shape to form over the input. Window shape\n * must be of length `data.ndim-axis`.\n * \\param strides How to stride the window along each dimension. Strides must be\n * of length `data.ndim-axis`.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the sliding_window operation\n */\ninline Tensor sliding_window(const Tensor& x, int axis, Array<Integer> window_shape,\n                             Array<Integer> strides, std::string name = \"T_sliding_window\",\n                             std::string tag = \"\") {\n  CHECK_GE(axis, 0);\n  auto _axis = size_t(axis);\n  CHECK_LT(_axis, x->shape.size()) << \"axis must be a valid dimension index of x.\";\n  CHECK_EQ(x->shape.size() - _axis, window_shape.size())\n      << \"There must be a window shape for every dimension of x \"\n      << \"over which we are sliding the window.\";\n  CHECK_EQ(strides.size(), window_shape.size()) << \"Windows and strides should be the same length.\";\n\n  // Compute the new shape.\n  Array<PrimExpr> new_shape;\n  // Dimensions up until `axis` remain the same.\n  for (size_t i = 0; i < _axis; ++i) {\n    new_shape.push_back(x->shape[i]);\n  }\n\n  // New dimensions which result from sliding the window in each dimension. One new dimension per\n  // window dimension.\n  for (size_t i = 0; i < window_shape.size(); ++i) {\n    // Length of the shape along this dimension.\n    auto dim_len = x->shape[_axis + i];\n    // Length of the window along this dimension.\n    auto window_len = window_shape[i];\n    // Strides along this dimension.\n    auto stride = strides[i];\n\n    new_shape.push_back(floordiv(dim_len - (window_len - 1) + stride - 1, stride));\n  }\n\n  // Dimensions comprising the window.\n  for (size_t i = 0; i < window_shape.size(); ++i) {\n    new_shape.push_back(window_shape[i]);\n  }\n\n  ICHECK(new_shape.size() == _axis + 2 * window_shape.size());\n\n  return compute(\n      new_shape,\n      [&](const Array<Var>& indices) {\n        // The index at which to index the old tensor x.\n        Array<PrimExpr> idx;\n\n        // Dimensions up until `axis` remain the same.\n        for (size_t i = 0; i < _axis; ++i) {\n          idx.push_back(indices[i]);\n        }\n\n        for (size_t i = 0; i < window_shape.size(); ++i) {\n          // Which window in this dimension we are indexing.\n          auto window_idx = indices[_axis + i];\n          // Which index within the window we are indexing.\n          auto idx_within_window = indices[_axis + window_shape.size() + i];\n          // Stride value for this dimension.\n          auto stride = strides[i];\n\n          idx.push_back(window_idx * stride + idx_within_window);\n        }\n\n        ICHECK(idx.size() == x->shape.size());\n\n        return x(idx);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation to insert new dimensions of length 1\n *\n * \\param x The input tensor\n * \\param axis The index of the first new dimension (allows negative\n * indices as offsets from the last dimension)\n * \\param num_newaxis The number of new dimensions to insert\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the dim expansion operation\n */\ninline Tensor expand_dims(const Tensor& x, int axis, int num_newaxis = 1,\n                          std::string name = \"T_expand_dims\", std::string tag = kBroadcast) {\n  int ndim = static_cast<int>(x->shape.size());\n  ICHECK(-ndim - 1 <= axis && axis <= ndim)\n      << \"expand_dims only accepts `axis` in [-data.ndim - 1, data.ndim]\"\n      << \", but got axis = \" << axis << \", and data.ndim = \" << ndim;\n  ICHECK(num_newaxis >= 0) << \"expand_dims only accepts `num_newaxis >= 0`\"\n                           << \", but got num_newaxis = \" << num_newaxis;\n  if (axis < 0) {\n    // Calculate offset from last dimension\n    axis = ndim + axis + 1;\n  }\n  Array<PrimExpr> new_shape;\n  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n    new_shape.push_back(x->shape[i]);\n  }\n  for (size_t i = 0; i < static_cast<size_t>(num_newaxis); ++i) {\n    new_shape.push_back(1);\n  }\n  for (size_t i = axis; i < x->shape.size(); ++i) {\n    new_shape.push_back(x->shape[i]);\n  }\n\n  return compute(\n      new_shape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> idx;\n        for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n          idx.push_back(indices[i]);\n        }\n        for (size_t i = axis + num_newaxis; i < indices.size(); ++i) {\n          idx.push_back(indices[i]);\n        }\n        return x(idx);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Permute the dimensions of an array\n *\n * \\param x The input tensor\n * \\param axes The indices of the permutation. If this is empty,\n * the dimensions will be reversed.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the transpose operation\n */\ninline Tensor transpose(const Tensor& x, Array<Integer> axes, std::string name = \"T_transpose\",\n                        std::string tag = kInjective) {\n  if (!axes.defined() || axes.size() == 0) {\n    axes = Array<Integer>();\n    for (int i = static_cast<int>(x->shape.size()) - 1; i >= 0; --i) {\n      axes.push_back(i);\n    }\n  }\n\n  Array<PrimExpr> new_shape;\n  for (size_t i = 0; i < axes.size(); ++i) {\n    int axis = static_cast<int>(axes[i]->value);\n    int new_axis = axis;\n    if (axis < 0) {\n      new_axis = static_cast<int>(x->shape.size()) + axis;\n      axes.Set(i, new_axis);\n    }\n    ICHECK((new_axis >= 0) && (new_axis < static_cast<int>(x->shape.size())))\n        << \"axis=\" << axis << \" is invalid for the \" << static_cast<int>(x->shape.size())\n        << \"-dimensional input tensor\";\n\n    for (size_t j = 0; j < axes.size(); ++j) {\n      if (i != j) {\n        ICHECK(new_axis != static_cast<int>(axes[j]->value)) << \"repeated axis in transpose\";\n      }\n    }\n    new_shape.push_back(x->shape[new_axis]);\n  }\n\n  return compute(\n      new_shape,\n      [&](const Array<Var>& indices) {\n        std::vector<PrimExpr> idx;\n        for (size_t i = 0; i < axes.size(); ++i) {\n          idx.push_back(1);\n        }\n        for (size_t i = 0; i < axes.size(); ++i) {\n          int axis = static_cast<int>(axes[i]->value);\n          idx[axis] = indices[i];\n        }\n        return x(idx);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Reverse the tensor for variable length slices.\n * Input is first sliced along batch axis and then elements are reversed along seq axis.\n *\n * \\param x The input tensor\n * \\param seq_lengths A 1D Tensor with length x.dims[batch_axis]. Optional Tensor() can be passed.\n * If not defined batch axis is ignored and tensor is reversed along seq_axis.\n * \\param seq_axis The axis along which the elements will be reveresed\n * \\param batch_axis The axis along which the tensor will be sliced\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the reverse_sequence operation\n */\ninline Tensor reverse_sequence(const Tensor& x, const Tensor& seq_lengths, int seq_axis = 1,\n                               int batch_axis = 0, std::string name = \"T_reverse_sequence\",\n                               std::string tag = kInjective) {\n  size_t src_tensor_dim = x->shape.size();\n  int seq_axis_inp = seq_axis;\n\n  if (seq_lengths.defined()) {\n    size_t seq_lengths_dim = seq_lengths->shape.size();\n    int batch_axis_inp = batch_axis;\n    if (batch_axis < 0) {\n      batch_axis = static_cast<int>(x->shape.size()) + batch_axis;\n    }\n\n    ICHECK(seq_lengths_dim == 1) << \"seq_lengths should be 1D vector\";\n\n    ICHECK(GetConstInt(seq_lengths->shape[0]) == GetConstInt(x->shape[batch_axis]))\n        << \"For reverse_sequnece seq_lengths size should match with dimension of batch axis\"\n        << \", but got dimension of batch_axis = \" << GetConstInt(x->shape[batch_axis])\n        << \", and seq_length size = \" << GetConstInt(seq_lengths->shape[0]);\n\n    ICHECK((0 <= batch_axis) && (batch_axis < static_cast<int>(x->shape.size())))\n        << \"batch_axis=\" << batch_axis_inp << \" is invalid for the \"\n        << static_cast<int>(x->shape.size()) << \"-dimensional input tensor\";\n  }\n\n  if (seq_axis < 0) {\n    seq_axis = static_cast<int>(x->shape.size()) + seq_axis;\n  }\n  ICHECK((0 <= seq_axis) && (seq_axis < static_cast<int>(x->shape.size())))\n      << \"seq_axis=\" << seq_axis_inp << \" is invalid for the \" << static_cast<int>(x->shape.size())\n      << \"-dimensional input tensor\";\n\n  auto func = [&](const Array<Var>& indices) {\n    Array<PrimExpr> real_indices;\n    for (size_t i = 0; i < src_tensor_dim; ++i) {\n      if (i == static_cast<size_t>(seq_axis)) {\n        if (seq_lengths.defined()) {\n          auto len = seq_lengths(indices[batch_axis]);\n          auto idx = if_then_else(\n              len <= 1 || len <= indices[i], indices[i],\n              if_then_else(len > x->shape[i], x->shape[i] - 1 - indices[i], len - 1 - indices[i]));\n          real_indices.push_back(idx);\n        } else {\n          real_indices.push_back(x->shape[i] - 1 - indices[i]);\n        }\n      } else {\n        real_indices.push_back(indices[i]);\n      }\n    }\n    return x(real_indices);\n  };\n\n  return compute(x->shape, func, name, tag);\n}\n\n/*!\n * \\brief Reshape a tensor\n *\n * \\param x The input tensor\n * \\param newshape The new shape\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the reshape operation\n */\ninline Tensor reshape(const Tensor& x, Array<PrimExpr> newshape, std::string name = \"T_reshape\",\n                      std::string tag = kInjective) {\n  auto x_shape = x->shape;\n  Array<PrimExpr> target_shape;\n\n  for (const auto& ele : newshape) {\n    if (ele.as<IntImmNode>()) {\n      target_shape.push_back(cast(DataType::Int(32), ele));\n    } else {\n      target_shape.push_back(ele);\n    }\n  }\n\n  // If either the input shape or the target shape contains a zero, return an empty tensor.\n  if (is_empty_shape(target_shape) || is_empty_shape(x->shape)) {\n    return compute(\n        target_shape, [&](const Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name, tag);\n  } else {\n    return compute(\n        target_shape,\n        [&](const Array<Var>& indices) {\n          return x(UnravelIndex(\n              RavelIndex(Array<PrimExpr>{indices.begin(), indices.end()}, target_shape), x_shape));\n        },\n        name, tag);\n  }\n}\n\n/*!\n * \\brief Converts a flat index or array of flat indices into a tuple of coordinate arrays\n *\n * \\param x The input tensor having indices.\n * \\param shape The shape tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor of coordinate arrays.\n */\n\ninline Tensor unravel_index(const Tensor& x, const Tensor& shape, std::string name = \"T_unravel\",\n                            std::string tag = kInjective) {\n  auto x_shape = x->shape;\n  auto shape_shape = shape->shape;\n\n  Array<PrimExpr> oshape;\n  oshape.push_back(shape_shape[0]);\n  if (x_shape.size() != 0) {\n    oshape.push_back(x_shape[0]);\n  }\n\n  auto func = [&](const Array<Var>& indices) {\n    auto i = indices[0];\n    std::vector<PrimExpr> indices_divs;\n    PrimExpr ret = 0;\n    PrimExpr cur_val = 0;\n    PrimExpr index_val = 0;\n\n    if (x_shape.size() != 0) {\n      index_val = x[indices[1]];\n    } else {\n      index_val = x();\n    }\n    indices_divs.push_back(index_val);\n    for (int v = GetConstInt(shape_shape[0]) - 1; v >= 0; --v) {\n      ret = tvm::if_then_else(i == v, indexmod(indices_divs.back(), shape[v]), ret);\n      cur_val = indexdiv(indices_divs.back(), shape[v]);\n      indices_divs.push_back(cur_val);\n    }\n    return ret;\n  };\n\n  return compute(oshape, func, name, tag);\n}\n\n/*!\n * \\brief Remove size 1 dimensions from the shape of a tensor.\n * The removed dimensions must have a constant size of 1.\n *\n * \\param x The input tensor\n * \\param axis Indices of the dimensions to remove. If this is None,\n * all entries with a constant size of 1 will be removed.\n * \\param atleast1d Whether the output need to be atleast1d.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the squeeze operation\n */\ninline Tensor squeeze(const Tensor& x, Array<Integer> axis, bool atleast1d = false,\n                      std::string name = \"T_squeeze\", std::string tag = kInjective) {\n  auto ndim = x->shape.size();\n  std::vector<int> axis_val;\n  if (!axis.defined()) {\n    for (size_t i = 0; i < ndim; ++i) {\n      if (IsConstInt(x->shape[i]) && GetConstInt(x->shape[i]) == 1) {\n        axis_val.push_back(static_cast<int>(i));\n      }\n    }\n  } else {\n    for (size_t i = 0; i < axis.size(); ++i) {\n      int64_t val = axis[i]->value;\n      if (val < 0) {\n        val += static_cast<int>(x->shape.size());\n      }\n      if (IsConstInt(x->shape[val])) {\n        ICHECK_EQ(GetConstInt(x->shape[val]), 1) << \"Dimension \" << val << \" must have size 1\";\n      }\n      axis_val.push_back(val);\n    }\n  }\n\n  std::unordered_set<int> axis_set(axis_val.begin(), axis_val.end());\n\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < ndim; ++i) {\n    if (axis_set.count(static_cast<int>(i)) == 0) {\n      out_shape.push_back(x->shape[i]);\n    }\n  }\n  if (out_shape.size() == 0 && atleast1d) {\n    out_shape.push_back(1);\n  }\n\n  return compute(\n      out_shape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> real_indices;\n        int flag = 0;\n        for (size_t i = 0; i < ndim; ++i) {\n          if (axis_set.count(static_cast<int>(i)) == 0) {\n            real_indices.push_back(indices[i - flag]);\n          } else {\n            real_indices.push_back(0);\n            flag += 1;\n          }\n        }\n        return x(real_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Join a sequence of tensors along an existing axis\n *\n * \\param inputs The input tensors\n * \\param axis The axis along which the tensors will be joined\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the concatenate operation\n */\ninline Tensor concatenate(const Array<Tensor>& inputs, int axis = 0, std::string name = \"T_concat\",\n                          std::string tag = kInjective) {\n  int ndim = static_cast<int>(inputs[0]->shape.size());\n  ICHECK(-ndim <= axis && axis < ndim) << \"concatenate only accepts `axis` in [-ndim, ndim)\"\n                                       << \", but got axis = \" << axis << \", and ndim = \" << ndim;\n  if (axis < 0) {\n    axis += ndim;\n  }\n  ICHECK_LT(axis, inputs[0]->shape.size()) << \"axis out of bounds\";\n\n  Array<PrimExpr> axis_sizes;\n  for (auto t : inputs) {\n    axis_sizes.push_back(t->shape[axis]);\n  }\n  arith::Analyzer analyzer;\n  PrimExpr join_size = axis_sizes[0];\n  for (size_t i = 1; i < axis_sizes.size(); ++i) {\n    join_size += axis_sizes[i];\n  }\n  join_size = analyzer.Simplify(join_size);\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < inputs[0]->shape.size(); ++i) {\n    out_shape.push_back(i == static_cast<size_t>(axis) ? join_size : inputs[0]->shape[i]);\n  }\n\n  return compute(\n      out_shape,\n      [&](const Array<Var>& indices) {\n        auto ret = inputs[0](indices);\n        auto ind = indices[axis];\n        for (size_t i = 0; i < inputs.size() - 1; ++i) {\n          ind -= axis_sizes[i];\n\n          Array<PrimExpr> idx;\n          for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n            idx.push_back(indices[i]);\n          }\n          idx.push_back(ind);\n          for (size_t i = axis + 1; i < indices.size(); ++i) {\n            idx.push_back(indices[i]);\n          }\n\n          ret = tvm::if_then_else(ind >= 0, inputs[i + 1](idx), ret);\n        }\n        return ret;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Join a sequence of tensors along a new axis.\n *\n * \\param inputs The input tensors\n * \\param axis The axis along which the tensors will be stacked\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the stack operation\n */\ninline Tensor stack(const Array<Tensor>& inputs, int axis = 0, std::string name = \"T_stack\",\n                    std::string tag = kInjective) {\n  int ndim = static_cast<int>(inputs[0]->shape.size());\n  ICHECK(-ndim - 1 <= axis && axis <= ndim)\n      << \"stack only accepts `axis` in [-ndim, ndim)\"\n      << \", but got axis = \" << axis << \", and ndim = \" << ndim;\n  if (axis < 0) {\n    axis += ndim + 1;\n  }\n  ICHECK_LT(axis, inputs[0]->shape.size() + 1) << \"axis out of bounds\";\n\n  const int stack_size = static_cast<int>(inputs.size());\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) out_shape.push_back(inputs[0]->shape[i]);\n  out_shape.push_back(stack_size);\n  for (size_t i = static_cast<size_t>(axis); i < static_cast<size_t>(ndim); ++i)\n    out_shape.push_back(inputs[0]->shape[i]);\n\n  return compute(\n      out_shape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> idx;\n        for (size_t i = 0; i < indices.size(); ++i)\n          if (i != static_cast<size_t>(axis)) idx.push_back(indices[i]);\n        auto ind = indices[axis];\n        auto ret = inputs[0](idx);\n        for (int i = 0; i < static_cast<int>(inputs.size() - 1); ++i) {\n          ret = tvm::if_then_else(ind == i + 1, inputs[i + 1](idx), ret);\n        }\n        return ret;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Split a tensor into multiple sub-tensors\n *\n * \\param x The input tensor\n * \\param split_indices The indices to split the input at. This must be in ascending\n * order.\n * \\param axis The axis to split along.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the split operation\n */\ninline Array<Tensor> split(const Tensor& x, Array<PrimExpr> split_indices, int axis,\n                           std::string name = \"T_split\", std::string tag = kInjective) {\n  if (axis < 0) {\n    axis += static_cast<int>(x->shape.size());\n  }\n  ICHECK_LT(axis, x->shape.size()) << \"axis out of bounds\";\n\n  auto src_axis_size = x->shape[axis];\n  std::vector<PrimExpr> begin_ids;\n  begin_ids.push_back(0);\n\n  for (auto idx : split_indices) {\n    auto idx_node = idx.as<IntImmNode>();\n    auto back_node = begin_ids.back().as<IntImmNode>();\n    if (idx_node && back_node) {\n      ICHECK_GT(idx_node->value, back_node->value) << \"split_indices must be sorted\";\n    }\n    begin_ids.push_back(idx);\n  }\n\n  Array<Array<PrimExpr>> out_shapes;\n  for (size_t i = 0; i < begin_ids.size(); ++i) {\n    PrimExpr out_axis_size;\n    if (i == begin_ids.size() - 1) {\n      out_axis_size = src_axis_size - begin_ids[i];\n    } else {\n      out_axis_size = begin_ids[i + 1] - begin_ids[i];\n    }\n\n    Array<PrimExpr> shape;\n    for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n      shape.push_back(x->shape[i]);\n    }\n    shape.push_back(out_axis_size);\n    for (size_t i = axis + 1; i < x->shape.size(); ++i) {\n      shape.push_back(x->shape[i]);\n    }\n\n    out_shapes.push_back(shape);\n  }\n\n  Array<Tensor> result;\n  for (size_t i = 0; i < begin_ids.size(); ++i) {\n    result.push_back(compute(\n        out_shapes[i],\n        [&](const Array<Var>& indices) {\n          auto begin = begin_ids[i];\n          Array<PrimExpr> real_indices;\n          for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {\n            real_indices.push_back(indices[j]);\n          }\n          real_indices.push_back(indices[axis] + begin);\n          for (size_t j = axis + 1; j < indices.size(); ++j) {\n            real_indices.push_back(indices[j]);\n          }\n\n          return x(real_indices);\n        },\n        name, tag));\n  }\n\n  return result;\n}\n\n/*!\n * \\brief strided_slice of a tensor where begin/end/stride can be mixed static and dynamic\n *\n * \\param x The input tensor\n * \\param begin The indices to begin with in the slicing\n * \\param end Indices indicating end of the slice\n * \\param strides Specifies the stride values, it can be negative\n * in that case, the input tensor will be reversed in that particular axis\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the dynamic_strided_slice operation\n */\ninline Tensor dynamic_strided_slice(const Tensor& x, const Array<PrimExpr>& begin,\n                                    const Array<PrimExpr>& end, const Array<PrimExpr>& strides,\n                                    std::string name = \"T_dynamic_strided_slice\",\n                                    std::string tag = kInjective) {\n  const size_t src_tensor_dim = x->shape.size();\n  ICHECK_LE(begin.size(), src_tensor_dim);\n  ICHECK_LE(end.size(), src_tensor_dim);\n  ICHECK_LE(strides.size(), src_tensor_dim);\n  ICHECK_EQ(begin.size(), end.size());\n  ICHECK_EQ(begin.size(), strides.size());\n\n  const size_t num_slice_axes = begin.size();\n  Array<PrimExpr> out_shape;\n\n  for (size_t i = 0; i < num_slice_axes; ++i) {\n    auto d = indexdiv(end[i] - begin[i], strides[i]);\n    if (d->IsInstance<tvm::IntImmNode>()) {\n      // Preserve static dimension if possible\n      out_shape.push_back(d);\n    } else {\n      out_shape.push_back(tvm::tir::Var(\"dim\"));\n    }\n  }\n\n  for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {\n    out_shape.push_back(x->shape[i]);\n  }\n\n  return te::compute(\n      out_shape,\n      [&](const Array<tvm::tir::Var>& indices) {\n        Array<PrimExpr> real_indices;\n        for (size_t i = 0; i < num_slice_axes; ++i) {\n          real_indices.push_back(indices[i] * strides[i] + tvm::min(begin[i], x->shape[i] - 1));\n        }\n        // keep input dim\n        for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {\n          real_indices.push_back(indices[i]);\n        }\n        return x(real_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief strided_slice of a tensor with dynamic begin/end/stride\n *\n * \\param x The input tensor\n * \\param begin The indices to begin with in the slicing\n * \\param end Indices indicating end of the slice\n * \\param strides Specifies the stride values, it can be negative\n * in that case, the input tensor will be reversed in that particular axis\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the dynamic_strided_slice operation\n */\ninline te::Tensor dynamic_strided_slice(const te::Tensor& x, const te::Tensor& begin,\n                                        const te::Tensor& end, const te::Tensor& strides,\n                                        std::string name = \"T_strided_slice_dynamic\",\n                                        std::string tag = topi::kInjective) {\n  const int64_t num_dynamic_axes = begin->shape[0].as<IntImmNode>()->value;\n  ICHECK_EQ(end->shape[0].as<IntImmNode>()->value, num_dynamic_axes);\n  ICHECK_EQ(strides->shape[0].as<IntImmNode>()->value, num_dynamic_axes);\n\n  Array<PrimExpr> begin_expr, end_expr, strides_expr;\n  for (int64_t i = 0; i < num_dynamic_axes; ++i) {\n    auto i64_ind = IntImm(DataType::Int(64), i);\n    begin_expr.push_back(begin(i64_ind));\n    end_expr.push_back(end(i64_ind));\n    strides_expr.push_back(strides(i64_ind));\n  }\n  return dynamic_strided_slice(x, begin_expr, end_expr, strides_expr, name, tag);\n}\n\n/*!\n * \\brief Calcluate the output shape of strided_slice, the entry point for Relay type relation\n *\n * \\param ishape The input tensor shape\n * \\param begin The indices to begin with in the slicing\n * \\param end Indices indicating end of the slice\n * \\param strides Specifies the stride values, it can be negative\n * in that case, the input tensor will be reversed in that particular axis\n * \\param axes Axes along which slicing is applied. When it is specified, the length of begin, end,\n * strides, and axes argument must be equal\n * \\param slice_mode Specifies the slice mode\n *\n * \\return The output shape of strided_slice using the arguments above\n */\ninline Array<PrimExpr> StridedSliceOutputShape(\n    const Array<PrimExpr>& ishape, const Array<Integer>& begin, const Array<Integer>& end,\n    const Array<Integer>& strides, const Array<Integer>& axes, const std::string& slice_mode) {\n  ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());\n  std::vector<int64_t> begin_vec, end_vec, strides_vec;\n  std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);\n  auto begin_canonicalized = StridedSliceCanonicalizeBegin(ishape, begin_vec, strides_vec, axes,\n                                                           begin[0]->dtype, slice_mode);\n  return StridedSliceOutputShape(ishape, begin_vec, end_vec, strides_vec, axes, slice_mode,\n                                 begin_canonicalized, true);\n}\n\n/*!\n * \\brief strided_slice of a tensor\n *\n * \\param x The input tensor\n * \\param begin The indices to begin with in the slicing\n * \\param end Indices indicating end of the slice\n * \\param strides Specifies the stride values, it can be negative\n * in that case, the input tensor will be reversed in that particular axis\n * \\param axes Axes along which slicing is applied. When it is specified, the length of begin, end,\n * strides, and axes argument must be equal\n * \\param slice_mode Specifies the slice mode\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the sstrided_slice operation\n */\ninline Tensor strided_slice_with_axes(const Tensor& x, const Array<Integer>& begin,\n                                      const Array<Integer>& end, const Array<Integer>& strides,\n                                      const Array<Integer>& axes, std::string slice_mode = \"end\",\n                                      std::string name = \"T_strided_slice_with_axes\",\n                                      std::string tag = kInjective) {\n  const size_t src_tensor_dim = x->shape.size();\n  ICHECK(axes.size() <= src_tensor_dim);\n  ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());\n\n  std::vector<int64_t> begin_vec, end_vec, strides_vec;\n  std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);\n\n  auto begin_expr = StridedSliceCanonicalizeBegin(x->shape, begin_vec, strides_vec, axes,\n                                                  begin[0]->dtype, slice_mode);\n  auto out_shape = StridedSliceOutputShape(x->shape, begin_vec, end_vec, strides_vec, axes,\n                                           slice_mode, begin_expr);\n\n  return te::compute(\n      out_shape,\n      [&](const Array<tir::Var>& indices) {\n        Array<PrimExpr> real_indices;\n        for (size_t i = 0; i < out_shape.size(); ++i) real_indices.push_back(indices[i]);\n        for (size_t i = 0; i < axes.size(); ++i) {\n          auto stride = make_const(strides[i].dtype(), strides_vec[i]);\n          PrimExpr ind = indices[axes[i].IntValue()] * stride + begin_expr[i];\n          real_indices.Set(axes[i].IntValue(), ind);\n        }\n        return x(real_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief strided_slice of a tensor\n *\n * \\param x The input tensor\n * \\param begin The indices to begin with in the slicing\n * \\param end Indices indicating end of the slice\n * \\param strides Specifies the stride values, it can be negative\n * in that case, the input tensor will be reversed in that particular axis\n * \\param slice_mode Specifies the slice mode\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the strided_slice operation\n */\ninline Tensor strided_slice(const Tensor& x, const Array<Integer>& begin, const Array<Integer>& end,\n                            const Array<Integer>& strides, std::string slice_mode = \"end\",\n                            std::string name = \"T_strided_slice\", std::string tag = kInjective) {\n  size_t src_tensor_dim = static_cast<size_t>(x->shape.size());\n  Array<Integer> axes;\n  for (size_t i = 0; i < src_tensor_dim; ++i) axes.push_back(i);\n  Array<Integer> begin_full(begin);\n  Array<Integer> end_full(end);\n  Array<Integer> strides_full(strides);\n\n  const IntImm one = IntImm(DataType::Int(64), 1);\n  const IntImm zero = IntImm(DataType::Int(64), 0);\n  const IntImm max_range = IntImm(DataType::Int(64), std::numeric_limits<int64_t>::max());\n\n  for (size_t i = strides.size(); i < src_tensor_dim; ++i) {\n    strides_full.push_back(one);\n  }\n  for (size_t i = begin.size(); i < src_tensor_dim; ++i) {\n    begin_full.push_back(GetConstInt(strides_full[i]) > 0 ? zero : max_range);\n  }\n  for (size_t i = end.size(); i < src_tensor_dim; ++i) {\n    end_full.push_back(GetConstInt(strides_full[i]) < 0 ? zero : max_range);\n  }\n\n  return strided_slice_with_axes(x, begin_full, end_full, strides_full, axes, slice_mode, name,\n                                 tag);\n}\n\n/*!\n * \\brief Split a tensor into a number of sub-tensors\n *\n * \\param x The input tensor\n * \\param num_sections The number of sections to split the tensor into.\n * this must be an integer factor of the size of the axis being split.\n * \\param axis The axis to split along.\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the split operation\n */\ninline Array<Tensor> split_sections(const Tensor& x, int num_sections, int axis,\n                                    std::string name = \"T_split_sections\",\n                                    std::string tag = kInjective) {\n  if (axis < 0) {\n    axis += static_cast<int>(x->shape.size());\n  }\n  ICHECK_LT(axis, x->shape.size()) << \"axis out of bounds\";\n\n  auto src_axis_size = x->shape[axis];\n\n  ICHECK_GT(num_sections, 0) << \"Slice count must be > 0\";\n\n  if (auto node = src_axis_size.as<IntImmNode>()) {\n    ICHECK_EQ(node->value % num_sections, 0)\n        << \"num_sections must be an integer factor of the size of axis \" << axis << \" (\"\n        << node->value << \")\";\n  }\n\n  Array<PrimExpr> split_indices;\n  auto seg_size = indexdiv(src_axis_size, num_sections);\n  for (int i = 0; i < num_sections; ++i) {\n    // region at index 0 is added by split()\n    if (i != 0) {\n      split_indices.push_back(seg_size * i);\n    }\n  }\n\n  return split(x, split_indices, axis, name, tag);\n}\n\n/*!\n * \\brief Take elements from an flattened input array when axis is None.\n *\n * \\param a The source array.\n * \\param indices The indices of the values to extract.\n * \\param batch_dims The number of batch dimensions.\n * \\param mode The mode of the operation.\n * \\param name The name of the operation.\n * \\param mode The mode of to handle out of bound indices.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the take operation\n */\ninline Tensor take(const Tensor& a, const Tensor& indices, int batch_dims,\n                   std::string mode = \"clip\", std::string name = \"T_take\",\n                   std::string tag = kInjective) {\n  Array<PrimExpr> a_shape = a->shape;\n  Array<PrimExpr> out_shape = indices->shape;\n  PrimExpr a_size = 1;\n  for (size_t i = 0; i < a_shape.size(); ++i) {\n    a_size = a_size * a_shape[i];\n  }\n\n  if (mode == \"clip\") {\n    return compute(\n        out_shape,\n        [&](const Array<Var>& out_index) {\n          auto idx = tvm::min(tvm::max(0, indices(out_index)), a_size - 1);\n          return a(UnravelIndex(idx, a_shape));\n        },\n        name, tag);\n  } else if (mode == \"fast\") {\n    LOG(WARNING) << \"Fast mode segfaults when there are out-of-bounds indices. \"\n                    \"Make sure input indices are in bound\";\n    return compute(\n        out_shape,\n        [&](const Array<Var>& out_index) { return a(UnravelIndex(indices(out_index), a_shape)); },\n        name, tag);\n  } else {  // mode == \"wrap\"\n    return compute(\n        out_shape,\n        [&](const Array<Var>& out_index) {\n          auto idx = truncmod(truncmod(indices(out_index), a_size) + a_size, a_size);\n          return a(UnravelIndex(idx, a_shape));\n        },\n        name, tag);\n  }\n}\n\n/*!\n * \\brief Mask the out-of-boundary elements of each sequence.\n *\n * \\param data The source array.\n * \\param valid_length The real length of each sequence.\n * \\param mask_value The masking value.\n * \\param axis The axis of the temporal dimension of the sequence\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the sequence_mask operation\n */\ninline Tensor sequence_mask(const Tensor& data, const Tensor& valid_length, double mask_value,\n                            int axis, std::string name = \"T_sequence_mask\",\n                            std::string tag = kInjective) {\n  ICHECK(axis == 0 || axis == 1) << \"axis must be either 0 or 1\";\n  ICHECK_EQ(valid_length->shape.size(), 1) << \"valid_length must have ndim=1, i.e., (batch_size,).\";\n  auto length_dim = data->shape[axis];\n  auto batch_dim = data->shape[1 - axis];\n  Array<PrimExpr> out_shape = data->shape;\n  Tensor out = compute(\n      out_shape,\n      [&](const Array<Var>& out_index) {\n        Array<PrimExpr> len_index;\n        auto tid = out_index[axis];\n        auto bid = out_index[1 - axis];\n        len_index.push_back(bid);\n        PrimExpr ret =\n            tvm::if_then_else(tvm::cast(valid_length->dtype, tid) >= valid_length(len_index),\n                              tvm::tir::make_const(data->dtype, mask_value), data(out_index));\n        return ret;\n      },\n      name, tag);\n  return out;\n}\n\n/*!\n * \\brief Take elements from an array along an axis.\n *\n * \\param a The source array.\n * \\param indices The indices of the values to extract.\n * \\param batch_dims The number of batch dimensions. By default is 0.\n * \\param axis The axis over which to select values. By default,\n * the flattened input array is used.\n * \\param mode The mode for handling out of bound indices.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the take operation\n */\ninline Tensor take(const Tensor& a, const Tensor& indices, int batch_dims, int axis,\n                   std::string mode = \"clip\", std::string name = \"T_take\",\n                   std::string tag = kInjective) {\n  if (axis < 0) {\n    axis += static_cast<int>(a->shape.size());\n  }\n  ICHECK_GE(axis, 0) << \"axis out of bounds\";\n  ICHECK_LT(axis, a->shape.size()) << \"axis out of bounds\";\n  auto axis_dim = a->shape[axis];\n  int indices_len = static_cast<int>(indices->shape.size());\n\n  int batch_dims_ = batch_dims;\n  if (batch_dims_ != 0) {\n    ICHECK_GE(batch_dims_, -static_cast<int>(indices->shape.size())) << \"batch_dims out of bounds\";\n    ICHECK_LE(batch_dims_, indices->shape.size()) << \"batch_dims out of bounds\";\n\n    if (batch_dims_ < 0) {\n      batch_dims_ = indices->shape.size() + batch_dims_;\n    }\n\n    ICHECK_LT(batch_dims_, a->shape.size()) << \"batch_dims out of bounds\";\n    ICHECK_LE(batch_dims_, axis) << \"batch_dims must be less than or equal to axis\";\n    for (int i = 0; i < batch_dims_; ++i) {\n      auto addr1 = a->shape[i];\n      auto addr2 = indices->shape[i];\n      auto v1 = static_cast<IntImm*>(&addr1)->get()->value;\n      auto v2 = static_cast<IntImm*>(&addr2)->get()->value;\n      ICHECK_EQ(v1, v2) << \"a.shape[\" << i << \"] should be equal to indices.shape[\" << i << \"]\";\n    }\n  }\n\n  // The result shape is a.shape[:axis] + indices.shape[batch_dims:] +\n  // a.shape[axis + 1:].\n\n  Array<PrimExpr> out_shape;\n  for (int i = 0; i < batch_dims_; ++i) {\n    out_shape.push_back(a->shape[i]);\n  }\n  for (int i = batch_dims_; i < axis; ++i) {\n    out_shape.push_back(a->shape[i]);\n  }\n  for (size_t i = static_cast<size_t>(batch_dims_); i < indices->shape.size(); ++i) {\n    out_shape.push_back(indices->shape[i]);\n  }\n  for (size_t i = axis + 1; i < a->shape.size(); ++i) {\n    out_shape.push_back(a->shape[i]);\n  }\n\n  if (mode == \"clip\") {\n    if (batch_dims_ == 0) {\n      return compute(\n          out_shape,\n          [&](const Array<Var>& out_index) {\n            Array<PrimExpr> indices_position;\n            for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {\n              indices_position.push_back(out_index[j]);\n            }\n            Array<PrimExpr> real_indices;\n            for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {\n              real_indices.push_back(out_index[j]);\n            }\n            auto idx = tvm::min(tvm::max(0, indices(indices_position)), axis_dim - 1);\n            real_indices.push_back(idx);\n            for (size_t j = axis + indices_len; j < out_index.size(); ++j) {\n              real_indices.push_back(out_index[j]);\n            }\n            return a(real_indices);\n          },\n          name, tag);\n    } else {\n      return compute(\n          out_shape,\n          [&](const Array<Var>& out_index) {\n            Array<PrimExpr> indices_position;\n            for (size_t j = 0; j < static_cast<size_t>(batch_dims_); ++j) {\n              indices_position.push_back(out_index[j]);\n            }\n            for (size_t j = axis; j < static_cast<size_t>(axis + indices_len - batch_dims_); ++j) {\n              indices_position.push_back(out_index[j]);\n            }\n            Array<PrimExpr> real_indices;\n            for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {\n              real_indices.push_back(out_index[j]);\n            }\n            auto idx = tvm::min(tvm::max(0, indices(indices_position)), axis_dim - 1);\n            real_indices.push_back(idx);\n            for (size_t j = axis + indices_len - batch_dims_; j < out_index.size(); ++j) {\n              real_indices.push_back(out_index[j]);\n            }\n            return a(real_indices);\n          },\n          name, tag);\n    }\n  } else if (mode == \"fast\") {\n    LOG(WARNING) << \"Fast mode segfaults when there are out-of-bounds indices. \"\n                    \"Make sure input indices are in bound\";\n    return compute(\n        out_shape,\n        [&](const Array<Var>& out_index) {\n          Array<PrimExpr> indices_position;\n          for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {\n            indices_position.push_back(out_index[j]);\n          }\n          Array<PrimExpr> real_indices;\n          for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {\n            real_indices.push_back(out_index[j]);\n          }\n          real_indices.push_back(indices(indices_position));\n          for (size_t j = axis + indices_len; j < out_index.size(); ++j) {\n            real_indices.push_back(out_index[j]);\n          }\n          return a(real_indices);\n        },\n        name, tag);\n  } else {  // mode == \"wrap\"\n    return compute(\n        out_shape,\n        [&](const Array<Var>& out_index) {\n          Array<PrimExpr> indices_position;\n          for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {\n            indices_position.push_back(out_index[j]);\n          }\n          Array<PrimExpr> real_indices;\n          for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {\n            real_indices.push_back(out_index[j]);\n          }\n          auto idx = truncmod(truncmod(indices(indices_position), axis_dim) + axis_dim, axis_dim);\n          real_indices.push_back(idx);\n          for (size_t j = axis + indices_len; j < out_index.size(); ++j) {\n            real_indices.push_back(out_index[j]);\n          }\n          return a(real_indices);\n        },\n        name, tag);\n  }\n}\n\n/*!\n * \\brief Return the elements, either from x or y, depending on the condition.\n *\n * \\param condition The condition array.\n * \\param x First array to be selected.\n * \\param y Second array to be selected.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor selected from x or y depending on condition.\n */\ninline Tensor where(const Tensor& condition, const Tensor& x, const Tensor& y,\n                    std::string name = \"T_where\", std::string tag = kBroadcast) {\n  ICHECK_EQ(x->dtype, y->dtype) << \"x and y must have the same dtype: \" << x->dtype << \" vs \"\n                                << y->dtype;\n  auto get_out_shape = [&]() {\n    auto bh1 = detail::BroadcastShape(x->shape, y->shape);\n    Array<PrimExpr> common_shape1(bh1.common_shape.begin(), bh1.common_shape.end());\n    auto bh2 = detail::BroadcastShape(condition->shape, common_shape1);\n    Array<PrimExpr> common_shape2(bh2.common_shape.begin(), bh2.common_shape.end());\n    return common_shape2;\n  };\n\n  auto oshape = get_out_shape();\n\n  auto c_bh = detail::BroadcastShape(condition->shape, oshape);\n  auto x_bh = detail::BroadcastShape(x->shape, oshape);\n  auto y_bh = detail::BroadcastShape(y->shape, oshape);\n\n  auto select = [&](tvm::Array<tvm::tir::Var> ovars) {\n    auto c = condition(InputIndexFromBroadcast(ovars, condition, c_bh.vars1, c_bh.all_vars));\n    auto true_val = x(InputIndexFromBroadcast(ovars, x, x_bh.vars1, x_bh.all_vars));\n    auto false_val = y(InputIndexFromBroadcast(ovars, y, y_bh.vars1, y_bh.all_vars));\n    return tvm::tir::Select(c != 0, true_val, false_val);\n  };\n\n  return compute(oshape, select, name, tag);\n}\n\n/*!\n * \\brief Creates an operation to repeat elements of an array\n *\n * \\param x The input tensor\n * \\param repeats The number of repetitions for each element\n * \\param axis The axis along which to repeat values (allows\n * negative indices as offsets from the last dimension)\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the repeat operation\n */\ninline Tensor repeat(const Tensor& x, int repeats, int axis, std::string name = \"T_repeat\",\n                     std::string tag = kBroadcast) {\n  int ndim = static_cast<int>(x->shape.size());\n  ICHECK(-ndim - 1 <= axis && axis <= ndim)\n      << \"repeat only accepts `axis` in [-data.ndim - 1, data.ndim]\"\n      << \", but got axis = \" << axis << \", and data.ndim = \" << ndim;\n  ICHECK(repeats >= 1) << \"repeat only accepts `repeats >= 1`\"\n                       << \", but got repeats = \" << repeats;\n  if (axis < 0) {\n    // Calculate offset from last dimension\n    axis += ndim;\n  }\n  Array<PrimExpr> new_shape;\n  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n    new_shape.push_back(x->shape[i]);\n  }\n  new_shape.push_back(repeats * x->shape[axis]);\n  for (size_t i = axis + 1; i < x->shape.size(); ++i) {\n    new_shape.push_back(x->shape[i]);\n  }\n\n  return compute(\n      new_shape,\n      [&](const Array<Var>& indices) {\n        Array<PrimExpr> idx;\n        for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {\n          idx.push_back(indices[i]);\n        }\n        idx.push_back(indexdiv(indices[axis], repeats));\n        for (size_t i = axis + 1; i < indices.size(); ++i) {\n          idx.push_back(indices[i]);\n        }\n        return x(idx);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation to tile elements of an array\n *\n * \\param x The input tensor\n * \\param reps The number of times for repeating the tensor\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the tile operation\n */\ninline Tensor tile(const Tensor& x, Array<Integer> reps, std::string name = \"T_tile\",\n                   std::string tag = kBroadcast) {\n  size_t ndim = x->shape.size();\n  size_t rdim = reps.size();\n  size_t tdim = (ndim > rdim) ? ndim : rdim;\n  Array<PrimExpr> data_shape;\n  Array<PrimExpr> reps_shape;\n  Array<PrimExpr> new_shape;\n  if (ndim == rdim) {\n    for (size_t i = 0; i < ndim; ++i) {\n      data_shape.push_back(x->shape[i]);\n      reps_shape.push_back(reps[i]);\n    }\n  } else if (ndim > rdim) {\n    for (size_t i = 0; i < ndim; ++i) data_shape.push_back(x->shape[i]);\n    for (size_t i = 0; i < (ndim - rdim); ++i) reps_shape.push_back(1);\n    for (size_t i = 0; i < rdim; ++i) reps_shape.push_back(reps[i]);\n  } else {\n    for (size_t i = 0; i < (rdim - ndim); ++i) data_shape.push_back(1);\n    for (size_t i = 0; i < ndim; ++i) data_shape.push_back(x->shape[i]);\n    for (size_t i = 0; i < rdim; ++i) reps_shape.push_back(reps[i]);\n  }\n  for (size_t i = 0; i < tdim; ++i) new_shape.push_back(data_shape[i] * reps_shape[i]);\n\n  if (is_empty_shape(new_shape)) {\n    return compute(\n        new_shape, [&](const Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name, tag);\n  } else {\n    return compute(\n        new_shape,\n        [&](const Array<Var>& indices) {\n          Array<PrimExpr> idx;\n          if (ndim >= rdim) {\n            for (size_t i = 0; i < ndim; ++i) idx.push_back(indexmod(indices[i], x->shape[i]));\n          } else {\n            for (size_t i = 0; i < ndim; ++i)\n              idx.push_back(indexmod(indices[rdim - ndim + i], x->shape[i]));\n          }\n          return x(idx);\n        },\n        name, tag);\n  }\n}\n\n/*!\n * \\brief Creates an operation to tile elements of an array\n *\n * \\param x The input tensor\n * \\param new_shape The shape of the output after tiling\n * \\param rdim The rank of the reps, provided by caller\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the tile operation\n */\ninline Tensor dyn_tile(const Tensor& x, Array<PrimExpr> new_shape, size_t rdim,\n                       std::string name = \"T_tile\", std::string tag = kBroadcast) {\n  size_t ndim = x->shape.size();\n  if (is_empty_shape(new_shape)) {\n    return compute(\n        new_shape, [&](const Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name, tag);\n  } else {\n    return compute(\n        new_shape,\n        [&](const Array<Var>& indices) {\n          Array<PrimExpr> idx;\n          if (ndim >= rdim) {\n            for (size_t i = 0; i < ndim; ++i) {\n              idx.push_back(indexmod(indices[i], x->shape[i]));\n            }\n          } else {\n            for (size_t i = 0; i < ndim; ++i) {\n              idx.push_back(indexmod(indices[rdim - ndim + i], x->shape[i]));\n            }\n          }\n          return x(idx);\n        },\n        name, tag);\n  }\n}\n\n/*!\n * \\brief Gather values along given axis from given indices.\n *\n * \\param data The input data to the operator.\n * \\param axis The axis along which to index.\n * \\param indices The indices of values to gather.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the gather operation\n */\ninline Tensor gather(const Tensor& data, int axis, const Tensor& indices,\n                     std::string name = \"T_gather\", std::string tag = kInjective) {\n  size_t ndim_d = data->shape.size();\n  size_t ndim_i = indices->shape.size();\n  ICHECK_GE(ndim_d, 1) << \"Cannot gather from a scalar.\";\n  ICHECK_EQ(ndim_d, ndim_i);\n  if (axis < 0) {\n    axis += ndim_d;\n  }\n  ICHECK_GE(axis, 0);\n  ICHECK_LT(axis, ndim_d);\n  if (indices->shape[axis].as<IntImmNode>()) {\n    size_t indices_dim_i = static_cast<size_t>(GetConstInt(indices->shape[axis]));\n    ICHECK_GE(indices_dim_i, 1);\n  }\n  ICHECK(indices->dtype.is_int() || indices->dtype.is_uint());\n\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < ndim_i; ++i) {\n    out_shape.push_back(indices->shape[i]);\n  }\n\n  return compute(\n      out_shape,\n      [&](const Array<Var>& out_index) {\n        Array<PrimExpr> indices_position;\n        for (size_t i = 0; i < ndim_i; ++i) {\n          indices_position.push_back(out_index[i]);\n        }\n        Array<PrimExpr> real_indices;\n        for (size_t i = 0; i < ndim_i; ++i) {\n          if (i == static_cast<size_t>(axis)) {\n            real_indices.push_back(indices(indices_position));\n          } else {\n            real_indices.push_back(indices_position[i]);\n          }\n        }\n        return data(real_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Gather elements from a n-dimension array.\n *\n * \\param data The source array.\n * \\param indices The indices of the values to extract.\n * \\param batch_dims The number of batch dimensions.\n * \\param name The name of the operation.\n * \\param tag The tag to mark the operation.\n *\n * \\return A Tensor whose op member is the gather_nd operation\n */\ninline Tensor gather_nd(const Tensor& data, const Tensor& indices, int batch_dims = 0,\n                        std::string name = \"T_gather_nd\", std::string tag = kInjective) {\n  size_t ndim_d = data->shape.size();\n  size_t ndim_i = indices->shape.size();\n  ICHECK_GE(ndim_i, 1) << \"indices tensor must have at least 1 dimensions\";\n  size_t indices_dim0 = static_cast<size_t>(GetConstInt(indices->shape[0]));\n  ICHECK_LE(indices_dim0, ndim_d) << \"dim 0 of indices tensor must be no more \"\n                                  << \"than dimensions of data tensor\";\n  Array<PrimExpr> out_shape;\n  for (size_t i = 1; i < ndim_i; ++i) {\n    out_shape.push_back(indices->shape[i]);\n  }\n  for (size_t i = indices_dim0 + batch_dims; i < ndim_d; ++i) {\n    out_shape.push_back(data->shape[i]);\n  }\n  return compute(\n      out_shape,\n      [&](const Array<Var>& out_index) {\n        Array<PrimExpr> indices_position;\n        indices_position.push_back(0);\n        for (size_t i = 0; i < ndim_i - 1; ++i) {\n          indices_position.push_back(out_index[i]);\n        }\n        Array<PrimExpr> real_indices;\n        for (size_t i = 0; i < static_cast<size_t>(batch_dims); ++i) {\n          real_indices.push_back(out_index[i]);\n        }\n        for (size_t i = 0; i < indices_dim0; ++i) {\n          indices_position.Set(0, make_const(DataType::Int(32), i));\n          if (indices->dtype.is_int() || indices->dtype.is_uint()) {\n            real_indices.push_back(indices(indices_position));\n          } else {\n            real_indices.push_back(tvm::cast(tvm::DataType::Int(32), indices(indices_position)));\n          }\n        }\n        if (real_indices.size() == ndim_d) {\n          return data(real_indices);\n        }\n        for (size_t i = ndim_i - 1; i < out_index.size(); ++i) {\n          real_indices.push_back(out_index[i]);\n        }\n        return data(real_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Creates an operation that calculates a matrix multiplication\n *  (row-major notation):\n *      A(i, k) * B(k, j), if trans_a == trans_b\n *          the usual transposed combinations, otherwise\n *\n * \\param A The matrix A\n * \\param B The matrix B\n * \\param trans_a Is A's layout transposed?\n * \\param trans_b Is B's layout transposed?\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the matmul operation\n */\ninline tvm::te::Tensor matmul(const tvm::te::Tensor& A, const tvm::te::Tensor& B,\n                              bool trans_a = false, bool trans_b = false,\n                              std::string name = \"T_matmul\", std::string tag = kMatMul) {\n  tvm::Array<tvm::PrimExpr> output_shape{A->shape[trans_a ? 1 : 0], B->shape[trans_b ? 0 : 1]};\n  auto k = tvm::te::reduce_axis(tvm::Range{0, A->shape[trans_a ? 0 : 1]}, \"k\");\n  auto l = [&](tvm::tir::Var i, tvm::tir::Var j) {\n    return tvm::sum((trans_a ? A[k][i] : A[i][k]) * (trans_b ? B[j][k] : B[k][j]), {k});\n  };\n  return tvm::te::compute(output_shape, l, name, tag);\n}\n\n/*!\n * \\brief A generalization of matrix multiplication to tensors.\n *\n * \\param A The tensor A\n * \\param B The tensor B\n * \\param axes The number of the dimensions to reduce over\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor computing the result\n */\ninline Tensor tensordot(const Tensor& A, const tvm::te::Tensor& B, int axes = 2,\n                        std::string name = \"T_tensordot\", std::string tag = kMatMul) {\n  ICHECK_GE(A->shape.size(), axes);\n  ICHECK_GE(B->shape.size(), axes);\n\n  Array<PrimExpr> output_shape(A->shape.begin(), A->shape.end() + (-axes));\n  for (auto it = B->shape.begin() + axes; it != B->shape.end(); ++it) output_shape.push_back(*it);\n\n  Array<IterVar> iter_vars;\n  for (int i = 0; i < axes; ++i)\n    iter_vars.push_back(reduce_axis(Range(0, B->shape[i]), \"k\" + std::to_string(i)));\n\n  auto func = [&A, &B, &iter_vars, axes](const Array<Var>& input_indices) {\n    Array<PrimExpr> A_indices(input_indices.begin(),\n                              input_indices.begin() + (A->shape.size() - axes));\n    for (auto& v : iter_vars) A_indices.push_back(v);\n\n    Array<PrimExpr> B_indices;\n    for (auto& v : iter_vars) B_indices.push_back(v);\n\n    auto it = input_indices.begin() + (A->shape.size() - axes);\n    for (; it != input_indices.end(); ++it) B_indices.push_back(*it);\n\n    // Some passes don't like reductions with empty axis, so avoid it here\n    if (iter_vars.empty()) {\n      return A(A_indices) * B(B_indices);\n    } else {\n      return sum(A(A_indices) * B(B_indices), iter_vars);\n    }\n  };\n\n  return compute(output_shape, func, name, tag);\n}\n\n/*!\n * \\brief A generalization of matrix multiplication to tensors.\n *\n * \\param A The tensor A\n * \\param B The tensor B\n * \\param A_axes The indices of the dimensions of tensor A to reduce over\n * \\param B_axes The indices of the dimensions of tensor B to reduce over\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor computing the result\n */\ninline Tensor tensordot(const Tensor& A, const tvm::te::Tensor& B, Array<PrimExpr> A_axes,\n                        Array<PrimExpr> B_axes, std::string name = \"T_tensordot\",\n                        std::string tag = kMatMul) {\n  ICHECK_EQ(A_axes.size(), B_axes.size());\n\n  auto A_axes_val = GetConstIntValues(A_axes, \"A_axes\");\n  auto B_axes_val = GetConstIntValues(B_axes, \"B_axes\");\n\n  Array<PrimExpr> output_shape;\n  for (unsigned i = 0; i < A->shape.size(); ++i)\n    if (std::find(A_axes_val.begin(), A_axes_val.end(), i) == A_axes_val.end())\n      output_shape.push_back(A->shape[i]);\n  for (unsigned i = 0; i < B->shape.size(); ++i)\n    if (std::find(B_axes_val.begin(), B_axes_val.end(), i) == B_axes_val.end())\n      output_shape.push_back(B->shape[i]);\n\n  Array<IterVar> iter_vars;\n  for (unsigned i = 0; i < B_axes_val.size(); ++i)\n    iter_vars.push_back(reduce_axis(Range(0, B->shape[B_axes_val[i]]), \"k\" + std::to_string(i)));\n\n  auto func = [&A, &B, &iter_vars, A_axes_val, B_axes_val](const Array<Var>& input_indices) {\n    int idx_input = 0;\n    Array<PrimExpr> A_indices;\n    for (unsigned i = 0; i < A->shape.size(); ++i) {\n      auto axes_pos = std::find(A_axes_val.begin(), A_axes_val.end(), i);\n      if (axes_pos == A_axes_val.end()) {\n        A_indices.push_back(input_indices[idx_input++]);\n      } else {\n        A_indices.push_back(iter_vars[axes_pos - A_axes_val.begin()]);\n      }\n    }\n\n    Array<PrimExpr> B_indices;\n    for (unsigned i = 0; i < B->shape.size(); ++i) {\n      auto axes_pos = std::find(B_axes_val.begin(), B_axes_val.end(), i);\n      if (axes_pos == B_axes_val.end()) {\n        B_indices.push_back(input_indices[idx_input++]);\n      } else {\n        B_indices.push_back(iter_vars[axes_pos - B_axes_val.begin()]);\n      }\n    }\n    return sum(A(A_indices) * B(B_indices), iter_vars);\n  };\n  return compute(output_shape, func, name, tag);\n}\n\ninline Tensor arange(const PrimExpr& start, const PrimExpr& stop, const PrimExpr& step,\n                     DataType dtype, std::string name = \"T_arange\", std::string tag = kInjective) {\n  PrimExpr num_elem = tvm::cast(\n      tvm::DataType::Int(32), tvm::ceil(tvm::cast(tvm::DataType::Float(32), stop - start) / step));\n  Array<PrimExpr> shape;\n  return compute(\n      {num_elem},\n      [&](const Array<Var>& indices) { return tvm::cast(dtype, start + step * indices[0]); }, name,\n      tag);\n}\n\n/*!\n * \\brief Produce grids by expanding input over dimensions defined by other inputs\n *\n * \\param inputs The input tensors\n * \\param indexing The indexing mode, either \"xy\" or \"ij\"\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the meshgrid operation\n */\ninline Array<Tensor> meshgrid(const Array<Tensor>& inputs, const std::string& indexing,\n                              std::string name = \"T_meshgrid\", std::string tag = kInjective) {\n  const bool cartesian_indexing = indexing == \"xy\" && inputs.size() >= 2;\n  Array<PrimExpr> out_shape;\n  for (size_t i = 0; i < inputs.size(); ++i) {\n    const int src_index = (cartesian_indexing && i < 2) ? 1 - i : i;\n    out_shape.push_back(inputs[src_index]->shape.size() == 0 ? 1 : inputs[src_index]->shape[0]);\n  }\n  Array<Tensor> result;\n  for (size_t i = 0; i < inputs.size(); ++i) {\n    result.push_back(compute(\n        out_shape,\n        [&](const Array<Var>& indices) {\n          const int src_index = (cartesian_indexing && i < 2) ? 1 - i : i;\n          auto ndim = inputs[i]->GetShape().size();\n          Array<PrimExpr> real_indices = {};\n          if (ndim > 0) {\n            real_indices = {indices[src_index]};\n          }\n          return inputs[i](real_indices);\n        },\n        name, tag));\n  }\n  return result;\n}\n\n/*!\n * \\brief Transform the layout according to \\p src_layout and \\p dst_layout\n * \\param src the source input.\n * \\param src_layout the source layout.\n * \\param dst_layout the destination layout.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return A tensor with shape in \\p dst_layout\n */\ninline Tensor layout_transform(const Tensor& src, const std::string& src_layout,\n                               const std::string& dst_layout,\n                               const std::string name = \"T_layout_trans\",\n                               const std::string tag = kInjective) {\n  Layout src_layout_struct(src_layout);\n  Layout dst_layout_struct(dst_layout);\n\n  if (src_layout_struct.Equals(dst_layout_struct)) {\n    return src;\n  }\n\n  ICHECK(src_layout_struct.defined() && dst_layout_struct.defined())\n      << \"cannot convert from/to undefined layout\";\n\n  auto layout_converter = tir::BijectiveLayout(src_layout_struct, dst_layout_struct);\n  ICHECK(layout_converter.defined())\n      << \"cannot convert from \" << src_layout << \" to \" << dst_layout;\n\n  Array<PrimExpr> dst_shape = layout_converter.ForwardShape(src->shape);\n\n  return compute(\n      dst_shape,\n      [&](const Array<Var>& dst_indices) {\n        Array<PrimExpr> dst_indices_expr(dst_indices.begin(), dst_indices.end());\n        Array<PrimExpr> src_indices = layout_converter.BackwardIndex(dst_indices_expr);\n        PrimExpr in_range = PrimExpr(1) > PrimExpr(0);  // init with dtype=bool and value=true\n        for (size_t i = 0; i < src.ndim(); ++i) {\n          in_range = in_range && (src_indices[i] < src->shape[i]);\n        }\n        return if_then_else(in_range, src(src_indices), tvm::cast(src->dtype, PrimExpr(0)));\n      },\n      name, tag);\n}\n\n/*! \\brief Utility function for auto_scheduler_layout_transform */\ninline void parse_auto_scheduler_layout(const String& layout, Array<PrimExpr>* shape,\n                                        std::vector<std::string>* axes) {\n  int32_t factor = 0;\n  std::string axis = \"\";\n  for (char c : std::string(layout)) {\n    if (c >= 'A' && c <= 'z') {\n      axis += c;\n      if (factor != 0) {\n        shape->push_back(factor);\n        factor = 0;\n      }\n    } else if (c >= '0' && c <= '9') {\n      factor = factor * 10 + c - '0';\n      if (!axis.empty()) {\n        axes->push_back(axis);\n        axis = \"\";\n      }\n    } else {\n      LOG(FATAL) << \"Invalid layout \" << layout;\n    }\n  }\n  if (!axis.empty()) {\n    axes->push_back(axis);\n  }\n}\n\n/*!\n * \\brief Transform the auto-scheduler generated layout according to\n *        \\p src_layout and \\p dst_layout\n * \\param src the source input.\n * \\param src_layout the source layout.\n * \\param dst_layout the destination layout.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return A tensor with shape in \\p dst_layout\n */\ninline Tensor auto_scheduler_layout_transform(const Tensor& src, const String& src_layout,\n                                              const String& dst_layout,\n                                              const String name = \"T_auto_scheduler_layout_trans\",\n                                              const String tag = kInjective) {\n  Array<PrimExpr> src_shape;\n  std::vector<std::string> src_axes;\n  Array<PrimExpr> dst_shape;\n  std::vector<std::string> dst_axes;\n\n  parse_auto_scheduler_layout(src_layout, &src_shape, &src_axes);\n  parse_auto_scheduler_layout(dst_layout, &dst_shape, &dst_axes);\n  return compute(\n      dst_shape,\n      [&](const Array<Var>& dst_indices) {\n        Array<PrimExpr> dst_indices_expr(dst_indices.begin(), dst_indices.end());\n        Array<PrimExpr> src_indices;\n        for (const std::string& src_axis : src_axes) {\n          PrimExpr src_index = 0;\n          CHECK_EQ(dst_indices_expr.size(), dst_axes.size());\n          for (size_t i = 0; i < dst_axes.size(); ++i) {\n            if (dst_axes[i] == src_axis) {\n              src_index = src_index * dst_shape[i] + dst_indices_expr[i];\n            }\n          }\n          src_indices.push_back(src_index);\n        }\n        return src(src_indices);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Transform the meta-schedule generated layout according to TIR's IndexMap\n * \\param src the source input.\n * \\param index_map The TIR IndexMap\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return A tensor. The layout transformation method\n * \\note Example:\n *\n * For the indexing pattern below:\n *\n *  for i in range(32):\n *    for j in range(64):\n *      load A[\n *        i / 16 *  4 + j / 16,\n *        i % 16 * 16 + j % 16,\n *      ]\n *\n *  The corresponding indexing pattern in TIR is:\n *\n *    A[i, j] => A'[i / 4, j / 16, i % 4, j % 16]\n *\n *  which converts the pattern to:\n *\n *  for i in range(32):\n *    for j in range(64):\n *      load A'[\n *        i / 16 + j / 64,\n *        i % 16,\n *        j % 64 / 16,\n *        j % 16,\n *      ]\n *\n *  In this case, the transformation pattern is:\n *    A'[a, b, c, d] = A[a * 4 + c, b * 16 + d]\n */\ninline Tensor meta_schedule_layout_transform(const Tensor& src, const tir::IndexMap& index_map,\n                                             const String name = \"T_meta_schedule_layout_trans\",\n                                             const String tag = kInjective) {\n  Array<Range> iter_domain;\n  iter_domain.reserve(src->shape.size());\n  for (const PrimExpr& e : src->shape) {\n    iter_domain.push_back(Range::FromMinExtent(make_zero(e->dtype), e));\n  }\n  Array<PrimExpr> post_transform_shape = index_map->MapShape(src->shape);\n  return compute(\n      post_transform_shape,\n      [src, inv = index_map.Inverse(iter_domain)](const Array<Var>& indices) -> PrimExpr {\n        return src(inv->MapIndices(Array<PrimExpr>{indices.begin(), indices.end()}));\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Get the shape of input tensor.\n * \\param src the input tensor.\n * \\param dtype the type of the elements in the tensor.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return Tensor of input shape.\n */\ninline Tensor shape(const Tensor& src, DataType dtype, const std::string name = \"T_shape\",\n                    const std::string tag = kInjective) {\n  int ndim = static_cast<int>(src->shape.size());\n  Array<PrimExpr> out_shape{ndim};\n  return compute(\n      out_shape,\n      [&](const Array<Var>& indices) {\n        auto idx = indices[0];\n        PrimExpr ret = 0;\n        for (int i = 0; i < ndim; ++i) {\n          ret = tvm::if_then_else(idx == i, src->shape[i], ret);\n        }\n        return tvm::cast(dtype, ret);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Get the size of input tensor.\n * \\param src the input tensor.\n * \\param dtype the type of the elements in the tensor.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return Tensor of input shape.\n */\ninline Tensor ndarray_size(const Tensor& src, const DataType& dtype,\n                           const std::string& name = \"ndarray_size\",\n                           const std::string& tag = kInjective) {\n  int ndim = static_cast<int>(src->shape.size());\n  Array<PrimExpr> out_ndarray_size = {};\n  return compute(\n      out_ndarray_size,\n      [&](const Array<Var>& indices) {\n        PrimExpr ret = 1;\n        for (int i = 0; i < ndim; ++i) {\n          ret *= src->shape[i];\n        }\n        return tvm::cast(dtype, ret);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Returns a one-hot tensor where the locations repsented by indices take value on_value,\n    other locations take value off_value.\n * \\param indices locations to set to on_value.\n * \\param on_value value that locations represented by indices take on.\n * \\param off_value value that other locations take on.\n * \\param depth depth of the one-hot dimension.\n * \\param axis axis to fill.\n * \\param dtype data type of the output tensor.\n * \\param oshape shape of the output tensor.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return one-hot tensor.\n */\ninline Tensor one_hot(const Tensor& indices, const PrimExpr on_value, const PrimExpr off_value,\n                      int depth, int axis, const DataType& dtype,\n                      Array<PrimExpr> oshape = Array<PrimExpr>(),\n                      const std::string name = \"T_one_hot\", const std::string tag = kInjective) {\n  int true_axis = (axis == -1) ? indices->shape.size() : axis;\n  if (oshape.size() == 0) {\n    int ndim = indices->shape.size() + 1;\n    int indices_index = 0;\n    for (int i = 0; i < ndim; i++) {\n      if (i == true_axis) {\n        oshape.push_back(Integer(depth));\n      } else {\n        oshape.push_back(indices->shape[indices_index++]);\n      }\n    }\n  }\n\n  PrimExpr on_value_cast = cast(dtype, on_value);\n  PrimExpr off_value_cast = cast(dtype, off_value);\n  return compute(\n      oshape,\n      [&](const Array<Var>& iter_vars) {\n        Array<Var> indices_indices;\n        for (size_t i = 0; i < iter_vars.size(); i++) {\n          if (static_cast<int>(i) == true_axis) {\n            continue;\n          }\n\n          indices_indices.push_back(iter_vars[i]);\n        }\n\n        auto idx = iter_vars[true_axis];\n        return tir::Select(indices(indices_indices) == idx, on_value_cast, off_value_cast);\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Get a dense tensor.\n * \\param sparse_indices sparse_indices[i] contains sparse_values[i] will be placed.\n * \\param output_shape is the shape of the dense output tensor .\n * \\param sparse_values is a 0-D or 1-D tensor. Values for each row of sparse_indices.\n * \\param default_value is a 0-D tensor. Defaults to zero.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return Tensor of output_shape.\n */\ninline Tensor sparse_to_dense(const Tensor& sparse_indices, const Array<PrimExpr>& output_shape,\n                              const Tensor& sparse_values, const PrimExpr& default_value,\n                              const std::string name = \"T_sparse_to_dense\",\n                              const std::string tag = kInjective) {\n  ICHECK(sparse_indices->dtype.is_int()) << \"sparse_indices only accepts integer values\";\n  ICHECK_LE(sparse_indices->shape.size(), 3)\n      << \"sparse_indices tensor should be 0D, 1D, or 2D only\";\n  ICHECK_LE(sparse_values->shape.size(), 2) << \"sparse_values tensor should be 0D or 1D only\";\n\n  const auto rank_sparse_indices = static_cast<int>(sparse_indices->shape.size());\n  Array<PrimExpr> oshape;\n  for (auto l : output_shape) {\n    oshape.push_back(l);\n  }\n  return compute(\n      oshape,\n      [&](const Array<Var>& indices) {\n        PrimExpr ret = default_value;\n        if (0 == rank_sparse_indices) {\n          ret = if_then_else(indices[0] == sparse_indices(), sparse_values(), ret);\n        } else if (1 == rank_sparse_indices) {\n          for (int j = 0; j < GetConstInt(sparse_indices->shape[0]); j++) {\n            ret = if_then_else(indices[0] == sparse_indices[j], sparse_values[j], ret);\n          }\n        } else {\n          for (int j = 0; j < GetConstInt(sparse_indices->shape[0]); j++) {\n            PrimExpr aggregate_condition;\n            for (int k = 0; k < GetConstInt(sparse_indices->shape[1]); k++) {\n              PrimExpr comparision = indices[k] == sparse_indices[j][k];\n              aggregate_condition = 0 == k ? comparision : aggregate_condition && comparision;\n            }\n            ret = if_then_else(aggregate_condition, sparse_values[j], ret);\n          }\n        }\n        return ret;\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Returns a tensor with the diagonal of input tensor replaced with the provided diagonals.\n * \\param input input tensor.\n * \\param diagonal values to be filled in the diagonals.\n * \\param k1 lower limit (included) of the range of diagonals.\n * \\param k2 upper limit (included) of the range of diagonals.\n * \\param super_diag_right_align bool, true iff super-diagonal is right aligned (left-padded).\n * \\param sub_diag_right_align bool, true iff sub-diagonal is right aligned (left-padded).\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return new tensor with given diagonal values.\n */\ninline Tensor matrix_set_diag(const Tensor& input, const Tensor& diagonal, int k1, int k2,\n                              bool super_diag_right_align, bool sub_diag_right_align,\n                              const std::string name = \"T_matrix_set_diag\",\n                              const std::string tag = kInjective) {\n  size_t ndim = input->shape.size() - 1;\n\n  bool only_one_diagonal = k1 == k2;\n\n  return compute(\n      input->shape,\n      [&](const Array<Var>& iter_vars) {\n        auto get_diag = [&]() {\n          Array<PrimExpr> diagonal_indices;\n          PrimExpr k, offset = 0;\n          for (size_t i = 0; i < ndim - 1; i++) {\n            diagonal_indices.push_back(iter_vars[i]);\n          }\n          if (only_one_diagonal) {\n            k = k1;\n          } else {\n            // Determining which diagonal/sub-diagonal/super-diagonal it is\n            k = iter_vars[ndim] - iter_vars[ndim - 1];\n            diagonal_indices.push_back(k2 - k);\n\n            // Calculating the offset in diagonal tensor for this diagonal\n            auto get_offset = [&](PrimExpr M, PrimExpr N) {\n              // offset = max_diagonal_length - diagonal_length\n              return diagonal->shape[diagonal->shape.size() - 1] - if_then_else(M < N, M, N);\n            };\n            offset = if_then_else(\n                k >= 0,\n                super_diag_right_align ? get_offset(input->shape[ndim] - k, input->shape[ndim - 1])\n                                       : 0,\n                sub_diag_right_align ? get_offset(input->shape[ndim], input->shape[ndim - 1] + k)\n                                     : 0);\n          }\n          diagonal_indices.push_back(if_then_else(k >= 0, iter_vars[ndim - 1], iter_vars[ndim]) +\n                                     offset);\n          return diagonal(diagonal_indices);\n        };\n        return if_then_else((PrimExpr)iter_vars[ndim] - iter_vars[ndim - 1] >= k1,\n                            if_then_else((PrimExpr)iter_vars[ndim] - iter_vars[ndim - 1] <= k2,\n                                         get_diag(), input(iter_vars)),\n                            input(iter_vars));\n      },\n      name, tag);\n}\n\n/*!\n * \\brief Numpy style advanced indexing with tensor.\n * \\param data is input data.\n * \\param indices is list of indexing tensors.\n * \\param name output tensor name.\n * \\param tag output tensor tag.\n * \\return Output tensor.\n */\ninline Tensor adv_index(const Tensor& data, const Array<Tensor>& indices,\n                        const std::string name = \"advanced_index\",\n                        const std::string tag = kInjective) {\n  ICHECK_LE(indices.size(), data->shape.size()) << \"too many indices for data!\";\n  Array<PrimExpr> oshape;\n  Array<PrimExpr> broadcast_shape;\n  Array<Tensor> bindices;\n\n  broadcast_shape = indices[0]->shape;\n  for (size_t i = 1; i < indices.size(); ++i) {\n    auto bh = detail::BroadcastShape(broadcast_shape, indices[i]->shape);\n    broadcast_shape = Array<PrimExpr>(bh.common_shape.begin(), bh.common_shape.end());\n  }\n  if (indices.size() == 1) {\n    // quick path\n    bindices = indices;\n  } else {\n    // Do broadcast for indices\n    for (size_t i = 0; i < indices.size(); ++i) {\n      bindices.push_back(broadcast_to(indices[i], broadcast_shape));\n    }\n  }\n\n  for (const auto& dim : broadcast_shape) {\n    oshape.push_back(dim);\n  }\n  for (size_t i = indices.size(); i < data->shape.size(); ++i) {\n    oshape.push_back(data->shape[i]);\n  }\n\n  return compute(\n      oshape,\n      [&](const Array<Var>& iter_var) {\n        Array<PrimExpr> tensor_indices;\n        for (size_t i = 0; i < broadcast_shape.size(); ++i) {\n          tensor_indices.push_back(iter_var[i]);\n        }\n\n        Array<PrimExpr> real_indices;\n        for (size_t i = 0; i < bindices.size(); ++i) {\n          real_indices.push_back(bindices[i](tensor_indices));\n        }\n        for (size_t i = broadcast_shape.size(); i < iter_var.size(); ++i) {\n          real_indices.push_back(iter_var[i]);\n        }\n\n        return data(real_indices);\n      },\n      name, tag);\n}\n\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Topi utility function\n * \\file topi/utils.h\n */\n#ifndef TVM_TOPI_UTILS_H_\n#define TVM_TOPI_UTILS_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/packed_func.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::runtime;\n\n/*! \\brief Canonicalize an argument that may be Array<Expr> or int to Array<Expr> */\ninline Array<Integer> ArrayOrInt(TVMArgValue arg) {\n  if (arg.type_code() == kDLInt || arg.type_code() == kDLUInt) {\n    Array<Integer> result;\n    result.push_back(arg.operator int());\n    return result;\n  } else {\n    return arg;\n  }\n}\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/vision/reorg.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Reorg op constructions\n * \\file vision/reorg.h\n */\n#ifndef TVM_TOPI_VISION_REORG_H_\n#define TVM_TOPI_VISION_REORG_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/constant_utils.h>\n#include <tvm/topi/reduction.h>\n#include <tvm/topi/tags.h>\n#include <tvm/topi/transform.h>\n\n#include <algorithm>\n#include <string>\n\nnamespace tvm {\nnamespace topi {\nnamespace vision {\n\nusing namespace tvm::te;\n\n/*!\n * \\brief Reorg operation\n *\n * \\param data The input tensor. Can be any dimension\n * \\param stride The input integer used as stride in reorg operation\n * \\param name The name of the operation\n * \\param tag The tag to mark the operation\n *\n * \\return A Tensor whose op member is the reorg operation\n */\ninline Tensor reorg(const Tensor& data, int stride = 1, std::string name = \"tensor\",\n                    std::string tag = \"reorg_output\") {\n  auto input_shape = data->shape;\n\n  int batch = GetConstInt(input_shape[0]);\n  int c_in = GetConstInt(input_shape[1]);\n  int h_in = GetConstInt(input_shape[2]);\n  int w_in = GetConstInt(input_shape[3]);\n  int out_c = c_in / (stride * stride);\n\n  auto out = tvm::te::compute(\n      input_shape,\n      [&](Var b, Var k, Var j, Var i) {\n        return data(b * stride * stride, indexmod(k, out_c) * stride * stride,\n                    (j * stride + indexdiv(indexdiv(k, out_c), stride)) * stride,\n                    (i * stride + indexmod(indexdiv(k, out_c), stride)));\n      },\n      name, tag);\n\n  out_c = c_in * stride * stride;\n  int out_h = h_in / stride;\n  int out_w = w_in / stride;\n\n  Array<PrimExpr> out_shape = {batch, out_c, out_h, out_w};\n  return reshape(out, out_shape);\n}\n}  // namespace vision\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_VISION_REORG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/x86/bnn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file x86/bnn.h\n * \\brief x86 schedule for binary operations\n */\n#ifndef TVM_TOPI_X86_BNN_H_\n#define TVM_TOPI_X86_BNN_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace x86 {\n/*!\n * \\brief Create a generic schedule for binarize_pack\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_binarize_pack(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto _schedule = [&](const Tensor& out) {\n    s[out].parallel(out->op.as<ComputeOpNode>()->axis[0]);\n  };\n\n  std::function<void(Operation)> traverse;\n  traverse = [&](const Operation& op) {\n    if (op->tag == \"binarize_pack\") {\n      _schedule(op.output(0));\n    } else {\n      LOG(ERROR) << \"Unsupported operator \" << op->tag;\n    }\n  };\n\n  traverse(outs[0]->op);\n  return s;\n}\n\n/*!\n * \\brief Create a generic schedule for binary_dense\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_binary_dense(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n\n  auto _schedule = [&](const Tensor& A, const Tensor& B, const Tensor& C) {\n    IterVar co, ci;\n    s[C].split(s[C]->op.as<ComputeOpNode>()->reduce_axis[0], 8, &co, &ci);\n    s[C].parallel(s[C]->op.as<ComputeOpNode>()->axis[0]);\n\n    Tensor out;\n    if (detail::contains(s->outputs, C->op)) {\n      out = C;\n    } else {\n      out = outs[0]->op.output(0);\n    }\n\n    IterVar xo, xi;\n    s[out].split(out->op.as<ComputeOpNode>()->axis[1], 8, &xo, &xi);\n    s[out].vectorize(xi);\n  };\n\n  std::function<void(Operation)> traverse;\n  traverse = [&](const Operation& op) {\n    // Inline all one-to-one-mapping operators except the last stage (output)\n    if (is_broadcast(op->tag)) {\n      if (!detail::contains(s->outputs, op)) {\n        s[op].compute_inline();\n      }\n      for (auto tensor : op->InputTensors()) {\n        if (tensor->op->InputTensors().size() > 0) {\n          traverse(tensor->op);\n        }\n      }\n    } else if (op->tag == \"binary_dense\") {\n      auto output = op.output(0);\n      auto data = op->InputTensors()[0];\n      auto weight = op->InputTensors()[1];\n      _schedule(data, weight, output);\n    } else {\n      LOG(ERROR) << \"Unsupported operator \" << op->tag;\n    }\n  };\n\n  traverse(outs[0]->op);\n  return s;\n}\n\n}  // namespace x86\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_X86_BNN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/x86/default.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file x86/default.h\n * \\brief default x86 schedule\n */\n#ifndef TVM_TOPI_X86_DEFAULT_H_\n#define TVM_TOPI_X86_DEFAULT_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule_pass.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace x86 {\n/*!\n * \\brief Helper to create a default x86 schedule for the given ops.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n * \\param auto_inline Whether to apply the auto inline step.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule MakeDefaultSchedule(const Target& target, const Array<Tensor>& outs,\n                                    bool auto_inline) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  auto x = outs[0];\n  auto axis = s[x]->op.as<ComputeOpNode>()->axis;\n\n  if (auto_inline) {\n    tvm::te::AutoInlineInjective(s);\n    if (axis.size() > 0) {\n      detail::Fuse(s[x], axis);\n    }\n    return s;\n  }\n\n  if (axis.size() == 4) {\n    auto n = axis[0];\n    auto c = axis[1];\n    auto fused = detail::Fuse(s[x], {n, c});  // for nhwc layout, fuse n and h\n    s[x].parallel(fused);\n  } else {\n    s[x].parallel(axis[0]);\n  }\n\n  return s;\n}\n\n/*!\n * \\brief Create a default x86 schedule for the given ops.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule default_schedule(const Target& target, const Array<Tensor>& outs) {\n  return MakeDefaultSchedule(target, outs, false);\n}\n\n/*!\n * \\brief Create a default x86 schedule for the given ops, with auto inline\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule default_schedule_auto_inline(const Target& target, const Array<Tensor>& outs) {\n  return MakeDefaultSchedule(target, outs, true);\n}\n\n}  // namespace x86\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_X86_DEFAULT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "include/tvm/topi/x86/injective.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file x86/injective.h\n * \\brief x86 schedule for injective ops\n */\n#ifndef TVM_TOPI_X86_INJECTIVE_H_\n#define TVM_TOPI_X86_INJECTIVE_H_\n\n#include <tvm/target/generic_func.h>\n#include <tvm/te/operation.h>\n#include <tvm/topi/detail/fuse.h>\n#include <tvm/topi/tags.h>\n\nnamespace tvm {\nnamespace topi {\n\nusing namespace tvm::te;\n\nnamespace x86 {\n\n/*!\n * \\brief Updates an existing schedule for the given injective ops.\n *\n * \\param sch The schedule to update.\n * \\param out The tensor representing the injective op.\n *\n * \\return The updated schedule.\n */\ninline Schedule schedule_injective_from_existing(Schedule sch, const Tensor& out) {\n  auto axis = sch[out]->op.as<ComputeOpNode>()->axis;\n  if (axis.size() == 4) {\n    auto n = axis[0];\n    auto c = axis[1];\n    auto fused = detail::Fuse(sch[out], {n, c});  // for nhwc layout, fuse n and h\n    sch[out].parallel(fused);\n  } else {\n    sch[out].parallel(axis[0]);\n  }\n  return sch;\n}\n\n/*!\n * \\brief Create an x86 schedule for the given injective ops.\n *\n * \\param target The target to generate a schedule for.\n * \\param outs The output tensors.\n *\n * \\return A schedule for the given ops.\n */\ninline Schedule schedule_injective(const Target& target, const Array<Tensor>& outs) {\n  Array<Operation> out_ops;\n  for (auto t : outs) {\n    out_ops.push_back(t->op);\n  }\n  auto s = create_schedule(out_ops);\n  tvm::te::AutoInlineInjective(s);\n\n  auto x = outs[0];\n  schedule_injective_from_existing(s, x);\n\n  return s;\n}\n\n}  // namespace x86\n}  // namespace topi\n}  // namespace tvm\n#endif  // TVM_TOPI_X86_INJECTIVE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/API.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * TVM API functions.\n */\npublic final class API {\n  private static ThreadLocal<Map<String, Function>> apiFuncs\n      = new ThreadLocal<Map<String, Function>>() {\n        @Override\n        protected Map<String, Function> initialValue() {\n          return new HashMap<String, Function>();\n        }\n      };\n\n  /**\n   * Get a tvm api function according by name.\n   * @param name function name.\n   * @return a TVM Function.\n   */\n  public static Function get(final String name) {\n    Function func = apiFuncs.get().get(name);\n    if (func == null) {\n      func = Function.getFunction(name);\n      apiFuncs.get().put(name, func);\n    }\n    return func;\n  }\n\n  /**\n   * Cannot be instantiated.\n   */\n  private API() {\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/APIInternal.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\n/**\n * Internal api functions.\n */\npublic final class APIInternal {\n  /**\n   * Get a tvm api function according by name.\n   * @param name function name.\n   * @return a TVM Function.\n   */\n  public static Function get(final String name) {\n    return API.get(name);\n  }\n\n  /**\n   * Cannot be instantiated.\n   */\n  private APIInternal() {\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/ArgTypeCode.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\n// Type code used in API calls\npublic enum ArgTypeCode {\n  INT(0), UINT(1), FLOAT(2), HANDLE(3), NULL(4), TVM_TYPE(5),\n  DLDEVICE(6), ARRAY_HANDLE(7), NODE_HANDLE(8), MODULE_HANDLE(9),\n  FUNC_HANDLE(10), STR(11), BYTES(12), NDARRAY_CONTAINER(13);\n\n  public final int id;\n\n  private ArgTypeCode(int id) {\n    this.id = id;\n  }\n\n  @Override\n  public String toString() {\n    return String.valueOf(id);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/Base.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport org.apache.tvm.NativeLibraryLoader.Action;\n\nimport java.io.File;\nimport java.io.IOException;\n\n/**\n * Initializing methods and types.\n */\nfinal class Base {\n\n  /**\n   * Hold Long reference for JNI.\n   */\n  public static class RefLong {\n    public final long value;\n\n    public RefLong(final long value) {\n      this.value = value;\n    }\n\n    public RefLong() {\n      this(0L);\n    }\n  }\n\n  /**\n   * Hold TVMValue reference for JNI.\n   */\n  public static class RefTVMValue {\n    public final TVMValue value;\n\n    public RefTVMValue(TVMValue value) {\n      this.value = value;\n    }\n\n    public RefTVMValue() {\n      this(null);\n    }\n  }\n\n  public static final LibInfo _LIB = new LibInfo();\n\n  static {\n    boolean loadNativeRuntimeLib = true;\n    try {\n      try {\n        tryLoadLibraryOS(\"tvm4j\");\n      } catch (UnsatisfiedLinkError e) {\n        System.err.println(\"[WARN] TVM native library not found in path. \"\n            + \"Copying native library from the archive. \"\n            + \"Consider installing the library somewhere in the path \"\n            + \"(for Windows: PATH, for Linux: LD_LIBRARY_PATH), \"\n            + \"or specifying by Java cmd option -Djava.library.path=[lib path].\");\n        NativeLibraryLoader.loadLibrary(\"tvm4j\");\n      }\n    } catch (Throwable e) {\n      System.err.println(\"[WARN] Couldn't find native library tvm4j.\");\n      e.printStackTrace();\n      System.err.println(\"Try to load tvm4j (runtime packed version) ...\");\n      try {\n        System.loadLibrary(\"tvm4j_runtime_packed\");\n        // if tvm runtime is packed in libtvm4j, we do not need to dlopen libtvm_runtime.so.\n        loadNativeRuntimeLib = false;\n      } catch (UnsatisfiedLinkError errFull) {\n        System.err.println(\"[ERROR] Couldn't find native library tvm4j_runtime_packed.\");\n        throw new RuntimeException(errFull);\n      }\n    }\n\n    System.err.println(\"libtvm4j loads successfully.\");\n\n    if (loadNativeRuntimeLib) {\n      String tvmLibFilename = System.getProperty(\"libtvm.so.path\");\n      if (tvmLibFilename == null || !new File(tvmLibFilename).isFile()\n          || _LIB.nativeLibInit(tvmLibFilename) != 0) {\n        try {\n          String runtimeLibname;\n          String os = System.getProperty(\"os.name\");\n          // ref: http://lopica.sourceforge.net/os.html\n          if (os.startsWith(\"Linux\")) {\n            runtimeLibname = \"libtvm_runtime.so\";\n          } else if (os.startsWith(\"Mac\")) {\n            runtimeLibname = \"libtvm_runtime.dylib\";\n          } else {\n            // TODO(yizhi) support windows later\n            throw new UnsatisfiedLinkError(os + \" not supported currently\");\n          }\n          NativeLibraryLoader.extractResourceFileToTempDir(runtimeLibname, new Action() {\n            @Override public void invoke(File target) {\n              System.err.println(\"Loading tvm runtime from \" + target.getPath());\n              checkCall(_LIB.nativeLibInit(target.getPath()));\n            }\n          });\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n    } else {\n      _LIB.nativeLibInit(null);\n    }\n\n    Runtime.getRuntime().addShutdownHook(new Thread() {\n      @Override public void run() {\n        _LIB.shutdown();\n      }\n    });\n  }\n\n  /**\n   * Load JNI for different OS.\n   * @param libname library name.\n   * @throws UnsatisfiedLinkError if loading fails.\n   */\n  private static void tryLoadLibraryOS(String libname) throws UnsatisfiedLinkError {\n    try {\n      System.err.println(String.format(\"Try loading %s from native path.\", libname));\n      System.loadLibrary(libname);\n    } catch (UnsatisfiedLinkError e) {\n      String os = System.getProperty(\"os.name\");\n      // ref: http://lopica.sourceforge.net/os.html\n      if (os.startsWith(\"Linux\")) {\n        tryLoadLibraryXPU(libname, \"linux-x86_64\");\n      } else if (os.startsWith(\"Mac\")) {\n        tryLoadLibraryXPU(libname, \"osx-x86_64\");\n      } else {\n        // TODO(yizhi) support windows later\n        throw new UnsatisfiedLinkError(\"Windows not supported currently\");\n      }\n    }\n  }\n\n  /**\n   * Load native library for different architectures.\n   * @param libname library name.\n   * @param arch architecture.\n   * @throws UnsatisfiedLinkError if loading fails\n   */\n  private static void tryLoadLibraryXPU(String libname, String arch) throws UnsatisfiedLinkError {\n    System.err.println(String.format(\"Try loading %s-%s from native path.\", libname, arch));\n    System.loadLibrary(String.format(\"%s-%s\", libname, arch));\n  }\n\n  // helper function definitions\n  /**\n   * Check the return value of C API call.\n   * <p>\n   * This function will raise exception when error occurs.\n   * Wrap every API call with this function\n   * </p>\n   * @param ret return value from API calls\n   */\n  public static void checkCall(int ret) throws TVMError {\n    if (ret != 0) {\n      throw new TVMError(_LIB.tvmGetLastError());\n    }\n  }\n\n  /**\n   * TVM Runtime error.\n   */\n  static class TVMError extends RuntimeException {\n    public TVMError(String err) {\n      super(err);\n    }\n  }\n\n  /**\n   * Cannot be instantiated.\n   */\n  private Base() {\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/Device.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.apache.tvm.rpc.RPC;\n\npublic class Device {\n  /**\n   * Provides the same information as the C++ enums DLDeviceType and\n   * TVMDeviceExtType.\n   */\n  static final int kDLCPU = 1, kDLCUDA = 2, kDLCUDAHost = 3, kDLOpenCL = 4, kDLVulkan = 7,\n                   kDLMetal = 8, kDLVPI = 9, kDLROCM = 10, kDLROCMHost = 11, kDLExtDev = 12,\n                   kDLCUDAManaged = 13, kDLOneAPI = 14, kDLWebGPU = 15, kDLHexagon = 16,\n                   kDLAOCL = 32, kDLSDAccel = 33, kOpenGL = 34, kDLMicroDev = 35;\n\n  private static final Map<Integer, String> MASK2STR = new HashMap<Integer, String>();\n  private static final Map<String, Integer> STR2MASK = new HashMap<String, Integer>();\n\n  static {\n    MASK2STR.put(kDLCPU, \"cpu\");\n    MASK2STR.put(kDLCUDA, \"cuda\");\n    MASK2STR.put(kDLOpenCL, \"opencl\");\n    MASK2STR.put(kDLVulkan, \"vulkan\");\n    MASK2STR.put(kDLMetal, \"metal\");\n    MASK2STR.put(kDLVPI, \"vpi\");\n    MASK2STR.put(kDLHexagon, \"hexagon\");\n\n    STR2MASK.put(\"cpu\", kDLCPU);\n    STR2MASK.put(\"cuda\", kDLCUDA);\n    STR2MASK.put(\"cl\", kDLOpenCL);\n    STR2MASK.put(\"opencl\", kDLOpenCL);\n    STR2MASK.put(\"vulkan\", kDLVulkan);\n    STR2MASK.put(\"metal\", kDLMetal);\n    STR2MASK.put(\"vpi\", kDLVPI);\n    STR2MASK.put(\"hexagon\", kDLHexagon);\n  }\n\n  /**\n   * Construct a CPU device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device cpu(int devId) {\n    return new Device(kDLCPU, devId);\n  }\n\n  public static Device cpu() {\n    return cpu(0);\n  }\n\n  /**\n   * Construct a CUDA GPU device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device cuda(int devId) {\n    return new Device(kDLCUDA, devId);\n  }\n\n  public static Device cuda() {\n    return cuda(0);\n  }\n\n  /**\n   * Construct a OpenCL device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device opencl(int devId) {\n    return new Device(kDLOpenCL, devId);\n  }\n\n  public static Device opencl() {\n    return opencl(0);\n  }\n\n  /**\n   * Construct a Vulkan device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device vulkan(int devId) {\n    return new Device(kDLVulkan, devId);\n  }\n\n  public static Device vulkan() {\n    return vulkan(0);\n  }\n\n  /**\n   * Construct a metal device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device metal(int devId) {\n    return new Device(kDLMetal, devId);\n  }\n\n  public static Device metal() {\n    return metal(0);\n  }\n\n  /**\n   * Construct a VPI simulated device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device vpi(int devId) {\n    return new Device(kDLVPI, devId);\n  }\n\n  public static Device vpi() {\n    return vpi(0);\n  }\n\n  /**\n   * Construct a Hexagon device.\n   * @param devId The device id\n   * @return The created device\n   */\n  public static Device hexagon(int devId) {\n    return new Device(kDLHexagon, devId);\n  }\n\n  public static Device hexagon() {\n    return hexagon(0);\n  }\n\n  public final int deviceType;\n  public final int deviceId;\n\n  public Device(int deviceType, int deviceId) {\n    this.deviceType = deviceType;\n    this.deviceId = deviceId;\n  }\n\n  public Device(String deviceType, int deviceId) {\n    this(STR2MASK.get(deviceType), deviceId);\n  }\n\n  /**\n   * Whether this device exists.\n   * @return true if exists.\n   */\n  public boolean exist() {\n    TVMValue ret =\n        APIInternal.get(\"_GetDeviceAttr\").pushArg(deviceType).pushArg(deviceId).pushArg(0).invoke();\n    return ((TVMValueLong) ret).value != 0;\n  }\n\n  /**\n   * Maximum number of threads on each block.\n   * @return the maximum thread number.\n   */\n  public long maxThreadsPerBlock() {\n    TVMValue ret =\n        APIInternal.get(\"_GetDeviceAttr\").pushArg(deviceType).pushArg(deviceId).pushArg(1).invoke();\n    return ((TVMValueLong) ret).value;\n  }\n\n  /**\n   * Number of threads that executes in concurrent.\n   * @return the thread number.\n   */\n  public long warpSize() {\n    TVMValue ret =\n        APIInternal.get(\"_GetDeviceAttr\").pushArg(deviceType).pushArg(deviceId).pushArg(2).invoke();\n    return ((TVMValueLong) ret).value;\n  }\n\n  /**\n   * Synchronize until jobs finished at the device.\n   */\n  public void sync() {\n    Base.checkCall(Base._LIB.tvmSynchronize(deviceType, deviceId));\n  }\n\n  @Override\n  public int hashCode() {\n    return (deviceType << 16) | deviceId;\n  }\n\n  @Override\n  public boolean equals(Object other) {\n    if (other != null && other instanceof Device) {\n      Device obj = (Device) other;\n      return deviceId == obj.deviceId && deviceType == obj.deviceType;\n    }\n    return false;\n  }\n\n  @Override\n  public String toString() {\n    if (deviceType >= RPC.RPC_SESS_MASK) {\n      int tblId = deviceType / RPC.RPC_SESS_MASK - 1;\n      int devType = deviceType % RPC.RPC_SESS_MASK;\n      return String.format(\"remote[%d]:%s(%d)\", tblId, MASK2STR.get(devType), deviceId);\n    }\n    return String.format(\"%s(%d)\", MASK2STR.get(deviceType), deviceId);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/Function.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * TVM Packed Function.\n */\npublic class Function extends TVMValue {\n  final long handle;\n  public final boolean isResident;\n  private boolean isReleased = false;\n\n  /**\n   * Get registered function.\n   * @param name full function name.\n   * @return TVM function.\n   */\n  public static Function getFunction(final String name) {\n    for (String fullName : listGlobalFuncNames()) {\n      if (fullName.equals(name)) {\n        return getGlobalFunc(fullName, true, false);\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Get list of global functions registered.\n   * @return List of global functions names.\n   */\n  private static List<String> listGlobalFuncNames() {\n    List<String> names = new ArrayList<String>();\n    Base.checkCall(Base._LIB.tvmFuncListGlobalNames(names));\n    return Collections.unmodifiableList(names);\n  }\n\n  /**\n   * Get a global function by name.\n   * @param name The name of the function.\n   * @param isResident Whether it is a global 'resident' function.\n   * @param allowMissing Whether allow missing function or raise an error.\n   * @return The function to be returned, None if function is missing.\n   */\n  private static Function getGlobalFunc(String name, boolean isResident, boolean allowMissing) {\n    Base.RefLong handle = new Base.RefLong();\n    Base.checkCall(Base._LIB.tvmFuncGetGlobal(name, handle));\n    if (handle.value != 0) {\n      return new Function(handle.value, isResident);\n    } else {\n      if (allowMissing) {\n        return null;\n      } else {\n        throw new IllegalArgumentException(\"Cannot find global function \" + name);\n      }\n    }\n  }\n\n  /**\n   * Initialize the function with handle.\n   * @param handle the handle to the underlying function.\n   * @param isResident Whether this is a resident function in jvm\n   */\n  Function(long handle, boolean isResident) {\n    super(ArgTypeCode.FUNC_HANDLE);\n    this.handle = handle;\n    this.isResident = isResident;\n  }\n\n  Function(long handle) {\n    this(handle, false);\n  }\n\n  @Override protected void finalize() throws Throwable {\n    release();\n    super.finalize();\n  }\n\n  /**\n   * Easy for user to get the instance from returned TVMValue.\n   * @return this\n   */\n  @Override public Function asFunction() {\n    return this;\n  }\n\n  @Override long asHandle() {\n    return handle;\n  }\n\n  /**\n   * Release the Function.\n   * <p>\n   * We highly recommend you to do this manually since the GC strategy is lazy.\n   * </p>\n   */\n  @Override public void release() {\n    if (!isReleased) {\n      if (!isResident) {\n        Base.checkCall(Base._LIB.tvmFuncFree(handle));\n        isReleased = true;\n      }\n    }\n  }\n\n  /**\n   * Invoke the function.\n   * @return the result.\n   */\n  public TVMValue invoke() {\n    Base.RefTVMValue ret = new Base.RefTVMValue();\n    Base.checkCall(Base._LIB.tvmFuncCall(handle, ret));\n    return ret.value;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg int argument.\n   * @return this\n   */\n  public Function pushArg(int arg) {\n    Base._LIB.tvmFuncPushArgLong(arg);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg long argument.\n   * @return this\n   */\n  public Function pushArg(long arg) {\n    Base._LIB.tvmFuncPushArgLong(arg);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg float argument.\n   * @return this\n   */\n  public Function pushArg(float arg) {\n    Base._LIB.tvmFuncPushArgDouble(arg);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg double argument.\n   * @return this\n   */\n  public Function pushArg(double arg) {\n    Base._LIB.tvmFuncPushArgDouble(arg);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg String argument.\n   * @return this\n   */\n  public Function pushArg(String arg) {\n    Base._LIB.tvmFuncPushArgString(arg);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg NDArray.\n   * @return this\n   */\n  public Function pushArg(NDArrayBase arg) {\n    int id = arg.isView ? ArgTypeCode.ARRAY_HANDLE.id : ArgTypeCode.NDARRAY_CONTAINER.id;\n    Base._LIB.tvmFuncPushArgHandle(arg.handle, id);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg Module.\n   * @return this\n   */\n  public Function pushArg(Module arg) {\n    Base._LIB.tvmFuncPushArgHandle(arg.handle, ArgTypeCode.MODULE_HANDLE.id);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg Function.\n   * @return this\n   */\n  public Function pushArg(Function arg) {\n    Base._LIB.tvmFuncPushArgHandle(arg.handle, ArgTypeCode.FUNC_HANDLE.id);\n    return this;\n  }\n\n  /**\n   * Push argument to the function.\n   * @param arg bytes.\n   * @return this\n   */\n  public Function pushArg(byte[] arg) {\n    Base._LIB.tvmFuncPushArgBytes(arg);\n    return this;\n  }\n\n  /**\n   * Invoke function with arguments.\n   * @param args Can be Integer, Long, Float, Double, String, NDArray.\n   * @return the result.\n   */\n  public TVMValue call(Object... args) {\n    for (Object arg : args) {\n      pushArgToStack(arg);\n    }\n    return invoke();\n  }\n\n  private static void pushArgToStack(Object arg) {\n    if (arg instanceof Integer) {\n      Base._LIB.tvmFuncPushArgLong((Integer) arg);\n    } else if (arg instanceof Long) {\n      Base._LIB.tvmFuncPushArgLong((Long) arg);\n    } else if (arg instanceof Float) {\n      Base._LIB.tvmFuncPushArgDouble((Float) arg);\n    } else if (arg instanceof Double) {\n      Base._LIB.tvmFuncPushArgDouble((Double) arg);\n    } else if (arg instanceof String) {\n      Base._LIB.tvmFuncPushArgString((String) arg);\n    } else if (arg instanceof byte[]) {\n      Base._LIB.tvmFuncPushArgBytes((byte[]) arg);\n    } else if (arg instanceof NDArrayBase) {\n      NDArrayBase nd = (NDArrayBase) arg;\n      int id = nd.isView ? ArgTypeCode.ARRAY_HANDLE.id : ArgTypeCode.NDARRAY_CONTAINER.id;\n      Base._LIB.tvmFuncPushArgHandle(nd.handle, id);\n    } else if (arg instanceof Module) {\n      Base._LIB.tvmFuncPushArgHandle(((Module) arg).handle, ArgTypeCode.MODULE_HANDLE.id);\n    } else if (arg instanceof Function) {\n      Base._LIB.tvmFuncPushArgHandle(((Function) arg).handle, ArgTypeCode.FUNC_HANDLE.id);\n    } else if (arg instanceof TVMValue) {\n      TVMValue tvmArg = (TVMValue) arg;\n      switch (tvmArg.typeCode) {\n        case UINT:\n        case INT:\n          Base._LIB.tvmFuncPushArgLong(tvmArg.asLong());\n          break;\n        case FLOAT:\n          Base._LIB.tvmFuncPushArgDouble(tvmArg.asDouble());\n          break;\n        case STR:\n          Base._LIB.tvmFuncPushArgString(tvmArg.asString());\n          break;\n        case BYTES:\n          Base._LIB.tvmFuncPushArgBytes(tvmArg.asBytes());\n          break;\n        case HANDLE:\n        case ARRAY_HANDLE:\n        case MODULE_HANDLE:\n        case FUNC_HANDLE:\n          Base._LIB.tvmFuncPushArgHandle(tvmArg.asHandle(), tvmArg.typeCode.id);\n          break;\n        default:\n          throw new IllegalArgumentException(\"Invalid argument: \" + arg);\n      }\n    } else {\n      throw new IllegalArgumentException(\"Invalid argument: \" + arg);\n    }\n  }\n\n  public static interface Callback {\n    public Object invoke(TVMValue... args);\n  }\n\n  /**\n   * Register user-defined global function.\n   * @param name The function name.\n   * @param function The function to be registered.\n   * @param override Whether override existing entry.\n   */\n  public static void register(String name, Callback function, boolean override) {\n    Base.RefLong createdFuncHandleRef = new Base.RefLong();\n    Base.checkCall(Base._LIB.tvmFuncCreateFromCFunc(function, createdFuncHandleRef));\n    int ioverride = override ? 1 : 0;\n    Base.checkCall(Base._LIB.tvmFuncRegisterGlobal(name, createdFuncHandleRef.value, ioverride));\n  }\n\n  /**\n   * Register user-defined global function, do not override existing entry.\n   * @param name The function name.\n   * @param function The function to be registered.\n   */\n  public static void register(String name, Callback function) {\n    register(name, function, false);\n  }\n\n  /**\n   * Convert a Java function to TVM function.\n   * @param function Java function.\n   * @return TVM function.\n   */\n  public static Function convertFunc(Callback function) {\n    Base.RefLong createdFuncHandleRef = new Base.RefLong();\n    Base.checkCall(Base._LIB.tvmFuncCreateFromCFunc(function, createdFuncHandleRef));\n    return new Function(createdFuncHandleRef.value);\n  }\n\n  private static Object invokeRegisteredCbFunc(Callback cb, TVMValue[] args) {\n    if (cb == null) {\n      System.err.println(\"[ERROR] Failed to get registered function\");\n      return null;\n    }\n    return cb.invoke(args);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/LibInfo.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.util.List;\n\nclass LibInfo {\n  native int nativeLibInit(String tvmLibFile);\n\n  native int shutdown();\n\n  native String tvmGetLastError();\n\n  // Function\n  native void tvmFuncPushArgLong(long arg);\n\n  native void tvmFuncPushArgDouble(double arg);\n\n  native void tvmFuncPushArgString(String arg);\n\n  native void tvmFuncPushArgBytes(byte[] arg);\n\n  native void tvmFuncPushArgHandle(long arg, int argType);\n\n  native int tvmFuncListGlobalNames(List<String> funcNames);\n\n  native int tvmFuncFree(long handle);\n\n  native int tvmFuncGetGlobal(String name, Base.RefLong handle);\n\n  native int tvmFuncCall(long handle, Base.RefTVMValue retVal);\n\n  native int tvmFuncCreateFromCFunc(Function.Callback function, Base.RefLong handle);\n\n  native int tvmFuncRegisterGlobal(String name, long handle, int override);\n\n  // Module\n  native int tvmModFree(long handle);\n\n  native int tvmModGetFunction(long handle, String name,\n                                      int queryImports, Base.RefLong retHandle);\n\n  native int tvmModImport(long mod, long dep);\n\n  // NDArray\n  native int tvmArrayFree(long handle);\n\n  native int tvmArrayAlloc(long[] shape, int dtypeCode, int dtypeBits, int dtypeLanes,\n      int deviceType, int deviceId, Base.RefLong refHandle);\n\n  native int tvmArrayGetShape(long handle, List<Long> shape);\n\n  native int tvmArrayCopyFromTo(long from, long to);\n\n  native int tvmArrayCopyFromJArray(byte[] fromRaw, long from, long to);\n\n  native int tvmArrayCopyToJArray(long from, byte[] to);\n\n  // Device\n  native int tvmSynchronize(int deviceType, int deviceId);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/Module.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Container of compiled functions of TVM.\n */\npublic class Module extends TVMValue {\n  public final long handle;\n  private boolean isReleased = false;\n\n  private static ThreadLocal<Map<String, Function>> apiFuncs\n      = new ThreadLocal<Map<String, Function>>() {\n        @Override\n        protected Map<String, Function> initialValue() {\n          return new HashMap<String, Function>();\n        }\n      };\n\n  private static Function getApi(String name) {\n    Function func = apiFuncs.get().get(name);\n    if (func == null) {\n      func = Function.getFunction(\"runtime.\" + name);\n      apiFuncs.get().put(name, func);\n    }\n    return func;\n  }\n\n  Module(long handle) {\n    super(ArgTypeCode.MODULE_HANDLE);\n    this.handle = handle;\n  }\n\n  private Function entry = null;\n  private final String entryName = \"__tvm_main__\";\n\n  @Override protected void finalize() throws Throwable {\n    release();\n    super.finalize();\n  }\n\n  /**\n   * Easy for user to get the instance from returned TVMValue.\n   * @return this\n   */\n  @Override public Module asModule() {\n    return this;\n  }\n\n  @Override long asHandle() {\n    return handle;\n  }\n\n  /**\n   * Release the Module.\n   * <p>\n   * We highly recommend you to do this manually since the GC strategy is lazy.\n   * </p>\n   */\n  @Override public void release() {\n    if (!isReleased) {\n      Base.checkCall(Base._LIB.tvmModFree(handle));\n      isReleased = true;\n    }\n  }\n\n  /**\n   * Get the entry function.\n   * @return The entry function if exist\n   */\n  public Function entryFunc() {\n    if (entry == null) {\n      entry = getFunction(entryName);\n    }\n    return entry;\n  }\n\n  /**\n   * Get function from the module.\n   * @param name The name of the function.\n   * @param queryImports Whether also query modules imported by this module.\n   * @return The result function.\n   */\n  public Function getFunction(String name, boolean queryImports) {\n    Base.RefLong retHandle = new Base.RefLong();\n    Base.checkCall(Base._LIB.tvmModGetFunction(\n        handle, name, queryImports ? 1 : 0, retHandle));\n    if (retHandle.value == 0) {\n      throw new IllegalArgumentException(\"Module has no function \" + name);\n    }\n    return new Function(retHandle.value, false);\n  }\n\n  public Function getFunction(String name) {\n    return getFunction(name, false);\n  }\n\n  /**\n   * Add module to the import list of current one.\n   * @param module The other module.\n   */\n  public void importModule(Module module) {\n    Base.checkCall(Base._LIB.tvmModImport(handle, module.handle));\n  }\n\n  /**\n   * Get type key of the module.\n   * @return type key of the module.\n   */\n  public String typeKey() {\n    return getApi(\"ModuleGetTypeKey\").pushArg(this).invoke().asString();\n  }\n\n  /**\n   * Load module from file.\n   * @param path The path to the module file.\n   * @param fmt The format of the file,\n   *            if not specified it will be inferred from suffix of the file.\n   * @return The loaded module\n   */\n  public static Module load(String path, String fmt) {\n    TVMValue ret = getApi(\"ModuleLoadFromFile\").pushArg(path).pushArg(fmt).invoke();\n    assert ret.typeCode == ArgTypeCode.MODULE_HANDLE;\n    return ret.asModule();\n  }\n\n  public static Module load(String path) {\n    return load(path, \"\");\n  }\n\n  /**\n   * Whether module runtime is enabled for target,\n   * e.g., The following code checks if cuda is enabled.\n   * Module.enabled(\"cuda\")\n   * @param target The target device type.\n   * @return Whether runtime is enabled.\n   */\n  public static boolean enabled(String target) {\n    TVMValue ret = getApi(\"RuntimeEnabled\").pushArg(target).invoke();\n    return ret.asLong() != 0;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/NDArray.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Lightweight NDArray class of TVM runtime.\n */\npublic class NDArray extends NDArrayBase {\n  private final TVMType dtype;\n  private final Device device;\n\n  NDArray(long handle, boolean isView, TVMType dtype, Device dev) {\n    super(handle, isView);\n    this.dtype = dtype;\n    this.device = dev;\n  }\n\n  @Override\n  protected void finalize() throws Throwable {\n    super.finalize();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by float64\n   * @param sourceArray the source data\n   */\n  public void copyFrom(double[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.FLOAT || dtype.bits != 64) {\n      throw new IllegalArgumentException(\"Cannot set double[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putDouble(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by float32\n   * @param sourceArray the source data\n   */\n  public void copyFrom(float[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.FLOAT || dtype.bits != 32) {\n      throw new IllegalArgumentException(\"Cannot set float[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putFloat(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by int64\n   * @param sourceArray the source data\n   */\n  public void copyFrom(long[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 64) {\n      throw new IllegalArgumentException(\"Cannot set long[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putLong(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by float32\n   * @param sourceArray the source data\n   */\n  public void copyFrom(int[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 32) {\n      throw new IllegalArgumentException(\"Cannot set int[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putInt(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by int16\n   * @param sourceArray the source data\n   */\n  public void copyFrom(short[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 16) {\n      throw new IllegalArgumentException(\"Cannot set short[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putShort(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by int8\n   * @param sourceArray the source data\n   */\n  public void copyFrom(byte[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 8) {\n      throw new IllegalArgumentException(\"Cannot set byte[] for \" + dtype.toString() + \" array\");\n    }\n    copyFromRaw(sourceArray);\n  }\n\n  /**\n   * Copy from a native array.\n   * The NDArray type must by uint16\n   * @param sourceArray the source data\n   */\n  public void copyFrom(char[] sourceArray) {\n    checkCopySize(sourceArray.length);\n    if (dtype.typeCode != TVMType.UINT || dtype.bits != 16) {\n      throw new IllegalArgumentException(\"Cannot set char[] for \" + dtype.toString() + \" array\");\n    }\n    byte[] nativeArr = new byte[sourceArray.length * dtype.numOfBytes];\n    for (int i = 0; i < sourceArray.length; ++i) {\n      wrapBytes(nativeArr, i * dtype.numOfBytes, dtype.numOfBytes).putChar(sourceArray[i]);\n    }\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(nativeArr, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  private void checkCopySize(int sourceLength) {\n    long arrSize = size();\n    if (arrSize != sourceLength) {\n      throw new IllegalArgumentException(\n          String.format(\"Array shape size not match: %d v.s. %d\", sourceLength, size()));\n    }\n  }\n\n  /**\n   * Copy from a raw byte array.\n   * @param sourceArray the source data\n   */\n  public void copyFromRaw(byte[] sourceArray) {\n    NDArray tmpArr = empty(shape(), this.dtype);\n    Base.checkCall(Base._LIB.tvmArrayCopyFromJArray(sourceArray, tmpArr.handle, handle));\n    tmpArr.release();\n  }\n\n  /**\n   * Get shape of current NDArray.\n   * @return an array representing shape of current ndarray\n   */\n  public long[] shape() {\n    List<Long> data = new ArrayList<Long>();\n    Base.checkCall(Base._LIB.tvmArrayGetShape(handle, data));\n    long[] shapeArr = new long[data.size()];\n    for (int i = 0; i < shapeArr.length; ++i) {\n      shapeArr[i] = data.get(i);\n    }\n    return shapeArr;\n  }\n\n  /**\n   * Get total size of current NDArray.\n   * @return size of current NDArray.\n   */\n  public long size() {\n    long product = 1L;\n    long[] shapeArr = shape();\n    for (int i = 0; i < shapeArr.length; ++i) {\n      product *= shapeArr[i];\n    }\n    return product;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be float64\n   * @return A copy of array content.\n   */\n  public double[] asDoubleArray() {\n    if (dtype.typeCode != TVMType.FLOAT || dtype.bits != 64) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to double[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    double[] array = new double[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getDouble();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be float32\n   * @return A copy of array content.\n   */\n  public float[] asFloatArray() {\n    if (dtype.typeCode != TVMType.FLOAT || dtype.bits != 32) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to float[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    float[] array = new float[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getFloat();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be int64\n   * @return A copy of array content.\n   */\n  public long[] asLongArray() {\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 64) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to long[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    long[] array = new long[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getLong();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be int32\n   * @return A copy of array content.\n   */\n  public int[] asIntArray() {\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 32) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to int[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    int[] array = new int[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getInt();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be int16\n   * @return A copy of array content.\n   */\n  public short[] asShortArray() {\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 16) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to short[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    short[] array = new short[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getShort();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be uint16\n   * @return A copy of array content.\n   */\n  public char[] asCharArray() {\n    if (dtype.typeCode != TVMType.UINT || dtype.bits != 16) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to char[] for \" + dtype.toString() + \" array\");\n    }\n    byte[][] units = groupInternalBytes();\n    char[] array = new char[units.length];\n    for (int i = 0; i < units.length; ++i) {\n      array[i] = wrapBytes(units[i]).getChar();\n    }\n    return array;\n  }\n\n  /**\n   * Return a copied flat java array of current array (row-major).\n   * The NDArray dtype must be int8\n   * @return A copy of array content.\n   */\n  public byte[] asByteArray() {\n    if (dtype.typeCode != TVMType.INT || dtype.bits != 8) {\n      throw new IllegalArgumentException(\n          \"Cannot set convert to byte[] for \" + dtype.toString() + \" array\");\n    }\n    return internal();\n  }\n\n  /**\n   * Return a copied internal byte array of current array (row-major).\n   * @return A copy of array content.\n   */\n  public byte[] internal() {\n    NDArray tmp = NDArray.empty(shape(), dtype);\n    copyTo(tmp);\n\n    int arrLength = dtype.numOfBytes * (int) size();\n    byte[] arr = new byte[arrLength];\n    Base.checkCall(Base._LIB.tvmArrayCopyToJArray(tmp.handle, arr));\n    return arr;\n  }\n\n  private byte[][] groupInternalBytes() {\n    byte[] raw = internal();\n    int unitSize = dtype.numOfBytes;\n    if (raw.length <= 0 || raw.length % unitSize != 0) {\n      throw new IllegalArgumentException(String.format(\n          \"%s size %d cannot divide byte array size %d\", dtype.toString(), unitSize, raw.length));\n    }\n\n    int numOfUnits = raw.length / unitSize;\n    byte[][] units = new byte[numOfUnits][unitSize];\n    for (int i = 0; i < numOfUnits; ++i) {\n      System.arraycopy(raw, i * unitSize, units[i], 0, unitSize);\n    }\n    return units;\n  }\n\n  /**\n   * Get the device of current array.\n   * @return the device.\n   */\n  public Device device() {\n    return device;\n  }\n\n  /**\n   * Create an empty array given shape, type and device.\n   * @param shape The shape of the array.\n   * @param dtype The data type of the array.\n   * @param dev The device of the array.\n   * @return The array tvm supported.\n   */\n  public static NDArray empty(long[] shape, TVMType dtype, Device dev) {\n    Base.RefLong refHandle = new Base.RefLong();\n    Base.checkCall(Base._LIB.tvmArrayAlloc(\n        shape, dtype.typeCode, dtype.bits, dtype.lanes, dev.deviceType, dev.deviceId, refHandle));\n    return new NDArray(refHandle.value, false, dtype, dev);\n  }\n\n  /**\n   * Create an empty array on cpu given shape and type.\n   * @param shape The shape of the array.\n   * @param dtype The data type of the array.\n   * @return The array tvm supported.\n   */\n  public static NDArray empty(long[] shape, TVMType dtype) {\n    return empty(shape, dtype, Device.cpu(0));\n  }\n\n  /**\n   * Create an empty float32 array on cpu given shape.\n   * @param shape The shape of the array.\n   * @return The array tvm supported.\n   */\n  public static NDArray empty(long[] shape) {\n    return empty(shape, new TVMType(\"float32\", 1), Device.cpu(0));\n  }\n\n  /**\n   * Create an empty float32 array given shape and device.\n   * @param shape The shape of the array.\n   * @param dev The device of the array.\n   * @return The array tvm supported.\n   */\n  public static NDArray empty(long[] shape, Device dev) {\n    return empty(shape, new TVMType(\"float32\", 1), dev);\n  }\n\n  private static ByteBuffer wrapBytes(byte[] bytes) {\n    ByteBuffer bb = ByteBuffer.wrap(bytes);\n    bb.order(ByteOrder.LITTLE_ENDIAN);\n    return bb;\n  }\n\n  private static ByteBuffer wrapBytes(byte[] bytes, int offset, int length) {\n    ByteBuffer bb = ByteBuffer.wrap(bytes, offset, length);\n    bb.order(ByteOrder.LITTLE_ENDIAN);\n    return bb;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/NDArrayBase.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\n/**\n * Base class of NDArray. To handle callback array.\n * Only deep-copy supported.\n */\npublic class NDArrayBase extends TVMValue {\n  protected final long handle;\n  protected final boolean isView;\n  private boolean isReleased = false;\n\n  NDArrayBase(long handle, boolean isView) {\n    super(ArgTypeCode.ARRAY_HANDLE);\n    this.handle = handle;\n    this.isView = isView;\n  }\n\n  NDArrayBase(long handle) {\n    this(handle, true);\n  }\n\n  @Override public NDArrayBase asNDArray() {\n    return this;\n  }\n\n  @Override long asHandle() {\n    return handle;\n  }\n\n  /**\n   * Copy array to target.\n   * @param target The target array to be copied, must have same shape as this array.\n   * @return target\n   */\n  public NDArrayBase copyTo(NDArrayBase target) {\n    Base.checkCall(Base._LIB.tvmArrayCopyFromTo(handle, target.handle));\n    return target;\n  }\n\n  /**\n   * Release the NDArray memory.\n   * <p>\n   * We highly recommend you to do this manually since the GC strategy is lazy.\n   * </p>\n   */\n  public void release() {\n    if (!isReleased) {\n      if (!isView) {\n        Base.checkCall(Base._LIB.tvmArrayFree(handle));\n        isReleased = true;\n      }\n    }\n  }\n\n  @Override protected void finalize() throws Throwable {\n    release();\n    super.finalize();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/NativeLibraryLoader.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\nclass NativeLibraryLoader {\n  private static final String libPathInJar = \"/lib/native/\";\n  private static File tempDir;\n\n  static {\n    try {\n      tempDir = File.createTempFile(\"tvm4j\", \"\");\n      if (!tempDir.delete() || !tempDir.mkdir()) {\n        throw new IOException(\"Couldn't create directory \" + tempDir.getAbsolutePath());\n      }\n\n      /*\n       * Different cleanup strategies for Windows and Linux.\n       * TODO: shutdown hook won't work on Windows\n       */\n      if (!\"Windows\".equals(getUnifiedOSName())) {\n        Runtime.getRuntime().addShutdownHook(new Thread() {\n          @Override public void run() {\n            for (File f : tempDir.listFiles()) {\n              System.err.println(\"Deleting \" + f.getAbsolutePath());\n              if (!f.delete()) {\n                System.err.println(\"[WARN] Couldn't delete temporary file \" + f.getAbsolutePath());\n              }\n            }\n            System.err.println(\"Deleting \" + tempDir.getAbsolutePath());\n            if (!tempDir.delete()) {\n              System.err.println(\n                  \"[WARN] Couldn't delete temporary directory \" + tempDir.getAbsolutePath());\n            }\n          }\n        });\n      } else {\n        throw new RuntimeException(\"Windows not supported yet.\");\n      }\n    } catch (IOException ex) {\n      System.err.println(\"Couldn't create temporary directory: \" + ex.getMessage());\n      throw new RuntimeException(ex);\n    }\n  }\n\n  /**\n   * Find the library as a resource in jar, copy it to a tempfile\n   * and load it using System.load(). The name of the library has to be the\n   * base name, it is mapped to the corresponding system name using\n   * System.mapLibraryName(). e.g., the library \"foo\" is called \"libfoo.so\"\n   * under Linux and \"foo.dll\" under Windows, but you just have to pass \"foo\" to\n   * the loadLibrary().\n   *\n   * @param libname basename of the library\n   * @throws UnsatisfiedLinkError if library not found.\n   * @throws IOException if file not found.\n   */\n  public static void loadLibrary(String libname) throws UnsatisfiedLinkError, IOException {\n    String mappedLibname = System.mapLibraryName(libname);\n    String loadLibname = mappedLibname;\n    if (mappedLibname.endsWith(\"dylib\")) {\n      System.err.println(\"Replaced .dylib with .jnilib\");\n      loadLibname = mappedLibname.replace(\".dylib\", \".jnilib\");\n    }\n    System.err.println(\"Attempting to load \" + loadLibname);\n    extractResourceFileToTempDir(loadLibname, new Action() {\n      @Override public void invoke(File target) {\n        System.err.println(\"Loading library from \" + target.getPath());\n        System.load(target.getPath());\n      }\n    });\n  }\n\n  /**\n   * Translate all those Windows to \"Windows\". (\"Windows XP\", \"Windows Vista\", \"Windows 7\", etc.)\n   */\n  private static String unifyOSName(String osname) {\n    if (osname.startsWith(\"Windows\")) {\n      return \"Windows\";\n    }\n    return osname;\n  }\n\n  private static String getUnifiedOSName() {\n    return unifyOSName(System.getProperty(\"os.name\"));\n  }\n\n  private static File createTempFile(String name) throws IOException {\n    return new File(tempDir + File.separator + name);\n  }\n\n  static interface Action {\n    public void invoke(File file);\n  }\n\n  /**\n   * Copies the resource file to a temp file and do an action.\n   * @param filename source file name (in lib/native).\n   * @param action callback function to deal with the copied file.\n   */\n  public static void extractResourceFileToTempDir(String filename, Action action)\n      throws IOException {\n    final String libFileInJar = libPathInJar + filename;\n    InputStream is = NativeLibraryLoader.class.getResourceAsStream(libFileInJar);\n    if (is == null) {\n      throw new UnsatisfiedLinkError(\"Couldn't find the resource \" + filename);\n    }\n    System.err.println(String.format(\"Loading %s from %s\", filename, libPathInJar));\n    try {\n      File tempfile = createTempFile(filename);\n      OutputStream os = new FileOutputStream(tempfile);\n      final long savedTime = System.currentTimeMillis();\n      byte[] buf = new byte[8192];\n      int len = is.read(buf);\n      while (len > 0) {\n        os.write(buf, 0, len);\n        len = is.read(buf);\n      }\n      os.flush();\n      final FileInputStream lock = new FileInputStream(tempfile);\n      os.close();\n      double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;\n      System.err.println(String.format(\"Copying took %.2f seconds.\", seconds));\n      action.invoke(tempfile);\n      lock.close();\n    } catch (IOException io) {\n      System.err.println(\"[ERROR] Could not create the temp file: \" + io.toString());\n      throw io;\n    } catch (UnsatisfiedLinkError ule) {\n      System.err.println(\"Couldn't load copied link file: \" + ule.toString());\n      throw ule;\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMType.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMType {\n  public static final int INT = 0;\n  public static final int UINT = 1;\n  public static final int FLOAT = 2;\n  public static final int HANDLE = 4;\n\n  public final int typeCode;\n  public final int bits;\n  public final int numOfBytes;\n  public final int lanes;\n\n  /**\n   * TVMType constructor.\n   * @param typeStr type name, e.g., \"float32\", \"float64\", \"uint8\", etc.\n   * @param lanes NDArray lanes.\n   */\n  public TVMType(String typeStr, int lanes) {\n    this.lanes = lanes;\n    int bitsTemp = 0;\n    if (typeStr.startsWith(\"int\")) {\n      typeCode = INT;\n      bitsTemp = Integer.parseInt(typeStr.substring(3));\n    } else if (typeStr.startsWith(\"uint\")) {\n      typeCode = UINT;\n      bitsTemp = Integer.parseInt(typeStr.substring(4));\n    } else if (typeStr.startsWith(\"float\")) {\n      typeCode = FLOAT;\n      bitsTemp = Integer.parseInt(typeStr.substring(5));\n    } else if (typeStr.startsWith(\"handle\")) {\n      typeCode = HANDLE;\n      bitsTemp = 64;\n    } else {\n      throw new IllegalArgumentException(\"Do not know how to handle type \" + typeStr);\n    }\n    bits = (bitsTemp == 0) ? 32 : bitsTemp;\n    if ((bits & (bits - 1)) != 0 || bits < 8) {\n      throw new IllegalArgumentException(\"Do not know how to handle type \" + typeStr);\n    }\n    numOfBytes = bits / 8;\n  }\n\n  public TVMType(String typeStr) {\n    this(typeStr, 1);\n  }\n\n  @Override public int hashCode() {\n    return (typeCode << 16) | (bits  << 8) | lanes;\n  }\n\n  @Override public boolean equals(Object other) {\n    if (other != null && other instanceof TVMType) {\n      TVMType otherInst = (TVMType) other;\n      return (bits == otherInst.bits)\n        && (typeCode == otherInst.typeCode) && (lanes == otherInst.lanes);\n    }\n    return false;\n  }\n\n  @Override public String toString() {\n    String typeCodeStr;\n    switch (typeCode) {\n      case INT:\n        typeCodeStr = \"int\";\n        break;\n      case UINT:\n        typeCodeStr = \"uint\";\n        break;\n      case FLOAT:\n        typeCodeStr = \"float\";\n        break;\n      case HANDLE:\n        typeCodeStr = \"handle\";\n        break;\n      default:\n        typeCodeStr = \"Unknown\";\n        break;\n    }\n    String str = typeCodeStr + bits;\n    if (lanes != 1) {\n      str += lanes;\n    }\n    return str;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValue.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValue {\n  public final ArgTypeCode typeCode;\n\n  public TVMValue(ArgTypeCode tc) {\n    typeCode = tc;\n  }\n\n  public void release() {\n  }\n\n  public long asLong() {\n    throw new UnsupportedOperationException();\n  }\n\n  public double asDouble() {\n    throw new UnsupportedOperationException();\n  }\n\n  public byte[] asBytes() {\n    throw new UnsupportedOperationException();\n  }\n\n  public Module asModule() {\n    throw new UnsupportedOperationException();\n  }\n\n  public Function asFunction() {\n    throw new UnsupportedOperationException();\n  }\n\n  public NDArrayBase asNDArray() {\n    throw new UnsupportedOperationException();\n  }\n\n  public String asString() {\n    throw new UnsupportedOperationException();\n  }\n\n  // easy for JNI to use.\n  long asHandle() {\n    throw new UnsupportedOperationException();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueBytes.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValueBytes extends TVMValue {\n  public final byte[] value;\n\n  public TVMValueBytes(byte[] value) {\n    super(ArgTypeCode.BYTES);\n    this.value = value;\n  }\n\n  @Override public byte[] asBytes() {\n    return value;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueDouble.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValueDouble extends TVMValue {\n  public final double value;\n\n  public TVMValueDouble(double value) {\n    super(ArgTypeCode.FLOAT);\n    this.value = value;\n  }\n\n  @Override public double asDouble() {\n    return value;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueHandle.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\n/**\n * Java class related to TVM handles (ArgTypeCode.HANDLE)\n */\npublic class TVMValueHandle extends TVMValue {\n  public final long value;\n\n  public TVMValueHandle(long value) {\n    super(ArgTypeCode.HANDLE);\n    this.value = value;\n  }\n\n  @Override public long asHandle() {\n    return value;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueLong.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValueLong extends TVMValue {\n  public final long value;\n\n  public TVMValueLong(long value) {\n    super(ArgTypeCode.INT);\n    this.value = value;\n  }\n\n  @Override public long asLong() {\n    return value;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueNull.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValueNull extends TVMValue {\n  public TVMValueNull() {\n    super(ArgTypeCode.NULL);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/TVMValueString.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\npublic class TVMValueString extends TVMValue {\n  public final String value;\n\n  public TVMValueString(String value) {\n    super(ArgTypeCode.STR);\n    this.value = value;\n  }\n\n  @Override public String asString() {\n    return value;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/contrib/GraphExecutor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.contrib;\n\nimport org.apache.tvm.Device;\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.TVMValue;\nimport org.apache.tvm.rpc.RPC;\nimport org.apache.tvm.rpc.RPCSession;\nimport org.apache.tvm.rpc.TVMRemoteDevice;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\npublic class GraphExecutor {\n  /**\n   * Create a runtime executor module given a graph and module.\n   * @param graphJson The graph deployed in json format output by compiler.\n   * @param libmod The module of the corresponding function.\n   * @param dev The local or remote device to deploy the module.\n   * @return Runtime graph module that can be used to execute the graph.\n   */\n  public static GraphModule create(String graphJson, Module libmod, Device dev) {\n    Function fcreate = Function.getFunction(\"tvm.graph_executor.create\");\n    if (fcreate == null) {\n      throw new RuntimeException(\"Cannot find global function tvm.graph_executor.create.\"\n          + \"Did you compile tvm_runtime with correct version?\");\n    }\n    Module graphModule = fcreate.pushArg(graphJson)\n        .pushArg(libmod).pushArg(dev.deviceType).pushArg(dev.deviceId)\n        .invoke().asModule();\n\n    return new GraphModule(graphModule, dev);\n  }\n\n  private static Object reflectionGetField(Object obj, String fieldName) {\n    try {\n      Field field = obj.getClass().getDeclaredField(fieldName);\n      field.setAccessible(true);\n      return field.get(obj);\n    } catch (NoSuchFieldException e) {\n      throw new RuntimeException(e);\n    } catch (IllegalAccessException e) {\n      throw new RuntimeException(e);\n    }\n  }\n\n  private static Object reflectionStaticCall(Class<?> clazz, String methodName, Object ... args) {\n    Class<?>[] types = new Class<?>[args.length];\n    for (int i = 0; i < args.length; ++i) {\n      types[i] = args[i].getClass();\n    }\n    try {\n      Method method = clazz.getDeclaredMethod(methodName, types);\n      method.setAccessible(true);\n      return method.invoke(null, args);\n    } catch (NoSuchMethodException e) {\n      throw new RuntimeException(e);\n    } catch (IllegalAccessException e) {\n      throw new RuntimeException(e);\n    } catch (InvocationTargetException e) {\n      throw new RuntimeException(e);\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/contrib/GraphModule.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.apache.tvm.contrib;\n\nimport org.apache.tvm.Device;\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.NDArray;\n\n/**\n * Wrapper runtime module.\n * This is a thin wrapper of the underlying TVM module.\n * you can also directly call set_input, run, and get_output\n * of underlying module functions.\n */\npublic class GraphModule {\n  private Module module;\n  private Device device;\n\n  private Function fsetInput;\n  private Function frun;\n  private Function fgetOutput;\n  private Function fgetInput;\n  private Function fdebugGetOutput;\n  private Function floadParams;\n\n  GraphModule(Module module, Device dev) {\n    this.module = module;\n    this.device = dev;\n    fsetInput = module.getFunction(\"set_input\");\n    frun = module.getFunction(\"run\");\n    fgetInput = module.getFunction(\"get_input\");\n    fgetOutput = module.getFunction(\"get_output\");\n    try {\n      fdebugGetOutput = module.getFunction(\"debug_get_output\");\n    } catch (IllegalArgumentException ignored) {\n      // ignore\n    }\n    floadParams = module.getFunction(\"load_params\");\n  }\n\n  /**\n   * Release the GraphModule.\n   * <p>\n   * We highly recommend you to do this manually since the GC strategy is lazy.\n   * </p>\n   */\n  public void release() {\n    fsetInput.release();\n    frun.release();\n    fgetInput.release();\n    fgetOutput.release();\n    if (fdebugGetOutput != null) {\n      fdebugGetOutput.release();\n    }\n    floadParams.release();\n    module.release();\n  }\n\n  /**\n   * Set inputs to the module.\n   * @param key The input key.\n   * @param value The input value\n   * @return self.\n   */\n  public GraphModule setInput(String key, NDArray value) {\n    NDArray input = value;\n    if (!value.device().equals(device)) {\n      input = NDArray.empty(value.shape(), device);\n      value.copyTo(input);\n    }\n    fsetInput.pushArg(key).pushArg(input).invoke();\n    return this;\n  }\n\n  /**\n   * Set inputs to the module.\n   * @param key The input key.\n   * @param value The input value.\n   * @return self.\n   */\n  public GraphModule setInput(int key, NDArray value) {\n    NDArray input = value;\n    if (!value.device().equals(device)) {\n      input = NDArray.empty(value.shape(), device);\n      value.copyTo(input);\n    }\n    fsetInput.pushArg(key).pushArg(input).invoke();\n    return this;\n  }\n\n  /**\n   * Run forward execution of the graph.\n   * @return self.\n   */\n  public GraphModule run() {\n    frun.invoke();\n    return this;\n  }\n\n  /**\n   * Get index-th input to out.\n   * @param index The input index.\n   * @param out The output array container.\n   * @return out.\n   */\n  public NDArray getInput(int index, NDArray out) {\n    fgetInput.pushArg(index).pushArg(out).invoke();\n    return out;\n  }\n\n  /**\n   * Get index-th output to out.\n   * @param index The output index.\n   * @param out The output array container.\n   * @return out.\n   */\n  public NDArray getOutput(int index, NDArray out) {\n    fgetOutput.pushArg(index).pushArg(out).invoke();\n    return out;\n  }\n\n  /**\n   * Run graph up to node and get the output to out.\n   * @param node The node name.\n   * @param out The output array container.\n   * @return out.\n   */\n  public NDArray debugGetOutput(String node, NDArray out) {\n    if (fdebugGetOutput != null) {\n      fdebugGetOutput.pushArg(node).pushArg(out).invoke();\n    } else {\n      throw new RuntimeException(\"Please compile runtime with USE_PROFILER = ON\");\n    }\n    return out;\n  }\n\n  /**\n   * Run graph up to node and get the output to out.\n   * @param node The node index.\n   * @param out The output array container.\n   * @return out.\n   */\n  public NDArray debugGetOutput(int node, NDArray out) {\n    if (fdebugGetOutput != null) {\n      fdebugGetOutput.pushArg(node).pushArg(out).invoke();\n    } else {\n      throw new RuntimeException(\"Please compile runtime with USE_PROFILER = ON\");\n    }\n    return out;\n  }\n\n  /**\n   * Load parameters from serialized byte array of parameter dict.\n   * @param params The serialized parameter.\n   * @return self.\n   */\n  public GraphModule loadParams(byte[] params) {\n    floadParams.pushArg(params).invoke();\n    return this;\n  }\n\n  /**\n   * Get internal module function.\n   * @param key The key to the module.\n   * @return The function.\n   * @throws IllegalArgumentException if function does not exist.\n   */\n  public Function getFunction(String key) {\n    return module.getFunction(key);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/Client.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.TVMValue;\n\npublic class Client {\n  /**\n   * Connect to RPC Server.\n   * @param url The url of the host.\n   * @param port The port to connect to.\n   * @param key Additional key to match server.\n   * @return The connected session.\n   */\n  public static RPCSession connect(String url, int port, String key) {\n    Function doConnect = RPC.getApi(\"Connect\");\n    if (doConnect == null) {\n      throw new RuntimeException(\"Please compile with USE_RPC=1\");\n    }\n    TVMValue sess = doConnect.pushArg(url).pushArg(port).pushArg(key).invoke();\n    return new RPCSession(sess.asModule());\n  }\n\n  /**\n   * Connect to RPC Server.\n   * @param url The url of the host.\n   * @param port The port to connect to.\n   * @return The connected session.\n   */\n  public static RPCSession connect(String url, int port) {\n    return connect(url, port, \"\");\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/ConnectProxyServerProcessor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketAddress;\n\n/**\n * Server processor for proxy connection.\n */\npublic class ConnectProxyServerProcessor implements ServerProcessor {\n  private final String host;\n  private final int port;\n  private final String key;\n\n  private volatile Socket currSocket = new Socket();\n  private Runnable callback;\n\n  /**\n   * Construct proxy server processor.\n   * @param host Proxy server host.\n   * @param port Proxy server port.\n   * @param key Proxy server key.\n   */\n  public ConnectProxyServerProcessor(String host, int port, String key) {\n    this.host = host;\n    this.port = port;\n    this.key = \"server:\" + key;\n  }\n\n  /**\n   * Set a callback when a connection is received e.g., to record the time for a\n   * watchdog.\n   * @param callback Runnable object.\n   */\n  public void setStartTimeCallback(Runnable callback) {\n    this.callback = callback;\n  }\n\n  /**\n   * Close the socket.\n   */\n  @Override public void terminate() {\n    Utils.closeQuietly(currSocket);\n  }\n\n  @Override public void run() {\n    try {\n      SocketAddress address = new InetSocketAddress(host, port);\n      currSocket.connect(address, 6000);\n      final InputStream in = currSocket.getInputStream();\n      final OutputStream out = currSocket.getOutputStream();\n      out.write(Utils.toBytes(RPC.RPC_MAGIC));\n      out.write(Utils.toBytes(key.length()));\n      out.write(Utils.toBytes(key));\n      int magic = Utils.wrapBytes(Utils.recvAll(in, 4)).getInt();\n      if (magic == RPC.RPC_MAGIC + 1) {\n        throw new RuntimeException(\n            String.format(\"key: %s has already been used in proxy\", key));\n      } else if (magic == RPC.RPC_MAGIC + 2) {\n        System.err.println(\"RPCProxy do not have matching client key \" + key);\n      } else if (magic != RPC.RPC_MAGIC) {\n        throw new RuntimeException(address + \" is not RPC Proxy\");\n      }\n      // Get key from remote\n      int keylen = Utils.wrapBytes(Utils.recvAll(in, 4)).getInt();\n      String remoteKey = Utils.decodeToStr(Utils.recvAll(in, keylen));\n      System.err.println(\"RPCProxy connected to \" + address);\n      if (callback != null) {\n        callback.run();\n      }\n\n      SocketChannel sockChannel = new SocketChannel(currSocket);\n      new NativeServerLoop(sockChannel.getFsend(), sockChannel.getFrecv()).run();\n      System.err.println(\"Finish serving \" + address);\n    } catch (Throwable e) {\n      e.printStackTrace();\n      throw new RuntimeException(e);\n    } finally {\n      terminate();\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/ConnectTrackerServerProcessor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.BindException;\nimport java.net.ConnectException;\nimport java.net.InetSocketAddress;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.SocketAddress;\nimport java.net.SocketException;\nimport java.net.SocketTimeoutException;\n\n\n/**\n * Server processor with tracker connection (based on standalone).\n * This RPC Server registers itself with an RPC Tracker for a specific queue\n * (using its device key) and listens for incoming requests.\n */\npublic class ConnectTrackerServerProcessor implements ServerProcessor {\n  private ServerSocket server;\n  private final String trackerHost;\n  private final int trackerPort;\n  // device key\n  private final String key;\n  // device key plus randomly generated key (per-session)\n  private final String matchKey;\n  private int serverPort = 5001;\n  public static final int MAX_SERVER_PORT = 5555;\n  // time to wait before aborting tracker connection (ms)\n  public static final int TRACKER_TIMEOUT = 6000;\n  // time to wait before retrying tracker connection (ms)\n  public static final int RETRY_PERIOD = TRACKER_TIMEOUT;\n  // time to wait for a connection before refreshing tracker connection (ms)\n  public static final int STALE_TRACKER_TIMEOUT = 300000;\n  // time to wait if no timeout value is specified (seconds)\n  public static final int HARD_TIMEOUT_DEFAULT = 300;\n  private RPCWatchdog watchdog;\n  private Socket trackerSocket;\n\n  /**\n   * Construct tracker server processor.\n   * @param trackerHost Tracker host.\n   * @param trackerPort Tracker port.\n   * @param key Device key.\n   * @param watchdog watch for timeout, etc.\n   * @throws java.io.IOException when socket fails to open.\n   */\n  public ConnectTrackerServerProcessor(String trackerHost, int trackerPort, String key,\n      RPCWatchdog watchdog) throws IOException {\n    while (true) {\n      try {\n        this.server = new ServerSocket(serverPort);\n        server.setSoTimeout(STALE_TRACKER_TIMEOUT);\n        break;\n      } catch (BindException e) {\n        System.err.println(serverPort);\n        System.err.println(e);\n        serverPort++;\n        if (serverPort > MAX_SERVER_PORT) {\n          throw e;\n        }\n      }\n    }\n    System.err.println(\"using port: \" + serverPort);\n    this.trackerHost = trackerHost;\n    this.trackerPort = trackerPort;\n    this.key = key;\n    this.matchKey = key + \":\" + Math.random();\n    this.watchdog = watchdog;\n  }\n\n  public String getMatchKey() {\n    return matchKey;\n  }\n\n  @Override public void terminate() {\n    try {\n      server.close();\n    } catch (IOException e) {\n      e.printStackTrace();\n    }\n  }\n\n  @Override public void run() {\n    String recvKey = null;\n    try {\n      trackerSocket = connectToTracker();\n      // open a socket and handshake with tracker\n      register();\n      Socket socket = null;\n      InputStream in = null;\n      OutputStream out = null;\n      while (true) {\n        try {\n          System.err.println(\"waiting for requests...\");\n          // wait for client request\n          socket = server.accept();\n          in = socket.getInputStream();\n          out = socket.getOutputStream();\n          int magic = Utils.wrapBytes(Utils.recvAll(in, 4)).getInt();\n          if (magic != RPC.RPC_MAGIC) {\n            out.write(Utils.toBytes(RPC.RPC_CODE_MISMATCH));\n            System.err.println(\"incorrect RPC magic\");\n            Utils.closeQuietly(socket);\n            continue;\n          }\n          recvKey = Utils.recvString(in);\n          System.err.println(\"matchKey:\" + matchKey);\n          System.err.println(\"key: \" + recvKey);\n          // incorrect key\n          if (recvKey.indexOf(matchKey) == -1) {\n            out.write(Utils.toBytes(RPC.RPC_CODE_MISMATCH));\n            System.err.println(\"key mismatch, expected: \" + matchKey + \" got: \" +  recvKey);\n            Utils.closeQuietly(socket);\n            continue;\n          }\n          // successfully got client request and completed handshake with client\n          break;\n        } catch (SocketTimeoutException e) {\n          System.err.println(\"no incoming connections, refreshing...\");\n          // need to reregister, if the tracker died we should see a socked closed exception\n          if (!needRefreshKey()) {\n            System.err.println(\"reregistering...\");\n            register();\n          }\n        }\n      }\n      int timeout = HARD_TIMEOUT_DEFAULT;\n      int timeoutArgIndex = recvKey.indexOf(RPC.TIMEOUT_ARG);\n      if (timeoutArgIndex != -1) {\n        timeout = Integer.parseInt(recvKey.substring(timeoutArgIndex + RPC.TIMEOUT_ARG.length()));\n      }\n      System.err.println(\"alloted timeout: \" + timeout);\n      if (!recvKey.startsWith(\"client:\")) {\n        System.err.println(\"recv key mismatch...\");\n        out.write(Utils.toBytes(RPC.RPC_CODE_MISMATCH));\n      } else {\n        out.write(Utils.toBytes(RPC.RPC_MAGIC));\n        // send server key to the client\n        Utils.sendString(out, recvKey);\n      }\n\n      System.err.println(\"Connection from \" + socket.getRemoteSocketAddress().toString());\n      // received timeout in seconds\n      watchdog.startTimeout(timeout * 1000);\n      SocketChannel sockChannel = new SocketChannel(socket);\n      new NativeServerLoop(sockChannel.getFsend(), sockChannel.getFrecv()).run();\n      System.err.println(\"Finish serving \" + socket.getRemoteSocketAddress().toString());\n      Utils.closeQuietly(socket);\n    } catch (ConnectException e) {\n      // if the tracker connection failed, wait a bit before retrying\n      try {\n        Thread.sleep(RETRY_PERIOD);\n      } catch (InterruptedException e_) {\n        System.err.println(\"interrupted before retrying to connect to tracker...\");\n      }\n    } catch (Throwable e) {\n      e.printStackTrace();\n    } finally {\n      try {\n        if (trackerSocket != null) {\n          trackerSocket.close();\n        }\n        server.close();\n      } catch (Throwable e) {\n        e.printStackTrace();\n      }\n    }\n  }\n\n  private Socket connectToTracker() throws IOException {\n    trackerSocket = new Socket();\n    SocketAddress address = new InetSocketAddress(trackerHost, trackerPort);\n    trackerSocket.connect(address, TRACKER_TIMEOUT);\n    InputStream trackerIn = trackerSocket.getInputStream();\n    OutputStream trackerOut = trackerSocket.getOutputStream();\n    trackerOut.write(Utils.toBytes(RPC.RPC_TRACKER_MAGIC));\n    int trackerMagic = Utils.wrapBytes(Utils.recvAll(trackerIn, 4)).getInt();\n    if (trackerMagic != RPC.RPC_TRACKER_MAGIC) {\n      throw new SocketException(\"failed to connect to tracker (WRONG MAGIC)\");\n    }\n    String infoJSON = generateCinfo(key);\n    Utils.sendString(trackerOut, infoJSON);\n    int recvCode = Integer.parseInt(Utils.recvString(trackerIn));\n    if (recvCode != RPC.TrackerCode.SUCCESS) {\n      throw new SocketException(\"failed to connect to tracker (not SUCCESS)\");\n    }\n    return trackerSocket;\n  }\n\n  /*\n   * Register the RPC Server with the RPC Tracker.\n   */\n  private void register() throws IOException {\n    InputStream trackerIn = trackerSocket.getInputStream();\n    OutputStream trackerOut = trackerSocket.getOutputStream();\n    // send a JSON with PUT, device key, RPC server port, and the randomly\n    // generated key\n    String putJSON = generatePut(RPC.TrackerCode.PUT, key, serverPort, matchKey);\n    Utils.sendString(trackerOut, putJSON);\n    int recvCode = Integer.parseInt(Utils.recvString(trackerIn));\n    if (recvCode != RPC.TrackerCode.SUCCESS) {\n      throw new SocketException(\"failed to register with tracker (not SUCCESS)\");\n    }\n    System.err.println(\"registered with tracker...\");\n  }\n\n  /*\n   * Check if the RPC Tracker has our key.\n   */\n  private boolean needRefreshKey() throws IOException {\n    InputStream trackerIn = trackerSocket.getInputStream();\n    OutputStream trackerOut = trackerSocket.getOutputStream();\n    String getJSON = generateGetPendingMatchKeys(RPC.TrackerCode.GET_PENDING_MATCHKEYS);\n    Utils.sendString(trackerOut, getJSON);\n    String recvJSON = Utils.recvString(trackerIn);\n    System.err.println(\"pending matchkeys: \" + recvJSON);\n    // fairly expensive string operation...\n    if (recvJSON.indexOf(matchKey) != -1 ) {\n      return true;\n    }\n    return false;\n  }\n\n  // handcrafted JSON\n  private String generateCinfo(String key) {\n    String cinfo = \"{\\\"key\\\" : \" + \"\\\"server:\" + key + \"\\\", \\\"addr\\\": [null, \\\"\"\n        + serverPort + \"\\\"]}\";\n    return \"[\" + RPC.TrackerCode.UPDATE_INFO + \", \" + cinfo + \"]\";\n  }\n\n  // handcrafted JSON\n  private String generatePut(int code, String key, int port, String matchKey) {\n    return \"[\" + code + \", \" + \"\\\"\" + key + \"\\\"\" + \", \" + \"[\" + port + \", \"\n            + \"\\\"\" + matchKey +  \"\\\"\" + \"]\" + \", \" + \"null\" + \"]\";\n  }\n\n  // handcrafted JSON\n  private String generateGetPendingMatchKeys(int code) {\n    return \"[\" + code  + \"]\";\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/NativeServerLoop.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.TVMValue;\n\nimport java.io.File;\nimport java.io.IOException;\n\n/**\n * Call native ServerLoop on socket file descriptor.\n */\npublic class NativeServerLoop implements Runnable {\n  private final Function fsend;\n  private final Function frecv;\n\n  /**\n   * Constructor for NativeServerLoop.\n   * @param fsend socket.send function.\n   * @param frecv socket.recv function.\n   */\n  public NativeServerLoop(final Function fsend, final Function frecv) {\n    this.fsend = fsend;\n    this.frecv = frecv;\n  }\n\n  @Override public void run() {\n    File tempDir = null;\n    try {\n      tempDir = serverEnv();\n      System.err.println(\"starting server loop...\");\n      RPC.getApi(\"ServerLoop\").pushArg(fsend).pushArg(frecv).invoke();\n      System.err.println(\"done server loop...\");\n    } catch (IOException e) {\n      e.printStackTrace();\n    } finally {\n      if (tempDir != null) {\n        String[] entries = tempDir.list();\n        for (String s : entries) {\n          File currentFile = new File(tempDir.getPath(), s);\n          if (!currentFile.delete()) {\n            System.err.println(\n                \"[WARN] Couldn't delete temporary file \" + currentFile.getAbsolutePath());\n          }\n        }\n        if (!tempDir.delete()) {\n          System.err.println(\n              \"[WARN] Couldn't delete temporary directory \" + tempDir.getAbsolutePath());\n        }\n      }\n    }\n  }\n\n  private static File serverEnv() throws IOException {\n    // Server environment function return temp dir.\n    final File tempDir = File.createTempFile(\"tvm4j_rpc_\", \"\");\n    if (!tempDir.delete() || !tempDir.mkdir()) {\n      throw new IOException(\"Couldn't create directory \" + tempDir.getAbsolutePath());\n    }\n\n    Function.register(\"tvm.rpc.server.workpath\", new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        return tempDir + File.separator + args[0].asString();\n      }\n    }, true);\n\n    Function.register(\"tvm.rpc.server.load_module\", new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        String filename = args[0].asString();\n        String path = tempDir + File.separator + filename;\n        System.err.println(\"Load module from \" + path);\n        return Module.load(path);\n      }\n    }, true);\n\n    return tempDir;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/RPC.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Function;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class RPC {\n  public static final int RPC_TRACKER_MAGIC = 0x2f271;\n  public static final int RPC_MAGIC = 0xff271;\n  public static final int RPC_CODE_MISMATCH = RPC_MAGIC + 2;\n  public static final int RPC_SESS_MASK = 128;\n\n  public static final String TIMEOUT_ARG = \"-timeout=\";\n\n  public class TrackerCode {\n    public static final int PUT = 3;\n    public static final int UPDATE_INFO = 5;\n    public static final int GET_PENDING_MATCHKEYS = 7;\n    public static final int SUCCESS = 0;\n  }\n\n  private static ThreadLocal<Map<String, Function>> apiFuncs\n      = new ThreadLocal<Map<String, Function>>() {\n          @Override\n          protected Map<String, Function> initialValue() {\n            return new HashMap<String, Function>();\n          }\n        };\n\n  /**\n   * Get internal function starts with namespace tvm.rpc.\n   * @param name function name.\n   * @return the function, null if not exists.\n   */\n  static Function getApi(String name) {\n    Function func = apiFuncs.get().get(name);\n    if (func == null) {\n      func = Function.getFunction(\"rpc.\" + name);\n      if (func == null) {\n        return null;\n      }\n      apiFuncs.get().put(name, func);\n    }\n    return func;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/RPCSession.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.apache.tvm.Device;\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\n\n/**\n * RPC Client session module.\n * Do not directly create the object, use Client.connect.\n */\npublic class RPCSession {\n  private final Module session;\n  private final int tblIndex;\n  private final Map<String, Function> remoteFuncs = new HashMap<String, Function>();\n\n  RPCSession(Module sess) {\n    session = sess;\n    tblIndex = (int) RPC.getApi(\"SessTableIndex\").pushArg(session).invoke().asLong();\n  }\n\n  /**\n   * Get function from the session.\n   * @param name The name of the function.\n   * @return The result function.\n   */\n  public Function getFunction(String name) {\n    return session.getFunction(name);\n  }\n\n  /**\n   * Construct a remote device.\n   * @param devType device type.\n   * @param devId device id.\n   * @return The corresponding encoded remote device.\n   */\n  public Device device(String devType, int devId) {\n    Device dev = new Device(devType, devId);\n    int encode = (tblIndex + 1) * RPC.RPC_SESS_MASK;\n    return new TVMRemoteDevice(dev.deviceType + encode, devId, this);\n  }\n\n  /**\n   * Construct a remote device.\n   * @param devType device type.\n   * @return The corresponding encoded remote device.\n   */\n  public Device device(String devType) {\n    return device(devType, 0);\n  }\n\n  /**\n   * Construct a remote device.\n   * @param devType device type.\n   * @param devId device id.\n   * @return The corresponding encoded remote device.\n   */\n  public Device device(int devType, int devId) {\n    int encode = (tblIndex + 1) * RPC.RPC_SESS_MASK;\n    return new TVMRemoteDevice(devType + encode, devId, this);\n  }\n\n  /**\n   * Construct a remote device.\n   * @param devType device type.\n   * @return The corresponding encoded remote device.\n   */\n  public Device device(int devType) {\n    return device(devType, 0);\n  }\n\n  /**\n   * Construct remote CPU device.\n   * @param devId device id.\n   * @return Remote CPU device.\n   */\n  public Device cpu(int devId) {\n    return Device.cpu(devId);\n  }\n\n  /**\n   * Construct remote CPU device.\n   * @return Remote CPU device.\n   */\n  public Device cpu() {\n    return cpu(0);\n  }\n\n  /**\n   * Construct remote CUDA GPU device.\n   * @param devId device id.\n   * @return Remote CUDA GPU device.\n   */\n  public Device cuda(int devId) {\n    return Device.cuda(devId);\n  }\n\n  /**\n   * Construct remote CUDA GPU device.\n   * @return Remote CUDA GPU device.\n   */\n  public Device cuda() {\n    return cuda(0);\n  }\n\n  /**\n   * Construct remote OpenCL device.\n   * @param devId device id.\n   * @return Remote OpenCL device.\n   */\n  public Device cl(int devId) {\n    return Device.opencl(devId);\n  }\n\n  /**\n   * Construct remote OpenCL device.\n   * @return Remote OpenCL device.\n   */\n  public Device cl() {\n    return cl(0);\n  }\n\n  /**\n   * Construct remote OpenCL device.\n   * @param devId device id.\n   * @return Remote OpenCL device.\n   */\n  public Device vulkan(int devId) {\n    return Device.vulkan(devId);\n  }\n\n  /**\n   * Construct remote OpenCL device.\n   * @return Remote OpenCL device.\n   */\n  public Device vulkan() {\n    return vulkan(0);\n  }\n\n  /**\n   * Construct remote Metal device.\n   * @param devId device id.\n   * @return Remote metal device.\n   */\n  public Device metal(int devId) {\n    return Device.metal(devId);\n  }\n\n  /**\n   * Construct remote Metal device.\n   * @return Remote metal device.\n   */\n  public Device metal() {\n    return metal(0);\n  }\n\n  /**\n   * Upload binary to remote runtime temp folder.\n   * @param data The binary in local to upload.\n   * @param target The path in remote, cannot be null.\n   */\n  public void upload(byte[] data, String target) {\n    if (target == null) {\n      throw new IllegalArgumentException(\"Please specify the upload target\");\n    }\n    final String funcName = \"upload\";\n    Function remoteFunc = remoteFuncs.get(funcName);\n    if (remoteFunc == null) {\n      remoteFunc = getFunction(\"tvm.rpc.server.upload\");\n      remoteFuncs.put(funcName, remoteFunc);\n    }\n    remoteFunc.pushArg(target).pushArg(data).invoke();\n  }\n\n  /**\n   * Upload file to remote runtime temp folder.\n   * @param data The file in local to upload.\n   * @param target The path in remote.\n   * @throws java.io.IOException for network failure.\n   */\n  public void upload(File data, String target) throws IOException {\n    byte[] blob = getBytesFromFile(data);\n    upload(blob, target);\n  }\n\n  /**\n   * Upload file to remote runtime temp folder.\n   * @param data The file in local to upload.\n   * @throws java.io.IOException for network failure.\n   */\n  public void upload(File data) throws IOException {\n    upload(data, data.getName());\n  }\n\n  /**\n   * Download file from remote temp folder.\n   * @param path The relative location to remote temp folder.\n   * @return The result blob from the file.\n   */\n  public byte[] download(String path) {\n    final String name = \"download\";\n    Function func = remoteFuncs.get(name);\n    if (func == null) {\n      func = getFunction(\"tvm.rpc.server.download\");\n      remoteFuncs.put(name, func);\n    }\n    return func.pushArg(path).invoke().asBytes();\n  }\n\n  /**\n   * Load a remote module, the file need to be uploaded first.\n   * @param path The relative location to remote temp folder.\n   * @return The remote module containing remote function.\n   */\n  public Module loadModule(String path) {\n    return RPC.getApi(\"LoadRemoteModule\").pushArg(session).pushArg(path).invoke().asModule();\n  }\n\n  private static byte[] getBytesFromFile(File file) throws IOException {\n    // Get the size of the file\n    long length = file.length();\n\n    if (length > Integer.MAX_VALUE) {\n      throw new IOException(\"File \" + file.getName() + \" is too large!\");\n    }\n\n    // cannot create an array using a long type.\n    byte[] bytes = new byte[(int) length];\n\n    // Read in the bytes\n    int offset = 0;\n    int numRead = 0;\n\n    InputStream is = new FileInputStream(file);\n    try {\n      while (\n          offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {\n        offset += numRead;\n      }\n    } finally {\n      is.close();\n    }\n\n    // Ensure all the bytes have been read in\n    if (offset < bytes.length) {\n      throw new IOException(\"Could not completely read file \" + file.getName());\n    }\n    return bytes;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/RPCWatchdog.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\n/**\n * Watchdog for RPC.\n */\npublic class RPCWatchdog extends Thread {\n  private int timeout = 0;\n  private boolean started = false;\n\n  public RPCWatchdog() {\n    super();\n  }\n\n  /**\n   * Start a timeout with watchdog (must be called before finishTimeout).\n   * @param timeout watchdog timeout in ms.\n   */\n  public synchronized void startTimeout(int timeout) {\n    this.timeout = timeout;\n    started = true;\n    this.notify();\n  }\n\n  /**\n   * Finish a timeout with watchdog (must be called after startTimeout).\n   */\n  public synchronized void finishTimeout() {\n    started = false;\n    this.notify();\n  }\n\n  /**\n   * Wait and kill RPC if timeout is exceeded.\n   */\n  @Override public void run() {\n    while (true) {\n      // timeout not started\n      synchronized (this) {\n        while (!started) {\n          try {\n            this.wait();\n          } catch (InterruptedException e) {\n            System.err.println(\"watchdog interrupted...\");\n          }\n        }\n      }\n      synchronized (this) {\n        while (started) {\n          try {\n            System.err.println(\"waiting for timeout: \" + timeout);\n            this.wait(timeout);\n            if (!started) {\n              System.err.println(\"watchdog woken up, ok...\");\n            } else {\n              System.err.println(\"watchdog woke up!\");\n              System.err.println(\"terminating...\");\n              terminate();\n            }\n          } catch (InterruptedException e) {\n            System.err.println(\"watchdog interrupted...\");\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * Default method to terminate the running RPCActivity process.\n   */\n  protected void terminate() {\n    System.exit(0);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/Server.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.IOException;\n\n/**\n * RPC Server.\n */\npublic class Server {\n  private final WorkerThread worker;\n\n  private static class WorkerThread extends Thread {\n    private volatile boolean running = true;\n    private final ServerProcessor processor;\n\n    public WorkerThread(ServerProcessor processor) {\n      this.processor = processor;\n    }\n\n    @Override public void run() {\n      while (running) {\n        processor.run();\n        try {\n          Thread.sleep(1000);\n        } catch (InterruptedException e) {\n          e.printStackTrace();\n        }\n      }\n    }\n\n    public void terminate() {\n      running = false;\n      processor.terminate();\n    }\n  }\n\n  /**\n   * Start a standalone server.\n   * @param serverPort Port.\n   * @throws IOException if failed to bind localhost:port.\n   */\n  public Server(int serverPort) throws IOException {\n    worker = new WorkerThread(new StandaloneServerProcessor(serverPort));\n  }\n\n  /**\n   * Start a server connected to proxy.\n   * Use sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess\n   * to get file descriptor for the socket.\n   * @param proxyHost The proxy server host.\n   * @param proxyPort The proxy server port.\n   * @param key The key to identify the server.\n   */\n  public Server(String proxyHost, int proxyPort, String key) {\n    worker = new WorkerThread(\n        new ConnectProxyServerProcessor(proxyHost, proxyPort, key));\n  }\n\n  /**\n   * Start the server.\n   */\n  public void start() {\n    worker.start();\n  }\n\n  /**\n   * Stop the server.\n   */\n  public void terminate() {\n    worker.terminate();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/ServerProcessor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\n/**\n * Abstract runnable class for RPC server process.\n */\npublic interface ServerProcessor extends Runnable {\n  public void terminate();\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/SocketChannel.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.TVMValue;\nimport org.apache.tvm.TVMValueBytes;\n\nimport java.io.IOException;\nimport java.net.Socket;\n\npublic class SocketChannel {\n  private final Socket socket;\n\n  SocketChannel(Socket sock) {\n    socket = sock;\n  }\n\n  private Function fsend = Function.convertFunc(new Function.Callback() {\n    @Override public Object invoke(TVMValue... args) {\n      byte[] data = args[0].asBytes();\n      try {\n        socket.getOutputStream().write(data);\n      } catch (IOException e) {\n        e.printStackTrace();\n        return -1;\n      }\n      return data.length;\n    }\n  });\n\n  private Function frecv = Function.convertFunc(new Function.Callback() {\n    @Override public Object invoke(TVMValue... args) {\n      long size = args[0].asLong();\n      try {\n        return new TVMValueBytes(Utils.recvAll(socket.getInputStream(), (int) size));\n      } catch (IOException e) {\n        e.printStackTrace();\n        return -1;\n      }\n    }\n  });\n\n  public Function getFsend() {\n    return fsend;\n  }\n\n  public Function getFrecv() {\n    return frecv;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/StandaloneServerProcessor.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\n/**\n * Server processor for standalone.\n */\npublic class StandaloneServerProcessor implements ServerProcessor {\n  private final ServerSocket server;\n\n  public StandaloneServerProcessor(int serverPort) throws IOException {\n    this.server = new ServerSocket(serverPort);\n  }\n\n  @Override public void terminate() {\n    try {\n      server.close();\n    } catch (IOException e) {\n      e.printStackTrace();\n    }\n  }\n\n  @Override public void run() {\n    try {\n      final Socket socket = server.accept();\n      final InputStream in = socket.getInputStream();\n      final OutputStream out = socket.getOutputStream();\n      int magic = Utils.wrapBytes(Utils.recvAll(in, 4)).getInt();\n      if (magic != RPC.RPC_MAGIC) {\n        Utils.closeQuietly(socket);\n        return;\n      }\n      int keyLen = Utils.wrapBytes(Utils.recvAll(in, 4)).getInt();\n      String key = Utils.decodeToStr(Utils.recvAll(in, keyLen));\n      if (!key.startsWith(\"client:\")) {\n        out.write(Utils.toBytes(RPC.RPC_MAGIC + 2));\n      } else {\n        out.write(Utils.toBytes(RPC.RPC_MAGIC));\n        // send server key to the client\n        String serverKey = \"server:java\";\n        out.write(Utils.toBytes(serverKey.length()));\n        out.write(Utils.toBytes(serverKey));\n      }\n\n      SocketChannel sockChannel = new SocketChannel(socket);\n      System.err.println(\"Connection from \" + socket.getRemoteSocketAddress().toString());\n      new NativeServerLoop(sockChannel.getFsend(), sockChannel.getFrecv()).run();\n      System.err.println(\"Finish serving \" + socket.getRemoteSocketAddress().toString());\n      Utils.closeQuietly(socket);\n    } catch (Throwable e) {\n      e.printStackTrace();\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/TVMRemoteDevice.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Device;\n\n// always related to RPCSession. Cannot construct by users.\npublic class TVMRemoteDevice extends Device {\n  public final RPCSession rpcSession;\n\n  TVMRemoteDevice(int deviceType, int deviceId, RPCSession rpcSession) {\n    super(deviceType, deviceId);\n    this.rpcSession = rpcSession;\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/main/java/org/apache/tvm/rpc/Utils.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.Socket;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * Utilities for RPC.\n */\nclass Utils {\n  public static byte[] recvAll(final InputStream in, final int numBytes) throws IOException {\n    byte[] res = new byte[numBytes];\n    int numRead = 0;\n    while (numRead < numBytes) {\n      int chunk = in.read(res, numRead, Math.min(numBytes - numRead, 1024));\n      numRead += chunk;\n    }\n    return res;\n  }\n\n  public static void closeQuietly(Socket socket) {\n    if (socket != null) {\n      try {\n        socket.shutdownInput();\n        socket.shutdownOutput();\n        socket.close();\n      } catch (IOException ioe) {\n        // close quietly, do nothing.\n      }\n    }\n  }\n\n  public static ByteBuffer wrapBytes(byte[] bytes) {\n    ByteBuffer bb = ByteBuffer.wrap(bytes);\n    bb.order(ByteOrder.LITTLE_ENDIAN);\n    return bb;\n  }\n\n  public static byte[] toBytes(int number) {\n    ByteBuffer bb = ByteBuffer.allocate(4);\n    bb.order(ByteOrder.LITTLE_ENDIAN);\n    return bb.putInt(number).array();\n  }\n\n  public static byte[] toBytes(String str) {\n    byte[] bytes = new byte[str.length()];\n    for (int i = 0; i < str.length(); ++i) {\n      bytes[i] = (byte) str.charAt(i);\n    }\n    return bytes;\n  }\n\n  public static String decodeToStr(byte[] bytes) {\n    StringBuilder builder = new StringBuilder();\n    for (byte bt : bytes) {\n      builder.append((char) bt);\n    }\n    return builder.toString();\n  }\n\n  public static String recvString(InputStream in) throws IOException {\n    String recvString = null;\n    int len = wrapBytes(Utils.recvAll(in, 4)).getInt();\n    recvString = decodeToStr(Utils.recvAll(in, len));\n    return recvString;\n  }\n\n  public static void sendString(OutputStream out, String string) throws IOException {\n    out.write(toBytes(string.length()));\n    out.write(toBytes(string));\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/FunctionTest.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\n\npublic class FunctionTest {\n  @Test\n  public void test_reg_sum_number() {\n    Function.register(\"sum_number\", new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        long res = 0L;\n        for (TVMValue arg : args) {\n          res += arg.asLong();\n        }\n        return res;\n      }\n    });\n    Function func = Function.getFunction(\"sum_number\");\n    TVMValue res = func.pushArg(10).pushArg(20).invoke();\n    assertEquals(30, res.asLong());\n    res.release();\n    func.release();\n  }\n\n  @Test\n  public void test_add_string() {\n    Function func = Function.convertFunc(new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        String res = \"\";\n        for (TVMValue arg : args) {\n          res += arg.asString();\n        }\n        return res;\n      }\n    });\n    TVMValue res = func.pushArg(\"Hello\").pushArg(\" \").pushArg(\"World!\").invoke();\n    assertEquals(\"Hello World!\", res.asString());\n    res.release();\n    func.release();\n  }\n\n  @Test\n  public void test_sum_first_byte() {\n    Function func = Function.convertFunc(new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        byte[] bt = new byte[1];\n        for (TVMValue arg : args) {\n          bt[0] += arg.asBytes()[0];\n        }\n        return bt;\n      }\n    });\n    TVMValue res = func.pushArg(new byte[]{1}).pushArg(new byte[]{2, 3}).invoke();\n    assertArrayEquals(new byte[]{3}, res.asBytes());\n    res.release();\n    func.release();\n  }\n\n  @Test\n  public void test_sum_ndarray() {\n    final long[] shape = new long[]{2, 1};\n    Function func = Function.convertFunc(new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        double sum = 0.0;\n        for (TVMValue arg : args) {\n          NDArray arr = NDArray.empty(shape, new TVMType(\"float32\"));\n          arg.asNDArray().copyTo(arr);\n          float[] nativeArr = arr.asFloatArray();\n          for (int i = 0; i < nativeArr.length; ++i) {\n            sum += nativeArr[i];\n          }\n          arr.release();\n        }\n        return sum;\n      }\n    });\n    NDArray arr = NDArray.empty(shape, new TVMType(\"float32\"));\n    arr.copyFrom(new float[]{2f, 3f});\n    TVMValue res = func.pushArg(arr).pushArg(arr).invoke();\n    assertEquals(10.0, res.asDouble(), 1e-3);\n    res.release();\n    func.release();\n  }\n\n  @Test\n  public void test_return_function() {\n    Function myFunc = Function.convertFunc(new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        final long y = args[0].asLong();\n        return Function.convertFunc(new Function.Callback() {\n          @Override public Object invoke(TVMValue... args) {\n            final long x = args[0].asLong();\n            return x + y;\n          }\n        });\n      }\n    });\n    Function func = myFunc.pushArg(10).invoke().asFunction();\n    TVMValue res = func.pushArg(20).invoke();\n    assertEquals(30, res.asLong());\n    func.release();\n    myFunc.release();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/ModuleTest.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport static org.junit.Assert.*;\n\nimport java.io.File;\nimport java.util.Random;\n\npublic class ModuleTest {\n  private final Logger logger = LoggerFactory.getLogger(ModuleTest.class);\n  private static String loadingDir;\n\n  @BeforeClass\n  public static void beforeClass() {\n    loadingDir = System.getProperty(\"test.tempdir\");\n  }\n\n  @Test\n  public void test_load_add_func_cpu() {\n    Module fadd = Module.load(loadingDir + File.separator + \"add_cpu.so\");\n\n    Device dev = new Device(\"cpu\", 0);\n    long[] shape = new long[]{2};\n    NDArray arr = NDArray.empty(shape, dev);\n\n    arr.copyFrom(new float[]{3f, 4f});\n\n    NDArray res = NDArray.empty(shape, dev);\n\n    fadd.entryFunc().pushArg(arr).pushArg(arr).pushArg(res).invoke();\n    assertArrayEquals(new float[]{6f, 8f}, res.asFloatArray(), 1e-3f);\n\n    // test call() api\n    fadd.entryFunc().call(arr, arr, res);\n    assertArrayEquals(new float[]{6f, 8f}, res.asFloatArray(), 1e-3f);\n\n    arr.release();\n    res.release();\n    fadd.release();\n  }\n\n  @Test\n  public void test_load_add_func_cuda() {\n    final Random RND = new Random(0);\n\n    Device dev = new Device(\"cuda\", 0);\n    if (!dev.exist()) {\n      logger.warn(\"CUDA GPU does not exist. Skip the test.\");\n      return;\n    }\n\n    Module fadd = Module.load(loadingDir + File.separator + \"add_cuda.so\");\n    Module faddDev = Module.load(loadingDir + File.separator + \"add_cuda.ptx\");\n    fadd.importModule(faddDev);\n\n    final int dim = 100;\n    long[] shape = new long[]{dim};\n    NDArray arr = NDArray.empty(shape, dev);\n\n    float[] data = new float[dim];\n    float[] dataX2 = new float[dim];\n    for (int i = 0; i < dim; ++i) {\n      data[i] = RND.nextFloat();\n      dataX2[i] = data[i] * 2;\n    }\n    arr.copyFrom(data);\n\n    NDArray res = NDArray.empty(shape, dev);\n    fadd.entryFunc().pushArg(arr).pushArg(arr).pushArg(res).invoke();\n\n    assertArrayEquals(dataX2, res.asFloatArray(), 1e-3f);\n\n    arr.release();\n    res.release();\n    faddDev.release();\n    fadd.release();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/NDArrayTest.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\npublic class NDArrayTest {\n  @Test\n  public void test_from_float32() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"float32\"));\n    ndarray.copyFrom(new float[]{1, 2, 3, 4});\n    assertArrayEquals(new float[]{1f, 2f, 3f, 4f}, ndarray.asFloatArray(), 1e-3f);\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_float64() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"float64\"));\n    ndarray.copyFrom(new double[]{1, 2, 3, 4});\n    assertArrayEquals(new double[]{1.0, 2.0, 3.0, 4.0}, ndarray.asDoubleArray(), 1e-3);\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_int8() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"int8\"));\n    ndarray.copyFrom(new byte[]{1, 2, 3, 4});\n    assertArrayEquals(new byte[]{1, 2, 3, 4}, ndarray.asByteArray());\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_int16() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"int16\"));\n    ndarray.copyFrom(new short[]{1, 2, 3, 4});\n    assertArrayEquals(new short[]{1, 2, 3, 4}, ndarray.asShortArray());\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_int32() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"int32\"));\n    ndarray.copyFrom(new int[]{1, 2, 3, 4});\n    assertArrayEquals(new int[]{1, 2, 3, 4}, ndarray.asIntArray());\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_int64() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"int64\"));\n    ndarray.copyFrom(new long[]{1, 2, 3, 4});\n    assertArrayEquals(new long[]{1, 2, 3, 4}, ndarray.asLongArray());\n    ndarray.release();\n  }\n\n  @Test\n  public void test_from_uint16() {\n    NDArray ndarray = NDArray.empty(new long[]{2, 2}, new TVMType(\"uint16\"));\n    ndarray.copyFrom(new char[]{65535, 2, 3, 4});\n    assertArrayEquals(new char[]{65535, 2, 3, 4}, ndarray.asCharArray());\n    ndarray.release();\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/TestUtils.java",
        "content": "package org.apache.tvm;\n\n/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n\nimport org.apache.tvm.rpc.Server;\n\nimport java.io.IOException;\n\npublic class TestUtils {\n  public static class RefInt {\n    public int value;\n  }\n\n  public static Server startServer(RefInt portRef) {\n    Server server = null;\n    int port = 9981;\n    for (int i = 0; i < 10; ++i) {\n      try {\n        server = new Server(port + i);\n        server.start();\n        portRef.value = port + i;\n        return server;\n      } catch (IOException e) {\n      }\n    }\n    throw new RuntimeException(\"Cannot find an available port.\");\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/contrib/GraphExecutorTest.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.contrib;\n\nimport org.apache.tvm.Module;\nimport org.apache.tvm.NDArray;\nimport org.apache.tvm.Device;\nimport org.apache.tvm.TestUtils;\nimport org.apache.tvm.rpc.Client;\nimport org.apache.tvm.rpc.RPCSession;\nimport org.apache.tvm.rpc.Server;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Scanner;\n\nimport static org.junit.Assert.assertArrayEquals;\n\npublic class GraphExecutorTest {\n  private final Logger logger = LoggerFactory.getLogger(GraphExecutor.class);\n  private static String loadingDir;\n\n  @BeforeClass\n  public static void beforeClass() {\n    loadingDir = System.getProperty(\"test.tempdir\");\n  }\n\n  @Test\n  public void test_add_one_local() throws IOException {\n    Module libmod = Module.load(loadingDir + File.separator + \"graph_addone_lib.so\");\n    String graphJson = new Scanner(new File(\n        loadingDir + File.separator + \"graph_addone.json\"))\n        .useDelimiter(\"\\\\Z\").next();\n\n    Device dev = Device.cpu();\n    GraphModule graph = GraphExecutor.create(graphJson, libmod, dev);\n\n    long[] shape = new long[]{4};\n    NDArray arr = NDArray.empty(shape, dev);\n    arr.copyFrom(new float[]{1f, 2f, 3f, 4f});\n\n    NDArray out = NDArray.empty(shape, dev);\n\n    graph.setInput(\"x\", arr).run();\n    graph.getOutput(0, out);\n\n    assertArrayEquals(new float[]{2f, 3f, 4f, 5f}, out.asFloatArray(), 1e-3f);\n\n    arr.release();\n    out.release();\n    graph.release();\n  }\n\n  @Test\n  public void test_add_one_remote() throws IOException {\n    if (!Module.enabled(\"rpc\")) {\n      logger.warn(\"RPC is not enabled. Skip.\");\n      return;\n    }\n\n    String libPath = loadingDir + File.separator + \"graph_addone_lib.so\";\n    String graphJson = new Scanner(new File(\n        loadingDir + File.separator + \"graph_addone.json\"))\n        .useDelimiter(\"\\\\Z\").next();\n\n    TestUtils.RefInt port = new TestUtils.RefInt();\n    Server server = null;\n    try {\n      server = TestUtils.startServer(port);\n      RPCSession remote = Client.connect(\"127.0.0.1\", port.value);\n      Device dev = remote.cpu();\n\n      remote.upload(new File(libPath));\n      Module mlib = remote.loadModule(\"graph_addone_lib.so\");\n\n      GraphModule graph = GraphExecutor.create(graphJson, mlib, dev);\n\n      long[] shape = new long[]{4};\n      NDArray arr = NDArray.empty(shape, dev);\n      arr.copyFrom(new float[]{1f, 2f, 3f, 4f});\n\n      NDArray out = NDArray.empty(shape, dev);\n\n      graph.setInput(\"x\", arr).run();\n      graph.getOutput(0, out);\n\n      assertArrayEquals(new float[]{2f, 3f, 4f, 5f}, out.asFloatArray(), 1e-3f);\n\n      arr.release();\n      out.release();\n      graph.release();\n    } finally {\n      if (server != null) {\n        server.terminate();\n      }\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/java/org/apache/tvm/rpc/RPCTest.java",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.tvm.rpc;\n\nimport org.apache.tvm.Function;\nimport org.apache.tvm.Module;\nimport org.apache.tvm.TVMValue;\nimport org.apache.tvm.TestUtils;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class RPCTest {\n  private final Logger logger = LoggerFactory.getLogger(RPCTest.class);\n\n  @Test\n  public void test_addone() {\n    if (!Module.enabled(\"rpc\")) {\n      logger.warn(\"RPC is not enabled. Skip.\");\n      return;\n    }\n    Function.register(\"test.rpc.addone\", new Function.Callback() {\n        @Override public Object invoke(TVMValue... args) {\n          return args[0].asLong() + 1L;\n        }\n      });\n\n    TestUtils.RefInt port = new TestUtils.RefInt();\n    Server server = null;\n    try {\n      server = TestUtils.startServer(port);\n      RPCSession client = Client.connect(\"127.0.0.1\", port.value);\n      Function func = client.getFunction(\"test.rpc.addone\");\n      assertEquals(11L, func.call(10).asLong());\n    } finally {\n      if (server != null) {\n        server.terminate();\n      }\n    }\n  }\n\n  @Test\n  public void test_strcat() {\n    if (!Module.enabled(\"rpc\")) {\n      logger.warn(\"RPC is not enabled. Skip.\");\n      return;\n    }\n    Function.register(\"test.rpc.strcat\", new Function.Callback() {\n      @Override public Object invoke(TVMValue... args) {\n        return args[0].asString() + \":\" + args[1].asLong();\n      }\n    });\n\n    TestUtils.RefInt port = new TestUtils.RefInt();\n    Server server = null;\n    try {\n      server = TestUtils.startServer(port);\n      RPCSession client = Client.connect(\"127.0.0.1\", port.value);\n      Function func = client.getFunction(\"test.rpc.strcat\");\n      assertEquals(\"abc:11\", func.call(\"abc\", 11L).asString());\n    } finally {\n      if (server != null) {\n        server.terminate();\n      }\n    }\n  }\n\n  @Ignore(\"Proxy server may not have been ready when this test runs,\"\n        + \" will add retry when callback function can deal with Java exception.\"\n        + \" After that we'll enable this test.\")\n  @Test\n  public void test_connect_proxy_server() {\n    String proxyHost = System.getProperty(\"test.rpc.proxy.host\");\n    int proxyPort = Integer.parseInt(System.getProperty(\"test.rpc.proxy.port\"));\n\n    Function.register(\"test.rpc.proxy.addone\", new Function.Callback() {\n      @Override public Object invoke(TVMValue... tvmValues) {\n        return tvmValues[0].asLong() + 1L;\n      }\n    });\n\n    Server server = null;\n    try {\n      server = new Server(proxyHost, proxyPort, \"x1\");\n      server.start();\n\n      RPCSession client = Client.connect(proxyHost, proxyPort, \"x1\");\n      Function f1 = client.getFunction(\"test.rpc.proxy.addone\");\n      assertEquals(11L, f1.call(10L).asLong());\n    } finally {\n      if (server != null) {\n        server.terminate();\n      }\n    }\n  }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/scripts/test_add_cpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cc, utils\n\n\ndef test_add(target_dir):\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n    fadd = tvm.build(s, [A, B, C], \"llvm\", name=\"myadd\")\n\n    fadd.save(os.path.join(target_dir, \"add_cpu.o\"))\n    cc.create_shared(\n        os.path.join(target_dir, \"add_cpu.so\"), [os.path.join(target_dir, \"add_cpu.o\")]\n    )\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) != 2:\n        sys.exit(-1)\n    test_add(sys.argv[1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/scripts/test_add_gpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cc, utils, nvcc\n\n\n@tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\ndef tvm_callback_cuda_compile(code):\n    ptx = nvcc.compile_cuda(code, target_format=\"ptx\")\n    return ptx\n\n\ndef test_add(target_dir):\n    if not tvm.runtime.enabled(\"cuda\"):\n        print(\"skip %s because cuda is not enabled...\" % __file__)\n        return\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n\n    s = te.create_schedule(C.op)\n\n    bx, tx = s[C].split(C.op.axis[0], factor=64)\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    fadd_cuda = tvm.build(s, [A, B, C], tvm.target.Target(\"cuda\", host=\"llvm\"), name=\"myadd\")\n\n    fadd_cuda.save(os.path.join(target_dir, \"add_cuda.o\"))\n    fadd_cuda.imported_modules[0].save(os.path.join(target_dir, \"add_cuda.ptx\"))\n    cc.create_shared(\n        os.path.join(target_dir, \"add_cuda.so\"), [os.path.join(target_dir, \"add_cuda.o\")]\n    )\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) != 2:\n        sys.exit(-1)\n    test_add(sys.argv[1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/scripts/test_graph_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\n\nimport tvm\nfrom tvm import te\nimport json\nfrom tvm.contrib import graph_executor\n\n\ndef dump_graph_lib(target_dir):\n    dim = 4\n    A = te.placeholder((dim,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    sched = te.create_schedule(B.op)\n\n    node0 = {\"op\": \"null\", \"name\": \"x\", \"inputs\": []}\n    node1 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"add\",\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\"func_name\": \"myadd\", \"flatten_data\": \"1\", \"num_inputs\": \"1\", \"num_outputs\": \"1\"},\n    }\n    nodes = [node0, node1]\n    arg_nodes = [0]\n    node_row_ptr = [0, 1, 2]\n    outputs = [[1, 0, 0]]\n    shape = (4,)\n    attrs = {\n        \"shape\": [\"list_shape\", [shape, shape]],\n        \"dltype\": [\"list_str\", [\"float32\", \"float32\"]],\n        \"storage_id\": [\"list_int\", [0, 1]],\n    }\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": outputs,\n        \"attrs\": attrs,\n    }\n\n    graph = json.dumps(graph)\n    mlib = tvm.build(sched, [A, B], \"llvm\", name=\"myadd\")\n\n    mlib.export_library(os.path.join(target_dir, \"graph_addone_lib.so\"))\n    with open(os.path.join(target_dir, \"graph_addone.json\"), \"w\") as fo:\n        fo.write(graph)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) != 2:\n        sys.exit(-1)\n    dump_graph_lib(sys.argv[1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/core/src/test/scripts/test_rpc_proxy_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport time\nfrom tvm.rpc import proxy\n\n\ndef start_proxy_server(port, timeout):\n    prox = proxy.Proxy(\"127.0.0.1\", port=port, port_end=port + 1)\n    if timeout > 0:\n        import time\n\n        time.sleep(timeout)\n        prox.terminate()\n    else:\n        prox.proc.join()\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) < 2:\n        sys.exit(-1)\n    port = int(sys.argv[1])\n    timeout = 0 if len(sys.argv) == 2 else float(sys.argv[2])\n    start_proxy_server(port, timeout)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "jvm/native/src/main/native/jni_helper_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file jni_helper_func.h\n * \\brief Helper functions for operating JVM objects\n */\n#include <jni.h>\n\n#ifndef TVM4J_JNI_MAIN_NATIVE_JNI_HELPER_FUNC_H_\n#define TVM4J_JNI_MAIN_NATIVE_JNI_HELPER_FUNC_H_\n\n// Helper functions for RefXXX getter & setter\njlong getLongField(JNIEnv* env, jobject obj) {\n  jclass refClass = env->FindClass(\"org/apache/tvm/Base$RefLong\");\n  jfieldID refFid = env->GetFieldID(refClass, \"value\", \"J\");\n  jlong ret = env->GetLongField(obj, refFid);\n  env->DeleteLocalRef(refClass);\n  return ret;\n}\n\njint getIntField(JNIEnv* env, jobject obj) {\n  jclass refClass = env->FindClass(\"org/apache/tvm/Base$RefInt\");\n  jfieldID refFid = env->GetFieldID(refClass, \"value\", \"I\");\n  jint ret = env->GetIntField(obj, refFid);\n  env->DeleteLocalRef(refClass);\n  return ret;\n}\n\nvoid setIntField(JNIEnv* env, jobject obj, jint value) {\n  jclass refClass = env->FindClass(\"org/apache/tvm/Base$RefInt\");\n  jfieldID refFid = env->GetFieldID(refClass, \"value\", \"I\");\n  env->SetIntField(obj, refFid, value);\n  env->DeleteLocalRef(refClass);\n}\n\nvoid setLongField(JNIEnv* env, jobject obj, jlong value) {\n  jclass refClass = env->FindClass(\"org/apache/tvm/Base$RefLong\");\n  jfieldID refFid = env->GetFieldID(refClass, \"value\", \"J\");\n  env->SetLongField(obj, refFid, value);\n  env->DeleteLocalRef(refClass);\n}\n\nvoid setStringField(JNIEnv* env, jobject obj, const char* value) {\n  jclass refClass = env->FindClass(\"org/apache/tvm/Base$RefString\");\n  jfieldID refFid = env->GetFieldID(refClass, \"value\", \"Ljava/lang/String;\");\n  env->SetObjectField(obj, refFid, env->NewStringUTF(value));\n  env->DeleteLocalRef(refClass);\n}\n\n// Helper functions for TVMValue\njlong getTVMValueLongField(JNIEnv* env, jobject obj,\n                           const char* clsname = \"org/apache/tvm/TVMValueLong\") {\n  jclass cls = env->FindClass(clsname);\n  jfieldID fid = env->GetFieldID(cls, \"value\", \"J\");\n  jlong ret = env->GetLongField(obj, fid);\n  env->DeleteLocalRef(cls);\n  return ret;\n}\n\njdouble getTVMValueDoubleField(JNIEnv* env, jobject obj) {\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueDouble\");\n  jfieldID fid = env->GetFieldID(cls, \"value\", \"D\");\n  jdouble ret = env->GetDoubleField(obj, fid);\n  env->DeleteLocalRef(cls);\n  return ret;\n}\n\njstring getTVMValueStringField(JNIEnv* env, jobject obj) {\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueString\");\n  jfieldID fid = env->GetFieldID(cls, \"value\", \"Ljava/lang/String;\");\n  jstring ret = static_cast<jstring>(env->GetObjectField(obj, fid));\n  env->DeleteLocalRef(cls);\n  return ret;\n}\n\njobject newTVMValueHandle(JNIEnv* env, jlong value) {\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueHandle\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n  jobject object = env->NewObject(cls, constructor, value);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newTVMValueLong(JNIEnv* env, jlong value) {\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueLong\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n  jobject object = env->NewObject(cls, constructor, value);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newTVMValueDouble(JNIEnv* env, jdouble value) {\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueDouble\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(D)V\");\n  jobject object = env->NewObject(cls, constructor, value);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newTVMValueString(JNIEnv* env, const char* value) {\n  jstring jvalue = env->NewStringUTF(value);\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueString\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(Ljava/lang/String;)V\");\n  jobject object = env->NewObject(cls, constructor, jvalue);\n  env->DeleteLocalRef(cls);\n  env->DeleteLocalRef(jvalue);\n  return object;\n}\n\njobject newTVMValueBytes(JNIEnv* env, const TVMByteArray* arr) {\n  jbyteArray jarr = env->NewByteArray(arr->size);\n  env->SetByteArrayRegion(jarr, 0, arr->size,\n                          reinterpret_cast<jbyte*>(const_cast<char*>(arr->data)));\n  jclass cls = env->FindClass(\"org/apache/tvm/TVMValueBytes\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"([B)V\");\n  jobject object = env->NewObject(cls, constructor, jarr);\n  env->DeleteLocalRef(cls);\n  env->DeleteLocalRef(jarr);\n  return object;\n}\n\njobject newModule(JNIEnv* env, jlong value) {\n  jclass cls = env->FindClass(\"org/apache/tvm/Module\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n  jobject object = env->NewObject(cls, constructor, value);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newFunction(JNIEnv* env, jlong value) {\n  jclass cls = env->FindClass(\"org/apache/tvm/Function\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n  jobject object = env->NewObject(cls, constructor, value);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newNDArray(JNIEnv* env, jlong handle, jboolean isview) {\n  jclass cls = env->FindClass(\"org/apache/tvm/NDArrayBase\");\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(JZ)V\");\n  jobject object = env->NewObject(cls, constructor, handle, isview);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\njobject newObject(JNIEnv* env, const char* clsname) {\n  jclass cls = env->FindClass(clsname);\n  jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"()V\");\n  jobject object = env->NewObject(cls, constructor);\n  env->DeleteLocalRef(cls);\n  return object;\n}\n\nvoid fromJavaDType(JNIEnv* env, jobject jdtype, DLDataType* dtype) {\n  jclass tvmTypeClass = env->FindClass(\"org/apache/tvm/DLDataType\");\n  dtype->code = (uint8_t)(env->GetIntField(jdtype, env->GetFieldID(tvmTypeClass, \"typeCode\", \"I\")));\n  dtype->bits = (uint8_t)(env->GetIntField(jdtype, env->GetFieldID(tvmTypeClass, \"bits\", \"I\")));\n  dtype->lanes = (uint16_t)(env->GetIntField(jdtype, env->GetFieldID(tvmTypeClass, \"lanes\", \"I\")));\n  env->DeleteLocalRef(tvmTypeClass);\n}\n\nvoid fromJavaDevice(JNIEnv* env, jobject jdev, DLDevice* dev) {\n  jclass deviceClass = env->FindClass(\"org/apache/tvm/Device\");\n  dev->device_type = static_cast<DLDeviceType>(\n      env->GetIntField(jdev, env->GetFieldID(deviceClass, \"deviceType\", \"I\")));\n  dev->device_id =\n      static_cast<int>(env->GetIntField(jdev, env->GetFieldID(deviceClass, \"deviceId\", \"I\")));\n  env->DeleteLocalRef(deviceClass);\n}\n\njobject tvmRetValueToJava(JNIEnv* env, TVMValue value, int tcode) {\n  switch (tcode) {\n    case kDLUInt:\n    case kDLInt:\n      return newTVMValueLong(env, static_cast<jlong>(value.v_int64));\n    case kDLFloat:\n      return newTVMValueDouble(env, static_cast<jdouble>(value.v_float64));\n    case kTVMOpaqueHandle:\n      return newTVMValueHandle(env, reinterpret_cast<jlong>(value.v_handle));\n    case kTVMModuleHandle:\n      return newModule(env, reinterpret_cast<jlong>(value.v_handle));\n    case kTVMPackedFuncHandle:\n      return newFunction(env, reinterpret_cast<jlong>(value.v_handle));\n    case kTVMDLTensorHandle:\n      return newNDArray(env, reinterpret_cast<jlong>(value.v_handle), true);\n    case kTVMNDArrayHandle:\n      return newNDArray(env, reinterpret_cast<jlong>(value.v_handle), false);\n    case kTVMStr:\n      return newTVMValueString(env, value.v_str);\n    case kTVMBytes:\n      return newTVMValueBytes(env, reinterpret_cast<TVMByteArray*>(value.v_handle));\n    case kTVMNullptr:\n      return newObject(env, \"org/apache/tvm/TVMValueNull\");\n    default:\n      LOG(FATAL) << \"Do NOT know how to handle return type code \" << tcode;\n  }\n  return NULL;\n}\n\n#endif  // TVM4J_JNI_MAIN_NATIVE_JNI_HELPER_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/gen_requirements.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"TVM Python requirements.txt generator.\n\nThis script generates a set of requirements.txt files (stored in `./requirements`) that describe\nTVM's Python dependencies.\n\n## Pieces\n\nTVM can be roughly broken into these named pieces along the lines of Python dependencies:\n\n- \"core\": A core piece, which is intended to be buildable with very few external dependencies. Users\n  can use Relay, compile models, and run autotuning with this part.\n- \"importer-<tool>\": Model importers, which convert models defined in various other tools (i.e.\n  TensorFlow, PyTorch, etc) into Relay models.\n- Extra features (i.e. XGBoost in AutoTVM). These enhance TVM's functionality, but aren't required\n  for basic operation.\n\n## What this tool does\n\nFrom these pieces, this tool builds:\n - requirements/<name>.txt - Python dependencies for each named piece above, `<name>` is the same as\n   the quoted piece name.\n - requirements/all.txt - Consolidated Python dependencies for all pieces, excluding dev below.\n - requirements/dev.txt - Python dependencies needed to develop TVM, such as lint and test tools.\n\nThe data representing each piece is contained in the two maps below.\n\"\"\"\n\nimport argparse\nimport collections\nimport os\nimport re\nimport textwrap\nimport sys\nimport typing\n\n\nRequirementsByPieceType = typing.List[typing.Tuple[str, typing.Tuple[str, typing.List[str]]]]\n\n\n# Maps named TVM piece (see description above) to a list of names of Python packages. Please use\n# alphabetical order for each package list, and do not add version constraints here!\nREQUIREMENTS_BY_PIECE: RequirementsByPieceType = [\n    # Base requirements needed to install tvm.\n    (\n        \"core\",\n        (\n            \"Base requirements needed to install tvm\",\n            [\n                \"attrs\",\n                \"cloudpickle\",\n                \"decorator\",\n                \"numpy\",\n                \"psutil\",\n                \"scipy\",\n                \"synr\",\n                \"tornado\",\n            ],\n        ),\n    ),\n    # Provide support for Arm(R) Ethos(TM)-U NPU.\n    (\n        \"ethosu\",\n        (\n            \"Requirements for using Arm(R) Ethos(TM)-U NPU\",\n            [\n                \"ethos-u-vela\",\n            ],\n        ),\n    ),\n    # Relay frontends.\n    (\n        \"importer-caffe\",\n        (\n            \"Requirements for the Caffe importer\",\n            [\n                \"numpy\",\n                \"protobuf\",\n                \"scikit-image\",\n                \"six\",\n            ],\n        ),\n    ),\n    (\n        \"importer-caffe2\",\n        (\n            \"Requirements for the Caffe2 importer\",\n            [\n                \"future\",  # Hidden dependency of torch.\n                \"torch\",\n            ],\n        ),\n    ),\n    (\"importer-coreml\", (\"Requirements for the CoreML importer\", [\"coremltools\"])),\n    (\"importer-darknet\", (\"Requirements for the DarkNet importer\", [\"opencv-python\"])),\n    (\n        \"importer-keras\",\n        (\"Requirements for the Keras importer\", [\"tensorflow\", \"tensorflow-estimator\"]),\n    ),\n    (\n        \"importer-onnx\",\n        (\n            \"Requirements for the ONNX importer\",\n            [\n                \"future\",  # Hidden dependency of torch.\n                \"onnx\",\n                \"onnxoptimizer\",\n                \"onnxruntime\",\n                \"torch\",\n                \"torchvision\",\n            ],\n        ),\n    ),\n    (\n        \"importer-paddle\",\n        (\"Requirements for the PaddlePaddle importer\", [\"paddlepaddle\"]),\n    ),\n    (\n        \"importer-pytorch\",\n        (\n            \"Requirements for the PyTorch importer\",\n            [\n                \"future\",  # Hidden dependency of torch.\n                \"torch\",\n                \"torchvision\",\n            ],\n        ),\n    ),\n    (\n        \"importer-tensorflow\",\n        (\"Requirements for the TensorFlow importer\", [\"tensorflow\", \"tensorflow-estimator\"]),\n    ),\n    (\n        \"importer-tflite\",\n        (\"Requirements for the TFLite importer\", [\"tensorflow\", \"tensorflow-estimator\", \"tflite\"]),\n    ),\n    (\n        \"tvmc\",\n        (\n            \"Requirements for the tvmc command-line tool\",\n            [\n                \"ethos-u-vela\",\n                \"future\",  # Hidden dependency of torch.\n                \"onnx\",\n                \"onnxoptimizer\",\n                \"onnxruntime\",\n                \"paddlepaddle\",\n                \"tensorflow\",\n                \"tflite\",\n                \"torch\",\n                \"torchvision\",\n                \"xgboost\",\n            ],\n        ),\n    ),\n    # Vitis AI requirements\n    (\n        \"vitis-ai\",\n        (\n            \"Requirements for the Vitis AI codegen\",\n            [\n                \"h5py\",\n                \"progressbar\",\n            ],\n        ),\n    ),\n    # XGBoost, useful for autotuning on some targets.\n    (\n        \"xgboost\",\n        (\n            \"Requirements for XGBoost autotuning\",\n            [\n                \"future\",  # Hidden dependency of torch.\n                \"torch\",\n                \"xgboost\",\n            ],\n        ),\n    ),\n    # Development requirements\n    (\n        \"dev\",\n        (\n            \"Requirements to develop TVM -- lint, docs, testing, etc.\",\n            [\n                \"astroid\",  # pylint requirement, listed so a hard constraint can be included.\n                \"autodocsumm\",\n                \"black\",\n                \"commonmark\",\n                \"cpplint\",\n                \"docutils\",\n                \"image\",\n                \"matplotlib\",\n                \"pillow\",\n                \"pylint\",\n                \"sphinx\",\n                \"sphinx_autodoc_annotation\",\n                \"sphinx_gallery\",\n                \"sphinx_rtd_theme\",\n                \"types-psutil\",\n            ],\n        ),\n    ),\n]\n\nConstraintsType = typing.List[typing.Tuple[str, typing.Union[None, str]]]\n\n# Maps a named Python package (which should appear in REQUIREMENTS_BY_PIECE above) to a\n# semver or pip version constraint. Semver constraints are translated into requirements.txt-friendly\n# constraints.\n#\n# These constraints serve only to record technical reasons why a particular version can't be used.\n# They are the default install_requires used in setup.py. These can be further narrowed to restrict\n# dependencies to those tested or used in CI; however, that process is not done here.\n#\n# Policy for constraints listed here:\n# 1. Each package specified in REQUIREMENTS_BY_PIECE must be included here.\n# 2. If TVM will functionally break against an old version of a dependency, specify a >= relation\n#    here. Include a comment linking to context or explaining why the constraint is in place.\nCONSTRAINTS = [\n    (\"astroid\", None),\n    (\"attrs\", None),\n    (\"autodocsumm\", None),\n    (\"black\", \"==20.8b1\"),\n    (\"cloudpickle\", None),\n    (\"commonmark\", \">=0.7.3\"),  # From PR #213.\n    (\"coremltools\", None),\n    (\"cpplint\", None),\n    (\"decorator\", None),\n    (\n        \"docutils\",\n        \"<0.17\",\n    ),  # Work around https://github.com/readthedocs/sphinx_rtd_theme/issues/1115\n    (\"ethos-u-vela\", \"==3.2.0\"),\n    (\"future\", None),\n    (\"h5py\", \"==2.10.0\"),\n    (\"image\", None),\n    (\"matplotlib\", None),\n    (\"numpy\", None),\n    (\"onnx\", None),\n    (\"onnxoptimizer\", None),\n    (\"onnxruntime\", None),\n    (\"opencv-python\", None),\n    (\"paddlepaddle\", None),\n    (\"pillow\", None),\n    (\"progressbar\", None),\n    (\"protobuf\", None),\n    (\"psutil\", None),\n    (\"pylint\", None),\n    (\"scikit-image\", None),\n    (\"scipy\", None),\n    (\"six\", None),\n    (\"sphinx\", None),\n    (\"sphinx_autodoc_annotation\", None),\n    (\"sphinx_gallery\", None),\n    (\"sphinx_rtd_theme\", None),\n    (\"synr\", \"==0.6.0\"),\n    (\"tensorflow\", None),\n    (\"tensorflow-estimator\", None),\n    (\"tflite\", None),\n    (\"torch\", None),\n    (\"torchvision\", None),\n    (\"tornado\", None),\n    (\"xgboost\", \">=1.1.0,<1.6.0\"),  # From PR #4953 & Issue #12009\n]\n\n################################################################################\n# End of configuration options.\n################################################################################\n\n\n# Required keys in REQUIREMENTS_BY_PIECE.\nREQUIRED_PIECES: typing.List[str] = [\"core\", \"dev\"]\n\n# Regex to validates piece names.\nPIECE_REGEX: typing.Pattern = re.compile(r\"^[a-z0-9][a-z0-9-]*\", re.IGNORECASE)\n\n# Regex to match a constraint specification. Multiple constraints are not supported.\nCONSTRAINT_REGEX: typing.Pattern = re.compile(r\"(?:\\^|\\<|(?:~=)|(?:<=)|(?:==)|(?:>=)|\\>)[^<>=\\^,]+\")\n\n# Regex for parsing semantic versions. See\n# https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nSEMVER_REGEX: typing.Pattern = re.compile(\n    r\"^(?P<major>0|[1-9]\\d*)\\.(?P<minor>0|[1-9]\\d*)\\.(?P<patch>0|[1-9]\\d*)(?:-(?P<prerelease>(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$\"\n)\n\n\ndef validate_requirements_by_piece() -> typing.List[str]:\n    \"\"\"Validate REQUIREMENTS_BY_PIECE, returning a list of problems.\n\n    Returns\n    -------\n    list[str] :\n        A list of strings, each one describing a distinct problem with REQUIREMENTS_BY_PIECE.\n    \"\"\"\n    problems = []\n\n    unseen_required_pieces = set(REQUIRED_PIECES)\n    seen_pieces = set()\n\n    # Ensure that core is listed first and dev is listed last.\n    saw_core = False\n    saw_dev = False\n\n    if not isinstance(REQUIREMENTS_BY_PIECE, (list, tuple)):\n        problems.append(f\"must be list or tuple, see {REQUIREMENTS_BY_PIECE!r}\")\n        return problems\n\n    for piece, value in REQUIREMENTS_BY_PIECE:\n        if not isinstance(piece, str):\n            problems.append(f\"piece {piece!r}: must be str\")\n            continue\n\n        if piece in unseen_required_pieces:\n            unseen_required_pieces.remove(piece)\n\n        piece_lower = piece.lower()\n        if piece_lower in seen_pieces:\n            problems.append(f\"piece {piece}: listed twice\")\n\n        seen_pieces.add(piece_lower)\n\n        if not saw_core and piece != \"core\":\n            problems.append(f'piece {piece}: must list after \"core\" (core must be first)')\n        elif piece == \"core\":\n            saw_core = True\n\n        if saw_dev:\n            problems.append(f'piece {piece}: must list before \"dev\" (dev must be last)')\n        elif piece == \"dev\":\n            saw_dev = True\n\n        if not isinstance(value, (tuple, list)) or len(value) != 2:\n            problems.append(\n                f'piece {piece}: should be formatted like (\"{piece}\", (\"<requirements.txt comment>\", [\"dep1\", \"dep2\", ...])). got: {value!r}'\n            )\n            continue\n\n        description, deps = value\n\n        if not isinstance(description, str):\n            problems.append(f\"piece {piece}: description should be a string, got {description!r}\")\n\n        if not isinstance(deps, (list, tuple)) or any(not isinstance(d, str) for d in deps):\n            problems.append(f\"piece {piece}: deps should be a list of strings, got {deps!r}\")\n            continue\n\n        if list(sorted(deps)) != list(deps):\n            problems.append(\n                f\"piece {piece}: deps must be sorted. Correct order:\\n  {list(sorted(deps))!r}\"\n            )\n\n        piece_deps = set()\n        for d in deps:\n            if CONSTRAINT_REGEX.search(d):\n                problems.append(\n                    f\"piece {piece}: dependency {d} should not specify a version. \"\n                    \"Add it to CONSTRAINTS instead.\"\n                )\n\n            if d.lower() in piece_deps:\n                problems.append(f\"piece {piece}: dependency {d} listed twice\")\n\n            piece_deps.add(d.lower())\n\n    extras_pieces = [\n        k for (k, _) in REQUIREMENTS_BY_PIECE if k not in (\"dev\", \"core\") if isinstance(k, str)\n    ]\n    sorted_extras_pieces = list(sorted(extras_pieces))\n    if sorted_extras_pieces != list(extras_pieces):\n        problems.append(\n            'pieces other than \"core\" and \"dev\" must appear in alphabetical order: '\n            f\"{sorted_extras_pieces}\"\n        )\n\n    return problems\n\n\ndef parse_semver(\n    package: str, constraint: str, problems: typing.List[str]\n) -> typing.Tuple[typing.List[str], int, int]:\n    \"\"\"Parse a semantic versioning constraint of the form \"^X.[.Y[.Z[...]]]]\"\n\n    Parameters\n    ----------\n    package : str\n        Name of the package specifying this constraint, for reporting problems.\n    constraint : str\n        The semver constraint. Must start with \"^\"\n    problems : List[str]\n        A list of strings describing problems that have occurred validating the configuration.\n        Problems encountered while validating constraint are appended to this list.\n\n    Returns\n    -------\n    tuple[list[str], int, int] :\n        A 3-tuple. The first element is a list containing an entry for each component in the\n        semver string (components separated by \".\"). The second element is the index of the\n        component in the list which must not change to meet the semver constraint. The third element\n        is an integer, the numeric value of the changing component (this can be non-trivial when\n        the patch is the changing part but pre-, post-release, or build metadta.\n\n        See \"Caret requirements\" at https://python-poetry.org/docs/versions/.\n    \"\"\"\n    m = SEMVER_REGEX.match(constraint[1:])\n    if not m:\n        problems.append(f\"{package}: invalid semver constraint {constraint}\")\n        return [], 0, 0\n\n    min_ver_parts = [\n        m.group(\"major\"),\n        m.group(\"minor\"),\n        m.group(\"patch\")\n        + (f\"-{m.group('prerelease')}\" if m.group(\"prerelease\") else \"\")\n        + (f\"+{m.group('buildmetadata')}\" if m.group(\"buildmetadata\") else \"\"),\n    ]\n\n    # Major/minor version handling is simple\n    for i, p in enumerate(min_ver_parts[:2]):\n        x = int(p.strip())\n        if x:\n            return min_ver_parts, i, x\n\n    # For patch version, consult only the numeric patch\n    if m.group(\"patch\"):\n        patch_int = int(m.group(\"patch\"))\n        if patch_int or min_ver_parts[2] != m.group(\"patch\"):\n            return min_ver_parts, 2, patch_int\n\n    # All 0's\n    return min_ver_parts, 0, 0\n\n\ndef validate_constraints() -> typing.List[str]:\n    \"\"\"Validate CONSTRAINTS, returning a list of problems found.\n\n    Returns\n    -------\n    list[str] :\n        A list of strings, each one describing a distinct problem found in CONSTRAINTS.\n    \"\"\"\n    problems = []\n\n    if not isinstance(CONSTRAINTS, (list, tuple)):\n        problems.append(f\"must be list or tuple, see: {CONSTRAINTS!r}\")\n\n    seen_packages = set()\n    all_deps = set()\n    for _, (_, deps) in REQUIREMENTS_BY_PIECE:\n        for d in deps:\n            all_deps.add(d.lower())\n\n    for package, constraint in CONSTRAINTS:\n        if package in seen_packages:\n            problems.append(f\"{package}: specified twice\")\n        seen_packages.add(package)\n\n        if package.lower() not in all_deps:\n            problems.append(f\"{package}: not specified in REQUIREMENTS_BY_PIECE\")\n\n        if constraint is None:  # None is just a placeholder that allows for comments.\n            continue\n\n        if not CONSTRAINT_REGEX.match(constraint):\n            problems.append(\n                f'{package}: constraint \"{constraint}\" does not look like a valid constraint'\n            )\n\n        if constraint.startswith(\"^\"):\n            parse_semver(package, constraint, problems)\n\n    all_constrained_packages = [p for (p, _) in CONSTRAINTS]\n    sorted_constrained_packages = list(sorted(all_constrained_packages))\n    if sorted_constrained_packages != all_constrained_packages:\n        problems.append(\n            \"CONSTRAINTS entries should be in this sorted order: \" f\"{sorted_constrained_packages}\"\n        )\n\n    return problems\n\n\nclass ValidationError(Exception):\n    \"\"\"Raised when a validation error occurs.\"\"\"\n\n    @staticmethod\n    def format_problems(config: str, problems: typing.List[str]) -> str:\n        \"\"\"Format a list of problems with a global config variable into human-readable output.\n\n        Parameters\n        ----------\n        config : str\n            Name of the global configuration variable of concern. Prepended to the output.\n        problems: list[str]\n            A list of strings, each one a distinct problem with that config variable.\n\n        Returns\n        -------\n        str :\n            A human-readable string suitable for console, listing the problems as bullet points.\n        \"\"\"\n        formatted = []\n        for p in problems:\n            assert isinstance(p, str), f\"problems element not a str: {p}\"\n            formatted.append(\n                \"\\n\".join(\n                    textwrap.wrap(\n                        f\"{config}: {p}\", width=80, initial_indent=\" * \", subsequent_indent=\"   \"\n                    )\n                )\n            )\n\n        return \"\\n\".join(formatted)\n\n    def __init__(self, config: str, problems: typing.List[str]):\n        \"\"\"Describes an error that occurs validating one of the global config variables.\n\n        Parameters\n        ----------\n        config : str\n            Name of the global configuration variable of concern. Prepended to the output.\n        problems: list[str]\n            A list of strings, each one a distinct problem with that config variable.\n        \"\"\"\n        super(ValidationError, self).__init__(self.format_problems(config, problems))\n        self.problems = problems\n\n\ndef validate_or_raise():\n    problems = validate_requirements_by_piece()\n    if problems:\n        raise ValidationError(\"REQUIREMENTS_BY_PIECE\", problems)\n\n    problems = validate_constraints()\n    if problems:\n        raise ValidationError(\"CONSTRAINTS\", problems)\n\n\ndef semver_to_requirements(dep: str, constraint: str, joined_deps: typing.List[str]):\n    \"\"\"Convert a SemVer-style constraint to a setuptools-compatible constraint.\n\n    Parameters\n    ----------\n    dep : str\n        Name of the PyPI package to depend on.\n    constraint : str\n        The SemVer constraint, of the form \"^<semver constraint>\"\n    joined_deps : list[str]\n        A list of strings, each a setuptools-compatible constraint which could be written to\n        a line in requirements.txt. The converted constraint is appended to this list.\n    \"\"\"\n    problems: typing.List[str] = []\n    min_ver_parts, fixed_index, fixed_part = parse_semver(dep, constraint, problems)\n    text_problems = \"\\n\" + \"\\n\".join(f\" * {p}\" for p in problems)\n    assert (\n        not problems\n    ), f\"should not happen: validated semver {constraint} parses with problems:{text_problems}\"\n\n    max_ver_parts = (\n        min_ver_parts[:fixed_index]\n        + [str(fixed_part + 1)]\n        + [\"0\" for _ in min_ver_parts[fixed_index + 1 :]]\n    )\n    joined_deps.append(f'{dep}>={\".\".join(min_ver_parts)},<{\".\".join(max_ver_parts)}')\n\n\ndef join_requirements() -> typing.Dict[str, typing.Tuple[str, typing.List[str]]]:\n    \"\"\"Validate, then join REQUIRMENTS_BY_PIECE against CONSTRAINTS and return the result.\n\n    Returns\n    -------\n    An OrderedDict containing REQUIREMENTS_BY_PIECE, except any dependency mentioned in CONSTRAINTS\n    is replaced by a setuptools-compatible constraint.\n    \"\"\"\n    validate_or_raise()\n\n    constraints_map = collections.OrderedDict([(p.lower(), c) for (p, c) in CONSTRAINTS])\n\n    to_return = collections.OrderedDict()\n    all_deps = set()\n    for piece, (description, deps) in REQUIREMENTS_BY_PIECE:\n        joined_deps = []\n        for d in deps:\n            constraint = constraints_map.get(d.lower())\n            if constraint is None:\n                joined_deps.append(d)\n                continue\n\n            if constraint[0] == \"^\":\n                semver_to_requirements(d, constraint, joined_deps)\n            else:\n                joined_deps.append(f\"{d}{constraint}\")\n\n        if piece != \"dev\":\n            all_deps.update(joined_deps)\n\n        to_return[piece] = (description, joined_deps)\n\n    to_return[\"all-prod\"] = (\n        \"Combined dependencies for all TVM pieces, excluding dev\",\n        list(sorted(all_deps)),\n    )\n\n    return to_return\n\n\ndef join_and_write_requirements(args: argparse.Namespace):\n    try:\n        joined_deps = join_requirements()\n    except ValidationError as e:\n        print(f\"ERROR: invalid requirements configuration in {__file__}:\", file=sys.stderr)\n        print(str(e), file=sys.stderr)\n        sys.exit(2)\n\n    if args.lint:\n        sys.exit(0)\n\n    output_dir = os.path.join(os.path.dirname(__file__), \"requirements\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    elif not os.path.isdir(output_dir):\n        print(\n            f\"ERROR: output directory {output_dir} exists but is not a dir. Delete it\",\n            file=sys.stderr,\n        )\n        sys.exit(2)\n\n    for piece, (description, deps) in joined_deps.items():\n        with open(os.path.join(output_dir, f\"{piece}.txt\"), \"w\") as f:\n            f.write(\n                f\"# AUTOGENERATED by python/gen_requirements.py{os.linesep}\"\n                f\"#{os.linesep}\"\n                f\"# {description}{os.linesep}\"\n            )\n            for d in deps:\n                f.write(f\"{d}{os.linesep}\")\n\n\ndef parse_args() -> argparse.Namespace:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--lint\", action=\"store_true\", help=\"Just lint dependencies, don't generate anything\"\n    )\n    return parser.parse_args()\n\n\ndef main():\n    args = parse_args()\n    join_and_write_requirements(args)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/setup.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, exec-used\n\"\"\"Setup TVM package.\"\"\"\nimport os\nimport shutil\nimport sys\nimport sysconfig\nimport pathlib\nimport platform\n\nfrom setuptools import find_packages\nfrom setuptools.dist import Distribution\n\n# need to use distutils.core for correct placement of cython dll\nif \"--inplace\" in sys.argv:\n    from distutils.core import setup\n    from distutils.extension import Extension\nelse:\n    from setuptools import setup\n    from setuptools.extension import Extension\n\nCURRENT_DIR = os.path.dirname(__file__)\nFFI_MODE = os.environ.get(\"TVM_FFI\", \"auto\")\nCONDA_BUILD = os.getenv(\"CONDA_BUILD\") is not None\n\n\ndef get_lib_path():\n    \"\"\"Get library path, name and version\"\"\"\n    # We can not import `libinfo.py` in setup.py directly since __init__.py\n    # Will be invoked which introduces dependencies\n    libinfo_py = os.path.join(CURRENT_DIR, \"./tvm/_ffi/libinfo.py\")\n    libinfo = {\"__file__\": libinfo_py}\n    exec(compile(open(libinfo_py, \"rb\").read(), libinfo_py, \"exec\"), libinfo, libinfo)\n    version = libinfo[\"__version__\"]\n    if not CONDA_BUILD:\n        lib_path = libinfo[\"find_lib_path\"]()\n        libs = [lib_path[0]]\n        if \"runtime\" not in libs[0]:\n            for name in lib_path[1:]:\n                if \"runtime\" in name:\n                    libs.append(name)\n                    break\n\n        # Add standalone_crt, if present\n        for name in lib_path:\n            candidate_path = os.path.join(os.path.dirname(name), \"standalone_crt\")\n            if os.path.isdir(candidate_path):\n                libs.append(candidate_path)\n                break\n\n        # Add microTVM template projects\n        for name in lib_path:\n            candidate_path = os.path.join(os.path.dirname(name), \"microtvm_template_projects\")\n            if os.path.isdir(candidate_path):\n                libs.append(candidate_path)\n                break\n\n        # Add tvmc configuration json files\n        for name in lib_path:\n            candidate_path = os.path.abspath(os.path.join(os.path.dirname(name), \"..\", \"configs\"))\n            if os.path.isdir(candidate_path):\n                libs.append(candidate_path)\n                break\n\n    else:\n        libs = None\n\n    return libs, version\n\n\ndef git_describe_version(original_version):\n    \"\"\"Get git describe version.\"\"\"\n    ver_py = os.path.join(CURRENT_DIR, \"..\", \"version.py\")\n    libver = {\"__file__\": ver_py}\n    exec(compile(open(ver_py, \"rb\").read(), ver_py, \"exec\"), libver, libver)\n    _, gd_version = libver[\"git_describe_version\"]()\n    if gd_version != original_version and \"--inplace\" not in sys.argv:\n        print(\"Use git describe based version %s\" % gd_version)\n    return gd_version\n\n\nLIB_LIST, __version__ = get_lib_path()\n__version__ = git_describe_version(__version__)\n\n\ndef config_cython():\n    \"\"\"Try to configure cython and return cython configuration\"\"\"\n    if FFI_MODE not in (\"cython\"):\n        if os.name == \"nt\" and not CONDA_BUILD:\n            print(\"WARNING: Cython is not supported on Windows, will compile without cython module\")\n            return []\n        sys_cflags = sysconfig.get_config_var(\"CFLAGS\")\n        if sys_cflags and \"i386\" in sys_cflags and \"x86_64\" in sys_cflags:\n            print(\"WARNING: Cython library may not be compiled correctly with both i386 and x64\")\n            return []\n    try:\n        from Cython.Build import cythonize\n\n        # from setuptools.extension import Extension\n        if sys.version_info >= (3, 0):\n            subdir = \"_cy3\"\n        else:\n            subdir = \"_cy2\"\n        ret = []\n        path = \"tvm/_ffi/_cython\"\n        extra_compile_args = [\"-std=c++17\", \"-DDMLC_USE_LOGGING_LIBRARY=<tvm/runtime/logging.h>\"]\n        if os.name == \"nt\":\n            library_dirs = [\"tvm\", \"../build/Release\", \"../build\"]\n            libraries = [\"tvm\"]\n            extra_compile_args = [\n                \"/std:c++17\",\n                \"/D DMLC_USE_LOGGING_LIBRARY=<tvm/runtime/logging.h>\",\n            ]\n            # library is available via conda env.\n            if CONDA_BUILD:\n                library_dirs = [os.environ[\"LIBRARY_LIB\"]]\n        else:\n            library_dirs = None\n            libraries = None\n\n        for fn in os.listdir(path):\n            if not fn.endswith(\".pyx\"):\n                continue\n            ret.append(\n                Extension(\n                    \"tvm._ffi.%s.%s\" % (subdir, fn[:-4]),\n                    [\"tvm/_ffi/_cython/%s\" % fn],\n                    include_dirs=[\n                        \"../include/\",\n                        \"../3rdparty/dmlc-core/include\",\n                        \"../3rdparty/dlpack/include\",\n                    ],\n                    extra_compile_args=extra_compile_args,\n                    library_dirs=library_dirs,\n                    libraries=libraries,\n                    language=\"c++\",\n                )\n            )\n        return cythonize(ret, compiler_directives={\"language_level\": 3})\n    except ImportError as error:\n        if FFI_MODE == \"cython\":\n            raise error\n        print(\"WARNING: Cython is not installed, will compile without cython module\")\n        return []\n\n\nclass BinaryDistribution(Distribution):\n    def has_ext_modules(self):\n        return True\n\n    def is_pure(self):\n        return False\n\n\nsetup_kwargs = {}\nif not CONDA_BUILD:\n    with open(\"MANIFEST.in\", \"w\") as fo:\n        for path in LIB_LIST:\n            if os.path.isfile(path):\n                shutil.copy(path, os.path.join(CURRENT_DIR, \"tvm\"))\n                _, libname = os.path.split(path)\n                fo.write(f\"include tvm/{libname}\\n\")\n\n            if os.path.isdir(path):\n                _, libname = os.path.split(path)\n                shutil.copytree(path, os.path.join(CURRENT_DIR, \"tvm\", libname))\n                fo.write(f\"recursive-include tvm/{libname} *\\n\")\n\n    setup_kwargs = {\"include_package_data\": True}\n\n\ndef get_package_data_files():\n    # Relay standard libraries\n    return [\"relay/std/prelude.rly\", \"relay/std/core.rly\"]\n\n\ndef long_description_contents():\n    with open(pathlib.Path(CURRENT_DIR).resolve().parent / \"README.md\", encoding=\"utf-8\") as readme:\n        description = readme.read()\n\n    return description\n\n\n# Temporarily add this directory to the path so we can import the requirements generator\n# tool.\nsys.path.insert(0, os.path.dirname(__file__))\nimport gen_requirements\n\nsys.path.pop(0)\n\nrequirements = gen_requirements.join_requirements()\nextras_require = {\n    piece: deps for piece, (_, deps) in requirements.items() if piece not in (\"all\", \"core\")\n}\n\nsetup(\n    name=\"tvm\",\n    version=__version__,\n    description=\"TVM: An End to End Tensor IR/DSL Stack for Deep Learning Systems\",\n    long_description=long_description_contents(),\n    long_description_content_type=\"text/markdown\",\n    url=\"https://tvm.apache.org/\",\n    download_url=\"https://github.com/apache/tvm/tags\",\n    author=\"Apache TVM\",\n    license=\"Apache\",\n    # See https://pypi.org/classifiers/\n    classifiers=[\n        \"License :: OSI Approved :: Apache Software License\",\n        \"Development Status :: 4 - Beta\",\n        \"Intended Audience :: Developers\",\n        \"Intended Audience :: Education\",\n        \"Intended Audience :: Science/Research\",\n    ],\n    keywords=\"machine learning\",\n    zip_safe=False,\n    entry_points={\"console_scripts\": [\"tvmc = tvm.driver.tvmc.main:main\"]},\n    install_requires=requirements[\"core\"][1],\n    extras_require=extras_require,\n    packages=find_packages(),\n    package_dir={\"tvm\": \"tvm\"},\n    package_data={\"tvm\": get_package_data_files()},\n    distclass=BinaryDistribution,\n    ext_modules=config_cython(),\n    **setup_kwargs,\n)\n\n\nif not CONDA_BUILD:\n    # Wheel cleanup\n    os.remove(\"MANIFEST.in\")\n    for path in LIB_LIST:\n        _, libname = os.path.split(path)\n        path_to_be_removed = f\"tvm/{libname}\"\n\n        if os.path.isfile(path_to_be_removed):\n            os.remove(path_to_be_removed)\n\n        if os.path.isdir(path_to_be_removed):\n            shutil.rmtree(path_to_be_removed)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"TVM: Open Deep Learning Compiler Stack.\"\"\"\nimport multiprocessing\nimport sys\nimport os\nimport traceback\n\n# top-level alias\n# tvm._ffi\nfrom ._ffi.base import TVMError, __version__, _RUNTIME_ONLY\n\nfrom ._ffi.runtime_ctypes import DataTypeCode, DataType\nfrom ._ffi import register_object, register_func, register_extension, get_global_func\n\n# top-level alias\n# tvm.runtime\nfrom .runtime.object import Object\nfrom .runtime.ndarray import device, cpu, cuda, gpu, opencl, cl, vulkan, metal, mtl\nfrom .runtime.ndarray import vpi, rocm, ext_dev, hexagon\nfrom .runtime import ndarray as nd\n\n# tvm.error\nfrom . import error\n\n# tvm.ir\nfrom .ir import IRModule\nfrom .ir import transform\nfrom .ir import instrument\nfrom .ir import container\nfrom .ir import PoolInfo\nfrom .ir import WorkspacePoolInfo\nfrom .ir import ConstantPoolInfo\nfrom .ir import PoolInfoProperties\nfrom .ir import WorkspaceMemoryPools\nfrom .ir import ConstantMemoryPools\nfrom . import ir\n\n# tvm.tir\nfrom . import tir\n\n# tvm.target\nfrom . import target\n\n# tvm.te\nfrom . import te\n\n# tvm.driver\nfrom .driver import build, lower\n\n# tvm.parser\nfrom . import parser\n\n# others\nfrom . import arith\n\n# support infra\nfrom . import support\n\n# Contrib initializers\nfrom .contrib import rocm as _rocm, nvcc as _nvcc, sdaccel as _sdaccel\n\nif not _RUNTIME_ONLY and support.libinfo().get(\"USE_MICRO\", \"OFF\") == \"ON\":\n    from . import micro\n\n# NOTE: This file should be python2 compatible so we can\n# raise proper error message when user run the package using\n# an older version of the python\n\n\ndef _should_print_backtrace():\n    in_pytest = \"PYTEST_CURRENT_TEST\" in os.environ\n    tvm_backtrace = os.environ.get(\"TVM_BACKTRACE\", \"0\")\n\n    try:\n        tvm_backtrace = bool(int(tvm_backtrace))\n    except ValueError:\n        raise ValueError(\n            \"invalid value for TVM_BACKTRACE {}, please set to 0 or 1.\".format(tvm_backtrace)\n        )\n\n    return in_pytest or tvm_backtrace\n\n\ndef tvm_wrap_excepthook(exception_hook):\n    \"\"\"Wrap given excepthook with TVM additional work.\"\"\"\n\n    def wrapper(exctype, value, trbk):\n        \"\"\"Clean subprocesses when TVM is interrupted.\"\"\"\n        if exctype is error.DiagnosticError and not _should_print_backtrace():\n            # TODO(@jroesch): consider moving to C++?\n            print(\"note: run with `TVM_BACKTRACE=1` environment variable to display a backtrace.\")\n        else:\n            exception_hook(exctype, value, trbk)\n\n        if hasattr(multiprocessing, \"active_children\"):\n            # pylint: disable=not-callable\n            for p in multiprocessing.active_children():\n                p.terminate()\n\n    return wrapper\n\n\nsys.excepthook = tvm_wrap_excepthook(sys.excepthook)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"C interfacing code.\n\nThis namespace contains everything that interacts with C code.\nMost TVM C related object are ctypes compatible, which means\nthey contains a handle field that is ctypes.c_void_p and can\nbe used via ctypes function calls.\n\nSome performance critical functions are implemented by cython\nand have a ctypes fallback implementation.\n\"\"\"\nfrom . import _pyversion\nfrom .base import register_error\nfrom .registry import register_object, register_func, register_extension\nfrom .registry import _init_api, get_global_func, get_object_type_index\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_ctypes/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"ctypes specific implementation of FFI\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_ctypes/ndarray.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Runtime NDArray api\"\"\"\nimport ctypes\nfrom ..base import _LIB, check_call, c_str\nfrom ..runtime_ctypes import TVMArrayHandle\nfrom .types import RETURN_SWITCH, C_TO_PY_ARG_SWITCH, _wrap_arg_func, _return_handle\n\n\nTVMPyCapsuleDestructor = ctypes.CFUNCTYPE(None, ctypes.c_void_p)\n_c_str_dltensor = c_str(\"dltensor\")\n_c_str_used_dltensor = c_str(\"used_dltensor\")\n\n\n# used for PyCapsule manipulation\nif hasattr(ctypes, \"pythonapi\"):\n    ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p\n    ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p\n    ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object\n\n\ndef _from_dlpack(dltensor):\n    dltensor = ctypes.py_object(dltensor)\n    if ctypes.pythonapi.PyCapsule_IsValid(dltensor, _c_str_dltensor):\n        ptr = ctypes.pythonapi.PyCapsule_GetPointer(dltensor, _c_str_dltensor)\n        # enforce type to make sure it works for all ctypes\n        ptr = ctypes.cast(ptr, ctypes.c_void_p)\n        handle = TVMArrayHandle()\n        check_call(_LIB.TVMArrayFromDLPack(ptr, ctypes.byref(handle)))\n        ctypes.pythonapi.PyCapsule_SetName(dltensor, _c_str_used_dltensor)\n        ctypes.pythonapi.PyCapsule_SetDestructor(dltensor, TVMPyCapsuleDestructor(0))\n        return _make_array(handle, False, False)\n    raise ValueError(\"Expect a dltensor field, PyCapsule can only be consumed once\")\n\n\ndef _dlpack_deleter(pycapsule):\n    pycapsule = ctypes.cast(pycapsule, ctypes.py_object)\n    if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor):\n        ptr = ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor)\n        # enforce type to make sure it works for all ctypes\n        ptr = ctypes.cast(ptr, ctypes.c_void_p)\n        _LIB.TVMDLManagedTensorCallDeleter(ptr)\n        ctypes.pythonapi.PyCapsule_SetDestructor(pycapsule, None)\n\n\n_c_dlpack_deleter = TVMPyCapsuleDestructor(_dlpack_deleter)\n\n\nclass NDArrayBase(object):\n    \"\"\"A simple Device/CPU Array object in runtime.\"\"\"\n\n    __slots__ = [\"handle\", \"is_view\"]\n    # pylint: disable=no-member\n    def __init__(self, handle, is_view=False):\n        \"\"\"Initialize the function with handle\n\n        Parameters\n        ----------\n        handle : TVMArrayHandle\n            the handle to the underlying C++ TVMArray\n        \"\"\"\n        self.handle = handle\n        self.is_view = is_view\n\n    def __del__(self):\n        if not self.is_view and _LIB:\n            check_call(_LIB.TVMArrayFree(self.handle))\n\n    @property\n    def _tvm_handle(self):\n        return ctypes.cast(self.handle, ctypes.c_void_p).value\n\n    def _copyto(self, target_nd):\n        \"\"\"Internal function that implements copy to target ndarray.\"\"\"\n        check_call(_LIB.TVMArrayCopyFromTo(self.handle, target_nd.handle, None))\n        return target_nd\n\n    @property\n    def shape(self):\n        \"\"\"Shape of this array\"\"\"\n        return tuple(self.handle.contents.shape[i] for i in range(self.handle.contents.ndim))\n\n    def to_dlpack(self):\n        \"\"\"Produce an array from a DLPack Tensor without copying memory\n\n        Returns\n        -------\n        dlpack : DLPack tensor view of the array data\n        \"\"\"\n        handle = ctypes.c_void_p()\n        check_call(_LIB.TVMArrayToDLPack(self.handle, ctypes.byref(handle)))\n        return ctypes.pythonapi.PyCapsule_New(handle, _c_str_dltensor, _c_dlpack_deleter)\n\n\ndef _make_array(handle, is_view, is_container):\n    global _TVM_ND_CLS\n    handle = ctypes.cast(handle, TVMArrayHandle)\n    if is_container:\n        tindex = ctypes.c_uint()\n        check_call(_LIB.TVMArrayGetTypeIndex(handle, ctypes.byref(tindex)))\n        cls = _TVM_ND_CLS.get(tindex.value, _CLASS_NDARRAY)\n    else:\n        cls = _CLASS_NDARRAY\n\n    ret = cls.__new__(cls)\n    ret.handle = handle\n    ret.is_view = is_view\n    return ret\n\n\n_TVM_COMPATS = ()\n\n\ndef _reg_extension(cls, fcreate):\n    global _TVM_COMPATS\n    _TVM_COMPATS += (cls,)\n    if fcreate:\n        fret = lambda x: fcreate(_return_handle(x))\n        RETURN_SWITCH[cls._tvm_tcode] = fret\n        C_TO_PY_ARG_SWITCH[cls._tvm_tcode] = _wrap_arg_func(fret, cls._tvm_tcode)\n\n\n_TVM_ND_CLS = {}\n\n\ndef _register_ndarray(index, cls):\n    global _TVM_ND_CLS\n    _TVM_ND_CLS[index] = cls\n\n\n_CLASS_NDARRAY = None\n\n\ndef _set_class_ndarray(cls):\n    global _CLASS_NDARRAY\n    _CLASS_NDARRAY = cls\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_ctypes/object.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Runtime Object api\"\"\"\nimport ctypes\nfrom ..base import _LIB, check_call\nfrom .types import ArgTypeCode, RETURN_SWITCH, C_TO_PY_ARG_SWITCH, _wrap_arg_func\nfrom .ndarray import _register_ndarray, NDArrayBase\n\n\nObjectHandle = ctypes.c_void_p\n__init_by_constructor__ = None\n\n\"\"\"Maps object type index to its constructor\"\"\"\nOBJECT_TYPE = {}\n\n\"\"\"Maps object type to its type index\"\"\"\nOBJECT_INDEX = {}\n\n_CLASS_OBJECT = None\n\n\ndef _set_class_object(object_class):\n    global _CLASS_OBJECT\n    _CLASS_OBJECT = object_class\n\n\ndef _register_object(index, cls):\n    \"\"\"register object class\"\"\"\n    if issubclass(cls, NDArrayBase):\n        _register_ndarray(index, cls)\n        return\n    OBJECT_TYPE[index] = cls\n    OBJECT_INDEX[cls] = index\n\n\ndef _get_object_type_index(cls):\n    \"\"\"get the type index of object class\"\"\"\n    return OBJECT_INDEX.get(cls)\n\n\ndef _return_object(x):\n    handle = x.v_handle\n    if not isinstance(handle, ObjectHandle):\n        handle = ObjectHandle(handle)\n    tindex = ctypes.c_uint()\n    check_call(_LIB.TVMObjectGetTypeIndex(handle, ctypes.byref(tindex)))\n    cls = OBJECT_TYPE.get(tindex.value, _CLASS_OBJECT)\n    if issubclass(cls, PyNativeObject):\n        obj = _CLASS_OBJECT.__new__(_CLASS_OBJECT)\n        obj.handle = handle\n        return cls.__from_tvm_object__(cls, obj)\n    # Avoid calling __init__ of cls, instead directly call __new__\n    # This allows child class to implement their own __init__\n    obj = cls.__new__(cls)\n    obj.handle = handle\n    return obj\n\n\nRETURN_SWITCH[ArgTypeCode.OBJECT_HANDLE] = _return_object\nC_TO_PY_ARG_SWITCH[ArgTypeCode.OBJECT_HANDLE] = _wrap_arg_func(\n    _return_object, ArgTypeCode.OBJECT_HANDLE\n)\n\nC_TO_PY_ARG_SWITCH[ArgTypeCode.OBJECT_RVALUE_REF_ARG] = _wrap_arg_func(\n    _return_object, ArgTypeCode.OBJECT_RVALUE_REF_ARG\n)\n\n\nclass PyNativeObject:\n    \"\"\"Base class of all TVM objects that also subclass python's builtin types.\"\"\"\n\n    __slots__ = []\n\n    def __init_tvm_object_by_constructor__(self, fconstructor, *args):\n        \"\"\"Initialize the internal tvm_object by calling constructor function.\n\n        Parameters\n        ----------\n        fconstructor : Function\n            Constructor function.\n\n        args: list of objects\n            The arguments to the constructor\n\n        Note\n        ----\n        We have a special calling convention to call constructor functions.\n        So the return object is directly set into the object\n        \"\"\"\n        # pylint: disable=assigning-non-slot\n        obj = _CLASS_OBJECT.__new__(_CLASS_OBJECT)\n        obj.__init_handle_by_constructor__(fconstructor, *args)\n        self.__tvm_object__ = obj\n\n\nclass ObjectBase(object):\n    \"\"\"Base object for all object types\"\"\"\n\n    __slots__ = [\"handle\"]\n\n    def __del__(self):\n        if _LIB is not None:\n            try:\n                handle = self.handle\n            except AttributeError:\n                return\n\n            check_call(_LIB.TVMObjectFree(handle))\n\n    def __init_handle_by_constructor__(self, fconstructor, *args):\n        \"\"\"Initialize the handle by calling constructor function.\n\n        Parameters\n        ----------\n        fconstructor : Function\n            Constructor function.\n\n        args: list of objects\n            The arguments to the constructor\n\n        Note\n        ----\n        We have a special calling convention to call constructor functions.\n        So the return handle is directly set into the Node object\n        instead of creating a new Node.\n        \"\"\"\n        # assign handle first to avoid error raising\n        # pylint: disable=not-callable\n        self.handle = None\n        handle = __init_by_constructor__(fconstructor, args)\n        if not isinstance(handle, ObjectHandle):\n            handle = ObjectHandle(handle)\n        self.handle = handle\n\n    def same_as(self, other):\n        \"\"\"Check object identity.\n\n        Parameters\n        ----------\n        other : object\n            The other object to compare against.\n\n        Returns\n        -------\n        result : bool\n             The comparison result.\n        \"\"\"\n        if not isinstance(other, ObjectBase):\n            return False\n        if self.handle is None:\n            return other.handle is None\n        return self.handle.value == other.handle.value\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_ctypes/packed_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# coding: utf-8\n# pylint: disable=invalid-name, protected-access, too-many-branches, global-statement, unused-import\n\"\"\"Function configuration API.\"\"\"\nimport ctypes\nimport traceback\nfrom numbers import Number, Integral\n\nfrom ..base import _LIB, get_last_ffi_error, py2cerror, check_call\nfrom ..base import c_str, string_types\nfrom ..runtime_ctypes import DataType, TVMByteArray, Device, ObjectRValueRef\nfrom . import ndarray as _nd\nfrom .ndarray import NDArrayBase, _make_array\nfrom .types import TVMValue, ArgTypeCode\nfrom .types import TVMPackedCFunc, TVMCFuncFinalizer\nfrom .types import RETURN_SWITCH, C_TO_PY_ARG_SWITCH, _wrap_arg_func, _device_to_int64\nfrom .object import ObjectBase, PyNativeObject, _set_class_object\nfrom . import object as _object\n\nPackedFuncHandle = ctypes.c_void_p\nModuleHandle = ctypes.c_void_p\nObjectHandle = ctypes.c_void_p\nTVMRetValueHandle = ctypes.c_void_p\n\n\ndef _ctypes_free_resource(rhandle):\n    \"\"\"callback to free resources when it is not needed.\"\"\"\n    pyobj = ctypes.cast(rhandle, ctypes.py_object)\n    ctypes.pythonapi.Py_DecRef(pyobj)\n\n\n# Global callback that is always alive\nTVM_FREE_PYOBJ = TVMCFuncFinalizer(_ctypes_free_resource)\nctypes.pythonapi.Py_IncRef(ctypes.py_object(TVM_FREE_PYOBJ))\n\n\ndef _make_packed_func(handle, is_global):\n    \"\"\"Make a packed function class\"\"\"\n    obj = _CLASS_PACKED_FUNC.__new__(_CLASS_PACKED_FUNC)\n    obj.is_global = is_global\n    obj.handle = handle\n    return obj\n\n\ndef convert_to_tvm_func(pyfunc):\n    \"\"\"Convert a python function to TVM function\n\n    Parameters\n    ----------\n    pyfunc : python function\n        The python function to be converted.\n\n    Returns\n    -------\n    tvmfunc: tvm.nd.Function\n        The converted tvm function.\n    \"\"\"\n    local_pyfunc = pyfunc\n\n    def cfun(args, type_codes, num_args, ret, _):\n        \"\"\"ctypes function\"\"\"\n        num_args = num_args.value if isinstance(num_args, ctypes.c_int) else num_args\n        pyargs = (C_TO_PY_ARG_SWITCH[type_codes[i]](args[i]) for i in range(num_args))\n        # pylint: disable=broad-except\n        try:\n            rv = local_pyfunc(*pyargs)\n        except Exception:\n            msg = traceback.format_exc()\n            msg = py2cerror(msg)\n            _LIB.TVMAPISetLastError(c_str(msg))\n            return -1\n\n        if rv is not None:\n            if isinstance(rv, tuple):\n                raise ValueError(\"PackedFunction can only support one return value\")\n            temp_args = []\n            values, tcodes, _ = _make_tvm_args((rv,), temp_args)\n            if not isinstance(ret, TVMRetValueHandle):\n                ret = TVMRetValueHandle(ret)\n            if _LIB.TVMCFuncSetReturn(ret, values, tcodes, ctypes.c_int(1)) != 0:\n                raise get_last_ffi_error()\n            _ = temp_args\n            _ = rv\n        return 0\n\n    handle = PackedFuncHandle()\n    f = TVMPackedCFunc(cfun)\n    # NOTE: We will need to use python-api to increase ref count of the f\n    # TVM_FREE_PYOBJ will be called after it is no longer needed.\n    pyobj = ctypes.py_object(f)\n    ctypes.pythonapi.Py_IncRef(pyobj)\n    if _LIB.TVMFuncCreateFromCFunc(f, pyobj, TVM_FREE_PYOBJ, ctypes.byref(handle)) != 0:\n        raise get_last_ffi_error()\n    return _make_packed_func(handle, False)\n\n\ndef _make_tvm_args(args, temp_args):\n    \"\"\"Pack arguments into c args tvm call accept\"\"\"\n    num_args = len(args)\n    values = (TVMValue * num_args)()\n    type_codes = (ctypes.c_int * num_args)()\n    for i, arg in enumerate(args):\n        if isinstance(arg, ObjectBase):\n            values[i].v_handle = arg.handle\n            type_codes[i] = ArgTypeCode.OBJECT_HANDLE\n        elif arg is None:\n            values[i].v_handle = None\n            type_codes[i] = ArgTypeCode.NULL\n        elif isinstance(arg, NDArrayBase):\n            values[i].v_handle = ctypes.cast(arg.handle, ctypes.c_void_p)\n            type_codes[i] = (\n                ArgTypeCode.NDARRAY_HANDLE if not arg.is_view else ArgTypeCode.DLTENSOR_HANDLE\n            )\n        elif isinstance(arg, PyNativeObject):\n            values[i].v_handle = arg.__tvm_object__.handle\n            type_codes[i] = ArgTypeCode.OBJECT_HANDLE\n        elif isinstance(arg, _nd._TVM_COMPATS):\n            values[i].v_handle = ctypes.c_void_p(arg._tvm_handle)\n            type_codes[i] = arg.__class__._tvm_tcode\n        elif isinstance(arg, Integral):\n            values[i].v_int64 = arg\n            type_codes[i] = ArgTypeCode.INT\n        elif isinstance(arg, Number):\n            values[i].v_float64 = arg\n            type_codes[i] = ArgTypeCode.FLOAT\n        elif isinstance(arg, DataType):\n            values[i].v_str = c_str(str(arg))\n            type_codes[i] = ArgTypeCode.STR\n        elif isinstance(arg, Device):\n            values[i].v_int64 = _device_to_int64(arg)\n            type_codes[i] = ArgTypeCode.DLDEVICE\n        elif isinstance(arg, (bytearray, bytes)):\n            # from_buffer only taeks in bytearray.\n            if isinstance(arg, bytes):\n                byte_arr = bytearray(arg)\n                temp_args.append(byte_arr)\n                arg = byte_arr\n\n            arr = TVMByteArray()\n            arr.data = ctypes.cast(\n                (ctypes.c_byte * len(arg)).from_buffer(arg), ctypes.POINTER(ctypes.c_byte)\n            )\n            arr.size = len(arg)\n            values[i].v_handle = ctypes.c_void_p(ctypes.addressof(arr))\n            temp_args.append(arr)\n            type_codes[i] = ArgTypeCode.BYTES\n        elif isinstance(arg, string_types):\n            values[i].v_str = c_str(arg)\n            type_codes[i] = ArgTypeCode.STR\n        elif isinstance(arg, (list, tuple, dict, _CLASS_OBJECT_GENERIC)):\n            arg = _FUNC_CONVERT_TO_OBJECT(arg)\n            values[i].v_handle = arg.handle\n            type_codes[i] = ArgTypeCode.OBJECT_HANDLE\n            temp_args.append(arg)\n        elif isinstance(arg, _CLASS_MODULE):\n            values[i].v_handle = arg.handle\n            type_codes[i] = ArgTypeCode.MODULE_HANDLE\n        elif isinstance(arg, PackedFuncBase):\n            values[i].v_handle = arg.handle\n            type_codes[i] = ArgTypeCode.PACKED_FUNC_HANDLE\n        elif isinstance(arg, ctypes.c_void_p):\n            values[i].v_handle = arg\n            type_codes[i] = ArgTypeCode.HANDLE\n        elif isinstance(arg, ObjectRValueRef):\n            values[i].v_handle = ctypes.cast(ctypes.byref(arg.obj.handle), ctypes.c_void_p)\n            type_codes[i] = ArgTypeCode.OBJECT_RVALUE_REF_ARG\n        elif callable(arg):\n            arg = convert_to_tvm_func(arg)\n            values[i].v_handle = arg.handle\n            type_codes[i] = ArgTypeCode.PACKED_FUNC_HANDLE\n            temp_args.append(arg)\n        else:\n            raise TypeError(\"Don't know how to handle type %s\" % type(arg))\n    return values, type_codes, num_args\n\n\nclass PackedFuncBase(object):\n    \"\"\"Function base.\"\"\"\n\n    __slots__ = [\"handle\", \"is_global\"]\n    # pylint: disable=no-member\n    def __init__(self, handle, is_global):\n        \"\"\"Initialize the function with handle\n\n        Parameters\n        ----------\n        handle : PackedFuncHandle\n            the handle to the underlying function.\n\n        is_global : bool\n            Whether this is a global function in python\n        \"\"\"\n        self.handle = handle\n        self.is_global = is_global\n\n    def __del__(self):\n        if not self.is_global and _LIB is not None:\n            if _LIB.TVMFuncFree(self.handle) != 0:\n                raise get_last_ffi_error()\n\n    def __call__(self, *args):\n        \"\"\"Call the function with positional arguments\n\n        args : list\n           The positional arguments to the function call.\n        \"\"\"\n        temp_args = []\n        values, tcodes, num_args = _make_tvm_args(args, temp_args)\n        ret_val = TVMValue()\n        ret_tcode = ctypes.c_int()\n        if (\n            _LIB.TVMFuncCall(\n                self.handle,\n                values,\n                tcodes,\n                ctypes.c_int(num_args),\n                ctypes.byref(ret_val),\n                ctypes.byref(ret_tcode),\n            )\n            != 0\n        ):\n            raise get_last_ffi_error()\n        _ = temp_args\n        _ = args\n        return RETURN_SWITCH[ret_tcode.value](ret_val)\n\n\ndef __init_handle_by_constructor__(fconstructor, args):\n    \"\"\"Initialize handle by constructor\"\"\"\n    temp_args = []\n    values, tcodes, num_args = _make_tvm_args(args, temp_args)\n    ret_val = TVMValue()\n    ret_tcode = ctypes.c_int()\n    if (\n        _LIB.TVMFuncCall(\n            fconstructor.handle,\n            values,\n            tcodes,\n            ctypes.c_int(num_args),\n            ctypes.byref(ret_val),\n            ctypes.byref(ret_tcode),\n        )\n        != 0\n    ):\n        raise get_last_ffi_error()\n    _ = temp_args\n    _ = args\n    assert ret_tcode.value == ArgTypeCode.OBJECT_HANDLE\n    handle = ret_val.v_handle\n    return handle\n\n\ndef _return_module(x):\n    \"\"\"Return function\"\"\"\n    handle = x.v_handle\n    if not isinstance(handle, ModuleHandle):\n        handle = ModuleHandle(handle)\n    return _CLASS_MODULE(handle)\n\n\ndef _handle_return_func(x):\n    \"\"\"Return function\"\"\"\n    handle = x.v_handle\n    if not isinstance(handle, PackedFuncHandle):\n        handle = PackedFuncHandle(handle)\n    return _CLASS_PACKED_FUNC(handle, False)\n\n\ndef _get_global_func(name, allow_missing=False):\n    handle = PackedFuncHandle()\n    check_call(_LIB.TVMFuncGetGlobal(c_str(name), ctypes.byref(handle)))\n\n    if handle.value:\n        return _make_packed_func(handle, False)\n\n    if allow_missing:\n        return None\n\n    raise ValueError(\"Cannot find global function %s\" % name)\n\n\n# setup return handle for function type\n_object.__init_by_constructor__ = __init_handle_by_constructor__\nRETURN_SWITCH[ArgTypeCode.PACKED_FUNC_HANDLE] = _handle_return_func\nRETURN_SWITCH[ArgTypeCode.MODULE_HANDLE] = _return_module\nRETURN_SWITCH[ArgTypeCode.NDARRAY_HANDLE] = lambda x: _make_array(x.v_handle, False, True)\nC_TO_PY_ARG_SWITCH[ArgTypeCode.PACKED_FUNC_HANDLE] = _wrap_arg_func(\n    _handle_return_func, ArgTypeCode.PACKED_FUNC_HANDLE\n)\nC_TO_PY_ARG_SWITCH[ArgTypeCode.MODULE_HANDLE] = _wrap_arg_func(\n    _return_module, ArgTypeCode.MODULE_HANDLE\n)\nC_TO_PY_ARG_SWITCH[ArgTypeCode.DLTENSOR_HANDLE] = lambda x: _make_array(x.v_handle, True, False)\nC_TO_PY_ARG_SWITCH[ArgTypeCode.NDARRAY_HANDLE] = _wrap_arg_func(\n    lambda x: _make_array(x.v_handle, False, True), ArgTypeCode.NDARRAY_HANDLE\n)\n\n_CLASS_MODULE = None\n_CLASS_PACKED_FUNC = None\n_CLASS_OBJECT_GENERIC = None\n_FUNC_CONVERT_TO_OBJECT = None\n\n\ndef _set_class_module(module_class):\n    \"\"\"Initialize the module.\"\"\"\n    global _CLASS_MODULE\n    _CLASS_MODULE = module_class\n\n\ndef _set_class_packed_func(packed_func_class):\n    global _CLASS_PACKED_FUNC\n    _CLASS_PACKED_FUNC = packed_func_class\n\n\ndef _set_class_object_generic(object_generic_class, func_convert_to_object):\n    global _CLASS_OBJECT_GENERIC\n    global _FUNC_CONVERT_TO_OBJECT\n    _CLASS_OBJECT_GENERIC = object_generic_class\n    _FUNC_CONVERT_TO_OBJECT = func_convert_to_object\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_ctypes/types.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The C Types used in API.\"\"\"\n# pylint: disable=invalid-name\nimport ctypes\nimport struct\nfrom ..base import py_str, check_call, _LIB\nfrom ..runtime_ctypes import TVMByteArray, ArgTypeCode, Device\n\n\nclass TVMValue(ctypes.Union):\n    \"\"\"TVMValue in C API\"\"\"\n\n    _fields_ = [\n        (\"v_int64\", ctypes.c_int64),\n        (\"v_float64\", ctypes.c_double),\n        (\"v_handle\", ctypes.c_void_p),\n        (\"v_str\", ctypes.c_char_p),\n    ]\n\n\nTVMPackedCFunc = ctypes.CFUNCTYPE(\n    ctypes.c_int,\n    ctypes.POINTER(TVMValue),\n    ctypes.POINTER(ctypes.c_int),\n    ctypes.c_int,\n    ctypes.c_void_p,\n    ctypes.c_void_p,\n)\n\n\nTVMCFuncFinalizer = ctypes.CFUNCTYPE(None, ctypes.c_void_p)\n\n\ndef _return_handle(x):\n    \"\"\"return handle\"\"\"\n    handle = x.v_handle\n    if not isinstance(handle, ctypes.c_void_p):\n        handle = ctypes.c_void_p(handle)\n    return handle\n\n\ndef _return_bytes(x):\n    \"\"\"return bytes\"\"\"\n    handle = x.v_handle\n    if not isinstance(handle, ctypes.c_void_p):\n        handle = ctypes.c_void_p(handle)\n    arr = ctypes.cast(handle, ctypes.POINTER(TVMByteArray))[0]\n    size = arr.size\n    res = bytearray(size)\n    rptr = (ctypes.c_byte * size).from_buffer(res)\n    if not ctypes.memmove(rptr, arr.data, size):\n        raise RuntimeError(\"memmove failed\")\n    return res\n\n\ndef _return_device(value):\n    \"\"\"return Device\"\"\"\n    # use bit unpacking from int64 view\n    # We use this to get around ctypes issue on Union of Structure\n    data = struct.pack(\"=q\", value.v_int64)\n    arr = struct.unpack(\"=ii\", data)\n    return Device(arr[0], arr[1])\n\n\ndef _wrap_arg_func(return_f, type_code):\n    def _wrap_func(x):\n        tcode = ctypes.c_int(type_code)\n        check_call(_LIB.TVMCbArgToReturn(ctypes.byref(x), ctypes.byref(tcode)))\n        return return_f(x)\n\n    return _wrap_func\n\n\ndef _device_to_int64(dev):\n    \"\"\"Pack context into int64 in native endian\"\"\"\n    data = struct.pack(\"=ii\", dev.device_type, dev.device_id)\n    return struct.unpack(\"=q\", data)[0]\n\n\nRETURN_SWITCH = {\n    ArgTypeCode.INT: lambda x: x.v_int64,\n    ArgTypeCode.FLOAT: lambda x: x.v_float64,\n    ArgTypeCode.HANDLE: _return_handle,\n    ArgTypeCode.NULL: lambda x: None,\n    ArgTypeCode.STR: lambda x: py_str(x.v_str),\n    ArgTypeCode.BYTES: _return_bytes,\n    ArgTypeCode.DLDEVICE: _return_device,\n}\n\nC_TO_PY_ARG_SWITCH = {\n    ArgTypeCode.INT: lambda x: x.v_int64,\n    ArgTypeCode.FLOAT: lambda x: x.v_float64,\n    ArgTypeCode.HANDLE: _return_handle,\n    ArgTypeCode.NULL: lambda x: None,\n    ArgTypeCode.STR: lambda x: py_str(x.v_str),\n    ArgTypeCode.BYTES: _return_bytes,\n    ArgTypeCode.DLDEVICE: _return_device,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_cy2/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"cython2 namespace\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_cy3/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"cython3 namespace\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/_pyversion.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Python version check\n\"\"\"\nimport sys\n\n# ----------------------------\n# Python3 version.\n# ----------------------------\nif not (sys.version_info[0] >= 3 and sys.version_info[1] >= 6):\n    PY3STATEMENT = \"The minimal Python requirement is Python 3.6\"\n    raise Exception(PY3STATEMENT)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# coding: utf-8\n# pylint: disable=invalid-name, import-outside-toplevel\n\"\"\"Base library for TVM FFI.\"\"\"\nimport sys\nimport os\nimport ctypes\nimport numpy as np\nfrom . import libinfo\n\n# ----------------------------\n# library loading\n# ----------------------------\nstring_types = (str,)\ninteger_types = (int, np.int32)\nnumeric_types = integer_types + (float, np.float16, np.float32)\n\n# this function is needed for python3\n# to convert ctypes.char_p .value back to python str\nif sys.platform == \"win32\":\n\n    def _py_str(x):\n        try:\n            return x.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            encoding = \"cp\" + str(ctypes.cdll.kernel32.GetACP())\n        return x.decode(encoding)\n\n    py_str = _py_str\nelse:\n    py_str = lambda x: x.decode(\"utf-8\")\n\n\ndef _load_lib():\n    \"\"\"Load libary by searching possible path.\"\"\"\n    lib_path = libinfo.find_lib_path()\n    # The dll search path need to be added explicitly in\n    # windows after python 3.8\n    if sys.platform.startswith(\"win32\") and sys.version_info >= (3, 8):\n        for path in libinfo.get_dll_directories():\n            os.add_dll_directory(path)\n    lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL)\n    lib.TVMGetLastError.restype = ctypes.c_char_p\n    return lib, os.path.basename(lib_path[0])\n\n\ntry:\n    # The following import is needed for TVM to work with pdb\n    import readline  # pylint: disable=unused-import\nexcept ImportError:\n    pass\n\n# version number\n__version__ = libinfo.__version__\n# library instance\n_LIB, _LIB_NAME = _load_lib()\n\n# Whether we are runtime only\n_RUNTIME_ONLY = \"runtime\" in _LIB_NAME\n\n# The FFI mode of TVM\n_FFI_MODE = os.environ.get(\"TVM_FFI\", \"auto\")\n\n\n# ----------------------------\n# helper function in ctypes.\n# ----------------------------\ndef c_str(string):\n    \"\"\"Create ctypes char * from a python string\n    Parameters\n    ----------\n    string : string type\n        python string\n\n    Returns\n    -------\n    str : c_char_p\n        A char pointer that can be passed to C API\n    \"\"\"\n    return ctypes.c_char_p(string.encode(\"utf-8\"))\n\n\ndef c_array(ctype, values):\n    \"\"\"Create ctypes array from a python array\n\n    Parameters\n    ----------\n    ctype : ctypes data type\n        data type of the array we want to convert to\n\n    values : tuple or list\n        data content\n\n    Returns\n    -------\n    out : ctypes array\n        Created ctypes array\n    \"\"\"\n    return (ctype * len(values))(*values)\n\n\ndef decorate(func, fwrapped):\n    \"\"\"A wrapper call of decorator package, differs to call time\n\n    Parameters\n    ----------\n    func : function\n        The original function\n\n    fwrapped : function\n        The wrapped function\n    \"\"\"\n    import decorator\n\n    return decorator.decorate(func, fwrapped)\n\n\n# -----------------------------------------\n# Base code for structured error handling.\n# -----------------------------------------\n# Maps error type to its constructor\nERROR_TYPE = {}\n\n\nclass TVMError(RuntimeError):\n    \"\"\"Default error thrown by TVM functions.\n\n    TVMError will be raised if you do not give any error type specification,\n    \"\"\"\n\n\ndef register_error(func_name=None, cls=None):\n    \"\"\"Register an error class so it can be recognized by the ffi error handler.\n\n    Parameters\n    ----------\n    func_name : str or function or class\n        The name of the error function.\n\n    cls : function\n        The function to create the class\n\n    Returns\n    -------\n    fregister : function\n        Register function if f is not specified.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      @tvm.error.register_error\n      class MyError(RuntimeError):\n          pass\n\n      err_inst = tvm.error.create_ffi_error(\"MyError: xyz\")\n      assert isinstance(err_inst, MyError)\n    \"\"\"\n    if callable(func_name):\n        cls = func_name\n        func_name = cls.__name__\n\n    def register(mycls):\n        \"\"\"internal register function\"\"\"\n        err_name = func_name if isinstance(func_name, str) else mycls.__name__\n        ERROR_TYPE[err_name] = mycls\n        return mycls\n\n    if cls is None:\n        return register\n    return register(cls)\n\n\ndef _valid_error_name(name):\n    \"\"\"Check whether name is a valid error name.\"\"\"\n    return all(x.isalnum() or x in \"_.\" for x in name)\n\n\ndef _find_error_type(line):\n    \"\"\"Find the error name given the first line of the error message.\n\n    Parameters\n    ----------\n    line : str\n        The first line of error message.\n\n    Returns\n    -------\n    name : str The error name\n    \"\"\"\n    if sys.platform == \"win32\":\n        # Stack traces aren't logged on Windows due to a DMLC limitation,\n        # so we should try to get the underlying error another way.\n        # DMLC formats errors \"[timestamp] file:line: ErrorMessage\"\n        # ErrorMessage is usually formatted \"ErrorType: message\"\n        # We can try to extract the error type using the final \":\"\n        end_pos = line.rfind(\":\")\n        if end_pos == -1:\n            return None\n        start_pos = line.rfind(\":\", 0, end_pos)\n        if start_pos == -1:\n            err_name = line[:end_pos].strip()\n        else:\n            err_name = line[start_pos + 1 : end_pos].strip()\n        if _valid_error_name(err_name):\n            return err_name\n        return None\n\n    end_pos = line.find(\":\")\n    if end_pos == -1:\n        return None\n    err_name = line[:end_pos]\n    if _valid_error_name(err_name):\n        return err_name\n    return None\n\n\ndef c2pyerror(err_msg):\n    \"\"\"Translate C API error message to python style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n\n    err_type : str\n        Detected error type.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    err_type = _find_error_type(arr[0])\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"        \") and len(stack_trace) > 0:\n                stack_trace[-1] += \"\\n\" + line\n            elif line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.startswith(\"Stack trace\"):\n                trace_mode = True\n            else:\n                message.append(line)\n    out_msg = \"\"\n    if stack_trace:\n        out_msg += \"Traceback (most recent call last):\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    out_msg += \"\\n\".join(message)\n    return out_msg, err_type\n\n\ndef py2cerror(err_msg):\n    \"\"\"Translate python style error message to C style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.find(\"Traceback\") != -1:\n                trace_mode = True\n            else:\n                message.append(line)\n    # Remove the first error name if there are two of them.\n    # RuntimeError: MyErrorName: message => MyErrorName: message\n    head_arr = message[0].split(\":\", 3)\n    if len(head_arr) >= 3 and _valid_error_name(head_arr[1].strip()):\n        head_arr[1] = head_arr[1].strip()\n        message[0] = \":\".join(head_arr[1:])\n    # reverse the stack trace.\n    out_msg = \"\\n\".join(message)\n    if stack_trace:\n        out_msg += \"\\nStack trace:\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    return out_msg\n\n\ndef get_last_ffi_error():\n    \"\"\"Create error object given result of TVMGetLastError.\n\n    Returns\n    -------\n    err : object\n        The error object based on the err_msg\n    \"\"\"\n    c_err_msg = py_str(_LIB.TVMGetLastError())\n    py_err_msg, err_type = c2pyerror(c_err_msg)\n    if err_type is not None and err_type.startswith(\"tvm.error.\"):\n        err_type = err_type[10:]\n    return ERROR_TYPE.get(err_type, TVMError)(py_err_msg)\n\n\ndef check_call(ret):\n    \"\"\"Check the return value of C API call\n\n    This function will raise exception when error occurs.\n    Wrap every API call with this function\n\n    Parameters\n    ----------\n    ret : int\n        return value from API calls\n    \"\"\"\n    if ret != 0:\n        raise get_last_ffi_error()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/libinfo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Library information.\"\"\"\nimport sys\nimport os\n\n\ndef split_env_var(env_var, split):\n    \"\"\"Splits environment variable string.\n\n    Parameters\n    ----------\n    env_var : str\n        Name of environment variable.\n\n    split : str\n        String to split env_var on.\n\n    Returns\n    -------\n    splits : list(string)\n        If env_var exists, split env_var. Otherwise, empty list.\n    \"\"\"\n    if os.environ.get(env_var, None):\n        return [p.strip() for p in os.environ[env_var].split(split)]\n    return []\n\n\ndef get_dll_directories():\n    \"\"\"Get the possible dll directories\"\"\"\n    # NB: This will either be the source directory (if TVM is run\n    # inplace) or the install directory (if TVM is installed).\n    # An installed TVM's curr_path will look something like:\n    #   $PREFIX/lib/python3.6/site-packages/tvm/_ffi\n    ffi_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n    source_dir = os.path.join(ffi_dir, \"..\", \"..\", \"..\")\n    install_lib_dir = os.path.join(ffi_dir, \"..\", \"..\", \"..\", \"..\")\n\n    dll_path = []\n\n    if os.environ.get(\"TVM_LIBRARY_PATH\", None):\n        dll_path.append(os.environ[\"TVM_LIBRARY_PATH\"])\n\n    if sys.platform.startswith(\"linux\") or sys.platform.startswith(\"freebsd\"):\n        dll_path.extend(split_env_var(\"LD_LIBRARY_PATH\", \":\"))\n        dll_path.extend(split_env_var(\"PATH\", \":\"))\n    elif sys.platform.startswith(\"darwin\"):\n        dll_path.extend(split_env_var(\"DYLD_LIBRARY_PATH\", \":\"))\n        dll_path.extend(split_env_var(\"PATH\", \":\"))\n    elif sys.platform.startswith(\"win32\"):\n        dll_path.extend(split_env_var(\"PATH\", \";\"))\n\n    # Pip lib directory\n    dll_path.append(os.path.join(ffi_dir, \"..\"))\n    # Default cmake build directory\n    dll_path.append(os.path.join(source_dir, \"build\"))\n    dll_path.append(os.path.join(source_dir, \"build\", \"Release\"))\n    # Default make build directory\n    dll_path.append(os.path.join(source_dir, \"lib\"))\n\n    dll_path.append(install_lib_dir)\n\n    if os.path.isdir(source_dir):\n        dll_path.append(os.path.join(source_dir, \"web\", \"dist\", \"wasm\"))\n        dll_path.append(os.path.join(source_dir, \"web\", \"dist\"))\n\n    dll_path = [os.path.realpath(x) for x in dll_path]\n    return [x for x in dll_path if os.path.isdir(x)]\n\n\ndef find_lib_path(name=None, search_path=None, optional=False):\n    \"\"\"Find dynamic library files.\n\n    Parameters\n    ----------\n    name : list of str\n        List of names to be found.\n\n    Returns\n    -------\n    lib_path : list(string)\n        List of all found path to the libraries\n    \"\"\"\n    use_runtime = os.environ.get(\"TVM_USE_RUNTIME_LIB\", False)\n    dll_path = get_dll_directories()\n\n    if search_path is not None:\n        if isinstance(search_path, list):\n            dll_path = dll_path + search_path\n        else:\n            dll_path.append(search_path)\n\n    if name is not None:\n        if isinstance(name, list):\n            lib_dll_path = []\n            for n in name:\n                lib_dll_path += [os.path.join(p, n) for p in dll_path]\n        else:\n            lib_dll_path = [os.path.join(p, name) for p in dll_path]\n        runtime_dll_path = []\n    else:\n        if sys.platform.startswith(\"win32\"):\n            lib_dll_names = [\"libtvm.dll\", \"tvm.dll\"]\n            runtime_dll_names = [\"libtvm_runtime.dll\", \"tvm_runtime.dll\"]\n        elif sys.platform.startswith(\"darwin\"):\n            lib_dll_names = [\"libtvm.dylib\"]\n            runtime_dll_names = [\"libtvm_runtime.dylib\"]\n        else:\n            lib_dll_names = [\"libtvm.so\"]\n            runtime_dll_names = [\"libtvm_runtime.so\"]\n\n        name = lib_dll_names + runtime_dll_names\n        lib_dll_path = [os.path.join(p, name) for name in lib_dll_names for p in dll_path]\n        runtime_dll_path = [os.path.join(p, name) for name in runtime_dll_names for p in dll_path]\n\n    if not use_runtime:\n        # try to find lib_dll_path\n        lib_found = [p for p in lib_dll_path if os.path.exists(p) and os.path.isfile(p)]\n        lib_found += [p for p in runtime_dll_path if os.path.exists(p) and os.path.isfile(p)]\n    else:\n        # try to find runtime_dll_path\n        use_runtime = True\n        lib_found = [p for p in runtime_dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n    if not lib_found:\n        if not optional:\n            message = (\n                f\"Cannot find libraries: {name}\\n\"\n                + \"List of candidates:\\n\"\n                + \"\\n\".join(lib_dll_path + runtime_dll_path)\n            )\n            raise RuntimeError(message)\n        return None\n\n    if use_runtime:\n        sys.stderr.write(\"Loading runtime library %s... exec only\\n\" % lib_found[0])\n        sys.stderr.flush()\n    return lib_found\n\n\ndef find_include_path(name=None, search_path=None, optional=False):\n    \"\"\"Find header files for C compilation.\n\n    Parameters\n    ----------\n    name : list of str\n        List of directory names to be searched.\n\n    Returns\n    -------\n    include_path : list(string)\n        List of all found paths to header files.\n    \"\"\"\n    ffi_dir = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    source_dir = os.path.join(ffi_dir, \"..\", \"..\", \"..\")\n\n    third_party_dir = os.path.join(source_dir, \"3rdparty\")\n\n    header_path = []\n\n    if os.environ.get(\"TVM_INCLUDE_PATH\", None):\n        header_path.append(os.environ[\"TVM_INCLUDE_PATH\"])\n\n    header_path.append(source_dir)\n    header_path.append(third_party_dir)\n\n    header_path = [os.path.abspath(x) for x in header_path]\n    if search_path is not None:\n        if isinstance(search_path, list):\n            header_path = header_path + search_path\n        else:\n            header_path.append(search_path)\n    if name is not None:\n        if isinstance(name, list):\n            tvm_include_path = []\n            for n in name:\n                tvm_include_path += [os.path.join(p, n) for p in header_path]\n        else:\n            tvm_include_path = [os.path.join(p, name) for p in header_path]\n        dlpack_include_path = []\n        dmlc_include_path = []\n    else:\n        tvm_include_path = [os.path.join(p, \"include\") for p in header_path]\n        dlpack_include_path = [os.path.join(p, \"dlpack/include\") for p in header_path]\n        dmlc_include_path = [os.path.join(p, \"dmlc-core/include\") for p in header_path]\n\n        # try to find include path\n        include_found = [p for p in tvm_include_path if os.path.exists(p) and os.path.isdir(p)]\n        include_found += [p for p in dlpack_include_path if os.path.exists(p) and os.path.isdir(p)]\n        include_found += [p for p in dmlc_include_path if os.path.exists(p) and os.path.isdir(p)]\n\n    if not include_found:\n        message = (\n            \"Cannot find the files.\\n\"\n            + \"List of candidates:\\n\"\n            + str(\"\\n\".join(tvm_include_path + dlpack_include_path))\n        )\n        if not optional:\n            raise RuntimeError(message)\n        return None\n\n    return include_found\n\n\n# current version\n# We use the version of the incoming release for code\n# that is under development.\n# The following line is set by tvm/python/update_version.py\n__version__ = \"0.11.dev0\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/registry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-import\n\"\"\"FFI registry to register function and objects.\"\"\"\nimport sys\nimport ctypes\n\nfrom .base import _LIB, check_call, py_str, c_str, string_types, _FFI_MODE, _RUNTIME_ONLY\n\ntry:\n    # pylint: disable=wrong-import-position,unused-import\n    if _FFI_MODE == \"ctypes\":\n        raise ImportError()\n    from ._cy3.core import _register_object, _get_object_type_index\n    from ._cy3.core import _reg_extension\n    from ._cy3.core import convert_to_tvm_func, _get_global_func, PackedFuncBase\nexcept (RuntimeError, ImportError) as error:\n    # pylint: disable=wrong-import-position,unused-import\n    if _FFI_MODE == \"cython\":\n        raise error\n    from ._ctypes.object import _register_object, _get_object_type_index\n    from ._ctypes.ndarray import _reg_extension\n    from ._ctypes.packed_func import convert_to_tvm_func, _get_global_func, PackedFuncBase\n\n\ndef register_object(type_key=None):\n    \"\"\"register object type.\n\n    Parameters\n    ----------\n    type_key : str or cls\n        The type key of the node\n\n    Examples\n    --------\n    The following code registers MyObject\n    using type key \"test.MyObject\"\n\n    .. code-block:: python\n\n      @tvm.register_object(\"test.MyObject\")\n      class MyObject(Object):\n          pass\n    \"\"\"\n    object_name = type_key if isinstance(type_key, str) else type_key.__name__\n\n    def register(cls):\n        \"\"\"internal register function\"\"\"\n        if hasattr(cls, \"_type_index\"):\n            tindex = cls._type_index\n        else:\n            tidx = ctypes.c_uint()\n            if not _RUNTIME_ONLY:\n                check_call(_LIB.TVMObjectTypeKey2Index(c_str(object_name), ctypes.byref(tidx)))\n            else:\n                # directly skip unknown objects during runtime.\n                ret = _LIB.TVMObjectTypeKey2Index(c_str(object_name), ctypes.byref(tidx))\n                if ret != 0:\n                    return cls\n            tindex = tidx.value\n        _register_object(tindex, cls)\n        return cls\n\n    if isinstance(type_key, str):\n        return register\n\n    return register(type_key)\n\n\ndef get_object_type_index(cls):\n    \"\"\"\n    Get type index of object type\n\n    Parameters\n    ----------\n    cls : type\n        The object type to get type index for.\n\n    Returns\n    -------\n    type_index : Optional[int]\n        The type index, or None if type not found in the registry.\n    \"\"\"\n    return _get_object_type_index(cls)\n\n\ndef register_extension(cls, fcreate=None):\n    \"\"\"Register a extension class to TVM.\n\n    After the class is registered, the class will be able\n    to directly pass as Function argument generated by TVM.\n\n    Parameters\n    ----------\n    cls : class\n        The class object to be registered as extension.\n\n    fcreate : function, optional\n        The creation function to create a class object given handle value.\n\n    Note\n    ----\n    The registered class is requires one property: _tvm_handle.\n\n    If the registered class is a subclass of NDArray,\n    it is required to have a class attribute _array_type_code.\n    Otherwise, it is required to have a class attribute _tvm_tcode.\n\n    - ```_tvm_handle``` returns integer represents the address of the handle.\n    - ```_tvm_tcode``` or ```_array_type_code``` gives integer represents type\n      code of the class.\n\n    Returns\n    -------\n    cls : class\n        The class being registered.\n\n    Example\n    -------\n    The following code registers user defined class\n    MyTensor to be DLTensor compatible.\n\n    .. code-block:: python\n\n       @tvm.register_extension\n       class MyTensor(object):\n           _tvm_tcode = tvm.ArgTypeCode.ARRAY_HANDLE\n\n           def __init__(self):\n               self.handle = _LIB.NewDLTensor()\n\n           @property\n           def _tvm_handle(self):\n               return self.handle.value\n    \"\"\"\n    assert hasattr(cls, \"_tvm_tcode\")\n    if fcreate:\n        raise ValueError(\"Extension with fcreate is no longer supported\")\n    _reg_extension(cls, fcreate)\n    return cls\n\n\ndef register_func(func_name, f=None, override=False):\n    \"\"\"Register global function\n\n    Parameters\n    ----------\n    func_name : str or function\n        The function name\n\n    f : function, optional\n        The function to be registered.\n\n    override: boolean optional\n        Whether override existing entry.\n\n    Returns\n    -------\n    fregister : function\n        Register function if f is not specified.\n\n    Examples\n    --------\n    The following code registers my_packed_func as global function.\n    Note that we simply get it back from global function table to invoke\n    it from python side. However, we can also invoke the same function\n    from C++ backend, or in the compiled TVM code.\n\n    .. code-block:: python\n\n      targs = (10, 10.0, \"hello\")\n      @tvm.register_func\n      def my_packed_func(*args):\n          assert(tuple(args) == targs)\n          return 10\n      # Get it out from global function table\n      f = tvm.get_global_func(\"my_packed_func\")\n      assert isinstance(f, tvm.PackedFunc)\n      y = f(*targs)\n      assert y == 10\n    \"\"\"\n    if callable(func_name):\n        f = func_name\n        func_name = f.__name__\n\n    if not isinstance(func_name, str):\n        raise ValueError(\"expect string function name\")\n\n    ioverride = ctypes.c_int(override)\n\n    def register(myf):\n        \"\"\"internal register function\"\"\"\n        if not isinstance(myf, PackedFuncBase):\n            myf = convert_to_tvm_func(myf)\n        check_call(_LIB.TVMFuncRegisterGlobal(c_str(func_name), myf.handle, ioverride))\n        return myf\n\n    if f:\n        return register(f)\n    return register\n\n\ndef get_global_func(name, allow_missing=False):\n    \"\"\"Get a global function by name\n\n    Parameters\n    ----------\n    name : str\n        The name of the global function\n\n    allow_missing : bool\n        Whether allow missing function or raise an error.\n\n    Returns\n    -------\n    func : PackedFunc\n        The function to be returned, None if function is missing.\n    \"\"\"\n    return _get_global_func(name, allow_missing)\n\n\ndef list_global_func_names():\n    \"\"\"Get list of global functions registered.\n\n    Returns\n    -------\n    names : list\n       List of global functions names.\n    \"\"\"\n    plist = ctypes.POINTER(ctypes.c_char_p)()\n    size = ctypes.c_uint()\n\n    check_call(_LIB.TVMFuncListGlobalNames(ctypes.byref(size), ctypes.byref(plist)))\n    fnames = []\n    for i in range(size.value):\n        fnames.append(py_str(plist[i]))\n    return fnames\n\n\ndef extract_ext_funcs(finit):\n    \"\"\"\n    Extract the extension PackedFuncs from a C module.\n\n    Parameters\n    ----------\n    finit : ctypes function\n        a ctypes that takes signature of TVMExtensionDeclarer\n\n    Returns\n    -------\n    fdict : dict of str to Function\n        The extracted functions\n    \"\"\"\n    fdict = {}\n\n    def _list(name, func):\n        fdict[name] = func\n\n    myf = convert_to_tvm_func(_list)\n    ret = finit(myf.handle)\n    _ = myf\n    if ret != 0:\n        raise RuntimeError(\"cannot initialize with %s\" % finit)\n    return fdict\n\n\ndef remove_global_func(name):\n    \"\"\"Remove a global function by name\n\n    Parameters\n    ----------\n    name : str\n        The name of the global function\n    \"\"\"\n    check_call(_LIB.TVMFuncRemoveGlobal(c_str(name)))\n\n\ndef _get_api(f):\n    flocal = f\n    flocal.is_global = True\n    return flocal\n\n\ndef _init_api(namespace, target_module_name=None):\n    \"\"\"Initialize api for a given module name\n\n    namespace : str\n       The namespace of the source registry\n\n    target_module_name : str\n       The target module name if different from namespace\n    \"\"\"\n    target_module_name = target_module_name if target_module_name else namespace\n    if namespace.startswith(\"tvm.\"):\n        _init_api_prefix(target_module_name, namespace[4:])\n    else:\n        _init_api_prefix(target_module_name, namespace)\n\n\ndef _init_api_prefix(module_name, prefix):\n    module = sys.modules[module_name]\n\n    for name in list_global_func_names():\n        if not name.startswith(prefix):\n            continue\n\n        fname = name[len(prefix) + 1 :]\n        target_module = module\n\n        if fname.find(\".\") != -1:\n            continue\n        f = get_global_func(name)\n        ff = _get_api(f)\n        ff.__name__ = fname\n        ff.__doc__ = \"TVM PackedFunc %s. \" % fname\n        setattr(target_module, ff.__name__, ff)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/_ffi/runtime_ctypes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common runtime ctypes.\"\"\"\n# pylint: disable=invalid-name\nimport ctypes\nimport json\nimport numpy as np\nfrom .base import _LIB, check_call\n\ntvm_shape_index_t = ctypes.c_int64\n\n\nclass ArgTypeCode(object):\n    \"\"\"Type code used in API calls\"\"\"\n\n    INT = 0\n    UINT = 1\n    FLOAT = 2\n    HANDLE = 3\n    NULL = 4\n    TVM_TYPE = 5\n    DLDEVICE = 6\n    DLTENSOR_HANDLE = 7\n    OBJECT_HANDLE = 8\n    MODULE_HANDLE = 9\n    PACKED_FUNC_HANDLE = 10\n    STR = 11\n    BYTES = 12\n    NDARRAY_HANDLE = 13\n    OBJECT_RVALUE_REF_ARG = 14\n    EXT_BEGIN = 15\n\n\nclass TVMByteArray(ctypes.Structure):\n    \"\"\"Temp data structure for byte array.\"\"\"\n\n    _fields_ = [(\"data\", ctypes.POINTER(ctypes.c_byte)), (\"size\", ctypes.c_size_t)]\n\n\nclass DataTypeCode(object):\n    \"\"\"DataType code in DLTensor.\"\"\"\n\n    INT = 0\n    UINT = 1\n    FLOAT = 2\n    HANDLE = 3\n    BFLOAT = 4\n\n\nclass DataType(ctypes.Structure):\n    \"\"\"TVM datatype structure\"\"\"\n\n    _fields_ = [(\"type_code\", ctypes.c_uint8), (\"bits\", ctypes.c_uint8), (\"lanes\", ctypes.c_uint16)]\n    CODE2STR = {\n        DataTypeCode.INT: \"int\",\n        DataTypeCode.UINT: \"uint\",\n        DataTypeCode.FLOAT: \"float\",\n        DataTypeCode.HANDLE: \"handle\",\n        DataTypeCode.BFLOAT: \"bfloat\",\n    }\n    NUMPY2STR = {\n        np.dtype(np.bool_): \"bool\",\n        np.dtype(np.int8): \"int8\",\n        np.dtype(np.int16): \"int16\",\n        np.dtype(np.int32): \"int32\",\n        np.dtype(np.int64): \"int64\",\n        np.dtype(np.uint8): \"uint8\",\n        np.dtype(np.uint16): \"uint16\",\n        np.dtype(np.uint32): \"uint32\",\n        np.dtype(np.uint64): \"uint64\",\n        np.dtype(np.float16): \"float16\",\n        np.dtype(np.float32): \"float32\",\n        np.dtype(np.float64): \"float64\",\n        np.dtype(np.float_): \"float64\",\n    }\n    STR2DTYPE = {\n        \"bool\": {\"type_code\": DataTypeCode.UINT, \"bits\": 1, \"lanes\": 1},\n        \"int8\": {\"type_code\": DataTypeCode.INT, \"bits\": 8, \"lanes\": 1},\n        \"int16\": {\"type_code\": DataTypeCode.INT, \"bits\": 16, \"lanes\": 1},\n        \"int32\": {\"type_code\": DataTypeCode.INT, \"bits\": 32, \"lanes\": 1},\n        \"int64\": {\"type_code\": DataTypeCode.INT, \"bits\": 64, \"lanes\": 1},\n        \"uint8\": {\"type_code\": DataTypeCode.UINT, \"bits\": 8, \"lanes\": 1},\n        \"uint16\": {\"type_code\": DataTypeCode.UINT, \"bits\": 16, \"lanes\": 1},\n        \"uint32\": {\"type_code\": DataTypeCode.UINT, \"bits\": 32, \"lanes\": 1},\n        \"uint64\": {\"type_code\": DataTypeCode.UINT, \"bits\": 64, \"lanes\": 1},\n        \"float16\": {\"type_code\": DataTypeCode.FLOAT, \"bits\": 16, \"lanes\": 1},\n        \"float32\": {\"type_code\": DataTypeCode.FLOAT, \"bits\": 32, \"lanes\": 1},\n        \"float64\": {\"type_code\": DataTypeCode.FLOAT, \"bits\": 64, \"lanes\": 1},\n    }\n\n    def __init__(self, type_str):\n        super(DataType, self).__init__()\n        numpy_str_map = DataType.NUMPY2STR\n        if type_str in numpy_str_map:\n            type_str = numpy_str_map[type_str]\n        elif isinstance(type_str, np.dtype):\n            type_str = str(type_str)\n\n        assert isinstance(type_str, str)\n\n        str_dtype_map = DataType.STR2DTYPE\n        if type_str in str_dtype_map:\n            dtype_map = str_dtype_map[type_str]\n            self.bits = dtype_map[\"bits\"]\n            self.type_code = dtype_map[\"type_code\"]\n            self.lanes = dtype_map[\"lanes\"]\n            return\n\n        arr = type_str.split(\"x\")\n        head = arr[0]\n        self.lanes = int(arr[1]) if len(arr) > 1 else 1\n        bits = 32\n\n        if head.startswith(\"int\"):\n            self.type_code = DataTypeCode.INT\n            head = head[3:]\n        elif head.startswith(\"uint\"):\n            self.type_code = DataTypeCode.UINT\n            head = head[4:]\n        elif head.startswith(\"float\"):\n            self.type_code = DataTypeCode.FLOAT\n            head = head[5:]\n        elif head.startswith(\"handle\"):\n            self.type_code = DataTypeCode.HANDLE\n            bits = 64\n            head = \"\"\n        elif head.startswith(\"bfloat\"):\n            self.type_code = DataTypeCode.BFLOAT\n            head = head[6:]\n        elif head.startswith(\"custom\"):\n            # pylint: disable=import-outside-toplevel\n            import tvm.runtime._ffi_api\n\n            low, high = head.find(\"[\"), head.find(\"]\")\n            if not low or not high or low >= high:\n                raise ValueError(\"Badly formatted custom type string %s\" % type_str)\n            type_name = head[low + 1 : high]\n            self.type_code = tvm.runtime._ffi_api._datatype_get_type_code(type_name)\n            head = head[high + 1 :]\n        else:\n            raise ValueError(\"Do not know how to handle type %s\" % type_str)\n        bits = int(head) if head else bits\n        self.bits = bits\n\n    def __repr__(self):\n        # pylint: disable=import-outside-toplevel\n        if self.bits == 1 and self.lanes == 1:\n            return \"bool\"\n        if self.type_code in DataType.CODE2STR:\n            type_name = DataType.CODE2STR[self.type_code]\n        else:\n            import tvm.runtime._ffi_api\n\n            type_name = \"custom[%s]\" % tvm.runtime._ffi_api._datatype_get_type_name(self.type_code)\n        x = \"%s%d\" % (type_name, self.bits)\n        if self.lanes != 1:\n            x += \"x%d\" % self.lanes\n        return x\n\n    def __eq__(self, other):\n        return (\n            self.bits == other.bits\n            and self.type_code == other.type_code\n            and self.lanes == other.lanes\n        )\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n\nRPC_SESS_MASK = 128\n\n\nclass Device(ctypes.Structure):\n    \"\"\"TVM device strucure.\n\n    Typically constructed using convenience function\n    :meth:`tvm.runtime.device`.\n\n    Exposes uniform interface to device-specific APIs such as CUDA or\n    OpenCL.  Some properties may return None depending on whether an\n    API exposes that particular property.\n\n    NOTE!  The integer values in MASK2STR and STR2MASK *must* correspond\n    to the values provided by the DLDeviceType and TVMDeviceExtType enums.\n    \"\"\"\n\n    kDLCPU = 1\n    kDLCUDA = 2\n    kDLCUDAHost = 3\n    kDLOpenCL = 4\n    kDLVulkan = 7\n    kDLMetal = 8\n    kDLVPI = 9\n    kDLROCM = 10\n    kDLROCMHost = 11\n    kDLExtDev = 12\n    kDLCUDAManaged = 13\n    kDLOneAPI = 14\n    kDLWebGPU = 15\n    kDLHexagon = 16\n    kDLAOCL = 32\n    kDLSDAccel = 33\n    kOpenGL = 34\n    kDLMicroDev = 35\n\n    _fields_ = [(\"device_type\", ctypes.c_int), (\"device_id\", ctypes.c_int)]\n    MASK2STR = {\n        kDLCPU: \"cpu\",\n        kDLCUDA: \"cuda\",\n        kDLCUDAHost: \"cuda_host\",\n        kDLCUDAManaged: \"cuda_managed\",\n        kDLOpenCL: \"opencl\",\n        kDLVulkan: \"vulkan\",\n        kDLMetal: \"metal\",\n        kDLVPI: \"vpi\",\n        kDLROCM: \"rocm\",\n        kDLROCMHost: \"rocm_host\",\n        kDLExtDev: \"ext_dev\",\n        kDLOneAPI: \"oneapi\",\n        kDLWebGPU: \"webgpu\",\n        kDLHexagon: \"hexagon\",\n        kDLAOCL: \"aocl\",\n        kDLSDAccel: \"sdaccel\",\n        kOpenGL: \"opengl\",\n        kDLMicroDev: \"microdev\",\n    }\n\n    STR2MASK = {\n        \"llvm\": kDLCPU,\n        \"stackvm\": kDLCPU,\n        \"cpu\": kDLCPU,\n        \"c\": kDLCPU,\n        \"test\": kDLCPU,\n        \"hybrid\": kDLCPU,\n        \"composite\": kDLCPU,\n        \"cuda\": kDLCUDA,\n        \"nvptx\": kDLCUDA,\n        \"cl\": kDLOpenCL,\n        \"opencl\": kDLOpenCL,\n        \"sdaccel\": kDLOpenCL,\n        \"aocl\": kDLAOCL,\n        \"aocl_sw_emu\": kDLAOCL,\n        \"vulkan\": kDLVulkan,\n        \"metal\": kDLMetal,\n        \"vpi\": kDLVPI,\n        \"rocm\": kDLROCM,\n        \"ext_dev\": kDLExtDev,\n        \"hexagon\": kDLHexagon,\n        \"webgpu\": kDLWebGPU,\n    }\n\n    def __init__(self, device_type, device_id):\n        super(Device, self).__init__()\n        self.device_type = int(device_type)\n        self.device_id = device_id\n\n    def _GetDeviceAttr(self, device_type, device_id, attr_id):\n        \"\"\"Internal helper function to invoke runtime.GetDeviceAttr\"\"\"\n        # pylint: disable=import-outside-toplevel\n        import tvm.runtime._ffi_api\n\n        return tvm.runtime._ffi_api.GetDeviceAttr(device_type, device_id, attr_id)\n\n    @property\n    def exist(self):\n        \"\"\"Whether this device exists.\n\n        Returns True if TVM has support for the device, if the\n        physical device is present, and the device is accessible\n        through appropriate drivers (e.g. cuda/vulkan).\n\n        Returns\n        -------\n        exist : bool\n            True if the device exists\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 0) != 0\n\n    @property\n    def max_threads_per_block(self):\n        \"\"\"Maximum number of threads on each block.\n\n        Returns device value for cuda, metal, rocm, opencl, and vulkan\n        devices.  Returns remote device value for RPC devices.\n        Returns None for all other devices.\n\n        Returns\n        -------\n        max_threads_per_block : int or None\n            The number of threads on each block\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 1)\n\n    @property\n    def warp_size(self):\n        \"\"\"Number of threads that execute concurrently.\n\n        Returns device value for cuda, rocm, and vulkan.  Returns\n        1 for metal and opencl devices, regardless of the physical\n        device.  Returns remote device value for RPC devices.  Returns\n        None for all other devices.\n\n        Returns\n        -------\n        warp_size : int or None\n            Number of threads that execute concurrently\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 2)\n\n    @property\n    def max_shared_memory_per_block(self):\n        \"\"\"Total amount of shared memory per block in bytes.\n\n        Returns device value for cuda, rocm, opencl, and vulkan.\n        Returns remote device value for RPC devices.  Returns None for\n        all other devices.\n\n        Returns\n        -------\n        max_shared_memory_per_block : int or None\n            Total amount of shared memory per block in bytes\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 3)\n\n    @property\n    def compute_version(self):\n        \"\"\"Get compute version number as string.\n\n        Returns maximum API version (e.g. CUDA/OpenCL/Vulkan)\n        supported by the device.\n\n        Returns device value for cuda, rocm, opencl, and\n        vulkan. Returns remote device value for RPC devices.  Returns\n        None for all other devices.\n\n        Returns\n        -------\n        version : str or None\n            The version string in `major.minor` format.\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 4)\n\n    @property\n    def device_name(self):\n        \"\"\"Return the vendor-specific name of device.\n\n        Returns device value for cuda, rocm, opencl, and vulkan.\n        Returns remote device value for RPC devices.  Returns None for\n        all other devices.\n\n        Returns\n        -------\n        device_name : str or None\n            The name of the device.\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 5)\n\n    @property\n    def max_clock_rate(self):\n        \"\"\"Return the max clock frequency of device (kHz).\n\n        Returns device value for cuda, rocm, and opencl.  Returns\n        remote device value for RPC devices.  Returns None for all\n        other devices.\n\n        Returns\n        -------\n        max_clock_rate : int or None\n            The maximum clock frequency of the device (kHz)\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 6)\n\n    @property\n    def multi_processor_count(self):\n        \"\"\"Return the number of compute units in the device.\n\n        Returns device value for cuda, rocm, and opencl.  Returns\n        remote device value for RPC devices.  Returns None for all\n        other devices.\n\n        Returns\n        -------\n        multi_processor_count : int or None\n            Thee number of compute units in the device\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 7)\n\n    @property\n    def max_thread_dimensions(self):\n        \"\"\"Return the maximum size of each thread axis\n\n        Returns device value for cuda, rocm, opencl, and vulkan.\n        Returns remote device value for RPC devices.  Returns None for\n        all other devices.\n\n        Returns\n        -------\n        dims: List of int, or None\n            The maximum length of threadIdx.x, threadIdx.y, threadIdx.z\n\n        \"\"\"\n        return json.loads(self._GetDeviceAttr(self.device_type, self.device_id, 8))\n\n    @property\n    def api_version(self):\n        \"\"\"Returns version number of the SDK used to compile TVM.\n\n        For example, CUDA_VERSION for cuda or VK_HEADER_VERSION for\n        Vulkan.\n\n        Returns device value for cuda, rocm, opencl, and vulkan.\n        Returns remote device value for RPC devices.  Returns None for\n        all other devices.\n\n        Returns\n        -------\n        version : int or None\n            The version of the SDK\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 11)\n\n    @property\n    def driver_version(self):\n        \"\"\"Returns version number of the driver\n\n        Returns driver vendor's internal version number.\n        (e.g. \"450.408.256\" for nvidia-driver-450)\n\n        Returns device value for opencl and vulkan.  Returns remote\n        device value for RPC devices.  Returns None for all other\n        devices.\n\n        Returns\n        -------\n        version : str or None\n            The version string in `major.minor.patch` format.\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 12)\n\n    def texture_spatial_limit(self):\n        \"\"\"Returns limits for textures by spatial dimensions\n\n        Returns\n        -------\n        limit : int or None\n            Maximum size of the texture by spatial dimensions\n\n        \"\"\"\n        return self._GetDeviceAttr(self.device_type, self.device_id, 12)\n\n    def create_raw_stream(self):\n        \"\"\"Create a new runtime stream at the context.\n\n        User should free the stream after use.\n\n        Returns\n        -------\n        stream : TVMStreamHandle\n            The created runtime stream.\n        \"\"\"\n        stream = ctypes.c_void_p()\n        check_call(_LIB.TVMStreamCreate(self.device_type, self.device_id, ctypes.byref(stream)))\n        return stream\n\n    def free_raw_stream(self, stream):\n        \"\"\"Free a created stream handle.\n\n        Parameters\n        ----------\n        stream : TVMStreamHandle\n            The stream which should to be released.\n        \"\"\"\n        check_call(_LIB.TVMStreamFree(self.device_type, self.device_id, stream))\n\n    def set_raw_stream(self, stream):\n        \"\"\"Set a created stream handle.\n\n        Parameters\n        ----------\n        stream : TVMStreamHandle\n            The stream which should to be set to the device.\n        \"\"\"\n        check_call(_LIB.TVMSetStream(self.device_type, self.device_id, stream))\n\n    def sync(self, stream=None):\n        \"\"\"Synchronize until jobs finished at the context.\n\n        Parameters\n        ----------\n        stream : TVMStreamHandle\n            Jobs in this stream should be finished.\n        \"\"\"\n        check_call(_LIB.TVMSynchronize(self.device_type, self.device_id, stream))\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, Device)\n            and self.device_id == other.device_id\n            and self.device_type == other.device_type\n        )\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def __hash__(self):\n        return hash(str(self))\n\n    def __repr__(self):\n        if self.device_type >= RPC_SESS_MASK:\n            tbl_id = self.device_type / RPC_SESS_MASK - 1\n            dev_type = self.device_type % RPC_SESS_MASK\n            return \"remote[%d]:%s(%d)\" % (tbl_id, Device.MASK2STR[dev_type], self.device_id)\n        return \"%s(%d)\" % (Device.MASK2STR[self.device_type], self.device_id)\n\n\nclass TVMArray(ctypes.Structure):\n    \"\"\"TVMValue in C API\"\"\"\n\n    _fields_ = [\n        (\"data\", ctypes.c_void_p),\n        (\"device\", Device),\n        (\"ndim\", ctypes.c_int),\n        (\"dtype\", DataType),\n        (\"shape\", ctypes.POINTER(tvm_shape_index_t)),\n        (\"strides\", ctypes.POINTER(tvm_shape_index_t)),\n        (\"byte_offset\", ctypes.c_uint64),\n    ]\n\n\nclass ObjectRValueRef:\n    \"\"\"Represent an RValue ref to an object that can be moved.\n\n    Parameters\n    ----------\n    obj : tvm.runtime.Object\n        The object that this value refers to\n    \"\"\"\n\n    __slots__ = [\"obj\"]\n\n    def __init__(self, obj):\n        self.obj = obj\n\n\nTVMArrayHandle = ctypes.POINTER(TVMArray)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Integer bound analysis, simplification and pattern detection.\"\"\"\n\nfrom .int_set import (\n    IntSet,\n    IntervalSet,\n    estimate_region_lower_bound,\n    estimate_region_strict_bound,\n    estimate_region_upper_bound,\n)\nfrom .analyzer import ModularSet, ConstIntBound, Analyzer\nfrom .bound import deduce_bound\nfrom .pattern import detect_linear_equation, detect_clip_bound\nfrom .int_solver import solve_linear_equations, solve_linear_inequalities\nfrom .iter_affine_map import IterMapExpr, IterMark, IterSplitExpr, IterSumExpr\nfrom .iter_affine_map import (\n    detect_iter_map,\n    normalize_iter_map_to_expr,\n    subspace_divide,\n    inverse_affine_iter_map,\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.arith\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"arith\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/analyzer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arithmetic data structure and utility\"\"\"\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"arith.ModularSet\")\nclass ModularSet(Object):\n    \"\"\"Represent range of (coeff * x + base) for x in Z\"\"\"\n\n    def __init__(self, coeff, base):\n        self.__init_handle_by_constructor__(_ffi_api.ModularSet, coeff, base)\n\n\n@tvm._ffi.register_object(\"arith.ConstIntBound\")\nclass ConstIntBound(Object):\n    \"\"\"Represent constant integer bound\n\n    Parameters\n    ----------\n    min_value : int\n        The minimum value of the bound.\n\n    max_value : int\n        The maximum value of the bound.\n    \"\"\"\n\n    POS_INF = (1 << 63) - 1\n    NEG_INF = -POS_INF\n\n    def __init__(self, min_value, max_value):\n        self.__init_handle_by_constructor__(_ffi_api.ConstIntBound, min_value, max_value)\n\n\nclass ConstraintScope:\n    \"\"\"Constraint scope.\n\n    Parameters\n    ----------\n    fenter : function\n        A function that will be called to create an enter context.\n\n    Note\n    ----\n    Do not create object directly, use Analyzer.constraint_scope\n    \"\"\"\n\n    def __init__(self, fenter):\n        self._fenter = fenter\n        self._fexit = None\n\n    def __enter__(self):\n        self._fexit = self._fenter()\n\n    def __exit__(self, ptype, value, trace):\n        self._fexit()\n\n\nclass Analyzer:\n    \"\"\"Integer arithmetic analyzer\n\n    This is a stateful analyzer class that can\n    be used to perform various symbolic integer analysis.\n    \"\"\"\n\n    def __init__(self):\n        _mod = _ffi_api.CreateAnalyzer()\n        self._const_int_bound = _mod(\"const_int_bound\")\n        self._const_int_bound_update = _mod(\"const_int_bound_update\")\n        self._bind = _mod(\"bind\")\n        self._modular_set = _mod(\"modular_set\")\n        self._simplify = _mod(\"Simplify\")\n        self._rewrite_simplify = _mod(\"rewrite_simplify\")\n        self._canonical_simplify = _mod(\"canonical_simplify\")\n        self._int_set = _mod(\"int_set\")\n        self._enter_constraint_context = _mod(\"enter_constraint_context\")\n        self._can_prove_equal = _mod(\"can_prove_equal\")\n\n    def const_int_bound(self, expr):\n        \"\"\"Find constant integer bound for expr.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n\n        Returns\n        -------\n        bound : ConstIntBound\n            The result bound\n        \"\"\"\n        return self._const_int_bound(expr)\n\n    def modular_set(self, expr):\n        \"\"\"Find a modular set that expr belongs to.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n\n        Returns\n        -------\n        result : ModularSet\n            The result.\n        \"\"\"\n        return self._modular_set(expr)\n\n    def simplify(self, expr, steps=2):\n        \"\"\"Simplify expression via both rewrite and canonicalization.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n        steps : The simplification runs in the order of\n                rewrite_simplify (step 1) -> canonical_simplify (step 2) ->\n                rewrite_simplify (step 3) -> canonical_simplify (step 4) -> ...\n                param steps controls how many steps to run.\n                Default is 2, i.e., rewrite_simplify + canonical_simplify.\n\n        Returns\n        -------\n        result : Expr\n            The result.\n        \"\"\"\n        return self._simplify(expr, steps)\n\n    def rewrite_simplify(self, expr):\n        \"\"\"Simplify expression via rewriting rules.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n\n        Returns\n        -------\n        result : Expr\n            The result.\n        \"\"\"\n        return self._rewrite_simplify(expr)\n\n    def canonical_simplify(self, expr):\n        \"\"\"Simplify expression via canonicalization.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n\n        Returns\n        -------\n        result : Expr\n            The result.\n        \"\"\"\n        return self._canonical_simplify(expr)\n\n    def int_set(self, expr, dom_map):\n        \"\"\"Compute a symbolic IntSet that covers expr for all values in dom_map.\n\n        Parameters\n        ----------\n        expr : PrimExpr\n            The expression.\n\n        dom_map : Dict[Var, tvm.arith.IntSet]\n            The domain for variables to be relaxed.\n\n        Returns\n        -------\n        result : IntSet\n            The result.\n        \"\"\"\n        return self._int_set(expr, dom_map)\n\n    def bind(self, var, expr):\n        \"\"\"Bind a variable to the expression.\n\n        Parameters\n        ----------\n        var : tvm.tir.Var\n            The variable.\n\n        expr : PrimExpr\n            The expression.\n        \"\"\"\n        return self._bind(var, expr)\n\n    def constraint_scope(self, constraint):\n        \"\"\"Create a constraint scope.\n\n        Parameters\n        ----------\n        constraint : PrimExpr\n            The constraint expression.\n\n        returns\n        -------\n        scope : ConstraintScope\n            The constraint scope\n\n        Examples\n        --------\n        .. code-block:: python\n\n          x = te.var(\"x\")\n          analyzer = tvm.arith.Analyzer()\n          with analzyer.constraint_scope(x % 3 == 0):\n              # constraint in effect\n              assert analyzer.modular_set(x).coeff == 3\n          # constraint no longer in effect\n          assert analyzer.modular_set(x).coeff != 3\n        \"\"\"\n\n        def _fenter():\n            return self._enter_constraint_context(constraint)\n\n        return ConstraintScope(_fenter)\n\n    def update(self, var, info, override=False):\n        \"\"\"Update infomation about var\n\n        Parameters\n        ----------\n        var : tvm.tir.Var\n            The variable.\n\n        info : tvm.Object\n            Related information.\n\n        override : bool\n            Whether allow override.\n        \"\"\"\n        if isinstance(info, ConstIntBound):\n            self._const_int_bound_update(var, info, override)\n        else:\n            raise TypeError(\"Do not know how to handle type {}\".format(type(info)))\n\n    def can_prove_equal(self, lhs: \"PrimExpr\", rhs: \"PrimExpr\"):\n        \"\"\"Whether we can prove that lhs == rhs\n\n        Parameters\n        ----------\n        lhs: PrimExpr\n            The left-hand side of the comparison\n\n        rhs: PrimExpr\n            The right-hand side of the comparison\n\n        Returns\n        -------\n        result: bool\n            Whether we can prove that lhs == rhs\n        \"\"\"\n        return self._can_prove_equal(lhs, rhs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/bound.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Bound deduction.\"\"\"\nfrom . import _ffi_api\n\n\ndef deduce_bound(var, cond, hint_map, relax_map):\n    \"\"\"Deduce the bound of the target variable in the cond.\n\n    Parameters\n    ----------\n    var : Var\n        The target variable to be deduced.\n\n    cond : PrimExpr\n        The condition\n\n    hint_map : Map[Var, IntSet]\n        Domain of variables used to help deduction.\n\n    relax_map : Map[Var, IntSet]\n        The fomain of the variables to be relaxed\n        using the provided domain.\n    \"\"\"\n    return _ffi_api.DeduceBound(var, cond, hint_map, relax_map)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/int_set.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Integer set.\"\"\"\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\nclass IntSet(Object):\n    \"\"\"Represent a set of integer in one dimension.\"\"\"\n\n    def is_nothing(self):\n        \"\"\"Whether the set represent nothing\"\"\"\n        return _ffi_api.IntSetIsNothing(self)\n\n    def is_everything(self):\n        \"\"\"Whether the set represent everything\"\"\"\n        return _ffi_api.IntSetIsEverything(self)\n\n    @staticmethod\n    def vector(vec):\n        \"\"\"Construct an integer set that covers the vector expr\n\n        Parameters\n        ----------\n        vec : PrimExpr\n            The vector expression.\n\n        Returns\n        -------\n        rset : IntSet\n            The result set.\n        \"\"\"\n        return _ffi_api.intset_vector(vec)\n\n    @staticmethod\n    def single_point(point):\n        \"\"\"Construct a point set.\n\n        Parameters\n        ----------\n        point : PrimExpr\n            The vector expression.\n\n        Returns\n        -------\n        rset : IntSet\n            The result set.\n        \"\"\"\n        return _ffi_api.intset_single_point(point)\n\n\n@tvm._ffi.register_object(\"arith.IntervalSet\")\nclass IntervalSet(IntSet):\n    \"\"\"Represent set of continuous interval [min_value, max_value]\n\n    Parameters\n    ----------\n    min_value : PrimExpr\n        The minimum value in the interval.\n\n    max_value : PrimExpr\n        The maximum value in the interval.\n    \"\"\"\n\n    def __init__(self, min_value, max_value):\n        self.__init_handle_by_constructor__(_ffi_api.IntervalSet, min_value, max_value)\n\n\ndef estimate_region_lower_bound(region, var_dom, predicate):\n    \"\"\"Analyze the region with affine map, given the domain of variables and their predicate\n    Some subregion may be discarded during the lower-bound analysis.\n\n    Parameters\n    ----------\n    region : List[Range]\n        The region to be analyzed.\n\n    var_dom : Dict[Var, Range]\n        The ranges of the variables\n\n    predicate : PrimExpr\n        The predicate for the affine map\n\n    Returns\n    ----------\n    region_int_set : Optional[List[IntSet]]\n        None if the detection fails, or an array of IntSets as the result of analysis\n    \"\"\"\n    return _ffi_api.EstimateRegionLowerBound(region, var_dom, predicate)\n\n\ndef estimate_region_strict_bound(region, var_dom, predicate):\n    \"\"\"Analyze the region with affine map, given the domain of variables and their predicate\n    The result should be strict, i.e. no region is discarded or relaxed.\n\n    Parameters\n    ----------\n    region : List[Range]\n        The region to be analyzed.\n\n    var_dom : Dict[Var, Range]\n        The ranges of the variables\n\n    predicate : PrimExpr\n        The predicate for the affine map\n\n    Returns\n    ----------\n    region_int_set : Optional[List[IntSet]]\n        None if the detection fails, or an array of IntSets as the result of analysis\n    \"\"\"\n    return _ffi_api.EstimateRegionStrictBound(region, var_dom, predicate)\n\n\ndef estimate_region_upper_bound(region, var_dom, predicate):\n    \"\"\"Analyze the region with affine map, given the domain of variables and their predicate\n    Relaxation of the region may be used in upper-bound analysis,\n    i.e. some extra region may be added to the result.\n\n    Parameters\n    ----------\n    region : List[Range]\n        The region to be analyzed.\n\n    var_dom : Dict[Var, Range]\n        The ranges of the variables\n\n    predicate : PrimExpr\n        The predicate for the affine map\n\n    Returns\n    ----------\n    region_int_set : List[IntSet]\n        an array of IntSets as the result of analysis\n    \"\"\"\n    return _ffi_api.EstimateRegionUpperBound(region, var_dom, predicate)\n\n\ndef pos_inf():\n    \"\"\"Returns the symbolic positive infinity\n\n    Returns\n    ----------\n    pos_inf : Var\n        A symbolic var that indicates positive infinity\n    \"\"\"\n    return _ffi_api.PosInf()\n\n\ndef neg_inf():\n    \"\"\"Returns the symbolic positive infinity\n\n    Returns\n    ----------\n    neg_inf : Var\n        A symbolic var that indicates positive infinity\n    \"\"\"\n    return _ffi_api.NegInf()\n\n\ndef union_lower_bound(sets):\n    \"\"\"Create a lower-bound of union set, where some of the segments may be dropped\n\n    Parameters\n    ----------\n    sets : List[IntSet]\n        The sets to be combined\n\n    Returns\n    ----------\n    union_lower_bound : List[IntSet]\n        An N-dimensional integer set, the lower bound of the union\n    \"\"\"\n    return _ffi_api.UnionLowerBound(sets)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/int_solver.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"integer constraints data structures and solvers\"\"\"\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"arith.IntGroupBounds\")\nclass IntGroupBounds(Object):\n    \"\"\"Represent integer grouped bounds which are classified into\n       lower bounds (include), upper bounds (include) and equalities.\n\n    Parameters\n    ----------\n    coef : tvm.ir.PrimExpr\n        The coefficient. Must be integer type.\n        coef * var >= lower\n        coef * var == equal\n        coef * var >= upper\n    lower : List[tvm.ir.PrimExpr]\n        the lower bounds (include)\n    equal : List[tvm.ir.PrimExpr]\n        equalities\n    upper : List[tvm.ir.PrimExpr]\n        the upper bounds (include)\n    \"\"\"\n\n    def __init__(self, coef, lower, equal, upper):\n        self.__init_handle_by_constructor__(_ffi_api.IntGroupBounds, coef, lower, equal, upper)\n\n    @staticmethod\n    def from_range(rng):\n        \"\"\"Construct a IntGroupedBounds by Range.\n\n        Parameters\n        ----------\n        rng : tvm.ir.Range\n\n\n        Returns\n        -------\n        ret : Range\n            The constructed range.\n        \"\"\"\n        return _ffi_api.IntGroupBounds_from_range(rng)\n\n    def find_best_range(self):\n        \"\"\"Return the best range from the grouped bounds.\n        None if (-inf, +inf).\n        \"\"\"\n        return _ffi_api.IntGroupBounds_FindBestRange(self)\n\n\n@tvm._ffi.register_object(\"arith.IntConstraints\")\nclass IntConstraints(Object):\n    \"\"\"Represent a set of integer constraints including variables, their ranges and\n       the relations between them (either equations or inequalities)\n\n    Parameters\n    ----------\n    variables : List[tvm.tir.Var]\n        The variables in the constraints. Must be integers\n    ranges    : Map[tvm.tir.Var, tvm.ir.Range]\n        The ranges of the variables.\n    relations : List[tvm.ir.PrimExpr]\n        The relations between the variables (either equations or inequalities)\n    \"\"\"\n\n    def __init__(self, variables, ranges, relations):\n        self.__init_handle_by_constructor__(_ffi_api.IntConstraints, variables, ranges, relations)\n\n\n@tvm._ffi.register_object(\"arith.IntConstraintsTransform\")\nclass IntConstraintsTransform(Object):\n    \"\"\"We can have different set of variables to represent the same integer constraints.\n       For example, the following two constrains are equivalent,\n       {a + b = 0 | a >= 0, b >= 0} and\n       {m - n = 0 | m >= 0, n <= 0}\n       This data structure represents the transformation\n       between two equivalent integer constraints.\n       In the above example,\n       src        : {a + b = 0 | a >= 0, b >= 0}\n       dst        : {m - n = 0 | m >= 0, n <= 0}\n       src_to_dst : {a -> m, b -> -n}\n       dst_to_src : {m -> a, n -> -b}\n\n    Parameters\n    ----------\n    src : arith.IntConstraints\n        source integer constraints, e.g., {a + b = 0 | a >= 0, b >= 0}\n    dst : arith.IntConstraints\n        integer constraints equivalent to the source, e.g., {m - n = 0 | m >= 0, n <= 0}\n    src_to_dst : Map[tvm.tir.Var, tvm.ir.PrimExpr]\n        mapping from variables in the src to the variables in the dst,\n                e.g., {a -> m, b -> -n}\n    dst_to_src : Map[tvm.tir.Var, tvm.ir.PrimExpr]\n        mapping from variables in the dst to the variables in the src,\n        e.g., {m -> a, n -> -b}\n    \"\"\"\n\n    def __init__(self, src, dst, src_to_dst, dst_to_src):\n        self.__init_handle_by_constructor__(\n            _ffi_api.IntConstraintsTransform, src, dst, src_to_dst, dst_to_src\n        )\n\n\ndef solve_linear_equations(equations, variables=None, ranges=None):\n    \"\"\"Solve linear equations.\n\n    Parameters\n    ----------\n    equations: List[tvm.ir.PrimExpr] or IntConstraints\n        The equations of the variables\n    variables : Optional[List[tvm.tir.Var]]\n        The variables in the system.\n    ranges    : Optional[Map[tvm.tir.Var, tvm.ir.Range]]\n        The ranges of the variables.\n\n    Returns\n    -------\n    int_constraints_transform : IntConstraintsTransform\n        New integer constraints, with less variables (if the problem is NOT of full rank),\n        or no variable (if the problem is of full rank),\n        or an empty integer constraints (if the problem is unsolvable).\n        It also provides the ranges of the variables in the new system,\n        as well as inequalities inferred from the problem.\n        You can get the mapping from the original variables to the solution via\n        int_constraints_transform.src_to_dst.\n    \"\"\"\n    if isinstance(equations, IntConstraints):\n        return _ffi_api.SolveLinearEquations(equations)\n    return _ffi_api.SolveLinearEquations(variables, ranges, equations)\n\n\ndef solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):\n    \"\"\"Solve linear inequalities.\n\n    Parameters\n    ----------\n    equations   : List[tvm.ir.PrimExpr] or IntConstraints\n        The inequalities of the variables\n    variables   : Optional[List[tvm.tir.Var]]\n        The variables in the system.\n    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]\n        The ranges of the variables.\n    deskew_range: Optional[bool]\n        Whether deskew the result ranges to be started from zero.\n        Default false.\n\n    Returns\n    -------\n    ret_ranges: IntConstraints or IntConstraintsTransform\n        The result ranges for each variables.\n        Constrains that cannot be transformed to Range will be stored in IntConstraints.relations.\n        If deskew_range is set (=True), the result ranges will be deskewed to be started from zero.\n        New variables are created accordingly therefore IntConstraintsTransform is returned.\n    \"\"\"\n    solver = (\n        _ffi_api.SolveInequalitiesDeskewRange if deskew_range else _ffi_api.SolveInequalitiesToRange\n    )\n    if isinstance(equations, IntConstraints):\n        assert variables is None\n        assert ranges is None\n        return solver(equations)\n    return solver(variables, ranges, equations)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/iter_affine_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Iterator (quasi)affine mapping patterns.\"\"\"\nfrom enum import IntEnum\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom tvm.ir import PrimExpr\nfrom . import _ffi_api\n\n\nclass IterMapExpr(PrimExpr):\n    \"\"\"Base class of all IterMap expressions.\"\"\"\n\n\n@tvm._ffi.register_object(\"arith.IterMark\")\nclass IterMark(Object):\n    \"\"\"Mark the source as an iterator in [0, extent).\n\n    Parameters\n    ----------\n    source : PrimExpr.\n        The source expression.\n\n    extent : PrimExpr\n        The extent of the iterator.\n    \"\"\"\n\n    def __init__(self, source, extent):\n        self.__init_handle_by_constructor__(_ffi_api.IterMark, source, extent)\n\n\n@tvm._ffi.register_object(\"arith.IterSplitExpr\")\nclass IterSplitExpr(IterMapExpr):\n    \"\"\"Split of an iterator.\n\n    result = floormod(floordiv(source, lower_factor), extent) * scale\n\n    Parameters\n    ----------\n    source : IterMark\n        The source marked iterator.\n\n    lower_factor : PrimExpr\n        The lower factor to split the domain.\n\n    extent : PrimExpr\n        The extent of the split.\n\n    scale : PrimExpr\n        Additional scale to the split.\n    \"\"\"\n\n    def __init__(self, source, lower_factor, extent, scale):\n        self.__init_handle_by_constructor__(\n            _ffi_api.IterSplitExpr, source, lower_factor, extent, scale\n        )\n\n\n@tvm._ffi.register_object(\"arith.IterSumExpr\")\nclass IterSumExpr(IterMapExpr):\n    \"\"\"Fuse multiple iterators by summing them with scaling.\n\n    result = sum(args) + base\n\n    Parameters\n    ----------\n    args : List[IterSplitExpr]\n        The input to the sum expression.\n\n    base : PrimExpr\n        The base offset.\n    \"\"\"\n\n    def __init__(self, args, base):\n        self.__init_handle_by_constructor__(_ffi_api.IterSumExpr, args, base)\n\n\nclass IterMapLevel(IntEnum):\n    \"\"\"Possible kinds of iter mapping check level.\"\"\"\n\n    Bijective = 0\n    Surjective = 1\n    NoCheck = 3\n\n    @staticmethod\n    def from_str(name: str):\n        \"\"\"Helper to create level enum from string\"\"\"\n        if name is None:\n            return IterMapLevel.NoCheck\n        name = name.lower()\n        if name == \"bijective\":\n            check_level = IterMapLevel.Bijective\n        elif name == \"surjective\":\n            check_level = IterMapLevel.Surjective\n        elif name == \"nocheck\":\n            check_level = IterMapLevel.NoCheck\n        else:\n            raise ValueError(f\"Unknown check level {name}\")\n        return check_level\n\n\ndef detect_iter_map(\n    indices,\n    input_iters,\n    predicate=True,\n    check_level=IterMapLevel.Surjective,\n    simplify_trivial_iterators=True,\n):\n    \"\"\"Detect if indices can be written as mapped iters from input iters\n\n    Parameters\n    ----------\n    indices : List[PrimExpr]\n        The input indices\n\n    input_iters : Map[Var, Range]\n        The domain of each input iterators.\n\n    predicate : PrimExpr\n        The predicate constraints on the input iterators\n\n    check_level : Union[str, IterMapLevel]\n        Checking level of iteration mapping\n\n    simplify_trivial_iterators: bool\n        If true, iterators with extent of 1 will be replaced with a\n        constant value.\n\n    Returns\n    -------\n    results : IterMapResult\n        The iter map matching result.\n        The result's .indices is empty array if no match can be found.\n\n    \"\"\"\n    if isinstance(check_level, str):\n        check_level = IterMapLevel.from_str(check_level)\n    elif check_level is None:\n        check_level = IterMapLevel.NoCheck\n    return _ffi_api.DetectIterMap(\n        indices, input_iters, predicate, check_level, simplify_trivial_iterators\n    )\n\n\ndef normalize_iter_map_to_expr(expr):\n    \"\"\"Given an IterMapExpr, transform it to normal PrimExpr\n\n    Parameters\n    ----------\n    expr : IterMapExpr\n        the input IterMapExpr\n\n    Returns\n    -------\n    result : PrimExpr\n        the corresponding normal PrimExpr\n    \"\"\"\n    return _ffi_api.NormalizeIterMapToExpr(expr)\n\n\ndef subspace_divide(\n    bindings, input_iters, sub_iters, predicate=True, check_level=IterMapLevel.Surjective\n):\n    \"\"\"Detect if bindings can be written as\n    [a_0*e_0 + b_0 + c_0, a_1*e_1 + b_1, ..., a_n*e_n + b_n]\n    where a = some-quasi-affine-iter-map(input_iters set_minus sub_iters)\n          b = some-quasi-affine-iter-map(sub_iters)\n          c is constant symbols\n          e is the extent of b\n    For example, z*12 + y*3 + x + c = (z*4+y)*3 + x\n                bindings = [z*12 + y*3 + x + c]\n                input_iters = [z, y, x]\n                sub_iter = [x]\n                Then the result will be [a, b] where\n                a = [z*4 + y]\n                b = [x]\n\n    Parameters\n    ----------\n    bindings : List[PrimExpr]\n        The input bindings\n\n    input_iters : Map[Var, Range]\n        The domain of input iterator, which is the basis of the whole space\n\n    sub_iters : Array[Var]\n        The subset of input_iters, which is the basis of the subspace\n\n    predicate : PrimExpr\n        The predicate constraints on the input iterators\n\n    check_level : Union[str, IterMapLevel]\n        Checking level of iteration mapping\n\n    Returns\n    -------\n    results : List[List[PrimExpr]]\n        The result list has length len(bindings) + 1\n        [0, len(bindings)): The iter map matching result. The inner list is of length 2.\n                            The first expr is the basis of the quotient space.\n                            The second expr is the basis of the subspace.\n        len(bindings): the predicate of outer space and inner space\n        Empty array if no match can be found.\n    \"\"\"\n    if isinstance(check_level, str):\n        check_level = IterMapLevel.from_str(check_level)\n    return _ffi_api.SubspaceDivide(bindings, input_iters, sub_iters, predicate, check_level)\n\n\ndef inverse_affine_iter_map(iter_map, outputs):\n    \"\"\"Apply the inverse of the affine transformation to the outputs.\n    Similar to the back-propagation, starting from the outputs, it visits the DAG of the expressions\n    in reverse topology order and applies the inverse of the affine transformation until it reaches\n    the input. The affine iter map is required to be bijective.\n\n    For example, iter_map = [l0 // 16, l0 % 16], outputs = [output_0, output_1],\n    the affine transformation specified by `iter_map` will be applied to `outputs` and the result\n    will be {l0: ((output_0*16) + output_1)}.\n\n    See also :any:`detect_iter_map`.\n\n    Parameters\n    ----------\n    iter_map : List[IterSumExpr]\n        The bijective affine iter map.\n    outputs : List[PrimExpr]\n        The outputs of the affine transformation.\n\n    Returns\n    -------\n    results : Map[Var, PrimExpr]\n        The map from the input to the transformed result.\n    \"\"\"\n    return _ffi_api.InverseAffineIterMap(iter_map, outputs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/arith/pattern.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Detect common patterns.\"\"\"\nfrom . import _ffi_api\n\n\ndef detect_linear_equation(expr, var_list):\n    \"\"\"Match `expr = sum_{i=0}^{n-1} var[i] * coeff[i] + coeff[n]`\n\n    Where coeff[i] and base are invariant of var[j] for all i and j.\n\n    Parameters\n    ----------\n    expr : PrimExpr\n        The expression to be matched.\n\n    var_list : List[tvm.tir.Var]\n        A list of variables.\n\n    Returns\n    -------\n    coeff : List[PrimExpr]\n        A list of co-efficients if the match is successful.\n        An empty list if the match failed.\n    \"\"\"\n    return _ffi_api.DetectLinearEquation(expr, var_list)\n\n\ndef detect_clip_bound(expr, var_list):\n    \"\"\"Detect if expression corresponds to clip bound of the vars\n\n    Parameters\n    ----------\n    expr : PrimExpr\n        The expression to be matched.\n\n    var_list : List[tvm.tir.Var]\n        A list of variables.\n\n    Returns\n    -------\n    coeff : List[PrimExpr]\n        `concat([min_value[i], max_value[i]] for i, v in enumerate(var_list))`\n        An empty list if the match failed.\n    \"\"\"\n    return _ffi_api.DetectClipBound(expr, var_list)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\" Namespace for TVM Auto-scheduler. \"\"\"\n\nfrom . import (\n    compute_dag,\n    dispatcher,\n    feature,\n    loop_state,\n    measure,\n    measure_record,\n    relay_integration,\n    search_policy,\n    search_task,\n    task_scheduler,\n    utils,\n    workload_registry,\n)\n\n# Shortcut\nfrom .compute_dag import (\n    ComputeDAG,\n    LayoutRewriteOption,\n    get_shape_from_rewritten_layout,\n)\nfrom .cost_model import RandomModel, XGBModel\nfrom .dispatcher import ApplyHistoryBest, ApplyHistoryBestOrSample, DispatchContext\nfrom .measure import (\n    LocalBuilder,\n    LocalRPCMeasureContext,\n    LocalRunner,\n    MeasureInput,\n    MeasureResult,\n    RPCRunner,\n    register_task_input_check_func,\n)\nfrom .measure_record import (\n    RecordReader,\n    RecordToFile,\n    load_best_record,\n    load_records,\n    save_records,\n)\nfrom .relay_integration import (\n    extract_tasks,\n    is_auto_scheduler_enabled,\n    remove_index_check,\n    rewrite_compute_body,\n    rewrite_tensor_shape,\n)\nfrom .search_policy import (\n    EmptyPolicy,\n    PreloadCustomSketchRule,\n    PreloadMeasuredStates,\n    SketchPolicy,\n)\nfrom .search_task import (\n    HardwareParams,\n    SearchTask,\n    TuningOptions,\n    auto_schedule,\n    create_task,\n)\nfrom .task_scheduler import TaskScheduler\nfrom .workload_registry import make_workload_key, register_workload\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Register FFI APIs from C++ for the namespace tvm.auto_scheduler. \"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"auto_scheduler\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/compute_dag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" The auto-scheduler's computational graph and related program analyses. \"\"\"\n\nimport hashlib\nimport json\n\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom tvm.runtime._ffi_node_api import LoadJSON, SaveJSON\n\nfrom . import _ffi_api\nfrom .loop_state import State, StateObject\nfrom .utils import get_const_tuple\nfrom .workload_registry import workload_key_to_tensors\n\n\nclass LayoutRewriteOption:\n    \"\"\"\n    Options for applying layout rewrite.\n\n    The NO_REWRITE and INSERT_TRANSFORM_STAGE are expected to be used when tuning a standalone op,\n    and the REWRITE_FOR_PRE_TRANSFORMED is expected to be used when tuning ops inside a network.\n    \"\"\"\n\n    # Do not perform layout rewrite\n    NO_REWRITE = 0\n    # Insert layout transformation stages for input placeholders in the compute DAG\n    INSERT_TRANSFORM_STAGE = 1\n    # Do not insert layout transformation stages and assume the input placeholders\n    # are pre-transformed.\n    # Note: The lowered function with this option does not accept the origial input shapes,\n    # so this option must be used along with `AutoSchedulerLayoutRewrite` pass in Relay.\n    REWRITE_FOR_PRE_TRANSFORMED = 2\n\n    @staticmethod\n    def get_target_default(target, in_relay_integration=False):\n        \"\"\"Get the default layout rewrite option for the specified target.\n        Currently we only enable layout rewrite for cpu / mali backend for now\n\n        Parameters\n        ----------\n        target: tvm.target.Target\n            The compilation target.\n        in_relay_integration: bool\n            If this check is ask for relay integration.\n\n        Returns\n        -------\n        layout_rewrite_option: LayoutRewriteOption\n            The default layout rewrite option for the specified target.\n        \"\"\"\n        layout_rewrite_option = LayoutRewriteOption.NO_REWRITE\n        if target.kind.name == \"llvm\" or (\n            \"device\" in target.attrs and target.attrs[\"device\"] == \"mali\"\n        ):\n            layout_rewrite_option = (\n                LayoutRewriteOption.REWRITE_FOR_PRE_TRANSFORMED\n                if in_relay_integration\n                else LayoutRewriteOption.INSERT_TRANSFORM_STAGE\n            )\n\n        return layout_rewrite_option\n\n\n@tvm._ffi.register_object(\"auto_scheduler.ComputeDAG\")\nclass ComputeDAG(Object):\n    \"\"\"\n    The auto-scheduler's computational graph and related program analyses.\n\n    We convert a compute declaration described by `tvm.compute` (could be a single operator or a\n    subgraph) to a ComputeDAG. It keeps the input/output tensors, all operations in the DAG, and\n    some static analysis results for the DAG (e.g. the total float operation count,\n    consumer/producer relations of operations, whether an operation stage should\n    be tiled/compute inlined).\n    These analyses can help the search policy to make decisions during the search.\n    ComputeDAG is also responsible for the interaction between auto-scheduler's `LoopState` and\n    TVM schedule (e.g. applying the `LoopState` transform steps to a TVM schedule, providing\n    `LoopState` with extra information got from TVM schedule).\n\n    Parameters\n    ----------\n    compute : Union[List[Tensor], str, tvm.te.Schedule]\n        Input/output tensors or workload key for a compute declaration.\n    \"\"\"\n\n    def __init__(self, compute_or_sche):\n        if isinstance(compute_or_sche, str):\n            compute = workload_key_to_tensors(compute_or_sche)\n            sche = None\n        elif isinstance(compute_or_sche, (list, tvm.ir.container.Array)):\n            for item in compute_or_sche:\n                if not isinstance(item, tvm.te.Tensor):\n                    raise ValueError(\n                        \"The input of ComputeDAG should be a list of Tensor, but got %s\"\n                        % type(item)\n                    )\n            compute = compute_or_sche\n            sche = None\n        elif isinstance(compute_or_sche, tvm.te.Schedule):\n            compute = None\n            sche = compute_or_sche\n        else:\n            raise ValueError(\n                \"Invalid compute type: %s. ComputeDAG expects string, list of Tensor, or Schedule\"\n                % type(compute_or_sche)\n            )\n        self.__init_handle_by_constructor__(_ffi_api.ComputeDAG, compute, sche)\n\n    def get_init_state(self):\n        \"\"\"Get the init state of this ComputeDAG.\n\n        Returns\n        -------\n        state : State\n            The initial State without any transform steps.\n        \"\"\"\n        return State(self.init_state, self)\n\n    def apply_steps_from_state(self, state, layout_rewrite=LayoutRewriteOption.NO_REWRITE):\n        \"\"\"\n        Apply the history transform steps from a State to get a TVM schedule.\n\n        Parameters\n        ----------\n        state : Union[State, StateObject]\n            The state from which we get transform steps.\n\n        layout_rewrite: LayoutRewriteOption = NoRewrite\n            Rewrite the layout of placeholders specified by \"layout_free_placeholders\" attr\n            to make it most friendly for the generated schedule to read from.\n\n        Returns\n        -------\n            A `te.schedule` and the a list of `te.Tensor` to be used in `tvm.lower` or `tvm.build`.\n        \"\"\"\n        state_obj = state if isinstance(state, StateObject) else state.state_object\n        return _ffi_api.ComputeDAGApplyStepsFromState(self, state_obj, layout_rewrite)\n\n    def print_python_code_from_state(self, state):\n        \"\"\"\n        Print transform steps in the history of a State as TVM's python schedule code.\n\n        This is used to print transformation steps for debugging.\n        Use `apply_steps_from_state` if you want to get a schedule for code generation.\n\n        Parameters\n        ----------\n        state : Union[State, StateObject]\n            The state from which we get transform steps.\n\n        Returns\n        -------\n        str : Str\n            The Python schedule code.\n        \"\"\"\n        state_obj = state if isinstance(state, StateObject) else state.state_object\n        return _ffi_api.ComputeDAGPrintPythonCodeFromState(self, state_obj)\n\n    def infer_bound_from_state(self, state):\n        \"\"\"\n        Infer and fill the bound of all iterators of a state.\n\n        The states may lose complete bound information after some transform steps\n        (e.g., compute_at).\n        We can call this function to infer and fill all the bound information.\n        This function calls TVM InferBound pass internally to get the bound.\n        The returned state of this function is guaranteed to have complete iterator extent\n        information.\n\n        Parameters\n        ----------\n        state : Union[State, StateObject]\n            The state from which we get transform steps.\n\n        Returns\n        -------\n        updated_state : State\n            The State with complete bound information.\n        \"\"\"\n        state_obj = state if isinstance(state, StateObject) else state.state_object\n        updated_state = State(_ffi_api.ComputeDAGInferBoundFromState(self, state_obj), self)\n        # Copy the stage_id_map from the original state to make sure the old indices are still\n        # valid\n        if isinstance(state, State):\n            for k, v in state.stage_id_map.items():\n                updated_state.stage_id_map[k] = v\n        return updated_state\n\n    def rewrite_layout_from_state(self, state):\n        \"\"\"\n        Rewrite the layout of the DAG according to the history transform steps of a state.\n\n        Parameters\n        ----------\n        state : Union[State, StateObject]\n            The state from which we get transform steps.\n\n        Returns\n        -------\n        updated_dag : ComputeDAG\n            The compute dag with rewritten layout.\n        \"\"\"\n        state_obj = state if isinstance(state, StateObject) else state.state_object\n        return _ffi_api.ComputeDAGRewriteLayoutFromState(self, state_obj)\n\n    def workload_key(self):\n        \"\"\"Return the workload key of this compute DAG.\n        The workload key is a JSON string from a tuple of (hash of DAG, tensor shapes...)\n\n        Returns\n        -------\n        key: str\n            The workload key of this compute DAG\n        \"\"\"\n        str_dag = _ffi_api.ComputeDAGPrintDAG(self, True)\n        hash_func = tvm._ffi.get_global_func(\n            \"auto_scheduler.compute_dag.hash_func\", allow_missing=True\n        )\n\n        if hash_func is None:\n            str_dag = str_dag.encode(\"utf-8\")\n            hash_key = hashlib.md5(str_dag).hexdigest()\n        else:\n            hash_key = hash_func(str_dag)\n\n        io_shapes = []\n        for tensor in self.tensors:\n            io_shapes.append(get_const_tuple(tensor.shape))\n        return json.dumps([hash_key] + io_shapes)\n\n    def __str__(self):\n        # pretty print\n        MAX_LINE_WIDTH = 256\n\n        raw_lines = super().__str__().split(\"\\n\")\n        lines = []\n        for line in raw_lines:\n            if len(line) > MAX_LINE_WIDTH:\n                line = (\n                    line[: MAX_LINE_WIDTH // 2] + \" ..(OMITTED).. \" + line[-MAX_LINE_WIDTH // 2 :]\n                )\n            lines.append(line)\n        return \"\\n\".join(lines)\n\n    def __getstate__(self):\n        return {\"tensors\": SaveJSON(self.tensors)}\n\n    def __setstate__(self, state):\n        # Since we always use tensors to recover the ComputeDAG, we do not support\n        # (de)serialization of the ComputeDAG constructed by a schedule.\n        self.__init_handle_by_constructor__(_ffi_api.ComputeDAG, LoadJSON(state[\"tensors\"]), None)\n\n\ndef get_shape_from_rewritten_layout(rewritten_layout, axis_names):\n    \"\"\"Get the orginal shape from a rewritten layout string.\n\n    Parameters\n    ----------\n    rewritten_layout: str\n        The layout after rewrite\n    axis_names: List[str]\n        Specify the order of axes by names\n\n    Returns\n    -------\n    shape: List[PrimExpr]\n        The original shape\n    \"\"\"\n    return _ffi_api.GetShapeFromRewrittenLayout(rewritten_layout, axis_names)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/cost_model/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\" Cost model that estimates the performance of programs \"\"\"\n\nfrom .cost_model import RandomModel\nfrom .xgb_model import XGBModel\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/cost_model/cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Cost models that estimate the performance of programs \"\"\"\nimport ctypes\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom .. import _ffi_api\n\n\n@tvm._ffi.register_object(\"auto_scheduler.CostModel\")\nclass CostModel(Object):\n    \"\"\"The base class for cost model\"\"\"\n\n\n@tvm._ffi.register_object(\"auto_scheduler.RandomModel\")\nclass RandomModel(CostModel):\n    \"\"\"A model that returns random estimation for all inputs\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_ffi_api.RandomModel)\n\n    def update(self, inputs, results):\n        \"\"\"Update the cost model according to new measurement results (training data).\n\n        Parameters\n        ----------\n        inputs : List[auto_scheduler.measure.MeasureInput]\n            The measurement inputs\n        results : List[auto_scheduler.measure.MeasureResult]\n            The measurement results\n        \"\"\"\n        _ffi_api.CostModelUpdate(self, inputs, results)\n\n    def predict(self, search_task, states):\n        \"\"\"Predict the scores of states\n\n        Parameters\n        ----------\n        search_task : SearchTask\n            The search task of states\n        states : List[State]\n            The input states\n\n        Returns\n        -------\n        scores: List[float]\n            The predicted scores for all states\n        \"\"\"\n        return [x.value for x in _ffi_api.CostModelPredict(self, search_task, states)]\n\n\n@tvm._ffi.register_func(\"auto_scheduler.cost_model.random_fill_float\")\ndef random_fill_float(size, return_ptr):\n    \"\"\"Fills a c++ float array with random numbers in [0, 1]\n\n    Parameters\n    ----------\n    size: int\n        The size of the array\n    return_ptr:\n        A pointer to a c++ float array\n    \"\"\"\n    if size == 0:\n        return\n    return_ptr = ctypes.cast(return_ptr, ctypes.POINTER(ctypes.c_float))\n    array_wrapper = np.ctypeslib.as_array(return_ptr, shape=(size,))\n    array_wrapper[:] = np.random.uniform(0, 1, (size,))\n\n\n@tvm._ffi.register_object(\"auto_scheduler.PythonBasedModel\")\nclass PythonBasedModel(CostModel):\n    \"\"\"Base class for cost models implemented in python\"\"\"\n\n    def __init__(self):\n        def update_func(inputs, results):\n            self.update(inputs, results)\n\n        def predict_func(task, states, return_ptr):\n            return_ptr = ctypes.cast(return_ptr, ctypes.POINTER(ctypes.c_float))\n            array_wrapper = np.ctypeslib.as_array(return_ptr, shape=(len(states),))\n            array_wrapper[:] = self.predict(task, states)\n\n        def predict_stage_func(task, states, return_ptr):\n            ret = self.predict_stages(task, states)\n            return_ptr = ctypes.cast(return_ptr, ctypes.POINTER(ctypes.c_float))\n            array_wrapper = np.ctypeslib.as_array(return_ptr, shape=ret.shape)\n            array_wrapper[:] = ret\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.PythonBasedModel, update_func, predict_func, predict_stage_func\n        )\n\n    def update(self, inputs, results):\n        \"\"\"Update the cost model according to new measurement results (training data).\n\n        Parameters\n        ----------\n        inputs : List[auto_scheduler.measure.MeasureInput]\n            The measurement inputs\n        results : List[auto_scheduler.measure.MeasureResult]\n            The measurement results\n        \"\"\"\n        raise NotImplementedError\n\n    def predict(self, task, states):\n        \"\"\"Predict the scores of states\n\n        Parameters\n        ----------\n        search_task : SearchTask\n            The search task of states\n        states : List[State]\n            The input states\n\n        Returns\n        -------\n        scores: List[float]\n            The predicted scores for all states\n        \"\"\"\n        raise NotImplementedError\n\n    def predict_stages(self, task, states):\n        \"\"\"Predict the scores of all stages in states. This is the breakdown version of `predict`.\n\n        Parameters\n        ----------\n        search_task : SearchTask\n            The search task of states\n        states : List[State]\n            The input states\n\n        Returns\n        -------\n        scores: List[float]\n            The predicted scores for all stages in all states in the packed format\n\n        Note\n        ----\n        For faster data copy between c++ and python, the python part returns scores in a\n        single flatten array using a packed format. The c++ part then unpacks the flatten array.\n\n        The packed format is:\n        {\n          float  scores[N];                 // scores[i] is the score for states[i].\n          int    n_stage_0;                 // the number of stages in states[0]\n          float  stage_scores_0[[n_stage_0] // the scores for all stages in states[0]\n          int    n_stage_1;                 // the number of stages in states[1]\n          float  stage_scores_1[n_stage_1]; // the scores for all stages in states[1]\n          ...\n          int    n_stage_i;                 // the number of stages in states[i]\n          float  stage_scores_1[n_stage_i]; // the scores for all stages in states[i]\n          ...  // until i == N - 1\n        }\n        To implement this format, we also store int as float, so we can store all numbers\n        into a single float array.\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/cost_model/xgb_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\"Cost model based on xgboost\"\"\"\nimport multiprocessing\nimport logging\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom tvm.autotvm.tuner.metric import max_curve\nfrom .cost_model import PythonBasedModel\nfrom ..feature import get_per_store_features_from_measure_pairs, get_per_store_features_from_states\nfrom ..measure_record import RecordReader\n\nxgb = None\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\nclass XGBDMatrixContext:\n    \"\"\"A global context to hold additional attributes of xgb.DMatrix\"\"\"\n\n    def __init__(self):\n        self.context_dict = defaultdict(dict)\n\n    def get(self, key, matrix, default=None):\n        \"\"\"\n        Get an attribute of a xgb.DMatrix\n        Parameters\n        ----------\n        key: str\n            The name of the attribute\n        matrix: xgb.DMatrix\n            The matrix\n        default: Optional[Any]\n            The default value if the item does not exist\n        \"\"\"\n        return self.context_dict[key].get(matrix.handle.value, default)\n\n    def set(self, key, matrix, value):\n        \"\"\"\n        Set an attribute for a xgb.DMatrix\n        Parameters\n        ----------\n        key: str\n            The name of the attribute\n        matrix: xgb.DMatrix\n            The matrix\n        value: Optional[Any]\n            The new value\n        \"\"\"\n        self.context_dict[key][matrix.handle.value] = value\n\n\ndmatrix_context = XGBDMatrixContext()\n\n\nclass XGBModel(PythonBasedModel):\n    \"\"\"Train a XGBoost model to predict the normalized throughputs of programs.\n    Let the normalized throughput be the score of a program (higher is better). We predict\n    the (approximate) score of a program = the sum of the scores of all stages in this program.\n    i.e. score(P) = score_s0 + score_s1 + ... + score_sn,\n    where score_si is the score of Stage i in Program P.\n    We extract feature for each stage and let the xgboost predict the score for each stage.\n    We then sum up the predictions as the score of the whole program.\n    We use RMSE as the loss function.  i.e. loss(P, y) = 1/2 * (score(P) - y)^2,\n    where P is the program and y is the normalized throughput according to\n    the ground truth (measurement).\n    XGBoost does not support this loss function because `score(P)` is a sum of the prediction\n    of several samples, so we implemented a custom loss function and call it pack-sum-rmse.\n    It is called \"pack-sum\" because we combine several samples into a \"pack\" and sum up\n    their predictions.\n\n    Parameters\n    ----------\n    verbose_eval: int = 25\n        Print training log every `verbose_eval` iterations.\n    num_warmup_sample: int = 100\n        The minimum number of samples to start to use the trained model.\n        If the number of samples is less than this number, the model outputs random predictions.\n    seed: Optional[int]\n        The random seed\n    model_file: Optional[str]\n        If is not None, save model to this file after every update.\n    adaptive_training: bool = False\n        Whether to use adaptive training, which reduces the training frequency when there are\n        too many logs.\n    \"\"\"\n\n    def __init__(\n        self,\n        verbose_eval=25,\n        num_warmup_sample=100,\n        seed=None,\n        model_file=None,\n        adaptive_training=False,\n    ):\n        global xgb\n        try:\n            if xgb is None:\n                xgb = __import__(\"xgboost\")\n        except ImportError:\n            # add \"from Node\" to silence\n            # \"During handling of the above exception, another exception occurred\"\n            raise ImportError(\n                \"XGBoost is required for XGBModel. \"\n                \"Please install its python package first. \"\n                \"Help: (https://xgboost.readthedocs.io/en/latest/) \"\n            ) from None\n\n        self.xgb_params = {\n            \"max_depth\": 10,\n            \"gamma\": 0.001,\n            \"min_child_weight\": 0,\n            \"eta\": 0.2,\n            # todo(merrymercy): automatically decrease learning rate when the loss is too large\n            \"n_gpus\": 0,\n            \"nthread\": multiprocessing.cpu_count() // 2,\n            \"verbosity\": 0,\n            \"seed\": seed or 43,\n            \"disable_default_eval_metric\": 1,\n        }\n        self.bst = None\n        self.plan_size = 32\n        self.num_warmup_sample = num_warmup_sample\n        self.verbose_eval = verbose_eval\n        self.model_file = model_file\n        self.adaptive_training = adaptive_training\n\n        super().__init__()\n\n        # cache measurement input/result pairs and extracted features\n        self.inputs = []\n        self.results = []\n        self.last_train_length = 0\n        self.inputs_feature_cache = []\n\n    def update(self, inputs, results):\n        \"\"\"Update the cost model according to new measurement results (training data).\n        XGBoost does not support incremental training, so we re-train a new model every time.\n        Parameters\n        ----------\n        inputs : List[MeasureInput]\n            The measurement inputs\n        results : List[MeasureResult]\n            The measurement results\n        \"\"\"\n        if len(inputs) <= 0:\n            return\n        assert len(inputs) == len(results)\n\n        self.inputs.extend(inputs)\n        self.results.extend(results)\n\n        if (\n            self.adaptive_training\n            and len(self.inputs) - self.last_train_length < self.last_train_length / 5\n        ):\n            # Set a training threshold related to `last_train_length` to reduce the training\n            # overhead when there're too many logs\n            return\n        self.last_train_length = len(self.inputs)\n\n        # extract feature\n        n_cached = len(self.inputs_feature_cache)\n        features, normalized_throughputs, task_ids = get_per_store_features_from_measure_pairs(\n            self.inputs, self.results, skip_first_n_feature_extraction=n_cached\n        )\n        if n_cached > 0:\n            features = list(features)\n            features[:n_cached] = self.inputs_feature_cache\n            features = np.array(features, dtype=object)\n        self.inputs_feature_cache = features\n        dtrain = pack_sum_xgbmatrix(\n            features, normalized_throughputs, task_ids, normalized_throughputs\n        )\n\n        # train xgb model\n        self.bst = xgb.train(\n            self.xgb_params,\n            dtrain,\n            num_boost_round=10000,\n            obj=pack_sum_square_error,\n            callbacks=[\n                custom_callback(\n                    stopping_rounds=50,\n                    metric=\"tr-p-rmse\",\n                    fevals=[\n                        pack_sum_rmse,\n                        pack_sum_average_peak_score(self.plan_size),\n                    ],\n                    evals=[(dtrain, \"tr\")],\n                    maximize=False,\n                    verbose_eval=self.verbose_eval,\n                )\n            ],\n        )\n\n        # Update the model file if it has been set\n        if self.model_file:\n            self.save(self.model_file)\n\n    def predict(self, task, states):\n        \"\"\"Predict the scores of states\n        Parameters\n        ----------\n        search_task : SearchTask\n            The search task of states\n        statse : List[State]\n            The input states\n        Returns\n        -------\n        scores: List[float]\n            The predicted scores for all states\n        \"\"\"\n        features = get_per_store_features_from_states(states, task)\n        if self.bst is not None and len(self.inputs) > self.num_warmup_sample:\n            dtest, pack_ids = feature_to_pack_sum_xgbmatrix(features)\n            raw_preds = self.bst.predict(dtest)\n            ret = predict_throughput_pack_sum(raw_preds, pack_ids)\n        else:\n            ret = np.random.uniform(0, 1, (len(states),))\n\n        # Predict -inf for invalid states that failed to be lowered.\n        for idx, feature in enumerate(features):\n            if feature.min() == feature.max() == 0:\n                ret[idx] = float(\"-inf\")\n\n        return ret\n\n    def predict_stages(self, task, states):\n        \"\"\"Predict the scores of all stages in states. This is the breakdown version of `predict`.\n\n        Parameters\n        ----------\n        search_task : SearchTask\n            The search task of states\n        statse : List[State]\n            The input states\n\n        Returns\n        -------\n        scores: List[float]\n            The predicted scores for all stages in all states in the packed format\n\n        Note\n        ----\n        For faster data copy between c++ and python, the python part returns scores in a\n        single flatten array using a packed format. The c++ part then unpacks the flatten array.\n        The packed format is:\n        {\n\n          float  scores[N];                 // scores[i] is the score for states[i].\n          int    n_stage_0;                 // the number of stages in states[0]\n          float  stage_scores_0[[n_stage_0] // the scores for all stages in states[0]\n          int    n_stage_1;                 // the number of stages in states[1]\n          float  stage_scores_1[n_stage_1]; // the scores for all stages in states[1]\n          ...\n          int    n_stage_i;                 // the number of stages in states[i]\n          float  stage_scores_1[n_stage_i]; // the scores for all stages in states[i]\n          ...  // untill i == N - 1\n\n        }\n        To implement this format, we also store int as float, so we can store all numbers\n        into a single float array.\n        \"\"\"\n        features = get_per_store_features_from_states(states, task)\n        if self.bst is not None and len(self.inputs) > self.num_warmup_sample:\n            dtest, pack_ids = feature_to_pack_sum_xgbmatrix(features)\n            raw_preds = self.bst.predict(dtest)\n            breakdown = predict_throughput_pack_sum(raw_preds, pack_ids)\n            stage_scores = [[] for _ in range(len(states))]\n            for pred, pack_id in zip(raw_preds, pack_ids):\n                stage_scores[pack_id].append(pred)\n            for idx, stage_score in enumerate(stage_scores):\n                breakdown = np.append(breakdown, len(stage_score))\n                breakdown = np.concatenate((breakdown, np.array(stage_score)))\n        else:\n            breakdown = np.concatenate(\n                (\n                    np.random.uniform(0, 1, (len(states),)),\n                    np.zeros(\n                        len(states),\n                    ),\n                )\n            )\n\n        # Predict 0 for invalid states that failed to be lowered.\n        for idx, feature in enumerate(features):\n            if feature.min() == feature.max() == 0:\n                breakdown[idx] = float(\"-inf\")\n\n        return breakdown\n\n    def update_from_file(self, file_name, n_lines=None):\n        \"\"\"Load measure records from a log file to update the cost model.\n        This function can be used to pre-train the cost model with history log files.\n        Parameters\n        ----------\n        file_name: str\n            The filename\n        n_lines: Optional[int]\n            Only load first n lines of the log file\n        \"\"\"\n        inputs, results = RecordReader(file_name).read_lines(n_lines)\n        logger.info(\"XGBModel: Loaded %s measurement records from %s\", len(inputs), file_name)\n        self.update(inputs, results)\n\n    def save(self, file_name: str):\n        \"\"\"Save the model to a file\n        Parameters\n        ----------\n        file_name: str\n            The filename\n        \"\"\"\n        self.bst.save_model(file_name)\n\n    def load(self, file_name: str):\n        \"\"\"Load the model from a file\n        Parameters\n        ----------\n        file_name: str\n            The filename\n        \"\"\"\n        if self.bst is None:\n            self.bst = xgb.Booster(self.xgb_params)\n        self.bst.load_model(file_name)\n        self.num_warmup_sample = -1\n\n\ndef feature_to_pack_sum_xgbmatrix(xs):\n    \"\"\"Convert an extracted multi-stage feature vector to a xgbmatrx in pack-sum format\n    Parameters\n    ----------\n    xs: np.ndarray\n        The feature vector\n    Returns\n    -------\n    dmatrix: xgb.DMatrix\n        The DMatrix\n    pack_ids: List[int]\n        pack ids information\n    \"\"\"\n    x_flatten = []\n    pack_ids = []\n\n    for ct, x in enumerate(xs):\n        for row in x:\n            x_flatten.append(row)\n            pack_ids.append(ct)\n\n    return xgb.DMatrix(np.array(x_flatten)), pack_ids\n\n\ndef pack_sum_xgbmatrix(xs, ys, gids=None, weights=None):\n    \"\"\"Convert (feature, label) pairs into a xgb matrix with pack-sum format\n    Parameters\n    ----------\n    xs: np.ndarray\n        The feature vector\n    ys: np.ndarray\n        The normaizlied throughput\n    gids: Optional[List[int]]\n        Group id (task id)\n    weights: Optional[np.ndarray]\n        The weight of samples\n    Returns\n    -------\n    dmatrix: xgb.DMatrix\n        The DMatrix with pack-sum information\n    \"\"\"\n    if gids is not None:\n        # sort by group\n        indices = gids.argsort()\n        xs, ys = xs[indices], ys[indices]\n        group_sizes = np.bincount(gids)\n        if weights is not None:\n            weights = weights[indices]\n    else:\n        # assume it has only one group\n        group_sizes = [len(xs)]\n\n    x_flatten = []\n    y_flatten = []\n    weights_flatten = []\n    pack_ids = []\n\n    if weights is not None:\n        for ct, (x, y, w) in enumerate(zip(xs, ys, weights)):\n            for row in x:\n                x_flatten.append(row)\n                y_flatten.append(y)\n                weights_flatten.append(w)\n                pack_ids.append(ct)\n    else:\n        for ct, (x, y) in enumerate(zip(xs, ys)):\n            for row in x:\n                x_flatten.append(row)\n                y_flatten.append(y)\n                pack_ids.append(ct)\n\n    ret = xgb.DMatrix(np.array(x_flatten), y_flatten)\n    if weights is not None:\n        ret.set_weight(weights_flatten)\n    dmatrix_context.set(\"pack_ids\", ret, np.array(pack_ids))\n    dmatrix_context.set(\"group_sizes\", ret, group_sizes)\n    return ret\n\n\ndef predict_throughput_pack_sum(raw_preds, pack_ids):\n    \"\"\"Predict the throughputs for predictions in pack-sum format\n    Parameters\n    ----------\n    raw_preds: np.ndarray\n        The raw predictions\n    pack_ids: List[int]\n        The pack id for predictions\n    Returns\n    -------\n    throughputs: np.ndarray\n        The throughput\n    \"\"\"\n    sum_pred = np.bincount(pack_ids, weights=raw_preds)\n    return sum_pred\n\n\ndef pack_sum_square_error(preds, dtrain):\n    \"\"\"Implement square error loss on pack-sum format as\n     a custom objective function for xgboost.\n    Parameters\n    ----------\n    preds: np.ndarray\n        The predicitons\n    dtrain: xgb.DMatrix\n        The training set\n    Returns\n    -------\n    gradient: np.ndarray\n    hessian: np.ndarray\n        gradient and hessian according to the xgboost format\n    \"\"\"\n    pack_ids = dmatrix_context.get(\"pack_ids\", dtrain)\n    weight = dtrain.get_weight()\n\n    sum_pred = np.bincount(pack_ids, weights=preds)\n    x = sum_pred[pack_ids]\n    y = dtrain.get_label()\n    gradient = x - y\n    hessian = np.ones_like(gradient)\n\n    if len(weight) == 0:\n        return gradient, hessian\n\n    return gradient * weight, hessian * weight\n\n\ndef pack_sum_rmse(raw_preds, labels):\n    \"\"\"Evaluate RMSE (rooted mean square error) in the pack-sum format\n    Parameters\n    ----------\n    raw_preds: np.ndarray\n        The raw prediction\n    labels: xgb.DMatrix\n        The groud-truth label matrix\n    Returns\n    -------\n    name: str\n    score: float\n        The name and score of this metric\n    \"\"\"\n    pack_ids = dmatrix_context.get(\"pack_ids\", labels)\n    preds = predict_throughput_pack_sum(raw_preds, pack_ids)[pack_ids]\n    return \"p-rmse\", np.sqrt(np.mean(np.square((preds - labels.get_label()))))\n\n\ndef pack_sum_average_peak_score(N):\n    \"\"\"Return the evaluation function for average-peak-score@N\n    Parameters\n    ----------\n    N: int\n        The \"N\" in \"average-peak-score@N\"\n    Returns\n    -------\n    The evaluation function\n    \"\"\"\n\n    def feval(preds, labels):\n        \"\"\"Evaluate average-peak-score@N in the pack-sum format\n        Parameters\n        ----------\n        raw_preds: np.ndarray\n            The raw prediction\n        labels: xgb.DMatrix\n            The groud-truth label matrix\n        Returns\n        -------\n        name: str\n        score: float\n        The name and score of this metric\n        \"\"\"\n        group_sizes = dmatrix_context.get(\"group_sizes\", labels, [len(preds)])\n        pack_ids = dmatrix_context.get(\"pack_ids\", labels)\n\n        preds = predict_throughput_pack_sum(preds, pack_ids)\n        labels = (\n            np.bincount(pack_ids, weights=labels.get_label())\n            / np.unique(pack_ids, return_counts=True)[1]\n        )\n\n        scores = []\n        offset = 0\n        for size in group_sizes:\n            preds_group = preds[offset : offset + size]\n            labels_group = labels[offset : offset + size]\n            offset += size\n\n            trials = np.argsort(preds_group)[::-1][:N]\n            trial_scores = labels_group[trials]\n            curve = max_curve(trial_scores) / np.max(labels_group)\n            scores.append(np.mean(curve))\n        return \"a-peak@%d\" % N, np.mean(scores)\n\n    return feval\n\n\ndef custom_callback(\n    stopping_rounds,\n    metric,\n    fevals,\n    evals=(),\n    log_file=None,\n    maximize=False,\n    verbose_eval=True,\n    skip_every=2,\n):\n    \"\"\"Callback function for xgboost to support multiple custom evaluation functions\"\"\"\n    # pylint: disable=import-outside-toplevel\n    from xgboost.core import EarlyStopException\n    from xgboost.callback import _fmt_metric\n\n    try:\n        from xgboost.training import aggcv\n    except ImportError:\n        from xgboost.callback import _aggcv as aggcv\n\n    state = {}\n    metric_shortname = metric.split(\"-\")[1]\n\n    def init(env):\n        \"\"\"internal function\"\"\"\n        bst = env.model\n\n        state[\"maximize_score\"] = maximize\n        state[\"best_iteration\"] = 0\n        if maximize:\n            state[\"best_score\"] = float(\"-inf\")\n        else:\n            state[\"best_score\"] = float(\"inf\")\n\n        if bst is not None:\n            if bst.attr(\"best_score\") is not None:\n                state[\"best_score\"] = float(bst.attr(\"best_score\"))\n                state[\"best_iteration\"] = int(bst.attr(\"best_iteration\"))\n                state[\"best_msg\"] = bst.attr(\"best_msg\")\n            else:\n                bst.set_attr(best_iteration=str(state[\"best_iteration\"]))\n                bst.set_attr(best_score=str(state[\"best_score\"]))\n        else:\n            assert env.cvfolds is not None\n\n    def callback(env):\n        \"\"\"internal function\"\"\"\n        if not state:\n            init(env)\n\n        bst = env.model\n        i = env.iteration\n        cvfolds = env.cvfolds\n\n        res_dict = {}\n\n        if i % skip_every == 1:\n            return\n\n        ##### evaluation #####\n        if cvfolds is not None:\n            for feval in fevals:\n                tmp = aggcv([f.eval(i, feval) for f in cvfolds])\n                for k, mean, std in tmp:\n                    res_dict[k] = [mean, std]\n        else:\n            for feval in fevals:\n                bst_eval = bst.eval_set(evals, i, feval)\n                res = [x.split(\":\") for x in bst_eval.split()]\n                for kv in res[1:]:\n                    res_dict[kv[0]] = [float(kv[1])]\n\n        eval_res = []\n        keys = list(res_dict.keys())\n        keys.sort(key=lambda x: x if metric_shortname not in x else \"a\" + x)\n        for key in keys:\n            v = res_dict[key]\n            eval_res.append([key] + v)\n\n        ##### print eval result #####\n        if not isinstance(verbose_eval, bool) and verbose_eval and i % verbose_eval == 0:\n            infos = [\"XGB iter: %3d\" % i]\n            for item in eval_res:\n                if \"null\" in item[0]:\n                    continue\n                infos.append(\"%s: %.6f\" % (item[0], item[1]))\n\n            logger.debug(\"\\t\".join(infos))\n            if log_file:\n                with open(log_file, \"a\") as fout:\n                    fout.write(\"\\t\".join(infos) + \"\\n\")\n\n        ##### choose score and do early stopping #####\n        score = None\n        for item in eval_res:\n            if item[0] == metric:\n                score = item[1]\n                break\n        assert score is not None\n\n        best_score = state[\"best_score\"]\n        best_iteration = state[\"best_iteration\"]\n        maximize_score = state[\"maximize_score\"]\n        if (maximize_score and score > best_score) or (not maximize_score and score < best_score):\n            msg = \"[%d] %s\" % (env.iteration, \"\\t\".join([_fmt_metric(x) for x in eval_res]))\n            state[\"best_msg\"] = msg\n            state[\"best_score\"] = score\n            state[\"best_iteration\"] = env.iteration\n            # save the property to attributes, so they will occur in checkpoint.\n            if env.model is not None:\n                env.model.set_attr(\n                    best_score=str(state[\"best_score\"]),\n                    best_iteration=str(state[\"best_iteration\"]),\n                    best_msg=state[\"best_msg\"],\n                )\n        elif env.iteration - best_iteration >= stopping_rounds:\n            best_msg = state[\"best_msg\"]\n            if verbose_eval and env.rank == 0:\n                logger.debug(\"XGB stopped. Best iteration: %s \", best_msg)\n            raise EarlyStopException(best_iteration)\n\n    return callback\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/dispatcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe global context that dispatches best schedules to workloads.\n\nIn auto-scheduler, a state (loop_state.py::StateObject) saves the\nschedule configuration by its transform_steps, so a state is used\nas a schedule configuration here.\n\"\"\"\n# pylint: disable=invalid-name\n\nimport logging\nimport pathlib\nfrom collections.abc import Iterable\n\nimport numpy as np\n\nfrom tvm.contrib.utils import tempdir\nfrom tvm.tir.expr import FloatImm\nfrom .cost_model import RandomModel, XGBModel\nfrom .measure import LocalRPCMeasureContext\nfrom .measure_record import RecordToFile, load_records\nfrom .search_policy import PreloadMeasuredStates, SketchPolicy\nfrom .search_task import SearchTask, TuningOptions\nfrom .utils import calc_workload_dis_factor, decode_workload_key\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\nclass DispatchContext(object):\n    \"\"\"\n    Base class of dispatch context.\n    \"\"\"\n\n    current = None\n\n    def __init__(self):\n        self._old_ctx = DispatchContext.current\n\n    def query(self, target, workload_key, has_complex_op, dag, func_name):\n        \"\"\"\n        Query the context to get the specific config for a workload.\n        If this function cannot find the result inside this context, it will query the result\n        from the upper contexts.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload_key : str\n            The workload key\n        has_complex_op: bool\n            Whether this workload has at least one complex op.\n        dag: ComputeDAG\n            The ComputeDAG of the workload.\n        func_name: str\n            The function name of this workload.\n\n        Returns\n        -------\n        state : StateObject\n            The state that stores schedule configuration for the workload\n        \"\"\"\n        ret = self._query_inside(target, workload_key, func_name)\n        if ret is None:\n            ret = self._old_ctx.query(target, workload_key, has_complex_op, dag, func_name)\n        return ret\n\n    def update(self, target, workload_key, state):\n        \"\"\"\n        Update the config for a workload\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload_key : str\n            The current workload_key.\n        state : StateObject\n            The state that stores schedule configuration for the workload\n        \"\"\"\n        raise NotImplementedError()\n\n    def _query_inside(self, target, workload_key, func_name):\n        \"\"\"\n        Query the context to get the specific config for a workload.\n        This function only query config inside this context.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload_key : str\n            The current workload_key.\n        func_name: str\n            The function name of this workload.\n\n        Returns\n        -------\n        state : StateObject\n            The schedule configuration for the workload\n        \"\"\"\n        raise NotImplementedError()\n\n    def __enter__(self):\n        self._old_ctx = DispatchContext.current\n        DispatchContext.current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        DispatchContext.current = self._old_ctx\n\n\nclass ApplyHistoryBest(DispatchContext):\n    \"\"\"\n    Apply the history best config\n\n    Parameters\n    ----------\n    records : str, list of str, or iterator of (auto_scheduler.measure.MeasureInput,\\\n                                                auto_scheduler.measure.MeasureResult)\n        Collection of tuning records.\n        If is str, then it should be the filename of a records log file.\n        Each row of this file is an encoded record pair. If it is an iterator,\n        it can either be a set of str filenames which will be applied jointly,\n        or a set of (input, result) tuples.\n    n_lines: Optional[int]\n        if it is not None, only load the first `n_lines` lines of log.\n    include_compatible: bool\n        When set to True, compatible records will also be considered.\n    \"\"\"\n\n    def __init__(self, records, n_lines=None, include_compatible=False):\n        super(ApplyHistoryBest, self).__init__()\n        self.include_compatible = include_compatible\n\n        # Dict[str (target key),\n        #   Dict[str (workload hash),\n        #     Dict[tuple (workload args), tuple (State, cost)]]]\n        self.best_by_targetkey = {}\n        self.best_by_model = {}\n        self._best_user_defined = {}\n\n        self.load(records, n_lines)\n\n    @staticmethod\n    def get_workload_entry(best_records, target_key, workload_key):\n        \"\"\"Get the entry of the target key and workload key hash in the given best record map.\n\n        Parameters\n        ----------\n        best_records: Dict[str, Dict[str, Dict[str, Any]]]\n            The best record map.\n        target_key: str\n            The first key to the best_records.\n        workload_key: str\n            The workload key that can be decoded to workload hash and args.\n\n        Returns\n        -------\n        entry: Dict[str, Any]\n            The entry in best_records with target key and workload hash.\n        workload_hash: str\n            The workload hash decoded from workload_key.\n        workload_args: Tuple[Any, ...]\n            The hashable tuple of workload args decoded from workload_key.\n        \"\"\"\n        workload_hash, workload_args = decode_workload_key(workload_key)\n        if target_key not in best_records:\n            best_records[target_key] = {}\n        if workload_hash not in best_records[target_key]:\n            best_records[target_key][workload_hash] = {}\n        return best_records[target_key][workload_hash], workload_hash, workload_args\n\n    def load(self, records, n_lines=None):\n        \"\"\"Load records to this dispatch context\n\n        Parameters\n        ----------\n        records : str or iterator of (auto_scheduler.measure.MeasureInput,\\\n                                      auto_scheduler.measure.MeasureResult)\n            Collection of tuning records.\n            If is str, then it should be the filename of a records log file.\n            Each row of this file is an encoded record pair. Otherwise, it is an iterator.\n        n_lines: Optional[int]\n            if it is not None, only load the first `n_lines` lines of log\n        \"\"\"\n        joint_records = []\n        if not isinstance(records, Iterable) or isinstance(records, str):\n            records = [records]\n\n        for rec in records:\n            if isinstance(rec, pathlib.Path):\n                rec = str(rec)\n\n            if isinstance(rec, str):\n                rec = load_records(rec)\n                joint_records += rec\n            else:\n                if rec is not None:\n                    joint_records.append(rec)\n\n        if not joint_records:\n            return\n\n        best_by_targetkey = self.best_by_targetkey\n        best_by_model = self.best_by_model\n\n        counter = 0\n        for inp, res in joint_records:\n            if n_lines is not None and counter >= n_lines:\n                break\n            counter += 1\n            if res.error_no != 0:\n                continue\n\n            costs = [x.value for x in res.costs if isinstance(x, FloatImm)]\n            cost = np.mean(costs)\n\n            # use target keys in tvm target system as key to build best map\n            for k in inp.task.target.keys:\n                entry, _, workload_args = self.get_workload_entry(\n                    best_by_targetkey, k, inp.task.workload_key\n                )\n                if workload_args not in entry:\n                    entry[workload_args] = (inp.state, cost)\n                else:\n                    _, other_cost = entry[workload_args]\n                    if other_cost > cost:\n                        entry[workload_args] = (inp.state, cost)\n\n            # use model as key to build best map\n            entry, _, workload_args = self.get_workload_entry(\n                best_by_model, inp.task.target.model, inp.task.workload_key\n            )\n            if workload_args not in entry:\n                if inp.task.target.model != \"unknown\":\n                    entry[workload_args] = (inp.state, cost)\n            else:\n                _, other_cost = entry[workload_args]\n                if other_cost > cost:\n                    entry[workload_args] = (inp.state, cost)\n\n        logger.debug(\"Finish loading %d records\", counter)\n\n    def _query_inside(self, target, workload_key, func_name):\n        if target is None:\n            raise RuntimeError(\n                \"Need a target context to find the history best. \"\n                \"Hint: If your target is llvm, use `with tvm.target.create('llvm'):`\"\n                \" above the dispatcher call. So does other target. \"\n            )\n\n        def match_record(best_records, target_key, workload_key):\n            \"\"\"The helper function to match the record in the given map\n            and return the matched state, or None if no match.\n            \"\"\"\n            ret = None\n\n            entry, workload_hash, workload_args = self.get_workload_entry(\n                best_records, target_key, workload_key\n            )\n            if workload_args in entry:\n                ret = entry[workload_args][0]\n            elif self.include_compatible:\n                best_cost = float(\"inf\")\n                for args, val in entry.items():\n                    dis_f = calc_workload_dis_factor(\n                        (workload_hash, workload_args), (workload_hash, args)\n                    )\n                    if dis_f == float(\"inf\"):\n                        continue\n\n                    state, cost = val\n                    cost *= dis_f\n                    if ret is None or cost < best_cost:\n                        best_cost = cost\n                        ret = state\n            return ret\n\n        # first try matching by model\n        ret = match_record(self._best_user_defined, target.model, workload_key)\n        if ret is not None:\n            return ret\n        ret = match_record(self.best_by_model, target.model, workload_key)\n        if ret is not None:\n            return ret\n\n        # then try matching by target key\n        for k in target.keys:\n            ret = match_record(self._best_user_defined, k, workload_key)\n            if ret is not None:\n                return ret\n            ret = match_record(self.best_by_targetkey, k, workload_key)\n            if ret is not None:\n                return ret\n\n        return None\n\n    def update(self, target, workload_key, state):\n        entry, _, workload_args = self.get_workload_entry(\n            self._best_user_defined, target.model, workload_key\n        )\n        entry[workload_args] = (state, 1)\n\n        for k in target.keys:\n            entry, _, _ = self.get_workload_entry(self._best_user_defined, k, workload_key)\n            entry[workload_args] = (state, 1)\n\n\nclass ApplyHistoryBestOrSample(ApplyHistoryBest):\n    \"\"\"\n    Apply the history best config, or sample a valid schedule if no config is found.\n\n    Parameters\n    ----------\n    records : str or iterator of (auto_scheduler.measure.MeasureInput,\\\n                                  auto_scheduler.measure.MeasureResult)\n        Collection of tuning records.\n        If is str, then it should be the filename of a records log file.\n        Each row of this file is an encoded record pair. Otherwise, it is an iterator.\n    sample_simple_workloads: bool\n        When False, sampling will not apply to simple workloads (w/o reduction).\n    cost_model_file: str\n        The filename of the pre-trained XGBoost cost model. If not present, then random\n        model will be used.\n    num_measure: int\n        Meausre the top-N rank of sampled schedules on the device. The default -1 means\n        no measurement and simply return the top-1 schedule ranked by the cost model.\n    \"\"\"\n\n    def __init__(\n        self, records, sample_simple_workloads=False, cost_model_file=None, num_measure=-1\n    ):\n        self.sample_simple_workloads = sample_simple_workloads\n        self.num_measure = num_measure\n        self.log_dir = tempdir()\n        if cost_model_file is None:\n            self.cost_model = RandomModel()\n        else:\n            self.cost_model = XGBModel()\n            self.cost_model.load(cost_model_file)\n\n        super(ApplyHistoryBestOrSample, self).__init__(\n            records, n_lines=None, include_compatible=True\n        )\n\n    def query(self, target, workload_key, has_complex_op, dag, func_name):\n        if has_complex_op or self.sample_simple_workloads:\n            ret = self._query_inside(target, workload_key, func_name)\n        else:\n            ret = super(ApplyHistoryBestOrSample, self)._query_inside(\n                target, workload_key, func_name\n            )\n\n        if ret is None:\n            ret = self._old_ctx.query(target, workload_key, has_complex_op, dag, func_name)\n        return ret\n\n    def _query_inside(self, target, workload_key, func_name):\n        ret = super(ApplyHistoryBestOrSample, self)._query_inside(target, workload_key, func_name)\n        if ret is not None:\n            return ret\n\n        # Sampling valid schedules when no existing records can be used.\n        task = SearchTask(workload_key=workload_key, target=target)\n        measure_ctx = LocalRPCMeasureContext(min_repeat_ms=300)\n\n        log_file = self.log_dir.relpath(\"%s.log\" % decode_workload_key(workload_key)[0])\n\n        while ret is None:\n            tune_option = TuningOptions(\n                num_measure_trials=self.num_measure,\n                runner=measure_ctx.runner,\n                measure_callbacks=[RecordToFile(log_file)],\n                verbose=0,\n            )\n            search_policy = SketchPolicy(\n                task,\n                self.cost_model,\n                params={\n                    \"eps_greedy\": 0.01,\n                    \"sample_init_min_population\": 64,\n                    \"evolutionary_search_num_iters\": 0,\n                },\n                init_search_callbacks=[PreloadMeasuredStates(log_file)],\n                verbose=0,\n            )\n            task.tune(tune_option, search_policy)\n\n            # Load the sampled records and query again.\n            self.load(log_file)\n            ret = super(ApplyHistoryBestOrSample, self)._query_inside(\n                target, workload_key, func_name\n            )\n\n        del measure_ctx\n        return ret\n\n\nclass FallbackContext(DispatchContext):\n    \"\"\"\n    A fallback dispatch context.\n    This is used as the root context.\n    \"\"\"\n\n    def __init__(self):\n        super(FallbackContext, self).__init__()\n        self.memory = {}\n\n        # Verbose level:\n        # 0: Completely silent.\n        # 1: Warning the missing configs for querying complex tasks.\n        # 2: Warning the missing configs for querying all tasks.\n        self.verbose = 1\n\n        # a set to prevent print duplicated message\n        self.messages = set()\n\n    def query(self, target, workload_key, has_complex_op, dag, func_name):\n        key = (str(target), workload_key)\n        if key in self.memory:\n            return self.memory[key]\n\n        if self.verbose == 2 or (has_complex_op and self.verbose == 1):\n            msg = (\n                f\"-----------------------------------\\n\"\n                f\"{func_name}\\n\"\n                f\"Cannot find tuned schedules for target={target}, workload_key={workload_key}. \"\n                f\"A fallback TOPI schedule is used, \"\n                f\"which may bring great performance regression or even compilation failure. \"\n                f\"Compute DAG info:\\n{dag}\"\n            )\n            if msg not in self.messages:\n                self.messages.add(msg)\n                logger.warning(msg)\n\n        state = None\n\n        # cache this config to avoid duplicated warning message\n        self.memory[key] = state\n        return state\n\n    def _query_inside(self, target, workload_key, func_name):\n        _ = target = workload_key = func_name\n        raise RuntimeError(\"This function should never be called\")\n\n    def update(self, target, workload_key, state):\n        key = (str(target), workload_key)\n        self.memory[key] = state\n\n\nDispatchContext.current = FallbackContext()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\"\nPython API for Feature extraction. The extracted features vector are used by cost models.\n\nWe extract one feature vector per BufferStoreNode statement in a TIR Stmt,\nso we call this feature as \"per-store\" feature.\nThe cost model also does prediction for each BufferStoreNode statement and aggregates\nthe predicted score of each BufferStoreNode as the score of a TIR Stmt.\n\nThe feature specification is defined by `src/auto_scheduler/feature.cc::FeatureSet`\n\"\"\"\n\nfrom typing import List, Tuple, Union, Optional, Dict\nimport struct\n\nimport numpy as np\n\nfrom .loop_state import State, StateObject\nfrom .measure import MeasureInput, MeasureResult\nfrom . import _ffi_api\nfrom ..tir import PrimFunc\n\n# The maximum number of extracted buffers for one statement\nDEFAULT_MAX_N_BUFS = 5\n\n# The length of the feature vector\nDEFAULT_FEATURE_VEC_LEN = 164\n\n# The size of int and float in bytes\nSIZE_OF_INT32 = 4\nSIZE_OF_FLOAT32 = 4\n\n\ndef unpack_feature(byte_arr: bytearray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n    \"\"\"Unpack the flatten feature (in byte array format) from c++\n\n    Parameters\n    ----------\n    byte_arr: bytearray\n        The two-dimensional feature vector in serialized byte array format\n\n    Returns\n    -------\n    features: np.ndarray\n        Feature vectors\n    normalized_throughputs: np.ndarray\n        Normalized throughputs\n    task_ids: np.ndarray\n        Task ids\n\n    Note\n    ----\n    For faster data copy between c++ and python, the c++ part returns features in a single\n    flatten array using a packed format. The python part then unpacks the flatten array.\n\n    The packed format for n records is:\n    {\n      int   n;\n      int   sizes[n+2];           // The sizes for the following arrays\n\n      float features_0[size[0]];  // The features for record 0\n      float features_1[size[1]];  // The features for record 1\n      ...\n      float features_i[size[i]];  // The features for record i\n      ... // until i == n - 1\n\n      float throughputs[sizes[n]];  // The normalized throughputs for n records\n      int   task_ids[size[n+1]];    // The task ids for n records\n\n    }\n    To implement this format, we also store int as float, so we can store all numbers\n    into a single float array.\n    \"\"\"\n    vec_len = DEFAULT_FEATURE_VEC_LEN\n\n    # unpack sizes\n    offset = 0\n    n = struct.unpack_from(\"1i\", byte_arr, offset=offset)[0]\n    offset += SIZE_OF_INT32\n\n    sizes = struct.unpack_from(\"%di\" % (n + 2), byte_arr, offset=offset)\n    offset += SIZE_OF_INT32 * (n + 2)\n\n    # unpack features\n    features = []\n    for size in sizes[:-2]:\n        row = []\n\n        # Now, we need to unpack the feature for multiple statements.\n        # The format is:\n        # {\n        #   int   n_stage;                        // The number of stages\n        #   float feature_vecs[n_stage][vec_len]  // The feature vector for each stage\n        # }\n        # where vec_len can be calculated by `(size - 1) / n_stmts`\n\n        if size == 0:\n            # failed during lowering\n            features.append(np.zeros((1, vec_len)))\n        else:\n            n_stmts = struct.unpack_from(\"f\", byte_arr, offset=offset)\n            offset += SIZE_OF_FLOAT32\n\n            n_stmts = int(n_stmts[0] + 0.5)\n            tmp_vec_len = (size - 1) // n_stmts\n            assert (\n                tmp_vec_len == vec_len\n            ), \"The length of feature vector is wrong. Expected %d but got %d.\" % (\n                vec_len,\n                tmp_vec_len,\n            )\n            assert tmp_vec_len * n_stmts == size - 1\n            for _ in range(n_stmts):\n                x = struct.unpack_from(\"%df\" % vec_len, byte_arr, offset=offset)\n                offset += vec_len * SIZE_OF_FLOAT32\n                row.append(x)\n\n            features.append(np.array(row))\n\n    # unpack normalized_throughputs\n    m = sizes[-2]\n    normalized_throughputs = struct.unpack_from(\"%df\" % m, byte_arr, offset=offset)\n    offset += m * SIZE_OF_FLOAT32\n\n    # unpack task_ids\n    m = sizes[-1]\n    task_ids = struct.unpack_from(\"%di\" % m, byte_arr, offset=offset)\n    offset += m * SIZE_OF_INT32\n\n    assert offset == len(byte_arr), \"%d vs %d\" % (offset, len(byte_arr))\n    return np.array(features, dtype=object), np.array(normalized_throughputs), np.array(task_ids)\n\n\ndef get_per_store_features_from_file(\n    filename: str, max_lines: int, max_n_bufs: Optional[int] = None\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n    \"\"\"Get per-store features from a log file\n\n    Parameters\n    ----------\n    filename: str\n        The input filename\n    max_lines: int\n        Only extract the first n lines of the file\n    max_n_bufs: Optional[int]\n        The maximum number of extracted buffers for one statement\n\n    Returns\n    -------\n    features: np.ndarray\n        Feature vectors\n    normalized_throughputs: np.ndarray\n        Normalized throughputs\n    task_ids: np.ndarray\n        Task ids\n    \"\"\"\n    byte_arr = _ffi_api.GetPerStoreFeaturesFromFile(\n        filename, max_lines, max_n_bufs or DEFAULT_MAX_N_BUFS\n    )\n    return unpack_feature(byte_arr)\n\n\ndef get_per_store_features_from_measure_pairs(\n    inputs: List[MeasureInput],\n    results: List[MeasureResult],\n    skip_first_n_feature_extraction: int = 0,\n    max_n_bufs: Optional[int] = None,\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n    \"\"\"Get per-store features from measurement input/result pairs\n\n    Parameters\n    ----------\n    inputs: List[MeasureInput]\n        The measure inputs\n    results: List[MeasureResult]\n        The measure results\n    skip_first_n_feature_extraction: int\n        Skip feature extraction for the first n states\n    max_n_bufs: int\n        The maximum number of extracted buffers for one statement\n\n    Returns\n    -------\n    features: np.ndarray\n        Feature vectors\n    normalized_throughputs: np.ndarray\n        Normalized throughputs\n    task_ids: np.ndarray\n        Task ids\n    \"\"\"\n    byte_arr = _ffi_api.GetPerStoreFeaturesFromMeasurePairs(\n        inputs, results, skip_first_n_feature_extraction, max_n_bufs or DEFAULT_MAX_N_BUFS\n    )\n    return unpack_feature(byte_arr)\n\n\ndef get_per_store_features_from_states(\n    states: List[Union[State, StateObject]], task: \"SearchTask\", max_n_bufs: Optional[int] = None\n) -> np.ndarray:\n    \"\"\"Get per-store features from measurement input/result pairs\n\n    Parameters\n    ----------\n    states: List[Union[State, StateObject]]\n        The input states\n    task: SearchTask\n        The search task of the input states\n    max_n_bufs: Optional[int]\n        The maximum number of extracted buffers for one statement\n\n    Returns\n    -------\n    features: np.ndarray\n        Feature vectors\n    \"\"\"\n    if isinstance(states[0], State):\n        state_objects = [s.state_object for s in states]\n    elif isinstance(states[0], StateObject):\n        state_objects = states\n    byte_arr = _ffi_api.GetPerStoreFeaturesFromStates(\n        state_objects, task, max_n_bufs or DEFAULT_MAX_N_BUFS\n    )\n    return unpack_feature(byte_arr)[0]\n\n\ndef get_per_store_feature_names(max_n_bufs: Optional[int] = None) -> List[str]:\n    \"\"\"Get the name of every element in the feature vector. Use this for debug and inspection.\n\n    Parameters\n    ----------\n    max_n_bufs: int\n        The maximum number of extracted buffers for one statement\n\n    Returns\n    -------\n    names: List[str]\n        The names of elements in the flatten feature vector\n    \"\"\"\n    return _ffi_api.GetPerStoreFeatureNames(max_n_bufs or DEFAULT_MAX_N_BUFS)\n\n\ndef features_from_primfunc(\n    func: PrimFunc,\n    cache_line_bytes: int = 64,\n    max_n_bufs: Optional[int] = None,\n    log_scale: bool = False,\n) -> Optional[np.ndarray]:\n    \"\"\"Extract performance features from a PrimFunc.\n\n    Parameters\n    ----------\n    func: PrimFunc\n        PrimFunc from which features will be extracted. Each store operation to\n        a unique buffer in the function will result in one row of features in\n        the output.\n\n    cache_line_bytes: int, optional\n        Size of a cache line in bytes. Defaults to 64 which is the size for\n        most x86 processors.\n\n    max_n_bufs: int, optional\n        Maximum number of buffers in generated features. This determines the\n        length of the resulting feature vector.\n\n    log_scale: bool\n        Should entries in the feature vector be scaled by log2(x + 1). Defaults\n        to False. Use True if using features with a cost model.\n\n    Returns\n    -------\n    Optional[np.ndarray]\n        Output features, one row per store into a unique buffer statement in `func`.\n    \"\"\"\n    return _ffi_api.FeaturesFromPrimFunc(\n        func, cache_line_bytes, max_n_bufs or DEFAULT_MAX_N_BUFS, log_scale\n    ).numpy()\n\n\ndef named_features_from_primfunc(\n    func: PrimFunc,\n    cache_line_bytes: int = 64,\n    max_n_bufs: Optional[int] = None,\n    log_scale: bool = False,\n) -> Optional[Dict[str, np.ndarray]]:\n    \"\"\"Extract performance features and associated names from a PrimFunc.\n\n    Parameters\n    ----------\n    func: PrimFunc\n        PrimFunc from which features will be extracted. Each store operation to\n        a unique buffer in the function will result in one row of features in\n        the output.\n\n    cache_line_bytes: int, optional\n        Size of a cache line in bytes. Defaults to 64 which is the size for\n        most x86 processors.\n\n    max_n_bufs: int, optional\n        Maximum number of buffers in generated features. This determines the\n        length of the resulting feature vector.\n\n    log_scale: bool\n        Should entries in the feature vector be scaled by log2(x + 1). Defaults\n        to False. Use True if using features with a cost model.\n\n    Returns\n    -------\n    Optional[Dict[str, np.ndarray]]\n        Mapping from feature name to features. One element per store into a\n        unique buffer statement in `func`.\n    \"\"\"\n    features = features_from_primfunc(func, cache_line_bytes, max_n_bufs, log_scale)\n    names = get_per_store_feature_names(max_n_bufs)\n    return {name: features[:, i] for i, name in enumerate(names)}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/loop_state.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import\n\n\"\"\"\nThe definition of the \"state\" in the search.\nEach LoopState corresponds to a schedule for its ComputeDAG.\nA LoopState consists of: 1. a current loop structure; 2. a list of transformation steps used to\nconstruct the loop structure.\nThe loop structure keeps a preview of how the schedule will finally look like after lowering the\ncurrent state (e.g. number of iterators, the extent of each iterator, the compute_at locations\n...).\nDuring the schedule search process, the loop structure can provide search policy with necessary\ninformation on how to manipulate the current state.\nThe transform history is a sequence of `TransformStep` which will finally be mapped to TVM\nschedule primitives. The steps are also used for the serialization of a state.\nThe LoopState can be seen as a lightweight loop structure IR specifically for schedule search.\nWe don't use the existing TVM IR but to extend a new structure on it is because:\n1. We want fast incremental change to the loop structures. The search policy needs to get the\nimmediate loop structures update rather than after TVM lowering;\n2. We want serializable transform history for replay, backtracking, and mutation;\n3. We may create some macro schedule primitives that represent the combination of several\nTVM schedule primitives.\nWhen the search is finished, we will lower the state to TVM IR with TVM's schedule primitives.\nSince we share a lot of common objects during search, the transformation is implemented in\ncopy on write style. All objects are immutable, which is similar to TVM IR.\n\"\"\"\n\nimport tvm._ffi\nfrom tvm.te.tensor import Operation, Tensor\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"auto_scheduler.Iterator\")\nclass Iterator(Object):\n    \"\"\"A loop iterator structure.\"\"\"\n\n\n@tvm._ffi.register_object(\"auto_scheduler.Stage\")\nclass Stage(Object):\n    \"\"\"A stage in the compute declaration. Similar to tvm.te.schedule.Stage.\"\"\"\n\n    # Static trans table for compute_at location\n    # This is used to transform the compute_at location to C++ enum\n    COMPUTE_AT_TRANS_TABLE = {\"root\": 0, \"inlined\": 1, \"iter\": 2}\n\n\n@tvm._ffi.register_object(\"auto_scheduler.State\")\nclass StateObject(Object):\n    \"\"\"The internal State object\"\"\"\n\n    def __eq__(self, other):\n        return _ffi_api.StateEqual(self, other)\n\n\nclass State:\n    \"\"\"\n    A state in the search process. It consists of the current loop structure\n    and a list of transformation steps used to construct it.\n    Each State corresponds to a specific schedule for its ComputeDAG.\n    Parameters\n    ----------\n    state_object : StateObject\n        The StateObject corresponding to C++ internal State object.\n    dag : ComputeDAG\n        The original ComputeDAG of this State.\n    Notes\n    -----\n    This is a wrapper class of StateObject to deal with copy-on-write property\n    \"\"\"\n\n    # Static trans table for thread bind and annotation\n    # This is used to transform the annotation name to C++ enum\n    ANNOTATION_TRANS_TABLE = {\n        \"none\": 0,\n        \"unroll\": 1,\n        \"vectorize\": 2,\n        \"parallel\": 3,\n        \"vthread\": 4,\n        \"blockIdx.x\": 5,\n        \"threadIdx.x\": 6,\n        \"blockIdx.y\": 7,\n        \"threadIdx.y\": 8,\n        \"blockIdx.z\": 9,\n        \"threadIdx.z\": 10,\n        \"tensorize\": 11,\n    }\n\n    def __init__(self, state_object, dag):\n        self.state_object = state_object\n        self.compute_dag = dag\n\n        self.stage_id_map = {}  # A dict maps operation to stage id\n        self._update_stage_id_map()\n\n    @property\n    def stages(self):\n        \"\"\"\n        Returns\n        -------\n        stages : List[Stage]\n        \"\"\"\n        return self.state_object.stages\n\n    @property\n    def transform_steps(self):\n        \"\"\"\n        Returns\n        -------\n        transform_steps : List[transform_steps]\n        \"\"\"\n        return self.state_object.transform_steps\n\n    @property\n    def stage_ops(self):\n        \"\"\"\n        Returns\n        -------\n        ops: List[Operation]\n        \"\"\"\n        return [stage.op for stage in self.stages]\n\n    def bind(self, stage, iterator, thread_name):\n        \"\"\"Schedule primitive corresponding to `te.Stage.bind`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be binded, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be binded.\n        thread_name : str\n            The thread type to be binded. Candidates:\n            - vthread\n            - blockIdx.x\n            - threadIdx.x\n            - blockIdx.y\n            - threadIdx.y\n            - blockIdx.z\n            - threadIdx.z\n        Returns\n        -------\n        res_it : Iterator\n            The binded Iterator.\n        \"\"\"\n        if not thread_name in State.ANNOTATION_TRANS_TABLE.keys():\n            raise ValueError(\"Invalid thread_name: \", thread_name)\n\n        self.state_object, res = _ffi_api.StateBind(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            iterator,\n            State.ANNOTATION_TRANS_TABLE[thread_name],\n        )\n        return res\n\n    def parallel(self, stage, iterator):\n        \"\"\"Schedule primitive corresponding to `te.Stage.parallel`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be paralleled, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be paralleled.\n        Returns\n        -------\n        res_it : Iterator\n            The paralleled Iterator.\n        \"\"\"\n        self.state_object, res = _ffi_api.StateParallel(\n            self.state_object, self._resolve_stage_id(stage), iterator\n        )\n        return res\n\n    def unroll(self, stage, iterator, max_unroll=None):\n        \"\"\"Schedule primitive corresponding to `te.Stage.unroll`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be unrolled, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be unrolled.\n        max_unroll : Optional[int]\n            The max unroll limit. Iterator with extent larger than this limit will be skipped.\n        Returns\n        -------\n        res_it : Iterator\n            The unrolled Iterator.\n        \"\"\"\n        self.state_object, res = _ffi_api.StateUnroll(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            iterator,\n            max_unroll if max_unroll else -1,\n        )\n        return res\n\n    def vectorize(self, stage, iterator):\n        \"\"\"Schedule primitive corresponding to `te.Stage.vectorize`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be vectorized, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be vectorized.\n        Returns\n        -------\n        res_it : Iterator\n            The vectorized Iterator.\n        \"\"\"\n        self.state_object, res = _ffi_api.StateVectorize(\n            self.state_object, self._resolve_stage_id(stage), iterator\n        )\n        return res\n\n    def fuse(self, stage, iters):\n        \"\"\"Schedule primitive corresponding to `te.Stage.fuse`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be fused, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iters : List[Iterator]\n            The iterators to be fused.\n        Returns\n        -------\n        res_it : Iterator\n            The fused Iterator.\n        Notes\n        -----\n        If the iterators to be fused have stages attached at them(by compute_at), the fused\n        result will become the new attach point.\n        \"\"\"\n        self.state_object, res = _ffi_api.StateFuse(\n            self.state_object, self._resolve_stage_id(stage), iters\n        )\n        return res\n\n    def pragma(self, stage, iterator, pragma_type):\n        \"\"\"Schedule primitive corresponding to `te.Stage.pragma`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to add pragma, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to add pragma.\n        pragma_type : str\n            The pragma string.\n        \"\"\"\n        self.state_object = _ffi_api.StatePragma(\n            self.state_object, self._resolve_stage_id(stage), iterator, pragma_type\n        )\n\n    def reorder(self, stage, order):\n        \"\"\"Schedule primitive corresponding to `te.Stage.reorder`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be reordered, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        order : List[Iterator]\n            Iterators in the expected order.\n        \"\"\"\n        self.state_object = _ffi_api.StateReorder(\n            self.state_object, self._resolve_stage_id(stage), order\n        )\n\n    def split(self, stage, iterator, lengths, inner_to_outer=True):\n        \"\"\"Schedule primitive corresponding to `te.Stage.split`.\n        See also the `te.Stage` for more details.\n        This API supports multiple split factors. (e.g. with 2 split factors, the original iterator\n        will be split to 3 parts, use `inner_to_outer` to control the split order)\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be split, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be split.\n        lengths: List[int]\n            The multiple split factors. Can be None to be filled by search policy.\n        inner_to_outer: boolean = True\n            Whether the factor go from inner to outer, or from outer to inner.\n        Returns\n        -------\n        res_its : List[Iterator]\n            The splitted new Iterators.\n        Notes\n        -----\n        If we do split on an iterator which has stages attached at it(by compute_at), the inner\n        most iterator of split results will become the new attach point.\n        \"\"\"\n        self.state_object, res = _ffi_api.StateSplit(\n            self.state_object, self._resolve_stage_id(stage), iterator, lengths, inner_to_outer\n        )\n        return res\n\n    def follow_split(self, stage, iterator, src_step_id, n_split):\n        \"\"\"The schedule primitive similar to split, but uses split factors from previous steps.\n        This step splits the iterator by the same factors as the given SplitStep.\n        Notes\n        ------\n            This step is useful in a scenario that we have subgraph Dense -> Relu,\n            and we want to compute the Dense stage at ReLU. In this case, we need them to have\n            the same tiling structure of common outer loops.\n            The follow_split step could be used here to split the Dense stage and makes sure its\n            splitting factors are the same as the given split step for the ReLU stage.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be split, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to split.\n        src_step_id : int\n            The index of the split step to be followed in the history.\n        n_split : int\n            The number of split level.\n        Returns\n        -------\n        res_its : List[Iterator]\n            The splitted new Iterators.\n        \"\"\"\n\n        self.state_object, res = _ffi_api.StateFollowSplit(\n            self.state_object, self._resolve_stage_id(stage), iterator, src_step_id, n_split\n        )\n        return res\n\n    def follow_fused_split(self, stage, iterator, src_step_ids, level, factor_or_nparts):\n        \"\"\"Schedule primitive extends to split step.\n        This step is used to split an iterator by the same factors\n        as the given list of SplitSteps and FuseSteps.\n        Notes\n        ------\n            This step is useful in a scenario that we have a subgraph\n            in GPU schedule: Input -> Dense\n            for i.0@j.0 = ... : Bind to blockIdx.x\n                for i.1@j.1 = ... : Bind to threadIdx.x\n                    for i.2@j.2 = ...\n                        Input_shared = Input ...\n                        for k = ...\n                            Dense = ...\n            We intend to apply cooperative fetching with the input stage, while the threadIdx.x\n            axis is bound to an iterator generated by split & fuse step.\n            The follow_fused_step is used split the iterator to 2 parts, while the split factor\n            matches the final extent of the threadIdx.x bound iterator.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be split, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The iterator to split.\n        src_step_ids : List[int]\n            The indices of the split steps to be followed in the history.\n        level : int\n            Use the length in this split level.\n        factor_or_nparts : bool\n            True to use `factor` for split from inner to outer,\n            False to use `nparts` for split from outer to inner.\n        Returns\n        -------\n        res_its : List[Iterator]\n            The splitted new Iterators.\n        \"\"\"\n\n        self.state_object, res = _ffi_api.StateFollowFusedSplit(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            iterator,\n            src_step_ids,\n            level,\n            factor_or_nparts,\n        )\n        return res\n\n    def storage_align(self, stage, iterator, factor, offset):\n        \"\"\"Schedule primitive corresponding to `te.Stage.storage_align`.\n        See also the `te.Stage` for  more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be storage aligned, which can be specified by the integer index,\n            Operation, or output tensor of the stage.\n        iterator : Iterator\n            The iterator to be aligned.\n        factor : int\n            The factor in alignment specification.\n        offset : int\n            The offset in the alignment specification.\n        \"\"\"\n        self.state_object = _ffi_api.StateStorageAlign(\n            self.state_object, self._resolve_stage_id(stage), iterator, factor, offset\n        )\n\n    def compute_at(self, stage, target_stage, target_iter):\n        \"\"\"Schedule primitive corresponding to `te.Stage.compute_at`.\n        See also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The source Stage of computed at, which can be specified by the integer index,\n            Operation, or output tensor of the stage.\n        target_stage : Union[int, Operation, Tensor]\n            The target stage of compute_at, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        target_iter : Iterator\n            The target Iterator of compute_at.\n        Notes\n        -----\n        After compute_at, we need careful dependency analysis to compute the accurate bound\n        information. However, it is relatively expensive and complicated, so we just fill \"None\"\n        as bound for the newly created iterators.\n        Call ComputeDAG::InferBound on the returned state to get the complete bound information.\n        \"\"\"\n        self.state_object = _ffi_api.StateComputeAt(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            self._resolve_stage_id(target_stage),\n            target_iter,\n        )\n\n    def compute_inline(self, stage):\n        \"\"\"Schedule primitive corresponding to `te.Stage.compute_inline`, see also the `te.Stage`\n        for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be marked compute inlined, which can be specified by the integer index,\n            Operation, or output tensor of the stage.\n        \"\"\"\n        self.state_object = _ffi_api.StateComputeInline(\n            self.state_object, self._resolve_stage_id(stage)\n        )\n\n    def compute_root(self, stage):\n        \"\"\"Schedule primitive corresponding to `te.Stage.compute_root`.\n        Ssee also the `te.Stage` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be marked compute at root, which can be specified by the integer index,\n            Operation, or output tensor of the stage.\n        Notes\n        -----\n        After compute_root, we need careful dependency analysis to compute the accurate bound\n        information. However, it is relatively expensive and complicated, so we just fill \"None\"\n        as bound for the newly created iterators.\n        Call ComputeDAG::InferBound on the returned state to get the complete bound information.\n        \"\"\"\n        self.state_object = _ffi_api.StateComputeRoot(\n            self.state_object, self._resolve_stage_id(stage)\n        )\n\n    def cache_read(self, stage, scope_name, reader_stages):\n        \"\"\"Schedule primitive corresponding to `te.Schedule.cache_read`.\n        See also the `te.Schedule` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be cache_read, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        scope_name : str\n            The scope name of the newly added read stage.\n        reader_stages : List[Union[int, Operation, Tensor]]\n            The reader stages. Each of the list can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        Returns\n        -------\n        new_stage_op : Operator\n            The Operator of the new added stage.\n        Notes\n        -----\n        Cache read step will insert an extra stage to the original ComputeDAG (at the back of the\n        target stage).\n        \"\"\"\n        reader_stage_ids = [self._resolve_stage_id(i) for i in reader_stages]\n        self.state_object, new_stage_id = _ffi_api.StateCacheRead(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            scope_name,\n            reader_stage_ids,\n            self.compute_dag,\n        )\n        # Add a new stage will change all ops behind the added stage. But we still want to keep the\n        # original ops map, apply stage id offset to stage_id_map to make them work.\n        self._apply_stage_id_offset(int(new_stage_id))\n        self._update_stage_id_map()\n        return self.stages[int(new_stage_id)].op\n\n    def cache_write(self, stage, scope_name):\n        \"\"\"Schedule primitive corresponding to `te.Schedule.cache_write`.\n        See also the `te.Schedule` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be cache_write, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        scope_name : str\n            The scope name of the newly added compute stage.\n        Returns\n        -------\n        new_stage_op : Operator\n            The Operator of the new added stage.\n        Notes\n        -----\n        Cache write step will insert an extra stage to the original ComputeDAG (in the front of the\n        target stage).\n        This step will cache write all output tensors of the target stage.\n        \"\"\"\n        self.state_object, new_stage_id = _ffi_api.StateCacheWrite(\n            self.state_object, self._resolve_stage_id(stage), scope_name, self.compute_dag\n        )\n        # Add a new stage will change all ops behind the added stage. But we still want to keep the\n        # original ops map, apply stage id offset to stage_id_map to make them work.\n        self._apply_stage_id_offset(int(new_stage_id))\n        self._update_stage_id_map()\n        return self.stages[int(new_stage_id)].op\n\n    def rfactor(self, stage, iterator, factor_iter_id):\n        \"\"\"Schedule primitive corresponding to `te.Schedule.rfactor`.\n        See also the `te.Schedule` for more details.\n        Parameters\n        ----------\n        stage : Union[int, Operation, Tensor]\n            The Stage to be factored, which can be specified by the integer index, Operation,\n            or output tensor of the stage.\n        iterator : Iterator\n            The reduction iterator to be factored.\n        factor_iter_id : int\n            The position where the new iterator is placed.\n        Returns\n        -------\n        new_stage_op : Operator\n            The Operator of the new added stage.\n        Notes\n        -----\n        Rfactor step will insert an extra stage to the original ComputeDAG (in the front of the\n        target stage).\n        \"\"\"\n        self.state_object, new_stage_id = _ffi_api.StateRfactor(\n            self.state_object,\n            self._resolve_stage_id(stage),\n            iterator,\n            factor_iter_id,\n            self.compute_dag,\n        )\n        # Add a new stage will change all ops behind the added stage. But we still want to keep the\n        # original ops map, apply stage id offset to stage_id_map to make them work.\n        self._apply_stage_id_offset(int(new_stage_id))\n        self._update_stage_id_map()\n        return self.stages[int(new_stage_id)].op\n\n    def copy(self):\n        \"\"\"Do deep copy of this State.\"\"\"\n        state = State(self.state_object, self.compute_dag)\n        state.stage_id_map = self.stage_id_map.copy()\n        return state\n\n    def _resolve_stage_id(self, stage_id):\n        if isinstance(stage_id, Operation):\n            return self.stage_id_map[stage_id]\n        if isinstance(stage_id, Tensor):\n            return self.stage_id_map[stage_id.op]\n        if isinstance(stage_id, int):\n            return stage_id\n        raise ValueError(\n            \"Invalid stage: \" + stage_id + \" . Expect to be a int, Operation or Tensor\"\n        )\n\n    def _update_stage_id_map(self):\n        for index, stage in enumerate(self.stages):\n            self.stage_id_map[stage.op] = index\n\n    def _apply_stage_id_offset(self, start_id, offset=1):\n        for key, value in self.stage_id_map.items():\n            if value >= start_id:\n                self.stage_id_map[key] = value + offset\n\n    def __getitem__(self, key):\n        if isinstance(key, Tensor):\n            key = key.op\n        if isinstance(key, Operation):\n            return self.stages[self.stage_id_map[key]]\n        raise ValueError(\"Invalid item: \" + key + \" . Expect to be a Operation or Tensor\")\n\n    def __str__(self):\n        return str(self.state_object)\n\n    def __eq__(self, other):\n        return _ffi_api.StateEqual(self.state_object, other.state_object)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/measure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nDistributed measurement infrastructure to measure the runtime costs of tensor programs.\n\nThese functions are responsible for building the tvm module, uploading it to\nremote devices, recording the running time costs, and checking the correctness of the output.\n\nWe separate the measurement into two steps: build and run.\nA builder builds the executable binary files and a runner runs the binary files to\nget the measurement results. The flow of data structures is\n\n  .               `ProgramBuilder`                 `ProgramRunner`\n  `MeasureInput` -----------------> `BuildResult` ----------------> `MeasureResult`\n\nWe implement these in python to utilize python's multiprocessing and error handling.\n\"\"\"\n\nimport logging\nimport multiprocessing\nimport os\nimport shutil\nimport tempfile\nimport time\n\nimport tvm._ffi\nfrom tvm.autotvm.env import AutotvmGlobalScope, reset_global_scope\nfrom tvm.contrib import ndk, tar\nfrom tvm.contrib.popen_pool import PopenPoolExecutor, PopenWorker, StatusKind\nfrom tvm.driver import build_module\nfrom tvm.ir import transform\nfrom tvm.runtime import Object, module, ndarray\nfrom tvm.target import Target\n\nfrom . import _ffi_api\nfrom .loop_state import StateObject\nfrom .utils import (\n    call_func_with_timeout,\n    check_remote,\n    get_const_tuple,\n    get_func_name,\n    make_traceback_info,\n    request_remote,\n)\nfrom .workload_registry import (\n    deserialize_workload_registry_entry,\n    serialize_workload_registry_entry,\n)\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"auto_scheduler\")\n\n# The time cost for measurements with errors\n# We use 1e10 instead of sys.float_info.max for better readability in log\nMAX_FLOAT = 1e10\n\n\nclass BuildFunc:\n    \"\"\"store build_func name and callable to class variable.\n    name: str = \"default\"\n        The name of registered build function.\n    build_func: callable = tar.tar\n        The callable of registered build function.\n    \"\"\"\n\n    name = \"default\"\n    build_func = tar.tar\n\n\n@tvm._ffi.register_object(\"auto_scheduler.MeasureCallback\")\nclass MeasureCallback(Object):\n    \"\"\"The base class of measurement callback functions.\"\"\"\n\n\n@tvm._ffi.register_object(\"auto_scheduler.PythonBasedMeasureCallback\")\nclass PythonBasedMeasureCallback(MeasureCallback):\n    \"\"\"Base class for measure callbacks implemented in python\"\"\"\n\n    def __init__(self):\n        def callback_func(policy, inputs, results):\n            self.callback(policy, inputs, results)\n\n        self.__init_handle_by_constructor__(_ffi_api.PythonBasedMeasureCallback, callback_func)\n\n    def callback(self, policy, inputs, results):\n        \"\"\"The callback function.\n\n        Parameters\n        ----------\n        policy: auto_scheduler.search_policy.SearchPolicy\n            The search policy.\n        inputs : List[auto_scheduler.measure.MeasureInput]\n            The measurement inputs\n        results : List[auto_scheduler.measure.MeasureResult]\n            The measurement results\n        \"\"\"\n        raise NotImplementedError\n\n\n@tvm._ffi.register_object(\"auto_scheduler.MeasureInput\")\nclass MeasureInput(Object):\n    \"\"\"Store the input of a measurement.\n\n    Parameters\n    ----------\n    task : SearchTask\n        The SearchTask of this measurement.\n    state : Union[State, StateObject]\n        The State to be measured.\n    \"\"\"\n\n    def __init__(self, task, state):\n        state = state if isinstance(state, StateObject) else state.state_object\n        self.__init_handle_by_constructor__(_ffi_api.MeasureInput, task, state)\n\n    def serialize(self):\n        \"\"\"Custom serialization to workaround MeasureInput not exposing all its\n        members to the TVM ffi interface.\n\n        Note that we do not implement __getstate__ as it does not seem to work\n        with initialization of the workload registry (maybe because of\n        initialization order?).\n        \"\"\"\n        return [\n            _ffi_api.SerializeMeasureInput(self),\n            serialize_workload_registry_entry(self.task.workload_key),\n        ]\n\n    @staticmethod\n    def deserialize(data):\n        inp = _ffi_api.DeserializeMeasureInput(data[0])\n        deserialize_workload_registry_entry(data[1])\n        return recover_measure_input(inp)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.BuildResult\")\nclass BuildResult(Object):\n    \"\"\"Store the result of a build.\n\n    Parameters\n    ----------\n    filename : Optional[str]\n        The filename of built binary file.\n    args : List[Tensor]\n        The arguments.\n    error_no : int\n        The error code.\n    error_msg : Optional[str]\n        The error message if there is any error.\n    time_cost : float\n        The time cost of build.\n    \"\"\"\n\n    def __init__(self, filename, args, error_no, error_msg, time_cost):\n        filename = filename if filename else \"\"\n        error_msg = error_msg if error_msg else \"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.BuildResult, filename, args, error_no, error_msg, time_cost\n        )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.MeasureResult\")\nclass MeasureResult(Object):\n    \"\"\"Store the results of a measurement.\n\n    Parameters\n    ----------\n    costs : List[float]\n        The time costs of execution.\n    error_no : int\n        The error code.\n    error_msg : Optional[str]\n        The error message if there is any error.\n    all_cost : float\n        The time cost of build and run.\n    timestamp : float\n        The time stamps of this measurement.\n    \"\"\"\n\n    def __init__(self, costs, error_no, error_msg, all_cost, timestamp):\n        error_msg = error_msg if error_msg else \"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureResult, costs, error_no, error_msg, all_cost, timestamp\n        )\n\n\ndef recover_measure_input(inp, rebuild_state=False):\n    \"\"\"\n    Recover a deserialized MeasureInput by rebuilding the missing fields.\n    1. Rebuid the compute_dag in inp.task\n    2. (Optional) Rebuild the stages in inp.state\n\n    Parameters\n    ----------\n    inp: MeasureInput\n        The deserialized MeasureInput\n    rebuild_state: bool = False\n        Whether rebuild the stages in MeasureInput.State\n\n    Returns\n    -------\n    new_input: MeasureInput\n        The fully recovered MeasureInput with all fields rebuilt.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from .search_task import SearchTask  # lazily import to avoid recursive dependency\n\n    task = inp.task\n    task.target, task.target_host = Target.canon_target_and_host(task.target, task.target_host)\n    new_task = SearchTask(\n        workload_key=task.workload_key,\n        target=task.target,\n        hardware_params=task.hardware_params,\n        layout_rewrite_option=task.layout_rewrite_option,\n        task_inputs=list(task.task_input_names),\n    )\n\n    if rebuild_state:\n        new_state = new_task.compute_dag.infer_bound_from_state(inp.state)\n    else:\n        new_state = inp.state\n\n    return MeasureInput(new_task, new_state)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.ProgramBuilder\")\nclass ProgramBuilder(Object):\n    \"\"\"The base class of ProgramBuilders.\"\"\"\n\n    def build(self, measure_inputs, verbose=1):\n        \"\"\"Build programs and return results.\n\n        Parameters\n        ----------\n        measure_inputs : List[MeasureInput]\n            A List of MeasureInput.\n        verbose: int = 1\n            Verbosity level. 0 for silent, 1 to output information during program building.\n\n        Returns\n        -------\n        res : List[BuildResult]\n        \"\"\"\n        return _ffi_api.ProgramBuilderBuild(self, measure_inputs, verbose)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.ProgramRunner\")\nclass ProgramRunner(Object):\n    \"\"\"The base class of ProgramRunners.\"\"\"\n\n    def run(self, measure_inputs, build_results, verbose=1):\n        \"\"\"Run measurement and return results.\n\n        Parameters\n        ----------\n        measure_inputs : List[MeasureInput]\n            A List of MeasureInput.\n        build_results : List[BuildResult]\n            A List of BuildResult to be ran.\n        verbose: int = 1\n            Verbosity level. 0 for silent, 1 to output information during program running.\n\n        Returns\n        -------\n        res : List[MeasureResult]\n        \"\"\"\n        return _ffi_api.ProgramRunnerRun(self, measure_inputs, build_results, verbose)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.ProgramMeasurer\")\nclass ProgramMeasurer(Object):\n    \"\"\"\n    Measurer that measures the time costs of tvm programs\n    This class combines ProgramBuilder and ProgramRunner, and provides a simpler API.\n\n    Parameters\n    ----------\n    builder : ProgramBuilder\n        The ProgramBuilder to build programs\n    runner : ProgramRunner\n        The ProgramRunner to measure programs.\n    callbacks : List[MeasureCallback]\n        Callbacks to be called after each measurement batch\n    verbose : int\n        The Verbosity level: 0 for silent, 1 to output information during program\n    max_continuous_error : Optional[int]\n        The number of allowed maximum continuous error before stop the tuning\n    \"\"\"\n\n    def __init__(self, builder, runner, callbacks, verbose, max_continuous_error=None):\n        max_continuous_error = max_continuous_error or -1  # -1 means using the default value\n        self.__init_handle_by_constructor__(\n            _ffi_api.ProgramMeasurer, builder, runner, callbacks, verbose, max_continuous_error\n        )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.LocalBuilder\")\nclass LocalBuilder(ProgramBuilder):\n    \"\"\"LocalBuilder use local CPU cores to build programs in parallel.\n\n    Parameters\n    ----------\n    timeout : int = 15\n        The timeout limit (in second) for each build thread.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    n_parallel : int = multiprocessing.cpu_count()\n        Number of threads used to build in parallel.\n    build_func: callable or str = \"default\"\n        If is 'default', use default build function\n        If is 'ndk', use function for android ndk\n        If is callable, use it as custom build function, expect lib_format field.\n    \"\"\"\n\n    def __init__(self, timeout=15, n_parallel=multiprocessing.cpu_count(), build_func=\"default\"):\n        if build_func == \"default\":\n            BuildFunc.name = \"default\"\n            BuildFunc.build_func = tar.tar\n        elif build_func == \"ndk\":\n            BuildFunc.name = \"ndk\"\n            BuildFunc.build_func = ndk.create_shared\n        elif callable(build_func):\n            BuildFunc.name = \"custom\"\n            BuildFunc.build_func = build_func\n        else:\n            raise ValueError(\"Invalid build_func\" + build_func)\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.LocalBuilder, timeout, n_parallel, BuildFunc.name\n        )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.LocalRunner\")\nclass LocalRunner(ProgramRunner):\n    \"\"\"LocalRunner that uses local CPU/GPU to measures the time cost of programs.\n\n    Parameters\n    ----------\n    timeout : int = 10\n        The timeout limit (in second) for each run.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    number : int = 3\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int = 1\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms : int = 100\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval : float = 0.0\n        The cool down interval between two measurements in seconds.\n    enable_cpu_cache_flush: bool = False\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    device: int = 0\n        Which device to run on if multiple are available.\n    \"\"\"\n\n    def __init__(\n        self,\n        timeout=10,\n        number=3,\n        repeat=1,\n        min_repeat_ms=100,\n        cooldown_interval=0.0,\n        enable_cpu_cache_flush=False,\n        device=0,\n    ):\n        if enable_cpu_cache_flush:\n            number = 1\n            min_repeat_ms = 0\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.LocalRunner,\n            timeout,\n            number,\n            repeat,\n            min_repeat_ms,\n            cooldown_interval,\n            enable_cpu_cache_flush,\n            device,\n        )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.RPCRunner\")\nclass RPCRunner(ProgramRunner):\n    \"\"\"RPCRunner that uses RPC call to measures the time cost of programs on remote devices.\n    Or sometime we may need to use RPC even in local running to insulate the thread environment.\n    (e.g. running CUDA programs)\n\n    Parameters\n    ----------\n    key : str\n        The key of the device registered in the RPC tracker.\n    host : str\n        The host address of the RPC Tracker.\n    port : int\n        The port of RPC Tracker.\n    priority : int = 1\n        The priority of this run request, larger is more prior.\n    n_parallel : int = 1\n        The number of tasks run in parallel.\n    timeout : int = 10\n        The timeout limit (in second) for each run.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    number : int = 3\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int = 1\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms : int = 100\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval : float = 0.0\n        The cool down interval between two measurements in seconds.\n    enable_cpu_cache_flush: bool = False\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    device: int = 0\n        Which device to run on if multiple are available.\n    \"\"\"\n\n    def __init__(\n        self,\n        key,\n        host,\n        port,\n        priority=1,\n        n_parallel=1,\n        timeout=10,\n        number=3,\n        repeat=1,\n        min_repeat_ms=100,\n        cooldown_interval=0.0,\n        enable_cpu_cache_flush=False,\n        device=0,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.RPCRunner,\n            key,\n            host,\n            port,\n            priority,\n            n_parallel,\n            timeout,\n            number,\n            repeat,\n            min_repeat_ms,\n            cooldown_interval,\n            enable_cpu_cache_flush,\n            device,\n        )\n\n        if check_remote(key, host, port, priority, timeout):\n            print(\"Get devices for measurement successfully!\")\n        else:\n            raise RuntimeError(\n                \"Cannot get remote devices from the tracker. \"\n                \"Please check the status of tracker by \"\n                \"'python -m tvm.exec.query_rpc_tracker --port [THE PORT YOU USE]' \"\n                \"and make sure you have free devices on the queue status.\"\n            )\n\n\nclass LocalRPCMeasureContext:\n    \"\"\"A context wrapper for running RPCRunner locally.\n    This will launch a local RPC Tracker and local RPC Server.\n\n    Parameters\n    ----------\n    priority : int = 1\n        The priority of this run request, larger is more prior.\n    n_parallel : int = 1\n        The number of tasks run in parallel.\n    timeout : int = 10\n        The timeout limit (in second) for each run.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    number : int = 3\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int = 1\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms : int = 0\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval : float = 0.0\n        The cool down interval between two measurements in seconds.\n    enable_cpu_cache_flush: bool = False\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    device: int = 0\n        Which device to run on if multiple are available.\n    \"\"\"\n\n    def __init__(\n        self,\n        priority=1,\n        n_parallel=1,\n        timeout=10,\n        number=3,\n        repeat=1,\n        min_repeat_ms=0,\n        cooldown_interval=0.0,\n        enable_cpu_cache_flush=False,\n        device=0,\n    ):\n        # pylint: disable=import-outside-toplevel\n        from tvm.rpc.server import Server\n        from tvm.rpc.tracker import Tracker\n\n        self.tracker = Tracker(port=9000, port_end=10000, silent=True)\n        device_key = \"$local$device$%d\" % self.tracker.port\n        self.server = Server(\n            port=self.tracker.port,\n            port_end=10000,\n            key=device_key,\n            silent=True,\n            tracker_addr=(\"127.0.0.1\", self.tracker.port),\n        )\n        self.runner = RPCRunner(\n            device_key,\n            \"127.0.0.1\",\n            self.tracker.port,\n            priority,\n            n_parallel,\n            timeout,\n            number,\n            repeat,\n            min_repeat_ms,\n            cooldown_interval,\n            enable_cpu_cache_flush,\n            device,\n        )\n        # Wait for the processes to start\n        time.sleep(0.5)\n\n    def __del__(self):\n        # Close the tracker and server before exit\n        self.tracker.terminate()\n        self.server.terminate()\n        time.sleep(0.5)\n\n\nclass MeasureErrorNo(object):\n    \"\"\"Error type for MeasureResult.\"\"\"\n\n    NO_ERROR = 0  # No error\n    INSTANTIATION_ERROR = 1  # Errors happen when apply transform steps from init state\n    COMPILE_HOST = 2  # Errors happen when compiling code on host (e.g., tvm.build)\n    COMPILE_DEVICE = 3  # Errors happen when compiling code on device\n    # (e.g. OpenCL JIT on the device)\n    RUNTIME_DEVICE = 4  # Errors happen when run program on device\n    WRONG_ANSWER = 5  # Answer is wrong when compared to a reference output\n    BUILD_TIMEOUT = 6  # Timeout during compilation\n    RUN_TIMEOUT = 7  # Timeout during run\n    UNKNOWN_ERROR = 8  # Unknown error\n\n\ndef _local_build_worker(inp_serialized, build_func, verbose):\n    tic = time.time()\n    inp = MeasureInput.deserialize(inp_serialized)\n    task = inp.task\n    task.target, task.target_host = Target.canon_target_and_host(task.target, task.target_host)\n\n    error_no = MeasureErrorNo.NO_ERROR\n    error_msg = None\n    args = []\n\n    try:\n        sch, args = task.compute_dag.apply_steps_from_state(\n            inp.state, layout_rewrite=task.layout_rewrite_option\n        )\n    # pylint: disable=broad-except\n    except Exception:\n        error_no = MeasureErrorNo.INSTANTIATION_ERROR\n        error_msg = make_traceback_info()\n\n    if error_no == 0:\n        dirname = tempfile.mkdtemp()\n        filename = os.path.join(dirname, \"tmp_func.\" + build_func.output_format)\n\n        try:\n            with transform.PassContext().current():\n                func = build_module.build(sch, args, target=task.target)\n            func.export_library(filename, build_func)\n        # pylint: disable=broad-except\n        except Exception:\n            error_no = MeasureErrorNo.COMPILE_HOST\n            error_msg = make_traceback_info()\n    else:\n        filename = \"\"\n\n    if verbose >= 1:\n        if error_no == MeasureErrorNo.NO_ERROR:\n            print(\".\", end=\"\", flush=True)\n        else:\n            print(\".E\", end=\"\", flush=True)  # Build error\n\n    return filename, args, error_no, error_msg, time.time() - tic\n\n\ndef local_build_worker(args):\n    \"\"\"\n    Build function of LocalBuilder to be ran in the Builder thread pool.\n\n    Parameters\n    ----------\n    args: Tuple[MeasureInput, callable, int]\n        inputs, build-func, verbose args passed to local_builder_build\n\n    Returns\n    -------\n    res : BuildResult\n        The build result of this Builder thread.\n    \"\"\"\n    inp, build_func, verbose = args\n\n    return _local_build_worker(inp, build_func, verbose)\n\n\n@tvm._ffi.register_func(\"auto_scheduler.local_builder.build\")\ndef local_builder_build(inputs, timeout, n_parallel, build_func=\"default\", verbose=1):\n    \"\"\"\n    Build function of LocalBuilder to build the MeasureInputs to runnable modules.\n\n    Parameters\n    ----------\n    inputs : List[MeasureInput]\n        The MeasureInputs to be built.\n    timeout : int\n        The timeout limit (in second) for each build thread.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    n_parallel : int\n        Number of threads used to build in parallel.\n    build_func : str = 'default'\n        The name of build function to process the built module.\n    verbose: int = 1\n        Verbosity level. 0 for silent, 1 to output information during program building.\n\n    Returns\n    -------\n    res : List[BuildResult]\n        The build results of these MeasureInputs.\n    \"\"\"\n    assert build_func == BuildFunc.name, (\n        \"BuildFunc.name: \" + BuildFunc.name + \", but args is: \" + build_func\n    )\n    executor = PopenPoolExecutor(\n        n_parallel, timeout, reset_global_scope, (AutotvmGlobalScope.current,)\n    )\n    tuple_res = executor.map_with_error_catching(\n        local_build_worker,\n        [\n            (\n                i.serialize(),\n                BuildFunc.build_func,\n                verbose,\n            )\n            for i in inputs\n        ],\n    )\n\n    results = []\n    for res in tuple_res:\n        if res.status == StatusKind.COMPLETE:\n            results.append(BuildResult(*res.value))\n        elif res.status == StatusKind.TIMEOUT:\n            if verbose >= 1:\n                print(\".T\", end=\"\", flush=True)  # Build timeout\n            results.append(BuildResult(None, [], MeasureErrorNo.BUILD_TIMEOUT, None, timeout))\n        elif res.status == StatusKind.EXCEPTION:\n            if verbose >= 1:\n                print(\".E\", end=\"\", flush=True)  # Build error\n            results.append(\n                BuildResult(None, [], MeasureErrorNo.COMPILE_HOST, repr(res.value), timeout)\n            )\n        else:\n            raise ValueError(\"Result status is not expected. Unreachable branch\")\n\n    return results\n\n\nTASK_INPUT_CHECK_FUNC_REGISTRY = {}\n\n\ndef register_task_input_check_func(func_name, f=None, override=False):\n    \"\"\"Register a function that checks the input buffer map.\n\n    The input function should take a list of Tensor wich indicate the Input/output Tensor of a TVM\n    subgraph and return a Map from the input Tensor to its buffer name.\n\n    Parameters\n    ----------\n    func_name : Union[Function, str]\n        The check function that returns the compute declaration Tensors or its function name.\n    f : Optional[Function]\n        The check function to be registered.\n    override : boolean = False\n        Whether to override existing entry.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      @auto_scheduler.register_task_input_check_func\n      def check_task_input_by_placeholder_name(args : List[Tensor]):\n          tensor_input_map = {}\n          for arg in args:\n              if isinstance(arg.op, tvm.te.PlaceholderOp):\n                  if arg.op.name != \"placeholder\":\n                      tensor_input_map[arg] = arg.op.name\n          return tensor_input_map\n    \"\"\"\n    global TASK_INPUT_CHECK_FUNC_REGISTRY\n\n    if callable(func_name):\n        f = func_name\n        func_name = get_func_name(f)\n    if not isinstance(func_name, str):\n        raise ValueError(\"expect string function name\")\n\n    def register(myf):\n        \"\"\"internal register function\"\"\"\n        if func_name in TASK_INPUT_CHECK_FUNC_REGISTRY and not override:\n            raise RuntimeError(\"%s has been registered already\" % func_name)\n        TASK_INPUT_CHECK_FUNC_REGISTRY[func_name] = myf\n        return myf\n\n    if f:\n        return register(f)\n    return register\n\n\ndef prepare_input_map(args, workload_key=None):\n    \"\"\"This function deals with special task inputs. Map the input Tensor of a TVM subgraph\n    to a specific buffer name in the global buffer map.\n\n    Parameters\n    ----------\n    args : List[Tensor]\n        Input/output Tensor of a TVM subgraph.\n\n    workload_key: Optional[str]\n        The workload for which these inputs are being prepared.  This\n        is used to identify if an input is being provided by (see\n        `register_task_input_buffer`).\n\n    Returns\n    -------\n    Dict[Tensor, str] :\n        Map from the input Tensor to its buffer name.\n\n    Notes\n    -----\n    The buffer name is specially designed, and these buffer should be provided in\n    `SearchTask(..., task_inputs={...})`.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n\n    global TASK_INPUT_CHECK_FUNC_REGISTRY\n\n    from .search_task import TASK_INPUT_BUFFER_TABLE\n\n    # A dict that maps the input tensor arg to a buffer name\n    tensor_input_map = {}\n\n    # Case 0: Check placeholder name\n    for arg in args:\n        if isinstance(arg.op, tvm.te.PlaceholderOp):\n            if (\n                workload_key\n                and workload_key in TASK_INPUT_BUFFER_TABLE\n                and arg.op.name in TASK_INPUT_BUFFER_TABLE[workload_key]\n            ):\n                tensor_input_map[arg] = arg.op.name\n\n    # Case 1: Check specific tensor inputs\n    for func_name in TASK_INPUT_CHECK_FUNC_REGISTRY:\n        func = TASK_INPUT_CHECK_FUNC_REGISTRY[func_name]\n        tensor_input_map.update(func(args))\n\n    return tensor_input_map\n\n\ndef prepare_runner_args(inp, build_res):\n    \"\"\"This function prepares the pre-defined arguments in `TASK_INPUT_BUFFER_TABLE` for local/rpc\n    runner in main process\n\n    Parameters\n    ----------\n    inp : MeasureInput\n        Measure input to be measured.\n\n    build_res : BuildResult\n        Build result to be measured.\n\n    Returns\n    -------\n    List[Optional[numpy.ndarray]] :\n        List of arguments for running the program. If the argument does not have a pre-defined input\n        buffer, None is added to the list as a placeholder.\n\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from .search_task import get_task_input_buffer  # lazily import to avoid recursive dependency\n\n    task_input_names = inp.task.task_input_names\n    tensor_input_map = prepare_input_map(build_res.args, inp.task.workload_key)\n    if not task_input_names:\n        tensor_input_map = {}\n    args = []\n    task_inputs_count = 0\n    for arg in build_res.args:\n        if arg in tensor_input_map:\n            tensor_name = tensor_input_map[arg]\n            if tensor_name in task_input_names:\n                task_input_buffer = get_task_input_buffer(inp.task.workload_key, tensor_name)\n                # convert tvm.NDArray to picklable numpy.ndarray\n                args.append(task_input_buffer.numpy())\n                task_inputs_count += 1\n            else:\n                raise ValueError(\n                    \"%s not found in task_inputs, \" % (tensor_name)\n                    + \"should provide with `SearchTask(..., task_inputs={...})`\"\n                )\n        else:\n            args.append(None)\n    if task_inputs_count != len(task_input_names):\n        raise RuntimeError(\"task_inputs not fully matched, check if there's any unexpected error\")\n    return args\n\n\ndef _timed_eval_func(\n    inp_serialized,\n    build_res,\n    args,\n    number,\n    repeat,\n    min_repeat_ms,\n    cooldown_interval,\n    enable_cpu_cache_flush,\n    verbose,\n    device,\n):\n    inp = MeasureInput.deserialize(inp_serialized)\n    tic = time.time()\n    error_no = 0\n    error_msg = None\n    try:\n        func = module.load_module(build_res.filename)\n        dev = ndarray.device(str(inp.task.target), device)\n        # Limitation:\n        # We can not get PackFunction directly in the remote mode as it is wrapped\n        # under the std::function. We could lift the restriction later once we fold\n        # the PackedFunc as an object. Currently, we pass function name to work\n        # around it.\n        f_prepare = \"cache_flush_cpu_non_first_arg\" if enable_cpu_cache_flush else \"\"\n        time_f = func.time_evaluator(\n            func.entry_name,\n            dev,\n            number=number,\n            repeat=repeat,\n            min_repeat_ms=min_repeat_ms,\n            f_preproc=f_prepare,\n        )\n    # pylint: disable=broad-except\n    except Exception:\n        costs = (MAX_FLOAT,)\n        error_no = MeasureErrorNo.COMPILE_DEVICE\n        error_msg = make_traceback_info()\n\n    if error_no == 0:\n        try:\n            random_fill = tvm.get_global_func(\"tvm.contrib.random.random_fill\", True)\n            assert random_fill, \"Please make sure USE_RANDOM is ON in the config.cmake\"\n            assert len(args) == len(build_res.args)\n            loc_args = []\n            # pylint: disable=consider-using-enumerate\n            for idx in range(len(args)):\n                if args[idx] is None:\n                    build_res_arg = build_res.args[idx]\n                    empty_array = ndarray.empty(\n                        get_const_tuple(build_res_arg.shape), build_res_arg.dtype, dev\n                    )\n                    random_fill(empty_array)\n                    loc_args.append(empty_array)\n                else:\n                    loc_args.append(ndarray.array(args[idx], dev))\n            dev.sync()\n            costs = time_f(*loc_args).results\n        # pylint: disable=broad-except\n        except Exception:\n            costs = (MAX_FLOAT,)\n            error_no = MeasureErrorNo.RUNTIME_DEVICE\n            error_msg = make_traceback_info()\n\n    shutil.rmtree(os.path.dirname(build_res.filename))\n    toc = time.time()\n    time.sleep(cooldown_interval)\n\n    if verbose >= 1:\n        if error_no == MeasureErrorNo.NO_ERROR:\n            print(\"*\", end=\"\", flush=True)\n        else:\n            print(\"*E\", end=\"\", flush=True)  # Run error\n    return costs, error_no, error_msg, toc - tic + build_res.time_cost, toc\n\n\n@tvm._ffi.register_func(\"auto_scheduler.local_runner.run\")\ndef local_run(\n    inputs,\n    build_results,\n    timeout=10,\n    number=3,\n    repeat=1,\n    min_repeat_ms=0,\n    cooldown_interval=0,\n    enable_cpu_cache_flush=False,\n    verbose=1,\n    device=0,\n):\n    \"\"\"\n    Run function of LocalRunner to test the performance of the input BuildResults.\n\n    Parameters\n    ----------\n    inputs : List[MeasureInput]\n        The MeasureInputs to be measured.\n    build_results : List[BuildResult]\n        The BuildResults to be measured.\n    timeout : int = 10\n        The timeout limit (in second) for each run.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    number : int = 3\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int = 1\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms : int = 0\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval : float = 0.0\n        The cool down interval between two measurements in seconds.\n    enable_cpu_cache_flush: bool = False\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    verbose: int = 1\n        Verbosity level. 0 for silent, 1 to output information during program measuring.\n    device: int = 0\n        Which device to run on if multiple are available.\n\n    Returns\n    -------\n    res : List[MeasureResult]\n        The measure results of these MeasureInputs.\n    \"\"\"\n\n    measure_results = []\n    assert len(inputs) == len(build_results), \"Measure input size should be equal to build results\"\n    worker = PopenWorker()\n    for inp, build_res in zip(inputs, build_results):\n        if build_res.error_no != 0:\n            res = (\n                (MAX_FLOAT,),\n                build_res.error_no,\n                build_res.error_msg,\n                build_res.time_cost,\n                time.time(),\n            )\n        else:\n            args = prepare_runner_args(inp, build_res)\n            res = call_func_with_timeout(\n                worker,\n                timeout,\n                _timed_eval_func,\n                args=(\n                    inp.serialize(),\n                    build_res,\n                    args,\n                    number,\n                    repeat,\n                    min_repeat_ms,\n                    cooldown_interval,\n                    enable_cpu_cache_flush,\n                    verbose,\n                    device,\n                ),\n            )\n            if isinstance(res, TimeoutError):\n                if verbose >= 1:\n                    print(\"*T\", end=\"\", flush=True)  # Run timeout\n                res = (\n                    (MAX_FLOAT,),\n                    MeasureErrorNo.RUN_TIMEOUT,\n                    None,\n                    build_res.time_cost + timeout,\n                    time.time(),\n                )\n            elif isinstance(res, Exception):\n                if verbose >= 1:\n                    print(\"*E\", end=\"\", flush=True)  # Run error\n                res = (\n                    (MAX_FLOAT,),\n                    MeasureErrorNo.RUNTIME_DEVICE,\n                    str(res),\n                    build_res.time_cost + timeout,\n                    time.time(),\n                )\n\n        measure_results.append(MeasureResult(*res))\n\n    if verbose >= 1:\n        print(\"\", flush=True)\n\n    return measure_results\n\n\ndef _rpc_run(\n    inp_serialized,\n    build_res,\n    args,\n    key,\n    host,\n    port,\n    priority,\n    timeout,\n    number,\n    repeat,\n    min_repeat_ms,\n    cooldown_interval,\n    enable_cpu_cache_flush,\n    verbose,\n    device,\n):\n    inp = MeasureInput.deserialize(inp_serialized)\n    tic = time.time()\n    error_no = 0\n    error_msg = None\n    try:\n        # upload built module\n        remote = request_remote(key, host, port, priority, timeout)\n        remote.upload(build_res.filename)\n        func = remote.load_module(os.path.split(build_res.filename)[1])\n        dev = remote.device(str(inp.task.target), device)\n        # Limitation:\n        # We can not get PackFunction directly in the remote mode as it is wrapped\n        # under the std::function. We could lift the restriction later once we fold\n        # the PackedFunc as an object. Currently, we pass function name to work\n        # around it.\n        f_prepare = \"cache_flush_cpu_non_first_arg\" if enable_cpu_cache_flush else \"\"\n        time_f = func.time_evaluator(\n            func.entry_name,\n            dev,\n            number=number,\n            repeat=repeat,\n            min_repeat_ms=min_repeat_ms,\n            f_preproc=f_prepare,\n        )\n    # pylint: disable=broad-except\n    except Exception:\n        costs = (MAX_FLOAT,)\n        error_no = MeasureErrorNo.COMPILE_DEVICE\n        error_msg = make_traceback_info()\n\n    if error_no == 0:\n        try:\n            stream = dev.create_raw_stream()\n            dev.set_raw_stream(stream)\n            random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n            assert (\n                random_fill\n            ), \"Please make sure USE_RANDOM is ON in the config.cmake on the remote devices\"\n\n            assert len(args) == len(build_res.args)\n            loc_args = []\n            # pylint: disable=consider-using-enumerate\n            for idx in range(len(args)):\n                if args[idx] is None:\n                    build_res_arg = build_res.args[idx]\n                    empty_array = ndarray.empty(\n                        get_const_tuple(build_res_arg.shape), build_res_arg.dtype, dev\n                    )\n                    random_fill(empty_array)\n                    loc_args.append(empty_array)\n                else:\n                    loc_args.append(ndarray.array(args[idx], dev))\n            dev.sync()\n\n            # First run for check that the kernel is correct\n            func.entry_func(*loc_args)\n            dev.sync()\n\n            costs = time_f(*loc_args).results\n\n            # clean up remote files\n            remote.remove(build_res.filename)\n            remote.remove(os.path.splitext(build_res.filename)[0] + \".so\")\n            remote.remove(\"\")\n            dev.free_raw_stream(stream)\n        # pylint: disable=broad-except\n        except Exception:\n            dev.free_raw_stream(stream)\n            costs = (MAX_FLOAT,)\n            error_no = MeasureErrorNo.RUNTIME_DEVICE\n            error_msg = make_traceback_info()\n\n    shutil.rmtree(os.path.dirname(build_res.filename))\n    toc = time.time()\n\n    time.sleep(cooldown_interval)\n    if verbose >= 1:\n        if error_no == MeasureErrorNo.NO_ERROR:\n            print(\"*\", end=\"\")\n        else:\n            print(\"*E\", end=\"\")  # Run error\n\n    return costs, error_no, error_msg, toc - tic + build_res.time_cost, toc\n\n\ndef _rpc_run_worker(args):\n    \"\"\"Function to be ran in the RPCRunner thread pool.\n\n    Parameters\n    ----------\n    args : Tuple[MeasureInput, BuildResult, ...]\n        Single input and build result plus the rest of the arguments to `rpc_runner_run`.\n\n    Returns\n    -------\n    res : MeasureResult\n        The measure result of this Runner thread.\n    \"\"\"\n    _, build_res, _, _, _, _, _, timeout, _, _, _, _, _, verbose, _ = args\n    if build_res.error_no != MeasureErrorNo.NO_ERROR:\n        return (\n            (MAX_FLOAT,),\n            build_res.error_no,\n            build_res.error_msg,\n            build_res.time_cost,\n            time.time(),\n        )\n\n    try:\n        res = _rpc_run(*args)\n    # pylint: disable=broad-except\n    except Exception:\n        if verbose >= 1:\n            print(\"*E\", end=\"\")  # Run error\n        res = (\n            (MAX_FLOAT,),\n            MeasureErrorNo.RUNTIME_DEVICE,\n            make_traceback_info(),\n            build_res.time_cost + timeout,\n            time.time(),\n        )\n\n    return res\n\n\n@tvm._ffi.register_func(\"auto_scheduler.rpc_runner.run\")\ndef rpc_runner_run(\n    inputs,\n    build_results,\n    key,\n    host,\n    port,\n    priority=1,\n    n_parallel=1,\n    timeout=10,\n    number=3,\n    repeat=1,\n    min_repeat_ms=0,\n    cooldown_interval=0.0,\n    enable_cpu_cache_flush=False,\n    verbose=1,\n    device=0,\n):\n    \"\"\"Run function of RPCRunner to test the performance of the input BuildResults.\n\n    Parameters\n    ----------\n    inputs : List[MeasureInput]\n        The MeasureInputs to be measured.\n    build_results : List[BuildResult]\n        The BuildResults to be measured.\n    key : str\n        The key of the device registered in the RPC tracker.\n    host : str\n        The host address of the RPC Tracker.\n    port : int\n        The port of RPC Tracker.\n    priority : int = 1\n        The priority of this run request, larger is more prior.\n    n_parallel : int = 1\n        The number of tasks run in parallel.\n    timeout : int = 10\n        The timeout limit (in second) for each run.\n        This is used in a wrapper of the multiprocessing.Process.join().\n    number : int = 3\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int = 1\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms : int = 0\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval : float = 0.0\n        The cool down interval between two measurements in seconds.\n    enable_cpu_cache_flush: bool = False\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    verbose: int = 1\n        Verbosity level. 0 for silent, 1 to output information during program measuring.\n    device: int = 0\n        Which device to run on if multiple are available.\n\n    Returns\n    -------\n    res : List[MeasureResult]\n        The measure results of these MeasureInputs.\n    \"\"\"\n    assert len(inputs) == len(build_results), \"Measure input size should be equal to build results\"\n    # This pool is not doing computationally intensive work, so we can use threads\n    executor = PopenPoolExecutor(n_parallel)\n    tuple_res = executor.map_with_error_catching(\n        _rpc_run_worker,\n        [\n            (\n                inp.serialize(),\n                build_res,\n                prepare_runner_args(inp, build_res),\n                key,\n                host,\n                port,\n                priority,\n                timeout,\n                number,\n                repeat,\n                min_repeat_ms,\n                cooldown_interval,\n                enable_cpu_cache_flush,\n                verbose,\n                device,\n            )\n            for inp, build_res in zip(inputs, build_results)\n        ],\n    )\n\n    results = []\n    for i, res in enumerate(tuple_res):\n        if res.status == StatusKind.COMPLETE:\n            results.append(MeasureResult(*res.value))\n        else:\n            assert res.status == StatusKind.TIMEOUT\n            if verbose >= 1:\n                print(\"*T\", end=\"\")  # Run timeout\n            build_res = build_results[i]\n            results.append(\n                MeasureResult(\n                    (MAX_FLOAT,),\n                    MeasureErrorNo.RUN_TIMEOUT,\n                    None,\n                    build_res.time_cost + timeout,\n                    time.time(),\n                )\n            )\n\n    if verbose >= 1:\n        print(\"\")\n\n    return results\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/measure_record.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, pointless-string-statement\n\n\"\"\" Serialization and other I/O support for measurement records (tuning logs). \"\"\"\nimport argparse\nimport logging\nimport os\nimport itertools\n\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom .measure import MeasureErrorNo, MeasureCallback\nfrom .utils import calc_workload_dis_factor, decode_workload_key\nfrom . import _ffi_api\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\n@tvm._ffi.register_object(\"auto_scheduler.RecordToFile\")\nclass RecordToFile(MeasureCallback):\n    \"\"\"\n    A measurement callback that writes measurement records into a file.\n\n    Parameters\n    ----------\n    filename : str\n        File name for this callback to write log to.\n    \"\"\"\n\n    def __init__(self, filename):\n        dirname = os.path.dirname(os.path.abspath(filename))\n        if not os.path.exists(dirname):\n            os.makedirs(dirname)\n        self.__init_handle_by_constructor__(_ffi_api.RecordToFile, filename)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.RecordReader\")\nclass RecordReader(Object):\n    \"\"\"\n    Reader of the json log file.\n\n    Parameters\n    ----------\n    filename : str\n        File name for this reader to load log from.\n    \"\"\"\n\n    def __init__(self, filename):\n        if not os.path.exists(filename):\n            logger.warning(\"%s does not exist!\", filename)\n        # a set to prevent print duplicated message\n        self.messages = set()\n        self.__init_handle_by_constructor__(_ffi_api.RecordReader, filename)\n\n    def check_workload_key(self, inputs):\n        \"\"\"Check and throw warnings for records with old format workload key.\n\n        Parameters\n        ----------\n        inputs: List[MeasureInput]\n            The measure inputs to be checked.\n\n        Notes\n        -----\n        This checker could be deprecated in the future.\n        \"\"\"\n        for inp in inputs:\n            _, args = decode_workload_key(inp.task.workload_key)\n            if args is None:\n                continue\n            if not args:\n                msg = (\n                    \"MeasureInput with old format workload key %s should be updated \"\n                    \"using the script from https://github.com/apache/tvm/pull/7317.\"\n                    % inp.task.workload_key\n                )\n                if msg not in self.messages:\n                    self.messages.add(msg)\n                    logger.warning(msg)\n\n    def read_lines(self, max_lines=None, skip_lines=0):\n        \"\"\"Read multiple lines from the log file.\n\n        Parameters\n        ----------\n        max_lines : Optional[int]\n            The maximum number of lines. None to read all lines.\n        skip_lines : int = 0\n            Skip the first n lines.\n\n        Returns\n        -------\n        inputs : List[auto_scheduler.measure.MeasureInput]\n            The MeasureInputs loaded from the log file.\n        results : List[auto_scheduler.measure.MeasureResult]\n            The MeasureResults loaded from the log file.\n\n        Notes\n        -----\n        Some unimportant and expensive fields in the returned MeasureInput are not deserialized\n        for faster read speed (e.g. input.task.compute_dag, input.state.stages).\n        If you want to use them, you can call the :code:`recover_measure_input` below\n        to rebuild these fields.\n        \"\"\"\n        inputs, results = _ffi_api.RecordReaderReadLines(\n            self, max_lines if max_lines else -1, skip_lines\n        )\n        self.check_workload_key(inputs)\n        return inputs, results\n\n    def __iter__(self):\n        while True:\n            ret = _ffi_api.RecordReaderReadNext(self)\n            if not ret:\n                break\n            self.check_workload_key([ret[0]])\n            yield ret[0], ret[1]  # (input, result)\n\n\ndef load_record_from_string(record):\n    \"\"\"\n    Load the measure record from string.\n\n    Parameters\n    ----------\n    record: str\n        A record string, including the serialized MeausreInput and MeasureResult.\n\n    Returns\n    -------\n    ret: Tuple[MeasureInput, MeasureResult]\n        A tuple of MeasureInput, MeasureResult.\n    \"\"\"\n    return _ffi_api.ReadMeasureRecord(record)\n\n\ndef dump_record_to_string(inp, res):\n    \"\"\"\n    Dump the measure record to a string.\n\n    Parameters\n    ----------\n    inp: MeasureInput\n        The measure input.\n\n    res: MeasureResult\n        The measure result.\n\n    Returns\n    -------\n    ret: str\n        The dumped string.\n    \"\"\"\n    return _ffi_api.WriteMeasureRecords(inp, res)\n\n\ndef load_records(filename):\n    \"\"\"\n    Load measurement records from a file.\n\n    Parameters\n    ----------\n    filename : str\n        File name to load log from.\n\n    Returns\n    -------\n    logs : List[auto_scheduler.measure.MeasureInput, auto_scheduler.measure.MeasureResult]\n\n    Notes\n    -----\n    Some unimportant and expensive fields in the returned MeasureInput are not deserialized\n    for faster read speed (e.g., input.task.compute_dag, input.state.stages).\n    If you want to use them, you can call the :code:`recover_measure_input` below\n    to rebuild these fields.\n    \"\"\"\n    return zip(*RecordReader(filename).read_lines())\n\n\ndef save_records(filename, inputs, results):\n    \"\"\"\n    Append measure records to file.\n\n    Parameters\n    ----------\n    filename : str\n        File name to write log to.\n    inputs: List[MeasureInputs]\n        The MeasureInputs to be written.\n    results: List[MeasureResults]\n        The MeasureResults to be written.\n    \"\"\"\n    dirname = os.path.dirname(os.path.abspath(filename))\n    if not os.path.exists(dirname):\n        os.makedirs(dirname)\n    _ffi_api.SaveRecords(filename, inputs, results)\n\n\ndef load_best_record(filename, workload_key=None, target=None, include_compatible=False):\n    \"\"\"Return the best measurement pair form a log file. This may return none results if\n    there is no legal measure pair with the specified workload_key/target found from the log file.\n\n    Parameters\n    ----------\n    filename : str\n        File name to load log from.\n    workload_key : Optional[str]\n        The workload key of the compute declaration.\n        With `None`, this returns the best measure pair of all workloads.\n    target : Optional[tvm.target.Target]\n        The target device.\n        With `None`, this returns the best measure pair of all target devices.\n    include_compatible: bool\n        When set to True, all compatible records in the log file will be considered.\n\n    Returns\n    -------\n    input : auto_scheduler.measure.MeasureInput\n        The best State's MeasureInput from this log fine.\n    result : auto_scheduler.measure.MeasureResult\n        The best State's MeasureResult from this log fine.\n    \"\"\"\n    log_reader = RecordReader(filename)\n    best_cost = 1e30\n    best_inp = None\n    best_res = None\n\n    for inp, res in log_reader:\n        if res.error_no != MeasureErrorNo.NO_ERROR:\n            continue\n        if target and inp.task.target.kind.name != target.kind.name:\n            continue\n\n        costs = [v.value for v in res.costs]\n        cost = np.mean(costs)\n\n        if workload_key is not None:\n            dis_f = calc_workload_dis_factor(\n                decode_workload_key(workload_key), decode_workload_key(inp.task.workload_key)\n            )\n            if dis_f == float(\"inf\"):\n                continue\n            if not include_compatible and dis_f != 1:\n                continue\n\n            # Since different workloads have different FLOPS, we multiply the factor to\n            # eliminate this difference, which is basically the concept of throughput.\n            cost *= dis_f\n\n        if cost < best_cost:\n            best_cost = cost\n            best_inp = inp\n            best_res = res\n\n    return best_inp, best_res\n\n\ndef distill_record_file(in_file, out_file):\n    \"\"\"\n    Pick the best entries from a record file and store them to another file.\n    This function distills the useful log entries from a large log file.\n    If out_file already exists, the best entries from both\n    in_file and out_file will be saved.\n\n    Parameters\n    ----------\n    in_file: str\n        The filename of input\n    out_file: str or file\n        The filename of output\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from .dispatcher import ApplyHistoryBest\n\n    context = load_records(in_file)\n\n    dirname = os.path.dirname(os.path.abspath(out_file))\n    if not os.path.exists(dirname):\n        os.makedirs(dirname)\n\n    if os.path.isfile(out_file):\n        out_context = load_records(out_file)\n        context = itertools.chain(context, out_context)\n\n    def measure_input_str_key(inp):\n        return _ffi_api.SerializeMeasureInput(inp)\n\n    # Dict[target key,\n    #   Dict[workload hash,\n    #     Dict[workload args, (cost, (MeasureInput, MeasureResult))]]]\n    # Full type: Dict[str, Dict[str, Dict[Tuple, Tuple[float, Tuple[Measureinput, MeasureResult]]]]]\n    best_records = {}\n\n    for inp, res in context:\n        if res.error_no != 0:\n            continue\n\n        # Keep the best record for each target and workload.\n        costs = [x.value for x in res.costs if isinstance(x, tvm.tir.expr.FloatImm)]\n        cost = np.mean(costs)\n        for k in inp.task.target.keys:\n            entry, _, workload_args = ApplyHistoryBest.get_workload_entry(\n                best_records, k, inp.task.workload_key\n            )\n            if workload_args not in entry or cost < entry[workload_args][0]:\n                entry[workload_args] = (cost, (inp, res))\n\n    # Remove duplications by multiple target keys.\n    out_records = {}\n    for target_entry in best_records.values():\n        for workload_entry in target_entry.values():\n            for _, (inp, res) in workload_entry.values():\n                out_records[measure_input_str_key(inp)] = (inp, res)\n\n    inputs = []\n    results = []\n    for inp, res in out_records.values():\n        inputs.append(inp)\n        results.append(res)\n\n    # create a new file and save the best records\n    open(out_file, \"w\")\n    save_records(out_file, inputs, results)\n    logger.info(\"Extract %d best records from %s to %s\", len(inputs), in_file, out_file)\n\n\ndef main():\n    \"\"\"The main function for CLI.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--mode\", choices=[\"distill\"], default=\"distill\")\n    parser.add_argument(\"-i\", \"--input\", type=str, help=\"input file\")\n    parser.add_argument(\"-o\", \"--output\", type=str, default=None, help=\"output file\")\n\n    args = parser.parse_args()\n    logging.basicConfig()\n    logger.setLevel(logging.INFO)\n\n    if args.mode == \"distill\":\n        args.output = args.output or args.input + \".best.json\"\n        distill_record_file(args.input, args.output)\n\n\n\"\"\"\nUsage:\n* Distill the best entries from a large log file\ne.g. python -m tvm.auto_scheduler.measure_record --mode distill -i input.json\n\"\"\"\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/relay_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable,invalid-name\n\n\"\"\"\nIntegrate auto_scheduler into relay. It implements the following items:\n1. Extract search tasks from a relay program\n2. Provide auto-scheduling for all TOPI compute functions\n\"\"\"\n\nimport json\nimport logging\nimport threading\nimport traceback\n\nimport tvm\nfrom tvm import autotvm, transform\nfrom tvm._ffi.base import TVMError\nfrom tvm.ir.transform import PassContext\nfrom tvm.runtime import convert_to_object\nfrom tvm.target import Target\nfrom tvm.te.tensor import ComputeOp, PlaceholderOp, Tensor\nfrom tvm.tir import Reduce\nfrom tvm.tir import expr as _expr\n\nfrom . import _ffi_api\nfrom .compute_dag import ComputeDAG, LayoutRewriteOption\nfrom .dispatcher import DispatchContext\nfrom .search_task import SearchTask\nfrom .utils import get_const_tuple\nfrom .workload_registry import register_workload_tensors\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\ndef call_all_topi_funcs(mod, params, target, error_list, opt_level=3):\n    \"\"\"Call all TOPI compute to extract auto_scheduler tasks in a Relay program\"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    # Turn off AutoTVM config not found warnings\n    old_autotvm_silent = autotvm.GLOBAL_SCOPE.silent\n    autotvm.GLOBAL_SCOPE.silent = True\n\n    with transform.PassContext(\n        opt_level=opt_level,\n        config={\n            \"relay.backend.use_auto_scheduler\": True,\n        },\n        disabled_pass={\"AutoSchedulerLayoutRewrite\"},\n    ):\n        compiler = relay.vm.VMCompiler()\n        if params:\n            compiler.set_params(params)\n        mod = tvm.IRModule.from_expr(mod) if isinstance(mod, relay.Function) else mod\n        try:\n            compiler.lower(mod, target)\n        except TVMError:\n            error_list.append(f\"{traceback.format_exc()}\")\n        finally:\n            autotvm.GLOBAL_SCOPE.silent = old_autotvm_silent\n\n\ndef extract_tasks(\n    mod,\n    params,\n    target,\n    target_host=None,\n    hardware_params=None,\n    include_simple_tasks=False,\n    dump_workload_to_dag_log=None,\n    opt_level=3,\n):\n    \"\"\"Extract tuning tasks from a relay program.\n\n    Parameters\n    ----------\n    mod: tvm.IRModule or relay.function.Function\n        The module or function to tune\n    params: dict of str to numpy array\n        The associated parameters of the program\n    target: Union[tvm.target.Target, str]\n        The compilation target\n    target_host: Optional[Union[tvm.target.Target, str]]\n        The host compilation target\n    hardware_params : Optional[HardwareParams]\n        Hardware parameters used for the search tasks\n    include_simple_tasks: bool\n        Whether to extract simple tasks that do not include complicated ops.\n    dump_workload_to_dag_log: Optional[str]\n        A file to dump an association between the workload keys and the actual DAG\n    opt_level : Optional[int]\n        The optimization level of the task extractions.\n\n    Returns\n    -------\n    tasks: List[SearchTask]\n        The tasks in this network\n    weights: List[int]\n        The weight (i.e. the number of appearance) of extracted tasks\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    # Run the compiler to collect all TOPI calls during compilation.\n    env = TracingEnvironment(\n        TracingMode.EXTRACT_TASK if include_simple_tasks else TracingMode.EXTRACT_COMPLEX_TASK_ONLY\n    )\n\n    dispatch_ctx = DispatchContext.current\n    old_verbose = dispatch_ctx.verbose\n    dispatch_ctx.verbose = 0\n\n    errors = []\n    with env:\n        # Wrap build call in a new thread to avoid the conflict\n        # between python's multiprocessing and tvm's thread pool\n        build_thread = threading.Thread(\n            target=call_all_topi_funcs, args=(mod, params, target, errors, opt_level)\n        )\n        build_thread.start()\n        build_thread.join()\n\n    if errors:\n        error_strings = [\"Task extraction had the following errors:\"] + errors\n        raise TVMError(\"\\n\".join(error_strings))\n\n    dispatch_ctx.verbose = old_verbose\n\n    # create search tasks\n    tasks = []\n    weights = []\n    for wkl_key, (weight, func_names) in env.wkl_key_to_weight.items():\n        tasks.append(\n            SearchTask(\n                workload_key=wkl_key,\n                target=target,\n                hardware_params=hardware_params,\n                # When auto scheduler is used in end to end network, try to apply layout rewrite\n                # to improve the overall performance\n                layout_rewrite_option=LayoutRewriteOption.get_target_default(target, True),\n                task_inputs=(\n                    env.wkl_key_to_input_names[wkl_key]\n                    if wkl_key in env.wkl_key_to_input_names\n                    else None\n                ),\n                task_inputs_save_to_file=True,\n                desc=\",\".join(func_names),\n            )\n        )\n        weights.append(int(weight))\n\n    if dump_workload_to_dag_log is not None:\n        with open(dump_workload_to_dag_log, \"w\") as f:\n            json.dump({task.workload_key: str(task.compute_dag) for task in tasks}, f)\n\n    return tasks, weights\n\n\nclass TracingMode:\n    \"\"\"Two modes for tracing\"\"\"\n\n    EXTRACT_TASK = 0  # trace all topi calls to extract tasks\n    # same as EXTRACT_TASK but ignore the task without complex ops\n    EXTRACT_COMPLEX_TASK_ONLY = 1\n    PREPARE_LAYOUT_REWRITE = 2  # trace topi calls to prepare layout rewrite\n\n\nclass TracingEnvironment:\n    \"\"\"Global environment for tracing all topi function calls\"\"\"\n\n    current = None\n\n    def __init__(self, tracing_mode):\n        self.tracing_mode = tracing_mode\n        self.relay_disable_build_cache = \"false\"\n        self.func_name_to_wkl_key = {}\n        self.wkl_key_to_weight = {}\n        self.wkl_key_to_input_names = {}\n\n    def __enter__(self):\n        TracingEnvironment.current = self\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        TracingEnvironment.current = None\n\n    def add_workload_key(self, func_name, workload_key):\n        \"\"\"Add the workload key of a search task.\n\n        Parameters\n        ----------\n        func_name: str\n            The function name of the task.\n\n        workload_key: str\n            The workload key of a task.\n        \"\"\"\n        self.func_name_to_wkl_key[func_name] = workload_key\n        if workload_key not in self.wkl_key_to_weight:\n            self.wkl_key_to_weight[workload_key] = (0, set())\n        weight, func_names = self.wkl_key_to_weight[workload_key]\n        func_names.add(func_name)\n        self.wkl_key_to_weight[workload_key] = (weight + 1, func_names)\n\n    def add_workload_input_names(self, workload_key, input_names):\n        \"\"\"Add special task inputs to this workload.\n\n        Parameters\n        ----------\n        workload_key : str\n            The workload key of a task.\n\n        input_names : List[str]\n            A list of input names.\n        \"\"\"\n        self.wkl_key_to_input_names[workload_key] = input_names\n\n\n@tvm._ffi.register_func(\"auto_scheduler.enter_layout_rewrite\")\ndef enter_layout_rewrite():\n    \"\"\"Enter layout rewrite tracing environment\"\"\"\n    env = TracingEnvironment(TracingMode.PREPARE_LAYOUT_REWRITE)\n    env.__enter__()\n\n\n@tvm._ffi.register_func(\"auto_scheduler.exit_layout_rewrite\")\ndef exit_layout_rewrite():\n    \"\"\"Exit layout rewrite tracing environment\"\"\"\n    env = TracingEnvironment.current\n    env.__exit__(None, None, None)\n\n\ndef traverse_to_get_io_tensors(outs):\n    \"\"\"Traverse from a list of output tensors to get input/output tensors and\n    other useful information.\n\n    Parameters\n    ----------\n    outs: List[Tensor]\n        The output tensors\n\n    Returns\n    -------\n    io_tensors: List[Tensor]\n        The input and output tensors with static shape\n    has_layout_free: bool\n        Whether the compute DAG has layout_free placeholders\n    has_complex_op: bool\n        Whether the topi compute function includes at least one complex (reduce) op\n    \"\"\"\n    layout_free_ops = []\n    inputs = []\n\n    has_complex_op = False\n    visited = set()\n\n    def traverse(t):\n        nonlocal has_complex_op\n\n        # We cannot directly add tensors to the set, because the comparison of\n        # two tensors with ndim=0 is ambiguous.\n        assert t.handle is not None\n        if t.handle.value in visited:\n            return\n        if isinstance(t.op, PlaceholderOp):\n            inputs.append(t)\n        elif isinstance(t.op, ComputeOp):\n            has_complex_op = has_complex_op or any([isinstance(e, Reduce) for e in t.op.body])\n            if \"layout_free_placeholders\" in t.op.attrs:\n                layout_free_ops.append(t.op)\n            for x in t.op.input_tensors:\n                traverse(x)\n        visited.add(t.handle.value)\n\n    for t in outs:\n        traverse(t)\n\n    io_tensors = inputs + list(outs)\n    for tensor in io_tensors:\n        # Reject the compute if any of its I/O tensors has dynamic shape.\n        if any([not isinstance(v, int) for v in get_const_tuple(tensor.shape)]):\n            return ([], False, False)\n\n    return (io_tensors, len(layout_free_ops) > 0, has_complex_op)\n\n\n@tvm._ffi.register_func(\"auto_scheduler.relay_integration.auto_schedule_topi_compute\")\ndef auto_schedule_topi(func_name, outs):\n    \"\"\"Use auto-scheduler to schedule any topi compute function.\n\n    Note: This is used internally for relay integration. Do\n    not use this as a general user-facing API.\n\n    Parameters\n    ----------\n    func_name: str\n        The name of the function being scheduled.\n\n    outs: List[Tensor]\n        The output tensors of topi compute functions\n\n    Returns\n    -------\n    sch: Optional[te.Schedule]\n        A tuned schedule or none (if not tuned) in the final build mode;\n        None in the tracing mode so that the fallback topi schedule will be used.\n    \"\"\"\n\n    # pylint: disable=import-outside-toplevel\n    from tvm.auto_scheduler.measure import (  # lazily import to avoid recursive dependency\n        prepare_input_map,\n    )\n\n    io_tensors, has_layout_free, has_complex_op = traverse_to_get_io_tensors(outs)\n    if not io_tensors:  # The compute includes dynamic shapes which are not supported yet.\n        return None\n\n    try:\n        dag = ComputeDAG(io_tensors)\n    except tvm.error.TVMError as err:\n        logger.info(\"Failed to create a ComputeDAG for auto_scheduler: %s\", str(err))\n        return None\n\n    workload_key = dag.workload_key()\n    key = register_workload_tensors(workload_key, io_tensors)\n    target = tvm.target.Target.current()\n\n    dispatch_ctx = DispatchContext.current\n    state = dispatch_ctx.query(target, key, has_complex_op, dag, func_name)\n    schedule = None\n\n    env = TracingEnvironment.current\n    if env is None:\n        # in the final build mode\n        if state is None:\n            return None\n\n        schedule, _ = dag.apply_steps_from_state(state)\n        return schedule\n\n    if env.tracing_mode in [TracingMode.EXTRACT_TASK, TracingMode.EXTRACT_COMPLEX_TASK_ONLY]:\n        # in the task extraction mode\n        if has_complex_op or env.tracing_mode == TracingMode.EXTRACT_TASK:\n            env.add_workload_key(func_name, key)\n            input_map = prepare_input_map(io_tensors, workload_key)\n            if input_map:\n                env.add_workload_input_names(key, list(input_map.values()))\n    elif env.tracing_mode == TracingMode.PREPARE_LAYOUT_REWRITE:\n        # in prepare_layout_rewrite mode\n        if (\n            LayoutRewriteOption.get_target_default(target, True) != LayoutRewriteOption.NO_REWRITE\n            and has_layout_free\n        ):\n            if state is None:\n                return None\n\n            # rewrite the layout and update the context for the new dag\n            new_dag = dag.rewrite_layout_from_state(state)\n            new_key = new_dag.workload_key()\n            if new_key != key:\n                dispatch_ctx.update(target, new_key, state)\n    else:\n        raise ValueError(\"Invalid tracing mode: \" + env.tracing_mode)\n\n    return schedule\n\n\n@tvm._ffi.register_func(\"auto_scheduler.relay_integration.te_compiler_update_weights\")\ndef te_compiler_update_weights(function_weights):\n    \"\"\"A callback for updating the weights of extracted tasks. When using the TE compiler\n    that avoids compiling the same function multiple times by caching, all extracted tasks\n    have weight 1, so the TE compiler invokes this callback at the end. In this case,\n    we override existing weights with the use_count in TE compiler cache.\n\n    Parameters\n    ----------\n    function_weights: Dict[str, int]\n        Mapping from function names to their weights.\n    \"\"\"\n    env = TracingEnvironment.current\n    if env is not None:\n        # Override this map with the weights in the TE compiler.\n        env.wkl_key_to_weight = {}\n\n        for func_name, weight in function_weights.items():\n            # If the function name is not in the map, then it means we are not interested in\n            # this function during task extraction (e.g., a function without reduction).\n            if func_name not in env.func_name_to_wkl_key:\n                continue\n\n            workload_key = env.func_name_to_wkl_key[func_name]\n            if workload_key not in env.wkl_key_to_weight:\n                env.wkl_key_to_weight[workload_key] = (0, set())\n\n            # Note that the function appears multiple times in a model will be renamed\n            # to make sure function names are unique, so we use the workload key generated\n            # from the function's TE compute to determine their weights.\n            old_weight, func_names = env.wkl_key_to_weight[workload_key]\n            func_names.add(func_name)\n            env.wkl_key_to_weight[workload_key] = (old_weight + weight, func_names)\n\n\ndef tensor_no_check_call(self, *indices):\n    \"\"\"An indexing function without any check.\n    This is the same as `tvm.te.Tensor::__call__` except that the safety\n    check is removed.\n    \"\"\"\n    indices = convert_to_object(indices)\n    args = []\n    for x in indices:\n        if isinstance(x, _expr.PrimExpr):\n            args.append(x)\n        elif isinstance(x, _expr.IterVar):\n            args.append(x.var)\n        else:\n            raise ValueError(\"The indices must be expression\")\n\n    return _expr.ProducerLoad(self, args)\n\n\ndef remove_index_check(tensor):\n    \"\"\"Remove the safety check in the indexing function for a tensor.\n    This is done by monkey patching its indexing function.\n    After removing the check, we are allowed to create a\n    temporary wrong IR and fix it later in other places.\n\n    Parameters\n    ----------\n    tensor: Tensor\n      The tensor to remove index check.\n    \"\"\"\n    # Monkey patch the indexing function\n    tensor.__call__ = tensor_no_check_call.__get__(tensor, Tensor)\n\n\ndef rewrite_compute_body(compute_tensor, new_layout):\n    \"\"\"Rewrite the body of a ComputeOp according to a new layout of a placeholder\"\"\"\n    op = compute_tensor.op\n\n    # Get layout free placeholders\n    layout_free_placeholders = op.attrs[\"layout_free_placeholders\"]\n    assert len(layout_free_placeholders) == 1, \"Only support one layout free placeholder\"\n    placeholder_op = layout_free_placeholders[0].op\n\n    # Rewrite the index expression in body\n    body = []\n    for b in op.body:\n        body.append(_ffi_api.RewriteIndexForNewLayout(placeholder_op, new_layout, b))\n    op_node = tvm.te._ffi_api.ComputeOp(op.name, op.tag, op.attrs, op.axis, body)\n\n    num = op_node.num_outputs\n    outputs = tuple(op_node.output(i) for i in range(num))\n    return outputs[0] if num == 1 else outputs\n\n\ndef rewrite_tensor_shape(tensor, shape):\n    \"\"\"Rewrite the tensor shape\"\"\"\n    _ffi_api.RewriteTensorShape(tensor, shape)\n\n\ndef is_auto_scheduler_enabled():\n    \"\"\"Return whether the auto-scheduler is enabled.\n\n    Parameters\n    ----------\n    enabled: bool\n        Whether the auto-scheduler is enabled\n    \"\"\"\n    return PassContext.current().config.get(\n        \"relay.backend.use_auto_scheduler\",\n        False,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/search_policy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThe search policies of TVM auto-scheduler.\n\nThe auto-scheduler constructs a search space according to the compute declaration.\nIt then randomly samples programs from the search space and uses evolutionary search with a\nlearned cost model to fine tune the sampled programs.\nThe final optimized programs are sent to actual hardware for measurement.\nThe above process is repeated until the auto-scheduler runs out of time budget.\n\nReference:\nL. Zheng, C. Jia, M. Sun, Z. Wu, C. Yu, et al. \"Ansor : Generating High-Performance Tensor\nPrograms for Deep Learning.\" (OSDI 2020).\n\"\"\"\n\nimport random\n\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom .cost_model import RandomModel\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"auto_scheduler.SearchCallback\")\nclass SearchCallback(Object):\n    \"\"\"Callback function before or after search process\"\"\"\n\n\n@tvm._ffi.register_object(\"auto_scheduler.PreloadMeasuredStates\")\nclass PreloadMeasuredStates(SearchCallback):\n    \"\"\"A SearchCallback to load measured states from the log file for a search policy.\n\n    This can resume the state of the search policy:\n        - Making sure an already measured state in former searches will never be measured again.\n        - The history states can be used to speed up the search process(e.g. SketchPolicy uses\n          history states as starting point to perform Evolutionary Search).\n\n    Parameters\n    ----------\n    filename : str\n        The name of the record file.\n    \"\"\"\n\n    def __init__(self, filename):\n        self.__init_handle_by_constructor__(_ffi_api.PreloadMeasuredStates, filename)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.PreloadCustomSketchRule\")\nclass PreloadCustomSketchRule(SearchCallback):\n    \"\"\"\n    A SearchCallback for SketchSearchPolicy that allows users to add\n    custom sketch rule.\n\n    Notes\n    -----\n    This is an advanced feature. Make sure you're clear how it works and this should only be used\n    in SketchSearchPolicy.\n\n    Parameters\n    ----------\n    meet_condition_func: Callable\n        A function with `(policy, state, stage_id) -> int`. Should return one of the result\n        enumeration.\n    apply_func: Callable\n        A function with `(policy, state, stage_id) -> [[State, int], ...]`.\n    rule_name: str = \"CustomSketchRule\"\n        The name of this custom sketch rule.\n    \"\"\"\n\n    # Result enumeration of the condition function.\n    PASS = 0  # Skip this rule and continue to try the next rules.\n    APPLY = 1  # Apply this rule and continue to try the next rules.\n    APPLY_AND_SKIP_REST = 2  # Apply this rule and skip the rest rules.\n\n    def __init__(self, meet_condition_func, apply_func, rule_name=\"CustomSketchRule\"):\n        self.__init_handle_by_constructor__(\n            _ffi_api.PreloadCustomSketchRule, meet_condition_func, apply_func, rule_name\n        )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.SearchPolicy\")\nclass SearchPolicy(Object):\n    \"\"\"The base class of search policies.\"\"\"\n\n    def continue_search_one_round(self, num_measure, measurer):\n        \"\"\"\n        Continue the search by doing an additional search round.\n\n        Parameters\n        ----------\n        num_measure: int\n            The number of programs to measure in this round\n        measurer: ProgramMeasurer\n            The program measurer to measure programs\n\n        Returns\n        -------\n        inputs: List[MeasureInput]\n            The inputs of measurments in this search round\n        results: List[MeasureResult]\n            The results of measurments in this search round\n        \"\"\"\n        return _ffi_api.SearchPolicyContinueSearchOneRound(self, num_measure, measurer)\n\n    def set_verbose(self, verbose):\n        \"\"\"\n        Set the verbosity level of the search policy.\n\n        Parameters\n        ----------\n        verbose: int\n            The verbosity level\n        \"\"\"\n        return _ffi_api.SearchPolicySetVerbose(self, verbose)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.EmptyPolicy\")\nclass EmptyPolicy(SearchPolicy):\n    \"\"\"A simple example of the search policy which always returns\n    the initial naive schedule (state).\n\n    Parameters\n    ----------\n    task : SearchTask\n        The SearchTask for the computation declaration.\n    init_search_callbacks : Optional[List[SearchCallback]]\n        Callback functions called before the search process.\n    \"\"\"\n\n    def __init__(self, task, init_search_callbacks=None):\n        self.__init_handle_by_constructor__(_ffi_api.EmptyPolicy, task, init_search_callbacks)\n\n\n@tvm._ffi.register_object(\"auto_scheduler.SketchPolicy\")\nclass SketchPolicy(SearchPolicy):\n    \"\"\"The search policy that searches in a hierarchical search space defined by sketches.\n    The policy randomly samples programs from the space defined by sketches and use evolutionary\n    search to fine-tune them.\n\n    Parameters\n    ----------\n    task : SearchTask\n        The SearchTask for the computation declaration.\n    program_cost_model : CostModel = RandomModel()\n        The cost model to estimate the complete schedules.\n    params : Optional[Dict[str, Any]]\n        Parameters of the search policy.\n        See `src/auto_scheduler/search_policy/sketch_search_policy.h` for the definitions.\n        See `DEFAULT_PARAMS` below to find the default values.\n    seed : Optional[int]\n        Random seed.\n    verbose : int = 1\n        Verbosity level. 0 for silent, 1 to output information during schedule search.\n    init_search_callbacks : Optional[List[SearchCallback]]\n        Callback functions called before the search process, usually used to do extra\n        initializations.\n        Possible callbacks:\n\n          - auto_scheduler.PreloadMeasuredStates\n          - auto_scheduler.PreloadCustomSketchRule\n    \"\"\"\n\n    DEFAULT_PARAMS = {\n        \"eps_greedy\": 0.05,\n        \"retry_search_one_round_on_empty\": 1,\n        \"sample_init_min_population\": 50,\n        \"sample_init_use_measured_ratio\": 0.2,\n        \"evolutionary_search_population\": 2048,\n        \"evolutionary_search_num_iters\": 4,\n        \"evolutionary_search_mutation_prob\": 0.85,\n        \"cpu_multi_level_tiling_structure\": \"SSRSRS\",\n        \"gpu_multi_level_tiling_structure\": \"SSSRRSRS\",\n        # Notice: the default thread bind policy of GPU assumes the tiling structure to have at\n        # least 3 spatial tiling levels in outermost\n        \"max_innermost_split_factor\": 64,\n        \"max_vectorize_size\": 16,\n        \"disable_change_compute_location\": 0,\n    }\n\n    def __init__(\n        self,\n        task,\n        program_cost_model=RandomModel(),\n        params=None,\n        seed=None,\n        verbose=1,\n        init_search_callbacks=None,\n    ):\n        if params is None:\n            params = SketchPolicy.DEFAULT_PARAMS\n        else:\n            for key, value in SketchPolicy.DEFAULT_PARAMS.items():\n                if key not in params:\n                    params[key] = value\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.SketchPolicy,\n            task,\n            program_cost_model,\n            params,\n            seed or random.randint(1, 1 << 30),\n            verbose,\n            init_search_callbacks,\n        )\n\n    def generate_sketches(self, print_for_debug=False):\n        \"\"\"Generate the sketches.\n        This python interface is mainly used for debugging and testing.\n        The actual search is all done in c++.\n\n        Parameters\n        ----------\n        print_for_debug : bool = False\n            Whether print out the sketches for debug.\n\n        Returns\n        -------\n        sketches : List[State]\n            The generated sketches of this search task.\n        \"\"\"\n        sketches = _ffi_api.SketchPolicyGenerateSketches(self)\n        if print_for_debug:\n            for i, s in enumerate(sketches):\n                print(\"=\" * 20 + \" %d \" % i + \"=\" * 20)\n                print(s)\n        return sketches\n\n    def sample_initial_population(self):\n        \"\"\"Sample initial population.\n        This python interface is mainly used for debugging and testing.\n        The actual search is all done in c++.\n\n        Returns\n        -------\n        states: List[State]\n            The sampled states\n        \"\"\"\n        states = _ffi_api.SketchPolicySampleInitialPopulation(self)\n        return states\n\n    def evolutionary_search(self, init_populations, out_size):\n        \"\"\"Perform evolutionary search.\n        This python interface is mainly used for debugging and testing.\n        The actual search is all done in c++.\n\n        Parameters\n        ----------\n        init_populations: List[State]\n            The initial population states\n        out_size : int\n            The size of generated states\n\n        Returns\n        -------\n        states: List[State]\n            The generated states\n        \"\"\"\n        states = _ffi_api.SketchPolicyEvolutionarySearch(self, init_populations, out_size)\n        return states\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/search_task.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" The definiton of SearchTask \"\"\"\n\nimport json\n\nimport os\nimport logging\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm.runtime import Object, ndarray\n\nfrom tvm.driver.build_module import build\nfrom tvm.target import Target\nfrom .measure import LocalBuilder, LocalRunner\nfrom .measure_record import load_best_record\nfrom .workload_registry import make_workload_key\nfrom .compute_dag import ComputeDAG, LayoutRewriteOption\nfrom .cost_model import XGBModel\nfrom .search_policy import SketchPolicy\nfrom .workload_registry import WORKLOAD_FUNC_REGISTRY, register_workload_tensors\nfrom . import _ffi_api\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\n@tvm._ffi.register_object(\"auto_scheduler.HardwareParams\")\nclass HardwareParams(Object):\n    \"\"\"The parameters of target hardware used to guide the search policy.\n\n    When a parameter isn't provided, it will instead use the\n    current machine's default value if target is specified.\n    TODO(jcf94): This is considered to be merged with the new Target specification:\n    https://discuss.tvm.apache.org/t/rfc-tvm-target-specification/6844\n    Parameters\n    ----------\n    num_cores : int, optional\n        The number of device cores.\n    vector_unit_bytes : int, optional\n        The width of vector units in bytes.\n    cache_line_bytes : int, optional\n        The size of cache line in bytes.\n    max_shared_memory_per_block : int, optional\n        The max shared memory per block in bytes.\n    max_local_memory_per_block : int, optional\n        The max local memory per block in bytes.\n    max_threads_per_block : int, optional\n        The max number of threads per block.\n    max_vthread_extent : int, optional\n        The max vthread extent.\n    warp_size : int, optional\n        The thread numbers of a warp.\n    target : str or Target, optional\n        The compilation target. Used to determine default values if provided.\n    target_host : str or Target, optional\n        The compilation target host. Used to determine default values if provided.\n    \"\"\"\n\n    def __init__(\n        self,\n        num_cores=None,\n        vector_unit_bytes=None,\n        cache_line_bytes=None,\n        max_shared_memory_per_block=None,\n        max_local_memory_per_block=None,\n        max_threads_per_block=None,\n        max_vthread_extent=None,\n        warp_size=None,\n        target=None,\n        target_host=None,\n    ):\n        # If target is provided, get the default paramters for this machine.\n        if target is not None:\n            if isinstance(target, str):\n                target = tvm.target.Target(target)\n            if isinstance(target_host, str):\n                target_host = tvm.target.Target(target_host)\n            default_params = _ffi_api.GetDefaultHardwareParams(target, target_host)\n\n            if num_cores is None:\n                num_cores = default_params.num_cores\n            if vector_unit_bytes is None:\n                vector_unit_bytes = default_params.vector_unit_bytes\n            if cache_line_bytes is None:\n                cache_line_bytes = default_params.cache_line_bytes\n            if max_shared_memory_per_block is None:\n                max_shared_memory_per_block = default_params.max_shared_memory_per_block\n            if max_local_memory_per_block is None:\n                max_local_memory_per_block = default_params.max_local_memory_per_block\n            if max_threads_per_block is None:\n                max_threads_per_block = default_params.max_threads_per_block\n            if max_vthread_extent is None:\n                max_vthread_extent = default_params.max_vthread_extent\n            if warp_size is None:\n                warp_size = default_params.warp_size\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.HardwareParams,\n            num_cores,\n            vector_unit_bytes,\n            cache_line_bytes,\n            max_shared_memory_per_block,\n            max_local_memory_per_block,\n            max_threads_per_block,\n            max_vthread_extent,\n            warp_size,\n        )\n\n    def __str__(self):\n        \"\"\"Pretty printing for hardware parameter configuration.\"\"\"\n        format_str = (\n            \"HardwareParams:\\n\"\n            f\"  num_cores: {self.num_cores}\\n\"\n            f\"  vector_unit_bytes: {self.vector_unit_bytes}\\n\"\n            f\"  cache_line_bytes: {self.cache_line_bytes}\\n\"\n            f\"  max_shared_memory_per_block: {self.max_shared_memory_per_block}\\n\"\n            f\"  max_local_memory_per_block: {self.max_local_memory_per_block}\\n\"\n            f\"  max_threads_per_block: {self.max_threads_per_block}\\n\"\n            f\"  max_vthread_extent: {self.max_vthread_extent}\\n\"\n            f\"  warp_size: {self.warp_size}\\n\"\n        )\n        return format_str\n\n\n@tvm._ffi.register_object(\"auto_scheduler.TuningOptions\")\nclass TuningOptions(Object):\n    \"\"\"This controls the options of performance tuning.\n\n    Parameters\n    ----------\n    num_measure_trials: int = 0\n        The number of measurement trials.\n        The search policy measures `num_measure_trials` schedules in total and returns the best one\n        among them.\n        With `num_measure_trials` == 0, the policy will do the schedule search but won't involve\n        measurement. This can be used to get a runnable schedule quickly without auto-tuning.\n    early_stopping: Optional[int]\n        Stop the tuning early if getting no improvement after n measurements.\n    num_measures_per_round: int = 64\n        The number of schedules to be measured at each search round.\n        The whole schedule search process will try a total number of `num_measure_trials` in several\n        rounds.\n    verbose: int = 1\n        Verbosity level. 0 for silent, 1 to output information during schedule search.\n    builder: Union[ProgramBuilder, str] = 'local'\n        ProgramBuilder which builds the program.\n    runner: Union[ProgramRunner, str] = 'local'\n        ProgramRunner which runs the program and measures time costs.\n    measure_callbacks: Optional[List[MeasureCallback]]\n        Callback functions called after each measurement.\n        Candidates:\n        - auto_scheduler.RecordToFile\n    \"\"\"\n\n    def __init__(\n        self,\n        num_measure_trials=0,\n        early_stopping=None,\n        num_measures_per_round=64,\n        verbose=1,\n        builder=\"local\",\n        runner=\"local\",\n        measure_callbacks=None,\n    ):\n        if isinstance(builder, str):\n            if builder == \"local\":\n                builder = LocalBuilder()\n            else:\n                raise ValueError(\"Invalid builder: \" + builder)\n        elif not isinstance(builder, tvm.auto_scheduler.measure.ProgramBuilder):\n            raise ValueError(\n                \"Invalid builder: \"\n                + builder\n                + \" . TuningOptions expects a ProgramBuilder or string.\"\n            )\n\n        if isinstance(runner, str):\n            if runner == \"local\":\n                runner = LocalRunner()\n            else:\n                raise ValueError(\"Invalid runner: \" + runner)\n        elif not isinstance(runner, tvm.auto_scheduler.measure.ProgramRunner):\n            raise ValueError(\n                \"Invalid runner: \" + runner + \" . TuningOptions expects a ProgramRunner or string.\"\n            )\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.TuningOptions,\n            num_measure_trials,\n            early_stopping or -1,\n            num_measures_per_round,\n            verbose,\n            builder,\n            runner,\n            measure_callbacks,\n        )\n\n\n# The map stores special registered buffer for measurement.\n# This can be used for sparse workloads when we cannot use random tensors for measurment.\n# {\n#     \"workload_key_0\": {\n#         \"task_input_0\": Tensor(...),\n#         \"task_input_1\": Tensor(...)\n#     },\n#     \"workload_key_1\": {\n#         \"task_input_2\": Tensor(...),\n#         \"task_input_3\": Tensor(...)\n#     },\n#     ...\n# }\nTASK_INPUT_BUFFER_TABLE = {}\n\n\ndef _save_buffer_to_file(buffer_name, buffer_data):\n    \"\"\"Save the current Tensor buffer to a numpy file.\n\n    File name will be: {buffer_name}.{buffer_shape}_{buffer_data_type}.npy\n    \"\"\"\n    np_data = buffer_data.numpy()\n\n    buffer_name += \".\"\n    for i in np_data.shape:\n        buffer_name += \"%d_\" % (i)\n    buffer_name += \"%s\" % (np_data.dtype)\n    buffer_name += \".npy\"\n\n    np_data.tofile(buffer_name, \" \")\n\n\ndef _try_load_buffer_from_file(buffer_name):\n    \"\"\"Try to load buffer from a numpy file, if not found, return None.\n\n    File name has a same format as `_save_buffer_to_file`.\n    \"\"\"\n    filelist = os.listdir()\n\n    for file in filelist:\n        if file.startswith(buffer_name + \".\"):\n            meta_info = file.split(\".\")[-2].split(\"_\")\n            shape = [int(i) for i in meta_info[:-1]]\n            dtype = meta_info[-1]\n            buffer_data = np.fromfile(file, dtype=dtype, sep=\" \")\n            buffer_data = buffer_data.reshape(shape)\n            return ndarray.array(buffer_data)\n\n    return None\n\n\ndef register_task_input_buffer(\n    workload_key,\n    input_name,\n    input_data,\n    overwrite=False,\n    save_to_file=False,\n):\n    \"\"\"Register special buffer for measurement.\n\n    Parameters\n    ----------\n    workload_key : str\n        The workload key of the SearchTask.\n\n    input_name : str\n        The name of input buffer.\n\n    input_data : tvm.nd.NDArray\n        The input Tensor data.\n\n    overwrite : bool = False\n        Whether to overwrite the data if a name has already registered.\n\n    save_to_file : bool = False\n        Whether to save the data to a local file as well. This can be reused to resume the last\n        tuning process.\n\n    Returns\n    -------\n    tvm.nd.NDArray\n        The actual registered Tensor data of this input_name. With `overwrite` set to False, will\n        return the original one if the name has already registered before.\n    \"\"\"\n    global TASK_INPUT_BUFFER_TABLE\n\n    if workload_key not in TASK_INPUT_BUFFER_TABLE:\n        TASK_INPUT_BUFFER_TABLE[workload_key] = {}\n    input_table = TASK_INPUT_BUFFER_TABLE[workload_key]\n\n    if not overwrite:\n        if input_name not in input_table.keys():\n            # Try to load buffer data from local file\n            tensor_from_file = _try_load_buffer_from_file(input_name)\n            if tensor_from_file:\n                input_table[input_name] = tensor_from_file\n        elif input_name in input_table.keys():\n            raise RuntimeError(\n                \"Tensor %s exists in TASK_INPUT_BUFFER_TABLE, %s\"\n                % (input_name, \"set overwrite to True or this Tensor will not be registered\")\n            )\n\n    input_table[input_name] = input_data\n    if save_to_file:\n        _save_buffer_to_file(input_name, input_data)\n    return input_data\n\n\ndef get_task_input_buffer(workload_key, input_name):\n    \"\"\"Get special buffer for measurement.\n\n    The buffers are registered by `register_task_input_buffer`.\n\n    Parameters\n    ----------\n    workload_key : str\n        The workload key of the SearchTask.\n\n    input_name : str\n        The name of input buffer.\n\n    Returns\n    -------\n    tvm.nd.NDArray\n        The registered input buffer.\n    \"\"\"\n    global TASK_INPUT_BUFFER_TABLE\n\n    if workload_key not in TASK_INPUT_BUFFER_TABLE:\n        TASK_INPUT_BUFFER_TABLE[workload_key] = {}\n    input_table = TASK_INPUT_BUFFER_TABLE[workload_key]\n\n    if input_name not in input_table:\n        # Try to load buffer data from local file\n        tensor_from_file = _try_load_buffer_from_file(input_name)\n        if tensor_from_file:\n            input_table[input_name] = tensor_from_file\n\n    # Then check for the default table, the input names extracted from a relay model will be\n    # stored here for we're not able to get the workload_key at that time\n    if input_name not in input_table:\n        input_table = TASK_INPUT_BUFFER_TABLE[\"default\"]\n\n    if input_name in input_table:\n        return input_table[input_name]\n\n    raise ValueError(\n        \"%s not found in TASK_INPUT_BUFFER_TABLE, \" % (input_name)\n        + \"should provide with `SearchTask(..., task_inputs={...})`\"\n    )\n\n\n@tvm._ffi.register_object(\"auto_scheduler.SearchTask\")\nclass SearchTask(Object):\n    \"\"\"The computation information and hardware parameters for a schedule search task.\n\n    Parameters\n    ----------\n    func : Union[Function, str]\n        The function that returns the compute declaration Tensors.\n        Can be the a function or the function name.\n    args : Union[Tuple[Any, ...], List[Any]]\n        The args of the function.\n    compute_dag : ComputeDAG\n        The ComputeDAG for the corresponding compute declaration.\n    workload_key : str\n        The workload key for the corresponding compute declaration.\n    target : any target-like object, see Target.canon_target\n        The target device of this search task.\n    target_host : None or any target-like object, see Target.canon_target\n        The target host device of this search task.\n    hardware_params : Optional[HardwareParams]\n        Hardware parameters used in this search task.\n    layout_rewrite_option : Optional[LayoutRewriteOption]\n        The layout rewrite option used for measuring programs. If None, the default value will be\n        set depending on the specified target.\n        Auto_scheduler will find a better schedule for the specified layout rewrite option.\n        The NO_REWRITE and INSERT_TRANSFORM_STAGE are expected to be used when tuning a standalone\n        op, and the REWRITE_FOR_PRE_TRANSFORMED is expected to be used when tuning ops inside a\n        network.\n    task_inputs : Union[Dict[str, tvm.nd.NDArray], List[str]]\n        A dict maps the input names to input tensors or a list of input names.\n        Some special Tensor used as inputs in program measuring. Usually we do not need to care\n        about it, but for special workloads like Sparse computation the Sparse Tensor input are\n        meaningful that we cannot use random input directly.\n    task_inputs_overwrite : bool = False\n        Whether to overwrite the data if a name has already in the global table.\n    task_inputs_save_to_file : bool = False\n        Whether to save the data to a local file as well. This can be reused to resume the last\n        tuning process.\n    desc: str = \"\"\n        The description string of this task.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      # We support two ways to create a search task\n\n      # Way 1: create a task by a workload generation function.\n      # The `workload_func` is a function decorated by @auto_scheduler.register_workload\n      task = SearchTask(func=workload_func, args=args, target=target)\n\n      # Way 2: create a task by a workload_key.\n      # The `workload_key` is a string, which can be either a hash key or a json-serialized\n      # tuple(func, args).\n      task = SearchTask(workload_key=workload_key, target=target)\n    \"\"\"\n\n    def __init__(\n        self,\n        func=None,\n        args=None,\n        compute_dag=None,\n        workload_key=None,\n        target=None,\n        target_host=None,\n        hardware_params=None,\n        layout_rewrite_option=None,\n        task_inputs=None,\n        task_inputs_overwrite=False,\n        task_inputs_save_to_file=False,\n        desc=\"\",\n    ):\n        assert (\n            func is not None or workload_key is not None\n        ), \"Either a workload generation function or a workload key should be provided\"\n\n        if func is not None:\n            workload_key = make_workload_key(func, args)\n        if compute_dag is None:\n            compute_dag = ComputeDAG(workload_key)\n\n        assert target is not None, \"Must specify a target.\"\n\n        target, target_host = Target.canon_target_and_host(target, target_host)\n\n        if layout_rewrite_option is None:\n            layout_rewrite_option = LayoutRewriteOption.get_target_default(target)\n\n        task_input_names = []\n        if isinstance(task_inputs, list):\n            task_input_names = task_inputs\n        elif isinstance(task_inputs, dict):\n            for input_name in task_inputs:\n                register_task_input_buffer(\n                    workload_key,\n                    input_name,\n                    task_inputs[input_name],\n                    task_inputs_overwrite,\n                    task_inputs_save_to_file,\n                )\n                task_input_names.append(input_name)\n        elif task_inputs is not None:\n            raise ValueError(\"task_inputs should be a dict or a list.\")\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchTask,\n            compute_dag,\n            workload_key,\n            target,\n            target_host,\n            hardware_params,\n            layout_rewrite_option,\n            task_input_names,\n            desc,\n        )\n\n    def tune(self, tuning_options, search_policy=None, adaptive_training=False):\n        \"\"\"Run auto scheduling search for a task\n\n        Parameters\n        ----------\n        tuning_options : TuningOptions\n            Tuning and measurement options.\n        search_policy : Optional[SearchPolicy]\n            The search policy to be used for schedule search.\n        \"\"\"\n        if search_policy is None:\n            cost_model = XGBModel(adaptive_training=adaptive_training)\n            search_policy = SketchPolicy(self, cost_model)\n\n        _ffi_api.AutoSchedule(search_policy, tuning_options)\n\n    def apply_best(self, log_file, include_compatible=False, layout_rewrite_option=None):\n        \"\"\"Apply the history best from a log file and return the schedule.\n\n        Parameters\n        ----------\n        log_file : str\n           The name of the log file.\n        include_compatible: bool\n            When set to True, all compatible records in the log file will be considered.\n        layout_rewrite_option : Optional[LayoutRewriteOption]\n           The layout rewrite option.\n\n\n        Returns\n        -------\n            A `te.Schedule` and the a list of `te.Tensor` to be used in `tvm.lower` or `tvm.build`.\n        \"\"\"\n        inp, _ = load_best_record(\n            log_file, self.workload_key, include_compatible=include_compatible\n        )\n        if inp is None:\n            raise RuntimeError(\n                \"Cannot find any valid schedule for %s in file %s\" % (self.workload_key, log_file)\n            )\n\n        sch, args = self.compute_dag.apply_steps_from_state(\n            inp.state, layout_rewrite_option or self.layout_rewrite_option\n        )\n        return sch, args\n\n    def print_best(self, log_file, print_mode=\"schedule\"):\n        \"\"\"Print the best schedule as python schedule API code or CUDA source code.\n\n        Parameters\n        ----------\n        log_file : str\n           The name of the log file\n        print_mode: str\n           if \"schedule\", print the best schedule as python schedule API code.\n           if \"cuda\", print the best schedule as CUDA source code.\n\n        Returns\n        -------\n        code: str\n            The best schedule code in python API or CUDA source code\n        \"\"\"\n        inp, _ = load_best_record(log_file, self.workload_key)\n        if inp is None:\n            raise RuntimeError(\n                \"Cannot find any valid schedule for %s in file %s\" % (self.workload_key, log_file)\n            )\n\n        if print_mode == \"schedule\":\n            return self.compute_dag.print_python_code_from_state(inp.state)\n        if print_mode == \"cuda\":\n            assert self.target.kind.name == \"cuda\"\n            sch, args = self.compute_dag.apply_steps_from_state(inp.state)\n            func = build(sch, args, \"cuda\")\n            return func.imported_modules[0].get_source()\n        raise ValueError(\"Invalid print_mode: %s\" % print_mode)\n\n    def __getstate__(self):\n        self.target, self.target_host = Target.canon_target_and_host(self.target, self.target_host)\n        return {\n            \"compute_dag\": self.compute_dag,\n            \"workload_key\": self.workload_key,\n            \"target\": self.target,\n            \"target_host\": self.target_host,\n            \"hardware_params\": self.hardware_params,\n            \"layout_rewrite_option\": self.layout_rewrite_option,\n            \"task_input_names\": self.task_input_names,\n            \"desc\": self.desc,\n        }\n\n    def __setstate__(self, state):\n        # Register the workload if needed\n        try:\n            workload = json.loads(state[\"workload_key\"])\n        except Exception:  # pylint: disable=broad-except\n            raise RuntimeError(\"Invalid workload key %s\" % state[\"workload_key\"])\n\n        # workload[0] is either the compute function name or the ComputeDAG hash.\n        # The compute functions are already registered when importing TVM, so here\n        # we only register the ComputeDAG workloads. If the same workload has\n        # already been registered, the later registration overrides the prvious one.\n        if workload[0] not in WORKLOAD_FUNC_REGISTRY:\n            register_workload_tensors(state[\"workload_key\"], state[\"compute_dag\"].tensors)\n\n        state[\"target\"], state[\"target_host\"] = Target.canon_target_and_host(\n            state[\"target\"], state[\"target_host\"]\n        )\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchTask,\n            state[\"compute_dag\"],\n            state[\"workload_key\"],\n            state[\"target\"],\n            state[\"target\"].host,\n            state[\"hardware_params\"],\n            state[\"layout_rewrite_option\"],\n            state[\"task_input_names\"],\n            state[\"desc\"],\n        )\n\n\ndef create_task(func, args, target, target_host=None, hardware_params=None):\n    \"\"\"THIS API IS DEPRECATED.\n\n    Create a search task.\n\n    Parameters\n    ----------\n    func : Union[Function, str]\n        The function that returns the compute declaration Tensors.\n        Can be the a function or the function name.\n    args : Union[Tuple[Any, ...], List[Any]]\n        The args of the function.\n    target : Union[tvm.target.Target, str]\n        The target device of this search task.\n    target_host : Optional[Union[tvm.target.Target, str]]\n        The target host device of this search task.\n    hardware_params : Optional[HardwareParams]\n        Hardware parameters used in this search task.\n\n    Returns\n    -------\n        SearchTask: the created task\n    \"\"\"\n    raise ValueError(\n        'The API \"auto_scheduler.create_task\" is deprecated.'\n        \"See https://github.com/apache/tvm/pull/7028 for the upgrade guide\"\n    )\n\n\ndef auto_schedule(task, search_policy=None, tuning_options=TuningOptions()):\n    \"\"\"THIS API IS DEPRECATED.\n\n    Run auto scheduling search for a task.\n\n    Parameters\n    ----------\n    task : SearchTask\n        The SearchTask for the computation declaration.\n    search_policy : Optional[SearchPolicy]\n        The search policy to be used for schedule search.\n    tuning_options : Optional[TuningOptions]\n        Tuning and measurement options.\n\n    Returns\n    -------\n        A `te.Schedule` and the a list of `te.Tensor` to be used in `tvm.lower` or `tvm.build`.\n    \"\"\"\n    raise ValueError(\n        'The API \"auto_scheduler.create_task\" is deprecated.'\n        \"See https://github.com/apache/tvm/pull/7028 for the upgrade guide.\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/task_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" The task scheduler that allocates the time resources when tuning multiple tasks together\n\nThe details of the \"gradient\" strategy below can be found in the section 6 of this paper:\nL. Zheng, C. Jia, M. Sun, Z. Wu, C. Yu, et al. \"Ansor : Generating High-Performance Tensor\nPrograms for Deep Learning.\" (OSDI 2020).\n\"\"\"\nimport os\nimport time\nimport math\nimport logging\n\nimport numpy as np\n\nfrom .search_policy import SearchPolicy, SketchPolicy, PreloadMeasuredStates\nfrom .cost_model import RandomModel, XGBModel\nfrom .utils import array_mean\nfrom .measure import ProgramMeasurer\nfrom .measure_record import RecordReader\nfrom . import _ffi_api\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n\ndef make_search_policies(\n    search_policy,\n    search_policy_params,\n    tasks,\n    num_measures_per_round,\n    verbose,\n    load_model_file=None,\n    load_log_file=None,\n    adaptive_training=False,\n):\n    \"\"\"Make a list of search policies for a list of search tasks.\n    It creates one policy per task.\n\n    Parameters\n    ----------\n    search_policy: Union[str, List[SearchPolicy]]\n        The name of search policy.\n    search_policy_params: Dict[str, Any]]\n        The parameters of the search policy.\n    tasks: List[SearchTask]\n        The list of all tasks\n    num_measures_per_round: int\n        The number of schedules to be measured at each search round.\n        This should be the same as `TuningOptions.num_measures_per_round`\n    verbose: int\n        The verbosity level. 0 for silent.\n    load_model_file: Optional[str]\n        Load pre-trained model from this file. If this is None, the cost model will\n        be trained from scratch.\n    load_log_file: Optional[str]\n        Load measurement records from this file. If it is not None, the status of the\n        task scheduler, search policies and cost models will be restored according to this file.\n    adaptive_training: bool = False\n        Option used by XGBModel to reduce the model training frequency when there're too\n        many logs.\n\n    Returns\n    -------\n    policies: List[SearchPolicy]\n        The list of search policies\n    \"\"\"\n    if search_policy == \"default\":\n        search_policy = \"sketch.xgb\"\n\n    if isinstance(search_policy, str):\n        policy_type, model_type = search_policy.split(\".\")\n        if model_type == \"xgb\":\n            cost_model = XGBModel(\n                num_warmup_sample=len(tasks) * num_measures_per_round,\n                model_file=load_model_file,\n                adaptive_training=adaptive_training,\n            )\n            if load_model_file and os.path.isfile(load_model_file):\n                logger.info(\"TaskScheduler: Load pretrained model...\")\n                cost_model.load(load_model_file)\n            elif load_log_file:\n                logger.info(\"TaskScheduler: Reload measured states and train the model...\")\n                cost_model.update_from_file(load_log_file)\n        elif model_type == \"random\":\n            cost_model = RandomModel()\n        else:\n            raise ValueError(\"Invalid search policy: \" + search_policy)\n\n        if policy_type == \"sketch\":\n            if load_log_file:\n                # use the log file to restore the status of search policies.\n                init_search_callbacks = [PreloadMeasuredStates(load_log_file)]\n            else:\n                init_search_callbacks = None\n            search_policies = [\n                SketchPolicy(\n                    task,\n                    cost_model,\n                    params=search_policy_params,\n                    verbose=verbose,\n                    init_search_callbacks=init_search_callbacks,\n                )\n                for task in tasks\n            ]\n        else:\n            raise ValueError(\"Invalid search policy: \" + search_policy)\n    else:\n        # check type\n        assert isinstance(search_policy, (tuple, list))\n        for item in search_policy:\n            assert isinstance(item, SearchPolicy)\n        search_policies = search_policy\n\n    return search_policies\n\n\ndef derive_similarity_tag(dag, log_base=1.618):\n    \"\"\"Derive the tag for similarity check from one computational DAG.\n    The DAGs with the same tag are considered as similar tasks.\n\n    The tag format is <op1-tag>_<op2-tag> ... <log(flop)>.\n\n    If the tag is \"\", then the task is not considered to be similar to any other tasks.\n\n    Parameters\n    ----------\n    dag: ComputeDAG\n        The input computational DAG\n    log_base: float = 1.618\n        The base of log to normalize FLOPS\n\n    Returns\n    -------\n    tag: str\n        The tag of this computational DAG.\n    \"\"\"\n    ret = \"\"\n    for op in dag.ops:\n        tag = op.attrs.get(\"auto_scheduler_task_scheduler_tag\", None)\n        if tag:\n            ret += op.attrs[\"auto_scheduler_task_scheduler_tag\"] + \"_\"\n    if ret:\n        ret += \"%d\" % int(math.log(dag.flop_ct + 1, log_base))\n    return ret\n\n\nclass TaskScheduler:\n    \"\"\"\n    Allocate the time resources when tuning multiple tasks together.\n    This implements two strategies: \"round-robin\" and \"gradient\".\n\n    Parameters\n    ----------\n    tasks: List[SearchTask]\n        All tasks to tune\n    task_weights: Optional[List[float]]\n        The weights of tasks.\n        If provided, the task scheduler will set the objective function to\n        sum(weight[t] * latency[t]), where weight[t] is the weight of a task\n        and the lantecy[t] is the lantecy of the task.\n        If not provided, the task scheduer will assign equal weights to all\n        tasks (i.e., the objective function is sum(latency[t])).\n    objective_func: Optional[Callable[List[float] -> float]]\n        The objective function to be minimized.\n        The objective function accepts the current latencies of all tasks and returns the\n        objective.\n        If not provided, the objective is the weighted sum of the latencies of all tasks.\n    strategy: str = \"gradient\"\n        The scheduling strategy.\n        \"round-robin\": Tune tasks in round robin order.\n        \"gradient\" : Tune tasks with gradient descent.\n    load_model_file: Optional[str]\n        Load pre-trained model from this file. If this is None, the cost model will\n        be trained from scratch.\n    load_log_file: Optional[str]\n        Load measurement records from this file. If it is not None, the status of the\n        task scheduler, search policies and cost models will be restored according to this file.\n    verbose: int = 1\n        The level of verbosity. 0 means silent.\n    alpha: float = 0.2\n        The parameter used for 'gradient' strategy\n    beta: float = 2\n        The parameter used for 'gradient' strategy\n    backward_window_size: int = 3\n        The parameter used for 'gradient' strategy\n    callbacks: Optional[List[TaskSchedulerCallback]]\n        The task scheduler callbacks that will be called before and after tuning a task.\n        If None, PrintTableInfo and LogEstimatedLatency callback will be used.\n    \"\"\"\n\n    def __init__(\n        self,\n        tasks,\n        task_weights=None,\n        objective_func=None,\n        strategy=\"gradient\",\n        load_model_file: str = None,\n        load_log_file: str = None,\n        alpha: float = 0.2,\n        beta: float = 2,\n        gamma: float = 0.5,\n        backward_window_size: int = 3,\n        callbacks=None,\n    ):\n        self.tasks = tasks\n        if objective_func:  # use custom objective function\n            self.objective_func = objective_func\n        else:  # use weighted sum\n            if task_weights:\n                self.objective_func = lambda costs: sum(c * w for c, w in zip(costs, task_weights))\n            else:\n                self.objective_func = sum\n\n        self.strategy = strategy\n        self.load_log_file = load_log_file\n        self.load_model_file = load_model_file\n        self.alpha = alpha\n        self.beta = beta\n        self.gamma = gamma\n        self.backward_window_size = backward_window_size\n        self.callbacks = (\n            callbacks\n            if callbacks is not None\n            else [PrintTableInfo(), LogEstimatedLatency(\"total_latency.tsv\")]\n        )\n\n        assert len(self.tasks) != 0, \"No tasks\"\n        assert self.strategy in [\"round-robin\", \"gradient\"]\n\n        # task_cts[i] saves how many times task i is tuned\n        self.task_cts = [0 for _ in range(len(self.tasks))]\n\n        # task_best_cts[i] saves the round task i found the best latency\n        self.task_best_cts = [0 for _ in range(len(self.tasks))]\n\n        # task_costs_history[i] saves the latency history of task i\n        self.task_costs_history = [[] for _ in range(len(self.tasks))]\n\n        # best_costs[i] saves the best latency of task i\n        self.best_costs = 1e10 * np.ones(len(self.tasks))\n        self.cur_score = self._compute_score(self.best_costs)\n\n        self.tune_option = self.measurer = self.search_policies = None\n        self.ct = self.best_ct = self.best_score = self.tic = None\n        self.num_measures_per_round = None\n        self.dead_tasks = set()\n\n        # Build similarity groups\n        self.task_tags = []  # task_id -> tag\n        self.tag_to_group_id = {}  # tag -> group_id\n        self.group_task_ids = []  # group_id -> all task ids in this group\n        self.flop_cts = []  # task_id -> the number of floating ops\n        for i, task in enumerate(self.tasks):\n            tag = derive_similarity_tag(task.compute_dag)\n            self.task_tags.append(tag)\n            self.flop_cts.append(task.compute_dag.flop_ct)\n            if not tag:\n                continue\n\n            if tag not in self.tag_to_group_id:\n                self.tag_to_group_id[tag] = len(self.tag_to_group_id)\n                self.group_task_ids.append([])\n            self.group_task_ids[self.tag_to_group_id[tag]].append(i)\n\n    def tune(\n        self,\n        tune_option,\n        search_policy=\"default\",\n        search_policy_params=None,\n        adaptive_training=False,\n        per_task_early_stopping=None,\n    ):\n        \"\"\"Tune a batch of tasks together.\n\n        Parameters\n        ----------\n        tune_option: TuningOptions\n            The tuning options applied to all tasks.\n        search_policy: : Union[str, List[SearchPolicy]] = \"default\"\n            The list of search policies.\n            If it is str,\n            \"default\" for the default policy (SketchPolicy + XGBModel),\n            \"sketch.xgb\" for SketchPolicy + XGBModel,\n            \"sketch.random\" for SketchPolicy + RandomModel.\n        search_policy_params : Optional[Dict[str, Any]]\n            The parameters of the search policy\n        adaptive_training : bool = False\n            Option used by XGBModel to reduce the model training frequency when there're\n            too many logs.\n        per_task_early_stopping : Optional[int]\n            Stop tuning a task early if getting no improvement after n measurements.\n        \"\"\"\n        # init members\n        self.tune_option = tune_option\n        self.early_stopping_all = (\n            1e20 if tune_option.early_stopping < 0 else tune_option.early_stopping\n        )\n        self.early_stopping_task = (\n            1e20 if per_task_early_stopping is None else per_task_early_stopping\n        )\n\n        self.measurer = ProgramMeasurer(\n            tune_option.builder,\n            tune_option.runner,\n            tune_option.measure_callbacks,\n            tune_option.verbose,\n        )\n        self.ct = self.best_ct = 0\n        self.tic = time.time()\n\n        # reset num_measures_per_round to make sure every task is tuned at least once\n        self.num_measures_per_round = min(\n            tune_option.num_measures_per_round, tune_option.num_measure_trials // len(self.tasks)\n        )\n        if self.num_measures_per_round <= 0:\n            raise ValueError(\n                \"num_measure_trials is too small. Please set it to a higher value.\"\n                f\"It should be at least {len(self.tasks)} for this model.\"\n            )\n\n        # restore the status of the task scheduler from a log file\n        if self.load_log_file:\n            self._restore_status(self.load_log_file, self.num_measures_per_round)\n\n        # make one search policy for one task\n        self.search_policies = make_search_policies(\n            search_policy,\n            search_policy_params,\n            self.tasks,\n            self.num_measures_per_round,\n            tune_option.verbose,\n            self.load_model_file,\n            self.load_log_file,\n            adaptive_training,\n        )\n\n        # do a round robin first to warm up\n        for idx in range(len(self.tasks)):\n            # skip warming up this task if it has been tuned before (restored from the log file)\n            if not self.task_cts[idx]:\n                self._tune_task(idx)\n        self.best_ct = self.ct\n        self.best_score = self.cur_score\n\n        # use the specific strategy to choose workload to tune\n        task_idx = -1\n        while self.ct < tune_option.num_measure_trials and len(self.dead_tasks) < len(self.tasks):\n            if self.strategy == \"round-robin\":\n                task_idx = (task_idx + 1) % len(self.tasks)\n                while task_idx in self.dead_tasks:\n                    task_idx = (task_idx + 1) % len(self.tasks)\n            elif self.strategy == \"gradient\":\n                gradients = []\n                for i in range(len(self.tasks)):\n                    if i in self.dead_tasks:\n                        gradients.append(0)\n                        continue\n\n                    # compute gradient from chain rule : (delta f / delta g_i)\n                    delta = 1e-4\n                    new_costs = list(self.best_costs)\n                    new_costs[i] -= delta\n                    chain_grad = (\n                        self._compute_score(self.best_costs) - self._compute_score(new_costs)\n                    ) / delta\n\n                    # compute (g_i(t_i) - g(t_i - \\Delta t)) / (\\Delta t)\n                    if (\n                        self.task_cts[i] - 1 < len(self.task_costs_history[i])\n                        and self.task_cts[i] - 1 - self.backward_window_size >= 0\n                    ):\n                        backward_grad = (\n                            self.task_costs_history[i][self.task_cts[i] - 1]\n                            - self.task_costs_history[i][\n                                self.task_cts[i] - 1 - self.backward_window_size\n                            ]\n                        ) / self.backward_window_size\n                    else:\n                        backward_grad = 0\n\n                    # compute (g_i(t_i + \\Delta t) - g(t_i)) / (\\Delta t)\n                    g_next_1 = self.best_costs[i] - (self.best_costs[i] / self.task_cts[i])\n\n                    g_next_2 = self.beta * 1e30\n                    group_id = self.tag_to_group_id.get(self.task_tags[i], None)\n                    if group_id is not None and len(self.group_task_ids[group_id]) > 1:\n                        best_flops = max(\n                            [\n                                self.flop_cts[j] / self.best_costs[j]\n                                for j in self.group_task_ids[group_id]\n                            ]\n                        )\n                        g_next_2 = self.beta * self.flop_cts[i] / best_flops\n\n                    g_next = min(g_next_1, g_next_2)\n                    forward_grad = g_next - self.best_costs[i]\n\n                    # combine all grads\n                    grad = chain_grad * (\n                        self.alpha * backward_grad + (1 - self.alpha) * forward_grad\n                    )\n                    assert grad <= 0\n                    gradients.append(grad)\n\n                if max(gradients) == min(gradients):\n                    task_idx = np.random.choice(len(gradients))\n                else:\n                    task_idx = np.argmin(gradients)\n            else:\n                raise ValueError(\"Invalid strategy: \" + self.strategy)\n\n            self._tune_task(task_idx)\n            self._adjust_similarity_group(task_idx)\n\n            if self.cur_score < self.best_score:\n                self.best_score = self.cur_score\n                self.best_ct = self.ct\n            elif self.ct - self.best_ct >= self.early_stopping_all and all(\n                cost < 1e9 for cost in self.best_costs\n            ):\n                if self.tune_option.verbose >= 1:\n                    print(\n                        \"Stop early since no performance improvement in the last \"\n                        + str(self.early_stopping_all)\n                        + \" measurement trials.\"\n                    )\n                break\n\n    def _tune_task(self, task_idx):\n        \"\"\"Tune the select task for one round\"\"\"\n\n        # Run pre-tune callbacks\n        for callback in self.callbacks:\n            callback.pre_tune(self, task_idx)\n\n        measure_inputs, measure_results = self.search_policies[task_idx].continue_search_one_round(\n            self.num_measures_per_round, self.measurer\n        )\n\n        self.task_cts[task_idx] += 1\n\n        for res in measure_results:\n            cost = array_mean(res.costs)\n            if cost < self.best_costs[task_idx]:\n                self.task_best_cts[task_idx] = self.task_cts[task_idx]\n                self.best_costs[task_idx] = cost\n\n        # Stop tuning this task in the rest of the process if its search space has been\n        # fully explored or it has no improvement for a long while.\n        no_change_trials = (\n            self.task_cts[task_idx] - self.task_best_cts[task_idx]\n        ) * self.num_measures_per_round\n        if len(measure_inputs) == 0 or no_change_trials > self.early_stopping_task:\n            self.dead_tasks.add(task_idx)\n\n        self.task_costs_history[task_idx].append(self.best_costs[task_idx])\n\n        self.ct += len(measure_inputs)\n        self.cur_score = self._compute_score(self.best_costs)\n\n        # Run post-tune callbacks\n        for callback in self.callbacks:\n            callback.post_tune(self, task_idx)\n\n    def _compute_score(self, costs):\n        \"\"\"compute the objective function\"\"\"\n        # Make sure to return float.\n        score = self.objective_func(costs)\n        return score.value if hasattr(score, \"value\") else score\n\n    def _adjust_similarity_group(self, task_idx):\n        \"\"\"adjust the similarity group for the selected task\"\"\"\n        group_id = self.tag_to_group_id.get(self.task_tags[task_idx], None)\n        if group_id is None or len(self.group_task_ids[group_id]) <= 1:\n            return\n\n        group_ids = self.group_task_ids[group_id]\n        best_group_flops = max([self.flop_cts[j] / self.best_costs[j] for j in group_ids])\n        cur_flops = self.flop_cts[task_idx] / self.best_costs[task_idx]\n\n        # if we tune a task for many times but it still cannot achieve\n        # a similar speed to the fastest one in its group, this means this task\n        # is actually not similar to other tasks in its group.\n        # So we will remove it from its original group.\n        if cur_flops < best_group_flops / self.beta and self.task_cts[task_idx] > 5 + max(\n            self.task_cts[j] for j in group_ids if j != task_idx\n        ):\n            self.task_tags[task_idx] = None\n            group_ids.remove(task_idx)\n\n    def _restore_status(self, log_file, num_measures_per_round):\n        \"\"\"restore task_cts and best_costs from a log file\"\"\"\n        str_target = str(self.tasks[0].target)\n        workload_key_to_task_id = {t.workload_key: i for i, t in enumerate(self.tasks)}\n        total_ct = -1\n\n        for total_ct, (inp, res) in enumerate(RecordReader(log_file)):\n            if str(inp.task.target) != str_target:\n                continue\n            task_idx = workload_key_to_task_id.get(inp.task.workload_key, None)\n            if task_idx is None:\n                continue\n\n            self.task_cts[task_idx] += 1\n\n            if res.error_no == 0:\n                cost = array_mean(res.costs)\n                if cost < self.best_costs[task_idx]:\n                    self.best_costs[task_idx] = cost\n                    self.task_best_cts[task_idx] = self.task_cts[task_idx]\n\n        for idx in range(len(self.tasks)):\n            if self.task_cts[idx] - self.task_best_cts[idx] > self.early_stopping_task:\n                self.dead_tasks.add(idx)\n\n            # The computation of taks_cts is just an estimation.\n            # The estimation may not be accurate if the log file is changed externally or\n            # `num_measures_per_round` is different from the last tuning.\n            self.task_cts[idx] = int(self.task_cts[idx] / num_measures_per_round + 0.5)\n            self.task_best_cts[idx] = int(self.task_best_cts[idx] / num_measures_per_round + 0.5)\n            self.task_costs_history[idx].append(self.best_costs[idx])\n\n        self.cur_score = self._compute_score(self.best_costs)\n\n        logger.info(\"TaskScheduler: Loaded %d measurement records from %s\", total_ct + 1, log_file)\n\n\nclass TaskSchedulerCallback:\n    \"\"\"The base class of task scheduler callback functions.\"\"\"\n\n    def pre_tune(self, task_scheduler, task_id):\n        \"\"\"The callback before tuning each task.\n\n        Parameters\n        ----------\n        task_scheduler: TaskScheduler\n            The task scheduler.\n        task_id: int\n            The task ID going to be tuned.\n        \"\"\"\n        # Do nothing by default\n\n    def post_tune(self, task_scheduler, task_id):\n        \"\"\"The callback after tuning each task.\n\n        Parameters\n        ----------\n        task_scheduler: TaskScheduler\n            The task scheduler.\n        task_id: int\n            The task ID be tuned.\n        \"\"\"\n        # Do nothing by default\n\n\nclass PrintTableInfo(TaskSchedulerCallback):\n    \"\"\"The callback that prints a table of current progress.\"\"\"\n\n    def pre_tune(self, task_scheduler, task_id):\n        if task_scheduler.tune_option.verbose < 1:\n            return\n\n        _ffi_api.PrintTitle(\"Task Scheduler\")\n        print(\n            \"|  ID  \"\n            \"|                       Task Description                        \"\n            \"| Latency (ms) | Speed (GFLOPS) | Trials |\"\n        )\n        print(\n            \"----------------------------------------------------------------\"\n            \"-------------------------------------------------\"\n        )\n\n        # content\n        for i in range(len(task_scheduler.tasks)):\n            id_str = \"%d\" % i\n            latency_str = (\n                \"%.3f\" % (1e3 * task_scheduler.best_costs[i])\n                if task_scheduler.best_costs[i] < 1e9\n                else \"-\"\n            )\n            task_desc = task_scheduler.tasks[i].desc\n            speed_str = (\n                \"%.2f\"\n                % (task_scheduler.tasks[i].compute_dag.flop_ct / task_scheduler.best_costs[i] / 1e9)\n                if task_scheduler.best_costs[i] < 1e9\n                else \"-\"\n            )\n            trials_str = \"%d\" % (task_scheduler.task_cts[i] * task_scheduler.num_measures_per_round)\n            print(\n                \"| %4s | %61s | %12s | % 14s | %6s |\"\n                % (id_str, task_desc, latency_str, speed_str, trials_str)\n            )\n        print(\n            \"----------------------------------------------------------------\"\n            \"-------------------------------------------------\"\n        )\n\n        # overall info\n        if all(cost < 1e9 for cost in task_scheduler.best_costs):\n            total_latency_str = \"%.3f\" % (task_scheduler.cur_score * 1e3)\n        else:\n            total_latency_str = \"-\"\n        print(\n            \"Estimated total latency: %s ms\\tTrials: %d\\tUsed time : %.0f s\\tNext ID: %d\\t\"\n            % (\n                total_latency_str,\n                task_scheduler.ct,\n                time.time() - task_scheduler.tic,\n                task_id,\n            )\n        )\n\n\nclass LogEstimatedLatency(TaskSchedulerCallback):\n    \"\"\"Log the estimated latency to the file after tuning a task.\n\n    Parameters\n    ----------\n    log_file: str\n        The log file path.\n    \"\"\"\n\n    def __init__(self, log_file):\n        if os.path.exists(log_file):  # Remove existing log\n            os.remove(log_file)\n\n        self.log_file = log_file\n\n    def post_tune(self, task_scheduler, task_id):\n        if all(cost < 1e9 for cost in task_scheduler.best_costs):\n            total_latency_str = \"%.3f\" % (task_scheduler.cur_score * 1e3)\n        else:\n            total_latency_str = \"N/A\"\n\n        with open(self.log_file, \"a\") as filep:\n            filep.write(\n                \"ElapsedTime(s)\\t%.0f\\tEstimatedLatency(ms)\\t%s\\tTrials\\t%d\\n\"\n                % (\n                    time.time() - task_scheduler.tic,\n                    total_latency_str,\n                    task_scheduler.ct,\n                )\n            )\n            filep.flush()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\"Testing utilities in auto scheduler.\"\"\"\n\n# NOTE: Do not import any module here by default\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/testing/tune_onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nfrom distutils.util import strtobool\nimport argparse\nimport json\nimport os\nimport onnx  # type: ignore\n\nimport tvm\nfrom tvm import auto_scheduler\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.tune_utils import generate_input_data, create_timer\nfrom tvm.meta_schedule.utils import cpu_count\nfrom tvm.relay.frontend import from_onnx\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--model-name\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--onnx-path\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--input-shape\",\n        type=str,\n        required=True,\n        help='example: `[{\"name\": \"input1\", \"dtype\": \"int64\", \"shape\": [1, 1, 8]}]',\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        help=\"example: graph / vm\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.input_shape = json.loads(parsed.input_shape)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    return parsed\n\n\nARGS = _parse_args()\n\n\ndef main():\n    log_file = os.path.join(ARGS.work_dir, f\"{ARGS.model_name}.json\")\n\n    runner = auto_scheduler.RPCRunner(\n        key=ARGS.rpc_key,\n        host=ARGS.rpc_host,\n        port=ARGS.rpc_port,\n        n_parallel=cpu_count(logical=True),\n        number=ARGS.number,\n        repeat=ARGS.repeat,\n        min_repeat_ms=ARGS.min_repeat_ms,\n        enable_cpu_cache_flush=ARGS.cpu_flush,\n        timeout=ARGS.rpc_config.session_timeout_sec,\n    )\n\n    if ARGS.target.kind.name == \"llvm\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=int(ARGS.target.attrs[\"num-cores\"]),\n            target=ARGS.target,\n        )\n    elif ARGS.target.kind.name == \"cuda\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=-1,\n            vector_unit_bytes=16,\n            cache_line_bytes=64,\n            max_shared_memory_per_block=int(ARGS.target.attrs[\"max_shared_memory_per_block\"]),\n            max_threads_per_block=int(ARGS.target.attrs[\"max_threads_per_block\"]),\n            # The value `max_local_memory_per_block` is not used in AutoScheduler,\n            # but is required by the API.\n            max_local_memory_per_block=12345678,\n            max_vthread_extent=8,\n            warp_size=32,\n        )\n    else:\n        raise NotImplementedError(f\"Unsupported target {ARGS.target}\")\n\n    describe()\n    print(f\"Workload: {ARGS.model_name}\")\n    onnx_model = onnx.load(ARGS.onnx_path)\n    shape_dict = {}\n    for item in ARGS.input_shape:\n        print(f\"  input_name : {item['name']}\")\n        print(f\"  input_shape: {item['shape']}\")\n        print(f\"  input_dtype: {item['dtype']}\")\n        shape_dict[item[\"name\"]] = item[\"shape\"]\n    mod, params = from_onnx(onnx_model, shape_dict, freeze_params=True)\n    input_data = {\n        item[\"name\"]: generate_input_data(item[\"shape\"], item[\"dtype\"]) for item in ARGS.input_shape\n    }\n\n    with ms.Profiler() as profiler:\n        tasks, task_weights = auto_scheduler.extract_tasks(\n            mod[\"main\"],\n            params,\n            target=ARGS.target,\n            hardware_params=hardware_params,\n        )\n        for idx, (task, task_weight) in enumerate(zip(tasks, task_weights)):\n            print(\n                f\"==== Task {idx}: {task.desc} \"\n                f\"(weight {task_weight} key: {task.workload_key}) =====\"\n            )\n            print(task.compute_dag)\n\n        if ARGS.num_trials > 0:\n            tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n            tuner.tune(\n                auto_scheduler.TuningOptions(\n                    num_measure_trials=ARGS.num_trials,\n                    runner=runner,\n                    measure_callbacks=[\n                        auto_scheduler.RecordToFile(log_file),\n                    ],\n                ),\n                adaptive_training=ARGS.adaptive_training,\n            )\n\n        relay_build = {\"graph\": relay.build, \"vm\": relay.vm.compile}[ARGS.backend]\n        with auto_scheduler.ApplyHistoryBest(log_file):\n            with tvm.transform.PassContext(\n                opt_level=3,\n                config={\"relay.backend.use_auto_scheduler\": True},\n            ):\n                lib = relay_build(\n                    mod,\n                    target=ARGS.target,\n                    params=params,\n                )\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    run_module_via_rpc(\n        rpc_config=ARGS.rpc_config,\n        lib=lib,\n        dev_type=ARGS.target.kind.name,\n        args=input_data,\n        continuation=create_timer(ARGS.backend),\n        backend=ARGS.backend,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/testing/tune_relay.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport argparse\nimport json\nimport os\nfrom distutils.util import strtobool\n\nimport tvm\nfrom tvm import auto_scheduler\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.meta_schedule.testing.tune_utils import create_timer, generate_input_data\nfrom tvm.meta_schedule.utils import cpu_count\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--workload\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--input-shape\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--layout\",\n        type=str,\n        default=None,\n    )\n    args.add_argument(\n        \"--cache-dir\",\n        type=str,\n        default=None,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        help=\"example: graph / vm\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.input_shape = json.loads(parsed.input_shape)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    return parsed\n\n\nARGS = _parse_args()\n\n\ndef main():\n    log_file = os.path.join(ARGS.work_dir, f\"{ARGS.workload}.json\")\n\n    runner = auto_scheduler.RPCRunner(\n        key=ARGS.rpc_key,\n        host=ARGS.rpc_host,\n        port=ARGS.rpc_port,\n        n_parallel=cpu_count(logical=True),\n        number=ARGS.number,\n        repeat=ARGS.repeat,\n        min_repeat_ms=ARGS.min_repeat_ms,\n        enable_cpu_cache_flush=ARGS.cpu_flush,\n        timeout=ARGS.rpc_config.session_timeout_sec,\n    )\n\n    if ARGS.target.kind.name == \"llvm\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=int(ARGS.target.attrs[\"num-cores\"]),\n            target=ARGS.target,\n        )\n    elif ARGS.target.kind.name == \"cuda\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=-1,\n            vector_unit_bytes=16,\n            cache_line_bytes=64,\n            max_shared_memory_per_block=int(ARGS.target.attrs[\"max_shared_memory_per_block\"]),\n            max_threads_per_block=int(ARGS.target.attrs[\"max_threads_per_block\"]),\n            # The value `max_local_memory_per_block` is not used in AutoScheduler,\n            # but is required by the API.\n            max_local_memory_per_block=12345678,\n            max_vthread_extent=8,\n            warp_size=32,\n        )\n    else:\n        raise NotImplementedError(f\"Unsupported target {ARGS.target}\")\n\n    describe()\n    print(f\"Workload: {ARGS.workload}\")\n    mod, params, (input_name, input_shape, input_dtype) = get_network(\n        ARGS.workload,\n        ARGS.input_shape,\n        layout=ARGS.layout,\n        cache_dir=ARGS.cache_dir,\n    )\n    input_info = [\n        {\n            \"name\": input_name,\n            \"shape\": input_shape,\n            \"dtype\": input_dtype,\n        },\n    ]\n    input_data = {\n        item[\"name\"]: generate_input_data(item[\"shape\"], item[\"dtype\"]) for item in input_info\n    }\n    for item in input_info:\n        print(f\"  input_name : {item['name']}\")\n        print(f\"  input_shape: {item['shape']}\")\n        print(f\"  input_dtype: {item['dtype']}\")\n\n    with ms.Profiler() as profiler:\n        with ms.Profiler.timeit(\"TaskExtraction\"):\n            tasks, task_weights = auto_scheduler.extract_tasks(\n                mod[\"main\"],\n                params,\n                target=ARGS.target,\n                hardware_params=hardware_params,\n            )\n            for idx, (task, task_weight) in enumerate(zip(tasks, task_weights)):\n                print(\n                    f\"==== Task {idx}: {task.desc} \"\n                    f\"(weight {task_weight} key: {task.workload_key}) =====\"\n                )\n                print(task.compute_dag)\n\n        with ms.Profiler.timeit(\"Tuning\"):\n            if ARGS.num_trials > 0:\n                tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n                tuner.tune(\n                    auto_scheduler.TuningOptions(\n                        num_measure_trials=ARGS.num_trials,\n                        runner=runner,\n                        measure_callbacks=[\n                            auto_scheduler.RecordToFile(log_file),\n                        ],\n                    ),\n                    adaptive_training=ARGS.adaptive_training,\n                )\n\n        relay_build = {\"graph\": relay.build, \"vm\": relay.vm.compile}[ARGS.backend]\n        with ms.Profiler.timeit(\"PostTuningCompilation\"):\n            with auto_scheduler.ApplyHistoryBest(log_file):\n                with tvm.transform.PassContext(\n                    opt_level=3,\n                    config={\"relay.backend.use_auto_scheduler\": True},\n                ):\n                    lib = relay_build(\n                        mod,\n                        target=ARGS.target,\n                        params=params,\n                    )\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    run_module_via_rpc(\n        rpc_config=ARGS.rpc_config,\n        lib=lib,\n        dev_type=ARGS.target.kind.name,\n        args=input_data,\n        continuation=create_timer(ARGS.backend),\n        backend=ARGS.backend,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/testing/tune_te.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nfrom distutils.util import strtobool\nimport argparse\nimport os\n\nimport tvm\nfrom tvm import auto_scheduler\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.te_workload import CONFIGS\nfrom tvm.meta_schedule.utils import cpu_count\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--workload\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        required=False,\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=60,\n    )\n    return parsed\n\n\nARGS = _parse_args()\n\n\ndef main():\n    log_file = os.path.join(ARGS.work_dir, f\"{ARGS.workload}.json\")\n\n    runner = auto_scheduler.RPCRunner(\n        key=ARGS.rpc_key,\n        host=ARGS.rpc_host,\n        port=ARGS.rpc_port,\n        n_parallel=cpu_count(logical=True),\n        number=ARGS.number,\n        repeat=ARGS.repeat,\n        min_repeat_ms=ARGS.min_repeat_ms,\n        enable_cpu_cache_flush=ARGS.cpu_flush,\n        timeout=ARGS.rpc_config.session_timeout_sec,\n    )\n\n    if ARGS.target.kind.name == \"llvm\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=int(ARGS.target.attrs[\"num-cores\"]),\n            target=ARGS.target,\n        )\n    elif ARGS.target.kind.name == \"cuda\":\n        hardware_params = auto_scheduler.HardwareParams(\n            num_cores=-1,\n            vector_unit_bytes=16,\n            cache_line_bytes=64,\n            max_shared_memory_per_block=int(ARGS.target.attrs[\"max_shared_memory_per_block\"]),\n            max_threads_per_block=int(ARGS.target.attrs[\"max_threads_per_block\"]),\n            # The value `max_local_memory_per_block` is not used in AutoScheduler,\n            # but is required by the API.\n            max_local_memory_per_block=12345678,\n            max_vthread_extent=8,\n            warp_size=32,\n        )\n    else:\n        raise NotImplementedError(f\"Unsupported target {ARGS.target}\")\n\n    describe()\n    print(f\"Workload: {ARGS.workload}\")\n    with ms.Profiler() as profiler:\n        # Same as MetaSchedule Tune TE\n        # Does not count ApplyHistoryBest time\n\n        workload_func, params = CONFIGS[ARGS.workload]\n        params = params[0]  # type: ignore\n        workload_func = auto_scheduler.register_workload(workload_func)\n\n        task = auto_scheduler.SearchTask(\n            func=workload_func,\n            args=params,\n            target=ARGS.target,\n            hardware_params=hardware_params,\n        )\n        # Inspect the computational graph\n        print(\"Computational DAG:\")\n        print(task.compute_dag)\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=ARGS.num_trials,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n            verbose=2,\n            runner=runner,\n        )\n        if ARGS.num_trials > 0:\n            print(\"Running AutoTuning:\")\n            task.tune(tune_option, adaptive_training=ARGS.adaptive_training)\n\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    print(\"History Best:\")\n    print(task.print_best(log_file))\n\n    sch, args = task.apply_best(log_file)\n    print(\"Lowered TIR:\")\n    print(tvm.lower(sch, args, simple_mode=True))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" Common utilities for auto_scheduler. \"\"\"\n\nfrom typing import Hashable\nimport json\nimport signal\nimport threading\nimport traceback\nimport os\n\nimport numpy as np\n\ntry:\n    import psutil\nexcept ImportError:\n    psutil = None\n\nimport tvm\nfrom tvm import rpc\nfrom tvm.tir import expr\nfrom tvm.tir.transform import Simplify\nfrom tvm.ir.transform import Sequential\nfrom ..te import Tensor, placeholder\n\n\ndef decode_workload_key(workload_key):\n    \"\"\"Decode the workload key from a string to the name and arguments. The wokrload key\n    is expected to be a list of \"[func_name/hash, args ...]\" in a JSON string. If not,\n    then simply return the workload key as the name without arguments.\n\n    Parameters\n    ----------\n    workload_key: str\n        The workload key in string. Format: \"[func_name/hash, args ...]\".\n\n    Returns\n    -------\n    name: str\n        The workload function name or the DAG hash.\n    args: Optional[Tuple[Any, ...]]\n        The flatten arguments in a tuple, or None if the workload key format is not decodeable.\n    \"\"\"\n\n    def flatten_list(inp):\n        ret = []\n        for elt in inp:\n            if isinstance(elt, list):\n                ret += flatten_list(elt)\n            else:\n                ret.append(elt)\n        return ret\n\n    try:\n        key_list = json.loads(workload_key)\n        if isinstance(key_list, list) and len(key_list) >= 1:\n            return key_list[0], tuple(flatten_list(key_list[1:]))\n    except json.decoder.JSONDecodeError:\n        pass\n    return workload_key, None\n\n\ndef calc_workload_dis_factor(target_workload_pair, workload_pair):\n    \"\"\"Calculate the distance factor of the workload to the target workload.\n    If two workloads are not compatible at all (i.e., different compute DAG or function),\n    then the distance factor is \"inf\". Otherwise, we calculate the factor by traversing\n    the workload arguments, which are the arguments of the compute function,\n    or the output shapes for the ComputeDAG. The factor is calculated by the following rules:\n\n    1. For non-zero integer values: `product(target_arg / candidate_arg)`.\n    2. For non-integer or zero values: \"inf\" if not equal else 1.\n\n    As a result, factor=1 is the optimal when two workloads are identical.\n\n    Parameters\n    ----------\n    target_workload_pair: Tuple[str, Optional[Tuple[Any, ...]]]\n        The target workload pair: (hash, argument tuple).\n\n    workload_pair: Tuple[str, Optional[Tuple[Any, ...]]]\n        The candidate workload pair: (hash, argument tuple).\n\n    Returns\n    -------\n    dis_f: float\n        The distance factor.\n    \"\"\"\n    target_key, target_args = target_workload_pair\n    target_args = target_args if target_args is not None else []\n    key, args = workload_pair\n    args = args if args is not None else []\n\n    # Not even the same func/DAG.\n    if key != target_key or len(target_args) != len(args):\n        return float(\"inf\")\n\n    dis_f = 1\n    for target_arg, arg in zip(target_args, args):\n        if isinstance(target_arg, int):\n            if target_arg == 0 or arg == 0:\n                if target_arg != arg:\n                    return float(\"inf\")\n            elif target_arg % arg != 0:\n                return float(\"inf\")\n            else:\n                dis_f *= target_arg / arg\n        elif target_arg != arg:\n            return float(\"inf\")\n    return dis_f\n\n\ndef get_func_name(func):\n    \"\"\"Get name of a function.\n\n    Parameters\n    ----------\n    func: Function\n        The input function.\n\n    Returns\n    -------\n    name: str\n        The function name.\n    \"\"\"\n    return func.func_name if hasattr(func, \"func_name\") else func.__qualname__\n\n\ndef get_const_int(exp):\n    \"\"\"Verifies expr is integer and get the constant value.\n\n    Parameters\n    ----------\n    exp : Union[tvm.tir.expr, int]\n        The input expression.\n\n    Returns\n    -------\n    out_value : int\n        The output.\n    \"\"\"\n    if isinstance(exp, int):\n        return exp\n    if not isinstance(exp, expr.IntImm):\n        opt = Sequential([Simplify()])\n        exp = opt(exp)\n    if not isinstance(exp, expr.IntImm):\n        raise ValueError(\"Expect value to be constant int\")\n    return exp.value\n\n\ndef get_const_tuple(in_tuple):\n    \"\"\"Verifies input tuple is IntImm, returns tuple of int.\n\n    Parameters\n    ----------\n    in_tuple : Tuple[tvm.tir.expr]\n        The input.\n\n    Returns\n    -------\n    out_tuple : Tuple[Union[int,tvm.tir.Var,tvm.tir.Any]]\n        The output tuple of int. The dynamic shape variables (Var or Any) will be preserved.\n    \"\"\"\n    ret = []\n    for elem in in_tuple:\n        if isinstance(elem, (tvm.tir.Var, tvm.tir.expr.Any)):\n            ret.append(elem)\n        else:\n            ret.append(get_const_int(elem))\n    return tuple(ret)\n\n\ndef list_to_tuple(x):\n    \"\"\"Convert a list to a tuple recursively.\"\"\"\n    assert isinstance(x, list)\n    return tuple(list_to_tuple(y) if isinstance(y, list) else y for y in x)\n\n\ndef serialize_args(args):\n    \"\"\"\n    Serialize arguments of a function to a hashable and jsonable tuple.\n    Currently this is mainly used for tvm.tensor.Tensor\n    \"\"\"\n    ret = []\n    if args is None:\n        return tuple(ret)\n\n    for t in args:\n        if isinstance(t, Tensor):\n            t = (\"TENSOR\", get_const_tuple(t.shape), t.dtype)\n        elif isinstance(t, list):\n            t = list_to_tuple(t)\n\n        assert isinstance(t, Hashable), str(t) + \" is not hashable\"\n        ret.append(t)\n\n    return tuple(ret)\n\n\ndef deserialize_args(args):\n    \"\"\"The inverse function of :code:`serialize_args`\"\"\"\n    ret = []\n    for t in args:\n        if isinstance(t, (tuple, list)) and t[0] == \"TENSOR\":\n            ret.append(placeholder(shape=t[1], dtype=t[2]))\n        else:\n            ret.append(t)\n    return ret\n\n\ndef kill_child_processes(parent_pid, sig=signal.SIGTERM):\n    \"\"\"kill all child processes recursively\"\"\"\n    if not psutil:\n        raise ImportError(\"psutil not found, try `pip install psutil` to fix this\")\n\n    try:\n        parent = psutil.Process(parent_pid)\n    except psutil.NoSuchProcess:\n        return\n\n    try:\n        children = parent.children(recursive=True)\n        for process in children:\n            process.send_signal(sig)\n    except psutil.NoSuchProcess:\n        return\n\n\n# The maximum length of traceback information\nMAX_TRACEBACK_INFO_LEN = 512\n\n\ndef make_traceback_info():\n    \"\"\"Get the error message from traceback.\"\"\"\n    info = str(traceback.format_exc())\n    if len(info) > MAX_TRACEBACK_INFO_LEN:\n        info = (\n            info[: MAX_TRACEBACK_INFO_LEN // 2] + \"\\n...\\n\" + info[-MAX_TRACEBACK_INFO_LEN // 2 :]\n        )\n    return info\n\n\nclass PropagatingThread(threading.Thread):\n    \"\"\"A thread that propagates the exception to the main thread\"\"\"\n\n    def run(self):\n        self.exc = None\n        try:\n            self.ret = self._target(*self._args, **self._kwargs)\n        except Exception as e:  # pylint: disable=broad-except\n            self.exc = e\n\n    def join(self, timeout=None):\n        super(PropagatingThread, self).join(timeout)\n        if self.exc:\n            raise self.exc\n        return self.ret\n\n\ndef call_func_with_thread(func, args, kwargs):\n    \"\"\"Call a function within a new thread\"\"\"\n    res = []\n\n    def wrapper():\n        res.append(func(*args, **kwargs))\n\n    t = PropagatingThread(target=wrapper)\n    t.start()\n    t.join()\n    return res[0]\n\n\ndef call_func_with_timeout(\n    worker, timeout, func, args=(), kwargs=None\n):  # pylint: disable=unused-argument\n    \"\"\"Call a function with timeout\"\"\"\n    worker.send(func, args, kwargs, timeout)\n    try:\n        res = worker.recv()\n    except Exception:  # pylint: disable=broad-except\n        res = Exception(make_traceback_info())\n\n    return res\n\n\ndef request_remote(device_key, host=None, port=None, priority=1, timeout=60):\n    \"\"\"Request a remote session.\n\n    Parameters\n    ----------\n    device_key : str\n        The device key of registered device in tracker.\n    host : Optional[str]\n        The host address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_HOST\".\n    port : Optional[int]\n        The port of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_PORT\".\n    priority : int = 1\n        The priority of this request, larger is more prior.\n    timeout : int = 60\n        The timeout of this session in second.\n\n    Returns\n    -------\n    remote : RPCSession\n        The connected remote RPCSession.\n    \"\"\"\n    # connect to the tracker\n    host = host or os.environ[\"TVM_TRACKER_HOST\"]\n    port = port or int(os.environ[\"TVM_TRACKER_PORT\"])\n\n    tracker = rpc.connect_tracker(host, port)\n    remote = tracker.request(device_key, priority=priority, session_timeout=timeout)\n    return remote\n\n\ndef check_remote(device_key, host=None, port=None, priority=100, timeout=10):\n    \"\"\"\n    Check the availability of a remote device.\n\n    Parameters\n    ----------\n    device_key: str\n        device key of registered device in tracker.\n    host: Optional[str]\n        The host address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_HOST\".\n    port: Optional[int]\n        The port address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_PORT\".\n    priority: int = 100\n        The priority of this request, larger is more prior.\n    timeout: int = 10\n        The timeout of this check in seconds.\n\n    Returns\n    -------\n    available: bool\n        True if can find available device.\n    \"\"\"\n\n    def _check():\n        request_remote(device_key, host, port, priority)\n\n    t = threading.Thread(\n        target=_check,\n    )\n    t.start()\n    t.join(timeout)\n    return not t.is_alive()\n\n\ndef array_mean(arr):\n    \"\"\"Compute mean of the elments in a TVM Array<PrimExpr>\n\n    Parameters\n    ----------\n    arr: Array\n        A TVM Array<PrimExpr>\n\n    Returns\n    -------\n    mean: float\n        The mean of the elements in the array\n    \"\"\"\n    return sum(x.value for x in arr) / len(arr)\n\n\ndef to_str_round(x, decimal=6):\n    \"\"\"Convert an object to str and round float numbers\n\n    Parameters\n    ----------\n    x: Union[str, list, int, float, np.ndarray]\n        The input object\n    decimal: int\n        The precision of decimal fraction\n\n    Returns\n    -------\n    ret: str\n        The string format of these objects\n    \"\"\"\n    if isinstance(x, str):\n        return x\n    if isinstance(x, (list, tuple, np.ndarray)):\n        return \"[\" + \", \".join([to_str_round(y, decimal=decimal) for y in x]) + \"]\"\n    if isinstance(x, dict):\n        return str({k: to_str_round(v) for k, v in x.items()})\n    if isinstance(x, int):\n        return str(x)\n    if isinstance(x, (np.float32, np.float64, float)):\n        format_str = \"%%.%df\" % decimal\n        return format_str % x\n    raise ValueError(\"Invalid value: \" + str(x) + \"\\ttype: \" + str(type(x)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/auto_scheduler/workload_registry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\"\nWorkload registration and serialization.\n\nWe use a json string to represent a workload (a computation graph).\nThe format of the string is `[func_name, [args...]]`.\nThe dag should be the return value of this `func_name(*args)`.\n\nRationale: The workload is actually a compute dag defined by tvm dsl. But serializing compute dags\nand matching them efficiently is not easy. Therefore, we use the above string to encode a compute\ndag.\nThese strings are efficient for serialization/matching and won't be too long.\nWhen we need the dag, we decode the string and call the function, which will return the dag.\n\"\"\"\n\nimport json\nimport logging\nimport pickle\n\nimport tvm._ffi\nfrom tvm.runtime._ffi_node_api import LoadJSON, SaveJSON\n\nfrom .utils import deserialize_args, get_func_name, serialize_args\n\nlogger = logging.getLogger(\"auto_scheduler\")\n\n# Global workload function and hash key registry\n# It stores two types of workload:\n# 1. User registered tasks. This type of workload is registered\n#    by the decorator \"register_workload\"\n# 2. Extracted tasks from a relay program. This type of workload is\n#    registered by function \"register_workload_tensors\".\n#\n# For 1, the dictionary maps a function name to its function pointer\n# For 2, the dictionary maps a hash key to a list of input/output tensors\nWORKLOAD_FUNC_REGISTRY = {}\n\n\ndef register_workload(func_name, f=None, override=False):\n    \"\"\"Register a function that generates a certain workload.\n\n    The input function should take hashable and jsonable arguments\n    (int, float, tuple of int, tvm.tensor.Tensor, ...) and return a list of tvm.tensor.Tensor.\n\n    Parameters\n    ----------\n    func_name : Union[Function, str]\n        The generation function that returns the compute declaration Tensors or its function name.\n    f : Optional[Function]\n        The generation function to be registered.\n    override : boolean = False\n        Whether to override existing entry.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      @auto_scheduler.register_workload\n      def matmul(N, M, K):\n          A = te.placeholder((N, K), name='A')\n          B = te.placeholder((K, M), name='B')\n          k = te.reduce_axis((0, K), name='k')\n          C = te.compute((N, M), lambda i, j: tvm.sum(A[i][k] * B[k][j], axis=[k]), name='C')\n          return [A, B, C]\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    if callable(func_name):\n        f = func_name\n        func_name = get_func_name(f)\n    if not isinstance(func_name, str):\n        raise ValueError(\"expect string function name\")\n\n    def register(myf):\n        \"\"\"internal register function\"\"\"\n        if func_name in WORKLOAD_FUNC_REGISTRY and not override:\n            raise RuntimeError(\"%s has been registered already\" % func_name)\n        WORKLOAD_FUNC_REGISTRY[func_name] = myf\n        return myf\n\n    if f:\n        return register(f)\n    return register\n\n\ndef register_workload_tensors(workload_key, tensors, override=True):\n    \"\"\"Register a workload by provding input/output tensors. Since this function is used\n    when extracting/deserializing tasks, it expects duplicated registrations by default.\n\n    Parameters\n    ----------\n    workload_key: str\n        The wokrload key of the compute DAG in JSON string.\n    tensors: List[Tensor]\n        The input/output tensors of a compute DAG\n    override : boolean = True\n        Whether to override existing entry.\n\n    Returns\n    -------\n    workload_key: str\n        The wokrload key of the compute DAG in JSON string.\n    \"\"\"\n    register_workload(workload_key, override=override)(tensors)\n    return workload_key\n\n\ndef make_workload_key(func, args):\n    \"\"\"Make a workload key by function and arguments.\n\n    Parameters\n    ----------\n    func : Union[Function, str]\n        The function that returns the compute declaration Tensors.\n        Can be the a function or the function name.\n    args : Args\n        The args of the function.\n\n    Returns\n    -------\n    workload_key : str\n        The workload key of the function.\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    if callable(func):\n        func_name = get_func_name(func)\n    elif isinstance(func, str):\n        func_name = func\n    else:\n        raise ValueError(\n            \"Invalid function: \"\n            + str(func)\n            + \" . `make_workload_key` expects a callable function or its function name\"\n        )\n\n    if not func_name in WORKLOAD_FUNC_REGISTRY:\n        raise ValueError(\n            \"%s is not registered. \" % func,\n            \"Please register it with @auto_scheduler.register_workload\",\n        )\n\n    args = serialize_args(args)\n\n    return json.dumps((func_name,) + args)\n\n\n@tvm._ffi.register_func(\"auto_scheduler.workload_key_to_tensors\")\ndef workload_key_to_tensors(workload_key):\n    \"\"\"Get the input/output tensors from the workload key.\n\n    This method is usually used to create a ComputeDAG by workload key.\n\n    Parameters\n    ----------\n    workload_key : str\n        The input workload key in JSON string. The format is either (func_name, arguments...)\n        for compute functions, or (hash, shapes...) for ComputeDAG.\n\n    Returns\n    -------\n    tensors : List[Tensor]\n        The registered compute declaration Tensors.\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    # We register ComputeDAG with both hash and argumetns, which are fixed in ComputeDAG,\n    # so we use an entire workload key to query the ComputeDAG.\n    if workload_key in WORKLOAD_FUNC_REGISTRY:\n        return WORKLOAD_FUNC_REGISTRY[workload_key]\n\n    # We register compute function with only the function name since\n    # it does not bind to specific arguments, so we use the function name to query\n    # the function and call the function with arguments to get the tensors.\n    workload = json.loads(workload_key)\n    name = workload[0]\n    value = WORKLOAD_FUNC_REGISTRY[name]\n    assert callable(value)\n\n    args = deserialize_args(workload[1:])\n    result = value(*args)\n    if isinstance(result, tuple):\n        result = list(result)\n    return result\n\n\ndef serialize_workload_registry_entry(workload_key):\n    \"\"\"\n    Serialize a workload registry entry.\n\n    This is used when the start method of multiprocessing is spawn.\n    We need to serialize the entry and register it in the new processes.\n\n    Parameters\n    ----------\n    workload_key : str\n        The workload key\n\n    Returns\n    -------\n    data: Tuple\n        The serialized pickable data\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    if workload_key in WORKLOAD_FUNC_REGISTRY:\n        sname = workload_key\n    else:\n        workload = json.loads(workload_key)\n        sname = workload[0]\n\n    svalue = WORKLOAD_FUNC_REGISTRY[sname]\n    if not callable(svalue):\n        # pylint: disable=assignment-from-no-return\n        svalue = SaveJSON(svalue)\n\n    return sname, svalue\n\n\ndef deserialize_workload_registry_entry(data):\n    \"\"\"\n    Deserialize a workload registry entry.\n    This should be used along with :code:`serialize_workload_registry_entry`\n\n    Parameters\n    ----------\n    data: Tuple\n        The return value of :code:`serialize_workload_registry_entry`\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    name, value = data\n    if name not in WORKLOAD_FUNC_REGISTRY:\n        # pylint: disable=assignment-from-no-return\n        if not callable(value):\n            value = LoadJSON(value)\n        WORKLOAD_FUNC_REGISTRY[name] = value\n\n\ndef save_workload_func_registry(filename):\n    \"\"\"Dump workload function registry to a pickle binary file.\n\n    Parameters\n    ----------\n    filename : str\n        The filename to dump workload function registry to.\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    pickle.dump(WORKLOAD_FUNC_REGISTRY, open(filename, \"wb\"))\n\n\ndef load_workload_func_registry(filename):\n    \"\"\"Load workload function registry from a pickle binary file.\n\n    Parameters\n    ----------\n    filename : str\n        The filename to load workload function registry from.\n    \"\"\"\n    global WORKLOAD_FUNC_REGISTRY\n\n    WORKLOAD_FUNC_REGISTRY = pickle.load(open(filename, \"rb\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The auto-tuning module of tvm\n\nThis module includes:\n\n* Tuning space definition API\n\n* Efficient auto-tuners\n\n* Tuning result and database support\n\n* Distributed measurement to scale up tuning\n\"\"\"\n\nfrom . import database\nfrom . import feature\nfrom . import measure\nfrom . import record\nfrom . import task\nfrom . import tuner\nfrom . import utils\nfrom . import env\nfrom . import tophub\n\n# some shortcuts\nfrom .measure import (\n    measure_option,\n    MeasureInput,\n    MeasureResult,\n    MeasureErrorNo,\n    LocalBuilder,\n    LocalRunner,\n    RPCRunner,\n)\nfrom .tuner import callback\nfrom .task import (\n    get_config,\n    create,\n    ConfigSpace,\n    ConfigEntity,\n    register_topi_compute,\n    register_topi_schedule,\n    template,\n    DispatchContext,\n    FallbackContext,\n    ApplyHistoryBest as apply_history_best,\n    ApplyGraphBest as apply_graph_best,\n    ApplyFixedConfig as apply_fixed_config,\n)\nfrom .env import GLOBAL_SCOPE\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=consider-using-enumerate,invalid-name\n\"\"\"\nDatabase of MeasureInput/MeasureResult pair.\nThis can be used for replaying measurement.\n\"\"\"\nimport os\n\nfrom .record import encode, decode, measure_str_key\n\n\nclass Database(object):\n    \"\"\"\n    Base class for a record database object.\n    \"\"\"\n\n    def load(self, inp, get_all=False):\n        \"\"\"\n        Load a result based on an input's string key\n\n        Parameters\n        ----------\n        inp: MeasureInput\n            to be translated into key for RedisDB\n        get_all: bool, optional\n            Whether the latest result (or all matching results) should be returned\n\n        Returns\n        -------\n        rec: MeasureResult if previously saved, otherwise None\n        \"\"\"\n        raise NotImplementedError()\n\n    def save(self, inp, res, extend=False):\n        \"\"\"\n        Save a result based on an input's string key\n\n        Parameters\n        ----------\n        inp: MeasureInput\n            to be translated into key for RedisDB\n        res: MeasureResult\n            to associate with key\n        extend:\n            Whether to extend existing MeasureResults if they exist\n        \"\"\"\n        raise NotImplementedError()\n\n\ndef filter_inputs(db, measure_inputs, retry=False):\n    \"\"\"\n    Filter a measure_inputs batch based on saved db results\n\n    Parameters\n    ----------\n    db: Database\n        database object\n    measure_inputs: Array of MeasureInput\n        measure_inputs as expected in measure_batch\n    retry: bool\n        whether to retry if the saved result is a failure\n\n    Returns\n    -------\n    partial_results: Array of MeasureResult\n        a full list of result, where None denotes no corresponding saved result\n    unsaved: Array of MeasureInput\n        a list that only contains unsaved inputs\n    \"\"\"\n    partial_results = list()\n    unsaved = list()\n    for inp in measure_inputs:\n        res = db.load(inp)\n        if res is None or (retry and res.error_no != 0):\n            unsaved.append(inp)\n            partial_results.append(None)\n        else:\n            partial_results.append(res)\n    return partial_results, unsaved\n\n\nclass RedisDatabase(Database):\n    \"\"\"\n    Redis version of record database\n    \"\"\"\n\n    REDIS_PROD = 15\n    REDIS_LOCA = 14\n    REDIS_TEST = 13  # for unit test\n    REDIS_NIGHT_TEMP = 12  # for nightly report (will be flushed after every workload)\n\n    MAGIC_SPLIT = \"$\"\n\n    def __init__(self, db_index=REDIS_PROD):\n        # pylint: disable=import-outside-toplevel\n        import redis\n\n        if db_index == RedisDatabase.REDIS_TEST:\n            host = \"127.0.0.1\"\n        else:\n            host = os.environ.get(\"TVM_FLEET_HOST\")\n        self.db = redis.StrictRedis(host=host, port=6379, db=db_index)\n        self.db_index = db_index\n\n    def set(self, key, value):\n        self.db.set(key, value)\n\n    def get(self, key):\n        current = self.db.get(key)\n        return current.decode() if isinstance(current, bytes) else current\n\n    def load(self, inp, get_all=False):\n        current = self.get(measure_str_key(inp))\n        if current is not None:\n            records = [decode(x) for x in current.split(RedisDatabase.MAGIC_SPLIT)]\n            results = [rec[1] for rec in records if rec is not None]\n            if get_all:\n                return results\n            return max(results, key=lambda result: result.timestamp)\n        return current\n\n    def save(self, inp, res, extend=False):\n        current = self.get(measure_str_key(inp))\n        if not extend or current is None:\n            self.set(measure_str_key(inp), RedisDatabase.MAGIC_SPLIT.join([encode(inp, res)]))\n        else:\n            current = current.split(RedisDatabase.MAGIC_SPLIT)\n            self.set(\n                measure_str_key(inp), RedisDatabase.MAGIC_SPLIT.join(current + [encode(inp, res)])\n            )\n\n    def filter(self, func):\n        \"\"\"\n        Dump all of the records that match the given rule\n\n        Parameters\n        ----------\n        func: callable\n            The signature of the function is (MeasureInput, [MeasureResult]) -> bool\n\n        Returns\n        -------\n        list of records in tuple (MeasureInput, MeasureResult) matching the rule\n\n        Examples\n        --------\n        get records for a target\n        >>> db.filter(lambda inp, results: \"cuda\" in inp.target.keys)\n        get records with errors\n        >>> db.filter(lambda inp, results: any(r.error_no != 0 for r in results))\n        \"\"\"\n        matched_records = list()\n        # may consider filtering in iterator in the future\n        for key in self.db.keys():\n            current = self.get(key)\n            try:\n                records = [decode(x) for x in current.split(RedisDatabase.MAGIC_SPLIT)]\n                records = [rec for rec in records if rec is not None]\n            except TypeError:  # got a badly formatted/old format record\n                continue\n\n            if not records:\n                continue\n            inps, results = zip(*records)\n            inp = inps[0]\n            if not func(inp, results):\n                continue\n            result = max(results, key=lambda res: res.timestamp)\n            matched_records.append((inp, result))\n        return matched_records\n\n    def flush(self):\n        self.db.flushdb()\n\n\nclass DummyDatabase(RedisDatabase):\n    \"\"\"\n    A database based on python dictionary for testing.\n    \"\"\"\n\n    def __init__(self):\n        # pylint: disable=super-init-not-called\n        self.db = {}\n\n    def set(self, key, value):\n        self.db[key] = value\n\n    def flush(self):\n        self.db = {}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/env.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Global configuration/variable scope for autotvm\"\"\"\n\n\nclass AutotvmGlobalScope(object):\n    \"\"\"The global autotvm scope.\"\"\"\n\n    current = None\n\n    def __init__(self):\n        self._old = AutotvmGlobalScope.current\n        AutotvmGlobalScope.current = self\n\n        self.in_tuning = False\n        self.silent = False\n\n    def deep_copy(self, global_scope):\n        \"\"\"Deep copy from another instance of AutotvmGlobalScope.\"\"\"\n        self._old = AutotvmGlobalScope.current\n\n        self.in_tuning = global_scope.in_tuning\n        self.silent = global_scope.silent\n\n\nGLOBAL_SCOPE = AutotvmGlobalScope()\n\n\ndef reset_global_scope(global_scope):\n    \"\"\"Reset global autotvm state. This is needed to initialize PopenPool workers.\"\"\"\n    global GLOBAL_SCOPE\n    GLOBAL_SCOPE.deep_copy(global_scope)\n    AutotvmGlobalScope.current = global_scope\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,\n\"\"\"Extract feature of iter vars\n\nThere are two types of feature\n1) Itervar feature\n   This feature is extracted based on loop variables.\n   Different loop structures will result in different shapes of feature\n2) Curve sample feature (relation feature)\n   This feature is extracted by sampling relation curve.\n   This feature is invariant of loop structure.\n\"\"\"\n\nimport struct\nimport numpy as np\nimport tvm._ffi\n\nfrom tvm.target import Target\nfrom tvm.driver import build_module\n\n\ndef ana_lower(sch, args, binds=None, simple_mode=True):\n    \"\"\"Do lower while keeping all axes in IR\n    i.e. Do not eliminate loop with extent of 1, do not vectorize, unroll or inject virtual threads\n    \"\"\"\n    sch = sch.normalize()\n    # Phase 0\n    context = tvm.transform.PassContext(config={\"tir.debug_keep_trivial_loop\": True})\n    with context:\n        mod = build_module.schedule_to_module(sch, args, binds=binds)\n\n    mod = tvm.tir.transform.StorageFlatten(64)(mod._move())\n    mod = tvm.tir.transform.Simplify()(mod._move())\n    assert simple_mode\n    return mod[\"main\"].body\n\n\ntry:\n    _get_buffer_curve_sample_flatten = tvm._ffi.get_global_func(\n        \"autotvm.feature.GetCurveSampleFeatureFlatten\"\n    )\n    _get_itervar_feature = tvm._ffi.get_global_func(\"autotvm.feature.GetItervarFeature\")\n    _get_itervar_feature_flatten = tvm._ffi.get_global_func(\n        \"autotvm.feature.GetItervarFeatureFlatten\"\n    )\nexcept ValueError as e:\n\n    def raise_error(*args, **kwargs):  # pylint: disable=unused-argument\n        raise RuntimeError(\"Cannot load autotvm c++ API\")\n\n    _get_buffer_curve_sample_flatten = (\n        _get_itervar_feature\n    ) = _get_itervar_feature_flatten = raise_error\n\n\ndef get_itervar_feature(sch, args, take_log=False):\n    \"\"\"get features of iter vars\n\n    Parameters\n    ----------\n    sch: tvm.te.schedule.Schedule\n    args: Array of te.tensor.Tensor\n        the buffer args for lower\n    take_log: bool\n        whether take log of numerical statics\n\n    Returns\n    -------\n    features of every axis in the IR, see doc/features.md for detail\n    \"\"\"\n    stmt = ana_lower(sch, args, simple_mode=True)\n    feas = _get_itervar_feature(stmt, take_log)\n\n    # convert tvm node to python type\n    ret = []\n    for row in feas:\n        tmp = []\n        tmp.append([row[0][0].value, row[0][1]])\n        for item in row[1:]:\n            tmp.append([item[0].value] + [x.value for x in item[1:]])\n        ret.append(tmp)\n    return ret\n\n\ndef flatten_itervar_feature(fea):\n    \"\"\"flatten features into one-dimensional feature vectors\n\n    Parameters\n    ----------\n    fea: list\n        return value of get_itervar_feature\n\n    Returns\n    -------\n    flatten_feature: np.ndarray\n        one-dimensional vector\n    \"\"\"\n    flatten = []\n    for axis in fea:\n        for pair in axis[1:]:\n            flatten.append(pair[1:])\n    return np.concatenate(flatten)\n\n\ndef get_itervar_feature_flatten(sch, args, take_log=True):\n    \"\"\"get flatten features of iter vars\n    this is equivalent to get_itervar_feature + flatten_itervar_feature, but much faster.\n\n    Parameters\n    ----------\n    sch: tvm.te.schedule.Schedule\n    args: Array of te.tensor.Tensor\n        the buffer args for lower\n    take_log: bool\n        whether take log of numerical statics\n\n    Returns\n    -------\n    flatten_feature: np.ndarray\n        one-dimensional vector\n    \"\"\"\n    stmt = ana_lower(sch, args, simple_mode=True)\n    feas = _get_itervar_feature_flatten(stmt, take_log)\n    feas = struct.unpack(\"%df\" % (len(feas) // 4), feas)\n    return feas\n\n\ndef get_flatten_name(fea):\n    \"\"\"Get names of feature after flatten.\n\n    Parameters\n    ----------\n    fea: list or str\n        return value of get_itervar_feature or a line of logfile\n\n    Returns\n    -------\n    feature_names: Array of str\n    \"\"\"\n\n    feature_name = {\n        \"_attr_\": [\"length\", \"nest_level\", \"topdown\", \"bottomup\"]\n        + [\"ann_%d\" % i for i in range(20)],\n        \"_arith_\": [\"add\", \"mul\", \"div\"],\n        \"buf_touch\": [\"stride\", \"mod\", \"count\", \"reuse\", \"T_count\", \"T_reuse\"],\n    }\n\n    if isinstance(fea, str):\n        # pylint: disable=import-outside-toplevel\n        from .record import decode\n\n        # flatten line to feature\n        line = fea\n        ret = decode(line)\n        if ret is None:\n            raise ValueError(\"Unsupported AutoTVM log format\")\n        inp, _ = ret\n        target = Target(inp.target)\n        with target:\n            s, args = inp.template.instantiate(inp.config)\n        fea = get_itervar_feature(s, args)\n\n    names = []\n    ct = 0\n    for row in fea:\n        var_name = str(row[0][1])\n        for pair in row[1:]:\n            key = pair[0]\n            if key in feature_name:\n                name_list = feature_name[key]\n            else:\n                name_list = feature_name[\"buf_touch\"]\n\n            for i in range(len((pair[1:]))):\n                names.append(\".\".join([\"f%d\" % ct, var_name, key, name_list[i]]))\n                ct += 1\n    return names\n\n\ndef get_buffer_curve_sample_flatten(sch, args, sample_n=30):\n    \"\"\"\n    Get flatten curve sample feature (relation feature)\n\n    Parameters\n    ----------\n    sch: tvm.te.schedule.Schedule\n    args: Array of te.tensor.Tensor\n        the buffer args for lower\n    sample_n: int\n        number of sample points along one dimension\n\n    Returns\n    -------\n    flatten_feature: np.ndarray\n        one-dimensional vector\n    \"\"\"\n    stmt = ana_lower(sch, args, simple_mode=True)\n    feas = _get_buffer_curve_sample_flatten(stmt, sample_n, False)\n    feas = struct.unpack(\"%df\" % (len(feas) // 4), feas)\n    return feas\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Autotvm graph tuner API.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom . import _base\nfrom . import base_graph_tuner\n\nfrom .base_graph_tuner import BaseGraphTuner\nfrom .dynamic_programming_tuner import DPTuner\nfrom .pbqp_tuner import PBQPTuner\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/_base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Helper functions and global data\"\"\"\n\n\n# We set a large time to represent an invalid layout-transformation.\n# This number is set to be 10e9 seconds to align with autotvm.\nINVALID_LAYOUT_TIME = 10e9\n\nMAX_OUTPUT_NODES = 16\n\nOPT_OUT_OP = [\"layout_transform\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/base_graph_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-arguments,too-many-locals,too-many-statements,too-many-instance-attributes,too-many-branches,too-many-nested-blocks,invalid-name,unused-argument,unused-variable,no-member,no-value-for-parameter\n\"\"\"Base class for graph tuner.\"\"\"\nimport logging\nfrom abc import abstractmethod\n\nimport numpy as np\nfrom tvm import topi\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm, relay\nfrom tvm.autotvm.task import get_config\nfrom tvm.autotvm.record import encode, load_from_file\nfrom tvm.autotvm.measure import MeasureResult, MeasureInput\nfrom tvm.target import Target\n\nfrom ...target import Target\nfrom .utils import (\n    is_boundary_node,\n    get_in_nodes,\n    get_out_nodes,\n    has_multiple_inputs,\n    bind_inputs,\n    expr2graph,\n)\nfrom ._base import INVALID_LAYOUT_TIME\n\nfrom ._base import OPT_OUT_OP\n\n\ndef get_infer_layout(task_name):\n    if task_name.startswith(\"conv2d\"):\n        return topi.nn.conv2d_infer_layout\n    if task_name.startswith(\"depthwise_conv2d\"):\n        return topi.nn.depthwise_conv2d_infer_layout\n    raise ValueError(\"Cannot find infer layout for task %s\" % task_name)\n\n\n@autotvm.template(\"layout_transform\")\ndef layout_transform(*args):\n    \"\"\"Autotvm layout transform template.\"\"\"\n    cfg = get_config()\n    cfg.add_flop(-1)\n    data = args[0]\n    out = topi.layout_transform(*args)\n    sch = topi.generic.schedule_injective([out])\n    return sch, [data, out]\n\n\nclass BaseGraphTuner(object):\n    \"\"\"Class to search schedules considering both kernel execution time and\n    layout transformation time.\n\n    Before creating a Graph Executor instance, schedule candidates for all kernels in\n    graph should be provided through tensor-level tuning.\n    \"\"\"\n\n    def __init__(\n        self,\n        graph,\n        input_shapes,\n        records,\n        target_ops,\n        target,\n        max_sch_num=20,\n        dtype=\"float32\",\n        verbose=True,\n        log_file=\"graph_tuner.log\",\n        log_level=logging.DEBUG,\n        name=\"graph_tuner\",\n    ):\n        \"\"\"Create a GlobalTuner instance. Local schedule searching for all nodes with\n        target_op in the input graph and layout transformation benchmark need to be\n        executed before initialization.\n\n        graph : tvm.relay.function.Function\n            Input graph\n\n        input_shapes : dict of str to tuple.\n            Input shapes of graph\n\n        records : str or iterator of (MeasureInput, MeasureResult)\n            Collection of kernel level tuning records.\n            If it is str, then it should be the filename of a records log file.\n                       Each row of this file is an encoded record pair.\n            Otherwise, it is an iterator.\n\n        target_ops : List of tvm.ir.Op\n            Target tuning operators.\n\n        target : str or tvm.target\n            Compilation target.\n\n        max_sch_num : int, optional\n            Maximum number of schedule candidates for each workload.\n\n        dtype : str, optional\n            Data type.\n\n        log_file : str, optional\n            graph tuner log file name\n\n        name : str, optional\n            Name of global tuner.\n        \"\"\"\n        self._node_list = []\n        self._layout_transform_perf_records = {}\n        self._layout_transform_interlayer_cost = {}\n        self._input_shapes = input_shapes\n        self._target_ops = target_ops\n\n        self._name = name\n        self._max_sch_num = max_sch_num\n        self._optimal_sch_dict = {}\n        self._records = records\n        self._dtype = dtype\n        if isinstance(target, str):\n            target = Target(target)\n        self._target = target\n        self._optimal_record_dict = {}\n\n        # Set up logger\n        self._verbose = verbose\n        self._logger = logging.getLogger(name + \"_logger\")\n        need_file_handler = need_console_handler = True\n        for handler in self._logger.handlers:\n            if handler.__class__.__name__ == \"FileHandler\":\n                need_file_handler = False\n            if handler.__class__.__name__ == \"StreamHandler\":\n                need_console_handler = False\n        self._log_level = log_level\n        self._log_file = log_file\n        self._formatter = logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\")\n        self._logger.setLevel(log_level)\n        if need_file_handler:\n            file_handler = logging.FileHandler(log_file)\n            file_handler.setFormatter(self._formatter)\n            self._logger.addHandler(file_handler)\n        if self._verbose and need_console_handler:\n            console_handler = logging.StreamHandler()\n            console_handler.setFormatter(self._formatter)\n            self._logger.addHandler(console_handler)\n            self._logger.setLevel(log_level)\n            self._logger.propagate = False\n\n        # Generate workload and schedule dictionaries.\n        if isinstance(graph, tvm.IRModule):\n            graph = graph[\"main\"]\n\n        if isinstance(graph, relay.function.Function):\n            node_dict = {}\n            graph = bind_inputs(graph, input_shapes, dtype)\n            expr2graph(graph, self._target_ops, node_dict, self._node_list, target)\n        else:\n            raise RuntimeError(\"Unsupported graph type: %s\" % str(type(graph)))\n\n        self._graph = graph\n        self._in_nodes_dict = get_in_nodes(self._node_list, self._target_ops, input_shapes.keys())\n        if len(self._in_nodes_dict) == 0:\n            raise RuntimeError(\n                \"Could not find any input nodes with whose \"\n                \"operator is one of %s\" % self._target_ops\n            )\n        self._out_nodes_dict = get_out_nodes(self._in_nodes_dict)\n        self._fetch_cfg()\n        self._opt_out_op = OPT_OUT_OP\n\n        # Setup infer_layout for elemwise-like nodes\n        # Note: graph tuner currently only supports tuning of single input and single output\n        # op as target op, such as conv2d, dense and conv2d_transpose. In this case, we can\n        # reuse infer_layout function from target ops for elemwise-like nodes. The behavior\n        # is to modify the first tensor shape of input workload to the output shape of\n        # elemwise-like node, and use infer_layout function from input op to generate layouts.\n        input_names = self._input_shapes.keys()\n        for idx in sorted(self._in_nodes_dict.keys()):\n            if has_multiple_inputs(self._node_list, idx, input_names, self._opt_out_op):\n                node_entry = self._node_list[idx]\n                node_entry[\"topi_op\"] = []\n                node_entry[\"workloads\"] = []\n                for input_idx in self._in_nodes_dict[idx]:\n                    input_node = self._node_list[input_idx]\n                    if not is_boundary_node(input_node, input_names):\n                        input_topi_op = input_node[\"topi_op\"][0]\n                        node_entry[\"topi_op\"].append(input_topi_op)\n                        # Only replace the first input tensor\n                        input_workload = input_node[\"workloads\"][0]\n                        first_tensor = input_workload[1]\n                        dtype = first_tensor[-1]\n                        new_shape = tuple([val.value for val in node_entry[\"types\"][0].shape])\n                        actual_workload = (\n                            (input_workload[0],)\n                            + ((\"TENSOR\", new_shape, dtype),)\n                            + input_workload[2:]\n                        )\n                        node_entry[\"workloads\"].append(actual_workload)\n                        if \"record_candidates\" not in node_entry:\n                            node_entry[\"record_candidates\"] = input_node[\"record_candidates\"]\n                    else:\n                        node_entry[\"topi_op\"].append(None)\n                        node_entry[\"workloads\"].append(None)\n\n    def _fetch_cfg(self):\n        \"\"\"Read and pre-process input schedules.\"\"\"\n        if isinstance(self._records, str):\n            records = load_from_file(self._records)\n        else:\n            records = self._records\n        cfg_dict = {}\n        for record in records:\n            in_measure, _ = record\n            workload = in_measure.task.workload\n            if workload not in cfg_dict:\n                cfg_dict[workload] = []\n            cfg_dict[workload].append(record)\n\n        cache_dict = {}\n        for key in self._in_nodes_dict:\n            node_entry = self._node_list[key]\n            if node_entry[\"op\"] not in self._target_ops:\n                continue\n            workload = node_entry[\"workloads\"][0]\n            if workload in cache_dict:\n                node_entry[\"record_candidates\"] = cache_dict[workload]\n                continue\n            record_candidates = []\n            infer_layout_func = get_infer_layout(node_entry[\"topi_op\"][0])\n            layout_tracking_dict = {}\n            for record in cfg_dict[workload]:\n                in_measure, out_measure = record\n                workload = in_measure.task.workload\n                cfg = in_measure.config\n                # For multiple cfgs which produces the same in/out layouts,\n                # only the most efficient one is preserved.\n                with self._target:\n                    layouts = infer_layout_func(workload, cfg)\n                    if layouts in layout_tracking_dict:\n                        cost = out_measure.costs[0]\n                        current_best_cost = layout_tracking_dict[layouts][1].costs[0]\n                        if cost < current_best_cost:\n                            layout_tracking_dict[layouts] = record\n                    else:\n                        layout_tracking_dict[layouts] = record\n            sorted_records = sorted(\n                layout_tracking_dict.values(), key=lambda item: item[1].costs[0]\n            )\n            for i in range(min(self._max_sch_num, len(sorted_records))):\n                record_candidates.append(sorted_records[i])\n            node_entry[\"record_candidates\"] = record_candidates\n            cache_dict[workload] = record_candidates\n\n    def _iterate_layout_transform(self, callback):\n        \"\"\"Iterate all possible layout transformations and execute callback for each\n        iteration. callback function accepts 6 arguments: from_node_idx, to_node_idx,\n        from_sch_idx, to_sch_idx, args which represent the argument list of layout\n        transformation and is_valid showing whether this is a valid layout transformation.\n        \"\"\"\n        input_names = self._input_shapes.keys()\n        pair_tracker = set()\n        for key, val in self._in_nodes_dict.items():\n            node_entry = self._node_list[key]\n            target_input_idx = -1\n            target_input_pos = -1\n            if has_multiple_inputs(self._node_list, key, input_names, self._opt_out_op):\n                for i, item in enumerate(val):\n                    node = self._node_list[item]\n                    if not is_boundary_node(node, input_names):\n                        target_input_idx = item\n                        target_input_pos = i\n                        break\n\n            for i, item in enumerate(val):\n                i_idx = item\n                in_node_entry = self._node_list[i_idx]\n                if is_boundary_node(in_node_entry, input_names):\n                    continue\n\n                if node_entry[\"op\"] in self._target_ops:\n                    o_idx = key\n                    o_infer_layout_func = get_infer_layout(node_entry[\"topi_op\"][0])\n                    o_wkl = node_entry[\"workloads\"][0]\n                    i_topi_op = in_node_entry[\"topi_op\"][0]\n                    i_wkl = in_node_entry[\"workloads\"][0]\n                    pivot = 0\n                    while not i_wkl:\n                        pivot += 1\n                        i_topi_op = in_node_entry[\"topi_op\"][pivot]\n                        i_wkl = in_node_entry[\"workloads\"][pivot]\n                    i_infer_layout_func = get_infer_layout(i_topi_op)\n                else:\n                    o_idx = target_input_idx\n                    if i <= target_input_pos:\n                        continue\n                    o_infer_layout_func = get_infer_layout(node_entry[\"topi_op\"][0])\n                    o_wkl = node_entry[\"workloads\"][target_input_pos]\n                    i_infer_layout_func = get_infer_layout(node_entry[\"topi_op\"][i])\n                    i_wkl = node_entry[\"workloads\"][i]\n\n                if (i_idx, o_idx) in pair_tracker:\n                    continue\n                pair_tracker.add((i_idx, o_idx))\n\n                for m, i_record in enumerate(in_node_entry[\"record_candidates\"]):\n                    for n, o_record in enumerate(node_entry[\"record_candidates\"]):\n                        i_cfg, o_cfg = i_record[0].config, o_record[0].config\n                        with self._target:\n                            i_input_info, i_output_info = i_infer_layout_func(i_wkl, i_cfg)\n                            o_input_info, o_output_info = o_infer_layout_func(o_wkl, o_cfg)\n                        if (\n                            len(i_input_info) > 1\n                            or len(i_output_info) > 1\n                            or len(o_input_info) > 1\n                            or len(o_output_info) > 1\n                        ):\n                            raise RuntimeError(\n                                \"Graph tuner only supports target operator \"\n                                \"with single input and single output. \"\n                                \"Please check target_ops argument.\"\n                            )\n\n                        in_shape, in_layout = i_output_info[0]\n                        if node_entry[\"op\"] in self._target_ops:\n                            _, out_layout = o_input_info[0]\n                        else:\n                            _, out_layout = o_output_info[0]\n                        data_placeholder = te.placeholder(in_shape, name=\"data\", dtype=self._dtype)\n                        args = [data_placeholder, in_layout, out_layout]\n                        callback(i_idx, o_idx, m, n, args)\n\n    def _create_matrix_callback(self, from_node_idx, to_node_idx, from_sch_idx, to_sch_idx, args):\n        \"\"\"Create dictionary containing matrix format of layout transformation\n        between nodes.\"\"\"\n        in_layout, out_layout = args[1], args[2]\n        ltf_workload = autotvm.task.args_to_workload(args, \"layout_transform\")\n        idx_pair_key = (from_node_idx, to_node_idx)\n\n        if in_layout == out_layout:\n            layout_transform_time = 0\n        else:\n            layout_transform_time = self._layout_transform_perf_records[ltf_workload][1].costs[0]\n\n        if idx_pair_key not in self._layout_transform_interlayer_cost:\n            self._layout_transform_interlayer_cost[idx_pair_key] = []\n        if len(self._layout_transform_interlayer_cost[idx_pair_key]) <= from_sch_idx:\n            self._layout_transform_interlayer_cost[idx_pair_key].append([])\n        self._layout_transform_interlayer_cost[idx_pair_key][from_sch_idx].append(\n            layout_transform_time\n        )\n\n    def benchmark_layout_transform(\n        self,\n        min_exec_num=100,\n        timeout=10,\n        use_rpc=False,\n        device_key=None,\n        host=\"127.0.0.1\",\n        port=9190,\n        n_parallel=1,\n        build_func=\"default\",\n        layout_records=None,\n        target_host=None,\n        infer_layout=False,\n        runner=None,\n    ):\n        \"\"\"Benchmark all possible layout transformation in the graph,\n        given a set of schedule candidates for each workload of target operator.\n\n        Parameters\n        ----------\n        min_exec_num : int, optional\n            Minimum number of execution. Final execution time is the average of\n            all execution time.\n\n        timeout : int, optional\n            Time out for each execution.\n\n        use_rpc : boolean, optional\n            Whether to use rpc mode for benchmarking.\n\n        device_key : str, optional\n            Remote device key which can be queried by\n            python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n\n        host : str, optional\n            IP address used to create RPC tracker on host machine.\n\n        port : int, optional\n            Port number used to create RPC tracker on host machine.\n\n        n_parallel: int, optional\n            The number of measurement task that can run in parallel.\n            Set this according to the number of cpu cores (for compilation) and\n            the number of devices you have (for measuring generate code).\n\n        build_func: str or callable, optional\n            'default': call default builder. This works for normal target (llvm, cuda)\n\n            'ndk': use Android NDK to create shared library. Use this for android target.\n\n            callable: customized build function for other backends (e.g. VTA).\n                      See autotvm/measure/measure_methods.py::default_build_func for example.\n\n        layout_records : str or iterator of (MeasureInput, MeasureResult). optional\n            Collection of layout_transform benchmarking records.\n            If is str, then it should be the filename of a records log file.\n                   Each row of this file is an encoded record pair.\n            Otherwise, it is an iterator.\n\n            If this argument is set, graph tuner will first check whether layout_transform\n            workload already exists in records and skip benchmarking if possible.\n\n        target_host : str, optional\n            str or :any:`tvm.target.Target` optional\n            Host compilation target, if target is device.\n            When TVM compiles device specific program such as CUDA,\n            we also need host(CPU) side code to interact with the driver\n            setup the dimensions and parameters correctly.\n            target_host is used to specify the host side codegen target.\n            By default, llvm is used if it is enabled,\n            otherwise a stackvm intepreter is used.\n\n        infer_layout : bool, optional\n            Whether to infer layout transformation time if it doesn't exist in records, instead\n            of benchmarking on target device.\n\n            This might bring performance loss comparing to benchmarking layout transformation.\n        runner : Runner, optional\n            Accept a user-supplied runner\n        \"\"\"\n        self._logger.info(\"Start to benchmark layout transformation...\")\n        self._target, target_host = Target.canon_target_and_host(self._target, target_host)\n\n        if layout_records is None and infer_layout:\n            raise RuntimeError(\"Requires some records to infer layout transformation time.\")\n\n        if isinstance(layout_records, str):\n            layout_records = load_from_file(layout_records)\n            if not layout_records and infer_layout:\n                raise RuntimeError(\"Records must be non-empty to infer layout transformation time.\")\n\n        if isinstance(layout_records, str):\n            layout_records = load_from_file(layout_records)\n        num_flops, total_time = 0, 0\n        if layout_records is not None:\n            for record in layout_records:\n                ltf_wkl = record[0].task.workload\n                self._layout_transform_perf_records[ltf_wkl] = record\n                input_shape = ltf_wkl[1][1]\n                flops = np.prod(input_shape)\n                num_flops += flops\n                total_time += record[1].costs[0]\n        avg_time = total_time / num_flops if num_flops > 0 else 0\n\n        args_list = []\n\n        def _fetch_args_callback(from_node_idx, to_node_idx, from_sch_idx, to_sch_idx, args):\n            \"\"\"Callback function to fetch layout transform args\"\"\"\n            _, in_layout, out_layout = args\n            if in_layout != out_layout:\n                args_list.append(args)\n\n        self._iterate_layout_transform(_fetch_args_callback)\n\n        def _log_to_list(record_list):\n            \"\"\"Callback to log result to a list.\"\"\"\n\n            def _callback(_, inputs, results):\n                \"\"\"Callback implementation\"\"\"\n                record_list.append((inputs[0], results[0]))\n\n            return _callback\n\n        builder = autotvm.LocalBuilder(n_parallel=n_parallel, build_func=build_func)\n        if use_rpc:\n            if device_key is None:\n                raise RuntimeError(\"device_key need to be set to use rpc tracker mode.\")\n            runner = autotvm.measure.RPCRunner(\n                device_key,\n                host,\n                port,\n                n_parallel=n_parallel,\n                number=min_exec_num,\n                repeat=1,\n                timeout=timeout,\n            )\n        elif not runner:\n            runner = autotvm.LocalRunner(number=min_exec_num, repeat=1, timeout=timeout)\n        measure_option = autotvm.measure_option(builder=builder, runner=runner)\n        for args in args_list:\n            data, in_layout, out_layout = args\n            ltf_workload = autotvm.task.args_to_workload(args, \"layout_transform\")\n            if ltf_workload in self._layout_transform_perf_records:\n                continue\n\n            if infer_layout:\n                input_shape = ltf_workload[1][1]\n                flops = 1\n                for i in input_shape:\n                    flops *= i\n\n                # Rule out invalid layout transformations\n                out = topi.layout_transform(data, in_layout, out_layout)\n                out_flops = 1\n                for i in topi.utils.get_const_tuple(out.shape):\n                    out_flops *= i\n\n                if flops != out_flops:\n                    inferred_time = INVALID_LAYOUT_TIME\n                else:\n                    inferred_time = flops * avg_time\n\n                record_input = MeasureInput(target=self._target, task=None, config=None)\n                record_output = MeasureResult(\n                    costs=(inferred_time,), error_no=0, all_cost=-1, timestamp=-1\n                )\n                self._layout_transform_perf_records[ltf_workload] = (record_input, record_output)\n                continue\n\n            records = []\n            task = autotvm.task.create(\"layout_transform\", args=args, target=self._target)\n            tuner = autotvm.tuner.GridSearchTuner(task)\n            tuner.tune(n_trial=1, measure_option=measure_option, callbacks=[_log_to_list(records)])\n            if not isinstance(records[0][1].costs[0], float):\n                records[0] = (records[0][0], records[0][1]._replace(costs=(INVALID_LAYOUT_TIME,)))\n            self._layout_transform_perf_records[ltf_workload] = records[0]\n\n        self._iterate_layout_transform(self._create_matrix_callback)\n        self._logger.info(\"Benchmarking layout transformation successful.\")\n\n    @property\n    def layout_transform_perf_records(self):\n        \"\"\"Get layout transformation dictionary for input graph.\n\n        Returns\n        -------\n        layout_transform_perf_records : dict of tuple to (MeasureInput, MeasureResult)\n            Layout transformation dictionary for input graph.\n        \"\"\"\n        return self._layout_transform_perf_records\n\n    def get_optimal_records(self):\n        \"\"\"Convert optimal record dictionary to a list of records\n        with ascending order of node index in graph.\n\n        Returns\n        -------\n        sch_list : list of tuple\n            List of records with ascending order of node index in graph.\n        \"\"\"\n        ordered_index_list = sorted(self._optimal_record_dict.keys())\n        ret = []\n        for index in ordered_index_list:\n            node_entry = self._node_list[index]\n            if node_entry[\"op\"] not in self._target_ops:\n                continue\n            ret.append(node_entry[\"record_candidates\"][self._optimal_record_dict[index]])\n        return ret\n\n    def write_opt_sch2record_file(self, record_file=\"graph_opt_schedule.log\"):\n        \"\"\"Write graph level optimal schedules into file.\n\n        Parameters\n        ----------\n        record_file : str, optional\n            Output schedule file.\n        \"\"\"\n        with open(record_file, \"a\") as out_file:\n            records = self.get_optimal_records()\n            for record in records:\n                out_file.write(encode(record[0], record[1]) + \"\\n\")\n        msg = \"Writing optimal schedules to %s successfully.\" % record_file\n        self._logger.info(msg)\n\n    @abstractmethod\n    def run(self, **kwargs):\n        \"\"\"Run graph tuning.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/dynamic_programming_stage.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-instance-attributes,too-many-branches,too-many-statements,too-many-arguments,too-many-locals,invalid-name\n\"\"\"Stage class for dynamic programming tuner\"\"\"\nimport numpy as np\n\nfrom .utils import is_boundary_node\n\n\nclass DPStage(object):\n    \"\"\"Class to represent node in Markov decision process. A stage has states\n    to represent different schedules of the current node. Since in this problem\n    the action is the schedule selected for current node, action can be fully\n    represented by states. No extra attribute needs for action.\n\n    In most cases, instance of this class should be created through DPTuner.\n    \"\"\"\n\n    def __init__(\n        self,\n        idx,\n        input_shapes,\n        node_list,\n        counted_nodes_set,\n        layout_transform_interlayer_cost,\n        stage_dict,\n        in_nodes_dict,\n        out_nodes_dict,\n        dep_dict,\n        target_ops,\n        dtype=\"float32\",\n    ):\n        \"\"\"Initialize a stage and create all states.\n\n        Parameters\n        ----------\n        idx : int\n            Index for current node.\n\n        input_shapes : dict of string to tuple of int\n            Input shapes for current graph.\n\n        node_list : list of dict\n            List of all nodes for current graph.\n\n        counted_nodes_set : set of int\n            Global set recording whether the execution time of a node has been counted.\n\n        layout_transform_interlayer_cost : dict of tuple to list\n            Dictionary maps node index pair to layout transformation time between them.\n\n        stage_dict : dict of int to Stage\n            Global dictionary for all stages mapping node index to stage.\n\n        in_nodes_dict : dict of int to list of int\n            Dictionary maps node index to corresponding input node index.\n\n        out_nodes_dict : dict of int to list of int\n            Dictionary maps node index to corresponding output node index.\n\n        dep_dict : dict of int to set of int\n            Dictionary maps node index to dependent node index.\n\n        target_ops : list of str\n            Target operators\n\n        dtype : str, optional\n            Data type.\n        \"\"\"\n        self._global_input_shapes = input_shapes\n        self._global_input_names = input_shapes.keys()\n        self._global_node_list = node_list\n        self._global_counted_nodes_set = counted_nodes_set\n        self._global_layout_transform_interlayer_cost = layout_transform_interlayer_cost\n        self._global_stage_dict = stage_dict\n        self._global_in_nodes_dict = in_nodes_dict\n        self._global_out_nodes_dict = out_nodes_dict\n        self._global_dep_dict = dep_dict\n\n        self._idx = idx\n        self._node_entry = self._global_node_list[idx]\n        self._target_ops = target_ops\n        self._wkl = self._node_entry[\"workloads\"][0]\n        self._record_list = self._node_entry[\"record_candidates\"]\n        self._dep = []\n        self._dtype = dtype\n        self._states = None\n        self._full_states = None\n        self._full_states_idx = None\n        self._create_states()\n\n    def _create_states(self):\n        \"\"\"Create states.\"\"\"\n        node = self._global_node_list[self._idx]\n        if node[\"op\"] in self._target_ops:\n            self._create_op_states()\n        else:\n            self._create_multi_inputs_states()\n\n    def _create_op_states(self):\n        \"\"\"State creation routine for nodes with target_op.\"\"\"\n        input_idx = self._global_in_nodes_dict[self._idx][0]\n        input_node_entry = self._global_node_list[input_idx]\n        if is_boundary_node(input_node_entry, self._global_input_names):\n            self._full_states = np.array([record[1].costs[0] for record in self._record_list])\n            self._states = self._full_states\n        else:\n            input_stage = self._global_stage_dict[input_idx]\n            input_dep = input_stage.dep\n            input_states = input_stage.states\n            input_flatten_states = input_states.flatten()\n            input_record_list = input_node_entry[\"record_candidates\"]\n            num_schedules = len(self._record_list)\n            num_input_schedules = len(input_record_list)\n            num_input_states = input_flatten_states.shape[0]\n\n            full_states_shape = tuple(\n                [num_schedules, num_input_schedules]\n                + [\n                    len(self._global_node_list[dep_idx][\"record_candidates\"])\n                    for dep_idx in input_dep\n                ]\n            )\n            self._full_states = np.zeros(full_states_shape).flatten().astype(\"float32\")\n            self._full_states_idx = [self._idx, input_idx] + input_dep\n            dep_multiplier = 1\n            for i in range(2, len(full_states_shape)):\n                dep_multiplier *= full_states_shape[i]\n            input_node_time_counted = input_idx in self._global_counted_nodes_set\n\n            for i in range(num_schedules):\n                current_sch_time = float(self._record_list[i][1].costs[0])\n                for j in range(num_input_states):\n                    input_sch_idx = j // dep_multiplier\n                    layout_transform_time = self._global_layout_transform_interlayer_cost[\n                        (input_idx, self._idx)\n                    ][input_sch_idx][i]\n\n                    if input_node_time_counted:\n                        total_time = current_sch_time + layout_transform_time\n                    else:\n                        total_time = (\n                            current_sch_time + layout_transform_time + input_flatten_states[j]\n                        )\n                    current_state_idx = i * num_input_states + j\n                    self._full_states[current_state_idx] = total_time\n\n            if not input_node_time_counted:\n                self._global_counted_nodes_set.add(input_idx)\n            self._full_states = self._full_states.reshape(full_states_shape)\n\n            # If out degree of input node is 1, we can remove the dimension of input node,\n            # since the states of input node will not be needed any more. Otherwise, input\n            # node should become a dependency.\n            if len(self._global_out_nodes_dict[input_idx]) == 1:\n                self._states = np.amin(self._full_states, axis=1)\n                self._dep = list(input_dep)\n            else:\n                self._states = self._full_states\n                self._dep = [\n                    input_idx,\n                ] + input_dep\n\n        # Update global dependency dictionary.\n        # This is to monitor the dependency states to decide\n        # when a dependency can be eliminated, so that total\n        # number of states can be largely reduced.\n        for dep_idx in self._dep:\n            self._global_dep_dict[dep_idx].remove(self._idx)\n            for child in self._global_out_nodes_dict[self._idx]:\n                self._global_dep_dict[dep_idx].add(child)\n        if len(self._global_out_nodes_dict[self._idx]) > 1:\n            self._global_dep_dict[self._idx] = set()\n            for child in self._global_out_nodes_dict[self._idx]:\n                self._global_dep_dict[self._idx].add(child)\n\n    def _create_multi_inputs_states(self):\n        \"\"\"State creation routine for multi_input operator\n\n        In tvm, layout transformation for an elemwise-like follow the rule which\n        all input operators transform their layouts to the leftmost input operator\n        layout. For example:\n                            elemwise-sum\n                            |    |    |\n                            |    |    |\n                           op0  op1  op2\n        In this block, the possible layout transformations are: op1 -> op0 and op2 -> op0.\n        In graph tuning, a 3-D array with shape (k0, k1, k2) can represent the layout\n        transformations between these three nodes. It is also possible some earlier states\n        belong to other nodes(We name them as dependency) are required for dynamic programming.\n        The final states array for this elemwise-sum can be with shape (e0, k0, k1, e1, k2).\n        To iterate through all states, we first align the shape of op0, op1 and op2 to be\n        (e0, k0, k1, e1, k2) by broadcasting the original states. We also record the axis of\n        each input node in the states array, together with the multiplier. For example,\n        the axis index for op0 is 1, and multiplier is k1 * e1 * k2. If current iterating index\n        in the flatten array is i, the index of op0 can be computed as:\n        i % (k0 * k1 * e1 * k2) // (k1 * e1 * k2).\n        \"\"\"\n        full_input_node_list = list(self._global_in_nodes_dict[self._idx])\n        input_index_list = []\n        # Remove input and ruled_out nodes\n        for input_idx in full_input_node_list:\n            input_node = self._global_node_list[input_idx]\n            if not is_boundary_node(input_node, self._global_input_names):\n                input_index_list.append(input_idx)\n\n        # Generate new states\n        states_list, aligned_node_list = DPStage.align_states(\n            input_index_list, self._global_stage_dict, self._global_node_list\n        )\n        target_node_idx, target_major_axis, target_multiplier, target_states = states_list[0]\n        aligned_shape = target_states.shape\n        self._full_states = np.zeros(aligned_shape).astype(\"float32\").flatten()\n        self._full_states_idx = list(aligned_node_list)\n        num_states = self._full_states.shape[0]\n        node_time_counted = [item[0] in self._global_counted_nodes_set for item in states_list]\n        target_states = target_states.flatten()\n        src_states_list = [states_list[i][3].flatten() for i in range(1, len(states_list))]\n\n        for i in range(num_states):\n            target_sch_idx = (\n                i % (target_multiplier * aligned_shape[target_major_axis])\n            ) // target_multiplier\n            if node_time_counted[0]:\n                new_state = 0\n            else:\n                new_state = target_states[i]\n\n            for j in range(1, len(states_list)):\n                src_states = src_states_list[j - 1]\n                src_node_idx, src_major_axis, src_multiplier, _ = states_list[j]\n                src_sch_idx = (\n                    i % (src_multiplier * aligned_shape[src_major_axis])\n                ) // src_multiplier\n                layout_transform_time = self._global_layout_transform_interlayer_cost[\n                    (src_node_idx, target_node_idx)\n                ][src_sch_idx][target_sch_idx]\n\n                if node_time_counted[j]:\n                    new_state += layout_transform_time\n                else:\n                    new_state += layout_transform_time + src_states[i]\n                self._full_states[i] = new_state\n\n        for i, node_counted in enumerate(node_time_counted):\n            if not node_counted:\n                self._global_counted_nodes_set.add(states_list[i][0])\n        self._full_states = self._full_states.reshape(aligned_shape)\n\n        # Remove dependency to reduce states\n        reduced_states = np.array(self._full_states)\n        reduced_states_transpose = [states_list[0][1]]\n        reduced_states_dep_list = []\n        self._dep = []\n        for i in range(len(reduced_states.shape)):\n            if i != states_list[0][1]:\n                reduced_states_transpose.append(i)\n                reduced_states_dep_list.append(aligned_node_list[i])\n        reduced_states = np.transpose(reduced_states, reduced_states_transpose)\n        shift = 0\n        for i, dep in enumerate(reduced_states_dep_list):\n            if dep not in self._global_dep_dict or len(self._global_dep_dict[dep]) == 1:\n                self._global_dep_dict.pop(dep, None)\n                reduced_states = np.amin(reduced_states, axis=i + 1 - shift)\n                shift += 1\n            else:\n                self._dep.append(dep)\n        self._states = reduced_states\n\n        # Update dependency\n        for dep in self._dep:\n            self._global_dep_dict[dep].remove(self._idx)\n            for child in self._global_out_nodes_dict[self._idx]:\n                self._global_dep_dict[dep].add(child)\n        if len(self._global_out_nodes_dict[self._idx]) > 1:\n            self._global_dep_dict[self._idx] = set()\n            for child in self._global_out_nodes_dict[self._idx]:\n                self._global_dep_dict[self._idx].add(child)\n\n    @property\n    def dep(self):\n        \"\"\"Get dependency list.\"\"\"\n        return self._dep\n\n    @property\n    def states(self):\n        \"\"\"Get states.\"\"\"\n        return self._states\n\n    @property\n    def full_states(self):\n        \"\"\"Get complete states.\"\"\"\n        return self._full_states\n\n    @property\n    def full_states_idx(self):\n        \"\"\"Get node index of complete states.\"\"\"\n        return self._full_states_idx\n\n    @staticmethod\n    def align_states(input_index_list, stage_dict, node_list):\n        \"\"\"Align all input node states shapes to be the same and transpose/reshape properly.\n\n        This is used in creating multi_input operator states.\n\n        Parameters\n        ----------\n        input_index_list : list of int\n            List of input node index.\n\n        stage_dict : dict of int to Stage\n            Global dictionary of node index to stage.\n\n        node_list : list of dict\n            List of all nodes for current graph.\n\n        Returns\n        -------\n        states_list : list of tuple\n            List of aligned states.\n\n        aligned_node_list : list in int\n            List of node index for aligned states.\n        \"\"\"\n        aligned_node_list = list(input_index_list)\n        states_list = []\n        for input_idx in input_index_list:\n            input_node_stage = stage_dict[input_idx]\n            for dep_idx in input_node_stage.dep:\n                if dep_idx not in aligned_node_list:\n                    aligned_node_list.append(dep_idx)\n        aligned_shape = []\n        for idx in aligned_node_list:\n            aligned_shape.append(len(node_list[idx][\"record_candidates\"]))\n        for input_idx in input_index_list:\n            input_node_stage = stage_dict[input_idx]\n            input_node_shape_idx_list = [input_idx] + input_node_stage.dep\n            transpose_idx_list = []\n            reshape_list = []\n            major_axis = -1\n            for i, idx in enumerate(aligned_node_list):\n                if input_idx == idx:\n                    major_axis = i\n                if idx in input_node_shape_idx_list:\n                    transpose_idx_list.append(idx)\n                    reshape_list.append(aligned_shape[i])\n                else:\n                    reshape_list.append(1)\n            transpose_list = [input_node_shape_idx_list.index(idx) for idx in transpose_idx_list]\n            input_node_states = np.transpose(input_node_stage.states, tuple(transpose_list))\n            input_node_states = np.reshape(input_node_states, tuple(reshape_list))\n            input_node_states = np.broadcast_to(input_node_states, aligned_shape)\n            multiplier = 1\n            for i in range(major_axis + 1, len(aligned_shape)):\n                multiplier *= aligned_shape[i]\n            states_list.append((input_idx, major_axis, multiplier, input_node_states))\n        return states_list, aligned_node_list\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/dynamic_programming_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-error,too-many-locals,too-many-statements,too-many-branches,unused-variable\n\"\"\"Dynamic programming tuner.\"\"\"\nimport sys\nimport numpy as np\n\nfrom ._base import MAX_OUTPUT_NODES\nfrom .base_graph_tuner import BaseGraphTuner\nfrom .dynamic_programming_stage import DPStage\nfrom .utils import has_multiple_inputs, is_boundary_node\n\nif sys.version_info[0] == 3:\n    import queue\nelse:\n    import Queue as queue\n\n\nclass DPTuner(BaseGraphTuner):\n    \"\"\"Tuner which uses dynamic programming to solve MDP problem.\n\n    Note: currently dynamic programming is used to solve this MDP problem. However,\n    this problem is intrinsically non-polynomial. DP can't apply for more complicated\n    models, such as networks with many element-wise sum operators. In this case, switch\n    to heuristic algorithm such as PBQP tuner.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Create a dynamic programming tuner.\"\"\"\n        super(DPTuner, self).__init__(*args, **kwargs)\n        self._num_states = self._max_num_states = None\n        self._stage_dict = {}\n        self._dep_dict = {}\n        self._counted_nodes_set = set()\n\n        self._global_data_dict = {\n            \"dtype\": self._dtype,\n            \"counted_nodes_set\": self._counted_nodes_set,\n            \"stage_dict\": self._stage_dict,\n            \"in_nodes_dict\": self._in_nodes_dict,\n            \"out_nodes_dict\": self._out_nodes_dict,\n            \"dep_dict\": self._dep_dict,\n            \"node_list\": self._node_list,\n            \"input_shapes\": self._input_shapes,\n            \"layout_transform_interlayer_cost\": self._layout_transform_interlayer_cost,\n        }\n\n    def _check_num_states(self, num_states):\n        \"\"\"Track the number of states.\"\"\"\n        self._num_states += num_states\n        if self._max_num_states is not None:\n            if self._num_states > self._max_num_states:\n                raise RuntimeError(\n                    \"Too many states detected while running dynamic \"\n                    \"programming: got %d states but upper limit is %d.\"\n                    % (self._num_states, self._max_num_states)\n                )\n\n    def _forward(self):\n        \"\"\"Forward pass in DP to generate states for all stages.\"\"\"\n        self._logger.info(\"Start forward pass...\")\n        for node_idx in sorted(self._in_nodes_dict.keys()):\n            stage = DPStage(idx=node_idx, target_ops=self._target_ops, **self._global_data_dict)\n            self._check_num_states(stage.full_states.size)\n            self._stage_dict[node_idx] = stage\n        self._logger.info(\"Finished forward pass.\")\n\n    def _backward(self):\n        \"\"\"Backward pass in DP to generate optimal solution.\"\"\"\n        self._logger.info(\"Start backward pass...\")\n        input_names = self._input_shapes.keys()\n        optimal_record_dict = {}\n        # Pick optimal schedule for output nodes\n        output_idx_list = []\n        for key, val in self._out_nodes_dict.items():\n            if not val:\n                output_idx_list.append(key)\n\n        # Restrict number of output nodes to avoid numpy reshape error\n        if len(output_idx_list) > MAX_OUTPUT_NODES:\n            msg = (\n                \"The number of outputs in graph is larger than upper \"\n                \"limit: %s vs %s. Usually this is caused by too many \"\n                \"LAYOUT_FIXED_OP in graph. Switch to greedily select schedule.\"\n                \"No action required at this moment. We will continuously improve graph tuner\"\n                % (len(output_idx_list), MAX_OUTPUT_NODES)\n            )\n            self._logger.warning(msg)\n            self._optimal_record_dict = {key: 0 for key in self._in_nodes_dict}\n            return\n\n        states_list, aligned_node_list = DPStage.align_states(\n            output_idx_list, self._stage_dict, self._node_list\n        )\n        num_states = states_list[0][3].size\n        self._check_num_states(num_states * len(output_idx_list))\n        aligned_node_shape = states_list[0][3].shape\n        min_time = 0\n        min_pos = -1\n        for states in states_list:\n            min_time += np.amax(states[3])\n        flatten_states_list = [current_states[3].flatten() for current_states in states_list]\n        for i in range(num_states):\n            current_time = 0\n            for j, current_states in enumerate(states_list):\n                current_time += flatten_states_list[j][i]\n            if min_time > current_time:\n                min_time = current_time\n                min_pos = i\n        for i, states in enumerate(states_list):\n            current_major_axis = states[1]\n            current_sch_idx = (\n                min_pos % (states[2] * aligned_node_shape[current_major_axis])\n            ) // states[2]\n            optimal_record_dict[aligned_node_list[i]] = current_sch_idx\n        # Pick optimal schedule for dependencies of output nodes\n        for i in range(len(states_list), len(aligned_node_list)):\n            multiplier = 1\n            for j in range(i + 1, len(aligned_node_list)):\n                multiplier *= aligned_node_shape[j]\n            optimal_record_dict[aligned_node_list[i]] = (\n                min_pos // multiplier % aligned_node_shape[i]\n            )\n\n        # Backward pass to get optimal schedules for other nodes\n        bfs_q = queue.Queue()\n        visited = set()\n        for out_idx in output_idx_list:\n            bfs_q.put(out_idx)\n        while not bfs_q.empty():\n            node_idx = bfs_q.get()\n            visited.add(node_idx)\n            node = self._node_list[node_idx]\n            if is_boundary_node(node, input_names):\n                continue\n            optimal_sch_idx = optimal_record_dict[node_idx]\n            full_states = self._stage_dict[node_idx].full_states\n            if not has_multiple_inputs(self._node_list, node_idx, input_names, self._opt_out_op):\n                input_idx = self._in_nodes_dict[node_idx][0]\n                input_node = self._node_list[input_idx]\n                if is_boundary_node(input_node, input_names):\n                    continue\n                if input_idx not in visited:\n                    bfs_q.put(input_idx)\n                    if input_idx not in optimal_record_dict:\n                        dep_list = self._stage_dict[node_idx].dep\n                        dep_idx = tuple([optimal_record_dict[item] for item in dep_list])\n                        tmp = np.argmin(full_states, axis=1)\n                        optimal_input_sch_idx = tmp[(optimal_sch_idx,) + dep_idx]\n                        optimal_record_dict[input_idx] = optimal_input_sch_idx\n            else:\n                input_idx_list = self._in_nodes_dict[node_idx]\n                optimal_record_dict[input_idx_list[0]] = optimal_sch_idx\n                full_states_idx = self._stage_dict[node_idx].full_states_idx\n                tmp = full_states[optimal_sch_idx]\n                new_states_idx, new_states_pos = [], []\n                visited_states_idx, visited_states_pos = [], []\n                for i in range(1, len(full_states_idx)):\n                    if full_states_idx[i] in optimal_record_dict:\n                        visited_states_idx.append(full_states_idx[i])\n                        visited_states_pos.append(i - 1)\n                    else:\n                        new_states_idx.append(full_states_idx[i])\n                        new_states_pos.append(i - 1)\n                if visited_states_idx:\n                    tmp = np.transpose(tmp, tuple(visited_states_pos + new_states_pos))\n                    tmp = tmp[tuple([optimal_record_dict[idx] for idx in visited_states_idx])]\n                min_pos = np.argmin(tmp)\n                multiplier = 1\n                for i in range(len(new_states_idx)):\n                    multiplier *= full_states.shape[new_states_pos[i] + 1]\n                for pos, idx in zip(new_states_pos, new_states_idx):\n                    multiplier //= full_states.shape[pos + 1]\n                    optimal_record_dict[idx] = min_pos // multiplier\n                    min_pos %= multiplier\n                for input_idx in input_idx_list:\n                    if input_idx not in visited:\n                        bfs_q.put(input_idx)\n\n        self._optimal_record_dict = optimal_record_dict\n        for node_idx, _ in self._in_nodes_dict.items():\n            if self._node_list[node_idx][\"op\"] not in self._target_ops:\n                continue\n        self._logger.info(\"Finished backward pass...\")\n\n    def run(self, **kwargs):\n        \"\"\"Run dynamic programming solver.\"\"\"\n        max_num_states = None if \"max_num_states\" not in kwargs else kwargs[\"max_num_states\"]\n        self._num_states = 0\n        self._max_num_states = max_num_states\n        self._logger.info(\"Start to run dynamic programming algorithm...\")\n        self._forward()\n        self._backward()\n        self._logger.info(\"Finished DPExecutor run.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/pbqp_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals\n\"\"\"Partitioned Boolean Quadratic Programming Tuner\"\"\"\nfrom ._base import INVALID_LAYOUT_TIME\nfrom .base_graph_tuner import BaseGraphTuner\nfrom .utils import is_boundary_node, has_multiple_inputs\n\n\nclass PBQPTuner(BaseGraphTuner):\n    \"\"\"An approximation method to deal with intractably\n    large size of graph tuning problem.\n\n    This graph coloring algorithm mainly comes from:\n\n    Lang Hames and Bernhard Scholz.\n    Nearly optimal register allocation with pbqp.JMLC 2006.\n    LNCS, vol.4228,pp. 346-361, 2016\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Create a partitioned boolean quadratic programming tuner.\"\"\"\n        super(PBQPTuner, self).__init__(*args, **kwargs)\n\n        # Remove input and ruled_out nodes\n        input_names = self._input_shapes.keys()\n        for node_idx in self._out_nodes_dict:\n            node = self._node_list[node_idx]\n            if is_boundary_node(node, input_names):\n                for out_node_idx in self._out_nodes_dict[node_idx]:\n                    self._in_nodes_dict[out_node_idx].remove(node_idx)\n\n        self._adj_dict = {}\n        for node_idx in self._in_nodes_dict:\n            self._adj_dict[node_idx] = list(self._in_nodes_dict[node_idx]) + list(\n                self._out_nodes_dict[node_idx]\n            )\n\n        self._record_cost_dict = {}\n        for key in self._in_nodes_dict:\n            self._record_cost_dict[key] = []\n            for record in self._node_list[key][\"record_candidates\"]:\n                self._record_cost_dict[key].append(record[1].costs[0])\n\n        self._max_degree = -1\n        self._node_degree_dict = {}\n        for node_idx in self._in_nodes_dict:\n            node_degree = self._get_degree(node_idx)\n            self._node_degree_dict[node_idx] = node_degree\n            self._max_degree = max(self._max_degree, node_degree)\n\n        self._stack = []\n        self._buckets = [[] for _ in range(self._max_degree + 2)]\n        for node_idx in sorted(self._in_nodes_dict):\n            node_degree = self._get_degree(node_idx)\n            self._buckets[node_degree].append(node_idx)\n\n        self._is_optimal = True\n\n    def _get_degree(self, node_idx):\n        \"\"\"Get node degree.\"\"\"\n        return len(self._adj_dict[node_idx])\n\n    def _reorder_adj_nodes(self, node_idx):\n        \"\"\"Update buckets list with current adjacency list.\"\"\"\n        for adj_node in self._adj_dict[node_idx]:\n            current_degree = self._get_degree(adj_node)\n            prev_degree = self._node_degree_dict[adj_node]\n            if prev_degree != current_degree:\n                self._buckets[prev_degree].remove(adj_node)\n                self._buckets[current_degree].insert(0, adj_node)\n                self._node_degree_dict[adj_node] = current_degree\n\n    def _remove_node(self, node_idx):\n        \"\"\"Remove node from graph. Update adjacency list accordingly.\"\"\"\n        node_degree = self._get_degree(node_idx)\n        self._buckets[node_degree].remove(node_idx)\n        for adj_node in self._adj_dict[node_idx]:\n            self._adj_dict[adj_node].remove(node_idx)\n\n    def _insert_edge(self, node_x, node_y, adj_cost_matrix):\n        \"\"\"Insert an edge between two nodes.\"\"\"\n        self._layout_transform_interlayer_cost[(node_x, node_y)] = adj_cost_matrix\n        self._layout_transform_interlayer_cost[(node_y, node_x)] = []\n        for i in range(len(adj_cost_matrix[0])):\n            self._layout_transform_interlayer_cost[(node_y, node_x)].append([])\n            for cost_vec in adj_cost_matrix:\n                self._layout_transform_interlayer_cost[(node_y, node_x)][i].append(cost_vec[i])\n\n        self._adj_dict[node_x].append(node_y)\n        self._adj_dict[node_y].append(node_x)\n\n    def _backward_insert_node(self, node_idx):\n        \"\"\"Reinsert node in backward pass.\"\"\"\n        for adj_node in self._adj_dict[node_idx]:\n            self._adj_dict[adj_node].append(node_idx)\n\n    def _RI_reduction(self, node_idx):\n        \"\"\"Reduce nodes with degree 1.\"\"\"\n        adj_node = self._adj_dict[node_idx][0]\n        ltf_matrix = self._layout_transform_interlayer_cost[(adj_node, node_idx)]\n        for i, cost_vec in enumerate(ltf_matrix):\n            min_cost = INVALID_LAYOUT_TIME\n            for j, cost in enumerate(cost_vec):\n                min_cost = min(min_cost, cost + self._record_cost_dict[node_idx][j])\n            self._record_cost_dict[adj_node][i] += min_cost\n        self._remove_node(node_idx)\n        self._reorder_adj_nodes(node_idx)\n        self._stack.append(node_idx)\n\n    def _RII_reduction(self, node_idx):\n        \"\"\"Reduce nodes with degree 2.\"\"\"\n        adj_node_x, adj_node_y = self._adj_dict[node_idx]\n        ltf_matrix_x = self._layout_transform_interlayer_cost[(adj_node_x, node_idx)]\n        ltf_matrix_y = self._layout_transform_interlayer_cost[(adj_node_y, node_idx)]\n        delta_matrix = [[] for _ in range(len(ltf_matrix_x))]\n        for i, cost_vec_x in enumerate(ltf_matrix_x):\n            for j, cost_vec_y in enumerate(ltf_matrix_y):\n                min_cost = INVALID_LAYOUT_TIME\n                for k in range(len(self._record_cost_dict[node_idx])):\n                    min_cost = min(\n                        min_cost,\n                        cost_vec_x[k] + cost_vec_y[k] + self._record_cost_dict[node_idx][k],\n                    )\n                delta_matrix[i].append(min_cost)\n\n        if adj_node_x == adj_node_y:\n            for i, delta_row in enumerate(delta_matrix):\n                self._record_cost_dict[adj_node_x][i] += delta_row[i]\n        elif adj_node_x in self._adj_dict[adj_node_y]:\n            for i, _ in enumerate(delta_matrix):\n                for j, delta in enumerate(delta_matrix[i]):\n                    self._layout_transform_interlayer_cost[(adj_node_x, adj_node_y)][i][j] += delta\n                    self._layout_transform_interlayer_cost[(adj_node_y, adj_node_x)][j][i] += delta\n        else:\n            self._insert_edge(adj_node_x, adj_node_y, delta_matrix)\n\n        self._remove_node(node_idx)\n        self._reorder_adj_nodes(node_idx)\n        self._stack.append(node_idx)\n\n    def _RN_reduction(self, node_idx):\n        \"\"\"Reduce nodes with degree greater than 2.\"\"\"\n        min_cost = INVALID_LAYOUT_TIME\n        record_idx = -1\n\n        for i, record_cost in enumerate(self._record_cost_dict[node_idx]):\n            current_cost = record_cost\n            for adj_node in self._adj_dict[node_idx]:\n                ltf_matrix = self._layout_transform_interlayer_cost[(node_idx, adj_node)]\n                adj_record_cost = list(self._record_cost_dict[adj_node])\n                for j, ltf_cost in enumerate(ltf_matrix[i]):\n                    adj_record_cost[j] += ltf_cost\n                current_cost += min(adj_record_cost)\n            if current_cost < min_cost:\n                min_cost = current_cost\n                record_idx = i\n\n        if record_idx < 0:\n            raise RuntimeError(\n                \"Can't find a soltuion for node %d when \" \"applying RN reduction\" % node_idx\n            )\n        self._optimal_record_dict[node_idx] = record_idx\n        self._is_optimal = False\n\n        for adj_node in self._adj_dict[node_idx]:\n            ltf_matrix = self._layout_transform_interlayer_cost[(node_idx, adj_node)]\n            for i, ltf_cost in enumerate(ltf_matrix[record_idx]):\n                self._record_cost_dict[adj_node][i] += ltf_cost\n\n        self._remove_node(node_idx)\n        self._reorder_adj_nodes(node_idx)\n        self._stack.append(node_idx)\n\n    def _forward(self):\n        \"\"\"Forward pass in PBQP to reduce nodes.\"\"\"\n        while True:\n            if self._buckets[1]:\n                node_idx = self._buckets[1][0]\n                self._RI_reduction(node_idx)\n            elif self._max_degree >= 2 and self._buckets[2]:\n                node_idx = self._buckets[2][0]\n                self._RII_reduction(node_idx)\n            elif self._max_degree >= 3:\n                max_degree_node = -1\n                for i in range(self._max_degree, 2, -1):\n                    if self._buckets[i]:\n                        max_degree_node = self._buckets[i][0]\n                        self._RN_reduction(max_degree_node)\n                        break\n                if max_degree_node < 0:\n                    break\n            else:\n                break\n\n    def _backward(self):\n        \"\"\"Backward pass in PBQP to generate optimal solution.\"\"\"\n        # Solve nodes left in the forward graph\n        for node_idx in self._buckets[0]:\n            record_costs = self._record_cost_dict[node_idx]\n            min_cost = min(record_costs)\n            self._optimal_record_dict[node_idx] = record_costs.index(min_cost)\n\n        # Solve nodes with one or two degrees\n        for node_idx in reversed(self._stack):\n            self._backward_insert_node(node_idx)\n            if node_idx not in self._optimal_record_dict:\n                record_costs = list(self._record_cost_dict[node_idx])\n                for adj_node in self._adj_dict[node_idx]:\n                    adj_optimal_idx = self._optimal_record_dict[adj_node]\n                    for i, _ in enumerate(record_costs):\n                        record_costs[i] += self._layout_transform_interlayer_cost[\n                            (node_idx, adj_node)\n                        ][i][adj_optimal_idx]\n                min_cost = min(record_costs)\n                self._optimal_record_dict[node_idx] = record_costs.index(min_cost)\n\n    def run(self, **kwargs):\n        \"\"\"Run partitioned boolean quadratic programming tuner.\"\"\"\n        self._logger.info(\"Start to run PBQP algorithm...\")\n        # Define virtual record lists and layout transformaton matrices\n        # for multi-input nodes.\n        input_names = self._input_shapes.keys()\n        temp = {}\n        for key, val in self._in_nodes_dict.items():\n            target_input_idx = -1\n            target_input_pos = -1\n            if has_multiple_inputs(self._node_list, key, input_names, self._opt_out_op):\n                for i, item in enumerate(val):\n                    node = self._node_list[item]\n                    if not is_boundary_node(node, input_names):\n                        target_input_idx = item\n                        target_input_pos = i\n                        break\n\n                # Skip boundary operator\n                if target_input_idx < 0:\n                    continue\n\n                temp[(target_input_idx, key)] = []\n                record_candidates = self._node_list[target_input_idx][\"record_candidates\"]\n                for j in range(len(record_candidates)):\n                    temp[(target_input_idx, key)].append([])\n                    for k in range(len(record_candidates)):\n                        temp[(target_input_idx, key)][j].append(\n                            0 if j == k else INVALID_LAYOUT_TIME\n                        )\n\n                for j in range(target_input_pos + 1, len(val)):\n                    input_idx = val[j]\n                    input_node = self._node_list[input_idx]\n                    if is_boundary_node(input_node, input_names):\n                        continue\n                    temp[(input_idx, key)] = self._layout_transform_interlayer_cost[\n                        (input_idx, target_input_idx)\n                    ]\n        self._layout_transform_interlayer_cost.update(temp)\n\n        # Create reverse layout transformation matrices\n        temp = {}\n        for idx_pair, ltf_matrix in self._layout_transform_interlayer_cost.items():\n            reverse_key = (idx_pair[1], idx_pair[0])\n            reverse_matrix = [[] for _ in range(len(ltf_matrix[0]))]\n            for i, _ in enumerate(ltf_matrix):\n                for j, ltf in enumerate(ltf_matrix[i]):\n                    reverse_matrix[j].append(ltf)\n            temp[reverse_key] = reverse_matrix\n        self._layout_transform_interlayer_cost.update(temp)\n\n        self._forward()\n        self._backward()\n        is_optimal = \"optimal\" if self._is_optimal else \"sub-optimal\"\n        msg = \"Finished PBQPExecutor run. Got %s solution.\" % is_optimal\n        self._logger.info(msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/utils/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Graph tuner utility functions\"\"\"\nfrom __future__ import absolute_import\n\nfrom . import traverse_graph\nfrom . import utils\n\nfrom .traverse_graph import expr2graph, get_direct_ancestor, get_in_nodes, get_out_nodes\nfrom .utils import has_multiple_inputs, is_boundary_node, bind_inputs\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/utils/traverse_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-locals,too-many-statements,too-many-branches,protected-access\n\"\"\"API for graph traversing.\"\"\"\nimport threading\nimport re\n\nimport tvm\nfrom tvm import relay, autotvm\nfrom tvm.relay import transform\nfrom tvm.relay.expr import Call, TupleGetItem, Var, Constant, Tuple\nfrom tvm.relay.function import Function\nfrom tvm.relay.ty import TupleType, TensorType\nfrom tvm.autotvm.task import TaskExtractEnv\n\nfrom .utils import has_multiple_inputs, is_boundary_node, is_skipped_node\nfrom .._base import OPT_OUT_OP\n\n\ndef expr2graph(expr, target_ops, node_dict, node_list, tvm_target):\n    \"\"\"Convert relay expr to graph data structure\n    and fetch workloads of target operators.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr.Function\n        Input relay function expression.\n\n    target_ops: List of tvm.ir.Op\n        List of target relay ops\n\n    node_dict : dictionary from tvm.relay.Expr to int\n        Dictionary to record node index\n\n    node_list : list of dictionary\n        List of nodes which contains all expr in the input relay function.\n        Each node will be stored as a dictionary in the format of\n        {\"op\": str, \"node\": tvm.relay.expr, \"inputs\": [int], \"types\": [tvm.relay.Type],\n         \"name\": str, \"workloads\": [tuple], \"topi_op\": [function]}\n\n    tvm_target : tvm.target\n        The TVM target object.\n    \"\"\"\n    # TODO(@kevinthesun, @icemelon9): Currently graph tuning pass relies on the fact\n    #   that # autotvm tasks == # ops. But this won't be true after having relay op\n    #   strategy. We need to find a solution to fix this.\n    env = TaskExtractEnv.get(allow_duplicate=True)\n    env.reset(target_ops)\n    # pylint: disable=not-context-manager\n    with env:\n        _expr2graph_impl(expr, target_ops, node_dict, node_list, tvm_target)\n        task_pos = 0\n        for node_entry in node_list:\n            if node_entry[\"op\"] in target_ops:\n                task_name, args = env.task_collection[task_pos]\n                task = autotvm.task.create(task_name, args, target=tvm_target)\n                node_entry[\"workloads\"] = [task.workload]\n                node_entry[\"topi_op\"] = [task_name]\n                task_pos += 1\n\n\ndef _infer_type(node):\n    \"\"\"A method to infer the type of a relay expression.\"\"\"\n    mod = tvm.IRModule.from_expr(node)\n    mod = transform.InferType()(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(node, relay.Function) else entry.body\n\n\ndef _replace_device_with_tracing(target):\n    \"\"\"This is to replace -device=XXX with -device=tracing in the tvm_target string.\n    It is a stand-along function for testability.\n    We need to have device=tracing in order to fetch the workloads, it is not used\n    for anything beyond that so it is safe to override the device here only.\"\"\"\n    target = str(target)\n    if \"-device\" in target:\n        return re.sub(\"-device=[^\\\\-$]+\", \"-device=tracing \", target).strip(\" \")\n    return target + \" -device=tracing\"\n\n\ndef _expr2graph_impl(expr, target_ops, node_dict, node_list, tvm_target):\n    \"\"\"Implementation to convert relay expr to graph data structure\"\"\"\n\n    def _traverse_expr(node):\n        if node in node_dict:\n            return\n        node_index = len(node_list)\n        node_entry = {\"node\": node, \"inputs\": [], \"types\": [], \"op\": None, \"name\": None}\n\n        if isinstance(node, Call):\n            op = node.op\n            node_entry[\"op\"] = node.op\n            for arg in node.args:\n                in_node_idx = node_dict[arg]\n                if isinstance(arg, (Tuple, TupleGetItem)):\n                    node_entry[\"inputs\"] += node_list[in_node_idx][\"inputs\"]\n                else:\n                    node_entry[\"inputs\"].append([in_node_idx, 0, 0])\n            infer_out = _infer_type(node)\n            out_type = infer_out._checked_type_\n            if isinstance(out_type, TensorType):\n                node_entry[\"types\"].append(out_type)\n            elif isinstance(out_type, TupleType):\n                for tupe_type in out_type.fields:\n                    node_entry[\"types\"].append(tupe_type)\n            else:\n                raise RuntimeError(\n                    \"Unsupported output type %s in operator %s\" % (type(out_type), op.name)\n                )\n\n            # Utilize tracing target to fetch workload with topo-order.\n            # Since we only need workload, dummy target can be used to\n            # create task.\n            if op in target_ops:\n                params = []\n                for i, input_idx in enumerate(node_entry[\"inputs\"]):\n                    input_node_entry = node_list[input_idx[0]]\n                    input_type = input_node_entry[\"types\"][input_idx[1]]\n                    if not isinstance(input_node_entry[\"node\"], (Var, Constant, Call)):\n                        raise RuntimeError(\n                            \"Graph tuner can only tune target \"\n                            \"operators with input node of type \"\n                            \"relay.expr.Var/Constant/Call. Now \"\n                            \"find a target op %s with input type %s\"\n                            % (op, str(type(input_node_entry[\"node\"])))\n                        )\n                    free_var = relay.Var(\"var_%d\" % i, input_type)\n                    params.append(free_var)\n                call = relay.Call(node.op, params, node.attrs)\n                mod = tvm.IRModule.from_expr(relay.Function(params, call))\n                relay.backend.te_compiler.get().clear()\n                tracing_target = _replace_device_with_tracing(tvm_target)\n                build_thread = threading.Thread(target=relay.build, args=(mod, tracing_target))\n                build_thread.start()\n                build_thread.join()\n        elif isinstance(node, Var):\n            node_entry[\"name\"] = node.name_hint\n            node_entry[\"types\"] = [node.type_annotation]\n        elif isinstance(node, Function):\n            # Ignore root node since it equals to input function expression\n            if node != expr:\n                _expr2graph_impl(node, target_ops, node_dict, node_list, tvm_target)\n            return\n        elif isinstance(node, TupleGetItem):\n            in_node_idx = node_dict[node.tuple_value]\n            node_entry[\"inputs\"].append([in_node_idx, node.index, 0])\n        elif isinstance(node, Tuple):\n            for tuple_item in node:\n                in_node_idx = node_dict[tuple_item]\n                if isinstance(tuple_item, TupleGetItem):\n                    node_entry[\"inputs\"] += node_list[in_node_idx][\"inputs\"]\n                elif isinstance(tuple_item, Tuple):\n                    raise RuntimeError(\"Graph tuner doesn't support nested tuple.\")\n                else:\n                    node_entry[\"inputs\"].append([in_node_idx, 0, 0])\n        elif isinstance(node, Constant):\n            node_entry[\"name\"] = \"Constant_\" + str(node_index)\n            node_entry[\"types\"] = [node.checked_type]\n        elif isinstance(node, tvm.ir.Op):\n            return\n        else:\n            raise RuntimeError(\n                \"Not supported relay node type in graph tuning: %s\" % str(type(node))\n            )\n        node_dict[node] = node_index\n        node_list.append(node_entry)\n\n    relay.analysis.post_order_visit(expr, _traverse_expr)\n\n\ndef get_direct_ancestor(node_list, visited_dict, target_ops, node_idx, input_names):\n    \"\"\"Given a node_list in relay function and a node index, return the\n    closest ancestor which has op_name as operator name or is multi_input operator.\n\n    If node has multiple inputs, multiple ancestor nodes will be returned.\n\n    Parameters\n    ----------\n    node_list : list of dict of str to object\n        List of all nodes in a graph.\n\n    visited_dict : dict of int to int\n        Nodes and corresponding ancestors which have been visited.\n\n    target_ops: List of str\n        List of target relay base op name\n\n    node_idx : int\n        Input node index.\n\n    input_names : list of str\n        Names of graph input nodes.\n\n    Returns\n    -------\n    out : list of int\n        List of ancestor node index.\n    \"\"\"\n    if node_idx in visited_dict:\n        return visited_dict[node_idx]\n    node = node_list[node_idx]\n    if is_boundary_node(node, input_names):\n        return [node_idx]\n\n    node_direct_ancestor = []\n    for item_idx in node[\"inputs\"]:\n        item = node_list[item_idx[0]]\n        is_multiple_inputs = has_multiple_inputs(node_list, item_idx[0], input_names, OPT_OUT_OP)\n        if item[\"op\"] in target_ops or is_multiple_inputs:\n            node_direct_ancestor.append(item_idx[0])\n        else:\n            tmp = get_direct_ancestor(node_list, visited_dict, target_ops, item_idx[0], input_names)\n            for tmp_item in tmp:\n                if tmp_item not in node_direct_ancestor:\n                    node_direct_ancestor.append(tmp_item)\n    visited_dict[node_idx] = node_direct_ancestor\n    return node_direct_ancestor\n\n\ndef get_in_nodes(node_list, target_ops, input_names):\n    \"\"\"Create a dictionary mapping from op_name nodes or multi-input\n    nodes to closest input ancestors.\n\n    Parameters\n    ----------\n    node_list : list of dict of str to object\n        List of all nodes in a graph.\n\n    target_ops: List of str\n        List of target relay op\n\n    input_names : list of str\n        Names of graph input nodes.\n\n    Returns\n    -------\n    out : dict of int to list of int\n        Dictionary maps node index to closest input ancestors.\n    \"\"\"\n\n    visited_dict = {}\n    in_node_dict = {}\n    for i, node in enumerate(node_list):\n        if is_boundary_node(node, input_names) or is_skipped_node(node):\n            continue\n        get_direct_ancestor(node_list, visited_dict, target_ops, i, input_names)\n    for key, val in visited_dict.items():\n        node = node_list[key]\n        is_multiple_inputs = has_multiple_inputs(node_list, key, input_names, OPT_OUT_OP)\n        if node[\"op\"] in target_ops or is_multiple_inputs:\n            in_node_dict[key] = val\n\n    # Reduce boundary nodes\n    out_node_dict = get_out_nodes(in_node_dict)\n    has_reduced_node = True\n    while has_reduced_node:\n        boundary_nodes = []\n        for key, val in in_node_dict.items():\n            node = node_list[key]\n            is_boundary = True\n            # Target ops can't be boundary nodes\n            if node[\"op\"] not in target_ops:\n                for input_idx in val:\n                    in_node = node_list[input_idx]\n                    if not is_boundary_node(in_node, input_names) and input_idx in in_node_dict:\n                        is_boundary = False\n                    else:\n                        val.remove(input_idx)\n                    if is_boundary:\n                        boundary_nodes.append(key)\n        if boundary_nodes:\n            for idx in boundary_nodes:\n                if idx in in_node_dict:\n                    del in_node_dict[idx]\n        else:\n            has_reduced_node = False\n\n    # Remove empty nodes to ignore pre-computed sub-graph\n    has_empty_node = True\n    while has_empty_node:\n        empty_nodes = []\n        for key, val in in_node_dict.items():\n            if not val:\n                empty_nodes.append(key)\n        if empty_nodes:\n            has_empty_node = True\n            for node in empty_nodes:\n                del in_node_dict[node]\n                if node in out_node_dict:\n                    for out_node in out_node_dict[node]:\n                        in_node_dict[out_node].remove(node)\n        else:\n            has_empty_node = False\n\n    return in_node_dict\n\n\ndef get_out_nodes(in_node_dict):\n    \"\"\"Create output dictionary from input dictionary.\n\n    Parameters\n    ----------\n    in_node_dict : dict of int to list of int\n        Dictionary maps node index to closest input ancestors.\n        It can be created with get_in_nodes.\n\n    Returns\n    -------\n    out : dict of int to list of int\n        Dictionary maps node index to closest output nodes.\n    \"\"\"\n    out_node_dict = {}\n    for key in in_node_dict:\n        out_node_dict[key] = []\n    for key, val in in_node_dict.items():\n        for item in val:\n            if item in out_node_dict:\n                out_node_dict[item].append(key)\n            else:\n                out_node_dict[item] = [key]\n\n    return out_node_dict\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/graph_tuner/utils/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=eval-used,invalid-name,too-many-arguments\n\"\"\"Utility functions\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef has_multiple_inputs(node_list, node_idx, input_names, opt_out_op):\n    \"\"\"Check whether a node has multiple input nodes\n    except variable nodes.\n\n    Parameters\n    ----------\n    node_list : list of dict of str to object\n        List of all nodes in a graph.\n\n    node_idx : int\n        Node index to be checked.\n\n    input_names : list of str\n        List of input names of graph.\n\n    Returns\n    -------\n    out : bool\n        Whether the specified node has multiple input nodes\n    \"\"\"\n    num_inputs = 0\n    node = node_list[node_idx]\n    for in_idx in node[\"inputs\"]:\n        in_idx = in_idx[0]\n        in_node = node_list[in_idx]\n        # Exclude parameter nodes\n        if in_node[\"op\"] is not None and in_node[\"op\"].name in opt_out_op:\n            increase = False\n            for t_idx in in_node[\"inputs\"]:\n                increase = has_multiple_inputs(node_list, t_idx[0], input_names, opt_out_op)\n            if increase:\n                num_inputs += 1\n        elif in_node[\"op\"] is not None or (\"name\" in in_node and in_node[\"name\"] in input_names):\n            num_inputs += 1\n    return num_inputs > 1\n\n\ndef is_boundary_node(node_entry, input_names):\n    \"\"\"Whether a node is a boundary node.\n    Currently input node and nodes in LAYOUT_FIXED_OP are\n    counted as boundary.\n\n    Parameters\n    ----------\n    node_entry : dict\n        Node entry.\n\n    input_names : list of str\n        List of input names of graph.\n\n    Returns\n    -------\n    out : bool\n        whether node is a boundary node.\n    \"\"\"\n    # Operators dependent on original layouts.\n    _LAYOUT_FIXED_OP = [\n        relay.op.get(name)\n        for name in (\n            \"nn.batch_flatten\",\n            \"transpose\",\n            \"reshape\",\n            \"vision.multibox_prior\",\n            \"vision.multibox_transform_loc\",\n            \"where\",\n            \"vision.non_max_suppression\",\n            \"strided_slice\",\n        )\n    ]\n\n    out = node_entry[\"op\"] in _LAYOUT_FIXED_OP or (\n        \"name\" in node_entry and node_entry[\"name\"] in input_names\n    )\n    return out\n\n\ndef is_skipped_node(node_entry):\n    \"\"\"Whether a node is not counted.\n\n    Parameters\n    ----------\n    node_entry : dict\n        Node entry.\n\n    Returns\n    -------\n    out : bool\n        whether node is skipped.\n    \"\"\"\n    # Operators not counted in graph tuner.\n    return isinstance(node_entry[\"node\"], relay.Tuple)\n\n\ndef bind_inputs(expr, input_shapes=None, input_dtypes=\"float32\"):\n    \"\"\"Bind input variables of a relay function expression\n    to new shapes and/or dtypes.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr.Function\n        Input relay function expression.\n\n    input_shapes : dict of str to tuple of int, optional\n        Input shapes.\n\n    input_dtypes : str or dict of str to str, optional\n        Input dtypes.\n\n    Returns\n    -------\n    out : tvm.relay.Expr.Function\n        Bind relay function expression.\n    \"\"\"\n    if input_shapes is None:\n        return expr\n    if isinstance(input_dtypes, str):\n        input_dtypes = {key: input_dtypes for key in input_shapes.keys()}\n\n    updated_input_dict = {}\n    for input_name in input_shapes.keys():\n        updated_input = relay.var(\n            input_name, shape=input_shapes[input_name], dtype=input_dtypes[input_name]\n        )\n        updated_input_dict[input_name] = updated_input\n\n    rebind_dict = {}\n    for var in expr.params:\n        if var.name_hint in updated_input_dict:\n            rebind_dict[var] = updated_input_dict[var.name_hint]\n    updated_expr = relay.expr.bind(expr, rebind_dict)\n\n    mod = tvm.IRModule.from_expr(updated_expr)\n    mod = transform.InferType()(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(updated_expr, relay.Function) else entry.body\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/measure/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Distributed executor infrastructure to scale up the tuning\"\"\"\n\nfrom .measure import (\n    MeasureInput,\n    MeasureResult,\n    MeasureErrorNo,\n    measure_option,\n    create_measure_batch,\n)\nfrom .measure_methods import (\n    LocalBuilder,\n    LocalRunner,\n    RPCRunner,\n    default_module_loader,\n    request_remote,\n)\nfrom .executor import Executor\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/measure/executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Abstraction for asynchronous job execution \"\"\"\n\n\nclass Executor(object):\n    \"\"\"\n    Base abstract executor interface for asynchronous job submission.\n    Allows submit asynchronous jobs and returns the Future object.\n    \"\"\"\n\n    # timeout for jobs that may hang\n    DEFAULT_TIMEOUT = 120\n\n    def submit(self, func, *args, **kwargs):\n        \"\"\"\n        Pass task (function, arguments) to the Executor.\n\n        Parameters\n        ----------\n        func : callable\n            function to be run by a worker\n        args : list or tuple, optional\n            arguments passed to the function\n        kwargs : dict, optional\n            The keyword arguments\n\n        Returns\n        -------\n        future : Future\n            Future object wrapping the task which can be used to\n            collect the task's result.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Future(object):\n    \"\"\"\n    Base class of the future object.\n    The implementations can return object of subclass of this.\n    This objects encapsulates the asynchronous execution of task\n    submitted to another thread, or another worker for execution.\n\n    Future objects store the state of tasks--can be polled for\n    result or a blocking call to retrieve the result can be used.\n    \"\"\"\n\n    def done(self):\n        \"\"\"\n        Return True if job was successfully cancelled or finished running.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get(self, timeout=None):\n        \"\"\"\n        Get the result. This will block until the result is available.\n\n        Parameters\n        ----------\n        timeout : int or float, optional\n            Maximum number of seconds to wait before it timeouts.\n            If not specified, it means we block until the result is available.\n\n        Returns\n        -------\n        result : Any\n            The result returned by the submitted function.\n\n        Raises\n        ------\n        TimeoutError : if the result call timeouts.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass FutureError(RuntimeError):\n    \"\"\"Base error class of all future events\"\"\"\n\n\n# pylint:disable=redefined-builtin\nclass TimeoutError(FutureError):\n    \"\"\"Error raised when a task is timeout.\"\"\"\n\n\nclass ExecutionError(FutureError):\n    \"\"\"\n    Error raised when future execution crashes or failed.\n    \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/measure/measure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=pointless-string-statement,consider-using-enumerate,invalid-name\n\"\"\"User facing API for specifying how to measure the generated code\"\"\"\nimport enum\nimport multiprocessing\nfrom collections import namedtuple\n\n\nclass MeasureInput(namedtuple(\"MeasureInput\", [\"target\", \"task\", \"config\"])):\n    \"\"\"\n    Stores all the necessary inputs for a measurement.\n\n    Parameters\n    ----------\n    target : tvm.target.Target\n        The target device\n    task : task.Task\n        Task function\n    config : ConfigEntity\n        Specific configuration.\n    \"\"\"\n\n\nclass MeasureResult(namedtuple(\"MeasureResult\", [\"costs\", \"error_no\", \"all_cost\", \"timestamp\"])):\n    \"\"\"\n    Stores all the results of a measurement\n\n    Parameters\n    ----------\n    costs: Array of float or Array of Exception\n        If no error occurs during measurement, it is an array of measured running times.\n        If an error occurs during measurement, it is an array of the exception objections.\n    error_no: int\n        Denote error type, defined by MeasureErrorNo\n    all_cost: float\n        All cost of this measure, including rpc, compilation, test runs\n    timestamp: float\n        The absolute time stamp when we finish measurement.\n    \"\"\"\n\n    def __repr__(self):\n        error_no_str = (\n            str(MeasureErrorNo(self.error_no))\n            if isinstance(self.error_no, (MeasureErrorNo, int))\n            else str(self.error_no)\n        )\n        return (\n            f\"{self.__class__.__name__}(costs={self.costs!r}, error_no={error_no_str}, \"\n            f\"all_cost={self.all_cost}, timestamp={self.timestamp!r})\"\n        )\n\n\nclass MeasureErrorNo(enum.IntEnum):\n    \"\"\"Error type for MeasureResult\"\"\"\n\n    NO_ERROR = 0  # no error\n    INSTANTIATION_ERROR = 1  # actively detected error in instantiating a template with a config\n    COMPILE_HOST = 2  # error when compiling code on host (e.g. tvm.build)\n    COMPILE_DEVICE = 3  # error when compiling code on device (e.g. OpenCL JIT on the device)\n    RUNTIME_DEVICE = 4  # error when run program on device\n    WRONG_ANSWER = 5  # answer is wrong when compared to a golden output\n    BUILD_TIMEOUT = 6  # timeout during compilation\n    RUN_TIMEOUT = 7  # timeout during run\n    UNKNOWN_ERROR = 8  # unknown error\n\n\nclass Builder(object):\n    \"\"\"Builder that builds programs in tuning\n\n    Parameters\n    ----------\n    timeout: float, optional\n        The timeout of a build task\n    n_parallel: int, optional\n        The number of tasks submitted in parallel\n        By default it will use all cpu cores\n    build_kwargs: dict, optional\n        Keyword args given to the build function.\n    \"\"\"\n\n    def __init__(self, timeout=10, n_parallel=None, build_kwargs=None):\n        self.timeout = timeout\n        self.n_parallel = n_parallel or multiprocessing.cpu_count()\n        self.user_build_kwargs = build_kwargs if build_kwargs is not None else {}\n        self.runner_build_kwargs = None\n        self.task = None\n\n    def set_task(self, task, build_kwargs=None):\n        \"\"\"\n        Initialize for a new tuning task\n\n        Parameters\n        ----------\n        task: Task\n            The tuning task\n        build_kwargs: dict, optional\n            The additional kwargs for build function\n        \"\"\"\n        self.task = task\n        self.build_kwargs = dict(build_kwargs.items()) if build_kwargs is not None else {}\n        if any(k in self.build_kwargs for k in self.user_build_kwargs):\n            logging.warn(\n                \"Overriding these runner-supplied kwargs with user-supplied:\\n%s\",\n                \"\\n\".join(\n                    f\" * {k}: from {build_kwargs[k]!r} to {self.user_build_kwargs[k]!r}\"\n                    for k in sorted([k for k in build_kwargs if k in self.user_build_kwargs])\n                ),\n            )\n        for k, v in self.user_build_kwargs.items():\n            self.build_kwargs[k] = v\n\n    def build(self, measure_inputs):\n        \"\"\"Build programs\n\n        Parameters\n        ----------\n        measure_inputs: List of MeasureInput\n            The measure input\n\n        Returns\n        -------\n        build_results: List of BuildResult\n            The build result.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Runner(object):\n    \"\"\"Runner that runs and measures the time cost of a generated program in tuning\n\n    Parameters\n    ----------\n    timeout: float, optional\n        The timeout of a build task\n    n_parallel: int, optional\n        The number of tasks submitted in parallel\n        By default it will use all cpu cores\n    \"\"\"\n\n    def __init__(self, timeout=5, n_parallel=None):\n        self.timeout = timeout\n        self.n_parallel = n_parallel or multiprocessing.cpu_count()\n        self.task = None\n\n    def set_task(self, task):\n        \"\"\"\n        Initialize for a new tuning task\n\n        Parameters\n        ----------\n        task: Task\n            The tuning task\n        \"\"\"\n        self.task = task\n\n    def get_build_kwargs(self):\n        \"\"\"\n        Get device specific build arguments (e.g. maximum shared memory size)\n\n        Returns\n        ----------\n        kwargs: dict\n            The additional keyword arguments\n        \"\"\"\n        raise NotImplementedError()\n\n    def run(self, measure_inputs, build_results):\n        \"\"\"Run amd measure built programs\n\n        Parameters\n        ----------\n        measure_inputs: List of MeasureInput\n            The raw measure input\n        build_results: List of BuildResults\n            The build results\n\n        Returns\n        -------\n        measure_results: List of MeasureResult\n            The final results of measurement\n        \"\"\"\n        raise NotImplementedError()\n\n\ndef measure_option(builder, runner):\n    \"\"\"\n    Set options for measure. To measure a config, we will build it and run it.\n    So we have to set options for these two steps.\n    They have their own options on timeout, parallel, etc.\n\n    Parameters\n    ----------\n    builder: Builder\n        Specify how to build programs\n    runner: Runner\n        Specify how to run programs\n\n    Examples\n    --------\n    # example setting for using local devices\n    >>> measure_option = autotvm.measure_option(\n    >>>     builder=autotvm.LocalBuilder(),      # use all local cpu cores for compilation\n    >>>     runner=autotvm.LocalRunner(          # measure them sequentially\n    >>>         number=10,\n    >>>         timeout=5)\n    >>> )\n\n    # example setting for using remote devices\n    >>> measure_option = autotvm.measure_option(\n    >>>    builder=autotvm.LocalBuilder(),  # use all local cpu cores for compilation\n    >>>    runner=autotvm.RPCRunner(\n    >>>        'rasp3b', 'locahost', 9190, # device key, host and port of the rpc tracker\n    >>>        number=4,\n    >>>        timeout=4) # timeout of a run on the device. RPC request waiting time is excluded.\n    >>>)\n\n    Note\n    ----\n    To make measurement results accurate, you should pick the correct value for the argument\n    `number` and `repeat` in Runner(). Some devices need a certain minimum running time to\n    \"warm up,\" such as GPUs that need time to reach a performance power state.\n    Using `min_repeat_ms` can dynamically adjusts `number`, so it is recommended.\n    The typical value for NVIDIA GPU is 150 ms.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from .measure_methods import LocalBuilder, LocalRunner\n\n    if isinstance(builder, str):\n        if builder == \"local\":\n            builder = LocalBuilder()\n        else:\n            raise ValueError(\"Invalid builder: \" + builder)\n\n    if isinstance(runner, str):\n        if runner == \"local\":\n            runner = LocalRunner()\n        else:\n            raise ValueError(\"Invalid runner: \" + runner)\n\n    opt = {\n        \"builder\": builder,\n        \"runner\": runner,\n    }\n\n    return opt\n\n\ndef create_measure_batch(task, option):\n    \"\"\"Get a standard measure_batch function.\n\n    Parameters\n    ----------\n    task: tvm.autotvm.task.Task\n        The tuning task\n    option: dict\n        The option for measuring generated code.\n        You should use the return value of function :any:`measure_option` for this argument.\n\n    Returns\n    -------\n    measure_batch: callable\n        a callback function to measure a batch of configs\n    \"\"\"\n    builder = option[\"builder\"]\n    runner = option[\"runner\"]\n\n    attach_objects = runner.set_task(task)\n\n    # feed device related information from runner to builder\n    # (e.g. max shared memory for validity checking)\n    build_kwargs = runner.get_build_kwargs()\n    builder.set_task(task, build_kwargs)\n\n    def measure_batch(measure_inputs):\n        build_results = builder.build(measure_inputs)\n        results = runner.run(measure_inputs, build_results)\n        return results\n\n    measure_batch.n_parallel = builder.n_parallel\n    measure_batch.attach_objects = attach_objects\n    return measure_batch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/measure/measure_methods.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-function-args,too-many-nested-blocks\n\"\"\"\nFunctions that run on executor for measurement.\n\nThese functions are responsible for building the tvm module, uploading it to\nremote devices, recording the running time costs, and checking the correctness of the output.\n\"\"\"\n\nimport contextlib\nimport logging\nimport os\nimport shutil\nimport tempfile\nimport threading\nimport time\nimport traceback\nimport typing\nimport warnings\nfrom collections import namedtuple\nfrom random import getrandbits\n\nimport tvm._ffi\nimport tvm.ir.transform\nfrom tvm import nd\nfrom tvm import rpc as _rpc\nfrom tvm.autotvm.env import AutotvmGlobalScope, reset_global_scope\nfrom tvm.contrib import ndk, stackvm, tar\nfrom tvm.contrib.popen_pool import PopenPoolExecutor\nfrom tvm.driver import build\nfrom tvm.error import TVMError\nfrom tvm.target import Target\n\nfrom ..env import AutotvmGlobalScope\nfrom ..task.space import InstantiationError\nfrom ..utils import get_const_tuple\nfrom .measure import Builder, MeasureErrorNo, MeasureResult, Runner\n\nlogger = logging.getLogger(\"autotvm\")\n\n\nclass BuildResult(namedtuple(\"BuildResult\", (\"filename\", \"arg_info\", \"error\", \"time_cost\"))):\n    \"\"\"\n    Stores all the necessary inputs for a measurement.\n\n    Parameters\n    ----------\n    filename : str\n        The filename of generated library\n    arg_info : Tuple\n        The shape and dtype information of tvm tensor arguments\n    error : Exception\n        The error happens during compilation.\n    time_cost : float\n        The time cost of building\n    \"\"\"\n\n\nclass LocalBuilder(Builder):\n    \"\"\"Run compilation on local machine\n\n    Parameters\n    ----------\n    timeout: float\n        The timeout of a compilation\n    n_parallel: int\n        The number of tasks run in parallel. \"None\" will use all cpu cores\n    build_kwargs: dict\n        If supplied, additional kwargs passed to build_func. Overrides any build_kwargs supplied\n        by the Runner.\n    build_func: callable or str\n        If is 'default', use default build function\n        If is 'ndk', use function for android ndk\n        If id 'stackvm', use function for stackvm\n        If is callable, use it as custom build function, expect lib_format field.\n    do_fork: bool\n        If False, do not fork when building. Requires n_parallel=1.\n    runtime: Optional[Runtime]\n        Specify the runtime to generate artifacts for\n    \"\"\"\n\n    def __init__(\n        self,\n        timeout=10,\n        n_parallel=None,\n        build_kwargs=None,\n        build_func=\"default\",\n        do_fork=False,\n        runtime=None,\n    ):\n        super(LocalBuilder, self).__init__(timeout, n_parallel, build_kwargs)\n\n        if isinstance(build_func, str):\n            if build_func == \"default\":\n                build_func = tar.tar\n            elif build_func == \"ndk\":\n                build_func = ndk.create_shared\n            elif build_func == \"stackvm\":\n                build_func = stackvm.build\n            else:\n                raise ValueError(\"Invalid build_func\" + build_func)\n        self.build_func = _WrappedBuildFunc(build_func, runtime)\n        if not do_fork:\n            assert n_parallel in (\n                None,\n                1,\n            ), f\"if do_fork=False, need n_parallel=None or 1; got {n_parallel}\"\n        self.executor = PopenPoolExecutor(\n            timeout=timeout, initializer=reset_global_scope, initargs=(AutotvmGlobalScope.current,)\n        )\n        self.tmp_dir = tempfile.mkdtemp()\n\n    def build(self, measure_inputs):\n        results = []\n\n        shutil.rmtree(self.tmp_dir, ignore_errors=True)\n        self.tmp_dir = tempfile.mkdtemp()\n\n        for i in range(0, len(measure_inputs), self.n_parallel):\n            futures = []\n            for inp in measure_inputs[i : i + self.n_parallel]:\n                ret = self.executor.submit(self.build_func, inp, self.tmp_dir, **self.build_kwargs)\n                futures.append(ret)\n\n            for future in futures:\n                try:\n                    res = future.result()\n                    if res.error is not None:\n                        assert len(res.error) == 2, (\n                            f\"BuildResult errors should be a 2-tuple, but it is a {len(res.error)}\"\n                            \"-tuple. This should not happen!\"\n                        )\n                        tb, exception = res.error\n                        # instantiation error\n                        if isinstance(exception, InstantiationError):\n                            res = MeasureResult(\n                                (\n                                    tb,\n                                    exception,\n                                ),\n                                MeasureErrorNo.INSTANTIATION_ERROR,\n                                res.time_cost,\n                                time.time(),\n                            )\n\n                        else:\n                            if \"InstantiationError\" in str(exception):\n                                msg = str(exception)\n                                try:\n                                    msg = msg.split(\"\\n\")[-2].split(\": \")[1]\n                                except Exception:  # pylint: disable=broad-except\n                                    pass\n                                res = MeasureResult(\n                                    (\n                                        tb,\n                                        InstantiationError(msg),\n                                    ),\n                                    MeasureErrorNo.INSTANTIATION_ERROR,\n                                    res.time_cost,\n                                    time.time(),\n                                )\n\n                            else:  # tvm error\n                                res = MeasureResult(\n                                    (\n                                        tb,\n                                        res.error,\n                                    ),\n                                    MeasureErrorNo.COMPILE_HOST,\n                                    res.time_cost,\n                                    time.time(),\n                                )\n                except TimeoutError as ex:\n                    tb = traceback.format_exc()\n                    res = MeasureResult(\n                        (\n                            tb,\n                            ex,\n                        ),\n                        MeasureErrorNo.BUILD_TIMEOUT,\n                        self.timeout,\n                        time.time(),\n                    )\n                except ChildProcessError as ex:\n                    tb = traceback.format_exc()\n                    res = MeasureResult(\n                        (\n                            tb,\n                            ex,\n                        ),\n                        MeasureErrorNo.RUNTIME_DEVICE,\n                        self.timeout,\n                        time.time(),\n                    )\n\n                results.append(res)\n\n        return results\n\n\nclass RPCRunner(Runner):\n    \"\"\"Run generated code on remove devices.\n    This function will ask a RPC Tracker to get device for measurement.\n\n    Parameters\n    ----------\n    timeout: float\n        The timeout of a RPCRunner measurement task\n    n_parallel: int\n        The number of tasks run in parallel. \"None\" will use all cpu cores\n    key: str\n        The key of the device registered in the tracker\n    host: str\n        The host address of RPC Tracker\n    port: int\n        The port of RPC Tracker\n    number: int\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int, optional\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first \"1\" is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms: int, optional\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval: float, optional\n        The cool down interval between two measurements.\n    enable_cpu_cache_flush: bool\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    module_loader : ModuleLoader\n        If given, a context manager that loads the module to be timed into the remote runtime.\n        If not given, default_module_loader is used.\n    \"\"\"\n\n    def __init__(\n        self,\n        key,\n        host,\n        port,\n        priority=1,\n        timeout=10,\n        n_parallel=None,\n        number=4,\n        repeat=3,\n        min_repeat_ms=0,\n        cooldown_interval=0.1,\n        enable_cpu_cache_flush=False,\n        module_loader=None,\n    ):\n        super(RPCRunner, self).__init__(timeout, n_parallel)\n\n        self.key = key\n        self.host = host\n        self.port = port\n        self.priority = priority\n        self.timeout = timeout\n\n        self.number = number\n        self.repeat = repeat\n        self.min_repeat_ms = min_repeat_ms\n        self._ref_input = None\n\n        self.enable_cpu_cache_flush = enable_cpu_cache_flush\n        self.cooldown_interval = cooldown_interval\n        self.module_loader = module_loader\n\n        self.executor = PopenPoolExecutor(\n            timeout=timeout * (self.n_parallel + 1),\n            initializer=reset_global_scope,\n            initargs=(AutotvmGlobalScope.current,),\n        )\n\n    @property\n    def ref_input(self):\n        \"\"\"\n        Fixed input for tuning special operators, e.g., sparse operators\n        requiring indices as input.\n        \"\"\"\n        return self._ref_input\n\n    @ref_input.setter\n    def ref_input(self, val):\n        if val is not None:\n            warnings.warn(\n                \"You are specifying fixed input for tuning the operator. \"\n                \"Be sure your input always fits the operator. Some \"\n                \"operators may conduct layout transformation during tuning, \"\n                \"thus can lead to unexpected behaviors. \",\n                RuntimeWarning,\n            )\n        self._ref_input = val\n\n    def set_task(self, task):\n        self.task = task\n\n        if check_remote(task.target, self.key, self.host, self.port):\n            logger.info(\"Get devices for measurement successfully!\")\n        else:\n            raise RuntimeError(\n                \"Cannot get remote devices from the tracker. \"\n                \"Please check the status of tracker by \"\n                \"'python -m tvm.exec.query_rpc_tracker --port [THE PORT YOU USE]' \"\n                \"and make sure you have free devices on the queue status.\"\n            )\n\n    def get_build_kwargs(self):\n        kwargs = {}\n        if (\n            \"cuda\" in self.task.target.keys\n            or \"opencl\" in self.task.target.keys\n            or \"rocm\" in self.task.target.keys\n            or \"vulkan\" in self.task.target.keys\n        ):\n            remote = request_remote(self.key, self.host, self.port)\n            dev = remote.device(str(self.task.target), 0)\n            max_dims = dev.max_thread_dimensions\n            kwargs[\"check_gpu\"] = {\n                \"max_shared_memory_per_block\": dev.max_shared_memory_per_block,\n                \"max_threads_per_block\": dev.max_threads_per_block,\n                \"max_thread_x\": max_dims[0],\n                \"max_thread_y\": max_dims[1],\n                \"max_thread_z\": max_dims[2],\n            }\n\n        return kwargs\n\n    def run(self, measure_inputs, build_results):\n        results = []\n        remote_kwargs = dict(\n            device_key=self.key,\n            host=self.host,\n            port=self.port,\n            priority=self.priority,\n            timeout=self.timeout,\n        )\n\n        for i in range(0, len(measure_inputs), self.n_parallel):\n            futures = []\n            for measure_inp, build_res in zip(\n                measure_inputs[i : i + self.n_parallel], build_results[i : i + self.n_parallel]\n            ):\n                module_loader = (\n                    self.module_loader\n                    if self.module_loader is not None\n                    else default_module_loader()\n                )\n                ret = self.executor.submit(\n                    run_through_rpc,\n                    measure_inp,\n                    build_res,\n                    self.number,\n                    self.repeat,\n                    self.min_repeat_ms,\n                    self.cooldown_interval,\n                    remote_kwargs,\n                    self.ref_input,\n                    self.enable_cpu_cache_flush,\n                    module_loader,\n                )\n                futures.append(ret)\n\n            for future in futures:\n                try:\n                    res = future.result()\n                    results.append(res)\n                except Exception as ex:  # pylint: disable=broad-except\n                    tb = traceback.format_exc()\n                    results.append(\n                        MeasureResult(\n                            (\n                                tb,\n                                ex,\n                            ),\n                            MeasureErrorNo.RUN_TIMEOUT,\n                            self.timeout,\n                            time.time(),\n                        )\n                    )\n\n        return results\n\n\nclass LocalRunner(RPCRunner):\n    \"\"\"Run generated code on local devices.\n\n    Parameters\n    ----------\n    timeout: float\n        The timeout of a compilation\n    number: int\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int, optional\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first one is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms: int, optional\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval: float, optional\n        The cool down interval between two measurements.\n    enable_cpu_cache_flush: bool\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    Note\n    ----\n    This is a \"fake\" local mode. We start a silent rpc tracker and rpc server\n    for the user. In this way we reuse timeout/isolation mechanism in RPC infrastructure.\n    \"\"\"\n\n    def __init__(\n        self,\n        timeout=10,\n        number=4,\n        repeat=3,\n        min_repeat_ms=0,\n        cooldown_interval=0.1,\n        enable_cpu_cache_flush=False,\n        module_loader=None,\n    ):\n        super(LocalRunner, self).__init__(\n            \"\",\n            None,\n            None,\n            0,\n            timeout=timeout,\n            n_parallel=1,\n            number=number,\n            repeat=repeat,\n            min_repeat_ms=min_repeat_ms,\n            cooldown_interval=cooldown_interval,\n            enable_cpu_cache_flush=enable_cpu_cache_flush,\n            module_loader=module_loader,\n        )\n        self.tracker = None\n        self.server = None\n\n    def set_task(self, task):\n        # pylint: disable=import-outside-toplevel\n        from ...rpc.server import Server\n        from ...rpc.tracker import Tracker\n\n        self.task = task\n        tracker = Tracker(port=9000, port_end=10000, silent=True)\n        device_key = \"$local$device$%d\" % tracker.port\n        server = Server(\n            port=9000,\n            port_end=10000,\n            key=device_key,\n            silent=True,\n            tracker_addr=(\"127.0.0.1\", tracker.port),\n        )\n        self.key = device_key\n        self.host = \"127.0.0.1\"\n        self.port = tracker.port\n\n        super(LocalRunner, self).set_task(task)\n        return server, tracker\n\n\ndef _build_func_common(measure_input, runtime=None, check_gpu=None, build_option=None):\n    \"\"\"Common part for building a configuration\"\"\"\n    target, task, config = measure_input\n    target, task.target_host = Target.canon_target_and_host(target, task.target_host)\n\n    with target:\n        s, args = task.instantiate(config)\n\n        # check invalidity of template and code hash consistency\n        if not config.valid():\n            raise InstantiationError(config.errors)\n\n        # if target is vta, we need to use vta build\n        if (\n            hasattr(measure_input.target, \"device_name\")\n            and measure_input.target.device_name == \"vta\"\n        ):\n            # pylint: disable=import-outside-toplevel\n            import vta\n\n            func = vta.build(s, args, target_host=task.target_host)\n        else:\n            current_pass_context: tvm.ir.transform.PassContext = (\n                tvm.ir.transform.PassContext.current()\n            )\n            current_config = dict(current_pass_context.config)\n            if build_option is not None:\n                current_config.update(build_option)\n\n            if \"tir.add_lower_pass\" in current_config:\n                current_add_lower_pass = list(current_config[\"tir.add_lower_pass\"])\n            else:\n                current_add_lower_pass = []\n            if check_gpu:\n                current_add_lower_pass.append((2, gpu_verify_pass(**check_gpu)))\n            current_config[\"tir.add_lower_pass\"] = current_add_lower_pass\n\n            with tvm.ir.transform.PassContext(\n                opt_level=current_pass_context.opt_level,\n                required_pass=current_pass_context.required_pass,\n                disabled_pass=current_pass_context.disabled_pass,\n                instruments=current_pass_context.instruments,\n                config=current_config,\n            ):\n                func = build(s, args, target_host=task.target_host, runtime=runtime)\n    return func, tuple((get_const_tuple(x.shape), x.dtype) for x in args)\n\n\nclass _WrappedBuildFunc:\n    \"\"\"\n    Wrap build_func to a function that can be used in measure.\n\n    Note: this is a class instead of a closure so that it can be pickled when\n    using multiprocessing.\n\n    Parameters\n    ----------\n    build_func : The compilation function\n        We expect fcompile to contain an attr \"output_format\".\n    runtime : Optional[Runtime]\n        The runtime to generate artifacts for\n\n    Returns\n    -------\n    wrapped_build_func : callable\n        The wrapped build function\n    \"\"\"\n\n    def __init__(self, build_func, runtime=None):\n        if not hasattr(build_func, \"output_format\"):\n            raise AttributeError(\"Expect build_func to have the attribute output_format.\")\n        self.build_func = build_func\n        self.runtime = runtime\n\n    def __call__(self, measure_input, tmp_dir, **kwargs):\n        \"\"\"\n        Wrapped build func.\n\n        Parameters\n        ----------\n        measure_input: MeasureInput\n            The input of measurement\n\n        tmp_dir: str\n            The path of temporary directory to export generated library\n        \"\"\"\n        tic = time.time()\n        try:\n            filename = os.path.join(\n                tmp_dir, \"tmp_func_%0x.%s\" % (getrandbits(64), self.build_func.output_format)\n            )\n            # TODO(tvm-team) consider linline _build_func_common\n            func, arg_info = _build_func_common(measure_input, self.runtime, **kwargs)\n            if self.build_func.output_format == \".model-library-format\":\n                # Late import to preserve autoTVM with USE_MICRO OFF\n                try:\n                    from tvm import micro  # pylint: disable=import-outside-toplevel\n                except ImportError:\n                    raise ImportError(\"Requires USE_MICRO\")\n                micro.export_model_library_format(func, filename)\n            else:\n                func.export_library(filename, self.build_func)\n        except Exception as e:  # pylint: disable=broad-except\n            tb = traceback.format_exc()\n            return BuildResult(None, None, (tb, e), time.time() - tic)\n        return BuildResult(filename, arg_info, None, time.time() - tic)\n\n\nModuleLoader = typing.Callable[\n    [dict, dict], typing.ContextManager[typing.Tuple[tvm.rpc.RPCSession, tvm.runtime.Module]]\n]\n\n\ndef run_through_rpc(\n    measure_input,\n    build_result,\n    number,\n    repeat,\n    min_repeat_ms,\n    cooldown_interval,\n    remote_kwargs,\n    ref_input,\n    enable_cpu_cache_flush=False,\n    module_loader=None,\n):\n    \"\"\"Run a generated library through rpc\n\n    Parameters\n    ----------\n    measure_input: MeasureInput\n        The raw measure input\n    build_result: BuildResult\n        The result returned from Builder. This contains the path to the generated library.\n    number: int\n        The number of times to run the generated code for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat : int, optional\n        The number of times to repeat the measurement.\n        In total, the generated code will be run (1 + number x repeat) times,\n        where the first one is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms: int, optional\n        The minimum duration of one `repeat` in milliseconds.\n        By default, one `repeat` contains `number` runs. If this parameter is set,\n        the parameters `number` will be dynamically adjusted to meet the\n        minimum duration requirement of one `repeat`.\n        i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n        will be automatically increased.\n    cooldown_interval: float\n        The cool down interval between two measurements\n    remote_kwargs: dict\n        Passed to module_loader(). Ultimately, keyword args to request_remote().\n    ref_input: List of np.ndarray\n        The reference input used for tuning. Empty for randomly filled input.\n    enable_cpu_cache_flush: bool\n        Whether to flush cache on CPU between repeated measurements.\n        Flushing cache can make the measured latency of one operator closer to\n        its actual latency during end-to-end inference.\n        To make this option effective, the argument `number` should also be set to 1.\n        This is only has effect on CPU task.\n    module_loader: ModuleLoader\n        A function that returns a ContextManager used to establish and teardown the remote session.\n    \"\"\"\n    if isinstance(build_result, MeasureResult):\n        return build_result\n\n    tic = time.time()\n    errno = MeasureErrorNo.NO_ERROR\n    try:\n        # upload built module\n        with module_loader(remote_kwargs, build_result) as (remote, mod):\n            dev = remote.device(str(measure_input.target), 0)\n\n            # Limitation:\n            # We can not get PackFunction directly in the remote mode as it is wrapped\n            # under the std::function. We could lift the restriction later once we fold\n            # the PackedFunc as an object. Currently, we pass function name to work\n            # around it.\n            f_prepare = \"cache_flush_cpu_non_first_arg\" if enable_cpu_cache_flush else \"\"\n            time_f = mod.time_evaluator(\n                mod.entry_name,\n                dev,\n                number=number,\n                repeat=repeat,\n                min_repeat_ms=min_repeat_ms,\n                f_preproc=f_prepare,\n            )\n\n            if ref_input:\n                args = [nd.array(x, device=dev) for x in ref_input]\n            else:\n                try:\n                    random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n                except AttributeError:\n                    raise AttributeError(\n                        \"Please make sure USE_RANDOM is ON in the config.cmake \"\n                        \"on the remote devices\"\n                    )\n                args = [nd.empty(x[0], x[1], dev) for x in build_result.arg_info]\n                if \"scatter\" not in measure_input.task.name:\n                    # the index tensor of scatter op cannot be randomly initialized\n                    for arg in args:\n                        random_fill(arg)\n                dev.sync()\n\n            costs = time_f(*args).results\n\n        if len(costs) > 2:  # remove largest and smallest value to reduce variance\n            costs = list(costs)\n            costs.sort()\n            costs = tuple(costs[1:-1])\n    except TVMError as exc:\n        msg = str(exc)\n        if \"Stack trace returned\" in msg:\n            msg = msg[: msg.index(\"Stack trace returned\")]\n        if \"CUDA Source\" in msg:\n            msg = msg[: msg.index(\"CUDA Source\")]\n        costs = (\n            traceback.format_exc(),\n            RuntimeError(msg[:1024]),\n        )\n        errno = MeasureErrorNo.RUNTIME_DEVICE\n    tstamp = time.time()\n    time.sleep(cooldown_interval)\n    return MeasureResult(costs, errno, tstamp - tic + build_result.time_cost, tstamp)\n\n\nclass DefaultModuleLoader:\n    \"\"\"See default_module_loader(). A pickleable emulation of the original function closure.\"\"\"\n\n    def __init__(self, pre_load_function=None) -> None:\n        self.pre_load_function = pre_load_function\n\n    @contextlib.contextmanager\n    def __call__(self, remote_kwargs, build_result):\n        remote = request_remote(**remote_kwargs)\n        if self.pre_load_function is not None:\n            self.pre_load_function(remote, build_result)\n\n        remote.upload(build_result.filename)\n        try:\n            yield remote, remote.load_module(os.path.split(build_result.filename)[1])\n\n        finally:\n            # clean up remote files\n            remote.remove(build_result.filename)\n            remote.remove(os.path.splitext(build_result.filename)[0] + \".so\")\n            remote.remove(\"\")\n\n\ndef default_module_loader(pre_load_function=None):\n    \"\"\"Returns a default function that can be passed as module_loader to run_through_rpc.\n\n    Parameters\n    ----------\n    pre_load_function : Optional[Function[tvm.rpc.Session, tvm.runtime.Module]]\n        Invoked after a session is established and before the default code-loading RPC calls are\n        issued. Allows performing pre-upload actions, e.g. resetting the remote runtime environment.\n\n    Returns\n    -------\n    DefaultModuleLoader :\n        A callable that can be passed as module_loader to run_through_rpc.\n    \"\"\"\n\n    # This was a function with a closure before but that couldn't be pickled!\n    # We need pickle to work for using python's multiprocessing on some platforms.\n    return DefaultModuleLoader(pre_load_function)\n\n\ndef request_remote(device_key, host=None, port=None, priority=1, timeout=60):\n    \"\"\"Request a remote session\n\n    Parameters\n    ----------\n    device_key: string\n        The device key of registered device in tracker\n    host: host, optional\n        The host address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_HOST\"\n    port: int, optional\n        The port of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_PORT\"\n    priority: int, optional\n        The priority of this request, larger is more prior\n    timeout: float, optional\n        The timeout of this session (units: second)\n\n    Returns\n    ------\n    session: RPCSession\n    \"\"\"\n    # connect to the tracker\n    host = host or os.environ[\"TVM_TRACKER_HOST\"]\n    port = port or int(os.environ[\"TVM_TRACKER_PORT\"])\n\n    tracker = _rpc.connect_tracker(host, port)\n    remote = tracker.request(device_key, priority=priority, session_timeout=timeout)\n    return remote\n\n\ndef check_remote(target, device_key, host=None, port=None, priority=100, timeout=10):\n    \"\"\"\n    Check the availability of a remote device\n\n    Parameters\n    ----------\n    target: Target\n        The wanted compilation target\n    device_key: string\n        device key of registered device in tracker\n    host: host, optional\n        The host address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_HOST\"\n    port: int, optional\n        The port address of rpc tracker.\n        If is none, will use environment variable \"TVM_TRACKER_PORT\"\n    priority: int, optional\n        The priority of this request, larger is more prior\n    timeout: float, optional\n        The timeout of this check (units: seconds).\n\n    Returns\n    -------\n    available: bool\n        True if can find available device\n    \"\"\"\n\n    def _check():\n        logger.debug(\"waiting for device...\")\n        remote = request_remote(device_key, host, port, priority)\n        dev = remote.device(str(target))\n        while not dev.exist:  # wait until we get an available device\n            pass\n        logger.debug(\"device available\")\n\n    t = threading.Thread(\n        target=_check,\n    )\n    t.start()\n    t.join(timeout)\n\n    remote = request_remote(device_key, host, port, priority)\n    dev = remote.device(str(target))\n    return dev.exist\n\n\ndef set_cuda_target_arch(arch):\n    \"\"\"THIS API IS DEPRECATED.\n\n    set target architecture of nvcc compiler\n\n    Parameters\n    ----------\n    arch: str or list\n        The argument of nvcc -arch. (e.g. \"sm_51\", \"sm_62\")\n        it can also be a count of gencode arguments pass to nvcc command line,\n        e.g., [\"-gencode\", \"arch=compute_52,code=sm_52\", \"-gencode\", \"arch=compute_70,code=sm_70\"]\n    \"\"\"\n    raise ValueError(\n        \"The API 'autotvm.measure.set_cuda_target_arch' is deprecated.\"\n        \"Try specifying it by adding '-arch=sm_xx' to your target, such as 'cuda -arch=sm_86'.\"\n        \"See https://github.com/apache/tvm/pull/9544 for the upgrade guide.\"\n    )\n\n\ndef gpu_verify_pass(**kwargs):\n    \"\"\"Verify the validity of a gpu kernel.\n    This pass will check memory usage and number of threads per block.\n    \"\"\"\n\n    def verify_pass(f, *_):\n        valid = tvm.tir.analysis.verify_gpu_code(f, kwargs)\n        if not valid:\n            raise InstantiationError(\"Skipped because of invalid gpu kernel\")\n        return f\n\n    return tvm.tir.transform.prim_func_pass(verify_pass, opt_level=0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/record.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=superfluous-parens, redefined-outer-name, redefined-outer-name,pointless-string-statement\n# pylint: disable=consider-using-enumerate,invalid-name\n\"\"\"Tuning record and serialization format\"\"\"\n\nimport argparse\nimport base64\nfrom io import TextIOBase\nimport logging\nimport pickle\nimport json\nimport time\nfrom typing import Union\nimport os\nimport itertools\nfrom collections import OrderedDict\nimport numpy as np\n\nfrom .. import build, lower\nfrom ..target import Target\nfrom ..contrib import popen_pool\nfrom .. import __version__\nfrom . import task\nfrom .task import ConfigEntity, ApplyHistoryBest\nfrom .measure import MeasureInput, MeasureResult\n\nAUTOTVM_LOG_VERSION = 0.2\n_old_version_warning = True\nlogger = logging.getLogger(\"autotvm\")\n\ntry:  # convert unicode to str for python2\n    _unicode = unicode\nexcept NameError:\n    _unicode = ()\n\ntry:\n    _long = long\nexcept NameError:\n    _long = int\n\n\ndef measure_str_key(inp, include_config=True):\n    \"\"\"get unique str key for MeasureInput\n\n    Parameters\n    ----------\n    inp: autotvm.measure.MeasureInput\n        input for the measure\n    include_config: bool, optional\n        whether includes config in the str key\n\n    Returns\n    -------\n    key: str\n        The str representation of key\n    \"\"\"\n    config_str = str(inp.config) if include_config else \"\"\n    return \"\".join(\n        [str(inp.target), inp.task.name, str(inp.task.args), str(inp.task.kwargs), config_str]\n    )\n\n\ndef encode(inp, result, protocol=\"json\"):\n    \"\"\"encode (MeasureInput, MeasureResult) pair to a string\n\n    Parameters\n    ----------\n    inp: autotvm.measure.MeasureInput\n    result: autotvm.measure.MeasureResult\n        pair of input/result\n    protocol: str\n        log protocol, json or pickle\n\n    Returns\n    -------\n    row: str\n        a row in the logger file\n    \"\"\"\n\n    if protocol == \"json\":\n        json_dict = {\n            \"input\": (str(inp.target), inp.task.name, inp.task.args, inp.task.kwargs),\n            \"config\": inp.config.to_json_dict(),\n            \"result\": (\n                result.costs if result.error_no == 0 else (1e9,),\n                result.error_no,\n                result.all_cost,\n                result.timestamp,\n            ),\n            \"version\": AUTOTVM_LOG_VERSION,\n            \"tvm_version\": __version__,\n        }\n        return json.dumps(json_dict)\n    if protocol == \"pickle\":\n        row = (\n            str(inp.target),\n            str(\n                base64.b64encode(\n                    pickle.dumps([inp.task.name, inp.task.args, inp.task.kwargs])\n                ).decode()\n            ),\n            str(base64.b64encode(pickle.dumps(inp.config)).decode()),\n            str(base64.b64encode(pickle.dumps(tuple(result))).decode()),\n            str(AUTOTVM_LOG_VERSION),\n            str(__version__),\n        )\n        return \"\\t\".join(row)\n\n    raise RuntimeError(\"Invalid log protocol: \" + protocol)\n\n\ndef decode(row, protocol=\"json\"):\n    \"\"\"Decode encoded record string to python object\n\n    Parameters\n    ----------\n    row : str\n        a row in the logger file\n\n    protocol : str\n        log protocol, json or pickle\n\n    Returns\n    -------\n    ret : tuple(autotvm.measure.MeasureInput, autotvm.measure.MeasureResult), or None\n        The tuple of input and result, or None if input uses old version log format.\n    \"\"\"\n    # pylint: disable=unused-variable\n    global _old_version_warning\n\n    if protocol == \"json\":\n        row = json.loads(row)\n        if \"v\" in row and row[\"v\"] == 0.1:\n            if _old_version_warning:\n                logger.warning(\"AutoTVM log version 0.1 is no longer supported.\")\n                _old_version_warning = False\n            return None\n\n        tgt, task_name, task_args, task_kwargs = row[\"input\"]\n        tgt = str(tgt)\n        if \"-target\" in tgt:\n            logger.warning('\"-target\" is deprecated, use \"-mtriple\" instead.')\n            tgt = tgt.replace(\"-target\", \"-mtriple\")\n        tgt = Target(str(tgt))\n\n        def clean_json_to_python(x):\n            \"\"\"1. Convert all list in x to tuple (hashable)\n            2. Convert unicode to str for python2\n            \"\"\"\n            if isinstance(x, list):\n                return tuple([clean_json_to_python(a) for a in x])\n            if isinstance(x, _unicode):\n                return str(x)\n            if isinstance(x, (_long, int)):\n                return int(x)\n            return x\n\n        tsk = task.Task(clean_json_to_python(task_name), clean_json_to_python(task_args))\n        config = ConfigEntity.from_json_dict(row[\"config\"])\n        inp = MeasureInput(tgt, tsk, config)\n        result = MeasureResult(*[tuple(x) if isinstance(x, list) else x for x in row[\"result\"]])\n        config.cost = np.mean(result.costs)\n\n        return inp, result\n    if protocol == \"pickle\":\n        items = row.split(\"\\t\")\n        if len(items) == 4:\n            if _old_version_warning:\n                logger.warning(\"AutoTVM log version 0.1 is no longer supported.\")\n                _old_version_warning = False\n            return None\n        tgt = Target(items[0])\n        task_tuple = pickle.loads(base64.b64decode(items[1].encode()))\n        config = pickle.loads(base64.b64decode(items[2].encode()))\n        result = MeasureResult(*pickle.loads(base64.b64decode(items[3].encode())))\n        config.cost = np.mean(result.costs)\n\n        tsk = task.Task(task_tuple[0], task_tuple[1])\n        return MeasureInput(tgt, tsk, config), result\n\n    raise RuntimeError(\"Invalid log protocol: \" + protocol)\n\n\ndef load_from_buffer(file: TextIOBase):\n    \"\"\"Generator: load records from buffer.\n    This is a generator that yields the records.\n\n    Parameters\n    ----------\n    file: io.TextIOBase\n\n    Yields\n    ------\n    input: autotvm.measure.MeasureInput\n    result: autotvm.measure.MeasureResult\n    \"\"\"\n    for row in file:\n        if row and not row.startswith(\"#\"):\n            ret = decode(row)\n            if ret is None:\n                continue\n            yield ret\n\n\ndef load_from_file(filepath: Union[str, bytes, os.PathLike]):\n    \"\"\"Generator: load records from path.\n    This is a generator that yields the records.\n\n    Parameters\n    ----------\n    filepath: str, bytes, or os.PathLike\n\n    Yields\n    ------\n    input: autotvm.measure.MeasureInput\n    result: autotvm.measure.MeasureResult\n    \"\"\"\n    with open(filepath) as f:\n        for row in f:\n            if row and not row.startswith(\"#\"):\n                ret = decode(row)\n                if ret is None:\n                    continue\n                yield ret\n\n\ndef split_workload(in_file, clean=True):\n    \"\"\"Split a log file into separate files, each of which contains only a single workload\n    This function can also delete duplicated records in log file\n\n    Parameters\n    ----------\n    in_file: str\n        input filename\n    clean: bool\n        whether delete duplicated items\n    \"\"\"\n    tic = time.time()\n    lines = list(open(in_file).readlines())\n\n    logger.info(\"start converting...\")\n    pool = popen_pool.PopenPoolExecutor()\n    lines = [rec for rec in pool.map(decode, lines) if rec is not None]\n    logger.info(\"map done %.2f\", time.time() - tic)\n\n    wkl_dict = OrderedDict()\n    for inp, res in lines:\n        wkl = measure_str_key(inp, False)\n        if wkl not in wkl_dict:\n            wkl_dict[wkl] = []\n        wkl_dict[wkl].append([inp, res])\n\n    if clean:\n        for i, (k, v) in enumerate(wkl_dict.items()):\n            # clean duplicated items\n            added = set()\n            cleaned = []\n            for inp, res in v:\n                str_key = measure_str_key(inp)\n                if str_key in added:\n                    continue\n                added.add(str_key)\n                cleaned.append([inp, res])\n\n            # write to file\n            logger.info(\"Key: %s\\tValid: %d\\tDup: %d\\t\", k, len(cleaned), len(v) - len(cleaned))\n            with open(args.i + \".%03d.wkl\" % i, \"w\") as fout:\n                for inp, res in cleaned:\n                    fout.write(encode(inp, res) + \"\\n\")\n    else:\n        for i, (k, v) in enumerate(wkl_dict.items()):\n            logger.info(\"Key: %s\\tNum: %d\", k, len(v))\n            with open(args.i + \".%03d.wkl\" % i, \"w\") as fout:\n                for inp, res in v:\n                    fout.write(encode(inp, res) + \"\\n\")\n\n\ndef pick_best(in_file, out_file):\n    \"\"\"\n    Pick the best entries from a file and store them to another file.\n    This function distills the useful log entries from a large log file.\n    If out_file already exists, the best entries from both\n    in_file and out_file will be saved.\n\n    Parameters\n    ----------\n    in_file: str\n        The filename of input\n    out_file: str or file\n        The filename of output\n    \"\"\"\n    context = load_from_file(in_file)\n    if os.path.isfile(out_file):\n        out_context = load_from_file(out_file)\n        context = itertools.chain(context, out_context)\n    context, context_clone = itertools.tee(context)\n    best_context = ApplyHistoryBest(context)\n    best_set = set()\n\n    for v in best_context.best_by_model.values():\n        best_set.add(measure_str_key(v[0]))\n\n    for v in best_context.best_by_targetkey.values():\n        best_set.add(measure_str_key(v[0]))\n\n    logger.info(\"Extract %d best records from the %s\", len(best_set), in_file)\n    fout = open(out_file, \"w\") if isinstance(out_file, str) else out_file\n\n    for inp, res in context_clone:\n        if measure_str_key(inp) in best_set:\n            fout.write(encode(inp, res) + \"\\n\")\n            best_set.remove(measure_str_key(inp))\n\n\n\"\"\"\nUsage:\nThis record executable module has three modes.\n\n* Print log file in readable format\ne.g. python -m tvm.autotvm.record --mode read --i collect_conv.log --begin 0 --end 5 --ir --code\n\n* Extract history best from a large log file\ne.g. python -m tvm.autotvm.record --mode pick --i collect.log\n\n* Split a log file into separate files, each of which contains only a single wkl\ne.g. python -m tvm.autotvm.record --mode split --i collect.log\n\"\"\"\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--mode\", choices=[\"read\", \"pick\", \"split\"], default=\"read\")\n    parser.add_argument(\"--i\", type=str, help=\"input file\")\n    parser.add_argument(\"--o\", type=str, default=None, help=\"output file\")\n    parser.add_argument(\"--begin\", type=int, default=0)\n    parser.add_argument(\"--end\", type=int, default=5)\n    parser.add_argument(\"--ir\", action=\"store_true\")\n    parser.add_argument(\"--code\", action=\"store_true\")\n\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n\n    if args.mode == \"pick\":\n        args.o = args.o or args.i + \".best.log\"\n        pick_best(args.i, args.o)\n    elif args.mode == \"read\":\n        for i, (inp, result) in enumerate(load_from_file(args.i)):\n            if args.begin <= i < args.end:\n                with inp.target:\n                    s, arg_bufs = inp.task.instantiate(inp.config)\n\n                print(\"\")\n                print(inp.target, inp.task, inp.config)\n                print(result)\n\n                if args.ir:\n                    with inp.target:\n                        print(lower(s, arg_bufs, simple_mode=True))\n\n                if args.code:\n                    with inp.target:\n                        func = build(s, arg_bufs)\n                        print(func.imported_modules[0].get_source())\n    elif args.mode == \"split\":\n        split_workload(args.i)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Task is a tunable composition of template functions.\n\nTuner takes a tunable task and optimizes the joint configuration\nspace of all the template functions in the task.\nThis module defines the task data structure, as well as a collection(zoo)\nof typical tasks of interest.\n\"\"\"\n\nfrom .task import (\n    Task,\n    create,\n    get_config,\n    args_to_workload,\n    template,\n    serialize_args,\n    deserialize_args,\n)\nfrom .space import ConfigSpace, ConfigEntity\nfrom .code_hash import attach_code_hash, attach_code_hash_to_arg\nfrom .dispatcher import (\n    DispatchContext,\n    ApplyConfig,\n    ApplyFixedConfig,\n    ApplyHistoryBest,\n    FallbackContext,\n    clear_fallback_cache,\n    ApplyGraphBest,\n)\n\nfrom .topi_integration import (\n    register_topi_compute,\n    register_topi_schedule,\n    TaskExtractEnv,\n    get_workload,\n)\nfrom .relay_integration import extract_from_program, extract_from_multiple_program\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/code_hash.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDecorator functions for hashing schedule code\n\ncode hashing is used to check the consistence of schedule code and the parameters loaded from log\n\"\"\"\nimport functools\nimport inspect\nimport zlib\n\nfrom tvm.te import schedule\n\n\ndef attach_code_hash(s):\n    \"\"\"Decorator for attaching a code hash to a schedule\n\n    Parameters\n    ----------\n    s: Schedule\n        tvm.te.schedule.Schedule to attach the hash to\n    \"\"\"\n\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            func(*args, **kwargs)\n            raw_hash = zlib.crc32(\"\".join(inspect.getsourcelines(func)[0]).encode())\n            s.code_hash = hex(raw_hash)[2:]\n\n        return wrapper\n\n    return decorator\n\n\ndef attach_code_hash_to_arg(arg_idx=1):\n    \"\"\"Decorator for attaching a code hash to a schedule\n\n    Parameters\n    ----------\n    arg_idx: int\n        index of the argument (expected to be a Schedule) to attach the code\n        hash to\n    \"\"\"\n\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            func(*args, **kwargs)\n            assert isinstance(args[arg_idx], schedule.Schedule)\n            raw_hash = zlib.crc32(\"\".join(inspect.getsourcelines(func)[0]).encode())\n            args[arg_idx].code_hash = hex(raw_hash)[2:]\n\n        return wrapper\n\n    return decorator\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/dispatcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTemplate dispatcher module.\n\nA dispatcher is a function that can contains multiple behaviors.\nIts specific behavior is can be controlled by DispatchContext.\n\nDispatchContext is used in two ways, usually via different implementation\nof the DispatchContext base class.\n\n- During search, we can use it to pass the current proposal from tuner.\n- During evaluation, we can use it to set pick the best policy.\n\"\"\"\n# pylint: disable=invalid-name\n\nfrom __future__ import absolute_import as _abs\n\nfrom io import TextIOBase\nimport logging\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import List, Iterable, Tuple, Union\n\nimport numpy as np\n\nfrom .space import FallbackConfigEntity\nfrom .. import env as _env\nfrom ..measure import MeasureInput, MeasureResult\n\nlogger = logging.getLogger(\"autotvm\")\n\nRecords = Union[\n    Union[str, bytes, Path],  # Path-like objects\n    TextIOBase,  # File-like objects\n    Iterable[Tuple[MeasureInput, MeasureResult]],\n]\n\n\nclass DispatchContext(object):\n    \"\"\"\n    Base class of dispatch context.\n\n    DispatchContext enables the target and workload\n    specific dispatch mechanism for templates.\n    \"\"\"\n\n    current = None\n    # a set to prevent print duplicated message\n    warning_messages = set()\n\n    def __init__(self):\n        self._old_ctx = DispatchContext.current\n\n    def query(self, target, workload):\n        \"\"\"\n        Query the context to get the specific config for a template.\n        If cannot find the result inside this context, this function will query it\n        from the upper contexts.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload : Workload\n            The current workload.\n\n        Returns\n        -------\n        cfg : ConfigSpace\n            The specific configuration.\n        \"\"\"\n        ret = self._query_inside(target, workload)\n        if ret is None:\n            ret = self._old_ctx.query(target, workload)\n        return ret\n\n    def update(self, target, workload, cfg):\n        \"\"\"\n        Update context with a specific config.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload : Workload\n            The current workload.\n        cfg : ConfigSpace\n            The specific configuration.\n\n        Note\n        ----\n        This interface is for cases when TVM decides to replace an operator in the graph.\n        For example, `AlterOpLayout` pass (enables when `opt_level = 3`) replaces `NCHW`\n        convolution with `NCHW[x]c` implementation on x86 CPUs.\n        Thus in TOPI, we first query schedule using original `NCHW` workload,\n        then update the dispatcher with the new `NCHW[x]c` workload.\n        So that later on, `NCHW[x]c` convolution can get schedule from the dispatcher using\n        its own workload directly.\n\n        .. code-block:: python\n\n            @conv2d_alter_layout.register(\"cpu\")\n            def _alter_conv2d_layout(attrs, inputs, tinfo):\n                workload = get_conv2d_workload(...)\n                dispatch_ctx = autotvm.task.DispatchContext.current\n                target = tvm.target.Target.current()\n                config = dispatch_ctx.query(target, workload)\n\n                # Get conv2d_NCHWc workload from config\n                # new_workload = ...\n                # new_inputs = ...\n                # new_attrs = ...\n\n                # Store altered operator's config\n                dispatch_ctx.update(target, new_workload, config)\n                return sym.contrib.conv2d_NCHWc(*new_inputs, **new_attrs)\n\n        We directly store `config` back because `conv2d_NCHW` and `conv2d_NCHWc`\n        share the same schedule parameters.\n        One can construct a new `ConfigEntity` if this is not the case.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _query_inside(self, target, workload):\n        \"\"\"\n        Query the context to get the specific config for a template.\n        This function only query config inside this context.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload : Workload\n            The current workload.\n\n        Returns\n        -------\n        cfg : ConfigSpace\n            The specific configuration.\n        \"\"\"\n        raise NotImplementedError()\n\n    def __enter__(self):\n        self._old_ctx = DispatchContext.current\n        DispatchContext.current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        DispatchContext.current = self._old_ctx\n\n\nclass ApplyConfig(DispatchContext):\n    \"\"\"Apply a deterministic config entity for all queries.\n\n    Parameters\n    ----------\n    config : ConfigSpace or ConfigEntity\n        The specific configuration we care about.\n    \"\"\"\n\n    def __init__(self, config):\n        super(ApplyConfig, self).__init__()\n        self._config = config\n        self.workload = None\n\n    def _query_inside(self, target, workload):\n        \"\"\"Override query\"\"\"\n        self.workload = workload\n        return self._config\n\n    def update(self, target, workload, cfg):\n        \"\"\"Override update\"\"\"\n        self.workload = workload\n        self._config = cfg\n\n\nclass ApplyFixedConfig(DispatchContext):\n    \"\"\"Apply a config of a deterministic schedule.\n    This is used for building a single Relay operator with deterministic schedule\n    for testing schedules at Relay level.\n\n    Parameters\n    ----------\n    tasks : list[tvm.autotvm.task.task.Task]\n        List of autoTVM tasks.\n    schedule_names : str, List[str]\n        Name of schedules to use.\n    \"\"\"\n\n    def __init__(self, tasks, schedule_names: Union[str, List[str]]):\n        super(ApplyFixedConfig, self).__init__()\n        if isinstance(schedule_names, str):\n            self._schedule_names = list(schedule_names)\n        elif isinstance(schedule_names, list):\n            self._schedule_names = schedule_names\n        else:\n            raise RuntimeError(\"Incorrect type: \" + schedule_names)\n        self._tasks = tasks\n        self.workload = None\n\n    def _query_inside(self, target, workload):\n        \"\"\"Override query\"\"\"\n        self.workload = workload\n\n        # Create a config from correct task\n        for task in self._tasks:\n            if task.name == workload[0]:\n                config = task.config_space.get(0)\n                break\n\n        if not config:\n            raise RuntimeError(\n                \"workload: %s does not exist in %s\" % (str(workload), str(self._tasks))\n            )\n        # Add low cost to the target schedule and high cost to others.\n        if workload[0] in self._schedule_names:\n            config.cost = 1e-6\n        else:\n            config.cost = 100000\n        return config\n\n    def update(self, target, workload, cfg):\n        \"\"\"Override update\"\"\"\n        self.workload = workload\n        self._config = cfg\n\n\nclass ApplyHistoryBest(DispatchContext):\n    \"\"\"\n    Apply the history best config\n\n    Parameters\n    ----------\n    records : None, Records, or iterator of Records objects, where a\n              Records object is a path-like object, a file-like object,\n              or an iterator of (MeasureInput, MeasureResult).\n\n        Collection of tuning records. If multiple Records objects are passed, their\n        contents will be merged.\n    \"\"\"\n\n    def __init__(self, records: Union[None, Records, Iterable[Records]]):\n        super(ApplyHistoryBest, self).__init__()\n\n        self.best_by_targetkey = {}\n        self.best_by_model = {}\n        self._best_user_defined = {}\n\n        if records:\n            self.load(records)\n\n    def load(self, records: Union[Records, Iterable[Records]]):\n        \"\"\"Load records to this dispatch context\n\n        Parameters\n        ----------\n        records : str, list of str, or iterator of (autotvm.measure.MeasureInput,\\\n                                                    autotvm.measure.MeasureResult)\n\n            Collection of tuning records. If multiple Records objects are passed, their\n            contents will be merged.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from ..record import load_from_file, load_from_buffer\n\n        def _unpack_records(\n            records: Union[Records, Iterable[Records]]\n        ) -> List[Tuple[MeasureInput, MeasureResult]]:\n\n            if isinstance(records, (str, bytes, PathLike)):\n                return load_from_file(records)\n\n            if isinstance(records, TextIOBase):\n                return load_from_buffer(records)\n\n            joint_records = []\n            for record in records:\n                if isinstance(record, Tuple) and isinstance(record[0], MeasureInput):\n                    joint_records.append(record)\n                else:\n                    joint_records += _unpack_records(record)\n\n            return joint_records\n\n        flattened_records = _unpack_records(records)\n        if not flattened_records:\n            return\n\n        best_by_targetkey = self.best_by_targetkey\n        best_by_model = self.best_by_model\n\n        counter = 0\n        for inp, res in flattened_records:\n            counter += 1\n            if res.error_no != 0:\n                continue\n\n            # use target keys in tvm target system as key to build best map\n            for k in inp.target.keys:\n                key = (k, inp.task.workload)\n                if key not in best_by_targetkey:\n                    best_by_targetkey[key] = (inp, res)\n                else:\n                    _, other_res = best_by_targetkey[key]\n                    if np.mean(other_res.costs) > np.mean(res.costs):\n                        best_by_targetkey[key] = (inp, res)\n\n            # use model as key to build best map\n            key = (inp.target.model, inp.task.workload)\n            if key not in best_by_model:\n                if inp.target.model != \"unknown\":\n                    best_by_model[key] = (inp, res)\n            else:\n                _, other_res = best_by_model[key]\n                if np.mean(other_res.costs) > np.mean(res.costs):\n                    best_by_model[key] = (inp, res)\n\n        logger.debug(\"Finish loading %d records\", counter)\n\n    def _query_inside(self, target, workload):\n        if target is None:\n            raise RuntimeError(\n                \"Need a target context to find the history best. \"\n                \"Hint: If your target is llvm, use `with tvm.target.Target('llvm'):`\"\n                \" above the dispatcher call. So does other target. \"\n            )\n\n        # first try matching by model\n        key = (target.model, workload)\n        if key in self._best_user_defined:\n            return self._best_user_defined[key]\n        if key in self.best_by_model:\n            inp, _ = self.best_by_model[key]\n            return inp.config\n\n        # then try matching by target key\n        for k in target.keys:\n            key = (k, workload)\n            if key in self._best_user_defined:\n                return self._best_user_defined[key]\n            if key in self.best_by_targetkey:\n                inp, _ = self.best_by_targetkey[key]\n                return inp.config\n\n        return None\n\n    def update(self, target, workload, cfg):\n        model = target.model\n        key = (model, workload)\n        # assume user provided config is the best\n        cfg.cost = 0\n        self._best_user_defined[key] = cfg\n\n        for k in target.keys:\n            key = (k, workload)\n            self._best_user_defined[key] = cfg\n\n\nclass FallbackContext(DispatchContext):\n    \"\"\"\n    A fallback dispatch context.\n\n    Any tunable template can be called under this context.\n    This is the root context.\n    \"\"\"\n\n    def __init__(self):\n        super(FallbackContext, self).__init__()\n        self.memory = {}\n\n    def _query_inside(self, target, workload):\n        key = (str(target), workload)\n        if key in self.memory:\n            return self.memory[key]\n\n        if not _env.GLOBAL_SCOPE.silent:\n            msg = (\n                \"Cannot find config for target=%s, workload=%s. A fallback configuration \"\n                \"is used, which may bring great performance regression.\" % (target, workload)\n            )\n            if msg not in DispatchContext.warning_messages:\n                DispatchContext.warning_messages.add(msg)\n                logger.warning(msg)\n        cfg = FallbackConfigEntity()\n\n        # cache this config\n        self.memory[key] = cfg\n        return cfg\n\n    def clear_cache(self, target, workload):\n        \"\"\"Clear fallback cache. Pass the same argument as _query_inside to this function\n        to clean the cache.\n\n        Parameters\n        ----------\n        target: Target\n            The current target\n        workload : Workload\n            The current workload.\n        \"\"\"\n        key = (str(target), workload)\n        if key in self.memory:\n            del self.memory[key]\n\n    def update(self, target, workload, cfg):\n        key = (str(target), workload)\n        self.memory[key] = cfg\n\n\nDispatchContext.current = FallbackContext()\n\n\ndef clear_fallback_cache(target, workload):\n    \"\"\"Clear fallback cache. Pass the same argument as _query_inside to this function\n    to clean the cache.\n\n    Parameters\n    ----------\n    target: Target\n        The current target\n    workload : Workload\n        The current workload.\n\n    Note\n    ----\n    This is used in alter_op_layout to clear the bad cache created before call topi compute function\n    \"\"\"\n    context = DispatchContext.current\n    while not isinstance(context, FallbackContext):\n        context = context._old_ctx\n    context.clear_cache(target, workload)\n\n\nclass ApplyGraphBest(DispatchContext):\n    \"\"\"Load the graph level tuning optimal schedules.\n\n    The input records should be in the ascending order of\n    node index for target operator. Usually this can be obtained\n    with graph tuner.\n\n    This context maintains an internal counter to indicate the current\n    node index.\n    \"\"\"\n\n    def __init__(self, records: Records):\n        \"\"\"\n        Parameters\n        ----------\n        records : str or iterator of (autotvm.measure.MeasureInput, autotvm.measure.MeasureResult)\n            Collection of tuning records.\n            If is str, then it should be the filename of a records log file.\n                   Each row of this file is an encoded record pair.\n            Otherwise, it is an iterator.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from ..record import load_from_file, load_from_buffer\n\n        super(ApplyGraphBest, self).__init__()\n        if isinstance(records, (str, bytes, PathLike)):\n            records = load_from_file(records)\n        elif isinstance(records, TextIOBase):\n            records = load_from_buffer(records)\n        else:\n            records = list(records)\n\n        self._records = list(records)\n        self._counter = 0\n        self._global_cfg_dict = {}\n\n    def _query_inside(self, target, workload):\n        \"\"\"\n        Query the context to get config from records.\n\n        Parameters\n        ----------\n        target : Target\n            The current target\n        workload : Workload\n            The current workload.\n\n        Returns\n        -------\n        cfg : ConfigSpace\n            The specific configuration.\n        \"\"\"\n        if self._counter < len(self._records):\n            cfg = self._records[self._counter][0].config\n            wkl = self._records[self._counter][0].task.workload\n            if workload is not None:\n                assert wkl == workload\n            self._counter += 1\n            self.update(target, wkl, cfg)\n            cfg.workload = wkl\n            return cfg\n        key = (str(target), workload)\n        if key not in self._global_cfg_dict:\n            msg = (\n                \"Config for target=%s, workload=%s is missing in ApplyGraphBest context. \"\n                \"A fallback configuration is used, which may bring great performance \"\n                \"regression.\" % (target, workload)\n            )\n            logger.warning(msg)\n            cfg = FallbackConfigEntity()\n            self._global_cfg_dict[key] = cfg\n        else:\n            cfg = self._global_cfg_dict[key]\n        return cfg\n\n    def update(self, target, workload, cfg):\n        key = (str(target), workload)\n        self._global_cfg_dict[key] = cfg\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/relay_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable,invalid-name, not-context-manager\n\"\"\"\nDecorator and utilities for the integration with TOPI and Relay\n99.9% copy-paste of implementation by @MerryMercy\n\n\"\"\"\nimport threading\nimport logging\n\nimport tvm\nfrom tvm.autotvm.task.dispatcher import DispatchContext, FallbackContext\nfrom tvm.target import Target\nfrom .task import create\nfrom .topi_integration import TaskExtractEnv\n\nlogger = logging.getLogger(\"autotvm\")\n\n\n# TODO(moreau89) find a more elegant way to lower for VTAs\ndef _lower(mod, target, params, opt_level=3):\n    \"\"\"Helper to lower VTA properly.\"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n    from tvm.relay.backend import graph_executor_codegen\n\n    if hasattr(target, \"device_name\") and target.device_name == \"vta\":\n        import vta\n\n        with vta.build_config(opt_level=opt_level, disabled_pass={\"AlterOpLayout\"}):\n            mod, _ = relay.optimize(mod, target=target, params=params)\n            grc = graph_executor_codegen.GraphExecutorCodegen(None, target)\n            grc.codegen(mod, mod[\"main\"])\n            return\n\n    # Alter op layout code has been written expecting that tuning is applied\n    # without it, so we disable AlterOpLayout to maintain that behavior.\n    with tvm.transform.PassContext(opt_level=opt_level, disabled_pass={\"AlterOpLayout\"}):\n        compiler = relay.vm.VMCompiler()\n        if params:\n            compiler.set_params(params)\n        compiler.lower(mod, target=target)\n\n\ndef extract_from_program(mod, params, target, target_host=None, ops=None):\n    \"\"\"Extract tuning tasks from a relay program.\n\n    This function is the single program version of extract_from_multiple_program.\n\n    Parameters\n    ----------\n    mod: tvm.IRModule or relay.function.Function\n        The module or function to tune\n    params: dict of str to numpy array\n        The associated parameters of the program\n    target: tvm.target.Target\n        The compilation target\n    target_host: tvm.target.Target\n        The host compilation target\n    ops: List[tvm.ir.Op] or None\n        List of relay ops to be tuned. If not specified, all tunable ops will be extracted.\n\n    Returns\n    -------\n    task: Array of autotvm.task.Task\n        collected tasks\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n    return extract_from_multiple_program([mod], [params], target, ops=ops)\n\n\ndef extract_from_multiple_program(mods, params, target, target_host=None, ops=None):\n    \"\"\"Extract tuning tasks from multiple relay programs.\n\n    This function collects tuning tasks by building a list of programs\n    with a \"tracing\" target and tracing all the calls to topi.\n\n    Parameters\n    ----------\n    mods: List[tvm.IRModule] or List[relay.function.Function]\n        The list of modules or functions to tune\n    params: List of dict of str to numpy array\n        The associated parameters of the programs\n    target: tvm.target.Target\n        The compilation target\n    target_host: tvm.target.Target\n        The host compilation target\n    ops: List[tvm.ir.Op] or None\n        List of relay ops to be tuned.  If not specified, all tunable ops will be extracted.\n\n    Returns\n    -------\n    task: Array of autotvm.task.Task\n        collected tasks\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n    from tvm import topi\n\n    env = TaskExtractEnv.get()\n\n    # merge target and target host\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    # run compiler to collect all TOPI calls during compilation\n    env.reset(ops)\n    with env:\n        # disable logger temporarily\n        old_state = logger.disabled\n        logger.disabled = True\n\n        for mod, param in zip(mods, params):\n            if isinstance(mod, relay.function.Function):\n                mod = tvm.IRModule.from_expr(mod)\n            assert isinstance(\n                mod, tvm.IRModule\n            ), \"only support relay Module or Function to be tuned\"\n            relay.backend.te_compiler.get().clear()\n            # wrap build call in thread to avoid multiprocessing problems\n            build_thread = threading.Thread(target=_lower, args=(mod, target, param))\n            build_thread.start()\n            build_thread.join()\n            relay.backend.te_compiler.get().clear()\n            # Clear the warning message cache in FallbackContext\n            if isinstance(DispatchContext.current, FallbackContext):\n                DispatchContext.current.memory = {}\n                DispatchContext.warning_messages = set()\n\n        logger.disabled = old_state\n\n    # create tasks for target\n    tasks = []\n    for task_name, args in env.get_tasks():\n        try:\n            tsk = create(task_name, args, target=target)\n            tasks.append(tsk)\n        except topi.InvalidShapeError:\n            logger.warning(\"Invalid shape during AutoTVM task creation\")\n\n    return tasks\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-few-public-methods,invalid-name,unused-argument,arguments-differ\n# pylint: disable=consider-using-enumerate,too-many-lines\n\"\"\"\nTemplate configuration space.\n\nEach template function can be parameterized by a ConfigSpace.\nThe space is declared when we invoke the template function with ConfigSpace.\nDuring evaluation, we pass in a ConfigEntity, which contains a specific\nentity in the space. This entity contains deterministic parameters.\n\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport itertools\nimport functools\nimport math\nfrom collections import namedtuple, OrderedDict\nfrom random import randrange\nimport numpy as np\n\nfrom tvm.te import schedule, thread_axis\nfrom tvm.tir import expr\nfrom tvm.autotvm.utils import get_const_int\n\nAxis = namedtuple(\"Axis\", [\"space\", \"index\"])\n\ntry:\n    _long = long\nexcept NameError:\n    _long = int\n\n\nclass InstantiationError(ValueError):\n    \"\"\"Actively detected error in instantiating a template with a config,\n    raised by cfg.raise_error\n    e.g. too many unrolling, too many threads in a block\n    \"\"\"\n\n\nclass TransformSpace(object):\n    \"\"\"Base class for transform space\n    TransformSpace is the node in the computation graph of axes\n\n    .. note::\n\n        We can regard our schedule code as a transformation graph of axes.\n        Starting from raw axes in the definition of te.compute, we can transform these axes\n        by some operators. The operator includes 'split', 'reorder' and 'annotate'.\n        Each operator has some tunable parameters (e.g. the split factor).\n        Then the tuning process is just to find good parameters of these op.\n\n    So all the combinations of the parameters of these op form our search space.\n\n    Naming convention:\n    We call the set of all possible values as XXXSpace. (XXX can be Split, Reorder, Config ...)\n    We call a specific entity in a space as XXXEntity.\n    \"\"\"\n\n    def __init__(self):\n        self.ins = []\n        self.num_output = 0\n        self.entities = []\n\n    def __len__(self):\n        return len(self.entities)\n\n    def __getitem__(self, index):\n        \"\"\"Get an entity of the space by index\n\n        Parameters\n        ----------\n        index: int\n\n        Returns\n        -------\n        transform entity\n        \"\"\"\n        return self.entities[index]\n\n    @staticmethod\n    def get_num_output():\n        \"\"\"get number of output axes after this transform\n\n        Returns\n        -------\n        n: int\n            number of output axes\n        \"\"\"\n        return 0\n\n\nclass VirtualAxis(TransformSpace):\n    \"\"\"Axis placeholder in template\n\n    Parameters\n    ----------\n    var: int or tvm.te.schedule.IterVar\n        If is int, return a virtual axis whose length is the provided argument.\n        If is IterVar, return a virtual axis whose length is extracted from\n        the IterVar's extent domain.\n\n    name: str\n    \"\"\"\n\n    name_ct = 0\n\n    def __init__(self, var, name=None):\n        super(VirtualAxis, self).__init__()\n        self.num_output = 1\n\n        if name is None:\n            name = \"axis_%d\" % VirtualAxis.name_ct\n            VirtualAxis.name_ct += 1\n\n        self.name = name\n        if isinstance(var, (int, _long)):\n            self.length = var\n        elif isinstance(var, schedule.IterVar):\n            self.name = var.var.name\n            if var.dom is None:\n                self.length = -1\n            else:\n                self.length = get_const_int(var.dom.extent)\n        elif isinstance(var, VirtualAxis):\n            self.length = var.length\n        else:\n            raise RuntimeError(\"Invalid type of axis: \" + str(type(var)))\n\n    @staticmethod\n    def get_num_output(var, name=None):\n        return 1\n\n    def __repr__(self):\n        return \"vaxis(%s)\" % self.name\n\n\ndef get_factors(n):\n    \"\"\"return all factors of an integer\n\n    Parameters\n    ----------\n    n: int\n        integer to factorize\n\n    Returns\n    -------\n    factors: list\n        List of all factors\n    \"\"\"\n    step = 2 if n % 2 else 1\n    ret = list(\n        set(\n            functools.reduce(\n                list.__add__,\n                ([i, n // i] for i in range(1, int(math.sqrt(n)) + 1, step) if n % i == 0),\n            )\n        )\n    )\n    ret.sort()\n    return ret\n\n\ndef get_pow2s(n):\n    \"\"\"return all power-of-two numbers that are less or equal than the integer\n\n    Parameters\n    ----------\n    n: int\n        integer for reference\n\n    Returns\n    -------\n    factors: list\n        List of all power-of-two numbers\n    \"\"\"\n    return [2**x for x in range(math.floor(math.log2(n)) + 1)]\n\n\nclass SplitSpace(TransformSpace):\n    \"\"\"Split an axis for several times\"\"\"\n\n    def __init__(self, axes, policy, **kwargs):\n        super(SplitSpace, self).__init__()\n        axis = axes[0]\n\n        self.policy = policy\n        self.entities = []\n\n        max_factor = kwargs.get(\"max_factor\", 1 << 31)\n        fil = kwargs.get(\"filter\", lambda x: True)\n        self.product = axis.length\n        self.num_output = kwargs.get(\"num_outputs\", 0)\n        assert self.num_output > 0\n\n        if policy == \"candidate\":\n            for size in kwargs[\"candidate\"]:\n                assert len(size) == self.num_output\n                self.entities.append(SplitEntity(size))\n        else:\n            if policy == \"verbose\":\n                # Include factors and power-of-twos. May generate tails.\n                divisibles = get_factors(self.product)\n                pow2s = get_pow2s(self.product)\n                factors = [x for x in list(set(divisibles) | set(pow2s)) if x <= max_factor]\n            elif policy == \"factors\":\n                # Include divisible factors. Guarantee no tails.\n                factors = [x for x in get_factors(self.product) if x <= max_factor]\n            elif policy == \"power2\":\n                # Include less, equal, and round-up power-of-two numbers. May generate tails.\n                factors = [x for x in get_pow2s(self.product) if x <= max_factor]\n            else:\n                raise RuntimeError(\"Invalid policy: %s\" % policy)\n\n            # Enforce the product of all split factors equals to the axis length\n            no_tail = kwargs.get(\"no_tail\", policy == \"factors\")\n\n            # Generate split entity by enumerating candidate factors.\n            self.factors = factors\n            self._generate_space(0, [None] * (self.num_output - 1), enforce_no_tail=no_tail)\n\n        self.entities = list(filter(fil, self.entities))\n\n    def _generate_space(self, now, tmp_stack, enforce_no_tail=False):\n        \"\"\"Generate space by DFS\"\"\"\n        if now == self.num_output - 1:\n            prod = functools.reduce(lambda x, y: x * y, tmp_stack)\n            if prod > self.product:\n                return\n            if self.product % prod == 0 or (not enforce_no_tail and prod < self.product):\n                self.entities.append(SplitEntity([-1] + tmp_stack[::-1]))\n        else:\n            for factor in self.factors:\n                tmp_stack[now] = factor\n                self._generate_space(now + 1, tmp_stack, enforce_no_tail)\n\n    @staticmethod\n    def get_num_output(axes, policy, **kwargs):\n        return kwargs[\"num_outputs\"]\n\n    def __repr__(self):\n        return \"Split(policy=%s, product=%d, num_outputs=%d) len=%d\" % (\n            self.policy,\n            self.product,\n            self.num_output,\n            len(self),\n        )\n\n\nclass SplitEntity(object):\n    \"\"\"\n    A split operation with detailed parameters\n    that can apply to an axis\n\n    Parameters\n    ----------\n    size: Array of int\n        the size of every axis after split.\n        e.g. an axis of extent 128, we split it into 3 axes, a possible\n        size is [4, 4, 8] (4x4x8 = 128).\n    \"\"\"\n\n    def __init__(self, size):\n        self.size = size\n\n    def apply(self, sch, op, axis):\n        \"\"\"Apply split to an axis\n\n        Parameters\n        ----------\n        sch: tvm.te.schedule.Schedule\n            The tvm schedule\n        op: tvm.te.Operation\n            The stage to be applied\n        axis: tvm.te.schedule.IterVar\n            axis to split\n\n        Returns\n        -------\n        axes : list of Axis\n            The transformed axes.\n        \"\"\"\n        ret = []\n        for i in range(1, len(self.size)):\n            ax0, ax1 = sch[op].split(axis, int(np.prod(self.size[i:])))\n            ret.append(ax0)\n            axis = ax1\n        return ret + [axis]\n\n    def __repr__(self):\n        return str(self.size)\n\n\nclass ReorderSpace(TransformSpace):\n    \"\"\"The parameter space for ordering an array of axes\"\"\"\n\n    def __init__(self, axes, policy, **kwargs):\n        super(ReorderSpace, self).__init__()\n        self.ins = axes\n        self.policy = policy\n        self.num_output = len(axes)\n\n        if policy == \"identity\":\n            self.entities = [ReorderEntity(range(len(axes)))]\n        elif policy == \"all\":\n            self.entities = [ReorderEntity(x) for x in itertools.permutations(range(len(axes)))]\n        elif policy == \"interval_all\":\n            begin, end = kwargs[\"interval\"]\n            sub_space = list(itertools.permutations(range(begin, end)))\n            prefix, suffix = tuple(range(begin)), tuple(range(end, len(axes)))\n            self.entities = [ReorderEntity(prefix + x + suffix) for x in sub_space]\n        elif policy == \"candidate\":\n            candidate = kwargs[\"candidate\"]\n            for can in candidate:\n                perm = [axes.index(x) for x in can]\n                self.entities.append(ReorderEntity(perm))\n        elif policy == \"interleave\":\n            spatial, reduce = kwargs[\"spatial\"], kwargs[\"reduce\"]\n\n            spatial = [[axes.index(x) for x in ch] for ch in spatial]\n            reduce = [[axes.index(x) for x in ch] for ch in reduce]\n\n            outer_merged = self._merge_chain([x[:-1] for x in spatial])\n            inner_merged = self._merge_chain([x[-1:] for x in spatial] + reduce)\n\n            for o in outer_merged:\n                for i in inner_merged:\n                    self.entities.append(ReorderEntity(o + i))\n        elif policy == \"interleave_cuda\":\n            spatial, reduce = kwargs[\"spatial\"], kwargs[\"reduce\"]\n\n            spatial = [[axes.index(x) for x in ch] for ch in spatial]\n            reduce = [[axes.index(x) for x in ch] for ch in reduce]\n\n            outer_merged = self._merge_chain([x[:-1] for x in spatial])\n            reduce_merged = self._merge_chain(reduce)\n            inner_merged = [x[-1] for x in spatial]\n\n            for o in outer_merged:\n                for r in reduce_merged:\n                    self.entities.append(ReorderEntity(o + r + inner_merged))\n        else:\n            raise RuntimeError(\"Invalid policy: \" + policy)\n\n    @staticmethod\n    def get_num_output(axes, policy, **kwargs):\n        return len(axes)\n\n    def __repr__(self):\n        return \"Reorder(policy=%s) len=%d\" % (self.policy, len(self))\n\n    def _merge_chain(self, chains):\n        \"\"\"generate all combinations of merge some chains\"\"\"\n        merged = []\n        tmp_pt = [0] * len(chains)\n        tmp_stack = []\n\n        size = np.sum([len(x) for x in chains])\n        self._merge_dfs(chains, size, tmp_pt, tmp_stack, merged)\n        return merged\n\n    def _merge_dfs(self, chains, size, tmp_pt, tmp_stack, merged):\n        if np.sum(tmp_pt) == size:\n            merged.append(list(tmp_stack))\n            return\n\n        for i in range(len(chains)):\n            # use i == np.argmax(....) here to take spatial order into consideration\n            # if we don't want to consider spatial order, we can use tmp_pt[i] == np.max(....)\n            if tmp_pt[i] < len(chains[i]) and (\n                i == np.argmax([len(chains[x]) - tmp_pt[x] for x in range(len(chains))])\n            ):\n                tmp_stack.append(chains[i][tmp_pt[i]])\n                tmp_pt[i] += 1\n                self._merge_dfs(chains, size, tmp_pt, tmp_stack, merged)\n                tmp_pt[i] -= 1\n                tmp_stack.pop()\n\n\nclass ReorderEntity(object):\n    \"\"\"A reorder operation with detailed parameters that can apply to axes\n\n    Parameters\n    ----------\n    perm: Array of int\n        define the permutation\n    \"\"\"\n\n    def __init__(self, perm):\n        self.perm = perm\n\n    def apply(self, sch, op, axes):\n        \"\"\"Apply reorder to an array of axes\n\n        Parameters\n        ----------\n        sch: tvm.te.schedule.Schedule\n            The tvm schedule\n        op: tvm.te.Operation\n            The stage to be applied\n        axis: tvm.te.schedule.IterVar\n            axis to split\n\n        Returns\n        -------\n        axes : list of Axis\n            The transformed axes.\n        \"\"\"\n        if len(axes) == len(self.perm):\n            new_order = [axes[i] for i in self.perm]\n        else:\n            new_order = [axes[i] for i in self.perm if i < len(axes)]\n        sch[op].reorder(*new_order)\n        return new_order\n\n    def __repr__(self):\n        return str(self.perm)\n\n\nclass AnnotateSpace(TransformSpace):\n    \"\"\"The parameter space for annotating an array of axes\"\"\"\n\n    def __init__(self, axes, policy, **kwargs):\n        super(AnnotateSpace, self).__init__()\n\n        self.ins = axes\n        self.policy = policy\n        self.num_output = len(axes)\n\n        if policy == \"bind_gpu\":\n            self.num_axis = len(axes)\n            if self.num_axis >= 6:\n                self.entities.append(\n                    AnnotateEntity(\n                        [\"fuse\"] * (self.num_axis - 6)\n                        + [\n                            \"blockIdx.z\",\n                            \"blockIdx.y\",\n                            \"blockIdx.x\",\n                            \"threadIdx.z\",\n                            \"threadIdx.y\",\n                            \"threadIdx.x\",\n                        ]\n                    )\n                )\n            elif self.num_axis >= 4:\n                self.entities.append(\n                    AnnotateEntity(\n                        [\"fuse\"] * (self.num_axis - 4)\n                        + [\"blockIdx.y\", \"blockIdx.x\", \"threadIdx.y\", \"threadIdx.x\"]\n                    )\n                )\n            elif self.num_axis >= 2:\n                self.entities.append(\n                    AnnotateEntity([\"fuse\"] * (self.num_axis - 2) + [\"blockIdx.x\", \"threadIdx.x\"])\n                )\n            else:\n                raise RuntimeError(\"Unhandled case in bind_gpu\")\n        elif policy == \"bind_gpu_virtual\":\n            self.num_axis = len(axes)\n            if self.num_axis >= 9:\n                self.entities.append(\n                    AnnotateEntity(\n                        [\"fuse\"] * (self.num_axis - 9)\n                        + [\n                            \"blockIdx.z\",\n                            \"blockIdx.y\",\n                            \"blockIdx.x\",\n                            \"vthread\",\n                            \"vthread\",\n                            \"vthread\",\n                            \"threadIdx.z\",\n                            \"threadIdx.y\",\n                            \"threadIdx.x\",\n                        ]\n                    )\n                )\n            elif self.num_axis >= 6:\n                self.entities.append(\n                    AnnotateEntity(\n                        [\"fuse\"] * (self.num_axis - 6)\n                        + [\n                            \"blockIdx.y\",\n                            \"blockIdx.x\",\n                            \"vthread\",\n                            \"vthread\",\n                            \"threadIdx.y\",\n                            \"threadIdx.x\",\n                        ]\n                    )\n                )\n            elif self.num_axis >= 3:\n                self.entities.append(\n                    AnnotateEntity(\n                        [\"fuse\"] * (self.num_axis - 3) + [\"blockIdx.x\", \"vthread\", \"threadIdx.x\"]\n                    )\n                )\n            else:\n                raise RuntimeError(\"Unhandled case in bind_gpu\")\n        elif policy == \"locate_cache\":\n            self.num_axis = len(axes)\n            num_anchor = kwargs[\"num_anchor\"]\n            self.anns = list(itertools.combinations(range(self.num_axis), num_anchor))\n            self.entities = [AnnotateEntity(x) for x in self.anns]\n        else:  # none, vec, unroll, try_vec, try_unroll, try_vec_unroll, ...\n            anns = policy.replace(\"try\", \"none\").split(\"_\")\n\n            for ann in anns:\n                if ann not in [\"none\", \"unroll\", \"vec\"]:\n                    raise RuntimeError(\"Invalid policy: \" + policy)\n\n            self.num_axis = len(axes)\n            self.anns = [anns] * self.num_axis\n            self._generate_space(0, [\"\"] * self.num_axis)\n\n    def _generate_space(self, now, tmp_stack):\n        \"\"\"Generate space by DFS\"\"\"\n        if now == self.num_axis:\n            # only vectorize inner most dimension\n            vec_ct = tmp_stack.count(\"vec\")\n            if vec_ct in (0, 1):\n                self.entities.append(AnnotateEntity(list(tmp_stack)))\n        else:\n            for ann in self.anns[now]:\n                tmp_stack[now] = ann\n                self._generate_space(now + 1, tmp_stack)\n\n    @staticmethod\n    def get_num_output(axes, policy, **kwargs):\n        return len(axes)\n\n    def __repr__(self):\n        return \"Annotate(policy=%s) len=%d\" % (self.policy, len(self))\n\n\nclass AnnotateEntity(object):\n    \"\"\"An annotation operation with detailed parameters that can apply to axes\n\n    Parameters\n    ----------\n    anns: Array of string\n        The annotations of axes\n    \"\"\"\n\n    def __init__(self, anns):\n        self.anns = anns\n\n    def apply(\n        self, sch, op, axes, axis_lens=None, max_unroll=None, vec_size=None, cfg=None, source=None\n    ):\n        \"\"\"Apply annotation to an array of axes\n\n        Parameters\n        ----------\n        sch: tvm.te.schedule.Schedule\n            The tvm schedule\n        op: tvm.te.Operation\n            The stage to be applied\n        axes: Array of tvm.te.schedule.IterVar\n            axis to split\n        axis_lens: Array of int, optional\n            the length of axes\n        max_unroll: int, optional\n            maximum unroll step\n        vec_size: Array of int, optional\n            valid vector lanes for vectorization\n        cfg: ConfigEntity, optional\n            cfg for recording error\n        source: Array of Array tensor, optional\n            source tensor for attaching cache\n\n        Returns\n        -------\n        axes : list of tvm.te.schedule.IterVar\n            The transformed axes\n        \"\"\"\n        if source is not None:  # special case : attach cache_read/cache_write\n            for src, to in zip(source, self.anns):\n                for t in src:\n                    sch[t].compute_at(sch[op], axes[to])\n        else:  # other cases\n            for i, ann in enumerate(self.anns):\n                if ann == \"none\":\n                    pass\n                elif ann == \"unroll\":\n                    if max_unroll and axis_lens[i] > max_unroll:\n                        cfg.raise_error(\"Too large factor for unrolling\")\n                    sch[op].unroll(axes[i])\n                elif ann == \"vec\":\n                    if vec_size and axis_lens[i] not in vec_size:\n                        cfg.raise_error(\"Wrong size of lanes in vectorization\")\n                    sch[op].vectorize(axes[i])\n                elif ann == \"blockIdx.x\":\n                    sch[op].bind(axes[i], thread_axis(\"blockIdx.x\"))\n                elif ann == \"blockIdx.y\":\n                    sch[op].bind(axes[i], thread_axis(\"blockIdx.y\"))\n                elif ann == \"blockIdx.z\":\n                    sch[op].bind(axes[i], thread_axis(\"blockIdx.z\"))\n                elif ann == \"threadIdx.x\":\n                    sch[op].bind(axes[i], thread_axis(\"threadIdx.x\"))\n                elif ann == \"threadIdx.y\":\n                    sch[op].bind(axes[i], thread_axis(\"threadIdx.y\"))\n                elif ann == \"threadIdx.z\":\n                    sch[op].bind(axes[i], thread_axis(\"threadIdx.z\"))\n                elif ann == \"vthread\":\n                    sch[op].bind(axes[i], thread_axis(\"vthread\"))\n                elif ann == \"fuse\":\n                    assert i < len(axes) - 1\n                    axes[i + 1] = sch[op].fuse(axes[i], axes[i + 1])\n                else:\n                    raise RuntimeError(\"Invalid annotation \" + ann)\n        return axes\n\n    def __repr__(self):\n        return str(self.anns)\n\n\nclass OtherOptionSpace(TransformSpace):\n    \"\"\"The parameter space for general option\"\"\"\n\n    def __init__(self, axes, policy, **kwargs):\n        super(OtherOptionSpace, self).__init__()\n\n        candidate = kwargs[\"candidate\"]\n        self.entities = [OtherOptionEntity(x) for x in candidate]\n\n    @staticmethod\n    def get_num_output(axes, policy, **kwargs):\n        return 0\n\n    def __repr__(self):\n        return \"OtherOption(%s) len=%d\" % (self.entities, len(self))\n\n\nclass OtherOptionEntity(object):\n    \"\"\"The parameter entity for general option, with a detailed value\"\"\"\n\n    def __init__(self, val):\n        self.val = val\n\n    def __repr__(self):\n        return str(self.val)\n\n\nclass ConfigSpace(object):\n    \"\"\"The configuration space of a schedule. Pass it as config in template to\n    collect transformation space and build transform graph of axes\n    \"\"\"\n\n    def __init__(self):\n        # private dict to provide sugar\n        self.space_map = OrderedDict()  # name -> space\n        self._collect = True\n        self._length = None\n        self._range_length = None\n        self._dims = None\n        self._entity_map = OrderedDict()  # name -> entity\n        self._constraints = []\n        self.errors = []\n        self.code_hash = None\n        self.flop = 0\n        self.cost = None\n        self.is_fallback = False\n        self._shared_filter = None\n        self._shared_filter_cache = None\n\n    @staticmethod\n    def axis(var):\n        \"\"\"get a virtual axis (axis placeholder)\n\n        Parameters\n        ----------\n        var: int or tvm.te.schedule.IterVar\n            If is int, return an axis whose length is the provided argument.\n            If is IterVar, return an axis whose length is extracted from the\n            IterVar's extent domain.\n        \"\"\"\n        return VirtualAxis(var)\n\n    reduce_axis = axis\n\n    def define_split(self, name, axis, policy=\"factors\", **kwargs):\n        \"\"\"Define a new tunable knob which splits an axis into a list of axes\n\n        Parameters\n        ----------\n        name: str\n            name to index the entity of this space\n        axis: tvm.te.schedule.IterVar\n            axis to split\n        policy: str\n            name of policy.\n            If is 'factors', the tuner will try all divisible factors.\n            If is 'power2', the tuner will try power-of-two factors less or equal to the length.\n            If is 'verbose', the tuner will try all candidates in above two policies.\n            If is 'candidate', try given candidates.\n        **kwargs:\n            extra arguments for policy\n\n            ``max_factor``:\n                the maximum split factor (`int`).\n            ``filter``:\n                see examples below for how to use filter (`Callable[[int], bool]`).\n            ``num_outputs``:\n                the total number of axis after split (`int`).\n            ``no_tail``:\n                should we only include divisible numbers as split factors (`bool`).\n            ``candidate``:\n                (policy=candidate) manual candidate list (`List`).\n\n        Examples\n        --------\n        >>> # use custom candidates\n        >>> cfg.define_split('tile_x', x, policy='candidate', num_outputs=3,\n        >>>   candidate=[[1, 4, 4], [4, 1, 4]])\n\n        >>> # use a filter that only accepts the split scheme whose inner most tile is less then 4\n        >>> cfg.define_split('tile_y', y, policy='factors', num_outputs=3,\n        >>>   filter=lambda x: x.size[-1] <= 4)\n        \"\"\"\n        axes = [axis]\n        return self._add_new_transform(SplitSpace, name, axes, policy, **kwargs)\n\n    def define_reorder(self, name, axes, policy, **kwargs):\n        \"\"\"Define a new tunable knob which reorders a list of axes\n\n        Parameters\n        ----------\n        name: str\n            name to index the entity of this space\n        axes: Array of tvm.te.schedule.IterVar\n            axes to reorder\n        policy: str\n            name of policy\n            If is 'identity', do an identity permutation.\n            If is 'all', try all permutations.\n            If is 'interval_all', try all permutations of an interval of axes.\n            If is 'candidate', try listed candidate.\n            If is 'interleave', interleave chains of spatial axes and chains of reduction axes.\n        kwargs: dict\n            extra arguments for policy\n        \"\"\"\n        return self._add_new_transform(ReorderSpace, name, axes, policy, **kwargs)\n\n    def define_annotate(self, name, axes, policy, **kwargs):\n        \"\"\"Define a new tunable knob which annotates a list of axes\n\n        Parameters\n        ----------\n        name: str\n            name to index the entity of this space\n        axes: Array of tvm.te.schedule.IterVar\n            axes to annotate\n        policy: str\n            name of policy\n            If is 'unroll', unroll the axes.\n            If is 'try_unroll', try to unroll the axes.\n            If is 'try_unroll_vec', try to unroll or vectorize the axes.\n            If is 'bind_gpu', bind the first few axes to gpu threads.\n            If is 'locate_cache', choose n axes to attach shared/local cache.\n        kwargs: dict\n            extra arguments for policy\n        \"\"\"\n        return self._add_new_transform(AnnotateSpace, name, axes, policy, **kwargs)\n\n    def define_knob(self, name, candidate):\n        \"\"\"Define a tunable knob with a list of candidates\n\n        Parameters\n        ----------\n        name: str\n            name key of that option\n        candidate: list\n            list of candidates\n        \"\"\"\n        return self._add_new_transform(OtherOptionSpace, name, [], None, candidate=candidate)\n\n    def add_flop(self, flop):\n        \"\"\"Add float operation statistics for this tuning task\n\n        Parameters\n        ---------\n        flop: int or float or IntImm or FloatImm\n            number of float operations\n        \"\"\"\n        if isinstance(flop, (expr.IntImm, expr.FloatImm)):\n            flop = flop.value\n        self.flop += float(flop)\n\n    def raise_error(self, msg):\n        \"\"\"register error in config\n        Using this to actively detect error when scheduling.\n        Otherwise these error will occur during runtime, which\n        will cost more time.\n\n        Parameters\n        ----------\n        msg: str\n        \"\"\"\n        self.errors.append(msg)\n\n    def valid(self):\n        \"\"\"Check whether the config meets all the constraints\n\n        .. note::\n\n            This check should be called after instantiation of task,\n            because the ConfigEntity/ConfigSpace collects errors during instantiation\n\n        Returns\n        -------\n        valid: bool\n            whether the config meets all the constraints\n        \"\"\"\n        return not bool(self.errors)\n\n    def is_index_valid(self, index):\n        \"\"\"Checks if the index satisfies the multi_filter condition\n\n        Parameters\n        ----------\n        index: int\n            index from the range of the space\n\n        Returns\n        -------\n        valid: bool\n            whether the index meets all the constraints\n        \"\"\"\n        assert 0 <= index < self.range_length\n        if self._shared_filter is None:\n            return True\n        if self._shared_filter_cache is None:\n            self._make_shared_filter_cache()\n        return self._shared_filter_cache[index]\n\n    def multi_filter(self, filter):  # pylint: disable=redefined-builtin\n        \"\"\"The filter can restrict combination of parameters in difference to the knob filter,\n        that restricts only single parameter\n\n        Parameters\n        ----------\n        filter: function\n            predicate with one argument (Callable[[int], bool])\n\n        .. note::\n\n            Using this filter causes additional restrictions on the use of __len__.\n            Normally, it define the count of valid indexes and the range of space, but when\n            multi_filter enabled, it requires to use __len__ for getting the count of valid\n            indexes or range_length for the range of space. It is recommended to use:\n            ``is_index_valid``, ``get_next_index``, ``get_rand_index`` to bypass the space\n\n        Examples\n        --------\n        >>> # Pre-requisites\n        >>> candidates = [[16, 64], [32, 32], [64, 16]]\n        >>> filter = lambda v: v.size[0] != 16\n        >>> multi_filter = lambda e: (e[\"tile_x\"].size[0] + e[\"tile_y\"].size[0]) <= 64\n\n        >>> # Case 1 - without filtering\n        >>> cfg.define_split(\"tile_x\", x, num_outputs=2, policy=\"candidate\", candidate=candidates)\n        >>> cfg.define_split(\"tile_y\", y, num_outputs=2, policy=\"candidate\", candidate=candidates)\n        >>> # [('tile_x', [16, 64]), ('tile_y', [16, 64])],None,0\n        >>> # [('tile_x', [32, 32]), ('tile_y', [16, 64])],None,1\n        >>> # [('tile_x', [64, 16]), ('tile_y', [16, 64])],None,2\n        >>> # [('tile_x', [16, 64]), ('tile_y', [32, 32])],None,3\n        >>> # [('tile_x', [32, 32]), ('tile_y', [32, 32])],None,4\n        >>> # [('tile_x', [64, 16]), ('tile_y', [32, 32])],None,5\n        >>> # [('tile_x', [16, 64]), ('tile_y', [64, 16])],None,6\n        >>> # [('tile_x', [32, 32]), ('tile_y', [64, 16])],None,7\n        >>> # [('tile_x', [64, 16]), ('tile_y', [64, 16])],None,8\n\n        >>> # Case 2 - with filter\n        >>> cfg.define_split(\"tile_x\", x, num_outputs=2, policy=\"candidate\", candidate=candidates,\n        >>>   filter=filter)\n        >>> cfg.define_split(\"tile_y\", y, num_outputs=2, policy=\"candidate\", candidate=candidates,\n        >>>   filter=filter)\n        >>> # [('tile_x', [32, 32]), ('tile_y', [32, 32])],None,0\n        >>> # [('tile_x', [64, 16]), ('tile_y', [32, 32])],None,1\n        >>> # [('tile_x', [32, 32]), ('tile_y', [64, 16])],None,2\n        >>> # [('tile_x', [64, 16]), ('tile_y', [64, 16])],None,3\n\n        >>> # Case 3 - with filter and multi_filter\n        >>> cfg.define_split(\"tile_x\", x, num_outputs=2, policy=\"candidate\", candidate=candidates,\n        >>>   filter=filter)\n        >>> cfg.define_split(\"tile_y\", y, num_outputs=2, policy=\"candidate\", candidate=candidates,\n        >>>   filter=filter)\n        >>> cfg.multi_filter(filter=multi_filter)\n        >>> # [('tile_x', [32, 32]), ('tile_y', [32, 32])],None,0\n        \"\"\"\n        if self._collect:\n            self.clear_cache()\n            self._shared_filter = filter\n\n    @property\n    def range_length(self):\n        \"\"\"Length of the index range in the space\"\"\"\n        if self._range_length is None:\n            self._range_length = int(np.prod([len(x) for x in self.space_map.values()]))\n        return self._range_length\n\n    @property\n    def dims(self):\n        \"\"\"Dimensions in the space\"\"\"\n        if self._dims is None:\n            self._dims = [len(x) for x in self.space_map.values()]\n        return self._dims\n\n    def subrange_length(self, start, end):\n        \"\"\"Returns the number of valid indexes within the limited range from [start, end]\n\n        Parameters\n        ----------\n        start: int\n            start of subrange, inclusive\n        end: int\n            end of subrange, exclusive\n\n        Returns\n        -------\n        count: int\n            number of valid indexes\n        \"\"\"\n        assert 0 <= start <= end <= self.range_length\n        if self._shared_filter is None:\n            return end - start\n        if self._shared_filter_cache is None:\n            self._make_shared_filter_cache()\n        return self._shared_filter_cache[start:end].count(True)\n\n    def get_rand_index(self, start=None, end=None, to_exclude=None):\n        \"\"\"Returns a random valid index unlisted to exclusion\n\n        Parameters\n        ----------\n        start: int, optional\n            specifying at which position to start, inclusive\n        end: int, optional\n            specifying at which position to end, exclusive\n        to_exclude: list, optional\n            determines unsuitable values\n\n        Returns\n        -------\n        rand: int\n            random index in the space\n\n        .. note::\n\n            Excluding all valid space indexes will lead to an infinite loop.\n\n        \"\"\"\n        start = start or 0\n        end = end or self.range_length\n        while True:\n            index = randrange(start, end)\n            if self.is_index_valid(index) and index not in (to_exclude or []):\n                return index\n\n    def get_next_index(self, index, n=1, start=None, end=None):\n        \"\"\"Returns the nth valid next index or None if out of range\n\n        Parameters\n        ----------\n        index: int\n            specifying at which position to start, inclusive\n        n: int, optional\n            step by using to find the next index, for the opposite\n            direction a negative number should be used\n        start: list, optional\n            start of subrange, inclusive\n        end: list, optional\n            end of subrange, exclusive\n\n        Returns\n        -------\n        next: int\n            next index in the space\n        \"\"\"\n        assert n != 0\n        start = start or 0\n        end = end or self.range_length\n        if self._shared_filter is None:\n            index += n\n            if start <= index < end:\n                return index\n            return None\n        trend = 1 if n > 0 else -1\n        counter = abs(n)\n        while counter != 0:\n            index += trend\n            if index < start or index >= end:\n                return None\n            if self.is_index_valid(index):\n                counter -= 1\n        return index\n\n    def clear_cache(self):\n        \"\"\"Clears the cache of index validity\"\"\"\n        del self._shared_filter_cache\n        self._dims = None\n        self._length = None\n        self._range_length = None\n        self._shared_filter_cache = None\n\n    def _make_shared_filter_cache(self):\n        def apply(t):\n            entities = OrderedDict()\n            for name, space in self.space_map.items():\n                entities[name] = space[t % len(space)]\n                t //= len(space)\n            return bool(self._shared_filter(entities))\n\n        self._shared_filter_cache = tuple(apply(i) for i in range(self.range_length))\n        self._length = self._shared_filter_cache.count(True)\n\n    def point2knob(self, point):\n        \"\"\"Convert point form (single integer) to knob (vector)\n\n        Parameters\n        ----------\n        point: int\n            point to convert\n\n        Returns\n        -------\n        knob: list\n            knob representation of the point\n        \"\"\"\n        knob = []\n        for dim in self.dims:\n            knob.append(point % dim)\n            point //= dim\n        return knob\n\n    def knob2point(self, knob):\n        \"\"\"Convert knob form (vector) to point form (single integer)\n\n        Parameters\n        ----------\n        knob: list\n            knob to convert\n\n        Returns\n        -------\n        point: int\n            point of the knob representation\n        \"\"\"\n        point = 0\n        for j, k in enumerate(knob):\n            point += int(np.prod(self.dims[:j])) * k\n        return point\n\n    def sample_ints(self, m):\n        \"\"\"\n        Sample m different integer numbers from [0, self.range_length) without replacement\n        This function is an alternative of `np.random.choice` when self.range_length > 2 ^ 32, in\n        which case numpy does not work.\n\n        Parameters\n        ----------\n        m: int\n            The number of sampled int\n\n        Returns\n        -------\n        ints: an numpy array of size m\n        \"\"\"\n        assert m <= len(self)\n        vis = set()\n        while len(vis) < m:\n            new = randrange(0, self.range_length)\n            if self.is_index_valid(new):\n                vis.add(new)\n        return np.fromiter(vis, int, len(vis))\n\n    def random_walk(self, point):\n        \"\"\"random walk as local transition\n\n        Parameters\n        ----------\n        point: int\n            index of the ConfigEntity\n\n        Returns\n        -------\n        new_point: int\n            new neighborhood index\n        \"\"\"\n        # transform to knob form\n        old_knob = self.point2knob(point)\n        new_knob = old_knob.copy()\n        new_point = self.knob2point(new_knob)\n        # mutate\n        while new_knob == old_knob or not self.is_index_valid(new_point):\n            from_i = np.random.randint(len(old_knob))\n            to_v = np.random.randint(self.dims[from_i])\n            new_knob[from_i] = to_v\n            new_point = self.knob2point(new_knob)\n        # transform to index form\n        return new_point\n\n    def _add_new_transform(self, space_class, name, axes, policy, **kwargs):\n        \"\"\"Add a new transform space in template\"\"\"\n        # if we do not have tuned info (_collect == True) but defined KNOB value\n        # for \"default\" scheduling before call of _add_new_transform, in this case\n        # no need to create new space and override previously pointed KNOB values\n        if kwargs.get(\"filter\"):\n            self.clear_cache()\n        if self._collect and not (self.is_fallback and name in self._entity_map):\n            # convert schedule axis to space definition axis\n            axes = [x if isinstance(x, (VirtualAxis, Axis)) else self.axis(x) for x in axes]\n\n            # add subspace (knob)\n            space = space_class(axes, policy, **kwargs)\n            self.space_map[name] = space\n            self._entity_map[name] = space[0]\n            return [Axis(space, i) for i in range(space.num_output)]\n        return [Axis(None, i) for i in range(space_class.get_num_output(axes, policy, **kwargs))]\n\n    def __len__(self):\n        \"\"\"Returns the number of valid indexes in the space\"\"\"\n        if self._shared_filter is None:\n            return self.range_length\n        if self._shared_filter_cache is None:\n            self._make_shared_filter_cache()\n        return self._length\n\n    def get(self, index):\n        \"\"\"Get a config entity with detailed parameters from this space\n\n        Parameters\n        ----------\n        index: int\n            index in the space\n\n        Returns\n        -------\n        config: ConfigEntity\n            config corresponds to the index\n        \"\"\"\n        if index < 0 or index >= self.range_length:\n            raise IndexError(\n                \"Index out of range: size {}, got index {}\".format(self.range_length, index)\n            )\n        if not self.is_index_valid(index):\n            raise IndexError(\n                \"Index does not correspond to the multi-filter condition, got index {}. \"\n                \"Use is_index_valid to pre-check\".format(index)\n            )\n        entities = OrderedDict()\n        t = index\n        for name, space in self.space_map.items():\n            entities[name] = space[t % len(space)]\n            t //= len(space)\n        ret = ConfigEntity(index, self.code_hash, entities, self._constraints)\n        return ret\n\n    def __iter__(self):\n        return self._entity_map.__iter__()\n\n    def __getitem__(self, name):\n        \"\"\"get the transform entity(knob) of this entity by name\n           do not use this to get a ConfigEntity of this space (should use ConfigSpace.get instead)\n\n        Parameters\n        ----------\n        name: str\n            name of the transform\n        \"\"\"\n        return self._entity_map[name]\n\n    def __repr__(self):\n        res = \"ConfigSpace (len={}, range_length={}, space_map=\\n\".format(\n            len(self), self.range_length\n        )\n        for i, (name, space) in enumerate(self.space_map.items()):\n            res += \"  %2d %s: %s\\n\" % (i, name, space)\n        return res + \")\"\n\n\n_ann_to_number = {\n    \"none\": 0,\n    \"vec\": 1,\n    \"unroll\": 2,\n    \"blockIdx.x\": 3,\n    \"blockIdx.y\": 4,\n    \"blockIdx.z\": 5,\n    \"threadIdx.x\": 6,\n    \"threadIdx.y\": 7,\n    \"threadIdx.z\": 8,\n    \"vthread\": 9,\n    \"fuse\": 10,\n}\n\n\nclass ConfigEntity(ConfigSpace):\n    \"\"\"A configuration with detailed parameters\n\n    Parameters\n    ----------\n    index: int\n        index of this config in space\n    code_hash: str\n        hash of schedule code\n    entity_map: dict\n        map name to transform entity\n    constraints : list\n        List of constraints\n    \"\"\"\n\n    def __init__(self, index, code_hash, entity_map, constraints):\n        super(ConfigEntity, self).__init__()\n        self.index = index\n        self._collect = False\n        self._entity_map = entity_map\n        self._space_map = None\n        self._constraints = constraints\n        self.code_hash = code_hash\n\n    def get_flatten_feature(self):\n        \"\"\"flatten entities to a numerical one-dimensional feature vector\n\n        Returns\n        -------\n        fea: np.array\n            one dimensional float32 array\n        \"\"\"\n        fea = []\n        for _, v in self._entity_map.items():\n            if isinstance(v, SplitEntity):\n                fea.extend(v.size)\n            elif isinstance(v, ReorderEntity):\n                # use a naive way: directly copy the permutation\n                fea.extend(v.perm)\n            elif isinstance(v, AnnotateEntity):\n                # one-hot encoding\n                for ann in v.anns:\n                    tmp = [0] * len(_ann_to_number)\n                    tmp[_ann_to_number[ann]] = 1\n                    fea.extend(tmp)\n            elif isinstance(v, OtherOptionEntity):\n                fea.append(v.val)\n        return np.array(fea, dtype=np.float32)\n\n    def get_other_option(self):\n        \"\"\"\n        Returns\n        -------\n        other_option: dict\n            other tunable parameters (tunable parameters defined by `cfg.define_knob`)\n        \"\"\"\n        return {x: x.val for x in self._entity_map.values() if isinstance(x, OtherOptionEntity)}\n\n    def to_json_dict(self):\n        \"\"\"convert to a json serializable dictionary\n\n        Return\n        ------\n        json_dict: dict\n            a json serializable dictionary\n        \"\"\"\n        ret = {}\n        ret[\"index\"] = int(self.index)\n        ret[\"code_hash\"] = self.code_hash\n        entity_map = []\n        for k, v in self._entity_map.items():\n            if isinstance(v, SplitEntity):\n                entity_map.append((k, \"sp\", v.size))\n            elif isinstance(v, ReorderEntity):\n                entity_map.append((k, \"re\", v.perm))\n            elif isinstance(v, AnnotateEntity):\n                entity_map.append((k, \"an\", v.anns))\n            elif isinstance(v, OtherOptionEntity):\n                entity_map.append((k, \"ot\", v.val))\n            else:\n                raise RuntimeError(\"Invalid entity instance: \" + v)\n        ret[\"entity\"] = entity_map\n        return ret\n\n    @staticmethod\n    def from_json_dict(json_dict):\n        \"\"\"Build a ConfigEntity from json serializable dictionary\n\n        Parameters\n        ----------\n        json_dict: dict\n            Json serializable dictionary. This should be the return value\n            of :any:`to_json_dict`.\n\n        Returns\n        -------\n        config: ConfigEntity\n            The corresponding config object\n\n        \"\"\"\n        index = json_dict[\"index\"]\n        code_hash = json_dict[\"code_hash\"]\n        constraints = []\n        entity_map = OrderedDict()\n\n        for item in json_dict[\"entity\"]:\n            key, knob_type, knob_args = item\n            if knob_type == \"sp\":\n                entity = SplitEntity(knob_args)\n            elif knob_type == \"re\":\n                entity = ReorderEntity(knob_args)\n            elif knob_type == \"an\":\n                entity = AnnotateEntity(knob_args)\n            elif knob_type == \"ot\":\n                entity = OtherOptionEntity(knob_args)\n            else:\n                raise RuntimeError(\"Invalid config knob type: \" + knob_type)\n            entity_map[str(key)] = entity\n\n        return ConfigEntity(index, code_hash, entity_map, constraints)\n\n    def __repr__(self):\n        return \"%s,%s,%d\" % (str(self._entity_map)[12:-1], self.code_hash, self.index)\n\n\nclass FallbackConfigEntity(ConfigSpace):\n    \"\"\"The config entity created to support fallback\"\"\"\n\n    def __init__(self):\n        super(FallbackConfigEntity, self).__init__()\n        self.is_fallback = True\n\n    def fallback_split(self, name, constraints):\n        \"\"\"Fallback a split knob\n\n        Parameters\n        ----------\n        name: str\n            name of the knob\n        constraints: List of int\n            The maximum tile size for every dimension. Value `-1` means no constraint.\n\n        Examples\n        --------\n        If you use cfg.define_split('tile_0', 128, num_outputs=3),\n        Then cfg.fallback_split('tile_0', [-1, 8, 4]) will give you cfg['tile_0'].size = [4, 8, 4]\n\n        If you use cfg.define_split('tile_0', 49, num_outputs=3),\n        Then cfg.fallback_split('tile_0', [-1, 8, 4]) will give you cfg['tile_0'].size = [7, 7, 1]\n        \"\"\"\n        space = self.space_map[name]\n        assert isinstance(space, SplitSpace)\n        assert len(constraints) == space.num_output\n\n        # '-1' means no constraint\n        constraints = [x if x != -1 else 1e10 for x in constraints]\n\n        entity = self._entity_map[name]\n        now = space.product\n\n        for i in reversed(range(space.num_output)):\n            factors = get_factors(now)\n\n            find = len(factors) - 1\n            for j, f in enumerate(factors):\n                if f > constraints[i]:\n                    find = j - 1\n                    break\n\n            if find >= 0:\n                entity.size[i] = factors[find]\n                now //= factors[find]\n            else:\n                raise RuntimeError(\"Cannot find feasible fallback split entity for node: \" + name)\n\n    def fallback_with_reference_log(self, ref_log):\n        \"\"\"A data driven fallback mechanism.\n        We use tuned parameters from TopHub as reference data.\n        For an unseen shape, we find the most similar tuned one from TopHub and\n        mimic its parameters.\n        Note that we are not matching by workload (e.g., input size, kernel size),\n        but instead matching by configuration space. The idea is that if two workloads have\n        similar configuration space, their optimal configurations are also likely to be similar.\n\n        Parameters\n        ----------\n        ref_log: List of (autotvm.measure.MeasureInput, autotvm.measure.MeasureResult)\n            The reference log\n        \"\"\"\n        knob_names = [x for x in self.space_map.keys() if isinstance(self.space_map[x], SplitSpace)]\n\n        # find best match config in reference data by matching tiling factors\n        factor_list = []\n        for knob_name in knob_names:\n            factor_list.append(get_factors(self.space_map[knob_name].product))\n\n        best_match_cfg = None\n        best_match_score = 0\n        for inp, _ in ref_log:\n            match_score = 0\n            for i, knob_name in enumerate(knob_names):\n                factors = get_factors(int(np.prod(inp.config[knob_name].size)))\n                match_score += float(len(set(factor_list[i]).intersection(factors))) / len(\n                    factor_list[i]\n                )\n\n                if match_score > best_match_score:\n                    best_match_score, best_match_cfg = match_score, inp.config\n\n        if best_match_cfg is None:\n            return\n\n        # mimic its tiling strategy\n        for knob_name in knob_names:\n            constraint = list(best_match_cfg[knob_name].size)\n            constraint[0] = -1\n            self.fallback_split(knob_name, constraint)\n\n        # copy other knobs\n        for knob_name in self.space_map.keys():\n            if not isinstance(self.space_map[knob_name], SplitSpace):\n                self._entity_map[knob_name] = best_match_cfg[knob_name]\n\n    def __setitem__(self, name, entity):\n        \"\"\"set the entity(knob) of by name\n\n        Parameters\n        ----------\n        name: str\n            name of the entity\n        entity: SplitEntity, ReorderEntity, AnnotateEntity, OtherOptionEntity\n            value of the entity\n        \"\"\"\n        self._entity_map[name] = entity\n\n    def __repr__(self):\n        return \"%s,%s\" % (str(self._entity_map)[12:-1], self.code_hash)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/task.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable,not-callable\n\"\"\"Definition of task function.\n\nTask can be constructed from tuple of func, args, and kwargs.\nfunc is a state-less function, or a string that\nregisters the standard task.\n\"\"\"\nimport functools\n\nimport numpy as np\n\nfrom tvm import runtime\nfrom tvm.ir import container\nfrom tvm.target import Target\nfrom tvm.te import placeholder, tensor\nfrom tvm.tir import expr\n\n\nfrom ..utils import get_const_int, get_const_tuple\nfrom .dispatcher import ApplyConfig, DispatchContext\nfrom .space import ConfigSpace\n\n\ndef _lookup_task(name):\n    task = TASK_TABLE.get(name)\n    if task is None:\n        # Unable to find the given task. This might be because we are\n        # creating a task based on a name that has not been imported.\n        # Rather than raising an exception here, we return a dummy\n        # task which cannot be invoked.\n        task = MissingTask(name)\n    return task\n\n\ndef serialize_args(args):\n    \"\"\"serialize arguments of a topi function to a hashable tuple.\n\n    Parameters\n    ----------\n    args: list of hashable or Tensor\n    \"\"\"\n\n    def _encode(x):\n        if isinstance(x, tensor.Tensor):\n            return (\"TENSOR\", get_const_tuple(x.shape), x.dtype)\n        if isinstance(x, (tuple, list, container.Array)):\n            return tuple([_encode(a) for a in x])\n        if isinstance(x, (str, int, float, expr.Var, expr.Any)):\n            return x\n        if isinstance(x, (expr.StringImm, expr.IntImm, expr.FloatImm)):\n            return x.value\n        if isinstance(x, runtime.container.String):\n            return str(x)\n        if x is None:\n            return None\n        raise RuntimeError(\n            'Do not support type \"%s\" in argument. Consider to use'\n            \"primitive types or tvm.tir.Var only\" % type(x)\n        )\n\n    ret = []\n    for t in args:\n        ret.append(_encode(t))\n    return tuple(ret)\n\n\ndef deserialize_args(args):\n    \"\"\"The inverse function of :code:`serialize_args`.\n\n    Parameters\n    ----------\n    args: list of hashable or Tensor\n    \"\"\"\n    ret = []\n    for t in args:\n        if isinstance(t, tuple) and t[0] == \"TENSOR\":\n            ret.append(placeholder(shape=t[1], dtype=t[2]))\n        else:\n            ret.append(t)\n    return ret\n\n\ndef args_to_workload(args, task_name=None):\n    \"\"\"Convert argument list to hashable workload tuple.\n    This function will convert list to tuple, tvm node to python value and\n    flatten te.tensor.Tensor to a tuple\n\n    Parameters\n    ----------\n    task_name : str\n        The AutoTVM task name\n\n    args : list of args\n        The arguments to the function\n\n    Returns\n    -------\n    ret: hashable\n        The hashable value\n    \"\"\"\n    return (task_name,) + serialize_args(args) if task_name is not None else serialize_args(args)\n\n\nclass Task(object):\n    \"\"\"A Tunable Task\n\n    Parameters\n    ----------\n    name: str\n        The name of the task.\n    args: Tuple\n        Positional argument of func\n    \"\"\"\n\n    def __init__(self, name, args):\n        self.name = name\n        self.args = args\n        self.kwargs = {}  # currently unused\n\n        # init null config space\n        self.config_space = None\n        self.func = _lookup_task(name)\n\n        # auxiliary info, available after `init_space` is called\n        self.flop = None\n        self.target = None\n        self.target_host = None\n\n    @property\n    def workload(self):\n        return (self.name,) + serialize_args(self.args)\n\n    def instantiate(self, config):\n        \"\"\"Instantiate this task function (template) with a config.\n        Returns corresponding schedule.\n\n        Parameters\n        ----------\n        config: template.ConfigEntity\n            parameter config for this template\n\n        Returns\n        -------\n        sch: tvm.te.schedule.Schedule\n            The tvm schedule\n        arg_bufs: Array of te.tensor.Tensor\n            The input/output buffers\n        \"\"\"\n        config.flop = 0\n        with ApplyConfig(config):\n            sch, arg_bufs = self.func(*self.args, **self.kwargs)\n        if not self.flop:\n            config.flop = config.flop or compute_flop(sch)\n            self.flop = config.flop\n        return sch, arg_bufs\n\n    def __getstate__(self):\n        # custom pickle implementation is required for\n        # some unpickable local task functions.\n        # So we only pickle the name of the function\n        # and restore the function by name when unpickling it.\n        import cloudpickle  # pylint: disable=import-outside-toplevel\n\n        self.target, self.target_host = Target.canon_target_and_host(self.target, self.target_host)\n        return {\n            \"name\": self.name,\n            \"args\": self.args,\n            \"kwargs\": self.kwargs,\n            \"config_space\": self.config_space,\n            \"flop\": self.flop,\n            \"target\": self.target,\n            \"target_host\": self.target_host,\n            \"func\": cloudpickle.dumps(self.func),\n        }\n\n    def __setstate__(self, state):\n        import cloudpickle  # pylint: disable=import-outside-toplevel\n\n        self.name = state[\"name\"]\n        self.args = state[\"args\"]\n        self.kwargs = state[\"kwargs\"]\n        self.config_space = state[\"config_space\"]\n        self.func = cloudpickle.loads(state[\"func\"])\n        self.flop = state[\"flop\"]\n        self.target, self.target_host = Target.canon_target_and_host(\n            state[\"target\"], state[\"target_host\"]\n        )\n\n    def __repr__(self):\n        return \"Task(func_name=%s, args=%s, kwargs=%s, workload=%s)\" % (\n            self.name,\n            self.args,\n            self.kwargs,\n            self.workload,\n        )\n\n\nTASK_TABLE = {}\n\n\nclass TaskTemplate(object):\n    \"\"\"\n    Task template is used to creates a tunable AutoTVM task.\n\n    It can be defined by a pair of compute and schedule function using\n    `_register_task_compute` and `_register_task_schedule`,\n    or by a customized task creation function that is more flexible using\n    `_register_customized_task`.\n\n    Note that when customized func is registered, compute and schedule function\n    will be ignored\n    \"\"\"\n\n    def __init__(self):\n        self.fcompute = None\n        self.fschedule = None\n        self.fcustomized = None\n\n    def __call__(self, *args, **kwargs):\n        args = deserialize_args(args)\n        if self.fcustomized is None:\n            return self._default_func(*args, **kwargs)\n        assert callable(self.fcustomized)\n        return self.fcustomized(*args, **kwargs)\n\n    def _default_func(self, *args, **kwargs):\n        assert callable(self.fcompute) and callable(self.fschedule)\n        out = self.fcompute(*args, **kwargs)\n        arg_bufs = [out] + self._get_inputs(out)\n        s = self.fschedule([out])\n        return s, arg_bufs\n\n    @staticmethod\n    def _get_inputs(out):\n        inputs = []\n        queue = [out]\n        hash_set = set()\n        while queue:\n            t = queue.pop(0)\n            if isinstance(t.op, tensor.PlaceholderOp):\n                inputs.append(t)\n            else:\n                input_tensors = [t for t in t.op.input_tensors if t not in hash_set]\n                queue.extend(input_tensors)\n                hash_set.update(input_tensors)\n        return inputs\n\n\nclass MissingTask(TaskTemplate):\n    \"\"\"\n    Dummy task template for a task lookup which cannot be resolved.\n    This can occur if the task being requested from _lookup_task()\n    has not been imported in this run.\n    \"\"\"\n\n    def __init__(self, taskname: str):\n        super().__init__()\n        self._taskname = taskname\n\n    def __call__(self, *args, **kwargs):\n        raise RuntimeError(\n            f\"Attempting to invoke a missing task {self._taskname}.\"\n            \"It is possible that the function is registered in a \"\n            \"Python module that is not imported in this run, or the log is out-of-date.\"\n        )\n\n\ndef _register_task_compute(name, func=None):\n    \"\"\"Register compute function to autotvm task\n\n    Parameters\n    ----------\n    name: str\n        The task name\n\n    func: None or callable\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    decorator: callable\n        A decorator\n    \"\"\"\n\n    def _do_reg(f):\n        if name not in TASK_TABLE:\n            TASK_TABLE[name] = TaskTemplate()\n        tmpl = TASK_TABLE[name]\n        if tmpl.fcompute is not None:\n            raise ValueError(\"Compute is already registered in autoTVM task %s\" % name)\n        tmpl.fcompute = f\n        return f\n\n    if func:\n        return _do_reg(func)\n    return _do_reg\n\n\ndef _register_task_schedule(name, func=None):\n    \"\"\"Register schedule function to autotvm task\n\n    Parameters\n    ----------\n    name: str\n        The task name\n\n    func: None or callable\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    decorator: callable\n        A decorator\n    \"\"\"\n\n    def _do_reg(f):\n        if name not in TASK_TABLE:\n            TASK_TABLE[name] = TaskTemplate()\n        tmpl = TASK_TABLE[name]\n        if tmpl.fschedule is not None:\n            raise ValueError(\"Schedule is already registered in autoTVM task %s\" % name)\n        tmpl.fschedule = f\n        return f\n\n    if func:\n        return _do_reg(func)\n    return _do_reg\n\n\ndef _register_customized_task(name, func=None):\n    \"\"\"Register a customized function to AutoTVM task.\n\n    Parameters\n    ----------\n    name: str\n        The task name\n\n    func: None or callable\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    decorator: callable\n        A decorator\n    \"\"\"\n\n    def _do_reg(f):\n        if name not in TASK_TABLE:\n            TASK_TABLE[name] = TaskTemplate()\n        tmpl = TASK_TABLE[name]\n        if tmpl.fcustomized is not None:\n            raise ValueError(\"Customized func is already registered in autoTVM task %s\" % name)\n        tmpl.fcustomized = f\n        return f\n\n    if func:\n        return _do_reg(func)\n    return _do_reg\n\n\ndef template(task_name, func=None):\n    \"\"\"Decorate a function as a tunable schedule template.\n\n    Parameters\n    ----------\n    task_name: str\n        The task name\n\n    func: None or callable\n        A callable template function.\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    func: callable\n        The decorated function\n\n    Examples\n    --------\n    The following code is a tunable template for a blocked matrix multiplication\n\n    .. code-block:: python\n\n        @autotvm.template(\"matmul\")\n        def matmul(N, L, M, dtype):\n            A = te.placeholder((N, L), name='A', dtype=dtype)\n            B = te.placeholder((L, M), name='B', dtype=dtype)\n\n            k = te.reduce_axis((0, L), name='k')\n            C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name='C')\n            s = te.create_schedule(C.op)\n\n            # schedule\n            y, x = s[C].op.axis\n            k = s[C].op.reduce_axis[0]\n\n            ##### define space begin #####\n            cfg = autotvm.get_config()\n            cfg.define_split(\"tile_y\", y, num_outputs=2)\n            cfg.define_split(\"tile_x\", x, num_outputs=2)\n            ##### define space end #####\n\n            # schedule according to config\n            yo, yi = cfg[\"tile_y\"].apply(s, C, y)\n            xo, xi = cfg[\"tile_x\"].apply(s, C, x)\n\n            s[C].reorder(yo, xo, k, yi, xi)\n\n            return s, [A, B, C]\n    \"\"\"\n\n    def _decorate(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            assert not kwargs, \"Do not support kwargs in template function call\"\n            workload = args_to_workload(args, task_name)\n            tgt = Target.current()\n            cfg = DispatchContext.current.query(tgt, workload)\n            with ApplyConfig(cfg):\n                return f(*args, **kwargs)\n\n        _register_customized_task(task_name, f)\n        return wrapper\n\n    if func:\n        return _decorate(func)\n    return _decorate\n\n\ndef create(task_name, args, target, target_host=None):\n    \"\"\"Create a tuning task and initialize its search space\n\n    Parameters\n    ----------\n    task_name : str\n        The AutoTVM task name\n    args : List\n        Positional arguments\n    target : Target\n        The compilation target\n    target_host: Target, optional\n        The compilation target for host side\n\n    Returns\n    -------\n    tsk: Task\n        a task object\n    \"\"\"\n    args = serialize_args(args)\n    ret = Task(task_name, args)\n\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    # init config space\n    ret.config_space = ConfigSpace()\n\n    ctx = ApplyConfig(ret.config_space)\n    with ctx:\n        with target:\n            sch, _ = ret.func(*args)\n            ret.config_space.code_hash = getattr(sch, \"code_hash\", None)\n\n    ret.flop = ret.config_space.flop or compute_flop(sch)\n    ret.target = target\n    ret.target_host = target_host\n\n    return ret\n\n\ndef get_config():\n    \"\"\"Get current config object\n\n    Returns\n    -------\n    cfg: ConfigSpace or ConfigEntity\n        The current config\n    \"\"\"\n    tgt = Target.current(allow_none=True)\n    return DispatchContext.current.query(tgt, None)\n\n\nclass FlopCalculationError(RuntimeError):\n    \"\"\"Error happens when estimating FLOP for a compute op\"\"\"\n\n\ndef compute_flop(sch):\n    \"\"\"Calculate number of FLOP (floating number operations) of the compute ops in a schedule\n\n    Parameters\n    ----------\n    sch: tvm.te.schedule.Schedule\n        schedule\n\n    Returns\n    -------\n    flop: int\n        number of FLOP in this schedule\n    \"\"\"\n\n    def _prod_length(axes):\n        \"\"\"compute product of the lengths of a list of axes\"\"\"\n        try:\n            num_iter = int(np.prod([get_const_int(axis.dom.extent) for axis in axes]))\n        except ValueError:\n            raise FlopCalculationError(\"The length of axis is not constant. \")\n        return num_iter\n\n    def _count_flop(exp):\n        \"\"\"compute flop for a single expression\"\"\"\n        if isinstance(exp, expr.Reduce):\n            num_iter = _prod_length(exp.axis)\n            combiner = exp.combiner.result\n            source = exp.source\n            if len(combiner) != 1:\n                raise FlopCalculationError(\"Found multiple output in the combiner of reduce op\")\n            if len(source) != 1:\n                raise FlopCalculationError(\"Found multiple output in the source of reduce op\")\n            return num_iter * (_count_flop(combiner[0]) + _count_flop(source[0]))\n        if isinstance(exp, (expr.FloatImm, expr.IntImm)):\n            return 0\n        if isinstance(exp, expr.Cast):\n            return _count_flop(exp.value)\n        if isinstance(exp, expr.Var):\n            return 0\n        if isinstance(\n            exp,\n            (\n                expr.Add,\n                expr.Sub,\n                expr.Mul,\n                expr.Div,\n                expr.Mod,\n                expr.FloorDiv,\n                expr.FloorMod,\n                expr.Max,\n                expr.Min,\n                expr.EQ,\n                expr.NE,\n                expr.LT,\n                expr.LE,\n                expr.GT,\n                expr.GE,\n                expr.And,\n                expr.Or,\n                expr.Not,\n            ),\n        ):\n            base = 1\n\n            if isinstance(exp, expr.Not):  # unary\n                return base + _count_flop(exp.a)\n\n            return base + _count_flop(exp.a) + _count_flop(exp.b)\n        if isinstance(exp, expr.Select):\n            return _count_flop(exp.condition) + max(\n                _count_flop(exp.true_value), _count_flop(exp.false_value)\n            )\n        if isinstance(exp, expr.ProducerLoad):\n            # Ignore flops from indexing expressions.\n            return 0\n\n        if isinstance(exp, expr.Call):\n            return sum([_count_flop(x) for x in exp.args])\n\n        raise FlopCalculationError(\"Found unsupported operator in the compute expr\")\n\n    def traverse(ops):\n        \"\"\"accumulate flops\"\"\"\n        ret = 0\n        for op in ops:\n            if isinstance(op, tensor.ComputeOp):\n                num_element = _prod_length(op.axis)\n\n                body = op.body\n                if len(body) != 1:\n                    raise FlopCalculationError(\"Found multiple output in the compute\")\n                exp = body[0]\n\n                ret += num_element * _count_flop(exp)\n                ret += traverse([t.op for t in op.input_tensors])\n\n            elif isinstance(op, tensor.PlaceholderOp):\n                pass\n            else:\n                raise FlopCalculationError(\n                    f\"{op.name} is not supported by autotvm. \"\n                    \"Only support te.compute currently. \"\n                    \"Other ops like tvm.te.scan/te.extern is not supported\"\n                )\n        return ret\n\n    try:\n        ret = traverse(sch.outputs)\n    except FlopCalculationError as exc:\n        raise RuntimeError(\n            \"FLOP estimator fails for this operator. Error msg: \"\n            + str(exc)\n            + \". Please use `cfg.add_flop` to manually set \"\n            \"FLOP for this operator\"\n        )\n\n    if ret == 0:\n        raise RuntimeError(\n            \"Cannot find float number operation in this operator. \"\n            \"Please use `cfg.add_flop` to manually set \"\n            \"FLOP for this operator\"\n        )\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/task/topi_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable,invalid-name,unused-argument\n\"\"\"\nDecorators for registering tunable templates to TOPI.\n\nThese decorators can make your simple implementation be able to use different configurations\nfor different workloads.\nHere we directly use all arguments to the TOPI call as \"workload\", so make sure all the arguments\n(except tvm.te.Tensor) in you calls are hashable. For tvm.te.Tensor,\nwe will serialize it to a hashable tuple.\n\nSee tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.\n\"\"\"\nimport functools\n\nimport tvm.te._ffi_api\nfrom tvm.target import Target\nfrom tvm.te import tensor\n\nfrom .task import (\n    args_to_workload,\n    serialize_args,\n    DispatchContext,\n    _register_task_compute,\n    _register_task_schedule,\n)\n\n\n# Task extractor for relay program\nclass TaskExtractEnv:\n    \"\"\"Global environment for extracting tuning tasks from graph\"\"\"\n\n    current = None\n    registered = None\n\n    def __init__(self, allow_duplicate=False):\n        self.allow_duplicate = allow_duplicate\n        self.task_collection = []\n        self.wanted_relay_ops = None\n        self.modified_funcs = []\n        self.tracing = False\n\n    def __enter__(self):\n        self.task_collection = []\n        self.tracing = True\n\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.tracing = False\n\n    def reset(self, wanted_relay_ops=None):\n        \"\"\"Reset task collections\n\n        Parameters\n        ----------\n        wanted_relay_ops: List of tvm.ir.Op\n            The relay ops to be extracted\n        \"\"\"\n        self.task_collection = []\n        self.wanted_relay_ops = wanted_relay_ops\n\n    def add_task(self, task_name, args):\n        \"\"\"Add AutoTVM task\n\n        Parameters\n        ----------\n        task_name: str\n            AutoTVM task name.\n\n        args: tuple\n            Arguments to the TOPI function.\n        \"\"\"\n        key = (task_name, serialize_args(args))\n        if self.allow_duplicate or key not in self.task_collection:\n            self.task_collection.append(key)\n\n    def get_tasks(self):\n        \"\"\"Get collected tasks\n\n        Returns\n        -------\n        tasks: List of tuple(name, args)\n            A list of tasks extracted from the graph\n        \"\"\"\n        return self.task_collection\n\n    @staticmethod\n    def get(allow_duplicate=False):\n        \"\"\"Get the single instance of TaskExtractEnv\n\n        Parameters\n        ----------\n        allow_duplicate : boolean\n            Whether to fetch all workloads in the network,\n            even though some of them are the same. This is\n            useful for graph tuning.\n\n        Returns\n        -------\n        env: TaskExtractEnv\n            The single instance of TaskExtractEnv\n        \"\"\"\n        if not TaskExtractEnv.current:\n            TaskExtractEnv.current = TaskExtractEnv(allow_duplicate)\n        else:\n            TaskExtractEnv.current.allow_duplicate = allow_duplicate\n        return TaskExtractEnv.current\n\n\ndef register_topi_compute(task_name, func=None):\n    \"\"\"Register a tunable template for a topi compute function.\n\n    The registration will wrap this topi compute to take `cfg` as the first argument,\n    followed by the original argument list. It uses all its argument as workload and\n    stores this \"workload\" to its final ComputeOp, which can be used to reconstruct\n    \"workload\" in the following topi_schedule call.\n\n    Parameters\n    ----------\n    task_name: str\n        The AutoTVM task name\n\n    func: None or callable\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    decorator: callable\n        A decorator\n\n    Examples\n    --------\n    See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.\n    \"\"\"\n\n    def _decorate(topi_compute):\n        @functools.wraps(topi_compute)\n        @_register_task_compute(task_name)\n        def wrapper(*args, **kwargs):\n            \"\"\"wrapper function for topi compute\"\"\"\n            assert not kwargs, \"Do not support kwargs in template function call\"\n            task_env = TaskExtractEnv.current\n            if task_env is not None and task_env.tracing:\n                task_env.add_task(task_name, args)\n            workload = args_to_workload(args, task_name)\n            tgt = Target.current()\n            cfg = DispatchContext.current.query(tgt, workload)\n            node = topi_compute(cfg, *args)\n\n            # attach workload to return op\n            op = node.op\n            attrs = {}\n            for k, v in node.op.attrs.items():\n                attrs[k] = v\n            attrs[\"workload\"] = workload\n            if isinstance(op, tensor.ComputeOp):\n                op = tvm.te._ffi_api.ComputeOp(op.name, op.tag, attrs, op.axis, op.body)\n            elif isinstance(op, tensor.ExternOp):\n                op = tvm.te._ffi_api.ExternOp(\n                    op.name,\n                    op.tag,\n                    attrs,\n                    op.inputs,\n                    op.input_placeholders,\n                    op.output_placeholders,\n                    op.body,\n                )\n            else:\n                raise RuntimeError(\"Unsupported op type: \" + str(type(op)))\n\n            if isinstance(node, tensor.Tensor):\n                return op.output(0)\n            return [op.output(i) for i in range(len(node))]\n\n        return wrapper\n\n    if func:\n        return _decorate(func)\n    return _decorate\n\n\ndef register_topi_schedule(task_name, func=None):\n    \"\"\"Register a tunable template for a topi schedule function.\n\n    The registration will wrap this topi schedule to take `cfg` as the first argument,\n    followed by the original argument list.\n\n    Note that this function will try to find \"workload\" from all the ComputeOp in the input.\n    You can attach \"workload\" to your compute op by using :any:`register_topi_compute`.\n\n    The task name has to be the same as that of the corresponding topi compute function.\n\n    Parameters\n    ----------\n    task_name: str\n        The AutoTVM task name\n\n    func: None or callable\n        If it is None, return a decorator.\n        If is callable, decorate this function.\n\n    Returns\n    -------\n    decorator: callable\n        A decorator\n\n    Examples\n    --------\n    See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.\n    \"\"\"\n\n    def _decorate(topi_schedule):\n        @functools.wraps(topi_schedule)\n        @_register_task_schedule(task_name)\n        def wrapper(outs, *args, **kwargs):\n            \"\"\"wrapper function for topi schedule\"\"\"\n            workload = get_workload(outs, task_name)\n            if workload is None:\n                raise RuntimeError(\n                    f\"Cannot find TOPI workload {task_name}. \"\n                    \"Is it registered with `register_topi_compute`?\"\n                )\n            tgt = Target.current()\n            cfg = DispatchContext.current.query(tgt, workload)\n            return topi_schedule(cfg, outs, *args, **kwargs)\n\n        return wrapper\n\n    if func:\n        return _decorate(func)\n    return _decorate\n\n\ndef get_workload(outs, task_name=None):\n    \"\"\"Retrieve the workload from outputs\"\"\"\n\n    def traverse(tensors):\n        \"\"\"traverse all ops to find attached workload\"\"\"\n        for t in tensors:\n            op = t.op\n            wkl = traverse(op.input_tensors)\n            if wkl is not None:\n                return wkl\n\n            if \"workload\" in op.attrs:\n                ret = args_to_workload(op.attrs[\"workload\"])\n                if task_name is None or ret[0] == task_name:\n                    return ret\n        return None\n\n    outs = [outs] if isinstance(outs, tensor.Tensor) else outs\n    return traverse(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testing utilities for autotvm\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/testing/tune_relay.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport argparse\nimport json\nimport os\nimport warnings\nfrom distutils.util import strtobool\n\nimport tvm\nfrom tvm import autotvm\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.autotvm.graph_tuner import DPTuner\nfrom tvm.autotvm.tuner import XGBTuner\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.meta_schedule.testing.tune_utils import create_timer, generate_input_data\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--workload\",\n        type=str,\n        required=True,\n        help=\"The name of the workload to tune. Supported models: \"\n        \"https://github.com/apache/tvm/blob/main/python/tvm/meta_schedule/testing/relay_workload.py#L303-L322\",  # pylint: disable=line-too-long\n    )\n    args.add_argument(\n        \"--input-shape\",\n        type=str,\n        required=True,\n        help=\"The input shape of the workload. Example: '[1, 3, 224, 224]'\",\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n        help=\"The target device to tune. \"\n        \"Example: 'aws/cpu/c5.9xlarge', 'nvidia/nvidia-v100', 'nvidia/geforce-rtx-3090'\",\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n        help=\"The number of trials per kernel. Example: 800\",\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n        help=\"The host address of the RPC tracker. Example: 192.168.6.66\",\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n        help=\"The port of the RPC tracker. Example: 4445\",\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n        help=\"The key of the RPC tracker. Example: '3090ti'\",\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n        help=\"The working directory to store the tuning logs. Example: '/tmp/tune_relay'\",\n    )\n    args.add_argument(\n        \"--layout\",\n        type=str,\n        default=None,\n        help=\"The layout of the workload. Example: 'NCHW', 'NHWC'\",\n    )\n    args.add_argument(\n        \"--cache-dir\",\n        type=str,\n        default=None,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--graph-tuner\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        help=\"example: graph / vm\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.input_shape = json.loads(parsed.input_shape)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    return parsed\n\n\nARGS = _parse_args()\n\n\ndef main():\n    if ARGS.target.kind.name != \"llvm\" and ARGS.graph_tuner:\n        raise ValueError(\"GraphTuner only supports llvm target\")\n    if ARGS.target.kind.name != \"llvm\" and ARGS.cpu_flush:\n        raise ValueError(\"cpu_flush only supports llvm target\")\n    if ARGS.target.kind.name == \"llvm\" and not ARGS.cpu_flush:\n        warnings.warn(\"cpu_flush is not enabled for llvm target\")\n\n    log_file = os.path.join(ARGS.work_dir, f\"{ARGS.workload}.json\")\n    graph_opt_sch_file = os.path.join(ARGS.work_dir, f\"{ARGS.workload}_graph_opt.log\")\n    measure_option = autotvm.measure_option(\n        builder=autotvm.LocalBuilder(),\n        runner=autotvm.RPCRunner(\n            key=ARGS.rpc_key,\n            host=ARGS.rpc_host,\n            port=ARGS.rpc_port,\n            number=ARGS.number,\n            repeat=ARGS.repeat,\n            min_repeat_ms=ARGS.min_repeat_ms,\n            enable_cpu_cache_flush=ARGS.cpu_flush,\n        ),\n    )\n    describe()\n    print(f\"Workload: {ARGS.workload}\")\n    mod, params, (input_name, input_shape, input_dtype) = get_network(\n        ARGS.workload,\n        ARGS.input_shape,\n        layout=ARGS.layout,\n        cache_dir=ARGS.cache_dir,\n    )\n    input_info = [\n        {\n            \"name\": input_name,\n            \"shape\": input_shape,\n            \"dtype\": input_dtype,\n        },\n    ]\n    input_data = {\n        item[\"name\"]: generate_input_data(item[\"shape\"], item[\"dtype\"]) for item in input_info\n    }\n    for item in input_info:\n        print(f\"  input_name : {item['name']}\")\n        print(f\"  input_shape: {item['shape']}\")\n        print(f\"  input_dtype: {item['dtype']}\")\n\n    with ms.Profiler() as profiler:\n        with ms.Profiler.timeit(\"TaskExtraction\"):\n            # extract workloads from relay program\n            tasks = autotvm.task.extract_from_program(\n                mod[\"main\"],\n                target=ARGS.target,\n                params=params,\n                ops=(\n                    relay.op.get(\"nn.conv2d\"),\n                    relay.op.get(\"nn.conv3d\"),\n                    relay.op.get(\"nn.conv2d_transpose\"),\n                    relay.op.get(\"nn.dense\"),\n                    relay.op.get(\"nn.batch_matmul\"),\n                ),\n            )\n            for i, task in enumerate(tasks):\n                print(f\"Task {i} {task.name}: {task}\")\n\n        with ms.Profiler.timeit(\"Tuning\"):\n            if ARGS.num_trials > 0:\n                for i, task in enumerate(tasks):\n                    prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n                    tuner_obj = XGBTuner(task, loss_type=\"rank\")\n                    n_trial = min(len(task.config_space), ARGS.num_trials)\n                    tuner_obj.tune(\n                        n_trial=n_trial,\n                        early_stopping=800,\n                        measure_option=measure_option,\n                        callbacks=[\n                            autotvm.callback.progress_bar(n_trial, prefix=prefix),\n                            autotvm.callback.log_to_file(log_file),\n                        ],\n                    )\n                if ARGS.graph_tuner:\n                    executor = DPTuner(\n                        graph=mod[\"main\"],\n                        input_shapes={input_name: input_shape},\n                        records=log_file,\n                        target_ops=[\n                            relay.op.get(\"nn.conv2d\"),\n                        ],\n                        target=ARGS.target,\n                    )\n                    executor.benchmark_layout_transform(min_exec_num=1000)\n                    executor.run()\n                    executor.write_opt_sch2record_file(graph_opt_sch_file)\n\n        relay_build = {\"graph\": relay.build, \"vm\": relay.vm.compile}[ARGS.backend]\n        with ms.Profiler.timeit(\"PostTuningCompilation\"):\n            if ARGS.graph_tuner:\n                ctx = autotvm.apply_graph_best(graph_opt_sch_file)\n            else:\n                ctx = autotvm.apply_history_best(log_file)\n            with ctx:\n                print(\"compile...\")\n                with tvm.transform.PassContext(opt_level=3):\n                    lib = relay_build(mod, target=ARGS.target, params=params)\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    run_module_via_rpc(\n        rpc_config=ARGS.rpc_config,\n        lib=lib,\n        dev_type=ARGS.target.kind.name,\n        args=input_data,\n        continuation=create_timer(ARGS.backend),\n        backend=ARGS.backend,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tophub.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTopHub: Tensor Operator Hub\nTo get the best performance, we typically need auto-tuning for the specific devices.\nTVM releases pre-tuned parameters in TopHub for some common networks and hardware targets.\nTVM will download these parameters for you when you call relay.build.\n\"\"\"\n# pylint: disable=invalid-name\n\nimport logging\nfrom os import getenv\nimport sys\nfrom pathlib import Path\nfrom tvm.ir.container import Array\n\nfrom .task import ApplyHistoryBest\nfrom ..target import Target\nfrom ..contrib.download import download\nfrom .record import load_from_file\nfrom .utils import EmptyContext\n\n# environment variable to read TopHub location\nAUTOTVM_TOPHUB_LOC_VAR = \"TOPHUB_LOCATION\"\n\n# default location of TopHub\nAUTOTVM_TOPHUB_DEFAULT_LOC = \"https://raw.githubusercontent.com/tlc-pack/tophub/main/tophub\"\n\n# value of AUTOTVM_TOPHUB_LOC_VAR to specify to not read from TopHub\nAUTOTVM_TOPHUB_NONE_LOC = \"NONE\"\n\n# root path to store TopHub files\nAUTOTVM_TOPHUB_ROOT_PATH = Path(Path(\"~\").expanduser(), \".tvm\", \"tophub\")\n\n# the version of each package\nPACKAGE_VERSION = {\n    \"arm_cpu\": \"v0.08\",\n    \"llvm\": \"v0.04\",\n    \"cuda\": \"v0.10\",\n    \"rocm\": \"v0.05\",\n    \"opencl\": \"v0.04\",\n    \"mali\": \"v0.06\",\n    \"intel_graphics\": \"v0.02\",\n    \"vta\": \"v0.10\",\n    \"amd_apu\": \"v0.01\",\n}\n\nlogger = logging.getLogger(\"autotvm\")\n\n\ndef _alias(name):\n    \"\"\"convert alias for some packages\"\"\"\n    table = {\n        \"vtacpu\": \"vta\",\n        \"webgpu\": \"opencl\",\n        \"vulkan\": \"opencl\",\n        \"nvptx\": \"cuda\",\n        \"amd_apu\": \"amd_apu\",\n    }\n    return table.get(name, name)\n\n\ndef _get_tophub_location():\n    location = getenv(AUTOTVM_TOPHUB_LOC_VAR, None)\n    return AUTOTVM_TOPHUB_DEFAULT_LOC if location is None else location\n\n\ndef context(target, extra_files=None):\n    \"\"\"Return the dispatch context with pre-tuned parameters.\n    This function will load the corresponding *.log files in AUTOTVM_TOPHUB_ROOT_PATH.\n    If cannot find them, it will download them from TopHub github repo.\n    Users can also add their own files in argument `extra_files`.\n\n    Parameters\n    ----------\n    target: Target or List of Target\n        The compilation targets\n    extra_files: list of str, optional\n        Extra log files to load\n    \"\"\"\n    tophub_location = _get_tophub_location()\n    if tophub_location == AUTOTVM_TOPHUB_NONE_LOC:\n        return EmptyContext()\n\n    best_context = ApplyHistoryBest([])\n\n    targets = target if isinstance(target, (Array, list, tuple)) else [target]\n\n    for tgt in targets:\n        if isinstance(tgt, str):\n            tgt = Target(tgt)\n\n        possible_names = []\n        device = tgt.attrs.get(\"device\", \"\")\n        if device != \"\":\n            possible_names.append(_alias(device))\n        possible_names.append(tgt.kind.name)\n\n        all_packages = list(PACKAGE_VERSION.keys())\n        for name in possible_names:\n            name = _alias(name)\n            if name in all_packages:\n                if not check_backend(tophub_location, name):\n                    continue\n\n                filename = \"%s_%s.log\" % (name, PACKAGE_VERSION[name])\n                best_context.load(Path(AUTOTVM_TOPHUB_ROOT_PATH, filename))\n                break  # only load one file to avoid some fallback template mismatch problem\n\n    if extra_files:\n        for filename in extra_files:\n            best_context.load(filename)\n\n    return best_context\n\n\ndef check_backend(tophub_location, backend):\n    \"\"\"Check whether have pre-tuned parameters of the certain target.\n    If not, will download it.\n\n    Parameters\n    ----------\n    backend: str\n        The name of backend.\n\n    Returns\n    ----------\n    success: bool\n        Whether the check is successful.\n    \"\"\"\n    backend = _alias(backend)\n    assert backend in PACKAGE_VERSION, 'Cannot find backend \"%s\" in TopHub' % backend\n\n    version = PACKAGE_VERSION[backend]\n    package_name = \"%s_%s.log\" % (backend, version)\n    if Path(AUTOTVM_TOPHUB_ROOT_PATH, package_name).is_file():\n        return True\n\n    # pylint: disable=import-outside-toplevel\n    if sys.version_info >= (3,):\n        import urllib.request as urllib2\n    else:\n        import urllib2\n    try:\n        download_package(tophub_location, package_name)\n        return True\n    except urllib2.URLError as e:\n        logging.warning(\"Failed to download tophub package for %s: %s\", backend, e)\n        return False\n\n\ndef download_package(tophub_location, package_name):\n    \"\"\"Download pre-tuned parameters of operators for a backend\n\n    Parameters\n    ----------\n    tophub_location: str\n        The location to download TopHub parameters from\n\n    package_name: str\n        The name of package\n    \"\"\"\n    rootpath = Path(AUTOTVM_TOPHUB_ROOT_PATH)\n    rootpath.mkdir(parents=True, exist_ok=True)\n\n    download_url = \"{0}/{1}\".format(tophub_location, package_name)\n    logger.info(\"Download pre-tuned parameters package from %s\", download_url)\n    download(download_url, Path(rootpath, package_name), overwrite=True)\n\n\n# global cache for load_reference_log\nREFERENCE_LOG_CACHE = {}\n\n\ndef load_reference_log(backend, model, workload_name):\n    \"\"\"Load reference log from TopHub to support fallback in template.\n    Template will use these reference logs to choose fallback config.\n\n    Parameters\n    ----------\n    backend: str\n        The backend name\n    model: str\n        The name of the device model\n    workload_name: str\n        The name of the workload. (The first item in the workload tuple)\n    \"\"\"\n\n    backend = _alias(backend)\n    if backend not in PACKAGE_VERSION:\n        return []\n    version = PACKAGE_VERSION[backend]\n    package_name = \"%s_%s.log\" % (backend, version)\n    filename = Path(AUTOTVM_TOPHUB_ROOT_PATH, package_name)\n\n    global REFERENCE_LOG_CACHE\n    key = (backend, model, workload_name)\n\n    if key not in REFERENCE_LOG_CACHE:\n        tmp = []\n        # If TOPHUB_LOCATION is not AUTOTVM_TOPHUB_NONE_LOC,\n        # Download the config file from tophub if not exists.\n        if not Path(filename).exists():\n            tophub_location = _get_tophub_location()\n            if tophub_location != AUTOTVM_TOPHUB_NONE_LOC:\n                download_package(tophub_location, package_name)\n        if Path(filename).is_file():  # in case download failed\n            find = False\n            inp = None\n            counts = {}\n            for inp, res in load_from_file(filename):\n                counts[inp.target.model] = counts.get(inp.target.model, 0) + 1\n                if model == inp.target.model:\n                    find = True\n                    break\n            # if device model is not find, use the device model with the most tuned workloads\n            if not find and counts:\n                model = max(counts.items(), key=lambda k: k[1])[0]\n\n            for inp, res in load_from_file(filename):\n                if model == inp.target.model and inp.task.workload[0] == workload_name:\n                    tmp.append((inp, res))\n        REFERENCE_LOG_CACHE[key] = tmp\n\n    return REFERENCE_LOG_CACHE[key]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nA tuner takes a task as input. It proposes some promising :any:`ConfigEntity`\nin the :any:`ConfigSpace` and measure them on the real hardware. Then it\nproposed the next batch of :any:`ConfigEntity` according to the measure results.\nThis tuning loop is repeated.\n\"\"\"\n\nfrom . import callback\n\nfrom .tuner import Tuner\n\nfrom .index_based_tuner import GridSearchTuner, RandomTuner\nfrom .ga_tuner import GATuner\nfrom .xgboost_tuner import XGBTuner\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/callback.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=consider-using-enumerate,invalid-name\n\"\"\"Namespace of callback utilities of AutoTVM\"\"\"\nimport sys\nimport time\nimport logging\n\nimport numpy as np\n\nfrom .. import record\nfrom ..utils import format_si_prefix\n\nlogger = logging.getLogger(\"autotvm\")\n\n\ndef log_to_file(file_out, protocol=\"json\"):\n    \"\"\"Log the tuning records into file.\n    The rows of the log are stored in the format of autotvm.record.encode.\n\n    Parameters\n    ----------\n    file_out : File or str\n        The file to log to.\n    protocol: str, optional\n        The log protocol. Can be 'json' or 'pickle'\n\n    Returns\n    -------\n    callback : callable\n        Callback function to do the logging.\n    \"\"\"\n\n    def _callback(_, inputs, results):\n        \"\"\"Callback implementation\"\"\"\n        if isinstance(file_out, str):\n            with open(file_out, \"a\") as f:\n                for inp, result in zip(inputs, results):\n                    f.write(record.encode(inp, result, protocol) + \"\\n\")\n        else:\n            for inp, result in zip(inputs, results):\n                file_out.write(record.encode(inp, result, protocol) + \"\\n\")\n\n    # pylint: disable=import-outside-toplevel\n    from pathlib import Path\n\n    if isinstance(file_out, Path):\n        file_out = str(file_out)\n\n    return _callback\n\n\ndef log_to_database(db):\n    \"\"\"Save the tuning records to a database object.\n\n    Parameters\n    ----------\n    db: Database\n        The database\n    \"\"\"\n\n    def _callback(_, inputs, results):\n        \"\"\"Callback implementation\"\"\"\n        for inp, result in zip(inputs, results):\n            db.save(inp, result)\n\n    return _callback\n\n\nclass Monitor(object):\n    \"\"\"A monitor to collect statistic during tuning\"\"\"\n\n    def __init__(self):\n        self.scores = []\n        self.timestamps = []\n\n    def __call__(self, tuner, inputs, results):\n        for inp, res in zip(inputs, results):\n            if res.error_no == 0:\n                flops = inp.task.flop / np.mean(res.costs)\n                self.scores.append(flops)\n            else:\n                self.scores.append(0)\n\n            self.timestamps.append(res.timestamp)\n\n    def reset(self):\n        self.scores = []\n        self.timestamps = []\n\n    def trial_scores(self):\n        \"\"\"get scores (currently is flops) of all trials\"\"\"\n        return np.array(self.scores)\n\n    def trial_timestamps(self):\n        \"\"\"get wall clock time stamp of all trials\"\"\"\n        return np.array(self.timestamps)\n\n\ndef progress_bar(total, prefix=\"\", si_prefix=\"G\"):\n    \"\"\"Display progress bar for tuning\n\n    Parameters\n    ----------\n    total: int\n        The total number of trials\n    prefix: str\n        The prefix of output message\n    si_prefix: str\n        SI prefix for flops\n    \"\"\"\n\n    class _Context(object):\n        \"\"\"Context to store local variables\"\"\"\n\n        def __init__(self):\n            self.best_flops = 0\n            self.cur_flops = 0\n            self.ct = 0\n            self.total = total\n\n        def __del__(self):\n            if logger.level < logging.DEBUG:  # only print progress bar in non-debug mode\n                sys.stdout.write(\" Done.\\n\")\n\n    ctx = _Context()\n    tic = time.time()\n\n    # Validate si_prefix argument\n    format_si_prefix(0, si_prefix)\n\n    if logger.level < logging.DEBUG:  # only print progress bar in non-debug mode\n        sys.stdout.write(\n            \"\\r%s Current/Best: %7.2f/%7.2f %sFLOPS | Progress: (%d/%d) \"\n            \"| %.2f s\" % (prefix, 0, 0, si_prefix, 0, total, time.time() - tic)\n        )\n        sys.stdout.flush()\n\n    def _callback(tuner, inputs, results):\n        ctx.ct += len(inputs)\n\n        flops = 0\n        for inp, res in zip(inputs, results):\n            if res.error_no == 0:\n                flops = inp.task.flop / np.mean(res.costs)\n\n        if not logger.isEnabledFor(logging.DEBUG):  # only print progress bar in non-debug mode\n            ctx.cur_flops = flops\n            ctx.best_flops = tuner.best_flops\n\n            sys.stdout.write(\n                \"\\r%s Current/Best: %7.2f/%7.2f %sFLOPS | Progress: (%d/%d) \"\n                \"| %.2f s\"\n                % (\n                    prefix,\n                    format_si_prefix(ctx.cur_flops, si_prefix),\n                    format_si_prefix(ctx.best_flops, si_prefix),\n                    si_prefix,\n                    ctx.ct,\n                    ctx.total,\n                    time.time() - tic,\n                )\n            )\n            sys.stdout.flush()\n\n    return _callback\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/ga_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=consider-using-enumerate,invalid-name,abstract-method\n\n\"\"\"Tuner with genetic algorithm\"\"\"\n\nimport numpy as np\n\nfrom .tuner import Tuner\n\n\nclass GATuner(Tuner):\n    \"\"\"Tuner with genetic algorithm.\n    This tuner does not have a cost model so it always run measurement on real machines.\n    This tuner expands the :code:`ConfigEntity` as gene.\n\n    Parameters\n    ----------\n    pop_size: int\n        number of genes in one generation\n    elite_num: int\n        number of elite to keep\n    mutation_prob: float\n        probability of mutation of a knob in a gene\n    \"\"\"\n\n    def __init__(self, task, pop_size=100, elite_num=3, mutation_prob=0.1):\n        super(GATuner, self).__init__(task)\n\n        # algorithm configurations\n        self.pop_size = pop_size\n        self.elite_num = elite_num\n        self.mutation_prob = mutation_prob\n\n        assert elite_num <= pop_size, \"The number of elites must be less than population size\"\n\n        # random initialization\n        self.pop_size = min(self.pop_size, len(self.space))\n        self.elite_num = min(self.pop_size, self.elite_num)\n        self.visited = set(self.space.sample_ints(self.pop_size))\n\n        # current generation\n        self.genes = [self.space.point2knob(idx) for idx in self.visited]\n        self.scores = []\n        self.elites = []\n        self.elite_scores = []\n        self.trial_pt = 0\n\n    def next_batch(self, batch_size):\n        ret = []\n        while len(ret) < batch_size and self.has_next():\n            gene = self.genes[self.trial_pt % self.pop_size]\n            self.trial_pt += 1\n            ret.append(self.space.get(self.space.knob2point(gene)))\n        return ret\n\n    def update(self, inputs, results):\n        for inp, res in zip(inputs, results):\n            if res.error_no == 0:\n                y = inp.task.flop / np.mean(res.costs)\n                self.scores.append(y)\n            else:\n                self.scores.append(0.0)\n\n        if len(self.scores) >= len(self.genes) and len(self.visited) < len(self.space):\n            next_genes = []\n            # There is no reason to crossover or mutate since the size of the unvisited\n            # is no larger than the size of the population.\n            if len(self.space) - len(self.visited) <= self.pop_size:\n                for idx in range(self.space.range_length):\n                    if self.space.is_index_valid(idx) and idx not in self.visited:\n                        next_genes.append(self.space.point2knob(idx))\n                        self.visited.add(idx)\n            else:\n                genes = self.genes + self.elites\n                scores = np.array(self.scores[: len(self.genes)] + self.elite_scores)\n\n                # reserve elite\n                self.elites, self.elite_scores = [], []\n                elite_indexes = np.argpartition(scores, -self.elite_num)[-self.elite_num :]\n                for ind in elite_indexes:\n                    self.elites.append(genes[ind])\n                    self.elite_scores.append(scores[ind])\n\n                indices = np.arange(len(genes))\n                scores += 1e-8\n                scores /= np.max(scores)\n                probs = scores / np.sum(scores)\n                while len(next_genes) < self.pop_size:\n                    # cross over\n                    p1, p2 = np.random.choice(indices, size=2, replace=False, p=probs)\n                    p1, p2 = genes[p1], genes[p2]\n                    point = np.random.randint(len(self.space.dims))\n                    tmp_gene = p1[:point] + p2[point:]\n                    # mutation\n                    for j, dim in enumerate(self.space.dims):\n                        if np.random.random() < self.mutation_prob:\n                            tmp_gene[j] = np.random.randint(dim)\n\n                    if self.space.is_index_valid(self.space.knob2point(tmp_gene)):\n                        next_genes.append(tmp_gene)\n                        self.visited.add(self.space.knob2point(tmp_gene))\n            self.genes = next_genes\n            self.trial_pt = 0\n            self.scores = []\n\n    def has_next(self):\n        return len(self.visited) - (len(self.genes) - self.trial_pt) < len(self.space)\n\n    def load_history(self, data_set, min_seed_records=500):\n        pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/index_based_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=abstract-method\n\"\"\"Grid search tuner and random tuner\"\"\"\n\nfrom .tuner import Tuner\n\n\nclass IndexBaseTuner(Tuner):\n    \"\"\"Base class for index based tuner\n    This type of tuner determine the next batch of configs based on config indices.\n\n    Parameters\n    ----------\n    task: autotvm.task.Task\n        The tuning task\n\n    range_idx: Optional[Tuple[int, int]]\n        A tuple of index range that this tuner can select from [begin_idx, end_idx]\n    \"\"\"\n\n    def __init__(self, task, range_idx=None):\n        super(IndexBaseTuner, self).__init__(task)\n        assert range_idx is None or isinstance(\n            range_idx, tuple\n        ), \"range_idx must be None or (int, int)\"\n\n        self.visited = []\n        self.begin_idx, self.end_idx = range_idx or (0, self.space.range_length - 1)\n        assert self.begin_idx >= 0, \"Start index must be positive\"\n        self.end_idx += 1  # Further end_idx is exclusive\n        assert (\n            self.end_idx <= self.space.range_length\n        ), \"Finish index must be less the space range length \"\n        self.range_length = self.end_idx - self.begin_idx\n        assert self.range_length > 0, \"Index range must be positive\"\n        self.visited_max = self.space.subrange_length(self.begin_idx, self.end_idx)\n\n    def has_next(self):\n        return len(self.visited) < self.visited_max\n\n    def load_history(self, data_set, min_seed_records=500):\n        pass\n\n\nclass GridSearchTuner(IndexBaseTuner):\n    \"\"\"Enumerate the search space in a grid search order\"\"\"\n\n    def __init__(self, task, range_idx=None):\n        super(GridSearchTuner, self).__init__(task, range_idx)\n\n        self.index = self.begin_idx\n        if not self.space.is_index_valid(self.index):\n            self.index = self.space.get_next_index(\n                self.index, start=self.begin_idx, end=self.end_idx\n            )\n\n    def next_batch(self, batch_size):\n        ret = []\n        while len(ret) < batch_size and self.has_next():\n            self.visited.append(self.index)\n            ret.append(self.space.get(self.index))\n            self.index = self.space.get_next_index(\n                self.index, start=self.begin_idx, end=self.end_idx\n            )\n        return ret\n\n\nclass RandomTuner(IndexBaseTuner):\n    \"\"\"Enumerate the search space in a random order\n\n    Parameters\n    ----------\n    task: autotvm.task.Task\n        Tuning Task\n\n    range_idx: Optional[Tuple[int, int]]\n        A tuple of index range to random\n    \"\"\"\n\n    def next_batch(self, batch_size):\n        ret = []\n        while len(ret) < batch_size and self.has_next():\n            index = self.space.get_rand_index(self.begin_idx, self.end_idx, to_exclude=self.visited)\n            self.visited.append(index)\n            ret.append(self.space.get(index))\n        return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/metric.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Metrics for evaluating tuning process\"\"\"\n\nimport numpy as np\n\nfrom ..utils import get_rank\n\n\ndef max_curve(trial_scores):\n    \"\"\"f(n) = max([s[i] fo i < n])\n\n    Parameters\n    ----------\n    trial_scores: Array of float\n        the score of i th trial\n\n    Returns\n    -------\n    curve: Array of float\n        function values\n    \"\"\"\n    ret = np.empty(len(trial_scores))\n    keep = -1e9\n    for i, score in enumerate(trial_scores):\n        keep = max(keep, score)\n        ret[i] = keep\n    return ret\n\n\ndef mean_curve(trial_scores):\n    \"\"\"f(n) = mean([s[i] fo i < n])\n\n    Parameters\n    ----------\n    trial_scores: Array of float\n        the score of i th trial\n\n    Returns\n    -------\n    curve: Array of float\n        function values\n    \"\"\"\n    ret = np.empty(len(trial_scores))\n    keep = 0\n    for i, score in enumerate(trial_scores):\n        keep += score\n        ret[i] = keep / (i + 1)\n    return ret\n\n\ndef recall_curve(trial_ranks, top=None):\n    \"\"\"\n    if top is None, f(n) = sum([I(rank[i] < n) for i < n]) / n\n    if top is K,    f(n) = sum([I(rank[i] < K) for i < n]) / K\n\n    Parameters\n    ----------\n    trial_ranks: Array of int\n        the rank of i th trial in labels\n    top: int or None\n        top-n recall\n\n    Returns\n    -------\n    curve: Array of float\n        function values\n    \"\"\"\n    if not isinstance(trial_ranks, np.ndarray):\n        trial_ranks = np.array(trial_ranks)\n\n    ret = np.zeros(len(trial_ranks))\n    if top is None:\n        for i in range(len(trial_ranks)):\n            ret[i] = np.sum(trial_ranks[:i] <= i) / (i + 1)\n    else:\n        for i in range(len(trial_ranks)):\n            ret[i] = 1.0 * np.sum(trial_ranks[:i] < top) / top\n    return ret\n\n\ndef cover_curve(trial_ranks):\n    \"\"\"\n    f(n) = max k s.t. {1,2,...,k} is a subset of {ranks[i] for i < n}\n\n    Parameters\n    ----------\n    trial_ranks: Array of int\n        the rank of i th trial in labels\n\n    Returns\n    -------\n    curve: Array of float\n        function values\n    \"\"\"\n    ret = np.empty(len(trial_ranks))\n    keep = -1\n    cover = set()\n    for i, rank in enumerate(trial_ranks):\n        cover.add(rank)\n        while keep + 1 in cover:\n            keep += 1\n        ret[i] = keep + 1\n    return ret / len(trial_ranks)\n\n\ndef average_recall(preds, labels, N):\n    \"\"\"evaluate average recall-n for predictions and labels\"\"\"\n    trials = np.argsort(preds)[::-1]\n    ranks = get_rank(labels[trials])\n    curve = recall_curve(ranks)\n    return np.sum(curve[:N]) / N\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/model_based_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return,invalid-name,consider-using-enumerate,abstract-method\n\"\"\"Base class for model-based tuner\nThis type of tuner will fit a cost model and use some optimization methods to\nfind optimums points of cost model in space.\n\"\"\"\nimport gc\n\nimport numpy as np\n\nfrom .tuner import Tuner\nfrom ..env import GLOBAL_SCOPE\n\n\nclass FeatureCache(object):\n    \"\"\"Feature cache manager for cache sharing between different cost models\"\"\"\n\n    def __init__(self):\n        self.feature_cache = {}\n\n    def get(self, key):\n        \"\"\"Get feature cache dictionary for a key\n\n        Parameters\n        ----------\n        key: str\n            The key of a feature type\n\n        Returns\n        -------\n        fea_cache: dict\n            cache dictionary\n        \"\"\"\n        if key not in self.feature_cache:\n            self.feature_cache[key] = {}\n\n        return self.feature_cache[key]\n\n    def size(self, key):\n        \"\"\" \" Get the size of a feature cache dictionary\n\n        Parameters\n        ----------\n        key: str\n            The key of a feature type\n\n        Returns\n        -------\n        n: int\n        \"\"\"\n        return len(self.feature_cache.get(key, tuple()))\n\n    def clear(self, key):\n        \"\"\"Clear feature cache for a key\n\n        Parameters\n        ----------\n        key: str\n            The key of a feature type\n        \"\"\"\n        del self.feature_cache[key]\n        self.feature_cache[key] = {}\n        gc.collect()\n\n\nclass CostModel(object):\n    \"\"\"Cost model to predict the speed of a config\"\"\"\n\n    def __init__(self):\n        pass\n\n    def fit(self, xs, ys, plan_size):\n        \"\"\"Fit to training data\n\n        Parameters\n        ----------\n        xs: Array of int\n            indexes of configs in the config space\n        ys: Array of float\n            The speed (flop, float number operations per second)\n        plan_size: int\n            The plan size of tuner\n        \"\"\"\n        raise NotImplementedError()\n\n    def fit_log(self, records, plan_size, min_seed_records=500):\n        \"\"\"Fit training data from log.\n\n        Parameters\n        ----------\n        records: Array of Tuple(MeasureInput, MeasureResult)\n            The tuning records\n        plan_size: int\n            The plan size of tuner\n        min_seed_records: int\n            Defaults to 500. Indicates the minimum number of records to\n            train the tuner with. If there are less than `min_seed_records`\n            number of records in `data_set`, no training of the tuner\n            will be done.\n        \"\"\"\n        raise NotImplementedError()\n\n    def predict(self, xs, output_margin=False):\n        \"\"\"Predict the speed of configs\n\n        Parameters\n        ----------\n        xs: Array of int\n            The indexes of configs to predict\n        output_margin: bool, optional\n            Whether output the untransformed margin.\n            When a model is used as base model, it should output untransformed margin\n\n        Returns\n        -------\n        preds: Array of float\n            The prediction\n        \"\"\"\n        raise NotImplementedError()\n\n    def load_basemodel(self, base_model):\n        \"\"\"Load base model for transfer learning\n\n        Parameters\n        ----------\n        base_model: CostModel\n                base model\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_base_model(self):\n        \"\"\"Clone a base model with the same parameters.\n        The base model is used to fit history data in transfer learning.\n\n        Returns\n        -------\n        model: CostModel\n            A model with the same hyperparameter (argument)\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass ModelOptimizer(object):\n    \"\"\"Optimizer used to find optimal points of cost model\"\"\"\n\n    def __init__(self):\n        pass\n\n    def find_maximums(self, model, num, exclusive):\n        \"\"\"Find maximum of a cost model\n\n        Note we use cost model to predict GFLOPS, so we should find the maximum\n\n        Parameters\n        ----------\n        model: CostModel\n            Cost model\n        num: int\n            The number of returned maximum points\n        exclusive: set, optional\n            The excluded set of this optimizer. Return results won't include any\n            elements in this set.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass ModelBasedTuner(Tuner):\n    \"\"\"Base class for model based tuner\n    This type of tuner will fit a cost model and use an optimizer to\n    find the maximums of the cost model as next trials\n\n    Parameters\n    ----------\n    task: autotvm.task.Task\n        The tuning task\n    cost_model: CostModel\n        The cost model that predicts the speed of a config (IR)\n    model_optimizer:\n        The optimizer to find local optimum points of cost model in tuning search space\n    plan_size: int\n        Tuner will re-fit model per `plan_size` new measure samples\n    diversity_filter_ratio: int or float, optional\n        If is not None, the tuner will first select\n        top-(plan_size * diversity_filter_ratio) candidates according to the cost model\n        and then pick plan_size of them according to the diversity metric.\n    \"\"\"\n\n    def __init__(self, task, cost_model, model_optimizer, plan_size, diversity_filter_ratio=None):\n        super(ModelBasedTuner, self).__init__(task)\n\n        # space\n        self.task = task\n        self.target = task.target\n        self.plan_size = plan_size\n\n        self.cost_model = cost_model\n        self.model_optimizer = model_optimizer\n        self.diversity_filter_ratio = diversity_filter_ratio\n\n        if self.diversity_filter_ratio:\n            assert self.diversity_filter_ratio >= 1, (\n                \"Diversity filter ratio \" \"must be larger than one\"\n            )\n\n        # trial plan\n        self.trials = []\n        self.trial_pt = 0\n        self.visited = set()\n\n        # observed samples\n        self.xs = []\n        self.ys = []\n        self.flops_max = 0.0\n        self.train_ct = 0\n\n    def next_batch(self, batch_size):\n        ret = []\n        while len(ret) < batch_size and self.has_next():\n            while self.trial_pt < len(self.trials):\n                index = self.trials[self.trial_pt]\n                if index not in self.visited and self.space.is_index_valid(index):\n                    break\n                self.trial_pt += 1\n\n            if self.trial_pt >= len(self.trials) - int(0.05 * self.plan_size):\n                # if the trial list is empty or\n                # the tuner is doing the last 5% trials (e-greedy), choose randomly\n                index = self.space.get_rand_index(to_exclude=self.visited)\n            ret.append(self.space.get(index))\n            self.visited.add(index)\n        return ret\n\n    def update(self, inputs, results):\n        for inp, res in zip(inputs, results):\n            index = inp.config.index\n            if res.error_no == 0:\n                self.xs.append(index)\n                flops = inp.task.flop / np.mean(res.costs)\n                self.flops_max = max(self.flops_max, flops)\n                self.ys.append(flops)\n            else:\n                self.xs.append(index)\n                self.ys.append(0.0)\n            # Usually the update function is called during the tune loop\n            # after the index is already added to the visited set.\n            # However, adding the index to visited again here enables us\n            # to also use this update function to resume tuning progress in\n            # case of interruption.\n            assert self.space.is_index_valid(index)\n            self.visited.add(index)\n        # if we have enough new training samples\n        if len(self.xs) >= self.plan_size * (self.train_ct + 1) and self.flops_max > 1e-6:\n            self.cost_model.fit(self.xs, self.ys, self.plan_size)\n            if self.diversity_filter_ratio:\n                candidate = self.model_optimizer.find_maximums(\n                    self.cost_model, self.plan_size * self.diversity_filter_ratio, self.visited\n                )\n                scores = self.cost_model.predict(candidate)\n                knobs = [self.space.point2knob(x) for x in candidate]\n                pick_index = submodular_pick(0 * scores, knobs, self.plan_size, knob_weight=1)\n                maximums = np.array(candidate)[pick_index]\n            else:\n                maximums = self.model_optimizer.find_maximums(\n                    self.cost_model, self.plan_size, self.visited\n                )\n\n            self.trials = maximums\n            self.trial_pt = 0\n            self.train_ct += 1\n\n    def load_history(self, data_set, min_seed_records=500):\n        # set in_tuning as True to make the feature extraction consistent\n        GLOBAL_SCOPE.in_tuning = True\n\n        # fit base model\n        base_model = self.cost_model.spawn_base_model()\n        success = base_model.fit_log(data_set, self.plan_size, min_seed_records)\n\n        if not success:\n            GLOBAL_SCOPE.in_tuning = False\n            return\n\n        # use base model to select initial points\n        if not self.trials:\n            # no plan yet, use base model to select initial trials\n            maximums = self.model_optimizer.find_maximums(base_model, self.plan_size, self.visited)\n            self.trials = maximums\n            self.trial_pt = 0\n\n        self.cost_model.load_basemodel(base_model)\n        GLOBAL_SCOPE.in_tuning = False\n\n    def has_next(self):\n        return len(self.visited) < len(self.space)\n\n\ndef submodular_pick(scores, knobs, n_pick, knob_weight=1.0):\n    \"\"\"Run greedy optimization to pick points with regard to both score and diversity.\n    DiversityScore = knob_weight * number of unique knobs in the selected set\n    Obj = sum(scores[i] for i in pick) + DiversityScore\n    Note that this objective function is a monotone submodular function.\n\n    Parameters\n    ----------\n    scores: Array of float\n        score of every points\n    knobs: Array of Array of int\n        feature vector (tunable knobs) of every points\n    n_pick: int\n        number of points to pick\n    knob_weight: float\n        weight of an unique knob feature\n    \"\"\"\n    n = len(scores)\n    assert n == len(knobs)\n    n_knobs = len(knobs[0])\n\n    knobs_set = [set() for _ in range(n_knobs)]\n\n    ret = []\n    remain = list(range(len(scores)))\n\n    for _ in range(n_pick):\n        max_x = -1\n        max_delta = -1e9\n\n        for x in remain:\n            tmp_delta = scores[x]\n            for i in range(n_knobs):\n                if knobs[x][i] not in knobs_set[i]:\n                    tmp_delta += knob_weight\n\n            if tmp_delta > max_delta:\n                max_delta, max_x = tmp_delta, x\n\n        ret.append(max_x)\n        remain.remove(max_x)\n        for i in range(n_knobs):\n            knobs_set[i].add(knobs[max_x][i])\n\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/sa_model_optimizer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=consider-using-enumerate, invalid-name, invalid-sequence-index\n\"\"\"\nCost model optimizer based on simulated annealing\n\"\"\"\n\nimport heapq\nimport logging\nimport time\n\nimport numpy as np\n\nfrom .model_based_tuner import ModelOptimizer\n\nlogger = logging.getLogger(\"autotvm\")\n\n\nclass SimulatedAnnealingOptimizer(ModelOptimizer):\n    \"\"\"parallel simulated annealing optimization algorithm\n\n    Parameters\n    ----------\n    task: Task\n        The tuning task\n    n_iter: int\n        The number of iterations of simulated annealing\n    temp: float or Array of float\n        If is a single float, then use a constant temperature.\n        If is an Array, then perform linear cooling from temp[0] to temp[1]\n    early_stop: int, optional\n        Stop iteration if the optimal set do not change in `early_stop` rounds\n    log_interval: int, optional\n        Print log every `log_interval` iterations\n    \"\"\"\n\n    def __init__(\n        self,\n        task,\n        n_iter=500,\n        temp=(1, 0),\n        persistent=True,\n        parallel_size=128,\n        early_stop=50,\n        log_interval=50,\n    ):\n        super(SimulatedAnnealingOptimizer, self).__init__()\n        self.task = task\n        self.n_iter = n_iter\n        self.temp = temp\n        self.persistent = persistent\n        self.parallel_size = min(parallel_size, len(self.task.config_space))\n        self.early_stop = early_stop or 1e9\n        self.log_interval = log_interval\n        self.points = None\n\n    def find_maximums(self, model, num, exclusive):\n        tic = time.time()\n        temp, n_iter, early_stop, log_interval = (\n            self.temp,\n            self.n_iter,\n            self.early_stop,\n            self.log_interval,\n        )\n\n        if self.persistent and self.points is not None:\n            points = self.points\n        else:\n            points = self.task.config_space.sample_ints(self.parallel_size)\n\n        scores = model.predict(points)\n\n        # build heap and insert initial points\n        heap_items = [(float(\"-inf\"), -1 - i) for i in range(num)]\n        heapq.heapify(heap_items)\n        in_heap = set(exclusive)\n        in_heap.update([x[1] for x in heap_items])\n\n        for s, p in zip(scores, points):\n            if s > heap_items[0][0] and p not in in_heap:\n                pop = heapq.heapreplace(heap_items, (s, p))\n                in_heap.remove(pop[1])\n                in_heap.add(p)\n\n        k = 0\n        k_last_modify = 0\n\n        if isinstance(temp, (tuple, list, np.ndarray)):\n            t = temp[0]\n            cool = 1.0 * (temp[0] - temp[1]) / (n_iter + 1)\n        else:\n            t = temp\n            cool = 0\n\n        while k < n_iter and k < k_last_modify + early_stop:\n            new_points = np.empty_like(points)\n            for i, p in enumerate(points):\n                new_points[i] = self.task.config_space.random_walk(p)\n\n            new_scores = model.predict(new_points)\n\n            ac_prob = np.exp(np.minimum((new_scores - scores) / (t + 1e-5), 1))\n            ac_index = np.random.random(len(ac_prob)) < ac_prob\n\n            points[ac_index] = new_points[ac_index]\n            scores[ac_index] = new_scores[ac_index]\n\n            for s, p in zip(new_scores, new_points):\n                if s > heap_items[0][0] and p not in in_heap:\n                    pop = heapq.heapreplace(heap_items, (s, p))\n                    in_heap.remove(pop[1])\n                    in_heap.add(p)\n                    k_last_modify = k\n\n            k += 1\n            t -= cool\n\n            if log_interval and k % log_interval == 0:\n                t_str = \"%.2f\" % t\n                logger.debug(\n                    \"SA iter: %d\\tlast_update: %d\\tmax-0: %.2f\\tmax-1: %.2f\\ttemp: %s\\t\"\n                    \"elapsed: %.2f\",\n                    k,\n                    k_last_modify,\n                    heap_items[0][0],\n                    np.max([v for v, _ in heap_items]),\n                    t_str,\n                    time.time() - tic,\n                )\n\n        heap_items.sort(key=lambda item: -item[0])\n        heap_items = [x for x in heap_items if x[0] >= 0]\n        logger.debug(\n            \"SA iter: %d\\tlast_update: %d\\telapsed: %.2f\", k, k_last_modify, time.time() - tic\n        )\n        logger.debug(\"SA Maximums: %s\", heap_items)\n\n        if self.persistent:\n            self.points = points\n\n        return [x[1] for x in heap_items]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, no-self-use, invalid-name\n\"\"\"Base class of tuner\"\"\"\nimport logging\nimport tempfile\n\nimport numpy as np\n\nfrom ..measure import MeasureInput, create_measure_batch\nfrom ..utils import format_si_prefix\n\nfrom ..env import GLOBAL_SCOPE\n\nlogger = logging.getLogger(\"autotvm\")\n\n\nclass Tuner(object):\n    \"\"\"Base class for tuners\n\n    Parameters\n    ----------\n    task: autotvm.task.Task\n        Tuning Task\n    \"\"\"\n\n    def __init__(self, task, **kwargs):\n        self.param = kwargs\n        self.recorder = None\n\n        self.task = task\n        self.space = self.task.config_space\n\n        # keep the current best\n        self.best_config = None\n        self.best_flops = 0\n        self.best_measure_pair = None\n        self.best_iter = 0\n        self.error_ct_threshold = 150\n\n        # time to leave\n        self.ttl = None\n        self.n_trial = None\n        self.early_stopping = None\n\n    def has_next(self):\n        \"\"\"Whether has next untried config in the space\n\n        Returns\n        -------\n        has_next: bool\n        \"\"\"\n        raise NotImplementedError()\n\n    def next_batch(self, batch_size):\n        \"\"\"get the next batch of configs to be measure on real hardware\n\n        Parameters\n        ----------\n        batch_size: int\n            The size of the batch\n\n        Returns\n        -------\n        a batch of configs\n        \"\"\"\n        raise NotImplementedError()\n\n    def update(self, inputs, results):\n        \"\"\"Update parameters of the tuner according to measurement results\n\n        Parameters\n        ----------\n        inputs: Array of autotvm.measure.MeasureInput\n            The input for measurement\n        results: Array of autotvm.measure.MeasureResult\n            result for measurement\n        \"\"\"\n\n    def tune(self, n_trial, measure_option, early_stopping=None, callbacks=(), si_prefix=\"G\"):\n        \"\"\"Begin tuning\n\n        Parameters\n        ----------\n        n_trial: int\n            Maximum number of configs to try (measure on real hardware)\n        measure_option: dict\n            The options for how to measure generated code.\n            You should use the return value ot autotvm.measure_option for this argument.\n        early_stopping: int, optional\n            Early stop the tuning when not finding better configs in this number of trials\n        callbacks: List of callable\n            A list of callback functions. The signature of callback function is\n            (Tuner, List of MeasureInput, List of MeasureResult)\n            with no return value. These callback functions will be called on\n            every measurement pair. See autotvm/tuner/callback.py for some examples.\n        si_prefix: str\n            One of tvm.autotvm.utils.SI_PREFIXES. The SI prefix to use when reporting FLOPS.\n        \"\"\"\n        measure_batch = create_measure_batch(self.task, measure_option)\n        n_parallel = getattr(measure_batch, \"n_parallel\", 1)\n        early_stopping = early_stopping or 1e9\n        self.n_trial = n_trial\n        self.early_stopping = early_stopping\n\n        # Validate si_prefix arg\n        format_si_prefix(0, si_prefix)\n\n        old_level = logger.level\n\n        GLOBAL_SCOPE.in_tuning = True\n        i = error_ct = 0\n        errors = []\n        while i < n_trial:\n            if not self.has_next():\n                break\n\n            configs = self.next_batch(min(n_parallel, n_trial - i))\n\n            inputs = [MeasureInput(self.task.target, self.task, config) for config in configs]\n            results = measure_batch(inputs)\n\n            # keep best config\n            for k, (inp, res) in enumerate(zip(inputs, results)):\n                config = inp.config\n                if res.error_no == 0:\n                    flops = inp.task.flop / np.mean(res.costs)\n                    error_ct = 0\n                    result_msg = res\n                else:\n                    flops = 0\n                    error_ct += 1\n                    tb, error = res.costs\n                    if isinstance(error, str):\n                        errors.append(tb + \"\\n\" + error)\n                    else:\n                        errors.append(tb + \"\\n\" + str(error))\n                    result_msg = errors[-1]\n\n                if flops > self.best_flops:\n                    self.best_flops = flops\n                    self.best_config = config\n                    self.best_measure_pair = (inp, res)\n                    self.best_iter = i + k\n\n                logger.debug(\n                    \"No: %d\\t%sFLOPS: %.2f/%.2f\\tresult: %s\\t%s\",\n                    i + k + 1,\n                    si_prefix,\n                    format_si_prefix(flops, si_prefix),\n                    format_si_prefix(self.best_flops, si_prefix),\n                    result_msg,\n                    config,\n                )\n\n            i += len(results)\n            self.ttl = min(early_stopping + self.best_iter, n_trial) - i\n\n            self.update(inputs, results)\n            for callback in callbacks:\n                callback(self, inputs, results)\n\n            if i >= self.best_iter + early_stopping:\n                logger.debug(\"Early stopped. Best iter: %d.\", self.best_iter)\n                break\n\n            if error_ct > self.error_ct_threshold:\n                logging.basicConfig()\n                logger.warning(\"Too many errors happen in the tuning. Switching to debug mode.\")\n                logger.setLevel(logging.DEBUG)\n            else:\n                logger.setLevel(old_level)\n\n        if error_ct == i:\n            _, f = tempfile.mkstemp(prefix=\"tvm_tuning_errors_\", suffix=\".log\", text=True)\n            with open(f, \"w\") as file:\n                file.write(\"\\n\".join(errors))\n            logging.warning(\n                \"Could not find any valid schedule for task %s. \"\n                \"A file containing the errors has been written to %s.\",\n                self.task,\n                f,\n            )\n        GLOBAL_SCOPE.in_tuning = False\n        del measure_batch\n\n    def reset(self):\n        \"\"\"reset the status of tuner\"\"\"\n        self.best_config = None\n        self.best_flops = 0\n        self.best_measure_pair = None\n\n    def load_history(self, data_set, min_seed_records=500):\n        \"\"\"load history data for transfer learning\n\n        Parameters\n        ----------\n        data_set: Array of (autotvm.measure.MeasureInput, autotvm.measure.MeasureResult) pair\n            Previous tuning records\n        min_seed_records: int\n            Defaults to 500. Indicates the minimum number of records to\n            train the tuner with. If there are less than `min_seed_records`\n            number of records in `data_set`, no training of the tuner\n            will be done.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_error_threshold(self, threshold):\n        \"\"\"Modify error counter threshold, which controls switch to debug mode\n\n        Parameters\n        ----------\n        threshold: New threshold value\n        \"\"\"\n        self.error_ct_threshold = threshold\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/xgboost_cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"XGBoost as cost model\"\"\"\n\nimport logging\nimport time\n\nimport numpy as np\nfrom tvm.contrib.popen_pool import PopenPoolExecutor, StatusKind\n\nfrom .. import feature\nfrom ..utils import get_rank\nfrom .metric import cover_curve, max_curve, recall_curve\nfrom .model_based_tuner import CostModel, FeatureCache\n\nxgb = None\n\nlogger = logging.getLogger(\"autotvm\")\n\n\nclass XGBoostCostModel(CostModel):\n    \"\"\"XGBoost as cost model\n\n    Parameters\n    ----------\n    task: Task\n        The tuning task\n    feature_type: str, optional\n        If is 'itervar', use features extracted from IterVar (loop variable).\n        If is 'knob', use flatten ConfigEntity directly.\n        If is 'curve', use sampled curve feature (relation feature).\n\n        Note on choosing feature type:\n        For single task tuning, 'itervar' and 'knob' are good.\n                                'itervar' is more accurate but 'knob' is much faster.\n                                There are some constraints on 'itervar', if you meet\n                                problems with feature extraction when using 'itervar',\n                                you can switch to 'knob'.\n\n        For cross-shape tuning (e.g. many convolutions with different shapes),\n                               'itervar' and 'curve' has better transferability,\n                               'knob' is faster.\n        For cross-device or cross-operator tuning, you can use 'curve' only.\n    loss_type: str\n        If is 'reg', use regression loss to train cost model.\n                     The cost model predicts the normalized flops.\n        If is 'rank', use pairwise rank loss to train cost model.\n                     The cost model predicts relative rank score.\n    num_threads: int, optional\n        The number of threads.\n    log_interval: int, optional\n        If is not none, the cost model will print training log every `log_interval` iterations.\n    upper_model: XGBoostCostModel, optional\n        The upper model used in transfer learning\n    \"\"\"\n\n    def __init__(\n        self, task, feature_type, loss_type, num_threads=None, log_interval=25, upper_model=None\n    ):\n        global xgb\n        super(XGBoostCostModel, self).__init__()\n        try:\n            if xgb is None:\n                xgb = __import__(\"xgboost\")\n        except ImportError:\n            raise ImportError(\n                \"XGBoost is required for XGBoostCostModel. \"\n                \"Please install its python package first. \"\n                \"Help: (https://xgboost.readthedocs.io/en/latest/) \"\n            )\n\n        self.task = task\n        self.target = task.target\n        self.space = task.config_space\n\n        self.fea_type = feature_type\n        self.loss_type = loss_type\n        self.num_threads = num_threads\n        self.log_interval = log_interval\n\n        if loss_type == \"reg\":\n            self.xgb_params = {\n                \"max_depth\": 3,\n                \"gamma\": 0.0001,\n                \"min_child_weight\": 1,\n                \"subsample\": 1.0,\n                \"eta\": 0.3,\n                \"lambda\": 1.00,\n                \"alpha\": 0,\n                \"objective\": \"reg:linear\",\n            }\n        elif loss_type == \"rank\":\n            self.xgb_params = {\n                \"max_depth\": 3,\n                \"gamma\": 0.0001,\n                \"min_child_weight\": 1,\n                \"subsample\": 1.0,\n                \"eta\": 0.3,\n                \"lambda\": 1.00,\n                \"alpha\": 0,\n                \"objective\": \"rank:pairwise\",\n            }\n        else:\n            raise RuntimeError(\"Invalid loss type: \" + loss_type)\n\n        self.xgb_params[\"verbosity\"] = 0\n        if num_threads:\n            self.xgb_params[\"nthread\"] = num_threads\n        self.bst = None\n\n        if feature_type == \"itervar\":\n            self.feature_extract_func = _extract_itervar_feature_index\n        elif feature_type == \"knob\":\n            self.feature_extract_func = _extract_knob_feature_index\n        elif feature_type == \"curve\":\n            self.feature_extract_func = _extract_curve_feature_index\n        else:\n            raise RuntimeError(\"Invalid feature type \" + feature_type)\n\n        if upper_model:  # share a same feature cache with upper model\n            self.feature_cache = upper_model.feature_cache\n        else:\n            self.feature_cache = FeatureCache()\n        self.upper_model = upper_model\n        self.feature_extra_ct = 0\n        self.pool = None\n        self.base_model = None\n\n        self._sample_size = 0\n        self._reset_pool(self.space, self.target, self.task)\n\n    def _reset_pool(self, space, target, task):\n        \"\"\"reset processing pool for feature extraction\"\"\"\n\n        if self.upper_model:  # base model will reuse upper model's pool,\n            self.upper_model._reset_pool(space, target, task)\n            return\n\n        self._close_pool()\n\n        self.pool = PopenPoolExecutor(\n            max_workers=self.num_threads,\n            initializer=_extract_popen_initializer,\n            initargs=(space, target, task),\n        )\n\n    def _close_pool(self):\n        if self.pool:\n            self.pool = None\n\n    def _get_pool(self):\n        if self.upper_model:\n            return self.upper_model._get_pool()\n        return self.pool\n\n    def _base_model_discount(self):\n        return 1.0 / (2 ** (self._sample_size / 64.0))\n\n    def fit(self, xs, ys, plan_size):\n        tic = time.time()\n        self._reset_pool(self.space, self.target, self.task)\n\n        x_train = self._get_feature(xs)\n        y_train = np.array(ys)\n        y_max = np.max(y_train)\n        y_train = y_train / max(y_max, 1e-8)\n\n        valid_index = y_train > 1e-6\n        index = np.random.permutation(len(x_train))\n        dtrain = xgb.DMatrix(x_train[index], y_train[index])\n        self._sample_size = len(x_train)\n\n        if self.base_model:\n            discount = self._base_model_discount()\n            if discount < 0.05:  # discard base model\n                self.base_model.upper_model = None\n                self.base_model = None\n            else:\n                dtrain.set_base_margin(discount * self.base_model.predict(xs, output_margin=True))\n\n        self.bst = xgb.train(\n            self.xgb_params,\n            dtrain,\n            num_boost_round=8000,\n            callbacks=[\n                custom_callback(\n                    stopping_rounds=20,\n                    metric=\"tr-a-recall@%d\" % plan_size,\n                    evals=[(dtrain, \"tr\")],\n                    maximize=True,\n                    fevals=[\n                        xgb_average_recalln_curve_score(plan_size),\n                    ],\n                    verbose_eval=self.log_interval,\n                )\n            ],\n        )\n\n        logger.debug(\n            \"XGB train: %.2f\\tobs: %d\\terror: %d\\tn_cache: %d\",\n            time.time() - tic,\n            len(xs),\n            len(xs) - np.sum(valid_index),\n            self.feature_cache.size(self.fea_type),\n        )\n\n    def fit_log(self, records, plan_size, min_seed_records=500):\n        tic = time.time()\n\n        # filter data, only pick the data with a same task\n        data = []\n        for inp, res in records:\n            if inp.task.name == self.task.name:\n                data.append((inp, res))\n\n        logger.debug(\"XGB load %d entries from history log file\", len(data))\n\n        # extract feature\n        self._reset_pool(self.space, self.target, self.task)\n        pool = self._get_pool()\n        if self.fea_type == \"itervar\":\n            feature_extract_func = _extract_itervar_feature_log\n        elif self.fea_type == \"knob\":\n            feature_extract_func = _extract_knob_feature_log\n        elif self.fea_type == \"curve\":\n            feature_extract_func = _extract_curve_feature_log\n        else:\n            raise RuntimeError(\"Invalid feature type: \" + self.fea_type)\n        result = pool.map_with_error_catching(feature_extract_func, data)\n        result = list(result)  # store results so we can iterate through them twice\n\n        # get maximum feature length\n        fea_len = -1\n        for res in result:\n            if res.status != StatusKind.COMPLETE:\n                continue\n            x, _ = res.value\n            fea_len = max(fea_len, x.shape[0])\n\n        xs, ys = [], []\n        for res in result:\n            if res.status != StatusKind.COMPLETE:\n                continue\n            x, y = res.value\n            # Features may not be the same size, pad them until they are\n            if fea_len > len(x):\n                xs.append(np.pad(x, (0, fea_len - len(x))))\n            else:\n                xs.append(x)\n            ys.append(y)\n\n        if len(xs) < min_seed_records:  # no enough samples\n            return False\n\n        xs, ys = np.array(xs), np.array(ys)\n        x_train = xs\n        y_train = ys\n        y_max = np.max(y_train)\n        y_train = y_train / max(y_max, 1e-8)\n\n        index = np.random.permutation(len(x_train))\n        dtrain = xgb.DMatrix(x_train[index], y_train[index])\n\n        plan_size *= 2\n        self.bst = xgb.train(\n            self.xgb_params,\n            dtrain,\n            num_boost_round=400,\n            callbacks=[\n                custom_callback(\n                    stopping_rounds=100,\n                    metric=\"tr-a-recall@%d\" % plan_size,\n                    evals=[(dtrain, \"tr\")],\n                    maximize=True,\n                    fevals=[\n                        xgb_average_recalln_curve_score(plan_size),\n                    ],\n                    verbose_eval=self.log_interval,\n                )\n            ],\n        )\n\n        logger.debug(\"XGB train: %.2f\\tobs: %d\", time.time() - tic, len(xs))\n\n        return True\n\n    def predict(self, xs, output_margin=False):\n        feas = self._get_feature(xs)\n        dtest = xgb.DMatrix(feas)\n\n        if self.base_model:\n            dtest.set_base_margin(\n                self._base_model_discount() * self.base_model.predict(xs, output_margin=True)\n            )\n\n        return self.bst.predict(dtest, output_margin=output_margin)\n\n    def load_basemodel(self, base_model):\n        self.base_model = base_model\n        self.base_model._close_pool()\n        self.base_model.upper_model = self\n\n    def spawn_base_model(self):\n        return XGBoostCostModel(\n            self.task, self.fea_type, self.loss_type, self.num_threads, self.log_interval, self\n        )\n\n    def _get_feature(self, indexes):\n        \"\"\"get features for indexes, run extraction if we do not have cache for them\"\"\"\n        # free feature cache\n        if self.feature_cache.size(self.fea_type) >= 100000:\n            self.feature_cache.clear(self.fea_type)\n\n        fea_cache = self.feature_cache.get(self.fea_type)\n\n        indexes = np.array(indexes)\n        need_extract = [x for x in indexes if x not in fea_cache]\n\n        if need_extract:\n            pool = self._get_pool()\n            feas = pool.map_with_error_catching(self.feature_extract_func, need_extract)\n            for i, fea in zip(need_extract, feas):\n                fea_cache[i] = fea.value if fea.status == StatusKind.COMPLETE else None\n\n        feature_len = -1\n        for idx in indexes:\n            if fea_cache[idx] is not None:\n                feature_len = max(fea_cache[idx].shape[-1], feature_len)\n\n        ret = np.empty((len(indexes), feature_len), dtype=np.float32)\n        for i, ii in enumerate(indexes):\n            t = fea_cache[ii]\n            if t is not None and t.shape[0] < feature_len:\n                t = np.pad(t, (0, feature_len - t.shape[0]))\n            ret[i, :] = t if t is not None else 0\n        return ret\n\n    def __del__(self):\n        self._close_pool()\n\n\n# Global variables for passing arguments to extract functions.\n_extract_space = None\n_extract_target = None\n_extract_task = None\n\n\ndef _extract_popen_initializer(space, target, task):\n    global _extract_space, _extract_target, _extract_task\n    _extract_space = space\n    _extract_target = target\n    _extract_task = task\n\n\ndef _extract_itervar_feature_index(args):\n    \"\"\"extract iteration var feature for an index in extract_space\"\"\"\n    config = _extract_space.get(args)\n    with _extract_target:\n        sch, fargs = _extract_task.instantiate(config)\n\n    fea = feature.get_itervar_feature_flatten(sch, fargs, take_log=True)\n    fea = np.concatenate((fea, list(config.get_other_option().values())))\n    return fea\n\n\ndef _extract_itervar_feature_log(arg):\n    \"\"\"extract iteration var feature for log items\"\"\"\n    inp, res = arg\n    config = inp.config\n    with inp.target:\n        sch, args = inp.task.instantiate(config)\n    fea = feature.get_itervar_feature_flatten(sch, args, take_log=True)\n    x = np.concatenate((fea, list(config.get_other_option().values())))\n\n    if res.error_no == 0:\n        y = inp.task.flop / np.mean(res.costs)\n    else:\n        y = 0.0\n    return x, y\n\n\ndef _extract_knob_feature_index(args):\n    \"\"\"extract knob feature for an index in extract_space\"\"\"\n    config = _extract_space.get(args)\n\n    return config.get_flatten_feature()\n\n\ndef _extract_knob_feature_log(arg):\n    \"\"\"extract knob feature for log items\"\"\"\n    inp, res = arg\n    config = inp.config\n    x = config.get_flatten_feature()\n\n    if res.error_no == 0:\n        with inp.target:  # necessary, for calculating flops of this task\n            inp.task.instantiate(config)\n        y = inp.task.flop / np.mean(res.costs)\n    else:\n        y = 0.0\n    return x, y\n\n\ndef _extract_curve_feature_index(args):\n    \"\"\"extract sampled curve feature for an index in extract_space\"\"\"\n    config = _extract_space.get(args)\n    with _extract_target:\n        sch, fargs = _extract_task.instantiate(config)\n\n    fea = feature.get_buffer_curve_sample_flatten(sch, fargs, sample_n=20)\n    fea = np.concatenate((fea, list(config.get_other_option().values())))\n    return np.array(fea)\n\n\ndef _extract_curve_feature_log(arg):\n    \"\"\"extract sampled curve feature for log items\"\"\"\n    inp, res = arg\n    config = inp.config\n    with inp.target:\n        sch, args = inp.task.instantiate(config)\n    fea = feature.get_buffer_curve_sample_flatten(sch, args, sample_n=20)\n    x = np.concatenate((fea, list(config.get_other_option().values())))\n\n    if res.error_no == 0:\n        y = inp.task.flop / np.mean(res.costs)\n    else:\n        y = 0.0\n    return x, y\n\n\ndef custom_callback(\n    stopping_rounds, metric, fevals, evals=(), log_file=None, maximize=False, verbose_eval=True\n):\n    \"\"\"callback function for xgboost to support multiple custom evaluation functions\"\"\"\n    # pylint: disable=import-outside-toplevel\n    from xgboost.callback import _fmt_metric\n    from xgboost.core import EarlyStopException\n\n    try:\n        from xgboost.training import aggcv\n    except ImportError:\n        from xgboost.callback import _aggcv as aggcv\n\n    state = {}\n    metric_shortname = metric.split(\"-\")[1]\n\n    def init(env):\n        \"\"\"internal function\"\"\"\n        bst = env.model\n\n        state[\"maximize_score\"] = maximize\n        state[\"best_iteration\"] = 0\n        if maximize:\n            state[\"best_score\"] = float(\"-inf\")\n        else:\n            state[\"best_score\"] = float(\"inf\")\n\n        if bst is not None:\n            if bst.attr(\"best_score\") is not None:\n                state[\"best_score\"] = float(bst.attr(\"best_score\"))\n                state[\"best_iteration\"] = int(bst.attr(\"best_iteration\"))\n                state[\"best_msg\"] = bst.attr(\"best_msg\")\n            else:\n                bst.set_attr(best_iteration=str(state[\"best_iteration\"]))\n                bst.set_attr(best_score=str(state[\"best_score\"]))\n        else:\n            assert env.cvfolds is not None\n\n    def callback(env):\n        \"\"\"internal function\"\"\"\n        if not state:\n            init(env)\n\n        bst = env.model\n        i = env.iteration\n        cvfolds = env.cvfolds\n\n        res_dict = {}\n\n        ##### evaluation #####\n        if cvfolds is not None:\n            for feval in fevals:\n                tmp = aggcv([f.eval(i, feval) for f in cvfolds])\n                for k, mean, std in tmp:\n                    res_dict[k] = [mean, std]\n        else:\n            for feval in fevals:\n                bst_eval = bst.eval_set(evals, i, feval)\n                res = [x.split(\":\") for x in bst_eval.split()]\n                for kv in res[1:]:\n                    res_dict[kv[0]] = [float(kv[1])]\n\n        eval_res = []\n        keys = list(res_dict.keys())\n        keys.sort(key=lambda x: x if metric_shortname not in x else \"a\" + x)\n        for key in keys:\n            v = res_dict[key]\n            eval_res.append([key] + v)\n\n        ##### print eval result #####\n        infos = [\"XGB iter: %3d\" % i]\n        for item in eval_res:\n            if \"null\" in item[0]:\n                continue\n            infos.append(\"%s: %.6f\" % (item[0], item[1]))\n\n        if not isinstance(verbose_eval, bool) and verbose_eval and i % verbose_eval == 0:\n            logger.debug(\"\\t\".join(infos))\n        if log_file:\n            with open(log_file, \"a\") as fout:\n                fout.write(\"\\t\".join(infos) + \"\\n\")\n\n        ##### choose score and do early stopping #####\n        score = None\n        for item in eval_res:\n            if item[0] == metric:\n                score = item[1]\n                break\n        assert score is not None\n\n        best_score = state[\"best_score\"]\n        best_iteration = state[\"best_iteration\"]\n        maximize_score = state[\"maximize_score\"]\n        if (maximize_score and score > best_score) or (not maximize_score and score < best_score):\n            msg = \"[%d] %s\" % (env.iteration, \"\\t\".join([_fmt_metric(x) for x in eval_res]))\n            state[\"best_msg\"] = msg\n            state[\"best_score\"] = score\n            state[\"best_iteration\"] = env.iteration\n            # save the property to attributes, so they will occur in checkpoint.\n            if env.model is not None:\n                env.model.set_attr(\n                    best_score=str(state[\"best_score\"]),\n                    best_iteration=str(state[\"best_iteration\"]),\n                    best_msg=state[\"best_msg\"],\n                )\n        elif env.iteration - best_iteration >= stopping_rounds:\n            best_msg = state[\"best_msg\"]\n            if verbose_eval and env.rank == 0:\n                logger.debug(\"XGB stopped. Best iteration: %s \", best_msg)\n            raise EarlyStopException(best_iteration)\n\n    return callback\n\n\n# feval wrapper for xgboost\ndef xgb_max_curve_score(N):\n    \"\"\"evaluate max curve score for xgb\"\"\"\n\n    def feval(preds, labels):\n        labels = labels.get_label()\n        trials = np.argsort(preds)[::-1]\n        scores = labels[trials]\n        curve = max_curve(scores)\n        return \"Smax@%d\" % N, curve[N] / np.max(labels)\n\n    return feval\n\n\ndef xgb_recalln_curve_score(N):\n    \"\"\"evaluate recall-n curve score for xgb\"\"\"\n\n    def feval(preds, labels):\n        labels = labels.get_label()\n        trials = np.argsort(preds)[::-1]\n        ranks = get_rank(labels[trials])\n        curve = recall_curve(ranks)\n        return \"recall@%d\" % N, curve[N]\n\n    return feval\n\n\ndef xgb_average_recalln_curve_score(N):\n    \"\"\"evaluate average recall-n curve score for xgb\"\"\"\n\n    def feval(preds, labels):\n        labels = labels.get_label()\n        trials = np.argsort(preds)[::-1]\n        ranks = get_rank(labels[trials])\n        curve = recall_curve(ranks)\n        return \"a-recall@%d\" % N, np.sum(curve[:N]) / N\n\n    return feval\n\n\ndef xgb_recallk_curve_score(N, topk):\n    \"\"\"evaluate recall-k curve score for xgb\"\"\"\n\n    def feval(preds, labels):\n        labels = labels.get_label()\n        trials = np.argsort(preds)[::-1]\n        ranks = get_rank(labels[trials])\n        curve = recall_curve(ranks, topk)\n        return \"recall@%d\" % topk, curve[N]\n\n    return feval\n\n\ndef xgb_cover_curve_score(N):\n    \"\"\"evaluate cover curve score for xgb\"\"\"\n\n    def feval(preds, labels):\n        labels = labels.get_label()\n        trials = np.argsort(preds)[::-1]\n        ranks = get_rank(labels[trials])\n        curve = cover_curve(ranks)\n        return \"cover@%d\" % N, curve[N]\n\n    return feval\n\n\ndef xgb_null_score(_):\n    \"\"\"empty score function for xgb\"\"\"\n\n    def feval(__, ___):\n        return \"null\", 0\n\n    return feval\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/tuner/xgboost_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tuner that uses xgboost as cost model\"\"\"\n\nfrom .model_based_tuner import ModelBasedTuner, ModelOptimizer\nfrom .xgboost_cost_model import XGBoostCostModel\nfrom .sa_model_optimizer import SimulatedAnnealingOptimizer\n\n\nclass XGBTuner(ModelBasedTuner):\n    \"\"\"Tuner that uses xgboost as cost model\n\n    Parameters\n    ----------\n    task: Task\n        The tuning task\n    plan_size: int\n        The size of a plan. After `plan_size` trials, the tuner will refit a new cost model\n        and do planing for the next `plan_size` trials.\n    feature_type: str, optional\n        If is 'itervar', use features extracted from IterVar (loop variable).\n        If is 'knob', use flatten ConfigEntity directly.\n        If is 'curve', use sampled curve feature (relation feature).\n\n        Note on choosing feature type:\n        For single task tuning, 'itervar' and 'knob' are good.\n        'itervar' is more accurate but 'knob' is much faster.\n        There are some constraints on 'itervar', if you meet\n        problems with feature extraction when using 'itervar',\n        you can switch to 'knob'.\n\n        For cross-shape tuning (e.g. many convolutions with different shapes),\n        'itervar' and 'curve' has better transferability,\n        'knob' is faster.\n\n        For cross-device or cross-operator tuning, you can use 'curve' only.\n    loss_type: str\n        If is 'reg', use regression loss to train cost model.\n        The cost model predicts the normalized flops.\n        If is 'rank', use pairwise rank loss to train cost model.\n        The cost model predicts relative rank score.\n\n    num_threads: int, optional\n        The number of threads.\n\n    optimizer: str or ModelOptimizer, optional\n        If is 'sa', use a default simulated annealing optimizer.\n        Otherwise it should be a ModelOptimizer object.\n\n    diversity_filter_ratio: int or float, optional\n        If is not None, the tuner will first select\n        top-(plan_size * diversity_filter_ratio) candidates according to the cost model\n        and then pick batch_size of them according to the diversity metric.\n\n    log_interval: int = 50\n        The verbose level.\n        If is 0, output nothing.\n        Otherwise, output debug information every `verbose` iterations.\n    \"\"\"\n\n    def __init__(\n        self,\n        task,\n        plan_size=64,\n        feature_type=\"itervar\",\n        loss_type=\"rank\",\n        num_threads=None,\n        optimizer=\"sa\",\n        diversity_filter_ratio=None,\n        log_interval=50,\n    ):\n        cost_model = XGBoostCostModel(\n            task,\n            feature_type=feature_type,\n            loss_type=loss_type,\n            num_threads=num_threads,\n            log_interval=log_interval // 2,\n        )\n        if optimizer == \"sa\":\n            optimizer = SimulatedAnnealingOptimizer(task, log_interval=log_interval)\n        else:\n            assert isinstance(optimizer, ModelOptimizer), (\n                \"Optimizer must be \" \"a supported name string\" \"or a ModelOptimizer object.\"\n            )\n\n        super(XGBTuner, self).__init__(\n            task, cost_model, optimizer, plan_size, diversity_filter_ratio\n        )\n\n    def tune(self, *args, **kwargs):  # pylint: disable=arguments-differ\n        super(XGBTuner, self).tune(*args, **kwargs)\n\n        # manually close pool to avoid multiprocessing issues\n        self.cost_model._close_pool()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/autotvm/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Utilities\"\"\"\nimport logging\nimport time\n\nimport numpy as np\nimport tvm.arith\nfrom tvm.tir import expr\nfrom tvm.contrib.popen_pool import PopenPoolExecutor\n\nlogger = logging.getLogger(\"autotvm\")\n\n\nclass EmptyContext(object):\n    \"\"\"An empty context\"\"\"\n\n    def __enter__(self):\n        pass\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        pass\n\n\ndef get_rank(values):\n    \"\"\"get rank of items\n\n    Parameters\n    ----------\n    values: Array\n\n    Returns\n    -------\n    ranks: Array of int\n        the rank of this item in the input (the largest value ranks first)\n    \"\"\"\n    tmp = np.argsort(-values)\n    ranks = np.empty_like(tmp)\n    ranks[tmp] = np.arange(len(tmp))\n    return ranks\n\n\ndef pool_map(func, args, batch_size, verbose=False, pool=None):\n    \"\"\"A wrapper of multiprocessing.pool.Pool.map to support small-batch mapping\n    for large argument list. This can reduce memory usage\n\n    Parameters\n    ----------\n    func: Func(arg) -> np.ndarray\n        mapping function\n    args: List\n        list of arguments\n    batch_size: int\n        batch size in mapping\n    verbose: bool, optional\n        whether print progress\n    pool: multiprocessing.Pool, optional\n        pool objection\n\n    Returns\n    -------\n    converted numpy array\n    \"\"\"\n\n    ret = None\n    tic = time.time()\n    local_pool = pool or PopenPoolExecutor()\n    if verbose:\n        logger.info(\"mapping begin\")\n    for i in range(0, len(args), batch_size):\n        if verbose:\n            logger.info(\"mapping %d/%d elapsed %.2f\", i, len(args), time.time() - tic)\n        tmp = np.array(local_pool.map(func, args[i : i + batch_size]))\n        ret = tmp if ret is None else np.concatenate((ret, tmp))\n    if verbose:\n        logger.info(\"mapping done\")\n    if not pool:\n        local_pool.close()\n    return ret\n\n\ndef get_func_name(func):\n    \"\"\"Get name of a function\n\n    Parameters\n    ----------\n    func: Function\n        The function\n    Returns\n    -------\n    name: str\n        The name\n    \"\"\"\n\n    return func.func_name if hasattr(func, \"func_name\") else func.__name__\n\n\ndef get_const_int(exp):\n    \"\"\"Verifies expr is integer and get the constant value.\n\n    Parameters\n    ----------\n    exp : tvm.Expr or int\n        The input expression.\n\n    Returns\n    -------\n    out_value : int\n        The output.\n    \"\"\"\n    if isinstance(exp, int):\n        return exp\n    if not isinstance(exp, (expr.IntImm,)):\n        ana = tvm.arith.Analyzer()\n        exp = ana.simplify(exp)\n    if not isinstance(exp, (expr.IntImm,)):\n        raise ValueError(\"Expect value to be constant int\")\n    return exp.value\n\n\ndef get_const_tuple(in_tuple):\n    \"\"\"Verifies input tuple is IntImm or Var, returns tuple of int or Var.\n\n    Parameters\n    ----------\n    in_tuple : tuple of Expr\n        The input.\n\n    Returns\n    -------\n    out_tuple : tuple of int\n        The output.\n    \"\"\"\n    ret = []\n    for elem in in_tuple:\n        if isinstance(elem, expr.Var):\n            ret.append(elem)\n        elif not isinstance(elem, (expr.IntImm, int)):\n            ana = tvm.arith.Analyzer()\n            elem = ana.simplify(elem)\n            if not isinstance(elem, (expr.IntImm)):\n                ret.append(elem)\n        else:\n            ret.append(get_const_int(elem))\n    return tuple(ret)\n\n\nSI_PREFIXES = \"yzafpn\\xb5m kMGTPEZY\"\nYOCTO_EXP10 = -24\n\n\ndef format_si_prefix(x, si_prefix):\n    exp10 = 10 ** (SI_PREFIXES.index(si_prefix) * 3 + YOCTO_EXP10)\n    return float(x) / exp10\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Contrib APIs of TVM python package.\n\nContrib API provides many useful not core features.\nSome of these are useful utilities to interact with\nthirdparty libraries and tools.\n\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cblas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to BLAS libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef matmul(lhs, rhs, transa=False, transb=False, **kwargs):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with CrhsLAS\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cblas.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n\n\ndef batch_matmul(lhs, rhs, transa=False, transb=False, iterative=False, **kwargs):\n    \"\"\"Create an extern op that compute batched matrix mult of A and rhs with CBLAS\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    b = te.max(lhs.shape[0], rhs.shape[0])\n    n = lhs.shape[2] if transa else lhs.shape[1]\n    m = rhs.shape[1] if transb else rhs.shape[2]\n    return te.extern(\n        (b, n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cblas.batch_matmul\"\n            if not iterative\n            else \"tvm.contrib.cblas.batch_matmul_iterative\",\n            ins[0],\n            ins[1],\n            outs[0],\n            transa,\n            transb,\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Util to invoke C/C++ compilers in the system.\"\"\"\n# pylint: disable=invalid-name\nimport sys\nimport os\nimport subprocess\n\nfrom .._ffi.base import py_str\n\n\ndef _is_linux_like():\n    return (\n        sys.platform == \"darwin\"\n        or sys.platform.startswith(\"linux\")\n        or sys.platform.startswith(\"freebsd\")\n    )\n\n\ndef get_cc():\n    \"\"\"Return the path to the default C/C++ compiler.\n\n    Returns\n    -------\n    out: Optional[str]\n        The path to the default C/C++ compiler, or None if none was found.\n    \"\"\"\n\n    if not _is_linux_like():\n        return None\n\n    env_cxx = os.environ.get(\"CXX\") or os.environ.get(\"CC\")\n    if env_cxx:\n        return env_cxx\n    cc_names = [\"g++\", \"gcc\", \"clang++\", \"clang\", \"c++\", \"cc\"]\n    dirs_in_path = os.get_exec_path()\n    for cc in cc_names:\n        for d in dirs_in_path:\n            cc_path = os.path.join(d, cc)\n            if os.path.isfile(cc_path) and os.access(cc_path, os.X_OK):\n                return cc_path\n    return None\n\n\ndef create_shared(output, objects, options=None, cc=None):\n    \"\"\"Create shared library.\n\n    Parameters\n    ----------\n    output : str\n        The target shared library.\n\n    objects : List[str]\n        List of object files.\n\n    options : List[str]\n        The list of additional options string.\n\n    cc : Optional[str]\n        The compiler command.\n    \"\"\"\n    cc = cc or get_cc()\n\n    if _is_linux_like():\n        _linux_compile(output, objects, options, cc, compile_shared=True)\n    elif sys.platform == \"win32\":\n        _windows_compile(output, objects, options)\n    else:\n        raise ValueError(\"Unsupported platform\")\n\n\ndef create_executable(output, objects, options=None, cc=None):\n    \"\"\"Create executable binary.\n\n    Parameters\n    ----------\n    output : str\n        The target executable.\n\n    objects : List[str]\n        List of object files.\n\n    options : List[str]\n        The list of additional options string.\n\n    cc : Optional[str]\n        The compiler command.\n    \"\"\"\n    cc = cc or get_cc()\n\n    if _is_linux_like():\n        _linux_compile(output, objects, options, cc)\n    elif sys.platform == \"win32\":\n        _windows_compile(output, objects, options)\n    else:\n        raise ValueError(\"Unsupported platform\")\n\n\ndef get_target_by_dump_machine(compiler):\n    \"\"\"Functor of get_target_triple that can get the target triple using compiler.\n\n    Parameters\n    ----------\n    compiler : Optional[str]\n        The compiler.\n\n    Returns\n    -------\n    out: Callable\n        A function that can get target triple according to dumpmachine option of compiler.\n    \"\"\"\n\n    def get_target_triple():\n        \"\"\"Get target triple according to dumpmachine option of compiler.\"\"\"\n        if compiler:\n            cmd = [compiler, \"-dumpmachine\"]\n            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n            (out, _) = proc.communicate()\n            if proc.returncode != 0:\n                msg = \"dumpmachine error:\\n\"\n                msg += py_str(out)\n                return None\n            return py_str(out)\n        return None\n\n    return get_target_triple\n\n\n# assign so as default output format\ncreate_shared.output_format = \"so\" if sys.platform != \"win32\" else \"dll\"\ncreate_shared.get_target_triple = get_target_by_dump_machine(os.environ.get(\"CXX\", get_cc()))\n\n\ndef cross_compiler(\n    compile_func, options=None, output_format=None, get_target_triple=None, add_files=None\n):\n    \"\"\"Create a cross compiler function by specializing compile_func with options.\n\n    This function can be used to construct compile functions that\n    can be passed to AutoTVM measure or export_library.\n\n\n    Parameters\n    ----------\n    compile_func : Union[str, Callable[[str, str, Optional[str]], None]]\n        Function that performs the actual compilation\n\n    options : Optional[List[str]]\n        List of additional optional string.\n\n    output_format : Optional[str]\n        Library output format.\n\n    get_target_triple: Optional[Callable]\n        Function that can target triple according to dumpmachine option of compiler.\n\n    add_files: Optional[List[str]]\n        List of paths to additional object, source, library files\n        to pass as part of the compilation.\n\n    Returns\n    -------\n    fcompile : Callable[[str, str, Optional[str]], None]\n        A compilation function that can be passed to export_library.\n\n    Examples\n    --------\n    .. code-block:: python\n\n       from tvm.contrib import cc, ndk\n       # export using arm gcc\n       mod = build_runtime_module()\n       mod.export_library(path_dso,\n                          cc.cross_compiler(\"arm-linux-gnueabihf-gcc\"))\n       # specialize ndk compilation options.\n       specialized_ndk = cc.cross_compiler(\n           ndk.create_shared,\n           [\"--sysroot=/path/to/sysroot\", \"-shared\", \"-fPIC\", \"-lm\"])\n       mod.export_library(path_dso, specialized_ndk)\n    \"\"\"\n    base_options = [] if options is None else options\n    kwargs = {}\n    add_files = [] if add_files is None else add_files\n\n    # handle case where compile_func is the name of the cc\n    if isinstance(compile_func, str):\n        kwargs = {\"cc\": compile_func}\n        compile_func = create_shared\n\n    def _fcompile(outputs, objects, options=None):\n        all_options = base_options\n        if options is not None:\n            all_options += options\n        compile_func(outputs, objects + add_files, options=all_options, **kwargs)\n\n    if not output_format and hasattr(compile_func, \"output_format\"):\n        output_format = compile_func.output_format\n    output_format = output_format if output_format else \"so\"\n\n    if not get_target_triple and hasattr(compile_func, \"get_target_triple\"):\n        get_target_triple = compile_func.get_target_triple\n\n    _fcompile.output_format = output_format\n    _fcompile.get_target_triple = get_target_triple\n    return _fcompile\n\n\ndef _linux_compile(output, objects, options, compile_cmd, compile_shared=False):\n    cmd = [compile_cmd]\n    if compile_cmd != \"nvcc\":\n        if compile_shared or output.endswith(\".so\") or output.endswith(\".dylib\"):\n            cmd += [\"-shared\", \"-fPIC\"]\n            if sys.platform == \"darwin\":\n                cmd += [\"-undefined\", \"dynamic_lookup\"]\n        elif output.endswith(\".obj\"):\n            cmd += [\"-c\"]\n    else:\n        if compile_shared or output.endswith(\".so\") or output.endswith(\".dylib\"):\n            cmd += [\"--shared\"]\n    cmd += [\"-o\", output]\n    if isinstance(objects, str):\n        cmd += [objects]\n    else:\n        cmd += objects\n    if options:\n        cmd += options\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += py_str(out)\n        msg += \"\\nCommand line: \" + \" \".join(cmd)\n        raise RuntimeError(msg)\n\n\ndef _windows_compile(output, objects, options):\n    cmd = [\"clang\"]\n    cmd += [\"-O2\"]\n\n    if output.endswith(\".so\") or output.endswith(\".dll\"):\n        cmd += [\"-shared\"]\n    elif output.endswith(\".obj\"):\n        cmd += [\"-c\"]\n\n    if isinstance(objects, str):\n        objects = [objects]\n    cmd += [\"-o\", output]\n    cmd += objects\n    if options:\n        cmd += options\n\n    try:\n        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        (out, _) = proc.communicate()\n    except FileNotFoundError:\n        raise RuntimeError(\n            \"Can not find the LLVM clang for Windows clang.exe).\"\n            \"Make sure it's installed\"\n            \" and the installation directory is in the %PATH% environment \"\n            \"variable. Prebuilt binaries can be found at: https://llvm.org/\"\n        )\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += \" \".join(cmd) + \"\\n\"\n        msg += py_str(out)\n\n        raise RuntimeError(msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/clang.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Util to invoke clang in the system.\"\"\"\n# pylint: disable=invalid-name\nimport subprocess\n\nfrom tvm._ffi.base import py_str\nimport tvm.target\nfrom . import utils\n\n\ndef find_clang(required=True):\n    \"\"\"Find clang in system.\n\n    Parameters\n    ----------\n    required : bool\n        Whether it is required,\n        runtime error will be raised if the compiler is required.\n\n    Returns\n    -------\n    valid_list : list of str\n        List of possible paths.\n\n    Note\n    ----\n    This function will first search clang that\n    matches the major llvm version that built with tvm\n    \"\"\"\n    cc_list = []\n    major = tvm.target.codegen.llvm_version_major(allow_none=True)\n    if major is not None:\n        cc_list += [\"clang-%d.0\" % major]\n        cc_list += [\"clang-%d\" % major]\n    cc_list += [\"clang\"]\n    cc_list += [\"clang.exe\"]\n    valid_list = [utils.which(x) for x in cc_list]\n    valid_list = [x for x in valid_list if x]\n    if not valid_list and required:\n        raise RuntimeError(\"cannot find clang, candidates are: \" + str(cc_list))\n    return valid_list\n\n\ndef create_llvm(inputs, output=None, options=None, cc=None):\n    \"\"\"Create llvm text ir.\n\n    Parameters\n    ----------\n    inputs : list of str\n        List of input files name or code source.\n\n    output : str, optional\n        Output file, if it is none\n        a temporary file is created\n\n    options : list\n        The list of additional options string.\n\n    cc : str, optional\n        The clang compiler, if not specified,\n        we will try to guess the matched clang version.\n\n    Returns\n    -------\n    code : str\n        The generated llvm text IR.\n    \"\"\"\n    cc = cc if cc else find_clang()[0]\n    cmd = [cc]\n    cmd += [\"-S\", \"-emit-llvm\"]\n    temp = utils.tempdir()\n    output = output if output else temp.relpath(\"output.ll\")\n    inputs = [inputs] if isinstance(inputs, str) else inputs\n    input_files = []\n    for i, code in enumerate(inputs):\n        if utils.is_source_path(code):\n            input_files.append(code)\n        else:\n            temp_path = temp.relpath(\"input%d.cc\" % i)\n            with open(temp_path, \"w\") as output_file:\n                output_file.write(code)\n            input_files.append(temp_path)\n    if options:\n        cmd += options\n    cmd += [\"-o\", output]\n    cmd += input_files\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n    return open(output).read()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/coreml_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"CoreML runtime that load and run coreml models.\"\"\"\nimport tvm._ffi\nfrom ..rpc import base as rpc_base\n\n\ndef create(symbol, compiled_model_path, device):\n    \"\"\"Create a runtime executor module given a coreml model and context.\n    Parameters\n    ----------\n    symbol : str\n        The symbol that represents the Core ML model.\n    compiled_model_path : str\n        The path of the compiled model to be deployed.\n    device : Device\n        The device to deploy the module. It can be local or remote when there\n        is only one Device.\n    Returns\n    -------\n    coreml_runtime : CoreMLModule\n        Runtime coreml module that can be used to execute the coreml model.\n    \"\"\"\n    device_type = device.device_type\n    runtime_func = \"tvm.coreml_runtime.create\"\n\n    if device_type >= rpc_base.RPC_SESS_MASK:\n        fcreate = device._rpc_sess.get_function(runtime_func)\n    else:\n        fcreate = tvm._ffi.get_global_func(runtime_func)\n\n    return CoreMLModule(fcreate(symbol, compiled_model_path))\n\n\nclass CoreMLModule(object):\n    \"\"\"Wrapper runtime module.\n\n    This is a thin wrapper of the underlying TVM module.\n    you can also directly call set_input, run, and get_output\n    of underlying module functions\n\n    Parameters\n    ----------\n    module : Module\n        The internal tvm module that holds the actual coreml functions.\n\n    Attributes\n    ----------\n    module : Module\n        The internal tvm module that holds the actual coreml functions.\n    \"\"\"\n\n    def __init__(self, module):\n        self.module = module\n        self.invoke = module[\"invoke\"]\n        self.set_input = module[\"set_input\"]\n        self.get_output = module[\"get_output\"]\n        self.get_num_outputs = module[\"get_num_outputs\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cublas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to cuBLAS libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef matmul(lhs, rhs, transa=False, transb=False, dtype=None):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with cuBLAS\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left matrix operand\n    rhs : Tensor\n        The right matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    dtype = dtype if dtype is not None else lhs.dtype\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cublas.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        dtype=dtype,\n        name=\"matmul_cublas\",\n    )\n\n\ndef batch_matmul(lhs, rhs, transa=False, transb=False, dtype=None):\n    \"\"\"Create an extern op that compute batch matrix mult of A and rhs with cuBLAS\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left matrix operand\n    rhs : Tensor\n        The right matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    b = lhs.shape[0]\n    n = lhs.shape[2] if transa else lhs.shape[1]\n    m = rhs.shape[1] if transb else rhs.shape[2]\n    dtype = dtype if dtype is not None else lhs.dtype\n    return te.extern(\n        (b, n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cublas.batch_matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        dtype=dtype,\n        name=\"batch_matmul_cublas\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cublaslt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to cuBLASlt libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef matmul(lhs, rhs, transa=False, transb=False, n=0, m=0, dtype=None):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with cuBLAS\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left matrix operand\n    rhs : Tensor\n        The right matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    if n == 0:\n        n = lhs.shape[1] if transa else lhs.shape[0]\n    if m == 0:\n        m = rhs.shape[0] if transb else rhs.shape[1]\n    dtype = dtype if dtype is not None else lhs.dtype\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cublaslt.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        dtype=dtype,\n        name=\"C\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cuda_graph/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cuda_graph/cuda_graph_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Graph executor with CUDA Graph\"\"\"\nimport tvm._ffi\n\nfrom tvm._ffi.base import string_types\nfrom tvm.contrib import graph_executor\n\n\ndef create(graph_json_str, libmod, device):\n    \"\"\"Create a runtime executor module given a graph and module.\n\n    Parameters\n    ----------\n    graph_json_str : str\n        The graph to be deployed in json format output by json graph.\n        The graph can contain operator(tvm_op) that points to the name\n        of PackedFunc in the libmod.\n\n    libmod : tvm.runtime.Module\n        The module of the corresponding function\n\n    device : Device\n        The device to deploy the module, only supports CUDA GPU\n\n    Returns\n    -------\n    graph_module : GraphModuleCudaGraph\n        CUDA graph executor module that can be used to execute the graph.\n\n    Note\n    ----\n    See also :py:class:`tvm.contrib.cuda_graph.cuda_graph_executor.GraphModuleCudaGraph`\n    for examples to directly construct a GraphModuleCudaGraph from an exported\n    relay compiled library.\n    \"\"\"\n    assert isinstance(graph_json_str, string_types)\n    try:\n        dev, num_rpc_dev, device_type_id = graph_executor.get_device(libmod, device)\n        if num_rpc_dev == len(dev):\n            fcreate = dev[0]._rpc_sess.get_function(\"tvm.graph_executor_cuda_graph.create\")\n        else:\n            fcreate = tvm._ffi.get_global_func(\"tvm.graph_executor_cuda_graph.create\")\n    except ValueError:\n        raise ValueError(\n            \"To enable CUDA graph support (experimental), please set \"\n            \"'(USE_GRAPH_EXECUTOR_CUGRAPH ON)' in config.cmake and rebuild TVM\"\n        )\n\n    return GraphModuleCudaGraph(fcreate(graph_json_str, libmod, *device_type_id))\n\n\nclass GraphModuleCudaGraph(graph_executor.GraphModule):\n    \"\"\"CUDA graph executor module.\n\n    This is a CUDA graph executor wrapper over the TVM runtime.\n    Runtime interfaces are wrapped with CUDA graph functionalities.\n\n    Parameters\n    ----------\n    module : Module\n        The internal tvm module that holds the actual graph functions.\n    \"\"\"\n\n    def __init__(self, module):\n        self._start_capture = module[\"start_capture\"]\n        self._end_capture = module[\"end_capture\"]\n        self._run_cuda_graph = module[\"run_cuda_graph\"]\n        self._cuda_graph_captured = False\n        graph_executor.GraphModule.__init__(self, module)\n\n    def capture_cuda_graph(self):\n        \"\"\"Capture a CUDA graph for tvm_op graph\n\n        This should be called before run_cuda_graph() to capture and\n        instantiate a CUDA graph instance.\n        \"\"\"\n        self._run()  # call cuModuleLoadData before cudaStream API\n        self._start_capture()\n        self._run()\n        self._end_capture()\n        self._cuda_graph_captured = True\n\n    def run_cuda_graph(self):\n        \"\"\"Run the CUDA graph for tvm_op graph\n\n        Run the captured CUDA graph instance instead of the\n        for-loop kernel launch of default graph executor\n        \"\"\"\n        self._run_cuda_graph()\n\n    def run(self, **input_dict):\n        \"\"\"A run wrapper for graph capture / launch, user can just\n        change default graph executor to cuda graph executor, and\n        the first call will capture a cuda graph for future launch\n\n        Parameters\n        ----------\n        input_dict: dict of str to NDArray\n            List of input values to be feed to\n        \"\"\"\n        if input_dict:\n            self.set_input(**input_dict)\n        if not self._cuda_graph_captured:\n            self.capture_cuda_graph()\n        else:\n            self._run_cuda_graph()\n\n    def debug_get_output(self, node, out):\n        \"\"\"Run graph up to node and get the output to out\n\n        Parameters\n        ----------\n        node : int / str\n            The node index or name\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        raise NotImplementedError(\"Please use debugger.debug_executor as graph_executor instead.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cudnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to CuDNN v7 library.\"\"\"\n# pylint: disable-msg=C0103\nimport ctypes\nimport numpy as np\nimport tvm\n\nimport tvm._ffi\nfrom tvm import te\n\n# algos can be read from cudnn.h\n_FWD_ALGOS = [\n    \"CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_GEMM\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_DIRECT\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_FFT\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED\",\n    \"CUDNN_CONVOLUTION_FWD_ALGO_COUNT\",\n]\n\n\ndef exists():\n    \"\"\"\n    Checks whether the local machine can use CuDNN.\n\n    Returns\n    -------\n        exists: bool\n\n            True if CuDNN support is enabled and a CuDNN-capable GPU\n            exists.  Otherwise, False.\n    \"\"\"\n    func = tvm.get_global_func(\"tvm.contrib.cudnn.exists\", allow_missing=True)\n    if func is None:\n        return False\n\n    return bool(func())\n\n\ndef algo_to_index(algo_type, algo_name):\n    \"\"\"Return a index represents the algorithm, which can be used in\n    calling CuDNN function\n\n    Parameters\n    ----------\n        algo_type : str\n            [\"fwd\", \"bwd_filter\", \"bwd_data]\n\n        algo_name : str\n            algorithm name in cudnn definition\n            fwd = [\n                \"CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_GEMM\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_DIRECT\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_FFT\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED\",\n                \"CUDNN_CONVOLUTION_FWD_ALGO_COUNT\",\n            ]\n            bwd_filter = [\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0\",\n                # non-deterministic\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1\",\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT\",\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3\",\n                # non-deterministic, algo0 with workspaceS\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD\",\n                # not implemented\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED\",\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING\",\n                \"CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT\",\n            ]\n            bwd_data = [\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_0\",\n                # non-deterministic\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_1\",\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT\",\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING\",\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD\",\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED\",\n                \"CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT\",\n            ]\n\n    Returns\n    -------\n        algo: int\n            algorithm index\n\n    \"\"\"\n    idx = -1\n    if algo_type == \"fwd\":\n        idx = _FWD_ALGOS.index(algo_name)\n    elif algo_type == \"bwd_filter\":\n        idx = _BWD_FILTER_ALGOS.index(algo_name)\n    elif algo_type == \"bwd_data\":\n        idx = _BWD_DATA_ALGOS.index(algo_name)\n    assert idx >= 0\n    return idx\n\n\ndef _get_np_int32_array_handle(arr):\n    \"\"\"Return a void_p handle for a numpy array\n\n    Parameters\n    ----------\n    arr: numpy.NDArray\n        source numpy array\n\n    Returns\n    -------\n    ptr:  ctypes.c_void_p\n        pointer to the data\n    \"\"\"\n    assert arr.dtype == np.int32\n    ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))\n    return ctypes.cast(ptr, ctypes.c_void_p)\n\n\ndef _prepare_global_func_params(dims, pad, stride, dilation, x_shape=None, w_shape=None):\n    full_dims = dims + 2\n    if x_shape:\n        assert isinstance(x_shape, list)\n        assert len(x_shape) == full_dims\n    if w_shape:\n        assert isinstance(w_shape, list)\n        assert len(w_shape) == full_dims\n\n    pad = (\n        np.full(dims, pad, dtype=np.int32)\n        if isinstance(pad, int)\n        else np.array(pad, dtype=np.int32)\n    )\n    stride = (\n        np.full(dims, stride, dtype=np.int32)\n        if isinstance(stride, int)\n        else np.array(stride, dtype=np.int32)\n    )\n    dilation = (\n        np.full(dims, dilation, dtype=np.int32)\n        if isinstance(dilation, int)\n        else np.array(dilation, dtype=np.int32)\n    )\n\n    xshape = np.array(x_shape, dtype=np.int32) if x_shape else None\n    wshape = np.array(w_shape, dtype=np.int32) if x_shape else None\n\n    return pad, stride, dilation, xshape, wshape\n\n\ndef conv_output_shape(\n    tensor_format, pad, stride, dilation, x_shape, w_shape, data_dtype, conv_dtype, groups=1\n):\n    \"\"\"Get output shape of 2D or 3D convolution\n\n    Paramters\n    ---------\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n        2: CUDNN_TENSOR_NCHW_VECT_C\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    x_shape: list\n        input shape\n    w_shape: list\n        weight shape\n    data_dtype: str\n        data type\n    conv_dtype: str\n        convolution type\n    groups: int\n        number of groups\n\n    Returns\n    -------\n    oshape: list\n        output shape\n    \"\"\"\n\n    assert len(x_shape) == len(w_shape)\n    assert len(x_shape) in (4, 5)\n\n    if tensor_format == 0:\n        n_output = x_shape[0]\n        c_output = w_shape[0]\n        x_chan = x_shape[1]\n        w_chan_input = w_shape[1]\n        x_shape = x_shape[2:]\n        w_shape = w_shape[2:]\n\n    elif tensor_format == 1:\n        n_output = x_shape[0]\n        c_output = w_shape[0]\n        x_chan = x_shape[-1]\n        w_chan_input = w_shape[-1]\n        assert len(x_shape) == 4, \"CuDNN layout NHWC is only well-defined for 4d tensors\"\n        x_shape = x_shape[1:-1]\n        w_shape = w_shape[1:-1]\n\n    elif tensor_format == 2:\n        n_output = x_shape[0]\n        c_output = w_shape[0]\n        x_chan = x_shape[1]\n        w_chan_input = w_shape[1]\n        w_lanes = tvm.runtime.DataType(conv_dtype).lanes\n        assert w_lanes == 1\n        x_shape = x_shape[2:]\n        w_shape = w_shape[2:]\n\n    else:\n        raise ValueError(\"Unknown CuDNN tensor format: '{}'\".format(tensor_format))\n\n    x_lanes = tvm.runtime.DataType(data_dtype).lanes\n    assert x_chan * x_lanes == w_chan_input * groups, (\n        \"Mismatched dimensions, data has {} channels/group \"\n        \"(dimension {} with {} lanes/value, {} groups), \"\n        \"but weights require {} input channels/group\"\n    ).format(x_chan // groups, x_chan, x_lanes, groups, w_chan_input)\n\n    output_dims = []\n    for x_shape_i, w_shape_i, pad_i, stride_i, dilation_i in zip(\n        x_shape, w_shape, pad, stride, dilation\n    ):\n        output_dim = 1 + (x_shape_i + 2 * pad_i - (((w_shape_i - 1) * dilation_i) + 1)) // stride_i\n        output_dims.append(output_dim)\n\n    if tensor_format in [0, 2]:\n        output = [n_output, c_output, *output_dims]\n    elif tensor_format == 1:\n        output = [n_output, *output_dims, c_output]\n    else:\n        raise ValueError(\"Unknown CuDNN tensor format: '{}'\".format(tensor_format))\n\n    return output\n\n\ndef conv_dgrad_shape(\n    tensor_format, pad, stride, dilation, dy_shape, w_shape, output_padding=(0, 0), groups=1\n):\n    \"\"\"Get output shape of conv2d gradient with respect to data\n\n    Paramters\n    ---------\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    dy_shape: list\n        output gradient shape\n    w_shape: list\n        weight shape\n    data_dtype: str\n        data type\n    conv_dtype: str\n        convolution type\n    groups: int\n        number of groups\n\n    Returns\n    -------\n    oshape: list\n        output shape\n    \"\"\"\n\n    assert len(dy_shape) == len(w_shape)\n    assert len(dy_shape) == 4\n\n    if tensor_format == 0:\n        N = dy_shape[0]\n        C = w_shape[1] * groups\n        dy_shape = dy_shape[2:]\n        w_shape = w_shape[2:]\n    elif tensor_format == 1:\n        N = dy_shape[0]\n        C = w_shape[-1] * groups\n        dy_shape = dy_shape[1:-1]\n        w_shape = w_shape[1:-1]\n    else:\n        raise ValueError(\"Unsupported CuDNN tensor format: '{}'\".format(tensor_format))\n\n    input_dims = []\n    for dy_shape_i, w_shape_i, pad_i, stride_i, dilation_i, out_pad in zip(\n        dy_shape, w_shape, pad, stride, dilation, output_padding\n    ):\n        input_dim = (\n            (dy_shape_i - 1) * stride_i - 2 * pad_i + (((w_shape_i - 1) * dilation_i) + 1) + out_pad\n        )\n        input_dims.append(input_dim)\n\n    if tensor_format == 0:\n        output = [N, C, *input_dims]\n    else:\n        output = [N, *input_dims, C]\n\n    return output\n\n\ndef _conv_find_algo(\n    func_name,\n    tensor_format,\n    pad,\n    stride,\n    dilation,\n    x_shape,\n    w_shape,\n    y_shape,\n    data_dtype,\n    conv_dtype,\n    groups=1,\n):\n    \"\"\"\n    Common function to choose the best cudnn convolution algorithm for the given input\n    and the convolution type.\n    \"\"\"\n    dims = len(x_shape)\n    assert dims in (4, 5)\n\n    pad, stride, dilation, xshape, wshape = _prepare_global_func_params(\n        dims - 2, pad, stride, dilation, x_shape, w_shape\n    )\n    yshape = np.array(y_shape, dtype=np.int32)\n    func = tvm._ffi.get_global_func(func_name)\n    return func(\n        tensor_format,\n        dims - 2,\n        _get_np_int32_array_handle(pad),\n        _get_np_int32_array_handle(stride),\n        _get_np_int32_array_handle(dilation),\n        _get_np_int32_array_handle(xshape),\n        _get_np_int32_array_handle(wshape),\n        _get_np_int32_array_handle(yshape),\n        data_dtype,\n        conv_dtype,\n        groups,\n    )\n\n\ndef conv_forward_find_algo(\n    tensor_format,\n    pad,\n    stride,\n    dilation,\n    x_shape,\n    w_shape,\n    y_shape,\n    data_dtype,\n    conv_dtype,\n    groups=1,\n):\n    \"\"\"Choose the best forward algorithm for the given input.\n\n    Paramters\n    ---------\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n        2: CUDNN_TENSOR_NCHW_VECT_C\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    x_shape: list\n        input shape\n    w_shape: list\n        weight shape\n    y_shape: list\n        output shape\n    data_dtype: str\n        data type\n    conv_dtype: str\n        convolution type\n    groups: int\n        number of groups\n\n    Returns\n    -------\n    algo: int\n        algo chosen by CUDNN\n    \"\"\"\n    return _conv_find_algo(\n        \"tvm.contrib.cudnn.conv.forward_find_algo\",\n        tensor_format,\n        pad,\n        stride,\n        dilation,\n        x_shape,\n        w_shape,\n        y_shape,\n        data_dtype,\n        conv_dtype,\n        groups,\n    )\n\n\ndef conv_backward_data_find_algo(\n    tensor_format,\n    pad,\n    stride,\n    dilation,\n    dy_shape,\n    w_shape,\n    dx_shape,\n    data_dtype,\n    conv_dtype,\n    groups=1,\n):\n    \"\"\"Choose the best backward data algorithm for the given input.\n\n    Paramters\n    ---------\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n        2: CUDNN_TENSOR_NCHW_VECT_C\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    dy_shape: list\n        output gradient shape\n    w_shape: list\n        weight shape\n    dx_shape: list\n        dgrad shape\n    data_dtype: str\n        data type\n    conv_dtype: str\n        convolution type\n    groups: int\n        number of groups\n\n    Returns\n    -------\n    algo: int\n        algo chosen by CUDNN\n    \"\"\"\n    return _conv_find_algo(\n        \"tvm.contrib.cudnn.conv.backward_data_find_algo\",\n        tensor_format,\n        pad,\n        stride,\n        dilation,\n        dy_shape,\n        w_shape,\n        dx_shape,\n        data_dtype,\n        conv_dtype,\n        groups,\n    )\n\n\ndef conv_backward_filter_find_algo(\n    tensor_format,\n    pad,\n    stride,\n    dilation,\n    dy_shape,\n    x_shape,\n    dw_shape,\n    data_dtype,\n    conv_dtype,\n    groups=1,\n):\n    \"\"\"Choose the best backward filter algorithm for the given input.\n\n    Paramters\n    ---------\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n        2: CUDNN_TENSOR_NCHW_VECT_C\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    dy_shape: list\n        output gradient shape\n    x_shape: list\n        weight shape\n    dw_shape: list\n        wgrad shape\n    data_dtype: str\n        data type\n    conv_dtype: str\n        convolution type\n    groups: int\n        number of groups\n\n    Returns\n    -------\n    algo: int\n        algo chosen by CUDNN\n    \"\"\"\n    return _conv_find_algo(\n        \"tvm.contrib.cudnn.conv.backward_filter_find_algo\",\n        tensor_format,\n        pad,\n        stride,\n        dilation,\n        dy_shape,\n        x_shape,\n        dw_shape,\n        data_dtype,\n        conv_dtype,\n        groups,\n    )\n\n\ndef conv_forward(x, w, pad, stride, dilation, conv_mode, tensor_format, algo, conv_dtype, groups=1):\n    \"\"\"Create an extern op that compute 2D or 3D convolution with CuDNN\n\n    Parameters\n    ----------\n    x: Tensor\n        input feature map\n    w: Tensor\n        convolution weight\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    conv_mode: int\n        0: CUDNN_CONVOLUTION\n        1: CUDNN_CROSS_CORRELATION\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n        2: CUDNN_TENSOR_NCHW_VECT_C\n    algo: int\n        Forward algorithm, get index from ```algo_to_index``` function\n        if algo == -1, the best algo will be chosen by CUDNN\n    conv_dtype: str\n        convolution type\n    groups: int\n        the number of groups\n\n    Returns\n    -------\n    y: Tensor\n        The result tensor\n    \"\"\"\n    dims = len(x.shape)\n    assert dims in (4, 5)\n\n    conv_dtype = x.dtype if conv_dtype is None else conv_dtype\n    pad, stride, dilation, _, _ = _prepare_global_func_params(dims - 2, pad, stride, dilation)\n\n    x_shape = list(x.shape)\n\n    if isinstance(x.shape[0], tvm.tir.expr.IntImm):\n        oshape = conv_output_shape(\n            tensor_format,\n            pad,\n            stride,\n            dilation,\n            x_shape,\n            list(w.shape),\n            x.dtype,\n            conv_dtype,\n            groups,\n        )\n        if algo == -1:\n            # For now if we try to call `cudnnFindConvolutionForwardAlgorithm` when\n            # using INT8 data type, CuDNN will crash down.\n            # On the other hand, CuDNN only support IMPLICIT_PRECOMP_GEMM at NHWC format\n            if tensor_format == 1 and conv_dtype == \"int32\":\n                algo = 1\n            else:\n                algo = conv_forward_find_algo(\n                    tensor_format,\n                    pad,\n                    stride,\n                    dilation,\n                    list(x.shape),\n                    list(w.shape),\n                    oshape,\n                    x.dtype,\n                    conv_dtype,\n                    groups,\n                )\n    else:\n        # The dynamic batch size case, pretend this is a single batch\n        x_shape[0] = 1\n        oshape = conv_output_shape(\n            tensor_format,\n            pad,\n            stride,\n            dilation,\n            x_shape,\n            list(w.shape),\n            x.dtype,\n            conv_dtype,\n            groups,\n        )\n        oshape[0] = x.shape[0]\n        # This picks CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM\n        # It seems this is the fastest among algorithms that are always applicable\n        algo = 1\n\n    if dims == 4:\n        return te.extern(\n            oshape,\n            [x, w],\n            lambda ins, outs: tvm.tir.call_packed(\n                \"tvm.contrib.cudnn.conv2d.forward\",\n                conv_mode,\n                tensor_format,\n                algo,\n                pad[0],\n                pad[1],\n                stride[0],\n                stride[1],\n                dilation[0],\n                dilation[1],\n                ins[0],\n                ins[1],\n                outs[0],\n                conv_dtype,\n                groups,\n            ),\n            name=\"y\",\n        )\n\n    return te.extern(\n        oshape,\n        [x, w],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.conv3d.forward\",\n            conv_mode,\n            tensor_format,\n            algo,\n            pad[0],\n            pad[1],\n            pad[2],\n            stride[0],\n            stride[1],\n            stride[2],\n            dilation[0],\n            dilation[1],\n            dilation[2],\n            ins[0],\n            ins[1],\n            outs[0],\n            conv_dtype,\n            groups,\n        ),\n        name=\"y\",\n    )\n\n\ndef conv_backward_data(\n    dy,\n    w,\n    pad,\n    stride,\n    dilation,\n    conv_mode,\n    tensor_format,\n    conv_dtype,\n    groups=1,\n    output_padding=(0, 0),\n):\n    \"\"\"Create a CuDNN extern op that computes the gradient of 2D convolution with respect to data.\n\n    Parameters\n    ----------\n    dy: Tensor\n        output gradient\n    w: Tensor\n        convolution weight\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    conv_mode: int\n        0: CUDNN_CONVOLUTION\n        1: CUDNN_CROSS_CORRELATION\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n    conv_dtype: str\n        convolution type\n    groups: int\n        the number of groups\n\n    Returns\n    -------\n    dx: Tensor\n        dgrad tensor\n    \"\"\"\n    dims = len(dy.shape)\n    assert dims == 4\n\n    conv_dtype = dy.dtype if conv_dtype is None else conv_dtype\n    pad, stride, dilation, _, _ = _prepare_global_func_params(dims - 2, pad, stride, dilation)\n\n    assert isinstance(\n        dy.shape[0], tvm.tir.expr.IntImm\n    ), \"Dynamic batch is not supported for cudnn conv2d backwad data yet.\"\n\n    dx_shape = conv_dgrad_shape(\n        tensor_format, pad, stride, dilation, dy.shape, w.shape, output_padding, groups\n    )\n\n    if exists():\n        # When cudnn exists, find the backward data algo\n        algo = conv_backward_data_find_algo(\n            tensor_format,\n            pad,\n            stride,\n            dilation,\n            list(dy.shape),\n            list(w.shape),\n            dx_shape,\n            dy.dtype,\n            conv_dtype,\n            groups,\n        )\n    else:\n        algo = 1\n\n    return te.extern(\n        dx_shape,\n        [dy, w],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.conv2d.backward_data\",\n            conv_mode,\n            tensor_format,\n            algo,\n            pad[0],\n            pad[1],\n            stride[0],\n            stride[1],\n            dilation[0],\n            dilation[1],\n            ins[0],\n            ins[1],\n            outs[0],\n            conv_dtype,\n            groups,\n        ),\n        name=\"dx\",\n    )\n\n\ndef conv_backward_filter(\n    dy, x, kernel_size, pad, stride, dilation, conv_mode, tensor_format, conv_dtype, groups=1\n):\n    \"\"\"Create a CuDNN extern op that computes the gradient of 2D convolution with respect to weight.\n\n    Parameters\n    ----------\n    dy: Tensor\n        output gradient\n    x: Tensor\n        input tensor\n    kernel_size: a pair of int\n        The spatial size of the corresponding forward convolution kernel\n    pad: int or list\n        padding\n    stride: int or list\n        stride\n    dilation: int or list\n        dilation\n    conv_mode: int\n        0: CUDNN_CONVOLUTION\n        1: CUDNN_CROSS_CORRELATION\n    tensor_format: int\n        0: CUDNN_TENSOR_NCHW\n        1: CUDNN_TENSOR_NHWC\n    conv_dtype: str\n        convolution type\n    groups: int\n        the number of groups\n\n    Returns\n    -------\n    dw: Tensor\n        wgrad tensor\n    \"\"\"\n    dims = len(x.shape)\n    assert dims == 4\n\n    conv_dtype = x.dtype if conv_dtype is None else conv_dtype\n    pad, stride, dilation, _, _ = _prepare_global_func_params(dims - 2, pad, stride, dilation)\n    filter_h, filter_w = kernel_size\n\n    x_shape = list(x.shape)\n\n    assert isinstance(\n        x.shape[0], tvm.tir.expr.IntImm\n    ), \"Dynamic batch is not supported for cudnn conv2d backwad filter yet.\"\n\n    ic_ind = 1 if tensor_format == 0 else 3\n\n    if groups > 1:\n        assert (\n            x_shape[ic_ind] == dy.shape[ic_ind] and x_shape[ic_ind] == groups\n        ), \"Only depthwise wgrad supported for groups > 1.\"\n        ic = 1\n    else:\n        ic = x_shape[ic_ind]\n\n    if tensor_format == 0:\n        dw_shape = [dy.shape[1], ic, filter_h, filter_w]\n    else:\n        dw_shape = [dy.shape[3], filter_h, filter_w, ic]\n\n    algo = conv_backward_filter_find_algo(\n        tensor_format,\n        pad,\n        stride,\n        dilation,\n        list(dy.shape),\n        list(x.shape),\n        dw_shape,\n        x.dtype,\n        conv_dtype,\n        groups,\n    )\n\n    return te.extern(\n        dw_shape,\n        [dy, x],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.conv2d.backward_filter\",\n            conv_mode,\n            tensor_format,\n            algo,\n            pad[0],\n            pad[1],\n            stride[0],\n            stride[1],\n            dilation[0],\n            dilation[1],\n            ins[0],\n            ins[1],\n            outs[0],\n            conv_dtype,\n            groups,\n        ),\n        name=\"dw\",\n    )\n\n\ndef softmax(x, axis=-1):\n    \"\"\"Compute softmax using CuDNN\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        The input tensor\n\n    axis : int\n        The axis to compute the softmax\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n        The result tensor\n    \"\"\"\n    return te.extern(\n        x.shape,\n        [x],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.softmax.forward\", ins[0], outs[0], axis\n        ),\n        name=\"y\",\n    )\n\n\ndef log_softmax(x, axis=-1):\n    \"\"\"Compute log_softmax using CuDNN\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        The input tensor\n\n    axis : int\n        The axis to compute log softmax over\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n        The result tensor\n    \"\"\"\n    return te.extern(\n        x.shape,\n        [x],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.log_softmax.forward\", ins[0], outs[0], axis\n        ),\n        name=\"y\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BYOC support for CUTLASS.\"\"\"\nfrom .build import has_cutlass, num_cutlass_partitions, finalize_modules, finalize_modules_vm\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/build.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, dangerous-default-value\n\"\"\"Driver for partitioning and building a Relay module for CUTLASS offload.\"\"\"\nimport logging\nimport os\nimport multiprocessing\nimport tvm\nfrom tvm import runtime, relay\nfrom tvm.contrib.nvcc import get_cuda_version\nfrom tvm._ffi.registry import register_func\nfrom .gen_gemm import CutlassGemmProfiler\nfrom .gen_conv2d import CutlassConv2DProfiler\nfrom .library import ConvKind\n\nlogger = logging.getLogger(\"cutlass\")\n\n\ndef has_cutlass():\n    \"\"\"Returns true if the CUTLASS custom codegen is available\"\"\"\n    return tvm.get_global_func(\"relay.ext.cutlass.create_c_source_module\", True) is not None\n\n\ndef _get_cutlass_path():\n    tvm_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../../../../\")\n    cutlass_path = os.path.join(tvm_root, \"3rdparty/cutlass\")\n    assert os.path.exists(\n        cutlass_path\n    ), \"\"\"The CUTLASS root directory not found in {}.\n        Currently, using CUTLASS requires building TVM from source.\"\"\".format(\n        cutlass_path\n    )\n    return cutlass_path\n\n\ndef _get_cutlass_compile_options(sm, threads, use_fast_math=False):\n    cutlass_root = _get_cutlass_path()\n    cutlass_include = os.path.join(cutlass_root, \"include\")\n    cutlass_util_include = os.path.join(cutlass_root, \"tools/util/include\")\n\n    kwargs = {}\n    kwargs[\"cc\"] = \"nvcc\"\n    kwargs[\"options\"] = [\n        \"-c\",\n        \"-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1\",\n        \"-gencode=arch=compute_%d,code=[sm_%d,compute_%d]\" % (sm, sm, sm),\n        \"-Xcompiler=-fPIC\",\n        \"-Xcompiler=-Wconversion\",\n        \"-Xcompiler=-fno-strict-aliasing\",\n        \"-O3\",\n        \"-std=c++17\",\n        \"-I\" + cutlass_include,\n        \"-I\" + cutlass_util_include,\n    ]\n    if use_fast_math:\n        kwargs[\"options\"].append(\"-DCUTLASS_USE_TANH_FOR_SIGMOID\")\n    cuda_ver = get_cuda_version()\n    if cuda_ver >= (11, 2):\n        ncpu = multiprocessing.cpu_count() if threads < 0 else threads\n        kwargs[\"options\"].append(\"-t %d\" % ncpu)\n    return kwargs\n\n\nclass OpAnnotator(tvm.relay.ExprVisitor):\n    \"\"\"Annotates partitioned functions with shape and dtype information.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.signature = {}\n\n    def visit_call(self, call):\n        op = call.op\n        if isinstance(op, relay.Function) and \"Composite\" in op.attrs:\n            self.signature[\"op_type\"] = op.attrs[\"Composite\"]\n            for i, arg in enumerate(op.params):\n                self.signature[\"arg%d_shape\" % i] = arg.checked_type.shape\n                self.signature[\"arg%d_dtype\" % i] = arg.checked_type.dtype\n            self.signature[\"ret_shape\"] = op.ret_type.shape\n            self.signature[\"ret_dtype\"] = op.ret_type.dtype\n            self.visit(op.body)\n\n        if str(op) in [\"nn.conv2d\", \"nn.conv2d_transpose\", \"nn.conv2d_backward_weight\"]:\n            self.op_attrs = call.attrs\n\n        for arg in call.args:\n            self.visit(arg)\n\n\ndef select_gemm_kernel(\n    cutlass_profiler,\n    op_type,\n    MM,\n    KK,\n    NN,\n    out_dtype,\n    arg0_dtype,\n    arg1_dtype,\n    use_3xtf32,\n    batched,\n    find_first_valid,\n    use_multiprocessing,\n):\n    \"\"\"Run CUTLASS profiler to select the best kernel, or return the default one for dynamic\n    workloads.\"\"\"\n    if any(isinstance(s, tvm.tir.Any) for s in [MM, KK, NN]):\n        out = cutlass_profiler.get_default(\n            op_type, out_dtype, arg0_dtype, arg1_dtype, use_3xtf32, batched=batched\n        )\n        name, cutlass_op_def = out[\"name\"], out[\"opdef\"]\n        logger.info(\"Picked the default kernel %s\", name)\n    else:\n        name, cutlass_op_def, _ = cutlass_profiler.profile(\n            op_type,\n            MM,\n            NN,\n            KK,\n            out_dtype,\n            arg0_dtype,\n            arg1_dtype,\n            use_3xtf32,\n            batched=batched,\n            find_first_valid=find_first_valid,\n            use_multiprocessing=use_multiprocessing,\n        )\n        if not find_first_valid:\n            logger.info(\"The best kernel is %s\", name)\n        else:\n            logger.info(\"Picked the first kernel found %s\", name)\n\n    return name, cutlass_op_def\n\n\ndef handle_batch_matmul(\n    cutlass_profiler,\n    op_type,\n    arg0_shape,\n    arg1_shape,\n    out_dtype,\n    arg0_dtype,\n    arg1_dtype,\n    use_3xtf32,\n    find_first_valid,\n    use_multiprocessing,\n):\n    \"\"\"Profile and select a kernel for batch_matmul op workload.\"\"\"\n    MM = arg0_shape[1]\n    KK = arg0_shape[2]\n    NN = arg1_shape[1]\n\n    name, cutlass_op_def = select_gemm_kernel(\n        cutlass_profiler,\n        op_type,\n        MM,\n        KK,\n        NN,\n        out_dtype,\n        arg0_dtype,\n        arg1_dtype,\n        use_3xtf32,\n        True,\n        find_first_valid,\n        use_multiprocessing,\n    )\n\n    return {\n        \"batch\": arg0_shape[0],\n        \"batch_stride_A\": arg0_shape[1] * arg0_shape[2],\n        \"batch_stride_B\": arg1_shape[1] * arg1_shape[2],\n        \"batch_stride_C\": arg0_shape[1] * arg1_shape[1],\n        \"cutlass_op_def\": cutlass_op_def,\n        \"cutlass_op_name\": name,\n        \"lda\": \"K\",\n        \"ldb\": \"K\",\n        \"ldc\": \"N\",\n    }\n\n\ndef handle_dense(\n    cutlass_profiler,\n    op_type,\n    arg0_shape,\n    arg1_shape,\n    out_dtype,\n    arg0_dtype,\n    arg1_dtype,\n    use_3xtf32,\n    find_first_valid,\n    use_multiprocessing,\n):\n    \"\"\"Profile and select a kernel for dense op workload.\"\"\"\n    MM = arg0_shape[0]\n    KK = arg0_shape[1]\n    NN = arg1_shape[0]\n\n    name, cutlass_op_def = select_gemm_kernel(\n        cutlass_profiler,\n        op_type,\n        MM,\n        KK,\n        NN,\n        out_dtype,\n        arg0_dtype,\n        arg1_dtype,\n        use_3xtf32,\n        False,\n        find_first_valid,\n        use_multiprocessing,\n    )\n\n    assert \"tn_align\" in name, \"Only supports (row_major, col_major) input layout for now.\"\n\n    return {\n        \"cutlass_op_def\": cutlass_op_def,\n        \"cutlass_op_name\": name,\n        \"lda\": \"K\",\n        \"ldb\": \"K\",\n        \"ldc\": \"N\",\n    }\n\n\ndef handle_conv2d(\n    cutlass_profiler,\n    op_type,\n    d_shape,\n    w_shape,\n    padding,\n    strides,\n    dilation,\n    out_dtype,\n    data_dtype,\n    weight_dtype,\n    use_3xtf32,\n    split_k_slices,\n    profile_all_alignments,\n    find_first_valid,\n    use_multiprocessing,\n):\n    \"\"\"Profile and select a kernel for conv2d op workload.\"\"\"\n    if \"conv2d_transpose\" in op_type:\n        conv_kind = ConvKind.Dgrad\n    elif \"backward_weight\" in op_type:\n        conv_kind = ConvKind.Wgrad\n    else:\n        conv_kind = ConvKind.Fprop\n\n    if any(isinstance(s, tvm.tir.Any) for s in d_shape):\n        out = cutlass_profiler.get_default(\n            op_type, out_dtype, data_dtype, weight_dtype, use_3xtf32, conv_kind, strides\n        )\n        name, cutlass_op_def = out[\"name\"], out[\"opdef\"]\n        logger.info(\"Picked the default kernel %s\", name)\n    else:\n        name, cutlass_op_def, _ = cutlass_profiler.profile(\n            op_type,\n            d_shape,\n            w_shape,\n            padding,\n            strides,\n            dilation,\n            out_dtype,\n            data_dtype,\n            weight_dtype,\n            use_3xtf32,\n            conv_kind,\n            split_k_slices,\n            profile_all_alignments,\n            find_first_valid=find_first_valid,\n            use_multiprocessing=use_multiprocessing,\n        )\n        if not find_first_valid:\n            logger.info(\"The best kernel is %s\", name)\n        else:\n            logger.info(\"Picked the first kernel found %s\", name)\n\n    return {\n        \"cutlass_op_def\": cutlass_op_def,\n        \"cutlass_op_name\": name,\n    }\n\n\ndef num_cutlass_partitions(mod):\n    return sum([(1 if \"cutlass\" in var.name_hint else 0) for var in mod.get_global_vars()])\n\n\ndef tune_cutlass_kernels(\n    mod,\n    sm,\n    use_3xtf32=True,\n    split_k_slices=[1],\n    profile_all_alignments=False,\n    find_first_valid=False,\n    use_multiprocessing=False,\n    tmp_dir=\"./tmp\",\n):\n    \"\"\"Given a module partitioned for CUTLASS offloading, profile each workload to select which\n    kernels to emit.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The Relay module with cutlass partitions.\n\n    sm : int\n        An integer specifying the compute capability. For example, 75 for Turing and\n        80 or 86 for Ampere.\n\n    use_3xtf32 : bool\n        Wheter or not use slower but very accurate (compared to tf32) 3xtf32 mode for\n        fp32 inputs on tensorcore.\n\n    split_k_slices : list of int\n        Split factor candidates for split-K GEMM. If split-K > 1, the GEMM K-loop is computed in\n        parallel across split-K blocks, and a separate global reduction kernel is launched to\n        accumulate partial reductions. The profiler will pick the best split-k factor from the\n        given candidate list. Note that the larger split-K factor requires a larger workspace.\n        Currently, parallel split-k has been tested only for wgrad. For GEMM and other conv2d\n        kinds, split_k_slices is ignored.\n\n    profile_all_alignments : bool\n        When True, profile all kernal variants with smaller alignments than the largest possible.\n\n    find_first_valid : bool\n        Whether or not profile all candidate kernels, or stop profiling after\n        the first applicable kernel is found.\n\n    use_multiprocessing : bool\n        Whether or not compile profiler executables for different kernels in parallel.\n\n    tmp_dir : string, optional\n        A temporary directory where intermediate compiled artifacts will be stored.\n\n    Returns\n    -------\n    mod : IRModule\n        The updated module annotated with cutlass profiling information.\n\n    num_cutlass_partition : int\n        The number of partitioned functions created for CUTLASS.\n    \"\"\"\n    gemm_profiler = CutlassGemmProfiler(sm, _get_cutlass_path(), tmp_dir)\n    conv2d_profiler = CutlassConv2DProfiler(sm, _get_cutlass_path(), tmp_dir)\n    num_cutlass_partition = 0\n    for var in mod.get_global_vars():\n        fun_name = var.name_hint\n        func = mod[fun_name]\n        if \"cutlass\" in fun_name:\n            num_cutlass_partition += 1\n            new_func = tune_cutlass_function(\n                func,\n                use_3xtf32,\n                split_k_slices,\n                profile_all_alignments,\n                find_first_valid,\n                use_multiprocessing,\n                gemm_profiler,\n                conv2d_profiler,\n            )\n            mod.update_func(var, new_func)\n\n    return mod, num_cutlass_partition\n\n\ndef tune_cutlass_function(\n    func,\n    use_3xtf32,\n    split_k_slices,\n    profile_all_alignments,\n    find_first_valid,\n    use_multiprocessing,\n    gemm_profiler,\n    conv2d_profiler,\n):\n    \"\"\"Given a function intended to be offloaded to CUTLASS,  profile each workload to select which\n    kernels to emit.\n\n    Parameters\n    ----------\n    func : IRModule\n        The Relay Function to tune for.\n\n    use_3xtf32 : bool\n        Wheter or not use slower but very accurate (compared to tf32) 3xtf32 mode for\n        fp32 inputs on tensorcore.\n\n    split_k_slices : list of int\n        Split factor candidates for split-K GEMM. If split-K > 1, the GEMM K-loop is computed in\n        parallel accross split-K blocks, and a seperate global reduction kernel is launched to\n        accumulate partial reductions. The profiler will pick the best split-k factor from the\n        given candidate list. Note that the larger split-K factor requires a larger workspace.\n        Currently, parallel split-k has been tested only for wgrad. For GEMM and other conv2d\n        kinds, split_k_slices is ignored.\n\n    profile_all_alignments : bool\n        When True, profile all kernal variants with smaller alignments than the largest possible.\n\n    find_first_valid : bool\n        Whether or not profile all candidate kernels, or stop profiling after\n        the first applicable kernel is found.\n\n    use_multiprocessing : bool\n        Whether or not compile profiler executables for different kernels in parallel.\n\n    gemm_profiler : CutlassGemmProfiler\n        Profiler for dense operators. May cache results between tuned functions.\n\n    conv2d_profiler : CutlassConv2DProfiler\n        Profiler for conv2d operators. May cach results between tuned functions.\n\n    Returns\n    -------\n    annot_func : Function\n        The input function with attributes capturing the best CUTLASS kernel found by tuning.\n    \"\"\"\n    annotator = OpAnnotator()\n    annotator.visit(func)\n    out_shape = annotator.signature[\"ret_shape\"]\n    out_dtype = annotator.signature[\"ret_dtype\"]\n    op_type = annotator.signature[\"op_type\"]\n\n    new_attrs = {\"op_type\": op_type}\n    new_attrs.update(annotator.signature)\n    new_attrs.update(func.attrs)\n    arg0_shape = new_attrs[\"arg0_shape\"]\n    arg1_shape = new_attrs[\"arg1_shape\"]\n    arg0_dtype = new_attrs[\"arg0_dtype\"]\n    arg1_dtype = new_attrs[\"arg1_dtype\"]\n\n    if \"conv2d\" in op_type:\n        new_attrs[\"padding\"] = annotator.op_attrs.padding\n        new_attrs[\"strides\"] = annotator.op_attrs.strides\n        new_attrs[\"dilation\"] = annotator.op_attrs.dilation\n\n        if \"conv2d_transpose\" in op_type:\n            d_shape = out_shape\n            w_shape = arg1_shape\n        elif \"conv2d_backward_weight\" in op_type:\n            d_shape = arg1_shape\n            w_shape = out_shape\n        else:\n            d_shape = arg0_shape\n            w_shape = arg1_shape\n\n        new_attrs.update(\n            handle_conv2d(\n                conv2d_profiler,\n                op_type,\n                d_shape,\n                w_shape,\n                annotator.op_attrs.padding,\n                annotator.op_attrs.strides,\n                annotator.op_attrs.dilation,\n                out_dtype,\n                arg0_dtype,\n                arg1_dtype,\n                use_3xtf32,\n                split_k_slices,\n                profile_all_alignments,\n                find_first_valid,\n                use_multiprocessing,\n            )\n        )\n    elif \"batch_matmul\" in op_type:\n        new_attrs.update(\n            handle_batch_matmul(\n                gemm_profiler,\n                op_type,\n                arg0_shape,\n                arg1_shape,\n                out_dtype,\n                arg0_dtype,\n                arg1_dtype,\n                use_3xtf32,\n                find_first_valid,\n                use_multiprocessing,\n            )\n        )\n    elif \"dense\" in op_type:\n        new_attrs.update(\n            handle_dense(\n                gemm_profiler,\n                op_type,\n                arg0_shape,\n                arg1_shape,\n                out_dtype,\n                arg0_dtype,\n                arg1_dtype,\n                use_3xtf32,\n                find_first_valid,\n                use_multiprocessing,\n            )\n        )\n    else:\n        raise ValueError(\"%s unsupported composite\" % op_type)\n\n    new_attrs = tvm.ir.make_node(\"DictAttrs\", **new_attrs)\n    return relay.Function(\n        func.params,\n        func.body,\n        ret_type=func.ret_type,\n        type_params=func.type_params,\n        attrs=new_attrs,\n    )\n\n\n@register_func(\"relay.ext.cutlass.compile_for_cutlass\")\ndef compile_for_cutlass(mod, cutlass_target):\n    \"\"\"Given an IRModule with at least one Compiler='cutlass' Relay function, return a\n    LibraryModule with all such functions compiled into their PackedFunc-compatible form.\n     - First runs CUTLASS tuning to decide on the best kernels, which itself requires the\n       repeated compilation and execution of CUDA code using nvcc. The results of this\n       is captured as annotation on each relevant function. Kernel performance is cached\n       overall all functions.\n     - Then generates a single CSourceModule containing C code implementing all the\n       Compiler='cutlass' Relay functions, accounting for the tuning done above.\n     - Then compiles that CSourceModule with the appropriate nvcc arguments to yield\n       a static .o library. An export_library step will be required on the final runtime\n       module to link that library into the overall .so library.\n     See CompileForCutlass in src/relay/backend/contrib/cutlass/codegen.cc for where this\n     helper function is used to implement the RelayToTIR pass hook for CUTLASS.\"\"\"\n\n    # Recover options from the current 'cutlass' Target\n    assert cutlass_target.kind.name == \"cutlass\"\n    tuning_config = {\n        key: cutlass_target.attrs.get(key)\n        for key in [\n            \"sm\",\n            \"use_3xtf32\",\n            \"split_k_slices\",\n            \"profile_all_alignments\",\n            \"find_first_valid\",\n            \"use_multiprocessing\",\n        ]\n    }\n    compile_config = {\n        key: cutlass_target.attrs.get(key) for key in [\"sm\", \"threads\", \"use_fast_math\"]\n    }\n    tmp_dir = cutlass_target.attrs.get(\"tmp_dir\")\n\n    # Tune\n    logger.info(\"Tuning for CUTLASS\")\n    mod, _ = tune_cutlass_kernels(mod, tmp_dir=tmp_dir, **tuning_config)\n\n    # Compile\n    logger.info(\"Creating CSource module for CUTLASS\")\n    create_c_source_module = tvm._ffi.get_global_func(\"relay.ext.cutlass.create_c_source_module\")\n    c_module = create_c_source_module(mod)\n    function_names = c_module.get_function(\"get_func_names\")()\n    compile_options = _get_cutlass_compile_options(**compile_config)\n    lib_path = os.path.join(tmp_dir, \"cutlass.o\")\n    logger.info(\"Compiling generated CUTLASS code\")\n    c_module.export_library(lib_path, workspace_dir=tmp_dir, **compile_options)\n\n    # Recover static library\n    logger.info(\"Loading compiled CUTLASS code\")\n    final_mod = tvm.runtime.load_static_library(lib_path, function_names)\n\n    logger.info(\"Done with CUTLASS compilation\")\n    return final_mod\n\n\ndef finalize_modules(lib, lib_path=\"compile.so\", tmp_dir=\"./tmp\"):\n    \"\"\"Returns lib with any C source, LLVM and static library modules complied and linked in ready\n    for use by the graph or AOT executors. This method is not specific to CUTLASS, however it does\n    assume nvcc will be used for final compilation and linking. It is provided here for\n    convenience.\n\n    Parameters\n    ----------\n    lib : runtime.Module\n        The output from relay.build.\n\n    lib_path : string\n        The path to a shared library which will be generated as the result of the build process.\n\n    tmp_dir : string\n        A temporary directory where intermediate compiled artifacts will be stored.\n\n    Returns\n    -------\n    updated_lib : runtime.Module\n        The updated library with all compilation and linking completed.\n\n    \"\"\"\n    lib_path = os.path.join(tmp_dir, lib_path)\n    lib.export_library(lib_path, workspace_dir=tmp_dir, cc=\"nvcc\")\n    return runtime.load_module(lib_path)\n\n\ndef finalize_modules_vm(vm_exec, lib_path=\"compile.so\", vmcode_path=\"vmcode.ro\", tmp_dir=\"./tmp\"):\n    \"\"\"Returns vm_exec with any C source, LLVM and static library modules compiled and linked in\n    ready for use by the VM executor. This method is not specific to CUTLASS, however it does\n    assume nvcc will be used for final compilation and linking. It is provided here for\n    convenience.\n\n    Parameters\n    ----------\n    vm_exec : vm.Executable\n        The output from relay.vm.compile containing compiled host code and kernels.\n\n    lib_path : string\n        The path to a shared library which will be generated as the result of the build process.\n\n    vmcode_path : string\n        The path where the VM bytecode will be serialized to as a side-effect.\n\n    tmp_dir : string\n        A temporary directory where intermediate compiled artifacts will be stored.\n\n    Returns\n    -------\n    updated_vm_exec : vm.Executable\n        The updated VM executable with all compilation and linking completed.\n    \"\"\"\n    code, lib = vm_exec.save()\n    lib_path = os.path.join(tmp_dir, lib_path)\n    vmcode_path = os.path.join(tmp_dir, vmcode_path)\n    lib.export_library(lib_path, workspace_dir=tmp_dir, cc=\"nvcc\")\n    with open(vmcode_path, \"wb\") as fo:\n        fo.write(code)\n    lib = tvm.runtime.load_module(lib_path)\n    return tvm.runtime.vm.Executable.load_exec(code, lib)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/conv2d_operation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-wildcard-import, wildcard-import\n\"\"\"Generator for CUTLASS Conv2D kernels.\"\"\"\nfrom .library import *\n\n\nclass Conv2dOperation:\n    \"\"\"Describes various attributes for instantiating Conv2d kernels.\"\"\"\n\n    def __init__(\n        self,\n        conv_kind,\n        iterator_algorithm,\n        arch,\n        tile_description,\n        A,\n        B,\n        C,\n        element_epilogue,\n        stride_support,\n        epilogue_functor=EpilogueFunctor.LinearCombination,\n        swizzling_functor=SwizzlingFunctor.Identity1,\n        split_k_slices=1,\n    ):\n        self.operation_kind = OperationKind.Conv2d\n        self.arch = arch\n        self.tile_description = tile_description\n        self.conv_kind = conv_kind\n        self.A = A\n        self.B = B\n        self.C = C\n        self.element_epilogue = element_epilogue\n        self.epilogue_functor = epilogue_functor\n        self.iterator_algorithm = iterator_algorithm\n        self.stride_support = stride_support\n        self.swizzling_functor = swizzling_functor\n        self.split_k_slices = split_k_slices\n\n    def accumulator_type(self):\n        return self.tile_description.math_instruction.element_accumulator\n\n    def core_name(self):\n        \"\"\"The basic operation kind is prefixed with a letter indicating the accumulation type.\"\"\"\n        intermediate_type = \"\"\n\n        if self.tile_description.math_instruction.opcode_class == OpcodeClass.TensorOp:\n            inst_shape = \"%d%d%d\" % tuple(self.tile_description.math_instruction.instruction_shape)\n            if (\n                self.tile_description.math_instruction.element_a != self.A.element\n                and self.tile_description.math_instruction.element_a != self.accumulator_type()\n            ):\n                intermediate_type = DataTypeNames[self.tile_description.math_instruction.element_a]\n        else:\n            inst_shape = \"\"\n\n        return \"%s%s%s%s_%s\" % (\n            ShortDataTypeNames[self.accumulator_type()],\n            inst_shape,\n            intermediate_type,\n            ConvKindNames[self.conv_kind],\n            IteratorAlgorithmNames[self.iterator_algorithm],\n        )\n\n    def extended_name(self):\n        \"\"\"Append data types if they differ from compute type.\"\"\"\n        if (\n            self.C.element != self.tile_description.math_instruction.element_accumulator\n            and self.A.element != self.tile_description.math_instruction.element_accumulator\n        ):\n            extended_name = \"${element_c}_${core_name}_${element_a}\"\n        elif (\n            self.C.element == self.tile_description.math_instruction.element_accumulator\n            and self.A.element != self.tile_description.math_instruction.element_accumulator\n        ):\n            extended_name = \"${core_name}_${element_a}\"\n        else:\n            extended_name = \"${core_name}\"\n\n        extended_name = substitute_template(\n            extended_name,\n            {\n                \"element_a\": DataTypeNames[self.A.element],\n                \"element_c\": DataTypeNames[self.C.element],\n                \"core_name\": self.core_name(),\n            },\n        )\n\n        return extended_name\n\n    def layout_name(self):\n        return \"%s\" % (ShortLayoutTypeNames[self.A.layout])\n\n    def procedural_name(self):\n        \"\"\"\n        The full procedural name indicates architecture, extended name, tile size, and layout.\n        \"\"\"\n        opcode_class_name = OpcodeClassNames[self.tile_description.math_instruction.opcode_class]\n\n        threadblock = \"%dx%d_%dx%d\" % (\n            self.tile_description.threadblock_shape[0],\n            self.tile_description.threadblock_shape[1],\n            self.tile_description.threadblock_shape[2],\n            self.tile_description.stages,\n        )\n\n        if self.stride_support == StrideSupport.Unity:\n            configuration_name = (\n                \"cutlass_${opcode_class}_${extended_name}_${threadblock}\"\n                \"_${layout}_align${alignment}_unity_stride\"\n            )\n        else:\n            configuration_name = (\n                \"cutlass_${opcode_class}_${extended_name}_${threadblock}\"\n                \"_${layout}_align${alignment}\"\n            )\n\n        if self.split_k_slices > 1:\n            configuration_name += \"_splitk%d\" % self.split_k_slices\n\n        return substitute_template(\n            configuration_name,\n            {\n                \"opcode_class\": opcode_class_name,\n                \"extended_name\": self.extended_name(),\n                \"threadblock\": threadblock,\n                \"layout\": self.layout_name(),\n                \"alignment\": \"%d\" % self.A.alignment,\n            },\n        )\n\n\nclass EmitConv2dInstance:\n    \"\"\"Responsible for emitting a CUTLASS template definition.\"\"\"\n\n    def __init__(self):\n        self.epilogue_default = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      ${epilogue_vector_length},\n      ${element_accumulator},\n      ${element_epilogue}\n    >\"\"\"\n\n        self.epilogue_no_beta_scaling = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      ${epilogue_vector_length},\n      ${element_accumulator},\n      ${element_epilogue},\n      cutlass::epilogue::thread::ScaleType::NoBetaScaling\n    >\"\"\"\n\n        self.epilogue_residual_block = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      ${element_accumulator},\n      ${element_epilogue},\n      ${element_c},\n      ${epilogue_vector_length},\n      ${activation},\n      ${binary_op},\n      ${unary_op}\n    >\"\"\"\n\n        self.epilogue_wgrad = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      4,\n      float,\n      float\n    >\"\"\"\n\n        self.template = \"\"\"\n  // Conv2d${conv_kind_name} ${iterator_algorithm_name} kernel instance \"${operation_name}\"\n  using ${operation_name} =\n  typename cutlass::conv::kernel::DefaultConv2d${conv_kind_name}${conv_kernel_postfix}<\n    ${element_a},\n    ${layout_a},\n    ${element_b},\n    ${layout_b},\n    ${element_c},\n    ${layout_c},\n    ${element_accumulator},\n    ${opcode_class},\n    ${arch},\n    cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,\n    cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k} >,\n    cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,\n    ${epilogue},\n    ${swizzling_functor}, // cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle<>,\n    ${stages},\n    ${math_operator},\n    ${iterator_algorithm},\n    ${stride_support},\n    ${align_a},\n    ${align_b}\n  >::Kernel;\n\n  ${reduction}\n\"\"\"\n\n        self.reduction_template = \"\"\"\nusing EpilogueOutputOp = ${epilogue};\nusing ReductionOp = cutlass::reduction::thread::ReduceAdd<\n    ${element_accumulator},\n    ${element_accumulator},\n      EpilogueOutputOp::kCount\n      >;\n\nusing ReductionKernel = cutlass::reduction::kernel::ReduceSplitK<\n    cutlass::MatrixShape<4, 32 * EpilogueOutputOp::kCount>,\n      EpilogueOutputOp,\n      ReductionOp\n      >;\n\nusing ReductionDevice = cutlass::reduction::device::ReduceSplitK<ReductionKernel>;\nusing ReductionStrideIndex = typename ReductionDevice::StrideIndex;\n\"\"\"\n\n    def emit(\n        self, operation, no_beta_scaling=False, residual_block_info=False, emit_reduction=False\n    ):\n        \"\"\"Instantiate a Conv2d kernel from given `operation`.\"\"\"\n        warp_shape = [\n            int(\n                operation.tile_description.threadblock_shape[idx]\n                / operation.tile_description.warp_count[idx]\n            )\n            for idx in range(3)\n        ]\n\n        epilogue_vector_length = int(\n            min(operation.C.alignment * DataTypeSize[operation.C.element], 128)\n            / DataTypeSize[operation.C.element]\n        )\n\n        element_c = operation.C.element\n        use_split_k_wgrad = operation.conv_kind == ConvKind.Wgrad and operation.split_k_slices > 1\n        # Gemm output always fp32 in wgrad with split k\n        element_c_gemm = DataType.f32 if use_split_k_wgrad else element_c\n\n        if emit_reduction:\n            epilogue_reduction = substitute_template(\n                self.epilogue_wgrad,\n                {\n                    \"epilogue_functor\": EpilogueFunctorTag[operation.epilogue_functor],\n                    \"element_c\": DataTypeTag[element_c],\n                },\n            )\n            reduction = substitute_template(\n                self.reduction_template,\n                {\n                    \"epilogue\": epilogue_reduction,\n                    \"operation_name\": operation.procedural_name(),\n                    \"element_accumulator\": DataTypeTag[operation.accumulator_type()],\n                },\n            )\n            gemm_template = substitute_template(self.template, {\"reduction\": reduction})\n        else:\n            gemm_template = substitute_template(self.template, {\"reduction\": \"\"})\n\n        values = {\n            \"operation_name\": operation.procedural_name(),\n            \"conv_kind\": ConvKindTag[operation.conv_kind],\n            \"conv_kind_name\": ConvKindNames[operation.conv_kind].capitalize(),\n            \"element_a\": DataTypeTag[operation.A.element],\n            \"layout_a\": LayoutTag[operation.A.layout],\n            \"element_b\": DataTypeTag[operation.B.element],\n            \"layout_b\": LayoutTag[operation.B.layout],\n            \"element_c\": DataTypeTag[element_c_gemm],\n            \"layout_c\": LayoutTag[operation.C.layout],\n            \"element_accumulator\": DataTypeTag[operation.accumulator_type()],\n            \"opcode_class\": OpcodeClassTag[\n                operation.tile_description.math_instruction.opcode_class\n            ],\n            \"arch\": \"cutlass::arch::Sm%d\" % operation.arch,\n            \"threadblock_shape_m\": str(operation.tile_description.threadblock_shape[0]),\n            \"threadblock_shape_n\": str(operation.tile_description.threadblock_shape[1]),\n            \"threadblock_shape_k\": str(operation.tile_description.threadblock_shape[2]),\n            \"warp_shape_m\": str(warp_shape[0]),\n            \"warp_shape_n\": str(warp_shape[1]),\n            \"warp_shape_k\": str(warp_shape[2]),\n            \"instruction_shape_m\": str(\n                operation.tile_description.math_instruction.instruction_shape[0]\n            ),\n            \"instruction_shape_n\": str(\n                operation.tile_description.math_instruction.instruction_shape[1]\n            ),\n            \"instruction_shape_k\": str(\n                operation.tile_description.math_instruction.instruction_shape[2]\n            ),\n            \"epilogue_vector_length\": str(epilogue_vector_length),\n            \"epilogue_functor\": EpilogueFunctorTag[operation.epilogue_functor],\n            \"element_epilogue\": str(DataTypeTag[operation.element_epilogue]),\n            \"swizzling_functor\": SwizzlingFunctorTag[operation.swizzling_functor],\n            \"stages\": str(operation.tile_description.stages),\n            \"iterator_algorithm\": IteratorAlgorithmTag[operation.iterator_algorithm],\n            \"iterator_algorithm_name\": IteratorAlgorithmNames[\n                operation.iterator_algorithm\n            ].capitalize(),\n            \"stride_support\": StrideSupportTag[operation.stride_support],\n            \"math_operator\": MathOperationTag[\n                operation.tile_description.math_instruction.math_operation\n            ],\n            \"align_a\": str(operation.A.alignment),\n            \"align_b\": str(operation.B.alignment),\n            \"conv_kernel_postfix\": \"\",\n        }\n\n        if use_split_k_wgrad:\n            # Even if the output is fp16, gemm output is always fp32 for split k wgrad.\n            epilogue_gemm = substitute_template(\n                self.epilogue_wgrad,\n                {\n                    \"epilogue_functor\": EpilogueFunctorTag[operation.epilogue_functor],\n                    \"element_c\": \"float\",\n                },\n            )\n            template = substitute_template(gemm_template, {\"epilogue\": epilogue_gemm})\n        elif residual_block_info:\n            template = substitute_template(\n                gemm_template, {\"epilogue\": self.epilogue_residual_block}\n            )\n            values.update(\n                {\n                    \"unary_op\": residual_block_info[\"unary_op\"],\n                    \"binary_op\": residual_block_info[\"binary_op\"],\n                    \"activation\": residual_block_info[\"activation\"],\n                    \"conv_kernel_postfix\": \"WithBroadcast\",\n                }\n            )\n        elif no_beta_scaling:\n            template = substitute_template(\n                gemm_template, {\"epilogue\": self.epilogue_no_beta_scaling}\n            )\n        else:\n            template = substitute_template(gemm_template, {\"epilogue\": self.epilogue_default})\n\n        return substitute_template(template, values)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/conv2d_profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-outside-toplevel, invalid-name\n\"\"\"Instantiate a C++ source for profiling CUTLASS kernels.\"\"\"\n\nfrom .library import DataTypeTag\n\n\nclass Conv2dProfilerEmitter(object):\n    \"\"\"Emit a C++ source for profiling CUTLASS kernels.\"\"\"\n\n    def __init__(self):\n        from jinja2 import Template\n\n        self.reduction = \"\"\"\n      ReductionDevice reduction_op;\n      static cutlass::conv::Operator const kConvolutionalOperator = ImplicitGemm::kConvolutionalOperator;\n      typename ReductionDevice::Arguments reduction_args(\n        cutlass::conv::implicit_gemm_problem_size(kConvolutionalOperator, problem_size).mn(),\n        problem_size.split_k_slices,\n        cutlass::conv::implicit_gemm_tensor_c_size(kConvolutionalOperator, problem_size),\n        {\n      \t reinterpret_cast<ImplicitGemm::ElementC*> (workspace.get()),\n      \t   ReductionStrideIndex(tensor_c.stride()[ImplicitGemm::ImplicitGemmKernel::kTensorCStrideIdx])\n      \t   },\n        {\n      \t tensor_d.device_data(),\n      \t   ReductionStrideIndex(tensor_d.stride()[ImplicitGemm::ImplicitGemmKernel::kTensorCStrideIdx])\n      \t   },\n        {\n      \t tensor_c.device_data(),\n      \t   ReductionStrideIndex(tensor_c.stride()[ImplicitGemm::ImplicitGemmKernel::kTensorCStrideIdx])\n      \t   },\n        {ElementComputeEpilogue(1), ElementComputeEpilogue(0)}\n        );\n\n      reduction_op.initialize(reduction_args, nullptr);\n      reduction_op();\n\"\"\"\n\n        self.template = Template(\n            \"\"\"\n#include <iostream>\n#include \"cutlass/cutlass.h\"\n#include \"cutlass/conv/kernel/default_conv2d_fprop.h\"\n#include \"cutlass/conv/kernel/default_conv2d_wgrad.h\"\n#include \"cutlass/conv/kernel/default_conv2d_dgrad.h\"\n#include \"cutlass/conv/device/implicit_gemm_convolution.h\"\n#include \"cutlass/util/command_line.h\"\n#include \"cutlass/util/host_tensor.h\"\n#include \"cutlass/util/reference/host/tensor_fill.h\"\n#include \"cutlass/reduction/device/reduce_split_k.h\"\n#include \"cutlass/reduction/thread/reduction_operators.h\"\n\n#define CUTLASS_CHECK(status)                                                                    \\\n  {                                                                                              \\\n    cutlass::Status error = status;                                                              \\\n    if (error != cutlass::Status::kSuccess) {                                                    \\\n      std::cerr << \"Got cutlass error: \" << cutlassGetStatusString(error) << \" at: \" << __LINE__ \\\n                << std::endl;                                                                    \\\n      exit(EXIT_FAILURE);                                                                        \\\n    }                                                                                            \\\n  }\n\n{{OperatorDef}}\nusing ImplicitGemm = cutlass::conv::device::ImplicitGemmConvolution<{{OperatorName}}>;\n\nstruct Options {\n  cutlass::Tensor4DCoord input_size;\n  cutlass::Tensor4DCoord filter_size;\n  cutlass::Tensor4DCoord padding;\n  cutlass::MatrixCoord conv_stride;\n  cutlass::MatrixCoord dilation;\n\n  void parse(int argc, char const **args) {\n    cutlass::CommandLine cmd(argc, args);\n    cmd.get_cmd_line_argument(\"n\", input_size.n());\n    cmd.get_cmd_line_argument(\"h\", input_size.h());\n    cmd.get_cmd_line_argument(\"w\", input_size.w());\n    cmd.get_cmd_line_argument(\"c\", input_size.c());\n    cmd.get_cmd_line_argument(\"k\", filter_size.n());\n    cmd.get_cmd_line_argument(\"r\", filter_size.h());\n    cmd.get_cmd_line_argument(\"s\", filter_size.w());\n    int pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w;\n    cmd.get_cmd_line_argument(\"pad_h\", pad_h);\n    cmd.get_cmd_line_argument(\"pad_w\", pad_w);\n    cmd.get_cmd_line_argument(\"stride_h\", stride_h);\n    cmd.get_cmd_line_argument(\"stride_w\", stride_w);\n    cmd.get_cmd_line_argument(\"dilation_h\", dilation_h);\n    cmd.get_cmd_line_argument(\"dilation_w\", dilation_w);\n    filter_size.c() = input_size.c();\n    padding = {pad_h, pad_h, pad_w, pad_w};\n    conv_stride = {stride_h, stride_w};\n    dilation = {dilation_h, dilation_w};\n  }\n\n  cutlass::Tensor4DCoord output_size() const {\n    auto dilated_h = (filter_size.h() - 1) * dilation.row() + 1;\n    auto dilated_w = (filter_size.w() - 1) * dilation.column() + 1;\n    auto h = (input_size.h() + padding.n() + padding.h() - dilated_h) / conv_stride.row() + 1;\n    auto w = (input_size.w() + padding.w() + padding.c() - dilated_w) / conv_stride.column() + 1;\n    return cutlass::Tensor4DCoord(input_size.n(), h, w, filter_size.n());\n  }\n};\n\ndouble profile_convolution(Options const &options) {\n  using ElementOutput = {{ElementOutput}};\n  using ElementInputA = typename ImplicitGemm::ElementA;\n  using ElementInputB = typename ImplicitGemm::ElementB;\n\n  int split_k_slices = {{SplitK}};\n  cutlass::conv::Conv2dProblemSize problem_size(\n\t\t\t\t\t\toptions.input_size,\n\t\t\t\t\t\toptions.filter_size,\n\t\t\t\t\t\toptions.padding,\n\t\t\t\t\t\toptions.conv_stride,\n\t\t\t\t\t\toptions.dilation,\n\t\t\t\t\t\toptions.output_size(),\n\t\t\t\t\t\tcutlass::conv::Mode::kCrossCorrelation,\n\t\t\t\t\t\tsplit_k_slices\n\t\t\t\t\t\t);\n\n  auto conv_kind = ImplicitGemm::kConvolutionalOperator;\n  auto a_extent = implicit_gemm_tensor_a_extent(conv_kind, problem_size);\n  auto b_extent = implicit_gemm_tensor_b_extent(conv_kind, problem_size);\n  auto c_extent = implicit_gemm_tensor_c_extent(conv_kind, problem_size);\n\n  using LayoutC = typename ImplicitGemm::LayoutC;\n  cutlass::HostTensor<ElementInputA, typename ImplicitGemm::LayoutA> tensor_a(a_extent);\n  cutlass::HostTensor<ElementInputB, typename ImplicitGemm::LayoutB> tensor_b(b_extent);\n  cutlass::HostTensor<ElementOutput, typename ImplicitGemm::LayoutC> tensor_c(c_extent);\n  cutlass::HostTensor<ElementOutput, LayoutC> tensor_d(c_extent);\n  cutlass::HostTensor<ImplicitGemm::ElementC, LayoutC> tensor_c_gemm(c_extent);\n\n  using ElementComputeEpilogue = typename ImplicitGemm::ElementCompute;\n\n  cutlass::conv::SplitKMode const split_k_mode = split_k_slices > 1 ?\n      cutlass::conv::SplitKMode::kParallel : cutlass::conv::SplitKMode::kSerial;\n\n  typename ImplicitGemm::Arguments arguments{\n    problem_size,\n    tensor_a.device_ref(),\n    tensor_b.device_ref(),\n    tensor_c_gemm.device_ref(),\n    tensor_c_gemm.device_ref(),\n    {ElementComputeEpilogue(1), ElementComputeEpilogue(0)},\n    split_k_mode,\n  };\n\n  ImplicitGemm implicit_gemm_op;\n  size_t workspace_size = implicit_gemm_op.get_workspace_size(arguments);\n  cutlass::device_memory::allocation<uint8_t> workspace(workspace_size);\n  auto status = implicit_gemm_op.can_implement(arguments);\n  CUTLASS_CHECK(status);\n\n  status = implicit_gemm_op.initialize(arguments, workspace.get());\n  CUTLASS_CHECK(status);\n  status = implicit_gemm_op();\n  CUTLASS_CHECK(status);\n\n  cudaEvent_t events[2];\n  for (auto & event : events) {\n    cudaEventCreate(&event);\n  }\n  cudaEventRecord(events[0]);\n\n  for (int iteration = 0; iteration < 100; ++iteration) {\n    auto status = implicit_gemm_op();\n    CUTLASS_CHECK(status);\n    {{Reduction}}\n  }\n\n  cudaEventRecord(events[1]);\n  cudaEventSynchronize(events[1]);\n  float runtime_ms = 0;\n  cudaEventElapsedTime(&runtime_ms, events[0], events[1]);\n\n  for (auto event : events) {\n    (void)cudaEventDestroy(event);\n  }\n  return double(runtime_ms) / 100.0;\n}\n\nint main(int argc, char const **args) {\n  Options options;\n  options.parse(argc, args);\n  std::cout << profile_convolution(options) << std::endl;\n  return 0;\n}\n\"\"\"\n        )\n\n    def emit(self, op_def, op_name, element_output, split_k_slices=1):\n        src = self.template.render(\n            OperatorDef=op_def,\n            OperatorName=op_name,\n            ElementOutput=DataTypeTag[element_output],\n            SplitK=split_k_slices,\n            Reduction=self.reduction if split_k_slices > 1 else \"\",\n        )\n        return src\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/gemm_operation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-wildcard-import, wildcard-import\n\"\"\"Generator for CUTLASS GEMM kernels.\"\"\"\nfrom .library import *\n\n\nclass GemmOperation:\n    \"\"\"Describes various attributes for instantiating GEMM kernels.\"\"\"\n\n    def __init__(\n        self,\n        arch,\n        tile_description,\n        A,\n        B,\n        C,\n        element_epilogue,\n        epilogue_functor=EpilogueFunctor.LinearCombination,\n        swizzling_functor=SwizzlingFunctor.Identity8,\n    ):\n        self.operation_kind = OperationKind.Gemm\n        self.arch = arch\n        self.tile_description = tile_description\n        self.A = A\n        self.B = B\n        self.C = C\n        self.element_epilogue = element_epilogue\n        self.epilogue_functor = epilogue_functor\n        self.swizzling_functor = swizzling_functor\n\n    def accumulator_type(self):\n        return self.tile_description.math_instruction.element_accumulator\n\n    def short_math_name(self):\n        return ShortDataTypeNames[self.accumulator_type()]\n\n    def core_name(self):\n        \"\"\"The basic operation kind is prefixed with a letter indicating the accumulation type.\"\"\"\n        inst_shape = \"\"\n        intermediate_type = \"\"\n\n        if (\n            self.tile_description.math_instruction.opcode_class == OpcodeClass.TensorOp\n            or self.tile_description.math_instruction.opcode_class == OpcodeClass.WmmaTensorOp\n        ):\n            inst_shape = \"%d%d%d\" % tuple(self.tile_description.math_instruction.instruction_shape)\n            if (\n                self.tile_description.math_instruction.element_a != self.A.element\n                and self.tile_description.math_instruction.element_a\n                != self.tile_description.math_instruction.element_accumulator\n            ):\n                intermediate_type = DataTypeNames[self.tile_description.math_instruction.element_a]\n\n        return \"%s%s%s%s\" % (\n            self.short_math_name(),\n            inst_shape,\n            intermediate_type,\n            \"gemm\",\n        )\n\n    def extended_name(self):\n        \"\"\"Append data types if they differ from compute type.\"\"\"\n        if (\n            self.C.element != self.tile_description.math_instruction.element_accumulator\n            and self.A.element != self.tile_description.math_instruction.element_accumulator\n        ):\n            extended_name = \"${element_c}_${core_name}_${element_a}\"\n        elif (\n            self.C.element == self.tile_description.math_instruction.element_accumulator\n            and self.A.element != self.tile_description.math_instruction.element_accumulator\n        ):\n            extended_name = \"${core_name}_${element_a}\"\n        else:\n            extended_name = \"${core_name}\"\n\n        extended_name = substitute_template(\n            extended_name,\n            {\n                \"element_a\": DataTypeNames[self.A.element],\n                \"element_c\": DataTypeNames[self.C.element],\n                \"core_name\": self.core_name(),\n            },\n        )\n\n        return extended_name\n\n    def layout_name(self):\n        return \"%s%s\" % (ShortLayoutTypeNames[self.A.layout], ShortLayoutTypeNames[self.B.layout])\n\n    def procedural_name(self):\n        \"\"\"The full procedural name indicates architecture, extended name, tile size,\n        and layout.\n        \"\"\"\n        threadblock = self.tile_description.procedural_name()\n        opcode_class_name = OpcodeClassNames[self.tile_description.math_instruction.opcode_class]\n\n        return substitute_template(\n            \"cutlass_${opcode_class}_${extended_name}_${threadblock}_${layout}_align${alignment}\",\n            {\n                \"opcode_class\": opcode_class_name,\n                \"extended_name\": self.extended_name(),\n                \"threadblock\": threadblock,\n                \"layout\": self.layout_name(),\n                \"alignment\": \"%d\" % self.A.alignment,\n            },\n        )\n\n    def leading_dim(self):\n        \"\"\"lda, ldb, ldc, according to the leading dimension.\"\"\"\n        if self.A.layout == LayoutType.RowMajor:\n            lda = \"K\"\n        elif self.A.layout == LayoutType.ColumnMajor:\n            lda = \"M\"\n        else:\n            ValueError(\"The layout of A is not implemented.\")\n\n        if self.B.layout == LayoutType.RowMajor:\n            ldb = \"N\"\n        elif self.B.layout == LayoutType.ColumnMajor:\n            ldb = \"K\"\n        else:\n            ValueError(\"The layout of B is not implemented.\")\n\n        if self.C.layout == LayoutType.RowMajor:\n            ldc = \"N\"\n        elif self.C.layout == LayoutType.ColumnMajor:\n            ldc = \"M\"\n        else:\n            ValueError(\"The layout of B is not implemented.\")\n\n        return substitute_template(\n            \"int lda = ${lda_val};\\n\\tint ldb = ${ldb_val};\\n\\tint ldc = ${ldc_val};\\n\",\n            {\n                \"lda_val\": lda,\n                \"ldb_val\": ldb,\n                \"ldc_val\": ldc,\n            },\n        )\n\n\nclass EmitGemmInstance:\n    \"\"\"Responsible for emitting a CUTLASS template definition.\"\"\"\n\n    def __init__(self):\n        self.epilogue_default = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      ${epilogue_vector_length},\n      ${element_accumulator},\n      ${element_epilogue}\n    >\"\"\"\n        self.epilogue_no_beta_scaling = \"\"\"\n    ${epilogue_functor}<\n      ${element_c},\n      ${epilogue_vector_length},\n      ${element_accumulator},\n      ${element_epilogue},\n      cutlass::epilogue::thread::ScaleType::NoBetaScaling\n    >\"\"\"\n        self.gemm_template = \"\"\"\n  // Gemm operator ${operation_name}\n  using Operation_${operation_name} = cutlass::gemm::device::${kernel_name}<\n    ${element_a}, ${layout_a},\n    ${element_b}, ${layout_b},\n    ${element_c}, ${layout_c},\n    ${element_accumulator},\n    ${opcode_class},\n    ${arch},\n    cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,\n    cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k}>,\n    cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,\n    ${epilogue},\n    ${swizzling_functor},\n    ${stages},\n    ${align_a},\n    ${align_b},\n    ${split_k_serial}\n    ${math_operation}\n  >;\n\"\"\"\n\n    def emit(self, operation, no_beta_scaling=False, batched=False):\n        \"\"\"Instantiate a GEMM kernel from given `operation`.\"\"\"\n        warp_shape = [\n            operation.tile_description.threadblock_shape[idx]\n            // operation.tile_description.warp_count[idx]\n            for idx in range(3)\n        ]\n        epilogue_vector_length = (\n            min(operation.C.alignment * DataTypeSize[operation.C.element], 128)\n            // DataTypeSize[operation.C.element]\n        )\n        values = {\n            \"operation_name\": operation.procedural_name(),\n            \"element_a\": DataTypeTag[operation.A.element],\n            \"layout_a\": LayoutTag[operation.A.layout],\n            \"element_b\": DataTypeTag[operation.B.element],\n            \"layout_b\": LayoutTag[operation.B.layout],\n            \"element_c\": DataTypeTag[operation.C.element],\n            \"layout_c\": LayoutTag[operation.C.layout],\n            \"element_accumulator\": DataTypeTag[operation.accumulator_type()],\n            \"opcode_class\": OpcodeClassTag[\n                operation.tile_description.math_instruction.opcode_class\n            ],\n            \"arch\": \"cutlass::arch::Sm%d\" % operation.arch,\n            \"threadblock_shape_m\": str(operation.tile_description.threadblock_shape[0]),\n            \"threadblock_shape_n\": str(operation.tile_description.threadblock_shape[1]),\n            \"threadblock_shape_k\": str(operation.tile_description.threadblock_shape[2]),\n            \"warp_shape_m\": str(warp_shape[0]),\n            \"warp_shape_n\": str(warp_shape[1]),\n            \"warp_shape_k\": str(warp_shape[2]),\n            \"instruction_shape_m\": str(\n                operation.tile_description.math_instruction.instruction_shape[0]\n            ),\n            \"instruction_shape_n\": str(\n                operation.tile_description.math_instruction.instruction_shape[1]\n            ),\n            \"instruction_shape_k\": str(\n                operation.tile_description.math_instruction.instruction_shape[2]\n            ),\n            \"epilogue_vector_length\": str(epilogue_vector_length),\n            \"element_epilogue\": str(DataTypeTag[operation.element_epilogue]),\n            \"epilogue_functor\": EpilogueFunctorTag[operation.epilogue_functor],\n            \"swizzling_functor\": SwizzlingFunctorTag[operation.swizzling_functor],\n            \"stages\": str(operation.tile_description.stages),\n            \"align_a\": str(operation.A.alignment),\n            \"align_b\": str(operation.B.alignment),\n            \"math_operation\": MathOperationTag[\n                operation.tile_description.math_instruction.math_operation\n            ],\n        }\n\n        values[\"kernel_name\"] = \"GemmBatched\" if batched else \"Gemm\"\n        values[\"split_k_serial\"] = \"\" if batched else \"false,\"\n\n        gemm_template = substitute_template(\n            self.gemm_template,\n            {\n                \"epilogue\": self.epilogue_no_beta_scaling\n                if no_beta_scaling\n                else self.epilogue_default\n            },\n        )\n        return substitute_template(gemm_template, values)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/gemm_profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-outside-toplevel, invalid-name\n\"\"\"Instantiate a C++ source for profiling CUTLASS kernels.\"\"\"\n\n\nclass GemmProfilerEmitter(object):\n    \"\"\"Emit a C++ source for profiling CUTLASS kernels.\"\"\"\n\n    def __init__(self):\n        from jinja2 import Template\n\n        self.template = Template(\n            \"\"\"\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <chrono>\n\n#include \"cuda_runtime.h\"\n#include \"cutlass/gemm/device/gemm.h\"\n\n#define CUTLASS_CHECK(status)                                                                    \\\\\n  {                                                                                              \\\\\n    cutlass::Status error = status;                                                              \\\\\n    if (error != cutlass::Status::kSuccess) {                                                    \\\\\n      std::cerr << \"Got cutlass error: \" << cutlassGetStatusString(error) << \" at: \" << __LINE__ \\\\\n                << std::endl;                                                                    \\\\\n      exit(EXIT_FAILURE);                                                                        \\\\\n    }                                                                                            \\\\\n  }\n\n#define CUDA_CHECK(status)                                              \\\\\n  {                                                                     \\\\\n    cudaError_t error = status;                                         \\\\\n    if (error != cudaSuccess) {                                         \\\\\n      std::cerr << \"Got bad cuda status: \" << cudaGetErrorString(error) \\\\\n                << \" at line: \" << __LINE__ << std::endl;               \\\\\n      exit(EXIT_FAILURE);                                               \\\\\n    }                                                                   \\\\\n  }\n\ntemplate<typename DTypeA, typename DTypeB, typename DTypeC>\ncudaError_t CutlassGemmRCR(\n    int M,\n    int N,\n    int K,\n    DTypeC alpha,\n    DTypeA const *A,\n    int lda,\n    DTypeB const *B,\n    int ldb,\n    DTypeC beta,\n    DTypeC *C,\n    int ldc) {\n  using namespace std::chrono;\n  {{OperatorDef}}\n  Operation_{{OperatorName}} gemm_operator;\n  Operation_{{OperatorName}}::Arguments args({M, N, K},\n                              {A, lda},\n                              {B, ldb},\n                              {C, ldc},\n                              {C, ldc},\n                              {alpha, beta});\n  cutlass::Status status = gemm_operator(args);\n  CUTLASS_CHECK(status)\n\n  high_resolution_clock::time_point t1 = high_resolution_clock::now();\n  for (int i = 0; i < 100; ++i) {\n    status = gemm_operator(args);\n  }\n  cudaDeviceSynchronize();\n  high_resolution_clock::time_point t2 = high_resolution_clock::now();\n  duration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n  std::cout << time_span.count() << std::endl;\n  return cudaSuccess;\n}\n\n\ntemplate<typename DType>\ncudaError_t AllocateMatrix(DType **matrix, int ldm, int rows, int columns, int seed = 0) {\n  cudaError_t result;\n\n  size_t sizeof_matrix = sizeof(DType) * rows * columns;\n\n  // Allocate device memory.\n  result = cudaMalloc(reinterpret_cast<void **>(matrix), sizeof_matrix);\n\n  if (result != cudaSuccess) {\n    std::cerr << \"Failed to allocate matrix: \"\n      << cudaGetErrorString(result) << std::endl;\n    return result;\n  }\n\n  // Clear the allocation.\n  result = cudaMemset(*matrix, 0, sizeof_matrix);\n\n  if (result != cudaSuccess) {\n    std::cerr << \"Failed to clear matrix device memory: \"\n      << cudaGetErrorString(result) << std::endl;\n    return result;\n  }\n\n  if (result != cudaSuccess) {\n    std::cerr << \"Failed to initialize matrix: \"\n      << cudaGetErrorString(result) << std::endl;\n    return result;\n  }\n\n  return result;\n}\n\ntemplate<typename DTypeA, typename DTypeB, typename DTypeC>\ncudaError_t TestCutlassGemm(int M, int N, int K, DTypeC alpha, DTypeC beta) {\n  cudaError_t result;\n\n  {{LeadingDim}}\n  // size_t sizeof_C = sizeof(DTypeC) * ldc * N;\n  DTypeA *A;\n  DTypeB *B;\n  DTypeC *C_cutlass;\n  result = AllocateMatrix<DTypeA>(&A, lda, M, K, 0);\n  if (result !=  cudaSuccess) {\n    return result;\n  }\n  result = AllocateMatrix<DTypeB>(&B, ldb, K, N, 17);\n  if (result !=  cudaSuccess) {\n    cudaFree(A);\n    return result;\n  }\n  result = AllocateMatrix<DTypeC>(&C_cutlass, ldc, M, N, 101);\n  if (result != cudaSuccess) {\n    cudaFree(A);\n    cudaFree(B);\n    return result;\n  }\n  result = CutlassGemmRCR<DTypeA, DTypeB, DTypeC>(M, N, K, alpha, A, lda, B, ldb,\n                                                  beta, C_cutlass, ldc);\n  if (result != cudaSuccess) {\n    std::cerr << \"CUTLASS GEMM kernel failed: \"\n      << cudaGetErrorString(result) << std::endl;\n    cudaFree(C_cutlass);\n    cudaFree(B);\n    cudaFree(A);\n\n    return result;\n  }\n  cudaFree(C_cutlass);\n  cudaFree(B);\n  cudaFree(A);\n  return cudaSuccess;\n}\n\nint main(int argc, const char *arg[]) {\n  int problem[3] = { 4096, 4096, 4096 };\n  for (int i = 1; i < argc && i < 4; ++i) {\n    std::stringstream ss(arg[i]);\n    ss >> problem[i - 1];\n  }\n  float scalars[2] = { 1, 0 };\n  cudaError_t result = TestCutlassGemm< {{DTypeA}}, {{DTypeB}}, {{DTypeC}}>(\n    problem[0],     // GEMM M dimension\n    problem[1],     // GEMM N dimension\n    problem[2],     // GEMM K dimension\n    static_cast<{{DTypeC}}>(scalars[0]),     // alpha\n    static_cast<{{DTypeC}}>(scalars[1])      // beta\n  );\n  return result == cudaSuccess ? 0 : -1;\n}\n\"\"\"\n        )\n\n    def emit(self, op_name, op_def, dtype_a, dtype_b, dtype_c, ld):\n        src = self.template.render(\n            OperatorName=op_name,\n            OperatorDef=op_def,\n            DTypeA=dtype_a,\n            DTypeB=dtype_b,\n            DTypeC=dtype_c,\n            LeadingDim=ld,\n        )\n        return src\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/gen_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, dangerous-default-value\n\"\"\"Conv2d kernel generator and profiler for CUTLASS.\"\"\"\nfrom functools import partial\nfrom .conv2d_operation import Conv2dOperation, EmitConv2dInstance\nfrom .gen_gemm import CutlassGemmProfiler\nfrom .conv2d_profiler import Conv2dProfilerEmitter\nfrom .gen_tensor_op import ProfilerEngine, GENERATOR_FUNC_TABLE, EPILOGUE_MAP\nfrom .library import (\n    DataType,\n    EpilogueFunctor,\n    SwizzlingFunctor,\n    TensorDescription,\n    LayoutType,\n    ConvKind,\n    StrideSupport,\n    IteratorAlgorithm,\n)\n\n\ndef create_conv2d_operator_with_epilogue(\n    conv_kind,\n    stride_support,\n    op_type,\n    tile_description,\n    data_type,\n    alignment,\n    swizzling_functor,\n    split_k_slices,\n):\n    \"\"\"\n    Instantiate a cutlass kernel from the given configuration,\n    along with the epilouge functor\n    \"\"\"\n    if \"residual\" in op_type:\n        activation_map = {\n            \"cutlass.conv2d_bias_hardswish\": \"cutlass::epilogue::thread::HardSwish\",\n            \"cutlass.conv2d_bias_silu\": \"cutlass::epilogue::thread::SiLu\",\n            \"cutlass.conv2d_bias_sigmoid\": \"cutlass::epilogue::thread::Sigmoid\",\n            \"cutlass.conv2d_bias_relu\": \"cutlass::epilogue::thread::ReLu\",\n            \"cutlass.conv2d_bias\": \"cutlass::epilogue::thread::Identity\",\n        }\n        prefix = op_type[: op_type.find(\"_residual\")]\n        activation = activation_map[prefix]\n        binary_op = \"cutlass::multiplies\" if \"residual_multiply\" in op_type else \"cutlass::plus\"\n        unary_op = (\n            \"cutlass::epilogue::thread::ReLu\"\n            if op_type.endswith(\"relu\")\n            else \"cutlass::epilogue::thread::Identity\"\n        )\n        residual_block_info = {\n            \"activation\": activation,\n            \"binary_op\": binary_op,\n            \"unary_op\": unary_op,\n        }\n        epilogue = EpilogueFunctor.LinearCombinationResidualBlock\n        no_beta_scaling = False\n    else:\n        residual_block_info = None\n        epilogue, no_beta_scaling = EPILOGUE_MAP[op_type]\n\n    element_a, element_b, element_c, element_epilogue = data_type\n\n    A = TensorDescription(element_a, LayoutType.TensorNHWC, alignment)\n    B = TensorDescription(element_b, LayoutType.TensorNHWC, alignment)\n    C = TensorDescription(element_c, LayoutType.TensorNHWC, alignment)\n\n    op = Conv2dOperation(\n        conv_kind,\n        IteratorAlgorithm.Optimized,\n        tile_description.minimum_compute_capability,\n        tile_description,\n        A,\n        B,\n        C,\n        element_epilogue,\n        stride_support,\n        epilogue,\n        swizzling_functor,\n        split_k_slices,\n    )\n\n    name = op.procedural_name()\n    opdef = EmitConv2dInstance().emit(\n        op,\n        no_beta_scaling=no_beta_scaling,\n        residual_block_info=residual_block_info,\n        emit_reduction=split_k_slices > 1,\n    )\n\n    return name, opdef\n\n\ndef enumerate_conv2d_operators(\n    conv_kind,\n    stride_support,\n    split_k_slices,\n    tile_descriptions,\n    data_type,\n    alignment_constraints,\n    swizzling_functor=SwizzlingFunctor.Identity4,\n):\n    \"\"\"Exhaustively instantiate all kernels from a given configuration.\"\"\"\n    ret = []\n\n    kernel_emitter = EmitConv2dInstance()\n    profiler_emitter = Conv2dProfilerEmitter()\n\n    element_a, element_b, element_c, element_epilogue = data_type\n\n    if conv_kind == ConvKind.Dgrad and stride_support == StrideSupport.Strided:\n        swizzling_functor = SwizzlingFunctor.StridedDgradIdentity1\n\n    for split_k_slice in split_k_slices:\n        for tile in tile_descriptions:\n            for alignment in alignment_constraints:\n\n                A = TensorDescription(element_a, LayoutType.TensorNHWC, alignment)\n                B = TensorDescription(element_b, LayoutType.TensorNHWC, alignment)\n                C = TensorDescription(element_c, LayoutType.TensorNHWC, alignment)\n\n                if element_c == DataType.s32 and A.alignment == 1:\n                    tile.threadblock_shape[0] = min(tile.threadblock_shape[0], 128)\n                    tile.threadblock_shape[1] = min(tile.threadblock_shape[1], 128)\n\n                op = Conv2dOperation(\n                    conv_kind,\n                    IteratorAlgorithm.Optimized,\n                    tile.minimum_compute_capability,\n                    tile,\n                    A,\n                    B,\n                    C,\n                    element_epilogue,\n                    stride_support,\n                    EpilogueFunctor.LinearCombination,\n                    swizzling_functor,\n                    split_k_slice,\n                )\n\n                ret.append(\n                    {\n                        \"src\": profiler_emitter.emit(\n                            kernel_emitter.emit(op, emit_reduction=split_k_slice > 1),\n                            op.procedural_name(),\n                            element_output=element_c,\n                            split_k_slices=split_k_slice,\n                        ),\n                        \"name\": op.procedural_name(),\n                        \"tile_description\": tile,\n                        \"alignment\": alignment,\n                        \"data_type\": data_type,\n                        \"swizzle_functor\": swizzling_functor,\n                        \"split_k_slices\": split_k_slice,\n                    }\n                )\n\n    return ret\n\n\nclass CutlassConv2DProfiler:\n    \"\"\"Profile all candidate kernels and select the best one.\"\"\"\n\n    def __init__(self, sm, cutlass_path, binary_path):\n        self.gemm_profiler = CutlassGemmProfiler(sm, cutlass_path, binary_path)\n        self.sm = sm\n        assert sm in GENERATOR_FUNC_TABLE, \"sm%d not supported yet.\" % sm\n        self.engine = ProfilerEngine(sm, cutlass_path, binary_path)\n        self.cache = {}\n\n    def get_default(\n        self,\n        op_type,\n        out_dtype,\n        arg0_dtype,\n        arg1_dtype,\n        use_3xtf32,\n        conv_kind=ConvKind.Fprop,\n        stride=(1, 1),\n    ):\n        \"\"\"Return the default kernel for the requested architecture.\n        For now, the default kernel was picked arbitrary.\n        \"\"\"\n        gemm_profile_result = self.gemm_profiler.get_default(\n            op_type, out_dtype, arg0_dtype, arg1_dtype, use_3xtf32\n        )\n        tile_description = gemm_profile_result[\"tile_description\"]\n        alignment = gemm_profile_result[\"alignment\"]\n        data_type = gemm_profile_result[\"data_type\"]\n        stride_support = StrideSupport.Strided if stride[0] > 1 else StrideSupport.Unity\n\n        if conv_kind == ConvKind.Dgrad and stride_support == StrideSupport.Strided:\n            swizzling_functor = SwizzlingFunctor.StridedDgradIdentity1\n        else:\n            swizzling_functor = SwizzlingFunctor.Identity4\n\n        name, opdef = create_conv2d_operator_with_epilogue(\n            conv_kind,\n            stride_support,\n            op_type,\n            tile_description,\n            data_type,\n            alignment,\n            swizzling_functor,\n            split_k_slices=1,\n        )\n        return {\"name\": name, \"opdef\": opdef}\n\n    def select_op(\n        self,\n        d_shape,\n        w_shape,\n        padding,\n        stride,\n        dilation,\n        out_dtype,\n        data_dtype,\n        weight_dtype,\n        use_3xtf32,\n        conv_kind,\n        stride_support,\n        split_k_slices,\n        profile_all_alignments=False,\n        find_first_valid=False,\n        use_multiprocessing=False,\n    ):\n        \"\"\"\n        Profile and select the best kernel from candidate kernels.\n        See the documentation for the profile method below.\n        \"\"\"\n        N, H, W, IC = d_shape\n        OC, R, S, _ = w_shape\n\n        workload = (\n            N,\n            H,\n            W,\n            IC,\n            OC,\n            R,\n            S,\n            padding[0],\n            padding[1],\n            stride[0],\n            stride[1],\n            dilation[0],\n            dilation[1],\n        )\n\n        if workload in self.cache:\n            return self.cache[workload]\n\n        ops = GENERATOR_FUNC_TABLE[self.sm](\n            out_dtype,\n            data_dtype,\n            weight_dtype,\n            partial(enumerate_conv2d_operators, conv_kind, stride_support, split_k_slices),\n            lambda align: all([dim % align == 0 for dim in [IC, OC]]),\n            use_3xtf32,\n            profile_all_alignments,\n            # Use fp32 accumulation for wgrad to align with cuDNN\n            accumlator_dtype=\"float32\" if conv_kind == ConvKind.Wgrad else out_dtype,\n        )\n\n        if not find_first_valid:\n            self.engine.compile_all(ops, use_multiprocessing)\n\n        args = (\n            \"--n=%d --h=%d --w=%d --c=%d --k=%d --r=%d --s=%d --pad_h=%d --pad_w=%d \"\n            \"--stride_h=%d --stride_w=%d --dilation_h=%d --dilation_w=%d\"\n        ) % workload\n\n        for op in ops:\n            out = self.engine.evaluate(op, args.split(\" \"))\n            op[\"runtime\"] = out\n            if out < float(\"inf\") and find_first_valid:\n                self.cache[workload] = op\n                return op\n\n        op = min(ops, key=lambda i: i[\"runtime\"])\n        self.cache[workload] = op\n        return op\n\n    def profile(\n        self,\n        op_type,\n        d_shape,\n        w_shape,\n        padding,\n        stride,\n        dilation,\n        out_dtype,\n        data_dtype,\n        weight_dtype,\n        use_3xtf32=True,\n        conv_kind=ConvKind.Fprop,\n        split_k_slices=[1],\n        profile_all_alignments=False,\n        find_first_valid=False,\n        use_multiprocessing=False,\n    ):\n        \"\"\"Profile and select the best kernel from candidate kernels.\n        If find_first_valid is True, return immediately after the first applicable kernel is found.\n        If use_multiprocessing is True, compile all profiler executables in parallel.\n        \"\"\"\n        # Dgrad requires Unity stride when stride == (1, 1)\n        stride_support = (\n            StrideSupport.Unity\n            if stride[0] == 1 and stride[1] == 1 and conv_kind == ConvKind.Dgrad\n            else StrideSupport.Strided\n        )\n\n        op = self.select_op(\n            d_shape,\n            w_shape,\n            padding,\n            stride,\n            dilation,\n            out_dtype,\n            data_dtype,\n            weight_dtype,\n            use_3xtf32,\n            conv_kind,\n            stride_support,\n            split_k_slices,\n            profile_all_alignments,\n            find_first_valid,\n            use_multiprocessing,\n        )\n\n        name, opdef = create_conv2d_operator_with_epilogue(\n            conv_kind,\n            stride_support,\n            op_type,\n            op[\"tile_description\"],\n            op[\"data_type\"],\n            op[\"alignment\"],\n            op[\"swizzle_functor\"],\n            op[\"split_k_slices\"],\n        )\n\n        return name, opdef, op[\"runtime\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/gen_gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"GEMM kernel generator and profiler for CUTLASS.\"\"\"\nfrom .gemm_operation import GemmOperation, EmitGemmInstance\nfrom .gemm_profiler import GemmProfilerEmitter\nfrom .gen_tensor_op import ProfilerEngine, GENERATOR_FUNC_TABLE, EPILOGUE_MAP\nfrom .library import (\n    DataType,\n    EpilogueFunctor,\n    SwizzlingFunctor,\n    TensorDescription,\n    DataTypeTag,\n    LayoutType,\n)\n\n\ndef create_gemm_operator_with_epilogue(\n    op_type,\n    tile_description,\n    data_type,\n    alignment,\n    swizzling_functor,\n    batched=False,\n):\n    \"\"\"\n    Instantiate a cutlass kernel from the given configuration,\n    along with the epilouge functor\n    \"\"\"\n    element_a, element_b, element_c, element_epilogue = data_type\n\n    A = TensorDescription(element_a, LayoutType.RowMajor, alignment)\n    B = TensorDescription(element_b, LayoutType.ColumnMajor, alignment)\n    C = TensorDescription(element_c, LayoutType.RowMajor, alignment)\n\n    if batched:\n        swizzling_functor = SwizzlingFunctor.Batched\n\n    epilogue, no_beta_scaling = EPILOGUE_MAP[op_type]\n\n    op = GemmOperation(\n        tile_description.minimum_compute_capability,\n        tile_description,\n        A,\n        B,\n        C,\n        element_epilogue,\n        epilogue,\n        swizzling_functor,\n    )\n\n    return (\n        op.procedural_name(),\n        EmitGemmInstance().emit(op, no_beta_scaling=no_beta_scaling, batched=batched),\n    )\n\n\ndef enumerate_gemm_operators(\n    tile_descriptions,\n    data_type,\n    alignment_constraints,\n    swizzling_functor=SwizzlingFunctor.Identity8,\n):\n    \"\"\"Exhaustively instantiate all kernels from a given configuration.\"\"\"\n    ret = []\n    kernel_emitter = EmitGemmInstance()\n    profiler_emitter = GemmProfilerEmitter()\n\n    element_a, element_b, element_c, element_epilogue = data_type\n\n    for tile_description in tile_descriptions:\n        for alignment in alignment_constraints:\n            A = TensorDescription(element_a, LayoutType.RowMajor, alignment)\n            B = TensorDescription(element_b, LayoutType.ColumnMajor, alignment)\n            C = TensorDescription(element_c, LayoutType.RowMajor, alignment)\n\n            if element_c == DataType.s32 and A.alignment == 1:\n                tile_description.threadblock_shape[0] = min(\n                    tile_description.threadblock_shape[0], 128\n                )\n                tile_description.threadblock_shape[1] = min(\n                    tile_description.threadblock_shape[1], 128\n                )\n\n            op = GemmOperation(\n                tile_description.minimum_compute_capability,\n                tile_description,\n                A,\n                B,\n                C,\n                element_epilogue,\n                EpilogueFunctor.LinearCombination,\n                swizzling_functor,\n            )\n\n            src = profiler_emitter.emit(\n                op.procedural_name(),\n                kernel_emitter.emit(op, batched=False),\n                DataTypeTag[element_a],\n                DataTypeTag[element_b],\n                DataTypeTag[element_c],\n                op.leading_dim(),\n            )\n\n            ret.append(\n                {\n                    \"src\": src,\n                    \"op\": op,\n                    \"name\": op.procedural_name(),\n                    \"tile_description\": tile_description,\n                    \"alignment\": alignment,\n                    \"data_type\": data_type,\n                    \"swizzle_functor\": swizzling_functor,\n                }\n            )\n\n    return ret\n\n\n# TODO(masahi): A sensible way to pick reasonable default kernels\nDEFAULT_KERNELS = {\n    75: {\n        (\"float16\", \"float16\"): \"cutlass_tensorop_h1688gemm_128x64_32x2_tn_align1\",\n        (\"float16\", \"float32\"): \"cutlass_tensorop_s1688gemm_f16_64x64_32x2_tn_align1\",\n    },\n    # align1 variants do not seem to be available for sm80\n    80: {\n        (\"float16\", \"float16\"): \"cutlass_tensorop_h1688gemm_128x64_32x2_tn_align1\",\n        (\"float16\", \"float32\"): \"cutlass_tensorop_s1688gemm_f16_64x64_32x2_tn_align1\",\n        # two kernels for tf32 and 3xtf32\n        (\"float32\", \"float32\"): (\n            \"cutlass_tensorop_s1688gemm_128x64_32x3_tn_align1\",\n            \"cutlass_tensorop_s1688gemm_64x64_16x3_tn_align1\",\n        ),\n    },\n}\n\n\nclass CutlassGemmProfiler:\n    \"\"\"Profile all candidate kernels and select the best one.\"\"\"\n\n    def __init__(self, sm, cutlass_path, binary_path):\n        assert sm in GENERATOR_FUNC_TABLE and sm in DEFAULT_KERNELS, \"sm%d not supported yet.\" % sm\n        self.engine = ProfilerEngine(sm, cutlass_path, binary_path)\n        self.sm = sm\n        self.cache = {}\n\n    def get_default(\n        self, op_type, out_dtype, arg0_dtype, arg1_dtype, use_3xtf32=True, batched=False\n    ):\n        \"\"\"Return the default kernel for the requested architecture.\n        For now, the default kernel was picked arbitrary.\n        \"\"\"\n        ops = GENERATOR_FUNC_TABLE[self.sm](\n            out_dtype,\n            arg0_dtype,\n            arg1_dtype,\n            enumerate_gemm_operators,\n            lambda align: align == 1,  # Only request align1 kernels\n            use_3xtf32,\n            profile_all_alignments=True,  # To include all align1 kernels\n            # TODO(masahi): Invesitigate when fp32 accumulation is needed for gemm\n            accumlator_dtype=out_dtype,\n        )\n\n        default_kernel_name = DEFAULT_KERNELS[self.sm][(arg0_dtype, out_dtype)]\n\n        if arg0_dtype == \"float32\":\n            default_kernel_name = (\n                default_kernel_name[0] if not use_3xtf32 else default_kernel_name[1]\n            )\n\n        filtered = list(filter(lambda op: op[\"name\"] == default_kernel_name, ops))\n        assert len(filtered) == 1\n        op = filtered[0]\n        name, opdef = create_gemm_operator_with_epilogue(\n            op_type,\n            op[\"tile_description\"],\n            op[\"data_type\"],\n            op[\"alignment\"],\n            op[\"swizzle_functor\"],\n            batched=batched,\n        )\n        op.update({\"name\": name, \"opdef\": opdef})\n        return op\n\n    def select_op(\n        self,\n        M,\n        N,\n        K,\n        out_dtype,\n        arg0_dtype,\n        arg1_dtype,\n        use_3xtf32,\n        profile_all_alignments=False,\n        find_first_valid=False,\n        use_multiprocessing=False,\n    ):\n        \"\"\"\n        Profile and select the best kernel from candidate kernels.\n        See the documentation for the profile method below.\n        \"\"\"\n        if (M, N, K) in self.cache:\n            op = self.cache[(M, N, K)]\n            return op\n\n        # TODO(masahi): CUTLASS alignment check on gemm kernels is too restrictive.\n        # See https://github.com/NVIDIA/cutlass/issues/362.\n        # When the above issue is resolved, we can remove the alignment check on M below.\n\n        ops = GENERATOR_FUNC_TABLE[self.sm](\n            out_dtype,\n            arg0_dtype,\n            arg1_dtype,\n            enumerate_gemm_operators,\n            lambda align: all([dim % align == 0 for dim in [M, N, K]]),\n            use_3xtf32,\n            profile_all_alignments=profile_all_alignments,\n            # TODO(masahi): Invesitigate when fp32 accumulation is needed for gemm\n            accumlator_dtype=out_dtype,\n        )\n\n        if not find_first_valid:\n            self.engine.compile_all(ops, use_multiprocessing)\n\n        for op in ops:\n            out = self.engine.evaluate(op, [M, N, K])\n            op[\"runtime\"] = out\n            if out < float(\"inf\") and find_first_valid:\n                self.cache[(M, N, K)] = op\n                return op\n\n        op = min(ops, key=lambda i: i[\"runtime\"])\n        self.cache[(M, N, K)] = op\n        return op\n\n    def profile(\n        self,\n        op_type,\n        M,\n        N,\n        K,\n        out_dtype,\n        arg0_dtype,\n        arg1_dtype,\n        use_3xtf32=True,\n        profile_all_alignments=False,\n        find_first_valid=False,\n        use_multiprocessing=False,\n        batched=False,\n    ):\n        \"\"\"Profile and select the best kernel from candidate kernels.\n        If find_first_valid is True, return immediately after the first applicable kernel is found.\n        If use_multiprocessing is True, compile all profiler executables in parallel.\n        \"\"\"\n        op = self.select_op(\n            M,\n            N,\n            K,\n            out_dtype,\n            arg0_dtype,\n            arg1_dtype,\n            use_3xtf32,\n            profile_all_alignments=profile_all_alignments,\n            find_first_valid=find_first_valid,\n            use_multiprocessing=use_multiprocessing,\n        )\n\n        name, opdef = create_gemm_operator_with_epilogue(\n            op_type,\n            op[\"tile_description\"],\n            op[\"data_type\"],\n            op[\"alignment\"],\n            op[\"swizzle_functor\"],\n            batched=batched,\n        )\n\n        return name, opdef, op[\"runtime\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/gen_tensor_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Common functions and classes for CUTLASS GEMM and Conv2d geneator.\"\"\"\nimport logging\nimport os\nimport tempfile\nimport subprocess\nimport multiprocessing\nfrom .library import (\n    MathInstruction,\n    DataType,\n    OpcodeClass,\n    MathOperation,\n    TileDescription,\n    EpilogueFunctor,\n)\n\nlogger = logging.getLogger(\"cutlass\")\n\n\ndtype_map = {\n    \"int8\": DataType.s8,\n    \"uint8\": DataType.u8,\n    \"float32\": DataType.f32,\n    \"float16\": DataType.f16,\n}\n\n\ndef generate_tensor_op_common(\n    math_instructions, alignment_constraints, get_tile_descriptions, op_creator\n):\n    \"\"\"Common kernel generator to be used by archtecture specific generators.\"\"\"\n    ops = []\n    for math_inst in math_instructions:\n        tile_descriptions = get_tile_descriptions(math_inst)\n        data_type = [\n            math_inst.element_a,\n            math_inst.element_b,\n            math_inst.element_c,\n            math_inst.element_accumulator,\n        ]\n\n        out = op_creator(tile_descriptions, data_type, alignment_constraints)\n\n        ops.extend(out)\n\n    return ops\n\n\ndef generate_sm75_tensor_op_1688(\n    out_dtype,\n    arg0_dtype,\n    arg1_dtype,\n    op_creator,\n    check_align,\n    _,\n    profile_all_alignments=False,\n    accumlator_dtype=\"float32\",\n):\n    \"\"\"Generate GEMM or Conv2D kernels for Turing.\"\"\"\n    assert out_dtype in [\"float32\", \"float16\", \"int32\"]\n    min_cc = 75\n    max_cc = 1024\n\n    if arg0_dtype == \"float16\" and arg1_dtype == \"float16\":\n        math_instructions = [\n            MathInstruction(\n                [16, 8, 8],\n                DataType.f16,\n                DataType.f16,\n                dtype_map[out_dtype],\n                dtype_map[accumlator_dtype],\n                OpcodeClass.TensorOp,\n                MathOperation.multiply_add,\n            )\n        ]\n        alignment_constraints = [8, 4, 2, 1]\n        tile_descriptions = [\n            ([256, 128, 32], 2, [4, 2, 1], min_cc, max_cc),\n            ([128, 256, 32], 2, [2, 4, 1], min_cc, max_cc),\n            ([128, 128, 32], 2, [2, 2, 1], min_cc, max_cc),\n            ([64, 128, 32], 2, [2, 2, 1], min_cc, max_cc),\n            ([128, 64, 32], 2, [2, 2, 1], min_cc, max_cc),\n            ([64, 64, 32], 2, [2, 2, 1], min_cc, max_cc),\n            ([64, 128, 64], 2, [1, 2, 2], min_cc, max_cc),\n        ]\n\n    else:\n        assert out_dtype == \"int32\"\n        math_instructions = [\n            MathInstruction(\n                [8, 8, 16],\n                dtype_map[arg0_dtype],\n                dtype_map[arg1_dtype],\n                DataType.s32,\n                DataType.s32,\n                OpcodeClass.TensorOp,\n                MathOperation.multiply_add_saturate,\n            ),\n        ]\n        alignment_constraints = [16, 8, 4, 2, 1]\n        tile_descriptions = [\n            ([256, 128, 64], 2, [4, 2, 1], min_cc, max_cc),\n            ([128, 256, 64], 2, [2, 4, 1], min_cc, max_cc),\n            ([128, 128, 64], 2, [2, 2, 1], min_cc, max_cc),\n            ([64, 256, 64], 2, [1, 4, 1], min_cc, max_cc),\n            ([256, 64, 64], 2, [4, 1, 1], min_cc, max_cc),\n            ([64, 128, 64], 2, [2, 2, 1], min_cc, max_cc),\n            ([128, 64, 64], 2, [2, 2, 1], min_cc, max_cc),\n            ([64, 64, 64], 2, [2, 2, 1], min_cc, max_cc),\n        ]\n\n    alignment_constraints = [align for align in alignment_constraints if check_align(align)]\n    assert len(alignment_constraints) > 0\n\n    if not profile_all_alignments:\n        alignment_constraints = [alignment_constraints[0]]\n\n    def get_tile_descriptions(math_inst):\n        return [\n            TileDescription(threadblock_shape, stages, warp_count, math_inst, min_cc, max_cc)\n            for threadblock_shape, stages, warp_count, min_cc, max_cc in tile_descriptions\n        ]\n\n    return generate_tensor_op_common(\n        math_instructions, alignment_constraints, get_tile_descriptions, op_creator\n    )\n\n\ndef generate_sm80_tensor_op_16816(\n    out_dtype,\n    arg0_dtype,\n    arg1_dtype,\n    op_creator,\n    check_align,\n    use_3xtf32=True,\n    profile_all_alignments=False,\n    accumlator_dtype=\"float32\",\n):\n    \"\"\"Generate GEMM or Conv2D kernels for Ampere.\"\"\"\n    min_cc = 80\n    max_cc = 1024\n    max_cc_smem_limited = 80\n\n    def get_default_tile_descriptions(block_k_factor):\n        return [\n            ([256, 128, int(32 * block_k_factor)], 3, [4, 2, 1], min_cc, max_cc),\n            ([128, 256, int(32 * block_k_factor)], 3, [2, 4, 1], min_cc, max_cc),\n            ([256, 64, int(32 * block_k_factor)], 4, [4, 1, 1], min_cc, max_cc),\n            ([64, 256, int(32 * block_k_factor)], 4, [1, 4, 1], min_cc, max_cc),\n            ([128, 128, int(32 * block_k_factor)], 3, [2, 2, 1], min_cc, max_cc),\n            ([128, 128, int(32 * block_k_factor)], 4, [2, 2, 1], min_cc, max_cc),\n            ([128, 128, int(32 * block_k_factor)], 5, [2, 2, 1], min_cc, max_cc),\n            ([128, 64, int(32 * block_k_factor)], 6, [2, 2, 1], min_cc, max_cc),\n            ([64, 128, int(32 * block_k_factor)], 6, [2, 2, 1], min_cc, max_cc),\n            ([64, 64, int(32 * block_k_factor)], 10, [2, 2, 1], min_cc, max_cc),\n            ([256, 128, int(64 * block_k_factor)], 3, [4, 2, 1], min_cc, max_cc_smem_limited),\n            ([128, 256, int(64 * block_k_factor)], 3, [2, 4, 1], min_cc, max_cc_smem_limited),\n            ([256, 64, int(64 * block_k_factor)], 4, [4, 1, 1], min_cc, max_cc_smem_limited),\n            ([64, 256, int(64 * block_k_factor)], 4, [1, 4, 1], min_cc, max_cc_smem_limited),\n            ([128, 128, int(64 * block_k_factor)], 4, [2, 2, 1], min_cc, max_cc),\n            ([128, 64, int(64 * block_k_factor)], 3, [2, 2, 1], min_cc, max_cc),\n            ([64, 128, int(64 * block_k_factor)], 3, [2, 2, 1], min_cc, max_cc),\n            ([64, 64, int(64 * block_k_factor)], 5, [2, 2, 1], min_cc, max_cc),\n        ]\n\n    if arg0_dtype == \"float16\" and arg1_dtype == \"float16\":\n        math_instructions = [\n            MathInstruction(\n                [16, 8, 16],\n                DataType.f16,\n                DataType.f16,\n                dtype_map[out_dtype],\n                dtype_map[accumlator_dtype],\n                OpcodeClass.TensorOp,\n                MathOperation.multiply_add,\n            )\n        ]\n        alignment_constraints = [8, 4, 2]\n        tile_descriptions = get_default_tile_descriptions(1)\n    elif arg0_dtype == \"float32\" and arg1_dtype == \"float32\":\n        math_instructions = [\n            MathInstruction(\n                [16, 8, 8],\n                DataType.f32,\n                DataType.f32,\n                DataType.f32,\n                DataType.f32,\n                OpcodeClass.TensorOp,\n                MathOperation.multiply_add_fast_f32 if use_3xtf32 else MathOperation.multiply_add,\n            ),\n        ]\n        alignment_constraints = [4, 2, 1]\n\n        if use_3xtf32:\n            tile_descriptions = [\n                ([128, 128, 16], 4, [4, 2, 1], min_cc, max_cc),\n                ([128, 128, 16], 3, [4, 2, 1], min_cc, max_cc),\n                ([256, 64, 16], 3, [4, 2, 1], min_cc, max_cc),\n                ([64, 256, 16], 3, [2, 4, 1], min_cc, max_cc),\n                ([128, 64, 16], 4, [2, 2, 1], min_cc, max_cc),\n                ([64, 128, 16], 4, [2, 2, 1], min_cc, max_cc),\n                ([64, 64, 16], 3, [2, 2, 1], min_cc, max_cc),\n                ([128, 128, 32], 3, [4, 2, 1], min_cc, max_cc),\n                ([256, 64, 32], 3, [4, 2, 1], min_cc, max_cc_smem_limited),\n                ([64, 256, 32], 3, [2, 4, 1], min_cc, max_cc_smem_limited),\n                ([128, 64, 32], 3, [2, 2, 1], min_cc, max_cc),\n                ([64, 128, 32], 3, [2, 2, 1], min_cc, max_cc),\n                ([64, 64, 32], 3, [2, 2, 1], min_cc, max_cc),\n            ]\n        else:\n            tile_descriptions = get_default_tile_descriptions(0.5)\n    else:\n        assert out_dtype == \"int32\"\n        math_instructions = [\n            MathInstruction(\n                [16, 8, 32],\n                dtype_map[arg0_dtype],\n                dtype_map[arg1_dtype],\n                DataType.s32,\n                DataType.s32,\n                OpcodeClass.TensorOp,\n                MathOperation.multiply_add_saturate,\n            ),\n        ]\n        alignment_constraints = [16, 8, 4]\n        tile_descriptions = get_default_tile_descriptions(2)\n\n    def get_tile_descriptions(math_inst):\n        return [\n            TileDescription(threadblock_shape, stages, warp_count, math_inst, min_cc, max_cc)\n            for threadblock_shape, stages, warp_count, min_cc, max_cc in tile_descriptions\n        ]\n\n    alignment_constraints = [align for align in alignment_constraints if check_align(align)]\n\n    if len(alignment_constraints) > 0 and not profile_all_alignments:\n        alignment_constraints = [alignment_constraints[0]]\n\n    if arg0_dtype != \"float32\" and arg1_dtype != \"float32\":\n        sm75_kernels = generate_sm75_tensor_op_1688(\n            out_dtype,\n            arg0_dtype,\n            arg1_dtype,\n            op_creator,\n            check_align,\n            False,\n            profile_all_alignments,\n            accumlator_dtype=accumlator_dtype,\n        )\n    else:\n        # TF32 (float32 + float32 case) is only supported on sm80\n        sm75_kernels = []\n\n    if len(alignment_constraints) > 0:\n        sm80_kernels = generate_tensor_op_common(\n            math_instructions, alignment_constraints, get_tile_descriptions, op_creator\n        )\n    else:\n        sm80_kernels = []\n\n    # TODO(masahi): For int8 kernels, The CUTLASS generator modifies the output tensor alignment\n    # after ops are created. Revisit how important this modification is.\n    # for op in operations:\n    #     if op.tile_description.threadblock_shape[1] >= 128:\n    #         op.C.alignment = 16\n    #     else:\n    #         op.C.alignment = 8\n\n    return sm75_kernels + sm80_kernels\n\n\nGENERATOR_FUNC_TABLE = {\n    75: generate_sm75_tensor_op_1688,\n    80: generate_sm80_tensor_op_16816,\n}\n\n\n# (Epilogue functor name, no_beta_scaling)\nEPILOGUE_MAP = {\n    \"cutlass.dense\": (EpilogueFunctor.LinearCombination, False),\n    \"cutlass.dense_bias\": (EpilogueFunctor.LinearCombinationBias, True),\n    \"cutlass.dense_bias_relu\": (EpilogueFunctor.LinearCombinationRelu, True),\n    \"cutlass.dense_bias_gelu_fp16\": (EpilogueFunctor.LinearCombinationGelu, False),\n    \"cutlass.dense_bias_gelu_fp32\": (EpilogueFunctor.LinearCombinationGelu, False),\n    \"cutlass.batch_matmul\": (EpilogueFunctor.LinearCombination, False),\n    \"cutlass.conv2d_bias_hardswish\": (EpilogueFunctor.LinearCombinationHardSwish, False),\n    \"cutlass.conv2d_bias_silu\": (EpilogueFunctor.LinearCombinationSilu, False),\n    \"cutlass.conv2d_bias_sigmoid\": (EpilogueFunctor.LinearCombinationSigmoid, False),\n    \"cutlass.conv2d_bias_relu\": (EpilogueFunctor.LinearCombinationRelu, True),\n    \"cutlass.conv2d_bias\": (EpilogueFunctor.LinearCombinationBias, True),\n    \"cutlass.conv2d\": (EpilogueFunctor.LinearCombination, False),\n    \"cutlass.conv2d_transpose\": (EpilogueFunctor.LinearCombination, False),\n    \"cutlass.conv2d_backward_weight\": (EpilogueFunctor.LinearCombination, False),\n}\n\n\nclass ProfilerEngine:\n    \"\"\"Compile and run a given profiler executable.\"\"\"\n\n    def __init__(self, cuda_arch, cutlass_path, binary_prefix):\n        self.cuda_arch = cuda_arch\n        self.binary_prefix = binary_prefix\n        self.cutlass = cutlass_path\n        self.cflags = \"-I{cutlass}/include -I{cutlass}/tools/util/include -O3 -std=c++11\".format(\n            cutlass=cutlass_path\n        )\n        self.cflags += \" -DCUTLASS_ENABLE_TENSOR_CORE_MMA=1\"\n        self.cflags += \" -gencode=arch=compute_{arch},code=[sm_{arch},compute_{arch}]\".format(\n            arch=cuda_arch\n        )\n        self.cflags += \" -Xcompiler=-Wconversion -Xcompiler=-fno-strict-aliasing\"\n        self.cmd = \"nvcc {cflags} {src} -o {output}\"\n\n    def _compile(self, op):\n        os.makedirs(self.binary_prefix, exist_ok=True)\n        opath = os.path.join(self.binary_prefix, op[\"name\"])\n        if os.path.exists(opath):\n            return\n        fi = tempfile.NamedTemporaryFile(\"w\", delete=False, prefix=self.binary_prefix, suffix=\".cu\")\n        fi.write(op[\"src\"])\n        fi.close()\n        cmd = self.cmd.format(cflags=self.cflags, src=fi.name, output=opath)\n        logger.info(\"invoking compilation %s\", cmd)\n        os.system(cmd)\n        os.unlink(fi.name)\n\n    def compile_all(self, ops, use_multiprocessing=False):\n        \"\"\"Compile all profiler executables.\"\"\"\n        if use_multiprocessing:\n            pool = multiprocessing.Pool(multiprocessing.cpu_count())\n            pool.map(self._compile, ops)\n        else:\n            for op in ops:\n                self._compile(op)\n\n    def evaluate(self, op, args):\n        \"\"\"Run the profiler executable corresponding to op_name with args.\"\"\"\n        op_name = op[\"name\"]\n        opath = os.path.join(self.binary_prefix, op_name)\n        if not os.path.exists(opath):\n            self._compile(op)\n        if not os.path.exists(opath):\n            # Bail out if compilation fails for a whatever reason (e.g. static assert failure)\n            return float(\"inf\")\n        cmd = [opath]\n        for arg in args:\n            cmd.append(str(arg))\n        try:\n            logger.info(\"invoking evaluation %s\", cmd)\n            sp = subprocess.run(cmd, capture_output=True, check=True)\n            rt = float(sp.stdout)\n            if rt == 0.0:\n                # This seems to happen with split-k using invalid split-k-slices\n                rt = float(\"inf\")\n            logger.info(\"%s, %f\", op_name, rt)\n        except subprocess.CalledProcessError:\n            rt = float(\"inf\")\n        return rt\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/cutlass/library.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,line-too-long\n\"\"\"Various type definitions to help instantiate CUTLASS kernels.\"\"\"\nimport re\nimport enum\nfrom enum import auto as enum_auto\n\n\nclass GeneratorTarget(enum.Enum):\n    Library = enum_auto()\n\n\nclass DataType(enum.Enum):\n    f16 = enum_auto()\n    f32 = enum_auto()\n    s8 = enum_auto()\n    u8 = enum_auto()\n    s32 = enum_auto()\n\n\nShortDataTypeNames = {\n    DataType.f16: \"h\",\n    DataType.f32: \"s\",\n    DataType.s32: \"i\",\n}\n\n\nDataTypeNames = {\n    DataType.f16: \"f16\",\n    DataType.f32: \"f32\",\n    DataType.s8: \"s8\",\n    DataType.u8: \"u8\",\n    DataType.s32: \"s32\",\n}\n\nDataTypeTag = {\n    DataType.f16: \"cutlass::half_t\",\n    DataType.f32: \"float\",\n    DataType.s8: \"int8_t\",\n    DataType.s32: \"int32_t\",\n    DataType.u8: \"uint8_t\",\n}\n\nDataTypeSize = {\n    DataType.f16: 16,\n    DataType.f32: 32,\n    DataType.u8: 8,\n    DataType.s8: 8,\n    DataType.s32: 32,\n}\n\n\nclass MathOperation(enum.Enum):\n    multiply_add = enum_auto()\n    multiply_add_saturate = enum_auto()\n    multiply_add_fast_f32 = enum_auto()\n\n\nMathOperationTag = {\n    MathOperation.multiply_add: \"cutlass::arch::OpMultiplyAdd\",\n    MathOperation.multiply_add_saturate: \"cutlass::arch::OpMultiplyAddSaturate\",\n    MathOperation.multiply_add_fast_f32: \"cutlass::arch::OpMultiplyAddFastF32\",\n}\n\n\nclass LayoutType(enum.Enum):\n    ColumnMajor = enum_auto()\n    RowMajor = enum_auto()\n    TensorNHWC = enum_auto()\n\n\nLayoutTag = {\n    LayoutType.ColumnMajor: \"cutlass::layout::ColumnMajor\",\n    LayoutType.RowMajor: \"cutlass::layout::RowMajor\",\n    LayoutType.TensorNHWC: \"cutlass::layout::TensorNHWC\",\n}\n\n\nTransposedLayout = {\n    LayoutType.ColumnMajor: LayoutType.RowMajor,\n    LayoutType.RowMajor: LayoutType.ColumnMajor,\n    LayoutType.TensorNHWC: LayoutType.TensorNHWC,\n}\n\n\nShortLayoutTypeNames = {\n    LayoutType.ColumnMajor: \"n\",\n    LayoutType.RowMajor: \"t\",\n    LayoutType.TensorNHWC: \"nhwc\",\n}\n\n\nclass OpcodeClass(enum.Enum):\n    Simt = enum_auto()\n    TensorOp = enum_auto()\n    WmmaTensorOp = enum_auto()\n\n\nOpcodeClassNames = {\n    OpcodeClass.Simt: \"simt\",\n    OpcodeClass.TensorOp: \"tensorop\",\n    OpcodeClass.WmmaTensorOp: \"wmma_tensorop\",\n}\n\nOpcodeClassTag = {\n    OpcodeClass.Simt: \"cutlass::arch::OpClassSimt\",\n    OpcodeClass.TensorOp: \"cutlass::arch::OpClassTensorOp\",\n    OpcodeClass.WmmaTensorOp: \"cutlass::arch::OpClassWmmaTensorOp\",\n}\n\n\nclass OperationKind(enum.Enum):\n    Gemm = enum_auto()\n    Conv2d = enum_auto()\n\n\nOperationKindNames = {OperationKind.Gemm: \"gemm\", OperationKind.Conv2d: \"conv2d\"}\n\n\nclass Target(enum.Enum):\n    library = enum_auto()\n\n\ndef substitute_template(template, values):\n    \"\"\"Instantiate a kernel template using `values`.\"\"\"\n    text = template\n    changed = True\n    while changed:\n        changed = False\n        for key, value in values.items():\n            regex = \"\\\\$\\\\{%s\\\\}\" % key\n            newtext = re.sub(regex, value, text)\n            if newtext != text:\n                changed = True\n            text = newtext\n    return text\n\n\nclass GemmKind(enum.Enum):\n    Gemm = enum_auto()\n\n\nGemmKindNames = {\n    GemmKind.Gemm: \"gemm\",\n}\n\n\nclass EpilogueFunctor(enum.Enum):\n    LinearCombination = enum_auto()\n    LinearCombinationRelu = enum_auto()\n    LinearCombinationBias = enum_auto()\n    LinearCombinationGelu = enum_auto()\n    LinearCombinationSigmoid = enum_auto()\n    LinearCombinationSilu = enum_auto()\n    LinearCombinationHardSwish = enum_auto()\n    LinearCombinationResidualBlock = enum_auto()\n\n\nEpilogueFunctorTag = {\n    EpilogueFunctor.LinearCombination: \"cutlass::epilogue::thread::LinearCombination\",\n    EpilogueFunctor.LinearCombinationRelu: \"cutlass::epilogue::thread::LinearCombinationRelu\",\n    EpilogueFunctor.LinearCombinationBias: \"cutlass::epilogue::thread::LinearCombination\",\n    EpilogueFunctor.LinearCombinationGelu: \"cutlass::epilogue::thread::LinearCombinationGELU\",\n    EpilogueFunctor.LinearCombinationSigmoid: \"cutlass::epilogue::thread::LinearCombinationSigmoid\",\n    EpilogueFunctor.LinearCombinationSilu: \"cutlass::epilogue::thread::LinearCombinationSilu\",\n    EpilogueFunctor.LinearCombinationHardSwish: \"cutlass::epilogue::thread::LinearCombinationHardSwish\",\n    EpilogueFunctor.LinearCombinationResidualBlock: \"cutlass::epilogue::thread::LinearCombinationResidualBlock\",\n}\n\n\nclass SwizzlingFunctor(enum.Enum):\n    Identity1 = enum_auto()\n    Identity2 = enum_auto()\n    Identity4 = enum_auto()\n    Identity8 = enum_auto()\n    Batched = enum_auto()\n    StridedDgradIdentity1 = enum_auto()\n    StridedDgradIdentity4 = enum_auto()\n\n\nSwizzlingFunctorTag = {\n    SwizzlingFunctor.Identity1: \"cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<1>\",\n    SwizzlingFunctor.Identity2: \"cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<2>\",\n    SwizzlingFunctor.Identity4: \"cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<4>\",\n    SwizzlingFunctor.Identity8: \"cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<8>\",\n    SwizzlingFunctor.Batched: \"cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle\",\n    SwizzlingFunctor.StridedDgradIdentity1: \"cutlass::conv::threadblock::StridedDgradIdentityThreadblockSwizzle<1>\",\n    SwizzlingFunctor.StridedDgradIdentity4: \"cutlass::conv::threadblock::StridedDgradIdentityThreadblockSwizzle<4>\",\n}\n\n\nclass ConvKind(enum.Enum):\n    Fprop = enum_auto()\n    Dgrad = enum_auto()\n    Wgrad = enum_auto()\n\n\nConvKindTag = {\n    ConvKind.Fprop: \"cutlass::conv::Operator::kFprop\",\n    ConvKind.Dgrad: \"cutlass::conv::Operator::kDgrad\",\n    ConvKind.Wgrad: \"cutlass::conv::Operator::kWgrad\",\n}\n\n\nConvKindNames = {\n    ConvKind.Fprop: \"fprop\",\n    ConvKind.Dgrad: \"dgrad\",\n    ConvKind.Wgrad: \"wgrad\",\n}\n\n\nclass StrideSupport(enum.Enum):\n    Strided = enum_auto()\n    Unity = enum_auto()\n\n\nStrideSupportTag = {\n    StrideSupport.Strided: \"cutlass::conv::StrideSupport::kStrided\",\n    StrideSupport.Unity: \"cutlass::conv::StrideSupport::kUnity\",\n}\n\n\nStrideSupportNames = {\n    StrideSupport.Strided: \"\",\n    StrideSupport.Unity: \"unity_stride\",\n}\n\n\nclass IteratorAlgorithm(enum.Enum):\n    Analytic = enum_auto()\n    Optimized = enum_auto()\n\n\nIteratorAlgorithmTag = {\n    IteratorAlgorithm.Analytic: \"cutlass::conv::IteratorAlgorithm::kAnalytic\",\n    IteratorAlgorithm.Optimized: \"cutlass::conv::IteratorAlgorithm::kOptimized\",\n}\n\n\nIteratorAlgorithmNames = {\n    IteratorAlgorithm.Analytic: \"analytic\",\n    IteratorAlgorithm.Optimized: \"optimized\",\n}\n\n\nclass MathInstruction:\n    \"\"\"Describe characteristics of a math instruction.\"\"\"\n\n    def __init__(\n        self,\n        instruction_shape,\n        element_a,\n        element_b,\n        element_c,\n        element_accumulator,\n        opcode_class,\n        math_operation=MathOperation.multiply_add,\n    ):\n        self.instruction_shape = instruction_shape\n        self.element_a = element_a\n        self.element_b = element_b\n        self.element_c = element_c\n        self.element_accumulator = element_accumulator\n        self.opcode_class = opcode_class\n        self.math_operation = math_operation\n\n\nclass TileDescription:\n    \"\"\"Describe characteristics of a GEMM tile.\"\"\"\n\n    def __init__(\n        self, threadblock_shape, stages, warp_count, math_instruction, min_compute, max_compute\n    ):\n        self.threadblock_shape = threadblock_shape\n        self.stages = stages\n        self.warp_count = warp_count\n        self.math_instruction = math_instruction\n        self.minimum_compute_capability = min_compute\n        self.maximum_compute_capability = max_compute\n\n    def procedural_name(self):\n        return \"%dx%d_%dx%d\" % (\n            self.threadblock_shape[0],\n            self.threadblock_shape[1],\n            self.threadblock_shape[2],\n            self.stages,\n        )\n\n\nclass TensorDescription:\n    def __init__(self, element, layout, alignment=1):\n        self.element = element\n        self.layout = layout\n        self.alignment = alignment\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/debugger/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/debugger/debug_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Graph debug runtime executes TVM debug packed functions.\"\"\"\n\nimport logging\nimport os\nimport shutil\nimport struct\nimport tempfile\n\nimport tvm._ffi\nfrom tvm._ffi.base import string_types\nfrom tvm.contrib import graph_executor\nfrom tvm.runtime.module import BenchmarkResult\n\nfrom ...runtime.profiling import Report\nfrom . import debug_result\n\n_DUMP_ROOT_PREFIX = \"tvmdbg_\"\n_DUMP_PATH_PREFIX = \"_tvmdbg_\"\n\n\ndef create(graph_json_str, libmod, device, dump_root=None):\n    \"\"\"Create a runtime executor module given a graph and module.\n\n    Parameters\n    ----------\n    graph_json_str : str\n        The graph to be deployed in json format output by graph compiler.\n        The graph can contain operator(tvm_op) that points to the name\n        of PackedFunc in the libmod.\n\n    libmod : tvm.Module\n        The module of the corresponding function.\n\n    device : Device\n        The device to deploy the module, can be local or remote.\n\n    dump_root : str\n        To select which folder the outputs should be kept.\n        None will make a temp folder in /tmp/tvmdbg<rand_string> and does the dumping\n    Returns\n    -------\n    graph_module : GraphModuleDebug\n        Debug Runtime graph module that can be used to execute the graph.\n    \"\"\"\n    assert isinstance(graph_json_str, string_types)\n\n    try:\n        dev, num_rpc_dev, device_type_id = graph_executor.get_device(libmod, device)\n        if num_rpc_dev == len(dev):\n            fcreate = dev[0]._rpc_sess.get_function(\"tvm.graph_executor_debug.create\")\n        else:\n            fcreate = tvm._ffi.get_global_func(\"tvm.graph_executor_debug.create\")\n    except ValueError:\n        raise ValueError(\n            \"Please set '(USE_PROFILER ON)' in \" \"config.cmake and rebuild TVM to enable debug mode\"\n        )\n    func_obj = fcreate(graph_json_str, libmod, *device_type_id)\n    gmod = GraphModuleDebug(func_obj, dev, graph_json_str, dump_root)\n\n    # Automatically set params if they can be extracted from the libmod\n    try:\n        params = libmod[\"get_graph_params\"]()\n    except (AttributeError, tvm.error.RPCError):\n        # Params can not be extracted from the libmod and must be set somewhere else manually\n        # Do not set params during RPC communication\n        pass\n    else:\n        gmod.set_input(**params)\n\n    return gmod\n\n\nclass GraphModuleDebug(graph_executor.GraphModule):\n    \"\"\"Graph debug runtime module.\n\n    This is a debug wrapper over the TVM runtime.\n    Runtime interfaces are wrapped with debug functionalities.\n    Manage the debug framework to format the debug data and\n    trigger the user interfaces.\n\n    Parameters\n    ----------\n    module : Module\n        The internal tvm module that holds the actual graph functions.\n\n    device : Device\n        The device that this module is under.\n\n    graph_json_str : str or graph class\n        Content of graph json file in string format\n\n    dump_root : str\n        To select which folder the outputs should be kept.\n        None will make a temp folder in /tmp/tvmdbg<rand_string> and does the dumping\n    \"\"\"\n\n    def __init__(self, module, device, graph_json_str, dump_root):\n        self._dump_root = dump_root\n        self._dump_path = None\n        self._run_individual = module[\"run_individual\"]\n        self._run_individual_node = module[\"run_individual_node\"]\n        self._debug_get_output = module[\"debug_get_output\"]\n        self._execute_node = module[\"execute_node\"]\n        self._get_node_output = module[\"get_node_output\"]\n        self._profile = module[\"profile\"]\n        self._profile_rpc = module[\"profile_rpc\"]\n        graph_executor.GraphModule.__init__(self, module)\n        self._create_debug_env(graph_json_str, device)\n\n    def _format_device(self, device):\n        return str(device[0]).upper().replace(\"(\", \":\").replace(\")\", \"\")\n\n    def _ensure_dir(self, directory):\n        \"\"\"Create a directory if not exists\n\n        Parameters\n        ----------\n\n        directory : str\n            File path to create\n        \"\"\"\n        if not os.path.exists(directory):\n            os.makedirs(directory, 0o700)\n\n    def _get_dump_path(self, device):\n        \"\"\"Make the graph and tensor dump folder and return the path.\n\n        Parameters\n        ----------\n        device : Device\n            The device that this module is under.\n\n        Returns\n        -------\n        path : str\n            Directory path where the graph and node outputs will be stored.\n        \"\"\"\n        # save to file\n        folder_name = _DUMP_PATH_PREFIX + \"device_\"\n        folder_name = folder_name + device.replace(\":\", \"_\")\n        path = os.path.join(self._dump_root, folder_name)\n        self._ensure_dir(path)\n        return path\n\n    def _remove_dump_root(self):\n        if os.path.isdir(self._dump_root):\n            shutil.rmtree(self._dump_root)\n\n    def _create_debug_env(self, graph_json, device):\n        \"\"\"Create UI wrapper framework to handle multiple UI frontends for tvmdbg\n\n        Parameters\n        ----------\n        graph_json : json format\n            json formatted NNVM graph contain list of each node's name, shape and type.\n\n        nodes_list : list\n            List of all the nodes presented in the graph\n\n        device : Device\n            The device that this module is under.\n        \"\"\"\n        # make the dump folder if not given\n        if not self._dump_root:\n            self._dump_root = tempfile.mkdtemp(prefix=_DUMP_ROOT_PREFIX)\n\n        # format the device\n        device = self._format_device(device)\n\n        # updates the dumping directories\n        self._dump_path = self._get_dump_path(device)\n\n        # init the debug dumping environment\n        self.debug_datum = debug_result.DebugResult(graph_json, self._dump_path)\n\n    def _execute_next_node(self, node_index, output_index):\n        \"\"\"Execute node assuming all previous nodes has been executed.\n        Return the output of this node.\n\n        Parameters\n        ----------\n        node_index : int\n            The node index\n        output_index: int\n            The node output index\n        Return\n        ------\n        output_tensors : Array<NDarray>\n            Array of output tensors\n        \"\"\"\n        output_tensors = self._execute_next_node_get_output(node_index, output_index)\n        return output_tensors\n\n    def _run_per_layer(self):\n        \"\"\"Execute up to each node and each debug output will be\n        copied to the buffer.\n\n        \"\"\"\n        output_tensors = []\n        for i, node in enumerate(self.debug_datum.get_graph_nodes()):\n            self._execute_node(i)\n            num_outputs = self.debug_datum.get_graph_node_output_num(node)\n            for j in range(num_outputs):\n                logging.info(\n                    \"running node=%d, output_ind=%d, with node_name: %s\", i, j, node[\"name\"]\n                )\n                output_tensors.append(self._get_node_output(i, j))\n        self.debug_datum.update_output_tensors(output_tensors)\n\n    def _run_debug(\n        self,\n        number,\n        repeat,\n        min_repeat_ms,\n        limit_zero_time_iterations,\n        cooldown_interval_ms,\n        repeats_to_cooldown,\n    ):\n        \"\"\"Execute the node specified with index will be executed.\n        Each debug output will be copied to the buffer\n        Time consumed for each execution will be set as debug output.\n        \"\"\"\n        # Get timing.\n        self.debug_datum._time_list = self.run_individual(\n            number=number,\n            repeat=repeat,\n            min_repeat_ms=min_repeat_ms,\n            limit_zero_time_iterations=limit_zero_time_iterations,\n            cooldown_interval_ms=cooldown_interval_ms,\n            repeats_to_cooldown=repeats_to_cooldown,\n        )\n\n        # Get outputs.\n        self._run_per_layer()\n\n    def debug_get_output(self, node, out=None):\n        \"\"\"Run graph up to node and get the output to out\n\n        Parameters\n        ----------\n        node : int / str\n            The node index or name\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        if isinstance(node, str):\n            node_index = None\n            for i, graph_node in enumerate(self.debug_datum.get_graph_nodes()):\n                if graph_node[\"name\"] == node:\n                    node_index = i\n                    break\n            else:\n                raise AttributeError(f\"Could not find a node named {node} in this graph.\")\n        elif isinstance(node, int):\n            node_index = node\n        else:\n            raise RuntimeError(f\"Require node index or name only.\")\n\n        self._debug_get_output(node_index, out)\n\n    # pylint: disable=arguments-differ\n    def run(\n        self,\n        number=10,\n        repeat=1,\n        min_repeat_ms=1,\n        limit_zero_time_iterations=100,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n        sort_by_time=True,\n        **input_dict,\n    ):\n        \"\"\"Run forward execution of the graph with debug\n\n        Parameters\n        ----------\n        number: int, optional\n            The number of times to run this function for taking average.\n            We call these runs as one `repeat` of measurement.\n\n        repeat: int, optional\n            The number of times to repeat the measurement.\n            In total, the function will be invoked (1 + number x repeat) times,\n            where the first one is warm up and will be discarded.\n            The returned result contains `repeat` costs,\n            each of which is an average of `number` costs.\n\n        min_repeat_ms: int, optional\n            The minimum duration of one `repeat` in milliseconds.\n            By default, one `repeat` contains `number` runs. If this parameter is set,\n            the parameters `number` will be dynamically adjusted to meet the\n            minimum duration requirement of one `repeat`.\n            i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n            will be automatically increased.\n\n        limit_zero_time_iterations: int, optional\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        cooldown_interval_ms: int, optional\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: int, optional\n            The number of repeats before the cooldown is activated.\n\n        sort_by_time: bool, optional\n            Whether to sort the debug output by time.\n\n        input_dict : dict of str to NDArray\n            List of input values to be feed to\n        \"\"\"\n        if input_dict:\n            self.set_input(**input_dict)\n\n        # Step 1. Execute the graph\n        self._run_debug(\n            number=number,\n            repeat=repeat,\n            min_repeat_ms=min_repeat_ms,\n            limit_zero_time_iterations=limit_zero_time_iterations,\n            cooldown_interval_ms=cooldown_interval_ms,\n            repeats_to_cooldown=repeats_to_cooldown,\n        )\n        # Step 2. Dump the output tensors to the dump folder\n        self.debug_datum.dump_output_tensor()\n        # Step 3. Dump the Chrome trace to the dump folder\n        self.debug_datum.dump_chrome_trace()\n        # Step 4. Display the collected information\n        self.debug_datum.display_debug_result(sort_by_time)\n\n    def run_individual(\n        self,\n        number,\n        repeat=1,\n        min_repeat_ms=0,\n        limit_zero_time_iterations=100,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n    ):\n        \"\"\"Run each operation in the graph and get the time per op for all ops.\n\n        number: int\n            The number of times to run this function for taking average.\n            We call these runs as one `repeat` of measurement.\n\n        repeat: int, optional\n            The number of times to repeat the measurement.\n            In total, the function will be invoked (1 + number x repeat) times,\n            where the first one is warm up and will be discarded.\n            The returned result contains `repeat` costs,\n            each of which is an average of `number` costs.\n\n        min_repeat_ms: int, optional\n            The minimum duration of one `repeat` in milliseconds.\n            By default, one `repeat` contains `number` runs. If this parameter is set,\n            the parameters `number` will be dynamically adjusted to meet the\n            minimum duration requirement of one `repeat`.\n            i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n            will be automatically increased.\n\n        limit_zero_time_iterations: int, optional\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        cooldown_interval_ms: int, optional\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: int, optional\n            The number of repeats before the cooldown is activated.\n\n        Returns\n        -------\n        A 2-dimensional array where the dimensions are: the index of the operation and\n        the repeat of the measurement.\n        \"\"\"\n        res = self._run_individual(\n            number,\n            repeat,\n            min_repeat_ms,\n            limit_zero_time_iterations,\n            cooldown_interval_ms,\n            repeats_to_cooldown,\n        )\n        results = []\n        offset = 0\n        format_size = \"@q\"\n        (nodes_count,) = struct.unpack_from(format_size, res, offset)\n        offset += struct.calcsize(format_size)\n        format_data = \"@\" + repeat * \"d\"\n        for _ in range(0, nodes_count):\n            ret = struct.unpack_from(format_data, res, offset)\n            offset += struct.calcsize(format_data)\n            results.append([*ret])\n        return results\n\n    def run_individual_node(\n        self,\n        index,\n        number=10,\n        repeat=1,\n        min_repeat_ms=0,\n        limit_zero_time_iterations=100,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n    ):\n        \"\"\"Benchmark a single node in the serialized graph.\n\n        This does not do any data transfers and uses arrays already on the device.\n\n        Parameters\n        ----------\n        index : int\n            The index of the node, see `self.debug_datum.get_graph_nodes`\n\n        number: int\n            The number of times to run this function for taking average.\n            We call these runs as one `repeat` of measurement.\n\n        repeat: int, optional\n            The number of times to repeat the measurement.\n            In total, the function will be invoked (1 + number x repeat) times,\n            where the first one is warm up and will be discarded.\n            The returned result contains `repeat` costs,\n            each of which is an average of `number` costs.\n\n        min_repeat_ms : int, optional\n            The minimum duration of one `repeat` in milliseconds.\n            By default, one `repeat` contains `number` runs. If this parameter is set,\n            the parameters `number` will be dynamically adjusted to meet the\n            minimum duration requirement of one `repeat`.\n            i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n            will be automatically increased.\n\n        limit_zero_time_iterations: int, optional\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        cooldown_interval_ms: int, optional\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: int, optional\n            The number of repeats before the cooldown is activated.\n\n        Returns\n        -------\n        A module BenchmarkResult\n        \"\"\"\n        # Results are returned as serialized strings which we deserialize\n        res = self._run_individual_node(\n            index,\n            number,\n            repeat,\n            min_repeat_ms,\n            limit_zero_time_iterations,\n            cooldown_interval_ms,\n            repeats_to_cooldown,\n        )\n        fmt = \"@\" + (\"d\" * repeat)\n        results = struct.unpack(fmt, res)\n        return BenchmarkResult(list(results))\n\n    def profile(self, collectors=None, **input_dict):\n        \"\"\"Run forward execution of the graph and collect overall and per-op\n        performance metrics.\n\n        Parameters\n        ----------\n        collectors : Optional[Sequence[MetricCollector]]\n            Extra metrics to collect. If profiling over RPC, collectors must be `None`.\n\n        input_dict : dict of str to NDArray\n            List of input values to be feed to\n\n        Return\n        ------\n        timing_results : str\n            Per-operator and whole graph timing results in a table format.\n        \"\"\"\n        if input_dict:\n            self.set_input(**input_dict)\n\n        if self.module.type_key == \"rpc\":\n            # We cannot serialize MetricCollectors over RPC\n            assert collectors is None, \"Profiling with collectors is not supported over RPC\"\n            return Report.from_json(self._profile_rpc())\n        return self._profile(collectors)\n\n    def exit(self):\n        \"\"\"Exits the dump folder and all its contents\"\"\"\n        self._remove_dump_root()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/debugger/debug_result.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Graph debug results dumping class.\"\"\"\nimport collections\nimport json\nimport os\n\nimport numpy as np\nimport tvm\n\nGRAPH_DUMP_FILE_NAME = \"_tvmdbg_graph_dump.json\"\nCHROME_TRACE_FILE_NAME = \"_tvmdbg_execution_trace.json\"\n\nChromeTraceEvent = collections.namedtuple(\"ChromeTraceEvent\", [\"ts\", \"tid\", \"pid\", \"name\", \"ph\"])\n\n\nclass DebugResult(object):\n    \"\"\"Graph debug data module.\n\n    Data dump module manage all the debug data formatting.\n    Output data and input graphs are formatted and dumped to file.\n    Frontend read these data and graph for visualization.\n\n    Parameters\n    ----------\n    graph_json : str\n        The graph to be deployed in json format output by graph compiler. Each operator (tvm_op)\n        in the graph will have a one to one mapping with the symbol in libmod which is used\n        to construct a \"PackedFunc\" .\n\n    dump_path : str\n        Output data path is read/provided from frontend\n    \"\"\"\n\n    def __init__(self, graph_json, dump_path):\n        self._dump_path = dump_path\n        self._output_tensor_list = []\n        self._time_list = []\n        json_obj = self._parse_graph(graph_json)\n        # dump the json information\n        self._dump_graph_json(json_obj)\n\n    def _parse_graph(self, graph_json):\n        \"\"\"Parse and extract the JSON graph and update the nodes, shapes and dltype.\n\n        Parameters\n        ----------\n        graph_json : str or graph class\n           The graph to be deployed in json format output by JSON graph.\n        \"\"\"\n        json_obj = json.loads(graph_json)\n        self._nodes_list = json_obj[\"nodes\"]\n        self._shapes_list = json_obj[\"attrs\"][\"shape\"]\n        self._dtype_list = json_obj[\"attrs\"][\"dltype\"]\n        self._update_graph_json()\n        return json_obj\n\n    def _update_graph_json(self):\n        \"\"\"update the nodes_list with name, shape and data type,\n        for temporarily storing the output.\n        \"\"\"\n        nodes_len = len(self._nodes_list)\n        for i in range(nodes_len):\n            node = self._nodes_list[i]\n            input_list = []\n            for input_node in node[\"inputs\"]:\n                input_list.append(self._nodes_list[input_node[0]][\"name\"])\n            node[\"inputs\"] = input_list\n            dtype = str(\"type: \" + self._dtype_list[1][i])\n            if \"attrs\" not in node:\n                node[\"attrs\"] = {}\n                node[\"op\"] = \"param\"\n            else:\n                node[\"op\"] = node[\"attrs\"][\"func_name\"]\n            node[\"attrs\"].update({\"T\": dtype})\n            node[\"shape\"] = self._shapes_list[1][i]\n\n    def _cleanup_tensors(self):\n        \"\"\"Remove the tensor dump file (graph wont be removed)\"\"\"\n        for filename in os.listdir(self._dump_path):\n            if os.path.isfile(filename) and not filename.endswith(\".json\"):\n                os.remove(filename)\n\n    def get_graph_nodes(self):\n        \"\"\"Return the nodes list\"\"\"\n        return self._nodes_list\n\n    def get_graph_node_shapes(self):\n        \"\"\"Return the nodes shapes list\"\"\"\n        return self._shapes_list\n\n    def get_graph_node_output_num(self, node):\n        \"\"\"Return the number of outputs of a node\"\"\"\n        return 1 if node[\"op\"] == \"param\" else int(node[\"attrs\"][\"num_outputs\"])\n\n    def get_graph_node_dtypes(self):\n        \"\"\"Return the nodes dtype list\"\"\"\n        return self._dtype_list\n\n    def get_output_tensors(self):\n        \"\"\"Get the output tensors of each operation in numpy format\"\"\"\n        eid = 0\n        output_tensors = {}\n        for i, node in enumerate(self._nodes_list):\n            num_outputs = self.get_graph_node_output_num(node)\n            for j in range(num_outputs):\n\n                # the node name is not unique, so we need a consistent\n                # indexing based on the list ordering in the nodes\n                key = f\"{node['name']}____topo-index:{i}____output-num:{j}\"\n                output_tensors[key] = self._output_tensor_list[eid]\n                eid += 1\n        return output_tensors\n\n    def update_output_tensors(self, tensors):\n        \"\"\"Update output tensors list\n\n        Parameters\n        ----------\n        tensors : list[NDArray]\n        \"\"\"\n        if not isinstance(tensors, list):\n            AttributeError(\"tensors with incorrect type.\")\n\n        for output_array in tensors:\n            self._output_tensor_list.append(output_array)\n\n    def dump_output_tensor(self):\n        \"\"\"Dump the outputs to a temporary folder, the tensors are in numpy format\"\"\"\n        # cleanup existing tensors before dumping\n        self._cleanup_tensors()\n        output_tensors = self.get_output_tensors()\n\n        with open(os.path.join(self._dump_path, \"output_tensors.params\"), \"wb\") as param_f:\n            param_f.write(save_tensors(output_tensors))\n\n    def dump_chrome_trace(self):\n        \"\"\"Dump the trace to the Chrome trace.json format.\"\"\"\n\n        def s_to_us(t):\n            return t * 10**6\n\n        starting_times = np.zeros(len(self._time_list) + 1)\n        starting_times[1:] = np.cumsum([np.mean(times) for times in self._time_list])\n\n        def node_to_events(node, times, starting_time):\n            return [\n                ChromeTraceEvent(\n                    ts=s_to_us(starting_time),\n                    tid=1,\n                    pid=1,\n                    ph=\"B\",\n                    name=node[\"name\"],\n                ),\n                ChromeTraceEvent(\n                    # Use start + duration instead of end to ensure precise timings.\n                    ts=s_to_us(np.mean(times) + starting_time),\n                    tid=1,\n                    pid=1,\n                    ph=\"E\",\n                    name=node[\"name\"],\n                ),\n            ]\n\n        events = [\n            e\n            for (node, times, starting_time) in zip(\n                self._nodes_list, self._time_list, starting_times\n            )\n            for e in node_to_events(node, times, starting_time)\n        ]\n        result = dict(displayTimeUnit=\"ns\", traceEvents=[e._asdict() for e in events])\n\n        with open(os.path.join(self._dump_path, CHROME_TRACE_FILE_NAME), \"w\") as trace_f:\n            json.dump(result, trace_f)\n\n    def _dump_graph_json(self, graph):\n        \"\"\"Dump json formatted graph.\n\n        Parameters\n        ----------\n        graph : json format\n            json formatted JSON graph contain list of each node's\n            name, shape and type.\n        \"\"\"\n        graph_dump_file_name = GRAPH_DUMP_FILE_NAME\n        with open(os.path.join(self._dump_path, graph_dump_file_name), \"w\") as outfile:\n            json.dump(graph, outfile, indent=4, sort_keys=False)\n\n    def get_debug_result(self, sort_by_time=True):\n        \"\"\"Return the debugger result\"\"\"\n        header = [\n            \"Node Name\",\n            \"Ops\",\n            \"Time(us)\",\n            \"Time(%)\",\n            \"Shape\",\n            \"Inputs\",\n            \"Outputs\",\n            \"Measurements(us)\",\n        ]\n        lines = [\n            \"---------\",\n            \"---\",\n            \"--------\",\n            \"-------\",\n            \"-----\",\n            \"------\",\n            \"-------\",\n            \"----------------\",\n        ]\n        eid = 0\n        data = []\n        total_time = sum([np.mean(time) for time in self._time_list])\n        for node, time in zip(self._nodes_list, self._time_list):\n            time_mean = np.mean(time)\n            num_outputs = self.get_graph_node_output_num(node)\n            for j in range(num_outputs):\n                op = node[\"op\"]\n                if node[\"op\"] == \"param\":\n                    eid += 1\n                    continue\n                name = node[\"name\"]\n                shape = str(self._output_tensor_list[eid].shape)\n                time_us = round(time_mean * 1e6, 3)\n                time_percent = round(((time_mean / total_time) * 100), 3)\n                inputs = str(node[\"attrs\"][\"num_inputs\"])\n                outputs = str(node[\"attrs\"][\"num_outputs\"])\n                measurements = str([round(repeat_data * 1e6, 3) for repeat_data in time])\n                node_data = [name, op, time_us, time_percent, shape, inputs, outputs, measurements]\n                data.append(node_data)\n                eid += 1\n\n        if sort_by_time:\n            # Sort on the basis of execution time. Prints the most expensive ops in the start.\n            data = sorted(data, key=lambda x: x[2], reverse=True)\n            # Insert a row for total time at the end.\n            rounded_total_time_us = round(total_time * 1e6, 3)\n            data.append([\"Total_time\", \"-\", rounded_total_time_us, \"-\", \"-\", \"-\", \"-\", \"-\", \"-\"])\n\n        fmt = \"\"\n        for i, _ in enumerate(header):\n            max_len = len(header[i])\n            for j, _ in enumerate(data):\n                item_len = len(str(data[j][i]))\n                if item_len > max_len:\n                    max_len = item_len\n            fmt = fmt + \"{:<\" + str(max_len + 2) + \"}\"\n        log = [fmt.format(*header)]\n        log.append(fmt.format(*lines))\n        for row in data:\n            log.append(fmt.format(*row))\n        return \"\\n\".join(log)\n\n    def display_debug_result(self, sort_by_time=True):\n        \"\"\"Displays the debugger result\"\"\"\n        print(self.get_debug_result(sort_by_time))\n\n\ndef save_tensors(params):\n    \"\"\"Save parameter dictionary to binary bytes.\n\n    The result binary bytes can be loaded by the\n    GraphModule with API \"load_params\".\n\n    Parameters\n    ----------\n    params : dict of str to NDArray\n        The parameter dictionary.\n\n    Returns\n    -------\n    param_bytes: bytearray\n        Serialized parameters.\n    \"\"\"\n    _save_tensors = tvm.get_global_func(\"tvm.relay._save_param_dict\")\n\n    return _save_tensors(params)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/debugger/debug_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Deprecated Python API for DebugExecutor.\"\"\"\n\nimport warnings\n\nfrom . import debug_executor\n\n\ndef create(*args, **kwargs):\n    warnings.warn(\n        \"This function has been moved to tvm.contrib.graph_executor and will be removed \"\n        \"in the next TVM release\"\n    )\n    return debug_executor.create(*args, **kwargs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/dlpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Wrapping functions to bridge frameworks with DLPack support to TVM\"\"\"\nfrom tvm.runtime import ndarray\n\n\ndef convert_func(tvm_func, tensor_type, to_dlpack_func):\n    \"\"\"Convert a tvm function into one that accepts a tensor from another\n       framework, provided the other framework supports DLPACK\n\n    Parameters\n    ----------\n    tvm_func: Function\n        Built tvm function operating on arrays\n\n    tensor_type: Type\n        Type of the tensors of the target framework\n\n    to_dlpack_func: Function\n        Function to convert the source tensors to DLPACK\n    \"\"\"\n    assert callable(tvm_func)\n\n    def _wrapper(*args):\n        args = tuple(\n            ndarray.from_dlpack(to_dlpack_func(arg)) if isinstance(arg, tensor_type) else arg\n            for arg in args\n        )\n        return tvm_func(*args)\n\n    return _wrapper\n\n\ndef to_pytorch_func(tvm_func):\n    \"\"\"Convert a tvm function into one that accepts PyTorch tensors\n\n    Parameters\n    ----------\n    tvm_func: Function\n        Built tvm function operating on arrays\n\n    Returns\n    -------\n    wrapped_func: Function\n        Wrapped tvm function that operates on PyTorch tensors\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    import torch\n    import torch.utils.dlpack\n\n    return convert_func(tvm_func, torch.Tensor, torch.utils.dlpack.to_dlpack)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/dnnl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to BLAS libraries.\"\"\"\nimport tvm\nfrom tvm import te\nfrom ..topi.nn.utils import get_pad_tuple\n\n\ndef matmul(lhs, rhs, transa=False, transb=False, **kwargs):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with CrhsLAS\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.dnnl.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n\n\ndef dnnl_conv2d(\n    src,\n    weights,\n    stride,\n    padding,\n    dilation,\n    groups,\n    channel_last=False,\n    out_dtype=\"float32\",\n    **kwargs,\n):\n    \"\"\"Convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    src : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    weights : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    groups: str\n        input data layout: NCHW or NHWC\n\n    channel_last: bool\n        chose if input/output data format is in channel_last format(NHWC) or\n        in plain format(NCHW)\n\n    out_dtype: str\n        output datatype: now only support float32\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    pre_cast = src.dtype == \"float32\"\n    post_cast = out_dtype == \"float32\"\n\n    if channel_last:\n        batch, in_height, in_width, _ = src.shape\n        kernel_h, kernel_w, _, num_filter = weights.shape\n    else:\n        batch, _, in_height, in_width = src.shape\n        num_filter, _, kernel_h, kernel_w = weights.shape\n\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = num_filter\n    out_height = (in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1\n    out_width = (in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1\n\n    if channel_last:\n        out_shape = (batch, out_height, out_width, out_channel)\n    else:\n        out_shape = (batch, out_channel, out_height, out_width)\n\n    return te.extern(\n        out_shape,\n        [src, weights],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.dnnl.conv2d\",\n            ins[0],\n            ins[1],\n            outs[0],\n            pad_top,\n            pad_down,\n            pad_left,\n            pad_right,\n            stride[0],\n            stride[1],\n            groups,\n            channel_last,\n            pre_cast,\n            post_cast,\n        ),\n        name=\"C\",\n        dtype=out_dtype,\n        **kwargs,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/download.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Helper utility for downloading\"\"\"\n\nimport logging\nimport os\nfrom pathlib import Path\nimport shutil\nimport tempfile\nimport time\n\nLOG = logging.getLogger(\"download\")\n\n\ndef download(url, path, overwrite=False, size_compare=False, retries=3):\n    \"\"\"Downloads the file from the internet.\n    Set the input options correctly to overwrite or do the size comparison\n\n    Parameters\n    ----------\n    url : str\n        Download url.\n\n    path : str\n        Local file path to save downloaded file.\n\n    overwrite : bool, optional\n        Whether to overwrite existing file, defaults to False.\n\n    size_compare : bool, optional\n        Whether to do size compare to check downloaded file, defaults\n        to False\n\n    retries: int, optional\n        Number of time to retry download, defaults to 3.\n\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    import urllib.request as urllib2\n\n    path = Path(path).resolve()\n    if path.exists() and path.is_file() and not overwrite:\n        if size_compare:\n            import requests\n\n            file_size = path.stat().st_size\n            res_head = requests.head(url)\n            res_get = requests.get(url, stream=True)\n            if \"Content-Length\" not in res_head.headers:\n                res_get = urllib2.urlopen(url)\n            url_file_size = int(res_get.headers[\"Content-Length\"])\n            if url_file_size != file_size:\n                LOG.warning(\"Existing file %s has incorrect size, downloading fresh copy\", path)\n                download(url, path, overwrite=True, size_compare=False, retries=retries)\n                return\n\n        LOG.info(\"File %s exists, skipping.\", path)\n        return\n\n    LOG.info(\"Downloading from url %s to %s\", url, path)\n\n    # Stateful start time\n    start_time = time.time()\n    dirpath = path.parent\n    dirpath.mkdir(parents=True, exist_ok=True)\n\n    def _download_progress(count, block_size, total_size):\n        # pylint: disable=unused-argument\n        \"\"\"Show the download progress.\"\"\"\n        if count == 0:\n            return\n        duration = time.time() - start_time\n        progress_bytes = int(count * block_size)\n        progress_megabytes = progress_bytes / (1024.0 * 1024)\n        speed_kbps = int(progress_bytes / (1024 * duration))\n        percent = min(int(count * block_size * 100 / total_size), 100)\n\n        # Temporarily suppress newlines on the output stream.\n        prev_terminator = logging.StreamHandler.terminator\n        logging.StreamHandler.terminator = \"\"\n        LOG.debug(\n            \"\\r...%d%%, %.2f MB, %d KB/s, %d seconds passed\",\n            percent,\n            progress_megabytes,\n            speed_kbps,\n            duration,\n        )\n        logging.StreamHandler.terminator = prev_terminator\n\n    with tempfile.TemporaryDirectory() as tempdir:\n        tempdir = Path(tempdir)\n        download_loc = tempdir.joinpath(path.name)\n\n        for i_retry in range(retries):\n            # pylint: disable=broad-except\n            try:\n\n                urllib2.urlretrieve(url, download_loc, reporthook=_download_progress)\n                LOG.debug(\"\")\n                try:\n                    download_loc.rename(path)\n                except OSError:\n                    # Prefer a move, but if the tempdir and final\n                    # location are in different drives, fall back to a\n                    # copy.\n                    shutil.copy2(download_loc, path)\n                return\n\n            except Exception as err:\n                if i_retry == retries - 1:\n                    raise err\n\n                LOG.warning(\n                    \"%s\\nDownload attempt %d/%d failed, retrying.\", repr(err), i_retry, retries\n                )\n\n\nif \"TEST_DATA_ROOT_PATH\" in os.environ:\n    TEST_DATA_ROOT_PATH = Path(os.environ.get(\"TEST_DATA_ROOT_PATH\"))\nelse:\n    TEST_DATA_ROOT_PATH = Path(Path(\"~\").expanduser(), \".tvm_test_data\")\nTEST_DATA_ROOT_PATH.mkdir(parents=True, exist_ok=True)\n\n\ndef download_testdata(url, relpath, module=None, overwrite=False):\n    \"\"\"Downloads the test data from the internet.\n\n    Parameters\n    ----------\n    url : str\n        Download url.\n\n    relpath : str\n        Relative file path.\n\n    module : Union[str, list, tuple], optional\n        Subdirectory paths under test data folder.\n\n    overwrite : bool, defaults to False\n        If True, will download a fresh copy of the file regardless of\n        the cache.  If False, will only download the file if a cached\n        version is missing.\n\n    Returns\n    -------\n    abspath : str\n        Absolute file path of downloaded file\n\n    \"\"\"\n    global TEST_DATA_ROOT_PATH\n    if module is None:\n        module_path = \"\"\n    elif isinstance(module, str):\n        module_path = module\n    elif isinstance(module, (list, tuple)):\n        module_path = Path(*module)\n    else:\n        raise ValueError(\"Unsupported module: \" + module)\n    abspath = Path(TEST_DATA_ROOT_PATH, module_path, relpath)\n    download(url, abspath, overwrite=overwrite, size_compare=False)\n    return str(abspath)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/emcc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Util to invoke emscripten compilers in the system.\"\"\"\n# pylint: disable=invalid-name\nimport subprocess\nfrom tvm._ffi.base import py_str\nfrom tvm._ffi.libinfo import find_lib_path\n\n\ndef create_tvmjs_wasm(output, objects, options=None, cc=\"emcc\"):\n    \"\"\"Create wasm that is supposed to run with the tvmjs.\n\n    Parameters\n    ----------\n    output : str\n        The target shared library.\n\n    objects : list\n        List of object files.\n\n    options : str\n        The additional options.\n\n    cc : str, optional\n        The compile string.\n    \"\"\"\n    cmd = [cc]\n    cmd += [\"-O3\"]\n\n    cmd += [\"-std=c++17\"]\n    cmd += [\"--no-entry\"]\n    cmd += [\"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\"]\n    cmd += [\"-s\", \"STANDALONE_WASM=1\"]\n    cmd += [\"-s\", \"ALLOW_MEMORY_GROWTH=1\"]\n\n    objects = [objects] if isinstance(objects, str) else objects\n\n    with_runtime = False\n    for obj in objects:\n        if obj.find(\"wasm_runtime.bc\") != -1:\n            with_runtime = True\n\n    if not with_runtime:\n        objects += [find_lib_path(\"wasm_runtime.bc\")[0]]\n\n    objects += [find_lib_path(\"tvmjs_support.bc\")[0]]\n    objects += [find_lib_path(\"webgpu_runtime.bc\")[0]]\n\n    cmd += [\"-o\", output]\n    cmd += objects\n\n    if options:\n        cmd += options\n\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n\ncreate_tvmjs_wasm.object_format = \"bc\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace for Arm(R) Ethos(TM)-U NPU contrib functionality\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The NPU cascader.\n\nThis component performs inter-operator scheduling to optimize\nfor both performance and memory usage on Arm(R) Ethos(TM)-U NPUs.\n\"\"\"\nfrom .stripe_config import StripeConfig\nfrom .block_config import BlockConfig\nfrom .propagator import Propagator\nfrom .graph import (\n    PerformanceInfo,\n    Tensor,\n    Part,\n    TESubgraph,\n    CascaderGraph,\n    BufferMode,\n    register_matcher,\n    create_cascader_graph,\n)\nfrom .parts import InlinePart, EthosuPart\nfrom .device_config import EthosuDeviceConfig\nfrom .tensor_config import TensorConfigState, MemoryRegion, TensorConfig\nfrom .plan import Plan\nfrom .scheduler import apply_proposal, cascade, extract_memory_info\nfrom .logging import Logging\nfrom .cascader_options import CascaderOptions\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for the NPU cascader.\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"contrib.ethosu.cascader\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/block_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Block config to hold an output block shape and a corresponding input block shape\"\"\"\nfrom typing import List\nimport tvm._ffi\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.BlockConfig\")\nclass BlockConfig(Object):\n    \"\"\"BlockConfig class\"\"\"\n\n    def __init__(\n        self,\n        input_shape: List[int],\n        output_shape: List[int],\n        compute_cycles: int,\n        output_cycles: int,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BlockConfig, input_shape, output_shape, compute_cycles, output_cycles\n        )\n\n    @property\n    def input_shape(self) -> List[int]:\n        return list(self._input_shape)\n\n    @property\n    def output_shape(self) -> List[int]:\n        return list(self._output_shape)\n\n    @property\n    def compute_cycles(self) -> int:\n        return int(self._compute_cycles)\n\n    @property\n    def output_cycles(self) -> int:\n        return int(self._output_cycles)\n\n    def __ge__(self, other: \"BlockConfig\"):\n        if len(self.output_shape) != len(other.output_shape):\n            return False\n\n        return all(a >= b for a, b in zip(self.output_shape, other.output_shape))\n\n    def __lt__(self, other: \"BlockConfig\"):\n        if len(self.output_shape) != len(other.output_shape):\n            return False\n\n        return other >= self\n\n    def __repr__(self) -> str:\n        return f\"BlockConfig(output_shape={self.output_shape})\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/cascader_options.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Object to hold options for the NPU cascader\"\"\"\nimport tvm._ffi\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\nfrom .tensor_config import MemoryRegion\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.CascaderOptions\")\nclass CascaderOptions(Object):\n    \"\"\"\n    A class to hold configuration options for the cascader.\n\n    Attributes\n    ----------\n    cascade_region : MemoryRegion\n        The MemoryRegion to place cascading buffers into.\n    max_proposals : int\n        The maximum number of Proposals to generate.\n    stripe_factors : int\n        How many striping factors to try per axis.\n    max_plan_size : int\n        The maximum number of Parts in a Plan.\n    max_open_plans : int\n        The maximum number of open Plans to keep after culling.\n    max_closed_plans : int\n        The maxmum number of closed Plans to keep after culling.\n    always_copy_size : int\n        The maximum size of a Tensor that will always be copied into the cascade region.\n    disable_pareto_plans : bool\n        Disable pareto culling for Plans.\n    disable_pareto_proposals : bool\n        Disable pareto culling for Proposals.\n    enable_multi_dimensional_striping : bool\n        Enable striping in multiple dimensions simultaneously.\n    disable_block_culling : bool\n        Disable culling of block configs.\n    enable_striping : bool\n        A boolean option to enable striping\n\n    \"\"\"\n\n    def __init__(\n        self,\n        cascade_region: MemoryRegion,\n        max_proposals: int,\n        stripe_factors: int,\n        max_plan_size: int,\n        max_open_plans: int,\n        max_closed_plans: int,\n        always_copy_size: int,\n        disable_pareto_plans: bool = False,\n        disable_pareto_proposals: bool = False,\n        enable_multi_dimensional_striping: bool = False,\n        disable_block_culling: bool = True,\n        enable_striping: bool = False,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.CascaderOptions,\n            cascade_region,\n            max_proposals,\n            stripe_factors,\n            max_plan_size,\n            max_open_plans,\n            max_closed_plans,\n            always_copy_size,\n            disable_pareto_plans,\n            disable_pareto_proposals,\n            enable_multi_dimensional_striping,\n            disable_block_culling,\n            enable_striping,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/device_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n# pylint: disable=too-many-nested-blocks\n\"\"\"Device config class to hold information about the target hardware\"\"\"\nfrom typing import Tuple, List, Dict, Optional\nfrom functools import reduce\n\nimport math\nimport numpy as np\n\nimport tvm\nfrom . import BlockConfig\nfrom . import StripeConfig\nfrom . import Propagator\n\n\ndef _round_up(a: int, b: int) -> int:\n    \"\"\"Round up to a multiple of b\"\"\"\n    return ((a + b - 1) // b) * b\n\n\ndef _round_up_div(a: int, b: int) -> int:\n    \"\"\"Divide by b and round up to a multiple of b\"\"\"\n    return (a + b - 1) // b\n\n\nclass _Shape:\n    \"\"\"Helper class for dealing with Tensor shapes of different layouts\"\"\"\n\n    def __init__(self, shape: List[int], layout=\"NHWC\"):\n        if layout == \"NHCWB16\":\n            self.height = int(shape[1])\n            self.width = int(shape[3])\n            self.depth = int(shape[2]) * int(shape[4])\n        else:\n            # identity layout is NHWC but the shape is not always 4\n            length = len(shape)\n            if length == 4:\n                self.height = int(shape[1])\n                self.width = int(shape[2])\n                self.depth = int(shape[3])\n            elif length == 3:\n                self.height = int(shape[0])\n                self.width = int(shape[1])\n                self.depth = int(shape[2])\n            elif length == 2:\n                self.height = int(shape[0])\n                self.width = int(shape[1])\n                self.depth = 1\n            elif length == 1:\n                self.height = int(shape[0])\n                self.width = 1\n                self.depth = 1\n\n    def round_up(self, other: \"_Shape\"):\n        self.height = _round_up(self.height, other.height)\n        self.width = _round_up(self.width, other.width)\n        self.depth = _round_up(self.depth, other.depth)\n\n    def area(self) -> int:\n        return self.height * self.width\n\n    def as_list(self):\n        return [1, self.height, self.width, self.depth]\n\n\nclass EthosuDeviceConfig:\n    \"\"\"Arm(R) Ethos(TM)-U NPU config class\"\"\"\n\n    def __init__(self, device: str, disable_block_bulling: bool = False):\n        self._device = device\n        self._subkernel_limits = (8, 8)\n        self._output_cycles = (1, 2, 3, 4, 6)\n        self._split_depth = 16\n        self._max_block_shape = _Shape([1, 32, 64, 128])\n        self._bank_size_bytes = 1024\n        self._disable_block_culling = disable_block_bulling\n        if self._device == \"ethos-u55-256\":\n            self._micro_block = _Shape([1, 2, 2, 8])\n            self._input_micro_block = _Shape([1, 2, 2, 8])\n            self._delay_cycles = (2, 2)\n            self._activation_cycles = (0.25, 1)\n            self._output_units = 8\n\n            self._total_banks = 48\n            self._reserved_banks = 4\n            self._input_granularity = {1: 8, 2: 8, 4: 16}\n            self._accumulator_granularity = {4: 16, 5: 20}\n            self._lut_reserved = True\n        elif self._device == \"ethos-u55-128\":\n            self._micro_block = _Shape([1, 1, 2, 8])\n            self._input_micro_block = _Shape([1, 1, 2, 8])\n            self._delay_cycles = (2, 3)\n            self._activation_cycles = (0.5, 1)\n            self._output_units = 4\n\n            self._total_banks = 24\n            self._reserved_banks = 4\n            self._input_granularity = {1: 4, 2: 4, 4: 8}\n            self._accumulator_granularity = {4: 8, 5: 12}\n            self._lut_reserved = True\n        elif self._device == \"ethos-u55-64\":\n            self._micro_block = _Shape([1, 1, 1, 8])\n            self._input_micro_block = _Shape([1, 1, 1, 8])\n            self._delay_cycles = (2, 3)\n            self._activation_cycles = (1, 1)\n            self._output_units = 2\n\n            self._total_banks = 16\n            self._reserved_banks = 2\n            self._input_granularity = {1: 2, 2: 2, 4: 4}\n            self._accumulator_granularity = {4: 4, 5: 8}\n            self._lut_reserved = False\n        elif self._device == \"ethos-u55-32\":\n            self._micro_block = _Shape([1, 1, 1, 4])\n            self._input_micro_block = _Shape([1, 1, 1, 8])\n            self._delay_cycles = (3, 7)\n            self._activation_cycles = (1, 2)\n            self._output_units = 1\n\n            self._total_banks = 16\n            self._reserved_banks = 2\n            self._input_granularity = {1: 2, 2: 2, 4: 4}\n            self._accumulator_granularity = {4: 4, 5: 4}\n            self._lut_reserved = False\n\n    def _get_output_cycles(\n        self, op_type: str, op_str: str, ifm_dtype: str, ofm_dtype: str, activation: str\n    ) -> float:\n        \"\"\"Estimate cycles per output element for an NPU operator\n\n        Parameters\n        ----------\n        op_type : str\n            The NPU primitive operator\n                \"ethosu_pooling\"\n        op_str : str\n            The type of NPU operator.\n                \"MAX\"\n        ifm_dtype: str\n            Datatype of the Input Feature Map tensor (IFM)\n        ofm_dtype: str\n            Datatype of the Output Feature Map tensor (OFM)\n        activation : str\n            The activation function to use.\n                \"NONE\" - no activation function.\n                \"CLIP\" - clip the output between clip_min and clip_max.\n                \"TANH\" - tanh activation function.\n                \"SIGMOID\" - sigmoid activation function.\n                \"LUT\" - use a look-up table to perform the activation function.\n\n        Returns\n        -------\n        float\n            The cycles per output element\n        \"\"\"\n        cycles = 0\n        bw_limit = 0\n        if op_type == \"ethosu_pooling\" and op_str == \"MAX\":\n            cycles = self._output_cycles[0]\n        elif op_type in (\"ethosu_pooling\", \"ethosu_conv2d\", \"ethosu_depthwise_conv2d\"):\n            cycles = self._output_cycles[1] if ifm_dtype == \"int8\" else self._output_cycles[2]\n        elif op_type == \"ethosu_binary_elementwise\":\n            # Binary Bandwidth Limitations\n            if ifm_dtype == \"int8\":\n                bw_limit = 0.125 if ofm_dtype == \"int8\" else 0.75\n            elif ifm_dtype == \"int16\":\n                bw_limit = 0.75 if ofm_dtype == \"int16\" else 1\n            else:\n                bw_limit = 1.5\n\n            if op_str in (\"MIN\", \"MAX\"):\n                cycles = self._output_cycles[1]\n            elif op_str == \"MUL\":\n                cycles = self._output_cycles[2]\n            if op_str in (\"ADD\", \"SUB\"):\n                if ofm_dtype == \"int32\":\n                    cycles = (\n                        self._output_cycles[2] if ifm_dtype == \"int32\" else self._output_cycles[3]\n                    )\n                else:\n                    cycles = self._output_cycles[4]\n\n        elif op_type == \"ethosu_unary_elementwise\":\n            # Unary Bandwidth Limitations\n            if ifm_dtype == \"int16\":\n                bw_limit = 0.25\n            elif ifm_dtype == \"int32\":\n                bw_limit = 1\n\n            if op_str == \"CLZ\":\n                cycles = self._output_cycles[1]\n            elif op_str in (\"SHL\", \"SHR\"):\n                cycles = self._output_cycles[2]\n            elif op_str in (\"LRELU\", \"ABS\"):\n                cycles = self._output_cycles[1]\n                if ifm_dtype == \"int16\":\n                    bw_limit = 0.5\n\n        act_cycles = 0\n        if activation == \"CLIP\":\n            act_cycles = self._activation_cycles[0]\n        elif activation in (\"LUT\", \"TANH\", \"SIGMOID\"):\n            act_cycles = self._activation_cycles[1]\n\n        return max((cycles / self._output_units), act_cycles, bw_limit)\n\n    def _get_delay_cycles(self, op_type: str, ifm_dtype: str) -> int:\n        \"\"\"Get the number of delay cycles during a bubble\n\n        Parameters\n        ----------\n        op_type : str\n            The NPU primitive operator\n                \"ethosu_pooling\"\n        op_str : str\n            The type of NPU operator.\n                \"MAX\"\n        ifm_dtype: str\n            Datatype of the Input Feature Map tensor (IFM)\n\n        Returns\n        ----------\n        int\n            The amount of delay cycles\n        \"\"\"\n        if op_type in (\"ethosu_conv2d\", \"ethosu_depthwise2d\", \"ethosu_pooling\"):\n            if ifm_dtype == \"int16\":\n                return self._delay_cycles[1]\n\n            return self._delay_cycles[0]\n\n        return 0\n\n    def _get_weight_decoder_cycles(self, op_type: str) -> int:\n        \"\"\"Get cycle estimate for weight decoding\n\n        Parameters\n        ----------\n        op_type: str\n            The NPU primitive operator\n                \"ethosu_pooling\"\n\n        Returns\n        ----------\n        int\n            Estimated cycles for weight decoding\n        \"\"\"\n        if op_type in (\"ethosu_conv2d\", \"ethosu_depthwise2d\"):\n            return 32 * self._micro_block.depth // 8\n\n        return 0\n\n    def get_output_quantum(self, ofm_layout: str) -> Tuple[int]:\n        \"\"\"Get the atomic output volume\n\n        Parameters\n        ----------\n        ofm_layout : str\n            The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n        Returns\n        ----------\n        Tuple[int]\n            The atomic output volume formatted to the ofm_layout parameter\n        \"\"\"\n        if ofm_layout == \"NHCWB16\":\n            return [\n                1,\n                self._micro_block.height,\n                1,\n                self._micro_block.width,\n                self._micro_block.depth,\n            ]\n\n        return self._micro_block.as_list()\n\n    def _align(self, x: int, n: int) -> int:\n        return int(math.ceil(x / n) * n)\n\n    def _get_input_size(\n        self, output_size: int, kernel_stride: int, border: int, upscaling_factor: int\n    ) -> int:\n        return int(math.ceil(((output_size - 1) * kernel_stride + border)) / upscaling_factor)\n\n    def _get_dilated_kernel_size(self, kernel_size: int, dilation: int) -> int:\n        return (kernel_size - 1) * dilation + 1\n\n    def _get_input_block(\n        self,\n        output_block: _Shape,\n        input_shape: _Shape,\n        dtype: str,\n        op_type: str,\n        partkernel: bool,\n        stride_h: int,\n        stride_w: int,\n        dilated_kernel_h: int,\n        dilated_kernel_w: int,\n        upscaling_factor: int,\n    ) -> _Shape:\n        height = self._get_input_size(\n            output_block.height,\n            stride_h,\n            min(dilated_kernel_h, self._subkernel_limits[0]),\n            upscaling_factor,\n        )\n        width = self._get_input_size(\n            output_block.width,\n            stride_w,\n            min(dilated_kernel_w, self._subkernel_limits[1]),\n            upscaling_factor,\n        )\n\n        if op_type == \"ethosu_conv2d\":\n            if dtype == \"int8\":\n                if partkernel:\n                    depth = self._align(min(32, input_shape.depth), 8)\n                else:\n                    depth = self._align(min(16, input_shape.depth), 8)\n            elif dtype == \"int16\":\n                depth = self._align(min(16, input_shape.depth), 4)\n            else:\n                depth = self._align(min(8, input_shape.depth), 2)\n        else:\n            depth = output_block.depth\n\n        return _Shape(\n            [\n                1,\n                self._align(height, self._micro_block.height),\n                self._align(width, self._micro_block.width),\n                depth,\n            ]\n        )\n\n    def get_kernel_steps(\n        self,\n        op_type: str,\n        dilated_kernel_h: int,\n        dilated_kernel_w: int,\n        ifm_dtype: str,\n        partkernel: bool = False,\n    ) -> List[int]:\n        \"\"\"Calculate the total number of subkernels and their sizes\n\n        Parameters\n        ----------\n        op_type : str\n            The NPU primitive operator\n                \"ethosu_pooling\"\n        dilated_kernel_h: int\n            Height of dilated kernel\n        dilated_kernel_w: int\n            Width of dilated kernel\n        ifm_dtype: str\n            Datatype of the Input Feature Map tensor (IFM)\n        partkernel: bool\n            Flag showing whether part-kernel first traversal is used\n\n        Returns\n        ----------\n        List[int]\n            List where each entry contains the amount of elements in one of the subkernels\n        \"\"\"\n        if op_type == \"ethosu_binary_elementwise\":\n            return [1]\n\n        subkernels = self._get_subkernels(dilated_kernel_h, dilated_kernel_w)\n\n        # Determine the number of kernel steps per subkernel\n        kernel_steps = []\n        for y, x in subkernels:\n            subkernel_elements = x * y\n            if op_type == \"ethosu_conv2d\" and partkernel:\n                # Part-kernel-first traversal conv2d\n                divisor = 4 if ifm_dtype == \"int8\" else 2\n                kernel_steps.append(int(_round_up_div(subkernel_elements, divisor)))\n            elif op_type == \"ethosu_depthwise_conv2d\":\n                kernel_steps.append(int(_round_up_div(subkernel_elements, 4)))\n            else:\n                # Depth-first traversal conv2d or pooling\n                kernel_steps.append(int(subkernel_elements))\n\n        return kernel_steps\n\n    def _get_subkernels(self, dilated_kernel_h: int, dilated_kernel_w: int):\n        num_subkernels_y = _round_up_div(dilated_kernel_h, self._subkernel_limits[0])\n        num_subkernels_x = _round_up_div(dilated_kernel_w, self._subkernel_limits[1])\n        subkernels_y = [\n            min((dilated_kernel_h - i * self._subkernel_limits[0]), self._subkernel_limits[0])\n            for i in range(num_subkernels_y)\n        ]\n        subkernels_x = [\n            min((dilated_kernel_w - i * self._subkernel_limits[1]), self._subkernel_limits[1])\n            for i in range(num_subkernels_x)\n        ]\n\n        subkernels = []\n        for y in subkernels_y:\n            for x in subkernels_x:\n                subkernels.append((y, x))\n\n        return subkernels\n\n    def _get_accumulator_width(self, op_type: str, ifm_dtype: str):\n        if ifm_dtype == \"int16\" and op_type != \"ethosu_pooling\":\n            return 5\n\n        return 4\n\n    def is_partkernel(\n        self, op_type: str, ifm_channels: int, ifm_dtype: str, kernel_elements: int\n    ) -> bool:\n        \"\"\"Determine which block traversal strategy has better DPU utilization\n\n        Parameters\n        ----------\n        op_type: str\n            The NPU primitive operator\n                \"ethosu_pooling\"\n        ifm_channels: int\n            Number of input channels\n        ifm_dtype: str\n            Datatype of the Input Feature Map tensor (IFM)\n        kernel_elements: int\n            Total number of elements in the kernel\n\n        Returns\n        ----------\n        bool\n            True if partkernel first has best DPU utilization\n        \"\"\"\n        if op_type != \"ethosu_conv2d\":\n            return False\n\n        depth_first_utilization = ifm_channels / _round_up(\n            ifm_channels, 32 if ifm_dtype == \"int8\" else 16\n        )\n        part_kernel_first_utilization = (ifm_channels / _round_up(ifm_channels, 8)) * (\n            kernel_elements / _round_up(kernel_elements, 4 if ifm_dtype == \"int8\" else 2)\n        )\n\n        return part_kernel_first_utilization > depth_first_utilization or ifm_channels <= 8\n\n    def _get_input_banks(self, input_block_shape, input_bytewidth):\n        input_bytes = input_block_shape.area() * self._align(\n            input_block_shape.depth * input_bytewidth, 8\n        )\n        input_banks = _round_up_div(input_bytes, self._bank_size_bytes) * 2\n        input_banks = _round_up(input_banks, self._input_granularity[input_bytewidth])\n\n        return input_banks\n\n    def _get_accumulator_banks(self, output_block_shape, acc_bytewidth):\n        acc_depth = _round_up(output_block_shape.depth, 8)\n        acc_bytes = output_block_shape.area() * self._align(acc_depth, 8) * acc_bytewidth\n        acc_banks = _round_up_div(acc_bytes, self._bank_size_bytes) * 2\n        acc_banks = _round_up(acc_banks, self._accumulator_granularity[acc_bytewidth])\n\n        return acc_banks\n\n    @staticmethod\n    def _create_layout_block(nhwc_block_config, layout):\n        \"\"\"A helper function to convert to brick layout\"\"\"\n        if layout == \"NHCWB16\":\n            return [\n                nhwc_block_config[0],\n                nhwc_block_config[1],\n                1 + ((nhwc_block_config[3] - 1) // 16),\n                nhwc_block_config[2],\n                16,\n            ]\n        # else it could only be NHWC\n        return nhwc_block_config\n\n    def get_elementwise_block_config(\n        self,\n        ifm_propagator: Propagator,\n        ifm2_propagator: Optional[Propagator],\n        op_attrs: Dict,\n        ofm_shape: List[int],\n        output_layout: str,\n        input_layout: str,\n        input2_layout: Optional[str],\n        ifm_dtype: str,\n        ofm_dtype: str,\n    ) -> List[BlockConfig]:\n        \"\"\"Get a suitable block config for an elementwise operator\n\n        Parameters\n        ----------\n        ifm_propagator: Propagator,\n            The propagator containing the data dependencies between input and output\n        ifm2_propagator: Propagator,\n            The propagator containing the data dependencies between input2 and output\n        op_attrs: Dict,\n            Dictionary containing operator attributes\n        ofm_shape: List[int],\n            Shape of the output tensor\n        output_layout: str,\n            The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n        input_layout: str,\n            The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n        input2_layout: str,\n            The layout of the Input2 Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n        ifm_dtype: str,\n            Datatype of the Input Feature Map tensor (IFM)\n        ofm_dtype: str,\n            Datatype of the Output Feature Map tensor (OFM)\n\n        Returns\n        ----------\n        List[BlockConfig]\n            List containing a single suitable block config\n        \"\"\"\n        block_config = []\n        output_shape = [int(a) for a in ofm_shape]\n\n        op_type = op_attrs.get(\"op\")\n        op_str = op_attrs.get(\"op_str\")\n        activation = op_attrs.get(\"activation\", \"NONE\")\n\n        input_bytewidth = 1 if ifm_dtype == \"int8\" else 2 if ifm_dtype == \"int16\" else 4\n        banks_available = self._total_banks - self._reserved_banks\n        if activation == \"LUT\" and not self._lut_reserved:\n            banks_available -= 2\n\n        # Handle user-forced block config\n        options = tvm.transform.PassContext.current().config.get(\"relay.ext.ethos-u.options\", None)\n        if options and options.dev_force_block_config:\n            block_config = [int(v) for v in options.dev_force_block_config.split(\"x\")]\n            assert len(block_config) == 3\n            if output_layout == \"NHWC\":\n                block_shape = [output_shape[0], block_config[0], block_config[1], block_config[2]]\n            else:\n                block_shape = [\n                    output_shape[0],\n                    block_config[0],\n                    1 + ((block_config[2] - 1) // 16),\n                    block_config[1],\n                    16,\n                ]\n            output_cycles = self._get_output_cycles(\n                op_type, op_str, ifm_dtype, ofm_dtype, activation\n            )\n            output_cycles *= reduce(lambda a, b: a * b, block_shape, 1)\n            output_cycles = int(math.ceil(output_cycles))\n            return [BlockConfig(block_shape, block_shape, 0, output_cycles)]\n\n        # Split the block in half until it fits into SHRAM\n        max_height, max_width, max_depth = self._max_block_shape.as_list()[1:]\n        if output_layout == \"NHCWB16\":\n            output_height = output_shape[1]\n            output_width = output_shape[3]\n            output_channels = output_shape[2] * 16\n        else:\n            output_height = output_shape[1]\n            output_width = output_shape[2]\n            output_channels = output_shape[3]\n\n        output_nhwc_block = [\n            1,\n            _round_up(min(output_height, max_height), self._micro_block.height),\n            _round_up(min(output_width, max_width), self._micro_block.width),\n            _round_up(min(output_channels, max_depth), self._micro_block.depth),\n        ]\n        output_block = self._create_layout_block(output_nhwc_block, output_layout)\n        split_order = (a for a in [1, 2, 3])\n        split_axis = next(split_order)\n\n        offset = [0] * len(output_block)\n        stripes = [1] * len(output_block)\n        order = [1, 2, 4, 3, 0] if output_layout == \"NHCWB16\" else [1, 2, 3, 4]\n        while True:\n            # Create stripe config for output block\n            output_stripe_config = StripeConfig(\n                output_block, output_block, output_block, order, stripes, offset\n            )\n\n            # Propagate the output to obtain the two input blocks\n            input_block = _Shape(ifm_propagator.propagate(output_stripe_config).shape, input_layout)\n            if ifm2_propagator:\n                input2_block = _Shape(\n                    ifm2_propagator.propagate(output_stripe_config).shape, input2_layout\n                )\n            else:\n                # Unary elementwise\n                input2_block = input_block\n\n            input_block.round_up(self._input_micro_block)\n            input2_block.round_up(self._input_micro_block)\n\n            # Banks required for input block\n            input_banks = self._get_input_banks(input_block, input_bytewidth)\n            # Banks required for input2 block\n            input2_banks = self._get_input_banks(input2_block, input_bytewidth)\n\n            # Check whether or not both IFMs fit into SHRAM\n            if (input_banks + input2_banks) <= banks_available:\n                output_cycles = self._get_output_cycles(\n                    op_type, op_str, ifm_dtype, ofm_dtype, activation\n                )\n                output_cycles *= reduce(lambda a, b: a * b, output_block, 1)\n                output_cycles = int(math.ceil(output_cycles))\n                block_config.append(\n                    BlockConfig(input_block.as_list(), output_block, 0, output_cycles)\n                )\n                break\n\n            if output_nhwc_block[split_axis] == self._micro_block.as_list()[split_axis]:\n                split_axis = next(split_order)\n\n            output_nhwc_block[split_axis] = _round_up(\n                _round_up_div(output_nhwc_block[split_axis], 2),\n                self._micro_block.as_list()[split_axis],\n            )\n            output_block = self._create_layout_block(output_nhwc_block, output_layout)\n\n        return block_config\n\n    def _get_subkernel_propagator(\n        self, op_attrs, ifm_propagator, input_layout, output_layout, depth\n    ):\n        op_type = op_attrs.get(\"op\")\n        stride_h = int(op_attrs.get(\"stride_h\", 1))\n        stride_w = int(op_attrs.get(\"stride_w\", 1))\n        transform = ifm_propagator.transform\n\n        if op_type != \"ethosu_identity\":\n            if input_layout == \"NHCWB16\":\n                transform[1][-1] = min(transform[1][-1], self._subkernel_limits[0] - stride_h)\n                transform[3][-1] = min(transform[3][-1], self._subkernel_limits[1] - stride_w)\n            else:\n                transform[1][-1] = min(transform[1][-1], self._subkernel_limits[0] - stride_h)\n                transform[2][-1] = min(transform[2][-1], self._subkernel_limits[1] - stride_w)\n\n            if op_type in (\"ethosu_pooling\", \"ethosu_depthwise_conv2d\"):\n                if output_layout == \"NHCWB16\" and input_layout == \"NHWC\":\n                    transform[3][-1] = depth\n                elif output_layout == \"NHCWB16\" and input_layout == \"NHCWB16\":\n                    transform[2][-1] = 1 + ((depth - 1) // 16)\n\n        return Propagator(transform, ifm_propagator.offset)\n\n    def get_valid_block_configs(\n        self,\n        ifm_propagator: Propagator,\n        op_attrs: Dict,\n        ofm_shape: List[int],\n        ofm_channels: int,\n        ifm_channels: int,\n        output_layout: str,\n        input_layout: str,\n        ifm_dtype: str,\n        ofm_dtype: str,\n        kernel_h: int = 1,\n        kernel_w: int = 1,\n    ) -> List[BlockConfig]:\n        \"\"\"Get all of the valid block configs\n\n        Parameters\n        ----------\n        ifm_propagator: Propagator,\n            The propagator containing the data dependencies between input and output\n        op_attrs: Dict,\n            Dictionary containing operator attributes\n        ofm_shape: List[int],\n            Shape of the output tensor\n        ofm_channels: int,\n            Number of output channels\n        ifm_channels: int,\n            Number of input channels\n        output_layout: str,\n            The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n        input_layout: str,\n            The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n        ifm_dtype: str,\n            Datatype of the Input Feature Map tensor (IFM)\n        ofm_dtype: str,\n            Datatype of the Output Feature Map tensor (OFM)\n        kernel_h: int,\n            Height of kernel\n        kernel_h: int\n            Width of kernel\n\n        Returns\n        ----------\n        List[BlockConfig]\n            List containing all of the valid block configs\n        \"\"\"\n        valid_block_configs = []\n\n        op_type = op_attrs.get(\"op\")\n        op_str = op_attrs.get(\"op_str\")\n        activation = op_attrs.get(\"activation\", \"NONE\")\n        upscaling_factor = 1 if op_attrs.get(\"upscale\", \"NONE\") == \"NONE\" else 2\n\n        if output_layout == \"NHCWB16\":\n            output_shape = _Shape([1, ofm_shape[1], ofm_shape[3], ofm_channels])\n        else:\n            output_shape = _Shape(ofm_shape)\n\n        # Define search space\n        max_height = min(output_shape.height, self._max_block_shape.height)\n        min_height = max(self._micro_block.height, upscaling_factor)\n\n        max_width = min(output_shape.width, self._max_block_shape.width)\n        min_width = max(self._micro_block.width, upscaling_factor)\n\n        max_depth = min(ofm_channels, self._max_block_shape.depth)\n        min_depth = max(self._micro_block.depth, upscaling_factor)\n\n        heights = range(min_height, max_height + min_height, min_height)\n        widths = range(min_width, max_width + min_width, min_width)\n        depths = range(min_depth, max_depth + min_depth, min_depth)\n\n        # Handle user-forced block config\n        options = tvm.transform.PassContext.current().config.get(\"relay.ext.ethos-u.options\", None)\n        forced = False\n        if options and options.dev_force_block_config:\n            block_config = [int(v) for v in options.dev_force_block_config.split(\"x\")]\n            assert len(block_config) == 3\n            heights = [block_config[0]]\n            widths = [block_config[1]]\n            depths = [block_config[2]]\n            forced = True\n\n        input_bytewidth = 1 if ifm_dtype == \"int8\" else 2\n        acc_bytewidth = self._get_accumulator_width(op_type, ifm_dtype)\n        banks_available = self._total_banks - self._reserved_banks\n        if activation == \"LUT\" and not self._lut_reserved:\n            banks_available -= 2\n\n        # Input block depth has additional limitations for operators that require full input depth\n        input_block_depth = 0\n        partkernel = self.is_partkernel(op_type, ifm_channels, ifm_dtype, kernel_h * kernel_w)\n        if op_type == \"ethosu_conv2d\":\n            if partkernel:\n                input_block_depth = min(ifm_channels, 16)\n            else:\n                input_block_depth = min(ifm_channels, 32)\n\n        for depth in reversed(depths):\n            if (depth < output_shape.depth) and (depth % self._split_depth != 0) and not forced:\n                # Block depth has to be less than full depth or a multiple of the split depth\n                continue\n\n            subkernel_propagator = self._get_subkernel_propagator(\n                op_attrs, ifm_propagator, input_layout, output_layout, depth\n            )\n\n            for width in reversed(widths):\n                for height in reversed(heights):\n                    if output_layout == \"NHCWB16\":\n                        output_block = (\n                            1,\n                            height,\n                            1 + ((depth - 1) // 16),\n                            width,\n                            16,\n                        )\n                        order = [1, 2, 4, 3, 0]\n                    else:\n                        output_block = (1, height, width, depth)\n                        order = [1, 2, 3, 4]\n\n                    offset = [0] * len(output_block)\n                    stripes = [1] * len(output_block)\n                    block_stripe_config = StripeConfig(\n                        output_block,\n                        output_block,\n                        output_block,\n                        order,\n                        stripes,\n                        offset,\n                    )\n\n                    # Propagate output block\n                    input_block = subkernel_propagator.propagate(block_stripe_config)\n\n                    input_block_shape = _Shape(input_block.shape, input_layout)\n                    input_block_shape.round_up(self._input_micro_block)\n\n                    output_block_shape = _Shape(output_block, output_layout)\n\n                    if op_type == \"ethosu_conv2d\":\n                        input_block_shape.depth = input_block_depth\n\n                    # Banks required for input block\n                    input_banks = self._get_input_banks(input_block_shape, input_bytewidth)\n                    # Banks required for accumulation\n                    acc_banks = self._get_accumulator_banks(output_block_shape, acc_bytewidth)\n\n                    if (input_banks + acc_banks) <= banks_available:\n                        output_cycles = self._get_output_cycles(\n                            op_type, op_str, ifm_dtype, ofm_dtype, activation\n                        )\n                        output_cycles *= np.prod(output_block).tolist()\n                        output_cycles = int(math.ceil(output_cycles))\n                        compute_cycles = self._estimate_compute_cycles_per_block(\n                            op_type,\n                            output_block_shape,\n                            input_block_shape,\n                            kernel_h,\n                            kernel_w,\n                            ifm_channels,\n                            \"int8\",\n                            partkernel,\n                        )\n                        block_config = BlockConfig(\n                            input_block_shape.as_list(), output_block, compute_cycles, output_cycles\n                        )\n\n                        if self._disable_block_culling:\n                            # Block culling disabled - add all block configs that fit\n                            valid_block_configs.append(block_config)\n                        else:\n                            # Add block config only if it's not dominated by an existing block.\n                            # A block config is dominated by another if its output_shape is greater\n                            # or equal in every dimension and strictly greater in at least one\n                            # dimension.\n                            dominated = False\n                            for valid_block in valid_block_configs:\n                                if block_config < valid_block:\n                                    dominated = True\n                                    break\n\n                            if not dominated:\n                                valid_block_configs.append(block_config)\n\n                            # Every consecutive block in the innermost loop will be dominated by\n                            # this one so break\n                            break\n\n        return valid_block_configs\n\n    def _estimate_compute_cycles_per_block(\n        self,\n        op_type: str,\n        block_shape: _Shape,\n        input_block_shape: _Shape,\n        kernel_h: int,\n        kernel_w: int,\n        input_channels: int,\n        ifm_dtype: str,\n        partkernel: bool = False,\n    ) -> Tuple[int, int]:\n        # Calculate the amount of micro blocks per block, per axis\n        num_quantum_x = _round_up_div(block_shape.width, self._micro_block.width)\n        num_quantum_y = _round_up_div(block_shape.height, self._micro_block.height)\n        num_quantum_z = _round_up_div(block_shape.depth, self._micro_block.depth)\n        num_quantum_xy = num_quantum_x * num_quantum_y\n\n        kernel_steps = self.get_kernel_steps(op_type, kernel_h, kernel_w, ifm_dtype, partkernel)\n\n        wd_cycles = self._get_weight_decoder_cycles(op_type)\n        delay_cycles = self._get_delay_cycles(op_type, ifm_dtype)\n        cycle_quantum = 4\n\n        compute_cycles = 0\n        for subkernel_steps in kernel_steps:\n            subkernel_cycles = 1 if op_type == \"ethosu_pooling\" else subkernel_steps\n            compute_cycles += (\n                max(wd_cycles, cycle_quantum * num_quantum_xy) * subkernel_cycles * num_quantum_z\n            )\n\n            if num_quantum_xy == 1:\n                if num_quantum_z == 1:\n                    compute_cycles += delay_cycles * subkernel_steps\n                elif subkernel_steps > 1:\n                    compute_cycles += delay_cycles * (subkernel_steps - 1) * num_quantum_z\n\n        if partkernel:\n            compute_cycles *= _round_up_div(input_block_shape.depth, 8)\n\n        if op_type == \"ethosu_conv2d\":\n            compute_cycles *= _round_up_div(input_channels, input_block_shape.depth)\n\n        return compute_cycles\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Graph objects to define compute graphs for the NPU cascader.\"\"\"\nfrom typing import List, Dict\nfrom enum import IntEnum\nfrom collections import namedtuple\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm import te\nfrom tvm.runtime import Object\n\nfrom .stripe_config import StripeConfig\nfrom .device_config import EthosuDeviceConfig\nfrom . import _ffi_api\n\n\n# A global store to register matching functions\nREGISTERED_MATCHERS = []\n\n\nTESubgraph = namedtuple(\"TESubgraph\", [\"input_tensors\", \"output_tensor\"])\n\n\nclass BufferMode(IntEnum):\n    RECOMPUTE = 0\n    ROLLING = 1\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.PerformanceInfo\")\nclass PerformanceInfo(Object):\n    \"\"\"PerformanceInfo class\"\"\"\n\n    @property\n    def compute_cycles(self):\n        return self._compute_cycles\n\n    @property\n    def read_bytes(self):\n        return list(self._read_bytes)\n\n    @property\n    def write_bytes(self):\n        return self._write_bytes\n\n    @property\n    def block_config(self):\n        return self._block_config\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.Tensor\")\nclass Tensor(Object):\n    \"\"\"Tensor class\"\"\"\n\n    def __init__(self, shape, dtype, is_constant=False, compression_ratio=1):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Tensor, shape, dtype, is_constant, compression_ratio\n        )\n\n    def add_producer(self, part):\n        _ffi_api.TensorAddProducer(self, part)\n\n    def add_consumer(self, part):\n        _ffi_api.TensorAddConsumer(self, part)\n\n    @property\n    def producers(self):\n        return list(self._producers)\n\n    @property\n    def consumers(self):\n        return list(self._consumers)\n\n    @property\n    def shape(self):\n        return list(self._shape)\n\n    @property\n    def dtype(self):\n        return self._dtype\n\n    @property\n    def is_constant(self):\n        return self._is_constant\n\n    @property\n    def compression_ratio(self):\n        return self._compression_ratio\n\n    @property\n    def size(self):\n        return self._size\n\n\nclass Part(Object):\n    \"\"\"Part base class\"\"\"\n\n    def set_input(self, index: int, tensor: Tensor):\n        _ffi_api.PartSetInput(self, index, tensor)\n\n    def set_output(self, tensor: Tensor):\n        _ffi_api.PartSetOutput(self, tensor)\n\n    def calculate_input_stripe_configs(\n        self, output_stripe_config: StripeConfig\n    ) -> List[StripeConfig]:\n        return list(_ffi_api.PartCalculateInputStripeConfigs(self, output_stripe_config))\n\n    def get_stripe_align_hint(self) -> List[int]:\n        return list(_ffi_api.PartGetStripeAlignHint(self))\n\n    def get_performance_info(\n        self, stripe_config: StripeConfig, buffer_mode: BufferMode\n    ) -> PerformanceInfo:\n        return _ffi_api.PartGetPerformanceInfo(self, stripe_config, buffer_mode)\n\n    @property\n    def input_tensors(self):\n        return list(self._input_tensors)\n\n    @property\n    def output_tensor(self):\n        return self._output_tensor\n\n    @property\n    def propagators(self):\n        return list(self._propagators)\n\n    @property\n    def in_line(self):\n        return self._in_line\n\n    @property\n    def subgraph(self):\n        return TESubgraph(list(self._te_input_tensors), self._te_output_tensor)\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.CascaderGraph\")\nclass CascaderGraph(Object):\n    \"\"\"A class to describe a graph of Parts and Tensors used by the cascader.\n\n    This class describes a graph consisting of two object types: Tensors and Parts.\n    It defines a topological ordering on the graph such that each Part and Tensor has a\n    position in the ordering. This ordering is used by the Plan and Proposal generation\n    algorithms. It is also the ordering the Parts are expected to be executed in.\n\n    In addition to defining an ordering, the Parts and Tensors are also all given unique\n    IDs which they can be referred to by.\"\"\"\n\n    def __init__(self, input_tensors: List[Tensor], output_tensors: List[Tensor]):\n        self.__init_handle_by_constructor__(_ffi_api.CascaderGraph, input_tensors, output_tensors)\n\n    def get_part_id(self, part: Part) -> int:\n        return _ffi_api.CascaderGraphGetPartID(self, part)\n\n    def get_tensor_id(self, tensor: Tensor) -> int:\n        return _ffi_api.CascaderGraphGetTensorID(self, tensor)\n\n    @property\n    def input_tensors(self):\n        return list(self._input_tensors)\n\n    @property\n    def output_tensors(self):\n        return list(self._output_tensors)\n\n    @property\n    def tensor_order(self):\n        return list(self._tensor_order)\n\n    @property\n    def part_order(self):\n        return list(self._part_order)\n\n\ndef register_matcher(matcher):\n    \"\"\"Register a match function to the frontend.\n\n    A match function takes a te.Tensor and checks whether it matches\n    a known operator/operator sequence. If it does, it returns a Part\n    which models the behaviour of that operator sequence. Otherwise,\n    it returns None.\n    \"\"\"\n    REGISTERED_MATCHERS.append(matcher)\n    return matcher\n\n\ndef create_cascader_graph(\n    te_graph: TESubgraph, const_dict: Dict[int, np.ndarray], device_config: EthosuDeviceConfig\n) -> CascaderGraph:\n    \"\"\"Create a CascaderGraph from a Tensor Expression graph and constant dictionary.\n\n    Parameters\n    ----------\n    te_graph : TESubgraph\n        The Tensor Expression graph.\n    const_dict : Dict[int, np.ndarray]\n        The constant dictionary.\n    device_config : EthosuDeviceConfig\n        Target device configuration.\n\n    Returns\n    -------\n    CascaderGraph\n        The CascaderGraph.\n    \"\"\"\n    tensor_map = {}\n\n    def _visit_tensor(tensor):\n        if tensor not in tensor_map:\n            is_const = False\n            # Logic to determine if the tensor is constant\n            if tensor in list(te_graph.inputs):\n                i = list(te_graph.inputs).index(tensor)\n                if i in const_dict:\n                    is_const = True\n\n            # TODO(@mbaret): Calculate the compression ratio\n            plan_tensor = Tensor(\n                tensor.shape,\n                tensor.dtype,\n                is_constant=is_const,\n            )\n            tensor_map[tensor] = plan_tensor\n            if isinstance(tensor.op, te.PlaceholderOp) or tensor in te_graph.inputs:\n                return\n\n            input_tensors = []\n            # Check whether any of the registered matchers match the current tensor\n            for matcher in REGISTERED_MATCHERS:\n                part = matcher(tensor, device_config)\n                if part:\n                    input_tensors = part.subgraph.input_tensors\n                    break\n\n            assert part is not None, f\"The tensor {tensor} doesn't match any part.\"\n            part.set_output(plan_tensor)\n            plan_tensor.add_producer(part)\n            for i, input_tensor in enumerate(input_tensors):\n                _visit_tensor(input_tensor)\n                part.set_input(i, tensor_map[input_tensor])\n                tensor_map[input_tensor].add_consumer(part)\n\n    for output in te_graph.outputs:\n        _visit_tensor(output)\n\n    input_tensors = []\n    for t in te_graph.inputs:\n        # This is needed because sometimes there are orphaned constants\n        if t in tensor_map:\n            input_tensors.append(tensor_map[t])\n\n    output_tensors = [tensor_map[t] for t in te_graph.outputs]\n    return CascaderGraph(input_tensors, output_tensors)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/logging.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A class to hold logging information about the cascader\"\"\"\nfrom typing import Tuple\nimport datetime\nimport json\nimport os\nimport math\n\n\nclass Logging:\n    \"\"\"Cascader logging class\"\"\"\n\n    def __init__(self):\n        self.min_memory_usage = 0\n        self.max_memory_usage = 0\n        self.min_cycles = 0\n        self.max_cycles = 0\n\n        self.selected_proposal_idx = -1\n        self.proposals = {}\n        self.cascader_runtime = 0\n\n    def add_proposal(self, idx: int, memory_usage: int, cycles: int):\n        self.proposals[idx] = {\"memory_usage\": memory_usage, \"cycles\": cycles}\n\n    def get_extreme_points(self) -> Tuple[int, int, int, int]:\n        min_cycles, min_mem_usage = math.inf, math.inf\n        max_cycles, max_mem_usage = 0, 0\n        for proposal in self.proposals.values():\n            min_mem_usage = min(proposal[\"memory_usage\"], min_mem_usage)\n            max_mem_usage = max(proposal[\"memory_usage\"], max_mem_usage)\n            min_cycles = min(proposal[\"cycles\"], min_cycles)\n            max_cycles = max(proposal[\"cycles\"], max_cycles)\n\n        return min_mem_usage, max_mem_usage, min_cycles, max_cycles\n\n    def dump_json(self):\n        min_mem_usage, max_mem_usage, min_cycles, max_cycles = self.get_extreme_points()\n        with open(os.getcwd() + \"/cascader_log.json\", \"w\") as json_file:\n            print(\n                json.dumps(\n                    {\n                        \"date\": f\"{datetime.datetime.now()}\",\n                        \"cascader_runtime\": self.cascader_runtime,\n                        \"min_cycles\": min_cycles,\n                        \"max_cycles\": max_cycles,\n                        \"min_memory_usage\": min_mem_usage,\n                        \"max_memory_usage\": max_mem_usage,\n                        \"selected_proposal\": self.selected_proposal_idx,\n                        \"proposals\": self.proposals,\n                    },\n                    indent=2,\n                ),\n                file=json_file,\n            )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/pareto.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pareto optimisation functions for the NPU cascader.\"\"\"\nfrom typing import List\n\nfrom tvm import Object\n\nfrom . import _ffi_api\nfrom .plan import Plan\n\n\ndef _get_pareto_frontier(costs: List[List[float]]) -> List[bool]:\n    for i, cost in enumerate(costs):\n        for j, value in enumerate(cost):\n            costs[i][j] = float(value)\n\n    return [bool(v) for v in _ffi_api.GetParetoFrontier(costs)]\n\n\ndef _thin_vector(vec: List[Object], max_size: int) -> List[Object]:\n    return list(_ffi_api.ThinVector(vec, max_size))\n\n\ndef _pareto_cull_plans(\n    plans: List[Plan], max_plans: int, disable_pareto_metric: bool\n) -> List[Plan]:\n    return list(_ffi_api.ParetoCullPlans(plans, max_plans, disable_pareto_metric))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/parts.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Parts used by the NPU cascader.\"\"\"\nfrom typing import List\nimport tvm._ffi\n\nfrom .propagator import Propagator\nfrom .graph import Part, TESubgraph\nfrom .block_config import BlockConfig\nfrom .stripe_config import StripeConfig\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.InlinePart\")\nclass InlinePart(Part):\n    \"\"\"InlinePart class\"\"\"\n\n    def __init__(\n        self,\n        te_subgraph: TESubgraph,\n        propagators: List[Propagator],\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.InlinePart,\n            te_subgraph.input_tensors,\n            te_subgraph.output_tensor,\n            propagators,\n        )\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.EthosuPart\")\nclass EthosuPart(Part):\n    \"\"\"A class to describe a Part to be executed on an Arm(R) Ethos(TM)-U NPU.\n\n    EthosuParts must be provided with an output quantum and the cycles taken to\n    compute an output quantum which depend on the operator the NPU is computing.\"\"\"\n\n    def __init__(\n        self,\n        te_subgraph: TESubgraph,\n        propagators: List[Propagator],\n        output_quantum: List[int],\n        subkernels: int,\n        valid_block_configs: List[BlockConfig],\n        weight_tensor_idx: int = -1,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.EthosuPart,\n            te_subgraph.input_tensors,\n            te_subgraph.output_tensor,\n            propagators,\n            output_quantum,\n            subkernels,\n            valid_block_configs,\n            weight_tensor_idx,\n        )\n\n    def get_block_config(self, stripe_config: StripeConfig) -> BlockConfig:\n        return _ffi_api.EthosuPartGetBlockConfig(self, stripe_config)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/plan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Plan class to hold subgraph scheduling information.\"\"\"\nfrom typing import Dict, FrozenSet\nimport tvm._ffi\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\nfrom .graph import Tensor, Part\nfrom .tensor_config import TensorConfig, MemoryRegion\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.Plan\")\nclass Plan(Object):\n    \"\"\"\n    A class which describes how to schedule a subgraph of Parts together.\n\n    A Plan takes the form of a subgraph of connected Parts (recorded in part_group) with\n    TensorConfigs for all of the required Tensors (recorded in tensor_configs). This information\n    can be used to produce a Tensor Expression schedule with inter-operator scheduling. A Plan is\n    necessarily single-output such that all non-output Parts are 'computed_at'ed the scope of the\n    output Part. This is what achieves the technique referred to as 'cascading'. A Plan also has\n    an interior memory region which specifies the region of memory into which all the Plans\n    intermediate buffers should be allocated.\n\n    Additionally, a Plan contains some other information used during the Plan generation and\n    selection algorithms. Both the memory and cycles required to run the Plan are accounted for so\n    that Plans can be ranked and Pareto-culled on these metrics. Furthermore, the TensorConfigs\n    which are 'open' is recorded indicating that these are valid points to merge with another Plan.\n    A Plan can only be turned into a schedule if it has no 'open' TensorConfigs - at which point\n    the Plan is said to be 'closed'.\n\n    Attributes\n    ----------\n    tensor_configs : Dict[Tensor, TensorConfig]\n        The TensorConfigs specified by the Plan.\n    open_configs : FrozenSet[TensorConfig]\n        The TensorConfigs which are 'open' meaning they are a Plan input/output but have\n        'interior' state.\n    output_config : TensorConfig\n        The TensorConfig of the Plan's output tensor.\n    part_group : FrozenSet[Part]\n        The Parts which are covered by the Plan.\n    interior_region : MemoryRegion\n        The MemoryRegion in which to store 'interior' Plan buffers.\n    memory_usage : int\n        The interior memory used by the Plan in bytes.\n    cycles : int\n        The cycles taken to execute the Plan.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        tensor_configs: Dict[Tensor, TensorConfig],\n        open_configs: FrozenSet[TensorConfig],\n        output_config: TensorConfig,\n        part_group: FrozenSet[Part],\n        interior_region: MemoryRegion,\n        memory_usage: int,\n        cycles: int,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Plan,\n            list(tensor_configs.values()),\n            list(open_configs),\n            output_config,\n            list(part_group),\n            interior_region,\n            memory_usage,\n            cycles,\n        )\n\n    def merge(self, other):\n        \"\"\"\n        Merge two Plans with share an 'open' TensorConfig.\n\n        The current Plan is referred to as the 'upper Plan' and the other Plan as the 'lower\n        Plan'. The 'open' output config of the upper Plan must be an 'open' input config of the\n        lower Plan. The Tensor referenced by these configs is the Tensor on which the two Plans\n        will be merged. The merge process does the following:\n\n        The tensor config maps will be merged with TensorConfigs from the upper Plan taking\n        priority. The open configs will be merged with the TensorConfigs that are being merged\n        having been removed. The output config will be that of the lower Plan. The part groups\n        will be merged. The interior region is necessarily the same for both the upper and lower\n        Plan. The cycles and memory usage will be summed.\n\n        Parameters\n        ----------\n        other : Plan\n            The Plan to merge with.\n\n        Return\n        ------\n        Plan\n            The merged Plan.\n\n        \"\"\"\n        return _ffi_api.PlanMerge(self, other)\n\n    @property\n    def tensor_configs(self):\n        \"\"\"The TensorConfigs specified by the Plan.\"\"\"\n        tensor_configs = {}\n        for config in self._tensor_configs:\n            tensor_configs[config.tensor] = config\n        return tensor_configs\n\n    @property\n    def open_configs(self):\n        \"\"\"\n        The TensorConfigs which are 'open' meaning they are a Plan input/output but have\n        'interior' state.\n        \"\"\"\n        return frozenset(self._open_configs)\n\n    @property\n    def output_config(self):\n        \"\"\"The TensorConfig of the Plan's output tensor.\"\"\"\n        return self._output_config\n\n    @property\n    def part_group(self):\n        \"\"\"The Parts which are covered by the Plan.\"\"\"\n        return frozenset(self._part_group)\n\n    @property\n    def interior_region(self):\n        \"\"\"The MemoryRegion in which to store 'interior' Plan buffers.\"\"\"\n        return self._interior_region\n\n    @property\n    def memory_usage(self):\n        \"\"\"The interior memory used by the Plan in bytes.\"\"\"\n        return self._memory_usage\n\n    @property\n    def cycles(self):\n        \"\"\"The cycles taken to execute the Plan.\"\"\"\n        return self._cycles\n\n    def __repr__(self):\n        return (\n            f\"Plan(tensor_configs={self.tensor_configs}, \"\n            f\"open_configs={self.open_configs}, \"\n            f\"output_config={self.output_config}, \"\n            f\"part_group={self.part_group}, \"\n            f\"interior_region={self.interior_region.name}, \"\n            f\"memory_usage={self.memory_usage}, \"\n            f\"cycles={self.cycles}, \"\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/plan_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Algorithms to generate Plans for a CascaderGraph.\"\"\"\nfrom typing import List, Dict, Tuple\n\nfrom tvm.contrib.ethosu.cascader.tensor_config import MemoryRegion, TensorConfig\n\nfrom . import _ffi_api\nfrom .cascader_options import CascaderOptions\nfrom .plan import Plan\nfrom .stripe_config import StripeConfig\nfrom .graph import CascaderGraph, Part, Tensor\n\n\ndef _generate_output_stripe_configs(\n    part: Part, stripe_factors: int, enable_striping: bool, multi_dimensional: bool\n) -> List[StripeConfig]:\n    return list(\n        _ffi_api.GenerateOutputStripeConfigs(\n            part, stripe_factors, enable_striping, multi_dimensional\n        )\n    )\n\n\ndef _generate_single_plans(\n    part: Part,\n    output_stripe_configs: List[StripeConfig],\n    home_map: Dict[Tensor, List[MemoryRegion]],\n    cascade_region: MemoryRegion,\n) -> List[Plan]:\n    return list(_ffi_api.GenerateSinglePlans(part, output_stripe_configs, home_map, cascade_region))\n\n\ndef _generate_graph_plans(\n    graph: CascaderGraph,\n    home_map: Dict[Tensor, List[MemoryRegion]],\n    options: CascaderOptions,\n):\n    return _ffi_api.GenerateGraphPlans(\n        graph,\n        home_map,\n        options,\n    )\n\n\ndef get_copy_cycles_hint(tensor_config: TensorConfig) -> Tuple[int, int]:\n    \"\"\"\n    Returns a hint estimating the number of cycles for the copy\n    specified by tensor_config.\n\n    Parameters\n    ----------\n    tensor_config : TensorConfig\n        The tensor configuration to estimate.\n\n    Returns\n    -------\n    mem2mem_cycles : int\n        Total estimated cycles.\n    initial_mem2mem_cycles : int\n        Estimated cycles for the first block.\n    \"\"\"\n    return _ffi_api.GetCopyCyclesHint(tensor_config)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/propagator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Propagator class.\"\"\"\n# pylint: disable=invalid-name\nimport tvm._ffi\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.Propagator\")\nclass Propagator(Object):\n    \"\"\"Propagator class\"\"\"\n\n    def __init__(self, transform, offset):\n        float_transform = list([list(float(v) for v in row) for row in transform])\n        self.__init_handle_by_constructor__(_ffi_api.Propagator, float_transform, offset)\n\n    def propagate(self, stripe_config):\n        return _ffi_api.PropagatorPropagate(self, stripe_config)\n\n    @property\n    def transform(self):\n        \"\"\"Get the transform matrix\"\"\"\n        new_matrix = []\n        for row in self._transform:\n            new_row = []\n            for v in row:\n                new_row.append(v.value)\n\n            new_matrix.append(new_row)\n\n        return new_matrix\n\n    @property\n    def offset(self):\n        \"\"\"Get the offset matrix\"\"\"\n        new_vec = []\n        for v in self._offset:\n            new_vec.append(v.value)\n\n        return new_vec\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/proposal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Proposal class to hold graph scheduling information.\"\"\"\nfrom typing import Dict, FrozenSet, List\nimport tvm._ffi\nfrom tvm.contrib.ethosu.cascader.plan import Plan\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\nfrom .graph import Tensor, Part, CascaderGraph\nfrom .tensor_config import TensorConfig, MemoryRegion\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.Proposal\")\nclass Proposal(Object):\n    \"\"\"A class which describes how to schedule a CascaderGraph as a series of disjoint Plans.\n\n    Attributes\n    ----------\n    graph : CascaderGraph\n        The CascaderGraph to which the Proposal applies.\n    part_group : FrozenSet[Part]\n        The Parts which are covered by the Proposal.\n    plans : List[Plan]\n        The Plans used in the Proposal.\n    input_tensor_configs : Dict[Tensor, TensorConfig]\n        The TensorConfigs indexed by Tensor in the Proposal which aren't produced by a Plan.\n    cascade_region : MemoryRegion\n        The MemoryRegion where cascading buffers should be homed.\n    memory_usage : int\n        The memory required to execute the Proposal in the cascading MemoryRegion.\n    cycles : int\n        The estimated cycles taken to execute the Proposal.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        graph: CascaderGraph,\n        part_group: FrozenSet[Part],\n        plans: List[Plan],\n        input_tensor_configs: Dict[Tensor, TensorConfig],\n        cascade_region: MemoryRegion,\n        memory_usage: Dict[MemoryRegion, int],\n        cycles: int,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Proposal,\n            graph,\n            list(part_group),\n            plans,\n            input_tensor_configs,\n            cascade_region,\n            memory_usage,\n            cycles,\n        )\n\n    @property\n    def graph(self) -> CascaderGraph:\n        \"\"\"The CascaderGraph to which the Proposal applies.\"\"\"\n        return self._graph\n\n    @property\n    def part_group(self) -> FrozenSet[Part]:\n        \"\"\"The Parts which are covered by the Proposal.\"\"\"\n        return frozenset(self._part_group)\n\n    @property\n    def plans(self) -> List[Plan]:\n        \"\"\"The Plans used in the Proposal.\"\"\"\n        return list(self._plans)\n\n    @property\n    def input_tensor_configs(self) -> Dict[Tensor, TensorConfig]:\n        \"\"\"The TensorConfigs indexed by Tensor in the Proposal which aren't produced by a Plan.\"\"\"\n        return dict(self._input_tensor_configs)\n\n    @property\n    def cascade_region(self) -> MemoryRegion:\n        \"\"\"The MemoryRegion where cascading buffers should be homed.\"\"\"\n        return self._cascade_region\n\n    @property\n    def memory_usage(self) -> int:\n        \"\"\"The memory required to execute the Proposal in the cascading MemoryRegion.\"\"\"\n        return int(self._memory_usage)\n\n    @property\n    def cycles(self) -> int:\n        \"\"\"The estimated cycles taken to execute the Proposal.\"\"\"\n        return int(self._cycles)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/proposal_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Algorithms to generate Proposals for a Graph.\"\"\"\nfrom typing import List, Dict, FrozenSet\n\nfrom . import _ffi_api\nfrom .cascader_options import CascaderOptions\nfrom .plan import Plan\nfrom .proposal import Proposal\nfrom .graph import CascaderGraph, Part\n\n\ndef generate_proposals(\n    graph: CascaderGraph,\n    home_map: Dict[FrozenSet[Part], List[Plan]],\n    options: CascaderOptions,\n) -> List[Proposal]:\n    \"\"\"Generate Pareto optimal Proposals for a CascaderGraph.\n\n    This algorithm takes a top-down dynamic programming approach to determining how\n    to optimally combine Plans into Proposals.\n\n    Parameters\n    ----------\n    graph : CascaderGraph\n        The CascaderGraph to generate Proposals for.\n    home_map : Dict[FrozenSet[Part], List[Plan]]\n        The Tensor homing map defining valid memory homes for Tensors.\n    options : CascaderOptions\n        The configuration options with which to run the generator.\n\n    Returns\n    ------\n    List[Proposal]\n        A list of Pareto optimal Proposals.\n\n    \"\"\"\n    return list(\n        _ffi_api.GenerateProposals(\n            graph,\n            home_map,\n            options,\n        )\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Scheduler for cascader which converts Proposals into Schedules.\"\"\"\nfrom typing import Tuple, List, Dict, DefaultDict\nfrom collections import defaultdict\nimport time\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import tir\nfrom tvm import PoolInfo\nfrom .cascader_options import CascaderOptions\nfrom .graph import CascaderGraph, Part, Tensor, TESubgraph\nfrom .parts import EthosuPart\nfrom .tensor_config import MemoryRegion\nfrom .proposal import Proposal\nfrom .proposal_generator import generate_proposals\nfrom .plan_generator import get_copy_cycles_hint\nfrom .graph import create_cascader_graph\nfrom .device_config import EthosuDeviceConfig\nfrom .logging import Logging\n\n\ndef tile_nd(\n    sch: te.Schedule, tensor: te.Tensor, tile: Tuple[int, ...]\n) -> Tuple[List[tir.IterVar], List[tir.IterVar]]:\n    \"\"\"Scheduling utility to perform N-dimensional tiling.\n\n    Parameters\n    ----------\n    sch : te.Schedule\n        The schedule to apply the tiling to.\n    tensor : te.Tensor\n        The tensor to apply the tiling to.\n    tile : Tuple[int, ...]\n        The N-dimensional tile size\n\n    Returns\n    -------\n    outer_indices : List[tir.IterVar]\n        The outer iteration variables.\n    inner_indices : List[tir.IterVar]\n        The inner iteration variables.\n\n    \"\"\"\n    outer_indices = []\n    inner_indices = []\n    for i, size in enumerate(tile):\n        outer, inner = sch[tensor].split(tensor.op.axis[i], size)\n        outer_indices.append(outer)\n        inner_indices.append(inner)\n\n    sch[tensor].reorder(*outer_indices, *inner_indices)\n    return outer_indices, inner_indices\n\n\ndef stripe_part(\n    part: Part, stripe_shape: Tuple[int, ...], sch: te.Schedule\n) -> Tuple[te.Stage, tir.IterVar]:\n    \"\"\"Apply a striping schedule to the TE subgraph represented by a Part.\"\"\"\n    te_subgraph = part.subgraph\n    te_output_tensor = te_subgraph.output_tensor\n    outer_indices, _ = tile_nd(sch, te_output_tensor, stripe_shape)\n    g = sch.create_group(\n        outputs=te_output_tensor.op.input_tensors,\n        inputs=te_subgraph.input_tensors,\n        include_inputs=False,\n    )\n    g.compute_at(sch[te_output_tensor], outer_indices[-1])\n    for axis in outer_indices:\n        sch[te_output_tensor].unroll(axis)\n\n    return sch[te_output_tensor], outer_indices[-1]\n\n\ndef cascade_part(\n    part: Part, stripe_stage: te.Stage, stripe_axis: tir.IterVar, sch: te.Schedule\n) -> None:\n    \"\"\"Schedule a Part into a cascade indicated by a stripe Stage.\"\"\"\n    te_subgraph = part.subgraph\n    g = sch.create_group(\n        outputs=te_subgraph.output_tensor, inputs=te_subgraph.input_tensors, include_inputs=False\n    )\n    g.compute_at(stripe_stage, stripe_axis)\n\n\ndef update_readers(part: Part, readers: DefaultDict[te.Tensor, List[te.Tensor]]) -> None:\n    \"\"\"\n    Update a dictionary which stores the te.Tensors that need to be read in\n    order to produce a given te.Tensor.\n    \"\"\"\n    visited = set()\n\n    def _visit(tensor):\n        if tensor not in visited and tensor not in part.subgraph.input_tensors:\n            visited.add(tensor)\n            for input_tensor in tensor.op.input_tensors:\n                readers[input_tensor].append(tensor)\n                _visit(input_tensor)\n\n    _visit(part.subgraph.output_tensor)\n\n\ndef apply_proposal(proposal: Proposal, sch: te.Schedule) -> None:\n    \"\"\"Apply a Proposal to a Schedule, converting all the Plans into TE scheduling instructions.\n\n    Note that the Schedule is mutated in-place.\n\n    Parameters\n    ----------\n    proposal : Proposal\n        The Proposal to apply to the Schedule.\n    sch : te.Schedule\n        The Schedule to apply to Proposal to.\n\n    \"\"\"\n    for plan in proposal.plans:\n        for part in plan.part_group:\n            if isinstance(part, EthosuPart):\n                tensor_config = plan.tensor_configs[part.output_tensor]\n                stripe_config = tensor_config.stripe_configs[0]\n                buffer_mode = tensor_config.buffer_mode\n                block_config = part.get_block_config(stripe_config)\n                compute_cycles = part.get_performance_info(\n                    stripe_config, buffer_mode\n                ).compute_cycles\n                iv = part.subgraph.output_tensor.op.axis[0]\n                block_shape = block_config.output_shape\n                if len(block_shape) == 4:\n                    height, width, depth = block_shape[1:]\n                else:\n                    height = block_shape[1]\n                    width = block_shape[3]\n                    depth = block_shape[2] * block_shape[4]\n                sch[part.subgraph.output_tensor].pragma(iv, \"block_config_height\", height)\n                sch[part.subgraph.output_tensor].pragma(iv, \"block_config_width\", width)\n                sch[part.subgraph.output_tensor].pragma(iv, \"block_config_depth\", depth)\n\n                # Attach AttrStmt directly to npu op so it isn't removed by ReplaceOperators\n                npu_op = part.subgraph.output_tensor.op.input_tensors[0].op.input_tensors[0]\n                # Force the pragma to interpret the compute cycles as an int64 value\n                compute_cycles_int64_cast = tvm.tir.IntImm(\"int64\", compute_cycles)\n                sch[npu_op].pragma(\n                    npu_op.op.axis[0], \"compute_cycles_hint\", compute_cycles_int64_cast\n                )\n\n        output_tensor_config = plan.output_config\n        output_tensor = output_tensor_config.tensor\n        output_part = output_tensor.producers[0]\n        if output_part.in_line:\n            continue\n        stripe_config = output_tensor_config.stripe_configs[0]\n        stripe_shape = [int(x) for x in stripe_config.shape]\n        stripe_stage, stripe_axis = stripe_part(output_part, stripe_shape, sch)\n        copy_te_tensors = []\n        compute_cycles_hints = []\n        readers = defaultdict(list)\n        for part in plan.part_group:\n            if part != output_part:\n                cascade_part(part, stripe_stage, stripe_axis, sch)\n\n            update_readers(part, readers)\n            for i, input_tensor in enumerate(part.input_tensors):\n                tensor_config = plan.tensor_configs[input_tensor]\n                if tensor_config.home_region != tensor_config.copy_region:\n                    copy_te_tensors.append(part.subgraph.input_tensors[i])\n\n                    compute_cycles_hint, _ = get_copy_cycles_hint(tensor_config)\n                    compute_cycles_hints.append(compute_cycles_hint)\n\n        for te_tensor, compute_cycles_hint in zip(copy_te_tensors, compute_cycles_hints):\n            copy_stage = sch.cache_read(te_tensor, \"global\", readers[te_tensor])\n            sch[copy_stage].pragma(\n                copy_stage.op.axis[0], \"compute_cycles_hint\", compute_cycles_hint\n            )\n            sch[copy_stage].compute_at(stripe_stage, stripe_axis)\n\n\ndef create_home_map(\n    graph: CascaderGraph,\n    io_region: MemoryRegion,\n    constant_region: MemoryRegion,\n    working_regions: List[MemoryRegion],\n) -> Dict[Tensor, List[MemoryRegion]]:\n    \"\"\"Create a map between Tensors and the MemoryRegions they can be homed in.\"\"\"\n    home_map = {}\n    for tensor in graph.tensor_order:\n        if tensor.is_constant:\n            home_map[tensor] = [constant_region]\n        elif tensor in graph.input_tensors or tensor in graph.output_tensors:\n            home_map[tensor] = [io_region]\n        else:\n            home_map[tensor] = working_regions\n\n    return home_map\n\n\ndef choose_proposal(\n    proposals: List[Proposal], cascade_region: MemoryRegion, select_proposal_idx: int\n):\n    \"\"\"Choose the best performing Proposal that doesn't overflow the cascade region.\"\"\"\n    if select_proposal_idx != -1:\n        # Manually select proposal based on index, take modulus the total number of proposals to\n        # ensure that some proposal is always selected.\n        proposal_choice = proposals[select_proposal_idx % len(proposals)]\n    else:\n        proposal_choice = proposals[0]\n        for proposal in reversed(proposals):\n            if proposal.memory_usage < cascade_region.size:\n                proposal_choice = proposal\n                break\n\n    return proposal_choice\n\n\ndef extract_memory_info(memory_pool: PoolInfo, memory_pressure: int) -> MemoryRegion:\n    \"Create a MemoryRegion based on the info in the memory pool\"\n    size = int(memory_pool.size_hint_bytes - memory_pressure)\n    read_bandwidth = int(memory_pool.read_bandwidth_bytes_per_cycle)\n    write_bandwidth = int(memory_pool.write_bandwidth_bytes_per_cycle)\n\n    for param in (size, read_bandwidth, write_bandwidth):\n        assert param != -1, f\"{param} needs to be specified for the cascader.\"\n\n    name_to_burst_length = {\n        target.kind.name: burst for target, burst in memory_pool.target_burst_bytes.items()\n    }\n\n    try:\n        burst_length = int(name_to_burst_length[\"ethos-u\"])\n    except KeyError:\n        burst_length = 1\n\n    return MemoryRegion(\n        name=memory_pool.pool_name,\n        size=size,\n        read_bandwidth=read_bandwidth,\n        write_bandwidth=write_bandwidth,\n        read_latency=int(memory_pool.read_latency_cycles),\n        write_latency=int(memory_pool.write_latency_cycles),\n        burst_length=burst_length,\n    )\n\n\ndef cascade(\n    sch: te.Schedule,\n    te_graph: TESubgraph,\n    const_dict: Dict[int, np.ndarray],\n    options: CascaderOptions,\n    io_region: MemoryRegion,\n    constant_region: MemoryRegion,\n    working_regions: List[MemoryRegion],\n    device_config: EthosuDeviceConfig,\n) -> None:\n    \"\"\"Schedule a Tensor Expression graph using the technique of 'cascading'.\n\n    'Cascading' is a technique whereby operations are split into smaller\n    dependent tiles ('stripes') which can then execute in an interleaved\n    fashion. This allows for operations to execute together rather than\n    sequentially which can reduce intermediate memory requirements and in\n    certain cases improve performance.\n\n    For more detail on 'cascading' as well as how it is implemented, refer to\n    the RFC here: https://github.com/apache/tvm-rfcs/pull/37.\n\n    Parameters\n    ----------\n    sch : te.Schedule\n        The Schedule to apply the cascading to.\n    te_graph : TESubgraph\n        The Tensor Expression graph from which the Schedule was created.\n    const_dict : Dict[int, np.ndarray]\n        A dictionary mapping input index to constant data if that input is\n        to be a constant.\n    options : CascaderOptions\n        Configuration options for the cascading scheduler.\n    io_region : MemoryRegion\n        The MemoryRegion in which input/output tensors should reside.\n    constant_region : MemoryRegion\n        The MemoryRegion in which constants should reside.\n    working_regions : List[MemoryRegion]\n        The MemoryRegions in which intermediate working tensors can reside. The\n        cascading scheduler will select which MemoryRegion to per tensor.\n    device_config : EthosuDeviceConfig\n        Target device configuration.\n\n    \"\"\"\n    tvmc_options = tvm.transform.PassContext.current().config.get(\"relay.ext.ethos-u.options\", None)\n    log = Logging() if tvmc_options and tvmc_options.dev_cascader_logging else None\n    select_proposal_idx = (\n        int(tvmc_options.dev_select_proposal_idx)\n        if tvmc_options and tvmc_options.dev_select_proposal_idx\n        else -1\n    )\n\n    if log:\n        start = time.time()\n\n    assert options.cascade_region in working_regions\n    # First convert the Tensor Expression graph into a CascaderGraph\n    casc_graph = create_cascader_graph(te_graph, const_dict, device_config)\n    # Then create a mapping between Tensors and their possible memory homes\n    home_map = create_home_map(casc_graph, io_region, constant_region, working_regions)\n    # Generate Proposals for Pareto-optimal ways to cascade the CascaderGraph\n    proposals = generate_proposals(casc_graph, home_map, options)\n    # Select the best Proposal subject to the memory constraints\n    proposal_choice = choose_proposal(proposals, options.cascade_region, select_proposal_idx)\n\n    if log:\n        for idx, proposal in enumerate(proposals):\n            log.add_proposal(idx, proposal.memory_usage, proposal.cycles)\n            if proposal == proposal_choice:\n                log.selected_proposal_idx = idx\n\n        log.cascader_runtime = time.time() - start\n        log.dump_json()\n\n    # Apply the selected Proposal to the Tensor Expression Schedule\n    apply_proposal(proposal_choice, sch)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/stripe_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Stripe config class to hold tensor striping information.\"\"\"\n# pylint: disable=invalid-name\nimport tvm._ffi\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.StripeConfig\")\nclass StripeConfig(Object):\n    \"\"\"StripeConfig class\"\"\"\n\n    def __init__(self, shape, extent, strides, order, stripes, offset):\n        strides = list([float(v) for v in strides])\n        self.__init_handle_by_constructor__(\n            _ffi_api.StripeConfig, shape, extent, strides, order, stripes, offset\n        )\n\n    @property\n    def shape(self):\n        return list(self._shape)\n\n    @property\n    def extent(self):\n        return list(self._extent)\n\n    @property\n    def strides(self):\n        return list([float(v.value) for v in self._strides])\n\n    @property\n    def order(self):\n        return list(self._order)\n\n    @property\n    def stripes(self):\n        return list(self._stripes)\n\n    @property\n    def offset(self):\n        return list(self._offset)\n\n    def __hash__(self):\n        return self._hash\n\n    def __eq__(self, other):\n        return _ffi_api.StripeConfigEqual(self, other)\n\n    def __repr__(self):\n        return (\n            f\"StripeConfig(shape={self.shape}, \"\n            f\"extent={self.extent}, \"\n            f\"strides={self.strides}, \"\n            f\"order={self.order}, \"\n            f\"stripes={self.stripes}, \"\n            f\"offset={self.offset}\"\n        )\n\n\ndef count_stripes(stripe_config: StripeConfig, enable_sliding_window: bool = False):\n    stripe_counts = dict(_ffi_api.CountStripes(stripe_config, enable_sliding_window))\n    # Some code to 'de-TVM' the data types and make them pure Python\n    clean_stripe_counts = dict()\n    for stripe, count in stripe_counts.items():\n        clean_stripe = tuple([int(v) for v in stripe])\n        clean_count = int(count)\n        clean_stripe_counts[clean_stripe] = clean_count\n\n    return clean_stripe_counts\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ethosu/cascader/tensor_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tensor config class to hold tensor scheduling information.\"\"\"\nfrom typing import List, Union\nfrom enum import IntEnum\nimport tvm._ffi\nfrom tvm.contrib.ethosu.cascader.stripe_config import StripeConfig\n\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\nfrom .stripe_config import StripeConfig\nfrom .graph import Tensor, BufferMode\n\n\nclass TensorConfigState(IntEnum):\n    \"\"\"\n    The 'state' of a TensorConfig as used in the Plan generation algorithm.\n\n    BOUNDARY - Should describe a Plan input/output Tensor.\n    INTERIOR - Should describe an intermediate Tensor in a 'closed' Plan.\n\n    \"\"\"\n\n    BOUNDARY = 0\n    INTERIOR = 1\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.MemoryRegion\")\nclass MemoryRegion(Object):\n    \"\"\"\n    MemoryRegion class to store information about device memories.\n\n    Attributes\n    ----------\n    name : str\n        The name of the region.\n    size : int\n        The size of the region.\n    read_bandwidth : int\n        The read bandwidth of the region in bytes per cycle.\n    write_bandwidth : int\n        The write bandwidth of the region in bytes per cycle.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        size: int,\n        read_bandwidth: int,\n        write_bandwidth: int,\n        read_latency: int = 0,\n        write_latency: int = 0,\n        burst_length: int = 1,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.MemoryRegion,\n            name,\n            size,\n            read_bandwidth,\n            write_bandwidth,\n            read_latency,\n            write_latency,\n            burst_length,\n        )\n\n\n@tvm._ffi.register_object(\"contrib.ethosu.cascader.TensorConfig\")\nclass TensorConfig(Object):\n    \"\"\"\n    A class which describes how to realize a Tensor.\n\n    The TensorConfig describes both how a Tensor is scheduled (the order in which it's\n    produced/consumed) and how its allocated in memory (which region it should reside in\n    and whether it should be copied).\n\n    Attributes\n    ----------\n    tensor : Tensor\n        The Tensor the config applies to.\n    home_region : MemoryRegion\n        The region where the tensor is allocated.\n    state : TensorConfigState\n        The state of the TensorConfig.\n\n        The TensorConfigState is only used as part of the Plan generation algorithm. For a Plan\n        to be 'closed' (and therefore not subject to any further merging), all the TensorConfigs\n        that describe Plan input or output Tensors must be in the 'BOUNDARY' state with the rest\n        being 'INTERIOR'. If any of the input or output tensors are described by an 'INTERIOR'\n        TensorConfig, then the Plan is 'open' and should be merged with other 'open' Plans until\n        the result becomes 'closed'.\n    buffer_mode : BufferMode\n        The mode in which the buffer should be realized.\n\n        There are multiple buffering strategies by which a tensor may be realized (computed).\n        These affect the amount of recomputation necessary as well as the size of buffer required\n        to store the tensor. See 'BufferMode' for a description of the allowable buffering modes.\n    stripe_configs : List[StringConfig]\n       The StripeConfigs with which to compute the tensor.\n\n       The StripeConfigs determine the order in which the elements of the tensor should be\n       computed, including potentially computing them multiple times (recompute). Multiple\n       StripeConfigs are used over just a single StripeConfig for the case where the tensor is\n       consumed by two different Parts executing themselves with different StripeConfigs. In this\n       case, there is a StripeConfig per consumer of the tensor.\n    copy_tensor : bool, optional\n        Whether to copy the tensor.\n\n        While a tensor will originally reside in its home region, the TensorConfig may optionally\n        specify that the tensor should be copied (according to the StripeConfigs) into another\n        MemoryRegion. As an example for where this may be used, if a weights tensor initially\n        resides in slow Flash memory then necessarily the home region will be Flash. However, if\n        the weights values are used multiple times by a Part, it may be more performant to choose\n        to copy the weights into a faster memory like SRAM.\n    copy_region : Union[MemoryRegion, None], optional\n        The region to copy the tensor to.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        tensor: Tensor,\n        home_region: MemoryRegion,\n        state: TensorConfigState,\n        buffer_mode: BufferMode,\n        stripe_configs: List[StripeConfig],\n        copy_tensor: bool = False,\n        copy_region: Union[MemoryRegion, None] = None,\n    ):\n        if copy_region is None:\n            copy_region = home_region\n        self.__init_handle_by_constructor__(\n            _ffi_api.TensorConfig,\n            tensor,\n            home_region,\n            state,\n            buffer_mode,\n            stripe_configs,\n            copy_tensor,\n            copy_region,\n        )\n\n    def get_buffer_size(self):\n        \"\"\"\n        The size of the buffer needed for the TensorConfig.\n\n        The size of buffer necessary to store a tensor being produced using the TensorConfig is\n        not necessarily just the size of the tensor. In Plans, a tensor may be being produced and\n        consumed in 'stripes' which are smaller than the full tensor. Therefore, the buffer\n        necessary to store the tensor may only need to be as large as the stripe. The precise size\n        of the buffer will depend both on the BufferMode and StripeConfigs (as well as, of course,\n        the Tensor).\n\n        \"\"\"\n        return _ffi_api.TensorConfigGetBufferSize(self)\n\n    @property\n    def tensor(self):\n        \"\"\"The Tensor the config applies to.\"\"\"\n        return self._tensor\n\n    @property\n    def home_region(self):\n        \"\"\"The region where the tensor is allocated.\"\"\"\n        return self._home_region\n\n    @property\n    def state(self):\n        \"\"\"The state of the TensorConfig.\"\"\"\n        return TensorConfigState(self._state)\n\n    @property\n    def buffer_mode(self):\n        \"\"\"The mode in which the buffer should be realized.\"\"\"\n        return BufferMode(self._buffer_mode)\n\n    @property\n    def stripe_configs(self):\n        \"\"\"The StripeConfigs with which to compute the tensor.\"\"\"\n        return list(self._stripe_configs)\n\n    @property\n    def copy_tensor(self):\n        \"\"\"Whether to copy the tensor.\"\"\"\n        return bool(self._copy_tensor)\n\n    @property\n    def copy_region(self):\n        \"\"\"The region to copy the tensor to.\"\"\"\n        return self._copy_region\n\n    def __hash__(self):\n        return self._hash\n\n    def __eq__(self, other):\n        return _ffi_api.TensorConfigEqual(self, other)\n\n    def __repr__(self):\n        return (\n            f\"TensorConfig(tensor={self.tensor}, \"\n            f\"home_region={self.home_region.name}, \"\n            f\"state={self.state.name}, \"\n            f\"buffer_mode={self.buffer_mode.name}, \"\n            f\"stripe_configs={self.stripe_configs}, \"\n            f\"copy_tensor={self.copy_tensor}, \"\n            f\"copy_region={self.copy_region.name}\"\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/graph_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Minimum graph executor that executes graph containing TVM PackedFunc.\"\"\"\nimport numpy as np\nimport tvm._ffi\n\nfrom tvm.rpc import _ffi_api as _rpc_ffi_api\nfrom tvm.rpc import base as rpc_base\nfrom tvm._ffi.base import string_types\nfrom tvm._ffi.runtime_ctypes import Device\n\n\ndef create(graph_json_str, libmod, device):\n    \"\"\"Create a runtime executor module given a graph and module.\n\n    Parameters\n    ----------\n    graph_json_str : str\n        The graph to be deployed in json format output by json graph.\n        The graph can contain operator(tvm_op) that points to the name\n        of PackedFunc in the libmod.\n\n    libmod : tvm.runtime.Module\n        The module of the corresponding function\n\n    device : Device or list of Device\n        The device to deploy the module. It can be local or remote when there\n        is only one Device. Otherwise, the first device in the list will\n        be used as this purpose. All device should be given for heterogeneous\n        execution.\n\n    Returns\n    -------\n    graph_module : GraphModule\n        Runtime graph module that can be used to execute the graph.\n\n    Note\n    ----\n    See also :py:class:`tvm.contrib.graph_executor.GraphModule`\n    for examples to directly construct a GraphModule from an exported\n    relay compiled library.\n    \"\"\"\n    assert isinstance(graph_json_str, string_types)\n\n    dev, num_rpc_dev, device_type_id = get_device(libmod, device)\n\n    if num_rpc_dev == len(dev):\n        fcreate = dev[0]._rpc_sess.get_function(\"tvm.graph_executor.create\")\n    else:\n        fcreate = tvm._ffi.get_global_func(\"tvm.graph_executor.create\")\n\n    return GraphModule(fcreate(graph_json_str, libmod, *device_type_id))\n\n\ndef get_device(libmod, device):\n    \"\"\"Parse and validate all the device(s).\n\n    Parameters\n    ----------\n    libmod : tvm.runtime.Module\n        The module of the corresponding function\n\n    device : Device or list of Device\n\n    Returns\n    -------\n    device : list of Device\n    num_rpc_dev : Number of rpc devices\n    device_type_id : List of device type and device id\n    \"\"\"\n\n    if isinstance(device, Device):\n        device = [device]\n    elif not isinstance(device, (list, tuple)):\n        raise ValueError(\"dev has to be the type of Device or a list of Device\")\n    for cur_dev in device:\n        if not isinstance(cur_dev, Device):\n            raise ValueError(\"dev has to be the type of Device or a list of Device\")\n\n    # device_type_id[0], device_type_id[1] are used as the primary/fallback\n    # device type and id. All other ones are used as device for\n    # heterogeneous execution.\n    num_rpc_dev = 0\n    device_type_id = []\n    for cur_dev in device:\n        device_type = cur_dev.device_type\n        if device_type >= rpc_base.RPC_SESS_MASK:\n            assert libmod.type_key == \"rpc\"\n            assert _rpc_ffi_api.SessTableIndex(libmod) == cur_dev._rpc_sess._tbl_index\n            num_rpc_dev += 1\n            device_type = cur_dev.device_type % rpc_base.RPC_SESS_MASK\n        device_type_id.append(device_type)\n        device_type_id.append(cur_dev.device_id)\n\n    if 0 < num_rpc_dev < len(device):\n        raise ValueError(\"Either all or none of the devices should be rpc.\")\n    return device, num_rpc_dev, device_type_id\n\n\nclass GraphModule(object):\n    \"\"\"Wrapper runtime module.\n\n    This is a thin wrapper of the underlying TVM module.\n    you can also directly call set_input, run, and get_output\n    of underlying module functions\n\n    Parameters\n    ----------\n    module : tvm.runtime.Module\n        The internal tvm module that holds the actual graph functions.\n\n    Attributes\n    ----------\n    module : tvm.runtime.Module\n        The internal tvm module that holds the actual graph functions.\n\n    Examples\n    --------\n\n    .. code-block:: python\n\n        import tvm\n        from tvm import relay\n        from tvm.contrib import graph_executor\n\n        # build the library using graph executor\n        lib = relay.build(...)\n        lib.export_library(\"compiled_lib.so\")\n        # load it back as a runtime\n        lib: tvm.runtime.Module = tvm.runtime.load_module(\"compiled_lib.so\")\n        # Call the library factory function for default and create\n        # a new runtime.Module, wrap with graph module.\n        gmod = graph_executor.GraphModule(lib[\"default\"](dev))\n        # use the graph module.\n        gmod.set_input(\"x\", data)\n        gmod.run()\n    \"\"\"\n\n    def __init__(self, module):\n        self.module = module\n        self._set_input = module[\"set_input\"]\n        self._run = module[\"run\"]\n        self._get_output = module[\"get_output\"]\n        self._get_input = module[\"get_input\"]\n        self._get_num_outputs = module[\"get_num_outputs\"]\n        self._get_input_index = module[\"get_input_index\"]\n        self._get_input_info = module[\"get_input_info\"]\n        self._get_num_inputs = module[\"get_num_inputs\"]\n        self._load_params = module[\"load_params\"]\n        self._share_params = module[\"share_params\"]\n\n    def set_input(self, key=None, value=None, **params):\n        \"\"\"Set inputs to the module via kwargs\n\n        Parameters\n        ----------\n        key : int or str\n           The input key\n\n        value : the input value.\n           The input key\n\n        params : dict of str to NDArray\n           Additional arguments\n        \"\"\"\n        if key is not None:\n            v = self._get_input(key)\n            if v is None:\n                raise RuntimeError(\"Could not find '%s' in graph's inputs\" % key)\n            v.copyfrom(value)\n\n        if params:\n            # upload big arrays first to avoid memory issue in rpc mode\n            keys = list(params.keys())\n            keys.sort(key=lambda x: -np.prod(params[x].shape))\n            for k in keys:\n                # TODO(zhiics) Skip the weights for submodule in a better way.\n                # We should use ConstLoaderModule for initialization and remove\n                # params from set_input\n                val = self._get_input(k)\n                if val:\n                    self._get_input(k).copyfrom(params[k])\n\n    def run(self, **input_dict):\n        \"\"\"Run forward execution of the graph\n\n        Parameters\n        ----------\n        input_dict: dict of str to NDArray\n            List of input values to be feed to\n        \"\"\"\n        if input_dict:\n            self.set_input(**input_dict)\n        self._run()\n\n    def get_num_outputs(self):\n        \"\"\"Get the number of outputs from the graph\n\n        Returns\n        -------\n        count : int\n            The number of outputs.\n        \"\"\"\n        return self._get_num_outputs()\n\n    def get_num_inputs(self):\n        \"\"\"Get the number of inputs to the graph\n\n        Returns\n        -------\n        count : int\n            The number of inputs.\n        \"\"\"\n        return self._get_num_inputs()\n\n    def get_input(self, index, out=None):\n        \"\"\"Get index-th input to out\n\n        Parameters\n        ----------\n        index : int\n            The input index\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        if out:\n            self._get_input(index).copyto(out)\n            return out\n\n        return self._get_input(index)\n\n    def get_input_index(self, name):\n        \"\"\"Get inputs index via input name.\n\n        Parameters\n        ----------\n        name : str\n           The input key name\n\n        Returns\n        -------\n        index: int\n            The input index. -1 will be returned if the given input name is not found.\n        \"\"\"\n        return self._get_input_index(name)\n\n    def get_input_info(self):\n        \"\"\"Return the 'shape' and 'dtype' dictionaries of the graph.\n\n        .. note::\n            We can't simply get the input tensors from a TVM graph\n            because weight tensors are treated equivalently. Therefore, to\n            find the input tensors we look at the 'arg_nodes' in the graph\n            (which are either weights or inputs) and check which ones don't\n            appear in the params (where the weights are stored). These nodes\n            are therefore inferred to be input tensors.\n\n        Returns\n        -------\n        shape_dict : Map\n            Shape dictionary - {input_name: tuple}.\n        dtype_dict : Map\n            dtype dictionary - {input_name: dtype}.\n        \"\"\"\n        input_info = self._get_input_info()\n        assert \"shape\" in input_info\n        shape_dict = input_info[\"shape\"]\n        assert \"dtype\" in input_info\n        dtype_dict = input_info[\"dtype\"]\n\n        return shape_dict, dtype_dict\n\n    def get_output(self, index, out=None):\n        \"\"\"Get index-th output to out\n\n        Parameters\n        ----------\n        index : int\n            The output index\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        if out:\n            self._get_output(index, out)\n            return out\n\n        return self._get_output(index)\n\n    def debug_get_output(self, node, out):\n        \"\"\"Run graph up to node and get the output to out\n\n        Parameters\n        ----------\n        node : int / str\n            The node index or name\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        raise NotImplementedError(\"Please use debugger.debug_executor as graph_executor instead.\")\n\n    def load_params(self, params_bytes):\n        \"\"\"Load parameters from serialized byte array of parameter dict.\n\n        Parameters\n        ----------\n        params_bytes : bytearray\n            The serialized parameter dict.\n        \"\"\"\n        self._load_params(bytearray(params_bytes))\n\n    def share_params(self, other, params_bytes):\n        \"\"\"Share parameters from pre-existing GraphExecutor instance.\n\n        Parameters\n        ----------\n        other: GraphExecutor\n            The parent GraphExecutor from which this instance should share\n            it's parameters.\n        params_bytes : bytearray\n            The serialized parameter dict (used only for the parameter names).\n        \"\"\"\n        self._share_params(other.module, bytearray(params_bytes))\n\n    def __getitem__(self, key):\n        \"\"\"Get internal module function\n\n        Parameters\n        ----------\n        key : str\n            The key to the module.\n        \"\"\"\n        return self.module[key]\n\n    def benchmark(\n        self,\n        device,\n        func_name=\"run\",\n        repeat=5,\n        number=5,\n        min_repeat_ms=None,\n        limit_zero_time_iterations=100,\n        end_to_end=False,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n        **kwargs,\n    ):\n        \"\"\"Calculate runtime of a function by repeatedly calling it.\n\n        Use this function to get an accurate measurement of the runtime of a function. The function\n        is run multiple times in order to account for variability in measurements, processor speed\n        or other external factors.  Mean, median, standard deviation, min and max runtime are all\n        reported.  On GPUs, CUDA and ROCm specifically, special on-device timers are used so that\n        synchonization and data transfer operations are not counted towards the runtime. This allows\n        for fair comparison of runtimes across different functions and models. The `end_to_end` flag\n        switches this behavior to include data transfer operations in the runtime.\n\n        The benchmarking loop looks approximately like so:\n\n        .. code-block:: python\n\n            for r in range(repeat):\n                time_start = now()\n                for n in range(number):\n                    func_name()\n                time_end = now()\n                total_times.append((time_end - time_start)/number)\n\n\n        Parameters\n        ----------\n        func_name : str\n            The function to benchmark. This is ignored if `end_to_end` is true.\n\n        repeat : int\n            Number of times to run the outer loop of the timing code (see above). The output will\n            contain `repeat` number of datapoints.\n\n        number : int\n            Number of times to run the inner loop of the timing code. This inner loop is run in\n            between the timer starting and stopping. In order to amortize any timing overhead,\n            `number` should be increased when the runtime of the function is small (less than a 1/10\n            of a millisecond).\n\n        min_repeat_ms : Optional[int]\n            If set, the inner loop will be run until it takes longer than `min_repeat_ms`\n            milliseconds. This can be used to ensure that the function is run enough to get an\n            accurate measurement.\n\n        limit_zero_time_iterations : Optional[int]\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        end_to_end : bool\n            If set, include time to transfer input tensors to the device and time to transfer\n            returned tensors in the total runtime. This will give accurate timings for end to end\n            workloads.\n\n        cooldown_interval_ms: Optional[int]\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: Optional[int]\n            The number of repeats before the cooldown is activated.\n\n        kwargs : Dict[str, Object]\n            Named arguments to the function. These are cached before running timing code, so that\n            data transfer costs are not counted in the runtime.\n\n        Returns\n        -------\n        timing_results : BenchmarkResult\n            Runtimes of the function. Use `.mean` to access the mean runtime, use `.results` to\n            access the individual runtimes (in seconds).\n        \"\"\"\n        min_repeat_ms = 0 if min_repeat_ms is None else min_repeat_ms\n        if end_to_end:\n            # Have to unpack kwargs into a single list\n            args = []\n            for k, v in kwargs.items():\n                args.append(k)\n                args.append(v)\n            return self.module.time_evaluator(\n                \"run_from_inputs\",\n                device,\n                repeat=repeat,\n                number=number,\n                min_repeat_ms=min_repeat_ms,\n                limit_zero_time_iterations=limit_zero_time_iterations,\n            )(device.device_type % rpc_base.RPC_SESS_MASK, device.device_id, *args)\n        if kwargs:\n            self.set_input(**kwargs)\n        return self.module.time_evaluator(\n            func_name,\n            device,\n            repeat=repeat,\n            number=number,\n            min_repeat_ms=min_repeat_ms,\n            limit_zero_time_iterations=limit_zero_time_iterations,\n            cooldown_interval_ms=cooldown_interval_ms,\n            repeats_to_cooldown=repeats_to_cooldown,\n        )()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/graph_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Deprecated Python API for GraphExecutor.\"\"\"\n\nimport warnings\n\nfrom . import graph_executor\n\n\ndef create(*args, **kwargs):\n    warnings.warn(\n        \"This function has been moved to tvm.contrib.graph_executor and will be removed \"\n        \"in the next TVM release\"\n    )\n    return graph_executor.create(*args, **kwargs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hexagon APIs.\"\"\"\n\nfrom .tools import *\nfrom .transform import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/_ci_env_check.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Hexagon environment checks for CI usage\n\nThese may be required by either tvm.testing or\ntvm.contrib.hexagon.pytest_plugin, and are separated here to avoid a\ncircular dependency.\n\"\"\"\n\nimport os\n\nimport tvm\n\nANDROID_SERIAL_NUMBER = \"ANDROID_SERIAL_NUMBER\"\nHEXAGON_TOOLCHAIN = \"HEXAGON_TOOLCHAIN\"\n\n\ndef _compile_time_check():\n    \"\"\"Return True if compile-time support for Hexagon is present, otherwise\n    error string.\n\n    Designed for use as a the ``compile_time_check`` argument to\n    `tvm.testing.Feature`.\n    \"\"\"\n    if (\n        tvm.testing.utils._cmake_flag_enabled(\"USE_LLVM\")\n        and tvm.target.codegen.llvm_version_major() < 7\n    ):\n        return \"Hexagon requires LLVM 7 or later\"\n\n    if \"HEXAGON_TOOLCHAIN\" not in os.environ:\n        return f\"Missing environment variable {HEXAGON_TOOLCHAIN}.\"\n\n    return True\n\n\ndef _run_time_check():\n    \"\"\"Return True if run-time support for Hexagon is present, otherwise\n    error string.\n\n    Designed for use as a the ``run_time_check`` argument to\n    `tvm.testing.Feature`.\n    \"\"\"\n    if ANDROID_SERIAL_NUMBER not in os.environ:\n        return f\"Missing environment variable {ANDROID_SERIAL_NUMBER}.\"\n\n    return True\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/build.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines top-level glue functions for building Hexagon.\"\"\"\n\nimport abc\nimport datetime\nimport logging\nimport multiprocessing as mp\nimport os\nimport pathlib\nimport signal\nimport socket\nimport stat\nimport random\nimport string\nimport subprocess\nimport tempfile\nfrom typing import Union\n\nfrom tvm.contrib.hexagon.hexagon_profiler import HexagonProfiler\nfrom ..._ffi import libinfo\nfrom .session import Session\nfrom .tools import HEXAGON_SIMULATOR_NAME\n\nHEXAGON_RPC_LIB_DIR = os.environ.get(\"HEXAGON_RPC_LIB_DIR\")\nANDROID_BASH_FILE_NAME = \"android_bash.sh\"\nHEXAGON_REMOTE_DEVICE_KEY = \"hexagon-dev\"\n\n\ndef _check_call_verbose(cmd, **kwargs) -> None:\n    \"\"\"\n    Similar to subprocess.check_call(cmd), but if the exit code is non-zero\n    then the raised Exception's message provides more detail, including\n    the stdout/stderr provided by the subprocess.\n    \"\"\"\n    try:\n        subprocess.run(\n            cmd,\n            check=True,\n            encoding=\"UTF-8\",\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            **kwargs,\n        )\n    except subprocess.CalledProcessError as err:\n        error_msg = f\"{err}\\nstdout:\\n{err.stdout}\\nstderr:\\n{err.stderr}\"\n        raise Exception(error_msg)\n\n\ndef _get_hexagon_rpc_lib_dir() -> pathlib.Path:\n    \"\"\"Find the Hexagon API binaries.\n\n    Returns\n    -------\n    pathlib.Path :\n        The path to the Hexagon API directory.\n    \"\"\"\n    global HEXAGON_RPC_LIB_DIR\n    if HEXAGON_RPC_LIB_DIR is None:\n        for path in libinfo.find_lib_path():\n            rpc_dir = os.path.join(os.path.dirname(path), \"hexagon_api_output\")\n            if os.path.isdir(rpc_dir):\n                HEXAGON_RPC_LIB_DIR = rpc_dir\n                break\n        else:\n            raise RuntimeError(\"hexagon_api binaries not found, please define HEXAGON_RPC_LIB_DIR\")\n    return pathlib.Path(HEXAGON_RPC_LIB_DIR)\n\n\ndef _get_test_directory_name() -> str:\n    \"\"\"Generate a time-stamped name for use as a test directory name.\"\"\"\n    date_str = datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\")\n    random_str = \"\".join(random.choice(string.ascii_lowercase) for _ in range(10))\n    return f\"{date_str}-{random_str}\"\n\n\nclass HexagonLauncherRPC(metaclass=abc.ABCMeta):\n    \"\"\"Base class for RPC-based launchers.\n\n    This is an abstract class intended to be a base class for specific\n    implementations of RPC launchers. There are two public methods that\n    each launcher needs to implement:\n    - start_server\n    - stop server\n    and two \"private\" methods used in setting up the environment:\n    - _copy_to_remote\n    - _create_remote_directory\n\n    The basic flow of interaction with the launcher is\n        launcher = HexagonLauncher(...)\n        launcher.start_server()\n        with launcher.create_session() as session:\n            # Do something with the session\n        launcher.stop_server()\n\n    Parameters\n    ----------\n    rpc_info : dict\n        Description of the RPC setup. Recognized keys:\n            \"rpc_tracker_host\" : str    name of the host running the tracker (default \"0.0.0.0\")\n            \"rpc_tracker_port\" : int    port number of the tracker (default: 9190)\n            \"rpc_server_port\"  : int    port number for the RPC server to use (default 7070)\n            \"workspace_base\"   : str    name of base test directory (default \".\")\n    workspace : str or patlib.Path\n        The server's remote working directory. If this directory does not\n        exist, it will be created. If it does exist, the servermust have\n        write permissions to it.\n        If this parameter is None, a subdirectory in the `workspace_base`\n        directory will be created, otherwise the `workspace_base` is not\n        used.\n    \"\"\"\n\n    def __init__(\n        self, rpc_info: dict, workspace: Union[str, pathlib.Path] = None, serial_number: str = None\n    ):\n        self._rpc_info = {\n            \"rpc_tracker_host\": \"0.0.0.0\",\n            \"rpc_tracker_port\": 9190,\n            \"rpc_server_port\": 7070,\n            \"workspace_base\": \".\",\n        }\n        self._rpc_info.update(rpc_info)\n        self._workspace = self._create_workspace(workspace)\n        self._serial_number = serial_number\n\n    @abc.abstractmethod\n    def start_server(self):\n        \"\"\"Start the RPC server\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def stop_server(self):\n        \"\"\"Stop the RPC server\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def cleanup_directory(self):\n        \"\"\"Cleanup working directory\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def _copy_to_remote(\n        self, local_path: Union[str, pathlib.Path], remote_path: Union[str, pathlib.Path]\n    ):\n        \"\"\"Copy a local file to a remote location.\n\n        Parameters\n        ----------\n        local_path : str or pathlib.Path\n            Path to the local file.\n        remote_path : str or pathlib.Path\n            Path to the remote file (to be written).\n        \"\"\"\n        ...\n\n    @abc.abstractmethod\n    def _create_remote_directory(self, remote_path: Union[str, pathlib.Path]) -> pathlib.Path:\n        \"\"\"Create a directory in the remote location.\n\n        Parameters\n        ----------\n        remote_path : str or pathlib.Path\n            Name of the directory to be created.\n\n        Returns\n        -------\n        pathlib.Path :\n            Absolute path of the remote workspace.\n        \"\"\"\n        ...\n\n    def _create_workspace(self, workspace: Union[str, pathlib.Path]) -> pathlib.Path:\n        \"\"\"Create a working directory for the server.\n\n        Parameters\n        ----------\n        workspace : str or pathlib.Path or NoneType\n            Name of the directory to create. If None, a new name is constructed\n            using workspace_base.\n\n        Returns\n        -------\n        pathlib.Path :\n            Created workspace.\n        \"\"\"\n        if not workspace:\n            base_dir = self._rpc_info[\"workspace_base\"]\n            workspace = os.path.join(base_dir, _get_test_directory_name())\n        return self._create_remote_directory(workspace)\n\n    @abc.abstractmethod\n    def get_profile_output(\n        self,\n        hex_profiler: HexagonProfiler,\n        session: Session,\n    ) -> str:\n        \"\"\"Extract profile output.\n\n        Parameters\n        ----------\n        hex_profiler : HexagonProfiler\n            HexagonProfiler object that contains the profiling related information.\n        session : Session\n            Remote session. The session must be established (via __enter__)\n            prior to calling this function.\n\n        Returns\n        -------\n        profile_data : str\n            Path of the profiling data file\n        \"\"\"\n        ...\n\n    def create_session(self, session_name: str = \"hexagon-rpc\") -> Session:\n        \"\"\"Create an RPC session.\n\n        Parameters\n        ----------\n        session_name : str\n            RPC session name.\n\n        Returns\n        -------\n        Session :\n            The session object.\n        \"\"\"\n        hexagon_session_kw = {\n            \"remote_workspace\": self._workspace,\n            \"rpc_tracker\": (self._rpc_info[\"rpc_tracker_host\"], self._rpc_info[\"rpc_tracker_port\"]),\n            \"rpc_server_key\": self._rpc_info[\"device_key\"],\n            \"serial_number\": self._serial_number,\n            \"session_name\": session_name,\n        }\n        return Session(**hexagon_session_kw)\n\n    def is_simulator(self):\n        return self._serial_number == HEXAGON_SIMULATOR_NAME\n\n\nclass HexagonLauncherAndroid(HexagonLauncherRPC):\n    \"\"\"Hexagon Launcher for Android.\"\"\"\n\n    ANDROID_HEXAGON_TEST_BASE_DIR = pathlib.Path(\"/data/local/tmp/hexagon_test\")\n    ANDROID_HEXAGON_RPC_FILES = [\n        \"libhexagon_rpc_skel.so\",\n        \"libtvm_runtime.so\",\n        \"tvm_rpc_android\",\n    ]\n\n    def __init__(\n        self,\n        serial_number: str,\n        rpc_info: dict,\n        workspace: Union[str, pathlib.Path] = None,\n        hexagon_debug: bool = False,\n        clear_logcat: bool = False,\n        sysmon_profile: bool = False,\n        farf_config: str = \"0x1e\",\n    ):\n        \"\"\"Configure a new HexagonLauncherAndroid\n\n        Parameters\n        ----------\n        serial_number : str\n            Android device serial number.\n        rpc_info : dict\n            Same as in HexagonLauncherRPC, except if the \"workspace_base\"\n            key is not present or is None, ANDROID_HEXAGON_TEST_BASE_DIR\n            is used as the base directory.\n        workspace : str or pathlib.Path, optional\n            Test workspace path on android.\n        hexagon_debug: bool, optional\n            Should the server run debug options.\n        clear_logcat: bool, optional\n            Should the server clear logcat before running.\n        sysmon_profile: bool, optional\n            Should the server run sysmon profiler in the background.\n        farf_config: str, optional\n            Configuration string for runtime log level filtering.\n            Use farf_config_from_python_log_level to generate a bitmask\n            string from a Python logging level (e.g., logging.INFO)\n        \"\"\"\n        if not rpc_info.get(\"workspace_base\"):\n            rpc_info[\"workspace_base\"] = self.ANDROID_HEXAGON_TEST_BASE_DIR\n        self._serial_number = serial_number\n        assert self._serial_number != \"\", \"Android serial number is not set.\"\n\n        adb_socket = rpc_info[\"adb_server_socket\"] if rpc_info[\"adb_server_socket\"] else \"tcp:5037\"\n        self._adb_device_sub_cmd = [\"adb\", \"-L\", adb_socket, \"-s\", self._serial_number]\n        self.forwarded_ports_ = []\n        self._hexagon_debug = hexagon_debug\n        self._clear_logcat = clear_logcat\n        self._sysmon_profile = sysmon_profile\n        self._sysmon_process = None\n        self._farf_config = farf_config\n        rpc_info[\"device_key\"] = HEXAGON_REMOTE_DEVICE_KEY + \".\" + self._serial_number\n\n        super(HexagonLauncherAndroid, self).__init__(rpc_info, workspace, self._serial_number)\n\n    def _copy_to_remote(\n        self, local_path: Union[str, pathlib.Path], remote_path: Union[str, pathlib.Path]\n    ):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n\n        _check_call_verbose(self._adb_device_sub_cmd + [\"push\", str(local_path), str(remote_path)])\n\n    def _create_remote_directory(self, remote_path: Union[str, pathlib.Path]) -> pathlib.Path:\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        _check_call_verbose(self._adb_device_sub_cmd + [\"shell\", \"mkdir\", \"-p\", str(remote_path)])\n        return pathlib.Path(remote_path)\n\n    def _copy_binaries(self):\n        \"\"\"Upload Android server binaries.\"\"\"\n\n        # Create bash script\n        with open(_get_hexagon_rpc_lib_dir() / f\"{ANDROID_BASH_FILE_NAME}.template\", \"r\") as src_f:\n            with tempfile.TemporaryDirectory() as temp_dir:\n                android_bash_script_path = pathlib.Path(temp_dir) / ANDROID_BASH_FILE_NAME\n                with open(android_bash_script_path, \"w\") as dest_f:\n                    for line in src_f.readlines():\n                        if \"<RPC_TRACKER_HOST>\" in line:\n                            line = line.replace(\n                                \"<RPC_TRACKER_HOST>\", str(self._rpc_info[\"rpc_tracker_host\"])\n                            )\n                        if \"<RPC_TRACKER_PORT>\" in line:\n                            line = line.replace(\n                                \"<RPC_TRACKER_PORT>\", str(self._rpc_info[\"rpc_tracker_port\"])\n                            )\n                        if \"<HEXAGON_REMOTE_DEVICE_KEY>\" in line:\n                            line = line.replace(\n                                \"<HEXAGON_REMOTE_DEVICE_KEY>\", self._rpc_info[\"device_key\"]\n                            )\n                        if \"<RPC_SERVER_PORT>\" in line:\n                            line = line.replace(\n                                \"<RPC_SERVER_PORT>\", str(self._rpc_info[\"rpc_server_port\"])\n                            )\n                        if \"<FARF_CONFIG>\" in line:\n                            line = line.replace(\"<FARF_CONFIG>\", str(self._farf_config))\n                        dest_f.write(line)\n\n                # Make shell script executable\n                android_bash_stat = os.stat(android_bash_script_path)\n                os.chmod(android_bash_script_path, android_bash_stat.st_mode | stat.S_IEXEC)\n                self._copy_to_remote(\n                    android_bash_script_path, self._workspace / android_bash_script_path.name\n                )\n\n        # Push files\n        lib_dir = _get_hexagon_rpc_lib_dir()\n        for item in self.ANDROID_HEXAGON_RPC_FILES:\n            self._copy_to_remote(lib_dir / item, self._workspace / item)\n\n    def _process_forwarded_ports(self):\n        forwarded_ports = subprocess.check_output(self._adb_device_sub_cmd + [\"forward\", \"--list\"])\n        existing_forwards = []\n        for forward in str(forwarded_ports).split(\"\\\\n\"):\n            entry = forward.split()\n            if len(entry) == 3:\n                _, local, _ = entry\n                existing_forwards.append(int(local.strip(\"tcp:\")))\n        return existing_forwards\n\n    def _forward_ports(self, rpc_server_port, existing_forwards):\n        # Enable port forward for RPC server. We forward the first ten open ports\n        # starting from the rpc_server_port\n        port = rpc_server_port\n        while len(self.forwarded_ports_) < 10:\n            if port not in existing_forwards and not _is_port_in_use(port):\n                _check_call_verbose(\n                    self._adb_device_sub_cmd + [\"forward\", f\"tcp:{port}\", f\"tcp:{port}\"]\n                )\n                self.forwarded_ports_.append(port)\n            port += 1\n\n    def _reverse_ports(self, rpc_tracker_port):\n        _check_call_verbose(\n            self._adb_device_sub_cmd\n            + [\"reverse\", f\"tcp:{rpc_tracker_port}\", f\"tcp:{rpc_tracker_port}\"]\n        )\n\n    def _run_server_script(self):\n        \"\"\"Setup the ADB connection and execute the server script.\"\"\"\n\n        # Collect any existing adb port forwarding to avoid duplication\n        # with another running process\n        existing_forwards = self._process_forwarded_ports()\n        # Enable port reverse for RPC tracker\n        rpc_tracker_port = self._rpc_info[\"rpc_tracker_port\"]\n        rpc_server_port = self._rpc_info[\"rpc_server_port\"]\n\n        self._reverse_ports(rpc_tracker_port)\n        self._forward_ports(rpc_server_port, existing_forwards)\n\n        # Run server and connect to tracker\n        subprocess.Popen(\n            self._adb_device_sub_cmd\n            + [\"shell\", f\"cd {self._workspace} && ./{ANDROID_BASH_FILE_NAME}\"],\n            stdout=subprocess.PIPE,\n            stdin=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n\n    def _cleanup_port_forwarding(self):\n        # Removed pre-defined forward/reverse rules\n        rpc_tracker_port = self._rpc_info[\"rpc_tracker_port\"]\n        _check_call_verbose(\n            self._adb_device_sub_cmd + [\"reverse\", \"--remove\", f\"tcp:{rpc_tracker_port}\"]\n        )\n        for port in self.forwarded_ports_:\n            _check_call_verbose(self._adb_device_sub_cmd + [\"forward\", \"--remove\", f\"tcp:{port}\"])\n\n    def _terminate_remote(self):\n        # Send interupt to main and child processes\n        subprocess.Popen(\n            self._adb_device_sub_cmd\n            + [\"shell\", f\"pkill -l sigint -P `cat {self._workspace}/rpc_pid.txt`\"]\n        )\n        subprocess.Popen(\n            self._adb_device_sub_cmd\n            + [\"shell\", f\"kill -s sigint `cat {self._workspace}/rpc_pid.txt`\"]\n        )\n        # Wait for processes to destruct cleanly after receiving the intrupt\n        subprocess.Popen(self._adb_device_sub_cmd + [\"shell\", \"sleep\", \"0.1s\"])\n        # Kill process children\n        subprocess.Popen(\n            self._adb_device_sub_cmd + [\"shell\", f\"pkill -P `cat {self._workspace}/rpc_pid.txt`\"]\n        )\n        # Kill main process\n        subprocess.Popen(\n            self._adb_device_sub_cmd + [\"shell\", f\"kill `cat {self._workspace}/rpc_pid.txt`\"]\n        )\n\n    def cleanup_directory(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        subprocess.Popen(self._adb_device_sub_cmd + [\"shell\", f\"rm -rf {self._workspace}\"])\n\n    def _start_sysmon(self):\n        hexagon_sdk_root = os.environ.get(\"HEXAGON_SDK_ROOT\", default=\"\")\n        subprocess.call(\n            self._adb_device_sub_cmd\n            + [\"push\", f\"{hexagon_sdk_root}/tools/utils/sysmon/sysMonApp\", \"/data/local/tmp/\"]\n        )\n        sysmon_process = subprocess.Popen(\n            self._adb_device_sub_cmd\n            + [\n                \"shell\",\n                \"/data/local/tmp/sysMonApp profiler --debugLevel 0 --samplePeriod 1 --q6 cdsp\",\n            ],\n            stdin=subprocess.PIPE,\n        )\n        return sysmon_process\n\n    def _stop_sysmon(self):\n        if self._sysmon_process is not None:\n            self._sysmon_process.communicate(input=b\"\\n\")\n            self._sysmon_process = None\n\n    def _retrieve_sysmon(self):\n        pathlib.Path(\"./sysmon_output/\").mkdir(exist_ok=True)\n        subprocess.call(\n            self._adb_device_sub_cmd + [\"pull\", \"/sdcard/sysmon_cdsp.bin\", \"./sysmon_output/\"]\n        )\n        subprocess.call(self._adb_device_sub_cmd + [\"root\"])\n        hexagon_sdk_root = os.environ.get(\"HEXAGON_SDK_ROOT\", default=\"\")\n        subprocess.call(\n            f\"{hexagon_sdk_root}/tools/utils/sysmon/parser_linux_v2/HTML_Parser/sysmon_parser \"\n            + \"./sysmon_output/sysmon_cdsp.bin --outdir ./sysmon_output/\",\n            shell=True,\n        )\n\n    def _clear_debug_logs(self):\n        subprocess.call(self._adb_device_sub_cmd + [\"shell\", \"logcat\", \"-c\"])\n\n    def _retrieve_debug_logs(self):\n        run_start_time = subprocess.check_output(\n            self._adb_device_sub_cmd\n            + [\n                \"shell\",\n                \"stat\",\n                f\"{self._workspace}/android_bash.sh | grep 'Change' | grep -oe '[0-9].*'\",\n            ]\n        )\n        run_start_time = run_start_time[:-1].decode(\"UTF-8\")\n        subprocess.call(\n            self._adb_device_sub_cmd\n            + [\n                \"shell\",\n                \"logcat\",\n                \"-t\",\n                f'\"{run_start_time}\"',\n                \"-f\",\n                f\"{self._workspace}/logcat.txt\",\n            ]\n        )\n        subprocess.call(self._adb_device_sub_cmd + [\"pull\", f\"{self._workspace}/logcat.txt\", \".\"])\n\n    def _print_cdsp_logs(self):\n        crash_count = 0\n        context_lines = 0\n        print_buffer = \"\"\n        try:\n            with open(\"./logcat.txt\", \"r\") as f:\n                for line in f:\n                    if \"Process on cDSP CRASHED\" in line:\n                        if crash_count <= 5:\n                            print(print_buffer, \"\\n\")\n                        context_lines = 40\n                        print_buffer = \"\"\n                        crash_count += 1\n                    if context_lines > 0 and \"platform_qdi_driver\" in line:\n                        context_lines -= 1\n                        print_buffer += line[80:]\n\n            if crash_count <= 5:\n                print(print_buffer, \"\\n\")\n\n            print(\n                f\"There were {crash_count} crashes on the cDSP during execution... \"\n                + \"Crash printing is limited to the first 5.\"\n            )\n        except FileNotFoundError:\n            print(\"Unable to parse logcat file.\")\n\n    def start_server(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        self._copy_binaries()\n        if self._sysmon_profile:\n            self._sysmon_process = self._start_sysmon()\n        self._run_server_script()\n        if self._clear_logcat:\n            self._clear_debug_logs()\n\n    def stop_server(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        if self._sysmon_profile and self._sysmon_process is not None:\n            self._stop_sysmon()\n            self._retrieve_sysmon()\n        if self._hexagon_debug:\n            self._retrieve_debug_logs()\n            self._print_cdsp_logs()\n        self._cleanup_port_forwarding()\n        self._terminate_remote()\n        if not self._hexagon_debug:\n            self.cleanup_directory()\n\n    def get_profile_output(\n        self,\n        hex_profiler: HexagonProfiler,\n        session: Session,\n    ):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        profile_data = \"\"\n        if hex_profiler.is_lwp_enabled():\n            temp_dir = hex_profiler.get_temp_dir()\n            remote_path = hex_profiler.get_remote_path()\n            if not temp_dir:\n                raise RuntimeError(\"tempdir not passed\")\n            fname = \"lwp.json\"\n            out_path = os.path.join(remote_path, fname)\n            profile_data = temp_dir.relpath(fname)\n            ret = session.get_profile_output(hex_profiler.get_mode(), fname)\n            if ret:\n                subprocess.check_call(self._adb_device_sub_cmd + [\"pull\", out_path, profile_data])\n            else:\n                raise RuntimeError(\"Error generating profile output\")\n        elif hex_profiler.profiling_mode == \"etm\":\n            hex_profiler.pull_files_for_etm_processing(self._workspace)\n        else:\n            raise RuntimeError(\"Profiling not enabled\")\n        return profile_data\n\n\nclass HexagonLauncherSimulator(HexagonLauncherRPC):\n    \"\"\"Hexagon Launcher for Hexagon simulator.\"\"\"\n\n    SIMULATOR_HEXAGON_RPC_FILES = [\"tvm_rpc_x86\", \"libhexagon_rpc_sim.so\"]\n\n    def __init__(self, rpc_info: dict, workspace: Union[str, pathlib.Path] = None):\n        \"\"\"Configure a new HexagonLauncherSimulator\n\n        Parameters are same as for HexagonLauncherRPC.\n        \"\"\"\n\n        self._toolchain = os.environ.get(\"HEXAGON_TOOLCHAIN\")\n        if not self._toolchain:\n            raise RuntimeError(\"Please set HEXAGON_TOOLCHAIN env variable\")\n        self._serial_number = HEXAGON_SIMULATOR_NAME\n\n        super(HexagonLauncherSimulator, self).__init__(rpc_info, workspace, self._serial_number)\n\n    def _copy_to_remote(\n        self, local_path: Union[str, pathlib.Path], remote_path: Union[str, pathlib.Path]\n    ):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        _check_call_verbose([\"cp\", str(local_path), str(remote_path)])\n\n    def _create_remote_directory(self, remote_path: Union[str, pathlib.Path]) -> pathlib.Path:\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        _check_call_verbose([\"mkdir\", \"-p\", str(remote_path)])\n        return pathlib.Path(os.path.abspath(remote_path))\n\n    def _copy_libcxx(self, dest_dir: Union[str, pathlib.Path]):\n        \"\"\"Copy libc++ libraries to the remote workspace.\"\"\"\n        # Copy the v68 versions, since we don't have target information.\n        # The v68 ones should work everywhere on v68+.\n        lib_dir = os.path.join(self._toolchain, \"target/hexagon/lib/v68/G0/pic\")\n\n        libcxx_files = []\n        for entry in os.scandir(lib_dir):\n            if entry.is_dir() or entry.name.find(\".so\") == -1:\n                continue\n            if entry.name.startswith(\"libc++\"):\n                libcxx_files.append(entry.name)\n\n        # Use tar to preserve the symbolic links. Libc++ libraries use the\n        # typical .so versioning, so that libc++.so may be a symlink to\n        # something else. Also, shared libraries using libc++ could be\n        # directly linked against some version, e.g. libc++.so.1, so make\n        # sure that all files are copied over. The preservation of symbolic\n        # links is to save disk space.\n        tar_in = f\"tar -cf - -C {lib_dir} \" + \" \".join(libcxx_files)\n        tar_out = f\"tar -xf - -C {str(dest_dir)}\"\n        _check_call_verbose(tar_in + \" | \" + tar_out, shell=True)\n\n    def start_server(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        # Copy binaries\n        lib_dir = _get_hexagon_rpc_lib_dir()\n        for item in self.SIMULATOR_HEXAGON_RPC_FILES:\n            self._copy_to_remote(lib_dir / item, self._workspace / item)\n        # Copy libc++ from the toolchain to the workspace\n        self._copy_libcxx(self._workspace)\n        self._rpc_info[\"device_key\"] = HEXAGON_REMOTE_DEVICE_KEY + \".\" + str(os.getpid())\n\n        rpc_tracker_host = self._rpc_info[\"rpc_tracker_host\"]\n        rpc_tracker_port = self._rpc_info[\"rpc_tracker_port\"]\n        rpc_server_port = self._rpc_info[\"rpc_server_port\"]\n        device_key = self._rpc_info[\"device_key\"]\n        server_exe = os.path.join(\".\", \"tvm_rpc_x86\")\n\n        args = [\n            \"server\",\n            f\"--tracker={rpc_tracker_host}:{rpc_tracker_port}\",\n            f\"--port={rpc_server_port}\",\n            f\"--key={device_key}\",\n            \"--timeout=0\",\n        ]\n\n        # pylint: disable=unused-argument\n        def _terminate_handler(self, signum, *rest):\n            # Terminate the Popen'ed (sub)process.\n            os.kill(self._subprocess_pid, signal.SIGTERM)\n\n        def _start(self):\n            # This function will be running in a new process. It will start the RPC\n            # (x86) server as a subprocess of itself.\n            log_out = self._workspace / \"stdout.txt\"\n            log_err = self._workspace / \"stderr.txt\"\n            # Intercept the TERM signal so we can also terminate the subprocess.\n            signal.signal(signal.SIGTERM, lambda *a: _terminate_handler(self, *a))\n\n            with open(log_out, \"w\") as out, open(log_err, \"w\") as err:\n                p = subprocess.Popen(\n                    [server_exe, *args], stdout=out, stderr=err, cwd=self._workspace\n                )\n                # Insert the pid of the subprocess in the self object.\n                self._subprocess_pid = p.pid\n                p.wait()\n\n        self._server_process = mp.Process(target=lambda *a: _start(self, *a))\n        self._server_process.start()\n\n    def cleanup_directory(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n\n    def stop_server(self):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        self._server_process.terminate()\n\n    def get_profile_output(\n        self,\n        hex_profiler: HexagonProfiler,\n        session: Session,\n    ):\n        \"\"\"Abstract method implementation. See description in HexagonLauncherRPC.\"\"\"\n        profile_data = \"\"\n        if hex_profiler.is_lwp_enabled():\n            fname = \"lwp.json\"\n            profile_data = f\"{self._workspace}/{fname}\"\n            ret = session.get_profile_output(hex_profiler.get_mode(), fname)\n            if not ret:\n                raise RuntimeError(\"Error generating profile output\")\n        elif hex_profiler.profiling_mode == \"etm\":\n            raise RuntimeError(\"ETM Profiling not supported on the simulator\")\n        else:\n            raise RuntimeError(\"Profiling not enabled\")\n\n        return profile_data\n\n\n# https://stackoverflow.com/a/52872579/2689797\ndef _is_port_in_use(port: int) -> bool:\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        return s.connect_ex((\"localhost\", port)) == 0\n\n\ndef farf_config_from_python_log_level(level) -> str:\n    \"\"\"Generates a FARF configuration string enabling logging at the specified level\n\n    Parameters\n    ----------\n    level : str or int\n        Minimum level to log at. Must be a known Python logging level or string\n        (e.g., logging.INFO or \"INFO\")\n    \"\"\"\n\n    # Runtime log levels can be selectively enabled by computing a bitmask\n    # corresponding to the levels you want to enable. These get forwarded to\n    # logcat by the DSP RPC daemon. The bits for each level are:\n\n    # 0x01 - Hexagon LOW / TVM DEBUG / Python DEBUG\n    # 0x02 - Hexagon MEDIUM / TVM INFO / Python INFO\n    # 0x04 - Hexagon HIGH / TVM WARN / Python WARNING\n    # 0x08 - Hexagon ERROR / TVM ERROR / Python ERROR\n    # 0x10 - Hexagon FATAL / TVM FATAL / Python CRITICAL\n\n    # Runtime logging can also be filtered on filenames by appending a\n    # comma-separated list of filenames. For more information, see\n    # the Hexagon SDK documentation.\n\n    if level in (logging.DEBUG, \"DEBUG\"):\n        return \"0x1F\"\n    if level in (logging.INFO, \"INFO\"):\n        return \"0x1E\"\n    if level in (logging.WARNING, \"WARNING\"):\n        return \"0x1C\"\n    if level in (logging.ERROR, \"ERROR\"):\n        return \"0x18\"\n    if level in (logging.CRITICAL, \"CRITICAL\"):\n        return \"0x10\"\n\n    raise ValueError(\"Argument must be a known Python logging level or string\")\n\n\n# pylint: disable=invalid-name\ndef HexagonLauncher(\n    serial_number: str,\n    rpc_info: dict,\n    workspace: Union[str, pathlib.Path] = None,\n    hexagon_debug: bool = False,\n    clear_logcat: bool = False,\n    sysmon_profile: bool = False,\n    farf_config: str = farf_config_from_python_log_level(logging.INFO),\n):\n    \"\"\"Creates a HexagonLauncher\"\"\"\n    if serial_number == HEXAGON_SIMULATOR_NAME:\n        return HexagonLauncherSimulator(rpc_info, workspace)\n    return HexagonLauncherAndroid(\n        serial_number, rpc_info, workspace, hexagon_debug, clear_logcat, sysmon_profile, farf_config\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/hexagon_profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Define HexagonProfiler class to enable profiling for Hexagon\"\"\"\n\nimport os\nimport subprocess\nimport typing\nfrom tvm.ir.transform import PassContext\nfrom tvm.contrib.hexagon.profiling.process_lwp_data import process_lwp_output\nfrom tvm.relay.backend.executor_factory import ExecutorFactoryModule\nfrom tvm.driver.build_module import OperatorModule\nfrom tvm.contrib import utils\n\n\nclass HexagonProfiler:\n    \"\"\"Hexagon Profiler\"\"\"\n\n    def __init__(\n        self,\n        dso_binary: str,\n        module: typing.Union[ExecutorFactoryModule, OperatorModule],\n        hexagon_server_process,\n        enable_debug,\n    ):\n        \"\"\"Configure HexagonProfiler\"\"\"\n        # Save test .so to process profiling data\n        self._temp_dir = utils.tempdir(keep_for_debug=enable_debug)\n        self._dso_binary_path = self._temp_dir.relpath(dso_binary)\n        if isinstance(module, OperatorModule):\n            module.save(self._dso_binary_path)\n        else:\n            module.get_lib().save(self._dso_binary_path)\n\n        self._android_serial_number = os.environ.get(\"ANDROID_SERIAL_NUMBER\")\n        self._remote_path = \"\"\n        self._logcat_path = \"\"\n\n        self._profiling_mode = None\n        config = PassContext.current().config\n        if self._android_serial_number is None:\n            raise RuntimeError(\"ANDROID_SERIAL_NUMBER must be set for profiling\")\n\n        if (\"tir.instrument_lwp\", True) in config.items():\n            # Set profiling mode\n            self._profiling_mode = \"lwp\"\n\n            if self._android_serial_number != \"simulator\":\n                # Clear the logcat buffer and create a child process to redirect logcat output\n                # into a file.\n                launcher = hexagon_server_process[\"launcher\"]\n                subprocess.check_call(launcher._adb_device_sub_cmd + [\"logcat\", \"-c\"])\n                self._logcat_path = self._temp_dir.relpath(\"logcat.log\")\n                self._fo = open(self._logcat_path, \"w\")\n                self._proc = subprocess.Popen(\n                    launcher._adb_device_sub_cmd + [\"logcat\"], stdout=self._fo\n                )\n\n                # Get the remote workspace on the device from where the lwp data needs to be copied.\n                self._remote_path = launcher._workspace\n\n        if self._profiling_mode is None:\n            raise RuntimeError(\"Profiling mode was not set or was not a valid one.\")\n\n    def get_mode(self):\n        return self._profiling_mode\n\n    def is_lwp_enabled(self):\n        return self._profiling_mode == \"lwp\"\n\n    def get_temp_dir(self):\n        return self._temp_dir\n\n    def get_remote_path(self):\n        return self._remote_path\n\n    def get_profile_output(self, hexagon_launcher, hexagon_session):\n        \"\"\"Get runtime profiling data\"\"\"\n        prof_out = hexagon_launcher.get_profile_output(self, hexagon_session)\n\n        print(\"lwp json can be found at -- \", prof_out)\n\n        # Process lightweight profiling output into an easily readable csv file\n        # The post-processing requires following parameters:\n        # 1) Path of the binary file\n        # 2) android_serial_number\n        # 3) Path of the lwp json file (lwp.json) which gets created in the current directory\n        # 4) Path to the run log depending on the environment:\n        #    a) For on-device runs:\n        #       Use logcat output as the run log\n        #    b) For simulator runs:\n        #       Use \"stdout.txt\" as the run log. There is no need to specify the full path to\n        #       \"stdout.txt\" as it will be inferred based on 'prof_out' location.\n        # 5) lwp processed output file -  \"lwp.csv\"\n        #\n        lwp_csv = self._temp_dir.relpath(\"lwp.csv\")\n        if self._android_serial_number == \"simulator\":\n            process_lwp_output(\n                self._dso_binary_path, self._android_serial_number, prof_out, \"stdout.txt\", lwp_csv\n            )\n        else:\n            # For on-device run\n            self._proc.kill()  # End the child process for logcat\n            self._fo.close()\n            if os.path.exists(self._logcat_path):\n                process_lwp_output(\n                    self._dso_binary_path,\n                    self._android_serial_number,\n                    prof_out,\n                    self._logcat_path,\n                    lwp_csv,\n                )\n            else:\n                raise RuntimeError(\"Error processing lwp output - missing logcat file\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/meta_schedule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta schedule tuning utilities for Hexagon.\"\"\"\nimport os\nimport tempfile\nfrom typing import Callable, List, Optional\nfrom tvm.contrib.popen_pool import PopenPoolExecutor\nfrom tvm.meta_schedule.utils import cpu_count, derived_object\nfrom tvm.meta_schedule.builder import LocalBuilder\nfrom tvm.meta_schedule.runner import (\n    EvaluatorConfig,\n    RunnerInput,\n    RunnerFuture,\n    PyRunner,\n)\nfrom tvm.meta_schedule.runner.rpc_runner import (\n    default_alloc_argument,\n    default_run_evaluator,\n    RPCRunnerFuture,\n)\n\nfrom .build import HexagonLauncherRPC\nfrom .tools import export_module\n\n\n@derived_object\nclass HexagonRPCRunner(PyRunner):\n    \"\"\"RPCRunner for Hexagon. See the documentation of RPCRunner for more details.\"\"\"\n\n    def __init__(\n        self,\n        hexagon_launcher: HexagonLauncherRPC,\n        evaluator_config: Optional[EvaluatorConfig] = None,\n        cooldown_sec: float = 0.0,\n        alloc_repeat: int = 1,\n        max_workers: Optional[int] = None,\n        initializer: Optional[Callable[[], None]] = None,\n    ):\n        \"\"\"\n        Parameters\n        ----------\n        hexagon_launcher : HexagonLauncherRPC\n            The RPC launcher for Hexagon. It is needed for creating hexagon.Session\n            object inside the worker function.\n        evaluator_config: EvaluatorConfig\n            The evaluator configuration.\n        cooldown_sec: float\n            The cooldown in seconds.\n        alloc_repeat: int\n            The number of times to random fill the allocation.\n        max_workers: Optional[int] = None\n            The maximum number of connections. Defaults to number of logical CPU cores.\n        initializer: Optional[Callable[[], None]]\n            The initializer function.\n        \"\"\"\n\n        super().__init__()\n        self.hexagon_launcher = hexagon_launcher\n        self.evaluator_config = EvaluatorConfig._normalized(evaluator_config)\n        self.cooldown_sec = cooldown_sec\n        self.alloc_repeat = alloc_repeat\n        if max_workers is None:\n            max_workers = cpu_count(logical=True)\n        self.pool = PopenPoolExecutor(\n            max_workers=max_workers,\n            timeout=100,\n            initializer=initializer,\n        )\n\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        results = []\n        for runner_input in runner_inputs:\n            future = RPCRunnerFuture(\n                future=self.pool.submit(\n                    _worker_func,\n                    self.hexagon_launcher,\n                    self.evaluator_config,\n                    self.alloc_repeat,\n                    str(runner_input.artifact_path),\n                    tuple(arg_info.as_json() for arg_info in runner_input.args_info),\n                ),\n                timeout_sec=100,\n            )\n            results.append(future)\n        return results\n\n\ndef _worker_func(hexagon_launcher, evaluator_config, alloc_repeat, artifact_path, args_info):\n    with hexagon_launcher.create_session() as session:\n        device = session.device\n        _, remote_path = os.path.split(artifact_path)\n        uploaded = session.upload(artifact_path, remote_path)\n        rt_mod = session.load_module(uploaded)\n        repeated_args = default_alloc_argument(\n            session,\n            device,\n            args_info,\n            alloc_repeat,\n        )\n        costs = default_run_evaluator(\n            session,\n            rt_mod,\n            device,\n            evaluator_config,\n            repeated_args,\n        )\n    return costs\n\n\ndef get_hexagon_local_builder():\n    \"\"\"Return Hexagon-compatible Builder for meta schedule.\"\"\"\n\n    def export_func(mod):\n        binary_path = export_module(mod, tempfile.mkdtemp())\n        return str(binary_path)\n\n    return LocalBuilder(f_export=export_func)\n\n\ndef get_hexagon_rpc_runner(\n    hexagon_launcher: HexagonLauncherRPC, number=3, repeat=1, min_repeat_ms=100\n):\n    \"\"\"Return Hexagon-compatible RPC Runner for meta schedule.\n\n    Parameters\n    ----------\n    hexagon_launcher : HexagonLauncherRPC\n        The RPC launcher for Hexagon.\n    number: int\n        The number of times to run this function for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat: int\n        The number of times to repeat the measurement.\n        In total, the function will be invoked (1 + number x repeat) times,\n        where the first one is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms: int\n        Minimum repeat time in ms. if the execution latency is too short,\n        increase the number of runs to the given time (in ms) to reduce the measurement error.\n    \"\"\"\n    evaluator_config = EvaluatorConfig(\n        number=number,\n        repeat=repeat,\n        min_repeat_ms=min_repeat_ms,\n        enable_cpu_cache_flush=False,\n    )\n\n    return HexagonRPCRunner(\n        hexagon_launcher,\n        evaluator_config,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/profiling/process_lwp_data.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport csv\nimport subprocess\nimport argparse\nimport os\nfrom re import search, compile\nfrom collections import OrderedDict\n\nENABLE_DEBUG = False\n\"\"\"\nProcess lightweight profiling output and generate a CSV file with processor\ncycles for the instrumented functions and loops.\n\nPlease note that some assumptions have been made while processing\nthe lightweight profiling output. They are as follows:\n\n1) We don't expect profiled functions to call another profiled function.\n  This constraint can be relaxed if needed but it simplifies the processing\n  significantly without introducing any limitations for our use case.\n2) For now, it's also assumed that every unique section (loop) ID has same start\n  and end offset which will not be true while a loop gets unrolled as it will\n  create multiple profiling section with the same ID. The current\n  implementation doesn't handle this case.\n\n\"\"\"\n\n\ndef get_func_info(model_so):\n    \"\"\"Get all the .text sections along with their start and end offset values\"\"\"\n    hexagon_nm_path = os.environ[\"HEXAGON_TOOLCHAIN\"] + \"/bin/hexagon-nm\"\n    out = subprocess.Popen(\n        [hexagon_nm_path, \"--print-size\", model_so],\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n    )\n    stdo, stde = out.communicate()\n    stdo = stdo.decode(\"utf-8\")\n\n    func_info = []\n    for l in stdo.split(\"\\n\"):\n        info = {}\n        if search(\" (T|t) \", l):  # If .text section\n            parts = l.split(\" \")\n            assert len(parts) == 4\n            info[\"start\"] = int(parts[0], base=16)\n            info[\"end\"] = int(parts[0], base=16) + int(parts[1], base=16)\n            info[\"name\"] = parts[3]\n            func_info.append(info)\n\n    # Sort the entries in the increasing order of the start offset value.\n    func_info = sorted(func_info, key=lambda d: d[\"start\"])\n\n    if ENABLE_DEBUG:\n        print(\"func_info :\\n \")\n        for f in func_info:\n            print(f)\n    return func_info\n\n\ndef find_func(func_info, offset):\n    \"\"\"For a given offset, find the function it belongs to.\"\"\"\n    fidx = 0\n    lidx = len(func_info) - 1\n    while fidx <= lidx:\n        midx = (fidx + lidx) // 2\n        ms = func_info[midx][\"start\"]\n        me = func_info[midx][\"end\"]\n        if fidx == lidx:\n            assert (\n                offset >= ms and offset <= me\n            ), f\"Couldn't find a function for this offset: {offset}\"\n            return fidx\n        else:\n            if offset > me:\n                fidx = midx + 1\n            elif offset < ms:\n                lidx = midx - 1\n            else:\n                return midx\n    assert False, \"Possible mismatch between model .so and LWP data\"\n\n\ndef accumulate_cycles(overall_cycles, func_cycles, func_name):\n    \"\"\"Accumulate function cycles\"\"\"\n    acc_cycles = overall_cycles[func_name]\n    for id in func_cycles:\n        assert id in acc_cycles, f\"id [{id}] missing in the existing function record\"\n        assert (\n            acc_cycles[id][\"start\"] == func_cycles[id][\"start\"]\n        ), \"Offset value doesn't match with the existing function record.\"\n        acc_cycles[id][\"cycles\"] += func_cycles[id][\"cycles\"]\n        acc_cycles[id][\"count\"] += func_cycles[id][\"count\"]\n    overall_cycles.update({func_name: acc_cycles})\n    return overall_cycles\n\n\ndef adjust_per_loop_counts(overall_cycles, data):\n    \"\"\"\n    Use execution count and the number of entries recorded for each function/loop\n    to compute the overall cycles spent on them.\n    \"\"\"\n    for func in overall_cycles:\n        func_cycles = overall_cycles[func]\n        for id in func_cycles:\n            exec_count = data[\"loop_counts\"][id]\n            rec_count = func_cycles[id][\"count\"]\n            assert exec_count != 0, \"Execution count should have been non-zero.\"\n            assert rec_count != 0, \"Entry count should have been non-zero.\"\n            exec_cycles = ((int(func_cycles[id][\"cycles\"])) * exec_count) // rec_count\n            func_cycles[id][\"cycles\"] = exec_cycles\n            func_cycles[id][\"count\"] = exec_count\n        overall_cycles.update({func: OrderedDict(sorted(func_cycles.items()))})\n    return overall_cycles\n\n\ndef create_csv_report(overall_cycles, fname):\n    \"\"\"Create csv report\"\"\"\n    header = [\n        \"function name\",\n        \"loop/function id\",\n        \"loop depth\",\n        \"start offset\",\n        \"end offset\",\n        \"pcycles\",\n        \"parent count\",\n    ]\n    with open(fname, \"w\") as f:\n        writer = csv.writer(f)\n        writer.writerow(header)\n        for func in overall_cycles:\n            func_cycles = overall_cycles[func]\n            data = []\n            root = -1\n            outer_most = -1\n            for key, value in func_cycles.items():\n                if value[\"parent\"] == -1:\n                    assert root == -1, \"Can't have multiple root nodes.\"\n                    root = key\n\n                data.append(func)\n                data.append(key)\n                if value[\"parent\"] == -1:\n                    data.append(\"-\")  # Total cycles over all invocations of this function.\n                elif value[\"parent\"] == root:\n                    data.append(0)\n                    outer_most = key\n                else:\n                    if outer_most > -1:\n                        data.append(key - outer_most)\n                    else:\n                        data.append(key - value[\"parent\"])\n                data.append(hex(value[\"start\"]))\n                data.append(hex(value[\"end\"]))\n                data.append(value[\"cycles\"])\n                data.append(value[\"count\"])\n                writer.writerow(data)\n                data.clear()\n\n\ndef process_data(data, func_info, so_ld_addr):\n    \"\"\"Process data\"\"\"\n    # Keep an ordered list of loop IDs as they are being visited. This is used\n    # to match entry and exit pairs. Once the function/loop is processed, it's\n    # removed from the list.\n    ordered_visited_list = []\n    # Store information regarding visited nodes as they are being processed. Once\n    # the function/loop is processed, it's removed from the set.\n    visited_set = {}\n    # Dictionary to store cycles for the entire model which is grouped into functions.\n    overall_cycles = {}\n    func_cycles = {}\n\n    func_idx = -1\n    func_name = \"\"\n    prev_func_name = \"\"\n    func_start = 0\n    func_end = 0\n    save_data = False\n    # Iterate over all the entries in the LWP data file and process them\n    # to construct a report.\n    for entry in data[\"entries\"]:\n        id = entry[\"id\"]\n        offset = entry[\"ret\"] - so_ld_addr\n\n        # Recorded return address should fall within the function begin and end\n        # offsets. If not, find the function it belongs to.\n        if offset < func_start or offset > func_end:\n            prev_func_name = func_name\n            if ENABLE_DEBUG:\n                print(\"offset : \", offset)\n                print(\"id : \", id)\n\n            func_idx = find_func(func_info, offset)\n            func_name = func_info[func_idx][\"name\"]\n            func_start = func_info[func_idx][\"start\"]\n            func_end = func_info[func_idx][\"end\"]\n            if ENABLE_DEBUG:\n                print(\"func_name : \", func_name)\n\n            if save_data:\n                # overall_cycles = save_func_cycles(prev_func_name, overall_cycles, func_cycles, ordered_visited_list)\n                # Done processing the previous function, copy its info into 'overall_cycles'.\n                if prev_func_name not in overall_cycles:\n                    overall_cycles[prev_func_name] = func_cycles.copy()\n                else:\n                    # Accumulate cycles into existing function entry.\n                    overall_cycles = accumulate_cycles(overall_cycles, func_cycles, prev_func_name)\n                # We don't allow for fused operators (functions) calling another operator.\n                if ENABLE_DEBUG:\n                    print(\"ordered_visited_list : \", ordered_visited_list)\n\n                assert len(ordered_visited_list) == 0, (\n                    f\"\\nDone processing function [{prev_func_name}] but ordered_visited_list not empty.\\n\"\n                    f\"\\t Possible reasons -- \\n\"\n                    f\"\\t\\t1) Mismatch between model .so and json file.\\n\"\n                    f\"\\t\\t2) LWP buffer may have overflowed resulting into missing entries!\"\n                )\n                func_cycles.clear()\n\n            save_data = True\n\n        if id not in visited_set:  # Found 'entry' record\n            visited_info = {\"func_idx\": func_idx, \"ret\": offset, \"cyc\": entry[\"cyc\"]}\n            visited_set[id] = visited_info\n            ordered_visited_list.append(id)\n        else:  # Found 'exit' record\n            # This should be the last entry in the ordered_visited_list. If not, error out.\n            assert ordered_visited_list[-1] == id, (\n                \"Problem with LWP output - Interleaved handler calls found.\"\n                f\"Loop [{ordered_visited_list[-1]}] hasn't exited yet.\"\n            )\n            ordered_visited_list.pop()\n            entry_node = visited_set.pop(id)\n            assert (\n                entry_node[\"func_idx\"] == func_idx\n            ), f'Error - Found under a different function name : {entry_node[\"func_idx\"]}'\n            cycles = entry[\"cyc\"] - entry_node[\"cyc\"]\n            parent = -1\n            if ordered_visited_list:\n                parent = int(ordered_visited_list[-1])\n            if id in func_cycles:\n                fcycles = func_cycles[id]\n                fcycles[\"cycles\"] += cycles\n                fcycles[\"count\"] += 1\n                func_cycles[id] = fcycles\n            else:\n                func_cycles[id] = {\n                    \"cycles\": cycles,\n                    \"start\": entry_node[\"ret\"],\n                    \"end\": offset,\n                    \"parent\": parent,\n                    \"count\": 1,\n                }\n\n    # Done processing the previous function, copy its info into 'overall_cycles'.\n    if func_name not in overall_cycles:\n        overall_cycles[func_name] = func_cycles.copy()\n    else:\n        # Accumulate cycles into existing function entry.\n        overall_cycles = accumulate_cycles(overall_cycles, func_cycles, func_name)\n    # We don't allow for fused operators (functions) calling another operator.\n    if ENABLE_DEBUG:\n        print(\"ordered_visited_list : \", ordered_visited_list)\n\n    assert len(ordered_visited_list) == 0, (\n        f\"\\nDone processing function [{prev_func_name}] but ordered_visited_list not empty.\\n\"\n        f\"\\t Possible reasons -- \\n\"\n        f\"\\t\\t1) Mismatch between model .so and json file.\\n\"\n        f\"\\t\\t2) LWP buffer may have overflowed resulting into missing entries!\" % prev_func_name\n    )\n\n    overall_cycles = adjust_per_loop_counts(overall_cycles, data)\n    return overall_cycles\n\n\ndef get_load_addr(serial_number: str, lwp_json: str, run_log: str):\n    \"\"\"Get load address of the binary file\"\"\"\n    if serial_number == \"simulator\":\n        basedir = os.path.dirname(lwp_json)\n        if run_log is None:\n            run_log = os.path.join(basedir, \"stdout.txt\")\n        else:\n            # If the directory name is specified for the run_log of the\n            # simulator (stdout.txt) then it must be same as lwp_json.\n            run_log_dir = os.path.dirname(run_log)\n            assert (\n                run_log_dir == \"\" or run_log_dir == basedir\n            ), f\"stdout.txt and {os.path.basename(lwp_json)} must be in the same directory\"\n            run_log = os.path.join(basedir, os.path.basename(run_log))\n        # To extract load address for the simulator run\n        pattern = compile(r\"Model.*: (\\w+):\")\n    else:\n        # To extract load address for on-device run\n        pattern = compile(r\"Model.*: (\\w+)\")\n\n    with open(run_log, \"r\") as f:\n        lines = f.read()\n        a = pattern.search(lines)\n        load_addr = int(a.group(1), 16)\n    if ENABLE_DEBUG:\n        print(\"load_addr : \", load_addr)\n    return load_addr\n\n\ndef process_lwp_output(\n    binary_path: str,\n    serial_number: str,\n    lwp_json: str,\n    run_log: str,\n    lwp_out: str,\n    enable_debug: bool = False,\n):\n    \"\"\"Process lightweight profiling data\"\"\"\n    # Enable debug messages\n    global ENABLE_DEBUG\n    ENABLE_DEBUG = enable_debug\n\n    # Get load address for the binary\n    load_addr = get_load_addr(serial_number, lwp_json, run_log)\n    # Opening JSON file\n    with open(lwp_json, \"r\") as f:\n        # Returns JSON object as a dictionary\n        data = json.load(f)\n\n    # Get function names, and their start and end offsets from the model .so\n    func_info = get_func_info(binary_path)\n\n    # Get the load address for model .so.\n    so_ld_addr = load_addr\n\n    # Process profiling data to construct a CSV report.\n    overall_cycles = process_data(data, func_info, so_ld_addr)\n    create_csv_report(overall_cycles, lwp_out)\n    print(\"lwp processed output written to -- \", lwp_out)\n    print(\"[NOTE: Use '--hexagon-debug' to keep the temp directory]\")\n\n\ndef get_args():\n    \"\"\"Add commandline arguments to run the script manually if needed\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--lwp-json\", help=\"LWP json file\", required=True)\n    parser.add_argument(\"--serial-num\", help=\"device-id/simulator\", required=True)\n    parser.add_argument(\"--test-so\", help=\"Test shared library\", required=True)\n    parser.add_argument(\n        \"--run-log\",\n        help=\"Logcat file for on-device run and stdout.txt for simulator run\",\n        required=True,\n    )\n    parser.add_argument(\"--lwp-out\", help=\"LWP output file name\", required=True)\n    parser.add_argument(\n        \"--debug\",\n        help=\"Enable debug output from the script\",\n        dest=\"debug\",\n        action=\"store_true\",\n        required=False,\n    )\n    parser.set_defaults(debug=False)\n    args = parser.parse_args()\n\n    global ENABLE_DEBUG\n    ENABLE_DEBUG = args.debug\n\n    return args\n\n\nif __name__ == \"__main__\":\n    args = get_args()\n    process_lwp_output(\n        args.test_so, args.serial_num, args.lwp_json, args.run_log, args.lwp_out, args.debug\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/pytest_plugin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,redefined-outer-name\n\"\"\" Hexagon testing fixtures used to deduce testing argument\n    values from testing parameters \"\"\"\n\nimport os\nimport random\nfrom typing import Optional, Union\n\nimport pytest\n\nimport tvm\nimport tvm.rpc.tracker\nfrom tvm.contrib.hexagon.build import HexagonLauncher, HexagonLauncherRPC\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.contrib.hexagon.tools import HEXAGON_SIMULATOR_NAME\n\nHEXAGON_TOOLCHAIN = \"HEXAGON_TOOLCHAIN\"\nTVM_TRACKER_HOST = \"TVM_TRACKER_HOST\"\nTVM_TRACKER_PORT = \"TVM_TRACKER_PORT\"\nANDROID_REMOTE_DIR = \"ANDROID_REMOTE_DIR\"\nANDROID_SERIAL_NUMBER = \"ANDROID_SERIAL_NUMBER\"\nADB_SERVER_SOCKET = \"ADB_SERVER_SOCKET\"\nRNG_SEEDED = False\n\nHEXAGON_AOT_LLVM_TARGET = (\n    \"llvm -keys=hexagon \"\n    \"-mattr=+hvxv68,+hvx-length128b,+hvx-qfloat,-hvx-ieee-fp \"\n    \"-mcpu=hexagonv68 -mtriple=hexagon\"\n)\n\n\n@tvm.testing.fixture\ndef shape_nhwc(batch, in_channel, in_size):\n    return (batch, in_size, in_size, in_channel)\n\n\ndef _compose(args, decs):\n    \"\"\"Helper to apply multiple markers\"\"\"\n    if len(args) > 0:\n        func = args[0]\n        for dec in reversed(decs):\n            func = dec(func)\n        return func\n    return decs\n\n\nrequires_hexagon_toolchain = tvm.testing.requires_hexagon(support_required=\"compile-only\")\n\n\ndef android_serial_number() -> Optional[str]:\n    \"\"\"Return the android serial number\"\"\"\n    serial = os.getenv(ANDROID_SERIAL_NUMBER, default=\"\")\n    # Setting ANDROID_SERIAL_NUMBER to an empty string should be\n    # equivalent to having it unset.\n    if not serial.strip():\n        return None\n\n    # Split android serial numbers into a list\n    serial = serial.split(\",\")\n    return serial\n\n\n# NOTE on server ports:\n# These tests use different port numbers for the RPC server (7070 + ...).\n# The reason is that an RPC session cannot be gracefully closed without\n# triggering TIME_WAIT state on the server socket. This prevents another\n# server to bind to the same port until the wait time elapses.\n\nLISTEN_PORT_MIN = 6000  # Avoid hitting well-known Android debug ports\nLISTEN_PORT_MAX = 9000  # Below the search range end (port_end=9199) of RPC server\nPREVIOUS_PORT = None\n\n\ndef get_free_port() -> int:\n    \"\"\"Return the next port that is available to listen on\"\"\"\n    global PREVIOUS_PORT\n    global RNG_SEEDED\n\n    if tvm.testing.utils.IS_IN_CI and not RNG_SEEDED:\n        random.seed(0)\n        RNG_SEEDED = True\n\n    if PREVIOUS_PORT is None:\n        port = random.randint(LISTEN_PORT_MIN, LISTEN_PORT_MAX)\n    else:\n        port = PREVIOUS_PORT + 1\n        if port > LISTEN_PORT_MAX:\n            port = LISTEN_PORT_MIN\n\n    while tvm.contrib.hexagon.build._is_port_in_use(port):\n        port = port + 1 if port < LISTEN_PORT_MAX else LISTEN_PORT_MIN\n\n    PREVIOUS_PORT = port\n    return port\n\n\n@pytest.fixture(scope=\"session\")\ndef _tracker_info() -> Union[str, int]:\n    env_tracker_host = os.getenv(TVM_TRACKER_HOST, default=\"\")\n    env_tracker_port = os.getenv(TVM_TRACKER_PORT, default=\"\")\n\n    if env_tracker_host or env_tracker_port:\n        # A tracker is already running, and we should connect to it\n        # when running tests.\n        assert env_tracker_host, \"TVM_TRACKER_PORT is defined, but TVM_TRACKER_HOST is not\"\n        assert env_tracker_port, \"TVM_TRACKER_HOST is defined, but TVM_TRACKER_PORT is not\"\n        env_tracker_port = int(env_tracker_port)\n\n        try:\n            tvm.rpc.connect_tracker(env_tracker_host, env_tracker_port)\n        except RuntimeError as exc:\n            message = (\n                \"Could not connect to external tracker \"\n                \"specified by $TVM_TRACKER_HOST and $TVM_TRACKER_PORT \"\n                f\"({env_tracker_host}:{env_tracker_port})\"\n            )\n            raise RuntimeError(message) from exc\n\n        yield (env_tracker_host, env_tracker_port)\n\n    else:\n        # No tracker is provided to the tests, so we should start one\n        # for the tests to use.\n        tracker = tvm.rpc.tracker.Tracker(\"127.0.0.1\", get_free_port())\n        try:\n            yield (tracker.host, tracker.port)\n        finally:\n            tracker.terminate()\n\n\n@pytest.fixture(scope=\"session\")\ndef tvm_tracker_host(_tracker_info) -> str:\n    host, _ = _tracker_info\n    return host\n\n\n@pytest.fixture(scope=\"session\")\ndef tvm_tracker_port(_tracker_info) -> int:\n    _, port = _tracker_info\n    return port\n\n\n@pytest.fixture(scope=\"session\")\ndef rpc_server_port_for_session() -> int:\n    return get_free_port()\n\n\n@pytest.fixture()\ndef rpc_server_port() -> int:\n    return get_free_port()\n\n\n@pytest.fixture(scope=\"session\")\ndef adb_server_socket() -> str:\n    return os.getenv(ADB_SERVER_SOCKET, default=\"tcp:5037\")\n\n\n@pytest.fixture(scope=\"session\")\ndef hexagon_server_process(\n    request,\n    rpc_server_port_for_session,\n    adb_server_socket,\n    skip_rpc,\n    hexagon_debug,\n    sysmon_profile,\n    clear_logcat,\n) -> HexagonLauncherRPC:\n    \"\"\"Initials and returns hexagon launcher if ANDROID_SERIAL_NUMBER is defined.\n    This launcher is started only once per test session.\n    \"\"\"\n    android_serial_num = android_serial_number()\n\n    if android_serial_num is None:\n        pytest.skip(\"ANDROID_SERIAL_NUMBER is not set.\")\n    if android_serial_num == [HEXAGON_SIMULATOR_NAME]:\n        yield None\n    else:\n        # Requesting these fixtures sets up a local tracker, if one\n        # hasn't been provided to us.  Delaying the evaluation of\n        # these fixtures avoids starting a tracker unless necessary.\n        tvm_tracker_host = request.getfixturevalue(\"tvm_tracker_host\")\n        tvm_tracker_port = request.getfixturevalue(\"tvm_tracker_port\")\n\n        rpc_info = {\n            \"rpc_tracker_host\": tvm_tracker_host,\n            \"rpc_tracker_port\": tvm_tracker_port,\n            \"rpc_server_port\": rpc_server_port_for_session,\n            \"adb_server_socket\": adb_server_socket,\n        }\n        workerinput = getattr(request.config, \"workerinput\", None)\n        if workerinput is None:  # single-process execution\n            device_adr = read_device_list()[0]\n        else:  # running in a subprocess here\n            device_adr = workerinput[\"device_adr\"]\n        launcher = HexagonLauncher(\n            serial_number=device_adr,\n            rpc_info=rpc_info,\n            hexagon_debug=hexagon_debug,\n            sysmon_profile=sysmon_profile,\n            clear_logcat=clear_logcat,\n        )\n        try:\n            if not skip_rpc:\n                launcher.start_server()\n            yield {\"launcher\": launcher, \"device_adr\": device_adr}\n        finally:\n            if not skip_rpc:\n                launcher.stop_server()\n\n\ndef read_device_list():\n    return android_serial_number()\n\n\ndef pytest_configure(config):\n    # read device list if we are on the master\n    if not hasattr(config, \"workerinput\"):\n        config.iplist = read_device_list()\n\n\ndef pytest_configure_node(node):\n    # the master for each node fills node input dictionary\n    # which pytest-xdist will transfer to the subprocess\n    if node.config.iplist is not None:\n        node.workerinput[\"device_adr\"] = node.config.iplist.pop()\n\n\n@pytest.fixture\ndef hexagon_launcher(\n    hexagon_server_process,\n    rpc_server_port,\n    tvm_tracker_host,\n    tvm_tracker_port,\n    adb_server_socket,\n    hexagon_debug,\n    sysmon_profile,\n    clear_logcat,\n) -> HexagonLauncherRPC:\n    \"\"\"Initials and returns hexagon launcher which reuses RPC info and Android serial number.\"\"\"\n    android_serial_num = android_serial_number()\n\n    if android_serial_num != [HEXAGON_SIMULATOR_NAME]:\n        rpc_info = hexagon_server_process[\"launcher\"]._rpc_info\n    else:\n        rpc_info = {\n            \"rpc_tracker_host\": tvm_tracker_host,\n            \"rpc_tracker_port\": tvm_tracker_port,\n            \"rpc_server_port\": rpc_server_port,\n            \"adb_server_socket\": adb_server_socket,\n        }\n    try:\n        if android_serial_num == [HEXAGON_SIMULATOR_NAME]:\n            launcher = HexagonLauncher(serial_number=android_serial_num[0], rpc_info=rpc_info)\n            launcher.start_server()\n        else:\n            launcher = HexagonLauncher(\n                serial_number=hexagon_server_process[\"device_adr\"],\n                rpc_info=rpc_info,\n                hexagon_debug=hexagon_debug,\n                sysmon_profile=sysmon_profile,\n                clear_logcat=clear_logcat,\n            )\n        yield launcher\n    finally:\n        if android_serial_num == [HEXAGON_SIMULATOR_NAME]:\n            launcher.stop_server()\n        elif not hexagon_debug:\n            launcher.cleanup_directory()\n\n\n@pytest.fixture\ndef hexagon_session(hexagon_launcher: HexagonLauncherRPC) -> Session:\n    if hexagon_launcher is None:\n        yield None\n    else:\n        with hexagon_launcher.create_session() as session:\n            yield session\n\n\n# If the execution aborts while an RPC server is running, the python\n# code that is supposed to shut it down will never execute. This will\n# keep pytest from terminating (indefinitely), so add a cleanup\n# fixture to terminate any still-running servers.\n@pytest.fixture(scope=\"session\", autouse=True)\ndef terminate_rpc_servers():\n    # Since this is a fixture that runs regardless of whether the\n    # execution happens on simulator or on target, make sure the\n    # yield happens every time.\n    serial = os.environ.get(ANDROID_SERIAL_NUMBER)\n    yield []\n    if serial == [HEXAGON_SIMULATOR_NAME]:\n        os.system(\"ps ax | grep tvm_rpc_x86 | awk '{print $1}' | xargs kill\")\n\n\naot_host_target = tvm.testing.parameter(\"c\", HEXAGON_AOT_LLVM_TARGET)\n\n\n@tvm.testing.fixture\ndef aot_target(aot_host_target):\n    if aot_host_target == \"c\":\n        yield tvm.target.hexagon(\"v68\")\n    elif aot_host_target.startswith(\"llvm\"):\n        yield aot_host_target\n    else:\n        assert False, \"Incorrect AoT host target: {aot_host_target}. Options are [c, llvm].\"\n\n\n@pytest.fixture(scope=\"session\")\ndef skip_rpc(request) -> bool:\n    return request.config.getoption(\"--skip-rpc\")\n\n\n@pytest.fixture(scope=\"session\")\ndef hexagon_debug(request) -> bool:\n    return request.config.getoption(\"--hexagon-debug\")\n\n\n@pytest.fixture(scope=\"session\")\ndef sysmon_profile(request) -> bool:\n    return request.config.getoption(\"--sysmon-profile\")\n\n\n@pytest.fixture(scope=\"session\")\ndef clear_logcat(request) -> bool:\n    return request.config.getoption(\"--clear-logcat\")\n\n\ndef pytest_addoption(parser):\n    \"\"\"Add pytest options.\"\"\"\n\n    parser.addoption(\n        \"--skip-rpc\",\n        action=\"store_true\",\n        default=False,\n        help=\"If set true, the RPC server initialization on Android would be skipped\",\n    )\n    parser.addoption(\n        \"--hexagon-debug\",\n        action=\"store_true\",\n        default=False,\n        help=\"If set true, it will keep the hexagon test directories on the target. \"\n        + \"Additionally logcat logs will be copied from device and cdsp errors printed out.\",\n    )\n    parser.addoption(\n        \"--sysmon-profile\",\n        action=\"store_true\",\n        default=False,\n        help=\"If set true, it will run sysmon profiler during the tests.\",\n    )\n    parser.addoption(\n        \"--clear-logcat\",\n        action=\"store_true\",\n        default=False,\n        help=\"If set true, it will clear logcat before execution.\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/session.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines a Session class for Hexagon devices.\"\"\"\n\nimport os\nimport pathlib\nimport tempfile\nfrom typing import Union\n\nimport tvm\nfrom tvm import rpc as _rpc\nimport tvm.contrib.hexagon as hexagon\nfrom tvm.relay.backend.executor_factory import (\n    ExecutorFactoryModule,\n    AOTExecutorFactoryModule,\n    GraphExecutorFactoryModule,\n)\nfrom .tools import export_module, HEXAGON_SIMULATOR_NAME\n\n\nclass Session:\n    \"\"\"Hexagon Device Session\n\n    Parameters\n    ----------\n    remote_workspace : Union[str, pathlib.Path]\n        Remote workspace path\n\n    rpc_tracker : tuple(str, int)\n        RPC tracker host and port number.\n\n    rpc_server_key : str\n        RPC server key on remote device.\n\n    serial_number : str\n        Device serial number. `simulator` used for hexagon simulator.\n\n    session_name : str\n        Hexagon RPC session name.\n\n    remote_stack_size_bytes : int\n        The stack size of the remote device, to be passed to\n        tvm.contrib.hexagon.create_hexagon_session.\n\n    rpc_receive_buffer_size_bytes : int\n        RPC receive buffer size in bytes.\n    \"\"\"\n\n    def __init__(\n        self,\n        remote_workspace: Union[str, pathlib.Path],\n        rpc_tracker: tuple,\n        rpc_server_key: str,\n        serial_number: str,\n        session_name: str = \"hexagon-rpc\",\n        remote_stack_size_bytes: int = 256 * 1024,  # Min size for main thread in QuRT/sim\n        rpc_receive_buffer_size_bytes: int = 256 * 1024 * 1024,  # Size for passing hexagon tests\n    ):\n        self._workspace = str(remote_workspace)\n        self._rpc_tracker = rpc_tracker\n        self._rpc_server_key = rpc_server_key\n        self._serial_number = serial_number\n        self._session_name: str = session_name\n        self._remote_stack_size_bytes: int = remote_stack_size_bytes\n        self._rpc_receive_buffer_size_bytes: int = rpc_receive_buffer_size_bytes\n        self._rpc = None\n        self._requires_cpu_device = False\n        self._device = None\n\n    def __enter__(self):\n        if self._rpc:\n            # Already initialized\n            return self\n\n        tracker = _rpc.connect_tracker(self._rpc_tracker[0], self._rpc_tracker[1])\n        try:\n            self._rpc = tracker.request(\n                self._rpc_server_key,\n                priority=0,\n                session_timeout=0,\n                session_constructor_args=[\n                    \"tvm.contrib.hexagon.create_hexagon_session\",\n                    self._session_name,\n                    self._remote_stack_size_bytes,\n                    os.environ.get(\"HEXAGON_SIM_ARGS\", \"\"),\n                    self._rpc_receive_buffer_size_bytes,\n                ],\n            )\n            func = self._rpc.get_function(\"device_api.hexagon.acquire_resources\")\n            func()\n            return self\n\n        except RuntimeError as exception:\n            raise exception\n\n    def __exit__(self, exc_type, exc_value, exc_traceback):\n        try:\n            func = self._rpc.get_function(\"device_api.hexagon.release_resources\")\n            func()\n        except RuntimeError as exception:\n            print(\n                \"Exception occurred while calling release_resources() during Session __exit__: \",\n                exception,\n            )\n        finally:\n            # close session to the tracker\n            shutdown_func = self._rpc._sess.get_function(\"CloseRPCConnection\")\n            shutdown_func()\n            del self._rpc\n\n    @property\n    def device(self):\n        \"\"\"Session device.\"\"\"\n\n        if self._device is not None:\n            return self._device\n\n        if self._requires_cpu_device:\n            self._device = self._rpc.cpu(0)\n        else:\n            self._device = self._rpc.hexagon(0)\n\n        return self._device\n\n    def is_simulator(self):\n        return self._serial_number == HEXAGON_SIMULATOR_NAME\n\n    def get_function(self, name):\n        return self._rpc.get_function(name)\n\n    def upload(self, local_path: Union[str, pathlib.Path], remote_filename: str) -> pathlib.Path:\n        \"\"\"Upload a local file to the remote workspace.\n\n        Parameters\n        ----------\n        local_path : str or pathlib.Path\n            Path to the local file to be copied.\n        remote_filename : str\n            Name of the file in the remote workspace.\n\n        Returns\n        -------\n        pathlib.Path :\n            Uploaded file remote path.\n        \"\"\"\n        upload_func = self._rpc.get_function(\"tvm.rpc.server.upload\")\n        remote_path = f\"{self._workspace}/{remote_filename}\"\n        with open(local_path, mode=\"rb\") as src_f:\n            data = bytearray(src_f.read())\n        upload_func(remote_path, data)\n        return remote_path\n\n    def load_module(self, module: Union[str, pathlib.Path, tvm.runtime.Module]):\n        \"\"\"Load TVM module.\n\n        The session must be established (via __enter__) prior to\n        calling this function.\n\n        Parameters\n        ----------\n        module : Union[str, pathlib.Path, tvm.runtime.Module]\n\n            The module to load.  If `module` is a\n            `tvm.runtime.Module`, it will be uploaded to the remote\n            session and loaded.\n\n            If the object passed is a string or pathlib.Path, it must\n            be a full path in the remote system.\n\n        Returns\n        -------\n        TVMModule :\n            TVM module object.\n        \"\"\"\n\n        assert self._rpc is not None, \"Hexagon session must be started using __enter__ prior to use\"\n\n        if isinstance(module, tvm.runtime.Module):\n            with tempfile.TemporaryDirectory() as temp_dir:\n                binary_name = \"test_binary.so\"\n                binary_path = export_module(module, temp_dir, binary_name)\n                remote_file_path = self.upload(binary_path, binary_name)\n        else:\n            remote_file_path = module\n\n        assert isinstance(remote_file_path, (str, pathlib.Path)), \"Invalid path type:\" + str(\n            type(remote_file_path)\n        )\n        return self._rpc.get_function(\"tvm.hexagon.load_module\")(str(remote_file_path))\n\n    def get_graph_executor(\n        self,\n        graph_json: str,\n        module_name: Union[str, pathlib.Path, tvm.runtime.Module],\n    ):\n        \"\"\"Create a local GraphModule which consumes a remote libmod.\n\n        The session must be established (via __enter__) prior to\n        calling this function.\n\n        Parameters\n        ----------\n        module_name : Union[str, pathlib.Path, tvm.runtime.Module]\n            The remote module filename, following the same restrictions\n            as `load_module`.\n        graph_json : str\n            The string with the graph JSON.\n\n        Returns\n        -------\n        GraphModule :\n            Runtime graph module that can be used to execute the graph.\n\n        \"\"\"\n        graph_mod = self.load_module(module_name)\n        self._set_device_type(graph_mod)\n        return tvm.contrib.graph_executor.create(graph_json, graph_mod, self.device)\n\n    def get_aot_executor(\n        self,\n        module_file: Union[str, pathlib.Path],\n    ):\n        \"\"\"Create a local GraphModule which consumes a remote libmod.\n        The session must be established (via __enter__) prior to\n        calling this function.\n        Parameters\n        ----------\n        module_file : Union[str, pathlib.Path]\n            The remote module filename, following the same restrictions\n            as `load_module`. The filename should be an absolute path.\n        Returns\n        -------\n        GraphModule :\n            Runtime graph module that can be used to execute the graph.\n        \"\"\"\n        aot_mod = self.load_module(module_file)\n        return tvm.runtime.executor.AotModule(aot_mod[\"default\"](self.device))\n\n    def get_graph_debug_executor(\n        self,\n        graph_json: str,\n        module_name: Union[str, pathlib.Path, tvm.runtime.Module],\n        dump_root: Union[str, pathlib.Path] = None,\n    ):\n        \"\"\"Create a local GraphModuleDebug which consumes a remote libmod.\n\n        Parameters\n        ----------\n        graph_json : str\n            The string with the graph JSON.\n         module_name : Union[str, pathlib.Path, tvm.runtime.Module]\n            The remote module filename, following the same restrictions\n            as `load_module`.\n        session : Session\n            Remote session. The session must be established (via __enter__)\n            prior to calling this function.\n\n        Returns\n        -------\n        GraphModuleDebug :\n            Runtime debug graph module that can be used to debug the graph.\n        \"\"\"\n\n        graph_debug_mod = self.load_module(module_name)\n        self._set_device_type(graph_debug_mod)\n        return tvm.contrib.debugger.debug_executor.create(\n            graph_json, graph_debug_mod, self.device, dump_root=str(dump_root)\n        )\n\n    def get_executor_from_factory(self, module: ExecutorFactoryModule):\n        \"\"\"Create a local GraphModule which consumes a remote libmod.\n\n        Parameters\n        ----------\n\n        module : ExecutorFactoryModule\n\n            The module to upload to the remote\n            session and load.\n        \"\"\"\n        if isinstance(module, AOTExecutorFactoryModule):\n            return self._aot_executor_from_factory(module)\n        if isinstance(module, GraphExecutorFactoryModule):\n            return self._graph_executor_from_factory(module)\n\n        raise TypeError(f\"Unsupported executor type: {type(module)}\")\n\n    def _set_device_type(self, module: Union[str, pathlib.Path, GraphExecutorFactoryModule]):\n        \"\"\"Set session device type(hexagon, cpu) based on target in module.\n\n        Parameters\n        ----------\n\n        module: TVMModule\n            TVM module object.\n        \"\"\"\n        # for cases when module is a single schedule without target attribute.\n        if not hasattr(module, \"target\"):\n            self._requires_cpu_device = False\n        else:\n            assert len(module.target) == 1\n            for target in module.target:\n                target_type = str(target).split()[0]\n\n            if target_type == \"llvm\":\n                self._requires_cpu_device = True\n            else:\n                self._requires_cpu_device = False\n\n    def _graph_executor_from_factory(\n        self,\n        module: Union[str, pathlib.Path, GraphExecutorFactoryModule],\n    ):\n        \"\"\"Create a local GraphModule which consumes a remote libmod.\n\n        The session must be established (via __enter__) prior to\n        calling this function.\n\n        Parameters\n        ----------\n\n        module : GraphExecutorFactoryModule\n\n            The graph executor module to upload to the remote and load.\n            This will typically be the output of `tvm.relay.build`,\n            when passing `executor=Executor(\"graph\")`.\n\n        Returns\n        -------\n        GraphModule :\n            Runtime graph module that can be used to execute the graph.\n\n        \"\"\"\n        return self.get_graph_executor(module.get_graph_json(), module.get_lib())\n\n    def _aot_executor_from_factory(\n        self,\n        module: Union[str, pathlib.Path, AOTExecutorFactoryModule],\n    ):\n        \"\"\"Create a local GraphModule which consumes a remote libmod.\n\n        The session must be established (via __enter__) prior to\n        calling this function.\n\n        Parameters\n        ----------\n\n        module : AOTExecutorFactoryModule\n\n            The graph executor module to upload to the remote and load.\n            This will typically be the output of `tvm.relay.build`,\n            when passing `executor=Executor(\"aot\")`.\n\n        Returns\n        -------\n        GraphModule :\n            Runtime graph module that can be used to execute the graph.\n\n        \"\"\"\n\n        hexagon_arch = set(\n            target.mcpu.replace(\"hexagon\", \"\")\n            for target in module.target\n            if \"hexagon\" in target.keys\n        )\n\n        self._set_device_type(module)\n\n        for target in module.target:\n            target_type = str(target).split()[0]\n\n        assert hexagon_arch, \"No hexagon target architecture found\"\n        assert len(hexagon_arch) == 1, f\"Inconsistent hexagon architecture found, {hexagon_arch}\"\n        hexagon_arch = hexagon_arch.pop()\n\n        with tempfile.TemporaryDirectory() as temp_dir:\n            temp_dir = pathlib.Path(temp_dir)\n            binary_name = \"test_binary.so\"\n            binary_path = temp_dir / binary_name\n\n            if target_type == \"hexagon\":\n                module.export_library(\n                    str(binary_path),\n                    fcompile=hexagon.create_aot_shared,\n                    hexagon_arch=hexagon_arch,\n                )\n            elif target_type == \"llvm\":\n                module.export_library(\n                    str(binary_path),\n                    cc=hexagon.hexagon_clang_plus(),\n                )\n            else:\n                raise ValueError(\n                    f\"Incorrect Target kind.\\n\"\n                    f\"Target kind should be from these options: [hexagon, llvm].\"\n                )\n\n            remote_file_path = self.upload(binary_path, binary_name)\n\n        return self.get_aot_executor(remote_file_path)\n\n    def get_profile_output(self, mode: str, path: str):\n        assert isinstance(mode, str), f\"Invalid mode type, {type(mode)} != str\"\n        assert isinstance(path, str), f\"Invalid path type, {type(path)} != str\"\n        return self._rpc.get_function(\"tvm.hexagon.get_profile_output\")(mode, path)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/tools.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Tools/compilers/linkers for Hexagon\"\"\"\n\nimport os\nimport pathlib\nfrom typing import Union\nimport numpy\n\nimport tvm\nimport tvm.contrib.cc as cc\nfrom ..._ffi.registry import register_func\n\n\n# Linking Hexagon shared libraries.\n#\n#   link_shared(name-of-shared-library, list-of-objects, kw-args)\n#\n# To use a custom linker, define a function that returns the path to the\n# linker, and pass it to 'register_linker':\n#\n#   def custom_linker_path():\n#       return '/path/to/hexagon/linker'\n#\n#   register_linker(custom_linker_path)\n#\n# Subsequent calls to 'link_shared' will use the newly registered linker.\n\nHEXAGON_TOOLCHAIN = os.environ.get(\"HEXAGON_TOOLCHAIN\", default=\"\")  # pylint: disable=invalid-name\nHEXAGON_SDK_ROOT = os.environ.get(\"HEXAGON_SDK_ROOT\", default=\"\")  # pylint: disable=invalid-name\nHEXAGON_LINK_MAIN = (\n    pathlib.Path(HEXAGON_TOOLCHAIN) / \"bin\" / \"hexagon-link\"\n)  # pylint: disable=invalid-name\nHEXAGON_CLANG_PLUS = (\n    pathlib.Path(HEXAGON_TOOLCHAIN) / \"bin\" / \"hexagon-clang++\"\n)  # pylint: disable=invalid-name\nHEXAGON_SDK_INCLUDE_DIRS = [  # pylint: disable=invalid-name\n    pathlib.Path(HEXAGON_SDK_ROOT) / \"incs\",\n    pathlib.Path(HEXAGON_SDK_ROOT) / \"incs\" / \"stddef\",\n]\n\nHEXAGON_SIMULATOR_NAME = \"simulator\"\n\n\ndef register_linker(f):\n    \"\"\"Register a function that will return the path to the Hexagon linker.\"\"\"\n    return register_func(\"tvm.contrib.hexagon.hexagon_link\", f, True)\n\n\n@register_func(\"tvm.contrib.hexagon.hexagon_link\")\ndef hexagon_link() -> str:\n    \"\"\"Return path to the Hexagon linker.\"\"\"\n    return str(HEXAGON_LINK_MAIN)\n\n\ndef hexagon_clang_plus() -> str:\n    \"\"\"Return path to the Hexagon clang++.\"\"\"\n    return str(HEXAGON_CLANG_PLUS)\n\n\n@register_func(\"tvm.contrib.hexagon.link_shared\")\ndef link_shared(so_name, objs, extra_args=None):\n    \"\"\"Link shared library on Hexagon using the registered Hexagon linker.\n\n    Parameters\n    ----------\n    so_name : str\n        Name of the shared library file.\n    objs : list[str,StringImm]\n    extra_args : dict (str->str) or Map<String,String>\n        Additional arguments:\n            'hex_arch' - Hexagon architecture, e.g. v66\n            'verbose'  - Print additional information if the key is present\n\n    Returns\n    -------\n    ret_val : int\n        This function returns 0 at the moment.\n    \"\"\"\n    # The list of object files can be passed as built-in Python strings,\n    # or as tvm.tir.StringImm's.\n    def to_str(s):\n        if isinstance(s, tvm.tir.StringImm):\n            return s.value\n        assert isinstance(s, str), 'argument \"' + str(s) + '\" should be a string or StrImm'\n        return s\n\n    objs = [to_str(s) for s in objs]\n\n    if not extra_args:\n        extra_args = {}\n    hex_arch = extra_args.get(\"hex_arch\") or \"v66\"\n    linker = tvm.get_global_func(\"tvm.contrib.hexagon.hexagon_link\")()\n    if extra_args.get(\"verbose\"):\n        print(\"tvm.contrib.hexagon.link_shared:\")\n        print(\"  Using linker:\", linker)\n        print(\"  Library name:\", so_name)\n        print(\"  Object files:\", objs)\n        print(\"  Architecture:\", hex_arch)\n    if not os.access(linker, os.X_OK):\n        message = 'The linker \"' + linker + '\" does not exist or is not executable.'\n        if not os.environ.get(\"HEXAGON_TOOLCHAIN\"):\n            message += (\n                \" The environment variable HEXAGON_TOOLCHAIN is unset. Please export \"\n                + \"HEXAGON_TOOLCHAIN in your environment, so that ${HEXAGON_TOOLCHAIN}/bin/\"\n                + \"hexagon-link exists.\"\n            )\n        else:\n            message += (\n                \" Please verify the value of the HEXAGON_LINKER environment variable \"\n                + '(currently set to \"'\n                + HEXAGON_TOOLCHAIN\n                + '\").'\n            )\n        raise Exception(message)\n\n    libpath = os.path.join(HEXAGON_TOOLCHAIN, \"target\", \"hexagon\", \"lib\", hex_arch, \"G0\")\n    cc.create_shared(\n        so_name,\n        objs,\n        # pylint: disable=bad-whitespace\n        options=[\n            \"-Bdynamic\",\n            \"-shared\",\n            \"-export-dynamic\",\n            os.path.join(libpath, \"pic\", \"libgcc.so\"),\n        ],\n        cc=linker,\n    )\n    return 0\n\n\ndef create_aot_shared(so_name: Union[str, pathlib.Path], files, hexagon_arch: str, options=None):\n    \"\"\"Export Hexagon AOT module.\"\"\"\n    options = options or []\n    if not os.access(str(HEXAGON_CLANG_PLUS), os.X_OK):\n        raise Exception(\n            'The Clang++ \"' + str(HEXAGON_CLANG_PLUS) + '\" does not exist or is not executable.'\n        )\n    if not HEXAGON_TOOLCHAIN:\n        raise Exception(\n            \" The environment variable HEXAGON_TOOLCHAIN is unset. Please export \"\n            + \"HEXAGON_TOOLCHAIN in your environment.\"\n        )\n    if not HEXAGON_SDK_ROOT:\n        raise Exception(\n            \" The environment variable HEXAGON_SDK_ROOT is unset. Please export \"\n            + \"HEXAGON_SDK_ROOT in your environment.\"\n        )\n\n    # The AOT C codegen uses TVM runtime functions\n    # (e.g. TVMBackendAllocWorkspace) directly. On Hexagon these calls\n    # should be made using functions pointers provided as __TVM*\n    # variables in the provided context.  This workaround allows the\n    # the TVM runtime symbols to be visible to the compiled shared\n    # library.\n    #\n    # This workaround can be removed when AOT codegen can be done with\n    # LLVM codegen.\n    workaround_link_flags = os.environ.get(\"HEXAGON_SHARED_LINK_FLAGS\")\n    if workaround_link_flags:\n        options.extend(workaround_link_flags.split())\n\n    tvm_dir = pathlib.Path(os.path.dirname(os.path.realpath(__file__))) / \"..\" / \"..\" / \"..\" / \"..\"\n    compute_arch = f\"compute{hexagon_arch}\"\n    compile_options = [\n        f\"-O3\",\n        f\"-I{tvm_dir / 'include'}\",\n        f\"-I{tvm_dir / '3rdparty' / 'dlpack' / 'include'}\",\n        f\"-I{tvm_dir / '3rdparty' / 'dmlc-core' / 'include'}\",\n        f\"-I{pathlib.Path(HEXAGON_SDK_ROOT) / 'rtos' / 'qurt' / compute_arch / 'include'/ 'posix'}\",\n        f\"-I{pathlib.Path(HEXAGON_SDK_ROOT) / 'rtos' / 'qurt' / compute_arch / 'include' / 'qurt'}\",\n        f\"-DDMLC_USE_LOGGING_LIBRARY=<tvm/runtime/logging.h>\",\n        f\"-D_MACH_I32=int\",\n    ]\n\n    # For debugging\n    for path in HEXAGON_SDK_INCLUDE_DIRS:\n        compile_options.append(f\"-I{str(path)}\")\n\n    cross_compile = cc.cross_compiler(compile_func=hexagon_clang_plus())\n    cross_compile.output_format = \"o\"\n    c_files = [str(file) for file in files]\n    cross_compile(str(so_name), c_files, options=compile_options + options)\n\n\ndef export_module(module, out_dir, binary_name=\"test_binary.so\"):\n    \"\"\"Export Hexagon shared object to a file.\"\"\"\n    binary_path = pathlib.Path(out_dir) / binary_name\n    module.save(str(binary_path))\n    return binary_path\n\n\ndef allocate_hexagon_array(\n    dev, tensor_shape=None, dtype=None, data=None, axis_separators=None, mem_scope=None\n):\n    \"\"\"\n    Allocate a hexagon array which could be a 2D array\n    on physical memory defined by axis_separators\n    \"\"\"\n    if tensor_shape is None:\n        assert data is not None, \"Must provide either tensor shape or numpy data array\"\n        tensor_shape = data.shape\n    elif data is not None:\n        assert (\n            tensor_shape == data.shape\n        ), \"Mismatch between provided tensor shape and numpy data array shape\"\n\n    if dtype is None:\n        assert data is not None, \"Must provide either dtype or numpy data array\"\n        dtype = data.dtype.name\n    elif data is not None:\n        assert dtype == data.dtype, \"Mismatch between provided dtype and numpy data array dtype\"\n\n    if axis_separators is None:\n        axis_separators = []\n\n    boundaries = [0, *axis_separators, len(tensor_shape)]\n    physical_shape = [\n        numpy.prod(tensor_shape[dim_i:dim_f])\n        for dim_i, dim_f in zip(boundaries[:-1], boundaries[1:])\n    ]\n\n    arr = tvm.nd.empty(physical_shape, dtype=dtype, device=dev, mem_scope=mem_scope)\n\n    if data is not None:\n        arr.copyfrom(data.reshape(physical_shape))\n\n    return arr._create_view(tensor_shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/hexagon/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Hexagon-specific IR transformations\"\"\"\n\nimport functools as ft\n\nimport tvm\nfrom ..._ffi.registry import register_func\n\n### VTCM\n\nvtcm_size = 4 * 1024 * 1024  # pylint: disable=invalid-name\n\n\n@register_func(\"tvm.info.mem.local.vtcm\")\ndef mem_info_vtcm():\n    # pylint: disable=bad-whitespace\n    return tvm.ir.make_node(\n        \"MemoryInfo\",\n        unit_bits=8,\n        max_num_bits=vtcm_size * 8,\n        max_simd_bits=128 * 8,\n        head_address=tvm.runtime.const(100, \"uint32\"),\n    )\n\n\ndef lower_vtcm_(get_alloc, get_free, def_align, func, mod, ctx):  # pylint: disable=unused-argument\n\n    \"\"\"Generic VTCM allocation\n\n    Parameters\n    ----------\n    get_alloc : function: tir.Allocate, int -> tir.expr (dtype='handle')\n      The VTCM allocation function. It takes an Allocate statement, and the required\n      alignment, and returns a pointer to the allocated VTCM buffer.\n    get_free : function: tir.expr (dtype='handle') -> None\n      The VTCM deallocation function. It takes the address of the allocated buffer\n      and frees it. It returns no value.\n    def_align : int\n      The default alignment that will be passed to the allocation function, if the\n      program does not specify the alignment via a 'storage_alignment' attribute.\n    func : tir.PrimFunc\n    mod : tvm.IRModule\n    ctx : transform.PassContext\n\n    Returns\n    -------\n    stmt : tvm.stmt\n        Transformed function body.\n    \"\"\"\n\n    vtcm_buffers = []\n    alignments = {}\n\n    def buf_align(var):\n        \"\"\"Determine the alignment of the buffer with variable 'var'.\"\"\"\n        if var in alignments and alignments[var]:\n            return alignments[var][-1]\n        return def_align\n\n    def visit(stmt):\n        \"\"\"Collect information about VTCM buffers and their alignments.\"\"\"\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if stmt.attr_key == \"storage_alignment\":\n                if not stmt.node in alignments:\n                    alignments[stmt.node] = []\n                alignments[stmt.node].append(stmt.value)\n        elif isinstance(stmt, tvm.tir.Allocate):\n            scope = stmt.buffer_var.type_annotation.storage_scope\n            if scope == \"local.vtcm\":\n                vtcm_buffers.append(stmt.buffer_var)\n\n    def mutate(stmt):\n        \"\"\"Insert calls to VTCM allocation and deallocation routines.\"\"\"\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if stmt.attr_key == \"storage_alignment\":\n                alignments[stmt.node].pop()\n            return stmt\n        if isinstance(stmt, tvm.tir.Allocate):\n            var = stmt.buffer_var\n            scope = var.type_annotation.storage_scope\n            is_vtcm = var in vtcm_buffers\n            if scope == \"local.vtcm\":\n                vtcm_buffers.pop()\n            if is_vtcm:\n                is_null = tvm.tir.call_intrin(\"bool\", tvm.ir.Op.get(\"tir.isnullptr\"), var)\n                throw_error = tvm.tir.call_intrin(\n                    \"int32\", tvm.ir.Op.get(\"tir.tvm_throw_last_error\")\n                )\n                body_w_free = tvm.tir.SeqStmt([stmt.body, tvm.tir.Evaluate(get_free(var))])\n                body_w_check = tvm.tir.IfThenElse(\n                    is_null, tvm.tir.Evaluate(throw_error), body_w_free\n                )\n                return tvm.tir.LetStmt(\n                    stmt.buffer_var, get_alloc(stmt, buf_align(var)), body_w_check\n                )\n            return stmt\n        raise ValueError(\"Wrong argument type (\" + type(stmt) + \") to 'mutate'\")\n\n    f = func.with_body(\n        tvm.tir.stmt_functor.ir_transform(\n            func.body, visit, mutate, [\"tir.Allocate\", \"tir.AttrStmt\"]\n        )\n    )\n    return f\n\n\ndef ir_lower_vtcm():\n    \"\"\"Create a VTCM lowering pass.\n\n    VTCM memory has to be allocated using special functions.\n    \"\"\"\n\n    def get_alloc(stmt, align):\n        assert isinstance(stmt, tvm.tir.Allocate)\n        return tvm.tir.call_extern(\n            \"handle\",\n            \"HexagonBackendAllocateVTCM\",\n            ft.reduce(lambda x, y: x * y, stmt.extents, 1),\n            align,\n        )\n\n    def get_free(var):\n        return tvm.tir.call_extern(\"handle\", \"HexagonBackendFreeVTCM\", var)\n\n    # pylint: disable=bad-whitespace\n    @tvm.tir.transform.prim_func_pass(opt_level=0, name=\"Lower VTCM pass\")\n    def transform(func, mod, ctx):\n        return lower_vtcm_(get_alloc, get_free, 2048, func, mod, ctx)\n\n    return transform\n\n\ndef ir_lower_vtcm_pass():\n    return [(3, ir_lower_vtcm())]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/miopen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to MIOpen library.\"\"\"\n# pylint: disable-msg=C0103\nimport ctypes\nimport numpy as np\nimport tvm\nimport tvm._ffi\n\nfrom tvm import te\n\n\ndef _get_np_int32_array_handle(arr):\n    \"\"\"Return a void_p handle for a numpy array\n\n    Parameters\n    ----------\n    arr: numpy.NDArray\n        source numpy array\n\n    Returns\n    -------\n    ptr:  ctypes.c_void_p\n        pointer to the data\n    \"\"\"\n    assert arr.dtype == np.int32\n    ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))\n    return ctypes.cast(ptr, ctypes.c_void_p)\n\n\ndef conv2d_forward(\n    x,\n    w,\n    stride_h=1,\n    stride_w=1,\n    pad_h=0,\n    pad_w=0,\n    dilation_h=1,\n    dilation_w=1,\n    conv_mode=0,\n    data_type=1,\n    group_count=1,\n):\n    \"\"\"Create an extern op that compute 2D convolution with MIOpen\n\n    Parameters\n    ----------\n    x: Tensor\n        input feature map\n    w: Tensor\n        convolution weight\n    stride_h: int\n        height stride\n    stride_w: int\n        width stride\n    pad_h: int\n        height pad\n    pad_w: int\n        weight pad\n    dilation_h: int\n        height dilation\n    dilation_w: int\n        width dilation\n    conv_mode: int\n        0: miopenConvolution\n        1: miopenTranspose\n    data_type: int\n        0: miopenHalf (fp16)\n        1: miopenFloat (fp32)\n    group_count: int\n        number of groups\n    Returns\n    -------\n    y: Tensor\n        The result tensor\n    \"\"\"\n    assert 0 <= conv_mode <= 2, \"0: miopenConvolution / 1: miopenTranspose / 2: miopenGroupConv\"\n    if group_count > 1:\n        conv_mode = 2\n    oshape = np.zeros((len(x.shape)), dtype=np.int32)\n    xshape = x.shape\n    wshape = w.shape\n    setup_func = tvm._ffi.get_global_func(\"tvm.contrib.miopen.conv2d.setup\")\n    algo = setup_func(\n        conv_mode,\n        data_type,\n        pad_h,\n        pad_w,\n        stride_h,\n        stride_w,\n        dilation_h,\n        dilation_w,\n        xshape[0].value,\n        xshape[1].value,\n        xshape[2].value,\n        xshape[3].value,\n        wshape[0].value,\n        wshape[1].value,\n        wshape[2].value,\n        wshape[3].value,\n        group_count,\n        _get_np_int32_array_handle(oshape),\n    )\n\n    return te.extern(\n        list(oshape),\n        [x, w],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.miopen.conv2d.forward\",\n            conv_mode,\n            data_type,\n            pad_h,\n            pad_w,\n            stride_h,\n            stride_w,\n            dilation_h,\n            dilation_w,\n            algo,\n            ins[0],\n            ins[1],\n            outs[0],\n        ),\n        name=\"y\",\n    )\n\n\ndef softmax(x, axis=-1):\n    \"\"\"Compute softmax with MIOpen\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        The input tensor\n\n    axis : int\n        The axis to compute softmax over\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n        The result tensor\n    \"\"\"\n    return te.extern(\n        x.shape,\n        [x],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.miopen.softmax.forward\", ins[0], outs[0], axis\n        ),\n        name=\"y\",\n    )\n\n\ndef log_softmax(x, axis=-1):\n    \"\"\"Compute log softmax with MIOpen\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        The input tensor\n\n    axis : int\n        The axis to compute log softmax over\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n        The result tensor\n    \"\"\"\n    return te.extern(\n        x.shape,\n        [x],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.miopen.log_softmax.forward\", ins[0], outs[0], axis\n        ),\n        name=\"y\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/mkl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to BLAS libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef matmul(lhs, rhs, transa=False, transb=False, **kwargs):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with CrhsLAS\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.mkl.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n\n\ndef matmul_u8s8s32(lhs, rhs, transa=False, transb=False, **kwargs):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with CrhsLAS\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.mkl.matmul_u8s8s32\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n\n\ndef batch_matmul(lhs, rhs, transa=False, transb=False, iterative=False, **kwargs):\n    \"\"\"Create an extern op that compute batched matrix mult of A and rhs with mkl\n    This function serves as an example on how to call external libraries.\n\n    Parameters\n    ----------\n    lhs: Tensor\n        The left matrix operand\n    rhs: Tensor\n        The right matrix operand\n    transa: bool\n        Whether transpose lhs\n    transb: bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C: Tensor\n        The result tensor.\n    \"\"\"\n    b = te.max(lhs.shape[0], rhs.shape[0])\n    n = lhs.shape[2] if transa else lhs.shape[1]\n    m = rhs.shape[1] if transb else rhs.shape[2]\n    return te.extern(\n        (b, n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.mkl.batch_matmul\"\n            if not iterative\n            else \"tvm.contrib.mkl.batch_matmul_iterative\",\n            ins[0],\n            ins[1],\n            outs[0],\n            transa,\n            transb,\n        ),\n        name=\"C\",\n        **kwargs,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/mps.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to MPS libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\n# pylint: disable=C0103,W0612\n\n\ndef matmul(lhs, rhs, transa=False, transb=False):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with CrhsLAS\n\n    This function serves as an example on how to calle external libraries.\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left matrix operand\n    rhs : Tensor\n        The right matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    m = lhs.shape[0] if transa is False else lhs.shape[1]\n    n = rhs.shape[1] if transb is False else rhs.shape[0]\n    if transa:\n        m = b\n    if transb:\n        n = c\n    return te.extern(\n        (m, n),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.mps.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n    )\n\n\ndef conv2d(data, weight, pad=\"SAME\", stride=1):\n    \"\"\"\n    Create an extern op that compute data * weight and return result in output\n\n    Parameters:\n    ----------\n    data: Tensor\n        The input data, format NHWC\n    weight: Tensor\n        The conv weight, format output_feature * kH * kW * input_feature\n    pad: str\n        Padding method, 'SAME' or 'VALID'\n    stride: int\n        convolution stride\n\n    Returns\n    -------\n    output: Tensor\n        The result tensor\n    \"\"\"\n    n, hi, wi, ci = data.shape\n    co, kh, kw, ciw = weight.shape\n    padding = 0 if pad == \"SAME\" else 1\n    ho = hi // stride\n    wo = wi // stride\n\n    return te.extern(\n        (n, ho, wo, co),\n        [data, weight],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.mps.conv2d\", ins[0], ins[1], outs[0], padding, stride\n        ),\n        name=\"C\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/mxnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"MXNet bridge wrap Function MXNet's async function.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm._ffi.registry\nimport tvm.runtime._ffi_api\nfrom tvm.runtime import Module\n\n# pylint: disable=invalid-name\n_wrap_async = None\n\n\ndef to_mxnet_func(func, const_loc=None):\n    \"\"\"Wrap a TVM function as MXNet function\n\n    MXNet function runs asynchrously via its engine.\n\n    Parameters\n    ----------\n    func : Function\n        A TVM function that can take positional arguments\n\n    const_loc : list of int\n        List of integers indicating the argument position\n        of read only NDArray argument.\n        The NDArray argument location that are not annotated\n        will be viewed as mutable arrays in MXNet's engine.\n\n    Returns\n    -------\n    async_func : Function\n        A function that can take MXNet NDArray as argument\n        in places that used to expect TVM NDArray.\n        Run asynchrously in MXNet's async engine.\n    \"\"\"\n    # only import mxnet when wrap get called.\n    # pylint: disable=import-self, import-outside-toplevel\n    import mxnet\n\n    if isinstance(func, Module):\n        func = func.entry_func\n\n    def _get_bridge_func():\n        \"\"\"Get MXNet bridge function\"\"\"\n        if not mxnet.base._LIB.MXTVMBridge:\n            raise RuntimeError(\n                \"MXTVMBridge not exist in mxnet package,\" \" please update to latest version\"\n            )\n\n        fdict = tvm._ffi.registry.extract_ext_funcs(mxnet.base._LIB.MXTVMBridge)\n        ret = fdict[\"WrapAsyncCall\"]\n        ret.is_global = True\n        return ret\n\n    global _wrap_async\n\n    if _wrap_async is None:\n        # Register extension type in first time\n        _wrap_async = _get_bridge_func()\n        tvm._ffi.registry.register_extension(mxnet.nd.NDArray)\n\n    const_loc = const_loc if const_loc else []\n    return _wrap_async(func, tvm.runtime._ffi_api.TVMSetStream, len(const_loc), *const_loc)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/ndk.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Util to invoke NDK compiler toolchain.\"\"\"\n# pylint: disable=invalid-name\nfrom __future__ import absolute_import as _abs\n\nimport subprocess\nimport os\nfrom .._ffi.base import py_str\nfrom .cc import get_target_by_dump_machine\n\n\ndef create_shared(output, objects, options=None):\n    \"\"\"Create shared library.\n\n    Parameters\n    ----------\n    output : str\n        The target shared library.\n\n    objects : list\n        List of object files.\n\n    options : list of str, optional\n        The additional options.\n    \"\"\"\n    if \"TVM_NDK_CC\" not in os.environ:\n        raise RuntimeError(\n            \"Require environment variable TVM_NDK_CC\" \" to be the NDK standalone compiler\"\n        )\n    compiler = os.environ[\"TVM_NDK_CC\"]\n    cmd = [compiler]\n    cmd += [\"-o\", output]\n\n    if isinstance(objects, str):\n        cmd += [objects]\n    else:\n        cmd += objects\n\n    options = options if options else [\"-shared\", \"-fPIC\", \"-lm\"]\n    cmd += options\n\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n\n# assign output format\ncreate_shared.output_format = \"so\"\ncreate_shared.get_target_triple = (\n    get_target_by_dump_machine(os.environ[\"TVM_NDK_CC\"]) if \"TVM_NDK_CC\" in os.environ else None\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/nnpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to NNPACK libraries.\"\"\"\nimport tvm\nfrom tvm import te\nimport tvm._ffi\n\n\ndef is_available():\n    \"\"\"Check whether NNPACK is available, that is, `nnp_initialize()`\n    returns `nnp_status_success`.\n    \"\"\"\n    return _initialize() == 0\n\n\ndef fully_connected_inference(lhs, rhs, nthreads=1):\n    \"\"\"Create an extern op that compute fully connected of 1D tensor lhs and\n    2D tensor rhs with nnpack.\n\n    Parameters\n    ----------\n    lhs : Tensor\n        lhs 1D array input[input_channels] of FP32 elements\n    rhs : Tensor\n        lhs 2D matrix kernel[output_channels][input_channels] of FP32 elements\n\n    Returns\n    -------\n    C : Tensor\n        lhs 1D array out[output_channels] of FP32 elements.\n    \"\"\"\n    m = rhs.shape[0]\n    return te.extern(\n        (m,),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.nnpack.fully_connected_inference\", ins[0], ins[1], outs[0], nthreads\n        ),\n        name=\"C\",\n    )\n\n\nclass ConvolutionAlgorithm:\n    AUTO = 0\n    FFT_8x8 = 1\n    FFT_16x16 = 2\n    WT_8x8 = 3\n    IMPLICIT_GEMM = 4\n    DIRECT = 5\n    WT_8x8_FP16 = 6\n\n\nclass ConvolutionTransformStrategy:\n    COMPUTE = 1\n    PRECOMPUTE = 2\n\n\ndef convolution_inference(\n    data, kernel, bias, padding, stride, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO\n):\n    \"\"\"Create an extern op to do inference convolution of 4D tensor data and\n    4D tensor kernel and 1D tensor bias with nnpack.\n\n    Parameters\n    ----------\n    data : Tensor\n        data 4D tensor input[batch][input_channels][input_height][input_width] of\n        FP32 elements.\n    kernel : Tensor\n        kernel 4D tensor kernel[output_channels][input_channels][kernel_height]\n        [kernel_width] of FP32 elements.\n    bias : Tensor\n        bias 1D array bias[output_channels][input_channels][kernel_height]\n        [kernel_width] of FP32 elements.\n    padding : list\n        padding A 4-dim list of [pad_top, pad_bottom, pad_left, pad_right],\n        which indicates the padding around the feature map.\n    stride : list\n        stride A 2-dim list of [stride_height, stride_width], which indicates\n        the stride.\n\n    Returns\n    -------\n    output : Tensor\n        output 4D tensor output[batch][output_channels][output_height][output_width]\n        of FP32 elements.\n    \"\"\"\n\n    assert isinstance(padding, list) and len(padding) == 4\n    assert isinstance(stride, list) and len(stride) == 2\n    batch, _, input_height, input_width = data.shape\n    output_channels, _, kernel_height, kernel_width = kernel.shape\n    idxdiv = te.indexdiv\n    output_height = idxdiv(input_height + padding[0] + padding[1] - kernel_height, stride[0]) + 1\n    output_width = idxdiv(input_width + padding[0] + padding[1] - kernel_width, stride[1]) + 1\n\n    return te.extern(\n        (batch, output_channels, output_height, output_width),\n        [data, kernel, bias] if bias is not None else [data, kernel],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.nnpack.convolution_inference\",\n            ins[0],\n            ins[1],\n            ins[2] if bias is not None else 0,\n            outs[0],\n            padding[0],\n            padding[1],\n            padding[2],\n            padding[3],\n            stride[0],\n            stride[1],\n            nthreads,\n            algorithm,\n        ),\n        name=\"C\",\n    )\n\n\ndef convolution_inference_without_weight_transform(\n    data, transformed_kernel, bias, padding, stride, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO\n):\n    \"\"\"Create an extern op to do inference convolution of 4D tensor data and\n    4D pre-transformed tensor kernel and 1D tensor bias with nnpack.\n\n    Parameters\n    ----------\n    data : Tensor\n        data 4D tensor input[batch][input_channels][input_height][input_width] of\n        FP32 elements.\n    transformed_kernel : Tensor\n        transformed_kernel 4D tensor kernel[output_channels][input_channels][tile]\n        [tile] of FP32 elements.\n    bias : Tensor\n        bias 1D array bias[output_channels][input_channels][kernel_height]\n        [kernel_width] of FP32 elements.\n    padding : list\n        padding A 4-dim list of [pad_top, pad_bottom, pad_left, pad_right],\n        which indicates the padding around the feature map.\n    stride : list\n        stride A 2-dim list of [stride_height, stride_width], which indicates\n        the stride.\n\n    Returns\n    -------\n    output : Tensor\n        output 4D tensor output[batch][output_channels][output_height][output_width]\n        of FP32 elements.\n    \"\"\"\n\n    assert algorithm in (ConvolutionAlgorithm.WT_8x8, ConvolutionAlgorithm.WT_8x8_FP16)\n    assert isinstance(padding, list) and len(padding) == 4\n    assert isinstance(stride, list) and len(stride) == 2\n    batch, _, input_height, input_width = data.shape\n    output_channels, _, _, _ = transformed_kernel.shape\n    kernel_height, kernel_width = (3, 3)\n    idxdiv = te.indexdiv\n    output_height = idxdiv(input_height + padding[0] + padding[1] - kernel_height, stride[0]) + 1\n    output_width = idxdiv(input_width + padding[0] + padding[1] - kernel_width, stride[1]) + 1\n\n    return te.extern(\n        (batch, output_channels, output_height, output_width),\n        [data, transformed_kernel, bias] if bias is not None else [data, transformed_kernel],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.nnpack.convolution_inference_without_weight_transform\",\n            ins[0],\n            ins[1],\n            ins[2] if bias is not None else 0,\n            outs[0],\n            padding[0],\n            padding[1],\n            padding[2],\n            padding[3],\n            stride[0],\n            stride[1],\n            nthreads,\n            algorithm,\n        ),\n        name=\"C\",\n        dtype=\"float32\",\n    )\n\n\ndef convolution_inference_weight_transform(\n    kernel, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO, dtype=\"float32\"\n):\n    \"\"\"Create an extern op to do inference convolution of 3D tensor data and\n    4D tensor kernel and 1D tensor bias with nnpack.\n\n    Parameters\n    ----------\n    kernel : Tensor\n        kernel 4D tensor kernel[output_channels][input_channels][kernel_height]\n        [kernel_width] of FP32 elements.\n\n    Returns\n    -------\n    output : Tensor\n        output 4D tensor output[output_channels][input_channels][tile][tile]\n        of FP32 elements.\n    \"\"\"\n    assert algorithm in (ConvolutionAlgorithm.WT_8x8, ConvolutionAlgorithm.WT_8x8_FP16)\n    output_channels, input_channels, _, _ = kernel.shape\n    transform_tile_size = 8\n    if not isinstance(dtype, str):\n        dtype = dtype.dtype\n    return te.extern(\n        (output_channels, input_channels, transform_tile_size, transform_tile_size),\n        [kernel],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.nnpack.convolution_inference_weight_transform\",\n            ins[0],\n            outs[0],\n            nthreads,\n            algorithm,\n        ),\n        name=\"transform_kernel\",\n        dtype=dtype,\n    )\n\n\ntvm._ffi._init_api(\"tvm.contrib.nnpack\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/nvcc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Utility to invoke nvcc compiler in the system\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport subprocess\nimport os\nimport warnings\n\nimport tvm._ffi\nfrom tvm.target import Target\n\nfrom . import utils\nfrom .._ffi.base import py_str\n\n\ndef compile_cuda(code, target_format=\"ptx\", arch=None, options=None, path_target=None):\n    \"\"\"Compile cuda code with NVCC from env.\n\n    Parameters\n    ----------\n    code : str\n        The cuda code.\n\n    target_format : str\n        The target format of nvcc compiler.\n\n    arch : str\n        The cuda architecture.\n\n    options : str or list of str\n        The additional options.\n\n    path_target : str, optional\n        Output file.\n\n    Return\n    ------\n    cubin : bytearray\n        The bytearray of the cubin\n    \"\"\"\n    if arch is None:\n        # If None, then it will use `tvm.target.Target.current().arch`.\n        # Target arch could be a str like \"sm_xx\", or a list, such as\n        # [\n        #   \"-gencode\", \"arch=compute_52,code=sm_52\",\n        #   \"-gencode\", \"arch=compute_70,code=sm_70\"\n        # ]\n        compute_version = \"\".join(\n            get_target_compute_version(Target.current(allow_none=True)).split(\".\")\n        )\n        arch = [\"-gencode\", f\"arch=compute_{compute_version},code=sm_{compute_version}\"]\n\n    temp = utils.tempdir()\n    if target_format not in [\"cubin\", \"ptx\", \"fatbin\"]:\n        raise ValueError(\"target_format must be in cubin, ptx, fatbin\")\n    temp_code = temp.relpath(\"my_kernel.cu\")\n    temp_target = temp.relpath(\"my_kernel.%s\" % target_format)\n\n    with open(temp_code, \"w\") as out_file:\n        out_file.write(code)\n\n    file_target = path_target if path_target else temp_target\n    cmd = [\"nvcc\"]\n    cmd += [\"--%s\" % target_format, \"-O3\"]\n    if isinstance(arch, list):\n        cmd += arch\n    elif isinstance(arch, str):\n        cmd += [\"-arch\", arch]\n\n    if options:\n        if isinstance(options, str):\n            cmd += [options]\n        elif isinstance(options, list):\n            cmd += options\n        else:\n            raise ValueError(\"options must be str or list of str\")\n\n    cmd += [\"-o\", file_target]\n    cmd += [temp_code]\n\n    # NOTE: ccbin option can be used to tell nvcc where to find the c++ compiler\n    # just in case it is not in the path. On Windows it is not in the path by default.\n    # However, we cannot use TVM_CXX_COMPILER_PATH because the runtime env.\n    # Because it is hard to do runtime compiler detection, we require nvcc is configured\n    # correctly by default.\n    # if cxx_compiler_path != \"\":\n    #    cmd += [\"-ccbin\", cxx_compiler_path]\n\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = code\n        msg += \"\\nCompilation error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n    with open(file_target, \"rb\") as f:\n        data = bytearray(f.read())\n        if not data:\n            raise RuntimeError(\"Compilation error: empty result is generated\")\n        return data\n\n\ndef find_cuda_path():\n    \"\"\"Utility function to find cuda path\n\n    Returns\n    -------\n    path : str\n        Path to cuda root.\n    \"\"\"\n    if \"CUDA_PATH\" in os.environ:\n        return os.environ[\"CUDA_PATH\"]\n    cmd = [\"which\", \"nvcc\"]\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    out = py_str(out)\n    if proc.returncode == 0:\n        return os.path.realpath(os.path.join(str(out).strip(), \"../..\"))\n    cuda_path = \"/usr/local/cuda\"\n    if os.path.exists(os.path.join(cuda_path, \"bin/nvcc\")):\n        return cuda_path\n    raise RuntimeError(\"Cannot find cuda path\")\n\n\ndef get_cuda_version(cuda_path=None):\n    \"\"\"Utility function to get cuda version\n\n    Parameters\n    ----------\n    cuda_path : Optional[str]\n\n        Path to cuda root.  If None is passed, will use\n        `find_cuda_path()` as default.\n\n    Returns\n    -------\n    version : float\n        The cuda version\n\n    \"\"\"\n    if cuda_path is None:\n        cuda_path = find_cuda_path()\n\n    version_file_path = os.path.join(cuda_path, \"version.txt\")\n    if not os.path.exists(version_file_path):\n        # Debian/Ubuntu repackaged CUDA path\n        version_file_path = os.path.join(cuda_path, \"lib\", \"cuda\", \"version.txt\")\n    try:\n        with open(version_file_path) as f:\n            version_str = f.read().strip().split()[-1]\n            return tuple(int(field) for field in version_str.split(\".\"))\n    except FileNotFoundError:\n        pass\n\n    cmd = [os.path.join(cuda_path, \"bin\", \"nvcc\"), \"--version\"]\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    out = py_str(out)\n    if proc.returncode == 0:\n        release_line = [l for l in out.split(\"\\n\") if \"release\" in l][0]\n        release_fields = [s.strip() for s in release_line.split(\",\")]\n        version_str = [f[1:] for f in release_fields if f.startswith(\"V\")][0]\n        return tuple(int(field) for field in version_str.split(\".\"))\n    raise RuntimeError(\"Cannot read cuda version file\")\n\n\n@tvm._ffi.register_func\ndef tvm_callback_cuda_compile(code):\n    \"\"\"use nvcc to generate fatbin code for better optimization\"\"\"\n    ptx = compile_cuda(code, target_format=\"fatbin\")\n    return ptx\n\n\n@tvm._ffi.register_func(\"tvm_callback_libdevice_path\")\ndef find_libdevice_path(arch):\n    \"\"\"Utility function to find libdevice\n\n    Parameters\n    ----------\n    arch : int\n        The compute architecture in int\n\n    Returns\n    -------\n    path : str\n        Path to libdevice.\n    \"\"\"\n    cuda_path = find_cuda_path()\n    lib_path = os.path.join(cuda_path, \"nvvm/libdevice\")\n    if not os.path.exists(lib_path):\n        # Debian/Ubuntu repackaged CUDA path\n        lib_path = os.path.join(cuda_path, \"lib/nvidia-cuda-toolkit/libdevice\")\n    selected_ver = 0\n    selected_path = None\n    cuda_ver = get_cuda_version(cuda_path)\n    major_minor = (cuda_ver[0], cuda_ver[1])\n    if major_minor in (\n        (9, 0),\n        (9, 1),\n        (10, 0),\n        (10, 1),\n        (10, 2),\n        (11, 0),\n        (11, 1),\n        (11, 2),\n        (11, 3),\n    ):\n        path = os.path.join(lib_path, \"libdevice.10.bc\")\n    else:\n        for fn in os.listdir(lib_path):\n            if not fn.startswith(\"libdevice\"):\n                continue\n\n            try:\n                # expected pattern: libdevice.${ARCH}.10.bc\n                #             e.g., libdevice.compute_20.10.bc\n                ver = int(fn.split(\".\")[-3].split(\"_\")[-1])\n                if selected_ver < ver <= arch:\n                    selected_ver = ver\n                    selected_path = fn\n            except ValueError:\n                # it can just be `libdevice.10.bc` in CUDA 10\n                selected_path = fn\n\n        if selected_path is None:\n            raise RuntimeError(\"Cannot find libdevice for arch {}\".format(arch))\n        path = os.path.join(lib_path, selected_path)\n    return path\n\n\ndef callback_libdevice_path(arch):\n    try:\n        return find_libdevice_path(arch)\n    except RuntimeError:\n        warnings.warn(\"Cannot find libdevice path\")\n        return \"\"\n\n\ndef get_target_compute_version(target=None):\n    \"\"\"Utility function to get compute capability of compilation target.\n\n    Looks for the target arch in three different places, first in the target input, then the\n    Target.current() scope, and finally the GPU device (if it exists).\n\n    Parameters\n    ----------\n    target : tvm.target.Target, optional\n        The compilation target\n\n    Returns\n    -------\n    compute_version : str\n        compute capability of a GPU (e.g. \"8.6\")\n    \"\"\"\n    # 1. input target object\n    # 2. Target.current()\n    target = target or Target.current()\n    if target and target.arch:\n        major, minor = target.arch.split(\"_\")[1]\n        return major + \".\" + minor\n\n    # 3. GPU compute version\n    if tvm.cuda(0).exist:\n        return tvm.cuda(0).compute_version\n\n    raise ValueError(\n        \"No CUDA architecture was specified or GPU detected.\"\n        \"Try specifying it by adding '-arch=sm_xx' to your target.\"\n    )\n\n\ndef parse_compute_version(compute_version):\n    \"\"\"Parse compute capability string to divide major and minor version\n\n    Parameters\n    ----------\n    compute_version : str\n        compute capability of a GPU (e.g. \"6.0\")\n\n    Returns\n    -------\n    major : int\n        major version number\n    minor : int\n        minor version number\n    \"\"\"\n    split_ver = compute_version.split(\".\")\n    try:\n        major = int(split_ver[0])\n        minor = int(split_ver[1])\n        return major, minor\n    except (IndexError, ValueError) as err:\n        # pylint: disable=raise-missing-from\n        raise RuntimeError(\"Compute version parsing error: \" + str(err))\n\n\ndef have_fp16(compute_version):\n    \"\"\"Either fp16 support is provided in the compute capability or not\n\n    Parameters\n    ----------\n    compute_version: str\n        compute capability of a GPU (e.g. \"6.0\")\n    \"\"\"\n    major, minor = parse_compute_version(compute_version)\n    # fp 16 support in reference to:\n    # https://docs.nvidia.com/cuda/cuda-c-programming-guide/#arithmetic-instructions\n    if major == 5 and minor == 3:\n        return True\n    if major >= 6:\n        return True\n\n    return False\n\n\ndef have_int8(compute_version):\n    \"\"\"Either int8 support is provided in the compute capability or not\n\n    Parameters\n    ----------\n    compute_version : str\n        compute capability of a GPU (e.g. \"6.1\")\n    \"\"\"\n    major, _ = parse_compute_version(compute_version)\n    if major >= 6:\n        return True\n\n    return False\n\n\ndef have_tensorcore(compute_version=None, target=None):\n    \"\"\"Either TensorCore support is provided in the compute capability or not\n\n    Parameters\n    ----------\n    compute_version : str, optional\n        compute capability of a GPU (e.g. \"7.0\").\n\n    target : tvm.target.Target, optional\n        The compilation target, will be used to determine arch if compute_version\n        isn't specified.\n    \"\"\"\n    if compute_version is None:\n        if tvm.cuda(0).exist:\n            compute_version = tvm.cuda(0).compute_version\n        else:\n            if target is None or \"arch\" not in target.attrs:\n                warnings.warn(\n                    \"Tensorcore will be disabled due to no CUDA architecture specified.\"\n                    \"Try specifying it by adding '-arch=sm_xx' to your target.\"\n                )\n                return False\n            compute_version = target.attrs[\"arch\"]\n            # Compute version will be in the form \"sm_{major}{minor}\"\n            major, minor = compute_version.split(\"_\")[1]\n            compute_version = major + \".\" + minor\n    major, _ = parse_compute_version(compute_version)\n    if major >= 7:\n        return True\n\n    return False\n\n\ndef have_cudagraph():\n    \"\"\"Either CUDA Graph support is provided\"\"\"\n    try:\n        cuda_ver = get_cuda_version()\n        if cuda_ver < (10, 0):\n            return False\n        return True\n    except RuntimeError:\n        return False\n\n\ndef have_bf16(compute_version):\n    \"\"\"Either bf16 support is provided in the compute capability or not\n\n    Parameters\n    ----------\n    compute_version : str\n        compute capability of a GPU (e.g. \"8.0\")\n    \"\"\"\n    major, _ = parse_compute_version(compute_version)\n    if major >= 8:\n        return True\n\n    return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/peak.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"measure bandwidth and compute peak\"\"\"\n\nimport logging\nimport tvm\nfrom tvm import te\nfrom tvm.target import Target\nfrom . import utils\nfrom .. import rpc\n\n\ndef _convert_to_remote(func, remote):\n    \"\"\"convert module function to remote rpc function\"\"\"\n    temp = utils.tempdir()\n    path_dso = temp.relpath(\"tmp_func.tar\")\n    func.export_library(path_dso)\n\n    remote.upload(path_dso)\n    func = remote.load_module(\"tmp_func.tar\")\n    return func\n\n\ndef measure_bandwidth_sum(\n    total_item,\n    item_per_thread,\n    stride,\n    base_type,\n    bits,\n    lanes,\n    target,\n    target_host,\n    remote,\n    dev,\n    n_times,\n):\n    \"\"\"measure memory bandwidth of gpu by product reduction for a given type\n\n    The IR for measurement is\n\n    for each thread\n        for i in 1..num_per_thread:\n            y[global_id] = y[global_id] * x[base + i * stride]\n\n    Parameters\n    ----------\n    total_item: int\n        number of elements in input array\n    item_per_thread: int\n        number of elements each thread accumulates\n    stride: int\n        stride in memory access\n    base_type: str\n        can be \"int\", \"float\"\n    bits: int\n        can be 16, 32\n    lanes: int\n       lane of the vector type, can be 1, 2, 4, 8, 16\n    target: :any:`tvm.target.Target`\n        the target and option of the compilation.\n    target_host : str or :any:`tvm.target.Target`\n        host compilation target\n    dev: Device\n        the device of array\n    remote: tvm.rpc.RPCSession\n        remote rpc session\n    n_times: int\n        number of runs for taking mean\n\n    Returns\n    -------\n    GBPS: float\n         gigabyte per second\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    n, m = total_item, item_per_thread\n    n //= lanes\n\n    base_type = str(base_type) + str(bits)\n    dtype = base_type if lanes == 1 else base_type + \"x\" + str(lanes)\n\n    k = te.reduce_axis((0, m), name=\"k\")\n\n    x = te.placeholder((n,), dtype=dtype, name=\"x\")\n    op = te.comm_reducer(lambda x, y: x * y, lambda t: tvm.tir.const(1, dtype=t), name=\"sum\")\n    y = te.compute(\n        (n // m,), lambda i: op(x[i // stride * stride * m + i % stride + k * stride], axis=k)\n    )\n    s = te.create_schedule(y.op)\n\n    yo, yi = s[y].split(y.op.axis[0], target.max_num_threads)\n    s[y].bind(yo, te.thread_axis(\"blockIdx.x\"))\n    s[y].bind(yi, te.thread_axis(\"threadIdx.x\"))\n    s[y].unroll(k)\n\n    try:\n        func = tvm.build(s, [x, y], target)\n\n        x = tvm.nd.empty((n,), dtype=dtype, device=dev)\n        y = tvm.nd.empty((n // m,), dtype=dtype, device=dev)\n\n        func = _convert_to_remote(func, remote)\n        time_f = func.time_evaluator(func.entry_name, dev, number=n_times)\n        time = time_f(x, y).mean\n    except tvm._ffi.base.TVMError:\n        # build error (occur when device does not support half)\n        return -1\n\n    return 1.0 * (total_item * bits / 8) / 1e9 / time\n\n\ndef measure_bandwidth_all_types(\n    total_item, item_per_thread, n_times, target, target_host, remote, dev, verbose=True\n):\n    \"\"\"measure memory bandwidth for all types\n\n    Parameters\n    ----------\n    total_item: int\n        number of elements in input array\n    item_per_thread: int\n        number of elements each thread accmulates\n    n_times: int\n        number of runs for averaging\n    target: :any:`tvm.target.Target`\n        the target and option of the compilation.\n    target_host : str or :any:`tvm.target.Target`\n        host compilation target\n    remote: tvm.rpc.RPCSession\n        remote rpc session\n    dev: Device\n        the device of array\n    verbose: bool\n        whether outputs immediate result\n\n    Returns\n    -------\n    result: list\n        a list of (type_name, GBPS) pairs\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n    max_threads = target.max_num_threads\n\n    result = []\n    for base_type in [\"float\"]:\n        for bits in [32]:\n            for lanes in [1, 2, 4, 8, 16]:\n                max_speed = -1e9\n                # try different strides\n                for stride in [max_threads, total_item // (lanes * item_per_thread)]:\n                    speed = measure_bandwidth_sum(\n                        total_item,\n                        item_per_thread,\n                        stride,\n                        base_type,\n                        bits,\n                        lanes,\n                        target,\n                        target_host,\n                        remote,\n                        dev,\n                        n_times,\n                    )\n                    max_speed = max(max_speed, speed)\n                type_name = base_type + str(bits)\n                result.append([\"%sx%d\" % (type_name, lanes), max_speed])\n                if verbose:\n                    logging.info(\"\\t%-10s %.2f GBPS\", result[-1][0], result[-1][1])\n    return result\n\n\ndef measure_compute_mad(\n    total_item, item_per_thread, base_type, bits, lanes, target, target_host, remote, dev, n_times\n):\n    \"\"\"measure peak compute speed by computing mad for a type\n\n    The IR for measurement is\n\n    for each thread\n        for i in 1..item_per_thread\n            x = mad(x, x, y)\n            y = mad(y, y, x)\n\n    Parameters\n    ----------\n    total_item: int\n        number of elements in input array\n    item_per_thread: int\n        number of operations each thread does\n    base_type: str\n        can be \"int\", \"float\"\n    bits: int\n        can be 16, 32\n    lanes: int\n       lane of the vector type, can be 1, 2, 4, 8, 16\n    target: :any:`tvm.target.Target`\n        the target and option of the compilation.\n    target_host : str or :any:`tvm.target.Target`\n        host compilation target\n    remote: tvm.rpc.RPCSession\n        if it is not None, use remote rpc session\n    dev: Device\n        the device of array\n    n_times: int\n        number of runs for taking mean\n\n    Returns\n    -------\n    GOPS: float\n         giga operation per second\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    n = total_item\n\n    if bits >= 64 or lanes >= 16:\n        n //= 2\n\n    max_threads = target.max_num_threads\n\n    base_type = str(base_type) + str(bits)\n    dtype = base_type if lanes == 1 else base_type + \"x\" + str(lanes)\n\n    def extern(ins, outs):\n        # pylint: disable=unused-argument\n        \"\"\"construct measurement function by building IR directly\"\"\"\n        ib = tvm.tir.ir_builder.create()\n\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n\n        ib.scope_attr(bx, \"thread_extent\", n // max_threads)\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n\n        idx = bx.var * max_threads + tx.var\n\n        a = ib.allocate(dtype, (1), name=\"a\", scope=\"local\")\n        b = ib.allocate(dtype, (1), name=\"b\", scope=\"local\")\n\n        a[0] = outs[0].vload(idx, dtype)\n        b[0] = outs[0].vload(idx, dtype)\n\n        if base_type.find(\"float\") != -1:\n\n            def mad_func(x, y):\n                return x * x + y\n\n        else:\n\n            def mad_func(x, y):\n                return y * y + x\n\n        for _ in range(item_per_thread // 4 // lanes):\n            a[0] = mad_func(a[0], b[0])\n            b[0] = mad_func(b[0], a[0])\n\n        ib.emit(outs[0].vstore(idx, b[0]))\n        return ib.get()\n\n    y = te.extern((n,), [], extern, name=\"y\", dtype=dtype)\n    s = te.create_schedule(y.op)\n\n    try:\n        func = tvm.build(s, [y], target)\n        func = _convert_to_remote(func, remote)\n        time_f = func.time_evaluator(func.entry_name, dev, number=n_times)\n        y = tvm.nd.empty((n,), dtype=dtype, device=dev)\n        time = time_f(y).mean\n    except tvm._ffi.base.TVMError:\n        # build error (occur when device does not support half)\n        return -1\n\n    return 1.0 * (n * item_per_thread) / 1e9 / time\n\n\ndef measure_compute_all_types(\n    total_item, item_per_thread, n_times, target, target_host, remote, dev, verbose=True\n):\n    \"\"\"measure peak flops for all types\n\n    Parameters\n    ----------\n    total_item: int\n        number of elements in input array\n    item_per_thread: int\n        number of elements each thread accmulates\n    n_times: int\n        number of runs for averaging\n    target: :any:`tvm.target.Target`\n        the target and option of the compilation.\n    target_host : str or :any:`tvm.target.Target`\n        host compilation target\n    remote: tvm.rpc.RPCSession\n        remote rpc session\n    dev: Device\n        the device of array\n    verbose: bool\n        whether outputs immediate result\n\n    Returns\n    -------\n    result: list\n        a list of (type_name, GFLOPS/GIOPS) pairs\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    result = []\n    for base_type in [\"float\", \"int\"]:\n        for bits in [16, 32, 64]:\n            for lanes in [1, 2, 4, 8, 16]:\n                if base_type == \"int\" and bits != 32:  # only measure int32\n                    continue\n\n                max_speed = -1e9\n                for per_thread in [item_per_thread // 2, item_per_thread, item_per_thread * 2]:\n                    speed = measure_compute_mad(\n                        total_item,\n                        per_thread,\n                        base_type,\n                        bits,\n                        lanes,\n                        target,\n                        target_host,\n                        remote,\n                        dev,\n                        n_times,\n                    )\n                    max_speed = max(max_speed, speed)\n                type_name = base_type + str(bits)\n                result.append([\"%sx%d\" % (type_name, lanes), max_speed])\n\n                unit = \"GFLOPS\" if base_type == \"float\" else \"GIOPS\"\n\n                if verbose:\n                    logging.info(\"\\t%-10s %.2f %s\", result[-1][0], result[-1][1], unit)\n\n    return result\n\n\ndef measure_peak_all(target, target_host, host, port):\n    \"\"\"measure memory bandwidth and peak compute for gpu devices\n\n    Parameters\n    ----------\n    target: str or :any:`tvm.target.Target`\n    target_host: str\n    host: str\n    port: int\n    \"\"\"\n\n    target, target_host = Target.canon_target_and_host(target, target_host)\n    remote = rpc.connect(host, port)\n    n_times = 20\n\n    bandwidth_total_item = 1 << 25\n    bandwidth_item_per_thread = 32\n\n    compute_total_item = 1 << 21\n    compute_item_per_thread = 4096\n\n    if str(target).startswith(\"opencl\"):\n        dev = remote.cl()\n    elif str(target).startswith(\"cuda\"):\n        dev = remote.cuda()\n    elif str(target).startswith(\"metal\"):\n        dev = remote.metal()\n    else:\n        raise RuntimeError(\"Unsupported target\")\n\n    logging.info(\"========== measure memory bandwidth ==========\")\n    measure_bandwidth_all_types(\n        bandwidth_total_item, bandwidth_item_per_thread, n_times, target, target_host, remote, dev\n    )\n\n    logging.info(\"========== measure peak compute ==========\")\n    measure_compute_all_types(\n        compute_total_item, compute_item_per_thread, n_times, target, target_host, remote, dev\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/pickle_memoize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Memoize result of function via pickle, used for cache testcases.\"\"\"\n# pylint: disable=broad-except,superfluous-parens\nimport os\nimport sys\nimport atexit\nfrom decorator import decorate\nfrom .._ffi.base import string_types\n\ntry:\n    import cPickle as pickle\nexcept ImportError:\n    import pickle\n\n\nclass Cache(object):\n    \"\"\"A cache object for result cache.\n\n    Parameters\n    ----------\n    key: str\n       The file key to the function\n    save_at_exit: bool\n        Whether save the cache to file when the program exits\n    \"\"\"\n\n    cache_by_key = {}\n\n    def __init__(self, key, save_at_exit):\n        cache_dir = \".pkl_memoize_py{0}\".format(sys.version_info[0])\n        try:\n            os.mkdir(cache_dir)\n        except FileExistsError:\n            pass\n        else:\n            self.cache = {}\n        self.path = os.path.join(cache_dir, key)\n        if os.path.exists(self.path):\n            try:\n                self.cache = pickle.load(open(self.path, \"rb\"))\n            except Exception:\n                self.cache = {}\n        else:\n            self.cache = {}\n        self.dirty = False\n        self.save_at_exit = save_at_exit\n\n    def save(self):\n        if self.dirty:\n            print(\"Save memoize result to %s\" % self.path)\n            with open(self.path, \"wb\") as out_file:\n                pickle.dump(self.cache, out_file, pickle.HIGHEST_PROTOCOL)\n\n\n@atexit.register\ndef _atexit():\n    \"\"\"Save handler.\"\"\"\n    for value in Cache.cache_by_key.values():\n        if value.save_at_exit:\n            value.save()\n\n\ndef memoize(key, save_at_exit=False):\n    \"\"\"Memoize the result of function and reuse multiple times.\n\n    Parameters\n    ----------\n    key: str\n        The unique key to the file\n    save_at_exit: bool\n        Whether save the cache to file when the program exits\n\n    Returns\n    -------\n    fmemoize : function\n        The decorator function to perform memoization.\n    \"\"\"\n\n    def _register(f):\n        \"\"\"Registration function\"\"\"\n        allow_types = (string_types, int, float, tuple)\n        fkey = key + \".\" + f.__name__ + \".pkl\"\n        if fkey not in Cache.cache_by_key:\n            Cache.cache_by_key[fkey] = Cache(fkey, save_at_exit)\n        cache = Cache.cache_by_key[fkey]\n        cargs = tuple(x.cell_contents for x in f.__closure__) if f.__closure__ else ()\n        cargs = (len(cargs),) + cargs\n\n        def _memoized_f(func, *args, **kwargs):\n            assert not kwargs, \"Only allow positional call\"\n            key = cargs + args\n            for arg in key:\n                if isinstance(arg, tuple):\n                    for x in arg:\n                        assert isinstance(x, allow_types)\n                else:\n                    assert isinstance(arg, allow_types)\n            if key in cache.cache:\n                return cache.cache[key]\n            res = func(*args)\n            cache.cache[key] = res\n            cache.dirty = True\n            return res\n\n        return decorate(f, _memoized_f)\n\n    return _register\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/pipeline_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pipeline executor that executes a series of modules in a pipeline fashion.\"\"\"\nimport json\nimport os\nimport time\nfrom tvm import runtime\nfrom tvm._ffi import get_global_func\nfrom tvm.contrib import graph_executor\n\n\ndef pipeline_executor_enabled():\n    \"\"\"Check if the pipeline executor is enabled.\n\n    Return\n    -------\n    enable: bool\n        Return whether the pipeline executor is enabled.\n    \"\"\"\n    return get_global_func(\"tvm.pipeline_executor.create\", allow_missing=True) is not None\n\n\nclass PipelineModule(object):\n    \"\"\"Wrapper of runtime module, caller can use this module to set parameters and get outputs.\n\n    Parameters\n    ----------\n    module : Union[PipelineExecutorFactoryModule, Module]\n        Common interface for pipeline executor factory modules or Module.\n    \"\"\"\n\n    def __init__(self, module):\n        if isinstance(module, PipelineExecutorFactoryModule):\n            self.module = module.get_pipeline_executor_module()\n        else:\n            self.module = module\n        # Get the packed functions from the pipeline executor.\n        self._get_params_group_pipeline_map = self.module[\"get_params_group_pipeline_map\"]\n        self._run = self.module[\"run\"]\n        self._set_param = self.module[\"set_param\"]\n        self._set_input = self.module[\"set_input\"]\n        self._get_input = self.module[\"get_input\"]\n        self._get_output = self.module[\"get_output\"]\n        self._get_num_outputs = self.module[\"get_num_outputs\"]\n        self._get_num_inputs = self.module[\"get_num_inputs\"]\n        self._get_input_pipeline_map = self.module[\"get_input_pipeline_map\"]\n        self._get_pipe_execute_count = self.module[\"get_execute_count\"]\n\n    def run(self):\n        \"\"\"Run the pipeline executor.\"\"\"\n        self._run()\n\n    def get_input_pipeline_map(self, name):\n        \"\"\"Using the \"name\" to get the corresponding subgraph index and also get the \"input name\"\n        of the corresponding subgraph interface.\n        Returns\n        -------\n        input map: Array[str]\n            Returning the index and \"input name\" of the subgraph.\n        \"\"\"\n        return self._get_input_pipeline_map(name)\n\n    def get_params_group_pipeline_map(self, name):\n        \"\"\"Use the name of the parameters group to get the corresponding runtime module index.\n\n        Parameters\n        ----------\n        name: str\n            The parameter group name.\n\n        Returns\n        -------\n        module_index: int\n            The index of the runtime module.\n        \"\"\"\n        return self._get_params_group_pipeline_map(name)\n\n    def set_input(self, key, value):\n        \"\"\"Set the input via input name.\n\n        Parameters\n        ----------\n        key : str\n            The input name\n        value : array_like.\n            The input value\n        \"\"\"\n        self._set_input(key, value)\n\n    def set_params(self, params_group_name, params_data):\n        \"\"\"Set the parameter group value given the parameter group name. Note that the parameter\n        group name is declared in the pipeline executor config.\n\n        Parameters\n        ----------\n        params_group_name : str\n            The parameters group name.\n\n        params_data : Dict[str, NDArray]\n            A map from parameter name to data.\n        \"\"\"\n        if not params_data:\n            raise RuntimeError('\"params_data is empty!\"')\n\n        for key, val in params_data.items():\n            self._set_param(params_group_name, key, val)\n\n    def get_input(self, key):\n        \"\"\"Get the input via an input name.\n        Parameters\n        ----------\n        key : str\n            The input key\n        Returns\n        -------\n        data : NDArray\n            The input data.\n        \"\"\"\n        return self._get_input(key)\n\n    def get_output(self, synchronize=True, sleep_interval=0.001):\n        \"\"\"Get the output.\n        Returns\n        -------\n        data : Array[NDArray]\n            A list of output data.\n        synchronize : BOOL\n            Whether to do a synchronize poll.\n        sleep_interval : Float32\n            When doing the synchronize loop poll, how many seconds the loop should sleep for yield.\n        \"\"\"\n        outputs = []\n        if not synchronize:\n            outputs = self._get_output()\n        else:\n            while not outputs:\n                outputs = self._get_output()\n                time.sleep(sleep_interval)\n\n        return outputs\n\n    @property\n    def num_executing_pipeline(self):\n        \"\"\"Getting the count of running pipeline.\n        Returns\n        -------\n        count : int\n            The count of running pipeline.\n        \"\"\"\n        return self._get_pipe_execute_count()\n\n    @property\n    def num_outputs(self):\n        \"\"\"Get the number of outputs.\n        Returns\n        -------\n        count : int\n            The number of outputs.\n        \"\"\"\n        return self._get_num_outputs()\n\n    @property\n    def num_inputs(self):\n        \"\"\"Get the number of inputs\n        Returns\n        -------\n        count : int\n            The number of inputs\n        \"\"\"\n        return self._get_num_inputs()\n\n    @staticmethod\n    def load_library(config_file_name):\n        \"\"\"Import files to create a pipeline executor.\n\n        Parameters\n        ----------\n        config_file_name : str\n            Path and name of the configuration file, the configuration file contains the\n            disk path of the parameter file, library file, and JSON file.\n        \"\"\"\n        with open(config_file_name, \"r\") as file_handle:\n            config = file_handle.read()\n        config = json.loads(config)\n        if \"load_config\" not in config or \"pipeline_config\" not in config:\n            raise RuntimeError(\n                '\"load_config\" or \"pipeline_config\" is missing in %s' % config_file_name\n            )\n\n        # The config file used to load library, prameters, and JSON files.\n        with open(config[\"load_config\"], \"r\") as file_handle:\n            load_config = file_handle.read()\n\n        # The config file used to load pipeline compute config.\n        with open(config[\"pipeline_config\"], \"r\") as file_handle:\n            pipeline_config = file_handle.read()\n\n        # Load a PipelineExecutor from the disk files.\n        load_library = get_global_func(\"tvm.pipeline_executor.load\", allow_missing=False)\n        module = load_library(load_config, pipeline_config)\n\n        return PipelineModule(module)\n\n\nclass PipelineExecutorFactoryModule(object):\n    \"\"\"Common interface for pipeline executor factory modules.\n\n    Parameters\n    ----------\n    pipeline_mods : List[GraphExecutorFactoryModule]\n        List of GraphExecutorFactoryModule.\n\n    mod_config : Dict[int, Dict[str, Any]]\n        Modules dependency configuration information.\n\n    \"\"\"\n\n    def __init__(self, pipeline_mods, mods_config):\n        self.pipeline_mods = pipeline_mods\n        self.mods_config = mods_config\n        self.module = None\n\n    def get_pipeline_executor_module(self):\n        \"\"\"Get the pipeline executor module.\n\n        Returns\n        -------\n        module : Module\n            Common interface for pipeline executor factory Module.\n        \"\"\"\n        if not self.module:\n            graph_executors, config = self.graph_executor_create(\n                self.pipeline_mods, self.mods_config\n            )\n            self.pipeline_create = get_global_func(\n                \"tvm.pipeline_executor.create\", allow_missing=False\n            )\n            self.module = self.pipeline_create(graph_executors, config)\n        return self.module\n\n    def graph_executor_create(self, pipeline_mods, mod_config):\n        \"\"\"Create graph_executor list and return configuration as a json string.\n\n        Parameters\n        ----------\n        pipeline_mods : List[GraphExecutorFactoryModule]\n          List of GraphExecutorFactoryModule\n\n        mod_config : Dict[str, Any]\n            Modules dependency configuration information.\n\n        Returns\n        -------\n        mods : List[Module]\n            The Module list.\n\n        mod_config : str\n            The Modudle configuration.\n        \"\"\"\n        # Should store modules in the list named 'mods' in index order.\n        mods = [None for _ in range(len(pipeline_mods))]\n        for lib_index in pipeline_mods:\n            pipeline_lib = pipeline_mods[lib_index][\"lib\"]\n            dev = pipeline_mods[lib_index][\"dev\"]\n            lib = graph_executor.GraphModule(pipeline_lib[\"default\"](dev))\n            # Return a module list sorted by lib_index.\n            mods[lib_index] = lib.module\n\n        return mods, json.dumps(mod_config)\n\n    def export_library(self, directory_path):\n        \"\"\"Export the pipeline executor into disk files.\n\n        Parameters\n        ----------\n        directory_path : str\n            Export the files to this directory.\n        \"\"\"\n        if not self.pipeline_mods:\n            raise RuntimeError(\"The pipeline executor has not been initialized.\")\n\n        # Check if the directory_path exists.\n        if not os.path.exists(directory_path):\n            raise RuntimeError(\"The directory {directory_path} does not exist.\")\n        # Create an load configuration.\n        load_config_file_name = \"{}/load_config\".format(directory_path)\n        pipeline_config_file_name = \"{}/pipeline_config\".format(directory_path)\n        config = {}\n        config[\"load_config\"] = load_config_file_name\n        config[\"pipeline_config\"] = pipeline_config_file_name\n        load_config = []\n        # Export the library, JSON, and parameter into files, then export these files path\n        # into a configuration file.\n        for lib_index in self.pipeline_mods:\n            mconfig = {}\n            mconfig[\"mod_idx\"] = lib_index\n            mconfig[\"lib_name\"] = \"{}/lib{}.so\".format(directory_path, lib_index)\n            mconfig[\"json_name\"] = \"{}/json{}\".format(directory_path, lib_index)\n            mconfig[\"params_name\"] = \"{}/params{}\".format(directory_path, lib_index)\n            mconfig[\"dev\"] = \"{},{}\".format(\n                self.pipeline_mods[lib_index][\"dev\"].device_type,\n                self.pipeline_mods[lib_index][\"dev\"].device_id,\n            )\n            # Get the graph, lib, and parameters from GraphExecutorFactoryModule.\n            lib = self.pipeline_mods[lib_index][\"lib\"]\n            # Export the lib, graph, and parameters to disk.\n            if self.pipeline_mods[lib_index][\"export_cc\"]:\n                lib.export_library(\n                    mconfig[\"lib_name\"], cc=self.pipeline_mods[lib_index][\"export_cc\"]\n                )\n            else:\n                lib.export_library(mconfig[\"lib_name\"])\n\n            with open(mconfig[\"json_name\"], \"w\") as file_handle:\n                file_handle.write(lib.graph_json)\n            with open(mconfig[\"params_name\"], \"wb\") as file_handle:\n                file_handle.write(runtime.save_param_dict(lib.params))\n\n            load_config.append(mconfig)\n\n        with open(load_config_file_name, \"w\") as file_handle:\n            json.dump(load_config, file_handle)\n\n        with open(pipeline_config_file_name, \"w\") as file_handle:\n            json.dump(self.mods_config, file_handle)\n\n        config_file_name = \"{}/config\".format(directory_path)\n        with open(config_file_name, \"w\") as file_handle:\n            json.dump(config, file_handle)\n\n        return config_file_name\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/pipeline_executor_build.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pipeline executor that executes a series of modules in a pipeline fashion.\"\"\"\nimport json\nimport os\nimport tvm._ffi\nfrom tvm import relay\nfrom tvm.relay.transform import InferType\nfrom tvm.contrib.pipeline_executor import PipelineExecutorFactoryModule\n\n\ndef pipeline_executor_build_enabled():\n    \"\"\"Check if the pipeline executor build is enabled.\n\n    Return\n    -------\n    enable: bool\n        Return whether the pipeline executor is enabled.\n    \"\"\"\n    return tvm.contrib.pipeline_executor.pipeline_executor_enabled()\n\n\ndef build(pipe_configs):\n    \"\"\"Build modules used in the pipeline executor, then use these modules and configuration\n    to create a pipeline executor.\n\n    Parameters\n    ----------\n    pipe_configs: PipelineConfig\n        Build Configuration information.\n\n    Returns\n    -------\n    ret: PipelineExecutorFactoryModule\n        Common interface for pipeline executor factory modules.\n    \"\"\"\n    libs = {}\n    config = pipe_configs.get_config()\n    if \"module_connection\" not in config:\n        raise RuntimeError('\"module_connection\" is missing')\n    if \"input_connection\" not in config:\n        raise RuntimeError('\"input_connection\" is missing')\n    if \"param_connection\" not in config:\n        raise RuntimeError('\"param_connection\" is missing')\n\n    mod_n_configs = config[\"module_connection\"]\n    config_len = len(mod_n_configs)\n    module_string_config = [{} for _ in range(config_len)]\n    # Use hardware configurations to build backend modules for each subgraph.\n    for ir_mod, mod_config in mod_n_configs.items():\n        pipe_config = mod_config[\"pipeline\"].copy()\n        mod_idx = pipe_config[\"mod_idx\"]\n        dev = mod_config[\"dev\"]\n        target = mod_config[\"target\"]\n        build_func = relay.build\n        # Callers may need to use a customized building function to wrap the pre-building logic\n        # and the backend building logic. For example, in order to support a backend which only\n        # can do \"int8\" computation, the caller may need to merge the \"quantization\" logic\n        # into the building logic to creat a customized building function.\n        if \"build\" in mod_config and mod_config[\"build\"]:\n            build_func = mod_config[\"build\"]\n\n        lib = build_func(\n            ir_mod,\n            target,\n            params=mod_config[\"params\"],\n            target_host=mod_config[\"target_host\"],\n            mod_name=mod_config[\"mod_name\"],\n        )\n\n        pipe_config[\"dev\"] = \"{},{}\".format(dev.device_type, dev.device_id)\n        # Use \"mod_idx\" as the key to create a \"module_connection\" map which is not only\n        # for the module index but also for the module connection used to build the pipeline.\n        module_string_config[mod_idx] = pipe_config\n        libs[mod_idx] = {\n            \"lib\": lib,\n            \"dev\": dev,\n            \"fcompile\": mod_config[\"fcompile\"],\n            \"export_cc\": mod_config[\"export_cc\"],\n        }\n\n    # Creating a text form configuration to record the \"input_connection\" and the\n    # \"module_connection\" information. The \"input_connection\" is used to record the\n    # map of global input and subgraph input, and the \"module_connection\" is used to\n    # record module dependency.\n    string_config = {}\n    string_config[\"param_connection\"] = config[\"param_connection\"]\n    string_config[\"input_connection\"] = config[\"input_connection\"]\n    string_config[\"module_connection\"] = module_string_config\n\n    return PipelineExecutorFactoryModule(libs, string_config)\n\n\ndef export_library(factory, directory_path):\n    \"\"\"Export the pipeline executor into disk files.\n\n    Parameters\n    ----------\n    factory : PipelineExecutorFactoryModule\n        The pipeline executor factory\n    directory_path : str\n        Export the files to this directory.\n    \"\"\"\n    if not factory.pipeline_mods:\n        raise RuntimeError(\"The pipeline executor has not been initialized.\")\n\n    # Check if the directory_path exists.\n    if not directory_path or not os.path.exists(directory_path):\n        raise RuntimeError(\"The directory {directory_path} does not exist.\")\n    # Create an load configuration.\n    load_config_file_name = \"{}/load_config\".format(directory_path)\n    pipeline_config_file_name = \"{}/pipeline_config\".format(directory_path)\n    config = {}\n    config[\"load_config\"] = load_config_file_name\n    config[\"pipeline_config\"] = pipeline_config_file_name\n    load_config = []\n    # Export the library, JSON, and parameter into files, then export these files path\n    # into a configuration file.\n    for lib_index in factory.pipeline_mods:\n        mconfig = {}\n        mconfig[\"mod_idx\"] = lib_index\n        mconfig[\"lib_name\"] = \"{}/lib{}.so\".format(directory_path, lib_index)\n        mconfig[\"json_name\"] = \"{}/json{}\".format(directory_path, lib_index)\n        mconfig[\"params_name\"] = \"{}/params{}\".format(directory_path, lib_index)\n        lib_config = factory.pipeline_mods[lib_index]\n        mconfig[\"dev\"] = \"{},{}\".format(lib_config[\"dev\"].device_type, lib_config[\"dev\"].device_id)\n        fcompile = lib_config[\"fcompile\"]\n        if not fcompile:\n            fcompile = False\n\n        # Get the graph, lib, and parameters from GraphExecutorFactoryModule.\n        lib = factory.pipeline_mods[lib_index][\"lib\"]\n        # Export the lib, graph, and parameters to disk.\n        lib.export_library(mconfig[\"lib_name\"], fcompile)\n        with open(mconfig[\"json_name\"], \"w\") as file_handle:\n            file_handle.write(lib.graph_json)\n        with open(mconfig[\"params_name\"], \"wb\") as file_handle:\n            file_handle.write(relay.save_param_dict(lib.params))\n\n        load_config.append(mconfig)\n\n    with open(load_config_file_name, \"w\") as file_handle:\n        json.dump(load_config, file_handle)\n\n    with open(pipeline_config_file_name, \"w\") as file_handle:\n        json.dump(factory.mods_config, file_handle)\n\n    config_file_name = \"{}/config\".format(directory_path)\n    with open(config_file_name, \"w\") as file_handle:\n        json.dump(config, file_handle)\n\n    return config_file_name\n\n\nclass PipelineConfig(object):\n    \"\"\"Pipeline configuration information, this class contains the DAG that expresses\n    the dependency of each module involved in a pipeline and the parameters for building\n    each module.\n    \"\"\"\n\n    class Binding:\n        \"\"\"This class defines the module connections information.\n        The type can only be \"input\" or \"output\".\n\n        Parameters\n        ----------\n        owner : ModuleWrapper\n            The class who owns this interface.\n\n        io_type : str\n            The I/O type of this interface. It can only be \"input\" or \"output\".\n\n        name : str/integer\n            Name, for input it is string such as \"data0\", for output it is an integer such as 0.\n\n        data_type: TensorType\n            The data type of this interface.\n        \"\"\"\n\n        def __init__(self, owner, io_type, name, data_type=None):\n            self.io_owner = owner\n            self.io_type = io_type\n            self.name = str(name)\n            # Child interfaces that depend on this interface.\n            self.bindings = []\n            # Parents interfaces that this interface depend on.\n            self.parents = []\n\n            self.data_type = data_type\n\n        def get_name(self):\n            # Return name of this interface and the name of owner who owns this interface.\n            owner_name = \"\"\n            if isinstance(self.io_owner, PipelineConfig.ModuleWrapper):\n                owner_name = self.io_owner.name\n\n            return owner_name, self.name\n\n        def get_owner_idx(self):\n            # If the owner is ModuleWrapper return the owner index, if not return 0.\n            if isinstance(self.io_owner, PipelineConfig.ModuleWrapper):\n                return self.io_owner.idx\n\n            return -1\n\n        def is_pipeline_executor_interface(self):\n            \"\"\"The pipeline interface is used to interact with the caller. There are two types\n            of interfaces, one is 'input' another is 'output'. The pipeline input interface\n            is responsible for passing parameters to the internal module interface, and the\n            pipeline output interface is responsible for outputting the results computed by\n            the pipeline executor to the caller.\n            \"\"\"\n            return not isinstance(self.io_owner, PipelineConfig.ModuleWrapper)\n\n        def __repr__(self):\n            # Geting the binding information in the form of text.\n            str_format = \"  |{}: \".format(self.name)\n            for binding in self.bindings:\n                mname, dname = binding.get_name()\n                str_format += \"{0}:{1} \".format(mname, dname)\n\n            return str_format\n\n        def check_binding_dict(self, connection_dict):\n            \"\"\"Checking the binding dictionary.\n            Parameter\n            ---------\n            connection_dict : Dict[str, Any]\n                It is a dictionary of module connections.\n            \"\"\"\n            if \"interface_name\" not in connection_dict:\n                raise RuntimeError('\"inteface_name\" is missing in global config!\"')\n            if \"connection\" not in connection_dict:\n                raise RuntimeError(f'\"connection\" is missing!\"')\n            # The global interface mapping should be one-to-one.\n            if not connection_dict[\"connection\"]:\n                raise RuntimeError(\"The global interface map is empty!\")\n            if len(connection_dict[\"connection\"]) > 1:\n                raise RuntimeError(\"A global interface maps multiple module interfaces!\")\n            if \"mod_idx\" not in connection_dict[\"connection\"][0]:\n                raise RuntimeError('\"mod_idx\" is missing!')\n\n        def get_binding_dict(self):\n            \"\"\"Returning the binding information in the form of dictionary.\n            Returns\n            -------\n            data : Dict[str, Any]\n                The binding information is in the form of dictionary.\n            \"\"\"\n            dict_format = {\"interface_name\": self.name, \"connection\": []}\n            for binding in self.bindings:\n                _, dname = binding.get_name()\n                midx = binding.get_owner_idx()\n                dict_format[\"connection\"].append({\"mod_idx\": midx, \"interface_name\": dname})\n\n            self.check_binding_dict(dict_format)\n            return dict_format\n\n        def check_dag_acyclic(self, start, inputs):\n            \"\"\"This is to check whether the DAG containing these input interfaces is acyclic.\n            Parameters\n            ----------\n            start: ModuleWrapper\n                The starting node of the cycle check algorithm.\n\n            inputs: Binding\n                These interfaces are used to connect to each other to build DAG.\n\n            Return\n            ------\n                Return true if there is no cycle in the DAG.\n            \"\"\"\n            for binding in inputs.values():\n                if start == binding.io_owner:\n                    return False\n                for p in binding.parents:\n                    if not self.check_dag_acyclic(start, p.io_owner.input_bindings.bindings):\n                        return False\n\n            return True\n\n        def connect(self, binding):\n            \"\"\"Connect the current interface to the destination interface.\n            Correct connections are as follows: 1. the pipeline input connected to a module input,\n            2. the module output connected to a pipeline output, 3. the module output connected to\n            a module input.\n\n            Parameters\n            ----------\n            binding: Binding\n                The destination of this connection.\n            \"\"\"\n\n            # Check whether the binding setting is correct or not.\n            if self.io_owner == binding.io_owner:\n                raise RuntimeError(\"Can not bind itself.\")\n\n            if self.io_type == \"param\" and not self.is_pipeline_executor_interface():\n                raise RuntimeError(\n                    'The \"param\" binding can only be used by a pipeline executor interface!'\n                )\n\n            if not self.is_pipeline_executor_interface() and self.io_type == \"input\":\n                raise RuntimeError(\"Module can only bind from output interface!\")\n\n            if self.io_type == \"param\" and binding.io_type != \"param\":\n                raise RuntimeError(\n                    'A global \"param\" interface can only be bind with a module \"param\" interface!'\n                )\n\n            if (\n                not self.is_pipeline_executor_interface()\n                and not binding.is_pipeline_executor_interface()\n                and binding.io_type == \"output\"\n            ):\n                raise RuntimeError(\"Can not bind module output with another module output!\")\n\n            if (\n                not self.is_pipeline_executor_interface()\n                and binding.is_pipeline_executor_interface()\n                and binding.io_type == \"input\"\n            ):\n                raise RuntimeError(\"Can not bind module output with pipeline input!\")\n\n            if self.is_pipeline_executor_interface() and self.io_type == \"output\":\n                raise RuntimeError(\"Global output can not be used as binding start point.\")\n\n            if (\n                self.is_pipeline_executor_interface()\n                and self.io_type == \"input\"\n                and binding.io_type != \"input\"\n            ):\n                raise RuntimeError(\"Global input can only bind with module input.\")\n\n            self.bindings.append(binding)\n            if not self.is_pipeline_executor_interface():\n                # Check whether the data types of the source and destination are the same.\n                if (\n                    isinstance(binding.io_owner, PipelineConfig.ModuleWrapper)\n                    and self.data_type != binding.data_type\n                ):\n                    raise RuntimeError(\n                        f\"Illegal type (%s vs. %s): binding type is not same!\"\n                        % (self.data_type, binding.data_type)\n                    )\n\n                binding.parents.append(self)\n\n                # Do acyclic check after increasing the in-degree of child node by setting\n                # current interface as a parent of the child node.\n\n                if not self.check_dag_acyclic(\n                    binding.io_owner, self.io_owner.input_bindings.bindings\n                ):\n                    raise RuntimeError(\"Illegal connection: Cause a cycle!\")\n\n    class BindingList:\n        \"\"\"Container for bindings(input or output interface).\n\n        Parameters\n        ----------\n        owner : ModuleWrapper/PipelineConfig\n            The owner of this class can be ModuleWrapper or PipelineConfig.\n\n        io_type : str\n            The type of this class can be \"input\" or \"output\".\n        \"\"\"\n\n        def __init__(self, owner, io_type):\n            self.bindings = {}\n            self.io_owner = owner\n            self.binding_type = io_type\n\n        def get_binding_data_type(self, key):\n            if isinstance(self.io_owner, PipelineConfig.ModuleWrapper):\n                return self.io_owner.get_data_type(key, self.binding_type)\n            return None\n\n        def __getitem__(self, key):\n            if key not in self.bindings:\n                data_type = self.get_binding_data_type(key)\n                if not data_type and isinstance(self.io_owner, PipelineConfig.ModuleWrapper):\n                    raise RuntimeError(f\"Can not find {key} in binding list {self.binding_type}.\")\n\n                self.bindings[key] = PipelineConfig.Binding(\n                    self.io_owner, self.binding_type, key, data_type\n                )\n\n            return self.bindings[key]\n\n    class ModuleWrapper:\n        \"\"\"This class is a wrapper representing the module and contains information such as\n        module information, binding information and building information.\n        \"\"\"\n\n        def __init__(self, mod=None):\n            self.target_host = None\n            self.build_func = None\n            self.params = None\n            self.target = None\n            self.fcompile = None\n            self.name = None\n            self.dev = None\n            self.export_cc = None\n            self.cpu_affinity = \"\"\n            self.idx = None\n            self.mod = mod\n            self.input_params = InferType()(mod)[\"main\"].params\n            self.output_type = InferType()(mod)[\"main\"].checked_type.ret_type\n            self.input_bindings = PipelineConfig.BindingList(self, \"input\")\n            self.output_bindings = PipelineConfig.BindingList(self, \"output\")\n            self.param_binding = PipelineConfig.Binding(self, \"param\", \"param\")\n\n        def __eq__(self, other):\n            if isinstance(other, PipelineConfig.ModuleWrapper):\n                return self.mod == other.mod\n\n            return False\n\n        def __getitem__(self, key):\n            if isinstance(key, str):\n                if key == \"input\":\n                    return self.input_bindings\n\n                if key == \"output\":\n                    return self.output_bindings\n\n                if key == \"param\":\n                    return self.param_binding\n\n                raise RuntimeError(f\"{key} not found!\")\n\n            raise RuntimeError('The data type of \"key\" is not supported!')\n\n        def get_data_type(self, key, interface_type):\n            \"\"\"Get the module interface data type according to the key value and interface type.\n            Parameters\n            ----------\n            key: str\n                The interface name.\n\n            interface_type:\n                The interface type.\n\n            Return\n            -------\n                Return data type.\n            \"\"\"\n            if interface_type == \"input\":\n                for param in self.input_params:\n                    if param.name_hint == key:\n                        return param._checked_type_\n\n            if interface_type == \"output\":\n                if isinstance(self.output_type, tvm.ir.type.TupleType):\n                    if int(key) < len(self.output_type.fields):\n                        return self.output_type.fields[int(key)]\n                elif int(key) == 0:\n                    return self.output_type\n\n            return None\n\n        def set_idx_name(self, idx):\n            # Set the index value and generate the module name.\n            self.idx = idx\n            self.name = \"mod{}\".format(str(idx))\n\n        def is_root_mod(self):\n            \"\"\"Check whether this node is the root node in DAG, this function is used\n            in topological sort.\n            \"\"\"\n            return all([not b.parents for b in self.input_bindings.bindings.values()])\n\n        def remove_self_from_bindings(self):\n            \"\"\"Remove the current node from child dependencies to reduce the in-degree\n            of child node, this function is used in topological sort.\n            \"\"\"\n            for binding in self.output_bindings.bindings.values():\n                for child in binding.bindings:\n                    if binding in child.parents:\n                        child.parents.remove(binding)\n\n    def __init__(self):\n        self.mod_wrapper = {}\n        self.input_bindings = self.BindingList(self, \"input\")\n        self.output_bindings = self.BindingList(self, \"output\")\n        # There is a map of global parameters group and module index.\n        self.param_group_bindings = self.BindingList(self, \"param\")\n\n    def __str__(self):\n        # Get configuration information as a string.\n\n        # Use topological sort to get correct module order.\n        self.dag_topology_sort()\n        # Getting the parameters dependencies.\n        param_dump = \"Params\\n\"\n        for param_name in self.param_group_bindings.bindings:\n            inf = self.param_group_bindings.bindings[param_name]\n            param_dump += str(inf) + \"\\n\"\n        # Get the input dependencies.\n        input_dump = \"\\nInputs\\n\"\n        for input_name in self.input_bindings.bindings:\n            inf = self.input_bindings.bindings[input_name]\n            input_dump += str(inf) + \"\\n\"\n\n        # Get the connections information of each module.\n        output = {}\n        connections_dump = \"\\nconnections\\n\"\n        for mod in self.mod_wrapper:\n            for interface in self.mod_wrapper[mod].output_bindings.bindings.values():\n                if interface.bindings:\n                    mname, dname = interface.get_name()\n                    iname = mname + \".output(\" + dname + \")->\"\n                    for dep in interface.bindings:\n                        dep_mname, dep_dname = dep.get_name()\n                        if isinstance(dep.io_owner, PipelineConfig.ModuleWrapper):\n                            iname += f\" {dep_mname}.{dep_dname}\"\n                            connections_dump += f\"  |{iname}\\n\"\n                        else:\n                            output[dep_dname] = f\"{mname}.output({dname})\"\n\n        # Get the output dependencies.\n        output_dump = \"\\noutput\\n\"\n        for name in sorted(output.keys()):\n            output_dump += f\"  |output({name}) : {output[name]}\\n\"\n\n        return param_dump + input_dump + output_dump + connections_dump\n\n    def __getitem__(self, key):\n        if isinstance(key, tvm.ir.module.IRModule):\n            if key not in self.mod_wrapper:\n                self.mod_wrapper[key] = self.ModuleWrapper(key)\n            return self.mod_wrapper[key]\n\n        if isinstance(key, str):\n            if key == \"input\":\n                return self.input_bindings\n            if key == \"output\":\n                return self.output_bindings\n            if key == \"param_group\":\n                return self.param_group_bindings\n\n            raise RuntimeError(f\"{key} not found!\")\n\n        raise RuntimeError(f'The key type \"{type(key)}\" is not supported!')\n\n    def get_config(self):\n        \"\"\"Get the configuration information in dictionary form, this configuration\n        will be used to create pipeline executor.\n        \"\"\"\n\n        # Use topological sort to get the correct order of modules.\n        self.dag_topology_sort()\n        mconfig = {}\n        module_connection = {}\n        for mod in self.mod_wrapper:\n            # Generate pipeline configuration.\n            mconf = {}\n            output_conf = []\n            module = self.mod_wrapper[mod]\n            for _, binding in module.output_bindings.bindings.items():\n                dep_conf = []\n                output = {}\n                if binding.bindings:\n                    for dep in binding.bindings:\n                        dep_item = {}\n                        _, dname = dep.get_name()\n                        if dep.is_pipeline_executor_interface():\n                            dep_item[\"global_output_index\"] = int(dname)\n                        else:\n                            dep_item[\"mod_idx\"] = dep.get_owner_idx()\n                            dep_item[\"input_name\"] = dname\n                        dep_conf.append(dep_item)\n\n                # The value of output_idx start from 0.\n                output[\"output_idx\"] = int(binding.name)\n                output[\"dependencies\"] = dep_conf\n                output_conf.append(output)\n\n            mconf[\"mod_idx\"] = module.idx\n            mconf[\"cpu_affinity\"] = module.cpu_affinity\n            mconf[\"output\"] = output_conf\n\n            module_connection[mod] = {\n                \"pipeline\": mconf,\n                \"target_host\": module.target_host,\n                \"mod_name\": \"default\",\n                \"build\": module.build_func,\n                \"params\": module.params,\n                \"target\": module.target,\n                \"fcompile\": module.fcompile,\n                \"dev\": module.dev,\n                \"export_cc\": module.export_cc,\n            }\n\n        # Creating a map including pipeline inputs and subgraph inputs.\n        input_connection = []\n        for input_name in self.input_bindings.bindings:\n            input_dict = self.input_bindings.bindings[input_name].get_binding_dict()\n            if \"interface_name\" not in input_dict[\"connection\"][0]:\n                raise RuntimeError(\"interface_name is missing in connection config!\")\n            # Creating the map including global interfaces and subgraph interfaces.\n            input_map = {\n                \"global_interface_name\": input_dict[\"interface_name\"],\n                \"mod_idx\": input_dict[\"connection\"][0][\"mod_idx\"],\n                \"module_interface_name\": input_dict[\"connection\"][0][\"interface_name\"],\n            }\n            input_connection.append(input_map)\n\n        # Create a map including global parameters groups and modules.\n        param_connection = []\n        for param_name in self.param_group_bindings.bindings:\n            param_dict = self.param_group_bindings.bindings[param_name].get_binding_dict()\n            param_map = {\n                \"global_param_name\": param_dict[\"interface_name\"],\n                \"mod_idx\": param_dict[\"connection\"][0][\"mod_idx\"],\n            }\n            param_connection.append(param_map)\n\n        mconfig[\"module_connection\"] = module_connection\n        mconfig[\"input_connection\"] = input_connection\n        mconfig[\"param_connection\"] = param_connection\n        return mconfig\n\n    def dag_topology_sort(self):\n        \"\"\"Use topological sort to get order of pipeline modules.\"\"\"\n        mlist = []\n        mod_wrapper = self.mod_wrapper.copy()\n        while mod_wrapper:\n            temp_list = []\n            for mod, wrapper in mod_wrapper.items():\n                if wrapper.is_root_mod():\n                    temp_list.append(mod)\n                    wrapper.remove_self_from_bindings()\n\n            for mod in temp_list:\n                mod_wrapper.pop(mod, None)\n\n            mlist += temp_list\n\n        mod_wrapper_sort = {}\n        for mod, i in zip(mlist, range(len(mlist))):\n            self.mod_wrapper[mod].set_idx_name(i)\n            mod_wrapper_sort[mod] = self.mod_wrapper[mod]\n\n        self.mod_wrapper = mod_wrapper_sort\n\n    def get_mod_idx(self, mod):\n        # Return the module index.\n        idx = self.mod_wrapper[mod].idx\n        return idx\n\n    def pipe_input(self, name):\n        # Return the input interface according to the name.\n        return self.input_bindings[name]\n\n    def pipe_output(self, idx):\n        # Return the output interface according to the name.\n        return self.output_bindings[idx]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/popen_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Multiprocessing via Popen.\n\nThis module provides a multi-processing pool backed by Popen.\nwith additional timeout support.\n\"\"\"\nimport os\nimport sys\nimport struct\nimport threading\nimport subprocess\nimport concurrent.futures\nfrom enum import IntEnum\nfrom collections import namedtuple\nimport pickle\n\n\ndef kill_child_processes(pid):\n    \"\"\"Kill all child processes recursively for a given pid.\n\n    Parameters\n    ----------\n    pid : int\n        The given parameter id.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    import psutil\n\n    try:\n        parent = psutil.Process(pid)\n        children = parent.children(recursive=True)\n    except psutil.NoSuchProcess:\n        return\n\n    for process in children:\n        try:\n            process.kill()\n        except psutil.NoSuchProcess:\n            pass\n\n\nclass StatusKind(IntEnum):\n    \"\"\"Running and return value status.\"\"\"\n\n    RUNNING = 0\n    COMPLETE = 1\n    EXCEPTION = 2\n    TIMEOUT = 3\n\n\nclass MapResult(namedtuple(\"MapResult\", [\"status\", \"value\"])):\n    \"\"\"Result of map_with_error_catching.\n\n    Parameters\n    ----------\n    status : StatusKind\n        The status of the result.\n\n    value : Any\n        The result value.\n    \"\"\"\n\n    __slots__ = []\n\n\nclass PopenWorker:\n    \"\"\"A subprocess worker via Popen.\n\n    PopenWorker provides a low-level\n    API to interact with a separate process via Popen.\n\n    Parameters\n    ----------\n    initializer: callable or None\n        A callable initializer, or None\n\n    initargs: Tuple[object]\n        A tuple of args for the initializer\n\n    maximum_uses: Optional[int]\n        The maximum number of times a process can be used before being recycled,\n        i.e. killed and restarted. If `None`, the process will be reused until\n        an operation times out.\n\n    stdout: Union[None, int, IO[Any]]\n        The standard output streams handler specified for the popen process.\n\n    stderr: Union[None, int, IO[Any]]\n        The standard error streams handler specified for the popen process.\n    \"\"\"\n\n    def __init__(self, initializer=None, initargs=(), maximum_uses=None, stdout=None, stderr=None):\n        self._proc = None\n        self._initializer = initializer\n        self._initargs = initargs\n        self._maximum_uses = maximum_uses\n        self._remaining_uses = None\n        self._stdout = stdout\n        self._stderr = stderr\n\n        if self._initializer is not None and not callable(self._initializer):\n            raise TypeError(\"initializer must be callable for PopenWorker\")\n\n    def __del__(self):\n        try:\n            self.kill()\n        except ImportError:\n            pass\n\n    def kill(self):\n        \"\"\"Kill the current running process and cleanup.\n\n        Note\n        ----\n        The worker can start a new process when send is called again.\n        \"\"\"\n        if self._proc is not None:\n            # allow gracefully shutdown\n            try:\n                self._writer.close()\n            except IOError:\n                pass\n            try:\n                self._reader.close()\n            except IOError:\n                pass\n            # kill all child processes recursively\n            try:\n                kill_child_processes(self._proc.pid)\n            except TypeError:\n                pass\n            try:\n                self._proc.kill()\n            except OSError:\n                pass\n\n            # Join the child process to avoid zombie processes\n            self.join(timeout=1.0)\n            self._proc = None\n            self._remaining_uses = None\n\n    def _start(self):\n        \"\"\"Start a new subprocess if nothing is available\"\"\"\n        if self._proc is not None:\n            return\n\n        # connect subprocess with a pair of pipes\n        main_read, worker_write = os.pipe()\n        worker_read, main_write = os.pipe()\n\n        cmd = [sys.executable, \"-m\", \"tvm.exec.popen_worker\"]\n        if sys.platform == \"win32\":\n            # pylint: disable=import-outside-toplevel\n            import msvcrt\n\n            worker_read_handle = msvcrt.get_osfhandle(worker_read)\n            worker_write_handle = msvcrt.get_osfhandle(worker_write)\n            os.set_handle_inheritable(worker_read_handle, True)\n            os.set_handle_inheritable(worker_write_handle, True)\n            cmd += [str(worker_read_handle), str(worker_write_handle)]\n            self._proc = subprocess.Popen(\n                cmd, close_fds=False, stdout=self._stdout, stderr=self._stderr\n            )\n        else:\n            cmd += [str(worker_read), str(worker_write)]\n            self._proc = subprocess.Popen(\n                cmd, pass_fds=(worker_read, worker_write), stdout=self._stdout, stderr=self._stderr\n            )\n\n        # close worker side of the pipe\n        os.close(worker_read)\n        os.close(worker_write)\n        self._reader = os.fdopen(main_read, \"rb\")\n        self._writer = os.fdopen(main_write, \"wb\")\n\n    def join(self, timeout=None):\n        \"\"\"Join the current process worker before it terminates.\n\n        Parameters\n        ----------\n        timeout: Optional[number]\n            Timeout value, block at most timeout seconds if it\n            is a positive number.\n        \"\"\"\n        if self._proc:\n            try:\n                self._proc.wait(timeout)\n            except subprocess.TimeoutExpired:\n                pass\n\n    def is_alive(self):\n        \"\"\"Check if the process is alive\"\"\"\n        if self._proc:\n            return self._proc.poll() is None\n        return False\n\n    def send(self, fn, args=(), kwargs=None, timeout=None):\n        \"\"\"Send a new function task fn(*args, **kwargs) to the subprocess.\n\n        Parameters\n        ----------\n        fn : function\n            The function to be invoked.\n\n        args : list\n            Positional argument.\n\n        kwargs : dict\n            Keyword arguments\n\n        timeout : float\n            Timeout value when executing the function\n\n        Note\n        ----\n        The caller must call recv before calling the next send in\n        order to make sure the timeout and child process exit\n        won't affect the later requests.\n        \"\"\"\n        # use cloud pickle\n        # pylint: disable=import-outside-toplevel\n        import cloudpickle\n\n        if self._proc is not None and self._maximum_uses and self._remaining_uses == 0:\n            # Time to recycle the process.\n            self.kill()\n\n        if self._proc is None:\n            self._start()\n            # init\n            if self._initializer is not None:\n                self.send(self._initializer, self._initargs)\n                self.recv()\n\n            # N.B. The initializer doesn't count as a \"use\"\n            self._remaining_uses = self._maximum_uses\n        kwargs = {} if not kwargs else kwargs\n        data = cloudpickle.dumps((fn, args, kwargs, timeout), protocol=pickle.HIGHEST_PROTOCOL)\n        try:\n            self._writer.write(struct.pack(\"<i\", len(data)))\n            self._writer.write(data)\n            self._writer.flush()\n        except IOError:\n            pass\n\n        if self._remaining_uses:\n            self._remaining_uses -= 1\n\n    def _child_process_error(self):\n        \"\"\"Raise a child process error.\"\"\"\n        # kill and lazily restart the process in the next send.\n        self.kill()\n        return ChildProcessError(\"Subprocess terminated\")\n\n    def recv(self):\n        \"\"\"Receive the result of the last send.\n\n        Returns\n        -------\n        result: object\n            The result of the last send.\n\n        Raises\n        ------\n        ChildProcessError: if the child process exited abnormally.\n        TimeoutError: if timeout happens\n        Exception: if other exception happens during the execution.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        import cloudpickle\n\n        try:\n            len_data = self._reader.read(4)\n        except IOError:\n            raise self._child_process_error()\n\n        if len(len_data) == 0:\n            raise self._child_process_error()\n\n        try:\n            recv_bytes = struct.unpack(\"<i\", len_data)[0]\n            status, value = cloudpickle.loads(self._reader.read(recv_bytes))\n        except IOError:\n            raise self._child_process_error()\n\n        if status == StatusKind.COMPLETE:\n            return value\n        if status == StatusKind.EXCEPTION:\n            raise value\n        assert status == StatusKind.TIMEOUT\n        # kill and lazily restart the process in the next send.\n        self.kill()\n        raise TimeoutError()\n\n\nclass PopenPoolExecutor:\n    \"\"\"An parallel executor backed by Popen processes.\n\n    Parameters\n    ----------\n    max_worker : int\n        Maximum number of workers\n\n    timeout : float\n        Timeout value for each function submit.\n\n    initializer: callable or None\n        A callable initializer, or None\n\n    initargs: Tuple[object]\n        A tuple of args for the initializer\n\n    maximum_process_uses: Optional[int]\n        The maximum number of times each process can be used before being recycled,\n        i.e. killed and restarted. If `None`, processes will be reused until an\n        operation times out.\n\n    stdout: Union[None, int, IO[Any]]\n        The standard output streams handler specified for the workers in the pool.\n\n    stderr: Union[None, int, IO[Any]]\n        The standard error streams handler specified for the workers in the pool.\n\n    Note\n    ----\n    If max_workers is NONE then the number returned by\n    os.cpu_count() is used. This method aligns with the\n    behavior of multiprocessing.pool().\n    \"\"\"\n\n    def __init__(\n        self,\n        max_workers=None,\n        timeout=None,\n        initializer=None,\n        initargs=(),\n        maximum_process_uses=None,\n        stdout=None,\n        stderr=None,\n    ):\n        if max_workers is None:\n            max_workers = os.cpu_count()\n        # Use an internal thread pool to send to popen workers\n        self._threadpool = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)\n        self._timeout = timeout\n        self._worker_map = {}\n        self._lock = threading.Lock()\n        self._initializer = initializer\n        self._initargs = initargs\n        self._maximum_process_uses = maximum_process_uses\n        self._stdout = stdout\n        self._stderr = stderr\n\n        if self._initializer is not None and not callable(self._initializer):\n            raise TypeError(\"initializer must be callable for PopenPoolExecutor\")\n\n    def __del__(self):\n        self._lock.acquire()\n        for worker in self._worker_map.values():\n            try:\n                worker.kill()\n            except ImportError:\n                pass\n        self._lock.release()\n        self._threadpool.shutdown()\n\n    def _worker_run(self, fn, args, kwargs):\n        \"\"\"Internal thread runner.\"\"\"\n        self._lock.acquire()\n        tid = threading.get_ident()\n        if tid not in self._worker_map:\n            proc = PopenWorker(\n                self._initializer,\n                self._initargs,\n                self._maximum_process_uses,\n                self._stdout,\n                self._stderr,\n            )\n            self._worker_map[tid] = proc\n        else:\n            proc = self._worker_map[tid]\n        self._lock.release()\n\n        proc.send(fn, args, kwargs, self._timeout)\n        return proc.recv()\n\n    def _worker_run_with_error_catching(self, fn, args, kwargs) -> MapResult:\n        # pylint: disable=broad-except\n        try:\n            return MapResult(status=StatusKind.COMPLETE, value=self._worker_run(fn, args, kwargs))\n        except TimeoutError as exception:\n            return MapResult(status=StatusKind.TIMEOUT, value=exception)\n        except Exception as exception:\n            return MapResult(status=StatusKind.EXCEPTION, value=exception)\n\n    def submit(self, fn, *args, **kwargs) -> concurrent.futures.Future:\n        \"\"\"Submit a new function job to the pool\n\n        Parameters\n        ----------\n        fn : function\n            The function to be invoked.\n\n        args : list\n            Positional argument.\n\n        kwargs : dict\n            Keyword arguments\n\n        Returns\n        -------\n        future : concurrent.futures.Future\n            A future that can be used to access the result.\n        \"\"\"\n        # pylint: disable=unnecessary-lambda\n        worker = lambda *args: self._worker_run(*args)\n        return self._threadpool.submit(worker, fn, args, kwargs)\n\n    def map_with_error_catching(self, fn, iterator):\n        \"\"\"Same as map, but catches exceptions and return them instead.\n\n        Parameters\n        ----------\n        fn : function\n            The function to be invoked.\n\n        iterator : Iterator\n            Input iterator.\n\n        Returns\n        -------\n        out_iter : Iterator[MapResult]\n            The result iterator.\n        \"\"\"\n        worker = lambda x: self._worker_run_with_error_catching(fn, (x,), None)\n        return self._threadpool.map(worker, iterator)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/random.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to random library.\"\"\"\nimport tvm\nfrom tvm import te\nimport tvm._ffi\n\n\ndef randint(low, high, size, dtype=\"int32\"):\n    \"\"\"Return random integers from low (inclusive) to high (exclusive).\n    Return random integers from the \"discrete uniform\" distribution of the\n    specified dtype in the \"half-open\" interval [low, high).\n\n    Parameters\n    ----------\n    low : int\n        Lowest (signed) integer to be drawn from the distribution\n    high : int\n        One above the largest (signed) integer to be drawn from the distribution\n\n    Returns\n    -------\n    out : Tensor\n        A tensor with specified size and dtype\n    \"\"\"\n    assert \"int\" in dtype, \"the type of randint output must be int or uint\"\n    return te.extern(\n        size,\n        [],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.random.randint\", int(low), int(high), outs[0]\n        ),\n        dtype=dtype,\n    )\n\n\ndef uniform(low, high, size):\n    \"\"\"Draw samples from a uniform distribution.\n\n    Samples are uniformly distributed over the half-open interval [low, high)\n    (includes low, but excludes high). In other words, any value within the\n    given interval is equally likely to be drawn by uniform.\n\n    Parameters\n    ----------\n    low : float\n        Lower boundary of the output interval. All values generated will be\n        greater than or equal to low.\n    high : float\n        Upper boundary of the output interval. All values generated will be\n        less than high.\n    size : tuple of ints\n        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k\n        samples are drawn.\n\n    Returns\n    -------\n    out : Tensor\n        A tensor with specified size and dtype.\n    \"\"\"\n    return te.extern(\n        size,\n        [],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.random.uniform\", float(low), float(high), outs[0]\n        ),\n        dtype=\"float32\",\n    )\n\n\ndef normal(loc, scale, size):\n    \"\"\"Draw samples from a normal distribution.\n\n    Return random samples from a normal distribution.\n\n    Parameters\n    ----------\n    loc : float\n        loc of the distribution.\n    scale : float\n        Standard deviation of the distribution.\n    size : tuple of ints\n        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k\n        samples are drawn.\n\n    Returns\n    ------\n    out : Tensor\n        A tensor with specified size and dtype\n    \"\"\"\n    return te.extern(\n        size,\n        [],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.random.normal\", float(loc), float(scale), outs[0]\n        ),\n        dtype=\"float32\",\n    )\n\n\ntvm._ffi._init_api(\"tvm.contrib.random\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/relay_viz/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Relay IR Visualizer\"\"\"\nfrom typing import Dict\nimport tvm\nfrom tvm import relay\nfrom .interface import (\n    Plotter,\n    VizGraph,\n    VizParser,\n)\nfrom .terminal import (\n    TermPlotter,\n    TermVizParser,\n)\nfrom .dot import (\n    DotPlotter,\n    DotVizParser,\n)\n\n\nclass RelayVisualizer:\n    \"\"\"Relay IR Visualizer\n\n    Parameters\n    ----------\n    relay_mod: tvm.IRModule\n        Relay IR module.\n    relay_param: None | Dict[str, tvm.runtime.NDArray]\n        Relay parameter dictionary. Default `None`.\n    plotter: Plotter\n        An instance of class inheriting from Plotter interface.\n        Default is an instance of `terminal.TermPlotter`.\n    parser: VizParser\n        An instance of class inheriting from VizParser interface.\n        Default is an instance of `terminal.TermVizParser`.\n    \"\"\"\n\n    def __init__(\n        self,\n        relay_mod: tvm.IRModule,\n        relay_param: Dict[str, tvm.runtime.NDArray] = None,\n        plotter: Plotter = None,\n        parser: VizParser = None,\n    ):\n        self._plotter = plotter if plotter is not None else TermPlotter()\n        self._relay_param = relay_param if relay_param is not None else {}\n        self._parser = parser if parser is not None else TermVizParser()\n\n        global_vars = relay_mod.get_global_vars()\n        graph_names = []\n        # If we have main function, put it to the first.\n        # Then main function can be shown on the top.\n        for gv_node in global_vars:\n            if gv_node.name_hint == \"main\":\n                graph_names.insert(0, gv_node.name_hint)\n            else:\n                graph_names.append(gv_node.name_hint)\n\n        node_to_id = {}\n        # callback to generate an unique string-ID for nodes.\n        # node_count_offset ensure each node ID is still unique across subgraph.\n        node_count_offset = 0\n\n        def traverse_expr(node):\n            if node in node_to_id:\n                return\n            node_to_id[node] = str(len(node_to_id) + node_count_offset)\n\n        for name in graph_names:\n            node_count_offset += len(node_to_id)\n            node_to_id.clear()\n            relay.analysis.post_order_visit(relay_mod[name], traverse_expr)\n            graph = self._plotter.create_graph(name)\n            self._add_nodes(graph, node_to_id)\n\n    def _add_nodes(self, graph: VizGraph, node_to_id: Dict[relay.Expr, str]):\n        \"\"\"add nodes and to the graph.\n\n        Parameters\n        ----------\n        graph : VizGraph\n            a VizGraph for nodes to be added to.\n\n        node_to_id : Dict[relay.expr, str]\n            a mapping from nodes to an unique ID.\n\n        relay_param : Dict[str, tvm.runtime.NDarray]\n            relay parameter dictionary.\n        \"\"\"\n        for node in node_to_id:\n            viz_node, viz_edges = self._parser.get_node_edges(node, self._relay_param, node_to_id)\n            if viz_node is not None:\n                graph.node(viz_node)\n            for edge in viz_edges:\n                graph.edge(edge)\n\n    def render(self, filename: str = None) -> None:\n        self._plotter.render(filename=filename)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/relay_viz/dot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Visualize Relay IR by Graphviz DOT language.\"\"\"\n\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n)\nfrom .interface import (\n    DefaultVizParser,\n    Plotter,\n    VizEdge,\n    VizGraph,\n    VizNode,\n)\n\ntry:\n    import graphviz\nexcept ImportError:\n    # add \"from None\" to silence\n    # \"During handling of the above exception, another exception occurred\"\n    raise ImportError(\n        \"The graphviz package is required for DOT renderer. \"\n        \"Please install it first. For example, pip3 install graphviz\"\n    ) from None\n\nDotVizParser = DefaultVizParser\n\n\nclass DotGraph(VizGraph):\n    \"\"\"DOT graph for relay IR.\n\n    See also :py:class:`tvm.contrib.relay_viz.dot.DotPlotter`\n\n    Parameters\n    ----------\n    name: str\n        name of this graph.\n    graph_attr: Optional[Dict[str, str]]\n        key-value pairs for the graph.\n    node_attr: Optional[Dict[str, str]]\n        key-value pairs for all nodes.\n    edge_attr: Optional[Dict[str, str]]\n        key-value pairs for all edges.\n    get_node_attr: Optional[Callable[[VizNode], Dict[str, str]]]\n        A callable returning attributes for the node.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        graph_attr: Dict[str, str] = None,\n        node_attr: Dict[str, str] = None,\n        edge_attr: Dict[str, str] = None,\n        get_node_attr: Callable[[VizNode], Dict[str, str]] = None,\n    ):\n        self._name = name\n        self._get_node_attr = self._default_get_node_attr\n        if get_node_attr is not None:\n            self._get_node_attr = get_node_attr\n\n        # graphviz recognizes the subgraph as a cluster subgraph\n        # by the name starting with \"cluster\" (all lowercase)\n        self._digraph = graphviz.Digraph(\n            name=f\"cluster_{self._name}\",\n            graph_attr=graph_attr,\n            node_attr=node_attr,\n            edge_attr=edge_attr,\n        )\n        self._digraph.attr(label=self._name)\n\n    def node(self, viz_node: VizNode) -> None:\n        \"\"\"Add a node to the underlying graph.\n        Nodes in a Relay IR Module are expected to be added in the post-order.\n\n        Parameters\n        ----------\n        viz_node : VizNode\n            A `VizNode` instance.\n        \"\"\"\n        self._digraph.node(\n            viz_node.identity,\n            f\"{viz_node.type_name}\\n{viz_node.detail}\",\n            **self._get_node_attr(viz_node),\n        )\n\n    def edge(self, viz_edge: VizEdge) -> None:\n        \"\"\"Add an edge to the underlying graph.\n\n        Parameters\n        ----------\n        viz_edge : VizEdge\n            A `VizEdge` instance.\n        \"\"\"\n        self._digraph.edge(viz_edge.start, viz_edge.end)\n\n    @property\n    def digraph(self):\n        return self._digraph\n\n    @staticmethod\n    def _default_get_node_attr(node: VizNode):\n        if \"Var\" in node.type_name:\n            return {\"shape\": \"ellipse\"}\n        return {\"shape\": \"box\"}\n\n\nclass DotPlotter(Plotter):\n    \"\"\"DOT language graph plotter\n\n    The plotter accepts various graphviz attributes for graphs, nodes, and edges.\n    Please refer to https://graphviz.org/doc/info/attrs.html for available attributes.\n\n    Parameters\n    ----------\n    graph_attr: Optional[Dict[str, str]]\n        key-value pairs for all graphs.\n    node_attr: Optional[Dict[str, str]]\n        key-value pairs for all nodes.\n    edge_attr: Optional[Dict[str, str]]\n        key-value pairs for all edges.\n    get_node_attr: Optional[Callable[[VizNode], Dict[str, str]]]\n        A callable returning attributes for a specific node.\n    render_kwargs: Optional[Dict[str, Any]]\n        keyword arguments directly passed to `graphviz.Digraph.render()`.\n\n    Examples\n    --------\n\n    .. code-block:: python\n\n        from tvm.contrib import relay_viz\n        from tvm.relay.testing import resnet\n\n        mod, param = resnet.get_workload(num_layers=18)\n        # graphviz attributes\n        graph_attr = {\"color\": \"red\"}\n        node_attr = {\"color\": \"blue\"}\n        edge_attr = {\"color\": \"black\"}\n\n        # VizNode is passed to the callback.\n        # We want to color NCHW conv2d nodes. Also give Var a different shape.\n        def get_node_attr(node):\n            if \"nn.conv2d\" in node.type_name and \"NCHW\" in node.detail:\n                return {\n                    \"fillcolor\": \"green\",\n                    \"style\": \"filled\",\n                    \"shape\": \"box\",\n                }\n            if \"Var\" in node.type_name:\n                return {\"shape\": \"ellipse\"}\n            return {\"shape\": \"box\"}\n\n        # Create plotter and pass it to viz. Then render the graph.\n        dot_plotter = relay_viz.DotPlotter(\n            graph_attr=graph_attr,\n            node_attr=node_attr,\n            edge_attr=edge_attr,\n            get_node_attr=get_node_attr)\n\n        viz = relay_viz.RelayVisualizer(\n            mod,\n            relay_param=param,\n            plotter=dot_plotter,\n            parser=relay_viz.DotVizParser())\n        viz.render(\"hello\")\n    \"\"\"\n\n    def __init__(\n        self,\n        graph_attr: Dict[str, str] = None,\n        node_attr: Dict[str, str] = None,\n        edge_attr: Dict[str, str] = None,\n        get_node_attr: Callable[[VizNode], Dict[str, str]] = None,\n        render_kwargs: Dict[str, Any] = None,\n    ):\n        self._name_to_graph = {}\n        self._graph_attr = graph_attr\n        self._node_attr = node_attr\n        self._edge_attr = edge_attr\n        self._get_node_attr = get_node_attr\n\n        self._render_kwargs = {} if render_kwargs is None else render_kwargs\n\n    def create_graph(self, name):\n        self._name_to_graph[name] = DotGraph(\n            name, self._graph_attr, self._node_attr, self._edge_attr, self._get_node_attr\n        )\n        return self._name_to_graph[name]\n\n    def render(self, filename: str = None):\n        \"\"\"render the graph generated from the Relay IR module.\n\n        This function is a thin wrapper of `graphviz.Digraph.render()`.\n        \"\"\"\n        # Create or update the filename\n        if filename is not None:\n            self._render_kwargs[\"filename\"] = filename\n        # default cleanup\n        if \"cleanup\" not in self._render_kwargs:\n            self._render_kwargs[\"cleanup\"] = True\n\n        root_graph = graphviz.Digraph()\n        for graph in self._name_to_graph.values():\n            root_graph.subgraph(graph.digraph)\n        root_graph.render(**self._render_kwargs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/relay_viz/interface.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Abstract class used by :py:class:`tvm.contrib.relay_viz.RelayVisualizer`.\"\"\"\nimport abc\nfrom typing import (\n    Dict,\n    Union,\n    Tuple,\n    List,\n)\n\nimport tvm\nfrom tvm import relay\n\nUNKNOWN_TYPE = \"unknown\"\n\n\nclass VizNode:\n    \"\"\"VizNode carry node information for `VizGraph` interface.\n\n    Parameters\n    ----------\n    node_id: str\n        Unique identifier for this node.\n    node_type: str\n        Type of this node.\n    node_detail: str\n        Any supplement for this node such as attributes.\n    \"\"\"\n\n    def __init__(self, node_id: str, node_type: str, node_detail: str):\n        self._id = node_id\n        self._type = node_type\n        self._detail = node_detail\n\n    @property\n    def identity(self) -> str:\n        return self._id\n\n    @property\n    def type_name(self) -> str:\n        return self._type\n\n    @property\n    def detail(self) -> str:\n        return self._detail\n\n    def __repr__(self) -> str:\n        detail = self._detail.replace(\"\\n\", \", \")\n        return f\"VizNode(identity: {self._id}, type_name: {self._type}, detail: {detail}\"\n\n\nclass VizEdge:\n    \"\"\"VizEdge connect two `VizNode`.\n\n    Parameters\n    ----------\n    start_node: str\n        The identifier of the node starting the edge.\n    end_node: str\n        The identifier of the node ending the edge.\n    \"\"\"\n\n    def __init__(self, start_node: str, end_node: str):\n        self._start_node = start_node\n        self._end_node = end_node\n\n    @property\n    def start(self) -> str:\n        return self._start_node\n\n    @property\n    def end(self) -> str:\n        return self._end_node\n\n\nclass VizParser(abc.ABC):\n    \"\"\"VizParser parses out a VizNode and VizEdges from a `relay.Expr`.\"\"\"\n\n    @abc.abstractmethod\n    def get_node_edges(\n        self,\n        node: relay.Expr,\n        relay_param: Dict[str, tvm.runtime.NDArray],\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        \"\"\"Get VizNode and VizEdges for a `relay.Expr`.\n\n        Parameters\n        ----------\n        node : relay.Expr\n            relay.Expr which will be parsed and generate a node and edges.\n\n        relay_param: Dict[str, tvm.runtime.NDArray]\n            relay parameters dictionary.\n\n        node_to_id : Dict[relay.Expr, str]\n            This is a mapping from relay.Expr to a unique id, generated by `RelayVisualizer`.\n\n        Returns\n        -------\n        rv1 : Union[VizNode, None]\n            VizNode represent the relay.Expr. If the relay.Expr is not intended to introduce a node\n            to the graph, return None.\n\n        rv2 : List[VizEdge]\n            a list of VizEdges to describe the connectivity of the relay.Expr.\n            Can be empty list to indicate no connectivity.\n        \"\"\"\n\n\nclass VizGraph(abc.ABC):\n    \"\"\"Abstract class for graph, which is composed of nodes and edges.\"\"\"\n\n    @abc.abstractmethod\n    def node(self, viz_node: VizNode) -> None:\n        \"\"\"Add a node to the underlying graph.\n        Nodes in a Relay IR Module are expected to be added in the post-order.\n\n        Parameters\n        ----------\n        viz_node : VizNode\n            A `VizNode` instance.\n        \"\"\"\n\n    @abc.abstractmethod\n    def edge(self, viz_edge: VizEdge) -> None:\n        \"\"\"Add an edge to the underlying graph.\n\n        Parameters\n        ----------\n        viz_edge : VizEdge\n            A `VizEdge` instance.\n        \"\"\"\n\n\nclass DefaultVizParser(VizParser):\n    \"\"\"DefaultVizParser provde a set of logics to parse a various relay types.\n    These logics are inspired and heavily based on\n    `visualize` function in https://tvm.apache.org/2020/07/14/bert-pytorch-tvm\n    \"\"\"\n\n    def get_node_edges(\n        self,\n        node: relay.Expr,\n        relay_param: Dict[str, tvm.runtime.NDArray],\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        if isinstance(node, relay.Function):\n            return self._function(node, node_to_id)\n        if isinstance(node, relay.expr.Call):\n            return self._call(node, node_to_id)\n        if isinstance(node, relay.expr.Var):\n            return self._var(node, relay_param, node_to_id)\n        if isinstance(node, relay.expr.Tuple):\n            return self._tuple(node, node_to_id)\n        if isinstance(node, relay.expr.TupleGetItem):\n            return self._tuple_get_item(node, node_to_id)\n        if isinstance(node, relay.expr.Constant):\n            return self._constant(node, node_to_id)\n        # GlobalVar possibly mean another global relay function,\n        # which is expected to in \"Graph\" level, not in \"Node\" level.\n        if isinstance(node, (relay.expr.GlobalVar, tvm.ir.Op)):\n            return None, []\n\n        viz_node = VizNode(node_to_id[node], UNKNOWN_TYPE, f\"don't know how to parse {type(node)}\")\n        viz_edges = []\n        return viz_node, viz_edges\n\n    def _var(\n        self,\n        node: relay.Expr,\n        relay_param: Dict[str, tvm.runtime.NDArray],\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        \"\"\"Render rule for a relay var node\"\"\"\n\n        node_id = node_to_id[node]\n        name_hint = node.name_hint\n        node_detail = f\"name_hint: {name_hint}\"\n        node_type = \"Var(Param)\" if name_hint in relay_param else \"Var(Input)\"\n\n        if node.type_annotation is not None:\n            if hasattr(node.type_annotation, \"shape\"):\n                shape = tuple(map(int, node.type_annotation.shape))\n                dtype = node.type_annotation.dtype\n                node_detail = f\"{node_detail}\\nshape: {shape}\\ndtype: {dtype}\"\n            else:\n                node_detail = f\"{node_detail}\\ntype_annotation: {node.type_annotation}\"\n\n        # only node\n        viz_node = VizNode(node_id, node_type, node_detail)\n        viz_edges = []\n        return viz_node, viz_edges\n\n    def _function(\n        self,\n        node: relay.Expr,\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        \"\"\"Render rule for a relay function node\"\"\"\n        node_details = []\n        name = \"\"\n        func_attrs = node.attrs\n        if func_attrs:\n            node_details = [f\"{k}: {func_attrs.get_str(k)}\" for k in func_attrs.keys()]\n            # \"Composite\" might from relay.transform.MergeComposite\n            if \"Composite\" in func_attrs.keys():\n                name = func_attrs[\"Composite\"]\n        node_id = node_to_id[node]\n\n        # Body -> FunctionNode\n        viz_node = VizNode(node_id, f\"Func {name}\", \"\\n\".join(node_details))\n        viz_edges = [VizEdge(node_to_id[node.body], node_id)]\n        return viz_node, viz_edges\n\n    def _call(\n        self,\n        node: relay.Expr,\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        \"\"\"Render rule for a relay call node\"\"\"\n        node_id = node_to_id[node]\n        op_name = UNKNOWN_TYPE\n        node_detail = []\n        if isinstance(node.op, tvm.ir.Op):\n            op_name = node.op.name\n            if node.attrs:\n                node_detail = [f\"{k}: {node.attrs.get_str(k)}\" for k in node.attrs.keys()]\n        elif isinstance(node.op, relay.Function):\n            func_attrs = node.op.attrs\n            op_name = \"Anonymous Func\"\n            if func_attrs:\n                node_detail = [f\"{k}: {func_attrs.get_str(k)}\" for k in func_attrs.keys()]\n                # \"Composite\" might from relay.transform.MergeComposite\n                if \"Composite\" in func_attrs.keys():\n                    op_name = func_attrs[\"Composite\"]\n        elif isinstance(node.op, relay.GlobalVar):\n            op_name = \"GlobalVar\"\n            node_detail = [f\"GlobalVar.name_hint: {node.op.name_hint}\"]\n        else:\n            op_name = str(type(node.op)).split(\".\")[-1].split(\"'\")[0]\n\n        # Arguments -> CallNode\n        viz_node = VizNode(node_id, f\"Call {op_name}\", \"\\n\".join(node_detail))\n        args = [node_to_id[arg] for arg in node.args]\n        viz_edges = [VizEdge(arg, node_id) for arg in args]\n        return viz_node, viz_edges\n\n    def _tuple(\n        self,\n        node: relay.Expr,\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        node_id = node_to_id[node]\n\n        # Fields -> TupleNode\n        viz_node = VizNode(node_id, \"Tuple\", \"\")\n        viz_edges = [VizEdge(node_to_id[field], node_id) for field in node.fields]\n        return viz_node, viz_edges\n\n    def _tuple_get_item(\n        self,\n        node: relay.Expr,\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        node_id = node_to_id[node]\n\n        # Tuple -> TupleGetItemNode\n        viz_node = VizNode(node_id, f\"TupleGetItem\", f\"idx: {node.index}\")\n        viz_edges = [VizEdge(node_to_id[node.tuple_value], node_id)]\n        return viz_node, viz_edges\n\n    def _constant(\n        self,\n        node: relay.Expr,\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        node_id = node_to_id[node]\n        node_detail = f\"shape: {node.data.shape}, dtype: {node.data.dtype}\"\n\n        # only node\n        viz_node = VizNode(node_id, \"Const\", node_detail)\n        viz_edges = []\n        return viz_node, viz_edges\n\n\nclass Plotter(abc.ABC):\n    \"\"\"Plotter can render a collection of Graph interfaces to a file.\"\"\"\n\n    @abc.abstractmethod\n    def create_graph(self, name: str) -> VizGraph:\n        \"\"\"Create a VizGraph\n\n        Parameters\n        ----------\n        name : str\n            the name of the graph\n\n        Return\n        ------\n        rv1: an instance of class inheriting from VizGraph interface.\n        \"\"\"\n\n    @abc.abstractmethod\n    def render(self, filename: str) -> None:\n        \"\"\"Render the graph as a file.\n\n        Parameters\n        ----------\n        filename : str\n            see the definition of implemented class.\n        \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/relay_viz/terminal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Visualize Relay IR in AST text-form.\"\"\"\n\nfrom collections import deque\nfrom typing import (\n    Dict,\n    Union,\n    Tuple,\n    List,\n)\nimport tvm\nfrom tvm import relay\nfrom .interface import (\n    DefaultVizParser,\n    Plotter,\n    VizEdge,\n    VizGraph,\n    VizNode,\n    VizParser,\n)\n\n\nclass TermVizParser(VizParser):\n    \"\"\"`TermVizParser` parse nodes and edges for `TermPlotter`.\"\"\"\n\n    def __init__(self):\n        self._default_parser = DefaultVizParser()\n\n    def get_node_edges(\n        self,\n        node: relay.Expr,\n        relay_param: Dict[str, tvm.runtime.NDArray],\n        node_to_id: Dict[relay.Expr, str],\n    ) -> Tuple[Union[VizNode, None], List[VizEdge]]:\n        \"\"\"Parse a node and edges from a relay.Expr.\"\"\"\n        if isinstance(node, relay.Call):\n            return self._call(node, node_to_id)\n        if isinstance(node, relay.Let):\n            return self._let(node, node_to_id)\n        if isinstance(node, relay.GlobalVar):\n            return self._global_var(node, node_to_id)\n        if isinstance(node, relay.If):\n            return self._if(node, node_to_id)\n        if isinstance(node, tvm.ir.Op):\n            return self._op(node, node_to_id)\n        if isinstance(node, relay.Function):\n            return self._function(node, node_to_id)\n\n        # Leverage logics from default parser.\n        return self._default_parser.get_node_edges(node, relay_param, node_to_id)\n\n    def _call(self, node, node_to_id):\n        node_id = node_to_id[node]\n        viz_node = VizNode(node_id, \"Call\", \"\")\n        viz_edges = [VizEdge(node_to_id[node.op], node_id)]\n        for arg in node.args:\n            arg_id = node_to_id[arg]\n            viz_edges.append(VizEdge(arg_id, node_id))\n        return viz_node, viz_edges\n\n    def _let(self, node, node_to_id):\n        node_id = node_to_id[node]\n        viz_node = VizNode(node_id, \"Let\", \"(var, val, body)\")\n        viz_edges = [\n            VizEdge(node_to_id[node.var], node_id),\n            VizEdge(node_to_id[node.value], node_id),\n            VizEdge(node_to_id[node.body], node_id),\n        ]\n        return viz_node, viz_edges\n\n    def _global_var(self, node, node_to_id):\n        node_id = node_to_id[node]\n        viz_node = VizNode(node_id, \"GlobalVar\", node.name_hint)\n        viz_edges = []\n        return viz_node, viz_edges\n\n    def _if(self, node, node_to_id):\n        node_id = node_to_id[node]\n        viz_node = VizNode(node_id, \"If\", \"(cond, true, false)\")\n        viz_edges = [\n            VizEdge(node_to_id[node.cond], node_id),\n            VizEdge(node_to_id[node.true_branch], node_id),\n            VizEdge(node_to_id[node.false_branch], node_id),\n        ]\n        return viz_node, viz_edges\n\n    def _op(self, node, node_to_id):\n        node_id = node_to_id[node]\n        op_name = node.name\n        viz_node = VizNode(node_id, op_name, \"\")\n        viz_edges = []\n        return viz_node, viz_edges\n\n    def _function(self, node, node_to_id):\n        node_id = node_to_id[node]\n        viz_node = VizNode(node_id, \"Func\", str(node.params))\n        viz_edges = [VizEdge(node_to_id[node.body], node_id)]\n        return viz_node, viz_edges\n\n\nclass TermNode:\n    \"\"\"TermNode is aimed to generate text more suitable for terminal visualization.\"\"\"\n\n    def __init__(self, viz_node: VizNode):\n        self.type = viz_node.type_name\n        # We don't want too many lines in a terminal.\n        self.other_info = viz_node.detail.replace(\"\\n\", \", \")\n\n\nclass TermGraph(VizGraph):\n    \"\"\"Terminal graph for a relay IR Module\n\n    Parameters\n    ----------\n    name: str\n        name of this graph.\n    \"\"\"\n\n    def __init__(self, name: str):\n        self._name = name\n        # A graph in adjacency list form.\n        # The key is source node, and the value is a list of destination nodes.\n        self._graph = {}\n        # a hash table for quick searching.\n        self._id_to_term_node = {}\n        # node_id in reversed post order\n        # That mean, root is the first node.\n        self._node_id_rpo = deque()\n\n    def node(self, viz_node: VizNode) -> None:\n        \"\"\"Add a node to the underlying graph.\n        Nodes in a Relay IR Module are expected to be added in the post-order.\n\n        Parameters\n        ----------\n        viz_node : VizNode\n            A `VizNode` instance.\n        \"\"\"\n\n        self._node_id_rpo.appendleft(viz_node.identity)\n\n        if viz_node.identity not in self._graph:\n            # Add the node into the graph.\n            self._graph[viz_node.identity] = []\n\n        # Create TermNode from VizNode\n        node = TermNode(viz_node)\n        self._id_to_term_node[viz_node.identity] = node\n\n    def edge(self, viz_edge: VizEdge) -> None:\n        \"\"\"Add an edge to the terminal graph.\n\n        Parameters\n        ----------\n        viz_edge : VizEdge\n            A `VizEdge` instance.\n        \"\"\"\n        # Take CallNode as an example, instead of \"arguments point to CallNode\",\n        # we want \"CallNode points to arguments\" in ast-dump form.\n        #\n        # The direction of edge is typically controlled by the implemented VizParser.\n        # Reverse start/end here simply because we leverage default parser implementation.\n        if viz_edge.end in self._graph:\n            self._graph[viz_edge.end].append(viz_edge.start)\n        else:\n            self._graph[viz_edge.end] = [viz_edge.start]\n\n    def render(self) -> str:\n        \"\"\"Draw a terminal graph\n\n        Returns\n        -------\n        rv1: str\n            text representing a graph.\n        \"\"\"\n        lines = []\n        seen_node = set()\n\n        def gen_line(indent, n_id):\n            if (indent, n_id) in seen_node:\n                return\n            seen_node.add((indent, n_id))\n\n            conn_symbol = [\"|--\", \"`--\"]\n            last = len(self._graph[n_id]) - 1\n            for i, next_n_id in enumerate(self._graph[n_id]):\n                node = self._id_to_term_node[next_n_id]\n                lines.append(\n                    f\"{indent}{conn_symbol[1 if i==last else 0]}{node.type} {node.other_info}\"\n                )\n                next_indent = indent\n                # increase indent for the next level.\n                next_indent += \"   \" if (i == last) else \"|  \"\n                gen_line(next_indent, next_n_id)\n\n        first_node_id = self._node_id_rpo[0]\n        first_node = self._id_to_term_node[first_node_id]\n        lines.append(f\"@{self._name}({first_node.other_info})\")\n        gen_line(\"\", first_node_id)\n\n        return \"\\n\".join(lines)\n\n\nclass TermPlotter(Plotter):\n    \"\"\"Terminal plotter\"\"\"\n\n    def __init__(self):\n        self._name_to_graph = {}\n\n    def create_graph(self, name):\n        self._name_to_graph[name] = TermGraph(name)\n        return self._name_to_graph[name]\n\n    def render(self, filename):\n        \"\"\"If filename is None, print to stdio. Otherwise, write to the filename.\"\"\"\n        lines = []\n        for name in self._name_to_graph:\n            text_graph = self._name_to_graph[name].render()\n            lines.append(text_graph)\n        if filename is None:\n            print(\"\\n\".join(lines))\n        else:\n            with open(filename, \"w\") as out_file:\n                out_file.write(\"\\n\".join(lines))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/rocblas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External function interface to rocBLAS libraries.\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef matmul(lhs, rhs, transa=False, transb=False):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with rocBLAS\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left matrix operand\n    rhs : Tensor\n        The right matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    n = lhs.shape[1] if transa else lhs.shape[0]\n    m = rhs.shape[0] if transb else rhs.shape[1]\n    return te.extern(\n        (n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.rocblas.matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n    )\n\n\ndef batch_matmul(lhs, rhs, transa=False, transb=False):\n    \"\"\"Create an extern op that compute matrix mult of A and rhs with rocBLAS\n\n    Parameters\n    ----------\n    lhs : Tensor\n        The left batched matrix operand\n    rhs : Tensor\n        The right batched matrix operand\n    transa : bool\n        Whether transpose lhs\n    transb : bool\n        Whether transpose rhs\n\n    Returns\n    -------\n    C : Tensor\n        The result tensor.\n    \"\"\"\n    batch_size = lhs.shape[0]\n    assert batch_size == rhs.shape[0]\n    n = lhs.shape[2] if transa else lhs.shape[1]\n    m = rhs.shape[1] if transb else rhs.shape[2]\n    return te.extern(\n        (batch_size, n, m),\n        [lhs, rhs],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.rocblas.batch_matmul\", ins[0], ins[1], outs[0], transa, transb\n        ),\n        name=\"C\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/rocm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility for ROCm backend\"\"\"\nimport subprocess\nfrom os.path import join, exists\n\nimport tvm._ffi\nfrom tvm._ffi.base import py_str\nimport tvm.runtime\nimport tvm.target\n\nfrom . import utils\n\n\ndef find_lld(required=True):\n    \"\"\"Find ld.lld in system.\n\n    Parameters\n    ----------\n    required : bool\n        Whether it is required,\n        runtime error will be raised if the compiler is required.\n\n    Returns\n    -------\n    valid_list : list of str\n        List of possible paths.\n\n    Note\n    ----\n    This function will first search ld.lld that\n    matches the major llvm version that built with tvm\n    \"\"\"\n    lld_list = []\n    major = tvm.target.codegen.llvm_version_major(allow_none=True)\n    if major is not None:\n        lld_list += [\"ld.lld-%d.0\" % major]\n        lld_list += [\"ld.lld-%d\" % major]\n    lld_list += [\"ld.lld\"]\n    valid_list = [utils.which(x) for x in lld_list]\n    valid_list = [x for x in valid_list if x]\n    if not valid_list and required:\n        raise RuntimeError(\"cannot find ld.lld, candidates are: \" + str(lld_list))\n    return valid_list\n\n\ndef rocm_link(in_file, out_file, lld=None):\n    \"\"\"Link relocatable ELF object to shared ELF object using lld\n\n    Parameters\n    ----------\n    in_file : str\n        Input file name (relocatable ELF object file)\n\n    out_file : str\n        Output file name (shared ELF object file)\n\n    lld : str, optional\n        The lld linker, if not specified,\n        we will try to guess the matched clang version.\n    \"\"\"\n\n    # if our result has undefined symbols, it will fail to load\n    # (hipModuleLoad/hipModuleLoadData), but with a somewhat opaque message\n    # so we have ld.lld check this here.\n    # If you get a complaint about missing symbols you might want to check the\n    # list of bitcode files below.\n    args = [\n        lld if lld is not None else find_lld()[0],\n        \"--no-undefined\",\n        \"-shared\",\n        in_file,\n        \"-o\",\n        out_file,\n    ]\n    proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Linking error using ld.lld:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n\n@tvm._ffi.register_func(\"tvm_callback_rocm_link\")\ndef callback_rocm_link(obj_bin):\n    \"\"\"Links object file generated from LLVM to HSA Code Object\n\n    Parameters\n    ----------\n    obj_bin : bytearray\n        The object file\n\n    Return\n    ------\n    cobj_bin : bytearray\n        The HSA Code Object\n    \"\"\"\n    tmp_dir = utils.tempdir()\n    tmp_obj = tmp_dir.relpath(\"rocm_kernel.o\")\n    tmp_cobj = tmp_dir.relpath(\"rocm_kernel.co\")\n    with open(tmp_obj, \"wb\") as out_file:\n        out_file.write(bytes(obj_bin))\n    rocm_link(tmp_obj, tmp_cobj)\n    cobj_bin = bytearray(open(tmp_cobj, \"rb\").read())\n    return cobj_bin\n\n\n@tvm._ffi.register_func(\"tvm_callback_rocm_bitcode_path\")\ndef callback_rocm_bitcode_path(rocdl_dir=None):\n    \"\"\"Utility function to find ROCm device library bitcodes\n\n    Parameters\n    ----------\n    rocdl_dir : str\n        The path to rocm library directory\n        The default value is the standard location\n    \"\"\"\n    # seems link order matters.\n\n    if rocdl_dir is None:\n        if exists(\"/opt/rocm/amdgcn/bitcode/\"):\n            rocdl_dir = \"/opt/rocm/amdgcn/bitcode/\"  # starting with rocm 3.9\n        else:\n            rocdl_dir = \"/opt/rocm/lib/\"  # until rocm 3.8\n\n    bitcode_names = [\n        \"oclc_daz_opt_on\",\n        \"ocml\",\n        \"hc\",\n        \"irif\",  # this does not exist in rocm 3.9, drop eventually\n        \"ockl\",\n        \"oclc_correctly_rounded_sqrt_off\",\n        \"oclc_correctly_rounded_sqrt_on\",\n        \"oclc_daz_opt_off\",\n        \"oclc_finite_only_off\",\n        \"oclc_finite_only_on\",\n        \"oclc_isa_version_803\",  # todo (t-vi): an alternative might be to scan for the\n        \"oclc_isa_version_900\",  #              isa version files (if the linker throws out\n        \"oclc_isa_version_906\",  #              the unneeded ones or we filter for the arch we need)\n        \"oclc_unsafe_math_off\",\n        \"oclc_unsafe_math_on\",\n        \"oclc_wavefrontsize64_on\",\n    ]\n\n    bitcode_files = []\n    for n in bitcode_names:\n        p = join(rocdl_dir, n + \".bc\")  # rocm >= 3.9\n        if not exists(p):  # rocm <= 3.8\n            p = join(rocdl_dir, n + \".amdgcn.bc\")\n        if exists(p):\n            bitcode_files.append(p)\n        elif \"isa_version\" not in n and n not in {\"irif\"}:\n            raise RuntimeError(\"could not find bitcode \" + n)\n\n    return tvm.runtime.convert(bitcode_files)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Deprecation RPC module\"\"\"\n# pylint: disable=unused-import\nfrom __future__ import absolute_import as _abs\nimport warnings\nfrom ..rpc import Server, RPCSession, LocalSession, TrackerSession, connect, connect_tracker\n\nwarnings.warn(\n    \"Please use tvm.rpc instead of tvm.conrtib.rpc. tvm.contrib.rpc is going to be removed in 0.5\",\n    DeprecationWarning,\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/sdaccel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility for Interacting with SDAccel Tools\"\"\"\nimport subprocess\nimport os\n\nimport tvm._ffi\nfrom . import utils\n\n\n@tvm._ffi.register_func(\"tvm_callback_sdaccel_compile\")\ndef compile_vhls(kernel_info, device_name):\n    \"\"\"Compile Vivado HLS code for SDAccel.\n\n    Parameters\n    ----------\n    kernel_info : list of (str, str)\n        List of kernel information.  The kernel information is a tuple of\n        function name and source code.\n\n    device_name : str\n        The name of the target device\n\n    Return\n    ------\n    xclbin : bytearray\n        The bytearray of the xclbin\n    \"\"\"\n    tmp_dir = utils.tempdir()\n\n    sdk = os.environ.get(\"XILINX_SDX\", None)\n    xocc = os.path.join(sdk, \"bin/xocc\") if sdk else \"xocc\"\n    target = os.environ.get(\n        \"XCL_TARGET\", \"sw_emu\" if os.environ.get(\"XCL_EMULATION_MODE\") else \"hw\"\n    )\n    advanced_params = [\n        \"--xp\",\n        \"param:compiler.preserveHlsOutput=1\",\n        \"--xp\",\n        \"param:compiler.generateExtraRunData=true\",\n    ]\n    platform = device_name\n    if not platform:\n        platform = os.environ.get(\"XCL_PLATFORM\", os.environ.get(\"AWS_PLATFORM\"))\n\n    if platform is None:\n        raise RuntimeError(\"No Xilinx device specified.\")\n\n    tmp_xo_files = []\n    for funcname, code in kernel_info:\n        funcname = funcname.value\n        code = code.value\n\n        tmp_cpp = tmp_dir.relpath(funcname + \".cpp\")\n        tmp_xo = tmp_dir.relpath(funcname + \".xo\")\n\n        with open(tmp_cpp, \"wb\") as out_file:\n            out_file.write(bytes(code))\n\n        # build xo\n        args = (\n            [xocc, \"-c\", \"-t\", target, \"--platform\", platform, \"-o\", tmp_xo, \"-k\", funcname]\n            + advanced_params\n            + [tmp_cpp]\n        )\n        returncode = subprocess.call(args)\n        if returncode != 0:\n            raise RuntimeError(\"Compile error\")\n\n        tmp_xo_files.append(tmp_xo)\n\n    # build xclbin\n    tmp_xclbin = tmp_dir.relpath(\"output.xclbin\")\n    args = (\n        [xocc, \"-l\", \"-t\", target, \"--platform\", platform, \"-o\", tmp_xclbin]\n        + tmp_xo_files\n        + advanced_params\n    )\n    returncode = subprocess.call(args)\n    if returncode != 0:\n        raise RuntimeError(\"Link error\")\n\n    return bytearray(open(tmp_xclbin, \"rb\").read())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tensor and Operation class for computation declaration.\"\"\"\n# pylint: disable=invalid-name\nimport warnings\nimport numpy as _np\nfrom tvm.runtime import ndarray as _nd\nfrom tvm import te\nfrom tvm.tir import expr as _expr\nfrom tvm.te import tensor as _tensor\n\n\nfloat32 = \"float32\"\nitype = \"int32\"\n\n\nclass CSRNDArray(object):\n    \"\"\"Sparse tensor object in CSR format.\"\"\"\n\n    def __init__(self, arg1, device=None, shape=None):\n        \"\"\"Construct a sparse matrix in CSR format.\n\n        Parameters\n        ----------\n        arg1 : numpy.ndarray or a tuple with (data, indices, indptr)\n            The corresponding a dense numpy array,\n            or a tuple for constructing a sparse matrix directly.\n\n        device: Device\n            The corresponding device.\n\n        shape : tuple of int\n            The shape of the array\n        \"\"\"\n        if isinstance(arg1, tuple):\n            assert len(arg1) == 3\n            self.data, self.indices, self.indptr = arg1\n            self.shape = shape\n        elif isinstance(arg1, _np.ndarray):\n            source_array = arg1\n            ridx, cidx = _np.nonzero(source_array)\n            data = source_array[ridx, cidx]\n            self.data = _nd.array(data, device)\n            indices = _np.nonzero(source_array)[1].astype(itype)\n            self.indices = _nd.array(indices, device)\n            indptr = [0] + _np.apply_along_axis(\n                _np.count_nonzero, axis=1, arr=source_array\n            ).tolist()\n            indptr = _np.cumsum(_np.array(indptr, itype)).astype(itype)\n            self.indptr = _nd.array(indptr, device)\n            self.shape = source_array.shape\n        else:\n            raise RuntimeError(\n                \"Construct CSRNDArray with either a tuple (data, indices, indptr) \"\n                \"or a numpy.array, can't handle type %s.\" % (type(arg1),)\n            )\n        self.stype = \"csr\"\n        self.dtype = self.data.dtype\n        assert self.shape is not None\n        assert isinstance(self.data, _nd.NDArray)\n        assert isinstance(self.indices, _nd.NDArray)\n        assert str(self.indices.dtype) == \"int32\" or str(self.indices.dtype) == \"int64\", str(\n            self.indices.dtype\n        )\n        assert isinstance(self.indptr, _nd.NDArray)\n        assert str(self.indptr.dtype) == \"int32\" or str(self.indptr.dtype) == \"int64\", str(\n            self.indptr.dtype\n        )\n\n    def asnumpy(self):\n        \"\"\"Construct a full matrix and convert it to numpy array. This API will be deprecated\n        in TVM v0.8 release. Please use `numpy` instead.\"\"\"\n        warnings.warn(\n            \"CSRNDArray.asnumpy() will be deprecated in TVM v0.8 release. \"\n            \"Please use CSRNDArray.numpy() instead.\",\n            DeprecationWarning,\n        )\n        return self.numpy()\n\n    def numpy(self):\n        \"\"\"Construct a full matrix and convert it to numpy array.\"\"\"\n        full = _np.zeros(self.shape, self.dtype)\n        ridx = _np.diff(self.indptr.numpy())\n        ridx = _np.hstack((_np.ones((v,), itype) * i for i, v in enumerate(ridx)))\n        full[ridx, self.indices.numpy().astype(itype)] = self.data.numpy()\n        return full\n\n\ndef array(source_array, device=None, shape=None, stype=\"csr\"):\n    \"\"\"Construct a sparse NDArray from numpy.ndarray\"\"\"\n    ret = None\n    if stype == \"csr\":\n        ret = CSRNDArray(source_array, shape=shape, device=device)\n    else:\n        raise NotImplementedError(\"stype=%s is not supported yet.\" % (stype,))\n    return ret\n\n\nclass SparsePlaceholderOp(object):\n    \"\"\"Placeholder class for sparse tensor representations.\"\"\"\n\n    def __init__(self, shape, nonzeros, dtype, name):\n        # pylint: disable=unused-argument\n        \"\"\"Contructing a bare bone structure for a sparse matrix\n\n        Parameters\n        ----------\n        shape: Tuple of Expr\n            The shape of the tensor\n\n        nonzeros: int\n            The number of non-zero values\n\n        dtype: str, optional\n            The data type of the tensor\n\n        name: str, optional\n            The name hint of the tensor\n        \"\"\"\n        self.shape = shape\n        self.dtype = dtype\n        self.name = name\n        self.stype = \"unknown\"\n\n\nclass CSRPlaceholderOp(SparsePlaceholderOp):\n    \"\"\"Placeholder class for CSR based sparse tensor representation.\"\"\"\n\n    def __init__(self, shape, nonzeros, dtype, name):\n        \"\"\"Contructing a bare bone structure for a csr_matrix\n\n        Parameters\n        ----------\n        shape: Tuple of Expr\n            The shape of the tensor\n\n        nonzeros: int\n            The number of non-zero values\n\n        dtype: str, optional\n            The data type of the tensor\n\n        name: str, optional\n            The name hint of the tensor\n        \"\"\"\n        SparsePlaceholderOp.__init__(self, shape, nonzeros, dtype, name)\n        self.stype = \"csr\"\n        self.data = te.placeholder((nonzeros,), dtype=dtype, name=self.name + \"_data\")\n        self.indices = te.placeholder((nonzeros,), dtype=itype, name=self.name + \"_indices\")\n        self.indptr = te.placeholder((self.shape[0] + 1,), dtype=itype, name=self.name + \"_indptr\")\n        assert isinstance(self.data, _tensor.Tensor)\n        assert isinstance(self.indices, _tensor.Tensor)\n        assert isinstance(self.indptr, _tensor.Tensor)\n\n\ndef placeholder(shape, nonzeros=None, dtype=None, name=\"placeholder\", stype=None):\n    \"\"\"Construct an empty sparse tensor object.\n\n    Parameters\n    ----------\n    shape: Tuple of Expr\n        The shape of the tensor\n\n    nonzeros: int\n        The number of non-zero values\n\n    dtype: str, optional\n        The data type of the tensor\n\n    name: str, optional\n        The name hint of the tensor\n\n    stype: str, optional\n        The name storage type of the sparse tensor (e.g. csr, coo, ell)\n\n    Returns\n    -------\n    tensor: SparsePlaceholderOp\n        The created sparse tensor placeholder\n    \"\"\"\n    shape = (shape,) if isinstance(shape, _expr.PrimExpr) else shape\n    nonzeros = 0 if nonzeros is None else nonzeros\n    dtype = float32 if dtype is None else dtype\n    stype = \"csr\" if stype is None else stype\n    ret = None\n    if stype == \"csr\":\n        ret = CSRPlaceholderOp(shape=shape, nonzeros=nonzeros, dtype=dtype, name=name)\n    else:\n        raise NotImplementedError(\"stype=%s is not supported yet.\" % (stype,))\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/spirv.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility for Interacting with SPIRV Tools\"\"\"\nimport subprocess\nimport os\nfrom . import utils\nfrom .._ffi.base import py_str\n\n\ndef optimize(spv_bin):\n    \"\"\"Optimize SPIRV using spirv-opt via CLI\n\n    Note that the spirv-opt is still experimental.\n\n    Parameters\n    ----------\n    spv_bin : bytearray\n        The spirv file\n\n    Return\n    ------\n    cobj_bin : bytearray\n        The HSA Code Object\n    \"\"\"\n\n    tmp_dir = utils.tempdir()\n    tmp_in = tmp_dir.relpath(\"input.spv\")\n    tmp_out = tmp_dir.relpath(\"output.spv\")\n    with open(tmp_in, \"wb\") as out_file:\n        out_file.write(bytes(spv_bin))\n\n    sdk = os.environ.get(\"VULKAN_SDK\", None)\n    cmd = os.path.join(sdk, \"bin/spirv-opt\") if sdk else \"spirv-opt\"\n    args = [cmd, \"-O\", tmp_in, \"-o\", tmp_out]\n    proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Opitmizationerror using spirv-opt:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n    return bytearray(open(tmp_out, \"rb\").read())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/stackvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Dummy StackVM build function.\"\"\"\n# pylint: disable=invalid-name\nfrom __future__ import absolute_import as _abs\nimport shutil\n\n\ndef build(output, files):\n    \"\"\"Simply copy StackVM output to the destination.\n\n    Parameters\n    ----------\n    output : str\n        The target StackVM file.\n\n    files : list\n        A single self-contained StackVM module file.\n    \"\"\"\n\n    if len(files) == 0:\n        raise RuntimeError(\"StackVM artifact must be provided\")\n    if len(files) > 1:\n        raise RuntimeError(\"Unexpected multiple StackVM artifacts\")\n\n    shutil.copy(files[0], output)\n\n\n# assign output format\nbuild.output_format = \"stackvm\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/tar.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Util to invoke tarball in the system.\"\"\"\n# pylint: disable=invalid-name\nfrom __future__ import absolute_import as _abs\nimport os\nimport shutil\nimport subprocess\nfrom . import utils\nfrom .._ffi.base import py_str\n\n\ndef tar(output, files):\n    \"\"\"Create tarball containing all files in root.\n\n    Parameters\n    ----------\n    output : str\n        The target shared library.\n\n    files : list\n        List of files to be bundled.\n    \"\"\"\n    cmd = [\"tar\"]\n    cmd += [\"-czf\"]\n    temp = utils.tempdir()\n    fset = set()\n    for fname in files:\n        base = os.path.basename(fname)\n        if base in fset:\n            raise ValueError(\"duplicate file name %s\" % base)\n        fset.add(base)\n        shutil.copy(fname, temp.relpath(base))\n    cmd += [output]\n    cmd += [\"-C\", temp.temp_dir]\n    cmd += temp.listdir()\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Tar error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n\n# assign output format\ntar.output_format = \"tar\"\n\n\ndef untar(tar_file, directory):\n    \"\"\"Unpack all tar files into the directory\n\n    Parameters\n    ----------\n    tar_file : str\n        The source tar file.\n\n    directory : str\n        The target directory\n    \"\"\"\n    cmd = [\"tar\"]\n    cmd += [\"-xf\"]\n    cmd += [tar_file]\n    cmd += [\"-C\", directory]\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Tar error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/target/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/target/coreml.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, import-outside-toplevel\n\"\"\"Utility to compile CoreML models\"\"\"\n\nimport os\nimport shutil\n\nimport tvm._ffi\nfrom ...relay.expr_functor import ExprVisitor\nfrom .. import xcode, coreml_runtime\n\n\ndef _convert_add(builder, name, inputs, outputs, args, attrs):\n    builder.add_elementwise(name=name, input_names=inputs, output_name=outputs[0], mode=\"ADD\")\n\n\ndef _convert_multiply(builder, name, inputs, outputs, args, attrs):\n    builder.add_elementwise(name=name, input_names=inputs, output_name=outputs[0], mode=\"MULTIPLY\")\n\n\ndef _convert_clip(builder, name, inputs, outputs, args, attrs):\n    builder.add_clip(\n        name=name,\n        input_name=inputs[0],\n        output_name=outputs[0],\n        min_value=attrs.a_min,\n        max_value=attrs.a_max,\n    )\n\n\ndef _convert_batch_flatten(builder, name, inputs, outputs, args, attrs):\n    builder.add_flatten_to_2d(name=name, input_name=inputs[0], output_name=outputs[0])\n\n\ndef _convert_expand_dims(builder, name, inputs, outputs, args, attrs):\n    if attrs.axis >= 0:\n        axes = list(range(attrs.axis, attrs.axis + attrs.num_newaxis))\n    else:\n        axes = list(range(attrs.axis - attrs.num_newaxis + 1, attrs.axis + 1))\n\n    builder.add_expand_dims(name=name, input_name=inputs[0], output_name=outputs[0], axes=axes)\n\n\ndef _convert_relu(builder, name, inputs, outputs, args, attrs):\n    builder.add_activation(\n        name=name, non_linearity=\"RELU\", input_name=inputs[0], output_name=outputs[0]\n    )\n\n\ndef _convert_softmax(builder, name, inputs, outputs, args, attrs):\n    builder.add_softmax_nd(\n        name=name, input_name=inputs[0], output_name=outputs[0], axis=int(attrs[\"axis\"])\n    )\n\n\ndef _convert_conv2d(builder, name, inputs, outputs, args, attrs):\n    weight = args[1].data.numpy()\n    if attrs[\"kernel_layout\"] == \"OIHW\":\n        # convert to 'HWIO'\n        weight = weight.transpose([2, 3, 1, 0])\n    kh, kw, kc, oc = weight.shape\n\n    builder.add_convolution(\n        name=name,\n        kernel_channels=kc,\n        output_channels=oc,\n        height=kh,\n        width=kw,\n        stride_height=int(attrs[\"strides\"][0]),\n        stride_width=int(attrs[\"strides\"][0]),\n        border_mode=\"valid\",\n        groups=int(attrs[\"groups\"]),\n        W=weight,\n        b=None,\n        has_bias=False,\n        input_name=inputs[0],\n        output_name=outputs[0],\n        dilation_factors=[int(v) for v in attrs[\"dilation\"]],\n        padding_top=int(attrs[\"padding\"][0]),\n        padding_bottom=int(attrs[\"padding\"][2]),\n        padding_left=int(attrs[\"padding\"][1]),\n        padding_right=int(attrs[\"padding\"][3]),\n    )\n\n\ndef _convert_global_avg_pool2d(builder, name, inputs, outputs, args, attrs):\n    builder.add_pooling(\n        name=name,\n        height=1,\n        width=1,\n        stride_height=1,\n        stride_width=1,\n        layer_type=\"AVERAGE\",\n        padding_type=\"VALID\",\n        input_name=inputs[0],\n        output_name=outputs[0],\n        is_global=True,\n    )\n\n\n_convert_map = {\n    \"add\": _convert_add,\n    \"multiply\": _convert_multiply,\n    \"clip\": _convert_clip,\n    \"expand_dims\": _convert_expand_dims,\n    \"nn.relu\": _convert_relu,\n    \"nn.batch_flatten\": _convert_batch_flatten,\n    \"nn.softmax\": _convert_softmax,\n    \"nn.conv2d\": _convert_conv2d,\n    \"nn.global_avg_pool2d\": _convert_global_avg_pool2d,\n}\n\n\nclass CodegenCoreML(ExprVisitor):\n    \"\"\"\n    A visitor to traverse subgraphs and build Core ML models.\n    \"\"\"\n\n    def __init__(self, model_name, function):\n        import coremltools\n        from coremltools.models.neural_network import NeuralNetworkBuilder\n\n        ExprVisitor.__init__(self)\n        self.model_name = model_name\n        self.function = function\n        self.out_map = {}\n        self.model_inputs_ = []\n        self.buf_idx_ = 0\n\n        # Update inputs and outputs after we visit all the nodes.\n        # Set dummy values for now.\n        # TODO: support multiple outputs\n        inputs = [\n            (\n                \"\",\n                coremltools.models.datatypes.Array(\n                    1,\n                ),\n            )\n            for _ in self.function.params\n        ]\n        outputs = [\n            (\n                \"\",\n                coremltools.models.datatypes.Array(\n                    1,\n                ),\n            )\n        ]\n        self.builder = NeuralNetworkBuilder(inputs, outputs, disable_rank5_shape_mapping=True)\n\n    def visit_constant(self, const):\n        output = \"buf_\" + str(self.buf_idx_)\n        self.builder.add_load_constant_nd(\n            name=output,\n            output_name=output,\n            constant_value=const.data.numpy(),\n            shape=const.data.shape,\n        )\n        self.buf_idx_ = self.buf_idx_ + 1\n        self.out_map[const] = [output]\n\n    def visit_var(self, var):\n        name = var.name_hint\n        shape = [int(n) for n in var.type_annotation.shape]\n        dtype = var.type_annotation.dtype\n        self.model_inputs_.append((name, shape, dtype))\n        self.out_map[var] = [name]\n\n    def visit_call(self, call):\n        inputs = []\n        for arg in call.args:\n            super().visit(arg)\n            for out in self.out_map[arg]:\n                inputs.append(out)\n        outputs = [\"buf_\" + str(self.buf_idx_)]\n        op_name = call.op.name\n        layer_name = op_name + \"_\" + str(self.buf_idx_)\n\n        assert op_name in _convert_map, \"{} is not supported\".format(op_name)\n        _convert_map[op_name](self.builder, layer_name, inputs, outputs, call.args, call.attrs)\n\n        self.buf_idx_ = self.buf_idx_ + 1\n        self.out_map[call] = outputs\n\n    def compile(self, out_dir):\n        \"\"\"\n        Build a Core ML model and compile it with Xcode toolchain.\n        \"\"\"\n        import coremltools\n        from coremltools.proto.Model_pb2 import ArrayFeatureType\n\n        FEATURE_TYPE_MAP = {\n            \"float32\": ArrayFeatureType.FLOAT32,\n            \"float64\": ArrayFeatureType.DOUBLE,\n            \"int32\": ArrayFeatureType.INT32,\n        }\n\n        input_names, input_dims, input_dtypes = zip(*self.model_inputs_)\n        self.builder.set_input(input_names, input_dims)\n        for i, dtype in enumerate(input_dtypes):\n            assert dtype in FEATURE_TYPE_MAP\n            input_desc = self.builder.spec.description.input\n            input_desc[i].type.multiArrayType.dataType = FEATURE_TYPE_MAP[dtype]\n\n        output_dim = [int(n) for n in self.function.ret_type.shape]\n        self.builder.set_output(self.out_map[self.function.body], [output_dim])\n        for i, dtype in enumerate([self.function.ret_type.dtype]):\n            assert dtype in FEATURE_TYPE_MAP\n            output_desc = self.builder.spec.description.output\n            output_desc[i].type.multiArrayType.dataType = FEATURE_TYPE_MAP[dtype]\n\n        model = coremltools.models.MLModel(self.builder.spec)\n        xcode.compile_coreml(model, self.model_name, out_dir)\n\n\n@tvm._ffi.register_func(\"relay.ext.coremlcompiler\")\ndef coreml_compiler(func):\n    \"\"\"\n    Create a CoreML runtime from a Relay module.\n    \"\"\"\n    assert isinstance(func, tvm.relay.function.Function)\n    model_dir = os.getcwd()\n    name = str(func.attrs.global_symbol)\n    builder = CodegenCoreML(name, func)\n    builder.visit(func.body)\n    mlmodelc_path = \"{}/{}.mlmodelc\".format(model_dir, name)\n    if os.path.exists(mlmodelc_path):\n        shutil.rmtree(mlmodelc_path)\n    builder.compile(model_dir)\n\n    dev = tvm.cpu(0)\n    return coreml_runtime.create(name, mlmodelc_path, dev).module\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/target/onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, unused-argument, too-many-lines, redefined-builtin\n\"\"\"Relay to ONNX codegen \"\"\"\n\nimport os\nimport struct\nimport copy\nimport numpy\nimport onnx\nimport onnx.utils\nfrom onnx import numpy_helper, OperatorSetIdProto, defs\nfrom onnx import TensorProto\nimport tvm\nfrom tvm import relay\nimport tvm._ffi\nfrom tvm.relay.expr_functor import ExprVisitor\nfrom tvm.relay.ty import TupleType, TensorType\n\nONNX_OPSET_VERSONS_SUPPORTED = [11]\n\n\ndef run_onnx_optimizer(onnx_model):\n    \"\"\"Run ONNX's optimization routines.\n\n    ONNX Optimizer was moved to an external library in\n    version 1.9.  Attempt to use the optimizer in onnx if\n    it is available, fall back to the standalone\n    onnxoptimizer otherwise, and return the model\n    unoptimized if neither are available.\n\n    \"\"\"\n    try:\n        onnx_polish_model = onnx.utils.polish_model\n    except AttributeError:\n        pass\n    else:\n        return onnx_polish_model(onnx_model)\n\n    try:\n        # pylint: disable=import-outside-toplevel\n        import onnxoptimizer\n    except ImportError:\n        pass\n    else:\n        return onnxoptimizer.optimize(onnx_model)\n\n    return onnx_model\n\n\ndef tvm_array_to_list(arr):\n    return tuple(x.value for x in arr)\n\n\ndef get_onnx_version():\n    return onnx.__version__\n\n\ndef get_node_shape(node):\n    return tuple(\"Any\" if isinstance(i, tvm.tir.Any) else int(i) for i in node.shape)\n\n\ndef infer_type(node):\n    \"\"\"A method to infer the type of a relay expression.\"\"\"\n    mod = tvm.IRModule.from_expr(node)\n    mod = relay.transform.InferType()(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(node, relay.Function) else entry.body\n\n\ndef call_node_infer_type(node):\n    \"\"\"infer the output types of call node\"\"\"\n    infer_out = infer_type(node)\n    out_type = infer_out._checked_type_\n    if isinstance(out_type, TensorType):\n        types = [out_type]\n    elif isinstance(out_type, TupleType):\n        types = list(out_type.fields)\n    else:\n        raise RuntimeError(\n            \"Unsupported output type %s in operator %s\" % (type(out_type), node.op.nae)\n        )\n\n    return types\n\n\ndef add_input(data, name, prefix, model_container):\n    input_name = \"{}_{}\".format(prefix, name)\n    dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[data.dtype]\n    tensor_value_info = onnx.helper.make_tensor_value_info(input_name, dtype, shape=data.shape)\n    model_container.add_inputs([tensor_value_info])\n    data_tensor = numpy_helper.from_array(data, input_name)\n    model_container.add_initializers([data_tensor])\n    return input_name\n\n\nclass OpConverter(object):\n    \"\"\"Operator converter Base Class.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        \"\"\"convert Relay attributes to ONNX attributes.\n        The derived classes should implement this method\n        if attributes are required by the operator\n        otherwise by default no attributes are passed\n        \"\"\"\n        return {}\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n        onnx_node = onnx.helper.make_node(\n            cls.__name__, node_entry[\"input_names\"], node_entry[\"output_names\"], **attrs\n        )\n        model_container.add_nodes([onnx_node])\n\n\ndef rename(op_name):\n    \"\"\"This method creates dynamic operator of name op_name with empty attributes\"\"\"\n    return type(op_name, (OpConverter,), {})\n\n\nclass Reshape(object):\n    \"\"\"Operator converter for Reshape.\"\"\"\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        \"\"\"Converts Relay operator Reshape to ONNX operator.\n        Relay operator accepts shape as attribute but ONNX operator\n        accepts it as a input.\n        \"\"\"\n        name = node_entry[\"name\"]\n        shape = numpy.asarray(\n            [a.value for a in node_entry[\"relay_node\"].attrs.newshape], dtype=numpy.int64\n        )\n\n        input_names = [\n            node_entry[\"input_names\"][0],\n            add_input(shape, name, \"shape\", model_container),\n        ]\n\n        node = onnx.helper.make_node(cls.__name__, input_names, node_entry[\"output_names\"])\n        model_container.add_nodes([node])\n\n\nclass Conv(OpConverter):\n    \"\"\"Operator converter for Conv.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"group\": attrs.get_int(\"groups\"),\n            \"pads\": attrs.get_int_tuple(\"padding\"),\n            \"strides\": attrs.get_int_tuple(\"strides\"),\n            \"dilations\": attrs.get_int_tuple(\"dilation\"),\n            \"kernel_shape\": attrs.get_int_tuple(\"kernel_size\"),\n        }\n\n\nclass ConvTranspose(OpConverter):\n    \"\"\"Operator converter for ConvTranspose.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"group\": attrs.get_int(\"groups\"),\n            \"pads\": attrs.get_int_tuple(\"padding\"),\n            \"strides\": attrs.get_int_tuple(\"strides\"),\n            \"dilations\": attrs.get_int_tuple(\"dilation\"),\n            \"kernel_shape\": attrs.get_int_tuple(\"kernel_size\"),\n            \"output_padding\": attrs.get_int_tuple(\"output_padding\"),\n        }\n\n\nclass MaxPool(OpConverter):\n    \"\"\"Operator converter for MaxPool.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"pads\": attrs.get_int_tuple(\"padding\"),\n            \"strides\": attrs.get_int_tuple(\"strides\"),\n            \"kernel_shape\": attrs.get_int_tuple(\"pool_size\"),\n            \"ceil_mode\": 1 if attrs.ceil_mode else 0,\n        }\n\n\nclass Transpose(OpConverter):\n    \"\"\"Operator converter for Transpose.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"perm\": attrs.get_int_tuple(\"axes\")} if attrs[\"axes\"] else {}\n\n\nclass MatMul(OpConverter):\n    \"\"\"Operator converter for MatMul.\"\"\"\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        inter_output_name = \"inter{}\".format(node_entry[\"name\"])\n        transpose_node = onnx.helper.make_node(\n            Transpose.__name__, [node_entry[\"input_names\"][1]], [inter_output_name], perm=(1, 0)\n        )\n        model_container.add_nodes([transpose_node])\n\n        inputs = [node_entry[\"input_names\"][0], inter_output_name]\n        matmul_node = onnx.helper.make_node(cls.__name__, inputs, node_entry[\"output_names\"])\n        model_container.add_nodes([matmul_node])\n\n\nclass Flatten(OpConverter):\n    \"\"\"Operator converter for Flatten.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"axis\": 1,\n        }\n\n\nclass BatchNormalization(OpConverter):\n    \"\"\"Operator converter for BatchNormalization.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"epsilon\": float(attrs.get_str(\"epsilon\")),\n            \"axis\": float(attrs.get_int(\"axis\")),\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        \"\"\"Converts Relay operator batch_norm to ONNX operator.\n        Relay operator has property axis to handle data in NHWC format.\n        \"\"\"\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n        transpose_out_name = node_entry[\"input_names\"][0]\n        inter_output_names = [node_entry[\"output_names\"][0]]\n        # axis==3 means channel is specified along the 3rd axis\n        if attrs[\"axis\"] == 3:\n            transpose_out_name = \"transpose_{}\".format(node_entry[\"name\"])\n            node_transposed = onnx.helper.make_node(\n                Transpose.__name__,\n                [node_entry[\"input_names\"][0]],\n                [transpose_out_name],\n                perm=[0, 3, 1, 2],\n            )\n            model_container.add_nodes([node_transposed])\n            inter_output_names = [\"batch_norm_{}\".format(node_entry[\"name\"])]\n\n        input_names = [transpose_out_name] + node_entry[\"input_names\"][1:]\n        batch_norm_node = onnx.helper.make_node(\n            cls.__name__, input_names, inter_output_names, epsilon=attrs[\"epsilon\"]\n        )\n        model_container.add_nodes([batch_norm_node])\n\n        if attrs[\"axis\"] == 3:\n            node_transposed = onnx.helper.make_node(\n                Transpose.__name__,\n                inter_output_names,\n                [node_entry[\"output_names\"][0]],\n                perm=[0, 2, 3, 1],\n            )\n            model_container.add_nodes([node_transposed])\n\n\nclass Dropout(OpConverter):\n    \"\"\"Operator converter for Dropout.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"ratio\": float(attrs.get_str(\"rate\")),\n        }\n\n\nclass AveragePool(MaxPool):\n    \"\"\"Operator converter for AveragePool.\"\"\"\n\n\nclass Concat(OpConverter):\n    \"\"\"Operator converter for Concat.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"axis\": attrs.get_int(\"axis\"),\n        }\n\n\nclass BiasAdd(OpConverter):\n    \"\"\"Operator converter for BiasAdd.\"\"\"\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node_entry can not be a Tuple\"\n        input_node = input_node[0]\n        data_ndim = len(input_node[\"types\"][0].shape)\n        axis = node_entry[\"relay_node\"].attrs.get_int(\"axis\")\n        if axis < 0:\n            axis = axis + data_ndim\n        new_axes = data_ndim - axis - 1\n        if new_axes:\n            inter_output_name = \"inter{}\".format(node_entry[\"name\"])\n            unsqueeze_node = onnx.helper.make_node(\n                \"Unsqueeze\",\n                [node_entry[\"input_names\"][1]],\n                [inter_output_name],\n                axes=tuple(range(1, new_axes + 1)),\n            )\n            model_container.add_nodes([unsqueeze_node])\n        else:\n            inter_output_name = node_entry[\"input_names\"][1]\n\n        inputs = [node_entry[\"input_names\"][0], inter_output_name]\n        matmul_node = onnx.helper.make_node(\"Add\", inputs, node_entry[\"output_names\"])\n        model_container.add_nodes([matmul_node])\n\n\nclass ReduceMean(OpConverter):\n    \"\"\"Operator converter for ReduceMean.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"axes\": attrs.axis,\n            \"keepdims\": 0 if bool(attrs.get_int(\"keepdims\", 0)) is False else 1,\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        shape = input_node[\"types\"][0].shape\n        axis = node_entry[\"relay_node\"].attrs.axis\n        axis = list(range(shape.size())) if not axis else tvm_array_to_list(axis)\n        exclude = 0 if not bool(node_entry[\"relay_node\"].attrs.exclude) else 1\n        keepdims = 0 if not bool(node_entry[\"relay_node\"].attrs.keepdims) else 1\n        if exclude:\n            all_axis = list(range(len(shape)))\n            axis = set(all_axis) - set(axis)\n\n        node = onnx.helper.make_node(\n            cls.__name__,\n            node_entry[\"input_names\"],\n            node_entry[\"output_names\"],\n            axes=axis,\n            keepdims=keepdims,\n        )\n        model_container.add_nodes([node])\n\n\nclass Pad(OpConverter):\n    \"\"\"Operator converter for Pad.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        before = []\n        after = []\n        for axis_pads in attrs.pad_width:\n            before.append(axis_pads[0])\n            after.append(axis_pads[1])\n        pads = before + after\n        pads = numpy.asarray(pads, dtype=pads[0].dtype)\n        return {\n            \"pads\": pads,\n            \"mode\": attrs.get_str(\"pad_mode\"),\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        \"\"\"Converts Relay operator Pad to ONNX operator.\n        Relay operator accepts pads as attribute but ONNX operator\n        accepts it as a input.\n        \"\"\"\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        name = node_entry[\"name\"]\n        pad_data = numpy.asarray(attrs[\"pads\"], dtype=attrs[\"pads\"][0].dtype).astype(numpy.int64)\n\n        input_names = [\n            node_entry[\"input_names\"][0],\n            add_input(pad_data, name, \"pads\", model_container),\n            node_entry[\"input_names\"][1],\n        ]\n\n        node = onnx.helper.make_node(\n            cls.__name__, input_names, node_entry[\"output_names\"], mode=attrs[\"mode\"]\n        )\n        model_container.add_nodes([node])\n\n\nclass Softmax(OpConverter):\n    \"\"\"Operator converter for SoftMax.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"axis\": attrs.axis,\n        }\n\n\nclass Squeeze(OpConverter):\n    \"\"\"Operator converter for Squeeze.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"axes\": attrs.axis,\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        shape = input_node[\"types\"][0].shape\n        axis = node_entry[\"relay_node\"].attrs.get_int(\"axis\")\n        if not axis:\n            axis = []\n            for axis_idx, val in enumerate(shape):\n                if val.value == 1:\n                    axis.append(axis_idx)\n        else:\n            axis = node_entry[\"relay_node\"].attrs.get_int_tuple(\"axis\")\n\n        node = onnx.helper.make_node(\n            cls.__name__, node_entry[\"input_names\"], node_entry[\"output_names\"], axes=axis\n        )\n        model_container.add_nodes([node])\n\n\nclass Slice(OpConverter):\n    \"\"\"Operator converter for Slice.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\n            \"starts\": attrs.get_int_tuple(\"begin\"),\n            \"ends\": attrs.get_int_tuple(\"end\"),\n            \"steps\": attrs.get_int_tuple(\"strides\"),\n            \"slice_mode\": attrs.get_str(\"slice_mode\"),\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        name = node_entry[\"name\"]\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        shape = input_node[\"types\"][0].shape\n\n        starts = list(attrs[\"starts\"])\n        ends = list(attrs[\"ends\"])\n        steps = list(attrs[\"steps\"])\n        starts += [0] * (len(shape) - len(starts))\n        ends += [shape[i] + 1 for i in range(len(ends), len(shape))]\n        axes = list(range(len(shape)))\n\n        if attrs[\"slice_mode\"] == \"size\":\n            ends = [\n                starts[i] + (shape[i] + 1 if ends[i] < 0 else ends[i]) for i in range(len(shape))\n            ]\n            steps = [1] * len(shape)\n        else:\n            steps += [1] * (len(shape) - len(steps))\n\n        starts = numpy.asarray(starts).astype(numpy.int64)\n        ends = numpy.asarray(ends).astype(numpy.int64)\n        axes = numpy.asarray(axes).astype(numpy.int64)\n        steps = numpy.asarray(steps).astype(numpy.int64)\n\n        input_names = []\n        input_names.append(add_input(starts, name, \"starts\", model_container))\n        input_names.append(add_input(ends, name, \"ends\", model_container))\n        input_names.append(add_input(axes, name, \"axes\", model_container))\n        input_names.append(add_input(steps, name, \"steps\", model_container))\n\n        input_names = [node_entry[\"input_names\"][0]] + input_names\n\n        slice_node = onnx.helper.make_node(cls.__name__, input_names, node_entry[\"output_names\"])\n        model_container.add_nodes([slice_node])\n\n\nclass Split(OpConverter):\n    \"\"\"Operator converter for Split.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        indices_or_sections = attrs[\"indices_or_sections\"]\n\n        if isinstance(indices_or_sections, (list, tvm.ir.container.Array)):\n            indices_or_sections = attrs.get_int_tuple(\"indices_or_sections\")\n        if isinstance(indices_or_sections, tvm.ir.PrimExpr):\n            indices_or_sections = indices_or_sections.value\n\n        return {\n            \"indices_or_section\": indices_or_sections,\n            \"axis\": attrs.get_int(\"axis\"),\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        shape = get_node_shape(input_node[\"types\"][0])\n\n        indices_or_sect = attrs[\"indices_or_section\"]\n        axis = attrs[\"axis\"]\n        axis_length = shape[axis]\n\n        if isinstance(indices_or_sect, int):\n            split = [axis_length // indices_or_sect] * indices_or_sect\n        else:\n            split = []\n            for i in range(len(indices_or_sect) + 1):\n                if i == 0:\n                    split.append(indices_or_sect[0])\n                elif i == len(indices_or_sect):\n                    split.append(axis_length - indices_or_sect[-1])\n                else:\n                    split.append(indices_or_sect[i] - indices_or_sect[i - 1])\n\n        slice_node = onnx.helper.make_node(\n            cls.__name__,\n            node_entry[\"input_names\"],\n            node_entry[\"output_names\"],\n            split=split,\n            axis=axis,\n        )\n        model_container.add_nodes([slice_node])\n\n\nclass LayoutTransform(OpConverter):\n    \"\"\"Operator converter for Layouttransform\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        src_layout = attrs.get_str(\"src_layout\")\n        dst_layout = attrs.get_str(\"dst_layout\")\n\n        perm = [src_layout.index(c) for c in dst_layout]\n        return {\"perm\": tuple(perm)}\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n        onnx_node = onnx.helper.make_node(\n            \"Transpose\", node_entry[\"input_names\"], node_entry[\"output_names\"], **attrs\n        )\n        model_container.add_nodes([onnx_node])\n\n\nclass Clip(OpConverter):\n    \"\"\"Operator converter for Clip.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"min\": attrs.a_min, \"max\": attrs.a_max}\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        name = node_entry[\"name\"]\n\n        min_val = numpy.asarray(attrs[\"min\"]).astype(numpy.float32)\n        max_val = numpy.asarray(attrs[\"max\"]).astype(numpy.float32)\n\n        input_names = []\n        input_names.append(add_input(min_val, name, \"min\", model_container))\n        input_names.append(add_input(max_val, name, \"max\", model_container))\n\n        input_names = [node_entry[\"input_names\"][0]] + input_names\n\n        node = onnx.helper.make_node(cls.__name__, input_names, node_entry[\"output_names\"])\n        model_container.add_nodes([node])\n\n\nclass Expand(OpConverter):\n    \"\"\"Operator converter for Expand_dims.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"axis\": attrs.axis, \"num_newaxis\": attrs.num_newaxis}\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        name = node_entry[\"name\"]\n\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node_entry can not be a Tuple\"\n        input_node = input_node[0]\n        data_shape = input_node[\"types\"][0].shape\n        new_shape = list(data_shape)\n\n        for _ in range(attrs[\"num_newaxis\"]):\n            new_shape.insert(attrs[\"axis\"], 1)\n\n        new_shape = numpy.asarray(new_shape).astype(numpy.int64)\n        input_names = []\n        input_names.append(add_input(new_shape, name, \"shape\", model_container))\n\n        input_names = [node_entry[\"input_names\"][0]] + input_names\n\n        node = onnx.helper.make_node(cls.__name__, input_names, node_entry[\"output_names\"])\n        model_container.add_nodes([node])\n\n\nclass ConstantOfShapeZeros(OpConverter):\n    \"\"\"Operator converter for ConstantOfShape.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"value\": 0}\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        dtype = input_node[\"types\"][0].dtype\n\n        name = node_entry[\"name\"]\n        shape = [val.value for val in input_node[\"types\"][0].shape]\n        shape = numpy.asarray(shape).astype(numpy.int64)\n\n        input_names = []\n        input_names.append(add_input(shape, name, \"shape\", model_container))\n\n        dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[numpy.dtype(dtype)]\n        tensor_value = onnx.helper.make_tensor(\"value\", dtype, [1], [attrs[\"value\"]])\n\n        node = onnx.helper.make_node(\n            \"ConstantOfShape\", input_names, node_entry[\"output_names\"], value=tensor_value\n        )\n        model_container.add_nodes([node])\n\n\nclass ConstantOfShapeOnes(ConstantOfShapeZeros):\n    \"\"\"Operator converter for ConstantOfShape.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"value\": 1}\n\n\nclass LRN(OpConverter):\n    \"\"\"Operator converter for LRN.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        \"\"\"axis attr is not supported as an argument in onnx.\n        Onnx only supports axis=1 (channels).\"\"\"\n        if attrs.get_int(\"axis\") != 1:\n            raise RuntimeError(\n                \"Unsupported axis %s in operator relay lrn operator. \"\n                \"Only axis = 1 is supported by Onnx.\" % (attrs.get_int(\"axis\"))\n            )\n\n        return {\"alpha\": attrs.alpha, \"beta\": attrs.beta, \"bias\": attrs.bias, \"size\": attrs.size}\n\n\nclass Cast(OpConverter):\n    \"\"\"Operator converter for Cast.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        return {\"to\": getattr(TensorProto, attrs.dtype.upper())}\n\n\nclass Resize(OpConverter):\n    \"\"\"Operator converter for Resize.\"\"\"\n\n    @classmethod\n    def convert_attributes(cls, attrs):\n        method = attrs.get_str(\"method\")\n        if method == \"nearest_neighbor\":\n            mode = b\"nearest\"\n        elif \"linear\" in method:  # linear / bilinear\n            mode = b\"linear\"\n        elif \"cubic\" in method:  # cubic / bicubic\n            mode = b\"cubic\"\n        else:\n            raise RuntimeError(\"Unsupported method %s in operator Resize\" % method)\n\n        coord_trans = attrs.get_str(\"coordinate_transformation_mode\")\n        if coord_trans == \"half_pixel\":\n            coord_trans = b\"half_pixel\"\n        elif coord_trans == \"align_corners\":\n            coord_trans = b\"align_corners\"\n        elif coord_trans == \"asymmetric\":\n            coord_trans = b\"asymmetric\"\n        else:\n            raise RuntimeError(\n                \"Unsupported coordinate transform mode %s in operator Resize\" % coord_trans\n            )\n\n        rounding_method = attrs.get_str(\"rounding_method\")\n        if rounding_method == \"round\":\n            rounding_method = b\"round_prefer_ceil\"\n        elif rounding_method == \"floor\":\n            rounding_method = b\"floor\"\n        elif rounding_method == \"ceil\":\n            rounding_method = b\"ceil\"\n        else:\n            raise RuntimeError(\n                \"Unsupported rounding method %s in operator Resize\" % rounding_method\n            )\n\n        size = attrs.get_int_tuple(\"size\")\n\n        return {\n            \"mode\": mode,\n            \"coord_trans\": coord_trans,\n            \"size\": size,\n            \"nearest_mode\": rounding_method,\n        }\n\n    @classmethod\n    def convert(cls, node_entry, model_container, node_dict):\n        attrs = cls.convert_attributes(node_entry[\"relay_node\"].attrs)\n\n        name = node_entry[\"name\"]\n        input_node = node_dict[node_entry[\"inputs\"][0]]\n        assert len(input_node) == 1, \"input node can not be a Tuple\"\n        input_node = input_node[0]\n        input_shape = input_node[\"types\"][0].shape\n\n        # (TBD) needed in opset 11\n        roi = [0] * len(input_shape) + [1] * len(input_shape)\n        roi_array = numpy.asarray(roi).astype(numpy.float64)\n        roi_node = add_input(roi_array, name, \"roi\", model_container)\n\n        out_size = attrs[\"size\"]\n\n        # (onnx) rank of scale / size must match rank of X\n        # relay size node contains only spatial dimensions\n        # pad with 1s to match rank\n        match_rank_pad = len(input_shape) - len(out_size)\n        out_size_full_rank = input_shape[:match_rank_pad] + list(out_size)\n        out_size_array = numpy.asarray(out_size_full_rank).astype(numpy.int64)\n\n        input_size_array = numpy.asarray(list(input_shape)).astype(numpy.int64)\n\n        scale_array = numpy.divide(out_size_array, input_size_array).astype(numpy.float32)\n        scale_node = add_input(scale_array, name, \"scales\", model_container)\n\n        input_names = [node_entry[\"input_names\"][0], roi_node, scale_node]\n\n        resize_node = onnx.helper.make_node(\n            cls.__name__,\n            input_names,\n            node_entry[\"output_names\"],\n            mode=attrs[\"mode\"],\n            coordinate_transformation_mode=attrs[\"coord_trans\"],\n            nearest_mode=attrs[\"nearest_mode\"],\n        )\n        model_container.add_nodes([resize_node])\n\n\nrelay_to_onnx_op_mapping = {\n    \"reshape\": Reshape,\n    \"nn.conv2d\": Conv,\n    \"nn.conv2d_transpose\": ConvTranspose,\n    \"add\": rename(\"Add\"),\n    \"nn.relu\": rename(\"Relu\"),\n    \"transpose\": Transpose,\n    \"nn.dense\": MatMul,\n    \"nn.max_pool2d\": MaxPool,\n    \"nn.batch_flatten\": Flatten,\n    \"multiply\": rename(\"Mul\"),\n    \"nn.bias_add\": BiasAdd,\n    \"nn.batch_norm\": BatchNormalization,\n    \"nn.global_avg_pool2d\": rename(\"GlobalAveragePool\"),\n    \"concatenate\": Concat,\n    \"nn.dropout\": Dropout,\n    \"nn.avg_pool2d\": AveragePool,\n    \"divide\": rename(\"Div\"),\n    \"mean\": ReduceMean,\n    \"nn.pad\": Pad,\n    \"nn.softmax\": Softmax,\n    \"squeeze\": Squeeze,\n    \"strided_slice\": Slice,\n    \"greater\": rename(\"Greater\"),\n    \"less\": rename(\"Less\"),\n    \"equal\": rename(\"Equal\"),\n    \"zeros_like\": ConstantOfShapeZeros,\n    \"ones_like\": ConstantOfShapeOnes,\n    \"subtract\": rename(\"Sub\"),\n    \"split\": Split,\n    \"exp\": rename(\"Exp\"),\n    \"layout_transform\": LayoutTransform,\n    \"clip\": Clip,\n    \"expand_dims\": Expand,\n    \"nn.lrn\": LRN,\n    \"sigmoid\": rename(\"Sigmoid\"),\n    \"copy\": rename(\"Identity\"),\n    \"round\": rename(\"Round\"),\n    \"cast\": Cast,\n    \"image.resize2d\": Resize,\n}\n\n\nclass ModelContainer(object):\n    \"\"\"A container class to hold  different attributes of ONNX model graph\"\"\"\n\n    def __init__(self, name, opset_version):\n        self._name = name\n        self._opset_version = opset_version\n        self._inputs = []\n        self._outputs = []\n        self._nodes = []\n        self._initializers = []\n\n    def add_inputs(self, inputs):\n        self._inputs.extend(inputs)\n\n    def add_outputs(self, outputs):\n        self._outputs.extend(outputs)\n\n    def add_nodes(self, nodes):\n        self._nodes.extend(nodes)\n\n    def add_initializers(self, initializers):\n        self._initializers.extend(initializers)\n\n    def _get_opsets(self):\n        opsets = []\n        imp = OperatorSetIdProto()\n        imp.version = self._opset_version\n        opsets.append(imp)\n        return opsets\n\n    def make_model(self):\n        \"\"\"Creates the onnx model from the graph\"\"\"\n        onnx_graph = onnx.helper.make_graph(\n            self._nodes, self._name, self._inputs, self._outputs, self._initializers\n        )\n        kwargs = {}\n        kwargs[\"opset_imports\"] = self._get_opsets()\n        kwargs[\"producer_name\"] = \"TVM Relay\"\n        kwargs[\"producer_version\"] = tvm.__version__\n\n        return onnx.helper.make_model(onnx_graph, **kwargs)\n\n\nclass RelayToONNXConverter(ExprVisitor):\n    \"\"\"A helper class to traverse the Relay graph and convert Relay nodes to ONNX model\n\n    Parameters\n    ----------\n    name : str\n       name of the model\n\n    params : dict\n        dict of the parameter names and NDarray values\n\n    opset_version : int\n        target onnx opset version\n\n    \"\"\"\n\n    def __init__(self, name, params, opset_version):\n        super().__init__()\n        self._name = name\n        self._mc = ModelContainer(name, opset_version)\n        self._params = params\n        self._node_dict = {}\n        self._node_count = 0\n        self.last_node = None\n\n    @classmethod\n    def _get_node_entry(cls, relay_node, name):\n        return {\n            \"relay_node\": relay_node,\n            \"inputs\": [relay_node],  # inputs in the form of relay nodes\n            \"types\": [],  # output types in case of call nodes else self type\n            \"name\": name,  # name of the node\n            \"input_names\": [name],  # input names in case of call nodes else self name\n            \"output_names\": [name],  # output names in case of call nodes else self name\n            \"op\": None,  # op name in case of call node else None\n        }\n\n    def convert_to_onnx(self, func):\n        \"\"\"Traverse Relay graph and generate a ONNX model\"\"\"\n\n        self.visit(func)\n        self._add_output(self._node_dict[self.last_node])\n        model = self._mc.make_model()\n        return run_onnx_optimizer(model)\n\n    def visit(self, expr):\n        self._node_count += 1\n        super().visit(expr)\n\n    def visit_constant(self, const):\n        node_index = self._node_count\n        name = self._name + \"_const_\" + str(node_index)\n        node_entry = self._get_node_entry(const, name)\n        node_entry[\"types\"] = [const.checked_type]\n\n        self._add_constant_input(node_entry, node_index)\n        self._node_dict[const] = [node_entry]\n\n    def visit_var(self, var):\n        node_index = self._node_count\n        node_entry = self._get_node_entry(var, var.name_hint)\n        node_entry[\"types\"] = [var.type_annotation]\n\n        self._add_input(node_entry, node_index)\n        self._node_dict[var] = [node_entry]\n\n    def visit_tuple(self, tup):\n        self._node_dict[tup] = []\n        for f in tup.fields:\n            self.visit(f)\n            self._node_dict[tup].extend(self._node_dict[f])\n\n        self.last_node = tup\n\n    def visit_tuple_getitem(self, t):\n        self.visit(t.tuple_value)\n        tup_node = self._node_dict[t.tuple_value]\n        if len(tup_node) > 1:\n            self._node_dict[t] = tup_node[t.index]\n        else:\n            node_entry = copy.deepcopy(tup_node[0])\n            output_names = [node_entry[\"output_names\"][t.index]]\n            node_entry[\"output_names\"] = output_names\n            self._node_dict[t] = [node_entry]\n        self.last_node = t\n\n    def visit_call(self, call):\n        node_index = self._node_count\n        op = call.op\n        name = \"{}_{}\".format(op, node_index)\n        node_entry = self._get_node_entry(call, name)\n\n        node_entry[\"op\"] = op\n        node_entry[\"input_names\"] = []\n        node_entry[\"inputs\"] = []\n        node_entry[\"output_names\"] = None\n        for input_arg in call.args:\n            self.visit(input_arg)\n            input_names = []\n            for arg_node_entry in self._node_dict[input_arg]:\n                input_names.extend(arg_node_entry[\"output_names\"])\n            node_entry[\"input_names\"].extend(input_names)\n            node_entry[\"inputs\"].extend([input_arg])\n\n        node_entry[\"types\"] = call_node_infer_type(call)\n        node_entry[\"output_names\"] = []\n        for i in range(len(node_entry[\"types\"])):\n            node_entry[\"output_names\"].append(name + str(i))\n        self.last_node = call\n        self._add_node(node_entry, node_index)\n        self._node_dict[call] = [node_entry]\n\n    def _add_node(self, node_entry, idx):\n        \"\"\"Convert Relay operator node to ONNX operator and add it to container nodes list\"\"\"\n        if node_entry[\"op\"].name not in relay_to_onnx_op_mapping:\n            raise NotImplementedError(\n                \"Currently the operator '{0}' is \" \"not supported.\".format(node_entry[\"op\"].name)\n            )\n        converter = relay_to_onnx_op_mapping[node_entry[\"op\"].name]()\n\n        return converter.convert(node_entry, self._mc, self._node_dict)\n\n    def _add_params(self, node_entry, idx):\n        \"\"\"Add param value to initializer and name to inputs\"\"\"\n        param_name = node_entry[\"name\"]\n        assert (\n            param_name in self._params\n        ), \"The parameter {0} is not present\" \"in params dict provided.\".format(param_name)\n        value = self._params[param_name]\n        numpy_array = value.numpy()\n        tensor = numpy_helper.from_array(numpy_array, param_name)\n        self._mc.add_initializers([tensor])\n        dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[numpy_array.dtype]\n        input = onnx.helper.make_tensor_value_info(param_name, dtype, shape=numpy_array.shape)\n        self._mc.add_inputs([input])\n\n    def _add_constant_input(self, node_entry, idx):\n        \"\"\"Create named input for constant and add it to container inputs.\n        If input is a parameter then add to param\n        \"\"\"\n        node = node_entry[\"relay_node\"]\n        param_name = node_entry[\"name\"]\n        self._params[param_name] = node.data\n        self._add_params(node_entry, idx)\n\n    def _add_input(self, node_entry, idx):\n        \"\"\"Add input node to container inputs. If input is a parameter then add to param\"\"\"\n        if node_entry[\"name\"] in self._params:\n            self._add_params(node_entry, idx)\n        else:\n            node_type = node_entry[\"types\"][0]\n            dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[numpy.dtype(node_type.dtype)]\n            input = onnx.helper.make_tensor_value_info(\n                node_entry[\"name\"], dtype, shape=get_node_shape(node_type)\n            )\n            self._mc.add_inputs([input])\n\n    def _add_output(self, node_entries):\n        \"\"\"Add output node to container outputs.\"\"\"\n\n        for node_entry in node_entries:\n            for node_type, output_name in zip(node_entry[\"types\"], node_entry[\"output_names\"]):\n                dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[numpy.dtype(node_type.dtype)]\n                output = onnx.helper.make_tensor_value_info(\n                    output_name, dtype, shape=get_node_shape(node_type)\n                )\n                self._mc.add_outputs([output])\n\n\ndef to_onnx(relay_ir, params, name, opset_version=11, path=None):\n    \"\"\"Convert a Relay Function Module into an equivalent ONNX and serialize it to the path\n\n    Parameters\n    ----------\n    relay_ir : tvm.ir.IRModule or tvm.relay.Function\n        The relay module object\n\n    params : dict\n        dict of the parameter names and NDarray values\n\n    name : str\n        name of the output ONNX graph\n\n    opset_version : int\n        target onnx opset version\n\n    path : str\n        The path where ONNX model will be saved\n\n    Returns\n    -------\n    onnx_model : onnx.ModelProto\n        converted ONNX model as a ModelProto.\n\n    \"\"\"\n\n    if opset_version not in ONNX_OPSET_VERSONS_SUPPORTED:\n        raise NotImplementedError(\"Currently only opset version 11 is supported.\")\n\n    if opset_version > defs.onnx_opset_version():\n        raise Exception(\n            \"The ONNX package installed of version {} does not support the opset \"\n            \"version {}. Upgrade the ONNX package to latest version.\".format(\n                get_onnx_version(), opset_version\n            )\n        )\n\n    func = relay_ir[\"main\"] if isinstance(relay_ir, tvm.ir.IRModule) else relay_ir\n    converter = RelayToONNXConverter(name, params, opset_version)\n    onnx_model = converter.convert_to_onnx(func)\n\n    if path:\n        onnx.save(onnx_model, path)\n    return onnx_model\n\n\n@tvm._ffi.register_func(\"relay.ext.onnx\")\ndef onnx_compiler(func):\n    \"\"\"Create a runtime module for ONNX from Relay Function\n\n    :param func: Relay function\n    :return: runtime module for ONNX\n    \"\"\"\n\n    assert isinstance(func, tvm.relay.function.Function)\n    name = str(func.attrs.global_symbol)\n    model = to_onnx(func, {}, name)\n    const_vars = [const.name for const in model.graph.initializer]\n    name_bytes = bytes(name, \"utf-8\")\n    name_size = struct.pack(\"I\", len(name_bytes))\n    model_serialized = model.SerializeToString()\n    model_size = struct.pack(\"I\", model.ByteSize())\n    data = b\"\" + name_size + name_bytes + model_size + model_serialized\n\n    runtime_func = \"runtime.ONNXModuleCreate\"\n    fcreate = tvm._ffi.get_global_func(runtime_func)\n    return fcreate(data.hex(), name, const_vars)\n\n\n@tvm._ffi.register_func(\"relay.ext.onnx.save_to_file\")\ndef save_to_file(hex_str, path=None, fmt=\"onnx\"):\n    \"\"\"Store the ONNX subgraphs in the path folder\n\n    :param hex_str: Subgrah names and corresponding serialized onnx hex string\n    :param path: path to which ONNX files to be stored\n                It is assumed that path exists\n    :param fmt: extension of the files to be stored\n    \"\"\"\n    onnx_ir = bytes.fromhex(hex_str)\n\n    offset = 0\n    while offset < len(onnx_ir):\n        stop = offset + 4\n        (name_size,) = struct.unpack(\"I\", onnx_ir[offset:stop])\n        name = onnx_ir[stop : stop + name_size].decode(\"utf-8\")\n        stop = stop + name_size\n        (model_size,) = struct.unpack(\"I\", onnx_ir[stop : stop + 4])\n        stop = stop + 4\n        model_serialized = onnx_ir[stop : stop + model_size]\n        offset = stop + model_size\n\n        model_onnx = onnx.load_model_from_string(model_serialized)\n        onnx.save(model_onnx, \"{}{}{}.{}\".format(path, os.path.sep, name, fmt))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/target/vitis_ai.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, import-outside-toplevel\n\n\"\"\"Utility to offload (sub-)models to Vitis-AI\"\"\"\n\nimport warnings\nimport importlib\n\nfrom tvm.relay.expr import Tuple, Call, TupleGetItem\nimport tvm._ffi\n\n# Placeholder for PyXIR module\npyxir = None\n\n\ndef vitis_ai_available():\n    \"\"\"Return whether Vitis AI tools are available\"\"\"\n    pyxir_spec = importlib.util.find_spec(\"pyxir\")\n    if not tvm.get_global_func(\"tvm.vitis_ai_runtime.from_xgraph\", True) or pyxir_spec is None:\n        return False\n    return True\n\n\nclass CodegenVitisAI:\n\n    \"\"\"Traverse Relay expression and convert into PyXIR XGraph format\n\n    Parameters\n    ----------\n    function : Function\n        The Relay function\n    dpu_target : str\n        The Vitis AI DPU target identifier\n    \"\"\"\n\n    def __init__(self, function, dpu_target):\n        global pyxir\n        try:\n            if pyxir is None:\n                pyxir = __import__(\"pyxir\")\n                __import__(\"pyxir.frontend.tvm\")\n        except ImportError:\n            # add \"from None\" to silence\n            # \"During handling of the above exception, another exception occurred\"\n            raise ImportError(\n                \"The pyxir package is required for the Vitis AI backend. \"\n                \"Please install it first. \"\n                \"Help: (https://tvm.apache.org/docs/deploy/vitis_ai.html) \"\n            ) from None\n\n        self.function = function\n        self.dpu_target = dpu_target\n        self.params = {}\n\n    def build(self):\n        \"\"\" \"Convert the Relay expression to a PyXIR XGraph to instantiate\n        the Vitis AI runtime\n\n        Returns\n        -------\n        xgraph_str : str\n            Serialized XGraph\n        \"\"\"\n        xgraph = pyxir.frontend.tvm.from_relay(\n            self.function, params=self.params, postprocessing=None\n        )\n        xgraph = pyxir.partition(xgraph, targets=[self.dpu_target])\n        output_relay_ids = self.get_output_names()\n        layers = xgraph.get_layers()\n\n        # Get the output tensor names using XGraph and output Relay ids\n        out_tensor_names = [\"unknown_name\"] * len(output_relay_ids)\n        for layer in layers:\n            if not layer.internal:\n                for relay_id in layer.attrs[\"relay_id\"]:\n                    if relay_id in output_relay_ids:\n                        out_tensor_names[output_relay_ids.index(relay_id)] = layer.name\n                        break\n        if any([name == \"unkown_name\" for name in out_tensor_names]):\n            raise ValueError(\n                \"During codegeneration the loading of subexpression\"\n                \" failed due to output tensor name mismatch in Relay PyXIR interface.\"\n            )\n        xgraph.meta_attrs[\"tvm_out_tensors\"] = out_tensor_names\n        xgraph_str = pyxir.get_xgraph_str(xgraph)\n        return xgraph_str\n\n    def get_output_names(self):\n        \"\"\"Get output names from Relay expression\"\"\"\n        func = self.function\n        output_relay_ids = []\n        expr = func.body\n        if isinstance(expr, Tuple):\n            for field in expr.fields:\n                output_relay_ids.append(hash(field))\n        elif isinstance(expr, Call):\n            output_relay_ids.append(hash(expr))\n        elif isinstance(expr, TupleGetItem):\n            output_relay_ids.append(hash(expr.tuple_value))\n        else:\n            raise ValueError(\"Vitis-AI codegen does not support {} as output\".format(type(expr)))\n        return output_relay_ids\n\n\n@tvm._ffi.register_func(\"relay.ext.vitis_ai\")\ndef vitis_ai_compiler(ref):\n    \"\"\"Create a Vitis-AI runtime from the provided Relay expression\"\"\"\n    assert isinstance(ref, tvm.relay.function.Function)\n\n    name = str(ref.attrs.global_symbol)\n\n    pass_context = tvm.get_global_func(\"transform.GetCurrentPassContext\")()\n\n    cfg = (\n        pass_context.config[\"relay.ext.vitis_ai.options\"]\n        if \"relay.ext.vitis_ai.options\" in pass_context.config\n        else None\n    )\n\n    # Backward compatibility with old pass context configs\n    if cfg is None:\n        warnings.warn(\n            \"You are using a deprecated way of passing build configs (e.g.\"\n            \" `relay.ext.vitis_ai.options.target`). Check out the Vitis AI \"\n            \" documentation here: https://tvm.apache.org/docs/deploy/vitis_ai.html\"\n            \" to switch to recommended way for passing build configs.\"\n        )\n\n        # The target Vitis-AI accelerator device\n        dpu_target = (\n            str(pass_context.config[\"relay.ext.vitis_ai.options.target\"])\n            if \"relay.ext.vitis_ai.options.target\" in pass_context.config\n            else None\n        )\n\n        # (Optional configs) The build and work directories to be used by Vitis-AI\n        vai_build_dir = (\n            str(pass_context.config[\"relay.ext.vitis_ai.options.build_dir\"])\n            if \"relay.ext.vitis_ai.options.build_dir\" in pass_context.config\n            else tvm.contrib.utils.tempdir().relpath(\"\")\n        )\n        vai_work_dir = (\n            str(pass_context.config[\"relay.ext.vitis_ai.options.work_dir\"])\n            if \"relay.ext.vitis_ai.options.work_dir\" in pass_context.config\n            else tvm.contrib.utils.tempdir().relpath(\"\")\n        )\n\n        # (Optional configs) Export and load PyXIR runtime module to file if provided. This is\n        #   used to compile and quantize a model on the host and deploy it at the edge\n        export_runtime_module = (\n            str(pass_context.config[\"relay.ext.vitis_ai.options.export_runtime_module\"])\n            if \"relay.ext.vitis_ai.options.export_runtime_module\" in pass_context.config\n            else \"\"\n        )\n        load_runtime_module = (\n            str(pass_context.config[\"relay.ext.vitis_ai.options.load_runtime_module\"])\n            if \"relay.ext.vitis_ai.options.load_runtime_module\" in pass_context.config\n            else \"\"\n        )\n    else:\n        dpu_target = cfg.dpu if cfg.dpu else None\n        # (Optional configs) The build and work directories to be used by Vitis AI\n        vai_build_dir = cfg.build_dir if cfg.build_dir else tvm.contrib.utils.tempdir().relpath(\"\")\n\n        # (Optional configs) Export and load PyXIR runtime module to file if provided. This is\n        #   used to compile and quantize a model on the host and deploy it at the edge\n        vai_work_dir = cfg.work_dir if cfg.work_dir else tvm.contrib.utils.tempdir().relpath(\"\")\n        export_runtime_module = cfg.export_runtime_module\n        load_runtime_module = cfg.load_runtime_module\n\n    # Config checks\n    if load_runtime_module and dpu_target is not None:\n        warnings.warn(\n            \"Both `load_runtime_module` and `dpu` configs were specified.\"\n            \" The `load_runtime_module` points to a prebuilt runtime module with\"\n            \" an internal DPU target so the `dpu` config will be ignored\"\n        )\n    if load_runtime_module and \"relay.ext.vitis_ai.options.build_dir\" in pass_context.config:\n        warnings.warn(\n            \"Both `load_runtime_module` and `build_dir` configs were specified.\"\n            \" The `load_runtime_module` points to a prebuilt runtime module with\"\n            \" an internal build directory so the `build_dir` config will be ignored\"\n        )\n    if load_runtime_module and \"relay.ext.vitis_ai.options.work_dir\" in pass_context.config:\n        warnings.warn(\n            \"Both `load_runtime_module` and `work_dir` configs were specified.\"\n            \" The `load_runtime_module` points to a prebuilt runtime module with\"\n            \" an internal work directory so the `work_dir` config will be ignored\"\n        )\n\n    # If load_runtime_module is not set, we will build the PyXIR runtime module from scratch\n    if load_runtime_module == \"\":\n        # Convert Relay expression into XGraph and do partitioning inside PyXIR\n        codegen = CodegenVitisAI(ref, dpu_target)\n        xgraph_str = codegen.build()\n\n        runtime_func = \"tvm.vitis_ai_runtime.from_xgraph\"\n        fcreate = tvm._ffi.get_global_func(runtime_func)\n        return fcreate(\n            name, xgraph_str, dpu_target, vai_build_dir, vai_work_dir, export_runtime_module\n        )\n\n    runtime_func = \"tvm.vitis_ai_runtime.from_rt_mod\"\n    fcreate = tvm._ffi.get_global_func(runtime_func)\n    return fcreate(name, load_runtime_module, export_runtime_module)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/tedd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-outside-toplevel\n\"\"\"Tensor Expression Debug Display (TEDD), visualizing Tensor Expression\"\"\"\nimport html\nimport json\nimport warnings\nfrom graphviz import Digraph\nfrom graphviz import Source\nimport tvm\n\nTVMDD_TABLE_BODY_WIDTH = 30\n# Must match enum IterVarType defined in include/tvm/expr.h\nITERVAR_TYPE_STRING_MAP = {\n    0: (\"kDataPar\", \"#FFFFFF\"),\n    1: (\"kThreadIndex\", \"#2980B9\"),\n    2: (\"kCommReduce\", \"#FAD7A0\"),\n    3: (\"kOrdered\", \"#D35400\"),\n    4: (\"kOpaque\", \"#ABB2B9\"),\n    5: (\"kUnrolled\", \"#D2B4DE\"),\n    6: (\"kVectorized\", \"#AED6F1\"),\n    7: (\"kParallelized\", \"#F5B7B1\"),\n    8: (\"kTensorized\", \"#A9DFBF\"),\n}\n\nPALETTE = {\n    0: \"#000000\",\n    1: \"#922B21\",\n    2: \"#76448A\",\n    3: \"#1F618D\",\n    4: \"#148F77\",\n    5: \"#B7950B\",\n    6: \"#AF601A\",\n    7: \"#F5B7B1\",\n    8: \"#A9DFBF\",\n}\n\nPALETTE_SIZE = 9\n\n\ndef dom_path_to_string(dom_path, prefix=\"\"):\n    path_string = prefix\n    for index in dom_path:\n        path_string = path_string + \"_\" + str(index)\n    return path_string\n\n\ndef insert_dot_id(sch):\n    \"\"\"Insert unique ID for each node in the DOM tree.\n    They are used as Dot node ID.\n    \"\"\"\n    for stage_idx, stage in enumerate(sch[\"stages\"]):\n        dom_path = [stage_idx]\n        stage[\"id\"] = dom_path_to_string(dom_path, stage[\"type\"])\n        for itervar_idx, itervar in enumerate(stage[\"all_itervars\"]):\n            dom_path = [stage_idx, itervar_idx]\n            itervar[\"id\"] = dom_path_to_string(dom_path, itervar[\"type\"])\n        for rel_idx, rel in enumerate(stage[\"relations\"]):\n            dom_path = [stage_idx, rel_idx]\n            rel[\"id\"] = dom_path_to_string(dom_path, rel[\"type\"])\n        for tensor_idx, tensor in enumerate(stage[\"output_tensors\"]):\n            dom_path = [stage_idx, tensor_idx]\n            tensor[\"id\"] = dom_path_to_string(dom_path, tensor[\"type\"])\n    return sch\n\n\nclass ObjectManager:\n    \"\"\"A helper class tracking schedule objects, e.g. stage, IterVar,\n    relationship, and tensor, to their DOM path.\"\"\"\n\n    def __init__(self, sch):\n        self.dict = {}\n        for stage_idx, stage in enumerate(sch.stages):\n            self.dict[stage] = [stage_idx]\n            for itervar_idx, itervar in enumerate(stage.all_iter_vars):\n                self.dict[itervar] = [stage_idx, itervar_idx]\n            for rel_idx, rel in enumerate(stage.relations):\n                self.dict[rel] = [stage_idx, rel_idx]\n            for tensor_idx in range(stage.op.num_outputs):\n                self.dict[frozenset({stage.op.name, tensor_idx})] = [stage_idx, tensor_idx]\n\n    def get_dom_path(self, obj):\n        if obj is None:\n            return None\n        assert obj in self.dict, \"Node is no found.\"\n        return self.dict[obj]\n\n\ndef get_or_create_dot_id(obj, prefix=\"\", assert_on_missing=False):\n    \"\"\"If obj's ID has been registered, return it.\n    If not, either assert or create a unique and legal ID, register and\n    return it, according to assert_on_missing.\n    ID must be a unique and legal Dotty ID.\n\n     Parameters\n     ----------\n     obj : objet\n                 Serve as the key to the ID.\n\n     prefix : string\n                 Prefix to attach to the ID.  Usually use obj's non-unique\n                 name as prefix.\n\n     assert_on_missing : bool\n                 Assert or not if object doesn't have a registered ID.\n    \"\"\"\n    prefix = prefix.replace(\".\", \"_\")\n    if not hasattr(get_or_create_dot_id, \"obj_id_dict\"):\n        get_or_create_dot_id.obj_id_dict = {}\n    if obj not in get_or_create_dot_id.obj_id_dict:\n        if assert_on_missing:\n            assert False, \"dot_id \" + str(obj) + \" has not been registered.\"\n        else:\n            get_or_create_dot_id.obj_id_dict[obj] = prefix + hex(id(obj))\n    return get_or_create_dot_id.obj_id_dict[obj]\n\n\ndef get_port_id(is_input, index):\n    return \"I_\" + str(index) if is_input else \"O_\" + str(index)\n\n\ndef get_itervar_type_info(iter_type):\n    assert iter_type < len(ITERVAR_TYPE_STRING_MAP), \"Unknown IterVar type: \" + str(iter_type)\n    return ITERVAR_TYPE_STRING_MAP[iter_type]\n\n\ndef get_itervar_label_color(itervar, iv_type):\n    type_info = get_itervar_type_info(iv_type)\n    return (\n        linebrk(str(itervar[\"name\"]) + \"(\" + type_info[0] + \")\", TVMDD_TABLE_BODY_WIDTH),\n        type_info[1],\n    )\n\n\ndef linebrk(s, n):\n    \"\"\"Break input string s with <br/> for every n charactors.\"\"\"\n    result = \"\"\n    j = 0\n    for i, c in enumerate(s):\n        if j == n and i != len(s) - 1:\n            result = result + \"\\n\"\n            j = 0\n        j = j + 1\n        result = result + c\n    result = html.escape(str(result), quote=True)\n    result = result.replace(\"\\n\", \"<br/>\")\n    return result\n\n\ndef create_graph(name=\"\", rankdir=\"BT\"):\n    graph = Digraph(name=name)\n    graph.graph_attr[\"rankdir\"] = rankdir\n    return graph\n\n\ndef itervar_label(itervar, index, index_color, label):\n    return (\n        '<TR><TD PORT=\"'\n        + itervar[\"id\"]\n        + '\" BGCOLOR=\"'\n        + index_color\n        + '\">'\n        + str(index)\n        + '</TD><TD BGCOLOR=\"white\" PORT=\"itervar\">'\n        + label\n        + \"<br/>\"\n        + str(itervar[\"properties\"][\"range\"])\n        + \"</TD></TR>\"\n    )\n\n\ndef stage_label(stage):\n    return stage[\"name\"] + \"<br/>Scope: \" + stage[\"properties\"][\"scope\"]\n\n\ndef legend_label():\n    \"\"\"Generate legend labels.\"\"\"\n    label = '<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">'\n    for iter_type in ITERVAR_TYPE_STRING_MAP:\n        name, color = ITERVAR_TYPE_STRING_MAP[iter_type]\n        label += (\n            '<TR><TD BGCOLOR=\"' + color + '\"></TD>' + '<TD BGCOLOR=\"white\">' + name + \"</TD></TR>\"\n        )\n    label += \"</TABLE>>\"\n    return label\n\n\ndef leaf_itervars(stage):\n    filtered = filter(lambda x: (x[\"index\"] >= 0), stage[\"all_itervars\"])\n    return sorted(filtered, key=lambda x: x[\"index\"])\n\n\ndef legend_dot(g):\n    with g.subgraph(name=\"cluster_legend\") as subgraph:\n        subgraph.attr(label=\"Legend\")\n        label = legend_label()\n        subgraph.node(\"legend\", label, shape=\"none\", margin=\"0\")\n\n\ndef extract_dom_for_viz(sch, need_range=True):\n    json_str = dump_json(sch, need_range)\n    s = json.loads(json_str)\n    s = insert_dot_id(s)\n    return s\n\n\ndef dump_graph(dot_string, show_svg=True, dot_file_path=\"\", output_dot_string=False):\n    \"\"\"Output dot_string in various formats.\"\"\"\n    if dot_file_path:\n        try:\n            dot_file = open(dot_file_path, \"w+\")\n            dot_file.write(dot_string)\n            dot_file.close()\n        except IOError:\n            print(\"Cannot open file: \" + dot_file_path)\n    if show_svg:\n        from IPython.display import display\n        from IPython.display import SVG\n\n        src = Source(dot_string)\n        display(SVG(src.pipe(format=\"svg\")))\n    if output_dot_string:\n        return dot_string\n    return None\n\n\ndef dump_json(sch, need_range):\n    \"\"\"Serialize data for visualization from a schedule in JSON format.\n\n    Parameters\n    ----------\n    sch : schedule\n                The schedule object to serialize\n\n    Returns\n    -------\n    json : string\n        Serialized JSON string\n    \"\"\"\n\n    def encode_itervar(itervar, stage, index, range_map):\n        \"\"\"Extract and encode IterVar visualization data to a dictionary\"\"\"\n        ivrange = range_map[itervar] if range_map is not None and itervar in range_map else None\n        bind_thread = None\n        tensor_intrin = None\n        if itervar in stage.iter_var_attrs:\n            attr = stage.iter_var_attrs[itervar]\n            iv_type = attr.iter_type\n            # binding\n            bind_thread = str(attr.bind_thread.var) if attr.bind_thread is not None else None\n            # tensorization\n            if attr.tensor_intrin is not None:\n                tensor_intrin = str(attr.tensor_intrin.body)\n                # remove the final \\n\n                tensor_intrin = tensor_intrin[0:-1] if tensor_intrin[-1] == \"\\n\" else tensor_intrin\n            else:\n                tensor_intrin = None\n        else:\n            iv_type = itervar.iter_type\n        itervar_dict = {\n            \"type\": \"IterVar\",\n            \"index\": index,\n            \"name\": str(itervar.var),\n            \"itervar_type\": iv_type,\n            \"properties\": {\n                \"thread\": bind_thread,\n                \"intrin\": tensor_intrin,\n                \"range\": str(ivrange) if ivrange is not None else \"range(N/A)\",\n            },\n        }\n        return itervar_dict\n\n    def encode_itervars(stage, range_map):\n        \"\"\"Extract and encode IterVars visualization data from a stage to a dictionary\"\"\"\n\n        def get_leaf_itervar_index(itervar, leaf_iv):\n            for leaf_index, ivar in enumerate(leaf_iv):\n                if ivar == itervar:\n                    return leaf_index\n            return -1\n\n        itervars = []\n        for itervar in stage.all_iter_vars:\n            leaf_index = get_leaf_itervar_index(itervar, stage.leaf_iter_vars)\n            itervars.append(encode_itervar(itervar, stage, leaf_index, range_map))\n        return itervars\n\n    def encode_itervar_relation(obj_manager, rel):\n        \"\"\"Extract and encode IterVar Relationship visualization data to a dictionary\"\"\"\n        rel_type = type(rel)\n        if rel_type is tvm.te.schedule.Split:\n            node_type = \"Split_Relation\"\n            rel_dict = {\n                \"type\": node_type,\n                \"parent\": obj_manager.get_dom_path(rel.parent),\n                \"outer\": obj_manager.get_dom_path(rel.outer),\n                \"inner\": obj_manager.get_dom_path(rel.inner),\n            }\n        elif rel_type is tvm.te.schedule.Fuse:\n            node_type = \"Fuse_Relation\"\n            rel_dict = {\n                \"type\": node_type,\n                \"fused\": obj_manager.get_dom_path(rel.fused),\n                \"outer\": obj_manager.get_dom_path(rel.outer),\n                \"inner\": obj_manager.get_dom_path(rel.inner),\n            }\n        elif rel_type is tvm.te.schedule.Singleton:\n            node_type = \"Singleton_Relation\"\n            rel_dict = {\n                \"type\": node_type,\n                \"iter\": obj_manager.get_dom_path(rel.iter),\n            }\n        else:\n            return None\n        return rel_dict\n\n    def encode_itervar_relations(obj_manager, stage):\n        relations = []\n        for i in range(len(stage.relations)):\n            rel = encode_itervar_relation(obj_manager, stage.relations[i])\n            if rel is not None:\n                relations.append(rel)\n        return relations\n\n    def encode_tensor(obj_manager, tensor, stage):\n        \"\"\"Extract and encode tensor visualization data to a dictionary\"\"\"\n        tensor_dict = {\n            \"type\": \"Tensor\",\n            \"source\": obj_manager.get_dom_path(stage),\n            \"value_index\": tensor.value_index,\n            \"shape\": str(tensor.op.output(tensor.value_index).shape),\n            \"data_type\": tensor.op.output(tensor.value_index).dtype,\n        }\n        return tensor_dict\n\n    def encode_tensors(obj_manager, stage):\n        tensors = []\n        for i in range(stage.op.num_outputs):\n            tensor = stage.op.output(i)\n            tensors.append(encode_tensor(obj_manager, tensor, stage))\n        tensors.sort(key=lambda tensor: tensor[\"value_index\"])\n        return tensors\n\n    def encode_stage(obj_manager, stage, range_map):\n        \"\"\"Extract and encode stage visualization data to a dictionary\"\"\"\n        stage_dict = {\n            \"type\": \"Stage\",\n            \"name\": stage.op.name,\n            \"attaching_to\": obj_manager.get_dom_path(stage.attach_ivar),\n            \"compute\": str(stage.op.body) if hasattr(stage.op, \"body\") else None,\n            \"properties\": {\n                \"scope\": stage.scope,\n            },\n            \"all_itervars\": encode_itervars(stage, range_map),\n            \"relations\": encode_itervar_relations(obj_manager, stage),\n            \"input_tensors\": [\n                obj_manager.get_dom_path(frozenset({tensor.op.name, tensor.value_index}))\n                for tensor in stage.op.input_tensors\n            ],\n            \"output_tensors\": encode_tensors(obj_manager, stage),\n        }\n        return stage_dict\n\n    def encode_schedule(sch, need_range):\n        \"\"\"Extract and encode data from a schedule for visualization to a nested dictionary.\n        It is useful for JSON to serialize schedule.\n\n            Parameters\n            ----------\n            sch : schedule\n                        The schedule object to extract\n\n            Returns\n            -------\n            dict : dictionary\n                A nested dictionary\n        \"\"\"\n        assert isinstance(\n            sch, tvm.te.schedule.Schedule\n        ), \"Input is not a tvm.te.schedule.Schedule object.\"\n        range_map = None\n        if need_range:\n            try:\n                range_map = tvm.te.schedule.InferBound(sch)\n            except tvm._ffi.base.TVMError as expt:\n                warnings.warn(\n                    \"Ranges are not available, because InferBound fails with the following error:\\n\"\n                    + str(expt)\n                )\n\n        obj_manager = ObjectManager(sch)\n        stages = []\n        for stage in sch.stages:\n            stages.append(encode_stage(obj_manager, stage, range_map))\n        return {\n            \"type\": \"Schedule\",\n            \"stages\": stages,\n        }\n\n    return json.dumps(sch, default=lambda s: encode_schedule(s, need_range))\n\n\ndef viz_schedule_tree(sch, show_svg=False, dot_file_path=\"\", output_dot_string=False):\n    \"\"\"Top level API to render schedule tree\n\n    Parameters\n    ----------\n    sch : schedule\n                The schedule object to visualize\n\n    show_svg : bool\n                Display graph as SVG, useful for Jupyter notebooks.\n\n    dot_file_path : string\n                Dot file to save the graph.\n\n    output_dot_string : bool\n                Return dot file content or an empty string.\n\n    Returns\n    -------\n    dot_string : string\n        Dot file content or an empty string according to output_dot_string\n\n    Examples\n    --------\n    The following code writes a schedule tree to a dot file.\n\n    .. code-block:: python\n        tedd.viz_schedule_tree(s, dot_file_path = '/tmp/example.dot')\n\n    Use the following code to render a SVG graph in a Jupyter notebook.\n\n    .. code-block:: python\n        tedd.viz_schedule_tree(s, show_svg = True)\n    \"\"\"\n\n    def create_schedule_tree_graph(name=\"\"):\n        return create_graph(name=name, rankdir=\"BT\")\n\n    def root_dot(g):\n        g.node(\"ROOT\", \"ROOT\", shape=\"oval\", margin=\"0\")\n\n    def stage_node_dot(g, stage):\n        node_label = stage_node_label(stage)\n        g.node(stage[\"id\"], node_label, shape=\"none\", margin=\"0\")\n\n    def stage_node_label(stage):\n        \"\"\"Return a html format label for the given stage.\"\"\"\n        label = (\n            '<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" '\n            'CELLPADDING=\"4\"> <TR><TD BGCOLOR=\"lightgrey\" '\n            'COLSPAN=\"2\" PORT=\"stage\">' + stage_label(stage) + \"</TD></TR>\"\n        )\n\n        for leafiv in leaf_itervars(stage):\n            iv_type = leafiv[\"itervar_type\"]\n            var_attr_label = \"\"\n            if \"thread\" in leafiv[\"properties\"] and leafiv[\"properties\"][\"thread\"] is not None:\n                var_attr_label = (\n                    var_attr_label\n                    + '<br/><font color=\"#2980B9\">('\n                    + str(leafiv[\"properties\"][\"thread\"])\n                    + \")</font>\"\n                )\n            if \"intrin\" in leafiv[\"properties\"] and leafiv[\"properties\"][\"intrin\"] is not None:\n                var_attr_label = (\n                    var_attr_label\n                    + \"<br/>\"\n                    + linebrk(\n                        \"(tensor_intrin:\" + str(leafiv[\"properties\"][\"intrin\"]) + \")\",\n                        TVMDD_TABLE_BODY_WIDTH,\n                    )\n                )\n            var_label, color = get_itervar_label_color(leafiv, iv_type)\n            label += itervar_label(leafiv, leafiv[\"index\"], color, var_label + var_attr_label)\n        if stage[\"compute\"] is not None:\n            label += (\n                '<TR><TD COLSPAN=\"2\">'\n                + linebrk(str(stage[\"compute\"]), TVMDD_TABLE_BODY_WIDTH)\n                + \"</TD></TR>\"\n            )\n        label += \"</TABLE>>\"\n        return label\n\n    def compute_at_dot(g, stage):\n        \"\"\"If the given stage attaches to another stage, create an edge from it\n        stage to its attach point; otherwise, create an edge to the ROOT.\n        \"\"\"\n        src = stage[\"id\"]\n        dst = (\n            dom_path_to_string([stage[\"attaching_to\"][0]], \"Stage\")\n            + \":\"\n            + dom_path_to_string(stage[\"attaching_to\"], \"IterVar\")\n            if stage[\"attaching_to\"] is not None\n            else \"ROOT\"\n        )\n        color = (\n            PALETTE[stage[\"attaching_to\"][1] + 1]\n            if stage[\"attaching_to\"] is not None and stage[\"attaching_to\"][1] < PALETTE_SIZE - 1\n            else PALETTE[0]\n        )\n        g.edge(src, dst, color=color)\n\n    graph = create_schedule_tree_graph(\"Schedule Tree\")\n    s = extract_dom_for_viz(sch)\n    legend_dot(graph)\n    for stage in s[\"stages\"]:\n        stage_node_dot(graph, stage)\n    for stage in s[\"stages\"]:\n        compute_at_dot(graph, stage)\n    root_dot(graph)\n    return dump_graph(graph.source, show_svg, dot_file_path, output_dot_string)\n\n\ndef viz_itervar_relationship_graph(sch, show_svg=False, dot_file_path=\"\", output_dot_string=False):\n    \"\"\"Top level API to render IterVar relationship graph\n\n    Parameters\n    ----------\n    sch : schedule\n                The schedule object to visualize\n\n    show_svg : bool\n                Display graph as SVG, useful for Jupyter notebooks.\n\n    dot_file_path : string\n                Dot file to save the graph.\n\n    output_dot_string : bool\n                Return dot file content or an empty string.\n\n    Examples\n    --------\n    The following code writes Ian tervar relationship graph to a dot file.\n\n    .. code-block:: python\n        tedd.viz_def viz_itervar_relationship_graph(sch,\n            (s, dot_file_path = '/tmp/example.dot')\n\n    Use the following code to render a SVG graph in a Jupyter notebook.\n\n    .. code-block:: python\n        tedd.viz_def viz_itervar_relationship_graph(sch,\n            (s, show_svg = True)\n    \"\"\"\n\n    def create_itervar_relation_graph(name=\"\"):\n        return create_graph(name=name, rankdir=\"TB\")\n\n    def itervar_node_dot(g, itervar, iv_type, index):\n        label = itervar_node_label(itervar, iv_type, index)\n        g.node(itervar[\"id\"], label, shape=\"none\", margin=\"0\")\n\n    def itervar_node_label(itervar, iv_type, index):\n        label = (\n            '<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" '\n            'CELLPADDING=\"4\">'\n            + itervar_label(\n                itervar,\n                index,\n                get_itervar_label_color(itervar, iv_type)[1],\n                get_itervar_label_color(itervar, iv_type)[0],\n            )\n            + \"</TABLE>>\"\n        )\n        return label\n\n    def itervar_relation_node_dot(g, node_id, node_label, input_ports, output_ports):\n        label = itervar_relation_node_label(node_label, input_ports, output_ports)\n        g.node(node_id, label, shape=\"none\", margin=\"0\")\n\n    def itervar_relation_node_label(node_label, input_ports, output_ports):\n        \"\"\"Return a html format label for an itervar relationship node\n        including node_label and input/output ports.\n        \"\"\"\n        label = '<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" ' 'CELLPADDING=\"4\">' + \"<TR>\"\n        max_port_num = max(len(input_ports), len(output_ports))\n        for i in range(max_port_num):\n            if i < len(input_ports):\n                input_port = input_ports[i]\n                label += '<TD BGCOLOR=\"lightgrey\" PORT=\"' + input_port + '\">' + input_port + \"</TD>\"\n            else:\n                label += '<TD BGCOLOR=\"white\"></TD>'\n        label += \"</TR>\"\n        label += (\n            '<TR><TD BGCOLOR=\"white\" COLSPAN=\"'\n            + str(max_port_num)\n            + '\" PORT=\"relation\">'\n            + node_label\n            + \"</TD></TR>\"\n        )\n        label += \"<TR>\"\n        for i in range(max_port_num):\n            if i < len(output_ports):\n                output_port = output_ports[i]\n                label += (\n                    '<TD BGCOLOR=\"lightgrey\" PORT=\"' + output_port + '\">' + output_port + \"</TD>\"\n                )\n            else:\n                label += '<TD BGCOLOR=\"white\"></TD>'\n        label += \"</TR>\"\n        label += \"</TABLE>>\"\n        return label\n\n    def itervar_relation_dot(g, node, node_id):\n        \"\"\"Create an itervar relationship node.\"\"\"\n        node_type = node[\"type\"]\n        if node_type == \"Split_Relation\":\n            node_type = \"Split\"\n            itervar_relation_node_dot(g, node_id, node_type, [\"Input\"], [\"Outer\", \"Inner\"])\n            parent = dom_path_to_string(node[\"parent\"], \"IterVar\")\n            outer = dom_path_to_string(node[\"outer\"], \"IterVar\")\n            inner = dom_path_to_string(node[\"inner\"], \"IterVar\")\n            g.edge(parent + \":itervar\", node_id + \":Input\")\n            g.edge(node_id + \":Outer\", outer + \":itervar\")\n            g.edge(node_id + \":Inner\", inner + \":itervar\")\n        elif node_type == \"Fuse_Relation\":\n            node_type = \"Fuse\"\n            itervar_relation_node_dot(g, node_id, node_type, [\"Outer\", \"Inner\"], [\"Fused\"])\n            fused = dom_path_to_string(node[\"fused\"], \"IterVar\")\n            outer = dom_path_to_string(node[\"outer\"], \"IterVar\")\n            inner = dom_path_to_string(node[\"inner\"], \"IterVar\")\n            g.edge(outer + \":itervar\", node_id + \":Outer\")\n            g.edge(inner + \":itervar\", node_id + \":Inner\")\n            g.edge(node_id + \":Fused\", fused + \":itervar\")\n        elif node_type == \"Singleton_Relation\":\n            node_type = \"Singleton\"\n            itervar_relation_node_dot(g, node_id, node_type, [], [\"Iter\"])\n            itervar = dom_path_to_string(node[\"inner\"], \"IterVar\")\n            g.edge(node_id + \":Iter\", itervar + \":itervar\")\n        else:\n            assert False, \"Unknown IterVarRelationNode: \" + node_type\n\n    def stage_node_dot(g, stage):\n        \"\"\"Create a stage node.\"\"\"\n        with g.subgraph(name=\"cluster_\" + stage[\"id\"]) as subgraph:\n            subgraph.attr(label=stage[\"name\"])\n            if stage[\"all_itervars\"]:\n                for itervar in stage[\"all_itervars\"]:\n                    iv_type = itervar[\"itervar_type\"]\n                    itervar_node_dot(subgraph, itervar, iv_type, itervar[\"index\"])\n                for rel in stage[\"relations\"]:\n                    node_id = rel[\"id\"]\n                    itervar_relation_dot(subgraph, rel, node_id)\n            else:\n                subgraph.node(stage[\"name\"] + \"_placeholder\", style=\"invis\")\n\n    graph = create_itervar_relation_graph(\"IterVar Relationship Graph\")\n    s = extract_dom_for_viz(sch)\n    legend_dot(graph)\n    for stage in s[\"stages\"]:\n        stage_node_dot(graph, stage)\n\n    return dump_graph(graph.source, show_svg, dot_file_path, output_dot_string)\n\n\ndef viz_dataflow_graph(sch, show_svg=False, dot_file_path=\"\", output_dot_string=False):\n    \"\"\"Top level API to render dataflow graph\n\n    Parameters\n    ----------\n    sch : schedule\n                The schedule object to visualize\n\n    show_svg : bool\n                Display graph as SVG, useful for Jupyter notebooks.\n\n    dot_file_path : string\n                Dot file to save the graph.\n\n    output_dot_string : bool\n                Return dot file content or an empty string.\n\n    Examples\n    --------\n    The following code writes a dataflow graph to a dot file.\n\n    .. code-block:: python\n        tedd.viz_dataflow_graph(s, dot_file_path = '/tmp/example.dot')\n\n    Use the following code to render a SVG graph in a Jupyter notebook.\n\n    .. code-block:: python\n        tedd.viz_dataflow_graph(s, show_svg = True)\"\"\"\n\n    def create_dataflow_graph(name=\"\"):\n        return create_graph(name=name, rankdir=\"LR\")\n\n    def tensor_node_dot(g, tensor):\n        \"\"\"Create a tensor node.\"\"\"\n        label = tensor_node_label(tensor)\n        g.node(tensor[\"id\"], label, shape=\"oval\", margin=\"0\")\n\n    def tensor_node_label(tensor):\n        \"\"\"Return a html format label for the given tensor.\"\"\"\n        label = str(tensor[\"shape\"]) + \"\\n\" + str(tensor[\"data_type\"])\n        return label\n\n    def stage_node_dot(g, stage):\n        \"\"\"Create a stage node.\"\"\"\n        label = stage_node_label(stage)\n        g.node(stage[\"id\"], label, shape=\"none\", margin=\"0\")\n\n    def stage_node_label(stage):\n        \"\"\"Return a html format label for the given stage.\"\"\"\n        rows = max(1, max(len(stage[\"output_tensors\"]), len(stage[\"input_tensors\"])))\n        label = '<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" ' 'CELLPADDING=\"4\">'\n        for i in range(rows):\n            label += \"<TR>\"\n            if i < len(stage[\"input_tensors\"]):\n                port_id = get_port_id(True, i)\n                label += (\n                    '<TD BGCOLOR=\"lightgrey\" COLSPAN=\"2\" PORT=\"' + port_id + '\">' + str(i) + \"</TD>\"\n                )\n            else:\n                label += '<TD BGCOLOR=\"white\" COLSPAN=\"2\"></TD>'\n            if i == 0:\n                label += (\n                    '<TD BGCOLOR=\"white\" COLSPAN=\"2\" ROWSPAN=\"'\n                    + str(rows)\n                    + '\">'\n                    + stage_label(stage)\n                    + \"</TD>\"\n                )\n            if i < len(stage[\"output_tensors\"]):\n                port_id = get_port_id(False, i)\n                label += (\n                    '<TD BGCOLOR=\"lightgrey\" COLSPAN=\"2\" PORT=\"' + port_id + '\">' + str(i) + \"</TD>\"\n                )\n            else:\n                label += '<TD BGCOLOR=\"white\" COLSPAN=\"2\"></TD>'\n            label += \"</TR>\"\n        label += \"</TABLE>>\"\n        return label\n\n    def dfg_dot(g, sch):\n        \"\"\"Create edges among stages.\"\"\"\n        stages = sch[\"stages\"]\n        for stage in stages:\n            for i in range(len(stage[\"input_tensors\"])):\n                src = dom_path_to_string(stage[\"input_tensors\"][i], \"Tensor\")\n                dst = stage[\"id\"] + \":\" + get_port_id(True, i)\n                g.edge(src, dst)\n            for i in range(len(stage[\"output_tensors\"])):\n                src = stage[\"id\"] + \":\" + get_port_id(False, i)\n                dst = stage[\"output_tensors\"][i][\"id\"]\n                g.edge(src, dst)\n\n    graph = create_dataflow_graph(\"Dataflow Graph\")\n    s = extract_dom_for_viz(sch, need_range=False)\n    for stage in s[\"stages\"]:\n        stage_node_dot(graph, stage)\n        for tensor in stage[\"output_tensors\"]:\n            tensor_node_dot(graph, tensor)\n\n    dfg_dot(graph, s)\n\n    return dump_graph(graph.source, show_svg, dot_file_path, output_dot_string)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/tf_op/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Module container of TensorFlow TVMDSO op\"\"\"\nfrom . import module\n\nOpModule = module.OpModule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/tf_op/module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Module container of TensorFlow TVMDSO op\"\"\"\nimport tensorflow as tf\nfrom tensorflow.python.framework import load_library\nfrom tensorflow.python import platform\n\n\nclass OpModule:\n    \"\"\"Module container of TensorFlow TVMDSO op which wraps exported\n    TVM op implementation library to be called on TensorFlow side\"\"\"\n\n    def __init__(self, lib_path):\n        self.lib_path = lib_path\n\n    def func(self, name, output_dtype=None, output_shape=None):\n        \"\"\"Get tvm op function wrapped as TensorFlow tensor to tensor function\n\n        Parameters\n        ----------\n        name: str\n            function name\n        output_dtype: str or TensorFlow datatype\n            Output datatype, default is float32\n        output_shape: List of integer/tf scalar tensor or tf shape tensor\n            Output shape, default the same with first input's shape\n\n        Returns\n        ----------\n        Func object that acts as TensorFlow tensor to tensor function.\n        \"\"\"\n        return TensorFunc(self.lib_path, name, output_dtype, output_shape)\n\n    def __getitem__(self, func_name):\n        return self.func(func_name)\n\n\nclass TensorFunc:\n    \"\"\"Function object that acts as TensorFlow tensor to tensor function.\"\"\"\n\n    def __init__(self, lib_path, func_name, output_dtype, output_shape):\n        self.lib_path = lib_path\n        self.func_name = func_name\n        self.output_dtype = output_dtype\n\n        # const(0) indicate invalid dynamic shape\n        self.dynamic_output_shape = tf.constant(0, tf.int64)\n        self.static_output_shape = None\n        self.has_static_output_shape = False  # extra flag is required\n\n        if self._is_static_shape(output_shape):\n            self.static_output_shape = output_shape\n            self.has_static_output_shape = True\n        elif output_shape is not None:\n            self.dynamic_output_shape = self._pack_shape_tensor(output_shape)\n\n        self.module = self._load_platform_specific_library(\"libtvm_dso_op\")\n        self.tvm_dso_op = self.module.tvm_dso_op\n\n    def apply(self, *params):\n        return self.tvm_dso_op(\n            params,\n            dynamic_output_shape=self.dynamic_output_shape,\n            static_output_shape=self.static_output_shape,\n            has_static_output_shape=self.has_static_output_shape,\n            lib_path=self.lib_path,\n            func_name=self.func_name,\n            output_dtype=self.output_dtype,\n        )\n\n    def __call__(self, *params):\n        return self.apply(*params)\n\n    def _load_platform_specific_library(self, lib_name):\n        system = platform.system()\n        if system == \"Darwin\":\n            lib_file_name = lib_name + \".dylib\"\n        elif system == \"Windows\":\n            lib_file_name = lib_name + \".dll\"\n        else:\n            lib_file_name = lib_name + \".so\"\n        return load_library.load_op_library(lib_file_name)\n\n    def _is_static_shape(self, shape):\n        if shape is None or not isinstance(shape, list):\n            return False\n        for dim_value in shape:\n            if not isinstance(dim_value, int):\n                return False\n            if dim_value < 0:\n                raise Exception(\"Negative dimension is illegal: %d\" % dim_value)\n        return True\n\n    def _pack_shape_tensor(self, shape):\n        if isinstance(shape, tf.Tensor):\n            if shape.dtype == tf.int32:\n                shape = tf.cast(shape, tf.int64)\n        elif isinstance(shape, list):\n            shape_dims = []\n            for dim_value in shape:\n                if isinstance(dim_value, int):\n                    shape_dims.append(tf.constant(dim_value, tf.int64))\n                elif isinstance(dim_value, tf.Tensor) and dim_value.shape.rank == 0:\n                    if dim_value.dtype == tf.int32:\n                        dim_value = tf.cast(dim_value, tf.int64)\n                    shape_dims.append(dim_value)\n                else:\n                    raise TypeError(\"Input shape dimension is neither scalar tensor nor int\")\n            shape = tf.stack(shape_dims)\n        else:\n            raise TypeError(\"Input shape is neither tensor nor list\")\n        return shape\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/tflite_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TFLite runtime that load and run tflite models.\"\"\"\nimport tvm._ffi\nfrom ..rpc import base as rpc_base\n\n\ndef create(tflite_model_bytes, device, runtime_target=\"cpu\"):\n    \"\"\"Create a runtime executor module given a tflite model and device.\n    Parameters\n    ----------\n    tflite_model_byte : bytes\n        The tflite model to be deployed in bytes string format.\n    device : Device\n        The device to deploy the module. It can be local or remote when there\n        is only one Device.\n    runtime_target: str\n        Execution target of TFLite runtime: either `cpu` or `edge_tpu`.\n    Returns\n    -------\n    tflite_runtime : TFLiteModule\n        Runtime tflite module that can be used to execute the tflite model.\n    \"\"\"\n    device_type = device.device_type\n\n    if runtime_target == \"edge_tpu\":\n        runtime_func = \"tvm.edgetpu_runtime.create\"\n    else:\n        runtime_func = \"tvm.tflite_runtime.create\"\n\n    if device_type >= rpc_base.RPC_SESS_MASK:\n        fcreate = device._rpc_sess.get_function(runtime_func)\n    else:\n        fcreate = tvm._ffi.get_global_func(runtime_func)\n\n    return TFLiteModule(fcreate(bytearray(tflite_model_bytes), device))\n\n\nclass TFLiteModule(object):\n    \"\"\"Wrapper runtime module.\n\n    This is a thin wrapper of the underlying TVM module.\n    you can also directly call set_input, run, and get_output\n    of underlying module functions\n\n    Parameters\n    ----------\n    module : Module\n        The internal tvm module that holds the actual tflite functions.\n\n    Attributes\n    ----------\n    module : Module\n        The internal tvm module that holds the actual tflite functions.\n    \"\"\"\n\n    def __init__(self, module):\n        self.module = module\n        self._set_input = module[\"set_input\"]\n        self._invoke = module[\"invoke\"]\n        self._get_output = module[\"get_output\"]\n        self._set_num_threads = module[\"set_num_threads\"]\n\n    def set_input(self, index, value):\n        \"\"\"Set inputs to the module via kwargs\n\n        Parameters\n        ----------\n        key : int or str\n           The input key\n\n        value : the input value.\n           The input key\n\n        params : dict of str to NDArray\n           Additonal arguments\n        \"\"\"\n        self._set_input(index, value)\n\n    def invoke(self):\n        \"\"\"Invoke forward execution of the model\n\n        Parameters\n        ----------\n        input_dict: dict of str to NDArray\n            List of input values to be feed to\n        \"\"\"\n        self._invoke()\n\n    def get_output(self, index):\n        \"\"\"Get index-th output to out\n\n        Parameters\n        ----------\n        index : int\n            The output index\n        \"\"\"\n        return self._get_output(index)\n\n    def set_num_threads(self, num_threads):\n        \"\"\"Set the number of threads via kwargs\n        Parameters\n        ----------\n        num_threads : int\n           The number of threads\n        \"\"\"\n        self._set_num_threads(num_threads)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/thrust.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for thrust\"\"\"\nimport logging\n\nfrom tvm._ffi import get_global_func\n\n\ndef maybe_warn(target, func_name):\n    if get_global_func(func_name, allow_missing=True) and not \"thrust\" in target.libs:\n        logging.warning(\"TVM is built with thrust but thrust is not used.\")\n    if \"thrust\" in target.libs and get_global_func(func_name, allow_missing=True) is None:\n        logging.warning(\"thrust is requested but TVM is not built with thrust.\")\n\n\ndef can_use_thrust(target, func_name):\n    maybe_warn(target, func_name)\n    return (\n        target.kind.name in [\"cuda\", \"nvptx\"]\n        and \"thrust\" in target.libs\n        and get_global_func(func_name, allow_missing=True)\n    )\n\n\ndef can_use_rocthrust(target, func_name):\n    maybe_warn(target, func_name)\n    return (\n        target.kind.name == \"rocm\"\n        and \"thrust\" in target.libs\n        and get_global_func(func_name, allow_missing=True)\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/torch/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position,redefined-builtin,invalid-name\n\"\"\"Module container of Pytorch custom class\"\"\"\nimport os\nimport platform\nimport warnings\nimport torch\nfrom tvm._ffi import libinfo\n\n\ndef _load_platform_specific_library(lib_name):\n    system = platform.system()\n    if system == \"Darwin\":\n        lib_file_name = lib_name + \".dylib\"\n    elif system == \"Windows\":\n        lib_file_name = lib_name + \".dll\"\n    else:\n        lib_file_name = lib_name + \".so\"\n    lib_path = libinfo.find_lib_path()[0]\n    lib_dir = os.path.dirname(lib_path)\n    lib_file_path = os.path.join(lib_dir, lib_file_name)\n    try:\n        torch.classes.load_library(lib_file_path)\n    except OSError as err:\n        errmsg = str(err)\n        if errmsg.find(\"undefined symbol\") != -1:\n            reason = \" \".join(\n                (\n                    \"Got undefined symbol error,\",\n                    \"which might be due to the CXXABI incompatibility.\",\n                )\n            )\n        else:\n            reason = errmsg\n        warnings.warn(\n            f\"The library {lib_name} is not built successfully. {reason}\",\n            RuntimeWarning,\n        )\n\n\n_load_platform_specific_library(\"libpt_tvmdsoop\")\n_load_platform_specific_library(\"libpt_tvmdsoop_new\")\n\nfrom . import module\n\nGraphModule = module.GraphModule\nVMModule = module.VMModule\nTraceTvmModule = module.TraceTvmModule\n\nfrom . import pytorch_tvm\n\nPyTorchTVMModule = pytorch_tvm.PyTorchTVMModule\ncompile = pytorch_tvm.compile\n\nfrom . import as_torch\n\nTVMScriptIRModule = as_torch.OperatorModuleWrapper\nas_torch = as_torch.as_torch\n\nfrom . import optimize_torch\n\nGraphExecutorFactoryWrapper = optimize_torch.GraphExecutorFactoryWrapper\noptimize_torch = optimize_torch.optimize_torch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/torch/as_torch.py",
        "content": "# pylint: disable=inconsistent-return-statements\n#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring\n# pylint: disable=missing-class-docstring\n# pylint: disable=missing-function-docstring\n\"\"\"\nas_torch: a decorator, which is used to wrap the TVMScript code to `torch.nn.module`.\n\"\"\"\nimport tempfile\nfrom typing import Callable, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nimport torch\nimport torch.utils.dlpack\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.target.target import Target\nfrom tvm.tir import PrimFunc\n\n\n# python wrapper for OperatorModule\nclass OperatorModuleWrapper(torch.nn.Module):\n    def __init__(\n        self,\n        module: Union[\n            tvm.ir.module.IRModule,\n            tvm.tir.function.PrimFunc,\n        ],\n    ):\n        super().__init__()\n        self.rt_module = None  # runtime module\n        self.ir_module = module  # IR modules\n\n    def tune(\n        self,\n        target: Union[str, Target] = \"cpu\",\n        max_trials_global: int = 32,\n        *,\n        num_trials_per_iter: int = 32,\n        builder: ms.Builder.BuilderType = \"local\",\n        runner: ms.Runner.RunnerType = \"local\",\n        database: ms.Database.DatabaseType = \"json\",\n        cost_model: ms.CostModel.CostModelType = \"xgb\",\n        measure_callbacks: ms.MeasureCallback.CallbackListType = \"default\",\n        task_scheduler: ms.TaskScheduler.TaskSchedulerType = \"round-robin\",\n        space: ms.SpaceGenerator.SpaceGeneratorType = \"post-order-apply\",\n        strategy: ms.SearchStrategy.SearchStrategyType = \"replay-trace\",\n        task_name: str = \"main\",\n        num_threads: Union[Literal[\"physical\", \"logical\"], int] = \"physical\",\n        seed: Optional[int] = None,\n    ) -> None:\n        \"\"\"\n        Tune the TVMScript code.\n\n        Parameters\n        ----------\n        config: Optional[TuneConfig]\n            The tuning configuration.\n\n        target : Optional[str, Target]\n            The target to tune for.\n        \"\"\"\n        if target == \"cpu\":\n            target = f\"llvm --num-cores {ms.utils.cpu_count(logical=False)}\"\n\n        with tempfile.TemporaryDirectory() as work_dir:\n            database = ms.tir_integration.tune_tir(\n                mod=self.ir_module,\n                target=target,\n                work_dir=work_dir,\n                max_trials_global=max_trials_global,\n                num_trials_per_iter=num_trials_per_iter,\n                builder=builder,\n                runner=runner,\n                database=database,\n                cost_model=cost_model,\n                measure_callbacks=measure_callbacks,\n                task_scheduler=task_scheduler,\n                space=space,\n                strategy=strategy,\n                task_name=task_name,\n                num_threads=num_threads,\n                seed=seed,\n            )\n            sch = ms.tir_integration.compile_tir(database, self.ir_module, target)\n            self.ir_module = sch.mod\n            self.build(target)\n\n    def script(self):\n        return self.ir_module.script()\n\n    def build(self, target=None):\n        runtime_module = tvm.build(self.ir_module, target=target)\n        func = tvm.get_global_func(\"tvmtorch.save_runtime_mod\", allow_missing=True)\n\n        if func is None:\n            raise ValueError('as_torch requires the flag /\"USE_PT_TVMDSOOP/\" set in config.cmake')\n        func(runtime_module)\n\n        self.rt_module = torch.classes.tvm_torch.OperatorModuleWrapper()\n\n    def forward(self, *torch_inputs: List[torch.Tensor]) -> List[torch.Tensor]:\n        if self.rt_module is None:\n            if torch_inputs[0].is_cuda:\n                self.build(target=\"cuda\")\n            elif torch_inputs[0].device.type == \"cpu\":\n                self.build()\n            else:\n                raise Exception(f\"the target {torch_inputs[0].device.type} is not supported yet\")\n\n        return self.rt_module.forward(torch_inputs)\n\n\ndef as_torch(func: Union[tvm.ir.module.IRModule, tvm.tir.function.PrimFunc, Callable]):\n    \"\"\"A decorator of converting TensorIR to PyTorch nn.Module.\n\n    Parameters\n    ----------\n    func: Optional[tvm.ir.module.IRModule, tvm.tir.function.PrimFunc, Callable]\n        The function written by TVMScript.\n\n    Returns\n    -------\n    mod : Union[OperatorModuleWrapper, Callable]\n        It will return an object, or a templated function of OperatorModuleWrapper,\n        which is the subclass of the original nn.Module.\n\n    \"\"\"\n    if isinstance(func, (tvm.ir.module.IRModule, PrimFunc)):\n        return OperatorModuleWrapper(func)\n    if callable(func):\n\n        def func_get_param(*args, **kwargs):\n            return OperatorModuleWrapper(func(*args, **kwargs))\n\n        return func_get_param\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/torch/module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Module container of PyTorch custom class\"\"\"\nimport warnings\nfrom typing import List\n\nimport torch\n\n\nclass GraphModule(torch.nn.Module):\n    r\"\"\"Module container of Pytorch class which wraps exported\n    TVM op implementation library to be called on Pytorch side\"\"\"\n\n    @classmethod\n    def shape_repr(cls, input_shapes):\n        return torch.ops.tvm_dsoop.tvm_shape_repr(input_shapes)\n\n    def __init__(self, num_inputs, num_outputs, device=None):\n        warnings.warn(\n            \"This module will be removed at TVM version 0.11\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        super().__init__()\n        self.dummy_param = torch.nn.Parameter(torch.empty(0))\n        self.engine = None\n\n        if device is not None:\n            self.to(device)\n        self.engine = torch.classes.tvm_dsoop.TvmGraphModule(num_inputs, num_outputs, self.device)\n\n    def init(self, input_shapes, lib_path, graph_path, params_path):\n        r\"\"\"Load tvm module\"\"\"\n        self.engine.load_tvm_module(input_shapes, lib_path, graph_path, params_path)\n\n    def forward(self, inputs: List[torch.Tensor]):\n        r\"\"\"Call tvm module to forward\"\"\"\n        return self.engine.forward(inputs)\n\n    @property\n    def device(self):\n        r\"\"\"Get the device string\"\"\"\n        return str(self.dummy_param.device)\n\n    def _apply(self, fn):\n        r\"\"\"Override to device function, manually move tvm module to desired device\"\"\"\n        super()._apply(fn)\n        if self.engine is not None:\n            self.engine.to(self.device)\n        return self\n\n\nclass VMModule(torch.nn.Module):\n    r\"\"\"Module container of Pytorch class which wraps exported\n    TVM op implementation library to be called on Pytorch side\"\"\"\n\n    @classmethod\n    def shape_repr(cls, input_shapes):\n        return torch.ops.tvm_dsoop.tvm_shape_repr(input_shapes)\n\n    def __init__(self, num_inputs, num_outputs, device=None):\n        warnings.warn(\n            \"This module will be removed at TVM version 0.11\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        super().__init__()\n        self.dummy_param = torch.nn.Parameter(torch.empty(0))\n        self.engine = None\n\n        if device is not None:\n            self.to(device)\n        self.engine = torch.classes.tvm_dsoop.TvmVMModule(num_inputs, num_outputs, self.device)\n\n    def init(self, input_shapes, lib_path, code_path):\n        r\"\"\"Load tvm module\"\"\"\n        self.engine.load_tvm_module(input_shapes, lib_path, code_path)\n\n    def forward(self, inputs: List[torch.Tensor]):\n        r\"\"\"Call tvm module to forward\"\"\"\n        return self.engine.forward(inputs)\n\n    @property\n    def device(self):\n        r\"\"\"Get the device string\"\"\"\n        return str(self.dummy_param.device)\n\n    def _apply(self, fn):\n        r\"\"\"Override to device function, manually move tvm module to desired device\"\"\"\n        super()._apply(fn)\n        if self.engine is not None:\n            self.engine.to(self.device)\n        return self\n\n\nclass TraceTvmModule(torch.nn.Module):\n    r\"\"\"Wrapper for trace GraphModule\n\n    GraphModule and VMModule only supports List[Tensor] inputs and cannot be traced.\n    This is a wrapper class for trace GraphModule or VMModule in order to support\n    arbitrary number of inputs\n\n    Example:\n        import tvm.contrib.torch\n        tvm_module = tvm.contrib.torch.GraphModule(1, 1, 'cuda:0')\n        tvm_module.init(input_shapes, lib_path, graph_path, params_path)\n\n        trace_wrapper = tvm.contrib.torch.TraceGraphModule(torch.jit.script(tvm_module))\n        traced = torch.jit.trace(trace_wrapper, example_inputs)\n    \"\"\"\n\n    def __init__(self, tvm_module):\n        warnings.warn(\n            \"This module will be removed at TVM version 0.11\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        super().__init__()\n        self.tvm_module = tvm_module\n\n    def forward(self, *inputs):\n        outputs = self.tvm_module(inputs)\n        return outputs[0] if len(outputs) == 1 else tuple(outputs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/torch/optimize_torch.py",
        "content": "# pylint: disable=inconsistent-return-statements\n#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring\n# pylint: disable=missing-class-docstring\n# pylint: disable=missing-function-docstring\n\"\"\"\noptimize_torch: a function similar to `torch.jit.trace`,\nwhich is used to optimize the `torch.nn.module` by TVM metaSchedule,\nand returns a custom TorchScript operator\n\"\"\"\nimport base64\nimport contextlib\nimport tempfile\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.dlpack\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm._ffi import get_global_func, register_func\nfrom tvm.target import Target\n\n\nclass GraphExecutorFactoryWrapper(torch.nn.Module):\n    def __init__(self, module: tvm.runtime.Module):\n        super().__init__()\n        self.inner_module = module\n\n    def forward(self, *torch_inputs: Tuple[torch.Tensor]):\n        ret = self.inner_module.forward(torch_inputs)\n        if len(ret) == 1:\n            return ret[0]\n        return ret\n\n\n@register_func(\"script_torch.save_to_base64\")\ndef save_to_base64(obj) -> bytes:\n    with tempfile.NamedTemporaryFile(suffix=\".so\") as tmpfile:\n        obj.export_library(tmpfile.name)\n        with open(tmpfile.name, \"rb\") as temp_file:\n            return base64.b64encode(temp_file.read())\n\n\ndef optimize_torch(\n    func,\n    example_inputs,\n    *,\n    max_trials_global: int,\n    work_dir=None,\n    target: Union[str, Target] = \"cpu\",\n    max_trials_per_task: Optional[int] = None,\n    num_trials_per_iter: int = 64,\n    builder: ms.Builder.BuilderType = \"local\",\n    runner: ms.Runner.RunnerType = \"local\",\n    database: ms.Database.DatabaseType = \"json\",\n    cost_model: ms.CostModel.CostModelType = \"xgb\",\n    measure_callbacks: ms.MeasureCallback.CallbackListType = \"default\",\n    task_scheduler: ms.TaskScheduler.TaskSchedulerType = \"gradient\",\n    space: ms.SpaceGenerator.SpaceGeneratorType = \"post-order-apply\",\n    strategy: ms.SearchStrategy.SearchStrategyType = \"evolutionary\",\n    seed: Optional[int] = None,\n):\n    \"\"\"Load PyTorch model that could be traced by TorchScript, then optimize it via MetaSchedule.\n\n    Parameters\n    ----------\n    func : callable or torch.nn.Module\n        A Python function or nn.Module that could run by TorchScript's trace.\n        (ie: torch.jit.trace(model, input))\n    example_inputs : tuple or torch.Tensor\n        Inputs to `torch.jit.trace`.\n    max_trials_global : int\n        The maximum number of trials to run globally.\n    work_dir : Optional[str]\n        The working directory to save intermediate results.\n    target : Optional[Union[str, Target]]\n        The target of the compilation.\n        If user doesn't set the target, the module will be built for the CPU target.\n    max_trials_per_task : Optional[int]\n        The maximum number of trials to run per task.\n    num_trials_per_iter : int\n        The number of trials to run per iteration\n    builder : Builder.BuilderType\n        The builder.\n    runner : Runner.RunnerType\n        The runner.\n    database : Database.DatabaseType\n        The database.\n    cost_model : CostModel.CostModelType\n        The cost model.\n    measure_callbacks : MeasureCallback.CallbackListType\n        The measure callbacks.\n    task_scheduler : TaskScheduler.TaskSchedulerType\n        The task scheduler.\n    space : SpaceGenerator.SpaceGeneratorType\n        The space generator to use.\n    strategy : SearchStrategy.SearchStrategyType\n        The search strategy to use.\n    seed : Optional[int]\n        The random seed to use.\n\n    Returns\n    -------\n    mod : GraphExecutorFactoryWrapper\n        It will return an object of GraphExecutorFactoryWrapper,\n        which is the subclass of the original nn.Module.\n    \"\"\"\n\n    if target == \"cpu\":\n        target = f\"llvm --num-cores {ms.utils.cpu_count(logical=False)}\"\n    if not isinstance(target, Target):\n        target = Target(target)\n\n    # If `func` is already a traced module this statement makes no effect\n    jit_mod = torch.jit.trace(func, example_inputs)\n    if isinstance(example_inputs, torch.Tensor):\n        example_inputs = [example_inputs]\n    shape_list = [(f\"inp_{idx}\", i.shape) for idx, i in enumerate(example_inputs)]\n    mod, params = relay.frontend.from_pytorch(jit_mod, shape_list)  # IRmodule\n\n    if work_dir:\n        context_manager = contextlib.nullcontext(work_dir)\n    else:\n        context_manager = tempfile.TemporaryDirectory()\n    with context_manager as work_dir:  # pylint: disable=redefined-argument-from-local\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            params=params,\n            target=target,\n            work_dir=work_dir,\n            max_trials_global=max_trials_global,\n            max_trials_per_task=max_trials_per_task,\n            num_trials_per_iter=num_trials_per_iter,\n            builder=builder,\n            runner=runner,\n            database=database,\n            cost_model=cost_model,\n            measure_callbacks=measure_callbacks,\n            task_scheduler=task_scheduler,\n            space=space,\n            strategy=strategy,\n            seed=seed,\n        )\n        executor_factory = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=target,\n            params=params,\n            backend=\"graph\",\n        )\n\n    save_runtime_mod = get_global_func(\"tvmtorch.save_runtime_mod\", allow_missing=True)\n    if save_runtime_mod is None:\n        raise ValueError('optimize_torch requires the flag /\"USE_PT_TVMDSOOP/\" set in config.cmake')\n    save_runtime_mod(executor_factory.module)\n\n    return GraphExecutorFactoryWrapper(torch.classes.tvm_torch.GraphExecutorFactoryWrapper())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/torch/pytorch_tvm.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin\n\"\"\"`compile` api that convert torch module to torch tvm module\"\"\"\nimport os\nimport warnings\nimport tvm\nimport tvm.testing\nfrom tvm import relay, autotvm\nfrom tvm.runtime import load_module\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.debugger import debug_executor\nfrom . import GraphModule\n\n\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n    \"\"\"Tune tasks and generate tuning log to file\"\"\"\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = f\"[Task {i + 1:2d}/{len(tasks):2d}] \"\n\n        # create tuner\n        if tuner in (\"xgb\", \"sgb-rank\"):\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=100)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    if not os.path.exists(log_filename):\n        with open(log_filename, \"w\", encoding=\"utf-8\"):\n            pass\n    if os.path.exists(tmp_log_file):\n        autotvm.record.pick_best(tmp_log_file, log_filename)\n        os.remove(tmp_log_file)\n\n\ndef get_tuning_opt(log_file=\"tuning.log\", n_trial=200):\n    \"\"\"Returns tuning options\"\"\"\n    tuning_opt = {\n        \"log_filename\": log_file,\n        \"tuner\": \"random\",\n        \"n_trial\": n_trial,\n        \"early_stopping\": 60,\n        \"measure_option\": autotvm.measure_option(\n            builder=autotvm.LocalBuilder(timeout=10),\n            runner=autotvm.LocalRunner(number=20, repeat=3, timeout=4, min_repeat_ms=150),\n        ),\n    }\n    return tuning_opt\n\n\nTVM_ASSETS = [\"mod.so\", \"graph.json\", \"params\"]\n\n\nclass PyTorchTVMModule:\n    \"\"\"Helper class for compiling pytorch module to tvm module\"\"\"\n\n    def __init__(self, target=\"cuda\", device=tvm.cuda(0)) -> None:\n        self.script_module = None\n        self.input_infos = None\n        self.default_dtype = \"float32\"\n        self.mod = None\n        self.params = None\n        self.tasks = None\n        self.target = target\n        self.dev = device\n        self.log_file = None\n        self.tvm_module = None\n        self.tvm_graph = None\n        self.tvm_lib = None\n        self.tvm_params = None\n\n    def from_pytorch(self, script_module, input_infos, default_dtype=\"float32\"):\n        self.script_module = script_module\n        self.input_infos = input_infos\n        self.default_dtype = default_dtype\n        self.mod, self.params = relay.frontend.from_pytorch(\n            script_module, input_infos, default_dtype=default_dtype\n        )\n\n    def tune_tvm(self, log_file=\"tuning.log\", n_trial=200):\n        self.tasks = autotvm.task.extract_from_program(\n            self.mod[\"main\"],\n            target=self.target,\n            params=self.params,\n        )\n        self.log_file = log_file\n        tuning_opt = get_tuning_opt(log_file, n_trial)\n        tune_tasks(self.tasks, **tuning_opt)\n\n    def build_tvm(self, export_dir, debug_runtime=False):\n        tvm_mod = self._build_tvm(debug_runtime)\n        self._export_tvm(export_dir)\n        return tvm_mod\n\n    def _build_tvm(self, debug_runtime=False):\n        # compile kernels with history best records\n        with autotvm.apply_history_best(self.log_file):\n            with tvm.transform.PassContext(opt_level=3):\n                self.tvm_graph, self.tvm_lib, self.tvm_params = relay.build(\n                    self.mod, target=self.target, params=self.params\n                )\n\n        if not debug_runtime:\n            self.tvm_module = graph_executor.create(self.tvm_graph, self.tvm_lib, device=self.dev)\n        else:\n            self.tvm_module = debug_executor.create(self.tvm_graph, self.tvm_lib, device=self.dev)\n        self.tvm_module.set_input(**self.tvm_params)\n        return self.tvm_module\n\n    def _export_tvm(self, export_dir):\n        if not os.path.isdir(export_dir):\n            os.makedirs(export_dir)\n        self.export_dir = export_dir\n        self.tvm_lib.export_library(os.path.join(export_dir, TVM_ASSETS[0]))\n        with open(os.path.join(export_dir, TVM_ASSETS[1]), \"w\", encoding=\"utf8\") as fout:\n            fout.write(self.tvm_graph)\n        with open(os.path.join(export_dir, TVM_ASSETS[2]), \"wb\") as fout:\n            fout.write(relay.save_param_dict(self.tvm_params))\n\n    def load_tvm(self, export_dir):\n        \"\"\"Load tvm module from export directory\"\"\"\n        self.export_dir = export_dir\n        self.tvm_lib = load_module(os.path.join(export_dir, TVM_ASSETS[0]))\n        with open(os.path.join(export_dir, TVM_ASSETS[1]), \"r\", encoding=\"utf8\") as f:\n            self.tvm_graph = f.read()\n        with open(os.path.join(export_dir, TVM_ASSETS[2]), \"rb\") as f:\n            self.tvm_params = relay.load_param_dict(f.read())\n\n        self.tvm_module = graph_executor.create(self.tvm_graph, self.tvm_lib, device=self.dev)\n        self.tvm_module.set_input(**self.tvm_params)\n        return self.tvm_module\n\n    def build_pytorch_module(self, num_inputs, num_outputs, input_infos=None):\n        \"\"\"Build pytorch module containing TVM Graph Module\"\"\"\n        warnings.warn(\n            \" \".join(\n                (\n                    \"This function will be removed at TVM version 0.11,\",\n                    \"we suggest users to use `optimized_torch` for tuning Torch modules instead.\",\n                )\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        assert self.export_dir, \"you must build_tvm or load_tvm before\"\n        input_infos = input_infos or self.input_infos\n        assert input_infos\n        assert len(input_infos) == num_inputs\n        assets = [os.path.join(self.export_dir, i) for i in TVM_ASSETS]\n        input_shapes = [i[1] for i in input_infos]\n\n        def _tvm_dev_to_pt_dev(device):\n            \"\"\"convert tvm device to pytorch device string\"\"\"\n            if tvm.runtime.Device.MASK2STR[device.device_type] == \"cpu\":\n                return \"cpu\"\n            if tvm.runtime.Device.MASK2STR[device.device_type] == \"cuda\":\n                return f\"cuda:{device.device_id}\"\n            raise ValueError(f\"unsupported device for pt graph module: {device}\")\n\n        mod = GraphModule(num_inputs=num_inputs, num_outputs=num_outputs).to(\n            _tvm_dev_to_pt_dev(self.dev)\n        )\n        mod.init(input_shapes, *assets)\n        return mod\n\n\ndef compile(script_module, option):\n    \"\"\"\n    example:\n    option = {\n        \"input_infos\": [\n            (\"x\", (1, 3, 244, 244)),\n        ],\n        \"default_dtype\": \"float16\",\n        \"export_dir\": \"pytorch_compiled\",\n        \"num_outputs\": 1,\n        \"tuning_n_trials\": 20,  # set zero to skip tuning\n        \"tuning_log_file\": \"tuning.log\",\n        \"target\": \"llvm\",\n        \"device\": tvm.cpu(),\n    }\n    script_module = torch.jit.script(model)\n    pytorch_tvm_module = compile(script_module, option)\n    pytorch_tvm_module(\"model_tvm.pt\")\n    \"\"\"\n    warnings.warn(\n        \" \".join(\n            (\n                \"This function will be removed at TVM version 0.11,\",\n                \"we suggest users to use `optimized_torch` for tuning Torch modules instead.\",\n            )\n        ),\n        DeprecationWarning,\n        stacklevel=2,\n    )\n    input_infos = option[\"input_infos\"]\n    default_dtype = option.get(\"default_dtype\", \"float32\")\n    export_dir = option.get(\"export_dir\", \"pytorch_compiled\")\n    tuning_log_file = option.get(\"tuning_log_file\", \"tuning.log\")\n    tuning_n_trials = option.get(\"tuning_n_trials\", 20)\n    num_outputs = option.get(\"num_outputs\", 1)\n    target = option.get(\"target\", \"cuda\")\n    device = option.get(\"device\", tvm.cuda(0))\n\n    mod = PyTorchTVMModule(target=target, device=device)\n    print(\"Converting...\")\n\n    mod.log_file = tuning_log_file\n    mod.from_pytorch(script_module, input_infos, default_dtype)\n\n    if tuning_n_trials > 0:\n        print(\"Tuning...\")\n        mod.tune_tvm(log_file=tuning_log_file, n_trial=tuning_n_trials)\n\n    print(\"Building...\")\n    mod.build_tvm(export_dir)\n    pytorch_mod = mod.build_pytorch_module(num_inputs=len(input_infos), num_outputs=num_outputs)\n    return pytorch_mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common system utilities\"\"\"\nimport atexit\nimport contextlib\nimport datetime\nimport os\nimport pathlib\nimport tempfile\nimport threading\nimport shutil\n\ntry:\n    import fcntl\nexcept ImportError:\n    fcntl = None\n\n\nclass DirectoryCreatedPastAtExit(Exception):\n    \"\"\"Raised when a TempDirectory is created after the atexit hook runs.\"\"\"\n\n\nclass TempDirectory(object):\n    \"\"\"Helper object to manage temp directory during testing.\n\n    Automatically removes the directory when it went out of scope.\n    \"\"\"\n\n    # When True, all TempDirectory are *NOT* deleted and instead live inside a predicable directory\n    # tree.\n    _KEEP_FOR_DEBUG = False\n\n    # In debug mode, each tempdir is named after the sequence\n    _NUM_TEMPDIR_CREATED = 0\n    _NUM_TEMPDIR_CREATED_LOCK = threading.Lock()\n\n    @classmethod\n    def _increment_num_tempdir_created(cls):\n        with cls._NUM_TEMPDIR_CREATED_LOCK:\n            to_return = cls._NUM_TEMPDIR_CREATED\n            cls._NUM_TEMPDIR_CREATED += 1\n\n        return to_return\n\n    _DEBUG_PARENT_DIR = None\n\n    @classmethod\n    def _get_debug_parent_dir(cls):\n        if cls._DEBUG_PARENT_DIR is None:\n            all_parents = f\"{tempfile.gettempdir()}/tvm-debug-mode-tempdirs\"\n            if not os.path.isdir(all_parents):\n                os.makedirs(all_parents)\n            cls._DEBUG_PARENT_DIR = tempfile.mkdtemp(\n                prefix=datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S___\"), dir=all_parents\n            )\n        return cls._DEBUG_PARENT_DIR\n\n    TEMPDIRS = set()\n\n    @classmethod\n    def remove_tempdirs(cls):\n        temp_dirs = getattr(cls, \"TEMPDIRS\", None)\n        if temp_dirs is None:\n            return\n\n        for path in temp_dirs:\n            shutil.rmtree(path, ignore_errors=True)\n\n        cls.TEMPDIRS = None\n\n    @classmethod\n    @contextlib.contextmanager\n    def set_keep_for_debug(cls, set_to=True):\n        \"\"\"Keep temporary directories past program exit for debugging.\"\"\"\n        old_keep_for_debug = cls._KEEP_FOR_DEBUG\n        try:\n            cls._KEEP_FOR_DEBUG = set_to\n            yield\n        finally:\n            cls._KEEP_FOR_DEBUG = old_keep_for_debug\n\n    def __init__(self, custom_path=None, keep_for_debug=None):\n        if self.TEMPDIRS is None:\n            raise DirectoryCreatedPastAtExit()\n\n        if keep_for_debug is not None:\n            self._created_with_keep_for_debug = keep_for_debug\n        else:\n            self._created_with_keep_for_debug = self._KEEP_FOR_DEBUG\n\n        if custom_path:\n            os.mkdir(custom_path)\n            self.temp_dir = custom_path\n        else:\n            if self._created_with_keep_for_debug:\n                parent_dir = self._get_debug_parent_dir()\n                self.temp_dir = f\"{parent_dir}/{self._increment_num_tempdir_created():05d}\"\n                os.mkdir(self.temp_dir)\n            else:\n                self.temp_dir = tempfile.mkdtemp()\n\n        if not self._created_with_keep_for_debug:\n            self.TEMPDIRS.add(self.temp_dir)\n\n    def remove(self):\n        \"\"\"Remove the tmp dir\"\"\"\n        if self.temp_dir:\n            if not self._created_with_keep_for_debug:\n                shutil.rmtree(self.temp_dir, ignore_errors=True)\n                self.TEMPDIRS.remove(self.temp_dir)\n            self.temp_dir = None\n\n    @property\n    def path(self):\n        return pathlib.Path(self.temp_dir)\n\n    def __truediv__(self, other):\n        if not isinstance(other, (str, pathlib.Path)):\n            raise TypeError(\n                \"TempDirectory / operator: must supply str or pathlib.Path; got %r\" % (other,)\n            )\n\n        return self.path / other\n\n    def __del__(self):\n        temp_dirs = getattr(self, \"TEMPDIRS\", None)\n        if temp_dirs is None:\n            # Do nothing if the atexit hook has already run.\n            return\n\n        self.remove()\n\n    def relpath(self, name):\n        \"\"\"Relative path in temp dir\n\n        Parameters\n        ----------\n        name : str\n            The name of the file.\n\n        Returns\n        -------\n        path : str\n            The concatenated path.\n        \"\"\"\n        return os.path.join(self.temp_dir, name)\n\n    def listdir(self):\n        \"\"\"List contents in the dir.\n\n        Returns\n        -------\n        names : list\n            The content of directory\n        \"\"\"\n        return os.listdir(self.temp_dir)\n\n\natexit.register(TempDirectory.remove_tempdirs)\n\n\ndef tempdir(custom_path=None, keep_for_debug=None):\n    \"\"\"Create temp dir which deletes the contents when exit.\n\n    Parameters\n    ----------\n    custom_path : str, optional\n        Manually specify the exact temp dir path\n\n    keep_for_debug : bool\n        Keep temp directory for debugging purposes\n    Returns\n    -------\n    temp : TempDirectory\n        The temp directory object\n    \"\"\"\n    return TempDirectory(custom_path=custom_path, keep_for_debug=keep_for_debug)\n\n\nclass FileLock(object):\n    \"\"\"File lock object\n\n    Parameters\n    ----------\n    path : str\n        The path to the lock\n    \"\"\"\n\n    def __init__(self, path):\n        self.lock_file = open(path, \"w\")\n        if fcntl:\n            fcntl.lockf(self.lock_file, fcntl.LOCK_EX)\n\n    def release(self):\n        \"\"\"Release the lock\"\"\"\n        if self.lock_file:\n            if fcntl:\n                fcntl.lockf(self.lock_file, fcntl.LOCK_UN)\n            self.lock_file.close()\n            self.lock_file = None\n\n\ndef filelock(path):\n    \"\"\"Create a file lock which locks on path\n\n    Parameters\n    ----------\n    path : str\n        The path to the lock\n\n    Returns\n    -------\n    lock : File lock object\n    \"\"\"\n    return FileLock(path)\n\n\ndef is_source_path(path):\n    \"\"\"Check if path is source code path.\n\n    Parameters\n    ----------\n    path : str\n        A possible path\n\n    Returns\n    -------\n    valid : bool\n        Whether path is a possible source path\n    \"\"\"\n    if os.path.exists(path):\n        return True\n    if path.find(\"\\n\") != -1:\n        return False\n    spath = path.rsplit(\".\", 1)\n    return len(spath) == 2 and spath[1].strip() == spath[1]\n\n\ndef which(exec_name):\n    \"\"\"Try to find full path of exec_name\n\n    Parameters\n    ----------\n    exec_name : str\n        The executable name\n\n    Returns\n    -------\n    path : str\n        The full path of executable if found, otherwise returns None\n    \"\"\"\n    base_list = [\"\", \"/bin\"] + os.environ.get(\"PATH\", \"\").split(os.pathsep)\n    for path in base_list:\n        full_path = os.path.join(path, exec_name)\n        if os.path.isfile(full_path) and os.access(full_path, os.X_OK):\n            return full_path\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/contrib/xcode.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Utility to invoke Xcode compiler toolchain\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport os\nimport sys\nimport subprocess\nimport json\nfrom .._ffi.base import py_str\nfrom . import utils\n\n\ndef xcrun(cmd):\n    \"\"\"Run xcrun and return the output.\n\n    Parameters\n    ----------\n    cmd : list of str\n        The command sequence.\n\n    Returns\n    -------\n    out : str\n        The output string.\n    \"\"\"\n    cmd = [\"xcrun\"] + cmd\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    return out.strip()\n\n\ndef __get_min_os_version(sdk):\n    if sdk == \"macosx\":\n        return None\n    if sdk in (\"iphoneos\", \"iphonesimulator\"):\n        return \"13.0\"\n    raise RuntimeError(\"Unsupported sdk: %s\" % sdk)\n\n\ndef __get_min_os_version_cmd(sdk, min_os_version):\n    if min_os_version is None:\n        min_os_version = __get_min_os_version(sdk)\n    if min_os_version is not None:\n        return \"-mios-version-min=\" + min_os_version\n    return \"\"\n\n\ndef create_dylib(output, objects, arch, sdk=\"macosx\", min_os_version=None):\n    \"\"\"Create dynamic library.\n\n    Parameters\n    ----------\n    output : str\n        The target shared library.\n\n    objects : list\n        List of object files.\n\n    options : str\n        The additional options.\n\n    arch : str\n        Target major architectures\n\n    sdk : str\n        The sdk to be used.\n    \"\"\"\n    clang = xcrun([\"-sdk\", sdk, \"-find\", \"clang\"])\n    sdk_path = xcrun([\"-sdk\", sdk, \"--show-sdk-path\"])\n    cmd = [clang]\n    cmd += [\"-dynamiclib\"]\n    cmd += [\"-arch\", arch]\n    cmd += [\"-isysroot\", sdk_path]\n    cmd += [__get_min_os_version_cmd(sdk, min_os_version)]\n    cmd += [\"-o\", output]\n    if isinstance(objects, str):\n        cmd += [objects]\n    else:\n        cmd += objects\n\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = \"Compilation error:\\n\"\n        msg += py_str(out)\n        raise RuntimeError(msg)\n\n\n# assign so as default output format\ncreate_dylib.output_format = \"dylib\"\n\n\ndef compile_metal(code, path_target=None, sdk=\"macosx\", min_os_version=None):\n    \"\"\"Compile metal with CLI tool from env.\n\n    Parameters\n    ----------\n    code : str\n        The cuda code.\n\n    path_target : str, optional\n        Output file.\n\n    sdk : str, optional\n        The target platform SDK.\n\n    Return\n    ------\n    metallib : bytearray\n        The bytearray of the metallib\n    \"\"\"\n    temp = utils.tempdir()\n    temp_code = temp.relpath(\"my_lib.metal\")\n    temp_ir = temp.relpath(\"my_lib.air\")\n    temp_target = temp.relpath(\"my_lib.metallib\")\n\n    with open(temp_code, \"w\") as out_file:\n        out_file.write(code)\n    file_target = path_target if path_target else temp_target\n\n    # See:\n    # - https://developer.apple.com/documentation/metal/gpu_functions_libraries/building_a_library_with_metal_s_command-line_tools#overview # pylint: disable=line-too-long\n    #\n    #   xcrun -sdk macosx metal -c MyLibrary.metal -o MyLibrary.air\n    #   xcrun -sdk macosx metallib MyLibrary.air -o MyLibrary.metallib\n    min_target = __get_min_os_version_cmd(sdk, min_os_version)\n    if sdk == \"macosx\":\n        language_version = \"-std=macos-metal2.3\"\n    elif sdk in (\"iphoneos\", \"iphonesimulator\"):\n        language_version = \"-std=ios-metal2.3\"\n    else:\n        raise RuntimeError(\"Unsupported sdk: %s\" % sdk)\n    cmd1 = [\"xcrun\", \"-sdk\", sdk, \"metal\", language_version, min_target, \"-O3\"]\n    cmd1 += [\"-c\", temp_code, \"-o\", temp_ir]\n    cmd2 = [\"xcrun\", \"-sdk\", sdk, \"metallib\"]\n    cmd2 += [temp_ir, \"-o\", file_target]\n    proc = subprocess.Popen(\n        \" \".join(cmd1) + \";\" + \" \".join(cmd2),\n        shell=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n    )\n    (out, _) = proc.communicate()\n    if proc.returncode != 0:\n        sys.stderr.write(\"Compilation error:\\n\")\n        sys.stderr.write(py_str(out))\n        sys.stderr.flush()\n        libbin = None\n    else:\n        libbin = bytearray(open(file_target, \"rb\").read())\n    return libbin\n\n\ndef compile_coreml(model, model_name=\"main\", out_dir=\".\"):\n    \"\"\"Compile coreml model and return the compiled model path.\"\"\"\n    mlmodel_path = os.path.join(out_dir, model_name + \".mlmodel\")\n    mlmodelc_path = os.path.join(out_dir, model_name + \".mlmodelc\")\n    metadata = {\"inputs\": list(model.input_description), \"outputs\": list(model.output_description)}\n    # Use the description field to send info to CoreML runtime\n    model.short_description = json.dumps(metadata)\n    model.save(mlmodel_path)\n\n    res = xcrun([\"coremlcompiler\", \"compile\", mlmodel_path, out_dir])\n    if not os.path.isdir(mlmodelc_path):\n        raise RuntimeError(\"Compile failed: %s\" % res)\n\n    return mlmodelc_path\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace for driver APIs\"\"\"\nfrom .build_module import lower, build\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.driver\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"driver\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name\n\"\"\"The build utils in python.\"\"\"\nfrom typing import Union, Optional, List, Mapping\n\nimport warnings\n\nimport tvm.tir\n\nfrom tvm import te\n\nfrom tvm.runtime import Module\nfrom tvm.runtime import ndarray\nfrom tvm.ir import container\nfrom tvm.tir import PrimFunc\nfrom tvm.ir.module import IRModule\nfrom tvm.te import tensor\nfrom tvm.target import Target\nfrom tvm.tir.buffer import Buffer\nfrom tvm.tir.expr import Var\nfrom tvm.driver import _ffi_api as _driver_ffi\n\nfrom . import _ffi_api as ffi\n\n\ndef get_binds(args, compact=False, binds=None):\n    \"\"\"Internal function to get binds and arg_list given arguments.\n    Parameters\n    ----------\n    args : list of Buffer or Tensor or Var\n        The argument lists to the function.\n    compact : bool\n        If the statement has already bound to a compact buffer.\n    binds : dict of :any:`Tensor` to :any:`Buffer`, optional\n        Dictionary that maps the Tensor to Buffer which specified the data layout\n        requirement of the function. By default, a new compact buffer is created\n        for each tensor in the argument.\n    Returns\n    -------\n    binds: dict\n        The bind specification\n    arg_list: list\n        The list of symbolic buffers of arguments.\n    \"\"\"\n    binds, arg_list = ffi.get_binds(args, compact, binds)\n    return binds, arg_list\n\n\ndef schedule_to_module(\n    sch: te.Schedule,\n    args: Optional[List[Union[Buffer, tensor.Tensor, Var]]] = None,\n    name: str = \"main\",\n    binds: Optional[Mapping[tensor.Tensor, Buffer]] = None,\n) -> IRModule:\n    \"\"\"According to the given schedule, form a function.\n\n    This is a low-level function intended for testing purposes, and\n    does not apply any optimization passes.  In general, `tvm.lower`\n    and `tvm.build` should be used instead.\n\n    Parameters\n    ----------\n    sch : tvm.te.schedule.Schedule\n        The given scheduler to form the raw body\n    args : list of Buffer or Tensor or Var\n        The argument lists to the function.\n    name : str\n        The name of result function, default name is \"main\"\n    binds : dict of :any:`Tensor` to :any:`Buffer`, optional\n        The binds information\n    Returns\n    -------\n    The body formed according to the given schedule\n    \"\"\"\n    return ffi.schedule_to_module(sch, args, name, binds)\n\n\ndef lower(\n    inp: Union[te.Schedule, PrimFunc, IRModule],\n    args: Optional[List[Union[Buffer, tensor.Tensor, Var]]] = None,\n    name: str = \"main\",\n    binds: Optional[Mapping[tensor.Tensor, Buffer]] = None,\n    simple_mode: bool = False,\n) -> IRModule:\n    \"\"\"Lowering step before build into target.\n\n    Parameters\n    ----------\n    inp : Union[tvm.te.schedule.Schedule, tvm.tir.PrimFunc, IRModule]\n        The TE schedule or TensorIR PrimFunc/IRModule to be built\n\n    args : Optional[List[Union[tvm.tir.Buffer, tensor.Tensor, Var]]]\n        The argument lists to the function for TE schedule.\n\n        It should be None if we want to lower TensorIR.\n    name : str\n        The name of the result function.\n\n    binds : Optional[Mapping[tensor.Tensor, tvm.tir.Buffer]]\n        Dictionary that maps the Tensor to Buffer which specified the data layout\n        requirement of the function. By default, a new compact buffer is created\n        for each tensor in the argument.\n\n    simple_mode : bool\n        Whether only output simple and compact statement, this will skip\n        LoopPartition, api wrapper generation and Unrolling.\n\n    Returns\n    -------\n    m : IRModule\n       The result IRModule\n    \"\"\"\n    if isinstance(inp, IRModule):\n        return ffi.lower_module(inp, simple_mode)\n    if isinstance(inp, PrimFunc):\n        return ffi.lower_primfunc(inp, name, simple_mode)\n    if isinstance(inp, te.Schedule):\n        return ffi.lower_schedule(inp, args, name, binds, simple_mode)\n    raise ValueError(\n        f\"Expected input to be an IRModule, PrimFunc or te.Schedule, but got {type(inp)}\"\n    )\n\n\ndef build(\n    inputs: Union[te.Schedule, PrimFunc, IRModule, Mapping[str, IRModule]],\n    args: Optional[List[Union[Buffer, tensor.Tensor, Var]]] = None,\n    target: Optional[Union[str, Target]] = None,\n    target_host: Optional[Union[str, Target]] = None,\n    runtime: Optional[\n        \"tvm.relay.backend.Runtime\"\n    ] = None,  # Type is annotated this way to avoid cyclic dependency\n    name: Optional[str] = \"default_function\",\n    binds: Optional[Mapping[tensor.Tensor, Buffer]] = None,\n):\n    \"\"\"Build a function with arguments as signature. Code will be generated\n    for devices coupled with target information.\n\n    Parameters\n    ----------\n    inputs : Union[tvm.te.schedule.Schedule, tvm.tir.PrimFunc, IRModule, Mapping[str, IRModule]]\n        The input to be built\n\n    args : Optional[List[Union[tvm.tir.Buffer, tensor.Tensor, Var]]]\n        The argument lists to the function.\n\n    target : Optional[Union[str, Target]]\n        The target and option of the compilation.\n\n    target_host : Optional[Union[str, Target]]\n        Host compilation target, if target is device.\n        When TVM compiles device specific program such as CUDA,\n        we also need host(CPU) side code to interact with the driver\n        setup the dimensions and parameters correctly.\n        target_host is used to specify the host side codegen target.\n        By default, llvm is used if it is enabled,\n        otherwise a stackvm interpreter is used.\n\n    runtime : Optional[Runtime]\n        Runtime to generate artifacts for\n\n    name : Optional[str]\n        The name of result function.\n\n    binds : Optional[Mapping[tensor.Tensor, tvm.tir.Buffer]]\n        Dictionary that maps the binding of symbolic buffer to Tensor.\n        By default, a new buffer is created for each tensor in the argument.\n\n    Returns\n    -------\n    ret : tvm.module\n        A module that combines both host and device code.\n\n    Examples\n    ________\n    There are two typical example uses of this function depending on the type\n    of the argument `inputs`:\n    1. it is an IRModule.\n\n    .. code-block:: python\n\n        n = 2\n        A = te.placeholder((n,), name='A')\n        B = te.placeholder((n,), name='B')\n        C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name='C')\n        s = tvm.te.create_schedule(C.op)\n        m = tvm.lower(s, [A, B, C], name=\"test_add\")\n        rt_mod = tvm.build(m, target=\"llvm\")\n\n    2. it is a dict of compilation target to IRModule.\n\n    .. code-block:: python\n\n        n = 2\n        A = te.placeholder((n,), name='A')\n        B = te.placeholder((n,), name='B')\n        C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name='C')\n        s1 = tvm.te.create_schedule(C.op)\n        with tvm.target.cuda() as cuda_tgt:\n          s2 = topi.cuda.schedule_injective(cuda_tgt, [C])\n          m1 = tvm.lower(s1, [A, B, C], name=\"test_add1\")\n          m2 = tvm.lower(s2, [A, B, C], name=\"test_add2\")\n          rt_mod = tvm.build({\"llvm\": m1, \"cuda\": m2})\n\n    Note\n    ----\n    See the note on :any:`tvm.target` on target string format.\n    \"\"\"\n    if isinstance(inputs, te.Schedule):\n        if args is None:\n            raise ValueError(\"args must be given for build from schedule\")\n        input_mod = lower(inputs, args, name=name, binds=binds)\n    elif isinstance(inputs, (list, tuple, container.Array)):\n        merged_mod = tvm.IRModule({})\n        for x in inputs:\n            merged_mod.update(lower(x))\n        input_mod = merged_mod\n    elif isinstance(inputs, PrimFunc):\n        input_mod = lower(inputs, name=name)\n    elif isinstance(inputs, tvm.IRModule):\n        input_mod = lower(inputs)\n    elif not isinstance(inputs, (dict, container.Map)):\n        raise ValueError(\n            f\"Inputs must be te.Schedule, IRModule, PrimFunc, \"\n            f\"or dict of target to IRModule, \"\n            f\"but got {type(inputs)}.\"\n        )\n\n    if not isinstance(inputs, (dict, container.Map)):\n        target = Target.current() if target is None else target\n        target = target if target else \"llvm\"\n        target_input_mod = {target: input_mod}\n    else:\n        target_input_mod = inputs\n\n    # Because modules can be created from a variety of sources, we annotate them\n    # with the relevant attributes here to ensure they propagate\n    annotated_mods = {}\n    for tar, mod in target_input_mod.items():\n        if not isinstance(tar, (str, Target)):\n            raise ValueError(\"The key of inputs must be str or \" \"Target when inputs is dict.\")\n        if not isinstance(mod, tvm.IRModule):\n            raise ValueError(\"inputs must be Schedule, IRModule,\" \"or dict of str to IRModule.\")\n        annotated_mods[tar] = mod.with_attr(\"runtime\", runtime)\n\n    # TODO(mbs): Both CompilationConfig and TIRToRuntime implement the same host target\n    #  defaulting logic, but there's currently no way to get back the decided host.\n    if target_host is not None:\n        warnings.warn(\n            \"target_host parameter is going to be deprecated. \"\n            \"Please pass in tvm.target.Target(target, host=target_host) instead.\"\n        )\n\n    annotated_mods, target_host = Target.canon_target_map_and_host(annotated_mods, target_host)\n    if not target_host:\n        for tar, mod in annotated_mods.items():\n            device_type = ndarray.device(tar.kind.name, 0).device_type\n            if device_type == ndarray.cpu(0).device_type:\n                target_host = tar\n                break\n    if not target_host:\n        target_host = \"llvm\" if tvm.runtime.enabled(\"llvm\") else \"stackvm\"\n\n    annotated_mods, target_host = Target.canon_target_map_and_host(annotated_mods, target_host)\n\n    rt_mod_host = _driver_ffi.tir_to_runtime(annotated_mods, target_host)\n\n    annotated_mods, target_host = Target.canon_target_map_and_host(annotated_mods, target_host)\n\n    if not isinstance(target_host, Target):\n        target_host = Target(target_host)\n\n    if str(runtime) == \"crt\" and runtime[\"system-lib\"]:\n        if target_host.kind.name == \"c\":\n            create_csource_crt_metadata_module = tvm._ffi.get_global_func(\n                \"runtime.CreateCSourceCrtMetadataModule\"\n            )\n            to_return = create_csource_crt_metadata_module([rt_mod_host], target_host, runtime)\n        elif target_host.kind.name == \"llvm\":\n            create_llvm_crt_metadata_module = tvm._ffi.get_global_func(\n                \"runtime.CreateLLVMCrtMetadataModule\"\n            )\n            to_return = create_llvm_crt_metadata_module([rt_mod_host], target_host, runtime)\n    else:\n        to_return = rt_mod_host\n\n    return OperatorModule.from_module(to_return, ir_module_by_target=annotated_mods, name=name)\n\n\nclass OperatorModule(Module):\n    \"\"\"Wraps the Module returned by tvm.build() and captures additional outputs of that function.\"\"\"\n\n    @classmethod\n    def from_module(cls, mod, **kwargs):\n        # NOTE(areusch): It is generally unsafe to continue using `mod` from this point forward.\n        # If an exception occurs in cls.__init__, handle will be deleted. For this reason,\n        # set mod.handle to None.\n        handle = mod.handle\n        mod.handle = None\n        return cls(handle, **kwargs)\n\n    def __init__(self, handle, ir_module_by_target=None, name=None):\n        super(OperatorModule, self).__init__(handle)\n        self.ir_module_by_target = ir_module_by_target\n        self.name = name\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin,wrong-import-position\n\"\"\"\nTVMC - TVM driver command-line interface\n\"\"\"\n\n\nclass TVMCException(Exception):\n    \"\"\"TVMC Exception\"\"\"\n\n\nclass TVMCImportError(TVMCException):\n    \"\"\"TVMC TVMCImportError\"\"\"\n\n\nfrom . import micro\nfrom . import runner\nfrom . import autotuner\nfrom . import compiler\nfrom . import result_utils\nfrom .frontends import load_model as load\nfrom .compiler import compile_model as compile\nfrom .runner import run_module as run\nfrom .autotuner import tune_model as tune\nfrom .model import TVMCModel, TVMCPackage, TVMCResult\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/__main__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC - TVM driver command-line interface\n\"\"\"\n\nfrom tvm.driver import tvmc\n\nif __name__ == \"__main__\":\n    tvmc.main.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/arguments.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC Argument Parsing\n\"\"\"\n\nimport argparse\n\nfrom tvm.driver.tvmc import TVMCException\n\n\nclass TVMCSuppressedArgumentParser(argparse.ArgumentParser):\n    \"\"\"\n    A silent ArgumentParser class.\n    This class is meant to be used as a helper for creating dynamic parsers in\n    TVMC. It will create a \"supressed\" parser based on an existing one (parent)\n    which does not include a help message, does not print a usage message (even\n    when -h or --help is passed) and does not exit on invalid choice parse\n    errors but rather throws a TVMCException so it can be handled and the\n    dynamic parser construction is not interrupted prematurely.\n    \"\"\"\n\n    def __init__(self, parent, **kwargs):\n        # Don't add '-h' or '--help' options to the newly created parser. Don't print usage message.\n        # 'add_help=False' won't supress existing '-h' and '--help' options from the parser (and its\n        # subparsers) present in 'parent'. However that class is meant to be used with the main\n        # parser, which is created with `add_help=False` - the help is added only later. Hence it\n        # the newly created parser won't have help options added in its (main) root parser. The\n        # subparsers in the main parser will eventually have help activated, which is enough for its\n        # use in TVMC.\n        super().__init__(parents=[parent], add_help=False, usage=argparse.SUPPRESS, **kwargs)\n\n    def exit(self, status=0, message=None):\n        # Don't exit on error when parsing the command line.\n        # This won't catch all the errors generated when parsing tho. For instance, it won't catch\n        # errors due to missing required arguments. But this will catch \"error: invalid choice\",\n        # which is what it's necessary for its use in TVMC.\n        raise TVMCException()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/autotuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support to auto-tuning networks using AutoTVM.\n\"\"\"\nimport os.path\nimport logging\nimport time\nfrom copy import deepcopy\nfrom typing import Any, Optional, Dict, List, Union\n\nfrom urllib.parse import urlparse\n\nimport tvm\nfrom tvm import autotvm, auto_scheduler\nfrom tvm.auto_scheduler.search_task import HardwareParams\nfrom tvm.autotvm.tuner import GATuner\nfrom tvm.autotvm.tuner import GridSearchTuner\nfrom tvm.autotvm.tuner import RandomTuner\nfrom tvm.autotvm.tuner import XGBTuner\nfrom tvm.target import Target\n\nfrom . import TVMCException, composite_target, frontends\nfrom .main import register_parser\nfrom .model import TVMCModel\nfrom .target import target_from_cli, generate_target_args, reconstruct_target_args\nfrom .shape_parser import parse_shape_string\nfrom .transform import convert_graph_layout\n\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\n@register_parser\ndef add_tune_parser(subparsers, _, json_params):\n    \"\"\"Include parser for 'tune' subcommand\"\"\"\n\n    parser = subparsers.add_parser(\"tune\", help=\"auto-tune a model\")\n    parser.set_defaults(func=drive_tune)\n    parser.add_argument(\n        \"--early-stopping\",\n        type=int,\n        help=\"minimum number of trials before early stopping\",\n    )\n\n    # There is some extra processing required to define the actual default value\n    # for --min-repeat-ms. This is done in `tune_model`.\n    parser.add_argument(\n        \"--min-repeat-ms\",\n        default=None,\n        type=int,\n        help=\"minimum time to run each trial, in milliseconds. \"\n        \"Defaults to 0 on x86 and 1000 on all other targets\",\n    )\n    parser.add_argument(\n        \"--model-format\",\n        choices=frontends.get_frontend_names(),\n        help=\"specify input model format\",\n    )\n    parser.add_argument(\n        \"--number\",\n        default=10,\n        type=int,\n        help=\"number of runs a single repeat is made of. \"\n        \"The final number of tuning executions is: \"\n        \"(1 + number * repeat)\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        required=True,\n        help=\"output file to store the tuning records for the tuning process\",\n    )\n    parser.add_argument(\n        \"--parallel\",\n        default=4,\n        type=int,\n        help=\"the maximum number of parallel devices to use when tuning\",\n    )\n    parser.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n        help=\"how many times to repeat each measurement\",\n    )\n    parser.add_argument(\n        \"--rpc-key\",\n        help=\"the RPC tracker key of the target device. \"\n        \"Required when --rpc-tracker is provided.\",\n    )\n    parser.add_argument(\n        \"--rpc-tracker\",\n        help=\"hostname (required) and port (optional, defaults to 9090) of the RPC tracker, \"\n        \"e.g. '192.168.0.100:9999'\",\n    )\n\n    generate_target_args(parser)\n    parser.add_argument(\n        \"--target-host\",\n        help=\"the host compilation target, defaults to 'llvm'\",\n        default=\"llvm\",\n    )\n\n    parser.add_argument(\"--timeout\", type=int, default=10, help=\"compilation timeout, in seconds\")\n    parser.add_argument(\n        \"--trials\",\n        type=int,\n        default=1000,\n        help=\"the maximum number of tuning trials to perform\",\n    )\n    parser.add_argument(\n        \"--tuning-records\",\n        metavar=\"PATH\",\n        help=\"path to an auto-tuning log file by AutoTVM.\",\n    )\n    parser.add_argument(\n        \"--desired-layout\",\n        choices=[\"NCHW\", \"NHWC\"],\n        default=None,\n        help=\"change the data layout of the whole graph\",\n    )\n    parser.add_argument(\n        \"--enable-autoscheduler\",\n        help=\"enable tuning the graph through the AutoScheduler tuner\",\n        action=\"store_true\",\n    )\n\n    auto_scheduler_group = parser.add_argument_group(\n        \"AutoScheduler options\",\n        \"AutoScheduler options, used when --enable-autoscheduler is provided\",\n    )\n\n    auto_scheduler_group.add_argument(\n        \"--cache-line-bytes\",\n        type=int,\n        help=\"the size of cache line in bytes. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--num-cores\",\n        type=int,\n        help=\"the number of device cores. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--vector-unit-bytes\",\n        type=int,\n        help=\"the width of vector units in bytes. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--max-shared-memory-per-block\",\n        type=int,\n        help=\"the max shared memory per block in bytes. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--max-local-memory-per-block\",\n        type=int,\n        help=\"the max local memory per block in bytes. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--max-threads-per-block\",\n        type=int,\n        help=\"the max number of threads per block. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--max-vthread-extent\",\n        type=int,\n        help=\"the max vthread extent. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--warp-size\",\n        type=int,\n        help=\"the thread numbers of a warp. \"\n        \"If not specified, it will be autoset for the current machine.\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--include-simple-tasks\",\n        help=\"whether to extract simple tasks that do not include complicated ops\",\n        action=\"store_true\",\n    )\n    auto_scheduler_group.add_argument(\n        \"--log-estimated-latency\",\n        help=\"whether to log the estimated latency to the file after tuning a task\",\n        action=\"store_true\",\n    )\n    autotvm_group = parser.add_argument_group(\n        \"AutoTVM options\",\n        \"AutoTVM options, used when the AutoScheduler is not enabled\",\n    )\n    autotvm_group.add_argument(\n        \"--tuner\",\n        choices=[\"ga\", \"gridsearch\", \"random\", \"xgb\", \"xgb_knob\", \"xgb-rank\"],\n        default=\"xgb\",\n        help=\"type of tuner to use when tuning with autotvm.\",\n    )\n    # TODO (@leandron) This is a path to a physical file, but\n    #     can be improved in future to add integration with a modelzoo\n    #     or URL, for example.\n    parser.add_argument(\"FILE\", help=\"path to the input model file\")\n    parser.add_argument(\n        \"--input-shapes\",\n        help=\"specify non-generic shapes for model to run, format is \"\n        '\"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]\"',\n        type=parse_shape_string,\n    )\n\n    for one_entry in json_params:\n        parser.set_defaults(**one_entry)\n\n\ndef drive_tune(args):\n    \"\"\"Invoke auto-tuning with command line arguments\n\n    Parameters\n    ----------\n    args: argparse.Namespace\n        Arguments from command line parser.\n    \"\"\"\n    if not os.path.isfile(args.FILE):\n        raise TVMCException(\n            f\"Input file '{args.FILE}' doesn't exist, is a broken symbolic link, or a directory.\"\n        )\n\n    tvmc_model = frontends.load_model(args.FILE, args.model_format, shape_dict=args.input_shapes)\n\n    # Specify hardware parameters, although they'll only be used if autoscheduling.\n    hardware_params = auto_scheduler.HardwareParams(\n        num_cores=args.num_cores,\n        vector_unit_bytes=args.vector_unit_bytes,\n        cache_line_bytes=args.cache_line_bytes,\n        max_shared_memory_per_block=args.max_shared_memory_per_block,\n        max_local_memory_per_block=args.max_local_memory_per_block,\n        max_threads_per_block=args.max_threads_per_block,\n        max_vthread_extent=args.max_vthread_extent,\n        warp_size=args.warp_size,\n        target=args.target,\n        target_host=args.target_host,\n    )\n\n    if args.rpc_tracker:\n        parsed_url = urlparse(\"//%s\" % args.rpc_tracker)\n        rpc_hostname = parsed_url.hostname\n        rpc_port = parsed_url.port or 9090\n        logger.info(\"RPC tracker hostname: %s\", rpc_hostname)\n        logger.info(\"RPC tracker port: %s\", rpc_port)\n\n        if not args.rpc_key:\n            raise TVMCException(\"need to provide an RPC tracker key (--rpc-key) for remote tuning\")\n    else:\n        rpc_hostname = None\n        rpc_port = None\n\n    tune_model(\n        tvmc_model,\n        args.target,\n        tuning_records=args.output,\n        prior_records=args.tuning_records,\n        enable_autoscheduler=args.enable_autoscheduler,\n        rpc_key=args.rpc_key,\n        hostname=rpc_hostname,\n        port=rpc_port,\n        trials=args.trials,\n        target_host=args.target_host,\n        tuner=args.tuner,\n        min_repeat_ms=args.min_repeat_ms,\n        early_stopping=args.early_stopping,\n        desired_layout=args.desired_layout,\n        timeout=args.timeout,\n        repeat=args.repeat,\n        number=args.number,\n        parallel=args.parallel,\n        hardware_params=hardware_params,\n        include_simple_tasks=args.include_simple_tasks,\n        log_estimated_latency=args.log_estimated_latency,\n        additional_target_options=reconstruct_target_args(args),\n    )\n\n\ndef tune_model(\n    tvmc_model: TVMCModel,\n    target: str,\n    tuning_records: Optional[str] = None,\n    prior_records: Optional[str] = None,\n    enable_autoscheduler: bool = False,\n    rpc_key: Optional[str] = None,\n    hostname: Optional[str] = None,\n    port: Optional[Union[int, str]] = 9090,\n    trials: int = 10000,\n    target_host: Optional[str] = None,\n    tuner: str = \"xgb\",\n    min_repeat_ms: Optional[int] = None,\n    early_stopping: Optional[int] = None,\n    desired_layout: Optional[str] = None,\n    timeout: int = 10,\n    repeat: int = 1,\n    number: int = 10,\n    parallel: int = 4,\n    hardware_params: Optional[HardwareParams] = None,\n    include_simple_tasks: bool = False,\n    log_estimated_latency: bool = False,\n    additional_target_options: Optional[Dict[str, Dict[str, Any]]] = None,\n):\n    \"\"\"Use tuning to automatically optimize the functions in a model.\n\n    Parameters\n    ----------\n    tvmc_model : TVMCModel\n        The model to be optimized.\n    target : str\n        Compilation target as plain string, inline JSON or path to a JSON file.\n    tuning_records: str, optional\n        The path to a file that tuning results will be saved to. If not specified,\n        a temporary file will be used.\n    prior_records: str, optional\n        A path to previous tuning results that will be used to hot-start the tuning\n        cost model if provided.\n    enable_autoscheduler : bool, optional\n        When true, use autoscheduling rather than autotvm. This should produce\n        faster kernels for compatible model-target pairs.\n    rpc_key : str, optional\n        The RPC tracker key of the target device. Required when rpc_tracker is provided.\n    hostname : str, optional\n        The IP address of an RPC tracker, used when benchmarking remotely.\n    port : int or str, optional\n        The port of the RPC tracker to connect to. Defaults to 9090.\n    trials : int, optional\n        The number of schedules to try out for the entire model. Note that the default\n        value is chosen as a decent average for most models, but larger models may need\n        more trials to reach a good result while smaller models will converge with fewer\n        trials.\n    tuner : str, optional\n        The type of tuner to use when tuning with autotvm. Can be one of\n        \"ga\", \"gridsearch\", \"random\", \"xgb\", \"xgb_knob\", and \"xgb-rank\".\n    min_repeat_ms : int, optional\n        Minimum time to run each trial. Defaults to 0 on x86 and 1000 on other targets.\n    early_stopping : int, optional\n        When specified, stop tuning after this number of trials if results aren't improving.\n    desired_layout : str, optional\n        Can be one of \"NCHW\" or \"NHWC\". When specified, compatible operations in the graph\n        will have their layout set to this format. Tasks will then be tuned using this\n        specified layout.\n    timeout : int, optional,\n        If a kernel trial lasts longer than this duration in seconds, it will be\n        considered a failure.\n    repeat : int, optional\n        How many times each measurement should be repeated.\n    number : int, optional\n        The number of runs a single repeat is made of.\n    parallel : int, optional\n        The maximum number of parallel devices to use when tuning.\n    hardware_params : auto_scheduler.HardwareParams, optional\n        When using the autoscheduler, this object defines the configuration of the target hardware.\n    include_simple_tasks : bool, optional\n        Whether to extract simple operations or only computationally intensive ones when using\n        the autoscheduler.\n    log_estimated_latency : bool, optional\n        If using the autoscheduler, write the estimated latency at each step of tuning to file.\n    additional_target_options: Optional[Dict[str, Dict[str, Any]]]\n        Additional target options in a dictionary to combine with initial Target arguments\n\n    Returns\n    -------\n    tuning_records : str\n        The path to the produced tuning log file.\n    \"\"\"\n    target, extra_targets = target_from_cli(target, additional_target_options)\n    target, target_host = Target.canon_target_and_host(target, target_host)\n    # TODO(jwfromm) Remove this deepcopy once AlterOpLayout bug that mutates source\n    # model is fixed. For now, creating a clone avoids the issue.\n    mod = deepcopy(tvmc_model.mod)\n    params = tvmc_model.params\n\n    with tvm.transform.PassContext(opt_level=3):\n        if tuning_records is None:\n            tuning_records = tvmc_model.default_tuning_records_path()\n\n        for codegen_from_cli in extra_targets:\n            codegen = composite_target.get_codegen_by_target(codegen_from_cli[\"name\"])\n            partition_function = codegen[\"pass_pipeline\"]\n            mod = partition_function(mod, params, **codegen_from_cli[\"opts\"])\n\n        # min_repeat_ms should be:\n        # a. the value provided by the user, if any, or\n        # b. 0ms in case target is \"cpu\"; otherwise 1000ms\n        if min_repeat_ms is None:\n            min_repeat_ms = 0 if target.keys[0] == \"cpu\" else 1000\n            logger.info(\"Default --min-repeat-ms for this target is %s\", min_repeat_ms)\n\n        if rpc_key:\n            if hostname is None or port is None:\n                raise TVMCException(\n                    \"You must provide a hostname and port to connect to a remote RPC device.\"\n                )\n            if isinstance(port, str):\n                port = int(port)\n\n            logger.info(\"Tuning will be performed on device %s at %s:%d.\", rpc_key, hostname, port)\n\n            runner_ctor = auto_scheduler.RPCRunner if enable_autoscheduler else autotvm.RPCRunner\n            runner = runner_ctor(\n                key=rpc_key,\n                host=hostname,\n                port=port,\n                number=number,\n                repeat=repeat,\n                n_parallel=parallel,\n                timeout=timeout,\n                min_repeat_ms=min_repeat_ms,\n            )\n        else:\n            logger.info(\"Starting localhost tuning.\")\n            runner_ctor = (\n                auto_scheduler.LocalRPCMeasureContext\n                if enable_autoscheduler\n                else autotvm.LocalRunner\n            )\n            local_server = runner_ctor(\n                number=number,\n                repeat=repeat,\n                timeout=timeout,\n                min_repeat_ms=min_repeat_ms,\n            )\n\n            # For autoscheduling on some devices, we need to maintain a\n            # LocalRPCMeasureContext object.\n            if enable_autoscheduler:\n                runner = local_server.runner\n            else:\n                runner = local_server\n\n        if enable_autoscheduler:\n\n            tasks, weights = autoscheduler_get_tuning_tasks(\n                mod=mod,\n                params=params,\n                target=target,\n                alter_layout=desired_layout,\n                hardware_params=hardware_params,\n                include_simple_tasks=include_simple_tasks,\n            )\n\n            # Create the autoscheduler tuning options\n            tuning_options = auto_scheduler.TuningOptions(\n                num_measure_trials=trials,\n                measure_callbacks=[auto_scheduler.RecordToFile(tuning_records)],\n                runner=runner,\n                early_stopping=early_stopping,\n            )\n\n            logger.info(\"Autoscheduling with configuration: %s\", tuning_options)\n\n            # Schedule the tasks (i.e., produce a schedule for each task)\n            schedule_tasks(tasks, weights, tuning_options, prior_records, log_estimated_latency)\n        else:\n            tasks = autotvm_get_tuning_tasks(\n                mod=mod,\n                params=params,\n                target=target,\n                alter_layout=desired_layout,\n            )\n\n            # In autotvm, trials is specified per task. We can convert the per-model input\n            # provided to per-task trials by dividing by the number of tasks.\n            trials = int(trials / max(len(tasks), 1))\n            logger.info(\"Autotuning with %d trials per task.\", trials)\n\n            tuning_options = {\n                \"tuner\": tuner,\n                \"trials\": trials,\n                \"early_stopping\": early_stopping,\n                \"measure_option\": autotvm.measure_option(\n                    builder=autotvm.LocalBuilder(build_func=\"default\"), runner=runner\n                ),\n                \"tuning_records\": prior_records,\n            }\n            logger.info(\"Autotuning with configuration: %s\", tuning_options)\n\n            tune_tasks(tasks, tuning_records, **tuning_options)\n\n        return tuning_records\n\n\ndef autotvm_get_tuning_tasks(\n    mod: tvm.IRModule,\n    params: Dict[str, tvm.nd.NDArray],\n    target: str,\n    target_host: Optional[str] = None,\n    alter_layout: Optional[str] = None,\n):\n    \"\"\"Get the autotvm tuning tasks for a given relay module.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The relay module from which to extract tuning tasks.\n    params : dict\n        The params for the relay module.\n    target : tvm.target.Target\n        The compilation target.\n    target_host : str, optional\n        The compilation target for the host.\n    alter_layout : str, optional\n        The layout to convert the graph to. Note, the convert layout\n        pass doesn't currently guarantee the whole of the graph will\n        be converted to the chosen layout.\n\n    Returns\n    -------\n    tasks : list of autotvm.Tasks\n        list of tasks to be tuned\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    if alter_layout:\n        mod = convert_graph_layout(mod, alter_layout)\n\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"],\n        target=target,\n        params=params,\n    )\n\n    return tasks\n\n\ndef autoscheduler_get_tuning_tasks(\n    mod: tvm.IRModule,\n    params: Dict[str, tvm.nd.NDArray],\n    target: str,\n    target_host: Optional[str] = None,\n    alter_layout: Optional[str] = None,\n    hardware_params: Optional[HardwareParams] = None,\n    include_simple_tasks: bool = False,\n):\n    \"\"\"Get the autoscheduler tuning tasks for a given relay module.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The relay module from which to extract tuning tasks.\n    params : dict\n        The params for the relay module.\n    target : tvm.target.Target\n        The compilation target.\n    target_host : str, optional\n        The compilation target for the host.\n    alter_layout : str, optional\n        The layout to convert the graph to. Note, the convert layout\n        pass doesn't currently guarantee the whole of the graph will\n        be converted to the chosen layout.\n    hardware_params : Optional[HardwareParams]\n        Hardware parameters used for the search tasks\n\n    Returns\n    -------\n    tasks : list of autotvm.Tasks\n        list of tasks to be tuned\n    weights : List[int]\n        the weight (i.e. the number of appearance) of extracted tasks\n    \"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n\n    if alter_layout:\n        mod = convert_graph_layout(mod, alter_layout)\n\n    # Extract the tasks\n    tasks, task_weights = auto_scheduler.extract_tasks(\n        mod[\"main\"],\n        params,\n        target=target,\n        hardware_params=hardware_params,\n        include_simple_tasks=include_simple_tasks,\n    )\n\n    return tasks, task_weights\n\n\ndef schedule_tasks(\n    tasks: List[auto_scheduler.SearchTask],\n    task_weights: List[float],\n    tuning_options: auto_scheduler.TuningOptions,\n    prior_records: Optional[str] = None,\n    log_estimated_latency: bool = False,\n):\n    \"\"\"Generate the schedules for the different tasks (i.e., subgraphs) contained in the module.\n    Store the schedules in a json file that will be used later by the compiler.\n\n    Parameters\n    ----------\n    tasks : list\n        A list of auto_scheduler.SearchTask to tune.\n    task_weights : list\n        The weight (i.e. the number of appearance) of extracted tasks\n    tuning_options: auto_scheduler.TuningOptions\n        The options of tuning\n    prior_records : str, optional\n        The json file used to preload the autoscheduler\n    log_estimated_latency : bool, optional\n        If true, writes the estimated runtime of the model during each step of tuning to file.\n    \"\"\"\n    if not log_estimated_latency:\n        callbacks = [auto_scheduler.task_scheduler.PrintTableInfo()]\n    else:\n        callbacks = [\n            auto_scheduler.task_scheduler.PrintTableInfo(),\n            auto_scheduler.task_scheduler.LogEstimatedLatency((\"total_latency.tsv\")),\n        ]\n\n    # Create the scheduler\n    tuner = auto_scheduler.TaskScheduler(\n        tasks, task_weights, load_log_file=prior_records, callbacks=callbacks\n    )\n\n    # Tune the tasks\n    tuner.tune(tuning_options)\n\n\ndef tune_tasks(\n    tasks: List[autotvm.task.Task],\n    log_file: str,\n    measure_option: autotvm.measure_option,\n    tuner: str,\n    trials: int,\n    early_stopping: Optional[int] = None,\n    tuning_records: Optional[str] = None,\n):\n    \"\"\"Tune a list of tasks and output the history to a log file.\n\n    Parameters\n    ----------\n    tasks : list\n        A list of autotvm.Tasks to tune.\n    log_file : str\n        A file to output the tuning history, in JSON.\n    measure_option : autotvm.measure_option\n        Options to build and run a tuning task.\n    tuner : str\n        Which tuner to use.\n    trials : int\n        The maximum number of tuning trials to perform.\n    early_stopping : int, optional\n        The minimum number of tuning trials to perform.\n        This will be equal to 'trials' if not specified.\n    tuning_records: str, optional\n        Path to the file produced by the tuning, to be used during\n        tuning.\n    \"\"\"\n    if not tasks:\n        logger.warning(\"there were no tasks found to be tuned\")\n        return\n\n    if not early_stopping:\n        early_stopping = trials\n\n    for i, tsk in enumerate(tasks):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # Create a tuner\n        if tuner in (\"xgb\", \"xgb-rank\"):\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"xgb_knob\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"knob\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise TVMCException(\"invalid tuner: %s \" % tuner)\n\n        # If transfer learning is being used, load the existing results\n        if tuning_records and os.path.exists(tuning_records):\n            logger.info(\"loading tuning records from %s\", tuning_records)\n            start_time = time.time()\n            tuner_obj.load_history(autotvm.record.load_from_file(tuning_records))\n            logging.info(\"loaded history in %.2f sec(s)\", time.time() - start_time)\n\n        tuner_obj.tune(\n            n_trial=min(trials, len(tsk.config_space)),\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(trials, prefix=prefix),\n                autotvm.callback.log_to_file(log_file),\n            ],\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support to compile networks both AOT and JIT.\n\"\"\"\nimport logging\nimport os.path\nfrom typing import Any, Optional, Dict, List, Union, Callable, Sequence\nfrom pathlib import Path\n\nimport tvm\nfrom tvm import autotvm, auto_scheduler\nfrom tvm import relay\nfrom tvm.driver.tvmc.registry import generate_registry_args, reconstruct_registry_entity\nfrom tvm.ir.instrument import PassInstrument\nfrom tvm.ir.memory_pools import WorkspaceMemoryPools\nfrom tvm.target import Target\nfrom tvm.relay.backend import Executor, Runtime\n\nfrom . import composite_target, frontends, TVMCException\nfrom .model import TVMCModel, TVMCPackage\nfrom .main import register_parser\nfrom .target import target_from_cli, generate_target_args, reconstruct_target_args\nfrom .pass_config import parse_configs\nfrom .pass_list import parse_pass_list_str\nfrom .transform import convert_graph_layout\nfrom .shape_parser import parse_shape_string\nfrom .workspace_pools import generate_workspace_pools_args, workspace_pools_recombobulate\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\n@register_parser\ndef add_compile_parser(subparsers, _, json_params):\n    \"\"\"Include parser for 'compile' subcommand\"\"\"\n\n    parser = subparsers.add_parser(\"compile\", help=\"compile a model.\")\n    parser.set_defaults(func=drive_compile)\n    parser.add_argument(\n        \"--cross-compiler\",\n        default=\"\",\n        help=\"the cross compiler to generate target libraries, e.g. 'aarch64-linux-gnu-gcc'.\",\n    )\n    parser.add_argument(\n        \"--cross-compiler-options\",\n        default=\"\",\n        help=\"the cross compiler options to generate target libraries, e.g. '-mfpu=neon-vfpv4'.\",\n    )\n    parser.add_argument(\n        \"--desired-layout\",\n        choices=[\"NCHW\", \"NHWC\"],\n        default=None,\n        help=\"change the data layout of the whole graph.\",\n    )\n    parser.add_argument(\n        \"--dump-code\",\n        metavar=\"FORMAT\",\n        default=\"\",\n        help=\"comma separated list of formats to export the input model, e.g. 'asm,ll,relay'.\",\n    )\n    parser.add_argument(\n        \"--model-format\",\n        choices=frontends.get_frontend_names(),\n        help=\"specify input model format.\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        default=\"module.tar\",\n        help=\"output the compiled module to a specified archive. Defaults to 'module.tar'.\",\n    )\n    parser.add_argument(\n        \"-f\",\n        \"--output-format\",\n        choices=[\"so\", \"mlf\"],\n        default=\"so\",\n        help=\"output format. Use 'so' for shared object or 'mlf' for Model Library Format \"\n        \"(only for microTVM targets). Defaults to 'so'.\",\n    )\n    parser.add_argument(\n        \"--pass-config\",\n        action=\"append\",\n        metavar=(\"name=value\"),\n        help=\"configurations to be used at compile time. This option can be provided multiple \"\n        \"times, each one to set one configuration value, \"\n        \"e.g. '--pass-config relay.backend.use_auto_scheduler=0', \"\n        \"e.g. '--pass-config tir.add_lower_pass=opt_level1,pass1,opt_level2,pass2'.\",\n    )\n\n    generate_target_args(parser)\n    parser.add_argument(\n        \"--tuning-records\",\n        metavar=\"PATH\",\n        default=\"\",\n        help=\"path to an auto-tuning log file by AutoTVM. If not presented, \"\n        \"the fallback/tophub configs will be used.\",\n    )\n    generate_registry_args(parser, Executor, \"graph\")\n    generate_registry_args(parser, Runtime, \"cpp\")\n\n    parser.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0, help=\"increase verbosity.\")\n    # TODO (@leandron) This is a path to a physical file, but\n    #     can be improved in future to add integration with a modelzoo\n    #     or URL, for example.\n    parser.add_argument(\"FILE\", help=\"path to the input model file.\")\n    parser.add_argument(\n        \"-O\",\n        \"--opt-level\",\n        default=3,\n        type=int,\n        choices=range(0, 4),\n        metavar=\"[0-3]\",\n        help=\"specify which optimization level to use. Defaults to '3'.\",\n    )\n    parser.add_argument(\n        \"--input-shapes\",\n        help=\"specify non-generic shapes for model to run, format is \"\n        '\"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]\".',\n        type=parse_shape_string,\n        default=None,\n    )\n    parser.add_argument(\n        \"--disabled-pass\",\n        help=\"disable specific passes, comma-separated list of pass names.\",\n        type=parse_pass_list_str,\n        default=\"\",\n    )\n    parser.add_argument(\n        \"--module-name\",\n        default=\"default\",\n        help=\"The output module name. Defaults to 'default'.\",\n    )\n    for one_entry in json_params:\n        parser.set_defaults(**one_entry)\n\n    generate_workspace_pools_args(parser)\n\n\ndef drive_compile(args):\n    \"\"\"Invoke tvmc.compiler module with command line arguments\n\n    Parameters\n    ----------\n    args: argparse.Namespace\n        Arguments from command line parser.\n\n    Returns\n    -------\n    int\n        Zero if successfully completed\n\n    \"\"\"\n\n    if not os.path.isfile(args.FILE):\n        raise TVMCException(\n            f\"Input file '{args.FILE}' doesn't exist, is a broken symbolic link, or a directory.\"\n        )\n\n    tvmc_model = frontends.load_model(args.FILE, args.model_format, args.input_shapes)\n\n    dump_code = [x.strip() for x in args.dump_code.split(\",\")] if args.dump_code else None\n\n    additional_targets = reconstruct_target_args(args)\n    workspace_pools_target, extra_targets = target_from_cli(args.target, additional_targets)\n\n    compile_model(\n        tvmc_model,\n        args.target,\n        opt_level=args.opt_level,\n        executor=reconstruct_registry_entity(args, Executor),\n        runtime=reconstruct_registry_entity(args, Runtime),\n        tuning_records=args.tuning_records,\n        package_path=args.output,\n        cross=args.cross_compiler,\n        cross_options=args.cross_compiler_options,\n        output_format=args.output_format,\n        dump_code=dump_code,\n        target_host=None,\n        desired_layout=args.desired_layout,\n        disabled_pass=args.disabled_pass,\n        pass_context_configs=args.pass_config,\n        mod_name=args.module_name,\n        additional_target_options=additional_targets,\n        workspace_pools=(\n            workspace_pools_recombobulate(args, [workspace_pools_target], extra_targets)\n        ),\n    )\n\n    return 0\n\n\ndef compile_model(\n    tvmc_model: TVMCModel,\n    target: str,\n    opt_level: int = 3,\n    executor: Optional[Executor] = Executor(\"graph\"),\n    runtime: Optional[Runtime] = Runtime(\"cpp\"),\n    tuning_records: Optional[str] = None,\n    package_path: Optional[str] = None,\n    cross: Optional[Union[str, Callable]] = None,\n    cross_options: Optional[str] = None,\n    output_format: str = \"so\",\n    dump_code: Optional[List[str]] = None,\n    target_host: Optional[str] = None,\n    desired_layout: Optional[str] = None,\n    disabled_pass: Optional[str] = None,\n    pass_context_configs: Optional[List[str]] = None,\n    additional_target_options: Optional[Dict[str, Dict[str, Any]]] = None,\n    use_vm: bool = False,\n    mod_name: Optional[str] = \"default\",\n    workspace_pools: Optional[WorkspaceMemoryPools] = None,\n    instruments: Optional[Sequence[PassInstrument]] = None,\n):\n    \"\"\"Compile a model from a supported framework into a TVM module.\n\n    This function takes a union of the arguments of both frontends.load_model\n    and compiler.compile_relay. The resulting TVM module can be executed using\n    the graph executor.\n\n    Parameters\n    ----------\n    tvmc_model : TVMCModel\n        The model object that should be compiled.\n    target : str\n        The target for which to compile. Can be a plain string or\n        a path.\n    opt_level : int\n        The option that controls various sorts of optimizations.\n    tuning_records : str\n        A path to tuning records produced using tvmc.tune. When provided,\n        compilation will use more optimized kernels leading to better results.\n    package_path : str, optional\n        The path to export the compiled model to. If not provided it will\n        be saved in a temporary directory.\n    cross : str or callable object, optional\n        Function that performs the actual compilation\n    cross_options : str, optional\n        Command line options to be passed to the cross compiler.\n    output_format : str\n        What format to use when saving the function library. Must be one of \"so\" or \"tar\".\n        When compiling for a remote device without a cross compiler, \"tar\" will likely work better.\n    dump_code : list, optional\n        Dump the generated code for the specified source types, on\n        the requested target.\n    target_host : str, optional\n        The target of the host machine if host-side code\n        needs to be generated.\n    desired_layout: str, optional\n        The layout to convert the graph to. Note, the convert layout\n        pass doesn't currently guarantee the whole of the graph will\n        be converted to the chosen layout.\n    disabled_pass: str, optional\n        Comma-separated list of passes which needs to be disabled\n        during compilation\n    pass_context_configs: list[str], optional\n        List of strings containing a set of configurations to be passed to the\n        PassContext.\n    additional_target_options: Optional[Dict[str, Dict[str, Any]]]\n        Additional target options in a dictionary to combine with initial Target arguments\n    use_vm: bool\n        Whether to use the VM to compile the model as opposed to the graph executor\n    mod_name: str, optional\n        The module name\n    workspace_pools: WorkspaceMemoryPools, optional\n        Specification of WorkspacePoolInfo objects to be used as workspace memory in the\n        compilation.\n    instruments: Optional[Sequence[PassInstrument]]\n        The list of pass instrument implementations.\n\n    Returns\n    -------\n    compiled_model : TVMCPackage\n        The compiled TVMCModel ready to be run.\n\n    \"\"\"\n    mod, params = tvmc_model.mod, tvmc_model.params\n\n    config = parse_configs(pass_context_configs)\n\n    tvm_target, extra_targets = target_from_cli(target, additional_target_options)\n    tvm_target, target_host = Target.canon_target_and_host(tvm_target, target_host)\n\n    partition_functions = []\n    partition_opts = []\n    for codegen_from_cli in extra_targets:\n        codegen = composite_target.get_codegen_by_target(codegen_from_cli[\"name\"])\n        partition_functions.append(codegen[\"pass_pipeline\"])\n        partition_opts.append(codegen_from_cli[\"opts\"])\n        if codegen[\"config_key\"] is not None:\n            config[codegen[\"config_key\"]] = codegen_from_cli[\"opts\"]\n\n    with tvm.transform.PassContext(\n        opt_level=opt_level,\n        config=config,\n        disabled_pass=disabled_pass,\n        instruments=instruments,\n    ):\n        if desired_layout:\n            mod = convert_graph_layout(mod, desired_layout)\n\n        for partition_function, opts in zip(partition_functions, partition_opts):\n            mod = partition_function(mod, params, mod_name=mod_name, **opts)\n\n        if tuning_records and os.path.exists(tuning_records):\n            logger.debug(\"tuning records file provided: %s\", tuning_records)\n\n            use_autoscheduler = True\n            try:\n                auto_scheduler.load_records(tuning_records)\n            except tvm._ffi.base.TVMError:\n                use_autoscheduler = False\n\n            if use_autoscheduler:\n                with auto_scheduler.ApplyHistoryBest(tuning_records):\n                    config[\"relay.backend.use_auto_scheduler\"] = True\n                    logger.debug(\"building relay graph with autoscheduler\")\n                    graph_module = build(\n                        mod,\n                        tvm_target=tvm_target,\n                        executor=executor,\n                        runtime=runtime,\n                        params=params,\n                        use_vm=use_vm,\n                        mod_name=mod_name,\n                        workspace_pools=workspace_pools,\n                    )\n            else:\n                with autotvm.apply_history_best(tuning_records):\n                    logger.debug(\"building relay graph with tuning records\")\n                    graph_module = build(\n                        mod,\n                        tvm_target=tvm_target,\n                        executor=executor,\n                        runtime=runtime,\n                        params=params,\n                        use_vm=use_vm,\n                        mod_name=mod_name,\n                        workspace_pools=workspace_pools,\n                    )\n        else:\n            logger.debug(\"building relay graph (no tuning records provided)\")\n            graph_module = build(\n                mod,\n                tvm_target=tvm_target,\n                executor=executor,\n                runtime=runtime,\n                params=params,\n                use_vm=use_vm,\n                mod_name=mod_name,\n                workspace_pools=workspace_pools,\n            )\n\n        # Generate output dump files with sources\n        if dump_code is None:\n            dump_code = []\n        if not isinstance(dump_code, list):\n            dump_code = [dump_code]\n        dumps = {}\n        for source_type in dump_code:\n            if use_vm:\n                lib = graph_module.lib\n            else:\n                lib = graph_module.get_lib()\n            # TODO lib.get_source call have inconsistent behavior for unsupported\n            #      formats (@leandron).\n            source = str(mod) if source_type == \"relay\" else lib.get_source(source_type)\n            dumps[source_type] = source\n\n        # Create a new tvmc model package object from the graph definition.\n        package_path = tvmc_model.export_package(\n            graph_module, package_path, cross, cross_options, output_format\n        )\n\n        # Write dumps to file.\n        if dumps:\n            save_dumps(package_path, dumps)\n\n        return TVMCPackage(package_path)\n\n\ndef build(\n    mod: tvm.IRModule,\n    tvm_target: str,\n    executor: Executor,\n    runtime: Runtime,\n    params: Dict[str, tvm.nd.NDArray],\n    use_vm: bool,\n    mod_name: str,\n    workspace_pools: Optional[WorkspaceMemoryPools],\n):\n    \"\"\"\n    Builds the model with the provided executor.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The relay module corresponding to this model.\n    tvm_target : str\n        The target for which to compile. Can be a plain string or\n        a path.\n    executor : Executor\n        The graph executor to build the model if use_vm is not True\n    runtime : Runtime\n        The runtime configuration.\n    params : dict\n        A parameter dictionary for the model.\n    use_vm: bool\n        Whether to use the VM to compile the model as opposed to the graph executor\n    mod_name: str\n        The module name\n\n    \"\"\"\n    if use_vm:\n        logger.debug(\"building with vm compile\")\n        return relay.vm.compile(mod, target=tvm_target, params=params)\n    logger.debug(\"building with relay build\")\n    return relay.build(\n        mod,\n        target=tvm_target,\n        executor=executor,\n        runtime=runtime,\n        params=params,\n        mod_name=mod_name,\n        workspace_memory_pools=workspace_pools,\n    )\n\n\ndef save_dumps(module_name: str, dumps: Dict[str, str], dump_root: str = \".\"):\n    \"\"\"\n    Serialize dump files to the disk.\n\n    Parameters\n    ----------\n    module_name : str\n        File name, referring to the module that generated\n        the dump contents\n    dumps : dict\n        The output contents to be saved into the files\n    dump_root : str, optional\n        Path in which dump files will be created\n    \"\"\"\n\n    for dump_format in dumps:\n        dump_name = module_name + \".\" + dump_format\n        with open(Path(dump_root, dump_name), \"w\") as f:\n            f.write(dumps[dump_format])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/composite_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support to composite target on TVMC.\n\"\"\"\nimport logging\n\n# Make sure Vitis AI codegen is registered\nimport tvm.contrib.target.vitis_ai  # pylint: disable=unused-import\n\nfrom tvm.relay.op.contrib.arm_compute_lib import partition_for_arm_compute_lib\nfrom tvm.relay.op.contrib.ethosn import partition_for_ethosn\nfrom tvm.relay.op.contrib.cmsisnn import partition_for_cmsisnn\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.relay.op.contrib.bnns import partition_for_bnns\nfrom tvm.relay.op.contrib.vitis_ai import partition_for_vitis_ai\n\n\nfrom tvm.driver.tvmc import TVMCException\n\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\n# Global dictionary to map targets\n#\n# Options\n# -------\n# config_key : str\n#   The configuration key to be used in the PassContext (if any).\n# pass_pipeline : Callable\n#   A function to transform a Module before compilation, mainly used\n#   for partitioning for the target currently.\nREGISTERED_CODEGEN = {\n    \"compute-library\": {\n        \"config_key\": None,\n        \"pass_pipeline\": partition_for_arm_compute_lib,\n    },\n    \"cmsis-nn\": {\n        \"config_key\": \"relay.ext.cmsisnn.options\",\n        \"pass_pipeline\": partition_for_cmsisnn,\n    },\n    \"ethos-n\": {\n        \"config_key\": \"relay.ext.ethos-n.options\",\n        \"pass_pipeline\": partition_for_ethosn,\n    },\n    \"ethos-u\": {\n        \"config_key\": \"relay.ext.ethos-u.options\",\n        \"pass_pipeline\": partition_for_ethosu,\n    },\n    \"bnns\": {\n        \"config_key\": None,\n        \"pass_pipeline\": partition_for_bnns,\n    },\n    \"vitis-ai\": {\n        \"config_key\": \"relay.ext.vitis_ai.options\",\n        \"pass_pipeline\": partition_for_vitis_ai,\n    },\n}\n\n\ndef get_codegen_names():\n    \"\"\"Return a list of all registered codegens.\n\n    Returns\n    -------\n    list of str\n        all registered targets\n    \"\"\"\n    return list(REGISTERED_CODEGEN.keys())\n\n\ndef get_codegen_by_target(name):\n    \"\"\"Return a codegen entry by name.\n\n    Parameters\n    ----------\n    name : str\n        The name of the target for which the codegen info should be retrieved.\n\n    Returns\n    -------\n    dict\n        requested target codegen information\n    \"\"\"\n    try:\n        return REGISTERED_CODEGEN[name]\n    except KeyError:\n        raise TVMCException(\"Composite target %s is not defined in TVMC.\" % name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/config_options.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nmanipulate json config file to work with TVMC\n\"\"\"\nimport os\nimport json\n\nfrom tvm._ffi import libinfo\nfrom tvm.driver.tvmc import TVMCException\n\nCONFIGS_JSON_DIR = None\n\n\nclass ConfigsJsonNotFoundError(TVMCException):\n    \"\"\"Raised when the JSON configs dirtree cannot be found.\"\"\"\n\n\ndef get_configs_json_dir() -> str:\n    \"\"\"Find the 'configs' directory, containing the JSON files used to configure tvmc\n    with persistent argument settings.\n\n    Returns\n    -------\n    str :\n        The path to the 'configs' directory\n    \"\"\"\n    global CONFIGS_JSON_DIR\n    if CONFIGS_JSON_DIR is None:\n\n        # If a non-default location for the build directory is used, e.g. set via TVM_LIBRARY_PATH\n        # we need to provide the user a way to overwrite CONFIGS_JSON_DIR as well.\n        if os.environ.get(\"TVM_CONFIGS_JSON_DIR\", None):\n            user_config_dir = os.environ[\"TVM_CONFIGS_JSON_DIR\"]\n            if os.path.isdir(user_config_dir):\n                CONFIGS_JSON_DIR = user_config_dir\n                return CONFIGS_JSON_DIR\n\n        candidate_paths = []\n        candidate_paths.extend(libinfo.find_lib_path())\n        # When running from source, the configs directory will be located one directory above the\n        # native libraries, so covering that case.\n        candidate_paths.extend(\n            [os.path.abspath(os.path.join(lib_path, \"..\")) for lib_path in libinfo.find_lib_path()]\n        )\n        for path in candidate_paths:\n            configs_path = os.path.join(os.path.dirname(path), \"configs\")\n            if os.path.isdir(configs_path):\n                CONFIGS_JSON_DIR = configs_path\n                break\n\n        else:\n            raise ConfigsJsonNotFoundError()\n\n    return CONFIGS_JSON_DIR\n\n\ndef find_json_file(name, path):\n    \"\"\"search for json file given file name a path\n\n    Parameters\n    ----------\n    name: string\n        the file name need to be searched\n    path: string\n        path to search at\n\n    Returns\n    -------\n    string\n        the full path to that file\n\n    \"\"\"\n    match = \"\"\n    for root, _dirs, files in os.walk(path):\n        if name in files:\n            match = os.path.join(root, name)\n            break\n\n    return match\n\n\ndef read_and_convert_json_into_dict(config_args):\n    \"\"\"Read json configuration file and return a dictionary with all parameters\n\n    Parameters\n    ----------\n    args: argparse.Namespace\n        Arguments from command line parser holding the json file path.\n\n    Returns\n    -------\n    dictionary\n        dictionary with all the json arguments keys and values\n\n    \"\"\"\n    try:\n        if \".json\" not in config_args.config:\n            config_args.config = config_args.config.strip() + \".json\"\n        if os.path.isfile(config_args.config):\n            json_config_file = config_args.config\n        else:\n            config_dir = get_configs_json_dir()\n            json_config_file = find_json_file(config_args.config, config_dir)\n        return json.load(open(json_config_file, \"rb\"))\n\n    except FileNotFoundError:\n        raise TVMCException(\n            f\"File {config_args.config} does not exist at {config_dir} or is wrong format.\"\n        )\n\n\ndef parse_target_from_json(one_target, command_line_list):\n    \"\"\"parse the targets out of the json file struct\n\n    Parameters\n    ----------\n    one_target: dict\n        dictionary with all target's details\n    command_line_list: list\n        list to update with target parameters\n    \"\"\"\n    target_kind, *sub_type = [\n        one_target[key] if key == \"kind\" else (key, one_target[key]) for key in one_target\n    ]\n\n    internal_dict = {}\n    if sub_type:\n        sub_target_type = sub_type[0][0]\n        target_value = sub_type[0][1]\n        internal_dict[f\"target_{target_kind}_{sub_target_type}\"] = target_value\n        command_line_list.append(internal_dict)\n\n    return target_kind\n\n\ndef convert_config_json_to_cli(json_params):\n    \"\"\"convert all configuration keys & values from dictionary to cli format\n\n    Parameters\n    ----------\n    args: dictionary\n        dictionary with all configuration keys & values.\n\n    Returns\n    -------\n    int\n        list of configuration values in cli format\n\n    \"\"\"\n    command_line_list = []\n    for param_key in json_params:\n        if param_key == \"targets\":\n            target_list = [\n                parse_target_from_json(one_target, command_line_list)\n                for one_target in json_params[param_key]\n            ]\n\n            internal_dict = {}\n            internal_dict[\"target\"] = \", \".join(map(str, target_list))\n            command_line_list.append(internal_dict)\n\n        elif param_key in (\"executor\", \"runtime\"):\n            for key, value in json_params[param_key].items():\n                if key == \"kind\":\n                    kind = f\"{value}_\"\n                    new_dict_key = param_key\n                else:\n                    new_dict_key = f\"{param_key}_{kind}{key}\"\n\n                internal_dict = {}\n                internal_dict[new_dict_key.replace(\"-\", \"_\")] = value\n                command_line_list.append(internal_dict)\n\n        elif isinstance(json_params[param_key], dict):\n            internal_dict = {}\n            modify_param_key = param_key.replace(\"-\", \"_\")\n            internal_dict[modify_param_key] = []\n            for key, value in json_params[param_key].items():\n                internal_dict[modify_param_key].append(f\"{key}={value}\")\n            command_line_list.append(internal_dict)\n\n        else:\n            internal_dict = {}\n            internal_dict[param_key.replace(\"-\", \"_\")] = json_params[param_key]\n            command_line_list.append(internal_dict)\n\n    return command_line_list\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/fmtopt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nUtils to format help text for project options.\n\"\"\"\nfrom textwrap import TextWrapper\n\n\n# Maximum column length for accommodating option name and its choices.\n# Help text is placed after it in a new line.\nMAX_OPTNAME_CHOICES_TEXT_COL_LEN = 80\n\n\n# Maximum column length for accommodating help text.\n# 0 turns off formatting for the help text.\nMAX_HELP_TEXT_COL_LEN = 0\n\n\n# Justification of help text placed below option name + choices text.\nHELP_TEXT_JUST = 2\n\n\ndef format_option(option_text, help_text, default_text, required=True):\n    \"\"\"Format option name, choices, and default text into a single help text.\n\n    Parameters\n    ----------\n    options_text: str\n        String containing the option name and option's choices formatted as:\n        optname={opt0, opt1, ...}\n\n    help_text: str\n        Help text string.\n\n    default_text: str\n        Default text string.\n\n    required: bool\n        Flag that controls if a \"(required)\" text mark needs to be added to the final help text to\n        inform if the option is a required one.\n\n    Returns\n    -------\n    help_text_just: str\n       Single justified help text formatted as:\n       optname={opt0, opt1, ... }\n         HELP_TEXT. \"(required)\" | \"Defaults to 'DEFAULT'.\"\n\n    \"\"\"\n    optname, choices_text = option_text.split(\"=\", 1)\n\n    # Prepare optname + choices text chunck.\n\n    optname_len = len(optname)\n    wrapper = TextWrapper(width=MAX_OPTNAME_CHOICES_TEXT_COL_LEN - optname_len)\n    choices_lines = wrapper.wrap(choices_text)\n\n    # Set first choices line which merely appends to optname string.\n    # No justification is necessary for the first line since first\n    # line was wrapped based on MAX_OPTNAME_CHOICES_TEXT_COL_LEN - optname_len,\n    # i.e. considering optname_len, hence only append justified choices_lines[0] line.\n    choices_just_lines = [optname + \"=\" + choices_lines[0]]\n\n    # Justify the remaining lines based on first optname + '='.\n    for line in choices_lines[1:]:\n        line_len = len(line)\n        line_just = line.rjust(\n            optname_len + 1 + line_len\n        )  # add 1 to align after '{' in the line above\n        choices_just_lines.append(line_just)\n\n    choices_text_just_chunk = \"\\n\".join(choices_just_lines)\n\n    # Prepare help text chunck.\n\n    help_text = help_text[0].lower() + help_text[1:]\n    if MAX_HELP_TEXT_COL_LEN > 0:\n        wrapper = TextWrapper(width=MAX_HELP_TEXT_COL_LEN)\n        help_text_lines = wrapper.wrap(help_text)\n    else:\n        # Don't format help text.\n        help_text_lines = [help_text]\n\n    help_text_just_lines = []\n    for line in help_text_lines:\n        line_len = len(line)\n        line_just = line.rjust(HELP_TEXT_JUST + line_len)\n        help_text_just_lines.append(line_just)\n\n    help_text_just_chunk = \"\\n\".join(help_text_just_lines)\n\n    # An option might be required for one method but optional for another one.\n    # If the option is required for one method it means there is no default for\n    # it when used in that method, hence suppress default text in that case.\n    if default_text and not required:\n        help_text_just_chunk += \" \" + default_text\n\n    if required:\n        help_text_just_chunk += \" (required)\"\n\n    help_text_just = choices_text_just_chunk + \"\\n\" + help_text_just_chunk\n    return help_text_just\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/frontends.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support to parse models from different frameworks into Relay networks.\n\nFrontend classes do lazy-loading of modules on purpose, to reduce time spent on\nloading the tool.\n\"\"\"\nimport logging\nimport os\nimport sys\nimport re\nimport importlib\nfrom abc import ABC\nfrom abc import abstractmethod\nfrom typing import Optional, List, Dict\nfrom pathlib import Path\n\nimport numpy as np\n\nfrom tvm import relay\nfrom tvm import parser\nfrom tvm.driver.tvmc import TVMCException, TVMCImportError\nfrom tvm.driver.tvmc.model import TVMCModel\n\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\nclass Frontend(ABC):\n    \"\"\"Abstract class for command line driver frontend.\n\n    Provide a unified way to import models (as files), and deal\n    with any required preprocessing to create a TVM module from it.\"\"\"\n\n    @staticmethod\n    @abstractmethod\n    def name():\n        \"\"\"Frontend name\"\"\"\n\n    @staticmethod\n    @abstractmethod\n    def suffixes():\n        \"\"\"File suffixes (extensions) used by this frontend\"\"\"\n\n    @abstractmethod\n    def load(self, path, shape_dict=None, **kwargs):\n        \"\"\"Load a model from a given path.\n\n        Parameters\n        ----------\n        path: str\n            Path to a file\n        shape_dict: dict, optional\n            Mapping from input names to their shapes.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The produced relay module.\n        params : dict\n            The parameters (weights) for the relay module.\n\n        \"\"\"\n\n\ndef lazy_import(pkg_name, from_pkg_name=None, hide_stderr=False):\n    \"\"\"Lazy import a frontend package or subpackage\"\"\"\n    try:\n        return importlib.import_module(pkg_name, package=from_pkg_name)\n    except ImportError as error:\n        raise TVMCImportError(pkg_name) from error\n    finally:\n        if hide_stderr:\n            sys.stderr = stderr\n\n\nclass KerasFrontend(Frontend):\n    \"\"\"Keras frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"keras\"\n\n    @staticmethod\n    def suffixes():\n        return [\"h5\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        # pylint: disable=C0103\n        tf = lazy_import(\"tensorflow\")\n        keras = lazy_import(\"keras\", from_pkg_name=\"tensorflow\")\n\n        # tvm build currently imports keras directly instead of tensorflow.keras\n        try:\n            model = keras.models.load_model(path)\n        except ValueError as err:\n            raise TVMCException(str(err))\n\n        # There are two flavours of keras model, sequential and\n        # functional, TVM expects a functional model, so convert\n        # if required:\n        if self.is_sequential_p(model):\n            model = self.sequential_to_functional(model)\n\n        in_shapes = []\n        for layer in model._input_layers:\n            if tf.executing_eagerly():\n                in_shapes.append(tuple(dim if dim is not None else 1 for dim in layer.input.shape))\n            else:\n                in_shapes.append(\n                    tuple(dim.value if dim.value is not None else 1 for dim in layer.input.shape)\n                )\n\n        inputs = [np.random.uniform(size=shape, low=-1.0, high=1.0) for shape in in_shapes]\n        input_shapes = {name: x.shape for (name, x) in zip(model.input_names, inputs)}\n        if shape_dict is not None:\n            input_shapes.update(shape_dict)\n        kwargs.setdefault(\"layout\", \"NHWC\")\n        return relay.frontend.from_keras(model, input_shapes, **kwargs)\n\n    def is_sequential_p(self, model):\n        keras = lazy_import(\"keras\", from_pkg_name=\"tensorflow\")\n        return isinstance(model, keras.models.Sequential)\n\n    def sequential_to_functional(self, model):\n        keras = lazy_import(\"keras\", from_pkg_name=\"tensorflow\")\n        assert self.is_sequential_p(model)\n        input_layer = keras.layers.Input(batch_shape=model.layers[0].input_shape)\n        prev_layer = input_layer\n        for layer in model.layers:\n            prev_layer = layer(prev_layer)\n        model = keras.models.Model([input_layer], [prev_layer])\n        return model\n\n\nclass OnnxFrontend(Frontend):\n    \"\"\"ONNX frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"onnx\"\n\n    @staticmethod\n    def suffixes():\n        return [\"onnx\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        onnx = lazy_import(\"onnx\")\n\n        # pylint: disable=E1101\n        model = onnx.load(path)\n\n        return relay.frontend.from_onnx(model, shape=shape_dict, **kwargs)\n\n\nclass TensorflowFrontend(Frontend):\n    \"\"\"TensorFlow frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"pb\"\n\n    @staticmethod\n    def suffixes():\n        return [\"pb\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        tf = lazy_import(\"tensorflow\")\n        tf_testing = lazy_import(\"tvm.relay.testing.tf\")\n\n        with tf.io.gfile.GFile(path, \"rb\") as tf_graph:\n            content = tf_graph.read()\n\n        graph_def = tf.compat.v1.GraphDef()\n        graph_def.ParseFromString(content)\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        logger.debug(\"parse TensorFlow model and convert into Relay computation graph\")\n        return relay.frontend.from_tensorflow(graph_def, shape=shape_dict, **kwargs)\n\n\nclass TFLiteFrontend(Frontend):\n    \"\"\"TFLite frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"tflite\"\n\n    @staticmethod\n    def suffixes():\n        return [\"tflite\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        model = lazy_import(\"tflite.Model\")\n\n        with open(path, \"rb\") as tf_graph:\n            content = tf_graph.read()\n\n        # tflite.Model.Model is tflite.Model in 1.14 and 2.1.0\n        try:\n            tflite_model = model.Model.GetRootAsModel(content, 0)\n        except AttributeError:\n            tflite_model = model.GetRootAsModel(content, 0)\n\n        try:\n            version = tflite_model.Version()\n            logger.debug(\"tflite version %s\", version)\n        except Exception:\n            raise TVMCException(\"input file not tflite\")\n\n        if version != 3:\n            raise TVMCException(\"input file not tflite version 3\")\n\n        logger.debug(\"parse TFLite model and convert into Relay computation graph\")\n        mod, params = relay.frontend.from_tflite(tflite_model, shape_dict=shape_dict, **kwargs)\n        return mod, params\n\n\nclass PyTorchFrontend(Frontend):\n    \"\"\"PyTorch frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"pytorch\"\n\n    @staticmethod\n    def suffixes():\n        # Torch Script is a zip file, but can be named pth\n        return [\"pth\", \"zip\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        torch = lazy_import(\"torch\")\n\n        if shape_dict is None:\n            raise TVMCException(\"--input-shapes must be specified for %s\" % self.name())\n\n        traced_model = torch.jit.load(path)\n        traced_model.eval()  # Switch to inference mode\n\n        # Convert shape dictionary to list for Pytorch frontend compatibility\n        input_shapes = list(shape_dict.items())\n\n        logger.debug(\"parse Torch model and convert into Relay computation graph\")\n        return relay.frontend.from_pytorch(\n            traced_model, input_shapes, keep_quantized_weight=True, **kwargs\n        )\n\n\nclass PaddleFrontend(Frontend):\n    \"\"\"PaddlePaddle frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"paddle\"\n\n    @staticmethod\n    def suffixes():\n        return [\"pdmodel\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        # pylint: disable=C0415\n        import paddle\n\n        paddle.enable_static()\n        paddle.disable_signal_handler()\n\n        if not os.path.exists(path):\n            raise TVMCException(\"File {} is not exist.\".format(path))\n        if not path.endswith(\".pdmodel\"):\n            raise TVMCException(\"Path of model file should be endwith suffixes '.pdmodel'.\")\n        prefix = \"\".join(path.strip().split(\".\")[:-1])\n        params_file_path = prefix + \".pdiparams\"\n        if not os.path.exists(params_file_path):\n            raise TVMCException(\"File {} is not exist.\".format(params_file_path))\n\n        # pylint: disable=E1101\n        exe = paddle.static.Executor(paddle.CPUPlace())\n        prog, _, _ = paddle.static.load_inference_model(prefix, exe)\n\n        return relay.frontend.from_paddle(prog, shape_dict=shape_dict, **kwargs)\n\n\nclass RelayFrontend(Frontend):\n    \"\"\"Relay frontend for TVMC\"\"\"\n\n    @staticmethod\n    def name():\n        return \"relay\"\n\n    @staticmethod\n    def suffixes():\n        return [\"relay\"]\n\n    def load(self, path, shape_dict=None, **kwargs):\n        with open(path, \"r\", encoding=\"utf-8\") as relay_text:\n            text = relay_text.read()\n        if shape_dict is None:\n            logger.warning(\n                \"Specify --input-shapes to ensure that model inputs \"\n                \"will not be considered as constants.\"\n            )\n\n        def _validate_text(text):\n            \"\"\"Check the provided file contents.\n            The relay.txt artifact contained in the MLF is missing the version header and\n            the metadata which is required to use meta[relay.Constant].\"\"\"\n\n            if re.compile(r\".*\\#\\[version\\.*\").match(text) is None:\n                raise TVMCException(\n                    \"The relay model does not include the required version information.\"\n                )\n            if re.compile(r\".*meta\\[.+\\].*\", re.DOTALL).match(text):\n                if \"#[metadata]\" not in text:\n                    raise TVMCException(\n                        \"The relay model does not include the required #[metadata] section. \"\n                        \"Use ir_mod.astext(show_meta_data=True) to export compatible code.\"\n                    )\n\n        _validate_text(text)\n\n        ir_mod = parser.fromtext(text)\n\n        if shape_dict:\n            input_names = shape_dict.keys()\n        else:\n            input_names = []\n\n        def _gen_params(ir_mod, skip_names=None):\n            \"\"\"Populate the all the params in the mode with ones.\"\"\"\n            main_func = ir_mod[\"main\"]\n            shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n            type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n            params = {}\n            for name, shape in shape_dict.items():\n                if skip_names and name in skip_names:\n                    continue\n\n                if \"int\" in type_dict[name]:\n                    data = np.random.randint(128, size=shape, dtype=type_dict[name])\n                else:\n                    data = np.random.uniform(-1, 1, size=shape).astype(type_dict[name])\n                params[name] = data\n            return params\n\n        params = _gen_params(ir_mod, skip_names=input_names)\n\n        return ir_mod, params\n\n\nALL_FRONTENDS = [\n    KerasFrontend,\n    OnnxFrontend,\n    TensorflowFrontend,\n    TFLiteFrontend,\n    PyTorchFrontend,\n    PaddleFrontend,\n    RelayFrontend,\n]\n\n\ndef get_frontend_names():\n    \"\"\"Return the names of all supported frontends\n\n    Returns\n    -------\n    list : list of str\n        A list of frontend names as strings\n\n    \"\"\"\n    return [frontend.name() for frontend in ALL_FRONTENDS]\n\n\ndef get_frontend_by_name(name: str):\n    \"\"\"\n    This function will try to get a frontend instance, based\n    on the name provided.\n\n    Parameters\n    ----------\n    name : str\n        the name of a given frontend\n\n    Returns\n    -------\n    frontend : tvm.driver.tvmc.Frontend\n        An instance of the frontend that matches with\n        the file extension provided in `path`.\n\n    \"\"\"\n\n    for frontend in ALL_FRONTENDS:\n        if name == frontend.name():\n            return frontend()\n\n    raise TVMCException(\n        \"unrecognized frontend '{0}'. Choose from: {1}\".format(name, get_frontend_names())\n    )\n\n\ndef guess_frontend(path: str):\n    \"\"\"\n    This function will try to imply which framework is being used,\n    based on the extension of the file provided in the path parameter.\n\n    Parameters\n    ----------\n    path : str\n        The path to the model file.\n\n    Returns\n    -------\n    frontend : tvm.driver.tvmc.Frontend\n        An instance of the frontend that matches with\n        the file extension provided in `path`.\n\n    \"\"\"\n\n    suffix = Path(path).suffix.lower()\n    if suffix.startswith(\".\"):\n        suffix = suffix[1:]\n\n    for frontend in ALL_FRONTENDS:\n        if suffix in frontend.suffixes():\n            return frontend()\n\n    raise TVMCException(\"failed to infer the model format. Please specify --model-format\")\n\n\ndef load_model(\n    path: str,\n    model_format: Optional[str] = None,\n    shape_dict: Optional[Dict[str, List[int]]] = None,\n    **kwargs,\n):\n    \"\"\"Load a model from a supported framework and convert it\n    into an equivalent relay representation.\n\n    Parameters\n    ----------\n    path : str\n        The path to the model file.\n    model_format : str, optional\n        The underlying framework used to create the model.\n        If not specified, this will be inferred from the file type.\n    shape_dict : dict, optional\n        Mapping from input names to their shapes.\n\n    Returns\n    -------\n    tvmc_model : TVMCModel\n        The produced model package.\n\n    \"\"\"\n\n    if model_format is not None:\n        frontend = get_frontend_by_name(model_format)\n    else:\n        frontend = guess_frontend(path)\n\n    mod, params = frontend.load(path, shape_dict, **kwargs)\n\n    return TVMCModel(mod, params)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/main.py",
        "content": "#!/usr/bin/env python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC - TVM driver command-line interface\n\"\"\"\nimport argparse\nimport logging\nimport sys\n\nimport tvm\n\nfrom tvm.driver.tvmc import TVMCException, TVMCImportError\nfrom tvm.driver.tvmc.config_options import (\n    read_and_convert_json_into_dict,\n    convert_config_json_to_cli,\n)\n\nREGISTERED_PARSER = []\n\n\ndef register_parser(make_subparser):\n    \"\"\"\n    Utility function to register a subparser for tvmc.\n\n    Functions decorated with `tvm.driver.tvmc.main.register_parser` will be invoked\n    with a parameter containing the subparser instance they need to add itself to,\n    as a parser.\n\n    Example\n    -------\n\n        @register_parser\n        def _example_parser(main_subparser):\n            subparser = main_subparser.add_parser('example', help='...')\n            ...\n\n    \"\"\"\n    REGISTERED_PARSER.append(make_subparser)\n    return make_subparser\n\n\ndef _main(argv):\n    \"\"\"TVM command line interface.\"\"\"\n\n    parser = argparse.ArgumentParser(\n        prog=\"tvmc\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"TVM compiler driver\",\n        epilog=__doc__,\n        # Help action will be added later, after all subparsers are created,\n        # so it doesn't interfere with the creation of the dynamic subparsers.\n        add_help=False,\n    )\n\n    parser.add_argument(\"--config\", default=\"default\", help=\"configuration json file\")\n    config_arg, argv = parser.parse_known_args(argv)\n\n    json_param_dict = read_and_convert_json_into_dict(config_arg)\n    json_config_values = convert_config_json_to_cli(json_param_dict)\n\n    parser.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0, help=\"increase verbosity\")\n    parser.add_argument(\"--version\", action=\"store_true\", help=\"print the version and exit\")\n\n    subparser = parser.add_subparsers(title=\"commands\")\n    for make_subparser in REGISTERED_PARSER:\n        make_subparser(subparser, parser, json_config_values)\n\n    # Finally, add help for the main parser.\n    parser.add_argument(\"-h\", \"--help\", action=\"help\", help=\"show this help message and exit.\")\n\n    args = parser.parse_args(argv)\n    if args.verbose > 4:\n        args.verbose = 4\n\n    logging.getLogger(\"TVMC\").setLevel(40 - args.verbose * 10)\n\n    if args.version:\n        sys.stdout.write(\"%s\\n\" % tvm.__version__)\n        return 0\n\n    if not hasattr(args, \"func\"):\n        # In case no valid subcommand is provided, show usage and exit\n        parser.print_help(sys.stderr)\n        return 1\n\n    try:\n        return args.func(args)\n    except TVMCImportError as err:\n        sys.stderr.write(\n            f'Package \"{err}\" is not installed. ' f'Hint: \"pip install tlcpack[tvmc]\".'\n        )\n        return 5\n    except TVMCException as err:\n        sys.stderr.write(\"Error: %s\\n\" % err)\n        return 4\n\n\ndef main():\n    sys.exit(_main(sys.argv[1:]))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/micro.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support for micro targets (microTVM).\n\"\"\"\nimport argparse\nimport os\nfrom pathlib import Path\nimport shutil\nimport sys\n\nfrom . import TVMCException\nfrom .main import register_parser\nfrom .arguments import TVMCSuppressedArgumentParser\nfrom .project import (\n    get_project_options,\n    get_and_check_options,\n    get_project_dir,\n)\n\ntry:\n    import tvm.micro.project as project\n    from tvm.micro import get_microtvm_template_projects\n    from tvm.micro.build import MicroTVMTemplateProjectNotFoundError\n    from tvm.micro.project_api.server import ServerError\n    from tvm.micro.project_api.client import ProjectAPIServerNotFoundError\n\n    SUPPORT_MICRO = True\nexcept (ImportError, NameError):\n    SUPPORT_MICRO = False\n\n\n@register_parser\ndef add_micro_parser(subparsers, main_parser, json_params):\n    \"\"\"Includes parser for 'micro' context and associated subcommands:\n    create-project (create), build, and flash.\n    \"\"\"\n\n    if SUPPORT_MICRO is False:\n        # Don't create 'tvmc micro' parser.\n        return\n\n    # Probe available default platform templates.\n    templates = {}\n    for p in (\"zephyr\", \"arduino\"):\n        try:\n            templates[p] = get_microtvm_template_projects(p)\n        except MicroTVMTemplateProjectNotFoundError:\n            pass\n\n    micro = subparsers.add_parser(\"micro\", help=\"select micro context.\")\n    micro.set_defaults(func=drive_micro)\n\n    micro_parser = micro.add_subparsers(title=\"subcommands\")\n    # Selecting a subcommand under 'micro' is mandatory\n    micro_parser.required = True\n    micro_parser.dest = \"subcommand\"\n\n    # 'create_project' subcommand\n    create_project_parser = micro_parser.add_parser(\n        \"create-project\",\n        aliases=[\"create\"],\n        help=\"create a project template of a given type or given a template dir.\",\n    )\n    create_project_parser.set_defaults(subcommand_handler=create_project_handler)\n    create_project_parser.add_argument(\n        \"project_dir\",\n        help=\"project dir where the new project based on the template dir will be created.\",\n    )\n    create_project_parser.add_argument(\"MLF\", help=\"Model Library Format (MLF) .tar archive.\")\n    create_project_parser.add_argument(\n        \"-f\",\n        \"--force\",\n        action=\"store_true\",\n        help=\"force project creating even if the specified project directory already exists.\",\n    )\n\n    # 'build' subcommand\n    build_parser = micro_parser.add_parser(\n        \"build\",\n        help=\"build a project dir, generally creating an image to be flashed, e.g. zephyr.elf.\",\n    )\n    build_parser.set_defaults(subcommand_handler=build_handler)\n    build_parser.add_argument(\"project_dir\", help=\"project dir to build.\")\n    build_parser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force rebuild.\")\n\n    # 'flash' subcommand\n    flash_parser = micro_parser.add_parser(\n        \"flash\", help=\"flash the built image on a given micro target.\"\n    )\n    flash_parser.set_defaults(subcommand_handler=flash_handler)\n    flash_parser.add_argument(\"project_dir\", help=\"project dir where the built image is.\")\n\n    # For each platform add arguments detected automatically using Project API info query.\n\n    # Create subparsers for the platforms under 'create-project', 'build', and 'flash' subcommands.\n    help_msg = (\n        \"you must select a platform from the list. You can pass '-h' for a selected \"\n        \"platform to list its options.\"\n    )\n    create_project_platforms_parser = create_project_parser.add_subparsers(\n        title=\"platforms\", help=help_msg, dest=\"platform\"\n    )\n    build_platforms_parser = build_parser.add_subparsers(\n        title=\"platforms\", help=help_msg, dest=\"platform\"\n    )\n    flash_platforms_parser = flash_parser.add_subparsers(\n        title=\"platforms\", help=help_msg, dest=\"platform\"\n    )\n\n    subcmds = {\n        # API method name    Parser associated to method      Handler func to call after parsing\n        \"generate_project\": [create_project_platforms_parser, create_project_handler],\n        \"build\": [build_platforms_parser, build_handler],\n        \"flash\": [flash_platforms_parser, flash_handler],\n    }\n\n    # Helper to add a platform parser to a subcmd parser.\n    def _add_parser(parser, platform):\n        platform_name = platform[0].upper() + platform[1:] + \" platform\"\n        platform_parser = parser.add_parser(\n            platform, add_help=False, help=f\"select {platform_name}.\"\n        )\n        platform_parser.set_defaults(platform=platform)\n        return platform_parser\n\n    parser_by_subcmd = {}\n    for subcmd, subcmd_parser_handler in subcmds.items():\n        subcmd_parser = subcmd_parser_handler[0]\n        subcmd_parser.required = True  # Selecting a platform or template is mandatory\n        parser_by_platform = {}\n        for platform in templates:\n            new_parser = _add_parser(subcmd_parser, platform)\n            parser_by_platform[platform] = new_parser\n\n        # Besides adding the parsers for each default platform (like Zephyr and Arduino), add a\n        # parser for 'template' to deal with adhoc projects/platforms.\n        new_parser = subcmd_parser.add_parser(\n            \"template\", add_help=False, help=\"select an adhoc template.\"\n        )\n        new_parser.add_argument(\n            \"--template-dir\", required=True, help=\"Project API template directory.\"\n        )\n        new_parser.set_defaults(platform=\"template\")\n        parser_by_platform[\"template\"] = new_parser\n\n        parser_by_subcmd[subcmd] = parser_by_platform\n\n    disposable_parser = TVMCSuppressedArgumentParser(main_parser)\n    try:\n        known_args, _ = disposable_parser.parse_known_args()\n    except TVMCException:\n        return\n\n    try:\n        subcmd = known_args.subcommand\n        platform = known_args.platform\n    except AttributeError:\n        # No subcommand or platform, hence no need to augment the parser for micro targets.\n        return\n\n    # Augment parser with project options.\n\n    if platform == \"template\":\n        # adhoc template\n        template_dir = str(Path(known_args.template_dir).resolve())\n    else:\n        # default template\n        template_dir = templates[platform]\n\n    try:\n        template = project.TemplateProject.from_directory(template_dir)\n    except ProjectAPIServerNotFoundError:\n        sys.exit(f\"Error: Project API server not found in {template_dir}!\")\n\n    template_info = template.info()\n\n    options_by_method = get_project_options(template_info)\n\n    # TODO(gromero): refactor to remove this map.\n    subcmd_to_method = {\n        \"create-project\": \"generate_project\",\n        \"create\": \"generate_project\",\n        \"build\": \"build\",\n        \"flash\": \"flash\",\n    }\n\n    method = subcmd_to_method[subcmd]\n    parser_by_subcmd_n_platform = parser_by_subcmd[method][platform]\n    _, handler = subcmds[method]\n\n    parser_by_subcmd_n_platform.formatter_class = (\n        # Set raw help text so help_text format works\n        argparse.RawTextHelpFormatter\n    )\n    parser_by_subcmd_n_platform.set_defaults(\n        subcommand_handler=handler,\n        valid_options=options_by_method[method],\n        template_dir=template_dir,\n    )\n\n    required = any([opt[\"required\"] for opt in options_by_method[method]])\n    nargs = \"+\" if required else \"*\"\n\n    help_text_by_option = [opt[\"help_text\"] for opt in options_by_method[method]]\n    help_text = \"\\n\\n\".join(help_text_by_option) + \"\\n\\n\"\n\n    parser_by_subcmd_n_platform.add_argument(\n        \"--project-option\", required=required, metavar=\"OPTION=VALUE\", nargs=nargs, help=help_text\n    )\n\n    parser_by_subcmd_n_platform.add_argument(\n        \"-h\",\n        \"--help\",\n        \"--list-options\",\n        action=\"help\",\n        help=\"show this help message which includes platform-specific options and exit.\",\n    )\n\n    for one_entry in json_params:\n        micro.set_defaults(**one_entry)\n\n\ndef drive_micro(args):\n    # Call proper handler based on subcommand parsed.\n    args.subcommand_handler(args)\n\n\ndef create_project_handler(args):\n    \"\"\"Creates a new project dir.\"\"\"\n    project_dir = get_project_dir(args.project_dir)\n\n    if os.path.exists(project_dir):\n        if args.force:\n            shutil.rmtree(project_dir)\n        else:\n            raise TVMCException(\n                \"The specified project dir already exists. \"\n                \"To force overwriting it use '-f' or '--force'.\"\n            )\n\n    template_dir = str(Path(args.template_dir).resolve())\n    if not os.path.exists(template_dir):\n        raise TVMCException(f\"Template directory {template_dir} does not exist!\")\n\n    mlf_path = str(Path(args.MLF).resolve())\n    if not os.path.exists(mlf_path):\n        raise TVMCException(f\"MLF file {mlf_path} does not exist!\")\n\n    options = get_and_check_options(args.project_option, args.valid_options)\n\n    try:\n        project.generate_project_from_mlf(template_dir, project_dir, mlf_path, options)\n    except ServerError as error:\n        print(\"The following error occurred on the Project API server side: \\n\", error)\n        sys.exit(1)\n\n\ndef build_handler(args):\n    \"\"\"Builds a firmware image given a project dir.\"\"\"\n    project_dir = get_project_dir(args.project_dir)\n\n    if not os.path.exists(project_dir):\n        raise TVMCException(f\"{project_dir} doesn't exist.\")\n\n    if os.path.exists(project_dir + \"/build\"):\n        if args.force:\n            shutil.rmtree(project_dir + \"/build\")\n        else:\n            raise TVMCException(\n                f\"There is already a build in {project_dir}. \"\n                \"To force rebuild it use '-f' or '--force'.\"\n            )\n\n    options = get_and_check_options(args.project_option, args.valid_options)\n\n    try:\n        prj = project.GeneratedProject.from_directory(project_dir, options=options)\n        prj.build()\n    except ServerError as error:\n        print(\"The following error occurred on the Project API server side: \", error)\n        sys.exit(1)\n\n\ndef flash_handler(args):\n    \"\"\"Flashes a firmware image to a target device given a project dir.\"\"\"\n\n    project_dir = get_project_dir(args.project_dir)\n\n    if not os.path.exists(project_dir + \"/build\"):\n        raise TVMCException(f\"Could not find a build in {project_dir}\")\n\n    options = get_and_check_options(args.project_option, args.valid_options)\n\n    try:\n        prj = project.GeneratedProject.from_directory(project_dir, options=options)\n        prj.flash()\n    except ServerError as error:\n        print(\"The following error occurred on the Project API server side: \", error)\n        sys.exit(1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file contains the definition of a set of classes that wrap the outputs\nof TVMC functions to create a simpler and more intuitive API.\n\nThere is one class for each required stage of a TVM workflow.\nThe TVMCModel represents the result of importing a model into TVM, it\ncontains the precompiled graph definition and parameters that define\nwhat the model does.\n\nCompiling a TVMCModel produces a TVMCPackage, which contains the generated\nartifacts that allow the model to be run on the target hardware.\n\nRunning a TVMCPackage produces a TVMCResult, which contains the outputs of\nthe model and the measured runtime.\n\nExamples\n--------\nThe following code shows a full lifecycle for a model using tvmc, first the\nmodel is imported from an exterior framework, in this case onnx, then it\nis tuned to find the best schedules on CPU, then compiled into a TVMCPackage,\nand finally run.\n\n.. code-block:: python\n    tvmc_model = tvmc.load(\"my_model.onnx\")\n    tuning_records = tvmc.tune(tvmc_model, target=\"llvm\")\n    tvmc_package = tvmc.compile(tvmc_model, target=\"llvm\", tuning_records=tuning_records)\n    result = tvmc.run(tvmc_package, device=\"cpu\")\n    print(result)\n\"\"\"\nimport os\nimport tarfile\nimport json\nfrom typing import Optional, Union, Dict, Callable, TextIO\nfrom pathlib import Path\nimport numpy as np\n\nimport tvm\nimport tvm.contrib.cc\nfrom tvm import relay\nfrom tvm.contrib import utils\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.relay.backend.executor_factory import GraphExecutorFactoryModule\nfrom tvm.runtime.module import BenchmarkResult\nfrom tvm.runtime.vm import Executable\n\n\ntry:\n    from tvm.micro import export_model_library_format\nexcept ImportError:\n    export_model_library_format = None\n\n\nclass TVMCModel(object):\n    \"\"\"Initialize a TVMC model from a relay model definition or a saved file.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule, optional\n        The relay module corresponding to this model.\n    params : dict, optional\n        A parameter dictionary for the model.\n    model_path: str, optional\n        An alternative way to load a TVMCModel, the path to a previously\n        saved model.\n    \"\"\"\n\n    def __init__(\n        self,\n        mod: Optional[tvm.IRModule] = None,\n        params: Optional[Dict[str, tvm.nd.NDArray]] = None,\n        model_path: Optional[str] = None,\n    ):\n        if (mod is None or params is None) and (model_path is None):\n            raise TVMCException(\n                \"Either mod and params must be provided \"\n                \"or a path to a previously saved TVMCModel\"\n            )\n        self._tmp_dir = utils.tempdir()\n        if model_path is not None:\n            self.load(model_path)\n        else:\n            self.mod = mod\n            self.params = params if params else {}\n\n    def save(self, model_path: str):\n        \"\"\"Save the TVMCModel to disk.\n\n        Note that this saves the graph representation,\n        the parameters, and the tuning records if applicable. It will not save any\n        compiled artifacts.\n\n        Parameters\n        ----------\n        model_path : str\n            A full path to save this TVMCModel to including the output file name.\n            The file will be saved as a tar file so using a \".tar\" extension is advised.\n        \"\"\"\n        temp = self._tmp_dir\n\n        # Save relay graph\n        relay_name = \"model.json\"\n        relay_path = temp.relpath(relay_name)\n        with open(relay_path, \"w\") as relay_file:\n            relay_file.write(tvm.ir.save_json(self.mod))\n\n        # Save params\n        params_name = \"model.params\"\n        params_path = temp.relpath(params_name)\n        with open(params_path, \"wb\") as params_file:\n            params_file.write(relay.save_param_dict(self.params))\n\n        # Create a tar file.\n        with tarfile.open(model_path, \"w\") as tar:\n            tar.add(relay_path, relay_name)\n            tar.add(params_path, params_name)\n            # If default tuning records exist, save them as well.\n            if os.path.exists(self.default_tuning_records_path()):\n                tar.add(self.default_tuning_records_path(), \"tuning_records\")\n            # Also save the compiled package if it can be found.\n            if os.path.exists(self.default_package_path()):\n                tar.add(self.default_package_path(), \"model_package.tar\")\n\n    def load(self, model_path: str):\n        \"\"\"Load a TVMCModel from disk.\n\n        Parameters\n        ----------\n        model_path : str\n            A path to load the TVMCModel from.\n        \"\"\"\n        temp = self._tmp_dir\n        t = tarfile.open(model_path)\n        t.extractall(temp.relpath(\".\"))\n\n        # Load relay IR.\n        relay_path = temp.relpath(\"model.json\")\n        with open(relay_path, \"r\") as relay_file:\n            self.mod = tvm.ir.load_json(relay_file.read())\n\n        # Load parameter dictionary.\n        params_path = temp.relpath(\"model.params\")\n        with open(params_path, \"rb\") as params_file:\n            self.params = relay.load_param_dict(params_file.read())\n\n    def default_tuning_records_path(self):\n        \"\"\"Get a full path for storing tuning records in this model's temporary direcotry\n\n        Note that when this path is used, the tuning records will be saved and loaded\n        when calling `save` and `load`.\n\n        Returns\n        -------\n        records_path: str\n            A path to the default location for tuning records.\n        \"\"\"\n        return self._tmp_dir.relpath(\"tuning_records\")\n\n    def default_package_path(self):\n        \"\"\"Get a full path for storing a compiled package in this model's temporary direcotry\n\n        Note that when this path is used, the package will be saved and loaded\n        when calling `save` and `load`.\n\n        Returns\n        -------\n        records_path: str\n            A path to the default location for tuning records.\n        \"\"\"\n        return self._tmp_dir.relpath(\"model_package.tar\")\n\n    def export_vm_format(\n        self,\n        vm_exec: Executable,\n        package_path: Optional[str] = None,\n        lib_format: str = \"so\",\n    ):\n        \"\"\"Save this TVMCModel compiled via vm to file.\n        Parameters\n        ----------\n        vm_exec : vm.Executable\n            The VM Executable containing compiled the compiled artifacts needed to run this model.\n        package_path : str, None\n            Where the model should be saved. Note that it will be packaged as a .tar file.\n            If not provided, the package will be saved to a generically named file in tmp.\n        lib_format : str\n            How to export the modules function library. Must be one of \"so\" or \"tar\".\n\n        Returns\n        -------\n        package_path : str\n            The path that the package was saved to.\n        \"\"\"\n        lib_name = \"lib.\" + lib_format\n        temp = self._tmp_dir\n        if package_path is None:\n            package_path = self.default_package_path()\n\n        path_lib = temp.relpath(lib_name)\n        vm_exec.mod.export_library(path_lib)\n        self.lib_path = path_lib\n        # Package up all the temp files into a tar file.\n        with tarfile.open(package_path, \"w\") as tar:\n            tar.add(path_lib, lib_name)\n\n        return package_path\n\n    def export_classic_format(\n        self,\n        executor_factory: GraphExecutorFactoryModule,\n        package_path: Optional[str] = None,\n        cross: Optional[Union[str, Callable]] = None,\n        cross_options: Optional[str] = None,\n        lib_format: str = \"so\",\n    ):\n        \"\"\"Save this TVMCModel to file.\n        Parameters\n        ----------\n        executor_factory : GraphExecutorFactoryModule\n            The factory containing compiled the compiled artifacts needed to run this model.\n        package_path : str, None\n            Where the model should be saved. Note that it will be packaged as a .tar file.\n            If not provided, the package will be saved to a generically named file in tmp.\n        cross : str or callable object, optional\n            Function that performs the actual compilation.\n        cross_options : str, optional\n            Command line options to be passed to the cross compiler.\n        lib_format : str\n            How to export the modules function library. Must be one of \"so\" or \"tar\".\n\n        Returns\n        -------\n        package_path : str\n            The path that the package was saved to.\n        \"\"\"\n        lib_name = \"mod.\" + lib_format\n        graph_name = \"mod.json\"\n        param_name = \"mod.params\"\n\n        temp = self._tmp_dir\n        if package_path is None:\n            package_path = self.default_package_path()\n        path_lib = temp.relpath(lib_name)\n\n        if not cross:\n            executor_factory.get_lib().export_library(path_lib)\n        else:\n            if not cross_options:\n                executor_factory.get_lib().export_library(\n                    path_lib, tvm.contrib.cc.cross_compiler(cross)\n                )\n            else:\n                executor_factory.get_lib().export_library(\n                    path_lib, tvm.contrib.cc.cross_compiler(cross, options=cross_options.split(\" \"))\n                )\n        self.lib_path = path_lib\n\n        with open(temp.relpath(graph_name), \"w\") as graph_file:\n            graph_file.write(executor_factory.get_graph_json())\n\n        with open(temp.relpath(param_name), \"wb\") as params_file:\n            params_file.write(relay.save_param_dict(executor_factory.get_params()))\n\n        # Package up all the temp files into a tar file.\n        with tarfile.open(package_path, \"w\") as tar:\n            tar.add(path_lib, lib_name)\n            tar.add(temp.relpath(graph_name), graph_name)\n            tar.add(temp.relpath(param_name), param_name)\n\n        return package_path\n\n    def export_package(\n        self,\n        executor_factory: Union[GraphExecutorFactoryModule, Executable],\n        package_path: Optional[str] = None,\n        cross: Optional[Union[str, Callable]] = None,\n        cross_options: Optional[str] = None,\n        output_format: str = \"so\",\n    ):\n        \"\"\"Save this TVMCModel to file.\n        Parameters\n        ----------\n        executor_factory : GraphExecutorFactoryModule\n            The factory containing the compiled artifacts needed to run this model.\n        package_path : str, None\n            Where the model should be saved. Note that it will be packaged as a .tar file.\n            If not provided, the package will be saved to a generically named file in tmp.\n        cross : str or callable object, optional\n            Function that performs the actual compilation.\n        cross_options : str, optional\n            Command line options to be passed to the cross compiler.\n        output_format : str\n            How to save the modules function library. Must be one of \"so\" and \"tar\" to save\n            using the classic format or \"mlf\" to save using the Model Library Format.\n\n        Returns\n        -------\n        package_path : str\n            The path that the package was saved to.\n        \"\"\"\n        if output_format not in [\"so\", \"tar\", \"mlf\"]:\n            raise TVMCException(\"Only 'so', 'tar', and 'mlf' output formats are supported.\")\n\n        if output_format == \"mlf\" and cross:\n            raise TVMCException(\"Specifying the MLF output and a cross compiler is not supported.\")\n\n        if isinstance(executor_factory, Executable):\n            package_path = self.export_vm_format(executor_factory, package_path, output_format)\n        elif output_format in [\"so\", \"tar\"]:\n            package_path = self.export_classic_format(\n                executor_factory, package_path, cross, cross_options, output_format\n            )\n        elif output_format == \"mlf\":\n            if export_model_library_format:\n                package_path = export_model_library_format(executor_factory, package_path)\n            else:\n                raise Exception(\"micro tvm is not enabled. Set USE_MICRO to ON in config.cmake\")\n\n        return package_path\n\n    def summary(self, file: TextIO = None):\n        \"\"\"Print the IR corressponding to this model.\n\n        Arguments\n        ---------\n        file: Writable, optional\n            If specified, the summary will be written to this file.\n        \"\"\"\n        print(self.mod, file=file)\n\n\nclass TVMCPackage(object):\n    \"\"\"Load a saved TVMCPackage from disk.\n\n    Parameters\n    ----------\n    package_path : str\n        The path to the saved TVMCPackage that will be loaded.\n\n    project_dir : Path, str\n        If given and loading a MLF file, the path to the project directory that contains the file.\n\n    use_vm : bool\n        Whether the graph module was compiled with vm or not.\n    \"\"\"\n\n    def __init__(\n        self,\n        package_path: str,\n        project_dir: Optional[Union[Path, str]] = None,\n    ):\n        self._tmp_dir = utils.tempdir()\n        self.package_path = package_path\n        self.import_package(self.package_path)\n\n        if project_dir and self.type != \"mlf\":\n            raise TVMCException(\"Setting 'project_dir' is only allowed when importing a MLF.!\")\n        self.project_dir = project_dir\n\n    def import_package(self, package_path: str):\n        \"\"\"Load a TVMCPackage from a previously exported TVMCModel.\n\n        Parameters\n        ----------\n        package_path : str\n            The path to the saved TVMCPackage.\n        \"\"\"\n        temp = self._tmp_dir\n        t = tarfile.open(package_path)\n        t.extractall(temp.relpath(\".\"))\n\n        if os.path.exists(temp.relpath(\"metadata.json\")):\n            # Model Library Format (MLF)\n            self.lib_name = None\n            self.lib_path = None\n            with open(temp.relpath(\"metadata.json\")) as metadata_json:\n                metadata = json.load(metadata_json)\n\n            all_module_names = []\n            for name in metadata[\"modules\"].keys():\n                all_module_names.append(name)\n            assert len(all_module_names) == 1, \"Multiple modules in MLF is not supported.\"\n\n            module_name = all_module_names[0]\n            module_metdata = metadata[\"modules\"][module_name]\n            has_graph_executor = \"graph\" in module_metdata[\"executors\"]\n            graph = (\n                temp.relpath(f\"executor-config/graph/{module_name}.graph\")\n                if has_graph_executor\n                else None\n            )\n            params = temp.relpath(f\"parameters/{module_name}.params\")\n\n            self.type = \"mlf\"\n        else:\n            # Classic format\n            classic_lib_name_so = \"mod.so\"\n            classic_lib_name_tar = \"mod.tar\"\n\n            # VM format\n            vm_lib_name_so = \"lib.so\"\n            vm_lib_name_tar = \"lib.tar\"\n\n            if os.path.exists(temp.relpath(classic_lib_name_so)):\n                self.lib_name = classic_lib_name_so\n                self.type = \"classic\"\n            elif os.path.exists(temp.relpath(classic_lib_name_tar)):\n                self.lib_name = classic_lib_name_tar\n                self.type = \"classic\"\n            elif os.path.exists(temp.relpath(vm_lib_name_so)):\n                self.lib_name = vm_lib_name_so\n                self.type = \"vm\"\n            elif os.path.exists(temp.relpath(vm_lib_name_tar)):\n                self.lib_name = vm_lib_name_tar\n                self.type = \"vm\"\n            else:\n                raise TVMCException(\"Couldn't find exported library in the package.\")\n\n            self.lib_path = temp.relpath(self.lib_name)\n\n            graph, params = None, None\n            if self.type == \"classic\":\n                graph = temp.relpath(\"mod.json\")\n                params = temp.relpath(\"mod.params\")\n\n        if params is not None:\n            with open(params, \"rb\") as param_file:\n                self.params = bytearray(param_file.read())\n        else:\n            self.params = None\n\n        if graph is not None:\n            with open(graph) as graph_file:\n                self.graph = graph_file.read()\n        else:\n            self.graph = None\n\n\nclass TVMCResult(object):\n    \"\"\"A class that stores the results of tvmc.run and provides helper utilities.\"\"\"\n\n    def __init__(self, outputs: Dict[str, np.ndarray], times: BenchmarkResult):\n        \"\"\"Create a convenience wrapper around the output of tvmc.run\n\n        Parameters\n        ----------\n        outputs : dict\n            Outputs dictionary mapping the name of the output to its numpy value.\n        times : BenchmarkResult\n            The execution times measured by the time evaluator in seconds to produce outputs.\n        \"\"\"\n        self.outputs = outputs\n        self.times = times\n\n    def format_times(self):\n        \"\"\"Format the mean, max, min and std of the execution times.\n\n        This has the effect of producing a small table that looks like:\n        .. code-block::\n            Execution time summary:\n            mean (ms)  median (ms) max (ms)    min (ms)    std (ms)\n            0.14310      0.14310   0.16161     0.12933    0.01004\n\n        Returns\n        -------\n        str\n            A formatted string containing the statistics.\n        \"\"\"\n        return str(self.times)\n\n    def get_output(self, name: str):\n        \"\"\"A helper function to grab one of the outputs by name.\n\n        Parameters\n        ----------\n        name : str\n            The name of the output to return\n\n        Returns\n        -------\n        output : np.ndarray\n            The output corresponding to name.\n        \"\"\"\n        return self.outputs[name]\n\n    def save(self, output_path: str):\n        \"\"\"Save the numpy outputs to disk as a .npz file.\n\n        Parameters\n        ----------\n        output_path : str\n            The path to save the numpy results to.\n        \"\"\"\n        np.savez(output_path, **self.outputs)\n\n    def __str__(self):\n        stat_table = self.format_times()\n        output_keys = f\"Output Names:\\n {list(self.outputs.keys())}\"\n        return stat_table + \"\\n\" + output_keys\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/pass_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC PassContext Interface\n\"\"\"\n\nimport importlib\n\nimport tvm\nfrom tvm.driver.tvmc import TVMCException\n\n\ndef load_function(full_name):\n    \"\"\"Dynamic loading a function by the full name.\n    Parameters\n    ----------\n    full_name: str\n        The name of a PackedFunc or a string of the form \"path.to.module.func\"\n        that indicates the module that can be imported.\n        You must be aware of the load order here, it first tries to find it via\n        TVM global function, if not find, try to import it by \"importlib.import_module\".\n    Returns\n    -------\n    func: function or PackedFunc\n        The loaded fucntion.\n    \"\"\"\n    global_func = tvm.get_global_func(full_name, allow_missing=True)\n    if global_func is not None:\n        return global_func\n\n    # split full name \"path.to.module.func\" into two parts [\"path.to.module\", \"func\"]\n    module_name, func_name = full_name.rsplit(\".\", 1)\n\n    # import module and find the function\n    module = importlib.import_module(module_name)\n    if hasattr(module, func_name):\n        return getattr(module, func_name)\n\n    raise TVMCException(f\"No function '{func_name}' found in module '{module_name}'.\")\n\n\ndef get_pass_config_value(name, value, config_type):\n    \"\"\"Get a PassContext configuration value, based on its config data type.\n\n    Parameters\n    ----------\n    name: str\n        config identifier name.\n    value: str\n        value assigned to the config, provided via command line.\n    config_type: str\n        data type defined to the config, as string.\n\n    Returns\n    -------\n    parsed_value: bool, int or str\n        a representation of the input value, converted to the type\n        specified by config_type.\n    \"\"\"\n\n    parsed_value = None\n\n    if config_type == \"IntImm\":\n        # \"Bool\" configurations in the PassContext are recognized as\n        # IntImm, so deal with this case here\n        mapping_values = {\n            \"false\": False,\n            \"true\": True,\n        }\n\n        if value.isdigit():\n            parsed_value = int(value)\n        else:\n            # if not an int, accept only values on the mapping table, case insensitive\n            parsed_value = mapping_values.get(value.lower(), None)\n\n        if parsed_value is None:\n            raise TVMCException(f\"Invalid value '{value}' for configuration '{name}'.\")\n\n    elif config_type == \"runtime.String\":\n        parsed_value = value\n\n    elif config_type == \"Array\":\n        if name == \"tir.add_lower_pass\":\n            pass_list = value.split(\",\")\n            if len(pass_list) % 2 != 0:\n                raise TVMCException(\n                    f\"The configuration of '{name}' must be of the form \"\n                    \"'tir.add_lower_pass=opt_level1,pass1,opt_evel2,pass2'\"\n                )\n\n            parsed_value = []\n            for i in range(0, len(pass_list), 2):\n                level, pass_func = pass_list[i].strip(), pass_list[i + 1].strip()\n                try:\n                    level = int(level)\n                except ValueError:\n                    raise TVMCException(f\"Only integer is allow for configuration '{name}'.\")\n\n                # TODO (@leeexyz) We should parse configurations of each tir Pass.\n                #     For now, we only use the defaults. Currently, There are four config nodes:\n                #     `tir.transform.LoopPartitionConfig`\n                #     `tir.transform.UnrollLoopConfig`\n                #     `tir.transform.HoistIfThenElseConfig`\n                #     `tir.transform.InjectDoubleBufferConfig`\n                # loading pass func and calling it to get the Pass\n                pass_func = load_function(pass_func)()\n                parsed_value.append((level, pass_func))\n        else:\n            raise TVMCException(f\"Unsupported configuration '{name}' for '{config_type}' type.\")\n\n    else:\n        # not raise here cause we alreay checked before calling this function\n        pass\n\n    return parsed_value\n\n\ndef parse_configs(input_configs):\n    \"\"\"Parse configuration values set via command line.\n\n    Parameters\n    ----------\n    input_configs: list of str\n        list of configurations provided via command line.\n\n    Returns\n    -------\n    pass_context_configs: dict\n        a dict containing key-value configs to be used in the PassContext.\n    \"\"\"\n    if not input_configs:\n        return {}\n\n    all_configs = tvm.ir.transform.PassContext.list_configs()\n    supported_config_types = (\"IntImm\", \"runtime.String\", \"Array\")\n    supported_configs = [\n        name for name in all_configs.keys() if all_configs[name][\"type\"] in supported_config_types\n    ]\n\n    pass_context_configs = {}\n\n    for config in input_configs:\n        if not config:\n            raise TVMCException(\n                f\"Invalid format for configuration '{config}', use <config>=<value>\"\n            )\n\n        # Each config is expected to be provided as \"name=value\"\n        try:\n            name, value = config.split(\"=\")\n            name = name.strip()\n            value = value.strip()\n        except ValueError:\n            raise TVMCException(\n                f\"Invalid format for configuration '{config}', use <config>=<value>\"\n            )\n\n        if name not in all_configs:\n            raise TVMCException(\n                f\"Configuration '{name}' is not defined in TVM. \"\n                f\"These are the existing configurations: {', '.join(all_configs)}\"\n            )\n\n        if name not in supported_configs:\n            raise TVMCException(\n                f\"Configuration '{name}' uses a data type not supported by TVMC. \"\n                f\"The following configurations are supported: {', '.join(supported_configs)}\"\n            )\n\n        config_type = all_configs[name][\"type\"]\n        parsed_value = get_pass_config_value(name, value, config_type)\n\n        if config_type == \"Array\" and name in pass_context_configs:\n            # merge configs if the configuration exists\n            pass_context_configs[name].extend(parsed_value)\n        else:\n            pass_context_configs[name] = parsed_value\n\n    return pass_context_configs\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/pass_list.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language\n\"\"\"\nTVMC Pass List Management\n\"\"\"\n\nimport argparse\n\nimport tvm\nfrom tvm._ffi import registry\n\n\ndef parse_pass_list_str(input_string):\n    \"\"\"Parse an input string for existing passes\n\n    Parameters\n    ----------\n    input_string: str\n        Possibly comma-separated string with the names of passes\n\n    Returns\n    -------\n    list: a list of existing passes.\n    \"\"\"\n    _prefix = \"relay._transform.\"\n    pass_list = input_string.split(\",\")\n    missing_list = [\n        p.strip()\n        for p in pass_list\n        if len(p.strip()) > 0 and tvm.get_global_func(_prefix + p.strip(), True) is None\n    ]\n    if len(missing_list) > 0:\n        available_list = [\n            n[len(_prefix) :] for n in registry.list_global_func_names() if n.startswith(_prefix)\n        ]\n        raise argparse.ArgumentTypeError(\n            \"Following passes are not registered within tvm: {}. Available: {}.\".format(\n                \", \".join(missing_list), \", \".join(sorted(available_list))\n            )\n        )\n    return pass_list\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/project.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC Project Generation Functions\n\"\"\"\n\nimport os\nimport pathlib\nfrom collections import defaultdict\nfrom typing import Union\n\nfrom . import TVMCException\nfrom .fmtopt import format_option\n\n\ndef get_project_options(project_info):\n    \"\"\"Get all project options as returned by Project API 'server_info_query'\n    and return them in a dict indexed by the API method they belong to.\n\n\n    Parameters\n    ----------\n    project_info: dict of list\n        a dict of lists as returned by Project API 'server_info_query' among\n        which there is a list called 'project_options' containing all the\n        project options available for a given project/platform.\n\n    Returns\n    -------\n    options_by_method: dict of list\n        a dict indexed by the API method names (e.g. \"generate_project\",\n        \"build\", \"flash\", or \"open_transport\") of lists containing all the\n        options (plus associated metadata and formatted help text) that belong\n        to a method.\n\n        The metadata associated to the options include the field 'choices' and\n        'required' which are convenient for parsers.\n\n        The formatted help text field 'help_text' is a string that contains the\n        name of the option, the choices for the option, and the option's default\n        value.\n    \"\"\"\n    options = project_info[\"project_options\"]\n\n    options_by_method = defaultdict(list)\n    for opt in options:\n        # Get list of methods associated with an option based on the\n        # existance of a 'required' or 'optional' lists. API specification\n        # guarantees at least one of these lists will exist. If a list does\n        # not exist it's returned as None by the API.\n        metadata = [\"required\", \"optional\"]\n        option_methods = [(opt[md], bool(md == \"required\")) for md in metadata if opt[md]]\n        for methods, is_opt_required in option_methods:\n            for method in methods:\n                name = opt[\"name\"]\n\n                # Only for boolean options set 'choices' accordingly to the\n                # option type. API returns 'choices' associated to them\n                # as None but 'choices' can be deduced from 'type' in this case.\n                if opt[\"type\"] == \"bool\":\n                    opt[\"choices\"] = [\"true\", \"false\"]\n\n                if opt[\"choices\"]:\n                    choices = \"{\" + \", \".join(opt[\"choices\"]) + \"}\"\n                else:\n                    choices = opt[\"name\"].upper()\n                option_choices_text = f\"{name}={choices}\"\n\n                help_text = opt[\"help\"][0].lower() + opt[\"help\"][1:]\n\n                if opt[\"default\"]:\n                    default_text = f\"Defaults to '{opt['default']}'.\"\n                else:\n                    default_text = None\n\n                formatted_help_text = format_option(\n                    option_choices_text, help_text, default_text, is_opt_required\n                )\n\n                option = {\n                    \"name\": opt[\"name\"],\n                    \"choices\": opt[\"choices\"],\n                    \"help_text\": formatted_help_text,\n                    \"required\": is_opt_required,\n                }\n                options_by_method[method].append(option)\n\n    return options_by_method\n\n\ndef get_options(options):\n    \"\"\"Get option and option value from the list options returned by the parser.\n\n    Parameters\n    ----------\n    options: list of str\n        list of strings of the form \"option=value\" as returned by the parser.\n\n    Returns\n    -------\n    opts: dict\n        dict indexed by option names and associated values.\n    \"\"\"\n\n    opts = {}\n    for option in options:\n        try:\n            k, v = option.split(\"=\")\n            opts[k] = v\n        except ValueError:\n            raise TVMCException(f\"Invalid option format: {option}. Please use OPTION=VALUE.\")\n\n    return opts\n\n\ndef check_options(options, valid_options):\n    \"\"\"Check if an option (required or optional) is valid. i.e. in the list of valid options.\n\n    Parameters\n    ----------\n    options: dict\n        dict indexed by option name of options and options values to be checked.\n\n    valid_options: list of dict\n        list of all valid options and choices for a platform.\n\n    Returns\n    -------\n    None. Raise TVMCException if check fails, i.e. if an option is not in the list of valid options.\n\n    \"\"\"\n    required_options = [opt[\"name\"] for opt in valid_options if opt[\"required\"]]\n    for required_option in required_options:\n        if required_option not in options:\n            raise TVMCException(\n                f\"Option '{required_option}' is required but was not specified. Use --list-options \"\n                \"to see all required options.\"\n            )\n\n    remaining_options = set(options) - set(required_options)\n    optional_options = [opt[\"name\"] for opt in valid_options if not opt[\"required\"]]\n    for option in remaining_options:\n        if option not in optional_options:\n            raise TVMCException(\n                f\"Option '{option}' is invalid. Use --list-options to see all available options.\"\n            )\n\n\ndef check_options_choices(options, valid_options):\n    \"\"\"Check if an option value is among the option's choices, when choices exist.\n\n    Parameters\n    ----------\n    options: dict\n        dict indexed by option name of options and options values to be checked.\n\n    valid_options: list of dict\n        list of all valid options and choices for a platform.\n\n    Returns\n    -------\n    None. Raise TVMCException if check fails, i.e. if an option value is not valid.\n\n    \"\"\"\n    # Dict of all valid options and associated valid choices.\n    # Options with no choices are excluded from the dict.\n    valid_options_choices = {\n        opt[\"name\"]: opt[\"choices\"] for opt in valid_options if opt[\"choices\"] is not None\n    }\n\n    for option in options:\n        if option in valid_options_choices:\n            if options[option] not in valid_options_choices[option]:\n                raise TVMCException(\n                    f\"Choice '{options[option]}' for option '{option}' is invalid. \"\n                    \"Use --list-options to see all available choices for that option.\"\n                )\n\n\ndef get_and_check_options(passed_options, valid_options):\n    \"\"\"Get options and check if they are valid.  If choices exist for them, check values against it.\n\n    Parameters\n    ----------\n    passed_options: list of str\n        list of strings in the \"key=value\" form as captured by argparse.\n\n    valid_option: list\n        list with all options available for a given API method / project as returned by\n        get_project_options().\n\n    Returns\n    -------\n    opts: dict\n        dict indexed by option names and associated values.\n\n    Or None if passed_options is None.\n\n    \"\"\"\n\n    if passed_options is None:\n        # No options to check\n        return None\n\n    # From a list of k=v strings, make a dict options[k]=v\n    opts = get_options(passed_options)\n    # Check if passed options are valid\n    check_options(opts, valid_options)\n    # Check (when a list of choices exists) if the passed values are valid\n    check_options_choices(opts, valid_options)\n\n    return opts\n\n\ndef get_project_dir(project_dir: Union[pathlib.Path, str]) -> str:\n    \"\"\"Get project directory path\"\"\"\n    if not os.path.isabs(project_dir):\n        return os.path.abspath(project_dir)\n    return project_dir\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/registry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file contains functions for processing registry based inputs for the TVMC CLI\n\"\"\"\n\nfrom tvm.driver.tvmc import TVMCException\n\n# We can't tell the type inside an Array but all current options are strings so\n# it can default to that. Bool is used alongside Integer but aren't distinguished\n# between as both are represented by IntImm\nINTERNAL_TO_NATIVE_TYPE = {\"runtime.String\": str, \"IntImm\": int, \"Array\": str}\nINTERNAL_TO_HELP = {\"runtime.String\": \" string\", \"IntImm\": \"\", \"Array\": \" options\"}\n\n\ndef _generate_registry_option_args(parser, registry, name):\n    target_group = parser.add_argument_group(f\"{registry.flag_registry_name} {name}\")\n    for option_name, option_type in registry.list_registered_options(name).items():\n        if option_type in INTERNAL_TO_NATIVE_TYPE:\n            target_group.add_argument(\n                f\"--{registry.flag_registry_name}-{name}-{option_name}\",\n                type=INTERNAL_TO_NATIVE_TYPE[option_type],\n                help=(\n                    f\"{registry.flag_registry_name.title()} \"\n                    + \"{name} {option_name}{INTERNAL_TO_HELP[option_type]}\"\n                ),\n            )\n\n\ndef generate_registry_args(parser, registry, default=None):\n    \"\"\"Walks through the given registry and generates arguments for each of the available options\"\"\"\n    parser.add_argument(\n        f\"--{registry.flag_registry_name}\",\n        help=f\"{registry.flag_registry_name.title()} to compile the model with\",\n        required=False,\n        default=default,\n    )\n    names = registry.list_registered()\n\n    for name in names:\n        _generate_registry_option_args(parser, registry, name)\n\n\ndef _reconstruct_registry_options(args, registry, name):\n    options = {}\n    for option, option_type in registry.list_registered_options(name).items():\n        if option_type in INTERNAL_TO_NATIVE_TYPE:\n            var_name = f\"{registry.flag_registry_name}_{name}_{option.replace('-', '_')}\"\n            option_value = getattr(args, var_name)\n            if option_value is not None:\n                options[option] = option_value\n    return options\n\n\ndef reconstruct_registry_entity(args, registry):\n    \"\"\"Reconstructs an entity from arguments generated from a registry\"\"\"\n    possible_names = registry.list_registered()\n    name = getattr(args, registry.flag_registry_name)\n    if name is None:\n        return None\n\n    if name not in possible_names:\n        raise TVMCException(f'{registry.flag_registry_name.title()} \"{name}\" is not defined')\n\n    reconstructed = {\n        possible_name: _reconstruct_registry_options(args, registry, possible_name)\n        for possible_name in possible_names\n    }\n\n    for possible_name in possible_names:\n        if possible_name != name and reconstructed[possible_name]:\n            first_option = list(reconstructed[possible_name])[0]\n            raise TVMCException(\n                f\"Passed --{registry.flag_registry_name}-{possible_name}-{first_option} \"\n                f\"but did not specify {possible_name} executor\"\n            )\n\n    return registry(name, reconstructed[name])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/result_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file contains utility functions for processing the outputs\nof TVMC models. These utilities are likely to be task specific,\novertime more will be added to support more machine learning tasks.\n\nExamples\n--------\nThe following code shows how one might postprocess\nthe output of a classification model.\n\n.. code-block:: python\n    result = tvmc.run(tvmc_package, device=\"cpu\")\n    top_results = result_utils.get_top_results(max_results=5)\n\"\"\"\nimport numpy as np\nfrom .model import TVMCResult\n\n\ndef get_top_results(result: TVMCResult, max_results: int):\n    \"\"\"Return the top n results from the output tensor.\n\n    This function is primarily for image classification and will\n    not necessarily generalize.\n\n    Parameters\n    ----------\n    result : TVMCResult\n        The output of a TVMCModel\n    max_results : int\n        Number of results to return\n\n    Returns\n    -------\n    top_results : np.array\n        Results array of shape (2, n).\n        The first row is the indices and the second is the values.\n\n    \"\"\"\n    output = np.copy(result.outputs[\"output_0\"])\n    sorted_labels = output.argsort()[0][-max_results:][::-1]\n    output.sort()\n    sorted_values = output[0][-max_results:][::-1]\n    top_results = np.array([sorted_labels, sorted_values])\n    return top_results\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProvides support to run compiled networks both locally and remotely.\n\"\"\"\nfrom contextlib import ExitStack\nimport logging\nimport pathlib\nfrom typing import Dict, Optional, Union\nfrom tarfile import ReadError\nimport argparse\nimport sys\nimport json\n\nimport numpy as np\n\nimport tvm\nfrom tvm import rpc\nfrom tvm.runtime import vm\nfrom tvm.autotvm.measure import request_remote\nfrom tvm.contrib import graph_executor as executor\nfrom tvm.contrib.debugger import debug_executor\nfrom tvm.runtime import profiler_vm\nfrom tvm.relay.param_dict import load_param_dict\nfrom . import TVMCException\nfrom .arguments import TVMCSuppressedArgumentParser\nfrom .project import (\n    get_project_options,\n    get_and_check_options,\n    get_project_dir,\n)\n\nfrom .main import register_parser\nfrom .model import TVMCPackage, TVMCResult\nfrom .result_utils import get_top_results\nfrom .tracker import tracker_host_port_from_cli\n\ntry:\n    import tvm.micro.project as project\n    from tvm.micro.project import TemplateProjectError\n    from tvm.micro.project_api.client import ProjectAPIServerNotFoundError\n\n    SUPPORT_MICRO = True\nexcept (ImportError, AttributeError) as exception:\n    SUPPORT_MICRO = False\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\n@register_parser\ndef add_run_parser(subparsers, main_parser, json_params):\n    \"\"\"Include parser for 'run' subcommand\"\"\"\n\n    # Use conflict_handler='resolve' to allow '--list-options' option to be properly overriden when\n    # augmenting the parser with the micro device options (i.e. when '--device micro').\n    parser = subparsers.add_parser(\"run\", help=\"run a compiled module\", conflict_handler=\"resolve\")\n    parser.set_defaults(func=drive_run)\n\n    # TODO --device needs to be extended and tested to support other targets,\n    #      like 'webgpu', etc (@leandron)\n    parser.add_argument(\n        \"--device\",\n        choices=[\"cpu\", \"cuda\", \"cl\", \"metal\", \"vulkan\", \"rocm\", \"micro\"],\n        default=\"cpu\",\n        help=\"target device to run the compiled module. Defaults to 'cpu'\",\n    )\n    parser.add_argument(\n        \"--fill-mode\",\n        choices=[\"zeros\", \"ones\", \"random\"],\n        default=\"random\",\n        help=\"fill all input tensors with values. In case --inputs/-i is provided, \"\n        \"they will take precedence over --fill-mode. Any remaining inputs will be \"\n        \"filled using the chosen fill mode. Defaults to 'random'\",\n    )\n    parser.add_argument(\"-i\", \"--inputs\", help=\"path to the .npz input file\")\n    parser.add_argument(\"-o\", \"--outputs\", help=\"path to the .npz output file\")\n    parser.add_argument(\n        \"--print-time\",\n        action=\"store_true\",\n        help=\"record and print the execution time(s). Enabling print-time will result \"\n        \" in (1 + repeat * number) executions of the model. (non-micro devices only)\",\n    )\n    parser.add_argument(\n        \"--print-top\",\n        metavar=\"N\",\n        type=int,\n        help=\"print the top n values and indices of the output tensor\",\n    )\n    parser.add_argument(\n        \"--profile\",\n        action=\"store_true\",\n        help=\"generate profiling data from the runtime execution. \"\n        \"Using --profile requires the Graph Executor Debug enabled on TVM. \"\n        \"Profiling may also have an impact on inference time, \"\n        \"making it take longer to be generated. (non-micro devices only)\",\n    )\n    parser.add_argument(\n        \"--end-to-end\",\n        action=\"store_true\",\n        help=\"Measure data transfers as well as model execution. This can provide a \"\n        \"more realistic performance measurement in many cases. Requires \"\n        \"'--print-time' to be specified.\",\n    )\n    parser.add_argument(\n        \"--repeat\",\n        metavar=\"N\",\n        type=int,\n        default=1,\n        help=\"How many times to repeat the run. Requires '--print-time' to be \"\n        \"specified. Defaults to '1'\",\n    )\n    parser.add_argument(\n        \"--number\",\n        metavar=\"N\",\n        type=int,\n        default=1,\n        help=\"The number of runs to measure within each repeat. Requires \"\n        \"'--print-time' to be specified. Defaults to '1'\",\n    )\n    parser.add_argument(\n        \"--rpc-key\",\n        help=\"the RPC tracker key of the target device. (non-micro devices only)\",\n    )\n    parser.add_argument(\n        \"--rpc-tracker\",\n        help=\"hostname (required) and port (optional, defaults to 9090) of the RPC tracker, \"\n        \"e.g. '192.168.0.100:9999'. (non-micro devices only)\",\n    )\n    parser.add_argument(\n        \"PATH\",\n        help=\"path to the compiled module file or to the project directory if '--device micro' \"\n        \"is selected.\",\n    )\n    parser.add_argument(\n        \"--list-options\",\n        action=\"store_true\",\n        help=\"show all run options and option choices when '--device micro' is selected. \"\n        \"(micro devices only)\",\n    )\n\n    disposable_parser = TVMCSuppressedArgumentParser(main_parser)\n    try:\n        known_args, _ = disposable_parser.parse_known_args()\n    except TVMCException:\n        return\n\n    if vars(known_args).get(\"device\") != \"micro\":\n        # No need to augment the parser for micro targets.\n        return\n\n    if SUPPORT_MICRO is False:\n        sys.exit(\n            \"'--device micro' is not supported. \"\n            \"Please build TVM with micro support (USE_MICRO ON)!\"\n        )\n\n    project_dir = get_project_dir(known_args.PATH)\n\n    try:\n        project_ = project.GeneratedProject.from_directory(project_dir, None)\n    except ProjectAPIServerNotFoundError:\n        sys.exit(f\"Error: Project API server not found in {project_dir}!\")\n    except TemplateProjectError:\n        sys.exit(\n            f\"Error: Project directory error. That usually happens when model.tar is not found.\"\n        )\n\n    project_info = project_.info()\n    options_by_method = get_project_options(project_info)\n    mlf_path = project_info[\"model_library_format_path\"]\n\n    parser.formatter_class = (\n        argparse.RawTextHelpFormatter\n    )  # Set raw help text so customized help_text format works\n\n    parser.set_defaults(valid_options=options_by_method[\"open_transport\"], mlf_path=mlf_path)\n\n    required = any([opt[\"required\"] for opt in options_by_method[\"open_transport\"]])\n    nargs = \"+\" if required else \"*\"\n\n    help_text_by_option = [opt[\"help_text\"] for opt in options_by_method[\"open_transport\"]]\n    help_text = \"\\n\\n\".join(help_text_by_option) + \"\\n\\n\"\n\n    parser.add_argument(\n        \"--project-option\", required=required, metavar=\"OPTION=VALUE\", nargs=nargs, help=help_text\n    )\n\n    parser.add_argument(\n        \"--list-options\",\n        action=\"help\",\n        help=\"show this help message with platform-specific options and exit.\",\n    )\n\n    for one_entry in json_params:\n        parser.set_defaults(**one_entry)\n\n\ndef drive_run(args):\n    \"\"\"Invoke runner module with command line arguments\n\n    Parameters\n    ----------\n    args: argparse.Namespace\n        Arguments from command line parser.\n    \"\"\"\n\n    path = pathlib.Path(args.PATH)\n    options = None\n    project_dir = None\n    if args.device == \"micro\":\n        # If it's a micro device, then grab the model.tar path from Project API instead.\n        # args.PATH will be used too since it points to the project directory. N.B.: there is no\n        # way to determine the model.tar path from the project dir or vice-verse (each platform\n        # is free to put model.tar whereever it's convenient).\n        project_dir = path\n        path = pathlib.Path(args.mlf_path)\n\n        # Check for options unavailable for micro targets.\n\n        if args.rpc_key or args.rpc_tracker:\n            raise TVMCException(\n                \"--rpc-key and/or --rpc-tracker can't be specified for micro targets.\"\n            )\n\n        if args.device != \"micro\":\n            raise TVMCException(\n                f\"Device '{args.device}' not supported. \"\n                \"Only device 'micro' is supported to run a model in MLF, \"\n                \"i.e. when '--device micro'.\"\n            )\n\n        if args.profile:\n            raise TVMCException(\"--profile is not currently supported for micro devices.\")\n\n        if args.print_time:\n            raise TVMCException(\"--print-time is not currently supported for micro devices.\")\n\n        # Get and check options for micro targets.\n        options = get_and_check_options(args.project_option, args.valid_options)\n\n    else:\n        # Check for options only availabe for micro targets.\n\n        if args.list_options:\n            raise TVMCException(\n                \"--list-options is only availabe on micro targets, i.e. when '--device micro'.\"\n            )\n\n    try:\n        tvmc_package = TVMCPackage(package_path=path, project_dir=project_dir)\n    except IsADirectoryError:\n        raise TVMCException(f\"File {path} must be an archive, not a directory.\")\n    except FileNotFoundError:\n        raise TVMCException(f\"File {path} does not exist.\")\n    except ReadError:\n        raise TVMCException(f\"Could not read model from archive {path}!\")\n\n    rpc_hostname, rpc_port = tracker_host_port_from_cli(args.rpc_tracker)\n\n    try:\n        inputs = np.load(args.inputs) if args.inputs else {}\n    except IOError as ex:\n        raise TVMCException(\"Error loading inputs file: %s\" % ex)\n\n    result = run_module(\n        tvmc_package,\n        args.device,\n        hostname=rpc_hostname,\n        port=rpc_port,\n        rpc_key=args.rpc_key,\n        inputs=inputs,\n        fill_mode=args.fill_mode,\n        benchmark=args.print_time,\n        repeat=args.repeat,\n        number=args.number,\n        profile=args.profile,\n        end_to_end=args.end_to_end,\n        options=options,\n    )\n\n    if args.print_time:\n        stat_table = result.format_times()\n        # print here is intentional\n        print(stat_table)\n\n    if args.print_top:\n        top_results = get_top_results(result, args.print_top)\n        # print here is intentional\n        print(top_results)\n\n    if args.outputs:\n        # Save the outputs\n        result.save(args.outputs)\n\n\ndef get_input_info(graph_str: str, params: Dict[str, tvm.nd.NDArray]):\n    \"\"\"Return the 'shape' and 'dtype' dictionaries for the input\n    tensors of a compiled module.\n\n    .. note::\n        We can't simply get the input tensors from a TVM graph\n        because weight tensors are treated equivalently. Therefore, to\n        find the input tensors we look at the 'arg_nodes' in the graph\n        (which are either weights or inputs) and check which ones don't\n        appear in the params (where the weights are stored). These nodes\n        are therefore inferred to be input tensors.\n\n    .. note::\n        There exists a more recent API to retrieve the input information\n        directly from the module. However, this isn't supported when using\n        with RPC due to a lack of support for Array and Map datatypes.\n        Therefore, this function exists only as a fallback when RPC is in\n        use. If RPC isn't being used, please use the more recent API.\n\n    Parameters\n    ----------\n    graph_str : str\n        JSON graph of the module serialized as a string.\n    params : dict\n        Parameter dictionary mapping name to value.\n\n    Returns\n    -------\n    shape_dict : dict\n        Shape dictionary - {input_name: tuple}.\n    dtype_dict : dict\n        dtype dictionary - {input_name: dtype}.\n    \"\"\"\n\n    shape_dict = {}\n    dtype_dict = {}\n    params_dict = load_param_dict(params)\n    param_names = [k for (k, v) in params_dict.items()]\n    graph = json.loads(graph_str)\n    for node_id in graph[\"arg_nodes\"]:\n        node = graph[\"nodes\"][node_id]\n        # If a node is not in the params, infer it to be an input node\n        name = node[\"name\"]\n        if name not in param_names:\n            shape_dict[name] = graph[\"attrs\"][\"shape\"][1][node_id]\n            dtype_dict[name] = graph[\"attrs\"][\"dltype\"][1][node_id]\n\n    return shape_dict, dtype_dict\n\n\ndef generate_tensor_data(shape: tuple, dtype: str, fill_mode: str):\n    \"\"\"Generate data to produce a tensor of given shape and dtype.\n\n    Random data generation depends on the dtype. For int8 types,\n    random integers in the range 0->255 are generated. For all other\n    types, random floats are generated in the range -1->1 and then\n    cast to the appropriate dtype.\n\n    This is used to quickly generate some data to input the models, as\n    a way to check that compiled module is sane for running.\n\n    Parameters\n    ----------\n    shape : tuple\n        The shape of the tensor.\n    dtype : str\n        The dtype of the tensor.\n    fill_mode : str\n        The fill-mode to use, either \"zeros\", \"ones\" or \"random\".\n\n    Returns\n    -------\n    tensor : np.array\n        The generated tensor as a np.array.\n    \"\"\"\n    if fill_mode == \"zeros\":\n        tensor = np.zeros(shape=shape, dtype=dtype)\n    elif fill_mode == \"ones\":\n        tensor = np.ones(shape=shape, dtype=dtype)\n    elif fill_mode == \"random\":\n        if \"int8\" in dtype:\n            tensor = np.random.randint(128, size=shape, dtype=dtype)\n        else:\n            tensor = np.random.uniform(-1, 1, size=shape).astype(dtype)\n    else:\n        raise TVMCException(\"unknown fill-mode: {}\".format(fill_mode))\n\n    return tensor\n\n\ndef make_inputs_dict(\n    shape_dict: tvm.container.Map,\n    dtype_dict: tvm.container.Map,\n    inputs: Optional[Dict[str, np.ndarray]] = None,\n    fill_mode: str = \"random\",\n):\n    \"\"\"Make the inputs dictionary for a graph.\n\n    Use data from 'inputs' where specified. For input tensors\n    where no data has been given, generate data according to the\n    chosen fill-mode.\n\n    Parameters\n    ----------\n    shape_dict : Map\n        Shape dictionary - {input_name: tuple}.\n    dtype_dict : Map\n        dtype dictionary - {input_name: dtype}.\n    inputs : dict, optional\n        A dictionary that maps input names to numpy values.\n    fill_mode : str, optional\n        The fill-mode to use when generating tensor data.\n        Can be either \"zeros\", \"ones\" or \"random\".\n\n    Returns\n    -------\n    inputs_dict : dict\n        Complete inputs dictionary - {input_name: np.array}.\n    \"\"\"\n    logger.debug(\"creating inputs dict\")\n\n    if inputs is None:\n        inputs = {}\n\n    # First check all the keys in inputs exist in the graph\n    for input_name in inputs:\n        if input_name not in shape_dict.keys():\n            raise TVMCException(\n                \"the input tensor '{}' is not in the graph. Expected inputs: '{}'\".format(\n                    input_name, list(shape_dict.keys())\n                )\n            )\n\n    # Now construct the input dict, generating tensors where no\n    # data already exists in 'inputs'\n    inputs_dict = {}\n    for input_name in shape_dict:\n        if input_name in inputs.keys():\n            logger.debug(\"setting input '%s' with user input data\", input_name)\n            inputs_dict[input_name] = inputs[input_name]\n        else:\n            # container.ShapleTuple -> tuple\n            shape = tuple(shape_dict[input_name])\n            # container.String -> str\n            dtype = str(dtype_dict[input_name])\n\n            logger.debug(\n                \"generating data for input '%s' (shape: %s, dtype: %s), using fill-mode '%s'\",\n                input_name,\n                shape,\n                dtype,\n                fill_mode,\n            )\n            data = generate_tensor_data(shape, dtype, fill_mode)\n            inputs_dict[input_name] = data\n\n    return inputs_dict\n\n\ndef run_module(\n    tvmc_package: TVMCPackage,\n    device: str,\n    hostname: Optional[str] = None,\n    port: Union[int, str] = 9090,\n    rpc_key: Optional[str] = None,\n    inputs: Optional[Dict[str, np.ndarray]] = None,\n    fill_mode: str = \"random\",\n    benchmark: bool = False,\n    repeat: int = 10,\n    number: int = 10,\n    profile: bool = False,\n    end_to_end: bool = False,\n    options: dict = None,\n):\n    \"\"\"Run a compiled graph executor module locally or remotely with\n    optional input values.\n\n    If input tensors are not specified explicitly, they can be filled\n    with zeroes, ones or random data.\n\n    Parameters\n    ----------\n    tvmc_package: TVMCPackage\n        The compiled model package object that will be run.\n    device: str,\n        the device (e.g. \"cpu\" or \"cuda\") to be targeted by the RPC\n        session, local or remote).\n    hostname : str, optional\n        The hostname of the target device on which to run.\n    port : int, optional\n        The port of the target device on which to run.\n    rpc_key : str, optional\n        The tracker key of the target device. If this is set, it\n        will be assumed that remote points to a tracker.\n    inputs : dict, optional\n        A dictionary that maps input names to numpy values. If not provided,\n        inputs will be generated using the fill_mode argument.\n    fill_mode : str, optional\n        The fill-mode to use when generating data for input tensors.\n        Valid options are \"zeros\", \"ones\" and \"random\".\n        Defaults to \"random\".\n    benchmark : bool, optional\n        Whether to benchmark the execution of the module. Enabling benchmark will\n        result in (1 + repeat * number) executions of the model.\n    repeat : int, optional\n        How many times to repeat the run. Requires `benchmark` to be set to True.\n    number : int, optional\n        The number of runs to measure within each repeat.\n        Requires `benchmark` to be set to True.\n    profile : bool\n        Whether to profile the run with the debug executor.\n    end_to_end : bool\n        Whether to measure the time of memory copies as well as model\n        execution. Turning this on can provide a more realistic estimate\n        of how long running the model in production would take.\n        Requires `benchmark` to be set to True.\n\n    Returns\n    -------\n    TVMCResult\n        The results of the run, including the output data.\n    \"\"\"\n    if not isinstance(tvmc_package, TVMCPackage):\n        raise TVMCException(\n            \"This model doesn't seem to have been compiled yet. \"\n            \"Try calling tvmc.compile on the model before running it.\"\n        )\n\n    with ExitStack() as stack:\n        # Currently only two package formats are supported: \"classic\" and\n        # \"mlf\". The later can only be used for micro targets, i.e. with microTVM.\n        if device == \"micro\":\n            if tvmc_package.type != \"mlf\":\n                raise TVMCException(f\"Model {tvmc_package.package_path} is not a MLF archive.\")\n\n            project_dir = get_project_dir(tvmc_package.project_dir)\n\n            # This is guaranteed to work since project_dir was already checked when\n            # building the dynamic parser to accommodate the project options, so no\n            # checks are in place when calling GeneratedProject.\n            project_ = project.GeneratedProject.from_directory(project_dir, options)\n        else:\n            if tvmc_package.type == \"mlf\":\n                raise TVMCException(\n                    \"You're trying to run a model saved using the Model Library Format (MLF). \"\n                    \"MLF can only be used to run micro device ('--device micro').\"\n                )\n\n        if hostname:\n            if isinstance(port, str):\n                port = int(port)\n            # Remote RPC\n            if rpc_key:\n                logger.debug(\"Running on remote RPC tracker with key %s.\", rpc_key)\n                session = request_remote(rpc_key, hostname, port, timeout=1000)\n            else:\n                logger.debug(\"Running on remote RPC with no key.\")\n                session = rpc.connect(hostname, port)\n        elif device == \"micro\":\n            # Remote RPC (running on a micro target)\n            logger.debug(\"Running on remote RPC (micro target).\")\n            try:\n                session = tvm.micro.Session(project_.transport())\n                stack.enter_context(session)\n            except:\n                raise TVMCException(\"Could not open a session with the micro target.\")\n        else:\n            # Local\n            logger.debug(\"Running a local session.\")\n            session = rpc.LocalSession()\n\n        # Micro targets don't support uploading a model. The model to be run\n        # must be already flashed into the micro target before one tries\n        # to run it. Hence skip model upload for micro targets.\n        if device != \"micro\":\n            session.upload(tvmc_package.lib_path)\n            lib = session.load_module(tvmc_package.lib_name)\n\n        # TODO expand to other supported devices, as listed in tvm.rpc.client (@leandron)\n        logger.debug(\"Device is %s.\", device)\n        if device == \"cuda\":\n            dev = session.cuda()\n        elif device == \"cl\":\n            dev = session.cl()\n        elif device == \"metal\":\n            dev = session.metal()\n        elif device == \"vulkan\":\n            dev = session.vulkan()\n        elif device == \"rocm\":\n            dev = session.rocm()\n        elif device == \"micro\":\n            dev = session.device\n            lib = session.get_system_lib()\n        else:\n            assert device == \"cpu\"\n            dev = session.cpu()\n\n        if tvmc_package.type == \"vm\":\n            assert inputs is not None, \"vm runner requires inputs to be provided as a dict\"\n\n            input_tensor = {}\n            for e, i in inputs.items():\n                input_tensor[e] = tvm.nd.array(i, dev)\n\n            if profile:\n                logger.debug(\"Creating vm with profile enabled.\")\n                exe = profiler_vm.VirtualMachineProfiler(lib, dev)\n                res = exe.profile(**input_tensor, func_name=\"main\")\n                # This print is intentional\n                print(res)\n            else:\n                exe = vm.VirtualMachine(lib, dev)\n\n            exe_outputs = exe.invoke(\"main\", **input_tensor)\n\n            if benchmark:\n                times = exe.benchmark(\n                    dev,\n                    **input_tensor,\n                    func_name=\"main\",\n                    repeat=repeat,\n                    number=number,\n                    end_to_end=end_to_end,\n                )\n            else:\n                exe.run(**input_tensor)\n                times = []\n\n            # Special handling if the output only has a single value\n            if not isinstance(exe_outputs, list):\n                exe_outputs = [exe_outputs]\n\n            outputs = {}\n            for i, val in enumerate(exe_outputs):\n                output_name = \"output_{}\".format(i)\n                outputs[output_name] = val.numpy()\n        else:\n            # TODO(gromero): Adjust for micro targets.\n            if profile:\n                logger.debug(\"Creating runtime with profiling enabled.\")\n                module = debug_executor.create(tvmc_package.graph, lib, dev, dump_root=\"./prof\")\n            else:\n                if device == \"micro\":\n                    logger.debug(\"Creating runtime (micro) with profiling disabled.\")\n                    module = tvm.micro.create_local_graph_executor(tvmc_package.graph, lib, dev)\n                else:\n                    logger.debug(\"Creating runtime with profiling disabled.\")\n                    module = executor.create(tvmc_package.graph, lib, dev)\n\n            logger.debug(\"Loading params into the runtime module.\")\n            module.load_params(tvmc_package.params)\n\n            logger.debug(\"Collecting graph input shape and type:\")\n\n            if isinstance(session, tvm.rpc.client.RPCSession):\n                # RPC does not support datatypes such as Array and Map,\n                # fallback to obtaining input information from graph json.\n                shape_dict, dtype_dict = get_input_info(tvmc_package.graph, tvmc_package.params)\n            else:\n                shape_dict, dtype_dict = module.get_input_info()\n\n            logger.debug(\"Graph input shape: %s\", shape_dict)\n            logger.debug(\"Graph input type: %s\", dtype_dict)\n\n            inputs_dict = make_inputs_dict(shape_dict, dtype_dict, inputs, fill_mode)\n\n            logger.debug(\"Setting inputs to the module.\")\n            module.set_input(**inputs_dict)\n\n            # Run must be called explicitly if profiling\n            if profile:\n                logger.info(\"Running the module with profiling enabled.\")\n                report = module.profile()\n                # This print is intentional\n                print(report)\n\n            if not benchmark or device == \"micro\":\n                # TODO(gromero): Fix time_evaluator() for micro targets. Once it's\n                # fixed module.benchmark() can be used instead and this if/else can\n                # be removed.\n                module.run()\n                times = []\n            else:\n                # Call the benchmarking function of the executor.\n                # Optionally measure e2e data transfers from the\n                # CPU to device memory overheads (e.g. PCIE\n                # overheads if the device is a discrete GPU).\n                if end_to_end:\n                    dev = session.cpu()\n                times = module.benchmark(dev, number=number, repeat=repeat, end_to_end=end_to_end)\n\n            logger.debug(\"Collecting the output tensors.\")\n            num_outputs = module.get_num_outputs()\n            outputs = {}\n            for i in range(num_outputs):\n                output_name = \"output_{}\".format(i)\n                outputs[output_name] = module.get_output(i).numpy()\n\n        return TVMCResult(outputs, times)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/shape_parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMC Shape Parsing\n\"\"\"\n\nimport argparse\nimport re\n\nfrom tvm import relay\n\n\ndef parse_shape_string(inputs_string):\n    \"\"\"Parse an input shape dictionary string to a usable dictionary.\n\n    Parameters\n    ----------\n    inputs_string: str\n        A string of the form \"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]\" that\n        indicates the desired shape for specific model inputs. Colons, forward slashes and dots\n        within input_names are supported. Spaces are supported inside of dimension arrays.\n\n    Returns\n    -------\n    shape_dict: dict\n        A dictionary mapping input names to their shape for use in relay frontend converters.\n    \"\"\"\n\n    # Create a regex pattern that extracts each separate input mapping.\n    # We want to be able to handle:\n    # * Spaces inside arrays\n    # * forward slashes inside names (but not at the beginning or end)\n    # * colons inside names (but not at the beginning or end)\n    # * dots inside names\n    pattern = r\"(?:\\w+\\/)?[:\\w.]+\\:\\s*\\[\\-?\\d+(?:\\,\\s*\\-?\\d+)*\\]\"\n    input_mappings = re.findall(pattern, inputs_string)\n    if not input_mappings:\n        raise argparse.ArgumentTypeError(\n            \"--input-shapes argument must be of the form \"\n            '\"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]\"'\n        )\n    shape_dict = {}\n    for mapping in input_mappings:\n        # Remove whitespace.\n        mapping = mapping.replace(\" \", \"\")\n        # Split mapping into name and shape.\n        name, shape_string = mapping.rsplit(\":\", 1)\n        # Convert shape string into a list of integers or Anys if negative.\n        shape = [int(x) if int(x) > 0 else relay.Any() for x in shape_string.strip(\"][\").split(\",\")]\n        # Add parsed mapping to shape dictionary.\n        shape_dict[name] = shape\n\n    return shape_dict\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file contains functions for processing target inputs for the TVMC CLI\n\"\"\"\n\nimport os\nimport logging\nimport json\nimport re\n\nimport tvm\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.driver.tvmc.composite_target import get_codegen_by_target, get_codegen_names\nfrom tvm.ir.attrs import make_node, _ffi_api as attrs_api\nfrom tvm.ir.transform import PassContext\nfrom tvm.target import Target, TargetKind\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n# We can't tell the type inside an Array but all current options are strings so\n# it can default to that. Bool is used alongside Integer but aren't distinguished\n# between as both are represented by IntImm\nINTERNAL_TO_NATIVE_TYPE = {\"runtime.String\": str, \"IntImm\": int, \"Array\": str}\nINTERNAL_TO_HELP = {\"runtime.String\": \" string\", \"IntImm\": \"\", \"Array\": \" options\"}\n\n\ndef _valid_target_kinds():\n    codegen_names = tvmc.composite_target.get_codegen_names()\n    return filter(lambda target: target not in codegen_names, Target.list_kinds())\n\n\ndef _generate_target_kind_args(parser, kind_name):\n    target_group = parser.add_argument_group(f\"target {kind_name}\")\n    for target_option, target_type in TargetKind.options_from_name(kind_name).items():\n        if target_type in INTERNAL_TO_NATIVE_TYPE:\n            target_group.add_argument(\n                f\"--target-{kind_name}-{target_option}\",\n                type=INTERNAL_TO_NATIVE_TYPE[target_type],\n                help=f\"target {kind_name} {target_option}{INTERNAL_TO_HELP[target_type]}\",\n            )\n\n\ndef _generate_codegen_args(parser, codegen_name):\n    codegen = get_codegen_by_target(codegen_name)\n    pass_configs = PassContext.list_configs()\n\n    if codegen[\"config_key\"] is not None and codegen[\"config_key\"] in pass_configs:\n        target_group = parser.add_argument_group(f\"target {codegen_name}\")\n        attrs = make_node(pass_configs[codegen[\"config_key\"]][\"type\"])\n        fields = attrs_api.AttrsListFieldInfo(attrs)\n        for field in fields:\n            for tvm_type, python_type in INTERNAL_TO_NATIVE_TYPE.items():\n                if field.type_info.startswith(tvm_type):\n                    target_option = field.name\n                    target_group.add_argument(\n                        f\"--target-{codegen_name}-{target_option}\",\n                        type=python_type,\n                        help=f\"target {codegen_name} {target_option}{python_type}\",\n                    )\n\n\ndef generate_target_args(parser):\n    \"\"\"Walks through the TargetKind registry and generates arguments for each Target's options\"\"\"\n    parser.add_argument(\n        \"--target\",\n        help=\"compilation target as plain string, inline JSON or path to a JSON file\",\n        required=False,\n    )\n    for target_kind in _valid_target_kinds():\n        _generate_target_kind_args(parser, target_kind)\n    for codegen_name in get_codegen_names():\n        _generate_codegen_args(parser, codegen_name)\n\n\ndef _reconstruct_target_kind_args(args, kind_name):\n    kind_options = {}\n    for target_option, target_type in TargetKind.options_from_name(kind_name).items():\n        if target_type in INTERNAL_TO_NATIVE_TYPE:\n            var_name = f\"target_{kind_name.replace('-', '_')}_{target_option.replace('-', '_')}\"\n            option_value = getattr(args, var_name)\n            if option_value is not None:\n                kind_options[target_option] = getattr(args, var_name)\n    return kind_options\n\n\ndef _reconstruct_codegen_args(args, codegen_name):\n    codegen = get_codegen_by_target(codegen_name)\n    pass_configs = PassContext.list_configs()\n    codegen_options = {}\n\n    if codegen[\"config_key\"] is not None and codegen[\"config_key\"] in pass_configs:\n        attrs = make_node(pass_configs[codegen[\"config_key\"]][\"type\"])\n        fields = attrs_api.AttrsListFieldInfo(attrs)\n        for field in fields:\n            for tvm_type in INTERNAL_TO_NATIVE_TYPE:\n                if field.type_info.startswith(tvm_type):\n                    target_option = field.name\n                    var_name = (\n                        f\"target_{codegen_name.replace('-', '_')}_{target_option.replace('-', '_')}\"\n                    )\n                    option_value = getattr(args, var_name)\n                    if option_value is not None:\n                        codegen_options[target_option] = option_value\n    return codegen_options\n\n\ndef reconstruct_target_args(args):\n    \"\"\"Reconstructs the target options from the arguments\"\"\"\n    reconstructed = {}\n    for target_kind in _valid_target_kinds():\n        kind_options = _reconstruct_target_kind_args(args, target_kind)\n        if kind_options:\n            reconstructed[target_kind] = kind_options\n\n    for codegen_name in get_codegen_names():\n        codegen_options = _reconstruct_codegen_args(args, codegen_name)\n        if codegen_options:\n            reconstructed[codegen_name] = codegen_options\n\n    return reconstructed\n\n\ndef validate_targets(parse_targets, additional_target_options=None):\n    \"\"\"\n    Apply a series of validations in the targets provided via CLI.\n    \"\"\"\n    tvm_target_kinds = tvm.target.Target.list_kinds()\n    targets = [t[\"name\"] for t in parse_targets]\n\n    if len(targets) > len(set(targets)):\n        raise TVMCException(\"Duplicate target definitions are not allowed\")\n\n    if targets[-1] not in tvm_target_kinds:\n        tvm_target_names = \", \".join(tvm_target_kinds)\n        raise TVMCException(\n            f\"The last target needs to be a TVM target. Choices: {tvm_target_names}\"\n        )\n\n    tvm_targets = [t for t in targets if t in _valid_target_kinds()]\n    if len(tvm_targets) > 2:\n        verbose_tvm_targets = \", \".join(tvm_targets)\n        raise TVMCException(\n            \"Only two of the following targets can be used at a time. \"\n            f\"Found: {verbose_tvm_targets}.\"\n        )\n\n    if additional_target_options is not None:\n        for target_name in additional_target_options:\n            if not any([target for target in parse_targets if target[\"name\"] == target_name]):\n                first_option = list(additional_target_options[target_name].keys())[0]\n                raise TVMCException(\n                    f\"Passed --target-{target_name}-{first_option}\"\n                    f\" but did not specify {target_name} target\"\n                )\n\n\ndef tokenize_target(target):\n    \"\"\"\n    Extract a list of tokens from a target specification text.\n\n    It covers some corner-cases that are not covered by the built-in\n    module 'shlex', such as the use of \"+\" as a punctuation character.\n\n\n    Example\n    -------\n\n    For the input `foo -op1=v1 -op2=\"v ,2\", bar -op3=v-4` we\n    should obtain:\n\n        [\"foo\", \"-op1=v1\", \"-op2=\"v ,2\"\", \",\", \"bar\", \"-op3=v-4\"]\n\n    Parameters\n    ----------\n    target : str\n        Target options sent via CLI arguments\n\n    Returns\n    -------\n    list of str\n        a list of parsed tokens extracted from the target string\n    \"\"\"\n\n    # Regex to tokenize the \"--target\" value. It is split into five parts\n    # to match with:\n    #  1. target and option names e.g. llvm, -mattr=, -mcpu=\n    #  2. option values, all together, without quotes e.g. -mattr=+foo,+opt\n    #  3. option values, when single quotes are used e.g. -mattr='+foo, +opt'\n    #  4. option values, when double quotes are used e.g. -mattr=\"+foo ,+opt\"\n    #  5. commas that separate different targets e.g. \"my-target, llvm\"\n    target_pattern = (\n        r\"(\\-{0,2}[\\w\\-]+\\=?\"\n        r\"(?:[\\w\\+\\-\\.]+(?:,[\\w\\+\\-\\.])*\"\n        r\"|[\\'][\\w\\+\\-,\\s\\.]+[\\']\"\n        r\"|[\\\"][\\w\\+\\-,\\s\\.]+[\\\"])*\"\n        r\"|,)\"\n    )\n\n    return re.findall(target_pattern, target)\n\n\ndef parse_target(target):\n    \"\"\"\n    Parse a plain string of targets provided via a command-line\n    argument.\n\n    To send more than one codegen, a comma-separated list\n    is expected. Options start with -<option_name>=<value>.\n\n    We use python standard library 'shlex' to parse the argument in\n    a POSIX compatible way, so that if options are defined as\n    strings with spaces or commas, for example, this is considered\n    and parsed accordingly.\n\n\n    Example\n    -------\n\n    For the input `--target=\"foo -op1=v1 -op2=\"v ,2\", bar -op3=v-4\"` we\n    should obtain:\n\n      [\n        {\n            name: \"foo\",\n            opts: {\"op1\":\"v1\", \"op2\":\"v ,2\"},\n            raw: 'foo -op1=v1 -op2=\"v ,2\"'\n        },\n        {\n            name: \"bar\",\n            opts: {\"op3\":\"v-4\"},\n            raw: 'bar -op3=v-4'\n        }\n      ]\n\n    Parameters\n    ----------\n    target : str\n        Target options sent via CLI arguments\n\n    Returns\n    -------\n    codegens : list of dict\n        This list preserves the order in which codegens were\n        provided via command line. Each Dict contains three keys:\n        'name', containing the name of the codegen; 'opts' containing\n        a key-value for all options passed via CLI; 'raw',\n        containing the plain string for this codegen\n    \"\"\"\n    codegen_names = tvmc.composite_target.get_codegen_names()\n    codegens = []\n\n    tvm_target_kinds = tvm.target.Target.list_kinds()\n    parsed_tokens = tokenize_target(target)\n\n    split_codegens = []\n    current_codegen = []\n    split_codegens.append(current_codegen)\n    for token in parsed_tokens:\n        # every time there is a comma separating\n        # two codegen definitions, prepare for\n        # a new codegen\n        if token == \",\":\n            current_codegen = []\n            split_codegens.append(current_codegen)\n        else:\n            # collect a new token for the current\n            # codegen being parsed\n            current_codegen.append(token)\n\n    # at this point we have a list of lists,\n    # each item on the first list is a codegen definition\n    # in the comma-separated values\n    for codegen_def in split_codegens:\n        # the first is expected to be the name\n        name = codegen_def[0]\n        is_tvm_target = name in tvm_target_kinds and name not in codegen_names\n        raw_target = \" \".join(codegen_def)\n        all_opts = codegen_def[1:] if len(codegen_def) > 1 else []\n        opts = {}\n        for opt in all_opts:\n            try:\n                # deal with -- prefixed flags\n                if opt.startswith(\"--\"):\n                    opt_name = opt[2:]\n                    opt_value = True\n                else:\n                    opt = opt[1:] if opt.startswith(\"-\") else opt\n                    opt_name, opt_value = opt.split(\"=\", maxsplit=1)\n\n                    # remove quotes from the value: quotes are only parsed if they match,\n                    # so it is safe to assume that if the string starts with quote, it ends\n                    # with quote.\n                    opt_value = opt_value[1:-1] if opt_value[0] in ('\"', \"'\") else opt_value\n            except ValueError:\n                raise ValueError(f\"Error when parsing '{opt}'\")\n\n            opts[opt_name] = opt_value\n\n        codegens.append(\n            {\"name\": name, \"opts\": opts, \"raw\": raw_target, \"is_tvm_target\": is_tvm_target}\n        )\n\n    return codegens\n\n\ndef is_inline_json(target):\n    try:\n        json.loads(target)\n        return True\n    except json.decoder.JSONDecodeError:\n        return False\n\n\ndef _combine_target_options(target, additional_target_options=None):\n    if additional_target_options is None:\n        return target\n    if target[\"name\"] in additional_target_options:\n        target[\"opts\"].update(additional_target_options[target[\"name\"]])\n    return target\n\n\ndef _recombobulate_target(target):\n    name = target[\"name\"]\n    opts = \" \".join([f\"-{key}={value}\" for key, value in target[\"opts\"].items()])\n    return f\"{name} {opts}\"\n\n\ndef target_from_cli(target, additional_target_options=None):\n    \"\"\"\n    Create a tvm.target.Target instance from a\n    command line interface (CLI) string.\n\n    Parameters\n    ----------\n    target : str\n        compilation target as plain string,\n        inline JSON or path to a JSON file\n\n    additional_target_options: Optional[Dict[str, Dict[str,str]]]\n        dictionary of additional target options to be\n        combined with parsed targets\n\n    Returns\n    -------\n    tvm.target.Target\n        an instance of target device information\n    extra_targets : list of dict\n        This list preserves the order in which extra targets were\n        provided via command line. Each Dict contains three keys:\n        'name', containing the name of the codegen; 'opts' containing\n        a key-value for all options passed via CLI; 'raw',\n        containing the plain string for this codegen\n    \"\"\"\n    extra_targets = []\n\n    if os.path.isfile(target):\n        with open(target) as target_file:\n            logger.debug(\"target input is a path: %s\", target)\n            target = \"\".join(target_file.readlines())\n    elif is_inline_json(target):\n        logger.debug(\"target input is inline JSON: %s\", target)\n    else:\n        logger.debug(\"target input is plain text: %s\", target)\n        try:\n            parsed_targets = parse_target(target)\n        except ValueError as error:\n            raise TVMCException(f\"Error parsing target string '{target}'.\\nThe error was: {error}\")\n\n        validate_targets(parsed_targets, additional_target_options)\n        tvm_targets = [\n            _combine_target_options(t, additional_target_options)\n            for t in parsed_targets\n            if t[\"is_tvm_target\"]\n        ]\n\n        # Validated target strings have 1 or 2 tvm targets, otherwise\n        # `validate_targets` above will fail.\n        if len(tvm_targets) == 1:\n            target = _recombobulate_target(tvm_targets[0])\n            target_host = None\n        else:\n            assert len(tvm_targets) == 2\n            target = _recombobulate_target(tvm_targets[0])\n            target_host = _recombobulate_target(tvm_targets[1])\n\n        extra_targets = [\n            _combine_target_options(t, additional_target_options)\n            for t in parsed_targets\n            if not t[\"is_tvm_target\"]\n        ]\n\n    return tvm.target.Target(target, host=target_host), extra_targets\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language\n\"\"\"\nTVMC Remote Tracker\n\"\"\"\n\nimport logging\nfrom urllib.parse import urlparse\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\ndef tracker_host_port_from_cli(rpc_tracker_str):\n    \"\"\"Extract hostname and (optional) port from strings\n    like \"1.2.3.4:9090\" or \"4.3.2.1\".\n\n    Used as a helper function to cover --rpc-tracker\n    command line argument, in different subcommands.\n\n    Parameters\n    ----------\n    rpc_tracker_str : str\n        hostname (or IP address) and port of the RPC tracker,\n        in the format 'hostname[:port]'.\n\n    Returns\n    -------\n    rpc_hostname : str or None\n        hostname or IP address, extracted from input.\n    rpc_port : int or None\n        port number extracted from input (9090 default).\n    \"\"\"\n\n    rpc_hostname = rpc_port = None\n\n    if rpc_tracker_str:\n        parsed_url = urlparse(\"//%s\" % rpc_tracker_str)\n        rpc_hostname = parsed_url.hostname\n        rpc_port = parsed_url.port or 9090\n        logger.info(\"RPC tracker hostname: %s\", rpc_hostname)\n        logger.info(\"RPC tracker port: %s\", rpc_port)\n\n    return rpc_hostname, rpc_port\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language\n\"\"\"\nTVMC Graph Transforms\n\"\"\"\n\nfrom tvm import relay, transform\nfrom tvm.driver.tvmc import TVMCException\n\n\ndef convert_graph_layout(mod, desired_layout):\n    \"\"\"Alter the layout of the input graph.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The relay module to convert.\n    desired_layout : str\n        The layout to convert to.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The converted module.\n    \"\"\"\n\n    # Assume for the time being that graphs only have\n    # conv2d as heavily-sensitive operators.\n    desired_layouts = {\n        \"nn.conv2d\": [desired_layout, \"default\"],\n        \"nn.conv2d_transpose\": [desired_layout, \"default\"],\n        \"qnn.conv2d\": [desired_layout, \"default\"],\n    }\n\n    # Convert the layout of the graph where possible.\n    seq = transform.Sequential(\n        [\n            relay.transform.RemoveUnusedFunctions(),\n            relay.transform.ConvertLayout(desired_layouts),\n            relay.transform.FoldConstant(),\n        ]\n    )\n\n    try:\n        return seq(mod)\n    except Exception as err:\n        raise TVMCException(\"Error converting layout to {0}: {1}\".format(desired_layout, str(err)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/driver/tvmc/workspace_pools.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nFunctions for processing dynamic workspace pool TVMC args\n\"\"\"\n\n\nimport logging\nimport re\n\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.target import Target\nfrom tvm.ir.memory_pools import PoolInfoProperties, WorkspaceMemoryPools, WorkspacePoolInfo\n\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"TVMC\")\n\n\ndef generate_workspace_pools_args(parser):\n    \"\"\"Generates arguments for each Workspace Pools's options\"\"\"\n    parser.add_argument(\n        \"--workspace-pools\",\n        help=\"\"\"The name of the memory pool\n                Example usage: --workspace-pools=flash\"\"\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-targets\",\n        help=\"\"\"The name of the targets specified for the memory pool\n                Example usage: --workspace-pools-targets=flash:llvm\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-size-hint-bytes\",\n        nargs=\"?\",\n        help=\"\"\"The expected size hint to be used by the allocator.\n                Example usage: --workspace-pools-size-hint-bytes=flash:8\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-clock-frequency-hz\",\n        nargs=\"?\",\n        help=\"\"\"The clock frequency that the memory pool runs at in Hz.\n                Example usage: --workspace-pools-clock-frequency-hz=flash:70000000\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-read-bandwidth-bytes-per-cycle\",\n        nargs=\"?\",\n        help=\"\"\"The read bandwidth of the memory pool in bytes/cycle.\n                Example usage: --workspace-pools-read-bandwidth-bytes-per-cycle=flash:4\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-write-bandwidth-bytes-per-cycle\",\n        nargs=\"?\",\n        help=\"\"\"The write bandwidth of the memory pool in bytes/cycle.\n                Example usage: --workspace-pools-write-bandwidth-bytes-per-cycle=flash:8\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-read-latency-cycles\",\n        nargs=\"?\",\n        help=\"\"\"The read latency of the memory pool in cycles.\n                Example usage: --workspace-pools-read-latency-cycles=flash:4\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-write-latency-cycles\",\n        nargs=\"?\",\n        help=\"\"\"The write latency of the memory pool in cycles.\n                Example usage: --workspace-pools-write-latency-cycles=flash:8\"\"\",\n        action=\"append\",\n    )\n    parser.add_argument(\n        \"--workspace-pools-target-burst-bytes\",\n        help=\"\"\"The burst length of the memory pool in bytes per target.\n                Example usage: --workspace-pools-target-burst-bytes=flash:accel:1\"\"\",\n        action=\"append\",\n    )\n\n\ndef _parse_target_burst(attr_str, pool_name):\n    if pool_name not in attr_str:\n        return {}\n\n    return {target: int(attr_str[pool_name][target]) for target in attr_str[pool_name]}\n\n\ndef _parse_target_string(attr_str, targets, pool_name):\n    if attr_str is None:\n        raise TVMCException(f'No target specified for Workspace Pool \"{pool_name}\"')\n\n    target_name = [re.split(\",\", attr_str)]\n    matched_targets = [\n        target\n        for target in targets\n        if any(target.kind.name in target_string_match for target_string_match in target_name[0])\n    ]\n    if not matched_targets:\n        raise TVMCException(f'Workspace Pool \"{pool_name}\" using undefined Target \"{target_name}\"')\n    return matched_targets\n\n\ndef _split_pools_to_pool_names(attr_str):\n    return re.split(\",\", attr_str) if attr_str else []\n\n\ndef _parse_target_attributes_of_pool_name(attr_str, targets):\n    if not targets or attr_str is None:\n        return {}\n\n    target_attributes = {}\n    for pool_values in attr_str:\n        pool_name, target_name, target_value = re.split(\":\", pool_values)\n        if pool_name not in target_attributes:\n            target_attributes[pool_name] = {}\n\n        matched_targets = [target for target in targets if target_name == target.kind.name]\n        if matched_targets:\n            target_attributes[pool_name][matched_targets[0]] = target_value\n        else:\n            raise TVMCException(\n                \"The workspace pool target specification \"\n                \"needs to contain a subset of the same TVM \"\n                \"targets as when specifying targets to use.\"\n            )\n    return target_attributes\n\n\ndef _parse_attribute_of_pool_name(attr_str):\n    return dict(pool.split(\":\", maxsplit=1) for pool in attr_str) if attr_str else {}\n\n\ndef workspace_pools_recombobulate(parsed, targets, extra_target):\n    \"\"\"Reconstructs the Workspace Pools args and returns a WorkspaceMemoryPool object\"\"\"\n    WORKSPACE_POOL_PARAMS = [\n        \"workspace_pools_size_hint_bytes\",\n        \"workspace_pools_targets\",\n        \"workspace_pools_clock_frequency_hz\",\n        \"workspace_pools_read_bandwidth_bytes_per_cycle\",\n        \"workspace_pools_write_bandwidth_bytes_per_cycle\",\n        \"workspace_pools_read_latency_cycles\",\n        \"workspace_pools_write_latency_cycles\",\n    ]\n    WORKSPACE_POOL_TARGET_PARAMS = [\n        \"workspace_pools_target_burst_bytes\",\n    ]\n\n    workspace_pools = _split_pools_to_pool_names(parsed.workspace_pools)\n    if not workspace_pools:\n        return None\n\n    parse_attribute_to_pool_name = {\n        workspace_pool_param: _parse_attribute_of_pool_name(getattr(parsed, workspace_pool_param))\n        for workspace_pool_param in WORKSPACE_POOL_PARAMS\n    }\n    parse_target_burst_bytes_to_pool = {\n        workspace_pool_param: _parse_target_attributes_of_pool_name(\n            getattr(parsed, workspace_pool_param), targets\n        )\n        for workspace_pool_param in WORKSPACE_POOL_TARGET_PARAMS\n    }\n\n    # Load extra targets from CLI\n    additional_targets = []\n\n    for t in extra_target:\n        additional_targets.append(Target(t[\"raw\"], host=targets[0].host or targets[0]))\n\n    target = targets + additional_targets\n    if targets[0].host:\n        target.append(targets[0].host)\n\n    return WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                pool_name,\n                targets=_parse_target_string(\n                    parse_attribute_to_pool_name[\"workspace_pools_targets\"].get(pool_name),\n                    target,\n                    pool_name,\n                ),\n                pool_info_properties=PoolInfoProperties(\n                    size_hint_bytes=int(\n                        parse_attribute_to_pool_name[\"workspace_pools_size_hint_bytes\"].get(\n                            pool_name, -1\n                        )\n                    ),\n                    clock_frequency_hz=int(\n                        parse_attribute_to_pool_name[\"workspace_pools_clock_frequency_hz\"].get(\n                            pool_name, -1\n                        )\n                    ),\n                    read_bandwidth_bytes_per_cycle=int(\n                        parse_attribute_to_pool_name[\n                            \"workspace_pools_read_bandwidth_bytes_per_cycle\"\n                        ].get(pool_name, -1)\n                    ),\n                    write_bandwidth_bytes_per_cycle=int(\n                        parse_attribute_to_pool_name[\n                            \"workspace_pools_write_bandwidth_bytes_per_cycle\"\n                        ].get(pool_name, -1)\n                    ),\n                    read_latency_cycles=int(\n                        parse_attribute_to_pool_name[\"workspace_pools_read_latency_cycles\"].get(\n                            pool_name, 0\n                        )\n                    ),\n                    write_latency_cycles=int(\n                        parse_attribute_to_pool_name[\"workspace_pools_write_latency_cycles\"].get(\n                            pool_name, 0\n                        )\n                    ),\n                    target_burst_bytes=_parse_target_burst(\n                        parse_target_burst_bytes_to_pool[\"workspace_pools_target_burst_bytes\"],\n                        pool_name,\n                    ),\n                ),\n            )\n            for pool_name in workspace_pools\n        ]\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/error.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Structured error classes in TVM.\n\nEach error class takes an error message as its input.\nSee the example sections for suggested message conventions.\nTo make the code more readable, we recommended developers to\ncopy the examples and raise errors with the same message convention.\n\n.. note::\n\n    Please also refer to :ref:`error-handling-guide`.\n\"\"\"\nfrom tvm._ffi.base import register_error, TVMError\n\n\n@register_error\nclass InternalError(TVMError):\n    \"\"\"Internal error in the system.\n\n    Examples\n    --------\n    .. code :: c++\n\n        // Example code C++\n        LOG(FATAL) << \"InternalError: internal error detail.\";\n\n    .. code :: python\n\n        # Example code in python\n        raise InternalError(\"internal error detail\")\n    \"\"\"\n\n    def __init__(self, msg):\n        # Patch up additional hint message.\n        if \"TVM hint:\" not in msg:\n            msg += (\n                \"\\nTVM hint: You hit an internal error. \"\n                + \"Please open a thread on https://discuss.tvm.apache.org/ to report it.\"\n            )\n        super(InternalError, self).__init__(msg)\n\n\nregister_error(\"ValueError\", ValueError)\nregister_error(\"TypeError\", TypeError)\nregister_error(\"AttributeError\", AttributeError)\nregister_error(\"KeyError\", KeyError)\nregister_error(\"IndexError\", IndexError)\n\n\n@register_error\nclass RPCError(TVMError):\n    \"\"\"Error thrown by the remote server handling the RPC call.\"\"\"\n\n\n@register_error\nclass OpError(TVMError):\n    \"\"\"Base class of all operator errors in frontends.\"\"\"\n\n\n@register_error\nclass OpNotImplemented(OpError, NotImplementedError):\n    \"\"\"Operator is not implemented.\n\n    Example\n    -------\n    .. code:: python\n\n        raise OpNotImplemented(\n            \"Operator {} is not supported in {} frontend\".format(\n                missing_op, frontend_name))\n    \"\"\"\n\n\n@register_error\nclass OpAttributeRequired(OpError, AttributeError):\n    \"\"\"Required attribute is not found.\n\n    Example\n    -------\n    .. code:: python\n\n        raise OpAttributeRequired(\n            \"Required attribute {} not found in operator {}\".format(\n                attr_name, op_name))\n    \"\"\"\n\n\n@register_error\nclass OpAttributeInvalid(OpError, AttributeError):\n    \"\"\"Attribute value is invalid when taking in a frontend operator.\n\n    Example\n    -------\n    .. code:: python\n\n        raise OpAttributeInvalid(\n            \"Value {} in attribute {} of operator {} is not valid\".format(\n                value, attr_name, op_name))\n    \"\"\"\n\n\n@register_error\nclass OpAttributeUnImplemented(OpError, NotImplementedError):\n    \"\"\"Attribute is not supported in a certain frontend.\n\n    Example\n    -------\n    .. code:: python\n\n        raise OpAttributeUnImplemented(\n            \"Attribute {} is not supported in operator {}\".format(\n                attr_name, op_name))\n    \"\"\"\n\n\n@register_error\nclass DiagnosticError(TVMError):\n    \"\"\"Error diagnostics were reported during the execution of a pass.\n\n    See the configured diagnostic renderer for detailed error information.\n    \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace of executables python files that directly run throw cmd\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/autotvm_log_editor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Pick best log entries from a large file and store them to a small file\"\"\"\n\nimport argparse\nimport os\nimport logging\nimport warnings\n\nfrom .. import autotvm\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--act\", type=str, choices=[\"pick-best\"], required=True, help=\"The action\")\n    parser.add_argument(\"--i\", type=str, help=\"The input file or directory\", required=True)\n    parser.add_argument(\"--o\", type=str, help=\"The output file\")\n\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n\n    if args.act == \"pick-best\":\n        if os.path.isfile(args.i):\n            args.o = args.o or args.i + \".best.log\"\n            autotvm.record.pick_best(args.i, args.o)\n        elif os.path.isdir(args.i):\n            args.o = args.o or \"best.log\"\n            tmp_filename = args.o + \".tmp\"\n\n            with open(tmp_filename, \"w\") as tmp_fout:\n                for filename in os.listdir(args.i):\n                    if filename.endswith(\".log\"):\n                        try:\n                            autotvm.record.pick_best(filename, tmp_fout)\n                        except Exception:  # pylint: disable=broad-except\n                            warnings.warn(\"Ignore invalid file %s\" % filename)\n\n            logging.info(\"Run final filter...\")\n            autotvm.record.pick_best(tmp_filename, args.o)\n            os.remove(tmp_filename)\n            logging.info(\"Output to %s ...\", args.o)\n        else:\n            raise ValueError(\"Invalid input file: \" + args.i)\n    else:\n        raise ValueError(\"Invalid action \" + args.act)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/measure_peak.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"measure bandwidth and compute peak\n\ne.g.\npython3 -m tvm.exec.measure_peak --target cuda --rpc-host 127.0.0.1 --rpc-port 9090\npython3 -m tvm.exec.measure_peak --target opencl --target-host \"llvm -mtriple=aarch64-linux-gnu\" \\\n        --rpc-host $TVM_OPENCL_DEVICE_HOST --rpc-port 9090\n\"\"\"\n\nimport argparse\nimport logging\n\nfrom tvm.target import Target\nfrom ..contrib.peak import measure_peak_all\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--target\", type=str, default=\"llvm\", help=\"The build target\")\n    parser.add_argument(\n        \"--target-host\", type=str, default=None, help=\"The host code compilation target\"\n    )\n    parser.add_argument(\n        \"--rpc-host\", type=str, default=\"127.0.0.1\", help=\"the hostname of the server\"\n    )\n    parser.add_argument(\"--rpc-port\", type=int, default=9090, help=\"The port of the RPC\")\n\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n\n    args.target, args.target_host = Target.canon_target_and_host(args.target, args.target_host)\n    measure_peak_all(args.target, args.target_host, args.rpc_host, args.rpc_port)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/microtvm_debug_shell.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-outer-name, invalid-name\n\"\"\"Start an RPC server intended for use as a microTVM debugger.\n\nmicroTVM aims to be runtime-agnostic, and to that end, frameworks often define command-line tools\nused to launch a debug flow. These tools often manage the process of connecting to an attached\ndevice using a hardware debugger, exposing a GDB server, and launching GDB connected to that\nserver with a source file attached. It's also true that this debugger can typically not be executed\nconcurrently with any flash tool, so this integration point is provided to allow TVM to launch and\nterminate any debuggers integrated with the larger microTVM compilation/autotuning flow.\n\nTo use this tool, first launch this script in a separate terminal window. Then, provide the hostport\nto your compiler's Flasher instance.\n\"\"\"\n\nimport argparse\nimport logging\nimport socket\nimport struct\n\nimport tvm.micro.debugger as _  # NOTE: imported to expose global PackedFuncs over RPC.\n\nfrom .._ffi.base import py_str\nfrom ..rpc import base\nfrom ..rpc import _ffi_api\n\n\n_LOG = logging.getLogger(__name__)\n\n\ndef parse_args():\n    \"\"\"Parse command line arguments to this script.\"\"\"\n    parser = argparse.ArgumentParser(description=\"microTVM debug-tool runner\")\n    parser.add_argument(\"--host\", default=\"0.0.0.0\", help=\"hostname to listen on\")\n    parser.add_argument(\"--port\", type=int, default=9090, help=\"hostname to listen on\")\n    parser.add_argument(\n        \"--impl\",\n        help=(\n            \"If given, name of a module underneath tvm.micro.contrib \"\n            \"which contains the Debugger implementation to use. For example, to enable a \"\n            \"debugger named BarDebugger in python/tvm/micro/contrib/foo.py, specify either \"\n            \"'tvm.micro.contrib.foo' or 'foo' here. To enable a debugger named BazDebugger in \"\n            \"a third-party module ext_package.debugger, specify 'ext_package.debugger' here. \"\n            \"NOTE: the module cannot be in a sub-package of tvm.micro.contrib.\"\n        ),\n    )\n\n    return parser.parse_args()\n\n\nclass ConnectionClosedError(Exception):\n    \"\"\"Raised when the connection is closed.\"\"\"\n\n\ndef handle_conn(conn, rpc_key):\n    \"\"\"Handle a single connection that has just been accept'd().\"\"\"\n\n    def send(data):\n        conn.sendall(data)\n        return len(data)\n\n    magic = struct.unpack(\"<i\", base.recvall(conn, 4))[0]\n    if magic != base.RPC_MAGIC:\n        conn.close()\n        return\n\n    keylen = struct.unpack(\"<i\", base.recvall(conn, 4))[0]\n    key = py_str(base.recvall(conn, keylen))\n    arr = key.split()\n    expect_header = \"client:\"\n    server_key = \"server:\" + rpc_key\n    if arr[0] != expect_header:\n        conn.sendall(struct.pack(\"<i\", base.RPC_CODE_MISMATCH))\n        _LOG.warning(\"mismatch key from %s\", addr)\n        return\n\n    conn.sendall(struct.pack(\"<i\", base.RPC_CODE_SUCCESS))\n    conn.sendall(struct.pack(\"<i\", len(server_key)))\n    conn.sendall(server_key.encode(\"utf-8\"))\n    server = _ffi_api.CreateEventDrivenServer(send, \"microtvm-rpc-debugger\", key)\n\n    def _readall(n):\n        buf = bytearray()\n        while len(buf) < n:\n            x = conn.recv(n - len(buf))\n            if not x:\n                raise ConnectionClosedError()\n\n            buf = buf + x\n\n        return buf\n\n    while True:\n        packet_length_bytes = _readall(8)\n        packet_length = struct.unpack(\"<q\", packet_length_bytes)[0]\n        if not packet_length:\n            break\n\n        status = server(packet_length_bytes, 3)\n        if status == 0:\n            break\n\n        packet_body = _readall(packet_length)\n        status = server(packet_body, 3)\n\n\ndef main():\n    \"\"\"Main entry point for microTVM debug shell.\"\"\"\n    args = parse_args()\n    logging.basicConfig(level=logging.INFO)\n    if args.impl:\n        package = None\n        if \".\" not in args.impl:\n            package = f\"tvm.micro.contrib.{args.impl}\"\n        importlib.import_module(args.impl, package)\n\n    sock = socket.socket(base.get_addr_family([args.host, args.port]), socket.SOCK_STREAM)\n    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    sock.bind((args.host, args.port))\n    sock.listen(1)\n    bind_addr, bind_port = sock.getsockname()\n    _LOG.info(\"listening for connections on %s:%d\", bind_addr, bind_port)\n\n    while True:\n        conn, peer = sock.accept()\n        _LOG.info(\"accepted connection from %s\", peer)\n        try:\n            handle_conn(conn, \"\")\n        except ConnectionClosedError:\n            pass\n        finally:\n            conn.close()\n            _LOG.info(\"closed connection from %s\", peer)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/popen_worker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Internal PopenWorker for PopenPool.\"\"\"\nimport sys\nimport os\nimport struct\nimport threading\nimport traceback\nimport pickle\nimport logging\nimport cloudpickle\n\nfrom tvm.contrib.popen_pool import StatusKind\n\n\nclass TimeoutStatus:\n    __slot__ = [\"status\"]\n\n    def __init__(self):\n        self.status = StatusKind.RUNNING\n\n\ndef main():\n    \"\"\"Main worker function\"\"\"\n    if len(sys.argv) != 3:\n        print(\"Usage: <read_fd> <write_fd>\")\n        return\n    if sys.platform == \"win32\":\n        # pylint: disable=import-outside-toplevel\n        import msvcrt\n\n        reader = os.fdopen(msvcrt.open_osfhandle(int(sys.argv[1]), os.O_BINARY), \"rb\")\n        writer = os.fdopen(msvcrt.open_osfhandle(int(sys.argv[2]), os.O_BINARY), \"wb\")\n    else:\n        reader = os.fdopen(int(sys.argv[1]), \"rb\")\n        writer = os.fdopen(int(sys.argv[2]), \"wb\")\n\n    logging.basicConfig(level=logging.INFO)\n\n    lock = threading.Lock()\n\n    def _respond(ret_value):\n        \"\"\"Send data back to the client.\"\"\"\n        data = cloudpickle.dumps(ret_value, protocol=pickle.HIGHEST_PROTOCOL)\n        writer.write(struct.pack(\"<i\", len(data)))\n        writer.write(data)\n        writer.flush()\n\n    def _cancel_run(status):\n        lock.acquire()\n        if status.status == StatusKind.RUNNING:\n            _respond((StatusKind.TIMEOUT, TimeoutError()))\n            status.status = StatusKind.TIMEOUT\n        lock.release()\n\n    while True:\n        raw_bytes_size = reader.read(4)\n        if len(raw_bytes_size) != 4:\n            # the parent exited\n            return\n        bytes_size = struct.unpack(\"<i\", raw_bytes_size)[0]\n        fn, args, kwargs, timeout = cloudpickle.loads(reader.read(bytes_size))\n        status = TimeoutStatus()\n\n        if timeout is not None:\n            watcher = threading.Timer(timeout, _cancel_run, [status])\n            watcher.daemon = True\n            watcher.start()\n\n        # pylint: disable=broad-except\n        try:\n            result = fn(*args, **kwargs)\n            ret_value = (StatusKind.COMPLETE, result)\n        except Exception as exception:\n            msg = traceback.format_exc()\n            ret_value = (StatusKind.EXCEPTION, type(exception)(msg))\n\n        if timeout is not None:\n            watcher.cancel()\n\n        lock.acquire()\n        if status.status == StatusKind.RUNNING:\n            _respond(ret_value)\n            status.status = StatusKind.COMPLETE\n        lock.release()\n\n\nif __name__ == \"__main__\":\n    try:\n        main()\n    except (KeyboardInterrupt, IOError):\n        pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/query_rpc_tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tool to query RPC tracker status\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport argparse\nimport os\nfrom .. import rpc\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--host\", type=str, default=\"\", help=\"the hostname of the tracker\")\n    parser.add_argument(\"--port\", type=int, default=None, help=\"The port of the RPC\")\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n\n    # default to local host or environment variable\n    if not args.host:\n        args.host = os.environ.get(\"TVM_TRACKER_HOST\", \"127.0.0.1\")\n\n    if not args.port:\n        args.port = int(os.environ.get(\"TVM_TRACKER_PORT\", \"9190\"))\n\n    conn = rpc.connect_tracker(args.host, args.port)\n    # pylint: disable=superfluous-parens\n    print(\"Tracker address %s:%d\\n\" % (args.host, args.port))\n    print(\"%s\" % conn.text_summary())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/rpc_proxy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-outer-name, invalid-name\n\"\"\"RPC web proxy, allows redirect to websocket based RPC servers(browsers)\"\"\"\nimport logging\nimport argparse\nimport os\nfrom tvm.rpc.proxy import Proxy\n\n\ndef find_example_resource():\n    \"\"\"Find resource examples.\"\"\"\n    curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n    base_path = os.path.abspath(os.path.join(curr_path, \"..\", \"..\", \"..\"))\n    index_page = os.path.join(base_path, \"web\", \"apps\", \"browser\", \"rpc_server.html\")\n    resource_files = [\n        os.path.join(base_path, \"web\", \"dist\", \"tvmjs.bundle.js\"),\n        os.path.join(base_path, \"web\", \"dist\", \"wasm\", \"tvmjs_runtime.wasi.js\"),\n    ]\n    resource_base = os.path.join(base_path, \"web\", \"dist\", \"www\")\n    if os.path.isdir(resource_base):\n        for fname in os.listdir(resource_base):\n            full_name = os.path.join(resource_base, fname)\n            if os.path.isfile(full_name):\n                resource_files.append(full_name)\n    for fname in [index_page] + resource_files:\n        if not os.path.exists(fname):\n            raise RuntimeError(\"Cannot find %s\" % fname)\n    return index_page, resource_files\n\n\ndef main(args):\n    \"\"\"Main function\"\"\"\n    if args.tracker:\n        url, port = args.tracker.split(\":\")\n        port = int(port)\n        tracker_addr = (url, port)\n    else:\n        tracker_addr = None\n\n    if args.example_rpc:\n        index, js_files = find_example_resource()\n        prox = Proxy(\n            args.host,\n            port=args.port,\n            web_port=args.web_port,\n            index_page=index,\n            resource_files=js_files,\n            tracker_addr=tracker_addr,\n        )\n    else:\n        prox = Proxy(args.host, port=args.port, web_port=args.web_port, tracker_addr=tracker_addr)\n    prox.proc.join()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--host\", type=str, default=\"127.0.0.1\", help=\"the hostname of the server\")\n    parser.add_argument(\"--port\", type=int, default=9090, help=\"The port of the RPC\")\n    parser.add_argument(\n        \"--web-port\", type=int, default=8888, help=\"The port of the http/websocket server\"\n    )\n    parser.add_argument(\n        \"--example-rpc\", type=bool, default=False, help=\"Whether to switch on example rpc mode\"\n    )\n    parser.add_argument(\"--tracker\", type=str, default=\"\", help=\"Report to RPC tracker\")\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n    main(args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/rpc_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-outer-name, invalid-name\n\"\"\"Start an RPC server\"\"\"\nimport argparse\nimport logging\nfrom .. import rpc\n\n\ndef main(args):\n    \"\"\"Main function\n\n    Parameters\n    ----------\n    args : argparse.Namespace\n        parsed args from command-line invocation\n    \"\"\"\n    if args.tracker:\n        url, port = args.tracker.rsplit(\":\", 1)\n        port = int(port)\n        tracker_addr = (url, port)\n        if not args.key:\n            raise RuntimeError(\"Need key to present type of resource when tracker is available\")\n    else:\n        tracker_addr = None\n\n    server = rpc.Server(\n        args.host,\n        args.port,\n        args.port_end,\n        is_proxy=args.through_proxy,\n        key=args.key,\n        tracker_addr=tracker_addr,\n        load_library=args.load_library,\n        custom_addr=args.custom_addr,\n        silent=args.silent,\n        no_fork=not args.fork,\n    )\n    server.proc.join()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--host\", type=str, default=\"0.0.0.0\", help=\"The host IP address the tracker binds to\"\n    )\n    parser.add_argument(\"--port\", type=int, default=9090, help=\"The port of the RPC\")\n    parser.add_argument(\n        \"--through-proxy\",\n        dest=\"through_proxy\",\n        action=\"store_true\",\n        help=(\n            \"Whether this server provide service through a proxy. If this is true, the host and\"\n            \"port actually is the address of the proxy.\"\n        ),\n    )\n    parser.add_argument(\"--port-end\", type=int, default=9199, help=\"The end search port of the RPC\")\n    parser.add_argument(\n        \"--tracker\",\n        type=str,\n        help=(\"The address of RPC tracker in host:port format. \" \"e.g. (10.77.1.234:9190)\"),\n    )\n    parser.add_argument(\n        \"--key\", type=str, default=\"\", help=\"The key used to identify the device type in tracker.\"\n    )\n    parser.add_argument(\"--silent\", action=\"store_true\", help=\"Whether run in silent mode.\")\n    parser.add_argument(\"--load-library\", type=str, help=\"Additional library to load\")\n    parser.add_argument(\n        \"--no-fork\",\n        dest=\"fork\",\n        action=\"store_false\",\n        help=\"Use spawn mode to avoid fork. This option \\\n                        is able to avoid potential fork problems with Metal, OpenCL \\\n                        and ROCM compilers.\",\n    )\n    parser.add_argument(\n        \"--custom-addr\", type=str, help=\"Custom IP Address to Report to RPC Tracker\"\n    )\n\n    parser.set_defaults(fork=True)\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n    if not args.fork is False and not args.silent:\n        logging.info(\n            \"If you are running ROCM/Metal, fork will cause \"\n            \"compiler internal error. Try to launch with arg ```--no-fork```\"\n        )\n    main(args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/exec/rpc_tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-outer-name, invalid-name\n\"\"\"Tool to start RPC tracker\"\"\"\nimport logging\nimport argparse\nfrom ..rpc.tracker import Tracker\n\n\ndef main(args):\n    \"\"\"Main function\"\"\"\n    tracker = Tracker(args.host, port=args.port, port_end=args.port_end, silent=args.silent)\n    tracker.proc.join()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--host\", type=str, default=\"0.0.0.0\", help=\"The host IP address the tracker binds to\"\n    )\n    parser.add_argument(\"--port\", type=int, default=9190, help=\"The port of the RPC\")\n    parser.add_argument(\"--port-end\", type=int, default=9199, help=\"The end search port of the RPC\")\n    parser.add_argument(\"--silent\", action=\"store_true\", help=\"Whether run in silent mode.\")\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n    main(args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Generic operators.\"\"\"\n# pylint:disable=unused-wildcard-import, wildcard-import\nfrom .tir.generic import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import\n\"\"\"Common data structures across all IR variants.\"\"\"\nfrom .base import SourceName, Span, Node, EnvFunc, load_json, save_json\nfrom .base import structural_equal, assert_structural_equal, structural_hash\nfrom .type import Type, TypeKind, PrimType, PointerType, TypeVar, GlobalTypeVar, TupleType\nfrom .type import TypeConstraint, FuncType, IncompleteType, RelayRefType\nfrom .tensor_type import TensorType\nfrom .affine_type import TensorAffineType, TupleAffineType\nfrom .type_relation import TypeCall, TypeRelation\nfrom .expr import BaseExpr, PrimExpr, RelayExpr, GlobalVar, Range\nfrom .op import Op, register_op_attr, register_intrin_lowering\nfrom .function import CallingConv, BaseFunc\nfrom .adt import Constructor, TypeData\nfrom .module import IRModule\nfrom .attrs import Attrs, DictAttrs, make_node\nfrom .container import Array, Map\nfrom .memory_pools import (\n    PoolInfo,\n    WorkspacePoolInfo,\n    ConstantPoolInfo,\n    WorkspaceMemoryPools,\n    ConstantMemoryPools,\n    PoolInfoProperties,\n)\n\nfrom . import transform\nfrom . import instrument\nfrom . import diagnostics\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.ir\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"ir\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/_ffi_instrument_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.instrument\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"instrument\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/_ffi_transform_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.transform\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"transform\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/adt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Algebraic data type definitions.\"\"\"\nimport tvm._ffi\n\nfrom .type import Type\nfrom .expr import RelayExpr\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"relay.Constructor\")\nclass Constructor(RelayExpr):\n    \"\"\"Relay ADT constructor.\n\n    Parameters\n    ----------\n    name_hint : str\n        Name of constructor (only a hint).\n\n    inputs : List[Type]\n        Input types.\n\n    belong_to : GlobalTypeVar\n        Denotes which ADT the constructor belongs to.\n    \"\"\"\n\n    def __init__(self, name_hint, inputs, belong_to):\n        self.__init_handle_by_constructor__(_ffi_api.Constructor, name_hint, inputs, belong_to)\n\n    def __call__(self, *args):\n        \"\"\"Call the constructor.\n\n        Parameters\n        ----------\n        args: List[RelayExpr]\n            The arguments to the constructor.\n\n        Returns\n        -------\n        call: RelayExpr\n            A call to the constructor.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from tvm import relay\n\n        return relay.Call(self, args)\n\n\n@tvm._ffi.register_object(\"relay.TypeData\")\nclass TypeData(Type):\n    \"\"\"Stores the definition for an Algebraic Data Type (ADT) in Relay.\n\n    Note that ADT definitions are treated as type-level functions because\n    the type parameters need to be given for an instance of the ADT. Thus,\n    any global type var that is an ADT header needs to be wrapped in a\n    type call that passes in the type params.\n\n    Parameters\n    ----------\n    header: GlobalTypeVar\n        The name of the ADT.\n        ADTs with the same constructors but different names are\n        treated as different types.\n\n    type_vars: List[TypeVar]\n        Type variables that appear in constructors.\n\n    constructors: List[Constructor]\n        The constructors for the ADT.\n    \"\"\"\n\n    def __init__(self, header, type_vars, constructors):\n        self.__init_handle_by_constructor__(_ffi_api.TypeData, header, type_vars, constructors)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/affine_type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Types for quantized Tensors.\"\"\"\nimport tvm._ffi\n\nfrom .base import Node\nfrom . import _ffi_api\n\n\nclass AffineType(Node):\n    \"\"\"The base class of Affine Types.\"\"\"\n\n    def __eq__(self, other):\n        \"\"\"Compare two types for structural equivalence.\"\"\"\n        return bool(tvm.ir.structural_equal(self, other))\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n\n@tvm._ffi.register_object(\"TensorAffineType\")\nclass TensorAffineType(AffineType):\n    \"\"\"The quantized type of a tensor, with scale, zero point, and datatype\n\n    The real space value is calculated as x = x_q * scale + zero_point\n\n    Parameters\n    ----------\n    scale: Expr\n        The scale\n\n    zero_point: Expr\n        The zero_point\n\n    dtype : str\n        The content data type.\n\n    axis : int\n        The axis for per-channel quantization.\n    \"\"\"\n\n    def __init__(self, scale, zero_point, dtype, axis=-1):\n        self.__init_handle_by_constructor__(\n            _ffi_api.TensorAffineType, scale, zero_point, dtype, axis\n        )\n\n\n@tvm._ffi.register_object(\"TupleAffineType\")\nclass TupleAffineType(AffineType):\n    \"\"\"Affine types of a node with multiple outputs\n\n    Parameters\n    ----------\n    types : List[TensorAffineType]\n        The shape of the Tensor\n\n    \"\"\"\n\n    def __init__(self, types):\n        self.__init_handle_by_constructor__(_ffi_api.TupleAffineType, types)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/attrs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" TVM Attribute module, which is mainly used for defining attributes of operators.\"\"\"\nimport tvm._ffi\n\nfrom tvm.runtime import Object\nimport tvm.runtime._ffi_node_api\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object\nclass Attrs(Object):\n    \"\"\"Attribute node, which is mainly use for defining attributes of relay operators.\n\n    Used by function registered in python side, such as compute, schedule and alter_layout.\n    Attrs is passed as the first argument to these functions.\n    \"\"\"\n\n    def list_field_info(self):\n        \"\"\"Get fields information\n\n        Returns\n        -------\n        infos: list of AttrFieldInfo\n            List of field information\n        \"\"\"\n        return _ffi_api.AttrsListFieldInfo(self)\n\n    def keys(self):\n        \"\"\"Get list of names in the attribute.\n\n        Returns\n        -------\n        keys : list of str\n            List of keys\n        \"\"\"\n        return [field.name for field in self.list_field_info()]\n\n    def get_int_tuple(self, key):\n        \"\"\"Get a python int tuple of a key\n\n        Parameters\n        ----------\n        key: str\n\n        Returns\n        -------\n        value: Tuple of int\n        \"\"\"\n        return tuple(x.value for x in self.__getattr__(key))\n\n    def get_int(self, key):\n        \"\"\"Get a python int value of a key\n\n        Parameters\n        ----------\n        key: str\n\n        Returns\n        -------\n        value: int\n        \"\"\"\n        return self.__getattr__(key)\n\n    def get_str(self, key):\n        \"\"\"Get a python int value of a key\n\n        Parameters\n        ----------\n        key: str\n\n        Returns\n        -------\n        value: int\n        \"\"\"\n        return self.__getattr__(key)\n\n    def __getitem__(self, item):\n        return self.__getattr__(item)\n\n\n@tvm._ffi.register_object\nclass DictAttrs(Attrs):\n    \"\"\"Dictionary attributes.\"\"\"\n\n    def _dict(self):\n        \"\"\"Get internal dict\"\"\"\n        return _ffi_api.DictAttrsGetDict(self)\n\n    def keys(self):\n        \"\"\"Get list of names in the attribute.\n\n        Returns\n        -------\n        keys : list of str\n            List of keys\n        \"\"\"\n        return [k for k, _ in self.items()]\n\n    def __getitem__(self, k):\n        return self._dict().__getitem__(k)\n\n    def __contains__(self, k):\n        return self._dict().__contains__(k)\n\n    def items(self):\n        \"\"\"Get items from the map.\"\"\"\n        return self._dict().items()\n\n    def __len__(self):\n        return self._dict().__len__()\n\n\ndef make_node(type_key, **kwargs):\n    \"\"\"Make a new IR node by its type key and fields\n\n    Parameters\n    ----------\n    type_key : str\n        The type key of the node.\n\n    **kwargs : dict\n        The fields of the node.\n\n    Returns\n    -------\n    node : Node\n        The corresponding IR Node\n\n    Note\n    ----\n    If the created node is instance of AttrsNode, then\n    the creator function will also run bound checks and\n    default value setup as supported by Attrs.\n\n    Example\n    -------\n    The following code constructs a IntImm object\n\n    .. code-block:: python\n\n       x = tvm.ir.make_node(\"IntImm\", dtype=\"int32\", value=10)\n       assert isinstance(x, tvm.tir.IntImm)\n       assert x.value == 10\n    \"\"\"\n    args = [type_key]\n    for k, v in kwargs.items():\n        args += [k, v]\n    return tvm.runtime._ffi_node_api.MakeNode(*args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common base structures.\"\"\"\nimport tvm._ffi\n\nimport tvm.error\nimport tvm.runtime._ffi_node_api\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\nfrom . import json_compact\n\n\nclass Node(Object):\n    \"\"\"Base class of all IR Nodes, implements astext function.\"\"\"\n\n    def astext(self, show_meta_data=True, annotate=None):\n        \"\"\"Get the text format of the expression.\n\n        Parameters\n        ----------\n        show_meta_data : bool\n            Whether to include meta data section in the text\n            if there is meta data.\n\n        annotate: Optional[Object->str]\n            Optionally annotate function to provide additional\n            information in the comment block.\n\n        Returns\n        -------\n        text : str\n            The text format of the expression.\n\n        Notes\n        -----\n        The meta data section is necessary to fully parse the text format.\n        However, it can contain dumps that are big (e.g constant weights),\n        so it can be helpful to skip printing the meta data section.\n        \"\"\"\n        return _ffi_api.AsText(self, show_meta_data, annotate)\n\n    def __str__(self):\n        return _ffi_api.PrettyPrint(self)\n\n\n@tvm._ffi.register_object(\"SourceName\")\nclass SourceName(Object):\n    \"\"\"A identifier for a source location.\n\n    Parameters\n    ----------\n    name : str\n        The name of the source.\n    \"\"\"\n\n    def __init__(self, name):\n        self.__init_handle_by_constructor__(_ffi_api.SourceName, name)\n\n\n@tvm._ffi.register_object(\"Span\")\nclass Span(Object):\n    \"\"\"Specifies a location in a source program.\n\n    Parameters\n    ----------\n    source : SourceName\n        The source name.\n\n    lineno : int\n        The line number.\n\n    col_offset : int\n        The column offset of the location.\n    \"\"\"\n\n    def __init__(self, source_name, line, end_line, column, end_column):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Span, source_name, line, end_line, column, end_column\n        )\n\n\n@tvm._ffi.register_object\nclass EnvFunc(Object):\n    \"\"\"Environment function.\n\n    This is a global function object that can be serialized by its name.\n    \"\"\"\n\n    def __call__(self, *args):\n        return _ffi_api.EnvFuncCall(self, *args)\n\n    @property\n    def func(self):\n        return _ffi_api.EnvFuncGetPackedFunc(self)\n\n    @staticmethod\n    def get(name):\n        \"\"\"Get a static env function\n\n        Parameters\n        ----------\n        name : str\n            The name of the function.\n        \"\"\"\n        return _ffi_api.EnvFuncGet(name)\n\n\ndef load_json(json_str):\n    \"\"\"Load tvm object from json_str.\n\n    Parameters\n    ----------\n    json_str : str\n        The json string\n\n    Returns\n    -------\n    node : Object\n        The loaded tvm node.\n    \"\"\"\n\n    try:\n        return tvm.runtime._ffi_node_api.LoadJSON(json_str)\n    except tvm.error.TVMError:\n        json_str = json_compact.upgrade_json(json_str)\n        return tvm.runtime._ffi_node_api.LoadJSON(json_str)\n\n\ndef save_json(node):\n    \"\"\"Save tvm object as json string.\n\n    Parameters\n    ----------\n    node : Object\n        A TVM object to be saved.\n\n    Returns\n    -------\n    json_str : str\n        Saved json string.\n    \"\"\"\n    return tvm.runtime._ffi_node_api.SaveJSON(node)\n\n\ndef structural_equal(lhs, rhs, map_free_vars=False):\n    \"\"\"Check structural equality of lhs and rhs.\n\n    The structural equality is recursively defined in the DAG of IRNodes.\n    There are two kinds of nodes:\n\n    - Graph node: a graph node in lhs can only be mapped as equal to\n      one and only one graph node in rhs.\n    - Normal node: equality is recursively defined without the restriction\n      of graph nodes.\n\n    Vars(tir::Var, TypeVar) and non-constant relay expression nodes are graph nodes.\n    For example, it means that `%1 = %x + %y; %1 + %1` is not structurally equal\n    to `%1 = %x + %y; %2 = %x + %y; %1 + %2` in relay.\n\n    A var-type node(e.g. tir::Var, TypeVar) can be mapped as equal to another var\n    with the same type if one of the following condition holds:\n\n    - They appear in a same definition point(e.g. function argument).\n    - They points to the same VarNode via the same_as relation.\n    - They appear in a same usage point, and map_free_vars is set to be True.\n\n    The rules for var are used to remap variables occurs in function\n    arguments and let-bindings.\n\n    Parameters\n    ----------\n    lhs : Object\n        The left operand.\n\n    rhs : Object\n        The left operand.\n\n    map_free_vars : bool\n        Whether free variables (i.e. variables without a definition site) should be mapped\n        as equal to each other.\n\n    Return\n    ------\n    result : bool\n        The comparison result.\n\n    See Also\n    --------\n    structural_hash\n    assert_strucural_equal\n    \"\"\"\n    lhs = tvm.runtime.convert(lhs)\n    rhs = tvm.runtime.convert(rhs)\n    return bool(tvm.runtime._ffi_node_api.StructuralEqual(lhs, rhs, False, map_free_vars))\n\n\ndef get_first_structural_mismatch(lhs, rhs, map_free_vars=False):\n    \"\"\"Like structural_equal(), but returns the ObjectPaths of the first detected mismatch.\n\n    Parameters\n    ----------\n    lhs : Object\n        The left operand.\n\n    rhs : Object\n        The left operand.\n\n    map_free_vars : bool\n        Whether free variables (i.e. variables without a definition site) should be mapped\n        as equal to each other.\n\n    Returns\n    -------\n    mismatch: Optional[Tuple[ObjectPath, ObjectPath]]\n        `None` if `lhs` and `rhs` are structurally equal.\n        Otherwise, a tuple of two ObjectPath objects that point to the first detected mismtach.\n    \"\"\"\n    lhs = tvm.runtime.convert(lhs)\n    rhs = tvm.runtime.convert(rhs)\n    mismatch = tvm.runtime._ffi_node_api.GetFirstStructuralMismatch(lhs, rhs, map_free_vars)\n    if mismatch is None:\n        return None\n    else:\n        return mismatch.lhs_path, mismatch.rhs_path\n\n\ndef assert_structural_equal(lhs, rhs, map_free_vars=False):\n    \"\"\"Assert lhs and rhs are structurally equal to each other.\n\n    Parameters\n    ----------\n    lhs : Object\n        The left operand.\n\n    rhs : Object\n        The left operand.\n\n    map_free_vars : bool\n        Whether or not shall we map free vars that does\n        not bound to any definitions as equal to each other.\n\n    Raises\n    ------\n    ValueError : if assertion does not hold.\n\n    See Also\n    --------\n    structural_equal\n    \"\"\"\n    lhs = tvm.runtime.convert(lhs)\n    rhs = tvm.runtime.convert(rhs)\n    tvm.runtime._ffi_node_api.StructuralEqual(lhs, rhs, True, map_free_vars)\n\n\ndef structural_hash(node, map_free_vars=False):\n    \"\"\"Compute structural hash of node\n\n    The structural hash value is recursively defined in the DAG of IRNodes.\n    There are two kinds of nodes:\n\n    - Normal node: the hash value is defined by its content and type only.\n    - Graph node: each graph node will be assigned a unique index ordered by the\n      first occurence during the visit. The hash value of a graph node is\n      combined from the hash values of its contents and the index.\n\n    structural_hash is made to be concistent with structural_equal.\n    If two nodes are structurally equal to each other,\n    then their structural hash (with the same map_free_vars option)\n    should be equal to each other as well.\n\n    If the structural hash of two nodes equals to each other,\n    then it is highly likely(except for rare hash value collison cases)\n    that the two nodes are structurally equal to each other.\n\n    Parameters\n    ----------\n    node : Object\n        The input to be hashed.\n\n    map_free_vars : bool\n        If map_free_vars is set to true, we will hash free variables\n        by the order of their occurrences. Otherwise, we will hash by\n        their in-memory pointer address.\n\n    Return\n    ------\n    result : int\n        The hash result\n\n    See Also\n    --------\n    structrual_equal\n    \"\"\"\n    return tvm.runtime._ffi_node_api.StructuralHash(node, map_free_vars)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/container.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Additional container data structures used across IR variants.\"\"\"\nimport tvm._ffi\n\nfrom tvm.runtime import Object\nfrom tvm.runtime.container import getitem_helper\nfrom tvm.runtime import _ffi_api\n\n\n@tvm._ffi.register_object(\"Array\")\nclass Array(Object):\n    \"\"\"Array container of TVM.\n\n    You do not need to create Array explicitly.\n    Normally python list and tuple will be converted automatically\n    to Array during tvm function call.\n    You may get Array in return values of TVM function call.\n    \"\"\"\n\n    def __getitem__(self, idx):\n        return getitem_helper(self, _ffi_api.ArrayGetItem, len(self), idx)\n\n    def __len__(self):\n        return _ffi_api.ArraySize(self)\n\n    def __dir__(self):\n        return sorted(dir(self.__class__) + [\"type_key\"])\n\n    def __getattr__(self, name):\n        if name == \"handle\":\n            raise AttributeError(\"handle is not set\")\n        if name == \"type_key\":\n            return super().__getattr__(name)\n        raise AttributeError(\"%s has no attribute %s\" % (str(type(self)), name))\n\n\n@tvm._ffi.register_object\nclass Map(Object):\n    \"\"\"Map container of TVM.\n\n    You do not need to create Map explicitly.\n    Normally python dict will be converted automatically to Map during tvm function call.\n    You can use convert to create a dict[Object-> Object] into a Map\n    \"\"\"\n\n    def __getitem__(self, k):\n        return _ffi_api.MapGetItem(self, k)\n\n    def __contains__(self, k):\n        return _ffi_api.MapCount(self, k) != 0\n\n    def __iter__(self):\n        akvs = _ffi_api.MapItems(self)\n        for i in range(len(self)):\n            yield akvs[i * 2]\n\n    def __dir__(self):\n        return sorted(dir(self.__class__) + [\"type_key\"])\n\n    def __getattr__(self, name):\n        if name == \"handle\":\n            raise AttributeError(\"handle is not set\")\n        if name == \"type_key\":\n            return super().__getattr__(name)\n        raise AttributeError(\"%s has no attribute %s\" % (str(type(self)), name))\n\n    def keys(self):\n        return iter(self)\n\n    def values(self):\n        akvs = _ffi_api.MapItems(self)\n        for i in range(len(self)):\n            yield akvs[i * 2 + 1]\n\n    def items(self):\n        \"\"\"Get the items from the map\"\"\"\n        akvs = _ffi_api.MapItems(self)\n        return [(akvs[i], akvs[i + 1]) for i in range(0, len(akvs), 2)]\n\n    def __len__(self):\n        return _ffi_api.MapSize(self)\n\n    def get(self, key, default=None):\n        \"\"\"Get an element with a default value.\n\n        Parameters\n        ----------\n        key : object\n            The attribute key.\n\n        default : object\n            The default object.\n\n        Returns\n        -------\n        value: object\n            The result value.\n        \"\"\"\n        return self[key] if key in self else default\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/diagnostics/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"\nThe diagnostic interface to TVM, used for reporting and rendering\ndiagnostic information by the compiler. This module exposes\nthree key abstractions: a Diagnostic, the DiagnosticContext,\nand the DiagnosticRenderer.\n\"\"\"\nimport enum\nimport tvm._ffi\nfrom . import _ffi_api\nfrom ... import get_global_func, register_func, Object\n\n\ndef get_renderer():\n    \"\"\"\n    Get the diagnostic renderer.\n\n    Returns\n    -------\n    renderer: DiagnosticRenderer\n    \"\"\"\n    return _ffi_api.GetRenderer()\n\n\n@tvm.register_func(\"diagnostics.override_renderer\")\ndef override_renderer(render_func):\n    \"\"\"\n    Sets a custom renderer for diagnostics.\n\n    Params\n    ------\n    render_func: Option[Callable[[DiagnosticContext], None]]\n        If the render_func is None it will remove the current custom renderer\n        and return to default behavior.\n    \"\"\"\n    if render_func:\n\n        def _render_factory():\n            return DiagnosticRenderer(render_func)\n\n        register_func(\"diagnostics.OverrideRenderer\", _render_factory, override=True)\n    else:\n        _ffi_api.ClearRenderer()\n\n\nclass DiagnosticLevel(enum.IntEnum):\n    \"\"\"The diagnostic level, see diagnostic.h for more details.\"\"\"\n\n    BUG = 10\n    ERROR = 20\n    WARNING = 30\n    NOTE = 40\n    HELP = 50\n\n\n@tvm._ffi.register_object(\"Diagnostic\")\nclass Diagnostic(Object):\n    \"\"\"A single diagnostic object from TVM.\"\"\"\n\n    def __init__(self, level, span, message):\n        self.__init_handle_by_constructor__(_ffi_api.Diagnostic, level, span, message)\n\n\n@tvm._ffi.register_object(\"DiagnosticRenderer\")\nclass DiagnosticRenderer(Object):\n    \"\"\"\n    A diagnostic renderer, which given a diagnostic context produces a \"rendered\"\n    form of the diagnostics for either human or computer consumption.\n    \"\"\"\n\n    def __init__(self, render_func):\n        self.__init_handle_by_constructor__(_ffi_api.DiagnosticRenderer, render_func)\n\n    def render(self, ctx):\n        \"\"\"\n        Render the provided context.\n\n        Params\n        ------\n        ctx: DiagnosticContext\n            The diagnostic context to render.\n        \"\"\"\n        return _ffi_api.DiagnosticRendererRender(self, ctx)\n\n\n# Register the diagnostic context.\n@tvm._ffi.register_object(\"DiagnosticContext\")\nclass DiagnosticContext(Object):\n    \"\"\"\n    A diagnostic context which records active errors\n    and contains a renderer.\n    \"\"\"\n\n    def __init__(self, module, renderer):\n        self.__init_handle_by_constructor__(_ffi_api.DiagnosticContext, module, renderer)\n\n    def emit(self, diagnostic):\n        \"\"\"Emit a diagnostic.\"\"\"\n        _ffi_api.Emit(self, diagnostic)\n\n    def render(self):\n        \"\"\"Render the current context using its renderer member.\"\"\"\n        _ffi_api.DiagnosticContextRender(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/diagnostics/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for TVM diagnostics.\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"diagnostics\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/expr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common expressions data structures in the IR.\"\"\"\nimport tvm._ffi\n\nfrom .base import Node\nfrom . import _ffi_api\nfrom ..runtime import const, convert\n\n\nclass BaseExpr(Node):\n    \"\"\"Base class of all the expressions.\"\"\"\n\n\nclass PrimExpr(BaseExpr):\n    \"\"\"Base class of all primitive expressions.\n\n    PrimExpr is used in the low-level code\n    optimizations and integer analysis.\n    \"\"\"\n\n\nclass RelayExpr(BaseExpr):\n    \"\"\"Base class of all non-primitive expressions.\"\"\"\n\n    @property\n    def checked_type(self):\n        \"\"\"Get the checked type of tvm.relay.Expr.\n\n        Returns\n        -------\n        checked_type : tvm.relay.Type\n            The checked type.\n        \"\"\"\n        ret = self._checked_type_\n        if ret is None:\n            raise ValueError(\"The type checker has not populated\" \" the checked_type for this node\")\n        return ret\n\n\n@tvm._ffi.register_object(\"GlobalVar\")\nclass GlobalVar(RelayExpr):\n    \"\"\"A global variable in the IR.\n\n    GlobalVar is used to refer to the global functions\n    stored in the IRModule.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the variable.\n    \"\"\"\n\n    def __init__(self, name_hint, type_annot=None):\n        self.__init_handle_by_constructor__(_ffi_api.GlobalVar, name_hint, type_annot)\n\n    def __call__(self, *args):\n        \"\"\"Call the global variable.\n\n        Parameters\n        ----------\n        args: List[RelayExpr]\n            The arguments to the call.\n\n        Returns\n        -------\n        call: BaseExpr\n            A call taking the variable as a function.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        if all(isinstance(x, RelayExpr) for x in args):\n            from tvm import relay\n\n            return relay.Call(self, args)\n        arg_types = [type(x) for x in args]\n        raise RuntimeError(\n            \"Do not know how to handle GlobalVar.__call__ for types {}\".format(arg_types)\n        )\n\n\n@tvm._ffi.register_object\nclass Range(Node):\n    \"\"\"Represent a range in TVM.\n\n    You do not need to create a Range explicitly.\n    Python lists and tuples will be converted automatically to a Range in API functions.\n\n    Parameters\n    ----------\n    begin : PrimExpr\n        The begin value of the range when end is None.\n        Otherwise it is the length of the range.\n\n    end : Optional[PrimExpr]\n        The end value of the range.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n\n    Note\n    ----\n    The constructor creates the range `[begin, end)`\n    if the end argument is not None. Otherwise, it creates `[0, begin)`.\n    \"\"\"\n\n    def __init__(self, begin, end=None, span=None):\n        if end is None:\n            end = convert(begin)\n            begin = const(0, dtype=end.dtype, span=span)\n        self.__init_handle_by_constructor__(_ffi_api.Range, begin, end, span)\n\n    @staticmethod\n    def from_min_extent(min_value, extent, span=None):\n        \"\"\"Construct a Range by min and extent.\n\n        This constructs a range in [min_value, min_value + extent)\n\n        Parameters\n        ----------\n        min_value : PrimExpr\n            The minimum value of the range.\n\n        extent : PrimExpr\n            The extent of the range.\n\n        span : Optional[Span]\n            The location of this itervar in the source code.\n\n        Returns\n        -------\n        rng : Range\n            The constructed range.\n        \"\"\"\n        return _ffi_api.Range_from_min_extent(min_value, extent, span)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/function.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Function defintiions.\"\"\"\nfrom enum import IntEnum\nimport tvm.runtime\n\nfrom .expr import RelayExpr\nfrom . import _ffi_api\n\n\nclass CallingConv(IntEnum):\n    \"\"\"Possible kinds of calling conventions.\"\"\"\n\n    DEFAULT = 0\n    C_PACKED_FUNC = 1\n    DEVICE_KERNEL_LAUNCH = 2\n\n\nclass BaseFunc(RelayExpr):\n    \"\"\"Base class of all functions.\"\"\"\n\n    @property\n    def attrs(self):\n        \"\"\"Return the attrs member of the function.\"\"\"\n        return _ffi_api.BaseFunc_Attrs(self)\n\n    def with_attr(self, attr_key_or_dict, attr_value=None):\n        \"\"\"Create a new copy of the function and update the attribute.\n\n        Parameters\n        ----------\n        attr_key_or_dict : Union[str, dict]\n            The attribute key to use or a dict containing multiple key value pairs.\n\n        attr_value : Object\n            The new attribute value.\n\n        Returns\n        -------\n        func : Function\n            A new copy of the function\n        \"\"\"\n        # make sure we first copy so that we can safely do copy on write\n        # for multiple updates.\n        res = _ffi_api.BaseFuncCopy(self)\n\n        if isinstance(attr_key_or_dict, dict):\n            for key, val in attr_key_or_dict.items():\n                res = _ffi_api.BaseFuncWithAttr(res._move(), key, tvm.runtime.convert(val))\n            return res\n\n        return _ffi_api.BaseFuncWithAttr(\n            res._move(), attr_key_or_dict, tvm.runtime.convert(attr_value)\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/instrument.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Common pass instrumentation across IR variants.\"\"\"\nimport inspect\nimport functools\n\nimport tvm._ffi\nimport tvm.runtime\n\nfrom . import _ffi_instrument_api\n\n\n@tvm._ffi.register_object(\"instrument.PassInstrument\")\nclass PassInstrument(tvm.runtime.Object):\n    \"\"\"A pass instrument implementation.\n\n    To use, a user class can either subclass from PassInstrument\n    directly, or can apply the :py:func:`pass_instrument` wrapper.  In\n    either case, the `enter_pass_ctx`, `exit_pass_ctx`, `should_run`,\n    `run_before_pass`, and `run_after_pass` methods can be defined to\n    adjust the instrument's behavior.  See the no-op implementations\n    in this class definition for more information on each.\n\n    \"\"\"\n\n    def __init__(self):\n        # initialize handle in case pi_cls creation failed.\n        self.handle = None\n        cls = type(self)\n\n        # If the child class declared the method, then use it.\n        # Otherwise, pass None to avoid a C++ -> Python round trip for\n        # a no-op.\n        def get_child_method(name):\n            if getattr(cls, name) is getattr(PassInstrument, name):\n                return None\n\n            return getattr(self, name)\n\n        # Create runtime pass instrument object.\n        # reister instance's enter_pass_ctx,exit_pass_ctx, should_run, run_before_pass and\n        # run_after_pass methods to it if present.\n        self.__init_handle_by_constructor__(\n            _ffi_instrument_api.PassInstrument,\n            cls.__name__,\n            get_child_method(\"enter_pass_ctx\"),\n            get_child_method(\"exit_pass_ctx\"),\n            get_child_method(\"should_run\"),\n            get_child_method(\"run_before_pass\"),\n            get_child_method(\"run_after_pass\"),\n        )\n\n    def enter_pass_ctx(self):\n        \"\"\"Called when entering the instrumented context.\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n    def exit_pass_ctx(self):\n        \"\"\"Called when exiting the instrumented context.\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n    def should_run(self, mod, info):\n        \"\"\"Determine whether to run the pass or not.\n\n        Called once for each pass that is run while the instrumented\n        context is active.\n\n        Parameters\n        ----------\n        mod : tvm.ir.module.IRModule\n\n            The module on which an optimization pass is being run.\n\n        info : tvm.transform.PassInfo\n\n            The pass information.\n\n        Returns\n        -------\n        should_run : bool\n\n            True to run the pass, or False to skip the pass.\n        \"\"\"\n\n    def run_before_pass(self, mod, info):\n        \"\"\"Instrument before the pass runs.\n\n        Called once for each pass that is run while the instrumented\n        context is active.\n\n        Parameters\n        ----------\n        mod : tvm.ir.module.IRModule\n\n            The module on which an optimization pass is being run.\n\n        info : tvm.transform.PassInfo\n\n            The pass information.\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n    def run_after_pass(self, mod, info):\n        \"\"\"Instrument after the pass runs.\n\n        Called once for each pass that is run while the instrumented\n        context is active.\n\n        Parameters\n        ----------\n        mod : tvm.ir.module.IRModule\n\n            The module on which an optimization pass is being run.\n\n        info : tvm.transform.PassInfo\n\n            The pass information.\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n\ndef _wrap_class_pass_instrument(pi_cls):\n    \"\"\"Wrap a python class as pass instrument\"\"\"\n\n    # No additional wrapping needed if the user class already\n    # inherits.\n    if issubclass(pi_cls, PassInstrument):\n        return pi_cls\n\n    class PyPassInstrument(pi_cls, PassInstrument):\n        \"\"\"Internal wrapper class to create a class instance.\"\"\"\n\n        def __init__(self, *args, **kwargs):\n            # initialize handle in case pi_cls creation failed.\n            self.handle = None\n            pi_cls.__init__(self, *args, **kwargs)\n            PassInstrument.__init__(self)\n\n    functools.update_wrapper(PyPassInstrument.__init__, pi_cls.__init__)\n    PyPassInstrument.__name__ = pi_cls.__name__\n    PyPassInstrument.__doc__ = pi_cls.__doc__\n    PyPassInstrument.__module__ = pi_cls.__module__\n    return PyPassInstrument\n\n\ndef pass_instrument(pi_cls=None):\n    \"\"\"Decorate a pass instrument.\n\n    Parameters\n    ----------\n    pi_class : class\n        Instrument class. See example below.\n\n    Examples\n    --------\n\n    .. code-block:: python\n\n        @tvm.instrument.pass_instrument\n        class SkipPass:\n            def __init__(self, skip_pass_name):\n                self.skip_pass_name = skip_pass_name\n\n            # Uncomment to customize\n            # def enter_pass_ctx(self):\n            #    pass\n\n            # Uncomment to customize\n            # def exit_pass_ctx(self):\n            #    pass\n\n            # If pass name contains keyword, skip it by return False. (return True: not skip)\n            def should_run(self, mod, pass_info)\n                if self.skip_pass_name in pass_info.name:\n                    return False\n                return True\n\n            # Uncomment to customize\n            # def run_before_pass(self, mod, pass_info):\n            #    pass\n\n            # Uncomment to customize\n            # def run_after_pass(self, mod, pass_info):\n            #    pass\n\n        skip_annotate = SkipPass(\"AnnotateSpans\")\n        with tvm.transform.PassContext(instruments=[skip_annotate]):\n            tvm.relay.build(mod, \"llvm\")\n    \"\"\"\n\n    def create_pass_instrument(pi_cls):\n        if not inspect.isclass(pi_cls):\n            raise TypeError(\"pi_cls must be a class\")\n\n        return _wrap_class_pass_instrument(pi_cls)\n\n    if pi_cls:\n        return create_pass_instrument(pi_cls)\n    return create_pass_instrument\n\n\n@tvm._ffi.register_object(\"instrument.PassInstrument\")\nclass PassTimingInstrument(tvm.runtime.Object):\n    \"\"\"A wrapper to create a passes time instrument that implemented in C++\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_ffi_instrument_api.MakePassTimingInstrument)\n\n    @staticmethod\n    def render():\n        \"\"\"Retrieve rendered time profile result\n        Returns\n        -------\n        string : string\n            The rendered string result of time profiles\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n            timing_inst = PassTimingInstrument()\n            with tvm.transform.PassContext(instruments=[timing_inst]):\n                relay_mod = relay.transform.InferType()(relay_mod)\n                relay_mod = relay.transform.FoldScaleAxis()(relay_mod)\n                # before exiting the context, get profile results.\n                profiles = timing_inst.render()\n        \"\"\"\n        return _ffi_instrument_api.RenderTimePassProfiles()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/json_compact.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tool to upgrade json from historical versions.\"\"\"\nimport json\nimport tvm.ir\nimport tvm.runtime\n\n\ndef create_updater(node_map, from_ver, to_ver):\n    \"\"\"Create an updater to update json loaded data.\n\n    Parameters\n    ----------\n    node_map : Map[str, Function]\n        Map from type_key to updating function\n\n    from_ver : str\n        Prefix of version that we can accept,\n\n    to_ver : str\n        The target version.\n\n    Returns\n    -------\n    fupdater : function\n        The updater function\n    \"\"\"\n\n    def _updater(data):\n        assert data[\"attrs\"][\"tvm_version\"].startswith(from_ver)\n        nodes = data[\"nodes\"]\n        for idx, item in enumerate(nodes):\n            f = node_map.get(item[\"type_key\"], None)\n            if isinstance(f, list):\n                for fpass in f:\n                    item = fpass(item, nodes)\n            elif f:\n                item = f(item, nodes)\n            nodes[idx] = item\n        data[\"attrs\"][\"tvm_version\"] = to_ver\n        return data\n\n    return _updater\n\n\ndef create_updater_08_to_09():\n    \"\"\"\n    Create an update to upgrade json from v0.8 to v0.9\n\n    Returns\n    -------\n    fupdater : function\n        The updater function\n    \"\"\"\n\n    def _initialize_virtual_device(item, _):\n        if \"virtual_device_\" not in item[\"attrs\"]:\n            item[\"attrs\"][\"virtual_device_\"] = \"0\"\n        return item\n\n    node_map = {\n        # Base IR\n        \"GlobalVar\": _initialize_virtual_device,\n        \"relay.Var\": _initialize_virtual_device,\n        \"relay.Function\": _initialize_virtual_device,\n        \"relay.Tuple\": _initialize_virtual_device,\n        \"relay.Call\": _initialize_virtual_device,\n        \"relay.Let\": _initialize_virtual_device,\n        \"relay.If\": _initialize_virtual_device,\n        \"relay.TupleGetItem\": _initialize_virtual_device,\n        \"relay.RefCreate\": _initialize_virtual_device,\n        \"relay.RefRead\": _initialize_virtual_device,\n        \"relay.RefWrite\": _initialize_virtual_device,\n        \"relay.Match\": _initialize_virtual_device,\n        \"relay.Constant\": _initialize_virtual_device,\n    }\n\n    return create_updater(node_map, \"0.8\", \"0.9\")\n\n\ndef create_updater_07_to_08():\n    \"\"\"Create an update to upgrade json from v0.7 to v0.8\"\"\"\n\n    def _initialize_module_attributes(item, _):\n        assert item[\"type_key\"] == \"IRModule\", \"Only initialize the attributes for IRModules\"\n        if \"attrs\" not in item[\"attrs\"]:\n            item[\"attrs\"][\"attrs\"] = \"0\"\n        return item\n\n    node_map = {\"IRModule\": _initialize_module_attributes}\n    return create_updater(node_map, \"0.7\", \"0.8\")\n\n\ndef create_updater_06_to_07():\n    \"\"\"Create an update to upgrade json from v0.6 to v0.7\n\n    Returns\n    -------\n    fupdater : function\n        The updater function\n    \"\"\"\n\n    def _ftype_var(item, nodes):\n        vindex = int(item[\"attrs\"][\"var\"])\n        item[\"attrs\"][\"name_hint\"] = nodes[vindex][\"attrs\"][\"name\"]\n        # set vindex to null\n        nodes[vindex][\"type_key\"] = \"\"\n        del item[\"attrs\"][\"var\"]\n        assert item[\"type_key\"].startswith(\"relay.\")\n        item[\"type_key\"] = item[\"type_key\"][len(\"relay.\") :]\n        return item\n\n    def _rename(new_name):\n        def _convert(item, _):\n            item[\"type_key\"] = new_name\n            return item\n\n        return _convert\n\n    def _update_tir_var(new_name):\n        def _convert(item, _):\n            item[\"type_key\"] = new_name\n            item[\"attrs\"][\"type_annotation\"] = \"0\"\n            return item\n\n        return _convert\n\n    def _update_global_key(item, _):\n        if \"global_key\" in item:\n            item[\"repr_str\"] = item[\"global_key\"]\n            del item[\"global_key\"]\n        return item\n\n    def _update_from_std_str(key):\n        def _convert(item, nodes):\n            str_val = item[\"attrs\"][key]\n            jdata = json.loads(tvm.ir.save_json(tvm.runtime.String(str_val)))\n            root_idx = jdata[\"root\"]\n            val = jdata[\"nodes\"][root_idx]\n            sidx = len(nodes)\n            nodes.append(val)\n            item[\"attrs\"][key] = \"%d\" % sidx\n            return item\n\n        return _convert\n\n    node_map = {\n        # Base IR\n        \"SourceName\": _update_global_key,\n        \"EnvFunc\": _update_global_key,\n        \"relay.Op\": [_update_global_key, _rename(\"Op\")],\n        \"relay.TypeVar\": [_ftype_var, _update_from_std_str(\"name_hint\")],\n        \"TypeVar\": _update_from_std_str(\"name_hint\"),\n        \"relay.Id\": [_update_from_std_str(\"name_hint\")],\n        \"relay.GlobalTypeVar\": [_ftype_var, _update_from_std_str(\"name_hint\")],\n        \"GlobalTypeVar\": _update_from_std_str(\"name_hint\"),\n        \"relay.Type\": _rename(\"Type\"),\n        \"relay.TupleType\": _rename(\"TupleType\"),\n        \"relay.TypeConstraint\": _rename(\"TypeConstraint\"),\n        \"relay.FuncType\": _rename(\"FuncType\"),\n        \"relay.IncompleteType\": _rename(\"IncompleteType\"),\n        \"relay.TypeRelation\": _rename(\"TypeRelation\"),\n        \"relay.TypeCall\": _rename(\"TypeCall\"),\n        \"relay.Constructor\": _update_from_std_str(\"name_hint\"),\n        \"relay.Module\": _rename(\"IRModule\"),\n        \"relay.SourceName\": _rename(\"SourceName\"),\n        \"relay.Span\": _rename(\"Span\"),\n        \"relay.GlobalVar\": [_rename(\"GlobalVar\"), _update_from_std_str(\"name_hint\")],\n        \"GlobalVar\": _update_from_std_str(\"name_hint\"),\n        \"relay.Pass\": _rename(\"transform.Pass\"),\n        \"relay.PassInfo\": _rename(\"transform.PassInfo\"),\n        \"relay.PassContext\": _rename(\"transform.PassContext\"),\n        \"relay.ModulePass\": _rename(\"transform.ModulePass\"),\n        \"relay.Sequential\": _rename(\"transform.Sequential\"),\n        \"StrMap\": _rename(\"Map\"),\n        # TIR\n        \"Variable\": [_update_tir_var(\"tir.Var\"), _update_from_std_str(\"name\")],\n        \"SizeVar\": [_update_tir_var(\"tir.SizeVar\"), _update_from_std_str(\"name\")],\n        \"StringImm\": [_rename(\"tir.StringImm\"), _update_from_std_str(\"value\")],\n        \"Cast\": _rename(\"tir.Cast\"),\n        \"Add\": _rename(\"tir.Add\"),\n        \"Sub\": _rename(\"tir.Sub\"),\n        \"Mul\": _rename(\"tir.Mul\"),\n        \"Div\": _rename(\"tir.Div\"),\n        \"Mod\": _rename(\"tir.Mod\"),\n        \"FloorDiv\": _rename(\"tir.FloorDiv\"),\n        \"FloorMod\": _rename(\"tir.FloorMod\"),\n        \"Min\": _rename(\"tir.Min\"),\n        \"Max\": _rename(\"tir.Max\"),\n        \"EQ\": _rename(\"tir.EQ\"),\n        \"NE\": _rename(\"tir.NE\"),\n        \"LT\": _rename(\"tir.LT\"),\n        \"LE\": _rename(\"tir.LE\"),\n        \"GT\": _rename(\"tir.GT\"),\n        \"GE\": _rename(\"tir.GE\"),\n        \"And\": _rename(\"tir.And\"),\n        \"Or\": _rename(\"tir.Or\"),\n        \"Not\": _rename(\"tir.Not\"),\n        \"Select\": _rename(\"tir.Select\"),\n        \"Load\": _rename(\"tir.Load\"),\n        \"BufferLoad\": _rename(\"tir.BufferLoad\"),\n        \"Ramp\": _rename(\"tir.Ramp\"),\n        \"Broadcast\": _rename(\"tir.Broadcast\"),\n        \"Shuffle\": _rename(\"tir.Shuffle\"),\n        \"Call\": [_rename(\"tir.Call\"), _update_from_std_str(\"name\")],\n        \"Let\": _rename(\"tir.Let\"),\n        \"Any\": _rename(\"tir.Any\"),\n        \"LetStmt\": _rename(\"tir.LetStmt\"),\n        \"AssertStmt\": _rename(\"tir.AssertStmt\"),\n        \"Store\": _rename(\"tir.Store\"),\n        \"BufferStore\": _rename(\"tir.BufferStore\"),\n        \"BufferRealize\": _rename(\"tir.BufferRealize\"),\n        \"Allocate\": _rename(\"tir.Allocate\"),\n        \"IfThenElse\": _rename(\"tir.IfThenElse\"),\n        \"Evaluate\": _rename(\"tir.Evaluate\"),\n        \"Prefetch\": _rename(\"tir.Prefetch\"),\n        \"AttrStmt\": [_rename(\"tir.AttrStmt\"), _update_from_std_str(\"attr_key\")],\n        \"Layout\": [_rename(\"tir.Layout\"), _update_from_std_str(\"name\")],\n        \"Buffer\": [\n            _rename(\"tir.Buffer\"),\n            _update_from_std_str(\"name\"),\n            _update_from_std_str(\"scope\"),\n        ],\n    }\n    return create_updater(node_map, \"0.6\", \"0.7\")\n\n\ndef upgrade_json(json_str):\n    \"\"\"Update json from a historical version.\n\n    Parameters\n    ----------\n    json_str : str\n        A historical json file.\n\n    Returns\n    -------\n    updated_json : str\n        The updated version.\n    \"\"\"\n    data = json.loads(json_str)\n    from_version = data[\"attrs\"][\"tvm_version\"]\n\n    if from_version.startswith(\"0.6\"):\n        data = create_updater_08_to_09()(create_updater_07_to_08()(create_updater_06_to_07()(data)))\n    elif from_version.startswith(\"0.7\"):\n        data = create_updater_08_to_09()(create_updater_07_to_08()(data))\n    elif from_version.startswith(\"0.8\"):\n        data = create_updater_08_to_09()(data)\n    else:\n        raise ValueError(\"Cannot update from version %s\" % from_version)\n    return json.dumps(data, indent=2)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/memory_pools.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Objects for Memory Pools to be used within the compilation\"\"\"\n\nfrom typing import Optional, List\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.runtime import NDArray\nfrom . import _ffi_api\n\n\n@register_object(\"ir.PoolInfo\")\nclass PoolInfo(Object):\n    \"\"\"PoolInfo object holds information related to memory pools\n    where the statically sized allocate nodes will pooled into.\n    This is a base class for WorkspacePoolInfo and ConstantPoolInfo.\n    \"\"\"\n\n    def __init__(self):\n        pass\n\n\n@register_object(\"ir.PoolInfoProperties\")\nclass PoolInfoProperties(Object):\n    \"\"\"PoolInfo object holds information related to memory pools\n    where the statically sized allocate nodes will pooled into.\n\n    Parameters\n    ----------\n    size_hint_bytes : Optional[int]\n        The expected size hint to be used by the allocator.\n        The default value would be -1 which means the pool\n        is not size restricted.\n\n    clock_frequency_hz : Optional[int]\n        The clock frequency that the memory pool runs at in Hz.\n        If not specified/known, this will default to -1 indicating\n        it hasn't been defined.\n\n    read_bandwidth_bytes_per_cycle : Optional[int]\n        The read bandwidth of the memory pool in bytes/cycle.\n        If not specified/known, this will default to -1 indicating\n        it hasn't been defined.\n\n    write_bandwidth_bytes_per_cycle : Optional[int]\n        The write bandwidth of the memory pool in bytes/cycle.\n        If not specified/known, this will default to -1 indicating\n        it hasn't been defined.\n\n    read_latency_cycles : Optional[int]\n        The read latency of the memory pool in cycles.\n        If not specified/known, this will default to 0.\n\n    write_latency_cycles : Optional[int]\n        The write latency of the memory pool in cycles.\n        If not specified/known, this will default to 0.\n\n    target_burst_bytes : Optional[Union[Dict[Target, int], None]]\n        The burst length of the memory pool in bytes per target.\n        If not specified/known for a given target, a burst length\n        of 1 byte will be assumed.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        size_hint_bytes: Optional[int] = -1,\n        clock_frequency_hz: Optional[int] = -1,\n        read_bandwidth_bytes_per_cycle: Optional[int] = -1,\n        write_bandwidth_bytes_per_cycle: Optional[int] = -1,\n        read_latency_cycles: Optional[int] = 0,\n        write_latency_cycles: Optional[int] = 0,\n        target_burst_bytes=None,\n    ):\n        if not target_burst_bytes:\n            target_burst_bytes = dict()\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.PoolInfoProperties,  # type: ignore # pylint: disable=no-member\n            size_hint_bytes,\n            clock_frequency_hz,\n            read_bandwidth_bytes_per_cycle,\n            write_bandwidth_bytes_per_cycle,\n            read_latency_cycles,\n            write_latency_cycles,\n            target_burst_bytes,\n        )\n\n\n@register_object(\"ir.ConstantInfo\")\nclass ConstantInfo(Object):\n    \"\"\"ConstantInfo object hold information on a constant pool.\n\n    Parameters\n    ----------\n    name_hint : str\n        Name of the constant.\n    byte_offset : int\n        The byte_offset of the constant.\n    data : NDArray\n        The data of the constant.\n    \"\"\"\n\n    def __init__(\n        self,\n        name_hint: str,\n        byte_offset: int,\n        data: NDArray,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ConstantInfo,  # type: ignore # pylint: disable=no-member\n            name_hint,\n            byte_offset,\n            data,\n        )\n\n\n@register_object(\"ir.WorkspacePoolInfo\")\nclass WorkspacePoolInfo(PoolInfo):\n    \"\"\"WorkspacePoolInfo object holds information related to RW memory pools\n    where the statically sized allocate nodes will pooled into.\n\n    Parameters\n    ----------\n    pool_name : str\n        The name of the memory pool\n\n    targets : list[Target]\n        A list of targets which could access the pool\n\n    pool_info_properties : PoolInfoProperties\n        The properties of the pool.\n    \"\"\"\n\n    def __init__(\n        self,\n        pool_name: str,\n        targets,\n        pool_info_properties=None,\n    ):\n        super().__init__()\n\n        if pool_info_properties is None:\n            pool_info_properties = PoolInfoProperties()\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.WorkspacePoolInfo,  # type: ignore # pylint: disable=no-member\n            pool_name,\n            targets,\n            pool_info_properties,\n        )\n\n\n@register_object(\"ir.ConstantPoolInfo\")\nclass ConstantPoolInfo(PoolInfo):\n    \"\"\"ConstantPoolInfo object holds information related to RO memory pools\n    where the statically sized allocate nodes are pooled into.\n\n    Parameters\n    ----------\n    pool_name : str\n        The name of the memory pool\n\n    targets : list[Target]\n        describes which targets could access the pool\n\n    pool_info_properties : PoolInfoProperties\n        The properties of the pool.\n    \"\"\"\n\n    def __init__(\n        self,\n        pool_name: str,\n        targets,  # list[Target]\n        constant_info_arr=None,  # list[ConstantInfo]\n        pool_info_properties=None,\n    ):\n        super().__init__()\n\n        if constant_info_arr is None:\n            constant_info_arr = []\n        if pool_info_properties is None:\n            pool_info_properties = PoolInfoProperties()\n        self.__init_handle_by_constructor__(\n            _ffi_api.ConstantPoolInfo,  # type: ignore # pylint: disable=no-member\n            pool_name,\n            targets,\n            constant_info_arr,\n            pool_info_properties,\n        )\n\n\n@register_object(\"ir.WorkspaceMemoryPools\")\nclass WorkspaceMemoryPools(Object):\n    \"\"\"This object contains a list of WorkspacePoolInfo objects to be used as\n    workspace memory in the compilation\n\n    Parameters\n    ----------\n    pools : List[WorkspacePoolInfo]\n        The list of ConstantPoolInfo objects to be used with the compilation\n    \"\"\"\n\n    def __init__(\n        self,\n        pools: List[WorkspacePoolInfo],\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.WorkspaceMemoryPools, pools  # type: ignore # pylint: disable=no-member\n        )\n\n\n@register_object(\"ir.ConstantMemoryPools\")\nclass ConstantMemoryPools(Object):\n    \"\"\"This object contains a list of ConstantPoolInfo objects to be used as\n    read-only memory in the compilation\n\n    Parameters\n    ----------\n    pools : List[ConstantPoolInfo]\n        The list of ConstantPoolInfo objects to be used with the compilation\n    \"\"\"\n\n    def __init__(\n        self,\n        pools: List[ConstantPoolInfo],\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ConstantMemoryPools, pools  # type: ignore # pylint: disable=no-member\n        )\n\n\n@register_object(\"ir.ConstantMemoryPools\")\nclass AllocatedPoolInfo(Object):\n    \"\"\"Allocate memory in a given pool.\n\n    Parameters\n    ----------\n    pool : PoolInfo\n        The pool in which to allocate memory.\n    allocated_size : int\n        The size of memory to allocate.\n    \"\"\"\n\n    def __init__(\n        self,\n        pool: PoolInfo,\n        allocated_size: int,\n        pool_var_idx: int = 0,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.AllocatedPoolInfo, pool, allocated_size, pool_var_idx  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"IRModule that holds the functions and type definitions.\"\"\"\nfrom typing import Optional\n\nfrom tvm._ffi.base import string_types\nimport tvm._ffi\n\nfrom .base import Node\nfrom . import expr as _expr\nfrom . import type as _ty\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"IRModule\")\nclass IRModule(Node):\n    \"\"\"IRModule that holds functions and type definitions.\n\n    IRModule is the basic unit for all IR transformations across the stack.\n\n    Parameters\n    ----------\n    functions: Optional[dict].\n        Map of global var to BaseFunc\n    \"\"\"\n\n    def __init__(self, functions=None, type_definitions=None):\n        if functions is None:\n            functions = {}\n        elif isinstance(functions, dict):\n            mapped_funcs = {}\n            for k, v in functions.items():\n                if isinstance(k, string_types):\n                    k = _expr.GlobalVar(k)\n                if not isinstance(k, _expr.GlobalVar):\n                    raise TypeError(\"Expect functions to be Dict[GlobalVar, Function]\")\n                mapped_funcs[k] = v\n            functions = mapped_funcs\n        if type_definitions is None:\n            type_definitions = {}\n        elif isinstance(type_definitions, dict):\n            mapped_type_defs = {}\n            for k, v in type_definitions.items():\n                if isinstance(k, string_types):\n                    k = _ty.GlobalTypeVar(k)\n                if not isinstance(k, _ty.GlobalTypeVar):\n                    raise TypeError(\"Expect type_definitions to be Dict[GlobalTypeVar, Type]\")\n                mapped_type_defs[k] = v\n            type_definitions = mapped_type_defs\n        self.__init_handle_by_constructor__(_ffi_api.IRModule, functions, type_definitions)\n\n    def __setitem__(self, var, val):\n        \"\"\"Add a mapping to the module.\n\n        Parameters\n        ---------\n        var: GlobalVar\n            The global variable.\n\n        val: Union[Function, Type]\n            The value.\n        \"\"\"\n        return self._add(var, val, True)\n\n    def _add(self, var, val, update=True):\n        if isinstance(val, _expr.RelayExpr):\n            if isinstance(var, string_types):\n                if _ffi_api.Module_ContainGlobalVar(self, var):\n                    var = _ffi_api.Module_GetGlobalVar(self, var)\n                else:\n                    var = _expr.GlobalVar(var)\n            _ffi_api.Module_Add(self, var, val, update)\n        else:\n            assert isinstance(val, _ty.Type)\n            if isinstance(var, string_types):\n                var = _ty.GlobalTypeVar(var)\n            _ffi_api.Module_AddDef(self, var, val, update)\n\n    def __getitem__(self, var):\n        \"\"\"Lookup a global definition by name or by variable.\n\n        Parameters\n        ----------\n        var: Union[String, GlobalVar, GlobalTypeVar]\n            The name or global variable.\n\n        Returns\n        -------\n        val: Union[Function, Type]\n            The definition referenced by :code:`var` (either a function or type).\n        \"\"\"\n        if isinstance(var, string_types):\n            return _ffi_api.Module_Lookup_str(self, var)\n        if isinstance(var, _expr.GlobalVar):\n            return _ffi_api.Module_Lookup(self, var)\n        return _ffi_api.Module_LookupDef(self, var)\n\n    def update(self, other):\n        \"\"\"Insert functions in another Module to current one.\n\n        Parameters\n        ----------\n        other: IRModule\n            The module to merge into the current Module.\n        \"\"\"\n        if isinstance(other, dict):\n            other = IRModule(other)\n\n        return _ffi_api.Module_Update(self, other)\n\n    def update_func(self, var, func):\n        \"\"\"Update the function corresponding to a global variable in the\n        module.\n\n        Parameters\n        ----------\n        var: GlobalVar\n            The global variable.\n\n        func: tvm.relay.Function\n            The function to be inserted.\n        \"\"\"\n        return _ffi_api.Module_UpdateFunction(self, var, func)\n\n    def get_global_var(self, name):\n        \"\"\"Get a global variable in the function by name.\n\n        Parameters\n        ----------\n        name: str\n            The name of the global variable.\n\n        Returns\n        -------\n        global_var: GlobalVar\n            The global variable mapped to :code:`name`.\n\n        Raises\n        ------\n        tvm.error.TVMError if we cannot find corresponding global var.\n        \"\"\"\n        return _ffi_api.Module_GetGlobalVar(self, name)\n\n    def get_global_vars(self):\n        \"\"\"Collect all global vars defined in this module.\n\n        Returns\n        -------\n        global_vars: Array[GlobalVar]\n            An array of global vars.\n        \"\"\"\n        return _ffi_api.Module_GetGlobalVars(self)\n\n    def get_global_type_vars(self):\n        \"\"\"Collect all global type vars defined in this module.\n\n        Returns\n        -------\n        global_type_vars: Array[GlobalTypeVar]\n            An array of global type vars.\n        \"\"\"\n        return _ffi_api.Module_GetGlobalTypeVars(self)\n\n    def get_global_type_var(self, name):\n        \"\"\"Get a global type variable in the function by name.\n\n        Parameters\n        ----------\n        name: str\n            The name of the global type variable.\n\n        Returns\n        -------\n        global_type_var: GlobalTypeVar\n            The global variable mapped to :code:`name`.\n\n        Raises\n        ------\n        tvm.error.TVMError if we cannot find corresponding global type var.\n        \"\"\"\n        return _ffi_api.Module_GetGlobalTypeVar(self, name)\n\n    def get_constructor(self, tag):\n        \"\"\"Look up an ADT constructor by tag.\n\n        Parameters\n        ----------\n        tag: int\n            The tag for a constructor.\n\n        Returns\n        -------\n        constructor: Constructor\n           The constructor associated with the given tag,\n\n        Raises\n        ------\n        tvm.error.TVMError if the corresponding constructor cannot be found.\n        \"\"\"\n        return _ffi_api.Module_LookupTag(self, tag)\n\n    def get_type(self, name):\n        ty_var = self.get_global_type_var(name)\n        ty_data = self.type_definitions[ty_var]\n        return tuple([ty_var] + list(ty_data.constructors))\n\n    @staticmethod\n    def from_expr(expr, functions=None, type_defs=None):\n        \"\"\"Construct a module from a standalone expression.\n\n        Parameters\n        ----------\n        expr: RelayExpr\n            The starting expression\n\n        global_funcs: Optional[dict]\n            Map of global vars to function definitions\n\n        type_defs: Optional[dict]\n            Map of global type vars to type definitions\n\n        Returns\n        -------\n        mod: Module\n            A module containing the passed definitions,\n            where expr is set as the entry point\n            (wrapped in a function if necessary)\n        \"\"\"\n        funcs = functions if functions is not None else {}\n        defs = type_defs if type_defs is not None else {}\n        return _ffi_api.Module_FromExpr(expr, funcs, defs)\n\n    def _import(self, file_to_import):\n        return _ffi_api.Module_Import(self, file_to_import)\n\n    def import_from_std(self, file_to_import):\n        # TODO(@jroesch): clean up prelude\n        _ffi_api.Module_ImportFromStd(self, file_to_import)\n        return tvm.relay.transform.InferType()(self)\n\n    def __str__(self):\n        return _ffi_api.PrettyPrint(self)\n\n    def __repr__(self):\n        return self.astext()\n\n    def script(self, tir_prefix: str = \"T\", show_meta: bool = False) -> str:\n        \"\"\"Print IRModule into TVMScript\n\n        Parameters\n        ----------\n        tir_prefix : str\n            The tir namespace prefix\n\n        show_meta : bool\n            Whether to show meta information\n\n        Returns\n        -------\n        script : str\n            The TVM Script of the IRModule\n        \"\"\"\n        return tvm._ffi.get_global_func(\"script.AsTVMScript\")(\n            self, tir_prefix, show_meta\n        )  # type: ignore\n\n    def show(self, style: Optional[str] = None) -> None:\n        \"\"\"\n        A sugar for print highlighted TVM script.\n        Parameters\n        ----------\n        style : str, optional\n            Pygments styles extended by \"light\" (default) and \"dark\", by default \"light\"\n        \"\"\"\n        from tvm.script.highlight import cprint  # pylint: disable=import-outside-toplevel\n\n        # Use deferred import to avoid circular import while keeping cprint under tvm/script\n        cprint(self, style=style)\n\n    def get_attr(self, attr_key):\n        \"\"\"Get the IRModule attribute.\n\n        Parameters\n        ----------\n        attr_key : str\n            The attribute key.\n\n        Returns\n        -------\n        attr_value : Any\n            Attribute value\n        \"\"\"\n\n        return _ffi_api.Module_GetAttr(self, attr_key)\n\n    def with_attr(self, attr_key, attr_value):\n        \"\"\"Copy the IRModule and add an attribute to it.\n\n        Parameters\n        ----------\n        attr_key : str\n            The attribute key.\n\n        attr_value : Object\n            The new attribute value.\n\n        Returns\n        -------\n        mod : IRModule\n            A new copy of the IRModule with the attribute\n        \"\"\"\n\n        return _ffi_api.Module_WithAttr(self, attr_key, attr_value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Primitive operators in the TVM IR.\"\"\"\nimport tvm._ffi\nfrom .expr import RelayExpr\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"Op\")\nclass Op(RelayExpr):\n    \"\"\"Primitive operator in the IR.\"\"\"\n\n    def __init__(self):\n        raise RuntimeError(\"Cannot create op, use get instead\")\n\n    @staticmethod\n    def get(op_name):\n        \"\"\"Get the Op for a given name\n\n        Parameters\n        ----------\n        op_name : str\n            The operator name\n\n        Returns\n        -------\n        op : Op\n            The op of the corresponding name\n        \"\"\"\n        return _ffi_api.GetOp(op_name)\n\n    def get_attr(self, attr_name):\n        \"\"\"Get additional attribute about the operator.\n\n        Parameters\n        ----------\n        attr_name : str\n            The attribute name.\n\n        Returns\n        -------\n        value : object\n            The attribute value\n        \"\"\"\n        return _ffi_api.OpGetAttr(self, attr_name)\n\n    def has_attr(self, attr_name):\n        \"\"\"Check whether the operator has additional attribute.\n\n        Parameters\n        ----------\n        attr_name : str\n            The attribute name.\n\n        Returns\n        -------\n        value : bool\n            Whether the operator has additional attribute\n        \"\"\"\n        return _ffi_api.OpHasAttr(self, attr_name)\n\n    def set_attr(self, attr_name, value, plevel=10):\n        \"\"\"Set attribute about the operator.\n\n        Parameters\n        ----------\n        attr_name : str\n            The attribute name\n\n        value : object\n            The attribute value\n\n        plevel : int\n            The priority level\n        \"\"\"\n        _ffi_api.OpSetAttr(self, attr_name, value, plevel)\n\n    def reset_attr(self, attr_name):\n        \"\"\"Reset attribute about the operator.\n\n        Parameters\n        ----------\n        attr_name : str\n            The attribute name\n        \"\"\"\n        _ffi_api.OpResetAttr(self, attr_name)\n\n    def add_type_rel(self, rel_name, type_rel_func=None):\n        \"\"\"Attach the type function corresponding to the return type.\n\n        Parameters\n        ----------\n        rel_name : str\n            The type relation name to register.\n\n        type_rel_func : Optional[function (args: List[Type], attrs: Attrs) -> Type]\n            The backing relation function which can solve an arbitrary relation on variables.\n            Differences with type_rel_func in C++:\n\n            1) When type_rel_func is not None\n\n               a) OpAddTypeRel on C++ side will adjust type_rel_func with TypeReporter to\n                  calling convention of relay type system.\n\n               b) type_rel_func returns output argument's type, return None means can't\n                  infer output's type.\n\n               c) only support single output operators for now, the last argument is output tensor.\n\n            2) when type_rel_func is None, will call predefined type_rel_funcs in relay\n                   according to ``tvm.relay.type_relation.`` + rel_name.\n\n        \"\"\"\n        _ffi_api.OpAddTypeRel(self, rel_name, type_rel_func)\n\n    def add_argument(self, name, type, description):  # pylint: disable=redefined-builtin\n        \"\"\"Add arguments information to the function.\n\n        Parameters\n        ----------\n        name : str\n            The argument name.\n        type : str\n            The argument type.\n        description : str\n            The argument description.\n        \"\"\"\n        _ffi_api.OpAddArgument(self, name, type, description)\n\n    def set_support_level(self, level):\n        \"\"\"Set the support level of op.\n\n        Parameters\n        ----------\n        level : int\n            The support level.\n        \"\"\"\n        _ffi_api.OpSetSupportLevel(self, level)\n\n    def set_num_inputs(self, n):\n        \"\"\"Set the support level of op.\n\n        Parameters\n        ----------\n        n : int\n            The input number.\n        \"\"\"\n        _ffi_api.OpSetNumInputs(self, n)\n\n    def set_attrs_type_key(self, key):\n        \"\"\"Set the attribute type key of op.\n\n        Parameters\n        ----------\n        key : str\n            The type key.\n        \"\"\"\n        _ffi_api.OpSetAttrsTypeKey(self, key)\n\n    @staticmethod\n    def list_op_names():\n        \"\"\"List all the op names in the op registry.\n\n        Returns\n        -------\n        value : List[str]\n            The registered op names\n        \"\"\"\n        return _ffi_api.ListOpNames()\n\n\ndef register_op_attr(op_name, attr_key, value=None, level=10):\n    \"\"\"Register an operator property of an operator by name.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of operator\n\n    attr_key : str\n        The attribute name.\n\n    value : object, optional\n        The value to set\n\n    level : int, optional\n        The priority level\n\n    Returns\n    -------\n    fregister : function\n        Register function if value is not specified.\n    \"\"\"\n\n    def _register(v):\n        \"\"\"internal register function\"\"\"\n        _ffi_api.RegisterOpAttr(op_name, attr_key, v, level)\n        return v\n\n    return _register(value) if value is not None else _register\n\n\ndef register_intrin_lowering(\n    op_name,\n    target,\n    *,\n    f=None,\n    level=10,\n):\n    \"\"\"Register Op lowering function\n\n    Parameters\n    ----------\n    op_name : str\n        The op name\n\n    target : str\n        The target string for given intrinsic lowering function\n\n    f : function, optional\n        The function to be registered.\n\n    level : int\n        The priority level\n\n    Returns\n    -------\n    fregister : function\n        Register op lowering function if f is not specified.\n    \"\"\"\n\n    def _register(f):\n        \"\"\"internal register function\"\"\"\n        _ffi_api.RegisterOpLowerIntrinsic(op_name, f, target, level)\n        return f\n\n    return _register(f) if f is not None else _register\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/supply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Suppliers that are used to guarantee uniqueness of names and GlobalVars.\"\"\"\nimport tvm\nfrom tvm import Object, IRModule\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"NameSupply\")\nclass NameSupply(Object):\n    \"\"\"NameSupply that can be used to generate unique names.\n\n    Parameters\n    ----------\n    prefix: The prefix to be added to the generated names.\n    \"\"\"\n\n    def __init__(self, prefix=\"\"):\n        self.__init_handle_by_constructor__(_ffi_api.NameSupply, prefix)\n\n    def fresh_name(self, name, add_prefix=True):\n        \"\"\"Generates a unique name from this NameSupply.\n\n        Parameters\n        ----------\n        name: String\n            The name from which the generated name is derived.\n\n        add_prefix: bool\n            If set to true, then the prefix of this NameSupply will be prepended to the name.\n        \"\"\"\n        return _ffi_api.NameSupply_FreshName(self, name, add_prefix)\n\n    def reserve_name(self, name, add_prefix=True):\n        \"\"\"Reserves an existing name with this NameSupply.\n\n        Parameters\n        ----------\n        name: String\n            The name to be reserved.\n\n        add_prefix: bool\n            If set to true, then the prefix of this NameSupply will be prepended to the name\n            before reserving it.\n        \"\"\"\n        return _ffi_api.NameSupply_ReserveName(self, name, add_prefix)\n\n    def contains_name(self, name, add_prefix=True):\n        \"\"\"Checks if this NameSupply already generated a name.\n\n        Parameters\n        ----------\n        name: String\n            The name to check.\n\n        add_prefix: bool\n            If set to true, then the prefix of this NameSupply will be prepended to the name\n            before checking for it.\n        \"\"\"\n        return _ffi_api.NameSupply_ContainsName(self, name, add_prefix)\n\n\n@tvm._ffi.register_object(\"GlobalVarSupply\")\nclass GlobalVarSupply(Object):\n    \"\"\"GlobalVarSupply that holds a mapping between names and GlobalVars.\n\n    GlobalVarSupply can be used to generate new GlobalVars with a unique name.\n    It also can be used to retrieve previously generated GlobalVars based on a name.\n\n    Parameters\n    ----------\n    value: Union[List[IRModule], IRModule, NameSupply]\n        The IRModules used to build this GlobalVarSupply or a NameSupply.\n    \"\"\"\n\n    def __init__(self, value=None):\n        if value is None:\n            name_supply = NameSupply(\"\")\n            self.__init_handle_by_constructor__(_ffi_api.GlobalVarSupply_NameSupply, name_supply)\n        elif isinstance(value, NameSupply):\n            self.__init_handle_by_constructor__(_ffi_api.GlobalVarSupply_NameSupply, value)\n        elif isinstance(value, (list, tvm.container.Array)):\n            self.__init_handle_by_constructor__(_ffi_api.GlobalVarSupply_IRModules, value)\n        elif isinstance(value, IRModule):\n            self.__init_handle_by_constructor__(_ffi_api.GlobalVarSupply_IRModule, value)\n\n    def fresh_global(self, name, add_prefix=True):\n        \"\"\"Generates a unique GlobalVar from this supply.\n\n        Parameters\n        ----------\n        name: String\n            The name from which the name of the GlobalVar is derived.\n\n        add_prefix: bool\n            If set to true, then the prefix of the contained NameSupply will be prepended\n            to the name.\n        \"\"\"\n        return _ffi_api.GlobalVarSupply_FreshGlobal(self, name, add_prefix)\n\n    def unique_global_for(self, name, add_prefix=True):\n        \"\"\"Looks up for a GlobalVar with the given name in this supply. If no entry is found\n        , creates one, places it in the cache and returns it.\n\n        Parameters\n        ----------\n        name: String\n            The name of the GlobalVar to search for.\n\n        add_prefix: bool\n            If set to true, the prefix of the contained NameSupply will be prepended to the\n            name before performing the search.\n        \"\"\"\n        return _ffi_api.GlobalVarSupply_UniqueGlobalFor(self, name, add_prefix)\n\n    def reserve_global(self, global_var, allow_conflict=False):\n        \"\"\"Reserves an existing GlobalVar with this supply.\n\n        Parameters\n        ----------\n        global_var: GlobalVar\n            The GlobalVar to be registered.\n\n        allow_conflict: bool\n            Allow conflict with other GlobalVars that have the same name\n        \"\"\"\n        return _ffi_api.GlobalVarSupply_ReserveGlobalVar(self, global_var, allow_conflict)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/tensor_type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Type relation and function for type checking.\"\"\"\nimport tvm._ffi\n\nfrom .type import Type\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"relay.TensorType\")\nclass TensorType(Type):\n    \"\"\"A concrete TensorType in Relay.\n\n    This is the type assigned to tensors with a known dtype and shape.\n    For example, a tensor of `float32` and `(5, 5)`.\n\n    Parameters\n    ----------\n    shape : List[tvm.ir.PrimExpr]\n        The shape of the Tensor\n\n    dtype : Optional[str]\n        The content data type.\n    \"\"\"\n\n    def __init__(self, shape, dtype=\"float32\"):\n        self.__init_handle_by_constructor__(_ffi_api.TensorType, shape, dtype)\n\n    @property\n    def concrete_shape(self):\n        \"\"\"Get shape of the type as concrete tuple of int.\n\n        Returns\n        -------\n        shape : List[int]\n            The concrete shape of the Type.\n\n        Raises\n        ------\n        TypeError : If the shape is symbolic\n        \"\"\"\n        return tuple(int(x) for x in self.shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Common pass infrastructure across IR variants.\"\"\"\nimport types\nimport inspect\nimport functools\n\nimport tvm._ffi\nimport tvm.runtime\n\nfrom . import _ffi_transform_api\n\n\n@tvm._ffi.register_object(\"transform.PassInfo\")\nclass PassInfo(tvm.runtime.Object):\n    \"\"\"The class contains the meta data required by a pass. It is the\n    container of information needed by running an optimization or analysis.\n    This class can be extended by adding new members when more meta data is\n    needed.\n\n    Parameters\n    ----------\n    opt_level : int\n        The optimization level of this pass.\n\n    name : str\n        The pass name.\n\n    required : List[str]\n        The list of passes that are required by a certain pass.\n    \"\"\"\n\n    def __init__(self, opt_level, name, required=None):\n        self.__init_handle_by_constructor__(_ffi_transform_api.PassInfo, opt_level, name, required)\n\n\n@tvm._ffi.register_object(\"transform.PassContext\")\nclass PassContext(tvm.runtime.Object):\n    \"\"\"The basis where a Relay optimization/analysis runs on.\n    Each pass context contains a number of auxiliary information that is used\n    to help an optimization pass. Such information includes the error reporter\n    to record the errors of during the optimization, etc.\n\n    opt_level : Optional[int]\n        The optimization level of this pass.\n\n    required_pass : Optional[Union[List[str], Set[str], Tuple[str]]]\n        The list of passes that are required by a certain pass.\n\n    disabled_pass : Optional[Union[List[str], Set[str], Tuple[str]]]\n        The list of passes that are disabled.\n\n    instruments : Optional[Sequence[PassInstrument]]\n        The list of pass instrument implementations.\n\n    config : Optional[Dict[str, Object]]\n        Additional configurations for specific passes.\n    \"\"\"\n\n    def __init__(\n        self,\n        opt_level=2,\n        required_pass=None,\n        disabled_pass=None,\n        instruments=None,\n        config=None,\n    ):\n        required = list(required_pass) if required_pass else []\n        if not isinstance(required, (list, tuple)):\n            raise TypeError(\"required_pass is expected to be the type of \" + \"list/tuple/set.\")\n\n        disabled = list(disabled_pass) if disabled_pass else []\n        if not isinstance(disabled, (list, tuple)):\n            raise TypeError(\"disabled_pass is expected to be the type of \" + \"list/tuple/set.\")\n\n        instruments = list(instruments) if instruments else []\n        if not isinstance(instruments, (list, tuple)):\n            raise TypeError(\"instruments is expected to be the type of \" + \"list/tuple/set.\")\n\n        config = config if config else None\n        self.__init_handle_by_constructor__(\n            _ffi_transform_api.PassContext, opt_level, required, disabled, instruments, config\n        )\n\n    def __enter__(self):\n        _ffi_transform_api.EnterPassContext(self)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        _ffi_transform_api.ExitPassContext(self)\n\n    def override_instruments(self, instruments):\n        \"\"\"Override instruments within this PassContext.\n\n        If there are existing instruments, their ``exit_pass_ctx`` callbacks are called.\n        Then switching to new instruments and calling new ``enter_pass_ctx`` callbacks.\n\n        instruments : Sequence[PassInstrument]\n            The list of pass instrument implementations.\n        \"\"\"\n        _ffi_transform_api.OverrideInstruments(self, instruments)\n\n    @staticmethod\n    def current():\n        \"\"\"Return the current pass context.\"\"\"\n        return _ffi_transform_api.GetCurrentPassContext()\n\n    @staticmethod\n    def list_configs():\n        \"\"\"List all registered `PassContext` configuration names and metadata.\n\n        Returns\n        -------\n        configs : Dict[str, Dict[str, str]]\n\n        \"\"\"\n        return _ffi_transform_api.ListConfigs()\n\n\n@tvm._ffi.register_object(\"transform.Pass\")\nclass Pass(tvm.runtime.Object):\n    \"\"\"The base class of all passes. All methods here are just simple wrappers\n    that are implemented in the backend. They are defined for users to\n    conveniently interact with the base class.\n    \"\"\"\n\n    @property\n    def info(self):\n        \"\"\"Get the pass meta.\"\"\"\n        return _ffi_transform_api.Info(self)\n\n    def __call__(self, mod):\n        \"\"\"Execute the pass. Note that for sequential pass, the dependency among\n        different passes will be resolved in the backend.\n\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            The module that a certain optimization is performed on.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The updated module after applying this pass.\n        \"\"\"\n        return _ffi_transform_api.RunPass(self, mod)\n\n\n@tvm._ffi.register_object(\"transform.ModulePass\")\nclass ModulePass(Pass):\n    \"\"\"A pass that works on tvm.IRModule. Users don't need to interact with\n    this class directly. Instead, a module pass should be created through\n    `module_pass`, because the design of the `module_pass` API is flexible\n    enough to handle the creation of a module pass in different manners. In\n    addition, all members of a module pass can be accessed from the base class.\n    The same rule applies to FunctionPass as well.\n    \"\"\"\n\n\n@tvm._ffi.register_object(\"transform.Sequential\")\nclass Sequential(Pass):\n    \"\"\"A pass that works on a sequence of pass objects. Multiple passes can be\n    executed sequentially using this class.\n\n    Note that users can also provide a series of passes that they don't want to\n    apply when running a sequential pass. Pass dependency will be resolved in\n    the backend as well.\n\n    Parameters\n    ----------\n    passes : Optional[List[Pass]]\n        A sequence of passes candidate for optimization.\n\n    opt_level : Optional[int]\n        The optimization level of this sequential pass.\n        The opt_level of a default sequential pass is set to 0.\n        Note that some of the passes within the Sequantial may still not be executed\n        if their opt_level is higher than the provided opt_level.\n\n    name : Optional[str]\n        The name of the sequential pass.\n\n    required : Optional[List[str]]\n        The list of passes that the sequential pass is dependent on.\n    \"\"\"\n\n    def __init__(self, passes=None, opt_level=0, name=\"sequential\", required=None):\n        passes = passes if passes else []\n        if not isinstance(passes, (list, tuple)):\n            raise TypeError(\"passes must be a list of Pass objects.\")\n\n        required = required if required else []\n        if not isinstance(required, (list, tuple)):\n            raise TypeError(\"Required is expected to be the type of list/tuple.\")\n\n        self.__init_handle_by_constructor__(\n            _ffi_transform_api.Sequential, passes, opt_level, name, required\n        )\n\n\ndef _wrap_class_module_pass(pass_cls, pass_info):\n    \"\"\"Wrap a python class as function pass\"\"\"\n\n    class PyModulePass(ModulePass):\n        \"\"\"Internal wrapper class to create a class instance.\"\"\"\n\n        def __init__(self, *args, **kwargs):\n            # initialize handle in cass pass_cls creation failed.fg\n            self.handle = None\n            inst = pass_cls(*args, **kwargs)\n\n            # it is important not to capture self to\n            # avoid a cyclic dependency\n            def _pass_func(mod, ctx):\n                return inst.transform_module(mod, ctx)\n\n            self.__init_handle_by_constructor__(\n                _ffi_transform_api.MakeModulePass, _pass_func, pass_info\n            )\n            self._inst = inst\n\n        def __getattr__(self, name):\n            # fall back to instance attribute if there is not any\n            return self._inst.__getattribute__(name)\n\n    functools.update_wrapper(PyModulePass.__init__, pass_cls.__init__)\n    PyModulePass.__name__ = pass_cls.__name__\n    PyModulePass.__doc__ = pass_cls.__doc__\n    PyModulePass.__module__ = pass_cls.__module__\n    return PyModulePass\n\n\ndef module_pass(pass_func=None, opt_level=None, name=None, required=None):\n    \"\"\"Decorate a module pass.\n\n    This function returns a callback when pass_func is provided.\n    Otherwise, it serves a decorator function.\n\n    pass_func can also be a class type with a method transform_module.\n    This function will create a decorated ModulePass using transform_module\n    as the pass function.\n\n    Parameters\n    ----------\n    pass_func : Optional[Callable[(Module, PassContext) ->Module]]\n        The transformation function or class.\n\n    opt_level : int\n        The optimization level of this module pass.\n\n    name : Optional[str]\n        The name of the module pass. The name could be empty. In this case, the\n        name of the optimization function will be used as the pass name.\n\n    required : Optional[List[str]]\n        The list of passes that the module pass is dependent on.\n\n    Returns\n    -------\n    create_module_pass : Union[Callable, ModulePass]\n        A decorator will be returned if pass_func is not provided,\n        otherwise return the decorated result.\n        The returned decorator has two behaviors depending on the input:\n        A new ModulePass will be returned when we decorate a pass function.\n        A new ModulePass class will be returned when we decorate a class type.\n\n    Examples\n    --------\n    The following code block decorates a module pass class.\n\n    .. code-block:: python\n\n        @relay.transform.module_pass\n        class CustomPipeline:\n            def __init__(self, enable_fold):\n                self.enable_fold = enable_fold\n                self.cse = relay.transform.EliminateCommonSubexpr()\n                self.const_fold = relay.transform.FoldConstant()\n\n            def transform_module(self, mod, ctx):\n                mod = self.cse(mod, ctx)\n                if self.enable_fold:\n                    mod = self.const_fold(mod, ctx)\n                return mod\n\n        # create an instance of customized pipeline\n        pipeline = CustomPipeline(enable_fold=False)\n        assert isinstance(pipeline, transform.ModulePass)\n        # run the pipeline.\n        output_module = pipeline(input_module)\n\n    The following code creates a module pass by decorating\n    a user defined transform function.\n\n    .. code-block:: python\n\n        @relay.transform.module_pass(opt_level=2)\n        def transform(mod, ctx):\n            tp = relay.TensorType((10,), \"float32\")\n            x = relay.var(\"x\", tp)\n            gv = relay.GlobalVar(\"var\")\n            func = relay.Function([x], relay.abs(x))\n            new_mod = tvm.IRModule({gv: func})\n            new_mod.update(mod)\n            return new_mod\n\n        module_pass = transform\n        assert isinstance(module_pass, transform.ModulePass)\n        assert module_pass.info.opt_level == 2\n\n        # Given a module m, the optimization could be invoked as the follwoing:\n        updated_mod = module_pass(m)\n        # Now a function abs should be added to the module m.\n    \"\"\"\n    if opt_level is None:\n        raise ValueError(\"Please provide opt_level for the module pass.\")\n\n    required = required if required else []\n    if not isinstance(required, (list, tuple)):\n        raise TypeError(\"Required is expected to be the type of \" + \"list/tuple.\")\n\n    def create_module_pass(pass_arg):\n        \"\"\"Internal function that creates a module pass\"\"\"\n        fname = name if name else pass_arg.__name__\n        info = PassInfo(opt_level, fname, required)\n        if inspect.isclass(pass_arg):\n            return _wrap_class_module_pass(pass_arg, info)\n        if not isinstance(pass_arg, (types.FunctionType, types.LambdaType)):\n            raise TypeError(\"pass_func must be a callable for Module pass\")\n        return _ffi_transform_api.MakeModulePass(pass_arg, info)\n\n    if pass_func:\n        return create_module_pass(pass_func)\n    return create_module_pass\n\n\ndef PrintIR(header=\"\", show_meta_data=False):\n    \"\"\"A special trace pass that prints the header and IR.\n\n    Parameters\n    ----------\n    header : str\n        The header to be displayed along with the dump.\n\n    show_meta_data : bool\n        A boolean flag to indicate if meta data should be printed.\n\n    Returns\n    --------\n    The pass\n    \"\"\"\n    return _ffi_transform_api.PrintIR(header, show_meta_data)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unified type system in the project.\"\"\"\nfrom enum import IntEnum\nimport tvm\nimport tvm._ffi\n\nfrom .base import Node\nfrom . import _ffi_api\n\n\nclass Type(Node):\n    \"\"\"The base class of all types.\"\"\"\n\n    def __eq__(self, other):\n        \"\"\"Compare two types for structural equivalence.\"\"\"\n        return bool(tvm.ir.structural_equal(self, other))\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def same_as(self, other):\n        \"\"\"Compares two Relay types by referential equality.\"\"\"\n        return super().__eq__(other)\n\n\nclass TypeKind(IntEnum):\n    \"\"\"Possible kinds of TypeVars.\"\"\"\n\n    Type = 0\n    ShapeVar = 1\n    BaseType = 2\n    Constraint = 4\n    AdtHandle = 5\n    TypeData = 6\n\n\n@tvm._ffi.register_object(\"PrimType\")\nclass PrimType(Type):\n    \"\"\"Primitive data type in the low level IR\n\n    Parameters\n    ----------\n    dtype : str\n        The runtime data type relates to the primtype.\n    \"\"\"\n\n    def __init__(self, dtype):\n        self.__init_handle_by_constructor__(_ffi_api.PrimType, dtype)\n\n\n@tvm._ffi.register_object(\"PointerType\")\nclass PointerType(Type):\n    \"\"\"PointerType used in the low-level TIR.\n\n    Parameters\n    ----------\n    element_type : tvm.ir.Type\n        The type of pointer's element.\n\n    storage_scope : str\n        The storage scope into which the pointer addresses.\n    \"\"\"\n\n    def __init__(self, element_type, storage_scope=\"\"):\n        self.__init_handle_by_constructor__(_ffi_api.PointerType, element_type, storage_scope)\n\n\n@tvm._ffi.register_object(\"TypeVar\")\nclass TypeVar(Type):\n    \"\"\"Type parameter in functions.\n\n    A type variable represents a type placeholder which will\n    be filled in later on. This allows the user to write\n    functions which are generic over types.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the type variable. This name only acts as a hint, and\n        is not used for equality.\n\n    kind : Optional[TypeKind]\n        The kind of the type parameter.\n    \"\"\"\n\n    def __init__(self, name_hint, kind=TypeKind.Type):\n        self.__init_handle_by_constructor__(_ffi_api.TypeVar, name_hint, kind)\n\n    def __call__(self, *args):\n        \"\"\"Create a type call from this type.\n\n        Parameters\n        ----------\n        args: List[Type]\n            The arguments to the type call.\n\n        Returns\n        -------\n        call: Type\n            The result type call.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from .type_relation import TypeCall\n\n        return TypeCall(self, args)\n\n\n@tvm._ffi.register_object(\"GlobalTypeVar\")\nclass GlobalTypeVar(Type):\n    \"\"\"A global type variable that is used for defining new types or type aliases.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the type variable. This name only acts as a hint, and\n        is not used for equality.\n\n    kind : Optional[TypeKind]\n        The kind of the type parameter.\n    \"\"\"\n\n    def __init__(self, name_hint, kind=TypeKind.AdtHandle):\n        self.__init_handle_by_constructor__(_ffi_api.GlobalTypeVar, name_hint, kind)\n\n    def __call__(self, *args):\n        \"\"\"Create a type call from this type.\n\n        Parameters\n        ----------\n        args: List[Type]\n            The arguments to the type call.\n\n        Returns\n        -------\n        call: Type\n            The result type call.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from .type_relation import TypeCall\n\n        return TypeCall(self, args)\n\n\n@tvm._ffi.register_object(\"TupleType\")\nclass TupleType(Type):\n    \"\"\"The type of tuple values.\n\n    Parameters\n    ----------\n    fields : List[Type]\n        The fields in the tuple\n    \"\"\"\n\n    def __init__(self, fields):\n        self.__init_handle_by_constructor__(_ffi_api.TupleType, fields)\n\n\n@tvm._ffi.register_object(\"TypeConstraint\")\nclass TypeConstraint(Type):\n    \"\"\"Abstract class representing a type constraint.\"\"\"\n\n\n@tvm._ffi.register_object(\"FuncType\")\nclass FuncType(Type):\n    \"\"\"Function type.\n\n    A function type consists of a list of type parameters to enable\n    the definition of generic functions,\n    a set of type constraints which we omit for the time being,\n    a sequence of argument types, and a return type.\n\n    We can informally write them as:\n    `forall (type_params), (arg_types) -> ret_type where type_constraints`\n\n    Parameters\n    ----------\n    arg_types : List[tvm.relay.Type]\n        The argument types\n\n    ret_type : tvm.relay.Type\n        The return type.\n\n    type_params : Optional[List[tvm.relay.TypeVar]]\n        The type parameters\n\n    type_constraints : Optional[List[tvm.relay.TypeConstraint]]\n        The type constraints.\n    \"\"\"\n\n    def __init__(self, arg_types, ret_type, type_params=None, type_constraints=None):\n        if type_params is None:\n            type_params = []\n        if type_constraints is None:\n            type_constraints = []\n        self.__init_handle_by_constructor__(\n            _ffi_api.FuncType, arg_types, ret_type, type_params, type_constraints\n        )\n\n\n@tvm._ffi.register_object(\"IncompleteType\")\nclass IncompleteType(Type):\n    \"\"\"Incomplete type during type inference.\n\n    kind : Optional[TypeKind]\n        The kind of the incomplete type.\n    \"\"\"\n\n    def __init__(self, kind=TypeKind.Type):\n        self.__init_handle_by_constructor__(_ffi_api.IncompleteType, kind)\n\n\n@tvm._ffi.register_object(\"relay.RefType\")\nclass RelayRefType(Type):\n    \"\"\"Reference Type in relay.\n\n    Parameters\n    ----------\n    value: Type\n        The value type.\n    \"\"\"\n\n    def __init__(self, value):\n        self.__init_handle_by_constructor__(_ffi_api.RelayRefType, value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/ir/type_relation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Type relation and function for type checking.\"\"\"\nimport tvm._ffi\n\nfrom .type import Type, TypeConstraint\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"TypeCall\")\nclass TypeCall(Type):\n    \"\"\"Type function application.\n\n    Parameters\n    ----------\n    func: tvm.ir.Type\n        The function.\n\n    args: List[tvm.ir.Type]\n        The arguments.\n\n    Returns\n    -------\n    type_call: TypeCall\n        The type function application.\n    \"\"\"\n\n    def __init__(self, func, args):\n        self.__init_handle_by_constructor__(_ffi_api.TypeCall, func, args)\n\n\n@tvm._ffi.register_object(\"TypeRelation\")\nclass TypeRelation(TypeConstraint):\n    \"\"\"User defined type relation, it is an input-output relation on types.\n\n    TypeRelation is more generalized than TypeCall as it allows inference\n     of both inputs and outputs.\n\n    Parameters\n    ----------\n    func : EnvFunc\n        User defined relation function.\n\n    args : [tvm.ir.Type]\n        List of types to the func.\n\n    num_inputs : int\n        Number of input arguments in args,\n        this act as a hint for type inference.\n\n    attrs : Attrs\n        The attribute attached to the relation information\n\n    Returns\n    -------\n    type_relation : tvm.ir.TypeRelation\n        The type relation.\n    \"\"\"\n\n    def __init__(self, func, args, num_inputs, attrs):\n        self.__init_handle_by_constructor__(_ffi_api.TypeRelation, func, args, num_inputs, attrs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package `tvm.meta_schedule`. The meta schedule infrastructure.\"\"\"\nfrom . import (\n    arg_info,\n    builder,\n    cost_model,\n    database,\n    feature_extractor,\n    measure_callback,\n    mutator,\n    postproc,\n    relay_integration,\n    runner,\n    schedule,\n    schedule_rule,\n    search_strategy,\n    space_generator,\n    tir_integration,\n    trace_apply,\n)\nfrom .builder import Builder\nfrom .cost_model import CostModel\nfrom .database import Database\nfrom .extracted_task import ExtractedTask\nfrom .feature_extractor import FeatureExtractor\nfrom .measure_callback import MeasureCallback\nfrom .mutator import Mutator\nfrom .postproc import Postproc\nfrom .profiler import Profiler\nfrom .relay_integration import is_meta_schedule_enabled\nfrom .runner import Runner\nfrom .schedule_rule import ScheduleRule\nfrom .search_strategy import MeasureCandidate, SearchStrategy\nfrom .space_generator import SpaceGenerator\nfrom .task_scheduler import TaskScheduler\nfrom .tir_integration import tune_tir\nfrom .tune import tune_tasks\nfrom .tune_context import TuneContext\nfrom .utils import derived_object\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.meta_schedule\"\"\"\nfrom .._ffi import _init_api\n\n_init_api(\"meta_schedule\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/arg_info.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The argument information\"\"\"\nfrom typing import Any, List, Union\n\nfrom tvm._ffi import register_object\nfrom tvm.ir import IRModule\nfrom tvm.runtime import DataType, Object, ShapeTuple\nfrom tvm.tir import PrimFunc\n\nfrom . import _ffi_api\nfrom .utils import _json_de_tvm\n\n\n@register_object(\"meta_schedule.ArgInfo\")\nclass ArgInfo(Object):\n    \"\"\"Argument information\"\"\"\n\n    def as_json(self) -> Any:\n        \"\"\"Converts the ArgInfo to its corresponding JSON representation.\"\"\"\n        return _json_de_tvm(_ffi_api.ArgInfoAsJSON(self))  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def from_json(json_obj: Any) -> \"ArgInfo\":\n        \"\"\"Parse the argument information from a JSON object.\n\n        Parameters\n        ----------\n        json_obj : Any\n            The json object to parse.\n\n        Returns\n        -------\n        parsed : ArgInfo\n            The argument information parsed.\n        \"\"\"\n        return _ffi_api.ArgInfoFromJSON(json_obj)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def from_prim_func(func: PrimFunc) -> List[\"ArgInfo\"]:\n        \"\"\"Extract a list of the argument information from PrimFunc.\n\n        Parameters\n        ----------\n        func : PrimFunc\n            The PrimFunc to get argument information from.\n\n        Returns\n        -------\n        extracted : List[ArgInfo]\n            An array of the argument information derived.\n        \"\"\"\n        return _ffi_api.ArgInfoFromPrimFunc(func)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def from_entry_func(mod: IRModule, remove_preproc: bool = True) -> List[\"ArgInfo\"]:\n        \"\"\"Extract a list of the argument information from the entry func of an IRModule.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to get argument information from.\n        remove_preproc : bool\n            Whether to remove the preprocessing blocks.\n\n        Returns\n        -------\n        extracted : List[ArgInfo]\n            An array of the argument information derived.\n        \"\"\"\n        return _ffi_api.ArgInfoFromEntryFunc(mod, remove_preproc)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"meta_schedule.TensorInfo\")\nclass TensorInfo(ArgInfo):\n    \"\"\"Tensor argument information\n\n    Parameters\n    ----------\n    dtype : DataType\n        The data type of the tensor.\n    shape : ShapeTuple\n        The shape of the tensor.\n    \"\"\"\n\n    dtype: DataType\n    shape: ShapeTuple\n\n    def __init__(\n        self,\n        dtype: DataType,\n        shape: Union[ShapeTuple, List[int]],\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        dtype : DataType\n            The data type of the tensor.\n        shape : ShapeTuple\n            The shape of the tensor.\n        \"\"\"\n        if isinstance(shape, ShapeTuple):\n            shape_tuple = shape\n        else:\n            shape_tuple = ShapeTuple(shape)\n        self.__init_handle_by_constructor__(\n            _ffi_api.TensorInfo,  # type: ignore # pylint: disable=no-member\n            dtype,\n            shape_tuple,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/builder/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.builder package.\nMeta Schedule builders that translate IRModule to runtime.Module,\nand then export\n\"\"\"\nfrom .builder import Builder, BuilderInput, BuilderResult, PyBuilder, create\nfrom .local_builder import LocalBuilder\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/builder/builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule builders that translate IRModule to runtime.Module, and then export\"\"\"\nfrom typing import Callable, Dict, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\nfrom tvm._ffi import register_object\nfrom tvm.ir import IRModule\nfrom tvm.runtime import NDArray, Object\nfrom tvm.target import Target\n\nfrom .. import _ffi_api\n\n\n@register_object(\"meta_schedule.BuilderInput\")\nclass BuilderInput(Object):\n    \"\"\"The builder's input.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The IRModule to be built.\n    target : Target\n        The target to be built for.\n    params: Optional[Dict[str, NDArray]]\n        The parameters for Relay build module\n    \"\"\"\n\n    mod: IRModule\n    target: Target\n    params: Optional[Dict[str, NDArray]]\n\n    def __init__(\n        self,\n        mod: IRModule,\n        target: Target,\n        params: Optional[Dict[str, NDArray]] = None,\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be built.\n        target : Target\n            The target to be built for.\n        params: Optional[Dict[str, NDArray]]\n            The parameters for Relay build module\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.BuilderInput,  # type: ignore # pylint: disable=no-member\n            mod,\n            target,\n            params,\n        )\n\n\n@register_object(\"meta_schedule.BuilderResult\")\nclass BuilderResult(Object):\n    \"\"\"The builder's result.\n\n    Parameters\n    ----------\n    artifact_path : Optional[str]\n        The path to the artifact.\n    error_msg : Optional[str]\n        The error message.\n    \"\"\"\n\n    artifact_path: Optional[str]\n    error_msg: Optional[str]\n\n    def __init__(\n        self,\n        artifact_path: Optional[str],\n        error_msg: Optional[str],\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        artifact_path : Optional[str]\n            The path to the artifact.\n        error_msg : Optional[str]\n            The error message.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.BuilderResult,  # type: ignore # pylint: disable=no-member\n            artifact_path,\n            error_msg,\n        )\n\n\n@register_object(\"meta_schedule.Builder\")\nclass Builder(Object):\n    \"\"\"The abstract builder interface.\"\"\"\n\n    BuilderType = Union[\"Builder\", Literal[\"local\"]]\n\n    def build(self, build_inputs: List[BuilderInput]) -> List[BuilderResult]:\n        \"\"\"Build the given inputs.\n\n        Parameters\n        ----------\n        build_inputs : List[BuilderInput]\n            The inputs to be built.\n        Returns\n        -------\n        build_results : List[BuilderResult]\n            The results of building the given inputs.\n        \"\"\"\n        return _ffi_api.BuilderBuild(self, build_inputs)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Literal[\"local\"] = \"local\",\n        *args,\n        **kwargs,\n    ) -> \"Builder\":\n        \"\"\"Create a Builder.\n\n        Parameters\n        ----------\n        kind : Literal[\"local\"]\n            The kind of the builder. For now, only \"local\" is supported.\n\n        Returns\n        -------\n        builder : Builder\n            The builder created.\n        \"\"\"\n        from . import LocalBuilder  # pylint: disable=import-outside-toplevel\n\n        if kind == \"local\":\n            return LocalBuilder(*args, **kwargs)  # type: ignore\n        raise ValueError(f\"Unknown Builder: {kind}\")\n\n\ncreate = Builder.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyBuilder\")\nclass _PyBuilder(Builder):\n    \"\"\"\n    A TVM object builder to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyBuilder\n    \"\"\"\n\n    def __init__(self, f_build: Callable = None):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.BuilderPyBuilder,  # type: ignore # pylint: disable=no-member\n            f_build,\n        )\n\n\nclass PyBuilder:\n    \"\"\"\n    An abstract builder with customized build method on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\"cls\": _PyBuilder, \"methods\": [\"build\"]}\n\n    def build(self, build_inputs: List[BuilderInput]) -> List[BuilderResult]:\n        \"\"\"Build the given inputs.\n\n        Parameters\n        ----------\n        build_inputs : List[BuilderInput]\n            The inputs to be built.\n        Returns\n        -------\n        build_results : List[BuilderResult]\n            The results of building the given inputs.\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/builder/local_builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Local builder that compile on the local host\"\"\"\nimport os\nimport tempfile\nfrom typing import Callable, Dict, List, Optional, Union\n\nfrom tvm._ffi import register_func\nfrom tvm.ir import IRModule\nfrom tvm.runtime import Module, NDArray, load_param_dict, save_param_dict\nfrom tvm.target import Target\n\nfrom ...contrib.popen_pool import MapResult, PopenPoolExecutor, StatusKind\nfrom ..logging import get_logger\nfrom ..utils import cpu_count, derived_object, get_global_func_with_default_on_worker\nfrom .builder import BuilderInput, BuilderResult, PyBuilder\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\nT_BUILD = Callable[  # pylint: disable=invalid-name\n    [IRModule, Target, Optional[Dict[str, NDArray]]], Module\n]\nT_EXPORT = Callable[[Module], str]  # pylint: disable=invalid-name\n\n\ndef _serialize_params(params: Optional[Dict[str, NDArray]]) -> Optional[bytearray]:\n    if params is None:\n        return None\n    return save_param_dict(params)\n\n\ndef _deserialize_params(params: Optional[bytearray]) -> Optional[Dict[str, NDArray]]:\n    if params is None:\n        return None\n    return load_param_dict(params)\n\n\n@derived_object\nclass LocalBuilder(PyBuilder):\n    \"\"\"A builder that builds the given input on local host.\n\n    Parameters\n    ----------\n    pool : PopenPoolExecutor\n        The process pool to run the build.\n    max_workers: int\n        The max number of Popen workers.\n    timeout_sec : float\n        The timeout in seconds for the build.\n    initializer: Optional[Callable[[], None]]\n        The initializer function for each popen worker.\n    f_build : Union[None, str, T_BUILD]\n        Name of the build function to be used.\n        Defaults to `meta_schedule.builder.default_build`.\n    f_export : Union[None, str, T_EXPORT]\n        Name of the export function to be used.\n        Defaults to `meta_schedule.builder.default_export`.\n\n    Attributes\n    ----------\n    T_BUILD : typing._GenericAlias\n        The signature of the function `f_build`, which is\n\n        .. code-block:: python\n\n        def default_build(\n            mod: IRModule,\n            target: Target,\n            params: Optional[Dict[str, NDArray]]\n        ) -> Module:\n            ...\n\n    T_EXPORT : typing._GenericAlias\n        The signature of the function `f_export`, which is\n\n        .. code-block:: python\n\n        def default_export(mod: Module) -> str:\n            ...\n\n    Note\n    ----\n    The build function and export function should be registered in the worker process.\n    The worker process is only aware of functions registered in TVM package,\n    if there are extra functions to be registered,\n    please send the registration logic via initializer.\n    \"\"\"\n\n    max_workers: int\n    timeout_sec: float\n    initializer: Optional[Callable[[], None]]\n    f_build: Union[None, str, T_BUILD]\n    f_export: Union[None, str, T_EXPORT]\n\n    def __init__(\n        self,\n        *,\n        max_workers: Optional[int] = None,\n        timeout_sec: float = 30.0,\n        f_build: Union[None, str, T_BUILD] = None,\n        f_export: Union[None, str, T_EXPORT] = None,\n        initializer: Optional[Callable[[], None]] = None,\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        max_workers : Optional[int]\n            The maximum number of worker processes to be used.\n            Defaults to number of CPUs.\n        timeout_sec : float\n            The timeout in seconds for the build.\n        f_build : T_BUILD\n            Name of the build function to be used.\n            Defaults to `meta_schedule.builder.default_build`.\n        f_export : T_EXPORT\n            Name of the export function to be used.\n            Defaults to `meta_schedule.builder.default_export`.\n        initializer : Optional[Callable[[], None]]\n            The initializer to be used for the worker processes.\n        \"\"\"\n        super().__init__()\n\n        if max_workers is None:\n            max_workers = cpu_count(logical=True)\n        logger.info(\"LocalBuilder: max_workers = %d\", max_workers)\n\n        self.max_workers = max_workers\n        self.timeout_sec = timeout_sec\n        self.initializer = initializer\n        self.f_build = f_build\n        self.f_export = f_export\n        self._sanity_check()\n\n    def build(self, build_inputs: List[BuilderInput]) -> List[BuilderResult]:\n        results: List[BuilderResult] = []\n        map_result: MapResult\n\n        # Here we restart the PopenPool everytime because of a known memory leak issue with the\n        # PopenPool workers after a couple times of usage. We don't apply the same to runners to\n        # avoid potential problem caused by async behaviour.\n        pool = PopenPoolExecutor(\n            max_workers=self.max_workers,\n            timeout=self.timeout_sec,\n            initializer=self.initializer,\n        )\n\n        # Dispatch the build inputs to the worker processes.\n        for map_result in pool.map_with_error_catching(\n            lambda x: _worker_func(*x),\n            [\n                (\n                    self.f_build,\n                    self.f_export,\n                    build_input.mod,\n                    build_input.target,\n                    _serialize_params(build_input.params),\n                )\n                for build_input in build_inputs\n            ],\n        ):\n            if map_result.status == StatusKind.COMPLETE:\n                results.append(BuilderResult(map_result.value, None))\n            elif map_result.status == StatusKind.TIMEOUT:\n                results.append(\n                    BuilderResult(\n                        None,\n                        f\"LocalBuilder: Timeout, killed after {self.timeout_sec} seconds\",\n                    )\n                )\n            elif map_result.status == StatusKind.EXCEPTION:\n                results.append(\n                    BuilderResult(\n                        None,\n                        \"LocalBuilder: An exception occurred\\n\" + str(map_result.value),\n                    )\n                )\n            else:\n                raise ValueError(\"Unreachable: unexpected result: {map_result}\")\n        del pool\n        return results\n\n    def _sanity_check(self) -> None:\n        def _check(f_build, f_export) -> None:\n            get_global_func_with_default_on_worker(name=f_build, default=None)\n            get_global_func_with_default_on_worker(name=f_export, default=None)\n\n        # Same reason for the single use PopenPool as mentioned above\n        pool = PopenPoolExecutor(\n            max_workers=self.max_workers,\n            timeout=self.timeout_sec,\n            initializer=self.initializer,\n        )\n        value = pool.submit(_check, self.f_build, self.f_export)\n        value.result()\n        del pool\n\n\ndef _worker_func(\n    _f_build: Union[None, str, T_BUILD],\n    _f_export: Union[None, str, T_EXPORT],\n    mod: IRModule,\n    target: Target,\n    params: Optional[bytearray],\n) -> str:\n    # Step 0. Get the registered functions\n    f_build: T_BUILD = get_global_func_with_default_on_worker(\n        _f_build,\n        default_build,\n    )\n    f_export: T_EXPORT = get_global_func_with_default_on_worker(\n        _f_export,\n        default_export,\n    )\n    # Step 1. Build the IRModule\n    rt_mod: Module = f_build(mod, target, _deserialize_params(params))\n    # Step 2. Export the Module\n    artifact_path: str = f_export(rt_mod)\n    return artifact_path\n\n\n@register_func(\"meta_schedule.builder.default_build\")\ndef default_build(mod: IRModule, target: Target, _params: Optional[Dict[str, NDArray]]) -> Module:\n    \"\"\"Default build function.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The IRModule to be built.\n    target : Target\n        The target to be built.\n    _params : Optional[Dict[str, NDArray]]\n        The parameters to be used for the build. Must be None.\n\n    Returns\n    -------\n    rt_mod : Module\n        The built Module.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm.driver import build as tvm_build\n    from tvm.tir.transform import RemoveWeightLayoutRewriteBlock\n\n    # pylint: enable=import-outside-toplevel\n    mod = RemoveWeightLayoutRewriteBlock(skip_ndarray_rewrite=True)(mod)\n    return tvm_build(mod, target=target)\n\n\n@register_func(\"meta_schedule.builder.default_export\")\ndef default_export(mod: Module) -> str:\n    \"\"\"Default export function.\n\n    Parameters\n    ----------\n    mod : Module\n        The Module to be exported.\n\n    Returns\n    -------\n    artifact_path : str\n        The path to the exported Module.\n    \"\"\"\n    from tvm.contrib.tar import tar  # pylint: disable=import-outside-toplevel\n\n    artifact_path = os.path.join(tempfile.mkdtemp(), \"tvm_tmp_mod.\" + tar.output_format)\n    mod.export_library(artifact_path, tar)\n    return artifact_path\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.cost_model package.\n\"\"\"\nfrom .cost_model import CostModel, PyCostModel\nfrom .random_model import RandomModel\nfrom .xgb_model import XGBModel\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule CostModel.\"\"\"\nimport ctypes\nfrom typing import Callable, List, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nimport numpy as np  # type: ignore\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\n\nfrom .. import _ffi_api\nfrom ..runner import RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\nfrom ..utils import _get_default_str\n\n\n@register_object(\"meta_schedule.CostModel\")\nclass CostModel(Object):\n    \"\"\"Cost model.\"\"\"\n\n    CostModelType = Union[\"CostModel\", Literal[\"xgb\", \"mlp\", \"random\"]]\n\n    def load(self, path: str) -> None:\n        \"\"\"Load the cost model from given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        _ffi_api.CostModelLoad(self, path)  # type: ignore # pylint: disable=no-member\n\n    def save(self, path: str) -> None:\n        \"\"\"Save the cost model to given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        _ffi_api.CostModelSave(self, path)  # type: ignore # pylint: disable=no-member\n\n    def update(\n        self,\n        context: TuneContext,\n        candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the cost model given running results.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n        results : List[RunnerResult]\n            The running results of the measure candidates.\n        \"\"\"\n        _ffi_api.CostModelUpdate(self, context, candidates, results)  # type: ignore # pylint: disable=no-member\n\n    def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray:\n        \"\"\"Predict normalized score with the cost model.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n\n        Return\n        ------\n        result : np.ndarray\n            The predicted normalized score.\n        \"\"\"\n        n = len(candidates)\n        results = np.zeros(shape=(n,), dtype=\"float64\")\n        _ffi_api.CostModelPredict(  # type: ignore # pylint: disable=no-member\n            self,\n            context,\n            candidates,\n            results.ctypes.data_as(ctypes.c_void_p),\n        )\n        return results\n\n    @staticmethod\n    def create(\n        kind: Literal[\"xgb\", \"mlp\", \"random\", \"none\"],\n        *args,\n        **kwargs,\n    ) -> \"CostModel\":\n        \"\"\"Create a CostModel.\n\n        Parameters\n        ----------\n        kind : Literal[\"xgb\", \"mlp\", \"random\", \"none\"]\n            The kind of the cost model. Can be \"xgb\", \"mlp\", \"random\" or \"none\".\n\n        Returns\n        -------\n        cost_model : CostModel\n            The created cost model.\n        \"\"\"\n        from . import RandomModel, XGBModel  # pylint: disable=import-outside-toplevel\n\n        if kind == \"xgb\":\n            return XGBModel(*args, **kwargs)  # type: ignore\n        if kind == \"random\":\n            return RandomModel(*args, **kwargs)  # type: ignore\n        if kind == \"mlp\":\n            from .mlp_model import (  # type: ignore  # pylint: disable=import-outside-toplevel\n                MLPModel,\n            )\n\n            return MLPModel(*args, **kwargs)  # type: ignore\n        if kind == \"none\":\n            return None  # no cost model required\n        raise ValueError(f\"Unknown CostModel: {kind}\")\n\n\ncreate = CostModel.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyCostModel\")\nclass _PyCostModel(CostModel):\n    \"\"\"\n    A TVM object cost model to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyCostModel\n    \"\"\"\n\n    def __init__(\n        self,\n        f_load: Callable = None,\n        f_save: Callable = None,\n        f_update: Callable = None,\n        predict_func: Callable = None,\n        f_as_string: Callable = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        def f_predict(context: TuneContext, candidates: List[MeasureCandidate], return_ptr) -> None:\n            n = len(candidates)\n            return_ptr = ctypes.cast(return_ptr, ctypes.POINTER(ctypes.c_double))\n            array_wrapper = np.ctypeslib.as_array(return_ptr, shape=(n,))\n            res = predict_func(context, candidates)\n            array_wrapper[:] = res\n            assert (\n                array_wrapper.dtype == \"float64\"\n            ), \"ValueError: Invalid data type returned from CostModel Predict!\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.CostModelPyCostModel,  # type: ignore # pylint: disable=no-member\n            f_load,\n            f_save,\n            f_update,\n            f_predict,\n            f_as_string,\n        )\n\n\nclass PyCostModel:\n    \"\"\"\n    An abstract cost model with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyCostModel,\n        \"methods\": [\"load\", \"save\", \"update\", \"predict\", \"__str__\"],\n    }\n\n    def load(self, path: str) -> None:\n        \"\"\"Load the cost model from given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        raise NotImplementedError\n\n    def save(self, path: str) -> None:\n        \"\"\"Save the cost model to given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        raise NotImplementedError\n\n    def update(\n        self,\n        context: TuneContext,\n        candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the cost model given running results.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n        results : List[RunnerResult]\n            The running results of the measure candidates.\n        \"\"\"\n        raise NotImplementedError\n\n    def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray:\n        \"\"\"Predict given the measure candidates.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n\n        Return\n        ------\n        result : np.ndarray\n            The predicted normalized score.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        \"\"\"Get the cost model as string with name.\n\n        Return\n        ------\n        result : str\n            Get the cost model as string with name.\n        \"\"\"\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/metric.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Cost model metrics for meta schedule\"\"\"\nimport numpy as np  # type: ignore\n\n\ndef max_curve(trial_scores: np.ndarray) -> np.ndarray:\n    \"\"\"f(n) = max([s[i] fo i < n])\n\n    Parameters\n    ----------\n    trial_scores : List[float]\n        the score of i-th trial\n\n    Returns\n    -------\n    curve : np.ndarray\n        A vector, the max-curve function values\n    \"\"\"\n    ret = np.empty(len(trial_scores))\n    keep = -1e9\n    for i, score in enumerate(trial_scores):\n        keep = max(keep, score)\n        ret[i] = keep\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/mlp_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# type: ignore[import]\n\"\"\"\nSegment Sum MLP cost model\n\"\"\"\nimport glob\nimport math\nimport os\nimport random\nimport tempfile\nfrom collections import OrderedDict\nfrom itertools import chain as itertools_chain\nfrom typing import Dict, List, NamedTuple, Optional, Tuple\n\nimport numpy as np  # type: ignore\nimport torch  # type: ignore\nimport tvm\n\nfrom ...contrib.tar import tar, untar\nfrom ...runtime import NDArray\nfrom ...target import Target\nfrom ..cost_model import PyCostModel\nfrom ..database import JSONDatabase\nfrom ..feature_extractor import FeatureExtractor, PerStoreFeature\nfrom ..logging import get_logger\nfrom ..runner import RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\nfrom ..utils import derived_object, shash2hex\n\nlogger = get_logger(\"mlp_model\")  # pylint: disable=invalid-name\n\n# pylint: disable=no-member,import-outside-toplevel\n\n\nclass SegmentSumMLPConfig(NamedTuple):\n    \"\"\"SegmentSum MLP model configuration\n\n    Parameters\n    ----------\n    input_dim : int\n        The input dim for the model.\n    hidden_dim : int\n        The hidden dim for the model.\n    output_dim : int\n        The output dim for the model.\n    use_norm : bool\n        Whether to normalize the segment sum or not.\n    use_sigmoid : bool\n        Whether to use sigmoid on the final output or not.\n    \"\"\"\n\n    input_dim: int = 172\n    hidden_dim: int = 256\n    output_dim: int = 1\n    use_norm: bool = False\n    use_sigmoid: bool = False\n\n    def to_dict(self):  # pylint: disable=missing-function-docstring\n        return {\n            \"input_dim\": self.input_dim,\n            \"hidden_dim\": self.hidden_dim,\n            \"output_dim\": self.output_dim,\n            \"use_norm\": self.use_norm,\n            \"use_sigmoid\": self.use_sigmoid,\n        }\n\n\nclass TrainerConfig(NamedTuple):\n    \"\"\"Trainer configuration\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size.\n    learning rate : float\n        The learning rate.\n    weight decay : float\n        The weight decay.\n    num_epoch_full : int\n        The number of epochs used in full training.\n    num_epoch_incremental : int\n        The number of epochs used in incremental training.\n    grad_clip_norm: float\n        The norm of gradient clipping.\n    train_verbose: int\n        The verbose frequency for training in batches.\n    test_interval: int\n        The testing interval in epochs.\n    test_split: float\n        The fraction of data for testing.\n    frozen: bool\n        Determine whether to re-train the model or not.\n    \"\"\"\n\n    batch_size: int = 128\n    learning_rate: float = 7e-4\n    weight_decay: float = 1e-6\n    num_epoch_full: int = 50\n    num_epoch_incremental: int = 5\n    grad_clip_norm: float = 0.5\n    train_verbose: int = 1000\n    test_interval: int = 1\n    test_split: float = 0.2\n    frozen: bool = False\n\n    def to_dict(self):  # pylint: disable=missing-function-docstring\n        return {\n            \"batch_size\": self.batch_size,\n            \"learning_rate\": self.learning_rate,\n            \"weight_decay\": self.weight_decay,\n            \"num_epoch_full\": self.num_epoch_full,\n            \"num_epoch_incremental\": self.num_epoch_incremental,\n            \"grad_clip_norm\": self.grad_clip_norm,\n            \"train_verbose\": self.train_verbose,\n            \"test_interval\": self.test_interval,\n            \"test_split\": self.test_split,\n            \"frozen\": self.frozen,\n        }\n\n\n# pylint: disable=too-few-public-methods\nclass FeatureGroup:\n    \"\"\"Feature group\n\n    Parameters\n    ----------\n    group_hash : str\n        The hash of the group\n    features : List[np.ndarray]\n        The features\n    costs : List[float]\n        The costs\n    min_cost : float\n        The minimum cost\n    \"\"\"\n\n    group_hash: str\n    features: List[np.ndarray]\n    costs: np.ndarray\n    min_cost: float\n\n    def __init__(\n        self,\n        group_hash: str,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n    ) -> None:\n        self.group_hash = group_hash\n        self.features = features\n        self.costs = costs\n        self.min_cost = np.min(costs)\n\n    def append(  # pylint: disable=missing-function-docstring\n        self,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n    ) -> None:\n        self.features.extend(features)\n        self.costs = np.append(self.costs, costs)\n        self.min_cost = np.min(self.costs)\n\n\n# pylint: disable=too-many-instance-attributes\nclass SegmentDataLoader:\n    \"\"\"Dataloader for Segment Sum MLP model.\n\n    Parameters\n    ----------\n    features : List[np.ndarray]\n        The features\n    results : np.ndarray\n        The measured results, can be None.\n    batch_size : int\n        The batch size\n    shuffle : bool\n        Whether to shuffle the dataset or not\n    \"\"\"\n\n    def __init__(\n        self,\n        features,\n        results=None,\n        batch_size=128,\n        shuffle=True,\n    ):\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.data_size = len(features)\n\n        # flatten features and store the starting indices\n        self.segment_sizes = torch.tensor([len(feature) for feature in features], dtype=torch.int32)\n        self.feature_offsets = (\n            torch.cumsum(self.segment_sizes, 0, dtype=torch.int32) - self.segment_sizes\n        )\n        features = torch.cat([torch.tensor(feature) for feature in features])\n        norm, _ = features.max(dim=0)\n        norm[norm == 0] = 1\n        self.features = features / norm\n        self.results = torch.tensor(results) if results is not None else None\n        self.iter_order = self.pointer = None\n\n    def __len__(self):\n        return self.data_size\n\n    def __iter__(self):\n        if self.shuffle:\n            self.iter_order = torch.randperm(self.data_size)\n        else:\n            self.iter_order = torch.arange(self.data_size)\n        self.pointer = 0\n        return self\n\n    def __next__(self):\n        if self.pointer >= self.data_size:\n            raise StopIteration\n        batch_indices = self.iter_order[self.pointer : self.pointer + self.batch_size]\n        self.pointer += self.batch_size\n        return self._fetch_indices(batch_indices)\n\n    def _fetch_indices(self, indices):\n        segment_sizes, feature_offsets = self.segment_sizes[indices], self.feature_offsets[indices]\n        feature_indices = torch.empty(segment_sizes.sum(), dtype=torch.int32)\n        idx = 0\n        for offset, seg_size in zip(feature_offsets, segment_sizes):\n            feature_indices[idx : idx + seg_size] = torch.arange(offset, offset + seg_size)\n            idx += seg_size\n        features = self.features[feature_indices.long()]\n        results = None\n        if self.results is not None:\n            results = self.results[indices.long()]\n        return segment_sizes, features, results\n\n\ndef lambda_rank_loss(  # pylint: disable=too-many-locals\n    preds: \"torch.Tensor\",\n    labels: \"torch.Tensor\",\n    k: int = None,\n    eps: float = 1e-10,\n    sigma: float = 1.0,\n) -> \"torch.Tensor\":\n    \"\"\"\n    LambdaLoss: Metric-Driven Loss for Learning-to-Rank\n\n    Parameters\n    ----------\n    preds : Tensor\n        The predicted runtime for each candidate.\n    labels : Tensor\n        The measured runtime for each candidate.\n    k : int\n        Loss for top k.\n        Default is None, which means computing all scores.\n    eps : float\n        The minimum value to the denominator and argument of log if they reach 0.\n    sigma : float\n        The scaling factor to the input of the sigmoid function.\n\n    Returns\n    -------\n    loss : Tensor\n        The lambda rank loss.\n    \"\"\"\n    device = preds.device\n    y_pred, y_true = preds[None, :], labels[None, :]\n    y_pred_sorted, indices_pred = y_pred.sort(descending=True, dim=-1)\n    y_true_sorted, _ = y_true.sort(descending=True, dim=-1)\n    true_sorted_by_preds = torch.gather(y_true, dim=1, index=indices_pred)\n    true_diffs = true_sorted_by_preds[:, :, None] - true_sorted_by_preds[:, None, :]\n    padded_pairs_mask = torch.isfinite(true_diffs) & (true_diffs > 0)\n    ndcg_at_k_mask = torch.zeros(\n        (y_pred.shape[1], y_pred.shape[1]), dtype=torch.bool, device=device\n    )\n    ndcg_at_k_mask[:k, :k] = 1\n    true_sorted_by_preds.clamp_(min=0.0)\n    y_true_sorted.clamp_(min=0.0)\n    pos_idxs = torch.arange(1, y_pred.shape[1] + 1).to(device)\n    D = torch.log2(1.0 + pos_idxs.float())[None, :]  # pylint: disable=invalid-name\n    maxDCGs = torch.sum(  # pylint: disable=invalid-name\n        ((torch.pow(2, y_true_sorted) - 1) / D)[:, :k], dim=-1\n    ).clamp(min=eps)\n    G = (torch.pow(2, true_sorted_by_preds) - 1) / maxDCGs[:, None]  # pylint: disable=invalid-name\n    weights = torch.abs(\n        torch.pow(D[:, :, None], -1.0) - torch.pow(D[:, None, :], -1.0)\n    ) * torch.abs(G[:, :, None] - G[:, None, :])\n    scores_diffs = (y_pred_sorted[:, :, None] - y_pred_sorted[:, None, :]).clamp(min=-1e8, max=1e8)\n    scores_diffs[torch.isnan(scores_diffs)] = 0.0\n    weighted_probs = (torch.sigmoid(sigma * scores_diffs).clamp(min=eps) ** weights).clamp(min=eps)\n    losses = torch.log2(weighted_probs)\n    masked_losses = losses[padded_pairs_mask & ndcg_at_k_mask]\n    loss = -torch.sum(masked_losses)\n    return loss\n\n\ndef topk_score(\n    pred_results: \"torch.Tensor\",\n    gt_results: \"torch.Tensor\",\n    k: int,\n) -> float:\n    \"\"\"\n    Evaluate the top-k score\n\n    Parameters\n    ----------\n    pred_results: Tensor\n        The raw prediction\n    gt_results: Tensor\n        The measured results\n    k : int\n        The k in top k score\n\n    Returns\n    -------\n    score : float\n        The top-k score\n    \"\"\"\n    k = min(k, len(pred_results))\n    topk_indices = torch.topk(pred_results, k, largest=False).indices\n    score = gt_results.min() / gt_results[topk_indices].min()\n    return score.item()\n\n\nclass SegmentSumMLP(torch.nn.Module):\n    \"\"\"Segment Sum MLP model.\n\n    Parameters\n    ----------\n    input_dim : int\n        The input dim for the model.\n    hidden_dim : int\n        The hidden dim for the model.\n    output_dim : int\n        The output dim for the model.\n    use_norm : bool\n        Whether to normalize the segment sum or not.\n    use_sigmoid : bool\n        Whether to use sigmoid on the final output or not.\n    \"\"\"\n\n    input_dim: int\n    hidden_dim: int\n    output_dim: int\n    use_norm: bool\n    use_sigmoid: bool\n\n    def __init__(  # pylint: disable=too-many-arguments\n        self,\n        input_dim: int = 172,\n        hidden_dim: int = 256,\n        output_dim: int = 1,\n        use_norm: bool = False,\n        use_sigmoid: bool = False,\n    ):\n        from torch import nn  # type: ignore\n\n        super().__init__()\n        self.encoder = nn.Sequential(\n            nn.Linear(input_dim, hidden_dim),\n            nn.ReLU(),\n            nn.Linear(hidden_dim, hidden_dim),\n            nn.ReLU(),\n        )\n        self.norm = nn.BatchNorm1d(hidden_dim) if use_norm else nn.Identity()\n        self.layer0 = nn.Sequential(\n            nn.Linear(hidden_dim, hidden_dim),\n            nn.ReLU(),\n        )\n        self.layer1 = nn.Sequential(\n            nn.Linear(hidden_dim, hidden_dim),\n            nn.ReLU(),\n        )\n        self.decoder = nn.Linear(hidden_dim, output_dim)\n        self.sigmoid = nn.Sigmoid() if use_sigmoid else nn.Identity()\n\n    def forward(  # pylint: disable=missing-function-docstring\n        self,\n        segment_sizes: \"torch.Tensor\",\n        features: \"torch.Tensor\",\n    ) -> \"torch.Tensor\":\n        n_seg = len(segment_sizes)\n        encoded_features = self.encoder(features)\n        segment_indices = torch.repeat_interleave(\n            torch.arange(n_seg, device=features.device),\n            segment_sizes.long(),\n        )\n        n_dim = encoded_features.shape[1]\n        segment_sum = torch.scatter_add(\n            input=torch.zeros((n_seg, n_dim), dtype=encoded_features.dtype, device=features.device),\n            dim=0,\n            index=segment_indices.view(-1, 1).expand(-1, n_dim),\n            src=encoded_features,\n        )\n        out = self.norm(segment_sum)\n        out = self.layer0(out) + out\n        out = self.layer1(out) + out\n        out = self.decoder(out).squeeze()\n        out = self.sigmoid(out)\n        return out\n\n\ndef extract_features(\n    context: TuneContext,\n    candidates: List[MeasureCandidate],\n    results: Optional[List[RunnerResult]] = None,\n    extractor: Optional[FeatureExtractor] = None,\n):\n    \"\"\"Extract feature vectors and compute mean costs.\n\n    Parameters\n    ----------\n    context: TuneContext\n        The tuning context.\n    candidates: List[MeasureCandidate]\n        The measure candidates.\n    results: Optional[List[RunnerResult]]\n        The measured results, can be None if used in prediction.\n    extractor: Optional[FeatureExtractor]\n        The feature extractor.\n\n    Returns\n    -------\n    new_features: List[np.ndarray]\n        The extracted features.\n    new_mean_costs: np.ndarray\n        The mean costs.\n    \"\"\"\n    extractor = extractor or PerStoreFeature(extract_workload=True)\n\n    def _feature(feature: NDArray) -> np.ndarray:\n        return feature.numpy().astype(\"float32\")\n\n    def _mean_cost(res: RunnerResult) -> float:\n        if not res.run_secs:\n            return 1e10\n        return float(np.median([float(s) for s in res.run_secs]))\n\n    new_features = [_feature(x) for x in extractor.extract_from(context, candidates)]\n    new_mean_costs = (\n        np.array([_mean_cost(x) for x in results]).astype(\"float32\")\n        if results is not None\n        else None\n    )\n    return new_features, new_mean_costs\n\n\nclass State:\n    \"\"\"State of the trainer\n\n    Parameters\n    ----------\n    model: SegmentSumMLP\n        The cost model.\n    data: Dict[str, FeatureGroup]\n        The data groups.\n    data_size: int\n        The size of all data.\n    untrained_size: int\n        The size of the untrained data.\n    \"\"\"\n\n    model: SegmentSumMLP\n    data: Dict[str, FeatureGroup]\n    data_size: int\n    untrained_size: int\n\n    def __init__(\n        self,\n        model_config: Optional[SegmentSumMLPConfig] = None,\n        extractor: Optional[FeatureExtractor] = None,\n    ):\n        model_config = model_config or SegmentSumMLPConfig()\n        extractor = extractor or PerStoreFeature(extract_workload=True)\n\n        self.model = SegmentSumMLP(**model_config.to_dict())\n        self.data = OrderedDict()\n        self.data_size = 0\n        self.untrained_size = 0\n        self.extractor = extractor\n\n    def load(  # pylint: disable=too-many-locals\n        self,\n        path: str,\n        target: str = \"nvidia/nvidia-v100\",\n    ) -> None:\n        \"\"\"Load the cached model, cached features, or raw data.\n\n        Parameters\n        ----------\n        path: str\n            The path to the tar file containing cached model, cached features,\n            or raw data.\n        target: str\n            The target for the tuning context.\n        \"\"\"\n        with tempfile.TemporaryDirectory() as tmp_dir:\n            model_path = os.path.join(tmp_dir, \"model.pth\")\n            cache_path = os.path.join(tmp_dir, \"cached_data.npy\")\n            raw_path = os.path.join(tmp_dir, \"raw_data\")\n            untar(path, tmp_dir)\n            if os.path.exists(model_path):\n                self.model.load_state_dict(torch.load(model_path))\n            if os.path.exists(cache_path):\n                for group_hash, features, costs in np.load(cache_path, allow_pickle=True):\n                    self.data[group_hash] = FeatureGroup(\n                        group_hash=group_hash,\n                        features=list(features),\n                        costs=costs,\n                    )\n                    self.data_size += len(costs)\n                    self.untrained_size += len(costs)\n            elif os.path.exists(raw_path):\n                from tqdm import tqdm  # type: ignore\n\n                model_dirs = glob.glob(os.path.join(raw_path, \"*\"))\n                workload_paths = []\n                for model_dir in model_dirs:\n                    json_files = glob.glob(os.path.join(model_dir, \"*.json\"))\n                    for json_file in json_files:\n                        if json_file.endswith(\"_workload.json\"):\n                            workload_paths.append(json_file)\n                for workload_path in tqdm(workload_paths):\n                    try:\n                        database = JSONDatabase(\n                            path_workload=workload_path,\n                            path_tuning_record=workload_path.replace(\n                                \"_workload.json\", \"_candidates.json\"\n                            ),\n                        )\n                    except tvm._ffi.base.TVMError:  # pylint: disable=protected-access\n                        continue\n                    candidates, results = [], []\n                    tuning_records = database.get_all_tuning_records()\n                    if len(tuning_records) == 0:\n                        continue\n                    for record in tuning_records:\n                        candidates.append(record.as_measure_candidate())\n                        results.append(RunnerResult(run_secs=record.run_secs, error_msg=None))\n                    assert len(candidates) == len(results)\n                    context = TuneContext(mod=tuning_records[0].workload.mod, target=Target(target))\n                    features, mean_costs = extract_features(\n                        context, candidates, results, self.extractor\n                    )\n                    self.add_to_group(features, mean_costs, shash2hex(context.mod))\n\n    def save(self, path: str) -> None:\n        \"\"\"Cache the model and data.\n\n        Parameters\n        ----------\n        path: str\n            The path to the cached tar file.\n        \"\"\"\n        with tempfile.TemporaryDirectory() as tmp_dir:\n            model_path = os.path.join(tmp_dir, \"model.pth\")\n            cache_path = os.path.join(tmp_dir, \"cached_data.npy\")\n            torch.save(self.model.state_dict(), model_path)\n            data = [\n                (\n                    g.group_hash,\n                    g.features,\n                    g.costs,\n                )\n                for g in self.data.values()\n            ]\n            np.save(\n                file=cache_path,\n                arr=np.array(data, dtype=object),\n            )\n            tar(path, [x for x in [model_path, cache_path] if x is not None])\n            logger.info(\"Saved MLPModel to %s\", path)\n\n    def add_to_group(\n        self,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n        group_hash: str,\n    ):\n        \"\"\"Add features and costs to the data groups with key group_hash.\n\n        Parameters\n        ----------\n        features: List[np.ndarray]\n            The feature vectors.\n        costs: np.ndarray\n            The measured results.\n        group_hash: str\n            The structural hash of the candidates.\n        \"\"\"\n        group = self.data.get(group_hash, None)\n        if group is None:\n            group = FeatureGroup(\n                group_hash=group_hash,\n                features=features,\n                costs=costs,\n            )\n        else:\n            group.append(features, costs)\n        self.data[group_hash] = group\n        self.data_size += len(features)\n        self.untrained_size += len(features)\n\n\nclass SegmentSumMLPTrainer:\n    \"\"\"The trainer for Segment Sum MLP model.\n\n    Parameters\n    ----------\n    state: State\n        The state of the trainer.\n    batch_size : int\n        The batch size.\n    learning rate : float\n        The learning rate.\n    weight decay : float\n        The weight decay.\n    num_epoch_full : int\n        The number of epochs used in full training.\n    num_epoch_incremental : int\n        The number of epochs used in incremental training.\n    grad_clip_norm: float\n        The norm of gradient clipping.\n    train_verbose: int\n        The verbose frequency for training in batches.\n    test_interval: int\n        The testing interval in epochs.\n    test_split: float\n        The fraction of data for testing.\n    frozen: bool\n        Determine whether to re-train the model or not.\n    optimizer: \"torch.optim.adam.Adam\"\n        The optimizer.\n    scheduler: \"torch.optim.lr_scheduler.StepLR\"\n        The scheduler.\n    \"\"\"\n\n    state: State\n    batch_size: int = 128\n    learning_rate: float = 7e-4\n    weight_decay: float = 1e-6\n    num_epoch_full: int = 50\n    num_epoch_incremental: int = 5\n    grad_clip_norm: float = 0.5\n    train_verbose: int = 1000\n    test_interval: int = 1\n    test_split: float = 0.2\n    frozen: bool = False\n    optimizer: \"torch.optim.adam.Adam\"  # type: ignore\n    scheduler: \"torch.optim.lr_scheduler.StepLR\"  # type: ignore\n\n    def __init__(\n        self,\n        train_config: Optional[TrainerConfig] = None,\n        state: Optional[State] = None,\n    ):\n        train_config = train_config or TrainerConfig()\n        state = state or State()\n\n        config = train_config.to_dict()\n        for attr in config:\n            setattr(self, attr, config[attr])\n        self.state = state\n        self.device = \"cuda\" if torch.cuda.device_count() else \"cpu\"\n        self.optimizer, self.scheduler = None, None\n\n    def train_step(\n        self,\n        data: Tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"],\n        batch: int = 0,\n        train_loss: Optional[float] = None,\n    ) -> float:\n        \"\"\"Helper function for training on a single batch.\n\n        Parameters\n        ----------\n        data: Tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"]\n            A batch of data, should be a tuple of (segment_sizes, features, gt_results).\n        batch: int = 0\n            The current batch number.\n        train_loss: Optional[float] = None\n            The previous averaged training loss, None if it is the first batch.\n\n        Returns\n        -------\n        train_loss: float\n            The averaged training loss after the current batch.\n        \"\"\"\n        segment_sizes, features, gt_results = (\n            data[0].to(self.device),\n            data[1].to(self.device),\n            data[2].to(self.device),\n        )\n        self.optimizer.zero_grad()\n        pred_results = self.state.model(segment_sizes, features)\n        loss = lambda_rank_loss(pred_results, gt_results)\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(self.state.model.parameters(), self.grad_clip_norm)\n        self.optimizer.step()\n        loss = loss.detach().cpu()\n        train_loss = (\n            train_loss * 0.95 + loss.item() * 0.05 if train_loss is not None else loss.item()\n        )\n        segment_sizes, features, gt_results, pred_results = (\n            segment_sizes.detach().cpu(),\n            features.detach().cpu(),\n            gt_results.detach().cpu(),\n            pred_results.detach().cpu(),\n        )\n        if batch % self.train_verbose == 0:\n            logger.info(\"Batch: %d, train loss: %6f\", batch, train_loss)\n        return train_loss\n\n    def predict_step(\n        self,\n        data: Tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"],\n    ):\n        \"\"\"Helper function for predicting (validating) on a single batch.\n\n        Parameters\n        ----------\n        data: Tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"]\n            A batch of data, should be a tuple of (segment_sizes, features, gt_results).\n            gt_results can be None if it is used for predicting.\n\n        Returns\n        -------\n        pred_results: np.ndarray\n            The predicted results for the current batch.\n        test_loss_batch: float\n            If used for validation, return the test loss for the current batch.\n        test_scores_batch: List[float]\n            If used for validation, return the topk scores for the current batch.\n        \"\"\"\n        test_loss_batch, test_scores_batch = None, []\n        segment_sizes, features = (\n            data[0].to(self.device),\n            data[1].to(self.device),\n        )\n        gt_results = data[2]\n        pred_results = self.state.model(segment_sizes, features)\n        segment_sizes, features, pred_results = (\n            segment_sizes.detach().cpu(),\n            features.detach().cpu(),\n            pred_results.detach().cpu(),\n        )\n        if gt_results is not None:\n            test_loss_batch = lambda_rank_loss(pred_results, gt_results).item()\n            for k in [1, 5, 10]:\n                test_scores_batch.append(topk_score(pred_results, gt_results, k))\n        return pred_results.numpy(), test_loss_batch, test_scores_batch\n\n    def train_full(self):  # pylint: disable=too-many-locals\n        \"\"\"Training on the full dataset.\"\"\"\n        # split into training and testing set\n        keys = list(self.state.data.keys())\n        test_keys = random.sample(keys, k=math.floor(len(keys) * self.test_split))\n        train_data = OrderedDict()\n        test_data = OrderedDict()\n        for key in keys:\n            if key in test_keys:\n                test_data[key] = self.state.data[key]\n            else:\n                train_data[key] = self.state.data[key]\n        train_features = list(\n            itertools_chain.from_iterable([g.features for g in train_data.values()])\n        )\n        test_features = list(\n            itertools_chain.from_iterable([g.features for g in test_data.values()])\n        )\n        train_results = np.concatenate([g.min_cost / g.costs for g in train_data.values()])\n        test_results = np.concatenate([g.min_cost / g.costs for g in test_data.values()])\n        train_loader = SegmentDataLoader(\n            train_features, train_results, batch_size=self.batch_size, shuffle=True\n        )\n        test_loader = SegmentDataLoader(\n            test_features, test_results, batch_size=self.batch_size, shuffle=False\n        )\n        self.optimizer = torch.optim.Adam(\n            self.state.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay\n        )\n        self.scheduler = torch.optim.lr_scheduler.StepLR(\n            self.optimizer,\n            step_size=self.num_epoch_full // 10,\n            gamma=0.8,\n            verbose=True,\n        )\n        self.state.model = self.state.model.to(self.device)\n        min_test_loss = 1e10\n        logger.info(\"Training size: %d; Testing size: %d\", len(train_loader), len(test_loader))\n\n        model_cache_path = tempfile.NamedTemporaryFile().name  # pylint: disable=consider-using-with\n        for epoch in range(self.num_epoch_full):\n            logger.info(\"Epoch: %d\", epoch)\n            # training\n            self.state.model.train()\n            train_loss = None\n            for batch, data in enumerate(train_loader):\n                train_loss = self.train_step(data, batch, train_loss)\n            self.scheduler.step()\n            # testing\n            if epoch % self.test_interval == 0:\n                self.state.model.eval()\n                test_losses, test_scores = [], []\n                for data in test_loader:\n                    _, test_loss_batch, test_scores_batch = self.predict_step(data)\n                    test_losses.append(test_loss_batch)\n                    test_scores.append(test_scores_batch)\n                test_loss = (\n                    np.array(test_losses[:-1]).mean() if len(test_losses) > 1 else test_losses[0]\n                )\n                logger.info(\n                    \"Average test loss: %6f, top1 score: %5f, top5 score: %5f, top10 score: %5f\",\n                    test_loss,\n                    np.array(test_scores)[:, 0].mean(),\n                    np.array(test_scores)[:, 1].mean(),\n                    np.array(test_scores)[:, 2].mean(),\n                )\n                if test_loss < min_test_loss:\n                    min_test_loss = test_loss\n                    torch.save(self.state.model.state_dict(), model_cache_path)\n        self.state.model.to(\"cpu\").load_state_dict(torch.load(model_cache_path))\n        self.state.untrained_size = 0\n\n    def train_incremental(\n        self,\n        features: List[np.ndarray],\n        results: np.ndarray,\n    ):\n        \"\"\"Training on incremental data.\n\n        Parameters\n        ----------\n        features: List[np.ndarray]\n            The extracted features.\n        results: np.ndarray\n            The measured results.\n        \"\"\"\n        results = np.min(results) / results\n        loader = SegmentDataLoader(features, results, batch_size=self.batch_size, shuffle=True)\n        self.optimizer = torch.optim.Adam(\n            self.state.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay\n        )\n        self.state.model = self.state.model.to(self.device)\n        logger.info(\"Incremental training size: %d\", len(loader))\n        for epoch in range(self.num_epoch_incremental):\n            logger.info(\"Epoch: %d\", epoch)\n            self.state.model.train()\n            loss = None\n            for batch, data in enumerate(loader):\n                loss = self.train_step(data, batch, loss)\n        self.state.model.to(\"cpu\")\n        self.state.untrained_size = max(0, self.state.untrained_size - len(loader))\n\n    def predict_incremental(\n        self,\n        features: List[np.ndarray],\n        results: Optional[np.ndarray] = None,\n    ) -> np.ndarray:\n        \"\"\"Predicting (validating) on incremental data.\n\n        Parameters\n        ----------\n        features: List[np.ndarray]\n            The extracted features.\n        results: Optional[np.ndarray]\n            The measured results, can be None if used for predicting.\n\n        Returns\n        -------\n        pred_results: np.ndarray\n            The predicted results.\n        \"\"\"\n        if results is not None:\n            results = np.min(results) / results\n        loader = SegmentDataLoader(features, results, batch_size=self.batch_size, shuffle=False)\n        self.state.model = self.state.model.to(self.device).eval()\n        logger.info(\"Incremental testing size: %d\", len(loader))\n        pred_results, losses, scores = [], [], []\n        for data in loader:\n            pred_results_batch, losses_batch, scores_batch = self.predict_step(data)\n            pred_results.append(pred_results_batch)\n            losses.append(losses_batch)\n            scores.append(scores_batch)\n        pred_results = np.concatenate(pred_results)\n        if results is not None:\n            losses = np.array(losses[:-1]).mean() if len(losses) > 1 else losses[0]\n            logger.info(\n                \"Average test loss: %6f, top1 score: %5f, top5 score: %5f, top10 score: %5f\",\n                losses,\n                np.array(scores)[:, 0].mean(),\n                np.array(scores)[:, 1].mean(),\n                np.array(scores)[:, 2].mean(),\n            )\n        return pred_results\n\n    def update(\n        self,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n        group_hash: str,\n    ):\n        \"\"\"Update the dataset and re-train the model if not frozen.\n\n        Parameters\n        ----------\n        features: List[np.ndarray]\n            The extracted features.\n        costs: np.ndarray\n            The measured results.\n        group_hash: str\n            The hash of the group.\n        \"\"\"\n        self.state.add_to_group(features, costs, group_hash)\n        if not self.frozen:\n            self.predict_incremental(features, costs)\n            if self.state.untrained_size / self.state.data_size > 0.2:\n                self.train_full()\n            else:\n                self.train_incremental(features, costs)\n\n\n@derived_object\nclass MLPModel(PyCostModel):\n    \"\"\"Segment Sum MLP Model\n\n    Parameters\n    ----------\n    trainer: SegmentSumMLPTrainer\n        The trainer for the model, handling the training interface.\n    \"\"\"\n\n    trainer: SegmentSumMLPTrainer\n\n    def __init__(\n        self,\n        *,\n        trainer: Optional[SegmentSumMLPTrainer] = None,\n    ):\n        super().__init__()\n        self.trainer = trainer or SegmentSumMLPTrainer()\n\n    def load(self, path: str) -> None:\n        \"\"\"Load the cost model, cached data or raw data from given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        self.trainer.state.load(path)\n\n    def save(self, path: str) -> None:\n        \"\"\"Save the cost model and data to given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        self.trainer.state.save(path)\n\n    def update(\n        self,\n        context: TuneContext,\n        candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the dataset, re-train the cost model if not frozen.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n        results : List[RunnerResult]\n            The running results of the measure candidates.\n        \"\"\"\n        features, mean_costs = extract_features(\n            context, candidates, results, self.trainer.state.extractor\n        )\n        self.trainer.update(features, mean_costs, shash2hex(context.mod))\n\n    def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray:\n        \"\"\"Predict given the measure candidates.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n\n        Return\n        ------\n        result : np.ndarray\n            The predicted normalized score.\n        \"\"\"\n        features, _ = extract_features(context, candidates, None, self.trainer.state.extractor)\n        pred_results = self.trainer.predict_incremental(features)\n        return pred_results\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/random_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nRandom cost model\n\"\"\"\nfrom typing import List, Optional, Tuple, Union\n\nfrom ..cost_model import PyCostModel\nfrom ..runner import RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\nfrom ..utils import derived_object  # type: ignore\n\n\n@derived_object\nclass RandomModel(PyCostModel):\n    \"\"\"Random cost model\n\n    Parameters\n    ----------\n    random_state : Union[Tuple[str, np.ndarray, int, int, float], dict]\n        The random state of the random number generator.\n    path : Optional[str]\n        The path of the random cost model.\n    max_range : Optional[int]\n        The maximum range of random results, [0, max_range].\n\n    Reference\n    ---------\n    https://numpy.org/doc/stable/reference/random/generated/numpy.random.get_state.html\n    \"\"\"\n\n    import numpy as np  # type: ignore # pylint: disable=import-outside-toplevel\n\n    random_state: Union[Tuple[str, np.ndarray, int, int, float], dict]\n    path: Optional[str]\n\n    def __init__(\n        self,\n        *,\n        seed: Optional[int] = None,\n        path: Optional[str] = None,\n        max_range: Optional[int] = 100,\n    ):\n        import numpy as np  # type: ignore # pylint: disable=import-outside-toplevel\n\n        super().__init__()\n        if path is not None:\n            self.load(path)\n        else:\n            np.random.seed(seed)\n            self.random_state = np.random.get_state()\n        self.max_range = max_range\n\n    def load(self, path: str) -> None:\n        \"\"\"Load the cost model from given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        import numpy as np  # type: ignore # pylint: disable=import-outside-toplevel\n\n        self.random_state = tuple(np.load(path, allow_pickle=True))  # type: ignore\n\n    def save(self, path: str) -> None:\n        \"\"\"Save the cost model to given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n        \"\"\"\n        import numpy as np  # type: ignore # pylint: disable=import-outside-toplevel\n\n        np.save(path, np.array(self.random_state, dtype=object), allow_pickle=True)\n\n    def update(\n        self,\n        context: TuneContext,\n        candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the cost model given running results.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n        results : List[RunnerResult]\n            The running results of the measure candidates.\n        \"\"\"\n\n    def predict(\n        self, context: TuneContext, candidates: List[MeasureCandidate]\n    ) -> np.ndarray:  # type: ignore # pylint: disable=used-before-assignment\n        \"\"\"Update the cost model given running results.\n\n        Parameters\n        ----------\n        context : TuneContext,\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n\n        Return\n        ------\n        result : np.ndarray\n            The predicted running results.\n        \"\"\"\n        import numpy as np  # type: ignore # pylint: disable=import-outside-toplevel\n\n        np.random.set_state(self.random_state)\n        # TODO(@zxybazh): Use numpy's RandState object:\n        # https://numpy.org/doc/1.16/reference/generated/numpy.random.RandomState.html#numpy.random.RandomState\n        result = np.random.rand(len(candidates)) * self.max_range  # type: ignore\n        self.random_state = np.random.get_state()\n        return result\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/cost_model/xgb_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"XGBoost-based cost model\"\"\"\nimport os\nimport tempfile\nfrom collections import OrderedDict\nfrom itertools import chain as itertools_chain\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Optional, Tuple\n\nimport numpy as np  # type: ignore\n\nfrom ...contrib.tar import tar, untar\nfrom ...runtime import NDArray\nfrom ..cost_model import PyCostModel\nfrom ..feature_extractor import FeatureExtractor\nfrom ..logging import get_logger\nfrom ..runner import RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..utils import cpu_count, derived_object, shash2hex\nfrom .metric import max_curve\n\nif TYPE_CHECKING:\n    import xgboost as xgb  # type: ignore\n    from xgboost.callback import TrainingCallback  # type: ignore\n\n    from ..tune_context import TuneContext\n\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\ndef make_metric_sorter(focused_metric):\n    \"\"\"Make sure the focused metric is the first one.\"\"\"\n\n    def metric_name_for_sort(name):\n        if focused_metric == name:\n            return \"!\" + name\n        return name\n\n    def sort_key(key):\n        key, _ = key\n        return metric_name_for_sort(key)\n\n    return sort_key\n\n\nclass PackSum:\n    \"\"\"The pack-sum format\n\n    Parameters\n    ----------\n    dmatrix : xgb.DMatrix\n        A float64 array of shape [n, m],\n        where `n` is the packed number of blocks,\n        and `m` is the length of feature vector on each block\n    ids : np.ndarray\n        An int64 array of shape [n] containing nonnegative integers,\n        indicating which the index of a sample that a block belongs to\n    \"\"\"\n\n    dmatrix: \"xgb.DMatrix\"  # type: ignore # pylint: disable=invalid-name\n    ids: np.ndarray\n\n    def __init__(\n        self,\n        xs: List[np.ndarray],  # pylint: disable=invalid-name\n        ys: Optional[np.ndarray],  # pylint: disable=invalid-name\n    ):\n        \"\"\"Create PackSum format given a batch of samples\n\n        Parameters\n        ----------\n        xs : List[np.ndarray]\n            A batch of input samples\n        ys : Optional[List[float]]\n            A batch of labels. None means no labels available.\n        \"\"\"\n        import xgboost as xgb  # type: ignore # pylint: disable=import-outside-toplevel\n\n        repeats = [x.shape[0] for x in xs]\n        xs = np.concatenate(xs, axis=0)\n        self.ids = np.concatenate([[i] * repeat for i, repeat in enumerate(repeats)], axis=0)\n        if ys is None:\n            self.dmatrix = xgb.DMatrix(data=xs, label=None)\n        else:\n            ys = np.concatenate([[y] * repeat for y, repeat in zip(ys, repeats)], axis=0)\n            self.dmatrix = xgb.DMatrix(data=xs, label=ys)\n            self.dmatrix.set_weight(ys)\n\n    def predict_with_score(self, pred: np.ndarray) -> np.ndarray:\n        \"\"\"Predict the labels given the block level prediction scores.\n\n        Parameters\n        ----------\n        pred : np.ndarray\n            The block level predictions\n\n        Returns\n        -------\n        result : np.ndarray\n            The predictions for each candidate.\n        \"\"\"\n        return np.bincount(self.ids, weights=pred)\n\n    def obj_square_error(self, ys_pred: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"Implement square error loss on pack-sum format as\n        a custom objective function for xgboost.\n\n        Parameters\n        ----------\n        ys_pred: np.ndarray\n            The predictions\n\n        Returns\n        -------\n        gradient: np.ndarray\n            The gradient according to the xgboost format\n        hessian: np.ndarray\n            The hessian according to the xgboost format\n        \"\"\"\n        # Making prediction\n        ys_pred = self.predict_with_score(ys_pred)\n        # Propagate prediction to each block\n        ys_pred = ys_pred[self.ids]  # pylint: disable=invalid-sequence-index\n        # The gradient and hessian\n        ys = self.dmatrix.get_label()  # type: ignore # pylint: disable=invalid-name\n        gradient = ys_pred - ys\n        hessian = np.ones_like(gradient)\n        return gradient * ys, hessian * ys\n\n    def rmse(self, ys_pred: np.ndarray) -> Tuple[str, float]:\n        \"\"\"Evaluate RMSE (rooted mean square error) in the pack-sum format\n\n        Parameters\n        ----------\n        ys_pred: np.ndarray\n            The raw predictions\n\n        Returns\n        -------\n        name: str\n            The name of the metric\n        score: float\n            The score of the metric\n        \"\"\"\n        # Making prediction\n        ys_pred = self.predict_with_score(ys_pred)\n        # Propagate prediction to each block\n        ys_pred = ys_pred[self.ids]  # pylint: disable=invalid-sequence-index\n        # The RMSE\n        ys = self.dmatrix.get_label()  # type: ignore # pylint: disable=invalid-name\n        square_error = np.square(ys_pred - ys)\n        rmse = np.sqrt(square_error.mean())\n        return \"p-rmse\", rmse\n\n    def average_peak_score(\n        self,\n        ys_pred: np.ndarray,\n        n: int,\n    ) -> Tuple[str, float]:\n        \"\"\"Evaluate average-peak-score@N in the pack-sum format\n\n        Parameters\n        ----------\n        ys_pred: np.ndarray\n            The raw prediction\n        n : int\n            The N in average-peak-score@N\n\n        Returns\n        -------\n        name: str\n            The name of the metric\n        score: float\n            The score of the metric\n        \"\"\"\n        ys = self.dmatrix.get_label()  # type: ignore # pylint: disable=invalid-name\n        ys = self.predict_with_score(ys)  # type: ignore # pylint: disable=invalid-name\n        ys = ys / np.unique(self.ids, return_counts=True)[1]  # type: ignore # pylint: disable=invalid-name\n        ys_pred = self.predict_with_score(ys_pred)\n        trials = np.argsort(ys_pred)[::-1][:n]\n        trial_scores = ys[trials]\n        curve = max_curve(trial_scores) / np.max(ys)\n        score = np.mean(curve)\n        return f\"a-peak@{n}\", score\n\n\nclass XGBConfig(NamedTuple):\n    \"\"\"XGBoost model configuration\n\n    Parameters\n    ----------\n    max_depth : int\n        The maximum depth.\n    gamma : float\n        The gamma.\n    min_child_weight : float\n        The minimum child weight.\n    eta : float\n        The eta, learning rate.\n    seed : int\n        The random seed.\n    nthread : Optional[int],\n        The number of threads to use.\n        Default is None, which means to use physical number of cores.\n    \"\"\"\n\n    max_depth: int = 10\n    gamma: float = 0.001\n    min_child_weight: float = 0\n    eta: float = 0.2\n    seed: int = 43\n    nthread: Optional[int] = None\n\n    def to_dict(self):\n        return {\n            \"max_depth\": self.max_depth,\n            \"gamma\": self.gamma,\n            \"min_child_weight\": self.min_child_weight,\n            \"eta\": self.eta,\n            \"seed\": self.seed,\n            \"nthread\": self.nthread,\n        }\n\n\nclass FeatureGroup:\n    \"\"\"Feature group\n\n    Parameters\n    ----------\n    group_hash : str\n        The hash of the group\n    features : List[np.ndarray]\n        The features\n    costs : List[float]\n        The costs\n    min_cost : float\n        The minimum cost\n    \"\"\"\n\n    group_hash: str\n    features: List[np.ndarray]\n    costs: np.ndarray\n    min_cost: float\n\n    def __init__(\n        self,\n        group_hash: str,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n    ) -> None:\n        self.group_hash = group_hash\n        self.features = features\n        self.costs = costs\n        self.min_cost = np.min(costs)\n\n    def append(\n        self,\n        features: List[np.ndarray],\n        costs: np.ndarray,\n    ) -> None:\n        self.features.extend(features)\n        self.costs = np.append(self.costs, costs)\n        self.min_cost = np.min(self.costs)\n\n\n@derived_object\nclass XGBModel(PyCostModel):\n    \"\"\"XGBoost model\n\n    Parameters\n    ----------\n    extractor : FeatureExtractor\n        The feature extractor for the model.\n    config : XGBConfig\n        The XGBoost model config.\n    num_warmup_samples : int\n        The number of samples that are used for warmup, i.e., the first few samples are predicted\n        with random results.\n    early_stopping_rounds : int\n        The number of rounds for early stopping.\n    verbose_eval : int\n        The verbose level when doing evaluation.\n    average_peak_n : int\n        The number to calculate average peak score.\n    adaptive_training : bool\n        Whether use adaptive training to reduce tuning time.\n    \"\"\"\n\n    # feature extractor\n    extractor: FeatureExtractor\n    # xgboost model config\n    config: XGBConfig\n    # behavior of randomness\n    num_warmup_samples: int\n    # evaluation\n    early_stopping_rounds: int\n    verbose_eval: int\n    average_peak_n: int\n    # states\n    data: Dict[str, FeatureGroup]\n    data_size: int\n    booster: Optional[\"xgb.Booster\"]\n    # adaptive training\n    adaptive_training: bool\n    last_train_size: int\n\n    def __init__(\n        self,\n        *,\n        # feature extractor\n        extractor: FeatureExtractor.FeatureExtractorType = \"per-store-feature\",\n        # xgboost model config\n        config: XGBConfig = XGBConfig(),\n        # random result before enough samples\n        num_warmup_samples: int = 100,\n        # evaluation\n        early_stopping_rounds: int = 50,\n        verbose_eval: int = 25,\n        average_peak_n: int = 32,\n        adaptive_training: bool = True,\n    ):\n        super().__init__()\n        if not isinstance(extractor, FeatureExtractor):\n            extractor = FeatureExtractor.create(extractor)\n        # feature extractor\n        self.extractor = extractor\n        # model-related\n        if config.nthread is None:\n            # use physical core number\n            config = config._replace(nthread=cpu_count(logical=False))\n        self.config = config\n        # behavior of randomness\n        self.num_warmup_samples = num_warmup_samples\n        # evaluation\n        self.early_stopping_rounds = early_stopping_rounds\n        self.verbose_eval = verbose_eval\n        self.average_peak_n = average_peak_n\n        # states\n        self.data = OrderedDict()\n        self.data_size = 0\n        self.booster = None\n        # adaptive training\n        self.adaptive_training = adaptive_training\n        self.last_train_size = 0\n\n    def load(self, path: str) -> None:\n        \"\"\"Load the cost model from given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n\n        Note\n        ----\n        Since XGBoost model trains from scratch, each time this method loads the model together with\n        previously cached feature vectors and results, so that the subsequent training process could\n        use all the existing data being stored on disk.\n        \"\"\"\n        import xgboost as xgb  # pylint: disable=import-outside-toplevel\n\n        with tempfile.TemporaryDirectory() as tmp_dir:\n            model_path = os.path.join(tmp_dir, \"model.bin\")\n            data_path = os.path.join(tmp_dir, \"data.npy\")\n            # Step 1. Untar\n            untar(path, tmp_dir)\n            # Step 2. Load data\n            data = OrderedDict()\n            data_size = 0\n            for group_hash, features, costs in np.load(data_path, allow_pickle=True):\n                data[group_hash] = FeatureGroup(\n                    group_hash=group_hash,\n                    features=list(features),\n                    costs=costs,\n                )\n                data_size += len(costs)\n            # Step 3. Load the model\n            if os.path.exists(model_path):\n                booster = xgb.Booster()\n                booster.load_model(model_path)\n            else:\n                self.booster = None\n        self.data = data\n        self.data_size = data_size\n        self.booster = booster\n\n    def save(self, path: str) -> None:\n        \"\"\"Save the cost model to given file location.\n\n        Parameters\n        ----------\n        path : str\n            The file path.\n\n        Note\n        ----\n        Since XGBoost model trains from scratch, each time this method saves the model together with\n        previously cached feature vectors and results, so that the subsequent training process could\n        use all the existing data being stored on disk.\n        \"\"\"\n        with tempfile.TemporaryDirectory() as tmp_dir:\n            model_path = os.path.join(tmp_dir, \"model.bin\")\n            data_path = os.path.join(tmp_dir, \"data.npy\")\n            # Step 1. Save the model\n            booster = self.booster\n            if booster is not None:\n                booster.save_model(model_path)\n            else:\n                model_path = None\n            # Step 2. Save data\n            data = [\n                (\n                    g.group_hash,\n                    g.features,\n                    g.costs,\n                )\n                for g in self.data.values()\n            ]\n            np.save(\n                file=data_path,\n                arr=np.array(data, dtype=object),\n            )\n            # Step 3. Tar it\n            tar(path, [x for x in [model_path, data_path] if x is not None])\n            logger.info(\"Saved XGBModel to %s\", path)\n\n    def update(\n        self,\n        context: \"TuneContext\",\n        candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the cost model given running results.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n        results : List[RunnerResult]\n            The running results of the measure candidates.\n        \"\"\"\n        assert len(candidates) == len(results)\n        if len(candidates) == 0:\n            return\n\n        # Step 1. Get the feature group\n        new_group_hash = shash2hex(context.mod)\n        group = self.data.get(new_group_hash, None)\n\n        # Step 2. Extract features\n        def _feature(x: NDArray) -> np.ndarray:\n            return x.numpy().astype(\"float32\")\n\n        def _mean_cost(x: RunnerResult) -> float:\n            if not x.run_secs:\n                return 1e10\n            return float(np.median([float(s) for s in x.run_secs]))\n\n        new_features = [_feature(x) for x in self.extractor.extract_from(context, candidates)]\n        new_mean_costs = np.array([_mean_cost(x) for x in results]).astype(\"float32\")\n\n        # Steps 3. Run validation\n        if group is not None and self.booster is not None:\n            logger.debug(\n                \"XGB validation: %s\",\n                \"\\t\".join(\n                    f\"{key}: {score:.6f}\"\n                    for key, score in self._validate(\n                        xs=new_features,\n                        ys=group.min_cost / new_mean_costs,\n                    )\n                ),\n            )\n\n        # Step 4. Add the features into the data points\n        if group is None:\n            group = FeatureGroup(\n                group_hash=new_group_hash,\n                features=new_features,\n                costs=new_mean_costs,\n            )\n        else:\n            group.append(new_features, new_mean_costs)\n        self.data[new_group_hash] = group\n        self.data_size += len(new_features)\n\n        if (\n            self.adaptive_training\n            and self.data_size - self.last_train_size < self.last_train_size / 5\n        ):\n            # Set a training threshold related to `last_train_size` to reduce the training\n            # overhead when there're too many results\n            return\n        self.last_train_size = self.data_size\n\n        # Step 5. Re-train the model\n        self._train(\n            xs=list(itertools_chain.from_iterable([g.features for g in self.data.values()])),\n            ys=np.concatenate(\n                [g.min_cost / g.costs for g in self.data.values()],\n                axis=0,\n            ),\n        )\n\n    def predict(\n        self,\n        context: \"TuneContext\",\n        candidates: List[MeasureCandidate],\n    ) -> np.ndarray:\n        \"\"\"Predict the normalized score using the cost model.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context.\n        candidates : List[MeasureCandidate]\n            The measure candidates.\n\n        Return\n        ------\n        result : np.ndarray\n            The predicted normalized score.\n        \"\"\"\n        if self.data_size >= self.num_warmup_samples and self.booster is not None:\n            ret = self._predict(\n                xs=[\n                    x.numpy().astype(\"float32\")\n                    for x in self.extractor.extract_from(\n                        context,\n                        candidates,\n                    )\n                ]\n            )\n        else:\n            ret = np.random.uniform(\n                low=0,\n                high=1,\n                size=(len(candidates),),\n            )\n        return ret.astype(\"float64\")\n\n    def _train(  # type: ignore # pylint: disable=invalid-name\n        self,\n        xs: List[np.ndarray],\n        ys: np.ndarray,\n    ) -> None:\n        import xgboost as xgb  # type: ignore # pylint: disable=import-outside-toplevel\n\n        self.d_train = PackSum(xs=xs, ys=ys)\n\n        def obj(ys_pred: np.ndarray, d_train: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return self.d_train.obj_square_error(ys_pred)\n\n        def rmse(ys_pred: np.ndarray, d_train: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return self.d_train.rmse(ys_pred)\n\n        def avg_peak_score(ys_pred: np.ndarray, d_train: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return self.d_train.average_peak_score(ys_pred, self.average_peak_n)\n\n        self.booster = xgb.train(\n            self.config.to_dict(),\n            self.d_train.dmatrix,\n            num_boost_round=10000,\n            obj=obj,\n            callbacks=[\n                _get_custom_call_back(\n                    early_stopping_rounds=self.early_stopping_rounds,\n                    verbose_eval=self.verbose_eval,\n                    fevals=[rmse, avg_peak_score],\n                    evals=[(self.d_train.dmatrix, \"tr\")],\n                    cvfolds=None,\n                )\n            ],\n        )\n\n        del self.d_train\n\n    def _predict(  # type: ignore # pylint: disable=invalid-name\n        self,\n        xs: List[np.ndarray],\n    ) -> np.ndarray:\n        d_test = PackSum(xs=xs, ys=None)\n        pred = self.booster.predict(d_test.dmatrix)\n        ret = d_test.predict_with_score(pred)\n        return ret\n\n    def _validate(  # type: ignore # pylint: disable=invalid-name\n        self,\n        xs: List[np.ndarray],\n        ys: np.ndarray,\n    ) -> List[Tuple[str, float]]:\n        \"\"\"Evaluate the score of inputs.\n\n        Parameters\n        ----------\n        xs : List[np.ndarray]\n            A batch of input samples\n        ys : List[float]\n            A batch of labels\n\n        Returns\n        -------\n        scores: np.ndarray\n            The predicted result for all inputs.\n        \"\"\"\n        assert self.booster is not None\n\n        d_valid = PackSum(xs=xs, ys=ys)\n\n        def average_peak_score(ys_pred: np.ndarray):\n            return d_valid.average_peak_score(ys_pred, n=self.average_peak_n)\n\n        ys_pred = self.booster.predict(d_valid.dmatrix)\n        eval_result: List[Tuple[str, float]] = [\n            feval(ys_pred)\n            for feval in (\n                average_peak_score,\n                d_valid.rmse,\n            )\n        ]\n        eval_result.sort(key=make_metric_sorter(\"p-rmse\"))\n        return eval_result\n\n\ndef _get_custom_call_back(\n    early_stopping_rounds: int,\n    verbose_eval: int,\n    fevals: List[Callable],\n    evals: List[Tuple[\"xgb.DMatrix\", str]],\n    focused_metric: str = \"tr-p-rmse\",\n    cvfolds: List[\"xgb.training.CVPack\"] = None,\n) -> \"TrainingCallback\":\n    \"\"\"Get a customized callback function for XGBoost. Work around xgboost import.\"\"\"\n\n    def optional_xgboost_callback(cls):\n        \"\"\"Decorator for importing TrainingCallback from xgboost\"\"\"\n        # pylint:disable = import-outside-toplevel\n        try:\n            from xgboost.callback import TrainingCallback  # type: ignore\n        # pylint:enable = import-outside-toplevel\n        except ImportError:\n\n            class TrainingCallback:  # type: ignore\n                pass\n\n        class OptXGBoostCustomCallback(cls, TrainingCallback):  # type: ignore\n            pass\n\n        return OptXGBoostCustomCallback\n\n    @optional_xgboost_callback\n    class XGBoostCustomCallback:\n        \"\"\"Custom callback class for xgboost to support multiple custom evaluation functions\"\"\"\n\n        def __init__(\n            self,\n            early_stopping_rounds: int,\n            verbose_eval: int,\n            fevals: List[Callable],\n            evals: List[Tuple[\"xgb.DMatrix\", str]],\n            focused_metric: str = \"tr-p-rmse\",\n            cvfolds: List[\"xgb.training.CVPack\"] = None,\n        ):\n            self.early_stopping_rounds = early_stopping_rounds\n            self.verbose_eval = verbose_eval\n            self.fevals = fevals\n            self.evals = evals\n            self.state: Dict[str, Any] = {}\n            self.focused_metric = focused_metric\n            self.sort_key = make_metric_sorter(focused_metric=focused_metric)\n            self.cvfolds = cvfolds\n            if cvfolds is not None:\n                self.aggregated_cv = None\n\n        def __call__(self, env: \"xgb.core.CallbackEnv\"):\n            # Compatibility with xgboost < 1.3\n            return self.after_iteration(env.model, env.iteration, env.evaluation_result_list)\n\n        def init(self, model: \"xgb.Booster\"):\n            \"\"\"Internal function for initialization\"\"\"\n            booster: \"xgb.Booster\" = model\n            self.state[\"best_iteration\"] = 0\n            self.state[\"best_score\"] = float(\"inf\")\n            if booster is None:\n                assert self.cvfolds is not None\n                return\n            if booster.attr(\"best_score\") is not None:\n                self.state[\"best_score\"] = float(booster.attr(\"best_score\"))\n                self.state[\"best_iteration\"] = int(booster.attr(\"best_iteration\"))\n                self.state[\"best_msg\"] = booster.attr(\"best_msg\")\n            else:\n                booster.set_attr(best_iteration=str(self.state[\"best_iteration\"]))\n                booster.set_attr(best_score=str(self.state[\"best_score\"]))\n\n        def after_iteration(\n            self, model: \"xgb.Booster\", epoch: int, evals_log: Dict\n        ):  # pylint: disable = unused-argument\n            \"\"\"Internal function for after_iteration\"\"\"\n            # pylint:disable = import-outside-toplevel\n            try:\n                from xgboost.callback import _fmt_metric  # type: ignore\n            except ImportError:\n                # Compatibility with xgboost >= 1.6\n\n                def _fmt_metric(value, show_stdv=True):\n                    if len(value) == 2:\n                        return f\"{value[0]}:{value[1]:.5f}\"\n                    if len(value) == 3:\n                        if show_stdv:\n                            return f\"{value[0]}:{value[1]:.5f}+{value[2]:.5f}\"\n                        return f\"{value[0]}:{value[1]:.5f}\"\n                    raise ValueError(\"wrong metric value\", value)\n\n            import xgboost as xgb\n            from xgboost import rabit  # type: ignore\n\n            try:\n                from xgboost.training import aggcv  # type: ignore\n            except ImportError:\n                from xgboost.callback import _aggcv as aggcv  # type: ignore\n\n            # pylint:enable = import-outside-toplevel\n            if not self.state:\n                self.init(model)\n            booster: xgb.Booster = model\n            iteration: int = epoch\n            cvfolds: List[xgb.training.CVPack] = self.cvfolds\n            ##### Evaluation #####\n            # `eval_result` is a list of (key, score)\n            eval_result: List[Tuple[str, float]] = []\n            if cvfolds is None:\n                eval_result = list(\n                    itertools_chain.from_iterable(\n                        [\n                            (key, float(value))\n                            for key, value in map(\n                                lambda x: x.split(\":\"),\n                                booster.eval_set(\n                                    evals=self.evals,\n                                    iteration=iteration,\n                                    feval=feval,\n                                ).split()[1:],\n                            )\n                        ]\n                        for feval in self.fevals\n                    )\n                )\n            else:\n                eval_result = list(\n                    itertools_chain.from_iterable(\n                        [\n                            (key, score)\n                            for key, score, _std in aggcv(\n                                fold.eval(\n                                    iteration=iteration,\n                                    feval=feval,\n                                )\n                                for fold in cvfolds\n                            )\n                        ]\n                        for feval in self.fevals\n                    )\n                )\n            eval_result = list(eval_result)\n            eval_result.sort(key=self.sort_key)\n\n            ##### Print eval result #####\n            if self.verbose_eval and iteration % self.verbose_eval == 0:\n                info = []\n                for key, score in eval_result:\n                    if \"null\" not in key:\n                        info.append(f\"{key}: {score:.6f}\")\n                logger.debug(\"XGB iter %3d: %s\", iteration, \"\\t\".join(info))\n\n            ##### Choose score and do early stopping #####\n            score = None\n            for key, _score in eval_result:\n                if key == self.focused_metric:\n                    score = _score\n                    break\n            assert score is not None\n\n            best_score = self.state[\"best_score\"]\n            best_iteration = self.state[\"best_iteration\"]\n            if score < best_score:\n                tab = \"\\t\"  # to work with f-string\n                msg = f\"[{epoch}] {tab.join([_fmt_metric(x) for x in eval_result])}\"\n                self.state[\"best_msg\"] = msg\n                self.state[\"best_score\"] = score\n                self.state[\"best_iteration\"] = epoch\n                # save the property to attributes, so they will occur in checkpoint.\n                if model is not None:\n                    model.set_attr(\n                        best_score=str(self.state[\"best_score\"]),\n                        best_iteration=str(self.state[\"best_iteration\"]),\n                        best_msg=self.state[\"best_msg\"],\n                    )\n            elif epoch - best_iteration >= self.early_stopping_rounds:\n                best_msg = self.state[\"best_msg\"]\n\n                if self.verbose_eval and rabit.get_rank() == 0:\n                    logger.debug(\"XGB stopped. Best iteration: %s \", best_msg)\n                # instead of raising EarlyStopException, returning True to end the training\n                return True\n            # False to indicate training should not stop.\n            return False\n\n    return XGBoostCustomCallback(\n        early_stopping_rounds=early_stopping_rounds,\n        verbose_eval=verbose_eval,\n        fevals=fevals,\n        evals=evals,\n        focused_metric=focused_metric,\n        cvfolds=cvfolds,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.database package.\nThe database that stores serialized tuning records and workloads\n\"\"\"\nfrom .database import Database, PyDatabase, TuningRecord, Workload, create\nfrom .json_database import JSONDatabase\nfrom .memory_database import MemoryDatabase\nfrom .ordered_union_database import OrderedUnionDatabase\nfrom .schedule_fn_database import ScheduleFnDatabase\nfrom .union_database import UnionDatabase\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TuningRecord database\"\"\"\nfrom typing import Any, Callable, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.ir.module import IRModule\nfrom tvm.runtime import Object\nfrom tvm.target import Target\nfrom tvm.tir.schedule import Schedule, Trace\n\nfrom .. import _ffi_api\nfrom ..arg_info import ArgInfo\nfrom ..utils import _json_de_tvm\n\n\n@register_object(\"meta_schedule.Workload\")\nclass Workload(Object):\n    \"\"\"A workload, i.e. an IRModule and its structural hash.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The workload's IRModule\n    \"\"\"\n\n    mod: IRModule\n\n    def __init__(self, mod: IRModule) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.Workload,  # type: ignore # pylint: disable=no-member\n            mod,\n        )\n\n    def as_json(self) -> Any:\n        \"\"\"Export the workload to JSON as a python object.\n\n        Returns\n        -------\n        json : Any\n            The JSON serialized as a python object (e.g. a Dict or List).\n            Use json.dumps() to get the associated json string.\n        \"\"\"\n        return _json_de_tvm(_ffi_api.WorkloadAsJSON(self))  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def from_json(json_obj: Any) -> \"Workload\":\n        \"\"\"Create a workload from a json object.\n\n        Parameters\n        ----------\n        json_obj : Any\n            The json object to parse.\n\n        Returns\n        -------\n        tuning_record : TuningRecord\n            The parsed tuning record.\n        \"\"\"\n        return _ffi_api.WorkloadFromJSON(json_obj)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"meta_schedule.TuningRecord\")\nclass TuningRecord(Object):\n    \"\"\"The class of tuning records.\n\n    Parameters\n    ----------\n    trace : tvm.ir.Trace\n        The trace of the tuning record.\n    workload : Workload\n        The workload of the tuning record.\n    run_secs : Optional[List[float]]\n        The run time of the tuning record.\n    target : Optional[Target]\n        The target of the tuning record.\n    args_info : Optional[List[ArgInfo]]\n        The argument information of the tuning record.\n    \"\"\"\n\n    trace: Trace\n    workload: Workload\n    run_secs: Optional[List[float]]\n    target: Optional[Target]\n    args_info: Optional[List[ArgInfo]]\n\n    def __init__(  # type: ignore # pylint: disable=too-many-arguments\n        self,\n        trace: Trace,\n        workload: Workload,\n        run_secs: Optional[List[float]] = None,\n        target: Optional[Target] = None,\n        args_info: Optional[List[ArgInfo]] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.TuningRecord,  # type: ignore # pylint: disable=no-member\n            trace,\n            workload,\n            run_secs,\n            target,\n            args_info,\n        )\n\n    def as_measure_candidate(self) -> Any:\n        \"\"\"Generate a measure candidate given an initial IR module and a trace\n        stored in the tuning record.\n\n        Returns\n        -------\n        candidate : MeasureCandidate\n            A generated candidate.\n        \"\"\"\n        return _ffi_api.TuningRecordAsMeasureCandidate(self)  # type: ignore # pylint: disable=no-member\n\n    def as_json(self) -> Any:\n        \"\"\"Export the tuning record to a JSON string.\n\n        Returns\n        -------\n        json_str : str\n            The JSON string exported.\n        \"\"\"\n        return _json_de_tvm(_ffi_api.TuningRecordAsJSON(self))  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def from_json(json_obj: Any, workload: Workload) -> \"TuningRecord\":\n        \"\"\"Create a tuning record from a json object.\n\n        Parameters\n        ----------\n        json_obj : Any\n            The json object to parse.\n        workload : Workload\n            The workload.\n\n        Returns\n        -------\n        tuning_record : TuningRecord\n            The parsed tuning record.\n        \"\"\"\n        return _ffi_api.TuningRecordFromJSON(json_obj, workload)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"meta_schedule.Database\")\nclass Database(Object):\n    \"\"\"The abstract database interface.\"\"\"\n\n    DatabaseType = Union[\"Database\", Literal[\"json\", \"memory\"]]\n\n    def has_workload(self, mod: IRModule) -> bool:\n        \"\"\"Check if the database has the given workload.\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        Returns\n        -------\n        result : bool\n            Whether the database has the given workload.\n        \"\"\"\n        return _ffi_api.DatabaseHasWorkload(self, mod)  # type: ignore # pylint: disable=no-member\n\n    def commit_workload(self, mod: IRModule) -> Workload:\n        \"\"\"Commit a workload to the database if missing.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for or added.\n\n        Returns\n        -------\n        workload : Workload\n            The workload corresponding to the given IRModule.\n        \"\"\"\n        return _ffi_api.DatabaseCommitWorkload(self, mod)  # type: ignore # pylint: disable=no-member\n\n    def commit_tuning_record(self, record: TuningRecord) -> None:\n        \"\"\"Commit a tuning record to the database.\n\n        Parameters\n        ----------\n        record : TuningRecord\n            The tuning record to add.\n        \"\"\"\n        _ffi_api.DatabaseCommitTuningRecord(self, record)  # type: ignore # pylint: disable=no-member\n\n    def get_top_k(self, workload: Workload, top_k: int) -> List[TuningRecord]:\n        \"\"\"Get the top K tuning records of given workload from the database.\n\n        Parameters\n        ----------\n        workload : Workload\n            The workload to be searched for.\n        top_k : int\n            The number of top records to get.\n\n        Returns\n        -------\n        top_k_records : List[TuningRecord]\n            The top K records.\n        \"\"\"\n        return _ffi_api.DatabaseGetTopK(self, workload, top_k)  # type: ignore # pylint: disable=no-member\n\n    def get_all_tuning_records(self) -> List[TuningRecord]:\n        \"\"\"Get all the tuning records from the database.\n\n        Returns\n        -------\n        tuning_records : List[TuningRecord]\n            All tuning records from the database.\n        \"\"\"\n        return _ffi_api.DatabaseGetAllTuningRecords(self)  # type: ignore # pylint: disable=no-member\n\n    def __len__(self) -> int:\n        \"\"\"Get the number of records in the database.\n\n        Returns\n        -------\n        num_records : int\n            The number of records in the database\n        \"\"\"\n        return _ffi_api.DatabaseSize(self)  # type: ignore # pylint: disable=no-member\n\n    def query_tuning_record(\n        self,\n        mod: IRModule,\n        target: Target,\n        workload_name: str,\n    ) -> Optional[TuningRecord]:\n        \"\"\"Query the best record of the given workload from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : str\n            The name of the workload to be searched for.\n\n        Returns\n        -------\n        tuning_record : Optional[TuningRecord]\n            The best record of the given workload; None if not found.\n        \"\"\"\n        return _ffi_api.DatabaseQueryTuningRecord(self, mod, target, workload_name)  # type: ignore # pylint: disable=no-member\n\n    def query_schedule(\n        self,\n        mod: IRModule,\n        target: Target,\n        workload_name: str,\n    ) -> Optional[Schedule]:\n        \"\"\"Query the best schedule of the given workload from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : str\n            The name of the workload to be searched for.\n\n        Returns\n        -------\n        schedule : Optional[Schedule]\n            The best schedule of the given workload; None if not found.\n        \"\"\"\n        return _ffi_api.DatabaseQuerySchedule(self, mod, target, workload_name)  # type: ignore # pylint: disable=no-member\n\n    def query_ir_module(\n        self,\n        mod: IRModule,\n        target: Target,\n        workload_name: str,\n    ) -> Optional[IRModule]:\n        \"\"\"Query the best IRModule of the given workload from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : str\n            The name of the workload to be searched for.\n\n        Returns\n        -------\n        ir_module : Optional[IRModule]\n            The best IRModule of the given workload; None if not found.\n        \"\"\"\n        return _ffi_api.DatabaseQueryIRModule(self, mod, target, workload_name)  # type: ignore # pylint: disable=no-member\n\n    def query(\n        self,\n        mod: IRModule,\n        target: Target,\n        *,\n        workload_name: str = \"main\",\n        kind: Union[\n            Literal[\"schedule\"],\n            Literal[\"record\"],\n            Literal[\"ir_module\"],\n        ] = \"schedule\",\n    ) -> Union[Schedule, IRModule, TuningRecord]:\n        \"\"\"Query the database to retrieve the best optimization outcome of the given workload.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        kind : str = \"schedule\" | \"record\" | \"ir_module\"\n            The kind of the optimization outcome to be returned.\n\n        Returns\n        -------\n        result : Union[Schedule, IRModule, TuningRecord]\n            The best optimization outcome of the given workload.\n        \"\"\"\n        if kind == \"schedule\":\n            return self.query_schedule(mod, target, workload_name)\n        if kind == \"record\":\n            return self.query_tuning_record(mod, target, workload_name)\n        if kind == \"ir_module\":\n            return self.query_ir_module(mod, target, workload_name)\n        raise ValueError(f'Unknown kind: {kind}. Candidates are: \"schedule\", \"record\", \"ir_module\"')\n\n    def __enter__(self) -> \"Database\":\n        \"\"\"Entering the scope of the context manager\"\"\"\n        _ffi_api.DatabaseEnterWithScope(self)  # type: ignore # pylint: disable=no-member\n        return self\n\n    def __exit__(self, ptype, value, trace) -> None:\n        \"\"\"Exiting the scope of the context manager\"\"\"\n        _ffi_api.DatabaseExitWithScope(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def current() -> Optional[\"Database\"]:\n        \"\"\"Get the current database under scope.\"\"\"\n        return _ffi_api.DatabaseCurrent()  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Union[\n            Literal[\n                \"json\",\n                \"memory\",\n                \"union\",\n                \"ordered_union\",\n            ],\n            Callable[[Schedule], bool],\n        ] = \"json\",\n        *args,\n        **kwargs,\n    ) -> \"Database\":\n        \"\"\"Create a Database.\n\n        Parameters\n        ----------\n        kind : str = \"json\" | \"memory\" | \"union\" | \"ordered_union\" | Callable[[Schedule], bool]\n            The kind of the database to be created. The following kinds are supported:\n            \"json\", \"memory\", \"union\", \"ordered_union\", and a custom schedule function.\n\n        Returns\n        -------\n        database : Database\n            The created database.\n        \"\"\"\n        from . import (  # pylint: disable=import-outside-toplevel\n            JSONDatabase,\n            MemoryDatabase,\n            OrderedUnionDatabase,\n            ScheduleFnDatabase,\n            UnionDatabase,\n        )\n\n        if callable(kind):\n            return ScheduleFnDatabase(kind, *args, **kwargs)  # type: ignore\n        if kind == \"json\":\n            return JSONDatabase(*args, **kwargs)\n        if kind == \"memory\":\n            return MemoryDatabase(*args, **kwargs)  # type: ignore\n        if kind == \"union\":\n            return UnionDatabase(*args, **kwargs)  # type: ignore\n        if kind == \"ordered_union\":\n            return OrderedUnionDatabase(*args, **kwargs)  # type: ignore\n        raise ValueError(f\"Unknown Database: {kind}\")\n\n\ncreate = Database.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyDatabase\")\nclass _PyDatabase(Database):\n    \"\"\"\n    A TVM object database to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyDatabase\n    \"\"\"\n\n    def __init__(\n        self,\n        f_has_workload: Callable = None,\n        f_commit_workload: Callable = None,\n        f_commit_tuning_record: Callable = None,\n        f_get_top_k: Callable = None,\n        f_get_all_tuning_records: Callable = None,\n        f_query_tuning_record: Callable = None,\n        f_query_schedule: Callable = None,\n        f_query_ir_module: Callable = None,\n        f_size: Callable = None,\n        module_equality: str = \"structural\",\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabasePyDatabase,  # type: ignore  # pylint: disable=no-member\n            f_has_workload,\n            f_commit_workload,\n            f_commit_tuning_record,\n            f_get_top_k,\n            f_get_all_tuning_records,\n            f_query_tuning_record,\n            f_query_schedule,\n            f_query_ir_module,\n            f_size,\n            module_equality,\n        )\n\n\nclass PyDatabase:\n    \"\"\"\n    An abstract database with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyDatabase,\n        \"methods\": [\n            \"has_workload\",\n            \"commit_workload\",\n            \"commit_tuning_record\",\n            \"get_top_k\",\n            \"get_all_tuning_records\",\n            \"query_tuning_record\",\n            \"query_schedule\",\n            \"query_ir_module\",\n            \"__len__\",\n        ],\n    }\n\n    def has_workload(self, mod: IRModule) -> bool:\n        \"\"\"Check if the database has the given workload.\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        Returns\n        -------\n        result : bool\n            Whether the database has the given workload.\n        \"\"\"\n        raise NotImplementedError\n\n    def commit_workload(self, mod: IRModule) -> Workload:\n        \"\"\"Commit a workload to the database if missing.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for or added.\n\n        Returns\n        -------\n        workload : Workload\n            The workload corresponding to the given IRModule.\n        \"\"\"\n        raise NotImplementedError\n\n    def commit_tuning_record(self, record: TuningRecord) -> None:\n        \"\"\"Commit a tuning record to the database.\n\n        Parameters\n        ----------\n        record : TuningRecord\n            The tuning record to add.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_top_k(self, workload: Workload, top_k: int) -> List[TuningRecord]:\n        \"\"\"Get the top K tuning records of given workload from the database.\n\n        Parameters\n        ----------\n        workload : Workload\n            The workload to be searched for.\n        top_k : int\n            The number of top records to get.\n\n        Returns\n        -------\n        top_k_records : List[TuningRecord]\n            The top K records.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_all_tuning_records(self) -> List[TuningRecord]:\n        \"\"\"Get all the tuning records from the database.\n\n        Returns\n        -------\n        tuning_records : List[TuningRecord]\n            All tuning records from the database.\n        \"\"\"\n        raise NotImplementedError\n\n    def query_tuning_record(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[TuningRecord]:\n        \"\"\"Query a tuning record from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : Optional[str]\n            The workload name to be searched for.\n\n        Returns\n        -------\n        record : Optional[TuningRecord]\n            The tuning record corresponding to the given workload.\n        \"\"\"\n        # Using self._outer to replace the self pointer\n        return _ffi_api.DatabaseQueryTuningRecord(  # type: ignore # pylint: disable=no-member\n            self._outer(), mod, target, workload_name  # type: ignore # pylint: disable=no-member\n        )\n\n    def query_schedule(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[Schedule]:\n        \"\"\"Query a schedule from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : Optional[str]\n            The workload name to be searched for.\n\n        Returns\n        -------\n        schedule : Optional[Schedule]\n            The schedule corresponding to the given workload.\n        \"\"\"\n        # Using self._outer to replace the self pointer\n        return _ffi_api.DatabaseQuerySchedule(  # type: ignore # pylint: disable=no-member\n            self._outer(), mod, target, workload_name  # type: ignore # pylint: disable=no-member\n        )\n\n    def query_ir_module(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[IRModule]:\n        \"\"\"Query an IRModule from the database.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The IRModule to be searched for.\n        target : Target\n            The target to be searched for.\n        workload_name : Optional[str]\n            The workload name to be searched for.\n\n        Returns\n        -------\n        mod : Optional[IRModule]\n            The IRModule corresponding to the given workload.\n        \"\"\"\n        # Using self._outer to replace the self pointer\n        return _ffi_api.DatabaseQueryIRModule(  # type: ignore # pylint: disable=no-member\n            self._outer(), mod, target, workload_name  # type: ignore # pylint: disable=no-member\n        )\n\n    def __len__(self) -> int:\n        \"\"\"Get the number of records in the database.\n\n        Returns\n        -------\n        num_records : int\n            The number of records in the database\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/json_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The default database that uses a JSON File to store tuning records\"\"\"\nimport os.path as osp\nfrom typing import Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .database import Database\n\n\n@register_object(\"meta_schedule.JSONDatabase\")\nclass JSONDatabase(Database):\n    \"\"\"Database class backed by JSON.\n\n    Parameters\n    ----------\n    path_workload : str\n        The path to the workload table.\n    path_tuning_record : str\n        The path to the tuning record table.\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n    \"\"\"\n\n    path_workload: str\n    path_tuning_record: str\n\n    def __init__(\n        self,\n        path_workload: Optional[str] = None,\n        path_tuning_record: Optional[str] = None,\n        *,\n        work_dir: Optional[str] = None,\n        allow_missing: bool = True,\n        module_equality: str = \"structural\",\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        path_workload : Optional[str] = None\n            The path to the workload table. If not specified,\n            will be generated from `work_dir` as `$work_dir/database_workload.json`.\n        path_tuning_record : Optional[str] = None\n            The path to the tuning record table. If not specified,\n            will be generated from `work_dir` as `$work_dir/database_tuning_record.json`.\n        work_dir : Optional[str] = None\n            The work directory, if specified, will be used to generate `path_tuning_record`\n            and `path_workload`.\n        allow_missing : bool\n            Whether to create new file when the given path is not found.\n        \"\"\"\n        if work_dir is not None:\n            if path_workload is None:\n                path_workload = osp.join(work_dir, \"database_workload.json\")\n            if path_tuning_record is None:\n                path_tuning_record = osp.join(work_dir, \"database_tuning_record.json\")\n        if path_workload is None:\n            raise ValueError(\"`path_workload` is not specified.\")\n        if path_tuning_record is None:\n            raise ValueError(\"`path_tuning_record` is not specified.\")\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabaseJSONDatabase,  # type: ignore # pylint: disable=no-member\n            path_workload,\n            path_tuning_record,\n            allow_missing,\n            module_equality,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/memory_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A database that stores TuningRecords in memory\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .database import Database\n\n\n@register_object(\"meta_schedule.MemoryDatabase\")\nclass MemoryDatabase(Database):\n    \"\"\"An in-memory database\n\n    Parameters\n    ----------\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n    \"\"\"\n\n    def __init__(\n        self,\n        module_equality: str = \"structural\",\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabaseMemoryDatabase,  # type: ignore # pylint: disable=no-member,\n            module_equality,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/ordered_union_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A database consists of multiple databases.\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .database import Database\n\n\n@register_object(\"meta_schedule.OrderedUnionDatabase\")\nclass OrderedUnionDatabase(Database):\n    \"\"\"A database composed of multiple databases, allowing users to guide IR rewriting using\n    combined knowledge of those databases. To each query, it returns the record from the first\n    database that responds to the query.\n\n    Examples\n    --------\n    Examples below demonstrate the usecases of and difference between UnionDatabase and\n    OrderDatabase.\n\n    Assumption:\n    * db1, db2 do not have tuning records for the target workload.\n    * Each of db3, db4, db5 has tuning records r3, r4, r5 for target workload respectively.\n\n    .. code-block:: python\n\n    #### Case 1. `UnionDatabase`:\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        db4  # has r4\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 2. `OrderedUnionDatabase`\n    merged_db = ms.database.OrderedUnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        db4  # has r4\n    )\n    # returns r3\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 3. Mix-use scenario\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        ms.database.OrderedUnionDatabase( # returns r4\n            db4,  # has r4\n            db5,  # has r5\n        )\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 4. Another mix-use scenario\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        ms.database.UnionDatabase( # returns best one between r4 and r5\n            db4,  # has r4\n            db5,  # has r5\n        )\n    )\n    # returns the best one among r3, r4 and r5\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 5. Yet another mix-use scenario\n    merged_db = ms.database.OrderedUnionDatabase(\n        db1, # no record\n        db2, # no record\n        ms.database.UnionDatabase( # returns best one between r3 and r4\n            db3, # has r3\n            db4,  # has r4\n        )\n        db5,  # has r5\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n    \"\"\"\n\n    def __init__(self, *databases: Database) -> None:\n        \"\"\"Construct a merged database from multiple databases.\n\n        Parameters\n        ----------\n        *databases : Database\n            The list of databases to combine.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabaseOrderedUnionDatabase,  # type: ignore # pylint: disable=no-member\n            databases,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/schedule_fn_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A database for injecting handcrafted schedule functions.\"\"\"\nfrom typing import Callable\n\nfrom tvm._ffi import register_object\nfrom tvm.tir import Schedule\n\nfrom .. import _ffi_api\nfrom .database import Database\n\n\n@register_object(\"meta_schedule.ScheduleFnDatabase\")\nclass ScheduleFnDatabase(Database):\n    \"\"\"A database for injecting handcrafted schedule functions.\n\n    Parameters\n    ----------\n    schedule_fn : Callable[[Schedule], bool],\n        The function to do scheduling, which takes a TIR schedule, and returns\n        a boolean indicating if the schedule is committed to the database.\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n    \"\"\"\n\n    def __init__(\n        self,\n        schedule_fn: Callable[[Schedule], bool],\n        module_equality: str = \"structural\",\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabaseScheduleFnDatabase,  # type: ignore # pylint: disable=no-member\n            schedule_fn,\n            module_equality,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/database/union_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A database consists of multiple databases.\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .database import Database\n\n\n@register_object(\"meta_schedule.UnionDatabase\")\nclass UnionDatabase(Database):\n    \"\"\"A database composed of multiple databases, allowing users to guide IR rewriting using\n    combined knowledge of those databases. To each query, it returns the best record among all the\n    databases given.\n\n    Examples\n    --------\n    Examples below demonstrate the usecases of and difference between UnionDatabase and\n    OrderDatabase.\n\n    Assumption:\n    * db1, db2 do not have tuning records for the target workload.\n    * Each of db3, db4, db5 has tuning records r3, r4, r5 for target workload respectively.\n\n    .. code-block:: python\n\n    #### Case 1. `UnionDatabase`:\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        db4  # has r4\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 2. `OrderedUnionDatabase`\n    merged_db = ms.database.OrderedUnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        db4  # has r4\n    )\n    # returns r3\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 3. Mix-use scenario\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        ms.database.OrderedUnionDatabase( # returns r4\n            db4,  # has r4\n            db5,  # has r5\n        )\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 4. Another mix-use scenario\n    merged_db = ms.database.UnionDatabase(\n        db1, # no record\n        db2, # no record\n        db3, # has r3\n        ms.database.UnionDatabase( # returns best one between r4 and r5\n            db4,  # has r4\n            db5,  # has r5\n        )\n    )\n    # returns the best one among r3, r4 and r5\n    merged_db.query_tuning_record(..., target_workload)\n\n    ### Case 5. Yet another mix-use scenario\n    merged_db = ms.database.OrderedUnionDatabase(\n        db1, # no record\n        db2, # no record\n        ms.database.UnionDatabase( # returns best one between r3 and r4\n            db3, # has r3\n            db4,  # has r4\n        )\n        db5,  # has r5\n    )\n    # returns the better one between r3 and r4\n    merged_db.query_tuning_record(..., target_workload)\n    \"\"\"\n\n    def __init__(self, *databases: Database) -> None:\n        \"\"\"Construct a merged database from multiple databases.\n\n        Parameters\n        ----------\n        *databases : Database\n            The list of databases to combine.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.DatabaseUnionDatabase,  # type: ignore # pylint: disable=no-member\n            databases,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/extracted_task.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Extracted tasks from high-level IR.\"\"\"\nfrom typing import List\n\nfrom tvm._ffi import register_object\nfrom tvm.ir import IRModule\nfrom tvm.runtime import Object\nfrom tvm.target import Target\n\nfrom . import _ffi_api\n\n\n@register_object(\"meta_schedule.ExtractedTask\")\nclass ExtractedTask(Object):\n    \"\"\"A tuning task extracted from the high-level IR\n\n    Parameters\n    ----------\n    task_name : str\n        The name of the task extracted\n    mod : IRModule\n        The high-level IR\n    target: Target\n        Target information\n    dispatched : List[IRModule]\n        A list of low-level IRs that the high-level IR could potentially dispatch to\n    weight : int\n        The weight of the task\n    \"\"\"\n\n    task_name: str\n    mod: IRModule\n    dispatched: List[IRModule]\n    weight: int\n\n    def __init__(\n        self,\n        task_name: str,\n        mod: IRModule,\n        target: Target,\n        dispatched: List[IRModule],\n        weight: int,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ExtractedTask,  # type: ignore # pylint: disable=no-member\n            task_name,\n            mod,\n            target,\n            dispatched,\n            weight,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/feature_extractor/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.feature_extractor package.\nMeta Schedule feature extractors that extracts features from\nmeasure candidates for use in cost model.\n\"\"\"\nfrom .feature_extractor import FeatureExtractor, PyFeatureExtractor\nfrom .per_store_feature import PerStoreFeature\nfrom .random_feature_extractor import RandomFeatureExtractor\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/feature_extractor/feature_extractor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule FeatureExtractor.\"\"\"\nfrom typing import Callable, List, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.runtime.ndarray import NDArray\n\nfrom .. import _ffi_api\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\nfrom ..utils import _get_default_str\n\n\n@register_object(\"meta_schedule.FeatureExtractor\")\nclass FeatureExtractor(Object):\n    \"\"\"Extractor for features from measure candidates for use in cost model.\"\"\"\n\n    FeatureExtractorType = Union[Literal[\"per-store-feature\"], \"FeatureExtractor\"]\n\n    def extract_from(\n        self, context: TuneContext, candidates: List[MeasureCandidate]\n    ) -> List[NDArray]:\n        \"\"\"Extract features from the given measure candidate.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for feature extraction.\n        candidates : List[MeasureCandidate]\n            The measure candidates to extract features from.\n\n        Returns\n        -------\n        features : List[NDArray]\n            The feature tvm ndarray extracted.\n        \"\"\"\n        result = _ffi_api.FeatureExtractorExtractFrom(  # type: ignore # pylint: disable=no-member\n            self, context, candidates\n        )\n        return result\n\n    @staticmethod\n    def create(\n        kind: Literal[\"per-store-feature\"],\n        *args,\n        **kwargs,\n    ) -> \"FeatureExtractor\":\n        \"\"\"Create a CostModel.\"\"\"\n        from . import PerStoreFeature  # pylint: disable=import-outside-toplevel\n\n        if kind == \"per-store-feature\":\n            return PerStoreFeature(*args, **kwargs)  # type: ignore\n        raise ValueError(f\"Unknown CostModel: {kind}\")\n\n\n@register_object(\"meta_schedule.PyFeatureExtractor\")\nclass _PyFeatureExtractor(FeatureExtractor):\n    \"\"\"\n    A TVM object feature extractor to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyFeatureExtractor\n    \"\"\"\n\n    def __init__(self, f_extract_from: Callable, f_as_string: Callable = None):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.FeatureExtractorPyFeatureExtractor,  # type: ignore # pylint: disable=no-member\n            f_extract_from,\n            f_as_string,\n        )\n\n\nclass PyFeatureExtractor:\n    \"\"\"\n    An abstract feature extractor with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyFeatureExtractor,\n        \"methods\": [\"extract_from\", \"__str__\"],\n    }\n\n    def extract_from(\n        self, context: TuneContext, candidates: List[MeasureCandidate]\n    ) -> List[NDArray]:\n        \"\"\"Extract features from the given measure candidate.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for feature extraction.\n        candidates : List[MeasureCandidate]\n            The measure candidates to extract features from.\n\n        Returns\n        -------\n        features : List[NDArray]\n            The feature tvm ndarray extracted.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/feature_extractor/per_store_feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"We extract one feature vector per BufferStoreNode statement in a TIR Stmt,\nso we call this feature as \"per-store\" feature.\n\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .feature_extractor import FeatureExtractor\n\n\n@register_object(\"meta_schedule.PerStoreFeature\")\nclass PerStoreFeature(FeatureExtractor):\n    \"\"\"PerStoreFeature extracts one feature vector per BufferStoreNode\n\n    Parameters\n    ----------\n    buffers_per_store : int\n        The number of buffers in each BufferStore; Pad or truncate if necessary.\n    arith_intensity_curve_num_samples : int\n        The number of samples used in the arithmetic intensity curve.\n    cache_line_bytes : int\n        The number of bytes in a cache line.\n    extract_workload : bool\n        Whether to extract features in the workload in tuning context or not.\n    \"\"\"\n\n    buffers_per_store: int\n    \"\"\"The number of buffers in each BufferStore; Pad or truncate if necessary.\"\"\"\n    arith_intensity_curve_num_samples: int  # pylint: disable=invalid-name\n    \"\"\"The number of samples used in the arithmetic intensity curve.\"\"\"\n    cache_line_bytes: int\n    \"\"\"The number of bytes in a cache line.\"\"\"\n    extract_workload: bool\n    \"\"\"Whether to extract features in the workload in tuning context or not.\"\"\"\n    feature_vector_length: int\n    \"\"\"Length of the feature vector.\"\"\"\n\n    def __init__(\n        self,\n        buffers_per_store: int = 5,\n        arith_intensity_curve_num_samples: int = 10,\n        cache_line_bytes: int = 64,\n        extract_workload: bool = False,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.FeatureExtractorPerStoreFeature,  # type: ignore # pylint: disable=no-member\n            buffers_per_store,\n            arith_intensity_curve_num_samples,\n            cache_line_bytes,\n            extract_workload,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/feature_extractor/random_feature_extractor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Random Feature Extractor.\"\"\"\nfrom typing import List, Tuple, Union\n\nimport numpy as np  # type: ignore\nfrom tvm.runtime.ndarray import NDArray, array\n\nfrom ..feature_extractor import PyFeatureExtractor\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\nfrom ..utils import derived_object\n\n\n@derived_object\nclass RandomFeatureExtractor(PyFeatureExtractor):\n    \"\"\"Random Feature Extractor\n\n    Parameters\n    ----------\n    feature_size : int\n        The size of each block's feature vector.\n    max_block_num : int\n        The maximum number of blocks in each schedule.\n    random_state : Union[Tuple[str, np.ndarray, int, int, float], dict]\n        The current random state of the f\n    \"\"\"\n\n    feature_size: int\n    max_block_num: int\n    random_state: Union[Tuple[str, np.ndarray, int, int, float], dict]\n\n    def __init__(self, *, feature_size: int = 30, max_block_num: int = 5, seed=0):\n        super().__init__()\n        assert max_block_num >= 1, \"Max block number must be greater or equal to one!\"\n        self.max_block_num = max_block_num\n        self.feature_size = feature_size\n        np.random.seed(seed)\n        self.random_state = np.random.get_state()\n\n    def extract_from(\n        self, context: TuneContext, candidates: List[MeasureCandidate]\n    ) -> List[NDArray]:\n        np.random.set_state(self.random_state)\n        result = [\n            np.random.rand(np.random.randint(1, self.max_block_num + 1), self.feature_size)\n            for candidate in candidates\n        ]\n        self.random_state = np.random.get_state()\n        return [array(x) for x in result]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/logging.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Logging interface in MetaSchedule\"\"\"\nimport logging\nimport logging.config\nimport os\nimport os.path as osp\nfrom logging import Logger\nfrom typing import Any, Callable, Dict, List, Optional\n\n\ndef get_logger(name: str) -> Logger:\n    \"\"\"Create or get a logger by its name. This is essentially a wrapper of python's native logger.\n\n    Parameters\n    ----------\n    name : str\n        The name of the logger.\n\n    Returns\n    -------\n    logger : Logger\n        The logger instance.\n    \"\"\"\n    return logging.getLogger(name)\n\n\ndef get_logging_func(logger: Logger) -> Optional[Callable[[int, str, int, str], None]]:\n    \"\"\"Get the logging function.\n\n    Parameters\n    ----------\n    logger : Logger\n        The logger instance.\n    Returns\n    -------\n    result : Optional[Callable]\n        The function to do the specified level of logging.\n    \"\"\"\n    if logger is None:\n        return None\n\n    level2log = {\n        logging.DEBUG: logger.debug,\n        logging.INFO: logger.info,\n        logging.WARNING: logger.warning,\n        logging.ERROR: logger.error,\n        # logging.FATAL not included\n    }\n\n    def logging_func(level: int, filename: str, lineo: int, msg: str):\n        if level < 0:  # clear the output in notebook / console\n            from IPython.display import (  # type: ignore # pylint: disable=import-outside-toplevel\n                clear_output,\n            )\n\n            clear_output(wait=True)\n        else:\n            level2log[level](f\"[{os.path.basename(filename)}:{lineo}] \" + msg)\n\n    return logging_func\n\n\ndef create_loggers(\n    log_dir: str,\n    params: List[Dict[str, Any]],\n    logger_config: Optional[Dict[str, Any]] = None,\n    disable_existing_loggers: bool = False,\n):\n    \"\"\"Create loggers from configuration\"\"\"\n    if logger_config is None:\n        config = {}\n    else:\n        config = logger_config\n\n    config.setdefault(\"loggers\", {})\n    config.setdefault(\"handlers\", {})\n    config.setdefault(\"formatters\", {})\n\n    global_logger_name = \"tvm.meta_schedule\"\n    global_logger = logging.getLogger(global_logger_name)\n    if global_logger.level is logging.NOTSET:\n        global_logger.setLevel(logging.DEBUG)\n    console_logging_level = logging._levelToName[  # pylint: disable=protected-access\n        global_logger.level\n    ]\n\n    config[\"loggers\"].setdefault(\n        global_logger_name,\n        {\n            \"level\": logging.DEBUG,\n            \"handlers\": [handler.get_name() for handler in global_logger.handlers]\n            + [global_logger_name + \".console\", global_logger_name + \".file\"],\n            \"propagate\": False,\n        },\n    )\n    config[\"loggers\"].setdefault(\n        \"{logger_name}\",\n        {\n            \"level\": \"DEBUG\",\n            \"handlers\": [\n                \"{logger_name}.file\",\n            ],\n            \"propagate\": False,\n        },\n    )\n    config[\"handlers\"].setdefault(\n        global_logger_name + \".console\",\n        {\n            \"class\": \"logging.StreamHandler\",\n            \"stream\": \"ext://sys.stdout\",\n            \"formatter\": \"tvm.meta_schedule.standard_formatter\",\n            \"level\": console_logging_level,\n        },\n    )\n    config[\"handlers\"].setdefault(\n        global_logger_name + \".file\",\n        {\n            \"class\": \"logging.FileHandler\",\n            \"filename\": \"{log_dir}/\" + __name__ + \".task_scheduler.log\",\n            \"mode\": \"a\",\n            \"level\": \"DEBUG\",\n            \"formatter\": \"tvm.meta_schedule.standard_formatter\",\n        },\n    )\n    config[\"handlers\"].setdefault(\n        \"{logger_name}.file\",\n        {\n            \"class\": \"logging.FileHandler\",\n            \"filename\": \"{log_dir}/{logger_name}.log\",\n            \"mode\": \"a\",\n            \"level\": \"DEBUG\",\n            \"formatter\": \"tvm.meta_schedule.standard_formatter\",\n        },\n    )\n    config[\"formatters\"].setdefault(\n        \"tvm.meta_schedule.standard_formatter\",\n        {\n            \"format\": \"%(asctime)s [%(levelname)s] %(message)s\",\n            \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n        },\n    )\n\n    # set up dictConfig loggers\n    p_config = {\"version\": 1, \"disable_existing_loggers\": disable_existing_loggers}\n    for k, v in config.items():\n        if k in [\"formatters\", \"handlers\", \"loggers\"]:\n            p_config[k] = _batch_parameterize_config(v, params)  # type: ignore\n        else:\n            p_config[k] = v\n    logging.config.dictConfig(p_config)\n\n    # check global logger\n    if global_logger.level not in [logging.DEBUG, logging.INFO]:\n        global_logger.warning(\n            \"Logging level set to %s, please set to logging.INFO\"\n            \" or logging.DEBUG to view full log.\",\n            logging._levelToName[global_logger.level],  # pylint: disable=protected-access\n        )\n    global_logger.info(\"Logging directory: %s\", log_dir)\n\n\ndef _batch_parameterize_config(\n    config: Dict[str, Any],\n    params: List[Dict[str, str]],\n) -> Dict[str, Any]:\n    \"\"\"Parameterize the given configuration with multiple parameters sets.\n\n    Parameters\n    ----------\n    config : Dict[str, Any]\n        The given config dict.\n    Params : List[Dict[str, str]]\n        List of the given multiple parameters sets.\n\n    Returns\n    -------\n    result : Dict[str, Any]\n        The parameterized configuration.\n    \"\"\"\n    results = {}\n    for name, cfg in config.items():\n        for p in params:\n            p_name = name.format(**p)\n            if p_name not in results:\n                p_cfg = _parameterize_config(cfg, p)\n                results[p_name] = p_cfg\n    return results\n\n\ndef _parameterize_config(\n    config: Dict[str, Any],\n    params: Dict[str, str],\n) -> Dict[str, Any]:\n    \"\"\"Parameterize the given configuration.\n\n    Parameters\n    ----------\n    config : Dict[str, Any]\n        The given config dict.\n    Params : Dict[str, str]\n        The given parameters.\n\n    Returns\n    -------\n    result : Dict[str, Any]\n        The parameterized configuration.\n    \"\"\"\n    result = {}\n    for k, v in config.items():\n        if isinstance(k, str):\n            k = k.format(**params)\n        if isinstance(v, str):\n            v = v.format(**params)\n        elif isinstance(v, dict):\n            v = _parameterize_config(v, params)\n        elif isinstance(v, list):\n            v = [t.format(**params) for t in v]\n        result[k] = v\n    return result\n\n\ndef get_loggers_from_work_dir(\n    work_dir: str,\n    task_names: List[str],\n) -> List[Logger]:\n    \"\"\"Create loggers from work directory\n\n    Parameters\n    ----------\n    work_dir : str\n        The work directory.\n    task_names : List[str]\n        The list of task names.\n\n    Returns\n    -------\n    loggers : List[Logger]\n        The list of loggers.\n    \"\"\"\n    log_dir = osp.join(work_dir, \"logs\")\n    os.makedirs(log_dir, exist_ok=True)\n    pattern = __name__ + \".task_{i:0\" + f\"{len(str(len(task_names) - 1))}\" + \"d}_{name}\"\n    loggers = [pattern.format(i=i, name=name) for i, name in enumerate(task_names)]\n    create_loggers(\n        log_dir=log_dir,\n        params=[{\"log_dir\": log_dir, \"logger_name\": logger} for logger in loggers],\n    )\n    return [get_logger(logger) for logger in loggers]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/measure_callback/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The tvm.meta_schedule.measure_callback package.\"\"\"\nfrom .add_to_database import AddToDatabase\nfrom .measure_callback import MeasureCallback, PyMeasureCallback\nfrom .remove_build_artifact import RemoveBuildArtifact\nfrom .update_cost_model import UpdateCostModel\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/measure_callback/add_to_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A callback that adds the measurement results into the database\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .measure_callback import MeasureCallback\n\n\n@register_object(\"meta_schedule.AddToDatabase\")\nclass AddToDatabase(MeasureCallback):\n    def __init__(self) -> None:\n        \"\"\"A callback that adds the measurement results into the database\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureCallbackAddToDatabase,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/measure_callback/measure_callback.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule MeasureCallback.\"\"\"\n\nfrom typing import TYPE_CHECKING, Callable, List, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\n\nfrom .. import _ffi_api\nfrom ..builder import BuilderResult\nfrom ..runner import RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..utils import _get_default_str\n\nif TYPE_CHECKING:\n    from ..task_scheduler import TaskScheduler\n\n\n@register_object(\"meta_schedule.MeasureCallback\")\nclass MeasureCallback(Object):\n    \"\"\"Rules to apply after measure results is available.\"\"\"\n\n    CallbackListType = Union[List[\"MeasureCallback\"], \"MeasureCallback\", Literal[\"default\"]]\n\n    def apply(\n        self,\n        task_scheduler: \"TaskScheduler\",\n        task_id: int,\n        measure_candidates: List[MeasureCandidate],\n        builder_results: List[BuilderResult],\n        runner_results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Apply a measure callback to the given schedule.\n\n        Parameters\n        ----------\n        task_scheduler: TaskScheduler\n            The task scheduler.\n        task_id: int\n            The task id.\n        measure_candidates: List[MeasureCandidate]\n            The measure candidates.\n        builder_results: List[BuilderResult]\n            The builder results by building the measure candidates.\n        runner_results: List[RunnerResult]\n            The runner results by running the built measure candidates.\n        \"\"\"\n        return _ffi_api.MeasureCallbackApply(  # type: ignore # pylint: disable=no-member\n            self,\n            task_scheduler,\n            task_id,\n            measure_candidates,\n            builder_results,\n            runner_results,\n        )\n\n    @staticmethod\n    def create(kind: Literal[\"default\"]) -> List[\"MeasureCallback\"]:\n        \"\"\"Create a list of measure callbacks.\"\"\"\n        if kind == \"default\":\n            return _ffi_api.MeasureCallbackDefault()  # type: ignore # pylint: disable=no-member\n        raise ValueError(f\"Unknown kind of MeasureCallback list: {kind}\")\n\n\n@register_object(\"meta_schedule.PyMeasureCallback\")\nclass _PyMeasureCallback(MeasureCallback):\n    \"\"\"\n    A TVM object measure callback to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyMeasureCallback\n    \"\"\"\n\n    def __init__(self, f_apply: Callable, f_as_string: Callable = None):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureCallbackPyMeasureCallback,  # type: ignore # pylint: disable=no-member\n            f_apply,\n            f_as_string,\n        )\n\n\nclass PyMeasureCallback:\n    \"\"\"\n    An abstract measure callback with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyMeasureCallback,\n        \"methods\": [\"apply\", \"__str__\"],\n    }\n\n    def apply(\n        self,\n        task_scheduler: \"TaskScheduler\",\n        task_id: int,\n        measure_candidates: List[MeasureCandidate],\n        builder_results: List[BuilderResult],\n        runner_results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Apply a measure callback to the given schedule.\n\n        Parameters\n        ----------\n        task_scheduler: TaskScheduler\n            The task scheduler.\n        task_id: int\n            The task id.\n        measure_candidates: List[MeasureCandidate]\n            The measure candidates.\n        builder_results: List[BuilderResult]\n            The builder results by building the measure candidates.\n        runner_results: List[RunnerResult]\n            The runner results by running the built measure candidates.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/measure_callback/remove_build_artifact.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A callback that removes the build artifacts from the disk\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .measure_callback import MeasureCallback\n\n\n@register_object(\"meta_schedule.RemoveBuildArtifact\")\nclass RemoveBuildArtifact(MeasureCallback):\n    def __init__(self) -> None:\n        \"\"\"A callback that removes the build artifacts from the disk\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureCallbackRemoveBuildArtifact,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/measure_callback/update_cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A measure callback that updates the cost model\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .measure_callback import MeasureCallback\n\n\n@register_object(\"meta_schedule.UpdateCostModel\")\nclass UpdateCostModel(MeasureCallback):\n    def __init__(self) -> None:\n        \"\"\"A measure callback that updates the cost model\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureCallbackUpdateCostModel,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.mutator package.\nMeta Schedule mutator that mutates the trace to explore the\ndesign space.\n\"\"\"\nfrom .mutator import Mutator, PyMutator\nfrom .mutate_compute_location import MutateComputeLocation\nfrom .mutate_tile_size import MutateTileSize\nfrom .mutate_thread_binding import MutateThreadBinding\nfrom .mutate_parallel import MutateParallel\nfrom .mutate_unroll import MutateUnroll\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutate_compute_location.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A mutator that mutates the compute-at location decision of SampleComputeLocation\"\"\"\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .mutator import Mutator\n\n\n@register_object(\"meta_schedule.MutateComputeLocation\")\nclass MutateComputeLocation(Mutator):\n    \"\"\"A mutator that mutates the compute-at location decision of SampleComputeLocation\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutatorMutateComputeLocation,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutate_parallel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Mutator that mutates the parallel extent\"\"\"\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .mutator import Mutator\n\n\n@register_object(\"meta_schedule.MutateParallel\")\nclass MutateParallel(Mutator):\n    \"\"\"Mutator that mutates the parallel extent\"\"\"\n\n    def __init__(self, max_jobs_per_core: int) -> None:\n        \"\"\"Mutator that mutates the parallel extent\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutatorMutateParallel,  # type: ignore # pylint: disable=no-member\n            max_jobs_per_core,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutate_thread_binding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Mutator that mutates the thread binding extent\"\"\"\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .mutator import Mutator\n\n\n@register_object(\"meta_schedule.MutateThreadBinding\")\nclass MutateThreadBinding(Mutator):\n    \"\"\"Mutator that mutates the binding extent\"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Mutator that mutates the binding extent\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutateThreadBinding,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutate_tile_size.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Mutator that mutates the decision of instruction Sample-Perfect-Tile\"\"\"\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .mutator import Mutator\n\n\n@register_object(\"meta_schedule.MutateTileSize\")\nclass MutateTileSize(Mutator):\n    \"\"\"Mutator that mutates the decision of instruction Sample-Perfect-Tile\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutatorMutateTileSize,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutate_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Mutator that mutates auto unroll step\"\"\"\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .mutator import Mutator\n\n\n@register_object(\"meta_schedule.MutateUnroll\")\nclass MutateUnroll(Mutator):\n    \"\"\"Mutator that mutates auto unroll step\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutatorMutateUnroll,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/mutator/mutator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule Mutator.\"\"\"\nfrom typing import TYPE_CHECKING, Callable, Dict, Optional\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.tir.schedule import Trace\n\nfrom .. import _ffi_api\nfrom ..utils import _get_default_str\n\nif TYPE_CHECKING:\n    from ..tune_context import TuneContext\n\n\nclass Mutator(Object):\n    \"\"\"Mutator is designed to mutate the trace to explore the design space.\"\"\"\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the mutator with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the mutator.\n        \"\"\"\n        _ffi_api.MutatorInitializeWithTuneContext(  # type: ignore # pylint: disable=no-member\n            self, context\n        )\n\n    def apply(self, trace: Trace) -> Optional[Trace]:\n        \"\"\"Apply the mutator function to the given trace.\n\n        Parameters\n        ----------\n        trace : Trace\n            The given trace for mutation.\n\n        Returns\n        -------\n        trace : Optional[Trace]\n            None if mutator failed, otherwise return the mutated trace.\n        \"\"\"\n        return _ffi_api.MutatorApply(self, trace, -1)  # type: ignore # pylint: disable=no-member\n\n    def clone(self) -> \"Mutator\":\n        \"\"\"Clone the mutator.\n\n        Returns\n        -------\n        mutator : Mutator\n            The cloned mutator.\n        \"\"\"\n        return _ffi_api.MutatorClone(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(\n        kind: Literal[\n            \"llvm\",\n            \"cuda\",\n            \"cuda-tensorcore\",\n            \"hexagon\",\n        ]\n    ) -> Dict[\"Mutator\", float]:\n        \"\"\"Create a list of default mutators.\n\n        Parameters\n        ----------\n        kind : Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"]\n            The kind of mutators.\n\n        Returns\n        -------\n        mutators : List[Mutator]\n            The list of mutators.\n        \"\"\"\n        funcs = {\n            # pylint: disable=no-member\n            \"llvm\": _ffi_api.MutatorDefaultLLVM,  # type: ignore\n            \"cuda\": _ffi_api.MutatorDefaultCUDA,  # type: ignore\n            \"cuda-tensorcore\": _ffi_api.MutatorDefaultCUDATensorCore,  # type: ignore\n            \"hexagon\": _ffi_api.MutatorDefaultHexagon,  # type: ignore\n            # pylint: enable=no-member\n        }\n        for k, v in funcs.items():\n            if k == kind:\n                return v()\n        raise ValueError(f\"Unsupported kind {kind} for mutator creation.\")\n\n\ncreate = Mutator.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyMutator\")\nclass _PyMutator(Mutator):\n    \"\"\"\n    A TVM object mutator to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyMutator\n    \"\"\"\n\n    def __init__(\n        self,\n        f_initialize_with_tune_context: Callable = None,\n        f_apply: Callable = None,\n        f_clone: Callable = None,\n        f_as_string: Callable = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.MutatorPyMutator,  # type: ignore # pylint: disable=no-member\n            f_initialize_with_tune_context,\n            f_apply,\n            f_clone,\n            f_as_string,\n        )\n\n\nclass PyMutator:\n    \"\"\"\n    An abstract mutator with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyMutator,\n        \"methods\": [\"_initialize_with_tune_context\", \"apply\", \"clone\", \"__str__\"],\n    }\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the mutator with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the mutator.\n        \"\"\"\n        raise NotImplementedError\n\n    def apply(self, trace: Trace, _) -> Optional[Trace]:\n        \"\"\"Apply the mutator function to the given trace.\n\n        Parameters\n        ----------\n        trace : Trace\n            The given trace for mutation.\n\n        Returns\n        -------\n        trace : Optional[Trace]\n            None if mutator failed, otherwise return the mutated trace.\n        \"\"\"\n        raise NotImplementedError\n\n    def clone(self) -> Mutator:\n        \"\"\"Clone the mutator.\n\n        Returns\n        -------\n        mutator : Mutator\n            The cloned mutator.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        \"\"\"Get the mutator as string with name.\n\n        Return\n        ------\n        result : str\n            Get the mutator as string with name.\n        \"\"\"\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The tvm.meta_schedule.postproc package.\"\"\"\nfrom .disallow_dynamic_loop import DisallowDynamicLoop\nfrom .postproc import Postproc, PyPostproc\nfrom .rewrite_cooperative_fetch import RewriteCooperativeFetch\nfrom .rewrite_layout import RewriteLayout\nfrom .rewrite_parallel_vectorize_unroll import RewriteParallelVectorizeUnroll\nfrom .rewrite_reduction_block import RewriteReductionBlock\nfrom .rewrite_tensorize import RewriteTensorize\nfrom .rewrite_unbound_block import RewriteUnboundBlock\nfrom .verify_gpu_code import VerifyGPUCode\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/disallow_dynamic_loop.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that checks if the IRModule has any loop with non-constant extent\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.DisallowDynamicLoop\")\nclass DisallowDynamicLoop(Postproc):\n    \"\"\"A postprocessor that checks if the IRModule has any loop with non-constant extent\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocDisallowDynamicLoop,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/postproc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule Postproc.\"\"\"\nfrom typing import TYPE_CHECKING, Callable, List\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.tir.schedule import Schedule\n\nfrom .. import _ffi_api\nfrom ..utils import _get_default_str\n\nif TYPE_CHECKING:\n    from ..tune_context import TuneContext\n\n\n@register_object(\"meta_schedule.Postproc\")\nclass Postproc(Object):\n    \"\"\"Rules to apply a postprocessor to a schedule.\"\"\"\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the postprocessor with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the postprocessor.\n        \"\"\"\n        _ffi_api.PostprocInitializeWithTuneContext(  # type: ignore # pylint: disable=no-member\n            self, context\n        )\n\n    def apply(self, sch: Schedule) -> bool:\n        \"\"\"Apply a postprocessor to the given schedule.\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be post processed.\n\n        Returns\n        -------\n        result : bool\n            Whether the postprocessor was successfully applied.\n        \"\"\"\n        return _ffi_api.PostprocApply(self, sch)  # type: ignore # pylint: disable=no-member\n\n    def clone(self) -> \"Postproc\":\n        \"\"\"Clone the postprocessor.\n\n        Returns\n        -------\n        cloned_postproc : Postproc\n            The cloned postprocessor.\n        \"\"\"\n        return _ffi_api.PostprocClone(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(kind: Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"]) -> List[\"Postproc\"]:\n        \"\"\"Create a list of default postprocessors.\n\n        Parameters\n        ----------\n        kind : Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"]\n            The kind of the postprocessors.\n\n        Returns\n        -------\n        postprocs : List[Mutator]\n            The list of postprocessors.\n        \"\"\"\n        funcs = {\n            # pylint: disable=no-member\n            \"llvm\": _ffi_api.PostprocDefaultLLVM,  # type: ignore\n            \"cuda\": _ffi_api.PostprocDefaultCUDA,  # type: ignore\n            \"cuda-tensorcore\": _ffi_api.PostprocDefaultCUDATensorCore,  # type: ignore\n            \"hexagon\": _ffi_api.PostprocDefaultHexagon,  # type: ignore\n            # pylint: enable=no-member\n        }\n        for k, v in funcs.items():\n            if k == kind:\n                return v()\n        raise ValueError(f\"Unsupported kind {kind} for postproc creation.\")\n\n\ncreate = Postproc.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyPostproc\")\nclass _PyPostproc(Postproc):\n    \"\"\"\n    A TVM object post processor to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyPostproc\n    \"\"\"\n\n    def __init__(\n        self,\n        f_initialize_with_tune_context: Callable = None,\n        f_apply: Callable = None,\n        f_clone: Callable = None,\n        f_as_string: Callable = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocPyPostproc,  # type: ignore # pylint: disable=no-member\n            f_initialize_with_tune_context,\n            f_apply,\n            f_clone,\n            f_as_string,\n        )\n\n\nclass PyPostproc:\n    \"\"\"\n    An abstract post processor with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyPostproc,\n        \"methods\": [\"_initialize_with_tune_context\", \"apply\", \"clone\", \"__str__\"],\n    }\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the postprocessor with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the postprocessor.\n        \"\"\"\n        raise NotImplementedError\n\n    def apply(self, sch: Schedule) -> bool:\n        \"\"\"Apply a postprocessor to the given schedule.\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be post processed.\n\n        Returns\n        -------\n        result : bool\n            Whether the postprocessor was successfully applied.\n        \"\"\"\n        raise NotImplementedError\n\n    def clone(self) -> Postproc:\n        \"\"\"Clone the postprocessor.\n\n        Returns\n        -------\n        cloned_postproc : Postproc\n            The cloned postprocessor.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        \"\"\"Get the post processor as string with name.\n\n        Return\n        ------\n        result : str\n            Get the post processor as string with name.\n        \"\"\"\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_cooperative_fetch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that rewrites the cooperative fetch annotation to actual\nvectorized cooperative fetching in loop bindings.\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteCooperativeFetch\")\nclass RewriteCooperativeFetch(Postproc):\n    \"\"\"A postprocessor that rewrites the cooperative fetch annotation to actual vectorized\n    cooperative fetching in loop bindings.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteCooperativeFetch,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that rewrites the layout of input tensor\"\"\"\n\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteLayout\")\nclass RewriteLayout(Postproc):\n    \"\"\"A postprocessor that rewrites the layout of input tensor\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteLayout,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_parallel_vectorize_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that applies parallelization, vectorization and auto unrolling\naccording to the annotation of each block\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteParallelVectorizeUnroll\")\nclass RewriteParallelVectorizeUnroll(Postproc):\n    \"\"\"A postprocessor that applies parallelization, vectorization and auto unrolling\n    according to the annotation of each block\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteParallelVectorizeUnroll,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_reduction_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that rewrites reduction block by moving the init block out.\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteReductionBlock\")\nclass RewriteReductionBlock(Postproc):\n    \"\"\"A postprocessor that rewrites reduction block by moving the init block out.\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteReductionBlock,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that tensorize related components.\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteTensorize\")\nclass RewriteTensorize(Postproc):\n    \"\"\"A postprocessor that applies tensorization to annotated blocks.\n\n    Parameters\n    ----------\n    vectorize_init_loop : bool\n       Whether or not vectorize the initialization loop produced by DecomposeReduction\n    \"\"\"\n\n    def __init__(self, vectorize_init_loop=False) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteTensorize,  # type: ignore # pylint: disable=no-member\n            vectorize_init_loop,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/rewrite_unbound_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that adds thread binding to unbound blocks\"\"\"\n\nfrom tvm._ffi.registry import register_object\n\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.RewriteUnboundBlock\")\nclass RewriteUnboundBlock(Postproc):\n    \"\"\"A postprocessor that adds thread binding to unbound blocks\"\"\"\n\n    def __init__(self, max_threadblocks: int = 256) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocRewriteUnboundBlock,  # type: ignore # pylint: disable=no-member\n            max_threadblocks,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/postproc/verify_gpu_code.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A postprocessor that verifies if the GPU code is correct\"\"\"\n\nfrom tvm._ffi.registry import register_object\nfrom .. import _ffi_api\nfrom .postproc import Postproc\n\n\n@register_object(\"meta_schedule.VerifyGPUCode\")\nclass VerifyGPUCode(Postproc):\n    \"\"\"A postprocessor that verifies if the GPU code is correct\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.PostprocVerifyGPUCode,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A context manager that profiles tuning time cost for different parts.\"\"\"\nfrom contextlib import contextmanager\nfrom typing import Dict, Optional\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\n\n@register_object(\"meta_schedule.Profiler\")\nclass Profiler(Object):\n    \"\"\"Tuning time profiler.\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.Profiler,  # type: ignore # pylint: disable=no-member\n        )\n\n    def get(self) -> Dict[str, float]:\n        \"\"\"Get the profiling results in seconds\"\"\"\n        return _ffi_api.ProfilerGet(self)  # type: ignore # pylint: disable=no-member\n\n    def table(self) -> str:\n        \"\"\"Get the profiling results in a table format\"\"\"\n        return _ffi_api.ProfilerTable(self)  # type: ignore # pylint: disable=no-member\n\n    def __enter__(self) -> \"Profiler\":\n        \"\"\"Entering the scope of the context manager\"\"\"\n        _ffi_api.ProfilerEnterWithScope(self)  # type: ignore # pylint: disable=no-member\n        return self\n\n    def __exit__(self, ptype, value, trace) -> None:\n        \"\"\"Exiting the scope of the context manager\"\"\"\n        _ffi_api.ProfilerExitWithScope(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def current() -> Optional[\"Profiler\"]:\n        \"\"\"Get the current profiler.\"\"\"\n        return _ffi_api.ProfilerCurrent()  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def timeit(name: str):\n        \"\"\"Timeit a block of code\"\"\"\n\n        @contextmanager\n        def _timeit():\n            try:\n                f = _ffi_api.ProfilerTimedScope(name)  # type: ignore # pylint: disable=no-member\n                yield\n            finally:\n                if f:\n                    f()\n\n        return _timeit()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/relay_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"MetaSchedule-Relay integration\"\"\"\nfrom contextlib import contextmanager\nfrom types import MappingProxyType\nfrom typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Tuple, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\nimport numpy as np  # type: ignore\nfrom tvm import nd\nfrom tvm._ffi import get_global_func\nfrom tvm.ir import IRModule, transform\nfrom tvm.runtime import NDArray\nfrom tvm.target import Target\n\nfrom .builder import Builder\nfrom .cost_model import CostModel\nfrom .database import Database\nfrom .extracted_task import ExtractedTask\nfrom .logging import get_loggers_from_work_dir\nfrom .measure_callback import MeasureCallback\nfrom .profiler import Profiler\nfrom .runner import Runner\nfrom .search_strategy import SearchStrategy\nfrom .space_generator import SpaceGenerator\nfrom .task_scheduler import TaskScheduler\nfrom .tune import tune_tasks\nfrom .tune_context import TuneContext\nfrom .utils import fork_seed\n\nif TYPE_CHECKING:\n    from tvm import relay\n\n_extract_task = get_global_func(  # pylint: disable=invalid-name\n    \"relay.backend.MetaScheduleExtractTask\",\n    allow_missing=True,\n)\n\n\n@contextmanager\ndef _autotvm_silencer():\n    \"\"\"A context manager that silences autotvm warnings.\"\"\"\n    from tvm import autotvm  # pylint: disable=import-outside-toplevel\n\n    silent = autotvm.GLOBAL_SCOPE.silent\n    autotvm.GLOBAL_SCOPE.silent = True\n    try:\n        yield\n    finally:\n        autotvm.GLOBAL_SCOPE.silent = silent\n\n\ndef _normalize_params(\n    mod: IRModule,\n    target: Union[Target, str],\n    params: Optional[Dict[str, NDArray]],\n    pass_config: Mapping[str, Any],\n    executor: Optional[\"relay.backend.Executor\"],\n) -> Tuple[\n    IRModule,\n    Target,\n    Dict[str, NDArray],\n    Dict[str, Any],\n    Optional[\"relay.backend.Executor\"],\n]:\n    from tvm import relay  # pylint: disable=import-outside-toplevel\n\n    if isinstance(mod, relay.Function):\n        mod = IRModule.from_expr(mod)\n    if not isinstance(target, Target):\n        target = Target(target)\n    if params is None:\n        params = {}\n    relay_params = {}\n    for name, param in params.items():\n        if isinstance(param, np.ndarray):\n            param = nd.array(param)\n        relay_params[name] = param\n\n    if executor is None:\n        executor = relay.backend.Executor(\"graph\")\n\n    if mod.get_attr(\"executor\") is None:\n        mod = mod.with_attr(\"executor\", executor)\n    else:\n        executor = mod.get_attr(\"executor\")\n\n    pass_config = dict(pass_config)\n    return mod, target, relay_params, pass_config, executor\n\n\ndef extract_tasks(\n    mod: IRModule,\n    target: Union[Target, str],\n    params: Optional[Dict[str, NDArray]],\n    *,\n    opt_level: int = 3,\n    pass_config: Mapping[str, Any] = MappingProxyType(\n        {\n            \"relay.backend.use_meta_schedule\": True,\n            \"relay.backend.tir_converter\": \"default\",\n        }\n    ),\n    executor: Optional[\"relay.backend.Executor\"] = None,\n    module_equality: str = \"structural\",\n) -> List[ExtractedTask]:\n    \"\"\"Extract tuning tasks from a relay program.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The module or function to tune\n    target : tvm.target.Target\n        The compilation target\n    params : Optional[Dict[str, tvm.runtime.NDArray]]\n        The associated parameters of the program\n    opt_level : int\n        The optimization level of the compilation\n    pass_config : Mapping[str, Any]\n        The pass configuration\n    executor : Optional[relay.backend.Executor]\n        The executor to use\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n\n    Returns\n    -------\n    tasks: List[ExtractedTask]\n        The tasks extracted from this network\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import autotvm\n\n    # pylint: enable=import-outside-toplevel\n    mod, target, params, pass_config, _ = _normalize_params(\n        mod, target, params, pass_config, executor\n    )\n    if target.kind.name != \"cuda\" and isinstance(\n        autotvm.DispatchContext.current, autotvm.FallbackContext\n    ):\n        tophub_context = autotvm.tophub.context(target)\n    else:\n        tophub_context = autotvm.utils.EmptyContext()\n    with Profiler.timeit(\"TaskExtraction\"):\n        with target, _autotvm_silencer(), tophub_context:\n            with transform.PassContext(\n                opt_level=opt_level,\n                config=pass_config,\n            ):\n                return list(_extract_task(mod, target, params, module_equality))\n\n\ndef extracted_tasks_to_tune_contexts(\n    extracted_tasks: List[ExtractedTask],\n    work_dir: str,\n    space: SpaceGenerator.SpaceGeneratorType = \"post-order-apply\",\n    strategy: SearchStrategy.SearchStrategyType = \"evolutionary\",\n    num_threads: Union[Literal[\"physical\", \"logical\"], int] = \"physical\",\n    seed: Optional[int] = None,\n) -> Tuple[List[TuneContext], List[float]]:\n    \"\"\"Convert ExtractedTask to TuneContext.\n\n    Parameters\n    ----------\n    tasks : List[ExtractedTask]\n        The tasks to be converted\n    work_dir : str\n        The working directory to store logs and databases\n    space : SpaceGenerator.SpaceGeneratorType\n        The space generator to use.\n    strategy : SearchStrategy.SearchStrategyType\n        The search strategy to use.\n    num_threads : Union[Literal[\"physical\", \"logical\"], int]\n        The number of threads to use in multi-threaded search algorithm.\n    seed : Optional[int]\n        The random seed to use.\n\n    Returns\n    -------\n    tasks : List[TuneContext]\n        The converted tasks\n    task_weights : List[float]\n        The weights of the tasks\n    \"\"\"\n    tasks: List[TuneContext] = []\n    task_weights: List[float] = []\n    for task, logger, rand_state in zip(\n        extracted_tasks,\n        get_loggers_from_work_dir(work_dir, [t.task_name for t in extracted_tasks]),\n        fork_seed(seed, n=len(extracted_tasks)),\n    ):\n        tasks.append(\n            TuneContext(\n                mod=task.dispatched[0],\n                target=task.target,\n                space_generator=space,\n                search_strategy=strategy,\n                task_name=task.task_name,\n                logger=logger,\n                rand_state=rand_state,\n                num_threads=num_threads,\n            ).clone()\n        )\n        task_weights.append(task.weight)\n    return tasks, task_weights\n\n\ndef tune_relay(\n    mod: IRModule,\n    params: Dict[str, NDArray],\n    target: Union[str, Target],\n    work_dir: str,\n    max_trials_global: int,\n    *,\n    max_trials_per_task: Optional[int] = None,\n    num_trials_per_iter: int = 64,\n    builder: Builder.BuilderType = \"local\",\n    runner: Runner.RunnerType = \"local\",\n    database: Database.DatabaseType = \"json\",\n    cost_model: CostModel.CostModelType = \"xgb\",\n    measure_callbacks: MeasureCallback.CallbackListType = \"default\",\n    task_scheduler: TaskScheduler.TaskSchedulerType = \"gradient\",\n    space: SpaceGenerator.SpaceGeneratorType = \"post-order-apply\",\n    strategy: SearchStrategy.SearchStrategyType = \"evolutionary\",\n    seed: Optional[int] = None,\n    module_equality: str = \"structural\",\n) -> Database:\n    \"\"\"Tune a Relay program.\n\n    Parameters\n    ----------\n    mod : Union[IRModule, tir.PrimFunc]\n        The module or function to tune\n    params : Optional[Dict[str, tvm.runtime.NDArray]]\n        The associated parameters of the program\n    target : Union[Target, str]\n        The compilation target\n    work_dir : str\n        The working directory to store the tuning records\n    max_trials_global : int\n        The maximum number of trials to run\n    max_trials_per_task : Optional[int]\n        The maximum number of trials to run for each task\n    num_trials_per_iter : int\n        The number of trials to run per iteration\n    builder : BuilderType\n        The builder to use\n    runner : RunnerType\n        The runner to use\n    database : DatabaseType\n        The database to use\n    cost_model : CostModelType\n        The cost model to use\n    measure_callbacks : CallbackListType\n        The measure callbacks to use\n    task_scheduler : TaskSchedulerType\n        The task scheduler to use\n    space : SpaceGeneratorType\n        The space generator to use\n    strategy : SearchStrategyType\n        The search strategy to use\n    seed : Optional[int]\n        The random seed\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n\n    Returns\n    -------\n    database : Database\n        The database that contains the tuning records\n    \"\"\"\n    tasks, task_weights = extracted_tasks_to_tune_contexts(\n        extracted_tasks=extract_tasks(mod, target, params, module_equality=module_equality),\n        work_dir=work_dir,\n        space=space,\n        strategy=strategy,\n        seed=seed,\n    )\n    return tune_tasks(\n        tasks=tasks,\n        task_weights=task_weights,\n        work_dir=work_dir,\n        max_trials_global=max_trials_global,\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        builder=builder,\n        runner=runner,\n        database=database,\n        cost_model=cost_model,\n        measure_callbacks=measure_callbacks,\n        task_scheduler=task_scheduler,\n        module_equality=module_equality,\n    )\n\n\ndef compile_relay(\n    database: Database,\n    mod: IRModule,\n    target: Union[Target, str],\n    params: Optional[Dict[str, NDArray]],\n    *,\n    backend: Literal[\"graph\", \"vm\"] = \"graph\",\n    opt_level: int = 3,\n    pass_config: Mapping[str, Any] = MappingProxyType(\n        {\n            \"relay.backend.use_meta_schedule\": True,\n            \"relay.backend.tir_converter\": \"default\",\n        }\n    ),\n    executor: Optional[\"relay.backend.Executor\"] = None,\n):\n    \"\"\"Compile a relay program with a MetaSchedule database.\n\n    Parameters\n    ----------\n    database : Database\n        The database to use\n    mod : IRModule\n        The Relay program to be compiled\n    target : tvm.target.Target\n        The compilation target\n    params : Optional[Dict[str, tvm.runtime.NDArray]]\n        The associated parameters of the program\n    backend : str\n        The backend to use. Builtin backends:\n            - \"graph\"\n            - \"vm\"\n    opt_level : int\n        The optimization level of the compilation\n    pass_config : Mapping[str, Any]\n        The pass configuration\n    executor : Optional[relay.backend.Executor]\n        The executor to use in relay.build. It is not supported by RelayVM.\n\n    Returns\n    -------\n    lib : Union[Module, tvm.runtime.vm.Executable]\n        The built runtime module or vm Executable for the given relay workload.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    # pylint: enable=import-outside-toplevel\n    mod, target, params, pass_config, executor = _normalize_params(\n        mod, target, params, pass_config, executor\n    )\n    pass_config.setdefault(\"relay.backend.use_meta_schedule_dispatch\", True)\n    with Profiler.timeit(\"PostTuningCompilation\"):\n        with target, _autotvm_silencer(), database:\n            with transform.PassContext(\n                opt_level=opt_level,\n                config=pass_config,\n            ):\n                if backend == \"graph\":\n                    return relay.build(mod, target=target, params=params, executor=executor)\n                elif backend == \"vm\":\n                    return relay.vm.compile(mod, target=target, params=params)\n                else:\n                    raise ValueError(f\"Unknown backend: {backend}\")\n\n\ndef is_meta_schedule_enabled() -> bool:\n    \"\"\"Return whether the meta-schedule is enabled.\n\n    Returns\n    -------\n    enabled: bool\n        Whether the meta schedule is enabled\n    \"\"\"\n    return transform.PassContext.current().config.get(\n        \"relay.backend.use_meta_schedule\",\n        False,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.runner package.\nMeta Schedule runners that runs an artifact either locally or through the RPC interface\n\"\"\"\nfrom .config import EvaluatorConfig, RPCConfig\nfrom .local_runner import LocalRunner, LocalRunnerFuture\nfrom .rpc_runner import RPCRunner\nfrom .runner import (\n    PyRunner,\n    PyRunnerFuture,\n    Runner,\n    RunnerFuture,\n    RunnerInput,\n    RunnerResult,\n    create,\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Configurations for measurements in the runner\"\"\"\nimport os\nfrom threading import Thread\nfrom typing import NamedTuple, Optional, Union\n\nfrom tvm import rpc\n\n\nclass EvaluatorConfig(NamedTuple):\n    \"\"\"Config Details of Evaluator\n\n    Parameters\n    ----------\n    number: int\n        The number of times to run this function for taking average.\n        We call these runs as one `repeat` of measurement.\n    repeat: int\n        The number of times to repeat the measurement.\n        In total, the function will be invoked (1 + number x repeat) times,\n        where the first one is warm up and will be discarded.\n        The returned result contains `repeat` costs,\n        each of which is an average of `number` costs.\n    min_repeat_ms: int\n        Minimum repeat time in ms. if the execution latency is too short,\n        increase the number of runs to the given time (in ms) to reduce the measurement error.\n    enable_cpu_cache_flush: bool\n        Whether to flush the cache on CPU.\n\n    Note\n    ----\n    The total number of actual executions is 1+number*repeat because we would warm up 1 time before\n    actual run. The number of runs would be increased if run time is below min_repeat_ms.\n    \"\"\"\n\n    number: int = 3\n    repeat: int = 1\n    min_repeat_ms: int = 100\n    enable_cpu_cache_flush: bool = False\n\n    @staticmethod\n    def _normalized(config: Optional[\"EvaluatorConfig\"]) -> \"EvaluatorConfig\":\n        if config is None:\n            return EvaluatorConfig()\n        config = EvaluatorConfig(\n            number=config.number,\n            repeat=config.repeat,\n            min_repeat_ms=config.min_repeat_ms,\n            enable_cpu_cache_flush=config.enable_cpu_cache_flush,\n        )\n        return config\n\n\nclass RPCConfig(NamedTuple):\n    \"\"\"RPC configuration\n\n    Parameters\n    ----------\n    tracker_host: str\n        Host of the RPC Tracker\n    tracker_port: int\n        Port of the RPC Tracker\n    tracker_key: str\n        Key of the Tracker\n    session_timeout_sec: float\n        Timeout of the RPC session\n    session_priority: int\n        Priority of the RPC session\n    \"\"\"\n\n    tracker_host: Optional[str] = None\n    tracker_port: Union[None, int, str] = None\n    tracker_key: Optional[str] = None\n    session_priority: int = 1\n    session_timeout_sec: int = 10\n\n    def _sanity_check(self) -> None:\n        err_str = (\n            \"RPCConfig.{0} is not provided. Please provide it explicitly,\"\n            \"or set environment variable {1}\"\n        )\n        if self.tracker_host is None:\n            raise ValueError(err_str.format(\"tracker_host\", \"TVM_TRACKER_HOST\"))\n        if self.tracker_port is None:\n            raise ValueError(err_str.format(\"tracker_port\", \"TVM_TRACKER_PORT\"))\n        if self.tracker_key is None:\n            raise ValueError(err_str.format(\"tracker_key\", \"TVM_TRACKER_KEY\"))\n\n    @staticmethod\n    def _normalized(config: Optional[\"RPCConfig\"]) -> \"RPCConfig\":\n        if config is None:\n            config = RPCConfig()\n        config = RPCConfig(\n            tracker_host=config.tracker_host or os.environ.get(\"TVM_TRACKER_HOST\", None),\n            tracker_port=config.tracker_port or os.environ.get(\"TVM_TRACKER_PORT\", None),\n            tracker_key=config.tracker_key or os.environ.get(\"TVM_TRACKER_KEY\", None),\n            session_priority=config.session_priority,\n            session_timeout_sec=config.session_timeout_sec,\n        )\n        config._sanity_check()  # pylint: disable=protected-access\n        return config\n\n    def connect_tracker(self) -> rpc.TrackerSession:\n        \"\"\"Connect to the tracker\n\n        Returns\n        -------\n        tracker : TrackerSession\n            The connected tracker session\n        \"\"\"\n        tracker: Optional[rpc.TrackerSession] = None\n\n        def _connect():\n            nonlocal tracker\n            tracker = rpc.connect_tracker(self.tracker_host, self.tracker_port)\n\n        t = Thread(target=_connect)\n        t.start()\n        t.join(self.session_timeout_sec)\n        if t.is_alive() or tracker is None:\n            raise ValueError(\n                \"Unable to connect to the tracker using the following configuration:\\n\"\n                f\"    tracker host: {self.tracker_host}\\n\"\n                f\"    tracker port: {self.tracker_port}\\n\"\n                f\"    timeout (sec): {self.session_timeout_sec}\\n\"\n                \"Please check the tracker status via the following command:\\n\"\n                \"     python3 -m tvm.exec.query_rpc_tracker \"\n                f\"--host {self.tracker_host} --port {self.tracker_port}\"\n            )\n        return tracker\n\n    def connect_server(self) -> rpc.RPCSession:\n        \"\"\"Connect to the server\n\n        Returns\n        -------\n        session : RPCSession\n            The connected rpc session\n        \"\"\"\n        tracker = self.connect_tracker()\n        session: rpc.RPCSession = tracker.request(\n            key=self.tracker_key,\n            priority=self.session_priority,\n            session_timeout=self.session_timeout_sec,\n        )\n        return session\n\n    def count_num_servers(self, allow_missing=True) -> int:\n        \"\"\"Count the number of servers available in the tracker\n\n        Parameters\n        ----------\n        allow_missing : bool\n            Whether to allow no server to be found.\n\n        Returns\n        -------\n        num_servers : int\n            The number of servers\n        \"\"\"\n        tracker = self.connect_tracker()\n        tracker_summary = tracker.summary()\n        result: int = 0\n        for item in tracker_summary[\"server_info\"]:\n            _, item_key = item[\"key\"].split(\":\")\n            if item_key == self.tracker_key:\n                result += 1\n        if result == 0 and not allow_missing:\n            raise ValueError(\n                \"Unable to find servers with the specific key using the following configuration:\\n\"\n                f\"    tracker host: {self.tracker_host}\\n\"\n                f\"    tracker port: {self.tracker_port}\\n\"\n                f\"    tracker key: {self.tracker_key}\\n\"\n                f\"    timeout (sec): {self.session_timeout_sec}\\n\"\n                \"Please check the tracker status via the following command:\\n\"\n                \"     python3 -m tvm.exec.query_rpc_tracker \"\n                f\"--host {self.tracker_host} --port {self.tracker_port}\\n\"\n                f'and look for key: \"{self.tracker_key}\"'\n            )\n        return result\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/local_runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Local Runner\"\"\"\nfrom contextlib import contextmanager\nfrom typing import Callable, List, Optional, Union\nimport subprocess\n\nimport tvm\n\nfrom ...contrib.popen_pool import PopenPoolExecutor\nfrom ...runtime import Device, Module\nfrom ..logging import get_logger\nfrom ..profiler import Profiler\nfrom ..utils import derived_object, get_global_func_with_default_on_worker\nfrom .config import EvaluatorConfig\nfrom .runner import PyRunner, PyRunnerFuture, RunnerFuture, RunnerInput, RunnerResult\nfrom .utils import (\n    T_ARG_INFO_JSON_OBJ_LIST,\n    T_ARGUMENT_LIST,\n    alloc_argument_common,\n    run_evaluator_common,\n)\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\nT_ALLOC_ARGUMENT = Callable[  # pylint: disable=invalid-name\n    [\n        Device,  # The device on the remote\n        T_ARG_INFO_JSON_OBJ_LIST,  # The metadata information of the arguments to be allocated\n        int,  # The number of repeated allocations to be done\n    ],\n    List[T_ARGUMENT_LIST],  # A list of argument lists\n]\nT_RUN_EVALUATOR = Callable[  # pylint: disable=invalid-name\n    [\n        Module,  # The Module opened on the remote\n        Device,  # The device on the remote\n        EvaluatorConfig,  # The evaluator configuration\n        List[T_ARGUMENT_LIST],  # A list of argument lists\n    ],\n    List[float],  # A list of running time\n]\nT_CLEANUP = Callable[  # pylint: disable=invalid-name\n    [],\n    None,\n]\n\n\n@derived_object\nclass LocalRunnerFuture(PyRunnerFuture):\n    \"\"\"Local based runner future\n\n    Parameters\n    ----------\n    res: Optional[List[float]]\n        The optional result as a list of float.\n    error_message: Optional[str]\n        The optional error message.\n\n    Note\n    ----\n    Only one of the parameters should be None upon the creation\n    of LocalRunnerFuture object\n    \"\"\"\n\n    res: Optional[List[float]]\n    error_message: Optional[str]\n\n    def __init__(\n        self, res: Optional[List[float]] = None, error_message: Optional[str] = None\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        res: Optional[List[float]]\n            The result of this LocalRunnerFuture\n        error_message: Optional[str]\n            The stringfied error message of any exception during execution\n\n        \"\"\"\n        super().__init__()\n        self.res = res\n        self.error_message = error_message\n\n        # sanity check upon the creation of LocalRunnerFuture object\n        if (res is None and error_message is None) or (\n            res is not None and error_message is not None\n        ):\n            raise AttributeError(\n                \"Only one of the two parameters should be None upon the creation\"\n                \"of LocalRunnerFuture object.\"\n            )\n\n    def done(self) -> bool:\n        return True\n\n    def result(self) -> RunnerResult:\n        return RunnerResult(self.res, self.error_message)\n\n\ndef _worker_func(\n    _f_alloc_argument: Optional[str],\n    _f_run_evaluator: Optional[str],\n    _f_cleanup: Optional[str],\n    evaluator_config: EvaluatorConfig,\n    alloc_repeat: int,\n    artifact_path: str,\n    device_type: str,\n    args_info: T_ARG_INFO_JSON_OBJ_LIST,\n) -> List[float]:\n    f_alloc_argument: T_ALLOC_ARGUMENT = get_global_func_with_default_on_worker(\n        _f_alloc_argument, default_alloc_argument\n    )\n    f_run_evaluator: T_RUN_EVALUATOR = get_global_func_with_default_on_worker(\n        _f_run_evaluator, default_run_evaluator\n    )\n    f_cleanup: T_CLEANUP = get_global_func_with_default_on_worker(_f_cleanup, default_cleanup)\n\n    @contextmanager\n    def resource_handler():\n        try:\n            yield\n        finally:\n            # Final step. Always clean up\n            with Profiler.timeit(\"LocalRunner/cleanup\"):\n                f_cleanup()\n\n    with resource_handler():\n        # Step 1: create the local runtime module\n        with Profiler.timeit(\"LocalRunner/load_module\"):\n            rt_mod = tvm.runtime.load_module(artifact_path)\n        # Step 2: Allocate input arguments\n        with Profiler.timeit(\"LocalRunner/alloc_argument\"):\n            device = tvm.runtime.device(dev_type=device_type, dev_id=0)\n            repeated_args: List[T_ARGUMENT_LIST] = f_alloc_argument(\n                device,\n                args_info,\n                alloc_repeat,\n            )\n        # Step 3: Run time_evaluator\n        with Profiler.timeit(\"LocalRunner/run_evaluator\"):\n            costs: List[float] = f_run_evaluator(\n                rt_mod,\n                device,\n                evaluator_config,\n                repeated_args,\n            )\n    return costs\n\n\n@derived_object\nclass LocalRunner(PyRunner):\n    \"\"\"Local runner\n\n    Parameters\n    ----------\n    evaluator_config: EvaluatorConfig\n        The evaluator configuration.\n    cooldown_sec: float\n        The cooldown in seconds.\n    alloc_repeat: int\n        The number of times to repeat the allocation.\n    f_alloc_argument: Optional[str, Callable]\n        The function name to allocate the arguments or the function itself.\n    f_run_evaluator: Optional[str, Callable]\n        The function name to run the evaluator or the function itself.\n    f_cleanup: Optional[str, Callable]\n        The function name to cleanup the session or the function itself.\n    pool: PopenPoolExecutor\n        The popen pool executor.\n\n    Attributes\n    ----------\n    T_ALLOC_ARGUMENT : typing._GenericAlias\n        The signature of the function `f_alloc_argument`, which is:\n\n        .. code-block:: python\n\n        def default_alloc_argument(\n            device: Device,\n            args_info: T_ARG_INFO_JSON_OBJ_LIST,\n            alloc_repeat: int,\n        ) -> List[T_ARGUMENT_LIST]:\n            ...\n\n    T_RUN_EVALUATOR : typing._GenericAlias\n        The signature of the function `f_run_evaluator`, which is:\n\n        .. code-block:: python\n\n        def default_run_evaluator(\n            rt_mod: Module,\n            device: Device,\n            evaluator_config: EvaluatorConfig,\n            repeated_args: List[T_ARGUMENT_LIST],\n        ) -> List[float]:\n            ...\n\n    T_CLEANUP : typing._GenericAlias\n        The signature of the function `f_cleanup`, which is:\n\n        .. code-block:: python\n\n        def default_cleanup() -> None:\n            ...\n    \"\"\"\n\n    timeout_sec: float\n    evaluator_config: EvaluatorConfig\n    cooldown_sec: float\n    alloc_repeat: int\n\n    f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None]\n    f_run_evaluator: Union[T_RUN_EVALUATOR, str, None]\n    f_cleanup: Union[T_CLEANUP, str, None]\n\n    pool: PopenPoolExecutor\n\n    def __init__(\n        self,\n        timeout_sec: float = 30,\n        evaluator_config: Optional[EvaluatorConfig] = None,\n        cooldown_sec: float = 0.0,\n        alloc_repeat: int = 1,\n        f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None] = None,\n        f_run_evaluator: Union[T_RUN_EVALUATOR, str, None] = None,\n        f_cleanup: Union[T_CLEANUP, str, None] = None,\n        initializer: Optional[Callable[[], None]] = None,\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        timeout_sec: float\n            The timeout setting.\n        evaluator_config: EvaluatorConfig\n            The evaluator configuration.\n        cooldown_sec: float\n            The cooldown in seconds.\n        alloc_repeat: int\n            The number of times to random fill the allocation.\n        f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None]\n            The function name to allocate the arguments or the function itself.\n        f_run_evaluator: Union[T_RUN_EVALUATOR, str, None]\n            The function name to run the evaluator or the function itself.\n        f_cleanup: Union[T_CLEANUP, str, None]\n            The function name to cleanup the session or the function itself.\n        initializer: Optional[Callable[[], None]]\n            The initializer function.\n        \"\"\"\n        super().__init__()\n        self.timeout_sec = timeout_sec\n        self.evaluator_config = EvaluatorConfig._normalized(evaluator_config)\n        self.cooldown_sec = cooldown_sec\n        self.alloc_repeat = alloc_repeat\n        self.f_alloc_argument = f_alloc_argument\n        self.f_run_evaluator = f_run_evaluator\n        self.f_cleanup = f_cleanup\n\n        logger.info(\"LocalRunner: max_workers = 1\")\n        self.pool = PopenPoolExecutor(\n            max_workers=1,  # one local worker\n            timeout=timeout_sec,\n            initializer=initializer,\n            stderr=subprocess.DEVNULL,  # suppress the stderr output\n        )\n        self._sanity_check()\n\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        results: List[RunnerFuture] = []\n        for runner_input in runner_inputs:\n            future = self.pool.submit(\n                _worker_func,\n                self.f_alloc_argument,\n                self.f_run_evaluator,\n                self.f_cleanup,\n                self.evaluator_config,\n                self.alloc_repeat,\n                str(runner_input.artifact_path),\n                str(runner_input.device_type),\n                tuple(arg_info.as_json() for arg_info in runner_input.args_info),\n            )\n            try:\n                result: List[float] = future.result()\n                error_message: str = None\n            except TimeoutError:\n                result = None\n                error_message = f\"LocalRunner: Timeout, killed after {self.timeout_sec} seconds\\n\"\n            except Exception as exception:  # pylint: disable=broad-except\n                result = None\n                error_message = \"LocalRunner: An exception occurred\\n\" + str(exception)\n            local_future = LocalRunnerFuture(res=result, error_message=error_message)\n            results.append(local_future)  # type: ignore\n        return results\n\n    def _sanity_check(self) -> None:\n        def _check(\n            f_alloc_argument,\n            f_run_evaluator,\n            f_cleanup,\n        ) -> None:\n            get_global_func_with_default_on_worker(name=f_alloc_argument, default=None)\n            get_global_func_with_default_on_worker(name=f_run_evaluator, default=None)\n            get_global_func_with_default_on_worker(name=f_cleanup, default=None)\n\n        value = self.pool.submit(\n            _check,\n            self.f_alloc_argument,\n            self.f_run_evaluator,\n            self.f_cleanup,\n        )\n        value.result()\n\n\ndef default_alloc_argument(\n    device: Device,\n    args_info: T_ARG_INFO_JSON_OBJ_LIST,\n    alloc_repeat: int,\n) -> List[T_ARGUMENT_LIST]:\n    \"\"\"Default function to allocate the arguments\n\n    Parameters\n    ----------\n    device: Device\n        The device to allocate the arguments\n    args_info: T_ARG_INFO_JSON_OBJ_LIST\n        The arguments info\n    alloc_repeat: int\n        The number of times to repeat the allocation\n\n    Returns\n    -------\n    repeated_args: List[T_ARGUMENT_LIST]\n        The allocation args\n    \"\"\"\n    f_random_fill = get_global_func_with_default_on_worker(\n        name=\"tvm.contrib.random.random_fill_for_measure\", default=None\n    )\n    return alloc_argument_common(f_random_fill, device, args_info, alloc_repeat)\n\n\ndef default_run_evaluator(\n    rt_mod: Module,\n    device: Device,\n    evaluator_config: EvaluatorConfig,\n    repeated_args: List[T_ARGUMENT_LIST],\n) -> List[float]:\n    \"\"\"Default function to run the evaluator\n\n    Parameters\n    ----------\n    rt_mod: Module\n        The runtime module\n    device: Device\n        The device to run the evaluator\n    evaluator_config: EvaluatorConfig\n        The evaluator config\n    repeated_args: List[T_ARGUMENT_LIST]\n        The repeated arguments\n\n    Returns\n    -------\n    costs: List[float]\n        The evaluator results\n    \"\"\"\n    return run_evaluator_common(rt_mod, device, evaluator_config, repeated_args)\n\n\ndef default_cleanup() -> None:\n    \"\"\"Default function to clean up the session\"\"\"\n    pass  # pylint: disable=unnecessary-pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/rpc_runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC Runner\"\"\"\nimport concurrent.futures\nimport os.path as osp\nfrom contextlib import contextmanager\nfrom typing import Callable, List, Optional, Union\n\nfrom tvm.contrib.popen_pool import PopenPoolExecutor\nfrom tvm.rpc import RPCSession\nfrom tvm.runtime import Device, Module\n\nfrom ..logging import get_logger\nfrom ..profiler import Profiler\nfrom ..utils import (\n    cpu_count,\n    derived_object,\n    get_global_func_on_rpc_session,\n    get_global_func_with_default_on_worker,\n)\nfrom .config import EvaluatorConfig, RPCConfig\nfrom .runner import PyRunner, PyRunnerFuture, RunnerFuture, RunnerInput, RunnerResult\nfrom .utils import (\n    T_ARG_INFO_JSON_OBJ_LIST,\n    T_ARGUMENT_LIST,\n    alloc_argument_common,\n    run_evaluator_common,\n)\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\nT_CREATE_SESSION = Callable[  # pylint: disable=invalid-name\n    [RPCConfig],  # The RPC configuration\n    RPCSession,  # The RPC Session\n]\nT_UPLOAD_MODULE = Callable[  # pylint: disable=invalid-name\n    [\n        RPCSession,  # The RPC Session\n        str,  # local path to the artifact\n        str,  # remote path to the artifact\n    ],\n    Module,  # the Module opened on the remote\n]\nT_ALLOC_ARGUMENT = Callable[  # pylint: disable=invalid-name\n    [\n        RPCSession,  # The RPC Session\n        Device,  # The device on the remote\n        T_ARG_INFO_JSON_OBJ_LIST,  # The metadata information of the arguments to be allocated\n        int,  # The number of repeated allocations to be done\n    ],\n    List[T_ARGUMENT_LIST],  # A list of argument lists\n]\nT_RUN_EVALUATOR = Callable[  # pylint: disable=invalid-name\n    [\n        RPCSession,  # The RPC Session\n        Module,  # The Module opened on the remote\n        Device,  # The device on the remote\n        EvaluatorConfig,  # The evaluator configuration\n        List[T_ARGUMENT_LIST],  # A list of argument lists\n    ],\n    List[float],  # A list of running time\n]\nT_CLEANUP = Callable[  # pylint: disable=invalid-name\n    [\n        Optional[RPCSession],  # The RPC Session to be cleaned up\n        Optional[str],  # remote path to the artifact\n    ],\n    None,\n]\n\n\n@derived_object\nclass RPCRunnerFuture(PyRunnerFuture):\n    \"\"\"RPC based runner future\n\n    Parameters\n    ----------\n    future: concurrent.futures.Future\n        The concurrent function to check when the function is done and to return the result.\n    timeout_sec: float\n        The timeout in seconds.\n    \"\"\"\n\n    future: concurrent.futures.Future\n    timeout_sec: float\n\n    def __init__(self, future: concurrent.futures.Future, timeout_sec: float) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        future: concurrent.futures.Future\n            The concurrent function to check when the function is done and to return the result.\n        timeout_sec: float\n            The timeout in seconds.\n        \"\"\"\n        super().__init__()\n        self.future = future\n        self.timeout_sec = timeout_sec\n\n    def done(self) -> bool:\n        return self.future.done()\n\n    def result(self) -> RunnerResult:\n        try:\n            run_secs: List[float] = self.future.result()\n        except TimeoutError:\n            return RunnerResult(\n                None,\n                error_msg=f\"RPCRunner: Timeout, killed after {self.timeout_sec} seconds\",\n            )\n        except Exception as exception:  # pylint: disable=broad-except\n            return RunnerResult(\n                None,\n                error_msg=\"RPCRunner: An exception occurred\\n\" + str(exception),\n            )\n        return RunnerResult(run_secs, None)\n\n\n@derived_object\nclass RPCRunner(PyRunner):\n    \"\"\"RPC based runner\n\n    Parameters\n    ----------\n    rpc_config: RPCConfig\n        The rpc configuration.\n    evaluator_config: EvaluatorConfig\n        The evaluator configuration.\n    cooldown_sec: float\n        The cooldown in seconds. TODO(@junrushao1994,@zxybazh): This is not used yet.\n    alloc_repeat: int\n        The number of times to repeat the allocation.\n    f_create_session: Optional[str, Callable]\n        The function name to create the session or the function itself.\n    f_upload_module: Optional[str, Callable]\n        The function name to upload the module or the function itself.\n    f_alloc_argument: Optional[str, Callable]\n        The function name to allocate the arguments or the function itself.\n    f_run_evaluator: Optional[str, Callable]\n        The function name to run the evaluator or the function itself.\n    f_cleanup: Optional[str, Callable]\n        The function name to cleanup the session or the function itself.\n    pool: PopenPoolExecutor\n        The popen pool executor.\n\n    Attributes\n    ----------\n    T_CREATE_SESSION : typing._GenericAlias\n        The signature of the function `f_create_session`, which is:\n\n        .. code-block:: python\n\n        def default_create_session(rpc_config: RPCConfig) -> RPCSession:\n            ...\n\n    T_UPLOAD_MODULE : typing._GenericAlias\n        The signature of the function `f_upload_module`, which is:\n\n        .. code-block:: python\n\n        def default_upload_module(\n            session: RPCSession,\n            local_path: str,\n            remote_path: str,\n        ) -> Module:\n            ...\n\n    T_ALLOC_ARGUMENT : typing._GenericAlias\n        The signature of the function `f_alloc_argument`, which is:\n\n        .. code-block:: python\n\n        def default_alloc_argument(\n            session: RPCSession,\n            device: Device,\n            args_info: T_ARG_INFO_JSON_OBJ_LIST,\n            alloc_repeat: int,\n        ) -> List[T_ARGUMENT_LIST]:\n            ...\n\n    T_RUN_EVALUATOR : typing._GenericAlias\n        The signature of the function `f_run_evaluator`, which is:\n\n        .. code-block:: python\n\n        def default_run_evaluator(\n            session: RPCSession,\n            rt_mod: Module,\n            device: Device,\n            evaluator_config: EvaluatorConfig,\n            repeated_args: List[T_ARGUMENT_LIST],\n        ) -> List[float]:\n            ...\n\n    T_CLEANUP : typing._GenericAlias\n        The signature of the function `f_cleanup`, which is:\n\n        .. code-block:: python\n\n        def default_cleanup(\n            session: Optional[RPCSession],\n            remote_path: Optional[str],\n        ) -> None:\n            ...\n    \"\"\"\n\n    rpc_config: RPCConfig\n    evaluator_config: EvaluatorConfig\n    cooldown_sec: float\n    alloc_repeat: int\n\n    f_create_session: Union[T_CREATE_SESSION, str, None]\n    f_upload_module: Union[T_UPLOAD_MODULE, str, None]\n    f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None]\n    f_run_evaluator: Union[T_RUN_EVALUATOR, str, None]\n    f_cleanup: Union[T_CLEANUP, str, None]\n\n    pool: PopenPoolExecutor\n\n    def __init__(\n        self,\n        rpc_config: Optional[RPCConfig] = None,\n        evaluator_config: Optional[EvaluatorConfig] = None,\n        cooldown_sec: float = 0.0,\n        alloc_repeat: int = 1,\n        f_create_session: Union[T_CREATE_SESSION, str, None] = None,\n        f_upload_module: Union[T_UPLOAD_MODULE, str, None] = None,\n        f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None] = None,\n        f_run_evaluator: Union[T_RUN_EVALUATOR, str, None] = None,\n        f_cleanup: Union[T_CLEANUP, str, None] = None,\n        max_workers: Optional[int] = None,\n        initializer: Optional[Callable[[], None]] = None,\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        rpc_config: RPCConfig\n            The rpc configuration.\n        evaluator_config: EvaluatorConfig\n            The evaluator configuration.\n        cooldown_sec: float\n            The cooldown in seconds.\n        alloc_repeat: int\n            The number of times to random fill the allocation.\n        f_create_session: Union[T_CREATE_SESSION, str, None]\n            The function name to create the session or the function itself.\n        f_upload_module: Union[T_UPLOAD_MODULE, str, None]\n            The function name to upload the module or the function itself.\n        f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None]\n            The function name to allocate the arguments or the function itself.\n        f_run_evaluator: Union[T_RUN_EVALUATOR, str, None]\n            The function name to run the evaluator or the function itself.\n        f_cleanup: Union[T_CLEANUP, str, None]\n            The function name to cleanup the session or the function itself.\n        max_workers: Optional[int] = None\n            The maximum number of connections. Defaults to number of logical CPU cores.\n        initializer: Optional[Callable[[], None]]\n            The initializer function.\n        \"\"\"\n        super().__init__()\n        self.rpc_config = RPCConfig._normalized(rpc_config)\n        self.evaluator_config = EvaluatorConfig._normalized(evaluator_config)\n        self.cooldown_sec = cooldown_sec\n        self.alloc_repeat = alloc_repeat\n        self.f_create_session = f_create_session\n        self.f_upload_module = f_upload_module\n        self.f_alloc_argument = f_alloc_argument\n        self.f_run_evaluator = f_run_evaluator\n        self.f_cleanup = f_cleanup\n        if max_workers is None:\n            max_workers = cpu_count(logical=True)\n        logger.info(\"RPCRunner: max_workers = %d\", max_workers)\n        self.pool = PopenPoolExecutor(\n            max_workers=max_workers,\n            timeout=rpc_config.session_timeout_sec,\n            initializer=initializer,\n        )\n        self._sanity_check()\n\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        results: List[RunnerFuture] = []\n        for runner_input in runner_inputs:\n            future = RPCRunnerFuture(\n                future=self.pool.submit(\n                    _worker_func,\n                    self.f_create_session,\n                    self.f_upload_module,\n                    self.f_alloc_argument,\n                    self.f_run_evaluator,\n                    self.f_cleanup,\n                    self.rpc_config,\n                    self.evaluator_config,\n                    self.alloc_repeat,\n                    str(runner_input.artifact_path),\n                    str(runner_input.device_type),\n                    tuple(arg_info.as_json() for arg_info in runner_input.args_info),\n                ),\n                timeout_sec=self.rpc_config.session_timeout_sec,\n            )\n            results.append(future)  # type: ignore\n        return results\n\n    def _sanity_check(self) -> None:\n        def _check(\n            f_create_session,\n            f_upload_module,\n            f_alloc_argument,\n            f_run_evaluator,\n            f_cleanup,\n        ) -> None:\n            get_global_func_with_default_on_worker(name=f_create_session, default=None)\n            get_global_func_with_default_on_worker(name=f_upload_module, default=None)\n            get_global_func_with_default_on_worker(name=f_alloc_argument, default=None)\n            get_global_func_with_default_on_worker(name=f_run_evaluator, default=None)\n            get_global_func_with_default_on_worker(name=f_cleanup, default=None)\n\n        value = self.pool.submit(\n            _check,\n            self.f_create_session,\n            self.f_upload_module,\n            self.f_alloc_argument,\n            self.f_run_evaluator,\n            self.f_cleanup,\n        )\n        value.result()\n\n\ndef _worker_func(\n    _f_create_session: Union[T_CREATE_SESSION, str, None],\n    _f_upload_module: Union[T_UPLOAD_MODULE, str, None],\n    _f_alloc_argument: Union[T_ALLOC_ARGUMENT, str, None],\n    _f_run_evaluator: Union[T_RUN_EVALUATOR, str, None],\n    _f_cleanup: Union[T_CLEANUP, str, None],\n    rpc_config: RPCConfig,\n    evaluator_config: EvaluatorConfig,\n    alloc_repeat: int,\n    artifact_path: str,\n    device_type: str,\n    args_info: T_ARG_INFO_JSON_OBJ_LIST,\n) -> List[float]:\n    # Step 0. Get the registered functions\n    f_create_session: T_CREATE_SESSION = get_global_func_with_default_on_worker(\n        _f_create_session, default_create_session\n    )\n    f_upload_module: T_UPLOAD_MODULE = get_global_func_with_default_on_worker(\n        _f_upload_module, default_upload_module\n    )\n    f_alloc_argument: T_ALLOC_ARGUMENT = get_global_func_with_default_on_worker(\n        _f_alloc_argument, default_alloc_argument\n    )\n    f_run_evaluator: T_RUN_EVALUATOR = get_global_func_with_default_on_worker(\n        _f_run_evaluator, default_run_evaluator\n    )\n    f_cleanup: T_CLEANUP = get_global_func_with_default_on_worker(_f_cleanup, default_cleanup)\n    # Managed resources\n    session: Optional[RPCSession] = None\n    remote_path: Optional[str] = None\n\n    @contextmanager\n    def resource_handler():\n        try:\n            yield\n        finally:\n            # Final step. Always clean up\n            with Profiler.timeit(\"RPCRunner/cleanup\"):\n                f_cleanup(session, remote_path)\n\n    with resource_handler():\n        # Step 1. Create session\n        with Profiler.timeit(\"RPCRunner/create_session\"):\n            session = f_create_session(rpc_config)\n            device = session.device(dev_type=device_type, dev_id=0)\n        # Step 2. Upload the module\n        with Profiler.timeit(\"RPCRunner/upload_module\"):\n            _, remote_path = osp.split(artifact_path)\n            local_path: str = artifact_path\n            rt_mod: Module = f_upload_module(session, local_path, remote_path)\n        # Step 3: Allocate input arguments\n        with Profiler.timeit(\"RPCRunner/alloc_argument\"):\n            repeated_args: List[T_ARGUMENT_LIST] = f_alloc_argument(\n                session,\n                device,\n                args_info,\n                alloc_repeat,\n            )\n        # Step 4: Run time_evaluator\n        with Profiler.timeit(\"LocalRunner/run_evaluator\"):\n            costs: List[float] = f_run_evaluator(\n                session,\n                rt_mod,\n                device,\n                evaluator_config,\n                repeated_args,\n            )\n    return costs\n\n\ndef default_create_session(rpc_config: RPCConfig) -> RPCSession:\n    \"\"\"Default function to create the session\n\n    Parameters\n    ----------\n    rpc_config : RPCConfig\n        The configuration of the RPC session\n\n    Returns\n    -------\n    session : RPCSession\n        The created rpc session\n    \"\"\"\n    return rpc_config.connect_server()\n\n\ndef default_upload_module(\n    session: RPCSession,\n    local_path: str,\n    remote_path: str,\n) -> Module:\n    \"\"\"Default function to upload the module\n\n    Parameters\n    ----------\n    session: RPCSession\n        The session to upload the module\n    local_path: str\n        The local path of the module\n    remote_path: str\n        The remote path to place the module\n\n    Returns\n    -------\n    rt_mod : Module\n        The runtime module\n    \"\"\"\n    session.upload(local_path, remote_path)\n    rt_mod: Module = session.load_module(remote_path)\n    return rt_mod\n\n\ndef default_alloc_argument(\n    session: RPCSession,\n    device: Device,\n    args_info: T_ARG_INFO_JSON_OBJ_LIST,\n    alloc_repeat: int,\n) -> List[T_ARGUMENT_LIST]:\n    \"\"\"Default function to allocate the arguments\n\n    Parameters\n    ----------\n    session: RPCSession\n        The session to allocate the arguments\n    device: Device\n        The device to allocate the arguments\n    args_info: T_ARG_INFO_JSON_OBJ_LIST\n        The arguments info\n    alloc_repeat: int\n        The number of times to repeat the allocation\n\n    Returns\n    -------\n    repeated_args: List[Args]\n        The allocation args\n    \"\"\"\n    f_random_fill = get_global_func_on_rpc_session(\n        session,\n        \"tvm.contrib.random.random_fill_for_measure\",\n        \"Please make sure 'USE_RANDOM' is turned ON in the config.cmake on the RPC server.\",\n    )\n\n    return alloc_argument_common(f_random_fill, device, args_info, alloc_repeat)\n\n\ndef default_run_evaluator(\n    session: RPCSession,  # pylint: disable=unused-argument\n    rt_mod: Module,\n    device: Device,\n    evaluator_config: EvaluatorConfig,\n    repeated_args: List[T_ARGUMENT_LIST],\n) -> List[float]:\n    \"\"\"Default function to run the evaluator\n\n    Parameters\n    ----------\n    session: RPCSession\n        The session to run the evaluator\n    rt_mod: Module\n        The runtime module\n    device: Device\n        The device to run the evaluator\n    evaluator_config: EvaluatorConfig\n        The evaluator config\n    repeated_args: List[T_ARGUMENT_LIST]\n        The repeated arguments\n\n    Returns\n    -------\n    costs: List[float]\n        The evaluator results\n    \"\"\"\n    return run_evaluator_common(rt_mod, device, evaluator_config, repeated_args)\n\n\ndef default_cleanup(\n    session: Optional[RPCSession],\n    remote_path: Optional[str],\n) -> None:\n    \"\"\"Default function to clean up the session\n\n    Parameters\n    ----------\n    session: RPCSession\n        The session to clean up\n    remote_path: str\n        The remote path to clean up\n    \"\"\"\n    if session is not None and remote_path is not None:\n        session.remove(remote_path)\n        session.remove(remote_path + \".so\")\n        session.remove(\"\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Runners\"\"\"\nfrom typing import Callable, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\n\nfrom .. import _ffi_api\nfrom ..arg_info import ArgInfo\n\n\n@register_object(\"meta_schedule.RunnerInput\")\nclass RunnerInput(Object):\n    \"\"\"The runner's input\n\n    Parameters\n    ----------\n    artifact_path : str\n        The path to the built artifact.\n    device_type : str\n        The device type.\n    args_info : List[ArgInfo]\n        The argument information.\n    \"\"\"\n\n    artifact_path: str\n    device_type: str\n    args_info: List[ArgInfo]\n\n    def __init__(\n        self,\n        artifact_path: str,\n        device_type: str,\n        args_info: List[ArgInfo],\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        artifact_path : str\n            The path to the built artifact.\n        device_type : str\n            The device type.\n        args_info : List[ArgInfo]\n            The argument information.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.RunnerInput,  # type: ignore # pylint: disable=no-member\n            artifact_path,\n            device_type,\n            args_info,\n        )\n\n\n@register_object(\"meta_schedule.RunnerResult\")\nclass RunnerResult(Object):\n    \"\"\"The runner's result\n\n    Parameters\n    ----------\n    run_secs : Optional[List[float]]\n        The run time in seconds.\n    error_msg : Optional[str]\n        The error message, if any.\n    \"\"\"\n\n    run_secs: Optional[List[float]]\n    error_msg: Optional[str]\n\n    def __init__(\n        self,\n        run_secs: Optional[List[float]],\n        error_msg: Optional[str],\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        run_secs : Optional[List[float]]\n            The run time in seconds.\n        error_msg : Optional[str]\n            The error message, if any.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.RunnerResult,  # type: ignore # pylint: disable=no-member\n            run_secs,\n            error_msg,\n        )\n\n\n@register_object(\"meta_schedule.RunnerFuture\")\nclass RunnerFuture(Object):\n    \"\"\"\n    A class to fetch asynchronous runner's output.\n    This is NOT the user facing class for function overloading inheritance.\n    Can be used for general return type of runner.\n\n    See also: PyRunnerFuture\n    \"\"\"\n\n    def __init__(self, f_done: Callable, f_result: Callable = None) -> None:\n        \"\"\"Constructor\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.RunnerFuture,  # type: ignore # pylint: disable=no-member\n            f_done,\n            f_result,\n        )\n\n    def done(self) -> bool:\n        \"\"\"Check whether the runner has finished.\"\"\"\n        return _ffi_api.RunnerFutureDone(self)  # type: ignore # pylint: disable=no-member\n\n    def result(self) -> RunnerResult:\n        \"\"\"Fetch the runner's output if it is ready.\"\"\"\n        return _ffi_api.RunnerFutureResult(self)  # type: ignore # pylint: disable=no-member\n\n\nclass PyRunnerFuture:\n    \"\"\"\n    A class to fetch asynchronous runner's output with customizable function on the python side.\n    This is the user facing class for function overloading inheritance.\n    Can NOT be used for general return type of runner.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    Example:\n        @derived_object\n        def LocalRunnerFuture(PyRunnerFuture):\n            ...\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": RunnerFuture,\n        \"methods\": [\"done\", \"result\"],\n    }\n\n    def done(self) -> bool:\n        \"\"\"Check whether the runner has finished.\"\"\"\n        raise NotImplementedError\n\n    def result(self) -> RunnerResult:\n        \"\"\"Fetch the runner's output if it is ready.\"\"\"\n        raise NotImplementedError\n\n\n@register_object(\"meta_schedule.Runner\")\nclass Runner(Object):\n    \"\"\"The abstract runner interface\"\"\"\n\n    RunnerType = Union[\"Runner\", Literal[\"local\", \"rpc\"]]\n\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        \"\"\"Run the built artifact and get runner futures.\n\n        Parameters\n        ----------\n        runner_inputs : List[RunnerInput]\n            The inputs to the runner.\n\n        Returns\n        -------\n        runner_futures: List[RunnerFuture]\n            The runner futures.\n        \"\"\"\n        return _ffi_api.RunnerRun(self, runner_inputs)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Literal[\"local\", \"rpc\"] = \"local\",\n        *args,\n        **kwargs,\n    ) -> \"Runner\":\n        \"\"\"Create a Runner.\"\"\"\n        from . import LocalRunner, RPCRunner  # pylint: disable=import-outside-toplevel\n\n        if kind == \"local\":\n            return LocalRunner(*args, **kwargs)  # type: ignore\n        elif kind == \"rpc\":\n            return RPCRunner(*args, **kwargs)  # type: ignore\n        raise ValueError(f\"Unknown Runner: {kind}\")\n\n\ncreate = Runner.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyRunner\")\nclass _PyRunner(Runner):\n    \"\"\"\n    A TVM object runner to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyRunner\n    \"\"\"\n\n    def __init__(self, f_run: Callable = None) -> None:\n        \"\"\"Constructor\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.RunnerPyRunner,  # type: ignore # pylint: disable=no-member\n            f_run,\n        )\n\n\nclass PyRunner:\n    \"\"\"\n    An abstract runner with customized run method on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyRunner,\n        \"methods\": [\"run\"],\n    }\n\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        \"\"\"Run the built artifact and get runner futures.\n\n        Parameters\n        ----------\n        runner_inputs : List[RunnerInput]\n            The inputs to the runner.\n\n        Returns\n        -------\n        runner_futures: List[RunnerFuture]\n            The runner futures.\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/runner/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Runner utility functions\"\"\"\nimport itertools\nfrom typing import Any, Callable, Dict, List\n\nfrom ...runtime import Device, Module, ndarray\nfrom .config import EvaluatorConfig\n\nT_ARG_INFO_JSON_OBJ = List[Any]  # pylint: disable=invalid-name\nT_ARG_INFO_JSON_OBJ_LIST = List[T_ARG_INFO_JSON_OBJ]  # pylint: disable=invalid-name\nT_ARGUMENT = Any  # pylint: disable=invalid-name\nT_ARGUMENT_LIST = List[T_ARGUMENT]  # pylint: disable=invalid-name\n\n\ndef alloc_argument_common(\n    f_random_fill: Callable,\n    device: Device,\n    args_info: T_ARG_INFO_JSON_OBJ_LIST,\n    alloc_repeat: int,\n) -> List[T_ARGUMENT_LIST]:\n    \"\"\"Common function to allocate the arguments\n\n    Parameters\n    ----------\n    f_random_fill: Callable\n        The callable function for random fill\n    device: Device\n        The device to allocate the arguments\n    args_info: T_ARG_INFO_JSON_OBJ_LIST\n        The arguments info\n    alloc_repeat: int\n        The number of times to repeat the allocation\n\n    Returns\n    -------\n    repeated_args: List[T_ARGUMENT_LIST]\n        The allocation args\n    \"\"\"\n\n    def alloc_tensor(_, dtype, shape) -> ndarray.NDArray:\n        arg = ndarray.empty(shape=shape, dtype=dtype, device=device)\n        f_random_fill(arg)\n        return arg\n\n    def alloc_fail(*arg_info) -> None:\n        raise NotImplementedError(arg_info)\n\n    dispatcher: Dict[Any, Callable] = {\n        \"TENSOR\": alloc_tensor,\n        None: alloc_fail,\n    }\n\n    repeated_args: List[T_ARGUMENT_LIST] = []\n    for _ in range(alloc_repeat):\n        args: T_ARGUMENT_LIST = []\n        arg_info: T_ARG_INFO_JSON_OBJ\n        for arg_info in args_info:\n            arg_type = arg_info[0]\n            arg: Any = dispatcher.get(arg_type, None)(*arg_info)\n            args.append(arg)\n        repeated_args.append(args)\n    return repeated_args\n\n\ndef run_evaluator_common(\n    rt_mod: Module,\n    device: Device,\n    evaluator_config: EvaluatorConfig,\n    repeated_args: List[T_ARGUMENT_LIST],\n) -> List[float]:\n    \"\"\"Common function to run the evaluator\n\n    Parameters\n    ----------\n    rt_mod: Module\n        The runtime module\n    device: Device\n        The device to run the evaluator\n    evaluator_config: EvaluatorConfig\n        The evaluator config\n    repeated_args: List[T_ARGUMENT_LIST]\n        The repeated arguments\n\n    Returns\n    -------\n    costs: List[float]\n        The evaluator results\n    \"\"\"\n    evaluator = rt_mod.time_evaluator(\n        func_name=rt_mod.entry_name,\n        dev=device,\n        number=evaluator_config.number,\n        repeat=evaluator_config.repeat,\n        min_repeat_ms=evaluator_config.min_repeat_ms,\n        f_preproc=\"cache_flush_cpu_non_first_arg\"\n        if evaluator_config.enable_cpu_cache_flush\n        else \"\",\n    )\n    repeated_costs: List[List[float]] = []\n    for args in repeated_args:\n        device.sync()\n        profile_result = evaluator(*args)\n        repeated_costs.append(profile_result.results)\n    costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)]\n    return costs\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Per-block schedule rules in MetaSchedule\"\"\"\nfrom . import cpu, cuda, generic, x86\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule/cpu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Per-block schedule rules in MetaSchedule for target key 'cpu'\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule/cuda/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Per-block schedule rules in MetaSchedule for target key 'cuda'\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule/generic/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Per-block schedule rules in MetaSchedule for generic cases\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule/x86/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Per-block schedule rules in MetaSchedule for target key 'x86'\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.schedule_rule package.\nMeta Schedule schedule rules are used for modification of\nblocks in a schedule. See also PostOrderApply.\n\"\"\"\nfrom .add_rfactor import AddRFactor\nfrom .apply_custom_rule import ApplyCustomRule\nfrom .auto_bind import AutoBind\nfrom .auto_inline import AutoInline, InlineConstantScalars\nfrom .cross_thread_reduction import CrossThreadReduction\nfrom .multi_level_tiling import (\n    MultiLevelTiling,\n    MultiLevelTilingTensorCore,\n    MultiLevelTilingWideVector,\n    MultiLevelTilingWithIntrin,\n    ReuseType,\n)\nfrom .parallel_vectorize_unroll import ParallelizeVectorizeUnroll\nfrom .random_compute_location import RandomComputeLocation\nfrom .schedule_rule import PyScheduleRule, ScheduleRule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/add_rfactor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Add-rfactor Rule that add-rfactor to some blocks if needed\"\"\"\nfrom typing import Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.AddRFactor\")\nclass AddRFactor(ScheduleRule):\n    \"\"\"Rules for add-rfactor to some blocks if needed.\n\n    Parameters\n    ----------\n    max_jobs_per_core: int\n        The maximum number of jobs to be launched per CPU core. It sets the uplimit of CPU\n        parallelism, i.e. `num_cores * max_jobs_per_core`.\n        Use -1 to disable parallelism.\n    max_innermost_factor: Optional[int] = None\n        The maximum size of the innermost factor. None means no limit.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_jobs_per_core: int = 16,\n        max_innermost_factor: Optional[int] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleAddRFactor,  # type: ignore # pylint: disable=no-member\n            max_jobs_per_core,\n            max_innermost_factor,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/apply_custom_rule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Create a rule that applies customized rules registered using block attribute `schedule_rule`.\nThe rule will be dispatched according to target keys.\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.ApplyCustomRule\")\nclass ApplyCustomRule(ScheduleRule):\n    \"\"\"A rule that applies customized rules registered using block attribute `schedule_rule`.\n    The rule will be dispatched according to target keys.\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleApplyCustomRule,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/auto_bind.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Auto-bind Rule that binds blocks to threads if needed\"\"\"\nfrom typing import List, Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.AutoBind\")\nclass AutoBind(ScheduleRule):\n    \"\"\"Auto bind loops around the block to BlockIdx and ThreadIdx\n\n    Parameters\n    ----------\n    max_threadblocks: int\n        The maximum number of threadblock on GPU.\n    thread_extents: Optional[List[int]]\n        Candidates of thread axis extent.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_threadblocks: int = 256,\n        thread_extents: Optional[List[int]] = None,\n    ) -> None:\n        if thread_extents is None:\n            thread_extents = [32, 64, 128, 256, 512, 1024]\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleAutoBind,  # type: ignore # pylint: disable=no-member\n            max_threadblocks,\n            thread_extents,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/auto_inline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Auto-Inline. Rule that inlines spatial blocks if it satisfies some conditions\"\"\"\nfrom typing import List, Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.AutoInline\")\nclass AutoInline(ScheduleRule):\n    \"\"\"Rule that inlines spatial blocks if it satisfies some conditions\n\n    Parameters\n    ----------\n    into_producer : bool\n        If allows to inline a block into its producer\n    into_consumer : bool\n        If allows to inline a block into its consumer\n    inline_const_tensor : bool\n        Always inline constant tensors\n    disallow_if_then_else : bool\n        Always disallow if-then-else-like constructs\n    require_injective : bool\n        Always require the read-to-write mapping to be ordered\n    require_ordered : bool\n        Always require the read-to-write mapping to be injective\n    disallow_op : Optional[List[str]]\n        The operators that are disallowed in auto inline\n    \"\"\"\n\n    def __init__(\n        self,\n        into_producer: bool,\n        into_consumer: bool,\n        inline_const_tensor: bool,\n        disallow_if_then_else: bool,\n        require_injective: bool,\n        require_ordered: bool,\n        disallow_op: Optional[List[str]] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleAutoInline,  # type: ignore # pylint: disable=no-member\n            into_producer,\n            into_consumer,\n            inline_const_tensor,\n            disallow_if_then_else,\n            require_injective,\n            require_ordered,\n            disallow_op,\n        )\n\n\n@register_object(\"meta_schedule.InlineConstantScalars\")\nclass InlineConstantScalars(ScheduleRule):\n    \"\"\"Inline blocks that produce a constant scalar.\n\n    Such blocks get in the way of ReverseComputeInline during AutoInline, since they are also\n    counted as a producer block unless they are inlined first. So it is recommended to run\n    InlineConstantScalars before AutoInline.\n    \"\"\"\n\n    def __init__(\n        self,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleInlineConstantScalars,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/cross_thread_reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Rules which apply cross-thread reduction to some reduction blocks correspondingly when needed\"\"\"\nfrom typing import List\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.CrossThreadReduction\")\nclass CrossThreadReduction(ScheduleRule):\n    \"\"\"A schedule rule which applies cross-thread reduction to some reduction blocks\n    correspondingly when needed\n\n    Parameters\n    ----------\n    thread_extents: List[int]\n        Candidates of thread axis extent (values are required to be positive).\n    \"\"\"\n\n    def __init__(self, thread_extents: List[int]) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleCrossThreadReduction,  # type: ignore # pylint: disable=no-member\n            thread_extents,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/multi_level_tiling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Multi-level tiling with reuse.\"\"\"\nfrom typing import Any, Dict, List, Mapping, NamedTuple, Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\nclass ReuseType(NamedTuple):\n    \"\"\"Reuse type.\"\"\"\n\n    req: str\n    levels: List[int]\n    scope: str\n\n    def as_dict(self) -> Dict[str, Any]:\n        \"\"\"Return the dict representation of the reuse type.\"\"\"\n        return {\n            \"req\": self.req,\n            \"levels\": self.levels,\n            \"scope\": self.scope,\n        }\n\n\n@register_object(\"meta_schedule.MultiLevelTiling\")\nclass MultiLevelTiling(ScheduleRule):\n    \"\"\"Multi-level tiling with reuse.\n\n    Parameters\n    ----------\n    structure : str\n        The tiling structure. Recommended:\n        - 'SSRSRS' on CPU\n        - 'SSSRRSRS' on GPU\n    tile_bind : Optional[List[str]]\n        For each level of tiles, which thread axis it is bound to. Recommended:\n        - None on CPU\n        - [blockIdx.x, vthread.x, threadIdx.x] on GPU\n    max_innermost_factor : Optional[int]\n        The maximum size of the innermost factor. None means no limit\n    vector_load_lens : Optional[List[int]]\n        The length of vector lane in vectorized cooperative fetching.\n        None means disable vectorization\n    reuse_read : Optional[ReuseType]\n        Data reuse configuration for reading. None means no reuse.\n    reuse_write : Optional[ReuseType]\n        Data reuse configuration for writing. None means no reuse.\n    \"\"\"\n\n    def __init__(\n        self,\n        structure: str,\n        tile_binds: Optional[List[str]] = None,\n        max_innermost_factor: Optional[int] = None,\n        vector_load_lens: Optional[List[int]] = None,\n        reuse_read: Optional[ReuseType] = None,\n        reuse_write: Optional[ReuseType] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleMultiLevelTiling,  # type: ignore # pylint: disable=no-member\n            structure,\n            tile_binds,\n            max_innermost_factor,\n            vector_load_lens,\n            reuse_read.as_dict() if reuse_read is not None else None,\n            reuse_write.as_dict() if reuse_write is not None else None,\n        )\n\n\n@register_object(\"meta_schedule.MultiLevelTilingWithIntrin\")\nclass MultiLevelTilingWithIntrin(ScheduleRule):\n    \"\"\"Extension of MultiLevelTiling for auto-tensorizing with a single intrinsic.\n\n    Parameters\n    ----------\n    intrin_name : str\n        The name of a tensor intrinsic, must be registerd via TensorIntrin.register(...) beforehand\n    structure : str\n        The tiling structure. Recommended:\n        - 'SSRSRS' on CPU\n        - 'SSSRRSRS' on GPU\n    tile_bind : Optional[List[str]]\n        For each level of tiles, which thread axis it is bound to. Recommended:\n        - None on CPU\n        - [blockIdx.x, vthread.x, threadIdx.x] on GPU\n    max_innermost_factor : Optional[int]\n        The maximum size of the innermost factor. None means no limit\n    vector_load_lens : Optional[List[int]]\n        The length of vector lane in vectorized cooperative fetching.\n        None means disable vectorization\n    reuse_read : Optional[ReuseType]\n        Data reuse configuration for reading. None means no reuse.\n    reuse_write : Optional[ReuseType]\n        Data reuse configuration for writing. None means no reuse.\n    \"\"\"\n\n    def __init__(\n        self,\n        intrin_name: str,\n        structure: str,\n        tile_binds: Optional[List[str]] = None,\n        max_innermost_factor: Optional[int] = None,\n        vector_load_lens: Optional[List[int]] = None,\n        reuse_read: Optional[ReuseType] = None,\n        reuse_write: Optional[ReuseType] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleMultiLevelTilingWithIntrin,  # type: ignore # pylint: disable=no-member\n            intrin_name,\n            structure,\n            tile_binds,\n            max_innermost_factor,\n            vector_load_lens,\n            reuse_read.as_dict() if reuse_read is not None else None,\n            reuse_write.as_dict() if reuse_write is not None else None,\n        )\n\n\n@register_object(\"meta_schedule.MultiLevelTilingTensorCore\")\nclass MultiLevelTilingTensorCore(ScheduleRule):\n    \"\"\"Extension of MultiLevelTiling for auto-tensorizing with multiple groups of candidate tensor\n    core intrinsics.\n\n    Parameters\n    ----------\n    intrin_groups : List[Mapping[str, str]]\n        A list of groups of tensor core intrinsics. The map should contains key \"init\", \"load_a\",\n        \"load_b\", \"compute\", \"store\", which represent the tensor intrin for initialization,\n        loading operand A, loading operand B, tensor core computation, storing the result.\n        The value of the map should be names of tensor intrinsics, must be registerd via\n        TensorIntrin.register(...) beforehand\n    structure : str\n        The tiling structure. Recommended:\n        - 'SSSRRSRS' on GPU\n    tile_bind : Optional[List[str]]\n        For each level of tiles, which thread axis it is bound to. Recommended:\n        - [blockIdx.y, vthread.x, threadIdx.y] on GPU\n    max_innermost_factor : Optional[int]\n        The maximum size of the innermost factor. None means no limit\n    vector_load_lens : Optional[List[int]]\n        The length of vector lane in vectorized cooperative fetching.\n        None means disable vectorization\n    reuse_read : Optional[ReuseType]\n        Data reuse configuration for reading. None means no reuse.\n    reuse_write : Optional[ReuseType]\n        Data reuse configuration for writing. None means no reuse.\n    use_software_pipeline : bool\n        Whether to use the software pipeline.\n    \"\"\"\n\n    def __init__(\n        self,\n        intrin_groups: List[Mapping[str, str]],\n        structure: str,\n        tile_binds: Optional[List[str]] = None,\n        max_innermost_factor: Optional[int] = None,\n        vector_load_lens: Optional[List[int]] = None,\n        reuse_read: Optional[ReuseType] = None,\n        reuse_write: Optional[ReuseType] = None,\n        use_software_pipeline: bool = False,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleMultiLevelTilingTensorCore,  # type: ignore # pylint: disable=no-member\n            intrin_groups,\n            structure,\n            tile_binds,\n            max_innermost_factor,\n            vector_load_lens,\n            reuse_read.as_dict() if reuse_read is not None else None,\n            reuse_write.as_dict() if reuse_write is not None else None,\n            use_software_pipeline,\n        )\n\n\n@register_object(\"meta_schedule.MultiLevelTilingWideVector\")\nclass MultiLevelTilingWideVector(ScheduleRule):\n    \"\"\"Extension of MultiLevelTiling for backends with wide vectors. The loop over the innermost\n    spatial axis of the output buffer is always vectorized with the maximum vector length.\n\n    Parameters\n    ----------\n    structure : str\n        The tiling structure. 'SSRSRS' is recommended.\n    vector_length_in_bits: int\n        The length of a vector register in bits.\n    max_innermost_factor : Optional[int]\n        The maximum size of the innermost factor. None means no limit\n    reuse_read : Optional[ReuseType]\n        Data reuse configuration for reading. None means no reuse.\n    reuse_write : Optional[ReuseType]\n        Data reuse configuration for writing. None means no reuse.\n    \"\"\"\n\n    def __init__(\n        self,\n        structure: str,\n        vector_length_in_bits: int,\n        max_innermost_factor: Optional[int] = None,\n        reuse_read: Optional[ReuseType] = None,\n        reuse_write: Optional[ReuseType] = None,\n    ) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleMultiLevelTilingWideVector,  # type: ignore # pylint: disable=no-member\n            structure,\n            vector_length_in_bits,\n            max_innermost_factor,\n            reuse_read.as_dict() if reuse_read is not None else None,\n            reuse_write.as_dict() if reuse_write is not None else None,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/parallel_vectorize_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Rule that mark parallelize, vectorize and unroll to the root block. The mark will be applied to\neach block in a follow-up post processor\"\"\"\nfrom typing import List, Optional\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.ParallelizeVectorizeUnroll\")\nclass ParallelizeVectorizeUnroll(ScheduleRule):\n    \"\"\"Rule that mark parallelize, vectorize and unroll to the root block. The mark will be applied\n    to each block in a follow-up post processor\n\n    Parameters\n    ----------\n    max_jobs_per_core: int\n        The maximum number of jobs to be launched per CPU core. It sets the upper limit of CPU\n        parallelism, i.e. `num_cores * max_jobs_per_core`.\n        Use -1 to disable parallelism.\n    max_vectorize_extent: int\n        The maximum extent to be vectorized. It sets the upper limit of the hardware target\n        vectorization.\n        Use -1 to disable vectorization.\n    unroll_max_steps: Optional[List[int]]\n        The options of the maximum number of unroll steps to be done.\n        Use None to disable unroll\n    unroll_explicit: bool\n        Whether to explicitly unroll the loop, or just add an \"unroll\" pragma\n    \"\"\"\n\n    def __init__(\n        self,\n        max_jobs_per_core: int = 16,\n        max_vectorize_extent: int = 16,\n        unroll_max_steps: Optional[List[int]] = None,\n        unroll_explicit: bool = True,\n    ) -> None:\n        if unroll_max_steps is None:\n            unroll_max_steps = []\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleParallelizeVectorizeUnroll,  # type: ignore # pylint: disable=no-member\n            max_jobs_per_core,\n            max_vectorize_extent,\n            unroll_max_steps,\n            unroll_explicit,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/random_compute_location.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Rule that randomly select a compute-at location for a free block\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .schedule_rule import ScheduleRule\n\n\n@register_object(\"meta_schedule.RandomComputeLocation\")\nclass RandomComputeLocation(ScheduleRule):\n    \"\"\"A rule that randomly select a compute-at location for a free block\"\"\"\n\n    def __init__(self) -> None:\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRuleRandomComputeLocation,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/schedule_rule/schedule_rule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nMeta Schedule schedule rules are used for modification of\nblocks in a schedule. See also PostOrderApply.\n\"\"\"\nfrom typing import TYPE_CHECKING, Callable, List\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.tir.schedule import BlockRV, Schedule\n\nfrom .. import _ffi_api\nfrom ..utils import _get_default_str\n\nif TYPE_CHECKING:\n    from ..tune_context import TuneContext\n\n\n@register_object(\"meta_schedule.ScheduleRule\")\nclass ScheduleRule(Object):\n    \"\"\"Rules to modify a block in a schedule.\"\"\"\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the schedule rule with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the schedule rule.\n        \"\"\"\n        _ffi_api.ScheduleRuleInitializeWithTuneContext(  # type: ignore # pylint: disable=no-member\n            self, context\n        )\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        \"\"\"Apply a schedule rule to the specific block in the given schedule.\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be modified.\n        block : BlockRV\n            The specific block to apply the schedule rule.\n\n        Returns\n        -------\n        design_spaces : List[Schedule]\n            The list of schedules generated by applying the schedule rule.\n        \"\"\"\n        return _ffi_api.ScheduleRuleApply(  #  type: ignore # pylint: disable=no-member\n            self, sch, block\n        )\n\n    def clone(self) -> \"ScheduleRule\":\n        \"\"\"Deep clone the schedule rule.\n\n        Returns\n        -------\n        cloned_rule : ScheduleRule\n            The cloned schedule rule.\n        \"\"\"\n        return _ffi_api.ScheduleRuleClone(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(kind: Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"]) -> List[\"ScheduleRule\"]:\n        \"\"\"Create a list of schedule rules for the given kind.\n\n        Parameters\n        ----------\n        kind : Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"]\n            The kind of the schedule rules.\n\n        Returns\n        -------\n        rules : List[ScheduleRule]\n            The list of schedule rules.\n        \"\"\"\n        funcs = {\n            # pylint: disable=no-member\n            \"llvm\": _ffi_api.ScheduleRuleDefaultLLVM,  # type: ignore\n            \"cuda\": _ffi_api.ScheduleRuleDefaultCUDA,  # type: ignore\n            \"cuda-tensorcore\": _ffi_api.ScheduleRuleDefaultCUDATensorCore,  # type: ignore\n            \"hexagon\": _ffi_api.ScheduleRuleDefaultHexagon,  # type: ignore\n            # pylint: enable=no-member\n        }\n        for k, v in funcs.items():\n            if k == kind:\n                return v()\n        raise ValueError(f\"Unsupported kind {kind} for schedule rule creation.\")\n\n\ncreate = ScheduleRule.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyScheduleRule\")\nclass _PyScheduleRule(ScheduleRule):\n    \"\"\"\n    A TVM object schedule rule to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyScheduleRule\n    \"\"\"\n\n    def __init__(\n        self,\n        f_initialize_with_tune_context: Callable = None,\n        f_apply: Callable = None,\n        f_clone: Callable = None,\n        f_as_string: Callable = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleRulePyScheduleRule,  # type: ignore # pylint: disable=no-member\n            f_initialize_with_tune_context,\n            f_apply,\n            f_clone,\n            f_as_string,\n        )\n\n\nclass PyScheduleRule:\n    \"\"\"\n    An abstract schedule rule with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyScheduleRule,\n        \"methods\": [\"_initialize_with_tune_context\", \"apply\", \"clone\", \"__str__\"],\n    }\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the schedule rule with a tune context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the schedule rule.\n        \"\"\"\n        raise NotImplementedError\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        \"\"\"Apply a schedule rule to the specific block in the given schedule.\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be modified.\n        block : BlockRV\n            The specific block to apply the schedule rule.\n\n        Returns\n        -------\n        design_spaces : List[Schedule]\n            The list of schedules generated by applying the schedule rule.\n        \"\"\"\n        raise NotImplementedError\n\n    def clone(self) -> ScheduleRule:\n        \"\"\"Deep clone the schedule rule.\n\n        Returns\n        -------\n        cloned_rule : ScheduleRule\n            The cloned schedule rule.\n        \"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        \"\"\"Get the schedule rule as string with name.\n\n        Return\n        ------\n        result : str\n            Get the schedule rule as string with name.\n        \"\"\"\n        return _get_default_str(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/search_strategy/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.search_strategy package.\nMeta Schedule search strategy utilizes the design spaces given\nto generate measure candidates.\n\"\"\"\n\nfrom .evolutionary_search import EvolutionarySearch\nfrom .replay_func import ReplayFunc\nfrom .replay_trace import ReplayTrace\nfrom .search_strategy import MeasureCandidate, PySearchStrategy, SearchStrategy, create\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/search_strategy/evolutionary_search.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Evolutionary Search Strategy\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .search_strategy import SearchStrategy\n\n\n@register_object(\"meta_schedule.EvolutionarySearch\")\nclass EvolutionarySearch(SearchStrategy):\n    \"\"\"\n    Replay Trace Search Strategy is a search strategy that always replays the trace by removing its\n    decisions so that the decisions would be randomly re-generated.\n\n    Parameters\n    ----------\n    population_size : int\n        The initial population of traces from measured samples and randomly generated samples.\n    init_measured_ratio : int\n        The ratio of measured samples in the initial population.\n    init_min_unmeasured : int\n        The minimal size of unmeasured population in the initial sampling.\n    max_fail_count : int\n        The maximum number of failure during initial sampling.\n    genetic_num_iters : int\n        The number of iterations for genetic algorithm.\n    genetic_mutate_prob : float\n        The probability of mutation.\n    genetic_max_fail_count : int\n        The maximum number to retry mutation.\n    eps_greedy : float\n        The ratio of greedy selected samples in the final picks.\n    \"\"\"\n\n    population_size: int\n    init_measured_ratio: int\n    init_min_unmeasured: int\n    genetic_num_iters: int\n    genetic_mutate_prob: float\n    genetic_max_fail_count: int\n    eps_greedy: float\n\n    def __init__(\n        self,\n        *,\n        population_size: int = 512,\n        init_measured_ratio: float = 0.2,\n        init_min_unmeasured: int = 50,\n        max_fail_count: int = 5,\n        genetic_num_iters: int = 4,\n        genetic_mutate_prob: float = 0.85,\n        genetic_max_fail_count: int = 10,\n        eps_greedy: float = 0.05,\n    ) -> None:\n        \"\"\"Constructor\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchStrategyEvolutionarySearch,  # type: ignore # pylint: disable=no-member\n            population_size,\n            init_measured_ratio,\n            init_min_unmeasured,\n            max_fail_count,\n            genetic_num_iters,\n            genetic_mutate_prob,\n            genetic_max_fail_count,\n            eps_greedy,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/search_strategy/replay_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Replay Trace Search Strategy\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .search_strategy import SearchStrategy\n\n\n@register_object(\"meta_schedule.ReplayFunc\")\nclass ReplayFunc(SearchStrategy):\n    \"\"\"\n    Replay Func Search Strategy is a search strategy that generates measure candidates by\n    calling a design space generator and transform the design space.\n\n    Parameters\n    ----------\n    num_trials_per_iter : int\n        Number of trials per iteration.\n    max_trials_per_task : int\n        Total number of trials for one task\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Constructor\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchStrategyReplayFunc,  # type: ignore # pylint: disable=no-member\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/search_strategy/replay_trace.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Replay Trace Search Strategy\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .search_strategy import SearchStrategy\n\n\n@register_object(\"meta_schedule.ReplayTrace\")\nclass ReplayTrace(SearchStrategy):\n    \"\"\"\n    Replay Trace Search Strategy is a search strategy that always replays the trace by removing its\n    decisions so that the decisions would be randomly re-generated.\n\n    Parameters\n    ----------\n    max_fail_count : int\n        Max number of failures during trace replaying.\n    \"\"\"\n\n    max_fail_count: int\n\n    def __init__(self, max_fail_count: int = 100):\n        \"\"\"Constructor\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchStrategyReplayTrace,  # type: ignore # pylint: disable=no-member\n            max_fail_count,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/search_strategy/search_strategy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nMeta Schedule search strategy that generates the measure\ncandidates for measurement.\n\"\"\"\nfrom typing import TYPE_CHECKING, Callable, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.tir.schedule import Schedule\n\nfrom .. import _ffi_api\nfrom ..arg_info import ArgInfo\nfrom ..runner import RunnerResult\n\nif TYPE_CHECKING:\n    from ..cost_model import CostModel\n    from ..database import Database\n    from ..tune_context import TuneContext\n\n\n@register_object(\"meta_schedule.MeasureCandidate\")\nclass MeasureCandidate(Object):\n    \"\"\"Measure candidate class.\n\n    Parameters\n    ----------\n    sch : Schedule\n        The schedule to be measured.\n    args_info : List[ArgInfo]\n        The argument information.\n    \"\"\"\n\n    sch: Schedule\n    args_info: List[ArgInfo]\n\n    def __init__(\n        self,\n        sch: Schedule,\n        args_info: List[ArgInfo],\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be measured.\n        args_info : List[ArgInfo]\n            The argument information.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.MeasureCandidate,  # type: ignore # pylint: disable=no-member\n            sch,\n            args_info,\n        )\n\n\n@register_object(\"meta_schedule.SearchStrategy\")\nclass SearchStrategy(Object):\n    \"\"\"Search strategy is the class that generates the measure candidates.\"\"\"\n\n    SearchStrategyType = Union[\n        \"SearchStrategy\",\n        Literal[\n            \"replay-func\",\n            \"replay-trace\",\n            \"evolutionary\",\n        ],\n    ]\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the search strategy with tuning context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initialization.\n        \"\"\"\n        _ffi_api.SearchStrategyInitializeWithTuneContext(  # type: ignore # pylint: disable=no-member\n            self, context\n        )\n\n    def pre_tuning(\n        self,\n        max_trials: int,\n        num_trials_per_iter: int,\n        design_spaces: List[Schedule],\n        database: Optional[\"Database\"] = None,\n        cost_model: Optional[\"CostModel\"] = None,\n    ) -> None:\n        \"\"\"Pre-tuning for the search strategy.\n\n        Parameters\n        ----------\n        max_trials : int\n            The maximum number of trials.\n        num_trials_per_iter : int\n            The number of trials per iteration.\n        design_spaces : List[Schedule]\n            The design spaces used during tuning process.\n        database : Optional[Database] = None\n            The database used during tuning process.\n        cost_model : Optional[CostModel] = None\n            The cost model used during tuning process.\n        \"\"\"\n        _ffi_api.SearchStrategyPreTuning(  # type: ignore # pylint: disable=no-member\n            self,\n            max_trials,\n            num_trials_per_iter,\n            design_spaces,\n            database,\n            cost_model,\n        )\n\n    def post_tuning(self) -> None:\n        \"\"\"Post-tuning for the search strategy.\"\"\"\n        _ffi_api.SearchStrategyPostTuning(self)  # type: ignore # pylint: disable=no-member\n\n    def generate_measure_candidates(self) -> Optional[List[MeasureCandidate]]:\n        \"\"\"Generate measure candidates from design spaces for measurement.\n\n        Returns\n        -------\n        measure_candidates : Optional[List[IRModule]]\n            The measure candidates generated, None if finished.\n        \"\"\"\n        return _ffi_api.SearchStrategyGenerateMeasureCandidates(self)  # type: ignore # pylint: disable=no-member\n\n    def notify_runner_results(\n        self,\n        measure_candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the search strategy with profiling results.\n\n        Parameters\n        ----------\n        measure_candidates : List[MeasureCandidate]\n            The measure candidates for update.\n        results : List[RunnerResult]\n            The profiling results from the runner.\n        \"\"\"\n        _ffi_api.SearchStrategyNotifyRunnerResults(  # type: ignore # pylint: disable=no-member\n            self,\n            measure_candidates,\n            results,\n        )\n\n    def clone(self) -> \"SearchStrategy\":\n        \"\"\"Clone the search strategy.\n\n        Returns\n        -------\n        cloned : SearchStrategy\n            The cloned search strategy.\n        \"\"\"\n        return _ffi_api.SearchStrategyClone(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Literal[\n            \"evolutionary\",\n            \"replay-trace\",\n            \"replay-func\",\n        ] = \"evolutionary\",\n        *args,\n        **kwargs,\n    ) -> \"SearchStrategy\":\n        \"\"\"Create a search strategy.\"\"\"\n        from . import (  # pylint: disable=import-outside-toplevel\n            EvolutionarySearch,\n            ReplayFunc,\n            ReplayTrace,\n        )\n\n        if kind == \"evolutionary\":\n            return EvolutionarySearch(*args, **kwargs)\n        if kind == \"replay-trace\":\n            return ReplayTrace(*args, **kwargs)\n        if kind == \"replay-func\":\n            return ReplayFunc(*args, **kwargs)  # type: ignore\n        raise ValueError(f\"Unknown SearchStrategy: {kind}\")\n\n\ncreate = SearchStrategy.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PySearchStrategy\")\nclass _PySearchStrategy(SearchStrategy):\n    \"\"\"\n    A TVM object search strategy to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PySearchStrategy\n    \"\"\"\n\n    def __init__(\n        self,\n        f_initialize_with_tune_context: Callable = None,\n        f_pre_tuning: Callable = None,\n        f_post_tuning: Callable = None,\n        f_generate_measure_candidates: Callable = None,\n        f_notify_runner_results: Callable = None,\n        f_clone: Callable = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.SearchStrategyPySearchStrategy,  # type: ignore # pylint: disable=no-member\n            f_initialize_with_tune_context,\n            f_pre_tuning,\n            f_post_tuning,\n            f_generate_measure_candidates,\n            f_notify_runner_results,\n            f_clone,\n        )\n\n\nclass PySearchStrategy:\n    \"\"\"\n    An abstract search strategy with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PySearchStrategy,\n        \"methods\": [\n            \"_initialize_with_tune_context\",\n            \"pre_tuning\",\n            \"post_tuning\",\n            \"generate_measure_candidates\",\n            \"notify_runner_results\",\n            \"clone\",\n        ],\n    }\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the search strategy with tuning context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initialization.\n        \"\"\"\n        raise NotImplementedError\n\n    def pre_tuning(\n        self,\n        max_trials: int,\n        num_trials_per_iter: int,\n        design_spaces: List[Schedule],\n        database: Optional[\"Database\"] = None,\n        cost_model: Optional[\"CostModel\"] = None,\n    ) -> None:\n        \"\"\"Pre-tuning for the search strategy.\n\n        Parameters\n        ----------\n        design_spaces : List[Schedule]\n            The design spaces for pre-tuning.\n        \"\"\"\n        raise NotImplementedError\n\n    def post_tuning(self) -> None:\n        \"\"\"Post-tuning for the search strategy.\"\"\"\n        raise NotImplementedError\n\n    def generate_measure_candidates(self) -> Optional[List[MeasureCandidate]]:\n        \"\"\"Generate measure candidates from design spaces for measurement.\n\n        Returns\n        -------\n        measure_candidates : Optional[List[IRModule]]\n            The measure candidates generated, None if finished.\n        \"\"\"\n        raise NotImplementedError\n\n    def notify_runner_results(\n        self,\n        measure_candidates: List[MeasureCandidate],\n        results: List[RunnerResult],\n    ) -> None:\n        \"\"\"Update the search strategy with profiling results.\n\n        Parameters\n        ----------\n        measure_candidates : List[MeasureCandidate]\n            The measure candidates for update.\n        results : List[RunnerResult]\n            The profiling results from the runner.\n        \"\"\"\n        raise NotImplementedError\n\n    def clone(self) -> SearchStrategy:\n        \"\"\"Clone the search strategy.\n\n        Returns\n        -------\n        strategy : SearchStrategy\n            The cloned search strategy.\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/space_generator/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.space_generator package.\nMeta Schedule design space generators that generates design\nspace for generation of measure candidates.\n\"\"\"\nfrom .post_order_apply import PostOrderApply\nfrom .schedule_fn import ScheduleFn\nfrom .space_generator import PySpaceGenerator, ScheduleFnType, SpaceGenerator, create\nfrom .space_generator_union import SpaceGeneratorUnion\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/space_generator/post_order_apply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Post Order Apply Space Generator.\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .space_generator import (\n    MutatorProbType,\n    PostprocType,\n    ScheduleRuleType,\n    SpaceGenerator,\n    _normalize_rules,\n)\n\n\n@register_object(\"meta_schedule.PostOrderApply\")\nclass PostOrderApply(SpaceGenerator):\n    \"\"\"\n    PostOrderApply is the design space generator that generates design spaces by applying schedule\n    rules to blocks in post-DFS order.\n\n    Parameters\n    ----------\n    f_block_filter : Optional[function]\n        An optional callback function that is used to filter which blocks have schedules generated\n        for them. The function should take in a block and return True if a schedule should\n        be generated or False if that block should be skipped. If no function is provided\n        all blocks will have schedules generated.\n    \"\"\"\n\n    def __init__(\n        self,\n        f_block_filter=None,\n        sch_rules: ScheduleRuleType = \"from-target\",\n        postprocs: PostprocType = \"from-target\",\n        mutator_probs: MutatorProbType = \"from-target\",\n    ):\n        \"\"\"Constructor\"\"\"\n        sch_rules, postprocs, mutator_probs = _normalize_rules(sch_rules, postprocs, mutator_probs)\n        self.__init_handle_by_constructor__(\n            _ffi_api.SpaceGeneratorPostOrderApply,  # type: ignore # pylint: disable=no-member\n            f_block_filter,\n            sch_rules,\n            postprocs,\n            mutator_probs,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/space_generator/schedule_fn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Union of meta Schedule design space generators.\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .space_generator import (\n    MutatorProbType,\n    PostprocType,\n    ScheduleRuleType,\n    SpaceGenerator,\n    _normalize_rules,\n)\n\n\n@register_object(\"meta_schedule.ScheduleFn\")\nclass ScheduleFn(SpaceGenerator):\n    \"\"\"Create a design space generator with customized schedule function.\n    The schedule function can have the following signatures:\n    - 1) [Schedule] -> None\n    - 2) [Schedule] -> Schedule\n    - 3) [Schedule] -> List[Schedule]\n    \"\"\"\n\n    def __init__(\n        self,\n        sch_fn: SpaceGenerator.ScheduleFnType,\n        sch_rules: ScheduleRuleType = \"from-target\",\n        postprocs: PostprocType = \"from-target\",\n        mutator_probs: MutatorProbType = \"from-target\",\n    ):\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        sch_fn : SpaceGenerator.ScheduleFnType\n            The schedule function, which can have the following signatures:\n            - 1) [Schedule] -> None\n            - 2) [Schedule] -> Schedule\n            - 3) [Schedule] -> List[Schedule]\n        \"\"\"\n        sch_rules, postprocs, mutator_probs = _normalize_rules(sch_rules, postprocs, mutator_probs)\n        self.__init_handle_by_constructor__(\n            _ffi_api.SpaceGeneratorScheduleFn,  # type: ignore # pylint: disable=no-member\n            sch_fn,\n            sch_rules,\n            postprocs,\n            mutator_probs,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/space_generator/space_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nMeta Schedule design space generators that generates design\nspace for generation of measure candidates.\n\"\"\"\nfrom typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\nfrom tvm._ffi import register_object\nfrom tvm.ir import IRModule\nfrom tvm.runtime import Object\nfrom tvm.tir.schedule import Schedule\n\nfrom .. import _ffi_api\n\nif TYPE_CHECKING:\n    from ..mutator import Mutator\n    from ..postproc import Postproc\n    from ..schedule_rule import ScheduleRule\n    from ..tune_context import TuneContext\n\n\n@register_object(\"meta_schedule.SpaceGenerator\")\nclass SpaceGenerator(Object):\n    \"\"\"The abstract design space generator interface.\"\"\"\n\n    ScheduleFnType = Union[\n        Callable[[Schedule], None],  # No output\n        Callable[[Schedule], Schedule],  # Single output\n        Callable[[Schedule], List[Schedule]],  # Multiple outputs\n    ]\n\n    SpaceGeneratorType = Union[\n        \"SpaceGenerator\",\n        ScheduleFnType,\n        Literal[\"post-order-apply\", \"union\"],\n    ]\n\n    sch_rules: Optional[List[\"ScheduleRule\"]]\n    postprocs: Optional[List[\"Postproc\"]]\n    mutator_probs: Optional[Dict[\"Mutator\", float]]\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the design space generator with tuning context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the design space generator.\n        \"\"\"\n        _ffi_api.SpaceGeneratorInitializeWithTuneContext(  # type: ignore # pylint: disable=no-member\n            self, context\n        )\n\n    def generate_design_space(self, mod: IRModule) -> List[Schedule]:\n        \"\"\"Generate design spaces given a module.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The module used for design space generation.\n\n        Returns\n        -------\n        design_spaces : List[Schedule]\n            The generated design spaces, i.e., schedules.\n        \"\"\"\n        return _ffi_api.SpaceGeneratorGenerateDesignSpace(self, mod)  # type: ignore # pylint: disable=no-member\n\n    def clone(self) -> \"SpaceGenerator\":\n        \"\"\"Clone the design space generator.\n\n        Returns\n        -------\n        cloned_sg : SpaceGenerator\n            The cloned design space generator.\n        \"\"\"\n        return _ffi_api.SpaceGeneratorClone(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Union[\n            Literal[\"post-order-apply\", \"union\"],\n            ScheduleFnType,\n        ] = \"post-order-apply\",\n        *args,\n        **kwargs,\n    ) -> \"SpaceGenerator\":\n        \"\"\"Create a design space generator.\"\"\"\n        from . import (  # pylint: disable=import-outside-toplevel\n            PostOrderApply,\n            ScheduleFn,\n            SpaceGeneratorUnion,\n        )\n\n        if callable(kind):\n\n            def create_schedule_fn(\n                func,\n                sch_rules=[],\n                postprocs=[],\n                mutator_probs={},\n            ):  # pylint: disable=dangerous-default-value\n                return ScheduleFn(func, sch_rules, postprocs, mutator_probs)\n\n            return create_schedule_fn(kind, *args, **kwargs)  # type: ignore\n        if kind == \"post-order-apply\":\n            return PostOrderApply(*args, **kwargs)\n        if kind == \"union\":\n            return SpaceGeneratorUnion(*args, **kwargs)\n        raise ValueError(f\"Unknown SpaceGenerator: {kind}\")\n\n\nScheduleFnType = SpaceGenerator.ScheduleFnType\nScheduleRuleType = Union[\n    List[\"ScheduleRule\"],\n    Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\", \"from-target\"],\n]\nPostprocType = Union[\n    List[\"Postproc\"],\n    Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\", \"from-target\"],\n]\nMutatorProbType = Union[\n    Dict[\"Mutator\", float],\n    Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\", \"from-target\"],\n]\ncreate = SpaceGenerator.create  # pylint: disable=invalid-name\n\n\ndef _normalize_rules(\n    sch_rules: ScheduleRuleType,\n    postprocs: PostprocType,\n    mutator_probs: MutatorProbType,\n) -> Tuple[\n    Optional[List[\"ScheduleRule\"]],\n    Optional[List[\"Postproc\"]],\n    Optional[Dict[\"Mutator\", float]],\n]:\n    # pylint: disable=import-outside-toplevel\n    from ..mutator import Mutator\n    from ..postproc import Postproc\n    from ..schedule_rule import ScheduleRule\n\n    # pylint: enable=import-outside-toplevel\n    assert sch_rules is not None\n    assert postprocs is not None\n    assert mutator_probs is not None\n\n    if isinstance(sch_rules, str):\n        if sch_rules == \"from-target\":\n            sch_rules = None\n        else:\n            sch_rules = ScheduleRule.create(sch_rules)\n    if isinstance(postprocs, str):\n        if postprocs == \"from-target\":\n            postprocs = None\n        else:\n            postprocs = Postproc.create(postprocs)\n    if isinstance(mutator_probs, str):\n        if mutator_probs == \"from-target\":\n            mutator_probs = None\n        else:\n            mutator_probs = Mutator.create(mutator_probs)\n    return sch_rules, postprocs, mutator_probs  # type: ignore\n\n\n@register_object(\"meta_schedule.PySpaceGenerator\")\nclass _PySpaceGenerator(SpaceGenerator):\n    \"\"\"\n    A TVM object space generator to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PySpaceGenerator\n    \"\"\"\n\n    def __init__(\n        self,\n        sch_rules: ScheduleRuleType = \"from-target\",\n        postprocs: PostprocType = \"from-target\",\n        mutator_probs: MutatorProbType = \"from-target\",\n        f_initialize_with_tune_context: Optional[Callable] = None,\n        f_generate_design_space: Optional[Callable] = None,\n        f_clone: Optional[Callable] = None,\n    ):\n        \"\"\"Constructor.\"\"\"\n        sch_rules, postprocs, mutator_probs = _normalize_rules(sch_rules, postprocs, mutator_probs)\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.SpaceGeneratorPySpaceGenerator,  # type: ignore # pylint: disable=no-member\n            sch_rules,\n            postprocs,\n            mutator_probs,\n            f_initialize_with_tune_context,\n            f_generate_design_space,\n            f_clone,\n        )\n\n\nclass PySpaceGenerator:\n    \"\"\"\n    An abstract space generator with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PySpaceGenerator,\n        \"fields\": [\"sch_rules\", \"postprocs\", \"mutator_probs\"],\n        \"methods\": [\"_initialize_with_tune_context\", \"generate_design_space\", \"clone\"],\n    }\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        \"\"\"Initialize the design space generator with tuning context.\n\n        Parameters\n        ----------\n        context : TuneContext\n            The tuning context for initializing the design space generator.\n        \"\"\"\n        raise NotImplementedError\n\n    def generate_design_space(self, mod: IRModule) -> List[Schedule]:\n        \"\"\"Generate design spaces given a module.\n\n        Parameters\n        ----------\n        mod : IRModule\n            The module used for design space generation.\n\n        Returns\n        -------\n        design_spaces : List[Schedule]\n            The generated design spaces, i.e., schedules.\n        \"\"\"\n        raise NotImplementedError\n\n    def clone(self) -> SpaceGenerator:\n        \"\"\"Clone the design space generator.\n\n        Returns\n        -------\n        cloned_sg : SpaceGenerator\n            The cloned design space generator.\n        \"\"\"\n        raise NotImplementedError\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/space_generator/space_generator_union.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Union of meta Schedule design space generators.\"\"\"\nfrom typing import List\n\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom .space_generator import (\n    MutatorProbType,\n    PostprocType,\n    ScheduleRuleType,\n    SpaceGenerator,\n    _normalize_rules,\n)\n\n\n@register_object(\"meta_schedule.SpaceGeneratorUnion\")\nclass SpaceGeneratorUnion(SpaceGenerator):\n    \"\"\"Union of design space generators.\"\"\"\n\n    def __init__(\n        self,\n        space_generators: List[SpaceGenerator],\n        sch_rules: ScheduleRuleType = \"from-target\",\n        postprocs: PostprocType = \"from-target\",\n        mutator_probs: MutatorProbType = \"from-target\",\n    ):\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        space_generators : List[SpaceGenerator]\n            The list of design space generators to be unioned.\n        \"\"\"\n        sch_rules, postprocs, mutator_probs = _normalize_rules(sch_rules, postprocs, mutator_probs)\n        self.__init_handle_by_constructor__(\n            _ffi_api.SpaceGeneratorSpaceGeneratorUnion,  # type: ignore # pylint: disable=no-member\n            space_generators,\n            sch_rules,\n            postprocs,\n            mutator_probs,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/task_scheduler/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe tvm.meta_schedule.task_scheduler package.\nMeta Schedule task scheduler that manage the task scheduling\nfor measure candidates generation and measurement, then save\nrecords to the database.\n\"\"\"\nfrom .gradient_based import GradientBased\nfrom .round_robin import RoundRobin\nfrom .task_scheduler import PyTaskScheduler, TaskScheduler, create\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/task_scheduler/gradient_based.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Gradient Based Task Scheduler\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom ..logging import get_logger, get_logging_func\nfrom .task_scheduler import TaskScheduler\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.GradientBased\")\nclass GradientBased(TaskScheduler):\n    \"\"\"Gradient Based Task Scheduler\"\"\"\n\n    def __init__(\n        self,\n        *,\n        alpha: float = 0.2,\n        window_size: int = 3,\n        seed: int = -1,\n    ) -> None:\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        alpha : float = 0.2\n            The parameter alpha in gradient computation.\n        window_size : int = 3\n            The parameter to control backward window size in gradient computation.\n        seed : int = -1\n            The random seed.\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.TaskSchedulerGradientBased,  # type: ignore # pylint: disable=no-member\n            get_logging_func(logger),\n            alpha,\n            window_size,\n            seed,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/task_scheduler/round_robin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Round Robin Task Scheduler\"\"\"\nfrom tvm._ffi import register_object\n\nfrom .. import _ffi_api\nfrom ..logging import get_logger, get_logging_func\nfrom .task_scheduler import TaskScheduler\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.RoundRobin\")\nclass RoundRobin(TaskScheduler):\n    \"\"\"Round Robin Task Scheduler\"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Constructor.\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.TaskSchedulerRoundRobin,  # type: ignore # pylint: disable=no-member\n            get_logging_func(logger),\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/task_scheduler/task_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Auto-tuning Task Scheduler\"\"\"\nfrom typing import Callable, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\n\nfrom .. import _ffi_api\nfrom ..builder import Builder, BuilderResult\nfrom ..cost_model import CostModel\nfrom ..database import Database\nfrom ..logging import get_logger, get_logging_func\nfrom ..measure_callback import MeasureCallback\nfrom ..runner import Runner, RunnerResult\nfrom ..search_strategy import MeasureCandidate\nfrom ..tune_context import TuneContext\n\nlogger = get_logger(__name__)  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.TaskRecord\")\nclass TaskRecord(Object):\n    \"\"\"The running record of a task.\"\"\"\n\n    ctx: TuneContext\n    task_weight: float\n    flop: float\n    is_terminated: bool\n    build_error_count: int\n    run_error_count: int\n    measure_candidates: List[MeasureCandidate]\n    builder_results: List[BuilderResult]\n    runner_results: List[RunnerResult]\n\n\n@register_object(\"meta_schedule.TaskScheduler\")\nclass TaskScheduler(Object):\n    \"\"\"The abstract task scheduler interface.\"\"\"\n\n    tasks_: List[TaskRecord]\n    measure_callbacks_: List[MeasureCallback]\n    database_: Optional[Database]\n    cost_model_: Optional[CostModel]\n    remaining_tasks_: int\n\n    TaskSchedulerType = Union[\"TaskScheduler\", Literal[\"gradient\", \"round-robin\"]]\n\n    def next_task_id(self) -> int:\n        \"\"\"Fetch the next task id.\n\n        Returns\n        -------\n        next_task_id : int\n            The next task id.\n        \"\"\"\n        return _ffi_api.TaskSchedulerNextTaskId(self)  # type: ignore # pylint: disable=no-member\n\n    def join_running_task(self, task_id: int) -> List[RunnerResult]:\n        \"\"\"Wait until the task is finished.\n\n        Parameters\n        ----------\n        task_id : int\n            The task id to be joined.\n\n        Returns\n        -------\n        results : List[RunnerResult]\n            The list of results.\n        \"\"\"\n        return _ffi_api.TaskSchedulerJoinRunningTask(self, task_id)  # type: ignore # pylint: disable=no-member\n\n    def tune(\n        self,\n        tasks: List[TuneContext],\n        task_weights: List[float],\n        max_trials_global: int,\n        max_trials_per_task: int,\n        num_trials_per_iter: int,\n        builder: Builder,\n        runner: Runner,\n        measure_callbacks: List[MeasureCallback],\n        database: Optional[Database],\n        cost_model: Optional[CostModel],\n    ) -> None:\n        \"\"\"Auto-tuning.\n\n        Parameters\n        ----------\n        tasks : List[TuneContext]\n            The list of tuning contexts as tasks.\n        task_weights : List[float]\n            The list of task weights.\n        max_trials_global : int\n            The maximum number of trials globally.\n        max_trials_per_task : int\n            The maximum number of trials per task.\n        num_trials_per_iter : int\n            The number of trials per iteration.\n        builder : Builder\n            The builder.\n        runner : Runner\n            The runner.\n        measure_callbacks : List[MeasureCallback]\n            The list of measure callbacks.\n        database : Optional[Database]\n            The database.\n        cost_model : Optional[CostModel]\n            The cost model.\n        \"\"\"\n        task_weights = [float(w) for w in task_weights]\n        _ffi_api.TaskSchedulerTune(  # type: ignore # pylint: disable=no-member\n            self,\n            tasks,\n            task_weights,\n            max_trials_global,\n            max_trials_per_task,\n            num_trials_per_iter,\n            builder,\n            runner,\n            measure_callbacks,\n            database,\n            cost_model,\n        )\n\n    def terminate_task(self, task_id: int) -> None:\n        \"\"\"Terminate the task\n\n        Parameters\n        ----------\n        task_id : int\n            The task id to be terminated.\n        \"\"\"\n        _ffi_api.TaskSchedulerTerminateTask(self, task_id)  # type: ignore # pylint: disable=no-member\n\n    def touch_task(self, task_id: int) -> None:\n        \"\"\"Touch the task and update its status\n\n        Parameters\n        ----------\n        task_id : int\n            The task id to be checked.\n        \"\"\"\n        _ffi_api.TaskSchedulerTouchTask(self, task_id)  # type: ignore # pylint: disable=no-member\n\n    def print_tuning_statistics(self) -> None:\n        \"\"\"Print out a human-readable format of the tuning statistics.\"\"\"\n        return _ffi_api.TaskSchedulerPrintTuningStatistics(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def create(  # pylint: disable=keyword-arg-before-vararg\n        kind: Literal[\"round-robin\", \"gradient\"] = \"gradient\",\n        *args,\n        **kwargs,\n    ) -> \"TaskScheduler\":\n        \"\"\"Create a task scheduler.\"\"\"\n        from . import (  # pylint: disable=import-outside-toplevel\n            GradientBased,\n            RoundRobin,\n        )\n\n        if kind == \"round-robin\":\n            return RoundRobin(*args, **kwargs)  # type: ignore\n        if kind == \"gradient\":\n            return GradientBased(*args, **kwargs)\n        raise ValueError(f\"Unknown TaskScheduler name: {kind}\")\n\n\ncreate = TaskScheduler.create  # pylint: disable=invalid-name\n\n\n@register_object(\"meta_schedule.PyTaskScheduler\")\nclass _PyTaskScheduler(TaskScheduler):\n    \"\"\"\n    A TVM object task scheduler to support customization on the python side.\n    This is NOT the user facing class for function overloading inheritance.\n\n    See also: PyTaskScheduler\n    \"\"\"\n\n    def __init__(\n        self,\n        f_next_task_id: Callable,\n        f_join_running_task: Callable,\n        f_tune: Callable,\n    ):\n        \"\"\"Constructor.\"\"\"\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.TaskSchedulerPyTaskScheduler,  # type: ignore # pylint: disable=no-member\n            get_logging_func(logger),\n            f_next_task_id,\n            f_join_running_task,\n            f_tune,\n        )\n\n\nclass PyTaskScheduler:\n    \"\"\"\n    An abstract task scheduler with customized methods on the python-side.\n    This is the user facing class for function overloading inheritance.\n\n    Note: @derived_object is required for proper usage of any inherited class.\n    \"\"\"\n\n    _tvm_metadata = {\n        \"cls\": _PyTaskScheduler,\n        \"fields\": [],\n        \"methods\": [\"next_task_id\", \"join_running_task\", \"tune\"],\n    }\n\n    def __init__(self):\n        ...\n\n    def tune(\n        self,\n        tasks: List[TuneContext],\n        task_weights: List[float],\n        max_trials_global: int,\n        max_trials_per_task: int,\n        builder: Builder,\n        runner: Runner,\n        measure_callbacks: List[MeasureCallback],\n        database: Optional[Database],\n        cost_model: Optional[CostModel],\n    ) -> None:\n        \"\"\"Auto-tuning.\"\"\"\n        # Using self._outer to replace the self pointer\n        _ffi_api.TaskSchedulerTune(  # type: ignore # pylint: disable=no-member\n            self._outer(),  # type: ignore # pylint: disable=no-member\n            tasks,\n            task_weights,\n            max_trials_global,\n            max_trials_per_task,\n            builder,\n            runner,\n            measure_callbacks,\n            database,\n            cost_model,\n        )\n\n    def next_task_id(self) -> int:\n        \"\"\"Fetch the next task id.\n\n        Returns\n        -------\n        next_task_id : int\n            The next task id.\n        \"\"\"\n        raise NotImplementedError\n\n    def join_running_task(self, task_id: int) -> List[RunnerResult]:\n        \"\"\"Wait until the task is finished.\n\n        Parameters\n        ----------\n        task_id : int\n            The task id to be joined.\n        \"\"\"\n        # Using self._outer to replace the self pointer\n        return _ffi_api.TaskSchedulerJoinRunningTask(self._outer(), task_id)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testing utilities in meta schedule\"\"\"\n\n# NOTE: Do not import any module here by default\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/custom_builder_runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Customized builder and runner methods\"\"\"\n# pylint: disable=import-outside-toplevel\n\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union, Callable\n\nif TYPE_CHECKING:\n    import numpy as np  # type: ignore\n    from tvm.ir import IRModule\n    from tvm.meta_schedule.runner import EvaluatorConfig, RPCConfig\n    from tvm.runtime import Device, Module, NDArray\n    from tvm.target import Target\n    from tvm.runtime.vm import Executable\n\n\ndef build_relay(\n    mod: \"IRModule\",\n    target: \"Target\",\n    params: Dict[str, \"NDArray\"],\n) -> \"Module\":\n    \"\"\"Build a Relay IRModule\n\n    Parameters\n    ----------\n    mod : IRModule\n        The Relay IRModule to build.\n    target : Target\n        The target to build the module for.\n    params : Dict[str, NDArray]\n        The parameter dict to build the module with.\n\n    Returns\n    -------\n    mod : runtime.Module\n        The built module.\n    \"\"\"\n    from tvm.relay.build_module import _build_module_no_factory as relay_build\n    from tvm.runtime import Module\n\n    result = relay_build(mod, target=target, target_host=None, params=params)\n    assert isinstance(result, Module)\n    return result\n\n\ndef build_relay_with_tensorrt(\n    mod: \"IRModule\",\n    target: \"Target\",\n    params: Dict[str, \"NDArray\"],\n) -> \"Module\":\n    \"\"\"Build a Relay IRModule with TensorRT BYOC\n\n    Parameters\n    ----------\n    mod : IRModule\n        The Relay IRModule to build.\n\n    target : Target\n        The target to build the module for.\n\n    params : Dict[str, NDArray]\n        The parameter dict to build the module with.\n\n    Returns\n    -------\n    mod : runtime.Module\n        The built module.\n    \"\"\"\n    from tvm.ir.transform import PassContext\n    from tvm.relay.build_module import _build_module_no_factory as relay_build\n    from tvm.relay.op.contrib import tensorrt\n    from tvm.runtime import Module\n\n    mod = tensorrt.partition_for_tensorrt(mod, params)\n    with PassContext(opt_level=3):\n        result = relay_build(mod, target=target, target_host=None, params=params)\n    assert isinstance(result, Module)\n    return result\n\n\ndef run_with_graph_executor(\n    rt_mod: \"Module\",\n    device: \"Device\",\n    evaluator_config: \"EvaluatorConfig\",\n    repeated_args: List[\"NDArray\"],\n) -> List[float]:\n    \"\"\"Run a Relay module with GraphExecutor\n\n    Parameters\n    ----------\n    rt_mod : Module\n        The Relay module to run.\n    device : Device\n        The device to run the module on.\n    evaluator_config : EvaluatorConfig\n        The evaluator configuration to run the module with.\n    repeated_args : List[NDArray]\n        The list of repeated arguments to run the module with.\n\n    Returns\n    -------\n    results : List[float]\n        The list of results.\n    \"\"\"\n    import itertools\n\n    from tvm.contrib.graph_executor import GraphModule\n\n    graph_mod = GraphModule(rt_mod[\"default\"](device))\n    evaluator = graph_mod.module.time_evaluator(\n        func_name=\"run\",\n        dev=device,\n        number=evaluator_config.number,\n        repeat=evaluator_config.repeat,\n        min_repeat_ms=evaluator_config.min_repeat_ms,\n        f_preproc=\"cache_flush_cpu_non_first_arg\"\n        if evaluator_config.enable_cpu_cache_flush\n        else \"\",\n    )\n    repeated_costs = []\n    for args in repeated_args:\n        profile_result = evaluator(*args)\n        repeated_costs.append(profile_result.results)\n    costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)]\n    return costs\n\n\ndef run_module_via_rpc(\n    rpc_config: \"RPCConfig\",\n    lib: Union[\"Module\", \"Executable\"],\n    dev_type: str,\n    args: Union[Dict[int, \"np.ndarray\"], Dict[str, \"np.ndarray\"]],\n    continuation: Callable,\n    backend: Optional[str] = \"graph\",\n):\n    \"\"\"Execute a tvm.runtime.Module on RPC remote\"\"\"\n    # pylint: disable=import-outside-toplevel\n    import os\n    import tempfile\n\n    from tvm.contrib.tar import tar\n    from tvm.runtime import ndarray\n\n    # pylint: enable=import-outside-toplevel\n\n    with tempfile.TemporaryDirectory() as tmp_dir:\n        filename = os.path.join(tmp_dir, \"tvm_tmp_mod.\" + tar.output_format)\n        if backend == \"vm\":\n            code, lib = lib.save()\n        lib.export_library(filename, tar)\n        session = rpc_config.connect_server()\n        session.upload(filename)\n        _, filename = os.path.split(filename)\n        rt_mod = session.load_module(filename)\n        if backend == \"vm\":\n            rt_mod = session.get_function(\"runtime.Load_Executable\")(code, rt_mod)\n        dev = session.device(dev_type=dev_type, dev_id=0)\n        nd_args = {k: ndarray.array(v, dev) for k, v in args.items()}\n        return continuation(rt_mod, dev, nd_args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/dataset_collect_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\n\nimport argparse\nimport os\nfrom typing import List, Tuple\n\nfrom tqdm import tqdm  # type: ignore\nfrom tvm.meta_schedule.testing.relay_workload import get_network\n\n\n# pylint: disable=too-many-branches\ndef _build_dataset() -> List[Tuple[str, List[int]]]:\n    network_keys = []\n    for name in [\n        \"resnet_18\",\n        \"resnet_50\",\n        \"mobilenet_v2\",\n        \"mobilenet_v3\",\n        \"wide_resnet_50\",\n        \"resnext_50\",\n        \"densenet_121\",\n        \"vgg_16\",\n    ]:\n        for batch_size in [1, 4, 8]:\n            for image_size in [224, 240, 256]:\n                network_keys.append((name, [batch_size, 3, image_size, image_size]))\n    # inception-v3\n    for name in [\"inception_v3\"]:\n        for batch_size in [1, 2, 4]:\n            for image_size in [299]:\n                network_keys.append((name, [batch_size, 3, image_size, image_size]))\n    # resnet3d\n    for name in [\"resnet3d_18\"]:\n        for batch_size in [1, 2, 4]:\n            for image_size in [112, 128, 144]:\n                network_keys.append((name, [batch_size, 3, image_size, image_size, 16]))\n    # bert\n    for name in [\"bert_tiny\", \"bert_base\", \"bert_medium\", \"bert_large\"]:\n        for batch_size in [1, 2, 4]:\n            for seq_length in [64, 128, 256]:\n                network_keys.append((name, [batch_size, seq_length]))\n    # dcgan\n    for name in [\"dcgan\"]:\n        for batch_size in [1, 4, 8]:\n            for image_size in [64]:\n                network_keys.append((name, [batch_size, 3, image_size, image_size]))\n    return network_keys\n\n\ndef main():\n    model_cache_dir = args.model_cache_dir\n    try:\n        os.makedirs(model_cache_dir, exist_ok=True)\n    except OSError:\n        print(f\"Directory {model_cache_dir} cannot be created successfully.\")\n    keys = _build_dataset()\n    for name, input_shape in tqdm(keys):\n        get_network(name=name, input_shape=input_shape, cache_dir=model_cache_dir)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()  # pylint: disable=invalid-name\n    parser.add_argument(\n        \"--model_cache_dir\",\n        type=str,\n        help=\"Please provide the full path to the model cache dir.\",\n    )\n    args = parser.parse_args()  # pylint: disable=invalid-name\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/dataset_extract_tasks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\n\nimport argparse\nimport glob\nimport json\nimport os\n\nimport tvm\nfrom tqdm import tqdm  # type: ignore\nfrom tvm import meta_schedule as ms\nfrom tvm.ir import save_json\nfrom tvm.meta_schedule.testing.relay_workload import _load_cache\nfrom tvm.runtime import load_param_dict\n\n\ndef _parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--model_cache_dir\", type=str, help=\"Please provide the full path to the model cache dir.\"\n    )\n    parser.add_argument(\n        \"--task_cache_dir\", type=str, help=\"Please provide the full path to save extracted tasks.\"\n    )\n    parser.add_argument(\n        \"--target\", type=str, default=\"cuda\", help=\"Please specify the target hardware for tuning.\"\n    )\n    return parser.parse_args()\n\n\n# pylint: disable=too-many-locals\ndef extract_and_save_tasks(cache_file):\n    \"\"\"Extract tuning tasks and cache the nonspatial ones in the given directory.\n\n    Parameters\n    ----------\n    cache_file : str\n        The filename of the cached model.\n\n    Returns\n    -------\n    None\n    \"\"\"\n\n    mod, params_bytearray, _ = _load_cache(args.model_cache_dir, cache_file)\n    params = load_param_dict(params_bytearray)\n    try:\n        extracted_tasks = ms.relay_integration.extract_tasks(mod, target=args.target, params=params)\n    except tvm.error.TVMError as error:\n        print(str(error))\n        return\n    task_cache_path = os.path.join(\n        args.task_cache_dir, cache_file.split(\".\")[0] + \"_extracted_tasks.json\"\n    )\n    is_spatial = tvm.get_global_func(\"tir.schedule.IsSpatialPrimFunc\")\n    with open(task_cache_path, \"w\", encoding=\"utf8\") as file:\n        for i, task in enumerate(extracted_tasks):\n            subgraph = task.dispatched[0]\n            prim_func = subgraph[subgraph.get_global_vars()[0]]\n            if not is_spatial(prim_func):\n                subgraph_str = save_json(subgraph)\n                json_obj = [task.task_name, json.loads(subgraph_str)]\n                json_str = json.dumps(json_obj)\n                assert \"\\n\" not in json_str, \"Failed to generate single line string.\"\n                if i == len(extracted_tasks) - 1:\n                    file.write(json_str)\n                else:\n                    file.write(json_str + \"\\n\")\n\n\nargs = _parse_args()  # pylint: disable=invalid-name\n\n\ndef main():\n    if not os.path.isdir(args.model_cache_dir):\n        raise Exception(\"Please provide a correct model cache dir.\")\n    try:\n        os.makedirs(args.task_cache_dir, exist_ok=True)\n    except OSError:\n        print(f\"Directory {args.task_cache_dir} cannot be created successfully.\")\n\n    paths = glob.glob(os.path.join(args.model_cache_dir, \"*.json\"))  # pylint: disable=invalid-name\n    for path in tqdm(paths):\n        filename = path.split(\"/\")[-1]\n        extract_and_save_tasks(filename)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/dataset_sample_candidates.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\n\nimport argparse\nimport glob\nimport json\nimport os\nfrom typing import List\n\nimport tvm\nfrom tqdm import tqdm  # type: ignore\nfrom tvm import meta_schedule as ms\nfrom tvm.ir import load_json\nfrom tvm.target import Target\n\n\ndef _parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--task_cache_dir\", type=str, help=\"Please provide the full path to the extracted tasks.\"\n    )\n    parser.add_argument(\n        \"--candidate_cache_dir\",\n        type=str,\n        help=\"Please provide the full path to save the sampled candidates.\",\n    )\n    parser.add_argument(\n        \"--target\",\n        type=str,\n        default=\"nvidia/geforce-rtx-3070\",\n        help=\"Please specify the target hardware for tuning.\\\n                    Note: for generating dataset, the hardware does not need to be present.\",\n    )\n    parser.add_argument(\n        \"--init_population_size\",\n        type=int,\n        default=256,\n        help=\"The initial population size used in evolutionary search.\",\n    )\n    parser.add_argument(\n        \"--num_samples_per_task\",\n        type=int,\n        default=400,\n        help=\"The number of samples to gather per tuning task.\",\n    )\n    parser.add_argument(\n        \"--num_trials_per_iter\",\n        type=int,\n        default=64,\n        help=\"The number of trials per iteration in evolutionary search.\",\n    )\n    parser.add_argument(\n        \"--max_trials_per_task\",\n        type=int,\n        default=400,\n        help=\"The maximum number of trials per task in evolutionary search.\",\n    )\n    parser.add_argument(\n        \"--max_retry_per_task\",\n        type=int,\n        default=10,\n        help=\"The maximum number of retry attempts allowed.\",\n    )\n    parser.add_argument(\n        \"--file_group\",\n        type=int,\n        default=0,\n        help=\"To enable running multiple scripts in parallel, files [idx * 10 : (idx + 1) * 10]\\\n        in the sorted file list from the given directory will be run.\",\n    )\n    return parser.parse_args()\n\n\n# pylint: disable=too-many-locals\ndef sample_candidates(task, task_name, model_name):\n    \"\"\"Randomly sample candidates for a task and save the candidates in the given directory.\n\n    Parameters\n    ----------\n    task : IRModule\n        The initial ir module used for generating the search space.\n    task_name : str\n        The name of the task.\n    model_name : str\n        The name of the model.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    candidate_path = os.path.join(\n        args.candidate_cache_dir, model_name, task_name + \"_candidates.json\"\n    )\n    workload_path = os.path.join(args.candidate_cache_dir, model_name, task_name + \"_workload.json\")\n    database = ms.database.JSONDatabase(\n        path_workload=workload_path,\n        path_tuning_record=candidate_path,\n    )\n    sample_init_population = tvm.get_global_func(\n        \"meta_schedule.SearchStrategyEvolutionarySearchSampleInitPopulation\"\n    )\n    evolve_with_cost_model = tvm.get_global_func(\n        \"meta_schedule.SearchStrategyEvolutionarySearchEvolveWithCostModel\"\n    )\n    strategy = ms.search_strategy.EvolutionarySearch(init_measured_ratio=0.0)\n    target = Target(args.target)\n    context = ms.TuneContext(\n        mod=task,\n        target=target,\n        space_generator=\"post-order-apply\",\n        search_strategy=strategy,\n        task_name=task_name,\n    )\n    context.initialize()\n    context.pre_tuning(\n        max_trials=args.max_trials_per_task,\n        num_trials_per_iter=args.num_trials_per_iter,\n        design_spaces=context.generate_design_space(),\n        database=database,\n        cost_model=ms.cost_model.RandomModel(),  # type: ignore\n    )\n\n    all_states: List[tvm.tir.Schedule] = []\n    num_retry, itr = 0, 0\n    states = sample_init_population(strategy, args.init_population_size)\n    while len(all_states) < args.num_samples_per_task and num_retry < args.max_retry_per_task:\n        states = evolve_with_cost_model(strategy, states, len(states))\n        all_states += states\n        if len(states) == 0:\n            states = sample_init_population(strategy, args.init_population_size)\n            num_retry += 1\n        else:\n            num_retry = 0\n        print(f\"iter: {itr}, number of states sampled: {len(all_states)}\")\n        itr += 1\n    all_states = all_states[: args.num_samples_per_task]\n\n    workload = ms.database.Workload(context.mod)\n    database.commit_workload(context.mod)\n    for state in all_states:\n        database.commit_tuning_record(ms.database.TuningRecord(state.trace, workload))\n\n\nargs = _parse_args()  # pylint: disable=invalid-name\n\n\ndef main():\n    if not os.path.isdir(args.task_cache_dir):\n        raise Exception(\"Please provide a correct task cache dir.\")\n    try:\n        os.makedirs(args.candidate_cache_dir, exist_ok=True)\n    except OSError:\n        print(f\"Directory {args.candidate_cache_dir} cannot be created successfully.\")\n\n    task_paths = sorted(glob.glob(os.path.join(args.task_cache_dir, \"*.json\")))[\n        args.file_group * 10 : (args.file_group + 1) * 10\n    ]\n    print(f\"Selected models: {task_paths}\")\n    for num, task_path in enumerate(task_paths):\n        print(f\"Processing model {num} ...\")\n        with open(task_path, \"rb\") as file:\n            tasks = file.readlines()\n        model_name = task_path.split(\"/\")[-1][len(\"relay-\") :][: -len(\"_extracted_tasks.json\")]\n        os.makedirs(os.path.join(args.candidate_cache_dir, model_name), exist_ok=True)\n        for task_str in tqdm(tasks):\n            task_name, task_mod = json.loads(task_str)\n            task_mod = load_json(json.dumps(task_mod))\n            sample_candidates(task_mod, task_name, model_name)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/distributed_measure_candidates.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\n\nimport argparse\nimport glob\nimport os\n\nfrom tqdm import tqdm  # type: ignore\nfrom tvm import meta_schedule as ms\nfrom tvm.target import Target\n\n\ndef _parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--candidate_cache_dir\", type=str, help=\"Please provide the full path to the candidates.\"\n    )\n    parser.add_argument(\n        \"--result_cache_dir\", type=str, help=\"Please provide the full path to the result database.\"\n    )\n    parser.add_argument(\n        \"--target\",\n        type=str,\n        default=\"nvidia/nvidia-v100\",\n        help=\"Please specify the target hardware for tuning context.\",\n    )\n    parser.add_argument(\n        \"--rpc_host\", type=str, help=\"Please provide the private IPv4 address for the tracker.\"\n    )\n    parser.add_argument(\n        \"--rpc_port\", type=int, default=4445, help=\"Please provide the port for the tracker.\"\n    )\n    parser.add_argument(\n        \"--rpc_key\",\n        type=str,\n        default=\"p3.2xlarge\",\n        help=\"Please provide the key for the rpc servers.\",\n    )\n    parser.add_argument(\n        \"--builder_timeout_sec\",\n        type=int,\n        default=10,\n        help=\"The time for the builder session to time out.\",\n    )\n    parser.add_argument(\n        \"--min_repeat_ms\", type=int, default=100, help=\"The time for preheating the gpu.\"\n    )\n    parser.add_argument(\n        \"--runner_timeout_sec\",\n        type=int,\n        default=100,\n        help=\"The time for the runner session to time out.\",\n    )\n    parser.add_argument(\n        \"--cpu_flush\", type=bool, default=False, help=\"Whether to enable cpu cache flush or not.\"\n    )\n    parser.add_argument(\n        \"--batch_size\",\n        type=int,\n        default=128,\n        help=\"The batch size of candidates sent to builder and runner each time.\",\n    )\n    return parser.parse_args()\n\n\n# pylint: disable=too-many-locals\ndef measure_candidates(database, builder, runner):\n    \"\"\"Send the candidates to builder and runner for distributed measurement,\n    and save the results in a new json database.\n\n    Parameters\n    ----------\n    database : JSONDatabase\n        The database for candidates to be measured.\n    builder : Builder\n        The builder for building the candidates.\n    runner : Runner\n        The runner for measuring the candidates.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    candidates, runner_results, build_fail_indices, run_fail_indices = [], [], [], []\n    context = ms.TuneContext(target=Target(args.target))\n    tuning_records = database.get_all_tuning_records()\n    for record in tuning_records:\n        candidates.append(record.as_measure_candidate())\n    with ms.Profiler() as profiler:\n        for idx in range(0, len(candidates), args.batch_size):\n            batch_candidates = candidates[idx : idx + args.batch_size]\n            context._set_measure_candidates(batch_candidates)  # pylint: disable=protected-access\n            with ms.Profiler.timeit(\"build\"):\n                context._send_to_builder(builder)  # pylint: disable=protected-access\n            with ms.Profiler.timeit(\"run\"):\n                context._send_to_runner(runner)  # pylint: disable=protected-access\n                batch_runner_results = context._join()  # pylint: disable=protected-access\n            runner_results.extend(batch_runner_results)\n            for i, result in enumerate(context.builder_results):\n                if result.error_msg is None:\n                    ms.utils.remove_build_dir(result.artifact_path)\n                else:\n                    build_fail_indices.append(i + idx)\n            context._clear_measure_state()  # pylint: disable=protected-access\n\n    model_name, workload_name = database.path_workload.split(\"/\")[-2:]\n    record_name = database.path_tuning_record.split(\"/\")[-1]\n    new_database = ms.database.JSONDatabase(\n        path_workload=os.path.join(args.result_cache_dir, model_name, workload_name),\n        path_tuning_record=os.path.join(args.result_cache_dir, model_name, record_name),\n    )\n    workload = tuning_records[0].workload\n    new_database.commit_workload(workload.mod)\n    for i, (record, result) in enumerate(zip(tuning_records, runner_results)):\n        if result.error_msg is None:\n            new_database.commit_tuning_record(\n                ms.database.TuningRecord(\n                    trace=record.trace,\n                    workload=workload,\n                    run_secs=[v.value for v in result.run_secs],\n                    target=Target(args.target),\n                )\n            )\n        else:\n            run_fail_indices.append(i)\n    fail_indices_name = workload_name.replace(\"_workload.json\", \"_failed_indices.txt\")\n    with open(\n        os.path.join(args.result_cache_dir, model_name, fail_indices_name), \"w\", encoding=\"utf8\"\n    ) as file:\n        file.write(\" \".join([str(n) for n in run_fail_indices]))\n    print(\n        f\"Builder time: {profiler.get()['build']}, Runner time: {profiler.get()['run']}\\n\\\n            Failed number of builds: {len(build_fail_indices)},\\\n            Failed number of runs: {len(run_fail_indices)}\"\n    )\n\n\nargs = _parse_args()  # pylint: disable=invalid-name\n\n\ndef main():\n    builder = ms.builder.LocalBuilder(timeout_sec=args.builder_timeout_sec)\n    runner = ms.runner.RPCRunner(\n        rpc_config=ms.runner.RPCConfig(\n            tracker_host=args.rpc_host,\n            tracker_port=args.rpc_port,\n            tracker_key=args.rpc_key,\n            session_timeout_sec=args.runner_timeout_sec,\n        ),\n        evaluator_config=ms.runner.EvaluatorConfig(\n            number=3,\n            repeat=1,\n            min_repeat_ms=args.min_repeat_ms,\n            enable_cpu_cache_flush=args.cpu_flush,\n        ),\n        max_workers=os.cpu_count(),\n    )\n    if not os.path.isdir(args.candidate_cache_dir):\n        raise Exception(\"Please provide a correct candidate cache dir.\")\n    try:\n        os.makedirs(args.result_cache_dir, exist_ok=True)\n    except OSError:\n        print(f\"Directory {args.result_cache_dir} cannot be created successfully.\")\n    model_dirs = glob.glob(os.path.join(args.candidate_cache_dir, \"*\"))\n    for model_dir in model_dirs:\n        model_name = model_dir.split(\"/\")[-1]\n        os.makedirs(os.path.join(args.result_cache_dir, model_name), exist_ok=True)\n        all_tasks = glob.glob(os.path.join(model_dir, \"*.json\"))\n        workload_paths = []\n        for path in all_tasks:\n            if path.endswith(\"_workload.json\"):\n                workload_paths.append(path)\n        for workload_path in tqdm(workload_paths):\n            candidate_path = workload_path.replace(\"_workload.json\", \"_candidates.json\")\n            database = ms.database.JSONDatabase(\n                path_workload=workload_path,\n                path_tuning_record=candidate_path,\n            )\n            measure_candidates(database, builder, runner)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/dummy_object.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Dummy objects for testing.\"\"\"\nimport random\nfrom typing import List, Optional\n\nfrom tvm.tir.schedule import Trace\n\nfrom ..builder import BuilderInput, BuilderResult, PyBuilder\nfrom ..mutator import PyMutator\nfrom ..runner import PyRunner, PyRunnerFuture, RunnerFuture, RunnerInput, RunnerResult\nfrom ..tune_context import TuneContext  # pylint: disable=unused-import\nfrom ..utils import derived_object\n\n\n@derived_object\nclass DummyRunnerFuture(PyRunnerFuture):\n    def done(self) -> bool:\n        return True\n\n    def result(self) -> RunnerResult:\n        run_secs = [random.uniform(5, 30) for _ in range(random.randint(1, 10))]\n        return RunnerResult(run_secs, None)\n\n\n@derived_object\nclass DummyBuilder(PyBuilder):\n    def build(self, build_inputs: List[BuilderInput]) -> List[BuilderResult]:\n        return [BuilderResult(\"test_path\", None) for _ in build_inputs]\n\n\n@derived_object\nclass DummyRunner(PyRunner):\n    def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n        return [DummyRunnerFuture() for _ in runner_inputs]  # type: ignore\n\n\n@derived_object\nclass DummyMutator(PyMutator):\n    \"\"\"Dummy Mutator for testing\"\"\"\n\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        pass\n\n    def apply(self, trace: Trace, _) -> Optional[Trace]:\n        return Trace(trace.insts, {})\n\n    def clone(self):\n        return DummyMutator()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/local_rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC tracker and server running locally\"\"\"\nfrom tvm.rpc.tracker import Tracker\nfrom tvm.rpc.server import Server\n\n\nclass LocalRPC:\n    \"\"\"A pair of RPC tracker/server running locally\n\n    Parameters\n    ----------\n    tracker_host : str\n        The host URL of the tracker\n    tracker_port : int\n        The port of the tracker\n    tracker_key: str\n        The key used in the tracker to refer to a worker\n    \"\"\"\n\n    tracker_host: str\n    tracker_port: int\n    tracker_key: str\n\n    def __init__(\n        self,\n        tracker_key: str = \"key\",\n        silent: bool = False,\n        no_fork: bool = False,\n    ) -> None:\n        self.tracker = Tracker(\n            silent=silent,\n            port=9190,\n            port_end=12345,\n        )\n        self.server = Server(\n            host=\"0.0.0.0\",\n            is_proxy=False,\n            tracker_addr=(self.tracker.host, self.tracker.port),\n            key=tracker_key,\n            silent=silent,\n            no_fork=no_fork,\n            port=9190,\n            port_end=12345,\n        )\n        self.tracker_host = self.tracker.host\n        self.tracker_port = self.tracker.port\n        self.tracker_key = tracker_key\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, _type, _value, _traceback):\n        if hasattr(self, \"server\"):\n            del self.server\n        if hasattr(self, \"tracker\"):\n            del self.tracker\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/relay_workload.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Workloads in Relay IR\"\"\"\n# pylint: disable=import-outside-toplevel\nimport logging\nimport multiprocessing\nimport os\nimport pickle\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport tvm\nimport tvm.relay.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.ir import IRModule\nfrom tvm.runtime import NDArray, load_param_dict, save_param_dict\nfrom tvm.target import Target\n\nlogger = logging.getLogger(__name__)  # pylint: disable=invalid-name\n\n\ndef _get_network(\n    args: Tuple[str, List[int], Optional[str]]\n) -> Tuple[IRModule, bytearray, Tuple[str, List[int], str]]:\n    name: str\n    input_shape: List[int]\n    layout: Optional[str]\n    name, input_shape, layout = args\n\n    if layout == \"None\":\n        layout = None\n\n    mod: IRModule\n    if name in [\n        \"resnet_18\",\n        \"resnet_50\",\n        \"wide_resnet_50\",\n        \"resnext_50\",\n        \"mobilenet_v2\",\n        \"mobilenet_v3\",\n        \"inception_v3\",\n        \"densenet_121\",\n        \"resnet3d_18\",\n        \"vgg_16\",\n    ]:\n        import torch  # type: ignore\n        from torchvision import models  # type: ignore\n\n        assert layout is None or layout in [\"NCHW\", \"NHWC\"]\n\n        params: Dict[str, Any] = {}\n        if name in [\"resnet_18\", \"resnet_50\"]:\n            model = getattr(models, name.replace(\"_\", \"\"))\n        elif name == \"wide_resnet_50\":\n            model = getattr(models, \"wide_resnet50_2\")\n        elif name == \"resnext_50\":\n            model = getattr(models, \"resnext50_32x4d\")\n        elif name == \"mobilenet_v2\":\n            model = getattr(models, name)\n        elif name == \"mobilenet_v3\":\n            model = getattr(models, name + \"_large\")\n        elif name == \"inception_v3\":\n            model = getattr(models, name)\n            params[\"aux_logits\"] = False\n        elif name == \"densenet_121\":\n            model = getattr(models, name.replace(\"_\", \"\"))\n        elif name == \"resnet3d_18\":\n            model = models.video.r3d_18\n        elif name == \"vgg_16\":\n            model = getattr(models, name.replace(\"_\", \"\"))\n        try:\n            model = model(**params, weights=None)\n        except TypeError:\n            model = model(**params, pretrained=False)\n\n        dtype = \"float32\"\n        input_data = torch.randn(input_shape).type(  # pylint: disable=no-member\n            {\n                \"float32\": torch.float32,  # pylint: disable=no-member\n            }[dtype]\n        )\n        scripted_model = torch.jit.trace(model, input_data).eval()  # type: ignore\n        input_name = \"input0\"\n        shape_list = [(input_name, input_shape)]\n        mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n        passes = [relay.transform.RemoveUnusedFunctions()]\n        if layout is None or layout == \"NHWC\":\n            # PyTorch is imported as NCHW by default\n            passes.append(\n                relay.transform.ConvertLayout(\n                    {\n                        \"nn.conv2d\": [\"NHWC\", \"default\"],\n                        \"nn.conv3d\": [\"NDHWC\", \"default\"],\n                        \"nn.max_pool2d\": [\"NHWC\", \"default\"],\n                        \"nn.avg_pool2d\": [\"NHWC\", \"default\"],\n                    }\n                )\n            )\n        with tvm.transform.PassContext(opt_level=3):\n            mod = tvm.transform.Sequential(passes)(mod)\n        inputs = (input_name, input_shape, dtype)\n    elif name in [\"bert_tiny\", \"bert_base\", \"bert_medium\", \"bert_large\"]:\n        os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n        # pip3 install transformers==3.5 torch==1.7\n        import torch  # type: ignore\n        import transformers  # type: ignore\n\n        assert layout is None\n\n        config_dict = {\n            \"bert_tiny\": transformers.BertConfig(\n                num_hidden_layers=6,\n                hidden_size=512,\n                intermediate_size=2048,\n                num_attention_heads=8,\n                return_dict=False,\n            ),\n            \"bert_base\": transformers.BertConfig(\n                num_hidden_layers=12,\n                hidden_size=768,\n                intermediate_size=3072,\n                num_attention_heads=12,\n                return_dict=False,\n            ),\n            \"bert_medium\": transformers.BertConfig(\n                num_hidden_layers=12,\n                hidden_size=1024,\n                intermediate_size=4096,\n                num_attention_heads=16,\n                return_dict=False,\n            ),\n            \"bert_large\": transformers.BertConfig(\n                num_hidden_layers=24,\n                hidden_size=1024,\n                intermediate_size=4096,\n                num_attention_heads=16,\n                return_dict=False,\n            ),\n        }\n        configuration = config_dict[name]\n        model = transformers.BertModel(configuration)\n        input_name = \"input_ids\"\n        input_dtype = \"int64\"\n        a = torch.randint(10000, input_shape)  # pylint: disable=no-member\n        model.eval()\n        scripted_model = torch.jit.trace(model, [a], strict=False)  # type: ignore\n        input_name = \"input_ids\"\n        shape_list = [(input_name, input_shape)]\n        mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n        mod = relay.transform.FastMath()(mod)\n        mod = relay.transform.CombineParallelBatchMatmul()(mod)\n        inputs = (input_name, input_shape, input_dtype)\n    elif name == \"dcgan\":\n        assert layout is None\n\n        output_shape = input_shape\n        batch_size = output_shape[0]\n        oshape = output_shape[1:]\n        mod, params = relay.testing.dcgan.get_workload(\n            batch_size=batch_size,\n            oshape=oshape,\n            layout=\"NHWC\",\n        )\n        inputs = (\"data\", [100], \"float32\")\n    else:\n        raise ValueError(\"Invalid name: \" + name)\n\n    params_bytearray: bytearray = save_param_dict(params)\n    return mod, params_bytearray, inputs\n\n\ndef _load_cache(cache_dir: Optional[str], filename: str) -> Optional[List[Any]]:\n    if cache_dir is None:\n        return None\n    path = os.path.join(os.path.expanduser(cache_dir), filename)\n    if not os.path.exists(path):\n        return None\n    logger.info(\"Loaded from cached: %s\", path)\n    with open(path, \"rb\") as i_f:\n        return pickle.load(i_f)\n\n\ndef _save_cache(cache_dir: Optional[str], filename: str, objects: List[Any]) -> None:\n    if cache_dir is None:\n        return\n    path = os.path.join(os.path.expanduser(cache_dir), filename)\n    with open(path, \"wb\") as o_f:\n        pickle.dump(objects, o_f)\n\n\ndef get_network(\n    name: str,\n    input_shape: List[int],\n    *,\n    layout: Optional[str] = None,\n    cache_dir: Optional[str] = None,\n) -> Tuple[IRModule, Dict[str, NDArray], Tuple[str, List[int], str]]:\n    \"\"\"Get the symbol definition and random weight of a network\n\n    Parameters\n    ----------\n    name : str\n        The name of the network.\n    input_shape : List[int]\n        The shape of the input tensor.\n    layout : Optional[str]\n        The layout of the input tensor. For vision models, the layout is by default NHWC.\n    cache_dir : Optional[str], optional\n        The directory to cache the generated network.\n        If not specified, the cache will be disabled.\n\n    Returns\n    -------\n    mod : IRModule\n        The IRModule representing the network.\n    params : Dict[str, NDArray]\n        The parameters of the networks.\n    inputs : Tuple[str, List[int], str]\n        The name, shape and dtype of the input tensor.\n    \"\"\"\n    mod: IRModule\n    params: Dict[str, NDArray]\n    inputs: Tuple[str, List[int], str]\n    params_bytearray: bytearray\n\n    filename = f'relay-{name}-{layout}-{\",\".join(str(i) for i in input_shape)}.json'\n    cached = _load_cache(cache_dir, filename)\n    if cached is None:\n        with multiprocessing.Pool(processes=1) as pool:\n            result = pool.map(_get_network, [(name, input_shape, layout)])\n        ((mod, params_bytearray, inputs),) = result\n        cached = [mod, params_bytearray, inputs]\n        _save_cache(cache_dir, filename, cached)\n    mod, params_bytearray, inputs = cached\n    params = load_param_dict(params_bytearray)\n    return mod, params, inputs\n\n\ndef extract_from_relay(\n    mod: IRModule,\n    target: Target,\n    params: Optional[Dict[str, NDArray]],\n    name: str,\n    input_shape: List[int],\n    *,\n    cache_dir: Optional[str] = None,\n) -> List[ms.ExtractedTask]:\n    \"\"\"Extract the tasks from a network.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The IRModule representing the network.\n    target : Target\n        The target that the network will be deployed to.\n    params : Optional[Dict[str, NDArray]]\n        The parameters of the networks.\n    name : str\n        The name of the network.\n    input_shape : List[int]\n        The shape of the input tensor.\n    cache_dir : Optional[str]\n        The directory to cache the generated network.\n        If not specified, the cache will be disabled.\n\n    Returns\n    -------\n    extracted_tasks : List[ExtractedTask]\n        The extracted tasks.\n    \"\"\"\n    filename = f'tasks-{target.kind.name}-{name}-{\",\".join(str(i) for i in input_shape)}.json'\n    extracted_tasks = _load_cache(cache_dir, filename)\n    if extracted_tasks is None:\n        extracted_tasks = ms.relay_integration.extract_tasks(\n            mod=mod,\n            target=target,\n            params=params,\n        )\n        extracted_tasks = list(extracted_tasks)\n        _save_cache(cache_dir, filename, extracted_tasks)\n    return extracted_tasks\n\n\nSUPPORTED = [\n    # TorchVision\n    \"resnet_18\",\n    \"resnet_50\",\n    \"mobilenet_v2\",\n    \"mobilenet_v3\",\n    \"wide_resnet_50\",\n    \"resnext_50\",\n    \"resnet3d_18\",\n    \"inception_v3\",\n    \"densenet_121\",\n    \"vgg_16\",\n    # Transformer\n    \"bert_tiny\",\n    \"bert_base\",\n    \"bert_medium\",\n    \"bert_large\",\n    # Relay testing\n    \"dcgan\",\n]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/space_generation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom typing import List, Optional, Tuple, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm import meta_schedule as ms\nfrom tvm.ir import IRModule, structural_equal\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\nfrom tvm.tir.schedule import Trace\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n\ndef get_rules(\n    kind: Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"],\n    types: Union[type, Tuple[type, ...]],\n) -> List[ms.ScheduleRule]:\n    \"\"\"Get default schedule rules\"\"\"\n    rules = ms.ScheduleRule.create(kind)\n    return [rule for rule in rules if isinstance(rule, types)]\n\n\ndef generate_design_space(\n    kind: Literal[\"llvm\", \"cuda\", \"cuda-tensorcore\", \"hexagon\"],\n    mod: IRModule,\n    target: Target,\n    types: Union[type, Tuple[type, ...]],\n    sch_rules: Optional[List[ms.ScheduleRule]] = None,\n) -> List[Schedule]:\n    if sch_rules is None:\n        sch_rules = get_rules(kind, types)\n    else:\n        assert types is None\n    return ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=sch_rules,\n            postprocs=[],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    ).generate_design_space()\n\n\ndef _find_match_sketch_id(\n    mod: IRModule,\n    sketches: List[Schedule],\n    expected_mod: IRModule,\n    expected_decision: List[Tuple[str, List[int]]],\n    *,\n    debug_mask=\"all\",\n) -> Optional[int]:\n    for sketch_id, sketch in enumerate(sketches):\n        i = 0\n        new_decisions = {}\n        for inst in sketch.trace.insts:\n            if not inst.kind.name.startswith(\"Sample\"):\n                continue\n            assert i < len(expected_decision)\n            if inst.kind.name == expected_decision[i][0]:\n                new_decisions[inst] = expected_decision[i][1]\n                i += 1\n        if len(new_decisions) != len(expected_decision):\n            continue\n        sch = Schedule(mod, debug_mask=debug_mask)\n        Trace(\n            insts=sketch.trace.insts,\n            decisions=new_decisions,\n        ).apply_to_schedule(sch, remove_postproc=True)\n        if structural_equal(sch.mod, expected_mod):\n            verify_trace_roundtrip(sch=sch, mod=mod, debug_mask=debug_mask)\n            return sketch_id\n    return None\n\n\ndef check_sketches(\n    mod: IRModule,\n    sketches: List[Schedule],\n    expected_mods: List[IRModule],\n    expected_decisions: List[List[Tuple[str, List[int]]]],\n    *,\n    debug_mask=\"all\",\n):\n    assert len(expected_mods) == len(expected_decisions)\n    assert len(sketches) == len(expected_mods)\n    expected_mods = [\n        IRModule({\"main\": m}) if not isinstance(m, IRModule) else m for m in expected_mods\n    ]\n    sketches = list(sketches)\n    for expected_id, (expected_mod, expected_decision) in enumerate(\n        zip(expected_mods, expected_decisions)\n    ):\n        sketch_id = _find_match_sketch_id(\n            mod,\n            sketches,\n            expected_mod,\n            expected_decision,\n            debug_mask=debug_mask,\n        )\n        if sketch_id is None:\n            raise AssertionError(\n                f\"Expected sketch #{expected_id} doesn't exist in the generated sketches.\"\n            )\n        sketches.pop(sketch_id)\n\n\ndef print_sketches(sketches: List[Schedule]):\n    for i, sch in enumerate(sketches):\n        print(f\"###### {i}\")\n        sch.mod.show()\n        for inst in sch.trace.insts:\n            if inst in sch.trace.decisions:\n                print(f'(\"{inst.kind.name}\", {sch.trace.decisions[inst]}),')\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/te_workload.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Workloads in TE\"\"\"\n# pylint: disable=missing-docstring\nfrom typing import Tuple\n\nfrom tvm import te, tir, topi\nfrom tvm.target import Target\n\n\ndef batch_matmul_nkkm(  # pylint: disable=invalid-name,missing-docstring\n    B: int,\n    N: int,\n    M: int,\n    K: int,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    x = te.placeholder((B, N, K), name=\"X\", dtype=in_dtype)\n    y = te.placeholder((B, K, M), name=\"Y\", dtype=in_dtype)\n    k = te.reduce_axis((0, K), name=\"k\")\n    z = te.compute(  # pylint: disable=invalid-name\n        (B, N, M),\n        lambda b, i, j: te.sum(\n            x[b][i][k].astype(out_dtype) * y[b][k][j].astype(out_dtype),\n            axis=[k],\n        ),\n        name=\"Z\",\n    )\n    return (x, y, z)\n\n\ndef conv1d_nlc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    L: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    dilation: int = 1,\n    groups: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder((N, L, CI), name=\"inputs\", dtype=in_dtype)\n    weight = te.placeholder((kernel_size, CI // groups, CO), name=\"weight\", dtype=in_dtype)\n\n    batch_size, in_len, _ = inputs.shape\n    k_len, channel_per_group, out_channel = weight.shape\n    out_channel_per_group = out_channel // groups\n    out_len = (in_len + 2 * padding - dilation * (k_len - 1) - 1) // stride + 1\n    rc = te.reduce_axis((0, channel_per_group), name=\"rc\")\n    rl = te.reduce_axis((0, k_len), name=\"rl\")\n\n    padded = topi.nn.pad(inputs, [0, padding, 0])\n    output = te.compute(\n        (batch_size, out_len, out_channel),\n        lambda n, l, co: te.sum(\n            (\n                padded[\n                    n,\n                    l * stride + rl * dilation,\n                    co // out_channel_per_group * channel_per_group + rc,\n                ].astype(out_dtype)\n                * weight[rl, rc, co].astype(out_dtype)\n            ),\n            axis=[rl, rc],\n        ),\n        name=\"conv1d_nlc\",\n    )\n    return (inputs, weight, output)\n\n\ndef conv2d_nhwc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    dilation: int = 1,\n    groups: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder((N, H, W, CI), name=\"inputs\", dtype=in_dtype)\n    weight = te.placeholder(\n        (kernel_size, kernel_size, CI // groups, CO), name=\"weight\", dtype=in_dtype\n    )\n    batch_size, in_h, in_w, _ = inputs.shape\n    k_h, k_w, channel_per_group, out_channel = weight.shape\n    out_channel_per_group = out_channel // groups\n\n    out_h = (in_h + 2 * padding - dilation * (k_h - 1) - 1) // stride + 1\n    out_w = (in_w + 2 * padding - dilation * (k_w - 1) - 1) // stride + 1\n    rh = te.reduce_axis((0, k_h), name=\"rh\")\n    rw = te.reduce_axis((0, k_w), name=\"rw\")\n    rc = te.reduce_axis((0, channel_per_group), name=\"rc\")\n\n    padded = topi.nn.pad(inputs, [0, padding, padding, 0])\n    output = te.compute(\n        (batch_size, out_h, out_w, out_channel),\n        lambda n, h, w, co: te.sum(\n            (\n                padded[\n                    n,\n                    h * stride + rh * dilation,\n                    w * stride + rw * dilation,\n                    co // out_channel_per_group * channel_per_group + rc,\n                ].astype(out_dtype)\n                * weight[rh, rw, rc, co].astype(out_dtype)\n            ),\n            axis=[rh, rw, rc],\n        ),\n        name=\"conv2d_nhwc\",\n    )\n    return (inputs, weight, output)\n\n\ndef conv3d_ndhwc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    D: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    dilation: int = 1,\n    groups: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder((N, D, H, W, CI), name=\"inputs\", dtype=in_dtype)\n    weight = te.placeholder(\n        (kernel_size, kernel_size, kernel_size, CI // groups, CO), name=\"weight\", dtype=in_dtype\n    )\n    batch_size, in_d, in_h, in_w, _ = inputs.shape\n    k_d, k_h, k_w, channel_per_group, out_channel = weight.shape\n    out_channel_per_group = out_channel // groups\n\n    out_d = (in_d + 2 * padding - dilation * (k_d - 1) - 1) // stride + 1\n    out_h = (in_h + 2 * padding - dilation * (k_h - 1) - 1) // stride + 1\n    out_w = (in_w + 2 * padding - dilation * (k_w - 1) - 1) // stride + 1\n    rd = te.reduce_axis((0, k_d), name=\"rd\")\n    rh = te.reduce_axis((0, k_h), name=\"rh\")\n    rw = te.reduce_axis((0, k_w), name=\"rw\")\n    rc = te.reduce_axis((0, channel_per_group), name=\"rc\")\n\n    padded = topi.nn.pad(inputs, [0, padding, padding, padding, 0])\n    output = te.compute(\n        (batch_size, out_d, out_h, out_w, out_channel),\n        lambda n, d, h, w, co: te.sum(\n            (\n                padded[\n                    n,\n                    d * stride + rd * dilation,\n                    h * stride + rh * dilation,\n                    w * stride + rw * dilation,\n                    co // out_channel_per_group * channel_per_group + rc,\n                ].astype(out_dtype)\n                * weight[rd, rh, rw, rc, co].astype(out_dtype)\n            ),\n            axis=[rd, rh, rw, rc],\n        ),\n        name=\"conv3d_ndhwc\",\n    )\n    return (inputs, weight, output)\n\n\ndef depthwise_conv2d_nhwc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    C: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    dilation: int = 1,\n    factor: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder((N, H, W, C), dtype=in_dtype)\n    weight = te.placeholder((factor, kernel_size, kernel_size, C), dtype=in_dtype)\n    batch_size, in_h, in_w, in_channel = inputs.shape\n    factor, k_h, k_w, in_channel = weight.shape\n    out_channel = in_channel * factor\n    assert int(factor) == 1, \"Not optimized for factor != 1\"\n    out_h = (in_h + 2 * padding - dilation * (k_h - 1) - 1) // stride + 1\n    out_w = (in_w + 2 * padding - dilation * (k_w - 1) - 1) // stride + 1\n    rh = te.reduce_axis((0, k_h), name=\"rh\")\n    rw = te.reduce_axis((0, k_w), name=\"rw\")\n    padded = topi.nn.pad(inputs, [0, padding, padding, 0])\n    output = te.compute(\n        (batch_size, out_h, out_w, out_channel),\n        lambda n, h, w, c: te.sum(\n            (\n                padded[\n                    n,\n                    h * stride + rh * dilation,\n                    w * stride + rw * dilation,\n                    c // factor,\n                ].astype(out_dtype)\n                * weight[c % factor, rh, rw, c // factor].astype(out_dtype)\n            ),\n            axis=[rh, rw],\n        ),\n        name=\"depth_conv2d_nhwc\",\n    )\n    return (inputs, weight, output)\n\n\ndef conv2d_transpose_nhwc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder((N, H, W, CI), name=\"inputs\", dtype=in_dtype)\n    weight = te.placeholder((kernel_size, kernel_size, CI, CO), name=\"weight\", dtype=in_dtype)\n\n    batch, in_h, in_w, in_c = inputs.shape\n    filter_h, filter_w, in_c, out_c = weight.shape\n    stride_h, stride_w = (stride, stride)\n\n    # compute padding\n    fpad_top, fpad_left, fpad_bottom, fpad_right = topi.nn.get_pad_tuple(\n        padding, (filter_h, filter_w)\n    )\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right\n\n    # padding stage\n    padded = topi.nn.pad(\n        inputs,\n        [\n            0,\n            (bpad_top + stride_h - 1) // stride_h,\n            (bpad_left + stride_w - 1) // stride_w,\n            0,\n        ],\n        [\n            0,\n            (bpad_bottom + stride_h - 1) // stride_h,\n            (bpad_right + stride_w - 1) // stride_w,\n            0,\n        ],\n    )\n\n    # remove extra padding introduced by dilatation\n    idx_div = te.indexdiv\n    idx_mod = te.indexmod\n    border_h = idx_mod(stride_h - idx_mod(bpad_top, stride_h), stride_h)\n    border_w = idx_mod(stride_w - idx_mod(bpad_left, stride_w), stride_w)\n\n    # dilation stage\n    strides = [1, stride_h, stride_w, 1]\n    n = len(padded.shape)\n\n    # We should embed this dilation directly into te.compute rather than creating a new te.compute.\n    # Only in this way can we use unroll to eliminate the multiplication of zeros.\n    def _dilate(*indices):\n        not_zero = []\n        index_tuple = []\n        for i in range(n):\n            if not strides[i] == 1:\n                index_tuple.append(idx_div(indices[i], strides[i]))\n                not_zero.append(idx_mod(indices[i], strides[i]).equal(0))\n            else:\n                index_tuple.append(indices[i])\n        if not_zero:\n            not_zero = te.all(*not_zero)\n            return te.if_then_else(not_zero, padded(*index_tuple), tir.const(0.0, padded.dtype))\n        return padded(*index_tuple)\n\n    # convolution stage\n    out_h = (in_h - 1) * stride_h - fpad_top - fpad_bottom + filter_h\n    out_w = (in_w - 1) * stride_w - fpad_left - fpad_right + filter_w\n    rc = te.reduce_axis((0, in_c), name=\"rc\")\n    rh = te.reduce_axis((0, filter_h), name=\"rh\")\n    rw = te.reduce_axis((0, filter_w), name=\"rw\")\n\n    output = te.compute(\n        (batch, out_h, out_w, out_c),\n        lambda n, h, w, co: te.sum(\n            _dilate(n, h + rh + border_h, w + rw + border_w, rc).astype(out_dtype)\n            * weight[filter_h - 1 - rh, filter_w - 1 - rw, rc, co].astype(out_dtype),\n            axis=[rh, rw, rc],\n        ),\n        name=\"conv2d_transpose_nhwc\",\n    )\n    return (inputs, weight, output)\n\n\ndef conv2d_capsule_nhwijc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    capsule_size: int = 4,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    inputs = te.placeholder(\n        (N, H, W, capsule_size, capsule_size, CI), name=\"inputs\", dtype=in_dtype\n    )\n    weight = te.placeholder(\n        (kernel_size, kernel_size, capsule_size, capsule_size, CI, CO),\n        name=\"weight\",\n        dtype=in_dtype,\n    )\n    batch_size, in_h, in_w, _, _, in_channel = inputs.shape\n    k_h, k_w, _, _, _, out_channel = weight.shape\n\n    out_h = (in_h + 2 * padding - kernel_size) // stride + 1\n    out_w = (in_w + 2 * padding - kernel_size) // stride + 1\n\n    rh = te.reduce_axis((0, k_h), name=\"rh\")\n    rw = te.reduce_axis((0, k_w), name=\"rw\")\n    cap_k = te.reduce_axis((0, capsule_size), name=\"cap_k\")\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n\n    padded = topi.nn.pad(inputs, [0, padding, padding, 0, 0, 0])\n    output = te.compute(\n        (batch_size, out_h, out_w, capsule_size, capsule_size, out_channel),\n        lambda n, h, w, cap_i, cap_j, co: te.sum(\n            (\n                padded[n, h * stride + rh, w * stride + rw, cap_i, cap_k, rc].astype(out_dtype)\n                * weight[rh, rw, cap_k, cap_j, rc, co].astype(out_dtype)\n            ),\n            axis=[rh, rw, cap_k, rc],\n        ),\n        name=\"conv2d_capsule_nhwijc\",\n    )\n    return (inputs, weight, output)\n\n\ndef norm_bmn(  # pylint: disable=invalid-name,missing-docstring\n    B: int,\n    M: int,\n    N: int,\n) -> Tuple[te.Tensor, te.Tensor]:\n    a = te.placeholder((B, M, N), name=\"A\")\n    i = te.reduce_axis((0, M), name=\"i\")\n    j = te.reduce_axis((0, N), name=\"j\")\n    c = te.compute(\n        (B,),\n        lambda b: te.sum(a[b][i][j] * a[b][i][j], axis=[i, j]),\n        name=\"C\",\n    )\n    d = te.compute((B,), lambda b: te.sqrt(c[b]), name=\"D\")\n    return (a, d)\n\n\ndef conv2d_nhwc_without_layout_rewrite(  # pylint: disable=invalid-name\n    Input: te.Tensor,\n    Filter: te.Tensor,\n    stride: int,\n    padding: int,\n    dilation: int,\n    out_dtype=\"float32\",\n):\n    \"\"\"A copy of `topi.nn.conv2d_nhwc` but without the 'layout_free` attribute.\n    We use this in single op and subgraph evaluation\n    because we don't want to introduce graph level optimization.\n    \"\"\"\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_height, in_width, in_channel = Input.shape  # type: ignore\n    kernel_h, kernel_w, _channel, num_filter = Filter.shape  # type: ignore\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = topi.nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = num_filter\n    out_height = topi.utils.simplify(\n        (in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1\n    )\n    out_width = topi.utils.simplify(\n        (in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1\n    )\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    PaddedInput = topi.nn.pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    Output = te.compute(\n        (batch, out_height, out_width, out_channel),\n        lambda nn, yy, xx, ff: te.sum(\n            PaddedInput[\n                nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rc\n            ].astype(out_dtype)\n            * Filter[ry, rx, rc, ff].astype(out_dtype),  # type: ignore\n            axis=[ry, rx, rc],\n        ),\n        name=\"Conv2dOutput\",\n        tag=\"conv2d_nhwc\",\n    )\n    return Output\n\n\ndef conv2d_nhwc_bn_relu(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    strides: int,\n    padding: int,\n    dilation: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor, te.Tensor, te.Tensor, te.Tensor]:\n    data = te.placeholder((N, H, W, CI), name=\"data\", dtype=in_dtype)\n    kernel = te.placeholder((kernel_size, kernel_size, CI, CO), name=\"kernel\", dtype=in_dtype)\n    bias = te.placeholder((CO,), name=\"bias\")\n    bn_scale = te.placeholder((CO,), name=\"bn_scale\")\n    bn_offset = te.placeholder((CO,), name=\"bn_offset\")\n    OH = (H + 2 * padding - (kernel_size - 1) * dilation - 1) // strides + 1\n    OW = (W + 2 * padding - (kernel_size - 1) * dilation - 1) // strides + 1\n    conv = conv2d_nhwc_without_layout_rewrite(data, kernel, strides, padding, dilation, out_dtype)\n    conv = te.compute(\n        (N, OH, OW, CO), lambda i, j, k, l: conv[i, j, k, l] + bias[l], name=\"bias_add\"\n    )\n    conv = te.compute(\n        (N, OH, OW, CO), lambda i, j, k, l: conv[i, j, k, l] * bn_scale[l], name=\"bn_mul\"\n    )\n    conv = te.compute(\n        (N, OH, OW, CO), lambda i, j, k, l: conv[i, j, k, l] + bn_offset[l], name=\"bn_add\"\n    )\n    out = topi.nn.relu(conv)\n    return (data, kernel, bias, bn_offset, bn_scale, out)\n\n\ndef transpose_batch_matmul(  # pylint: disable=invalid-name,missing-docstring\n    batch: int,\n    seq_len: int,\n    n_head: int,\n    n_dim: int,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    query = te.placeholder((batch, seq_len, n_head, n_dim), name=\"query\", dtype=in_dtype)\n    value = te.placeholder((batch, seq_len, n_head, n_dim), name=\"value\", dtype=in_dtype)\n    query_T = te.compute(\n        (batch, n_head, seq_len, n_dim),\n        lambda b, h, l, d: query[b, l, h, d],\n        name=\"query_T\",\n    )\n    value_T = te.compute(\n        (batch, n_head, n_dim, seq_len),\n        lambda b, h, d, l: value[b, l, h, d],\n        name=\"value_T\",\n    )\n    k = te.reduce_axis((0, n_dim), name=\"k\")\n    out = te.compute(\n        (batch, n_head, seq_len, seq_len),\n        lambda b, h, i, j: te.sum(\n            query_T[b, h, i, k].astype(out_dtype) * value_T[b, h, k, j].astype(out_dtype), axis=[k]\n        ),\n        name=\"C\",\n    )\n    return (query, value, out)\n\n\ndef conv2d_winograd_nhwc(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 0,\n    dilation: int = 1,\n    tile_size: int = 4,\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    from tvm.topi.nn.conv2d import (  # pylint: disable=import-outside-toplevel\n        _conv2d_winograd_nhwc_impl,\n    )\n\n    target = Target.current(allow_none=True)\n    if target is not None and target.kind.name == \"cuda\":\n        write_cache_level = 3\n    else:\n        write_cache_level = 2\n    data = te.placeholder((N, H, W, CI), \"float32\", name=\"data\")\n    weight = te.placeholder((kernel_size, kernel_size, CO, CI), \"float32\", name=\"weight\")\n    out = _conv2d_winograd_nhwc_impl(\n        data,\n        weight,\n        stride,\n        padding,\n        dilation,\n        \"float32\",\n        pre_computed=True,\n        auto_scheduler_rewritten_layout=\"\",\n        meta_schedule_original_shape=None,\n        tile_size=tile_size,\n        write_cache_level=write_cache_level,\n    )\n    return (data, weight, out)\n\n\ndef conv2d_winograd_nchw(  # pylint: disable=invalid-name,missing-docstring\n    N: int,\n    H: int,\n    W: int,\n    CI: int,\n    CO: int,\n    kernel_size: int,\n    stride: int = 1,\n    padding: int = 1,\n    dilation: int = 1,\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    from tvm.topi.cuda.conv2d_winograd import (  # pylint: disable=import-outside-toplevel\n        _infer_tile_size,\n    )\n    from tvm.topi.nn.conv2d import (  # pylint: disable=import-outside-toplevel\n        _conv2d_winograd_nchw_impl,\n    )\n\n    data = te.placeholder((N, CI, H, W), \"float32\", name=\"data\")\n    weight = te.placeholder((kernel_size, kernel_size, CI, CO), \"float32\", name=\"weight\")\n    out = _conv2d_winograd_nchw_impl(\n        data,\n        weight,\n        stride,\n        padding,\n        dilation,\n        \"float32\",\n        pre_computed=True,\n        auto_scheduler_rewritten_layout=\"\",\n        meta_schedule_original_shape=None,\n        tile_size=_infer_tile_size(data, weight),\n    )\n    return (data, weight, out)\n\n\ndef matmul(\n    n: int, m: int, k: int, in_dtype: str = \"float32\", out_dtype: str = \"float32\"\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    a = te.placeholder((n, k), name=\"A\", dtype=in_dtype)\n    b = te.placeholder((k, m), name=\"B\", dtype=in_dtype)\n    k = te.reduce_axis((0, k), name=\"k\")\n    c = te.compute(\n        (n, m),\n        lambda i, j: te.sum(a[i, k].astype(out_dtype) * b[k, j].astype(out_dtype), axis=[k]),\n        name=\"C\",\n    )\n    return (a, b, c)\n\n\ndef matmul_relu(\n    n: int, m: int, k: int, in_dtype: str = \"float32\", out_dtype: str = \"float32\"\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    a = te.placeholder((n, k), name=\"A\", dtype=in_dtype)\n    b = te.placeholder((k, m), name=\"B\", dtype=in_dtype)\n    k = te.reduce_axis((0, k), name=\"k\")\n    c = te.compute(\n        (n, m),\n        lambda i, j: te.sum(a[i, k].astype(out_dtype) * b[k, j].astype(out_dtype), axis=[k]),\n        name=\"C\",\n    )\n    d = topi.nn.relu(c)  # pylint: disable=invalid-name\n    return (a, b, d)\n\n\ndef conv2d_nchw(  # pylint: disable=invalid-name\n    n: int,\n    h: int,\n    w: int,\n    ci: int,\n    co: int,\n    kh: int,\n    kw: int,\n    stride: int,\n    padding: int,\n    dilation: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor]:\n    x = te.placeholder((n, ci, h, w), name=\"X\", dtype=in_dtype)\n    w = te.placeholder((co, ci, kh, kw), name=\"W\", dtype=in_dtype)\n    y = topi.nn.conv2d_nchw(\n        Input=x, Filter=w, stride=stride, padding=padding, dilation=dilation, out_dtype=out_dtype\n    )\n    return (x, w, y)\n\n\ndef conv2d_nchw_bias_bn_relu(  # pylint: disable=invalid-name\n    n: int,\n    h: int,\n    w: int,\n    ci: int,\n    co: int,\n    kh: int,\n    kw: int,\n    stride: int,\n    padding: int,\n    dilation: int = 1,\n    in_dtype: str = \"float32\",\n    out_dtype: str = \"float32\",\n) -> Tuple[te.Tensor, te.Tensor, te.Tensor, te.Tensor, te.Tensor, te.Tensor]:\n    oh = (h + 2 * padding - (kh - 1) * dilation - 1) // stride + 1  # pylint: disable=invalid-name\n    ow = (w + 2 * padding - (kw - 1) * dilation - 1) // stride + 1  # pylint: disable=invalid-name\n    x = te.placeholder((n, ci, h, w), name=\"X\", dtype=in_dtype)\n    w = te.placeholder((co, ci, kh, kw), name=\"W\", dtype=in_dtype)\n    b = te.placeholder((co, 1, 1), name=\"B\", dtype=out_dtype)\n    bn_scale = te.placeholder((co, 1, 1), name=\"bn_scale\", dtype=out_dtype)\n    bn_offset = te.placeholder((co, 1, 1), name=\"bn_offset\", dtype=out_dtype)\n    y = topi.nn.conv2d_nchw(\n        Input=x, Filter=w, stride=stride, padding=padding, dilation=dilation, out_dtype=out_dtype\n    )\n    y = te.compute((n, co, oh, ow), lambda i, j, k, l: y[i, j, k, l] + b[j, 0, 0], name=\"bias_add\")\n    y = te.compute(\n        (n, co, oh, ow), lambda i, j, k, l: y[i, j, k, l] * bn_scale[j, 0, 0], name=\"bn_mul\"\n    )\n    y = te.compute(\n        (n, co, oh, ow), lambda i, j, k, l: y[i, j, k, l] + bn_offset[j, 0, 0], name=\"bn_add\"\n    )\n    y = topi.nn.relu(y)\n    return (x, w, b, bn_scale, bn_offset, y)\n\n\ndef max_pool2d_nchw(  # pylint: disable=invalid-name\n    n: int,\n    h: int,\n    w: int,\n    ci: int,\n    padding: int,\n) -> Tuple[te.Tensor, te.Tensor]:  # pylint: disable=invalid-name\n    x = te.placeholder((n, ci, h, w), name=\"X\")\n    y = topi.nn.pool2d(x, [2, 2], [1, 1], [1, 1], [padding, padding, padding, padding], \"max\")\n    return (x, y)\n\n\ndef softmax_mn(m, n) -> Tuple[te.Tensor, te.Tensor]:  # pylint: disable=invalid-name\n    a = te.placeholder((m, n), name=\"A\")\n    b = topi.nn.softmax(a, axis=1)\n\n    return (a, b)\n\n\ndef create_te_workload(name: str, idx: int) -> tir.PrimFunc:\n    workload_func, params = CONFIGS[name]\n    return te.create_prim_func(workload_func(*params[idx]))  # type: ignore\n\n\nCONFIGS = {\n    \"C1D\": (\n        conv1d_nlc,\n        [\n            # derived from conv2d_shapes\n            (1, 256, 64, 128, 3, 2, 1),\n            #    (1, 256, 64, 128, 1, 2, 0),\n            #    (1, 256, 64, 64, 1, 1, 0),\n            #    (1, 128, 128, 256, 3, 2, 1),\n            (1, 128, 128, 256, 1, 2, 0),\n            #    (1, 128, 128, 128, 3, 1, 1),\n            #    (1, 64, 256, 512, 3, 2, 1),\n            #    (1, 64, 256, 512, 1, 2, 0),\n            (1, 64, 256, 256, 5, 1, 2),\n            (1, 32, 512, 512, 3, 1, 1),\n        ],\n    ),\n    \"C2D\": (\n        conv2d_nhwc,\n        [\n            # all conv2d layers in resnet-18\n            (1, 224, 224, 3, 64, 7, 2, 3),\n            #    (1, 56, 56, 64, 128, 3, 2, 1),\n            #    (1, 56, 56, 64, 128, 1, 2, 0),\n            #    (1, 56, 56, 64, 64, 3, 1, 1),\n            (1, 56, 56, 64, 64, 1, 1, 0),\n            #    (1, 28, 28, 128, 256, 3, 2, 1),\n            #    (1, 28, 28, 128, 256, 1, 2, 0),\n            #    (1, 28, 28, 128, 128, 3, 1, 1),\n            #    (1, 14, 14, 256, 512, 3, 2, 1),\n            #    (1, 14, 14, 256, 512, 1, 2, 0),\n            (1, 14, 14, 256, 256, 3, 1, 1),\n            (1, 7, 7, 512, 512, 3, 1, 1),\n        ],\n    ),\n    \"C3D\": (\n        conv3d_ndhwc,\n        [\n            # Derived from conv2d_shapes. Use depth=16 for all configurations\n            (1, 16, 224, 224, 3, 64, 7, 2, 3),\n            #    (1, 16, 56, 56, 64, 128, 3, 2, 1),\n            #    (1, 16, 56, 56, 64, 128, 1, 2, 0),\n            #    (1, 16, 56, 56, 64, 64, 3, 1, 1),\n            (1, 16, 56, 56, 64, 64, 1, 1, 0),\n            #    (1, 16, 28, 28, 128, 256, 3, 2, 1),\n            #    (1, 16, 28, 28, 128, 256, 1, 2, 0),\n            #    (1, 16, 28, 28, 128, 128, 3, 1, 1),\n            #    (1, 16, 14, 14, 256, 512, 3, 2, 1),\n            #    (1, 16, 14, 14, 256, 512, 1, 2, 0),\n            (1, 16, 14, 14, 256, 256, 3, 1, 1),\n            (1, 16, 7, 7, 512, 512, 3, 1, 1),\n        ],\n    ),\n    \"GMM\": (\n        batch_matmul_nkkm,\n        [\n            (1, 128, 128, 128),\n            (1, 512, 32, 512),\n            (1, 512, 512, 512),\n            (1, 1024, 1024, 1024),\n        ],\n    ),\n    \"GRP\": (\n        conv2d_nhwc,\n        [\n            # Derived from conv2d_shapes. Use group=4 for all configurations\n            (1, 56, 56, 64, 128, 3, 2, 1, 1, 4),\n            #    (1, 56, 56, 64, 128, 1, 2, 0 , 1, 4),\n            #    (1, 56, 56, 64, 64, 3, 1, 1  , 1, 4),\n            (1, 56, 56, 64, 64, 1, 1, 0, 1, 4),\n            #    (1, 28, 28, 128, 256, 3, 2, 1, 1, 4),\n            #    (1, 28, 28, 128, 256, 1, 2, 0, 1, 4),\n            #    (1, 28, 28, 128, 128, 3, 1, 1, 1, 4),\n            #    (1, 14, 14, 256, 512, 3, 2, 1, 1, 4),\n            #    (1, 14, 14, 256, 512, 1, 2, 0, 1, 4),\n            (1, 14, 14, 256, 256, 3, 1, 1, 1, 4),\n            (1, 7, 7, 512, 512, 3, 1, 1, 1, 4),\n        ],\n    ),\n    \"DIL\": (\n        conv2d_nhwc,\n        [\n            # Derived from conv2d_shapes. Use dilation=2 for all configurations\n            (1, 224, 224, 3, 64, 7, 2, 3, 2),\n            #    (1, 56, 56, 64, 128, 3, 2, 1 , 2),\n            #    (1, 56, 56, 64, 128, 1, 2, 0 , 2),\n            #    (1, 56, 56, 64, 64, 3, 1, 1  , 2),\n            (1, 56, 56, 64, 64, 1, 1, 0, 2),\n            #    (1, 28, 28, 128, 256, 3, 2, 1, 2),\n            #    (1, 28, 28, 128, 256, 1, 2, 0, 2),\n            #    (1, 28, 28, 128, 128, 3, 1, 1, 2),\n            #    (1, 14, 14, 256, 512, 3, 2, 1, 2),\n            #    (1, 14, 14, 256, 512, 1, 2, 0, 2),\n            (1, 14, 14, 256, 256, 3, 1, 1, 2),\n            (1, 7, 7, 512, 512, 3, 1, 1, 2),\n        ],\n    ),\n    \"DEP\": (\n        depthwise_conv2d_nhwc,\n        [\n            # all depthwise conv2d layers in mobilenet\n            (1, 112, 112, 32, 3, 1, 1),\n            (1, 112, 112, 64, 3, 2, 1),\n            #    (1,  56,  56, 128, 3, 1, 1),\n            #    (1,  56,  56, 128, 3, 2, 1),\n            #    (1,  28,  28, 256, 3, 1, 1),\n            #    (1,  28,  28, 256, 3, 2, 1),\n            #    (1,  14,  14, 512, 3, 1, 1),\n            (1, 14, 14, 512, 3, 2, 1),\n            (1, 7, 7, 1024, 3, 1, 1),\n        ],\n    ),\n    \"T2D\": (\n        conv2d_transpose_nhwc,\n        [\n            # all conv2d transpose layers in DCGAN\n            (1, 4, 4, 512, 256, 4, 2, 1),\n            (1, 8, 8, 256, 128, 4, 2, 1),\n            (1, 16, 16, 128, 64, 4, 2, 1),\n            (1, 32, 32, 64, 3, 4, 2, 1),\n        ],\n    ),\n    \"CAP\": (\n        conv2d_capsule_nhwijc,\n        [\n            # all conv2d capsule layers in matrix capsules withemrouting (ICLR 2018)\n            (1, 16, 16, 32, 32, 3, 2, 1),\n            (1, 8, 8, 32, 32, 3, 1, 1),\n            (1, 16, 16, 8, 16, 3, 2, 1),\n            (1, 8, 8, 16, 16, 3, 1, 1),\n        ],\n    ),\n    \"NRM\": (\n        norm_bmn,\n        [\n            (1, 256, 256),\n            (1, 512, 512),\n            (1, 1024, 1024),\n            (1, 4096, 1024),\n        ],\n    ),\n    \"SFM\": (\n        softmax_mn,\n        [\n            (256, 256),\n            (512, 512),\n            (1024, 1024),\n            (2048, 2048),\n        ],\n    ),\n    \"CBR\": (\n        conv2d_nhwc_bn_relu,\n        [\n            (1, 224, 224, 3, 64, 7, 2, 3),\n            (1, 56, 56, 64, 128, 3, 2, 1),\n            (1, 28, 28, 128, 256, 1, 2, 0),\n            (1, 7, 7, 512, 512, 3, 1, 1),\n        ],\n    ),\n    \"TBG\": (\n        transpose_batch_matmul,\n        [\n            (1, 128, 12, 64),\n            (1, 128, 16, 64),\n            (1, 64, 12, 128),\n            (1, 128, 12, 128),\n        ],\n    ),\n    \"C2D_WIN_NHWC\": (\n        conv2d_winograd_nhwc,\n        [\n            (1, 14, 14, 128, 128, 6),\n        ],\n    ),\n    \"C2D_WIN_NCHW\": (\n        conv2d_winograd_nchw,\n        [\n            (1, 56, 56, 64, 64, 6),\n        ],\n    ),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/tlcbench.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,import-outside-toplevel\n# type: ignore\n\"\"\"Model loader for TLCBench.\"\"\"\nimport logging\nimport multiprocessing\nimport os\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\n\nlog = logging.getLogger(__name__)\n\n\ndef _convert(args):\n    onnx_model, shape_dict, json_path, params_path = args\n    mod, params = relay.frontend.from_onnx(onnx_model, shape_dict, freeze_params=True)\n\n    seq = tvm.transform.Sequential(\n        [relay.transform.InferType(), relay.transform.FakeQuantizationToInteger(use_qat=True)]\n    )\n    mod = seq(mod)\n\n    with open(json_path, \"w\") as fo:\n        fo.write(tvm.ir.save_json(mod))\n\n    with open(params_path, \"wb\") as fo:\n        fo.write(relay.save_param_dict(params))\n\n\ndef convert_to_qnn(onnx_path, json_path, params_path, input_info):\n    \"\"\"Run the ONNX frontend and the FQ2I pass. The output is serialized to disk.\"\"\"\n    import onnx\n\n    onnx_model = onnx.load(onnx_path)\n\n    shape_dict = dict(input_info)\n\n    log.info(\"Converting te ONNX model to Relay and running the FQ2I pass, it may take a while...\")\n\n    with multiprocessing.Pool(processes=1) as pool:\n        pool.map(_convert, [(onnx_model, shape_dict, json_path, params_path)])\n\n\ndef deserialize_relay(json_path, params_path):\n    with open(json_path, \"r\") as fi:\n        mod = tvm.ir.load_json(fi.read())\n\n    with open(params_path, \"rb\") as fi:\n        params = relay.load_param_dict(fi.read())\n    return mod, params\n\n\ndef load_quantized_bert_base(batch_size=1, seq_len=384):\n    \"\"\"\n    Load the quantized bert-base model from TLCBench, possibly downloading it from github\n    and caching the converted int8 QNN module to disk.\n\n    In addition to returing the relay module and its parameters, it also returns input name\n    and shape information, which can be used at the deployment time as follows:\n\n    ```\n    mod, params, input_info = load_quantized_bert_base()\n\n    ...\n\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    for name, shape in input_info:\n        arr = np.random.uniform(1, 10, size=shape).astype(\"int64\")\n        runtime.set_input(name, arr)\n\n    runtime.run()\n    ```\n\n    \"\"\"\n    url = \"https://github.com/tlc-pack/TLCBench/raw/main/models/bert-base-qat.onnx\"\n    log.info(\"Downloading quantized bert-base model.\")\n    onnx_path = download_testdata(url, \"bert-base-qat.onnx\", module=\"tlcbench\")\n    data_dir = os.path.dirname(onnx_path)\n\n    json_path = os.path.join(data_dir, \"bert_base_int8_b%d_s%d.json\" % (batch_size, seq_len))\n    params_path = os.path.join(data_dir, \"bert_base_int8_b%d_s%d.params\" % (batch_size, seq_len))\n\n    # Input names and order encoded in the ONNX model\n    input_info = [\n        (\"input_ids\", (batch_size, seq_len)),\n        (\"segment_ids\", (batch_size, seq_len)),\n        (\"input_mask\", (batch_size, seq_len)),\n    ]\n\n    if not os.path.exists(json_path) or not os.path.exists(params_path):\n        convert_to_qnn(onnx_path, json_path, params_path, input_info)\n\n    def deserialize():\n        try:\n            return deserialize_relay(json_path, params_path)\n        except ValueError:\n            # A serialized Relay json file may become invalid after TVM bump\n            # Update the serialized model and try loading again\n            convert_to_qnn(onnx_path, json_path, params_path, input_info)\n            return deserialize_relay(json_path, params_path)\n\n    mod, params = deserialize()\n\n    return mod, params, input_info\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/torchbench/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/torchbench/run.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis script is for benchmarking TVM performance on models from TorchBench.\nIt uses the TorchDynamo as the frontend to ingest models into TVM, and it also\nleverages the benchmark util from TorchDynamo.\n\nTorchDynamo (https://github.com/pytorch/torchdynamo) and TorchBench\n(https://github.com/pytorch/benchmark) need to be in the parent directory of TVM.\nWe need a local clone of these repos because torchbench and the benchmark runner\nin TorchDynamo isn't designed to be used as a Python package.\n\nTo setup the environment, run the following commands in the parent directory of TVM and with\nthe appropriate Python environment:\n```bash\n# torchdynamo requires nightly pytorch. If it fails to find the specified version, try\n# installing the latest nightly pytorch.\npip3 install --pre \\\n    --extra-index-url https://download.pytorch.org/whl/nightly/cu116 \\\n    torch==1.13.0.dev20220926 \\\n    torchvision==0.14.0.dev20220926 \\\n    torchtext==0.14.0.dev20220926\n\ngit clone https://github.com/pytorch/torchdynamo\npushd torchdynamo\ngit checkout c537639f9712621dc04ca09908796dbbe86c354b\npip install -e .\npopd\n\nsudo apt install git-lfs  # git lfs is used for TorchBench\ngit clone https://github.com/pytorch/benchmark\npushd benchmark\npython install.py --continue_on_fail  # fambench_xlmr might fail to install\npopd\n```\n\nTo run a benchmark, the script can be run under 'tune' mode by\n```bash\npython python/tvm/meta_schedule/testing/torchbench/run.py \\\n    --mode tune \\\n    --model resnet50 \\\n    --target \"nvidia/geforce-rtx-3070\" \\\n    --work-dir /path/to/work/dir/ \\\n    --num-trials 20000 \\\n    --rpc-host <rpc tracker host for tuning> \\\n    --rpc-port <rpc tracker port for tuning> \\\n    --rpc-key <rpc key> \\\n```\n\nAll available target tags (like nvidia/geforce-rtx-3070) can be found at\nhttps://github.com/apache/tvm/blob/main/src/target/tag.cc\n\nThen the script can be run under 'eval' mode to actual benchmark the performance,\nusing the tuning database under the work directory. This can be executed on a different\nmachine than the one executes tuning (the database json files need to be inside\nof the work directory).\n```bash\npython python/tvm/meta_schedule/testing/torchbench/run.py \\\n    --mode eval \\\n    --model resnet50 \\\n    --target \"nvidia/geforce-rtx-3070\" \\\n    --work-dir /path/to/work/dir/ \\\n    --num-trials 0\n```\n\nAlternatively, both tuning and evaluation can be done in a single run on the same machine,\nby\n```bash\npython python/tvm/meta_schedule/testing/torchbench/run.py \\\n    --mode all \\\n    --model resnet50 \\\n    --target \"llvm -num-cores 6\" \\\n    --work-dir /path/to/work/dir/ \\\n    --num-trials 0\n```\n\"\"\"\n# pylint: disable=logging-format-interpolation\n\nimport argparse\nimport contextlib\nimport logging\nimport os\nimport sys\nimport warnings\nfrom collections import defaultdict\nfrom enum import Enum\nfrom typing import Callable, Dict, List, Tuple\n\nimport numpy as np  # type: ignore\nimport torch  # type: ignore\nfrom scipy.stats import ttest_ind  # type: ignore\n\nimport tvm\nimport tvm.relay\nfrom tvm import meta_schedule as ms\nfrom tvm._ffi import get_global_func\nfrom tvm.contrib.graph_executor import GraphModule\nfrom tvm.meta_schedule.testing.torchbench.utils import (\n    load_torchdynamo_benchmark_runner,\n    same,\n    timed,\n)\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.support import describe\n\n# Needs to be imported after the .utils is executed\nimport torchdynamo  # type: ignore  # isort: skip, pylint: disable=wrong-import-order\n\n\nclass RunMode(Enum):\n    \"\"\"\n    The running mode of this script. Available values are:\n    - tune: Only tune the model and create the tuning database.\n    - eval: Only benchmark model using pre-existing tuning database.\n    - all: Run both tuning and benchmark\n    \"\"\"\n\n    ALL = \"all\"\n    TUNE = \"tune\"\n    EVAL = \"eval\"\n\n    @property\n    def should_tune(self):\n        \"\"\"\n        Returns whether it should tune the model.\n        \"\"\"\n        return self != RunMode.EVAL\n\n    @property\n    def should_eval(self):\n        \"\"\"\n        Returns whether it should actually benchmark the model.\n        \"\"\"\n        return self != RunMode.TUNE\n\n\nclass ResultComparisonMetric(Enum):\n    \"\"\"\n    This changes how it compares the results with the expected value during\n    accuracy check.\n    - cosine: Use the cosine similarity. It should be greater than 0.99.\n    - allclose-1e-4: Use the max elementwise absolute difference. It should be less than 1e-4.\n    \"\"\"\n\n    COSINE = \"cosine\"\n    ALLCLOSE = \"allclose-1e-4\"\n\n\ndef parse_args():\n    \"\"\"\n    Parse arguments\n    \"\"\"\n    args = argparse.ArgumentParser()\n\n    args.add_argument(\n        \"--mode\",\n        type=RunMode,\n        default=RunMode.ALL,\n        help=RunMode.__doc__,\n    )\n    args.add_argument(\n        \"--batch-size\",\n        type=int,\n        default=None,\n        help=\"The batch size of model input. Use TorchBench's default value if not specified.\",\n    )\n    args.add_argument(\n        \"--result-metric\",\n        type=ResultComparisonMetric,\n        default=ResultComparisonMetric.ALLCLOSE,\n        help=ResultComparisonMetric.__doc__,\n    )\n    args.add_argument(\n        \"--benchmark-repeat\",\n        type=int,\n        default=10,\n        help=\"The number of times to repeat the benchmark measurement.\",\n    )\n    args.add_argument(\n        \"--benchmark-warmup-rounds\",\n        type=int,\n        default=5,\n        help=\"The number of rounds to warmup before starting to measure the performance.\",\n    )\n\n    # Model selection\n    args.add_argument(\n        \"--model\",\n        type=str,\n        required=True,\n        help=\"\"\"\n        The name of model to run. It should a directory name under\n        https://github.com/pytorch/benchmark/tree/main/torchbenchmark/models.\n        \"\"\",\n    )\n    args.add_argument(\n        \"--float32\",\n        action=\"store_true\",\n        help=\"\"\"\n        Cast model and inputs to fp32\n        \"\"\",\n    )\n\n    # Tuning-related config\n    args.add_argument(\n        \"--target\",\n        type=tvm.target.Target,\n        required=True,\n        help=\"The target to tune and run benchmark for.\",\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n        help=\"\"\"\n        The working directory to save intermediate results and store databases for compilation.\n        \"\"\",\n    )\n    args.add_argument(\n        \"--strategy\",\n        type=str,\n        default=\"evolutionary\",\n        help=\"The search strategy used by MetaSchdule.\",\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n        help=\"The max number of trials to run MetaSchedule.\",\n    )\n    args.add_argument(\n        \"--max-trials-per-task\",\n        type=int,\n        default=None,\n        help=\"\"\"\n        The max number of trials to run per task extracted in MetaSchedule.\n        By default it's the same as --num-trials.\n        \"\"\",\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        default=\"graph\",\n        help=\"The backend to use for relay compilation(graph / vm).\",\n    )\n    # TODO(@yelite): Add a layout arg to transform the network after\n    # ingesting into Relay and before feeding into MetaSchedule.\n\n    # Evaluator-related config\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n        help=\"The number of times to run the model for taking average in a single measurement.\",\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n        help=\"The number of times to repeat the measurement.\",\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n        help=\"\"\"\n        Minimum repeat time in ms. The number of runs will be increased if the actual\n        repeat time is lowered than this.\n        \"\"\",\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        action=\"store_true\",\n        help=\"Whether to use adaptive training for cost model.\",\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        action=\"store_true\",\n        help=\"Whether to perform CPU cache flush.\",\n    )\n\n    # RPC-related args\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        help=\"Host of the RPC Tracker for tuning. Use LocalRunner if not provided\",\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        help=\"Port of the RPC Tracker for tuning\",\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        help=\"Key of the RPC Tracker for tuning\",\n    )\n\n    parsed = args.parse_args()\n\n    # Trim all args, otherwise it confuses the arg parser of timm_efficientdet\n    sys.argv = sys.argv[:1]\n\n    return parsed\n\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\nARGS = parse_args()\nIS_CUDA = ARGS.target.kind.name == \"cuda\"\n\nlogger = logging.getLogger(__name__)  # pylint: disable=invalid-name\nlogger.setLevel(logging.INFO)\n\n\nrunner = load_torchdynamo_benchmark_runner(  # pylint: disable=invalid-name\n    IS_CUDA,\n    cosine_similarity=ARGS.result_metric == ResultComparisonMetric.COSINE,\n    float32=ARGS.float32,\n)\n\n\ndef get_meta_schedule_runner() -> ms.runner.PyRunner:\n    \"\"\"\n    Get the Runner for MetaSchedule.\n\n    It returns RPCRunner if --rpc-host is given, otherwise it returns LocalRunner\n    \"\"\"\n    if ARGS.rpc_host is not None:\n        assert ARGS.rpc_port is not None, \"Missing rpc_port\"\n        assert ARGS.rpc_key is not None, \"Missing rpc_key\"\n        return ms.runner.RPCRunner(\n            rpc_config=ms.runner.RPCConfig(\n                tracker_host=ARGS.rpc_host,\n                tracker_port=ARGS.rpc_port,\n                tracker_key=ARGS.rpc_key,\n                session_timeout_sec=600,\n            ),\n            evaluator_config=ms.runner.EvaluatorConfig(\n                number=ARGS.number,\n                repeat=ARGS.repeat,\n                min_repeat_ms=ARGS.min_repeat_ms,\n                enable_cpu_cache_flush=ARGS.cpu_flush,\n            ),\n            alloc_repeat=1,\n        )\n    else:\n        warnings.warn(\"Falling back to MetaSchedule LocalRunner because --rpc-host isn't provided.\")\n        return ms.runner.LocalRunner()\n\n\ndef get_graph_executor_forward(\n    graph_executor_factory: tvm.runtime.Module, device: tvm.runtime.Device\n) -> Callable:\n    \"\"\"\n    Get the forward function for graph executor, in order to integrate with TorchDynamo.\n    \"\"\"\n\n    # It has to lazily import this package, loading the C++ PyTorch integration\n    # after the transformers package is imported when loading model. Otherwise\n    # there will be segfault caused by the protobuf library.\n    import tvm.contrib.torch  # pylint: disable=import-outside-toplevel, unused-import, redefined-outer-name\n\n    save_runtime_mod = get_global_func(\"tvmtorch.save_runtime_mod\", allow_missing=True)\n    if save_runtime_mod is None:\n        warnings.warn(\n            \"C++ PyTorch TVM integration is missing. Fallback to Python forward function.\"\n            \"Build TVM with 'USE_PT_TVMDSOOP' to enable the C++ custom operator\"\n        )\n        mod = GraphModule(graph_executor_factory[\"default\"](device))\n\n        def forward(*args):\n            if IS_CUDA:\n                torch.cuda.synchronize()\n            args = tuple(arg.detach().contiguous() for arg in args)\n            for idx, arg in enumerate(args, 0):\n                mod.set_input(\n                    f\"inp_{idx}\",\n                    tvm.nd.from_dlpack(arg),\n                )\n            mod.run()\n            device.sync()\n            result = [torch.from_dlpack(mod.get_output(i)) for i in range(mod.get_num_outputs())]\n            return result\n\n        return forward\n    else:\n        save_runtime_mod(graph_executor_factory.module)\n        module = torch.classes.tvm_torch.GraphExecutorFactoryWrapper()\n\n        def forward(*args):  # type: ignore  # isort: skip, pylint: disable=function-redefined\n            return module.forward(args)\n\n        return forward\n\n\ndef get_vm_forward(virtual_machine: VirtualMachine, device: tvm.runtime.Device) -> Callable:\n    \"\"\"\n    Get the forward function for VM, in order to integrate with TorchDynamo.\n    \"\"\"\n\n    def forward(*args):\n        if IS_CUDA:\n            torch.cuda.synchronize()\n        args = tuple(tvm.nd.from_dlpack(arg.detach().contiguous()) for arg in args)\n        result = virtual_machine.invoke(\"main\", *args)\n        device.sync()\n\n        if isinstance(result, tvm.nd.NDArray):\n            result = [result]\n        return [torch.from_dlpack(m) for m in result]\n\n    return forward\n\n\ndef should_skip_subgraph(graph_module: torch.fx.GraphModule) -> bool:\n    \"\"\"\n    Returns whether it should skip optimizing the input graph module.\n    The graph could be empyt or only containing nodes calling function\n    for side effect.\n    \"\"\"\n    graph = graph_module.graph\n\n    inputs = [n for n in graph.nodes if n.op == \"placeholder\"]\n    outputs = [n for n in graph.nodes if n.op == \"output\"]\n\n    return len(inputs) == 0 and all(output.args == ((),) for output in outputs)\n\n\ndef create_tvm_task_collection_backend() -> Tuple[Callable, List[ms.ExtractedTask]]:\n    \"\"\"\n    This torchdynamo backend only collects the extracted tasks from MetaSchedule.\n    It doesn't tune the model.\n    \"\"\"\n\n    subgraph_idx = 0\n    subgraphs_dir = os.path.join(ARGS.work_dir, \"subgraphs\")\n    os.makedirs(subgraphs_dir, exist_ok=True)\n\n    collected_tasks = []\n    task_index: Dict[int, List[ms.ExtractedTask]] = defaultdict(list)\n\n    def collect_task(task):\n        task_hash = tvm.ir.structural_hash(task.dispatched[0])\n\n        for duplicate_task in task_index[task_hash]:\n            if tvm.ir.structural_equal(duplicate_task.dispatched[0], task.dispatched[0]):\n                duplicate_task.weight += task.weight\n                return\n\n        task_index[task_hash].append(task)\n        collected_tasks.append(task)\n\n    def backend(graph_module, example_inputs):\n        nonlocal subgraph_idx\n\n        torch.save(graph_module, os.path.join(subgraphs_dir, f\"graph_module_{subgraph_idx}\"))\n        torch.save(example_inputs, os.path.join(subgraphs_dir, f\"example_inputs_{subgraph_idx}\"))\n\n        if should_skip_subgraph(graph_module):\n            return graph_module.forward\n\n        jit_mod = torch.jit.trace(graph_module, example_inputs)\n        shape_list = [(f\"inp_{idx}\", i.shape) for idx, i in enumerate(example_inputs)]\n        ir_mod, params = tvm.relay.frontend.from_pytorch(jit_mod, shape_list)\n\n        extracted_tasks = ms.relay_integration.extract_tasks(\n            mod=ir_mod,\n            target=ARGS.target,\n            params=params,\n        )\n        old_tasks_count = len(collected_tasks)\n        for task in extracted_tasks:\n            collect_task(task)\n        logger.info(\n            \"Extracted %d tasks from graph %d, with %d new tasks\",\n            len(extracted_tasks),\n            subgraph_idx,\n            len(collected_tasks) - old_tasks_count,\n        )\n\n        subgraph_idx += 1\n\n        return graph_module.forward\n\n    return backend, collected_tasks\n\n\ndef create_tvm_compilation_backend(database: ms.database.Database) -> Callable:\n    \"\"\"\n    This torchdynamo backend compiles the model using history best record from the\n    MetaSchedule database.\n    \"\"\"\n\n    def backend(graph_module, example_inputs):\n        if should_skip_subgraph(graph_module):\n            return graph_module.forward\n\n        jit_mod = torch.jit.trace(graph_module, example_inputs)\n        shape_list = [(f\"inp_{idx}\", i.shape) for idx, i in enumerate(example_inputs)]\n        ir_mod, params = tvm.relay.frontend.from_pytorch(jit_mod, shape_list)\n\n        lib = ms.relay_integration.compile_relay(\n            database=database,\n            mod=ir_mod,\n            target=ARGS.target,\n            params=params,\n            backend=ARGS.backend,\n        )\n        device = tvm.cuda(0) if IS_CUDA else tvm.cpu(0)\n\n        if ARGS.backend == \"graph\":\n            return get_graph_executor_forward(lib, device)\n        elif ARGS.backend == \"vm\":\n            vm = VirtualMachine(lib, device)  # pylint: disable=invalid-name\n            return get_vm_forward(vm, device)\n        else:\n            raise RuntimeError(f\"Unknown backend {ARGS.backend}\")\n\n    return backend\n\n\ndef format_time(seconds: float) -> str:\n    \"\"\"\n    Format elapsed time based on its value.\n    \"\"\"\n    if seconds > 1:\n        return f\"{seconds:.3g}s\"\n    else:\n        return f\"{seconds * 1000:.3g}ms\"\n\n\ndef is_output_correct(output: torch.Tensor, expected: torch.Tensor) -> bool:\n    \"\"\"\n    Check whether the output is correct.\n    \"\"\"\n    comparison_metric = ARGS.result_metric\n    if comparison_metric == ResultComparisonMetric.COSINE:\n        return same(expected, output, cosine_similarity=True)\n    elif comparison_metric == ResultComparisonMetric.ALLCLOSE:\n        return same(expected, output, tol=1e-4)\n    else:\n        raise RuntimeError(f\"Unknown comparison metric {comparison_metric}\")\n\n\ndef inspect_output_error(output, expected):\n    \"\"\"\n    Inpsect the error between the actual output and expected output.\n    \"\"\"\n    if not isinstance(output, torch.Tensor):\n        logger.info(\n            f\"Unsupported type for error inspection: {type(output).__name__}.\"\n            f\"Please manually check output.pt\"\n        )\n        return\n    output = output.cpu().float()\n    expected = expected.cpu().float()\n\n    abs_error = (output - expected).abs()\n    rel_error = (abs_error / expected).abs()\n\n    def format_error_table(error, bins) -> str:\n        bin_tensor = torch.as_tensor([float(b) for b in bins], dtype=error.dtype)\n        error_hist = torch.histogram(error, bin_tensor).hist.int()\n        return \"\\n\".join(f\"< {b}\\t{e}\" for e, b in zip(error_hist, bins[1:]))\n\n    abs_error_bins = [\n        \"-1e10\",\n        \"0\",\n        \"1e-8\",\n        \"1e-6\",\n        \"1e-5\",\n        \"1e-4\",\n        \"1e-3\",\n        \"1e-2\",\n        \"1e-1\",\n        \"1\",\n        \"1e10\",\n    ]\n    rel_error_bins = [\n        \"-1e10\",\n        \"0\",\n        \"1e-4\",\n        \"1e-3\",\n        \"1e-2\",\n        \"1e-1\",\n        \"1\",\n        \"1e1\",\n        \"1e2\",\n        \"1e3\",\n        \"1e100\",\n    ]\n\n    large_rel_error_idx = rel_error > 1\n    abs_error_with_large_rel_error = abs_error[large_rel_error_idx]\n\n    logger.error(f\"Expected (PyTorch eager): {expected}\")\n    logger.error(f\"Actual (Optimized): {output}\")\n    logger.error(f\"Absolute Error\\n{format_error_table(abs_error, abs_error_bins)}\")\n    logger.error(f\"Relative Error\\n{format_error_table(rel_error, rel_error_bins)}\")\n    logger.error(\n        f\"Max absolute error for position with large relative error (> 1):\"\n        f\"{abs_error_with_large_rel_error.max()}\"\n    )\n\n\ndef performance_experiment(\n    model_iter_fn: Callable,\n    model: torch.nn.Module,\n    example_inputs: Tuple[torch.Tensor],\n) -> str:\n    \"\"\"\n    Performs the actual benchmarking\n    Simplified from https://github.com/pytorch/torchdynamo/blob/c537639f9712621dc04ca09908796dbbe86c354b/benchmarks/common.py#L494 pylint: disable=line-too-long\n    \"\"\"\n    timings = np.zeros((ARGS.benchmark_repeat, 2), np.float64)\n    if IS_CUDA:\n        torch.cuda.empty_cache()\n\n    is_correct = True\n\n    frozen_model_iter_fn = torchdynamo.run(model_iter_fn)\n\n    for _ in range(ARGS.benchmark_warmup_rounds):\n        frozen_model_iter_fn(model, example_inputs)\n        model_iter_fn(model, example_inputs)\n\n    for rep in range(ARGS.benchmark_repeat):\n        # interleave the runs to handle frequency scaling and load changes\n        timings[rep, 0], expected_output = timed(\n            model, model_iter_fn, example_inputs, return_result=True\n        )\n        timings[rep, 1], actual_output = timed(\n            model, frozen_model_iter_fn, example_inputs, return_result=True\n        )\n        is_correct = is_correct and is_output_correct(expected_output, actual_output)\n\n    pvalue = ttest_ind(timings[:, 0], timings[:, 1]).pvalue\n    median = np.median(timings, axis=0)\n    speedup = median[0] / median[1]\n    logger.info(\n        f\"eager:{format_time(median[0])} \"\n        f\"optimized:{format_time(median[1])} \"\n        f\"speedup:{speedup:.3f}x p:{pvalue:.3f}\"\n    )\n    torch.save(actual_output, os.path.join(ARGS.work_dir, \"output.pt\"))\n    torch.save(expected_output, os.path.join(ARGS.work_dir, \"expected.pt\"))\n    if not is_correct:\n        logger.error(\"Result is incorrect.\")\n        inspect_output_error(actual_output, expected_output)\n\n    return \"\"\n\n\ndef get_torch_device_type(target: tvm.target.Target) -> str:\n    if target.kind.name == \"llvm\":\n        return \"cpu\"\n    elif target.kind.name == \"cuda\":\n        return \"cuda\"\n    else:\n        raise RuntimeError(f\"Unsupported target {target}\")\n\n\ndef main():\n    \"\"\"\n    Entry point of the benchmark\n    \"\"\"\n    describe()\n\n    meta_schedule_work_dir = os.path.join(ARGS.work_dir, \"meta_schedule\")\n    os.makedirs(meta_schedule_work_dir, exist_ok=True)\n\n    database = ms.database.JSONDatabase(work_dir=meta_schedule_work_dir)\n    if not ARGS.mode.should_tune:\n        if len(database) == 0:\n            raise RuntimeError(\n                \"Script is running in eval mode while the tuning database is empty. \"\n                \"Please tune the model first.\"\n            )\n\n    if IS_CUDA and ARGS.cpu_flush:\n        warnings.warn(\n            \"Benchmark is running on CUDA, while --cpu-flush is turned on. \"\n            \"This flag will have no effect on CUDA.\"\n        )\n        ARGS.cpu_flush = False\n\n    try:\n        logger.info(f\"Loading model with batch size: {ARGS.batch_size}\")\n        _, name, model, example_inputs, batch_size = runner.load_model(\n            get_torch_device_type(ARGS.target),\n            ARGS.model,\n            batch_size=ARGS.batch_size,\n        )\n        model, example_inputs = runner.maybe_cast(model, example_inputs)\n        logger.info(f\"Got model with batch size: {batch_size}\")\n    except NotImplementedError:\n        logger.exception(f\"{ARGS.model} failed to load\")\n        raise\n\n    with contextlib.ExitStack() as stack:\n        profiler = stack.enter_context(ms.Profiler())\n        stack.enter_context(torch.no_grad())\n\n        if ARGS.mode.should_tune:\n            task_collect_backend, extracted_tasks = create_tvm_task_collection_backend()\n            task_collect_ctx = torchdynamo.optimize(task_collect_backend)\n            task_collect_ctx(runner.model_iter_fn)(model, example_inputs)\n\n            tasks, task_weights = ms.relay_integration.extracted_tasks_to_tune_contexts(\n                extracted_tasks=extracted_tasks,\n                work_dir=ARGS.work_dir,\n                strategy=ARGS.strategy,\n            )\n            database = ms.tune.tune_tasks(\n                tasks=tasks,\n                task_weights=task_weights,\n                work_dir=ARGS.work_dir,\n                max_trials_global=ARGS.num_trials,\n                max_trials_per_task=ARGS.max_trials_per_task,\n                runner=get_meta_schedule_runner(),  # type: ignore\n                database=database,\n                cost_model=ms.cost_model.XGBModel(  # type: ignore\n                    extractor=ms.feature_extractor.PerStoreFeature(),\n                    adaptive_training=ARGS.adaptive_training,\n                ),\n            )\n\n        if ARGS.mode.should_eval:\n            torchdynamo.reset()\n            model_compile_ctx = torchdynamo.optimize(create_tvm_compilation_backend(database))\n            model_compile_ctx(runner.model_iter_fn)(model, example_inputs)\n            with torch.no_grad():\n                performance_experiment(runner.model_iter_fn, model, example_inputs)\n\n    print(profiler.table())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/torchbench/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nHelper functions for running TorchBench through the benchmark functions\nfrom TorchDynamo.\n\"\"\"\n\nimport os\nimport sys\nfrom dataclasses import dataclass\n\nimport torch  # type: ignore\n\n\ndef find_torchdynamo() -> str:\n    \"\"\"\n    Find the directory of TorchDynamo repo.\n\n    It can't directly import the benchmark runner in TorchDynamo\n    becuase it isn't designed to be used as a Python package.\n    \"\"\"\n    candidates = [\n        \"torchdynamo\",\n        \"../torchdynamo\",\n        \"../../torchdynamo\",\n    ]\n    for library_dir in candidates:\n        if os.path.exists(f\"{library_dir}/benchmarks\"):\n            return library_dir\n\n    raise RuntimeError(\n        \"\"\"\n        Cannot find directory for torchdynamo.\n        You need to clone https://github.com/pytorch/torchdynamo to the parent directory of cwd.\n        \"\"\"\n    )\n\n\nDYNAMO_DIR = find_torchdynamo()\nsys.path.insert(\n    0, DYNAMO_DIR\n)  # opacus_cifar10 depends on opacus, which installs a package called 'benchmarks'\nsys.path.append(f\"{DYNAMO_DIR}/benchmarks\")\n\n# pylint: disable=wrong-import-position, unused-import\nfrom benchmarks.common import same, timed  # type: ignore\nfrom torchbench import TorchBenchmarkRunner  # type: ignore\n\n# pylint: disable=wrong-import-position, unused-import\n\n\ndef load_torchdynamo_benchmark_runner(\n    is_cuda: bool, cosine_similarity: bool = False, float32: bool = False\n) -> TorchBenchmarkRunner:\n    \"\"\"\n    Load the benchmark runner from TorchDynamo.\n    \"\"\"\n\n    @dataclass\n    class RunnerArgs:\n        \"\"\"\n        This class simulates the parsed args required by the benchmark code from TorchDynamo.\n        \"\"\"\n\n        ci: bool = False  # Whether runs in CI mode. pylint: disable=invalid-name\n        training: bool = False  # Whether it benchmarks training workload.\n        use_eval_mode: bool = True  # Whether the model should be in eval mode.\n        dynamic_shapes: bool = False  # Whether runs the model in dynamic shape mode.\n        float16: bool = False  # Whether to cast model and inputs to float16\n        float32: bool = False  # Whether to cast model and inputs to float32\n\n        accuracy: bool = False  # Whether to perform a accuracy test\n        performance: bool = True  # Whether to perform a performance test\n\n        cosine: bool = False  # Whether to use consine similarity to check if output is correct.\n\n    args = RunnerArgs(cosine=cosine_similarity, float32=float32)\n\n    runner = TorchBenchmarkRunner()\n    runner.args = args\n    runner.model_iter_fn = runner.forward_pass\n\n    if is_cuda:\n        # pylint: disable=import-outside-toplevel\n        import benchmarks.common  # type: ignore\n\n        # pylint: enable=import-outside-toplevel\n\n        benchmarks.common.synchronize = torch.cuda.synchronize\n\n    return runner\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/tune_onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport argparse\nimport json\nimport logging\nfrom distutils.util import strtobool\n\nimport onnx  # type: ignore\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.relay.frontend import from_onnx\nfrom tvm.support import describe\n\nfrom .tune_utils import create_timer, generate_input_data\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--model-name\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--onnx-path\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--input-shape\",\n        type=str,\n        required=True,\n        help='example: `[{\"name\": \"input1\", \"dtype\": \"int64\", \"shape\": [1, 1, 8]}]',\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        help=\"example: graph / vm\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.input_shape = json.loads(parsed.input_shape)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    return parsed\n\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\nARGS = _parse_args()\n\n\ndef main():\n    describe()\n    print(f\"Workload: {ARGS.model_name}\")\n\n    onnx_model = onnx.load(ARGS.onnx_path)\n    shape_dict = {}\n    for item in ARGS.input_shape:\n        print(f\"  input_name : {item['name']}\")\n        print(f\"  input_shape: {item['shape']}\")\n        print(f\"  input_dtype: {item['dtype']}\")\n        shape_dict[item[\"name\"]] = item[\"shape\"]\n    mod, params = from_onnx(onnx_model, shape_dict, freeze_params=True)\n    input_data = {\n        item[\"name\"]: generate_input_data(item[\"shape\"], item[\"dtype\"]) for item in ARGS.input_shape\n    }\n\n    with ms.Profiler() as profiler:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=ARGS.target,\n            params=params,\n            work_dir=ARGS.work_dir,\n            max_trials_global=ARGS.num_trials,\n            num_trials_per_iter=64,\n            runner=ms.runner.RPCRunner(  # type: ignore\n                rpc_config=ARGS.rpc_config,\n                evaluator_config=ms.runner.EvaluatorConfig(\n                    number=ARGS.number,\n                    repeat=ARGS.repeat,\n                    min_repeat_ms=ARGS.min_repeat_ms,\n                    enable_cpu_cache_flush=ARGS.cpu_flush,\n                ),\n                alloc_repeat=1,\n            ),\n            cost_model=ms.cost_model.XGBModel(  # type: ignore\n                extractor=ms.feature_extractor.PerStoreFeature(),\n                adaptive_training=ARGS.adaptive_training,\n            ),\n            strategy=ms.search_strategy.EvolutionarySearch(),\n        )\n        lib = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=ARGS.target,\n            params=params,\n            backend=ARGS.backend,\n        )\n\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    run_module_via_rpc(\n        rpc_config=ARGS.rpc_config,\n        lib=lib,\n        dev_type=ARGS.target.kind.name,\n        args=input_data,\n        continuation=create_timer(ARGS.backend),\n        backend=ARGS.backend,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/tune_relay.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport argparse\nimport json\nimport logging\nfrom distutils.util import strtobool\nfrom typing import Dict\n\nimport numpy as np  # type: ignore\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.meta_schedule.testing.tune_utils import create_timer, generate_input_data\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--workload\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--input-shape\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--layout\",\n        type=str,\n        default=None,\n    )\n    args.add_argument(\n        \"--cache-dir\",\n        type=str,\n        default=None,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    args.add_argument(\n        \"--backend\",\n        type=str,\n        choices=[\"graph\", \"vm\"],\n        help=\"example: graph / vm\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.input_shape = json.loads(parsed.input_shape)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    return parsed\n\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\nARGS = _parse_args()\n\n\ndef main():\n    describe()\n    print(f\"Workload: {ARGS.workload}\")\n\n    mod, params, (input_name, input_shape, input_dtype) = get_network(\n        ARGS.workload,\n        ARGS.input_shape,\n        layout=ARGS.layout,\n        cache_dir=ARGS.cache_dir,\n    )\n    input_info = [\n        {\n            \"name\": input_name,\n            \"shape\": input_shape,\n            \"dtype\": input_dtype,\n        },\n    ]\n    input_data: Dict[str, np.ndarray] = {\n        item[\"name\"]: generate_input_data(  # type: ignore\n            item[\"shape\"],  # type: ignore\n            item[\"dtype\"],  # type: ignore\n        )\n        for item in input_info\n    }\n    for item in input_info:\n        print(f\"  input_name : {item['name']}\")\n        print(f\"  input_shape: {item['shape']}\")\n        print(f\"  input_dtype: {item['dtype']}\")\n\n    with ms.Profiler() as profiler:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=ARGS.target,\n            work_dir=ARGS.work_dir,\n            max_trials_global=ARGS.num_trials,\n            num_trials_per_iter=64,\n            params=params,\n            runner=ms.runner.RPCRunner(  # type: ignore\n                rpc_config=ARGS.rpc_config,\n                evaluator_config=ms.runner.EvaluatorConfig(\n                    number=ARGS.number,\n                    repeat=ARGS.repeat,\n                    min_repeat_ms=ARGS.min_repeat_ms,\n                    enable_cpu_cache_flush=ARGS.cpu_flush,\n                ),\n                alloc_repeat=1,\n            ),\n            cost_model=ms.cost_model.XGBModel(  # type: ignore\n                extractor=ms.feature_extractor.PerStoreFeature(),\n                adaptive_training=ARGS.adaptive_training,\n            ),\n            strategy=ms.search_strategy.EvolutionarySearch(),\n        )\n        lib = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=ARGS.target,\n            params=params,\n            backend=ARGS.backend,\n        )\n\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    run_module_via_rpc(\n        rpc_config=ARGS.rpc_config,\n        lib=lib,\n        dev_type=ARGS.target.kind.name,\n        args=input_data,\n        continuation=create_timer(ARGS.backend),\n        backend=ARGS.backend,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/tune_te.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport argparse\nimport logging\nfrom distutils.util import strtobool\nfrom typing import Optional\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.support import describe\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--workload\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--target\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--num-trials\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--adaptive-training\",\n        type=lambda x: bool(strtobool(x)),\n        required=False,\n        help=\"example: True / False\",\n        default=True,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=60,\n    )\n    return parsed\n\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\nARGS = _parse_args()\n\n\ndef main():\n    describe()\n    print(f\"Workload: {ARGS.workload}\")\n    with ms.Profiler() as profiler:\n        sch: Optional[tir.Schedule] = ms.tir_integration.tune_tir(\n            mod=create_te_workload(ARGS.workload, 0),\n            target=ARGS.target,\n            work_dir=ARGS.work_dir,\n            max_trials_global=ARGS.num_trials,\n            num_trials_per_iter=64,\n            runner=ms.runner.RPCRunner(  # type: ignore\n                rpc_config=ARGS.rpc_config,\n                evaluator_config=ms.runner.EvaluatorConfig(\n                    number=ARGS.number,\n                    repeat=ARGS.repeat,\n                    min_repeat_ms=ARGS.min_repeat_ms,\n                    enable_cpu_cache_flush=ARGS.cpu_flush,\n                ),\n                alloc_repeat=1,\n            ),\n            cost_model=ms.cost_model.XGBModel(  # type: ignore\n                extractor=ms.feature_extractor.PerStoreFeature(),\n                adaptive_training=ARGS.adaptive_training,\n            ),\n            strategy=ms.search_strategy.EvolutionarySearch(),\n            task_name=ARGS.workload,\n        )\n\n    print(\"Tuning Time:\")\n    print(profiler.table())\n\n    if sch is None:\n        print(\"No valid schedule found!\")\n    else:\n        print(sch.mod.script())\n        print(sch.trace)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/tune_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testing utility functions in meta schedule\"\"\"\nfrom typing import Callable, Optional, Union, List, Dict\nfrom statistics import median\nimport json\nimport warnings\nimport numpy as np  # type: ignore\n\nimport tvm\nfrom tvm.runtime import NDArray\n\n\ndef generate_input_data(\n    input_shape: List[int],\n    input_dtype: str,\n    *,\n    low: Optional[int] = None,\n    high: Optional[int] = None,\n) -> np.ndarray:\n    \"\"\"Generate input date with given shape and data type.\n\n    Parameters\n    ----------\n    input_shape : List[int]\n        The shape of the input data.\n    input_dtype : str\n        The data type of the input date.\n\n    Returns\n    -------\n    input_data : np.ndarray\n        The generated input data with given shape and data type in numpy ndarray.\n    \"\"\"\n    if input_dtype.startswith(\"float\"):\n        return np.random.uniform(size=input_shape).astype(input_dtype)\n    if low is None or high is None:\n        warnings.warn(\n            f\"Model input value range for shape {input_shape} of {input_dtype} is not set!\"\n        )\n    range_map = {\n        \"uint8\": (0, 255),\n        \"int8\": (-128, 127),\n        \"int32\": (0, 10000),\n        \"int64\": (0, 10000),\n    }\n    if input_dtype in range_map:\n        _low, _high = range_map[input_dtype]\n        return np.random.randint(\n            low=_low if low is None else low,\n            high=_high if high is None else high,\n            size=input_shape,\n            dtype=input_dtype,\n        )\n    raise ValueError(\"Unsupported input datatype!\")\n\n\ndef create_timer(backend: str) -> Callable:\n    \"\"\"Create a function to run and benchmark the performance of whole given runtime module,\n    or Executable in relay vm.\n\n    Parameters\n    ----------\n    backend : str\n        The backend to use, graph / vm.\n\n    Returns\n    -------\n    func : Callable\n        The function to benchmark the workload.\n    \"\"\"\n\n    def f_timer(\n        rt_mod: Union[tvm.runtime.Module, tvm.runtime.vm.Executable],\n        dev: tvm.runtime.Device,\n        input_data: Dict[str, NDArray],\n    ) -> None:\n        \"\"\"Run and benchmark the given runtime module, print out the result.\n\n        Parameters\n        ----------\n        rt_mod : Union[tvm.runtime.Module, tvm.runtime.vm.Executable]\n            The runtime module or vm executable.\n        dev : tvm.runtime.Device\n            The device type to run workload.\n        input_data : Dict[str, np.ndarray]\n            The input data as a dictionary.\n        \"\"\"\n        from tvm.contrib.graph_executor import GraphModule  # pylint:disable=import-outside-toplevel\n        from tvm.runtime.vm import VirtualMachine  # pylint:disable=import-outside-toplevel\n\n        try:\n            if backend == \"vm\":\n                vm = VirtualMachine(rt_mod, dev)  # pylint: disable=invalid-name\n                ftimer = vm.benchmark(\n                    dev, min_repeat_ms=500, repeat=5, number=1, end_to_end=False, **input_data\n                )\n            elif backend == \"graph\":\n                mod = GraphModule(rt_mod[\"default\"](dev))\n                for input_name, input_value in input_data.items():\n                    mod.set_input(input_name, input_value)\n                ftimer = mod.module.time_evaluator(\n                    \"run\", dev, min_repeat_ms=500, repeat=5, number=1\n                )()\n            else:\n                raise ValueError(f\"Backend {backend} not supported in f_timer!\")\n\n            results = list(np.array(ftimer.results) * 1000.0)  # type: ignore\n\n            print(\"Running time in time_evaluator: \", results)\n            print(\"-------------------------------\")\n            print(f\"    Min (ms) : {min(results)}\")\n            print(f\"    Max (ms) : {max(results)}\")\n            print(f\" Median (ms) : {median(results)}\")\n            print(f\"Average (ms) : {sum(results) / len(results)}\")\n        except Exception as exc:  # pylint: disable=broad-except\n            print(\n                f\"Run module f_timer via RPC failed, exception: {exc}\",\n            )\n\n    return f_timer\n\n\ndef create_time_per_layer(graph: str) -> Callable:\n    \"\"\"Create a function to run and benchmark the per-layer performance of given runtime module,\n    given the graph output of the module from graph compiler.\n\n    Parameters\n    ----------\n    graph : str\n        The json format graph output of the module from graph compiler.\n\n    Returns\n    -------\n    func : Callable\n        The function using the json format graph.\n    \"\"\"\n\n    def f_time_per_layer(\n        rt_mod: tvm.runtime.Module,\n        dev: tvm.runtime.Device,\n        input_data: Dict[str, NDArray],\n    ) -> None:\n        \"\"\"Run and benchmark the per-layer performance of given runtime module,\n        print out the result.\n\n        Parameters\n        ----------\n        rt_mod : tvm.runtime.Module\n            The runtime module.\n        dev : tvm.runtime.Device\n            The device type to run workload.\n        input_data : Dict[str, np.ndarray]\n            The input data as a dictionary.\n        \"\"\"\n        # pylint:disable=import-outside-toplevel\n        from tvm.contrib.debugger.debug_executor import create\n\n        # pylint:enable=import-outside-toplevel\n\n        try:\n            mod = create(graph, rt_mod, dev)\n            for input_name, input_value in input_data.items():\n                mod.set_input(input_name, input_value)\n            graph_nodes = [n[\"name\"] for n in json.loads(graph)[\"nodes\"]]\n            graph_time = mod.run_individual(number=10, repeat=1, min_repeat_ms=5000)\n\n            print(\"Running time of each layer:\")\n            print(\"---------------------------\")\n            print(\"|graph_nodes| = \", len(graph_nodes))\n            print(\"|graph_time| = \", len(graph_time))\n\n            for k, v in zip(graph_nodes, graph_time):\n                print(k, float(v) * 1e6, \"us\")\n        except Exception as exc:  # pylint: disable=broad-except\n            print(\n                f\"Run module f_time_per_layer via RPC failed, exception: {exc}\",\n            )\n\n    return f_time_per_layer\n\n\ndef create_calculator(backend: str) -> Callable:\n    \"\"\"Create a function to fetch the computing result of running the given runtime module.\n\n    Parameters\n    ----------\n    backend : str\n        The backend to use, only tir is supported for now.\n\n    Returns\n    -------\n    func : Callable\n        The function to fetch the computing result.\n    \"\"\"\n\n    def f_calculator(\n        rt_mod: tvm.runtime.Module,\n        dev: tvm.runtime.Device,  # pylint: disable=unused-argument\n        input_data: Dict[str, NDArray],\n    ) -> List[NDArray]:\n        \"\"\"Fetch the result of running the given runtime module.\n\n        Parameters\n        ----------\n        rt_mod : Union[tvm.runtime.Module, tvm.runtime.vm.Executable]\n            The runtime module or vm executable.\n        dev : tvm.device\n            The device type to run workload.\n        input_data : Dict[str, np.ndarray]\n            The input data as a dictionary.\n        \"\"\"\n        try:\n            if backend == \"tir\":\n                data = [v for _, v in sorted(input_data.items(), key=lambda x: x[0])]\n                rt_mod(*data)\n                return data\n            else:\n                raise ValueError(f\"Backend {backend} not supported in f_calculator!\")\n\n        except Exception as exc:  # pylint: disable=broad-except\n            print(\n                f\"Run module f_calculator via RPC failed, exception: {exc}\",\n            )\n            return None\n\n    return f_calculator\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/testing/validate_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"JSON Database validation script\"\"\"\nfrom typing import Union, Callable, List\nfrom distutils.util import strtobool\nimport argparse\nimport logging\nimport warnings\nimport numpy as np  # type: ignore\n\nimport tvm\nfrom tvm.target import Target\nfrom tvm.ir import IRModule\nfrom tvm.tir import Schedule\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.tune_utils import create_calculator, generate_input_data\nfrom tvm._ffi import get_global_func, register_func\nfrom tvm.support import describe\n\nDELIMITOR = \"\\n\" + \"-\" * 30 + \"\\n\"\n\n\ndef _parse_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--work-dir\",\n        type=str,\n        required=True,\n        help=\"The path to the work directory containing database files.\",\n    )\n    args.add_argument(\n        \"--target\",\n        type=Target,\n        required=True,\n    )\n    args.add_argument(\n        \"--baseline-target\",\n        type=Target,\n        default=\"llvm -num-cores=1\",\n        required=False,\n        help=\"The baseline target to compile the original module.\",\n    )\n    args.add_argument(\n        \"--rpc-host\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-port\",\n        type=int,\n        required=True,\n    )\n    args.add_argument(\n        \"--rpc-key\",\n        type=str,\n        required=True,\n    )\n    args.add_argument(\n        \"--number\",\n        type=int,\n        default=3,\n    )\n    args.add_argument(\n        \"--repeat\",\n        type=int,\n        default=1,\n    )\n    args.add_argument(\n        \"--min-repeat-ms\",\n        type=int,\n        default=100,\n    )\n    args.add_argument(\n        \"--cpu-flush\",\n        type=lambda x: bool(strtobool(x)),\n        help=\"example: True / False\",\n        required=True,\n    )\n    parsed = args.parse_args()\n    parsed.target = tvm.target.Target(parsed.target)\n    parsed.rpc_config = ms.runner.RPCConfig(\n        tracker_host=parsed.rpc_host,\n        tracker_port=parsed.rpc_port,\n        tracker_key=parsed.rpc_key,\n        session_timeout_sec=600,\n    )\n    if parsed.cpu_flush and parsed.target.kind.name != \"llvm\":\n        warnings.warn(\"cpu_flush is only supported on llvm target\")\n    return parsed\n\n\n# logging\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\n\n# arg parser\nARGS = _parse_args()\n\n\n@register_func(\"tvm.meta_schedule.testing.default_input_generator\")\ndef default_input_generator(mod: IRModule) -> List[tvm.nd.NDArray]:\n    args_info = ms.arg_info.TensorInfo.from_prim_func(mod[\"main\"])\n    inputs = [\n        tvm.nd.array(generate_input_data(input_shape=arg_info.shape, input_dtype=arg_info.dtype))\n        for arg_info in args_info\n    ]\n    return inputs\n\n\n@register_func(\"tvm.meta_schedule.testing.default_check_metric\")\ndef default_check_metric(a: List[tvm.nd.NDArray], b: List[tvm.nd.NDArray]) -> bool:\n    assert len(a) == len(b), \"Different number of outputs from two modules\"\n    for i, _ in enumerate(a):\n        if not np.allclose(a[i].numpy(), b[i].numpy(), rtol=1e-3, atol=2e-3):\n            return False\n    return True\n\n\ndef validate_correctness(\n    original_mod: IRModule,  # compiled for \"baseline_target\"\n    scheduled_mod: IRModule,  # compiled for \"target\"\n    *,\n    baseline_target: Target,\n    target: Target,\n    dev_type: str,\n    rpc_config: ms.runner.RPCConfig,\n    f_input_generator: Union[\n        str, Callable[[IRModule], List[tvm.nd.NDArray]]\n    ] = default_input_generator,\n    f_check_metric: Union[\n        str, Callable[[tvm.nd.NDArray, tvm.nd.NDArray], bool]\n    ] = default_check_metric,\n) -> bool:\n    \"\"\"Function to validate the correctness of a scheduled module.\n\n    Parameters\n    ----------\n    original_mod : IRModule\n        The original module to be compiled.\n    scheduled_mod : IRModule\n        The scheduled module to be compiled.\n    baseline_target : Target\n        The baseline target to compile the original module.\n    target : Target\n        The target to compile the scheduled module.\n    dev_type : str\n        The device type to run the module via rpc.\n    rpc_config : RPCConfig\n        The RPCConfig to run the scheduled module.\n    f_input_generator : Union[str, Callable]\n        The function to generate the input data.\n    f_check_metric : Union[str, Callable]\n        The function to check the metric.\n\n    Returns\n    -------\n    result : bool\n        The result of the validation.\n    \"\"\"\n\n    def to_numpy(a: List[tvm.nd.NDArray]) -> List[np.ndarray]:\n        \"\"\"Convert a list of TVM NDArray to a list of numpy array\"\"\"\n        assert a is not None, \"Empty result cannot be converted to numpy\"\n        return [x.numpy() for x in a]\n\n    def to_tvm_ndarray(a: List[np.ndarray]) -> List[tvm.nd.NDArray]:\n        \"\"\"Convert a list of numpy array to a list of TVM NDArray\"\"\"\n        assert a is not None, \"Empty result cannot be converted to TVM NDArray\"\n        return [tvm.nd.array(x) for x in a]\n\n    def build_and_run(mod: IRModule, target: Target, dev_type: str) -> np.ndarray:\n        \"\"\"Build and run the module on the target device.\"\"\"\n        rt_mod = tvm.build(mod, target=target)\n        return run_module_via_rpc(\n            rpc_config=rpc_config,\n            lib=rt_mod,\n            dev_type=dev_type,\n            args={i: v for i, v in enumerate(inputs)},  # pylint: disable=unnecessary-comprehension\n            continuation=create_calculator(backend=\"tir\"),\n            backend=\"tir\",\n        )\n\n    # fetch functions & prepare inputs\n    if isinstance(f_input_generator, str):\n        f_input_generator = get_global_func(f_input_generator)\n    if isinstance(f_check_metric, str):\n        f_check_metric = get_global_func(f_check_metric)\n    inputs = to_numpy(f_input_generator(original_mod))  # type: ignore\n    # build & run original result\n    original_res = to_numpy(build_and_run(original_mod, target=baseline_target, dev_type=\"cpu\"))\n    scheduled_res = to_numpy(build_and_run(scheduled_mod, target=target, dev_type=dev_type))\n    # check metric\n    if f_check_metric(to_tvm_ndarray(original_res), to_tvm_ndarray(scheduled_res)):  # type: ignore\n        return True\n    else:\n        print(\n            (\"\\n\\n\").join(\n                [\n                    \"Validation failed!\",\n                    \"Original Result:\" + DELIMITOR + str(original_res),\n                    \"Scheduled Result:\" + DELIMITOR + str(scheduled_res),\n                    \"Input:\" + DELIMITOR + str(inputs),\n                    \"Original IRModule:\" + DELIMITOR + original_mod.script(),\n                    \"Scheduled IRModule:\" + DELIMITOR + scheduled_mod.script(),\n                ]\n            )\n        )\n        return False\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    describe()\n    database = ms.database.create(work_dir=ARGS.work_dir)\n    target = ARGS.target\n    if target.kind.name == \"llvm\":\n        dev_type = \"cpu\"\n    elif target.kind.name == \"cuda\":\n        dev_type = \"cuda\"\n    else:\n        raise RuntimeError(f\"Unsupported target kind: {target.kind.name}\")\n    records = database.get_all_tuning_records()\n    with ms.Profiler() as profiler:\n        for i, record in enumerate(records):\n            scope_name = f\"validate #{i}\"\n            with profiler.timeit(scope_name):\n                original_mod = record.workload.mod\n                sch = Schedule(original_mod)\n                record.trace.apply_to_schedule(sch=sch, remove_postproc=False)\n                scheduled_mod = sch.mod\n                is_success = False\n                try:\n                    is_success = validate_correctness(\n                        original_mod=original_mod,\n                        scheduled_mod=scheduled_mod,\n                        target=target,\n                        baseline_target=ARGS.baseline_target,\n                        dev_type=dev_type,\n                        rpc_config=ARGS.rpc_config,\n                    )\n                except Exception as e:  # pylint: disable=broad-except, invalid-name\n                    print(\n                        (\"\\n\\n\").join(\n                            [\n                                \"Validation failed!\",\n                                \"Original IRModule:\" + DELIMITOR + original_mod.script(),\n                                \"Scheduled IRModule:\" + DELIMITOR + scheduled_mod.script(),\n                                \"Exception\" + DELIMITOR + str(e),\n                            ]\n                        )\n                    )\n            if is_success:\n                print(\n                    f\"Progress {i+1: 6d} / {len(records): 6d} checked,\"\n                    f\" used {float(profiler.get()[scope_name]): 3.3f} sec.\"\n                )\n            else:\n                return\n\n    print(\"Validation passed!\")\n    print(f\"Total time spent: {float(profiler.get()['Total']): 3.3f} sec.\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/tir_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"MetaSchedule-TIR integration\"\"\"\nfrom typing import Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\nfrom tvm import ir, tir\nfrom tvm.target import Target\n\nfrom .builder import Builder\nfrom .cost_model import CostModel\nfrom .database import Database\nfrom .logging import get_loggers_from_work_dir\nfrom .measure_callback import MeasureCallback\nfrom .runner import Runner\nfrom .search_strategy import SearchStrategy\nfrom .space_generator import SpaceGenerator\nfrom .task_scheduler import TaskScheduler\nfrom .tune import tune_tasks\nfrom .tune_context import TuneContext, _normalize_mod\nfrom .utils import fork_seed\n\n\ndef tune_tir(\n    mod: Union[ir.IRModule, tir.PrimFunc],\n    target: Union[str, Target],\n    work_dir: str,\n    max_trials_global: int,\n    *,\n    num_trials_per_iter: int = 64,\n    builder: Builder.BuilderType = \"local\",\n    runner: Runner.RunnerType = \"local\",\n    database: Database.DatabaseType = \"json\",\n    cost_model: CostModel.CostModelType = \"xgb\",\n    measure_callbacks: MeasureCallback.CallbackListType = \"default\",\n    task_scheduler: TaskScheduler.TaskSchedulerType = \"round-robin\",\n    space: SpaceGenerator.SpaceGeneratorType = \"post-order-apply\",\n    strategy: SearchStrategy.SearchStrategyType = \"evolutionary\",\n    task_name: str = \"main\",\n    num_threads: Union[Literal[\"physical\", \"logical\"], int] = \"physical\",\n    seed: Optional[int] = None,\n) -> Database:\n    \"\"\"Tune a TIR function.\n\n    Parameters\n    ----------\n    mod : Union[ir.IRModule, tir.PrimFunc]\n        The TIR function to tune.\n    target : Union[str, Target]\n        The target to tune for.\n    work_dir : str\n        The working directory.\n    max_trials_global : int\n        The maximum number of trials to run globally.\n    num_trials_per_iter : int\n        The number of trials to run per iteration\n    builder : Builder.BuilderType\n        The builder.\n    runner : Runner.RunnerType\n        The runner.\n    database : Database.DatabaseType\n        The database.\n    cost_model : CostModel.CostModelType\n        The cost model.\n    measure_callbacks : MeasureCallback.CallbackListType\n        The measure callbacks.\n    task_scheduler : TaskScheduler.TaskSchedulerType\n        The task scheduler.\n    space : SpaceGenerator.SpaceGeneratorType\n        The space generator.\n    strategy : SearchStrategy.SearchStrategyType\n        The search strategy.\n    task_name : str\n        The name of the task.\n    num_threads : Union[Literal[\"physical\", \"logical\"], int]\n        The number of threads to use.\n    seed : Optional[int]\n        The seed for the random number generator.\n\n    Returns\n    -------\n    database : Database\n        The database with all tuning records\n    \"\"\"\n    (logger,) = get_loggers_from_work_dir(work_dir, [task_name])\n    (seed,) = fork_seed(seed, n=1)\n    return tune_tasks(\n        tasks=[\n            TuneContext(\n                mod=mod,\n                target=target,\n                space_generator=space,\n                search_strategy=strategy,\n                task_name=task_name,\n                logger=logger,\n                rand_state=seed,\n                num_threads=num_threads,\n            ).clone()\n        ],\n        task_weights=[1.0],\n        work_dir=work_dir,\n        max_trials_global=max_trials_global,\n        max_trials_per_task=max_trials_global,\n        num_trials_per_iter=num_trials_per_iter,\n        builder=builder,\n        runner=runner,\n        database=database,\n        cost_model=cost_model,\n        measure_callbacks=measure_callbacks,\n        task_scheduler=task_scheduler,\n    )\n\n\ndef compile_tir(\n    database: Database,\n    mod: Union[ir.IRModule, tir.PrimFunc],\n    target: Union[Target, str],\n) -> tir.Schedule:\n    \"\"\"Compile a TIR to tir.Schedule, according to the records in the database.\n\n    Parameters\n    ----------\n    database : Database\n        The database of tuning records.\n    mod : Union[ir.IRModule, tir.PrimFunc]\n        The TIR function to tune.\n    target : Union[str, Target]\n        The target to tune for.\n\n    Returns\n    -------\n    sch : tir.Schedule\n        The best schedule found in the database.\n    \"\"\"\n    mod = _normalize_mod(mod)\n    if not isinstance(target, Target):\n        target = Target(target)\n    return database.query_schedule(mod, target, workload_name=\"main\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/trace_apply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Specialized applications of trace\"\"\"\nfrom ..tir.schedule import Schedule, Trace\nfrom ..target import Target\nfrom . import _ffi_api\n\n\ndef schedule_using_anchor_trace(sch: Schedule, anchor_trace: Trace, target: Target) -> None:\n    \"\"\"Apply the trace from a TIR module whose anchor block is the same but fused elemewise op\n    blocks differ. This function can be used for transferring a trace tuned on a conv2d -> add\n    subgraph to other subgraphs having the same conv2d workload, for example. We call such trace\n    an \"anchor trace\". Those blocks that are not scheduled by the given anchor trace will be either\n    inlined or parallelized.\n\n    Parameters\n    ----------\n    sch : Schedule\n        The target schedule\n    anchor_trace: Trace\n        The trace generated for other TIR module having the same anchor block\n    target : tvm.target.Target\n        The compilation target\n    \"\"\"\n    _ffi_api.ScheduleUsingAnchorTrace(sch, anchor_trace, target)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/tune.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The core tuning API\"\"\"\nfrom typing import List, Optional\n\nfrom .builder import Builder\nfrom .cost_model import CostModel\nfrom .database import Database\nfrom .measure_callback import MeasureCallback\nfrom .runner import Runner\nfrom .task_scheduler import TaskScheduler\nfrom .tune_context import TuneContext\n\n\ndef tune_tasks(\n    *,\n    tasks: List[TuneContext],\n    task_weights: List[float],\n    work_dir: str,\n    max_trials_global: int,\n    max_trials_per_task: Optional[int] = None,\n    num_trials_per_iter: int = 64,\n    builder: Builder.BuilderType = \"local\",\n    runner: Runner.RunnerType = \"local\",\n    database: Database.DatabaseType = \"json\",\n    cost_model: CostModel.CostModelType = \"xgb\",\n    measure_callbacks: MeasureCallback.CallbackListType = \"default\",\n    task_scheduler: TaskScheduler.TaskSchedulerType = \"gradient\",\n    module_equality: str = \"structural\",\n) -> Database:\n    \"\"\"Tune a list of tasks. Using a task scheduler.\n\n    Parameters\n    ----------\n    tasks : List[TuneContext]\n        The list of tasks to tune.\n    task_weights : List[float]\n        The weight of each task.\n    work_dir : str\n        The working directory.\n    max_trials_global : int\n        The maximum number of trials to run globally.\n    max_trials_per_task : Optional[int]\n        The maximum number of trials to run per task.\n    num_trials_per_iter : int\n        The number of trials to run per iteration\n    builder : Builder.BuilderType\n        The builder.\n    runner : Runner.RunnerType\n        The runner.\n    database : Database.DatabaseType\n        The database.\n    cost_model : CostModel.CostModelType\n        The cost model.\n    measure_callbacks : MeasureCallback.CallbackListType\n        The measure callbacks.\n    task_scheduler : TaskScheduler.TaskSchedulerType\n        The task scheduler.\n    module_equality : Optional[str]\n        A string to specify the module equality testing and hashing method.\n        It must be one of the followings:\n          - \"structural\": Use StructuralEqual/Hash\n          - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n                              equality testing and hashing.\n          - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n                            given module. The \"ignore-ndarray\" varint is used for the extracted\n                            blocks or in case no anchor block is found.\n                            For the definition of the anchor block, see tir/analysis/analysis.py.\n\n    Returns\n    -------\n    database : Database\n        The database with all tuning records\n    \"\"\"\n    if len(tasks) != len(task_weights):\n        raise ValueError(\n            f\"Length of tasks ({len(tasks)}) and task_weights ({len(task_weights)}) do not match.\"\n        )\n    if max_trials_per_task is None:\n        max_trials_per_task = max_trials_global\n    if not isinstance(builder, Builder):\n        builder = Builder.create(builder)\n    if not isinstance(runner, Runner):\n        runner = Runner.create(runner)\n    if database == \"json\":\n        database = Database.create(database, work_dir=work_dir, module_equality=module_equality)\n    elif not isinstance(database, Database):\n        database = Database.create(database, module_equality=module_equality)\n    if not isinstance(cost_model, CostModel):\n        cost_model = CostModel.create(cost_model)\n    if isinstance(measure_callbacks, MeasureCallback):\n        measure_callbacks = [measure_callbacks]\n    elif measure_callbacks == \"default\":\n        measure_callbacks = MeasureCallback.create(measure_callbacks)\n    if not isinstance(task_scheduler, TaskScheduler):\n        task_scheduler = TaskScheduler.create(task_scheduler)\n    task_scheduler.tune(\n        tasks=tasks,\n        task_weights=task_weights,\n        max_trials_global=max_trials_global,\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        builder=builder,\n        runner=runner,\n        measure_callbacks=measure_callbacks,\n        database=database,\n        cost_model=cost_model,\n    )\n    return database\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/tune_context.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Meta Schedule tuning context.\"\"\"\n\nfrom typing import TYPE_CHECKING, List, Optional, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nfrom tvm import IRModule\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.target import Target\nfrom tvm.tir import PrimFunc, Schedule\n\nfrom . import _ffi_api\nfrom .logging import Logger, get_logger, get_logging_func\nfrom .utils import cpu_count\n\nif TYPE_CHECKING:\n    from .cost_model import CostModel\n    from .database import Database\n    from .runner import RunnerResult\n    from .search_strategy import MeasureCandidate, SearchStrategy\n    from .space_generator import SpaceGenerator\n\n\ndef _normalize_mod(mod: Union[PrimFunc, IRModule]) -> IRModule:\n    \"\"\"Normalize the input to an IRModule\"\"\"\n    if isinstance(mod, PrimFunc):\n        mod = mod.with_attr(\"global_symbol\", \"main\")\n        mod = mod.with_attr(\"tir.noalias\", True)\n        mod = IRModule({\"main\": mod})\n    if not isinstance(mod, IRModule):\n        raise TypeError(f\"Expected `mod` to be PrimFunc or IRModule, but gets: {mod}\")\n    func_names = mod.get_global_vars()\n    (func_name,) = func_names\n    if len(func_names) == 1 and func_name.name_hint != \"main\":\n        mod = IRModule({\"main\": mod[func_name]})\n    return mod\n\n\n@register_object(\"meta_schedule.TuneContext\")\nclass TuneContext(Object):\n    \"\"\"The tune context class is designed to contain all resources for a tuning task.\n\n    Parameters\n    ----------\n    mod : Optional[IRModule] = None\n        The workload to be optimized.\n    target : Optional[Target] = None\n        The target to be optimized for.\n    space_generator : Union[None, ScheduleFnType, SpaceGenerator] = None\n        The design space generator.\n    search_strategy : Union[None, SearchStrategy] = None\n        The search strategy.\n        if None, the strategy is left blank.\n    task_name : Optional[str] = None\n        The name of the tuning task.\n    logger : logging.Logger\n        The logger for the tuning task.\n    rand_state : int = -1\n        The random state.\n        Need to be in integer in [1, 2^31-1], -1 means using random number.\n    num_threads : int = None\n        The number of threads to be used, None means using the logical cpu count.\n    \"\"\"\n\n    mod: Optional[IRModule]\n    target: Optional[Target]\n    space_generator: Optional[\"SpaceGenerator\"]\n    search_strategy: Optional[\"SearchStrategy\"]\n    task_name: str\n    logger: Optional[Logger]\n    rand_state: int\n    num_threads: int\n\n    def __init__(\n        self,\n        mod: Optional[IRModule] = None,\n        *,\n        target: Union[Target, str, None] = None,\n        space_generator: Union[\"SpaceGenerator.SpaceGeneratorType\", None] = None,\n        search_strategy: Union[\"SearchStrategy.SearchStrategyType\", None] = None,\n        task_name: str = \"main\",\n        rand_state: int = -1,\n        num_threads: Union[int, Literal[\"physical\", \"logical\"]] = \"physical\",\n        logger: Optional[Logger] = None,\n    ):\n        # pylint: disable=import-outside-toplevel\n        import tvm.tir.tensor_intrin  # pylint: disable=unused-import\n\n        from .search_strategy import SearchStrategy\n        from .space_generator import SpaceGenerator\n\n        # pylint: enable=import-outside-toplevel\n        if isinstance(mod, PrimFunc):\n            mod = _normalize_mod(mod)\n        if target is not None:\n            if not isinstance(target, Target):\n                target = Target(target)\n        if space_generator is not None:\n            if not isinstance(space_generator, SpaceGenerator):\n                space_generator = SpaceGenerator.create(space_generator)\n        if search_strategy is not None:\n            if not isinstance(search_strategy, SearchStrategy):\n                search_strategy = SearchStrategy.create(search_strategy)\n        if logger is None:\n            logger = get_logger(__name__)\n        if not isinstance(num_threads, int):\n            if num_threads == \"physical\":\n                num_threads = cpu_count(logical=False)\n            elif num_threads == \"logical\":\n                num_threads = cpu_count(logical=True)\n            else:\n                raise ValueError(\n                    f\"Invalid num_threads: {num_threads}, \"\n                    \"should be either an integer, 'physical', or 'logical'\"\n                )\n        self.__init_handle_by_constructor__(\n            _ffi_api.TuneContext,  # type: ignore # pylint: disable=no-member\n            mod,\n            target,\n            space_generator,\n            search_strategy,\n            task_name,\n            num_threads,\n            rand_state,\n            get_logging_func(logger),\n        )\n        _ffi_api.TuneContextInitialize(self)  # type: ignore # pylint: disable=no-member\n\n    def generate_design_space(self) -> List[Schedule]:\n        \"\"\"Generate design spaces given a module.\n\n        Delegated to self.space_generator.generate_design_space with self.mod\n\n        Returns\n        -------\n        design_spaces : List[Schedule]\n            The generated design spaces, i.e., schedules.\n        \"\"\"\n        if self.mod is None:\n            raise ValueError(\"`mod` is not provided. Please construct TuneContext with `mod`\")\n        if self.space_generator is None:\n            raise ValueError(\n                \"space_generator is not provided.\"\n                \"Please construct TuneContext with space_generator\"\n            )\n        return self.space_generator.generate_design_space(self.mod)\n\n    def pre_tuning(\n        self,\n        max_trials: int,\n        num_trials_per_iter: int = 64,\n        design_spaces: Optional[List[Schedule]] = None,\n        database: Optional[\"Database\"] = None,\n        cost_model: Optional[\"CostModel\"] = None,\n    ) -> None:\n        \"\"\"A method to be called for SearchStrategy to do necessary preparation before tuning.\n\n        Delegated to self.search_strategy.pre_tuning.\n\n        Parameters\n        ----------\n        max_trials : int\n            The maximum number of trials to be executed.\n        num_trials_per_iter : int = 64\n            The number of trials to be executed per iteration.\n        design_spaces : Optional[List[Schedule]]\n            The design spaces used during tuning process.\n            If None, use the outcome of `self.generate_design_space()`.\n        database : Optional[Database] = None\n            The database used during tuning process.\n            If None, and the search strategy is `EvolutionarySearch`,\n            then use `tvm.meta_schedule.database.MemoryDatabase`.\n        cost_model : Optional[CostModel] = None\n            The cost model used during tuning process.\n            If None, and the search strategy is `EvolutionarySearch`,\n            then use `tvm.meta_schedule.cost_model.RandomModel`.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from .cost_model import RandomModel\n        from .database import MemoryDatabase\n        from .search_strategy import EvolutionarySearch\n\n        # pylint: enable=import-outside-toplevel\n\n        if self.search_strategy is None:\n            raise ValueError(\n                \"search_strategy is not provided.\"\n                \"Please construct TuneContext with search_strategy\"\n            )\n        if design_spaces is None:\n            design_spaces = self.generate_design_space()\n        if database is None:\n            if isinstance(self.search_strategy, EvolutionarySearch):\n                database = MemoryDatabase()  # type: ignore\n        if cost_model is None:\n            if isinstance(self.search_strategy, EvolutionarySearch):\n                cost_model = RandomModel()  # type: ignore\n        return self.search_strategy.pre_tuning(\n            max_trials,\n            num_trials_per_iter,\n            design_spaces,\n            database,\n            cost_model,\n        )\n\n    def post_tuning(self) -> None:\n        \"\"\"A method to be called for SearchStrategy to do necessary cleanup after tuning.\n\n        Delegated to self.search_strategy.post_tuning.\n        \"\"\"\n        if self.search_strategy is None:\n            raise ValueError(\n                \"search_strategy is not provided.\"\n                \"Please construct TuneContext with search_strategy\"\n            )\n        return self.search_strategy.post_tuning()\n\n    def generate_measure_candidates(self) -> Optional[List[\"MeasureCandidate\"]]:\n        \"\"\"Generate a batch of measure candidates from design spaces for measurement.\n\n        Delegated to self.search_strategy.generate_measure_candidates.\n\n        Returns\n        -------\n        measure_candidates : Optional[List[IRModule]]\n            The measure candidates generated, None if search is finished.\n        \"\"\"\n        if self.search_strategy is None:\n            raise ValueError(\n                \"search_strategy is not provided.\"\n                \"Please construct TuneContext with search_strategy\"\n            )\n        return self.search_strategy.generate_measure_candidates()\n\n    def notify_runner_results(\n        self,\n        measure_candidates: List[\"MeasureCandidate\"],\n        results: List[\"RunnerResult\"],\n    ) -> None:\n        \"\"\"Update the state in SearchStrategy with profiling results.\n\n        Delegated to self.search_strategy.notify_runner_results.\n\n        Parameters\n        ----------\n        measure_candidates : List[MeasureCandidate]\n            The measure candidates for update.\n        results : List[RunnerResult]\n            The profiling results from the runner.\n        \"\"\"\n        if self.search_strategy is None:\n            raise ValueError(\n                \"search_strategy is not provided.\"\n                \"Please construct TuneContext with search_strategy\"\n            )\n        return self.search_strategy.notify_runner_results(measure_candidates, results)\n\n    def clone(self) -> \"TuneContext\":\n        \"\"\"Clone the TuneContext.\n\n        Returns\n        -------\n        cloned_context : TuneContext\n            The cloned TuneContext.\n        \"\"\"\n        return _ffi_api.TuneContextClone(self)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/meta_schedule/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for meta schedule\"\"\"\nimport ctypes\nimport os\nimport shutil\nfrom typing import Any, Callable, List, Optional, Union\n\nimport numpy as np  # type: ignore\nimport psutil  # type: ignore\nfrom tvm._ffi import get_global_func, register_func\nfrom tvm.error import TVMError\nfrom tvm.ir import Array, IRModule, Map\nfrom tvm.rpc import RPCSession\nfrom tvm.runtime import PackedFunc, String\nfrom tvm.tir import FloatImm, IntImm\n\n\ndef derived_object(cls: type) -> type:\n    \"\"\"A decorator to register derived subclasses for TVM objects.\n\n    Parameters\n    ----------\n    cls : type\n        The derived class to be registered.\n\n    Returns\n    -------\n    cls : type\n        The decorated TVM object.\n\n    Example\n    -------\n    .. code-block:: python\n\n        @register_object(\"meta_schedule.PyRunner\")\n        class _PyRunner(meta_schedule.Runner):\n            def __init__(self, f_run: Callable = None):\n                self.__init_handle_by_constructor__(_ffi_api.RunnerPyRunner, f_run)\n\n        class PyRunner:\n            _tvm_metadata = {\n                \"cls\": _PyRunner,\n                \"methods\": [\"run\"]\n            }\n            def run(self, runner_inputs):\n                raise NotImplementedError\n\n        @derived_object\n        class LocalRunner(PyRunner):\n            def run(self, runner_inputs):\n                ...\n    \"\"\"\n\n    import functools  # pylint: disable=import-outside-toplevel\n    import weakref  # pylint: disable=import-outside-toplevel\n\n    def _extract(inst: type, name: str):\n        \"\"\"Extract function from intrinsic class.\"\"\"\n\n        def method(*args, **kwargs):\n            return getattr(inst, name)(*args, **kwargs)\n\n        if getattr(base, name) is getattr(cls, name) and name != \"__str__\":\n            # for task scheduler return None means calling default function\n            # otherwise it will trigger a TVMError of method not implemented\n            # on the c++ side when you call the method, __str__ not required\n            return None\n        return method\n\n    assert isinstance(cls.__base__, type)\n    assert hasattr(\n        cls, \"_tvm_metadata\"\n    ), \"Please use the user-facing method overriding class, i.e., PyRunner.\"\n\n    base = cls.__base__\n    metadata = getattr(base, \"_tvm_metadata\")\n    fields = metadata.get(\"fields\", [])\n    methods = metadata.get(\"methods\", [])\n\n    class TVMDerivedObject(metadata[\"cls\"]):  # type: ignore\n        \"\"\"The derived object to avoid cyclic dependency.\"\"\"\n\n        def __init__(self, *args, **kwargs):\n            \"\"\"Constructor.\"\"\"\n            self.handle = None\n            self._inst = cls(*args, **kwargs)\n\n            super().__init__(\n                # the constructor's parameters, builder, runner, etc.\n                *[getattr(self._inst, name) for name in fields],\n                # the function methods, init_with_tune_context, build, run, etc.\n                *[_extract(self._inst, name) for name in methods],\n            )\n\n            # for task scheduler hybrid funcs in c++ & python side\n            # using weakref to avoid cyclic dependency\n            self._inst._outer = weakref.ref(self)\n\n        def __getattr__(self, name: str):\n            \"\"\"Bridge the attribute function.\"\"\"\n            try:\n                return self._inst.__getattribute__(name)\n            except AttributeError:\n                return super(TVMDerivedObject, self).__getattr__(name)\n\n        def __setattr__(self, name, value):\n            if name not in [\"_inst\", \"key\", \"handle\"]:\n                self._inst.__setattr__(name, value)\n            else:\n                super(TVMDerivedObject, self).__setattr__(name, value)\n\n    functools.update_wrapper(TVMDerivedObject.__init__, cls.__init__)  # type: ignore\n    TVMDerivedObject.__name__ = cls.__name__\n    TVMDerivedObject.__doc__ = cls.__doc__\n    TVMDerivedObject.__module__ = cls.__module__\n    return TVMDerivedObject\n\n\n@register_func(\"meta_schedule.cpu_count\")\ndef _cpu_count_impl(logical: bool = True) -> int:\n    \"\"\"Return the number of logical or physical CPUs in the system\n\n    Parameters\n    ----------\n    logical : bool = True\n        If True, return the number of logical CPUs, otherwise return the number of physical CPUs\n\n    Returns\n    -------\n    cpu_count : int\n        The number of logical or physical CPUs in the system\n\n    Note\n    ----\n    The meta schedule search infra intentionally does not adopt the following convention in TVM:\n    - C++ API `tvm::runtime::threading::MaxConcurrency()`\n    - Environment variable `TVM_NUM_THREADS` or\n    - Environment variable `OMP_NUM_THREADS`\n    This is because these variables are dedicated to controlling\n    the runtime behavior of generated kernels, instead of the host-side search.\n    Setting these variables may interfere the host-side search with profiling of generated kernels\n    when measuring locally.\n    \"\"\"\n    return psutil.cpu_count(logical=logical) or 1\n\n\ndef cpu_count(logical: bool = True) -> int:\n    \"\"\"Return the number of logical or physical CPUs in the system\n\n    Parameters\n    ----------\n    logical : bool = True\n        If True, return the number of logical CPUs, otherwise return the number of physical CPUs\n\n    Returns\n    -------\n    cpu_count : int\n        The number of logical or physical CPUs in the system\n\n    Note\n    ----\n    The meta schedule search infra intentionally does not adopt the following convention in TVM:\n    - C++ API `tvm::runtime::threading::MaxConcurrency()`\n    - Environment variable `TVM_NUM_THREADS` or\n    - Environment variable `OMP_NUM_THREADS`\n\n    This is because these variables are dedicated to controlling\n    the runtime behavior of generated kernels, instead of the host-side search.\n    Setting these variables may interfere the host-side search with profiling of generated kernels\n    when measuring locally.\n    \"\"\"\n    return _cpu_count_impl(logical)\n\n\n@register_func(\"meta_schedule.using_ipython\")\ndef _using_ipython() -> bool:\n    \"\"\"Return whether the current process is running in an IPython shell.\n\n    Returns\n    -------\n    result : bool\n        Whether the current process is running in an IPython shell.\n    \"\"\"\n    try:\n        return get_ipython().__class__.__name__ == \"ZMQInteractiveShell\"  # type: ignore\n    except NameError:\n        return False\n\n\n@register_func(\"meta_schedule.print_interactive_table\")\ndef print_interactive_table(data: str) -> None:\n    \"\"\"Print the dataframe interactive table in notebook.\n\n    Parameters\n    ----------\n    data : str\n        The serialized performance table from MetaSchedule table printer.\n    \"\"\"\n    import pandas as pd  # type: ignore # pylint: disable=import-outside-toplevel\n    from IPython.display import display  # type: ignore # pylint: disable=import-outside-toplevel\n\n    pd.set_option(\"display.max_rows\", None)\n    pd.set_option(\"display.max_colwidth\", None)\n    parsed = [\n        x.split(\"|\")[1:] for x in list(filter(lambda x: set(x) != {\"-\"}, data.strip().split(\"\\n\")))\n    ]\n    display(\n        pd.DataFrame(\n            parsed[1:],\n            columns=parsed[0],\n        )\n    )\n\n\ndef get_global_func_with_default_on_worker(\n    name: Union[None, str, Callable],\n    default: Callable,\n) -> Callable:\n    \"\"\"Get the registered global function on the worker process.\n\n    Parameters\n    ----------\n    name : Union[None, str, Callable]\n        If given a string, retrieve the function in TVM's global registry;\n        If given a python function, return it as it is;\n        Otherwise, return `default`.\n\n    default : Callable\n        The function to be returned if `name` is None.\n\n    Returns\n    -------\n    result : Callable\n        The retrieved global function or `default` if `name` is None\n    \"\"\"\n    if name is None:\n        return default\n    if callable(name):\n        return name\n    try:\n        return get_global_func(name)\n    except TVMError as error:\n        raise ValueError(\n            \"Function '{name}' is not registered on the worker process. \"\n            \"The build function and export function should be registered in the worker process. \"\n            \"Note that the worker process is only aware of functions registered in TVM package, \"\n            \"if there are extra functions to be registered, \"\n            \"please send the registration logic via initializer.\"\n        ) from error\n\n\ndef get_global_func_on_rpc_session(\n    session: RPCSession,\n    name: str,\n    extra_error_msg: Optional[str] = None,\n) -> PackedFunc:\n    \"\"\"Get a PackedFunc from the global registry from an RPCSession.\n\n    Parameters\n    ----------\n    session : RPCSession\n        The RPCSession to be retrieved from\n    name : str\n        The name of the PackedFunc\n    extra_error_msg : Optional[str]\n        Extra information to provide in the error message\n\n    Returns\n    -------\n    result : PackedFunc\n        The result\n    \"\"\"\n    try:\n        result = session.get_function(name)\n    except AttributeError as error:\n        error_msg = f'Unable to find function \"{name}\" on the remote RPC server.'\n        if extra_error_msg:\n            error_msg = f\"{error_msg} {extra_error_msg}\"\n        raise AttributeError(error_msg) from error\n    return result\n\n\n@register_func(\"meta_schedule.remove_build_dir\")\ndef remove_build_dir(artifact_path: str) -> None:\n    \"\"\"Clean up the build directory\"\"\"\n    shutil.rmtree(os.path.dirname(artifact_path))\n\n\ndef _json_de_tvm(obj: Any) -> Any:\n    \"\"\"Unpack a TVM nested container to a JSON object in python.\n\n    Parameters\n    ----------\n    obj : Any\n        The TVM nested container to be unpacked.\n\n    Returns\n    -------\n    result : Any\n        The unpacked json object.\n    \"\"\"\n    if obj is None:\n        return None\n    if isinstance(obj, (int, float)):\n        return obj\n    if isinstance(obj, (IntImm, FloatImm)):\n        return obj.value\n    if isinstance(obj, (str, String)):\n        return str(obj)\n    if isinstance(obj, Array):\n        return [_json_de_tvm(i) for i in obj]\n    if isinstance(obj, Map):\n        return {_json_de_tvm(k): _json_de_tvm(v) for k, v in obj.items()}\n    raise TypeError(\"Not supported type: \" + str(type(obj)))\n\n\ndef shash2hex(mod: IRModule) -> str:\n    \"\"\"Get the structural hash of a module.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The module to be hashed.\n\n    Returns\n    -------\n    result : str\n        The structural hash of the module.\n    \"\"\"\n    func = get_global_func(\"meta_schedule._SHash2Hex\")\n    return str(func(mod))\n\n\ndef _get_default_str(obj: Any) -> str:\n    return (\n        # pylint: disable=protected-access\n        f\"meta_schedule.{obj.__class__.__name__}\"\n        + f\"({_to_hex_address(obj._outer().handle)})\"  # type: ignore\n        # pylint: enable=protected-access\n    )\n\n\ndef _to_hex_address(handle: ctypes.c_void_p) -> str:\n    \"\"\"Get the hexadecimal address of a handle.\n    Parameters\n    ----------\n    handle : ctypes.c_void_p\n        The handle to be converted.\n    Returns\n    -------\n    result : str\n        The hexadecimal address of the handle.\n    \"\"\"\n    return hex(ctypes.cast(handle, ctypes.c_void_p).value)\n\n\ndef fork_seed(seed: Optional[int], n: int) -> List[int]:\n    # fmt: off\n    return np.random.RandomState(seed=seed).randint(1, 2 ** 30, size=n).tolist()\n    # fmt: on\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"MicroTVM module for bare-metal backends\"\"\"\nfrom .build import autotvm_build_func\nfrom .build import AutoTvmModuleLoader\nfrom .build import get_standalone_crt_dir\nfrom .build import get_microtvm_template_projects\n\nfrom .model_library_format import (\n    export_model_library_format,\n    UnsupportedInModelLibraryFormatError,\n)\nfrom .project import generate_project, GeneratedProject, TemplateProject\nfrom .session import (\n    create_local_graph_executor,\n    create_local_debug_executor,\n    Session,\n    SessionTerminatedError,\n)\nfrom .transport import TransportLogger\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Base definitions for MicroTVM\"\"\"\n\nimport tvm\nimport tvm._ffi\n\ntvm._ffi._init_api(\"tvm.micro\", \"tvm.micro.base\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/build.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines top-level glue functions for building microTVM artifacts.\"\"\"\n\nimport json\nimport logging\nimport os\nimport contextlib\nimport enum\n\nfrom typing import Union\nfrom .._ffi import libinfo\nfrom .. import rpc as _rpc\n\n\n_LOG = logging.getLogger(__name__)\n\n\nSTANDALONE_CRT_DIR = None\n\n\nclass MicroTVMTemplateProject(enum.Enum):\n    ZEPHYR = \"zephyr\"\n    ARDUINO = \"arduino\"\n    CRT = \"crt\"\n\n    @classmethod\n    def list(cls):\n        return list(map(lambda c: c.value, cls))\n\n\nclass CrtNotFoundError(Exception):\n    \"\"\"Raised when the standalone CRT dirtree cannot be found.\"\"\"\n\n\nclass MicroTVMTemplateProjectNotFoundError(Exception):\n    \"\"\"Raised when the microTVM template project dirtree cannot be found.\"\"\"\n\n\ndef get_standalone_crt_dir() -> str:\n    \"\"\"Find the standalone_crt directory.\n\n    Though the C runtime source lives in the tvm tree, it is intended to be distributed with any\n    binary build of TVM. This source tree is intended to be integrated into user projects to run\n    models targeted with --runtime=c.\n\n    Returns\n    -------\n    str :\n        The path to the standalone_crt\n    \"\"\"\n    global STANDALONE_CRT_DIR\n    if STANDALONE_CRT_DIR is None:\n        for path in libinfo.find_lib_path():\n            crt_path = os.path.join(os.path.dirname(path), \"standalone_crt\")\n            if os.path.isdir(crt_path):\n                STANDALONE_CRT_DIR = crt_path\n                break\n\n        else:\n            raise CrtNotFoundError()\n\n    return STANDALONE_CRT_DIR\n\n\ndef get_microtvm_template_projects(platform: str) -> str:\n    \"\"\"Find microTVM template project directory for specific platform.\n\n    Parameters\n    ----------\n    platform : str\n        Platform type which should be defined in MicroTVMTemplateProject.\n\n    Returns\n    -------\n    str :\n        Path to template project directory for platform.\n    \"\"\"\n    if platform not in MicroTVMTemplateProject.list():\n        raise ValueError(f\"platform {platform} is not supported.\")\n\n    if platform == MicroTVMTemplateProject.CRT.value:\n        return os.path.join(get_standalone_crt_dir(), \"template\", \"host\")\n\n    microtvm_template_projects = None\n    for path in libinfo.find_lib_path():\n        template_path = os.path.join(os.path.dirname(path), \"microtvm_template_projects\")\n        if os.path.isdir(template_path):\n            microtvm_template_projects = template_path\n            break\n    else:\n        raise MicroTVMTemplateProjectNotFoundError()\n\n    return os.path.join(microtvm_template_projects, platform)\n\n\nclass AutoTvmModuleLoader:\n    \"\"\"MicroTVM AutoTVM Module Loader\n\n    Parameters\n    ----------\n    template_project_dir : Union[os.PathLike, str]\n        project template path\n\n    project_options : dict\n        project generation option\n\n    project_dir: str\n        if use_existing is False: The path to save the generated microTVM Project.\n        if use_existing is True: The path to a generated microTVM Project for debugging.\n\n    use_existing: bool\n        skips the project generation and opens transport to the project at the project_dir address.\n    \"\"\"\n\n    def __init__(\n        self,\n        template_project_dir: Union[os.PathLike, str],\n        project_options: dict = None,\n        project_dir: Union[os.PathLike, str] = None,\n        use_existing: bool = False,\n    ):\n        self._project_options = project_options\n        self._use_existing = use_existing\n\n        if isinstance(template_project_dir, (os.PathLike, str)):\n            self._template_project_dir = str(template_project_dir)\n        elif not isinstance(template_project_dir, str):\n            raise TypeError(f\"Incorrect type {type(template_project_dir)}.\")\n\n        if isinstance(project_dir, (os.PathLike, str)):\n            self._project_dir = str(project_dir)\n        else:\n            self._project_dir = None\n\n    @contextlib.contextmanager\n    def __call__(self, remote_kw, build_result):\n        with open(build_result.filename, \"rb\") as build_file:\n            build_result_bin = build_file.read()\n\n        tracker = _rpc.connect_tracker(remote_kw[\"host\"], remote_kw[\"port\"])\n        remote = tracker.request(\n            remote_kw[\"device_key\"],\n            priority=remote_kw[\"priority\"],\n            session_timeout=remote_kw[\"timeout\"],\n            session_constructor_args=[\n                \"tvm.micro.compile_and_create_micro_session\",\n                build_result_bin,\n                self._template_project_dir,\n                json.dumps(self._project_options),\n                self._project_dir,\n                self._use_existing,\n            ],\n        )\n        system_lib = remote.get_function(\"runtime.SystemLib\")()\n        yield remote, system_lib\n\n\ndef autotvm_build_func():\n    \"\"\"A dummy build function which causes autotvm to use a different export format.\"\"\"\n\n\n# A sentinel value for the output format.\nautotvm_build_func.output_format = \".model-library-format\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/class_factory.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines a utility for representing deferred class instatiations as JSON.\"\"\"\n\nimport importlib\nimport json\nimport typing\n\n\nJsonSerializable = typing.Union[int, float, str, None, bool]\n\n\nclass SerializedFactoryError(Exception):\n    \"\"\"Raised when ClassFactory.from_json is invoked with an invalid JSON blob.\"\"\"\n\n\nclass ClassFactory:\n    \"\"\"Describes a JSON-serializable class instantiation, for use with the RPC server.\"\"\"\n\n    # When not None, the superclass from which all cls must derive.\n    SUPERCLASS = None\n\n    def __init__(\n        self,\n        cls: typing.Callable,\n        init_args: typing.List[JsonSerializable],\n        init_kw: typing.Dict[str, JsonSerializable],\n    ):\n        self.cls = cls\n        self.init_args = init_args\n        self.init_kw = init_kw\n\n    def override_kw(self, **kw_overrides):\n        kwargs = self.init_kw\n        if kw_overrides:\n            kwargs = dict(kwargs)\n            for k, v in kw_overrides.items():\n                kwargs[k] = v\n\n        return self.__class__(self.cls, self.init_args, kwargs)\n\n    def instantiate(self):\n        return self.cls(*self.init_args, **self.init_kw)\n\n    @property\n    def to_json(self):\n        return json.dumps(\n            {\n                \"cls\": \".\".join([self.cls.__module__, self.cls.__name__]),\n                \"init_args\": self.init_args,\n                \"init_kw\": self.init_kw,\n            }\n        )\n\n    EXPECTED_KEYS = (\"cls\", \"init_args\", \"init_kw\")\n\n    @classmethod\n    def from_json(cls, data):\n        \"\"\"Reconstruct a ClassFactory instance from its JSON representation.\n\n        Parameters\n        ----------\n        data : str\n            The JSON representation of the ClassFactory.\n\n        Returns\n        -------\n        ClassFactory :\n            The reconstructed ClassFactory instance.\n\n        Raises\n        ------\n        SerializedFactoryError :\n            If the JSON object represented by `data` is malformed.\n        \"\"\"\n        obj = json.loads(data)\n        if not isinstance(obj, dict):\n            raise SerializedFactoryError(f\"deserialized json payload: want dict, got: {obj!r}\")\n\n        for key in cls.EXPECTED_KEYS:\n            if key not in obj:\n                raise SerializedFactoryError(\n                    f\"deserialized json payload: expect key {key}, got: {obj!r}\"\n                )\n\n        cls_package_name, cls_name = obj[\"cls\"].rsplit(\".\", 1)\n        cls_package = importlib.import_module(cls_package_name)\n        cls_obj = getattr(cls_package, cls_name)\n        return cls(cls_obj, obj[\"init_args\"], obj[\"init_kw\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/contrib/stm32/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n\r\n\"\"\"Module container of STM32 code generator.\"\"\"\r\n\r\nfrom .emitter import CodeEmitter, get_input_tensor_name, get_output_tensor_name\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/contrib/stm32/emitter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=line-too-long\n\n\"\"\"Code emission for the STM32 targets.\"\"\"\n\nimport contextlib\nimport json\nimport os\nimport re\nimport shutil\nimport tarfile\nimport textwrap\n\nfrom datetime import datetime\n\nimport numpy as np\n\nimport tvm\nfrom tvm.contrib import utils\n\nAI_API_VERSION_MAJOR = 1\nAI_API_VERSION_MINOR = 0\nAI_API_VERSION_MICRO = 0\n\nAI_TOOLS_REVISION = \"v1\"\n\nDBAR = \"=\" * 60\n\n\ndef _fix_name(node_name):\n    \"\"\"Replace ':' with '_' in names like 'InputImg:0'\"\"\"\n    return node_name.replace(\":\", \"_\")\n\n\ndef get_input_tensor_name(node_name):\n    return _fix_name(node_name)\n\n\ndef get_output_tensor_name(node_name, idx):\n    return _fix_name(node_name) + \"_\" + str(idx)\n\n\ndef _get_node_args_name(node_name):\n    return _fix_name(node_name) + \"_args\"\n\n\ndef _get_node_arg_types_name(node_name):\n    return _fix_name(node_name) + \"_arg_type_ids\"\n\n\ndef _get_type_size(dltype):\n    if dltype in (\"uint64\", \"int64\"):\n        return 8\n    if dltype in (\"uint32\", \"int32\", \"float32\"):\n        return 4\n    if dltype in (\"uint16\", \"int16\"):\n        return 2\n    if dltype in (\"uint8\", \"int8\"):\n        return 1\n    raise ValueError(f\"Data type {dltype} is not supported\")\n\n\nC_TYPE_TO_DLTYPE = {\n    \"uint64\": \"kDLUInt, 64, 1\",\n    \"int64\": \"kDLInt, 64, 1\",\n    \"float32\": \"kDLFloat, 32, 1\",\n    \"uint32\": \"kDLUInt, 32, 1\",\n    \"int32\": \"kDLInt, 32, 1\",\n    \"uint16\": \"kDLUInt, 16, 1\",\n    \"int16\": \"kDLInt, 16, 1\",\n    \"uint8\": \"kDLUInt, 8, 1\",\n    \"int8\": \"kDLInt, 8, 1\",\n}\n\n\ndef _get_type_data(dltype):\n    try:\n        return C_TYPE_TO_DLTYPE[dltype]\n    except KeyError:\n        raise ValueError(f\"Data type {dltype} is not supported\")\n\n\ndef _get_aligned_offset(offset, dltype):\n    align = _get_type_size(dltype)\n    if offset % align != 0:\n        offset = offset + (align - offset % align)\n    return offset\n\n\ndef _get_num_tensor_elts(shape):\n    size = 1\n    for dim in shape:\n        size = size * dim\n    return size\n\n\ndef _get_tensor_size_bytes(dims, dltype):\n    size = _get_num_tensor_elts(dims)\n    return size * _get_type_size(dltype)\n\n\ndef _preprocess_code(src):\n    \"\"\"Hack the C code implementing the model.\"\"\"\n    dst = \"#include <stdio.h>\\n\" \"#include <math.h>\\n\\n\"\n    dst = dst + src\n    return dst\n\n\nclass CodeEmitter(object):\n    \"\"\"Code emitter class.\"\"\"\n\n    DATA_ALIGNMENT_BYTES = 8\n\n    def __init__(self, include_activations=True, include_inputs=True, include_outputs=True):\n        \"\"\"Initialize the Emitter instance.\n\n        Parameters\n        ----------\n        include_activations:\n            The Emitter allocates the storage for the activations data\n            and places it in a specific data section. If Falsr, the\n            main application is responsible for allocating the activations\n            storage. Default: True.\n\n        include_inputs/include_outputs:\n            The Emitter allocates the storage for the input/output data.\n            This storage is shared with the activations and placed in the\n            specific activations data section. If False, the main\n            application is responsible for allocating the input/output\n            data storage. Default: True.\n\n        Returns\n        -------\n            CodeEmitter object.\n\n        \"\"\"\n\n        # Static model: activations placed into a nn_data_act section\n        # Dynamic model: activations need to be malloc'ed by the\n        #   applications.\n        self.activations_static = include_activations\n\n        # Inputs/outputs may be allocated within the activations or\n        # separately.\n        # TODO: Separate the inputs from activations inside TVM.\n        if include_inputs:\n            assert (\n                self.activations_static == True\n            ), \"###Error: Static inputs are not allowed without activations.\"\n        self.inputs_static = include_inputs\n\n        if include_outputs:\n            assert (\n                self.activations_static == True\n            ), \"###Error: Static outputs are not allowed without activations.\"\n        self.outputs_static = include_outputs\n\n        # Parsed graph\n        self._nodes = []\n        self._arg_nodes = []\n        self._outputs = []\n        self._attrs = {}\n        self._node_row_ptr = []\n\n        # Parameters\n        self._params = {}\n\n        # Filled by data_placement()\n        self._weights = {}\n        self._activations = {}\n        self._input_data = {}\n        self._output_data = {}\n        self._nodes_size = 0\n        self._weights_size = 0\n        self._activations_size = 0\n\n        self._quantization = {}\n\n    def _extract_quantization_info(self, quantization):\n        \"\"\"Build dictionary with quantization infos.\"\"\"\n\n        for dl_tensor_name in self._input_data:\n            if dl_tensor_name in quantization:\n                self._quantization[dl_tensor_name] = quantization[dl_tensor_name]\n\n        # Matching outputs is more difficult because TVM does not preserve\n        # output tensor names.\n        # We only support models with a single output now.\n        assert len(self._output_data) == 1, \"Multiple outputs models are not yet supported.\"\n\n        for dl_tensor_name in self._output_data:\n            for name in quantization:\n                if name not in self._input_data:\n                    self._quantization[\"output\"] = quantization[name]\n                    break\n\n    def _get_node_arg_name(self, arg):\n        arg_nid = arg[0]\n        arg_idx = arg[1]\n        arg_node = self._nodes[arg_nid]\n        arg_name = self._nodes[arg_nid][\"name\"]\n        if arg_node[\"op\"] == \"null\":\n            # parameter\n            dl_tensor_name = get_input_tensor_name(arg_name)\n        elif arg_node[\"name\"] == \"reshape_nop\":\n            # Handle __nop\n            src = arg_node[\"inputs\"][0]\n            dl_tensor_name = self._get_node_arg_name(src)\n        else:\n            # activation\n            dl_tensor_name = get_output_tensor_name(arg_name, arg_idx)\n        return dl_tensor_name\n\n    def _tensor_is_output(self, nid, idx):\n        for out in self._outputs:\n            out_nid = out[0]\n            out_idx = out[1]\n            if out_nid == nid and out_idx == idx:\n                return True\n        return False\n\n    def _get_tensor_from_node(self, nid, idx):\n        # 'eid' is index into the dltype', 'shape', etc.\n        eid = self._node_row_ptr[nid] + idx\n        dltype = self._attrs[\"dltype\"][1][eid]\n        dims = self._attrs[\"shape\"][1][eid]\n        storage_id = self._attrs[\"storage_id\"][1][eid]\n        ndim = len(dims)\n        size = _get_tensor_size_bytes(dims, dltype)\n\n        tensor = {\n            \"dltype\": dltype,\n            \"ndim\": ndim,\n            \"dims\": dims,\n            \"strides\": None,\n            \"storage_id\": storage_id,\n            \"byte_offset\": 0,\n            \"offset\": 0,\n            \"size\": size,\n        }\n\n        return tensor\n\n    def _compute_data_placement(self):\n        \"\"\"Compute inputs, outputs, weight, activation sizes\"\"\"\n\n        self._inputs = self._arg_nodes.copy()\n\n        # weights:\n        offset = 0\n\n        for key in self._params:\n\n            # First, find the node in graph\n            nid = 0\n            for node in self._nodes:\n                if node[\"name\"] == key:\n                    break\n                nid += 1\n\n            dl_tensor_name = get_input_tensor_name(key)\n            tensor = self._get_tensor_from_node(nid, 0)\n\n            # Compute the offset\n            dltype = tensor[\"dltype\"]\n            aligned_offset = _get_aligned_offset(offset, dltype)\n            tensor[\"offset\"] = aligned_offset\n\n            for idx in self._arg_nodes:\n                node = self._nodes[idx]\n                node_name = node[\"name\"]\n                if node_name == key:\n                    self._inputs.remove(idx)\n\n            self._weights[dl_tensor_name] = tensor\n\n            # Next offset\n            offset = aligned_offset + tensor[\"size\"]\n\n        self._weights_size = offset\n\n        # activations:\n        buffer_list_ = {}\n\n        nid = 0\n        for node in self._nodes:\n\n            if node[\"op\"] == \"null\":\n                nid += 1\n                continue\n\n            if node[\"op\"] != \"tvm_op\":\n                raise ValueError(f\"Only TVM ops are supported\")\n\n            node_name = node[\"name\"]\n            node_attrs = node[\"attrs\"]\n            func_name = node_attrs[\"func_name\"]\n            num_outputs = int(node_attrs[\"num_outputs\"])\n\n            if func_name == \"__nop\":\n                assert node_name == \"reshape_nop\", f\"Unsupported __nop operator {node_name}.\"\n                assert num_outputs == 1\n                assert not self._tensor_is_output(nid, 0)\n                nid += 1\n                continue\n\n            for idx in range(num_outputs):\n\n                # Do not count the '_outputs'\n                if self._tensor_is_output(nid, idx):\n                    continue\n\n                dl_tensor_name = get_output_tensor_name(node_name, idx)\n                tensor = self._get_tensor_from_node(nid, idx)\n\n                # Remember this tensor with the storage id\n                storage_id = tensor[\"storage_id\"]\n                if storage_id not in buffer_list_:\n                    buffer_list_[storage_id] = []\n                buffer_entry = buffer_list_[storage_id]\n                buffer_entry.append(tensor)\n\n                self._activations[dl_tensor_name] = tensor\n\n            self._nodes_size = self._nodes_size + 1\n\n            nid += 1\n\n        # Compute '_input_data'\n        offset = 0\n        for nid in self._inputs:\n            node = self._nodes[nid]\n            node_name = node[\"name\"]\n\n            # Arthur: I suppose that input nodes only have a single\n            #         output dependency\n            dl_tensor_name = get_input_tensor_name(node_name)\n\n            # This tensor is at some index inside '_input_data' dictionary\n            # depending on the '_inputs' list order. We refer to this position\n            # when generating the XXX.h file.\n            tensor = self._get_tensor_from_node(nid, 0)\n\n            if self.inputs_static:\n\n                # Remember this tensor with the storage id\n                storage_id = tensor[\"storage_id\"]\n                if storage_id not in buffer_list_:\n                    buffer_list_[storage_id] = []\n                buffer_entry = buffer_list_[storage_id]\n                buffer_entry.append(tensor)\n            else:\n\n                # Compute the offset\n                dltype = tensor[\"dltype\"]\n                aligned_offset = _get_aligned_offset(offset, dltype)\n                tensor[\"offset\"] = aligned_offset\n\n            self._input_data[dl_tensor_name] = tensor\n\n            # Next offset\n            offset = aligned_offset + tensor[\"size\"]\n\n        # Compute '_output_data'\n        offset = 0\n        for output in self._outputs:\n            nid = output[0]\n            idx = output[1]\n\n            node = self._nodes[nid]\n            node_name = node[\"name\"]\n\n            dl_tensor_name = get_output_tensor_name(node_name, idx)\n\n            tensor = self._get_tensor_from_node(nid, idx)\n\n            if self.outputs_static:\n\n                # Remember this tensor with the storage id\n                storage_id = tensor[\"storage_id\"]\n                if storage_id not in buffer_list_:\n                    buffer_list_[storage_id] = []\n                buffer_entry = buffer_list_[storage_id]\n                buffer_entry.append(tensor)\n            else:\n\n                # Compute the offset\n                dltype = tensor[\"dltype\"]\n                aligned_offset = _get_aligned_offset(offset, dltype)\n                tensor[\"offset\"] = aligned_offset\n\n            self._output_data[dl_tensor_name] = tensor\n\n            # Next offset\n            offset = aligned_offset + tensor[\"size\"]\n\n        # Go over all storage IDs and compute offsets and _activations_size\n        offset = 0\n        for storage_id in buffer_list_:\n            buffer_entry = buffer_list_[storage_id]\n\n            new_offset = offset\n            for tensor in buffer_entry:\n                assert tensor[\"storage_id\"] == storage_id\n                dltype = tensor[\"dltype\"]\n                aligned_offset = _get_aligned_offset(offset, dltype)\n                tensor[\"offset\"] = aligned_offset\n                size = tensor[\"size\"]\n                if (aligned_offset + size) > new_offset:\n                    new_offset = aligned_offset + size\n            offset = new_offset\n\n        self._activations_size = offset\n\n    def _parse_model(self, quantization=None):\n        \"\"\"Parse the module. Build internal data structures.\n\n        Parameters\n        ----------\n        module : TVM module or ModuleLibraryFormat object\n           The module to parse\n\n        quantization: Dictionary\n           The quantization information for model inputs/outputs.\n        \"\"\"\n\n        for key in self._graph:\n            if key == \"nodes\":\n                self._nodes = self._graph[\"nodes\"]\n            elif key == \"arg_nodes\":\n                self._arg_nodes = self._graph[\"arg_nodes\"]\n            elif key == \"node_row_ptr\":\n                self._node_row_ptr = self._graph[\"node_row_ptr\"]\n            elif key == \"heads\":\n                self._outputs = self._graph[\"heads\"]\n            elif key == \"attrs\":\n                self._attrs = self._graph[\"attrs\"]\n            elif key == \"metadata\":\n                continue\n            else:\n                print(\"### Error: JSON key {} not supported\".format(key))\n                assert False\n\n        # Build all tensor lists\n        self._compute_data_placement()\n\n        # Extract quantization info for inputs/outputs\n        if quantization is not None:\n            self._extract_quantization_info(quantization)\n\n    def parse_library_format(self, model_library_format_path, quantization=None):\n        \"\"\"Parse the module. Build internal data structures.\n\n        Parameters\n        ----------\n        model_library_format_path :\n           The ModuleLibraryFormat object to parse\n\n        quantization: Dictionary\n           The quantization information for model inputs/outputs.\n        \"\"\"\n\n        temp_dir = utils.tempdir()\n        extract_path = temp_dir.relpath(\"extract\")\n        os.mkdir(extract_path)\n        with tarfile.TarFile(model_library_format_path) as f:\n            f.extractall(extract_path)\n\n        with open(os.path.join(extract_path, \"metadata.json\")) as metadata_f:\n            metadata = json.load(metadata_f)\n\n        all_module_names = []\n        for name in metadata[\"modules\"].keys():\n            all_module_names.append(name)\n        assert len(metadata[\"modules\"]) == 1, \"Multiple modules is not supported.\"\n\n        # Extract informations from the Model Library Format\n        graph_file = os.path.join(\n            extract_path, \"executor-config\", \"graph\", f\"{all_module_names[0]}.graph\"\n        )\n        with open(graph_file, \"r\") as f:\n            # returns JSON object as a dictionary\n            graph_dict = json.load(f)\n\n        params_dict = {}\n        param_file = os.path.join(extract_path, \"parameters\", \"default.params\")\n        with open(param_file, \"rb\") as f:\n            params = tvm.runtime.load_param_dict(f.read())\n\n            # Map -> Python Dict\n            tmp_dict = {}\n            for (k, v) in params.items():\n                tmp_dict[k] = v\n\n            # Sort params for debugging\n            for k in sorted(tmp_dict.keys()):\n                params_dict[k] = tmp_dict[k]\n\n        src_dir = os.path.join(extract_path, \"codegen\", \"host\", \"src\")\n        # List of strings from Model Library Format C files\n        src_files = []\n        for filename in os.listdir(src_dir):\n            with open(os.path.join(src_dir, filename), \"r\") as fin:\n                src = fin.read()\n                src_files.append(src)\n\n        self._graph = graph_dict\n        self._params = params_dict\n        self._lib = src_files\n\n        self._parse_model(quantization)\n\n    def parse_module(self, module, quantization=None):\n        \"\"\"Parse the module. Build internal data structures.\n\n        Parameters\n        ----------\n        module : TVM Runtime Module\n           The module to parse.\n\n        quantization: Dictionary\n           The quantization information for model inputs/outputs.\n        \"\"\"\n\n        graph = module.get_json()\n        if not isinstance(graph, (str,)):\n            try:\n                graph = graph._tvm_graph_json()\n            except AttributeError:\n                raise ValueError(\"Type %s is not supported\" % type(graph))\n\n        # Sort params for debugging\n        params_dict = {}\n        tmp_params = module.get_params()\n        for k in sorted(tmp_params.keys()):\n            params_dict[k] = tmp_params[k]\n\n        self._graph = json.loads(graph)\n        self._params = params_dict\n        self._lib = module.get_lib()\n\n        self._parse_model(quantization)\n\n    def _emit_params_data(self, name, out_h, out_c):\n        \"\"\"Emits the network_data[c,h] files with parameters.\"\"\"\n\n        name_upper = name.upper()\n\n        # XXX_data.h\n\n        out_h.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        #ifndef __{name_upper}_DATA_H_\n        #define __{name_upper}_DATA_H_\n\n        #include \\\"ai_runtime_api.h\\\"\n\n        AI_API_ENTRY\n        const ai_ptr ai_{name}_data_weights_get (void);\n\n        #endif /* __{name_upper}_DATA_H_ */\n        \"\"\"\n            )\n        )\n\n        # XXX_data.cc\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        #include \\\"{name}_data.h\\\"\n\n        const ai_ptr ai_{name}_data_weights_get (void)\n        {{\n          AI_ALIGNED({self.DATA_ALIGNMENT_BYTES}) static const __attribute__ ((section(\\\".nn_weights\\\"))) uint8_t s_{name}_weights[] = {{\n        \"\"\"\n            )\n        )\n\n        # Weights are arranged in the order of 'params_'\n        offset = 0\n\n        for key in self._params:\n            data = self._params[key]  # ND Array\n            npdata = data.asnumpy()\n            blob = npdata.tobytes()\n\n            out_c.write(f'// \"{key}\": \\n')\n            out_c.write(f\"\\t\")\n\n            count = 0\n\n            # Align by emitting garbage between un-aligned data\n            dl_tensor_name = get_input_tensor_name(key)\n            tensor = self._weights[dl_tensor_name]\n            tensor_offset = tensor[\"offset\"]\n            tensor_size = tensor[\"size\"]\n\n            while offset < tensor_offset:\n                count += 1\n                out_c.write(\"0x{:02X}, \".format(0))\n                if count == 12:\n                    out_c.write(\"\\n\\t\")\n                    count = 0\n                offset += 1\n\n            for val in blob:\n                count += 1\n                out_c.write(\"0x{:02X}, \".format(val))\n                if count == 12:\n                    out_c.write(\"\\n\\t\")\n                    count = 0\n\n            offset += tensor_size\n\n            out_c.write(f\"\\n\")\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\\\n          }};\n          return (const ai_ptr)s_{name}_weights;\n        }}\n        \"\"\"\n            )\n        )\n\n    def _emit_open(self, name, out_h, out_c):\n        \"\"\"Emits the network.h file with a few network defines and\n        writes the header part of the network.c file.\"\"\"\n\n        name_upper = name.upper()\n\n        input_size = len(self._input_data)\n        output_size = len(self._output_data)\n\n        # XXX.h\n\n        out_h.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        #ifndef __AI_{name_upper}_H__\n        #define __AI_{name_upper}_H__\n\n        #include \\\"ai_runtime_api.h\\\"\n\n        #define _{name_upper}_INPUTS_COUNT_ ({input_size})\n        #define _{name_upper}_OUTPUTS_COUNT_ ({output_size})\n        #define _{name_upper}_ACTIVATION_BYTES_ ({self._activations_size})\n        \"\"\"\n            )\n        )\n\n        # XXX.c\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        #include <stdio.h>\n\n        #include \\\"dlpack/dlpack.h\\\"\n        #include \\\"tvm/runtime/c_runtime_api.h\\\"\n        #include \\\"{name}.h\\\"\n        #include \\\"{name}_data.h\\\"\n        \"\"\"\n            )\n        )\n\n    def _emit_close(self, name, out_h, out_c):\n        \"\"\"Emits the ai_model_info structure.\"\"\"\n\n        name_upper = name.upper()\n\n        # datetime object containing current date and time\n        now = datetime.now()\n        # dd/mm/YY H:M:S\n        dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n        # XXX.h\n\n        out_h.write(f\"#endif /*__AI_{name_upper}_H__*/ \\n\")\n\n        # XXX.c\n\n        if self.activations_static:\n            out_c.write(\n                f'AI_ALIGNED({self.DATA_ALIGNMENT_BYTES}) __attribute__ ((section(\".{name}.nn_data_act\"))) uint8_t {name}_activations[{self._activations_size}];\\n'\n            )\n        else:\n            out_c.write(f\"AI_STATIC ai_ptr {name}_activations = NULL;\")\n\n        # Emit network structure\n        num_inputs = len(self._input_data)\n        num_outputs = len(self._output_data)\n\n        tool_version = tvm.__version__\n        api_version = f\"{AI_API_VERSION_MAJOR}.{AI_API_VERSION_MINOR}.{AI_API_VERSION_MICRO}.0\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        AI_API_ENTRY  __attribute__ ((section(\".nn_models\"))) ai_model_info {name}_network = {{\n          .name = \\\"{name}\\\",\n          .datetime = \\\"{dt_string}\\\",\n          .revision = \\\"{AI_TOOLS_REVISION}\\\",\n          .tool_version = \\\"{tool_version}\\\",\n          .api_version = \\\"{api_version}\\\",\n          .n_nodes = {self._nodes_size},\n          .n_inputs = {num_inputs},\n          .n_outputs = {num_outputs},\n          .activations_size = {self._activations_size},\n          .params_size = {self._weights_size},\n          .activations = {name}_activations,\n          .inputs = _InputsList,\n          .outputs = _OutputsList,\n          .ai_get_params = &ai_{name}_data_weights_get,\n          .ai_create = &ai_{name}_create,\n          .ai_destroy = &ai_{name}_destroy,\n          .ai_run = &ai_{name}_run\n        }};\n        \"\"\"\n            )\n        )\n\n    def _emit_tensor_shape(self, dl_tensor_name, ndim, shape, strides, out_c):\n        out_c.write(f\"AI_STATIC int64_t {dl_tensor_name}_shape[{ndim}] = {{{shape[1:-1]}}}; \\n\")\n        assert strides is None, f\"###Error: non-compact tensors are not handled yet.\"\n        out_c.write(f\"AI_STATIC int64_t {dl_tensor_name}_strides[{ndim}] = {{}}; \\n\")\n\n    def _emit_tensor_quant(self, dl_tensor_name, out_c):\n\n        if dl_tensor_name in self._quantization:\n            quantization = self._quantization[dl_tensor_name]\n\n        # At this time, TVM only supports quantization info with\n        # single output models.\n        elif dl_tensor_name in self._output_data and \"output\" in self._quantization.keys():\n            quantization = self._quantization[\"output\"]\n        else:\n            quantization = None\n\n        if quantization is not None:\n            scale = quantization[\"scale\"]\n            zero_point = quantization[\"zero_point\"]\n\n            # Sometimes we get a scalar with ScaleAsNumpy.\n            # This seem to mean not quantized ?\n            if not isinstance(scale, np.ndarray):\n                assert scale == 0.0, f\"Non-quantized tensor with scale != 0.0\"\n                assert (\n                    not isinstance(zero_point, np.ndarray) and zero_point == 0\n                ), f\"Non-quantized tensor with zero_point != 0\"\n                return None\n\n            scale_size = len(scale)\n            zero_point_size = len(zero_point)\n\n            assert len(scale) == len(\n                zero_point\n            ), f\"Inconsistent quantizations scale:{scale} vs zero-point:{zero_point}\"\n\n            if len(scale) == 1:\n                quant_name = dl_tensor_name + \"_quant\"\n\n                out_c.write(f\"AI_STATIC float {quant_name}_scale[{scale_size}] = {{ \")\n                for val in scale:\n                    out_c.write(f\"{val}, \")\n                out_c.write(f\"}};\\n\")\n                out_c.write(f\"AI_STATIC int32_t {quant_name}_zero_point[{zero_point_size}] = {{ \")\n                for val in zero_point:\n                    out_c.write(f\"{val}, \")\n                out_c.write(f\"}};\")\n                out_c.write(\n                    textwrap.dedent(\n                        f\"\"\"\n                AI_STATIC ai_quantization_info {quant_name} = {{\n                  .scale = {quant_name}_scale,\n                  .zero_point = {quant_name}_zero_point,\n                  .dim = -1\n                }};\n                \"\"\"\n                    )\n                )\n\n                return quant_name\n\n        return None\n\n    def _emit_tensor_init(self, dl_tensor_name, tensor, out_c):\n        \"\"\"Emits the tensor instantiation code.\"\"\"\n\n        dltype = tensor[\"dltype\"]\n        dims = tensor[\"dims\"]\n        strides = tensor[\"strides\"]\n        byte_offset = tensor[\"byte_offset\"]\n        dtype = _get_type_data(dltype)\n        ndim = len(dims)\n        shape = str(dims)\n        self._emit_tensor_shape(dl_tensor_name, ndim, shape, strides, out_c)\n\n        # Quantization\n        quant_name = self._emit_tensor_quant(dl_tensor_name, out_c)\n\n        # Contents\n        #\n        # TODO: use the 'storage_id':\n        #   \"    .ctx = {{ {} }}, \\n\".format(str(storage_id)[1:-1])\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        AI_ALIGNED({self.DATA_ALIGNMENT_BYTES}) AI_STATIC ai_tensor {dl_tensor_name} = {{\n          .dltensor = {{\n            .data = (ai_ptr)(NULL),\n            .device = {{kDLCPU,0}},\n            .ndim = {ndim},\n            .dtype = {{{dtype}}},\n            .shape = {dl_tensor_name}_shape,\n            .strides = {dl_tensor_name}_strides,\n            .byte_offset = {byte_offset}\n          }},\n        \"\"\"\n            )\n        )\n\n        # Figure out quantization, if exists\n        if quant_name is not None:\n            out_c.write(f\"  .quant = &{quant_name} \\n\")\n        else:\n            out_c.write(f\"  .quant = NULL \\n\")\n        out_c.write(f\"}}; \\n\")\n\n    def _emit_activation_buffers(self, name, out_c):\n        # pylint: disable=unused-argument\n        \"\"\"Emits activation tensors, including inputs/outputs.\"\"\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        //\n        // Inputs:\n        //\n        \"\"\"\n            )\n        )\n\n        # shape/buffer\n        for dl_tensor_name in self._input_data:\n            tensor = self._input_data[dl_tensor_name]\n            self._emit_tensor_init(dl_tensor_name, tensor, out_c)\n            out_c.write(f\"\\n\")\n        out_c.write(f\"\\n\")\n\n        # tensor\n        idx = 0\n        out_c.write(f\"AI_STATIC ai_tensor * _InputsList[] = {{ \\n\")\n        for dl_tensor_name in self._input_data:\n            out_c.write(f\"  &{dl_tensor_name}, // [{idx}]\\n\")\n            idx = idx + 1\n        out_c.write(f\"}}; \\n\")\n        out_c.write(f\"\\n\")\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        //\n        // Activations:\n        //\n        \"\"\"\n            )\n        )\n        for dl_tensor_name in self._activations:\n            tensor = self._activations[dl_tensor_name]\n            self._emit_tensor_init(dl_tensor_name, tensor, out_c)\n        out_c.write(f\"\\n\")\n\n        # Outputs:\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\\\n        //\n        // Outputs:\n        //\n        \"\"\"\n            )\n        )\n        for dl_tensor_name in self._output_data:\n            tensor = self._output_data[dl_tensor_name]\n            self._emit_tensor_init(dl_tensor_name, tensor, out_c)\n            out_c.write(f\"\\n\")\n        out_c.write(f\"\\n\")\n\n        idx = 0\n        out_c.write(f\"AI_STATIC ai_tensor * _OutputsList[] = {{ \\n\")\n        for dl_tensor_name in self._output_data:\n            out_c.write(f\"  &{dl_tensor_name}, // [{idx}]\\n\")\n            idx = idx + 1\n        out_c.write(f\"}}; \\n\")\n        out_c.write(f\"\\n\")\n\n    def _emit_params_buffers(self, name, out_c):\n        \"\"\"Emits all parameter tensors.\"\"\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        //\n        // Weights: {name}\n        //\n        \"\"\"\n            )\n        )\n        for dl_tensor_name in self._weights:\n            tensor = self._weights[dl_tensor_name]\n            self._emit_tensor_init(dl_tensor_name, tensor, out_c)\n        out_c.write(f\"\\n\")\n\n    def _emit_network(self, name, out_c):\n        \"\"\"Emits prototypes for the network operator functions.\"\"\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        //\n        // Network: {name}\n        //\n        \"\"\"\n            )\n        )\n        for node in self._nodes:\n            if node[\"op\"] == \"null\":\n                continue\n            assert node[\"op\"] == \"tvm_op\", f\"###Error: Only TVM ops are supported.\"\n            node_attrs = node[\"attrs\"]\n            func_name = node_attrs[\"func_name\"]\n\n            if func_name == \"__nop\":\n                continue\n\n            out_c.write(\n                f\"TVM_DLL int32_t {func_name}(void * args, void * arg_type_ids, int32_t num_args); \\n\"\n            )\n        out_c.write(f\"\\n\")\n\n    def _emit_tensor_activation(self, dl_tensor_name, tensor, out_c):\n\n        storage_id = tensor[\"storage_id\"]\n        offset = tensor[\"offset\"]\n        out_c.write(\n            textwrap.indent(\n                textwrap.dedent(\n                    f\"\"\"\n        //\n        // {dl_tensor_name}: storage_id:{storage_id}\n        //\n        {dl_tensor_name}.dltensor.data = (ai_ptr)(activations + {offset});\n        \"\"\"\n                ),\n                \"  \",\n            )\n        )\n\n    def _emit_activation_init(self, name, out_c):\n        \"\"\"Emits buffer initialization code for activation tensors.\"\"\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        // {DBAR}\n        //   {name}_configure_activations\n        // {DBAR}\n        AI_STATIC AI_INLINE\n        ai_status {name}_configure_activations (\n          const ai_ptr activations\n        )\n        {{\n          if (activations == NULL) {{\n            TVMAPISetLastError (\\\"Non-null activations arena is required for this model.\\\");\n            return AI_STATUS_ERROR;\n          }}\n        \"\"\"\n            )\n        )\n\n        # Allocate inputs with the static model\n        if self.inputs_static:\n            for dl_tensor_name in self._input_data:\n                tensor = self._input_data[dl_tensor_name]\n                self._emit_tensor_activation(dl_tensor_name, tensor, out_c)\n\n        # Prepare activation buffers\n        for dl_tensor_name in self._activations:\n            tensor = self._activations[dl_tensor_name]\n            self._emit_tensor_activation(dl_tensor_name, tensor, out_c)\n\n        # Allocate outputs with the static model\n        if self.outputs_static:\n            for dl_tensor_name in self._output_data:\n                tensor = self._output_data[dl_tensor_name]\n                self._emit_tensor_activation(dl_tensor_name, tensor, out_c)\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n          return AI_STATUS_OK;\n        }}\n        \"\"\"\n            )\n        )\n\n    def _emit_params_init(self, name, out_c):\n        \"\"\"Emits buffer initialization code for params tensors.\"\"\"\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        // {DBAR}\n        //   {name}_configure_weights\n        // {DBAR}\n        AI_STATIC AI_INLINE\n        ai_status {name}_configure_weights (\n          const ai_ptr weights\n        )\n        {{\n          if (weights == NULL) {{\n            TVMAPISetLastError(\\\"Non-null weights arena is required for this model.\\\");\n            return AI_STATUS_ERROR;\n          }}\n        \"\"\"\n            )\n        )\n\n        for dl_tensor_name in self._weights:\n            tensor = self._weights[dl_tensor_name]\n            offset = tensor[\"offset\"]\n            out_c.write(\n                textwrap.indent(\n                    textwrap.dedent(\n                        f\"\"\"\\\n            //\n            //  {dl_tensor_name}\n            //\n            {dl_tensor_name}.dltensor.data = (ai_ptr)(weights + {offset});\n            \"\"\"\n                    ),\n                    \"  \",\n                )\n            )\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n          return AI_STATUS_OK;\n        }}\n        \"\"\"\n            )\n        )\n\n    def _emit_init(self, name, out_c):\n        \"\"\"Emits buffer initialization code.\"\"\"\n\n        self._emit_activation_init(name, out_c)\n        self._emit_params_init(name, out_c)\n\n    def _emit_run(self, name, out_h, out_c):\n        \"\"\"Emits the run function code.\"\"\"\n\n        out_h.write(\n            textwrap.dedent(\n                f\"\"\"\n        AI_API_ENTRY\n        ai_status ai_{name}_run (\n          ai_tensor *inputs[],\n          ai_tensor *outputs[]\n        );\n        \"\"\"\n            )\n        )\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        // {DBAR}\n        //   ai_{name}_run\n        // {DBAR}\n        AI_API_ENTRY\n        ai_status ai_{name}_run (\n          ai_tensor *inputs[],\n          ai_tensor *outputs[]\n        )\n        {{\n        \"\"\"\n            )\n        )\n\n        # Execute nodes one by one\n        nid = 0\n\n        for node in self._nodes:\n            node_name = node[\"name\"]\n            node_name_upper = node_name.upper()\n\n            nid += 1\n\n            if node[\"op\"] == \"null\":\n                continue\n\n            assert node[\"op\"] == \"tvm_op\", f\"###Error: Only TVM ops are supported.\"\n            node_attrs = node[\"attrs\"]\n            func_name = node_attrs[\"func_name\"]\n\n            if func_name == \"__nop\":\n                continue\n\n            out_c.write(f\"  // \\n\")\n            out_c.write(f\"  // {func_name}\\n\")\n            out_c.write(f\"  // \\n\")\n\n            # Prepare TVM packed function - this is the one called\n            if name == \"__nop\":\n                print(\"      exec: __nop\")\n                continue\n\n            if name == \"__copy\":\n                print(\"      exec: __copy\")\n                continue\n\n            # Get function from the TVM module\n            #\n            #  void * args         : arg_values.data()\n            #  void * arg_type_ids : arg_tcodes.data()\n            #  int32_t num_args    : arg_values.size()\n\n            dl_args_name = _get_node_args_name(node_name)\n            dl_arg_types_name = _get_node_arg_types_name(node_name)\n\n            num_inputs = len(node[\"inputs\"])\n            num_outputs = int(node_attrs[\"num_outputs\"])\n            num_args = num_inputs + num_outputs\n\n            out_c.write(f\"  TVMValue {dl_args_name}[{num_args}]; \\n\")\n            out_c.write(f\"  int32_t {dl_arg_types_name}[{num_args}]; \\n\")\n\n            curr_idx = 0\n\n            for arg in node[\"inputs\"]:\n                dl_tensor_name = self._get_node_arg_name(arg)\n                #\n                # If this input is not an activation or a parameter => find the input\n                #\n                if dl_tensor_name not in self._weights and dl_tensor_name not in self._activations:\n\n                    assert dl_tensor_name in self._input_data, \"Tensor {} not registered ?\".format(\n                        dl_tensor_name\n                    )\n\n                    input_idx = 0\n                    for dl_entry_name in self._input_data:\n                        if dl_entry_name == dl_tensor_name:\n                            break\n                        input_idx += 1\n                    out_c.write(\n                        f\"  {dl_args_name}[{curr_idx}].v_handle = &inputs[{input_idx}]->dltensor; \\n\"\n                    )\n                else:\n                    out_c.write(\n                        f\"  {dl_args_name}[{curr_idx}].v_handle = &{dl_tensor_name}.dltensor; \\n\"\n                    )\n                out_c.write(f\"  {dl_arg_types_name}[{curr_idx}] = kTVMNDArrayHandle; \\n\")\n\n                curr_idx += 1\n\n            for idx in range(num_outputs):\n                dl_tensor_name = get_output_tensor_name(node_name, idx)\n\n                # If this output is not an activation => find the output\n                if dl_tensor_name not in self._activations:\n\n                    assert dl_tensor_name in self._output_data\n\n                    output_idx = 0\n                    for dl_exit_name in self._output_data:\n                        if dl_exit_name == dl_tensor_name:\n                            break\n                        output_idx += 1\n                    out_c.write(\n                        f\"  {dl_args_name}[{curr_idx}].v_handle = &outputs[{output_idx}]->dltensor; \\n\"\n                    )\n                else:\n                    out_c.write(\n                        f\"  {dl_args_name}[{curr_idx}].v_handle = &{dl_tensor_name}.dltensor; \\n\"\n                    )\n                out_c.write(f\"  {dl_arg_types_name}[{curr_idx}] = kTVMNDArrayHandle; \\n\")\n                out_c.write(f\"\\n\")\n\n                curr_idx += 1\n\n            # call this function\n            out_c.write(\n                textwrap.dedent(\n                    f\"\"\"\n            #if (_VERBOSE_ > 0)\n              printf (\\\"  {func_name}  ... \\\\r\\\\n\\\");\n            #endif\n              if ({func_name} ({dl_args_name}, {dl_arg_types_name}, {num_args})) {{\n                TVMAPISetLastError(\"Invalid handle\");\n                return AI_STATUS_ERROR;\n              }}\n            #if (_VERBOSE_ > 0)\n              printf (\\\"  {func_name}  Done.\\\\r\\\\n\\\");\n            #endif\n            \"\"\"\n                )\n            )\n        out_c.write(f\"\\n\")\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n          return AI_STATUS_OK;\n        }}\n        \"\"\"\n            )\n        )\n        out_c.write(f\"\\n\")\n\n    def _emit_create_destroy(self, name, out_h, out_c):\n        \"\"\"Emits the create/destroy functions.\"\"\"\n\n        out_h.write(\n            textwrap.dedent(\n                f\"\"\"\n        AI_API_ENTRY\n        ai_status ai_{name}_create (\n          const ai_ptr weights,\n          const ai_ptr activations\n        );\n        \"\"\"\n            )\n        )\n\n        out_h.write(\n            textwrap.dedent(\n                f\"\"\"\n        AI_API_ENTRY\n        ai_status ai_{name}_destroy ();\n        \"\"\"\n            )\n        )\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        // {DBAR}\n        //   ai_{name}_create\n        // {DBAR}\n        AI_API_ENTRY\n        ai_status ai_{name}_create(\n          const ai_ptr weights,\n          const ai_ptr activations\n        )\n        {{\n          ai_status status = AI_STATUS_OK;\n          status = {name}_configure_weights (weights);\n          if (status != AI_STATUS_OK) {{\n            return status;\n          }}\n          status = {name}_configure_activations (activations);\n          if (status != AI_STATUS_OK) {{\n            return status;\n          }}\n          return AI_STATUS_OK;\n        }}\n        \"\"\"\n            )\n        )\n\n        out_c.write(\n            textwrap.dedent(\n                f\"\"\"\n        // {DBAR}\n        //   ai_{name}_destroy\n        // {DBAR}\n        AI_API_ENTRY\n        ai_status ai_{name}_destroy ()\n        {{\n          return AI_STATUS_OK;\n        }}\n        \"\"\"\n            )\n        )\n\n    def emit_code(self, dest_dir, model_name):\n        \"\"\"Emits the C code implementing the model.\"\"\"\n\n        # Build the directory structure\n        if os.path.exists(dest_dir):\n            raise ValueError(f\"emit_code.Error: {dest_dir} exists.\")\n\n        # Make a new one\n        os.makedirs(dest_dir)\n\n        # Fix the model name\n        model_name = re.sub(\"[^0-9a-zA-Z_]+\", \"_\", model_name)\n        model_name = model_name.lower()\n\n        # Write the C code: we can parse the string\n        if isinstance(self._lib, list):\n            # List of strings from Model Library Format C files\n            for idx, src in enumerate(self._lib):\n                code = _preprocess_code(src)\n                filename = os.path.join(dest_dir, f\"{model_name}_lib{idx}.c\")\n                with open(filename, \"w\") as fout:\n                    fout.write(code)\n        else:\n            # a TVM RuntimeGraphFactory\n            src = self._lib.get_source(fmt=\"c\")\n            code = _preprocess_code(src)\n            filename = os.path.join(dest_dir, f\"{model_name}_lib.c\")\n            with open(filename, \"w\") as fout:\n                fout.write(code)\n\n        # Save params as binary data\n        saved_params = tvm.runtime.save_param_dict(self._params)\n        params_name = os.path.join(dest_dir, model_name + \".params\")\n        with open(params_name, \"wb\") as f:\n            f.write(saved_params)\n\n        # Write the .json\n        graph_name = os.path.join(dest_dir, model_name + \".json\")\n        json_string = json.dumps(self._graph, indent=4)\n        with open(graph_name, \"w\") as f:\n            print(json_string, file=f)\n\n        # emit X_data[c,h]\n        data_h_name = os.path.join(dest_dir, model_name + \"_data.h\")\n        data_c_name = os.path.join(dest_dir, model_name + \"_data.c\")\n        model_h_name = os.path.join(dest_dir, model_name + \".h\")\n        model_c_name = os.path.join(dest_dir, model_name + \".c\")\n\n        with contextlib.ExitStack() as exit_stack:\n\n            # emit X[c,h]\n\n            data_h = exit_stack.enter_context(open(data_h_name, \"w\"))\n            data_c = exit_stack.enter_context(open(data_c_name, \"w\"))\n            out_h = exit_stack.enter_context(open(model_h_name, \"w\"))\n            out_c = exit_stack.enter_context(open(model_c_name, \"w\"))\n\n            self._emit_params_data(model_name, data_h, data_c)\n\n            self._emit_open(model_name, out_h, out_c)\n            self._emit_params_buffers(model_name, out_c)\n            self._emit_activation_buffers(model_name, out_c)\n            self._emit_network(model_name, out_c)\n\n            self._emit_init(model_name, out_c)\n            self._emit_create_destroy(model_name, out_h, out_c)\n            self._emit_run(model_name, out_h, out_c)\n\n            self._emit_close(model_name, out_h, out_c)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/debugger.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines functions for controlling debuggers for micro TVM binaries.\"\"\"\n\nimport atexit\nimport abc\nimport errno\nimport logging\nimport os\nimport shlex\nimport signal\nimport subprocess\nimport sys\nimport termios\nimport threading\nimport time\n\nimport psutil\n\nfrom .._ffi import register_func\nfrom . import class_factory\nfrom . import transport\nfrom .transport.file_descriptor import FdTransport\n\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Debugger(metaclass=abc.ABCMeta):\n    \"\"\"An interface for controlling micro TVM debuggers.\"\"\"\n\n    @abc.abstractmethod\n    def start(self):\n        \"\"\"Start the debugger, but do not block on it.\n\n        The runtime will continue to be driven in the background.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def stop(self):\n        \"\"\"Terminate the debugger.\"\"\"\n        raise NotImplementedError()\n\n\nclass GdbDebugger(Debugger):\n    \"\"\"Handles launching, suspending signals, and potentially dealing with terminal issues.\"\"\"\n\n    # Number of seconds to wait in stop() for a graceful shutdown. After this time has elapsed,\n    # the debugger is kill()'d.\n    _GRACEFUL_SHUTDOWN_TIMEOUT_SEC = 5.0\n\n    # The instance of GdbDebugger that's currently started.\n    _STARTED_INSTANCE = None\n\n    @classmethod\n    def _stop_all(cls):\n        if cls._STARTED_INSTANCE:\n            cls._STARTED_INSTANCE.stop()\n\n    def __init__(self):\n        super(GdbDebugger, self).__init__()\n        self._is_running = False\n        self._is_running_lock = threading.RLock()\n        self._child_exited_event = threading.Event()\n        self._signals_reset_event = threading.Event()\n\n    @abc.abstractmethod\n    def popen_kwargs(self):\n        raise NotImplementedError()\n\n    def _internal_stop(self):\n        if not self._is_running:\n            return\n\n        os.kill(os.getpid(), signal.SIGUSR1)\n        self._signals_reset_event.wait()\n        termios.tcsetattr(sys.stdin.fileno(), termios.TCSAFLUSH, self.old_termios)\n\n        try:\n            children = psutil.Process(self.popen.pid).children(recursive=True)\n            for c in children:\n                c.terminate()\n                _, alive = psutil.wait_procs(children, timeout=self._GRACEFUL_SHUTDOWN_TIMEOUT_SEC)\n                for a in alive:\n                    a.kill()\n        except psutil.NoSuchProcess:\n            pass\n        finally:\n            self.__class__._STARTED_INSTANCE = None\n            self._is_running = False\n            self._child_exited_event.set()\n\n    def _wait_for_child(self):\n        self.popen.wait()\n        with self._is_running_lock:\n            self._internal_stop()\n\n    @classmethod\n    def _sigusr1_handler(cls, signum, stack_frame):  # pylint: disable=unused-argument\n        assert (\n            cls._STARTED_INSTANCE is not None\n        ), \"overridden sigusr1 handler should not be invoked when GDB not started\"\n        signal.signal(signal.SIGINT, cls._STARTED_INSTANCE.old_sigint_handler)\n        signal.signal(signal.SIGUSR1, cls._STARTED_INSTANCE.old_sigusr1_handler)\n        cls._STARTED_INSTANCE._signals_reset_event.set()\n\n    @classmethod\n    def _sigint_handler(cls, signum, stack_frame):  # pylint: disable=unused-argument\n        assert (\n            cls._STARTED_INSTANCE is not None\n        ), \"overridden sigint handler should not be invoked when GDB not started\"\n        with cls._STARTED_INSTANCE._is_running_lock:\n            exists = cls._STARTED_INSTANCE._is_running\n        if exists:\n            try:\n                os.killpg(cls._STARTED_INSTANCE.child_pgid, signal.SIGINT)\n            except ProcessLookupError:\n                pass\n\n    def start(self):\n        with self._is_running_lock:\n            assert not self._is_running\n            assert not self._STARTED_INSTANCE\n\n            kwargs = self.popen_kwargs()\n            self.did_start_new_session = kwargs.setdefault(\"start_new_session\", True)\n\n            self.old_termios = termios.tcgetattr(sys.stdin.fileno())\n            self.popen = subprocess.Popen(**kwargs)\n            self._is_running = True\n            self.old_sigint_handler = signal.signal(signal.SIGINT, self._sigint_handler)\n            self.old_sigusr1_handler = signal.signal(signal.SIGUSR1, self._sigusr1_handler)\n            self.__class__._STARTED_INSTANCE = self\n            try:\n                self.child_pgid = os.getpgid(self.popen.pid)\n            except Exception:\n                self.stop()\n                raise\n            with self._is_running_lock:\n                self._is_child_alive = True\n            t = threading.Thread(target=self._wait_for_child)\n            t.daemon = True\n            t.start()\n\n    def stop(self):\n        self._child_exited_event.wait()\n\n\natexit.register(GdbDebugger._stop_all)\n\n\nclass GdbTransportDebugger(GdbDebugger):\n    \"\"\"A debugger that uses a single GDB subprocess as both the transport and the debugger.\n\n    Opens pipes for the target's stdin and stdout, launches GDB and configures GDB's target\n    arguments to read and write from the pipes using /dev/fd.\n    \"\"\"\n\n    def __init__(self, args, **popen_kw):\n        super(GdbTransportDebugger, self).__init__()\n        self.args = args\n        self.popen_kw = popen_kw\n\n    def popen_kwargs(self):\n        stdin_read, stdin_write = os.pipe()\n        stdout_read, stdout_write = os.pipe()\n\n        os.set_inheritable(stdin_read, True)\n        os.set_inheritable(stdout_write, True)\n\n        sysname = os.uname()[0]\n        if sysname == \"Darwin\":\n            args = [\n                \"lldb\",\n                \"-O\",\n                f\"target create {self.args[0]}\",\n                \"-O\",\n                f\"settings set target.input-path /dev/fd/{stdin_read}\",\n                \"-O\",\n                f\"settings set target.output-path /dev/fd/{stdout_write}\",\n            ]\n            if len(self.args) > 1:\n                args.extend(\n                    [\"-O\", \"settings set target.run-args {}\".format(\" \".join(self.args[1:]))]\n                )\n        elif sysname == \"Linux\":\n            args = [\n                \"gdb\",\n                \"-ex\",\n                f\"file {self.args[0]}\",\n                \"-ex\",\n                (\n                    f\"set args {' '.join(shlex.quote(a) for a in self.args[1:])} \"\n                    f\"</dev/fd/{stdin_read} >/dev/fd/{stdout_write}\"\n                ),\n            ]\n        else:\n            raise NotImplementedError(f\"System {sysname} is not yet supported\")\n\n        self.fd_transport = FdTransport(\n            stdout_read, stdin_write, transport.debug_transport_timeouts()\n        )\n        self.fd_transport.open()\n\n        return {\n            \"args\": args,\n            \"pass_fds\": [stdin_read, stdout_write],\n        }\n\n    def _internal_stop(self):\n        self.fd_transport.close()\n        super(GdbTransportDebugger, self)._internal_stop()\n\n    class _Transport(transport.Transport):\n        def __init__(self, gdb_transport_debugger):\n            self.gdb_transport_debugger = gdb_transport_debugger\n\n        def timeouts(self):\n            return transport.debug_transport_timeouts()\n\n        def open(self):\n            pass  # Pipes opened by parent class.\n\n        def write(self, data, timeout_sec):\n            end_time = time.monotonic() + timeout_sec if timeout_sec is not None else None\n            while True:\n                try:\n                    return self.gdb_transport_debugger.fd_transport.write(data, timeout_sec)\n                except OSError as exc:\n                    # NOTE: this error sometimes happens when writes are initiated before the child\n                    # process launches.\n                    if exc.errno == errno.EAGAIN:\n                        if end_time is None or time.monotonic() < end_time:\n                            time.sleep(0.1)  # sleep to avoid excessive CPU usage\n                            continue\n\n                    raise exc\n\n            raise base.IoTimeoutError()\n\n        def read(self, n, timeout_sec):\n            end_time = time.monotonic() + timeout_sec if timeout_sec is not None else None\n            while True:\n                try:\n                    return self.gdb_transport_debugger.fd_transport.read(n, timeout_sec)\n                except OSError as exc:\n                    # NOTE: this error sometimes happens when reads are initiated before the child\n                    # process launches.\n                    if exc.errno == errno.EAGAIN:\n                        if end_time is None or time.monotonic() < end_time:\n                            time.sleep(0.1)  # sleep to avoid excessive CPU usage\n                            continue\n\n                    raise exc\n\n            raise base.IoTimeoutError()\n\n        def close(self):\n            pass  # Pipes closed by parent class (DebugWrapperTransport calls stop() next).\n\n    def transport(self):\n        return self._Transport(self)\n\n\nclass GdbRemoteDebugger(GdbDebugger):\n    \"\"\"A Debugger that invokes GDB and attaches to a remote GDBserver-based target.\"\"\"\n\n    def __init__(\n        self, gdb_binary, remote_hostport, debug_binary, wrapping_context_manager=None, **popen_kw\n    ):\n        super(GdbRemoteDebugger, self).__init__()\n        self.gdb_binary = gdb_binary\n        self.remote_hostport = remote_hostport\n        self.debug_binary = debug_binary\n        self.wrapping_context_manager = wrapping_context_manager\n        self.popen_kw = popen_kw\n\n    def popen_kwargs(self):\n        kwargs = {\n            \"args\": [\n                self.gdb_binary,\n                \"-iex\",\n                f\"file {self.debug_binary}\",\n                \"-iex\",\n                f\"target remote {self.remote_hostport}\",\n            ],\n        }\n        kwargs.update(self.popen_kw)\n\n        return kwargs\n\n    def start(self):\n        if self.wrapping_context_manager is not None:\n            self.wrapping_context_manager.__enter__()\n        super(GdbRemoteDebugger, self).start()\n\n    def stop(self):\n        try:\n            super(GdbRemoteDebugger, self).stop()\n        finally:\n            if self.wrapping_context_manager is not None:\n                self.wrapping_context_manager.__exit__(None, None, None)\n\n\nGLOBAL_DEBUGGER = None\n\n\nclass DebuggerFactory(class_factory.ClassFactory):\n\n    SUPERCLASS = Debugger\n\n\ndef launch_debugger(debugger_factory, *args, **kw):\n    global GLOBAL_DEBUGGER\n    if GLOBAL_DEBUGGER is not None:\n        stop_debugger()\n\n    GLOBAL_DEBUGGER = debugger_factory.instantiate(*args, **kw)\n    GLOBAL_DEBUGGER.start()\n\n\n@register_func(\"tvm.micro.debugger.launch_debugger\")\ndef _launch_debugger(debugger_factory_json):\n    launch_debugger(DebuggerFactory.from_json(debugger_factory_json))\n\n\n@register_func(\"tvm.micro.debugger.stop_debugger\")\ndef stop_debugger():\n    global GLOBAL_DEBUGGER\n    if GLOBAL_DEBUGGER is not None:\n        try:\n            GLOBAL_DEBUGGER.stop()\n        finally:\n            GLOBAL_DEBUGGER = None\n\n\nclass RpcDebugger(Debugger):\n    \"\"\"A Debugger instance that launches the actual debugger on a remote TVM RPC server.\"\"\"\n\n    def __init__(self, rpc_session, factory, wrapping_context_manager=None):\n        super(RpcDebugger, self).__init__()\n        self._factory = factory\n        self.launch_debugger = rpc_session.get_function(\"tvm.micro.debugger.launch_debugger\")\n        self.stop_debugger = rpc_session.get_function(\"tvm.micro.debugger.stop_debugger\")\n        self.wrapping_context_manager = wrapping_context_manager\n\n    def start(self):\n        if self.wrapping_context_manager is not None:\n            self.wrapping_context_manager.__enter__()\n\n        try:\n            self.launch_debugger(self._factory.to_json)\n        except Exception:\n            if self.wrapping_context_manager is not None:\n                self.wrapping_context_manager.__exit__(None, None, None)\n            raise\n\n        try:\n            input(\"Press [Enter] when debugger is set\")\n        except Exception:\n            self.stop()\n            raise\n\n        self._is_running = True\n\n    def stop(self):\n        try:\n            self.stop_debugger()\n        finally:\n            if self.wrapping_context_manager is not None:\n                self.wrapping_context_manager.__exit__(None, None, None)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/model_library_format.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines functions for exporting to Model Library Format.\"\"\"\n\nimport datetime\nimport json\nimport os\nimport pathlib\nimport re\nimport tarfile\nimport typing\n\nimport tvm\nfrom tvm.ir.type import TupleType\nfrom tvm.micro import get_standalone_crt_dir\nfrom .._ffi import get_global_func\nfrom ..contrib import utils\nfrom ..driver import build_module\nfrom ..relay.backend import executor_factory\nfrom ..relay.backend.name_transforms import to_c_variable_style, prefix_generated_name\nfrom ..relay import param_dict\nfrom ..tir import expr\n\n# This should be kept identical to runtime::symbol::tvm_module_main\nMAIN_FUNC_NAME_STR = \"__tvm_main__\"\nSTANDALONE_CRT_URL = \"./runtime\"\nMETADATA_FILE = \"metadata.json\"\n\n\nclass UnsupportedInModelLibraryFormatError(Exception):\n    \"\"\"Raised when export_model_library_format does not support the given Module tree.\"\"\"\n\n\ndef generate_c_interface_header(\n    module_name, inputs, outputs, pools, io_pool_allocations, devices, workspace_size, include_path\n):\n    \"\"\"Generate C Interface header to be included in MLF\"\"\"\n    mangled_name = to_c_variable_style(prefix_generated_name(module_name))\n    metadata_header = os.path.join(include_path, f\"{mangled_name}.h\")\n\n    interface_c_create = tvm._ffi.get_global_func(\"runtime.InterfaceCCreate\")\n    interface_c_module = interface_c_create(\n        module_name, inputs, outputs, pools, io_pool_allocations, devices, workspace_size\n    )\n\n    with open(metadata_header, \"w\") as header_file:\n        header_file.write(interface_c_module.get_source())\n\n    return metadata_header\n\n\n# List of type_key for modules which are ephemeral and do not need to be exported.\nEPHEMERAL_MODULE_TYPE_KEYS = (\"metadata_module\",)\n\n\ndef _populate_codegen_dir(\n    mods: typing.Union[\n        typing.List[executor_factory.ExecutorFactoryModule],\n        typing.List[tvm.runtime.Module],\n    ],\n    codegen_dir: str,\n):\n    \"\"\"Populate the codegen sub-directory as part of a Model Library Format export.\n\n    Parameters\n    ----------\n    mods : List[tvm.relay.backend.executor_factory.ExecutorFactoryModule], List[tvm.runtime.Module]\n        A list of the return value of tvm.relay.build, which\n        will be exported into Model Library Format.\n    codegen_dir : str\n        Path to the codegen directory on disk.\n    module_name: Optional[str]\n        Name used to prefix the generated source files\n\n    \"\"\"\n    dso_modules = []\n    for mod in mods:\n        if isinstance(mod, executor_factory.ExecutorFactoryModule):\n            lib = mod.lib\n        elif isinstance(mod, tvm.runtime.Module):\n            lib = mod\n        else:\n            raise RuntimeError(f\"Not supported module type: {type(mod)}\")\n\n        dso_modules = lib._collect_dso_modules()\n        non_dso_modules = lib._collect_from_import_tree(lambda m: m not in dso_modules)\n\n        # Filter ephemeral modules which cannot be exported.\n        dso_modules = [m for m in dso_modules if m.type_key not in EPHEMERAL_MODULE_TYPE_KEYS]\n        non_dso_modules = [\n            m for m in non_dso_modules if m.type_key not in EPHEMERAL_MODULE_TYPE_KEYS\n        ]\n\n        if non_dso_modules:\n            raise UnsupportedInModelLibraryFormatError(\n                f\"Don't know how to export non-c or non-llvm modules; found: {non_dso_modules!r}\"\n            )\n\n        mod_indices = {\"lib\": 0, \"src\": 0}\n        host_codegen_dir = os.path.join(codegen_dir, \"host\")\n        lib_name = (\n            f\"{mod.libmod_name}_lib\"\n            if isinstance(mod, executor_factory.ExecutorFactoryModule)\n            else \"lib\"\n        )\n\n        for dso_mod in dso_modules:\n            if dso_mod.type_key == \"c\":\n                assert dso_mod.format in [\"c\", \"cc\", \"cpp\"]\n                ext = dso_mod.format\n                index = mod_indices[\"src\"]\n                mod_indices[\"src\"] += 1\n                parent_dir = os.path.join(host_codegen_dir, \"src\")\n                file_name = os.path.join(parent_dir, f\"{lib_name}{index}.{ext}\")\n            elif dso_mod.type_key == \"llvm\":\n                index = mod_indices[\"lib\"]\n                mod_indices[\"lib\"] += 1\n                parent_dir = os.path.join(host_codegen_dir, \"lib\")\n                file_name = os.path.join(parent_dir, f\"{lib_name}{index}.o\")\n            else:\n                assert (\n                    False\n                ), f\"do not expect module with type_key={lib.type_key} from _collect_dso_modules\"\n\n            if not os.path.exists(parent_dir):\n                os.makedirs(parent_dir)\n            dso_mod.save(file_name)\n\n\ndef _build_memory_map(mod):\n    ret = dict()\n    if isinstance(mod, executor_factory.GraphExecutorFactoryModule):\n        ret[\"sids\"] = _build_sid_map(mod.graph_json)\n    ret[\"functions\"] = _build_function_memory_map(mod.function_metadata)\n    return ret\n\n\ndef _build_sid_map(graph_json):\n    \"\"\"Build a simpler storage id info map from graph JSON.\n\n    Parameters\n    ----------\n    graph_json : str\n        String representation of the graph_json created from tvm.relay.build().\n\n    Returns\n    -------\n    list :\n        A list with one entry per storage id describing that memory.\n    \"\"\"\n    graph = json.loads(graph_json)\n    seen_storage_ids = set()\n    memory_map = []\n    for node_id, storage_id in enumerate(graph[\"attrs\"][\"storage_id\"][1]):\n        if storage_id in seen_storage_ids:\n            continue\n\n        seen_storage_ids.add(storage_id)\n        num_elements = 1\n        for dim in graph[\"attrs\"][\"shape\"][1][storage_id]:\n            num_elements *= dim\n\n        dltype = graph[\"attrs\"][\"dltype\"][1][storage_id]\n        m = re.match(r\"^[a-zA-Z]+([0-9]+)$\", dltype)\n        assert m, f\"Exported graph contains unknown dltype {dltype}\"\n\n        elem_bits = int(m.group(1))\n\n        map_entry = {\n            \"storage_id\": storage_id,\n            \"size_bytes\": (num_elements * elem_bits + 7) // 8,\n        }\n        if node_id in graph[\"arg_nodes\"]:\n            map_entry[\"input_binding\"] = graph[\"nodes\"][node_id][\"name\"]\n\n        memory_map.append(map_entry)\n\n    return memory_map\n\n\ndef _build_function_memory_map(function_metadata):\n    \"\"\"Build a simple map that shows how much workspace is required to execute\n    each primitive function. The main_func describes how much memory is required\n    to execute the main control code.\n\n    Parameters\n    ----------\n    function_metadata : Map<String, FunctionInfo>\n        This contains all the compiled metadata on a function basis\n\n    Returns\n    -------\n    dict :\n        This will have two entries:\n        1.) A list with one entry per function describing local memory it is using.\n        2.) A global memory requirement if all functions are executed sequentially\n    \"\"\"\n    device_max_workspace = dict()\n    main_func_metadata = function_metadata[MAIN_FUNC_NAME_STR]\n    func_entries = []\n    target_local_entries = dict()\n\n    for func_name, finfo in function_metadata.items():\n        # Skip a few unsupported cases:\n        # 1. The main function metadata is exported elsewhere.\n        # 2. BYOC operator implementations do not currently export useful FunctionInfo.\n        if func_name == MAIN_FUNC_NAME_STR or not finfo.tir_primfuncs:\n            continue\n        if func_name not in target_local_entries.keys():\n            target_local_entries[func_name] = list()\n        for target in dict(finfo.workspace_sizes).keys():\n            workspace_size = finfo.workspace_sizes[target]\n            target_entry = {\n                \"device\": int(target.get_target_device_type()),\n                \"workspace_size_bytes\": int(workspace_size),\n            }\n            target_local_entries[func_name].append(target_entry)\n            if workspace_size >= device_max_workspace.get(int(target.get_target_device_type()), 0):\n                device_max_workspace[int(target.get_target_device_type())] = workspace_size\n\n    for func_name, target_entries_ in target_local_entries.items():\n        func_entry = {\n            \"function_name\": str(func_name),\n            \"workspace\": target_entries_,\n        }\n        func_entries.append(func_entry)\n\n    target_main_entries = dict()\n\n    def _create_empty_entry(target_device_type):\n        return {\n            \"device\": int(target_device_type),\n            \"workspace_size_bytes\": 0,\n            \"constants_size_bytes\": 0,\n            \"io_size_bytes\": 0,\n        }\n\n    for target in dict(main_func_metadata.workspace_sizes).keys():\n        main_func_local_workspace = main_func_metadata.workspace_sizes[target]\n        target_main_entries[int(target.get_target_device_type())] = _create_empty_entry(\n            int(target.get_target_device_type())\n        )\n        target_main_entries[int(target.get_target_device_type())][\"workspace_size_bytes\"] = int(\n            device_max_workspace.get(int(target.get_target_device_type()), 0)\n        ) + int(main_func_local_workspace)\n\n    for target in dict(main_func_metadata.constant_sizes).keys():\n        if int(target.get_target_device_type()) not in target_main_entries.keys():\n            target_main_entries[int(target.get_target_device_type())] = _create_empty_entry(\n                int(target.get_target_device_type())\n            )\n        target_main_entries[int(target.get_target_device_type())][\"constants_size_bytes\"] = int(\n            main_func_metadata.constant_sizes[target]\n        )\n\n    for target in dict(main_func_metadata.io_sizes).keys():\n        if int(target.get_target_device_type()) not in target_main_entries.keys():\n            target_main_entries[int(target.get_target_device_type())] = _create_empty_entry(\n                int(target.get_target_device_type())\n            )\n        target_main_entries[int(target.get_target_device_type())][\"io_size_bytes\"] = int(\n            main_func_metadata.io_sizes[target]\n        )\n\n    ret = {\n        \"operator_functions\": func_entries,\n        \"main\": list(target_main_entries.values()),\n    }\n    return ret\n\n\ndef _get_main_relay_func(mod: executor_factory.ExecutorFactoryModule):\n    main_func = mod.function_metadata[MAIN_FUNC_NAME_STR]\n    target = list(main_func.relay_primfuncs.keys())[0]\n    return main_func.relay_primfuncs[target]\n\n\ndef _convert_tuple_to_outputs(ret_type, offset=0):\n    outputs = []\n    added_fields = len(ret_type.fields)\n    for output_index in range(added_fields):\n        next_output = offset + len(outputs)\n        if isinstance(ret_type.fields[output_index], TupleType):\n            outputs.extend(_convert_tuple_to_outputs(ret_type.fields[output_index], next_output))\n        else:\n            outputs.append(f\"output{next_output}\")\n    return outputs\n\n\ndef _get_inputs_and_outputs_from_module(mod):\n    inputs = [str(input_var.name) for input_var in mod.executor_codegen_metadata.inputs]\n    outputs = list(mod.executor_codegen_metadata.outputs)\n    return inputs, outputs\n\n\ndef _get_pools_from_module(mod):\n    return list(dict(mod.executor_codegen_metadata.pool_inputs).values())\n\n\ndef _get_io_pool_allocation_from_module(mod):\n    return dict(mod.executor_codegen_metadata.io_pool_allocations)\n\n\ndef _should_generate_interface_header(mod):\n    return \"interface-api\" in mod.executor and mod.executor[\"interface-api\"] == \"c\"\n\n\ndef _make_tar(source_dir, tar_file_path, modules):\n    \"\"\"Build a tar file from source_dir.\"\"\"\n    with tarfile.open(tar_file_path, \"w\") as tar_f:\n\n        def reset(tarinfo):\n            tarinfo.uid = tarinfo.gid = 0\n            tarinfo.uname = tarinfo.gname = \"root\"\n            return tarinfo\n\n        tar_f.add(str(source_dir), arcname=\".\", filter=reset)\n\n        for mod in modules:\n            is_aot = isinstance(mod, executor_factory.AOTExecutorFactoryModule)\n            if is_aot and str(mod.runtime) == \"crt\":\n                tar_f.add(get_standalone_crt_dir(), arcname=STANDALONE_CRT_URL)\n                break\n\n\n_GENERATED_VERSION = 7\n\n\ndef _is_module_names_unique(mods: typing.List[executor_factory.ExecutorFactoryModule]):\n    \"\"\"Check if built modules have unique names.\n\n    Parameters\n    ----------\n    mods : List[tvm.relay.backend.executor_factory.ExecutorFactoryModule]\n        A list of the return value of tvm.relay.build,\n        which will be exported into Model Library Format.\n    \"\"\"\n    all_names = []\n    for mod in mods:\n        all_names.append(mod.libmod_name)\n\n    return len(set(all_names)) == len(all_names)\n\n\ndef _export_graph_model_library_format(\n    mods: typing.List[executor_factory.ExecutorFactoryModule], tempdir: pathlib.Path\n):\n    \"\"\"Export a tvm.relay.build artifact in Model Library Format.\n\n    Parameters\n    ----------\n    mods : List[tvm.relay.backend.executor_factory.ExecutorFactoryModule]\n        A list of the return value of tvm.relay.build,\n        which will be exported into Model Library Format.\n    tempdir : pathlib.Path\n        Temporary directory to populate with Model Library Format contents.\n    \"\"\"\n\n    assert _is_module_names_unique(mods), \"Multiple modules should have unique names.\"\n\n    metadata = {\n        \"version\": _GENERATED_VERSION,\n    }\n    metadata[\"modules\"] = {}\n    for mod in mods:\n        is_aot = isinstance(mod, executor_factory.AOTExecutorFactoryModule)\n        executor = [\"aot\"] if is_aot else [\"graph\"]\n        module_name = mod.libmod_name\n        metadata[\"modules\"][module_name] = {\n            \"model_name\": module_name,\n            \"export_datetime\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%SZ\"),\n            \"memory\": _build_memory_map(mod),\n            \"target\": [str(t) for t in mod.target],\n            \"executors\": executor,\n            \"style\": \"full-model\",\n        }\n\n        if is_aot and (str(mod.runtime) == \"crt\"):\n            standalone_crt = {\n                \"short_name\": \"tvm_standalone_crt\",\n                \"url\": f\"{STANDALONE_CRT_URL}\",\n                \"url_type\": \"mlf_path\",\n                \"version_spec\": f\"{tvm.__version__}\",\n            }\n            external_dependencies = [standalone_crt]\n            metadata[\"modules\"][module_name][\"external_dependencies\"] = external_dependencies\n\n    with open(tempdir / METADATA_FILE, \"w\") as json_f:\n        json.dump(metadata, json_f, indent=2, sort_keys=True)\n\n    codegen_dir = tempdir / \"codegen\"\n    codegen_dir.mkdir()\n    _populate_codegen_dir(mods, codegen_dir)\n\n    parameters_dir = tempdir / \"parameters\"\n    parameters_dir.mkdir()\n    src_dir = tempdir / \"src\"\n    src_dir.mkdir()\n    graph_config_dir = tempdir / \"executor-config\" / \"graph\"\n    for mod in mods:\n        if _should_generate_interface_header(mod):\n            include_path = codegen_dir / \"host\" / \"include\"\n            if not include_path.exists():\n                include_path.mkdir()\n\n            inputs, outputs = _get_inputs_and_outputs_from_module(mod)\n            devices = mod.get_devices()\n            pools = _get_pools_from_module(mod)\n            io_pool_allocations = _get_io_pool_allocation_from_module(mod)\n            workspace_size = int(\n                metadata[\"modules\"][mod.libmod_name][\"memory\"][\"functions\"][\"main\"][0][\n                    \"workspace_size_bytes\"\n                ]\n            )\n            generate_c_interface_header(\n                mod.libmod_name,\n                inputs,\n                outputs,\n                pools,\n                io_pool_allocations,\n                devices,\n                workspace_size,\n                include_path,\n            )\n\n        is_aot = isinstance(mod, executor_factory.AOTExecutorFactoryModule)\n        param_filename = parameters_dir / f\"{mod.libmod_name}.params\"\n        with open(param_filename, \"wb\") as f:\n            f.write(param_dict.save_param_dict(mod.params))\n\n        with open(src_dir / f\"{mod.libmod_name}.relay\", \"w\") as f:\n            f.write(str(mod.ir_mod))\n\n        if not is_aot:\n            if not graph_config_dir.exists():\n                graph_config_dir.mkdir(parents=True)\n            with open(graph_config_dir / f\"{mod.libmod_name}.graph\", \"w\") as f:\n                f.write(mod.get_executor_config())\n\n\nclass NonStaticShapeError(Exception):\n    \"\"\"Raised when a shape has elements other than IntImm.\"\"\"\n\n\ndef _shape_to_size(shape, dtype):\n    bits_per_item = int(\n        re.match(r\"((float)|(int))(?P<width_bits>[0-9]+)\", dtype).group(\"width_bits\")\n    )\n    assert bits_per_item is not None, f\"don't know how to compute size of type {dtype}\"\n    total_bits = bits_per_item\n    for s in shape:\n        total_bits *= s\n\n    return (total_bits + 7) // 8\n\n\ndef _write_tir_and_build_operator_memory_map(src_dir, targets, ir_module_by_target):\n    def _eval_shape(param_name, buffer_shape):\n        shape = []\n        for x in buffer_shape:\n            if not isinstance(x, expr.IntImm):\n                raise NonStaticShapeError(\n                    f\"Parameter {param_name} has shape with non-IntImm elements: {buffer_shape}\"\n                )\n            shape.append(x.value)\n        return shape\n\n    memory_map = {}\n    for target in targets:\n        # TODO(mbs): The device type is not unique, better would be to use target.kind.name\n        target_device_type = target.get_target_device_type()\n        ir_mod = ir_module_by_target[target]\n        printer = get_global_func(\"tir.ModelLibraryFormatPrinter\")(False, None, False)\n        with open(src_dir / f\"tir-{target_device_type}.txt\", \"w\") as f:\n            f.write(printer[\"print\"](ir_mod))\n\n        for v in ir_mod.get_global_vars():\n            map_entry = []\n            for p, b in ir_mod[v.name_hint].buffer_map.items():\n                shape = _eval_shape(p.name, b.shape)\n                buffer_size_bytes = _shape_to_size(shape, str(b.dtype))\n                # NOTE: cannot tell what is an input or output at this point.\n                map_entry.append(\n                    {\n                        \"size_bytes\": buffer_size_bytes,\n                        \"shape\": [int(x) for x in b.shape],\n                        \"dtype\": b.dtype,\n                        \"input_binding\": printer[\"get_var_name\"](p),\n                    }\n                )\n            memory_map[v.name_hint] = map_entry\n\n    return memory_map\n\n\ndef _export_operator_model_library_format(mod: build_module.OperatorModule, tempdir):\n    \"\"\"Export the result of tvm.build() in Model Library Format.\n    Parameters\n    ----------\n    mod : runtime.Module\n        The Module returned from tvm.build().\n    tempdir : str\n        Path to the .tar archive to generate.\n    \"\"\"\n    targets = []\n    for target in mod.ir_module_by_target.keys():\n        if str(target.kind) not in (\"llvm\", \"c\"):\n            raise UnsupportedInModelLibraryFormatError(\n                f\"Operator has non-DSO-exportable target {target!s}, which is not yet supported in \"\n                \"Model Library Format\"\n            )\n\n        targets.append(target)\n\n    src_dir = tempdir / \"src\"\n    src_dir.mkdir()\n    memory_map = _write_tir_and_build_operator_memory_map(src_dir, targets, mod.ir_module_by_target)\n\n    metadata = {\n        \"version\": _GENERATED_VERSION,\n        \"model_name\": mod.name,\n        \"export_datetime\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%SZ\"),\n        \"memory\": memory_map,\n        \"target\": [str(t) for t in targets],\n        \"executors\": [],\n        \"style\": \"operator\",\n    }\n    with open(tempdir / METADATA_FILE, \"w\") as metadata_f:\n        json.dump(metadata, metadata_f)\n\n    codegen_dir = tempdir / \"codegen\"\n    codegen_dir.mkdir()\n    _populate_codegen_dir(list([mod]), codegen_dir)\n\n\nExportableModule = typing.Union[\n    build_module.OperatorModule,\n    executor_factory.AOTExecutorFactoryModule,\n    executor_factory.GraphExecutorFactoryModule,\n]\n\n\ndef export_model_library_format(\n    mods: typing.Union[ExportableModule, typing.List[ExportableModule]],\n    file_name: typing.Union[str, pathlib.Path],\n):\n    \"\"\"Export the build artifact in Model Library Format.\n\n    This function creates a .tar archive containing the build artifacts in a standardized\n    layout. It's intended to allow downstream automation to build TVM artifacts against the C\n    runtime.\n\n    Parameters\n    ----------\n    mod : ExportableModule, List[ExportableModule]\n        The return value of tvm.build or tvm.relay.build.\n    file_name : str\n        Path to the .tar archive to generate.\n\n    Returns\n    -------\n    file_name : str\n        The path to the generated .tar archive.\n    \"\"\"\n    modules = mods\n    if not isinstance(mods, list):\n        modules = list([mods])\n\n    operator_module_type = all(isinstance(mod, build_module.OperatorModule) for mod in modules)\n    graph_module_type = all(\n        isinstance(\n            mod,\n            (\n                executor_factory.AOTExecutorFactoryModule,\n                executor_factory.GraphExecutorFactoryModule,\n            ),\n        )\n        for mod in modules\n    )\n\n    file_name = pathlib.Path(file_name)\n    tempdir = utils.tempdir()\n\n    if operator_module_type:\n        if len(modules) != 1:\n            raise RuntimeError(\"Multiple operator is not supported.\")\n        _export_operator_model_library_format(modules[0], tempdir.path)\n    elif graph_module_type:\n        _export_graph_model_library_format(modules, tempdir.path)\n    else:\n        raise NotImplementedError(\n            f\"Don't know how to export module of type {modules[0].__class__!r}\"\n        )\n\n    _make_tar(tempdir.path, file_name, modules)\n\n    return file_name\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/project.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines glue wrappers around the Project API which mate to TVM interfaces.\"\"\"\n\nimport pathlib\nfrom typing import Union\n\nfrom .. import __version__\nfrom ..contrib import utils\nfrom .build import get_standalone_crt_dir\nfrom .model_library_format import ExportableModule, export_model_library_format\nfrom .project_api import client\nfrom .transport import Transport, TransportTimeouts\n\n\nclass ProjectTransport(Transport):\n    \"\"\"A Transport implementation that uses the Project API client.\"\"\"\n\n    def __init__(self, api_client, options):\n        self._api_client = api_client\n        self._options = options\n        self._timeouts = None\n\n    def timeouts(self):\n        assert self._timeouts is not None, \"Transport not yet opened\"\n        return self._timeouts\n\n    def open(self):\n        reply = self._api_client.open_transport(self._options)\n        self._timeouts = TransportTimeouts(**reply[\"timeouts\"])\n\n    def close(self):\n        if not self._api_client.is_shutdown:\n            self._api_client.close_transport()\n            self._api_client.shutdown()\n\n    def write(self, data, timeout_sec):\n        self._api_client.write_transport(data, timeout_sec)\n\n    def read(self, n, timeout_sec):\n        return self._api_client.read_transport(n, timeout_sec)[\"data\"]\n\n\nclass TemplateProjectError(Exception):\n    \"\"\"Raised when the Project API server given to GeneratedProject reports is_template=True.\"\"\"\n\n\nclass GeneratedProject:\n    \"\"\"Defines a glue interface to interact with a generated project through the API server.\"\"\"\n\n    @classmethod\n    def from_directory(cls, project_dir: Union[pathlib.Path, str], options: dict):\n        return cls(client.instantiate_from_dir(project_dir), options)\n\n    def __init__(self, api_client, options):\n        self._api_client = api_client\n        self._options = options\n        self._info = self._api_client.server_info_query(__version__)\n        if self._info[\"is_template\"]:\n            raise TemplateProjectError()\n\n    def build(self):\n        self._api_client.build(self._options)\n\n    def flash(self):\n        self._api_client.flash(self._options)\n\n    def transport(self):\n        return ProjectTransport(self._api_client, self._options)\n\n    def info(self):\n        return self._info\n\n    @property\n    def options(self):\n        return self._options\n\n    @options.setter\n    def options(self, options):\n        self._options = options\n\n\nclass NotATemplateProjectError(Exception):\n    \"\"\"Raised when the API server given to TemplateProject reports is_template=false.\"\"\"\n\n\nclass TemplateProject:\n    \"\"\"Defines a glue interface to interact with a template project through the API Server.\"\"\"\n\n    @classmethod\n    def from_directory(cls, template_project_dir):\n        return cls(client.instantiate_from_dir(template_project_dir))\n\n    def __init__(self, api_client):\n        self._api_client = api_client\n        self._info = self._api_client.server_info_query(__version__)\n        if not self._info[\"is_template\"]:\n            raise NotATemplateProjectError()\n\n    def _check_project_options(self, options: dict):\n        \"\"\"Check if options are valid ProjectOptions\"\"\"\n        available_options = [option[\"name\"] for option in self.info()[\"project_options\"]]\n        if options and not set(options.keys()).issubset(available_options):\n            raise ValueError(\n                f\"\"\"options:{list(options)} include non valid ProjectOptions.\n                        Here is a list of available options:{list(available_options)}.\"\"\"\n            )\n\n    def generate_project_from_mlf(self, model_library_format_path, project_dir, options: dict):\n        \"\"\"Generate a project from MLF file.\"\"\"\n        self._check_project_options(options)\n        self._api_client.generate_project(\n            model_library_format_path=str(model_library_format_path),\n            standalone_crt_dir=get_standalone_crt_dir(),\n            project_dir=project_dir,\n            options=options,\n        )\n\n        return GeneratedProject.from_directory(project_dir, options)\n\n    def info(self):\n        return self._info\n\n    def generate_project(self, graph_executor_factory, project_dir, options):\n        \"\"\"Generate a project given GraphRuntimeFactory.\"\"\"\n        model_library_dir = utils.tempdir()\n        model_library_format_path = model_library_dir.relpath(\"model.tar\")\n        export_model_library_format(graph_executor_factory, model_library_format_path)\n\n        return self.generate_project_from_mlf(model_library_format_path, project_dir, options)\n\n\ndef generate_project(\n    template_project_dir: Union[pathlib.Path, str],\n    module: ExportableModule,\n    generated_project_dir: Union[pathlib.Path, str],\n    options: dict = None,\n):\n    \"\"\"Generate a project for an embedded platform that contains the given model.\n\n    Parameters\n    ----------\n    template_project_path : pathlib.Path or str\n        Path to a template project containing a microTVM Project API server.\n\n    generated_project_path : pathlib.Path or str\n        Path to a directory to be created and filled with the built project.\n\n    module : ExportableModule\n        A runtime.Module exportable as Model Library Format. The value returned from tvm.relay.build\n        or tvm.build.\n\n    options : dict\n        If given, Project API options given to the microTVM API server found in both\n        template_project_path and generated_project_path.\n\n    Returns\n    -------\n    GeneratedProject :\n        A class that wraps the generated project and which can be used to further interact with it.\n    \"\"\"\n    template = TemplateProject.from_directory(str(template_project_dir))\n    return template.generate_project(module, str(generated_project_dir), options)\n\n\ndef generate_project_from_mlf(\n    template_project_dir: Union[pathlib.Path, str],\n    project_dir: Union[pathlib.Path, str],\n    mlf_path: Union[pathlib.Path, str],\n    options: dict,\n):\n    \"\"\"Generate a project from a platform template and an existing Model Library Format archive.\n\n    Parameters\n    ----------\n    template_project_path : pathlib.Path or str\n        Path to a template project containing a microTVM Project API server.\n\n    project_dir : pathlib.Path or str\n        Path to a directory where the project will be created.\n\n    mlf_path : pathlib.Path or str\n        Path to the Model Library Format archive that will be used when creating\n        the new project. The archive file will be copied to project_dir.\n\n    options : dict\n        Project API options given to the microTVM API server for the specified platform.\n\n    Returns\n    -------\n    GeneratedProject :\n        A class that wraps the generated project and which can be used to further interact with it.\n    \"\"\"\n\n    template = TemplateProject.from_directory(str(template_project_dir))\n    return template.generate_project_from_mlf(str(mlf_path), str(project_dir), options)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/project_api/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"MicroTVM Project API Client and Server\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/project_api/client.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nProject API client.\n\"\"\"\nimport base64\nimport io\nimport json\nimport logging\nimport platform\nimport os\nimport pathlib\nimport subprocess\nimport sys\nimport typing\n\nfrom . import server\n\n_LOG = logging.getLogger(__name__)\n\n\nclass ProjectAPIErrorBase(Exception):\n    \"\"\"Base class for all Project API errors.\"\"\"\n\n\nclass ConnectionShutdownError(ProjectAPIErrorBase):\n    \"\"\"Raised when a request is made but the connection has been closed.\"\"\"\n\n\nclass MalformedReplyError(ProjectAPIErrorBase):\n    \"\"\"Raised when the server responds with an invalid reply.\"\"\"\n\n\nclass MismatchedIdError(ProjectAPIErrorBase):\n    \"\"\"Raised when the reply ID does not match the request.\"\"\"\n\n\nclass ProjectAPIServerNotFoundError(ProjectAPIErrorBase):\n    \"\"\"Raised when the Project API server can't be found in the repo.\"\"\"\n\n\nclass UnsupportedProtocolVersionError(ProjectAPIErrorBase):\n    \"\"\"Raised when the protocol version returned by the API server is unsupported.\"\"\"\n\n\nclass RPCError(ProjectAPIErrorBase):\n    def __init__(self, request, error):\n        ProjectAPIErrorBase.__init__()\n        self.request = request\n        self.error = error\n\n    def __str__(self):\n        return f\"Calling project API method {self.request['method']}:\" \"\\n\" f\"{self.error}\"\n\n\nclass ProjectAPIClient:\n    \"\"\"A client for the Project API.\"\"\"\n\n    def __init__(\n        self,\n        read_file: typing.BinaryIO,\n        write_file: typing.BinaryIO,\n        testonly_did_write_request: typing.Optional[typing.Callable] = None,\n    ):\n        self.read_file = io.TextIOWrapper(read_file, encoding=\"UTF-8\", errors=\"strict\")\n        self.write_file = io.TextIOWrapper(\n            write_file, encoding=\"UTF-8\", errors=\"strict\", write_through=True\n        )\n        self.testonly_did_write_request = testonly_did_write_request\n        self.next_request_id = 1\n\n    @property\n    def is_shutdown(self):\n        return self.read_file.closed\n\n    def shutdown(self):\n        if self.is_shutdown:  # pylint: disable=using-constant-test\n            return\n\n        self.read_file.close()\n        self.write_file.close()\n\n    def _request_reply(self, method, params):\n        if self.is_shutdown:  # pylint: disable=using-constant-test\n            raise ConnectionShutdownError(\"connection already closed\")\n\n        request = {\n            \"jsonrpc\": \"2.0\",\n            \"method\": method,\n            \"params\": params,\n            \"id\": self.next_request_id,\n        }\n        self.next_request_id += 1\n\n        request_str = json.dumps(request)\n        self.write_file.write(request_str)\n        _LOG.debug(\"send -> %s\", request_str)\n        self.write_file.write(\"\\n\")\n        if self.testonly_did_write_request:\n            self.testonly_did_write_request()  # Allow test to assert on server processing.\n        reply_line = self.read_file.readline()\n        _LOG.debug(\"recv <- %s\", reply_line)\n        if not reply_line:\n            self.shutdown()\n            raise ConnectionShutdownError(\"got EOF reading reply from API server\")\n\n        reply = json.loads(reply_line)\n\n        if reply.get(\"jsonrpc\") != \"2.0\":\n            raise MalformedReplyError(\n                f\"Server reply should include 'jsonrpc': '2.0'; \"\n                f\"saw jsonrpc={reply.get('jsonrpc')!r}\"\n            )\n\n        if reply[\"id\"] != request[\"id\"]:\n            raise MismatchedIdError(\n                f\"Reply id ({reply['id']}) does not equal request id ({request['id']}\"\n            )\n\n        if \"error\" in reply:\n            raise server.JSONRPCError.from_json(f\"calling method {method}\", reply[\"error\"])\n\n        if \"result\" not in reply:\n            raise MalformedReplyError(f\"Expected 'result' key in server reply, got {reply!r}\")\n\n        return reply[\"result\"]\n\n    def server_info_query(self, tvm_version: str):\n        reply = self._request_reply(\"server_info_query\", {\"tvm_version\": tvm_version})\n        if reply[\"protocol_version\"] != server.ProjectAPIServer._PROTOCOL_VERSION:\n            raise UnsupportedProtocolVersionError(\n                f'microTVM API Server supports protocol version {reply[\"protocol_version\"]}; '\n                f\"want {server.ProjectAPIServer._PROTOCOL_VERSION}\"\n            )\n\n        return reply\n\n    def generate_project(\n        self,\n        model_library_format_path: str,\n        standalone_crt_dir: str,\n        project_dir: str,\n        options: dict = None,\n    ):\n        return self._request_reply(\n            \"generate_project\",\n            {\n                \"model_library_format_path\": model_library_format_path,\n                \"standalone_crt_dir\": standalone_crt_dir,\n                \"project_dir\": project_dir,\n                \"options\": (options if options is not None else {}),\n            },\n        )\n\n    def build(self, options: dict = None):\n        return self._request_reply(\"build\", {\"options\": (options if options is not None else {})})\n\n    def flash(self, options: dict = None):\n        return self._request_reply(\"flash\", {\"options\": (options if options is not None else {})})\n\n    def open_transport(self, options: dict = None):\n        return self._request_reply(\n            \"open_transport\", {\"options\": (options if options is not None else {})}\n        )\n\n    def close_transport(self):\n        return self._request_reply(\"close_transport\", {})\n\n    def read_transport(self, n, timeout_sec):\n        reply = self._request_reply(\"read_transport\", {\"n\": n, \"timeout_sec\": timeout_sec})\n        reply[\"data\"] = base64.b85decode(reply[\"data\"])\n        return reply\n\n    def write_transport(self, data, timeout_sec):\n        return self._request_reply(\n            \"write_transport\",\n            {\"data\": str(base64.b85encode(data), \"utf-8\"), \"timeout_sec\": timeout_sec},\n        )\n\n\n# NOTE: windows support untested\nSERVER_LAUNCH_SCRIPT_FILENAME = (\n    f\"launch_microtvm_api_server.{'sh' if platform.system() != 'Windows' else '.bat'}\"\n)\n\n\nSERVER_PYTHON_FILENAME = \"microtvm_api_server.py\"\n\n\ndef instantiate_from_dir(project_dir: typing.Union[pathlib.Path, str], debug: bool = False):\n    \"\"\"Launch server located in project_dir, and instantiate a Project API Client\n    connected to it.\"\"\"\n    args = None\n    project_dir = pathlib.Path(project_dir)\n\n    python_script = project_dir / SERVER_PYTHON_FILENAME\n    if python_script.is_file():\n        args = [sys.executable, str(python_script)]\n\n    launch_script = project_dir / SERVER_LAUNCH_SCRIPT_FILENAME\n    if launch_script.is_file():\n        args = [str(launch_script)]\n\n    if args is None:\n        raise ProjectAPIServerNotFoundError(\n            f\"No Project API server found in project directory: {project_dir}\"\n            \"\\n\"\n            f\"Tried: {SERVER_LAUNCH_SCRIPT_FILENAME}, {SERVER_PYTHON_FILENAME}\"\n        )\n\n    api_server_read_fd, tvm_write_fd = os.pipe()\n    tvm_read_fd, api_server_write_fd = os.pipe()\n\n    args.extend([\"--read-fd\", str(api_server_read_fd), \"--write-fd\", str(api_server_write_fd)])\n    if debug:\n        args.append(\"--debug\")\n\n    api_server_proc = subprocess.Popen(  # pylint: disable=unused-variable\n        args, bufsize=0, pass_fds=(api_server_read_fd, api_server_write_fd), cwd=project_dir\n    )\n    os.close(api_server_read_fd)\n    os.close(api_server_write_fd)\n\n    return ProjectAPIClient(\n        os.fdopen(tvm_read_fd, \"rb\", buffering=0), os.fdopen(tvm_write_fd, \"wb\", buffering=0)\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/project_api/server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines a basic Project API server template.\n\nThis file is meant to be imported or copied into Project API servers, so it should not have any\nimports or dependencies outside of things strictly required to run the API server.\n\"\"\"\n\nimport abc\nimport argparse\nimport base64\nimport collections\nimport enum\nimport io\nimport json\nimport logging\nimport os\nimport pathlib\nimport re\nimport select\nimport sys\nimport time\nimport traceback\nimport typing\n\n\n_LOG = logging.getLogger(__name__)\n\n\n_ProjectOption = collections.namedtuple(\n    \"ProjectOption\", (\"name\", \"choices\", \"default\", \"type\", \"required\", \"optional\", \"help\")\n)\n\n\nclass ProjectOption(_ProjectOption):\n    \"\"\"Class used to keep the metadata associated to project options.\"\"\"\n\n    def __new__(cls, name, **kw):\n        \"\"\"Override __new__ to force all options except name to be specified as kwargs.\"\"\"\n        assert \"name\" not in kw\n        assert (\n            \"required\" in kw or \"optional\" in kw\n        ), \"at least one of 'required' or 'optional' must be specified.\"\n        assert \"type\" in kw, \"'type' field must be specified.\"\n\n        kw[\"name\"] = name\n        for param in [\"choices\", \"default\", \"required\", \"optional\"]:\n            kw.setdefault(param, None)\n\n        return super().__new__(cls, **kw)\n\n    def replace(self, attributes):\n        \"\"\"Update attributes associated to the project option.\"\"\"\n        updated_option = self\n        return updated_option._replace(**attributes)\n\n\nServerInfo = collections.namedtuple(\n    \"ServerInfo\", (\"platform_name\", \"is_template\", \"model_library_format_path\", \"project_options\")\n)\n\n\n# Timeouts supported by the underlying C++ MicroSession.\n#\n# session_start_retry_timeout_sec : float\n#     Number of seconds to wait for the device to send a kSessionStartReply after sending the\n#     initial session start message. After this time elapses another\n#     kSessionTerminated-kSessionStartInit train is sent. 0 disables this.\n# session_start_timeout_sec : float\n#     Total number of seconds to wait for the session to be established. After this time, the\n#     client gives up trying to establish a session and raises an exception.\n# session_established_timeout_sec : float\n#     Number of seconds to wait for a reply message after a session has been established. 0\n#     disables this.\nTransportTimeouts = collections.namedtuple(\n    \"TransportTimeouts\",\n    [\n        \"session_start_retry_timeout_sec\",\n        \"session_start_timeout_sec\",\n        \"session_established_timeout_sec\",\n    ],\n)\n\n\nclass ErrorCode(enum.IntEnum):\n    \"\"\"Enumerates error codes which can be returned. Includes JSON-RPC standard and custom codes.\"\"\"\n\n    # Custom (in reserved error code space).\n    SERVER_ERROR = -32000  # A generic error was raised while processing the request.\n\n    # JSON-RPC standard\n    PARSE_ERROR = -32700\n    INVALID_REQUEST = -32600\n    METHOD_NOT_FOUND = -32601\n    INVALID_PARAMS = -32602\n    INTERNAL_ERROR = -32603\n\n\nclass JSONRPCError(Exception):\n    \"\"\"An error class with properties that meet the JSON-RPC error spec.\"\"\"\n\n    def __init__(self, code, message, data, client_context=None):\n        Exception.__init__(self)\n        self.code = code\n        self.message = message\n        self.data = data\n        self.client_context = client_context\n\n    def to_json(self):\n        return {\n            \"code\": self.code,\n            \"message\": self.message,\n            \"data\": self.data,\n        }\n\n    def __str__(self):\n        data_str = \"\"\n        if self.data:\n            if isinstance(self.data, dict) and self.data.get(\"traceback\"):\n                data_str = f'\\n{self.data[\"traceback\"]}'\n            else:\n                data_str = f\"\\n{self.data!r}\"\n        return f\"JSON-RPC error # {self.code}: {self.message}\" + data_str\n\n    @classmethod\n    def from_json(cls, client_context, json_error):\n        \"\"\"Convert an encapsulated ServerError into JSON-RPC compliant format.\"\"\"\n        found_server_error = False\n        try:\n            if ErrorCode(json_error[\"code\"]) == ErrorCode.SERVER_ERROR:\n                found_server_error = True\n        except ValueError:\n            ServerError.from_json(client_context, json_error)\n\n        if found_server_error:\n            return ServerError.from_json(client_context, json_error)\n\n        return cls(\n            json_error[\"code\"],\n            json_error[\"message\"],\n            json_error.get(\"data\", None),\n            client_context=client_context,\n        )\n\n\nclass ServerError(JSONRPCError):\n    \"\"\"Superclass for JSON-RPC errors which occur while processing valid requests.\"\"\"\n\n    @classmethod\n    def from_exception(cls, exc, **kw):\n        to_return = cls(**kw)\n        to_return.set_traceback(traceback.TracebackException.from_exception(exc).format())\n        return to_return\n\n    def __init__(self, message=None, data=None, client_context=None):\n        if self.__class__ == ServerError:\n            assert message is not None, \"Plain ServerError must have message=\"\n        else:\n            assert (\n                message is None\n            ), f\"ServerError subclasses must not supply message=; got {message!r}\"\n            message = self.__class__.__name__\n\n        super(ServerError, self).__init__(ErrorCode.SERVER_ERROR, message, data)\n        self.client_context = client_context\n\n    def __str__(self):\n        context_str = f\"{self.client_context}: \" if self.client_context is not None else \"\"\n        super_str = super(ServerError, self).__str__()\n        return context_str + super_str\n\n    def set_traceback(self, traceback):  # pylint: disable=redefined-outer-name\n        \"\"\"Format a traceback to be embedded in the JSON-RPC format.\"\"\"\n\n        if self.data is None:\n            self.data = {}\n\n        if \"traceback\" not in self.data:\n            # NOTE: TVM's FFI layer reorders Python stack traces several times and strips\n            # intermediary lines that start with \"Traceback\". This logic adds a comment to the first\n            # stack frame to explicitly identify the first stack frame line that occurs on the\n            # server.\n            traceback_list = list(traceback)\n\n            # The traceback list contains one entry per stack frame, and each entry contains 1-2\n            # lines:\n            #    File \"path/to/file\", line 123, in <method>:\n            #      <copy of the line>\n            # We want to place a comment on the first line of the outermost frame to indicate this\n            # is the server-side stack frame.\n            first_frame_list = traceback_list[1].split(\"\\n\")\n            self.data[\"traceback\"] = (\n                traceback_list[0]\n                + f\"{first_frame_list[0]}  # <--- Outermost server-side stack frame\\n\"\n                + \"\\n\".join(first_frame_list[1:])\n                + \"\".join(traceback_list[2:])\n            )\n\n    @classmethod\n    def from_json(cls, client_context, json_error):\n        assert json_error[\"code\"] == ErrorCode.SERVER_ERROR\n\n        for sub_cls in cls.__subclasses__():\n            if sub_cls.__name__ == json_error[\"message\"]:\n                return sub_cls(\n                    data=json_error.get(\"data\"),\n                    client_context=client_context,\n                )\n\n        return cls(\n            json_error[\"message\"], data=json_error.get(\"data\"), client_context=client_context\n        )\n\n\nclass TransportClosedError(ServerError):\n    \"\"\"Raised when a transport can no longer be used due to underlying I/O problems.\"\"\"\n\n\nclass IoTimeoutError(ServerError):\n    \"\"\"Raised when the I/O operation could not be completed before the timeout.\n\n    Specifically:\n     - when no data could be read before the timeout\n     - when some of the write data could be written before the timeout\n\n    Note the asymmetric behavior of read() vs write(), since in one case the total length of the\n    data to transfer is known.\n    \"\"\"\n\n\nclass UnsupportedTVMVersionError(ServerError):\n    \"\"\"Raised when the version of TVM supplied to server_info_query is unsupported.\"\"\"\n\n\nclass ProjectAPIHandler(metaclass=abc.ABCMeta):\n    \"\"\"The interface class for all Project API implementations.\n\n    Extend this class in your microtvm_api_server.py and implement each function defined here.\n    \"\"\"\n\n    @abc.abstractmethod\n    def server_info_query(self, tvm_version: str) -> ServerInfo:\n        \"\"\"Initial request issued by TVM to retrieve metadata about this API server and project.\n\n        Should this API server not\n\n        Parameters\n        ----------\n        tvm_version : str\n            The value of tvm.__version__.\n\n        Returns\n        -------\n        ServerInfo :\n            A ServerInfo namedtuple containing the metadata needed by TVM.\n\n        Raises\n        ------\n        UnsupportedTVMVersionError :\n           When tvm_version indicates a known-unsupported version of TVM.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def generate_project(\n        self,\n        model_library_format_path: pathlib.Path,\n        standalone_crt_dir: pathlib.Path,\n        project_dir: pathlib.Path,\n        options: dict,\n    ):\n        \"\"\"Generate a project from the given artifacts, copying ourselves to that project.\n\n        Parameters\n        ----------\n        model_library_format_path : pathlib.Path\n            Path to the Model Library Format tar archive.\n        standalone_crt_dir : pathlib.Path\n            Path to the root directory of the \"standalone_crt\" TVM build artifact. This contains the\n            TVM C runtime.\n        project_dir : pathlib.Path\n            Path to a nonexistent directory which should be created and filled with the generated\n            project.\n        options : dict\n            Dict mapping option name to ProjectOption.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def build(self, options: dict):\n        \"\"\"Build the project, enabling the flash() call to made.\n\n        Parameters\n        ----------\n        options : Dict[str, ProjectOption]\n            ProjectOption which may influence the build, keyed by option name.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def flash(self, options: dict):\n        \"\"\"Program the project onto the device.\n\n        Parameters\n        ----------\n        options : Dict[str, ProjectOption]\n            ProjectOption which may influence the programming process, keyed by option name.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def open_transport(self, options: dict) -> TransportTimeouts:\n        \"\"\"Open resources needed for the transport layer.\n\n        This function might e.g. open files or serial ports needed in write_transport or\n        read_transport.\n\n        Calling this function enables the write_transport and read_transport calls. If the\n        transport is not open, this method is a no-op.\n\n        Parameters\n        ----------\n        options : Dict[str, ProjectOption]\n            ProjectOption which may influence the programming process, keyed by option name.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def close_transport(self):\n        \"\"\"Close resources needed to operate the transport layer.\n\n        This function might e.g. close files or serial ports needed in write_transport or\n        read_transport.\n\n        Calling this function disables the write_transport and read_transport calls. If the\n        transport is not open, this method is a no-op.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    # pylint: disable=unidiomatic-typecheck\n    def read_transport(self, n: int, timeout_sec: typing.Union[float, type(None)]) -> bytes:\n        \"\"\"Read data from the transport.\n\n        Parameters\n        ----------\n        n : int\n            The exact number of bytes to read from the transport.\n        timeout_sec : Union[float, None]\n            Number of seconds to wait for at least one byte to be written before timing out. If\n            timeout_sec is 0, write should attempt to service the request in a non-blocking fashion.\n            If timeout_sec is None, write should block until all `n` bytes of data can be returned.\n\n        Returns\n        -------\n        bytes :\n            Data read from the channel. Should be exactly `n` bytes long.\n\n        Raises\n        ------\n        TransportClosedError :\n            When the transport layer determines that the transport can no longer send or receive\n            data due to an underlying I/O problem (i.e. file descriptor closed, cable removed, etc).\n\n        IoTimeoutError :\n            When `timeout_sec` elapses without receiving any data.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_transport(self, data: bytes, timeout_sec: float):\n        \"\"\"Write data to the transport.\n\n        This function should either write all bytes in `data` or raise an exception.\n\n        Parameters\n        ----------\n        data : bytes\n            The data to write over the channel.\n        timeout_sec : Union[float, None]\n            Number of seconds to wait for all bytes to be written before timing out. If timeout_sec\n            is 0, write should attempt to service the request in a non-blocking fashion. If\n            timeout_sec is None, write should block until it has written all data.\n\n        Raises\n        ------\n        TransportClosedError :\n            When the transport layer determines that the transport can no longer send or receive\n            data due to an underlying I/O problem (i.e. file descriptor closed, cable removed, etc).\n\n        IoTimeoutError :\n            When `timeout_sec` elapses without receiving any data.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass ProjectAPIServer:\n    \"\"\"Base class for Project API Servers.\n\n    This API server implements communication using JSON-RPC 2.0:\n        https://www.jsonrpc.org/specification\n\n    Suggested use of this class is to import this module or copy this file into Project Generator\n    implementations, then instantiate it with server.start().\n\n    This RPC server is single-threaded, blocking, and one-request-at-a-time. Don't get anxious.\n    \"\"\"\n\n    _PROTOCOL_VERSION = 1\n\n    def __init__(\n        self, read_file: typing.BinaryIO, write_file: typing.BinaryIO, handler: ProjectAPIHandler\n    ):\n        \"\"\"Initialize a new ProjectAPIServer.\n\n        Parameters\n        ----------\n        read_file : BinaryIO\n            A file-like object used to read binary data from the client.\n        write_file : BinaryIO\n            A file-like object used to write binary data to the client.\n        handler : ProjectAPIHandler\n            A class which extends the abstract class ProjectAPIHandler and implements the server RPC\n            functions.\n        \"\"\"\n        self._read_file = io.TextIOWrapper(read_file, encoding=\"UTF-8\", errors=\"strict\")\n        self._write_file = io.TextIOWrapper(\n            write_file, encoding=\"UTF-8\", errors=\"strict\", write_through=True\n        )\n        self._handler = handler\n\n    def serve_forever(self):\n        \"\"\"Serve requests until no more are available.\"\"\"\n        has_more = True\n        while has_more:\n            has_more = self.serve_one_request()\n\n    def serve_one_request(self):\n        \"\"\"Read, process, and reply to a single request from read_file.\n\n        When errors occur reading the request line or loading the request into JSON, they are\n        propagated to the caller (the stream is then likely corrupted and no further requests\n        should be served. When errors occur past this point, they are caught and send back to the\n        client.\n\n        Return\n        ----------\n        bool :\n            True when more data could be read from read_file, False otherwise.\n        \"\"\"\n        try:\n            line = self._read_file.readline()\n            _LOG.debug(\"read request <- %s\", line)\n            if not line:\n                return False\n\n            request = json.loads(line)\n\n        except EOFError:\n            _LOG.error(\"EOF\")\n            return False\n\n        except Exception as exc:  # pylint: disable=broad-except\n            _LOG.error(\"Caught error reading request\", exc_info=1)\n            return False\n\n        did_validate = False\n        try:\n            self._validate_request(request)\n            did_validate = True\n            self._dispatch_request(request)\n        except JSONRPCError as exc:\n            if isinstance(exc, ServerError):\n                exc.set_traceback(traceback.TracebackException.from_exception(exc).format())\n            request_id = None if not did_validate else request.get(\"id\")\n            self._reply_error(request_id, exc)\n            return did_validate\n        except Exception as exc:  # pylint: disable=broad-except\n            message = \"validating request\"\n            if did_validate:\n                message = f\"calling method {request['method']}\"\n\n            exc = ServerError.from_exception(exc, message=message)\n            request_id = None if not isinstance(request, dict) else request.get(\"id\")\n            self._reply_error(request_id, exc)\n            return did_validate\n\n        return True\n\n    VALID_METHOD_RE = re.compile(\"^[a-zA-Z0-9_]+$\")\n\n    def _validate_request(self, request):\n        if not isinstance(request, dict):\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST, f\"request: want dict; got {request!r}\", None\n            )\n\n        jsonrpc = request.get(\"jsonrpc\")\n        if jsonrpc != \"2.0\":\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST, f'request[\"jsonrpc\"]: want \"2.0\"; got {jsonrpc!r}', None\n            )\n\n        method = request.get(\"method\")\n        if not isinstance(method, str):\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST, f'request[\"method\"]: want str; got {method!r}', None\n            )\n\n        if not self.VALID_METHOD_RE.match(method):\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST,\n                f'request[\"method\"]: should match regex {self.VALID_METHOD_RE.pattern}; '\n                f\"got {method!r}\",\n                None,\n            )\n\n        params = request.get(\"params\")\n        if not isinstance(params, dict):\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST, f'request[\"params\"]: want dict; got {type(params)}', None\n            )\n\n        request_id = request.get(\"id\")\n        # pylint: disable=unidiomatic-typecheck\n        if not isinstance(request_id, (str, int, type(None))):\n            raise JSONRPCError(\n                ErrorCode.INVALID_REQUEST,\n                f'request[\"id\"]: want str, number, null; got {request_id!r}',\n                None,\n            )\n\n    def _dispatch_request(self, request):\n        method = request[\"method\"]\n\n        interface_method = getattr(ProjectAPIHandler, method, None)\n        if interface_method is None:\n            raise JSONRPCError(\n                ErrorCode.METHOD_NOT_FOUND, f'{request[\"method\"]}: no such method', None\n            )\n\n        has_preprocessing = True\n        dispatch_method = getattr(self, f\"_dispatch_{method}\", None)\n        if dispatch_method is None:\n            dispatch_method = getattr(self._handler, method)\n            has_preprocessing = False\n\n        request_params = request[\"params\"]\n        params = {}\n\n        for var_name, var_type in typing.get_type_hints(interface_method).items():\n            if var_name in (\"self\", \"return\"):\n                continue\n\n            # NOTE: types can only be JSON-compatible types, so var_type is expected to be of type\n            # 'type'.\n            if var_name not in request_params:\n                raise JSONRPCError(\n                    ErrorCode.INVALID_PARAMS,\n                    f'method {request[\"method\"]}: parameter {var_name} not given',\n                    None,\n                )\n\n            param = request_params[var_name]\n            if not has_preprocessing and not isinstance(param, var_type):\n                raise JSONRPCError(\n                    ErrorCode.INVALID_PARAMS,\n                    f'method {request[\"method\"]}: parameter {var_name}: want {var_type!r}, '\n                    f\"got {type(param)!r}\",\n                    None,\n                )\n\n            params[var_name] = param\n\n        extra_params = [p for p in request[\"params\"] if p not in params]\n        if extra_params:\n            raise JSONRPCError(\n                ErrorCode.INVALID_PARAMS,\n                f'{request[\"method\"]}: extra parameters: {\", \".join(extra_params)}',\n                None,\n            )\n\n        return_value = dispatch_method(**params)\n        self._write_reply(request[\"id\"], result=return_value)\n\n    def _write_reply(self, request_id, result=None, error=None):\n        reply_dict = {\n            \"jsonrpc\": \"2.0\",\n            \"id\": request_id,\n        }\n\n        if error is not None:\n            assert (\n                result is None\n            ), f\"Want either result= or error=, got result={result!r} and error={error!r})\"\n            reply_dict[\"error\"] = error\n        else:\n            reply_dict[\"result\"] = result\n\n        reply_str = json.dumps(reply_dict)\n        _LOG.debug(\"write reply -> %r\", reply_dict)\n        self._write_file.write(reply_str)\n        self._write_file.write(\"\\n\")\n\n    def _reply_error(self, request_id, exception):\n        self._write_reply(request_id, error=exception.to_json())\n\n    def _dispatch_generate_project(\n        self, model_library_format_path, standalone_crt_dir, project_dir, options\n    ):\n        return self._handler.generate_project(\n            pathlib.Path(model_library_format_path),\n            pathlib.Path(standalone_crt_dir),\n            pathlib.Path(project_dir),\n            options,\n        )\n\n    def _dispatch_server_info_query(self, tvm_version):\n        query_reply = self._handler.server_info_query(tvm_version)\n        to_return = query_reply._asdict()\n        if to_return[\"model_library_format_path\"] is not None:\n            to_return[\"model_library_format_path\"] = str(to_return[\"model_library_format_path\"])\n        to_return.setdefault(\"protocol_version\", self._PROTOCOL_VERSION)\n        to_return[\"project_options\"] = [o._asdict() for o in query_reply.project_options]\n        return to_return\n\n    def _dispatch_open_transport(self, options):\n        reply = self._handler.open_transport(options)\n        return {\"timeouts\": reply._asdict()}\n\n    def _dispatch_read_transport(self, n, timeout_sec):\n        reply_data = self._handler.read_transport(n, timeout_sec)\n        return {\"data\": str(base64.b85encode(reply_data), \"utf-8\")}\n\n    def _dispatch_write_transport(self, data, timeout_sec):\n        self._handler.write_transport(base64.b85decode(data), timeout_sec)\n\n\ndef _await_nonblocking_ready(rlist, wlist, timeout_sec=None, end_time=None):\n    if end_time is None:\n        return True\n\n    if timeout_sec is None:\n        timeout_sec = max(0, end_time - time.monotonic())\n    rlist, wlist, xlist = select.select(rlist, wlist, rlist + wlist, timeout_sec)\n    if not rlist and not wlist and not xlist:\n        raise IoTimeoutError()\n\n    return True\n\n\ndef read_with_timeout(fd, n, timeout_sec):  # pylint: disable=invalid-name\n    \"\"\"Read data from a file descriptor, with timeout.\n\n    This function is intended as a helper function for implementations of ProjectAPIHandler\n    read_transport. Tested on Linux and OS X. Not tested on Windows.\n\n    Parameters\n    ----------\n    fd : int\n        File descriptor to read from. Must be opened in non-blocking mode (e.g. with O_NONBLOCK)\n        if timeout_sec is not None.\n\n    n : int\n        Maximum number of bytes to read.\n\n    timeout_sec : float or None\n        If not None, maximum number of seconds to wait before raising IoTimeoutError.\n\n    Returns\n    -------\n    bytes :\n        If at least one byte was received before timeout_sec, returns a bytes object with length\n        in [1, n]. If timeout_sec is None, returns the equivalent of os.read(fd, n).\n\n    Raises\n    ------\n    IoTimeoutException :\n        When timeout_sec is not None and that number of seconds elapses before any data is read.\n    \"\"\"\n    end_time = None if timeout_sec is None else time.monotonic() + timeout_sec\n\n    while True:\n        _await_nonblocking_ready([fd], [], end_time=end_time)\n        try:\n            to_return = os.read(fd, n)\n            break\n        except BlockingIOError:\n            pass\n\n    # When EOF is reached, close the file.\n    if not to_return:\n        os.close(fd)\n        raise TransportClosedError()\n\n    return to_return\n\n\ndef write_with_timeout(fd, data, timeout_sec):  # pylint: disable=invalid-name\n    \"\"\"Write data to a file descriptor, with timeout.\n\n    This function is intended as a helper function for implementations of ProjectAPIHandler\n    write_transport. Tested on Linux and OS X. Not tested on Windows.\n\n    Parameters\n    ----------\n    fd : int\n        File descriptor to read from. Must be opened in non-blocking mode (e.g. with O_NONBLOCK)\n        if timeout_sec is not None.\n\n    data : bytes\n        Data to write.\n\n    timeout_sec : float or None\n        If not None, maximum number of seconds to wait before raising IoTimeoutError.\n\n    Returns\n    -------\n    int :\n        The number of bytes written to the file descriptor, if any bytes were written. A value\n        in [1, len(data)]. If timeout_sec is None, returns the equivalent of os.write(fd, data).\n\n    Raises\n    ------\n    IoTimeoutException :\n        When timeout_sec is not None and that number of seconds elapses before any data is read.\n    \"\"\"\n    end_time = None if timeout_sec is None else time.monotonic() + timeout_sec\n\n    num_written = 0\n    while data:\n        try:\n            _await_nonblocking_ready([], [fd], end_time=end_time)\n        except IoTimeoutError as exc:\n            if num_written:\n                return num_written\n\n            raise exc\n\n        num_written_this_cycle = os.write(fd, data)\n\n        if not num_written_this_cycle:\n            os.close(fd)\n            raise base.TransportClosedError()\n\n        data = data[num_written_this_cycle:]\n        num_written += num_written_this_cycle\n\n    return num_written\n\n\ndef default_project_options(**kw) -> typing.List[ProjectOption]:\n    \"\"\"Get default Project Options\n\n    Attributes of any default option can be updated. Here is an example\n    when attribute `optional` from `verbose` option needs to be updates:\n\n        default_project_options(verbose={\"optional\": [\"build\"]})\n\n    This will update the `optional` attribute of `verbose` ProjectOption\n    to be `[\"build\"]`.\n\n    Returns\n    -------\n    options: List[ProjectOption]\n        A list of default ProjectOption with modifications.\n    \"\"\"\n    options = [\n        ProjectOption(\n            \"verbose\",\n            optional=[\"generate_project\"],\n            type=\"bool\",\n            default=False,\n            help=\"Run build with verbose output.\",\n        ),\n        ProjectOption(\n            \"project_type\",\n            required=[\"generate_project\"],\n            type=\"str\",\n            help=\"Type of project to generate.\",\n        ),\n        ProjectOption(\n            \"board\",\n            required=[\"generate_project\"],\n            type=\"str\",\n            help=\"Name of the board to build for.\",\n        ),\n        ProjectOption(\n            \"cmsis_path\",\n            optional=[\"generate_project\"],\n            type=\"str\",\n            default=None,\n            help=\"Path to the CMSIS directory.\",\n        ),\n        ProjectOption(\n            \"warning_as_error\",\n            optional=[\"generate_project\"],\n            type=\"bool\",\n            default=False,\n            help=\"Treat warnings as errors and raise an Exception.\",\n        ),\n        ProjectOption(\n            \"compile_definitions\",\n            optional=[\"generate_project\"],\n            type=\"str\",\n            default=None,\n            help=\"Extra definitions added project compile.\",\n        ),\n        ProjectOption(\n            \"extra_files_tar\",\n            optional=[\"generate_project\"],\n            type=\"str\",\n            default=None,\n            help=\"If given, during generate_project, \"\n            \"uncompress the tarball at this path into the project dir.\",\n        ),\n    ]\n    for name, config in kw.items():\n        option_found = False\n        for ind, option in enumerate(options):\n            if option.name == name:\n                options[ind] = option.replace(config)\n                option_found = True\n                break\n        if not option_found:\n            raise ValueError(\"Option {} was not found in default ProjectOptions.\".format(name))\n\n    return options\n\n\ndef main(handler: ProjectAPIHandler, argv: typing.List[str] = None):\n    \"\"\"Start a Project API server.\n\n    Parameters\n    ----------\n    argv : list[str]\n        Command-line parameters to this program. If not given, sys.argv is used.\n    handler : ProjectAPIHandler\n        Handler class that implements the API server RPC calls.\n    \"\"\"\n    if argv is None:\n        argv = sys.argv[1:]\n\n    parser = argparse.ArgumentParser(description=\"Generic TVM Project API server entry point\")\n    parser.add_argument(\n        \"--read-fd\",\n        type=int,\n        required=True,\n        help=\"Numeric file descriptor where RPC requests should be read.\",\n    )\n    parser.add_argument(\n        \"--write-fd\",\n        type=int,\n        required=True,\n        help=\"Numeric file descriptor where RPC replies should be written.\",\n    )\n    parser.add_argument(\n        \"--debug\", action=\"store_true\", help=\"When given, configure logging at DEBUG level.\"\n    )\n    args = parser.parse_args()\n\n    logging.basicConfig(level=\"DEBUG\" if args.debug else \"INFO\", stream=sys.stderr)\n\n    read_file = os.fdopen(args.read_fd, \"rb\", buffering=0)\n    write_file = os.fdopen(args.write_fd, \"wb\", buffering=0)\n\n    server = ProjectAPIServer(read_file, write_file, handler)\n    server.serve_forever()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/session.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines a top-level glue class that operates the Transport and Flasher classes.\"\"\"\n\nimport json\nimport logging\nimport sys\nimport os\nimport pathlib\nimport shutil\nfrom typing import Union\nfrom ..error import register_error\nfrom .._ffi import get_global_func, register_func\nfrom ..contrib import graph_executor\nfrom ..contrib import utils\nfrom ..contrib.debugger import debug_executor\nfrom ..rpc import RPCSession\nfrom . import project\nfrom .transport import IoTimeoutError\nfrom .transport import TransportLogger\n\ntry:\n    from .base import _rpc_connect\nexcept ImportError:\n    raise ImportError(\"micro tvm is not enabled. Set USE_MICRO to ON in config.cmake\")\n\n\n@register_error\nclass SessionTerminatedError(Exception):\n    \"\"\"Raised when a transport read operation discovers that the remote session is terminated.\"\"\"\n\n\nclass Session:\n    \"\"\"MicroTVM Device Session\n\n    Parameters\n    ----------\n    config : dict\n        configuration for this session (as generated by\n        `tvm.micro.device.host.default_config()`, for example)\n\n    Example\n    --------\n    .. code-block:: python\n\n      c_mod = ...  # some module generated with \"c\" as the target\n      dev_config = micro.device.arm.stm32f746xx.default_config('127.0.0.1', 6666)\n      with tvm.micro.Session(dev_config) as sess:\n          micro_mod = sess.create_micro_mod(c_mod)\n    \"\"\"\n\n    def __init__(\n        self,\n        transport_context_manager=None,\n        session_name=\"micro-rpc\",\n        timeout_override=None,\n    ):\n        \"\"\"Configure a new session.\n\n        Parameters\n        ----------\n        transport_context_manager : ContextManager[transport.Transport]\n            If given, `flasher` and `binary` should not be given. On entry, this context manager\n            should establish a transport between this TVM instance and the device.\n        session_name : str\n            Name of the session, used for debugging.\n        timeout_override : TransportTimeouts\n            If given, TransportTimeouts that govern the way Receive() behaves. If not given, this is\n            determined by calling has_flow_control() on the transport.\n        \"\"\"\n        self.transport_context_manager = transport_context_manager\n        self.session_name = session_name\n        self.timeout_override = timeout_override\n\n        self._rpc = None\n        self._graph_executor = None\n        self._enable_rpc_logger = False\n\n        self._exit_called = False\n\n    def get_system_lib(self):\n        return self._rpc.get_function(\"runtime.SystemLib\")()\n\n    def create_aot_executor(self):\n        return self._rpc.get_function(\"tvm.aot_executor.create\")(\n            self.get_system_lib(), self.device, \"default\"\n        )\n\n    def _wrap_transport_read(self, n, timeout_microsec):\n        try:\n            return self.transport.read(\n                n, float(timeout_microsec) / 1e6 if timeout_microsec is not None else None\n            )\n        except IoTimeoutError:\n            return bytes([])\n\n    def _wrap_transport_write(self, data, timeout_microsec):\n        self.transport.write(\n            data, float(timeout_microsec) / 1e6 if timeout_microsec is not None else None\n        )\n\n        return len(data)  # TODO(areusch): delete\n\n    def __enter__(self):\n        \"\"\"Initialize this session and establish an RPC session with the on-device RPC server.\n\n        Returns\n        -------\n        Session :\n            Returns self.\n        \"\"\"\n        self.transport = TransportLogger(\n            self.session_name, self.transport_context_manager, level=logging.DEBUG\n        ).__enter__()\n\n        try:\n            timeouts = self.timeout_override\n            if timeouts is None:\n                timeouts = self.transport.timeouts()\n\n            self._rpc = RPCSession(\n                _rpc_connect(\n                    self.session_name,\n                    self._wrap_transport_write,\n                    self._wrap_transport_read,\n                    int(timeouts.session_start_retry_timeout_sec * 1e6),\n                    int(timeouts.session_start_timeout_sec * 1e6),\n                    int(timeouts.session_established_timeout_sec * 1e6),\n                    self._cleanup,\n                    self._enable_rpc_logger,\n                )\n            )\n            self.device = self._rpc.cpu(0)\n            return self\n\n        except:\n            self.transport.__exit__(*sys.exc_info())\n            raise\n\n    def __exit__(self, exc_type, exc_value, exc_traceback):\n        \"\"\"Tear down this session and associated RPC session resources.\"\"\"\n        if not self._exit_called:\n            self._exit_called = True\n            self.transport.__exit__(exc_type, exc_value, exc_traceback)\n            shutdown_func = self._rpc._sess.get_function(\"CloseRPCConnection\")\n            shutdown_func()\n\n    def _cleanup(self):\n        self.__exit__(None, None, None)\n\n\ndef lookup_remote_linked_param(mod, storage_id, template_tensor, device):\n    \"\"\"Lookup a parameter that has been pre-linked into a remote (i.e. over RPC) Module.\n\n    This function signature matches the signature built by\n\n    Parameters\n    ----------\n    mod : tvm.runtime.Module\n        The remote Module containing the pre-linked parameters.\n    storage_id : int\n        An integer identifying the pre-linked paramter to find\n    template_tensor : DLTensor\n        A DLTensor containing metadata that should be filled-in to the returned NDArray. This\n        function should mostly not inspect this, and just pass it along to\n        NDArrayFromRemoteOpaqueHandle.\n    device : Device\n        The remote CPU device to be used with the returned NDArray.\n\n    Returns\n    -------\n    tvm.nd.NDArray :\n        NDArray containing the pre-linked parameter.\n    \"\"\"\n    try:\n        lookup_linked_param = mod.get_function(\"_lookup_linked_param\")\n    except AttributeError:\n        return None\n\n    remote_data = lookup_linked_param(storage_id)\n    if remote_data is None:\n        return None\n\n    return get_global_func(\"tvm.rpc.NDArrayFromRemoteOpaqueHandle\")(\n        mod, remote_data, template_tensor, device, None\n    )\n\n\ndef create_local_graph_executor(graph_json_str, mod, device):\n    \"\"\"Create a local graph executor driving execution on the remote CPU device given.\n\n    Parameters\n    ----------\n    graph_json_str : str\n        A string containing the graph representation.\n\n    mod : tvm.runtime.Module\n        The remote module containing functions in graph_json_str.\n\n    device : tvm.runtime.Device\n        The remote CPU execution device.\n\n    Returns\n    -------\n    tvm.contrib.GraphExecutor :\n         A local graph executor instance that executes on the remote device.\n    \"\"\"\n    device_type_id = [device.device_type, device.device_id]\n    fcreate = get_global_func(\"tvm.graph_executor.create\")\n    return graph_executor.GraphModule(\n        fcreate(graph_json_str, mod, lookup_remote_linked_param, *device_type_id)\n    )\n\n\ndef create_local_debug_executor(graph_json_str, mod, device, dump_root=None):\n    \"\"\"Create a local debug runtime driving execution on the remote CPU device given.\n\n    Parameters\n    ----------\n    graph_json_str : str\n        A string containing the graph representation.\n\n    mod : tvm.runtime.Module\n        The remote module containing functions in graph_json_str.\n\n    device : tvm.runtime.Device\n        The remote CPU execution device.\n\n    dump_root : Optional[str]\n        If given, passed as dump_root= to GraphModuleDebug.\n\n    Returns\n    -------\n    tvm.contrib.GraphExecutor :\n         A local graph executor instance that executes on the remote device.\n    \"\"\"\n    device_type_id = [device.device_type, device.device_id]\n    fcreate = get_global_func(\"tvm.graph_executor_debug.create\")\n    return debug_executor.GraphModuleDebug(\n        fcreate(graph_json_str, mod, lookup_remote_linked_param, *device_type_id),\n        [device],\n        graph_json_str,\n        dump_root=dump_root,\n    )\n\n\n@register_func(\"tvm.micro.compile_and_create_micro_session\")\ndef compile_and_create_micro_session(\n    mod_src_bytes: bytes,\n    template_project_dir: str,\n    project_options: dict = None,\n    project_dir: Union[os.PathLike, str] = None,\n    use_existing: bool = False,\n):\n    \"\"\"Compile the given libraries and sources into a MicroBinary, then invoke create_micro_session.\n\n    Parameters\n    ----------\n    mod_src_bytes : bytes\n        The content of a tarfile which contains the TVM-generated sources which together form the\n        SystemLib. This tar is expected to be created by export_library. The tar will be extracted\n        into a directory and the sources compiled into a MicroLibrary using the Compiler.\n\n    template_project_dir: str\n        The path to a template microTVM Project API project which is used to generate the embedded\n        project that is built and flashed onto the target device.\n\n    project_options: dict\n        Options for the microTVM API Server contained in template_project_dir.\n\n    project_dir: Union[os.PathLike, str]\n        if use_existing is False: The path to save the generated microTVM Project.\n        if use_existing is True: The path to a generated microTVM Project for debugging.\n\n    use_existing: bool\n        skips the project generation and opens transport to the project at the project_dir address.\n    \"\"\"\n\n    if use_existing:\n        project_dir = pathlib.Path(project_dir)\n        assert project_dir.is_dir(), f\"{project_dir} does not exist.\"\n        build_dir = project_dir / \"generated-project\" / \"build\"\n        shutil.rmtree(build_dir)\n        generated_project = project.GeneratedProject.from_directory(\n            project_dir / \"generated-project\",\n            options=json.loads(project_options),\n        )\n    else:\n        if project_dir:\n            temp_dir = utils.tempdir(custom_path=project_dir, keep_for_debug=True)\n        else:\n            temp_dir = utils.tempdir()\n\n        model_library_format_path = temp_dir / \"model.tar.gz\"\n        with open(model_library_format_path, \"wb\") as mlf_f:\n            mlf_f.write(mod_src_bytes)\n\n        try:\n            template_project = project.TemplateProject.from_directory(template_project_dir)\n            generated_project = template_project.generate_project_from_mlf(\n                model_library_format_path,\n                str(temp_dir / \"generated-project\"),\n                options=json.loads(project_options),\n            )\n        except Exception as exception:\n            logging.error(\"Project Generate Error: %s\", str(exception))\n            raise exception\n\n    generated_project.build()\n    generated_project.flash()\n    transport = generated_project.transport()\n\n    rpc_session = Session(transport_context_manager=transport)\n    # RPC exit is called by cleanup function.\n    rpc_session.__enter__()\n    return rpc_session._rpc._sess\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Allows the tools specified below to be imported directly from tvm.micro.testing\"\"\"\nfrom .evaluation import tune_model, create_aot_session, predict_labels_aot\nfrom .utils import get_supported_boards, get_target\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/testing/aot_test_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThis file provides utilities for running AOT tests, especially for Corstone.\n\n\"\"\"\n\nimport logging\nimport itertools\nimport shutil\n\nimport pytest\n\nimport tvm\nfrom tvm.testing.aot import AOTTestRunner\n\npytest.importorskip(\"tvm.micro\")\n\n_LOG = logging.getLogger(__name__)\n\n\nAOT_DEFAULT_RUNNER = AOTTestRunner()\n\n# AOT Test Runner using the Arm\u00ae Corstone\u2122-300 Reference Systems\n# see: https://developer.arm.com/ip-products/subsystem/corstone/corstone-300\nAOT_CORSTONE300_RUNNER = AOTTestRunner(\n    makefile=\"corstone300\",\n    prologue=\"\"\"\n    uart_init();\n    \"\"\",\n    includes=[\"uart.h\"],\n    pass_config={\n        \"relay.ext.cmsisnn.options\": {\n            \"mcpu\": \"cortex-m55\",\n        }\n    },\n)\n\nAOT_USMP_CORSTONE300_RUNNER = AOTTestRunner(\n    makefile=\"corstone300\",\n    prologue=\"\"\"\n    uart_init();\n    \"\"\",\n    includes=[\"uart.h\"],\n    pass_config={\n        \"relay.ext.cmsisnn.options\": {\n            \"mcpu\": \"cortex-m55\",\n        },\n        \"tir.usmp.enable\": True,\n    },\n)\n\n\ndef parametrize_aot_options(test):\n    \"\"\"Parametrize over valid option combinations\"\"\"\n\n    requires_arm_eabi = pytest.mark.skipif(\n        shutil.which(\"arm-none-eabi-gcc\") is None, reason=\"ARM embedded toolchain unavailable\"\n    )\n\n    interface_api = [\"packed\", \"c\"]\n    use_unpacked_api = [True, False]\n    test_runner = [AOT_DEFAULT_RUNNER, AOT_CORSTONE300_RUNNER]\n\n    all_combinations = itertools.product(interface_api, use_unpacked_api, test_runner)\n\n    # Filter out packed operators with c interface\n    valid_combinations = filter(\n        lambda parameters: not (parameters[0] == \"c\" and not parameters[1]),\n        all_combinations,\n    )\n\n    # Only use reference system for C interface and unpacked API calls\n    valid_combinations = filter(\n        lambda parameters: not (\n            parameters[2] == AOT_CORSTONE300_RUNNER\n            and (parameters[0] == \"packed\" or not parameters[1])\n        ),\n        valid_combinations,\n    )\n\n    # Skip reference system tests if running in i386 container\n    marked_combinations = map(\n        lambda parameters: pytest.param(*parameters, marks=[requires_arm_eabi])\n        if parameters[2] == AOT_CORSTONE300_RUNNER\n        else parameters,\n        valid_combinations,\n    )\n\n    func = pytest.mark.parametrize(\n        [\"interface_api\", \"use_unpacked_api\", \"test_runner\"],\n        marked_combinations,\n    )(test)\n\n    return tvm.testing.skip_if_32bit(reason=\"Reference system unavailable in i386 container\")(func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/testing/evaluation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nProvides high-level functions for instantiating and timing AOT models. Used\nby autotuning tests in tests/micro, and may be used for more performance\ntests in the future.\n\n\"\"\"\n\nimport logging\nfrom io import StringIO\nfrom pathlib import Path\nfrom contextlib import ExitStack\nimport tempfile\nimport shutil\n\nimport tvm\nfrom tvm.relay.op.contrib import cmsisnn\n\n\ndef tune_model(\n    platform,\n    board,\n    target,\n    mod,\n    params,\n    num_trials,\n    tuner_cls=tvm.autotvm.tuner.GATuner,\n    project_options=None,\n):\n    \"\"\"Autotunes a model with microTVM and returns a StringIO with the tuning logs\"\"\"\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        tasks = tvm.autotvm.task.extract_from_program(mod[\"main\"], {}, target)\n    assert len(tasks) > 0\n    assert isinstance(params, dict)\n\n    project_options = {\n        \"board\": board,\n        \"project_type\": \"host_driven\",\n        **(project_options or {}),\n    }\n\n    module_loader = tvm.micro.AutoTvmModuleLoader(\n        template_project_dir=tvm.micro.get_microtvm_template_projects(platform),\n        project_options=project_options,\n    )\n\n    builder = tvm.autotvm.LocalBuilder(\n        n_parallel=1,\n        build_kwargs={\"build_option\": {\"tir.disable_vectorize\": True}},\n        do_fork=False,\n        build_func=tvm.micro.autotvm_build_func,\n        runtime=tvm.relay.backend.Runtime(\"crt\", {\"system-lib\": True}),\n    )\n    runner = tvm.autotvm.LocalRunner(number=1, repeat=1, timeout=100, module_loader=module_loader)\n    measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner)\n\n    results = StringIO()\n    for task in tasks:\n        tuner = tuner_cls(task)\n\n        tuner.tune(\n            n_trial=num_trials,\n            measure_option=measure_option,\n            callbacks=[\n                tvm.autotvm.callback.log_to_file(results),\n                tvm.autotvm.callback.progress_bar(num_trials, si_prefix=\"M\"),\n            ],\n            si_prefix=\"M\",\n        )\n        # Note that we might not find a working schedule at all, in which case\n        # tuner.best_flops would equal zero. This is not good, but checking for\n        # this case will happen elsewhere.\n\n    return results\n\n\ndef create_aot_session(\n    platform,\n    board,\n    target,\n    mod,\n    params,\n    build_dir=Path(tempfile.mkdtemp()),\n    tune_logs=None,\n    timeout_override=None,\n    use_cmsis_nn=False,\n    project_options=None,\n    use_existing=False,\n):\n    \"\"\"AOT-compiles and uploads a model to a microcontroller, and returns the RPC session\"\"\"\n\n    executor = tvm.relay.backend.Executor(\"aot\")\n    crt_runtime = tvm.relay.backend.Runtime(\"crt\", {\"system-lib\": True})\n\n    with ExitStack() as stack:\n        config = {\"tir.disable_vectorize\": True}\n        if use_cmsis_nn:\n            config[\"relay.ext.cmsisnn.options\"] = {\"mcpu\": target.mcpu}\n        stack.enter_context(tvm.transform.PassContext(opt_level=3, config=config))\n        if use_cmsis_nn:\n            mod = cmsisnn.partition_for_cmsisnn(mod, params, mcpu=target.mcpu)\n        if tune_logs is not None:\n            stack.enter_context(tvm.autotvm.apply_history_best(tune_logs))\n\n        lowered = tvm.relay.build(\n            mod,\n            target=target,\n            params=params,\n            runtime=crt_runtime,\n            executor=executor,\n        )\n    parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params()))\n    print(f\"Model parameter size: {parameter_size}\")\n\n    project_options = {\n        \"board\": board,\n        \"project_type\": \"host_driven\",\n        # {} shouldn't be the default value for project options ({}\n        # is mutable), so we use this workaround\n        **(project_options or {}),\n    }\n\n    if use_existing:\n        shutil.rmtree(build_dir / \"project\" / \"build\")\n        project = tvm.micro.GeneratedProject.from_directory(\n            build_dir / \"project\",\n            options=project_options,\n        )\n\n    else:\n        project = tvm.micro.generate_project(\n            str(tvm.micro.get_microtvm_template_projects(platform)),\n            lowered,\n            build_dir / \"project\",\n            project_options,\n        )\n\n    project.build()\n    project.flash()\n    return tvm.micro.Session(project.transport(), timeout_override=timeout_override)\n\n\ndef predict_labels_aot(session, aot_executor, input_data, runs_per_sample=1):\n    \"\"\"Predicts labels for each sample in input_data using host-driven AOT.\n    Returns an iterator of (label, runtime) tuples. This function can only\n    be used with models for which the output is the confidence for each class.\"\"\"\n\n    assert aot_executor.get_num_inputs() == 1\n    assert aot_executor.get_num_outputs() == 1\n    assert runs_per_sample > 0\n\n    for counter, sample in enumerate(input_data):\n        logging.info(\"Evaluating sample %d\", counter)\n        aot_executor.get_input(0).copyfrom(sample)\n        result = aot_executor.module.time_evaluator(\"run\", session.device, number=runs_per_sample)()\n        predicted_label = aot_executor.get_output(0).numpy().argmax()\n        runtime = result.mean\n        yield predicted_label, runtime\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/testing/pytest_plugin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,redefined-outer-name\n\"\"\" microTVM testing fixtures used to deduce testing argument\n    values from testing parameters \"\"\"\n\nimport pathlib\nimport os\nimport datetime\nimport pytest\n\nfrom tvm.contrib.utils import tempdir\n\nfrom .utils import get_supported_platforms, get_supported_boards\n\n\ndef pytest_addoption(parser):\n    \"\"\"Adds more pytest arguments\"\"\"\n    parser.addoption(\n        \"--platform\",\n        choices=get_supported_platforms(),\n        help=(\"microTVM platform for tests.\"),\n    )\n    parser.addoption(\n        \"--board\",\n        choices=list(get_supported_boards(\"zephyr\").keys())\n        + list(get_supported_boards(\"arduino\").keys()),\n        help=(\n            \"microTVM boards for tests. Board refers to instances\"\n            \"of microcontrollers/emulators defined in a platform.\"\n        ),\n    )\n    parser.addoption(\n        \"--test-build-only\",\n        action=\"store_true\",\n        default=False,\n        help=\"Only run tests that don't require physical hardware.\",\n    )\n    parser.addoption(\n        \"--microtvm-debug\",\n        action=\"store_true\",\n        default=False,\n        help=(\n            \"If set true, it will keep the project directory for debugging.\"\n            \"Also, it will enable debug level logging in project generation.\"\n        ),\n    )\n\n\ndef pytest_generate_tests(metafunc):\n    \"\"\"Hooks into pytest to add platform and board fixtures to tests that\n    require them. To make sure that \"platform\" and \"board\" are treated as\n    parameters for the appropriate tests (and included in the test names),\n    we add them as function level parametrizations. This prevents data\n    from being overwritten in Junit XML files if multiple platforms\n    or boards are tested.\"\"\"\n\n    for argument in [\"platform\", \"board\"]:\n        if argument in metafunc.fixturenames:\n            value = metafunc.config.getoption(f\"--{argument}\", default=None)\n\n            if not value:\n                raise ValueError(\n                    f\"Test {metafunc.function.__name__} in module {metafunc.module.__name__} \"\n                    f\"requires a --{argument} argument, but none was given.\"\n                )\n\n            metafunc.parametrize(argument, [metafunc.config.getoption(f\"--{argument}\")])\n\n\n@pytest.fixture(scope=\"session\")\ndef microtvm_debug(request):\n    return request.config.getoption(\"--microtvm-debug\")\n\n\ndef pytest_collection_modifyitems(config, items):\n    if config.getoption(\"--test-build-only\"):\n        skip_hardware_tests = pytest.mark.skip(reason=\"--test-build-only was passed\")\n        for item in items:\n            if \"requires_hardware\" in item.keywords:\n                item.add_marker(skip_hardware_tests)\n\n\n@pytest.fixture\ndef workspace_dir(request, board, microtvm_debug):\n    \"\"\"Creates workspace directory for each test.\"\"\"\n    parent_dir = pathlib.Path(os.path.dirname(request.module.__file__))\n    board_workspace = (\n        parent_dir / f\"workspace_{board}\" / datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\")\n    )\n    board_workspace_base = str(board_workspace)\n    number = 1\n    while board_workspace.exists():\n        board_workspace = pathlib.Path(board_workspace_base + f\"-{number}\")\n        number += 1\n\n    if not os.path.exists(board_workspace.parent):\n        os.makedirs(board_workspace.parent)\n\n    keep_for_debug = microtvm_debug if microtvm_debug else None\n    test_temp_dir = tempdir(custom_path=board_workspace, keep_for_debug=keep_for_debug)\n    return test_temp_dir\n\n\n@pytest.fixture(autouse=True)\ndef skip_by_board(request, board):\n    \"\"\"Skip test if board is in the list.\"\"\"\n    if request.node.get_closest_marker(\"skip_boards\"):\n        if board in request.node.get_closest_marker(\"skip_boards\").args[0]:\n            pytest.skip(\"skipped on this board: {}\".format(board))\n\n\ndef pytest_configure(config):\n    config.addinivalue_line(\n        \"markers\",\n        \"skip_boards(board): skip test for the given board\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/testing/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines the test methods used with microTVM.\"\"\"\n\nfrom functools import lru_cache\nimport json\nimport logging\nfrom pathlib import Path\nimport tarfile\nimport time\nfrom typing import Union\n\nimport tvm\nfrom tvm import relay\nfrom tvm.micro.project_api.server import IoTimeoutError\n\n# Timeout in seconds for AOT transport.\nTIMEOUT_SEC = 10\n\n\n@lru_cache(maxsize=None)\ndef get_supported_platforms():\n    return [\"arduino\", \"zephyr\"]\n\n\n@lru_cache(maxsize=None)\ndef get_supported_boards(platform: str):\n    template = Path(tvm.micro.get_microtvm_template_projects(platform))\n    with open(template / \"boards.json\") as f:\n        return json.load(f)\n\n\ndef get_target(platform: str, board: str) -> tvm.target.Target:\n    \"\"\"Intentionally simple function for making Targets for microcontrollers.\n    If you need more complex arguments, one should call target.micro directly. Note\n    that almost all, but not all, supported microcontrollers are Arm-based.\"\"\"\n    model = get_supported_boards(platform)[board][\"model\"]\n    return tvm.target.target.micro(model, options=[\"-device=arm_cpu\"])\n\n\ndef check_tune_log(log_path: Union[Path, str]):\n    \"\"\"Read the tuning log and check each result.\"\"\"\n    with open(log_path, \"r\") as f:\n        lines = f.readlines()\n\n    for line in lines:\n        if len(line) > 0:\n            tune_result = json.loads(line)\n            assert tune_result[\"result\"][0][0] < 1000000000.0\n\n\ndef aot_transport_init_wait(transport):\n    \"\"\"Send init message to microTVM device until it receives wakeup sequence.\"\"\"\n    while True:\n        try:\n            aot_transport_find_message(transport, \"wakeup\", timeout_sec=TIMEOUT_SEC)\n            break\n        except IoTimeoutError:\n            transport.write(b\"init%\", timeout_sec=TIMEOUT_SEC)\n\n\ndef aot_transport_find_message(transport, expression: str, timeout_sec: int) -> str:\n    \"\"\"Read transport message until it finds the expression.\"\"\"\n    timeout = timeout_sec\n    start_time = time.monotonic()\n    while True:\n        data = _read_line(transport, timeout)\n        logging.debug(\"new line: %s\", data)\n        if expression in data:\n            return data\n        timeout = max(0, timeout_sec - (time.monotonic() - start_time))\n\n\ndef _read_line(transport, timeout_sec: int) -> str:\n    data = bytearray()\n    while True:\n        new_data = transport.read(1, timeout_sec=timeout_sec)\n        logging.debug(\"read data: %s\", new_data)\n        for item in new_data:\n            data.append(item)\n            if str(chr(item)) == \"\\n\":\n                return data.decode(encoding=\"utf-8\")\n\n\ndef mlf_extract_workspace_size_bytes(mlf_tar_path: Union[Path, str]) -> int:\n    \"\"\"Extract an MLF archive file and read workspace size from metadata file.\"\"\"\n\n    workspace_size = 0\n    with tarfile.open(mlf_tar_path, \"r:*\") as tar_file:\n        tar_members = [ti.name for ti in tar_file.getmembers()]\n        assert \"./metadata.json\" in tar_members\n        with tar_file.extractfile(\"./metadata.json\") as f:\n            metadata = json.load(f)\n            for mod_name in metadata[\"modules\"].keys():\n                workspace_size += metadata[\"modules\"][mod_name][\"memory\"][\"functions\"][\"main\"][0][\n                    \"workspace_size_bytes\"\n                ]\n            return workspace_size\n\n\ndef get_conv2d_relay_module():\n    \"\"\"Generate a conv2d Relay module for testing.\"\"\"\n    data_shape = (1, 3, 64, 64)\n    weight_shape = (8, 3, 5, 5)\n    data = relay.var(\"data\", relay.TensorType(data_shape, \"int8\"))\n    weight = relay.var(\"weight\", relay.TensorType(weight_shape, \"int8\"))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        channels=8,\n        kernel_size=(5, 5),\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        out_dtype=\"int32\",\n    )\n    f = relay.Function([data, weight], y)\n    mod = tvm.IRModule.from_expr(f)\n    mod = relay.transform.InferType()(mod)\n    return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/micro/transport.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines abstractions and implementations of the RPC transport used with micro TVM.\"\"\"\n\nimport abc\nimport logging\nimport string\nimport typing\n\nfrom .project_api.server import IoTimeoutError, TransportTimeouts\nfrom .project_api.server import TransportClosedError\n\n\n_ = TransportClosedError  # work around pylint unused-import error\n\n\n_LOG = logging.getLogger(__name__)\n\n\ndef debug_transport_timeouts(session_start_retry_timeout_sec=0):\n    return TransportTimeouts(\n        session_start_retry_timeout_sec=session_start_retry_timeout_sec,\n        session_start_timeout_sec=0,\n        session_established_timeout_sec=0,\n    )\n\n\nclass Transport(metaclass=abc.ABCMeta):\n    \"\"\"The abstract Transport class used for micro TVM.\"\"\"\n\n    def __enter__(self):\n        self.open()\n        return self\n\n    def __exit__(self, exc_type, exc_value, exc_traceback):\n        self.close()\n\n    @abc.abstractmethod\n    def timeouts(self):\n        \"\"\"Return TransportTimeouts suitable for use with this transport.\n\n        See the TransportTimeouts documentation in python/tvm/micro/session.py.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def open(self):\n        \"\"\"Open any resources needed to send and receive RPC protocol data for a single session.\"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def close(self):\n        \"\"\"Release resources associated with this transport.\"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def read(self, n, timeout_sec):\n        \"\"\"Read up to n bytes from the transport.\n\n        Parameters\n        ----------\n        n : int\n            Maximum number of bytes to read from the transport.\n        timeout_sec : Union[float, None]\n            Number of seconds to wait for all `n` bytes to be received before timing out. The\n            transport can wait additional time to account for transport latency or bandwidth\n            limitations based on the selected configuration and number of bytes being received. If\n            timeout_sec is 0, read should attempt to service the request in a non-blocking fashion.\n            If timeout_sec is None, read should block until at least 1 byte of data can be returned.\n\n        Returns\n        -------\n        bytes :\n            Data read from the channel. Less than `n` bytes may be returned, but 0 bytes should\n            never be returned. If returning less than `n` bytes, the full timeout_sec, plus any\n            internally-added timeout, should be waited. If a timeout or transport error occurs,\n            an exception should be raised rather than simply returning empty bytes.\n\n\n        Raises\n        ------\n        TransportClosedError :\n            When the transport layer determines that the transport can no longer send or receive\n            data due to an underlying I/O problem (i.e. file descriptor closed, cable removed, etc).\n\n        IoTimeoutError :\n            When `timeout_sec` elapses without receiving any data.\n        \"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write(self, data, timeout_sec):\n        \"\"\"Write data to the transport channel.\n\n        Parameters\n        ----------\n        data : bytes\n            The data to write over the channel.\n        timeout_sec : Union[float, None]\n            Number of seconds to wait for at least one byte to be written before timing out. The\n            transport can wait additional time to account for transport latency or bandwidth\n            limitations based on the selected configuration and number of bytes being received. If\n            timeout_sec is 0, write should attempt to service the request in a non-blocking fashion.\n            If timeout_sec is None, write should block until at least 1 byte of data can be\n            returned.\n\n        Returns\n        -------\n        int :\n            The number of bytes written to the underlying channel. This can be less than the length\n            of `data`, but cannot be 0 (raise an exception instead).\n\n        Raises\n        ------\n        TransportClosedError :\n            When the transport layer determines that the transport can no longer send or receive\n            data due to an underlying I/O problem (i.e. file descriptor closed, cable removed, etc).\n\n        IoTimeoutError :\n            When `timeout_sec` elapses without receiving any data.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass TransportLogger(Transport):\n    \"\"\"Wraps a Transport implementation and logs traffic to the Python logging infrastructure.\"\"\"\n\n    def __init__(self, name, child, logger=None, level=logging.INFO):\n        self.name = name\n        self.child = child\n        self.logger = logger or _LOG\n        self.level = level\n\n    # Construct PRINTABLE to exclude whitespace from string.printable.\n    PRINTABLE = string.digits + string.ascii_letters + string.punctuation\n\n    @classmethod\n    def _to_hex(cls, data):\n        lines = []\n        if not data:\n            lines.append(\"\")\n            return lines\n\n        for i in range(0, (len(data) + 15) // 16):\n            chunk = data[i * 16 : (i + 1) * 16]\n            hex_chunk = \" \".join(f\"{c:02x}\" for c in chunk)\n            ascii_chunk = \"\".join((chr(c) if chr(c) in cls.PRINTABLE else \".\") for c in chunk)\n            lines.append(f\"{i * 16:04x}  {hex_chunk:47}  {ascii_chunk}\")\n\n        if len(lines) == 1:\n            lines[0] = lines[0][6:]\n\n        return lines\n\n    def timeouts(self):\n        return self.child.timeouts()\n\n    def open(self):\n        self.logger.log(self.level, \"%s: opening transport\", self.name)\n        self.child.open()\n\n    def close(self):\n        self.logger.log(self.level, \"%s: closing transport\", self.name)\n        return self.child.close()\n\n    def read(self, n, timeout_sec):\n        timeout_str = f\"{timeout_sec:5.2f}s\" if timeout_sec is not None else \" None \"\n        try:\n            data = self.child.read(n, timeout_sec)\n        except IoTimeoutError:\n            self.logger.log(\n                self.level,\n                \"%s: read {%s} %4d B -> [IoTimeoutError %s]\",\n                self.name,\n                timeout_str,\n                n,\n                timeout_str,\n            )\n            raise\n        except Exception as err:\n            self.logger.log(\n                self.level,\n                \"%s: read {%s} %4d B -> [err: %s]\",\n                self.name,\n                timeout_str,\n                n,\n                err.__class__.__name__,\n                exc_info=1,\n            )\n            raise err\n\n        hex_lines = self._to_hex(data)\n        if len(hex_lines) > 1:\n            self.logger.log(\n                self.level,\n                \"%s: read {%s} %4d B -> [%3d B]:\\n%s\",\n                self.name,\n                timeout_str,\n                n,\n                len(data),\n                \"\\n\".join(hex_lines),\n            )\n        else:\n            self.logger.log(\n                self.level,\n                \"%s: read {%s} %4d B -> [%3d B]: %s\",\n                self.name,\n                timeout_str,\n                n,\n                len(data),\n                hex_lines[0],\n            )\n\n        return data\n\n    def write(self, data, timeout_sec):\n        timeout_str = f\"{timeout_sec:5.2f}s\" if timeout_sec is not None else \" None \"\n        try:\n            self.child.write(data, timeout_sec)\n        except IoTimeoutError:\n            self.logger.log(\n                self.level,\n                \"%s: write {%s}       <- [%3d B]: [IoTimeoutError %s]\",\n                self.name,\n                timeout_str,\n                len(data),\n                timeout_str,\n            )\n            raise\n        except Exception as err:\n            self.logger.log(\n                self.level,\n                \"%s: write {%s}       <- [%3d B]: [err: %s]\",\n                self.name,\n                timeout_str,\n                len(data),\n                err.__class__.__name__,\n                exc_info=1,\n            )\n            raise err\n\n        hex_lines = self._to_hex(data)\n        if len(hex_lines) > 1:\n            self.logger.log(\n                self.level,\n                \"%s: write {%s}        <- [%3d B]:\\n%s\",\n                self.name,\n                timeout_str,\n                len(data),\n                \"\\n\".join(hex_lines),\n            )\n        else:\n            self.logger.log(\n                self.level,\n                \"%s: write {%s}        <- [%3d B]: %s\",\n                self.name,\n                timeout_str,\n                len(data),\n                hex_lines[0],\n            )\n\n\nTransportContextManager = typing.ContextManager[Transport]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/api.py",
        "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass, field\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, ir\n\nfrom .extool import *\nfrom .types import *\nfrom . import runtime, topi\n\nVisitorT = typing.Callable[ [RelayExpr, ParametersT], None ]\nTransformerT = typing.Callable[\n        [RelayExpr, ParametersT], typing.Optional[RelayExpr]]\n\n@dataclass\nclass Trace:\n    name: str\n    \"\"\" Trace Name \"\"\"\n    expr: RelayExpr\n    params: ParametersT\n\n    input_vars: typing.List[Var] = field(init=False)\n    param_vars: typing.List[Var] = field(init=False)\n\n    def __post_init__(self):\n        self.input_vars = []\n        self.param_vars = []\n\n        for v in relay.analysis.free_vars(self.expr):\n            if v.name_hint in self.params:\n                self.param_vars.append(v)\n            else:\n                self.input_vars.append(v)\n\n    @property\n    def input_names(self) -> typing.List[str]:\n        return [i.name for i in self.input_vars]\n\n    def random_inputs(self) -> typing.Dict[str, np.ndarray]:\n        inputs = {}\n        for v in self.input_vars:\n            shape = v.type_annotation.concrete_shape\n            dtype = v.type_annotation.dtype\n            data = np.random.randn(*shape).astype(dtype)\n            inputs[v.name_hint] = data\n        return inputs\n\n    def calibrate(self,\n            data: typing.Optional[np.ndarray] = None,\n            data_dict: typing.Dict[str, np.ndarray] = {},\n        ) -> typing.Dict[str, np.ndarray]:\n        self.infer_type()\n\n        calibrate_outputs: typing.Dict[str, np.ndarray] = {\n                k: v.numpy() for k, v in params.items()}\n\n        # set input data\n        for v in self.input_vars:\n            shape = v.type_annotation.concrete_shape\n            dtype = v.type_annotation.dtype\n            val = data_dict.get(v.name_hint, data)\n            if val is None:\n                print(\"input: {} use random data\".format(\n                    v.name_hint))\n                val = np.random.randn(*shape).astype(dtype)\n            calibrate_outputs[v.name_hint] = val\n\n        def _calibrate(expr: RelayExpr, params: ParametersT):\n            data = [ calibrate_outputs[e] for e in args(expr) ]\n            out = topi.execute(expr, data)\n            shape = list(expr.checked_type.concrete_shape)\n            assert list(out.shape) == shape\n            assert str(out.dtype) == expr.checked_type.dtype\n            calibrate_outputs[expr] = out\n        self.visit(_calibrate)\n        return calibrate_outputs\n\n    def run(self,\n            data: typing.Optional[np.ndarray] = None,\n            data_dict: typing.Dict[str, np.ndarray] = {},\n            device: tvm.runtime.Device = tvm.runtime.cpu(0),\n    ) -> typing.List[np.ndarray]:\n        inputs = {k: v for k, v in self.params.items()}\n        for v in self.input_vars:\n            shape = v.type_annotation.concrete_shape\n            dtype = v.type_annotation.dtype\n            val = data_dict.get(v.name_hint, data)\n            assert val is not None\n            assert list(shape) == list(val.shape), (\n                    \"{}: {} vs. {}\").format(\n                            v.name_hint, shape, val.shape)\n            assert dtype == val.dtype\n            inputs[v.name_hint] = val\n        return runtime.infer(self.expr, inputs)\n\n    def eval(self, device) -> runtime.ValidateFunctionT:\n        return runtime.validator(\n                self.expr, self.params, self.name,\n                device=device)\n\n    def visit(self, callback: VisitorT):\n        def _visitor(expr: RelayExpr):\n            callback(expr, self.params)\n        visit(self.expr, _visitor)\n\n    def transform(self, callback: TransformerT) -> Trace:\n        def _tfm(expr: RelayExpr):\n            return callback(expr, self.params)\n        return Trace(callback.__name__,\n                transform(self.expr, _tfm), self.params)\n\n    def infer_type(self) -> Model:\n        return Trace(\"infer_type\",\n                infer_type(self.expr), self.params)\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/calibrate.py",
        "content": "from __future__ import annotations\n\nimport typing\nimport numpy as np\n\nimport tvm\n\nfrom dataclasses import dataclass, field, InitVar\n\nfrom .symbol import *\nfrom . import runtime\nfrom .transform import Transformer\nfrom .types import *\n\n@dataclass\nclass Calibrator(Transformer):\n    args: typing.List[Calibrator]\n\n    is_nd: bool = False\n    output: typing.List[np.ndarray] = field(default_factory=list)\n\n    def __call__(self,\n            data: tvm.nd.NDArray | None =None,\n            data_dict: ParametersT = {}):\n        if self.is_input():\n            out = data_dict.get(self.name, data)\n            if out is None:\n                # use random input data\n                out = np.random.randn(*self.shape)\n                out = out.astype(self.dtype)\n                out = tvm.nd.array(out)\n        elif self.is_param():\n            out = self.params[self.name]\n        elif self.is_op(TUPLE_GET_ITEM_NAME):\n            out = self.args[0].raw_output[self.attrs[\"index\"]]\n            assert isinstance(out, tvm.nd.NDArray), type(out)\n        else:\n            out = self.run({ a.name: a.raw_output \\\n                    for a in self.args })\n\n        if isinstance(out, tvm.nd.NDArray):\n            self.is_nd = True\n            self.output = [ out, ]\n            self._assert(out.dtype, self.dtype)\n            self._assert(out.shape, self.shape)\n        else:\n            self.is_nd = False\n            self.output = out\n            self._assert([o.dtype for o in out], self.dtype)\n            self._assert([o.shape for o in out], self.shape)\n\n        print(self.name, self.op_name, self.shape, self.dtype)\n\n    def run(self, args_data: typing.Dict[str, tvm.nd.NDArray]):\n        args = [ a.as_parameter() for a in self.args]\n        sym = self.clone(Symbol, args=args)\n        expr = symbol2expr(sym)\n        #  data = { a.name: a.raw_output for a in self.args }\n        return runtime.infer(expr, args_data)\n\n    @property\n    def raw_output(self):\n        return self.output[0] if self.is_nd else self.output\n\n    def _assert(self, val, expect):\n        if isinstance(val, (list, tuple)):\n            assert len(val) == len(expect), (\n                    \"{} vs. {}\").format(val, expect)\n            for v, e in zip(val, expect):\n                self._assert(v, e)\n            return\n        assert val == expect, \"{} vs. {}\".format(val, expect)\n\n    #  @property\n    #  def shape(self):\n    #      return self.output[0].shape if self.is_nd \\\n    #              else [ o.shape for o in self.output ]\n\n    #  @property\n    #  def dtype(self):\n    #      return self.output[0].shape if self.is_nd \\\n    #              else [ o.shape for o in self.output ]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/data.py",
        "content": "\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, ir, runtime\n\nfrom .extool import *\nfrom .types import ParametersT\n\ndef random_inputs(expr: ir.expr.RelayExpr,\n        params: ParametersT = {}) -> ParametersT:\n    input_data = {k: v for k, v in params.items()}\n    for v in relay.analysis.free_vars(expr):\n        if v.name_hint in params:\n            continue\n\n        print(v.name_hint, v.type_annotation)\n\n        ty = v.type_annotation\n        # ty = v.checked_type\n        np_data = np.random.randn(\n                *ty.concrete_shape).astype(ty.dtype)\n        input_data[v.name_hint] = tvm.nd.array(np_data)\n    return input_data\n\ndef set_inputs(expr: ir.expr.RelayExpr,\n        params: ParametersT = {}) -> ParametersT:\n    free_vars = relay.analysis.free_vars(expr)\n    input_data = {k: v for k, v in params.items()}\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/dataset-old.py",
        "content": "\"\"\" Dataset Class Definition.\n\n    Customized datasets definition and customized interface\n    definition including ``metrics``, ``validate``,\n    ``_load_data`` and ``iter_func``.\n\n    Only **crucial parts** of the custommized interface\n    implementation are elaborated.\n\"\"\"\n\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet import nd\nfrom gluoncv import data as gdata\nfrom gluoncv.data.batchify import Tuple, Stack, Pad\nfrom gluoncv.data.transforms.presets.yolo import YOLO3DefaultValTransform\nfrom gluoncv.utils.metrics.voc_detection import VOC07MApMetric\nfrom gluoncv.utils.metrics.coco_detection import COCODetectionMetric\nfrom gluoncv.data.transforms.presets.ssd import SSDDefaultValTransform\nimport numpy as np\nimport requests\nimport tarfile\n\nimport os\nfrom os import path\nimport math\nimport pickle\nimport logging\n\nfrom . import conf\n\n__all__ = [\"DS_REG\", \"Dataset\"]\n\n# dataset_dir = path.expanduser(\"~/.mxnet/datasets\")\nsrc = \"http://0.0.0.0:8827\"\n\ndef extract_file(tar_path, target_path):\n    tar = tarfile.open(tar_path, \"r\")\n    if path.exists(path.join(target_path,\n                tar.firstmember.name)):\n        return\n    tar.extractall(target_path)\n    tar.close()\n\ndef download_files(category, files, base_url=src, root=conf.MRT_DATASET_ROOT):\n    logger = logging.getLogger(\"dataset\")\n    root_dir = path.join(root, category)\n    os.makedirs(root_dir, exist_ok=True)\n\n    for df in files:\n        url = path.join(base_url, 'datasets', category, df)\n        fpath = path.join(root_dir, df)\n        if path.exists(fpath):\n            continue\n        fdir = path.dirname(fpath)\n        if not path.exists(fdir):\n            os.makedirs(fdir)\n\n        logger.info(\"Downloading dateset %s into %s from url[%s]\",\n                df, root_dir, url)\n        r = requests.get(url)\n        if r.status_code != 200:\n            logger.error(\"Url response invalid status code: %s\",\n                    r.status_code)\n            exit()\n        r.raise_for_status()\n        with open(fpath, \"wb\") as fout:\n            fout.write(r.content)\n    return root_dir\n\nDS_REG = {\n    # \"voc\": VOCDataset,\n    # \"imagenet\": ImageNetDataset,\n    # \"cifar10\": Cifar10Dataset,\n    # \"quickdraw\": QuickDrawDataset,\n    # \"mnist\": MnistDataset,\n    # \"trec\": TrecDataset,\n    # \"coco\": COCODataset,\n}\n\ndef register_dataset(name):\n    def _wrapper(dataset):\n        dataset.name = name\n        if name in DS_REG:\n            raise NameError(\"Dataset \" + name + \" has been registered\")\n        DS_REG[name] = dataset;\n        return dataset \n    return _wrapper\n\nclass Dataset:\n    \"\"\" Base dataset class, with pre-defined interface.\n\n        The dataset directory is located at the ``root`` directory containing\n        the dataset `name` directory. And the custom dataset should pass\n        the parameter location of root, or implement the derived class\n        of your data iterator, metrics and validate function.\n\n        Notice:\n            Our default imagenet dataset is organized as an ``record``\n            binary format, which can amplify the throughput for image read.\n            Custom Image dataset of third party could be preprocessed by the\n            `im2rec` procedure to transform the image into the record format.\n\n            The transformation script is located at ``docs/mrt/im2rec.py``.\n            And more details refer to the script helper documentation\n            please(print usage with command ``-h``).\n\n\n        Parameters\n        ==========\n        input_shape: Tuple or List\n            The input shape requested from user, and some dataset would\n            check the format validity. Generally, specific dataset will\n            do some checks for input shape, such as the channel number for\n            image.\n            Example: imagenet's input shape is like to this, (N, C, H, W),\n            where the C must be equal to 3, H equals to W and N indicates\n            the batch size user want. Different H(W) requests the dataset\n            loader to resize image.\n\n        root: os.path.Path or path string\n            The location where dataset is stored, defined with variable\n            ``MRT_DATASET_ROOT`` in conf.py or custom directory.\n\n\n        **Custom Dataset Implementation (derived this class):**\n\n            1. Register dataset name into DS_REG that can be accessed\n            at the ``dataset`` package API. And releated function is\n            the ``register_dataset`` function.\n\n            2. Override the abstract method defined in base dataset class:\n\n                _load_data(self) [Required]:\n                    Load data from disk that stored into the data variable.\n                    And save the required `data_loader` to the member: `data`.\n\n                iter_func(self) [Optional]:\n                    Return the tuple (data, label) for each invocation according\n                    to the member `data` loaded from the function `_load_data`.\n\n                    Also, this function is optional since we have implemented\n                    a naive version if the member `data` is python generator-\n                    compatible type, supporting the `iter(data)` function. Or\n                    you will override the function you need.\n\n                metrics(self) [Required]:\n                    Return the metrics object for the dataset, such as\n                    some auxiliary variable.\n\n                validate(self, metrics, predict, label) [Required]:\n                    Calculates the accuracy for model inference of string.\n                    Return formated string type\n\n        Examples\n        ========\n        >>> from mxnet import ndarray as nd\n        >>> @register_dataset(\"my_dataset\")\n        >>> class MyDataset(Dataset):\n        ...     def _load_data(self):\n        ...         B = self.ishape[0]\n        ...         def _data_loader():\n        ...             for i in range(1000):\n        ...                 yield nd.array([i + c for c in range(B)])\n        ...         self.data = _data_loader()\n        ...\n        ...     # use the default `iter_func` defined in base class\n        ...\n        ...     def metrics(self):\n        ...         return {\"count\": 0, \"total\": 0}\n        ...     def validate(self, metrics, predict, label):\n        ...         for idx in range(predict.shape[0]):\n        ...             res_label = predict[idx].asnumpy().argmax()\n        ...             data_label = label[idx].asnumpy()\n        ...             if res_label == data_label:\n        ...                 metrics[\"acc\"] += 1\n        ...             metrics[\"total\"] += 1\n        ...         acc = 1. * metrics[\"acc\"] / metrics[\"total\"]\n        ...         return \"{:6.2%}\".format(acc)\n        >>>\n        >>> # usage\n        >>> md_cls = DS_REG[\"my_dataset\"]\n        >>> ds = md_cls([8]) # batch size is 8\n        >>> data_iter_func = ds.iter_func()\n        >>> data_iter_func() # get the batch data\n        NDArray<[0, 1, 2, 3, 4, 5, 6, 7] @ctx(cpu)>\n    \"\"\"\n    name = None\n    \"\"\" Registered Dataset Name \"\"\"\n\n    def __init__(self, input_shape, root=conf.MRT_DATASET_ROOT):\n        self.ishape = input_shape\n\n        if self.name is None:\n            raise RuntimeError(\"Dataset name not set\")\n\n        # Dataset not to download the file, it's user's responsibility\n        self.root_dir = path.join(root, self.name)\n        # self.root_dir = download_files(\n        #     self.name, self.download_deps, base_url, root) \\\n        #     if dataset_dir is None else dataset_dir\n        # for fname in self.download_deps:\n        #     if fname.endswith(\".tar\") or fname.endswith(\".tar.gz\"):\n        #         extract_file(\n        #               path.join(self.root_dir, fname), self.root_dir)\n\n        self.data = None\n        self._load_data()\n\n    def metrics(self):\n        raise NotImplementedError(\n                \"Derived \" + self.name + \" dataset not override the\" +\n                \" base `metric` function defined in Dataset\")\n\n    def validate(self, metrics, predict, label):\n        raise NotImplementedError(\n                \"Derived \" + self.name + \" dataset not override the\" +\n                \" base `validate` function defined in Dataset\")\n\n    def _load_data(self):\n        \"\"\" Load data from disk.\n\n            Save the data loader into member `data` like:\n\n            .. code-block:: python\n\n                self.data = data_loader\n\n            And validate the input shape if necessary:\n\n            .. code-block:: python\n\n                N, C, H, W = self.ishape\n                assert C == 3 and H == W\n        \"\"\"\n        raise NotImplementedError(\n                \"Derived \" + self.name + \" dataset not override the\" +\n                \" base `_load_data` function defined in Dataset\")\n\n    def iter_func(self):\n        \"\"\" Returns (data, label) iterator function.\n\n            Get the iterator of `self.data` and iterate each batch sample\n            with `next` function manually. Call like this:\n\n            .. code-block:: python\n\n                data_iter_func = dataset.iter_func()\n                data, label = data_iter_func()\n        \"\"\"\n        data_iter = iter(self.data)\n        def _wrapper():\n            return next(data_iter)\n        return _wrapper\n\n\n@register_dataset(\"coco\")\nclass COCODataset(Dataset):\n    # download_deps = ['val2017.zip']\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            COCO dataset only support layout of NCHW and the number of channels must be 3, i.e. (batch_size, 3, input_size, input_size).\n\n            The validation dataset will be created by *MS COCO Detection Dataset* and use SSDDefaultValTransform as data preprocess function.\n        \"\"\"\n        assert len(self.ishape) == 4\n        N, C, H, W = self.ishape\n        assert C == 3\n        self.val_dataset = gdata.COCODetection(\n            root=self.root_dir, splits='instances_val2017', skip_empty=False)\n        val_batchify_fn = Tuple(Stack(), Pad(pad_val=-1))\n        self.data = gluon.data.DataLoader(\n            self.val_dataset.transform(SSDDefaultValTransform(W, H)),\n            batch_size=N, shuffle=False, batchify_fn=val_batchify_fn,\n            last_batch='rollover', num_workers=30)\n\n    def metrics(self):\n        \"\"\" Customized metrics method introduction.\n\n            COCODetectionMetric is used which is the detection metric for COCO bbox task.\n        \"\"\"\n        _, _, H, W = self.ishape\n        metric = COCODetectionMetric(\n            self.val_dataset, '_eval', cleanup=True, data_shape=(H, W))\n        metric.reset()\n        return metric\n\n    def validate(self, metrics, predict, label):\n        \"\"\" Customized validate method introduction.\n\n            The image height must be equal to the image width.\n\n            The model output is [id, score, bounding_box], \n            where bounding_box is of layout (x1, y1, x2, y2).\n\n            The data label is implemented as follows:\n\n            .. code-block:: python\n\n                map_name, mean_ap = metrics.get()\n                acc = {k: v for k,v in zip(map_name, mean_ap)}\n                acc = float(acc['~~~~ MeanAP @ IoU=[0.50, 0.95] ~~~~\\\\n']) / 100\n        \"\"\"\n        det_ids, det_scores, det_bboxes = [], [], []\n        gt_ids, gt_bboxes, gt_difficults = [], [], []\n\n        _, _, H, W = self.ishape\n        assert H == W\n        ids, scores, bboxes = predict\n        det_ids.append(ids)\n        det_scores.append(scores)\n        # clip to image size\n        det_bboxes.append(bboxes.clip(0, H))\n        gt_ids.append(label.slice_axis(axis=-1, begin=4, end=5))\n        gt_difficults.append(\n            label.slice_axis(axis=-1, begin=5, end=6) \\\n            if label.shape[-1] > 5 else None)\n        gt_bboxes.append(label.slice_axis(axis=-1, begin=0, end=4))\n\n        metrics.update(det_bboxes, det_ids, det_scores,\n                            gt_bboxes, gt_ids, gt_difficults)\n        names, values = metrics.get()\n        acc = {k:v for k,v in zip(names, values)}\n        acc = float(acc['~~~~ MeanAP @ IoU=[0.50,0.95] ~~~~\\n']) / 100\n        return \"{:6.2%}\".format(acc)\n\n\n@register_dataset(\"voc\")\nclass VOCDataset(Dataset):\n    # name = \"voc\"\n    # download_deps = [\"VOCtest_06-Nov-2007.tar\"]\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            VOC dataset only support layout of NCHW and the number of channels must be 3, i.e. (batch_size, 3, input_size, input_size).\n\n            The validation dataset will be created by Pascal *VOC detection Dataset* and use YOLO3DefaultValTransform as data preprocess function.\n        \"\"\"\n        assert len(self.ishape) == 4\n        N, C, H, W = self.ishape\n        assert C == 3\n        val_dataset = gdata.VOCDetection(\n            root=path.join(self.root_dir, 'VOCdevkit'),\n            splits=[('2007', 'test')])\n        val_batchify_fn = Tuple(Stack(), Pad(pad_val=-1))\n        self.data = gluon.data.DataLoader(\n            val_dataset.transform(YOLO3DefaultValTransform(W, H)),\n            N, False, batchify_fn=val_batchify_fn,\n            last_batch='discard', num_workers=30)\n\n    def metrics(self):\n        \"\"\" Customized metric method introduction.\n\n            VOC07MApMetric is used which is the Mean average precision metric for PASCAL V0C 07 dataset.\n        \"\"\"\n        metric = VOC07MApMetric(\n            iou_thresh=0.5, class_names=gdata.VOCDetection.CLASSES)\n        metric.reset()\n        return metric\n\n    def validate(self, metrics, predict, label):\n        \"\"\" Customized validate method introduction.\n\n            The image height must be equal to the image width.\n\n            The model output is [id, score, bounding_box], \n            where bounding_box is of layout (x1, y1, x2, y2).\n\n            The data label is implemented as follows:\n\n            .. code-block:: python\n\n                map_name, mean_ap = metrics.get()\n                acc = {k: v for k,v in zip(map_name, mean_ap)}['mAP']\n        \"\"\"\n        det_ids, det_scores, det_bboxes = [], [], []\n        gt_ids, gt_bboxes, gt_difficults = [], [], []\n\n        _, _, H, W = self.ishape\n        assert H == W\n        ids, scores, bboxes = predict\n        det_ids.append(ids)\n        det_scores.append(scores)\n        # clip to image size\n        det_bboxes.append(bboxes.clip(0, H))\n        gt_ids.append(label.slice_axis(axis=-1, begin=4, end=5))\n        gt_difficults.append(\n            label.slice_axis(axis=-1, begin=5, end=6) \\\n            if label.shape[-1] > 5 else None)\n        gt_bboxes.append(label.slice_axis(axis=-1, begin=0, end=4))\n\n        metrics.update(det_bboxes, det_ids, det_scores,\n                            gt_bboxes, gt_ids, gt_difficults)\n        map_name, mean_ap = metrics.get()\n        acc = {k:v for k,v in zip(map_name, mean_ap)}['mAP']\n        return \"{:6.2%}\".format(acc)\n\n\nclass VisionDataset(Dataset):\n    pass\n    #  def metrics(self):\n    #      \"\"\" Customized metric method introduction.\n\n    #          Computes accuracy classification score and top k predictions accuracy.\n    #      \"\"\"\n    #      return [mx.metric.Accuracy(),\n    #              mx.metric.TopKAccuracy(5)]\n\n    #  def validate(self, metrics, predict, label):\n    #      \"\"\" Customized metric method introduction.\n\n    #          The model output include score for 1000 classes.\n    #      \"\"\"\n    #      metrics[0].update(label, predict)\n    #      metrics[1].update(label, predict)\n    #      _, top1 = metrics[0].get()\n    #      _, top5 = metrics[1].get()\n    #      return \"top1={:6.2%} top5={:6.2%}\".format(top1, top5)\n\n\n@register_dataset(\"imagenet\")\nclass ImageNetDataset(VisionDataset):\n    # name = \"imagenet\"\n    download_deps = [\"rec/val.rec\", \"rec/val.idx\"]\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            ImageNet dataset only support layout of NCHW and the number of channels must be 3, i.e. (batch_size, 3, input_size, input_size). The image height must be equal to the image width.\n\n            The data preprocess process includes:\n\n            .. math::\n                crop_ratio = 0.875\n\n            .. math::\n                resize = ceil(H / crop\\_ratio)\n\n            .. math::\n                mean_rgb = [123.68, 116.779, 103.939]\n\n            .. math::\n                std_rgb = [58.393, 57.12, 57.375]\n\n            Use ImageRecordIter to iterate on image record io files.\n        \"\"\"\n        assert len(self.ishape) == 4\n        N, C, H, W = self.ishape\n        assert C == 3\n        assert H == W\n\n        crop_ratio = 0.875\n        resize = int(math.ceil(H / crop_ratio))\n        mean_rgb = [123.68, 116.779, 103.939]\n        std_rgb = [58.393, 57.12, 57.375]\n        rec_val = path.join(self.root_dir, self.download_deps[0])\n        rec_val_idx = path.join(self.root_dir, self.download_deps[1])\n\n\n        self.data = mx.io.ImageRecordIter(\n            path_imgrec         = rec_val,\n            path_imgidx         = rec_val_idx,\n            preprocess_threads  = 24,\n            shuffle             = False,\n            batch_size          = N,\n\n            resize              = resize,\n            data_shape          = (3, H, W),\n            mean_r              = mean_rgb[0],\n            mean_g              = mean_rgb[1],\n            mean_b              = mean_rgb[2],\n            std_r               = std_rgb[0],\n            std_g               = std_rgb[1],\n            std_b               = std_rgb[2],\n        )\n\n    def iter_func(self):\n        def _wrapper():\n            data = self.data.next()\n            return data.data[0], data.label[0]\n        return _wrapper\n\n\n@register_dataset(\"cifar10\")\nclass Cifar10Dataset(VisionDataset):\n    # name = \"cifar10\"\n    #  download_deps = [\"cifar-10-binary.tar.gz\"]\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            Cifar10Dataset only support layout of NCHW and the number of channels must be 3, i.e. (batch_size, 3, 32, 32). The image height and width must be equal to 32.\n\n            The data preprocess process includes:\n\n            .. math::\n                mean = [0.4914, 0.4822, 0.4465]\n\n            .. math::\n                std = [0.2023, 0.1994, 0.2010]\n        \"\"\"\n        N, C, H, W = self.ishape\n        assert C == 3 and H == W and H == 32\n        transform_test = gluon.data.vision.transforms.Compose([\n            gluon.data.vision.transforms.ToTensor(),\n            gluon.data.vision.transforms.Normalize([0.4914, 0.4822, 0.4465],\n                                                   [0.2023, 0.1994, 0.2010])])\n        self.data = gluon.data.DataLoader(\n            gluon.data.vision.CIFAR10(root=self.root_dir,\n                train=False).transform_first(transform_test),\n            batch_size=N, shuffle=False, num_workers=4)\n\n\n@register_dataset(\"quickdraw\")\nclass QuickDrawDataset(VisionDataset):\n    name = \"quickdraw\"\n\n    def __init__(self, input_shape, is_train=False, **kwargs):\n        self.download_deps = [\n            \"quickdraw_X.npy\", \"quickdraw_y.npy\"] if is_train else \\\n            [\"quickdraw_X_test.npy\", \"quickdraw_y_test.npy\"]\n        self.is_train = is_train\n        super().__init__(input_shape, **kwargs)\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            QuickDrawDataset only support layout of NCHW and the number of channels must be 3, the image height and width must be equal to 32, i.e. (batch_size, 3, 28, 28).\n        \"\"\"\n        N, C, H, W = self.ishape\n        assert C == 1 and H == 28 and W == 28\n        X = nd.array(np.load(path.join(self.root_dir, self.download_deps[0])))\n        Y = nd.array(np.load(path.join(self.root_dir, self.download_deps[1])))\n        self.data = gluon.data.DataLoader(\n                mx.gluon.data.dataset.ArrayDataset(X, Y),\n                batch_size=N,\n                last_batch='discard',\n                shuffle=self.is_train,\n                num_workers=4)\n\n\n@register_dataset(\"mnist\")\nclass MnistDataset(VisionDataset):\n    # name = \"mnist\"\n    # there is no need to download the data from cortexlabs,\n    #   since mxnet has supplied the neccesary download logic.\n    # download_deps = [\"t10k-images-idx3-ubyte.gz\",\n    #                  \"t10k-labels-idx1-ubyte.gz\",\n    #                  \"train-images-idx3-ubyte.gz\",\n    #                  \"train-labels-idx1-ubyte.gz\"]\n\n    def data_xform(self, data):\n        \"\"\"Move channel axis to the beginning,\n            cast to float32, and normalize to [0, 1].\n        \"\"\"\n        return nd.moveaxis(data, 2, 0).astype('float32') / 255\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            The MxNet gluon package will auto-download the mnist dataset.\n\n            MnistDataset only support layout of NCHW and the number of channels must be 1, the image height and width must be equal to 32, i.e. (batch_size, 1, 28, 28).\n        \"\"\"\n        val_data = mx.gluon.data.vision.MNIST(\n            root=self.root_dir, train=False).transform_first(\n                self.data_xform)\n\n        N, C, H, W = self.ishape\n        assert C == 1 and H == 28 and W == 28\n        self.data = mx.gluon.data.DataLoader(\n            val_data, shuffle=False, batch_size=N)\n\n\n@register_dataset(\"trec\")\nclass TrecDataset(Dataset):\n    # name = \"trec\"\n    download_deps = [\"TREC.train.pk\", \"TREC.test.pk\"]\n\n    def __init__(self, input_shape, is_train=False, **kwargs):\n        self.is_train = is_train\n        super().__init__(input_shape, **kwargs)\n\n    def _load_data(self):\n        \"\"\" Customized _load_data method introduction.\n\n            The MxNet gluon package will auto-download the mnist dataset.\n\n            TrecDataset only support layout of (I, N), the image height and width must be equal to 32, i.e. (batch_size, 1, 28, 28).\n        \"\"\"\n        fname = path.join(\n            self.root_dir, self.download_deps[0] \\\n            if self.is_train else self.download_deps[1])\n\n        I, N = self.ishape\n        assert I == 38\n\n        # (38, batch), (batch,)\n        with open(fname, \"rb\") as fin:\n            reader = pickle.load(fin)\n\n        def data_loader():\n            data, label = [], []\n            for x, y in reader:\n                if len(data) < self.ishape[1]:\n                    data.append(x)\n                    label.append(y)\n                else:\n                    yield nd.transpose(nd.array(data)), nd.array(label)\n                    data, label = [], []\n            yield nd.transpose(nd.array(data)), nd.array(label)\n\n        self.data = data_loader()\n\n    def metrics(self):\n        return {\"acc\": 0, \"total\": 0}\n\n    def validate(self, metrics, predict, label):\n        \"\"\" Customized validate method introduction.\n\n            The score for 6 classes is the model output. The data label is implemented as follows:\n\n            .. code-block:: python\n\n                acc = 1. * metrcs[\"acc\"] / metrics[\"total\"]\n        \"\"\"\n        for idx in range(predict.shape[0]):\n            res_label = predict[idx].asnumpy().argmax()\n            data_label = label[idx].asnumpy()\n            if res_label == data_label:\n                metrics[\"acc\"] += 1\n            metrics[\"total\"] += 1\n\n        acc = 1. * metrics[\"acc\"] / metrics[\"total\"]\n        return \"{:6.2%}\".format(acc)\n\n\n@register_dataset(\"stdrandom\")\nclass StdRandomDataset(Dataset):\n    def _load_data(self):\n        def data_loader():\n            N, I, C = self.ishape\n            assert I == 1 and C == 3\n            data, label = [], []\n            while True:\n                if len(data) < N:\n                    x = np.random.uniform(low=0.0, high=1.0, size=(I,C))\n                    y = np.random.uniform(low=0.0, high=1.0, size=(I))\n                    data.append(x)\n                    label.append(y)\n                else:\n                    batch_data, batch_label = nd.array(data), nd.array(label)\n                    yield batch_data, batch_label\n                    data, label = [], []\n        self.data = data_loader()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/dataset.py",
        "content": "import typing\n\nfrom os import path\n\nimport tvm\n\nfrom .types import *\n\nclass Dataset:\n    def next(self) -> typing.Optional[DataLabelT]:\n        \"\"\" get next data, None if end. \"\"\"\n        raise RuntimeError(\"Base Dataset Error\")\n\n    def reset(self):\n        \"\"\" reset dataset internal reader status. \"\"\"\n        raise RuntimeError(\"Base Dataset Error\")\n\nclass ImageNet(Dataset):\n    category_name = \"imagenet_category.json\"\n\n    def __init__(self):\n        base_dir = path.join(path.dirname(__file__), \"datasets\")\n\n        with open(path.join(base_dir, self.category_name)) as f:\n            self.synset = eval(f.read())\n\n    def label(self, index):\n        return self.synset.get(index, \"unknown category\")\n\n    def labels(self, indexes):\n        return [ self.label(i) for i in indexes ]\n\n\nclass MemoryDataset(Dataset):\n    def __init__(self, available_dls: typing.List[DataLabelT]):\n        self.data = available_dls\n        self._max = len(self.data)\n        self._index = 0\n\n    def next(self) -> typing.Optional[DataLabelT]:\n        if self._index < self._max:\n            self._index += 1\n            return self.data[self._index-1]\n        return None\n\n    def reset(self):\n        self._index = 0\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/extool.py",
        "content": "from __future__ import annotations\nimport typing\n\nimport copy\nfrom functools import wraps\nimport pprint\n\nimport tvm\nfrom tvm import relay, ir\nfrom tvm.ir.expr import *\nfrom tvm.relay.expr import *\n\nfrom .types import *\n\ndef update_expr_args(old: RelayExpr, expr_map) -> RelayExpr:\n    try:\n        new = eval(\"relay.\" + op_name(old))(\n                *args(old), **attrs(old))\n    except Exception as e:\n        print(op_name(old))\n        raise e\n\n    if isinstance(new, relay.TupleWrapper):\n        new = new.tuple_value\n    return new\n\n\ndef clone(expr: RelayExpr, **kwargs) -> RelayExpr:\n    expr = copy.copy(expr)\n    for k, v in kwargs.items():\n        setattr(expr, k, v)\n\n\n_VisitorT = typing.Callable[ [RelayExpr], None ]\n_TransformerT = typing.Callable[\n        [RelayExpr], typing.Optional[RelayExpr]]\n\"\"\" Expr Transformer\n\n    Return new expr to transform old expr into updated one,\n        or just return None for expr visit.\n\"\"\"\n\ndef transform(expr: RelayExpr, callback: _TransformerT) -> RelayExpr:\n    expr_list: typing.List[RelayExpr] = []\n    def _collect_expr(expr: RelayExpr):\n        # primitive ir operators, wrapper by CallNode\n        if isinstance(expr, ir.op.Op):\n            return\n\n        expr_list.append(expr)\n    relay.analysis.post_order_visit(expr, _collect_expr)\n\n    expr_map = {}\n    for i, sym in enumerate(expr_list):\n        out = update_expr_args(sym, expr_map)\n        # pre-clone symbol, to avoid misleading usage in callback\n        out = callback(out) or out\n        assert isinstance(out, RelayExpr)\n        expr_map[sym] = out\n    return expr_map[expr]\n\ndef infer_type(expr: RelayExpr) -> expr:\n    mod = relay.transform.InferType()(ir.IRModule.from_expr(expr))\n    return mod[\"main\"].body\n\ndef visit(expr: RelayExpr, callback: _VisitorT):\n    expr_list: typing.List[RelayExpr] = []\n    def _collect_expr(expr: RelayExpr):\n        # primitive ir operators, wrapper by CallNode\n        if isinstance(expr, ir.op.Op):\n            return\n        expr_list.append(expr)\n    relay.analysis.post_order_visit(expr, _collect_expr)\n\n    for sym in expr_list:\n        callback(sym)\n\n\ndef simple_raw_print(expr: RelayExpr, params: ParametersT = {}):\n    info = { \"op\": 0, \"param\": 0 }\n    def _simple_visit(sym):\n        if not is_operator(sym):\n            print(\"{:68} /* attrs */ \\t{}\".format(\n                sym.name, sym.attrs))\n            if is_param(sym, params):\n                info[\"param\"] += utils.product(sym.attrs[\"shape\"])\n            return\n\n        info[\"op\"] += 1\n        print(\"{:15} = {:>20}{:30} /* attrs */ \\t{}\".format(\n            sym.name, sym.op_name,\n            \"(\" + \", \".join([i.name for i in sym.args]) + \")\",\n            sym.attrs,\n        ))\n    transform(expr, _simple_visit)\n    print(\"=\"*50)\n    print(\"Operators: {} | Parameters: {}\".format(\n        info[\"op\"], info[\"param\"]))\n    print(\"=\"*50)\n\ndef to_json(expr: RelayExpr):\n    json_map = {}\n    def _cast(expr: RelayExpr):\n        data = {\n            \"op_name\": op_name(expr),\n            \"args\": [],\n            \"attrs\": {},\n        }\n\n        json_map[expr] = data\n    visit(expr, _cast)\n    return json_map[expr]\n\n\ndef filter_operators(*op_names: typing.List[str]):\n    def _pass(f):\n        @wraps(f)\n        def _wrapper(expr: RelayExpr, *args, **kw):\n            if op_name(expr) not in op_names:\n                return\n            return f(expr, *args, **kw)\n        return _wrapper\n    return _pass\n\nVAR_NAME = \"var\"\nTUPLE_NAME = \"Tuple\"\nTUPLE_GET_ITEM_NAME = \"TupleGetItem\"\n\ndef op_name(expr: RelayExpr):\n    if isinstance(expr, Call):\n        return expr.op.name\n    elif isinstance(expr, TupleGetItem):\n        return TUPLE_GET_ITEM_NAME\n    elif isinstance(expr, Tuple):\n        return TUPLE_NAME\n    elif isinstance(expr, Var):\n        return VAR_NAME\n    assert False, type(expr)\n\ndef args(expr: RelayExpr) -> List[RelayExpr]:\n    if isinstance(expr, Call):\n        return expr.args\n    elif isinstance(expr, TupleGetItem):\n        return [ expr.tuple_value ]\n    elif isinstance(expr, Tuple):\n        return expr.fields\n    elif isinstance(expr, Var):\n        return []\n    assert False, type(expr)\n\ndef attrs(expr: RelayExpr) -> dict:\n    if isinstance(expr, Call):\n        attrs = expr.attrs or {}\n        return {k: attrs[k] for k in attrs.keys()}\n    elif isinstance(expr, TupleGetItem):\n        return { \"index\": expr.index }\n    elif isinstance(expr, Tuple):\n        return {}\n    elif isinstance(expr, Var):\n        return {\n            \"name_hint\": expr.name_hint,\n            \"shape\": expr.type_annotation.concrete_shape,\n            \"dtype\": expr.type_annotation.dtype,\n        }\n    assert False, type(expr)\n\n\ndef is_operator(expr: RelayExpr, params: ParametersT = {}):\n    return not isinstance(expr, Var)\ndef is_variable(expr: RelayExpr, params: Parameters = {}):\n    return isinstance(expr, Var)\ndef is_param(expr: RelayExpr, params: Parameters):\n    return is_variable(expr) and expr.name_hint in params\ndef is_input(expr: RelayExpr, params: Parameters):\n    return is_variable(expr) and expr.name_hint not in params\n\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/fuse.py",
        "content": "from dataclasses import InitVar\n\nfrom .symbol import *\n\n@dataclass\nclass FusionOp(Symbol):\n\n    params: InitVar[ParametersT]\n\n    def __post_init__(self, params):\n        self._fuse_batch_norm()\n\n\n    @filter_operators(\"nn.batch_norm\")\n    def _fuse_batch_norm(self):\n        X = self.args[0]\n        assert X.is_op(\"nn.conv2d\"), str(self)\n        print(self)\n\n        return self\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/gluon.py",
        "content": "\"\"\" Gluon model zoo for MRT quantizatoin.\n\n    Only **crucial parts** of the module are elaborated.\n\n    Current supported MxNet Model List:\n\n    resnet18_v1, resnet34_v1, resnet50_v1, resnet101_v1, resnet152_v1, resnet18_v2, resnet34_v2, resnet50_v2, resnet101_v2, resnet152_v2,\n    se_resnet18_v1, se_resnet34_v1, se_resnet50_v1, se_resnet101_v1, se_resnet152_v1, se_resnet18_v2, se_resnet34_v2, se_resnet50_v2, se_resnet101_v2, se_resnet152_v2,\n    vgg11, vgg13, vgg16, vgg19, vgg11_bn, vgg13_bn, vgg16_bn, vgg19_bn,\n    alexnet,\n    densenet121, densenet161, densenet169, densenet201,\n    squeezenet1.0, squeezenet1.1,\n    inceptionv3,\n    mobilenet1.0, mobilenet0.75, mobilenet0.5, mobilenet0.25, mobilenetv2_1.0, mobilenetv2_0.75, mobilenetv2_0.5, mobilenetv2_0.25,\n    ssd_300_vgg16_atrous_voc, ssd_300_vgg16_atrous_coco, ssd_300_vgg16_atrous_custom, ssd_512_vgg16_atrous_voc, ssd_512_vgg16_atrous_coco, ssd_512_vgg16_atrous_custom, ssd_512_resnet18_v1_voc, ssd_512_resnet18_v1_coco, ssd_512_resnet50_v1_voc, ssd_512_resnet50_v1_coco, ssd_512_resnet50_v1_custom, ssd_512_resnet101_v2_voc, ssd_512_resnet152_v2_voc, ssd_512_mobilenet1.0_voc, ssd_512_mobilenet1.0_coco, ssd_512_mobilenet1.0_custom,\n    faster_rcnn_resnet50_v1b_voc, faster_rcnn_resnet50_v1b_coco, faster_rcnn_fpn_resnet50_v1b_coco, faster_rcnn_fpn_bn_resnet50_v1b_coco, faster_rcnn_resnet50_v1b_custom, faster_rcnn_resnet101_v1d_voc, faster_rcnn_resnet101_v1d_coco, faster_rcnn_fpn_resnet101_v1d_coco, faster_rcnn_resnet101_v1d_custom,\n    mask_rcnn_resnet50_v1b_coco, mask_rcnn_fpn_resnet50_v1b_coco, mask_rcnn_resnet101_v1d_coco, mask_rcnn_fpn_resnet101_v1d_coco,\n    cifar_resnet20_v1, cifar_resnet56_v1, cifar_resnet110_v1, cifar_resnet20_v2, cifar_resnet56_v2, cifar_resnet110_v2,\n    cifar_wideresnet16_10, cifar_wideresnet28_10, cifar_wideresnet40_8,\n    cifar_resnext29_32x4d, cifar_resnext29_16x64d,\n    fcn_resnet50_voc, fcn_resnet101_coco, fcn_resnet101_voc, fcn_resnet50_ade, fcn_resnet101_ade,\n    psp_resnet101_coco, psp_resnet101_voc, psp_resnet50_ade, psp_resnet101_ade, psp_resnet101_citys,\n    deeplab_resnet101_coco, deeplab_resnet101_voc, deeplab_resnet152_coco, deeplab_resnet152_voc, deeplab_resnet50_ade, deeplab_resnet101_ade,\n    resnet18_v1b, resnet34_v1b, resnet50_v1b, resnet50_v1b_gn, resnet101_v1b_gn, resnet101_v1b, resnet152_v1b, resnet50_v1c, resnet101_v1c, resnet152_v1c, resnet50_v1d, resnet101_v1d, resnet152_v1d, resnet50_v1e, resnet101_v1e, resnet152_v1e, resnet50_v1s, resnet101_v1s, resnet152_v1s, resnext50_32x4d, resnext101_32x4d, resnext101_64x4d,\n    se_resnext50_32x4d, se_resnext101_32x4d, se_resnext101_64x4d,\n    senet_154,\n    darknet53,\n    yolo3_darknet53_coco, yolo3_darknet53_voc, yolo3_darknet53_custom,\n    yolo3_mobilenet1.0_coco, yolo3_mobilenet1.0_voc, yolo3_mobilenet1.0_custom,\n    nasnet_4_1056, nasnet_5_1538, nasnet_7_1920, nasnet_6_4032,\n    simple_pose_resnet18_v1b, simple_pose_resnet50_v1b, simple_pose_resnet101_v1b, simple_pose_resnet152_v1b, simple_pose_resnet50_v1d, simple_pose_resnet101_v1d, simple_pose_resnet152_v1d,\n    residualattentionnet56, residualattentionnet92, residualattentionnet128, residualattentionnet164, residualattentionnet200, residualattentionnet236, residualattentionnet452,\n    cifar_residualattentionnet56, cifar_residualattentionnet92, cifar_residualattentionnet452,\n    resnet18_v1b_0.89, resnet50_v1d_0.86, resnet50_v1d_0.48, resnet50_v1d_0.37, resnet50_v1d_0.11, resnet101_v1d_0.76, resnet101_v1d_0.73,\n    mobilenet1.0_int8,\n    resnet50_v1_int8,\n    ssd_300_vgg16_atrous_voc_int8,\n    ssd_512_mobilenet1.0_voc_int8,\n    SSD_512_RESNET50_V1_VOC_INT8,\n    SSD_512_VGG16_ATROUS_VOC_INT8\n\"\"\"\nimport os\n\nimport mxnet as mx\nfrom mxnet import ndarray as nd\nfrom mxnet.gluon.model_zoo import vision\n\nimport gluoncv as cv\n\nfrom . import utils\n\ndef load_inception_v3(ctx):\n    return vision.inception_v3(pretrained=True, ctx=ctx, prefix=\"\")\ndef save_inception_v3():\n    graph = load_inception_v3(mx.cpu())\n    sym = graph(mx.symbol.Variable('data'))\n    with open('./data/inception_v3.json', 'w') as fout:\n        fout.write(sym.tojson())\n    graph.save_params('./data/inception_v3.params')\n\ndef load_mobilenet1_0(ctx):\n    return vision.mobilenet1_0(pretrained=True, ctx=ctx, prefix=\"\")\ndef save_mobilenet1_0():\n    graph = load_mobilenet1_0(mx.cpu())\n    sym = graph(mx.symbol.Variable('data'))\n    with open('./data/mobilenet1_0.json', 'w') as fout:\n        fout.write(sym.tojson())\n    graph.save_params('./data/mobilenet1_0.params')\n\ndef load_mobilenet_v2_1_0(ctx):\n    return vision.mobilenet_v2_1_0(pretrained=True, ctx=ctx, prefix=\"\")\ndef save_mobilenet_v2_1_0():\n    graph = load_mobilenet_v2_1_0(mx.cpu())\n    sym = graph(mx.sym.var('data'))\n    with open('./data/mobilenet_v2_1_0.json', 'w') as fout:\n        fout.write(sym.tojson())\n    graph.save_parameters('./data/mobilenet_v2_1_0.params')\n\ndef load_resnet18_v1_yolo():\n    return cv.model_zoo.get_model('yolo3_resnet18_v1_voc',\n            pretrained=False, pretrained_base=True,\n            ctx=mx.gpu())\n\ndef get_model(name, ctx=mx.gpu(), **kwargs):\n    \"\"\" Returns a pre-defined model by name\n\n        Parameters\n        ----------\n        name : str\n            Name of the model.\n        classes : int\n            Number of classes for the output layer.\n        ctx : mxnet.context()\n            Devices to get model.\n\n        Returns\n        -------\n        ret : HybridBlock\n            The model.\n    \"\"\"\n    return cv.model_zoo.get_model(\n            name, pretrained=True,\n            ctx=ctx, **kwargs)\n\ndef load_model(sym_fname, param_fname):\n    return mx.sym.load(sym_fname), nd.load(param_fname)\n\ndef save_model(name, data_dir=None, ctx=mx.gpu(), **kwargs):\n    \"\"\" Returns a pre-defined model by name\n\n        Parameters\n        ----------\n        name : str\n            Name of the model.\n        data_dir : str\n            Directory to store the model.\n        ctx : mxnet.context()\n            Devices to get model.\n\n        Returns\n        -------\n        ret : tuple\n            The symbol path and the model path.\n    \"\"\"\n    net = get_model(name, ctx=ctx, **kwargs)\n    sym = net(mx.sym.var('data'))\n    if isinstance(sym, tuple):\n        sym = mx.sym.Group([*sym])\n\n    data_dir = utils.MRT_MODEL_ROOT if data_dir is None else data_dir\n    prefix = os.path.join(data_dir, name)\n    sym_path, prm_path = utils.extend_fname(prefix)\n\n    with open(sym_path, \"w\") as fout:\n        fout.write(sym.tojson())\n    net.collect_params().save(prm_path)\n    return sym_path, prm_path\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/image.py",
        "content": "from os import path\n\nimport numpy as np\nfrom PIL import Image\n\nimport tvm\nfrom tvm.contrib.download import download_testdata\n\n\ndef get_real_image(im_height, im_width) -> np.ndarray:\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    data = np.array(image).astype(\"float32\")\n    data = np.reshape(data, (1, im_height, im_width, 3))\n    data = np.transpose(data, (0, 3, 1, 2))\n    return data\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/runtime.py",
        "content": "import typing\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, ir, runtime\nfrom tvm.contrib import graph_executor\nfrom tvm.ir import RelayExpr\n\nfrom .types import *\nfrom .dataset import Dataset\nfrom .stats import Statistics\nfrom . import symbol\n\n__all__ = [\"infer\"]\n\ndef create_executor(\n        expr: RelayExpr, params: ParametersT, device=runtime.cpu(0),\n        opt_level=0\n) -> relay.build_module.GraphExecutor:\n    target = \"llvm\"\n    with tvm.transform.PassContext(opt_level=opt_level):\n        lib = relay.build_module.build(\n                ir.IRModule.from_expr(expr),\n                target=target, params=params)\n\n    rt_mod: relay.build_module.GraphExecutor = \\\n            graph_executor.GraphModule(lib[\"default\"](device))\n    return rt_mod\n\nOutputDataType = typing.List[np.ndarray]\n\ndef infer(expr: RelayExpr, params: ParametersT,\n        device=runtime.cpu(0)) -> OutputDataType:\n    # #  target = \"llvm\"\n    # target = tvm.target.cuda()\n    # with tvm.transform.PassContext(opt_level=3):\n    #     lib = relay.build_module.build(\n    #             ir.IRModule.from_expr(expr),\n    #             target=target,\n    #             params=params)\n\n    # rt_mod: relay.build_module.GraphExecutor = graph_executor.GraphModule(lib[\"default\"](device))\n    # #  rt_mod.set_input(\"input\", data)\n    # rt_mod.run()\n    # return [rt_mod.get_output(i).numpy() \\\n    #         for i in range(rt_mod.get_num_outputs())]\n\n    result = tvm.relay.create_executor(\n        \"graph\", mod=ir.IRModule.from_expr(expr),\n        device=device, target=\"llvm\",\n    ).evaluate()(**params)\n    return result\n    # if isinstance(result, tvm.runtime.NDArray):\n    #     result = [ result, ]\n    # return [ r.numpy() for r in result ]\n\n\ndef validator(expr: RelayExpr, params: ParametersT, name: str,\n        device=runtime.cpu(0), ):\n    target = \"llvm\"\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build_module.build(\n                ir.IRModule.from_expr(expr),\n                target=target,\n                params=params)\n    mod: relay.build_module.GraphExecutor = graph_executor.GraphModule(lib[\"default\"](device))\n\n    input_names = []\n    for v in relay.analysis.free_vars(expr):\n        if v.name_hint not in params:\n            input_names.append(v.name_hint)\n\n    assert len(input_names) == 1\n    assert mod.get_num_outputs() == 1\n    input_name = input_names[0]\n\n    def _run(dl: DataLabelT) -> DataLabelT:\n        data, label = dl\n        mod.set_input(input_name, dl)\n        mod.run()\n        return mod.get_output(0).numpy, dl\n    _run.__name__ = name\n    return _run\n\n\nValidateFunctionT = typing.Callable[[DataLabelT], DataLabelT]\n\ndef multiple_validate(\n        base_func: ValidateFunctionT,\n        dataset: Dataset, stats_type: typing.Type[Statistics],\n        *comp_funcs: typing.List[ValidateFunctionT],\n        max_iter_num: typing.Optional[int] = None,\n):\n    all_funcs = [ base_func, ] + list(comp_funcs)\n    all_stats = [stats_type() for _ in all_funcs]\n\n    log_str = \"Iteration: {:3d} | \"\n    for func in all_funcs:\n        log_str += func.__name__ + \": {} | \"\n    for i in range(max_iter_num):\n        dl = dataset.next()\n        if dl is None:\n            break\n        for func, stats in zip(all_funcs, all_stats):\n            out_dl = func(dl)\n            stats.merge(out_dl)\n        msg = log_str.format(i, *[s.info() for s in all_stats])\n        print(msg)\n\n    print(\"Multiple Validation Done!\")\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/stats.py",
        "content": "from os import path\nimport enum\n\nimport tvm\nimport numpy as np\n\nfrom .utils import PY_ROOT\nfrom .types import *\n\nclass StatsConfig(enum.Enum):\n    NONE    = enum.auto()\n    ALL     = enum.auto()\n\n    ACCURACY    = enum.auto()\n    \"\"\" enable accuracy info in stats, True by default. \"\"\"\n    TIME        = enum.auto()\n    \"\"\" enable time logger in stats. \"\"\"\n    DL          = enum.auto()\n    \"\"\" print current DataLabelT's info, this will suppress all other config. \"\"\"\n\n\nclass Statistics:\n    def __init__(self):\n        self.stats_info = {}\n\n    def reset(self):\n        \"\"\" reset statistic status. \"\"\"\n        raise RuntimeError(\"Accuracy Type Error\")\n\n    def merge(self, dl: DataLabelT):\n        \"\"\" merge model output and update status. \"\"\"\n        raise RuntimeError(\"Accuracy Type Error\")\n\n    def info(self) -> str:\n        \"\"\" return statistic information. \"\"\"\n        raise RuntimeError(\"Accuracy Type Error\")\n\n    def dl_info(self) -> str:\n        \"\"\" return current DataLabel information. \"\"\"\n        raise RuntimeError(\"Accuracy Type Error\")\n\n\nclass ClassificationOutput(Statistics):\n    def __init__(self):\n        self.num_classes = None\n        self.data, self.label = None, None\n\n        self.top1_hit = 0\n        self.top5_hit = 0\n        self.dl_total = 0\n\n        self.dl_top1, self.top1_raw = [], []\n        self.dl_top5, self.top5_raw = [], []\n\n    def reset(self):\n        self.top1_hit = 0\n        self.top5_hit = 0\n        self.dl_total = 0\n\n    def merge(self, dl: DataLabelT):\n        data, label = dl\n        self.argsort = [ np.argsort(d).tolist() for d in data]\n\n        self.dl_top1 = [a[-1] for a in self.argsort]\n        self.dl_top5 = [a[-5:] for a in self.argsort]\n        self.top1_raw = [ data[i][b] \\\n                for i, b in enumerate(self.dl_top1) ]\n        self.top5_raw = [ [data[i][a] for a in b] \\\n                for i, b in enumerate(self.dl_top5) ]\n\n        assert len(data.shape) == 2\n        self.batch = data.shape[0]\n        assert len(label.shape) == 1\n        assert self.batch == label.shape[0]\n        if self.num_classes is None:\n            self.num_classes = data.shape[1]\n        else:\n            assert self.num_classes == data.shape[1]\n\n        label = label.tolist()\n        self.dl_total += self.batch\n        for d, l in zip(self.dl_top1, label):\n            self.top1_hit += (d == int(l))\n\n        for d, l in zip(self.dl_top5, label):\n            self.top5_hit += (int(l) in d)\n\n    def dl_info(self):\n        print(\"=\" * 50)\n        print(\"Batch: {}, Class Number: {}\".format(\n            self.batch, self.num_classes))\n        top1, top1_raw = self.dl_top1, self.top1_raw\n        top5, top5_raw = self.dl_top5, self.top5_raw\n        for i in range(self.batch):\n            print(\"{:5} Top1: {:3} | Raw: {}\".format(\n                i, top1[i], top1_raw[i]))\n            print(\"{:5} Top5: {} | Raw: {}\".format(\n                i, top5[i], top5_raw[i]))\n            # print(\"{:5} Top1: {:3} | Top5: {}\".format(\n            #     i, top1[i], top5[i]))\n        print(\"=\" * 50)\n\n    def info(self):\n        return \"{},{}\".format(\n                (1. * self.top1_hit / self.dl_total),\n                (1. * self.top5_hit / self.dl_total))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/symbol.py",
        "content": "from __future__ import annotations\nimport typing\n\nfrom dataclasses import dataclass, fields, is_dataclass\nfrom functools import wraps\nimport json\n\nimport tvm\nfrom tvm import relay, ir\nfrom tvm.ir.expr import *\nfrom tvm.relay.expr import *\n\nfrom .utils import *\nfrom .types import *\n\n# __all__ = [\n#         \"Symbol\", \"ParametersT\",\n#         \"is_operator\", \"is_variable\", \"is_input\", \"is_param\",\n#         # symbol pass wrapper and some help functions\n#         \"transform\", \"filter_operators\", \"visit\",\n#         \"simple_raw_print\",\n#         # API with expr\n#         \"expr2symbol\", \"symbol2expr\",\n#         ]\n\nVAR_NAME = \"var\"\nTUPLE_GET_ITEM_NAME = \"TupleGetItem\"\nTUPLE_NAME = \"Tuple\"\n\ndef is_operator(symbol: Symbol, params: ParametersT = {}):\n    return symbol.op_name != VAR_NAME\n\ndef is_variable(symbol: Symbol, params: ParametersT = {}):\n    return symbol.op_name == VAR_NAME\n\ndef is_input(symbol: Symbol, params: ParametersT):\n    return is_variable(symbol) and symbol.name not in params\n\ndef is_param(symbol: Symbol, params: ParametersT):\n    return is_variable(symbol) and symbol.name in params\n\n_CopyAttrsT = typing.Union[typing.List[str], str]\n\n@dataclass\nclass Symbol:\n    \"\"\" Uniform Symbol Representation for RelayExpr\n\n    RelayExpr has different format for operators, functions,\n        which is hard to apply uniform transformation pass.\n        Such as the `TupleGetItem`.\n\n    Abstract representation allows different definitions\n        for operators, which can be easier for graph\n        transformation. Like the `BatchNorm` op returns\n        a 3-tuple, whereas the return is first in cvm.\n\n    We need to consistently print symbol information such as name,\n        for the user's config about quantization layers.\n    \"\"\"\n\n    name: str\n    op_name: str\n    args: typing.List[Symbol]\n    attrs: typing.Dict[str, typing.Any]\n\n    def __hash__(self) -> int:\n        return hash(str(self))\n\n    @staticmethod\n    def variable(name):\n        return Symbol(name, VAR_NAME, [], { \"name_hint\": name })\n\n    def as_parameter(self) -> Symbol:\n        var = Symbol.variable(self.name)\n        var.attrs[\"shape\"] = self.shape\n        var.attrs[\"dtype\"] = self.dtype\n        return var\n\n    def is_op(self, op_name):\n        return self.op_name == op_name\n\n    def to_dict(self):\n        return dict((f.name, getattr(self, f.name)) \\\n                for f in fields(self))\n\n    def clone(self, cls: typing.Type[Symbol] = None, **kw):\n        cls = cls or type(self)\n        assert is_dataclass(cls)\n\n        data = {}\n        for k in [f.name for f in fields(cls)]:\n            if k in [f.name for f in fields(self)]:\n                data[k] = getattr(self, k)\n        data.update(kw)\n\n        try:\n            new = cls(**data)\n        except Exception as e:\n            print(\"clone failed: \", cls.__name__,\n                    self, list(data.keys()))\n            raise e\n        return new\n\n    @property\n    def shape(self):\n        return self.attrs[\"shape\"]\n\n    @property\n    def dtype(self):\n        return self.attrs[\"dtype\"]\n\n    def __eq__(self, other: Symbol):\n        return self.args == other.args and hash(self) == hash(other)\n\n    def __str__(self):\n        args_info= [\"{}@{}\".format(\n            i.name, i.attrs.get(\"shape\", None)) \\\n            for i in self.args ]\n        return \"{} = {}({}) /* attrs */ \\t{}\".format(\n            self.name, self.op_name,\n            \", \".join(args_info),\n            self.attrs)\n\n\ndef _topo_sort(symbol: Symbol, sym_list: typing.List[Symbol]):\n    if sym_list.count(symbol) > 0:\n        return\n    for c in symbol.args:\n        _topo_sort(c, sym_list)\n    sym_list.append(symbol)\n\n_VisitorT = typing.Callable[[Symbol], None]\n_TransformerT = typing.Callable[[Symbol], typing.Optional[Symbol]]\n\"\"\" Symbol Transformer\n\n    Return new symbol to transform old symbol into updated one,\n        or just return None for symbol visit.\n\"\"\"\n\ndef visit(symbol: Symbol, callback: _VisitorT):\n    \"\"\" Visitor mode, possible modify symbol itself. \"\"\"\n    sym_list: typing.List[Symbol] = []\n    _topo_sort(symbol, sym_list)\n    for sym in sym_list:\n        callback(sym)\n\n\ndef transform(symbol: Symbol, callback: _TransformerT) -> Symbol:\n    \"\"\" Transform symbol from old to new, with inputs updated.\n\n        Only the return value indicates mutation, while changing\n        attributes in parameter passed in args does nothing.\n    \"\"\"\n    sym_list: typing.List[Symbol] = []\n    _topo_sort(symbol, sym_list)\n\n    sym_map = {}\n    for sym in sym_list:\n        args = [sym_map[c.name] for c in sym.args]\n        # pre-clone symbol, to avoid misleading usage in callback\n        sym = sym.clone(\n                args=args,\n                attrs={k: v for k, v in sym.attrs.items()})\n        out = callback(sym) or sym\n        assert isinstance(out, Symbol)\n        sym_map[sym.name] = out\n    return sym_map[symbol.name]\n\ndef filter_operators(*op_names: typing.List[str]):\n    def _pass(f):\n        @wraps(f)\n        def _wrapper(sym: Symbol) -> typing.Any:\n            if any([ sym.is_op(n) for n in op_names ]):\n                return f(sym)\n        return _wrapper\n    return _pass\n\ndef simple_raw_print(symbol: Symbol, params: ParametersT ={}):\n    info = { \"op\": 0, \"param\": 0 }\n    def _simple_visit(sym):\n        if is_param(sym, params):\n            info[\"param\"] += product(params[sym.name].shape)\n\n        info[\"op\"] += is_operator(sym)\n        print(\"{:30} = {:>15}{:30} /* attrs */ {}\".format(\n            sym.name, sym.op_name,\n            \"(\" + \", \".join([i.name for i in sym.args]) + \")\",\n            sym.attrs,\n        ))\n    transform(symbol, _simple_visit)\n    print(\"=\"*50)\n    print(\"Operators: {} | Parameters: {}\".format(\n        info[\"op\"], info[\"param\"]))\n    print(\"=\"*50)\n\n# ==============================================================\n# API from relay.Function to Symbol.\n# ==============================================================\n\nSUPPORTED_EXPR_TYPE = (\n        relay.expr.Var,\n        ir.op.Op, # Op are wrapped by Call.\n        relay.expr.Call,\n        relay.expr.TupleGetItem,\n        )\n\ndef expr_type(checked_type: ir.type.Type, key):\n    if isinstance(checked_type, ir.type.TupleType):\n        return [expr_type(f, key) for f in checked_type.fields]\n    return getattr(checked_type, key)\n\ndef expr2symbol(expr: RelayExpr) -> Symbol:\n    mod = relay.transform.InferType()(ir.IRModule.from_expr(expr))\n    expr = mod[\"main\"].body\n\n    symbol_map = {}\n    def _cast_expr(node: RelayExpr):\n        if not isinstance(node, SUPPORTED_EXPR_TYPE):\n            raise RuntimeError(\n                \"MRT not support expr type:{}\".format(type(node)))\n\n        if isinstance(node, ir.op.Op):\n            return\n\n        if isinstance(node, relay.Var):\n            name = node.name_hint or N.n(prefix=\"input_\")\n            symbol_map[node] = Symbol.variable(name)\n        elif isinstance(node, relay.Call):\n            args = [symbol_map[i] for i in node.args]\n            attrs = node.attrs or {}\n            attrs = {k: attrs[k] for k in attrs.keys()}\n            symbol_map[node] = Symbol(N.n(), node.op.name,\n                    args, attrs)\n        elif isinstance(node, relay.TupleGetItem):\n            args = [ symbol_map[node.tuple_value], ]\n            symbol_map[node] = Symbol(N.n(), TUPLE_GET_ITEM_NAME,\n                    args, { \"index\": node.index })\n        elif isinstance(node, relay.Tuple):\n            args = [ symbol_map[f] for f in node.fields ]\n            symbol_map[node] = Symbol(N.n(), TUPLE_NAME,\n                    args, {})\n\n        dtype = expr_type(node.checked_type, \"dtype\")\n        shape = expr_type(node.checked_type, \"concrete_shape\")\n        #  print(dtype, shape, type(shape))\n        symbol_map[node].attrs.update({\n            \"shape\": list(shape),\n            \"dtype\": dtype,\n        })\n\n    with N():\n        relay.analysis.post_order_visit(expr, _cast_expr)\n    return symbol_map[expr]\n\ndef symbol2expr(symbol: Symbol, expr_map={}) -> RelayExpr:\n    # operator creator don't need shape or dtype attrs,\n    #   except for the variable.\n    def _remove_type(sym: Symbol):\n        if is_variable(sym):\n            return\n\n        if \"shape\" in sym.attrs:\n            del sym.attrs[\"shape\"]\n        if \"dtype\" in sym.attrs:\n            del sym.attrs[\"dtype\"]\n        return sym\n    symbol = transform(symbol, _remove_type)\n\n    expr_map.clear()\n    def _cast_symbol(sym: Symbol):\n        args = [expr_map[i] for i in sym.args]\n        if sym.is_op(TUPLE_NAME):\n            out = relay.Tuple(args)\n        else:\n            try:\n                out = eval(\"relay.\" + sym.op_name)(*args, **sym.attrs)\n            except Exception as e:\n                print(sym, [type(a) for a in args])\n                raise e\n\n        if isinstance(out, relay.TupleWrapper):\n            out = out.tuple_value\n        # relay.transform.InferTypeLocal(out)\n        expr_map[sym] = out\n\n    _ = transform(symbol, _cast_symbol)\n    return expr_map[symbol]\n\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/topi.py",
        "content": "import typing\nfrom functools import wraps\n\nimport numpy as np\n\nimport tvm\nfrom tvm.ir import RelayExpr\nfrom tvm.topi import testing\n\nfrom .extool import *\n\nTOPI_REGS = {}\n\nDataType = typing.List[np.ndarray]\n\ndef register_topi(op_name):\n    def _wrapper(f):\n        TOPI_REGS[op_name] = f\n        return f\n    return _wrapper\n\n@register_topi(\"nn.conv2d\")\ndef run_conv2d(data: DataType, attrs: AttrsT):\n    dw_np = topi.testing.dilate_python()\n    return testing.conv2d_nchw_python(*data, **attrs)\n\n@register_topi(\"nn.batchnorm\")\ndef run_batchnorm(data: DataType, attrs: AttrsT):\n    return testing.batch_norm(*data, **attrs)\n\n# def execute(op_name: str, attrs: AttrsT, data: DataType) -> np.ndarray:\n#     eval(\"relay.\" + op_name)(op_name, )\n#     return TOPI_REGS[op_name](data, attrs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/torch.py",
        "content": "from torchvision import models\n\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/trace.py",
        "content": "from __future__ import annotations\nimport typing\n\nfrom dataclasses import dataclass, field\nfrom functools import wraps\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, ir\nfrom tvm.contrib import graph_executor as graph\n\nfrom .symbol import *\nfrom .types import *\nfrom . import topi\nfrom . import runtime\n\nVisitor = typing.Callable[[Symbol, ParametersT], None]\nTransformer = typing.Callable[[Symbol, ParametersT], typing.Optional[Symbol]]\n\n@dataclass\nclass Trace:\n    \"\"\" Only use visitor mode in Trace. \"\"\"\n\n    name: str\n    \"\"\" Trace Name \"\"\"\n    symbol: Symbol\n    params: ParametersT\n\n    sym_inputs: typing.List[Symbol] = field(init=False)\n    sym_params: typing.List[Symbol] = field(init=False)\n\n    def __post_init__(self):\n        self.sym_inputs = []\n        self.sym_params = []\n        def _init(sym: Symbol):\n            if is_input(sym, self.params):\n                self.sym_inputs.append(sym)\n            elif is_param(sym, self.params):\n                sym_shape = list(sym.attrs[\"shape\"])\n                param_shape = self.params[sym.name].shape\n                assert sym_shape == list(param_shape), (\n                    \"param:{} shape inconsistent: {} vs. {}\"\n                ).format(sym.name, sym_shape, param_shape)\n                # sym.attrs[\"shape\"] = self.params[sym.name].shape\n                self.sym_params.append(sym)\n        visit(self.symbol, _init)\n\n    @property\n    def input_names(self) -> typing.List[str]:\n        return [i.name for i in self.sym_inputs]\n\n    @property\n    def input_shapes(self) -> typing.List[ShapeT]:\n        return [i.attrs[\"shape\"] for i in self.sym_inputs]\n\n    def random_inputs(self) -> ParametersT:\n        data = {}\n        for sym in self.sym_inputs:\n            shape = sym.attrs[\"shape\"]\n            dtype = sym.attrs[\"dtype\"]\n            np_data = np.random.randn(*shape).astype(dtype)\n            data[sym.name] = tvm.nd.array(np_data)\n        return data\n\n    def calibrate(self,\n            data: typing.Optional[np.ndarray] = None,\n            data_dict: typing.Dict[str, np.ndarray] = {},\n        ) -> typing.Dict[str, np.ndarray]:\n        calibrate_outputs: typing.Dict[str, np.ndarray] = {\n                k: v.numpy() for k, v in self.params.items()}\n\n        # set input data\n        for v in self.sym_inputs:\n            shape, dtype = v.attrs[\"shape\"], v.attrs[\"dtype\"]\n            val = data_dict.get(v.name, data)\n            if val is None:\n                print(\"input: {} use random data\".format(v.name))\n                val = np.random.randn(*shape).astype(dtype)\n            calibrate_outputs[v.name] = val\n\n        def _execute(sym: Symbol, data: ParametersT) -> runtime.OutputDataType:\n            args = [ a.as_parameter() for a in sym.args]\n            sym = sym.clone(args=args)\n            expr = symbol2expr(sym)\n            result = runtime.infer(expr, data)\n            return result\n\n        def _tassert(expect: typing.Any, val: typing.Any):\n            if isinstance(expect, ( list, tuple )):\n                assert len(expect) == len(val), (\n                    \"{} vs. {}\").format(expect, val)\n                for e, o in zip(expect, val):\n                    _tassert(e, o)\n            elif isinstance(expect, ( int, str )):\n                assert expect == val\n\n        def _get_type(out, key):\n            if isinstance(out, tvm.runtime.NDArray):\n                return getattr(out, key)\n            return [ _get_type(o, key) for o in out ]\n\n        def _calibrate(sym: Symbol, params: ParametersT):\n            global TUPLE_GET_ITEM_NAME\n\n            if is_variable(sym, params):\n                return\n            if sym.op_name == TUPLE_GET_ITEM_NAME:\n                out = calibrate_outputs[sym.args[0].name][sym.attrs['index']]\n            else:\n                out = _execute(sym, calibrate_outputs)\n\n            _tassert(sym.attrs[\"shape\"], _get_type(out, \"shape\"))\n            _tassert(sym.attrs[\"dtype\"], _get_type(out, \"dtype\"))\n            calibrate_outputs[sym.name] = out\n\n        self.visit(_calibrate)\n        return calibrate_outputs\n\n    def run(self,\n            data: typing.Optional[tvm.nd.NDArray] = None,\n            data_dict: ParametersT = {},\n            device: tvm.runtime.Device = tvm.runtime.cpu(0),\n    ) -> typing.List[np.ndarray]:\n        params = {k: v for k, v in self.params.items()}\n        for sym in self.sym_inputs:\n            val = data_dict.get(sym.name, data)\n            shape = sym.attrs[\"shape\"]\n            dtype = sym.attrs[\"dtype\"]\n            assert val is not None\n            assert shape == list(val.shape), (\n                    \"{}: {} vs. {}\").format(\n                            sym.name, shape, val.shape)\n            assert dtype == val.dtype\n            params[sym.name] = val\n\n        return runtime.infer(self.to_mod(), params, device=device)\n\n    def random_run(self) -> typing.List[tvm.nd.NDArray]:\n        data = {}\n        for sym in self.sym_inputs:\n            shape = sym.attrs[\"shape\"]\n            dtype = sym.attrs[\"dtype\"]\n            np_data = np.random.randn(*shape).astype(dtype)\n            data[sym.name] = tvm.nd.array(np_data)\n        return self.run(data_dict=data)\n\n    def set_input_shape(self,\n            shape = None, shape_dict = {}) -> Trace:\n       shape_dict[\"common_shape\"] = shape\n       def _set_shape(sym: Symbol):\n           if is_input(sym, self.params):\n               shape = shape_dict.get(\n                       sym.name, shape_dict[\"common_shape\"])\n               if shape is not None:\n                   sym.attrs[\"shape\"] = shape\n           return sym\n\n       symbol = transform(self.symbol, _set_shape)\n       return Trace.from_expr(symbol2expr(symbol), self.params)\n\n    def print(self):\n        simple_raw_print(self.symbol, self.params)\n\n    def visit(self, callback: Visitor):\n        def _visitor(sym: Symbol):\n            callback(sym, self.params)\n        visit(self.symbol, _visitor)\n\n    def transform(self, callback: Transformer) -> Trace:\n        def _tfm(sym: Symbol):\n            return callback(sym, self.params)\n        return Trace(callback.__name__,\n                transform(self.symbol, _tfm), self.params)\n\n    def to_expr(self, expr_map={}) -> ir.RelayExpr:\n        return symbol2expr(self.symbol, expr_map)\n\n    @staticmethod\n    def from_expr(expr: RelayExpr, params: ParametersT) -> Trace:\n        return Trace(\"init\", expr2symbol(expr), params)\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/transform.py",
        "content": "from __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass, fields\n\nimport tvm\nfrom tvm import relay, ir\n\nfrom . import transformers\nfrom .symbol import *\nfrom .trace import *\n\n@dataclass\nclass Transformer(Symbol):\n    \"\"\" Type TransformerT for Trace \"\"\"\n\n    params: ParametersT = field(default_factory=dict)\n\n    def is_input(self) -> bool:\n        return is_input(self, self.params)\n    def is_param(self) -> bool:\n        return is_param(self, self.params)\n    def is_variable(self) -> bool:\n        return is_variable(self, self.params)\n    def is_operator(self) -> bool:\n        return is_operator(self, self.params)\n\n    @classmethod\n    def apply(cls, *args, **kw):\n        def _tfm(symbol: Symbol, params: ParametersT):\n            ins = symbol.clone(cls, params=params)\n            return ins(*args, **kw) or ins\n        return _tfm\n\n    def __call__(self, *args, **kw) -> Symbol:\n        return self\n\n\nclass Validator(Transformer):\n    pass\n\nclass Quantizer(Transformer):\n    def expect_max_precision(self, max_prec) -> Quantizer:\n        \"\"\" Requantization Method  \"\"\"\n        raise NotImplementedError(\"\")\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/transformers/__init__.py",
        "content": "\n\nfrom .validate import *\nfrom .quantize import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/transformers/quantize.py",
        "content": "\nfrom tvm import relay, ir\n\ndef quantize_conv2d(expr: relay.Call, attrs):\n    \"\"\" quantize by scale. \"\"\"\n    assert isinstance(expr, relay.Call)\n    expr.op\n    pass\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/transformers/validate.py",
        "content": "\nfrom tvm import relay, ir\n\nfrom ..extool import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/types.py",
        "content": "import typing\n\nimport tvm\nimport numpy as np\n\nParametersT = typing.Dict[str, tvm.nd.NDArray]\nAttrsT = typing.Dict[str, typing.Any]\n\nShapeT = typing.Union[typing.List[int], typing.Tuple[int]]\n\"\"\" shape type, tuple of int, such as (1, 3, 34, 34). \"\"\"\n\nDataLabelT = typing.Tuple[np.ndarray, typing.Any]\n\"\"\" a (data, label) representation. \"\"\"\n\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/mrt/utils.py",
        "content": "from __future__ import annotations\n\nimport typing\nimport threading\nimport os\nfrom os import path\n\nfrom tvm import relay, ir\n\nfrom .types import *\n\nROOT = path.abspath(path.join(__file__, \"../../../\"))\nPY_ROOT = path.join(ROOT, \"python\")\n\nMRT_MODEL_ROOT = path.expanduser(\"~/mrt_model\")\nif not path.exists(MRT_MODEL_ROOT):\n    os.makedirs(MRT_MODEL_ROOT)\n\nMRT_DATASET_ROOT = path.expanduser(\"~/.mxnet/datasets\")\nif not path.exists(MRT_DATASET_ROOT):\n    os.makedirs(MRT_DATASET_ROOT)\n\ndef product(shape: ShapeT):\n    total = 1\n    for s in shape:\n        total *= s\n    return total\n\nclass N:\n    def __init__(self, name=\"\"):\n        self.counter = 0\n        self.scope_name = name\n        self.lock = threading.Lock()\n        self.last_scope = N.__GLOBAL_INSTANCE__\n\n    def __enter__(self):\n        self._set_name_scope(self)\n        return self\n\n    def __exit__(self, *args):\n        self._set_name_scope(self.last_scope)\n\n    def _alloc_name(self, prefix, suffix):\n        with self.lock:\n            index = self.counter\n            self.counter += 1\n        name = \"{}{}{}\".format(prefix, index, suffix)\n        if self.scope_name:\n            name = \"{}.{}\".format(self.scope_name, name)\n        return name\n\n    __GLOBAL_INSTANCE__ = None\n\n    @staticmethod\n    def _set_name_scope(ins):\n        N.__GLOBAL_INSTANCE__ = ins\n\n    @staticmethod\n    def n(prefix=\"%\", suffix=\"\"):\n        ins = N.__GLOBAL_INSTANCE__\n        if ins is None:\n            raise RuntimeError(\"Namescope not specified\")\n        return ins._alloc_name(prefix, suffix)\n\n    @staticmethod\n    def register_global_scope(name=\"\"):\n        N._set_name_scope(N(name))\n\ndef extend_fname(prefix, with_ext=False):\n    \"\"\" Get the precision of the data.\n\n        Parameters\n        __________\n        prefix : str\n            The model path prefix.\n        with_ext : bool\n            Whether to include ext_file path in return value.\n\n        Returns\n        _______\n        ret : tuple\n            The symbol path, params path; and with_ext is True, also return ext file path.\n    \"\"\"\n    ret = [\"%s.json\"%prefix, \"%s.params\"%prefix]\n    if with_ext:\n        ret.append(\"%s.ext\"%prefix)\n    return tuple(ret)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/parser/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"The under development unified IR parsing infrastructure.\"\"\"\nfrom .. import _ffi, Object\nfrom . import _ffi_api\n\n\n@_ffi.register_object(\"SourceMap\")\nclass SourceMap(Object):\n    def add(self, name, content):\n        return _ffi.get_global_func(\"SourceMapAdd\")(self, name, content)\n\n\ndef parse(source, source_name=\"from_string\", init_module=None, init_meta_table=None):\n    if init_meta_table is None:\n        init_meta_table = {}\n    return _ffi_api.ParseModuleInContext(source_name, source, init_module, init_meta_table)\n\n\ndef parse_expr(source):\n    return _ffi_api.ParseExpr(\"string\", source)\n\n\ndef fromtext(source, source_name=\"from_string\"):\n    return parse(source, source_name)\n\n\ndef SpanCheck():\n    \"\"\"A debugging utility for reporting missing span information.\"\"\"\n    return _ffi_api.SpanCheck()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/parser/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.ir\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"parser\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay IR namespace containing the IR definition and compiler.\"\"\"\nimport os\nfrom sys import setrecursionlimit\n\nfrom . import base\nfrom . import ty\nfrom . import expr\nfrom . import function\nfrom . import type_functor\nfrom . import expr_functor\nfrom . import adt\nfrom . import prelude\nfrom . import loops\nfrom . import scope_builder\n\nfrom . import transform\nfrom . import analysis\nfrom . import collage\nfrom .build_module import build, create_executor, optimize\nfrom .transform import build_config\nfrom . import debug\nfrom . import param_dict\nfrom .backend import vm\n\n# Root operators\nfrom .op import nn\nfrom .op import image\nfrom .op import annotation\nfrom .op import vision\nfrom .op import contrib\nfrom .op import dyn\nfrom .op import random\nfrom .op.reduce import *\nfrom .op.tensor import *\nfrom .op.transform import *\nfrom .op.algorithm import *\nfrom . import frontend\nfrom . import backend\nfrom . import quantize\nfrom . import data_dep_optimization\n\n# Dialects\nfrom . import qnn\n\nfrom .scope_builder import ScopeBuilder\n\n# Load Memory Passes\nfrom .transform import memory_plan\n\n# Required to traverse large programs\nsetrecursionlimit(10000)\n\n# Span\nSpan = base.Span\nSourceName = base.SourceName\n\n# Type\nType = ty.Type\nTupleType = ty.TupleType\nTensorType = ty.TensorType\nTypeKind = ty.TypeKind\nTypeVar = ty.TypeVar\nShapeVar = ty.ShapeVar\nTypeConstraint = ty.TypeConstraint\nFuncType = ty.FuncType\nTypeRelation = ty.TypeRelation\nIncompleteType = ty.IncompleteType\nscalar_type = ty.scalar_type\nRefType = ty.RefType\nGlobalTypeVar = ty.GlobalTypeVar\nTypeCall = ty.TypeCall\nAny = ty.Any\n\n# Expr\nExpr = expr.RelayExpr\nConstant = expr.Constant\nTuple = expr.Tuple\nVar = expr.Var\nGlobalVar = expr.GlobalVar\nFunction = function.Function\nCall = expr.Call\nLet = expr.Let\nIf = expr.If\nTupleGetItem = expr.TupleGetItem\nRefCreate = expr.RefCreate\nRefRead = expr.RefRead\nRefWrite = expr.RefWrite\n\n# ADT\nPattern = adt.Pattern\nPatternWildcard = adt.PatternWildcard\nPatternVar = adt.PatternVar\nPatternConstructor = adt.PatternConstructor\nPatternTuple = adt.PatternTuple\nConstructor = adt.Constructor\nTypeData = adt.TypeData\nClause = adt.Clause\nMatch = adt.Match\n\n# helper functions\nvar = expr.var\nconst = expr.const\nbind = expr.bind\n\n# TypeFunctor\nTypeFunctor = type_functor.TypeFunctor\nTypeVisitor = type_functor.TypeVisitor\nTypeMutator = type_functor.TypeMutator\n\n# ExprFunctor\nExprFunctor = expr_functor.ExprFunctor\nExprVisitor = expr_functor.ExprVisitor\nExprMutator = expr_functor.ExprMutator\n\n# Prelude\nPrelude = prelude.Prelude\n\n# Scope Builder\nScopeBuilder = scope_builder.ScopeBuilder\n\n# Param Serialization\nsave_param_dict = param_dict.save_param_dict\nload_param_dict = param_dict.load_param_dict\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/_build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable\n\"\"\"The interface for building Relay functions exposed from C++.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.build_module\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for Relay program IR.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.ir\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe constructors for all Relay AST nodes exposed from C++.\n\nThis module includes MyPy type signatures for all of the\nexposed modules.\n\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/adt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, unused-import\n\"\"\"Algebraic data types in Relay.\"\"\"\nfrom tvm.ir import Constructor, TypeData\nfrom tvm.runtime import Object\nimport tvm._ffi\n\nfrom .base import RelayNode\nfrom . import _ffi_api\nfrom .ty import Type\nfrom .expr import ExprWithOp, RelayExpr, Call\n\n\nclass Pattern(RelayNode):\n    \"\"\"Base type for pattern matching constructs.\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.PatternWildcard\")\nclass PatternWildcard(Pattern):\n    \"\"\"Wildcard pattern in Relay: Matches any ADT and binds nothing.\"\"\"\n\n    def __init__(self):\n        \"\"\"Constructs a wildcard pattern.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        wildcard: PatternWildcard\n            a wildcard pattern.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.PatternWildcard)\n\n\n@tvm._ffi.register_object(\"relay.PatternVar\")\nclass PatternVar(Pattern):\n    \"\"\"Variable pattern in Relay: Matches anything and binds it to the variable.\"\"\"\n\n    def __init__(self, var):\n        \"\"\"Construct a variable pattern.\n\n        Parameters\n        ----------\n        var: tvm.relay.Var\n\n        Returns\n        -------\n        pv: PatternVar\n            A variable pattern.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.PatternVar, var)\n\n\n@tvm._ffi.register_object(\"relay.PatternConstructor\")\nclass PatternConstructor(Pattern):\n    \"\"\"Constructor pattern in Relay: Matches an ADT of the given constructor, binds recursively.\"\"\"\n\n    def __init__(self, constructor, patterns=None):\n        \"\"\"Construct a constructor pattern.\n\n        Parameters\n        ----------\n        constructor: Constructor\n            The constructor.\n        patterns: Optional[List[Pattern]]\n            Optional subpatterns: for each field of the constructor,\n            match to the given subpattern (treated as a variable pattern by default).\n\n        Returns\n        -------\n        wildcard: PatternWildcard\n            a wildcard pattern.\n        \"\"\"\n        if patterns is None:\n            patterns = []\n        self.__init_handle_by_constructor__(_ffi_api.PatternConstructor, constructor, patterns)\n\n\n@tvm._ffi.register_object(\"relay.PatternTuple\")\nclass PatternTuple(Pattern):\n    \"\"\"Constructor pattern in Relay: Matches a tuple, binds recursively.\"\"\"\n\n    def __init__(self, patterns=None):\n        \"\"\"Construct a tuple pattern.\n\n        Parameters\n        ----------\n        patterns: Optional[List[Pattern]]\n            Optional subpatterns: for each field of the constructor,\n            match to the given subpattern (treated as a variable pattern by default).\n\n        Returns\n        -------\n        wildcard: PatternWildcard\n            a wildcard pattern.\n        \"\"\"\n        if patterns is None:\n            patterns = []\n        self.__init_handle_by_constructor__(_ffi_api.PatternTuple, patterns)\n\n\n@tvm._ffi.register_object(\"relay.Clause\")\nclass Clause(Object):\n    \"\"\"Clause for pattern matching in Relay.\"\"\"\n\n    def __init__(self, lhs, rhs):\n        \"\"\"Construct a clause.\n\n        Parameters\n        ----------\n        lhs: tvm.relay.Pattern\n            Left-hand side of match clause.\n        rhs: tvm.relay.Expr\n            Right-hand side of match clause.\n\n        Returns\n        -------\n        clause: Clause\n            The Clause.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.Clause, lhs, rhs)\n\n\n@tvm._ffi.register_object(\"relay.Match\")\nclass Match(ExprWithOp):\n    \"\"\"Pattern matching expression in Relay.\"\"\"\n\n    def __init__(self, data, clauses, complete=True):\n        \"\"\"Construct a Match.\n\n        Parameters\n        ----------\n        data: tvm.relay.Expr\n            The value being deconstructed and matched.\n\n        clauses: List[tvm.relay.Clause]\n            The pattern match clauses.\n\n        complete: Optional[Bool]\n            Should the match be complete (cover all cases)?\n            If yes, the type checker will generate an error if there are any missing cases.\n\n        Returns\n        -------\n        match: tvm.relay.Expr\n            The match expression.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.Match, data, clauses, complete)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay IR namespace containing the analysis passes.\"\"\"\n# Analysis passes\nfrom .analysis import *\n\n# Annotations\nfrom .annotated_regions import AnnotatedRegionSet\n\n# Call graph\nfrom . import call_graph\nfrom .call_graph import CallGraph\n\n# Feature\nfrom . import feature\nfrom . import sparse_dense\nfrom . import sparse_conv2d\n\n# Utilities\nfrom .count_layers import count_layers\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for Relay program analysis.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.analysis\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/analysis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return\n# pylint: disable=unidiomatic-typecheck\n\"\"\"\nThis file contains the set of passes for Relay, which exposes an interface for\nconfiguring the passes and scripting them in Python.\n\"\"\"\nfrom ...ir import IRModule\nfrom ...relay import transform, build_module\nfrom ...runtime.ndarray import cpu\n\nfrom . import _ffi_api\nfrom .feature import Feature\n\n\ndef post_order_visit(expr, fvisit):\n    \"\"\"Recursively visit the ir in post DFS order node,\n    apply fvisit. Each node is guaranteed to be visited\n    only once.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression.\n\n    fvisit : function\n        The visitor function to be applied.\n    \"\"\"\n    return _ffi_api.post_order_visit(expr, fvisit)\n\n\ndef well_formed(expr):\n    \"\"\"Check that each Var is only bound once (well formed).\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    well_form : bool\n        Whether the input expression is well formed\n    \"\"\"\n    return _ffi_api.well_formed(expr)\n\n\ndef check_kind(t, mod=None):\n    \"\"\"Check that the type is well kinded and return the kind.\n    For example, this mean type cannot has tensor of tensor, or is a tuple type\n    of 2 shapes.\n\n    Parameters\n    ----------\n    t : tvm.relay.Type\n        The type to check\n\n    mod : Optional[tvm.IRModule]\n        The global module.\n\n    Returns\n    -------\n    kind : Kind\n        the kind of t\n\n    Examples\n    --------\n    .. code:: python\n\n        assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Shape)])) == Shape\n        assert check_kind(relay.TupleType([relay.TypeParam('tp1', relay.Kind.Type)])) == Type\n    \"\"\"\n    if mod is not None:\n        return _ffi_api.check_kind(t, mod)\n    else:\n        return _ffi_api.check_kind(t)\n\n\ndef check_constant(expr):\n    \"\"\"Check whether an expression is constant\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    result : bool\n        Whether the expression is constant.\n    \"\"\"\n    return _ffi_api.check_constant(expr)\n\n\ndef check_basic_block_normal_form(expr):\n    \"\"\"Check whether an expression is in the basic block form\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    result : bool\n        Whether the expression is in the basic block form.\n    \"\"\"\n    return _ffi_api.check_basic_block_normal_form(expr)\n\n\ndef free_vars(expr):\n    \"\"\"Get free Vars from expression expr in Post DFS order.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    free : List[tvm.relay.Var]\n        The list of free variables in post DFS order.\n\n    Note\n    ----\n    The fact that Vars are post-DFS ordred are useful in\n    neural networks: usually this means weights of previous\n    are ordered first.\n    \"\"\"\n    return _ffi_api.free_vars(expr)\n\n\ndef bound_vars(expr):\n    \"\"\"Get bound vars from expression expr in post-DFS order.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    free : List[tvm.relay.Var]\n        The list of bound variables in post-DFS order.\n    \"\"\"\n    return _ffi_api.bound_vars(expr)\n\n\ndef all_vars(expr):\n    \"\"\"Get all vars from expression expr in post-DFS order.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    free : List[tvm.relay.Var]\n        The list of all variables in post-DFS order.\n    \"\"\"\n    return _ffi_api.all_vars(expr)\n\n\ndef free_type_vars(expr, mod=None):\n    \"\"\"Get free type variables from expression/type e\n\n    Parameters\n    ----------\n    expr : Union[tvm.relay.Expr,tvm.relay.Type]\n        The input expression/type\n\n    mod : Optional[tvm.IRModule]\n        The global module\n\n    Returns\n    -------\n    free : List[tvm.relay.TypeVar]\n        The list of free type variables in post-DFS order\n    \"\"\"\n    use_mod = mod if mod is not None else IRModule()\n    return _ffi_api.free_type_vars(expr, use_mod)\n\n\ndef bound_type_vars(expr, mod=None):\n    \"\"\"Get bound type variables from expression/type e\n\n    Parameters\n    ----------\n    expr : Union[tvm.relay.Expr,tvm.relay.Type]\n        The input expression/type\n\n    mod : Optional[tvm.IRModule]\n        The global module\n\n    Returns\n    -------\n    free : List[tvm.relay.TypeVar]\n        The list of bound type variables in post-DFS order\n    \"\"\"\n    use_mod = mod if mod is not None else IRModule()\n    return _ffi_api.bound_type_vars(expr, use_mod)\n\n\ndef all_type_vars(expr, mod=None):\n    \"\"\"Get all type variables from expression/type e\n\n    Parameters\n    ----------\n    expr : Union[tvm.relay.Expr,tvm.relay.Type]\n        The input expression/type\n\n    mod : Optional[tvm.IRModule]\n        The global module\n\n    Returns\n    -------\n    free : List[tvm.relay.TypeVar]\n        The list of all type variables in post-DFS order\n    \"\"\"\n    use_mod = mod if mod is not None else IRModule()\n    return _ffi_api.all_type_vars(expr, use_mod)\n\n\ndef all_dtypes(expr):\n    \"\"\"Collect set of all data types used in `expr`.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression\n\n    Returns\n    -------\n    ret : Set[String]\n        Set of data types used in the expression (e.g., `{'int8', 'int32'}`)\n    \"\"\"\n    return set(_ffi_api.all_dtypes(expr))\n\n\ndef get_total_mac_number(expr):\n    \"\"\"\n    Count the number of MACs (multiply-accumulate) of a model\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression.\n\n    Returns\n    -------\n    result : int64\n      The number of MACs (multiply-accumulate) of a model\n    \"\"\"\n    return _ffi_api.GetTotalMacNumber(expr)\n\n\ndef unmatched_cases(match, mod=None):\n    \"\"\"\n    Finds cases that the match expression does not catch, if any.\n\n    Parameters\n    ----------\n    match : tvm.relay.Match\n        The match expression\n\n    mod : Optional[tvm.IRModule]\n        The module (defaults to an empty module)\n\n    Returns\n    -------\n    missing_patterns : [tvm.relay.Pattern]\n        Patterns that the match expression does not catch.\n    \"\"\"\n    return _ffi_api.unmatched_cases(match, mod)\n\n\ndef detect_feature(a, b=None):\n    \"\"\"\n    Detect the feature used in a relay program.\n\n    Parameters\n    ----------\n    a : Union[tvm.relay.Expr, tvm.IRModule]\n      The input expression or module.\n\n    b : Optional[Union[tvm.relay.Expr, tvm.IRModule]]\n      The input expression or module.\n      The two arguments cannot both be expression or module.\n\n    Returns\n    -------\n    features : Set[Feature]\n      Features used in the program.\n    \"\"\"\n    if isinstance(a, IRModule):\n        a, b = b, a\n    return {Feature(int(x)) for x in _ffi_api.detect_feature(a, b)}\n\n\ndef extract_fused_functions(mod):\n    \"\"\"Pass to extract IRModule of only fused primitive functions.\n\n    The ExtractFusedFunctions pass invokes SimplifyInference, FuseOps(3),\n    and ExtractFusedFunctions in that order\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n\n    Returns\n    -------\n    ret : Dict[int, tvm.relay.function.Function]\n        A module containing only fused primitive functions\n    \"\"\"\n    ret_mod = _ffi_api.ExtractFusedFunctions()(mod)\n    ret = {}\n    for hash_, func in ret_mod.functions.items():\n        ret[hash_] = func\n    return ret\n\n\ndef list_op_freqs(mod):\n    \"\"\"Pass to extract unique operator names and how frequently they appear\n    in an IRModule. Fused functions are traversed to count the operators\n    that compose them.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n\n    Returns\n    -------\n    ret : Dict[str, int]\n        Dict of unique operator names to frequency\n    \"\"\"\n    return _ffi_api.ExtractOperators(mod)\n\n\ndef list_fake_quantized_op_freqs(mod):\n    \"\"\"Pass to extract fake quantized op names and the frequency that they appear\n    in fake quantized regions of an IRModule.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n\n    Returns\n    -------\n    ret : Dict[str, int]\n        Dict of fake quantized operator names to frequency\n    \"\"\"\n    return _ffi_api.ExtractFakeQuantizedOps(mod)\n\n\ndef search_fc_transpose(expr):\n    \"\"\"Search fc weight name in the patten: y = nn.dense(x, transpose(w, [1, 0]))\n\n    This function is used in the data_dep_optimization.simplify_fc_transpose method\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n\n    Returns\n    -------\n    ret : Array[String]\n        Array of weight variable name in pattern y = nn.dense(x, transpose(w, [1, 0]))\n    \"\"\"\n    ret = _ffi_api.search_fc_transpose(expr)\n    return ret\n\n\ndef get_calibration_data(mod, data):\n    \"\"\"Get the calibration data of a given relay graph\n\n    This pass uses the graph executor to get the calibration data of a module, which\n    includes the input and output values of each function. The returned data uses\n    the GlobalVar of each function as a key. Users can further access the inputs and\n    outputs by using `inputs` or  `outputs` as the key.\n\n    Following are some limitations:\n    1. The input module (graph) cannot have control flows.\n    2. The input arguments of each function cannot be tuples (outputs can be tuples).\n    3. We only handle top-level functions (i.e., nested function is not handled).\n    4. We only handle functions with `Compiler` attribute being set.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The input module for collecting the calibration data\n\n    data : Dict[str, NDArray]\n        The input data for running the module\n\n    Returns\n    -------\n    data : Dict[tvm.relay.GlobalVar, Dict[str, NDArray]]\n    \"\"\"\n    output_map = _ffi_api.get_calibrate_output_map(mod)\n\n    mod = _ffi_api.get_calibrate_module(mod)\n    mod = transform.Inline()(mod)\n\n    ref_res = build_module.create_executor(\"graph\", mod=mod, device=cpu(0)).evaluate()(**data)\n\n    calib_data = {}\n    for gvar, indices in output_map.items():\n        offset = int(indices[0])\n        in_len = int(indices[1])\n        out_len = int(indices[2])\n        value = {\n            \"inputs\": ref_res[offset : offset + in_len],\n            \"outputs\": ref_res[offset + in_len : offset + in_len + out_len],\n        }\n        calib_data[gvar] = value\n\n    return calib_data\n\n\ndef extract_intermdeiate_expr(mod, expr_id):\n    \"\"\"Extract Relay Expr by its expression ID\n\n    This function is used for extracting Relay Expr\n    by its expression ID of the main function\n    that we can see in `print(mod[\"main\"])`.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n\n    expr_id : the Expr ID that we want to extract\n\n    Returns\n    -------\n    ret : Extracted IRModule\n\n    Examples\n    --------\n    .. code-block:: python\n\n        # Suppose our module is printed like this:\n        # def @main(%x: Tensor[(1, 1, 5, 1), float32], %w1, %w2) {\n        #   %0 = nn.conv2d(%x, %w1, padding=[1, 1, 1, 1], channels=1, kernel_size=[3, 3]);\n        #   %1 = nn.conv2d(%0, %w2, padding=[1, 1, 1, 1], channels=1, kernel_size=[3, 3]);\n        #   %2 = add(%0, %1);\n        #   %3 = split(%2, indices_or_sections=1);\n        #   %4 = %3.0;\n        #   add(%4, 1f)\n        # }\n        # if we want to extract `%1 = nn.conv2d`\n        from tvm import relay\n\n        relay.analysis.extract_intermdeiate_expr(mod, 1)\n    \"\"\"\n    return _ffi_api.ExtractIntermediateExpr(mod, expr_id)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/annotated_regions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, unused-import\n\"\"\"Regions used in Relay.\"\"\"\n\nfrom ...runtime import Object\nfrom . import _ffi_api\n\n\nclass AnnotatedRegionSet(Object):\n    \"\"\"Class to represent a relay expression split into regions.\"\"\"\n\n    def __init__(self, expr, region_begin_op, region_end_op):\n        \"\"\"Construct regions from an expression.\n\n        Parameters\n        ----------\n        expr : tvm.relay.Expr\n            The expression from which to construct the regions.\n        region_begin_op : tvm.ir.Op\n            The region begin annotation.\n        region_end_op : tvm.ir.Op\n            The region end annotation.\n\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.AnnotatedRegionSet, expr, region_begin_op, region_end_op\n        )\n\n    def __len__(self):\n        return len(self.regions)\n\n    def get_region(self, expr):\n        \"\"\"Get the region an expression belongs to.\n\n        Parameters\n        ----------\n        expr : tvm.relay.Expr\n            The expression.\n\n        Returns\n        -------\n        region\n            The region containing the expression.\n            None if not found.\n        \"\"\"\n        return _ffi_api.GetRegion(self, expr)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/call_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, unused-import\n\"\"\"Call graph used in Relay.\"\"\"\n\nfrom ...ir import IRModule\nfrom ...runtime import Object\nfrom ..expr import GlobalVar\nfrom . import _ffi_api\n\n\nclass CallGraph(Object):\n    \"\"\"Class to represent a call graph.\"\"\"\n\n    def __init__(self, module):\n        \"\"\"Construct a call graph.\n\n        Parameters\n        ----------\n        module : tvm.ir.IRModule\n            The IR module used to create a call graph\n\n        Returns\n        -------\n        call_graph: CallGraph\n            A constructed call graph.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.CallGraph, module)\n\n    @property\n    def module(self):\n        \"\"\"Return the contained Relay IR module.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        ret : tvm.ir.IRModule\n            The contained IRModule\n        \"\"\"\n        return _ffi_api.GetModule(self)\n\n    def ref_count(self, var):\n        \"\"\"Return the number of references to the global var\n\n        Parameters\n        ----------\n        var : Union[String, tvm.relay.GlobalVar]\n\n        Returns\n        -------\n        ret : int\n            The number reference to the global var\n        \"\"\"\n        var = self._get_global_var(var)\n        return _ffi_api.GetRefCountGlobalVar(self, var)\n\n    def global_call_count(self, var):\n        \"\"\"Return the number of global function calls from a given global var.\n\n        Parameters\n        ----------\n        var : Union[String, tvm.relay.GlobalVar]\n\n        Returns\n        -------\n        ret : int\n            The number of global function calls from the given var.\n        \"\"\"\n        var = self._get_global_var(var)\n        return _ffi_api.GetGlobalVarCallCount(self, var)\n\n    def is_recursive(self, var):\n        \"\"\"Return if the function corresponding to a var is a recursive\n        function.\n\n        Parameters\n        ----------\n        var : Union[String, tvm.relay.GlobalVar]\n\n        Returns\n        -------\n        ret : Boolean\n            If the function corresponding to var is recurisve.\n        \"\"\"\n        var = self._get_global_var(var)\n        return _ffi_api.IsRecursive(self, var)\n\n    def _get_global_var(self, var):\n        \"\"\"Return the global var using a given name or GlobalVar.\n\n        Parameters\n        ----------\n        var : Union[String, tvm.relay.GlobalVar]\n\n        Returns\n        -------\n        ret : tvm.relay.GlobalVar\n            The global var.\n        \"\"\"\n        if isinstance(var, str):\n            mod = self.module\n            var = mod.get_global_var(var)\n\n        if isinstance(var, GlobalVar):\n            return var\n        else:\n            raise TypeError(\"var should be either a string or GlobalVar\")\n\n    def print_var(self, var):\n        \"\"\"Print a call graph of a global function by name or by variable.\n\n        Parameters\n        ----------\n        var: Union[String, tvm.relay.GlobalVar]\n            The name or global variable.\n\n        Returns\n        -------\n        ret : String\n            The call graph represented in string.\n        \"\"\"\n        var = self._get_global_var(var)\n        return _ffi_api.PrintCallGraphGlobalVar(self, var)\n\n    def __str__(self):\n        \"\"\"Print the call graph in the topological order.\"\"\"\n        return _ffi_api.PrintCallGraph(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/count_layers.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities that enable counting the number of layers in a graph.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom ..expr_functor import ExprVisitor\n\n\nclass LayerCounter(ExprVisitor):\n    \"\"\"A visitor pass that computes the deepest chain of specified ops in graph.\"\"\"\n\n    def __init__(self, valid_ops):\n        self.depth_count = 0\n        self.deepest_count = 0\n        self.valid_ops = [relay.op.get(op) for op in valid_ops]\n        super().__init__()\n\n    def visit_call(self, call):\n        if call.op in self.valid_ops:\n            self.depth_count += 1\n        current_count = self.depth_count\n        self.deepest_count = max(self.deepest_count, current_count)\n        for arg in call.args:\n            self.visit(arg)\n            self.depth_count = current_count\n\n    def count(self):\n        return self.deepest_count\n\n\ndef count_layers(expr, valid_ops):\n    \"\"\"Determine the number of layers of specified ops in a graph.\n    This pass computes only the deepest chain of ops rather than the\n    total number of ops in a graph. Thus, if there are two parallel\n    convolutions (for example), they would be considered a single layer.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr, tvm.relay.Function, or tvm.ir.IRModule.\n        The input expression.\n\n    valid_ops: List[str]\n        A list of the operations that should be included in the count.\n\n    Returns\n    -------\n    layer_count : int\n        The number of layers of the specified operations found in the graph.\n    \"\"\"\n    if isinstance(expr, tvm.ir.IRModule):\n        expr = expr[\"main\"]\n    count_pass = LayerCounter(valid_ops)\n    count_pass.visit(expr)\n    return count_pass.count()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name\n\"\"\"The type nodes of the Relay language.\"\"\"\nfrom enum import IntEnum\n\n\nclass Feature(IntEnum):\n    \"\"\"The features a program might contain.\"\"\"\n\n    fVar = 0\n    fGlobalVar = 1\n    fConstant = 2\n    fTuple = 3\n    fTupleGetItem = 4\n    fFunction = 5\n    fOp = 6\n    fCall = 7\n    fLet = 8\n    fIf = 9\n    fRefCreate = 10\n    fRefRead = 11\n    fRefWrite = 12\n    fConstructor = 13\n    fMatch = 14\n    \"\"\" Whether any non-atom fragment of the program is shared, making the program a graph. \"\"\"\n    fGraph = 15\n    \"\"\" Whether there is local fixpoint in the program. \"\"\"\n    fLetRec = 16\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/sparse_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return\n# pylint: disable=unidiomatic-typecheck\n\"\"\"\nThis file contains helper functions for convert dense model\nto block sparse model\n\"\"\"\nfrom collections import namedtuple\nimport numpy as np\nimport scipy.sparse as sp\nimport tvm\nfrom . import _ffi_api\n\n\nSparseAnalysisResult = namedtuple(\n    \"SparseAnalysisResult\",\n    [\n        \"weight_name\",\n        \"weight_shape\",\n    ],\n)\n\n\ndef _search_conv2d_op_weight(expr):\n    \"\"\"Search name of weight in all ```nn.conv2d``` operator\n       This is a helpful function to determine which param need\n       to be converted to sparse\n\n    Parameters\n    ----------\n    expr : relay.Expr\n        Expr will be searched\n\n    Returns\n    -------\n    ret : Array[String]\n        name of weight in all ``nn.conv2d``` operator\n    \"\"\"\n    return _ffi_api.search_conv2d_op_weight(expr)\n\n\ndef process_params(\n    expr, params, block_size, sparsity_threshold, layout, kernel_size, reg_task_input=True\n):\n    \"\"\"Process parameters of conv2d from dense to sparse.\n\n    Parameters\n    ----------\n    expr : Relay.Expr\n        Expr of the network\n    params : Dict[String, tvm.nd.array]\n        parameters of the network\n    block_size : Tuple(int, int)\n        Blocksize in BSR matrix\n    sparsity_threshold : float\n        Minimal sparsity requirement for converting to sparse operation\n    layout : str\n        layout of network\n\n    Returns\n    -------\n    ret : Namedtuple[weight_name: Array[String], weight_shape: Array[Array[IntImm]]]\n        return names of qualified conv2d weight and the shape in BSR format\n    \"\"\"\n\n    # pylint: disable=import-outside-toplevel\n    from tvm.auto_scheduler.search_task import (\n        register_task_input_buffer,\n    )  # lazily import to avoid recursive dependency\n\n    memo = SparseAnalysisResult(weight_name=[], weight_shape=[])\n    weight_names = _search_conv2d_op_weight(expr)\n    for name in weight_names:\n        name = str(name)\n        w_np = params[name].numpy()\n\n        if layout == \"NHWC\":  # HWIO\n            weight_kernel = (w_np.shape[0], w_np.shape[1])\n        elif layout == \"NCHW\":  # OIHW\n            weight_kernel = (w_np.shape[2], w_np.shape[3])\n        if weight_kernel[0] != weight_kernel[1]:\n            continue\n\n        if weight_kernel[0] == kernel_size == 1:\n            sparsity = 1.0 - (np.count_nonzero(w_np) / w_np.size)\n            if sparsity < sparsity_threshold:\n                continue\n            if layout == \"NHWC\":\n                w_np = w_np.squeeze().T\n            elif layout == \"NCHW\":\n                w_np = w_np.squeeze()\n\n            sparse_weight = sp.bsr_matrix(w_np, blocksize=block_size)\n\n            # when bs_c=1, remove this dim\n            if block_size[1] == 1:\n                sparse_weight_data = sparse_weight.data.reshape(\n                    sparse_weight.data.shape[0], block_size[0]\n                )\n            else:\n                sparse_weight_data = sparse_weight.data\n        elif weight_kernel[0] == kernel_size == 3:\n            if layout == \"NHWC\":  # HWIO\n                w_np = w_np.reshape((-1, w_np.shape[-1])).T\n            elif layout == \"NCHW\":  # OIHW\n                w_np = w_np.reshape((w_np.shape[0], -1))\n            sparse_weight = sp.bsr_matrix(w_np, blocksize=block_size)\n            if 1 - (sparse_weight.nnz / w_np.size) < sparsity_threshold:\n                continue\n            sparse_weight_data = sparse_weight.data\n        else:\n            continue\n\n        # remove dense weight\n        del params[name]\n        memo.weight_name.append(name)\n        memo.weight_shape.append(\n            list(sparse_weight_data.shape)\n            + list(sparse_weight.indices.shape)\n            + list(sparse_weight.indptr.shape)\n        )\n        params[name + \".data\"] = tvm.nd.array(sparse_weight_data)\n        params[name + \".indices\"] = tvm.nd.array(sparse_weight.indices)\n        params[name + \".indptr\"] = tvm.nd.array(sparse_weight.indptr)\n\n        if reg_task_input:\n            prefix = \"sparse_conv2d_bsr_%d_%d_%d_%d_%d_%d_\" % (\n                w_np.shape[0],\n                w_np.shape[1],\n                block_size[0],\n                block_size[1],\n                sparse_weight.indices.shape[0],\n                sparse_weight.indptr.shape[0],\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_data\",\n                tvm.runtime.ndarray.array(sparse_weight_data),\n                overwrite=True,\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_indices\",\n                tvm.runtime.ndarray.array(sparse_weight.indices),\n                overwrite=True,\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_indptr\",\n                tvm.runtime.ndarray.array(sparse_weight.indptr),\n                overwrite=True,\n            )\n    ret = SparseAnalysisResult(\n        weight_name=tvm.runtime.convert(memo.weight_name),\n        weight_shape=tvm.runtime.convert(memo.weight_shape),\n    )\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/analysis/sparse_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return\n# pylint: disable=unidiomatic-typecheck\n\"\"\"\nThis file contains helper functions for convert dense model\nto block sparse model\n\"\"\"\nfrom collections import namedtuple\nimport numpy as np\nimport scipy.sparse as sp\nimport tvm\nfrom . import _ffi_api\n\n\nSparseAnalysisResult = namedtuple(\n    \"SparseAnalysisResult\",\n    [\n        \"weight_name\",\n        \"weight_shape\",\n    ],\n)\n\n\ndef _search_dense_op_weight(expr):\n    \"\"\"Search name of weight in all ```nn.dense``` operator\n       This is a helpful function to determine which param need\n       to be converted to sparse\n\n    Parameters\n    ----------\n    expr : relay.Expr\n        Expr will be searched\n\n    Returns\n    -------\n    ret : Array[String]\n        name of weight in all ``nn.dense``` operator\n    \"\"\"\n    return _ffi_api.search_dense_op_weight(expr)\n\n\ndef process_params(expr, params, block_size, sparsity_threshold):\n    \"\"\"[summary]\n\n    Parameters\n    ----------\n    expr : Relay.Expr\n        Expr of the network\n    params : Dict[String, tvm.nd.array]\n        parameters of the network\n    block_size : Tuple(int, int)\n        Blocksize in BSR matrix\n    sparsity_threshold : float\n        Minimal sparsity requirement for converting to sparse operation\n\n    Returns\n    -------\n    ret : Namedtuple[weight_name: Array[String], weight_shape: Array[Array[IntImm]]]\n        return names of qualified dense weight and the shape in BSR format\n    \"\"\"\n\n    # pylint: disable=import-outside-toplevel\n    from tvm.auto_scheduler.search_task import (\n        register_task_input_buffer,\n    )  # lazily import to avoid recursive dependency\n\n    memo = SparseAnalysisResult(weight_name=[], weight_shape=[])\n    weight_names = _search_dense_op_weight(expr)\n    for name in weight_names:\n        name = str(name)\n        w_np = params[name].numpy()\n        sparsity = 1.0 - (np.count_nonzero(w_np) / w_np.size)\n        if sparsity >= sparsity_threshold:\n            sparse_weight = sp.bsr_matrix(w_np, blocksize=block_size)\n            # remove dense weight\n            del params[name]\n            memo.weight_name.append(name)\n            memo.weight_shape.append(\n                list(sparse_weight.data.shape)\n                + list(sparse_weight.indices.shape)\n                + list(sparse_weight.indptr.shape)\n            )\n            params[name + \".data\"] = tvm.nd.array(sparse_weight.data)\n            params[name + \".indices\"] = tvm.nd.array(sparse_weight.indices)\n            params[name + \".indptr\"] = tvm.nd.array(sparse_weight.indptr)\n\n            prefix = \"sparse_dense_bsr_%d_%d_%d_%d_%d_%d_\" % (\n                w_np.shape[0],\n                w_np.shape[1],\n                block_size[0],\n                block_size[1],\n                sparse_weight.indices.shape[0],\n                sparse_weight.indptr.shape[0],\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_data\",\n                tvm.runtime.ndarray.array(sparse_weight.data),\n                overwrite=True,\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_indices\",\n                tvm.runtime.ndarray.array(sparse_weight.indices),\n                overwrite=True,\n            )\n            register_task_input_buffer(\n                \"default\",\n                prefix + \"W_indptr\",\n                tvm.runtime.ndarray.array(sparse_weight.indptr),\n                overwrite=True,\n            )\n    ret = SparseAnalysisResult(\n        weight_name=tvm.runtime.convert(memo.weight_name),\n        weight_shape=tvm.runtime.convert(memo.weight_shape),\n    )\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend codegen modules for relay.\"\"\"\nfrom . import te_compiler\nfrom .executor import Executor\nfrom .runtime import Runtime\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/_aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The AOT FFI namespace.\n\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.backend.aot\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/_backend.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The interface of expr function exposed from C++.\"\"\"\nimport tvm._ffi\nimport tvm.driver\n\n\n@tvm._ffi.register_func(\"relay.backend.build\")\ndef build(mod, target, target_host=None):\n    \"\"\"Backend build function.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule or Dict[str, tvm.IRModule]\n        Input module\n\n    target : tvm.Target\n        The target to run the code on.\n\n    target_host : tvm.Target\n        The host target.\n\n    Returns\n    -------\n    module : tvm.Module\n        The runtime module.\n    \"\"\"\n    target_host = None if target_host == \"\" else target_host\n    return tvm.driver.build(mod, target=target, target_host=target_host)\n\n\n@tvm._ffi.register_func(\"relay._tensor_value_repr\")\ndef _tensor_value_repr(tvalue):\n    return str(tvalue.data.numpy())\n\n\n@tvm._ffi.register_func(\"relay._constant_repr\")\ndef _tensor_constant_repr(tvalue):\n    dtype = tvm.runtime.DataType(tvalue.data.dtype)\n    if tvm.target.datatype.get_type_registered(dtype.type_code):\n        return \"custom tensor of type \" + dtype.type_code\n    return str(tvalue.data.numpy())\n\n\ntvm._ffi._init_api(\"relay.backend\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/_vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The Relay virtual machine FFI namespace.\n\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay._vm\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"AOT passes\"\"\"\nfrom typing import Dict\n\nfrom tvm import IRModule\nfrom tvm.relay.backend import Executor\nfrom tvm.ir.transform import Pass\nfrom .utils import CallType\n\nfrom . import _aot\n\n\ndef AOTLowerMain(mod_name: str, config: object, call_type: CallType) -> Pass:\n    \"\"\"Lower a Relay main function into an AOT TIR main function.\n\n    Parameters\n    ----------\n    mod_name: str\n        The name of the module.\n    config : CompilationConfig\n        The compilation configuration.\n    call_type : CallType\n        The calling convention to use.\n\n    Returns\n    -------\n    Pass\n        The AOTLowerMain pass.\n\n    \"\"\"\n    return _aot.AOTLowerMain(mod_name, config, call_type.value)\n\n\ndef CreateFunctionMetadata(\n    mod: IRModule, workspace_byte_alignment: int, constant_byte_alignment: int\n) -> Dict[str, object]:\n    \"\"\"Create the function metadata (FunctionInfos) from an AOT module.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The IRModule.\n    workspace_byte_alignment : int\n        The alignment of the workspace buffer in bytes.\n    constant_byte_alignment : int\n        The alignment of the constant buffer in bytes.\n\n    Returns\n    -------\n    Dict[str, FunctionInfo]\n        A map between function names and FunctionInfos.\n\n    \"\"\"\n    return _aot.CreateFunctionMetadata(mod, workspace_byte_alignment, constant_byte_alignment)\n\n\ndef CreateExecutorMetadata(\n    mod: IRModule,\n    mod_name: str,\n    executor: Executor,\n    workspace_byte_alignment: int,\n    constant_byte_alignment: int,\n) -> object:\n    \"\"\"Create the executor metadata from an AOT module.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The IRModule.\n    mod_name : str\n        The name of the module.\n    executor : Executor\n        The executor configuration.\n    workspace_byte_alignment : int\n        The alignment of the workspace buffer in bytes.\n    constant_byte_alignment : int\n        The alignment of the constant buffer in bytes.\n\n    Returns\n    -------\n    ExecutorCodegenMetadata\n        The executor metadata.\n\n    \"\"\"\n    return _aot.CreateExecutorMetadata(\n        mod, mod_name, executor, workspace_byte_alignment, constant_byte_alignment\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"External backend codegen modules for Relay.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm(R) Ethos(TM)-U NPU codegen modules for Relay.\"\"\"\nfrom . import util\nfrom . import legalize\nfrom . import preprocess\nfrom . import codegen\nfrom . import vela_api\nfrom . import tir_to_cs_translator\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for relay transformation passes.\"\"\"\nimport tvm._ffi  # type: ignore\n\ntvm._ffi._init_api(\"relay.ext.ethos-u\", __name__)\ntvm._ffi._init_api(\"tir.contrib.ethos-u\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Codegen for Arm(R) Ethos(TM)-U NPU\"\"\"\nfrom collections import defaultdict\n\nfrom typing import List, Callable\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import LowerToTIR\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import copy_constants\nfrom tvm.contrib.ethosu.cascader import (\n    cascade,\n    EthosuDeviceConfig,\n    CascaderOptions,\n    MemoryRegion,\n    extract_memory_info,\n)\nfrom tvm.relay.backend.contrib.ethosu.legalize import LegalizeEthosU\nfrom tvm.relay.backend.contrib.ethosu import tir_to_cs_translator, util\nfrom tvm.relay.expr_functor import ExprMutator, ExprVisitor\n\n# pylint: disable=unused-import\nfrom tvm.relay.backend.contrib.ethosu.op import op_attrs\nfrom tvm.relay.backend.contrib.ethosu import op\n\nfrom . import _ffi_api\n\n\nclass OptimizeLUTs(ExprMutator):\n    \"\"\"A pass to merge an identity operator with a LUT based activation function with\n    a preceding operator provided that operator can do a table lookup for the activation\n    in the hardware\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.lut_ops = {\n            \"contrib.ethosu.conv2d\": op.ethosu_conv2d,\n            \"contrib.ethosu.depthwise_conv2d\": op.ethosu_depthwise_conv2d,\n            \"contrib.ethosu.pooling\": op.ethosu_pooling,\n        }\n\n    def create_op_with_lut(self, call):\n        \"\"\"Extract the parameters and attributes from the NPU operator and create\n        a new operator with LUT.\n\n        Parameters\n        ----------\n        call : tvm.relay.expr.Call\n            The current call node being visited.\n\n        Returns\n        -------\n        tvm.relay.expr.Call\n            The new operator with LUT.\n        \"\"\"\n        identity = call\n        ethosu_op = call.args[0]\n        lut = identity.args[1]\n        activation = identity.attrs.activation\n\n        new_attrs = dict(ethosu_op.attrs)\n        new_attrs[\"activation\"] = activation\n\n        # Assume that LUT is always the last argument\n        new_args = ethosu_op.args[:-1] + [lut]\n        assert ethosu_op.op.name in self.lut_ops.keys()\n\n        return self.lut_ops[ethosu_op.op.name](*new_args, **new_attrs)\n\n    def visit_call(self, call: tvm.relay.expr.Call) -> tvm.relay.expr.Call:\n        \"\"\"Recursively visit call nodes in the input graph and if an ethosu.identity\n        operator with LUT is found and the preceding operator has a LUT attribute, create\n        a new NPU operator.\n\n        Parameters\n        ----------\n        call : tvm.relay.expr.Call\n            The current call node being visited.\n\n        Returns\n        -------\n        tvm.relay.expr.Call\n            The input call node in the case the current call node does\n            not refer to an Op. Else, a new call node with a new operator.\n        \"\"\"\n        new_call = call\n        lut_activations = [\"TANH\", \"LUT\", \"SIGMOID\"]\n\n        if isinstance(call.op, tvm.ir.Op) and isinstance(call.args[0], tvm.relay.expr.Call):\n            producer_op = call.args[0]\n            # Check if the producer can do a LUT operation\n            if (\n                producer_op.op.name in self.lut_ops.keys()\n                and call.op.name == \"contrib.ethosu.identity\"\n                and call.attrs.activation in lut_activations\n            ):\n                # Check the producer doesn't already have a LUT\n                has_lut = producer_op.attrs.activation in lut_activations\n                if not has_lut:\n                    new_call = self.create_op_with_lut(call)\n\n        new_call = super().visit_call(new_call)\n\n        return new_call\n\n\n@util.create_npu_function_pass(opt_level=1)\nclass LUTsOptimizer:\n    \"\"\"Register LUTsOptimizer as a relay pass.\"\"\"\n\n    def transform_npu_function(self, _, func: relay.Function) -> relay.Function:\n        \"\"\"Visit relay nodes in the given NPU function.\n\n        Parameters\n        ----------\n        func : tvm.relay.function.Function\n            The function to apply the optimization pass for multiple LUTs to.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            New module with optimized LUTs.\n        \"\"\"\n        return OptimizeLUTs().visit(func)\n\n    def __call__(self, *args, **kwargs):\n        pass\n\n\nclass AnalyzeConsumers(ExprVisitor):\n    \"\"\"Traverses the graph to determine consumers that are NPU operations. The\n    result is maintained in `npu_consumers`.\n\n    Attributes\n    ----------\n    npu_consumers : Dict[tvm.relay.expr.Call, List[bool]]\n        Mapping from NPU operation to list of boolean values that represent\n        whether or not each consumer is an NPU operation.\n    optimize_ops : Dict[str, Callable]\n        A map from NPU operation name to function that creates NPU operation.\n    \"\"\"\n\n    def __init__(self, optimize_ops):\n        self.npu_consumers = defaultdict(list)\n        self.optimize_ops = optimize_ops\n        super().__init__()\n\n    def visit_call(self, call: relay.Call):\n        is_npu_consumer = call.op.name in self.optimize_ops\n        args = []\n\n        # Expand tuples\n        for arg in call.args:\n            if isinstance(arg, relay.Tuple):\n                args.extend(arg.fields)\n            else:\n                args.append(arg)\n\n        for arg in args:\n            if isinstance(arg, relay.Call) and arg.op.name in self.optimize_ops:\n                self.npu_consumers[arg].append(is_npu_consumer)\n\n        super().visit_call(call)\n\n\nclass LayoutOptimization(ExprMutator):\n    \"\"\"A pass to optimize the layout of NPU operations by converting to brick format (NHCWB16).\n    This pass traverses the graph and attempts to alter the input/output layouts when an NPU\n    operation is visited. Whether or not the input/output layout can be altered for a given NPU\n    operation depends on the following:\n\n    Check alter input layout: For each argument, if the producer is also an NPU operation and\n        its output is altered to brick format, then the input layout with respect to the current\n        argument is altered to brick format.\n\n    Check alter output layout: If all consumers (child nodes) are an NPU operation, then the\n        output layout is altered to brick format.\n\n    Note\n    ----\n    In order for this pass to be run, the consumers of each NPU operation must first be analyzed\n    by the `AnalyzeConsumers` pass, since Relay doesn't keep a reference to child nodes.\n\n    Attributes\n    ----------\n    npu_consumers : Dict[tvm.relay.expr.Call, bool]\n        A map from current call to a list boolean values that state whether or not each consumer\n        is an NPU operation.\n    optimize_ops : Dict[str, Callable]\n        A map from NPU operation name to function that creates NPU operation.\n    \"\"\"\n\n    def __init__(self, npu_consumers, optimize_ops):\n        self.npu_consumers = npu_consumers\n        self.optimize_ops = optimize_ops\n        super().__init__()\n\n    def alter_ethosu_op_layout(self, call: tvm.relay.expr.Call) -> tvm.relay.expr.Call:\n        \"\"\"Alter the layouts of given NPU operation to brick format if possible.\n\n        Parameters\n        ----------\n        call : tvm.relay.expr.Call\n            The call pointing to an NPU operation that will be checked if\n            the layout needs altering.\n\n        Returns\n        -------\n        new_call : tvm.relay.expr.Call\n            New call with altered layouts.\n        \"\"\"\n        assert isinstance(call.attrs, tvm.ir.Attrs), (\n            f\"The attributes for operator '{call.op.name}' could not be \"\n            \"found. Did you register the relay.attrs.Ethosu<opname>Attrs \"\n            \"object in python api?\"\n        )\n\n        new_attrs = dict(call.attrs)\n\n        # Check if we can rewrite the input layouts\n        input_count = 0\n        for arg in call.args:\n            input_count += 1\n            if arg not in self.npu_consumers:\n                continue\n            consumers = self.npu_consumers[arg]\n            parent_has_brick_output = consumers and all(consumers)\n            if parent_has_brick_output:\n                layout_string = \"ifm_layout\" if input_count <= 1 else f\"ifm{input_count}_layout\"\n                new_attrs[layout_string] = \"NHCWB16\"\n\n        # Check if we can rewrite the output layouts\n        consumers = self.npu_consumers[call]\n        if consumers and all(consumers):\n            new_attrs[\"ofm_layout\"] = \"NHCWB16\"\n\n        name = call.op.name\n        return self.optimize_ops[name](*call.args, **new_attrs)\n\n    def visit_call(self, call: tvm.relay.expr.Call) -> tvm.relay.expr.Call:\n        \"\"\"Recursively visit call nodes in the input graph and alter the\n        layout of an op if needed.\n\n        Parameters\n        ----------\n        call : tvm.relay.expr.Call\n            The current call node being visited.\n\n        Returns\n        -------\n        tvm.relay.expr.Call\n            The input call node in the case the current call node does\n            not refer to an Op. Else, a new call node with altered Op\n            attributes.\n        \"\"\"\n        if isinstance(call.op, tvm.ir.Op) and call.op.name in self.optimize_ops:\n            call = self.alter_ethosu_op_layout(call)\n        return super().visit_call(call)\n\n\n@util.create_npu_function_pass(opt_level=1)\nclass LayoutOptimizer:\n    \"\"\"Register LayoutOptimizer as a Relay pass.\"\"\"\n\n    def transform_npu_function(self, _, func: relay.Function) -> relay.Function:\n        \"\"\"A pass to optimize the layout of NPU operations. If both the\n        producer and consumer of a tensor are NPU operators, then the\n        layout is converted from NHWC to NHCWB16 as this is the layout NPU\n        uses internally.\"\"\"\n\n        optimize_ops = {\n            \"contrib.ethosu.conv2d\": op.ethosu_conv2d,\n            \"contrib.ethosu.depthwise_conv2d\": op.ethosu_depthwise_conv2d,\n            \"contrib.ethosu.pooling\": op.ethosu_pooling,\n            \"contrib.ethosu.binary_elementwise\": op.ethosu_binary_elementwise,\n            \"contrib.ethosu.unary_elementwise\": op.ethosu_unary_elementwise,\n        }\n\n        analyze = AnalyzeConsumers(optimize_ops)\n        analyze.visit(func)\n        return LayoutOptimization(analyze.npu_consumers, optimize_ops).visit(func)\n\n    def __call__(self, *args, **kwargs):\n        pass\n\n\ndef IdentityOptimizer():  # pylint: disable=invalid-name\n    \"\"\"Pass that removes redundant identities\n\n    Return\n    ------\n    Pass\n        The module pass.\n    \"\"\"\n    return _ffi_api.IdentityOptimizer()\n\n\ndef OutlineCompilerFunctions(compiler_name):  # pylint: disable=invalid-name\n    \"\"\"Pass that outlines functions given a named Compiler attribute.\n\n    Parameters\n    ----------\n    compiler_name\n        The name of the compiler to look for and outline.\n\n    Return\n    ------\n    Pass\n        The module pass.\n    \"\"\"\n    return _ffi_api.OutlineCompilerFunctions(compiler_name)\n\n\n@tvm._ffi.register_func(\"relay.ext.ethos-u.constant_updater\")\ndef constant_updater(expr, symbol):  # pylint: disable=unused-argument\n    \"\"\"\n    The constant updater process happen after lowering in the core compiler.\n    For the NPU, we dont want the build process to extract constants to be loaded in\n    the runtime as we are embedding them inside the C runtime.Module.\n    \"\"\"\n    return dict()\n\n\ndef _create_cascader(\n    options: CascaderOptions,\n    io_region: MemoryRegion,\n    constant_region: MemoryRegion,\n    working_regions: List[MemoryRegion],\n    device_config: EthosuDeviceConfig,\n) -> Callable:\n    def _cascader(te_graph, const_dict, sch):\n        cascade(\n            sch,\n            te_graph,\n            const_dict,\n            options,\n            io_region,\n            constant_region,\n            working_regions,\n            device_config,\n        )\n\n    return _cascader\n\n\ndef _ethos_u55_cascader(sram, enable_striping) -> Callable:\n    # TODO(ekalda): Extract the flash info from ConstantPools once it is implemented\n    flash = MemoryRegion(name=\"FLASH\", size=10**7, read_bandwidth=4, write_bandwidth=4)\n\n    device_config = EthosuDeviceConfig(util.get_accelerator_config())\n    cascader_options = CascaderOptions(\n        cascade_region=sram,\n        max_proposals=64,\n        stripe_factors=5,\n        max_plan_size=10,\n        always_copy_size=1024,\n        max_open_plans=8,\n        max_closed_plans=32,\n        enable_striping=enable_striping,\n    )\n    return _create_cascader(\n        options=cascader_options,\n        io_region=sram,\n        constant_region=flash,\n        working_regions=[sram],\n        device_config=device_config,\n    )\n\n\ndef _calculate_memory_pressure(mod: tvm.ir.IRModule) -> int:\n    \"\"\"\n    Calculates a worst-case estimate of the memory consumed at the callsite of\n    each microNPU function. This value can be used as a hint to guide the cascader,\n    indicating how aggressively it will need to optimize the input module to fit\n    into the memory that remains in the memory workspace.\n\n    Parameters\n    ----------\n    mod : tvm.ir.IRModule\n        The input module\n\n    Returns\n    -------\n    int\n        Memory pressure value for the module.\n    \"\"\"\n    memory_pressure = 0\n\n    @util.create_npu_function_pass(opt_level=1)\n    class CalculateMemoryPressure:\n        \"\"\"\n        Traverse the module and get total memory used by external NPU functions.\n        \"\"\"\n\n        def transform_npu_function(self, _, func: relay.Function) -> relay.Function:\n            nonlocal memory_pressure\n            max_val = max(func.attrs[\"used_memory\"])\n            memory_pressure += max_val\n            return func\n\n    CalculateMemoryPressure()(mod)  # pylint: disable=not-callable\n\n    io_used_memory = 0\n    if not tvm.tir.usmp.utils.use_workspace_io_is_enabled():\n        io_used_memory = int(mod[\"main\"].attrs[\"io_used_memory\"])\n\n    return memory_pressure - io_used_memory\n\n\n@tvm._ffi.register_func(\"relay.ext.ethos-u.relay_to_tir\")\ndef relay_to_tir(mod: tvm.ir.IRModule) -> tvm.ir.IRModule:\n    \"\"\"\n    This is the hook for python-based lowering of a Relay module which lowers NPU\n    external functions to TIR.\n\n    Parameters\n    ----------\n    mod : tvm.ir.IRModule\n        This is the Relay module.\n\n    Returns\n    -------\n    mod : tvm.ir.IRModule\n        The Relay module with scheduled NPU external functions.\n    \"\"\"\n    mod = OutlineCompilerFunctions(\"ethos-u\")(mod)\n    mod = LegalizeEthosU()(mod)\n    mod = LUTsOptimizer()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = IdentityOptimizer()(mod)\n    mod = LayoutOptimizer()(mod)\n    mod = relay.transform.InferType()(mod)\n\n    device_contexts = {\n        gv: \"ethos-u\" for gv, _ in filter(lambda x: util.is_npu_func(x[1]), mod.functions.items())\n    }\n    mod = mod.with_attr(\"device_contexts\", device_contexts)\n\n    # Use the cascader if it is enabled for the U55 accelerator, otherwise use copy_constants\n    # scheduler\n    if util.is_cascader_enabled():\n        if util.get_accelerator_config() == \"ethos-u65-256\":\n            raise ValueError(\"Cascading is not supported for the U65 accelerator\")\n\n        workspace_memory_pools = mod.attrs[\"workspace_memory_pools\"]\n\n        if not workspace_memory_pools:\n            raise ValueError(\"Workspace memory pool needs to be provided for the U55 cascader\")\n        if len(workspace_memory_pools.pools) != 1:\n            raise ValueError(\"Exactly one workspace pool needs to be provided for the U55 cascader\")\n\n        memory_pressure = _calculate_memory_pressure(mod)\n        sram = extract_memory_info(workspace_memory_pools.pools[0], memory_pressure)\n        tir_mod = LowerToTIR(_ethos_u55_cascader(sram, util.is_striping_enabled()))(mod)\n    else:\n        tir_mod = LowerToTIR(copy_constants())(mod)\n\n    return tir_mod\n\n\n@tvm._ffi.register_func(\"relay.ext.ethos-u.primfunc_to_artifact\")\ndef primfunc_to_artifact(primfunc: tvm.tir.PrimFunc) -> util.CompilationArtifact:\n    \"\"\"\n    This is the hook for python-based lowering of TIR PrimFunc\n    that has undergone unified optimization to compilation\n    artifact destined for the microNPU.\n\n    Parameters\n    ----------\n    primfunc : tir.PrimFunc\n        TIR PrimFunc that has undergone unified optimizations\n\n    Returns\n    -------\n    CompilationArtifact\n        This is a structure that holds the binary artifacts\n        for the microNPU\n    \"\"\"\n    symbol = str(primfunc.attrs[\"global_symbol\"])\n    const_dict = primfunc.attrs[\"ethos-u.constants\"]\n    tir_mod = tvm.IRModule()\n    tir_mod[symbol] = primfunc\n\n    const_dict_np = dict()\n    for buffer_var in const_dict.keys():\n        const_dict_np[buffer_var] = const_dict[buffer_var].numpy()\n\n    cmms, encoded_constants, base_addresses = tir_to_cs_translator.translate(tir_mod, const_dict_np)\n    return util.CompilationArtifact(symbol, cmms, encoded_constants, base_addresses)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/legalize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, import-outside-toplevel, no-value-for-parameter\n\"\"\"A set of passes to legalize some of operations for the NPU\"\"\"\nfrom typing import List, Type, Callable\nimport math\n\nimport numpy as np  # type: ignore\nfrom ethosu.vela import scaling, fp_math\n\nimport tvm  # type: ignore\nfrom tvm import relay\nfrom tvm.relay.dataflow_pattern import DFPatternCallback  # type: ignore\nfrom tvm.relay.dataflow_pattern import wildcard\nfrom tvm.relay.dataflow_pattern import is_op\nfrom tvm.relay.dataflow_pattern import rewrite\nfrom tvm.relay.dataflow_pattern import CallPattern\nfrom tvm.relay.backend.contrib.ethosu import op as ethosu_ops  # type: ignore\nfrom tvm.relay.backend.contrib.ethosu import vela_api\nfrom tvm.relay.backend.contrib.ethosu import util\nfrom tvm.relay.op.contrib import ethosu as ethosu_patterns  # type: ignore\n\n\nclass SplitRewriter(DFPatternCallback):\n    \"\"\"This rewriting converts split operations into a sequence of\n    strided_slice operations, because codegen is going to be based\n    on strided_slices that will define the slice of the tensor that\n    will be fed to the consumer.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.split_in = wildcard()\n        self.pattern = is_op(\"split\")(self.split_in)\n\n    @staticmethod\n    def get_section_begin_coords(split: tvm.relay.Expr) -> List[int]:\n        \"\"\"Currently, the split operator takes an array of indices or an integer\n        indicating the number of splits. However, its an array of indices could\n        represent both cases, therefore this function just make it an array of\n        indices where each index represent the co-ordinate of beginning of each\n        section -- defines as section begins.\n\n        Parameters\n        ----------\n        split : tvm.relay.Expr\n            The Relay Call expression for a split operator\n\n        Returns\n        -------\n        section_begins : List[int]\n            A list containing integers corresponding to section\n            begins\n        \"\"\"\n        indices_or_sections = split.attrs.indices_or_sections\n        input_shape = split.args[0].checked_type.shape\n        split_axis = split.attrs.axis\n\n        if isinstance(indices_or_sections, tvm.ir.container.Array):\n            # 0 is the beginning of the first section.\n            return [0] + list(indices_or_sections)\n        split_axis_len = input_shape[split_axis].value\n        section_length = split_axis_len // indices_or_sections.value\n        return list(range(0, split_axis_len, section_length))\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        split_input = post.args[0]\n        split_begins = list()\n        split_ends = list()\n        section_begins_in_split_axis = self.get_section_begin_coords(post)\n        for split_cord in section_begins_in_split_axis:\n            # first begin is [0, 0, ... , 0]\n            begin_shape = [0 for i in range(len(split_input.checked_type.shape))]\n            begin_shape[post.attrs.axis] = split_cord\n            split_begins.append(begin_shape)\n\n            end_shape = list(split_input.checked_type.shape)\n            # Only the split axis coordinate changes\n            end_shape[post.attrs.axis] = split_cord\n            split_ends.append(end_shape)\n\n        # Coordinates needs to be shifted left because beginning\n        # of the next section is the end of the previous\n        split_ends = split_ends[1:]\n        # Last section end is the shape of the tensor itself.\n        split_ends.append(list(split_input.checked_type.shape))\n\n        strided_slices = list()\n        for sb, se in zip(split_begins, split_ends):\n            strided_slices.append(relay.strided_slice(split_input, sb, se))\n\n        return relay.Tuple(strided_slices)\n\n\nclass PartitionedSplitRewriter(DFPatternCallback):\n    \"\"\"This pass brings the split out of the partitioned function\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.SplitParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        split_input = post.args[0]\n        split_params = ethosu_patterns.SplitParams(post.op.body)\n        indices_or_sections = split_params.indices_or_sections\n        axis = split_params.axis\n        return relay.op.split(split_input, indices_or_sections, axis=axis).astuple()\n\n\ndef get_lut_from_func(\n    ifm_scale: float,\n    ifm_zp: int,\n    ofm_scale: float,\n    ofm_zp: int,\n    func: Callable[[float], float],\n) -> List[int]:\n    \"\"\"Calculates the values of the lookup table based on the calculation function\"\"\"\n\n    lut_values = list()\n    # Only int8 is currently supported\n    dtype = np.int8\n    qmin, qmax = np.iinfo(dtype).min, np.iinfo(dtype).max\n    for x in range(qmin, qmax + 1):\n        x_real = ifm_scale * (x - ifm_zp)\n        out_real = func(x_real)\n        lut_result = int(util.round_away_zero(ofm_zp + out_real / ofm_scale))\n        lut_result = min(qmax, max(qmin, lut_result))\n        lut_values.append(lut_result)\n\n    return lut_values\n\n\nclass LutActivationRewriter(DFPatternCallback):\n    \"\"\"A class to create an identity operator with the LUT\"\"\"\n\n    def __init__(\n        self,\n        params_class: Type,\n        activation_type: str,\n        calc_func: Callable[[float], float],\n    ):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.params_class = params_class\n        self.pattern = (wildcard().has_attr({\"Composite\": params_class.composite_name}))(wildcard())\n        self.activation_type = activation_type\n        self.calc_func = calc_func\n\n    def callback(self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map):\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        input_scale = float(params.ifm.q_params.scale_f32)\n        input_zp = int(params.ifm.q_params.zero_point)\n        output_scale = float(params.ofm.q_params.scale_f32)\n        output_zp = int(params.ofm.q_params.zero_point)\n\n        lut_values = get_lut_from_func(\n            input_scale,\n            input_zp,\n            output_scale,\n            output_zp,\n            self.calc_func,\n        )\n        lut = relay.const(lut_values, dtype=params.ifm.dtype)\n\n        # We baked the requantization into the LUT, so we don't requantize the identity operator\n        identity = ethosu_ops.ethosu_identity(\n            ifm=params.ifm.tensor,\n            lut=lut,\n            ifm_scale=input_scale,\n            ifm_zero_point=input_zp,\n            ofm_scale=input_scale,\n            ofm_zero_point=input_zp,\n            activation=self.activation_type,\n        )\n\n        return identity\n\n\nclass TanhRewriter(LutActivationRewriter):\n    \"\"\"This pass adds tanh as a LUT to the identity operator\"\"\"\n\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.TanhParams, activation_type=\"TANH\", calc_func=math.tanh\n        )\n\n\ndef sigmoid_calc_func(x: float) -> float:\n    \"\"\"Function to calculate the values for sigmoid\"\"\"\n    # These limits are inherited from TFLite\n    upper_limit = 8.0\n    lower_limit = -8.0\n\n    if x <= lower_limit:\n        y = 0.0\n    elif x >= upper_limit:\n        y = 1.0\n    else:\n        y = 1 / (1 + math.exp(-x))\n    return y\n\n\nclass SigmoidRewriter(LutActivationRewriter):\n    \"\"\"This pass adds sigmoid as a LUT for identity op\"\"\"\n\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.SigmoidParams,\n            activation_type=\"SIGMOID\",\n            calc_func=sigmoid_calc_func,\n        )\n\n\ndef leaky_relu_calc_func(x: float, alpha: float) -> float:\n    \"\"\"Function to calculate the values for leaky relu.\"\"\"\n    return x if x >= 0 else x * alpha\n\n\nclass LeakyReLURewriter(DFPatternCallback):\n    \"\"\"This pass adds leaky relu as a LUT for identity op.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.params_class = ethosu_patterns.LeakyReLUParams\n        self.pattern = wildcard().has_attr({\"Composite\": self.params_class.composite_name})(\n            wildcard()\n        )\n\n    def callback(self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map):\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        input_scale = np.double(float(params.ifm.q_params.scale_f32))\n        input_zp = int(params.ifm.q_params.zero_point)\n        output_scale = np.double(float(params.ofm.q_params.scale_f32))\n        output_zp = int(params.ofm.q_params.zero_point)\n\n        alpha = params.alpha\n\n        # The calculation of the LUT values is similar to that in Vela\n        # convert_lrelu_to_lut(op, arch)\n        # (https://review.mlplatform.org/plugins/gitiles/ml/ethos-u/ethos-u-vela/+/refs/tags/3.2.0/ethosu/vela/tflite_graph_optimiser.py#864)  # pylint: disable=line-too-long\n        alpha_scalar = 1\n        alpha_scale, alpha_shift = scaling.elementwise_mul_scale(input_scale, alpha, output_scale)\n        identity_scale, identity_shift = scaling.elementwise_mul_scale(input_scale, 1, output_scale)\n\n        dtype = params.ifm.dtype\n        qmin, qmax = np.iinfo(dtype).min, np.iinfo(dtype).max\n\n        def calculate_lut_value(i):\n            zp_shift = (\n                fp_math.multiply_by_quantized_multiplier(\n                    alpha_scalar * (i - input_zp), alpha_scale, alpha_shift\n                )\n                if i < input_zp\n                else fp_math.multiply_by_quantized_multiplier(\n                    i - input_zp, identity_scale, identity_shift\n                )\n            )\n\n            return min(qmax, max(qmin, output_zp + zp_shift))\n\n        values = list(map(calculate_lut_value, range(qmin, qmax + 1)))\n        lut = relay.const(values, dtype=dtype)\n\n        # We baked the requantization into the LUT, so we don't requantize the identity operator\n        identity = ethosu_ops.ethosu_identity(\n            ifm=params.ifm.tensor,\n            lut=lut,\n            ifm_scale=input_scale,\n            ifm_zero_point=input_zp,\n            ofm_scale=input_scale,\n            ofm_zero_point=input_zp,\n            activation=\"LUT\",\n        )\n\n        return identity\n\n\nclass HardSwishRewriter(DFPatternCallback):\n    \"\"\"Convert ethosu.hard_swish composite function to add operation with LUT.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.params_class = ethosu_patterns.HardSwishParams\n        self.pattern = wildcard().has_attr({\"Composite\": self.params_class.composite_name})(\n            wildcard()\n        )\n\n    def callback(self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map):\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        # The calculation of the LUT values is similar to that in Vela\n        # convert_hardswish_to_lut(op, arch, nng)\n        # (https://review.mlplatform.org/plugins/gitiles/ml/ethos-u/ethos-u-vela/+/refs/tags/3.2.0/ethosu/vela/tflite_graph_optimiser.py#719)  # pylint: disable=line-too-long\n        input_scale = np.double(params.ifm.q_params.scale_f32)\n        input_zp = int(params.ifm.q_params.zero_point)\n        hires_input_scale = (1 / 128) * input_scale\n\n        output_scale = np.double(params.ofm.q_params.scale_f32)\n        output_zp = int(params.ofm.q_params.zero_point)\n        output_scale, output_shift = scaling.quantise_scale(hires_input_scale / output_scale)\n        output_scale_16 = fp_math.downscale_multiplier_int32_to_int16(output_scale)\n        output_shift = 31 - output_shift\n        output_shift = -output_shift if output_shift < 0 else 0\n\n        dtype = params.ifm.dtype\n        qmin, qmax = np.iinfo(dtype).min, np.iinfo(dtype).max\n\n        def calculate_relu_multiplier(inp, input_scale):\n            rmultiplier = np.double(3 / 32768)\n            rscale, rshift = scaling.quantise_scale(input_scale / rmultiplier)\n            rscale_16 = fp_math.downscale_multiplier_int32_to_int16(rscale)\n\n            rvalue = np.int16(inp)\n            if rshift < 31:\n                rvalue = fp_math.shift_left16(rvalue, 30 - rshift)\n                rvalue = fp_math.saturating_rounding_mul16(rvalue, rscale_16)\n                rvalue = fp_math.shift_left16(rvalue, 1)\n            elif rshift > 31:\n                rvalue = fp_math.saturating_rounding_mul16(rvalue, rscale_16)\n                rvalue = fp_math.rounding_divide_by_pot(rvalue, rshift - 31)\n            else:\n                rvalue = fp_math.saturating_rounding_mul16(rvalue, rscale_16)\n\n            rvalue = (rvalue + (1 << 15)) >> 1\n            return rvalue\n\n        def calculate_lut_values(i):\n            hires_input_value = (i - input_zp) * 128\n            preshift_input_value = fp_math.saturating_rounding_mul16(\n                hires_input_value, output_scale_16\n            )\n            relu_value = calculate_relu_multiplier(hires_input_value, hires_input_scale)\n            lut_result = fp_math.saturating_mul16(relu_value, preshift_input_value)\n            lut_result = fp_math.rounding_divide_by_pot(lut_result, output_shift) + output_zp\n            return min(qmax, max(qmin, lut_result))\n\n        values = list(map(calculate_lut_values, range(-128, 128)))\n        lut = relay.const(values, dtype=dtype)\n\n        # We baked the requantization into the LUT, so we don't requantize the identity operator\n        identity = ethosu_ops.ethosu_identity(\n            ifm=params.ifm.tensor,\n            lut=lut,\n            ifm_scale=input_scale,\n            ifm_zero_point=input_zp,\n            ofm_scale=input_scale,\n            ofm_zero_point=input_zp,\n            activation=\"LUT\",\n        )\n\n        return identity\n\n\nclass Conv2DRewriter(DFPatternCallback):\n    \"\"\"Convert conv2d related composite functions into ethosu_conv2d operators\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (wildcard().has_attr({\"Composite\": \"ethos-u.qnn_conv2d\"}))(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.QnnConv2DParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n        channels_map = {\n            \"NHWC\": 3,\n        }\n        kernel_size_map = {\n            \"HWIO\": params.weights.shape[0:2],\n            \"OHWI\": params.weights.shape[1:3],\n            \"HWOI\": params.weights.shape[0:2],\n        }\n        activation_map = {\"clip\": \"CLIP\"}\n        weight_to_ohwi_transform_map = {\"HWIO\": [3, 0, 1, 2]}\n        weights_values = params.weights.values\n        weights_values_ohwi = np.transpose(\n            weights_values, weight_to_ohwi_transform_map[str(params.weights.layout)]\n        )\n        if params.activation:\n            activation = activation_map[params.activation.op.name]\n            clip_min = int(params.activation.attrs.a_min)\n            clip_max = int(params.activation.attrs.a_max)\n        else:\n            activation = \"NONE\"\n            clip_min = 0\n            clip_max = 0\n        scale_bias = vela_api.pack_biases(\n            biases=params.biases.tensor.data.asnumpy(),\n            ifm_scale=params.ifm.q_params.scale_f32,\n            ifm_dtype=np.dtype(params.ifm.dtype),\n            weight_scales=params.weights.q_params.scale_f32,\n            ofm_scale=params.ofm.q_params.scale_f32,\n            is_activation_tanh_or_sigmoid=activation in [\"TANH\", \"SIGMOID\"],\n        )\n        ethosu_conv2d = ethosu_ops.ethosu_conv2d(\n            ifm=post.args[0],\n            weight=relay.const(weights_values_ohwi, params.weights.values.dtype),\n            scale_bias=relay.const(scale_bias, \"uint8\"),\n            lut=relay.const([], dtype=\"int8\"),\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            weight_zero_point=int(params.weights.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            kernel_shape=kernel_size_map[str(params.weights.layout)],\n            ofm_channels=params.ofm.shape[channels_map[str(params.ofm.layout)]],\n            strides=params.strides,\n            padding=params.padding,\n            dilation=params.dilation,\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            upscale=\"NONE\",\n            ifm_layout=str(params.ifm.layout),\n            ofm_layout=str(params.ofm.layout),\n        )\n        return ethosu_conv2d\n\n\nclass Conv2DTransposeRewriter(DFPatternCallback):\n    \"\"\"Convert conv2d_transpose related composite functions into\n    ethosu_conv2d_transpose operators.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (wildcard().has_attr({\"Composite\": \"ethos-u.qnn_conv2d_transpose\"}))(\n            wildcard()\n        )\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.QnnConv2DTransposeParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        ofm_shape = params.ofm.shape\n        legalize_padding = params.legalize_padding\n\n        weight_to_ohwi_transform_map = {\"IOHW\": [1, 2, 3, 0]}\n        weights_values = params.weights.values\n        weights_values_ohwi = np.transpose(\n            weights_values, weight_to_ohwi_transform_map[str(params.weights.layout)]\n        )\n        weights_values_ohwi = np.flip(weights_values_ohwi, (1, 2))\n        weights = relay.const(weights_values_ohwi, dtype=params.weights.values.dtype)\n\n        bias_values = (\n            params.biases.tensor.data.asnumpy()\n            if params.biases\n            else np.zeros((params.ifm.shape[-1]))\n        )\n        scale_bias = vela_api.pack_biases(\n            biases=bias_values,\n            ifm_scale=params.ifm.q_params.scale_f32,\n            ifm_dtype=np.dtype(params.ifm.dtype),\n            weight_scales=params.weights.q_params.scale_f32,\n            ofm_scale=params.ofm.q_params.scale_f32,\n            is_activation_tanh_or_sigmoid=False,\n        )\n\n        reduced_op = ethosu_ops.ethosu_conv2d(\n            ifm=post.args[0],\n            weight=weights,\n            scale_bias=relay.const(scale_bias, \"uint8\"),\n            lut=relay.const([], dtype=\"int8\"),\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            weight_zero_point=int(params.weights.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            kernel_shape=params.kernel_shape,\n            ofm_channels=int(ofm_shape[-1]),\n            strides=(1, 1),\n            padding=legalize_padding,\n            dilation=params.dilation,\n            ifm_layout=str(params.ifm.layout),\n            ofm_layout=str(params.ofm.layout),\n            upscale=\"ZEROS\",\n        )\n\n        # Remove additional padding by 'cropping' back to expected size\n        return relay.strided_slice(reduced_op, (0, 0, 0, 0), ofm_shape)\n\n\nclass DepthwiseConv2DRewriter(DFPatternCallback):\n    \"\"\"Convert ethosu.qnn_depthwise_conv2d composite functions to ethosu_depthwise_conv2d\n    operators\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (\n            wildcard().has_attr(\n                {\"Composite\": ethosu_patterns.QnnDepthwiseConv2DParams.composite_name}\n            )\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.QnnDepthwiseConv2DParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n        channels_map = {\n            \"NHWC\": 3,\n        }\n        kernel_shape_map = {\n            \"HWOI\": params.weights.shape[0:2],\n        }\n\n        weights_values = params.weights.values\n        weights_values_ohwi = np.moveaxis(weights_values, [0, 1, 2, 3], [1, 2, 0, 3])\n\n        activation = \"NONE\"\n        # Activations requiring LUT is currently not supported, so setting it to an empty list\n        lut = relay.const([], \"int8\")\n        clip_min = 0\n        clip_max = 0\n        if params.activation:\n            activation = ethosu_patterns.QnnDepthwiseConv2DParams.activation_map[\n                params.activation.op.name\n            ]\n            if activation == \"CLIP\":\n                clip_min = int(params.activation.attrs.a_min)\n                clip_max = int(params.activation.attrs.a_max)\n        scale_bias = vela_api.pack_biases(\n            biases=params.biases.tensor.data.asnumpy(),\n            ifm_scale=params.ifm.q_params.scale_f32,\n            ifm_dtype=np.dtype(params.ifm.dtype),\n            weight_scales=params.weights.q_params.scale_f32,\n            ofm_scale=params.ofm.q_params.scale_f32,\n            is_activation_tanh_or_sigmoid=activation in [\"TANH\", \"SIGMOID\"],\n        )\n\n        ethosu_depthwise_conv2d = ethosu_ops.ethosu_depthwise_conv2d(\n            post.args[0],  # IFM\n            relay.const(weights_values_ohwi, params.weights.values.dtype),\n            relay.const(scale_bias, \"uint8\"),\n            lut,\n            float(params.ifm.q_params.scale_f32),\n            int(params.ifm.q_params.zero_point),\n            int(params.weights.q_params.zero_point),\n            float(params.ofm.q_params.scale_f32),\n            int(params.ofm.q_params.zero_point),\n            kernel_shape_map[str(params.weights.layout)],\n            params.ofm.shape[channels_map[str(params.ofm.layout)]],\n            strides=params.strides,\n            padding=params.padding,\n            dilation=params.dilation,\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            upscale=\"NONE\",\n            ifm_layout=str(params.ifm.layout),\n            ofm_layout=str(params.ofm.layout),\n            ofm_dtype=str(params.ofm.dtype),\n        )\n        return ethosu_depthwise_conv2d\n\n\nclass PoolingRewriter(DFPatternCallback):\n    \"\"\"Convert ethosu.avgpool2d and ethosu.maxpool2d composite functions to\n    ethosu_pooling operators\"\"\"\n\n    def __init__(\n        self,\n        params_class: Type,\n        pattern: CallPattern,\n    ):\n        super().__init__(require_type=True)\n        self.params_class = params_class\n        self.pattern = pattern\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[0]\n        channels_map = {\n            \"NHWC\": 3,\n        }\n\n        activation_map = {\"clip\": \"CLIP\"}\n        if params.activation:\n            activation = activation_map[params.activation.op.name]\n            clip_min = int(params.activation.attrs.a_min)\n            clip_max = int(params.activation.attrs.a_max)\n        else:\n            activation = \"NONE\"\n            clip_min = 0\n            clip_max = 0\n\n        # Activations requiring LUT is currently not supported, so setting it to an empty list\n        lut = relay.const([], dtype=\"int8\")\n\n        return ethosu_ops.ethosu_pooling(\n            ifm=post.args[0],\n            lut=lut,\n            pooling_type=params.pooling_type,\n            ifm_scale=params.ifm.q_params.scale_f32,\n            ifm_zero_point=params.ifm.q_params.zero_point,\n            ofm_scale=params.ofm.q_params.scale_f32,\n            ofm_zero_point=params.ofm.q_params.zero_point,\n            pool_shape=params.pool_shape,\n            ofm_channels=params.ofm.shape[channels_map[str(params.ofm.layout)]],\n            strides=params.strides,\n            padding=params.padding,\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            upscale=\"NONE\",\n            ifm_layout=str(params.ifm.layout),\n            ofm_layout=str(params.ofm.layout),\n        )\n\n\nclass MaxPoolingRewriter(PoolingRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.MaxPool2DParams,\n            pattern=(\n                wildcard().has_attr({\"Composite\": ethosu_patterns.MaxPool2DParams.composite_name})\n            )(wildcard()),\n        )\n\n\nclass AvgPoolingRewriter(PoolingRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.AvgPool2DParams,\n            pattern=(\n                wildcard().has_attr({\"Composite\": ethosu_patterns.AvgPool2DParams.composite_name})\n            )(wildcard()),\n        )\n\n\nclass BinaryElementwiseRewriter(DFPatternCallback):\n    \"\"\"Convert ethosu binary elementwise composite functions to\n    ethosu_binary_elementwise operators\"\"\"\n\n    def __init__(\n        self,\n        params_class: Type,\n        pattern: CallPattern,\n    ):\n        super().__init__(require_type=True)\n        self.params_class = params_class\n        self.pattern = pattern\n\n    @staticmethod\n    def reshape_input(\n        inputs: List[\"TensorParams\"],\n    ) -> List[tvm.relay.Expr]:\n        \"\"\"Reshape the inputs so that the following binary elementwise\n        operator receives 4-dimensional inputs.\n\n        Parameters\n        ----------\n        inputs: List[TensorParams]\n            The inputs to reshape.\n\n        Returns\n        -------\n        reshaped_inputs: List[tvm.relay.Expr]\n            The new reshaped inputs.\n        \"\"\"\n        reshaped_inputs = []\n        for i in inputs:\n            in_shape = i.shape\n            if len(in_shape) < 4:\n                pad_size = 4 - len(in_shape)\n                new_shape = ([1] * pad_size) + in_shape\n                new_call = relay.reshape(i.tensor, new_shape)\n                reshaped_inputs.append(new_call)\n            else:\n                reshaped_inputs.append(i.tensor)\n        return reshaped_inputs\n\n    @staticmethod\n    def reshape_output(output: tvm.relay.Expr, ifm_input_shape: List[int]) -> tvm.relay.Expr:\n        \"\"\"Reshape the output back to the original dimensionality.\n        Since the NPU must have the brodcastable tensor as the\n        second operand, the original shape of the first ifm must\n        be the output shape.\n\n        Parameters\n        ----------\n        output: tvm.relay.Expr\n            The output to reshape.\n\n        ifm_input_shape: List[int]\n            The shape of the non-reshaped ifm tensor.\n\n        Returns\n        -------\n        reshaped_output: tvm.relay.Expr\n            The reshaped output expression.\n        \"\"\"\n        if len(ifm_input_shape) == 4:\n            return output\n        reshaped_output = relay.reshape(output, ifm_input_shape)\n        return reshaped_output\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[1] if params.reversed_operands else post.args[0]\n        params.ifm2.tensor = post.args[0] if params.reversed_operands else post.args[1]\n\n        activation_map = {\"clip\": \"CLIP\"}\n        if params.activation:\n            activation = activation_map[params.activation.op.name]\n            clip_min = int(params.activation.attrs.a_min)\n            clip_max = int(params.activation.attrs.a_max)\n        else:\n            activation = \"NONE\"\n            clip_min = 0\n            clip_max = 0\n\n        # We don't yet support activation functions that need to get legalized to LUTs.\n        lut = relay.const([], dtype=\"int8\")\n\n        inputs = [params.ifm, params.ifm2]\n        inputs = self.reshape_input(inputs)\n\n        ethosu_binary_elementwise = ethosu_ops.ethosu_binary_elementwise(\n            ifm=inputs[0],\n            ifm2=inputs[1],\n            lut=lut,\n            operator_type=params.operator_type,\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            ifm2_scale=float(params.ifm2.q_params.scale_f32),\n            ifm2_zero_point=int(params.ifm2.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            ifm_channels=params.ifm.shape[-1] if params.ifm.shape else 1,\n            ifm2_channels=params.ifm2.shape[-1] if params.ifm2.shape else 1,\n            reversed_operands=params.reversed_operands,\n            ofm_dtype=params.ofm.dtype,\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            ifm_layout=str(params.ifm.layout),\n            ifm2_layout=str(params.ifm2.layout),\n            ofm_layout=str(params.ofm.layout),\n        )\n        output = self.reshape_output(ethosu_binary_elementwise, params.ifm.shape)\n        return output\n\n\nclass AddRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.AddParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.AddParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass SubRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.SubParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.SubParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass MulRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.MulParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.MulParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass MinRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.MinParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.MinParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass MaxRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.MaxParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.MaxParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass ShlRewriter(BinaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.ShlParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.ShlParams.composite_name}))(\n                wildcard(), wildcard()\n            ),\n        )\n\n\nclass StridedSliceRewriter(DFPatternCallback):\n    \"\"\"This pass brings the strided slice out of the partitioned function\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.StridedSliceParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n\n        slice_input = post.args[0]\n\n        # TODO(lhutton1) For an unknown reason compilation will fail for strides of 4\n        # dimensions, so we cannot use params.strides as this will sometimes give\n        # strides as [1, 1, 1, 1]. Since we only support strides of 1, hardcoding this\n        # value for now.\n        strides = [1]\n\n        params = ethosu_patterns.StridedSliceParams(post.op.body)\n        strided_slice = relay.op.strided_slice(\n            slice_input,\n            params.begin,\n            params.end,\n            strides=strides,\n            axes=params.axes,\n            slice_mode=params.slice_mode,\n        )\n        return strided_slice\n\n\nclass ReshapeRewriter(DFPatternCallback):\n    \"\"\"This pass brings the reshape out of the partitioned function\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.ReshapeParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        reshape_input = post.args[0]\n        reshape_params = ethosu_patterns.ReshapeParams(post.op.body)\n        new_shape = reshape_params.new_shape\n        return relay.op.reshape(reshape_input, newshape=new_shape)\n\n\nclass NoOpRewriter(DFPatternCallback):\n    \"\"\"This pass adds an idenity operator to reshape and strided slice to avoid a no op\n    without a consumer\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.reshape = is_op(\"reshape\")(wildcard())\n        self.strided_slice = is_op(\"strided_slice\")(wildcard())\n        self.pattern = self.reshape | self.strided_slice\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        if pre.checked_type.dtype == \"int32\":\n            return post\n        return ethosu_ops.ethosu_identity(ifm=post, lut=relay.const([], dtype=\"int8\"))\n\n\nclass UnaryElementwiseRewriter(DFPatternCallback):\n    \"\"\"\n    Convert ethosu unary elementwise composite function to\n    ethosu_unary_elementwise operators\n    \"\"\"\n\n    def __init__(self, params_class: Type, pattern: CallPattern):\n        super().__init__(require_type=True)\n        self.params_class = params_class\n        self.pattern = pattern\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = self.params_class(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        activation_map = {\"clip\": \"CLIP\"}\n        if params.activation:\n            activation = activation_map[params.activation.op.name]\n            clip_min = int(params.activation.attrs.a_min)\n            clip_max = int(params.activation.attrs.a_max)\n        else:\n            activation = \"NONE\"\n            clip_min = 0\n            clip_max = 0\n\n        # We don't yet support activation functions that use LUT.\n        lut = relay.const([], dtype=\"int8\")\n\n        unary_input_shape = params.ifm.shape\n        # If the input tensor is not 4D, enter reshapes before and after the unary operator\n        if len(params.ifm.shape) == 4:\n            unary_input = params.ifm.tensor\n        else:\n            pad_size = 4 - len(unary_input_shape)\n            unary_input_shape = ([1] * pad_size) + unary_input_shape\n            unary_input = relay.op.reshape(params.ifm.tensor, newshape=unary_input_shape)\n\n        ethosu_unary_elementwise = ethosu_ops.ethosu_unary_elementwise(\n            ifm=unary_input,\n            lut=lut,\n            operator_type=params.operator_type,\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            ofm_channels=unary_input_shape[3],\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            ifm_layout=str(params.ifm.layout),\n            ofm_layout=str(params.ofm.layout),\n        )\n        if len(params.ifm.shape) == 4:\n            op = ethosu_unary_elementwise\n        else:\n            op = relay.op.reshape(ethosu_unary_elementwise, newshape=params.ifm.shape)\n        return op\n\n\nclass AbsRewriter(UnaryElementwiseRewriter):\n    def __init__(self):\n        super().__init__(\n            params_class=ethosu_patterns.AbsParams,\n            pattern=(wildcard().has_attr({\"Composite\": ethosu_patterns.AbsParams.composite_name}))(\n                wildcard()\n            ),\n        )\n\n\nclass MeanRewriter(DFPatternCallback):\n    \"\"\"Convert ethosu.mean composite functions to an equivalent legalization:\n    - Case 1 (axis == [1, 2] and keepsdims == True):\n        ethosu_depthwise_conv2d + ethosu_binary_elementwise\n    - Case 2 (ifm qparams == ofm qparams): ethosu_pooling\n    - Case 3 (else): ethosu_depthwise_conv2d\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.MeanParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.MeanParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        ifm_shape = params.ifm.shape\n        ofm_shape = params.ofm.shape\n        lut = relay.const([], \"int8\")\n        axis = params.axis\n        reduced_op = params.ifm.tensor\n\n        # Enforce 4d input\n        if len(ifm_shape) < 4:\n            axis = [x + 1 for x in axis]\n            if len(ifm_shape) == 3:\n                ifm_shape = [1, params.height, params.width, ifm_shape[2]]\n            else:\n                ifm_shape = [1, params.height, params.width, 1]\n            reduced_op = relay.reshape(reduced_op, ifm_shape)\n\n        filter_height = ifm_shape[1] if 1 in axis else 1\n        filter_width = ifm_shape[2] if 2 in axis else 1\n        in_channels = out_channels = ifm_shape[-1]\n\n        # If the height is greater than max kernel height, reshape the input\n        # from [filter_height, filter_width] to [1, (filter_height*filter_width)]\n        # only in the case the axis is [1, 2].\n        if axis == [1, 2] and filter_height > 64:\n            ifm_shape = (ifm_shape[0], 1, filter_height * filter_width, in_channels)\n            filter_width = filter_height * filter_width\n            filter_height = 1\n            reduced_op = relay.reshape(reduced_op, ifm_shape)\n\n        if axis == [1, 2] and params.keepdims:\n            weight_scale = 1\n            weight_values = np.ones([out_channels, filter_height, filter_width, 1])\n            scale_bias = vela_api.pack_biases(\n                biases=np.zeros(ifm_shape[-1]),\n                ifm_scale=params.ifm.q_params.scale_f32,\n                ifm_dtype=np.dtype(params.ifm.dtype),\n                weight_scales=np.array([weight_scale], dtype=np.float),\n                ofm_scale=params.ofm.q_params.scale_f32,\n                is_activation_tanh_or_sigmoid=False,\n            )\n\n            reduced_op = ethosu_ops.ethosu_depthwise_conv2d(\n                ifm=reduced_op,\n                weight=relay.const(weight_values, params.ifm.dtype),\n                scale_bias=relay.const(scale_bias, \"uint8\"),\n                lut=lut,\n                ifm_scale=float(params.ifm.q_params.scale_f32),\n                ifm_zero_point=int(params.ifm.q_params.zero_point),\n                weight_zero_point=0,\n                ofm_scale=float(params.ofm.q_params.scale_f32),\n                ofm_zero_point=int(params.ofm.q_params.zero_point),\n                kernel_shape=(filter_height, filter_width),\n                ofm_channels=out_channels,\n                ofm_dtype=\"int16\",\n            )\n\n            n = int(filter_height * filter_width)\n            eps = 1 / (256 * (n + 1)) if n % 2 == 0 else 0\n\n            scalar_tensor = relay.const(np.ones([1, 1, 1, 1], dtype=\"int16\"), dtype=\"int16\")\n\n            reduced_op = ethosu_ops.ethosu_binary_elementwise(\n                ifm=reduced_op,\n                ifm2=scalar_tensor,\n                lut=lut,\n                operator_type=\"MUL\",\n                ifm_scale=float(params.ofm.q_params.scale_f32),\n                ifm_zero_point=int(params.ofm.q_params.zero_point),\n                ifm2_scale=1 / (n - eps),\n                ifm2_zero_point=0,\n                ofm_scale=float(params.ofm.q_params.scale_f32),\n                ofm_zero_point=int(params.ofm.q_params.zero_point),\n                ifm_channels=out_channels,\n                ifm2_channels=out_channels,\n                reversed_operands=False,\n                ofm_dtype=\"int8\",\n                rounding_mode=\"NATURAL\",\n            )\n        elif (\n            params.ifm.q_params.scale_f32 == params.ofm.q_params.scale_f32\n            and params.ifm.q_params.zero_point == params.ofm.q_params.zero_point\n        ):\n            reduced_op = ethosu_ops.ethosu_pooling(\n                ifm=reduced_op,\n                lut=lut,\n                pooling_type=\"AVG\",\n                ifm_scale=float(params.ifm.q_params.scale_f32),\n                ifm_zero_point=0,\n                ofm_scale=float(params.ofm.q_params.scale_f32),\n                ofm_zero_point=0,\n                pool_shape=(filter_height, filter_width),\n                ofm_channels=out_channels,\n                rounding_mode=\"TRUNCATE\",\n            )\n        else:\n            weight_scale = 1 / (filter_height * filter_width)\n            weight_values = np.ones([out_channels, filter_height, filter_width, 1])\n            bias = -1 * int(params.ifm.q_params.zero_point) * filter_height * filter_width\n\n            scale_bias = vela_api.pack_biases(\n                biases=np.ones([ifm_shape[-1]]) * bias,\n                ifm_scale=params.ifm.q_params.scale_f32,\n                ifm_dtype=np.dtype(params.ifm.dtype),\n                weight_scales=np.array([weight_scale], dtype=np.float),\n                ofm_scale=params.ofm.q_params.scale_f32,\n                is_activation_tanh_or_sigmoid=False,\n            )\n            reduced_op = ethosu_ops.ethosu_depthwise_conv2d(\n                ifm=reduced_op,\n                weight=relay.const(weight_values, params.ifm.dtype),\n                scale_bias=relay.const(scale_bias, \"uint8\"),\n                lut=lut,\n                ifm_scale=float(params.ifm.q_params.scale_f32),\n                ifm_zero_point=0,\n                weight_zero_point=0,\n                ofm_scale=float(params.ofm.q_params.scale_f32),\n                ofm_zero_point=int(params.ofm.q_params.zero_point),\n                kernel_shape=(filter_height, filter_width),\n                ofm_channels=out_channels,\n                rounding_mode=\"NATURAL\",\n            )\n\n        # Reshape to original ofm shape\n        if len(ofm_shape) < 4:\n            reduced_op = relay.reshape(reduced_op, ofm_shape)\n\n        return reduced_op\n\n\nclass ConcatRewriter(DFPatternCallback):\n    \"\"\"The newer versions of TFLite converters return a concatenate operator that concatenates\n    tensors with same QNN params (if the QNN params of tensors were initially different,\n    the converter adds a requantize node), so this rewriter replaces the QNN concatenate with\n    \"normal\" concatenate\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.ConcatParams.composite_name})\n        )(None)\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        # Find the tensors that are inputs to the concat and the scales and zero points\n        concat_args = list()\n        for arg in post.args:\n            if isinstance(arg, tvm.relay.expr.Call):\n                concat_args.append(arg)\n\n        axis = post.op.body.attrs.axis\n        concat = relay.op.concatenate(relay.Tuple(concat_args), axis=axis)\n        return concat\n\n\nclass RequantizeRewriter(DFPatternCallback):\n    \"\"\"Convert ethos-u.requantize composite function to an identity operation.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.RequantizeParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.RequantizeParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        lut = relay.const([], \"int8\")\n\n        return ethosu_ops.ethosu_identity(\n            ifm=params.ifm.tensor,\n            lut=lut,\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n        )\n\n\nclass Resize2dRewriter(DFPatternCallback):\n    \"\"\"\n    Convert ethos-u.resize2d composite function to an equivalent operation that\n    performs the relevant upsampling operation.\n\n    Case 1: No upsampling (upscale factor of 1):\n        Identity.\n    Case 1: Nearest neighbor upsampling:\n        1x1 pooling with 2x2 nearest neighbor upsampling.\n    Case 2: Bilinear upsampling:\n        2x2 average pool with 2x2 nearest neighbor upsampling.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.Resize2dParams.composite_name})\n        )(wildcard())\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.Resize2dParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        lut = relay.const([], \"int8\")\n        ifm_shape = params.ifm.shape\n        in_channels = ifm_shape[-1]\n        reduced_op = params.ifm.tensor\n        current_size = np.array(ifm_shape[1:3])\n        output_size = np.array(params.size)\n\n        if (current_size == output_size).all():\n            return ethosu_ops.ethosu_identity(\n                reduced_op,\n                lut,\n                ifm_scale=float(params.ifm.q_params.scale_f32),\n                ifm_zero_point=int(params.ifm.q_params.zero_point),\n                ofm_scale=float(params.ofm.q_params.scale_f32),\n                ofm_zero_point=int(params.ofm.q_params.zero_point),\n            )\n\n        padding = [0, 0, 0, 0]\n        rounding_mode = \"TFL\"\n        pool_shape = [1, 1]\n        if params.method == \"linear\":\n            pool_shape = [2, 2]\n            rounding_mode = \"NATURAL\"\n            if params.coordinate_transformation_mode == \"asymmetric\":\n                # Use SAME padding.\n                ypad = Resize2dRewriter.get_required_padding(ifm_shape[1])\n                xpad = Resize2dRewriter.get_required_padding(ifm_shape[2])\n                padding = [ypad // 2, xpad // 2, (ypad + 1) // 2, (xpad + 1) // 2]\n\n        return ethosu_ops.ethosu_pooling(\n            ifm=reduced_op,\n            lut=lut,\n            pooling_type=\"AVG\",\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            pool_shape=pool_shape,\n            ofm_channels=in_channels,\n            strides=[1, 1],\n            padding=padding,\n            upscale=\"NEAREST\",\n            rounding_mode=rounding_mode,\n        )\n\n    @staticmethod\n    def get_required_padding(input_size: int, pool_size: int = 2) -> int:\n        \"\"\"Gets the amount of padding required needed to achieve\n        'SAME' padding for a given axis.\"\"\"\n        needed_input = (input_size - 1) + pool_size\n        total_padding = max(0, needed_input - input_size)\n        return total_padding\n\n\nclass ExpandDimsRewriter(DFPatternCallback):\n    \"\"\"Legalize expand dims to a reshape operator.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.ExpandDimsParams.composite_name})\n        )(None)\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.ExpandDimsParams(post.op.body)\n        return relay.op.reshape(post.args[0], newshape=params.output.shape)\n\n\nclass SqueezeRewriter(DFPatternCallback):\n    \"\"\"Legalize squeeze to a reshape operator.\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True, rewrite_once=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.SqueezeParams.composite_name})\n        )(None)\n\n    def callback(\n        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map\n    ) -> tvm.relay.Expr:\n        params = ethosu_patterns.SqueezeParams(post.op.body)\n        return relay.op.reshape(post.args[0], newshape=params.output.shape)\n\n\nclass FullyConnectedRewriter(DFPatternCallback):\n    \"\"\"Legalize Fully Connected (with bias and clip) to an NPU operator\"\"\"\n\n    def __init__(self):\n        super().__init__(require_type=True)\n        self.pattern = (\n            wildcard().has_attr({\"Composite\": ethosu_patterns.FullyConnectedParams.composite_name})\n        )(wildcard())\n\n    def callback(self, pre, post, node_map):\n        params = ethosu_patterns.FullyConnectedParams(post.op.body)\n        params.ifm.tensor = post.args[0]\n\n        # IFM reshapes\n        ifm = post.args[0]\n        if len(params.ifm.shape) != 4 or not params.ifm.shape[1] == params.ifm.shape[2] == 1:\n            ifm = relay.reshape(ifm, (1, 1, 1, params.ifm.shape[-1]))\n\n        # Weight transformations\n        weights_values = params.weights.values\n        weights_values_ohwi = np.expand_dims(weights_values, axis=(1, 2))\n        if params.activation:\n            activation = \"CLIP\"\n            clip_min = int(params.activation.attrs.a_min)\n            clip_max = int(params.activation.attrs.a_max)\n        else:\n            activation = \"NONE\"\n            clip_min = 0\n            clip_max = 0\n        bias_values = (\n            params.biases.tensor.data.asnumpy()\n            if params.biases\n            else np.zeros((params.ofm.shape[-1]))\n        )\n        scale_bias = vela_api.pack_biases(\n            biases=bias_values,\n            ifm_scale=params.ifm.q_params.scale_f32,\n            ifm_dtype=np.dtype(params.ifm.dtype),\n            weight_scales=params.weights.q_params.scale_f32,\n            ofm_scale=params.ofm.q_params.scale_f32,\n            is_activation_tanh_or_sigmoid=False,\n        )\n        ethosu_fc = ethosu_ops.ethosu_conv2d(\n            ifm=ifm,\n            weight=relay.const(weights_values_ohwi, params.weights.values.dtype),\n            scale_bias=relay.const(scale_bias, \"uint8\"),\n            lut=relay.const([], dtype=\"int8\"),\n            ifm_scale=float(params.ifm.q_params.scale_f32),\n            ifm_zero_point=int(params.ifm.q_params.zero_point),\n            weight_zero_point=int(params.weights.q_params.zero_point),\n            ofm_scale=float(params.ofm.q_params.scale_f32),\n            ofm_zero_point=int(params.ofm.q_params.zero_point),\n            kernel_shape=[1, 1],\n            ofm_channels=params.weights.shape[0],\n            strides=(1, 1),\n            padding=(0, 0, 0, 0),\n            dilation=(1, 1),\n            activation=activation,\n            clip_min=clip_min,\n            clip_max=clip_max,\n            upscale=\"NONE\",\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n\n        if len(params.ofm.shape) != 4 or not params.ofm.shape[1] == params.ofm.shape[2] == 1:\n            ethosu_fc = relay.reshape(ethosu_fc, params.ofm.shape)\n        return ethosu_fc\n\n\n@util.create_npu_function_pass(opt_level=1)\nclass LegalizeEthosU:\n    \"\"\"This is the pass to call graph-rewrites to perform graph transformation\n    in a way such that the operations are replaced with hardware/codegen supported\n    operations.\n    \"\"\"\n\n    def transform_npu_function(self, _, func: relay.Function) -> relay.Function:\n        \"\"\"This is the method that replaces the operations with hardware/codegen supported\n        operations.\n        \"\"\"\n        rewriters = [\n            PartitionedSplitRewriter(),\n            SplitRewriter(),\n            Conv2DRewriter(),\n            Conv2DTransposeRewriter(),\n            DepthwiseConv2DRewriter(),\n            FullyConnectedRewriter(),\n            MaxPoolingRewriter(),\n            AvgPoolingRewriter(),\n            AddRewriter(),\n            SubRewriter(),\n            MulRewriter(),\n            MinRewriter(),\n            MaxRewriter(),\n            ShlRewriter(),\n            AbsRewriter(),\n            TanhRewriter(),\n            HardSwishRewriter(),\n            LeakyReLURewriter(),\n            MeanRewriter(),\n            ConcatRewriter(),\n            SigmoidRewriter(),\n            RequantizeRewriter(),\n            Resize2dRewriter(),\n            ExpandDimsRewriter(),\n            SqueezeRewriter(),\n            ReshapeRewriter(),\n            StridedSliceRewriter(),\n            NoOpRewriter(),\n        ]\n        for rewriter in rewriters:\n            func = rewrite(rewriter, func)\n\n        return func\n\n    def __call__(self, *args, **kwargs):\n        # pylint is unable figure out the decorated\n        # class is callable, thus adding this to\n        # suppress the warning.\n        pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"Relay operators for the Arm(R) Ethos(TM)-U NPU\"\n\nfrom .convolution import ethosu_conv2d\nfrom .depthwise import ethosu_depthwise_conv2d\nfrom .pooling import ethosu_pooling\nfrom .binary_elementwise import ethosu_binary_elementwise\nfrom .identity import ethosu_identity\nfrom .unary_elementwise import ethosu_unary_elementwise\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/binary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay operators for binary elementwise operators for Arm(R) Ethos(TM)-U NPU\"\"\"\nfrom typing import Optional\nimport tvm\nfrom tvm.relay.op import _make\nfrom tvm.topi.generic import schedule_injective\nfrom tvm.relay.op.op import OpStrategy\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import binary_elementwise_compute\n\n\ndef _extract_ethosu_binary_elementwise_params(attrs, args):\n    \"\"\"Get the parameters necessary to construct a ethosu_binary_elementwise compute TE\n    from a ethosu_binary_elementwise Relay call.\"\"\"\n    ifm = args[0]\n    ifm2 = args[1]\n    lut = args[2]\n    operator_type = attrs.operator_type\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    ifm2_scale = attrs.ifm2_scale\n    ifm2_zero_point = attrs.ifm2_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    ifm_channels = attrs.ifm_channels\n    ifm2_channels = attrs.ifm2_channels\n    reversed_operands = attrs.reversed_operands\n    activation = attrs.activation\n    clip_min = attrs.clip_min\n    clip_max = attrs.clip_max\n    rounding_mode = attrs.rounding_mode\n    ifm_layout = attrs.ifm_layout\n    ifm2_layout = attrs.ifm2_layout\n    ofm_layout = attrs.ofm_layout\n    ofm_dtype = attrs.ofm_dtype\n\n    return (\n        ifm,\n        ifm2,\n        lut,\n        operator_type,\n        ifm_scale,\n        ifm_zero_point,\n        ifm2_scale,\n        ifm2_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        ifm_channels,\n        ifm2_channels,\n        reversed_operands,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        ifm_layout,\n        ifm2_layout,\n        ofm_layout,\n        ofm_dtype,\n    )\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.binary_elementwise\", \"FTVMCompute\")\ndef create_ethosu_binary_elementwise_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_binary_elementwise compute op.\"\"\"\n    params = _extract_ethosu_binary_elementwise_params(attrs, args)\n    op = binary_elementwise_compute(*params)\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.binary_elementwise\", \"FTVMStrategy\")\ndef binary_elementwise_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_binary_elementwise_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_binary_elementwise\",\n    )\n    return strategy\n\n\ndef ethosu_binary_elementwise(\n    ifm: tvm.relay.Expr,\n    ifm2: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    operator_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ifm2_scale: float,\n    ifm2_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    ifm_channels: int,\n    ifm2_channels: int,\n    reversed_operands: bool,\n    ofm_dtype: str,\n    activation: Optional[str] = \"NONE\",\n    clip_min: Optional[int] = 0,\n    clip_max: Optional[int] = 0,\n    rounding_mode: Optional[str] = \"TFL\",\n    ifm_layout: Optional[str] = \"NHWC\",\n    ifm2_layout: Optional[str] = \"NHWC\",\n    ofm_layout: Optional[str] = \"NHWC\",\n) -> tvm.relay.Call:\n    \"\"\"This is a quantized binary elementwise operation as supported by\n    the NPU. It accepts either NHWC or NHCWB16 format\n    for the input data.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    ifm2 : tvm.relay.Expr\n        The Input Feature Map tensor 2 (IFM2).\n    lut : tvm.relay.Expr\n        The look-up table of values to use if activation = \"LUT\".\n    operator_type: str\n        The type of the binary elementwise operator.\n            \"ADD\"\n            \"SUB\"\n            \"MUL\"\n            \"MIN\"\n            \"MAX\"\n            \"SHR\"\n            \"SHL\"\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ifm2_scale : float\n        The quantization scale for the Input Feature Map tensor 2.\n    ifm2_zero_point : int\n        The quantization zero point for the Input Feature Map tensor 2.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n       The quantization zero point for the Output Feature Map tensor.\n    ifm_channels : int\n        The number of the Input Feature Map channels.\n    ifm2_channels : int\n        The number of the Input Feature Map 2 channels.\n    reversed_operands : bool\n        True if IFM2 is the first operand and IFM is the second operand.\n    ofm_dtype: str\n        The Output Feature Map tensor type.\n        MUL, ADD, SUB {IFM}->{OFM}:\n          {uint8, int8 int32} -> {uint8, int8, int32}, any pairing\n        MAX, MIN:\n          IFM and OFM must be of the same type, one of:\n          {int8, uint8}\n        SHR {IFM}->{OFM}:\n          {int32}->{int8, uint8, int32}, any pairing\"\n        SHL:\n          {int32}->{int32} only\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n        Available activations for activation type:\n            {int8, uint8}: \"NONE\", \"CLIP\", \"TANH\", \"SIGMOID\", \"LUT\"\n            {int32}: \"NONE\"\n    clip_min : int, optional\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int, optional\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str, optional\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ifm2_layout : str, optional\n        The layout of the Input Feature Map tensor 2. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    out : tvm.relay.Call\n        A call to the ethosu_binary_elementwise op.\n    \"\"\"\n    return _make.ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        lut,\n        operator_type,\n        ifm_scale,\n        ifm_zero_point,\n        ifm2_scale,\n        ifm2_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        ifm_channels,\n        ifm2_channels,\n        reversed_operands,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        ifm_layout,\n        ifm2_layout,\n        ofm_layout,\n        ofm_dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/convolution.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay operators for convolutions for Arm(R) Ethos(TM)-U NPU\"\"\"\nfrom typing import Tuple\n\nimport tvm  # type: ignore\nfrom tvm.relay.op import _make  # type: ignore\nfrom tvm.topi.generic import schedule_injective  # type: ignore\nfrom tvm.relay.op.op import OpStrategy  # type: ignore\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import conv2d_compute\n\n\ndef _extract_ethosu_conv2d_params(attrs, args):\n    \"\"\"Get the parameters necessary to construct a compute TE\n    from a ethosu_conv2d Relay call.\"\"\"\n    ifm = args[0]\n    weight = args[1]\n    scale_bias = args[2]\n    lut = args[3]\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    weight_zero_point = attrs.weight_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    strides = attrs.strides\n    padding = attrs.padding\n    dilation = attrs.dilation\n    activation = attrs.activation\n    clip_min = attrs.clip_min\n    clip_max = attrs.clip_max\n    rounding_mode = attrs.rounding_mode\n    upscale = attrs.upscale\n    ifm_layout = attrs.ifm_layout\n    ofm_layout = attrs.ofm_layout\n\n    return (\n        ifm,\n        weight,\n        scale_bias,\n        lut,\n        ifm_scale,\n        ifm_zero_point,\n        weight_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        strides,\n        padding,\n        dilation,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n    )\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.conv2d\", \"FTVMCompute\")\ndef create_ethosu_conv2d_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_conv2d compute op.\"\"\"\n    params = _extract_ethosu_conv2d_params(attrs, args)\n    op = conv2d_compute(*params)\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.conv2d\", \"FTVMStrategy\")\ndef conv2d_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_conv2d_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_conv2d\",\n    )\n    return strategy\n\n\ndef ethosu_conv2d(\n    ifm: tvm.relay.Expr,\n    weight: tvm.relay.Expr,\n    scale_bias: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    weight_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    kernel_shape: Tuple[int, int],\n    ofm_channels: int,\n    strides: Tuple[int, int] = (1, 1),\n    padding: Tuple[int, int, int, int] = (0, 0, 0, 0),\n    dilation: Tuple[int, int] = (1, 1),\n    activation: str = \"NONE\",\n    clip_min: int = 0,\n    clip_max: int = 0,\n    rounding_mode: str = \"TFL\",\n    upscale: str = \"NONE\",\n    ifm_layout: str = \"NHWC\",\n    ofm_layout: str = \"NHWC\",\n) -> tvm.relay.Call:\n    \"\"\"This is a quantized 2D convolution operation as supported by\n    the NPU. It accepts either NHWC or NHCWB16 format\n    for the input data and OHWI format for the kernel weights.\n\n    Reference: https://developer.arm.com/documentation/102420/0200/\n\n    Note that the per-channel weight scale and bias tensor must be\n    packed together into a combined tensor of uint80s. This is represented\n    in TVM by a (channels, 10) tensor of type uint8. For more detail,\n    refer to the Technical Reference Manual linked above.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    weight : tvm.relay.Expr\n        The weight tensor.\n    scale_bias : tvm.relay.Expr\n        The packed per-channel weight scale and bias tensor.\n    lut : tvm.relay.Expr\n        The look-up table of values to use if activation = \"LUT\".\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    weight_zero_point : int\n        The quantization zero point for the weight tensor.\n    ofm_scale : int\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    kernel_shape : tuple of int\n        The 2 dimensional kernel shape as (kernel_height, kernel_width).\n    ofm_channels : int\n        The number of the Output Feature Map channels.\n    strides : tuple of int, optional\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : tuple of int, optional\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    dilation : tuple of int, optional\n        The 2 dimensional dilation as (dilation_height, dilation_width).\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int, optional\n        The minimum clipping value if activation = \"CLIP\"\n    clip_max : int, optional,\n        The maximum clipping value if activation = \"CLIP\"\n    rounding_mode : str, optional\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale : str, optional\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    tvm.relay.Call\n        A call to the ethosu_conv2d op.\n\n    \"\"\"\n    return _make.ethosu_conv2d(\n        ifm,\n        weight,\n        scale_bias,\n        lut,\n        ifm_scale,\n        ifm_zero_point,\n        weight_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        kernel_shape,\n        ofm_channels,\n        strides,\n        padding,\n        dilation,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/depthwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay operator for depthwise convolution for Arm(R) Ethos(TM)-U NPU\"\"\"\n\nfrom typing import Tuple\n\nimport tvm\nfrom tvm.relay.op import _make\nfrom tvm.topi.generic import schedule_injective\nfrom tvm.relay.op.op import OpStrategy\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import depthwise_conv2d_compute\n\n\ndef _extract_ethosu_depthwise_conv2d_params(attrs, args):\n    \"\"\"Get the parameters necessary to construct a ethosu_depthwise_conv2d compute TE\n    from a ethosu_depthwise_conv2d Relay call.\"\"\"\n    ifm = args[0]\n    weight = args[1]\n    scale_bias = args[2]\n    lut = args[3]\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    weight_zero_point = attrs.weight_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    strides = attrs.strides\n    padding = attrs.padding\n    dilation = attrs.dilation\n    activation = attrs.activation\n    clip_min = attrs.clip_min\n    clip_max = attrs.clip_max\n    rounding_mode = attrs.rounding_mode\n    upscale = attrs.upscale\n    ifm_layout = attrs.ifm_layout\n    ofm_layout = attrs.ofm_layout\n    ofm_dtype = attrs.ofm_dtype\n\n    return (\n        ifm,\n        weight,\n        scale_bias,\n        lut,\n        ifm_scale,\n        ifm_zero_point,\n        weight_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        strides,\n        padding,\n        dilation,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n        ofm_dtype,\n    )\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.depthwise_conv2d\", \"FTVMCompute\")\ndef create_ethosu_depthwise_conv2d_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_depthwise_conv2d compute op.\"\"\"\n    params = _extract_ethosu_depthwise_conv2d_params(attrs, args)\n    op = depthwise_conv2d_compute(*params)\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.depthwise_conv2d\", \"FTVMStrategy\")\ndef depthwise_conv2d_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_depthwise_conv2d_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_depthwise_conv2d\",\n    )\n    return strategy\n\n\ndef ethosu_depthwise_conv2d(\n    ifm: tvm.relay.Expr,\n    weight: tvm.relay.Expr,\n    scale_bias: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    weight_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    kernel_shape: Tuple[int, int],\n    ofm_channels: int,\n    strides: Tuple[int, int] = (1, 1),\n    padding: Tuple[int, int, int, int] = (0, 0, 0, 0),\n    dilation: Tuple[int, int] = (1, 1),\n    activation: str = \"NONE\",\n    clip_min: int = 0,\n    clip_max: int = 0,\n    rounding_mode: str = \"TFL\",\n    upscale: str = \"NONE\",\n    ifm_layout: str = \"NHWC\",\n    ofm_layout: str = \"NHWC\",\n    ofm_dtype: str = \"int8\",\n) -> tvm.relay.Call:\n    \"\"\"This is a quantized 2D depthwise convolution operation as supported by\n    the NPU. It accepts either NHWC or NHCWB16 format\n    for the input data and OHWI format for the kernel weights.\n\n    Reference: https://developer.arm.com/documentation/102420/0200/\n\n    Note that the per-channel weight scale and bias tensor must be\n    packed together into a combined tensor of uint80s. This is represented\n    in TVM by a (channels, 10) tensor of type uint8. For more detail,\n    refer to the Technical Reference Manual linked above.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    weight : tvm.relay.Expr\n        The weight tensor.\n    scale_bias : tvm.relay.Expr\n        The packed per-channel weight scale and bias tensor.\n    lut : tvm.relay.Expr\n        The look-up table of values to use if activation = \"LUT\"\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    weight_zero_point : int\n        The quantization zero point for the weight tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    kernel_shape : tuple of int\n        The 2 dimensional kernel shape as (kernel_height, kernel_width).\n    ofm_channels : int\n        The number of the Output Feature Map channels.\n    strides : tuple of int, optional\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : tuple of int, optional\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    dilation : tuple of int, optional\n        The 2 dimensional dilation as (dilation_height, dilation_width).\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform\n        the activation function.\n    clip_min : int, optional\n        The minimum clipping value if activation = \"CLIP\"\n    clip_max : int, optional,\n        The maximum clipping value if activation = \"CLIP\"\n    rounding_mode : str, optional\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale : str, optional\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_dtype : str, optional\n        The Output Feature Map tensor data type. Can be 'int8', 'uint8' or 'int16'.\n\n    Returns\n    -------\n    out : tvm.relay.Call\n        A call to the ethosu_depthwise_conv2d op.\n\n    \"\"\"\n    return _make.ethosu_depthwise_conv2d(\n        ifm,\n        weight,\n        scale_bias,\n        lut,\n        ifm_scale,\n        ifm_zero_point,\n        weight_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        kernel_shape,\n        ofm_channels,\n        strides,\n        padding,\n        dilation,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n        ofm_dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/identity.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay identity operator for Arm(R) Ethos(TM)-U NPU\"\"\"\n\nimport tvm\nfrom tvm.relay.op import _make\nfrom tvm.topi.generic import schedule_injective\nfrom tvm.relay.op.op import OpStrategy\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import identity_compute\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.identity\", \"FTVMCompute\")\ndef create_ethosu_identity_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_identity compute op.\"\"\"\n    ifm = args[0]\n    lut = args[1]\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    activation = attrs.activation\n    op = identity_compute(\n        ifm, lut, ifm_scale, ifm_zero_point, ofm_scale, ofm_zero_point, activation\n    )\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.identity\", \"FTVMStrategy\")\ndef identity_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_identity_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_identity\",\n    )\n    return strategy\n\n\ndef ethosu_identity(\n    ifm: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    ifm_scale: float = 1,\n    ifm_zero_point: int = 0,\n    ofm_scale: float = 1,\n    ofm_zero_point: int = 0,\n    activation: str = \"NONE\",\n) -> tvm.relay.Call:\n    \"\"\"The Identity operator that runs on the NPU.\n\n    This operator takes in a tensor of any shape and returns the same tensor,\n    with the data optionally requantized.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    lut : tvm.relay.Expr\n        The look-up table values to use if activation = \"LUT\", \"TANH\" or \"SIGMOID\".\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n       The quantization zero point for the Output Feature Map tensor.\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n\n    Returns\n    -------\n    out : tvm.relay.Call\n        A call to the ethosu_identity op.\n    \"\"\"\n    return _make.ethosu_identity(\n        ifm, lut, ifm_scale, ifm_zero_point, ofm_scale, ofm_zero_point, activation\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/op_attrs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The attributes node used for Arm(R) Ethos(TM)-U NPU Relay operators.\"\"\"\nfrom tvm.ir import Attrs\nimport tvm._ffi\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuConv2DAttrs\")\nclass EthosuConv2DAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.conv2d.\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuIdentityAttrs\")\nclass EthosuIdentityAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.identity.\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuDepthwiseConv2DAttrs\")\nclass EthosuDepthwiseConv2DAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.depthwise_conv2d.\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuPoolingAttrs\")\nclass EthosuPooling2DAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.pooling.\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuBinaryElementwiseAttrs\")\nclass EthosuBinaryElementwiseAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.binary_elementwise\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EthosuUnaryElementwiseAttrs\")\nclass EthosuUnaryElementwiseAttrs(Attrs):\n    \"\"\"Attributes for contrib.ethosu.unary_elementwise\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay operators for pooling for Arm(R) Ethos(TM)-U NPU\"\"\"\nfrom typing import Tuple\n\nimport tvm\nfrom tvm.relay.op import _make\nfrom tvm.topi.generic import schedule_injective\nfrom tvm.relay.op.op import OpStrategy\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import pooling_compute\n\n\ndef _extract_ethosu_pooling_params(attrs, args):\n    \"\"\"Get the parameters necessary to construct a ethosu_pooling compute TE\n    from a ethosu_pooling Relay call.\"\"\"\n    ifm = args[0]\n    lut = args[1]\n    pooling_type = attrs.pooling_type\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    pool_shape = attrs.pool_shape\n    ofm_channels = attrs.ofm_channels\n    strides = attrs.strides\n    padding = attrs.padding\n    activation = attrs.activation\n    clip_min = attrs.clip_min\n    clip_max = attrs.clip_max\n    rounding_mode = attrs.rounding_mode\n    upscale = attrs.upscale\n    ifm_layout = attrs.ifm_layout\n    ofm_layout = attrs.ofm_layout\n\n    return (\n        ifm,\n        lut,\n        pooling_type,\n        ifm_scale,\n        ifm_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n    )\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.pooling\", \"FTVMCompute\")\ndef create_ethosu_pooling_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_pooling compute op.\"\"\"\n    params = _extract_ethosu_pooling_params(attrs, args)\n    op = pooling_compute(*params)\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.pooling\", \"FTVMStrategy\")\ndef pooling_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_pooling_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_pooling\",\n    )\n    return strategy\n\n\ndef ethosu_pooling(\n    ifm: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    pooling_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    pool_shape: Tuple[int, int],\n    ofm_channels: int,\n    strides: Tuple[int, int] = (1, 1),\n    padding: Tuple[int, int, int, int] = (0, 0, 0, 0),\n    activation: str = \"NONE\",\n    clip_min: int = 0,\n    clip_max: int = 0,\n    rounding_mode: str = \"TFL\",\n    upscale: str = \"NONE\",\n    ifm_layout: str = \"NHWC\",\n    ofm_layout: str = \"NHWC\",\n) -> tvm.relay.Call:\n    \"\"\"This is a quantized 2D pooling operation as supported by\n    the NPU. It accepts either NHWC or NHCWB16 format\n    for the input data.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    lut : tvm.relay.Expr\n         The look-up table of values to use if activation = \"LUT\".\n    pooling_type: str\n        The type of the pooling. \"AVG\" - average pool,   \"MAX\" - max pool.\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n       The quantization zero point for the Output Feature Map tensor.\n    pool_shape : tuple of int\n        The 2 dimensional pool shape as (pool_shape_height, pool_shape_width).\n    ofm_channels : int\n        The number of the Output Feature Map channels\n    strides : tuple of int, optional\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : tuple of int, optional\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int, optional\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int, optional\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str, optional\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale: str, optional\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    out : tvm.relay.Call\n        A call to the ethosu_pooling op.\n    \"\"\"\n    return _make.ethosu_pooling(\n        ifm,\n        lut,\n        pooling_type,\n        ifm_scale,\n        ifm_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        upscale,\n        ifm_layout,\n        ofm_layout,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/op/unary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Relay operator for unary elementwise operations for Arm(R) Ethos(TM)-U NPU\"\"\"\nfrom typing import Optional\nimport tvm\nfrom tvm.relay.op import _make\nfrom tvm.topi.generic import schedule_injective\nfrom tvm.relay.op.op import OpStrategy\nfrom tvm.relay.op import strategy as _strategy\n\nfrom ..te import unary_elementwise_compute\n\n\ndef _extract_ethosu_unary_elementwise_params(attrs, args):\n    \"\"\"Get the parameters necessary to construct a ethosu_unary_elementwise compute TE\n    from a ethosu_unary_elementwise Relay call.\"\"\"\n    ifm = args[0]\n    lut = args[1]\n    operator_type = attrs.operator_type\n    ifm_scale = attrs.ifm_scale\n    ifm_zero_point = attrs.ifm_zero_point\n    ofm_scale = attrs.ofm_scale\n    ofm_zero_point = attrs.ofm_zero_point\n    ofm_channels = attrs.ofm_channels\n    activation = attrs.activation\n    clip_min = attrs.clip_min\n    clip_max = attrs.clip_max\n    rounding_mode = attrs.rounding_mode\n    ifm_layout = attrs.ifm_layout\n    ofm_layout = attrs.ofm_layout\n\n    return (\n        ifm,\n        lut,\n        operator_type,\n        ifm_scale,\n        ifm_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        ofm_channels,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        ifm_layout,\n        ofm_layout,\n    )\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.unary_elementwise\", \"FTVMCompute\")\ndef create_ethosu_unary_elementwise_compute(attrs, args, out_type):\n    \"\"\"Create an ethosu_unary_elementwise compute op.\"\"\"\n    params = _extract_ethosu_unary_elementwise_params(attrs, args)\n    op = unary_elementwise_compute(*params)\n    return [op]\n\n\n@tvm.ir.register_op_attr(\"contrib.ethosu.unary_elementwise\", \"FTVMStrategy\")\ndef unary_elementwise_strategy_ethosu(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        create_ethosu_unary_elementwise_compute,\n        _strategy.wrap_topi_schedule(schedule_injective),\n        name=\"ethosu_unary_elementwise\",\n    )\n    return strategy\n\n\ndef ethosu_unary_elementwise(\n    ifm: tvm.relay.Expr,\n    lut: tvm.relay.Expr,\n    operator_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    ofm_channels: int,\n    activation: Optional[str] = \"NONE\",\n    clip_min: Optional[int] = 0,\n    clip_max: Optional[int] = 0,\n    rounding_mode: Optional[str] = \"TFL\",\n    ifm_layout: Optional[str] = \"NHWC\",\n    ofm_layout: Optional[str] = \"NHWC\",\n) -> tvm.relay.Call:\n    \"\"\"This is a quantized unary elementwise operation as supported by the\n    NPU. It accepts either NHWC or NHCWB16 format for the input data.\n\n    Parameters\n    ----------\n    ifm : tvm.relay.Expr\n        The Input Feature Map tensor (IFM).\n    lut : tvm.relay.Expr\n        The look-up table values to use if activation = \"LUT\".\n    operator_type: str\n        The type of the unary elementwise operator.\n            \"ABS\"\n            \"CLZ\"\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n       The quantization zero point for the Output Feature Map tensor.\n    ofm_channels : int\n        The number of OFM channels.\n    activation : str, optional\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int, optional\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int, optional\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str, optional\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    out : tvm.relay.Call\n        A call to the ethosu_unary_elementwise op.\n    \"\"\"\n    return _make.ethosu_unary_elementwise(\n        ifm,\n        lut,\n        operator_type,\n        ifm_scale,\n        ifm_zero_point,\n        ofm_scale,\n        ofm_zero_point,\n        ofm_channels,\n        activation,\n        clip_min,\n        clip_max,\n        rounding_mode,\n        ifm_layout,\n        ofm_layout,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/preprocess.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, import-outside-toplevel\n\"\"\"Set of passes to pre-process the IRModule to support Arm(R)-Ethos(TM)-U\nNPU code generation. These set of passes will mutate both the main and the\nexternal functions.\n\"\"\"\nimport tvm  # type: ignore\nfrom . import _ffi_api  # type: ignore\n\n\ndef preprocess_ext_io() -> tvm.transform.Pass:\n    \"\"\"This pass mutates the number of inputs going to / outputs coming out to/from\n    external functions to one. This is achieved via concatenation\n    of inputs and splitting of outputs in around the call to the external function.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass to mutate the IO of the external functions and their calls.\n    \"\"\"\n    return _ffi_api.PreprocessExternalFuncIO()  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tensor Expressions for the NPU\"\"\"\n\nfrom .convolution import *\nfrom .depthwise import *\nfrom .pooling import *\nfrom .binary_elementwise import *\nfrom .identity import *\nfrom .unary_elementwise import *\nfrom .inline import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/binary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expressions for binary_elementwise\"\"\"\nimport operator\nimport numpy as np\nfrom tvm import te\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\n\nfrom .dma import dma_ofm_compute, dma_ifm_compute\nfrom .common import get_layout_transform_matrices\n\n\ndef binary_elementwise_compute(\n    ifm: te.Tensor,\n    ifm2: te.Tensor,\n    lut: te.Tensor,\n    operator_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ifm2_scale: float,\n    ifm2_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    ifm_channels: int,\n    ifm2_channels: int,\n    reversed_operands: bool,\n    activation: str,\n    clip_min: int,\n    clip_max: int,\n    rounding_mode: str,\n    ifm_layout: str,\n    ifm2_layout: str,\n    ofm_layout: str,\n    ofm_dtype: str,\n) -> te.Tensor:\n    \"\"\"A compute operator representing the capabilities of binary_elementwise for the NPU.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    ifm2 : te.Tensor\n        The Input Feature Map tensor 2 (IFM2).\n    lut : te.Tensor\n        The look-up table values to use if activation = \"LUT\".\n    operator_type: str\n        The type of the binary elementwise operator.\n            \"ADD\"\n            \"SUB\"\n            \"MUL\"\n            \"MIN\"\n            \"MAX\"\n            \"SHR\"\n            \"SHL\"\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ifm2_scale : float\n        The quantization scale for the Input Feature Map tensor 2.\n    ifm2_zero_point : int\n        The quantization zero point for the Input Feature Map tensor 1.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    ifm_channels : int\n        The number of the Input Feature Map channels.\n    ifm2_channels : int\n        The number of the Input Feature Map 2 channels.\n    reversed_operands : bool\n        True if IFM2 is the first operand and IFM is the second operand.\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n        Available activations for activation type:\n            {int8, uint8}: \"NONE\", \"CLIP\", \"TANH\", \"SIGMOID\", \"LUT\"\n            {int32}: \"NONE\"\n    clip_min : int\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ifm2_layout : str, optional\n        The layout of the Input Feature Map tensor 2. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_dtype: str\n        The Output Feature Map tensor type.\n        MUL, ADD, SUB {IFM}->{OFM}:\n          {uint8, int8 int32} -> {uint8, int8, int32}, any pairing\n        MAX, MIN:\n          IFM and OFM must be of the same type, one of:\n          {int8, uint8}\n        SHR {IFM}->{OFM}:\n          {int32}->{int8, uint8, int32}, any pairing\"\n        SHL:\n          {int32}->{int32} only\n\n    Returns\n    -------\n    te.Tensor\n        The Output Feature Map tensor.\n    \"\"\"\n    assert ifm.shape[0] == 1\n    assert ifm2.shape[0] == 1\n    assert ifm_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ifm2_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ofm_layout in {\"NHWC\", \"NHCWB16\"}\n\n    # Compute operation for the IFM DMA pipeline\n    dmaed_ifm = dma_ifm_compute(\n        ifm, ifm_layout, ifm_zero_point, ifm_scale, ifm_channels, (0, 0, 0, 0)\n    )\n    dmaed_ifm2 = dma_ifm_compute(\n        ifm2, ifm2_layout, ifm2_zero_point, ifm2_scale, ifm2_channels, (0, 0, 0, 0)\n    )\n\n    # Binary elementwise compute operation\n    ofm_height = dmaed_ifm.shape[1]\n    ofm_width = dmaed_ifm.shape[2]\n\n    binary_elementwise_attrs = {\n        \"op\": \"ethosu_binary_elementwise\",\n        \"operator_type\": operator_type,\n        \"reversed_operands\": reversed_operands,\n        \"activation\": activation,\n        \"clip_min\": clip_min,\n        \"clip_max\": clip_max,\n        \"rounding_mode\": rounding_mode,\n    }\n\n    operators = {\n        \"ADD\": operator.add,\n        \"SUB\": operator.sub,\n        \"MUL\": operator.mul,\n        \"MIN\": te.min,\n        \"MAX\": te.max,\n        \"SHR\": operator.add,\n        \"SHL\": operator.add,\n    }\n    broadcast = [value == 1 for value in dmaed_ifm2.shape]\n\n    if reversed_operands:\n        binary_elementwise = te.compute(\n            (1, ofm_height, ofm_width, ifm_channels),\n            lambda nn, hh, ww, cc: operators[operator_type](\n                dmaed_ifm2(\n                    0 if broadcast[0] else nn,\n                    0 if broadcast[1] else hh,\n                    0 if broadcast[2] else ww,\n                    0 if broadcast[3] else cc,\n                ).astype(ifm.dtype),\n                dmaed_ifm(nn, hh, ww, cc).astype(ifm.dtype),\n            ).astype(ofm_dtype),\n            name=\"ethosu_binary_elementwise\",\n            attrs=binary_elementwise_attrs,\n        )\n    else:\n        binary_elementwise = te.compute(\n            (1, ofm_height, ofm_width, ifm_channels),\n            lambda nn, hh, ww, cc: operators[operator_type](\n                dmaed_ifm(nn, hh, ww, cc).astype(ifm.dtype),\n                dmaed_ifm2(\n                    0 if broadcast[0] else nn,\n                    0 if broadcast[1] else hh,\n                    0 if broadcast[2] else ww,\n                    0 if broadcast[3] else cc,\n                ).astype(ifm.dtype),\n            ).astype(ofm_dtype),\n            name=\"ethosu_binary_elementwise\",\n            attrs=binary_elementwise_attrs,\n        )\n\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(int(ifm_channels))\n\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    ifm2_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, (1 - int(broadcast[1])), 0, 0, int(broadcast[1])],\n        [0, 0, (1 - int(broadcast[2])), 0, int(broadcast[2])],\n        [0, 0, 0, (1 - int(broadcast[3])), int(broadcast[3])],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n        ifm2_matrix = np.matmul(ifm2_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n    if ifm2_layout == \"NHCWB16\":\n        ifm2_matrix = np.matmul(nhwc_to_nhcwb16, ifm2_matrix).tolist()\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        [0, 0, 0, 0] if ifm_layout == \"NHWC\" else [0, 0, 0, 0, 0],\n    )\n    ifm2_propagator = Propagator(\n        ifm2_matrix,\n        [0, 0, 0, 0] if ifm2_layout == \"NHWC\" else [0, 0, 0, 0, 0],\n    )\n    propagator_attrs = {\n        \"ifm_propagator\": ifm_propagator,\n        \"ifm2_propagator\": ifm2_propagator,\n    }\n\n    # Compute operation for the OFM DMA pipeline\n    return dma_ofm_compute(\n        binary_elementwise,\n        ofm_layout,\n        ofm_zero_point,\n        ofm_scale,\n        ifm_channels,\n        attrs=propagator_attrs,\n    )\n\n\n@register_matcher\ndef match_ethosu_binary_elementwise(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU Binary Elementwise.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    convert_to_nhcwb16 = write.op.input_tensors[0]\n    if convert_to_nhcwb16.op.name != \"ethosu_convert_to_nhcwb16\":\n        return None\n    binary_elementwise = convert_to_nhcwb16.op.input_tensors[0]\n    if binary_elementwise.op.name != \"ethosu_binary_elementwise\":\n        return None\n    pad = binary_elementwise.op.input_tensors[0]\n    if pad.op.name != \"ethosu_pad\":\n        return None\n    upscale = pad.op.input_tensors[0]\n    if upscale.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc = upscale.op.input_tensors[0]\n    if convert_to_nhwc.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read = convert_to_nhwc.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n    pad2 = binary_elementwise.op.input_tensors[1]\n    if pad2.op.name != \"ethosu_pad\":\n        return None\n    upscale2 = pad2.op.input_tensors[0]\n    if upscale2.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc2 = upscale2.op.input_tensors[0]\n    if convert_to_nhwc2.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read2 = convert_to_nhwc2.op.input_tensors[0]\n    if read2.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n        read2.op.input_tensors[0],\n    ]\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n        write.op.attrs[\"ifm2_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    output_layout = convert_to_nhcwb16.op.attrs[\"layout\"]\n    input_layout = convert_to_nhwc.op.attrs[\"layout\"]\n    input2_layout = convert_to_nhwc2.op.attrs[\"layout\"]\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    block_config = device_config.get_elementwise_block_config(\n        propagators[0],\n        propagators[1],\n        binary_elementwise.op.attrs,\n        output_tensor.shape,\n        output_layout,\n        input_layout,\n        input2_layout,\n        ifm_dtype,\n        ofm_dtype,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        1,\n        block_config,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common methods for the NPU tensor expressions\"\"\"\n\nfrom typing import Tuple, List\n\n\ndef get_layout_transform_matrices(ofm_channels: int) -> Tuple[List[List[float]], List[List[float]]]:\n    \"\"\"Get the NHWC->NHCWB16 and NHCWB16->NHWC layout transform matrices.\n    For information about the supported layouts see https://developer.arm.com/documentation/102420/\n    0200/Functional-description/Control-and-data-flow/Supported-memory-formats-for-feature-maps\n\n    Parameters\n    ----------\n    ofm_channels : int\n        The number of output channels in a NHWC layout\n\n    Returns\n    -------\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc : Tuple[List[List[float]], List[List[float]]]\n        The layout transformation matrices\n    \"\"\"\n\n    # The value of the last dimension (B16) is always 16.\n    nhwc_to_nhcwb16 = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 0, 1 / 16, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 0, 16],\n        [0, 0, 0, 0, 1],\n    ]\n\n    # When we convert from NHWC to NHCWB16, the new C value is given by\n    # (ofm_channels - 1) // 16 + 1, which is a lossy operation, so we need to use\n    # the actual value of channels in the transform matrix to accurately recover\n    # the C in NHWC when we convert from NHCWB16 to NHWC.\n    nhcwb16_to_nhwc = [\n        [1, 0, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0, 0],\n        [0, 0, 0, 1, 0, 0],\n        # We need to offset only if number of ofm_channels is not divisible by 16\n        # Moreover, we can't use just the \"ofm_channels\" as last element because\n        # the propogation matrices are used to propogate block configs as well.\n        [0, 0, 16, 0, 0, -(int(ofm_channels % 16 != 0)) * (16 - ofm_channels % 16)],\n        [0, 0, 0, 0, 0, 1],\n    ]\n\n    return nhwc_to_nhcwb16, nhcwb16_to_nhwc\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/convolution.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expressions for convolutions for the NPU\"\"\"\nfrom typing import Tuple, Union, List\nimport numpy as np  # type: ignore\n\nfrom tvm import te  # type: ignore\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\n\nfrom .dma import dma_ofm_compute, dma_ifm_compute\nfrom .common import get_layout_transform_matrices\n\n\ndef conv2d_compute(\n    ifm: te.Tensor,\n    weight: te.Tensor,\n    scale_bias: te.Tensor,\n    lut: te.Tensor,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    weight_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    strides: Tuple[int, int],\n    padding: Tuple[int, int, int, int],\n    dilation: Union[Tuple[int, int], List[int]],\n    activation: str,\n    clip_min: int,\n    clip_max: int,\n    rounding_mode: str,\n    upscale: str,\n    ifm_layout: str,\n    ofm_layout: str,\n) -> te.Tensor:\n    \"\"\"A compute operator representing the capabilities of a 2D convolution for the NPU.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    weight : te.Tensor\n        The weight tensor.\n    scale_bias : te.Tensor\n        The packed per-channel weight scale and bias tensor.\n    lut : te.Tensor\n        The look-up table of values to use if activation = \"LUT\".\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    weight_zero_point : int\n        The quantization zero point for the weight tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    strides : tuple\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : tuple\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    dilation : Union[Tuple[int, int], List[int]]\n        The 2 dimensional dilation as (dilation_height, dilation_width).\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale : str\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    ifm_layout : str\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    te.Tensor\n        The OFM tensor.\n\n    \"\"\"\n    assert ifm.shape[0] == 1\n    assert ifm_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ofm_layout in {\"NHWC\", \"NHCWB16\"}\n\n    padding = [int(v) for v in padding]\n    stride_h, stride_w = [int(v) for v in strides]\n    dilation_h, dilation_w = [int(v) for v in dilation]\n    ofm_channels, kernel_h, kernel_w, ifm_channels = [int(v) for v in weight.shape]\n    upscale_factor = 2 if upscale != \"NONE\" else 1\n\n    # Compute operation for the IFM DMA pipeline\n    dmaed_ifm = dma_ifm_compute(\n        ifm,\n        ifm_layout,\n        ifm_zero_point,\n        ifm_scale,\n        weight.shape[3],\n        padding,\n        upscale_factor,\n    )\n\n    # 2D Convolution compute operation\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    ofm_height = (dmaed_ifm.shape[1] - dilated_kernel_h) // stride_h + 1\n    ofm_width = (dmaed_ifm.shape[2] - dilated_kernel_w) // stride_w + 1\n    rc = te.reduce_axis((0, ifm_channels), name=\"rc\")\n    rh = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rw = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    conv2d_attrs = {\n        \"op\": \"ethosu_conv2d\",\n        \"weight_zero_point\": weight_zero_point,\n        \"activation\": activation,\n        \"upscale\": upscale,\n        \"clip_min\": clip_min,\n        \"clip_max\": clip_max,\n        \"rounding_mode\": rounding_mode,\n        \"stride_h\": stride_h,\n        \"stride_w\": stride_w,\n        \"dilation_h\": dilation_h,\n        \"dilation_w\": dilation_w,\n    }\n\n    has_lut = activation in (\"TANH\", \"LUT\", \"SIGMOID\")\n\n    # This is a trick to insert the LUT tensor into the TE graph if LUT is present\n    lut_expr = (lut[0] + lut[255]).astype(ifm.dtype) if has_lut else 0\n\n    # Add the LUT tensor to the attributes to be able to later tell which tensor is the LUT\n    if has_lut:\n        conv2d_attrs[\"lut\"] = lut\n\n    conv = te.compute(\n        (1, ofm_height, ofm_width, ofm_channels),\n        lambda nn, hh, ww, cc: te.sum(\n            dmaed_ifm(\n                nn, hh * stride_h + rh * dilation_h, ww * stride_w + rw * dilation_w, rc\n            ).astype(ifm.dtype)\n            * weight[cc, rh, rw, rc].astype(ifm.dtype)\n            # This is a trick to load 10 elements of the scale_bias at once, not accurate maths\n            + (scale_bias[cc, 0] * scale_bias[cc, 9] + lut_expr).astype(ifm.dtype),\n            axis=[rh, rw, rc],\n        ),\n        name=\"ethosu_conv2d\",\n        attrs=conv2d_attrs,\n    )\n\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(ofm_channels)\n\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, stride_h, 0, 0, (dilated_kernel_h - stride_h)],\n        [0, 0, stride_w, 0, (dilated_kernel_w - stride_w)],\n        [0, 0, 0, 0, ifm_channels],\n        [0, 0, 0, 0, 1],\n    ]\n    weights_matrix = [\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, kernel_h],\n        [0, 0, 0, 0, kernel_w],\n        [0, 0, 0, 0, ifm_channels],\n        [0, 0, 0, 0, 1],\n    ]\n    bias_matrix = [\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 10],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n        weights_matrix = np.matmul(weights_matrix, nhcwb16_to_nhwc).tolist()\n        bias_matrix = np.matmul(bias_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        [0, -padding[0], -padding[1], 0]\n        if ifm_layout == \"NHWC\"\n        else [0, -padding[0], 0, -padding[1], 0],\n    )\n    weights_propagator = Propagator(\n        weights_matrix,\n        [0, 0, 0, 0],\n    )\n    bias_propagator = Propagator(\n        bias_matrix,\n        [0, 0],\n    )\n    propagator_attrs = {\n        \"ifm_propagator\": ifm_propagator,\n        \"weights_propagator\": weights_propagator,\n        \"bias_propagator\": bias_propagator,\n    }\n\n    # Compute operation for the OFM DMA pipeline\n    dma_ofm = dma_ofm_compute(\n        conv, ofm_layout, ofm_zero_point, ofm_scale, ofm_channels, attrs=propagator_attrs\n    )\n    return dma_ofm\n\n\n@register_matcher\ndef match_ethosu_conv2d(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU Conv2D.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    convert_to_nhcwb16 = write.op.input_tensors[0]\n    if convert_to_nhcwb16.op.name != \"ethosu_convert_to_nhcwb16\":\n        return None\n    conv2d = convert_to_nhcwb16.op.input_tensors[0]\n    if conv2d.op.name != \"ethosu_conv2d\":\n        return None\n    pad = conv2d.op.input_tensors[0]\n    if pad.op.name != \"ethosu_pad\":\n        return None\n    upscale = pad.op.input_tensors[0]\n    if upscale.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc = upscale.op.input_tensors[0]\n    if convert_to_nhwc.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read = convert_to_nhwc.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n        conv2d.op.input_tensors[1],\n        conv2d.op.input_tensors[2],\n    ]\n\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n        write.op.attrs[\"weights_propagator\"],\n        write.op.attrs[\"bias_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    # Use channels from the weights tensor since that its shape doesn't change during layout\n    # conversion\n    ifm_channels = int(input_tensors[1].shape[3])\n    ofm_channels, kernel_height, kernel_width = (int(axis) for axis in input_tensors[1].shape[0:3])\n    kernel_elements = kernel_height * kernel_width\n\n    is_part_kernel = device_config.is_partkernel(\n        conv2d.op.name, ifm_channels, ifm_dtype, kernel_elements\n    )\n    subkernels = len(\n        device_config.get_kernel_steps(\n            conv2d.op.name, kernel_height, kernel_width, ifm_dtype, is_part_kernel\n        )\n    )\n\n    output_layout = convert_to_nhcwb16.op.attrs[\"layout\"]\n    input_layout = convert_to_nhwc.op.attrs[\"layout\"]\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    valid_block_configs = device_config.get_valid_block_configs(\n        propagators[0],\n        conv2d.op.attrs,\n        output_tensor.shape,\n        ofm_channels,\n        ifm_channels,\n        output_layout,\n        input_layout,\n        ifm_dtype,\n        ofm_dtype,\n        kernel_height,\n        kernel_width,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        subkernels,\n        valid_block_configs,\n        1,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/depthwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expressions for depthwise convolutions\"\"\"\nfrom typing import Tuple, Union, List\nimport numpy as np\n\nfrom tvm import te\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\n\nfrom .dma import dma_ofm_compute, dma_ifm_compute\nfrom .common import get_layout_transform_matrices\n\n\ndef depthwise_conv2d_compute(\n    ifm: te.Tensor,\n    weight: te.Tensor,\n    scale_bias: te.Tensor,\n    lut: te.Tensor,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    weight_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    strides: Tuple[int, int],\n    padding: Tuple[int, int, int, int],\n    dilation: Union[Tuple[int, int], List[int]],\n    activation: str,\n    clip_min: int,\n    clip_max: int,\n    rounding_mode: str,\n    upscale: str,\n    ifm_layout: str,\n    ofm_layout: str,\n    ofm_dtype: str,\n) -> te.Tensor:\n    \"\"\"A compute operator representing the capabilities of 2D convolution for the NPU.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    weight : te.Tensor\n        The weight tensor.\n    scale_bias : te.Tensor\n        The packed per-channel weight scale and bias tensor.\n    lut : te.Tensor\n        The look-up table of values to use if activation = \"LUT\".\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    weight_zero_point : int\n        The quantization zero point for the weight tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    strides : tuple\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : tuple\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    dilation : Union[int, tuple, list]\n        The 2 dimensional dilation as (dilation_height, dilation_width).\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale : str\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n    ifm_layout : str\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_dtype : str, optional\n        The Output Feature Map tensor data type. Can be 'int8', 'uint8' or 'int16'.\n\n    Returns\n    -------\n    te.Tensor\n        The OFM tensor.\n\n    \"\"\"\n    assert ifm.shape[0] == 1, f\"Only batch size 1 is supported\"\n    assert ifm_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ofm_layout in {\"NHWC\", \"NHCWB16\"}\n\n    padding = [int(v) for v in padding]\n    stride_h, stride_w = [int(v) for v in strides]\n    dilation_h, dilation_w = [int(v) for v in dilation]\n    channels, kernel_h, kernel_w, _ = [int(v) for v in weight.shape]\n\n    # Compute operation for the IFM DMA pipeline\n    dmaed_ifm = dma_ifm_compute(ifm, ifm_layout, ifm_zero_point, ifm_scale, channels, padding)\n\n    # 2D Depthwise Convolution compute operation\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    ofm_height = (dmaed_ifm.shape[1] - dilated_kernel_h) // stride_h + 1\n    ofm_width = (dmaed_ifm.shape[2] - dilated_kernel_w) // stride_w + 1\n    rh = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rw = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    depthwise_conv2d_attrs = {\n        \"op\": \"ethosu_depthwise_conv2d\",\n        \"weight_zero_point\": weight_zero_point,\n        \"activation\": activation,\n        \"clip_min\": clip_min,\n        \"clip_max\": clip_max,\n        \"rounding_mode\": rounding_mode,\n        \"upscale\": upscale,\n        \"stride_h\": stride_h,\n        \"stride_w\": stride_w,\n        \"dilation_h\": dilation_h,\n        \"dilation_w\": dilation_w,\n    }\n\n    has_lut = activation in (\"TANH\", \"LUT\", \"SIGMOID\")\n\n    # This is a trick to insert the LUT tensor into the TE graph if LUT is present\n    lut_expr = (lut[0] + lut[255]).astype(ifm.dtype) if has_lut else 0\n\n    # Add the LUT tensor to the attributes to be able to later tell which tensor is the LUT\n    if has_lut:\n        depthwise_conv2d_attrs[\"lut\"] = lut\n\n    depthwise = te.compute(\n        (1, ofm_height, ofm_width, channels),\n        lambda nn, hh, ww, cc: te.sum(\n            (\n                dmaed_ifm(\n                    nn, hh * stride_h + rh * dilation_h, ww * stride_w + rw * dilation_w, cc\n                ).astype(ifm.dtype)\n                * weight[cc, rh, rw, 0].astype(ifm.dtype)\n                # This is a trick to load 10 elements of the scale_bias at once, not accurate maths\n                + (scale_bias[cc, 0] * scale_bias[cc, 9] + lut_expr).astype(ifm.dtype)\n            ).astype(ofm_dtype),\n            axis=[rh, rw],\n        ),\n        name=\"ethosu_depthwise_conv2d\",\n        attrs=depthwise_conv2d_attrs,\n    )\n\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(channels)\n\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, stride_h, 0, 0, (dilated_kernel_h - stride_h)],\n        [0, 0, stride_w, 0, (dilated_kernel_w - stride_w)],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    weights_matrix = [\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, kernel_h],\n        [0, 0, 0, 0, kernel_w],\n        [0, 0, 0, 0, 1],\n        [0, 0, 0, 0, 1],\n    ]\n    bias_matrix = [\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 10],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n        weights_matrix = np.matmul(weights_matrix, nhcwb16_to_nhwc).tolist()\n        bias_matrix = np.matmul(bias_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        [0, -padding[0], -padding[1], 0]\n        if ifm_layout == \"NHWC\"\n        else [0, -padding[0], 0, -padding[1], 0],\n    )\n    weights_propagator = Propagator(\n        weights_matrix,\n        [0, 0, 0, 0],\n    )\n    bias_propagator = Propagator(\n        bias_matrix,\n        [0, 0],\n    )\n    propagator_attrs = {\n        \"ifm_propagator\": ifm_propagator,\n        \"weights_propagator\": weights_propagator,\n        \"bias_propagator\": bias_propagator,\n    }\n\n    # Compute operation for the OFM DMA pipeline\n    return dma_ofm_compute(\n        depthwise, ofm_layout, ofm_zero_point, ofm_scale, channels, attrs=propagator_attrs\n    )\n\n\n@register_matcher\ndef match_ethosu_depthwise_conv2d(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU Depthwise Conv2D.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration.\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    convert_to_nhcwb16 = write.op.input_tensors[0]\n    if convert_to_nhcwb16.op.name != \"ethosu_convert_to_nhcwb16\":\n        return None\n    depthwise2d = convert_to_nhcwb16.op.input_tensors[0]\n    if depthwise2d.op.name != \"ethosu_depthwise_conv2d\":\n        return None\n    pad = depthwise2d.op.input_tensors[0]\n    if pad.op.name != \"ethosu_pad\":\n        return None\n    upscale = pad.op.input_tensors[0]\n    if upscale.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc = upscale.op.input_tensors[0]\n    if convert_to_nhwc.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read = convert_to_nhwc.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n        depthwise2d.op.input_tensors[1],\n        depthwise2d.op.input_tensors[2],\n    ]\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n        write.op.attrs[\"weights_propagator\"],\n        write.op.attrs[\"bias_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    channels, kernel_height, kernel_width = (int(axis) for axis in input_tensors[1].shape[0:3])\n\n    subkernels = len(\n        device_config.get_kernel_steps(depthwise2d.op.name, kernel_height, kernel_width, ifm_dtype)\n    )\n\n    output_layout = convert_to_nhcwb16.op.attrs[\"layout\"]\n    input_layout = convert_to_nhwc.op.attrs[\"layout\"]\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    valid_block_configs = device_config.get_valid_block_configs(\n        propagators[0],\n        depthwise2d.op.attrs,\n        output_tensor.shape,\n        channels,\n        channels,\n        output_layout,\n        input_layout,\n        ifm_dtype,\n        ofm_dtype,\n        kernel_height,\n        kernel_width,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        subkernels,\n        valid_block_configs,\n        1,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/dma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unnecessary-lambda\n\"\"\"Tensor Expressions for operations supported by the NPU DMA engine\"\"\"\nfrom typing import Callable, Tuple, Optional, List\n\nimport tvm  # type: ignore\nfrom tvm import te\nfrom tvm.topi.utils import equal_const_int  # type: ignore\n\n\ndef _pad_tensor(\n    tensor: te.Tensor, pad_before: List[int], pad_after: Optional[List[int]] = None\n) -> Callable:\n    \"\"\"Generate a padded tensor.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to pad.\n    pad_before : tuple of int\n        The 'before' padding on each axis.\n    pad_after : tuple of int\n        The 'after' padding on each axis.\n    Returns\n    -------\n    _pad : callable\n        The padded tensor.\n\n    \"\"\"\n    pad_after = pad_after or pad_before\n    dims = len(tensor.shape)\n    assert len(pad_before) == dims\n    assert len(pad_after) == dims\n\n    def _pad(*indices):\n        not_zero = []  # A list of padding conditions that aren't trivial (zero padding)\n        index_tuple = []  # The indices with which to access the padded tensor\n        for i in range(dims):\n            if equal_const_int(pad_before[i], 0) and equal_const_int(pad_after[i], 0):\n                index_tuple.append(indices[i])\n            else:\n                index_tuple.append(indices[i] - pad_before[i])\n                not_zero.append(indices[i] >= pad_before[i])\n                not_zero.append(indices[i] < tensor.shape[i] + pad_before[i])\n        if not_zero:\n            not_zero = tvm.tir.all(*not_zero)\n            return tvm.tir.if_then_else(\n                not_zero, tensor(*index_tuple), tvm.tir.const(0, tensor.dtype)\n            )\n        return tensor(*index_tuple)\n\n    return _pad\n\n\ndef read_compute(\n    tensor: te.Tensor, zero_point: int, scale: float, layout: Optional[str] = None\n) -> te.Tensor:\n    \"\"\"A tensor expression which represents a read.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to read.\n    zero_point : int\n        The zero point of the tensor.\n    scale : float\n        The scale of the tensor.\n    layout : Optional[str]\n        The layout of the tensor, either NHWC or NHCWB16.\n\n    Returns\n    -------\n    te.Tensor\n        The tensor having been read.\n\n    \"\"\"\n    read_attrs = {\n        \"op\": \"ethosu_read\",\n        \"zero_point\": zero_point,\n        \"scale\": scale,\n    }\n\n    if layout:\n        assert layout in {\"NHWC\", \"NHCWB16\"}\n        read_attrs[\"layout\"] = layout\n\n    return te.compute(tensor.shape, lambda *i: tensor(*i), name=\"ethosu_read\", attrs=read_attrs)\n\n\ndef write_compute(\n    tensor: te.Tensor,\n    zero_point: int,\n    scale: float,\n    layout: Optional[str] = None,\n    attrs: dict = None,\n) -> te.Tensor:\n    \"\"\"A tensor expression which represents a write.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to write.\n    zero_point : int\n        The zero point of the tensor.\n    scale : float\n        The scale of the tensor.\n    layout : Optional[str]\n        The layout of the tensor, either NHWC or NHCWB16.\n    attrs : dict, optional\n        Additional attributes to add to the compute op.\n\n    Returns\n    -------\n    te.Tensor\n        The tensor having been written.\n\n    \"\"\"\n\n    if not attrs:\n        attrs = {}\n\n    write_attrs = {\n        \"op\": \"ethosu_write\",\n        \"zero_point\": zero_point,\n        \"scale\": scale,\n    }\n\n    if layout:\n        assert layout in {\"NHWC\", \"NHCWB16\"}\n        write_attrs[\"layout\"] = layout\n\n    write_attrs = {**write_attrs, **attrs}\n    return te.compute(\n        tensor.shape,\n        lambda *i: tensor(*i),\n        name=\"ethosu_write\",\n        attrs=write_attrs,\n    )\n\n\ndef convert_to_nhwc_compute(tensor: te.Tensor, layout: str, channels: int) -> te.Tensor:\n    \"\"\"Converts a tensor into NHWC layout if it's in NHWCB16 layout.\n\n    When the current layout is NHCWB16, a reduce sum operation is inserted\n    to ensure that the whole of the input tensor has a data dependency on\n    the copy operation. Without this, TVM removes compute that is deemed to\n    be unnecessary, which causes strides for the NPU to be calculated\n    incorrectly.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to convert.\n    layout : str\n        The layout of the tensor, either NHWC or NHCWB16.\n    channels : int\n        The number of valid channels for the tensor.\n\n    Returns\n    -------\n    te.Tensor\n        The converted tensor in NHWC layout.\n\n    \"\"\"\n    assert layout in {\"NHWC\", \"NHCWB16\"}\n    convert_to_nhwc_attrs = {\n        \"op\": \"ethosu_convert_to_nhwc\",\n        \"layout\": layout,\n    }\n    if layout == \"NHCWB16\":\n        rc = te.reduce_axis((0, 16), name=\"rc\")\n        return te.compute(\n            (tensor.shape[0], tensor.shape[1], tensor.shape[3], channels),\n            lambda nn, hh, ww, cc: te.sum(\n                tensor(nn, hh, te.indexdiv(cc, 16), ww, te.indexmod(rc, 16)), axis=rc\n            ),\n            name=\"ethosu_convert_to_nhwc\",\n            attrs=convert_to_nhwc_attrs,\n        )\n\n    return te.compute(\n        tensor.shape,\n        lambda *i: tensor(*i),\n        name=\"ethosu_convert_to_nhwc\",\n        attrs=convert_to_nhwc_attrs,\n    )\n\n\ndef convert_to_nhcwb16_compute(tensor: te.Tensor, layout: str, channels: int) -> te.Tensor:\n    \"\"\"Converts a tensor into NHCWB16 layout if it's in NHWC layout.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to convert.\n    layout : str\n        The layout of the tensor, either NHWC or NHCWB16.\n    channels : int\n        The number of valid channels for the tensor.\n\n    Returns\n    -------\n    te.Tensor\n        The converted tensor in NHCWB16 layout.\n\n    \"\"\"\n    assert layout in {\"NHWC\", \"NHCWB16\"}\n    convert_to_nhcwb16_attrs = {\n        \"op\": \"ethosu_convert_to_nhcwb16\",\n        \"layout\": layout,\n    }\n    if layout == \"NHCWB16\":\n        out_channel_bricks = te.indexdiv(channels - 1, 16) + 1\n        output_shape = (1, tensor.shape[1], out_channel_bricks, tensor.shape[2], 16)\n        return te.compute(\n            output_shape,\n            lambda nn, hh, cc, ww, cb: tvm.tir.if_then_else(\n                cc * 16 + cb < channels,\n                tensor(nn, hh, ww, cc * 16 + cb),\n                tvm.tir.IntImm(tensor.dtype, 0),\n            ),\n            name=\"ethosu_convert_to_nhcwb16\",\n            attrs=convert_to_nhcwb16_attrs,\n        )\n\n    return te.compute(\n        tensor.shape,\n        lambda *i: tensor(*i),\n        name=\"ethosu_convert_to_nhcwb16\",\n        attrs=convert_to_nhcwb16_attrs,\n    )\n\n\ndef pad_compute(tensor: te.Tensor, padding: tuple) -> te.Tensor:\n    \"\"\"Pad an NHWC tensor in the height and width axes.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to pad.\n    padding : tuple\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n\n    Returns\n    -------\n    te.Tensor\n        The padded tensor.\n\n    \"\"\"\n    pad_top, pad_left, pad_down, pad_right = padding\n    pad_before = [0, int(pad_top), int(pad_left), 0]\n    pad_after = [0, int(pad_down), int(pad_right), 0]\n    pad_attrs = {\n        \"op\": \"ethosu_pad\",\n    }\n    shape = tensor.shape\n    return te.compute(\n        (shape[0], shape[1] + pad_top + pad_down, shape[2] + pad_left + pad_right, shape[3]),\n        lambda nn, hh, ww, cc: _pad_tensor(tensor, pad_before, pad_after)(nn, hh, ww, cc),\n        name=\"ethosu_pad\",\n        attrs=pad_attrs,\n    )\n\n\ndef upscale_compute(tensor: te.Tensor, upscale_factor: int) -> te.Tensor:\n    \"\"\"Apply upscaling to an NHWC tensor.\n\n    Parameters\n    ----------\n    tensor : te.Tensor\n        The tensor to pad.\n    upscale_factor : int\n        The factor by which to apply upscaling.\n\n    Returns\n    -------\n    te.Tensor\n        The upscaled tensor.\n\n    \"\"\"\n    shape = tensor.shape\n\n    reason = f\"The compiler only supports 2x2 upscaling, but factor was {upscale_factor}.\"\n    assert upscale_factor in (1, 2), reason\n    new_shape = (shape[0], shape[1] * upscale_factor, shape[2] * upscale_factor, shape[3])\n\n    upscale_attrs = {\"op\": \"ethosu_upscale\"}\n\n    return te.compute(\n        new_shape,\n        lambda nn, hh, ww, cc: tensor(nn, hh // upscale_factor, ww // upscale_factor, cc),\n        name=\"ethosu_upscale\",\n        attrs=upscale_attrs,\n    )\n\n\ndef dma_ifm_compute(\n    ifm: te.Tensor,\n    layout: str,\n    zero_point: int,\n    scale: float,\n    channels: int,\n    padding: Tuple[int, int, int, int],\n    upscale_factor: Optional[int] = 1,\n) -> te.Tensor:\n    \"\"\"A sequence of compute operators representing the DMA capabilities for an IFM.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map (IFM) tensor.\n    layout : str\n        The layout of the data, either NHWC or NHCWB16.\n    zero_point : int\n        The zero point of the data.\n    scale : float\n        The scale of the data.\n    channels : int\n        The number of valid channels for the data.\n    padding : tuple\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    upscale_factor : Optional[int]\n        The factor by which to apply upscaling. By default there will be no upscaling.\n\n    Returns\n    -------\n    te.Tensor\n        The dma-ed IFM tensor.\n\n    \"\"\"\n    read_ifm = read_compute(ifm, zero_point, scale, layout=layout)\n    convert_to_nhwc_ifm = convert_to_nhwc_compute(read_ifm, layout, channels)\n    upscale_ifm = upscale_compute(convert_to_nhwc_ifm, upscale_factor)\n    return pad_compute(upscale_ifm, padding)\n\n\ndef dma_ofm_compute(\n    ofm: te.Tensor, layout: str, zero_point: int, scale: float, channels: int, attrs: dict = None\n) -> te.Tensor:\n    \"\"\"A sequence of compute operators representing the DMA capabilities for an OFM.\n\n    Parameters\n    ----------\n    ofm : te.Tensor\n        The Output Feature Map (OFM) tensor.\n    layout : str\n        The layout of the data, either NHWC or NHCWB16.\n    zero_point : int\n        The zero point of the data.\n    scale : float\n        The scale of the data.\n    channels : int\n        The number of valid channels for the data.\n    attrs : dict, optional\n        Additional attributes to add to the write compute op.\n\n\n    Returns\n    -------\n    te.Tensor\n        The dma-ed OFM tensor.\n\n    \"\"\"\n    if not attrs:\n        attrs = {}\n    convert_to_nhcwb16_ofm = convert_to_nhcwb16_compute(ofm, layout, channels)\n    return write_compute(convert_to_nhcwb16_ofm, zero_point, scale, layout=layout, attrs=attrs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/identity.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expression for identity\"\"\"\nimport numpy as np\nfrom tvm import te\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\n\nfrom .dma import read_compute, write_compute\n\n\ndef identity_compute(\n    ifm: te.Tensor,\n    lut: te.Tensor,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    activation: str,\n) -> te.Tensor:\n    \"\"\"A compute operator for the NPU identity operator.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    lut : te.Tensor\n        The look-up table values to use if activation is \"LUT\", \"TANH\" or \"SIGMOID\".\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n\n    Returns\n    -------\n    te.Tensor\n        The Output Feature Map tensor.\n    \"\"\"\n    dmaed_ifm = read_compute(ifm, ifm_zero_point, ifm_scale)\n    id_attrs = {\"op\": \"ethosu_identity\", \"activation\": activation}\n\n    has_lut = activation in (\"TANH\", \"LUT\", \"SIGMOID\")\n\n    # This is a trick to insert the LUT tensor into the TE graph if LUT is present\n    lut_expr = (lut[0] + lut[255]).astype(ifm.dtype) if has_lut else 0\n\n    # Add the LUT tensor to the attributes to be able to later tell which tensor is the LUT\n    if has_lut:\n        id_attrs[\"lut\"] = lut\n\n    identity = te.compute(\n        ifm.shape,\n        lambda *i: (dmaed_ifm(*i) + lut_expr).astype(ifm.dtype),\n        name=\"ethosu_identity\",\n        attrs=id_attrs,\n    )\n    length = len(ifm.shape)\n    ifm_matrix = np.identity(length + 1)\n    offset = np.zeros(length, dtype=\"int64\")\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        offset.tolist(),\n    )\n    propagator_attrs = {\n        \"ifm_propagator\": ifm_propagator,\n    }\n    return write_compute(identity, ofm_zero_point, ofm_scale, attrs=propagator_attrs)\n\n\n@register_matcher\ndef match_ethosu_identity(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU identity.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    identity = write.op.input_tensors[0]\n    if identity.op.name != \"ethosu_identity\":\n        return None\n    read = identity.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n    ]\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    input_tensors_shape = input_tensors[0].shape\n    length = len(input_tensors_shape)\n    assert length <= 4, \"Input tensor shape must be <= 4 for the identity operator\"\n    channels = int(input_tensors_shape[length - 1]) if length >= 3 else 1\n\n    subkernels = len(device_config.get_kernel_steps(identity.op.name, 1, 1, ifm_dtype))\n\n    input_layout = output_layout = \"NHWC\"\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    valid_block_configs = device_config.get_valid_block_configs(\n        propagators[0],\n        identity.op.attrs,\n        output_tensor.shape,\n        channels,\n        channels,\n        output_layout,\n        input_layout,\n        ifm_dtype,\n        ofm_dtype,\n        1,\n        1,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        subkernels,\n        valid_block_configs,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/inline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Tensor Expressions for operations that will be inlined\"\"\"\nimport numpy as np  # type: ignore\n\nfrom tvm.contrib.ethosu.cascader import TESubgraph, InlinePart, Propagator, register_matcher\n\n\nINLINE_OPS = {\"T_reshape\", \"T_strided_slice\"}\n\n\n@register_matcher\ndef match_ethosu_inline(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an operator that will be inlined.\n\n    If the Tensor Expression matches, an InlinePart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned. This matcher is\n    naive and assumes nothing about the compute of the Tensor Expression. Therefore,\n    the resulting InlinePart will have full-tensor dependencies (i.e. each output\n    element depends on every input element).\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, InlinePart]\n        The created InlinePart if there was a match, otherwise None.\n\n    \"\"\"\n    if output_tensor.op.name not in INLINE_OPS:\n        return None\n\n    input_tensors = output_tensor.op.input_tensors\n    propagators = []\n    output_dims = len(output_tensor.shape)\n    for input_tensor in input_tensors:\n        input_dims = len(input_tensor.shape)\n        transform_matrix = np.zeros((input_dims + 1, output_dims + 1))\n        for i, axis in enumerate(input_tensor.shape):\n            transform_matrix[i, output_dims] = int(axis)\n        transform_matrix[input_dims, output_dims] = 1\n        offset_vector = np.zeros(input_dims, dtype=\"int64\")\n        propagators.append(\n            Propagator(\n                transform_matrix.tolist(),\n                offset_vector.tolist(),\n            )\n        )\n\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    return InlinePart(\n        subgraph,\n        propagators,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expressions for poolings\"\"\"\nfrom typing import Tuple\n\nimport numpy as np\nfrom tvm import te\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\n\nfrom .dma import dma_ofm_compute, dma_ifm_compute\nfrom .common import get_layout_transform_matrices\n\n\ndef pooling_compute(\n    ifm: te.Tensor,\n    lut: te.Tensor,\n    pooling_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    pool_shape: Tuple[int, int],\n    ofm_channels: int,\n    strides: Tuple[int, int],\n    padding: Tuple[int, int, int, int],\n    activation: str,\n    clip_min: int,\n    clip_max: int,\n    rounding_mode: str,\n    upscale: str,\n    ifm_layout: str,\n    ofm_layout: str,\n) -> te.Tensor:\n    \"\"\"A compute operator representing the capabilities of pooling for the NPU.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    lut : te.Tensor\n        The look-up table of values to use if activation = \"LUT\".\n    pooling_type: str\n        The type of the pooling. \"AVG\" - average pool,   \"MAX\" - max pool.\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    pool_shape : Tuple[int, int]\n        The 2 dimensional pool shape as (pool_shape_height, pool_shape_width).\n    ofm_channels : int\n        The number of the Output Feature Map channels\n    strides : Tuple[int, int]\n        The 2 dimensional strides as (stride_height, stride_width).\n    padding : Tuple[int, int, int, int]\n        The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    upscale : str\n        The 2x2 upscaling mode to apply to the Input Feature Map tensor.\n            \"NONE\" - no upscaling.\n            \"NEAREST\" - upscale using nearest neighbour.\n            \"ZEROS\" - upscale using zeros.\n    ifm_layout : str\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    te.Tensor\n        The OFM tensor.\n    \"\"\"\n    assert ifm.shape[0] == 1\n    assert ifm_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ofm_layout in {\"NHWC\", \"NHCWB16\"}\n\n    padding = [int(v) for v in padding]\n    stride_h, stride_w = [int(v) for v in strides]\n    pool_shape_h, pool_shape_w = [int(v) for v in pool_shape]\n    upscale_factor = 2 if upscale != \"NONE\" else 1\n\n    # Compute operation for the IFM DMA pipeline\n    dmaed_ifm = dma_ifm_compute(\n        ifm, ifm_layout, ifm_zero_point, ifm_scale, ofm_channels, padding, upscale_factor\n    )\n\n    # Pooling compute operation\n    ofm_height = (dmaed_ifm.shape[1] - pool_shape_h) // stride_h + 1\n    ofm_width = (dmaed_ifm.shape[2] - pool_shape_w) // stride_w + 1\n    rh = te.reduce_axis((0, pool_shape_h), name=\"ry\")\n    rw = te.reduce_axis((0, pool_shape_w), name=\"rx\")\n\n    pooling_attrs = {\n        \"op\": \"ethosu_pooling\",\n        \"pooling_type\": pooling_type,\n        \"pool_shape_h\": pool_shape_h,\n        \"pool_shape_w\": pool_shape_w,\n        \"stride_h\": stride_h,\n        \"stride_w\": stride_w,\n        \"activation\": activation,\n        \"clip_min\": clip_min,\n        \"clip_max\": clip_max,\n        \"rounding_mode\": rounding_mode,\n        \"upscale\": upscale,\n    }\n\n    has_lut = activation in (\"TANH\", \"LUT\", \"SIGMOID\")\n\n    # This is a trick to insert the LUT tensor into the TE graph if LUT is present\n    lut_expr = (lut[0] + lut[255]).astype(ifm.dtype) if has_lut else 0\n\n    # Add the LUT tensor to the attributes to be able to later tell which tensor is the LUT\n    if has_lut:\n        pooling_attrs[\"lut\"] = lut\n\n    pooling = te.compute(\n        (1, ofm_height, ofm_width, ofm_channels),\n        lambda nn, hh, ww, cc: te.max(\n            (dmaed_ifm(nn, hh * stride_h + rh, ww * stride_w + rw, cc) + lut_expr).astype(\n                ifm.dtype\n            ),\n            axis=[rh, rw],\n        ),\n        name=\"ethosu_pooling\",\n        attrs=pooling_attrs,\n    )\n\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(int(ofm_channels))\n\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, stride_h, 0, 0, (pool_shape_h - stride_h)],\n        [0, 0, stride_w, 0, (pool_shape_w - stride_w)],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        [0, -padding[0], -padding[1], 0]\n        if ifm_layout == \"NHWC\"\n        else [0, -padding[0], 0, -padding[1], 0],\n    )\n    propagator_attrs = {\n        \"ifm_propagator\": ifm_propagator,\n    }\n\n    # Compute operation for the OFM DMA pipeline\n    return dma_ofm_compute(\n        pooling, ofm_layout, ofm_zero_point, ofm_scale, ofm_channels, attrs=propagator_attrs\n    )\n\n\n@register_matcher\ndef match_ethosu_pooling(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU Pooling.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    convert_to_nhcwb16 = write.op.input_tensors[0]\n    if convert_to_nhcwb16.op.name != \"ethosu_convert_to_nhcwb16\":\n        return None\n    pool2d = convert_to_nhcwb16.op.input_tensors[0]\n    if pool2d.op.name != \"ethosu_pooling\":\n        return None\n    pad = pool2d.op.input_tensors[0]\n    if pad.op.name != \"ethosu_pad\":\n        return None\n    upscale = pad.op.input_tensors[0]\n    if upscale.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc = upscale.op.input_tensors[0]\n    if convert_to_nhwc.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read = convert_to_nhwc.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n    ]\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    # Use channels from a stage of TE graph where the IFM is always NHWC\n    channels = int(pool2d.shape[3])\n    pool_shape_h = int(pool2d.op.attrs[\"pool_shape_h\"])\n    pool_shape_w = int(pool2d.op.attrs[\"pool_shape_w\"])\n\n    subkernels = len(\n        device_config.get_kernel_steps(pool2d.op.name, pool_shape_h, pool_shape_w, ifm_dtype)\n    )\n\n    output_layout = convert_to_nhcwb16.op.attrs[\"layout\"]\n    input_layout = convert_to_nhwc.op.attrs[\"layout\"]\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    valid_block_configs = device_config.get_valid_block_configs(\n        propagators[0],\n        pool2d.op.attrs,\n        output_tensor.shape,\n        channels,\n        channels,\n        output_layout,\n        input_layout,\n        ifm_dtype,\n        ofm_dtype,\n        pool_shape_h,\n        pool_shape_w,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        subkernels,\n        valid_block_configs,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/te/unary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Tensor Expressions for unary_elementwise for the NPU\"\"\"\n\nimport numpy as np\nfrom tvm import te\nfrom tvm.contrib.ethosu.cascader import TESubgraph, EthosuPart, Propagator, register_matcher\nfrom .dma import dma_ofm_compute, dma_ifm_compute\nfrom .common import get_layout_transform_matrices\n\n\ndef unary_elementwise_compute(\n    ifm: te.Tensor,\n    lut: te.Tensor,\n    operator_type: str,\n    ifm_scale: float,\n    ifm_zero_point: int,\n    ofm_scale: float,\n    ofm_zero_point: int,\n    ofm_channels: int,\n    activation: str,\n    clip_min: int,\n    clip_max: int,\n    rounding_mode: str,\n    ifm_layout: str,\n    ofm_layout: str,\n) -> te.Tensor:\n    \"\"\"A compute operator representing the capabilities of unary_elementwise for the NPU.\n\n    Parameters\n    ----------\n    ifm : te.Tensor\n        The Input Feature Map tensor (IFM).\n    lut : te.Tensor\n        The look-up table values to use if activation = \"LUT\".\n    operator_type: str\n        The type of the unary elementwise operator.\n            \"ABS\"\n            \"CLZ\"\n    ifm_scale : float\n        The quantization scale for the Input Feature Map tensor.\n    ifm_zero_point : int\n        The quantization zero point for the Input Feature Map tensor.\n    ofm_scale : float\n        The quantization scale for the Output Feature Map tensor.\n    ofm_zero_point : int\n        The quantization zero point for the Output Feature Map tensor.\n    ofm_channels : int\n        The number of OFM channels.\n    activation : str\n        The activation function to use.\n            \"NONE\" - no activation function.\n            \"CLIP\" - clip the output between clip_min and clip_max.\n            \"TANH\" - tanh activation function.\n            \"SIGMOID\" - sigmoid activation function.\n            \"LUT\" - use a look-up table to perform the activation function.\n    clip_min : int\n        The minimum clipping value if activation = \"CLIP\".\n    clip_max : int\n        The maximum clipping value if activation = \"CLIP\".\n    rounding_mode : str\n        The rounding mode to apply to the Output Feature Map tensor.\n            \"TFL\" - Tensorflow Lite rounding scheme.\n            \"TRUNCATE\" - Truncate towards zero.\n            \"NATURAL\" - Round to nearest value, with x.5 rounded up towards +infinity.\n    ifm_layout : str, optional\n        The layout of the Input Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n    ofm_layout : str, optional\n        The layout of the Output Feature Map tensor. Can be \"NHWC\" or \"NHCWB16\".\n\n    Returns\n    -------\n    te.Tensor\n        The OFM tensor.\n\n    \"\"\"\n    assert ifm.shape[0] == 1\n    assert ifm_layout in {\"NHWC\", \"NHCWB16\"}\n    assert ofm_layout in {\"NHWC\", \"NHCWB16\"}\n\n    # Changing the ifm and ofm scale to conform with that expected by Vela API\n    ofm_scale = ifm_scale / ofm_scale\n    ifm_scale = 1.0\n\n    # Compute operation for the IFM DMA pipeline\n    dmaed_ifm = dma_ifm_compute(\n        ifm, ifm_layout, ifm_zero_point, ifm_scale, ofm_channels, (0, 0, 0, 0)\n    )\n\n    # Unary elementwise compute operation\n    ofm_height = dmaed_ifm.shape[1]\n    ofm_width = dmaed_ifm.shape[2]\n\n    unary_elementwise_attrs = {\n        \"op\": \"ethosu_unary_elementwise\",\n        \"operator_type\": operator_type,\n        \"activation\": activation,\n        \"clip_min\": clip_min,\n        \"clip_max\": clip_max,\n        \"rounding_mode\": rounding_mode,\n    }\n\n    def clz_imp(inp):\n        # Assuming that it's a 32 bit int\n        return 32 - te.log2(inp)\n\n    operators = {\"ABS\": te.abs, \"CLZ\": clz_imp}\n\n    unary_elementwise = te.compute(\n        (1, ofm_height, ofm_width, ofm_channels),\n        lambda nn, hh, ww, cc: operators[operator_type](\n            dmaed_ifm(nn, hh, ww, cc).astype(ifm.dtype)\n        ),\n        name=\"ethosu_unary_elementwise\",\n        attrs=unary_elementwise_attrs,\n    )\n\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(int(ofm_channels))\n\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n\n    ifm_propagator = Propagator(\n        ifm_matrix,\n        [0, 0, 0, 0] if ifm_layout == \"NHWC\" else [0, 0, 0, 0, 0],\n    )\n    propagator_attrs = {\"ifm_propagator\": ifm_propagator}\n\n    # Compute operation for the OFM DMA pipeline\n    return dma_ofm_compute(\n        unary_elementwise,\n        ofm_layout,\n        ofm_zero_point,\n        ofm_scale,\n        ofm_channels,\n        attrs=propagator_attrs,\n    )\n\n\n@register_matcher\ndef match_ethosu_unary_elementwise(output_tensor, device_config):\n    \"\"\"Match a Tensor Expression corresponding to an NPU Unary Elementwise.\n\n    If the Tensor Expression matches, an EthosuPart will be created that models the\n    matched Tensor Expression. Otherwise, None will be returned.\n\n    Parameters\n    ----------\n    output_tensor : tvm.te.Tensor\n        The tensor to attempt to match with.\n    device_config : EthosuDeviceConfig\n        Target device configuration\n\n    Returns\n    -------\n    Union[None, EthosuPart]\n        The created EthosuPart if there was a match, otherwise None.\n\n    \"\"\"\n    write = output_tensor\n    if write.op.name != \"ethosu_write\":\n        return None\n    convert_to_nhcwb16 = write.op.input_tensors[0]\n    if convert_to_nhcwb16.op.name != \"ethosu_convert_to_nhcwb16\":\n        return None\n    unary_elementwise = convert_to_nhcwb16.op.input_tensors[0]\n    if unary_elementwise.op.name != \"ethosu_unary_elementwise\":\n        return None\n    pad = unary_elementwise.op.input_tensors[0]\n    if pad.op.name != \"ethosu_pad\":\n        return None\n    upscale = pad.op.input_tensors[0]\n    if upscale.op.name != \"ethosu_upscale\":\n        return None\n    convert_to_nhwc = upscale.op.input_tensors[0]\n    if convert_to_nhwc.op.name != \"ethosu_convert_to_nhwc\":\n        return None\n    read = convert_to_nhwc.op.input_tensors[0]\n    if read.op.name != \"ethosu_read\":\n        return None\n\n    input_tensors = [\n        read.op.input_tensors[0],\n    ]\n    subgraph = TESubgraph(input_tensors, output_tensor)\n    propagators = [\n        write.op.attrs[\"ifm_propagator\"],\n    ]\n    ifm_dtype = input_tensors[0].dtype\n    ofm_dtype = output_tensor.dtype\n\n    output_layout = convert_to_nhcwb16.op.attrs[\"layout\"]\n    input_layout = convert_to_nhwc.op.attrs[\"layout\"]\n    output_quantum = device_config.get_output_quantum(output_layout)\n\n    block_config = device_config.get_elementwise_block_config(\n        propagators[0],\n        None,\n        unary_elementwise.op.attrs,\n        output_tensor.shape,\n        output_layout,\n        input_layout,\n        None,\n        ifm_dtype,\n        ofm_dtype,\n    )\n\n    return EthosuPart(\n        subgraph,\n        propagators,\n        output_quantum,\n        1,\n        block_config,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm(R) Ethos(TM)-U NPU TIR codegen modules.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/binary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract information from the binary_elementwise operators in TIR.\"\"\"\nfrom typing import Tuple\nimport tvm\nfrom .utils import get_outer_loops, get_op_attrs\nfrom .dma import get_ifm_params, get_ofm_params\nfrom .spec import SerialActivation, SerialBinaryElementwise\nfrom .producers_consumers import ProducersConsumers\n\n\ndef ignore_cast(tir_load: tvm.tir.expr.Load) -> tvm.tir.Var:\n    \"\"\"When the datatype of the ifm, ifm2 and ofm do not match,\n    casts are inserted in TE to handle the difference in these types.\n    Since TIR is not directly run on the NPU we can simply ignore\n    these, and allow the NPU to handle the difference in datatypes\n    itself.\n\n    Parameters\n    ----------\n    tir_load : tvm.tir.expr.Load\n\n    Returns\n    -------\n    tvm.tir.Var\n    \"\"\"\n    return tir_load.value if isinstance(tir_load, tvm.tir.Cast) else tir_load\n\n\ndef get_binary_elementwise_params(\n    stmt: tvm.tir.AttrStmt, producers_consumers: ProducersConsumers\n) -> Tuple[SerialBinaryElementwise, tvm.tir.Var, tvm.tir.Var]:\n    \"\"\"Get the parameters necessary to construct a call_extern for a binary_elementwise.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a binary elementwise loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    SerialBinaryElementwise\n        The parameters needed to construct a binary elementwise operator.\n    output_pointer : tvm.tir.Var\n        The output pointer of the binary elementwise operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the binary elementwise output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    reversed_operands = attrs[\"reversed_operands\"]\n\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    op = ignore_cast(inner.value)\n    input_pointer = ignore_cast(op.a).buffer.data\n    input_pointer1 = ignore_cast(op.b).buffer.data\n\n    if reversed_operands:\n        input_pointer, input_pointer1 = input_pointer1, input_pointer\n    output_pointer = inner.buffer.data\n    # Get feature map info\n    serial_ifm, _ = get_ifm_params(input_pointer, producers_consumers, stmt)\n    serial_ifm2, _ = get_ifm_params(input_pointer1, producers_consumers, stmt)\n    serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(\n        output_pointer, producers_consumers, stmt\n    )\n    # Get activation info\n    serial_activation = SerialActivation(\n        op=attrs[\"activation\"], clip_min=attrs[\"clip_min\"], clip_max=attrs[\"clip_max\"]\n    )\n    return (\n        SerialBinaryElementwise(\n            ifm=serial_ifm,\n            ifm2=serial_ifm2,\n            ofm=serial_ofm,\n            operator_type=attrs[\"operator_type\"],\n            reversed_operands=reversed_operands,\n            activation=serial_activation,\n            rounding_mode=attrs[\"rounding_mode\"],\n            block_config=serial_block_config,\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"The integration of the Arm(R) Ethos(TM)-U NPU TIR compiler.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.expr_functor import ExprMutator\nfrom tvm.driver.build_module import schedule_to_module\n\nfrom . import passes as ethosu_passes\nfrom .scheduler import schedule\nfrom .. import util\n\n\ndef lower_ethosu(sch, args, const_dict, name=\"main\"):\n    \"\"\"Lower a schedule to TIR for the Arm(R) Ethos(TM)-U NPU target.\n\n    The resulting TIR module will contain a single function\n    that consists of a sequence of tir.call_extern to NPU\n    operations.\n\n    Parameters\n    ----------\n    sch : tvm.te.Schedule\n        The schedule to be lowered.\n    args : Union[list of tvm.te.Tensor, TEGraph]\n        The input/output tensors.\n    const_dict : dict of int to numpy.ndarray\n        The constant dictionary.\n    name : str, optional\n        The name of the lowered primitive function.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The lowered TIR module.\n    const_dict : dict of int to numpy.ndarray\n        The modified constant dictionary.\n\n    \"\"\"\n    if not isinstance(args, list):\n        args = list(args.inputs) + list(args.outputs)\n    # config setup\n    curr_pass_ctx = tvm.ir.transform.PassContext.current()\n    curr_cfg = dict()\n    for key, value in curr_pass_ctx.config.items():\n        curr_cfg[key] = value\n    tir_compiler_cfg = {\n        \"tir.LoopPartition\": {\n            \"partition_const_loop\": True,\n            \"no_unroll_loop_with_extent_one\": True,\n        },\n        \"tir.UnrollLoop\": {\"auto_max_depth\": -1},\n        \"tir.noalias\": True,\n        \"tir.debug_keep_trivial_loop\": True,\n    }\n    # Merge two configs\n    curr_cfg = {**curr_cfg, **tir_compiler_cfg}\n\n    sch = sch.normalize()\n\n    with tvm.transform.PassContext(config=curr_cfg):\n        mod = schedule_to_module(sch, args, name)\n\n        mod = tvm.tir.transform.Simplify()(mod)\n        mod = ethosu_passes.RemoveConcatenates()(mod)\n        mod = tvm.tir.transform.InjectRollingBuffer()(mod)\n        mod = tvm.tir.transform.StorageFlatten(64)(mod)\n        mod = tvm.tir.transform.UnrollLoop()(mod)\n        mod = tvm.tir.transform.Simplify()(mod)\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        mod = ethosu_passes.RemoveZeroStores()(mod)\n        mod = tvm.tir.transform.Simplify()(mod)\n        mod = tvm.tir.transform.RemoveNoOp()(mod)\n        mod = ethosu_passes.ReplaceOperators()(mod)\n        mod = tvm.tir.transform.RemoveNoOp()(mod)\n        mod, const_dict = ethosu_passes.EncodeConstants(const_dict)(mod)\n        mod = ethosu_passes.HoistAllocates()(mod)\n        mod = tvm.tir.transform.RemoveNoOp()(mod)\n        mod, const_dict = ethosu_passes.MergeConstants(const_dict)(mod)\n        mod = ethosu_passes.CopyComputeReordering()(mod)\n\n        # When striping is enabled and if storage_rewrite is not run\n        # the striping results in incorrect code generation. This needs\n        # further investigation. Until such a time that is fixed, disable_storage_rewrite\n        # user directive will be overridden if striping is enabled.\n        disable_storage_rewrite = curr_cfg.get(\"tir.disable_storage_rewrite\", False)\n        if not disable_storage_rewrite or util.is_striping_enabled():\n            mod = tvm.tir.transform.StorageRewrite()(mod)\n\n        mod = tvm.tir.transform.RemoveNoOp()(mod)\n        mod = ethosu_passes.AnnotateAllocates()(mod)\n        mod, const_dict = ethosu_passes.CreatePrimFuncWithoutConstants(const_dict)(mod)\n    return mod, const_dict\n\n\ndef lower_to_te(prim_func):\n    \"\"\"Lower a Relay primitive function to a Tensor Expression in an unscheduled CachedFunc.\n\n    Parameters\n    ----------\n    prim_func : tvm.relay.Function\n        The Relay function to lower.\n\n    Returns\n    -------\n    out : CachedFunc\n        The lowered Tensor Expression as part of a CachedFunc.\n\n    \"\"\"\n    f = tvm._ffi.get_global_func(\"relay.backend.LowerToTE\")\n    return f(prim_func)\n\n\nclass ExtractConstants(ExprMutator):\n    \"\"\"The actual mutator pass to extract the constants from a function and replace them with\n    Vars so the function can be lowered to a TE graph. Additionally returns all the values of\n    the constants extracted.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.constants = []\n        self.const_vars = []\n\n    def visit_constant(self, const):\n        if isinstance(const.checked_type, relay.ty.TensorType):\n            self.constants.append(const.data.asnumpy())\n            name = \"p\" + str(len(self.constants))\n            var = relay.var(type_annotation=const.checked_type, name_hint=name)\n            self.const_vars.append(var)\n            return var\n\n        return const\n\n    def visit_function(self, fn):\n        new_body = self.visit(fn.body)\n        new_params = list(fn.params) + self.const_vars\n        return relay.Function(new_params, new_body)\n\n    def extract_constants(self, func):\n        new_func = self.visit(func)\n        return new_func, self.constants\n\n\ndef extract_constants(func):\n    \"\"\"Extract the constants from a function and replace them with\n    Vars so the function can be lowered to a TE graph. Additionally\n    returns all the values of the constants extracted.\n\n    Parameters\n    ----------\n    func : tvm.relay.Function\n        The Relay function from which to extract constants.\n\n    Returns\n    -------\n    new_func : tvm.relay.Function\n        The Relay function with constants replaced by vars.\n    const_dict : dict of int to numpy.ndarray\n        A dict of the extracted constants keyed by their param index.\n\n    \"\"\"\n    const_dict = {}\n    params = len(func.params)\n    new_func, consts = ExtractConstants().extract_constants(func)\n    for i, const in enumerate(consts):\n        const_dict[params + i] = const\n\n    new_func = tvm.relay.transform.InferType()(tvm.IRModule.from_expr(new_func))[\"main\"]\n    return new_func, const_dict\n\n\n@util.create_npu_function_pass(opt_level=1)\nclass LowerToTIR:\n    \"\"\"A pass that lowers NPU Relay functions to TIR. This pass wraps\n    the _lower_to_tir pass that operates function->function, while this\n    is IRModule->IRModule.\n\n    Attributes\n    ----------\n    scheduler : callable\n        A function to schedule NPU operations. For example,\n        scheduler.py/copy_constants.\n    \"\"\"\n\n    def __init__(self, scheduler):\n        self.scheduler = scheduler\n\n    def transform_npu_function(self, _, func: relay.Function) -> relay.Function:\n        \"\"\"Lower NPU functions to TIR.\"\"\"\n\n        tir_mod, const_dict = _lower_to_tir(func, self.scheduler)\n\n        for param in const_dict.keys():\n            const_dict[param] = tvm.nd.array(const_dict[param])\n\n        compiler_name = \"ethos-u\"\n        primfunc = tir_mod[\"main\"]\n        primfunc = primfunc.with_attr(\"global_symbol\", func.attrs[\"global_symbol\"])\n        primfunc = primfunc.with_attr(\"ethos-u.constants\", const_dict)\n        primfunc = primfunc.with_attr(\"target\", tvm.target.Target(compiler_name))\n        return primfunc\n\n    def __call__(self, *args, **kwargs):\n        pass\n\n\ndef _lower_to_tir(func, cascader=None):\n    \"\"\"Lower a Relay function to TIR for the Arm(R) Ethos(TM)-U NPU target.\n\n    The Relay function should only contain operations supported\n    by the NPU.\n\n    Parameters\n    ----------\n    func : tvm.relay.Function\n        The Relay function to lower.\n    cascader : Callable\n        An optional cascading function,\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The lowered TIR module.\n    consts : dict of int to numpy.ndarray\n        A dict of the extracted constants keyed by their param index.\n\n    \"\"\"\n    func, consts = extract_constants(func)\n    mod = tvm.IRModule.from_expr(func)\n    func = relay.transform.InferType()(mod)[\"main\"]\n    cached_func = lower_to_te(func)\n    s = schedule(cached_func, consts, cascader)\n    mod, consts = lower_ethosu(s, cached_func, consts)\n    return mod, consts\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/convolution.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract parameters from the convolution operators in TIR.\"\"\"\nimport math\nimport tvm\nfrom ethosu.vela import api as vapi\nfrom ..vela_api import SCALE_BIAS_LENGTH, get_accelerator_config\nfrom .utils import get_outer_loops, get_op_attrs, get_base_address, get_loads, get_stores\nfrom .dma import get_ifm_params, get_ofm_params\nfrom .spec import SerialKernel, SerialAddressRange, SerialActivation, Serial2DConvolution\n\n\ndef get_conv2d_params(stmt, producers_consumers):\n    \"\"\"Get the parameters necessary to construct a call_extern for a 2D convolution.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a convolution loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    Serial2DConvolution\n        The parameters needed to construct a 2D convolution.\n    output_pointer : tvm.tir.Var\n        The output pointer of the convolution operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the convolution output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n\n    \"\"\"\n    accel_config = get_accelerator_config()\n\n    attrs, body = get_op_attrs(stmt)\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    rh = inner\n    rw = rh.body\n    rc = rw.body\n    # loads = [output, input, weights, scale_bias, scale_bias, LUT, LUT]\n    loads = get_loads(rc.body)\n    # stores = [output]\n    stores = get_stores(rc.body)\n    input_pointer = loads[1].buffer.data\n    output_pointer = stores[0].buffer.data\n    # Get feature map info\n    serial_ifm, serial_padding = get_ifm_params(input_pointer, producers_consumers, stmt)\n    serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(\n        output_pointer, producers_consumers, stmt\n    )\n    # Get kernel info\n    serial_kernel = SerialKernel(\n        width=int(rw.extent),\n        height=int(rh.extent),\n        stride_w=int(attrs[\"stride_w\"]),\n        stride_h=int(attrs[\"stride_h\"]),\n        dilation_w=int(attrs[\"dilation_w\"]),\n        dilation_h=int(attrs[\"dilation_h\"]),\n    )\n    # Get scale_bias info\n    scale_bias_load = loads[3]\n    scale_bias_base = [get_base_address(index) for index in scale_bias_load.indices]\n    # Get weight info\n    weight_load = loads[2]\n    weight_base = [get_base_address(index) for index in weight_load.indices]\n    channels = serial_ofm[3] if isinstance(serial_ofm[3], int) else serial_ofm[3].value\n\n    if accel_config == vapi.NpuAccelerator.Ethos_U65_512:\n        scale_bias_length = SCALE_BIAS_LENGTH * math.ceil(channels / 2)\n        scale_bias2_length = SCALE_BIAS_LENGTH * math.floor(channels / 2)\n\n        serial_scale_bias = SerialAddressRange(\n            address=tvm.tir.BufferLoad(scale_bias_load.buffer, scale_bias_base),\n            length=scale_bias_length,\n        )\n        serial_scale_bias2 = SerialAddressRange(\n            address=tvm.tir.BufferLoad(\n                scale_bias_load.buffer, [scale_bias_base[0] + scale_bias_length]\n            ),\n            length=scale_bias2_length,\n        )\n\n        weight_length = (\n            channels * serial_kernel[0] * serial_kernel[1] * math.ceil(rc.extent.value / 2)\n        )\n        weight2_length = (\n            channels * serial_kernel[0] * serial_kernel[1] * math.floor(rc.extent.value / 2)\n        )\n\n        serial_weight = SerialAddressRange(\n            address=tvm.tir.BufferLoad(weight_load.buffer, weight_base),\n            length=weight_length,\n        )\n        serial_weight2 = SerialAddressRange(\n            address=tvm.tir.BufferLoad(weight_load.buffer, [weight_base[0] + weight_length]),\n            length=weight2_length,\n        )\n    else:\n        scale_bias_length = SCALE_BIAS_LENGTH * channels\n\n        serial_scale_bias = SerialAddressRange(\n            address=tvm.tir.BufferLoad(scale_bias_load.buffer, scale_bias_base),\n            length=scale_bias_length,\n        )\n        # Insert -1s into the spec to denote the absence of the other pointer\n        serial_scale_bias2 = SerialAddressRange(\n            address=tvm.tir.IntImm(\"int8\", -1),\n            length=tvm.tir.IntImm(\"int8\", -1),\n        )\n\n        weight_length = channels * serial_kernel[0] * serial_kernel[1] * rc.extent.value\n\n        serial_weight = SerialAddressRange(\n            address=tvm.tir.BufferLoad(weight_load.buffer, weight_base),\n            length=weight_length,\n        )\n        serial_weight2 = SerialAddressRange(\n            address=tvm.tir.IntImm(\"int8\", -1),\n            length=tvm.tir.IntImm(\"int8\", -1),\n        )\n    # Get activation info\n    serial_activation = SerialActivation(\n        op=attrs[\"activation\"], clip_min=attrs[\"clip_min\"], clip_max=attrs[\"clip_max\"]\n    )\n    return (\n        Serial2DConvolution(\n            ifm=serial_ifm,\n            ofm=serial_ofm,\n            kernel=serial_kernel,\n            weight=serial_weight,\n            weight2=serial_weight2,\n            weight_zero_point=attrs[\"weight_zero_point\"],\n            scale_bias=serial_scale_bias,\n            scale_bias2=serial_scale_bias2,\n            padding=serial_padding,\n            activation=serial_activation,\n            rounding_mode=attrs[\"rounding_mode\"],\n            upscale=attrs[\"upscale\"],\n            block_config=serial_block_config,\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/depthwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract information from the depthwise convolution operators in TIR.\"\"\"\nfrom typing import Tuple\nimport tvm\nfrom ..vela_api import SCALE_BIAS_LENGTH\nfrom .utils import get_outer_loops, get_op_attrs, get_base_address, get_loads, get_stores\nfrom .dma import get_ifm_params, get_ofm_params\nfrom .spec import (\n    SerialKernel,\n    SerialAddressRange,\n    SerialActivation,\n    Serial2DDepthwise,\n)\nfrom .producers_consumers import ProducersConsumers\n\n\ndef get_depthwise_conv2d_params(\n    stmt: tvm.tir.AttrStmt, producers_consumers: ProducersConsumers\n) -> Tuple[Serial2DDepthwise, tvm.tir.Var, tvm.tir.Var]:\n    \"\"\"Get the parameters necessary to construct a call_extern for a depthwise_conv2d.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a depthwise loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    Serial2DDepthwise\n        The parameters needed to construct a 2D depthwise.\n    output_pointer : tvm.tir.Var\n        The output pointer of the convolution operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the convolution output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    rh = inner\n    rw = rh.body\n    # loads = [output, input, weights, scale_bias, scale_bias]\n    loads = get_loads(rw.body)\n    # stores = [output]\n    stores = get_stores(rw.body)\n    input_pointer = loads[1].buffer.data\n    output_pointer = stores[0].buffer.data\n    # Get feature map info\n    serial_ifm, serial_padding = get_ifm_params(input_pointer, producers_consumers, stmt)\n    serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(\n        output_pointer, producers_consumers, stmt\n    )\n    # Get kernel info\n    serial_kernel = SerialKernel(\n        width=int(rw.extent),\n        height=int(rh.extent),\n        stride_w=int(attrs[\"stride_w\"]),\n        stride_h=int(attrs[\"stride_h\"]),\n        dilation_w=int(attrs[\"dilation_w\"]),\n        dilation_h=int(attrs[\"dilation_h\"]),\n    )\n    # Get scale_bias info\n    scale_bias_load = loads[3]\n    scale_bias_base = [get_base_address(index) for index in scale_bias_load.indices]\n    serial_scale_bias = SerialAddressRange(\n        address=tvm.tir.BufferLoad(scale_bias_load.buffer, scale_bias_base),\n        length=SCALE_BIAS_LENGTH * serial_ofm[3],\n    )\n    # Get weight info\n    weight_load = loads[2]\n    weight_base = [get_base_address(index) for index in weight_load.indices]\n    serial_weight = SerialAddressRange(\n        address=tvm.tir.BufferLoad(weight_load.buffer, weight_base),\n        length=serial_ofm[3] * serial_kernel[0] * serial_kernel[1],\n    )\n    # Get activation info\n    serial_activation = SerialActivation(\n        op=attrs[\"activation\"], clip_min=attrs[\"clip_min\"], clip_max=attrs[\"clip_max\"]\n    )\n\n    return (\n        Serial2DDepthwise(\n            ifm=serial_ifm,\n            ofm=serial_ofm,\n            kernel=serial_kernel,\n            weight=serial_weight,\n            weight_zero_point=attrs[\"weight_zero_point\"],\n            scale_bias=serial_scale_bias,\n            padding=serial_padding,\n            activation=serial_activation,\n            rounding_mode=attrs[\"rounding_mode\"],\n            upscale=\"NONE\",\n            block_config=serial_block_config,\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/dma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract parameters from the DMA operators in TIR.\"\"\"\nfrom typing import NamedTuple, Union\nimport tvm\nfrom .utils import get_outer_loops, get_base_address, get_strides, get_op_attrs\nfrom .spec import SerialBlockConfig, SerialFeatureMap, SerialPadding\n\n\ndef get_pad_params(stmt):\n    \"\"\"Get the padding parameters from a pad loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a pad loop nest.\n\n    Returns\n    -------\n    pad : SerialPadding\n        The serializable padding.\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    _, body = get_op_attrs(stmt)\n    n, h, w, c, _, inner = get_outer_loops(body, \"NHWC\")\n    output_pointer = inner.buffer.data\n    pad = SerialPadding(top=0, left=0, bottom=0, right=0)\n    if isinstance(inner.value, tvm.tir.Call):\n        input_pointer = inner.value.args[1].buffer.data\n    else:\n        input_pointer = inner.value.buffer.data\n        return pad, input_pointer, output_pointer\n\n    padded_shape = [n.extent, h.extent, w.extent, c.extent]\n\n    def _visit(expr):\n        if isinstance(expr, tvm.tir.expr.LT):\n            var = expr.a\n            val = expr.b\n            if var == h.loop_var:\n                pad.bottom = padded_shape[1] - val\n            else:\n                pad.right = padded_shape[2] - val\n        elif isinstance(expr, tvm.tir.expr.LE):\n            var = expr.b\n            val = expr.a\n            if var == h.loop_var:\n                pad.top = val\n            else:\n                pad.left = val\n\n    cond = inner.value.args[0]\n    tvm.tir.stmt_functor.post_order_visit(cond, _visit)\n    return (\n        pad,\n        input_pointer,\n        output_pointer,\n    )\n\n\ndef get_upscale_params(stmt):\n    \"\"\"Get the upscale parameters from a loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of an upscale loop nest.\n\n    Returns\n    -------\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n    \"\"\"\n    _, body = get_op_attrs(stmt)\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    if isinstance(inner.value, tvm.tir.Call):\n        input_pointer = inner.value.args[1].buffer.data\n    else:\n        input_pointer = inner.value.buffer.data\n    output_pointer = inner.buffer.data\n    return (input_pointer, output_pointer)\n\n\ndef get_convert_to_nhwc_params(stmt):\n    \"\"\"Get the true number of channels from a convert_to_nhwc loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a convert_to_nhwc loop nest.\n\n    Returns\n    -------\n    int\n        The true number of channels.\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, _, _, c, _, inner = get_outer_loops(body, \"NHWC\")\n\n    # Ignore the reduce sum operation inserted to ensure\n    # compute that is deemed uneccesary isn't removed by TVM.\n    if attrs[\"layout\"] == \"NHCWB16\":\n        inner = inner.body\n        input_pointer = inner.value.b.buffer.data\n    else:\n        input_pointer = inner.value.buffer.data\n\n    output_pointer = inner.buffer.data\n    return c.extent, input_pointer, output_pointer\n\n\ndef get_convert_to_nhcwb16_params(stmt):\n    \"\"\"Get the true number of channels from a convert_to_nhcwb16 loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a convert_to_nhcwb16 loop nest.\n\n    Returns\n    -------\n    out_channels : int\n        The true number of channels.\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, _, _, c, b, inner = get_outer_loops(body, attrs[\"layout\"])\n    output_pointer = inner.buffer.data\n    if isinstance(inner.value, tvm.tir.Call):\n        cond = inner.value.args[0]\n        out_channels = cond.b.value\n        input_pointer = inner.value.args[1].buffer.data\n    else:\n        input_pointer = inner.value.buffer.data\n        out_channels = c.extent * b.extent if attrs[\"layout\"] == \"NHCWB16\" else c.extent\n\n    return out_channels, input_pointer, output_pointer\n\n\nclass Tiles(NamedTuple):\n    height_0: tvm.tir.expr.IntImm\n    height_1: tvm.tir.expr.IntImm\n    width_0: tvm.tir.expr.IntImm\n    address_0: Union[tvm.tir.expr.BufferLoad, int]\n    address_1: Union[tvm.tir.expr.BufferLoad, int]\n    address_2: Union[tvm.tir.expr.BufferLoad, int]\n\n\ndef create_tiles(stmt: tvm.tir.stmt.AttrStmt) -> Tiles:\n    \"\"\"Given an AttrStmt this function returns a Tiles instance\n    containing the tiles' addresses and dimensions.\n\n    When rolling buffers are not used only tile0 is used.\n    Otherwise, when rolling buffers are used, the statement contains\n    modulo arithmetic operations, which are unsupported by the NPU.\n    To support this scenario more than one tile is used.\n    In particular, when the rolling variable is the height one\n    tile0 and tile2 are used, otherwise, when the rolling variable\n    is the width one, tile0 and tile1 are used.\n\n    As an example consider this statement:\n\n    // attr [iter_var(i0, )] pragma_op = \"ethosu_read\"\n    // attr [iter_var(i0, )] pragma_zero_point = 0\n    // attr [iter_var(i0, )] pragma_layout = \"NHCWB16\"\n    // attr [iter_var(i0, )] pragma_scale = 1f\n    for (i0, 0, 1) {\n      for (i1, 0, 6) {\n        for (i2, 0, 1) {\n          for (i3, 0, 1) {\n            for (i4, 0, 16) {\n              ethosu_read[((i1*16) + i4)] = ethosu_write[((floormod((i1 + 4), 6)*16) + i4)]\n            }\n          }\n        }\n      }\n    }\n\n    You can see from the floormod expression floormod((i1 + 4), 6)\n    that the rolling variable is i1, that is, the height one.\n    In this case tile0 and tile2 are used.\n    The height of tile0 will be 6 - 4 = 2, and height of tile2 will be 4.\n    Both the width of tile0 and tile2 will be equal to the extent of the width variable.\n    Also, the addresses are set accordingly.\n    When the rolling variable is the width one a simmetric approach will be used.\n\n    It is worth mentioning that only the height of tile0, the height of tile1,\n    and the width of tile0 must be computed, the other ones can be inferred.\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, h, w, _, _, inner = get_outer_loops(body, attrs[\"layout\"])\n    base_address = [get_base_address(index) for index in inner.value.indices]\n    read_stmt = inner.value\n    floor_mod_mul = None\n\n    def _compute_stride(for_stmt):\n        stride = 1\n        while isinstance(for_stmt.body, tvm.tir.For):\n            for_stmt = for_stmt.body\n            stride *= for_stmt.extent\n        return stride\n\n    def _get_floor_mod_mul(stmt):\n        nonlocal floor_mod_mul\n        if (\n            isinstance(stmt, tvm.tir.expr.Mul)\n            and isinstance(stmt.b, tvm.tir.expr.IntImm)\n            and isinstance(stmt.a, tvm.tir.FloorMod)\n            and isinstance(stmt.a.b, tvm.tir.expr.IntImm)\n            and isinstance(stmt.a.a, tvm.tir.expr.Add)\n            and isinstance(stmt.a.a.a, tvm.tir.expr.Var)\n            and isinstance(stmt.a.a.b, tvm.tir.expr.IntImm)\n        ):\n            floor_mod_mul = stmt\n\n    tvm.tir.stmt_functor.post_order_visit(read_stmt, _get_floor_mod_mul)\n    if floor_mod_mul is not None:\n        rolling_var = floor_mod_mul.a.a.a\n        count = 0\n\n        def _count_var(var):\n            nonlocal count\n            if var == rolling_var:\n                count += 1\n\n        tvm.tir.stmt_functor.ir_transform(inner, _count_var, None, [\"tir.Var\"])\n        if count == 2:\n            stride = floor_mod_mul.b\n            tile_length = floor_mod_mul.a.b - floor_mod_mul.a.a.b\n            if rolling_var == h.loop_var and _compute_stride(h) == stride:\n                return Tiles(\n                    height_0=tile_length,\n                    height_1=0,\n                    width_0=w.extent,\n                    address_0=tvm.tir.BufferLoad(inner.value.buffer, base_address),\n                    address_1=0,\n                    address_2=tvm.tir.BufferLoad(inner.value.buffer, [0]),\n                )\n            if rolling_var == w.loop_var and _compute_stride(w) == stride:\n                return Tiles(\n                    height_0=h.extent,\n                    height_1=h.extent,\n                    width_0=tile_length,\n                    address_0=tvm.tir.BufferLoad(inner.value.buffer, base_address),\n                    address_1=tvm.tir.BufferLoad(inner.value.buffer, [0]),\n                    address_2=0,\n                )\n\n    return Tiles(\n        height_0=h.extent,\n        height_1=0,\n        width_0=w.extent,\n        address_0=tvm.tir.BufferLoad(inner.value.buffer, base_address),\n        address_1=0,\n        address_2=0,\n    )\n\n\ndef get_read_params(stmt):\n    \"\"\"Get the feature map parameters from a read loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a read loop nest.\n\n    Returns\n    -------\n    SerialFeatureMap\n        The serializable feature map.\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, h, w, c, _, inner = get_outer_loops(body, attrs[\"layout\"])\n    input_pointer = inner.value.buffer.data\n    output_pointer = inner.buffer.data\n\n    # Needed for stride calculation, can replace with\n    # inner.value.buffer.strides in future.\n    assert len(inner.value.indices) == 1, \"Ethos-U DMA expects flattened buffers\"\n    stride_vars = [h.loop_var, w.loop_var, c.loop_var]\n    strides = get_strides(inner.value.indices[0], stride_vars)\n\n    data_type = inner.buffer.data.type_annotation.element_type.dtype\n    tiles = create_tiles(stmt)\n    return (\n        SerialFeatureMap(\n            data_type=data_type,\n            height=h.extent,\n            width=w.extent,\n            channels=c.extent,\n            tile_height_0=tiles.height_0,\n            tile_height_1=tiles.height_1,\n            tile_width_0=tiles.width_0,\n            tile_address_0=tiles.address_0,\n            tile_address_1=tiles.address_1,\n            tile_address_2=tiles.address_2,\n            tile_address_3=0,\n            scale=attrs[\"scale\"],\n            zero_point=attrs[\"zero_point\"],\n            layout=attrs[\"layout\"],\n            stride_h=strides[0],\n            stride_w=strides[1],\n            stride_c=strides[2],\n        ),\n        input_pointer,\n        output_pointer,\n    )\n\n\ndef get_write_params(stmt):\n    \"\"\"Get the feature map parameters from a write loop nest.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a write loop nest.\n\n    Returns\n    -------\n    SerialFeatureMap\n        The serializable feature map.\n    input_pointer : tvm.tir.Var\n        The pointer consumed by the operation.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, h, w, c, _, inner = get_outer_loops(body, attrs[\"layout\"])\n    input_pointer = inner.value.buffer.data\n    output_pointer = inner.buffer.data\n\n    # Needed for stride calculation, can replace with\n    # inner.value.buffer.strides in future.\n    assert len(inner.indices) == 1, \"Ethos-U DMA expects flattened buffers\"\n    stride_vars = [h.loop_var, w.loop_var, c.loop_var]\n    strides = get_strides(inner.indices[0], stride_vars)\n\n    base_address = [get_base_address(index) for index in inner.indices]\n    data_type = inner.buffer.data.type_annotation.element_type.dtype\n    if \"block_config_height\" in attrs:\n        block_config = SerialBlockConfig(\n            height=int(attrs[\"block_config_height\"]),\n            width=int(attrs[\"block_config_width\"]),\n            depth=int(attrs[\"block_config_depth\"]),\n        )\n    else:\n        block_config = SerialBlockConfig(0, 0, 0)\n    return (\n        SerialFeatureMap(\n            data_type=data_type,\n            height=h.extent,\n            width=w.extent,\n            channels=c.extent,\n            tile_height_0=h.extent,\n            tile_height_1=0,\n            tile_width_0=w.extent,\n            tile_address_0=tvm.tir.BufferLoad(inner.buffer, base_address),\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=attrs[\"scale\"],\n            zero_point=attrs[\"zero_point\"],\n            layout=attrs[\"layout\"],\n            stride_h=strides[0],\n            stride_w=strides[1],\n            stride_c=strides[2],\n        ),\n        block_config,\n        input_pointer,\n        output_pointer,\n    )\n\n\ndef get_ifm_params(pointer, producers_consumers, stmt):\n    \"\"\"Get the parameters associated with the DMA capabilities for an IFM.\n\n    Parameters\n    ----------\n    pointer : tvm.tir.Var\n        The pointer that the IFM DMA pipeline produces.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    serial_ifm : SerialFeatureMap\n        The serializable IFM.\n    serial_padding : SerialPadding\n        The serializable padding.\n\n    \"\"\"\n    pad = producers_consumers.get_producer(pointer, stmt)\n    serial_padding, input_pointer, _ = get_pad_params(pad)\n    upscale = producers_consumers.get_producer(input_pointer, pad)\n    input_pointer, _ = get_upscale_params(upscale)\n    convert_to_nhwc = producers_consumers.get_producer(input_pointer, upscale)\n    in_channels, input_pointer, _ = get_convert_to_nhwc_params(convert_to_nhwc)\n    read = producers_consumers.get_producer(input_pointer, convert_to_nhwc)\n    serial_ifm, _, _ = get_read_params(read)\n    serial_ifm.channels = in_channels\n\n    floor_mod_stmt = None\n    for_stmt = None\n\n    def _get_buffer_var(stmt):\n        nonlocal for_stmt\n        nonlocal floor_mod_stmt\n        if isinstance(stmt, tvm.tir.For):\n            for_stmt = stmt\n        if isinstance(stmt, tvm.tir.FloorMod):\n            floor_mod_stmt = stmt\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, _get_buffer_var)\n\n    if floor_mod_stmt is not None:\n        layout = get_op_attrs(read)[0][\"layout\"]\n        channels = serial_ifm.channels\n        if for_stmt.body.loop_var == floor_mod_stmt.a.a.a:\n            height_a = floor_mod_stmt.b - floor_mod_stmt.a.b\n            height_b = serial_ifm.height\n            serial_ifm.height = height_a + height_b\n            serial_ifm.tile_height_0 = serial_ifm.height\n            address = serial_ifm.tile_address_0\n            offset = (\n                height_a * (channels // 16 + 1) * serial_ifm.width * 16\n                if layout == \"NHCWB16\"\n                else height_a * serial_ifm.width * channels\n            )\n            serial_ifm.tile_address_0 = tvm.tir.BufferLoad(\n                address.buffer, [address.indices[0] - offset]\n            )\n        else:\n            width_a = floor_mod_stmt.b - floor_mod_stmt.a.b\n            width_b = serial_ifm.width\n            serial_ifm.width = width_a + width_b\n            serial_ifm.tile_width_0 = serial_ifm.width\n            address = serial_ifm.tile_address_0\n            offset = width_a * 16 if layout == \"NHCWB16\" else width_a * channels\n            serial_ifm.tile_address_0 = tvm.tir.BufferLoad(\n                address.buffer, [address.indices[0] - offset]\n            )\n    return serial_ifm, serial_padding\n\n\ndef get_ofm_params(pointer, producers_consumers, stmt):\n    \"\"\"Get the parameters associated with the DMA capabilities for an OFM.\n\n    Parameters\n    ----------\n    pointer : tvm.tir.Var\n        The pointer that the OFM DMA pipeline consumes.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    serial_ifm : SerialFeatureMap\n        The serializable OFM.\n    serial_block_config : SerialBlockConfig\n        The serializable block config.\n    output_pointer : tvm.tir.Var\n        The pointer that the OFM DMA pipeline produces.\n    is_allocator : bool\n        Whether this operator allocates its output.\n\n    \"\"\"\n    convert_to_nhcwb16 = producers_consumers.get_consumer(pointer, stmt)\n    out_channels, _, output_pointer = get_convert_to_nhcwb16_params(convert_to_nhcwb16)\n    write = producers_consumers.get_consumer(output_pointer, convert_to_nhcwb16)\n    serial_ofm, serial_block_config, _, output_pointer = get_write_params(write)\n    is_allocator = True\n\n    producer = producers_consumers.get_producer(output_pointer, write)\n    if producer is None or producer != write:\n        is_allocator = False\n    serial_ofm.channels = out_channels\n    return serial_ofm, serial_block_config, output_pointer, is_allocator\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/identity.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract information from the identity operator in TIR.\"\"\"\nfrom typing import Tuple\nimport tvm\nfrom .spec import (\n    SerialBlockConfig,\n    SerialKernel,\n    SerialActivation,\n    SerialPooling,\n    SerialPadding,\n    SerialFeatureMap,\n)\nfrom .utils import get_op_attrs, get_base_address, get_strides, get_loads\nfrom .producers_consumers import ProducersConsumers\n\n\ndef _get_feature_map(stmt: tvm.tir.AttrStmt, fm_type: str) -> Tuple[SerialFeatureMap, tvm.tir.Var]:\n    \"\"\"Get the feature map parameters from a loop nest of any shape (as long there are at\n    most 4 nested loops).\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a loop nest.\n    fm_type: str\n        Either \"ifm\" or \"ofm\", depending on whether it is an input or output feature map\n\n    Returns\n    -------\n    SerialFeatureMap\n        The serializable feature map.\n    output_pointer : tvm.tir.Var\n        The pointer produced by the operation.\n\n    \"\"\"\n    assert fm_type in (\"ifm\", \"ofm\")\n\n    attrs, body = get_op_attrs(stmt)\n\n    loops = []\n    inner = body\n    # extact the loops and the innermost statement\n    while hasattr(inner, \"body\"):\n        loops.append(inner)\n        inner = inner.body\n\n    # If the batch size loop is present, we need to remove it\n    if len(loops) > 3:\n        assert loops[0].extent == 1\n        loops = loops[1:]\n\n    fm_inner = inner.value if fm_type == \"ifm\" else inner\n\n    # Needed for stride calculation, can replace with\n    # inner.value.buffer.strides in future.\n    assert len(fm_inner.indices) == 1, \"Ethos-U passes expect flattened buffers\"\n    stride_vars = [l.loop_var for l in loops]\n    strides = get_strides(fm_inner.indices[0], stride_vars)\n\n    base_address = [get_base_address(index) for index in fm_inner.indices]\n    data_type = inner.buffer.data.type_annotation.element_type.dtype\n\n    serial_feature_map = SerialFeatureMap(\n        data_type=data_type,\n        height=loops[0].extent,\n        width=loops[1].extent if len(loops) > 1 else 1,\n        channels=loops[2].extent if len(loops) > 2 else 1,\n        tile_height_0=loops[0].extent,\n        tile_height_1=0,\n        tile_width_0=loops[1].extent if len(loops) > 1 else 1,\n        tile_address_0=tvm.tir.BufferLoad(fm_inner.buffer, base_address),\n        tile_address_1=0,\n        tile_address_2=0,\n        tile_address_3=0,\n        scale=attrs[\"scale\"],\n        zero_point=attrs[\"zero_point\"],\n        layout=\"NHWC\",\n        stride_h=strides[0] if len(strides) > 0 else 1,\n        stride_w=strides[1] if len(strides) > 1 else 1,\n        stride_c=strides[2] if len(strides) > 2 else 1,\n    )\n\n    output_pointer = inner.buffer.data\n\n    return serial_feature_map, output_pointer\n\n\ndef get_identity_params(\n    stmt: tvm.tir.AttrStmt, producers_consumers: ProducersConsumers\n) -> Tuple[SerialPooling, tvm.tir.Var, tvm.tir.Var]:\n    \"\"\"Get the parameters necessary to construct a call_extern for an identity pooling.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of an identity pooling loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    SerialPooling\n        The parameters needed to construct a 2D pooling.\n    output_pointer : tvm.tir.Var\n        The output pointer of the pooling operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the pooling output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n\n    \"\"\"\n    attrs, _ = get_op_attrs(stmt)\n    # Find the inner loop\n    store = stmt\n    while hasattr(store, \"body\"):\n        store = store.body\n\n    # loads = [input, LUT, LUT]\n    loads = get_loads(store)\n\n    input_pointer = loads[0].buffer.data\n    output_pointer = store.buffer.data\n\n    read = producers_consumers.get_producer(input_pointer, stmt)\n    write = producers_consumers.get_consumer(output_pointer, stmt)\n\n    serial_ifm, _ = _get_feature_map(read, \"ifm\")\n    serial_ofm, write_output_pointer = _get_feature_map(write, \"ofm\")\n\n    replace_pointer = write_output_pointer\n\n    is_allocator = True\n    producer = producers_consumers.get_producer(write_output_pointer, write)\n    if producer is None or producer != write:\n        is_allocator = False\n\n    # TODO: We might want to support stand alone ReLU in the future by adding clip_min and\n    # clip max attributes to the identity operator\n    serial_activation = SerialActivation(op=attrs[\"activation\"], clip_min=0, clip_max=0)\n\n    # Create a serialized identity pooling to be run on the NPU\n    return (\n        SerialPooling(\n            ifm=serial_ifm,\n            ofm=serial_ofm,\n            pooling_type=\"AVG\",\n            pool_shape=SerialKernel(1, 1, 1, 1, 1, 1),\n            padding=SerialPadding(0, 0, 0, 0),\n            activation=serial_activation,\n            upscale=\"NONE\",\n            rounding_mode=\"TFL\",\n            block_config=SerialBlockConfig(0, 0, 0),\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/passes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, no-else-return, inconsistent-return-statements, too-many-nested-blocks\n\"\"\"The TIR passes to be run on Arm(R) Ethos(TM)-U NPU TIR Compiler.\"\"\"\nfrom collections import namedtuple\nfrom typing import Optional\nimport numpy as np  # type: ignore\n\nimport tvm\nfrom tvm.relay.backend.contrib.ethosu import vela_api\nfrom tvm.relay.backend.contrib.ethosu import tir_to_cs_translator as tirtocs\nfrom ethosu.vela import api as vapi\nfrom .convolution import get_conv2d_params\nfrom .depthwise import get_depthwise_conv2d_params\nfrom .pooling import get_pooling_params\nfrom .binary_elementwise import get_binary_elementwise_params\nfrom .identity import get_identity_params\nfrom .unary_elementwise import get_unary_elementwise_params\nfrom .transform import get_copy_params\nfrom .producers_consumers import ProducersConsumers\n\nfrom .. import _ffi_api\n\n\ndef RemoveZeroStores():\n    \"\"\"This pass removes stores which just store zero to initialise buffers.\n\n    We don't codegen these stores and they otherwise considerably reduce\n    the simplicity of the static traversal of convolution.\"\"\"\n\n    def _remove_zero_store(stmt):\n        if isinstance(stmt.value, tvm.tir.IntImm) and int(stmt.value) == 0:\n            return tvm.tir.Evaluate(tvm.tir.IntImm(\"uint8\", 0))\n        return stmt\n\n    def _ftransform(f, mod, ctx):\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(f.body, _remove_zero_store, None, [\"tir.Store\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.remove_zero_stores\"\n    )\n\n\ndef ReplaceOperators():\n    \"\"\"Replace operators represented as explicit loop nests with call_externs\n    to NPU operators.\"\"\"\n    op_map = {\n        \"ethosu_conv2d\": get_conv2d_params,\n        \"ethosu_copy\": get_copy_params,\n        \"ethosu_depthwise_conv2d\": get_depthwise_conv2d_params,\n        \"ethosu_pooling\": get_pooling_params,\n        \"ethosu_binary_elementwise\": get_binary_elementwise_params,\n        \"ethosu_identity\": get_identity_params,\n        \"ethosu_unary_elementwise\": get_unary_elementwise_params,\n    }\n    producers_consumers = ProducersConsumers()\n    replace_output_pointer = {}\n    pointer_to_extents = {}\n\n    ReplaceInfo = namedtuple(\"ReplaceInfo\", [\"pointer\", \"reallocate\"])\n\n    def _find_pointer_to_extent(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            pointer_to_extents[stmt.buffer_var] = stmt.extents\n\n    def _resolve_pointers(stmt):\n        \"\"\"This pass determines information about the pointers present in the IR.\n        In particular, it associates pointers with both the operations that\n        produce them and the operations that consume them through the\n        pointer_to_producer and pointer_to_consumer dicts.\n\n        Additionally, it determines the extent (size/shape) of each pointer which\n        is required for the _replace_pointers pass which runs later.\"\"\"\n        loads = []\n\n        def _get_loads(stmt):\n            if isinstance(stmt, tvm.tir.BufferLoad):\n                loads.append(stmt.buffer.data)\n\n        buffer_var = None\n\n        def _get_buffer_var(stmt):\n            if isinstance(stmt, tvm.tir.BufferStore):\n                nonlocal buffer_var\n                buffer_var = stmt.buffer.data\n\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if stmt.attr_key == \"pragma_op\":\n                tvm.tir.stmt_functor.post_order_visit(stmt, _get_buffer_var)\n                producers_consumers.add_producer(buffer_var, stmt)\n\n                tvm.tir.stmt_functor.post_order_visit(stmt, _get_loads)\n                for load_pointer in loads:\n                    if load_pointer != buffer_var:\n                        producers_consumers.add_consumer(load_pointer, stmt)\n\n    def _replace_operator(stmt):\n        \"\"\"Replace operators with call_externs, having derived the parameters\n        from the relevant TIR expressions/statements.\n\n        Note the complexity of this pass is mostly from the concept of 'replace\n        pointers'. A call_extern may in principle require information from several\n        loop nests in TIR (each corresponding to a different TE compute op). For\n        example, a convolution operator will have other TE compute ops before and\n        after corresponding to the input/output DMA functionality. Therefore, when\n        the 'central' convolution op is replaced with a call_extern, the memory\n        from the final DMA output op must be hoisted to the location/scope of\n        the call_extern.\n\n        The is done by replacing the pointer corresponding to the current operation\n        with the 'true' output operator through the replace_output_pointer dict.\n        Because of this, the param_func must provide a replace_pointer if the op\n        isn't the true output but instead a no_compile op is.\"\"\"\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            op_name = stmt.value.value\n            if stmt.attr_key == \"pragma_op\" and op_name in op_map:\n                # Get the parameters for the extern call\n                param_func = op_map[op_name]\n                info, output_pointer, replace_pointer, is_allocator = param_func(\n                    stmt, producers_consumers\n                )\n                if replace_pointer is not None:\n                    replace_output_pointer[output_pointer] = ReplaceInfo(\n                        replace_pointer, is_allocator\n                    )\n                # Make the extern call\n                irb = tvm.tir.ir_builder.create()\n                irb.emit(tvm.tir.call_extern(\"handle\", op_name, *info))\n                return irb.get()\n        return None\n\n    def _remove_no_compile(stmt):\n        \"\"\"Certain operators are marked as 'no compile' operators. This means they\n        should be removed from the IR as they are compiled as part of other operators.\n        The IFM DMA operations are an example of this, as they don't get compiled\n        independently but instead get compiled into the operator they're associated with,\n        e.g. a conv2d.\n\n        There are potentially 2 parts to remove for an operator:\n        the allocate for its output and the compute nest itself. For the\n        allocate, we can check if the pointer they reference is produced by a 'no compile'\n        operator. For the compute nest, we can just check the op pragma.\"\"\"\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            # Remove compute nests\n            if stmt.attr_key == \"pragma_op\" and stmt.value.value not in op_map:\n                return tvm.tir.Evaluate(0)\n\n        if isinstance(stmt, tvm.tir.Allocate):\n            # Remove allocates\n            producer = producers_consumers.get_last_producer(stmt.buffer_var)\n            if producer:\n                if producer.attr_key == \"pragma_op\" and producer.value.value not in op_map:\n                    return stmt.body\n\n        return None\n\n    def _replace_pointers(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            # If the allocate allocates a pointer that needs replacing\n            if stmt.buffer_var in replace_output_pointer:\n                replace_pointer, reallocate = replace_output_pointer[stmt.buffer_var]\n                if not reallocate:\n                    return stmt.body\n                # Otherwise, rewrite the allocation statement with the new pointer\n                # and the new extent\n                replace_type = replace_pointer.type_annotation.element_type.dtype\n                replace_extents = pointer_to_extents[replace_pointer]\n                return tvm.tir.Allocate(\n                    replace_pointer, replace_type, replace_extents, stmt.condition, stmt.body\n                )\n        return None\n\n    def _post_transform(stmt):\n        # Replace operators with call_externs\n        result = _replace_operator(stmt)\n        # Remove operators that don't need compiling\n        result = result or _remove_no_compile(stmt)\n        # Replace necessary pointers that were removed in the previous step\n        return result or _replace_pointers(stmt)\n\n    def _ftransform(f, mod, ctx):\n        tvm.tir.stmt_functor.post_order_visit(f.body, _find_pointer_to_extent)\n        tvm.tir.stmt_functor.post_order_visit(f.body, _resolve_pointers)\n        producers_consumers.add_allocate_variables(pointer_to_extents.keys())\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(\n                f.body, None, _post_transform, [\"tir.AttrStmt\", \"tir.Allocate\"]\n            )\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.replace_operators\"\n    )\n\n\ndef DivideConstants(const_dict):\n    \"\"\"This pass rewrites the IR and constant dict such that all constant\n    accesses are at 0 offset and full length (i.e. they read the whole buffer).\n\n    Where necessary, new constants are created in order to ensure the rewrite\n    can take place. As an example, if a convolution is tiled along the channels\n    axis, the accesses to the weights will need to be offset. This pass will\n    create new constants consisting of 'slices' of the weights so each tile\n    of the compute can access one of these 'slices'.\n\n    The purpose of this pass is to transform the IR into a form we can apply\n    constant encoding to (which will compress weights and encode biases).\"\"\"\n    buffer_to_const = {}  # type: ignore\n    new_buffers = []\n    new_consts = []\n    keep_buffers = set()\n    new_const_dict = {}\n\n    def _visit(stmt):\n        new_args = []\n        # We don't want to divide the constant that will be executed on two cores in parallel\n        is_u65_conv2d = (\n            vela_api.get_accelerator_config() == vapi.NpuAccelerator.Ethos_U65_512\n            and stmt.args[0] == \"ethosu_conv2d\"\n        )\n        for i, arg in enumerate(stmt.args):\n            if isinstance(arg, tvm.tir.expr.BufferLoad):\n                # If we're trying to load a buffer that maps to a constant\n                if arg.buffer.data in buffer_to_const:\n                    const = buffer_to_const[arg.buffer.data]\n                    flattened_const_shape = np.prod(const.shape)\n\n                    offset = int(arg.indices[0])\n                    # Note by convention the arg after a constant read is the length of the read\n                    length = int(stmt.args[i + 1])\n                    # If it's anything other than a full read, create a new buffer\n                    if (offset != 0 or flattened_const_shape != length) and not is_u65_conv2d:\n                        out_channels = const.shape[0]\n                        offset_channels = int((offset * out_channels) / flattened_const_shape)\n                        length_channels = int((length * out_channels) / flattened_const_shape)\n                        # split the constant up across channels\n                        split_const = np.split(const, out_channels, axis=0)\n                        # create a new const out of the channels we want to keep\n                        new_const = np.concatenate(\n                            split_const[offset_channels : offset_channels + length_channels], axis=0\n                        )\n                        new_consts.append(new_const)\n                        new_buffer = tvm.tir.decl_buffer(\n                            (length,), arg.dtype, scope=arg.buffer.scope()\n                        )\n                        new_buffers.append(new_buffer)\n                        new_args.append(tvm.tir.expr.BufferLoad(new_buffer, [0]))\n                        continue\n                    keep_buffers.add(arg.buffer.data)\n\n            new_args.append(arg)\n\n        return tvm.tir.Call(stmt.dtype, stmt.op, new_args, stmt.span)\n\n    def _ftransform(f, mod, ctx):\n        for i, param in enumerate(f.params):\n            if i in const_dict:\n                buffer_to_const[param] = const_dict[i]\n                buffer_to_const[f.buffer_map[param].data] = const_dict[i]\n\n        new_body = tvm.tir.stmt_functor.ir_transform(f.body, _visit, None, [\"tir.Call\"])\n        # Both the params and buffer map need updating for the newly introduced buffers\n        new_params = []  # type: ignore\n        new_buffer_map = {}\n        for i, param in enumerate(f.params):\n            buffer = f.buffer_map[param]\n            pointer = buffer.data\n            if pointer in buffer_to_const:\n                if pointer not in keep_buffers:\n                    continue\n                new_const_dict[len(new_params)] = const_dict[i]\n            new_params.append(param)\n            new_buffer_map[param] = buffer\n\n        for i, new_buffer in enumerate(new_buffers):\n            handle = tvm.tir.Var(\"placeholder\", \"handle\")\n            new_params.append(handle)\n            new_buffer_map[handle] = new_buffer\n            new_const_dict[len(new_params) - 1] = new_consts[i]\n\n        new_f = tvm.tir.PrimFunc(\n            new_params,\n            new_body,\n            f.ret_type,\n            new_buffer_map,\n            f.preflattened_buffer_map,\n            f.attrs,\n            f.span,\n        )\n        return new_f\n\n    def _divide_constants(mod):\n        transform_func = tvm.tir.transform.prim_func_pass(\n            _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.divide_constants\"\n        )\n        new_func = transform_func(mod)\n        return new_func, new_const_dict\n\n    return _divide_constants\n\n\ndef EncodeConstants(const_dict):\n    \"\"\"the NPU requires that weights are compressed and bias/scales are 'encoded', both\n    of which are performed by this pass.\n\n    This pass modifies both the constant dict to contain the post-encoding values of the\n    constants and the IR to adjust buffer types/sizes/accesses so they align with the\n    encoded constants. Calls to the Vela API are made to perform the actual compression/\n    encoding.\n\n    \"\"\"\n    new_const_dict = {}\n\n    def collect_encoding_definitions(stmt, old_buffer_to_const):\n        # Map from copy destination to copy source.\n        copy_map = {}\n        # List of buffer copies that occurred\n        copied_buffers = []\n        # List of encoded buffer information\n        constant_buffer_replacements = []\n\n        def _align_scale_bias(tir_extern_call, bias):\n            \"\"\"Align the scale_bias to 16 bytes.\"\"\"\n            value_bytes = bytearray()\n            value_bytes.extend(bias.tobytes())\n            # Align to 16\n            remainder = (len(value_bytes)) % 16\n            if remainder > 0:\n                value_bytes.extend(bytearray(16 - remainder))\n            value = np.frombuffer(value_bytes, dtype=\"uint8\")\n            return value\n\n        accel_config = vela_api.get_accelerator_config()\n\n        def _encode_weights(tir_extern_call, weights):\n            \"\"\"Encode the weights for a TIR extern call.\"\"\"\n            value_bytes = vela_api.encode_weights(tir_extern_call, weights, accel_config)\n            value = np.frombuffer(value_bytes, dtype=\"uint8\")\n            return value\n\n        def _declare_constant_buffer(old_buffer, encoded_constants, split_idx):\n            \"\"\"Create a new buffer and add the old buffer and its pointer to the\n            rewriting maps.\"\"\"\n            new_buffer = tvm.tir.decl_buffer(\n                shape=[len(encoded_constants)],\n                dtype=str(encoded_constants.dtype),\n                name=old_buffer.name + \"_encoded\",\n                scope=old_buffer.scope(),\n            )\n\n            constant_buffer_replacements.append(\n                {\n                    \"old_buffer\": old_buffer,\n                    \"new_buffer\": new_buffer,\n                    \"encoded_constants\": encoded_constants,\n                    \"split_idx\": split_idx,\n                }\n            )\n\n        def _encode_weights_or_bias(buffer1, buffer2, stmt, encode_func):\n            \"\"\"Encode the weights or align the bias either for one or two cores,\n            depending on the variant.\"\"\"\n            constant = old_buffer_to_const[buffer1]\n\n            # If we have just one core, encode the whole constant\n            if buffer2 is None:\n                new_const = encode_func(stmt, constant)\n                return new_const, None\n\n            # Assume that the constant tensor has not been flattened yet\n            assert len(constant.shape) != 1\n            channels = constant.shape[0]\n            split_const = np.split(constant, channels, axis=0)\n\n            const_list = [split_const[i] for i in range(channels) if i % 2 == 0]\n            const_to_encode = np.concatenate(const_list, axis=0)\n\n            new_const = encode_func(stmt, const_to_encode)\n            split_idx = len(new_const)\n\n            # Encode half of the constant separately for the other core if it exists\n            assert buffer1.same_as(buffer2)\n            const2_list = [split_const[i] for i in range(channels) if i % 2 == 1]\n            const2_to_encode = np.concatenate(const2_list, axis=0)\n\n            new_const2 = encode_func(stmt, const2_to_encode)\n            new_const = np.append(new_const, new_const2).astype(\"uint8\")\n\n            return new_const, split_idx\n\n        def _visit(stmt):\n            if isinstance(stmt, tvm.tir.Call):\n                op = str(stmt.args[0].value)\n                # Handle copies as a special-case by propagating the buffer information\n                # from the read to the write pointer.\n                if op == \"ethosu_copy\":\n                    read_buffer = stmt.args[1].buffer\n                    write_buffer = stmt.args[3].buffer\n                    # Assert writing to the base of the write_var (pre-StorageRewrite)\n                    assert list(stmt.args[3].indices) == [0]\n                    assert list(stmt.args[1].indices) == [0]\n                    copied_buffers.append({\"source\": read_buffer, \"dest\": write_buffer})\n                    copy_map[write_buffer] = read_buffer\n\n                ops_with_weights = {\n                    \"ethosu_conv2d\": tirtocs.translate_ethosu_conv2d,\n                    \"ethosu_depthwise_conv2d\": tirtocs.translate_ethosu_depthwise_conv2d,\n                }\n                if op in ops_with_weights:\n                    npu_op, _ = ops_with_weights[op](stmt)\n\n                    # Encode the weights\n                    weights_buffer = npu_op.weights[0].address.buffer\n                    if weights_buffer in copy_map:\n                        weights_buffer = copy_map[weights_buffer]\n\n                    # In case of U65 512 mac variant the weights are split across two cores\n                    # and need to be encoded separately\n                    weights2_buffer = (\n                        npu_op.weights[1].address.buffer\n                        if accel_config == vapi.NpuAccelerator.Ethos_U65_512\n                        else None\n                    )\n                    if weights2_buffer in copy_map:\n                        weights2_buffer = copy_map[weights2_buffer]\n\n                    new_weights, split_idx = _encode_weights_or_bias(\n                        weights_buffer, weights2_buffer, stmt, _encode_weights\n                    )\n                    _declare_constant_buffer(weights_buffer, new_weights, split_idx)\n\n                    # Align the scale_bias to 16 bytes\n                    scale_bias_buffer = npu_op.biases[0].address.buffer\n                    if scale_bias_buffer in copy_map:\n                        scale_bias_buffer = copy_map[scale_bias_buffer]\n                    scale_bias2_buffer = (\n                        npu_op.biases[1].address.buffer\n                        if accel_config == vapi.NpuAccelerator.Ethos_U65_512\n                        else None\n                    )\n                    if scale_bias2_buffer in copy_map:\n                        scale_bias2_buffer = copy_map[scale_bias2_buffer]\n\n                    new_scale_bias, split_idx = _encode_weights_or_bias(\n                        scale_bias_buffer, scale_bias2_buffer, stmt, _align_scale_bias\n                    )\n\n                    _declare_constant_buffer(scale_bias_buffer, new_scale_bias, split_idx)\n\n        tvm.tir.stmt_functor.post_order_visit(stmt, _visit)\n\n        return {\n            \"copied_buffers\": copied_buffers,\n            \"constant_buffer_replacements\": constant_buffer_replacements,\n        }\n\n    def transform_stmt(\n        stmt, buf_remap, var_remap, pointer_to_buffer, new_buffer_to_const, new_buffer_to_split_idx\n    ):\n        def _visit_rewrite(stmt):\n            if isinstance(stmt, tvm.tir.Call):\n                # For extern calls, we need to rewrite pairs of arguments corresponding to\n                # base address load and the length of the load.\n                old_args = list(stmt.args)\n\n                new_args = [stmt.args[0]]\n                for prev_arg, arg in zip(old_args[:-1], old_args[1:]):\n                    # If the previous argument was a load from an\n                    # encoded buffer, the current should be a length.\n                    if (\n                        isinstance(prev_arg, tvm.tir.BufferLoad)\n                        and prev_arg.buffer in new_buffer_to_const\n                    ):\n                        buffer_size = np.prod(list(prev_arg.buffer.shape))\n                        arg = buffer_size\n                        # We have to check for split weights/bias for conv2d and depthwise_conv2d\n                        if old_args[0] in (\"ethosu_conv2d\", \"depthwise_conv2d\"):\n                            # We have split weights/bias\n                            if prev_arg.buffer in new_buffer_to_split_idx:\n                                split_idx = new_buffer_to_split_idx[prev_arg.buffer]\n                                # The first half of the split buffer\n                                if prev_arg.indices[0] == 0:\n                                    arg = split_idx\n                                # the second half of the split buffer\n                                else:\n                                    arg = buffer_size - split_idx\n\n                    new_args.append(arg)\n\n                return tvm.tir.Call(stmt.dtype, stmt.op, new_args, stmt.span)\n\n            if isinstance(stmt, tvm.tir.Allocate):\n                # Where a pointer needs rewriting, the allocate for it must be rewritten\n                allocate_pointer = stmt.buffer_var\n                if allocate_pointer in var_remap:\n                    new_allocate_pointer = var_remap[allocate_pointer]\n                    new_buffer = pointer_to_buffer[new_allocate_pointer]\n\n                    return tvm.tir.Allocate(\n                        new_buffer.data,\n                        new_buffer.dtype,\n                        new_buffer.shape,\n                        stmt.condition,\n                        stmt.body,\n                        stmt.span,\n                    )\n\n            # The following rewrites would be better expressed by just\n            # rewriting the Buffers. However ir_transform doesn't\n            # visit Buffers, so instead we do the next best thing and\n            # rewrite the nodes which contain the Buffers.\n            if isinstance(stmt, tvm.tir.BufferLoad):\n                if stmt.buffer in buf_remap:\n                    new_buffer = buf_remap[stmt.buffer]\n                    new_indices = stmt.indices\n                    offset = new_indices[0]\n                    if offset != 0 and new_buffer in new_buffer_to_split_idx:\n                        offset = new_buffer_to_split_idx[new_buffer]\n                    return tvm.tir.BufferLoad(buf_remap[stmt.buffer], [offset], stmt.span)\n\n            if isinstance(stmt, tvm.tir.AttrStmt):\n                node_pointer = stmt.node\n                if node_pointer in var_remap:\n                    return tvm.tir.AttrStmt(\n                        var_remap[node_pointer],\n                        stmt.attr_key,\n                        stmt.value,\n                        stmt.body,\n                        stmt.span,\n                    )\n\n            return None\n\n        return tvm.tir.stmt_functor.ir_transform(\n            stmt,\n            None,\n            _visit_rewrite,\n            [\"tir.Call\", \"tir.Allocate\", \"tir.BufferLoad\", \"tir.AttrStmt\"],\n        )\n\n    def _ftransform(f, mod, ctx):\n        # Step 0: Unpack the constant dictionary in terms of the\n        # functions buffers.\n        old_buffer_to_const = {}\n        for i, param in enumerate(f.params):\n            if i in const_dict:\n                old_buffer_to_const[f.buffer_map[param]] = const_dict[i]\n\n        # Step 1: Collect information on the buffers that will be\n        # replaced by encodings.\n        buffer_information = collect_encoding_definitions(f.body, old_buffer_to_const)\n\n        # Step 2: Generate variable/buffer remaps, based on the\n        # collected information.\n        buf_remap = {}\n        new_buffer_to_const = {}\n        new_buffer_to_split_idx = {}\n\n        # Any encoded buffers must be replaced\n        for info in buffer_information[\"constant_buffer_replacements\"]:\n            buf_remap[info[\"old_buffer\"]] = info[\"new_buffer\"]\n            new_buffer_to_const[info[\"new_buffer\"]] = info[\"encoded_constants\"]\n\n            if info[\"split_idx\"]:\n                new_buffer_to_split_idx[info[\"new_buffer\"]] = info[\"split_idx\"]\n\n        # Any buffers that are copied into from an encoded buffer must\n        # be replaced.\n        for info in buffer_information[\"copied_buffers\"]:\n            copy_source = info[\"source\"]\n            while copy_source in buf_remap:\n                copy_source = buf_remap[copy_source]\n\n            copy_dest = info[\"dest\"]\n\n            if copy_source.shape != copy_dest.shape or copy_source.dtype != copy_dest.dtype:\n                new_dest = tvm.tir.decl_buffer(\n                    shape=copy_source.shape,\n                    dtype=copy_source.dtype,\n                    name=copy_dest.name,\n                    scope=copy_dest.scope(),\n                )\n                buf_remap[copy_dest] = new_dest\n                if copy_source in new_buffer_to_const:\n                    new_buffer_to_const[new_dest] = new_buffer_to_const[copy_source]\n\n                if copy_source in new_buffer_to_split_idx:\n                    new_buffer_to_split_idx[new_dest] = new_buffer_to_split_idx[copy_source]\n\n        # Define additional dependent lookup tables.\n        var_remap = {old.data: new.data for (old, new) in buf_remap.items()}\n        pointer_to_buffer = {\n            buf.data: buf for (old, new) in buf_remap.items() for buf in [old, new]\n        }\n\n        # Step 3: Then perform the rewrites\n        new_body = transform_stmt(\n            f.body,\n            buf_remap,\n            var_remap,\n            pointer_to_buffer,\n            new_buffer_to_const,\n            new_buffer_to_split_idx,\n        )\n\n        # Step 4: Rewrite the buffer map and const dict to instead use the encoded versions\n        new_buffer_map = {}\n        for i, param in enumerate(f.params):\n            buffer = f.buffer_map[param]\n            if buffer in buf_remap:\n                buffer = buf_remap[buffer]\n\n            if buffer in new_buffer_to_const:\n                new_const_dict[i] = new_buffer_to_const[buffer].flatten()\n            elif buffer in old_buffer_to_const:\n                new_const_dict[i] = old_buffer_to_const[buffer].flatten()\n\n            new_buffer_map[param] = buffer\n\n        new_f = tvm.tir.PrimFunc(\n            f.params,\n            new_body,\n            f.ret_type,\n            new_buffer_map,\n            f.preflattened_buffer_map,\n            f.attrs,\n            f.span,\n        )\n        return new_f\n\n    def _encode_constants(mod):\n        mod, divided_const_dict = DivideConstants(const_dict)(mod)\n        const_dict.clear()\n        for key, value in divided_const_dict.items():\n            const_dict[key] = value\n        transform_func = tvm.tir.transform.prim_func_pass(\n            _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.encode_constants\"\n        )\n        new_func = transform_func(mod)\n        return new_func, new_const_dict\n\n    return _encode_constants\n\n\n# This need to be kept in sync with kDisableLowerTVMBuiltin in include/tvm/tir/transform.h\nDISABLE_LOWER_BUILTIN = \"disable_lower_builtin\"\n\n\ndef AnnotateAllocates():\n    \"\"\"\n    This is pass to annotate all allocate\n    nodes of the PrimFuncs of the microNPU\n    to be not lowered to built-ins.\n    \"\"\"\n\n    def _post_transform(allocate):\n        return tvm.tir.Allocate(\n            buffer_var=allocate.buffer_var,\n            dtype=allocate.dtype,\n            extents=allocate.extents,\n            condition=allocate.condition,\n            body=allocate.body,\n            annotations={DISABLE_LOWER_BUILTIN: True},\n        )\n\n    def _ftransform(f, mod, ctx):\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(f.body, None, _post_transform, [\"tir.Allocate\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.annotate_allocates\"\n    )\n\n\ndef RemoveConcatenates():\n    \"\"\"Remove concatenate operators by modifying the input buffers to write directly into\n    the concatenated buffer with the appropriate offset.\n\n    This pass works in two stages. The first finds every concatenate operation (marked by\n    pragma_op = ethosu_concatenate) and it performs the following analysis. For each buffer\n    that is concatenated, the buffer is marked that it is to be replaced with the concat\n    buffer and the axis along which it is concatenated as well as the offset along that\n    axis is recorded in 'ReplaceInfo'. Once this analysis is completed, the concatenate\n    loop nest along with its buffer realization statements are removed.\n\n    In the second stage, the input buffers to the concatenate operators are rewritten\n    to use the concat buffer directly. This means applying the correct offset to the\n    concatenation axis where ever the buffer is loaded or stored. Additionally, as the\n    realization statements for the concat buffers were removed in the first stage, they\n    are rewritten in place of the input buffer realization with the earliest liveness.\"\"\"\n\n    in_concat = [False]  # Whether the visitor is currently inside a concatenate operator\n    concat_buffers = []  # The buffers produced by concatenate operators\n    buffer_replace_map = {}  # A map of buffers to be replaced with the concat buffer\n    attrs_by_buffer = {}  # AttrStmts by the buffer they reference\n    realizes_by_buffer = {}  # BufferRealize statements by the buffer they reference\n    first_replacements = {}  # The first buffers to be replaced by a given concat buffer\n\n    ReplaceInfo = namedtuple(\"ReplaceInfo\", [\"buffer\", \"axis\", \"offset\"])\n\n    def _get_replace_info(buffer_load, concat_buffer):\n        axis = 0\n        offset = 0\n        dmap = dict()\n\n        for i, index in enumerate(buffer_load.indices):\n            if isinstance(index, tvm.tir.Sub):\n                axis = i\n                dmap = {}\n\n                def _visit(stmt):\n                    if isinstance(stmt, tvm.tir.Var):\n                        dmap[stmt] = tvm.arith.IntervalSet(0, 0)\n\n                tvm.tir.stmt_functor.post_order_visit(index, _visit)\n                offset = abs(int(tvm.arith.Analyzer().int_set(index, dmap).max_value))\n        return ReplaceInfo(concat_buffer, axis, offset)\n\n    def _pre_remove(stmt):\n        if isinstance(stmt, tvm.tir.BufferRealize):\n            # Record the realize statements by buffer as we need to hoist some of these\n            realizes_by_buffer[stmt.buffer] = stmt\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if stmt.attr_key == \"realize_scope\" and isinstance(stmt.node, tvm.tir.Buffer):\n                # Record the realize_scope attrs by buffer as we need to hoist some of these\n                attrs_by_buffer[stmt.node] = stmt\n            if stmt.attr_key == \"pragma_op\" and stmt.value.value == \"ethosu_concatenate\":\n                # Record that we're entering a concatenate loop nest\n                in_concat[0] = True\n        if isinstance(stmt, tvm.tir.BufferLoad) and in_concat[0]:\n            # Any buffer loaded inside a concat is a buffer we intend to replace with this pass.\n            # The buffer_replace_map keeps track of which buffers need replacing with the\n            # concat buffer.\n            replace_info = _get_replace_info(stmt, concat_buffers[-1])\n            buffer_replace_map[stmt.buffer] = replace_info\n        if isinstance(stmt, tvm.tir.BufferStore) and in_concat[0]:\n            # If we're inside a concat, the BufferStore indicates what the concat buffer is\n            concat_buffers.append(stmt.buffer)\n\n    def _post_remove(stmt):\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if isinstance(stmt.node, tvm.tir.Buffer) and stmt.node in concat_buffers:\n                return stmt.body\n            if stmt.attr_key == \"pragma_op\" and stmt.value.value == \"ethosu_concatenate\":\n                # When we leave a concatenate operator, record it and then remove the loop nest\n                in_concat[0] = False\n                return tvm.tir.Evaluate(0)\n        if isinstance(stmt, tvm.tir.BufferRealize):\n            if stmt.buffer in concat_buffers:\n                return stmt.body\n        return None\n\n    def _pre_replace(stmt):\n        if isinstance(stmt, (tvm.tir.BufferLoad, tvm.tir.BufferStore)):\n            # The first buffer referenced that needs replacing with a concat buffer shall\n            # be the one that the concat buffer realize is hoisted to.\n            if stmt.buffer in buffer_replace_map:\n                concat_buffer = buffer_replace_map[stmt.buffer].buffer\n                if concat_buffer not in first_replacements:\n                    first_replacements[concat_buffer] = stmt.buffer\n\n    def _post_replace(stmt):\n        if isinstance(stmt, tvm.tir.BufferStore):\n            if stmt.buffer in buffer_replace_map:\n                # Replace the original buffer store with a new one into the concat buffer\n                # and adjust the indices accordingly to account for the offset\n                replace_info = buffer_replace_map[stmt.buffer]\n                concat_buffer = replace_info.buffer\n                new_indices = list(stmt.indices)\n                new_indices[replace_info.axis] += replace_info.offset\n                # The new buffer store node that stores the tensor directly into the concat buffer\n                new_store = tvm.tir.BufferStore(concat_buffer, stmt.value, new_indices, stmt.span)\n                return new_store\n        if isinstance(stmt, tvm.tir.BufferLoad):\n            if stmt.buffer in buffer_replace_map:\n                # Replace the original buffer load with a new one into the concat buffer\n                # and adjust the indices accordingly to account for the offset\n                replace_info = buffer_replace_map[stmt.buffer]\n                concat_buffer = replace_info.buffer\n                new_indices = list(stmt.indices)\n                new_indices[replace_info.axis] += replace_info.offset\n                new_load = tvm.tir.BufferLoad(concat_buffer, new_indices, stmt.span)\n                return new_load\n        if isinstance(stmt, tvm.tir.BufferRealize):\n            if stmt.buffer in buffer_replace_map:\n                concat_buffer = buffer_replace_map[stmt.buffer].buffer\n                # If this isn't the first buffer replaced, don't hoist the realize\n                if first_replacements[concat_buffer] != stmt.buffer:\n                    return stmt.body\n                # Otherwise, do hoist it\n                else:\n                    concat_realize = realizes_by_buffer[concat_buffer]\n                    new_realize = tvm.tir.BufferRealize(\n                        concat_realize.buffer,\n                        concat_realize.bounds,\n                        concat_realize.condition,\n                        stmt.body,\n                        stmt.span,\n                    )\n                    return new_realize\n        if isinstance(stmt, tvm.tir.AttrStmt):\n            if isinstance(stmt.node, tvm.tir.Buffer) and stmt.node in buffer_replace_map:\n                concat_buffer = buffer_replace_map[stmt.node].buffer\n                # If this isn't the first buffer replaced, don't hoist the attrstmt\n                if first_replacements[concat_buffer] != stmt.node:\n                    return stmt.body\n                # Otherwise, do hoist it\n                else:\n                    concat_attr = attrs_by_buffer[concat_buffer]\n                    new_attr = tvm.tir.AttrStmt(\n                        concat_attr.node,\n                        concat_attr.attr_key,\n                        concat_attr.value,\n                        stmt.body,\n                        stmt.span,\n                    )\n                    return new_attr\n\n    def _ftransform(f, mod, ctx):\n        f = f.with_body(\n            tvm.tir.stmt_functor.ir_transform(\n                f.body,\n                _pre_remove,\n                _post_remove,\n                [\"tir.AttrStmt\", \"tir.BufferLoad\", \"tir.BufferStore\", \"tir.BufferRealize\"],\n            )\n        )\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(\n                f.body,\n                _pre_replace,\n                _post_replace,\n                [\"tir.AttrStmt\", \"tir.BufferLoad\", \"tir.BufferStore\", \"tir.BufferRealize\"],\n            )\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.remove_concatenates\"\n    )\n\n\ndef CreatePrimFuncWithoutConstants(const_dict):\n    \"\"\"\n    This pass will remove arguments that are constants\n    from PrimFunc Args. These should be replaced properly\n    with tir.allocate_const when it becomes available.\n\n    It also modifies the constant dictionary to\n    rewrite the keys as the actual tir.Vars that are params\n    rather than the index because this pass removes PrimFunc\n    arguments that represent constants.\n    \"\"\"\n\n    new_const_dict = dict()\n\n    def _ftransform(f, mod, ctx):\n        new_params = list()\n        new_buffer_map = dict()\n        new_preflattened_buffer_map = dict()\n        for param_idx in const_dict.keys():\n            # We are using buffer_var to key the constants as\n            # PrimFunc params of constants will be removed.\n            new_const_dict[f.buffer_map[f.params[param_idx]].data] = const_dict[param_idx]\n        for i, param in enumerate(f.params):\n            if i not in const_dict.keys():\n                new_params.append(param)\n                new_buffer_map[param] = f.buffer_map[param]\n                if param in f.preflattened_buffer_map:\n                    new_preflattened_buffer_map[param] = f.preflattened_buffer_map[param]\n        return tvm.tir.PrimFunc(\n            new_params,\n            f.body,\n            f.ret_type,\n            new_buffer_map,\n            new_preflattened_buffer_map,\n            f.attrs,\n            f.span,\n        )\n\n    def _create_primfunc_without_constants(mod):\n        transform_func = tvm.tir.transform.prim_func_pass(\n            _ftransform, opt_level=0, name=\"tir.contrib.ethos-u.CreatePrimFuncWithoutConstants\"\n        )\n        mod = transform_func(mod)\n        return mod, new_const_dict\n\n    return _create_primfunc_without_constants\n\n\ndef HoistAllocates() -> tvm.IRModule:\n    \"\"\"\n    Hoist allocate nodes up to the top of the body of the main function.\n\n    Returns\n    -------\n    tvm.IRModule\n        The new module with hoisted allocate nodes.\n    \"\"\"\n    return _ffi_api.HoistAllocates()\n\n\ndef CopyComputeReordering(\n    max_copy_movements: Optional[int] = None, reorder_by_cycles: Optional[bool] = None\n) -> tvm.IRModule:\n    \"\"\"\n    Reorders copy and compute nodes in such a way that independent DMA copies\n    and computes happen in parallel.\n    Copies to buffers with local scope are not reordered since they copy LUT\n    into the SHRAM and that already happens in parallel with copying weights into\n    the weights encoder.\n\n    If reorder_by_cycles is set, we use the compute_cycles_hint to decide the reordering. If it is\n    not set, we move the copies up by a fixed number of movements, either by max_copy_movements if\n    it is specified, or by default value of 1.\n\n    If reordering based on the cycle count is enabled, we try to achieve further copy latency\n    hiding with a two step algorithm:\n    (1) Move all the global copies (i.e. copies that copy a constant into SRAM for conv2d or\n    depthwise_conv2d) above a preceding compute op. If in general the computes take longer than\n    copies, this should be enough to hide the copy latencies.\n    (2) If there are some global copies that take longer than the computes, we might be able to\n    hide them further by moving them further up in a graph since in general there are more compute\n    ops than copy ops in a graph (as only conv2d and depthwise_conv2d have constants associated\n    with them). The algortithm checks whether a copy is hidden and if it is not, it checks if a\n    preceding compute op has a preceding copy and if it doesn't it moves the copy that we try to\n    hide further up. It keeps moving the copy until it can't move it any further or until the\n    latency is hidden.\n\n    Parameters\n    ----------\n    max_copy_movements: Optional[int]\n        The maximum number of movements allowed for a copy.\n        If None, the pass context option\n        tir.contrib.ethos-u.copy_compute_reordering_max_copy_movements\n        is used if provided, otherwise the default value will be 1.\n\n    reorder_by_cycles: Optional[bool]\n        Whether to reorder the computes and copies based on the cycle hint.\n        If None, the pass context option\n        tir.contrib.ethos-u.copy_compute_reordering_reorder_by_cycles\n        is used if provided, otherwise the default value will be False.\n\n    Returns\n    -------\n    tvm.IRModule\n        The new module with copy and compute nodes reordered.\n    \"\"\"\n    return _ffi_api.CopyComputeReordering(max_copy_movements, reorder_by_cycles)\n\n\ndef MergeConstants(const_dict):\n    \"\"\"\n    This pass looks for the constants used by each compute operator\n    and merges them into a single buffer.\n    Constants written to a buffer with local scope are not merged.\n    \"\"\"\n\n    def _merge_constants(mod):\n        nonlocal const_dict\n        try:\n            mod[\"main\"]\n        except:\n            raise tvm.TVMError(\n                \"Expected a single primitive function called 'main'. \"\n                \"Please run the MergeConstants pass in conjunction with the LowerToTIR() pass.\"\n            )\n\n        new_const_dict = {}\n        for param in const_dict.keys():\n            new_const_dict[tvm.tir.IntImm(\"int64\", param)] = tvm.nd.array(const_dict[param])\n        mod[\"main\"] = mod[\"main\"].with_attr(\"ethos-u.const_dict\", new_const_dict)\n\n        mod = _ffi_api.MergeConstants()(mod)\n        const_dict = mod[\"main\"].attrs[\"ethos-u.const_dict\"]\n        mod = _ffi_api.RemoveConstDictAttribute()(mod)\n\n        new_const_dict = {}\n        for param in const_dict.keys():\n            new_const_dict[int(param)] = const_dict[param].numpy()\n\n        return mod, new_const_dict\n\n    return _merge_constants\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract information from the pooling operators in TIR.\"\"\"\nfrom typing import Tuple\nimport tvm\nfrom .utils import get_outer_loops, get_op_attrs, get_loads, get_stores\nfrom .dma import get_ifm_params, get_ofm_params\nfrom .spec import SerialKernel, SerialActivation, SerialPooling\nfrom .producers_consumers import ProducersConsumers\n\n\ndef get_pooling_params(\n    stmt: tvm.tir.AttrStmt, producers_consumers: ProducersConsumers\n) -> Tuple[SerialPooling, tvm.tir.Var, tvm.tir.Var]:\n    \"\"\"Get the parameters necessary to construct a call_extern for a pooling.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a convolution loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    SerialPooling\n        The parameters needed to construct a 2D convolution.\n    output_pointer : tvm.tir.Var\n        The output pointer of the convolution operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the convolution output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    rh = inner\n    rw = rh.body\n    # loads = [output, input, LUT, LUT]\n    loads = get_loads(rw.body)\n    # stores = [output]\n    stores = get_stores(rw.body)\n    input_pointer = loads[1].buffer.data\n    output_pointer = stores[0].buffer.data\n    # Get feature map info\n    serial_ifm, serial_padding = get_ifm_params(input_pointer, producers_consumers, stmt)\n    serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(\n        output_pointer, producers_consumers, stmt\n    )\n    # Get kernel info\n    serial_kernel = SerialKernel(\n        width=int(rw.extent),\n        height=int(rh.extent),\n        stride_w=int(attrs[\"stride_w\"]),\n        stride_h=int(attrs[\"stride_h\"]),\n        dilation_w=1,\n        dilation_h=1,\n    )\n\n    # Get activation info\n    serial_activation = SerialActivation(\n        op=attrs[\"activation\"], clip_min=attrs[\"clip_min\"], clip_max=attrs[\"clip_max\"]\n    )\n    return (\n        SerialPooling(\n            ifm=serial_ifm,\n            ofm=serial_ofm,\n            pooling_type=attrs[\"pooling_type\"],\n            pool_shape=serial_kernel,\n            padding=serial_padding,\n            activation=serial_activation,\n            rounding_mode=attrs[\"rounding_mode\"],\n            upscale=attrs[\"upscale\"],\n            block_config=serial_block_config,\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/producers_consumers.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"The ProducersConsumers class\"\"\"\nfrom typing import Optional\nfrom collections.abc import KeysView\nimport tvm\n\n\nclass ProducersConsumers:\n    \"\"\"It associates pointers with the loop nest that produces\n    their values and with the loop nest that consumes their values.\"\"\"\n\n    def __init__(self) -> None:\n        self.indices: dict[tvm.tir.AttrStmt, int] = {}\n        self.producers: list[(tvm.tir.AttrStmt, tvm.tir.expr.Var)] = []\n        self.consumers: list[(tvm.tir.AttrStmt, list[tvm.tir.expr.Var])] = []\n        self.allocate_variables: Optional[KeysView] = None\n\n    def add_producer(self, var: tvm.tir.expr.Var, attr: tvm.tir.AttrStmt) -> None:\n        \"\"\"Add the attribute statement attr as producer of the variable var.\"\"\"\n        self.indices[attr] = len(self.producers)\n        self.producers.append((attr, var))\n\n    def get_producer(\n        self, var: tvm.tir.expr.Var, attr: tvm.tir.AttrStmt\n    ) -> Optional[tvm.tir.AttrStmt]:\n        \"\"\"Get the last attribute statement which produces the variable var when\n        the current attribute statement is attr.\"\"\"\n        if var not in self.allocate_variables:\n            return None\n\n        index = self.indices[attr]\n        for i in list(reversed(range(index + 1))):\n            if self.producers[i][1] == var:\n                return self.producers[i][0]\n        return None\n\n    def get_last_producer(self, var: tvm.tir.expr.Var) -> Optional[tvm.tir.AttrStmt]:\n        \"\"\"Get the last attribute statement which produces the variable var.\"\"\"\n        return self.get_producer(var, self.producers[-1][0])\n\n    def add_allocate_variables(self, allocate_variables: KeysView) -> None:\n        \"\"\"Add the allocated variables.\"\"\"\n        self.allocate_variables = allocate_variables\n\n    def add_consumer(self, var: tvm.tir.expr.Var, attr: tvm.tir.AttrStmt) -> None:\n        \"\"\"Add the attribute statement attr as consumer of the variable var.\"\"\"\n        index = self.indices[attr]\n        if index < len(self.consumers):\n            self.consumers[index][1].append(var)\n        else:\n            self.consumers.append((attr, [var]))\n\n    def get_consumer(\n        self, var: tvm.tir.expr.Var, attr: tvm.tir.AttrStmt\n    ) -> Optional[tvm.tir.AttrStmt]:\n        \"\"\"Get the first attribute statement which consumes the variable var when\n        the current attribute statement is attr.\"\"\"\n        index = self.indices[attr]\n        for i in range(index, len(self.consumers)):\n            if var in self.consumers[i][1]:\n                return self.consumers[i][0]\n        return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Scheduling for Arm(R) Ethos(TM)-U NPU.\"\"\"\nimport tvm\nfrom tvm.contrib.ethosu.cascader import Propagator\n\n\ndef schedule(cached_func, const_dict, cascader=None):\n    \"\"\"Schedule a CachedFunc for NPU compilation.\n\n    Parameters\n    ----------\n    cached_func : CachedFunc\n        The CachedFunc to schedule.\n    const_dict : dict of int to numpy.ndarray\n        The constant dictionary.\n    cascader : callable, optional\n        A cascading function to apply optimizing scheduling\n        to the graph.\n\n    Returns\n    -------\n    s : tvm.te.Schedule\n        The completed schedule for the graph.\n\n    \"\"\"\n    s = tvm.te.create_schedule([t.op for t in cached_func.outputs])\n    if cascader:\n        cascader(cached_func, const_dict, s)\n    inline_no_ops(cached_func, s)\n    copy_luts()(cached_func, const_dict, s)\n    inline_no_ops(cached_func, s)\n    schedule_pragmas(s)\n    schedule_cache_reads(s)\n    return s\n\n\ndef tile_nd(s, tensor, tile):\n    \"\"\"Scheduling utility to perform N-dimensional tiling.\n\n    Parameters\n    ----------\n    s : tvm.te.Schedule\n        The schedule to apply the tiling to.\n    tensor : tvm.te.Tensor\n        The tensor to apply the tiling to.\n    tile : tuple\n        The N-dimensional tile size.\n\n    Returns\n    -------\n    outer_indices : list of tvm.tir.IterVar\n        The outer iteration variables.\n    inner_indices : list of tvm.tir.IterVar\n        The inner iteration variables.\n\n    \"\"\"\n    outer_indices = []\n    inner_indices = []\n    for i, size in enumerate(tile):\n        outer, inner = s[tensor].split(tensor.op.axis[i], size)\n        outer_indices.append(outer)\n        inner_indices.append(inner)\n\n    s[tensor].reorder(*outer_indices, *inner_indices)\n    return outer_indices, inner_indices\n\n\ndef total_cascader(stripe_size):\n    \"\"\"A demo/test cascader which tries to cascade every op in the graph together.\n\n    The desired output stride size should be specified. Note this only works\n    for single output graphs.\n\n    Parameters\n    ----------\n    stripe_size : tuple\n        The output stripe size.\n\n    Returns\n    -------\n    func : callable\n        The cascading function.\n\n    \"\"\"\n\n    def _cascader(cached_func, const_dict, sch):\n        scheduled = set()\n\n        def _visit(tensor, stage, ax):\n            if tensor not in scheduled and isinstance(tensor.op, tvm.te.ComputeOp):\n                sch[tensor].compute_at(stage, ax)\n                scheduled.add(tensor)\n                for input_tensor in tensor.op.input_tensors:\n                    _visit(input_tensor, stage, ax)\n\n        assert len(cached_func.outputs) == 1\n        out = cached_func.outputs[0]\n        oi, _ = tile_nd(sch, out, stripe_size)\n        for ax in oi:\n            sch[out].unroll(ax)\n        for input_tensor in out.op.input_tensors:\n            _visit(input_tensor, sch[out], oi[-1])\n\n    return _cascader\n\n\ndef copy_constants():\n    \"\"\"A simple planner which copies all constant data from FLASH -> SRAM.\n\n    Returns\n    -------\n    planner : callable\n        The planning function.\n    \"\"\"\n\n    def _planner(cached_func, const_dict, sch):\n        planned = set()  # type: ignore\n\n        def _visit(tensor, reader, lut):\n            if tensor not in planned:\n                planned.add(tensor)\n                if isinstance(tensor.op, tvm.te.PlaceholderOp) and tensor != lut:\n                    # Find index of input using 'same_as' check to prevent equality\n                    # ambiguity when encountering a scalar.\n                    is_same = [var.same_as(tensor) for var in cached_func.inputs]\n                    index = is_same.index(True)\n                    if index in const_dict:\n                        sch.cache_read(tensor, \"global\", [reader])\n\n                elif isinstance(tensor.op, tvm.te.ComputeOp):\n                    if \"lut\" in tensor.op.attrs.keys():\n                        lut = tensor.op.attrs[\"lut\"]\n                    for input_tensor in tensor.op.input_tensors:\n                        _visit(input_tensor, tensor, lut)\n\n        for output_tensor in cached_func.outputs:\n            _visit(output_tensor, None, None)\n\n    return _planner\n\n\ndef copy_luts():\n    \"\"\"A scheduler that copies LUTs to SHRAM.\n\n    Returns\n    -------\n    planner : callable\n        The planning function.\n    \"\"\"\n\n    def _planner(te_graph, const_dict, sch):\n        planned = set()  # type: ignore\n\n        def _visit(tensor, reader, lut):\n            if tensor not in planned:\n                planned.add(tensor)\n                if isinstance(tensor.op, tvm.te.PlaceholderOp) and tensor == lut:\n                    index = list(te_graph.inputs).index(tensor)\n                    if index in const_dict:\n                        sch.cache_read(tensor, \"local\", [reader])\n\n                elif isinstance(tensor.op, tvm.te.ComputeOp):\n                    if \"lut\" in tensor.op.attrs.keys():\n                        lut = tensor.op.attrs[\"lut\"]\n                    for input_tensor in tensor.op.input_tensors:\n                        _visit(input_tensor, tensor, lut)\n\n        for output_tensor in te_graph.outputs:\n            _visit(output_tensor, None, None)\n\n    return _planner\n\n\ndef schedule_pragmas(sch):\n    \"\"\"Add pragmas to the operators that require them.\n\n    This adds the pragmas used for codegen to the NPU ops.\n    They are taken directly from the TE compute op's attributes.\n    Modifies the schedule in-place.\n\n    Parameters\n    ----------\n    sch : tvm.te.Schedule\n        The schedule.\n\n    \"\"\"\n\n    def _add_pragmas(stage, ax):\n        if stage.op.name == \"T_concat\":\n            stage.pragma(ax, \"op\", \"ethosu_concatenate\")\n        if \"op\" in [attr for attr, val in stage.op.attrs.items()]:\n            stage.pragma(ax, \"op\", stage.op.attrs[\"op\"])\n            for attr, val in stage.op.attrs.items():\n                if attr not in (\"op\", \"lut\") and not isinstance(val, Propagator):\n                    stage.pragma(ax, str(attr), val)\n        if stage.op.axis[0] in stage.iter_var_attrs:\n            attrs = stage.iter_var_attrs[stage.op.axis[0]]\n            if \"block_config_height\" in attrs.pragma_keys:\n                pragmas = dict(zip([k.value for k in attrs.pragma_keys], attrs.pragma_values))\n                stage.pragma(ax, \"block_config_height\", pragmas[\"block_config_height\"])\n                stage.pragma(ax, \"block_config_width\", pragmas[\"block_config_width\"])\n                stage.pragma(ax, \"block_config_depth\", pragmas[\"block_config_depth\"])\n\n    for stage in sch.stages:\n        if (\n            isinstance(stage.op, tvm.te.ComputeOp)\n            and len(stage.op.axis) + len(stage.op.reduce_axis) > 0\n        ):\n            # The logic ensures the pragmas are assigned to the inner tiling loops\n            # rather than the outer ones (which end up getting unrolled).\n            num_inner_loops = len(stage.op.axis) + len(stage.op.reduce_axis)\n            ax = stage.leaf_iter_vars[-num_inner_loops]\n            _add_pragmas(stage, ax)\n\n\ndef schedule_cache_reads(sch):\n    \"\"\"Schedule cache reads that have been introduced.\n\n    There are two things we need to happen to cache_read stages. They should be tagged\n    with the 'ethosu_copy' pragma and have all their axes fused to make them 1D.\n\n    Parameters\n    ----------\n    sch : tvm.te.Schedule\n        The schedule.\n\n    \"\"\"\n\n    def _detect_cache_read(stage):\n        # Try and detect cache_reads by checking if the compute op is identity\n        if isinstance(stage.op, tvm.te.ComputeOp):\n            op = stage.op\n            if \"ethosu\" in op.name:\n                return False\n            axes = op.axis\n            if len(op.input_tensors) == 1:\n                tensor = op.input_tensors[0]\n                try:\n                    identity_op = tensor(*axes)\n                except ValueError:\n                    return False\n                if tvm.tir.analysis.expr_deep_equal(identity_op, op.body[0]):\n                    return True\n        return False\n\n    for stage in sch.stages:\n        if stage.attach_type != 2:  # Not inlined\n            if _detect_cache_read(stage):\n                fax = stage.fuse(*stage.op.axis)\n\n                # propagate pragmas placed on the outer loop\n                if len(stage.op.axis) > 0 and stage.op.axis[0] in stage.iter_var_attrs:\n                    attrs = stage.iter_var_attrs[stage.op.axis[0]]\n                    for k, v in zip(attrs.pragma_keys, attrs.pragma_values):\n                        stage.pragma(fax, k.value, v)\n\n                stage.pragma(fax, \"op\", \"ethosu_copy\")\n\n\ndef inline_no_ops(cached_func, sch):\n    \"\"\"Inline 'no-ops' - operations that in principle do nothing.\n\n    Modifies the schedule in-place. For now we inline reshape and\n    strided slice - more could be added.\n\n    Parameters\n    ----------\n    cached_func : CachedFunc\n        The cached func.\n    sch : tvm.te.Schedule\n        The schedule.\n\n    \"\"\"\n    no_ops = {\"T_reshape\", \"T_strided_slice\"}\n    scheduled = set()\n\n    def _visit(tensor):\n        if tensor not in scheduled and isinstance(tensor.op, tvm.te.ComputeOp):\n            if tensor.op.name in no_ops:\n                sch[tensor].compute_inline()\n            scheduled.add(tensor)\n            for input_tensor in tensor.op.input_tensors:\n                _visit(input_tensor)\n\n    for out in cached_func.outputs:\n        _visit(out)\n\n\nclass OperatorCompute:\n    \"\"\"A helper class to manipulate the series of compute ops that make up an operator.\"\"\"\n\n    def __init__(self, read, convert_to_nhwc, pad, upscale, op, convert_to_nhcwb16, write):\n        self.read = read\n        self.convert_to_nhwc = convert_to_nhwc\n        self.pad = pad\n        self.upscale = upscale\n        self.op = op\n        self.convert_to_nhcwb16 = convert_to_nhcwb16\n        self.write = write\n\n    @classmethod\n    def from_output(cls, out):\n        write = out\n        convert_to_nhcwb16 = write.op.input_tensors[0]\n        op = convert_to_nhcwb16.op.input_tensors[0]\n        pad = op.op.input_tensors[0]\n        upscale = pad.op.input_tensors[0]\n        convert_to_nhwc = upscale.op.input_tensors[0]\n        read = convert_to_nhwc.op.input_tensors[0]\n        return cls(read, convert_to_nhwc, pad, upscale, op, convert_to_nhcwb16, write)\n\n    def split(self, sch, axis, val):\n        outer, inner = sch[self.write].split(self.write.op.axis[axis], val)\n        iter_vars = [ax for ax in self.write.op.axis if ax != self.write.op.axis[axis]]\n        iter_vars.insert(axis, inner)\n        sch[self.write].reorder(outer, *iter_vars)\n        sch[self.write].unroll(outer)\n        g = sch.create_group(outputs=self.convert_to_nhcwb16, inputs=self.read, include_inputs=True)\n        g.compute_at(sch[self.write], outer)\n        return outer\n\n    def rolling_buffer(self, sch):\n        sch[self.read].rolling_buffer()\n        sch[self.convert_to_nhwc].rolling_buffer()\n        sch[self.pad].rolling_buffer()\n        sch[self.upscale].rolling_buffer()\n        sch[self.op].rolling_buffer()\n        sch[self.convert_to_nhcwb16].rolling_buffer()\n        sch[self.write].rolling_buffer()\n\n    def compute_at(self, sch, stage, axis):\n        sch[self.read].compute_at(stage, axis)\n        sch[self.convert_to_nhwc].compute_at(stage, axis)\n        sch[self.pad].compute_at(stage, axis)\n        sch[self.upscale].compute_at(stage, axis)\n        sch[self.op].compute_at(stage, axis)\n        sch[self.convert_to_nhcwb16].compute_at(stage, axis)\n        sch[self.write].compute_at(stage, axis)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/spec.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The TIR serialization specification for Arm(R) Ethos(TM)-U NPU.\"\"\"\nfrom typing import Union\nfrom typing import get_type_hints\nfrom inspect import isclass\n\nimport tvm\nfrom tvm.relay.backend.contrib.ethosu import util\n\n\ndef create_serial_object(serialized_type, deserialized_elements):\n    \"\"\"\n    This function will create serialized type that is one of the subclasses\n    of tvm.relay.backend.contrib.ethosu.tir.spec.SerializableFormat\n\n    Parameters\n    ----------\n    serialized_type : a subclass type of SerializableFormat\n\n    deserialized_elements : list\n        The list of arguments that needs to packed to create SerializableFormat objects\n\n    Returns\n    -------\n    The constructed object of type serialized_type\n    \"\"\"\n\n    def _create_serial_object(internal_serialized_type, read_element_idx=0):\n        \"\"\"The internal function that increments the read_element_idx\n        when creating nested serial objects\"\"\"\n        arg_len = util.get_arg_count(internal_serialized_type.__init__) - 1\n        serial_init_types = get_type_hints(internal_serialized_type.__init__)\n        serial_init_arg_names = list(serial_init_types.keys())\n        serial_init_args = []\n        assert arg_len == len(serial_init_arg_names)\n        for si_arg_name in serial_init_arg_names:\n            si_arg_type = serial_init_types[si_arg_name]\n            if isclass(si_arg_type) and issubclass(si_arg_type, SerializableFormat):\n                sia, read_element_idx = _create_serial_object(si_arg_type, read_element_idx)\n                serial_init_args.append(sia)\n            else:\n                serial_init_args.append(deserialized_elements[read_element_idx])\n                read_element_idx += 1\n        return internal_serialized_type(*serial_init_args), read_element_idx\n\n    # Just return the primary serial object\n    return _create_serial_object(serialized_type)[0]\n\n\nclass SerializableFormat:\n    \"\"\"Base class to retrieve arguments on a predefined ordering\"\"\"\n\n    def __iter__(self):\n        # Note class attribute definition order is preserved - see PEP 520\n        for name in self.__dict__:\n            value = self.__getattribute__(name)\n            if isinstance(value, SerializableFormat):\n                yield from list(value)\n            else:\n                yield value\n\n    def __getitem__(self, index):\n        # Note class attribute definition order is preserved - see PEP 520\n        name = list(self.__dict__.keys())[index]\n        return self.__getattribute__(name)\n\n\nclass SerialFeatureMap(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a Feature Map\n    (similiar to NpuFeatureMap of Vela) on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        data_type: str,\n        height: int,\n        width: int,\n        channels: int,\n        tile_height_0: int,\n        tile_height_1: int,\n        tile_width_0: int,\n        tile_address_0: tvm.tir.expr.BufferLoad,\n        tile_address_1: Union[tvm.tir.expr.BufferLoad, int],\n        tile_address_2: Union[tvm.tir.expr.BufferLoad, int],\n        tile_address_3: Union[tvm.tir.expr.BufferLoad, int],\n        scale: float,\n        zero_point: int,\n        layout: str,\n        stride_h: int,\n        stride_w: int,\n        stride_c: int,\n    ):\n        self.data_type = data_type\n        self.height = height\n        self.width = width\n        self.channels = channels\n        self.tile_height_0 = tile_height_0\n        self.tile_height_1 = tile_height_1\n        self.tile_width_0 = tile_width_0\n        self.tile_address_0 = tile_address_0\n        self.tile_address_1 = tile_address_1\n        self.tile_address_2 = tile_address_2\n        self.tile_address_3 = tile_address_3\n        self.scale = scale\n        self.zero_point = zero_point\n        self.layout = layout\n        self.stride_h = stride_h\n        self.stride_w = stride_w\n        self.stride_c = stride_c\n\n\nclass SerialKernel(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a Kernel\n    (similiar to NpuKernel of Vela) on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        width: int,\n        height: int,\n        stride_w: int,\n        stride_h: int,\n        dilation_w: int,\n        dilation_h: int,\n    ):\n        self.width = width\n        self.height = height\n        self.stride_w = stride_w\n        self.stride_h = stride_h\n        self.dilation_w = dilation_w\n        self.dilation_h = dilation_h\n\n\nclass SerialAddressRange(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a AddressRange\n    (similiar to NpuAddressRange of Vela) on a predefined ordering\"\"\"\n\n    def __init__(self, address: tvm.tir.expr.BufferLoad, length: int):\n        self.address = address\n        self.length = length\n\n\nclass SerialPadding(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a Padding\n    (similiar to NpuPadding of Vela) on a predefined ordering\"\"\"\n\n    def __init__(self, top: int, left: int, bottom: int, right: int):\n        self.top = top\n        self.left = left\n        self.bottom = bottom\n        self.right = right\n\n\nclass SerialActivation(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a Activation\n    (similiar to NpuActivation of Vela) on a predefined ordering\"\"\"\n\n    def __init__(self, op: str, clip_min: int, clip_max: int):\n        self.op = op\n        self.clip_min = clip_min\n        self.clip_max = clip_max\n\n\nclass SerialBlockConfig(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of a BlockConfig\n    (similar to NpuBlockConfig of Vela) on a predefined ordering\"\"\"\n\n    def __init__(self, height: int, width: int, depth: int):\n        self.height = height\n        self.width = width\n        self.depth = depth\n\n\nclass Serial2DConvolution(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.conv2d tir extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        ifm: SerialFeatureMap,\n        ofm: SerialFeatureMap,\n        kernel: SerialKernel,\n        weight: SerialAddressRange,\n        weight2: SerialAddressRange,\n        weight_zero_point: int,\n        scale_bias: SerialAddressRange,\n        scale_bias2: SerialAddressRange,\n        padding: SerialPadding,\n        activation: SerialActivation,\n        rounding_mode: str,\n        upscale: str,\n        block_config: SerialBlockConfig,\n    ):\n        self.ifm = ifm\n        self.ofm = ofm\n        self.kernel = kernel\n        self.weight = weight\n        self.weight2 = weight2\n        self.weight_zero_point = weight_zero_point\n        self.scale_bias = scale_bias\n        self.scale_bias2 = scale_bias2\n        self.padding = padding\n        self.activation = activation\n        self.rounding_mode = rounding_mode\n        self.upscale = upscale\n        self.block_config = block_config\n\n\nclass Serial2DDepthwise(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.depthwise_conv2d TIR extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        ifm: SerialFeatureMap,\n        ofm: SerialFeatureMap,\n        kernel: SerialKernel,\n        weight: SerialAddressRange,\n        weight_zero_point: int,\n        scale_bias: SerialAddressRange,\n        padding: SerialPadding,\n        activation: SerialActivation,\n        rounding_mode: str,\n        upscale: str,\n        block_config: SerialBlockConfig,\n    ):\n        self.ifm = ifm\n        self.ofm = ofm\n        self.kernel = kernel\n        self.weight = weight\n        self.weight_zero_point = weight_zero_point\n        self.scale_bias = scale_bias\n        self.padding = padding\n        self.activation = activation\n        self.rounding_mode = rounding_mode\n        self.upscale = upscale\n        self.block_config = block_config\n\n\nclass SerialCopy(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.copy tir extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        read_address: tvm.tir.expr.BufferLoad,\n        length: int,\n        write_address: tvm.tir.expr.BufferLoad,\n    ):\n        self.read_address = read_address\n        self.length = length\n        self.write_address = write_address\n\n\nclass SerialPooling(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.pooling tir extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        ifm: SerialFeatureMap,\n        ofm: SerialFeatureMap,\n        pooling_type: str,\n        pool_shape: SerialKernel,\n        padding: SerialPadding,\n        activation: SerialActivation,\n        rounding_mode: str,\n        upscale: str,\n        block_config: SerialBlockConfig,\n    ):\n        self.ifm = ifm\n        self.ofm = ofm\n        self.pooling_type = pooling_type\n        self.pool_shape = pool_shape\n        self.padding = padding\n        self.activation = activation\n        self.rounding_mode = rounding_mode\n        self.upscale = upscale\n        self.block_config = block_config\n\n\nclass SerialBinaryElementwise(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.binary_elementwise tir extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        ifm: SerialFeatureMap,\n        ifm2: SerialFeatureMap,\n        ofm: SerialFeatureMap,\n        operator_type: str,\n        reversed_operands: bool,\n        activation: SerialActivation,\n        rounding_mode: str,\n        block_config: SerialBlockConfig,\n    ):\n        self.ifm = ifm\n        self.ifm2 = ifm2\n        self.ofm = ofm\n        self.operator_type = operator_type\n        self.reversed_operands = reversed_operands\n        self.activation = activation\n        self.rounding_mode = rounding_mode\n        self.block_config = block_config\n\n\nclass SerialUnaryElementwise(SerializableFormat):\n    \"\"\"Specialization class to retrieve arguments of\n    a ethosu.unary_elementwise tir extern call on a predefined ordering\"\"\"\n\n    def __init__(\n        self,\n        ifm: SerialFeatureMap,\n        ofm: SerialFeatureMap,\n        operator_type: str,\n        activation: SerialActivation,\n        rounding_mode: str,\n        block_config: SerialBlockConfig,\n    ):\n        self.ifm = ifm\n        self.ofm = ofm\n        self.operator_type = operator_type\n        self.activation = activation\n        self.rounding_mode = rounding_mode\n        self.block_config = block_config\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract parameters from the transform operators in TIR.\"\"\"\nimport tvm\nfrom .spec import SerialCopy\nfrom .utils import get_base_address, get_op_attrs\n\n\ndef get_copy_params(stmt, producers_consumers):\n    \"\"\"Get the parameters necessary to construct a call_extern for a copy.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a copy loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    SerialCopy\n        The parameters needed to construct a copy.\n    tvm.tir.Var\n        The output pointer of the copy operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the convolution output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n    \"\"\"\n    _, body = get_op_attrs(stmt)\n    length = body.extent\n    write_store = body.body\n    write_base = [get_base_address(index) for index in write_store.indices]\n    read_load = body.body.value\n    read_base = [get_base_address(index) for index in read_load.indices]\n    return (\n        SerialCopy(\n            read_address=tvm.tir.expr.BufferLoad(read_load.buffer, read_base),\n            length=length,\n            write_address=tvm.tir.expr.BufferLoad(write_store.buffer, write_base),\n        ),\n        write_store.buffer.data,\n        None,\n        True,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/unary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Extract information from the unary_elementwise operators in TIR.\"\"\"\nfrom tvm import tir\nfrom .utils import get_outer_loops, get_op_attrs\nfrom .dma import get_ifm_params, get_ofm_params\nfrom .spec import SerialActivation, SerialUnaryElementwise\n\n\ndef get_unary_elementwise_params(stmt, producers_consumers):\n    \"\"\"Get the parameters necessary to construct a call_extern for a unary_elementwise.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement of a unary elementwise loop nest.\n    producers_consumers: ProducersConsumers\n        It associates pointers with the loop nest that produces\n        their values and with the loop nest that consumes their values.\n\n    Returns\n    -------\n    SerialUnaryElementwise\n        The parameters needed to construct a unary elementwise operator.\n    output_pointer : tvm.tir.Var\n        The output pointer of the unary elementwise operation.\n    replace_pointer : tvm.tir.Var\n        The output pointer of the DMA write operation, which is to replace\n        the unary elementwise output pointer.\n    is_allocator : bool\n        Whether this operator allocates its output.\n    \"\"\"\n    attrs, body = get_op_attrs(stmt)\n\n    _, _, _, _, _, inner = get_outer_loops(body, \"NHWC\")\n    input_pointer = None\n    if isinstance(inner.value, tir.expr.Select):\n        # ABS\n        input_pointer = inner.value.condition.b.buffer.data\n    if isinstance(inner.value, tir.expr.Sub):\n        # CLZ\n        input_pointer = inner.value.b.args[0].buffer.data\n    output_pointer = inner.buffer.data\n    # Get feature map info\n    serial_ifm, _ = get_ifm_params(input_pointer, producers_consumers, stmt)\n    serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(\n        output_pointer, producers_consumers, stmt\n    )\n    # Get activation info\n    serial_activation = SerialActivation(\n        op=attrs[\"activation\"], clip_min=attrs[\"clip_min\"], clip_max=attrs[\"clip_max\"]\n    )\n    return (\n        SerialUnaryElementwise(\n            ifm=serial_ifm,\n            ofm=serial_ofm,\n            operator_type=attrs[\"operator_type\"],\n            activation=serial_activation,\n            rounding_mode=attrs[\"rounding_mode\"],\n            block_config=serial_block_config,\n        ),\n        output_pointer,\n        replace_pointer,\n        is_allocator,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Helper utility functions used by the NPU TIR compiler\"\"\"\nimport tvm\nfrom tvm import arith\n\n\ndef get_op_attrs(stmt):\n    \"\"\"Iterate through nested attribute statements accumulating their values\n    in an attribute dictionary.\n\n    The \"pragma_\" prefix is removed as a convenience.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.AttrStmt\n        The outermost attribute statement to begin from.\n\n    Returns\n    -------\n    attrs : dict of str to object\n        The attribute dictionary.\n    stmt : tvm.tir.Stmt\n        The body after having collected the final attribute statement.\n\n    \"\"\"\n    attrs = {}\n    while isinstance(stmt, tvm.tir.AttrStmt):\n        # The pragma scheduler inserts \"pragma_\" before all the\n        # attr names, this is annoying so we get rid of it\n        attr = stmt.attr_key.replace(\"pragma_\", \"\")\n        attrs[attr] = stmt.value\n        stmt = stmt.body\n\n    return attrs, stmt\n\n\ndef get_strides(index, stride_vars):\n    \"\"\"Get the striding of given vars in an indexing expression.\n\n    Parameters\n    ----------\n    index : tvm.tir.PrimExpr\n        The index expression where the stride vars are present.\n    stride_vars : list of tvm.tir.Var\n        The vars to determine the striding of.\n\n    Returns\n    -------\n    strides : list of int\n        The striding of each stride var in the index expression\n        in the same order as the stride vars were given.\n\n    \"\"\"\n    strides = [1] * len(stride_vars)\n    dmap = {}\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Var):\n            dmap[stmt] = arith.IntervalSet(0, 0)\n\n    tvm.tir.stmt_functor.post_order_visit(index, _visit)\n    min_value = int(arith.Analyzer().int_set(index, dmap).min_value)\n    for var in dmap:\n        if var in stride_vars:\n            # NOTE: Doing this using a [0, 1] interval doesn't work reliably\n            # Seems to be a bug\n            dmap[var] = arith.IntervalSet(1, 1)\n            max_value = int(arith.Analyzer().int_set(index, dmap).max_value)\n            stride = int(max_value - min_value)\n            i = stride_vars.index(var)\n            strides[i] = stride\n            dmap[var] = arith.IntervalSet(0, 0)\n\n    return strides\n\n\ndef get_base_address(index):\n    \"\"\"Determine the first (base) address accessed by an index expression.\n\n    Parameters\n    ----------\n    index : tvm.tir.PrimExpr\n        The index expression to determine the base address of.\n\n    Returns\n    -------\n    base_address:\n        The first address accessed by the index expression.\n\n    \"\"\"\n    dmap = {}\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Var):\n            dmap[stmt] = arith.IntervalSet(0, 0)\n\n    tvm.tir.stmt_functor.post_order_visit(index, _visit)\n    base_address = int(arith.Analyzer().int_set(index, dmap).min_value)\n    return base_address\n\n\ndef get_outer_loops(stmt, layout):\n    \"\"\"Get the outer loops of an operator.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.For\n        The outermost loop.\n    layout : str\n        The output tensor layout (NHWC or NHCWB16).\n\n    Returns\n    -------\n    n : tvm.tir.For\n        The batch loop.\n    h : tvm.tir.For\n        The height loop.\n    w : tvm.tir.For\n        The width loop.\n    c : tvm.tir.For\n        The channels loop.\n    b : tvm.tir.For\n        The brick loop. None for NHWC\n    body : tvm.tir.Stmt\n        The inner body of the loops.\n\n    \"\"\"\n    if layout == \"NHWC\":\n        n = stmt\n        h = n.body\n        w = h.body\n        c = w.body\n        b = tvm.tir.For(tvm.tir.Var(\"b\", \"int32\"), 0, 0, 0, tvm.tir.Evaluate(0))\n        return n, h, w, c, b, c.body\n    if layout == \"NHCWB16\":\n        n = stmt\n        h = n.body\n        cb = h.body\n        w = cb.body\n        b = w.body\n        return n, h, w, cb, b, b.body\n    return None\n\n\ndef collect_buffer_map(stmt):\n    \"\"\"Collect a map of Var -> Buffer\n\n    Generate a map from a buffer's backing `tir.Var` to the\n    `tir.Buffer` object that uses it.  If multiple such buffers exist,\n    return the first occurrence.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.Stmt\n        The statement to get the BufferLoads from.\n\n    Returns\n    -------\n    buffer_map : Dict[Var, Buffer]\n        The map from buffer var to the buffers that use it.\n    \"\"\"\n    buffer_map = {}\n\n    def _visit(node):\n        if isinstance(node, (tvm.tir.BufferLoad, tvm.tir.BufferStore)):\n            buf = node.buffer\n            if buf.data not in buffer_map:\n                buffer_map[buf.data] = buf\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, _visit)\n\n    return buffer_map\n\n\ndef get_loads(stmt):\n    \"\"\"Get the BufferLoad statements.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.Stmt\n        The statement to get the BufferLoads from.\n\n    Returns\n    -------\n    loads : list of tvm.tir.BufferLoad\n        The BufferLoads found.\n\n    \"\"\"\n    loads = []\n\n    def _visit(s):\n        if isinstance(s, tvm.tir.BufferLoad):\n            loads.append(s)\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, _visit)\n    return loads\n\n\ndef get_stores(stmt):\n    \"\"\"Get the BufferStore statements.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.Stmt\n        The statement to get the BufferStores from.\n\n    Returns\n    -------\n    stores : list of tvm.tir.BufferStore\n        The BufferStores found.\n\n    \"\"\"\n    stores = []\n\n    def _visit(s):\n        if isinstance(s, tvm.tir.BufferStore):\n            stores.append(s)\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, _visit)\n    return stores\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/tir_to_cs_translator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"This source will contain code to convert TIR, as produced by\nthe Relay to TIR compilation process, to Vela API calls to\ngenerate command stream.\n\"\"\"\nfrom typing import Dict, NamedTuple, Tuple, Union, List\nfrom enum import auto\nfrom enum import Enum\nimport numpy as np  # type: ignore\nimport ethosu.vela.api as vapi  # type: ignore\n\nimport tvm\nfrom tvm.tir import stmt_functor\nfrom tvm.relay.backend.contrib.ethosu import util\nfrom tvm.relay.backend.contrib.ethosu import vela_api\nfrom tvm.relay.backend.contrib.ethosu.tir import spec\nfrom tvm.relay.backend.contrib.ethosu.tir import utils as tir_utils\n\n\nclass BufferType(Enum):\n    \"\"\"The type of information that a buffer contains.\"\"\"\n\n    constant = auto()\n    input_or_output = auto()\n    scratch = auto()\n    input = auto()\n    output = auto()\n    shram = auto()\n\n\nclass BufferInfo(NamedTuple):\n    \"\"\"A data structure to hold metadata of the buffer.\"\"\"\n\n    # If the buffer holds constants, the values will contain that otherwise None\n    values: np.ndarray\n    shape: tvm.ir.container.Array\n    dtype: np.dtype\n    btype: BufferType\n\n\nclass AcceleratorArchConfig:\n    def __init__(self, total_shram_banks):\n        self.shram_bank_size = 1024\n        self.total_shram_banks = total_shram_banks\n        self.shram_size_bytes = self.shram_bank_size * self.total_shram_banks\n        self.lut_size_bytes = 2048\n        self.lut_start_address = self.shram_size_bytes - self.lut_size_bytes\n\n\ndef get_accelerator_arch_config(accel_type):\n    accel_config_str_map = {\n        \"ethos-u55-32\": AcceleratorArchConfig(16),\n        \"ethos-u55-64\": AcceleratorArchConfig(16),\n        \"ethos-u55-128\": AcceleratorArchConfig(24),\n        \"ethos-u55-256\": AcceleratorArchConfig(48),\n        \"ethos-u65-256\": AcceleratorArchConfig(48),\n    }\n    return accel_config_str_map[accel_type]\n\n\nclass RegionOffset(NamedTuple):\n    \"\"\"A data structure to hold region and address offset corresponding to a tensor\"\"\"\n\n    region: int\n    offset: int\n\n\ndef analyze_scratch_memory_acesses(mod: tvm.IRModule, candidate_regions_for_scratch: List[int]):\n    \"\"\"\n    This function analyzes the IRModule for intermediary tensors that can be resulting\n    from a offset of pool variables (via Let nodes) and/or allocate nodes. The allocate\n    nodes will be folded into a single TVMBackendallocWorkspace call with offsets. Ultimately\n    this will produce a mapping from each such node to a RegionOffset named tuple that\n    has the region and the obtained offset, as mentioned above.\n\n    Parameters\n    ----------\n    mod: tvm.IRModule\n        The TIR module containing ethosu extern calls\n    candidate_regions_for_scratch: List[int]\n        A list of region integers that could be used for scratch regions\n\n    Returns\n    -------\n    scratch_region_map : Dict[tvm.tir.Var, RegionOffset]\n        A map between buffer vars to scratch regions they are assigned\n    tvm_backend_alloc_workspace_size : int\n        The size of tvm_backend_alloc_workspace call required to service\n        remaining allocate nodes if any\n    tvm_backend_alloc_workspace_region : int\n        The region associated with the tvm_backend_alloc_workspace\n    \"\"\"\n    scratch_region_map = dict()\n    pool_var_region_map = dict()\n    # There should only be a single function\n    assert len(mod.functions.items()) == 1\n    primfunc = mod.functions.items()[0][1]\n    if \"pool_args\" in primfunc.attrs.keys():\n        pool_args = primfunc.attrs[\"pool_args\"]\n        for pool_arg in pool_args:\n            pool_param = primfunc.params[int(pool_arg.pool_var_idx)]\n            pool_var_region_map[pool_param] = candidate_regions_for_scratch.pop()\n            scratch_region_map[pool_param] = RegionOffset(\n                region=pool_var_region_map[pool_param], offset=None\n            )\n\n    def analyze_pool_access(stmt):\n        if isinstance(stmt, tvm.tir.stmt.LetStmt):\n            call_address_of = stmt.value\n            load = call_address_of.args[0]\n            pool_var = load.buffer.data\n            scratch_region_map[stmt.var] = RegionOffset(\n                region=pool_var_region_map[pool_var], offset=int(load.indices[0])\n            )\n\n    tvm.tir.stmt_functor.post_order_visit(primfunc.body, analyze_pool_access)\n\n    dynamic_allocation_region = None\n    if len(candidate_regions_for_scratch) > 0:\n        dynamic_allocation_region = candidate_regions_for_scratch.pop()\n        dynamic_allocation_size = 0\n\n        # If there are tir.Allocate remaining by now, they need to be serviced via\n        # dynamic_allocation calls.\n        def analyze_remaining_allocates(stmt):\n            nonlocal dynamic_allocation_size\n            if isinstance(stmt, tvm.tir.stmt.Allocate):\n                allocate = stmt\n                pointer_type = allocate.buffer_var.type_annotation\n                storage_scope = pointer_type.storage_scope\n                if storage_scope == \"global\":\n                    dtype_bytes = np.iinfo(np.dtype(allocate.dtype)).bits // 8\n                    size_in_bytes = int(dtype_bytes * np.prod(list(allocate.extents)))\n                    # Every memory address the NPU access have to be 16 byte aligned\n                    size_in_bytes = util.round_up(size_in_bytes, 16)\n                    address = dynamic_allocation_size\n                    dynamic_allocation_size += size_in_bytes\n                    scratch_region_map[allocate.buffer_var] = RegionOffset(\n                        region=dynamic_allocation_region, offset=address\n                    )\n\n        tvm.tir.stmt_functor.post_order_visit(primfunc.body, analyze_remaining_allocates)\n\n    return (\n        scratch_region_map,\n        dynamic_allocation_size,\n        dynamic_allocation_region,\n    )\n\n\ndef _get_region(buffer_type, var=None, scratch_region_map=None):\n    \"\"\"A helper to obtain regions for buffer_types and buffer vars\"\"\"\n    static_regions = {\n        BufferType.constant: 0,\n        BufferType.input: 3,\n        BufferType.output: 4,\n        BufferType.shram: int((1 << 8) | (3 << 0)),\n    }\n    if buffer_type in static_regions.keys():\n        return static_regions[buffer_type]\n    assert buffer_type == BufferType.scratch\n    assert var in scratch_region_map.keys(), f\"{var} is not analyzed for scratch regions\"\n    return scratch_region_map[var].region\n\n\ndef translate(tir_module, params):\n    \"\"\"This will take an tir module for the NPU\n    and compile to command stream\n\n    Parameters\n    ----------\n    tir_module : tvm.IRModule\n        The TIR module containing ethosu extern calls\n    params : dict\n        A dictionary containing TIR primfunc argument ordering\n        idx to constant NDArray map\n    accel_type : ethosu.vela.api.NpuAccelerator\n        the accelerator variant the tir module needs to compiled to\n\n    Returns\n    -------\n    cs : str\n        An hex string of the bytes of command stream\n    encoded_constants : str\n        An hex string of the bytes that includes concat'd\n        encoded weights, encoded biases and scales.\n    base_addresses : List[util.BaseAddress]\n        base addresses to be used by the driver\n    \"\"\"\n\n    # The NPU has 6 usable regions ranging from 0-6\n    # The regions 0, 3, and 4 is already used for input,\n    # output and constant, respectively (See _get_regions()).\n    # Thus, for scratch we are left with 5, 2 and 1.\n    candidate_regions_for_scratch = [5, 2, 1]\n    (\n        scratch_region_map,\n        dynamic_allocation_size,\n        dynamic_allocation_region,\n    ) = analyze_scratch_memory_acesses(tir_module, candidate_regions_for_scratch)\n    buffer_info = extract_buffer_info(tir_module, params)\n    call_extern_list = extract_call_extern_list(tir_module)\n    _npu_ops = list()\n    for call_extern in call_extern_list:\n        _npu_ops.append(translate_ethosu_tir_call_extern(call_extern))\n    _npu_ops, constant_data = assign_addresses(buffer_info, _npu_ops, scratch_region_map)\n    base_addresses = extract_param_base_addresses(tir_module, buffer_info, scratch_region_map)\n    if dynamic_allocation_size:\n        base_addresses.append(\n            util.BaseAddress(\n                name=\"dynamic_allocation\",\n                primfunc_param_idx=None,\n                region=dynamic_allocation_region,\n                size=dynamic_allocation_size,\n                is_runtime_allocation=True,\n            )\n        )\n    target_accel_config = vela_api.get_accelerator_config()\n    cmds = vapi.npu_generate_register_command_stream(_npu_ops, target_accel_config)\n    payload = vapi.npu_create_driver_payload(cmds, target_accel_config)\n    return payload.hex(), constant_data, base_addresses\n\n\ndef extract_param_base_addresses(mod, buffer_info, scratch_region_map) -> List[util.BaseAddress]:\n    \"\"\"This function extracts base addresses to be used by the driver\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The TIR Module for NPU\n    buffer_info : Dict[tvm.tir.Var, BufferInfo]\n        Information regarding buffer vars used in the PrimFunc\n\n    Returns\n    -------\n    List[util.BaseAddress]\n        base addresses to be used by the driver\n    \"\"\"\n    # There should only be a single function\n    assert len(mod.functions.items()) == 1\n    primfunc = mod.functions.items()[0][1]\n\n    buffer_map = tir_utils.collect_buffer_map(primfunc.body)\n\n    base_addresses = list()\n    idx = 0\n\n    for param in primfunc.params:\n        # constants are pooled together and handled specially\n        # this will change after tir.allocate_const.\n        # For now, we are skipping generating buffer addresses here\n        if buffer_info[param].btype == BufferType.constant:\n            continue\n\n        if param in buffer_map:\n            buffer = buffer_map[param]\n            dtype = buffer.dtype\n            element_size_bytes = np.iinfo(dtype).bits // 8\n            size_bytes = element_size_bytes * np.prod(list(buffer.shape))\n            base_addresses.append(\n                util.BaseAddress(\n                    param.name.replace(\"-\", \"_\"),\n                    idx,\n                    _get_region(buffer_info[param].btype, param, scratch_region_map),\n                    size_bytes,\n                )\n            )\n        else:\n            base_addresses.append(\n                util.BaseAddress(\n                    param.name.replace(\"-\", \"_\"),\n                    idx,\n                    _get_region(buffer_info[param].btype, param, scratch_region_map),\n                    0,\n                )\n            )\n        idx += 1\n\n    return base_addresses\n\n\ndef extract_call_extern_list(mod):\n    \"\"\"This function will obtain all extern\n    calls from a TIR module\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The TIR Module for NPU\n\n    Returns\n    -------\n    list\n        of tvm.tir.Call objects\n        that are tir extern calls\n    \"\"\"\n    # There should only be a single function\n    assert len(mod.functions.items()) == 1\n    primfunc = mod.functions.items()[0][1]\n\n    call_extern_list = list()\n\n    def populate_call_extern_list(stmt):\n        if isinstance(stmt, tvm.tir.Call) and stmt.op.name == \"tir.call_extern\":\n            call_extern_list.append(stmt)\n\n    stmt_functor.post_order_visit(primfunc.body, populate_call_extern_list)\n    return call_extern_list\n\n\ndef extract_buffer_info(\n    mod: tvm.IRModule, param_dict: Dict[int, np.ndarray]\n) -> Dict[str, BufferInfo]:\n    \"\"\"This function is to read the tvm.IRModule that\n    contains Relay to TIR compiled IRModule. Thereafter,\n    this will extract the buffer information as the shape\n    and constant data (if any).\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The NPU TIR IRModule.\n    param_dict : Dict[tvm.tir.Var, np.ndarray]\n        A dictionary containing param idx --> const numpy.NDArray\n\n    Returns\n    -------\n    dict : Dict[str, BufferInfo]\n        A dictionary of buffer names --> BufferInfo\n\n    \"\"\"\n    buffer_info = dict()\n    # There should only be a single function\n    assert len(mod.functions.items()) == 1\n    primfunc = mod.functions.items()[0][1]\n\n    for param, const_data in param_dict.items():\n        if isinstance(param, tvm.tir.Buffer):\n            param = param.data\n        buffer_info[param] = BufferInfo(\n            const_data, const_data.shape, const_data.dtype, BufferType.constant\n        )\n\n    pool_param_indices = list()\n    if \"pool_args\" in primfunc.attrs.keys():\n        pool_args = primfunc.attrs[\"pool_args\"]\n        pool_param_indices = [allocated_pool_info.pool_var_idx for allocated_pool_info in pool_args]\n\n    for idx, param in enumerate(primfunc.params):\n        if param not in buffer_info.keys():\n            if idx in pool_param_indices:\n                btype = BufferType.scratch\n            else:\n                btype = BufferType.input_or_output\n            buffer_info[param] = BufferInfo(\n                None,\n                None,\n                None,\n                btype,\n            )\n\n    def populate_allocate_buffer_info(stmt):\n        if isinstance(stmt, tvm.tir.stmt.Allocate):\n            allocate = stmt\n            pointer_type = allocate.buffer_var.type_annotation\n            storage_scope = pointer_type.storage_scope\n            if storage_scope == \"local\":\n                buffer_info[allocate.buffer_var] = BufferInfo(\n                    None,\n                    allocate.extents,\n                    allocate.dtype,\n                    BufferType.shram,\n                )\n\n    tvm.tir.stmt_functor.post_order_visit(primfunc.body, populate_allocate_buffer_info)\n    return buffer_info\n\n\ndef assign_addresses(buffer_info, npu_ops, scratch_region_map):\n    \"\"\"This function will assign addresses to tensors\n    within two buffers : scratch and constants.\n    The scratch is the buffer created to hold all intermediary data\n    The constants is the buffer created via unifying all the constant data\n    (post-encoding).\n    Parameters\n    ----------\n    buffer_info : dict\n        This is the dictionary obtained via calling extract_buffer_info.\n        The key is the buffer name to BufferInfo\n    npu_ops : list\n        A list of Vela NpuOps with tir.BufferLoads for addresses\n        A list of Vela NpuOps with tir.Loads for addresses\n    scratch_region_map : Dict[tvm.tir.Var, RegionOffset]\n        A buffer_var to region and offset map.\n    Returns\n    -------\n    npu_ops : list\n        A list of Vela NpuOps with addesses within scratch and constant buffers\n    constant_tensor : NDArray\n        A unified constant data array of uint8 as the constant buffer\n    \"\"\"\n\n    def replace_npu_fm_with_address(npu_fm):\n        assert isinstance(npu_fm.tiles.addresses[0], tvm.tir.BufferLoad)\n        buffer = npu_fm.tiles.addresses[0].buffer.data\n        if buffer in scratch_region_map.keys():\n            address = scratch_region_map[buffer].offset\n            region = scratch_region_map[buffer].region\n        else:\n            assert buffer in buffer_addresses.keys()\n            address, buffer_type = buffer_addresses[buffer]\n            region = _get_region(buffer_type)\n        assert (\n            len(npu_fm.tiles.addresses[0].indices) == 1\n        ), \"Ethos-U translation expects flattened buffers\"\n        index = npu_fm.tiles.addresses[0].indices[0] * (\n            np.iinfo(np.dtype(npu_fm.tiles.addresses[0])).bits // 8\n        )\n        npu_fm.tiles.addresses[0] = address + int(index)\n        npu_fm.tiles.addresses[1] = (\n            address if isinstance(npu_fm.tiles.addresses[1], tvm.tir.BufferLoad) else 0\n        )\n        npu_fm.tiles.addresses[2] = (\n            address if isinstance(npu_fm.tiles.addresses[2], tvm.tir.BufferLoad) else 0\n        )\n        npu_fm.tiles.addresses[3] = 0\n        npu_fm.region = region\n        return npu_fm\n\n    def replace_npu_address_range_with_address(npu_addr_range):\n        assert isinstance(npu_addr_range.address, tvm.tir.BufferLoad)\n        buffer = npu_addr_range.address.buffer.data\n        index = int(\n            npu_addr_range.address.indices[0]\n            * (np.iinfo(np.dtype(npu_addr_range.address)).bits // 8)\n        )\n        if buffer in scratch_region_map.keys():\n            return vapi.NpuAddressRange(\n                scratch_region_map[buffer].region,\n                scratch_region_map[buffer].offset + index,\n                npu_addr_range.length,\n            )\n        assert buffer in buffer_addresses.keys(), f\"searching for buffer : {buffer}, but not found\"\n        address, buffer_type = buffer_addresses[buffer]\n        address = address + int(npu_addr_range.address.indices[0].value)\n        return vapi.NpuAddressRange(_get_region(buffer_type), address, npu_addr_range.length)\n\n    def replace_tir_loads(npu_object):\n        if isinstance(npu_object, vapi.NpuFeatureMap):\n            return replace_npu_fm_with_address(npu_object)\n        if isinstance(npu_object, vapi.NpuAddressRange):\n            return replace_npu_address_range_with_address(npu_object)\n        return npu_object\n\n    def classify_io(buffer):\n        for _npu_op in npu_ops:\n            if issubclass(type(_npu_op), vapi.NpuBlockOperation):\n                if _npu_op.ifm and _npu_op.ifm.tiles.addresses[0].buffer.data == buffer:\n                    return BufferType.input\n                if _npu_op.ifm2 and _npu_op.ifm2.tiles.addresses[0].buffer.data == buffer:\n                    return BufferType.input\n                if _npu_op.ofm and _npu_op.ofm.tiles.addresses[0].buffer.data == buffer:\n                    return BufferType.output\n\n        raise ValueError(f\"Unused IO : {buffer} in tir module.\")\n\n    constant_hex_data = []\n    total_constant_len = 0\n    buffer_addresses = dict()\n    for _buffer, info in buffer_info.items():\n        if info.values is not None:\n            assert info.btype == BufferType.constant\n            assert len(info.shape) == 1\n            buffer_addresses[_buffer] = (\n                (total_constant_len, info.btype) if constant_hex_data else (0, info.btype)\n            )\n            dtype_bytes = np.iinfo(np.dtype(info.dtype)).bits // 8\n            size_in_bytes = dtype_bytes * np.prod(list(info.shape))\n            # Every memory address the NPU access have to be 16 byte aligned\n            size_in_bytes = util.round_up(size_in_bytes, 16)\n            constant_tensor = np.resize(info.values, size_in_bytes // dtype_bytes)\n            constant_tensor = constant_tensor.tobytes().hex()\n            constant_hex_data.append(constant_tensor)\n            total_constant_len += len(constant_tensor) // 2\n        else:\n            if info.btype == BufferType.input_or_output or info.btype == BufferType.input:\n                buffer_type = info.btype\n                if info.btype == BufferType.input_or_output:\n                    buffer_type = classify_io(_buffer)\n                assert buffer_type in (BufferType.input, BufferType.output)\n                address = 0\n                buffer_addresses[_buffer] = (address, buffer_type)\n                buffer_info[_buffer] = BufferInfo(\n                    values=None, shape=info.dtype, dtype=info.dtype, btype=buffer_type\n                )\n            elif info.btype == BufferType.shram:\n                accl_config = util.get_accelerator_config()\n                arch_config = get_accelerator_arch_config(accl_config)\n                address = arch_config.lut_start_address\n                buffer_addresses[_buffer] = (address, info.btype)\n            else:\n                # These buffer_vars are already updated in scratch_region_map\n                assert info.btype == BufferType.scratch\n\n    for npu_op in npu_ops:\n        for attr_name, attr in npu_op.__dict__.items():\n            if isinstance(attr, list):\n                new_attr = list()\n                for attr_ in attr:\n                    new_attr.append(replace_tir_loads(attr_))\n                setattr(npu_op, attr_name, new_attr)\n            else:\n                setattr(npu_op, attr_name, replace_tir_loads(attr))\n\n    constant_data = \"\".join(constant_hex_data)\n    return (npu_ops, constant_data)\n\n\ndef translate_ethosu_tir_call_extern(tir_call_extern):\n    \"\"\"This is a dispatcher function to dispatch\n    correct translation call depending on the extern call's\n    first argument\"\"\"\n    supported_call_extern = {\n        \"ethosu_conv2d\": translate_ethosu_conv2d,\n        \"ethosu_copy\": translate_ethosu_copy,\n        \"ethosu_depthwise_conv2d\": translate_ethosu_depthwise_conv2d,\n        \"ethosu_pooling\": translate_ethosu_pooling,\n        \"ethosu_binary_elementwise\": translate_ethosu_binary_elementwise,\n        \"ethosu_identity\": translate_ethosu_pooling,\n        \"ethosu_unary_elementwise\": translate_ethosu_unary_elementwise,\n    }\n    ext_call_type = tir_call_extern.args[0].value\n    assert ext_call_type in supported_call_extern.keys(), f\"{ext_call_type} is not yet supported\"\n    npu_op = supported_call_extern[ext_call_type](tir_call_extern)\n    # Some conversions return additional outputs\n    # if they are needed, the caller should use the function directly\n    if isinstance(npu_op, tuple):\n        return npu_op[0]\n    return npu_op\n\n\ndef translate_ethosu_copy(tir_call_extern: tvm.tir.Call) -> vapi.NpuDmaOperation:\n    \"\"\"This function will translate a TIR call_extern\n    as produced by NPU Relay to TIR compilation.\n\n    Parameters\n    ----------\n    tir_call_extern : tvm.tir.Call\n\n    Returns\n    -------\n    ethosu.vela.api.NpuDmaOperation\n        The vela object containing the params of ethosu_copy\n    \"\"\"\n    # We skip the first element as it is the call_extern function name\n    serial_object = spec.create_serial_object(spec.SerialCopy, tir_call_extern.args[1:])\n    return _create_npu_dma_op(serial_object)\n\n\ndef _convert_clip_bounds(npu_op: vapi.NpuBlockOperation):\n    \"\"\"This function will convert the min and max value\n    of clip activations to non quantized floats as\n    expected by the API.\n\n    Parameters\n    ----------\n    npu_op : vapi.NpuBlockOperation\n\n    \"\"\"\n    clip_min_quant = npu_op.activation.min\n    clip_max_quant = npu_op.activation.max\n    clip_min_actual = (\n        clip_min_quant - npu_op.ofm.quantization.zero_point\n    ) * npu_op.ofm.quantization.scale_f32\n    clip_max_actual = (\n        clip_max_quant - npu_op.ofm.quantization.zero_point\n    ) * npu_op.ofm.quantization.scale_f32\n    npu_op.activation.min = clip_min_actual\n    npu_op.activation.max = clip_max_actual\n\n\ndef translate_ethosu_conv2d(tir_call_extern: tvm.tir.Call) -> Tuple[vapi.NpuConv2DOperation, int]:\n    \"\"\"This function will translate a TIR call_extern\n    as produced by NPU Relay to TIR compilation.\n\n    Parameters\n    ----------\n    tir_call_extern : tvm.tir.Call\n        This should be a TIR call_extern that has agreed upon ordering\n        for TIR Compiler. See Serial2DConvolution in\n        tvm/relay/backend/contrib/ethosu/tir/spec.py for the ordering.\n\n    Returns\n    -------\n    ethosu.vela.api.NpuConv2DOperation\n        The vela object containing the params of ethosu_conv2d\n    weights_zero_point : int\n        The zero point of the weights\n    \"\"\"\n    # We skip the first element as it is the call_extern function name\n    serial_object = spec.create_serial_object(spec.Serial2DConvolution, tir_call_extern.args[1:])\n    return _create_npu_op_conv2d(serial_object)\n\n\ndef _create_npu_op_conv2d(\n    serial_2d_convolution: spec.Serial2DConvolution,\n) -> Tuple[vapi.NpuConv2DOperation, int]:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuConv2DOperation object.\n    \"\"\"\n    has_two_weights = serial_2d_convolution.weight2.address != -1\n    has_two_biases = serial_2d_convolution.scale_bias2.address != -1\n\n    npu_conv2d_op = vapi.NpuConv2DOperation()\n    npu_conv2d_op.ifm = _create_npu_feature_map(serial_2d_convolution.ifm)\n    npu_conv2d_op.ofm = _create_npu_feature_map(serial_2d_convolution.ofm)\n    npu_conv2d_op.kernel = _create_npu_kernel(serial_2d_convolution.kernel)\n    npu_conv2d_op.weights = (\n        [\n            _create_npu_address_range(serial_2d_convolution.weight),\n            _create_npu_address_range(serial_2d_convolution.weight2),\n        ]\n        if has_two_weights\n        else [_create_npu_address_range(serial_2d_convolution.weight)]\n    )\n    weights_zero_point = np.int64(serial_2d_convolution.weight_zero_point.value)\n    npu_conv2d_op.biases = (\n        [\n            _create_npu_address_range(serial_2d_convolution.scale_bias),\n            _create_npu_address_range(serial_2d_convolution.scale_bias2),\n        ]\n        if has_two_biases\n        else [_create_npu_address_range(serial_2d_convolution.scale_bias)]\n    )\n    npu_conv2d_op.padding = _create_npu_padding(serial_2d_convolution.padding)\n\n    npu_conv2d_op.activation = _create_npu_activation(serial_2d_convolution.activation)\n    if (\n        npu_conv2d_op.activation\n        and npu_conv2d_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    ):\n        _convert_clip_bounds(npu_conv2d_op)\n\n    npu_conv2d_op.rounding_mode = _create_npu_rounding_mode(serial_2d_convolution.rounding_mode)\n    npu_conv2d_op.ifm_upscale = _create_npu_resampling_mode(serial_2d_convolution.upscale)\n    weights_shape_ohwi = [\n        npu_conv2d_op.ofm.shape.depth,\n        npu_conv2d_op.kernel.height,\n        npu_conv2d_op.kernel.width,\n        npu_conv2d_op.ifm.shape.depth,\n    ]\n    npu_conv2d_op.block_traversal = vela_api.calculate_block_traversal_mode(\n        is_depthwise=False,\n        weights_shape_ohwi=weights_shape_ohwi,\n        ifm_bitdepth=npu_conv2d_op.ifm.data_type.size_in_bits(),\n    )\n    npu_conv2d_op.block_config = _create_npu_block_config(serial_2d_convolution.block_config)\n\n    if not npu_conv2d_op.block_config:\n        target_accel_config = vela_api.get_accelerator_config()\n        block_config = vela_api.get_optimal_block_config(npu_conv2d_op, target_accel_config)\n        npu_conv2d_op.block_config = block_config\n\n    return npu_conv2d_op, weights_zero_point\n\n\ndef translate_ethosu_depthwise_conv2d(\n    tir_call_extern: tvm.tir.Call,\n) -> Tuple[vapi.NpuConvDepthWiseOperation, int]:\n    \"\"\"This function will translate a TIR call_extern\n    as produced by NPU Relay to TIR compilation.\n\n    Parameters\n    ----------\n    tir_call_extern : tvm.tir.Call\n        This should be a TIR call_extern that has agreed upon ordering\n        for TIR Compiler. See Serial2DDepthwise in\n        tvm/relay/backend/contrib/ethosu/tir/spec.py for the ordering.\n\n    Returns\n    -------\n    ethosu.vela.api.NpuConvDepthWiseOperation\n        The vela object containing the params of ethosu_depthwise_conv2d\n    weights_zero_point : int\n        The zero point of the weights\n    \"\"\"\n    serial_object = spec.create_serial_object(spec.Serial2DDepthwise, tir_call_extern.args[1:])\n    return _create_npu_op_depthwise_conv2d(serial_object)\n\n\ndef _create_npu_op_depthwise_conv2d(serial_2d_depthwise):\n    npu_depthwise_conv2d_op = vapi.NpuConvDepthWiseOperation()\n\n    npu_depthwise_conv2d_op.ifm = _create_npu_feature_map(serial_2d_depthwise.ifm)\n    npu_depthwise_conv2d_op.ofm = _create_npu_feature_map(serial_2d_depthwise.ofm)\n    npu_depthwise_conv2d_op.kernel = _create_npu_kernel(serial_2d_depthwise.kernel)\n    npu_depthwise_conv2d_op.weights = [_create_npu_address_range(serial_2d_depthwise.weight)]\n    weights_zero_point = np.int64(serial_2d_depthwise.weight_zero_point.value)\n    npu_depthwise_conv2d_op.biases = [_create_npu_address_range(serial_2d_depthwise.scale_bias)]\n    npu_depthwise_conv2d_op.padding = _create_npu_padding(serial_2d_depthwise.padding)\n\n    npu_depthwise_conv2d_op.activation = _create_npu_activation(serial_2d_depthwise.activation)\n    if (\n        npu_depthwise_conv2d_op.activation\n        and npu_depthwise_conv2d_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    ):\n        _convert_clip_bounds(npu_depthwise_conv2d_op)\n\n    npu_depthwise_conv2d_op.rounding_mode = _create_npu_rounding_mode(\n        serial_2d_depthwise.rounding_mode\n    )\n    npu_depthwise_conv2d_op.ifm_upscale = _create_npu_resampling_mode(serial_2d_depthwise.upscale)\n    npu_depthwise_conv2d_op.block_config = _create_npu_block_config(\n        serial_2d_depthwise.block_config\n    )\n\n    if not npu_depthwise_conv2d_op.block_config:\n        target_accel_config = vela_api.get_accelerator_config()\n        block_config = vela_api.get_optimal_block_config(\n            npu_depthwise_conv2d_op, target_accel_config\n        )\n        npu_depthwise_conv2d_op.block_config = block_config\n\n    return npu_depthwise_conv2d_op, weights_zero_point\n\n\ndef _create_npu_feature_map(serial_feature_map: spec.SerialFeatureMap) -> vapi.NpuFeatureMap:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuFeatureMap object.\n    \"\"\"\n    layout_map = {\"NHWC\": vapi.NpuLayout.NHWC, \"NHCWB16\": vapi.NpuLayout.NHCWB16}\n    datatype_map = {\n        \"uint8\": vapi.NpuDataType.UINT8,\n        \"int8\": vapi.NpuDataType.INT8,\n        \"uint16\": vapi.NpuDataType.UINT16,\n        \"int16\": vapi.NpuDataType.INT16,\n        \"int32\": vapi.NpuDataType.INT32,\n    }\n    layout = str(serial_feature_map.layout.value)\n    data_type = str(serial_feature_map.data_type.value)\n    date_type_bytes = np.iinfo(np.dtype(data_type)).bits // 8\n    assert layout in layout_map.keys()\n    assert data_type in datatype_map.keys()\n    nfm = vapi.NpuFeatureMap()\n    nfm.data_type = datatype_map[data_type]\n    nfm.shape = vapi.NpuShape3D(\n        int(serial_feature_map.height),\n        int(serial_feature_map.width),\n        int(serial_feature_map.channels),\n    )\n    nfm.tiles = vapi.NpuTileBox(\n        int(serial_feature_map.tile_height_0),\n        int(serial_feature_map.tile_height_1),\n        int(serial_feature_map.tile_width_0),\n        [\n            serial_feature_map.tile_address_0,\n            serial_feature_map.tile_address_1,\n            serial_feature_map.tile_address_2,\n            serial_feature_map.tile_address_3,\n        ],\n    )\n    nfm.quantization = _create_npu_quantization(\n        serial_feature_map.scale, serial_feature_map.zero_point\n    )\n    nfm.layout = layout_map[layout]\n    nfm.strides = vapi.NpuShape3D(\n        int(serial_feature_map.stride_h.value) * date_type_bytes,\n        int(serial_feature_map.stride_w.value) * date_type_bytes,\n        int(serial_feature_map.stride_c.value) * date_type_bytes,\n    )\n    return nfm\n\n\ndef _create_npu_kernel(serial_kernel: spec.SerialKernel) -> vapi.NpuKernel:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuKernel object.\n    \"\"\"\n    nknl = vapi.NpuKernel(\n        w=int(serial_kernel.width),\n        h=int(serial_kernel.height),\n        stride_x=int(serial_kernel.stride_w),\n        stride_y=int(serial_kernel.stride_h),\n        dilation_x=int(serial_kernel.dilation_w),\n        dilation_y=int(serial_kernel.dilation_h),\n    )\n    return nknl\n\n\ndef _create_npu_address_range(\n    serial_address_range: spec.SerialAddressRange,\n) -> vapi.NpuAddressRange:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuAddressRange object.\n    \"\"\"\n    addr_range = vapi.NpuAddressRange(\n        # region will be updated later\n        region=0,\n        address=serial_address_range.address,\n        length=int(serial_address_range.length),\n    )\n    return addr_range\n\n\ndef _create_npu_quantization(\n    scale: Union[tvm.tir.FloatImm, float],\n    zero_point: Union[tvm.tir.IntImm, int],\n) -> vapi.NpuQuantization:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuQuantization object.\n    \"\"\"\n    return vapi.NpuQuantization(scale_f32=float(scale), zero_point=int(zero_point))\n\n\ndef _create_npu_weights_zero_point(\n    zero_point: Union[int, tvm.tir.IntImm],\n) -> int:\n    \"\"\"This is a helper function to capture the weights zero point.\"\"\"\n    return int(zero_point)\n\n\ndef _create_npu_padding(serial_padding: spec.SerialPadding) -> vapi.NpuPadding:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuPadding object.\"\"\"\n    padding = vapi.NpuPadding(\n        top=int(serial_padding.top),\n        left=int(serial_padding.left),\n        bottom=int(serial_padding.bottom),\n        right=int(serial_padding.right),\n    )\n    return padding\n\n\ndef _create_npu_block_config(serial_block_config: spec.SerialBlockConfig) -> vapi.NpuShape3D:\n    \"\"\"A helper function to convert a SerialBlockConfig into an NpuShape3D\"\"\"\n    if serial_block_config.height * serial_block_config.width * serial_block_config.depth == 0:\n        return None\n\n    block_config = vapi.NpuShape3D(\n        height=int(serial_block_config.height),\n        width=int(serial_block_config.width),\n        depth=int(serial_block_config.depth),\n    )\n    return block_config\n\n\ndef _create_npu_activation(serial_activation: spec.SerialActivation) -> vapi.NpuActivation:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuActivation object.\"\"\"\n    if serial_activation.op == \"NONE\":\n        return None\n    if (\n        serial_activation.op == \"CLIP\"\n        and serial_activation.clip_min == 0\n        and serial_activation.clip_max == 0\n    ):\n        return None\n    op_map = {\n        \"CLIP\": vapi.NpuActivationOp.NONE_OR_RELU,\n        \"TANH\": vapi.NpuActivationOp.TABLE_LOOKUP,\n        \"SIGMOID\": vapi.NpuActivationOp.TABLE_LOOKUP,\n        \"LUT\": vapi.NpuActivationOp.TABLE_LOOKUP,\n    }\n    op = str(serial_activation.op.value)\n    assert op in op_map.keys()\n    act_op = vapi.NpuActivation(op_map[op])\n    if serial_activation.op == \"CLIP\":\n        act_op.min = int(serial_activation.clip_min.value)\n        act_op.max = int(serial_activation.clip_max.value)\n    if op_map[op] == vapi.NpuActivationOp.TABLE_LOOKUP:\n        act_op.lookup_table_index = 0\n    return act_op\n\n\ndef _create_npu_resampling_mode(\n    mode: str,\n) -> vapi.NpuResamplingMode:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuResamplingMode object.\"\"\"\n    mode_map = {\n        \"NONE\": vapi.NpuResamplingMode.NONE,\n        \"NEAREST\": vapi.NpuResamplingMode.NEAREST,\n        \"ZEROS\": vapi.NpuResamplingMode.TRANSPOSE,\n    }\n    mode = str(mode.value)\n    assert mode in mode_map.keys()\n    return mode_map[mode]\n\n\ndef _create_npu_rounding_mode(\n    mode: str,\n) -> vapi.NpuRoundingMode:\n    \"\"\"This is a helper function to capture a list\n    of arguments to create Vela NpuRoundingMode object.\"\"\"\n    mode_map = {\n        \"TFL\": vapi.NpuRoundingMode.TFL,\n        \"TRUNCATE\": vapi.NpuRoundingMode.TRUNCATE,\n        \"NATURAL\": vapi.NpuRoundingMode.NATURAL,\n    }\n    mode = str(mode.value)\n    assert mode in mode_map.keys()\n    return mode_map[mode]\n\n\ndef _create_npu_dma_op(serial_copy):\n    \"\"\"This is a helper function to capture the list of arguments\n    to create a NpuDmaOperation object\"\"\"\n    data_type_bytes = np.iinfo(np.dtype(serial_copy.read_address.dtype)).bits // 8\n    src = vapi.NpuAddressRange(\n        # region will be updated later\n        region=0,\n        address=serial_copy.read_address,\n        length=int(serial_copy.length.value) * data_type_bytes,\n    )\n    dest = vapi.NpuAddressRange(\n        # region will be updated later\n        region=0,\n        address=serial_copy.write_address,\n        length=int(serial_copy.length.value) * data_type_bytes,\n    )\n    return vapi.NpuDmaOperation(src, dest)\n\n\ndef translate_ethosu_pooling(tir_call_extern: tvm.tir.Call) -> vapi.NpuPoolingOperation:\n    \"\"\"This function will translate a TIR call_extern\n    as produced by NPU Relay to TIR compilation.\n\n    Parameters\n    ----------\n    tir_call_extern : tvm.tir.Call\n        This should be a TIR call_extern that has agreed upon ordering\n        for TIR Compiler. See SerialPooling in\n        tvm/relay/backend/contrib/ethosu/tir/spec.py for the ordering.\n\n    Returns\n    -------\n    ethosu.vela.api.NpuPoolingOperation\n        The vela object containing the params of ethosu_pooling\n    \"\"\"\n    serial_object = spec.create_serial_object(spec.SerialPooling, tir_call_extern.args[1:])\n    return _create_npu_op_pooling(serial_object)\n\n\ndef _create_npu_op_pooling(serial_pooling: spec.SerialPooling):\n    pooling_type = serial_pooling.pooling_type\n    if pooling_type == \"AVG\":\n        npu_pooling_op = vapi.NpuPoolingOp.AVERAGE\n    elif pooling_type == \"MAX\":\n        npu_pooling_op = vapi.NpuPoolingOp.MAX\n\n    npu_pooling_op = vapi.NpuPoolingOperation(npu_pooling_op)\n    npu_pooling_op.ifm = _create_npu_feature_map(serial_pooling.ifm)\n    npu_pooling_op.ofm = _create_npu_feature_map(serial_pooling.ofm)\n    npu_pooling_op.kernel = _create_npu_kernel(serial_pooling.pool_shape)\n    npu_pooling_op.padding = _create_npu_padding(serial_pooling.padding)\n\n    npu_pooling_op.activation = _create_npu_activation(serial_pooling.activation)\n    if (\n        npu_pooling_op.activation\n        and npu_pooling_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    ):\n        _convert_clip_bounds(npu_pooling_op)\n\n    npu_pooling_op.rounding_mode = _create_npu_rounding_mode(serial_pooling.rounding_mode)\n    npu_pooling_op.ifm_upscale = _create_npu_resampling_mode(serial_pooling.upscale)\n    npu_pooling_op.block_config = _create_npu_block_config(serial_pooling.block_config)\n\n    if not npu_pooling_op.block_config:\n        target_accel_config = vela_api.get_accelerator_config()\n        block_config = vela_api.get_optimal_block_config(npu_pooling_op, target_accel_config)\n        npu_pooling_op.block_config = block_config\n\n    return npu_pooling_op\n\n\ndef translate_ethosu_binary_elementwise(\n    tir_call_extern: tvm.tir.Call,\n) -> vapi.NpuElementWiseOperation:\n    \"\"\"This function will translate a TIR call_extern\n    as produced by NPU Relay to TIR compilation.\n\n    Parameters\n    ----------\n    tir_call_extern : tvm.tir.Call\n        This should be a TIR call_extern that has agreed upon ordering\n        for TIR Compiler. See SerialBinaryElementwise in\n        tvm/relay/backend/contrib/ethosu/tir/spec.py for the ordering.\n\n    Returns\n    -------\n    ethosu.vela.api.NpuElementWiseOperation\n        The vela object containing the params of ethosu_binary_elementwise\n    \"\"\"\n    serial_object = spec.create_serial_object(\n        spec.SerialBinaryElementwise, tir_call_extern.args[1:]\n    )\n    return _create_npu_op_binary_elementwise(serial_object)\n\n\ndef _create_npu_op_binary_elementwise(serial_binary_elementwise: spec.SerialBinaryElementwise):\n    operator_type = serial_binary_elementwise.operator_type\n    if operator_type == \"ADD\":\n        op = vapi.NpuElementWiseOp.ADD\n    elif operator_type == \"SUB\":\n        op = vapi.NpuElementWiseOp.SUB\n    elif operator_type == \"MUL\":\n        op = vapi.NpuElementWiseOp.MUL\n    elif operator_type == \"MIN\":\n        op = vapi.NpuElementWiseOp.MIN\n    elif operator_type == \"MAX\":\n        op = vapi.NpuElementWiseOp.MAX\n    elif operator_type == \"SHR\":\n        op = vapi.NpuElementWiseOp.SHR\n    elif operator_type == \"SHL\":\n        op = vapi.NpuElementWiseOp.SHL\n\n    npu_binary_elementwise_op = vapi.NpuElementWiseOperation(op)\n    npu_binary_elementwise_op.ifm = _create_npu_feature_map(serial_binary_elementwise.ifm)\n    npu_binary_elementwise_op.ifm2 = _create_npu_feature_map(serial_binary_elementwise.ifm2)\n    npu_binary_elementwise_op.ofm = _create_npu_feature_map(serial_binary_elementwise.ofm)\n    npu_binary_elementwise_op.reversed_operands = serial_binary_elementwise.reversed_operands\n\n    npu_binary_elementwise_op.activation = _create_npu_activation(\n        serial_binary_elementwise.activation\n    )\n    if (\n        npu_binary_elementwise_op.activation\n        and npu_binary_elementwise_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    ):\n        _convert_clip_bounds(npu_binary_elementwise_op)\n\n    npu_binary_elementwise_op.rounding_mode = _create_npu_rounding_mode(\n        serial_binary_elementwise.rounding_mode\n    )\n    npu_binary_elementwise_op.block_config = _create_npu_block_config(\n        serial_binary_elementwise.block_config\n    )\n\n    if not npu_binary_elementwise_op.block_config:\n        target_accel_config = vela_api.get_accelerator_config()\n        block_config = vela_api.get_optimal_block_config(\n            npu_binary_elementwise_op, target_accel_config\n        )\n        npu_binary_elementwise_op.block_config = block_config\n\n    return npu_binary_elementwise_op\n\n\ndef translate_ethosu_unary_elementwise(\n    tir_extern_call: tvm.tir.Call,\n) -> vapi.NpuElementWiseOperation:\n\n    \"\"\"This function will translate a tir extern_call\n    as produced by Relay to TIR compilation.\n    Parameters\n    ----------\n    tir_extern_call : tvm.tir.Call\n        This should be a tir external call that has a agreed upon ordering\n        for the NPU TIR Compiler. See SerialUnaryElementwise in\n        tvm/relay/backend/contrib/ethosu/tir/spec.py for the ordering.\n\n    Returns\n    -------\n    ethosu.vela.api.NpuElementWiseOperation\n        The vela object containing the params of ethosu_unary_elementwise\n    \"\"\"\n    serial_object = spec.create_serial_object(spec.SerialUnaryElementwise, tir_extern_call.args[1:])\n    return _create_npu_op_unary_elementwise(serial_object)\n\n\ndef _create_npu_op_unary_elementwise(serial_unary_elementwise):\n    operator_type = serial_unary_elementwise.operator_type\n    if operator_type == \"ABS\":\n        op = vapi.NpuElementWiseOp.ABS\n    if operator_type == \"CLZ\":\n        op = vapi.NpuElementWiseOp.CLZ\n\n    npu_unary_elementwise_op = vapi.NpuElementWiseOperation(op)\n    npu_unary_elementwise_op.ifm = _create_npu_feature_map(serial_unary_elementwise.ifm)\n    npu_unary_elementwise_op.ofm = _create_npu_feature_map(serial_unary_elementwise.ofm)\n\n    npu_unary_elementwise_op.activation = _create_npu_activation(\n        serial_unary_elementwise.activation\n    )\n    if (\n        npu_unary_elementwise_op.activation\n        and npu_unary_elementwise_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    ):\n        _convert_clip_bounds(npu_unary_elementwise_op)\n\n    npu_unary_elementwise_op.rounding_mode = _create_npu_rounding_mode(\n        serial_unary_elementwise.rounding_mode\n    )\n    npu_unary_elementwise_op.block_config = _create_npu_block_config(\n        serial_unary_elementwise.block_config\n    )\n\n    if not npu_unary_elementwise_op.block_config:\n        target_accel_type = vela_api.get_accelerator_config()\n        block_config = vela_api.get_optimal_block_config(\n            npu_unary_elementwise_op, target_accel_type\n        )\n        npu_unary_elementwise_op.block_config = block_config\n\n    return npu_unary_elementwise_op\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nHelper utility Enums and Functions used through out code generation.\n\nThe rest of the utility functions are misc.\nRefer to the description inside such functions\n\"\"\"\n\nfrom inspect import signature\nfrom enum import Enum\nfrom typing import Union, Tuple, List\nimport numpy as np  # type: ignore\n\nimport tvm  # type: ignore\nfrom tvm import relay\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\nclass QConv2DArgs(Enum):\n    \"\"\"\n    This is a helper enum to obtain the correct index\n    of qnn.conv2d arguments.\n    \"\"\"\n\n    IFM = 0\n    WEIGHTS = 1\n    IFM_ZERO_POINT = 2\n    WEIGHTS_ZERO_POINT = 3\n    IFM_SCALE = 4\n    WEIGHTS_SCALE = 5\n\n\nclass QConv2DTransposeArgs(Enum):\n    \"\"\"\n    This is a helper enum to obtain the correct index\n    of qnn.conv2d_transpose arguments.\n    \"\"\"\n\n    IFM = 0\n    WEIGHTS = 1\n    IFM_ZERO_POINT = 2\n    WEIGHTS_ZERO_POINT = 3\n    IFM_SCALE = 4\n    WEIGHTS_SCALE = 5\n\n\nclass RequantArgs(Enum):\n    \"\"\"\n    This is a helper enum to obtain the correct index\n    of qnn.requantize arguments.\n    \"\"\"\n\n    IFM_SCALE = 1\n    IFM_ZERO_POINT = 2\n    OFM_SCALE = 3\n    OFM_ZERO_POINT = 4\n\n\nclass BiasAddArgs(Enum):\n    \"\"\"\n    This is a helper enums to obtain the correct index\n    of qnn.bias_add arguments.\n    \"\"\"\n\n    BIASES = 1\n\n\nclass ClipArgs(Enum):\n    \"\"\"\n    This is a helper enums to obtain the correct index\n    of clip arguments.\n    \"\"\"\n\n    A_MIN = 1\n    A_MAX = 2\n\n\nclass BinaryElementwiseArgs(Enum):\n    \"\"\"This is a helper enums to access the correct index\n    of binary elementwise arguments\n    \"\"\"\n\n    IFM = 0\n    IFM2 = 1\n    IFM_SCALE = 2\n    IFM_ZERO_POINT = 3\n    IFM2_SCALE = 4\n    IFM2_ZERO_POINT = 5\n    OFM_SCALE = 6\n    OFM_ZERO_POINT = 7\n\n\nclass QuantizeArgs(Enum):\n    \"\"\"\n    This is a helper enums to access the correct index of\n    quantize arguments\n    \"\"\"\n\n    IFM = 0\n    OFM_SCALE = 1\n    OFM_ZERO_POINT = 2\n\n\nclass DequantizeArgs(Enum):\n    \"\"\"\n    This is a helper enums to access the correct index of\n    dequantize arguments\n    \"\"\"\n\n    IFM = 0\n    IFM_SCALE = 1\n    IFM_ZERO_POINT = 2\n\n\nclass QDenseArgs(Enum):\n    \"\"\"\n    This is a helper enum to access the correct index of\n    qnn.dense arguments\n    \"\"\"\n\n    IFM = 0\n    WEIGHTS = 1\n    IFM_ZERO_POINT = 2\n    WEIGHTS_ZERO_POINT = 3\n    IFM_SCALE = 4\n    WEIGHTS_SCALE = 5\n\n\ndef is_npu_func(func: relay.Function) -> bool:\n    \"\"\"Check if the given function is an NPU function.\"\"\"\n    return func.attrs and \"Compiler\" in func.attrs and func.attrs[\"Compiler\"] == \"ethos-u\"\n\n\ndef is_composite_func(func: relay.Function, name: str) -> bool:\n    \"\"\"\n    This method checks whether the call is to\n    a composite function of a given name.\n\n    Parameters\n    ----------\n    func : relay.Function\n        The header to be displayed along with the dump.\n\n    name : str\n        The candidate name to be checked\n\n    Returns\n    --------\n    a boolean\n    \"\"\"\n\n    if not hasattr(func, \"attrs\"):\n        return False\n    if \"Composite\" not in func.attrs.keys():\n        return False\n    composite_name = func.attrs[\"Composite\"]\n\n    return composite_name == name\n\n\ndef is_named_ethosu_op(expr: tvm.relay.Expr, name: str) -> bool:\n    \"\"\"Checks whether a relay expression matches that of the\n    named operator.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The expression to check.\n    name : str\n        The name of the expected operator\n        (without NPU prefix \"contrib.ethosu\").\n\n    Returns\n    -------\n    bool\n        True if expression matches name, false if not.\n    \"\"\"\n    prefix = \"contrib.ethosu.\"\n    return (\n        isinstance(expr, tvm.relay.expr.Call)\n        and isinstance(expr.op, tvm.ir.op.Op)\n        and expr.op.name == prefix + name\n    )\n\n\ndef get_range_for_dtype_str(dtype: str) -> Tuple[int, int]:\n    \"\"\"\n    Produce the min,max for a give data type.\n\n    Parameters\n    ----------\n    dtype : str\n        a type string (e.g., int8)\n\n    Returns\n    -------\n    type_info.min : int\n        the minimum of the range\n    type_info.max : int\n        the maximum of the range\n    \"\"\"\n\n    try:\n        type_info = np.iinfo(dtype)\n    except ValueError:\n        type_info = np.finfo(dtype)\n    return type_info.min, type_info.max\n\n\ndef round_away_zero(f: Union[float, np.double, np.single, np.float32, np.float64]) -> np.float64:\n    \"\"\"Round the number away from zero towards +inf / -inf\"\"\"\n    offset = -0.5 if (f < 0) else 0.5\n    return np.trunc(f + offset)\n\n\ndef round_up(a: int, b: int) -> int:\n    \"\"\"Round up to a multiple of b\"\"\"\n    return ((a + b - 1) // b) * b\n\n\ndef get_accelerator_config():\n    \"\"\"Get the variant of the accelerator to compile for\"\"\"\n    compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n    return compiler_attrs.accelerator_config\n\n\ndef is_cascader_enabled():\n    \"\"\"Determine whether the cascader is enabled\"\"\"\n    compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n    return compiler_attrs.enable_cascader\n\n\ndef is_striping_enabled():\n    \"\"\"Determine whether the cascader is enabled\"\"\"\n    compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n    return compiler_attrs.enable_striping\n\n\ndef get_arg_count(func):\n    \"\"\"Helper function to get the number of\n    arguments in a python function\"\"\"\n    sig = signature(func)\n    return len(sig.parameters)\n\n\ndef get_dim_value(layout: str, dim: int):\n    \"\"\"This is a helper function to retrieve the value\n    of the dimension given the shape and the layout\n    \"\"\"\n    assert isinstance(layout, str)\n    assert dim in list(layout)\n    for idx, dim_char in enumerate(layout):\n        if dim_char == dim:\n            return idx\n    return None\n\n\ndef calculate_size_bytes(expr):\n    \"\"\"This is a helper function to calculate the number\n    of bytes required to hold the tensor/relay.expr\"\"\"\n    try:\n        type_info = np.iinfo(expr.checked_type.dtype)\n    except ValueError:\n        type_info = np.finfo(expr.checked_type.dtype)\n    element_size = type_info.bits // 8\n    elements = np.prod(list(expr.checked_type.shape))\n    return element_size * elements\n\n\n@register_object(\"relay.ext.ethos-u.BaseAddress\")\nclass BaseAddress(Object):\n    \"\"\"\n    This is a structure to hold base addresses for pointers\n    provided for the driver.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        primfunc_param_idx: int,\n        region: int,\n        size: int,\n        is_runtime_allocation: bool = False,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BaseAddress,  # type: ignore # pylint: disable=no-member\n            name,\n            primfunc_param_idx,\n            region,\n            size,\n            is_runtime_allocation,\n        )\n\n\n@register_object(\"relay.ext.ethos-u.CompilationArtifact\")\nclass CompilationArtifact(Object):\n    \"\"\"\n    This is a structure to hold binary artifacts\n    for the microNPU.\n    \"\"\"\n\n    def __init__(\n        self,\n        function_name: str,\n        command_stream: str,\n        encoded_constants: str,\n        base_addresses: List[BaseAddress],\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.CompilationArtifact,  # type: ignore # pylint: disable=no-member\n            function_name,\n            command_stream,\n            encoded_constants,\n            base_addresses,\n        )\n\n\ndef create_npu_function_pass(opt_level: int, name: str = \"\"):\n    \"\"\"\n    A utility decorator that wraps a given class as an NPU function pass. That is,\n    a pass that behaves like a function pass and only traverses NPU external\n    functions. How each NPU function is mutated is defined by the\n    `transform_npu_function(global_variable, relay_function)` function which should\n    be created in the class that is to be decorated. See the example below.\n\n    Example\n    -------\n    This small example demonstrates a pass over NPU functions that performs no\n    mutation.\n\n    @create_npu_function_pass(opt_level=1)\n    class MyPass:\n        def transform_npu_function(self, global_var, func):\n            return func\n\n    mod = tvm.IRModule()\n    mod = MyPass()(mod)\n\n    Parameters\n    ----------\n    opt_level: int\n        Optimization level for the module pass.\n    name: str, optional\n        Name for the module pass.\n\n    Returns\n    -------\n    decorator\n        The npu_pass decorator.\n    \"\"\"\n\n    def decorator(npu_pass_class):\n        @tvm.ir.transform.module_pass(name=name, opt_level=opt_level)\n        class ModulePassWrapper:\n            \"\"\"The wrapper for the NPU pass.\"\"\"\n\n            def __init__(self, *args, **kwargs):\n                self.args = args\n                self.kwargs = kwargs\n\n            def transform_module(self, mod: tvm.ir.IRModule, _) -> tvm.ir.IRModule:\n                npu_functions = filter(lambda x: is_npu_func(x[1]), mod.functions.items())\n                for global_var, func in npu_functions:\n                    npu_pass = npu_pass_class(*self.args, **self.kwargs)\n                    func = npu_pass.transform_npu_function(global_var, func)\n                    mod.update_func(global_var, func)\n                return mod\n\n        return ModulePassWrapper\n\n    return decorator\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/ethosu/vela_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis is an adapter module for conversions between TVM and Vela.\nThe following conversion APIs are added :\n    *Obtaining the best block config\n    *Compressing weights\n    *Packing biases\n\"\"\"\nimport logging\nimport math\nfrom typing import Tuple, Optional, List\nimport numpy as np  # type: ignore\nfrom ethosu.vela import api as vapi  # type: ignore\n\nimport tvm\nfrom tvm.relay.backend.contrib.ethosu import util  # type: ignore\nfrom tvm.relay.backend.contrib.ethosu import tir_to_cs_translator as tirtocs\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"Ethos-U\")\n\nVELA_TO_NP_DTYPES = {\n    vapi.NpuDataType.UINT8: np.uint8,\n    vapi.NpuDataType.UINT16: np.uint16,\n    vapi.NpuDataType.INT8: np.int8,\n    vapi.NpuDataType.INT16: np.int16,\n    vapi.NpuDataType.INT32: np.int32,\n}\n\nSCALE_BIAS_LENGTH = 10\n\n\ndef get_optimal_block_config(\n    npu_op: vapi.NpuOperation, accel_config: vapi.NpuAccelerator\n) -> vapi.NpuShape3D:\n    \"\"\"\n    \"The NPU's unit of work is known as a block. It will fetch block(s) from Input\n    Feature Map (IFM) and a compute block for Output Feature Map (OFM).\n    Therefore, we need to pick an optimal block configuration considering bandwidth\n    to bring IFM blocks and the number of OFM block computes need to happen\n    to cover the OFM as indicated by the npu op.\n\n    Parameters\n    ----------\n    npu_op : ethosu.vela.api.NpuOperation\n        The NPU operation and its params\n    accel_config : ethosu.vela.api.NpuAccelerator\n        The NPU accelerator config\n\n    Returns\n    -------\n    ethosu.vela.api.NpuShape3D :\n        The optimal block config for the operator\n    \"\"\"\n    options = tvm.transform.PassContext.current().config.get(\"relay.ext.ethos-u.options\", None)\n    if options and options.dev_force_block_config:\n        block_config = [int(v) for v in options.dev_force_block_config.split(\"x\")]\n        return vapi.NpuShape3D(height=block_config[0], width=block_config[1], depth=block_config[2])\n    all_valid_block_configs = vapi.npu_find_block_configs(npu_op, accel_config)\n    return _get_optimal_block_config(all_valid_block_configs)\n\n\ndef _get_optimal_block_config(all_valid_block_configs: List[vapi.NpuShape3D]) -> vapi.NpuShape3D:\n    \"\"\"An internal function to get block config with largest depth\n    and then highest volume/area\"\"\"\n    assert isinstance(all_valid_block_configs, list)\n    for block_cfg in all_valid_block_configs:\n        assert isinstance(block_cfg, vapi.NpuShape3D)\n\n    # Getting the largest volume block for benchmarking\n    all_valid_block_configs.sort(\n        key=lambda _cfg: _cfg.depth * _cfg.height * _cfg.width, reverse=True\n    )\n    largest_volume_block_config = all_valid_block_configs[0]\n    largest_volume = (\n        largest_volume_block_config.depth\n        * largest_volume_block_config.height\n        * largest_volume_block_config.width\n    )\n\n    all_valid_block_configs.sort(key=lambda _cfg: _cfg.depth, reverse=True)\n    max_d = all_valid_block_configs[0].depth\n    max_depth_block_configs = [_cfg for _cfg in all_valid_block_configs if _cfg.depth == max_d]\n    max_depth_block_configs.sort(key=lambda _cfg: _cfg.height * _cfg.width, reverse=True)\n    max_area = max_depth_block_configs[0].height * max_depth_block_configs[0].width\n    max_area_depth_block_configs = [\n        _cfg for _cfg in max_depth_block_configs if _cfg.height * _cfg.width == max_area\n    ]\n    # This to get a deterministic anwser everytime\n    max_area_depth_block_configs.sort(key=lambda _cfg: _cfg.height, reverse=True)\n    assert len(max_area_depth_block_configs) > 0\n    current_volume = (\n        max_area_depth_block_configs[0].depth\n        * max_area_depth_block_configs[0].height\n        * max_area_depth_block_configs[0].width\n    )\n    logger.info(\"Using block config=%s\", max_area_depth_block_configs[0])\n    logger.info(\n        \"Quality of the block config w.r.t. max volume block config=%s\",\n        100.0 * (current_volume / largest_volume),\n    )\n    return max_area_depth_block_configs[0]\n\n\ndef encode_weights(\n    tir_extern_call: tvm.tir.Call, values: np.ndarray, accel_config: vapi.NpuAccelerator\n):\n    \"\"\"This is an API function to compress weights by passing\n    a tir_extern_call to NPU Convolution operation and values.\n\n    Parameters\n    ----------\n    tir_extern_call : tvm.tir.Call\n        tir_extern_call to NPU Convolution operation\n    values : numpy.ndarray\n        The constant flattened weight data in OHWI layout\n    accel_config : ethosu.vela.api.NpuAccelerator\n        The NPU accelerator config\n\n    Returns\n    -------\n    bytearray\n        Compressed weights\n    \"\"\"\n    supported_ops = {\n        \"ethosu_conv2d\": tirtocs.translate_ethosu_conv2d,\n        \"ethosu_depthwise_conv2d\": tirtocs.translate_ethosu_depthwise_conv2d,\n    }\n    op = str(tir_extern_call.args[0].value)\n    assert op in supported_ops.keys()\n    npu_op, weights_zero_point = supported_ops[op](tir_extern_call)\n    is_depthwise = op == \"ethosu_depthwise_conv2d\"\n    # Recover the original shape if we are dealing with a flattened tensor\n    if len(values.shape) == 1:\n        shape_ohwi = (\n            npu_op.ofm.shape.depth,\n            npu_op.kernel.height,\n            npu_op.kernel.width,\n            1 if is_depthwise else npu_op.ifm.shape.depth,\n        )\n        assert values.size == np.prod(shape_ohwi)\n        values = np.reshape(values, shape_ohwi)\n\n    return compress_weights(\n        weights=values,\n        weights_zp=weights_zero_point,\n        # The weight layout is assumed to be OHWI, always.\n        weights_layout=\"OHWI\",\n        ifm_bitdepth=npu_op.ifm.data_type.size_in_bits(),\n        block_depth=npu_op.block_config.depth,\n        dilation=(npu_op.kernel.dilation_x, npu_op.kernel.dilation_y),\n        accel_config=accel_config,\n        is_depthwise=is_depthwise,\n    )\n\n\ndef compress_weights(\n    weights: np.ndarray,\n    weights_zp: int,\n    weights_layout: str,\n    ifm_bitdepth: int,\n    block_depth: int,\n    dilation: Tuple[int, int],\n    accel_config: vapi.NpuAccelerator,\n    is_depthwise: Optional[bool] = False,\n) -> bytearray:\n    \"\"\"The NPU requires the weights to be compressed\n    to be executed. Therefore, this function calls into\n    the Vela APIs to compress the weights.\n\n    Parameters\n    ----------\n    weights : numpy.ndarray\n        The raw weights\n    weights_zp : int\n        The zero point of the weights\n    weights_layout : str\n        A string literal indicating the layout\n        Supported values : HWIO, HWOI, OHWI\n    ifm_bitdepth : int\n        The bit depth of the ifm the weights are used with\n    block_depth : int\n        The depth of the optimal block config for the operator\n    dilation : tuple\n        A tuple of 2 elements indicating dilation in h and w\n    accel_config : ethosu.vela.api.NpuAccelerator\n        The NPU accelerator config\n    is_depthwise : bool, Optional\n        This indicates whether the weights are compressed for depthwise convolution\n\n    Returns\n    -------\n    compressed_weights : bytearray\n        Compressed weights\n    \"\"\"\n    layout_transform_indices = {\"HWIO\": (3, 0, 1, 2), \"HWOI\": (2, 0, 1, 3), \"OHWI\": (0, 1, 2, 3)}\n    assert weights_layout in layout_transform_indices.keys()\n    assert isinstance(weights_zp, np.int64)\n    weights = weights.astype(np.int16) - weights_zp\n    # Vela needs the weights in OHWI layout\n    weights_ohwi = np.transpose(weights, layout_transform_indices[weights_layout])\n    shape_ohwi = [\n        weights.shape[layout_transform_indices[weights_layout][0]],\n        weights.shape[layout_transform_indices[weights_layout][1]],\n        weights.shape[layout_transform_indices[weights_layout][2]],\n        weights.shape[layout_transform_indices[weights_layout][3]],\n    ]\n    block_traversal = calculate_block_traversal_mode(is_depthwise, shape_ohwi, ifm_bitdepth)\n\n    compressed_weights = vapi.npu_encode_weights(\n        accelerator=accel_config,\n        weights_volume=weights_ohwi,\n        dilation_xy=dilation,\n        ifm_bitdepth=ifm_bitdepth,\n        ofm_block_depth=block_depth,\n        is_depthwise=is_depthwise,\n        block_traversal=block_traversal,\n    )\n    return compressed_weights\n\n\ndef calculate_block_traversal_mode(\n    is_depthwise: bool, weights_shape_ohwi: List[int], ifm_bitdepth: int\n) -> vapi.NpuBlockTraversal:\n    \"\"\"Calculate a block traversal mode given whether the op is depthwise convolution,\n    shape of weights and bit-depth of the ifm.\n    \"\"\"\n\n    if is_depthwise:\n        return vapi.NpuBlockTraversal.DEPTH_FIRST\n    # Determine which block traversal strategy has better DPU utilization\n    kernel_size = weights_shape_ohwi[1] * weights_shape_ohwi[2]\n    depth_utilization = weights_shape_ohwi[3] / util.round_up(\n        weights_shape_ohwi[3], 32 if ifm_bitdepth == 8 else 16\n    )\n    part_kernel_utilization = (weights_shape_ohwi[3] / util.round_up(weights_shape_ohwi[3], 8)) * (\n        kernel_size / util.round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)\n    )\n    if part_kernel_utilization >= depth_utilization or weights_shape_ohwi[3] <= 8:\n        # Part-kernel first is always better for ifm depths <= 8\n        return vapi.NpuBlockTraversal.PART_KERNEL_FIRST\n    return vapi.NpuBlockTraversal.DEPTH_FIRST\n\n\ndef pack_biases(\n    biases: np.ndarray,\n    ifm_scale: float,\n    ifm_dtype: np.dtype,\n    weight_scales: np.ndarray,\n    ofm_scale: float,\n    is_activation_tanh_or_sigmoid: bool = False,\n) -> np.ndarray:\n    \"\"\"\n    The NPU requires the each bias value to be packed with\n    output scale parameters in a 80-bit format (that is returned\n    via npu_encode_bias API). This function will pack such values\n    to a binary artifact that the NPU will use in the execution.\n\n\n    Parameters\n    ----------\n    biases : numpy.ndarray\n        The values of biases\n    ifm_scale : float\n        The quantization scale parameter of input feature map\n    ifm_dtype : numpy.dtype\n        The data type of input feature map data.\n    weight_scales : numpy.ndarray\n        The quantization scale parameter of weight feature map\n        This could be a tuple if per-channel quantization is present.\n    ofm_scale : float\n        The quantization scale parameter of output feature map.\n    is_activation_tanh_or_sigmoid : bool\n        Indicates whether the fused activation function is tanh or sigmoid.\n\n    Returns\n    -------\n    scale_bias : numpy.ndarray\n        Packed scales/biases as the hardware requires them.\n    \"\"\"\n    # The BYOC infra should not partition anything else.\n    supported_ifm_dtypes = (np.uint8, np.int8, np.int16)\n    assert ifm_dtype in supported_ifm_dtypes\n\n    if weight_scales.size == 1:\n        weight_scales = [weight_scales] * biases.size\n\n    hw_bias_scales = _calculate_hw_bias_scales(\n        ifm_scale, weight_scales, ofm_scale, ifm_dtype, is_activation_tanh_or_sigmoid\n    )\n    assert len(hw_bias_scales) == biases.size\n    biases = biases.astype(\"int64\")\n    packed_biases = bytearray()\n    for idx, scale in enumerate(hw_bias_scales):\n        packed_biases.extend(vapi.npu_encode_bias(biases[idx], *scale))\n    scale_bias = np.frombuffer(packed_biases, dtype=np.uint8)\n    scale_bias = np.reshape(scale_bias, (-1, 10))\n    return scale_bias\n\n\ndef _quantize_scale(scale: float) -> Tuple[int, int]:\n    \"\"\"Quantize floating point scale into 32-bit int scale with a 6-bit shift.\n    This is to be used with 8-bit data.\n    \"\"\"\n    mantissa, exponent = math.frexp(scale)\n    mantissa_scaled = mantissa * (1 << 31)\n    mantissa_scaled = int(util.round_away_zero(mantissa_scaled))\n    required_shift = 31 - exponent\n    if required_shift < 0 or required_shift >= (1 << 6):\n        # Shift outside of valid range, set scale to 0\n        return 0, 16\n\n    return mantissa_scaled, required_shift\n\n\ndef _reduced_quantize_scale(scale: float) -> Tuple[int, int]:\n    \"\"\"A reduction of precision is required for 16 bit data.\"\"\"\n    mantissa_scaled, required_shift = _quantize_scale(scale)\n    # This is max a signed 16-bit number could represent\n    max_reduced_mantissa_scaled = (1 << 15) - 1\n    # if the current value is larger than pre-scaled max_reduced_mantissa_scaled\n    # we need to saturate the anwser to max_reduced_mantissa_scaled\n    if mantissa_scaled >= max_reduced_mantissa_scaled << 16:\n        reduced_mantissa_scaled = max_reduced_mantissa_scaled\n    else:\n        reduced_mantissa_scaled = (mantissa_scaled + (1 << 15)) >> 16\n    reduced_shift = required_shift - 16\n\n    if required_shift < 0 or required_shift >= (1 << 6):\n        # Shift outside of valid range, set scale to 0\n        return 0, 16\n\n    return reduced_mantissa_scaled, reduced_shift\n\n\ndef _calculate_hw_bias_scales(\n    ifm_scale: float,\n    weight_scales: List[float],\n    ofm_scale: float,\n    ifm_dtype: np.dtype,\n    is_faf_tanh_sigmoid: bool = False,\n) -> List[Tuple[int, int]]:\n    \"\"\"This function will produce a scale that is calculated using scales of ifm,\n    weights and ofm. It is also important to note that if per-channel / per-value\n    quantization required they should go into hw bias scales\"\"\"\n    if is_faf_tanh_sigmoid:\n        ifm_scale = ifm_scale * 0x3000\n    if ifm_dtype == np.uint8:\n        bias_scales = [np.double(ifm_scale * ws) / np.double(ofm_scale) for ws in weight_scales]\n    else:\n        assert ifm_dtype in (np.int8, np.int16)\n        ifm_scale_dbl = np.double(ifm_scale)\n        ofm_scale_dbl = np.double(ofm_scale)\n        bias_scales = [ifm_scale_dbl * np.double(ws) / ofm_scale_dbl for ws in weight_scales]\n\n    if ifm_dtype == np.int16:\n        hw_bias_scales = [_reduced_quantize_scale(bs) for bs in bias_scales]\n    else:\n        assert ifm_dtype in (np.uint8, np.int8)\n        hw_bias_scales = [_quantize_scale(bs) for bs in bias_scales]\n\n    return hw_bias_scales\n\n\ndef get_accelerator_config() -> vapi.NpuAccelerator:\n    \"\"\"Get the configuration of the NPU accelerator.\n\n    The configuration string provided as a compiler option is converted into\n    an NpuAccelerator object. Valid configuration strings:\n     - 'ethos-u55-256'\n     - 'ethos-u55-128'\n     - 'ethos-u55-64'\n     - 'ethos-u55-32'\n\n    \"\"\"\n    npu_accel_str_map = {\n        \"ethos-u55-256\": vapi.NpuAccelerator.Ethos_U55_256,\n        \"ethos-u55-128\": vapi.NpuAccelerator.Ethos_U55_128,\n        \"ethos-u55-64\": vapi.NpuAccelerator.Ethos_U55_64,\n        \"ethos-u55-32\": vapi.NpuAccelerator.Ethos_U55_32,\n        \"ethos-u65-256\": vapi.NpuAccelerator.Ethos_U65_256,\n        \"ethos-u65-512\": vapi.NpuAccelerator.Ethos_U65_512,\n    }\n    compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n    accel_config_str = compiler_attrs.accelerator_config\n    assert accel_config_str in npu_accel_str_map.keys(), f\"{accel_config_str} is not supported\"\n    return npu_accel_str_map[accel_config_str]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"UMA modules for Relay.\"\"\"\n\nfrom .backend import UMABackend\nfrom .api.utils import uma_available\n\n__all__ = [\"UMABackend\", \"uma_available\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"UMA: Universal Modular Accelerator Interface API\"\"\"\n\nfrom .codegen import UMACodegen\nfrom .lower import UMALower\nfrom .partitioner import UMAPartitioner\n\n\n__all__ = [\"UMACodegen\", \"UMALower\", \"UMAPartitioner\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for relay transformation passes.\"\"\"\nimport tvm._ffi  # type: ignore\n\ntvm._ffi._init_api(\"relay.ext.uma\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Codegen base class of the Universal Modular Accelerator Interface (UMA)\"\"\"\n\nfrom typing import Callable, Optional\nimport tvm\n\n\nclass UMACodegen(object):\n    \"\"\"\n    Codegen base class of the Universal Modular Accelerator Interface (UMA)\n    \"\"\"\n\n    def __init__(self, target_name: str) -> None:\n        self.target_name = target_name\n\n    def _register_codegen(\n        self, fmt: str = \"c\", includes: Optional[Callable[[], str]] = None, **kwargs\n    ) -> None:\n        \"\"\"Registration codegen in UMA.\n\n        Parameters\n        ----------\n        fmt: str\n            format of codegen. Currently only \"c\" is supported.\n        includes : OptionalCallable[[], str]]\n            user-defined function that adds C-#include statement to UMA C-Code.\n        \"\"\"\n        if fmt == \"c\":\n            self._register_c_codegen(includes, **kwargs)\n        else:\n            raise RuntimeError(f'Unsupported codegen format \"{fmt}\"')\n\n    def _register_c_codegen(self, includes: Optional[Callable[[], str]] = None) -> None:\n        \"\"\"Registration of UMA helper functions, e.g. includes and replace_call_extern.\n\n        Parameters\n        ----------\n        includes : OptionalCallable[[], str]]\n            user-defined function that adds C-#include statement to UMA C-Code.\n        \"\"\"\n        if includes is not None:\n            tvm._ffi.register_func(\n                f\"relay.ext.uma.codegen_c_includes_{self.target_name}\",\n                includes,\n                override=True,\n            )\n\n    def register(self) -> None:\n        pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/lower.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Lowering base class of the Universal Modular Accelerator Interface (UMA)\"\"\"\n\nfrom typing import List, Tuple, Callable, Optional\n\nimport tvm\nfrom tvm import relay, te\nfrom tvm.relay.op.op import register_strategy\nfrom . import _ffi_api\nfrom .utils import PassPhase\n\nOperatorStrategies = List[\n    Tuple[\n        str,\n        Callable[\n            [tvm.ir.Attrs, tvm.ir.Array, tvm.ir.TensorType, tvm.target.Target],\n            tvm.relay.op.op.OpStrategy,\n        ],\n        Optional[int],\n    ]\n]\n\n\nclass UMALower:\n    \"\"\"Lowering base class of the Universal Modular Accelerator Interface (UMA).\"\"\"\n\n    def __init__(self, target_name: str) -> None:\n        self.target_name = target_name\n        self._operator_strategies: OperatorStrategies = []\n        self._tir_passes: List[Tuple[PassPhase, tvm.tir.transform.PrimFuncPass]] = []\n\n    def _lower_relay_to_tir(self, relay_prim_func: relay.Function) -> tvm.tir.PrimFunc:\n        \"\"\"Lower a Relay primitive function to a S-TIR primitive function.\n\n        Parameters\n        ----------\n        prim_func : tvm.relay.Function\n            The Relay function to lower.\n\n        Returns\n        -------\n        out : tvm.tir.PrimFunc\n            The lowered schedulable TensorIR primitive function.\n\n        \"\"\"\n\n        def _get_tensors(te_cached_func):\n            return list(te_cached_func.inputs) + list(te_cached_func.outputs)\n\n        lower_to_te = tvm._ffi.get_global_func(\"relay.backend.LowerToTE\")\n        te_cached_func = lower_to_te(relay_prim_func)\n        x = _get_tensors(te_cached_func)\n        tir_prim_func = te.create_prim_func(x)\n        tir_prim_func = tir_prim_func.with_attr(\n            \"global_symbol\", relay_prim_func.attrs[\"global_symbol\"]\n        )\n\n        compiler_attr = relay_prim_func.attrs[\"Compiler\"]\n        target = tvm.target.Target.current()\n        if target.kind.name != compiler_attr:\n            target = tvm.target.Target(compiler_attr)\n\n        tir_prim_func = tir_prim_func.with_attr(\"target\", target)\n        tir_prim_func = tir_prim_func.with_attr(\"relay_attrs\", relay_prim_func.attrs)\n        return tir_prim_func\n\n    def _lower_stir_to_nstir(self, prim_func: tvm.tir.PrimFunc) -> tvm.tir.PrimFunc:\n        \"\"\"Lower a S-TIR primitive function to a NS-TIR primitive function.\n\n        Parameters\n        ----------\n        prim_func : tvm.tir.PrimFunc\n            The primitive function to lower.\n\n        Returns\n        -------\n        out : tvm.tir.PrimFunc\n            The lowered non-schedulable TensorIR primitive function.\n\n        \"\"\"\n        curr_ctxt = tvm.transform.PassContext().current()\n        assert \"tir.add_lower_pass\" not in curr_ctxt.config\n\n        pass_map = {\n            PassPhase.TIR_PHASE_0: 0,\n            PassPhase.TIR_PHASE_1: 1,\n            PassPhase.TIR_PHASE_2: 2,\n            PassPhase.TIR_PHASE_3: 3,\n        }\n        lower_passes = [(pass_map[k], v) for k, v in self._tir_passes]\n\n        with tvm.transform.PassContext(\n            opt_level=curr_ctxt.opt_level,\n            required_pass=curr_ctxt.required_pass,\n            disabled_pass=curr_ctxt.disabled_pass,\n            instruments=curr_ctxt.instruments,\n            config={**dict(curr_ctxt.config), \"tir.add_lower_pass\": lower_passes},\n        ):\n            mod = tvm.lower(tvm.ir.IRModule.from_expr(prim_func))\n        prim_func = mod[prim_func.attrs[\"global_symbol\"]]\n        return prim_func\n\n    def relay_to_tir(self, mod: tvm.ir.IRModule) -> tvm.ir.IRModule:\n        \"\"\"\n        This is the hook for python-based lowering of a Relay module which lowers NPU\n        external functions to TIR.\n\n        Parameters\n        ----------\n        mod : tvm.ir.IRModule\n            This is the Relay module.\n\n        Returns\n        -------\n        mod : tvm.ir.IRModule\n            The Relay module with scheduled NPU external functions.\n        \"\"\"\n        mod = _ffi_api.OutlineCompilerFunctions(self.target_name)(mod)\n        for gvar, func in mod.functions.items():\n            if \"Compiler\" in func.attrs and func.attrs[\"Compiler\"] == self.target_name:\n                func = self._lower_relay_to_tir(func)\n                func = self._lower_stir_to_nstir(func)\n                mod.update_func(gvar, func)\n        return mod\n\n    def register(self) -> None:\n        \"\"\"Register all relevant relay-to-tir functions.\"\"\"\n        tvm._ffi.register_func(f\"relay.ext.uma.{self.target_name}.relay_to_tir\", self.relay_to_tir)\n        for op, strategy, plevel in self._operator_strategies:\n            register_strategy(op, strategy, plevel)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/partitioner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Partitioner base class of the Universal Modular Accelerator Interface (UMA)\"\"\"\n\nfrom typing import Callable, Dict, List, Tuple, Optional\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.contrib.register import register_pattern_table\nfrom .utils import PassPhase\n\n\nPatternTable = List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Callable]]\n\n\nclass UMAPartitioner:\n    \"\"\"Partitioner base class of the Universal Modular Accelerator Interface (UMA).\"\"\"\n\n    def __init__(self, target_name: str, merge_compiler_regions: bool = True) -> None:\n        self.target_name = target_name\n        self.merge_compiler_regions = merge_compiler_regions\n\n        self._relay_passes: List[Tuple[PassPhase, tvm.transform.Pass]] = []\n        self._patterns: PatternTable = []\n\n    def add_pattern(\n        self,\n        name: str,\n        pattern: tvm.relay.dataflow_pattern.DFPattern,\n        predicate: Optional[Callable] = None,\n    ) -> None:\n        \"\"\"Add pattern to UMA partitioner\n\n        Parameters\n        ----------\n        name : str\n            relay name of pattern\n\n        pattern: tvm.relay.dataflow_pattern.DFPattern\n            pattern description as DFPattern\n\n        predicate: Optional[Callable]\n            Optional predicate\n\n        \"\"\"\n\n        name = self.target_name + \".\" + name\n        if predicate:\n            self._patterns.append((name, pattern, predicate))\n        else:\n            self._patterns.append((name, pattern))\n\n    def _pattern_table(self) -> PatternTable:\n        return self._patterns\n\n    def register(self) -> None:\n        \"\"\"Register all relevant relay-to-relay functions.\"\"\"\n        register_pattern_table(self.target_name, self._pattern_table)\n\n    def partition(\n        self, mod: tvm.IRModule, params: Optional[Dict[str, tvm.runtime.NDArray]] = None\n    ) -> tvm.IRModule:\n        \"\"\"Partition the relay graph in parts supported and unsupported by the\n        target hardware accelerator.\n\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            The relay module to be partitioned.\n\n        params: Optional[Dict[str, tvm.runtime.NDArray]]\n\n        Returns\n        -------\n        out : tvm.IRModule\n            The partitioned relay module.\n\n        \"\"\"\n        if params:\n            mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n        pass_sequence = []\n        pass_sequence.extend(\n            [p[1] for p in self._relay_passes if p[0] == PassPhase.PRE_PARTITIONING]\n        )\n        pass_sequence.append(relay.transform.MergeComposite(self._pattern_table()))\n        pass_sequence.append(relay.transform.AnnotateTarget(self.target_name))\n        if self.merge_compiler_regions:\n            pass_sequence.append(relay.transform.MergeCompilerRegions())\n        pass_sequence.append(relay.transform.PartitionGraph())\n        pass_sequence.extend(\n            [p[1] for p in self._relay_passes if p[0] == PassPhase.POST_PARTITIONING_0]\n        )\n\n        sequential_passes = tvm.transform.Sequential(pass_sequence)\n        mod = sequential_passes(mod)\n\n        # Defunctionalize the partitioned functions to allow lowering\n        for gvar, func in mod.functions.items():\n            mod.update_func(gvar, relay.transform.Defunctionalization(func, mod))\n\n        post_partition_passes_1 = tvm.transform.Sequential(\n            [p[1] for p in self._relay_passes if p[0] == PassPhase.POST_PARTITIONING_1]\n        )\n        mod = post_partition_passes_1(mod)\n\n        return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/api/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility methods for the Universal Modular Accelerator Interface (UMA)\"\"\"\n\nfrom enum import Enum, auto\nimport uuid\n\nimport tvm\nimport tvm.tir\nfrom tvm.contrib import utils, clang\n\n\ndef uma_available() -> bool:\n    registration_func = tvm.get_global_func(\n        \"relay.backend.contrib.uma.RegisterTarget\", allow_missing=True\n    )\n    return registration_func is not None\n\n\nclass PassPhase(Enum):\n    \"\"\"\n    UMA pass phases:\n\n    PRE_PARTITIONING: prior to UMA partitioning\n    POST_PARTITIONING_0: after UMA partitioning, before Defunctionalization\n    POST_PARTITIONING_1: after UMA partitioning and after Defunctionalization\n    TIR_PHASE_0: Generates the raw IR and loop levels.\n    TIR_PHASE_1: Flattens the array storage.\n    TIR_PHASE_2: Transforms loops, like unroll, vectorization and thread-binding.\n    TIR_PHASE_3: Does some cleanup work.\n\n    Reference to TIR phases: src/driver/driver_api.c\n    \"\"\"\n\n    PRE_PARTITIONING = auto()\n    POST_PARTITIONING_0 = auto()\n    POST_PARTITIONING_1 = auto()\n    TIR_PHASE_0 = auto()\n    TIR_PHASE_1 = auto()\n    TIR_PHASE_2 = auto()\n    TIR_PHASE_3 = auto()\n\n\ndef _c_to_llvm(c_code: str) -> str:\n    unique_filename = str(uuid.uuid4())\n    temp = utils.tempdir()\n    ll_path = temp.relpath(f\"{unique_filename}.ll\")\n    ll_code = clang.create_llvm([c_code], output=ll_path)\n    return ll_code\n\n\ndef add_llvm_to_block(\n    sch: tvm.tir.Schedule, block_name: str, c_code_str: str = \"\"\n) -> tvm.tir.Schedule:\n    block = sch.get_block(block_name)\n    loops = sch.get_loops(block)\n    assert len(loops) > 0\n    sch.annotate(loops[0], \"pragma_import_llvm\", _c_to_llvm(c_code_str))\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/contrib/uma/backend.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend base class of the Universal Modular Accelerator Interface (UMA)\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Union, Dict, Callable, Optional, Any\n\nimport tvm\nfrom tvm.relay.backend.contrib.uma.api.codegen import UMACodegen\nfrom tvm.relay.backend.contrib.uma.api.lower import UMALower\nfrom tvm.relay.backend.contrib.uma.api.partitioner import UMAPartitioner\nfrom tvm.relay.backend.contrib.uma.api.utils import PassPhase\n\n\nclass UMABackend(ABC):\n    \"\"\"Backend base class of the Universal Modular Accelerator Interface (UMA)\"\"\"\n\n    def __init__(self, merge_compiler_regions: bool = True) -> None:\n        self._target_attrs: Dict = {}\n        self._target_preprocessor: Callable[[str], Dict[str, Any]] = None\n        self._relay_to_relay = UMAPartitioner(self.target_name, merge_compiler_regions)\n        self._relay_to_tir = UMALower(self.target_name)\n        self._tir_to_runtime = UMACodegen(self.target_name)\n\n    @property\n    @abstractmethod\n    def target_name(self) -> str:\n        \"\"\"Name of the hardware target.\n\n        Returns\n        -------\n        out : str\n            The hardware target name.\n        \"\"\"\n        ...\n\n    # Target configuration\n    def _register_target_attr(\n        self,\n        name: str,\n        default: Optional[Union[str, int, bool]] = \"\",\n    ) -> None:\n        \"\"\"Register a target attribute name that can be used during target instantiation.\n        Parameters\n        ----------\n        name: str\n           The name of the target attribute.\n\n        default: Optional[Union[str, int, bool]]\n            A default value for the attribute.\n            If none is provided, the attribute will be treated as a string.\n\n        Example\n        -------\n        Here is an example of how two attribute options are registered.\n\n        .. code-block:: python\n\n            self._register_target_attr(\"attrA\", default=0)\n            self._register_target_attr(\"attrB\", default=False)\n        \"\"\"\n        self._target_attrs[name] = default\n\n    # Relay to Relay function registration\n    def _register_relay_pass(self, phase: PassPhase, relay_pass: tvm.transform.Pass) -> None:\n        \"\"\"Registers a relay pass at the given phase in the lowering process.\n\n        Parameters\n        ----------\n        phase: PassPhase\n           The phase at which the pass is registered.\n\n        relay_pass: tvm.transform.Pass\n            The relay pass to be registered.\n\n        Example\n        -------\n        Here is an example of how two relay passes are registered.\n        Passes of the same phase are executed in the order they are registered.\n\n        .. code-block:: python\n\n            self._register_relay_pass(PassPhase.PRE_PARTITIONING, MyPassA)\n            self._register_relay_pass(PassPhase.POST_PARTITIONING, MyPassB)\n\n        Where a relay pass can look like this:\n\n        .. code-block:: python\n\n            @tvm.ir.transform.module_pass(opt_level=0)\n            class MyPassA:\n                def transform_module(self, mod, ctx):\n                    # My pass functionality...\n                    return mod\n        \"\"\"\n        self._relay_to_relay._relay_passes.append((phase, relay_pass))\n\n    def _register_pattern(\n        self,\n        name: str,\n        pattern: tvm.relay.dataflow_pattern.DFPattern,\n        predicate: Optional[Callable] = None,\n    ) -> None:\n        \"\"\"Registers a dataflow pattern that is used to partition the relay graph.\n\n        Parameters\n        ----------\n        name: str\n           The name of the pattern\n\n        pattern: tvm.relay.dataflow_pattern.DFPattern\n            Relay DFPattern\n\n        predicate: Optional[Callable]\n            Optional predicate for Relay DFPattern\n        Example\n        -------\n        Here is an example of how two dataflow patterns are registered.\n        During partioning, patterns are searched in order of registration.\n\n        .. code-block:: python\n\n            self._register_pattern(\"conv1d\", conv1d_pattern)\n            self._register_pattern(\"conv2d\", conv2d_pattern)\n\n        Where a dataflow pattern can look like this:\n\n        .. code-block:: python\n\n            conv1d_pattern = is_op(\"nn.conv1d\")(wildcard(), wildcard())\n            optional_bias = lambda x: is_op(\"nn.bias_add\")(x, wildcard())\n            optional_relu = lambda x: is_op(\"nn.relu\")(x)\n            conv1d_pattern = conv1d_pattern.optional(optional_bias).optional(optional_relu)\n        \"\"\"\n        self._relay_to_relay.add_pattern(name, pattern, predicate)\n\n    # Relay to TIR function registration\n    def _register_operator_strategy(\n        self,\n        op: str,\n        strategy: Callable[\n            [tvm.ir.Attrs, tvm.ir.Array, tvm.ir.TensorType, tvm.target.Target],\n            tvm.relay.op.op.OpStrategy,\n        ],\n        plevel: Optional[int] = 11,\n    ) -> None:\n        \"\"\"Registers an operator strategy that is used to partition the relay graph.\n\n        Parameters\n        ----------\n        op: str\n           The name of the operator for which this strategy will be registered.\n\n        strategy: Callable[[tvm.ir.Attrs, tvm.ir.Array, tvm.ir.TensorType, tvm.target.Target],\n                            tvm.relay.op.op.OpStrategy]\n            The strategy function.\n\n        plevel: Optional[int] = 11\n            The priority level of the strategy. Higher plevel equals higher priorization.\n            The TVM default for topi strategies is 10 so by default new UMA strategies are\n            always used.\n\n        Example\n        -------\n        Here is an example of how two operator strategies are registered.\n\n        .. code-block:: python\n\n            self._register_operator_strategy(\"nn.conv1d\", custom_conv1d_strategy)\n            self._register_operator_strategy(\"nn.conv2d\", custom_conv2d_strategy)\n\n        Where a strategy function can look like this:\n\n        .. code-block:: python\n\n            @relay.op.strategy.override_native_generic_func(\"custom_conv1d_strategy\")\n            def custom_conv1d_strategy(attrs, inputs, out_type, target):\n                strategy = _op.OpStrategy()\n                strategy.add_implementation(\n                    wrap_compute_conv1d(custom_conv1d_compute),\n                    wrap_topi_schedule(custom_conv1d_schedule),\n                    name=\"custom_conv1d.generic\",\n                return strategy\n        \"\"\"\n        self._relay_to_tir._operator_strategies.append((op, strategy, plevel))\n\n    def _register_tir_pass(\n        self, phase: PassPhase, tir_pass: tvm.tir.transform.PrimFuncPass\n    ) -> None:\n        \"\"\"Registers a TIR pass at the given phase in the lowering process.\n\n        Parameters\n        ----------\n        phase: PassPhase\n           The phase at which the pass is registered.\n\n        tir_pass: tvm.tir.transform.PrimFuncPass\n            The TIR pass to be registered.\n        Example\n        -------\n        Here is an example of how two TIR passes are registered.\n        Passes of the same phase are executed in the order they are registered.\n\n        .. code-block:: python\n\n            self._register_tir_pass(PassPhase.TIR_PHASE_0, MyPassA)\n            self._register_tir_pass(PassPhase.TIR_PHASE_1, MyPassB)\n\n        Where a TIR pass can look like this:\n\n        .. code-block:: python\n\n            @tvm.tir.transform.prim_func_pass(opt_level=0)\n            class MyPassA:\n                def transform_function(self, func, mod, ctx):\n                    # My pass functionality...\n                    return func\n        \"\"\"\n        self._relay_to_tir._tir_passes.append((phase, tir_pass))\n\n    # TIR to runtime function registration\n    def _register_codegen(self, fmt: str = \"c\", **kwargs) -> None:\n        \"\"\"Registers a codegen which is used in place of the default C-codegen.\n\n        Parameters\n        ----------\n        fmt: str\n            The codegen format. For now, only C-codegen is supported by UMA.\n\n        **kwargs\n            Keyword arguments for the chosen codegen.\n\n        Example\n        -------\n        Here is an example of how the custom C-codegen is registered and configured.\n        Passes of the same phase are executed in the order they are registered.\n\n        .. code-block:: python\n\n            self._register_codegen(\n                fmt=\"c\", includes=gen_includes\n            )\n\n        The C-codegen currently provides one hook which allows the user to insert code through\n        the python API.\n            - `includes` hooks into the include stream and allows insertion of custom includes.\n\n\n        The code generation functions can look like this:\n\n        .. code-block:: python\n\n            def gen_includes() -> str:\n                includes = \"#include <my_custom_header.h>\\n\"\n                return includes\n        \"\"\"\n        self._tir_to_runtime._register_codegen(fmt, **kwargs)\n\n    # Backend functions\n    def register(self) -> None:\n        \"\"\"\n        Registering UMABackend:\n         registering target attributes, relay_to_relay, relay_to_tir and tir_to_runtime\n        \"\"\"\n        registration_func = tvm.get_global_func(\"relay.backend.contrib.uma.RegisterTarget\")\n\n        for name, attr in self._target_attrs:\n            if attr is None:\n                raise ValueError(\"Target attribute None is not supported.\")\n\n        if registration_func(self.target_name, self._target_attrs):\n            self._relay_to_relay.register()\n            self._relay_to_tir.register()\n            self._tir_to_runtime.register()\n\n    def partition(\n        self, mod: tvm.IRModule, params: Optional[Dict[str, tvm.runtime.NDArray]] = None\n    ) -> tvm.IRModule:\n        return self._relay_to_relay.partition(mod, params)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=len-as-condition,no-else-return,invalid-name\n\"\"\"Executor configuration\"\"\"\n\nimport tvm\nfrom tvm.runtime import Object\n\nfrom . import _backend\n\n\n@tvm._ffi.register_object\nclass Executor(Object):\n    \"\"\"Executor configuration\"\"\"\n\n    flag_registry_name = \"executor\"\n\n    def __init__(self, name, options=None) -> None:\n        if options is None:\n            options = {}\n        self.__init_handle_by_constructor__(_backend.CreateExecutor, name, options)\n        self._attrs = _backend.GetExecutorAttrs(self)\n\n    def __contains__(self, name):\n        return name in self._attrs\n\n    def __getitem__(self, name):\n        return self._attrs[name]\n\n    def __eq__(self, other):\n        return str(other) == str(self) and dict(other._attrs) == dict(self._attrs)\n\n    @staticmethod\n    def list_registered():\n        \"\"\"Returns a list of possible executors\"\"\"\n        return list(_backend.ListExecutors())\n\n    @staticmethod\n    def list_registered_options(executor):\n        \"\"\"Returns the dict of available option names and types\"\"\"\n        return dict(_backend.ListExecutorOptions(str(executor)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/executor_factory.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Executor factory modules.\"\"\"\nfrom abc import abstractmethod\nimport warnings\n\nfrom ..._ffi.base import string_types\nfrom ..._ffi.registry import get_global_func\nfrom ...runtime import ndarray\n\n\nclass ExecutorFactoryModule:\n    \"\"\"Common interface for executor factory modules\n    This class describes the common API of different\n    factory modules\n    \"\"\"\n\n    @abstractmethod\n    def get_executor_config(self):\n        \"\"\"Return the internal configuration the executor uses to execute the network\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_params(self):\n        \"\"\"Return the compiled parameters.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_lib(self):\n        \"\"\"Return the generated library\"\"\"\n        raise NotImplementedError\n\n    def __getitem__(self, item):\n        return self.module.__getitem__(item)\n\n    def __iter__(self):\n        warnings.warn(\n            \"legacy graph executor behavior of producing json / lib / params will be \"\n            \"removed in the next release.\"\n            \" Please see documents of tvm.contrib.graph_executor.GraphModule for the \"\n            \" new recommended usage.\",\n            DeprecationWarning,\n            2,\n        )\n        return self\n\n    def __next__(self):\n        if self.iter_cnt > 2:\n            raise StopIteration\n\n        objs = [self.get_executor_config(), self.lib, self.params]\n        obj = objs[self.iter_cnt]\n        self.iter_cnt += 1\n        return obj\n\n\nclass AOTExecutorFactoryModule(ExecutorFactoryModule):\n    \"\"\"AOT executor factory module.\n\n    Attributes\n    ----------\n    ir_mod : :py:class:`~tvm.IRModule`\n        The IR module to build.\n    lowered_ir_mods : dict[Target, IRModule]\n        The IR modules lowered per Target.\n    target : tvm.Target\n        The Target used to build this module.\n    executor : tvm.relay.backend.Executor\n        Internal representation of the Executor\n    runtime : tvm.relay.backend.Runtime\n        Internal representation of the Runtime\n    libmod : tvm.Module\n        The module of the corresponding function\n    libmod_name: str\n        The name of module\n    params : dict of str to NDArray\n        The parameters of module\n    function_metadata : Map of String to FunctionInfo\n        This holds a map function names to their information\n    devices : List[str]\n        List of devices used in the module\n    \"\"\"\n\n    def __init__(\n        self,\n        ir_mod,\n        lowered_ir_mods,\n        target,\n        executor,\n        runtime,\n        libmod,\n        libmod_name,\n        params,\n        function_metadata,\n        executor_codegen_metadata,\n        devices,\n    ):\n        fcreate = get_global_func(\"tvm.aot_executor_factory.create\")\n        args = []\n        for k, v in params.items():\n            args.append(k)\n            args.append(ndarray.array(v))\n\n        self.module = fcreate(libmod, libmod_name, *args)\n        self.ir_mod = ir_mod\n        self.lowered_ir_mods = lowered_ir_mods\n        self.target = target\n        self.executor = executor\n        self.runtime = runtime\n        self.lib = libmod\n        self.libmod_name = libmod_name\n        self.params = params\n        self.iter_cnt = 0\n        self.function_metadata = function_metadata\n        self.executor_codegen_metadata = executor_codegen_metadata\n        self.devices = devices\n\n    def get_devices(self):\n        return self.devices\n\n    def get_params(self):\n        return self.params\n\n    def get_executor_config(self):\n        return None\n\n    def get_lib(self):\n        return self.lib\n\n    def export_library(self, file_name, fcompile=None, addons=None, **kwargs):\n        return self.module.export_library(file_name, fcompile, addons, **kwargs)\n\n\nclass GraphExecutorFactoryModule(ExecutorFactoryModule):\n    \"\"\"Graph executor factory module.\n    This is a module of graph executor factory\n\n    Attributes\n    ----------\n    ir_mod : :py:class:`~tvm.IRModule`\n        The IR module to build.\n    target : tvm.Target\n        The Target used to build this module.\n    executor : tvm.relay.backend.Executor\n        Internal representation of the Executor\n    graph_json_str : the json graph to be deployed in json format output by graph compiler.\n        The graph can contain operator(tvm_op) that points to the name of\n        PackedFunc in the libmod.\n    libmod : tvm.Module\n        The module of the corresponding function\n    libmod_name: str\n        The name of module\n    params : dict of str to NDArray\n        The parameters of module\n    function_metadata : Map of String to FunctionInfo\n        This holds a map function names to their information\n    \"\"\"\n\n    def __init__(\n        self,\n        ir_mod,\n        target,\n        executor,\n        graph_json_str,\n        libmod,\n        libmod_name,\n        params,\n        function_metadata,\n    ):\n        assert isinstance(graph_json_str, string_types)\n        fcreate = get_global_func(\"tvm.graph_executor_factory.create\")\n        args = []\n        for k, v in params.items():\n            args.append(k)\n            args.append(ndarray.array(v))\n\n        self.ir_mod = ir_mod\n        self.target = target\n        self.executor = executor\n        self.module = fcreate(graph_json_str, libmod, libmod_name, *args)\n        self.graph_json = graph_json_str\n        self.lib = libmod\n        self.libmod_name = libmod_name\n        self.params = params\n        self.iter_cnt = 0\n        self.function_metadata = function_metadata\n\n    def export_library(self, file_name, fcompile=None, addons=None, **kwargs):\n        return self.module.export_library(file_name, fcompile, addons, **kwargs)\n\n    def get_devices(self):\n        return []\n\n    def get_params(self):\n        return self.params\n\n    def get_graph_json(self):\n        return self.graph_json\n\n    def get_executor_config(self):\n        return self.graph_json\n\n    def get_lib(self):\n        return self.lib\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/graph_executor_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nA compiler from a Relay expression to TVM's graph executor.\n\nThe compiler is built from a few pieces.\n\nFirst we define a compiler from a single Relay expression to the\ngraph language. We require the expression to be a function.\nThe function's parameters correspond to the placeholder/inputs\nand model parameters found in the computation graph representation.\nThe body of the function represents the computation graph.\n\nThe compiler's output is a program in the graph language, which is composed of\nNode, NodeRef, InputNode, OpNode. This \"little language\" represents programs in\nTVM's graph format.\n\nTo connect to the graph executor, we use a printer that converts our graph format\ninto TVM's JSON format. The resulting string can be loaded by\ncontrib.graph_executor or any other TVM runtime compatible systems.\n\"\"\"\nfrom tvm.runtime.ndarray import empty\nfrom tvm.relay import _build_module\nfrom tvm.target import Target\nfrom .utils import mangle_module_name\n\n\nclass GraphExecutorCodegen(object):\n    \"\"\"The compiler from Relay to the TVM runtime system.\"\"\"\n\n    def __init__(self, mod, target):\n        self._mod = _build_module._GraphExecutorCodegen()\n        self._init = self._mod[\"init\"]\n        self._codegen = self._mod[\"codegen\"]\n        self._get_graph_json = self._mod[\"get_graph_json\"]\n        self._list_params_name = self._mod[\"list_params_name\"]\n        self._get_param_by_name = self._mod[\"get_param_by_name\"]\n        self._get_irmodule = self._mod[\"get_irmodule\"]\n        self._setup(mod, target)\n\n    def _setup(self, mod, target):\n        raw_targets = Target.canon_multi_target_and_host(target)\n        self._init(mod, raw_targets)\n\n    def codegen(self, ir_module, func):\n        \"\"\"Compile a single function into a graph.\n\n        Parameters\n        ----------\n        ir_module: tvm.ir.Module\n            The module to compile\n        func: tvm.relay.Expr\n            The function to compile.\n\n        Returns\n        -------\n        graph_json : str\n            The graph json that can be consumed by runtime.\n        mod : IRModule or Dict[Target, IRModule]\n            The lowered functions.\n        params : Dict[str, tvm.nd.NDArray]\n            Additional constant parameters.\n        \"\"\"\n        default_mod_name = mangle_module_name(\"default\")\n        self._codegen(ir_module, func, default_mod_name)\n        graph_json = self._get_graph_json()\n        lowered_func = self._get_irmodule()\n        param_names = self._list_params_name()\n        params = {}\n        for key in param_names:\n            arr = self._get_param_by_name(key)\n            param = empty(arr.shape, dtype=arr.dtype, device=arr.device)\n            arr.copyto(param)\n            params[key] = param\n        return graph_json, lowered_func, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/interpreter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return\n\"\"\"The Python interface to the Relay reference interpreter.\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm.runtime import container, Object\n\nfrom . import _backend\nfrom .. import _make, analysis\nfrom ... import nd\nfrom ..expr import Tuple, RefCreate, Call, Constant, GlobalVar, const\nfrom ..function import Function\nfrom ..scope_builder import ScopeBuilder\n\n\n@tvm._ffi.register_object(\"relay.ConstructorValue\")\nclass ConstructorValue(Object):\n    def __init__(self, tag, fields, constructor):\n        self.__init_handle_by_constructor__(_make.ConstructorValue, tag, fields, constructor)\n\n\n@tvm._ffi.register_object(\"relay.RefValue\")\nclass RefValue(Object):\n    def __init__(self, value):\n        self.__init_handle_by_constructor__(_make.RefValue, value)\n\n\ndef _arg_to_ast(mod, arg):\n    if isinstance(arg, nd.NDArray):\n        return Constant(arg.copyto(nd.cpu(0)))\n    elif isinstance(arg, container.ADT):\n        return Tuple([_arg_to_ast(mod, field) for field in arg])\n    elif isinstance(arg, tuple):\n        return Tuple([_arg_to_ast(mod, field) for field in arg])\n    elif isinstance(arg, RefValue):\n        return RefCreate(_arg_to_ast(mod, arg.value))\n    elif isinstance(arg, ConstructorValue):\n        return Call(mod.get_constructor(arg.tag), [_arg_to_ast(mod, field) for field in arg.fields])\n    elif isinstance(arg, np.ndarray):\n        return Constant(nd.array(arg))\n    elif isinstance(arg, Constant):\n        return arg\n    else:\n        return const(arg)\n\n\nclass Executor(object):\n    \"\"\"An abstract interface for executing Relay programs.\"\"\"\n\n    def _convert_args(self, expr, args, kwargs):\n        \"\"\"\n        Convert the combination of arguments and keyword arguments\n        into a sequence of arguments that may be passed to\n        a Relay evaluator.\n\n        We first provide all positional arguments, and then attempt\n        to fill in the remaining arguments using the keyword arguments. We\n        map the keyword arguments to the corresponding parameters, if there\n        is an ambiguity between positional and keyword arguments this\n        procedure will raise an error.\n\n        Parameters\n        ----------\n        expr: relay.Expr\n            The expression to evaluate\n\n        args: List[tvm.nd.NDArray]\n            The arguments to pass to the evaluator.\n\n        kwargs: Dict[str, tvm.NDArrray]\n            The keyword arguments to pass to the evaluator.\n\n        Returns:\n            args: List[tvm.nd.NDArray]\n                The new arguments with all keyword arguments placed in the correct slot.\n        \"\"\"\n        assert expr is not None\n\n        if not kwargs:\n            return args\n\n        if kwargs and not isinstance(expr, Function):\n            raise Exception(\n                \"can only supply keyword parameters for a \" \"relay.Function, found {0}\".format(expr)\n            )\n\n        params = expr.params\n        param_names = [p.name_hint for p in params]\n        num_of_args = len(args)\n\n        cargs = list(args)[:]\n        for i, name in enumerate(param_names):\n            if i < num_of_args:\n                if kwargs.get(name):\n                    raise Exception(\n                        \"duplicate argument supplied in \"\n                        \"both positional args (at position: {0}), \"\n                        \"and keyword argument (with name: {1})\".format(i, name)\n                    )\n            else:\n                cargs.append(kwargs[name])\n\n        if len(cargs) != len(params):\n            raise Exception(\n                \"insufficient arguments, expected \"\n                \"{0}, provided {1}\".format(len(cargs), len(params))\n            )\n\n        return tuple(cargs)\n\n    def _make_executor(self, expr=None):\n        \"\"\"\n        Construct a Python function that implements the evaluation\n        of expression.\n\n        Parameters\n        ----------\n        expr: Optional[relay.Expr]\n            The Relay expression to execute.\n\n        Returns\n        -------\n        executor: function,\n            A Python function which implements the behavior of `expr`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def evaluate(self, expr=None, binds=None):\n        \"\"\"\n        Evaluate a Relay expression on the executor.\n\n        Parameters\n        ----------\n        expr: Optional[tvm.relay.Expr]\n            The expression to evaluate.\n\n        binds: Optional[Map[tvm.relay.Var, tvm.relay.Expr]]\n            Additional binding of free variable.\n\n        Returns\n        -------\n        val : Union[function, Object]\n            The evaluation result.\n        \"\"\"\n        if binds:\n            scope_builder = ScopeBuilder()\n            for key, value in binds.items():\n                scope_builder.let(key, _arg_to_ast(self.mod, value))\n            scope_builder.ret(expr)\n            expr = scope_builder.get()\n\n        if not expr:\n            return self._make_executor()\n\n        if isinstance(expr, Function):\n            assert not analysis.free_vars(expr)\n\n        if isinstance(expr, (Function, GlobalVar)):\n            return self._make_executor(expr)\n\n        # normal expression evaluated by running a function.\n        # TODO(mbs): This should really be type rather than syntax driven.\n        func = Function([], expr)\n        return self._make_executor(func)()\n\n\nclass Interpreter(Executor):\n    \"\"\"\n    Simple interpreter interface.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The module to support the execution.\n\n    device : Device\n        The runtime device to run the code on.\n\n    target : tvm.Target\n        The target option to build the function. Only homogeneous execution is supported.\n\n    CAUTION: Despite the API the module is prepared upon each call to evaluate\n    rather than once in create_executor.\n    That is:\n    .. code-block:: python\n\n        executor = relay.create_executor(kind=\"debug\", mod=module)\n        a = executor.evaluate(expr)(args1)\n        b = executor.evaluate(expr)(args2)\n\n    will prepare all the bindings in module twice. For efficiency, try to hoist\n    calls to evaluate as high as possible, preferably immediately after create_executor:\n    .. code-block:: python\n\n        func = relay.create_executor(kind=\"debug\", mod=module).evaluate(expr)\n        a = func(args1)\n        b = func(args2)\n    \"\"\"\n\n    def __init__(self, mod, device, target):\n        self.mod = mod\n        self.device = device\n        self.target = target\n\n    def _make_executor(self, expr=None):\n        if expr is None or isinstance(expr, GlobalVar):\n            assert self.mod is not None\n\n        if expr is None:\n            # A missing expr denotes 'main' in the given module.\n            expr = self.mod.get_global_var(\"main\")\n\n        # Evaluate expr to a packed function we can efficiently re-apply\n        # to Relay arguments.\n        func = _backend.EvalFunction(self.mod, expr, self.device, self.target)\n\n        def _apply_args(*args, **kwargs):\n            if isinstance(expr, GlobalVar):\n                # When expanding args, look inside the actual global definition so kwargs\n                # can be matched.\n                args = self._convert_args(self.mod[expr.name_hint], args, kwargs)\n            else:\n                args = self._convert_args(expr, args, kwargs)\n            # Reflect python arguments up into Relay.\n            relay_args = []\n            for arg in args:\n                relay_args.append(_arg_to_ast(self.mod, arg))\n            # Apply func to Relay args\n            return func(relay_args)\n\n        return _apply_args\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/name_transforms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nName transformation functions for use in code generation\n\"\"\"\n\nfrom typing import List, Union\n\nfrom tvm import TVMError\nfrom . import _backend\n\n\ndef to_c_function_style(original_name: str):\n    \"\"\"Transform a name to the C function style assuming it is\n    appropriately constructed using the prefixing functions\n\n    Parameters\n    ----------\n    original_name : str\n        Original name to transform\n    \"\"\"\n    return _backend.ToCFunctionStyle(original_name)\n\n\ndef to_c_variable_style(original_name: str):\n    \"\"\"Transform a name to the C variable style assuming it is\n    appropriately constructed using the prefixing functions\n\n    Parameters\n    ----------\n    original_name : str\n        Original name to transform\n    \"\"\"\n    return _backend.ToCVariableStyle(original_name)\n\n\ndef to_c_constant_style(original_name: str):\n    \"\"\"Transform a name to the C constant style assuming it is\n    appropriately constructed using the prefixing functions\n\n    Parameters\n    ----------\n    original_name : str\n        Original name to transform\n    \"\"\"\n    return _backend.ToCConstantStyle(original_name)\n\n\ndef _preprocess_names(names: Union[List[str], str]):\n    \"\"\"Preprocesses name strings into format for C++ functions\n\n    Parameters\n    ----------\n    names : Union[List[str], str]\n        List of names to combine to form a combined name or the name itself\n    \"\"\"\n    if isinstance(names, str):\n        if names == \"\":\n            raise TVMError(\"Name is empty\")\n        return [names]\n    return names\n\n\ndef prefix_name(names: Union[List[str], str]):\n    \"\"\"Apply TVM-specific prefix to a function name\n\n    Parameters\n    ----------\n    names : Union[List[str], str]\n        List of names to combine to form a combined name or the name itself\n    \"\"\"\n\n    return _backend.PrefixName(_preprocess_names(names))\n\n\ndef prefix_generated_name(names: Union[List[str], str]):\n    \"\"\"Apply generated TVM-specific prefix to a function name\n\n    Parameters\n    ----------\n    names : Union[List[str], str]\n        List of names to combine to form a combined name or the name itself\n    \"\"\"\n\n    return _backend.PrefixGeneratedName(_preprocess_names(names))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=len-as-condition,no-else-return,invalid-name\n\"\"\"Runtime configuration\"\"\"\n\nimport tvm\nfrom tvm.runtime import Object\n\nfrom . import _backend\n\n\n@tvm._ffi.register_object\nclass Runtime(Object):\n    \"\"\"Runtime configuration\"\"\"\n\n    flag_registry_name = \"runtime\"\n\n    def __init__(self, name, options=None) -> None:\n        if options is None:\n            options = {}\n        self.__init_handle_by_constructor__(_backend.CreateRuntime, name, options)\n        self._attrs = _backend.GetRuntimeAttrs(self)\n\n    def __contains__(self, name):\n        return name in self._attrs\n\n    def __getitem__(self, name):\n        self._attrs = _backend.GetRuntimeAttrs(self)\n        return self._attrs[name]\n\n    def __eq__(self, other):\n        return str(other) == str(self) and dict(other._attrs) == dict(self._attrs)\n\n    @staticmethod\n    def list_registered():\n        \"\"\"Returns a list of possible runtimes\"\"\"\n        return list(_backend.ListRuntimes())\n\n    @staticmethod\n    def list_registered_options(runtime):\n        \"\"\"Returns the dict of available option names and types\"\"\"\n        return dict(_backend.ListRuntimeOptions(str(runtime)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/te_compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=len-as-condition,no-else-return,invalid-name\n\"\"\"TE compiler engine (replacing legacy compile_engine).\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\n\nimport numpy as np\nimport tvm\nfrom tvm import autotvm, te\nfrom tvm.auto_scheduler import is_auto_scheduler_enabled\nfrom tvm.meta_schedule import is_meta_schedule_enabled\nfrom tvm.runtime import Object\nfrom tvm.support import libinfo\nfrom tvm.target import Target\n\nfrom .. import function as _function\nfrom .. import ty as _ty\nfrom ..backend.utils import mangle_module_name\nfrom . import _backend\n\nlogger = logging.getLogger(\"te_compiler\")\nautotvm_logger = logging.getLogger(\"autotvm\")\n\n_first_warning = True\n\n\n@tvm._ffi.register_object(\"relay.LoweredOutput\")\nclass LoweredOutput(Object):\n    \"\"\"Lowered output\"\"\"\n\n    def __init__(self, outputs, implement):\n        self.__init_handle_by_constructor__(_backend._make_LoweredOutput, outputs, implement)\n\n\n@tvm._ffi.register_object(\"relay.CCacheKey\")\nclass CCacheKey(Object):\n    \"\"\"Key in the TE Compiler.\n\n    Parameters\n    ----------\n    source_func : tvm.relay.Function\n        The source function.\n\n    target : tvm.Target\n        The target we want to run the function on.\n    \"\"\"\n\n    def __init__(self, source_func, target):\n        self.__init_handle_by_constructor__(_backend._make_CCacheKey, source_func, target)\n\n\n@tvm._ffi.register_object(\"relay.CCacheValue\")\nclass CCacheValue(Object):\n    \"\"\"Value in the TE Compiler, including usage statistics.\"\"\"\n\n\ndef _get_cache_key(source_func, target):\n    if isinstance(source_func, _function.Function):\n        if isinstance(target, str):\n            target = Target(target)\n            if not target:\n                raise ValueError(\"Need target when source_func is a Function\")\n        return CCacheKey(source_func, target)\n    if not isinstance(source_func, CCacheKey):\n        raise TypeError(\"Expect source_func to be CCacheKey\")\n    return source_func\n\n\ndef get_valid_implementations(op, attrs, inputs, out_type, target):\n    \"\"\"Get all valid implementations from the op strategy.\n\n    Note that this function doesn't support op with symbolic input shapes.\n\n    Parameters\n    ----------\n    op : tvm.ir.Op\n        Relay operator.\n\n    attrs : object\n        The op attribute.\n\n    inputs : List[tvm.te.Tensor]\n        Input tensors to the op.\n\n    out_type : relay.Type\n        The output type.\n\n    target : tvm.target.Target\n        The target to compile the op.\n\n    Returns\n    -------\n    ret : List[relay.op.OpImplementation]\n        The list of all valid op implementations.\n    \"\"\"\n    fstrategy = op.get_attr(\"FTVMStrategy\")\n    assert fstrategy is not None, (\n        \"%s doesn't have an FTVMStrategy registered. You can register \"\n        \"one in python with `tvm.relay.op.register_strategy`.\" % op.name\n    )\n    with target:\n        strategy = fstrategy(attrs, inputs, out_type, target)\n    analyzer = tvm.arith.Analyzer()\n    ret = []\n    for spec in strategy.specializations:\n        if spec.condition:\n            # check if all the clauses in the specialized condition are true\n            flag = True\n            for clause in spec.condition.clauses:\n                clause = analyzer.canonical_simplify(clause)\n                if isinstance(clause, tvm.tir.IntImm) and clause.value:\n                    continue\n                flag = False\n                break\n            if flag:\n                for impl in spec.implementations:\n                    ret.append(impl)\n        else:\n            for impl in spec.implementations:\n                ret.append(impl)\n    return ret\n\n\ndef select_implementation(op, attrs, inputs, out_type, target, use_autotvm=True):\n    \"\"\"Select the best implementation from the op strategy.\n\n    If use_autotvm is True, it'll first try to find the best implementation\n    based on AutoTVM profile results. If no AutoTVM profile result is found,\n    it'll choose the implementation with highest plevel.\n\n    If use_autotvm is False, it'll directly choose the implementation with\n    highest plevel.\n\n    Note that this function doesn't support op with symbolic input shapes.\n\n    Parameters\n    ----------\n    op : tvm.ir.Op\n        Relay operator.\n\n    attrs : object\n        The op attribute.\n\n    inputs : List[tvm.te.Tensor]\n        Input tensors to the op.\n\n    out_type : relay.Type\n        The output type.\n\n    target : tvm.target.Target\n        The target to compile the op.\n\n    use_autotvm : bool\n        Whether query AutoTVM to pick the best.\n\n    Returns\n    -------\n    ret : tuple(relay.op.OpImplementation, List[tvm.te.Tensor])\n        The best op implementation and the corresponding output tensors.\n    \"\"\"\n    all_impls = get_valid_implementations(op, attrs, inputs, out_type, target)\n    if len(all_impls) == 0:\n        raise RuntimeError(f\"No valid {op} implementations for {target}\")\n    best_plevel_impl = max(all_impls, key=lambda x: x.plevel)\n\n    # Disable autotvm if auto_scheduler is enabled.\n    # (i.e., always return the implementation with the highest priority for auto-scheduler).\n    if is_auto_scheduler_enabled() or is_meta_schedule_enabled():\n        use_autotvm = False\n\n    # If not use autotvm, always return the implementation with the highest priority\n    if not use_autotvm:\n        logger.info(\n            \"Using %s for %s based on highest priority (%d)\",\n            best_plevel_impl.name,\n            op.name,\n            best_plevel_impl.plevel,\n        )\n        outs = best_plevel_impl.compute(attrs, inputs, out_type)\n        return best_plevel_impl, outs\n\n    # Otherwise, try autotvm templates\n    outputs = {}\n    workloads = {}\n    best_autotvm_impl = None\n    best_cfg = None\n    dispatch_ctx = autotvm.task.DispatchContext.current\n    old_silent = autotvm.GLOBAL_SCOPE.silent\n    autotvm.GLOBAL_SCOPE.silent = True\n    for impl in all_impls:\n        outs = impl.compute(attrs, inputs, out_type)\n        outputs[impl] = outs\n        workload = autotvm.task.get_workload(outs)\n        workloads[impl] = workload\n        if workload is None:\n            # Not an AutoTVM tunable implementation\n            continue\n        cfg = dispatch_ctx.query(target, workload)\n        if cfg.is_fallback:\n            # Skip fallback config\n            continue\n        logger.info(\"Implementation %s for %s has cost %.2e\", impl.name, op.name, cfg.cost)\n        if best_cfg is None or best_cfg.cost > cfg.cost:\n            best_autotvm_impl = impl\n            best_cfg = cfg\n    autotvm.GLOBAL_SCOPE.silent = old_silent\n\n    if best_autotvm_impl:\n        # The best autotvm implementation definitely doesn't use fallback config\n        logger.info(\n            \"Using %s for %s based on lowest cost (%.2e)\",\n            best_autotvm_impl.name,\n            op.name,\n            best_cfg.cost,\n        )\n        return best_autotvm_impl, outputs[best_autotvm_impl]\n\n    # Use the implementation with highest plevel\n    if workloads[best_plevel_impl] is not None:\n        msg = (\n            \"Cannot find tuning records for:\\n    target=%s\\n    key=%s\\n\"\n            \"TVM will apply a default schedule which may negatively impact performance.\"\n            % (target, workloads[best_plevel_impl])\n        )\n        if (\n            not autotvm.env.GLOBAL_SCOPE.silent\n            and msg not in autotvm.task.DispatchContext.warning_messages\n        ):\n            autotvm.task.DispatchContext.warning_messages.add(msg)\n            global _first_warning\n            if _first_warning:\n                _first_warning = False\n                info_msg = (\n                    \"One or more operators have not been tuned. Please tune your model \"\n                    \"for better performance. Use DEBUG logging level to see more details.\"\n                )\n                autotvm_logger.warning(info_msg)\n            autotvm_logger.debug(msg)\n\n    logger.info(\n        \"Using %s for %s based on highest priority (%s)\",\n        best_plevel_impl.name,\n        op.name,\n        best_plevel_impl.plevel,\n    )\n    return best_plevel_impl, outputs[best_plevel_impl]\n\n\ndef get_shape(shape):\n    \"\"\"Convert the shape to correct dtype and vars.\"\"\"\n    ret = []\n    for dim in shape:\n        if isinstance(dim, tvm.tir.IntImm):\n            if libinfo()[\"INDEX_DEFAULT_I64\"] == \"ON\":\n                ret.append(dim)\n            else:\n                val = int(dim)\n                assert val <= np.iinfo(np.int32).max\n                ret.append(tvm.tir.IntImm(\"int32\", val))\n        elif isinstance(dim, tvm.tir.Any):\n            ret.append(te.size_var(\"any_dim\", \"int32\"))\n        else:\n            ret.append(dim)\n    return ret\n\n\n@tvm._ffi.register_func(\"relay.backend.lower_call\")\ndef lower_call(call, inputs, target, otype=None):\n    \"\"\"Lower the call expression to op implementation and tensor outputs.\"\"\"\n    assert isinstance(call.op, tvm.ir.Op)\n    op = call.op\n\n    if otype is not None:\n        ret_type = otype\n    else:\n        # Prepare the call_node->checked_type(). For the call node inputs, we ensure that\n        # the shape is Int32. Following code ensures the same for the output as well.\n        # TODO(@icemelon9): Support recursive tuple\n        ret_type = call.checked_type\n        if isinstance(ret_type, _ty.TensorType):\n            ret_type = _ty.TensorType(get_shape(ret_type.shape), ret_type.dtype)\n        elif isinstance(ret_type, _ty.TupleType):\n            new_fields = []\n            for field in ret_type.fields:\n                if isinstance(field, _ty.TensorType):\n                    new_fields.append(_ty.TensorType(get_shape(field.shape), field.dtype))\n                else:\n                    new_fields.append(field)\n            ret_type = _ty.TupleType(new_fields)\n\n    is_dyn = _ty.is_dynamic(call.checked_type)\n    for arg in call.args:\n        is_dyn = is_dyn or _ty.is_dynamic(arg.checked_type)\n\n    # check if in the AutoTVM tracing mode, and disable if op is not in wanted list\n    env = autotvm.task.TaskExtractEnv.current\n    reenable_tracing = False\n    if env is not None and env.tracing:\n        if env.wanted_relay_ops is not None and op not in env.wanted_relay_ops:\n            env.tracing = False\n            reenable_tracing = True\n\n    if not is_dyn:\n        best_impl, outputs = select_implementation(op, call.attrs, inputs, ret_type, target)\n    else:\n        # TODO(@icemelon9): Allow tvm to generate multiple kernels for dynamic shapes.\n        best_impl, outputs = select_implementation(\n            op, call.attrs, inputs, ret_type, target, use_autotvm=False\n        )\n\n    # re-enable AutoTVM tracing\n    if reenable_tracing:\n        env.tracing = True\n    return LoweredOutput(outputs, best_impl)\n\n\n@tvm._ffi.register_object(\"relay.TECompiler\")\nclass TECompiler(Object):\n    \"\"\"TECompiler to get lowered code.\"\"\"\n\n    def __init__(self):\n        raise RuntimeError(\"Cannot construct a TECompiler\")\n\n    def lower(self, source_func, target=None, mod_name=\"default\"):\n        \"\"\"Lower a source_func to a CachedFunc.\n\n        Parameters\n        ----------\n        source_func : Union[tvm.relay.Function, CCacheKey]\n            The source relay function.\n\n        target : tvm.Target\n            The target platform.\n\n        Returns\n        -------\n        cached_func: CachedFunc\n            The result of lowering.\n        \"\"\"\n        # pylint: disable=broad-except, import-outside-toplevel\n        try:\n            mod_name = mangle_module_name(mod_name)\n            key = _get_cache_key(source_func, target)\n            return _backend._TECompilerLower(self, key, mod_name)\n        except Exception:\n            import traceback\n\n            msg = traceback.format_exc()\n            msg += \"Error during compile func\\n\"\n            msg += \"--------------------------\\n\"\n            msg += source_func.astext(show_meta_data=False)\n            msg += \"--------------------------\\n\"\n            raise RuntimeError(msg)\n\n    def jit(self, source_func, target=None):\n        \"\"\"JIT a source_func to a tvm.runtime.PackedFunc.\n\n        Parameters\n        ----------\n        source_func : Union[tvm.relay.Function, CCacheKey]\n            The source relay function.\n\n        target : tvm.Target\n            The target platform.\n\n        Returns\n        -------\n        jited_func: tvm.runtime.PackedFunc\n            The result of jited function.\n        \"\"\"\n        key = _get_cache_key(source_func, target)\n        return _backend._TECompilerJIT(self, key)\n\n    def clear(self):\n        \"\"\"clear the existing cached functions\"\"\"\n        _backend._TECompilerClear(self)\n\n    def items(self):\n        \"\"\"List items in the cache.\n        Returns\n        -------\n        item_list : List[Tuple[CCacheKey, CCacheValue]]\n            The list of items.\n        \"\"\"\n        res = _backend._TECompilerListItems(self)\n        assert len(res) % 2 == 0\n        return [(res[2 * i], res[2 * i + 1]) for i in range(len(res) // 2)]\n\n\ndef get():\n    \"\"\"Get the global TE Compiler.\n\n    Returns\n    -------\n    engine : tvm.relay.backend.TECompiler\n        The TE Compiler.\n    \"\"\"\n    return _backend._TECompilerGlobal()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utility backend functions.\"\"\"\nfrom enum import Enum\n\n\nclass CallType(Enum):\n    Packed = 0\n    CPacked = 1\n    Unpacked = 2\n\n\ndef _is_valid_modname(mod_name):\n    \"\"\"Determine if mod_name is a valid string to use inside function names\"\"\"\n    if mod_name:\n        try:\n            mod_name.encode(\"ascii\")\n            return True\n        except UnicodeEncodeError:\n            return False\n\n    return True\n\n\ndef mangle_module_name(mod_name):\n    if not _is_valid_modname(mod_name):\n        raise ValueError(mod_name + \" contains invalid characters\")\n    if mod_name:\n        return \"tvmgen_\" + mod_name\n    return \"tvmgen\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/backend/vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name, redefined-builtin\n\"\"\"\nThe Relay Virtual Machine.\n\nImplements a Python interface to compiling and executing on the Relay VM.\n\"\"\"\nimport numpy as np\n\nimport tvm.runtime.ndarray as _nd\nimport tvm.runtime.vm as vm_rt\nfrom tvm import autotvm\nfrom tvm.relay import expr as _expr\nfrom tvm.relay.backend.interpreter import Executor\nfrom tvm.target import Target\nfrom . import _vm\n\n\ndef compile(mod, target=None, target_host=None, params=None):\n    \"\"\"Compile the module to VM executable. A helper function for VMCompiler.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The Relay module to build.\n\n    target : any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n\n    target_host : None, or any target-like object, see Target.canon_target\n        Host compilation target, if target is device.\n        When TVM compiles device specific program such as CUDA,\n        we also need host(CPU) side code to interact with the driver\n        to setup the dimensions and parameters correctly.\n        target_host is used to specify the host side codegen target.\n        By default, llvm is used if it is enabled,\n        otherwise a stackvm intepreter is used.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    Returns\n    -------\n    exec : tvm.runtime.vm.Executable\n        The VM executable that contains both library code and bytecode.\n    \"\"\"\n    compiler = VMCompiler()\n    if params:\n        compiler.set_params(params)\n    compiler.lower(mod, target, target_host)\n    compiler.codegen()\n    return compiler.get_exec()\n\n\nclass VMCompiler(object):\n    \"\"\"Compiler that compiles Relay module to VM executable.\"\"\"\n\n    def __init__(self):\n        self.mod = _vm._VMCompiler()\n        self._lower = self.mod[\"lower\"]\n        self._codegen = self.mod[\"codegen\"]\n        self._get_exec = self.mod[\"get_executable\"]\n        self._set_params_func = self.mod[\"set_params\"]\n        self._get_params_func = self.mod[\"get_params\"]\n        self._optimize = self.mod[\"optimize\"]\n\n    def set_params(self, params):\n        \"\"\"Set constant parameters for the model.\n\n        Parameters\n        ----------\n        params : dict of str to NDArray\n            Input parameters to the graph that do not change\n            during inference time. Used for constant folding.\n        \"\"\"\n        inputs = {}\n        for name, param in params.items():\n            if isinstance(param, np.ndarray):\n                param = _nd.array(param)\n            inputs[name] = _expr.const(param)\n        self._set_params_func(inputs)\n\n    def get_params(self):\n        \"\"\"Return the updated weights.\"\"\"\n        params = self._get_params_func()\n        ret = {}\n        for key, value in params.items():\n            ret[key] = value.data\n        return ret\n\n    def lower(self, mod, target=None, target_host=None):\n        \"\"\"Lower the module to VM bytecode.\n\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            The Relay module to build.\n\n        target : any multi-target like object, see Target.canon_multi_target\n            For homogeneous compilation, the unique build target.\n            For heterogeneous compilation, a dictionary or list of possible build targets.\n\n        target_host : any target-like object, see Target.canon_target\n            Host compilation target, if target is device.\n        \"\"\"\n        raw_targets = Target.canon_multi_target_and_host(target, target_host)\n        tophub_context = self._tophub_context(raw_targets)\n        with tophub_context:\n            self._lower(mod, raw_targets)\n\n    def codegen(self):\n        \"\"\"Generate the kernel library.\"\"\"\n        self._codegen()\n\n    def optimize(self, mod, target=None, target_host=None, params=None):\n        \"\"\"Helper method that optimizes a Relay module via VM.\n\n        Parameters\n        ----------\n        mod : tvm.IRModule\n\n        target : any multi-target like object, see Target.canon_multi_target\n            For homogeneous compilation, the unique build target.\n            For heterogeneous compilation, a dictionary or list of possible build targets.\n\n        target_host : any target-like object, see Target.canon_target\n            Host compilation target, if target is device.\n\n        params : dict of str to NDArray\n            Input parameters to the graph that do not change\n            during inference time. Used for constant folding.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The optimized relay module.\n\n        params : dict\n            The parameters of the final module.\n        \"\"\"\n        raw_targets = Target.canon_multi_target_and_host(target, target_host)\n        if params:\n            self.set_params(params)\n        return self._optimize(mod, raw_targets), self.get_params()\n\n    def get_exec(self):\n        \"\"\"Get the VM executable.\n\n        Returns\n        -------\n        exec : tvm.runtime.vm.Executable\n            The VM executable that contains both library code and bytecode.\n        \"\"\"\n        return vm_rt.Executable(self._get_exec())\n\n    def _tophub_context(self, raw_targets):\n        \"\"\"Get the autotvm context.\"\"\"\n        # If current dispatch context is fallback context (the default root context),\n        # then load pre-tuned parameters from TopHub\n        if isinstance(autotvm.DispatchContext.current, autotvm.FallbackContext):\n            tophub_context = autotvm.tophub.context(raw_targets)\n        else:\n            tophub_context = autotvm.utils.EmptyContext()\n        return tophub_context\n\n\nclass VMExecutor(Executor):\n    \"\"\"\n    An implementation of the executor interface for\n    the Relay VM.\n\n    Useful interface for experimentation and debugging\n    the VM can also be used directly from the API.\n    supported by `tvm.runtime.vm`.\n\n    Parameters\n    ----------\n    mod : :py:class:`~tvm.IRModule`\n        The module to support the execution.\n\n    device : :py:class:`~tvm.runtime.Device`\n        The runtime device to run the code on.\n\n    target : any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n    \"\"\"\n\n    def __init__(self, mod, device, target):\n        if mod is None:\n            raise RuntimeError(\"Must provide module to get VM executor.\")\n        self.mod = mod\n        self.device = device\n        self.target = target\n        self.executable = None\n        self.vm = None\n\n    def _make_executor(self, expr=None):\n        if expr:\n            self.mod[\"main\"] = expr\n\n        self.executable = compile(self.mod, self.target)\n        self.vm = vm_rt.VirtualMachine(self.executable, self.device)\n\n        def _vm_wrapper(*args, **kwargs):\n            args = self._convert_args(self.mod[\"main\"], args, kwargs)\n            return self.vm.run(*args)\n\n        return _vm_wrapper\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, unused-import\n\"\"\"The base node types for the Relay language.\"\"\"\nimport os\nimport tvm._ffi\n\nfrom tvm.runtime import Object\nfrom tvm.ir import SourceName, Span, Node as RelayNode\n\n\n__STD_PATH__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"std\")\n\n\n@tvm._ffi.register_func(\"tvm.relay.std_path\")\ndef _std_path():\n    return __STD_PATH__\n\n\n@tvm._ffi.register_object(\"relay.Id\")\nclass Id(Object):\n    \"\"\"Unique identifier(name) used in Var.\n    Guaranteed to be stable across all passes.\n    \"\"\"\n\n    def __init__(self):\n        raise RuntimeError(\"Cannot directly construct Id\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nConstruct the necessary state for the TVM graph executor\nfrom a Relay expression.\n\"\"\"\nimport warnings\n\nimport numpy as np\nfrom tvm.ir import IRModule\nfrom tvm.target import Target\n\nfrom .. import autotvm\nfrom .. import nd as _nd\nfrom .. import register_func\nfrom ..contrib import graph_executor as _graph_executor\nfrom ..contrib import utils as contrib_utils\nfrom ..runtime import load_module\nfrom ..runtime.executor import aot_executor as _aot_executor\nfrom ..target import Target\nfrom . import _build_module\nfrom . import expr as _expr\nfrom . import function as _function\nfrom . import ty as _ty\nfrom .backend import Executor, Runtime\nfrom .backend import executor_factory as _executor_factory\nfrom .backend import interpreter as _interpreter\nfrom .backend.utils import mangle_module_name\nfrom .backend.vm import VMExecutor\nfrom .transform import InferType\n\n\ndef _convert_param_map(params):\n    inputs = {}\n    for name, param in params.items():\n        if isinstance(param, np.ndarray):\n            param = _nd.array(param)\n        inputs[name] = _expr.const(param)\n    return inputs\n\n\nclass BuildModule(object):\n    \"\"\"Build an IR module to run on TVM graph executor. This class is used\n    to expose the `RelayBuildModule` APIs implemented in C++.\n    \"\"\"\n\n    def __init__(self):\n        self.mod = _build_module._BuildModule()\n        self._get_graph_json = self.mod[\"get_graph_json\"]\n        self._get_module = self.mod[\"get_module\"]\n        self._build = self.mod[\"build\"]\n        self._optimize = self.mod[\"optimize\"]\n        self._set_params_func = self.mod[\"set_params\"]\n        self._get_params_func = self.mod[\"get_params\"]\n        self._get_function_metadata = self.mod[\"get_function_metadata\"]\n        self._get_executor_codegen_metadata = self.mod[\"get_executor_codegen_metadata\"]\n        self._get_devices = self.mod[\"get_devices\"]\n        self._get_irmodule = self.mod[\"get_irmodule\"]\n\n    def build(\n        self,\n        mod,\n        target=None,\n        target_host=None,\n        executor=Executor(\"graph\"),\n        runtime=Runtime(\"cpp\"),\n        workspace_memory_pools=None,\n        constant_memory_pools=None,\n        params=None,\n        mod_name=None,\n    ):\n        \"\"\"\n        Parameters\n        ----------\n        mod : :py:class:`~tvm.IRModule`\n            The IRModule to build.\n\n        target : any multi-target like object, see Target.canon_multi_target\n            For homogeneous compilation, the unique build target.\n            For heterogeneous compilation, a dictionary or list of possible build targets.\n\n        target_host : None, or any target-like object, see Target.canon_target\n            Host compilation target, if target is device.\n            When TVM compiles device specific program such as CUDA,\n            we also need host(CPU) side code to interact with the driver\n            to setup the dimensions and parameters correctly.\n            target_host is used to specify the host side codegen target.\n            By default, llvm is used if it is enabled,\n            otherwise a stackvm interpreter is used.\n\n        executor : Optional[Executor]\n            The executor configuration with which to build the model.\n            Defaults to \"graph\" if no executor specified.\n\n        runtime : Optional[Runtime]\n            Runtime configuration to use when building the model.\n            Defaults to \"cpp\" if no runtime specified.\n\n        workspace_memory_pools : Optional[WorkspaceMemoryPools]\n            The object that contains an Array of WorkspacePoolInfo objects\n            that hold properties of read-write workspace pools that could be\n            used by the inference.\n\n        constant_memory_pools : Optional[ConstantMemoryPools]\n            The object that contains an Array of ConstantPoolInfo objects\n            that hold properties of read-only memory pools that could be\n            used by the inference.\n\n        params : dict of str to NDArray\n            Input parameters to the graph that do not change\n            during inference time. Used for constant folding.\n\n        mod_name: Optional[str]\n            The module name we will build\n\n        Returns\n        -------\n        graph_json : str\n            The json string that can be accepted by graph executor.\n\n        mod : tvm.Module\n            The module containing necessary libraries.\n\n        params : dict\n            The parameters of the final graph.\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from tvm.auto_scheduler import is_auto_scheduler_enabled\n        from tvm.meta_schedule import is_meta_schedule_enabled\n\n        # pylint: enable=import-outside-toplevel\n        # Setup the params.\n        if params:\n            self._set_params(params)\n\n        # Build the IR module. If auto_scheduler is not enabled,\n        # then use the TOPI-defined schedule.\n\n        # Turn off AutoTVM config not found warnings if auto_scheduler is enabled.\n        old_autotvm_silent = autotvm.GLOBAL_SCOPE.silent\n        autotvm.GLOBAL_SCOPE.silent = (\n            is_auto_scheduler_enabled() or is_meta_schedule_enabled() or old_autotvm_silent\n        )\n\n        mod_name = mangle_module_name(mod_name)\n\n        self._build(\n            mod,\n            target,\n            target_host,\n            executor,\n            runtime,\n            workspace_memory_pools,\n            constant_memory_pools,\n            mod_name,\n        )\n        autotvm.GLOBAL_SCOPE.silent = old_autotvm_silent\n\n        # Get artifacts\n        mod = self.get_module()\n        params = self.get_params()\n        executor_config = self.get_graph_json() if executor.name == \"graph\" else None\n\n        return executor_config, mod, params\n\n    def optimize(self, mod, target=None, target_host=None, params=None):\n        \"\"\"\n        Parameters\n        ----------\n        mod : :py:class:`~tvm.IRModule`\n            The IR module to build.\n\n        target : any multi-target like object, see Target.canon_multi_target.\n            For homogeneous compilation, the unique build target.\n            For heterogeneous compilation, a dictionary or list of possible build targets.\n\n        target_host : None, or any target-like object, see Target.canon_target\n            Host compilation target, if target is device.\n\n        params : dict of str to NDArray\n            Input parameters to the graph that do not change\n            during inference time. Used for constant folding.\n\n        Returns\n        -------\n        mod : :py:class:`~tvm.IRModule`\n            The optimized relay module.\n\n        params : dict\n            The parameters of the final graph.\n        \"\"\"\n        raw_targets = Target.canon_multi_target_and_host(target, target_host)\n\n        # Setup the params.\n        if params:\n            self._set_params(params)\n        mod = self._optimize(mod, raw_targets)\n        # Get artifacts\n        params = self.get_params()\n\n        return mod, params\n\n    def _set_params(self, params):\n        self._set_params_func(_convert_param_map(params))\n\n    def get_graph_json(self):\n        \"\"\"Return the json file of the built program.\"\"\"\n        return self._get_graph_json()\n\n    def get_module(self):\n        \"\"\"Return the built module.\"\"\"\n        return self._get_module()\n\n    def get_function_metadata(self):\n        \"\"\"Return the compiled function metadata.\n        Currently, the metadata contains workspace size required by\n        each PrimFunc\"\"\"\n        return self._get_function_metadata()\n\n    def get_executor_codegen_metadata(self):\n        \"\"\"Return the metadata produced after executor\n        codegen\n        \"\"\"\n        return self._get_executor_codegen_metadata()\n\n    def get_devices(self):\n        \"\"\"Returns a list of devices configured in this module\"\"\"\n        return self._get_devices()\n\n    def get_params(self):\n        \"\"\"Return the updated weights.\"\"\"\n        params = self._get_params_func()\n        ret = {}\n        for key, value in params.items():\n            ret[key] = value.data\n        return ret\n\n    def get_irmodule(self):\n        \"\"\"Returns the TargetIRModule's post-lowering\"\"\"\n        return self._get_irmodule()\n\n\n@register_func(\"tvm.relay.module_export_library\")\ndef _module_export(module, file_name):  # fcompile, addons, kwargs?\n    return module.export_library(file_name)\n\n\n@register_func(\"tvm.relay.build\")\ndef _build_module_no_factory_impl(mod, target, target_host, params, mod_name):\n    return build(\n        mod, target=target, target_host=target_host, params=params, mod_name=mod_name\n    ).module\n\n\ndef _build_module_no_factory(mod, target=None, target_host=None, params=None, mod_name=\"default\"):\n    \"\"\"A wrapper around build which discards the Python GraphFactoryRuntime.\n    This wrapper is suitable to be used from other programming languages as\n    the runtime::Module can be freely passed between language boundaries.\n    \"\"\"\n    return _build_module_no_factory_impl(mod, target, target_host, params, mod_name)\n\ndef build_with_bldmod(\n    ir_mod,\n    target=None,\n    target_host=None,\n    executor=Executor(\"graph\"),\n    runtime=Runtime(\"cpp\"),\n    workspace_memory_pools=None,\n    constant_memory_pools=None,\n    params=None,\n    mod_name=\"default\",\n):\n    # fmt: off\n    # pylint: disable=line-too-long\n    \"\"\"Helper function that builds a Relay function to run on TVM graph executor.\n\n    Parameters\n    ----------\n    ir_mod : :py:class:`~tvm.IRModule`\n        The IR module to build. Using relay.Function is deprecated.\n\n    target : None, or any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n        Defaults to the current target in the environment if None.\n\n    target_host : None, or any target like object, see Target.canon_target\n        Host compilation target, if target is device.\n\n    executor : Optional[Executor]\n        The executor configuration with which to build the model.\n        Defaults to \"graph\" if no executor specified.\n\n    runtime : Optional[Runtime]\n        Runtime configuration to use when building the model.\n        Defaults to \"cpp\" if no runtime specified.\n\n    workspace_memory_pools : Optional[WorkspaceMemoryPools]\n        The object that contains an Array of WorkspacePoolInfo objects\n        that hold properties of read-write workspace pools that could be\n        used by the inference.\n\n    constant_memory_pools : Optional[ConstantMemoryPools]\n        The object that contains an Array of ConstantPoolInfo objects\n        that hold properties of read-only pools that could be\n        used by the inference.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    mod_name: Optional[str]\n        The module name we will build\n\n    Returns\n    -------\n    factory_module : tvm.relay.backend.executor_factory.ExecutorFactoryModule\n            The runtime factory for the TVM graph executor.\n    \"\"\"\n    # pylint: enable=line-too-long\n    # fmt: on\n\n    if not isinstance(ir_mod, (IRModule, _function.Function)):\n        raise ValueError(\"Type of input parameter mod must be tvm.IRModule\")\n\n    if isinstance(ir_mod, _function.Function):\n        if params:\n            ir_mod = bind_params_by_name(ir_mod, params)\n        ir_mod = IRModule.from_expr(ir_mod)\n        warnings.warn(\n            \"Please use input parameter mod (tvm.IRModule) \"\n            \"instead of deprecated parameter mod (tvm.relay.function.Function)\",\n            DeprecationWarning,\n        )\n\n    raw_targets = Target.canon_multi_target_and_host(Target.target_or_current(target), target_host)\n    assert len(raw_targets) > 0\n    target_host = raw_targets[0].host\n\n    # If current dispatch context is fallback context (the default root context),\n    # then load pre-tuned parameters from TopHub\n    if isinstance(autotvm.DispatchContext.current, autotvm.FallbackContext):\n        tophub_context = autotvm.tophub.context(list(raw_targets))\n    else:\n        tophub_context = autotvm.utils.EmptyContext()\n\n    with tophub_context:\n        bld_mod = BuildModule()\n        graph_json, runtime_mod, params = bld_mod.build(\n            mod=ir_mod,\n            target=raw_targets,\n            params=params,\n            executor=executor,\n            runtime=runtime,\n            workspace_memory_pools=workspace_memory_pools,\n            constant_memory_pools=constant_memory_pools,\n            mod_name=mod_name,\n        )\n        func_metadata = bld_mod.get_function_metadata()\n        devices = bld_mod.get_devices()\n        lowered_ir_mods = bld_mod.get_irmodule()\n        executor_codegen_metadata = bld_mod.get_executor_codegen_metadata()\n\n        if executor.name == \"aot\":\n            executor_factory = _executor_factory.AOTExecutorFactoryModule(\n                ir_mod,\n                lowered_ir_mods,\n                raw_targets,\n                executor,\n                runtime,\n                runtime_mod,\n                mod_name,\n                params,\n                func_metadata,\n                executor_codegen_metadata,\n                devices,\n            )\n        elif executor.name == \"graph\":\n            executor_factory = _executor_factory.GraphExecutorFactoryModule(\n                ir_mod,\n                raw_targets,\n                executor,\n                graph_json,\n                runtime_mod,\n                mod_name,\n                params,\n                func_metadata,\n            )\n        else:\n            assert False, \"Executor \" + executor + \" not supported\"\n\n        return executor_factory, bld_mod\n\n\ndef build(\n    ir_mod,\n    target=None,\n    target_host=None,\n    executor=Executor(\"graph\"),\n    runtime=Runtime(\"cpp\"),\n    workspace_memory_pools=None,\n    constant_memory_pools=None,\n    params=None,\n    mod_name=\"default\",\n):\n    # fmt: off\n    # pylint: disable=line-too-long\n    \"\"\"Helper function that builds a Relay function to run on TVM graph executor.\n\n    Parameters\n    ----------\n    ir_mod : :py:class:`~tvm.IRModule`\n        The IR module to build. Using relay.Function is deprecated.\n\n    target : None, or any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n        Defaults to the current target in the environment if None.\n\n    target_host : None, or any target like object, see Target.canon_target\n        Host compilation target, if target is device.\n\n    executor : Optional[Executor]\n        The executor configuration with which to build the model.\n        Defaults to \"graph\" if no executor specified.\n\n    runtime : Optional[Runtime]\n        Runtime configuration to use when building the model.\n        Defaults to \"cpp\" if no runtime specified.\n\n    workspace_memory_pools : Optional[WorkspaceMemoryPools]\n        The object that contains an Array of WorkspacePoolInfo objects\n        that hold properties of read-write workspace pools that could be\n        used by the inference.\n\n    constant_memory_pools : Optional[ConstantMemoryPools]\n        The object that contains an Array of ConstantPoolInfo objects\n        that hold properties of read-only pools that could be\n        used by the inference.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    mod_name: Optional[str]\n        The module name we will build\n\n    Returns\n    -------\n    factory_module : tvm.relay.backend.executor_factory.ExecutorFactoryModule\n            The runtime factory for the TVM graph executor.\n    \"\"\"\n    # pylint: enable=line-too-long\n    # fmt: on\n\n    if not isinstance(ir_mod, (IRModule, _function.Function)):\n        raise ValueError(\"Type of input parameter mod must be tvm.IRModule\")\n\n    if isinstance(ir_mod, _function.Function):\n        if params:\n            ir_mod = bind_params_by_name(ir_mod, params)\n        ir_mod = IRModule.from_expr(ir_mod)\n        warnings.warn(\n            \"Please use input parameter mod (tvm.IRModule) \"\n            \"instead of deprecated parameter mod (tvm.relay.function.Function)\",\n            DeprecationWarning,\n        )\n\n    raw_targets = Target.canon_multi_target_and_host(Target.target_or_current(target), target_host)\n    assert len(raw_targets) > 0\n    target_host = raw_targets[0].host\n\n    # If current dispatch context is fallback context (the default root context),\n    # then load pre-tuned parameters from TopHub\n    if isinstance(autotvm.DispatchContext.current, autotvm.FallbackContext):\n        tophub_context = autotvm.tophub.context(list(raw_targets))\n    else:\n        tophub_context = autotvm.utils.EmptyContext()\n\n    with tophub_context:\n        bld_mod = BuildModule()\n        graph_json, runtime_mod, params = bld_mod.build(\n            mod=ir_mod,\n            target=raw_targets,\n            params=params,\n            executor=executor,\n            runtime=runtime,\n            workspace_memory_pools=workspace_memory_pools,\n            constant_memory_pools=constant_memory_pools,\n            mod_name=mod_name,\n        )\n        func_metadata = bld_mod.get_function_metadata()\n        devices = bld_mod.get_devices()\n        lowered_ir_mods = bld_mod.get_irmodule()\n        executor_codegen_metadata = bld_mod.get_executor_codegen_metadata()\n\n        if executor.name == \"aot\":\n            executor_factory = _executor_factory.AOTExecutorFactoryModule(\n                ir_mod,\n                lowered_ir_mods,\n                raw_targets,\n                executor,\n                runtime,\n                runtime_mod,\n                mod_name,\n                params,\n                func_metadata,\n                executor_codegen_metadata,\n                devices,\n            )\n        elif executor.name == \"graph\":\n            executor_factory = _executor_factory.GraphExecutorFactoryModule(\n                ir_mod,\n                raw_targets,\n                executor,\n                graph_json,\n                runtime_mod,\n                mod_name,\n                params,\n                func_metadata,\n            )\n        else:\n            assert False, \"Executor \" + executor + \" not supported\"\n\n        return executor_factory\n\n\ndef optimize(mod, target=None, params=None):\n    \"\"\"Helper function that optimizes a Relay module.\n\n    Parameters\n    ----------\n    mod : :py:class:`~tvm.IRModule`\n        The module to build. Using relay.Function is deprecated.\n\n    target : None, or any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n        Defaults to the current target in the environment if None.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    Returns\n    -------\n    mod : :py:class:`~tvm.IRModule`\n        The optimized relay module.\n\n    params : dict\n        The parameters of the final graph.\n    \"\"\"\n    if not isinstance(mod, (IRModule, _function.Function)):\n        raise ValueError(\"Type of input parameter mod must be tvm.IRModule\")\n\n    if isinstance(mod, _function.Function):\n        if params:\n            mod = bind_params_by_name(mod, params)\n        mod = IRModule.from_expr(mod)\n        warnings.warn(\n            \"Please use input parameter mod (tvm.IRModule) \"\n            \"instead of deprecated parameter func (tvm.relay.function.Function)\",\n            DeprecationWarning,\n        )\n\n    raw_targets = Target.canon_multi_target_and_host(Target.target_or_current(target))\n\n    # If current dispatch context is fallback context (the default root context),\n    # then load pre-tuned parameters from TopHub\n    if isinstance(autotvm.DispatchContext.current, autotvm.FallbackContext):\n        tophub_context = autotvm.tophub.context(raw_targets)\n    else:\n        tophub_context = autotvm.utils.EmptyContext()\n\n    with tophub_context:\n        bld_mod = BuildModule()\n        mod, params = bld_mod.optimize(mod, target=raw_targets, params=params)\n    return mod, params\n\n\ndef bind_params_by_name(func, params):\n    \"\"\"Bind params to function by name.\n    This could be useful when assembling custom Relay optimization\n    passes that involve constant folding.\n\n    Parameters\n    ----------\n    func : relay.Function\n        The function to bind parameters to.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    Returns\n    -------\n    func : relay.Function\n        The function with parameters bound\n    \"\"\"\n    inputs = _convert_param_map(params)\n    return _build_module.BindParamsByName(func, inputs)\n\n\nclass GraphExecutor(_interpreter.Executor):\n    \"\"\"Wrapper around Executor interface.\n\n    This executor is used for debug and testing purposes.\n\n    Parameters\n    ----------\n    mod : :py:class:`~tvm.IRModule`\n        The module to support the execution.\n\n    device : :py:class:`Device`\n        The runtime device to run the code on.\n\n    target : any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n    \"\"\"\n\n    def __init__(self, mod, device, target):\n        assert mod is not None\n        self.mod = mod\n        self.device = device\n        self.target = target\n\n    def _make_executor(self, expr=None):\n        if expr:\n            self.mod[\"main\"] = expr\n        self.mod = InferType()(self.mod)\n        ret_type = self.mod[\"main\"].checked_type.ret_type\n        if _ty.is_dynamic(ret_type):\n            raise ValueError(\n                \"Graph Executor only supports static graphs, got output type\", ret_type\n            )\n        mod = build(self.mod, target=self.target)\n        gmodule = _graph_executor.GraphModule(mod[\"default\"](self.device))\n\n        def _unflatten(flat_iter, cur_type):\n            if isinstance(cur_type, _ty.TensorType):\n                return next(flat_iter)\n            if isinstance(cur_type, _ty.TupleType):\n                fields = []\n                for field_type in cur_type.fields:\n                    field = _unflatten(flat_iter, field_type)\n                    fields.append(field)\n                return fields\n            raise ValueError(\"Return type\", ret_type, \"contains unsupported type\", cur_type)\n\n        def _graph_wrapper(*args, **kwargs):\n            args = self._convert_args(self.mod[\"main\"], args, kwargs)\n            # Create map of inputs.\n            for i, arg in enumerate(args):\n                gmodule.set_input(i, arg)\n            # Run the module, and fetch the output.\n            gmodule.run()\n            flattened = []\n            for i in range(gmodule.get_num_outputs()):\n                flattened.append(gmodule.get_output(i).copyto(_nd.cpu(0)))\n            unflattened = _unflatten(iter(flattened), ret_type)\n            return unflattened\n\n        return _graph_wrapper\n\n\nclass AotExecutor(_interpreter.Executor):\n    \"\"\"Implements the Executor interface for AOT.\n\n    Parameters\n    ----------\n    mod : :py:class:`~tvm.IRModule`\n        The module to support the execution.\n\n    device : :py:class:`Device`\n        The runtime device to run the code on.\n\n    target : any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n    \"\"\"\n\n    def __init__(self, mod, device, target):\n        assert mod is not None\n        self.mod = mod\n        self.device = device\n        self.target = target\n\n    def _make_executor(self, expr=None):\n        if expr:\n            self.mod[\"main\"] = expr\n        self.mod = InferType()(self.mod)\n        ret_type = self.mod[\"main\"].checked_type.ret_type\n        if _ty.is_dynamic(ret_type):\n            raise ValueError(\"AOT Executor only supports static graphs, got output type\", ret_type)\n        mod = build(self.mod, target=self.target)\n\n        # NOTE: Given AOT requires use of the \"c\" backend, must export/import to compile the\n        # generated code.\n        temp_so_dir = contrib_utils.TempDirectory()\n        temp_so = temp_so_dir / \"temp.so\"\n        mod.export_library(temp_so, cc=\"gcc\", options=[\"-std=c11\"])\n\n        mod = load_module(temp_so)\n        aot_mod = mod[\"default\"](self.device)\n        gmodule = _aot_executor.AotModule(aot_mod)\n\n        def _unflatten(flat_iter, cur_type):\n            if isinstance(cur_type, _ty.TensorType):\n                return next(flat_iter)\n            if isinstance(cur_type, _ty.TupleType):\n                fields = []\n                for field_type in cur_type.fields:\n                    field = _unflatten(flat_iter, field_type)\n                    fields.append(field)\n                return fields\n            raise ValueError(\"Return type\", ret_type, \"contains unsupported type\", cur_type)\n\n        def _aot_wrapper(*args, **kwargs):\n            args = self._convert_args(self.mod[\"main\"], args, kwargs)\n            # Create map of inputs.\n            for i, arg in enumerate(args):\n                gmodule.set_input(i, arg)\n            # Run the module, and fetch the output.\n            gmodule.run()\n            flattened = []\n            for i in range(gmodule.get_num_outputs()):\n                flattened.append(gmodule.get_output(i).copyto(_nd.cpu(0)))\n            unflattened = _unflatten(iter(flattened), ret_type)\n            return unflattened\n\n        return _aot_wrapper\n\n\n# TODO(mbs): Collapse the create_executor/evaluate phases together since a) most callers don't\n# reuse the executor for multiple expressions and b) any preparation necessary for the expression\n# evaluation needs to (currently) be done along with preparation for the module.\ndef create_executor(kind=\"debug\", mod=None, device=None, target=\"llvm\", params=None):\n\n    \"\"\"Factory function to create an executor.\n\n    Example\n    -------\n    .. code-block:: python\n\n        import tvm.relay\n        import numpy as np\n\n        x = tvm.relay.var(\"x\", tvm.relay.TensorType([1], dtype=\"float32\"))\n        expr = tvm.relay.add(x, tvm.relay.Constant(tvm.nd.array(np.array([1], dtype=\"float32\"))))\n        tvm.relay.create_executor(\n            kind=\"vm\", mod=tvm.IRModule.from_expr(tvm.relay.Function([x], expr))\n        ).evaluate()(np.array([2], dtype=\"float32\"))\n        # returns `array([3.], dtype=float32)`\n\n    Parameters\n    ----------\n    kind : str\n        The type of executor. Avaliable options are `debug` for the interpreter, `graph` for the\n        graph executor, `aot` for the aot executor, and `vm` for the virtual machine.\n\n    mod : :py:class:`~tvm.IRModule`\n        The Relay module containing collection of functions\n\n    device : :py:class:`Device`\n        The device to execute the code.\n\n    target : any multi-target like object, see Target.canon_multi_target\n        For homogeneous compilation, the unique build target.\n        For heterogeneous compilation, a dictionary or list of possible build targets.\n        CAUTION: Though this API allows multiple targets, it does not allow multiple devices, so\n        heterogenous compilation is not yet supported.\n\n    params : dict of str to NDArray\n         Input parameters to the graph that do not change\n         during inference time.\n\n    Returns\n    -------\n    executor : :py:class:`~tvm.relay.backend.interpreter.Executor`\n    \"\"\"\n    raw_targets = Target.canon_multi_target(target)\n    if mod is None:\n        mod = IRModule()\n    if device is not None:\n        assert device.device_type == raw_targets[0].get_target_device_type()\n    else:\n        # Derive the default device from the first target.\n        device = _nd.device(raw_targets[0].get_target_device_type(), 0)\n\n    if params is not None:\n        mod = IRModule.from_expr(bind_params_by_name(mod[\"main\"], params))\n\n    assert \"executor\" not in raw_targets[0].attrs or raw_targets[0].attrs[\"executor\"] == kind\n\n    if kind == \"debug\":\n        assert len(raw_targets) == 1, \"The interpreter currently only supports a single target\"\n        return _interpreter.Interpreter(mod, device, raw_targets[0])\n    if kind == \"graph\":\n        return GraphExecutor(mod, device, raw_targets)\n    if kind == \"vm\":\n        return VMExecutor(mod, device, raw_targets)\n    if kind == \"aot\":\n        return AotExecutor(mod, device, raw_targets)\n    raise RuntimeError(\"unknown execution strategy: {0}\".format(kind))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/collage/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"relay.collage exports\"\"\"\nfrom .collage import (\n    MEASURE_NUMBER,\n    MEASURE_REPEAT,\n    WARMUP_MIN_REPEAT_MS,\n    CostEstimator,\n    MockCostEstimator,\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/collage/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for the Collage partitioner.\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"relay.collage\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/collage/collage.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Mostly helper methods which interface the main C++ Collage implementation with Python.\n   See relay.transform.CollagePartition for the main Collage entrypoint.\"\"\"\n\nimport logging\nimport os\nimport math\nimport tempfile\n\nimport numpy as np\n\nimport tvm\nfrom tvm._ffi.registry import register_func, register_object\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n# Parameters to use when estimating latency (of both partitions and overall models).\nMEASURE_NUMBER = 20\nMEASURE_REPEAT = 5\nWARMUP_MIN_REPEAT_MS = 250\n\n\n@register_object(\"relay.collage.CostEstimator\")\nclass CostEstimator(Object):\n    \"\"\"CostEstimator class\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_ffi_api.CostEstimator)\n\n\n@register_object(\"relay.collage.MockCostEstimator\")\nclass MockCostEstimator(Object):\n    \"\"\"MockEstimator class\"\"\"\n\n    def __init__(self, target_costs, max_estimates=0):\n        self.__init_handle_by_constructor__(_ffi_api.MockCostEstimator, target_costs, max_estimates)\n\n\ndef arg_for(arg_type, device):\n    \"\"\"Returns a test argument of Relay arg_type on device\"\"\"\n    assert isinstance(arg_type, tvm.ir.TensorType)\n    return tvm.nd.array(\n        np.random.uniform(-1.0, 1.0, size=arg_type.concrete_shape).astype(arg_type.dtype),\n        device=device,\n    )\n\n\ndef vm_estimate_seconds(device, the_vm, func_name, args):\n    \"\"\"Returns the estimated latency, in seconds, of running func_name with args on the_vm.\"\"\"\n    # Warmup\n    the_vm.benchmark(\n        device, repeat=1, number=1, min_repeat_ms=WARMUP_MIN_REPEAT_MS, func_name=func_name, **args\n    )\n    # One more time, with feeling\n    return the_vm.benchmark(\n        device,\n        repeat=MEASURE_REPEAT,\n        number=MEASURE_NUMBER,\n        min_repeat_ms=0,\n        func_name=func_name,\n        **args,\n    )\n\n\n@register_func(\"tvm.relay.collage.estimate_seconds\")\ndef estimate_seconds(mod, target):\n    \"\"\"Returns the mean execution time of \"main\" in mod on target with params. The module\n    may contain \"Primitive\" functions, possibly with \"Compiler\" attributes.\"\"\"\n    device = tvm.device(target.get_target_device_type())\n\n    try:\n        # Build the module.\n        logging.info(\"Compiling module to estimate\")\n        exe = tvm.relay.vm.compile(mod, target)\n    except RuntimeError as err:\n        # A build failure indicates the partition is not supported.\n        # eg trying to build an nn.batch_norm on GPU, which has no schedule since we assume it\n        # is only ever used with a tuple projection which is rewritten away.\n        logging.info(\"Assigning module infinite cost since unable to build: %s\", err)\n        return math.inf\n\n    # Finalize compilation\n    tmp_dir = tempfile.mkdtemp()\n    code, lib = exe.save()\n    lib_path = os.path.join(tmp_dir, \"library.so\")\n    # TODO(mbs): Avoid nvcc dependency?\n    lib.export_library(lib_path, workspace_dir=tmp_dir, cc=\"nvcc\")\n    lib = tvm.runtime.load_module(lib_path)\n    exe = tvm.runtime.vm.Executable.load_exec(code, lib)\n\n    # Benchmark the module.\n    the_vm = tvm.runtime.vm.VirtualMachine(exe, device)\n    func_name = \"main\"\n    main_args = {v.name_hint: arg_for(v.checked_type, device) for v in mod[func_name].params}\n    logging.info(\"Benchmarking module to estimate\")\n    profile = vm_estimate_seconds(device, the_vm, func_name, main_args)\n    logging.info(\"profile: %s\", profile)\n    return profile.median  # seconds\n\n\ndef make_labelled_dfpattern_partition_rule_wrapper(compiler, pattern_tuple):\n    \"\"\"Returns a DFPatternPartitionRule representing one (label, pattern, predicate) entry from\n    the pattern table for external codegen compiler\"\"\"\n    if len(pattern_tuple) == 2:\n        rule_name, dataflow_pattern = pattern_tuple\n        return _ffi_api.MakeLabelledDFPatternPartitionRule(compiler, rule_name, dataflow_pattern)\n    else:\n        rule_name, dataflow_pattern, predicate = pattern_tuple\n        return _ffi_api.MakeLabelledDFPatternPartitionRuleWithPredicate(\n            compiler, rule_name, dataflow_pattern, predicate\n        )\n\n\n@register_func(\"tvm.relay.collage.make_byoc_partition_rule\")\ndef make_byoc_partition_rule(compiler):\n    \"\"\"Returns the PartitionRule for external codegen compiler\"\"\"\n    pattern_table = tvm.relay.op.contrib.get_pattern_table(compiler)\n    assert (\n        pattern_table is not None\n    ), f\"No pattern table entry was found for BYOC compiler {compiler}\"\n    logging.info(\n        \"Converting %s rules for %s for use in pattern style BYOC lowering/codegen\",\n        len(pattern_table),\n        compiler,\n    )\n    sub_rules = [\n        make_labelled_dfpattern_partition_rule_wrapper(compiler, pattern_tuple)\n        for pattern_tuple in pattern_table\n    ]\n    return _ffi_api.MakePatternBYOCPartitionRule(compiler, sub_rules)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/data_dep_optimization/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Optimizations involves changing of paramters\"\"\"\n\nfrom . import bsr_dense\nfrom . import simplify_fc_transpose\nfrom . import bsr_conv2d\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/data_dep_optimization/bsr_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Automatic convert model from dense to block sparse\"\"\"\n\nfrom tvm import relay\nfrom tvm.relay.analysis.sparse_conv2d import process_params\n\nfrom .utils import _run_opt_pass\n\n\ndef convert(func, params, blocksize, sparsity_threshold, layout=\"NHWC\", kernel_size=1):\n    \"\"\"Convert a conv2d func and according parameters to block sparse\n\n    Parameters\n    ----------\n    func : relay.Expr\n        Expr will be optimized to sparse operation\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the Expr\n    blocksize : Tuple(int, int)\n        Blocksize for BSR matrix\n    sparsity_threshold : float\n        Minimal sparsity requirement for converting.\n        If weight sparsity is lower than this threshold,\n        the dense operation will be kept.\n    layout : str\n        layout of network\n\n    Returns\n    -------\n    new_func: relay.Expr\n        Mutated Expr with sparse operations\n\n    params: Dict[Srting, tvm.nd.array]\n        New params with BSR matrix for mutated Expr\n    \"\"\"\n    weight_info = process_params(func, params, blocksize, sparsity_threshold, layout, kernel_size)\n    new_func = _run_opt_pass(\n        func,\n        relay.transform.Conv2dToSparse(\n            weight_info.weight_name, weight_info.weight_shape, layout, kernel_size\n        ),\n    )\n\n    return new_func, params\n\n\ndef convert2(func, params, blocksize, sparsity_threshold, layout, kernel_size):\n    \"\"\"Convert a freezed conv2d func to block sparse\n\n    Parameters\n    ----------\n    func : relay.Expr\n        Expr will be optimized to sparse operation, with params freezed\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the Expr (not used in this pass)\n    blocksize : Tuple(int, int)\n        Blocksize for BSR matrix\n    sparsity_threshold : float\n        Minimal sparsity requirement for converting.\n        If weight sparsity is lower than this threshold,\n        the dense operation will be kept.\n    layout : str\n        layout of network\n    kernel_size : int\n        kernel size of the conv2d, for filtering\n\n    Returns\n    -------\n    new_func: relay.Expr\n        Mutated Expr with sparse operations\n\n    params: Dict[Srting, tvm.nd.array]\n        New params with BSR matrix for mutated Expr (not modified)\n    \"\"\"\n    new_func = _run_opt_pass(\n        func, relay.transform.Conv2dToSparse2(layout, kernel_size, blocksize, sparsity_threshold)\n    )\n    return new_func, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/data_dep_optimization/bsr_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Automatic convert model from dense to block sparse\"\"\"\n\nfrom tvm import relay\nfrom tvm.relay.analysis.sparse_dense import process_params\n\nfrom .utils import _run_opt_pass\n\n\ndef convert(func, params, blocksize, sparsity_threshold):\n    \"\"\"Convert a dense func and according parameters to block sparse\n\n    Parameters\n    ----------\n    func : relay.Expr\n        Expr will be optimized to sparse operation\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the Expr\n    blocksize : Tuple(int, int)\n        Blocksize for BSR matrix\n    sparsity_threshold : float\n        Minimal sparsity requirement for converting.\n        If weight sparsity is lower than this threshold,\n        the dense operation will be kept.\n\n    Returns\n    -------\n    new_func: relay.Expr\n        Mutated Expr with sparse operations\n\n    params: Dict[Srting, tvm.nd.array]\n        New params with BSR matrix for mutated Expr\n    \"\"\"\n    weight_info = process_params(func, params, blocksize, sparsity_threshold)\n    new_func = _run_opt_pass(\n        func, relay.transform.DenseToSparse(weight_info.weight_name, weight_info.weight_shape)\n    )\n    return new_func, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/data_dep_optimization/simplify_fc_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Automatic optimize fc tranpose\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.analysis import search_fc_transpose\n\nfrom .utils import _run_opt_pass\n\n\ndef convert(func, params):\n    \"\"\"convert all ```y = nn.dense(x, transpose(w, [1, 0]))``` to\n        ```y = nn.dense(x, wt)```\n\n    Parameters\n    ----------\n    func : relay.Expr\n        Expr will be optimized\n    params : Dict[String, tvm.nd.array]\n        Parameters of Expr\n\n    Returns\n    -------\n    new_func : relay.Expr\n        Mutated Expr from ```y = nn.dense(x, transpose(w, [1, 0]))``` to\n        ```y = nn.dense(x, wt)```\n    params: Dict[String, tvm.nd.array]\n        Parameters of mutated Expr, with weights pre-transposed\n    \"\"\"\n    weight_info = search_fc_transpose(func)\n    for item in weight_info:\n        name = str(item)\n        w_np = params[name].numpy()\n        new_w = np.transpose(w_np, axes=[1, 0])\n        params[name + \".T\"] = tvm.nd.array(new_w)\n        del params[name]\n    new_func = _run_opt_pass(\n        func,\n        relay.transform.SimplifyFCTranspose(\n            weight_info,\n        ),\n    )\n    return new_func, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/data_dep_optimization/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Utils functions for optimizations\"\"\"\n\nimport tvm\n\n\ndef _run_opt_pass(expr, opt_pass):\n    \"\"\"Helper function to run pass\n\n    Parameters\n    ----------\n    expr : relay.Expr\n        Expr will be optimized\n    opt_pass : relay.Pass\n        Optimization pass\n\n    Returns\n    -------\n    ret: relay.Expr\n        Optimized Expr by running opt_pass\n    \"\"\"\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = opt_pass(mod)\n    return mod[\"main\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/dataflow_pattern/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The Relay Pattern Language and tooling.\"\"\"\n# pylint: disable=no-member\nfrom typing import Callable, Dict, List, Optional\n\nimport tvm._ffi\nfrom tvm.relay.expr import RelayExpr as Expr\n\nfrom ... import _ffi as tvm_ffi\nfrom ... import ir as _ir\nfrom ...ir import make_node\nfrom ...ir.base import Node\nfrom ...runtime import Object\nfrom ..op import get\nfrom . import _ffi as ffi\n\n\ndef register_df_node(type_key=None):\n    \"\"\"Register a Relay node type.\n\n    Parameters\n    ----------\n    type_key : str or cls\n        The type key of the node.\n    \"\"\"\n    if not isinstance(type_key, str):\n        return tvm._ffi.register_object(\"relay.dataflow_pattern.\" + type_key.__name__)(type_key)\n    return tvm._ffi.register_object(type_key)\n\n\nclass DFPattern(Node):\n    \"\"\"Base class of all Patterns.\"\"\"\n\n    def __call__(self, *args):\n        args = list(args)\n        if len(args) == 1 and args[0] is None:\n            args = None\n        return CallPattern(self, args)\n\n    def __or__(self, other):\n        return AltPattern(self, other)\n\n    def __add__(self, other):\n        return is_op(\"add\")(self, other)\n\n    def __sub__(self, other):\n        return is_op(\"subtract\")(self, other)\n\n    def __mul__(self, other):\n        return is_op(\"multiply\")(self, other)\n\n    def __truediv__(self, other):\n        return is_op(\"divide\")(self, other)\n\n    def has_attr(self, attrs: Dict[str, Object]):\n        \"\"\"\n        Add an attribute constraint to this pattern\n\n        Parameters\n        ----------\n        attrs: Dict[str, Object]\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting AttrPattern\n        \"\"\"\n        attrs = make_node(\"DictAttrs\", **attrs)\n        return AttrPattern(self, attrs)\n\n    def has_type(self, ttype: tvm.ir.type.Type):\n        \"\"\"\n        Add a type constraint to this pattern\n\n        Parameters\n        ----------\n        ttype: tvm.ir.type.Type\n            The type to match\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting TypePattern\n        \"\"\"\n        return has_type(ttype, self)\n\n    def has_dtype(self, dtype: str):\n        \"\"\"\n        Add a type constraint to this pattern\n\n        Parameters\n        ----------\n        dtype: str\n            The dtype to match\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting DataTypePattern\n        \"\"\"\n        return has_dtype(dtype, self)\n\n    def has_shape(self, shape: List[tvm.ir.PrimExpr]):\n        \"\"\"\n        Add a type constraint to this pattern\n\n        Parameters\n        ----------\n        shape: List[tvm.ir.PrimExpr]\n            The shape to match\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting ShapePattern\n        \"\"\"\n        return has_shape(shape, self)\n\n    def match(self, expr: Expr) -> bool:\n        \"\"\"\n        Match this pattern to an expression\n\n        Parameters\n        ----------\n        expr : tvm.relay.Expr\n            The expression to match.\n\n        Returns\n        -------\n        result: bool\n            Whether or not the expression matches the pattern\n        \"\"\"\n        return match(self, expr)\n\n    def partition(\n        self,\n        expr: Expr,\n        attrs: Optional[Dict[str, Object]] = None,\n        check: Callable[[Expr], bool] = lambda x: True,\n    ) -> Expr:\n        \"\"\"\n        Partition the expression into functions defined by this pattern\n\n        Parameters\n        ----------\n        expr : tvm.relay.Expr\n            The expression to match.\n        attrs : Optional[Dict[str, Object]]\n            A dictionary of Attribute name/values to add to the paritioned function\n        check : Callable[[Expr], bool]\n            A function to perform more complicated checks on the matched expression.\n            Returns true if partitioning should proceed, false otherwise.\n\n        Returns\n        -------\n        result : tvm.relay.Expr\n            The Expression with matched subgraphs replaced by function calls to that subgraph\n        \"\"\"\n        return partition(self, expr, attrs, check)\n\n    def dominates(self, parent: \"DFPattern\", path: \"DFPattern\" = None):\n        \"\"\"\n        Create a dominator for this pattern.\n\n        Parameters\n        ----------\n        parent: tvm.relay.dataflow_pattern.DFPattern\n            The parent pattern this pattern dominates.\n        path: tvm.relay.dataflow_pattern.DFPattern\n            The fuzzy path pattern.\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting DominatorPattern.\n        \"\"\"\n        if path is None:\n            path = wildcard()\n        return DominatorPattern(parent, path, self)\n\n    def optional(self, option_constructor: Callable[[\"DFPattern\"], \"DFPattern\"]):\n        \"\"\"\n        Create a optional user of this pattern.\n\n        Parameters\n        ----------\n        option_constructor: function\n            A function that takes a single Pattern parameter and returns\n            a constructed pattern matching the option\n\n        Returns\n        -------\n        result: tvm.relay.dataflow_pattern.DFPattern\n            The resulting Pattern\n        \"\"\"\n        return self | option_constructor(self)\n\n\ndef is_var(name: str = \"\") -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an optionally named VarPattern.\n\n    Parameters\n    ----------\n    name: str\n        The name of the input pattern to match.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return VarPattern(name)\n\n\ndef is_constant() -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating a ConstantPattern.\n\n    Parameters\n    ----------\n    name: str\n        The name of the input pattern to match.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return ConstantPattern()\n\n\ndef is_expr(expr: Expr) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an ExprPattern.\n\n    Parameters\n    ----------\n    expr: Expr\n        The Relay expression to match.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return ExprPattern(expr)\n\n\ndef is_op(op_name: str) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an operator ExprPattern.\n\n    Parameters\n    ----------\n    op_name: String\n        The name of the relay op\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting ExprPattern\n    \"\"\"\n    op = get(op_name)\n    return ExprPattern(op)\n\n\ndef is_tuple(fields: tvm.ir.container.Array) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an ExprPattern.\n\n    Parameters\n    ----------\n    fields : Array[tvm.relay.dataflow_pattern.DFPattern]\n        The fields in the tuple.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return TuplePattern(fields)\n\n\ndef is_tuple_get_item(tuple_value: \"DFPattern\", index: Optional[int] = None) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an ExprPattern.\n\n    Parameters\n    ----------\n    tuple_value: tvm.relay.dataflow_pattern.DFPattern\n        The input tuple expression.\n\n    index: Optional[int]\n        The index to match; Default (None) to match a TupleGetItem with any index.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return TupleGetItemPattern(tuple_value, index)\n\n\ndef is_if(cond, true_branch, false_branch):\n    \"\"\"\n    Syntatic sugar for creating an IfPattern.\n\n    Parameters\n    ----------\n    cond: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the condition of If.\n\n    true_branch: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the true branch of If.\n\n    false_branch: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the false branch of If.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return IfPattern(cond, true_branch, false_branch)\n\n\ndef is_let(var, value, body):\n    \"\"\"\n    Syntatic sugar for creating a LetPattern.\n\n    Parameters\n    ----------\n    var: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the variable of Let.\n\n    value: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the value of Let.\n\n    body: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the body where the binding is in effect.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return LetPattern(var, value, body)\n\n\ndef wildcard() -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating a WildcardPattern.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting pattern.\n    \"\"\"\n    return WildcardPattern()\n\n\ndef has_type(ttype: tvm.ir.type.Type, pattern: \"DFPattern\" = None) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating a TypePattern\n\n    Parameters\n    ----------\n    ttype: tvm.ir.type.Type\n        The type to match\n\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The pattern that needs type annotation\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting TypePattern\n    \"\"\"\n    if pattern is None:\n        pattern = wildcard()\n    return TypePattern(pattern, ttype)\n\n\ndef has_dtype(dtype: str, pattern: \"DFPattern\" = None) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating a DataTypePattern\n\n    Parameters\n    ----------\n    dtype: str\n        The dtype to match\n\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The pattern that needs type annotation\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting DataTypePattern\n    \"\"\"\n    if pattern is None:\n        pattern = wildcard()\n    return DataTypePattern(pattern, dtype)\n\n\ndef has_shape(shape: List[tvm.ir.PrimExpr], pattern: \"DFPattern\" = None) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating a ShapePattern\n\n    Parameters\n    ----------\n    shape: List[tvm.ir.PrimExpr]\n        The shape to match\n\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The pattern that needs type annotation\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting ShapePattern\n    \"\"\"\n    if pattern is None:\n        pattern = wildcard()\n    return ShapePattern(pattern, shape)\n\n\ndef has_attr(attrs, pattern=None) -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an AttrPattern\n\n    Parameters\n    ----------\n    attrs: Dict[str, Object]\n        The attributes to match\n\n    pattern: Optional[tvm.relay.dataflow_pattern.DFPattern]\n        The input pattern.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting AttrPattern\n    \"\"\"\n    if pattern is None:\n        pattern = wildcard()\n    return pattern.has_attr(attrs)\n\n\ndef dominates(parent: \"DFPattern\", path: \"DFPattern\", child: \"DFPattern\") -> \"DFPattern\":\n    \"\"\"\n    Syntatic sugar for creating an Dominator pattern\n\n    Parameters\n    ----------\n    parent: tvm.relay.dataflow_pattern.DFPattern\n        The parent pattern.\n    path: tvm.relay.dataflow_pattern.DFPattern\n        The fuzzy path pattern.\n    child: tvm.relay.dataflow_pattern.DFPattern\n        The child pattern.\n\n    Returns\n    -------\n    result: tvm.relay.dataflow_pattern.DFPattern\n        The resulting DominatorPattern.\n    \"\"\"\n    return DominatorPattern(parent, path, child)\n\n\ndef match(pattern: \"DFPattern\", expr: Expr) -> bool:\n    \"\"\"\n    Match a pattern to an expression\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The input pattern.\n    expr : tvm.relay.Expr\n        The expression to match.\n    \"\"\"\n    return ffi.match(pattern, expr)\n\n\n@register_df_node\nclass ExprPattern(DFPattern):\n    \"\"\"A pattern which matches a constant expression.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The expression to match.\n    \"\"\"\n\n    def __init__(self, expr: Expr):\n        self.__init_handle_by_constructor__(ffi.ExprPattern, expr)\n\n\n@register_df_node\nclass VarPattern(DFPattern):\n    \"\"\"A local variable in Relay.\n\n    Local variable can be used to declare input\n    arguments to a function, or intermediate variables.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the variable. Optional, if not provided,\n        the pattern will match any VarNode.\n\n    type_annotation: tvm.ir.type.Type, optional\n        The type annotation on the variable.\n    \"\"\"\n\n    def __init__(self, name_hint: str = \"\"):\n        self.__init_handle_by_constructor__(ffi.VarPattern, name_hint)\n\n\n@register_df_node\nclass ConstantPattern(DFPattern):\n    \"\"\"A pattern matching a Relay Constant.\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(ffi.ConstantPattern)\n\n\n@register_df_node\nclass CallPattern(DFPattern):\n    \"\"\"A pattern matching a function call node in Relay.\n\n    Parameters\n    ----------\n    op: relay.dataflow_pattern.DFPattern\n        The operation to be called.\n\n    args: List[relay.dataflow_pattern.DFPattern]\n        The arguments to the call or None to match any arguments.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        op: \"DFPattern\",\n        args: List[\"DFPattern\"],\n    ):\n        self.__init_handle_by_constructor__(ffi.CallPattern, op, args)\n\n\n@register_df_node\nclass FunctionPattern(DFPattern):\n    \"\"\"A pattern matching a function node in Relay.\n\n    Parameters\n    ----------\n    params: List[relay.dataflow_pattern.DFPattern]\n        The parameters to the Function or None to match any parameters.\n\n    body: relay.dataflow_pattern.DFPattern\n        The body fo the Function\n\n    \"\"\"\n\n    def __init__(\n        self,\n        params: List[\"DFPattern\"],\n        body: \"DFPattern\",\n    ):\n        self.__init_handle_by_constructor__(ffi.FunctionPattern, params, body)\n\n\n@register_df_node\nclass IfPattern(DFPattern):\n    \"\"\"A patern matching a Relay If.\n\n    Parameters\n    ----------\n    cond: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the condition of If.\n\n    true_branch: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the true branch of If.\n\n    false_branch: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the false branch of If.\n    \"\"\"\n\n    def __init__(self, cond: \"DFPattern\", true_branch: \"DFPattern\", false_branch: \"DFPattern\"):\n        self.__init_handle_by_constructor__(ffi.IfPattern, cond, true_branch, false_branch)\n\n\n@register_df_node\nclass LetPattern(DFPattern):\n    \"\"\"A patern matching a Relay Let.\n\n    Parameters\n    ----------\n    var: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the variable of Let.\n\n    value: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the value of Let.\n\n    body: tvm.relay.dataflow_pattern.DFPattern\n        The pattern describing the body where the binding is in effect.\n\n    \"\"\"\n\n    def __init__(self, var: \"DFPattern\", value: \"DFPattern\", body: \"DFPattern\"):\n        self.__init_handle_by_constructor__(ffi.LetPattern, var, value, body)\n\n\n@register_df_node\nclass TuplePattern(DFPattern):\n    \"\"\"A patern matching a Relay Tuple.\n\n    Parameters\n    ----------\n    fields : Array[tvm.relay.dataflow_pattern.DFPattern]\n        The fields in the tuple.\n    \"\"\"\n\n    def __init__(self, fields: tvm.ir.container.Array):\n        self.__init_handle_by_constructor__(ffi.TuplePattern, fields)\n\n    def __getitem__(self, index: int):\n        if index >= len(self):\n            raise IndexError(\"TuplePattern index out of range\")\n        return self.fields[index]\n\n    def __len__(self):\n        return len(self.fields)\n\n    def astype(self, _):\n        raise TypeError(\"astype cannot be used on TuplePattern\")\n\n\n@register_df_node\nclass TupleGetItemPattern(DFPattern):\n    \"\"\"Get index-th item from a TuplePattern.\n\n    Parameters\n    ----------\n    tuple_value: tvm.relay.dataflow_pattern.DFPattern\n        The input tuple expression.\n\n    index: Optional[int]\n        The index to match; Default (None) to match a TupleGetItem with any index.\n    \"\"\"\n\n    def __init__(self, tuple_value: \"DFPattern\", index: Optional[int] = None):\n        match_index = index if index is not None else -1\n        self.__init_handle_by_constructor__(ffi.TupleGetItemPattern, tuple_value, match_index)\n\n\n@register_df_node\nclass AltPattern(DFPattern):\n    \"\"\"Create a Pattern that can match one of two conditions\n\n    Parameters\n    ----------\n    left: tvm.relay.dataflow_pattern.DFPattern\n        One possible matching pattern.\n    right: tvm.relay.dataflow_pattern.DFPattern\n        One possible matching pattern.\n    \"\"\"\n\n    def __init__(self, left: \"DFPattern\", right: \"DFPattern\"):\n        self.__init_handle_by_constructor__(ffi.AltPattern, left, right)\n\n\n@register_df_node\nclass WildcardPattern(DFPattern):\n    \"\"\"A pattern which matches anything.\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(ffi.WildcardPattern)\n\n\n@register_df_node\nclass TypePattern(DFPattern):\n    \"\"\"A pattern that matches another pattern with a certain type annotation.\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The input pattern that needs type annotation.\n\n    ttype: tvm.ir.type.Type\n        The type to match.\n    \"\"\"\n\n    def __init__(self, pattern: \"DFPattern\", ttype: tvm.ir.type.Type):\n        self.__init_handle_by_constructor__(ffi.TypePattern, pattern, ttype)\n\n\n@register_df_node\nclass DataTypePattern(DFPattern):\n    \"\"\"A pattern that matches another pattern with certain data type\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The input pattern that needs type annotation.\n\n    dtype: str\n        The dtype to match.\n    \"\"\"\n\n    def __init__(self, pattern: \"DFPattern\", dtype: str):\n        self.__init_handle_by_constructor__(ffi.DataTypePattern, pattern, dtype)\n\n\n@register_df_node\nclass ShapePattern(DFPattern):\n    \"\"\"A pattern that matches another pattern with a certain tensor shape\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The input pattern that needs type annotation.\n\n    shape: List[tvm.ir.PrimExpr]\n        The shape to match.\n    \"\"\"\n\n    def __init__(self, pattern: \"DFPattern\", shape: List[tvm.ir.PrimExpr]):\n        self.__init_handle_by_constructor__(ffi.ShapePattern, pattern, shape)\n\n\n@register_df_node\nclass AttrPattern(DFPattern):\n    \"\"\"Get match an expression with a certain attributes.\n    Currently only supports Op Attributes, not call Attributes.\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The input pattern.\n\n    attrs: tvm.ir.attrs.Attrs\n        The attributes to match.\n    \"\"\"\n\n    def __init__(self, pattern: \"DFPattern\", attrs: tvm.ir.attrs.Attrs):\n        self.__init_handle_by_constructor__(ffi.AttrPattern, pattern, attrs)\n\n\n@register_df_node\nclass DominatorPattern(DFPattern):\n    \"\"\"Match a domination graph.\n\n    Parameters\n    ----------\n    parent: tvm.relay.dataflow_pattern.DFPattern\n        The parent, i.e., the single node which produces something,\n        later aggregated by the child.\n    path: tvm.relay.dataflow_pattern.DFPattern\n        The fuzzy path pattern between parent and child,\n        typically matches elementwise ops.\n    child: tvm.relay.dataflow_pattern.DFPattern\n        The last node in the domination which is the end user\n        for all nodes in the path and the parent.\n    \"\"\"\n\n    def __init__(self, parent: \"DFPattern\", path: \"DFPattern\", child: \"DFPattern\"):\n        self.__init_handle_by_constructor__(ffi.DominatorPattern, parent, path, child)\n\n\nclass DFPatternCallback:\n    \"\"\"A Callback for Pattern Rewriting.\n\n    When rewrite is called on this DFPatternCallback, the backend will find matches for the\n    pattern, call the callback function, and replace the matched expression with whatever\n    the callback returns.\n\n    Users are expect to inherit from this class and provide a \"self.pattern\" to match\n\n    Parameters\n    ----------\n    require_type: bool\n        Whether InferType is required to be run before the callback.\n    rewrite_once: bool\n        If True, run the callback only once.\n    \"\"\"\n\n    def __init__(self, require_type=False, rewrite_once=False):\n        self.pattern = None\n        self.require_type = require_type\n        self.rewrite_once = rewrite_once\n\n    def rewrite(self, expr: Expr) -> Expr:\n        \"\"\"\n        Rewrite expression with this callback\n\n        Parameters\n        ----------\n        expr : tvm.relay.Expr\n            The expression to rewrite.\n\n        Returns\n        -------\n        result : tvm.relay.Expr\n            The Expression with matched subgraphs rewritten by the callbacks.\n        \"\"\"\n        return rewrite(self, expr)\n\n    def callback(self, pre: Expr, post: Expr, node_map: tvm.ir.container.Map) -> Expr:\n        \"\"\"\n        Callback function to use when we found a match to the pattern\n\n        Parameters\n        ----------\n        pre : tvm.relay.Expr\n            The matching expression from the original graph.\n        post : tvm.relay.Expr\n            The matching expression with rewritten inputs\n        node_map : tvm.ir.container.Map[DFPattern, List[Expr]]\n            The map between patterns and matched expressions\n\n        Returns\n        -------\n        result : tvm.relay.Expr\n            The Expression with matched subgraph rewritten by the callback\n        \"\"\"\n        raise \"Unimplemented\"\n\n\nclass _DFPatternCallback(Object):\n    \"\"\"C++ implemenation\"\"\"\n\n    def __init__(self, pattern, callback, require_type, rewrite_once):\n        self.__init_handle_by_constructor__(\n            ffi.DFPatternCallback, pattern, callback, require_type, rewrite_once\n        )\n\n\ndef rewrite(callbacks, expr: Expr, mod: Optional[_ir.IRModule] = None) -> Expr:\n    \"\"\"\n    Rewrite expression with the given callbacks.\n\n    Parameters\n    ----------\n    callbacks: tvm.relay.dataflow_pattern.DFPatternCallback\n        The input callback or list of callbacks.\n    expr : tvm.relay.Expr\n        The expression to rewrite.\n    mod : Optional[tvm.ir.IRModule]\n        The module that associates with the expression.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The Expression with matched subgraphs rewritten by the callbacks.\n    \"\"\"\n    if mod is None:\n        mod = _ir.IRModule()\n    callbacks = [callbacks] if isinstance(callbacks, DFPatternCallback) else callbacks\n    tmp = []\n    for callback in callbacks:\n        assert callback.pattern is not None\n        tmp.append(\n            _DFPatternCallback(\n                callback.pattern, callback.callback, callback.require_type, callback.rewrite_once\n            )\n        )\n\n    return ffi.rewrite(tmp, expr, mod)\n\n\ndef partition(\n    pattern: \"DFPattern\",\n    expr: Expr,\n    attrs: Optional[Dict[str, Object]] = None,\n    check: Callable[[Expr], bool] = lambda x: True,\n) -> Expr:\n    \"\"\"\n    Parition the expression into a series of functions that match the pattern\n\n    Parameters\n    ----------\n    pattern: tvm.relay.dataflow_pattern.DFPattern\n        The pattern to match\n    expr : tvm.relay.Expr\n        The expression to split into functions\n    attrs : Optional[Dict[str, Object]]\n        A dict of attributes to apply to the partitioned function\n    check : Callable[[Expr], bool]\n        A function to perform more complicated checks on the matched expression.\n        Returns true if partitioning should proceed, false otherwise.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The Expression with matched subgraphs replaced by function calls to that subgraph\n    \"\"\"\n    return ffi.partition(pattern, expr, attrs, check)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/dataflow_pattern/_ffi.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"DataFlow Pattern Language FFI bindings.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.dataflow_pattern\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/debug.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay IR namespace containing the IR definition and compiler.\"\"\"\nimport tvm._ffi\n\n# pylint: disable=unused-argument, import-outside-toplevel\ndef _debugger_init(expr, stack):\n    import pdb\n\n    pdb.set_trace()\n\n\n@tvm._ffi.register_func(\"relay.debug\")\ndef _debug(*args):\n    import pdb\n\n    pdb.set_trace()\n\n\n# pylint: disable=unused-argument\n@tvm._ffi.register_func(\"relay.debug_interp\")\ndef _debug_interp(*args):\n    _, _, _, ist = args\n    print(\"Relay Debugger\")\n    print(\"  You can manipulate the expression under evaluation with the name `expr`.\")\n    print(\"  You can manipulate the call stack with the name `stack`.\")\n    print(\"--------------\")\n    print(\"--------------\")\n    _debugger_init(ist.current_expr, ist.stack)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/expr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, invalid-name, unused-import\n\"\"\"The expression nodes of Relay.\"\"\"\nfrom __future__ import absolute_import\nfrom numbers import Number as _Number\n\nimport numpy as _np\nimport tvm._ffi\nfrom tvm._ffi import base as _base\nfrom tvm.runtime import NDArray, ndarray as _nd\nfrom tvm.ir import RelayExpr, GlobalVar, Node\n\nfrom .base import RelayNode\nfrom . import _ffi_api\nfrom . import ty as _ty\n\n# alias relay expr as Expr.\nExpr = RelayExpr\n\n# will be registered afterwards\n_op_make = None\n\n\nclass ExprWithOp(RelayExpr):\n    \"\"\"Basetype of all relay expressions that defines op overloading.\"\"\"\n\n    def astype(self, dtype):\n        \"\"\"Cast the content type of the current data to dtype.\n\n        Parameters\n        ----------\n        dtype : str\n            The target data type.\n\n        Note\n        ----\n        This function only works for TensorType Exprs.\n\n        Returns\n        -------\n        result : tvm.relay.Expr\n            The result expression.\n        \"\"\"\n        return _ffi_api.cast(self, dtype)\n\n    def __neg__(self):\n        return _op_make.negative(self)\n\n    def __lt__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.less(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __gt__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.greater(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __ge__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.greater_equal(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __le__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.less_equal(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __add__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.add(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __radd__(self, other):\n        return self.__add__(other)\n\n    def __sub__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.subtract(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __rsub__(self, other):\n        if isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __mul__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.multiply(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __rmul__(self, other):\n        return self.__mul__(other)\n\n    def __div__(self, other):\n        if isinstance(other, Expr):\n            return _op_make.divide(self, other)\n        elif isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __rdiv__(self, other):\n        if isinstance(other, _Number):\n            raise TypeError('convert \"%s\" with `const` first' % str(other))\n        raise TypeError(\"type %s not supported\" % str(type(other)))\n\n    def __truediv__(self, other):\n        return self.__div__(other)\n\n    def __rtruediv__(self, other):\n        return self.__rdiv__(other)\n\n    def __call__(self, *args):\n        \"\"\"Call the variable (if it represents a function).\n\n        Parameters\n        ----------\n        args: List[relay.Expr]\n            The arguments to the call.\n\n        Returns\n        -------\n        call: Call\n            A call taking the variable as a function.\n        \"\"\"\n        return Call(self, args)\n\n\n@tvm._ffi.register_object(\"relay.Constant\")\nclass Constant(ExprWithOp):\n    \"\"\"A constant expression in Relay.\n\n    Parameters\n    ----------\n    data : tvm.nd.NDArray\n        The data content of the constant expression.\n    \"\"\"\n\n    def __init__(self, data):\n        self.__init_handle_by_constructor__(_ffi_api.Constant, data)\n\n\n@tvm._ffi.register_object(\"relay.Tuple\")\nclass Tuple(ExprWithOp):\n    \"\"\"Tuple expression that groups several fields together.\n\n    Parameters\n    ----------\n    fields : List[tvm.relay.Expr]\n        The fields in the tuple.\n\n    span: Optional[tvm.relay.Span]\n        Span that points to original source code\n    \"\"\"\n\n    def __init__(self, fields, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Tuple, fields, span)\n\n    def __getitem__(self, index):\n        if index >= len(self):\n            raise IndexError(\"Tuple index out of range\")\n        return self.fields[index]\n\n    def __len__(self):\n        return len(self.fields)\n\n    def astype(self, _):\n        raise TypeError(\"astype cannot be used on tuple\")\n\n\n@tvm._ffi.register_object(\"relay.Var\")\nclass Var(ExprWithOp):\n    \"\"\"A local variable in Relay.\n\n    Local variable can be used to declare input\n    arguments to a function, or intermediate variables.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the variable.\n        This name only acts as a hint, and is not used\n        for equality.\n\n    type_annotation: tvm.relay.Type, optional\n        The type annotation on the variable.\n    \"\"\"\n\n    def __init__(self, name_hint, type_annotation=None):\n        self.__init_handle_by_constructor__(_ffi_api.Var, name_hint, type_annotation)\n\n    @property\n    def name_hint(self):\n        \"\"\"Get name hint of the current var.\"\"\"\n        name = str(self.vid.name_hint)\n        return name\n\n\n@tvm._ffi.register_object(\"relay.Call\")\nclass Call(ExprWithOp):\n    \"\"\"Function call node in Relay.\n\n    Call node corresponds the operator application node\n    in computational graph terminology.\n\n    Parameters\n    ----------\n    op: tvm.ir.Op or any tvm.relay.Expr with function type.\n        The operation to be called.\n\n    args: List[tvm.relay.Expr]\n        The arguments to the call.\n\n    attrs: Optional[tvm.Attrs]\n        Attributes to the call, can be None\n\n    type_args: Optional[List[tvm.relay.Type]]\n        The additional type arguments, this is only\n        used in advanced usecase of template functions.\n\n    span: Optional[tvm.relay.Span]\n        Span that points to original source code\n    \"\"\"\n\n    def __init__(self, op, args, attrs=None, type_args=None, span=None):\n        if not type_args:\n            type_args = []\n        self.__init_handle_by_constructor__(_ffi_api.Call, op, args, attrs, type_args, span)\n\n\n@tvm._ffi.register_object(\"relay.Let\")\nclass Let(ExprWithOp):\n    \"\"\"Let variable binding expression.\n\n    Parameters\n    ----------\n    variable: tvm.relay.Var\n        The local variable to be bound.\n\n    value: tvm.relay.Expr\n        The value to be bound.\n\n    body: tvm.relay.Expr\n        The body of the let binding.\n    \"\"\"\n\n    def __init__(self, variable, value, body):\n        self.__init_handle_by_constructor__(_ffi_api.Let, variable, value, body)\n\n\n@tvm._ffi.register_object(\"relay.If\")\nclass If(ExprWithOp):\n    \"\"\"A conditional expression in Relay.\n\n    Parameters\n    ----------\n    cond: tvm.relay.Expr\n        The condition.\n\n    true_branch: tvm.relay.Expr\n        The expression evaluated when condition is true.\n\n    false_branch: tvm.relay.Expr\n        The expression evaluated when condition is false.\n    \"\"\"\n\n    def __init__(self, cond, true_branch, false_branch):\n        self.__init_handle_by_constructor__(_ffi_api.If, cond, true_branch, false_branch)\n\n\n@tvm._ffi.register_object(\"relay.TupleGetItem\")\nclass TupleGetItem(ExprWithOp):\n    \"\"\"Get index-th item from a tuple.\n\n    Parameters\n    ----------\n    tuple_value: tvm.relay.Expr\n        The input tuple expression.\n\n    index: int\n        The index.\n    \"\"\"\n\n    def __init__(self, tuple_value, index):\n        self.__init_handle_by_constructor__(_ffi_api.TupleGetItem, tuple_value, index)\n\n\n@tvm._ffi.register_object(\"relay.RefCreate\")\nclass RefCreate(ExprWithOp):\n    \"\"\"Create a new reference from initial value.\n    Parameters\n    ----------\n    value: tvm.relay.Expr\n       The initial value.\n    \"\"\"\n\n    def __init__(self, value):\n        self.__init_handle_by_constructor__(_ffi_api.RefCreate, value)\n\n\n@tvm._ffi.register_object(\"relay.RefRead\")\nclass RefRead(ExprWithOp):\n    \"\"\"Get the value inside the reference.\n    Parameters\n    ----------\n    ref: tvm.relay.Expr\n         The reference.\n    \"\"\"\n\n    def __init__(self, ref):\n        self.__init_handle_by_constructor__(_ffi_api.RefRead, ref)\n\n\n@tvm._ffi.register_object(\"relay.RefWrite\")\nclass RefWrite(ExprWithOp):\n    \"\"\"\n    Update the value inside the reference.\n    The whole expression will evaluate to an empty tuple.\n    Parameters\n    ----------\n    ref: tvm.relay.Expr\n        The reference.\n    value: tvm.relay.Expr\n        The new value.\n    \"\"\"\n\n    def __init__(self, ref, value):\n        self.__init_handle_by_constructor__(_ffi_api.RefWrite, ref, value)\n\n\nclass TempExpr(ExprWithOp):\n    \"\"\"Baseclass of all TempExpr.\n\n    TempExprs are pass specific expression that can be\n    useful to define intermediate result in the\n    rewriting pass such as layout or type transformation.\n    \"\"\"\n\n    def realize(self):\n        \"\"\"Convert the expression to a normal(non-temp) Expr.\n\n        Returns\n        -------\n        The corresponding normal expression.\n        \"\"\"\n        return _ffi_api.TempExprRealize(self)\n\n\nclass TupleWrapper(object):\n    \"\"\"TupleWrapper.\n\n    This class is a Python wrapper for a Relay tuple of known size.\n    It allows for accessing the fields of the Relay tuple as though\n    it were a Python tuple.\n\n    Parameters\n    ----------\n    tuple_value: tvm.relay.Expr\n        The input tuple\n\n    size: int\n        The size of the tuple.\n    \"\"\"\n\n    def __init__(self, tuple_value, size):\n        self.tuple_value = tuple_value\n        self.size = size\n\n    def astuple(self):\n        \"\"\"Returns the underlying Relay tuple if this wrapper is passed\n        as an argument to an FFI function.\"\"\"\n        return self.tuple_value\n\n    def astext(self):\n        \"\"\"Get the text format of the tuple expression.\n\n        Returns\n        -------\n        text : str\n            The text format of the tuple expression.\n        \"\"\"\n        return self.tuple_value.astext()\n\n    def __getitem__(self, index):\n        if index >= len(self):\n            raise IndexError(\"Tuple index out of range\")\n        return TupleGetItem(self.tuple_value, index)\n\n    def __len__(self):\n        return self.size\n\n    def __repr__(self):\n        return \"TupleWrapper(\" + self.tuple_value.__repr__() + \", \" + str(self.size) + \")\"\n\n    def astype(self, _):\n        raise TypeError(\"astype cannot be used on tuple\")\n\n\ndef var(name_hint, type_annotation=None, shape=None, dtype=\"float32\"):\n    \"\"\"Create a new tvm.relay.Var.\n\n    This is a simple wrapper function that allows specify\n    shape and dtype directly.\n\n    Parameters\n    ----------\n    name_hint: str\n        The name of the variable.\n        This name only acts as a hint, and is not used\n        for equality.\n\n    type_annotation: Optional[tvm.relay.Type, str]\n        The type annotation on the variable.\n        When type_annotation is a str, we will create a scalar variable.\n\n    shape: Optional[List[tvm.Expr]]\n        The shape of the tensor type.\n\n    dtype: str, optional\n        The data type of the tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      # The following 4 lines are equivalent to each other\n      x = tvm.relay.Var(\"x\", tvm.relay.TensorType([1, 2]))\n      x = tvm.relay.var(\"x\", tvm.relay.TensorType([1, 2]))\n      x = tvm.relay.var(\"x\", shape=[1, 2])\n      x = tvm.relay.var(\"x\", shape=[1, 2], dtype=\"float32\")\n\n      # The following 2 lines are equivalent to each other.\n      y = tvm.relay.var(\"x\", \"float32\")\n      y = tvm.relay.var(\"x\", shape=(), dtype=\"float32\")\n    \"\"\"\n    if type_annotation is not None and shape is not None:\n        raise ValueError(\"Can only specify either type_annotation or shape.\")\n    if shape is not None:\n        type_annotation = _ty.TensorType(shape, dtype)\n    elif isinstance(type_annotation, str):\n        type_annotation = _ty.TensorType((), type_annotation)\n    return Var(name_hint, type_annotation)\n\n\ndef const(value, dtype=None):\n    \"\"\"Create a constant value.\n\n    Parameters\n    ----------\n    value: Union[bool, int, float, numpy.ndarray, tvm.nd.NDArray]\n        The constant value.\n\n    dtype: str, optional\n        The data type of the resulting constant.\n\n    Note\n    ----\n    When dtype is None, we use the following rule:\n\n    - int maps to \"int32\"\n    - float maps to \"float32\"\n    - bool maps to \"bool\"\n    - other using the same default rule as numpy.\n    \"\"\"\n    if isinstance(value, (_base.numeric_types, (bool, list))):\n        value = _np.array(value, dtype=dtype)\n\n    if not dtype:\n        # when dtype is None: int maps to \"int32\", float maps to \"float32\"\n        dtype = {_np.dtype(\"int64\"): _np.int32, _np.dtype(\"float64\"): _np.float32}.get(\n            value.dtype, None\n        )\n\n    if isinstance(value, (_np.ndarray, _np.generic)):\n        if dtype is not None:\n            value = value.astype(dtype)\n        value = _nd.array(value)\n\n    if not isinstance(value, _nd.NDArray):\n        raise ValueError(\"value has to be scalar or NDArray\")\n\n    return Constant(value)\n\n\ndef bind(expr, binds):\n    \"\"\"Bind an free variables in expr or function arguments.\n\n    We can bind parameters expr if it is a function.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression.\n\n    binds : Map[tvm.relay.Var, tvm.relay.Expr]\n        The specific bindings.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The expression or function after binding.\n    \"\"\"\n    return _ffi_api.Bind(expr, binds)\n\n\n@tvm._ffi.register_object(\"relay.StorageInfo\")\nclass StorageInfo(Node):\n    \"\"\"StorageInfo\n\n    The static storage information produced by memory planning.\n    Contains the storage ids where expressions are stored, the\n    type of the \"virtual devices\" the expressions are stored on,\n    and the sizes of each storage element.\"\"\"\n\n    def __init__(self, sids, dev_types, sizes):\n        self.__init_handle_by_constructor__(_ffi_api.StorageInfo, sids, dev_types, sizes)\n\n    @property\n    def storage_ids(self):\n        return _ffi_api.StorageInfoStorageIds(self)\n\n    @property\n    def device_types(self):\n        return _ffi_api.StorageInfoDeviceTypes(self)\n\n    @property\n    def storage_sizes(self):\n        return _ffi_api.StorageInfoStorageSizes(self)\n\n    @property\n    def virtual_devices(self):\n        return _ffi_api.StorageInfoVirtualDevices(self)\n\n\n@tvm._ffi.register_object(\"relay.StaticMemoryPlan\")\nclass StaticMemoryPlan(Node):\n    \"\"\"StaticMemoryPlan\n\n    The result of static memory planning.\"\"\"\n\n    def __init__(self, expr_to_storage_info):\n        self.__init_handle_by_constructor__(_ffi_api.StaticMemoryPlan, expr_to_storage_info)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/expr_functor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name\n\"\"\"The expression functor of Relay.\"\"\"\nfrom tvm.ir import Op\n\nfrom .function import Function, FunctionWithFields\nfrom .expr import Call, Let, Var, GlobalVar\nfrom .expr import If, Tuple, TupleGetItem, Constant\nfrom .expr import RefCreate, RefRead, RefWrite\nfrom .adt import Constructor, Match, Clause\n\n\nclass ExprFunctor:\n    \"\"\"\n    An abstract visitor defined over Expr.\n\n    Defines the default dispatch over expressions, and\n    implements memoization.\n    \"\"\"\n\n    def __init__(self):\n        self.memo_map = {}\n\n    # pylint: disable=no-else-return\n    def visit(self, expr):\n        \"\"\"Apply the visitor to an expression.\"\"\"\n        if expr in self.memo_map:\n            return self.memo_map[expr]\n\n        if isinstance(expr, Function):\n            res = self.visit_function(expr)\n        elif isinstance(expr, Call):\n            res = self.visit_call(expr)\n        elif isinstance(expr, Let):\n            res = self.visit_let(expr)\n        elif isinstance(expr, Var):\n            res = self.visit_var(expr)\n        elif isinstance(expr, GlobalVar):\n            res = self.visit_global_var(expr)\n        elif isinstance(expr, If):\n            res = self.visit_if(expr)\n        elif isinstance(expr, Tuple):\n            res = self.visit_tuple(expr)\n        elif isinstance(expr, TupleGetItem):\n            res = self.visit_tuple_getitem(expr)\n        elif isinstance(expr, Constant):\n            res = self.visit_constant(expr)\n        elif isinstance(expr, Op):\n            res = self.visit_op(expr)\n        elif isinstance(expr, RefCreate):\n            res = self.visit_ref_create(expr)\n        elif isinstance(expr, RefRead):\n            res = self.visit_ref_read(expr)\n        elif isinstance(expr, RefWrite):\n            res = self.visit_ref_write(expr)\n        elif isinstance(expr, Constructor):\n            res = self.visit_constructor(expr)\n        elif isinstance(expr, Match):\n            res = self.visit_match(expr)\n        else:\n            raise Exception(\"warning unhandled case: {0}\".format(type(expr)))\n\n        self.memo_map[expr] = res\n\n        return res\n\n    def visit_function(self, _):\n        raise NotImplementedError()\n\n    def visit_let(self, _):\n        raise NotImplementedError()\n\n    def visit_call(self, _):\n        raise NotImplementedError()\n\n    def visit_var(self, _):\n        raise NotImplementedError()\n\n    def visit_type(self, typ):\n        return typ\n\n    def visit_if(self, _):\n        raise NotImplementedError()\n\n    def visit_tuple(self, _):\n        raise NotImplementedError()\n\n    def visit_tuple_getitem(self, _):\n        raise NotImplementedError()\n\n    def visit_global_var(self, _):\n        raise NotImplementedError()\n\n    def visit_op(self, _):\n        raise NotImplementedError()\n\n    def visit_constant(self, _):\n        raise NotImplementedError()\n\n    def visit_ref_create(self, _):\n        raise NotImplementedError()\n\n    def visit_ref_write(self, _):\n        raise NotImplementedError()\n\n    def visit_ref_read(self, _):\n        raise NotImplementedError()\n\n    def visit_constructor(self, _):\n        raise NotImplementedError()\n\n    def visit_match(self, _):\n        raise NotImplementedError()\n\n\nclass ExprVisitor(ExprFunctor):\n    \"\"\"\n    A visitor over Expr.\n\n    The default behavior recursively traverses the AST.\n    \"\"\"\n\n    def visit_tuple(self, tup):\n        for x in tup.fields:\n            self.visit(x)\n\n    def visit_call(self, call):\n        self.visit(call.op)\n        for a in call.args:\n            self.visit(a)\n\n    def visit_var(self, var):\n        pass\n\n    def visit_let(self, let):\n        self.visit(let.var)\n        self.visit(let.value)\n        self.visit(let.body)\n\n    def visit_function(self, fn):\n        for x in fn.params:\n            self.visit(x)\n        self.visit(fn.body)\n\n    def visit_if(self, i):\n        self.visit(i.cond)\n        self.visit(i.true_branch)\n        self.visit(i.false_branch)\n\n    def visit_global_var(self, gv):\n        pass\n\n    def visit_constructor(self, c):\n        pass\n\n    def visit_op(self, op):\n        pass\n\n    def visit_constant(self, const):\n        pass\n\n    def visit_ref_create(self, r):\n        self.visit(r.value)\n\n    def visit_ref_read(self, r):\n        self.visit(r.ref)\n\n    def visit_ref_write(self, r):\n        self.visit(r.ref)\n        self.visit(r.value)\n\n    def visit_tuple_getitem(self, t):\n        self.visit(t.tuple_value)\n\n    def visit_match(self, m):\n        self.visit(m.data)\n        for c in m.clauses:\n            self.visit(c.rhs)\n\n\nclass ExprMutator(ExprFunctor):\n    \"\"\"\n    A functional visitor over Expr.\n\n    The default behavior recursively traverses the AST\n    and reconstructs the AST.\n    \"\"\"\n\n    def visit_function(self, fn):\n        new_params = [self.visit(x) for x in fn.params]\n        new_body = self.visit(fn.body)\n        return FunctionWithFields(\n            fn,\n            list(new_params),\n            new_body,\n        )\n\n    def visit_let(self, let):\n        new_var = self.visit(let.var)\n        new_val = self.visit(let.value)\n        new_body = self.visit(let.body)\n        return Let(new_var, new_val, new_body)\n\n    def visit_call(self, call):\n        new_fn = self.visit(call.op)\n        new_args = [self.visit(arg) for arg in call.args]\n        return Call(new_fn, new_args, call.attrs, call.type_args, call.span)\n\n    def visit_var(self, var):\n        return var\n\n    def visit_global_id(self, global_var):\n        return global_var\n\n    def visit_if(self, ite):\n        return If(self.visit(ite.cond), self.visit(ite.true_branch), self.visit(ite.false_branch))\n\n    def visit_tuple(self, tup):\n        return Tuple([self.visit(field) for field in tup.fields], tup.span)\n\n    def visit_tuple_getitem(self, op):\n        tuple_value = self.visit(op.tuple_value)\n        if not tuple_value.same_as(op.tuple_value):\n            return TupleGetItem(tuple_value, op.index)\n        return op\n\n    def visit_global_var(self, gvar):\n        return gvar\n\n    def visit_op(self, op):\n        return op\n\n    def visit_constant(self, const):\n        return const\n\n    def visit_constructor(self, con):\n        return con\n\n    def visit_match(self, m):\n        return Match(\n            self.visit(m.data),\n            [Clause(c.lhs, self.visit(c.rhs)) for c in m.clauses],\n            complete=m.complete,\n        )\n\n    def visit_ref_create(self, r):\n        return RefCreate(self.visit(r.value))\n\n    def visit_ref_write(self, r):\n        return RefWrite(self.visit(r.ref), self.visit(r.value))\n\n    def visit_ref_read(self, r):\n        return RefRead(self.visit(r.ref))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nFrontends for constructing Relay programs.\n\nContains the model importers currently defined\nfor Relay.\n\"\"\"\nfrom .mxnet import from_mxnet\nfrom .mxnet_qnn_op_utils import quantize_conv_bias_mkldnn_from_var\nfrom .keras import from_keras\nfrom .oneflow import from_oneflow\nfrom .onnx import from_onnx\nfrom .tflite import from_tflite\nfrom .coreml import from_coreml\nfrom .caffe2 import from_caffe2\nfrom .tensorflow import from_tensorflow\nfrom .darknet import from_darknet\nfrom .pytorch import from_pytorch\nfrom .caffe import from_caffe\nfrom .paddlepaddle import from_paddle\nfrom .change_datatype import ChangeDatatype\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/caffe.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-argument, too-many-lines, import-outside-toplevel\n# pylint: disable=no-else-return, no-else-continue\n\"\"\"Caffe frontend.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .common import ExprTable\nfrom .common import infer_shape as _infer_shape\n\n__all__ = [\"from_caffe\"]\n\n\nclass OperatorConverter(object):\n    \"\"\"Operator Converted for converting Caffe ops to Relay ops\"\"\"\n\n    def __init__(self, init_layer_dict, predict_layer, exp_tab):\n        self.init_layer_dict = init_layer_dict\n        self.predict_layer = predict_layer\n        self.exp_tab = exp_tab\n        self.new_bn = {}\n        self.changed_layers = None\n\n        self.convert_map = {\n            \"BatchNorm\": self.convert_batch_norm,\n            \"Concat\": self.convert_concat,\n            \"Convolution\": self.convert_conv,\n            \"Crop\": self.convert_crop,\n            \"Deconvolution\": self.convert_deconv,\n            \"Dropout\": self.convert_dropout,\n            \"Eltwise\": self.convert_eltwise,\n            \"Embed\": self.convert_embed,\n            \"Flatten\": self.convert_flatten,\n            \"InnerProduct\": self.convert_innerproduct,\n            \"Input\": None,\n            \"LRN\": self.convert_lrn,\n            \"Permute\": self.convert_permute,\n            \"Pooling\": self.convert_pooling,\n            \"Power\": self.convert_power,\n            \"PReLU\": self.convert_prelu,\n            \"ReLU\": self.convert_relu,\n            \"Reshape\": self.convert_reshape,\n            \"Scale\": self.convert_scale,\n            \"Sigmoid\": self.convert_sigmoid,\n            \"Slice\": self.convert_slice,\n            \"Softmax\": self.convert_softmax,\n            \"TanH\": self.convert_tanh,\n            \"Reduction\": self.convert_reduction,\n        }\n\n    def convert_flatten(self, op):\n        \"\"\"Convert Flatten layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n\n        flatten_params = op.flatten_param.axis\n        assert flatten_params == 1, \"flatten axis should be 1\"\n        out = _op.nn.batch_flatten(in_expr)\n\n        return out\n\n    def convert_eltwise(self, op):\n        \"\"\"Convert Eltwise layer\"\"\"\n        inputs = op.bottom\n        assert len(inputs) >= 2, \"input tensors length should be larger than 2\"\n\n        # gethering initial 2 input expressions\n        lhs_expr = self.exp_tab.get_expr(inputs[0])\n        rhs_expr = self.exp_tab.get_expr(inputs[1])\n        lhs_shape = _infer_shape(lhs_expr)\n        rhs_shape = _infer_shape(rhs_expr)\n        assert lhs_shape == rhs_shape, \"input tensors shape should be equal\"\n\n        eltwise_params = op.eltwise_param\n        eltwise_type_dict = [\"PROD\", \"SUM\", \"MAX\"]\n        eltwise_type = eltwise_params.operation\n        coeff = list(eltwise_params.coeff)\n\n        if eltwise_type_dict[eltwise_type] == \"PROD\":\n            out = _op.multiply(lhs_expr, rhs_expr)\n            # for rest inputs\n            for i in range(len(inputs) - 2):\n                extra_expr = self.exp_tab.get_expr(inputs[i + 2])\n                assert _infer_shape(out) == _infer_shape(extra_expr)\n                out = _op.multiply(out, extra_expr)\n        elif eltwise_type_dict[eltwise_type] == \"SUM\":\n            if coeff:\n                left_coeff_expr = self.exp_tab.new_const(np.asarray(coeff[0], np.float32))\n                right_coeff_expr = self.exp_tab.new_const(np.asarray(coeff[1], np.float32))\n                lhs_expr_scale = _op.multiply(lhs_expr, left_coeff_expr)\n                rhs_expr_scale = _op.multiply(rhs_expr, right_coeff_expr)\n                out = _op.add(lhs_expr_scale, rhs_expr_scale)\n            else:\n                out = _op.add(lhs_expr, rhs_expr)\n            # for rest inputs\n            for i in range(len(inputs) - 2):\n                extra_expr = self.exp_tab.get_expr(inputs[i + 2])\n                assert _infer_shape(out) == _infer_shape(extra_expr)\n                if coeff:\n                    coeff_expr = self.exp_tab.new_const(np.asarray(coeff[i + 2], np.float32))\n                    extra_expr_scale = _op.multiply(extra_expr, coeff_expr)\n                    out = _op.add(out, extra_expr_scale)\n                else:\n                    out = _op.add(out, extra_expr)\n        elif eltwise_type_dict[eltwise_type] == \"MAX\":\n            out = _op.maximum(lhs_expr, rhs_expr)\n            # for rest inputs\n            for i in range(len(inputs) - 2):\n                extra_expr = self.exp_tab.get_expr(inputs[i + 2])\n                assert _infer_shape(out) == _infer_shape(extra_expr)\n                out = _op.maximum(out, extra_expr)\n        else:\n            raise tvm.error.OpNotImplemented(\n                \"eltwise_type {} is not supported for frontend Caffe.\".format(eltwise_type)\n            )\n\n        return out\n\n    def _parse_conv_params(self, op):\n        \"\"\"Parse the parameters of Convolution and Deconvolution layer\"\"\"\n        nonzone = lambda val, pos, dflt: val[pos] if pos < len(val) else dflt\n\n        conv_params = op.convolution_param\n\n        params = dict()\n        # parse kernel size\n        if conv_params.kernel_h > 0 or conv_params.kernel_w > 0:\n            params[\"kernel_size\"] = (conv_params.kernel_h, conv_params.kernel_w)\n        else:\n            ksize_h = nonzone(conv_params.kernel_size, 0, 1)\n            ksize_w = nonzone(conv_params.kernel_size, 1, ksize_h)\n            params[\"kernel_size\"] = (ksize_h, ksize_w)\n\n        # parse padding size\n        if conv_params.pad_h > 0 or conv_params.pad_w > 0:\n            params[\"padding\"] = (conv_params.pad_h, conv_params.pad_w)\n        else:\n            pad_h = nonzone(conv_params.pad, 0, 0)\n            pad_w = nonzone(conv_params.pad, 1, pad_h)\n            params[\"padding\"] = (pad_h, pad_w)\n\n        # parse stride size\n        if conv_params.stride_h > 0 or conv_params.stride_w > 0:\n            params[\"strides\"] = (conv_params.stride_h, conv_params.stride_w)\n        else:\n            stride_h = nonzone(conv_params.stride, 0, 1)\n            stride_w = nonzone(conv_params.stride, 1, stride_h)\n            params[\"strides\"] = (stride_h, stride_w)\n\n        # parse dilation size\n        if hasattr(conv_params, \"dilation\") and len(conv_params.dilation) > 0:\n            dilation = \" \".join(str(d) for d in conv_params.dilation)\n            dilation = tuple(map(int, dilation.split(\" \")))\n            params[\"dilation\"] = dilation\n            if len(dilation) == 1:\n                params[\"dilation\"] = (dilation[0], dilation[0])\n\n        params[\"kernel_layout\"] = \"OIHW\"\n        params[\"data_layout\"] = \"NCHW\"\n        params[\"groups\"] = conv_params.group\n        params[\"channels\"] = conv_params.num_output\n        return params\n\n    def convert_batch_norm(self, op):\n        \"\"\"Convert BatchNorm layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        n, c, h, w = _infer_shape(in_expr)\n\n        if op.name in self.new_bn:\n            mean, var, eps, gamma, beta = self.new_bn[op.name]\n            mean_expr = self.exp_tab.new_const(mean, dtype=\"float32\")\n            var_expr = self.exp_tab.new_const(var, dtype=\"float32\")\n            gamma_expr = self.exp_tab.new_const(gamma, dtype=\"float32\")\n            beta_expr = self.exp_tab.new_const(beta, dtype=\"float32\")\n            out = _op.nn.batch_norm(\n                in_expr, gamma_expr, beta_expr, mean_expr, var_expr, epsilon=eps, scale=True\n            )\n\n        else:\n            weight_bias_blobs = self.init_layer_dict[op.name].blobs\n            mean = np.asarray(weight_bias_blobs[0].data, np.float32)\n            var = np.asarray(weight_bias_blobs[1].data, np.float32)\n            if len(weight_bias_blobs) == 2:\n                mean = np.repeat(mean, h * w).reshape((c, h, w))\n                mean = np.expand_dims(mean, 0).repeat(n, axis=0)\n                mean_expr = self.exp_tab.new_const(mean, dtype=\"float32\")\n\n                var = np.repeat(var, h * w).reshape((c, h, w))\n                var = np.expand_dims(var, 0).repeat(n, axis=0)\n                var_expr = self.exp_tab.new_const(var, dtype=\"float32\")\n\n                tmp_out = _op.multiply(in_expr, mean_expr)\n                out = _op.add(tmp_out, var_expr)\n\n                return out\n            else:\n                scale = np.asarray(weight_bias_blobs[2].data, np.float32)\n                if scale:\n                    scale = 1 / scale\n            mean_expr = self.exp_tab.new_const(mean * scale, dtype=\"float32\")\n            var_expr = self.exp_tab.new_const(var * scale, dtype=\"float32\")\n\n            # caffe bn layer not support scale\n            gamma_expr = self.exp_tab.new_const(\n                np.ones(mean.shape, dtype=np.float32), dtype=\"float32\"\n            )\n            beta_expr = self.exp_tab.new_const(\n                np.zeros(mean.shape, dtype=np.float32), dtype=\"float32\"\n            )\n\n            bn_params = op.batch_norm_param.eps\n            out = _op.nn.batch_norm(\n                in_expr, gamma_expr, beta_expr, mean_expr, var_expr, epsilon=bn_params, scale=False\n            )\n\n        return out[0]\n\n    def convert_scale(self, op):\n        \"\"\"Convert Scale layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        weight_bias_blobs = self.init_layer_dict[op.name].blobs\n\n        params = dict()\n        params[\"bias\"] = op.scale_param.bias_term\n        params[\"axis\"] = op.scale_param.axis\n\n        gamma = np.asarray(weight_bias_blobs[0].data, np.float32)\n        gamma_expr = self.exp_tab.new_const(gamma, dtype=\"float32\")\n        if params[\"bias\"]:\n            beta = np.asarray(weight_bias_blobs[1].data, np.float32)\n            beta_expr = self.exp_tab.new_const(beta, dtype=\"float32\")\n        else:\n            beta_expr = self.exp_tab.new_const(\n                np.zeros(gamma.shape, dtype=np.float32), dtype=\"float32\"\n            )\n\n        _, c, _, _ = _infer_shape(in_expr)\n        gamma_expr = _op.reshape(gamma_expr, newshape=(1, c, 1, 1))\n        beta_expr = _op.reshape(beta_expr, newshape=(1, c, 1, 1))\n        out = _op.multiply(in_expr, gamma_expr)\n        out = _op.add(out, beta_expr)\n\n        return out\n\n    def convert_concat(self, op):\n        \"\"\"Convert Concat layer\"\"\"\n        inputs = op.bottom\n        in_expr = (self.exp_tab.get_expr(inputs[i]) for i in range(len(inputs)))\n\n        c_params = dict()\n        c_params[\"axis\"] = op.concat_param.axis\n        out = _op.concatenate(in_expr, axis=c_params[\"axis\"])\n\n        return out\n\n    def convert_reshape(self, op):\n        \"\"\"Convert Reshape layer\"\"\"\n        inputs = op.bottom\n        input_name = inputs[0]\n\n        reshape_param = op.reshape_param\n        dims = list(reshape_param.shape.dim)\n\n        in_expr = self.exp_tab.get_expr(input_name)\n        input_shape = list(_infer_shape(in_expr))\n\n        start_axis = int(reshape_param.axis)\n        if start_axis < 0:\n            start_axis = len(input_shape) + start_axis + 1\n        num_axes = int(reshape_param.num_axes)\n        end_axis = len(input_shape)\n        if num_axes != -1:\n            end_axis = start_axis + num_axes\n\n        left_shape = input_shape[:start_axis]\n        if end_axis == len(input_shape):\n            center_shape = input_shape[start_axis:]\n            right_shape = []\n        else:\n            center_shape = input_shape[start_axis:end_axis]\n            right_shape = input_shape[end_axis:]\n\n        for idx, dim in enumerate(dims):\n            if dim == 0:\n                dims[idx] = center_shape[idx]\n\n        tmp = np.random.rand(*center_shape)\n        tmp = np.reshape(tmp, dims)\n        center_shape = list(tmp.shape)\n\n        newshape = left_shape + center_shape + right_shape\n\n        out = _op.reshape(in_expr, newshape=newshape)\n        return out\n\n    def convert_softmax(self, op):\n        \"\"\"Convert Softmax layer\"\"\"\n        inputs = op.bottom\n        assert len(inputs) == 1, \"input tensors length should be 1\"\n\n        input_name = inputs[0]\n        in_expr = self.exp_tab.get_expr(input_name)\n\n        softmax_param = op.softmax_param\n        parmas = {\"axis\": softmax_param.axis}\n\n        out = _op.nn.softmax(in_expr, **parmas)\n\n        return out\n\n    def convert_conv(self, op):\n        \"\"\"Convert Convolution layer\"\"\"\n        params = self._parse_conv_params(op)\n        weight_bias_blobs = self.init_layer_dict[op.name].blobs\n        conv_params = op.convolution_param\n        inputs = op.bottom\n        # process weight and bias blobs\n        weight, bias = None, None\n        if len(weight_bias_blobs) > 1:\n            weight = weight_bias_blobs[0]\n            bias = weight_bias_blobs[1]\n        else:\n            weight = weight_bias_blobs[0]\n        if weight:\n            kh, kw = params[\"kernel_size\"]\n            weight_shape = [conv_params.num_output, -1, kh, kw]\n            weight_value = np.asarray(weight.data, np.float32)\n            weight_value = np.reshape(weight_value, weight_shape)\n        else:\n            raise Exception(\"No weight value of layer {} in caffemodel\".format(op.name))\n\n        weight_expr = self.exp_tab.new_const(weight_value, dtype=\"float32\")\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        out = _op.nn.conv2d(data=in_expr, weight=weight_expr, **params)\n        if bias:\n            bias_value = np.asarray(bias.data, np.float32)\n            bias_expr = self.exp_tab.new_const(bias_value, dtype=\"float32\")\n            out = _op.nn.bias_add(out, bias_expr)\n        return out\n\n    def convert_pooling(self, op):\n        \"\"\"Convert Pooling layer\"\"\"\n        inputs = op.bottom\n        input_name = inputs[0]\n\n        pool_params = op.pooling_param\n        pool_type_dict = [\"MAX\", \"AVE\", \"STOCHASTIC\"]\n\n        params = dict()\n        # parse pool type: 0: MAX, 1: AVE, 2: STOCHASTIC\n        pool_type = pool_params.pool\n        # parse kernel size\n        if pool_params.kernel_h > 0 or pool_params.kernel_w > 0:\n            params[\"pool_size\"] = (pool_params.kernel_h, pool_params.kernel_w)\n        else:\n            params[\"pool_size\"] = (pool_params.kernel_size, pool_params.kernel_size)\n\n        # parse padding size\n        if pool_params.pad_h > 0 or pool_params.pad_w > 0:\n            params[\"padding\"] = (pool_params.pad_h, pool_params.pad_w)\n        else:\n            params[\"padding\"] = (pool_params.pad, pool_params.pad)\n\n        # parse stride size\n        if pool_params.stride_h > 0 or pool_params.stride_w > 0:\n            params[\"strides\"] = (pool_params.stride_h, pool_params.stride_w)\n        else:\n            params[\"strides\"] = (pool_params.stride, pool_params.stride)\n\n        params[\"ceil_mode\"] = True\n        if hasattr(pool_params, \"round_mode\"):\n            params[\"ceil_mode\"] = pool_params.round_mode == \"CEIL\"\n\n        in_expr = self.exp_tab.get_expr(input_name)\n\n        if pool_type_dict[pool_type] == \"MAX\":\n            if pool_params.global_pooling:\n                out = _op.nn.global_max_pool2d(in_expr)\n            else:\n                if len(op.top) == 1:\n                    out = _op.nn.max_pool2d(in_expr, **params)\n                elif len(op.top) == 2:\n                    out1 = _op.nn.max_pool2d_with_argmax(in_expr, **params)\n                    out2 = _op.vision.max_pool2d_location(in_expr, **params)\n                    return _expr.Tuple((out1, out2))\n\n        elif pool_type_dict[pool_type] == \"AVE\":  # AVE\n            if pool_params.global_pooling:\n                out = _op.nn.global_avg_pool2d(in_expr)\n            else:\n                params[\"count_include_pad\"] = True\n                out = _op.nn.avg_pool2d(in_expr, **params)\n        else:\n            raise tvm.error.OpNotImplemented(\n                \"Operator {} is not supported for frontend Caffe.\".format(\n                    pool_type_dict[pool_type] + \" pool\"\n                )\n            )\n\n        return out\n\n    def convert_lrn(self, op):\n        \"\"\"Convert LRN layer\"\"\"\n        inputs = op.bottom\n        input_name = inputs[0]\n\n        params = dict()\n        lrn_params = op.lrn_param\n        params[\"size\"] = lrn_params.local_size\n        params[\"bias\"] = lrn_params.k\n        params[\"alpha\"] = lrn_params.alpha\n        params[\"beta\"] = lrn_params.beta\n\n        in_expr = self.exp_tab.get_expr(input_name)\n        out = _op.nn.lrn(in_expr, **params)\n        return out\n\n    def convert_innerproduct(self, op):\n        \"\"\"Convert InnerProduct layer\"\"\"\n        inputs = op.bottom\n        weight_bias_blobs = self.init_layer_dict[op.name].blobs\n        dense_params = op.inner_product_param\n\n        params = dict()\n        params[\"num_output\"] = dense_params.num_output\n        params[\"bias\"] = dense_params.bias_term\n        params[\"axis\"] = dense_params.axis\n        if params[\"axis\"] != 1:\n            raise Exception(\"Only support 2D InnerProduct\")\n\n        # process weight and bias blobs\n        weight, bias = None, None\n        if params[\"bias\"]:\n            weight = weight_bias_blobs[0]\n            bias = weight_bias_blobs[1]\n        else:\n            weight = weight_bias_blobs[0]\n\n        if weight:\n            weight_value = np.asarray(weight.data, np.float32)\n            weight_value = np.reshape(weight_value, (params[\"num_output\"], -1))\n            weight_shape = weight_value.shape\n        else:\n            raise Exception(\"No weight value of layer {} in caffemodel\".format(op.name))\n\n        weight_expr = self.exp_tab.new_const(weight_value, dtype=\"float32\")\n\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        in_reshape = _op.reshape(data=in_expr, newshape=(-1, weight_shape[-1]))\n\n        out = _op.nn.dense(data=in_reshape, weight=weight_expr)\n\n        if bias:\n            bias_value = np.asarray(bias.data, np.float32)\n            bias_expr = self.exp_tab.new_const(bias_value, dtype=\"float32\")\n            out = _op.nn.bias_add(out, bias_expr, axis=params[\"axis\"])\n        return out\n\n    def convert_dropout(self, op):\n        \"\"\"Convert Dropout layer\"\"\"\n        inputs = op.bottom\n        input_name = inputs[0]\n\n        params = dict()\n        dropout_params = op.dropout_param\n\n        params[\"rate\"] = dropout_params.dropout_ratio\n\n        in_expr = self.exp_tab.get_expr(input_name)\n        out = _op.nn.dropout(in_expr, **params)\n        return out\n\n    def convert_relu(self, op):\n        \"\"\"Convert ReLU layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        negative_slope = op.relu_param.negative_slope\n        if negative_slope:\n            out = _op.nn.leaky_relu(in_expr, negative_slope)\n            return out\n\n        out = _op.nn.relu(in_expr)\n        return out\n\n    def convert_prelu(self, op):\n        \"\"\"Convert PReLU layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n\n        alpha = self.init_layer_dict[op.name].blobs[0].data\n        alpha = np.asarray(alpha, np.float32)\n        alpha = self.exp_tab.new_const(alpha, dtype=\"float32\")\n        axis = 1\n        out = _op.nn.prelu(in_expr, alpha, axis=axis)\n        return out\n\n    def convert_deconv(self, op):\n        \"\"\"Convert Deconvolution layer\"\"\"\n        params = self._parse_conv_params(op)\n        weight_bias_blobs = self.init_layer_dict[op.name].blobs\n        conv_params = op.convolution_param\n        inputs = op.bottom\n\n        # process weight and bias blobs\n        weight, bias = None, None\n        if len(weight_bias_blobs) > 1:\n            weight = weight_bias_blobs[0]\n            bias = weight_bias_blobs[1]\n        else:\n            weight = weight_bias_blobs[0]\n        if weight:\n            kh, kw = params[\"kernel_size\"]\n            weight_shape = [-1, conv_params.num_output, kh, kw]\n            if not weight.data:\n                if conv_params.weight_filler:\n                    _filler = conv_params.weight_filler.value\n                    weight_value = np.full(weight.shape.dim, _filler, np.float32)\n                else:\n                    raise tvm.error.OpAttributeInvalid(\"At least weight_filler must be given\")\n            else:\n                weight_value = np.asarray(weight.data, np.float32)\n            weight_value = np.reshape(weight_value, weight_shape)\n\n            # weight shape is in relay's IOHW format rn, we need it to be OIHW\n            weight_value = np.transpose(weight_value, [1, 0, 2, 3])\n        else:\n            raise tvm.error.OpAttributeRequired(\n                \"No weight value of layer {} in caffemodel\".format(op.name)\n            )\n\n        weight_expr = self.exp_tab.new_const(weight_value, dtype=\"float32\")\n        in_expr = self.exp_tab.get_expr(inputs[0])\n\n        groups = params[\"groups\"]\n        channels = params[\"channels\"]\n\n        if bias:\n            bias_value = np.asarray(bias.data, np.float32)\n            bias_expr = self.exp_tab.new_const(bias_value, dtype=\"float32\")\n\n        if groups > channels:\n            raise tvm.error.OpAttributeInvalid(\n                \"Groups cannot be larger than the number of input channels\"\n            )\n\n        if groups == channels:\n            inputs_expr = _op.split(in_expr, groups, axis=1)\n            # changing split axis to 0, according to PR #9336\n            weights_expr = _op.split(weight_expr, groups, axis=0)\n            # Preventing to create Concat layer with too many tensors(> 16)\n            q = groups >> 4\n            r = groups % 16\n\n            params[\"groups\"] = 1\n            params[\"channels\"] = 1\n            out = []\n            for lc in range(q):\n                _outputs = []\n                _inputs = [inputs_expr[i] for i in range(lc << 4, (lc << 4) + 16)]\n                _weights = [weights_expr[i] for i in range(lc << 4, (lc << 4) + 16)]\n                for (i, w) in zip(_inputs, _weights):\n                    _out = _op.nn.conv2d_transpose(data=i, weight=w, **params)\n                    if bias:\n                        _out = _op.nn.bias_add(_out, bias_expr)\n                    _outputs.append(_out)\n                out.append(_op.concatenate(_outputs, axis=1))\n            if r != 0:\n                _outputs = []\n                _inputs = [inputs_expr[i] for i in range(groups - r, groups)]\n                _weights = [weights_expr[i] for i in range(groups - r, groups)]\n                for (i, w) in zip(_inputs, _weights):\n                    _out = _op.nn.conv2d_transpose(data=i, weight=w, **params)\n                    if bias:\n                        _out = _op.nn.bias_add(_out, bias_expr)\n                    _outputs.append(_out)\n                out.append(_op.concatenate(_outputs, axis=1))\n            out = _op.concatenate(out, axis=1)\n        elif groups == 1:\n            out = _op.nn.conv2d_transpose(data=in_expr, weight=weight_expr, **params)\n            if bias:\n                out = _op.nn.bias_add(out, bias_expr)\n        else:\n            raise tvm.error.OpAttributeInvalid(\"Unable to handle.\")\n        return out\n\n    def convert_slice(self, op):\n        \"\"\"Convert Slice layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n\n        output_num = len(op.top)\n\n        slice_params = op.slice_param\n        axis = int(slice_params.axis)\n        indices_or_sections = list([int(s) for s in slice_params.slice_point])\n        if len(indices_or_sections) == 0:\n            indices_or_sections = output_num\n        else:\n            indices_or_sections = sorted(indices_or_sections)\n\n        out = _op.split(in_expr, indices_or_sections=indices_or_sections, axis=axis)\n        return out\n\n    def convert_sigmoid(self, op):\n        \"\"\"Convert Sigmoid layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        out = _op.sigmoid(in_expr)\n        return out\n\n    def convert_tanh(self, op):\n        \"\"\"Convert TanH layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        out = _op.tanh(in_expr)\n        return out\n\n    def convert_reduction(self, op):\n        \"\"\"Convert Reduction layer\"\"\"\n        reduction_dic = [\"NOP\", \"SUM\", \"ASUM\", \"SUMSQ\", \"MEAN\"]\n\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        method = op.reduction_param.operation\n        axis = op.reduction_param.axis\n        coeff = op.reduction_param.coeff\n        coeff_expr = self.exp_tab.new_const(np.asarray(coeff, np.float32))\n        num_axes = len(_infer_shape(in_expr))\n\n        # Currently, only reduction along ALL \"tail\" axes is supported in Caffe;\n        # reduction of axis M through N, where N < num_axes - 1, is unsupported.\n        if 0 < axis < (num_axes - 1):\n            for _axis in reversed(range(axis + 1, num_axes)):\n                in_expr = _op.sum(in_expr, axis=_axis)\n            in_expr = _op.squeeze(in_expr)\n\n        if reduction_dic[method] == \"SUM\":\n            out = _op.sum(in_expr, axis=axis)\n        elif reduction_dic[method] == \"MEAN\":\n            out = _op.mean(in_expr, axis=axis)\n        elif reduction_dic[method] == \"ASUM\":\n            in_expr = _op.abs(in_expr)\n            out = _op.sum(in_expr, axis=axis)\n        elif reduction_dic[method] == \"SUMSQ\":\n            in_expr = _op.multiply(in_expr, in_expr)\n            out = _op.sum(in_expr, axis=axis)\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                \"reduction method:{} is invalid in Caffe frontend.\".format(method)\n            )\n\n        if float(coeff) != 1.0:\n            out = _op.multiply(out, coeff_expr)\n        return out\n\n    def convert_crop(self, op):\n        \"\"\"Convert Crop layer\"\"\"\n        inputs = op.bottom\n        assert len(inputs) == 2, \"Need two inputs of Crop layer\"\n        in_expr_a = self.exp_tab.get_expr(inputs[0])\n        in_expr_b = self.exp_tab.get_expr(inputs[1])\n\n        # parse crop params\n        crop_params = op.crop_param\n        axis = int(getattr(crop_params, \"axis\", 2))\n        offset = list(getattr(crop_params, \"offset\", 0))\n\n        # expand offset to (offset1, offset2, ...)\n        in_a_shape = _infer_shape(in_expr_a)\n        num_to_crop = len(in_a_shape) - axis\n        if not offset:\n            offset = [0] * num_to_crop\n        if len(offset) == 1:\n            offset = offset * num_to_crop\n        elif len(offset) != num_to_crop:\n            raise Exception(\"No matching the number between axis and offset!\")\n\n        slice_end = in_a_shape\n        slice_start = [0] * len(in_a_shape)\n        for i in range(num_to_crop):\n            slice_start[i + axis] = offset[i]\n\n        to_crop_axis = list(range(len(in_a_shape)))\n        to_crop_axis = to_crop_axis[axis:]\n\n        # secondly, crop in_expr_a by in_expr_b\n        in_expr_a_stride = _op.strided_slice(in_expr_a, slice_start, slice_end)\n        out = _op.slice_like(in_expr_a_stride, in_expr_b, axes=to_crop_axis)\n        return out\n\n    def convert_permute(self, op):\n        \"\"\"Convert Permute layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n\n        # parse permute params\n        permute_param = op.permute_param\n        axes = list(getattr(permute_param, \"order\", 0))\n        out = _op.transpose(in_expr, axes)\n        return out\n\n    def convert_embed(self, op):\n        \"\"\"Convert Embed layer\"\"\"\n        inputs = op.bottom\n        embed_param = op.embed_param\n        num_output = embed_param.num_output\n        input_dim = embed_param.input_dim\n        bias_term = embed_param.bias_term\n        weight_bias_blobs = self.init_layer_dict[op.name].blobs\n        weight, bias = None, None\n        if bias_term:\n            weight = weight_bias_blobs[0]\n            bias = weight_bias_blobs[1]\n            assert weight and bias\n        else:\n            weight = weight_bias_blobs[0]\n            assert weight\n        weight_value = np.asarray(weight.data, np.float32)\n        weight_value = np.reshape(weight_value, [input_dim, num_output])\n        weight_expr = self.exp_tab.new_const(weight_value, dtype=\"float32\")\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        input_shape = _infer_shape(in_expr)\n        input_count = 1\n        for dim in input_shape:\n            input_count *= dim\n\n        index = _op.cast(in_expr, \"int32\")\n        out = _op.take(weight_expr, index, axis=0)\n\n        if bias_term:\n            bias_value = np.asarray(bias.data, np.float32)\n            bias_expr = self.exp_tab.new_const(bias_value, dtype=\"float32\")\n            out = _op.reshape(out, [input_count, num_output])\n            out = _op.add(out, bias_expr)\n\n        out_shape = list(input_shape)\n        out_shape.append(num_output)\n        out = _op.reshape(out, out_shape)\n\n        return out\n\n    def convert_power(self, op):\n        \"\"\"Convert Power layer\"\"\"\n        inputs = op.bottom\n        in_expr = self.exp_tab.get_expr(inputs[0])\n        power = _expr.const(op.power_param.power)\n        scale = _expr.const(op.power_param.scale)\n        shift = _expr.const(op.power_param.shift)\n\n        out = _op.multiply(in_expr, scale)\n        out = _op.add(out, shift)\n        out = _op.power(out, power)\n        return out\n\n    def check_unsupported_ops(self):\n        \"\"\"Check unsupported Caffe ops in our converter.\"\"\"\n        unsupported_ops_set = set()\n\n        include_layer = dict()\n        for pl in self.predict_layer:\n            if pl.type not in include_layer:\n                include_layer[pl.type] = 1\n            else:\n                include_layer[pl.type] = include_layer[pl.type] + 1\n\n        for pl in self.predict_layer:\n            op_name = pl.type\n            if op_name not in self.convert_map:\n                unsupported_ops_set.add(op_name)\n\n        if unsupported_ops_set:\n            msg = \"The following operators are not supported in frontend \" \"Caffe: {}\"\n            ops = str(list(unsupported_ops_set)).strip(\"[,]\")\n            raise tvm.error.OpNotImplemented(msg.format(ops))\n\n    def fuse_op(self, layers):\n        \"\"\"Fusing the BatchNorm and Scale layer\"\"\"\n        bn, scale = layers[\"bn\"], layers[\"scale\"]\n\n        # bn params\n        bn_weight_bias_blobs = self.init_layer_dict[bn.name].blobs\n        bn_scale = np.asarray(bn_weight_bias_blobs[2].data, np.float32)\n        if bn_scale:\n            bn_scale = 1 / bn_scale\n        bn_mean = np.asarray(bn_weight_bias_blobs[0].data, np.float32) * bn_scale\n        bn_var = np.asarray(bn_weight_bias_blobs[1].data, np.float32) * bn_scale\n        bn_eps = bn.batch_norm_param.eps\n\n        # scale params\n        scale_weight_bias_blobs = self.init_layer_dict[scale.name].blobs\n        scale_gamma = np.asarray(scale_weight_bias_blobs[0].data, np.float32)\n        scale_bias = scale.scale_param.bias_term\n        if scale_bias:\n            scale_beta = np.asarray(scale_weight_bias_blobs[1].data, np.float32)\n        else:\n            scale_beta = np.zeros(scale_gamma.shape, dtype=np.float32)\n\n        # new params\n        self.new_bn[bn.name] = [bn_mean, bn_var, bn_eps, scale_gamma, scale_beta]\n        return bn\n\n    def op_fuse(self):\n        \"\"\"fuse bn and scale\"\"\"\n        new_layers = []\n        temp_layers = {}\n        changed_layers = {}\n\n        for index, pl in enumerate(self.predict_layer):\n            op_type = pl.type\n            if op_type == \"Input\":\n                new_layers.append(pl)\n                continue\n            elif op_type == \"BatchNorm\":\n                if (index != len(self.predict_layer) - 1) and (\n                    self.predict_layer[index + 1].type == \"Scale\"\n                ):\n                    temp_layers[\"bn\"] = pl\n                    continue\n                else:\n                    new_layers.append(pl)\n                    temp_layers.clear()\n            elif op_type == \"Scale\":\n                if self.predict_layer[index - 1].type == \"BatchNorm\":\n                    temp_layers[\"scale\"] = pl\n                else:\n                    new_layers.append(pl)\n                    temp_layers.clear()\n            else:\n                temp_layers.clear()\n\n            if len(temp_layers) == 2:\n                layer = self.fuse_op(temp_layers)\n                new_layers.append(layer)\n                changed_layers[temp_layers[\"scale\"].name] = temp_layers[\"bn\"].name\n\n            for idx, plt in enumerate(pl.bottom):\n                if plt in changed_layers:\n                    pl.bottom[idx] = changed_layers[plt]\n\n            if op_type not in [\"BatchNorm\", \"Scale\"]:\n                new_layers.append(pl)\n\n        self.predict_layer = new_layers\n        self.changed_layers = changed_layers\n\n    def convert_op_to_relay(self):\n        \"\"\"Convert Caffe ops to relay ops\"\"\"\n        for pl in self.predict_layer:\n            op_type = pl.type\n            if op_type == \"Input\":\n                continue\n            output_tensors = pl.top\n\n            ret = self.convert_map[op_type](pl)\n\n            if len(output_tensors) == 1:\n                self.exp_tab.set_expr(output_tensors[0], ret)\n            else:\n                for idx, output_tensor in enumerate(output_tensors):\n                    self.exp_tab.set_expr(output_tensor, ret[idx])\n\n\ndef _rebuild_layers(predict_layer):\n    \"\"\"Rebuild caffe layer. If the caffe net include in-place layers, repalce its top\n    with its name and update the bottom of other layer that is related to it.\n    \"\"\"\n    # dict of input name that will be changed to new name\n    changed_top_dict = dict()\n\n    for pl in predict_layer:\n        if pl.type == \"Input\":\n            continue\n        # if current layer has single input and output and input equals to output\n        # it means that the layer does \"in-place\"\n        if len(pl.top) == 1 and len(pl.bottom) == 1:\n            if pl.top[0] == pl.bottom[0]:\n                # change current layer's input firstly\n                if pl.bottom[0] in changed_top_dict:\n                    pl.bottom[0] = changed_top_dict[pl.bottom[0]]\n                # update \"change\" dict\n                changed_top_dict[pl.top[0]] = pl.name\n                # change current layer's output to its name\n                pl.top[0] = pl.name\n            else:\n                if pl.bottom[0] in changed_top_dict:\n                    pl.bottom[0] = changed_top_dict[pl.bottom[0]]\n        # if the layer does not\n        else:\n            for index, plt in enumerate(pl.bottom):\n                if plt in changed_top_dict:\n                    pl.bottom[index] = changed_top_dict[plt]\n\n\ndef _get_inputs_outputs(predict_layer):\n    \"\"\"Obtain Caffe model's inputs and outpus\"\"\"\n    # model inputs / outputs\n    model_inputs = list()\n    model_outputs = list()\n\n    # The bottoms of every layer can not be as outputs\n    not_outputs = set()\n    for pl in predict_layer:\n        if pl.type == \"Input\":\n            assert len(pl.top) == 1, \"The number of Input layer's output is more than 1.\"\n            model_inputs.append(pl.top[0])\n        for i in pl.bottom:\n            not_outputs.add(i)\n\n    for pl in predict_layer:\n        if len(pl.bottom) > 0:\n            for t in pl.top:\n                if t not in not_outputs:\n                    model_outputs.append(t)\n    return model_inputs, model_outputs\n\n\ndef from_caffe(init_net, predict_net, shape_dict, dtype_dict):\n    \"\"\"Convert from caffe model into compatible relay Function.\n\n    Parameters\n    ----------\n    init_net : caffe_pb2.NetParameter\n        caffemodel\n    predict_net : caffe_pb2.NetParameter\n        caffe prototxt\n    shape_dict : dict of str to int list/tuple\n        Input shapes of the model.\n    dtype_dict : dict of str to str\n        Input types of the model.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation.\n\n    params : dict of str to tvm.NDArray\n        The parameter dict to be used by relay\n    \"\"\"\n    old_caffe = False\n    if len(predict_net.input) != 0:  # old caffe version\n        old_caffe = True\n        model_inputs = list(predict_net.input)\n\n    predict_layer = predict_net.layer\n\n    # replace layer's top with its name and update other layers'bottoms\n    _rebuild_layers(predict_layer)\n    # obtain inputs and outputs of Net\n    if old_caffe:\n        _, model_outputs = _get_inputs_outputs(predict_layer)\n    else:\n        model_inputs, model_outputs = _get_inputs_outputs(predict_layer)\n\n    exp_tab = ExprTable()\n    for in_name in model_inputs:\n        shape = shape_dict[in_name] if in_name in shape_dict else None\n        dtype = dtype_dict[in_name] if in_name in dtype_dict else \"float32\"\n        exp_tab.set_expr(in_name, _expr.var(in_name, shape=shape, dtype=dtype))\n    if list(init_net.layer):\n        init_layer = init_net.layer\n    else:\n        init_layer = init_net.layers\n    init_layer_dict = {il.name: il for il in init_layer}\n    # op code in model\n    op_converter = OperatorConverter(init_layer_dict, predict_layer, exp_tab)\n    op_converter.check_unsupported_ops()\n    op_converter.op_fuse()\n    op_converter.convert_op_to_relay()\n\n    # params and outputs\n    params = {k: _nd.array(np.array(v)) for k, v in exp_tab.params.items()}\n    outputs = list()\n    for n in model_outputs:\n        if n in op_converter.changed_layers:\n            n = op_converter.changed_layers[n]\n        outputs.append(exp_tab.get_expr(n))\n    outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n    func = _function.Function(analysis.free_vars(outputs), outputs)\n    mod = IRModule.from_expr(func)\n\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/caffe2.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, line-too-long, unused-argument\n\"\"\"Caffe2 frontend\"\"\"\nimport tvm\nfrom tvm.ir import IRModule\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom ... import nd as _nd\nfrom .common import AttrCvt, Renamer\nfrom .common import get_relay_op, new_var, infer_channels\n\n__all__ = [\"from_caffe2\"]\n\n\ndef dimension_picker(prefix, surfix=\"\"):\n    def _impl(attr):\n        kernel = attr[\"kernel_shape\"]\n        if len(kernel) == 2:\n            return prefix + \"2d\" + surfix\n        raise tvm.error.OpAttributeUnImplemented(\n            \"Non-2D kernels are not supported for operator {}2d\".format(prefix)\n        )\n\n    return _impl\n\n\ndef revert_caffe2_pad(pads):\n    \"\"\"Caffe2 requires two times the normal padding.\"\"\"\n    if len(pads) == 4:\n        pads = pads[:2]\n    elif len(pads) == 2:\n        pass\n    else:\n        raise tvm.error.OpAttributeInvalid(\"Number of pads must equal 2 or 4.\")\n    return pads\n\n\ndef dimension_constraint():\n    def _dim_check(args):\n        if len(args[\"kernel_shape\"]) == 2:\n            return True\n        return False\n\n    return _dim_check, \"Only 2d kernel supported.\"\n\n\ndef _clean_up_pool_args(args):\n    \"\"\"A helper function to clean up common arguments in conv and pooling ops.\"\"\"\n    assert isinstance(args, dict)\n\n    if \"stride_h\" in args and \"stride_w\" in args:\n        assert \"stride\" not in args and \"strides\" not in args\n        args[\"strides\"] = [args[\"stride_h\"], args[\"stride_w\"]]\n        args.pop(\"stride_h\")\n        args.pop(\"stride_w\")\n    elif \"stride\" in args:\n        args[\"strides\"] = [args[\"stride\"], args[\"stride\"]]\n        args.pop(\"stride\")\n\n    # rename 'kernel', 'kernels', to 'kernel_shape'\n    if \"kernel_h\" in args and \"kernel_w\" in args:\n        assert \"kernel\" not in args and \"kernels\" not in args\n        args[\"kernel_shape\"] = [args[\"kernel_h\"], args[\"kernel_w\"]]\n        args.pop(\"kernel_h\")\n        args.pop(\"kernel_w\")\n    elif \"kernel\" in args:\n        args[\"kernel_shape\"] = [args[\"kernel\"], args[\"kernel\"]]\n        args.pop(\"kernel\")\n    elif \"kernels\" in args:\n        args[\"kernel_shape\"] = args[\"kernels\"]\n        args.pop(\"kernels\")\n\n    if \"pad_t\" in args and \"pad_l\" in args and \"pad_b\" in args and \"pad_r\" in args:\n        assert \"pad\" not in args and \"pads\" not in args\n        args[\"pads\"] = [args[\"pad_t\"], args[\"pad_l\"], args[\"pad_b\"], args[\"pad_r\"]]\n        for pad in [\"pad_t\", \"pad_l\", \"pad_b\", \"pad_r\"]:\n            args.pop(pad)\n    elif \"pad\" in args:\n        args[\"pads\"] = [args[\"pad\"], args[\"pad\"]]\n        args.pop(\"pad\")\n\n    if \"dilation_h\" in args and \"dilation_w\" in args:\n        assert \"dilation\" not in args and \"dilations\" not in args\n        args[\"dilations\"] = [args[\"dilation_h\"], args[\"dilation_w\"]]\n        args.pop(\"dilation_h\")\n        args.pop(\"dilation_w\")\n    elif \"dilation\" in args:\n        args[\"dilations\"] = [args[\"dilation\"], args[\"dilation\"]]\n        args.pop(\"dilation\")\n\n    return args\n\n\nclass Caffe2OpConverter(object):\n    \"\"\"A helper class for holding Caffe2 op converters.\"\"\"\n\n    @classmethod\n    def get_converter(cls):\n        \"\"\"Get converter.\n\n        :return: converter, which should be `_impl`.\n        \"\"\"\n\n        if hasattr(cls, \"_impl\"):\n            return getattr(cls, \"_impl\")\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported in frontend Caffe2.\".format(cls.__name__)\n        )\n\n\n_caffe2_internal_args = [\n    # nnpack args\n    \"algo\",\n    \"convolution_transform_strategy\",\n    \"float16_compute\",\n    \"shared_buffer\",\n    # training args\n    \"init_params\",\n    \"cudnn_exhaustive_search\",\n    \"exhaustive_search\",\n    # training args\n    \"adj\",\n    \"hwgq\",\n    # args that we don't care\n    \"legacy_pad\",\n]\n\n\nclass Elemwise(Caffe2OpConverter):\n    \"\"\"A helper class for elemwise op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        assert len(inputs) == 2, \"Math op take 2 inputs, {} given\".format(len(inputs))\n        op_name = cls.name\n        conv_ops = [\"conv2d\", \"conv2d_transpose\"]\n        if args.get(\"broadcast\", 0) and any(x in str(inputs[0]) for x in conv_ops):\n            # TODO(zhreshold): remove hard coded infershape\n            axis = int(args.get(\"axis\", 0))\n            inputs[1] = _op.expand_dims(inputs[1], axis=axis, num_newaxis=2)\n        return get_relay_op(op_name)(*inputs)\n\n\nclass Add(Elemwise):\n    \"\"\"Operator converter for Add.\"\"\"\n\n    name = \"add\"\n\n\nclass Mul(Elemwise):\n    \"\"\"Operator converter for Mul.\"\"\"\n\n    name = \"multiply\"\n\n\nclass Pool(Caffe2OpConverter):\n    \"\"\"A helper class for pool op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        _clean_up_pool_args(args)\n        if \"global_pooling\" in args and args[\"global_pooling\"] == 1:\n            op_name = dimension_picker(\"global_\" + cls.name)\n            return get_relay_op(op_name(args))(*inputs)\n\n        return AttrCvt(\n            op_name=dimension_picker(cls.name),\n            transforms={\n                \"kernel_shape\": \"pool_size\",\n                \"pads\": (\"padding\", (0, 0), revert_caffe2_pad),\n                \"strides\": \"strides\",\n            },\n            ignores=[\"dilations\", \"order\", \"legacy_pad\", \"global_pooling\"],\n            extras={\"ceil_mode\": False},\n            custom_check=dimension_constraint(),\n        )(inputs, args, params)\n\n\nclass AveragePool(Pool):\n    name = \"avg_pool\"\n\n\nclass MaxPool(Pool):\n    name = \"max_pool\"\n\n\nclass Conv(Caffe2OpConverter):\n    \"\"\"Operator converter for Conv.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        # get number of channels\n        channels = infer_channels(inputs[1])\n        args[\"channels\"] = channels\n        _clean_up_pool_args(args)\n        out = AttrCvt(\n            op_name=dimension_picker(\"conv\"),\n            transforms={\n                \"group\": (\"groups\", 1),\n                \"kernel_shape\": \"kernel_size\",\n                \"pads\": (\"padding\", (0, 0), revert_caffe2_pad),\n                \"strides\": \"strides\",\n                \"dilations\": (\"dilation\", (1, 1)),\n                \"order\": (\n                    \"data_layout\",\n                    (\"NCHW\"),\n                    lambda x: x if isinstance(x, str) else x.decode(\"UTF-8\"),\n                ),\n            },\n            excludes=[],\n            ignores=_caffe2_internal_args,\n            custom_check=dimension_constraint(),\n        )(inputs[:2], args, params)\n        use_bias = len(inputs) == 3\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[2])\n        return out\n\n\nclass ConvTranspose(Caffe2OpConverter):\n    \"\"\"Operator converter for ConvTranspose.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        # get number of channels\n        channels = infer_channels(inputs[1], True)\n        args[\"channels\"] = channels\n        _clean_up_pool_args(args)\n        out = AttrCvt(\n            op_name=dimension_picker(\"conv\", \"_transpose\"),\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"pads\": (\"padding\", (0, 0), revert_caffe2_pad),\n                \"dilations\": (\"dilation\", (1, 1)),\n                \"order\": (\n                    \"data_layout\",\n                    (\"NCHW\"),\n                    lambda x: x if isinstance(x, str) else x.decode(\"UTF-8\"),\n                ),\n            },\n            excludes=[],\n            ignores=_caffe2_internal_args,\n            custom_check=dimension_constraint(),\n        )(inputs[:2], args, params)\n        use_bias = len(inputs) == 3\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[2])\n        return out\n\n\nclass Concat(Caffe2OpConverter):\n    \"\"\"Operator converter for Concat.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        def _get_axis_from_order_str(order):\n            order = order if isinstance(order, str) else order.decode(\"UTF-8\")\n            if order == \"NCHW\":\n                return 1\n            if order == \"NHWC\":\n                return 3\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Order {} is not supported in operator Concat.\".format(order)\n            )\n\n        return AttrCvt(\n            op_name=\"concatenate\",\n            transforms={\n                \"order\": (\"axis\", (1), _get_axis_from_order_str),\n            },\n            excludes=[\"add_axis\"],\n        )((inputs,), args, params)\n\n\nclass NormalizePlanarYUV(Caffe2OpConverter):\n    \"\"\"Operator converter for NormalizePlanarYUV.\n    caffe2 definition: https://github.com/pytorch/pytorch/blob/master/caffe2/operators/norm_planar_yuv_op.cc\n    \"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        assert len(inputs) == 3\n        mean = _op.expand_dims(inputs[1], axis=2, num_newaxis=2)\n        std = _op.expand_dims(inputs[2], axis=2, num_newaxis=2)\n\n        return _op.divide(_op.subtract(inputs[0], mean), std)\n\n\nclass ResizeNearest(Caffe2OpConverter):\n    \"\"\"Operator converter for Upsample (nearest mode).\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        width_scale = args[\"width_scale\"] if \"width_scale\" in args else 1\n        height_scale = args[\"height_scale\"] if \"height_scale\" in args else 1\n        assert width_scale == height_scale\n\n        return _op.nn.upsampling(\n            inputs[0], scale_h=int(width_scale), scale_w=int(width_scale), method=\"NEAREST_NEIGHBOR\"\n        )\n\n\nclass Sum(Caffe2OpConverter):\n    \"\"\"Operator converter for Sum.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        # Sum Operator\n        for in_index in range(len(inputs) - 1):\n            inputs[in_index + 1] = _op.add(inputs[in_index], inputs[in_index + 1])\n\n        return inputs[len(inputs) - 1]\n\n\nclass Softmax(Caffe2OpConverter):\n    \"\"\"Operator converter for Softmax.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        # set default value when axis is not set in the model\n        if \"axis\" not in args:\n            args[\"axis\"] = 1\n        return AttrCvt(\"softmax\", transforms={\"axis\": (\"axis\", args[\"axis\"])})(inputs, args, params)\n\n\nclass FC(Caffe2OpConverter):\n    \"\"\"Operator converter for FC.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        inputs[0] = _op.nn.batch_flatten(inputs[0])\n        units = infer_channels(inputs[1])\n        res = _op.nn.dense(inputs[0], inputs[1], units=units)\n        use_bias = len(inputs) == 3\n        if use_bias:\n            res = _op.nn.bias_add(res, inputs[2])\n        return res\n\n\nclass SpatialBN(Caffe2OpConverter):\n    \"\"\"Operator converter for SpatialBN.\"\"\"\n\n    @classmethod\n    def _impl(cls, inputs, args, params):\n        return AttrCvt(\n            op_name=\"batch_norm\",\n            disables=[\"momentum\"],\n            ignores=[\"order\", \"spatial\", \"is_test\", \"consumed_inputs\", \"num_batches\"],\n        )(inputs, args, params)\n\n\n# compatible operators that do NOT require any conversion.\n_identity_list = []\n\n# _convert_map defines maps of name to converter functor(callable)\n# for 1 to 1 mapping, use Renamer if nothing but name is different\n# use AttrCvt if attributes need to be converted\n# for 1 to N mapping(composed), use custom callable functions\n# for N to 1 mapping, currently not supported(?)\n\n# Minimal set of ops for squeezenet and resnet50\ndef _get_convert_map():\n    return {\n        # caffe2 common operators\n        \"Add\": Add.get_converter(),\n        \"Sum\": Sum.get_converter(),\n        \"Mul\": Mul.get_converter(),\n        \"Softmax\": Softmax.get_converter(),\n        # nn\n        \"AveragePool\": AveragePool.get_converter(),\n        \"MaxPool\": MaxPool.get_converter(),\n        \"Conv\": Conv.get_converter(),\n        \"ConvTranspose\": ConvTranspose.get_converter(),\n        \"Concat\": Concat.get_converter(),\n        \"FC\": FC.get_converter(),\n        \"SpatialBN\": SpatialBN.get_converter(),\n        \"ResizeNearest\": ResizeNearest.get_converter(),\n        \"Relu\": AttrCvt(\"relu\", {}, ignores=[\"order\"]),\n        \"Sigmoid\": Renamer(\"sigmoid\"),\n        \"Dropout\": AttrCvt(\"dropout\", {\"ratio\": \"rate\"}, ignores=[\"is_test\"]),\n        # c2 image preprocessing ops\n        \"NormalizePlanarYUV\": NormalizePlanarYUV.get_converter(),\n    }\n\n\nclass Caffe2NetDef(object):\n    \"\"\"A helper class for handling Relay expression copying from pb2.GraphProto.\n    Definition: https://github.com/pytorch/pytorch/blob/master/caffe2/proto/caffe2.proto\n    \"\"\"\n\n    def __init__(self, shape, dtype):\n        self._nodes = {}\n        self._params = {}\n        self._visited_nodes = set()\n        self._ops = {}\n        self._shape = shape\n        self._dtype = dtype\n        self._mod = IRModule({})\n\n    def from_caffe2(self, init_net, predict_net):\n        \"\"\"Construct Relay expression from caffe2 graph.\n\n        Parameters\n        ----------\n        init_net : protobuf object\n        predict_net : protobuf object\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The module that optimizations will be performed on.\n\n        params : dict\n            A dict of name: tvm.nd.array pairs, used as pretrained weights\n        \"\"\"\n        # pylint: disable=import-outside-toplevel\n        from caffe2.python import workspace\n\n        workspace.RunNetOnce(init_net)\n\n        # Input\n        input_name = predict_net.op[0].input[0]\n\n        # Params\n        self._params = {}\n        used_blobs = set()\n        for c2_op in predict_net.op:\n            for i in c2_op.input:\n                used_blobs.add(i)\n        for blob in workspace.Blobs():\n            if blob in used_blobs and blob != input_name:\n                self._params[blob] = _nd.array(workspace.FetchBlob(blob))\n\n        # Variables\n        self._nodes = {}\n        for blob in predict_net.external_input:\n            if blob in self._params:\n                self._nodes[blob] = new_var(\n                    blob, shape=self._params[blob].shape, dtype=self._params[blob].dtype\n                )\n            else:\n                shape = self._shape[blob] if blob in self._shape else ()\n                if isinstance(self._dtype, dict) and blob in self._dtype:\n                    dtype = str(self._dtype[blob])\n                elif isinstance(self._dtype, str):\n                    dtype = self._dtype\n                else:\n                    dtype = \"float32\"\n                self._nodes[blob] = new_var(blob, shape=shape, dtype=dtype)\n\n        # Ops\n        for c2_op in predict_net.op:\n            for blob in c2_op.output:\n                self._ops[blob] = c2_op\n\n        for c2_op in predict_net.op:\n            self._process_op(c2_op)\n\n        # Outputs\n        out = []\n        for blob in predict_net.external_output:\n            out.append(self._nodes[blob])\n\n        if len(out) > 1:\n            outputs = _expr.Tuple(out)\n        else:\n            outputs = out[0]\n\n        func = _function.Function(analysis.free_vars(outputs), outputs)\n        self._mod[\"main\"] = func\n\n        return self._mod, self._params\n\n    def _get_node(self, blob):\n        \"\"\"Get the Symbol of blob and detect cyclic dependency in the graph.\"\"\"\n        if blob in self._nodes:\n            return self._nodes[blob]\n\n        assert blob not in self._visited_nodes, \"Cyclic dependency in the graph (in {})\".format(\n            blob\n        )\n        self._visited_nodes.add(blob)\n\n        self._process_op(self._ops[blob])\n        return self._nodes[blob]\n\n    def _process_op(self, c2_op):\n        op_type = c2_op.type\n        args = self._parse_arg(c2_op.arg)\n        inputs = [self._get_node(i) for i in c2_op.input]\n        tvm_op = self._convert_operator(op_type, inputs, args)\n\n        if not isinstance(tvm_op, _expr.TupleWrapper):\n            self._nodes[c2_op.output[0]] = tvm_op\n        else:\n            for k, i in zip(list(c2_op.output), range(len(tvm_op))):\n                self._nodes[k] = tvm_op[i]\n\n    def _parse_arg(self, arg):\n        \"\"\"Convert a list of Argument to a dict, with names as keys.\"\"\"\n        args = {}\n        for a in arg:\n            for f in [\"f\", \"i\", \"s\"]:\n                if a.HasField(f):\n                    args[a.name] = getattr(a, f)\n            for f in [\"floats\", \"ints\", \"strings\"]:\n                if list(getattr(a, f)):\n                    assert a.name not in args, \"Only one type of attr is allowed\"\n                    args[a.name] = tuple(getattr(a, f))\n            for f in [\"n\"]:\n                if a.HasField(f):\n                    raise NotImplementedError(\"Field {} is not supported in relay.\".format(f))\n            for f in [\"nets\"]:\n                if list(getattr(a, f)):\n                    raise NotImplementedError(\"Field {} is not supported in relay.\".format(f))\n            if a.name not in args:\n                raise ValueError(\"Cannot parse attribute: \\n{}\\n.\".format(a))\n        return args\n\n    def _convert_operator(self, op_type, inputs, args, identity_list=None, convert_map=None):\n        \"\"\"Convert from Caffe2 operator to Relay operator.\n        The converter must specify conversions explicitly for incompatible name, and\n        apply handlers to operator attributes.\n\n        Parameters\n        ----------\n        op_type : str\n            Operator name, such as Convolution, FullyConnected\n        inputs : list of tvm.relay.function.Function\n            List of input inputs.\n        args : dict\n            Dict of operator attributes\n        identity_list : list\n            List of operators that don't require conversion\n        convert_map : dict\n            Dict of name : callable, where name is the op's name that\n            require conversion to relay, callable are functions which\n            take args and return (new_op_type, new_args)\n\n        Returns\n        -------\n        func : tvm.relay.function.Function\n            Converted relay function\n        \"\"\"\n        identity_list = identity_list if identity_list else _identity_list\n        convert_map = convert_map if convert_map else _get_convert_map()\n        if op_type in identity_list:\n            func = get_relay_op(op_type)(*inputs, **args)\n        elif op_type in convert_map:\n            # Add a sanitizing step to convert all byte strings in args to strings\n            func = convert_map[op_type](inputs, args, self._params)\n        else:\n            raise tvm.error.OpNotImplemented(\n                \"Operator {} is not supported in frontend Caffe2.\".format(op_type)\n            )\n        return func\n\n\ndef from_caffe2(init_net, predict_net, shape=None, dtype=\"float32\"):\n    \"\"\"Load caffe2 graph which contains init_net and predict_net into Relay Function.\n\n    Parameters\n    ----------\n    init_net : protobuf object\n        Caffe2 NetDef containing the weights\n\n    predict_net : protobuf object\n        Caffe2 NetDef containing the graph\n\n    shape : dict of str to tuple\n        The input shape to the graph\n\n    dtype : str or dict of str to str\n        The input types to the graph\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The module that optimizations will be performed on.\n\n    params : dict of str to tvm.nd.NDArray\n        Dict of converted parameters stored in tvm.nd.NDArray format\n    \"\"\"\n\n    caffe2 = Caffe2NetDef(shape, dtype)\n    return caffe2.from_caffe2(init_net, predict_net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/change_datatype.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Change Datatype Pass\"\"\"\nfrom ..function import Function\nfrom ..expr_functor import ExprMutator\nfrom ..transform.transform import function_pass\nfrom ..expr import var, bind\n\n\n@function_pass(opt_level=0)\nclass ChangeDatatype(ExprMutator):\n    \"\"\"Mutator for changing the datatype of Relay programs.\n\n    This pass should be useful for users of the Bring Your Own Datatypes\n    framework.\n    TODO(@gussmith23 @hypercubestart) Add link to documentation when it exists\n\n    Example:\n\n    .. code-block:: python\n\n        from tvm.relay.testing.inception_v3 import get_workload\n        mod, params = get_workload()\n\n        def change_dtype(mod, params, src, dst):\n            mod = ChangeDatatype(src, dst)(mod)\n            params = dict((p, tvm.nd.array(params[p].numpy().astype(dst))) for p in params)\n            return mod, params\n\n        mod, params = change_dtype(mod, params, \"float32\", \"custom[posites2]32\")\n\n    Parameters\n    ----------\n    src : String\n        The source datatype name, e.g. \"float\" or \"posites2\" (but not \"float32\"\n        or \"custom[posites2]32\").\n    dst : String\n        The destination datatype name, in the same format.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        Module where all nodes of dtype `src` have been changed to have dtype\n        `dst`.\n    \"\"\"\n\n    def __init__(self, src, dst):\n        self.src = src\n        self.dst = dst\n        super().__init__()\n\n    def transform_function(self, func, mod, ctx):\n        return self.visit(func)\n\n    def visit_constant(self, const):\n        if const.data.dtype == self.src:\n            return const.astype(self.dst)\n        return const\n\n    def visit_function(self, fn):\n        new_params = []\n        binds = {}\n\n        for param in fn.params:\n            # Get the parameter's type annotation.\n            var_type = param.type_annotation\n\n            # See if we want to replace dtype.\n            if var_type.dtype == self.src:\n                dtype = self.dst\n            else:\n                dtype = var_type.dtype\n\n            # Generate new variable.\n            new_param = var(param.name_hint, shape=var_type.shape, dtype=dtype)\n\n            new_params.append(new_param)\n            binds[param] = new_param\n\n        new_body = self.visit(fn.body)\n        # Rewrite the body to use new parameters.\n        new_body = bind(new_body, binds)\n\n        # Construct the updated function and return.\n        return Function(\n            new_params,\n            new_body,\n            # You could change the return type, if you use None it will re-infer.\n            None,\n            type_params=fn.type_params,\n            attrs=fn.attrs,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=broad-except\n\"\"\"Common utilities\"\"\"\nfrom __future__ import absolute_import as _abs\nimport logging\nimport numpy as np\n\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import transform as _transform\nfrom .. import op as _op\nfrom .. import ty as _ty\nfrom .. import analysis\n\n\nclass DuplicateFilter:\n    \"\"\"A log filter that only prints the same message once.\"\"\"\n\n    def __init__(self):\n        self.msgs = set()\n\n    def filter(self, record):\n        self.msgs.add(record.msg)\n        return record.msg not in self.msgs\n\n\n# pylint: disable=invalid-name\nlogger = logging.getLogger(\"Frontend\")\nlogger.addFilter(DuplicateFilter())\n# Uncomment below line to print all debug msgs\n# logger.setLevel(logging.DEBUG)\n\n\nclass RequiredAttr(object):\n    \"\"\"Dummpy class to represent required attr\"\"\"\n\n\nclass StrAttrsDict(object):\n    \"\"\"Helper class to parse attrs stored as Dict[str, str].\n\n    Parameters\n    ----------\n    attrs : Dict[str, str]\n        The attributes to be used.\n    \"\"\"\n\n    def __init__(self, attrs):\n        self.attrs = attrs\n\n    def has_attr(self, key):\n        \"\"\"Checks if a attribute is present in the map.\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        Returns\n        -------\n        bool : True if the key is present in the attributes else false.\n        \"\"\"\n        return key in self.attrs\n\n    def get_float(self, key, default=RequiredAttr()):\n        \"\"\"Get float attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            return float(self.attrs[key])\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_int(self, key, default=RequiredAttr()):\n        \"\"\"Get int attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            val = self.attrs[key]\n            if val == \"None\":\n                return None\n            return int(val)\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_str(self, key, default=RequiredAttr()):\n        \"\"\"Get str attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            return self.attrs[key]\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_int_tuple(self, key, default=RequiredAttr()):\n        \"\"\"Get int tuple attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            tshape = self.attrs[key]\n            return tuple(\n                int(x) if x.strip(\"- \").isdigit() else None\n                for x in tshape.strip(\"()[]\").split(\",\")\n                if x\n            )\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_float_tuple(self, key, default=RequiredAttr()):\n        \"\"\"Get float tuple attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n\n        if key in self.attrs:\n            tshape = self.attrs[key]\n            return tuple(float(x.strip()) for x in tshape.strip(\"()[]\").split(\",\"))\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_tuple_tuple_int(self, key, default=RequiredAttr()):\n        \"\"\"Get int list attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            value = self.attrs[key]\n            seq = []\n            for tup in value.strip(\"()\").split(\"),\"):\n                tup = tup.strip(\"[]()\")\n                els = [int(x.strip(\"( \")) for x in tup.split(\",\")]\n                seq.append(tuple(els))\n\n            return tuple(seq)\n\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_int_list(self, key, default=RequiredAttr()):\n        \"\"\"Get int list attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            tshape = self.attrs[key]\n            return tuple(int(x.strip()) for x in tshape.strip(\"[]()\").split(\",\"))\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n    def get_bool(self, key, default=RequiredAttr()):\n        \"\"\"Get bool tuple attribute\n\n        Parameters\n        ----------\n        key : str\n            The attribute key\n\n        default : float\n            The default value.\n\n        Returns\n        -------\n        value : The result\n        \"\"\"\n        if key in self.attrs:\n            val = self.attrs[key]\n            return val.strip().lower() in [\"true\", \"1\", \"t\", \"y\", \"yes\"]\n        if isinstance(default, RequiredAttr):\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return default\n\n\ndef get_relay_op(op_name):\n    \"\"\"Get the callable function from Relay based on operator name.\n    Parameters\n    ----------\n    op_name : str\n        The Relay operator name.\n    \"\"\"\n    if \".\" in op_name:\n        # explicit hierarchical modules\n        op = _op\n        try:\n            for opn in op_name.split(\".\"):\n                op = getattr(op, opn)\n        except AttributeError:\n            op = None\n    else:\n        # try search op in various modules\n        for candidate in (_op, _op.nn, _op.image, _op.vision, _op.contrib):\n            op = getattr(candidate, op_name, None)\n            if op is not None:\n                break\n    if not op:\n        raise tvm.error.OpNotImplemented(\"Unable to map op_name {} to relay\".format(op_name))\n    return op\n\n\nclass ExprTable(object):\n    \"\"\"Table storing Relay expressions by names.\"\"\"\n\n    def __init__(self):\n        self.exprs = {}\n        self.params = {}\n        self.const_ctr = 1\n        self.in_padding = False\n\n    def new_const(self, value, shape=None, dtype=\"float32\"):\n        name = \"_param_%d\" % (self.const_ctr)\n        if hasattr(value, \"shape\"):\n            shape = value.shape\n        self.const_ctr += 1\n        self.params[name] = value\n        self.exprs[name] = _expr.var(name_hint=name, shape=shape, dtype=dtype)\n        return self.exprs[name]\n\n    def get_expr(self, name):\n        return self.exprs[name]\n\n    def set_expr(self, name, expr, force_override=False):\n        assert isinstance(expr, _expr.Expr)\n        # if name exists, we should override the value\n        # otherwise, we can not get like x = func(x) work.\n        # One example is CoreML preprocess, which will override\n        # the same name of input.\n        # However, according to git log, Find keras frontend depends\n        # on this property, so we add one force_override to control it.\n        if name not in self.exprs or force_override:\n            self.exprs[name] = expr\n\n    def has_expr(self, name):\n        return name in self.exprs\n\n    def set_padding(self, paddings):\n        self.paddings = paddings\n        self.in_padding = True\n\n    def clear_padding(self):\n        self.in_padding = False\n\n\nclass AttrCvt(object):\n    \"\"\"Common attribute converter. An AttrConverter instance is a callable:\n    ```\n    attr_converter = AttrConverter(op_name, transforms={'a':'b', 'c':('d', 1)})\n    new_op_name, new_attr = attr_converter(attrs)\n    ```\n\n    Parameters\n    ----------\n    op_name : str or callable\n        If set as str, returned operator name is the str.\n        If set as callable, returned operator is the str returned by calling:\n        `op_name = func(attr)`\n\n    transforms : dict of `new_name, or (new_name, default_value, transform function)`\n        If only a new_name is provided, it's like renaming the attribute name.\n        If default_value if provided, then the attribute is considered as optional.\n        If transform function is provided, the original attribute value is handled\n        by transform function.\n\n    excludes : list\n        A list of excluded attributes that should `NOT` appear.\n        Raise NotImplementedError if occurred.\n\n    disables : list\n        A list of attributes that is disabled in relay. Log warnings.\n\n    ignores : list\n        A list of attributes that is ignored in relay. Debug level logging.\n\n    extras : dict\n        A series of additional attributes should be added anyway to the returned\n        attribute dict.\n\n    custom_check : callable\n        A custom function takes attribute, and return True/False.\n        Raise RuntimeError if not bool(True) returned.\n    \"\"\"\n\n    def __init__(\n        self,\n        op_name,\n        transforms=None,\n        excludes=None,\n        disables=None,\n        ignores=None,\n        extras=None,\n        custom_check=None,\n    ):\n        self._op_name = op_name\n        self._transforms = transforms if transforms else {}\n        self._excludes = excludes if excludes else []\n        self._disables = disables if disables else []\n        self._ignores = ignores if ignores else []\n        self._extras = extras if extras else {}\n        self._custom_check = custom_check\n\n    def __call__(self, inputs, attrs, *args):\n        self._ignores.append(\"_output_shapes\")\n        self._ignores.append(\"_input_shapes\")\n        self._ignores.append(\"T\")\n        self._ignores.append(\"use_cudnn_on_gpu\")\n        self._ignores.append(\"_node_name\")\n        self._ignores.append(\"is_training\")\n        self._ignores.append(\"_target_layout\")\n\n        # apply custom check\n        if self._custom_check:\n            func, msg = self._custom_check\n            if not func(attrs):\n                raise RuntimeError(\"Check failed: {}\".format(msg))\n        # get new op_name\n        if isinstance(self._op_name, str):\n            op_name = self._op_name\n        else:\n            assert callable(self._op_name), \"op_name can either be string or callable\"\n            op_name = self._op_name(attrs)\n\n        # ignore 'tvm_custom' always\n        self._ignores.append(\"tvm_custom\")\n\n        # convert attributes\n        new_attrs = {}\n        for k in attrs.keys():\n            if k in self._excludes:\n                raise NotImplementedError(\n                    \"Attribute %s in operator %s is not\" + \" supported.\", k, op_name\n                )\n            if k in self._disables:\n                logger.debug(\"Attribute %s is disabled in relay.sym.%s\", k, op_name)\n            elif k in self._ignores:\n                if k != \"tvm_custom\":\n                    logger.debug(\"Attribute %s is ignored in relay.sym.%s\", k, op_name)\n            elif k in self._transforms:\n                new_name, defaults, transform = self._parse_default(self._transforms[k])\n                if defaults is None:\n                    new_attr = self._required_attr(attrs, k)\n                else:\n                    new_attr = attrs.get(k, None)\n                if new_attr is None:\n                    new_attrs[new_name] = defaults\n                else:\n                    new_attrs[new_name] = transform(new_attr)\n            else:\n                # copy\n                new_attrs[k] = attrs[k]\n        # add extras\n        new_attrs.update(self._extras)\n        return get_relay_op(op_name)(*inputs, **new_attrs)\n\n    def _parse_default(self, target):\n        \"\"\"Helper function to parse default values.\"\"\"\n        if not isinstance(target, (list, tuple)):\n            k, v, t = target, None, lambda x: x\n        elif len(target) == 1:\n            k, v, t = target[0], None, lambda x: x\n        elif len(target) == 2:\n            k, v, t = target[0], target[1], lambda x: x\n        elif len(target) > 2:\n            k, v, t = target[0], target[1], target[2]\n        else:\n            k = None  # should raise\n        if not isinstance(k, str):\n            msg = \"{} is not a valid target, (name, default) expected.\".format(target)\n            raise ValueError(msg)\n        return k, v, t\n\n    def _parse_bool(self, value):\n        \"\"\"Helper function to parse default boolean values.\"\"\"\n        if isinstance(value, str):\n            return value.strip().lower() in [\"true\", \"1\", \"t\", \"y\", \"yes\"]\n        return bool(value)\n\n    def _required_attr(self, attr, key):\n        \"\"\"Wrapper for getting required attributes.\"\"\"\n        assert isinstance(attr, dict)\n        if key not in attr:\n            raise AttributeError(\"Required attribute {} not found.\".format(key))\n        return attr[key]\n\n\ndef get_name(node):\n    name = \"\"\n    if hasattr(node, \"name_hint\"):\n        name = node.name_hint\n    return name\n\n\ndef infer_type(node, mod=None):\n    \"\"\"A method to infer the type of an intermediate node in the relay graph.\"\"\"\n    if isinstance(mod, IRModule):\n        mod[\"main\"] = _function.Function(tvm.relay.analysis.free_vars(node), node)\n        mod = _transform.InferType()(mod)\n        entry = mod[\"main\"]\n        ret = entry.body\n    else:\n        new_mod = IRModule.from_expr(node)\n        if mod is not None:\n            new_mod.update(mod)\n\n        new_mod = _transform.InferType()(new_mod)\n        entry = new_mod[\"main\"]\n        ret = entry if isinstance(node, _function.Function) else entry.body\n\n    return ret\n\n\ndef fold_constant(node, mod=None):\n    if mod is None:\n        mod = IRModule()\n    return _transform.FoldConstantExpr(node, mod)\n\n\ndef infer_channels(inputs, transpose=False):\n    \"\"\"A hack for getting 'channels' or 'units' since caffe2 does not provide\n    these attributes. We check the shape of weights provided to get the number.\n    \"\"\"\n    out_type = infer_type(inputs)\n    out_shapes = [get_const_tuple(out_type.checked_type.shape)]\n    channels = out_shapes[0][0] if not transpose else out_shapes[0][1]\n    return channels\n\n\ndef infer_shape(inputs, mod=None):\n    \"\"\"A method to get the output type of an intermediate node in the graph.\"\"\"\n    out_type = infer_type(inputs, mod=mod)\n    checked_type = out_type.checked_type\n    if hasattr(checked_type, \"shape\"):\n        # Regular operator that outputs tensors\n        return get_const_tuple(checked_type.shape)\n    # The return type is not a tensor, for example List\n    return checked_type\n\n\ndef infer_value(input_val, params, mod=None):\n    \"\"\"A hack for getting the value of an expression by evaluating a\n    portion of the relay graph. This is often needed for functions that\n    whose output shape depends on the value of a tensor.\n    \"\"\"\n    # Check that all free variables have associated parameters.\n    assert all(\n        var.name_hint in params.keys() for var in analysis.free_vars(input_val)\n    ), \"All inputs to infer must be available in params.\"\n    assert tvm.runtime.enabled(\"llvm\"), \"LLVM must be enabled to infer value.\"\n    try:\n        # TODO(kevinthesun): Use VM for all cases.\n        # pylint: disable=import-outside-toplevel\n        from tvm.contrib import graph_executor\n\n        func = _function.Function(analysis.free_vars(input_val), input_val)\n        with tvm.transform.PassContext(opt_level=0):\n            lib = tvm.relay.build(func, target=\"llvm\", params=params)\n        dev = tvm.cpu(0)\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        m.run()\n        return m.get_output(0)\n    except Exception:\n        if isinstance(mod, IRModule):\n            mod[\"main\"] = _function.Function(analysis.free_vars(input_val), input_val)\n        else:\n            mod = IRModule.from_expr(input_val)\n        inputs = []\n        for param in mod[\"main\"].params:\n            inputs.append(params[param.name_hint])\n        result = tvm.relay.create_executor(\n            \"debug\", mod=mod, device=tvm.cpu(), target=\"llvm\"\n        ).evaluate()(*inputs)\n        return result\n\n\ndef infer_value_simulated(input_val, params):\n    \"\"\"Extension to infer_value that can be used when some input\n    values are missing. This function creates dummy inputs with the same\n    shape and random values then calls infer_value. This is helpful when\n    implementing certain onnx operators where we need to evaluate the graph\n    to determine a static shape.\n    \"\"\"\n    fake_params = []\n    # Add a fake copy of all missing params.\n    for free_param in analysis.free_vars(input_val):\n        if free_param.name_hint not in params:\n            fp_dtype = free_param.type_annotation.dtype\n            fp_shape = [s.value for s in free_param.type_annotation.shape]\n            fake_params.append(free_param)\n            params[free_param.name_hint] = tvm.nd.array(np.random.rand(*fp_shape).astype(fp_dtype))\n    # Now infer the value.\n    output_value = infer_value(input_val, params)\n    # Clean fake params out of param dictionary.\n    for fake_p in fake_params:\n        params.pop(fake_p.name_hint, None)\n    return output_value\n\n\ndef try_infer_value(val, on_success=None, on_failure=None, parameters=None):\n    \"\"\"Try running infer_value on the input val, and if successful, return the inferred value or\n    pass it to on_success callback if provided. Otherwise, run on_failure callback if it is\n    provided, or return the input val as output. In each case, the second return value\n    indicates whether infer_value has succeeded or not.\n    \"\"\"\n    try:\n        params = parameters if parameters is not None else {}\n        ret = infer_value(val, params).numpy()\n        if on_success:\n            return on_success(ret), True\n        return ret, True\n    except Exception:\n        if on_failure:\n            return on_failure(), False\n        return val, False\n\n\ndef shape_of(x, dtype=\"int64\", start=None, end=None):\n    \"\"\"Get shape of a tensor.\"\"\"\n\n    ttype = infer_type(x).checked_type\n    if not _ty.is_dynamic(ttype):\n        shape = list(ttype.shape)\n        start = start or 0  # default to first\n        end = end or len(shape)  # default to last\n        shape_sliced = shape[start:end]\n        return _expr.const(shape_sliced, dtype)\n    return _op.shape_of(x, dtype)\n\n\ndef new_var(name_hint, type_annotation=None, shape=None, dtype=\"float32\"):\n    return _expr.var(name_hint, type_annotation, shape, dtype)\n\n\nclass Renamer(object):\n    \"\"\"A simply renamer for operators.\n\n    Parameters\n    ----------\n    new_name : str\n        The new name for the operator\n    \"\"\"\n\n    def __init__(self, new_name):\n        self._new_name = new_name\n\n    def __call__(self, inputs, attrs, *args):\n        if \"tvm_custom\" in attrs:\n            attrs.pop(\"tvm_custom\")\n        return get_relay_op(self._new_name)(*inputs, **attrs)\n\n\ndef to_int_list(np_array):\n    \"\"\"Convert a np array to a python int list.\n\n    Note: This function converts np.int32 to python's int.\n    If we don't do this conversion, numpy's automatic upcast will make\n    the shape / parameters be converted to int64 IntImm in relay and\n    cause problems in relay/TOPI.\n    \"\"\"\n    return [int(x) for x in np_array]\n\n\ndef unbind(data, axis=0):\n    \"\"\"\n    Unbind was taken from Pytorch frontend. The operation removes a tensor dimension\n    and returns a tuple of all slices along a given dimension, with specified axis removed.\n    TODO (vvchernov): It needs such operation on relay side to reduce time consumption\n    on squeeze operation.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Input tensor\n    axis : int\n        Axis along which tensor is split.\n    Returns\n    -------\n    result : List[relay.Expr]\n        The sequence of computed tensors\n    \"\"\"\n    shape = infer_shape(data)\n    if axis >= len(shape):\n        msg = \"Please check input dim, it shouldn't be greater than or equal to rank.\"\n        raise AttributeError(msg)\n\n    selections = shape[axis]\n    res_split = _op.split(data, selections, axis)\n    ret = []\n    for i in range(selections):\n        ret.append(_op.squeeze(res_split[i], axis=[axis]))\n    return _expr.TupleWrapper(_expr.Tuple(ret), selections)\n\n\ndef rnn_cell(\n    input_seqs, hidden_state, w_inp, w_hid, b_inp=None, b_hid=None, backwards=False, act=_op.tanh\n):\n    \"\"\"\n    Common implementation of RNN cell for all frontends of TVM\n\n    Parameters\n    ----------\n    input_seqs : List[relay.Expr]\n        The sequence of input tensors\n        Input tensor should be 2d while issue #8412 is not resolved\n        Shape = (batch, feature_size)\n    hidden_state : relay.Expr\n        Hidden state. shape = (batch_size, hidden_size)\n    w_inp, w_hid: relay.Expr\n        weight matrices. shape = (hidden_size, feature_size), (hidden_size, feature_size)\n    b_inp, b_hid : relay.Expr\n        bias matrices. The same order of internal parts as for weights. shape = (1 * hidden_size)\n    backwards : bool\n        Flag for reverse pass of RNN\n    act : relay.op\n        activation function. It is tanh by default.\n\n    Returns\n    -------\n    result : List[relay.Expr], relay.Expr, relay.Expr\n        The sequence of computed result, final hidden and cell state\n    \"\"\"\n    outputs_list = []\n    for x_t in input_seqs if not backwards else reversed(input_seqs):\n        xwt = _op.nn.dense(x_t, w_inp)\n        hwt = _op.nn.dense(hidden_state, w_hid)\n        if b_inp is not None and b_hid is not None:\n            xwt += b_inp\n            hwt += b_hid\n        hidden_state = act(xwt + hwt)\n        outputs_list.append(hidden_state)  # [seq_num, (batch, hidden_size)]\n    return outputs_list, hidden_state\n\n\ndef gru_cell(\n    input_seqs,\n    hidden_state,\n    w_inp,\n    w_hid,\n    b_inp=None,\n    b_hid=None,\n    rz_act=_op.sigmoid,\n    n_act=_op.tanh,\n    backwards=False,\n    linear_before_reset=True,\n):\n    \"\"\"\n    Common implementation of GRU cell for all frontends of TVM\n    TODO(vvchernov): currently it is used by pytorch and ONNX. Extend for other frontends\n\n    Parameters\n    ----------\n    input_seqs : List[relay.Expr]\n        The sequence of input tensors\n        Input tensor should be 2d while issue #8412 is not resolved\n        Shape = (batch, feature_size)\n    hidden_state : relay.Expr\n        Hidden state. shape = (batch_size, hidden_size)\n    w_inp, w_hid : relay.Expr\n        weight matrices. wi shape = (3 * hidden_size, feature_size)\n        wh shape = (3 * hidden_size, hidden_size)\n        NOTE: wi = (w_ir|w_iz|w_in) for reset, update and new gates.\n        The order is important for correct GRU calculation!\n    b_inp, b_hid : relay.Expr\n        bias matrices. The same order of internal parts as for weights. shape = (3 * hidden_size)\n    r_act : relay.op\n        activation function for reset gate. it is sigmoid by default\n    z_act : relay.op\n        activation function for update gate. it is sigmoid by default\n    n_act : relay.op\n        activation function for new gate. it is tanh by default\n    backwards : bool\n        Flag for reverse pass of GRU\n\n    Returns\n    -------\n    result : List[relay.Expr], relay.Expr, relay.Expr\n        The sequence of computed result, final hidden and cell state\n    \"\"\"\n\n    outputs_list = []\n    for x_t in input_seqs if not backwards else reversed(input_seqs):\n        xwt = _op.nn.dense(x_t, w_inp)\n        if linear_before_reset:\n            hwt = _op.nn.dense(hidden_state, w_hid)\n            if b_inp is not None and b_hid is not None:\n                xwt += b_inp\n                hwt += b_hid\n            i_r, i_z, i_n = _op.split(xwt, 3, axis=-1)\n            h_r, h_z, h_n = _op.split(hwt, 3, axis=-1)\n            r_gate = rz_act(i_r + h_r)\n            z_gate = rz_act(i_z + h_z)\n            n_gate = n_act(i_n + r_gate * h_n)\n        else:\n            i_r, i_z, i_n = _op.split(xwt, 3, axis=1)\n            w_hr, w_hz, w_hn = _op.split(w_hid, 3, axis=0)\n            r_gate = i_r + _op.nn.dense(hidden_state, w_hr)\n            z_gate = i_z + _op.nn.dense(hidden_state, w_hz)\n            if b_inp is not None and b_hid is not None:\n                b_ir, b_iz, b_in = _op.split(b_inp, 3, axis=-1)\n                b_hr, b_hz, b_hn = _op.split(b_hid, 3, axis=-1)\n                r_gate += b_ir + b_hr\n                r_gate = rz_act(r_gate)\n                z_gate += b_iz + b_hz\n                i_n += b_in\n                h_n = _op.nn.dense((r_gate * hidden_state), w_hn) + b_hn\n            else:\n                r_gate = rz_act(r_gate)\n                h_n = _op.nn.dense((r_gate * hidden_state), w_hn)\n            z_gate = rz_act(z_gate)\n            n_gate = n_act(i_n + h_n)\n\n        hidden_state = (hidden_state - n_gate) * z_gate + n_gate\n\n        outputs_list.append(hidden_state)  # [seq_num, (batch, hidden_size)]\n\n    return outputs_list, hidden_state\n\n\ndef lstm_cell(\n    input_seqs,\n    hidden_state,\n    cell_state,\n    w_inp,\n    w_hid,\n    b_inp=None,\n    b_hid=None,\n    proj=None,\n    p_i=None,\n    p_f=None,\n    p_o=None,\n    f_act=_op.sigmoid,\n    g_act=_op.tanh,\n    h_act=_op.tanh,\n    backwards=False,\n):\n    \"\"\"\n    Common implementation of LSTM cell for all frontends of TVM\n    TODO (vvchernov): currently it is used by onnx and pytorch. Extend for other frontends\n\n    Parameters\n    ----------\n    input_seqs : List[relay.Expr]\n        The sequence of input tensors\n        Input tensor should be 2d while issue #8412 is not resolved\n        Shape = (batch, feature_size)\n    hidden_state : relay.Expr\n        Hidden state. shape = (batch, hidden_size)\n    cell_state : relay.Expr\n        Cell state. shape = (batch, hidden_size)\n    w_inp, w_hid : relay.Expr\n        weight matrices. wi shape = (4 * hidden_size, feature_size)\n        wh shape = (4 * hidden_size, hidden_size or proj_size)\n        NOTE: wi = (w_ii|w_if|w_ig|w_io) for input, forget, cell and output gates.\n        The order is important for correct LSTM calculation!\n    b_inp, b_hid : relay.Expr\n        bias matrices. The same order of internal parts as for weights. shape = (4 * hidden_size)\n    proj : relay.Expr\n        projection matrix. shape = (proj_size, hidden_size)\n    p_i, p_f, p_o : relay.Expr\n        peephole LSTM matrices. shape = (batch, hidden_size)\n    f_act, g_act, h_act : relay.op\n        activation functions\n    backwards : bool\n        Flag for reverse pass of LSTM\n\n    Returns\n    -------\n    result : List[relay.Expr], relay.Expr, relay.Expr\n        The sequence of computed result, final hidden and cell state\n    \"\"\"\n\n    outputs_list = []\n    for x_t in input_seqs if not backwards else reversed(input_seqs):\n        # x_t shape = (batch, feature size), step shape = (batch, feature size + hidden_size)\n        step = _op.concatenate([x_t, hidden_state], axis=1)\n        cat_w = _op.concatenate([w_inp, w_hid], axis=1)\n        # Instead of nn.dense(x_t, w_inp) + nn.dense(hidden_state, w_hid)\n        # nn.dense(step, cat_w) is used\n        # gates shape = (batch, 4 * hidden_size)\n        gates = _op.nn.dense(step, cat_w)\n        # Add biases\n        if b_inp is not None:\n            gates += b_inp\n        if b_hid is not None:\n            gates += b_hid\n        # any gate shape = (batch, hidden_size)\n        inp_gate, fgt_gate, cell_gate, otp_gate = _op.split(gates, 4, axis=-1)\n\n        if p_i is not None and p_f is not None:\n            inp_gate = f_act(inp_gate + p_i * cell_state)\n            fgt_gate = f_act(fgt_gate + p_f * cell_state)\n        else:\n            inp_gate = f_act(inp_gate)\n            fgt_gate = f_act(fgt_gate)\n\n        cell_gate = g_act(cell_gate)\n        cell_state = fgt_gate * cell_state + inp_gate * cell_gate\n        if p_o is not None:\n            otp_gate = f_act(otp_gate + p_o * cell_state)\n        else:\n            otp_gate = f_act(otp_gate)\n\n        hidden_state = otp_gate * h_act(cell_state)\n\n        if proj is not None:\n            hidden_state = _op.nn.dense(hidden_state, proj)\n\n        outputs_list.append(hidden_state)  # [seq_num, (batch, hidden_size)]\n\n    return outputs_list, hidden_state, cell_state\n\n\ndef autopad(\n    data,\n    strides,\n    kernel_shape,\n    dilations=(1, 1),\n    pad_type=\"constant\",\n    deconv=False,\n    mode=\"SAME_UPPER\",\n    pad_value=0.0,\n):\n    \"\"\"\n    Perform autopadding with dynamic input shapes\n    \"\"\"\n    # get attributes as constants\n    strides = _op.const(np.array(strides), dtype=\"int64\")\n    dilated_kernel_shape = _op.const(\n        np.array(\n            [(kernel - 1) * dilation + 1 for kernel, dilation in zip(kernel_shape, dilations)]\n        ),\n        dtype=\"int64\",\n    )\n    # get input shape\n    ndim = len(infer_shape(data))\n    shape = _op.strided_slice(shape_of(data, dtype=\"int64\"), [2], [ndim])\n\n    # set up integer constants\n    zero = _op.const(0, dtype=\"int64\")\n    one = _op.const(1, dtype=\"int64\")\n    two = _op.const(2, dtype=\"int64\")\n\n    # Calculate total padding\n    mod = _op.mod(shape, strides)\n\n    left = _op.maximum(dilated_kernel_shape - strides, zero)\n    right = _op.maximum(dilated_kernel_shape - mod, zero)\n\n    total_pad = _op.where(_op.equal(mod, zero), left, right)\n    if deconv:\n        total_pad = _op.const(np.array(kernel_shape), dtype=\"int64\") - one - total_pad\n\n    # split total padding into before and after\n    pad_before = _op.floor_divide(total_pad, two)\n    pad_after = total_pad - pad_before\n\n    # combine\n    if \"LOWER\" in mode:\n        pad = _op.concatenate(\n            [_op.reshape(pad_after, [-1, 1]), _op.reshape(pad_before, [-1, 1])], axis=1\n        )\n    else:\n        pad = _op.concatenate(\n            [_op.reshape(pad_before, [-1, 1]), _op.reshape(pad_after, [-1, 1])], axis=1\n        )\n\n    # pad N and C with zeros\n    pad = _op.concatenate([_op.const(np.zeros([2, 2], dtype=\"int64\"), dtype=\"int64\"), pad], axis=0)\n\n    if isinstance(pad_value, (float, int)):\n        pad_value = _op.const(pad_value)\n\n    return _op.nn.pad(data, fold_constant(pad), pad_value, pad_type)\n\n\ndef ensure_scalar_shape(x):\n    \"\"\"\n    Assume that `x` is a tensor with one element (regardless of tensor rank).\n    Return a version of that tensor with rank 0.\n    \"\"\"\n    x_shape = infer_shape(x)\n    x_rank = len(x_shape)\n\n    if x_rank == 0:\n        return x\n\n    num_elem = np.prod(x_shape)\n    assert num_elem == 1, \"Cannot squeeze tensor shape {} to scalar form.\".format(x_shape)\n\n    return _op.squeeze(x)\n\n\ndef try_resolve_var_to_const(x, graph_params):\n    \"\"\"\n    Try to resolve the value of tensor `x` to a specific value.\n    If successful, return a Const op with that value.\n    If unsuccessful, simply return `x`.\n    \"\"\"\n    if isinstance(x, _expr.Var) and x.name_hint in graph_params:\n        value = graph_params[x.name_hint].numpy()\n        dtype = infer_type(x).checked_type.dtype\n        return _op.const(value, dtype)\n\n    return x\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/coreml.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, unused-argument, unused-variable, no-else-return\n# pylint: disable=inconsistent-return-statements, import-outside-toplevel\n\"\"\"CoreML frontend.\"\"\"\nimport math\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom ... import nd as _nd\nfrom ..._ffi import base as _base\nfrom .common import ExprTable\nfrom .common import infer_shape as _infer_shape\n\n__all__ = [\"from_coreml\"]\n\n\ndef _NeuralNetworkImageScaler(op, inexpr, etab):\n    # TODO: we need to support more colorspace, such as rgb.\n    # this changes the symbol\n    biases = np.array([op.blueBias, op.greenBias, op.redBias]).reshape([3, 1, 1])\n    bias = etab.new_const(biases)\n    ret = _op.multiply(inexpr, _expr.const(op.channelScale, dtype=\"float32\"))\n    ret = _op.add(ret, bias)\n    return ret\n\n\ndef _NeuralNetworkMeanImage(op, inexpr, etab):\n    # this changes the symbol\n    ret = _op.subtract(inexpr, _expr.const(op.meanImage, dtype=\"float32\"))\n    return ret\n\n\ndef _ConvolutionLayerParams(op, inexpr, etab):\n    \"\"\"Convolution layer params.\"\"\"\n    if op.isDeconvolution:\n        weights = etab.new_const(\n            np.array(list(op.weights.floatValue)).reshape(\n                tuple([op.kernelChannels, op.outputChannels] + list(op.kernelSize))\n            )\n        )\n    else:\n        weights = etab.new_const(\n            np.array(list(op.weights.floatValue)).reshape(\n                tuple([op.outputChannels, op.kernelChannels] + list(op.kernelSize))\n            )\n        )\n    dilation = list(op.dilationFactor)\n    if not dilation:\n        dilation = [1, 1]\n    N, C, H, W = _infer_shape(inexpr)\n    params = {\n        \"channels\": op.outputChannels,\n        \"kernel_size\": list(op.kernelSize),\n        \"strides\": list(op.stride),\n        \"dilation\": dilation,\n        \"groups\": op.nGroups,\n    }\n\n    if op.WhichOneof(\"ConvolutionPaddingType\") == \"valid\":\n        valid = op.valid\n        if valid.paddingAmounts.borderAmounts:\n            assert len(valid.paddingAmounts.borderAmounts) == 2\n            pad_t = valid.paddingAmounts.borderAmounts[0].startEdgeSize\n            pad_l = valid.paddingAmounts.borderAmounts[1].startEdgeSize\n            pad_b = valid.paddingAmounts.borderAmounts[0].endEdgeSize\n            pad_r = valid.paddingAmounts.borderAmounts[1].endEdgeSize\n            if not all(v == 0 for v in (pad_t, pad_l, pad_b, pad_r)):\n                params[\"padding\"] = (pad_t, pad_l, pad_b, pad_r)\n    elif op.WhichOneof(\"ConvolutionPaddingType\") == \"same\":\n        assert op.same.asymmetryMode == 0, (\n            \"Only support BOTTOM_RIGHT_HEAVY mode, \" \"which is used by tf/caffe and so on\"\n        )\n        kernel = params[\"kernel_size\"]\n        strides = params[\"strides\"]\n        pad_t, pad_b = get_pad_value(H, kernel[0], strides[0])\n        pad_l, pad_r = get_pad_value(W, kernel[1], strides[1])\n        params[\"padding\"] = (pad_t, pad_l, pad_b, pad_r)\n    else:\n        raise NotImplementedError(\"Valid/Same convolution padding implemented\")\n\n    if op.isDeconvolution:\n        ret = _op.nn.conv2d_transpose(data=inexpr, weight=weights, **params)\n    else:\n        ret = _op.nn.conv2d(data=inexpr, weight=weights, **params)\n    if op.hasBias:\n        biases = etab.new_const(list(op.bias.floatValue))\n        ret = _op.nn.bias_add(ret, biases)\n\n    return ret\n\n\ndef _BatchnormLayerParams(op, inexpr, etab):\n    \"\"\"Get layer of batchnorm parameter\"\"\"\n    # this changes the symbol\n    if op.instanceNormalization:\n        raise tvm.error.OpNotImplemented(\n            'Operator \"instance normalization\" is not supported in frontend CoreML.'\n        )\n    params = {\n        \"gamma\": etab.new_const(list(op.gamma.floatValue)),\n        \"beta\": etab.new_const(list(op.beta.floatValue)),\n        \"moving_mean\": etab.new_const(list(op.mean.floatValue)),\n        \"moving_var\": etab.new_const(list(op.variance.floatValue)),\n        \"epsilon\": op.epsilon,\n    }\n    result, moving_mean, moving_var = _op.nn.batch_norm(data=inexpr, **params)\n    return result\n\n\ndef _ActivationParams(op, inexpr, etab):\n    \"\"\"Get activation parameters\"\"\"\n    whichActivation = op.WhichOneof(\"NonlinearityType\")\n    par = getattr(op, whichActivation)\n    if whichActivation == \"linear\":\n        alpha = _expr.const(par.alpha, dtype=\"float32\")\n        beta = _expr.const(par.beta, dtype=\"float32\")\n        return _op.add(_op.multiply(inexpr, alpha), beta)\n    if whichActivation == \"ReLU\":\n        return _op.nn.relu(inexpr)\n    if whichActivation == \"leakyReLU\":\n        return _op.nn.leaky_relu(inexpr, alpha=par.alpha)\n    elif whichActivation == \"thresholdedReLU\":\n        alpha_tensor = _op.full_like(inexpr, fill_value=_expr.const(par.alpha, dtype=\"float32\"))\n        return _op.multiply(inexpr, _op.greater(inexpr, alpha_tensor).as_type(\"float32\"))\n    if whichActivation == \"PReLU\":\n        return _op.nn.prelu(inexpr, alpha=_expr.const(par.alpha, dtype=\"float32\"))\n    if whichActivation == \"tanh\":\n        return _op.tanh(inexpr)\n    if whichActivation == \"scaledTanh\":\n        alpha = _expr.const(par.alpha, dtype=\"float32\")\n        beta = _expr.const(par.beta, dtype=\"float32\")\n        return _op.multiply(_op.tanh(_op.multiply(inexpr, beta)), alpha)\n    if whichActivation == \"sigmoid\":\n        return _op.sigmoid(inexpr)\n    if whichActivation == \"sigmoidHard\":\n        alpha = _expr.const(par.alpha, dtype=\"float32\")\n        beta = _expr.const(par.beta, dtype=\"float32\")\n        transformX = (alpha * inexpr) + beta\n        return _op.clip(transformX, a_min=0.0, a_max=1.0)\n    if whichActivation == \"ELU\":\n        return _op.multiply(\n            _op.add(_op.exp(inexpr), _expr.const(-1, dtype=\"float32\")),\n            _expr.const(par.alpha, dtype=\"float32\"),\n        )\n    if whichActivation == \"softsign\":\n        return inexpr / (\n            _expr.const(1, dtype=\"float32\")\n            + (op.nn.relu(inexpr) + _op.nn.relu(_op.negative(inexpr)))\n        )\n    if whichActivation == \"softplus\":\n        return _op.log(_op.add(_op.exp(inexpr), _expr.const(1, dtype=\"float32\")))\n    if whichActivation == \"parametricSoftplus\":\n        alpha = list(par.alpha.floatValue)\n        beta = list(par.alpha.floatValue)\n        if len(alpha) == 1:\n            return _op.multiply(\n                _op.log(_op.add(_op.exp(inexpr), _expr.const(beta[0], dtype=\"float32\"))),\n                _expr.const(alpha[0], dtype=\"float32\"),\n            )\n        alpha = np.array(alpha).reshape((len(alpha), 1, 1))\n        beta = np.array(beta).reshape((len(beta), 1, 1))\n        alpha_expr = etab.new_const(alpha)\n        beta_expr = etab.new_const(beta)\n        return _op.multiply(_op.log(_op.add(_op.exp(inexpr), beta_expr)), alpha_expr)\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} is not supported in frontend CoreML.\".format(whichActivation)\n    )\n\n\ndef _ScaleLayerParams(op, inexpr, etab):\n    \"\"\"Scale layer params.\"\"\"\n    scale = etab.new_const(\n        np.array(list(op.scale.floatValue)).reshape(tuple(list(op.shapeScale) + [1, 1]))\n    )\n    ret = _op.multiply(inexpr, scale)\n    if op.hasBias:\n        bias = etab.new_const(\n            np.array(list(op.bias.floatValue)).reshape(tuple(list(op.shapeBias) + [1, 1]))\n        )\n        ret = _op.add(ret, bias)\n    return ret\n\n\ndef _PoolingLayerParams(op, inexpr, etab):\n    \"\"\"get pooling parameters\"\"\"\n    if op.globalPooling:\n        if op.type == 0:\n            return _op.nn.global_max_pool2d(inexpr)\n        if op.type == 1:\n            return _op.nn.global_avg_pool2d(inexpr)\n        raise tvm.error.OpNotImplemented(\n            \"Only Max and Average Pooling are supported in frontend CoreML.\"\n        )\n\n    params = {\"pool_size\": list(op.kernelSize), \"strides\": list(op.stride)}\n\n    if op.WhichOneof(\"PoolingPaddingType\") == \"valid\":\n        valid = op.valid\n        if valid.paddingAmounts.borderAmounts:\n            assert len(valid.paddingAmounts.borderAmounts) == 2\n            pad_t = valid.paddingAmounts.borderAmounts[0].startEdgeSize\n            pad_l = valid.paddingAmounts.borderAmounts[1].startEdgeSize\n            pad_b = valid.paddingAmounts.borderAmounts[0].endEdgeSize\n            pad_r = valid.paddingAmounts.borderAmounts[1].endEdgeSize\n            if not all(v == 0 for v in (pad_t, pad_l, pad_b, pad_r)):\n                params[\"padding\"] = [pad_t, pad_l, pad_b, pad_r]\n    elif op.WhichOneof(\"PoolingPaddingType\") == \"includeLastPixel\":\n        # I don't know if this is correct\n        valid = op.includeLastPixel\n        padding = list(valid.paddingAmounts)\n        params[\"padding\"] = padding\n        params[\"ceil_mode\"] = True\n    else:\n        msg = \"PoolingPaddingType {} is not supported in operator Pooling.\"\n        op_name = op.WhichOneof(\"PoolingPaddingType\")\n        raise tvm.error.OpAttributeUnImplemented(msg.format(op_name))\n\n    if op.type == 0:\n        return _op.nn.max_pool2d(inexpr, **params)\n    if op.type == 1:\n        return _op.nn.avg_pool2d(inexpr, **params)\n    raise tvm.error.OpNotImplemented(\"Only Max and Average Pooling are supported in CoreML.\")\n\n\ndef _SoftmaxLayerParams(op, inexpr, etab):\n    return _op.nn.softmax(_op.nn.batch_flatten(inexpr))\n\n\ndef _InnerProductLayerParams(op, inexpr, etab):\n    weights = etab.new_const(\n        np.array(op.weights.floatValue).reshape((op.outputChannels, op.inputChannels))\n    )\n    out = _op.nn.dense(data=inexpr, weight=weights, units=op.outputChannels)\n    if op.hasBias:\n        bias = etab.new_const(np.array(op.bias.floatValue))\n        out = _op.nn.bias_add(out, bias)\n    return out\n\n\ndef _AddLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list):\n        inexpr = [inexpr]\n    ret = inexpr[0]\n    for i in range(1, len(inexpr)):\n        ret = _op.add(ret, inexpr[i])\n    if op.alpha > 0:\n        ret = _op.add(ret, _expr.const(op.alpha, dtype=\"float32\"))\n    return ret\n\n\ndef _MultiplyLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list):\n        inexpr = [inexpr]\n    ret = inexpr[0]\n    for i in range(1, len(inexpr)):\n        ret = _op.multiply(ret, inexpr[i])\n    if op.alpha != 1:\n        ret = _op.multiply(ret, _expr.const(op.alpha, dtype=\"float32\"))\n    return ret\n\n\ndef _ConcatLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list):\n        inexpr = [inexpr]\n    if op.sequenceConcat:\n        raise tvm.error.OpNotImplemented(\n            \"Operator Sequence Concat is not supported in frontend CoreML.\"\n        )\n    ret = _op.concatenate(inexpr, axis=1)\n    return ret\n\n\ndef _FlattenLayerParams(op, inexpr, etab):\n    if op.mode == 1:\n        inexpr = _op.transpose(_op.reshape(inexpr, newshape=(0, 0, -1)), axes=(0, 2, 1))\n    return _op.nn.batch_flatten(inexpr)\n\n\ndef _PaddingLayerParams(op, inexpr, etab):\n    \"\"\"Padding layer params.\"\"\"\n    if op.WhichOneof(\"PaddingType\") == \"constant\":\n        constant = op.constant\n        if constant.value != 0:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"{} is not supported in operator Padding.\".format(constant.value)\n            )\n        pad_t = op.paddingAmounts.borderAmounts[0].startEdgeSize\n        pad_l = op.paddingAmounts.borderAmounts[1].startEdgeSize\n        pad_b = op.paddingAmounts.borderAmounts[0].endEdgeSize\n        pad_r = op.paddingAmounts.borderAmounts[1].endEdgeSize\n        return _op.nn.pad(data=inexpr, pad_width=((0, 0), (0, 0), (pad_t, pad_b), (pad_l, pad_r)))\n    raise tvm.error.OpNotImplemented(\"Non-constant padding is not supported in frontend CoreML.\")\n\n\ndef _PermuteLayerParams(op, inexpr, etab):\n    axes = tuple(op.axis)\n    return _op.transpose(inexpr, axes=axes)\n\n\ndef _UpsampleLayerParams(op, inexpr, etab):\n    if op.scalingFactor[0] != op.scalingFactor[1]:\n        raise tvm.error.OpAttributeUnimplemented(\"Upsample height and width must be equal.\")\n    interpolationMode = \"nearest_neighbor\" if op.mode == 0 else \"bilinear\"\n    return _op.nn.upsampling(\n        inexpr, scale_h=op.scalingFactor[0], scale_w=op.scalingFactor[1], method=interpolationMode\n    )\n\n\ndef _L2NormalizeLayerParams(op, inexpr, etab):\n    return _op.nn.l2_normalize(inexpr, eps=op.epsilon, axis=[1])\n\n\ndef _LRNLayerParams(op, inexpr, etab):\n    par = {}\n    par[\"size\"] = op.localSize\n    par[\"bias\"] = op.k\n    par[\"alpha\"] = op.alpha\n    par[\"beta\"] = op.beta\n    par[\"axis\"] = 1  # default layout is nchw\n    return _op.nn.lrn(data=inexpr, **par)\n\n\ndef _AverageLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list) or len(inexpr) < 2:\n        raise ValueError(\"Expect minimum 2 inputs\")\n    count = len(inexpr)\n    _sum = inexpr[0]\n    for i in range(1, count):\n        _sum = _op.add(_sum, inexpr[i])\n    return _sum / _expr.const(count, dtype=\"float32\")\n\n\ndef _MaxLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list) or len(inexpr) < 2:\n        raise ValueError(\"Expect minimum 2 inputs\")\n    _max = inexpr[0]\n    for i in range(1, len(inexpr)):\n        _max = _op.maximum(_max, inexpr[i])\n    return _max\n\n\ndef _MinLayerParams(op, inexpr, etab):\n    if not isinstance(inexpr, list) or len(inexpr) < 2:\n        raise ValueError(\"Expect minimum 2 inputs\")\n    _min = inexpr[0]\n    for i in range(1, len(inexpr)):\n        _min = _op.minimum(_min, inexpr[i])\n    return _min\n\n\ndef _UnaryFunctionLayerParams(op, inexpr, etab):\n    op_type = op.type\n    if op_type == op.SQRT:\n        return _op.sqrt(inexpr)\n    elif op_type == op.RSQRT:\n        epsilon = _expr.const(op.epsilon)\n        return _op.rsqrt(inexpr + epsilon)\n    elif op_type == op.INVERSE:\n        epsilon = _expr.const(op.epsilon)\n        return _expr.const(1.0) / (inexpr + epsilon)\n    elif op_type == op.POWER:\n        alpha = _expr.const(op.alpha)\n        return _op.power(inexpr, alpha)\n    elif op_type == op.EXP:\n        return _op.exp(inexpr)\n    elif op_type == op.LOG:\n        return _op.log(inexpr)\n    elif op_type == op.ABS:\n        return _op.abs(inexpr)\n    elif op_type == op.THRESHOLD:\n        alpha = _expr.const(op.alpha)\n        return _op.maximum(inexpr, alpha)\n    else:\n        msg = \"Unary Op type value {} is not supported in frontend CoreML.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(op_type))\n\n\ndef _ReduceLayerParams(op, inexpr, etab):\n    axis = op.axis\n    if axis == op.CHW:\n        axis = [-3, -2, -1]\n    elif axis == op.HW:\n        axis = [-2, -1]\n    elif axis == op.C:\n        axis = -3\n    elif axis == op.H:\n        axis = -2\n    elif axis == op.W:\n        axis = -1\n    else:\n        msg = \"Reduce axis value {} is not supported in frontend CoreML.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(axis))\n\n    mode = op.mode\n    if mode == op.SUM:\n        return _op.sum(inexpr, axis=axis, keepdims=True)\n    elif mode == op.AVG:\n        return _op.mean(inexpr, axis=axis, keepdims=True)\n    elif mode == op.PROD:\n        return _op.prod(inexpr, axis=axis, keepdims=True)\n    elif mode == op.MIN:\n        return _op.min(inexpr, axis=axis, keepdims=True)\n    elif mode == op.MAX:\n        return _op.max(inexpr, axis=axis, keepdims=True)\n    elif mode == op.ARGMAX:\n        return _op.argmax(inexpr, axis=axis, keepdims=True)\n    else:\n        msg = \"Reduce mode value {} is not supported in frontend CoreML.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(mode))\n\n\ndef _ReshapeLayerParams(op, inexpr, etab):\n    return _op.reshape(inexpr, op.targetShape)\n\n\ndef _SplitLayerParams(op, inexpr, etab):\n    return _op.split(inexpr, op.nOutputs, axis=-3)\n\n\n_convert_map = {\n    \"NeuralNetworkMeanImage\": _NeuralNetworkMeanImage,\n    \"NeuralNetworkImageScaler\": _NeuralNetworkImageScaler,\n    \"ConvolutionLayerParams\": _ConvolutionLayerParams,\n    \"BatchnormLayerParams\": _BatchnormLayerParams,\n    \"ActivationParams\": _ActivationParams,\n    \"ScaleLayerParams\": _ScaleLayerParams,\n    \"PoolingLayerParams\": _PoolingLayerParams,\n    \"SoftmaxLayerParams\": _SoftmaxLayerParams,\n    \"InnerProductLayerParams\": _InnerProductLayerParams,\n    \"AddLayerParams\": _AddLayerParams,\n    \"MultiplyLayerParams\": _MultiplyLayerParams,\n    \"FlattenLayerParams\": _FlattenLayerParams,\n    \"ConcatLayerParams\": _ConcatLayerParams,\n    \"PaddingLayerParams\": _PaddingLayerParams,\n    \"PermuteLayerParams\": _PermuteLayerParams,\n    \"UpsampleLayerParams\": _UpsampleLayerParams,\n    \"L2NormalizeLayerParams\": _L2NormalizeLayerParams,\n    \"LRNLayerParams\": _LRNLayerParams,\n    \"AverageLayerParams\": _AverageLayerParams,\n    \"MaxLayerParams\": _MaxLayerParams,\n    \"MinLayerParams\": _MinLayerParams,\n    \"UnaryFunctionLayerParams\": _UnaryFunctionLayerParams,\n    \"ReduceLayerParams\": _ReduceLayerParams,\n    \"ReshapeLayerParams\": _ReshapeLayerParams,\n    \"SplitLayerParams\": _SplitLayerParams,\n}\n\n# SAME padding: https://www.tensorflow.org/api_guides/python/nn\ndef get_pad_value(data, kernel, stride):\n    \"\"\"Get the pad tuple of value for SAME padding\n\n    Parameters\n    ----------\n    data:\n        1D input data\n\n    kernel:\n        1D input kernel\n\n    stride:\n        1D input stride\n\n    Returns\n    -------\n        pad tuple of value\n    \"\"\"\n\n    out = int(math.ceil(float(data) / float(stride)))\n    pad = max(0, (out - 1) * stride + kernel - data)\n    pad_before = pad // 2\n    pad_after = pad - pad_before\n    return pad_before, pad_after\n\n\ndef coreml_op_to_relay(op, inname, outnames, etab):\n    \"\"\"Convert coreml layer to a Relay expression and update the expression table.\n\n    Parameters\n    ----------\n    op: a coreml protobuf bit\n\n    inname : str or list of str\n        Name of the input Relay expression.\n\n    outnames : str or list of str\n        Name of the output Relay expression.\n\n    etab : relay.frontend.common.ExprTable\n        The global expression table to be updated.\n    \"\"\"\n    classname = type(op).__name__\n    if classname not in _convert_map:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported in frontend CoreML.\".format(classname)\n        )\n    if isinstance(inname, _base.string_types):\n        insym = etab.get_expr(inname)\n    else:\n        insym = [etab.get_expr(i) for i in inname]\n    outs = _convert_map[classname](op, insym, etab)\n\n    if outnames:\n        if isinstance(outnames, _base.string_types) or len(outnames) == 1:\n            outname = outnames if isinstance(outnames, _base.string_types) else outnames[0]\n            etab.set_expr(outname, outs, force_override=True)\n        else:\n            # the number of outputs from model op and tvm relay must be same\n            assert len(outnames) == len(outs)\n            for outname, out in zip(outnames, outs):\n                etab.set_expr(outname, out, force_override=True)\n\n\ndef from_coreml(model, shape=None):\n    \"\"\"Convert from coreml model into Relay Function.\n\n    Parameters\n    ----------\n    model:\n        coremltools.models.MLModel of a NeuralNetworkClassifier\n\n    shape : dict of str to int list/tuple, optional\n        The input shapes\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation.\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by Relay.\n    \"\"\"\n    try:\n        import coremltools as cm\n    except ImportError:\n        raise ImportError(\"The coremltools package must be installed\")\n\n    assert isinstance(model, cm.models.MLModel)\n    spec = model.get_spec()\n    modeltype = spec.WhichOneof(\"Type\")\n    assert modeltype in [\"neuralNetworkClassifier\", \"neuralNetwork\", \"neuralNetworkRegressor\"]\n    cc = getattr(spec, modeltype)\n\n    etab = ExprTable()\n    for i in spec.description.input:\n        input_shape = list(shape[i.name]) if shape is not None and i.name in shape else None\n        etab.set_expr(i.name, _expr.var(i.name, shape=input_shape))\n\n    for pp in cc.preprocessing:\n        whichpp = pp.WhichOneof(\"preprocessor\")\n        ppmethod = getattr(pp, whichpp)\n        if whichpp == \"scaler\":\n            # Be careful we maybe only preprocess one input when we have multi inputs\n            # which is stored in pp.featureName. See unit testing verify_image_scaler\n            # in test_forward.py for CoreML.\n            for i in spec.description.input:\n                # we have multi inputs\n                if len(spec.description.input) > 1:\n                    assert pp.featureName != \"\"\n                    if i.name == pp.featureName:\n                        coreml_op_to_relay(ppmethod, i.name, i.name, etab)\n                else:\n                    assert pp.featureName == \"\"\n                    coreml_op_to_relay(ppmethod, i.name, i.name, etab)\n        else:\n            coreml_op_to_relay(ppmethod, pp.featureName, pp.featureName, etab)\n\n    for l in cc.layers:\n        layertype = l.WhichOneof(\"layer\")\n        layerop = getattr(l, layertype)\n        if len(l.input) == 1:\n            coreml_op_to_relay(layerop, l.input[0], l.output, etab)\n        else:\n            coreml_op_to_relay(layerop, list(l.input), l.output, etab)\n\n    outexpr = [\n        etab.get_expr(o.name) if o.name in etab.exprs else _expr.var(o.name)\n        for o in spec.description.output\n    ]\n\n    # check there are multiple outputs in the model and all are there in etab\n    multi_out = all([bool(o.name in etab.exprs) for o in spec.description.output])\n    outexpr = _expr.Tuple(outexpr) if multi_out else outexpr[0]\n\n    func = _function.Function(analysis.free_vars(outexpr), outexpr)\n    params = {k: _nd.array(np.array(v, dtype=np.float32)) for k, v in etab.params.items()}\n    return IRModule.from_expr(func), params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/darknet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"\nDarkNet symbol frontend for Relay.\n\"\"\"\n\nfrom enum import Enum\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .common import get_relay_op, new_var\n\n__all__ = [\"from_darknet\"]\n\n\ndef _darknet_not_support(attr, op=\"relay\"):\n    \"\"\"Raise error if any operation is not supported.\"\"\"\n    err = \"{} is not supported in {}.\".format(attr, op)\n    raise NotImplementedError(err)\n\n\ndef _get_params_prefix(opname, layer_num):\n    \"\"\"Makes the params prefix name from opname and layer number.\"\"\"\n    return str(opname).replace(\".\", \"_\") + str(layer_num)\n\n\ndef _get_params_name(prefix, item):\n    \"\"\"Makes the params name for the k,v pair.\"\"\"\n    return prefix + \"_\" + item\n\n\ndef _get_param_var(params, prefix, item):\n    name = _get_params_name(prefix, item)\n    if name not in params:\n        raise AttributeError(\"{} not found in params dict.\".format(name))\n    return new_var(name, shape=params[name].shape, dtype=params[name].dtype)\n\n\ndef _darknet_maxpooling(inputs, params, attrs, prefix):\n    \"\"\"Process the max pool 2d operation.\"\"\"\n    new_attrs = {}\n    kernel = attrs.get(\"kernel\")\n    strides = attrs.get(\"stride\", 1)\n    pads = attrs.get(\"pad\", 1)\n    new_attrs[\"pool_size\"] = (kernel, kernel)\n    new_attrs[\"strides\"] = (strides, strides)\n    new_attrs[\"padding\"] = (pads, pads)\n    extra_pad_size = attrs.get(\"extra_pad_size\", 0)\n    if extra_pad_size:\n        pad_width = ((0, 0), (0, 0), (0, extra_pad_size), (0, extra_pad_size))\n        inputs = [\n            get_relay_op(\"pad\")(*inputs, pad_width=pad_width, pad_value=np.finfo(np.float32).min)\n        ]\n    return get_relay_op(\"max_pool2d\")(*inputs, **new_attrs)\n\n\ndef _darknet_avgpooling(inputs, params, attrs, prefix):\n    \"\"\"Process the average pool 2d operation.\"\"\"\n    new_attrs = {}\n    kernel = attrs.get(\"kernel\")\n    strides = attrs.get(\"stride\", 1)\n    pads = attrs.get(\"pad\", 0)\n\n    new_attrs[\"pool_size\"] = (kernel, kernel)\n    new_attrs[\"strides\"] = (strides, strides)\n    new_attrs[\"padding\"] = (pads, pads)\n    return get_relay_op(\"avg_pool2d\")(*inputs, **new_attrs)\n\n\ndef _darknet_conv2d(inputs, params, attrs, prefix):\n    \"\"\"Process the convolution 2d operation.\"\"\"\n    new_attrs = {}\n    kernel = attrs.get(\"kernel\")\n    strides = attrs.get(\"stride\", 1)\n    pads = attrs.get(\"pad\", 0)\n\n    new_attrs[\"channels\"] = attrs.get(\"num_filter\")\n    new_attrs[\"kernel_size\"] = (kernel, kernel)\n    new_attrs[\"strides\"] = (strides, strides)\n    new_attrs[\"padding\"] = (pads, pads)\n    new_attrs[\"dilation\"] = attrs.get(\"dilate\", (1, 1))\n    new_attrs[\"groups\"] = attrs.get(\"num_group\", 1)\n\n    weight = _get_param_var(params, prefix, \"weight\")\n    out = get_relay_op(\"conv2d\")(*inputs, weight=weight, **new_attrs)\n\n    use_bias = not attrs.get(\"use_batchNorm\", False)\n    if use_bias:\n        new_attrs = {}\n        new_attrs[\"axis\"] = 1\n        bias = _get_param_var(params, prefix, \"bias\")\n        out = get_relay_op(\"bias_add\")(out, bias=bias, **new_attrs)\n    else:\n        new_attrs = {}\n        new_attrs[\"epsilon\"] = 0.000001\n        gamma = _get_param_var(params, prefix, \"gamma\")\n        beta = _get_param_var(params, prefix, \"beta\")\n        moving_mean = _get_param_var(params, prefix, \"moving_mean\")\n        moving_var = _get_param_var(params, prefix, \"moving_var\")\n        out = get_relay_op(\"batch_norm\")(out, gamma, beta, moving_mean, moving_var, **new_attrs)\n\n    if \"activation\" in attrs:\n        new_attrs = {}\n        new_attrs[\"activation\"] = attrs[\"activation\"]\n        new_attrs[\"slope\"] = 0.1\n        out = _darknet_activations(out, None, new_attrs)\n    return out\n\n\ndef _darknet_shortcut(inputs, params, attrs, prefix):\n    \"\"\"Process the shortcut operation.\"\"\"\n    input_0 = inputs[0]\n    input_1 = inputs[1]\n\n    input_0_channel = int(attrs[\"out_channel\"])\n    input_1_channel = int(attrs[\"add_out_channel\"])\n    input_0_size = int(attrs[\"out_size\"])\n    input_1_size = int(attrs[\"add_out_size\"])\n\n    if input_0_size > input_1_size:\n        scale = int(input_0_size / input_1_size)\n        input_1 = get_relay_op(\"upsampling\")(input_1, scale_h=scale, scale_w=scale)\n\n    elif input_0_size < input_1_size:\n        stride = int(input_1_size / input_0_size)\n        input_1 = get_relay_op(\"avg_pool2d\")(\n            input_1, pool_size=(1, 1), strides=(stride, stride), padding=(0, 0)\n        )\n\n    if input_0_channel != input_1_channel:\n        pad_channel = input_0_channel - input_1_channel\n        input_1 = get_relay_op(\"pad\")(\n            input_1, pad_width=((0, 0), (0, pad_channel), (0, 0), (0, 0)), pad_value=0.0\n        )\n    sym = input_0 + input_1\n    if \"activation\" in attrs:\n        new_attrs = {}\n        new_attrs[\"activation\"] = attrs[\"activation\"]\n        sym = _darknet_activations(sym, None, new_attrs)\n    return sym\n\n\ndef _darknet_dense(inputs, params, attrs, prefix):\n    \"\"\"Process the dense operation.\"\"\"\n    new_attrs = {}\n    new_attrs[\"units\"] = attrs.get(\"num_hidden\")\n    data = inputs[0]\n\n    if attrs.get(\"use_flatten\", False) is True:\n        data = get_relay_op(\"batch_flatten\")(data)\n\n    weight = _get_param_var(params, prefix, \"weight\")\n    data = get_relay_op(\"dense\")(data, weight, **new_attrs)\n\n    use_bias = attrs.get(\"use_bias\", False)\n    if use_bias:\n        bias = _get_param_var(params, prefix, \"bias\")\n        data = get_relay_op(\"bias_add\")(data, bias, axis=1)\n\n    if \"use_batchNorm\" in attrs:\n        new_attrs = {}\n        new_attrs[\"epsilon\"] = 0.000001\n        gamma = _get_param_var(params, prefix, \"gamma\")\n        beta = _get_param_var(params, prefix, \"beta\")\n        moving_mean = _get_param_var(params, prefix, \"moving_mean\")\n        moving_var = _get_param_var(params, prefix, \"moving_var\")\n        data = get_relay_op(\"batch_norm\")(data, gamma, beta, moving_mean, moving_var, **new_attrs)\n    if \"activation\" in attrs:\n        new_attrs = {}\n        new_attrs[\"activation\"] = attrs[\"activation\"]\n        data = _darknet_activations(data, None, new_attrs)\n    return data\n\n\ndef _darknet_dropout(inputs, params, attrs, prefix):\n    \"\"\"Process the dropout operation, its a blank operation.\"\"\"\n    new_attrs = {}\n    new_attrs[\"rate\"] = attrs.get(\"p\", 0.5)\n    return get_relay_op(\"dropout\")(*inputs, **new_attrs)\n\n\ndef _darknet_reshape(inputs, params, attrs, prefix):\n    \"\"\"Process the reshape operation.\"\"\"\n    new_attrs = {}\n    new_attrs[\"shape\"] = attrs.get(\"shape\")\n    return get_relay_op(\"reshape\")(*inputs, **new_attrs)\n\n\ndef _darknet_upsampling(inputs, params, attrs, prefix):\n    \"\"\"Process the upsampling operation.\"\"\"\n    new_attrs = {}\n    new_attrs[\"scale_h\"] = attrs.get(\"scale\", 1)\n    new_attrs[\"scale_w\"] = attrs.get(\"scale\", 1)\n    return get_relay_op(\"upsampling\")(*inputs, **new_attrs)\n\n\ndef _darknet_l2normalize(inputs, params, attrs, prefix):\n    \"\"\"Process the l2 normalization operation.\"\"\"\n    new_attrs = {}\n    new_attrs[\"eps\"] = attrs.get(\"eps\", 0.0)\n    new_attrs[\"axis\"] = [attrs.get(\"axis\", 1)]\n    return get_relay_op(\"l2_normalize\")(*inputs, **new_attrs)\n\n\ndef _darknet_softmax_output(inputs, params, attrs, prefix):\n    \"\"\"Process the softmax operation.\"\"\"\n    temperature = attrs.get(\"temperature\", 1)\n    data = inputs[0]\n    if temperature != 1:\n        data = data / _expr.const(float(temperature))\n\n    if attrs.get(\"use_flatten\", False) is True:\n        data = get_relay_op(\"batch_flatten\")(data)\n\n    new_attrs = {}\n    if attrs.get(\"multi_output\", False):\n        new_attrs[\"axis\"] = 1\n    return get_relay_op(\"softmax\")(data, **new_attrs)\n\n\ndef _darknet_route(inputs, params, attrs, prefix):\n    \"\"\"Process the route operation, which is equivalent to concat.\"\"\"\n    new_attrs = {\"axis\": attrs.get(\"dim\", 1)}\n    return get_relay_op(\"concatenate\")((inputs[0], inputs[1]), **new_attrs)\n\n\ndef _darknet_reorg(inputs, params, attrs, prefix):\n    \"\"\"Process the reorg operation.\"\"\"\n    new_attrs = {}\n    if \"stride\" in attrs:\n        new_attrs = {\"stride\": attrs.get(\"stride\", 1)}\n    return get_relay_op(\"yolo_reorg\")(*inputs, **new_attrs)\n\n\ndef _darknet_region(inputs, params, attrs, prefix):\n    \"\"\"Process the region operation.\"\"\"\n    num = attrs.get(\"n\", 1)\n    classes = attrs.get(\"classes\", 1)\n    coords = attrs.get(\"coords\", 0)\n    background = attrs.get(\"background\", 0)\n    softmax = attrs.get(\"softmax\", True)\n    input_shape = attrs.get(\"shape\")\n\n    split_size = classes + coords + 1\n    intermediate_shape = (input_shape[0], num, split_size, input_shape[2], input_shape[3])\n    data_block = get_relay_op(\"reshape\")(inputs[0], newshape=intermediate_shape)\n    split_indices = (2, 4, 5)\n    split_res = get_relay_op(\"split\")(data_block, indices_or_sections=split_indices, axis=2)\n    split_res0 = get_relay_op(\"sigmoid\")(split_res[0])\n    split_res2 = split_res[2] if background else get_relay_op(\"sigmoid\")(split_res[2])\n    split_res3 = get_relay_op(\"softmax\")(split_res[3], axis=2) if softmax else split_res[3]\n    out = get_relay_op(\"concatenate\")((split_res0, split_res[1], split_res2, split_res3), axis=2)\n    return get_relay_op(\"reshape\")(out, newshape=input_shape)\n\n\ndef _darknet_yolo(inputs, params, attrs, prefix):\n    \"\"\"Process the yolo operation.\"\"\"\n    num = attrs.get(\"n\", 1)\n    classes = attrs.get(\"classes\", 1)\n    input_shape = attrs.get(\"shape\")\n    split_size = classes + 5\n    intermediate_shape = (input_shape[0], num, split_size, input_shape[2], input_shape[3])\n    data_block = get_relay_op(\"reshape\")(inputs[0], newshape=intermediate_shape)\n    split_indices = (2, 4)\n    split_res = get_relay_op(\"split\")(data_block, indices_or_sections=split_indices, axis=2)\n    split_res0 = get_relay_op(\"sigmoid\")(split_res[0])\n    split_res2 = get_relay_op(\"sigmoid\")(split_res[2])\n    out = get_relay_op(\"concatenate\")((split_res0, split_res[1], split_res2), axis=2)\n    return get_relay_op(\"reshape\")(out, newshape=input_shape)\n\n\nclass ACTIVATION(object):\n    \"\"\"Darknet ACTIVATION Class constant.\"\"\"\n\n    LOGISTIC = 0\n    RELU = 1\n    RELIE = 2\n    LINEAR = 3\n    RAMP = 4\n    TANH = 5\n    PLSE = 6\n    LEAKY = 7\n    ELU = 8\n    LOGGY = 9\n    STAIR = 10\n    HARDTAN = 11\n    LHTAN = 12\n\n\ndef _darknet_activations(inputs, params, attrs):\n    \"\"\"Process the activation function.\"\"\"\n    act = attrs.get(\"activation\")\n    data = inputs[0] if isinstance(inputs, _expr.TupleWrapper) else inputs\n\n    def _const(val):\n        return _expr.const(val)\n\n    def _relu(data):\n        return get_relay_op(\"relu\")(data)\n\n    def _exp(data):\n        return get_relay_op(\"exp\")(data)\n\n    def _tanh(data):\n        return get_relay_op(\"tanh\")(data)\n\n    def _sigmoid(data):\n        return get_relay_op(\"sigmoid\")(data)\n\n    def _elu(data):\n        alpha = _const(-1.0)\n        return alpha * _relu(_const(1.0) - _exp(data)) + _relu(data)\n\n    def _leaky_relu(data, slope):\n        new_attrs = {}\n        new_attrs[\"alpha\"] = slope\n        return get_relay_op(\"leaky_relu\")(data, **new_attrs)\n\n    if ACTIVATION.LOGISTIC == act:\n        data = _sigmoid(data)\n    elif ACTIVATION.RELU == act:\n        data = _relu(data)\n    elif ACTIVATION.TANH == act:\n        data = _tanh(data)\n    elif ACTIVATION.LINEAR == act:\n        return data\n    elif ACTIVATION.LEAKY == act:\n        data = _leaky_relu(data, attrs.get(\"slope\", 0.1))\n    elif ACTIVATION.ELU == act:\n        data = _elu(data)\n    else:\n        _darknet_not_support(\"act: \" + attrs)\n    return data\n\n\nclass LAYERTYPE(Enum):\n    \"\"\"Darknet LAYERTYPE Class constant.\"\"\"\n\n    CONVOLUTIONAL = 0\n    DECONVOLUTIONAL = 1\n    CONNECTED = 2\n    MAXPOOL = 3\n    SOFTMAX = 4\n    DETECTION = 5\n    DROPOUT = 6\n    CROP = 7\n    ROUTE = 8\n    COST = 9\n    NORMALIZATION = 10\n    AVGPOOL = 11\n    LOCAL = 12\n    SHORTCUT = 13\n    ACTIVE = 14\n    RNN = 15\n    GRU = 16\n    LSTM = 17\n    CRNN = 18\n    BATCHNORM = 19\n    NETWORK = 20\n    XNOR = 21\n    REGION = 22\n    YOLO = 23\n    REORG = 24\n    UPSAMPLE = 25\n    LOGXENT = 26\n    L2NORM = 27\n    BLANK = 28\n\n\n_DARKNET_CONVERT_MAP = {\n    LAYERTYPE.CONVOLUTIONAL: _darknet_conv2d,\n    LAYERTYPE.CONNECTED: _darknet_dense,\n    LAYERTYPE.MAXPOOL: _darknet_maxpooling,\n    LAYERTYPE.SOFTMAX: _darknet_softmax_output,\n    LAYERTYPE.DROPOUT: _darknet_dropout,\n    LAYERTYPE.AVGPOOL: _darknet_avgpooling,\n    LAYERTYPE.ROUTE: _darknet_route,\n    LAYERTYPE.REORG: _darknet_reorg,\n    LAYERTYPE.REGION: _darknet_region,\n    LAYERTYPE.SHORTCUT: _darknet_shortcut,\n    LAYERTYPE.UPSAMPLE: _darknet_upsampling,\n    LAYERTYPE.L2NORM: _darknet_l2normalize,\n    LAYERTYPE.YOLO: _darknet_yolo,\n    LAYERTYPE.DECONVOLUTIONAL: _darknet_not_support,\n    LAYERTYPE.BATCHNORM: _darknet_not_support,\n    LAYERTYPE.DETECTION: _darknet_not_support,\n    LAYERTYPE.CROP: _darknet_not_support,\n    LAYERTYPE.COST: _darknet_not_support,\n    LAYERTYPE.NORMALIZATION: _darknet_not_support,\n    LAYERTYPE.LOCAL: _darknet_not_support,\n    LAYERTYPE.ACTIVE: _darknet_not_support,\n    LAYERTYPE.RNN: _darknet_not_support,\n    LAYERTYPE.GRU: _darknet_not_support,\n    LAYERTYPE.LSTM: _darknet_not_support,\n    LAYERTYPE.CRNN: _darknet_not_support,\n    LAYERTYPE.NETWORK: _darknet_not_support,\n    LAYERTYPE.XNOR: _darknet_not_support,\n    LAYERTYPE.BLANK: _darknet_not_support,\n}\n\n\ndef _darknet_convert_symbol(op_name, inputs, params, attrs, params_prefix):\n    \"\"\"Convert from darknet op to relay op.\n    Parameters\n    ----------\n    op_name : str\n        Operator name, such as Convolution, Connected, etc\n    inputs : list of relay.Function\n        List of input symbols.\n    attrs : dict\n        Dict of operator attributes\n    params_prefix: str\n        Params name for this operation\n\n    Returns\n    -------\n    out_name : converted out name of operation\n    sym : tvm.relay.Function\n        Converted relay function\n    \"\"\"\n\n    if op_name in _DARKNET_CONVERT_MAP:\n        sym = _DARKNET_CONVERT_MAP[op_name](inputs, params, attrs, params_prefix)\n    else:\n        _darknet_not_support(\"Operator type \" + str(op_name))\n    return sym\n\n\ndef _as_list(arr):\n    \"\"\"Force being a list, ignore if already is.\"\"\"\n    if isinstance(arr, list):\n        return arr\n    return [arr]\n\n\nclass GraphProto(object):\n    \"\"\"A helper class for handling relay functions from darknet model.\"\"\"\n\n    def __init__(self, net, shape, dtype=\"float32\"):\n        self._net = net\n        self._shape = shape\n        self._dtype = dtype\n        self._sym_array = {}\n        self._tvmparams = {}\n        self._outs = []\n        self._state_ctr = {}\n        self._state_ctr[\"rnn\"] = 0\n        self._state_ctr[\"crnn\"] = 0\n        self._state_ctr[\"lstm\"] = 0\n        self._state_ctr[\"cell_state\"] = 0\n        self._state_ctr[\"gru\"] = 0\n\n    def _read_memory_buffer(self, shape, data, dtype=None):\n        if dtype is None:\n            dtype = self._dtype\n        length = 1\n        for x in shape:\n            length *= x\n        data_np = np.zeros(length, dtype=dtype)\n        for i in range(length):\n            data_np[i] = data[i]\n        return data_np.reshape(shape)\n\n    def _get_convolution_weights(self, layer, opname):\n        \"\"\"Get the convolution layer weights and biases.\"\"\"\n        if layer.nweights == 0:\n            return None\n\n        if (layer.n * layer.c // layer.groups * layer.size * layer.size) != layer.nweights:\n            raise RuntimeError(\"layer weights size not matching with n c h w\")\n\n        params = {}\n        shape = (layer.n, layer.c // layer.groups, layer.size, layer.size)\n        weights = self._read_memory_buffer(shape, layer.weights)\n\n        biases = self._read_memory_buffer((layer.n,), layer.biases)\n\n        k = _get_params_name(opname, \"weight\")\n        params[k] = tvm.nd.array(weights)\n\n        if layer.batch_normalize == 1 and layer.dontloadscales != 1:\n            params.update(self._get_batchnorm_weights(layer, opname, layer.n))\n            k = _get_params_name(opname, \"beta\")\n            params[k] = tvm.nd.array(biases)\n        else:\n            k = _get_params_name(opname, \"bias\")\n            params[k] = tvm.nd.array(biases)\n        return params\n\n    def _get_connected_weights(self, layer, opname):\n        \"\"\"Parse the weights and biases for fully connected or dense layer.\"\"\"\n        size = layer.outputs * layer.inputs\n        if size == 0:\n            return None\n\n        weights = self._read_memory_buffer((layer.outputs, layer.inputs), layer.weights)\n        biases = self._read_memory_buffer((layer.outputs,), layer.biases)\n\n        params = {}\n        k = _get_params_name(opname, \"weight\")\n        params[k] = tvm.nd.array(weights)\n\n        if layer.batch_normalize == 1 and layer.dontloadscales != 1:\n            params.update(self._get_batchnorm_weights(layer, opname, layer.outputs))\n            k = _get_params_name(opname, \"beta\")\n            params[k] = tvm.nd.array(biases)\n        else:\n            k = _get_params_name(opname, \"bias\")\n            params[k] = tvm.nd.array(biases)\n        return params\n\n    def _get_region_weights(self, layer, opname):\n        \"\"\"Parse the biases for region layer.\"\"\"\n        biases = self._read_memory_buffer((layer.n * 2,), layer.biases)\n        attributes = np.array(\n            [\n                layer.n,\n                layer.out_c,\n                layer.out_h,\n                layer.out_w,\n                layer.classes,\n                layer.coords,\n                layer.background,\n            ],\n            dtype=np.int32,\n        )\n        params = {}\n        k = _get_params_name(opname, \"bias\")\n        params[k] = tvm.nd.array(biases)\n        k = _get_params_name(opname, \"attr\")\n        params[k] = tvm.nd.array(attributes)\n        return params\n\n    def _get_yolo_weights(self, layer, opname):\n        \"\"\"Parse the biases and mask for yolo layer.\"\"\"\n        biases = self._read_memory_buffer((layer.total * 2,), layer.biases)\n        mask = self._read_memory_buffer((layer.n,), layer.mask, dtype=\"int32\")\n        attributes = np.array(\n            [layer.n, layer.out_c, layer.out_h, layer.out_w, layer.classes, layer.total],\n            dtype=np.int32,\n        )\n        params = {}\n        k = _get_params_name(opname, \"bias\")\n        params[k] = tvm.nd.array(biases)\n        k = _get_params_name(opname, \"mask\")\n        params[k] = tvm.nd.array(mask)\n        k = _get_params_name(opname, \"attr\")\n        params[k] = tvm.nd.array(attributes)\n        return params\n\n    def _get_batchnorm_weights(self, layer, opname, size):\n        \"\"\"Parse the weights for batchnorm, which includes, scales, moving mean\n        and moving variances.\"\"\"\n        scales = self._read_memory_buffer((size,), layer.scales)\n        rolling_mean = self._read_memory_buffer((size,), layer.rolling_mean)\n        rolling_variance = self._read_memory_buffer((size,), layer.rolling_variance)\n\n        params = {}\n        k = _get_params_name(opname, \"moving_mean\")\n        params[k] = tvm.nd.array(rolling_mean)\n        k = _get_params_name(opname, \"moving_var\")\n        params[k] = tvm.nd.array(rolling_variance)\n        k = _get_params_name(opname, \"gamma\")\n        params[k] = tvm.nd.array(scales)\n        return params\n\n    def _get_darknet_attrs(self, layer, layer_num):\n        \"\"\"Parse attributes of each layer and return.\"\"\"\n        attr = {}\n        use_flatten = True\n        layer_type = LAYERTYPE(layer.type)\n        if LAYERTYPE.CONVOLUTIONAL == layer_type:\n            attr.update({\"pad\": layer.pad})\n            attr.update({\"num_group\": layer.groups})\n            attr.update({\"num_filter\": layer.n})\n            attr.update({\"stride\": layer.stride})\n            attr.update({\"kernel\": layer.size})\n            attr.update({\"activation\": (layer.activation)})\n\n            if layer.nbiases == 0:\n                attr.update({\"use_bias\": False})\n            else:\n                attr.update({\"use_bias\": True})\n\n            if layer.batch_normalize == 1 and layer.dontloadscales != 1:\n                attr.update({\"use_batchNorm\": True})\n                attr.update({\"use_scales\": True})\n\n        elif LAYERTYPE.CONNECTED == layer_type:\n            attr.update({\"num_hidden\": layer.outputs})\n            attr.update({\"activation\": (layer.activation)})\n            if layer_num != 0:\n                layer_prev = self._net.layers[layer_num - 1]\n                if (\n                    layer_prev.out_h == layer.h\n                    and layer_prev.out_w == layer.w\n                    and layer_prev.out_c == layer.c\n                ):\n                    use_flatten = False\n            attr.update({\"use_flatten\": use_flatten})\n            attr.update({\"use_bias\": True})\n            if layer.batch_normalize == 1 and layer.dontloadscales != 1:\n                attr.update({\"use_batchNorm\": True})\n                attr.update({\"use_scales\": True})\n                attr.update({\"use_bias\": False})\n\n        elif LAYERTYPE.MAXPOOL == layer_type:\n            attr.update({\"pad\": layer.pad})\n            attr.update({\"stride\": layer.stride})\n            attr.update({\"kernel\": layer.size})\n            max_output = (layer.w - layer.size + 2 * layer.pad) / float(layer.stride) + 1\n            if max_output < layer.out_w:\n                extra_pad = (layer.out_w - max_output) * layer.stride\n                attr.update({\"extra_pad_size\": int(extra_pad)})\n        elif LAYERTYPE.AVGPOOL == layer_type:\n            attr.update({\"pad\": layer.pad})\n            if layer.stride == 0:\n                attr.update({\"stride\": 1})\n            else:\n                attr.update({\"stride\": layer.stride})\n            if layer.size == 0 and layer.h == layer.w:\n                attr.update({\"kernel\": layer.h})\n            else:\n                attr.update({\"kernel\": layer.size})\n\n        elif LAYERTYPE.DROPOUT == layer_type:\n            attr.update({\"p\": layer.probability})\n\n        elif LAYERTYPE.SOFTMAX == layer_type:\n            attr.update({\"axis\": 1})\n            attr.update({\"use_flatten\": True})\n            if layer.temperature:\n                attr.update({\"temperature\": str(layer.temperature)})\n\n        elif LAYERTYPE.SHORTCUT == layer_type:\n            add_layer = self._net.layers[layer.index]\n            attr.update({\"activation\": layer.activation})\n            attr.update({\"out_channel\": layer.out_c})\n            attr.update({\"out_size\": layer.out_h})\n            attr.update({\"add_out_channel\": add_layer.out_c})\n            attr.update({\"add_out_size\": add_layer.out_h})\n\n        elif LAYERTYPE.ROUTE == layer_type:\n            pass\n\n        elif LAYERTYPE.COST == layer_type:\n            pass\n\n        elif LAYERTYPE.REORG == layer_type:\n            attr.update({\"stride\": layer.stride})\n\n        elif LAYERTYPE.REGION == layer_type:\n            attr.update({\"n\": layer.n})\n            attr.update({\"classes\": layer.classes})\n            attr.update({\"coords\": layer.coords})\n            attr.update({\"background\": layer.background})\n            attr.update({\"softmax\": layer.softmax})\n            attr.update({\"shape\": (-1, layer.c, layer.h, layer.w)})\n\n        elif LAYERTYPE.YOLO == layer_type:\n            attr.update({\"n\": layer.n})\n            attr.update({\"classes\": layer.classes})\n            attr.update({\"shape\": (-1, layer.c, layer.h, layer.w)})\n\n        elif LAYERTYPE.UPSAMPLE == layer_type:\n            attr.update({\"scale\": layer.stride})\n\n        elif LAYERTYPE.L2NORM == layer_type:\n            pass\n\n        else:\n            err = \"Darknet layer type {} is not supported in relay.\".format(layer_type)\n            raise NotImplementedError(err)\n\n        return attr\n\n    def _get_darknet_params(self, layer, opname):\n        \"\"\"To parse and get the darknet params.\"\"\"\n        layer_type = LAYERTYPE(layer.type)\n        params = None\n        if LAYERTYPE.CONVOLUTIONAL == layer_type:\n            params = self._get_convolution_weights(layer, opname)\n        elif LAYERTYPE.CONNECTED == layer_type:\n            params = self._get_connected_weights(layer, opname)\n        elif LAYERTYPE.REGION == layer_type:\n            params = self._get_region_weights(layer, opname)\n        elif LAYERTYPE.YOLO == layer_type:\n            params = self._get_yolo_weights(layer, opname)\n        return params\n\n    def _preproc_layer(self, layer, layer_num):\n        \"\"\"To preprocess each darknet layer, some layer doesnt need processing.\"\"\"\n        if layer_num == 0:\n            name = \"data\"\n            sym = new_var(name, shape=self._shape, dtype=self._dtype)\n        else:\n            sym = self._sym_array[layer_num - 1]\n        skip_layer = False\n        layer_type = LAYERTYPE(layer.type)\n        if LAYERTYPE.ROUTE == layer_type:\n            sym = []\n            for j in range(layer.n):\n                sym.append(self._sym_array[layer.input_layers[j]])\n            if layer.n == 1:\n                skip_layer = True\n\n        elif LAYERTYPE.COST == layer_type:\n            skip_layer = True\n\n        elif LAYERTYPE.SHORTCUT == layer_type:\n            sym = [sym, self._sym_array[layer.index]]\n\n        elif LAYERTYPE.BLANK == layer_type:\n            skip_layer = True\n\n        if skip_layer is True:\n            self._sym_array[layer_num] = sym\n\n        return skip_layer, sym\n\n    def _get_opname(self, layer):\n        \"\"\"Returs the layer name.\"\"\"\n        return LAYERTYPE(layer.type)\n\n    def _new_rnn_state_var(self, state=None, name=\"rnn\"):\n        \"\"\"Returs a symbol for state\"\"\"\n        sym_name = name + \"%d_state\" % self._state_ctr[name]\n        self._state_ctr[name] += 1\n        return new_var(sym_name, shape=state.shape, dtype=str(state.dtype))\n\n    def _get_rnn_state_buffer(self, layer, name):\n        \"\"\"Get the state buffer for rnn.\"\"\"\n        buffer = np.zeros((1, layer.outputs), self._dtype)\n        return self._new_rnn_state_var(buffer, name)\n\n    def _get_darknet_rnn_attrs(self, layer, name, sym):\n        \"\"\"Get the rnn converted symbol from attributes.\"\"\"\n        attr = self._get_darknet_attrs(layer, 0)\n        op_name = self._get_opname(layer)\n        prefix = _get_params_prefix(op_name, name)\n        params = self._get_darknet_params(layer, prefix)\n        sym = _darknet_convert_symbol(op_name, _as_list(sym), params, attr, prefix)\n        if params:\n            self._tvmparams.update(params)\n        return sym\n\n    def _handle_darknet_rnn_layers(self, layer_num, sym):\n        \"\"\"Parse attributes and handle the rnn layers.\"\"\"\n        attr = {}\n        layer = self._net.layers[layer_num]\n        processed = False\n\n        layer_type = LAYERTYPE(layer.type)\n        if LAYERTYPE.RNN == layer_type:\n            attr.update({\"n\": layer.n})\n            attr.update({\"batch\": layer.batch})\n            attr.update({\"num_hidden\": str(layer.outputs)})\n            state = self._get_rnn_state_buffer(layer, \"rnn\")\n            for _ in range(layer.steps):\n                input_layer = layer.input_layer\n                prefix = \"_input_\" + str(layer_num)\n                sym = self._get_darknet_rnn_attrs(input_layer, prefix, sym)\n\n                self_layer = layer.self_layer\n                prefix = \"_self_\" + str(layer_num)\n                state = self._get_darknet_rnn_attrs(self_layer, prefix, state)\n\n                state = sym + state\n                self._outs.append(state)\n\n                output_layer = layer.output_layer\n                prefix = \"_output_\" + str(layer_num)\n                sym = self._get_darknet_rnn_attrs(output_layer, prefix, state)\n\n            self._sym_array[layer_num] = sym\n            processed = True\n        return processed, sym\n\n    def _make_outlist(self, sym, op_name, layer, layer_num):\n        layer_type = LAYERTYPE(layer.type)\n        if layer_type == LAYERTYPE.REGION:\n            # Add attributes\n            k = _get_params_name(op_name, \"attr\")\n            dshape = self._tvmparams[k].shape\n            dtype = self._tvmparams[k].dtype\n            self._outs.insert(0, new_var(k, shape=dshape, dtype=dtype))\n\n            # Add bias\n            k = _get_params_name(op_name, \"bias\")\n            dshape = self._tvmparams[k].shape\n            dtype = self._tvmparams[k].dtype\n            self._outs.insert(0, new_var(k, shape=dshape, dtype=dtype))\n            if layer_num != self._net.n - 1:\n                self._outs.insert(0, sym)\n\n        elif layer_type == LAYERTYPE.YOLO:\n            # Add attributes\n            k = _get_params_name(op_name, \"attr\")\n            dshape = self._tvmparams[k].shape\n            dtype = self._tvmparams[k].dtype\n            self._outs.insert(0, new_var(k, shape=dshape, dtype=dtype))\n\n            # Add bias\n            k = _get_params_name(op_name, \"bias\")\n            dshape = self._tvmparams[k].shape\n            dtype = self._tvmparams[k].dtype\n            self._outs.insert(0, new_var(k, shape=dshape, dtype=dtype))\n\n            # Add mask\n            k = _get_params_name(op_name, \"mask\")\n            dshape = self._tvmparams[k].shape\n            dtype = self._tvmparams[k].dtype\n            self._outs.insert(0, new_var(k, shape=dshape, dtype=dtype))\n\n            if layer_num != self._net.n - 1:\n                self._outs.insert(0, sym)\n\n    def from_darknet(self):\n        \"\"\"To convert the darknet symbol to relay functions.\"\"\"\n        for i in range(self._net.n):\n            layer = self._net.layers[i]\n            need_skip, sym = self._preproc_layer(layer, i)\n            if need_skip:\n                continue\n\n            processed, sym = self._handle_darknet_rnn_layers(i, sym)\n            if processed:\n                continue\n\n            attr = self._get_darknet_attrs(layer, i)\n            op_name = self._get_opname(layer)\n            prefix = _get_params_prefix(op_name, i)\n            params = self._get_darknet_params(self._net.layers[i], prefix)\n            sym = _darknet_convert_symbol(op_name, _as_list(sym), params, attr, prefix)\n\n            if params:\n                self._tvmparams.update(params)\n            self._sym_array[i] = sym\n            self._make_outlist(sym, prefix, layer, i)\n\n        outputs = _as_list(sym) + self._outs\n        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n        sym = _function.Function(analysis.free_vars(outputs), outputs)\n        return IRModule.from_expr(sym), self._tvmparams\n\n\ndef from_darknet(net, shape=None, dtype=\"float32\"):\n    \"\"\"Convert from Darknet's model into compatible relay Function.\n\n    Parameters\n    ----------\n    net : Darknet net parameter\n        Darknet net structure.\n    shape : dict of str to tuple, optional\n        The input shape to the graph\n    dtype : str or dict of str to str\n        The input types to the graph\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation.\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by relay\n    \"\"\"\n\n    return GraphProto(net, shape, dtype).from_darknet()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/keras.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, import-outside-toplevel\n\"\"\"Keras frontend.\"\"\"\nimport dis\nimport sys\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule, TensorType, TupleType\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom ... import nd as _nd\nfrom .common import ExprTable, new_var\n\n__all__ = [\"from_keras\"]\n\n\ndef _check_data_format(keras_layer):\n    if hasattr(keras_layer, (\"data_format\")):\n        if keras_layer.data_format != \"channels_last\":\n            raise ValueError(\"Keras frontend currently supports data_format = channels_last only.\")\n\n\ndef _get_pad_pair(input1d, kernel1d, stride1d):\n    out1d = (input1d + stride1d - 1) // stride1d\n    pad = np.maximum((out1d - 1) * stride1d + kernel1d - input1d, 0)\n    pad_before = pad // 2\n    pad_after = pad - pad_before\n    return [pad_before, pad_after]\n\n\ndef _get_elu(inexpr, alpha):\n    \"\"\"A helper method for elu.\"\"\"\n    return _op.negative(alpha) * _op.nn.relu(\n        _expr.const(1.0, dtype=\"float32\") - _op.exp(inexpr)\n    ) + _op.nn.relu(inexpr)\n\n\ndef _as_list(arr):\n    \"\"\"Force being a list, ignore if already is.\"\"\"\n    if isinstance(arr, list):\n        return arr\n    return [arr]\n\n\ndef _convert_recurrent_activation(inexpr, keras_layer):\n    act_type = keras_layer.recurrent_activation.__name__\n    return _convert_activation(inexpr, act_type, None, None, None)\n\n\ndef _convert_activation(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    if isinstance(keras_layer, str):\n        act_type = keras_layer\n    else:\n        if sys.version_info.major < 3:\n            act_type = keras_layer.activation.func_name\n        else:\n            act_type = keras_layer.activation.__name__\n    if act_type == \"linear\":\n        if isinstance(keras_layer, str):\n            return inexpr\n        alpha = keras_layer.alpha if hasattr(keras_layer, \"alpha\") else 1.0\n        beta = keras_layer.beta if hasattr(keras_layer, \"beta\") else 0.0\n        alpha = _expr.const(alpha, dtype=\"float32\")\n        beta = _expr.const(beta, dtype=\"float32\")\n        return _op.add(_op.multiply(inexpr, alpha), beta)\n    if act_type == \"softmax\":\n        axis = 1 if data_layout == \"NCHW\" else -1\n        return _op.nn.softmax(inexpr, axis)\n    if act_type == \"sigmoid\":\n        return _op.sigmoid(inexpr)\n    if act_type == \"tanh\":\n        return _op.tanh(inexpr)\n    if act_type == \"relu\":\n        return _op.nn.relu(inexpr)\n    if act_type == \"softplus\":\n        return _op.log(_op.add(_op.exp(inexpr), _expr.const(1.0, dtype=\"float32\")))\n    if act_type == \"elu\":\n        alpha = keras_layer.alpha if hasattr(keras_layer, \"alpha\") else 1.0\n        alpha = _expr.const(alpha, dtype=\"float32\")\n        return _get_elu(inexpr, alpha)\n    if act_type == \"selu\":\n        # Alpha, Gamma values obtained from https://arxiv.org/abs/1706.02515\n        alpha = (\n            keras_layer.alpha\n            if hasattr(keras_layer, \"alpha\")\n            else 1.6732632423543772848170429916717\n        )\n        gamma = (\n            keras_layer.gamma\n            if hasattr(keras_layer, \"gamma\")\n            else 1.0507009873554804934193349852946\n        )\n        alpha = _expr.const(alpha, dtype=\"float32\")\n        gamma = _expr.const(gamma, dtype=\"float32\")\n        return gamma * _get_elu(inexpr, alpha)\n    if act_type == \"relu6\":\n        return _op.clip(inexpr, a_min=0.0, a_max=6.0)\n    if act_type == \"softsign\":\n        return inexpr / (_expr.const(1.0, dtype=\"float32\") + _op.abs(inexpr))\n    if act_type == \"hard_sigmoid\":\n        x = (_expr.const(0.2, dtype=\"float32\") * inexpr) + _expr.const(0.5, dtype=\"float32\")\n        return _op.clip(x, a_min=0.0, a_max=1.0)\n\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} is not supported in frontend Keras.\".format(act_type)\n    )\n\n\ndef _convert_advanced_activation(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    act_type = type(keras_layer).__name__\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if act_type == \"Softmax\":\n        axis = keras_layer.axis\n        dims = len(input_shape)\n        if isinstance(axis, list):\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Softmax with axes {} is not supported.\".format(axis)\n            )\n        if data_layout == \"NCHW\":\n            if axis == -1:\n                axis = 1\n            else:\n                axis = axis + 1 if axis < dims - 1 else 1\n        return _op.nn.softmax(inexpr, axis=axis)\n    if act_type == \"ReLU\":\n        threshold = _expr.const(keras_layer.threshold, dtype=\"float32\")\n        if keras_layer.max_value and float(keras_layer.threshold) == 0:\n            # f(x) = max_value, for x >= max_value\n            # f(x) = x,         for threshold <= x < max_value\n            return _op.clip(inexpr, a_min=0.0, a_max=float(keras_layer.max_value))\n        if keras_layer.max_value and _op.greater(threshold, inexpr).astype(\"float32\"):\n            # f(x) = negative_slope * (inexpr - threshold)\n            negative_slope = _expr.const(keras_layer.negative_slope, dtype=\"float32\")\n            return _op.multiply(negative_slope, _op.subtract(inexpr, threshold))\n        return _op.nn.relu(inexpr)\n    if act_type == \"LeakyReLU\":\n        return _op.nn.leaky_relu(inexpr, alpha=float(keras_layer.alpha))\n    if act_type == \"ELU\":\n        alpha = keras_layer.alpha if hasattr(keras_layer, \"alpha\") else 1.0\n        alpha = _expr.const(alpha, dtype=\"float32\")\n        return _get_elu(inexpr, alpha)\n    if act_type == \"PReLU\":\n        assert hasattr(keras_layer, \"alpha\"), \"alpha required for PReLU.\"\n        _check_data_format(keras_layer)\n        size = len(keras_layer.alpha.shape)\n        if data_layout == \"NCHW\":\n            alpha = etab.new_const(keras_layer.get_weights()[0].transpose(np.roll(range(size), 1)))\n        else:\n            alpha = etab.new_const(keras_layer.get_weights()[0])\n        return _op.negative(alpha) * _op.nn.relu(_op.negative(inexpr)) + _op.nn.relu(inexpr)\n    if act_type == \"ThresholdedReLU\":\n        theta = keras_layer.theta if hasattr(keras_layer, \"theta\") else 1.0\n        return _op.multiply(\n            inexpr, _op.greater(inexpr, _expr.const(theta, dtype=\"float32\")).astype(\"float32\")\n        )\n\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} is not supported in frontend Keras.\".format(act_type)\n    )\n\n\ndef _convert_merge(\n    inexpr, keras_layer, _, input_shape=None, data_layout=None\n):  # pylint: disable=unused-argument\n    merge_type = type(keras_layer).__name__\n    ret = inexpr[0]\n    if merge_type == \"Dot\":\n        axes = keras_layer.axes\n        if isinstance(keras_layer.axes, int):\n            axes = [keras_layer.axes, keras_layer.axes]\n        if isinstance(axes, list):\n            if len(axes) != 2:\n                raise tvm.error.OpAttributeUnImplemented(\n                    \"Dot with axes {} is not supported.\".format(keras_layer.axes)\n                )\n            for i, axis in enumerate(axes):\n                if axis not in [1, 2]:\n                    raise tvm.error.OpAttributeUnImplemented(\n                        \"Dot with axes {} is not supported.\".format(keras_layer.axes)\n                    )\n                if axes[i] == 2:\n                    inexpr[i] = _op.transpose(inexpr[i], axes=[0, 2, 1])\n        else:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Dot with axes {} is not supported.\".format(keras_layer.axes)\n            )\n        ret_dot = _op.nn.batch_matmul(inexpr[0], inexpr[1])\n        ret = _op.transpose(ret_dot, axes=[0, 2, 1])\n    elif merge_type == \"Subtract\":\n        assert len(inexpr) == 2, \"Subtract merge takes 2 inputs.\"\n        ret = _op.subtract(ret, inexpr[1])\n    elif merge_type in [\"Add\", \"Multiply\", \"Minimum\", \"Maximum\"]:\n        op_map = {\n            \"Add\": _op.add,\n            \"Multiply\": _op.multiply,\n            \"Minimum\": _op.minimum,\n            \"Maximum\": _op.maximum,\n        }\n        for i in range(1, len(inexpr)):\n            ret = op_map[merge_type](ret, inexpr[i])\n    elif merge_type == \"Average\":\n        for i in range(1, len(inexpr)):\n            ret = _op.add(ret, inexpr[i])\n        ret = ret / _expr.const(len(inexpr), dtype=\"float32\")\n    else:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported in frontend Keras.\".format(merge_type)\n        )\n    return ret\n\n\ndef _convert_permute(\n    inexpr, keras_layer, _, input_shape=None, data_layout=None\n):  # pylint: disable=unused-argument\n    return _op.transpose(inexpr, axes=(0,) + keras_layer.dims)\n\n\ndef _convert_embedding(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    indices = inexpr\n    weightList = keras_layer.get_weights()\n    weight = etab.new_const(weightList[0])\n    out = _op.take(weight, indices.astype(\"int32\"), axis=0)\n\n    return out\n\n\ndef _convert_dense(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    weightList = keras_layer.get_weights()\n    weight = etab.new_const(weightList[0].transpose([1, 0]))\n    params = {\"weight\": weight, \"units\": weightList[0].shape[1]}\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    input_dim = len(input_shape)\n    # In case of RNN dense, input shape will be (1, 1, n)\n    if input_dim > 2:\n        input_shape = tuple(dim if dim else 1 for dim in _as_list(input_shape)[0])\n        if input_dim != 3 or input_shape[0] != 1 or input_shape[1] != 1:\n            raise tvm.error.OpAttributeInvalid(\n                \"Input shape {} is not valid for operator Dense.\".format(input_shape)\n            )\n        inexpr = _op.squeeze(inexpr, axis=[0])\n    out = _op.nn.dense(data=inexpr, **params)\n    if keras_layer.use_bias:\n        bias = etab.new_const(weightList[1])\n        out = _op.nn.bias_add(out, bias)\n    # defuse activation\n    if sys.version_info.major < 3:\n        act_type = keras_layer.activation.func_name\n    else:\n        act_type = keras_layer.activation.__name__\n    if act_type != \"linear\":\n        out = _convert_activation(out, act_type, etab, data_layout)\n    if input_dim > 2:\n        out = _op.expand_dims(out, axis=0)\n    return out\n\n\ndef _convert_convolution1d(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    _check_data_format(keras_layer)\n    weightList = keras_layer.get_weights()\n    weight = weightList[0]\n\n    if data_layout == \"NWC\":\n        kernel_layout = \"WIO\"\n    else:\n        kernel_layout = \"OIW\"\n        msg = (\n            \"Kernel layout with {} is not supported for operator Convolution1D \"\n            \"in frontend Keras.\"\n        )\n        raise tvm.error.OpAttributeUnImplemented(msg.format(data_layout))\n\n    is_deconv = type(keras_layer).__name__ == \"Conv1DTranspose\"\n\n    if is_deconv:\n        if kernel_layout == \"OIW\":\n            weight = weight.transpose([2, 0, 1])\n        kernel_w, n_filters, _ = weight.shape\n    else:\n        kernel_w, _, n_filters = weight.shape\n\n    dilation_rate = keras_layer.dilation_rate\n    if isinstance(dilation_rate, (list, tuple)):\n        dilation = [dilation_rate[0]]\n    else:\n        dilation = [dilation_rate]\n\n    dilated_kernel_w = (kernel_w - 1) * dilation[0] + 1\n    stride_w = keras_layer.strides[0]\n    params = {\n        \"weight\": etab.new_const(weight),\n        \"kernel_size\": [kernel_w],\n        \"strides\": [stride_w],\n        \"dilation\": dilation,\n        \"padding\": [0],\n        \"data_layout\": data_layout,\n        \"kernel_layout\": kernel_layout,\n    }\n    params[\"channels\"] = n_filters\n\n    if keras_layer.padding == \"valid\":\n        pass\n    # calculate the padding values\n    elif keras_layer.padding == \"same\":\n        in_w = input_shape[1]\n        pad_w = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n        params[\"padding\"] = [pad_w[0], pad_w[1]]\n    else:\n        msg = \"Padding with {} is not supported for operator Convolution3D \" \"in frontend Keras.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(keras_layer.padding))\n\n    if is_deconv:\n        out = _op.nn.conv1d_transpose(data=inexpr, **params)\n    else:\n        out = _op.nn.conv1d(data=inexpr, **params)\n\n    channel_axis = -1 if data_layout == \"NWC\" else 1\n    if keras_layer.use_bias:\n        bias = etab.new_const(weightList[1])\n        out = _op.nn.bias_add(out, bias, channel_axis)\n\n    # defuse activation\n    if sys.version_info.major < 3:\n        act_type = keras_layer.activation.func_name\n    else:\n        act_type = keras_layer.activation.__name__\n    if act_type != \"linear\":\n        out = _convert_activation(out, act_type, etab, data_layout)\n\n    return out\n\n\ndef _convert_convolution(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    _check_data_format(keras_layer)\n    is_deconv = type(keras_layer).__name__ == \"Conv2DTranspose\"\n    is_depthconv = type(keras_layer).__name__ == \"DepthwiseConv2D\"\n    weightList = keras_layer.get_weights()\n    weight = weightList[0]\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if data_layout == \"NHWC\":\n        if is_depthconv:\n            kernel_layout = \"HWOI\"\n        else:\n            kernel_layout = \"HWIO\"\n    else:\n        if is_deconv:\n            kernel_layout = \"IOHW\"\n        else:\n            kernel_layout = \"OIHW\"\n\n    if is_deconv:\n        kernel_h, kernel_w, n_filters, in_channels = weight.shape\n        if kernel_layout == \"IOHW\":\n            weight = weight.transpose([3, 2, 0, 1])\n    elif is_depthconv:\n        kernel_h, kernel_w, in_channels, depth_mult = weight.shape\n        if kernel_layout == \"OIHW\":\n            weight = weight.transpose([2, 3, 0, 1])\n    elif data_layout == \"NCHW\":\n        kernel_h, kernel_w, in_channels, n_filters = weight.shape\n        weight = weight.transpose([3, 2, 0, 1])\n    else:\n        kernel_h, kernel_w, in_channels, n_filters = weight.shape\n    if isinstance(keras_layer.dilation_rate, (list, tuple)):\n        dilation = [keras_layer.dilation_rate[0], keras_layer.dilation_rate[1]]\n    else:\n        dilation = [keras_layer.dilation_rate, keras_layer.dilation_rate]\n    dilated_kernel_h = (kernel_h - 1) * dilation[0] + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation[1] + 1\n    stride_h, stride_w = keras_layer.strides\n    params = {\n        \"weight\": etab.new_const(weight),\n        \"kernel_size\": [kernel_h, kernel_w],\n        \"strides\": [stride_h, stride_w],\n        \"dilation\": dilation,\n        \"padding\": [0, 0],\n        \"data_layout\": data_layout,\n        \"kernel_layout\": kernel_layout,\n    }\n    if is_depthconv:\n        params[\"channels\"] = in_channels * depth_mult\n        params[\"groups\"] = in_channels\n    else:\n        params[\"channels\"] = n_filters\n    if keras_layer.padding == \"valid\":\n        pass\n    # we insert a separate pad operator\n    elif keras_layer.padding == \"same\":\n        in_h = input_shape[1]\n        in_w = input_shape[2]\n        pad_t, pad_b = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n        pad_l, pad_r = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n        params[\"padding\"] = (pad_t, pad_l, pad_b, pad_r)\n    else:\n        msg = \"Padding with {} is not supported for operator Convolution \" \"in frontend Keras.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(keras_layer.padding))\n    if is_deconv:\n        out = _op.nn.conv2d_transpose(data=inexpr, **params)\n    else:\n        out = _op.nn.conv2d(data=inexpr, **params)\n\n    if keras_layer.use_bias:\n        bias = etab.new_const(weightList[1])\n        if data_layout == \"NCHW\":\n            out = _op.nn.bias_add(out, bias)\n        else:\n            out = _op.nn.bias_add(out, bias, axis=-1)\n    # defuse activation\n    if sys.version_info.major < 3:\n        act_type = keras_layer.activation.func_name\n    else:\n        act_type = keras_layer.activation.__name__\n    if act_type != \"linear\":\n        out = _convert_activation(out, act_type, etab, data_layout)\n\n    return out\n\n\ndef _convert_convolution3d(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    _check_data_format(keras_layer)\n    weightList = keras_layer.get_weights()\n    weight = weightList[0]\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if data_layout == \"NDHWC\":\n        kernel_layout = \"DHWIO\"\n    else:\n        kernel_layout = \"OIDHW\"\n        msg = (\n            \"Kernel layout with {} is not supported for operator Convolution3D \"\n            \"in frontend Keras.\"\n        )\n        raise tvm.error.OpAttributeUnImplemented(msg.format(data_layout))\n\n    is_deconv = type(keras_layer).__name__ == \"Conv3DTranspose\"\n\n    if is_deconv:\n        kernel_d, kernel_h, kernel_w, n_filters, _ = weight.shape\n        if kernel_layout == \"OIDHW\":\n            weight = weight.transpose([4, 3, 2, 0, 1])\n    else:\n        kernel_d, kernel_h, kernel_w, _, n_filters = weight.shape\n\n    dilation_rate = keras_layer.dilation_rate\n    if isinstance(dilation_rate, (list, tuple)):\n        dilation = [dilation_rate[0], dilation_rate[1], dilation_rate[2]]\n    else:\n        dilation = [dilation_rate, dilation_rate, dilation_rate]\n\n    dilated_kernel_d = (kernel_d - 1) * dilation[0] + 1\n    dilated_kernel_h = (kernel_h - 1) * dilation[1] + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation[2] + 1\n    stride_d, stride_h, stride_w = keras_layer.strides\n    params = {\n        \"weight\": etab.new_const(weight),\n        \"kernel_size\": [kernel_d, kernel_h, kernel_w],\n        \"strides\": [stride_d, stride_h, stride_w],\n        \"dilation\": dilation,\n        \"padding\": [0, 0, 0],\n        \"data_layout\": data_layout,\n        \"kernel_layout\": kernel_layout,\n    }\n    params[\"channels\"] = n_filters\n\n    if keras_layer.padding == \"valid\":\n        pass\n    # calculate the padding values\n    elif keras_layer.padding == \"same\":\n        in_d = input_shape[1]\n        in_h = input_shape[2]\n        in_w = input_shape[3]\n        pad_d = _get_pad_pair(in_d, dilated_kernel_d, stride_d)\n        pad_h = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n        pad_w = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n        params[\"padding\"] = [pad_d[0], pad_h[0], pad_w[0], pad_d[1], pad_h[1], pad_w[1]]\n    else:\n        msg = \"Padding with {} is not supported for operator Convolution3D \" \"in frontend Keras.\"\n        raise tvm.error.OpAttributeUnImplemented(msg.format(keras_layer.padding))\n    if is_deconv:\n        out = _op.nn.conv3d_transpose(data=inexpr, **params)\n    else:\n        out = _op.nn.conv3d(data=inexpr, **params)\n\n    channel_axis = -1 if data_layout == \"NDHWC\" else 1\n    if keras_layer.use_bias:\n        bias = etab.new_const(weightList[1])\n        out = _op.nn.bias_add(out, bias, channel_axis)\n\n    # defuse activation\n    if sys.version_info.major < 3:\n        act_type = keras_layer.activation.func_name\n    else:\n        act_type = keras_layer.activation.__name__\n    if act_type != \"linear\":\n        out = _convert_activation(out, act_type, etab, None)\n\n    return out\n\n\ndef _convert_separable_convolution(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    _check_data_format(keras_layer)\n\n    if data_layout == \"NHWC\":\n        kernel_layout = \"HWOI\"\n    else:\n        kernel_layout = \"OIHW\"\n\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    weightList = keras_layer.get_weights()\n    # depthwise conv\n    kernel_h, kernel_w, in_channels, depth_mult = weightList[0].shape\n    stride_h, stride_w = keras_layer.strides\n    if kernel_layout == \"OIHW\":\n        weight0 = weightList[0].transpose([2, 3, 0, 1])\n    else:\n        weight0 = weightList[0]\n    params0 = {\n        \"weight\": etab.new_const(weight0),\n        \"channels\": in_channels * depth_mult,\n        \"groups\": in_channels,\n        \"kernel_size\": [kernel_h, kernel_w],\n        \"strides\": [stride_h, stride_w],\n        \"dilation\": [1, 1],\n        \"padding\": [0, 0],\n        \"data_layout\": data_layout,\n        \"kernel_layout\": kernel_layout,\n    }\n    if keras_layer.padding == \"valid\":\n        pass\n    # we insert a separate pad operator\n    elif keras_layer.padding == \"same\":\n        in_h = input_shape[1]\n        in_w = input_shape[2]\n        pad_t, pad_b = _get_pad_pair(in_h, kernel_h, stride_h)\n        pad_l, pad_r = _get_pad_pair(in_w, kernel_w, stride_w)\n        params0[\"padding\"] = (pad_t, pad_l, pad_b, pad_r)\n    else:\n        msg = (\n            \"Padding with {} is not supported for operator Separable \"\n            \"Convolution in frontend Keras.\"\n        )\n        raise tvm.error.OpAttributeUnImplemented(msg.format(keras_layer.padding))\n    depthconv = _op.nn.conv2d(data=inexpr, **params0)\n    # pointwise conv\n    if kernel_layout == \"OIHW\":\n        weight1 = weightList[1].transpose([3, 2, 0, 1])\n    else:\n        weight1 = weightList[1]\n        kernel_layout = \"HWIO\"\n    params1 = {\n        \"weight\": etab.new_const(weight1),\n        \"channels\": weightList[1].shape[3],\n        \"groups\": 1,\n        \"kernel_size\": [1, 1],\n        \"strides\": [1, 1],\n        \"dilation\": [1, 1],\n        \"data_layout\": data_layout,\n        \"kernel_layout\": kernel_layout,\n    }\n    out = _op.nn.conv2d(data=depthconv, **params1)\n    if keras_layer.use_bias:\n        bias = etab.new_const(weightList[2])\n        if data_layout == \"NCHW\":\n            out = _op.nn.bias_add(out, bias)\n        else:\n            out = _op.nn.bias_add(out, bias, axis=-1)\n    # defuse activation\n    if sys.version_info.major < 3:\n        act_type = keras_layer.activation.func_name\n    else:\n        act_type = keras_layer.activation.__name__\n    if act_type != \"linear\":\n        out = _convert_activation(out, act_type, etab, data_layout)\n    return out\n\n\ndef _convert_flatten(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n\n    # NCHW -> NHWC so that dense can be correctly converted\n    if data_layout == \"NCHW\":\n        inexpr = _op.transpose(inexpr, axes=[0, 2, 3, 1])\n    return _op.nn.batch_flatten(inexpr)\n\n\ndef _convert_pooling(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n\n    pool_type = type(keras_layer).__name__\n    # global pool in keras = global pool + flatten in relay\n    global_pool_params = {\"layout\": data_layout}\n\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if pool_type == \"GlobalMaxPooling2D\":\n        return _convert_flatten(\n            _op.nn.global_max_pool2d(inexpr, **global_pool_params), keras_layer, etab, data_layout\n        )\n    if pool_type == \"GlobalAveragePooling2D\":\n        global_avg_pool2d = _op.nn.global_avg_pool2d(inexpr, **global_pool_params)\n        keep_dims = len(keras_layer.input.shape) == len(keras_layer.output.shape)\n        if keep_dims:\n            return global_avg_pool2d\n        return _convert_flatten(global_avg_pool2d, keras_layer, etab, data_layout)\n    pool_h, pool_w = keras_layer.pool_size\n    stride_h, stride_w = keras_layer.strides\n    params = {\n        \"pool_size\": [pool_h, pool_w],\n        \"strides\": [stride_h, stride_w],\n        \"padding\": [0, 0],\n        \"layout\": data_layout,\n    }\n    if keras_layer.padding == \"valid\":\n        pass\n    elif keras_layer.padding == \"same\":\n        in_h = input_shape[1]\n        in_w = input_shape[2]\n        pad_t, pad_b = _get_pad_pair(in_h, pool_h, stride_h)\n        pad_l, pad_r = _get_pad_pair(in_w, pool_w, stride_w)\n        params[\"padding\"] = [pad_t, pad_l, pad_b, pad_r]\n    else:\n        raise tvm.error.OpAttributeUnImplemented(\n            \"Padding with {} is not supported in operator Pooling.\".format(keras_layer.padding)\n        )\n    if pool_type == \"MaxPooling2D\":\n        return _op.nn.max_pool2d(inexpr, **params)\n    if pool_type == \"AveragePooling2D\":\n        params[\"count_include_pad\"] = False\n        return _op.nn.avg_pool2d(inexpr, **params)\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} is not supported for frontend Keras.\".format(keras_layer)\n    )\n\n\ndef _convert_pooling3d(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    pool_type = type(keras_layer).__name__\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if pool_type not in [\"MaxPooling3D\", \"AveragePooling3D\"]:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend Keras.\".format(keras_layer)\n        )\n\n    pool_d1, pool_d2, pool_d3 = keras_layer.pool_size\n    stride_d1, stride_d2, stride_d3 = keras_layer.strides\n    params = {\n        \"pool_size\": [pool_d1, pool_d2, pool_d3],\n        \"strides\": [stride_d1, stride_d2, stride_d3],\n        \"padding\": [0, 0, 0],\n        \"layout\": data_layout,\n    }\n\n    if keras_layer.padding == \"valid\":\n        pass\n    elif keras_layer.padding == \"same\":\n        in_d1 = input_shape[1]\n        in_d2 = input_shape[2]\n        in_d3 = input_shape[3]\n        pad_d1 = _get_pad_pair(in_d1, pool_d1, stride_d1)\n        pad_d2 = _get_pad_pair(in_d2, pool_d2, stride_d2)\n        pad_d3 = _get_pad_pair(in_d3, pool_d3, stride_d3)\n        params[\"padding\"] = [pad_d1[0], pad_d2[0], pad_d3[0], pad_d1[1], pad_d2[1], pad_d3[1]]\n    else:\n        raise tvm.error.OpAttributeUnImplemented(\n            \"Padding with {} is not supported in operator Pooling3D.\".format(keras_layer.padding)\n        )\n\n    out = _op.transpose(inexpr, axes=(0, 4, 1, 2, 3))\n    params[\"layout\"] = \"NCDHW\"\n    if pool_type == \"MaxPooling3D\":\n        out = _op.nn.max_pool3d(out, **params)\n    elif pool_type == \"AveragePooling3D\":\n        out = _op.nn.avg_pool3d(out, **params)\n\n    return _op.transpose(out, axes=(0, 2, 3, 4, 1))\n\n\ndef _convert_global_pooling3d(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    pool_type = type(keras_layer).__name__\n\n    global_pool_params = {\"layout\": data_layout}\n    if pool_type == \"GlobalMaxPooling3D\":\n        out = _op.nn.global_max_pool3d(inexpr, **global_pool_params)\n    elif pool_type == \"GlobalAveragePooling3D\":\n        out = _op.nn.global_avg_pool3d(inexpr, **global_pool_params)\n    else:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend Keras.\".format(keras_layer)\n        )\n\n    return _convert_flatten(out, keras_layer, etab, input_shape, data_layout)\n\n\ndef _convert_upsample(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    upsample_type = type(keras_layer).__name__\n    params = {}\n    if upsample_type == \"UpSampling1D\":\n        h = keras_layer.size\n        params[\"scale_h\"] = h\n    elif upsample_type == \"UpSampling2D\":\n        h, w = keras_layer.size\n        if h != w:\n            raise tvm.error.OpAttributeInvalid(\"Height must equal width for operator Upsample.\")\n        params[\"scale_h\"] = h\n        params[\"scale_w\"] = h\n\n        if hasattr(keras_layer, \"interpolation\"):\n            interpolation = keras_layer.interpolation\n            if interpolation == \"nearest\":\n                params[\"method\"] = \"nearest_neighbor\"\n            else:\n                params[\"method\"] = \"bilinear\"\n    else:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend Keras.\".format(upsample_type)\n        )\n    params[\"layout\"] = data_layout\n    out = _op.nn.upsampling(inexpr, **params)\n    return out\n\n\ndef _convert_upsample3d(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n\n    params = {}\n    d, h, w = keras_layer.size\n    params[\"scale_d\"] = d\n    params[\"scale_h\"] = h\n    params[\"scale_w\"] = w\n    params[\"layout\"] = data_layout\n    params[\"coordinate_transformation_mode\"] = \"asymmetric\"\n    out = _op.nn.upsampling3d(inexpr, **params)\n    return out\n\n\ndef _convert_cropping(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    crop_type = type(keras_layer).__name__\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    if crop_type == \"Cropping2D\":\n        (_, in_h, in_w, _) = input_shape\n        ((crop_t, crop_b), (crop_l, crop_r)) = keras_layer.cropping\n    else:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend Keras.\".format(crop_type)\n        )\n    int32_max = np.iinfo(np.int32).max\n    return _op.strided_slice(\n        inexpr,\n        begin=[0, 0, crop_t, crop_l],\n        end=[int32_max, int32_max, in_h - crop_b, in_w - crop_r],\n    )\n\n\ndef _convert_batchnorm(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    if data_layout == \"NCHW\" or len(input_shape) < 4:\n        axis = 1\n    else:\n        axis = 3\n\n    params = {\"scale\": False, \"center\": False, \"epsilon\": keras_layer.epsilon, \"axis\": axis}\n    idx = 0\n    if keras_layer.scale:\n        params[\"scale\"] = True\n        gamma = keras_layer.get_weights()[idx]\n        params[\"gamma\"] = etab.new_const(gamma)\n        idx += 1\n    if keras_layer.center:\n        params[\"center\"] = True\n        beta = keras_layer.get_weights()[idx]\n        params[\"beta\"] = etab.new_const(beta)\n        idx += 1\n    moving_mean = keras_layer.get_weights()[idx]\n    moving_var = keras_layer.get_weights()[idx + 1]\n    params[\"moving_mean\"] = etab.new_const(moving_mean)\n    params[\"moving_var\"] = etab.new_const(moving_var)\n    # in case beta or gamma is not defined\n    params[\"beta\"] = (\n        etab.new_const(np.zeros(moving_mean.shape)) if \"beta\" not in params else params[\"beta\"]\n    )\n    params[\"gamma\"] = (\n        etab.new_const(np.ones(moving_mean.shape)) if \"gamma\" not in params else params[\"gamma\"]\n    )\n    result, moving_mean, moving_var = _op.nn.batch_norm(inexpr, **params)\n    return result\n\n\ndef _convert_padding(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n\n    padding_type = type(keras_layer).__name__\n    padding = keras_layer.padding\n    top = left = bottom = right = 0\n    if padding_type == \"ZeroPadding2D\":\n        if isinstance(padding, int):\n            top = left = bottom = right = padding\n        elif isinstance(padding, tuple):\n            if isinstance(padding[0], int):\n                top, left = padding\n                bottom, right = padding\n            elif isinstance(padding[0], tuple):\n                top, bottom = padding[0]\n                left, right = padding[1]\n            else:\n                msg = 'Value {} in attribute \"padding\" of operator Padding ' \"is not valid.\"\n                raise tvm.error.OpAttributeInvalid(msg.format(str(padding)))\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Padding is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(str(padding)))\n    else:\n        msg = \"Operator {} is not supported in frontend Keras.\"\n        raise tvm.error.OpNotImplemented(msg.format(padding_type))\n    if data_layout == \"NCHW\":\n        return _op.nn.pad(data=inexpr, pad_width=((0, 0), (0, 0), (top, bottom), (left, right)))\n    return _op.nn.pad(data=inexpr, pad_width=((0, 0), (top, bottom), (left, right), (0, 0)))\n\n\ndef _convert_padding3d(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n\n    padding = keras_layer.padding\n\n    d_pad = h_pad = w_pad = [0, 0]\n\n    # padding can be 'int' or 'tuple of 3 ints' or 'tuple of 3 tuples of 2 ints' or 'tuple\n    # of 3 tuples of 2 ints different values'. In all these scenarios keras will send 3\n    # tuples of 2 ints.\n    if isinstance(padding, tuple) and isinstance(padding[0], tuple):\n        d_pad = padding[0]\n        h_pad = padding[1]\n        w_pad = padding[2]\n    else:\n        msg = 'Value {} in attribute \"padding\" of operator ZeroPadding3D is ' \"not valid.\"\n        raise tvm.error.OpAttributeInvalid(msg.format(str(padding)))\n\n    if data_layout == \"NCDHW\":\n        out = _op.nn.pad(\n            data=inexpr,\n            pad_width=(\n                (0, 0),\n                (0, 0),\n                (d_pad[0], d_pad[1]),\n                (h_pad[0], h_pad[1]),\n                (w_pad[0], w_pad[1]),\n            ),\n        )\n    else:\n        out = _op.nn.pad(\n            data=inexpr,\n            pad_width=(\n                (0, 0),\n                (d_pad[0], d_pad[1]),\n                (h_pad[0], h_pad[1]),\n                (w_pad[0], w_pad[1]),\n                (0, 0),\n            ),\n        )\n    return out\n\n\ndef _convert_concat(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    if data_layout == \"NHWC\" or len(input_shape[0]) < 4:\n        axis = -1\n    else:\n        axis = 1\n    return _op.concatenate(_as_list(inexpr), axis=axis)\n\n\ndef _convert_reshape(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    inshape = input_shape  # includes batch\n    tshape = keras_layer.target_shape  # no batch\n    shape = (-1,) + tshape\n\n    if data_layout == \"NCHW\" and (len(inshape) > 3 or len(tshape) > 2):\n        # Perform reshape in original NHWC format.\n        inexpr = _op.transpose(inexpr, [0] + list(range(2, len(inshape))) + [1])\n        inexpr = _op.reshape(inexpr, newshape=shape)\n        return _op.transpose(inexpr, axes=[0, -1] + list(range(1, len(shape) - 1)))\n\n    return _op.reshape(inexpr, newshape=shape)\n\n\ndef _convert_lstm(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    if not isinstance(inexpr, list):\n        buf = np.zeros((1, keras_layer.units), \"float32\")\n        c_op = etab.new_const(buf)\n        h_op = etab.new_const(buf)\n        inexpr = [inexpr, h_op, c_op]\n    in_data = inexpr[0]\n    next_h = inexpr[1]\n    next_c = inexpr[2]\n    weightList = keras_layer.get_weights()\n    in_shape = tuple(dim if dim else 1 for dim in _as_list(input_shape)[0])\n    kernel_weight = etab.new_const(weightList[0].transpose([1, 0]))\n    recurrent_weight = etab.new_const(weightList[1].transpose([1, 0]))\n    if keras_layer.use_bias:\n        in_bias = etab.new_const(weightList[2])\n    units = list(weightList[0].shape)[1]\n    time_steps = in_shape[1]\n    in_data = _op.squeeze(in_data, axis=[0])\n    in_data = _op.split(in_data, indices_or_sections=time_steps, axis=0)\n    # loop for the number of time_steps\n    out_list = []  # store h outputs in case return_sequences is True\n    for data in in_data:\n        ixh1 = _op.nn.dense(data, kernel_weight, units=units)\n        ixh2 = _op.nn.dense(next_h, recurrent_weight, units=units)\n        if keras_layer.use_bias:\n            ixh2 = _op.nn.bias_add(ixh2, bias=in_bias)\n        gate = ixh1 + ixh2\n        gates = _op.split(gate, indices_or_sections=4, axis=1)\n        in_gate = _convert_recurrent_activation(gates[0], keras_layer)\n        in_transform = _convert_recurrent_activation(gates[1], keras_layer)\n        next_c = in_transform * next_c + in_gate * _convert_activation(\n            gates[2], keras_layer, etab, data_layout\n        )\n        out_gate = _convert_recurrent_activation(gates[3], keras_layer)\n        next_h = out_gate * _convert_activation(next_c, keras_layer, etab, data_layout)\n        if keras_layer.return_sequences:\n            out_list.append(_op.expand_dims(next_h, axis=1))\n    out = _op.concatenate(out_list, axis=1) if keras_layer.return_sequences else next_h\n    out_shape = tuple(dim if dim else 1 for dim in _as_list(keras_layer.output_shape)[0])\n    out = _op.reshape(out, newshape=out_shape)\n    return [out, next_h, next_c]\n\n\ndef _convert_simple_rnn(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    if not isinstance(inexpr, list):\n        buf = np.zeros((1, keras_layer.units), \"float32\")\n        prev_op = etab.new_const(buf)\n        inexpr = [inexpr, prev_op]\n    in_data = inexpr[0]\n    prev_op = inexpr[1]\n    weightList = keras_layer.get_weights()\n    kernel_weight = etab.new_const(weightList[0].transpose([1, 0]))\n    recurrent_weight = etab.new_const(weightList[1].transpose([1, 0]))\n    if keras_layer.use_bias:\n        in_bias = etab.new_const(weightList[2])\n    units = list(weightList[0].shape)[1]\n    in_data = _op.nn.batch_flatten(in_data)\n    ixh = _op.nn.dense(in_data, kernel_weight, units=units)\n    if keras_layer.use_bias:\n        ixh = _op.nn.bias_add(ixh, bias=in_bias)\n    prev_op = _op.nn.batch_flatten(prev_op)\n    ixh2 = _op.nn.dense(prev_op, recurrent_weight, units=units)\n    output = ixh + ixh2\n    output = _convert_activation(output, keras_layer, etab, data_layout)\n    out_shape = tuple(dim if dim else 1 for dim in _as_list(keras_layer.output_shape)[0])\n    output = _op.reshape(output, newshape=out_shape)\n    return [output, output]\n\n\ndef _convert_gru(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    _check_data_format(keras_layer)\n    if not isinstance(inexpr, list):\n        buf = np.zeros((1, keras_layer.units), \"float32\")\n        h_tm1 = etab.new_const(buf)\n        inexpr = [inexpr, h_tm1]\n    in_data = inexpr[0]\n    h_tm1_op = inexpr[1]\n    weightList = keras_layer.get_weights()\n    kernel_weight = etab.new_const(weightList[0].transpose([1, 0]))\n    recurrent_weight = etab.new_const(weightList[1].transpose([1, 0]))\n    if keras_layer.use_bias:\n        in_bias = etab.new_const(weightList[2])\n    units = list(weightList[0].shape)[1]\n    in_data = _op.nn.batch_flatten(in_data)\n    matrix_x = _op.nn.dense(in_data, kernel_weight, units=units)\n    if keras_layer.use_bias:\n        matrix_x = _op.nn.bias_add(matrix_x, in_bias)\n    # inputs projected by all gate matrices at once\n    split_indices = [keras_layer.units, 2 * keras_layer.units]\n    gates = _op.split(matrix_x, indices_or_sections=split_indices, axis=1)\n    x_z = gates[0]\n    x_r = gates[1]\n    x_h = gates[2]\n    # hidden state projected separately for update/reset and new\n    units = 2 * keras_layer.units\n    split_indices = [units]\n    rec_weights = _op.split(recurrent_weight, indices_or_sections=split_indices, axis=0)\n    h_tm1_op = _op.nn.batch_flatten(h_tm1_op)\n    matrix_inner = _op.nn.dense(h_tm1_op, rec_weights[0], units=units)\n    split_indices = [keras_layer.units]\n    recurrent = _op.split(matrix_inner, indices_or_sections=split_indices, axis=1)\n    recurrent_z = recurrent[0]\n    recurrent_r = recurrent[1]\n    rec_act_z = _convert_recurrent_activation(x_z + recurrent_z, keras_layer)\n    rec_act_r = _convert_recurrent_activation(x_r + recurrent_r, keras_layer)\n    units = keras_layer.units\n    recurrent_h = _op.nn.dense(rec_act_r * h_tm1_op, rec_weights[1], units=units)\n    act_hh = _convert_activation(x_h + recurrent_h, keras_layer, etab, data_layout)\n    # previous and candidate state mixed by update gate\n    output = rec_act_z * h_tm1_op + (_expr.const(1.0, dtype=\"float32\") - rec_act_z) * act_hh\n    out_shape = tuple(dim if dim else 1 for dim in _as_list(keras_layer.output_shape)[0])\n    output = _op.reshape(output, newshape=out_shape)\n    return [output, output]\n\n\ndef _convert_repeat_vector(\n    inexpr, keras_layer, etab, data_layout, input_shape=None\n):  # pylint: disable=unused-argument\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n    input_shape = list(input_shape)\n    repeats = keras_layer.n\n    out_shape = [-1, repeats] + input_shape[1:]\n    out = _op.repeat(inexpr, repeats=repeats, axis=0)\n    out = _op.reshape(out, out_shape)\n    return out\n\n\ndef _convert_l2_normalize(inexpr, keras_layer, data_layout):\n    l2_normalize_is_loaded = False\n    param_list = []\n    for i in dis.get_instructions(keras_layer.function):\n        if i.opname in [\"LOAD_GLOBAL\", \"LOAD_DEREF\"]:\n            continue\n        if i.opname in [\"LOAD_ATTR\", \"LOAD_METHOD\"]:\n            if i.argval == \"l2_normalize\":\n                assert not l2_normalize_is_loaded, \"l2_normalize was already LOADED\"\n                l2_normalize_is_loaded = True\n        elif i.opname in [\"LOAD_CONST\", \"LOAD_FAST\"] and l2_normalize_is_loaded:\n            param_list.append(i.argval)\n        elif i.opname == \"BUILD_LIST\":\n            sz = i.argval\n            assert len(param_list) >= sz\n            new_list = param_list[-sz:]\n            param_list = param_list[:-sz]\n            param_list.append(new_list)\n        elif i.opname in [\"CALL_FUNCTION_KW\", \"CALL_METHOD\"]:\n            break\n\n    axis = None\n    is_param_list_parsed = False\n    if l2_normalize_is_loaded and len(param_list) > 0:\n        # last param_list item is tuple of strings means that\n        # lambda uses named parameters when calling l2_normalize\n        if (\n            isinstance(param_list[-1], tuple)\n            and len(param_list[-1]) > 0\n            and isinstance(param_list[-1][0], str)\n        ):\n            param_names = param_list[-1]\n            if len(param_names) == 1 and param_names[0] == \"x\":\n                # lambda v: K.l2_normalize(x=v)\n                axis = None\n                is_param_list_parsed = True\n            elif len(param_names) == 1 and param_names[0] == \"axis\" and len(param_list) == 3:\n                # lambda x: K.l2_normalize(x, axis=(2,3))\n                axis = param_list[1]\n                is_param_list_parsed = True\n            elif len(param_names) == 2 and len(param_list) == 3:\n                # lambda x: K.l2_normalize(x=x, axis=(2,3))\n                # lambda x: K.l2_normalize(axis=(2,3), x=x)\n                axis = param_list[param_names.index(\"axis\")]\n                is_param_list_parsed = True\n        else:\n            # lambda x: K.l2_normalize(x)\n            if len(param_list) == 1:\n                axis = None\n                is_param_list_parsed = True\n            # lambda x: K.l2_normalize(x, (2,3))\n            elif len(param_list) == 2:\n                axis = param_list[1]\n                is_param_list_parsed = True\n\n    def is_int_or_tuple_of_ints(v):\n        if isinstance(v, list) and len(v) > 0:\n            for i in v:\n                if not isinstance(i, int):\n                    return False\n            return True\n        if isinstance(v, tuple) and len(v) > 0:\n            return isinstance(v[0], int)\n        return isinstance(v, int)\n\n    assert is_param_list_parsed and (\n        axis is None or is_int_or_tuple_of_ints(axis)\n    ), \"Can not parse l2_normalize lambda function found in Lambda layer\"\n    if isinstance(axis, int):\n        axis = [axis]\n\n    if data_layout == \"NCHW\":\n        dims = len(keras_layer.input_shape)\n\n        def fix_axis_for_nchw(axis):\n            if axis == 0:\n                return 0\n            if axis in [(dims - 1), -1]:\n                return 1\n            return axis + 1\n\n        axis = [fix_axis_for_nchw(x) for x in axis]\n    return _op.nn.l2_normalize(inexpr, eps=1e-12, axis=axis)\n\n\ndef _convert_lambda(inexpr, keras_layer, _, data_layout):\n    fcode = keras_layer.function.__code__\n    # Convert l2_normalize\n    if (\n        fcode.co_name == \"<lambda>\"\n        and len(fcode.co_names) > 0\n        and fcode.co_names[-1] == \"l2_normalize\"\n    ):\n        return _convert_l2_normalize(inexpr, keras_layer, data_layout)\n    raise tvm.error.OpNotImplemented(\n        \"Function {} used in Lambda layer is not supported in frontend Keras.\".format(\n            fcode.co_names\n        )\n    )\n\n\ndef _convert_time_distributed(inexpr, keras_layer, etab, data_layout, input_shape=None):\n    # TimeDistributed: split input tensor along the second dimension (assumed to be time),\n    # apply inner layer to each split individually,\n    # and then combine the results\n    if input_shape is None:\n        input_shape = keras_layer.input_shape\n\n    assert len(input_shape) >= 2, \"Input to TimeDistributed must have at least two dimensions\"\n\n    inner_layer = keras_layer.layer\n    inner_input_shape = [d for (i, d) in enumerate(input_shape) if i != 1]\n\n    # for NDHWC, inner data layout will drop the D\n    inner_data_layout = data_layout\n    if data_layout == \"NDHWC\":\n        inner_data_layout = \"NHWC\"\n\n    # some code duplication from keras_op_to_relay\n    # but it's useful to avoid cluttering the etab\n    inner_layer_op_name = type(keras_layer.layer).__name__\n    if inner_layer_op_name not in _convert_map:\n        raise tvm.error.OpNotImplemented(\n            \"The inner layer for TimeDistributed {} is not supported for frontend Keras.\".format(\n                inner_layer_op_name\n            )\n        )\n\n    conversion_func = lambda expr: _convert_map[inner_layer_op_name](\n        expr, inner_layer, etab, inner_data_layout, input_shape=inner_input_shape\n    )\n\n    split_dim = input_shape[1]\n    split_input = _op.split(inexpr, split_dim, 1)\n\n    split_shape = list(input_shape)\n    if split_shape[0] is None:\n        split_shape[0] = 1\n    split_shape[1] = 1\n\n    split_var = new_var(\n        \"time_distributed_split\",\n        type_annotation=TupleType(\n            [TensorType(split_shape, dtype=\"float32\") for i in range(split_dim)]\n        ),\n    )\n\n    # For each split, squeeze away the second dimension,\n    # apply the inner layer.\n    # Afterwards, combine the transformed splits back along\n    # the second dimension using stack\n    splits = [\n        conversion_func(_op.squeeze(_expr.TupleGetItem(split_var, i), axis=[1]))\n        for i in range(split_dim)\n    ]\n\n    return _expr.Let(split_var, split_input.astuple(), _op.stack(splits, axis=1))\n\n\ndef _default_skip(inexpr, keras_layer, etab, data_layout):  # pylint: disable=unused-argument\n    \"\"\"Layers that can be skipped because they are train time only.\"\"\"\n    return inexpr\n\n\n_convert_map = {\n    \"Dense\": _convert_dense,\n    \"Activation\": _convert_activation,\n    \"Softmax\": _convert_advanced_activation,\n    \"ReLU\": _convert_advanced_activation,\n    \"LeakyReLU\": _convert_advanced_activation,\n    \"PReLU\": _convert_advanced_activation,\n    \"ELU\": _convert_advanced_activation,\n    \"ThresholdedReLU\": _convert_advanced_activation,\n    \"AveragePooling2D\": _convert_pooling,\n    \"MaxPooling2D\": _convert_pooling,\n    \"GlobalAveragePooling2D\": _convert_pooling,\n    \"GlobalMaxPooling2D\": _convert_pooling,\n    \"Conv2D\": _convert_convolution,\n    \"Conv2DTranspose\": _convert_convolution,\n    \"DepthwiseConv2D\": _convert_convolution,\n    \"SeparableConv2D\": _convert_separable_convolution,\n    \"Flatten\": _convert_flatten,\n    \"Reshape\": _convert_reshape,\n    \"Concatenate\": _convert_concat,\n    \"BatchNormalization\": _convert_batchnorm,\n    # Specific tf.Keras terminology for batch normalization\n    \"BatchNormalizationV1\": _convert_batchnorm,\n    \"Add\": _convert_merge,\n    \"Subtract\": _convert_merge,\n    \"Multiply\": _convert_merge,\n    \"ZeroPadding2D\": _convert_padding,\n    \"UpSampling2D\": _convert_upsample,\n    \"Cropping2D\": _convert_cropping,\n    # 'ZeroPadding1D'          : _convert_padding,\n    # 'AveragePooling1D'       : _convert_pooling,\n    # 'MaxPooling1D'           : _convert_pooling,\n    # 'GlobalAveragePooling1D' : _convert_pooling,\n    # 'GlobalMaxPooling1D'     : _convert_pooling,\n    # 'Cropping1D'             : _convert_cropping,\n    # 'UpSampling1D'           : _convert_upsample,\n    \"Conv1D\": _convert_convolution1d,\n    # \"Conv1DTranspose\": _convert_convolution1d,\n    \"Conv3D\": _convert_convolution3d,\n    \"Conv3DTranspose\": _convert_convolution3d,\n    # 'SeparableConv3D'        : _convert_convolution3d,\n    \"MaxPooling3D\": _convert_pooling3d,\n    \"AveragePooling3D\": _convert_pooling3d,\n    \"GlobalMaxPooling3D\": _convert_global_pooling3d,\n    \"GlobalAveragePooling3D\": _convert_global_pooling3d,\n    \"UpSampling3D\": _convert_upsample3d,\n    \"ZeroPadding3D\": _convert_padding3d,\n    \"SimpleRNN\": _convert_simple_rnn,\n    \"LSTM\": _convert_lstm,\n    \"GRU\": _convert_gru,\n    # 'Bidirectional'          : _convert_bidirectional,\n    \"TimeDistributed\": _convert_time_distributed,\n    \"Average\": _convert_merge,\n    \"Minimum\": _convert_merge,\n    \"Maximum\": _convert_merge,\n    \"Dot\": _convert_merge,\n    \"Permute\": _convert_permute,\n    \"Embedding\": _convert_embedding,\n    \"RepeatVector\": _convert_repeat_vector,\n    \"Lambda\": _convert_lambda,\n    \"InputLayer\": _default_skip,\n    \"Dropout\": _default_skip,\n    \"AlphaDropout\": _default_skip,\n    \"SpatialDropout2D\": _default_skip,\n    \"SpatialDropout1D\": _default_skip,\n    \"GaussianDropout\": _default_skip,\n    \"GaussianNoise\": _default_skip,\n}\n\n\ndef _check_unsupported_layers(model):\n    missing_ops = set()\n    for layer in model.layers:\n        op_name = type(layer).__name__\n        if op_name not in _convert_map:\n            missing_ops.add(op_name)\n\n    if missing_ops:\n        raise NotImplementedError(\n            \"The following operators are not implemented: {}\".format(missing_ops)\n        )\n\n\ndef keras_op_to_relay(inexpr, keras_layer, outname, etab, data_layout):\n    \"\"\"Convert a Keras layer to a Relay expression and update the expression table.\n\n    Parameters\n    ----------\n    inexpr : relay.expr.Expr or a list of it\n        The input Relay expression(s).\n\n    keras_layer : keras.layers\n        The Keras layer to be converted.\n\n    outname : str\n        Name of the output Relay expression.\n\n    etab : relay.frontend.common.ExprTable\n        The global expression table to be updated.\n\n    data_layout : str\n        The input data layout\n    \"\"\"\n    op_name = type(keras_layer).__name__\n    if op_name not in _convert_map:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend Keras.\".format(op_name)\n        )\n    outs = _convert_map[op_name](inexpr, keras_layer, etab, data_layout)\n    outs = _as_list(outs)\n    for t_idx, out in enumerate(outs):\n        name = outname + \":\" + str(t_idx)\n        etab.set_expr(name, out)\n    return outs\n\n\ndef from_keras(model, shape=None, layout=\"NCHW\"):\n    \"\"\"Convert keras model to relay Function.\n\n    Parameters\n    ----------\n    model : keras.engine.training.Model or tensorflow.keras.models.Model\n        The keras model to be converted.\n\n    shape: dict of str to int list/tuple\n        Input shapes of the model, optional\n\n    layout: str\n        One of 'NCHW' or 'NHWC', indicates how data should be arranged in\n        the output model. Default layout is 'NCHW' as it in general\n        performs better across TVM.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation.\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by Relay.\n    \"\"\"\n\n    def _check_model_is_tf_keras():\n        return type(model).__module__.startswith(\"tensorflow.python.keras\")\n\n    def _convert_input_layer(keras_layer):\n        input_name = keras_layer.name\n        input_shape = shape[input_name] if shape is not None and input_name in shape else None\n        etab.set_expr(input_name, new_var(input_name, shape=input_shape))\n\n    def _convert_layer(keras_layer, etab, scope=\"\"):\n        inbound_nodes = (\n            keras_layer.inbound_nodes\n            if hasattr(keras_layer, \"inbound_nodes\")\n            else keras_layer._inbound_nodes\n            if hasattr(keras_layer, \"_inbound_nodes\")\n            else None\n        )\n        if inbound_nodes is None:\n            raise TypeError(\n                \"Unknown layer type or unsupported Keras version : {}\".format(keras_layer)\n            )\n        outs = []\n        for node_idx, node in enumerate(inbound_nodes):\n            # If some nodes in imported model are not relevant to the current model,\n            # skip such layers.\n            # - In Keras, model._network_nodes contains keys of all nodes relevant to the\n            #   current model;\n            # - In tf.Keras, this is already done as part of tensorflow.keras.network.get_config\n            if not is_tf_keras:\n                if (\n                    hasattr(model, \"_node_key\")\n                    and not model._node_key(keras_layer, node_idx) in model._network_nodes\n                ):\n                    continue\n            inexpr = []\n            # Since Keras allows creating multiple layers from the same name instance,\n            # we append node index to the expr name to make it unique.\n            # The one exception is InputLayer. Changing input variable names after conversion\n            # would confuse users, so we should keep them as far as possible. Fortunately,\n            # they are named uniquely to input_1, input_2, input_3... by default.\n            # node_indices attribute removed in tensorflow 2.3, however iterate_inbound() can\n            # be used\n            if hasattr(node, \"node_indices\"):\n                zip_node = zip(\n                    _as_list(node.inbound_layers),\n                    _as_list(node.node_indices),\n                    _as_list(node.tensor_indices),\n                    _as_list(node.input_tensors),\n                )\n                node_attributes = zip_node\n            else:\n                node_attributes = node.iterate_inbound()\n\n            for inbound_layer, n_idx, t_idx, _ in node_attributes:\n                if isinstance(inbound_layer, input_layer_class):\n                    expr_name = inbound_layer.name\n                    _convert_input_layer(inbound_layer)\n                else:\n                    expr_name = scope + inbound_layer.name + \":\" + str(n_idx) + \":\" + str(t_idx)\n                expr = etab.get_expr(expr_name)\n                inexpr.append(expr)\n\n            # Handle nested layers\n            if hasattr(keras_layer, \"layers\"):\n                input_index = 0\n                for layer in keras_layer.layers:\n                    if isinstance(layer, input_layer_class):\n                        # Replace input layer with inbound node\n                        etab.set_expr(layer.name, inexpr[input_index])\n                        input_index += 1\n                    else:\n                        # Convert child layer. Prepend scope with parent layer name.\n                        layer_outs = _convert_layer(layer, etab, keras_layer.name + \"_\" + scope)\n\n                # Get output of last child layer and mark as output of parent.\n                outname = keras_layer.name + \":\" + str(node_idx)\n                for t_idx, out in enumerate(layer_outs):\n                    name = outname + \":\" + str(t_idx)\n                    etab.set_expr(name, out)\n                outs.extend(layer_outs)\n            else:\n                if len(inexpr) == 1:\n                    inexpr = inexpr[0]\n                outs.extend(\n                    keras_op_to_relay(\n                        inexpr,\n                        keras_layer,\n                        scope + keras_layer.name + \":\" + str(node_idx),\n                        etab,\n                        layout,\n                    )\n                )\n        return outs\n\n    is_tf_keras = _check_model_is_tf_keras()\n\n    if not is_tf_keras:\n        # Importing from Keras\n        try:\n            import keras\n        except ImportError:\n            raise ImportError(\"Keras must be installed\")\n        if keras.backend.backend() != \"tensorflow\":\n            raise ValueError(\"Keras frontend currently supports tensorflow backend only.\")\n        if keras.backend.image_data_format() != \"channels_last\":\n            raise ValueError(\"Keras frontend currently supports data_format = channels_last only.\")\n        expected_model_class = keras.engine.training.Model\n        if hasattr(keras.engine, \"InputLayer\"):\n            input_layer_class = keras.engine.InputLayer\n        else:\n            # TFlite >=2.6\n            input_layer_class = keras.engine.input_layer.InputLayer\n    else:\n        # Importing from Tensorflow Keras (tf.keras)\n        try:\n            from tensorflow import keras as tf_keras\n        except ImportError:\n            raise ImportError(\"Tensorflow must be installed\")\n        expected_model_class = tf_keras.models.Model\n        input_layer_class = tf_keras.layers.InputLayer\n\n    assert isinstance(model, expected_model_class)\n\n    etab = ExprTable()\n    # Set global data format.\n    assert layout in [\n        \"NWC\",\n        \"NCHW\",\n        \"NHWC\",\n        \"NDHWC\",\n    ], \"Layout must be one of 'NWC', 'NCHW', NHWC or NDHWC\"\n    for keras_layer in model.layers:\n        if isinstance(keras_layer, input_layer_class):\n            _convert_input_layer(keras_layer)\n        else:\n            _convert_layer(keras_layer, etab)\n\n    # model._output_coordinates contains out_node(oc[0]), node_index(oc[1]) and tensor_index(oc[2])\n    # Get all output nodes in etab using the name made from above values.\n    # The out exprs were added to etab in keras_op_to_relay using this name.\n    outexpr = [\n        etab.get_expr(oc[0].name + \":\" + str(oc[1]) + \":\" + str(oc[2]))\n        for oc in model._output_coordinates\n    ]\n    outexpr = outexpr[0] if len(outexpr) == 1 else _expr.Tuple(outexpr)\n    func = _function.Function(analysis.free_vars(outexpr), outexpr)\n    params = {k: _nd.array(np.array(v, dtype=np.float32)) for k, v in etab.params.items()}\n    return IRModule.from_expr(func), params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/mxnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, no-else-return, too-many-lines\n\"\"\"MXNet symbol frontend.\"\"\"\nimport json\nimport math\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .. import scope_builder as _scope_builder\nfrom .common import StrAttrsDict\nfrom .common import get_name as _get_name\nfrom .common import infer_shape as _infer_shape\nfrom .common import infer_type as _infer_type\nfrom .common import infer_value as _infer_value\nfrom .mxnet_qnn_op_utils import (\n    dequantize_mxnet_min_max,\n    get_conv_mkldnn_requantized_scale_outDtype,\n    get_mkldnn_int8_scale,\n    get_mkldnn_requantize_scale_outDtype,\n    get_mkldnn_uint8_scale,\n    quantize_conv_bias_mkldnn_from_var,\n    quantize_conv_weights_bias_channel_mkldnn_from_var,\n    quantize_mxnet_min_max,\n)\nfrom .nnvm_common import (\n    _arg_reduce,\n    _binop_scalar,\n    _cast,\n    _clip,\n    _elemwise_sum,\n    _init_op,\n    _rbinop_scalar,\n    _reduce,\n    _rename,\n    _reshape,\n    _softmax_op,\n    _transpose,\n    _upsampling,\n    _warn_not_used,\n)\n\n__all__ = [\"from_mxnet\"]\n\n_activation_map = {\"sigmoid\": _op.sigmoid, \"tanh\": _op.tanh, \"relu\": _op.nn.relu}\n\n\ndef _mx_fully_connected(inputs, attrs):\n    import mxnet as mx  # pylint: disable=import-outside-toplevel\n\n    units = attrs.get_int(\"num_hidden\")\n    use_bias = not attrs.get_bool(\"no_bias\", False)\n    try:\n        _ = mx.sym.FullyConnected(mx.sym.var(\"x\"), num_hidden=1, flatten=True)\n        has_flatten = True\n    except mx.base.MXNetError:\n        # no flatten attribute in old mxnet\n        has_flatten = False\n    use_flatten = attrs.get_bool(\"flatten\", True)\n    if has_flatten and use_flatten:\n        inputs[0] = _op.nn.batch_flatten(inputs[0])\n    data_shape = _infer_type(inputs[0]).checked_type.shape\n    if len(data_shape) > 2:\n        inputs[0] = _op.reverse_reshape(inputs[0], [-1, 0])\n    res = _op.nn.dense(inputs[0], inputs[1], units=units)\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=-1)\n    if len(data_shape) > 2:\n        new_shape = data_shape[:-1]\n        new_shape.append(units)\n        res = _op.reshape(res, new_shape)\n    return res\n\n\ndef _get_channel_axis(layout, op_name):\n    if layout in [\"NCHW\", \"NCDHW\"]:\n        return 1\n    if layout == \"NHWC\":\n        return 3\n    if layout == \"NDHWC\":\n        return 4\n    raise tvm.error.OpAttributeInvalid(\n        'Value {} in attribute \"layout\" of operator {} is not valid.'.format(layout, op_name)\n    )\n\n\ndef _mx_activations(inputs, attrs):\n    act_type = attrs.get_str(\"act_type\")\n    assert len(inputs) == 1\n    if act_type == \"softrelu\":\n\n        def _stable_softrelu(x):\n            # log(1 + exp(-abs(x))) + relu(x)\n            one = _expr.const(1, dtype=\"float32\")\n            exp_neg_abs_x = _op.exp(_op.negative(_op.abs(x)))\n            return _op.add(_op.log(_op.add(one, exp_neg_abs_x)), _op.nn.relu(x))\n\n        return _stable_softrelu(inputs[0])\n    if act_type not in _activation_map:\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} is not supported for frontend MXNet.\".format(act_type)\n        )\n    return _activation_map[act_type](inputs[0])\n\n\ndef _mx_compare(new_op, wrapper):\n    def impl(inputs, attrs):\n        expr = _infer_type(inputs[0])\n        dtype = expr.checked_type.dtype\n        return wrapper(new_op)(inputs, attrs).astype(dtype)\n\n    return impl\n\n\ndef _mx_unravel_index(inputs, attrs):\n    assert len(inputs) == 1\n    shape = attrs.get_int_tuple(\"shape\")\n    shape_expr = _expr.const(list(shape))\n    return _op.unravel_index(inputs[0], shape_expr)\n\n\ndef _mx_swap_axis(inputs, attrs):\n    assert len(inputs) == 1\n    dim1 = attrs.get_int(\"dim1\")\n    dim2 = attrs.get_int(\"dim2\")\n    shape = _infer_type(inputs[0]).checked_type.shape\n    axes = list(range(len(shape)))\n    axes[dim1] = dim2\n    axes[dim2] = dim1\n    return _op.transpose(inputs[0], axes=axes)\n\n\ndef _mx_zeros(inputs, attrs):\n    assert len(inputs) == 0\n    shape = attrs.get_int_tuple(\"shape\")\n    dtype = attrs.get_str(\"dtype\", \"float32\")\n    if 0 in shape:\n        return None\n    return _op.zeros(shape=shape, dtype=dtype)\n\n\ndef _mx_conv(inputs, attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    if len(kernel_size) == 3:\n        return _mx_conv3d(inputs, attrs)\n    elif len(kernel_size) == 2:\n        return _mx_conv2d(inputs, attrs)\n    elif len(kernel_size) == 1:\n        return _mx_conv1d(inputs, attrs)\n    else:\n        raise tvm.error.OpAttributeInvalid(\n            \"1D, 2D or 3D kernels only are supported for operator Convolution\"\n        )\n\n\ndef _mx_conv1d(inputs, attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    if len(kernel_size) != 1:\n        raise tvm.error.OpAttributeInvalid(\n            \"Non 1D or 2D kernels are not supported for operator Convolution\"\n        )\n    data_layout = attrs.get_str(\"layout\", \"NCW\")\n    # MXNet Conv1D only supports \u2018NCW\u2019 layout for now.\n    if data_layout != \"NCW\":\n        raise tvm.error.OpAttributeInvalid('Only \"NCW\" data layout is supported for 1D Convolution')\n    data_layout = \"NCHW\"\n    channel_axis = 1\n    kernel_layout = \"OIHW\"\n\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = (1,) + kernel_size\n    new_attrs[\"strides\"] = (1,) + attrs.get_int_tuple(\"stride\", (1,))\n    new_attrs[\"padding\"] = (0,) + attrs.get_int_tuple(\"pad\", (0,))\n    new_attrs[\"dilation\"] = (1,) + attrs.get_int_tuple(\"dilate\", (1,))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    use_bias = not attrs.get_bool(\"no_bias\", False)\n    data = _op.expand_dims(inputs[0], axis=2)\n    kernel = _op.expand_dims(inputs[1], axis=2)\n    res = _op.nn.conv2d(data, kernel, **new_attrs)\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    res = _op.squeeze(res, axis=[2])\n    return res\n\n\ndef _get_mx_conv2d_attrs(attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    data_layout = attrs.get_str(\"layout\", \"NCHW\")\n    if \"kernel_layout\" in attrs.attrs:\n        kernel_layout = attrs.get_str(\"kernel_layout\")\n    else:\n        kernel_layout = \"HWIO\" if data_layout == \"NHWC\" else \"OIHW\"\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = kernel_size\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1))\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0))\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\", (1, 1))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    return new_attrs\n\n\ndef _mx_conv2d(inputs, attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    data_layout = attrs.get_str(\"layout\", \"NCHW\")\n    if len(kernel_size) != 2:\n        raise tvm.error.OpAttributeInvalid(\"Only 2D kernels are supported for operator Convolution\")\n\n    new_attrs = _get_mx_conv2d_attrs(attrs)\n    channel_axis = _get_channel_axis(data_layout, \"conv2d\")\n    use_bias = not attrs.get_bool(\"no_bias\", False)\n    res = _op.nn.conv2d(inputs[0], inputs[1], **new_attrs)\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    return res\n\n\ndef _get_mx_conv3d_attrs(attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    data_layout = attrs.get_str(\"layout\", \"NCDHW\")\n    if \"kernel_layout\" in attrs.attrs:\n        kernel_layout = attrs.get_str(\"kernel_layout\")\n    else:\n        kernel_layout = \"DHWIO\" if data_layout == \"NDHWC\" else \"OIDHW\"\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = kernel_size\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1, 1))\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0, 0))\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\", (1, 1, 1))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    return new_attrs\n\n\ndef _mx_conv3d(inputs, attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    data_layout = attrs.get_str(\"layout\", \"NCDHW\")\n    if len(kernel_size) != 3:\n        raise tvm.error.OpAttributeInvalid(\"Only 3D kernels are supported for operator Convolution\")\n\n    new_attrs = _get_mx_conv3d_attrs(attrs)\n    channel_axis = _get_channel_axis(data_layout, \"conv3d\")\n    use_bias = not attrs.get_bool(\"no_bias\", False)\n    res = _op.nn.conv3d(inputs[0], inputs[1], **new_attrs)\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    return res\n\n\ndef _mx_conv_transpose(inputs, attrs):\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    if len(kernel_size) == 3:\n        return _mx_conv3d_transpose(inputs, attrs)\n    elif len(kernel_size) == 2:\n        return _mx_conv2d_transpose(inputs, attrs)\n    elif len(kernel_size) == 1:\n        return _mx_conv1d_transpose(inputs, attrs)\n    else:\n        raise tvm.error.OpAttributeInvalid(\n            \"1D, 2D or 3D kernels only are supported for operator Convolution\"\n        )\n\n\ndef _mx_conv1d_transpose(inputs, attrs):\n    if \"target_shape\" in attrs.attrs:\n        raise tvm.error.OpAttributeUnImplemented(\n            'Attribute \"target_shape\" is not supported for operator Conv2D-transpose.'\n        )\n    data_layout = attrs.get_str(\"layout\", \"NCW\")\n    if data_layout != \"NCW\":\n        raise tvm.error.OpAttributeInvalid('Only \"NCW\" data layout is supported for 1D Convolution')\n    channel_axis = 1\n    kernel_layout = \"OIW\"\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = attrs.get_int_tuple(\"kernel\")\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1,))\n    new_attrs[\"output_padding\"] = attrs.get_int_tuple(\"adj\", (0,))\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0,))\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\", (1,))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    use_bias = not attrs.get_bool(\"no_bias\", True)\n    res = _op.nn.conv1d_transpose(inputs[0], inputs[1], **new_attrs)\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    return res\n\n\ndef _mx_conv2d_transpose(inputs, attrs):\n    if \"target_shape\" in attrs.attrs:\n        raise tvm.error.OpAttributeUnImplemented(\n            'Attribute \"target_shape\" is not supported for operator Conv2D-transpose.'\n        )\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    if len(kernel_size) != 2:\n        raise tvm.error.OpAttributeInvalid(\n            \"Non-2D kernels are not supported for operator Conv2D-transpose.\"\n        )\n    data_layout = attrs.get_str(\"layout\", \"NCHW\")\n    channel_axis = _get_channel_axis(data_layout, \"conv2d_transpose\")\n\n    if \"kernel_layout\" in attrs.attrs:\n        kernel_layout = attrs.get_str(\"kernel_layout\")\n    else:\n        kernel_layout = \"HWIO\" if data_layout == \"NHWC\" else \"IOHW\"\n\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = kernel_size\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1))\n    new_attrs[\"output_padding\"] = attrs.get_int_tuple(\"adj\", (0, 0))\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0))\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\", (1, 1))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    use_bias = not attrs.get_bool(\"no_bias\", True)\n    res = _op.nn.conv2d_transpose(inputs[0], inputs[1], **new_attrs)\n\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    return res\n\n\ndef _mx_conv3d_transpose(inputs, attrs):\n    if \"target_shape\" in attrs.attrs:\n        raise tvm.error.OpAttributeUnImplemented(\n            'Attribute \"target_shape\" is not supported for operator Conv3D-transpose.'\n        )\n    kernel_size = attrs.get_int_tuple(\"kernel\")\n    if len(kernel_size) != 3:\n        raise tvm.error.OpAttributeInvalid(\n            \"Non-3D kernels are not supported for operator Conv3D-transpose.\"\n        )\n    data_layout = attrs.get_str(\"layout\", \"NCDHW\")\n    channel_axis = _get_channel_axis(data_layout, \"conv3d_transpose\")\n\n    if \"kernel_layout\" in attrs.attrs:\n        kernel_layout = attrs.get_str(\"kernel_layout\")\n    else:\n        kernel_layout = \"DHWIO\" if data_layout == \"NDHWC\" else \"OIDHW\"\n\n    new_attrs = {}\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"kernel_size\"] = kernel_size\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1, 1))\n    new_attrs[\"output_padding\"] = attrs.get_int_tuple(\"adj\", (0, 0, 0))\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0, 0))\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\", (1, 1, 1))\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    new_attrs[\"data_layout\"] = data_layout\n    new_attrs[\"kernel_layout\"] = kernel_layout\n    use_bias = not attrs.get_bool(\"no_bias\", True)\n    res = _op.nn.conv3d_transpose(inputs[0], inputs[1], **new_attrs)\n\n    if use_bias:\n        assert len(inputs) == 3\n        res = _op.nn.bias_add(res, inputs[2], axis=channel_axis)\n    return res\n\n\ndef _mx_pooling(inputs, attrs):\n    global_pool = attrs.get_bool(\"global_pool\", False)\n    pool_type = attrs.get_str(\"pool_type\")\n\n    def _pool2d(new_op, is_avg):\n        kernel_size = attrs.get_int_tuple(\"kernel\")\n        if len(kernel_size) != 2:\n            raise tvm.error.OpAttributeInvalid(\"Only 2D kernels are supported for operator Pool2D.\")\n        new_attrs = {}\n        new_attrs[\"pool_size\"] = kernel_size\n        new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1))\n        new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0))\n        new_attrs[\"ceil_mode\"] = attrs.get_str(\"pooling_convention\", \"valid\") == \"full\"\n        if is_avg:\n            new_attrs[\"count_include_pad\"] = attrs.get_bool(\"count_include_pad\", True)\n        return new_op(inputs[0], **new_attrs)\n\n    def _pool3d(new_op, is_avg):\n        kernel_size = attrs.get_int_tuple(\"kernel\")\n        if len(kernel_size) != 3:\n            raise tvm.error.OpAttributeInvalid(\"Only 3D kernels are supported for operator Pool3D.\")\n        new_attrs = {}\n        new_attrs[\"pool_size\"] = kernel_size\n        new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\", (1, 1, 1))\n        new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\", (0, 0, 0))\n        new_attrs[\"ceil_mode\"] = attrs.get_str(\"pooling_convention\", \"valid\") == \"full\"\n        if is_avg:\n            new_attrs[\"count_include_pad\"] = attrs.get_bool(\"count_include_pad\", True)\n        return new_op(inputs[0], **new_attrs)\n\n    # 3D pooling\n    if len(_infer_shape(inputs[0])) == 5:\n        if pool_type == \"max\":\n            if global_pool:\n                return _op.nn.global_max_pool3d(inputs[0])\n            return _pool3d(_op.nn.max_pool3d, False)\n        if pool_type == \"avg\":\n            if global_pool:\n                return _op.nn.global_avg_pool3d(inputs[0])\n            return _pool3d(_op.nn.avg_pool3d, True)\n        raise tvm.error.OpNotImplemented(\n            \"Operator {} Pooling is not supported for frontend MXNet.\".format(\n                pool_type.capitalize()\n            )\n        )\n    # 2D Pooling\n    if pool_type == \"max\":\n        if global_pool:\n            return _op.nn.global_max_pool2d(inputs[0])\n        return _pool2d(_op.nn.max_pool2d, False)\n    if pool_type == \"avg\":\n        if global_pool:\n            return _op.nn.global_avg_pool2d(inputs[0])\n        return _pool2d(_op.nn.avg_pool2d, True)\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} Pooling is not supported for frontend MXNet.\".format(pool_type.capitalize())\n    )\n\n\ndef _mx_adaptive_avg_pooling(inputs, attrs):\n    output_size = attrs.get_int_tuple(\"output_size\", [])\n    return _op.nn.adaptive_avg_pool2d(inputs[0], output_size)\n\n\ndef _mx_dropout(inputs, attrs):\n    rate = attrs.get_float(\"p\", 0.5)\n    return _op.nn.dropout(inputs[0], rate=rate)\n\n\ndef _mx_BlockGrad(inputs, attrs):  # pylint: disable=unused-argument\n    return inputs\n\n\ndef _mx_batch_norm(inputs, attrs):\n    if attrs.get_bool(\"output_mean_var\", False):\n        raise tvm.error.OpAttributeUnImplemented(\n            'Attribute \"output_mean_var\" is not supported for operator Batch Norm.'\n        )\n    if attrs.get_bool(\"use_global_stats\", False):\n        _warn_not_used(\"use_global_stats\", \"batch_norm\")\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", 1)\n    new_attrs[\"epsilon\"] = attrs.get_float(\"eps\", 0.001)\n    new_attrs[\"center\"] = True\n    new_attrs[\"scale\"] = not attrs.get_bool(\"fix_gamma\", True)\n    return _op.nn.batch_norm(*inputs, **new_attrs)\n\n\ndef _mx_instance_norm(inputs, attrs):\n    assert len(inputs) == 3\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", 1)\n    new_attrs[\"epsilon\"] = attrs.get_float(\"eps\", 1e-5)\n    return _op.nn.instance_norm(*inputs, **new_attrs)\n\n\ndef _mx_layer_norm(inputs, attrs):\n    assert len(inputs) == 3\n    if attrs.get_bool(\"output_mean_var\", False):\n        raise tvm.error.OpAttributeUnimplemented(\n            'Attribute \"output_mean_var\" is not supported for operator Layer Norm.'\n        )\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", -1)\n    new_attrs[\"epsilon\"] = attrs.get_float(\"eps\", 1e-5)\n    return _op.nn.layer_norm(*inputs, **new_attrs)\n\n\ndef _mx_group_norm(inputs, attrs):\n    assert len(inputs) == 3\n    if attrs.get_bool(\"output_mean_var\", False):\n        raise tvm.error.OpAttributeUnimplemented(\n            'Attribute \"output_mean_var\" is not supported for operator Group Norm.'\n        )\n    new_attrs = {}\n    new_attrs[\"axis\"] = 1\n    new_attrs[\"num_groups\"] = attrs.get_int(\"num_groups\", 1)\n    new_attrs[\"epsilon\"] = attrs.get_float(\"eps\", 1e-5)\n    return _op.nn.group_norm(*inputs, **new_attrs)\n\n\ndef _mx_slice(inputs, attrs):\n    new_attrs = {}\n    begin = list(attrs.get_int_tuple(\"begin\", None))\n    end = list(attrs.get_int_tuple(\"end\", None))\n    stride = attrs.get_int_tuple(\"step\", None)\n    input_shape = _infer_type(inputs[0]).checked_type.shape\n    if begin is None:\n        raise tvm.error.OpAttributeRequired('Attribute \"begin\" not found in operator Slice.')\n    if end is None:\n        raise tvm.error.OpAttributeRequired('Attribute \"end\" not found in operator Slice.')\n    begin = (x if x is not None else 0 for x in begin)\n    for i, ed in enumerate(end):\n        if ed is None:\n            end[i] = input_shape[i]\n    new_attrs = {\"begin\": list(begin), \"end\": list(end)}\n    if stride is not None:\n        stride = (x if x is not None else 1 for x in stride)\n        new_attrs[\"strides\"] = list(stride)\n    return _op.strided_slice(inputs[0], **new_attrs)\n\n\ndef _mx_slice_like(inputs, attrs):\n    assert len(inputs) == 2\n    new_attrs = {}\n    new_attrs[\"axes\"] = attrs.get_int_tuple(\"axes\", None)\n    return _op.slice_like(*inputs, **new_attrs)\n\n\ndef _mx_slice_axis(inputs, attrs):\n    assert len(inputs) == 1\n    expr = _infer_type(inputs[0])\n    shape = expr.checked_type.shape\n    axis = attrs.get_int(\"axis\")\n    ax_beg = attrs.get_int(\"begin\")\n    ax_end = attrs.get_str(\"end\")\n    if axis < 0:\n        axis += len(shape)\n    assert 0 <= axis < len(shape)\n    if ax_end == \"None\":\n        ax_end = int(shape[axis])\n    else:\n        ax_end = int(ax_end)\n    if ax_beg < 0:\n        ax_beg += int(shape[axis])\n    if ax_end < 0:\n        ax_end += int(shape[axis])\n    assert 0 <= ax_beg < int(shape[axis])\n    assert ax_beg < ax_end <= int(shape[axis])\n    begin = []\n    end = []\n    for i, dim in enumerate(shape):\n        if i != axis:\n            begin.append(0)\n            end.append(dim)\n        else:\n            begin.append(ax_beg)\n            end.append(ax_end)\n    return _op.strided_slice(inputs[0], begin, end)\n\n\ndef _mx_crop_like(inputs, attrs):\n    if len(inputs) < 2:\n        raise tvm.error.OpAttributeUnimplemented(\n            \"Only support crop_like pattern for operator Crop.\"\n        )\n    if attrs.get_bool(\"center_crop\", False):\n        raise tvm.error.OpAttributeUnimplemented(\"Center crop is not supported in operator Crop.\")\n    if attrs.get_int_tuple(\"h_w\", (0, 0)) != (0, 0):\n        raise tvm.error.OpAttributeUnimplemented(\"Doesn't support h_w in operator Crop.\")\n    offset = attrs.get_int_tuple(\"offset\", (0, 0))\n    new_attrs = {}\n    if offset == (0, 0):\n        new_attrs[\"axes\"] = (2, 3)\n        return _op.slice_like(*inputs, **new_attrs)\n    expr = _infer_type(inputs[1])\n    like_shape = expr.checked_type.shape\n    new_attrs[\"begin\"] = [0, 0, offset[0], offset[1]]\n    new_attrs[\"end\"] = [\n        like_shape[0],\n        like_shape[1],\n        offset[0] + like_shape[2],\n        offset[1] + like_shape[3],\n    ]\n    return _op.strided_slice(inputs[0], **new_attrs)\n\n\ndef _mx_split(inputs, attrs):\n    axis = attrs.get_int(\"axis\", 1)\n    new_attrs = {}\n    new_attrs[\"indices_or_sections\"] = attrs.get_int(\"num_outputs\")\n    new_attrs[\"axis\"] = axis\n    res = _op.split(inputs[0], **new_attrs)\n    if attrs.get_bool(\"squeeze_axis\", False):\n        return tuple([_op.squeeze(x, axis=[axis]) for x in res])\n    return res\n\n\ndef _mx_softmax_activation(inputs, attrs):\n    mode = attrs.get_str(\"mode\", \"instance\")\n    axis = 0 if mode == \"instance\" else 1\n    return _op.nn.softmax(inputs[0], axis=axis)\n\n\ndef _mx_softmax_output(inputs, attrs):\n    if attrs.get_bool(\"multi_output\", False):\n        return _op.nn.softmax(inputs[0], axis=1)\n    return _op.nn.softmax(inputs[0])\n\n\ndef _mx_linear_regression_output(inputs, _):\n    return inputs[0]\n\n\ndef _mx_logistic_regression_output(inputs, _):\n    return _op.sigmoid(inputs[0])\n\n\ndef _mx_concat(inputs, attrs):\n    axis = attrs.get_int(\"dim\", 1)\n    return _op.concatenate(tuple(inputs), axis=axis)\n\n\ndef _mx_stack(inputs, attrs):\n    axis = attrs.get_int(\"axis\", 0)\n    return _op.stack(tuple(inputs), axis=axis)\n\n\ndef _mx_expand_dims(inputs, attrs):\n    axis = attrs.get_int(\"axis\")\n    return _op.expand_dims(inputs[0], axis=axis)\n\n\ndef _mx_pad(inputs, attrs):\n    pad_mode = attrs.get_str(\"mode\", None)\n    if pad_mode is None:\n        raise tvm.error.OpAttributeRequired('Attribute \"mode\" not found in operator pad.')\n    if pad_mode not in [\"constant\", \"edge\", \"reflect\"]:\n        raise tvm.error.OpAttributeInvalid(\"Value \" + mode + ' in attribute \"mode\" is not valid')\n    pad_width = attrs.get_int_tuple(\"pad_width\", None)\n    if pad_width is None:\n        raise tvm.error.OpAttributeRequired('Attribute \"pad_width\" not found in operator pad.')\n    if None in pad_width:\n        raise tvm.error.OpAttributeInvalid(\n            'Value None in attribute \"pad_width\" of operator Slice is not valid.'\n        )\n    constant_value = attrs.get_float(\"constant_value\", 0.0)\n    padding = tuple(tuple((b, a)) for b, a in zip(pad_width[::2], pad_width[1::2]))\n    return _op.nn.pad(\n        data=inputs[0], pad_width=padding, pad_value=constant_value, pad_mode=pad_mode\n    )\n\n\ndef _mx_leaky_relu(inputs, attrs):\n    act_type = attrs.get_str(\"act_type\", \"leaky\")\n    if act_type == \"leaky\":\n        return _op.nn.leaky_relu(inputs[0], alpha=attrs.get_float(\"slope\", 0.25))\n    if act_type == \"prelu\":\n        assert len(inputs) == 2\n        return _op.nn.prelu(*inputs)\n    if act_type == \"elu\":\n        # -slope * relu(1-exp(x)) + relu(x)\n        slope = attrs.get_float(\"slope\", 0.25)\n        one = _expr.const(1, dtype=\"float32\")\n        x = inputs[0]\n        mslope = _op.nn.relu(_op.subtract(one, _op.exp(x)))\n        mslope = _op.multiply(mslope, _expr.const(-slope, dtype=\"float32\"))\n        return _op.add(mslope, _op.nn.relu(x))\n    if act_type == \"rrelu\":\n        # NOTE this is only converted for inference.\n        lower_bound = attrs.get_float(\"lower_bound\")\n        upper_bound = attrs.get_float(\"upper_bound\")\n        alpha = (lower_bound + upper_bound) / 2.0\n        return _op.nn.leaky_relu(inputs[0], alpha=alpha)\n    if act_type == \"gelu\":\n        # 0.5 * x * (1 + erf(x / sqrt(2)))\n        sqrt2 = _expr.const(math.sqrt(2), dtype=\"float32\")\n        erf = _op.erf(_op.divide(inputs[0], sqrt2))\n        one = _expr.const(1, dtype=\"float32\")\n        erf_plus_one = _op.add(one, erf)\n        half = _expr.const(0.5, dtype=\"float32\")\n        half_x = _op.multiply(inputs[0], half)\n        return _op.multiply(half_x, erf_plus_one)\n    raise tvm.error.OpNotImplemented(\n        \"Operator {} is not supported for frontend MXNet.\".format(act_type)\n    )\n\n\ndef _mx_make_power(power):\n    def _impl(inputs, _):  # Note: no attrs\n        assert len(inputs) == 1\n        scalar = _expr.const(power, dtype=None)\n        # Note: int maps to \"int32\", float maps to \"float32\"\n        return _op.power(inputs[0], scalar)\n\n    return _impl\n\n\ndef _mx_make_exponent(base):\n    # exp(b, x) = e^b * e^x\n    def _impl(inputs, _):  # Note: no attrs\n        assert len(inputs) == 1\n        scalar = _op.exp(_expr.const(base, dtype=\"float32\"))\n        return _op.multiply(inputs[0], scalar)\n\n    return _impl\n\n\ndef _mx_make_logarithm(base):\n    # log(b, x) = log(x) / log(b)\n    def _impl(inputs, _):  # Note: no attrs\n        assert len(inputs) == 1\n        scalar = _op.log(_expr.const(base, dtype=\"float32\"))\n        return _op.divide(inputs[0], scalar)\n\n    return _impl\n\n\ndef _mx_expm1():\n    # exp_minus_1 x = exp(x) - 1\n    def _impl(inputs, _):  # Note: no attrs\n        assert len(inputs) == 1\n        one = _expr.const(1, dtype=\"float32\")\n        return _op.log(_op.subtract(inputs[0], one))\n\n    return _impl\n\n\ndef _mx_log1p():\n    # 1_plus_log x = log(x + 1)\n    def _impl(inputs, _):  # Note: no attrs\n        assert len(inputs) == 1\n        one = _expr.const(1, dtype=\"float32\")\n        return _op.log(_op.add(inputs[0], one))\n\n    return _impl\n\n\ndef _mx_lrn(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"alpha\"] = attrs.get_float(\"alpha\", 0.0001)\n    new_attrs[\"beta\"] = attrs.get_float(\"beta\", 0.75)\n    new_attrs[\"bias\"] = attrs.get_float(\"knorm\", 2)\n    # NCHW format and normalization along channel axis\n    new_attrs[\"axis\"] = 1\n    new_attrs[\"size\"] = attrs.get_int(\"nsize\")\n    assert len(inputs) == 1\n    return _op.nn.lrn(inputs[0], **new_attrs)\n\n\ndef _mx_multibox_prior(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"sizes\"] = attrs.get_float_tuple(\"sizes\", (1.0,))\n    new_attrs[\"steps\"] = attrs.get_float_tuple(\"steps\", (-1.0, -1.0))\n    new_attrs[\"offsets\"] = attrs.get_float_tuple(\"offsets\", (0.5, 0.5))\n    new_attrs[\"ratios\"] = attrs.get_float_tuple(\"ratios\", (1.0,))\n    new_attrs[\"clip\"] = attrs.get_bool(\"clip\", False)\n    return _op.vision.multibox_prior(inputs[0], **new_attrs)\n\n\ndef _mx_multibox_detection(inputs, attrs):\n    new_attrs0 = {}\n    new_attrs0[\"clip\"] = attrs.get_bool(\"clip\", True)\n    new_attrs0[\"threshold\"] = attrs.get_float(\"threshold\", 0.01)\n    new_attrs0[\"variances\"] = attrs.get_float_tuple(\"variances\", (0.1, 0.1, 0.2, 0.2))\n\n    new_attrs1 = {}\n    new_attrs1[\"return_indices\"] = False\n    new_attrs1[\"iou_threshold\"] = attrs.get_float(\"nms_threshold\", 0.5)\n    new_attrs1[\"force_suppress\"] = attrs.get_bool(\"force_suppress\", False)\n    new_attrs1[\"top_k\"] = attrs.get_int(\"nms_topk\", -1)\n\n    ret = _op.vision.multibox_transform_loc(inputs[0], inputs[1], inputs[2], **new_attrs0)\n    return _op.vision.non_max_suppression(ret[0], ret[1], ret[1], **new_attrs1)\n\n\ndef _mx_dot(inputs, attrs):\n    assert len(inputs) == 2\n    a, b = inputs\n    rank_a = len(_infer_type(a).checked_type.shape)\n    rank_b = len(_infer_type(b).checked_type.shape)\n    if rank_a != 2 or rank_b != 2:\n        raise tvm.error.OpAttributeUnimplemented(\"Only 2-D arrays are supported.\")\n    transpose_a = attrs.get_bool(\"transpose_a\", False)\n    transpose_b = attrs.get_bool(\"transpose_b\", False)\n    if transpose_a is True:\n        msg = 'Value {} in attribute \"transpose_a\" of operator dot ' \"is not valid.\"\n        raise tvm.error.OpAttributeInvalid(msg.format(transpose_a))\n    if transpose_b is False:\n        b = _op.transpose(b, axes=[1, 0])\n    return _op.nn.dense(a, b)\n\n\ndef _mx_batch_dot(inputs, attrs):\n    assert len(inputs) == 2\n    a, b = inputs\n    a_shape = _infer_type(a).checked_type.shape\n    batch_shapes = None\n    if len(a_shape) > 3:\n        batch_shapes = a_shape[:-2]\n        a = _op.reverse_reshape(a, newshape=(-1, 0, 0))\n    b_shape = _infer_type(b).checked_type.shape\n    if len(b_shape) > 3:\n        if batch_shapes is None:\n            batch_shapes = b_shape[:-2]\n        b = _op.reverse_reshape(b, newshape=(-1, 0, 0))\n    transpose_a = attrs.get_bool(\"transpose_a\", False)\n    transpose_b = attrs.get_bool(\"transpose_b\", False)\n    if transpose_a is True:\n        msg = 'Value {} in attribute \"transpose_a\" of operator batch_dot ' \"is not valid.\"\n        raise tvm.error.OpAttributeInvalid(msg.format(transpose_a))\n    if transpose_b is False:\n        b = _op.transpose(b, axes=[0, 2, 1])\n    out = _op.nn.batch_matmul(a, b)\n    if batch_shapes is not None:\n        out = _op.reverse_reshape(out, newshape=tuple(batch_shapes) + (0, 0))\n    return out\n\n\ndef _mx_arange(inputs, attrs):\n    assert len(inputs) == 0\n    if attrs.get_int(\"repeat\", 1) != 1:\n        raise tvm.error.OpAttributeUnimplemented(\n            'Attribute \"repeat\" is not supported in operator arange.'\n        )\n    dtype = attrs.get_str(\"dtype\", \"float32\")\n    stop = attrs.get_str(\"stop\", \"None\")\n    if stop == \"None\":\n        stop = None\n    else:\n        stop = _expr.const(float(stop), dtype=dtype)\n    new_attrs = {}\n    new_attrs[\"start\"] = _expr.const(attrs.get_float(\"start\", 0.0), dtype=dtype)\n    new_attrs[\"stop\"] = stop\n    new_attrs[\"step\"] = _expr.const(attrs.get_float(\"step\", 1.0), dtype=dtype)\n    new_attrs[\"dtype\"] = dtype\n    return _op.arange(**new_attrs)\n\n\n# pylint: disable=unused-argument\ndef _mx_make_loss(inputs, attrs):\n    # while doing inference make_loss does not have any effect\n    # and it should be mapped to identity\n    return inputs[0]\n\n\ndef _mx_contrib_arange_like(inputs, attrs):\n    assert len(inputs) == 1\n    if attrs.get_int(\"repeat\", 1) != 1:\n        raise tvm.error.OpAttributeUnimplemented(\n            'Attribute \"repeat\" is not supported in operator arange_like.'\n        )\n    ty = _infer_type(inputs[0]).checked_type\n    assert ty\n    shape, dtype = get_const_tuple(ty.shape), ty.dtype\n    axis = attrs.get_int(\"axis\", None)\n    if axis is None:\n        n_elems = 1\n        for dim in shape:\n            if not isinstance(dim, int):\n                raise tvm.error.OpError(\"Don't support arange_like with symbolic input shape.\")\n            n_elems *= dim\n    else:\n        axis = axis + len(shape) if axis < 0 else axis\n        assert 0 <= axis < len(shape)\n        n_elems = shape[axis]\n        if not isinstance(n_elems, int):\n            raise tvm.error.OpError(\"Don't support arange_like with symbolic input shape.\")\n        shape = (n_elems,)\n    start = attrs.get_float(\"start\", 0.0)\n    step = attrs.get_float(\"step\", 1.0)\n    stop = start + step * n_elems\n    new_attrs = {}\n    new_attrs[\"start\"] = _expr.const(start, dtype=dtype)\n    new_attrs[\"stop\"] = _expr.const(stop, dtype=dtype)\n    new_attrs[\"step\"] = _expr.const(step, dtype=dtype)\n    new_attrs[\"dtype\"] = dtype\n    ret = _op.arange(**new_attrs)\n    if len(shape) > 1:\n        ret = _op.reshape(ret, shape)\n    return ret\n\n\ndef _mx_repeat(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"repeats\"] = attrs.get_int(\"repeats\")\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", 0)\n    return _op.repeat(inputs[0], **new_attrs)\n\n\ndef _mx_tile(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"reps\"] = attrs.get_int_tuple(\"reps\")\n    return _op.tile(inputs[0], **new_attrs)\n\n\ndef _mx_take(inputs, attrs):\n    assert len(inputs) == 2\n    mode = attrs.get_str(\"mode\", \"clip\")\n    if mode == \"raise\":\n        raise tvm.error.OpAttributeUnimplemented(\"take with raise mode is not supported yet\")\n    axis = attrs.get_int(\"axis\", 0)\n    return _op.take(inputs[0], inputs[1].astype(\"int32\"), axis=axis, mode=mode)\n\n\ndef _mx_gather_nd(inputs, attrs):\n    assert len(inputs) == 2\n    assert len(_infer_shape(inputs[1])) > 1, \"index tensor to have at least 2 dimensions\"\n    return _op.gather_nd(inputs[0], inputs[1])\n\n\ndef _mx_reverse(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\")\n    return _op.reverse(inputs[0], **new_attrs)\n\n\ndef _mx_sequence_reverse(inputs, attrs):\n    new_attrs = {}\n    use_seq_lengths = attrs.get_bool(\"use_sequence_length\")\n    if not use_seq_lengths:\n        assert len(inputs) == 1\n        new_attrs[\"axis\"] = attrs.get_int(\"axis\")\n        return _op.reverse(inputs[0], **new_attrs)\n\n    assert len(inputs) == 2\n    new_attrs[\"seq_axis\"] = attrs.get_int(\"axis\")\n    # MXNet assumes batch_axis as 1.\n    new_attrs[\"batch_axis\"] = 1\n    return _op.reverse_sequence(inputs[0], inputs[1], **new_attrs)\n\n\ndef _mx_roi_align(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"pooled_size\"] = attrs.get_int_tuple(\"pooled_size\")\n    new_attrs[\"spatial_scale\"] = attrs.get_float(\"spatial_scale\")\n    new_attrs[\"sample_ratio\"] = attrs.get_int(\"sample_ratio\", -1)\n    new_attrs[\"layout\"] = \"NCHW\"\n    return _op.vision.roi_align(inputs[0], inputs[1], **new_attrs)\n\n\ndef _mx_resize(inputs, attrs):\n    scale_height = attrs.get_float(\"scale_height\", None)\n    scale_width = attrs.get_float(\"scale_width\", None)\n    height = attrs.get_int(\"height\", 1)\n    width = attrs.get_int(\"width\", 1)\n    expr = _infer_type(inputs[0])\n    shape = expr.checked_type.shape\n    if scale_height is not None:\n        height = (scale_height * shape[2]).astype(\"int32\")\n    if scale_width is not None:\n        width = (scale_width * shape[3]).astype(\"int32\")\n    size = (height, width)\n    return _op.image.resize2d(inputs[0], size, coordinate_transformation_mode=\"align_corners\")\n\n\ndef _mx_amp_multicast(inputs, attrs):\n    cast_narrow = attrs.get_bool(\"cast_narrow\", False)\n    dtypes = [_infer_type(x).checked_type.dtype for x in inputs]\n    supported_dtypes = [\"float16\", \"float32\"]\n    assert all(\n        [x in supported_dtypes for x in dtypes]\n    ), \"amp_multicast support is limited to float16 and float32 inputs only.\"\n    has_float16 = any(x == \"float16\" for x in dtypes)\n    has_float32 = any(x == \"float32\" for x in dtypes)\n    dtype = dtypes[0]\n    if cast_narrow and has_float16:\n        dtype = \"float16\"\n    if not cast_narrow and has_float32:\n        dtype = \"float32\"\n    return [_op.cast(x, dtype) for x in inputs]\n\n\ndef _mx_grid_generator(inputs, attrs):\n    transform_type = attrs.get_str(\"transform_type\")\n    if transform_type == \"affine\":\n        target_shape = attrs.get_int_tuple(\"target_shape\")\n        return _op.image.affine_grid(_op.reshape(inputs[0], (0, 2, 3)), target_shape)\n    if transform_type == \"warp\":\n        checked_type = _infer_type(inputs[0]).checked_type\n        batch, _, height, width = get_const_tuple(checked_type.shape)\n        dtype = checked_type.dtype\n        identity_affine = relay.const(np.array([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]], dtype=dtype))\n        identity_affine = _op.broadcast_to(identity_affine, (batch, 2, 3))\n        normalizer = (2.0 / np.array([width - 1, height - 1])).reshape(1, -1, 1, 1).astype(dtype)\n        normalized_flow = inputs[0] * relay.const(normalizer)\n        grid = _op.image.affine_grid(identity_affine, (height, width))\n        return grid + normalized_flow\n    raise ValueError(\"unknown transform type\" + transform_type)\n\n\ndef _mx_bilinear_sampler(inputs, attrs):\n    return _op.image.grid_sample(inputs[0], inputs[1], \"bilinear\", \"NCHW\")\n\n\ndef _mx_roi_pooling(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"pooled_size\"] = attrs.get_int_tuple(\"pooled_size\")\n    new_attrs[\"spatial_scale\"] = attrs.get_float(\"spatial_scale\")\n    new_attrs[\"layout\"] = \"NCHW\"\n    return _op.vision.roi_pool(inputs[0], inputs[1], **new_attrs)\n\n\ndef _mx_proposal(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"scales\"] = attrs.get_float_tuple(\"scales\", (4.0, 8.0, 16.0, 32.0))\n    new_attrs[\"ratios\"] = attrs.get_float_tuple(\"ratios\", (0.5, 1.0, 2.0))\n    new_attrs[\"feature_stride\"] = attrs.get_int(\"feature_stride\", 16)\n    new_attrs[\"threshold\"] = attrs.get_float(\"threshold\", 0.7)\n    new_attrs[\"rpn_pre_nms_top_n\"] = attrs.get_int(\"rpn_pre_nms_top_n\", 6000)\n    new_attrs[\"rpn_post_nms_top_n\"] = attrs.get_int(\"rpn_post_nms_top_n\", 300)\n    new_attrs[\"rpn_min_size\"] = attrs.get_int(\"rpn_min_size\", 16)\n    new_attrs[\"iou_loss\"] = attrs.get_bool(\"iou_loss\", False)\n    assert not attrs.get_bool(\"output_score\", False), \"proposal doesn't support output score\"\n    return _op.vision.proposal(inputs[0], inputs[1], inputs[2], **new_attrs)\n\n\ndef _mx_box_nms(inputs, attrs):\n    force_suppress = attrs.get_bool(\"force_suppress\", False)\n    iou_thresh = attrs.get_float(\"overlap_thresh\", 0.5)\n    top_k = attrs.get_int(\"topk\", -1)\n    valid_thresh = attrs.get_float(\"valid_thresh\", 0)\n    coord_start = attrs.get_int(\"coord_start\", 2)\n    score_index = attrs.get_int(\"score_index\", 1)\n    id_index = attrs.get_int(\"id_index\", -1)\n    in_format = attrs.get_str(\"in_format\", \"corner\")\n    out_format = attrs.get_str(\"out_format\", \"corner\")\n    if in_format != \"corner\":\n        raise tvm.error.OpAttributeInvalid(\n            'Value of attribute \"in_format\" must equal \"corner\" for operator box_nms.'\n        )\n    if out_format != \"corner\":\n        raise tvm.error.OpAttributeInvalid(\n            'Value of attribute \"out_format\" must equal \"corner\" for operator box_nms.'\n        )\n\n    ret = _op.vision.get_valid_counts(\n        inputs[0], score_threshold=valid_thresh, id_index=id_index, score_index=score_index\n    )\n    nms_out = _op.vision.non_max_suppression(\n        ret[1],\n        ret[0],\n        ret[2],\n        iou_threshold=iou_thresh,\n        force_suppress=force_suppress,\n        top_k=top_k,\n        coord_start=coord_start,\n        score_index=score_index,\n        id_index=id_index,\n        return_indices=False,\n        invalid_to_bottom=True,\n    )\n    return nms_out\n\n\ndef _mx_box_decode(inputs, attrs):\n    std0 = relay.const(attrs.get_float(\"std0\", 1), \"float32\")\n    std1 = relay.const(attrs.get_float(\"std1\", 1), \"float32\")\n    std2 = relay.const(attrs.get_float(\"std2\", 1), \"float32\")\n    std3 = relay.const(attrs.get_float(\"std3\", 1), \"float32\")\n    clip = attrs.get_float(\"clip\", -1)\n    in_format = attrs.get_str(\"format\", \"corner\")\n\n    anchors = inputs[1]  # (1, N, 4) encoded in corner or center\n    a = _op.split(anchors, indices_or_sections=4, axis=-1)\n    # Convert to format \"center\".\n    if in_format == \"corner\":\n        a_width = a[2] - a[0]\n        a_height = a[3] - a[1]\n        a_x = a[0] + a_width * relay.const(0.5, \"float32\")\n        a_y = a[1] + a_height * relay.const(0.5, \"float32\")\n    else:\n        a_x, a_y, a_width, a_height = a\n    data = inputs[0]  # (B, N, 4) predicted bbox offset\n    p = _op.split(data, indices_or_sections=4, axis=-1)\n    ox = p[0] * std0 * a_width + a_x\n    oy = p[1] * std1 * a_height + a_y\n    dw = p[2] * std2\n    dh = p[3] * std3\n    if clip > 0:\n        clip = relay.const(clip, \"float32\")\n        dw = _op.minimum(dw, clip)\n        dh = _op.minimum(dh, clip)\n    dw = _op.exp(dw)\n    dh = _op.exp(dh)\n    ow = dw * a_width * relay.const(0.5, \"float32\")\n    oh = dh * a_height * relay.const(0.5, \"float32\")\n    out = _op.concatenate([ox - ow, oy - oh, ox + ow, oy + oh], axis=-1)\n    return out\n\n\ndef _mx_l2_normalize(inputs, attrs):\n    new_attrs = {}\n    mode = attrs.get_str(\"mode\", \"instance\")\n    if mode == \"channel\":\n        new_attrs[\"axis\"] = [1]\n    elif mode == \"instance\":\n        ndim = len(_infer_type(inputs[0]).checked_type.shape)\n        new_attrs[\"axis\"] = list(range(1, ndim))\n    elif mode == \"spatial\":\n        ndim = len(_infer_type(inputs[0]).checked_type.shape)\n        new_attrs[\"axis\"] = list(range(2, ndim))\n    else:\n        raise tvm.error.OpAttributeInvalid(\n            'Mode \"{}\" is not supported for operator l2_normalize.'.format(mode)\n        )\n    new_attrs[\"eps\"] = attrs.get_float(\"eps\", 1e-10)\n    return _op.nn.l2_normalize(inputs[0], **new_attrs)\n\n\ndef _mx_softsign(inputs, attrs):\n    return inputs[0] / (_expr.const(1.0) + _op.abs(inputs[0]))\n\n\ndef _mx_softmin(inputs, attrs):\n    axis = attrs.get_int(\"axis\", -1)\n    return _op.nn.softmax(_op.negative(inputs[0]), axis)\n\n\ndef _mx_hard_sigmoid(inputs, attrs):\n    x = (_expr.const(0.2) * inputs[0]) + _expr.const(0.5)\n    return _op.clip(x, a_min=0.0, a_max=1.0)\n\n\ndef _mx_reciprocal(inputs, attrs):\n    return _expr.const(1.0) / inputs[0]\n\n\ndef _mx_shape_array(inputs, attrs):\n    assert len(inputs) == 1\n    if attrs.get_int(\"lhs_begin\", None) is not None:\n        raise tvm.error.OpAttributeUnimplemented(\"shape_array doesn't support lhs_begin\")\n    if attrs.get_int(\"lhs_end\", None) is not None:\n        raise tvm.error.OpAttributeUnimplemented(\"shape_array doesn't support lhs_end\")\n    if attrs.get_int(\"rhs_begin\", None) is not None:\n        raise tvm.error.OpAttributeUnimplemented(\"shape_array doesn't support rhs_begin\")\n    if attrs.get_int(\"rhs_end\", None) is not None:\n        raise tvm.error.OpAttributeUnimplemented(\"shape_array doesn't support rhs_end\")\n    return _op.shape_of(inputs[0], dtype=\"int64\")\n\n\ndef _mx_full(inputs, attrs):\n    assert len(inputs) == 0\n    val = attrs.get_float(\"value\")\n    shape = attrs.get_int_tuple(\"shape\")\n    dtype = attrs.get_str(\"dtype\", \"float32\")\n    return _op.full(_expr.const(val, dtype), shape, dtype)\n\n\ndef _mx_squeeze(inputs, attrs):\n    assert len(inputs) == 1\n    axis = attrs.get_int_tuple(\"axis\", None)\n    return _op.squeeze(inputs[0], axis)\n\n\ndef _mx_broadcast_axis(inputs, attrs):\n    assert len(inputs) == 1\n    axis = attrs.get_int_tuple(\"axis\", [])\n    size = attrs.get_int_tuple(\"size\", [])\n    assert len(axis) == len(size)\n    if len(axis) == 0:\n        return inputs[0]\n    expr = _infer_type(inputs[0])\n    src_shape = expr.checked_type.shape\n    tgt_shape = []\n    for i, dim in enumerate(src_shape):\n        if i not in axis:\n            tgt_shape.append(dim)\n        else:\n            assert int(dim) == 1\n            idx = axis.index(i)\n            tgt_shape.append(size[idx])\n    return _op.broadcast_to(inputs[0], tgt_shape)\n\n\ndef _mx_embedding(inputs, _):\n    assert len(inputs) == 2\n    indices, weight = inputs\n    return _op.take(weight, indices.astype(\"int32\"), axis=0)\n\n\ndef _mx_smooth_l1(inputs, attrs):\n    scalar = attrs.get_float(\"scalar\", 1.0)\n    scalar_sq = scalar * scalar\n    mask = _op.less(inputs[0], _expr.const(1.0 / scalar_sq, dtype=\"float32\"))\n    return _op.where(\n        mask,\n        _expr.const(scalar_sq / 2.0, dtype=\"float32\") * inputs[0] * inputs[0],\n        _op.abs(inputs[0]) - _expr.const(0.5 / scalar_sq),\n    )\n\n\ndef _mx_deformable_convolution(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"kernel_size\"] = attrs.get_int_tuple(\"kernel\")\n    new_attrs[\"strides\"] = attrs.get_int_tuple(\"stride\")\n    new_attrs[\"padding\"] = attrs.get_int_tuple(\"pad\")\n    new_attrs[\"dilation\"] = attrs.get_int_tuple(\"dilate\")\n    new_attrs[\"channels\"] = attrs.get_int(\"num_filter\")\n    new_attrs[\"deformable_groups\"] = attrs.get_int(\"num_deformable_group\", 1)\n    new_attrs[\"groups\"] = attrs.get_int(\"num_group\", 1)\n    assert attrs.get_str(\"layout\", \"NCHW\") == \"NCHW\", \"Deformable conv2d only supports NCHW layout\"\n    use_bias = not attrs.get_bool(\"no_bias\", False)\n    res = _op.nn.deformable_conv2d(inputs[0], inputs[1], inputs[2], **new_attrs)\n    if use_bias:\n        assert len(inputs) == 4\n        res = _op.nn.bias_add(res, inputs[3])\n    return res\n\n\ndef _mx_argsort(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", -1)\n    new_attrs[\"is_ascend\"] = attrs.get_bool(\"is_ascend\", True)\n    new_attrs[\"dtype\"] = attrs.get_str(\"dtype\", \"float32\")\n    return _op.argsort(inputs[0], **new_attrs)\n\n\ndef _mx_topk(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"k\"] = attrs.get_int(\"k\", 1)\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", -1)\n    new_attrs[\"is_ascend\"] = attrs.get_bool(\"is_ascend\", False)\n    ret_type = attrs.get_str(\"ret_typ\", \"indices\")\n    if ret_type == \"mask\":\n        raise tvm.error.OpAttributeUnimplemented(\n            \"Attribute ret_type=mask is not supported in topk operator\"\n        )\n    new_attrs[\"ret_type\"] = \"values\" if ret_type == \"value\" else ret_type\n    new_attrs[\"dtype\"] = attrs.get_str(\"dtype\", \"float32\")\n    return _op.topk(inputs[0], **new_attrs)\n\n\ndef _mx_sequence_mask(inputs, attrs):\n    assert len(inputs) == 1 or len(inputs) == 2\n    new_attrs = {}\n    use_sequence_length = attrs.get_bool(\"use_sequence_length\", False)\n    new_attrs[\"mask_value\"] = attrs.get_float(\"value\", 0.0)\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\", 0)\n    if use_sequence_length:\n        return _op.sequence_mask(*inputs, **new_attrs)\n    else:\n        return inputs[0]\n\n\ndef _mx_contrib_div_sqrt_dim(inputs, _):\n    assert len(inputs) == 1\n    ndim = len(_infer_type(inputs[0]).checked_type.shape)\n    dim = _op.take(_op.shape_of(inputs[0]), _expr.const(ndim - 1, dtype=\"int32\"))\n    dtype = _infer_type(inputs[0]).checked_type.dtype\n    sqrt_dim = _op.sqrt(dim.astype(dtype))\n    out = inputs[0] / sqrt_dim\n    return out\n\n\ndef _mx_rnn_param_concat(inputs, _):\n    # We don't need to concatenate RNN params because we will unravel the RNN op\n    return [inputs]\n\n\ndef _mx_rnn_layer(inputs, attrs):\n    def _rnn_cell(data, states, i2h_weight, h2h_weight, i2h_bias, h2h_bias, activation):\n        i2h = _op.nn.bias_add(_op.nn.dense(data, i2h_weight), i2h_bias, axis=-1)\n        h2h = _op.nn.bias_add(_op.nn.dense(states[0], h2h_weight), h2h_bias, axis=-1)\n        out = _activation_map[activation](i2h + h2h)\n        return out, [out]\n\n    def _gru_cell(data, states, i2h_weight, h2h_weight, i2h_bias, h2h_bias):\n        expr = _infer_type(data)\n        dtype = expr.checked_type.dtype\n        i2h = _op.nn.bias_add(_op.nn.dense(data, i2h_weight), i2h_bias, axis=-1)\n        h2h = _op.nn.bias_add(_op.nn.dense(states[0], h2h_weight), h2h_bias, axis=-1)\n        i2h_r, i2h_z, i2h = _op.split(i2h, indices_or_sections=3, axis=1)\n        h2h_r, h2h_z, h2h = _op.split(h2h, indices_or_sections=3, axis=1)\n        reset_gate = _activation_map[\"sigmoid\"](i2h_r + h2h_r)\n        update_gate = _activation_map[\"sigmoid\"](i2h_z + h2h_z)\n        next_h_tmp = _activation_map[\"tanh\"](reset_gate * h2h + i2h)\n        next_h = (_expr.const(1, dtype) - update_gate) * next_h_tmp + update_gate * states[0]\n        return next_h, [next_h]\n\n    def _lstm_cell(data, states, i2h_weight, h2h_weight, i2h_bias, h2h_bias):\n        i2h = _op.nn.bias_add(_op.nn.dense(data, i2h_weight), i2h_bias, axis=-1)\n        h2h = _op.nn.bias_add(_op.nn.dense(states[0], h2h_weight), h2h_bias, axis=-1)\n        gates = i2h + h2h\n        slice_gates = _op.split(gates, indices_or_sections=4, axis=1)\n        in_gate = _activation_map[\"sigmoid\"](slice_gates[0])\n        forget_gate = _activation_map[\"sigmoid\"](slice_gates[1])\n        in_transform = _activation_map[\"tanh\"](slice_gates[2])\n        out_gate = _activation_map[\"sigmoid\"](slice_gates[3])\n        next_c = forget_gate * states[1] + in_gate * in_transform\n        next_h = out_gate * _activation_map[\"tanh\"](next_c)\n        return next_h, [next_h, next_c]\n\n    num_layers = attrs.get_int(\"num_layers\", 1)\n    mode = attrs.get_str(\"mode\")\n    output_states = attrs.get_bool(\"state_outputs\", False)\n    if mode.startswith(\"rnn\"):\n        mode, activation = mode.split(\"_\")\n    assert mode in [\"rnn\", \"gru\", \"lstm\"]\n    bidirectional = attrs.get_bool(\"bidirectional\", False)\n    direct = 2 if bidirectional else 1\n    layout = attrs.get_str(\"layout\", \"TNC\")\n    if layout != \"TNC\":\n        raise tvm.error.OpAttributeUnimplemented(\n            \"RNN with layout other than TNC is not supported yet\"\n        )\n    num_states = 2 if mode == \"lstm\" else 1\n    assert len(inputs) == num_states + 2\n\n    seq_data = inputs[0]\n    concat_weight = inputs[1]\n    init_states = inputs[2:]\n    expr = _infer_type(seq_data)\n    data_shape = expr.checked_type.shape\n    seq_len = int(data_shape[0])\n    assert len(concat_weight) == num_layers * 4 * direct\n\n    for idx, state in enumerate(init_states[:]):\n        if isinstance(state, dict):\n            node = state\n            attrs = StrAttrsDict(node.get(\"attrs\", {}))\n            op_name = node[\"op\"]\n            # by default, RNN layer uses zeros to initialize states\n            assert op_name == \"_zeros\"\n            shape = attrs.get_int_tuple(\"shape\")\n            dtype = attrs.get_str(\"dtype\", \"float32\")\n            init_layout = attrs.get_str(\"__layout__\")\n            new_shape = list(shape)\n            for i, dim in enumerate(shape):\n                if dim == 0:\n                    axis = layout.find(init_layout[i])\n                    assert axis >= 0\n                    new_shape[i] = int(data_shape[axis])\n            init_states[idx] = _op.zeros(new_shape, dtype)\n\n    weights = []\n    bias = []\n    states = []\n    back_weights = []\n    back_bias = []\n    back_states = []\n    for i in range(num_layers):\n        weights.append(\n            [concat_weight[i * 2 * direct].args[0], concat_weight[i * 2 * direct + 1].args[0]]\n        )\n        bias.append(\n            [\n                concat_weight[(num_layers + i) * 2 * direct].args[0],\n                concat_weight[(num_layers + i) * 2 * direct + 1].args[0],\n            ]\n        )\n        s = []\n        for state in init_states:\n            s.append(_op.take(state, _expr.const(i * direct, \"int32\"), axis=0))\n        states.append(s)\n        if bidirectional:\n            back_weights.append(\n                [\n                    concat_weight[i * 2 * direct + 2].args[0],\n                    concat_weight[i * 2 * direct + 3].args[0],\n                ]\n            )\n            back_bias.append(\n                [\n                    concat_weight[(num_layers + i) * 2 * direct + 2].args[0],\n                    concat_weight[(num_layers + i) * 2 * direct + 3].args[0],\n                ]\n            )\n            s = []\n            for state in init_states:\n                s.append(_op.take(state, _expr.const(i * direct + 1, \"int32\"), axis=0))\n            back_states.append(s)\n\n    xs = [_op.take(seq_data, _expr.const(t, \"int32\"), axis=0) for t in range(seq_len)]\n    for l in range(num_layers):\n        outputs = []\n        back_outputs = []\n        for x in xs:\n            if mode == \"rnn\":\n                out, new_states = _rnn_cell(x, states[l], *weights[l], *bias[l], activation)\n            elif mode == \"gru\":\n                out, new_states = _gru_cell(x, states[l], *weights[l], *bias[l])\n            else:  # mode == \"lstm\"\n                out, new_states = _lstm_cell(x, states[l], *weights[l], *bias[l])\n            states[l] = new_states\n            outputs.append(out)\n        if bidirectional:\n            for x in reversed(xs):\n                if mode == \"rnn\":\n                    out, new_states = _rnn_cell(\n                        x, back_states[l], *back_weights[l], *back_bias[l], activation\n                    )\n                elif mode == \"gru\":\n                    out, new_states = _gru_cell(x, back_states[l], *back_weights[l], *back_bias[l])\n                else:  # mode == \"lstm\"\n                    out, new_states = _lstm_cell(x, back_states[l], *back_weights[l], *back_bias[l])\n                back_states[l] = new_states\n                back_outputs.append(out)\n            back_outputs.reverse()\n            concat_outputs = []\n            for t, out in enumerate(outputs):\n                new_out = _op.concatenate([out, back_outputs[t]], axis=-1)\n                concat_outputs.append(new_out)\n            outputs = concat_outputs\n        xs = outputs\n\n    ret = [_op.stack(outputs, axis=0)]\n    if output_states:\n        for i in range(num_states):\n            inputs = []\n            for l, s in enumerate(states):\n                inputs.append(s[i])\n                if bidirectional:\n                    inputs.append(back_states[l][i])\n            ret.append(_op.stack(inputs, axis=0))\n    return ret\n\n\ndef _mx_one_hot(inputs, attrs):\n    indices = inputs[0].astype(\"int32\")\n    depth = attrs.get_int(\"depth\", 0)\n    dtype = attrs.get_str(\"dtype\", \"int32\")\n    on_value = tvm.relay.const(attrs.get_float(\"on_value\", 1.0), dtype)\n    off_value = tvm.relay.const(attrs.get_float(\"off_value\", 0.0), dtype)\n    return _op.one_hot(indices, on_value, off_value, depth, -1, dtype)\n\n\ndef _mx_depth_to_space(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"block_size\"] = attrs.get_int(\"block_size\")\n    return _op.nn.depth_to_space(*inputs, **new_attrs)\n\n\ndef _mx_space_to_depth(inputs, attrs):\n    assert len(inputs) == 1\n    new_attrs = {}\n    new_attrs[\"block_size\"] = attrs.get_int(\"block_size\")\n    return _op.nn.space_to_depth(*inputs, **new_attrs)\n\n\ndef _mx_correlation(inputs, attrs):\n    assert len(inputs) == 2\n    new_attrs = {}\n    new_attrs[\"kernel_size\"] = attrs.get_int(\"kernel_size\", 1)\n    new_attrs[\"max_displacement\"] = attrs.get_int(\"max_displacement\", 1)\n    new_attrs[\"stride1\"] = attrs.get_int(\"stride1\", 1)\n    new_attrs[\"stride2\"] = attrs.get_int(\"stride2\", 1)\n    new_attrs[\"padding\"] = attrs.get_int(\"pad_size\", 0)\n    new_attrs[\"is_multiply\"] = attrs.get_bool(\"is_multiply\", True)\n    new_attrs[\"layout\"] = \"NCHW\"\n    return _op.nn.correlation(*inputs, **new_attrs)\n\n\ndef _mx_contrib_fifo_buffer(inputs, attrs):\n    new_attrs = {}\n    new_attrs[\"axis\"] = attrs.get_int(\"axis\")\n    return _op.nn.fifo_buffer(*inputs, **new_attrs)\n\n\ndef _mx_contrib_interleaved_matmul_selfatt_qk(inputs, attrs):\n    \"\"\"\n    tmp = mx.nd.reshape(queries_keys_values, shape=(0, 0, num_heads, 3, -1))\n    q_proj = mx.nd.transpose(tmp[:,:,:,0,:], axes=(1, 2, 0, 3))\n    q_proj = mx.nd.reshape(q_proj, shape=(-1, 0, 0), reverse=True)\n    q_proj = mx.nd.contrib.div_sqrt_dim(q_proj)\n    k_proj = mx.nd.transpose(tmp[:,:,:,1,:], axes=(1, 2, 0, 3))\n    k_proj = mx.nd.reshape(k_proj, shape=(-1, 0, 0), reverse=True)\n    output = mx.nd.batch_dot(q_proj, k_proj, transpose_b=True)\n    \"\"\"\n    assert len(inputs) == 1\n    qkv = inputs[0]\n    num_heads = attrs.get_int(\"heads\")\n    qkv = _op.reshape(qkv, newshape=(0, 0, num_heads, 3, -1))\n    q_proj = _op.take(qkv, _expr.const(0, \"int32\"), axis=3)\n    q_proj = _op.transpose(q_proj, axes=[1, 2, 0, 3])\n    q_proj = _op.reverse_reshape(q_proj, newshape=(-1, 0, 0))\n    q_proj = _mx_contrib_div_sqrt_dim([q_proj], None)\n    k_proj = _op.take(qkv, _expr.const(1, \"int32\"), axis=3)\n    k_proj = _op.transpose(k_proj, axes=[1, 2, 0, 3])\n    k_proj = _op.reverse_reshape(k_proj, newshape=(-1, 0, 0))\n    ret = _op.nn.batch_matmul(q_proj, k_proj)\n    return ret\n\n\ndef _mx_contrib_interleaved_matmul_selfatt_valatt(inputs, attrs):\n    \"\"\"\n    tmp = mx.nd.reshape(queries_keys_values, shape=(0, 0, num_heads, 3, -1))\n    v_proj = mx.nd.transpose(tmp[:,:,:,2,:], axes=(1, 2, 0, 3))\n    v_proj = mx.nd.reshape(v_proj, shape=(-1, 0, 0), reverse=True)\n    output = mx.nd.batch_dot(attention, v_proj)\n    output = mx.nd.reshape(output, shape=(-1, num_heads, 0, 0), reverse=True)\n    output = mx.nd.transpose(output, axes=(2, 0, 1, 3))\n    output = mx.nd.reshape(output, shape=(0, 0, -1))\n    \"\"\"\n    assert len(inputs) == 2\n    qkv, att = inputs\n    num_heads = attrs.get_int(\"heads\")\n    qkv = _op.reshape(qkv, newshape=(0, 0, num_heads, 3, -1))\n    v_proj = _op.take(qkv, _expr.const(2, \"int32\"), axis=3)\n    v_proj = _op.transpose(v_proj, axes=(1, 2, 0, 3))\n    v_proj = _op.reverse_reshape(v_proj, newshape=(-1, 0, 0))\n    v_proj = _op.transpose(v_proj, axes=[0, 2, 1])\n    out = _op.nn.batch_matmul(att, v_proj)\n    out = _op.reverse_reshape(out, newshape=(-1, num_heads, 0, 0))\n    out = _op.transpose(out, axes=(2, 0, 1, 3))\n    out = _op.reshape(out, newshape=(0, 0, -1))\n    return out\n\n\ndef _mx_cond(inputs, attrs, subgraphs):\n    assert len(subgraphs) == 3\n    cond_input_locs = json.loads(attrs.get_str(\"cond_input_locs\"))\n    then_input_locs = json.loads(attrs.get_str(\"then_input_locs\"))\n    else_input_locs = json.loads(attrs.get_str(\"else_input_locs\"))\n    num_outputs = attrs.get_int(\"num_outputs\")\n\n    input_args = []\n    for i, arg in enumerate(inputs):\n        var = _expr.var(\"arg%s\" % i, _infer_type(arg).checked_type)\n        input_args.append(var)\n    cond_args = [input_args[i] for i in cond_input_locs]\n    then_args = [input_args[i] for i in then_input_locs]\n    else_args = [input_args[i] for i in else_input_locs]\n\n    cond_arg_shapes = [arg.type_annotation.shape for arg in cond_args]\n    cond_arg_dtype_info = [arg.type_annotation.dtype for arg in cond_args]\n    cond_func = _from_mxnet_impl(subgraphs[0], cond_arg_shapes, cond_arg_dtype_info)\n    cond = _expr.Call(cond_func, cond_args).astype(\"bool\")\n    cond_shape = get_const_tuple(_infer_type(cond).checked_type.shape)\n    if len(cond_shape) > 0:\n        assert len(cond_shape) == 1 and cond_shape[0] == 1, \"Condition is not scalar\"\n        cond = _op.take(cond, _expr.const(1, \"int\"))\n\n    sb = _scope_builder.ScopeBuilder()\n    with sb.if_scope(cond):\n        then_arg_shapes = [arg.type_annotation.shape for arg in then_args]\n        then_arg_dtype_info = [arg.type_annotation.dtype for arg in then_args]\n        then_func = _from_mxnet_impl(subgraphs[1], then_arg_shapes, then_arg_dtype_info)\n        sb.ret(_expr.Call(then_func, then_args))\n    with sb.else_scope():\n        else_arg_shapes = [arg.type_annotation.shape for arg in else_args]\n        else_arg_dtype_info = [arg.type_annotation.dtype for arg in else_args]\n        else_func = _from_mxnet_impl(subgraphs[2], else_arg_shapes, else_arg_dtype_info)\n        sb.ret(_expr.Call(else_func, else_args))\n    func = _function.Function(input_args, sb.get())\n    ret = _expr.Call(func, inputs)\n    if num_outputs > 1:\n        ret = _expr.TupleWrapper(ret, num_outputs)\n    return ret\n\n\ndef _qnn_contrib_concat(inputs, attrs):\n    axis = attrs.get_int(\"dim\", 1)\n    num_args = attrs.get_int(\"num_args\", -1)\n    assert num_args > 0\n\n    input_exprs = inputs[0:num_args]\n\n    min_start_idx = num_args\n    max_start_idx = num_args + 1\n\n    mins = list()\n    maxs = list()\n\n    for i in range(min_start_idx, len(inputs), 2):\n        mins.append(inputs[i])\n\n    for i in range(max_start_idx, len(inputs), 2):\n        maxs.append(inputs[i])\n\n    # Check if all the input tensors have same qnn params.\n    if len(set(mins)) == 1 and len(set(maxs)) == 1:\n        output_min = mins[0]\n        output_max = maxs[0]\n        concat = _op.concatenate(tuple(input_exprs), axis=axis)\n        return concat, output_min, output_max\n    else:\n        # Get all dtypes. Find input and output scales, call concatenate.\n        dtypes = [_infer_type(x).checked_type.dtype for x in input_exprs]\n        assert all(\n            [x == \"uint8\" for x in dtypes]\n        ), \"Current support is limited to uint8 inputs only.\"\n        new_min = min(mins)\n        new_max = max(maxs)\n        assert new_min == 0\n\n        output_scale = get_mkldnn_uint8_scale(new_min, new_max)\n        min_max = zip(mins, maxs)\n        input_scales = [get_mkldnn_uint8_scale(x, y) for (x, y) in min_max]\n        input_zeros = [0] * len(input_scales)\n        output_zero = 0\n\n        input_scales_expr = [relay.const(x, \"float32\") for x in input_scales]\n        input_zeros_expr = [relay.const(x, \"int32\") for x in input_zeros]\n\n        output_scale_expr = relay.const(output_scale, \"float32\")\n        output_zero_expr = relay.const(output_zero, \"int32\")\n\n        res = relay.qnn.op.concatenate(\n            input_exprs,\n            input_scales_expr,\n            input_zeros_expr,\n            output_scale_expr,\n            output_zero_expr,\n            axis=axis,\n        )\n        return res, new_min, new_max\n\n\ndef _qnn_quantize(inputs, attrs):\n    out_dtype = \"int8\"\n    out_type = attrs.get_str(\"out_type\")\n    if out_type == \"auto\":\n        if attrs.has_attr(\"min_calib_range\") and attrs.has_attr(\"max_calib_range\"):\n            if attrs.get_float(\"min_calib_range\") >= 0:\n                out_dtype = \"uint8\"\n            else:\n                out_dtype = \"int8\"\n    else:\n        out_dtype = out_type\n    if out_dtype not in {\"int8\", \"uint8\"}:\n        raise ValueError(\"Unsupported out_dtype: %s\" % out_dtype)\n    min_calib_range = attrs.get_float(\"min_calib_range\", 0.0)\n    max_calib_range = attrs.get_float(\"max_calib_range\", 0.0)\n    quantized_output, _, _ = quantize_mxnet_min_max(\n        inputs[0], min_range=min_calib_range, max_range=max_calib_range, out_dtype=out_dtype\n    )\n    return quantized_output, min_calib_range, max_calib_range\n\n\ndef _qnn_contrib_quantized_fifo_buffer(inputs, attrs, params):\n    data = inputs[0]\n    buffer = inputs[1]\n    min_calib_range = inputs[2]\n    max_calib_range = inputs[3]\n    data_dtype = _infer_type(data).checked_type.dtype\n    buffer_shape = _infer_shape(buffer)\n    buffer_name = _get_name(buffer)\n    params[buffer_name] = _nd.array(np.zeros(buffer_shape).astype(data_dtype))\n    new_buffer = relay.var(buffer_name, relay.TensorType(buffer_shape, data_dtype))\n    inputs[1] = new_buffer\n    res = _op.nn.fifo_buffer(data=data, buffer=new_buffer, axis=attrs.get_int(\"axis\"))\n    return res, min_calib_range, max_calib_range\n\n\ndef _get_subgraph_op(subgraphs, op_name):\n    assert len(subgraphs) == 1, \"Subgraph should have 1 node but has {}\".format(len(subgraphs))\n    subgraph = subgraphs[0]\n    nodes = subgraph[\"nodes\"]\n    assert nodes is not None\n    for node in nodes:\n        if node[\"op\"] == op_name:\n            return node\n    raise ValueError(\"Op {} was not found in the subgraph\".format(op_name))\n\n\ndef _qnn_conv(inputs, attrs, subgraphs, params):\n    def _has_fused_activation(_attrs, _supported_activations):\n        has_fused_activation = False\n        if attrs.get_bool(\"with_act\", False) or attrs.get_bool(\"with_postsum_act\", False):\n            subgraph_activation_attrs = _get_subgraph_op(subgraphs, \"Activation\")[\"attrs\"]\n            act_type = subgraph_activation_attrs[\"act_type\"]\n            if act_type not in _supported_activations:\n                raise ValueError(\n                    \"Fused activation {} is not supported at \" \"this time\".format(act_type)\n                )\n            has_fused_activation = True\n        return has_fused_activation\n\n    def _get_data_scale_and_zp(_data, _inputs, _data_min_idx, _data_max_idx):\n        \"\"\"Finds the Qnn params for the data expr.\"\"\"\n        data_min = _inputs[_data_min_idx]\n        data_max = _inputs[_data_max_idx]\n        assert data_min <= data_max\n        data_dtype = _infer_type(_data).checked_type.dtype\n        assert data_dtype in {\"int8\", \"uint8\"}\n        if data_min < 0.0:\n            assert (\n                data_dtype == \"int8\"\n            ), \"Expect int8 when data_min < 0.0, consider quantize model with int8.\"\n        _data_scale = (\n            get_mkldnn_uint8_scale(data_min, data_max)\n            if data_dtype == \"uint8\"\n            else get_mkldnn_int8_scale(data_min, data_max)\n        )\n        _data_zero_point = 0\n        return _data_scale, _data_zero_point\n\n    def _get_bn_alpha_coeff(_bn_gamma_idx, _bn_beta_idx, _bn_running_mean_idx, _bn_running_var_idx):\n        \"\"\"Extract the BN coeff. These will be use later for BN folding into convolution.\"\"\"\n        # Extract relevant attrs from bn.\n        bn_attrs = _get_subgraph_op(subgraphs, \"BatchNorm\")[\"attrs\"]\n        bn_epsilon_param = float(bn_attrs[\"eps\"])\n        bn_scale_param = bn_attrs[\"fix_gamma\"] == \"False\"\n        bn_center_param = True\n\n        # Extract the relevant relay expressions.\n        bn_running_var = inputs[_bn_running_var_idx]\n        bn_gamma = inputs[_bn_gamma_idx]\n        bn_beta = inputs[_bn_beta_idx]\n        bn_running_mean = inputs[_bn_running_mean_idx]\n\n        # Get coefficient to multiply to weights.\n        bn_epsilon = relay.const(bn_epsilon_param, \"float32\")\n        denominator = relay.sqrt(relay.add(bn_running_var, bn_epsilon))\n        _bn_scale = relay.divide(relay.const(1.0, \"float32\"), denominator)\n        if bn_scale_param:\n            _bn_scale = relay.multiply(bn_gamma, _bn_scale)\n\n        # Get the shift.\n        _bn_shift = relay.negative(relay.multiply(bn_running_mean, _bn_scale))\n        if bn_center_param:\n            _bn_shift = relay.add(bn_beta, _bn_shift)\n\n        return _bn_scale, _bn_shift\n\n    def _fold_bn(_bn_scale, _bn_shift, _has_bias, _has_bn):\n        \"\"\"Fold BN into kernel and bias. Get new kernel and bias.\"\"\"\n        _kernel = inputs[1]\n        if _bn_scale:\n            assert attrs.get_bool(\"with_bn\", False)\n            # Weights are on OIHW, and _bn_scale is in O.\n            exp_bn_scale = relay.expand_dims(_bn_scale, axis=1, num_newaxis=3)\n            _kernel = relay.multiply(exp_bn_scale, _kernel)\n\n        _bias = None\n        if _has_bias:\n            _bias = inputs[2]\n            if _has_bn:\n                assert _bn_shift is not None\n                assert _bn_scale is not None\n                _bias = relay.add(relay.multiply(_bn_scale, _bias), _bn_shift)\n        elif _has_bn:\n            assert _bn_shift is not None\n            assert _bn_scale is not None\n            _bias = _bn_shift\n        return _kernel, _bias\n\n    def _get_quantized_kernel(_kernel, _bias, _data_scale):\n        # For quantizing, we need min/max of kernel. So, we have to pre compute this expr.\n        np_kernel = _infer_value(_kernel, params).numpy()\n        kernel_channel_min = np.amin(np_kernel, axis=(1, 2, 3))\n        kernel_channel_max = np.amax(np_kernel, axis=(1, 2, 3))\n\n        np_bias = None\n        if _bias is not None:\n            np_bias = _infer_value(_bias, params).numpy()\n        return quantize_conv_weights_bias_channel_mkldnn_from_var(\n            _kernel, np_bias, kernel_channel_min, kernel_channel_max, _data_scale\n        )\n\n    def _get_qnn_conv2d(\n        _data,\n        _kernel,\n        _data_zero_point,\n        _kernel_zero_point,\n        _data_scale,\n        _kernel_vector_scale,\n        _conv2d_attrs,\n    ):\n        return relay.qnn.op.conv2d(\n            _data,\n            _kernel,\n            input_zero_point=relay.const(_data_zero_point, \"int32\"),\n            kernel_zero_point=relay.const(_kernel_zero_point, \"int32\"),\n            input_scale=relay.const(_data_scale, \"float32\"),\n            kernel_scale=relay.const(_kernel_vector_scale),\n            channels=_conv2d_attrs[\"channels\"],\n            groups=_conv2d_attrs[\"groups\"],\n            kernel_size=_conv2d_attrs[\"kernel_size\"],\n            strides=_conv2d_attrs[\"strides\"],\n            dilation=_conv2d_attrs[\"dilation\"],\n            padding=_conv2d_attrs[\"padding\"],\n            data_layout=_conv2d_attrs[\"data_layout\"],\n            kernel_layout=_conv2d_attrs[\"kernel_layout\"],\n        )\n\n    def _get_requantized_op(_res, _input_scale, _output_scale, _out_dtype):\n        # Requantize to get the output back\n        return relay.qnn.op.requantize(\n            _res,\n            input_scale=relay.const(_input_scale),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(_output_scale, \"float32\"),\n            output_zero_point=relay.const(0, \"int32\"),\n            axis=1,\n            out_dtype=_out_dtype,\n        )\n\n    def _get_sum(_res, _output_scale, out_dtype):\n        \"\"\"Handles sum of the second quantized tensor.\"\"\"\n        # This is done in following steps\n        #   1) rhs is the add's second operand. First rhs will be requantized to output scale with\n        #   dtype int32. The int32 dtype is to keep precision high before adding.\n        #   2) Call normal add\n        #   3) Depending on final out_dtype, clip and cast (basically requantize).\n\n        _output_scale = relay.const(_output_scale, \"float32\")\n        data_sum = inputs[-5]\n        data_sum_min = inputs[-2]\n        data_sum_max = inputs[-1]\n\n        data_sum_dtype = _infer_type(data_sum).checked_type.dtype\n        data_sum_scale = (\n            get_mkldnn_uint8_scale(data_sum_min, data_sum_max)\n            if data_sum_dtype == \"uint8\"\n            else get_mkldnn_int8_scale(data_sum_min, data_sum_max)\n        )\n        data_sum_scale = relay.const(data_sum_scale, \"float32\")\n        zero_point = relay.const(0, \"int32\")\n\n        # Save one requantize if the previous expr already has a requantize node. This also improves\n        # little bit with accuracy.\n        if isinstance(data_sum, _expr.Call) and data_sum.op.name == \"qnn.requantize\":\n            prev_input, prev_scale, prev_zero_point = data_sum.args[0:3]\n            prev_axis = data_sum.attrs.axis\n            data_sum = relay.qnn.op.requantize(\n                prev_input,\n                input_scale=prev_scale,\n                input_zero_point=prev_zero_point,\n                output_scale=_output_scale,\n                output_zero_point=zero_point,\n                axis=prev_axis,\n                out_dtype=\"int32\",\n            )\n        else:\n            data_sum = relay.qnn.op.requantize(\n                data_sum,\n                input_scale=data_sum_scale,\n                input_zero_point=zero_point,\n                output_scale=_output_scale,\n                output_zero_point=zero_point,\n                out_dtype=\"int32\",\n            )\n\n        # 2) Add two int32 tensors.\n        _res = relay.add(_res, data_sum)\n\n        # 3) Clip/cast to change the out dtype.\n        _res = relay.clip(\n            _res,\n            a_min=float(tvm.tir.op.min_value(out_dtype).value),\n            a_max=float(tvm.tir.op.max_value(out_dtype).value),\n        )\n        _res = relay.cast(_res, out_dtype)\n        return _res\n\n    def _parse():\n        assert len(subgraphs) == 1\n        subgraph_conv_attrs = StrAttrsDict(_get_subgraph_op(subgraphs, \"Convolution\")[\"attrs\"])\n\n        is_quantized = attrs.get_bool(\"quantized\", False)\n        if is_quantized:\n            # The MKLDNN has a quantized convolution subgraph. There are many different arguments\n            # that are taken into account to parse the subgraph.\n            #   * no_bias\n            #   * with_sum\n            #   * with_bn\n            #   * with_postsum_relu\n            #   * with_act\n            #\n            # Note - Relu/clip handling is not required because output min/max take care of that.\n            #\n            # The parsing can be broken down into following steps\n            #   1) Get the input data scale and zero points.\n            #   2) Extract BN params.\n            #   3) Fold the BN params into kernel and bias.\n            #   4) Quantize the kernel.\n            #   4) Call QNN conv2d op.\n            #   5) Quantize bias and call bias_add.\n            #   6) Handle sum of quantized tensors if needed. Or just Requantize.\n\n            has_bias = not subgraph_conv_attrs.get_bool(\"no_bias\", False)\n            has_sum = attrs.get_bool(\"with_sum\", False)\n            has_bn = attrs.get_bool(\"with_bn\", False)\n\n            ###############################################\n            #   1) Get the input data scale and zero point.\n            ###############################################\n            # Last 2 indexes are data min and max. If the conv has a sum, then last 2 indexes are\n            # for the second tensor. So, the data min max indexes are last 3 and 4\n            data_min_idx = -2\n            data_max_idx = -1\n            if has_sum:\n                data_min_idx = -4\n                data_max_idx = -3\n\n            data = inputs[0]\n            data_scale, data_zero_point = _get_data_scale_and_zp(\n                data, inputs, data_min_idx, data_max_idx\n            )\n\n            #############################\n            #   2) Extract the BN params.\n            #############################\n            # Find the indexes to look at for BN.\n            bn_scale = bn_shift = None\n            if has_bn:\n                if has_bias:\n                    bn_start_idx = 3\n                else:\n                    bn_start_idx = 2\n\n                bn_gamma_idx = bn_start_idx\n                bn_beta_idx = bn_start_idx + 1\n                bn_running_mean_idx = bn_start_idx + 2\n                bn_running_var_idx = bn_start_idx + 3\n\n                bn_scale, bn_shift = _get_bn_alpha_coeff(\n                    bn_gamma_idx, bn_beta_idx, bn_running_mean_idx, bn_running_var_idx\n                )\n\n            ########################################\n            #   3) Fold the BN into kernel and bias.\n            ########################################\n            kernel, bias = _fold_bn(bn_scale, bn_shift, has_bias, has_bn)\n\n            #######################################################################\n            #   4) Fold BN params into kernel. Get quantized kernel and QNN params.\n            #######################################################################\n            kernel, kernel_vector_scale, kernel_zero_point = _get_quantized_kernel(\n                kernel, bias, data_scale\n            )\n\n            ##########################\n            #   5) Call QNN conv2d op.\n            ##########################\n            conv2d_attrs = _get_mx_conv2d_attrs(subgraph_conv_attrs)\n            res = _get_qnn_conv2d(\n                data,\n                kernel,\n                data_zero_point,\n                kernel_zero_point,\n                data_scale,\n                kernel_vector_scale,\n                conv2d_attrs,\n            )\n\n            ###############################################\n            #   6) Fold BN params into bias. Call bias_add.\n            ###############################################\n            if has_bias or has_bn:\n                bias_scale = data_scale * kernel_vector_scale\n                int32_bias = quantize_conv_bias_mkldnn_from_var(bias, bias_scale)\n                res = _op.nn.bias_add(res, int32_bias, axis=1)\n\n            #####################################################################\n            #   7) Handle sum of quantized tensors if needed. Or just Requantize.\n            #####################################################################\n            min_output_range = attrs.get_float(\"min_calib_range\")\n            max_output_range = attrs.get_float(\"max_calib_range\")\n            output_scale, out_dtype = get_conv_mkldnn_requantized_scale_outDtype(\n                min_output_range, max_output_range\n            )\n\n            # QNN conv2d output scale is product of data_scale and kernel_vector_scale\n            input_scale = data_scale * kernel_vector_scale\n            if attrs.get_bool(\"with_sum\", False):\n                # There is a second tensor that has to be added to the QNN conv2d output. Therefore,\n                # the QNN conv2d is first requantized to output scale with int32 precision. The\n                # second tensor will also be requantized to output scale with int32 precision,\n                # followed by an add operator.\n                res = _get_requantized_op(res, input_scale, output_scale, \"int32\")\n                res = _get_sum(res, output_scale, out_dtype)\n            else:\n                # Get the requantized conv output\n                res = _get_requantized_op(res, input_scale, output_scale, out_dtype)\n\n            return res, min_output_range, max_output_range\n        else:\n            res = _mx_conv(inputs, subgraph_conv_attrs)\n            has_fused_relu = _has_fused_activation(attrs, [\"relu\"])\n            if has_fused_relu:\n                res = _op.nn.relu(res)\n            return res\n\n    return _parse()\n\n\ndef _qnn_flatten(inputs, attrs):\n    # pylint: disable=unused-argument\n    data = inputs[0]\n    output_min = inputs[1]\n    output_max = inputs[2]\n    output = _op.nn.batch_flatten(data)\n    return output, output_min, output_max\n\n\ndef _qnn_dequantize(inputs, attrs):\n    # pylint: disable=unused-argument\n    data = inputs[0]\n    input_min = inputs[1]\n    input_max = inputs[2]\n    in_dtype = _infer_type(data).checked_type.dtype\n    result = dequantize_mxnet_min_max(data, input_min, input_max, in_dtype)\n    return result\n\n\ndef _qnn_activation(inputs, attrs):\n    act_type = attrs.get_str(\"act_type\")\n    assert len(inputs) == 3\n    assert act_type == \"relu\", \"Currently only relu is supported\"\n    data = inputs[0]\n    range_min = inputs[1]\n    range_max = inputs[2]\n    res = _op.nn.relu(data)\n    return res, range_min, range_max\n\n\ndef _qnn_pooling(inputs, attrs):\n    input_min = inputs[1]\n    input_max = inputs[2]\n    data = inputs[0]\n    data_dtype = _infer_type(data).checked_type.dtype\n    pool_type = attrs.get_str(\"pool_type\")\n    if data_dtype in (\"int8\", \"uint8\") and pool_type != \"max\":\n        data = _op.cast(data, \"int32\")\n    res = _mx_pooling([data, input_min, input_max], attrs)\n    if data_dtype in (\"int8\", \"uint8\") and pool_type != \"max\":\n        res = _op.cast(res, data_dtype)\n    return res, input_min, input_max\n\n\ndef _qnn_batch_norm(inputs, attrs):\n    # Perform batch norm in FP32\n    data = inputs[0]\n\n    # Dequantize the data.\n    data_min_idx, data_max_idx = (-2, -1)\n    data_min, data_max = inputs[data_min_idx], inputs[data_max_idx]\n    data_dtype = _infer_type(data).checked_type.dtype\n    data_scale = (\n        get_mkldnn_uint8_scale(data_min, data_max)\n        if data_dtype == \"uint8\"\n        else get_mkldnn_int8_scale(data_min, data_max)\n    )\n    data_zp = 0\n    data = relay.qnn.op.dequantize(\n        data, relay.const(data_scale, \"float32\"), relay.const(data_zp, \"int32\")\n    )\n\n    # Run BN. The last 4 inputs are same as before.\n    new_inputs = [data, *inputs[1:5]]\n    res = _mx_batch_norm(new_inputs, attrs)\n\n    # Quantize the result\n    min_output_range = attrs.get_float(\"min_calib_range\")\n    max_output_range = attrs.get_float(\"max_calib_range\")\n    output_scale, out_dtype = get_conv_mkldnn_requantized_scale_outDtype(\n        min_output_range, max_output_range\n    )\n    res = relay.qnn.op.quantize(\n        res[0], relay.const(output_scale, \"float32\"), relay.const(0, \"int32\"), out_dtype=out_dtype\n    )\n    return res, min_output_range, max_output_range\n\n\ndef _qnn_fully_connected(inputs, attrs, subgraphs, params):\n    def _get_input_scale_zp(_data_dtype, _inputs, _has_bias):\n        data_min_idx, data_max_idx = (3, 4) if _has_bias else (2, 3)\n        data_min, data_max = _inputs[data_min_idx], _inputs[data_max_idx]\n        _data_scale = (\n            get_mkldnn_uint8_scale(data_min, data_max)\n            if _data_dtype == \"uint8\"\n            else get_mkldnn_int8_scale(data_min, data_max)\n        )\n        _data_zp = 0\n        return _data_scale, _data_zp\n\n    def _get_kernel_scale_zp_tensor_quantized(_kernel, _inputs, _has_bias):\n        kernel_dtype = _infer_type(_kernel).checked_type.dtype\n\n        if kernel_dtype != \"int8\":\n            raise tvm.error.OpNotImplemented(\n                \"Tensor wise quantized expects weights in int8 data type\"\n            )\n\n        if isinstance(_kernel, tvm.relay.Call) and _kernel.op.name == \"qnn.quantize\":\n            _kernel_scale = _kernel.args[1].data.numpy()\n            _kernel_zp = _kernel.args[2].data.numpy()\n            return _kernel_scale, _kernel_zp\n\n        kernel_min_idx, kernel_max_idx = (5, 6) if _has_bias else (4, 5)\n        kernel_min_name = _get_name(_inputs[kernel_min_idx])\n        kernel_min = params[kernel_min_name].numpy()[0]\n        kernel_max_name = _get_name(_inputs[kernel_max_idx])\n        kernel_max = params[kernel_max_name].numpy()[0]\n        _kernel_scale = (\n            get_mkldnn_uint8_scale(kernel_min, kernel_max)\n            if kernel_dtype == \"uint8\"\n            else get_mkldnn_int8_scale(kernel_min, kernel_max)\n        )\n        _kernel_zp = 0\n        return _kernel_scale, _kernel_zp\n\n    def _get_kernel_scale_zp_channel_quantized(_kernel, _bias, _data_scale):\n        kernel_dtype = _infer_type(_kernel).checked_type.dtype\n        if kernel_dtype != \"float32\":\n            raise tvm.error.OpNotImplemented(\n                \"Channel wise quantized expects weights in float32 data type\"\n            )\n\n        # Get the FP32 values, calculate min/max and then channel quantize them\n        np_kernel = _infer_value(_kernel, params).numpy()\n        kernel_channel_min = np.amin(np_kernel, axis=(1,))\n        kernel_channel_max = np.amax(np_kernel, axis=(1,))\n\n        np_bias = None\n        if _bias is not None:\n            np_bias = _infer_value(_bias, params).numpy()\n        return quantize_conv_weights_bias_channel_mkldnn_from_var(\n            _kernel, np_bias, kernel_channel_min, kernel_channel_max, _data_scale\n        )\n\n    def _get_bias_requantize_scale(_inputs, _data_scale, _kernel_scale):\n        _bias = _inputs[2]\n        if isinstance(_bias, tvm.relay.Call) and _bias.op.name == \"qnn.quantize\":\n            _bias_scale = _bias.args[1].data.numpy()\n            _bias_requantize_scale = _bias_scale / (_data_scale * _kernel_scale)\n            _bias_requantize_scale = _expr.const(_bias_requantize_scale, dtype=\"float32\")\n            return _bias_requantize_scale\n\n        bias_min_name = _get_name(_inputs[7])\n        bias_min = params[bias_min_name].numpy()[0]\n        bias_max_name = _get_name(_inputs[8])\n        bias_max = params[bias_max_name].numpy()[0]\n        bias_scale = get_mkldnn_int8_scale(bias_min, bias_max)\n        _bias_requantize_scale = bias_scale / (_data_scale * _kernel_scale)\n        _bias_requantize_scale = _expr.const(_bias_requantize_scale, dtype=\"float32\")\n        return _bias_requantize_scale\n\n    is_quantized = attrs.get_bool(\"quantized\", False)\n    with_relu = attrs.get_bool(\"with_relu\", False)\n    subgraph_dense_attrs = StrAttrsDict(_get_subgraph_op(subgraphs, \"FullyConnected\")[\"attrs\"])\n    if not is_quantized:\n        res = _mx_fully_connected(inputs, subgraph_dense_attrs)\n        if with_relu:\n            res = _op.nn.relu(res)\n        return res\n    else:\n        has_bias = not subgraph_dense_attrs.get_bool(\"no_bias\", False)\n        units = subgraph_dense_attrs.get_int(\"num_hidden\")\n        is_flatten = subgraph_dense_attrs.get_bool(\"flatten\", True)\n        enable_float_output = attrs.get_bool(\"enable_float_output\", False)\n        is_channel_quantized = attrs.get_bool(\"channel_wise_quantize\", False)\n\n        ########################\n        # Get data, kernel, bias\n        ########################\n        data, kernel = inputs[0], inputs[1]\n        bias = None\n        if has_bias:\n            bias = inputs[2]\n\n        ##############################\n        # Handle for shape of data > 2\n        ##############################\n        if is_flatten:\n            data = _op.nn.batch_flatten(data)\n        data_shape = _infer_type(data).checked_type.shape\n        if len(data_shape) > 2:\n            data = _op.reverse_reshape(data, [-1, 0])\n\n        ###############################\n        # Get data scale and zero point\n        ###############################\n        data_dtype = _infer_type(data).checked_type.dtype\n        data_scale, data_zp = _get_input_scale_zp(data_dtype, inputs, has_bias)\n\n        #################################\n        # Get weight scale and zero point\n        #################################\n        if is_channel_quantized:\n            kernel, kernel_scale, kernel_zp = _get_kernel_scale_zp_channel_quantized(\n                kernel, bias, data_scale\n            )\n        else:\n            kernel_scale, kernel_zp = _get_kernel_scale_zp_tensor_quantized(\n                kernel, inputs, has_bias\n            )\n\n        ################\n        # Call QNN dense\n        ################\n        res = relay.qnn.op.dense(\n            data,\n            kernel,\n            input_zero_point=relay.const(data_zp, \"int32\"),\n            kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n            input_scale=relay.const(data_scale, \"float32\"),\n            kernel_scale=relay.const(kernel_scale, \"float32\"),\n            units=units,\n        )\n\n        #################\n        # Handle bias add\n        #################\n        if has_bias:\n            if is_channel_quantized:\n                bias_scale = data_scale * kernel_scale\n                int32_bias = quantize_conv_bias_mkldnn_from_var(bias, bias_scale)\n                res = _op.nn.bias_add(res, int32_bias, axis=-1)\n            else:\n                bias_data = inputs[2]\n                bias_requantize_scale = _get_bias_requantize_scale(inputs, data_scale, kernel_scale)\n                multiplied_bias = _op.multiply(\n                    _op.cast(bias_data, \"float32\"), bias_requantize_scale\n                )\n                rounded_bias = _op.round(multiplied_bias)\n                clipped_bias = _op.clip(\n                    rounded_bias,\n                    a_min=tvm.tir.op.min_value(\"int32\").value,\n                    a_max=tvm.tir.op.max_value(\"int32\").value,\n                )\n                requantized_bias = _op.cast(clipped_bias, \"int32\")\n                res = _op.nn.bias_add(res, requantized_bias, axis=-1)\n\n        ##############################################\n        # Dequantize if float32 output else Requantize\n        ##############################################\n        if enable_float_output:\n            output_scale = np.float32(data_scale * kernel_scale)\n            res = relay.qnn.op.dequantize(\n                res, relay.const(output_scale), input_zero_point=relay.const(0, \"int32\"), axis=1\n            )\n            if with_relu:\n                res = _op.nn.relu(res)\n        else:\n\n            if is_channel_quantized:\n                raise tvm.error.OpNotImplemented(\n                    \"Channel wise quantized dense with non float output is not supported yet\"\n                )\n            out_dtype = \"uint8\" if attrs.get_bool(\"with_relu\", False) else \"int8\"\n            input_scale = np.float32(data_scale * kernel_scale)\n            min_output_range = attrs.get_float(\"min_calib_range\")\n            max_output_range = attrs.get_float(\"max_calib_range\")\n            output_scale = get_mkldnn_requantize_scale_outDtype(\n                min_output_range, max_output_range, out_dtype\n            )\n            res = relay.qnn.op.requantize(\n                res,\n                input_scale=relay.const(input_scale, \"float32\"),\n                input_zero_point=relay.const(0, \"int32\"),\n                output_scale=relay.const(output_scale, \"float32\"),\n                output_zero_point=relay.const(0, \"int32\"),\n                out_dtype=out_dtype,\n            )\n            if with_relu:\n                res = _op.nn.relu(res)\n\n        ##############################\n        # Handle for shape of data > 2\n        ##############################\n        if len(data_shape) > 2:\n            new_shape = data_shape[:-1]\n            new_shape.append(units)\n            res = _op.reshape(res, new_shape)\n\n        if enable_float_output:\n            return res\n        return res, min_output_range, max_output_range\n\n\ndef _mx_broadcast_to(inputs, attrs):\n    data = inputs[0]\n    tgt_shape = attrs.get_int_tuple(\"shape\", [])\n\n    return _op.broadcast_to(data, tgt_shape)\n\n\ndef _mx_broadcast_like(inputs, attrs):\n    assert len(inputs) == 2\n    for axes in [\"lhs_axes\", \"rhs_axes\"]:\n        if axes in attrs.attrs:\n            raise tvm.error.OpAttributeUnImplemented(\n                'Attribute \"{}\" is not supported for operator broadcast_like.'.format(axes)\n            )\n    return _op.broadcast_to_like(*inputs)\n\n\ndef _mx_logical_not(inputs, input_types):\n    data = inputs[0]\n    dtype = _infer_type(data).checked_type.dtype\n    data = _op.cast(data, \"bool\") if dtype != \"bool\" else data\n\n    return _op.cast(_op.logical_not(data), dtype)\n\n\ndef _mx_broadcast_logical(logical_op):\n    def impl(inputs, input_types):\n        lhs_type = _infer_type(inputs[0]).checked_type.dtype\n        rhs_type = _infer_type(inputs[1]).checked_type.dtype\n        lhs = _op.cast(inputs[0], \"bool\") if lhs_type != \"bool\" else inputs[0]\n        rhs = _op.cast(inputs[1], \"bool\") if rhs_type != \"bool\" else inputs[1]\n\n        return _op.cast(logical_op(lhs, rhs), lhs_type)\n\n    return impl\n\n\ndef _mx_npi_transpose(inputs, attrs):\n    axes = attrs.get_int_tuple(\"axes\", None)\n    # translate default case\n    axes = None if len(axes) == 0 or axes[0] is None else axes\n    return _op.transpose(inputs[0], axes=axes)\n\n\ndef _mx_npi_pad(inputs, attrs):\n    pad_mode = attrs.get_str(\"mode\", None)\n    if pad_mode is None:\n        raise tvm.error.OpAttributeRequired('Attribute \"mode\" not found in operator pad.')\n    if pad_mode not in [\"constant\", \"edge\", \"reflect\"]:\n        raise tvm.error.OpAttributeInvalid(\"Value \" + mode + ' in attribute \"mode\" is not valid')\n    if \"pad_width\" not in attrs.attrs:\n        raise tvm.error.OpAttributeRequired('Attribute \"pad_width\" not found in operator pad.')\n    # Begin to parse tuple of tuple, we cannot use get_int_tuple here because it's a tuple of tuple.\n    pad_width = attrs.attrs[\"pad_width\"]\n    pad_width = pad_width.replace(\"(\", \"[\")\n    pad_width = pad_width.replace(\")\", \"]\")\n    pad_width = json.loads(pad_width)\n    constant_values = attrs.get_float(\"constant_values\", 0.0)\n    return _op.nn.pad(\n        data=inputs[0], pad_width=pad_width, pad_value=constant_values, pad_mode=pad_mode\n    )\n\n\ndef _mx_npi_concatenate(inputs, attrs):\n    axis = attrs.get_str(\"axis\", \"0\")\n    if axis == \"None\":\n        return _op.reshape(_op.concatenate(tuple(inputs), axis=0), (-1,))\n    else:\n        return _op.concatenate(tuple(inputs), axis=int(axis))\n\n\ndef _mx_npi_stack(inputs, attrs):\n    axis = attrs.get_str(\"axis\", \"0\")\n    if axis == \"None\":\n        return _op.reshape(_op.stack(tuple(inputs), axis=0), (-1,))\n    else:\n        return _op.stack(tuple(inputs), axis=int(axis))\n\n\ndef _mx_npx_reshape(inputs, attrs):\n    shape = attrs.get_int_tuple(\"newshape\")\n    reverse = attrs.get_bool(\"reverse\", False)\n    shape_list = list(shape)\n    old_shape = get_const_tuple(_infer_type(inputs[0]).checked_type.shape)\n    new_shape = []\n    if reverse:\n        old_shape = old_shape[::-1]\n        shape_list = shape_list[::-1]\n    ptr = 0\n    unknown_axis = None\n    src_ptr = 0\n    while src_ptr < len(shape_list):\n        ele = shape_list[src_ptr]\n        src_ptr += 1\n        if ele > 0:\n            new_shape.append(ele)\n            ptr += 1\n        elif ele == -1:\n            new_shape.append(-1)\n            if unknown_axis is not None:\n                raise tvm.error.OpAttributeInvalid(\"Can only have one -1 in the input shape.\")\n            unknown_axis = len(new_shape)\n            ptr += 1\n        elif ele == -2:\n            new_shape.append(old_shape[ptr])\n            ptr += 1\n        elif ele == -3:\n            if old_shape[ptr] != 1:\n                raise tvm.error.OpAttributeInvalid(\n                    \"Dimension of the original shape \"\n                    \"that corresponds to -3 must be 1. Received\"\n                    \" {}\".format(old_shape[ptr])\n                )\n            ptr += 1\n        elif ele == -4:\n            new_shape += old_shape[ptr:]\n            break\n        elif ele == -5:\n            new_shape.append(old_shape[ptr] * old_shape[ptr + 1])\n            ptr += 2\n        elif ele == -6:\n            # Split axis\n            lhs = shape_list[src_ptr]\n            rhs = shape_list[src_ptr + 1]\n            src_ptr += 2\n            if lhs == -1 and rhs == -1:\n                raise tvm.error.OpAttributeInvalid(\"The lhs and rhs can not both be -1.\")\n            if lhs == -1:\n                if old_shape[ptr] % rhs != 0:\n                    raise tvm.error.OpAttributeInvalid(\n                        \"When splitting the axis, \"\n                        \"the dimension of the split axis must \"\n                        \"be divisible by the splitted values.\"\n                    )\n                lhs = old_shape[ptr] // rhs\n            if rhs == -1:\n                if old_shape[ptr] % lhs != 0:\n                    raise tvm.error.OpAttributeInvalid(\n                        \"When splitting the axis, \"\n                        \"the dimension of the split axis must \"\n                        \"be divisible by the splitted values.\"\n                    )\n                rhs = old_shape[ptr] // lhs\n            new_shape.append(lhs)\n            new_shape.append(rhs)\n            ptr += 1\n        else:\n            raise tvm.error.OpAttributeInvalid(\"Shape dimension %d is not supported\" % ele)\n    if reverse:\n        new_shape = new_shape[::-1]\n    return _op.reshape(inputs[0], newshape=new_shape)\n\n\ndef _mx_split_v2(inputs, attrs):\n    axis = attrs.get_int(\"axis\")\n    indices = list(attrs.get_int_tuple(\"indices\", []))\n    # remove the prefix '0'\n    if len(indices) != 0 and indices[0] == 0:\n        indices.remove(0)\n    sections = attrs.get_int(\"sections\", 0)\n    indices_or_sections = list(indices) if len(indices) != 0 else sections\n    res = _op.split(inputs[0], indices_or_sections=indices_or_sections, axis=axis)\n    if attrs.get_bool(\"squeeze_axis\", False):\n        res = tuple([_op.squeeze(x, axis=[axis]) for x in res])\n    return res\n\n\ndef _mx_npi_where_rscalar(inputs, attrs):\n    cond, dat = inputs\n    scalar = attrs.get_float(\"scalar\")\n    cond_shape = get_const_tuple(_infer_type(cond).checked_type.shape)\n    dat_shape = get_const_tuple(_infer_type(dat).checked_type.shape)\n    dtype = _infer_type(dat).checked_type.dtype\n    # Check for broadcasting\n    out_shape = np.broadcast(np.empty(cond_shape), np.empty(dat_shape)).shape\n    if out_shape != cond_shape:\n        cond = _op.broadcast_to(cond, out_shape)\n    if out_shape != dat_shape:\n        dat = _op.broadcast_to(dat, out_shape)\n    scalar = _expr.const(scalar, dtype=dtype)\n    ones = _op.ones_like(dat)\n    scalar = _op.multiply(ones, scalar)\n    return _op.where(cond, dat, scalar)\n\n\n# Note: due to attribute conversion constraint\n# ops in the identity set must be attribute free\n_identity_list = [\n    \"abs\",\n    \"log\",\n    \"exp\",\n    \"erf\",\n    \"sqrt\",\n    \"floor\",\n    \"ceil\",\n    \"round\",\n    \"trunc\",\n    \"sign\",\n    \"sigmoid\",\n    \"negative\",\n    \"reshape_like\",\n    \"zeros_like\",\n    \"ones_like\",\n    \"cos\",\n    \"cosh\",\n    \"sin\",\n    \"sinh\",\n    \"tan\",\n    \"tanh\",\n    \"where\",\n]\n\n_convert_map = {\n    \"_copy\": _rename(_op.copy),\n    \"relu\": _rename(_op.nn.relu),\n    \"broadcast_add\": _rename(_op.add),\n    \"broadcast_plus\": _rename(_op.add),\n    \"broadcast_sub\": _rename(_op.subtract),\n    \"broadcast_minus\": _rename(_op.subtract),\n    \"broadcast_mul\": _rename(_op.multiply),\n    \"broadcast_div\": _rename(_op.divide),\n    \"broadcast_mod\": _rename(_op.mod),\n    \"broadcast_maximum\": _rename(_op.maximum),\n    \"broadcast_minimum\": _rename(_op.minimum),\n    \"broadcast_power\": _rename(_op.power),\n    \"arccos\": _rename(_op.acos),\n    \"arcsin\": _rename(_op.asin),\n    \"arctan\": _rename(_op.atan),\n    \"arccosh\": _rename(_op.acosh),\n    \"arcsinh\": _rename(_op.asinh),\n    \"arctanh\": _rename(_op.atanh),\n    \"broadcast_equal\": _mx_compare(_op.equal, _rename),\n    \"broadcast_not_equal\": _mx_compare(_op.not_equal, _rename),\n    \"broadcast_greater\": _mx_compare(_op.greater, _rename),\n    \"broadcast_greater_equal\": _mx_compare(_op.greater_equal, _rename),\n    \"broadcast_lesser\": _mx_compare(_op.less, _rename),\n    \"broadcast_lesser_equal\": _mx_compare(_op.less_equal, _rename),\n    \"broadcast_logical_or\": _mx_broadcast_logical(_op.logical_or),\n    \"broadcast_logical_and\": _mx_broadcast_logical(_op.logical_and),\n    \"broadcast_logical_xor\": _mx_broadcast_logical(_op.logical_xor),\n    \"broadcast_to\": _mx_broadcast_to,\n    \"broadcast_like\": _mx_broadcast_like,\n    \"logical_not\": _mx_logical_not,\n    \"_equal\": _mx_compare(_op.equal, _rename),\n    \"_not_equal\": _mx_compare(_op.not_equal, _rename),\n    \"_greater\": _mx_compare(_op.greater, _rename),\n    \"_greater_equal\": _mx_compare(_op.greater_equal, _rename),\n    \"_lesser\": _mx_compare(_op.less, _rename),\n    \"_lesser_equal\": _mx_compare(_op.less_equal, _rename),\n    \"elemwise_add\": _rename(_op.add),\n    \"elemwise_sub\": _rename(_op.subtract),\n    \"elemwise_mul\": _rename(_op.multiply),\n    \"elemwise_div\": _rename(_op.divide),\n    \"_maximum\": _rename(_op.maximum),\n    \"_minimum\": _rename(_op.minimum),\n    \"flatten\": _rename(_op.nn.batch_flatten),\n    \"Flatten\": _rename(_op.nn.batch_flatten),\n    # scalar power\n    \"square\": _mx_make_power(2),\n    \"rsqrt\": _mx_make_power(-1 / 2),\n    \"cbrt\": _mx_make_power(1 / 3),\n    \"rcbrt\": _mx_make_power(-1 / 3),\n    \"__pow_scalar__\": _binop_scalar(_op.power),\n    \"_power_scalar\": _binop_scalar(_op.power),\n    \"__rsub_scalar__\": _rbinop_scalar(_op.subtract),\n    \"_rminus_scalar\": _rbinop_scalar(_op.subtract),\n    \"__rdiv_scalar__\": _rbinop_scalar(_op.divide),\n    \"_rdiv_scalar\": _rbinop_scalar(_op.divide),\n    \"__rpow_scalar__\": _rbinop_scalar(_op.power),\n    # scalar op\n    \"__add_scalar__\": _binop_scalar(_op.add),\n    \"_plus_scalar\": _binop_scalar(_op.add),\n    \"__sub_scalar__\": _binop_scalar(_op.subtract),\n    \"_minus_scalar\": _binop_scalar(_op.subtract),\n    \"__mul_scalar__\": _binop_scalar(_op.multiply),\n    \"_mul_scalar\": _binop_scalar(_op.multiply),\n    \"__div_scalar__\": _binop_scalar(_op.divide),\n    \"_div_scalar\": _binop_scalar(_op.divide),\n    \"log2\": _mx_make_logarithm(2),\n    \"log10\": _mx_make_logarithm(10),\n    \"log1p\": _mx_log1p,\n    \"expm1\": _mx_expm1,\n    \"_equal_scalar\": _mx_compare(_op.equal, _binop_scalar),\n    \"_not_equal_scalar\": _mx_compare(_op.not_equal, _binop_scalar),\n    \"_greater_scalar\": _mx_compare(_op.greater, _binop_scalar),\n    \"_greater_equal_scalar\": _mx_compare(_op.greater_equal, _binop_scalar),\n    \"_lesser_scalar\": _mx_compare(_op.less, _binop_scalar),\n    \"_lesser_equal_scalar\": _mx_compare(_op.less_equal, _binop_scalar),\n    \"_maximum_scalar\": _binop_scalar(_op.maximum),\n    \"_minimum_scalar\": _binop_scalar(_op.minimum),\n    # reduction ops\n    \"mean\": _reduce(_op.mean),\n    \"max\": _reduce(_op.max),\n    \"min\": _reduce(_op.min),\n    \"sum\": _reduce(_op.sum),\n    \"max_axis\": _reduce(_op.max),\n    \"min_axis\": _reduce(_op.min),\n    \"sum_axis\": _reduce(_op.sum),\n    \"argmax\": _arg_reduce(_op.argmax),\n    \"argmin\": _arg_reduce(_op.argmin),\n    # init ops\n    \"_ones\": _init_op(_op.ones),\n    # softmax\n    \"softmax\": _softmax_op(_op.nn.softmax),\n    \"log_softmax\": _softmax_op(_op.nn.log_softmax),\n    \"Softmax\": _softmax_op(_op.nn.softmax),\n    \"softsign\": _mx_softsign,\n    \"softmin\": _mx_softmin,\n    \"hard_sigmoid\": _mx_hard_sigmoid,\n    \"reciprocal\": _mx_reciprocal,\n    # per op specialization\n    \"Reshape\": _reshape,\n    \"reshape\": _reshape,\n    \"Cast\": _cast,\n    \"amp_cast\": _cast,\n    \"amp_multicast\": _mx_amp_multicast,\n    \"clip\": _clip,\n    \"transpose\": _transpose,\n    \"UpSampling\": _upsampling,\n    \"add_n\": _elemwise_sum,\n    # MXNet specific implementations\n    \"_zeros\": _mx_zeros,\n    \"FullyConnected\": _mx_fully_connected,\n    \"Activation\": _mx_activations,\n    \"Convolution\": _mx_conv,\n    \"Convolution_v1\": _mx_conv2d,\n    \"Deconvolution\": _mx_conv_transpose,\n    \"Pooling\": _mx_pooling,\n    \"Pooling_v1\": _mx_pooling,\n    \"Dropout\": _mx_dropout,\n    \"BatchNorm\": _mx_batch_norm,\n    \"BatchNorm_v1\": _mx_batch_norm,\n    \"_contrib_SyncBatchNorm\": _mx_batch_norm,\n    \"InstanceNorm\": _mx_instance_norm,\n    \"LayerNorm\": _mx_layer_norm,\n    \"GroupNorm\": _mx_group_norm,\n    \"LRN\": _mx_lrn,\n    \"L2Normalization\": _mx_l2_normalize,\n    \"slice\": _mx_slice,\n    \"slice_like\": _mx_slice_like,\n    \"slice_axis\": _mx_slice_axis,\n    \"SliceChannel\": _mx_split,\n    \"split\": _mx_split,\n    \"_split_v2\": _mx_split_v2,\n    \"SwapAxis\": _mx_swap_axis,\n    \"expand_dims\": _mx_expand_dims,\n    \"Concat\": _mx_concat,\n    \"concat\": _mx_concat,\n    \"stack\": _mx_stack,\n    \"dot\": _mx_dot,\n    \"batch_dot\": _mx_batch_dot,\n    \"LeakyReLU\": _mx_leaky_relu,\n    \"_arange\": _mx_arange,\n    \"_full\": _mx_full,\n    \"repeat\": _mx_repeat,\n    \"tile\": _mx_tile,\n    \"pad\": _mx_pad,\n    \"Pad\": _mx_pad,\n    \"take\": _mx_take,\n    \"gather_nd\": _mx_gather_nd,\n    \"reverse\": _mx_reverse,\n    \"SequenceReverse\": _mx_sequence_reverse,\n    \"squeeze\": _mx_squeeze,\n    \"broadcast_axis\": _mx_broadcast_axis,\n    \"broadcast_axes\": _mx_broadcast_axis,\n    \"BlockGrad\": _mx_BlockGrad,\n    \"shape_array\": _mx_shape_array,\n    \"Embedding\": _mx_embedding,\n    \"argsort\": _mx_argsort,\n    \"topk\": _mx_topk,\n    \"_unravel_index\": _mx_unravel_index,\n    \"SequenceMask\": _mx_sequence_mask,\n    \"SoftmaxOutput\": _mx_softmax_output,\n    \"SoftmaxActivation\": _mx_softmax_activation,\n    \"LinearRegressionOutput\": _mx_linear_regression_output,\n    \"LogisticRegressionOutput\": _mx_logistic_regression_output,\n    \"smooth_l1\": _mx_smooth_l1,\n    \"make_loss\": _mx_make_loss,\n    \"_contrib_div_sqrt_dim\": _mx_contrib_div_sqrt_dim,\n    \"_contrib_arange_like\": _mx_contrib_arange_like,\n    \"one_hot\": _mx_one_hot,\n    \"depth_to_space\": _mx_depth_to_space,\n    \"space_to_depth\": _mx_space_to_depth,\n    \"Correlation\": _mx_correlation,\n    # vision\n    \"_contrib_BilinearResize2D\": _mx_resize,\n    \"_contrib_MultiBoxPrior\": _mx_multibox_prior,\n    \"_contrib_MultiBoxDetection\": _mx_multibox_detection,\n    \"_contrib_ROIAlign\": _mx_roi_align,\n    \"ROIPooling\": _mx_roi_pooling,\n    \"_contrib_Proposal\": _mx_proposal,\n    \"_contrib_MultiProposal\": _mx_proposal,\n    \"_contrib_box_nms\": _mx_box_nms,\n    \"_contrib_box_decode\": _mx_box_decode,\n    \"_contrib_DeformableConvolution\": _mx_deformable_convolution,\n    \"_contrib_AdaptiveAvgPooling2D\": _mx_adaptive_avg_pooling,\n    \"GridGenerator\": _mx_grid_generator,\n    \"BilinearSampler\": _mx_bilinear_sampler,\n    # NLP\n    \"RNN\": _mx_rnn_layer,\n    \"_rnn_param_concat\": _mx_rnn_param_concat,\n    \"_contrib_interleaved_matmul_selfatt_qk\": _mx_contrib_interleaved_matmul_selfatt_qk,\n    \"_contrib_interleaved_matmul_selfatt_valatt\": _mx_contrib_interleaved_matmul_selfatt_valatt,\n    # control flow\n    \"_cond\": _mx_cond,\n    # Depricated:\n    \"Crop\": _mx_crop_like,\n    # List of missing operators that are present in NNVMv1\n    # TODO(tvm-tvm): support all operators.\n    #\n    # \"contrib_fifo_buffer\": _mx_contrib_fifo_buffer,\n    \"ring_buffer\": _mx_contrib_fifo_buffer,\n    # Qnn ops\n    \"_contrib_quantize_v2\": _qnn_quantize,\n    \"_contrib_quantized_concat\": _qnn_contrib_concat,\n    # \"_contrib_quantized_fifo_buffer\": _qnn_contrib_quantized_fifo_buffer,\n    \"_contrib_quantized_ring_buffer\": _qnn_contrib_quantized_fifo_buffer,\n    \"_sg_mkldnn_conv\": _qnn_conv,\n    \"_contrib_quantized_flatten\": _qnn_flatten,\n    \"_contrib_dequantize\": _qnn_dequantize,\n    \"_contrib_quantized_act\": _qnn_activation,\n    \"_contrib_quantized_pooling\": _qnn_pooling,\n    \"_contrib_quantized_batch_norm\": _qnn_batch_norm,\n    \"_sg_mkldnn_fully_connected\": _qnn_fully_connected,\n    # numpy\n    \"_np_transpose\": _mx_npi_transpose,\n    \"_npi_transpose\": _mx_npi_transpose,\n    \"_npi_pad\": _mx_npi_pad,\n    \"_npi_concatenate\": _mx_npi_concatenate,\n    \"_npx_reshape\": _mx_npx_reshape,\n    \"_np_copy\": _rename(_op.copy),\n    \"_npi_copy\": _rename(_op.copy),\n    \"_npi_power\": _rename(_op.power),\n    \"_npi_power_scalar\": _binop_scalar(_op.power),\n    \"_npi_multiply\": _rename(_op.multiply),\n    \"_npi_multiply_scalar\": _binop_scalar(_op.multiply),\n    \"_npi_add\": _rename(_op.add),\n    \"_npi_add_scalar\": _binop_scalar(_op.add),\n    \"_npi_subtract\": _rename(_op.subtract),\n    \"_npi_subtract_scalar\": _binop_scalar(_op.subtract),\n    \"_npi_where_rscalar\": _mx_npi_where_rscalar,\n    \"_npi_less\": _rename(_op.less),\n    \"_npi_less_equal\": _mx_compare(_op.less_equal, _rename),\n    \"_npi_tanh\": _rename(_op.tanh),\n    \"_npi_true_divide_scalar\": _binop_scalar(_op.divide),\n    \"_npi_stack\": _mx_npi_stack,\n}\n\n# set identity list\n_convert_map.update({k: _rename(k) for k in _identity_list})\n\n_control_flow_ops = [\"_cond\", \"_foreach\", \"_while_loop\"]\n_qnn_subgraph_ops = [\"_sg_mkldnn_conv\", \"_sg_mkldnn_fully_connected\"]\n_subgraph_ops = _control_flow_ops + _qnn_subgraph_ops\n_params_ops = [\"_contrib_quantized_ring_buffer\"]\n\n\ndef _get_op_params(children, attrs, op_name, node, params):\n    op_params = [children, attrs]\n    if op_name in _subgraph_ops:\n        subgraphs = node[\"subgraphs\"]\n        op_params.append(subgraphs)\n        if op_name in _qnn_subgraph_ops:\n            op_params.append(params)\n    if op_name in _params_ops:\n        op_params.append(params)\n    return op_params\n\n\ndef _from_mxnet_impl(symbol, shape_dict, dtype_info, params=None, mod=None):\n    # pylint: disable=unused-argument\n    \"\"\"Convert mxnet symbol to compatible relay Function.\n\n    Reconstruct a relay Function by traversing the mxnet symbol.\n\n    Parameters\n    ----------\n    symbol : mxnet.sym.Symbol\n        Incompatible symbol from mxnet.\n        The op_name and attrs inside are not always compatible.\n\n    shape_dict : dict\n        Known parameter shapes\n\n    dtype_info : dict or str.\n        Known parameter dtypes\n\n    mod : tvm.IRModule\n        The module that contains global information. It will be used for\n        converting ops that need global information, e.g. control-flow ops.\n\n    Returns:\n    -------\n    func : tvm.relay.Function\n        Converted relay Function\n    \"\"\"\n    assert symbol is not None\n    if isinstance(symbol, dict):\n        jgraph = symbol\n    else:\n        jgraph = json.loads(symbol.tojson())\n    jnodes = jgraph[\"nodes\"]\n    node_map = {}\n    shape_idx = 0\n\n    # Check if there have any unsupported ops\n    unsupported = {}\n    for node in jnodes:\n        op_name = node[\"op\"]\n        if op_name != \"null\" and op_name not in _convert_map:\n            if op_name not in unsupported:\n                unsupported[op_name] = 0\n            unsupported[op_name] += 1\n\n    if unsupported:\n        msg = \"\\n\".join([\"{}: {}\".format(op_name, cnt) for op_name, cnt in unsupported.items()])\n        raise tvm.error.OpNotImplemented(\n            \"One or more operators are not supported in frontend MXNet:\\n{}\".format(msg)\n        )\n\n    for nid, node in enumerate(jnodes):\n        children = [node_map[e[0]][e[1]] for e in node[\"inputs\"]]\n        attrs = StrAttrsDict(node.get(\"attrs\", {}))\n        node_name = node[\"name\"]\n        op_name = node[\"op\"]\n        if op_name == \"null\":\n            if isinstance(shape_dict, dict):\n                shape = shape_dict[node_name] if node_name in shape_dict else None\n            elif isinstance(shape_dict, (list, tuple)):\n                shape = shape_dict[shape_idx]\n            else:\n                raise ValueError(\"Unknown type of shape_dict: %s\" + type(shape_dict))\n            if isinstance(dtype_info, dict):\n                dtype = dtype_info[node_name] if node_name in dtype_info else \"float32\"\n            elif isinstance(dtype_info, (list, tuple)):\n                dtype = dtype_info[shape_idx]\n            else:\n                dtype = dtype_info\n            if isinstance(shape_dict, (list, tuple)):\n                shape_idx += 1\n            node_map[nid] = [_expr.var(node_name, shape=shape, dtype=dtype)]\n        else:\n            assert op_name in _convert_map\n            op_params = _get_op_params(children, attrs, op_name, node, params)\n            res = _convert_map[op_name](*op_params)\n            if res is None:\n                # defer conversion, used in RNN state initialization\n                res = [node]\n            elif isinstance(res, (_expr.TupleWrapper, tuple, list)):\n                pass\n            elif isinstance(res, _expr.Expr):\n                res = [res]\n            else:\n                raise RuntimeError(\"unexpected type %s\" % type(res))\n            node_map[nid] = res\n    outputs = [node_map[e[0]][e[1]] for e in jgraph[\"heads\"]]\n    outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n    func = _function.Function(analysis.free_vars(outputs), outputs)\n    return func\n\n\ndef _update_shape_dtype(shape, dtype, params):\n    \"\"\"Update shape dtype given params information\"\"\"\n    shape = {} if shape is None else shape\n    if not params:\n        return shape, dtype\n    shape = shape.copy()\n    shape.update({k: v.shape for k, v in params.items()})\n    if isinstance(dtype, str):\n        for k, v in params.items():\n            if v.dtype != dtype:\n                raise ValueError(\"%s: dtype not expected %s vs %s\" % (k, dtype, v.dtype))\n    else:\n        dtype = dtype.copy()\n        dtype.update({k: str(v.dtype) for k, v in params.items()})\n    return shape, dtype\n\n\ndef from_mxnet(symbol, shape=None, dtype=\"float32\", arg_params=None, aux_params=None):\n    \"\"\"Convert from MXNet\"s model into compatible relay Function.\n\n    Parameters\n    ----------\n    symbol : mxnet.Symbol or mxnet.gluon.HybridBlock\n        MXNet symbol.\n\n    shape : dict of str to tuple, optional\n        The input shape to the graph\n\n    dtype : str or dict of str to str\n        The input types to the graph\n\n    arg_params : dict of str to mx.NDArray\n        The argument parameters in mxnet\n\n    aux_params : dict of str to mx.NDArray\n        The auxiliary parameters in mxnet\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by nnvm\n    \"\"\"\n    try:\n        import mxnet as mx  # pylint: disable=import-outside-toplevel\n    except ImportError as e:\n        raise ImportError(\"{}. MXNet is required to parse symbols.\".format(e))\n\n    mod = IRModule()\n    if isinstance(symbol, mx.sym.Symbol):\n        params = {}\n        arg_params = arg_params if arg_params else {}\n        aux_params = aux_params if aux_params else {}\n        for k, v in arg_params.items():\n            params[k] = _nd.array(v.asnumpy())\n        for k, v in aux_params.items():\n            params[k] = _nd.array(v.asnumpy())\n        shape, dtype = _update_shape_dtype(shape, dtype, params)\n        func = _from_mxnet_impl(symbol, shape, dtype, params, mod)\n    elif isinstance(symbol, mx.gluon.HybridBlock):\n        if arg_params is not None or aux_params is not None:\n            raise ValueError(\"arg_params and aux_params ae not used when importing HybridBlock\")\n        params = {}\n        for k, v in symbol.collect_params().items():\n            params[k] = _nd.array(v.data().asnumpy())\n        inputs = []\n        for name in shape:\n            inputs.append(mx.sym.Variable(name))\n        sym = symbol(*inputs)\n        if isinstance(sym, (list, tuple)):\n            sym = mx.sym.Group(sym)\n        shape, dtype = _update_shape_dtype(shape, dtype, params)\n        func = _from_mxnet_impl(sym, shape, dtype, params, mod)\n    elif isinstance(symbol, mx.gluon.Block):\n        raise NotImplementedError(\"Only Hybrid Blocks are supported now.\")\n    else:\n        msg = \"mxnet.Symbol or gluon.HybridBlock expected, got {}\".format(type(symbol))\n        raise ValueError(msg)\n    mod[\"main\"] = func\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/mxnet_qnn_op_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, no-else-return\n\"\"\"MXNet qnn dialect helper methods for MXNet specific implementations of more\n   generic qnn supported ops.\n\"\"\"\n\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay.qnn.op.qnn import quantize, dequantize\n\n# The below values are taken from -\n# https://github.com/apache/incubator-mxnet/blob/master/src/operator/quantization/quantization_utils.h#L38-L39\nzero_centered_uint8_quantized_range = np.float32(255.5)\nzero_centered_int8_quantized_range = np.float32(127.5)\n\n\ndef _get_mkldnn_scale(data_min, data_max, quantized_range):\n    \"\"\"Computes the scale as per MKLDNN specification mentioned here -\n    https://intel.github.io/mkl-dnn/ex_int8_simplenet.html\n\n    Parameters\n    ----------\n    data_min : float32\n        A number representing the lower end of the tensor to be quantized.\n    data_max : float32\n        A number representing the upper end of the tensor to be quantized.\n    quantized_range : float32\n        255 for uint8 and 127 for int8. This is the data type range.\n\n    Returns\n    -------\n    scale : A floating point number which acts as the scale for quantization.\n    \"\"\"\n    real_range = np.max([np.abs(np.float32(data_min)), np.abs(np.float32(data_max))])\n    scale = np.divide(quantized_range, real_range)\n    scale_inverse = np.divide(1.0, scale)\n    return scale_inverse\n\n\ndef _quantize_scale_with_zero_centered(data, scale, zero_point, out_dtype):\n    quantized_output = quantize(\n        data, relay.const(scale, \"float32\"), relay.const(zero_point, \"int32\"), out_dtype=out_dtype\n    )\n    return quantized_output, scale, zero_point\n\n\ndef _quantize_with_zero_centered(data, data_min, data_max, quantized_range, out_dtype):\n    \"\"\"Quantizes the given data tensor by calculating the scale\n    using the MKLDNN formula `quantized_range / max(abs(data_min, data_max))`.\n    Where quantized_range is 255 for uint8 and 127 for int8. The `data_min`\n    and `data_max` are the min and max to use for the `data` tensor elements.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    data_min : float\n        The minimum to use data elements.\n    data_max : float\n        The maximum to use for data elements.\n    quantized_range : float\n        255 for uint8 and 127 for int8. This is the data type range.\n    out_dtype : str\n        The output data type. Can be int8 or uint8\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    scale = _get_mkldnn_scale(data_min, data_max, quantized_range)\n    zero_point = 0\n    return _quantize_scale_with_zero_centered(data, scale, zero_point, out_dtype)\n\n\ndef _quantize_mkldnn_min_max_uint8(data, data_min, data_max):\n    \"\"\"Quantizes the given `data` in float32 and the given\n    min and max ranges and the output data type is `uint8`.\n    The method of quantizing is described here - https://tinyurl.com/y5k6fz5w.\n    We use our default quantize implementation from src/relay/qnn/op/quantize.cc:72\n    but compute the `scale` and `zero_point` to fit our equation.\n    Unlike in TFLite where we get the scale and zero_point from the model, MKLDNN\n    stores the min and max from which we calculate the scale and zero_point.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    imin_range : float\n        The minimum to use data elements.\n    imax_range : float\n        The maximum to use for data elements.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _quantize_with_zero_centered(\n        data, data_min, data_max, zero_centered_uint8_quantized_range, \"uint8\"\n    )\n\n\ndef _quantize_mkldnn_min_max_int8(data, data_min, data_max):\n    \"\"\"Quantizes the given `data` in float32 and the given\n    min and max ranges and the output data type is `int8`.\n    The method of quantizing is described here - https://tinyurl.com/y5k6fz5w.\n    We use our default quantize implementation from src/relay/qnn/op/quantize.cc:72\n    but compute the `scale` and `zero_point` to fit our equation.\n    Unlike in TFLite where we get the scale and zero_point from the model, MKLDNN\n    stores the min and max from which we calculate the scale and zero_point.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    data_min : float\n        The minimum to use data elements.\n    data_max : float\n        The maximum to use for data elements.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _quantize_with_zero_centered(\n        data, data_min, data_max, zero_centered_int8_quantized_range, \"int8\"\n    )\n\n\ndef get_mkldnn_int8_scale(range_min, range_max):\n    \"\"\"Computes the quantization scale using MKLDNN specifications\n    with the given range. The output datatype of tensor to be quantized should be\n    int8.\n\n    Parameters\n    ----------\n    range_min : float32\n        A number representing the lower end of the tensor to be quantized.\n    range_max : float32\n        A number representing the upper end of the tensor to be quantized.\n\n    Returns\n    -------\n    scale : A float32 number which acts as the scale for quantization.\n    \"\"\"\n\n    scale = _get_mkldnn_scale(range_min, range_max, zero_centered_int8_quantized_range)\n    return np.float32(scale)\n\n\ndef get_mkldnn_uint8_scale(range_min, range_max):\n    \"\"\"Computes the quantization scale using MKLDNN specifications\n    with the given range. The output datatype of tensor to be quantized should be\n    uint8.\n\n    Parameters\n    ----------\n    range_min : float32\n        A number representing the lower end of the tensor to be quantized.\n    range_max : float32\n        A number representing the upper end of the tensor to be quantized.\n\n    Returns\n    -------\n    scale : A float32 number which acts as the scale for quantization.\n    \"\"\"\n\n    scale = _get_mkldnn_scale(range_min, range_max, zero_centered_uint8_quantized_range)\n    return np.float32(scale)\n\n\ndef quantize_conv_weights_bias_channel_mkldnn_from_var(\n    weights_var, bias, min_vector_range, max_vector_range, data_scale\n):\n    \"\"\"Helper method to quantize the convolution kernel in prequantized model\n    in MXNet with MKLDNN. The kernel is always quantized to int8 output datatype.\n    The inputs are the raw weights which are floating point numbers. The min and\n    max ranges are used from the weight itself. The name supplied is used to create\n    a tvm.relay.var with the given name.\n\n    Parameters\n    ----------\n    weights_var : tvm.relay.var\n        The float32 representation of the weights.\n    bias : np.array\n        The float32 np array for bias.\n    min_vector_range : array of float32\n        A number representing the minimum of the weights per channel.\n    max_vector_range : array of float32\n        A number representing the maximum of the weights per channel.\n    data_scale : float\n        The data scale value.\n\n    Returns\n    -------\n    result : tvm.relay.expr\n           The quantized representation of the weights.\n    \"\"\"\n\n    quantized_range = zero_centered_int8_quantized_range\n    real_vector_range = np.maximum(np.absolute(min_vector_range), np.absolute(max_vector_range))\n    # If real_vector_range is 0, then to avoid division by 0 in scaling,\n    # make real_vector INT32_max\n    vector_scale = np.where(\n        real_vector_range == 0,\n        1.0 / float(np.iinfo(np.int32).max),\n        np.divide(real_vector_range, quantized_range),\n    )\n\n    # Handle bias impact on scales as done by MxNet-MKLDNN.\n    if bias is not None:\n        common = 2.0 * bias.astype(\"float32\") * (1 / data_scale)\n        vector_scale_min = np.where(\n            bias > 0, common / float(np.iinfo(np.int32).max), common / float(np.iinfo(np.int32).min)\n        )\n        vector_scale = np.maximum(vector_scale, vector_scale_min)\n\n    zero_point = 0\n    quantized_output = quantize(\n        weights_var,\n        relay.const(vector_scale),\n        relay.const(zero_point, \"int32\"),\n        axis=0,\n        out_dtype=\"int8\",\n    )\n    return quantized_output, vector_scale, zero_point\n\n\ndef get_mkldnn_requantize_scale_outDtype(min_output_range, max_output_range, out_dtype):\n    \"\"\"Get the MKLDNN requantized scale.\"\"\"\n    quantized_out_range = (\n        zero_centered_int8_quantized_range\n        if out_dtype == \"int8\"\n        else zero_centered_uint8_quantized_range\n    )\n    out_range = np.max([np.abs(np.float32(min_output_range)), np.abs(np.float32(max_output_range))])\n    output_scale = quantized_out_range / out_range\n    requantize_scale = np.float32(1 / output_scale)\n    return requantize_scale\n\n\ndef get_conv_mkldnn_requantized_scale_outDtype(min_output_range, max_output_range):\n    out_dtype = \"uint8\" if min_output_range >= 0.0 else \"int8\"\n    requantize_scale = get_mkldnn_requantize_scale_outDtype(\n        min_output_range, max_output_range, out_dtype\n    )\n    return requantize_scale, out_dtype\n\n\ndef quantize_conv_bias_mkldnn_from_var(bias_var, bias_scale):\n    \"\"\"Quantized conv2d bias\"\"\"\n    zero_point = 0\n    quantized_bias = quantize(\n        data=bias_var,\n        output_scale=relay.const(bias_scale),\n        output_zero_point=relay.const(zero_point, \"int32\"),\n        axis=0,\n        out_dtype=\"int32\",\n    )\n\n    return quantized_bias\n\n\ndef quantize_mxnet_min_max(data, min_range, max_range, out_dtype=\"int8\"):\n    \"\"\"Quantizes the given `data` in float32 and the given\n    min and max ranges and the output data type.\n    Only `int8` and `uint8` is supported as output data types.\n    The input data type is expected to be `float32`.\n    Mxnet has two different flavors for quantization 1) Default 2)MKLDNN.\n    To get the second one Mxnet must be built with MKLDNN during compile time.\n    Users can choose either of the implementation for TVM runtime.\n    The main difference between the two implementation is that MKLDNN is centered\n    around 0 and the default implementation for uint8 is not.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    min_range : float\n        The minimum to use data elements.\n    max_range : float\n        The maximum to use for data elements.\n    out_dtype: str, optional\n        The output data type, can be 'int8' or 'uint8'\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    if out_dtype == \"uint8\":\n        return _quantize_mkldnn_min_max_uint8(data, min_range, max_range)\n    elif out_dtype == \"int8\":\n        return _quantize_mkldnn_min_max_int8(data, min_range, max_range)\n    else:\n        raise ValueError(\"Expected out_dtype to be int8 or uint8 but was  %s\" % out_dtype)\n\n\ndef _dequantize_zero_centered(data, data_min, data_max, quantized_range):\n    \"\"\"Dequantizes the given data tensor by calculating the scale\n    using the MKLDNN formula `max(abs(data_min, data_max))/quantized_range`.\n    Where quantized_range is 255 for uint8 and 127 for int8. The `data_min`\n    and `data_max` are the min and max to use for the `data` tensor elements.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type {int8 or uint8}.\n    data_min : float\n        The minimum to use data elements.\n    data_max : float\n        The maximum to use for data elements.\n    quantized_range : float\n        255 for uint8 and 127 for int8. This is the data type range.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    real_range = np.max([np.abs(np.float32(data_min)), np.abs(np.float32(data_max))])\n    scale = relay.const(np.divide(real_range, quantized_range), \"float32\")\n    zero_point = relay.const(0, \"int32\")\n    return dequantize(data, scale, zero_point)\n\n\ndef _dequantize_mkldnn_min_max_int8(data, imin_range, imax_range):\n    \"\"\"Dequantizes the given `data` in {int8 or uint8} and the given\n    min and max ranges and the output data type is `float32`.\n    The method of dequantizing is described here - https://tinyurl.com/y5k6fz5w.\n    We use our default quantize implementation from src/relay/qnn/op/dequantize.cc:67\n    but compute the `scale` and `zero_point` to fit our equation.\n    Unlike in TFLite where we get the scale and zero_point from the model, MKLDNN\n    stores the min and max from which we calculate the scale and zero_point.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    imin_range : float\n        The minimum to use data elements.\n    imax_range : float\n        The maximum to use for data elements.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _dequantize_zero_centered(\n        data,\n        data_min=imin_range,\n        data_max=imax_range,\n        quantized_range=zero_centered_int8_quantized_range,\n    )\n\n\ndef _dequantize_mkldnn_min_max_uint8(data, imin_range, imax_range):\n    \"\"\"Dequantizes the given `data` in {int8 or uint8} and the given\n    min and max ranges and the output data type is `float32`.\n    The method of dequantize is described here - https://tinyurl.com/y5k6fz5w.\n    We use our default quantize implementation from src/relay/qnn/op/dequantize.cc:67\n    but compute the `scale` and `zero_point` to fit our equation.\n    Unlike in TFLite where we get the scale and zero_point from the model, MKLDNN\n    stores the min and max from which we calculate the scale and zero_point.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    imin_range : float\n        The minimum to use data elements.\n    imax_range : float\n        The maximum to use for data elements.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _dequantize_zero_centered(\n        data,\n        data_min=imin_range,\n        data_max=imax_range,\n        quantized_range=zero_centered_uint8_quantized_range,\n    )\n\n\ndef dequantize_mxnet_min_max(data, min_range, max_range, in_dtype=\"int8\"):\n    \"\"\"Dequantizes the given `data` in {int8 or uint8} and the given\n    min and max ranges. The output data type is float32.\n    Only `float32` is supported as output data types.\n    The input data type is expected to be {int8 or uint8}.\n    Mxnet has two different flavors for dequantization 1) Default 2)MKLDNN.\n    To get the second one Mxnet must be built with MKLDNN during compile time.\n    Users can choose either of the implementation for TVM runtime.\n    The main difference between the two implementation is that MKLDNN is centered\n    around 0 and the default implementation for uint8 is not.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n    min_range : float\n        The minimum to use data elements for the output.\n    max_range : float\n        The maximum to use for data elements for the output.\n    in_dtype: str, optional\n        The input data type, can be 'int8' or 'uint8'\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    if in_dtype == \"uint8\":\n        return _dequantize_mkldnn_min_max_uint8(data, min_range, max_range)\n    elif in_dtype == \"int8\":\n        return _dequantize_mkldnn_min_max_int8(data, min_range, max_range)\n    else:\n        raise ValueError(\"Expected out_dtype to be int8 or uint8 but was  %s\" % in_dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/nnvm_common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition\n\"\"\"Utility functions common to NNVM and MxNet conversion.\"\"\"\nimport warnings\nfrom ... import error\nfrom ...tir.op import min_value\nfrom .. import expr as _expr\nfrom .. import op as _op\nfrom .common import get_relay_op\nfrom .common import infer_type as _infer_type\nfrom .common import infer_shape as _infer_shape\n\n\ndef _warn_not_used(attr, op=\"nnvm\"):\n    err = \"{} is ignored in {}.\".format(attr, op)\n    warnings.warn(err)\n\n\ndef _rename(new_op):\n    if isinstance(new_op, str):\n        new_op = get_relay_op(new_op)\n    # attrs are ignored.\n    def impl(inputs, _, _dtype=\"float32\"):\n        return new_op(*inputs)\n\n    return impl\n\n\ndef _reshape(inputs, attrs):\n    shape = attrs.get_int_tuple(\"shape\")\n    reverse = attrs.get_bool(\"reverse\", False)\n    if reverse:\n        return _op.reverse_reshape(inputs[0], newshape=shape)\n    return _op.reshape(inputs[0], newshape=shape)\n\n\ndef _init_op(new_op):\n    \"\"\"Init ops like zeros/ones\"\"\"\n\n    def _impl(inputs, attrs):\n        assert len(inputs) == 0\n        shape = attrs.get_int_tuple(\"shape\")\n        dtype = attrs.get_str(\"dtype\", \"float32\")\n        return new_op(shape=shape, dtype=dtype)\n\n    return _impl\n\n\ndef _softmax_op(new_op):\n    \"\"\"softmax/log_softmax\"\"\"\n\n    def _impl(inputs, attrs, _dtype=\"float32\"):\n        axis = attrs.get_int(\"axis\", -1)\n        use_length = attrs.get_bool(\"use_length\", False)\n        if use_length:\n            # The second arg is valid_length. We can use sequence mask to mask the input before\n            # computing softmax\n            assert len(inputs) == 2\n\n            data = inputs[0]\n            length = inputs[1]\n            data_shape = _infer_shape(data)\n            data_dtype = _infer_type(data).checked_type.dtype\n            length_shape = _infer_shape(length)\n\n            if axis < 0:\n                axis = len(data_shape) + axis\n\n            data_ndims = len(data_shape)\n            length_ndims = len(length_shape)\n\n            # Sequence_mask supports axis = 0 and 1 and requires data to be in specific format.\n            if axis == data_ndims - 1 and data_ndims > 2 and length_ndims == 2:\n                new_batch_size = 1\n                for dim in range(length_ndims):\n                    assert data_shape[dim] == length_shape[dim]\n                    new_batch_size *= data_shape[dim]\n\n                # Reshape the data and length to satisfy sequence mask\n                data = _op.reshape(data, newshape=(new_batch_size, -1))\n                length = _op.reshape(length, newshape=(new_batch_size))\n\n                # Input data is now 2D, we can set the axis = 1\n                axis = 1\n            elif data_ndims > 2:\n                raise error.OpNotImplemented(\n                    \"Operator softmax with use_length=True is supported only for axis -1\"\n                )\n\n            res = _op.sequence_mask(\n                data=data,\n                valid_length=length,\n                mask_value=float(min_value(data_dtype).value),\n                axis=axis,\n            )\n\n            # Apply softmax\n            res = new_op(res, axis=axis)\n\n            # Reshape back to input data shape\n            if len(data_shape) > 2:\n                return _op.reshape(res, newshape=data_shape)\n            return res\n        return new_op(inputs[0], axis=axis)\n\n    return _impl\n\n\ndef _reduce(new_op):\n    \"\"\"Reduction ops like sum/min/max\"\"\"\n\n    def _impl(inputs, attrs, _dtype=\"float32\"):\n        assert len(inputs) == 1\n        axis = attrs.get_int_tuple(\"axis\", [])\n        keepdims = attrs.get_bool(\"keepdims\", False)\n        exclude = attrs.get_bool(\"exclude\", False)\n        # use None for reduce over all axis.\n        axis = None if len(axis) == 0 else axis\n        return new_op(inputs[0], axis=axis, keepdims=keepdims, exclude=exclude)\n\n    return _impl\n\n\ndef _arg_reduce(new_op):\n    \"\"\"Arg Reduction ops like argmin/argmax\"\"\"\n\n    def _impl(inputs, attrs):\n        assert len(inputs) == 1\n        axis = attrs.get_int(\"axis\", None)\n        keepdims = attrs.get_bool(\"keepdims\", False)\n        res = new_op(inputs[0], axis=[axis], keepdims=keepdims)\n        # cast to dtype.\n        res = res.astype(\"float32\")\n        return res\n\n    return _impl\n\n\ndef _cast(inputs, attrs):\n    \"\"\"Type cast\"\"\"\n    dtype = attrs.get_str(\"dtype\")\n    return inputs[0].astype(dtype=dtype)\n\n\ndef _clip(inputs, attrs):\n    a_min = attrs.get_float(\"a_min\")\n    a_max = attrs.get_float(\"a_max\")\n    return _op.clip(inputs[0], a_min=a_min, a_max=a_max)\n\n\ndef _transpose(inputs, attrs):\n    axes = attrs.get_int_tuple(\"axes\", None)\n    # translate default case\n    axes = None if len(axes) == 0 else axes\n    return _op.transpose(inputs[0], axes=axes)\n\n\ndef _upsampling(inputs, attrs):\n    scale = attrs.get_int(\"scale\")\n    return _op.nn.upsampling(inputs[0], scale_h=scale, scale_w=scale)\n\n\ndef _elemwise_sum(inputs, _, _dtype=\"float32\"):\n    assert len(inputs) > 0\n    res = inputs[0]\n    for x in inputs[1:]:\n        res = _op.add(res, x)\n    return res\n\n\ndef _binop_scalar(new_op):\n    def _impl(inputs, attrs, odtype=None):\n        assert len(inputs) == 1\n        scalar = attrs.get_float(\"scalar\")\n        if odtype is None:\n            odtype = _infer_type(inputs[0]).checked_type.dtype\n        scalar = _expr.const(scalar, dtype=odtype)\n        return new_op(inputs[0], scalar)\n\n    return _impl\n\n\ndef _rbinop_scalar(new_op):\n    def _impl(inputs, attrs, odtype=None):\n        assert len(inputs) == 1\n        scalar = attrs.get_float(\"scalar\")\n        if odtype is None:\n            odtype = _infer_type(inputs[0]).checked_type.dtype\n        scalar = _expr.const(scalar, dtype=odtype)\n        return new_op(scalar, inputs[0])\n\n    return _impl\n\n\ndef _compare(new_op):\n    \"\"\"Compare ops like greater/less\"\"\"\n\n    def _impl(inputs, _, odtype=\"float32\"):\n        assert len(inputs) == 2\n        return new_op(inputs[0], inputs[1]).astype(odtype)\n\n    return _impl\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/oneflow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, unused-argument, too-many-lines\n# pylint: disable=import-outside-toplevel\n\"\"\"OneFlow: OneFlow is a performance-centered and open-source deep learning framework.\"\"\"\n\nimport os\nimport re\nimport copy\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .. import ty as _ty\nfrom .common import (\n    AttrCvt,\n    Renamer,\n    fold_constant,\n    get_relay_op,\n    infer_shape,\n    infer_type,\n    new_var,\n)\n\n__all__ = [\"from_oneflow\"]\n\nFLOW_2_STR_DTYPE = {\n    2: \"float32\",\n    3: \"float64\",\n    6: \"int64\",\n    5: \"int32\",\n    4: \"int8\",\n    7: \"uint8\",\n    9: \"float16\",\n}\n\n\ndef is_input_op(node):\n    \"\"\"Return true when the node is the input of the graph.\"\"\"\n    return node.WhichOneof(\"op_type\") == \"input_conf\"\n\n\ndef is_user_op(node):\n    \"\"\"Return true when the node is the intermediate variables of graph.\"\"\"\n    return node.WhichOneof(\"op_type\") == \"user_conf\"\n\n\ndef is_output_op(node):\n    \"\"\"Return true when the node is the output of the graph.\"\"\"\n    return node.WhichOneof(\"op_type\") == \"output_conf\"\n\n\ndef is_param_op(node):\n    \"\"\"Return true when the node is the intermediate variables of model(saved).\"\"\"\n    return node.WhichOneof(\"op_type\") == \"variable_conf\"\n\n\ndef get_node_info(node):\n    \"\"\"\n    Get basic information about nodes: shape, data_type\n    \"\"\"\n    # list->tuple\n    shape = tuple(node.input_conf.blob_conf.shape.dim)\n    # get data type\n    dtype = node.input_conf.blob_conf.data_type\n    if dtype in list(FLOW_2_NP_DTYPE.keys()):\n        data_type = FLOW_2_NP_DTYPE[dtype]\n    else:\n        raise IndexError(\"Please check the data type of your node: %s\" % node.name)\n\n    return shape, data_type\n\n\ndef _dtype_shape_promotion(inputs):\n    \"\"\"Promote data type and shape for list of tensors.\"\"\"\n\n    dtype_order = [\"bool\", \"int8\", \"int16\", \"int32\", \"int64\", \"float32\", \"float64\"]\n    ranks = [len(infer_shape(x)) for x in inputs]\n    if set(ranks) == set([1, 0]):\n        for i, r in enumerate(ranks):\n            if r == 0:\n                inputs[i] = _op.expand_dims(inputs[i], axis=0)\n\n    dtypes = set(dtype_order.index(infer_type(x).checked_type.dtype) for x in inputs)\n    if len(dtypes) == 1:\n        return inputs\n    max_dtype = dtype_order[max(dtypes)]\n    for i, input_op in enumerate(inputs):\n        if infer_type(input_op).checked_type.dtype != max_dtype:\n            inputs[i] = input_op.astype(max_dtype)\n    return inputs\n\n\ndef parse_attr(attr):\n    \"\"\"Parse attribute of user op in oneflow.\"\"\"\n    attrs = {}\n    for a in attr:\n        attr_str = str(attr[a])\n\n        if attr_str[0:7] == \"at_list\":\n            attr_str_ = attr_str.split(\" \")[0]\n\n            if attr_str_ == \"at_list_float\":\n                attrs[a] = tuple(attr[a].at_list_float.val)\n            elif attr_str_ == \"at_list_int32\":\n                attrs[a] = tuple(attr[a].at_list_int32.val)\n            elif attr_str_ == \"at_list_int64\":\n                attrs[a] = tuple(attr[a].at_list_int64.val)\n\n        elif attr_str.split(\":\")[0] == \"at_string\":\n            attrs[a] = attr[a].at_string\n\n        elif attr_str.split(\" \")[0] == \"at_shape\":\n            attrs[a] = tuple(list(attr[a].at_shape.dim))\n\n        else:\n            attr_str_ = attr_str.split(\":\")[0]\n            if attr_str_ == \"at_bool\":\n                attrs[a] = attr[a].at_bool\n            elif attr_str_ == \"at_double\":\n                attrs[a] = attr[a].at_double\n            elif attr_str_ == \"at_float\":\n                attrs[a] = attr[a].at_float\n            elif attr_str_ == \"at_int32\":\n                attrs[a] = attr[a].at_int32\n            elif attr_str_ == \"at_int64\":\n                attrs[a] = attr[a].at_int64\n\n    return attrs\n\n\ndef shape_of(x, dtype=\"int64\"):\n    ttype = infer_type(x).checked_type\n    if not _ty.is_dynamic(ttype):\n        shape = list(ttype.shape)\n        return _expr.const(shape, dtype)\n\n    return _op.shape_of(x, dtype)\n\n\ndef dimension_constraint():\n    def _dim_check(attrs):\n        if len(attrs[\"kernel_size\"]) in [1, 2, 3]:\n            return True\n        return False\n\n    return _dim_check, \"Only 1d, 2d and 3d kernel supported.\"\n\n\nclass OneFlowOpConverter(object):\n    \"\"\"A helper class for holding oneflow op converters.\"\"\"\n\n    @classmethod\n    def get_converter(cls):\n        \"\"\"\n        Get converter matches given opset.\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        converter, which should be `_impl_vx`.\n        \"\"\"\n        version = 1\n        if hasattr(cls, \"_impl_v{}\".format(version)):\n            return getattr(cls, \"_impl_v{}\".format(version))\n        raise NotImplementedError(\"version {} of {} not implemented\".format(version, cls.__name__))\n\n\nclass Pool(OneFlowOpConverter):\n    \"\"\"A helper class for pool op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        data = inputs[0]\n        attrs.pop(\"data_format\")\n        out = AttrCvt(\n            op_name=cls.name,\n            transforms={\n                \"kernel_size\": \"pool_size\",\n                \"stride\": \"strides\",\n                \"dilations\": (\"dilation\", 1),\n            },\n            ignores=[\"return_indices\", \"divisor_override\"],\n            custom_check=dimension_constraint(),\n        )([data], attrs, params)\n\n        return out\n\n\nclass AdaptiveAvgPool2d(OneFlowOpConverter):\n    \"\"\"Operator converter for AdaptiveAvgPool2d\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.nn.adaptive_avg_pool2d(inputs[0], output_size=attrs[\"output_size\"])\n\n\nclass AdaptiveMaxPool2d(OneFlowOpConverter):\n    \"\"\"Operator converter for AdaptiveMaxPool2d\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.nn.adaptive_max_pool2d(inputs[0], output_size=attrs[\"output_size\"])\n\n\nclass GlobalAveragePool(OneFlowOpConverter):\n    \"\"\"Operator converter for GlobalAveragePool\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        rank = len(infer_shape(inputs[0]))\n        if rank == 3:\n            return _op.nn.global_avg_pool1d(inputs[0])\n        if rank == 4:\n            return _op.nn.global_avg_pool2d(inputs[0])\n        if rank == 5:\n            return _op.nn.global_avg_pool3d(inputs[0])\n        raise NotImplementedError(\n            \"Global average pooling is only implemented for 1D, 2D, and 3D kernels, got %dD.\"\n            % (rank - 2),\n        )\n\n\nclass GlobalMaxPool(OneFlowOpConverter):\n    \"\"\"Operator converter for GlobalMaxPool\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        rank = len(infer_shape(inputs[0]))\n        if rank == 3:\n            return _op.nn.global_max_pool1d(inputs[0])\n        if rank == 4:\n            return _op.nn.global_max_pool2d(inputs[0])\n        if rank == 5:\n            return _op.nn.global_max_pool3d(inputs[0])\n        raise NotImplementedError(\n            \"Global max pooling is only implemented for 1D, 2D, and 3D kernels, got %dD.\"\n            % (rank - 2),\n        )\n\n\nclass Conv(OneFlowOpConverter):\n    \"\"\"A helper class for conv op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        # The kernel is imported from model_dir_path, without the \".weight\" logo, etc.\n        # The data is obtained through the graph, its op contains \"_input.\"\n        in_names = [\"_input.\"]\n        kernel_names = [\".weight\"]\n        for i in inputs:\n            IN_NAMES = any(x in str(i) for x in in_names)\n            KERNEL_NAMES = any(x in str(i) for x in kernel_names)\n            if IN_NAMES:\n                data = i\n            elif KERNEL_NAMES:\n                kernel = i\n            else:\n                data = i\n\n        # Use shape of input to determine convolution type.\n        kernel_type = infer_type(kernel)\n        kernel_shapes = [get_const_tuple(kernel_type.checked_type.shape)]\n\n        if \"kernel_size\" not in attrs:\n            attrs[\"kernel_size\"] = kernel_shapes[0][2:]\n        if \"dilation_rate\" in attrs:\n            attrs[\"dilation\"] = list(attrs[\"dilation_rate\"])\n            attrs.pop(\"dilation_rate\")\n\n        pad_v = attrs.get(\"padding_before\", [0, 0])\n        attrs[\"padding\"] = [pad_v[0], pad_v[1], pad_v[0], pad_v[1]]\n\n        group_conv1d = False\n        if cls.name == \"conv1d\" and attrs.get(\"groups\") != 1:\n            group_conv1d = True\n            # Expand input from NCW to NCHW\n            data = _op.expand_dims(data, axis=2)\n            # Expand kernel from OIW to OIHW\n            kernel = _op.expand_dims(kernel, axis=2)\n            # Add new value to kernel_shape, strices, dilation, pads, if needed\n            attrs[\"kernel_size\"] = [1] + list(attrs[\"kernel_size\"])\n            if \"strides\" in attrs:\n                attrs[\"strides\"] = [1] + list(attrs[\"strides\"])\n            if \"dilations\" in attrs:\n                attrs[\"dilation\"] = [1] + list(attrs[\"dilations\"])\n\n        out = AttrCvt(\n            op_name=cls.name,\n            transforms={\n                \"group\": (\"groups\", 1),\n            },\n            ignores=[\"data_format\", \"filters\", \"padding_after\", \"padding_before\"],\n            custom_check=dimension_constraint(),\n        )([data, kernel], attrs, params)\n\n        # If this was a group_conv1d, squish output back to NCW.\n        if group_conv1d:\n            out = _op.squeeze(out, axis=[2])\n\n        return out\n\n\nclass ConvTranspose(OneFlowOpConverter):\n    \"\"\"Operator converter for ConvTranspose.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        in_names = [\"_input.\"]\n        kernel_names = [\".weight\"]\n        for i in inputs:\n            IN_NAMES = any(x in str(i) for x in in_names)\n            KERNEL_NAMES = any(x in str(i) for x in kernel_names)\n            if IN_NAMES:\n                data = i\n            elif KERNEL_NAMES:\n                kernel = i\n            else:\n                data = i\n\n        # get number of channels\n        attrs[\"channels\"] = attrs.get(\"filters\", 1)\n        attrs[\"groups\"] = attrs.get(\"group\", 1)\n\n        kernel_type = infer_type(kernel)\n        kernel_shapes = [get_const_tuple(kernel_type.checked_type.shape)]\n\n        if \"kernel_size\" not in attrs:\n            attrs[\"kernel_size\"] = kernel_shapes[0][2:]\n\n        if \"dilation_rate\" in attrs:\n            attrs[\"dilation\"] = list(attrs[\"dilation_rate\"])\n            attrs.pop(\"dilation_rate\")\n\n        pad_v = attrs.get(\"padding_before\", [0, 0])\n        attrs[\"padding\"] = [pad_v[0], pad_v[1], pad_v[0], pad_v[1]]\n\n        out = AttrCvt(\n            op_name=cls.name,\n            transforms={\n                \"group\": (\"groups\", 1),\n            },\n            disables=[\"filters\", \"data_format\", \"padding_before\"],\n            custom_check=dimension_constraint(),\n        )([data, kernel], attrs, params)\n\n        return out\n\n\nclass Upsample(OneFlowOpConverter):\n    \"\"\"A helper class for upsample op converters\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        dims = len(input_shape)\n\n        width_scale = attrs.get(\"width_scale\", 1.0)\n        height_scale = attrs.get(\"height_scale\", 1.0)\n        align_corners = attrs.get(\"align_corners\", False)\n\n        if \"nearest\" in cls.name:\n            method = \"nearest_neighbor\"\n        elif \"trilinear\" in cls.name:\n            method = \"trilinear\"\n        elif \"bilinear\" in cls.name:\n            method = \"bilinear\"\n\n        # in 3d case, we use the purely static op\n        if dims == 5:\n            if isinstance(scales, _expr.Expr):\n                scale_h = _op.take(scales, _op.const(3))\n                scale_w = _op.take(scales, _op.const(4))\n                scale_d = _op.take(scales, _op.const(1))\n            else:\n                assert len(scales) == 5\n                scale_h = scales[-2]\n                scale_w = scales[-1]\n                scale_d = scales[-3]\n\n            layout = \"NCDHW\"\n            out = _op.nn.upsampling3d(\n                data,\n                scale_d,\n                scale_h,\n                scale_w,\n                layout=layout,\n                method=method,\n                coordinate_transformation_mode=\"asymmetric\",\n            )\n        # in 2d case, use dynamic op\n        else:\n            if isinstance(height_scale, _expr.Expr):\n                height_scale = _op.take(height_scale, _op.const(3))\n                width_scale = _op.take(width_scale, _op.const(4))\n            layout = \"NCHW\"\n\n            out = _op.nn.upsampling(\n                inputs[0],\n                height_scale,\n                width_scale,\n                layout=layout,\n                method=method,\n                align_corners=align_corners,\n            )\n        return out\n\n\nclass UpsampleNearest(Upsample):\n    \"\"\"Operator converter for Upsample Nearest\"\"\"\n\n    name = \"upsample_nearest\"\n\n\nclass UpsampleBiLinear(Upsample):\n    \"\"\"Operator converter for Upsample Bilinear\"\"\"\n\n    name = \"upsample_bilinear\"\n\n\nclass Conv2d(Conv):\n    \"\"\"Operator converter for Conv2d\"\"\"\n\n    name = \"conv2d\"\n\n\nclass ConvTranspose2d(ConvTranspose):\n    \"\"\"Operator converter for ConvTranspose2d\"\"\"\n\n    name = \"conv2d_transpose\"\n\n\nclass BatchNorm(OneFlowOpConverter):\n    \"\"\"Operator converter for BatchNorm\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        # sort the inputs\n        sorted_inputs = copy.deepcopy(inputs)\n        for i in inputs:\n            IN_NAMES = \"_input.\" in str(i)\n            if IN_NAMES:\n                sorted_inputs[0] = i\n            elif \"weight\" in str(i) and not IN_NAMES:\n                sorted_inputs[1] = i\n            elif \"bias\" in str(i) and not IN_NAMES:\n                sorted_inputs[2] = i\n            elif \"mean\" in str(i) and not IN_NAMES:\n                sorted_inputs[3] = i\n            elif \"var\" in str(i) and not IN_NAMES:\n                sorted_inputs[4] = i\n\n        if \"data_format\" in attrs:\n            if attrs[\"data_format\"] == \"channel_first\":\n                attrs[\"axis\"] = 1\n\n        out = AttrCvt(op_name=\"batch_norm\", ignores=[\"training\"], disables=[\"momentum\"])(\n            sorted_inputs, attrs, params\n        )\n        return out[0]\n\n\nclass Flatten(OneFlowOpConverter):\n    \"\"\"Operator converter for Flatten\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        x = inputs[0]\n        input_shape = list(infer_shape(x))\n\n        start = attrs[\"start_dim\"]\n        end = attrs[\"end_dim\"]\n        ndim = len(input_shape)\n        if end < 0:\n            end += ndim\n        new_shape = [0] * start\n\n        new_shape.append(-1)\n        squeeze_axes = []\n        for i in range(start + 1, end + 1):\n            new_shape.append(1)\n            squeeze_axes.append(i)\n        for _ in range(end + 1, ndim):\n            new_shape.append(0)\n        out = _op.reshape(x, new_shape)\n        if squeeze_axes:\n            out = _op.squeeze(out, axis=squeeze_axes)\n        return out\n\n\nclass MatMul(OneFlowOpConverter):\n    \"\"\"Operator converter for MatMul\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 2, \"MatMul op take 2 inputs, {} given\".format(len(inputs))\n\n        dtype = infer_type(inputs[0]).checked_type.dtype\n        # Y = alpha * A * B\n        alpha = float(attrs.get(\"alpha\", 1.0))\n        transA = bool(attrs.get(\"transpose_a\", False))\n        transB = bool(attrs.get(\"transpose_b\", False))\n\n        a_shape = infer_shape(inputs[0])\n        b_shape = infer_shape(inputs[1])\n        if (\n            (transA and transB and a_shape[-2] != b_shape[-1])\n            or (transA and not transB and a_shape[-2] != b_shape[-2])\n            or (transB and not transA and a_shape[-1] != b_shape[-1])\n            or (not transB and not transA and a_shape[-1] != b_shape[-2])\n        ):\n            matmul_a = inputs[1]\n            matmul_b = inputs[0]\n        else:\n            matmul_a = inputs[0]\n            matmul_b = inputs[1]\n\n        if transA:\n            perm = list(range(len(a_shape)))\n            perm[-2] = len(a_shape) - 1\n            perm[-1] = len(a_shape) - 2\n            matmul_a = _op.transpose(matmul_a, axes=perm)\n        if transB:\n            perm = list(range(len(b_shape)))\n            perm[-2] = len(b_shape) - 1\n            perm[-1] = len(b_shape) - 2\n            matmul_b = _op.transpose(matmul_b, axes=perm)\n\n        # This implemention almost keeps same with ONNX\n        # Need to check input shape as batch matmul must be supported.\n        a_shape = shape_of(matmul_a, dtype=\"int32\")\n        a_rank = infer_shape(a_shape)[0]\n        b_shape = shape_of(matmul_b, dtype=\"int32\")\n        b_rank = infer_shape(b_shape)[0]\n        # When performing a batch matmul, we need to properly handle N-dim shapes.\n        if a_rank > 2 or b_rank > 2:\n\n            def flatten_to_nd(x, x_shape, nd=3):\n                ndims = infer_shape(x_shape)[0]\n                if ndims == nd:\n                    return x\n                newshape = _op.concatenate(\n                    [\n                        _expr.const([-1], dtype=infer_type(x_shape).checked_type.dtype),\n                        _op.strided_slice(x_shape, [ndims - nd + 1], [ndims]),\n                    ],\n                    0,\n                )\n                out = _op.reshape(x, fold_constant(newshape))\n                return out\n\n            b_type = infer_type(matmul_b)\n            # Convert to dense if the second matrix is 2d and non-dynamic\n            if b_rank == 2 and not _ty.is_dynamic(b_type.checked_type):\n                a = flatten_to_nd(matmul_a, a_shape, 2)\n                b = _op.transpose(matmul_b)\n                output = _op.nn.dense(a, b)\n            else:\n                # Convert a and b into 3 dimensional tensors.\n                a = flatten_to_nd(matmul_a, a_shape, 3)\n                b = flatten_to_nd(matmul_b, b_shape, 3)\n                # Transpose matrix dimensions of b.\n                b = _op.transpose(b, [0, 2, 1])\n                # Perform a batch matmul.\n                output = _op.nn.batch_matmul(a, b)\n            # Determine the output batch dimension.\n            if a_rank > b_rank:\n                out_batch = _op.strided_slice(a_shape, [0], [a_rank - 2])\n            elif a_rank < b_rank:\n                out_batch = _op.strided_slice(b_shape, [0], [b_rank - 2])\n            # If its unclear how broadcasting should be applied, the output\n            # shape is determined by choosing the maximum value from each input.\n            else:\n                out_batch = _op.concatenate(\n                    [\n                        _op.maximum(\n                            _op.strided_slice(a_shape, [i], [i + 1]),\n                            _op.strided_slice(b_shape, [i], [i + 1]),\n                        )\n                        for i in range(a_rank - 2)\n                    ],\n                    0,\n                )\n            # Reshape output to original dimensions.\n            final_shape = _op.concatenate(\n                [\n                    out_batch,\n                    _op.strided_slice(\n                        a_shape, [infer_shape(a_shape)[0] - 2], [infer_shape(a_shape)[0] - 1]\n                    ),\n                    _op.strided_slice(\n                        b_shape, [infer_shape(b_shape)[0] - 1], [infer_shape(b_shape)[0]]\n                    ),\n                ],\n                0,\n            )\n            out = _op.reshape(output, fold_constant(final_shape))\n        else:\n            if b_rank == 1:\n                matmul_b = _op.expand_dims(matmul_b, 1, 1)\n            # Otherwise a simple dense op will get the job done.\n            input_1_t = _op.transpose(matmul_b, axes=(1, 0))\n            out = _op.nn.dense(matmul_a, input_1_t)\n            if b_rank == 1:\n                out = _op.squeeze(out, axis=[-1])\n        if not np.isclose(alpha, 1.0):\n            out = out * _expr.const(alpha, dtype=dtype)\n        return out\n\n\nclass Reduce(OneFlowOpConverter):\n    \"\"\"Operator converter for reduce ops\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        attr = {\"axis\": attrs.get(\"axis\", 0), \"keepdims\": attrs.get(\"keepdims\", True)}\n        return AttrCvt(cls.name)(inputs, attr)\n\n\nclass ReduceMax(Reduce):\n    \"\"\"Operator converter for ReduceMax\"\"\"\n\n    name = \"max\"\n\n\nclass ReduceMin(Reduce):\n    \"\"\"Operator converter for ReduceMin\"\"\"\n\n    name = \"min\"\n\n\nclass ReduceSum(Reduce):\n    \"\"\"Operator converter for ReduceSum\"\"\"\n\n    name = \"sum\"\n\n\nclass ReduceMean(Reduce):\n    \"\"\"Operator converter for ReduceMean\"\"\"\n\n    name = \"mean\"\n\n\nclass Square(OneFlowOpConverter):\n    \"\"\"Operator converter for square\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 1, \"Square op {} take 1 inputs, {} given\".format(\n            cls.name, len(inputs)\n        )\n        return _op.multiply(inputs[0], inputs[0])\n\n\nclass Add(OneFlowOpConverter):\n    \"\"\"Operator converter for Add\"\"\"\n\n    name = \"add\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 2, \"Math op {} take 2 inputs, {} given\".format(cls.name, len(inputs))\n        axis = int(attrs.get(\"axis\", 0))\n\n        true_names = [\"weight\", \"bias\"]\n        false_names = [\"_input.\"]\n\n        for i in inputs:\n            T_NAMES = any(x in str(i) for x in true_names)\n            F_NAMES = any(x in str(i) for x in false_names)\n            if T_NAMES and not F_NAMES:\n                add_b = i\n            else:\n                add_a = i\n\n        # fix the shape\n        add_shape = infer_shape(add_a)\n        if len(add_shape) > 2:\n            add_b = _op.expand_dims(add_b, axis=axis, num_newaxis=len(add_shape) - 2)\n        add_b_shape = list(infer_shape(add_b))\n        add_b_shape.insert(0, add_shape[0])\n\n        add_b = _op.reshape(add_b, tuple(add_b_shape))\n        out = get_relay_op(cls.name)(add_a, add_b)\n\n        return out\n\n\nclass Expand(OneFlowOpConverter):\n    \"\"\"Operator converter for Expand\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        data_in = inputs[0]\n        shape = list(infer_shape(data_in))\n\n        ndims = len(shape)\n        sizes = attrs[\"logical_expand_shape\"]\n        out = data_in\n        out_dims = len(sizes)\n        if ndims < out_dims:\n            num_newaxis = out_dims - ndims\n            out = _op.expand_dims(out, axis=0, num_newaxis=num_newaxis)\n            shape = [1] * num_newaxis + shape\n\n        for i in range(out_dims):\n            if sizes[i] != -1 and shape[i] == 1:\n                out = _op.repeat(out, sizes[i], axis=i)\n\n        return out\n\n\nclass Transpose(OneFlowOpConverter):\n    \"\"\"Operator converter for transpose.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        perm = attrs[\"perm\"]\n        return _op.transpose(inputs[0], axes=perm)\n\n\nclass ExpandDim(OneFlowOpConverter):\n    \"\"\"Operator converter for ExpandDim\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n\n        return _op.expand_dims(inputs[0], axis=attrs.get(\"axis\", 0))\n\n\nclass BroadcastMath(OneFlowOpConverter):\n    \"\"\"Operator converter for broadcast math ops\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 2, \"Math op {} take 2 inputs, {} given\".format(cls.name, len(inputs))\n        beta_names = [\"weight\", \"bias\", \"mean\", \"var\", \"Constant\"]\n\n        for i in inputs:\n            T_NAMES = any([x in str(i) for x in beta_names])\n            if T_NAMES and \"_input.\" not in str(i):\n                input_b = i\n            else:\n                input_a = i\n\n        if cls.name == \"divide\":\n            length = []\n            for i in inputs:\n                length.append(len(str(i)))\n            for i in inputs:\n                if len(str(i)) == max(length):\n                    input_a = i\n                else:\n                    input_b = i\n        if cls.name == \"subtract\":\n            length = []\n            for i in inputs:\n                length.append(len(str(i)))\n            for i in inputs:\n                if len(str(i)) == max(length):\n                    input_b = i\n                else:\n                    input_a = i\n        try:\n            return get_relay_op(cls.name)(input_a, input_b)\n        except UnboundLocalError:\n            return get_relay_op(cls.name)(*inputs)\n\n\nclass BroadcastMul(BroadcastMath):\n    \"\"\"Operator converter for Mul broadcast\"\"\"\n\n    name = \"multiply\"\n\n\nclass BroadcastAdd(BroadcastMath):\n    \"\"\"Operator converter for Add broadcast\"\"\"\n\n    name = \"add\"\n\n\nclass BroadcastSub(BroadcastMath):\n    \"\"\"Operator converter for Sub broadcast\"\"\"\n\n    name = \"subtract\"\n\n\nclass BroadcastDiv(BroadcastMath):\n    \"\"\"Operator converter for Div broadcast\"\"\"\n\n    name = \"divide\"\n\n\nclass LogicalGreater(OneFlowOpConverter):\n    \"\"\"Operator converter for greater\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        res = None\n        if attrs.get(\"has_int_operand\", True):\n            value = attrs.get(\"int_operand\", 0.0)\n            res = _op.greater(inputs[0], _op.full_like(inputs[0], fill_value=_expr.const(value)))\n        elif attrs.get(\"has_float_operand\", True):\n            value = float(attrs.get(\"float_operand\", 0.0))\n            res = _op.greater(\n                inputs[0], _op.full_like(inputs[0], fill_value=_expr.const(value)).astype(\"float32\")\n            )\n        else:\n            raise AttributeError(\n                \"please check if has_int_operand or has_float_operand in your attrs\"\n            )\n        return res\n\n\nclass Log1p(OneFlowOpConverter):\n    \"\"\"Operator converter for Log1p\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.log(inputs[0] + _expr.const(1.0))\n\n\nclass Pow(OneFlowOpConverter):\n    \"\"\"Operator converter for Power\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        inputs = _dtype_shape_promotion(inputs)\n        return get_relay_op(cls.name)(inputs[0], inputs[1])\n\n\nclass Expm1(OneFlowOpConverter):\n    \"\"\"Operator converter for Expm1\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.exp(inputs[0]) - _expr.const(1.0)\n\n\nclass Unary(OneFlowOpConverter):\n    \"\"\"A helper class for unary op converters\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 1, \"Unary math op {} takes 1 input, {} given\".format(\n            cls.name, len(inputs)\n        )\n        return get_relay_op(cls.name)(*inputs)\n\n\nclass Absolute(Unary):\n    \"\"\"Operator converter for Absolute.\"\"\"\n\n    name = \"abs\"\n\n\nclass AddN(OneFlowOpConverter):\n    \"\"\"Operator converter for Add_n\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) > 0, \"add_n take >=1 inputs, but 0 given.\"\n\n        res = inputs[0]\n        for each in inputs[1:]:\n            res = _op.add(res, each)\n        return res\n\n\nclass ScalarAdd(OneFlowOpConverter):\n    \"\"\"Operator convert for Add_scalar\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 1, \"add_scalar take == 1 inputs, but {} given.\".format(len(inputs))\n\n        if attrs.get(\"has_int_operand\", True):\n            res = inputs[0] + _expr.const(attrs[\"int_operand\"])\n        elif attrs.get(\"has_float_operand\", True):\n            res = inputs[0] + _expr.const(attrs[\"float_operand\"])\n        else:\n            raise AttributeError(\n                \"please check if has_int_operand or has_float_operand in your attrs\"\n            )\n\n        return res\n\n\nclass ScalarMul(OneFlowOpConverter):\n    \"\"\"Operator convert for Mul_scalar\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 1, \"add_scalar take == 1 inputs, but {} given.\".format(len(inputs))\n\n        if attrs.get(\"has_int_operand\", True):\n            res = inputs[0] * _expr.const(attrs[\"int_operand\"], dtype=\"float32\")\n        elif attrs.get(\"has_float_operand\", True):\n            res = inputs[0] * _expr.const(attrs[\"float_operand\"])\n        else:\n            raise AttributeError(\n                \"please check if has_int_operand or has_float_operand in your attrs\"\n            )\n\n        return res\n\n\nclass ScalarDiv(OneFlowOpConverter):\n    \"\"\"Operator convert for Div_scalar\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 1, \"div_scalar take == 1 inputs, but {} given.\".format(len(inputs))\n\n        if attrs.get(\"has_int_operand\", True):\n            res = inputs[0] / _expr.const(attrs[\"int_operand\"], dtype=\"float32\")\n        elif attrs.get(\"has_float_operand\", True):\n            res = inputs[0] / _expr.const(attrs[\"float_operand\"])\n        else:\n            raise AttributeError(\n                \"please check if has_int_operand or has_float_operand in your attrs\"\n            )\n\n        return res\n\n\nclass ScalarPow(OneFlowOpConverter):\n    \"\"\"Operator convert for Pow_scalar\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        if attrs.get(\"has_int_operand\", True):\n            coeff = _expr.const(attrs[\"int_operand\"])\n        elif attrs.get(\"has_float_operand\", True):\n            coeff = _expr.const(attrs[\"float_operand\"])\n        return _op.power(inputs[0], coeff)\n\n\nclass MaxPool2d(Pool):\n    \"\"\"Operator converter for MaxPool\"\"\"\n\n    name = \"max_pool2d\"\n\n\nclass AveragePool2d(Pool):\n    \"\"\"Operator converter for AveragePool.\"\"\"\n\n    name = \"avg_pool2d\"\n\n\nclass Affine(OneFlowOpConverter):\n    \"\"\"Operator converter for Affine transformation.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        alpha = _expr.const(attrs.get(\"alpha\", 1.0))\n        beta = _expr.const(attrs.get(\"beta\", 0.0))\n        return (alpha * inputs[0]) + beta\n\n\nclass Reshape(OneFlowOpConverter):\n    \"\"\"Operator converter for Reshape.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.reshape(inputs[0], attrs[\"shape\"])\n\n\nclass Softmax(OneFlowOpConverter):\n    \"\"\"Operator converter for Softmax.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        axis = attrs.get(\"axis\", -1)\n        data = inputs[0]\n        if isinstance(axis, str):\n            axis = int(axis)\n\n        return _op.nn.softmax(data, axis=axis)\n\n\nclass LogSoftmax(OneFlowOpConverter):\n    \"\"\"Operator converter for LogSoftmax.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        axis = attrs.get(\"axis\", 1)\n        ndim = len(infer_shape(inputs[0]))\n        if axis < 0:\n            axis += ndim\n        axes = list(range(axis, ndim))\n        x = inputs[0]\n        m = _op.max(x, axes, keepdims=True)\n        e = _op.exp(x - m)\n        s = _op.sum(e, axes, keepdims=True)\n        return x - m - _op.log(s)\n\n\nclass Dropout(OneFlowOpConverter):\n    \"\"\"Operator converter for Dropout.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        out = AttrCvt(\"dropout\", {\"ratio\": \"rate\"}, ignores=[\"is_test\"])\n        return out\n\n\nclass ThresholdedRelu(OneFlowOpConverter):\n    \"\"\"Operator converter for ThresholdedRelu.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        alpha = float(attrs.get(\"alpha\", 1.0))\n        alpha_tensor = _op.full_like(inputs[0], fill_value=_expr.const(alpha))\n        mask = _op.greater(inputs[0], alpha_tensor).astype(\"float32\")\n        return inputs[0] * mask\n\n\nclass Elu(OneFlowOpConverter):\n    \"\"\"Operator converter for Elu\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        alpha = float(attrs.get(\"alpha\", 1.0))\n        return _expr.const(-alpha) * _op.nn.relu(\n            _expr.const(1.0) - _op.exp(inputs[0])\n        ) + _op.nn.relu(inputs[0])\n\n\nclass PReLU(OneFlowOpConverter):\n    \"\"\"Operator converter for PReLU\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        assert len(inputs) == 2, \"PReLU need 2 inputs, but {} given\".format(len(inputs))\n        for i in inputs:\n            if \"_input.\" in str(i):\n                prelu_a = i\n            else:\n                prelu_b = i\n\n        input_shape = shape_of(prelu_a)\n        alpha = _op.broadcast_to_like(prelu_b, prelu_a)\n        alpha = _op.reshape(alpha, [-1])\n\n        output = _op.nn.prelu(_op.reshape(prelu_a, [-1]), alpha, axis=0)\n        out = _op.reshape(output, input_shape)\n        return out\n\n\nclass Selu(OneFlowOpConverter):\n    \"\"\"Operator converter for Selu\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        alpha = float(attrs.get(\"alpha\", 1.67326319217681884765625))\n        gamma = float(attrs.get(\"gamma\", 1.05070102214813232421875))\n        return _expr.const(gamma) * (\n            _expr.const(-alpha) * _op.nn.relu(_expr.const(1.0) - _op.exp(inputs[0]))\n            + _op.nn.relu(inputs[0])\n        )\n\n\nclass Silu(OneFlowOpConverter):\n    \"\"\"Operator converter for Silu\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        a = inputs[0]\n        b = _op.sigmoid(inputs[0])\n        return _op.multiply(a, b)\n\n\nclass Gelu(OneFlowOpConverter):\n    \"\"\"Operator converter for Gelu\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        data = inputs[0]\n        return data * (\n            _expr.const(0.5) + _op.erf(data * _expr.const(0.5**0.5)) * _expr.const(0.5)\n        )\n\n\nclass HardTanh(OneFlowOpConverter):\n    \"\"\"Operator converter for HardTanh\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        tanh_min = attrs.get(\"min_val\", 0.0)\n        tanh_max = attrs.get(\"max_val\", 0.0)\n        return _op.tensor.clip(inputs[0], tanh_min, tanh_max)\n\n\nclass Softplus(OneFlowOpConverter):\n    \"\"\"Operator converter for Softplus\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        data = inputs[0]\n        data_dtype = infer_type(data).checked_type.dtype\n        data = _op.exp(data) + _expr.const(1, dtype=data_dtype)\n        return _op.log(data)\n\n\nclass Softsign(OneFlowOpConverter):\n    \"\"\"Operator converter for Softsign\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return inputs[0] / (_expr.const(1.0) + Absolute.get_converter()(inputs, attrs, params))\n\n\nclass Variance(OneFlowOpConverter):\n    \"\"\"Operator converter for Variance\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        axis = attrs[\"dim\"]\n        keepdims = attrs[\"keepdim\"]\n        unbiased = bool(attrs[\"unbiased\"])\n        return _op.reduce.variance(inputs[0], axis=axis, keepdims=keepdims, unbiased=unbiased)\n\n\nclass Concat(OneFlowOpConverter):\n    \"\"\"Operator converter for Concat\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        attrs.pop(\"max_dim_size\")\n        inputs = _dtype_shape_promotion(inputs)\n        return _op.concatenate(inputs, axis=attrs[\"axis\"])\n\n\nclass Clip(OneFlowOpConverter):\n    \"\"\"Operator converter for Clip\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        attr = {}\n        dtype = infer_type(inputs[0])\n\n        if \"float\" in str(dtype):\n            attr[\"a_min\"] = attrs[\"floating_min\"]\n            attr[\"a_max\"] = attrs[\"floating_max\"]\n        elif \"int\" in str(dtype):\n            attr[\"a_min\"] = attrs[\"integral_min\"]\n            attr[\"a_max\"] = attrs[\"integral_max\"]\n        else:\n            attr[\"a_min\"] = -np.inf\n            attr[\"a_max\"] = np.inf\n\n        out = AttrCvt(\"clip\")(inputs, attr, params)\n        return out\n\n\nclass Slice(OneFlowOpConverter):\n    \"\"\"Operator converter for Slice\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        starts = list(attrs[\"start\"])\n        ends = list(attrs[\"stop\"])\n        steps = list(attrs[\"step\"])\n        return _op.strided_slice(inputs[0], starts, ends, steps)\n\n\nclass Split(OneFlowOpConverter):\n    \"\"\"Operator converter for Split\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        splits = attrs.get(\"split\", None)\n        if splits is not None:\n            indices = []\n            attrs[\"indices_or_sections\"] = []\n            index = 0\n            for i in splits[:-1]:\n                index += i\n                indices.append(index)\n        output = _op.split(inputs[0], indices, attrs.get(\"axis\", 0))\n        # If the output of split is a single value, unpack if from the TupleWrapper\n        if len(output) == 1:\n            output = output[0]\n        return output\n\n\nclass Scatter(OneFlowOpConverter):\n    \"\"\"Operator converter for Scatter\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        axis = attrs.get(\"axis\", 0)\n        return _op.scatter(inputs[0], inputs[1], inputs[2], axis)\n\n\nclass Unsqueeze(OneFlowOpConverter):\n    \"\"\"Operator converter for Unsqueeze\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        axes = sorted(attrs[\"axes\"])\n        for axis in axes:\n            inputs[0] = _op.expand_dims(inputs[0], axis=axis, num_newaxis=1)\n        return inputs[0]\n\n\nclass Sign(OneFlowOpConverter):\n    \"\"\"Operator converter for Sign\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.sign(inputs[0])\n\n\nclass Reciprocal(OneFlowOpConverter):\n    \"\"\"Operator converter for Reciprocal\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        dtype = infer_type(inputs[0]).checked_type.dtype\n        return _expr.const(1.0, dtype=dtype) / inputs[0]\n\n\nclass Erf(OneFlowOpConverter):\n    \"\"\"Operator converter for Erf\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _op.erf(inputs[0])\n\n\nclass Erfc(OneFlowOpConverter):\n    \"\"\"Operator converter for Erfs\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        return _expr.const(1.0) - _op.erf(inputs[0])\n\n\nclass HardSigmoid(OneFlowOpConverter):\n    \"\"\"Operator converter for HardSigmoid\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        alpha = attrs.get(\"alpha\", 0.2)\n        beta = attrs.get(\"beta\", 0.5)\n        transformX = (inputs[0] * _expr.const(alpha)) + _expr.const(beta)\n        attr = {\"a_min\": 0, \"a_max\": 1}\n        return AttrCvt(\"clip\")([transformX], attr)\n\n\nclass OneHot(OneFlowOpConverter):\n    \"\"\"Operator converter for OneHot\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        # Extract relay one_hot inputs.\n        indices, depth, values = inputs\n        ndim = len(infer_shape(indices))\n        # Split onnx on off values into two separate expressions.\n        off_value, on_value = _op.take(values, _op.const(0)), _op.take(values, _op.const(1))\n        # Extract the datatype of the output from on_value.\n        dtype = infer_type(on_value).checked_type.dtype\n        ind_dtype = infer_type(indices).checked_type.dtype\n        # Normalize the indices to a positive range\n        indices = _op.where(\n            indices < _op.const(0, ind_dtype), indices + _op.cast(depth, ind_dtype), indices\n        )\n        # set default value when axis is not set in the model\n        axis = attrs.get(\"axis\", -1)\n        if axis < 0:\n            axis += ndim + 1\n\n        return _op.one_hot(indices, on_value, off_value, depth, axis, dtype=dtype)\n\n\nclass Where(OneFlowOpConverter):\n    \"\"\"Operator converter for Where\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        condition_rank = len(infer_shape(inputs[0]))\n        x_rank = len(infer_shape(inputs[1]))\n        y_rank = len(infer_shape(inputs[2]))\n        ranks = [condition_rank, x_rank, y_rank]\n\n        # If one rank is longer than others, then we can broadcast\n        # to that shape.\n        max_rank = max(ranks)\n        max_rank_idxs = [i for i, x in enumerate(ranks) if x == max_rank]\n        broadcast_shape = shape_of(inputs[max_rank_idxs[0]])\n        # If two or more inputs have the same rank, compute the broadcast\n        # shape by taking the maximum value of each dimensions.\n        if len(max_rank_idxs) > 1:\n            for idx in max_rank_idxs:\n                broadcast_shape = _op.maximum(broadcast_shape, shape_of(inputs[idx]))\n\n        broadcast_shape = fold_constant(broadcast_shape)\n\n        condition = _op.broadcast_to(inputs[0], broadcast_shape)\n        x = _op.broadcast_to(inputs[1], broadcast_shape)\n        y = _op.broadcast_to(inputs[2], broadcast_shape)\n        return _op.where(condition, x, y)\n\n\nclass Constant(OneFlowOpConverter):\n    \"\"\"Operator converter for Constant\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        is_float = attrs.get(\"is_floating_value\", True)\n        shape = attrs.get(\"shape\", (1,))\n        if is_float:\n            dtype = \"float32\"\n            value = attrs.pop(\"floating_value\")\n        else:\n            dtype = \"int8\"\n            value = attrs.pop(\"integer_value\")\n        np_array = np.zeros(shape)\n        np_array.fill(value)\n        value = _expr.const(np_array, dtype)\n        return value\n\n\nclass Range(OneFlowOpConverter):\n    \"\"\"Operator converter for Range\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        if len(inputs) != 0:\n            raise ValueError(\"Expect no inputs but get {}\".format(len(inputs)))\n        start = attrs.get(\"start\", 0.0)\n        limit = attrs.get(\"limit\", 1.0)\n        delta = attrs.get(\"delta\", 1.0)\n        return _op.arange(\n            _expr.const(start, dtype=\"float32\"),\n            _expr.const(limit, dtype=\"float32\"),\n            _expr.const(delta, dtype=\"float32\"),\n        )\n\n\nclass Cast(OneFlowOpConverter):\n    \"\"\"Operator converter for Cast\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attrs, params):\n        attrs[\"dtype\"] = infer_type(inputs[0]).checked_type.dtype\n        return AttrCvt(op_name=\"cast\")(inputs, attrs)\n\n\ndef get_convert_map():\n    # supported oneflow2relay op\n    return {\n        # defs/math\n        \"bias_add\": Add.get_converter(),\n        \"scalar_add\": ScalarAdd.get_converter(),\n        \"scalar_mul\": ScalarMul.get_converter(),\n        \"scalar_div\": ScalarDiv.get_converter(),\n        \"scalar_pow\": ScalarPow.get_converter(),\n        \"reduce_sum\": ReduceSum.get_converter(),\n        \"reduce_max\": ReduceMax.get_converter(),\n        \"reduce_min\": ReduceMin.get_converter(),\n        \"reduce_mean\": ReduceMean.get_converter(),\n        \"broadcast_add\": BroadcastAdd.get_converter(),\n        \"broadcast_mul\": BroadcastMul.get_converter(),\n        \"broadcast_sub\": BroadcastSub.get_converter(),\n        \"broadcast_div\": BroadcastDiv.get_converter(),\n        \"scalar_logical_greater\": LogicalGreater.get_converter(),\n        \"log\": Renamer(\"log\"),\n        \"log1p\": Log1p.get_converter(),\n        \"acos\": Renamer(\"acos\"),\n        \"acosh\": Renamer(\"acosh\"),\n        \"asin\": Renamer(\"asin\"),\n        \"asinh\": Renamer(\"asinh\"),\n        \"atan\": Renamer(\"atan\"),\n        \"atanh\": Renamer(\"atanh\"),\n        \"cos\": Renamer(\"cos\"),\n        \"cosh\": Renamer(\"cosh\"),\n        \"sin\": Renamer(\"sin\"),\n        \"sinh\": Renamer(\"sinh\"),\n        \"tan\": Renamer(\"tan\"),\n        \"tanh\": Renamer(\"tanh\"),\n        \"pow\": Pow.get_converter(),\n        \"exp\": Renamer(\"exp\"),\n        \"expm1\": Expm1.get_converter(),\n        \"floor\": Renamer(\"floor\"),\n        \"ceil\": Renamer(\"ceil\"),\n        \"round\": Renamer(\"round\"),\n        \"add_n\": AddN.get_converter(),\n        \"sqrt\": Renamer(\"sqrt\"),\n        \"rsqrt\": Renamer(\"rsqrt\"),\n        \"square\": Square.get_converter(),\n        \"sign\": Sign.get_converter(),\n        \"erf\": Erf.get_converter(),\n        \"erfc\": Erfc.get_converter(),\n        \"reciprocal\": Reciprocal.get_converter(),\n        # defs/activation\n        \"softmax\": Softmax.get_converter(),\n        \"softsign\": Softsign.get_converter(),\n        \"hardtanh\": HardTanh.get_converter(),\n        \"relu\": Renamer(\"relu\"),\n        \"leaky_relu\": Renamer(\"leaky_relu\"),\n        \"prelu\": PReLU.get_converter(),\n        \"selu\": Selu.get_converter(),\n        \"silu\": Silu.get_converter(),\n        \"gelu\": Gelu.get_converter(),\n        # defs/nn\n        \"conv2d\": Conv2d.get_converter(),\n        \"deconv2d\": ConvTranspose2d.get_converter(),\n        \"maxpool_2d\": MaxPool2d.get_converter(),\n        \"avgpool_2d\": AveragePool2d.get_converter(),\n        \"adaptive_avg_pool2d\": AdaptiveAvgPool2d.get_converter(),\n        \"adaptive_max_pool2d\": AdaptiveMaxPool2d.get_converter(),\n        \"dropout\": Dropout.get_converter(),\n        \"normalization\": BatchNorm.get_converter(),\n        \"upsample_nearest_2d\": UpsampleNearest.get_converter(),\n        \"upsample_bilinear_2d\": UpsampleBiLinear.get_converter(),\n        # defs/tensor\n        \"matmul\": MatMul.get_converter(),\n        \"batch_matmul\": MatMul.get_converter(),\n        \"broadcast_matmul\": MatMul.get_converter(),\n        \"concat\": Concat.get_converter(),\n        \"clip_by_scalar\": Clip.get_converter(),\n        \"slice\": Slice.get_converter(),\n        \"expand\": Expand.get_converter(),\n        \"transpose\": Transpose.get_converter(),\n        \"expand_dims\": ExpandDim.get_converter(),\n        \"range\": Range.get_converter(),\n        \"cast\": Cast.get_converter(),\n        # defs/others\n        \"reshape\": Reshape.get_converter(),\n        \"constant\": Constant.get_converter(),\n        \"where\": Where.get_converter(),\n        \"flatten\": Flatten.get_converter(),\n        \"sigmoid\": Renamer(\"sigmoid\"),\n        \"sigmoid_v2\": Renamer(\"sigmoid\"),\n        \"hardsigmoid\": HardSigmoid.get_converter(),\n        \"softplus\": Softplus.get_converter(),\n        \"squeeze\": AttrCvt(\"squeeze\", {\"axes\": \"axis\"}),\n        \"unsqueeze\": Unsqueeze.get_converter(),\n        \"identity\": Renamer(\"copy\"),\n        \"var\": Variance.get_converter(),\n    }\n\n\nclass oneflow_input(object):\n    \"\"\"\n    Dual purpose list or dictionary access object\n    \"\"\"\n\n    def __init__(self):\n        self.input_keys = []\n        self.input_dict = {}\n        self.n = 0\n\n    def __getitem__(self, item):\n        if isinstance(item, int):\n            if item > (len(self.input_keys) - 1):\n                return None\n            return self.input_dict[self.input_keys[item]]\n        if isinstance(item, str):\n            if item not in self.input_keys:\n                return None\n            return self.input_dict[item]\n        if isinstance(item, slice):\n            keys = self.input_keys[item]\n            return [self.input_dict[key] for key in keys]\n\n        raise ValueError(\"Only integer, string, and slice accesses allowed.\")\n\n    def __setitem__(self, item, value):\n        if isinstance(item, int):\n            self.input_dict[self.input_keys[item]] = value\n        elif isinstance(item, str):\n            self.input_keys.append(item)\n            self.input_dict[item] = value\n        else:\n            raise ValueError(\"Only integer and string indexed writes allowed.\")\n\n    def keys(self):\n        return self.input_keys\n\n    def __len__(self):\n        return len(self.input_keys)\n\n    def __iter__(self):\n        self.n = 0\n        return self\n\n    def __next__(self):\n        if self.n < len(self.input_keys):\n            output = self.input_dict[self.input_keys[self.n]]\n            self.n += 1\n            return output\n\n        raise StopIteration\n\n\ndef deal_with_input_convert(\n    node_input, node_input_shape, node_input_dtype, node_path, _nodes, _input_path_2_name\n):\n    \"\"\"deal with input convert in oneflow.\"\"\"\n    if node_input not in _nodes:\n        if (\n            node_path not in _input_path_2_name\n            or \"_input.\" in node_input\n            or \"FreeEagerTensor\" in node_input\n        ):\n            _nodes[node_input] = new_var(\n                node_input,\n                shape=node_input_shape,\n                dtype=node_input_dtype,\n            )\n        else:\n            names = _input_path_2_name[node_path]\n            node_replace = None\n            for k in names:\n                if k in _nodes:\n                    node_replace = k\n            if node_replace is not None:\n                op_replace = copy.deepcopy(_nodes[node_replace])\n                _nodes[node_input] = op_replace\n            else:\n                print(\"{} will not be in _nodes\".format(node_input))\n\n\ndef deal_parameter_convert(\n    node_input_paths, model_dir_path, _input_path_2_name, _model_array, _params, _nodes\n):\n    \"\"\"deal with parameter(weight) convert in oneflow.\"\"\"\n    for node_input_path in node_input_paths:\n        node_path = os.path.join(model_dir_path, node_input_path.replace(\"m.\", \"\", 1))\n        node_input_name = node_input_path.split(\"/\")[0]\n        _input_path_2_name[node_path] = node_input_name\n        for param_name in _model_array:\n            node_p = _model_array[param_name]\n            if node_path == node_p[\"path\"]:\n                node_array = node_p[\"params\"]\n                _params[node_input_name] = node_array\n                _nodes[node_input_name] = new_var(\n                    node_input_name, shape=node_array.shape, dtype=str(node_array.dtype)\n                )\n                break\n\n\nclass OneflowGraph(object):\n    \"\"\"\n    A helper class for handling Relay expression\n\n    Parameters\n    ----------\n    shape : dict of str to tuple, optional\n        The input shape to the graph\n    dtype : dict of str to str\n        The input types to the graph\n\n    node name:\n    1. param: m.layer4.1.bn1.weight / ...\n    2. buffer: m.layer4.1.bn1.running_mean / ...\n    3. node inputs: m.layer4.1.bn1_input.0\n    4. node outputs: m.layer4.1.bn1_output.0\n    \"\"\"\n\n    def __init__(self, shape, dtype, nodes, model_dir_path):\n        self._nodes = {}\n        self._params = {}\n        self._inputs = {}\n        self._num_input = 0\n        self._num_param = 0\n        self._input_names = []\n        self._model_array = {}\n        self._input_path_2_name = {}\n        self._output_path_2_name = {}\n        self._init_variable_node = []\n        self._shape = shape\n        self._dtype = dtype\n        self._identity_list = []\n        self._sort_inputs = {}\n\n        import oneflow\n\n        model = oneflow.load(model_dir_path)\n        # model_array: keys: layer_name, values: dict('path', 'params')\n        for layer_name in model:\n            layer = model[layer_name]\n            layer_node = {}\n            layer_node[\"path\"] = os.path.join(model_dir_path, layer_name, \"out\")  # get path\n            if \"System-Train\" in layer_name:\n                continue\n            node_name = \"m.\" + layer_name\n            shape = self._shape[node_name]\n            dtype = self._dtype[node_name]\n            array = layer.detach().cpu().numpy()\n            layer_node[\"params\"] = array.reshape(shape)\n            self._model_array[layer_name] = layer_node\n\n        for node_name in nodes:\n            node = nodes[node_name]\n            if is_user_op(node):\n                for input_name in node.user_conf.input:\n                    node_input_paths = getattr(node.user_conf.input[input_name], \"s\")\n                    deal_parameter_convert(\n                        node_input_paths,\n                        model_dir_path,\n                        self._input_path_2_name,\n                        self._model_array,\n                        self._params,\n                        self._nodes,\n                    )\n                for output_name in node.user_conf.output:\n                    node_output_paths = getattr(node.user_conf.output[output_name], \"s\")\n                    for node_output_path in node_output_paths:\n                        node_path = os.path.join(model_dir_path, node_output_path.replace(\"m.\", \"\"))\n                        node_output_name = node_output_path.split(\"/\")[0]\n                        self._output_path_2_name[node_path] = node_output_name\n            elif is_output_op(node):\n                node_output_path = getattr(node.output_conf, \"in\")\n                output_path = os.path.join(\n                    model_dir_path, getattr(node.output_conf, \"in\").replace(\"m.\", \"\")\n                )\n                self._output_path_2_name[output_path] = node_name\n            elif is_param_op(node):\n                if \"FreeEagerTensor\" in node.name:\n                    shape = tuple(node.variable_conf.shape.dim)\n                    dtype = FLOW_2_STR_DTYPE[node.variable_conf.data_type]\n                    self._shape[node.name] = shape\n                    self._dtype[node.name] = dtype\n                    self._init_variable_node.append(node.name)\n        if self._init_variable_node != []:\n            print(\"{} should be defined by user\".format(self._init_variable_node))\n\n    def _parse_input(self, node, model_dir_path):\n        input_user_conf_list = []\n        for input_name in node.user_conf.input:\n            input_user_conf_list.append(input_name)\n        input_user_conf_list.sort()\n        for input_name in input_user_conf_list:\n            node_input_paths = getattr(node.user_conf.input[input_name], \"s\")\n            for i in node_input_paths:\n                node_input = i.split(\"/\")[0]\n                node_input_shape = self._shape[node_input]\n                node_input_dtype = self._dtype[node_input]\n                node_path = os.path.join(model_dir_path, i.replace(\"m.\", \"\"))\n                deal_with_input_convert(\n                    node_input,\n                    node_input_shape,\n                    node_input_dtype,\n                    node_path,\n                    self._nodes,\n                    self._input_path_2_name,\n                )\n\n    def _parse_output(self, op_name, outputs, cnt_init=0):\n        \"\"\"\n        o: m.classifier.1_output.xxx\n        new_o: m.classifier.1-conv2d_0\n        \"_\"+new_o_xxx is in self._shape\n        \"\"\"\n        for o in outputs:\n            if \"_output.\" not in o:\n                new_o = o.replace(\"-\" + op_name, \"_output\")\n                new_o = new_o.replace(\"-\" + new_o.split(\"-\")[-1], \".0\")\n                for k in self._shape.keys():\n                    if new_o in k:\n                        self._shape[o] = self._shape[k]\n                        self._dtype[o] = self._dtype[k]\n                        break\n            elif len(outputs) > 1:\n                outputs.remove(o)\n        if op_name.lower() == \"dropout\":\n            if len(outputs) == 1:\n                return outputs\n            outputs = outputs[:-1]\n        elif op_name.lower() == \"constant\":\n            outputs = [self._init_variable_node[cnt_init]]\n\n        if len(outputs) > 1:\n            outputs = list(set(outputs))\n\n        return outputs\n\n    def from_oneflow(self, nodes, model_dir_path):\n        \"\"\"\n        Implementation of convert the OneFlow model into an equivalent Relay Function.\n        \"\"\"\n        # step 1: find out if unsupported ops are used\n        convert_map = get_convert_map()\n        unsupported_ops = set()\n        for node_name in nodes:\n            node = nodes[node_name]\n            if is_user_op(node):\n                # op names, not the layer names\n                op_name = node.user_conf.op_type_name\n                if (\n                    op_name not in convert_map\n                    and \"constant\" not in op_name\n                    and op_name not in self._identity_list\n                ):\n                    unsupported_ops.add(op_name)\n        # find out the unsupported op\n        if unsupported_ops:\n            msg = \"The following operators are not supported for frontend OneFlow: \"\n            msg += \", \".join(unsupported_ops)\n            raise tvm.error.OpNotImplemented(msg)\n\n        # step 2: convert op\n        for node_name in nodes:\n            node = nodes[node_name]\n            if is_user_op(node):\n                # If there is a user-defined node, skip the following steps\n                if node_name in self._inputs:\n                    continue\n\n                op_name = node.user_conf.op_type_name\n                op_attr = parse_attr(node.user_conf.attr)\n\n                self._parse_input(node, model_dir_path=model_dir_path)\n\n                node_inputs = oneflow_input()\n                input_user_conf_list = []\n                for input_name in node.user_conf.input:\n                    input_user_conf_list.append(input_name)\n                input_user_conf_list.sort()\n                for input_name in input_user_conf_list:\n                    node_input_paths = getattr(node.user_conf.input[input_name], \"s\")\n                    for i in node_input_paths:\n                        node_input = i.split(\"/\")[0]\n                        node_inputs[node_input] = self._nodes[node_input]\n\n                node_outputs = []\n                for output_name in node.user_conf.output:\n                    node_output_paths = getattr(node.user_conf.output[output_name], \"s\")\n                    for i in node_output_paths:\n                        node_output_path = os.path.join(model_dir_path, i.replace(\"m.\", \"\"))\n                        if node_output_path in self._input_path_2_name:\n                            node_outputs.append(self._input_path_2_name[node_output_path])\n                        elif node_output_path in self._output_path_2_name:\n                            node_outputs.append(self._output_path_2_name[node_output_path])\n                node_outputs = self._parse_output(op_name, node_outputs)\n\n                # convert\n                op = self._convert_operator(op_name, node_inputs, op_attr)\n\n                if not isinstance(op, _expr.TupleWrapper):\n                    outputs_num = 1\n                else:\n                    outputs_num = len(op)\n\n                assert (\n                    len(node_outputs) == outputs_num\n                ), \"Number of output mismatch {} vs {} in {}.\".format(\n                    len(node_outputs), outputs_num, op_name\n                )\n                if outputs_num == 1:\n                    op = fold_constant(op)\n                else:\n                    op = _expr.TupleWrapper(fold_constant(op.astuple()), len(op))\n\n                op_temp = []\n                op_temp.append(op)\n                for i, _ in enumerate(node_outputs):\n                    if isinstance(node_outputs[i], list):\n                        for k in node_outputs[i]:\n                            self._nodes[k] = op_temp[i]\n                    else:\n                        self._nodes[node_outputs[i]] = op_temp[i]\n\n        # step 3: get the outputs\n        outputs = []\n        for node_name, node in nodes.items():\n            if is_output_op(node):\n                node_name_v2 = getattr(node.output_conf, \"in\").split(\"/\")[0]\n                if node_name in self._nodes:\n                    outputs.append(self._nodes[node_name])\n                elif node_name_v2 in self._nodes:\n                    outputs.append(self._nodes[node_name_v2])\n        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n\n        # step 4: get the relay IR\n        free_vars = analysis.free_vars(outputs)\n\n        nodes = {v: k for k, v in self._nodes.items()}\n        free_vars = [nodes[var] for var in free_vars]\n        free_vars_inputs = []\n        free_vars_parameters = []\n        for x in free_vars:\n            if \"_input.0\" in x:\n                free_vars_inputs.append(x)\n            else:\n                free_vars_parameters.append(x)\n        free_vars = free_vars_inputs + free_vars_parameters\n\n        # step 5: make sure the '_input.0' is the first in self._inputs\n        for free_var in free_vars:\n            if free_var not in self._inputs:\n                self._inputs[free_var] = self._nodes[free_var]\n\n        input_names = list(self._inputs.keys())\n        for input_name in input_names:\n            if input_name in self._inputs:\n                self._sort_inputs[input_name] = self._inputs[input_name]\n            else:\n                raise IndexError(\"{} is not in self._inputs\".format(input_name))\n\n        # step 6: create a function from our output expression and all input variables.\n        func = _function.Function([v for _, v in self._sort_inputs.items()], outputs)\n\n        return IRModule.from_expr(func), self._params\n\n    def _convert_operator(self, op_name, node_inputs, op_attr):\n        \"\"\"\n        Parameters\n        ----------\n        op_name : str\n            Operator name, such as conv2d and relu\n        node_inputs : list of tvm.relay.function.Function\n            List of inputs.\n        op_attr : dict\n            Dict of operator attributes\n\n        Returns\n        -------\n        sym : tvm.relay.function.Function\n            Converted relay function\n        \"\"\"\n        convert_map = get_convert_map()\n        if op_name in self._identity_list:\n            sym = get_relay_op(op_name)(*node_inputs, **op_attr)\n        elif op_name in convert_map:\n            sym = convert_map[op_name](node_inputs, op_attr, self._params)\n        else:\n            raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n\n        return sym\n\n\ndef from_oneflow(graph, model_dir_path):\n    \"\"\"Convert a OneFlow model into an equivalent Relay Function.\n\n    At present, there are two ways to run models in deep learning framework\n    Dynamic Graph and Static Graph, which are also called Eager Mode and Graph\n    Mode in OneFlow.\n\n    In general, dynamic graphs are easier to use and static graphs have better performance.\n    OneFlow offers nn.Graph, so that users can use the eager-like programming style to build\n    static graphs and train the models.\n\n    We utilize the intermediate representation of nn.Graph to convert the OneFlow model to Reley.\n\n    Parameters\n    ----------\n    nodes : dict, keys: node.name, value: node\n        contain the graph\n    model_dir_path: str\n        The path of weight\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The returned relay module\n    params : dict\n        A dict of name: tvm.nd.array pairs, used as pretrained weights\n    \"\"\"\n    try:\n        import oneflow as flow\n    except ImportError:\n        raise ImportError(\"please check that OneFlow is installed\")\n\n    # get info of nodes\n    shape = {}\n    dtype = {}\n    graph_str = repr(graph)\n    size_where = 2\n    if \"cuda\" in graph_str:\n        size_where = 3\n\n    p_size = re.compile(r\"size=\\(.*?\\)\", re.S)\n    p_type = re.compile(r\"dtype=.*?\\)\", re.S)\n    types = [\"INPUT\", \"PARAMETER\", \"BUFFER\", \"OUTPUT\"]\n    for t in types:\n        data = re.finditer(t + \":.*\", graph_str)\n        for i in data:\n            attrs = i.group().split(\":\")\n            size_str = re.findall(p_size, attrs[size_where])\n            type_str = re.findall(p_type, attrs[size_where])\n            assert size_str != [], \"size should not be None, please check your repr(graph)\"\n\n            size_attr = size_str[0].replace(\"size=\", \"\")\n            if size_attr[-2] == \",\":\n                size_attr = size_attr.replace(\",\", \"\")\n            data_size = tuple(map(int, size_attr[1:-1].split(\", \")))\n            node_name = attrs[1]\n            shape[node_name] = data_size\n            dtype[node_name] = \"float32\"\n\n            if type_str != []:\n                type_attr = type_str[0].replace(\"dtype=\", \"\").replace(\")\", \"\")\n                if type_attr[-1] == \",\":\n                    type_attr = type_attr.replace(\",\", \"\")\n                dtype[node_name] = type_attr.replace(\"oneflow.\", \"\")\n\n    # get graph proto, if you don't _compile the graph, the _graph_proto will be None\n    graph_input = re.search(r\"INPUT:.*\", graph_str).group().split(\":\")\n    shape_input = tuple(\n        map(\n            int,\n            re.findall(p_size, graph_input[size_where])[0].replace(\"size=\", \"\")[1:-1].split(\", \"),\n        )\n    )\n    if not graph._is_compiled:\n        graph._compile(flow.rand(shape_input))\n    graph_proto = graph._graph_proto\n\n    # get all nodes\n    nodes = OrderedDict()\n    for op in graph_proto.net.op:\n        nodes[op.name] = op\n\n    g = OneflowGraph(shape, dtype, nodes, model_dir_path)\n\n    # Use the graph proto as a scope so that ops can access other nodes if needed.\n    mod, params = g.from_oneflow(nodes=nodes, model_dir_path=model_dir_path)\n\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, unused-argument, too-many-lines\n# pylint: disable=import-outside-toplevel\n\"\"\"ONNX: Open Neural Network Exchange frontend for Relay.\"\"\"\nimport copy\nimport math\nimport warnings\nfrom typing import Optional\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import loops as _loops\nfrom .. import op as _op\nfrom .. import qnn as _qnn\nfrom .. import random as _random\nfrom .. import ty as _ty\nfrom .. import vision as _vision\nfrom .common import (\n    AttrCvt,\n    Renamer,\n    autopad,\n    ensure_scalar_shape,\n    fold_constant,\n    get_name,\n    get_relay_op,\n    gru_cell,\n    infer_channels,\n    infer_shape,\n    infer_type,\n    infer_value,\n    lstm_cell,\n    new_var,\n    rnn_cell,\n    shape_of,\n    try_resolve_var_to_const,\n    unbind,\n)\n\n__all__ = [\"from_onnx\"]\n\n# The default configurations of Relay ONNX frontend.\nONNX_DEFAULT_CONFIGS = {\n    # By default, TVM converts qualified onnx `matmul` to `transpose(weight) + nn.batch_matmul_NT`.\n    # Change this flag to False to directly convert to `nn.batch_matmul`.\n    # Note that `nn.batch_matmul` with format other than NT is in experimental, it may have some\n    # performance issues.\n    \"use_nt_batch_matmul\": True,\n}\n\n\nclass onnx_input(list):\n    \"\"\"A helper extension to list that returns None for out of bound indices.\"\"\"\n\n    def __getitem__(self, item):\n        if isinstance(item, slice):\n            if item.stop is None:\n                stop = len(self)\n            else:\n                stop = item.stop\n            indices = list(range(stop)[item])\n            return [self[i] for i in indices]\n        if isinstance(item, int):\n            return list(self)[item] if item < len(self) else None\n        raise TypeError(\"list indices must be integers or slices, not %s\" % type(item).__name__)\n\n\ndef get_numpy(tensor_proto):\n    \"\"\"Grab data in TensorProto and convert to numpy array.\"\"\"\n    try:\n        from onnx.numpy_helper import to_array\n    except ImportError as e:\n        raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n    return to_array(tensor_proto)\n\n\ndef get_type(elem_type):\n    \"\"\"Converts onnx integer datatype to numpy datatype\"\"\"\n    # If a string was passed instead of a tensor type, it does not need\n    # conversion and can be returned.\n    if isinstance(elem_type, str):\n        return elem_type\n\n    try:\n        from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE\n    except ImportError as e:\n        raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n\n    try:\n        from onnx import TensorProto\n    except ImportError as e:\n        raise ImportError(\"Unable to import TensorProto from onnx {}\".format(e))\n\n    # Onnx mapping converts bfloat16 to float16 because\n    # numpy does not have a bfloat16 data type. However,\n    # tvm has one, so we force the return type to be bfloat16\n    if elem_type == int(TensorProto.BFLOAT16):\n        return \"bfloat16\"\n    return str(TENSOR_TYPE_TO_NP_TYPE[elem_type])\n\n\ndef get_info(info_proto):\n    \"\"\"Extract the shape from a ValueInfoProto.\"\"\"\n    shape = []\n    shape_name = []\n    for dim in info_proto.type.tensor_type.shape.dim:\n        name = dim.dim_param\n        value = dim.dim_value\n        if value is None or value == 0:\n            value = _ty.Any()\n            shape_name.append(name)\n        else:\n            shape_name.append(value)\n        shape.append(value)\n\n    name = info_proto.name\n    if info_proto.type.tensor_type.elem_type:\n        dtype = get_type(info_proto.type.tensor_type.elem_type)\n    else:\n        dtype = None\n    return name, shape, dtype, shape_name\n\n\ndef dimension_picker(prefix, suffix=\"\"):\n    \"\"\"Check that dimensions are supported.\"\"\"\n\n    def _impl(attr):\n        kernel = attr[\"kernel_shape\"]\n        if len(kernel) == 1:\n            return prefix + \"1d\" + suffix\n        if len(kernel) == 2:\n            return prefix + \"2d\" + suffix\n        if len(kernel) == 3:\n            return prefix + \"3d\" + suffix\n        msg = \"Only 1D, 2D, and 3D kernels are supported for operator {}.\"\n        op_name = prefix + \"1d/2d/3d\"\n        raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n    return _impl\n\n\ndef revert_caffe2_pad(pads):\n    \"\"\"Caffe2 requires two times the normal padding.\"\"\"\n    if len(pads) == 4:\n        pads = pads[:2]\n    elif len(pads) == 2:\n        pass\n    else:\n        raise tvm.error.OpAttributeInvalid(\"Number of pads must be either 2 or 4.\")\n    return pads\n\n\ndef get_pad_pair(input1d, kernel1d, stride1d, mode):\n    \"\"\"infer pad size\"\"\"\n    if input1d % stride1d == 0:\n        pad = max(kernel1d - stride1d, 0)\n    else:\n        pad = max(kernel1d - (input1d % stride1d), 0)\n    pad_before = pad // 2\n    pad_after = pad - pad_before\n    if \"LOWER\" in mode:\n        return [pad_after, pad_before]\n    return [pad_before, pad_after]\n\n\ndef onnx_default_layout(dims, op_name):\n    if dims == 1:\n        return \"NCW\"\n    if dims == 2:\n        return \"NCHW\"\n    if dims == 3:\n        return \"NCDHW\"\n\n    msg = \"Only 1D, 2D and 3D layouts are currently supported for operator {}.\"\n    raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n\ndef onnx_storage_order2layout(storage_order, dims, op_name):\n    \"\"\"converter of onnx storage order parameter to tvm storage order format\"\"\"\n    if storage_order not in (0, 1):\n        raise tvm.error.OpAttributeInvalid(\"Mode of storage_order must be either 0 or 1\")\n\n    if dims == 1:\n        return \"NCW\" if storage_order == 0 else \"NWC\"\n    if dims == 2:\n        return \"NCHW\" if storage_order == 0 else \"NHWC\"\n    if dims == 3:\n        return \"NCDHW\" if storage_order == 0 else \"NDHWC\"\n\n    msg = \"Only 1D, 2D and 3D layouts are currently supported for operator {}.\"\n    raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n\ndef dimension_constraint():\n    def _dim_check(attrs):\n        if len(attrs[\"kernel_shape\"]) in [1, 2, 3]:\n            return True\n        return False\n\n    return _dim_check, \"Only 1d, 2d and 3d kernel supported.\"\n\n\ndef get_scalar(x, params, dtype=\"float32\"):\n    \"\"\"Helper to get a scalar value for Quantized operators.\"\"\"\n    if isinstance(x, _expr.Var) and x.name_hint in params:\n        return _op.const(params[x.name_hint].numpy(), dtype)\n    rank = len(infer_shape(x))\n    assert rank <= 1, \"scale and zero_point input must be scalars\"\n    if rank == 1:\n        x = _op.squeeze(x, [0])\n    return _op.cast(x, dtype)\n\n\ndef get_scalar_or_1d_tensor(x, params, dtype=\"float32\"):\n    \"\"\"Helper to get a scalar value or 1D tensor for Quantized operators.\"\"\"\n    if isinstance(x, _expr.Var) and x.name_hint in params:\n        return _op.const(params[x.name_hint].numpy(), dtype)\n    rank = len(infer_shape(x))\n    assert rank <= 1, \"scale and zero_point input must be scalars or 1D tensors\"\n    return _op.cast(x, dtype)\n\n\ndef flatten_to_nd(x, x_shape, nd=3):\n    \"\"\"Flatten input tensor to nd rank\"\"\"\n    ndims = infer_shape(x_shape)[0]\n    if ndims == nd:\n        return x\n    newshape = _op.concatenate(\n        [\n            _expr.const([-1], dtype=infer_type(x_shape).checked_type.dtype),\n            _op.strided_slice(x_shape, [ndims - nd + 1], [ndims]),\n        ],\n        0,\n    )\n    out = _op.reshape(x, fold_constant(newshape))\n    return out\n\n\ndef matmul_out_dtype(inputs, out_dtype):\n    \"\"\"Common function to handle MatMul and MatMulInteger16\"\"\"\n    a_shape = shape_of(inputs[0])\n    a_rank = infer_shape(a_shape)[0]\n    b_shape = shape_of(inputs[1])\n    b_rank = infer_shape(b_shape)[0]\n    if a_rank > 2 or b_rank > 2:\n        # Determine the output batch dimension.\n        new_a_shape = a_shape\n        new_b_shape = b_shape\n        if a_rank > b_rank:\n            rank_diff = a_rank - b_rank\n            new_b_shape = _op.concatenate(\n                [\n                    _expr.const([1] * rank_diff, dtype=infer_type(b_shape).checked_type.dtype),\n                    b_shape,\n                ],\n                0,\n            )\n        elif a_rank < b_rank:\n            rank_diff = b_rank - a_rank\n            new_a_shape = _op.concatenate(\n                [\n                    _expr.const([1] * rank_diff, dtype=infer_type(a_shape).checked_type.dtype),\n                    a_shape,\n                ],\n                0,\n            )\n        else:\n            pass\n\n        out_batch = _op.concatenate(\n            [\n                _op.maximum(\n                    _op.strided_slice(new_b_shape, [i], [i + 1]),\n                    _op.strided_slice(new_a_shape, [i], [i + 1]),\n                )\n                for i in range(max(a_rank, b_rank) - 2)\n            ],\n            0,\n        )\n\n        b_type = infer_type(inputs[1])\n        # Convert to dense if the second matrix is 2d and non-dynamic\n        if b_rank == 2 and not _ty.is_dynamic(b_type.checked_type):\n            a = flatten_to_nd(inputs[0], a_shape, 2)\n            b = _op.transpose(inputs[1])\n            output = _op.nn.dense(a, b, out_dtype=out_dtype)\n        else:\n            a = inputs[0]\n            b = inputs[1]\n            # broadcast a and b\n            a_broadcasted_shape = fold_constant(\n                _op.concatenate(\n                    [\n                        out_batch,\n                        _op.strided_slice(a_shape, [a_rank - 2], [a_rank]),\n                    ],\n                    0,\n                )\n            )\n            b_broadcasted_shape = fold_constant(\n                _op.concatenate(\n                    [\n                        out_batch,\n                        _op.strided_slice(b_shape, [b_rank - 2], [b_rank]),\n                    ],\n                    0,\n                )\n            )\n            if not tvm.ir.structural_equal(a_shape, a_broadcasted_shape):\n                a = _op.transform.broadcast_to(a, a_broadcasted_shape)\n            if not tvm.ir.structural_equal(b_shape, b_broadcasted_shape):\n                b = _op.transform.broadcast_to(b, b_broadcasted_shape)\n            # Convert a and b into 3 dimensional tensors.\n            a = flatten_to_nd(a, shape_of(a), 3)\n            b = flatten_to_nd(b, shape_of(b), 3)\n            if ONNX_DEFAULT_CONFIGS[\"use_nt_batch_matmul\"]:\n                # Transpose matrix dimensions of b.\n                bt = _op.transpose(b, [0, 2, 1])\n                # Perform a NT batch matmul.\n                output = _op.nn.batch_matmul(a, bt, out_dtype=out_dtype)\n            else:\n                # Perform a NN batch matmul.\n                output = _op.nn.batch_matmul(a, b, out_dtype=out_dtype, transpose_b=False)\n        # Reshape output to original dimensions.\n        final_shape = _op.concatenate(\n            [\n                out_batch,\n                _op.strided_slice(\n                    a_shape, [infer_shape(a_shape)[0] - 2], [infer_shape(a_shape)[0] - 1]\n                ),\n                _op.strided_slice(\n                    b_shape, [infer_shape(b_shape)[0] - 1], [infer_shape(b_shape)[0]]\n                ),\n            ],\n            0,\n        )\n        return _op.reshape(output, fold_constant(final_shape))\n\n    if a_rank == 1:\n        return _op.squeeze(_op.nn.matmul(_op.expand_dims(inputs[0], axis=0), inputs[1]), axis=[0])\n\n    # Otherwise a simple dense op will get the job done.\n    input_1_t = _op.transpose(inputs[1], axes=(1, 0))\n    return _op.nn.dense(inputs[0], input_1_t, out_dtype=out_dtype)\n\n\ndef qmatmul(\n    a,\n    b,\n    a_zp_scalar,\n    b_zp_scalar,\n    a_scale_scalar,\n    b_scale_scalar,\n    transform_num_hidden_units,\n    matmul_result_dtype,\n):\n    \"\"\"\n    Helper function to handle QLinearMatMul\n    It is very close to 'matmul_out_dtype' but separated due to\n    differences in signatures of dense, matmul, batch_matmul of nn and qnn.\n    They requre scaling and zero point arguments\n    \"\"\"\n    a_shape = shape_of(a)\n    a_rank = infer_shape(a_shape)[0]\n    b_shape = shape_of(b)\n    b_rank = infer_shape(b_shape)[0]\n    if a_rank > 2 or b_rank > 2:\n        # Determine the output batch dimension.\n        new_a_shape = a_shape\n        new_b_shape = b_shape\n        if a_rank > b_rank:\n            rank_diff = a_rank - b_rank\n            new_b_shape = _op.concatenate(\n                [\n                    _expr.const([1] * rank_diff, dtype=infer_type(b_shape).checked_type.dtype),\n                    b_shape,\n                ],\n                0,\n            )\n        elif a_rank < b_rank:\n            rank_diff = b_rank - a_rank\n            new_a_shape = _op.concatenate(\n                [\n                    _expr.const([1] * rank_diff, dtype=infer_type(a_shape).checked_type.dtype),\n                    a_shape,\n                ],\n                0,\n            )\n        else:\n            pass\n\n        out_batch = _op.concatenate(\n            [\n                _op.maximum(\n                    _op.strided_slice(new_b_shape, [i], [i + 1]),\n                    _op.strided_slice(new_a_shape, [i], [i + 1]),\n                )\n                for i in range(max(a_rank, b_rank) - 2)\n            ],\n            0,\n        )\n\n        b_type = infer_type(b)\n        # Convert to dense if the second matrix is 2d and non-dynamic\n        if b_rank == 2 and not _ty.is_dynamic(b_type.checked_type):\n            a = flatten_to_nd(a, a_shape, 2)\n            b = _op.transpose(b)\n            output = _qnn.op.dense(\n                a,\n                b,\n                a_zp_scalar,\n                b_zp_scalar,\n                a_scale_scalar,\n                b_scale_scalar,\n                transform_num_hidden_units,\n                matmul_result_dtype,\n            )\n        else:\n            # broadcast a and b\n            a_broadcasted_shape = fold_constant(\n                _op.concatenate(\n                    [\n                        out_batch,\n                        _op.strided_slice(a_shape, [a_rank - 2], [a_rank]),\n                    ],\n                    0,\n                )\n            )\n            b_broadcasted_shape = fold_constant(\n                _op.concatenate(\n                    [\n                        out_batch,\n                        _op.strided_slice(b_shape, [b_rank - 2], [b_rank]),\n                    ],\n                    0,\n                )\n            )\n            if not tvm.ir.structural_equal(a_shape, a_broadcasted_shape):\n                a = _op.transform.broadcast_to(a, a_broadcasted_shape)\n            if not tvm.ir.structural_equal(b_shape, b_broadcasted_shape):\n                b = _op.transform.broadcast_to(b, b_broadcasted_shape)\n            # Convert a and b into 3 dimensional tensors.\n            a = flatten_to_nd(a, shape_of(a), 3)\n            b = flatten_to_nd(b, shape_of(b), 3)\n            # Transpose matrix dimensions of b.\n            bt = _op.transpose(b, [0, 2, 1])\n            # Perform a NT batch matmul.\n            output = _qnn.op.batch_matmul(\n                a,\n                bt,\n                a_zp_scalar,\n                b_zp_scalar,\n                a_scale_scalar,\n                b_scale_scalar,\n                matmul_result_dtype,\n            )\n        # Reshape output to original dimensions.\n        final_shape = _op.concatenate(\n            [\n                out_batch,\n                _op.strided_slice(a_shape, [a_rank - 2], [a_rank - 1]),\n                _op.strided_slice(b_shape, [b_rank - 1], [b_rank]),\n            ],\n            0,\n        )\n        return _op.reshape(output, fold_constant(final_shape))\n\n    if a_rank == 1:\n        # TODO(vvchernov): There should be qnn.matmul but it is not implemented\n        # return _op.squeeze(_qnn.op.matmul(_op.expand_dims(a, axis=0),\n        #                                   b,\n        #                                   a_zp_scalar,\n        #                                   b_zp_scalar,\n        #                                   a_scale_scalar,\n        #                                   b_scale_scalar,\n        #                                   transform_num_hidden_units,\n        #                                   matmul_result_dtype,\n        #                                  ),\n        #                    axis=[0]\n        #                   )\n        return _op.squeeze(\n            _qnn.op.dense(\n                _op.expand_dims(a, axis=0),\n                _op.transpose(b),\n                a_zp_scalar,\n                b_zp_scalar,\n                a_scale_scalar,\n                b_scale_scalar,\n                transform_num_hidden_units,\n                matmul_result_dtype,\n            ),\n            axis=[0],\n        )\n\n    # Otherwise a simple dense op will get the job done.\n    return _qnn.op.dense(\n        a,\n        _op.transpose(b),\n        a_zp_scalar,\n        b_zp_scalar,\n        a_scale_scalar,\n        b_scale_scalar,\n        transform_num_hidden_units,\n        matmul_result_dtype,\n    )\n\n\ndef layer_norm(x, eps, gamma, beta):\n    \"\"\"A common function to handle layer norm.\n\n    Use LayerNormalization for the actual onnx op.\n    \"\"\"\n    eps_dtype = infer_type(x).checked_type.dtype\n    u, s = _op.mean_variance(x, axis=-1, keepdims=True)\n    output = _op.divide(\n        _op.subtract(x, u),\n        _op.sqrt(_op.add(s, _op.const(eps, dtype=eps_dtype))),\n    )\n    output = _op.multiply(output, gamma)\n    if beta is not None:\n        output = _op.add(output, beta)\n\n    return output\n\n\nclass OnnxOpConverter(object):\n    \"\"\"A helper class for holding onnx op converters.\"\"\"\n\n    @classmethod\n    def get_converter(cls, opset):\n        \"\"\"Get converter matches given opset.\n\n        Parameters\n        ----------\n        opset: int\n            opset from model.\n\n        Returns\n        -------\n        converter, which should be `_impl_vx`. Number x is the biggest\n            number smaller than or equal to opset belongs to all support versions.\n        \"\"\"\n        versions = [int(d.replace(\"_impl_v\", \"\")) for d in dir(cls) if \"_impl_v\" in d]\n        versions = sorted(versions + [opset])\n        version = versions[max([i for i, v in enumerate(versions) if v == opset]) - 1]\n        if hasattr(cls, \"_impl_v{}\".format(version)):\n            return getattr(cls, \"_impl_v{}\".format(version))\n        raise NotImplementedError(\n            \"opset version {} of {} not implemented\".format(version, cls.__name__)\n        )\n\n\nclass Unary(OnnxOpConverter):\n    \"\"\"A helper class for unary op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 1, \"Unary math op {} takes 1 input, {} given\".format(\n            cls.name, len(inputs)\n        )\n        op_name = cls.name\n        return get_relay_op(op_name)(*inputs)\n\n\nclass Elemwise(OnnxOpConverter):\n    \"\"\"A helper class for elemwise op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"Math op {} take 2 inputs, {} given\".format(cls.name, len(inputs))\n        op_name = cls.name\n        conv_ops = [\"conv2d\", \"conv2d_transpose\"]\n        if attr.get(\"broadcast\", 0) and any(x in str(inputs[0]) for x in conv_ops):\n            # TODO(zhreshold): remove hard coded infershape\n            axis = int(attr.get(\"axis\", 0))\n            inputs[1] = _op.expand_dims(inputs[1], axis=axis, num_newaxis=2)\n        return get_relay_op(op_name)(*inputs)\n\n\nclass Pool(OnnxOpConverter):\n    \"\"\"A helper class for pool op converters.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        ndim = len(input_shape)\n\n        attr_cvt, data = cls._run_calculation(inputs, attr, params)\n        out = attr_cvt([data], attr, params)\n\n        if ndim - len(attr[\"kernel_shape\"]) == 1:\n            out = _op.squeeze(out, axis=[0])\n        return out\n\n    @classmethod\n    def _run_calculation(cls, inputs, attr, params):\n        \"\"\"Helper method to return the processed input data and AttrCvt object\"\"\"\n\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        input_dtype = infer_type(data).checked_type.dtype\n        ndim = len(input_shape)\n        if \"auto_pad\" in attr:\n            attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                if cls.name == \"avg_pool\":\n                    pad_tuple = []\n                    for axis in range(len(input_shape) - 2):\n                        axis_shape = input_shape[2 + axis]\n                        stride = attr.get(\"strides\", [1] * ndim)[axis]\n                        kernel = attr[\"kernel_shape\"][axis]\n                        pad = get_pad_pair(axis_shape, kernel, stride, attr[\"auto_pad\"])\n                        pad_tuple.append(pad)\n                    pad_tuple = tuple([val for pair in zip(*pad_tuple) for val in pair])\n                    attr[\"pads\"] = pad_tuple\n                else:\n                    # Warning: Pool does not yet support dynamic shapes,\n                    # one will need to run dynamic_to_static on this model after import\n                    if \"int\" in input_dtype:\n                        pad_val = np.iinfo(np.dtype(input_dtype)).min\n                    else:\n                        pad_val = np.finfo(np.dtype(input_dtype)).min\n                    data = autopad(\n                        data,\n                        attr.get(\"strides\", [1] * (ndim - 2)),\n                        attr[\"kernel_shape\"],\n                        [1] * ndim,\n                        pad_value=pad_val,\n                        mode=attr[\"auto_pad\"],\n                    )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator {} is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"], cls.name))\n            attr.pop(\"auto_pad\")\n\n        if \"storage_order\" in attr:\n            attr[\"layout\"] = onnx_storage_order2layout(\n                attr[\"storage_order\"], dims=(len(input_shape) - 2), op_name=cls.name\n            )\n        else:\n            if ndim - len(attr[\"kernel_shape\"]) == 1:\n                data = _op.expand_dims(data, axis=0)\n                input_shape = [1] + list(input_shape)\n\n            attr[\"layout\"] = onnx_default_layout(dims=(len(input_shape) - 2), op_name=cls.name)\n\n        return (\n            AttrCvt(\n                op_name=dimension_picker(cls.name),\n                transforms={\n                    \"kernel_shape\": \"pool_size\",\n                    \"pads\": (\"padding\", 0),\n                    \"dilations\": (\"dilation\", 1),\n                },\n                ignores=[\"storage_order\"],\n                custom_check=dimension_constraint(),\n            ),\n            data,\n        )\n\n\nclass Absolute(Unary):\n    \"\"\"Operator converter for Absolute.\"\"\"\n\n    name = \"abs\"\n\n\nclass Add(Elemwise):\n    \"\"\"Operator converter for Add.\"\"\"\n\n    name = \"add\"\n\n\nclass AveragePool(Pool):\n    \"\"\"Operator converter for AveragePool.\"\"\"\n\n    name = \"avg_pool\"\n\n\nclass QLinearAveragePool(Pool):\n    \"\"\"Operator converter for QLinearAveragePool from Microsoft onnxruntime contrib opset.\"\"\"\n\n    name = \"avg_pool\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        x_scale = get_scalar(inputs[1], params)\n        x_zero_point = get_scalar(inputs[2], params, dtype=\"int32\")\n        y_scale = fold_constant(get_scalar(inputs[3], params))\n        y_zero_point = get_scalar(inputs[4], params, dtype=\"int32\")\n\n        attr_cvt, data = cls._run_calculation(inputs, attr, params)\n\n        input_dtype = infer_type(data).checked_type.dtype\n        # Onnxruntime doesn't actually do this op in integer, they dequantize to fp32\n        # and then requantize afer (according to documentation below)\n        # https://github.com/microsoft/onnxruntime/blob/master/docs/ContribOperators.md#com.microsoft.QLinearAveragePool\n        float_node = _qnn.op.dequantize(data, x_scale, x_zero_point)\n        out = attr_cvt([float_node], attr, params)\n        return _qnn.op.quantize(out, y_scale, y_zero_point, out_dtype=input_dtype)\n\n\nclass BatchNorm(OnnxOpConverter):\n    \"\"\"Operator converter for BatchNorm.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # TODO(zhreshold): 'spatial' is not properly handled here.\n        # TODO(vvchernov): 'training_mode' (onnx tag) is not correctly handled, ignore for now\n        out = AttrCvt(\n            op_name=\"batch_norm\",\n            ignores=[\"spatial\", \"is_test\", \"consumed_inputs\", \"momentum\", \"training_mode\"],\n        )(inputs, attr, params)\n        # We only support test mode, so we return data, moving_mean, moving_var,\n        # and then moving_mean and moving_var again as placeholders for\n        # the expected \"saved_mean\", \"saved_var\".\n        return _expr.TupleWrapper(_expr.Tuple((*out, out[1], out[2])), 5)\n\n\nclass InstanceNorm(OnnxOpConverter):\n    \"\"\"Operator converter for BatchNorm.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return AttrCvt(op_name=\"instance_norm\")(inputs, attr, params)\n\n\nclass Conv(OnnxOpConverter):\n    \"\"\"Operator converter for Conv.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # Use shape of input to determine convolution type.\n        data = inputs[0]\n        kernel = inputs[1]\n        input_shape = infer_shape(data)\n        ndim = len(input_shape)\n\n        kernel_type = infer_type(inputs[1])\n        kernel_shapes = [get_const_tuple(kernel_type.checked_type.shape)]\n\n        if \"kernel_shape\" not in attr:\n            attr[\"kernel_shape\"] = kernel_shapes[0][2:]\n\n        if \"auto_pad\" in attr:\n            attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: Convolution does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                data = autopad(\n                    data,\n                    attr.get(\"strides\", [1] * (ndim - 2)),\n                    attr[\"kernel_shape\"],\n                    attr.get(\"dilations\", [1] * (ndim - 2)),\n                    mode=attr[\"auto_pad\"],\n                )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = [0 for i in range(ndim - 2)]\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n            attr.pop(\"auto_pad\")\n\n        attr[\"channels\"] = kernel_shapes[0][0]\n        out = AttrCvt(\n            op_name=dimension_picker(\"conv\"),\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"dilations\": (\"dilation\", 1),\n                \"pads\": (\"padding\", 0),\n                \"group\": (\"groups\", 1),\n            },\n            custom_check=dimension_constraint(),\n        )([data, kernel], attr, params)\n\n        use_bias = len(inputs) == 3\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[2])\n        return out\n\n\nclass ConvTranspose(OnnxOpConverter):\n    \"\"\"Operator converter for ConvTranspose.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # get number of channels\n        out_type = infer_type(inputs[1])\n        kernel_shape = [get_const_tuple(out_type.checked_type.shape)]\n        out_channels = kernel_shape[0][1] * attr.get(\"group\", 1)\n        attr[\"channels\"] = out_channels\n        groups = attr.get(\"group\", 1)\n\n        if \"kernel_shape\" not in attr:\n            attr[\"kernel_shape\"] = kernel_shape[0][2:]\n\n        attr[\"groups\"] = groups\n        # infer pads for auto_pad\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        ndim = len(input_shape)\n        if \"auto_pad\" in attr or \"output_shape\" in attr:\n            if \"auto_pad\" in attr:\n                attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if \"output_shape\" in attr or attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: Convolution does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                kernel_shape = attr[\"kernel_shape\"]\n                kndim = len(kernel_shape)\n                dilations = attr.get(\"dilations\", [1] * kndim)\n                output_padding = attr.get(\"output_padding\", [0] * kndim)\n                strides = attr[\"strides\"]\n                total_pad = [0] * kndim\n                # https://github.com/onnx/onnx/blob/main/docs/Operators.md#ConvTranspose\n                if \"output_shape\" in attr:\n                    for i in range(kndim):\n                        total_pad[i] = (\n                            strides[i] * (input_shape[ndim - kndim + i] - 1)\n                            + output_padding[i]\n                            + ((kernel_shape[i] - 1) * dilations[i] + 1)\n                            - attr[\"output_shape\"][i]\n                        )\n                    left = [p // 2 for p in total_pad]\n                    right = [total_pad[i] - left[i] for i in range(kndim)]\n                    if \"output_shape\" in attr and \"auto_pad\" not in attr:\n                        pad = right + left\n                    elif \"LOWER\" in attr[\"auto_pad\"]:\n                        pad = left + right\n                    else:\n                        pad = right + left\n                    attr[\"pads\"] = pad\n                else:\n                    data = autopad(\n                        data,\n                        attr.get(\"strides\", [1] * (ndim - 2)),\n                        attr[\"kernel_shape\"],\n                        attr.get(\"dilations\", [1] * (ndim - 2)),\n                        deconv=True,\n                        mode=attr[\"auto_pad\"],\n                    )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n            if \"auto_pad\" in attr:\n                attr.pop(\"auto_pad\")\n\n        out = AttrCvt(\n            op_name=dimension_picker(\"conv\", \"_transpose\"),\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"dilations\": (\"dilation\", 1),\n                \"pads\": (\"padding\", 0),\n                \"group\": (\"groups\", 1),\n            },\n            disables=[\"output_shape\"],\n            custom_check=dimension_constraint(),\n        )([data, inputs[1]], attr, params)\n        use_bias = len(inputs) == 3\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[2])\n        return out\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        # get number of channels\n        out_type = infer_type(inputs[1])\n        kernel_shape = [get_const_tuple(out_type.checked_type.shape)]\n        out_channels = kernel_shape[0][1] * attr.get(\"group\", 1)\n        attr[\"channels\"] = out_channels\n        groups = attr.get(\"group\", 1)\n\n        if \"kernel_shape\" not in attr:\n            attr[\"kernel_shape\"] = kernel_shape[0][2:]\n\n        attr[\"groups\"] = groups\n        # infer pads for auto_pad\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        ndim = len(input_shape)\n        if \"auto_pad\" in attr or \"output_shape\" in attr:\n            if \"auto_pad\" in attr:\n                attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if \"output_shape\" in attr or attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: Convolution does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                kernel_shape = attr[\"kernel_shape\"]\n                kndim = len(kernel_shape)\n                dilations = attr.get(\"dilations\", [1] * kndim)\n                output_padding = attr.get(\"output_padding\", [0] * kndim)\n                strides = attr[\"strides\"]\n                total_pad = [0] * kndim\n                # https://github.com/onnx/onnx/blob/main/docs/Operators.md#ConvTranspose\n                if \"output_shape\" in attr:\n                    for i in range(kndim):\n                        total_pad[i] = (\n                            strides[i] * (input_shape[ndim - kndim + i] - 1)\n                            + output_padding[i]\n                            + ((kernel_shape[i] - 1) * dilations[i] + 1)\n                            - attr[\"output_shape\"][i]\n                        )\n                else:\n                    for i in range(kndim):\n                        total_pad[i] = (\n                            output_padding[i]\n                            + ((kernel_shape[i] - 1) * dilations[i] + 1)\n                            - strides[i]\n                        )\n                left = [p // 2 for p in total_pad]\n                right = [total_pad[i] - left[i] for i in range(kndim)]\n                if \"output_shape\" in attr and \"auto_pad\" not in attr:\n                    pad = right + left\n                elif \"LOWER\" in attr[\"auto_pad\"]:\n                    pad = left + right\n                else:\n                    pad = right + left\n                attr[\"pads\"] = pad\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n            if \"auto_pad\" in attr:\n                attr.pop(\"auto_pad\")\n\n        out = AttrCvt(\n            op_name=dimension_picker(\"conv\", \"_transpose\"),\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"dilations\": (\"dilation\", 1),\n                \"pads\": (\"padding\", 0),\n                \"group\": (\"groups\", 1),\n            },\n            disables=[\"output_shape\"],\n            custom_check=dimension_constraint(),\n        )([data, inputs[1]], attr, params)\n        use_bias = len(inputs) == 3\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[2])\n        return out\n\n\nclass GlobalAveragePool(OnnxOpConverter):\n    \"\"\"Operator converter for GlobalAveragePool\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        rank = len(infer_shape(inputs[0]))\n        if rank == 3:\n            return _op.nn.global_avg_pool1d(inputs[0])\n        if rank == 4:\n            return _op.nn.global_avg_pool2d(inputs[0])\n        if rank == 5:\n            return _op.nn.global_avg_pool3d(inputs[0])\n        raise NotImplementedError(\n            \"Global average pooling is only implemented for 1D, 2D, and 3D kernels, got %dD.\"\n            % (rank - 2),\n        )\n\n\nclass QLinearGlobalAveragePool(OnnxOpConverter):\n    \"Operator converter for QLinearGlobalAveragePool from Microsoft onnxruntime contrib opset.\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        rank = len(infer_shape(inputs[0]))\n\n        x_scale = get_scalar(inputs[1], params)\n        x_zero_point = get_scalar(inputs[2], params, dtype=\"int32\")\n        y_scale = fold_constant(get_scalar(inputs[3], params))\n        y_zero_point = get_scalar(inputs[4], params, dtype=\"int32\")\n\n        input_dtype = infer_type(inputs[0]).checked_type.dtype\n\n        # Onnxruntime documentation does not mention that this global avg_pool should follow the\n        # sequence dequantize -> float op -> quantize, but that is how QLinearAveragePool is done.\n        #\n        # This op also follows the same pattern since qnn op is not available right now.\n        # TODO: Generate QNN op to perform quantized operation instead of dequant -> op -> quant\n        x = _qnn.op.dequantize(inputs[0], x_scale, x_zero_point)\n        if rank == 3:\n            out = _op.nn.global_avg_pool1d(x)\n        elif rank == 4:\n            out = _op.nn.global_avg_pool2d(x)\n        elif rank == 5:\n            out = _op.nn.global_avg_pool3d(x)\n        else:\n            raise NotImplementedError(\n                \"Global average pooling is only implemented for 1D, 2D, and 3D kernels, got %dD.\"\n                % (rank - 2),\n            )\n        return _qnn.op.quantize(out, y_scale, y_zero_point, out_dtype=input_dtype)\n\n\nclass GlobalMaxPool(OnnxOpConverter):\n    \"\"\"Operator converter for GlobalMaxPool\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        rank = len(infer_shape(inputs[0]))\n        if rank == 3:\n            return _op.nn.global_max_pool1d(inputs[0])\n        if rank == 4:\n            return _op.nn.global_max_pool2d(inputs[0])\n        if rank == 5:\n            return _op.nn.global_max_pool3d(inputs[0])\n        raise NotImplementedError(\n            \"Global max pooling is only implemented for 1D, 2D, and 3D kernels, got %dD.\"\n            % (rank - 2),\n        )\n\n\nclass Div(Elemwise):\n    \"\"\"Operator converter for Divide.\"\"\"\n\n    name = \"divide\"\n\n\nclass Elu(OnnxOpConverter):\n    \"\"\"Operator converter for Elu.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = float(attr.get(\"alpha\", 1.0))\n        return _expr.const(-alpha) * _op.nn.relu(\n            _expr.const(1.0) - _op.exp(inputs[0])\n        ) + _op.nn.relu(inputs[0])\n\n\nclass Gelu(OnnxOpConverter):\n    \"\"\"Operator converter for Gelu from Microsoft onnxruntime contrib opset.\n\n    gelu(x) = 0.5x(1 + erf(x/sqrt(2)))\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        x = inputs[0]\n\n        # Declare consts\n        const_dtype = infer_type(x).checked_type.dtype\n        half = _expr.const(0.5, dtype=const_dtype)\n        one = _expr.const(1.0, dtype=const_dtype)\n        sqrt2 = _expr.const(math.sqrt(2), dtype=const_dtype)\n\n        # Compute gelu\n        term1 = _op.multiply(half, x)\n        erf = _op.erf(_op.divide(x, sqrt2))\n        term2 = _op.add(one, erf)\n        return _op.multiply(term1, term2)\n\n\nclass FastGelu(OnnxOpConverter):\n    \"\"\"Operator converter for FastGelu from Microsoft onnxruntime contrib opset.\n\n    fast_gelu(x) = 0.5x(1 + tanh(sqrt(2/pi)(x + 0.044715x^3)))\n                 = 0.5x(1 + tanh((sqrt(2/pi)x + 0.044715(sqrt(2/pi)x^3)))\n                 = 0.5x(1 + tanh(c1 * x + c2 * x^3)))\n    , where\n        c1 = sqrt(2/pi)\n        c2 = 0.044715 * sqrt(2/pi)\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        x = inputs[0]\n        if inputs[1]:\n            bias = inputs[1]\n            bias_shape = infer_shape(bias)\n            assert len(bias_shape) == 1, \"bias term must be a 1D tensor\"\n            x += bias\n\n        # Declare consts\n        const_dtype = infer_type(x).checked_type.dtype\n        half = _expr.const(0.5, dtype=const_dtype)\n        one = _expr.const(1.0, dtype=const_dtype)\n        const1 = _expr.const(math.sqrt(2 / math.pi), dtype=const_dtype)\n        const2 = _expr.const(0.044715 * math.sqrt(2 / math.pi), dtype=const_dtype)\n\n        # Compute FastGelu\n        term1 = _op.multiply(half, x)\n        term2 = _op.multiply(const1, x)\n        term3 = _op.multiply(const2, _op.power(x, _expr.const(3, const_dtype)))\n        tanh = _op.tanh(_op.add(term2, term3))\n        return _op.multiply(term1, _op.add(one, tanh))\n\n\nclass BiasGelu(OnnxOpConverter):\n    \"\"\"Operator converter for BiasGelu from Microsoft onnxruntime contrib opset.\n\n    bias_gelu(x, b) = 0.5(x + b)(1 + erf((x + b)/sqrt(2)))\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        x = inputs[0]\n        b = inputs[1]\n\n        b_shape = infer_shape(b)\n        assert len(b_shape) == 1, \"BiasGelu bias term must be a 1D tensor\"\n\n        inp = _op.add(x, b)\n        return Gelu._impl_v1([inp], attr, params)\n\n\nclass LayerNormalization(OnnxOpConverter):\n    \"\"\"Operator converter for LayerNormalization from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v17(cls, inputs, attr, params):\n        x = inputs[0]\n        gamma = inputs[1]\n        beta = inputs[2]\n        axis = attr.get(\"axis\", -1)\n        eps = attr.get(\"epsilon\", 1e-5)\n        # according to the onnx doc, given the int axis (default -1)\n        # to compute the mean and inv_stdev which are of dim [d[0], ..., d[axis-1], 1, ..., 1]\n        # the actual computation is over (axis, ..., rank(x) - 1) axes\n        # see https://github.com/onnx/onnx/blob/main/docs/Changelog.md#layernormalization-17\n        rank = len(infer_shape(x))\n        axis = tuple(range(axis, rank)) if axis >= 0 else tuple(range(rank + axis, rank))\n        dtype = infer_type(x).checked_type.dtype\n        mean = _op.mean(x, axis, keepdims=True)\n        var = _op.variance(x, axis, keepdims=True, with_mean=mean)\n        inv_stdev = _op.divide(\n            _op.const(1, dtype=dtype), _op.sqrt(_op.add(var, _op.const(eps, dtype=dtype)))\n        )\n        x_norm = _op.multiply(_op.subtract(x, mean), inv_stdev)\n        ln = _op.multiply(x_norm, gamma)\n        if beta is not None:\n            ln = _op.add(ln, beta)\n\n        return _expr.TupleWrapper(_expr.Tuple([ln, mean, inv_stdev]), 3)\n\n\nclass EmbedLayerNormalization(OnnxOpConverter):\n    \"\"\"Operator converter for EmbedLayerNormalization from Microsoft onnxruntime contrib opset.\n\n    This layer embeds the input tokens, sums them, and applies layer normalization.\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        input_ids = inputs[0]\n        segment_ids = inputs[1]\n        word_emb = inputs[2]\n        pos_emb = inputs[3]\n        segment_emb = inputs[4]\n        gamma = inputs[5]\n        beta = inputs[6]\n\n        mask = inputs[7]\n        pos_ids = inputs[8]\n\n        eps = attr.get(\"epsilon\", 1e-12)\n\n        (batch_size, seq_len) = infer_shape(input_ids)\n\n        if segment_ids:\n            assert segment_emb\n\n        if pos_ids is None:\n            pos_ids = _op.const([list(range(seq_len))] * batch_size, dtype=\"int32\")\n\n        word_vec = _op.take(word_emb, input_ids, axis=0)\n        segment_vec = _op.take(segment_emb, segment_ids, axis=0)\n        pos_vec = _op.take(pos_emb, pos_ids, axis=0)\n\n        vec_sum = _op.add(word_vec, pos_vec)\n        if segment_ids:\n            vec_sum = _op.add(vec_sum, segment_vec)\n\n        ln = layer_norm(vec_sum, eps, gamma, beta)\n\n        mask_index = _op.const(np.zeros((batch_size,), dtype=\"int32\"))\n        if mask:\n            # calculate number of words per sentence\n            mask_index = _op.sum(mask, axis=1)\n\n        # TODO(@anwang2009): onnxruntime v1.10.0 requires a third output of vec_sum\n        return _expr.TupleWrapper(_expr.Tuple([ln, mask_index]), 2)\n\n\nclass SkipLayerNormalization(OnnxOpConverter):\n    \"\"\"Operator converter for SkipLayerNormalization from Microsoft onnxruntime contrib opset.\n\n    This layer sums the two input tensors (along with optional bias), and applies layer\n    normalization.\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        skip = inputs[1]\n        gamma = inputs[2]\n        beta = inputs[3]\n        bias = inputs[4]\n\n        assert (\n            beta is not None and bias is not None\n        ), \"SkipLayerNormalization import currently only supports required beta and bias\"\n\n        eps = attr.get(\"epsilon\", 1e-12)\n\n        x = _op.add(data, skip)\n        if bias is not None:\n            x = _op.add(x, bias)\n\n        output = layer_norm(x, eps, gamma, beta)\n\n        # onnxruntime doesn't compute the other outputs, despite the documentation\n        placeholder = _op.const(0, dtype=\"float32\")\n\n        return _expr.TupleWrapper(_expr.Tuple([output, placeholder, placeholder]), 3)\n\n\nclass Attention(OnnxOpConverter):\n    \"\"\"Operator converter for Attention from Microsoft onnxruntime contrib opset.\n\n    This is the self-attention mechanism used in transformer models.\n    \"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        num_heads = attr[\"num_heads\"]\n        assert (\n            \"qkv_hidden_sizes\" not in attr\n        ), \"different hidden sizes for Q, K, V are not currently supported\"\n        assert \"unidirectional\" not in attr, \"unidirectional attention not current supported\"\n\n        # (batch, seq, in_hidden)\n        input_emb = inputs[0]\n\n        # (in_hidden, 3 * out_hidden), where out_hidden = num_heads * head_size\n        weight = inputs[1]\n\n        # (3 * out_hidden,)\n        bias = inputs[2]\n\n        # 1. (    batch,              1,        max_seq, max_seq)\n        # 2. (    batch, past_seq + seq,)\n        # 3. (    batch,            seq, past_seq + seq,)\n        # 4. (    batch,)\n        # 5. (2 * batch,)\n        # For now, we only support case 2.\n        mask_index = inputs[3]\n\n        # (2, batch, num_heads, past_seq, head_size)\n        past = inputs[4]\n\n        # (batch, num_heads, seq, seq)\n        extra_add = inputs[5]\n\n        (batch_size, seq_len, _) = infer_shape(input_emb)\n        (out_hidden_x3,) = infer_shape(bias)\n        assert out_hidden_x3 % 3 == 0, \"bias shape should be divisible by 3\"\n        out_hidden = out_hidden_x3 // 3\n        assert (\n            out_hidden % num_heads == 0\n        ), \"output hidden size should be divisible by number of attention heads\"\n        head_size = out_hidden // num_heads\n\n        assert (\n            mask_index is not None\n        ), \"Attention import currently only supports required mask_index\"\n        mask_index_shape = infer_shape(mask_index)\n        assert (\n            len(mask_index_shape) == 2\n            and mask_index_shape[0] == batch_size\n            and mask_index_shape[1] == seq_len\n        ), \"currently only support (batch_size, sequence_length) mask index\"\n\n        assert past is None, \"past K, V state is not currently supported\"\n        assert extra_add is None, \"extra add to QxK not currently supported\"\n\n        # split weight and biases and do the matmuls\n        w_Q, w_K, w_V = _op.split(weight, 3, axis=1)\n        b_Q, b_K, b_V = _op.split(bias, 3, axis=0)\n        # need to merge batch dimensions since TVM matmul is 2D\n        input_emb = _op.reverse_reshape(input_emb, (-1, 0))\n        Q = _op.add(_op.nn.matmul(input_emb, w_Q), b_Q)\n        K = _op.add(_op.nn.matmul(input_emb, w_K), b_K)\n        V = _op.add(_op.nn.matmul(input_emb, w_V), b_V)\n\n        # massage tensors in preparation for batched matmul\n        def massage(tensor):\n            tensor = _op.reshape(tensor, (batch_size, seq_len, num_heads, head_size))\n\n            # (batch_size, num_heads, seq_len, head_size)\n            tensor = _op.transpose(tensor, axes=[0, 2, 1, 3])\n\n            # (batch_size * num_heads, seq_len, head_size)\n            return _op.reverse_reshape(tensor, (-1, 0, 0))\n\n        Q = massage(Q)\n        K = massage(K)\n        V = massage(V)\n\n        K_present = _op.reshape(K, (batch_size, num_heads, seq_len, head_size))\n        V_present = _op.reshape(V, (batch_size, num_heads, seq_len, head_size))\n        present = _op.stack([K_present, V_present], axis=0)\n\n        att_scores = _op.nn.batch_matmul(Q, K, transpose_a=False, transpose_b=True)\n        score_dtype = infer_type(att_scores).checked_type.dtype\n        att_scores = _op.divide(\n            att_scores,\n            _op.const(np.sqrt(head_size), dtype=infer_type(att_scores).checked_type.dtype),\n        )\n        att_scores = _op.reshape(att_scores, (batch_size, num_heads, seq_len, seq_len))\n\n        # build the attention mask\n        att_mask = _op.cast(mask_index, score_dtype)\n        att_mask = _op.expand_dims(att_mask, 1, num_newaxis=2)\n        att_mask = _op.subtract(_op.const(1, dtype=score_dtype), att_mask)\n        att_mask = _op.multiply(att_mask, _op.const(-10000, dtype=score_dtype))\n\n        # apply the mask\n        att_scores = _op.add(att_scores, att_mask)\n        att_scores = _op.reshape(att_scores, (batch_size * num_heads, seq_len, seq_len))\n\n        att_probs = _op.nn.softmax(att_scores, axis=-1)\n\n        output = _op.nn.batch_matmul(att_probs, V, transpose_a=False, transpose_b=False)\n        output = _op.reverse_reshape(output, (-1, num_heads, 0, 0))\n        output = _op.transpose(output, axes=[0, 2, 1, 3])\n        output = _op.reshape(output, (0, 0, out_hidden))\n\n        return _expr.TupleWrapper(_expr.Tuple([output, present]), 2)\n\n\nclass Gemm(OnnxOpConverter):\n    \"\"\"Operator converter for Gemm.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 3 or len(inputs) == 2, \"Gemm op take 2 or 3 inputs, {} given\".format(\n            len(inputs)\n        )\n        input0_state = infer_type(inputs[0])\n        dtype = input0_state.checked_type.dtype\n        # Y = alpha * A * B + beta * C\n        alpha = float(attr.get(\"alpha\", 1.0))\n        beta = float(attr.get(\"beta\", 1.0))\n        transA = int(attr.get(\"transA\", 0))\n        transB = int(attr.get(\"transB\", 0))\n        # get number of channels\n        channels = infer_channels(inputs[1], not transB)\n        if transA:\n            inputs[0] = _op.transpose(inputs[0], axes=(1, 0))\n        if not transB:\n            inputs[1] = _op.transpose(inputs[1], axes=(1, 0))\n        if len(input0_state.checked_type.shape) != 2:\n            inputs[0] = _op.nn.batch_flatten(inputs[0])\n        if alpha != 1.0:\n            inputs[0] *= _expr.const(alpha, dtype=dtype)\n        out = _op.nn.dense(inputs[0], inputs[1], units=channels)\n        if len(inputs) == 3:\n            out = out + _expr.const(beta, dtype=dtype) * inputs[2]\n        return out\n\n\nclass MatMul(OnnxOpConverter):\n    \"\"\"Operator converter for MatMul.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"MatMul op take 2 inputs, {} given\".format(len(inputs))\n        # Need to check input shape as batch matmul must be supported.\n        return matmul_out_dtype(inputs, out_dtype=infer_type(inputs[0]).checked_type.dtype)\n\n\nclass MatMulInteger16(OnnxOpConverter):\n    \"\"\"Operator converter for MatMulInteger16 from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"MatMulInteger16 op take 2 inputs, {} given\".format(len(inputs))\n        a_dtype = infer_type(inputs[0]).checked_type.dtype\n        b_dtype = infer_type(inputs[1]).checked_type.dtype\n        # Check input data types\n        assert a_dtype in (\"int16\", \"uint16\"), \"MatMulInteger16: invalid dtype for first input\"\n        assert b_dtype in (\"int16\", \"uint16\"), \"MatMulInteger16: invalid dtype for second input\"\n        out_dtype = \"int32\"\n        if a_dtype == \"uint16\" and b_dtype == \"uint16\":\n            out_dtype = \"uint32\"\n        return matmul_out_dtype(inputs, out_dtype)\n\n\nclass Mod(OnnxOpConverter):\n    \"\"\"Operator converter for Mod.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"Mod op take 2 inputs, {} given\".format(len(inputs))\n\n        # Note: attr['fmod'] determines whether the operator should behave like np.fmod or np.mod.\n        # attr['fmod'] == 0 will behave as np.mod and attr['fmod'] == 1 will force fmod treatment.\n        # The relay equivalent of np.fmod is relay.mod and np.mod is relay.floor_mod\n        if attr.get(\"fmod\", 0) == 0:\n            op_name = \"floor_mod\"\n        else:\n            op_name = \"mod\"\n\n        return AttrCvt(op_name)(inputs, {}, params)\n\n\nclass MaxPool(Pool):\n    \"\"\"Operator converter for MaxPool\"\"\"\n\n    name = \"max_pool\"\n\n\nclass MaxUnpool(OnnxOpConverter):\n    \"\"\"Operator converter for MaxUnpool\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        # Unpack inputs and attributes\n        data = inputs[0]\n        data_type = infer_type(data).checked_type.dtype\n        indices = inputs[1]\n        output_shape = inputs[2]\n        kernel_shape = attr.get(\"kernel_shape\")\n        pads = attr.get(\"pads\", None)\n        strides = attr.get(\"strides\", [1] * len(kernel_shape))\n\n        # Compute the proper output shape before padding.\n        multiplier = _op.concatenate(\n            [_expr.const([1, 1], dtype=\"int64\"), _expr.const(list(strides), dtype=\"int64\")], axis=0\n        )\n        total_output_shape = multiplier * shape_of(data, dtype=\"int64\")\n        # Add extra dimensions from kernel size and stride mismatch\n        total_output_shape += _op.concatenate(\n            [_expr.const([0, 0], \"int64\"), _expr.const(list(kernel_shape), \"int64\")], axis=0\n        ) - _op.concatenate(\n            [_expr.const([0, 0], \"int64\"), _expr.const(list(strides), \"int64\")], axis=0\n        )\n\n        # Compute padding amount if output shape is specified.\n        if output_shape is not None:\n            total_output_shape = output_shape\n\n        elif pads is not None:\n            # Get pads in the proper format for relay.\n            pads = _op.concatenate(\n                [_expr.const([0, 0, 0, 0], \"int64\"), _expr.const(list(pads), \"int64\")], axis=0\n            )\n            pads = _op.reshape(pads, [-1, 2])\n            # Compute the total padding per axis.\n            total_pad = _op.sum(pads, axis=-1)\n            # Reversing maxpool means that padding actually makes our output smaller.\n            total_output_shape = total_output_shape - total_pad\n\n        # Create a tensor of zeros then scatter our data through it.\n        zeros_tensor = _op.zeros(total_output_shape, data_type)\n        # We need to flatten all our tensors before scattering.\n        flat_tensor = _op.scatter(\n            _op.reshape(zeros_tensor, [-1]),\n            _op.reshape(indices, [-1]),\n            _op.reshape(data, [-1]),\n            axis=0,\n        )\n        # Now reshape back to prepadded shape.\n        output_tensor = _op.reshape(flat_tensor, total_output_shape)\n\n        return output_tensor\n\n\nclass LpPool(OnnxOpConverter):\n    \"\"\"A helper class for lppool op converters.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = infer_type(inputs[0]).checked_type.dtype\n        data = inputs[0]\n        input_shape = infer_shape(data)\n        ndim = len(input_shape)\n        if \"auto_pad\" in attr:\n            attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: LpPool does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                data = autopad(\n                    data,\n                    attr[\"strides\"],\n                    attr[\"kernel_shape\"],\n                    [1] * ndim,\n                    mode=attr[\"auto_pad\"],\n                )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator {} is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"], \"LpPool\"))\n            attr.pop(\"auto_pad\")\n\n        if \"storage_order\" in attr:\n            attr[\"layout\"] = onnx_storage_order2layout(\n                attr[\"storage_order\"], dims=(len(input_shape) - 2), op_name=\"LpPool\"\n            )\n        else:\n            attr[\"layout\"] = onnx_default_layout(dims=(len(input_shape) - 2), op_name=\"LpPool\")\n\n        p_value = attr.get(\"p\", 2)\n        p = _expr.const(p_value, dtype)\n        reci_p = _expr.const(1.0 / p_value, dtype)\n        data = _op.power(data, p)\n\n        out = AttrCvt(\n            op_name=dimension_picker(\"avg_pool\"),\n            transforms={\"kernel_shape\": \"pool_size\", \"pads\": (\"padding\", 0)},\n            extras={\"count_include_pad\": True},\n            ignores=[\"p\"],\n            custom_check=dimension_constraint(),\n        )([data], attr, params)\n        kernels = attr[\"kernel_shape\"]\n        out = _op.abs(out) * _expr.const(np.prod(kernels).astype(dtype))\n        return _op.power(out, reci_p)\n\n\nclass GlobalLpPool(OnnxOpConverter):\n    \"\"\"Operator converter for GlobalLpPool.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # TODO: GlobalLpPool does not yet support dynamic shapes\n        in_shape = infer_shape(inputs[0])\n        attr[\"kernel_shape\"] = in_shape[2:]\n\n        return LpPool._impl_v1(inputs, attr, params)\n\n\nclass Mul(Elemwise):\n    \"\"\"Operator converter for Multiply.\"\"\"\n\n    name = \"multiply\"\n\n\nclass Pad(OnnxOpConverter):\n    \"\"\"Operator converter for Pad.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        pad_width = []\n        pads = attr.pop(\"paddings\")\n        dims = int(len(pads) / 2)\n        for i in range(dims):\n            pad_width.append((pads[i], pads[i + dims]))\n        attr[\"pad_width\"] = pad_width\n        pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n        if pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n            attr[\"pad_mode\"] = pad_mode\n            attr.pop(\"mode\", None)\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n            )\n\n        return AttrCvt(\n            _op.nn.pad,\n            transforms={\n                \"value\": \"pad_value\",\n            },\n        )(inputs, attr, params)\n\n    @classmethod\n    def _impl_v2(cls, inputs, attr, params):\n        pad_width = []\n        pads = attr.pop(\"pads\")\n        dims = int(len(pads) / 2)\n        for i in range(dims):\n            pad_width.append((pads[i], pads[i + dims]))\n        attr[\"pad_width\"] = pad_width\n        pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n        if pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n            attr[\"pad_mode\"] = pad_mode\n            attr.pop(\"mode\", None)\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n            )\n\n        return AttrCvt(\n            \"pad\",\n            transforms={\n                \"value\": \"pad_value\",\n            },\n        )(inputs, attr, params)\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        pads = inputs[1]\n        if len(inputs) == 3:\n            value = fold_constant(_op.take(inputs[2], _op.const(0)))\n        else:\n            value = 0.0\n\n        pad_width_expr = fold_constant(_op.transpose(_op.reshape(pads, (2, -1))))\n        pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n        if not pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n            raise tvm.error.OpAttributeInvalid(\n                \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n            )\n\n        return _op.nn.pad(inputs[0], pad_width_expr, value, pad_mode=pad_mode)\n\n\nclass ParametricSoftPlus(OnnxOpConverter):\n    \"\"\"Operator converter for ParametricSoftPlus.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = _expr.const(float(attr.get(\"alpha\", 1.0)))\n        beta = _expr.const(float(attr.get(\"beta\", 1.0)))\n        return _op.log(_op.exp(beta * inputs[0]) + _expr.const(1.0)) * alpha\n\n\nclass Pow(OnnxOpConverter):\n    \"\"\"Operator converter for Pow.\"\"\"\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        x = inputs[0]\n        y = inputs[1]\n\n        x_type = infer_type(x).checked_type.dtype\n        output_type = x_type\n        y_type = infer_type(y).checked_type.dtype\n\n        if not x_type.startswith(\"float\"):\n            x_type = \"float32\"\n            x = _op.cast(x, x_type)\n\n        if x_type != y_type:\n            y = _op.cast(y, x_type)\n\n        # TODO: come up with good default integer pow() func for common backends\n        result = _op.power(x, y)\n        if x_type != output_type:\n            return _op.cast(result, output_type)\n        return result\n\n\nclass Prelu(OnnxOpConverter):\n    \"\"\"Operator converter for Prelu.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"Prelu need 2 inputs, {} given\".format(len(inputs))\n        input_shape = shape_of(inputs[0])\n        alpha = _op.broadcast_to_like(inputs[1], inputs[0])\n        alpha = _op.reshape(alpha, [-1])\n        output = _op.nn.prelu(_op.reshape(inputs[0], [-1]), alpha, axis=0)\n        return _op.reshape(output, input_shape)\n\n\nclass Reciprocal(OnnxOpConverter):\n    \"\"\"Operator converter for Reciprocal.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = infer_type(inputs[0]).checked_type.dtype\n        return _expr.const(1.0, dtype=dtype) / inputs[0]\n\n\nclass Flatten(OnnxOpConverter):\n    \"\"\"Operator converter for Flatten.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 1)\n        ishape = shape_of(inputs[0])\n        ndim = infer_shape(ishape)[0]\n        if axis < 0:\n            axis = axis + ndim\n\n        if axis == 1:\n            out = _op.nn.batch_flatten(inputs[0])\n        else:\n            pre_shape = _op.prod(_op.strided_slice(ishape, [0], [axis], [1]), keepdims=True)\n            post_shape = _op.prod(_op.strided_slice(ishape, [axis], [ndim], [1]), keepdims=True)\n            newshape = fold_constant(_op.concatenate([pre_shape, post_shape], axis=0))\n            out = _op.reshape(inputs[0], newshape)\n        return out\n\n\nclass Reshape(OnnxOpConverter):\n    \"\"\"Operator converter for Reshape.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return _op.reshape(inputs[0], attr[\"shape\"])\n\n    @classmethod\n    def _impl_v5(cls, inputs, attr, params):\n        allowzero = attr.get(\"allowzero\", False)\n        if get_name(inputs[1]) in params:\n            shape = tuple(params[inputs[1].name_hint].numpy().astype(\"int32\"))\n            out = _op.reshape(inputs[0], shape, allowzero=allowzero)\n        else:\n            out = _op.reshape(*inputs, allowzero=allowzero)\n        return out\n\n\nclass DepthToSpace(OnnxOpConverter):\n    \"\"\"Operator converter for DepthToSpace.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        block_size = int(attr[\"blocksize\"])\n        mode = attr.get(\"mode\", b\"DCR\").decode(\"utf-8\")\n        return _op.nn.depth_to_space(inputs[0], block_size, mode=mode)\n\n\nclass SpaceToDepth(OnnxOpConverter):\n    \"\"\"Operator converter for SpaceToDepth.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n\n        block_size = int(attr[\"blocksize\"])\n        return _op.nn.space_to_depth(inputs[0], block_size)\n\n\nclass Concat(OnnxOpConverter):\n    \"\"\"Operator converter for Concat.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, args, params):\n        return AttrCvt(op_name=\"concatenate\")((inputs,), args)\n\n\nclass Scale(OnnxOpConverter):\n    \"\"\"Operator converter for Scale.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        scale = float(attr.get(\"scale\", 1.0))\n        return inputs[0] * _expr.const(scale)\n\n\nclass Selu(OnnxOpConverter):\n    \"\"\"Operator converter for Selu.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = float(attr.get(\"alpha\", 1.67326319217681884765625))\n        gamma = float(attr.get(\"gamma\", 1.05070102214813232421875))\n        return _expr.const(gamma) * (\n            _expr.const(-alpha) * _op.nn.relu(_expr.const(1.0) - _op.exp(inputs[0]))\n            + _op.nn.relu(inputs[0])\n        )\n\n\nclass ScaledTanh(OnnxOpConverter):\n    \"\"\"Operator converter for ScaledTanh.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = float(attr.get(\"alpha\", 1.0))\n        beta = float(attr.get(\"beta\", 1.0))\n        return _op.tanh(_expr.const(beta) * inputs[0]) * _expr.const(alpha)\n\n\nclass Shrink(OnnxOpConverter):\n    \"\"\"Operator converter for Shrink.\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        x = inputs[0]\n        dtype = infer_type(x).checked_type.dtype\n        lambd = _op.const(attr.get(\"lambd\", 0.5), dtype=dtype)\n        bias = _op.const(attr.get(\"bias\", 0.0), dtype=dtype)\n\n        zeros = _op.zeros_like(x)\n        return _op.where(x < -lambd, x + bias, zeros) + _op.where(x > lambd, x - bias, zeros)\n\n\nclass Softsign(OnnxOpConverter):\n    \"\"\"Operator converter for Softsign.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return inputs[0] / (_expr.const(1.0) + Absolute.get_converter(1)(inputs, attr, params))\n\n\nclass Sub(Elemwise):\n    \"\"\"Operator converter for Subtract.\"\"\"\n\n    name = \"subtract\"\n\n\nclass Sum(OnnxOpConverter):\n    \"\"\"Operator converter for Sum.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # Onnx Sum Operator\n        for in_index in range(len(inputs) - 1):\n            inputs[in_index + 1] = _op.add(inputs[in_index], inputs[in_index + 1])\n\n        return inputs[len(inputs) - 1]\n\n\nclass Optional_(OnnxOpConverter):\n    \"\"\"Operator converter for Optional based on sequence construction op.\"\"\"\n\n    @classmethod\n    def _impl_v15(cls, inputs, attr, params):\n        return SequenceConstruct._impl_v11(inputs, attr, params)\n\n\nclass OptionalHasElement(OnnxOpConverter):\n    \"\"\"Operator converter for OptionalHasElement.\"\"\"\n\n    @classmethod\n    def _impl_v15(cls, inputs, attr, params):\n        shape = infer_shape(inputs[0])\n        return _op.const(True) if shape else _op.const(False)\n\n\nclass OptionalGetElement(OnnxOpConverter):\n    \"\"\"Operator converter for OptionalGetElement based on sequence construction op.\"\"\"\n\n    @classmethod\n    def _impl_v15(cls, inputs, attr, params):\n        opt_as_seq = Optional_._impl_v15(inputs, attr, params)\n        return _expr.TupleGetItem(opt_as_seq, 0)\n\n\nclass Affine(OnnxOpConverter):\n    \"\"\"Operator converter for Affine transformation.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = _expr.const(attr.get(\"alpha\", 1.0))\n        beta = _expr.const(attr.get(\"beta\", 0.0))\n        return (alpha * inputs[0]) + beta\n\n\nclass ThresholdedRelu(OnnxOpConverter):\n    \"\"\"Operator converter for ThresholdedRelu.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = float(attr.get(\"alpha\", 1.0))\n        alpha_tensor = _op.full_like(inputs[0], fill_value=_expr.const(alpha))\n        mask = _op.greater(inputs[0], alpha_tensor).astype(\"float32\")\n        return inputs[0] * mask\n\n\ndef _broadcast_constraint():\n    def _broadcast_check(attrs):\n        if attrs.get(\"axis\", None):\n            return False\n        return True\n\n    return _broadcast_check, \"Specifying broadcast axis not allowed.\"\n\n\ndef _fully_connected(opset):\n    def _impl(inputs, attr, params):\n        # get number of channels\n        channels = infer_channels(inputs[1], params)\n        attr[\"units\"] = channels\n        return AttrCvt(\"dense\", ignores=[\"axis\", \"axis_w\"])(inputs, attr)\n\n    return _impl\n\n\nclass Upsample(OnnxOpConverter):\n    \"\"\"Operator converter for Upsample (nearest mode).\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        scales = attr.get(\"scales\")\n\n        input_shape = infer_shape(inputs[0])\n        dims = len(input_shape)\n\n        if not scales:\n            # Here we are going to higher OPSET version.\n            assert len(inputs) == 2, \"Upsample op takes 2 inputs, {} given\".format(len(inputs))\n\n            if get_name(inputs[1]) in params:\n                scales = params[inputs[1].name_hint].numpy()\n            else:\n                scales = inputs[1]\n        if isinstance(scales, _expr.Constant):\n            scales = list(scales.data.numpy())\n        if not isinstance(scales, _expr.Expr):\n            assert scales[0] == 1.0 and scales[1] == 1.0\n\n        mode = attr.get(\"mode\")\n        if mode == b\"nearest\":\n            method = \"nearest_neighbor\"\n        elif mode == b\"linear\":\n            method = \"trilinear\" if dims == 5 else \"bilinear\"\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                'Value {} in attribute \"mode\" of operator Upsample is not valid.'.format(mode)\n            )\n\n        # in 3d case, we use the purely static op\n        if dims == 5:\n            if isinstance(scales, _expr.Expr):\n                scale_h = _op.take(scales, _op.const(3))\n                scale_w = _op.take(scales, _op.const(4))\n                scale_d = _op.take(scales, _op.const(1))\n            else:\n                assert len(scales) == 5\n                scale_h = scales[-2]\n                scale_w = scales[-1]\n                scale_d = scales[-3]\n\n            layout = \"NCDHW\"\n            out = _op.nn.upsampling3d(\n                inputs[0],\n                scale_d,\n                scale_h,\n                scale_w,\n                layout=layout,\n                method=method,\n                coordinate_transformation_mode=\"asymmetric\",\n            )\n        # in 2d case, use dynamic op\n        else:\n            if isinstance(scales, _expr.Expr):\n                scale_h = _op.take(scales, _op.const(3))\n                scale_w = _op.take(scales, _op.const(4))\n            else:\n                assert len(scales) == 4\n                scale_h = scales[-2]\n                scale_w = scales[-1]\n            layout = \"NCHW\"\n\n            out = _op.nn.upsampling(\n                inputs[0],\n                scale_h,\n                scale_w,\n                layout=layout,\n                method=method,\n                align_corners=False,\n            )\n        return out\n\n\nclass Shape(OnnxOpConverter):\n    \"\"\"Operator converter for Shape.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return shape_of(inputs[0], \"int64\")\n\n    @classmethod\n    def _impl_v15(cls, inputs, attr, params):\n        start = attr.get(\"start\")\n        end = attr.get(\"end\")\n        return shape_of(inputs[0], dtype=\"int64\", start=start, end=end)\n\n\nclass CumSum(OnnxOpConverter):\n    \"\"\"Operator converter for CumSum.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        dim = inputs[1]\n\n        if dim is not None:\n            dim = int(infer_value(dim, params).numpy())\n\n        exclusive = attr.get(\"exclusive\", 0)\n        reverse = attr.get(\"reverse\", 0)\n\n        if reverse != 0:\n            out = _op.reverse(data, axis=dim)\n            out = _op.cumsum(out, axis=dim, exclusive=exclusive)\n            return _op.reverse(out, axis=dim)\n\n        return _op.cumsum(data, axis=dim, exclusive=exclusive)\n\n\nclass Cast(OnnxOpConverter):\n    \"\"\"Operator converter for Cast.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return AttrCvt(op_name=\"cast\", transforms={\"to\": \"dtype\"})(inputs, attr)\n\n    @classmethod\n    def _impl_v6(cls, inputs, attr, params):\n        try:\n            from onnx import TensorProto\n        except ImportError as e:\n            raise ImportError(\"Unable to import TensorProto from onnx {}\".format(e))\n\n        # If onnx mapping is used, bfloat16 gets converted to float16\n        # which is not the desired behavior\n        if attr[\"to\"] == int(TensorProto.BFLOAT16):\n            attr[\"to\"] = \"bfloat16\"\n        else:\n            try:\n                from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE\n\n                attr[\"to\"] = str(TENSOR_TYPE_TO_NP_TYPE[attr[\"to\"]])\n            except ImportError as e:\n                raise ImportError(\"Unable to import onnx.mapping which is required {}\".format(e))\n\n        return AttrCvt(op_name=\"cast\", transforms={\"to\": \"dtype\"})(inputs, attr)\n\n\nclass CastLike(OnnxOpConverter):\n    \"\"\"Operator converter for CastLike.\"\"\"\n\n    @classmethod\n    def _impl_v15(cls, inputs, attr, params):\n        return AttrCvt(op_name=\"cast_like\")(inputs, attr)\n\n\nclass Unsqueeze(OnnxOpConverter):\n    \"\"\"Operator converter for Unsqueeze.\"\"\"\n\n    @classmethod\n    def run_calculation(cls, tensor, axes):\n        axes = sorted(axes)\n        for axis in axes:\n            tensor = _op.expand_dims(tensor, axis=axis, num_newaxis=1)\n        return tensor\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return cls.run_calculation(inputs[0], attr[\"axes\"])\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        if isinstance(inputs[1], _expr.Constant):\n            constant_axes = list(inputs[1].data.numpy())\n            constant_axes = list(map(int, constant_axes))\n            return cls.run_calculation(inputs[0], constant_axes)\n\n        rank_input = len(infer_type(inputs[0]).checked_type.shape)\n        num_new_axis = int(infer_type(inputs[1]).checked_type.shape[0])\n        axes = relay.sort(inputs[1])\n        axes = relay.split(axes, num_new_axis).astuple()\n        result = inputs[0]\n\n        # TODO (AndrewZhaoLuo): investigate performance issues with consecutive\n        # dynamic expand_dims on non-llvm targets.\n        for i in range(num_new_axis):\n            axis = relay.TupleGetItem(axes, i)\n            # Unpack scalar\n            axis = relay.reshape(axis, [])\n            axis = relay.where(\n                axis >= relay.const(0, \"int64\"), axis, axis + relay.const(rank_input, \"int64\")\n            )\n            result = _op.expand_dims(result, axis)\n        return result\n\n\nclass Squeeze(OnnxOpConverter):\n    \"\"\"Operator converter for Squeeze.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axes\", None)\n        return _op.squeeze(inputs[0], axis)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        ishape = infer_shape(inputs[0])\n        axis = inputs[1]\n\n        if axis is None:\n            # If axes is not provided, all the single dimensions will be removed from the shape.\n            if not ishape:  # scalar\n                return inputs[0]\n\n            axis = [i for i in range(len(ishape)) if ishape[i] == 1]\n            axis = _op.const(axis)\n\n        dtype = infer_type(axis).checked_type.dtype\n\n        if isinstance(axis, _expr.Constant):\n            constant_axes = list(axis.data.numpy())\n            constant_axes = list(map(int, constant_axes))\n            return _op.squeeze(inputs[0], constant_axes)\n\n        rank = _op.shape_of(_op.shape_of(inputs[0], dtype), dtype)\n        axis = _op.where(axis < _op.const(0, dtype), axis + rank, axis)\n        return _op.squeeze(inputs[0], fold_constant(axis))\n\n\nclass Split(OnnxOpConverter):\n    \"\"\"Operator converter for Split.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        splits = attr.get(\"split\", None)\n        if splits is not None and len(splits) > 1:\n            indices = []\n            index = 0\n            for i in splits[:-1]:\n                index += i\n                indices.append(index)\n        # When splits isnt specified divide evenly over axis.\n        else:\n            indices = attr[\"tvm_custom\"][\"num_outputs\"]\n        output = _op.split(inputs[0], indices, attr.get(\"axis\", 0))\n        # If the output of split is a single value, unpack if from the TupleWrapper\n        if len(output) == 1:\n            output = output[0]\n        return output\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        splits = inputs[1]\n        splits_rank = None\n        if splits is not None:\n            splits_rank = len(infer_shape(splits))\n        if splits is not None and splits_rank > 0:\n            if isinstance(splits, _expr.Constant):\n                splits = splits.data.asnumpy()\n                indices = []\n                index = 0\n                for i in splits[:-1]:\n                    index += i\n                    indices.append(index)\n            else:\n                raise ValueError(\"Dynamic Split not yet supported\")\n        # When splits isnt specified divide evenly over axis.\n        else:\n            indices = attr[\"tvm_custom\"][\"num_outputs\"]\n        output = _op.split(inputs[0], indices, attr.get(\"axis\", 0))\n        # If the output of split is a single value, unpack if from the TupleWrapper\n        if len(output) == 1:\n            output = output[0]\n        return output\n\n\nclass Slice(OnnxOpConverter):\n    \"\"\"Operator converter for Slice.\"\"\"\n\n    @classmethod\n    def _common(cls, starts, ends, axes):\n        N = max(axes) + 1\n        new_axes = list(range(N))\n        new_starts = [0] * N\n        new_ends = [np.iinfo(np.int32).max] * N\n        for i, axis in enumerate(axes):\n            new_starts[axis] = starts[i]\n            new_ends[axis] = ends[i]\n        return new_starts, new_ends, new_axes\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if isinstance(attr[\"starts\"], int):\n            attr[\"starts\"] = (attr[\"starts\"],)\n            attr[\"ends\"] = (attr[\"ends\"],)\n\n        try:\n            # Update the starts and ends according to axes if required.\n            if isinstance(attr[\"axes\"], int):\n                attr[\"axes\"] = (attr[\"axes\"],)\n            new_starts, new_ends, new_axes = cls._common(attr[\"starts\"], attr[\"ends\"], attr[\"axes\"])\n            attr[\"axes\"] = new_axes\n            attr[\"starts\"] = new_starts\n            attr[\"ends\"] = new_ends\n        except KeyError:\n            pass\n        begin = list(attr[\"starts\"])\n        end = list(attr[\"ends\"])\n\n        return _op.strided_slice(inputs[0], begin=begin, end=end)\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        starts = inputs[1]\n        ends = inputs[2]\n        axes = inputs[3]\n        steps = inputs[4]\n\n        ishape = infer_shape(inputs[0])\n        data_rank = len(ishape)\n\n        if axes is not None:\n            # Normalize for negative axes\n            axes_dtype = infer_type(axes).checked_type.dtype\n            axes = fold_constant(\n                _op.where(\n                    axes < _op.const(0, axes_dtype), axes + _op.const(data_rank, axes_dtype), axes\n                )\n            )\n\n        def has_static_axes():\n            return (\n                isinstance(axes, _expr.Constant)\n                and isinstance(starts, _expr.Constant)\n                and isinstance(ends, _expr.Constant)\n                and (steps is None or isinstance(steps, _expr.Constant))\n            )\n\n        if axes is not None and has_static_axes():\n            axes_np = axes.data.numpy().astype(\"int64\")\n            begin_np = starts.data.numpy().astype(\"int64\")\n            end_np = ends.data.numpy().astype(\"int64\")\n            if steps is None:\n                strides_np = np.ones_like(begin_np).astype(\"int64\")\n            else:\n                strides_np = steps.data.numpy().astype(\"int64\")\n            if all([isinstance(ishape[i], int) for i in axes_np]):\n                return _op.strided_slice(\n                    inputs[0], list(begin_np), list(end_np), list(strides_np), axes=list(axes_np)\n                )\n\n        # Update the starts and ends according to axes if required.\n        if axes is not None:\n            data_shape = shape_of(inputs[0], dtype=infer_type(ends).checked_type.dtype)\n            starts = _op.scatter(\n                _op.const([0] * data_rank, dtype=infer_type(starts).checked_type.dtype),\n                axes,\n                starts,\n                axis=0,\n            )\n            ends = _op.scatter(data_shape, axes, ends, axis=0)\n            if steps is not None:\n                steps = _op.scatter(\n                    _op.const([1] * data_rank, dtype=infer_type(steps).checked_type.dtype),\n                    axes,\n                    steps,\n                    axis=0,\n                )\n\n        if steps is None:\n            steps = _op.const([1] * data_rank, dtype=infer_type(starts).checked_type.dtype)\n\n        return _op.strided_slice(\n            inputs[0], fold_constant(starts), fold_constant(ends), fold_constant(steps)\n        )\n\n\ndef normalize_gather_indices(data, indices, axis):\n    \"\"\"Make sure gather indices aren't negative\"\"\"\n    ind_dtype = infer_type(indices).checked_type.dtype\n    # Normalize the indices to a positive range\n    s = _op.take(_op.shape_of(data, dtype=ind_dtype), _op.const(axis, dtype=\"int64\"))\n    cond = fold_constant(indices < _op.const(0, ind_dtype))\n    if isinstance(cond, _expr.Constant):\n        val = cond.data.numpy()\n        if val.size == 1:\n            cond = val.item()\n            if cond:\n                indices = indices + s\n            return indices\n    indices = _op.where(cond, indices + s, indices)\n    return indices\n\n\nclass Gather(OnnxOpConverter):\n    \"\"\"Operator converter for Gather.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 0)\n        data = inputs[0]\n        indices = inputs[1]\n        indices = normalize_gather_indices(data, indices, axis)\n        return _op.take(data, indices, axis)\n\n\nclass GatherElements(OnnxOpConverter):\n    \"\"\"Operator converter for GatherElements.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        indices = inputs[1]\n        axis = attr.get(\"axis\", 0)\n        indices = normalize_gather_indices(data, indices, axis)\n        return _op.gather(data, axis, indices)\n\n\nclass GatherND(OnnxOpConverter):\n    \"\"\"Operator converter for GatherND.\"\"\"\n\n    @classmethod\n    def _impl_common(cls, data, indices, batch_dims=0):\n        indices_dims = len(infer_shape(indices))\n        indices_shape = infer_shape(indices)\n        indices = _op.transpose(indices, axes=[-1] + list(range(indices_dims - 1)))\n        index_rank = indices_shape[-1]\n        return _op.gather_nd(\n            data,\n            indices,\n            batch_dims=batch_dims,\n            index_rank=index_rank,\n        )\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return cls._impl_common(inputs[0], inputs[1])\n\n    @classmethod\n    def _impl_v12(cls, inputs, attr, params):\n        batch_dims = attr.get(\"batch_dims\", 0)\n        return cls._impl_common(inputs[0], inputs[1], batch_dims)\n\n\nclass Compress(OnnxOpConverter):\n    \"\"\"Operator converter for compress\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        input_tensor, condition_tensor = inputs\n\n        axis = attr.get(\"axis\", None)\n\n        # Change one hot tensor to indices e.g. [0, 1, 1, 0, 1] -> [1, 2, 4]\n        condition_tensor = _op.reshape(_op.argwhere(condition_tensor), (-1,))\n\n        if axis is not None:\n            return _op.take(input_tensor, condition_tensor, axis=axis)\n\n        # if axis is None, flatten input tensor before selection\n        input_tensor = _op.reshape(input_tensor, (-1,))\n        return _op.take(input_tensor, condition_tensor, axis=0)\n\n\nclass Scatter(OnnxOpConverter):\n    \"\"\"Operator converter for Scatter.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 0)\n        return _op.scatter(inputs[0], inputs[1], inputs[2], axis)\n\n\nclass ScatterND(OnnxOpConverter):\n    \"\"\"Operator converter for ScatterND.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        indices_dim = len(infer_shape(inputs[1]))\n        axes = list(range(indices_dim))\n        return _op.scatter_nd(\n            inputs[0], _op.transpose(inputs[1], axes[-1:] + axes[:-1]), inputs[2], \"update\"\n        )\n\n\nclass EyeLike(OnnxOpConverter):\n    \"\"\"Operator converter for EyeLike.\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        dtype = attr.get(\"dtype\", None)\n        if dtype is None:\n            in_checked_type = infer_type(inputs[0]).checked_type\n            in_dtype = in_checked_type.dtype\n            dtype = in_dtype\n        else:\n            dtype = get_type(dtype)\n\n        in_shape = _op.shape_of(inputs[0])\n        zeros = _op.zeros(in_shape, dtype)\n\n        dim = _op.take(in_shape, _op.const(0))\n\n        indices = _op.arange(_op.const(0), dim, dtype=\"int32\")\n        ones = _op.full(_op.const(1), _op.reshape(dim, (1,)), dtype=dtype)\n        k = _op.const(attr.get(\"k\", 0), dtype=\"int32\")\n        return _op.scatter_nd(zeros, _op.stack([indices, indices + k], axis=0), ones, \"update\")\n\n\nclass LRN(OnnxOpConverter):\n    \"\"\"Operator converter for Local Response Normalization.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        \"\"\"LRN support only NCHW format\n        https://github.com/onnx/onnx/blob/main/docs/Operators.md#LRN\n        \"\"\"\n        axis = 1\n        alpha = attr.get(\"alpha\", 0.0001)\n        beta = attr.get(\"beta\", 0.75)\n        bias = attr.get(\"bias\", 1.0)\n        nsize = attr.get(\"size\")\n        attr = {\"size\": nsize, \"axis\": axis, \"alpha\": alpha, \"beta\": beta, \"bias\": bias}\n        return AttrCvt(\"lrn\")(inputs, attr)\n\n\nclass Maximum(OnnxOpConverter):\n    \"\"\"Operator converter for Maximum.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) == 1:\n            return inputs[0]\n        _max = inputs[0]\n        for i in range(1, len(inputs)):\n            _max = AttrCvt(\"maximum\")([_max, inputs[i]], {})\n        return _max\n\n\nclass Minimum(OnnxOpConverter):\n    \"\"\"Operator converter for Minimum.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) == 1:\n            return inputs[0]\n        _min = inputs[0]\n        for i in range(1, len(inputs)):\n            _min = AttrCvt(\"minimum\")([_min, inputs[i]], {})\n        return _min\n\n\nclass Mean(OnnxOpConverter):\n    \"\"\"Operator converter for Mean.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) == 1:\n            return inputs[0]\n        # avoid overflow\n        concat = _op.concatenate([_op.expand_dims(x, axis=0) for x in inputs], axis=0)\n        return _op.mean(concat, axis=0, keepdims=False)\n\n\nclass MeanVarianceNormalization(OnnxOpConverter):\n    \"\"\"Operator converter for MeanVarianceNormalization.\"\"\"\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        axis = attr.get(\"axes\", (0, 2, 3))\n        data_mean = _op.mean(inputs[0], axis=axis, keepdims=True)\n        data_mean_squared = _op.power(data_mean, _expr.const(2, \"float32\"))\n        data_squared = _op.power(inputs[0], _expr.const(2, \"float32\"))\n        data_squared_mean = _op.mean(data_squared, axis=axis, keepdims=True)\n        return (inputs[0] - data_mean) / _op.sqrt(data_squared_mean - data_mean_squared)\n\n\nclass HardSigmoid(OnnxOpConverter):\n    \"\"\"Operator converter for HardSigmoid.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = attr.get(\"alpha\", 0.2)\n        beta = attr.get(\"beta\", 0.5)\n        transformX = (inputs[0] * _expr.const(alpha)) + _expr.const(beta)\n        attr = {\"a_min\": 0, \"a_max\": 1}\n        return AttrCvt(\"clip\")([transformX], attr)\n\n\nclass HardSwish(OnnxOpConverter):\n    \"\"\"Operator converter for HardSwish.\"\"\"\n\n    @classmethod\n    def _impl_v14(cls, inputs, attr, params):\n        alpha = attr.get(\"alpha\", 1 / 6)\n        beta = attr.get(\"beta\", 0.5)\n        transformX = inputs[0] * _expr.const(alpha) + _expr.const(beta)\n        attr = {\"a_min\": 0, \"a_max\": 1}\n        return inputs[0] * AttrCvt(\"clip\")([transformX], attr)\n\n\nclass Reduce(OnnxOpConverter):\n    \"\"\"Operator converter for reduce ops.\"\"\"\n\n    name = \"\"\n\n    @classmethod\n    def run_calculation(cls, inputs, axis, keepdims):\n        attr = {\"axis\": axis, \"keepdims\": keepdims}\n        return AttrCvt(cls.name)(inputs, attr)\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if \"axes\" in attr:\n            axis = attr.get(\"axes\", 0)\n        else:\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n\n        return cls.run_calculation(inputs, axis, attr.get(\"keepdims\", True))\n\n    @classmethod\n    def _impl_v12(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if len(inputs) == 2:\n            if isinstance(inputs[1], _expr.Constant):\n                # Get axis and unpack scalar\n                constant_axis = int(inputs[1].data.numpy()[0])\n                return cls.run_calculation([inputs[0]], constant_axis, attr.get(\"keepdims\", True))\n\n            raise ValueError(\"Dynamic Reduce is not supported yet!\")\n\n        return cls._impl_v1(inputs, attr, params)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        noop_with_empty_axes = attr.get(\"noop_with_empty_axes\", 0)\n        num_axis = int(infer_type(inputs[1]).checked_type.shape[0]) if inputs[1] is not None else 0\n\n        if noop_with_empty_axes and num_axis == 0:\n            return inputs[0]\n\n        if len(inputs) == 2:\n            if isinstance(inputs[1], _expr.Constant):\n                # Get axis and unpack scalar\n                constant_axis = int(inputs[1].data.numpy()[0])\n                return cls.run_calculation([inputs[0]], constant_axis, attr.get(\"keepdims\", True))\n\n            if num_axis > 0:\n                raise ValueError(\"Dynamic Reduce is not supported yet!\")\n\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n            return cls.run_calculation([inputs[0]], axis, attr.get(\"keepdims\", True))\n\n        return cls._impl_v1(inputs, attr, params)\n\n\nclass ReduceMax(Reduce):\n    \"\"\"Operator converter for ReduceMax.\"\"\"\n\n    name = \"max\"\n\n\nclass ReduceMin(Reduce):\n    \"\"\"Operator converter for ReduceMin.\"\"\"\n\n    name = \"min\"\n\n\nclass ReduceSum(Reduce):\n    \"\"\"Operator converter for ReduceSum.\"\"\"\n\n    name = \"sum\"\n\n\nclass ReduceMean(Reduce):\n    \"\"\"Operator converter for ReduceMean.\"\"\"\n\n    name = \"mean\"\n\n\nclass ReduceProd(Reduce):\n    \"\"\"Operator converter for ReduceProd.\"\"\"\n\n    name = \"prod\"\n\n\nclass ReduceLogSumExp(Reduce):\n    \"\"\"Operator converter for ReduceLogSumExp.\"\"\"\n\n    name = \"logsumexp\"\n\n\nclass ReduceSumSquare(OnnxOpConverter):\n    \"\"\"Operator converter for ReduceSumSquare.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if \"axes\" in attr:\n            axis = attr.get(\"axes\", 0)\n        else:\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n        attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n        inputs[0] = inputs[0] * inputs[0]\n\n        return AttrCvt(\"sum\")(inputs, attr)\n\n\nclass ReduceL1(OnnxOpConverter):\n    \"\"\"Operator converter for ReduceL1.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if \"axes\" in attr:\n            axis = attr.get(\"axes\", 0)\n        else:\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n        attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n        inputs[0] = _op.abs(inputs[0])\n\n        return AttrCvt(\"sum\")(inputs, attr)\n\n\nclass ReduceL2(OnnxOpConverter):\n    \"\"\"Operator converter for ReduceL2.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if \"axes\" in attr:\n            axis = attr.get(\"axes\", 0)\n        else:\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n        attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n        inputs[0] = inputs[0] * inputs[0]\n        out = AttrCvt(\"sum\")(inputs, attr)\n\n        return _op.sqrt(out)\n\n\nclass ReduceLogSum(OnnxOpConverter):\n    \"\"\"Operator converter for ReduceLogSum.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if not infer_shape(inputs[0]):  # promote scalar to 1-D tensor\n            inputs[0] = _op.expand_dims(inputs[0], axis=0)\n\n        if \"axes\" in attr:\n            axis = attr.get(\"axes\", 0)\n        else:\n            axis_len = len(infer_shape(inputs[0]))\n            axis = list(range(axis_len))\n        attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n        out = AttrCvt(\"sum\")(inputs, attr)\n\n        return _op.log(out)\n\n\nclass ArgMax(OnnxOpConverter):\n    \"\"\"Operator converter for ArgMax.\"\"\"\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 0)\n        keepdims = attr.get(\"keepdims\", True)\n        select_last_index = attr.get(\"select_last_index\", False)\n        attr = {\"axis\": axis, \"keepdims\": keepdims, \"select_last_index\": select_last_index}\n        return _op.cast(AttrCvt(\"argmax\")(inputs, attr), \"int64\")\n\n\nclass ArgMin(OnnxOpConverter):\n    \"\"\"Operator converter for ArgMin.\"\"\"\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 0)\n        keepdims = attr.get(\"keepdims\", True)\n        select_last_index = attr.get(\"select_last_index\", False)\n        attr = {\"axis\": axis, \"keepdims\": keepdims, \"select_last_index\": select_last_index}\n        return _op.cast(AttrCvt(\"argmin\")(inputs, attr), \"int64\")\n\n\nclass Softmax(OnnxOpConverter):\n    \"\"\"Operator converter for Softmax.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 1)\n        in_shape = infer_shape(inputs[0])\n        ndim = len(in_shape)\n        if axis < 0:\n            axis += ndim\n        if axis == 0:\n            reshape_shape = [-1]\n        elif axis == ndim - 1:\n            return _op.nn.softmax(inputs[0], axis=axis)\n        else:\n            axis_val = [in_shape[i] for i in range(axis)]\n            reshape_shape = [np.prod(axis_val)] + [-1]\n        data_reshape = _op.reshape(inputs[0], newshape=reshape_shape)\n        out = _op.nn.softmax(data_reshape, axis=-1)\n        out = _op.reshape(out, newshape=in_shape)\n        return out\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, _):\n        axis = attr.get(\"axis\", -1)\n        ndim = len(infer_shape(inputs[0]))\n        if axis < 0:\n            axis += ndim\n        return _op.nn.softmax(inputs[0], axis=axis)\n\n\nclass LogSoftmax(OnnxOpConverter):\n    \"\"\"Operator converter for Softmax.\"\"\"\n\n    @classmethod\n    def run_calculation(cls, inputs, attr, params, opset):\n        \"\"\"Run the calculation for Log Softmax calculation.\"\"\"\n        res = Softmax.get_converter(opset)(inputs, attr, params)\n        return _op.log(res)\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return cls.run_calculation(inputs, attr, params, opset=1)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        return cls.run_calculation(inputs, attr, params, opset=13)\n\n\nclass Hardmax(OnnxOpConverter):\n    \"\"\"Operator converter for Hardmax.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 1)\n        ndim = len(infer_shape(inputs[0]))\n        if axis < 0:\n            axis += ndim\n        dtype = infer_type(inputs[0]).checked_type.dtype\n\n        if axis == 0:\n            pre = _op.const([1], \"int64\")\n        else:\n            pre = _op.prod(\n                _op.strided_slice(shape_of(inputs[0]), [0], [axis], [1]), axis=0, keepdims=True\n            )\n        post = _op.prod(\n            _op.strided_slice(shape_of(inputs[0]), [axis], [2147483647], [1]), axis=0, keepdims=True\n        )\n        newshape = _op.concatenate([pre, post], axis=0)\n        x = _op.reshape(inputs[0], fold_constant(newshape))\n        argmax = _op.argmax(x, axis=1)\n        onehot = _op.one_hot(\n            argmax,\n            _op.const(1.0, dtype),\n            _op.const(0.0, dtype),\n            fold_constant(_op.take(shape_of(x), _op.const([1], \"int64\"))),\n            1,\n            dtype,\n        )\n        return _op.reshape(onehot, shape_of(inputs[0]))\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params) -> relay.Expr:\n        inferred_type = infer_type(inputs[0])\n        dtype = inferred_type.checked_type.dtype\n        ndim = len(inferred_type.checked_type.shape)\n        axis = attr.get(\"axis\", -1) % ndim\n\n        argmax = _op.argmax(inputs[0], axis=axis)\n        return _op.one_hot(\n            argmax,\n            _op.const(1.0, dtype),\n            _op.const(0.0, dtype),\n            fold_constant(_op.take(shape_of(inputs[0]), _op.const([axis], \"int64\"))),\n            axis,\n            dtype,\n        )\n\n\nclass OneHot(OnnxOpConverter):\n    \"\"\"Operator converter for OneHot.\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        # Extract relay one_hot inputs.\n        indices, depth, values = inputs\n        ndim = len(infer_shape(indices))\n        # Split onnx on off values into two separate expressions.\n        off_value, on_value = _op.take(values, _op.const(0)), _op.take(values, _op.const(1))\n        # Extract the datatype of the output from on_value.\n        dtype = infer_type(on_value).checked_type.dtype\n        ind_dtype = infer_type(indices).checked_type.dtype\n        # Normalize the indices to a positive range\n        indices = _op.where(\n            indices < _op.const(0, ind_dtype), indices + _op.cast(depth, ind_dtype), indices\n        )\n        # set default value when axis is not set in the model\n        if \"axis\" not in attr:\n            attr[\"axis\"] = -1\n        axis = attr[\"axis\"]\n        if axis < 0:\n            axis += ndim + 1\n\n        return _op.one_hot(indices, on_value, off_value, depth, axis, dtype=dtype)\n\n\nclass ConstantOfShape(OnnxOpConverter):\n    \"\"\"Operator converter for ConstantOfShape.\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        if \"value\" in attr:\n            np_value = get_numpy(attr.pop(\"value\"))[0]\n            value = _expr.const(np_value)\n            dtype = np_value.dtype.name\n        else:\n            value = _expr.const(0)\n            dtype = \"float32\"\n        output = _op.full(value, inputs[0], dtype=dtype)\n        return output\n\n\nclass Constant(OnnxOpConverter):\n    \"\"\"Operator converter for ConstantOfShape.\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        if \"value\" not in attr:\n            raise tvm.errors.OpAttributeRequired(\"no value in Constant\")\n        value = attr.pop(\"value\")\n        # Constants may rarely have string types. These are likely exported\n        # from other frameworks and not actually used in TVM. We'll just use\n        # a zero valued constant for compatibility.\n        if isinstance(value, bytes):\n            np_value = np.asarray([0]).astype(\"int64\")\n        else:\n            np_value = get_numpy(value)\n        dtype = np_value.dtype.name\n        value = _expr.const(np_value, dtype)\n        return value\n\n\nclass Sign(OnnxOpConverter):\n    \"\"\"Operator converter for Sign.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return _op.sign(inputs[0])\n\n\nclass Equal(Elemwise):\n    \"\"\"Operator converter for Equal.\"\"\"\n\n    name = \"equal\"\n\n\nclass Not(Elemwise):\n    \"\"\"Operator converter for Not.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return _op.logical_not(inputs[0])\n\n\nclass And(Elemwise):\n    \"\"\"Operator converter for And.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return _op.logical_and(inputs[0], inputs[1])\n\n\nclass Tile(Elemwise):\n    \"\"\"Operator converter for Tile\"\"\"\n\n    @classmethod\n    def _impl_v6(cls, inputs, attr, params):\n        return _op.tile(inputs[0], inputs[1])\n\n\nclass Erf(OnnxOpConverter):\n    \"\"\"Operator converter for Erf\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        return _op.erf(inputs[0])\n\n\nclass Where(OnnxOpConverter):\n    \"\"\"Operator converter for Where\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        return _op.where(*inputs)\n\n\nclass Or(Elemwise):\n    \"\"\"Operator converter for Or.\"\"\"\n\n    @classmethod\n    def _impl_v7(cls, inputs, attr, params):\n        return _op.logical_or(inputs[0], inputs[1])\n\n\nclass Expand(OnnxOpConverter):\n    \"\"\"Operator converter for Expand.\"\"\"\n\n    @classmethod\n    def _impl_v8(cls, inputs, attr, params):\n        dtype = infer_type(inputs[1]).checked_type.dtype\n        in_shape = shape_of(inputs[0], dtype=dtype)\n        shape = inputs[1]\n\n        # Currently 'op.broadcast_to' expect the rank of the given 'shape'\n        # (the 2nd input) is always higher than that of the given 'input' (the 1st input)\n        # However, ONNX Expand supports multi-directional broadcasting, which allows\n        # above pattern and also some extent of 'shape' can be smaller than the corresponding\n        # extent of 'input'. In this case, the extent of 'shape' must be 1.\n        # https://github.com/onnx/onnx/blob/main/docs/Broadcasting.md\n        # In above cases, we cannot directorly apply 'op.broadcast_to' instead of 'expand'\n        # so, here we solved this problem by expanding the given 'shape' itself.\n        def expand_shape(in_shape, shape):\n            \"\"\"A function expands the shape when the rank is lower than that of the given\n            intput. Also it replaces the extent of the shape with the corresponding extent\n            of the intput when it is 1.\n            \"\"\"\n            in_dims = infer_shape(in_shape)[0]\n            new_dims = infer_shape(shape)[0]\n\n            if in_dims < new_dims:\n                in_shape = _op.concatenate(\n                    [\n                        _expr.const(\n                            [\n                                1,\n                            ]\n                            * (new_dims - in_dims),\n                            dtype=dtype,\n                        ),\n                        in_shape,\n                    ],\n                    axis=0,\n                )\n            elif new_dims < in_dims:\n                shape = _op.concatenate(\n                    [\n                        _expr.const(\n                            [\n                                1,\n                            ]\n                            * (in_dims - new_dims),\n                            dtype=dtype,\n                        ),\n                        shape,\n                    ],\n                    axis=0,\n                )\n            new_shape = _op.maximum(in_shape, shape)\n            return new_shape\n\n        shape = fold_constant(expand_shape(in_shape, shape))\n        return _op.broadcast_to(inputs[0], shape=shape)\n\n\nclass RNN(OnnxOpConverter):\n    \"\"\"Operator converter for RNNs such as RNN, LSTM and GRU.\"\"\"\n\n    @classmethod\n    def _activation_helper(cls, activation, alpha, beta):\n        convert_map = _get_convert_map(1)\n        attrs = {}\n        if alpha is not None:\n            attrs[\"alpha\"] = alpha\n        if beta is not None:\n            attrs[\"beta\"] = beta\n        return lambda x: convert_map[activation.decode(\"utf-8\")]([x], attrs, {})\n\n    @classmethod\n    def _activation_needs_alpha(cls, activation):\n        needs_alpha = [\n            \"Affine\",\n            \"LeakyRelu\",\n            \"ThresholdedRelu\",\n            \"ScaledTanh\",\n            \"HardSigmoid\",\n            \"Elu\",\n        ]\n        return activation.decode(\"utf-8\") in needs_alpha\n\n    @classmethod\n    def _activation_needs_beta(cls, activation):\n        needs_beta = [\n            \"Affine\",\n            \"ScaledTanh\",\n            \"HardSigmoid\",\n        ]\n        return activation.decode(\"utf-8\") in needs_beta\n\n    @classmethod\n    def bidir_rnn_cell(\n        cls,\n        input_seqs,\n        weight_dicts,\n        acts,\n    ):\n        \"\"\"\n        Bidirectional RNN cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t = rnn_cell(\n            input_seqs,\n            **weight_dicts[0],\n            act=acts[0],\n        )\n\n        reverse_outputs, rev_H_t = rnn_cell(\n            input_seqs,\n            **weight_dicts[1],\n            act=acts[1],\n            backwards=True,\n        )\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.stack([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=0)\n            )\n\n        return (\n            _op.stack(final_outputs, axis=0),\n            _op.stack([fw_H_t, rev_H_t], axis=0),\n        )\n\n    @classmethod\n    def _default_activations(cls, num_directions):\n        return [_op.tanh] * num_directions\n\n    @classmethod\n    def _get_activations(cls, attr, multiplier, num_directions, rnn_type):\n        \"\"\"\n        Activation functions\n        \"\"\"\n        if \"activations\" in attr:\n            activations = attr[\"activations\"]\n            if len(activations) != multiplier * num_directions:\n                raise NotImplementedError(\n                    \"{} assumes {} * num_directions activation functions are provided\".format(\n                        rnn_type, multiplier\n                    )\n                )\n            alpha_loc = 0\n            alphas = attr.get(\"activation_alpha\", [])\n            if isinstance(alphas, float):\n                alphas = [alphas]\n            beta_loc = 0\n            betas = attr.get(\"activation_beta\", [])\n            if isinstance(betas, float):\n                betas = [betas]\n            acts = []\n            for i in range(multiplier * num_directions):\n                alpha = None\n                beta = None\n                activation = activations[i]\n                if cls._activation_needs_alpha(activation) and len(alphas) > alpha_loc:\n                    alpha = alphas[alpha_loc]\n                    alpha_loc += 1\n                if cls._activation_needs_beta(activation) and len(betas) > beta_loc:\n                    beta = betas[beta_loc]\n                    beta_loc += 1\n                acts.append(cls._activation_helper(activation, alpha, beta))\n        else:\n            acts = cls._default_activations(num_directions)\n        return acts\n\n    @classmethod\n    def _inputs_helper(cls, inputs, layout):\n        \"\"\"\n        Process inputs\n        \"\"\"\n        # Unpack inputs, note that if optional and not provided then value will be None.\n        X = inputs[0]\n        Wp = inputs[1]\n        Rp = inputs[2]\n        Bp = inputs[3]\n        # Sequence length currently unused as it can be inferred from shapes.\n        # sequence_lens = inputs['sequence_lens']\n        Hp_0 = inputs[5]\n\n        num_directions = infer_shape(Wp)[0]\n\n        if num_directions not in [1, 2]:\n            raise ValueError(\"num_directions must be either 1 or 2!\")\n\n        if layout == 1:\n            X = _op.transpose(X, axes=(1, 0))\n\n        # Initialize state if not provided.\n        if Hp_0 is None:\n            W_dtype = infer_type(Wp).checked_type.dtype\n            X_shape = infer_shape(X)\n            hidden_size = infer_shape(Rp)[-1]\n            batch_size = X_shape[1]\n            Hp_0 = _op.zeros((num_directions, batch_size, hidden_size), W_dtype)\n        elif layout == 1:\n            Hp_0 = _op.transpose(Hp_0, axes=(1, 0))\n\n        # TODO (vvchernov): It can be replaced by _op.split if issue #8412 is resolved\n        X_steps = unbind(X, axis=0)\n\n        H_ts = _op.split(Hp_0, num_directions)\n        Ws = _op.split(Wp, num_directions)\n        Rs = _op.split(Rp, num_directions)\n\n        Bs = None\n        if Bp is not None:\n            Bs = _op.split(Bp, num_directions)\n        return X_steps, H_ts, Ws, Rs, Bs, num_directions\n\n    @classmethod\n    def _impl_common(cls, inputs, attr, layout):\n        X_steps, H_ts, Ws, Rs, Bs, num_directions = cls._inputs_helper(inputs, layout)\n        acts = cls._get_activations(attr, 1, num_directions, \"RNN\")\n\n        weights_dicts = []\n        for i in range(num_directions):\n            weights_dict = {}\n\n            weights_dict[\"hidden_state\"] = _op.squeeze(H_ts[i], axis=[0])\n\n            weights_dict[\"w_inp\"] = _op.squeeze(Ws[i], axis=[0])\n            weights_dict[\"w_hid\"] = _op.squeeze(Rs[i], axis=[0])\n            if Bs is not None:\n                Bi, Bh = _op.split(Bs[i], 2, -1)\n                weights_dict[\"b_inp\"] = _op.squeeze(Bi, axis=[0])\n                weights_dict[\"b_hid\"] = _op.squeeze(Bh, axis=[0])\n            weights_dicts.append(weights_dict)\n\n        if num_directions == 2:\n            output, H = RNN.bidir_rnn_cell(\n                input_seqs=X_steps,\n                weight_dicts=weights_dicts,\n                acts=acts,\n            )\n        else:\n            # outputs shape = [seqs_num, (batch_size, hidden_size)]\n            outputs, H = rnn_cell(\n                input_seqs=X_steps,\n                **weights_dicts[0],\n                act=acts[0],\n            )\n\n            # output shape = (seqs_num, num_directions, batch_size, hidden_size)\n            output = _op.expand_dims(_op.stack(outputs, axis=0), axis=1)\n            H = _op.expand_dims(H, axis=0)\n\n        if layout == 1:\n            output = _op.transpose(output, axes=(1, 0))\n            H = _op.transpose(H, axes=(1, 0))\n        return _expr.TupleWrapper(_expr.Tuple((output, H)), 2)\n\n    @classmethod\n    def _impl_v7(cls, inputs, attr, params):\n        return cls._impl_common(inputs, attr, 0)\n\n    @classmethod\n    def _impl_v14(cls, inputs, attr, params):\n        layout = attr.get(\"layout\", 0)\n        return cls._impl_common(inputs, attr, layout)\n\n\nclass LSTM(RNN):\n    \"\"\"Operator converter for LSTM\"\"\"\n\n    @classmethod\n    def bidir_lstm_cell(\n        cls,\n        input_seqs,\n        weight_dicts,\n        acts,\n    ):\n        \"\"\"\n        Bidirectional LSTM cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t, fw_C_t = lstm_cell(\n            input_seqs,\n            **weight_dicts[0],\n            f_act=acts[0],\n            g_act=acts[1],\n            h_act=acts[2],\n        )\n\n        reverse_outputs, rev_H_t, rev_C_t = lstm_cell(\n            input_seqs,\n            **weight_dicts[1],\n            f_act=acts[3],\n            g_act=acts[4],\n            h_act=acts[5],\n            backwards=True,\n        )\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.stack([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=0)\n            )\n\n        return (\n            _op.stack(final_outputs, axis=0),\n            _op.stack([fw_H_t, rev_H_t], axis=0),\n            _op.stack([fw_C_t, rev_C_t], axis=0),\n        )\n\n    @classmethod\n    def _default_activations(cls, num_directions):\n        return [_op.sigmoid, _op.tanh, _op.tanh] * num_directions\n\n    @classmethod\n    def _impl_common(cls, inputs, attr, layout):\n        X_steps, H_ts, Ws, Rs, Bs, num_directions = cls._inputs_helper(inputs, layout)\n        acts = cls._get_activations(attr, 3, num_directions, \"LSTM\")\n\n        # cell state\n        Cp_0 = inputs[6]\n        if Cp_0 is None:\n            C_ts = _expr.TupleWrapper(\n                _expr.Tuple([_op.zeros_like(H_ts[i]) for i in range(num_directions)]),\n                num_directions,\n            )\n        else:\n            if layout == 1:\n                Cp_0 = _op.transpose(Cp_0, axes=(1, 0))\n            C_ts = _op.split(Cp_0, num_directions)\n\n        # peepholes\n        Pp = inputs[7]\n        if Pp is not None:\n            p_i, p_o, p_f = _op.split(Pp, 3, axis=1)\n\n            p_is = _op.split(p_i, num_directions)\n            p_fs = _op.split(p_f, num_directions)\n            p_os = _op.split(p_o, num_directions)\n\n        weights_dicts = []\n        for i in range(num_directions):\n            weights_dict = {}\n\n            weights_dict[\"hidden_state\"] = _op.squeeze(H_ts[i], axis=[0])\n            weights_dict[\"cell_state\"] = _op.squeeze(C_ts[i], axis=[0])\n\n            # Weights permutation: onnx format i-o-f-c, lstm cell format i-f-c-o\n            mati, mato, matf, matc = _op.split(_op.squeeze(Ws[i], axis=[0]), 4)\n            weights_dict[\"w_inp\"] = _op.concatenate([mati, matf, matc, mato], axis=0)\n            mati, mato, matf, matc = _op.split(_op.squeeze(Rs[i], axis=[0]), 4)\n            weights_dict[\"w_hid\"] = _op.concatenate([mati, matf, matc, mato], axis=0)\n            if Bs is not None:\n                Bi, Bh = _op.split(Bs[i], 2, -1)\n                mati, mato, matf, matc = _op.split(_op.squeeze(Bi, axis=[0]), 4)\n                weights_dict[\"b_inp\"] = _op.concatenate([mati, matf, matc, mato], axis=0)\n                mati, mato, matf, matc = _op.split(_op.squeeze(Bh, axis=[0]), 4)\n                weights_dict[\"b_hid\"] = _op.concatenate([mati, matf, matc, mato], axis=0)\n            if Pp is not None:\n                weights_dict[\"p_i\"] = _op.squeeze(p_is[i], axis=[0])\n                weights_dict[\"p_f\"] = _op.squeeze(p_fs[i], axis=[0])\n                weights_dict[\"p_o\"] = _op.squeeze(p_os[i], axis=[0])\n            weights_dicts.append(weights_dict)\n\n        if num_directions == 2:\n            output, H, C = LSTM.bidir_lstm_cell(\n                input_seqs=X_steps,\n                weight_dicts=weights_dicts,\n                acts=acts,\n            )\n        else:\n            # outputs shape = [seqs_num, (batch_size, hidden_size)]\n            outputs, H, C = lstm_cell(\n                input_seqs=X_steps,\n                **weights_dicts[0],\n                f_act=acts[0],\n                g_act=acts[1],\n                h_act=acts[2],\n            )\n\n            # output shape = (seqs_num, num_directions, batch_size, hidden_size)\n            output = _op.expand_dims(_op.stack(outputs, axis=0), axis=1)\n            H = _op.expand_dims(H, axis=0)\n            C = _op.expand_dims(C, axis=0)\n\n        if layout == 1:\n            output = _op.transpose(output, axes=(1, 0))\n            H = _op.transpose(H, axes=(1, 0))\n            C = _op.transpose(C, axes=(1, 0))\n        return _expr.TupleWrapper(_expr.Tuple((output, H, C)), 3)\n\n\nclass GRU(RNN):\n    \"\"\"Operator convert for GRU\"\"\"\n\n    @classmethod\n    def bidir_gru_cell(\n        cls,\n        input_seqs,\n        weight_dicts,\n        acts,\n    ):\n        \"\"\"\n        Bidirectional GRU cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t = gru_cell(\n            input_seqs,\n            **weight_dicts[0],\n            rz_act=acts[0],\n            n_act=acts[1],\n        )\n\n        reverse_outputs, rev_H_t = gru_cell(\n            input_seqs,\n            **weight_dicts[1],\n            rz_act=acts[2],\n            n_act=acts[3],\n            backwards=True,\n        )\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.stack([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=0)\n            )\n\n        return (\n            _op.stack(final_outputs, axis=0),\n            _op.stack([fw_H_t, rev_H_t], axis=0),\n        )\n\n    @classmethod\n    def _default_activations(cls, num_directions):\n        return [_op.sigmoid, _op.tanh] * num_directions\n\n    @classmethod\n    def _impl_common(cls, inputs, attr, layout):\n        X_steps, H_ts, Ws, Rs, Bs, num_directions = cls._inputs_helper(inputs, layout)\n        acts = cls._get_activations(attr, 2, num_directions, \"GRU\")\n        linear_before_reset = attr.get(\"linear_before_reset\", 0)\n\n        weights_dicts = []\n        for i in range(num_directions):\n            weights_dict = {}\n\n            weights_dict[\"hidden_state\"] = _op.squeeze(H_ts[i], axis=[0])\n            weights_dict[\"linear_before_reset\"] = linear_before_reset\n\n            # Weights permutation: onnx format i-o-f-c, lstm cell format i-f-c-o\n            matz, matr, matn = _op.split(_op.squeeze(Ws[i], axis=[0]), 3)\n            weights_dict[\"w_inp\"] = _op.concatenate([matr, matz, matn], axis=0)\n            matz, matr, matn = _op.split(_op.squeeze(Rs[i], axis=[0]), 3)\n            weights_dict[\"w_hid\"] = _op.concatenate([matr, matz, matn], axis=0)\n            if Bs is not None:\n                Bi, Bh = _op.split(Bs[i], 2, -1)\n                matz, matr, matn = _op.split(_op.squeeze(Bi, axis=[0]), 3)\n                weights_dict[\"b_inp\"] = _op.concatenate([matr, matz, matn], axis=0)\n                matz, matr, matn = _op.split(_op.squeeze(Bh, axis=[0]), 3)\n                weights_dict[\"b_hid\"] = _op.concatenate([matr, matz, matn], axis=0)\n            weights_dicts.append(weights_dict)\n\n        if num_directions == 2:\n            output, H = GRU.bidir_gru_cell(\n                input_seqs=X_steps,\n                weight_dicts=weights_dicts,\n                acts=acts,\n            )\n        else:\n            # outputs shape = [seqs_num, (batch_size, hidden_size)]\n            outputs, H = gru_cell(\n                input_seqs=X_steps,\n                **weights_dicts[0],\n                rz_act=acts[0],\n                n_act=acts[1],\n            )\n\n            # output shape = (seqs_num, num_directions, batch_size, hidden_size)\n            output = _op.expand_dims(_op.stack(outputs, axis=0), axis=1)\n            H = _op.expand_dims(H, axis=0)\n\n        if layout == 1:\n            output = _op.transpose(output, axes=(1, 0))\n            H = _op.transpose(H, axes=(1, 0))\n        return _expr.TupleWrapper(_expr.Tuple((output, H)), 2)\n\n\nclass Resize(OnnxOpConverter):\n    \"\"\"Operator converter for Resize\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        mode = attr.get(\"mode\").decode(\"ascii\")\n        if mode == \"nearest\":\n            method = \"nearest_neighbor\"\n        elif mode == \"linear\":\n            method = \"linear\"\n        elif mode == \"cubic\":\n            method = \"cubic\"\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                'Value {} in attribute \"mode\" of operator Resize is not valid.'.format(mode)\n            )\n\n        scale = inputs[1]\n        size = _op.cast(shape_of(inputs[0]), infer_type(scale).checked_type.dtype) * scale\n        ndims = len(infer_shape(inputs[0]))\n        out = None\n        if ndims == 3:\n            out_size = fold_constant(_op.strided_slice(size, [2], [3]))\n            out = _op.image.resize1d(inputs[0], out_size, None, \"NCW\", method, \"asymmetric\")\n        elif ndims == 4:\n            out_size = fold_constant(_op.strided_slice(size, [2], [4]))\n            out = _op.image.resize2d(inputs[0], out_size, None, \"NCHW\", method, \"asymmetric\")\n        elif ndims == 5:\n            out_size = fold_constant(_op.strided_slice(size, [2], [5]))\n            out = _op.image.resize3d(inputs[0], out_size, None, \"NCDHW\", method, \"asymmetric\")\n        else:\n            raise NotImplementedError(\"Resize only supports 3, 4, or 5 dims\")\n        return out\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        scale = inputs[2]\n        scale_shape = infer_shape(scale)\n        if len(inputs) == 4:\n            assert (\n                len(scale_shape) == 0 or scale_shape[0] == 0\n            ), \"One of scale or size should be passed, not both.\"\n            size = inputs[3]\n        else:\n            assert len(scale_shape) != 0, \"One of scale or size should be passed.\"\n            size = _op.cast(shape_of(inputs[0]), infer_type(scale).checked_type.dtype) * scale\n        return cls.v11_13_common(inputs, size, attr, params)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        scale = inputs[2]\n        size = inputs[3]\n\n        # Some versions of onnx exporters produce an opset 13 model with the opset 11\n        # resize op, handle that edge case\n        if scale is not None and size is not None:\n            return cls._impl_v11(inputs, attr, params)\n\n        if size is not None:\n            assert scale is None, \"One of scale or size should be passed, not both.\"\n        else:\n            scale_type = infer_type(scale)\n            scale_shape = scale_type.checked_type.shape\n            scale_dtype = scale_type.checked_type.dtype\n            assert len(scale_shape) != 0, \"One of scale or size should be passed.\"\n            size = _op.cast(shape_of(inputs[0]), scale_dtype) * scale\n\n        return cls.v11_13_common(inputs, size, attr, params)\n\n    @classmethod\n    def v11_13_common(cls, inputs, size, attr, params):\n        \"\"\"\n        Resize v11 and Resize v13 are identical except in how\n        they handle the passing of scale and size. This utility\n        provides the implementation for both\n        \"\"\"\n        roi = inputs[1]\n        if roi is not None and infer_shape(roi)[0] == 0:\n            roi = None\n        ndims = len(infer_shape(inputs[0]))\n        mode = attr.get(\"mode\").decode(\"ascii\")\n        if mode == \"nearest\":\n            method = \"nearest_neighbor\"\n        elif mode == \"linear\":\n            method = \"linear\"\n        elif mode == \"cubic\":\n            method = \"cubic\"\n        else:\n            raise tvm.error.OpAttributeInvalid(\n                'Value {} in attribute \"mode\" of operator Resize is not valid.'.format(mode)\n            )\n\n        coord_trans = attr.get(\"coordinate_transformation_mode\", b\"half_pixel\").decode(\"ascii\")\n        nearest_mode = attr.get(\"nearest_mode\", b\"round_prefer_floor\").decode(\"ascii\")\n        alpha = attr.get(\"cubic_coeff_a\", -0.75)\n        exclude = attr.get(\"exclude_outside\", 0)\n        extrapolation_value = attr.get(\"extrapolation_value\", 0.0)\n\n        if roi is not None:\n            roi = fold_constant(\n                _op.concatenate(\n                    [\n                        _op.strided_slice(roi, [2], [ndims]),\n                        _op.strided_slice(roi, [ndims + 2], [2 * ndims]),\n                    ],\n                    axis=0,\n                )\n            )\n\n        out_size = fold_constant(_op.strided_slice(size, [2], [ndims]))\n\n        out = None\n        if ndims == 3:\n            out = _op.image.resize1d(\n                inputs[0],\n                out_size,\n                roi,\n                \"NCW\",\n                method,\n                coord_trans,\n                nearest_mode,\n                alpha,\n                exclude,\n                extrapolation_value,\n            )\n        elif ndims == 4:\n            out = _op.image.resize2d(\n                inputs[0],\n                out_size,\n                roi,\n                \"NCHW\",\n                method,\n                coord_trans,\n                nearest_mode,\n                alpha,\n                exclude,\n                extrapolation_value,\n            )\n        elif ndims == 5:\n            out = _op.image.resize3d(\n                inputs[0],\n                out_size,\n                roi,\n                \"NCDHW\",\n                method,\n                coord_trans,\n                nearest_mode,\n                alpha,\n                exclude,\n                extrapolation_value,\n            )\n        else:\n            raise NotImplementedError(\"Resize only supports 3, 4, or 5 dims\")\n\n        return out\n\n\nclass NonZero(OnnxOpConverter):\n    \"\"\"Operator converter for NonZero\"\"\"\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        if len(inputs) > 1:\n            raise ValueError(\"Expect 1 input only\")\n\n        output = AttrCvt(op_name=\"argwhere\")(inputs, attr, params)\n        # ONNX NonZero always outputs int64\n        output = _op.cast(output, \"int64\")\n        return _op.transpose(output, axes=(1, 0))\n\n\nclass ReverseSequence(OnnxOpConverter):\n    \"\"\"Operator converter for ReverseSequence\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n\n        return _op.reverse_sequence(inputs[0], inputs[1], attr[\"time_axis\"], attr[\"batch_axis\"])\n\n\nclass TopK(OnnxOpConverter):\n    \"\"\"Operator converter for TopK\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) != 2:\n            raise ValueError(\"Expect 2 input only\")\n        axis = attr.get(\"axis\", -1)\n        largest = attr.get(\"largest\", 1)\n\n        if largest == 0:\n            # TODO(mbrookhart): optimize this by adding a smallest attribute to topi if this\n            # ever becomes a bottleneck\n            ndim = len(infer_shape(inputs[0]))\n            if axis < 0:\n                axis += ndim\n            sort = _op.sort(inputs[0], axis=axis)\n            argsort = _op.argsort(inputs[0], axis=axis, dtype=\"int64\")\n            begin = [0] * ndim\n            stride = [1] * ndim\n            end = _op.concatenate(\n                [\n                    _op.const([np.iinfo(np.int64).max] * axis, dtype=\"int64\"),\n                    inputs[1],\n                    _op.const([np.iinfo(np.int64).max] * (ndim - axis - 1), dtype=\"int64\"),\n                ],\n                axis=0,\n            )\n            return _expr.TupleWrapper(\n                _expr.Tuple(\n                    [\n                        _op.strided_slice(sort, begin, end, stride),\n                        _op.strided_slice(argsort, begin, end, stride),\n                    ]\n                ),\n                2,\n            )\n\n        return _op.topk(inputs[0], inputs[1], axis=axis, dtype=\"int64\")\n\n\nclass Range(OnnxOpConverter):\n    \"\"\"Operator converter for Range\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) != 3:\n            raise ValueError(\"Expect 3 input only\")\n\n        return _op.arange(\n            inputs[0], inputs[1], inputs[2], dtype=infer_type(inputs[0]).checked_type.dtype\n        )\n\n\nclass IsInf(OnnxOpConverter):\n    \"\"\"Operator converter for IsInf\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        detect_negative = attr.get(\"detect_negative\", 1)\n        detect_positive = attr.get(\"detect_positive\", 1)\n        dtype = infer_type(inputs[0]).checked_type.dtype\n        isinf = _op.isinf(inputs[0])\n        if not detect_negative:\n            isinf = isinf * (inputs[0] > _op.const(0, dtype))\n        if not detect_positive:\n            isinf = isinf * (inputs[0] < _op.const(0, dtype))\n        return isinf\n\n\nclass Celu(OnnxOpConverter):\n    \"\"\"Operator convereter for celu\"\"\"\n\n    @classmethod\n    def _impl_v12(cls, inputs, attr, params):\n        x = inputs[0]\n        dtype = infer_type(x).checked_type.dtype\n        alpha = _op.const(attr.get(\"alpha\", 1.0), dtype)\n        zero = _op.const(0, dtype)\n        one = _op.const(1, dtype)\n        out = _op.maximum(zero, x) + _op.minimum(zero, alpha * (_op.exp(x / alpha) - one))\n        return out\n\n\nclass MaxRoiPool(OnnxOpConverter):\n    \"\"\"Operator converter for MaxRoiPool.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        assert len(inputs) == 2, \"MMaxRoiPool op take 2 inputs, {} given\".format(len(inputs))\n\n        data = inputs[0]\n        rois = inputs[1]\n        pooled_shape = attr.get(\"pooled_shape\")\n        spatial_scale = attr.get(\"spatial_scale\", 1.0)\n\n        return _vision.roi_pool(data, rois, pooled_shape, spatial_scale)\n\n\nclass RoiAlign(OnnxOpConverter):\n    \"\"\"Operator converter for RoiAlign.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if len(inputs) != 3:\n            raise ValueError(\"Expect 3 inputs only\")\n        x = inputs[0]\n        rois = inputs[1]\n        batch_indices = inputs[2]\n        mode = attr.get(\"mode\", b\"avg\")\n        if mode not in (b\"avg\", b\"max\"):\n            raise NotImplementedError(\"RoiAlign in Relay only uses avg and max modes\")\n        output_height = attr.get(\"output_height\", 1)\n        output_width = attr.get(\"output_width\", 1)\n\n        sampling_ratio = attr.get(\"sampling_ratio\", 0)\n        spatial_scale = attr.get(\"spatial_scale\", 1.0)\n\n        batch_indices = _op.expand_dims(batch_indices, axis=1, num_newaxis=1)\n        batch_indices = _op.cast(batch_indices, infer_type(rois).checked_type.dtype)\n        rois = _op.concatenate([batch_indices, rois], 1)\n\n        return _vision.roi_align(\n            x, rois, [output_height, output_width], spatial_scale, sampling_ratio, mode=mode\n        )\n\n\nclass Clip(OnnxOpConverter):\n    \"\"\"Operator converter for Clip.\"\"\"\n\n    @staticmethod\n    def convert_attributes(inputs, attr, params):\n        convert = AttrCvt(\"clip\", transforms={\"min\": \"a_min\", \"max\": \"a_max\"})\n        return convert(inputs, attr, params)\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        if \"min\" not in attr:\n            attr[\"min\"] = -np.inf\n        if \"max\" not in attr:\n            attr[\"max\"] = np.inf\n        return Clip.convert_attributes(inputs, attr, params)\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        if len(inputs) == 3 and isinstance(inputs[2], _expr.Constant):\n            attr[\"max\"] = inputs[2].data.numpy().item()\n            inputs = inputs[0:2]\n        if len(inputs) >= 2 and isinstance(inputs[1], _expr.Constant):\n            attr[\"min\"] = inputs[1].data.numpy().item()\n            inputs = inputs[0:1]\n        if \"min\" in attr and \"max\" in attr:\n            return Clip.convert_attributes(inputs, attr, params)\n\n        assert len(inputs) <= 3, \"Clip-11 takes up to 3 inputs, input, min, max\"\n        result = inputs[0]\n        for i, op in enumerate([_op.tensor.maximum, _op.tensor.minimum]):\n            if i < len(inputs) - 1:\n                if inputs[i + 1] is not None:\n                    result = op(result, inputs[i + 1])\n        return result\n\n\nclass Softplus(OnnxOpConverter):\n    \"\"\"Operator converter for Softplus.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        data_dtype = infer_type(data).checked_type.dtype\n        data = _op.exp(data) + _expr.const(1, dtype=data_dtype)\n        return _op.log(data)\n\n\nclass Loop(OnnxOpConverter):\n    \"\"\"Operator converter for Loop\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        max_loop_count = inputs[0]\n        cond = inputs[1]\n        loop_deps = inputs[2:]\n        num_deps = len(loop_deps)\n        # Create a copy of the body function to prevent the original\n        # from being modified.\n        body = copy.copy(attr[\"body\"])\n        iter_dtype = infer_type(max_loop_count).checked_type.dtype\n\n        # Determine what condition mode we're in.\n        assert cond is not None or max_loop_count is not None\n        is_for_loop = max_loop_count is not None and cond is None\n        is_condition_for_loop = cond is not None and max_loop_count is not None\n\n        # Loop inputs will be packed as\n        # [iter_count, max_count, condition, loop_deps, scan_outputs]\n        def cond_fn(*loop_inputs):\n            i = loop_inputs[0]\n            max_count = loop_inputs[1]\n            w = loop_inputs[2]\n\n            if cond is not None:\n                out_while = _op.equal(w, _expr.const(True, \"bool\"))\n            if max_loop_count is not None:\n                out_loop = _op.less(i, max_count)\n\n            if is_condition_for_loop:\n                return _op.logical_and(out_while, out_loop)\n            if is_for_loop:\n                return out_loop\n            return out_while\n\n        # Get the current graph proto and create a clone for the subgraph\n        graph_scope = GraphProto.current\n        subgraph_scope = GraphProto(\n            graph_scope._shape, graph_scope._dtype, graph_scope._freeze_params\n        )\n        # Load nodes from outer graph into inner graph.\n        subgraph_scope._nodes = graph_scope._nodes.copy()\n\n        # Create a list of variables for each value updated in the loop.\n        def get_var(name, val, scan=False):\n            checked_type = infer_type(val)\n            if hasattr(checked_type, \"type_annotation\"):\n                checked_type = checked_type.type_annotation\n            if hasattr(checked_type, \"checked_type\"):\n                checked_type = checked_type.checked_type\n            shape = get_const_tuple(checked_type.shape)\n            actual_shape = []\n            for dim in shape:\n                if isinstance(dim, int) and dim == 0:\n                    actual_shape.append(_ty.Any())\n                else:\n                    actual_shape.append(dim)\n            if scan:\n                return _expr.var(name, shape=[_ty.Any()] + actual_shape, dtype=checked_type.dtype)\n\n            return _expr.var(name, shape=actual_shape, dtype=checked_type.dtype)\n\n        loop_vars = [\n            _expr.var(body.input[0].name, shape=(), dtype=iter_dtype),  # iteration count\n            _expr.var(\"max_count\", shape=(), dtype=iter_dtype),  # iteration count\n            get_var(body.input[1].name, cond),  # exit condition\n        ]\n        loop_vars += [get_var(body.input[i + 2].name, v) for i, v in enumerate(loop_deps)]\n        loop_var_names = [v.name_hint for v in loop_vars]\n\n        num_scan_outputs = len(body.output) - (1 + num_deps)\n\n        # Construct variables and initial empty tensors for any scan outputs.\n        # To do this, we'll figure out the output shapes of the body subgraph by importing\n        # it and doing type inference.\n        scan_output_vars = []\n        scan_output_init = []\n        if num_scan_outputs > 0:\n            with subgraph_scope:\n                loop_outputs = subgraph_scope.from_onnx(\n                    body, graph_scope.opset, get_output_expr=True\n                )\n            loop_outputs = _expr.TupleWrapper(loop_outputs, len(body.output))\n\n        for i in range(num_scan_outputs):\n            name, _, _, _ = get_info(body.output[i + 1 + num_deps])\n            output_node = infer_type(loop_outputs[i + 1 + num_deps])\n            shape = get_const_tuple(output_node.checked_type.shape)\n            dtype = output_node.checked_type.dtype\n            scan_output_vars.append(\n                _expr.var(name, shape=([_ty.Any()] * (len(shape) + 1)), dtype=dtype)\n            )\n            scan_output_init.append(\n                _op.reshape(_expr.const(np.array([]).astype(dtype)), [0] + [1] * len(shape))\n            )\n\n        # Now we can remove loop iter variables from our inner loop's inputs.\n        # This is kind of a hack since we have graph inputs that we don't\n        # want to treat as actual inputs.\n        while len(body.input) != 0:\n            body.input.pop(0)\n\n        # Define the loop body, in this function we need to unpack loop inputs,\n        # convert the loop subgraph, and pack outputs for the next iteration.\n        def body_fn(*loop_inputs):\n            # Unpack inputs\n            loop_count = loop_inputs[0]\n            max_count = loop_inputs[1]\n            cond = loop_inputs[2]\n            current_vars = list(loop_inputs[3 : (3 + num_deps)])\n            scan_outputs = loop_inputs[(3 + num_deps) :]\n\n            # Prepare body inputs by adding them to node dictionary.\n            new_inputs = [loop_count, max_count, cond] + current_vars\n            for i, inp in enumerate(new_inputs):\n                subgraph_scope._nodes[loop_var_names[i]] = inp\n\n            # Get the output of the current loop using the updated inputs.\n            with subgraph_scope:\n                loop_outputs = subgraph_scope.from_onnx(\n                    body, graph_scope.opset, get_output_expr=True\n                )\n            # Unpack the body outputs and prepare variables for next iteration.\n            new_cond = loop_outputs[0]\n            new_loop_vars = [loop_outputs[i] for i in range(1, 1 + num_deps)]\n            new_scan_outputs = [loop_outputs[i] for i in range(1 + num_deps, len(loop_outputs))]\n\n            # Add new scan outputs to tracking\n            combined_scan_outputs = []\n            for i, scan in enumerate(scan_outputs):\n                rank = len(infer_shape(scan)) - 1\n                new_scan = new_scan_outputs[i]\n                expand_scan = _op.expand_dims(new_scan, axis=0)\n                # For non scalar outputs we need to broadcast the initial value.\n                if rank > 0:\n                    new_scan_shape = shape_of(new_scan, dtype=iter_dtype)\n                    scan_broadcast = _op.concatenate(\n                        [_op.reshape(loop_count, [1]), new_scan_shape], axis=0\n                    )\n                    scan = _op.broadcast_to(scan, scan_broadcast)\n                combined_scan = _op.concatenate([scan, expand_scan], axis=0)\n                combined_scan_outputs.append(combined_scan)\n\n            # Increment counter.\n            if max_loop_count is not None:\n                incr = _expr.const(1, dtype=iter_dtype)\n                loop_count = loop_count + incr\n\n            # Pack loop outputs for next iteration\n            # [iter_count, cond, loop_deps, loop_scans]\n            return [loop_count, max_count, new_cond] + new_loop_vars + combined_scan_outputs\n\n        # Create the loop function.\n        loop = fold_constant(_loops.while_loop(cond_fn, loop_vars + scan_output_vars, body_fn))\n\n        # Now need to run initial values through the graph.\n        init_count = _expr.const(0, dtype=iter_dtype)\n        loop_vals = loop(init_count, max_loop_count, cond, *loop_deps, *scan_output_init)\n\n        # Extract final iteration outputs.\n        if num_deps + num_scan_outputs == 1:\n            outputs = _expr.TupleGetItem(loop_vals, 3)\n        else:\n            outputs = _expr.TupleWrapper(\n                _expr.Tuple(\n                    [\n                        _expr.TupleGetItem(loop_vals, i + 3)\n                        for i in range(num_deps + num_scan_outputs)\n                    ]\n                ),\n                num_deps + num_scan_outputs,\n            )\n\n        # Update outer graph with constants found in the subgraph.\n        free_vars = analysis.free_vars(loop)\n        graph_scope._params.update(subgraph_scope._params)\n        graph_scope._nodes.update(subgraph_scope._nodes)\n        for var in free_vars:\n            graph_scope._nodes.update({var.name_hint: var})\n        return outputs\n\n\nclass If(OnnxOpConverter):\n    \"\"\"Operator converter for If\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        cond = inputs[0]\n        # Convert array to bool if needed.\n        if len(infer_shape(cond)) > 0:\n            cond = _op.take(cond, _expr.const(0, dtype=\"int64\"))\n        then_branch = attr.get(\"then_branch\", None)\n        else_branch = attr.get(\"else_branch\", None)\n        assert then_branch is not None and else_branch is not None\n\n        # Create graph converters for both branches.\n        graph_scope = GraphProto.current\n        then_graph = GraphProto(graph_scope._shape, graph_scope._dtype, graph_scope._freeze_params)\n        then_graph._nodes = graph_scope._nodes.copy()\n        else_graph = GraphProto(graph_scope._shape, graph_scope._dtype, graph_scope._freeze_params)\n        else_graph._nodes = graph_scope._nodes.copy()\n\n        # Convert each branch to a relay expression.\n        with then_graph:\n            then_expr = then_graph.from_onnx(then_branch, graph_scope.opset, get_output_expr=True)\n        with else_graph:\n            else_expr = else_graph.from_onnx(else_branch, graph_scope.opset, get_output_expr=True)\n\n        # Add constants from both branches to parent graph.\n        graph_scope._params.update(then_graph._params)\n        graph_scope._nodes.update(then_graph._nodes)\n        then_free_vars = analysis.free_vars(then_expr)\n        for var in then_free_vars:\n            graph_scope._nodes.update({var.name_hint: var})\n        graph_scope._params.update(else_graph._params)\n        graph_scope._nodes.update(else_graph._nodes)\n        else_free_vars = analysis.free_vars(else_expr)\n        for var in else_free_vars:\n            graph_scope._nodes.update({var.name_hint: var})\n\n        # Now we can construct the relay if statement and return.\n        ret = _expr.If(cond, then_expr, else_expr)\n        if len(then_branch.output) > 1:\n            ret = _expr.TupleWrapper(ret, len(then_branch.output))\n        return ret\n\n\nclass Scan(OnnxOpConverter):\n    \"\"\"Operator converter for Scan\"\"\"\n\n    @classmethod\n    def _impl_v8(cls, inputs, attr, params):\n        new_inputs = inputs[1:]\n        batch_num = infer_shape(inputs[1])[0]\n        out = []\n        for i in range(batch_num):\n            v9_inputs = [\n                _op.take(new_inputs[j], _expr.const(i), axis=0) for j in range(len(new_inputs))\n            ]\n            results = cls._impl_v9(v9_inputs, attr, params)\n            results = [_op.expand_dims(results[j], axis=0) for j in range(len(results))]\n            if i == 0:\n                out = results\n            else:\n                out = [_op.concatenate([out[j], results[j]], axis=0) for j in range(len(results))]\n\n        out = _expr.TupleWrapper(_expr.Tuple(out), len(out))\n        return out\n\n    @classmethod\n    def _impl_v9(cls, inputs, attr, params):\n        body = attr.get(\"body\")\n        num_scan_inputs = attr.get(\"num_scan_inputs\")\n        num_all_inputs = len(inputs)\n        num_state_inputs = len(body.input) - num_scan_inputs\n        num_state_outputs = num_state_inputs\n        num_all_outputs = len(body.output)\n        num_scan_outputs = num_all_outputs - num_state_outputs\n        scan_input_axes = attr.get(\"scan_input_axes\", [0] * num_scan_inputs)\n        scan_input_directions = attr.get(\"scan_input_directions\", [0] * num_scan_inputs)\n        scan_output_axes = list(attr.get(\"scan_output_axes\", [0] * num_scan_outputs))\n        scan_output_directions = attr.get(\"scan_output_directions\", [0] * num_scan_outputs)\n        # loop count are the same for all scan inputs, so get loop count by first input scan\n        # strided_slice not support dynamic axes, so assume input shape are static\n        max_loop_count = infer_shape(inputs[num_state_inputs])[scan_input_axes[0]]\n\n        # Create a copy of the body function to prevent the original\n        # from being modified.\n        body = copy.copy(attr[\"body\"])\n\n        # Loop inputs will be packed as\n        # [iter_count, loop_deps, scan_outputs]\n        def cond_fn(*loop_inputs):\n            i = loop_inputs[0]\n            return _op.less(i, relay.const(max_loop_count, \"int32\"))\n\n        # Get the current graph proto and create a clone for the subgraph\n        graph_scope = GraphProto.current\n        subgraph_scope = GraphProto(\n            graph_scope._shape, graph_scope._dtype, graph_scope._freeze_params\n        )\n        # Load nodes from outer graph into inner graph.\n        subgraph_scope._nodes = graph_scope._nodes.copy()\n\n        # Create a list of variables for each value updated in the loop.\n        def get_var(name, val, scan=False):\n            checked_type = infer_type(val)\n            if hasattr(checked_type, \"type_annotation\"):\n                checked_type = checked_type.type_annotation\n            if hasattr(checked_type, \"checked_type\"):\n                checked_type = checked_type.checked_type\n            shape = get_const_tuple(checked_type.shape)\n            actual_shape = []\n            for dim in shape:\n                if isinstance(dim, int) and dim == 0:\n                    actual_shape.append(_ty.Any())\n                else:\n                    actual_shape.append(dim)\n            if scan:\n                return _expr.var(name, shape=[_ty.Any()] + actual_shape, dtype=checked_type.dtype)\n\n            return _expr.var(name, shape=actual_shape, dtype=checked_type.dtype)\n\n        # Construct variables and initial empty tensors for any scan outputs.\n        # To do this, we'll figure out the output shapes of the body subgraph by importing\n        # it and doing type inference.\n        scan_output_vars = []\n        scan_output_init = []\n        if num_scan_outputs > 0:\n            with subgraph_scope:\n                loop_outputs = subgraph_scope.from_onnx(\n                    body, graph_scope.opset, get_output_expr=True\n                )\n            loop_outputs = _expr.TupleWrapper(loop_outputs, len(body.output))\n\n        for i in range(num_scan_outputs):\n            name, _, _, _ = get_info(body.output[i + num_state_outputs])\n            output_node = infer_type(loop_outputs[i + num_state_outputs])\n            shape = list(get_const_tuple(output_node.checked_type.shape))\n            if scan_output_axes[i] < 0:\n                scan_output_axes[i] = len(shape) + scan_output_axes[i] + 1\n            shape.insert(scan_output_axes[i], max_loop_count)\n            dtype = output_node.checked_type.dtype\n            scan_output_vars.append(_expr.var(name, shape=shape, dtype=dtype))\n            scan_output_init.append(_op.zeros(shape, dtype))\n\n        # loop vars = [iter_count, scan_state, scan_out]\n        loop_vars = [\n            _expr.var(\"iter\", shape=(), dtype=\"int32\"),  # iteration count\n        ]\n        loop_vars += [\n            get_var(body.input[i].name, v) for i, v in enumerate(inputs) if i < num_state_inputs\n        ]\n        loop_vars += scan_output_vars\n        body_input_var_names = [\"iter\"] + [body.input[i].name for i in range(len(body.input))]\n\n        # # Now we can remove loop iter variables from our inner loop's inputs.\n        # # This is kind of a hack since we have graph inputs that we don't\n        # # want to treat as actual inputs.\n        while len(body.input) != 0:\n            body.input.pop(0)\n\n        # Define the loop body, in this function we need to unpack loop inputs,\n        # convert the loop subgraph, and pack outputs for the next iteration.\n        def body_fn(*loop_inputs):\n            # Unpack inputs\n            loop_count = loop_inputs[0]\n            state_vars = list(loop_inputs[1 : 1 + num_state_inputs])\n            scan_vars = list(loop_inputs[1 + num_state_inputs :])\n            # body take scan graph scan inputs as original input\n            input_scan_exprs = []\n            for i in range(num_state_inputs, num_all_inputs):\n                if scan_input_directions[i - num_state_inputs] != 0:\n                    input_scan_exprs.append(\n                        relay.take(\n                            inputs[i],\n                            relay.const(max_loop_count - 1, \"int32\") - loop_count,\n                            axis=scan_input_axes[i - num_state_inputs],\n                        )\n                    )\n                else:\n                    input_scan_exprs.append(\n                        relay.take(\n                            inputs[i],\n                            loop_count,\n                            axis=scan_input_axes[i - num_state_inputs],\n                        )\n                    )\n\n            # Prepare body inputs by adding them to node dictionary.\n            body_inputs = [loop_count] + state_vars + input_scan_exprs\n            for i, inp in enumerate(body_inputs):\n                subgraph_scope._nodes[body_input_var_names[i]] = inp\n\n            # Get the output of the current loop using the updated inputs.\n            with subgraph_scope:\n                loop_outputs = subgraph_scope.from_onnx(\n                    body, graph_scope.opset, get_output_expr=True\n                )\n            # Unpack the body outputs and prepare variables for next iteration.\n            new_state_vars = [loop_outputs[i] for i in range(num_state_outputs)]\n            new_scan_vars = [loop_outputs[i] for i in range(num_state_outputs, num_all_outputs)]\n\n            # Add new scan outputs to tracking\n            combined_scan_outputs = []\n            for i in range(num_scan_outputs):\n                if scan_output_directions[i] == 0:\n                    # append new scan output\n                    combined_scan = _op.concatenate(\n                        [scan_vars[i], _op.expand_dims(new_scan_vars[i], axis=scan_output_axes[i])],\n                        axis=scan_output_axes[i],\n                    )\n                    # pop head scan output\n                    combined_scan = _op.strided_slice(\n                        combined_scan,\n                        begin=[1],\n                        end=[max_loop_count + 1],\n                        strides=[1],\n                        axes=[scan_output_axes[i]],\n                    )\n                else:\n                    # prepend new scan output\n                    combined_scan = _op.concatenate(\n                        [_op.expand_dims(new_scan_vars[i], axis=scan_output_axes[i]), scan_vars[i]],\n                        axis=scan_output_axes[i],\n                    )\n                    # pop tail scan output\n                    combined_scan = _op.strided_slice(\n                        combined_scan,\n                        begin=[0],\n                        end=[max_loop_count],\n                        strides=[1],\n                        axes=[scan_output_axes[i]],\n                    )\n                combined_scan_outputs.append(combined_scan)\n\n            incr = _expr.const(1, dtype=\"int32\")\n            loop_count = loop_count + incr\n\n            # Pack loop outputs for next iteration\n            # [iter_count, state_var, scan_var]\n            return [loop_count] + new_state_vars + combined_scan_outputs\n\n        # Create the loop function.\n        loop = fold_constant(_loops.while_loop(cond_fn, loop_vars, body_fn))\n\n        # Now need to run initial values through the graph.\n        init_count = _expr.const(0, dtype=\"int32\")\n\n        input_states = [inputs[i] for i in range(num_state_inputs)]\n        loop_vals = loop(init_count, *input_states, *scan_output_init)\n\n        outputs = _expr.TupleWrapper(\n            _expr.Tuple([_expr.TupleGetItem(loop_vals, i + 1) for i in range(num_all_outputs)]),\n            num_all_outputs,\n        )\n\n        # Update outer graph with constants found in the subgraph.\n        free_vars = analysis.free_vars(loop)\n        graph_scope._params.update(subgraph_scope._params)\n        graph_scope._nodes.update(subgraph_scope._nodes)\n        for var in free_vars:\n            graph_scope._nodes.update({var.name_hint: var})\n        return outputs\n\n\nclass LinearRegressor(OnnxOpConverter):\n    \"\"\"Operator converter for LinearRegressor.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        data = inputs[0]\n        coefficients = attr.get(\"coefficients\", 0)\n        data_shape = infer_shape(data)\n        targets = attr.get(\"targets\", 1)\n        coefficients = _expr.const(list(coefficients), dtype=\"float32\")\n        coefficients_shape = infer_shape(coefficients)\n\n        coefficients = _op.reshape(coefficients, (targets, coefficients_shape[0] // targets))\n        if coefficients_shape[0] // targets < data_shape[-1]:\n            data = _op.split(data, [coefficients_shape[0] // targets], -1)[0]\n\n        mm_out = _op.nn.dense(data, coefficients)\n\n        if \"intercepts\" in attr:\n            intercepts = attr.get(\"intercepts\", 0)\n            intercepts = _expr.const(list(intercepts), dtype=\"float32\")\n\n            if targets == 1:\n                return _op.nn.bias_add(mm_out, intercepts, axis=-1)\n            return get_relay_op(\"add\")(mm_out, intercepts)\n\n        return mm_out\n\n\nclass NonMaxSuppression(OnnxOpConverter):\n    \"\"\"Operator converter for NonMaxSuppression.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        # Get parameter values\n        boxes = inputs[0]\n        scores = inputs[1]\n        max_output_boxes_per_class = inputs[2]\n        iou_threshold = inputs[3]\n        score_threshold = inputs[4]\n\n        boxes_dtype = infer_type(boxes).checked_type.dtype\n\n        if attr.get(\"center_point_box\", 0) != 0:\n            xc, yc, w, h = _op.split(boxes, 4, axis=2)\n            half_w = w / _expr.const(2.0, boxes_dtype)\n            half_h = h / _expr.const(2.0, boxes_dtype)\n            x1 = xc - half_w\n            x2 = xc + half_w\n            y1 = yc - half_h\n            y2 = yc + half_h\n            boxes = _op.concatenate([y1, x1, y2, x2], axis=2)\n\n        if iou_threshold is None:\n            iou_threshold = _expr.const(0.0, dtype=\"float32\")\n        if score_threshold is None:\n            score_threshold = _expr.const(0.0, dtype=\"float32\")\n\n        def conditionally_squeeze_scalar(x):\n            rank = len(infer_shape(x))\n            assert rank <= 1, \"nms thresholds must be scalars\"\n            if rank == 1:\n                return _op.squeeze(x, [0])\n            return x\n\n        max_output_boxes_per_class = conditionally_squeeze_scalar(max_output_boxes_per_class)\n        iou_threshold = conditionally_squeeze_scalar(iou_threshold)\n        score_threshold = conditionally_squeeze_scalar(score_threshold)\n\n        nms_out = _op.vision.all_class_non_max_suppression(\n            boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold\n        )\n\n        return _op.strided_slice(nms_out[0], _op.const([0], dtype=\"int64\"), nms_out[1])\n\n\nclass ATen(OnnxOpConverter):\n    \"\"\"Operator converter for Pytorch ATen ops.\"\"\"\n\n    @classmethod\n    def _op_dispatch(cls, operator, inputs, attr, params):\n        op_map = {\n            \"size\": cls._size,\n            \"arange\": cls._arange,\n            \"index_put\": cls._index_put,\n            \"reshape\": cls._reshape,\n            \"embedding_bag\": cls._embedding_bag,\n        }\n        assert operator in op_map, \"Operator %s is not supported.\" % operator\n        return op_map[operator](inputs, attr, params)\n\n    @classmethod\n    def _size(cls, inputs, attr, params):\n        return _op.take(\n            _op.shape_of(inputs[0], dtype=\"int64\"),\n            _expr.const(-1, dtype=\"int64\"),\n            axis=0,\n            mode=\"wrap\",\n        )\n\n    @classmethod\n    def _arange(cls, inputs, attr, params):\n        return _op.arange(inputs[0], inputs[1], inputs[2], dtype=\"int64\")\n\n    @classmethod\n    def _check_index(cls, indices, values):\n        def unfolding_indices(indices, values):\n            n = len(indices)\n            flatten_indices = []\n            slices_size = []\n            for index in indices:\n                flatten_indices.append(_op.reshape(index, _op.const([-1])))\n                slices_size.append(infer_shape(flatten_indices[-1])[0])\n            repeat_size = [1]\n            tile_size = [1]\n            for i in range(1, n):\n                repeat_size.append(slices_size[-i] * repeat_size[-1])\n                tile_size.append(slices_size[i - 1] * tile_size[-1])\n            repeat_size.reverse()\n            unflod_slices = []\n            for i in range(n):\n                unflod_slices.append(\n                    fold_constant(\n                        _op.repeat(_op.tile(flatten_indices[i], (tile_size[i],)), repeat_size[i], 0)\n                    )\n                )\n            return unflod_slices, _op.reshape(values, _op.const([-1]))\n\n        values_shape = infer_shape(values)\n        if len(values_shape) != 1:\n            return unfolding_indices(indices, values)\n        return indices, values\n\n    @classmethod\n    def _index_put(cls, inputs, attr, params):\n        in_tensor = inputs[0]\n        indices, values = cls._check_index(inputs[1 : len(inputs) - 2], inputs[len(inputs) - 2])\n        accumulate = inputs[len(inputs) - 1].data.asnumpy() != 0\n        if not accumulate:\n            mode = \"update\"\n        else:\n            mode = \"add\"\n        index_tensor = _op.stack(indices, axis=0)\n        return _op.transform.scatter_nd(in_tensor, index_tensor, values, mode)\n\n    @classmethod\n    def _reshape(cls, inputs, attr, params):\n        return _op.reshape(inputs[0], inputs[1])\n\n    @classmethod\n    def _embedding_bag(cls, inputs, attr, params):\n        mode_map = {0: _op.sum, 1: _op.mean, 2: _op.max}\n\n        mode = attr.get(\"mode\", 1)\n        reduction_fn = mode_map[mode]\n        weights, indices, offsets = inputs[0], inputs[1], inputs[2]\n        offsets_shape = _op.shape_of(offsets, dtype=\"int64\")\n        indices_shape = _op.stack(\n            [\n                _op.take(offsets_shape, _expr.const(0, dtype=\"int64\")),\n                _expr.const(-1, dtype=\"int64\"),\n            ],\n            axis=0,\n        )\n        indices = _op.reshape(indices, indices_shape)\n        embedding = _op.take(weights, indices.astype(\"int64\"), axis=0)\n        rembedding = reduction_fn(embedding, axis=1)\n        # EmbeddingBag has 4 outputs for some reason despite only one ever being used.\n        # Fill the rest with 0s.\n        unused_output = _expr.const(0, dtype=\"float32\")\n        return _expr.TupleWrapper(\n            _expr.Tuple((rembedding, unused_output, unused_output, unused_output)), 4\n        )\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        operator = attr.get(\"operator\", None).decode(\"utf-8\")\n        assert operator, \"ATen Operator not found\"\n        return cls._op_dispatch(operator, inputs, attr, params)\n\n\nclass QuantizeLinear(OnnxOpConverter):\n    \"\"\"Operator converter for QuantizeLinear.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        data, scale, zp = inputs\n        out_dtype = infer_type(zp).checked_type.dtype\n        return _qnn.op.quantize(data, scale, _op.cast(zp, \"int32\"), 0, out_dtype)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        data, scale, zp = inputs\n        out_dtype = infer_type(zp).checked_type.dtype\n        axis = attr.get(\"axis\", 1)\n        if len(infer_shape(data)) < 2:\n            axis = 0\n        return _qnn.op.quantize(data, scale, _op.cast(zp, \"int32\"), axis, out_dtype)\n\n\nclass DequantizeLinear(OnnxOpConverter):\n    \"\"\"Operator converter for QuantizeLinear.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        data, scale, zp = inputs\n        return _qnn.op.dequantize(data, scale, _op.cast(zp, \"int32\"), 0)\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        data, scale, zp = inputs\n        axis = attr.get(\"axis\", 1)\n        if len(infer_shape(data)) <= 1:\n            axis = 0\n        return _qnn.op.dequantize(data, scale, _op.cast(zp, \"int32\"), axis)\n\n\nclass DynamicQuantizeLinear(OnnxOpConverter):\n    \"\"\"Operator converter for QuantizeLinear.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        \"\"\"This op is deprecated an only supports uint8\"\"\"\n        data = inputs[0]\n        data_dtype = infer_type(data).checked_type.dtype\n        zero = _op.const(0, dtype=data_dtype)\n        maximum = _op.maximum(zero, _op.max(data))\n        minimum = _op.minimum(zero, _op.min(data))\n        scale = (maximum - minimum) / _op.const(255, dtype=data_dtype)\n        zp = zero - _op.min(data) / scale\n        zp = _op.cast(_op.round(_op.clip(zp, 0, 255)), \"uint8\")\n        return _expr.TupleWrapper(\n            _expr.Tuple(\n                [_qnn.op.quantize(data, scale, _op.cast(zp, \"int32\"), 0, \"uint8\"), scale, zp]\n            ),\n            size=3,\n        )\n\n\nclass QLinearConv(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearConv.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        data = inputs[0]\n        x_scale = get_scalar(inputs[1], params)\n        x_zero_point = get_scalar(inputs[2], params, \"int32\")\n        weight = inputs[3]\n        w_scale = get_scalar_or_1d_tensor(inputs[4], params)\n        w_zero_point = get_scalar_or_1d_tensor(inputs[5], params, \"int32\")\n        y_scale = fold_constant(get_scalar(inputs[6], params))\n        y_zero_point = get_scalar(inputs[7], params, \"int32\")\n\n        # Check shapes for per channel quantization\n        w_scale_shape = infer_shape(w_scale)\n        w_zero_point_shape = infer_shape(w_zero_point)\n        if len(w_scale_shape) == 1 or len(w_zero_point_shape) == 1:\n            m = infer_shape(weight)[0]\n            if m != w_scale_shape[0] or m != w_zero_point_shape[0]:\n                raise tvm.error.OpAttributeInvalid(\n                    \"The number of elements should be equal to the number of output channels\"\n                )\n\n        input_shape = infer_shape(data)\n\n        ndim = len(input_shape)\n        kernel_type = infer_type(weight)\n        kernel_shapes = [get_const_tuple(kernel_type.checked_type.shape)]\n        if \"kernel_shape\" not in attr:\n            attr[\"kernel_shape\"] = kernel_shapes[0][2:]\n\n        if \"auto_pad\" in attr:\n            attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: Convolution does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                zp = fold_constant(x_zero_point)\n                assert isinstance(zp, relay.Constant), \"Zero point expected to be a constant\"\n                data = autopad(\n                    data,\n                    attr.get(\"strides\", [1] * (ndim - 2)),\n                    attr[\"kernel_shape\"],\n                    attr.get(\"dilations\", [1] * (ndim - 2)),\n                    pad_value=zp.data,\n                    mode=attr[\"auto_pad\"],\n                )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n            attr.pop(\"auto_pad\")\n\n        out_channels = kernel_shapes[0][0]\n        dilation = attr.get(\"dilations\", [1] * (ndim - 2))\n        strides = attr.get(\"strides\", [1] * (ndim - 2))\n        padding = attr[\"pads\"] if \"pads\" in attr else 0\n        groups = attr[\"group\"] if \"group\" in attr else 1\n\n        if ndim != 4:\n            raise tvm.error.OpAttributeInvalid(\n                \"Only 2D kernels are supported for operator QLinearConv.\"\n            )\n\n        out = _qnn.op.conv2d(\n            data,\n            weight,\n            x_zero_point,\n            w_zero_point,\n            x_scale,\n            w_scale,\n            kernel_size=attr[\"kernel_shape\"],\n            channels=out_channels,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n        )\n        use_bias = len(inputs) == 9\n        if use_bias:\n            out = _op.nn.bias_add(out, inputs[8])\n\n        out_dtype = infer_type(inputs[7]).checked_type.dtype\n        requantize_scale = _op.multiply(x_scale, w_scale)\n\n        # requantize requires y_scale to be constant,\n        # if y_scale is not constant, doing dequantize -> quantize\n        if isinstance(y_scale, _expr.Constant):\n            out = _qnn.op.requantize(\n                out,\n                requantize_scale,\n                _op.const(0, dtype=\"int32\"),\n                y_scale,\n                y_zero_point,\n                out_dtype=out_dtype,\n                axis=1,\n            )\n        else:\n            out = _qnn.op.dequantize(out, requantize_scale, _op.const(0, dtype=\"int32\"), axis=1)\n            out = _qnn.op.quantize(out, y_scale, y_zero_point, axis=1, out_dtype=out_dtype)\n        return out\n\n\nclass QLinearAdd(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearAdd from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        a = inputs[0]\n        a_scale = get_scalar(inputs[1], params)\n        a_zero_point = get_scalar(inputs[2], params, \"int32\")\n        b = inputs[3]\n        b_scale = get_scalar(inputs[4], params)\n        b_zero_point = get_scalar(inputs[5], params, \"int32\")\n        c_scale = get_scalar(inputs[6], params)\n        c_zero_point = get_scalar(inputs[7], params, \"int32\")\n\n        dtype = infer_type(a).checked_type.dtype\n\n        ## Onnxruntime doesn't actually do this op in integer, they dequantize to fp32\n        ## and then requantize afer\n        ## https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/core/mlas/lib/qladd.cpp\n        a = _qnn.op.dequantize(\n            inputs[0], a_scale, a_zero_point\n        )  # , c_scale, c_zero_point, out_dtype = dtype)\n        b = _qnn.op.dequantize(\n            inputs[3], b_scale, b_zero_point\n        )  # , c_scale, c_zero_point, out_dtype = dtype)\n        out = _op.add(a, b)\n        return _qnn.op.quantize(out, c_scale, c_zero_point, out_dtype=dtype)\n\n\nclass QLinearMatMul(OnnxOpConverter):\n    \"\"\"\n    Operator converter for QLinearMatMul from Microsoft onnxruntime contrib opset.\n\n    Limitations:\n    - Not guaranteed to meet the integer-overflow behavior stipulated in the\n      ONNX documentation for this operator.\n\n    The QLinearMatMul converter is re-used for MatMulInteger and is adapted for\n    the latter with the optional `expected_out_dtypes` argument.\n    \"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params, expected_out_dtypes=None):\n        if expected_out_dtypes is None:\n            # The default QLinearMatMul converter is expected to have one of\n            # these output dtypes.\n            expected_out_dtypes = [\"int8\", \"uint8\"]\n\n        # Some of the ops used below take scalar-like inputs, and may require either\n        # of the following:\n        #\n        # - the input is Const node (not merely an expression that *could* be reduced\n        #   to a single Const at graph-compilation time)\n        #\n        # - the input has a specific dtype\n        #\n        # This function attempts to present 'x' in a form that meets both of those\n        # requirements.\n        def try_resolve_to_const(x, dtype_override=None):\n            x2 = try_resolve_var_to_const(x, params)\n            num_elem = np.prod(infer_shape(x))\n            if num_elem == 1:\n                x2 = ensure_scalar_shape(x2)\n            x_dtype = infer_type(x).checked_type.dtype\n            if (dtype_override is not None) and (dtype_override != x_dtype):\n                x2 = _op.cast(x2, dtype_override)\n            x3 = fold_constant(x2)\n            return x3\n\n        # Unpack the inputs and obtain some type info...\n        a, a_scale, a_zp, b, b_scale, b_zp, y_scale, y_zp = inputs\n\n        a_type = infer_type(a).checked_type  # 'T1' in ONNX doc for this op\n        a_scale_type = infer_type(a_scale).checked_type\n        a_zp_type = infer_type(a_zp).checked_type\n\n        b_type = infer_type(b).checked_type  # 'T2' in ONNX doc for this op\n        b_scale_type = infer_type(b_scale).checked_type\n        b_zp_type = infer_type(b_zp).checked_type\n\n        y_scale_type = infer_type(y_scale).checked_type\n        y_zp_type = infer_type(y_zp).checked_type  # 'T3' in ONNX doc for this op\n\n        # Verify type assumptions, based on the ONNX doc for this op...\n        assert a_type.dtype in [\"int8\", \"uint8\"]\n        assert a_scale_type.dtype == \"float32\"\n        assert a_zp_type.dtype == a_type.dtype\n\n        assert b_type.dtype in [\"int8\", \"uint8\"]\n        assert b_scale_type.dtype == \"float32\"\n        assert b_zp_type.dtype == b_type.dtype\n\n        assert y_scale_type.dtype == \"float32\"\n        assert y_zp_type.dtype in expected_out_dtypes\n\n        # _qnn.op.dense requires the zero-point values to have dtype int32.\n        a_scale_scalar = try_resolve_to_const(a_scale)\n        a_zp_scalar = try_resolve_to_const(a_zp, \"int32\")\n\n        b_scale_scalar = try_resolve_to_const(b_scale)\n        b_zp_scalar = try_resolve_to_const(b_zp, \"int32\")\n\n        y_scale_scalar = try_resolve_to_const(y_scale)\n        y_zp_scalar = try_resolve_to_const(y_zp, \"int32\")\n\n        # TODO: Confirm that we're using 'num_hidden_units' correctly / as intended with\n        # the '_qnn.op.dense' instance below.\n        num_hidden_units = infer_shape(b)[-1]\n\n        # - Specify the matmul result dtype as int32, so that hopefully the matmul will use\n        #   a 32-bit accumulator as seems to be required by the ONNX op's documentation.\n        #\n        # TL;DR:\n        # The ONNX documentation for this op is clear about acceptable overflow\n        # behavior during the matmul operation:\n        #   - The scalar multiplication ops MAY NOT overflow.\n        #   - The scalar addition ops, which sum the results of the scalar multiplication,\n        #     MAY overflow, but if they do so, it must behave as one would expect during\n        #     32-bit integer-addition overflow.\n        # As of this writing, Relay's qnn.op.dense operator doesn't expose a way for us to\n        # express these constraints.\n        #\n        # TODO: Extend TVM / Relay / TIR / etc. to allow this kind of constraint to be\n        # expressed in a Relay graph. And then update this importer and various TVM\n        # backends accordingly.\n        matmul_result_dtype = \"int32\"\n        # TODO(vvchernov): possibly it is better to use unsigned type for result\n        # if input types are unsigned:\n        # if a_type.dtype == \"uint8\" and b_type.dtype == \"uint8\":\n        #     matmul_result_dtype = \"uint32\"\n\n        matmul_result = qmatmul(\n            a,\n            b,\n            a_zp_scalar,\n            b_zp_scalar,\n            a_scale_scalar,\n            b_scale_scalar,\n            num_hidden_units,\n            matmul_result_dtype,\n        )\n\n        # This information might only be found in the C++ code-comments for the\n        # dense.matmul op, but the quantized tensor returned by _qnn.op.dense\n        # has scale==(a_scale_scalar * b_scale_scalar), and zero_point==0.\n        #\n        # 'matmul_result_zp_scalar' has type 'int32' to satisfy input requirements\n        # of the [de/re]quantize ops below.\n        matmul_result_scale_scalar = fold_constant(_op.multiply(a_scale_scalar, b_scale_scalar))\n        matmul_result_zp_scalar = _op.const(0, dtype=\"int32\")\n\n        if \"int32\" in expected_out_dtypes:\n            # This is the adaptation of the QLinearMatMul converter for MatMulInteger,\n            # in the MatMulInteger case we skip the unnecessary requantization step.\n            return matmul_result\n\n        # requantize requires y_scale to be constant,\n        # if y_scale is not constant, doing dequantize -> quantize\n        if isinstance(y_scale_scalar, _expr.Constant):\n            y = _qnn.op.requantize(\n                matmul_result,\n                matmul_result_scale_scalar,\n                matmul_result_zp_scalar,\n                y_scale_scalar,\n                y_zp_scalar,\n                axis=-1,\n                rounding=\"TONEAREST\",\n                out_dtype=y_zp_type.dtype,\n            )\n        else:\n            matmul_result_deq = _qnn.op.dequantize(\n                matmul_result, matmul_result_scale_scalar, matmul_result_zp_scalar, axis=0\n            )\n\n            y = _qnn.op.quantize(\n                matmul_result_deq, y_scale_scalar, y_zp_scalar, axis=0, out_dtype=y_zp_type.dtype\n            )\n\n        return y\n\n\nclass MatMulInteger(OnnxOpConverter):\n    \"\"\"Operator converter for MatMulInteger.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        a = inputs[0]\n        b = inputs[1]\n\n        a_dtype = infer_type(a).checked_type.dtype\n        b_dtype = infer_type(b).checked_type.dtype\n\n        assert a_dtype in (\"int8\", \"uint8\"), \"MatMulInteger: invalid dtype for first input\"\n        assert b_dtype in (\"int8\", \"uint8\"), \"MatMulInteger: invalid dtype for second input\"\n\n        assert a_dtype == b_dtype, \"MatMulInteger: input dtypes must match\"\n\n        a_scale = _op.const(1.0, dtype=\"float32\")\n        b_scale = _op.const(1.0, dtype=\"float32\")\n        out_scale = _op.const(1.0, dtype=\"float32\")\n\n        a_zero_point = _op.const(0.0, dtype=a_dtype)\n        b_zero_point = _op.const(0.0, dtype=b_dtype)\n        out_zero_point = _op.const(0.0, dtype=\"int32\")\n\n        if len(inputs) == 4:\n            a_zero_point = inputs[2]\n            b_zero_point = inputs[3]\n\n            a_zp_dtype = infer_type(a_zero_point).checked_type.dtype\n            b_zp_dtype = infer_type(b_zero_point).checked_type.dtype\n            assert (\n                a_zp_dtype == a_dtype and b_zp_dtype == b_dtype\n            ), \"MatMulInteger: input dtype doesn't match zero point dtype\"\n        elif len(inputs) != 2:\n            raise AssertionError(\n                \"MatMulInteger op takes 2 or 4 inputs, {} given\".format(len(inputs))\n            )\n\n        inputs = [\n            a,\n            a_scale,\n            a_zero_point,\n            b,\n            b_scale,\n            b_zero_point,\n            out_scale,\n            out_zero_point,\n        ]\n\n        return QLinearMatMul.get_converter(10)(inputs, attr, params, expected_out_dtypes=[\"int32\"])\n\n\nclass QLinearMul(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearMul from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        a = inputs[0]\n        a_scale = get_scalar(inputs[1], params)\n        a_zero_point = get_scalar(inputs[2], params, \"int32\")\n        b = inputs[3]\n        b_scale = get_scalar(inputs[4], params)\n        b_zero_point = get_scalar(inputs[5], params, \"int32\")\n        y_scale = fold_constant(get_scalar(inputs[6], params))\n        y_zero_point = get_scalar(inputs[7], params, \"int32\")\n\n        dtype = infer_type(a).checked_type.dtype\n\n        ## Onnxruntime doesn't actually do this op in integer, they dequantize to fp32\n        ## and then requantize afer\n        ## https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/core/mlas/lib/qlmul.cpp\n        a = _qnn.op.dequantize(inputs[0], a_scale, a_zero_point)\n        b = _qnn.op.dequantize(inputs[3], b_scale, b_zero_point)\n        out = _op.multiply(a, b)\n        return _qnn.op.quantize(out, y_scale, y_zero_point, out_dtype=dtype)\n\n\nclass QLinearLeakyRelu(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearLeakyRelu from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n\n        a_scale = get_scalar(inputs[1], params)\n        a_zero_point = get_scalar(inputs[2], params, \"int32\")\n        y_scale = fold_constant(get_scalar(inputs[3], params))\n        y_zero_point = get_scalar(inputs[4], params, \"int32\")\n        alpha = float(attr.get(\"alpha\", 1.0))\n\n        dtype = infer_type(inputs[0]).checked_type.dtype\n\n        # Onnxruntime doesn't actually do this op in integer, they dequantize to fp32\n        # and then requantize afer (according to documentation below)\n        # https://github.com/microsoft/onnxruntime/blob/master/docs/ContribOperators.md#com.microsoft.QLinearLeakyRelu\n        a = _qnn.op.dequantize(inputs[0], a_scale, a_zero_point)\n        out = _op.nn.leaky_relu(a, alpha)\n        return _qnn.op.quantize(out, y_scale, y_zero_point, out_dtype=dtype)\n\n\nclass QLinearSigmoid(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearSigmoid from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        x = inputs[0]\n        x_scale = get_scalar(inputs[1], params)\n        x_zero_point = get_scalar(inputs[2], params, \"int32\")\n        y_scale = fold_constant(get_scalar(inputs[3], params))\n        y_zero_point = get_scalar(inputs[4], params, \"int32\")\n\n        dtype = infer_type(x).checked_type.dtype\n\n        ## Apparently, onnxruntime doesn't do this op in integer, they dequantize to fp32\n        ## and then requantize after:\n        ## https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/core/\n        ## providers/dml/DmlExecutionProvider/src/GraphTransformer.cpp#L245\n        x = _qnn.op.dequantize(x, x_scale, x_zero_point)\n        out = _op.sigmoid(x)\n        return _qnn.op.quantize(out, y_scale, y_zero_point, out_dtype=dtype)\n\n\nclass QLinearConcat(OnnxOpConverter):\n    \"\"\"Operator converter for QLinearConcat from Microsoft onnxruntime contrib opset.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        # which axis to concat on\n        axis = attr[\"axis\"]\n\n        y_scale = fold_constant(get_scalar(inputs[0], params))\n        y_zero_point = get_scalar(inputs[1], params, \"int32\")\n\n        # input tensors, scales, zero_points\n        assert (\n            len(inputs) % 3 == 2\n        ), \"Additional input count must be a multiple of 3 -- tensor/scale/zero_point tuples\"\n        tensors = []\n        scales = []\n        zero_points = []\n        for i in range(2, len(inputs), 3):\n            tensors.append(inputs[i])\n            scales.append(get_scalar(inputs[i + 1], params))\n            zero_points.append(get_scalar(inputs[i + 2], params, \"int32\"))\n\n        return _qnn.op.concatenate(tensors, scales, zero_points, y_scale, y_zero_point, axis)\n\n\nclass ConvInteger(OnnxOpConverter):\n    \"\"\"Operator converter for ConvInteger.\"\"\"\n\n    @classmethod\n    def _impl_v10(cls, inputs, attr, params):\n        data = inputs[0]\n        weight = inputs[1]\n        data_zp = inputs[2]\n        weight_zp = inputs[3]\n        if data_zp is None:\n            data_zp = _expr.const(0, \"int32\")\n        if weight_zp is None:\n            weight_zp = _expr.const(0, \"int32\")\n\n        input_type = infer_type(data)\n        input_shape = get_const_tuple(input_type.checked_type.shape)\n\n        ndim = len(input_shape)\n        kernel_type = infer_type(weight)\n        kernel_shape = get_const_tuple(kernel_type.checked_type.shape)\n        if \"kernel_shape\" not in attr:\n            attr[\"kernel_shape\"] = kernel_shape[2:]\n\n        if \"auto_pad\" in attr:\n            attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n            if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n                # Warning: Convolution does not yet support dynamic shapes,\n                # one will need to run dynamic_to_static on this model after import\n                data = autopad(\n                    data,\n                    attr.get(\"strides\", [1] * (ndim - 2)),\n                    attr[\"kernel_shape\"],\n                    attr.get(\"dilations\", [1] * (ndim - 2)),\n                    pad_value=data_zp,\n                    mode=attr[\"auto_pad\"],\n                )\n            elif attr[\"auto_pad\"] == \"VALID\":\n                attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n            elif attr[\"auto_pad\"] == \"NOTSET\":\n                pass\n            else:\n                msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n                raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n            attr.pop(\"auto_pad\")\n\n        out_channels = kernel_shape[0]\n        dilation = attr.get(\"dilations\", [1] * (ndim - 2))\n        strides = attr.get(\"strides\", [1] * (ndim - 2))\n        padding = attr[\"pads\"] if \"pads\" in attr else 0\n        groups = attr[\"group\"] if \"group\" in attr else 1\n\n        if ndim != 4:\n            raise tvm.error.OpAttributeInvalid(\n                \"Only 2D kernels are supported for operator ConvInteger.\"\n            )\n\n        return _qnn.op.conv2d(\n            data,\n            weight,\n            _op.cast(data_zp, \"int32\"),\n            _op.cast(weight_zp, \"int32\"),\n            _expr.const(1.0, \"float32\"),\n            _expr.const(1.0, \"float32\"),\n            kernel_size=attr[\"kernel_shape\"],\n            channels=out_channels,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n        )\n\n\nclass BitShift(OnnxOpConverter):\n    \"\"\"Operator converter for NonZero\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        if len(inputs) != 2:\n            raise ValueError(\"Bitshift expects 2 inputs\")\n\n        direction = attr.get(\"direction\", \"LEFT\").decode(\"ascii\")\n        if direction == \"LEFT\":\n            out = _op.left_shift(*inputs)\n        elif direction == \"RIGHT\":\n            out = _op.right_shift(*inputs)\n        else:\n            raise ValueError(\"Unsupported Shift Direction: \" + direction)\n        return out\n\n\nclass Unique(OnnxOpConverter):\n    \"\"\"Operator converter for unique\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        if len(inputs) != 1:\n            raise ValueError(\"Unique expects 1 input\")\n\n        data = inputs[0]\n        axis = attr.get(\"axis\", None)\n        if axis is None:  # If axis is None, flatten the input before calling unique\n            data = _op.reshape(data, _op.const([-1]))\n        else:\n            data_shape = infer_shape(data)\n            if len(data_shape) != 1:\n                raise ValueError(\"TVM only supports 1D Unique operator.\")\n        is_sorted = attr.get(\"sorted\", 1)  # sorted is 0 or 1, 1 by default\n\n        # ONNX documentation lists return_counts as optional but there is no input to specify\n        # whether it is returned. Therefore we'll just always return it.\n        unique = _op.unique(data, is_sorted=(is_sorted == 1), return_counts=True)\n        num_unique = unique[3]\n\n        trim_unique_lambda = lambda input: _op.strided_slice(input, _op.const([0]), num_unique)\n\n        unique_vals = trim_unique_lambda(unique[0])\n        indices = _op.cast(trim_unique_lambda(unique[1]), \"int64\")  # ONNX always returns int64\n        inverse_indices = _op.cast(unique[2], \"int64\")  # ONNX always returns int64\n        counts = _op.cast(trim_unique_lambda(unique[4]), \"int64\")  # ONNX always returns int64\n        # ONNX unique returns unique, indices, inverse_indices, (optional) counts\n        return _expr.TupleWrapper(_expr.Tuple([unique_vals, indices, inverse_indices, counts]), 4)\n\n\nclass Einsum(OnnxOpConverter):\n    \"\"\"Operator converter for Einsum\"\"\"\n\n    @classmethod\n    def _impl_v12(cls, inputs, attr, params):\n        equation = attr[\"equation\"].decode(\"utf-8\")\n        return _op.einsum(inputs, equation)\n\n\nclass Trilu(OnnxOpConverter):\n    \"\"\"Operator converter for Trilu\"\"\"\n\n    @classmethod\n    def _impl_v14(cls, inputs, attr, params):\n        upper = attr.get(\"upper\", True)\n        if len(inputs) == 2:\n            data, k = inputs\n        else:\n            data = inputs[0]\n            k = 0\n        return _op.trilu(data, k, upper)\n\n\nclass GridSample(OnnxOpConverter):\n    \"\"\"Operator converter for GridSample\"\"\"\n\n    @classmethod\n    def _impl_v16(cls, inputs, attr, params):\n        grid = inputs[1]\n        # onnx grid is of shape (N, H, W, 2) which should be transposed to (N, 2, H, W) for relay\n        grid = _op.transform.transpose(grid, axes=(0, 3, 1, 2))\n        method: str = attr.get(\"mode\", b\"bilinear\").decode(\"utf-8\")\n        padding_mode: str = attr.get(\"padding_mode\", b\"zeros\").decode(\"utf-8\")\n        # onnx default is 0 which should be changed to False in relay\n        align_corners = attr.get(\"align_corners\", 0) != 0\n        return _op.image.grid_sample(\n            inputs[0], grid, method, padding_mode=padding_mode, align_corners=align_corners\n        )\n\n\nclass RandomNormal(OnnxOpConverter):\n    \"\"\"Operator converter for random_normal\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = get_type(attr.get(\"dtype\", 1))\n        mean = attr.get(\"mean\", 0.0)\n        scale = attr.get(\"scale\", 1.0)\n        seed = attr.get(\"seed\", None)\n        shape = attr[\"shape\"]\n\n        assert dtype in [\n            \"float32\",\n            \"float64\",\n        ], \"Only float random value generation is currently supported.\"\n\n        if seed is None:\n            seed = np.random.randint(1e6)\n        else:\n            seed = int(seed)\n        key = _random.threefry_key(seed)\n        output = _op.random.normal(key, shape, dtype=dtype, mean=mean, scale=scale)\n        _, vals = _expr.TupleWrapper(output, 2)\n        return vals\n\n\nclass RandomNormalLike(OnnxOpConverter):\n    \"\"\"Operator converter for random_normal_like\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = attr.get(\"dtype\", None)\n        scale = attr.get(\"scale\", 1.0)\n        mean = attr.get(\"mean\", 0.0)\n        seed = attr.get(\"seed\", None)\n        shape = infer_shape(inputs[0])\n        if dtype is None:\n            dtype = infer_type(inputs[0]).checked_type.dtype\n        else:\n            dtype = get_type(dtype)\n\n        assert dtype in [\n            \"float32\",\n            \"float64\",\n        ], \"Only float random value generation is currently supported.\"\n\n        if seed is None:\n            seed = np.random.randint(1e6)\n        else:\n            seed = int(seed)\n        key = _random.threefry_key(seed)\n        output = _op.random.normal(key, shape, dtype=dtype, mean=mean, scale=scale)\n        _, vals = _expr.TupleWrapper(output, 2)\n        return vals\n\n\nclass RandomUniform(OnnxOpConverter):\n    \"\"\"Operator converter for random_uniform\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = get_type(attr.get(\"dtype\", 1))\n        high = attr.get(\"high\", 1.0)\n        low = attr.get(\"low\", 0.0)\n        seed = attr.get(\"seed\", None)\n        shape = attr[\"shape\"]\n\n        assert dtype in [\n            \"float32\",\n            \"float64\",\n        ], \"Only float random value generation is currently supported.\"\n\n        if seed is None:\n            seed = np.random.randint(1e6)\n        else:\n            seed = int(seed)\n        key = _random.threefry_key(seed)\n        output = _op.random.uniform(key, shape, dtype=dtype, low=low, high=high)\n        _, vals = _expr.TupleWrapper(output, 2)\n        return vals\n\n\nclass RandomUniformLike(OnnxOpConverter):\n    \"\"\"Operator converter for random_uniform_like\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        dtype = attr.get(\"dtype\", None)\n        high = attr.get(\"high\", 1.0)\n        low = attr.get(\"low\", 0.0)\n        seed = attr.get(\"seed\", None)\n        shape = infer_shape(inputs[0])\n        if dtype is None:\n            dtype = infer_type(inputs[0]).checked_type.dtype\n        else:\n            dtype = get_type(dtype)\n\n        assert dtype in [\n            \"float32\",\n            \"float64\",\n        ], \"Only float random value generation is currently supported.\"\n\n        if seed is None:\n            seed = np.random.randint(1e6)\n        else:\n            seed = int(seed)\n        key = _random.threefry_key(seed)\n        output = _op.random.uniform(key, shape, dtype=dtype, low=low, high=high)\n        _, vals = _expr.TupleWrapper(output, 2)\n        return vals\n\n\nclass Multinomial(OnnxOpConverter):\n    \"\"\"Operator converter for multinomial\"\"\"\n\n    @classmethod\n    def _impl_v7(cls, inputs, attr, params):\n        dtype = attr.get(\"dtype\", \"int64\")\n        sample_size = attr.get(\"sample_size\", 1)\n        seed = attr.get(\"seed\", None)\n        if seed is None:\n            seed = np.random.randint(1e6)\n        key = _op.random.threefry_key(seed)\n        output = _op.random.multinomial(key, inputs[0], sample_size)\n        _, indices = _expr.TupleWrapper(output, 2)\n        return _op.cast(indices, get_type(dtype))\n\n\nclass NegativeLogLikelihoodLoss(OnnxOpConverter):\n    \"\"\"Operator converter for NegativeLogLikehoodLoss\"\"\"\n\n    VALID_REDUCTIONS = {\"mean\", \"sum\", \"none\"}\n\n    @classmethod\n    def run_calculation(\n        cls: \"NegativeLogLikelihoodLoss\",\n        input_tensor: relay.Expr,\n        target_tensor: relay.Expr,\n        weight_tensor: Optional[relay.Expr],\n        ignore_index: int,\n    ):\n        \"\"\"Run calculation for NegativeLogLikelihood, returning output tensor and\n        weight tensor used for mean-style reductions.\n        \"\"\"\n        # Convert negative indices --> positive indices for gather ops, note we have to\n        # use the original target tensor to interact with ignore_index to have proper behavior.\n        normalized_target_tensor = normalize_gather_indices(input_tensor, target_tensor, 1)\n\n        if weight_tensor is None:\n            channels = infer_shape(input_tensor)[1]\n            weight_tensor = relay.ones(\n                [channels],\n                dtype=infer_type(input_tensor).checked_type.dtype,\n            )\n\n        loss = -relay.gather(\n            input_tensor,\n            axis=1,\n            indices=relay.expand_dims(normalized_target_tensor, 1),\n        )\n        loss = relay.squeeze(loss, axis=[1])\n\n        expanded_normalized_target_tensor = relay.expand_dims(normalized_target_tensor, 0)\n        expanded_normalized_target_tensor = relay.nn.batch_flatten(\n            expanded_normalized_target_tensor\n        )\n        flattened_weights = relay.gather_nd(weight_tensor, expanded_normalized_target_tensor)\n        select_weights = relay.reshape_like(flattened_weights, loss)\n        loss *= select_weights\n\n        if ignore_index is not None:\n            # \"Ignore\" values whose target is the ignore_index\n            mask_tensor = relay.equal(\n                target_tensor, relay.const(ignore_index, dtype=target_tensor.type_annotation.dtype)\n            )\n            mask_tensor = relay.const(1, dtype=\"int8\") - relay.cast(mask_tensor, \"int8\")\n            loss = relay.where(\n                mask_tensor, loss, relay.const(0, infer_type(loss).checked_type.dtype)\n            )\n\n            # This is not explained super clearly in the onnx spec, but masked values don't\n            # contribute toward the final value in reduction\n            select_weights *= relay.cast_like(mask_tensor, select_weights)\n\n        weight_total = relay.sum(select_weights)\n        return loss, weight_total\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        ignore_index = attr.get(\"ignore_index\", None)\n        reduction = attr.get(\"reduction\", b\"mean\").decode(\"utf-8\")\n\n        if reduction not in cls.VALID_REDUCTIONS:\n            raise ValueError(\n                f\"Unknown reduction type {reduction}, choices are {cls.VALID_REDUCTIONS}\"\n            )\n\n        input_tensor, target_tensor = inputs[0], inputs[1]\n        if len(inputs) == 3:\n            weight_tensor = inputs[2]\n        else:\n            weight_tensor = None\n\n        loss, weight_total = cls.run_calculation(\n            input_tensor,\n            target_tensor,\n            weight_tensor=weight_tensor,\n            ignore_index=ignore_index,\n        )\n        if reduction == \"mean\":\n            return relay.sum(loss) / weight_total\n        if reduction == \"sum\":\n            return relay.sum(loss)\n        # Case reduction == 'none'\n        return loss\n\n\nclass SoftmaxCrossEntropyLoss(OnnxOpConverter):\n    \"\"\"Operator converter for SCE_loss\"\"\"\n\n    @classmethod\n    def _impl_v13(cls, inputs, attr, params):\n        ignore_index = attr.get(\"ignore_index\", None)\n        reduction = attr.get(\"reduction\", b\"mean\").decode(\"utf-8\")\n        input_tensor, target_tensor = inputs[0], inputs[1]\n        if len(inputs) == 3:\n            weight_tensor = inputs[2]\n        else:\n            weight_tensor = None\n\n        get_log_prob = attr[\"tvm_custom\"][\"num_outputs\"] == 2\n        log_softmax_attr = {\"axis\": 1}\n        log_softmax_tensor = LogSoftmax.get_converter(13)([input_tensor], log_softmax_attr, None)\n\n        loss, weight_total = NegativeLogLikelihoodLoss.run_calculation(\n            log_softmax_tensor,\n            target_tensor,\n            weight_tensor,\n            ignore_index=ignore_index,\n        )\n\n        if reduction == \"mean\":\n            loss = relay.sum(loss) / weight_total\n        elif reduction == \"sum\":\n            loss = relay.sum(loss)\n\n        if get_log_prob:\n            return relay.TupleWrapper(relay.Tuple((loss, log_softmax_tensor)), 2)\n        return loss\n\n\nclass Adagrad(OnnxOpConverter):\n    \"\"\"Operator converter for adagrad op.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        decay_factor = attr.get(\"decay_factor\", 0.0)\n        epsilon = attr.get(\"epsilon\", 0.0)\n        norm_coefficient = attr.get(\"norm_coefficient\", 0.0)\n\n        R = inputs[0]\n        T = inputs[1]\n\n        # convert attributes to constants, proper types\n        dtype_inputs = infer_type(inputs[3]).checked_type.dtype\n        decay_factor = relay.const(decay_factor, dtype=dtype_inputs)\n        epsilon = relay.const(epsilon, dtype=dtype_inputs)\n        norm_coefficient = relay.const(norm_coefficient, dtype=dtype_inputs)\n        T = relay.cast_like(T, inputs[3])\n\n        assert (\n            len(inputs) - 2\n        ) % 3 == 0, f\"Expect triplets for remaining inputs, found {len(inputs) - 2}\"\n\n        # Remaining inputs are:\n        # [x_1, x_2 ..., x_1_gradient, x_2_gradient, ... x_1_sq_g, x_2_sq_g...]\n        num_input_tensors = (len(inputs) - 2) // 3\n        output_tensors = []\n        output_accumulated_squared_gradients = []\n        for i in range(num_input_tensors):\n            x = inputs[i + 2]\n            gradient = inputs[i + 2 + num_input_tensors]\n            accumulated_squared_gradient = inputs[i + 2 + 2 * num_input_tensors]\n\n            r = R / (relay.const(1.0, dtype=dtype_inputs) + T * decay_factor)\n            g_regularized = norm_coefficient * x + gradient\n            new_accumulated_squared_gradient = (\n                accumulated_squared_gradient + g_regularized * g_regularized\n            )\n            h_adaptive = relay.sqrt(new_accumulated_squared_gradient) + epsilon\n\n            x_new = x - r * g_regularized / h_adaptive\n\n            output_tensors.append(x_new)\n            output_accumulated_squared_gradients.append(new_accumulated_squared_gradient)\n\n        # append lists together, momentums come after result tensors\n        result = output_tensors + output_accumulated_squared_gradients\n        return _expr.TupleWrapper(_expr.Tuple(result), len(result))\n\n\nclass Adam(OnnxOpConverter):\n    \"\"\"Operator converter for Adam op.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = attr.get(\"alpha\", 0.9)\n        beta = attr.get(\"beta\", 0.999)\n\n        # Note in the docs epsilon default is 0.0 but in the tests it is set to 1e-2:\n        # https://git.io/Ju5C4\n        epsilon = attr.get(\"epsilon\", 1e-2)\n        norm_coefficient = attr.get(\"norm_coefficient\", 0.0)\n        norm_coefficient_post = attr.get(\"norm_coefficient_post\", 0.0)\n\n        R = inputs[0]\n        T = inputs[1]\n\n        assert (\n            len(inputs) - 2\n        ) % 4 == 0, f\"Expect 4-lets for remaining inputs, found {len(inputs) - 2}\"\n\n        # convert attributes to constants, proper types\n        dtype_inputs = infer_type(inputs[3]).checked_type.dtype\n        inverse_alpha = relay.const(1 - alpha, dtype=dtype_inputs)\n        alpha = relay.const(alpha, dtype=dtype_inputs)\n        inverse_beta = relay.const(1 - beta, dtype=dtype_inputs)\n        beta = relay.const(beta, dtype=dtype_inputs)\n        epsilon = relay.const(epsilon, dtype=dtype_inputs)\n        norm_coefficient = relay.const(norm_coefficient, dtype=dtype_inputs)\n        norm_coefficient_post = relay.const(norm_coefficient_post, dtype=dtype_inputs)\n        one = relay.const(1, dtype=dtype_inputs)\n        T = relay.cast_like(T, inputs[3])\n\n        # Remaining inputs are:\n        # [x_1, x_2 ..., x_1_grad, x_2_grad, ... x_1_g_accum, x_2_g_accum..., x_1_g_sq_accum, ...]\n        num_input_tensors = (len(inputs) - 2) // 4\n        output_tensors = []\n        output_accumulated_gradients = []\n        output_accumulated_squared_gradients = []\n        for i in range(num_input_tensors):\n            x = inputs[i + 2]\n            g = inputs[i + 2 + num_input_tensors]\n            v = inputs[i + 2 + 2 * num_input_tensors]\n            h = inputs[i + 2 + 3 * num_input_tensors]\n\n            g_regularized = norm_coefficient * x + g\n            v_new = alpha * v + inverse_alpha * g_regularized\n            h_new = beta * h + inverse_beta * g_regularized * g_regularized\n            h_sqrt = relay.sqrt(h_new) + epsilon\n\n            true_branch = R * relay.sqrt(one - relay.power(beta, T)) / (one - relay.power(alpha, T))\n            R_adjusted = relay.If(T > relay.const(0, dtype=dtype_inputs), true_branch, R)\n\n            x_new = x - R_adjusted * (v_new / h_sqrt)\n            x_result = (one - norm_coefficient_post) * x_new\n\n            output_tensors.append(x_result)\n            output_accumulated_gradients.append(v_new)\n            output_accumulated_squared_gradients.append(h_new)\n\n        # append lists together to get final result\n        result = (\n            output_tensors + output_accumulated_gradients + output_accumulated_squared_gradients\n        )\n        return _expr.TupleWrapper(_expr.Tuple(result), len(result))\n\n\nclass Momentum(OnnxOpConverter):\n    \"\"\"Operator converter for Momentum op.\"\"\"\n\n    @classmethod\n    def _impl_v1(cls, inputs, attr, params):\n        alpha = attr[\"alpha\"]\n        beta = attr[\"beta\"]\n        mode = attr[\"mode\"].decode(\"utf-8\")\n        norm_coefficient = attr[\"norm_coefficient\"]\n\n        assert mode in [\"nesterov\", \"standard\"], f\"Unknown momentum mode {mode}\"\n        R = inputs[0]\n        T = inputs[1]\n\n        assert (\n            len(inputs) - 2\n        ) % 3 == 0, f\"Expect triplets for remaining inputs, found {len(inputs) - 2}\"\n        # Remaining inputs are:\n        # [x_1, x_2 ..., x_1_gradient, x_2_gradient, ... x_1_momentum, x_2_momentum...]\n        num_input_tensors = (len(inputs) - 2) // 3\n\n        # convert attributes to constants\n        dtype_inputs = infer_type(inputs[3]).checked_type.dtype\n        alpha = relay.const(alpha, dtype=dtype_inputs)\n        beta = relay.const(beta, dtype=dtype_inputs)\n        norm_coefficient = relay.const(norm_coefficient, dtype=dtype_inputs)\n        default_beta = relay.const(1.0, dtype=dtype_inputs)\n\n        # Calculate updated values for every input\n        output_tensors = []\n        output_momentums = []\n        for i in range(num_input_tensors):\n            x = inputs[i + 2]\n            gradient = inputs[i + 2 + num_input_tensors]\n            momentum = inputs[i + 2 + 2 * num_input_tensors]\n            g_regularized = norm_coefficient * x + gradient\n            beta_adjusted = relay.If(T > relay.const(0, dtype=\"int64\"), beta, default_beta)\n            new_momentum = alpha * momentum + beta_adjusted * g_regularized\n\n            if mode == \"standard\":\n                x_output = x - R * new_momentum\n            else:\n                # mode == 'nesterov'\n                x_output = x - R * (g_regularized + alpha * new_momentum)\n\n            output_tensors.append(x_output)\n            output_momentums.append(new_momentum)\n\n        # append lists together, momentums come after result tensors\n        result = output_tensors + output_momentums\n        return _expr.TupleWrapper(_expr.Tuple(result), len(result))\n\n\nclass Round(OnnxOpConverter):\n    \"\"\"Operator converter for round op.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        # Onnx round uses Banker's rounding which rounds .5 to the nearest even integer\n\n        x = inputs[0]\n        dtype = infer_type(x).checked_type.dtype\n        half = _expr.const(0.5, dtype=dtype)\n        one = _expr.const(1, dtype=dtype)\n        two = _expr.const(2, dtype=dtype)\n\n        rounded = _op.ceil(x - half)\n        bankers_mask = one - (_op.ceil(x + half) - _op.floor(x + half))\n        non_even = _op.abs(_op.mod(rounded, two))\n        return rounded + (bankers_mask * non_even)\n\n\nclass SequenceConstruct(OnnxOpConverter):\n    \"\"\"Operator converter for sequence construction op.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        # Construct a tuple from input tensors.\n        return _expr.Tuple(inputs)\n\n\nclass SequenceInsert(OnnxOpConverter):\n    \"\"\"Operator converter for sequence insert op.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        # Insert a new tensor into a tuple of tensors.\n        input_sequence = inputs[0]\n        new_tensor = inputs[1]\n\n        if len(inputs) == 3:\n            position = inputs[2]\n            # Non constant position is not supported.\n            if isinstance(position, _expr.Constant):\n                position = position.data.numpy()\n            elif position.name_hint in params:\n                position = params[position.name_hint].numpy()\n            else:\n                raise NotImplementedError(\"Position must be a constant.\")\n        else:\n            position = -1\n\n        if position < 0:\n            position = len(input_sequence) + position + 1\n        # Convert sequence to a list, insert new tensor, and repackage as Tuple.\n        tensor_list = [input_sequence[i] for i in range(len(input_sequence))]\n        # Insert new tensor.\n        tensor_list.insert(position, new_tensor)\n        # Create new tuple and return.\n        return _expr.Tuple(tensor_list)\n\n\nclass ConcatFromSequence(OnnxOpConverter):\n    \"\"\"Operator converter for sequence concatenation op.\"\"\"\n\n    @classmethod\n    def _impl_v11(cls, inputs, attr, params):\n        axis = attr.get(\"axis\", 0)\n        new_axis = attr.get(\"new_axis\", 0)\n\n        # If a new axis should be created, just stack input tensors.\n        if new_axis == 1:\n            return _op.stack(inputs[0], axis=axis)\n\n        return _op.concatenate(inputs[0], axis=axis)\n\n\n# compatible operators that do NOT require any conversion.\n_identity_list = []\n\n# _convert_map defines maps of name to converter functor(callable)\n# for 1 to 1 mapping, use Renamer if nothing but name is different\n# use AttrCvt if attributes need to be converted\n# for 1 to N mapping(composed), use custom callable functions\n# for N to 1 mapping, currently not supported(?)\ndef _get_convert_map(opset):\n    return {\n        # defs/experimental\n        \"Identity\": Renamer(\"copy\"),\n        \"Optional\": Optional_.get_converter(opset),\n        \"OptionalHasElement\": OptionalHasElement.get_converter(opset),\n        \"OptionalGetElement\": OptionalGetElement.get_converter(opset),\n        \"Affine\": Affine.get_converter(opset),\n        \"BitShift\": BitShift.get_converter(opset),\n        \"ThresholdedRelu\": ThresholdedRelu.get_converter(opset),\n        \"ScaledTanh\": ScaledTanh.get_converter(opset),\n        \"ParametricSoftplus\": ParametricSoftPlus.get_converter(opset),\n        \"Constant\": Constant.get_converter(opset),\n        \"ConstantOfShape\": ConstantOfShape.get_converter(opset),\n        # 'GivenTensorFill'\n        \"FC\": AttrCvt(\"dense\", ignores=[\"axis\", \"axis_w\"]),\n        \"Scale\": Scale.get_converter(opset),\n        # 'GRUUnit'\n        # 'ATen'\n        # 'ImageScaler'\n        \"MeanVarianceNormalization\": MeanVarianceNormalization.get_converter(opset),\n        # 'Crop'\n        # 'Embedding'\n        \"Upsample\": Upsample.get_converter(opset),\n        \"SpatialBN\": BatchNorm.get_converter(opset),\n        # defs/generator\n        # 'RandomUniform'\n        # 'RandomNormal'\n        # 'RandomUniformLike'\n        # 'RandomNormalLike'\n        # defs/logical\n        # defs/math\n        \"Add\": Add.get_converter(opset),\n        \"Sub\": Sub.get_converter(opset),\n        \"Mul\": Mul.get_converter(opset),\n        \"Div\": Div.get_converter(opset),\n        \"Neg\": Renamer(\"negative\"),\n        \"Abs\": Absolute.get_converter(opset),\n        \"Reciprocal\": Reciprocal.get_converter(opset),\n        \"Floor\": Renamer(\"floor\"),\n        \"Ceil\": Renamer(\"ceil\"),\n        \"Round\": Round.get_converter(opset),\n        \"IsInf\": IsInf.get_converter(opset),\n        \"IsNaN\": Renamer(\"isnan\"),\n        \"Sqrt\": Renamer(\"sqrt\"),\n        \"Relu\": Renamer(\"relu\"),\n        \"Celu\": Celu.get_converter(opset),\n        \"LeakyRelu\": Renamer(\"leaky_relu\"),\n        \"Selu\": Selu.get_converter(opset),\n        \"Elu\": Elu.get_converter(opset),\n        \"Gelu\": Gelu.get_converter(opset),\n        \"FastGelu\": FastGelu.get_converter(opset),\n        \"BiasGelu\": BiasGelu.get_converter(opset),\n        \"LayerNormalization\": LayerNormalization.get_converter(opset),\n        # TODO: We need a better way to handle different domains, in case\n        # of name collisions. EmbedLayerNormalization, SkipLayerNormalization, and Attention\n        # are in the `com.microsoft` domain.\n        \"EmbedLayerNormalization\": EmbedLayerNormalization.get_converter(opset),\n        \"SkipLayerNormalization\": SkipLayerNormalization.get_converter(opset),\n        \"Attention\": Attention.get_converter(opset),\n        \"Exp\": Renamer(\"exp\"),\n        \"Greater\": Renamer(\"greater\"),\n        \"GreaterOrEqual\": Renamer(\"greater_equal\"),\n        \"Less\": Renamer(\"less\"),\n        \"LessOrEqual\": Renamer(\"less_equal\"),\n        \"Log\": Renamer(\"log\"),\n        \"Acos\": Renamer(\"acos\"),\n        \"Acosh\": Renamer(\"acosh\"),\n        \"Asin\": Renamer(\"asin\"),\n        \"Asinh\": Renamer(\"asinh\"),\n        \"Atan\": Renamer(\"atan\"),\n        \"Atanh\": Renamer(\"atanh\"),\n        \"Cos\": Renamer(\"cos\"),\n        \"Cosh\": Renamer(\"cosh\"),\n        \"Sin\": Renamer(\"sin\"),\n        \"Sinh\": Renamer(\"sinh\"),\n        \"Tan\": Renamer(\"tan\"),\n        \"Tanh\": Renamer(\"tanh\"),\n        \"Pow\": Pow.get_converter(opset),\n        \"PRelu\": Prelu.get_converter(opset),\n        \"Sigmoid\": Renamer(\"sigmoid\"),\n        \"HardSigmoid\": HardSigmoid.get_converter(opset),\n        \"HardSwish\": HardSwish.get_converter(opset),\n        \"Max\": Maximum.get_converter(opset),\n        \"Min\": Minimum.get_converter(opset),\n        \"Sum\": Sum.get_converter(opset),\n        \"Mean\": Mean.get_converter(opset),\n        \"Clip\": Clip.get_converter(opset),\n        \"Softplus\": Softplus.get_converter(opset),\n        # softmax default axis is different in onnx\n        \"Softmax\": Softmax.get_converter(opset),\n        \"LogSoftmax\": LogSoftmax.get_converter(opset),\n        \"OneHot\": OneHot.get_converter(opset),\n        \"Hardmax\": Hardmax.get_converter(opset),\n        \"Shrink\": Shrink.get_converter(opset),\n        \"Softsign\": Softsign.get_converter(opset),\n        \"Gemm\": Gemm.get_converter(opset),\n        \"MatMul\": MatMul.get_converter(opset),\n        \"MatMulInteger\": MatMulInteger.get_converter(opset),\n        \"MatMulInteger16\": MatMulInteger16.get_converter(opset),\n        \"Mod\": Mod.get_converter(opset),\n        \"Xor\": Renamer(\"logical_xor\"),\n        # defs/nn\n        \"AveragePool\": AveragePool.get_converter(opset),\n        \"LpPool\": LpPool.get_converter(opset),\n        \"GlobalLpPool\": GlobalLpPool.get_converter(opset),\n        \"MaxPool\": MaxPool.get_converter(opset),\n        \"MaxUnpool\": MaxUnpool.get_converter(opset),\n        \"Conv\": Conv.get_converter(opset),\n        \"ConvTranspose\": ConvTranspose.get_converter(opset),\n        \"GlobalAveragePool\": GlobalAveragePool.get_converter(opset),\n        \"GlobalMaxPool\": GlobalMaxPool.get_converter(opset),\n        \"BatchNormalization\": BatchNorm.get_converter(opset),\n        \"InstanceNormalization\": InstanceNorm.get_converter(opset),\n        # 'LpNormalization'\n        \"Dropout\": AttrCvt(\"dropout\", {\"ratio\": \"rate\"}, ignores=[\"is_test\"]),\n        \"Flatten\": Flatten.get_converter(opset),\n        \"LRN\": LRN.get_converter(opset),\n        # Recurrent Layers\n        \"RNN\": RNN.get_converter(opset),\n        \"LSTM\": LSTM.get_converter(opset),\n        \"GRU\": GRU.get_converter(opset),\n        # defs/vision\n        \"MaxRoiPool\": MaxRoiPool.get_converter(opset),\n        \"RoiAlign\": RoiAlign.get_converter(opset),\n        \"NonMaxSuppression\": NonMaxSuppression.get_converter(opset),\n        # defs/reduction\n        \"ReduceMax\": ReduceMax.get_converter(opset),\n        \"ReduceMin\": ReduceMin.get_converter(opset),\n        \"ReduceSum\": ReduceSum.get_converter(opset),\n        \"ReduceMean\": ReduceMean.get_converter(opset),\n        \"ReduceProd\": ReduceProd.get_converter(opset),\n        \"ReduceLogSumExp\": ReduceLogSumExp.get_converter(opset),\n        \"ReduceLogSum\": ReduceLogSum.get_converter(opset),\n        \"ReduceSumSquare\": ReduceSumSquare.get_converter(opset),\n        \"ReduceL1\": ReduceL1.get_converter(opset),\n        \"ReduceL2\": ReduceL2.get_converter(opset),\n        # defs/sorting\n        \"ArgMax\": ArgMax.get_converter(opset),\n        \"ArgMin\": ArgMin.get_converter(opset),\n        \"TopK\": TopK.get_converter(opset),\n        # defs/tensor\n        \"Cast\": Cast.get_converter(opset),\n        \"CastLike\": CastLike.get_converter(opset),\n        \"Reshape\": Reshape.get_converter(opset),\n        \"Expand\": Expand.get_converter(opset),\n        \"Concat\": Concat.get_converter(opset),\n        \"Split\": Split.get_converter(opset),\n        \"Slice\": Slice.get_converter(opset),\n        \"Transpose\": AttrCvt(\"transpose\", {\"perm\": \"axes\"}),\n        \"DepthToSpace\": DepthToSpace.get_converter(opset),\n        \"SpaceToDepth\": SpaceToDepth.get_converter(opset),\n        \"Gather\": Gather.get_converter(opset),\n        \"GatherElements\": GatherElements.get_converter(opset),\n        \"GatherND\": GatherND.get_converter(opset),\n        \"Compress\": Compress.get_converter(opset),\n        \"Size\": AttrCvt(\"ndarray_size\", extras={\"dtype\": \"int64\"}),\n        \"Scatter\": Scatter.get_converter(opset),\n        \"ScatterElements\": Scatter.get_converter(opset),\n        \"ScatterND\": ScatterND.get_converter(opset),\n        \"EyeLike\": EyeLike.get_converter(opset),\n        \"Squeeze\": Squeeze.get_converter(opset),\n        \"Unsqueeze\": Unsqueeze.get_converter(opset),\n        \"Pad\": Pad.get_converter(opset),\n        \"Shape\": Shape.get_converter(opset),\n        \"Sign\": Sign.get_converter(opset),\n        \"Equal\": Equal.get_converter(opset),\n        \"Not\": Not.get_converter(opset),\n        \"And\": And.get_converter(opset),\n        \"Tile\": Tile.get_converter(opset),\n        \"Erf\": Erf.get_converter(opset),\n        \"Where\": Where.get_converter(opset),\n        \"Or\": Or.get_converter(opset),\n        \"Resize\": Resize.get_converter(opset),\n        \"NonZero\": NonZero.get_converter(opset),\n        \"Range\": Range.get_converter(opset),\n        \"CumSum\": CumSum.get_converter(opset),\n        \"Unique\": Unique.get_converter(opset),\n        \"Einsum\": Einsum.get_converter(opset),\n        \"Trilu\": Trilu.get_converter(opset),\n        \"GridSample\": GridSample.get_converter(opset),\n        # defs/control_flow\n        \"Loop\": Loop.get_converter(opset),\n        \"If\": If.get_converter(opset),\n        # Torch ATen Dispatcher.\n        \"ATen\": ATen.get_converter(opset),\n        # Quantization\n        \"QuantizeLinear\": QuantizeLinear.get_converter(opset),\n        \"DequantizeLinear\": DequantizeLinear.get_converter(opset),\n        \"DynamicQuantizeLinear\": DynamicQuantizeLinear.get_converter(opset),\n        \"ReverseSequence\": ReverseSequence.get_converter(opset),\n        \"QLinearConv\": QLinearConv.get_converter(opset),\n        \"QLinearConcat\": QLinearConcat.get_converter(opset),\n        \"QLinearAdd\": QLinearAdd.get_converter(opset),\n        \"QLinearMatMul\": QLinearMatMul.get_converter(opset),\n        \"QLinearMul\": QLinearMul.get_converter(opset),\n        \"QLinearSigmoid\": QLinearSigmoid.get_converter(opset),\n        \"ConvInteger\": ConvInteger.get_converter(opset),\n        \"QLinearAveragePool\": QLinearAveragePool.get_converter(opset),\n        \"QLinearGlobalAveragePool\": QLinearGlobalAveragePool.get_converter(opset),\n        \"QLinearLeakyRelu\": QLinearLeakyRelu.get_converter(opset),\n        # Random number generation.\n        \"RandomNormal\": RandomNormal.get_converter(opset),\n        \"RandomNormalLike\": RandomNormalLike.get_converter(opset),\n        \"RandomUniform\": RandomUniform.get_converter(opset),\n        \"RandomUniformLike\": RandomUniformLike.get_converter(opset),\n        \"Multinomial\": Multinomial.get_converter(opset),\n        # Loss functions / training\n        \"NegativeLogLikelihoodLoss\": NegativeLogLikelihoodLoss.get_converter(opset),\n        \"SoftmaxCrossEntropyLoss\": SoftmaxCrossEntropyLoss.get_converter(opset),\n        \"Adagrad\": Adagrad.get_converter(opset),\n        \"Adam\": Adam.get_converter(opset),\n        \"Momentum\": Momentum.get_converter(opset),\n        \"Scan\": Scan.get_converter(opset),\n        # ML\n        \"LinearRegressor\": LinearRegressor.get_converter(opset),\n        # Sequence operators\n        \"SequenceConstruct\": SequenceConstruct.get_converter(opset),\n        \"SequenceInsert\": SequenceInsert.get_converter(opset),\n        \"ConcatFromSequence\": ConcatFromSequence.get_converter(opset),\n    }\n\n\nclass GraphProto:\n    \"\"\"A helper class for handling Relay expression copying from pb2.GraphProto.\n    Definition: https://github.com/onnx/onnx/blob/main/onnx/onnx.proto\n\n        Parameters\n    ----------\n    shape : dict of str to tuple, optional\n        The input shape to the graph\n\n    dtype : str or dict of str to str\n        The input types to the graph\n\n    freeze_params: bool\n        If this parameter is true, the importer will take any provided\n        onnx input values (weights, shapes, etc) and embed them into the relay model\n        as Constants instead of variables. This allows more aggressive optimizations\n        at compile time and helps in making models static if certain inputs represent\n        attributes relay would traditionally consider compile-time constants.\n\n    \"\"\"\n\n    current = None\n\n    def __init__(self, shape, dtype, freeze_params=False):\n        self._nodes = {}\n        self._params = {}\n        self._inputs = {}\n        self._renames = {}\n        self._num_input = 0\n        self._num_param = 0\n        self._shape = shape.copy() if shape else {}\n        self._input_names = []\n        self._dtype = dtype\n        self.opset = None\n        self._freeze_params = freeze_params\n\n    def __enter__(self):\n        self._old_manager = GraphProto.current\n        GraphProto.current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        GraphProto.current = self._old_manager\n\n    def freeze(self, func, params):\n        bind_map = {}\n        for name in params.keys():\n            if name in self._nodes.keys():\n                bind_map[self._nodes[name]] = _expr.const(params[name])\n        body = _expr.bind(func.body, bind_map)\n        fn = _function.Function(analysis.free_vars(body), body)\n        return fn, {}\n\n    def from_onnx(self, graph, opset, get_output_expr=False):\n        \"\"\"Construct Relay expression from ONNX graph.\n\n        Onnx graph is a python protobuf object.\n        The companion parameters will be handled automatically.\n        However, the input names from onnx graph is vague, mixing inputs and\n        network weights/bias such as \"1\", \"2\"...\n        For convenience, we rename the `real` input names to \"input_0\",\n        \"input_1\"... And renaming parameters to \"param_0\", \"param_1\"...\n\n        Parameters\n        ----------\n        graph : onnx protobuf object\n            The loaded onnx graph\n\n        opset : opset version\n\n        get_output_expr: bool\n            If set to true, this conversion will return each output expression rather\n            than a packaged module. This can be useful when converting subgraphs to\n            relay.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The returned relay module\n\n        params : dict\n            A dict of name: tvm.nd.array pairs, used as pretrained weights\n        \"\"\"\n        self.opset = opset\n        self._parse_graph_initializers(graph)\n        self._parse_graph_input(graph)\n        self._check_user_inputs_in_outermost_graph_scope()\n        self._check_for_unsupported_ops(graph)\n        self._construct_nodes(graph)\n\n        # now return the outputs\n        outputs = [self._nodes[self._parse_value_proto(i)] for i in graph.output]\n        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n        # If requested, directly return the converted expressions.\n        if get_output_expr:\n            return outputs\n        ## Maintain the order of inputs and parameters from the ONNX graph, but only include\n        ## those parameters that are needed to execute the relay graph\n        free_vars = analysis.free_vars(outputs)\n        nodes = {v: k for k, v in self._nodes.items()}\n        free_vars = [nodes[var] for var in free_vars]\n        for i_name in self._params:\n            if i_name in free_vars and i_name not in self._inputs:\n                self._inputs[i_name] = self._nodes[i_name]\n        # Create a function from our output expression and all input variables.\n        func = _function.Function([v for k, v in self._inputs.items()], outputs)\n        return IRModule.from_expr(func), self._params\n\n    def _parse_graph_initializers(self, graph):\n        \"\"\"Parse network inputs to relay, aka parameters.\"\"\"\n        for init_tensor in graph.initializer:\n            if not init_tensor.name.strip():\n                raise ValueError(\"Tensor's name is required.\")\n            array = self._parse_array(init_tensor)\n            if self._freeze_params:\n                self._nodes[init_tensor.name] = _expr.const(array)\n            else:\n                self._params[init_tensor.name] = array\n                self._nodes[init_tensor.name] = new_var(\n                    init_tensor.name,\n                    shape=self._params[init_tensor.name].shape,\n                    dtype=self._params[init_tensor.name].dtype,\n                )\n\n    def _parse_graph_input(self, graph):\n        for i in graph.input:\n            # from onnx v0.2, GraphProto.input has type ValueInfoProto,\n            #  and the name is 'i.name'\n            i_name, i_shape, d_type, i_shape_name = get_info(i)\n            if i_name in self._params:\n                # i is a param instead of input\n                self._num_param += 1\n                self._nodes[i_name] = new_var(\n                    i_name, shape=self._params[i_name].shape, dtype=self._params[i_name].dtype\n                )\n            elif i_name in self._nodes:\n                continue\n            else:\n                self._num_input += 1\n                self._input_names.append(i_name)\n                if i_name in self._shape:\n                    i_shape = self._shape[i_name]\n                else:\n                    if \"?\" in str(i_shape):\n                        warning_msg = (\n                            \"Input %s has unknown dimension shapes: %s. \"\n                            \"Specifying static values may improve performance\"\n                            % (i_name, str(i_shape_name))\n                        )\n                        warnings.warn(warning_msg)\n                if isinstance(self._dtype, dict):\n                    dtype = self._dtype[i_name] if i_name in self._dtype else d_type\n                else:\n                    dtype = d_type\n                self._nodes[i_name] = new_var(i_name, shape=i_shape, dtype=dtype)\n            self._inputs[i_name] = self._nodes[i_name]\n\n    def _check_user_inputs_in_outermost_graph_scope(self):\n        \"\"\"Only check user inputs in the outer-most graph scope.\"\"\"\n        if self._old_manager is None:\n            assert all(\n                [name in self._input_names for name in self._shape.keys()]\n            ), \"User specified the shape for inputs that weren't found in the graph: \" + str(\n                self._shape\n            )\n\n    def _check_for_unsupported_ops(self, graph):\n        convert_map = _get_convert_map(self.opset)\n        unsupported_ops = set()\n        for node in graph.node:\n            op_name = node.op_type\n            if (\n                op_name not in convert_map\n                and op_name != \"Constant\"\n                and op_name not in _identity_list\n            ):\n                unsupported_ops.add(op_name)\n        if unsupported_ops:\n            msg = \"The following operators are not supported for frontend ONNX: \"\n            msg += \", \".join(unsupported_ops)\n            raise tvm.error.OpNotImplemented(msg)\n\n    def _construct_nodes(self, graph):\n        \"\"\"Nodes are stored as directed acyclic graph.\"\"\"\n        for node in graph.node:\n            op_name = node.op_type\n            attr = self._parse_attr(node.attribute)\n            # Create and populate input list.\n            inputs = onnx_input()\n            for i in node.input:\n                if i != \"\":\n                    inputs.append(self._nodes[self._renames.get(i, i)])\n                else:\n                    inputs.append(None)\n            i_name = self._parse_value_proto(node)\n            node_output = self._fix_outputs(op_name, node.output)\n            attr[\"tvm_custom\"] = {}\n            attr[\"tvm_custom\"][\"name\"] = i_name\n            attr[\"tvm_custom\"][\"num_outputs\"] = len(node_output)\n\n            op = self._convert_operator(op_name, inputs, attr, self.opset)\n            if not isinstance(op, _expr.TupleWrapper):\n                outputs_num = 1\n            else:\n                outputs_num = len(op)\n\n            if outputs_num == 1:\n                op = fold_constant(op)\n            else:\n                op = _expr.TupleWrapper(fold_constant(op.astuple()), len(op))\n\n            if outputs_num > 1:\n                # ONNX supports optional outputs for some nodes.\n                # This block searches for missing outputs in the ONNX graph\n                # and removes any unneeded ops\n                valid_outputs = [False] * outputs_num\n                for i, output in enumerate(node_output):\n                    if output != \"\":\n                        valid_outputs[i] = True\n                # If we have outputs ONNX isn't expecting, we need to drop them\n                if not all(valid_outputs):\n                    tup = op.astuple()\n                    # TupleWrapper can also wrap ops with TupleType outputs\n                    if isinstance(tup, _expr.Tuple):\n                        # For tuples, we extract the fields instead of using GetTupleItem\n                        outputs = [tup.fields[i] for i, valid in enumerate(valid_outputs) if valid]\n                    else:\n                        # For call nodes, we need to GetTupleItem\n                        outputs = [op[i] for i, valid in enumerate(valid_outputs) if valid]\n                    # Create the new op with valid outputs\n                    if len(outputs) == 1:\n                        op = outputs[0]\n                    elif len(outputs) != outputs_num:\n                        op = _expr.TupleWrapper(_expr.Tuple(outputs), len(outputs))\n                    # Drop invalid outputs for the onnx node\n                    outputs_num = len(outputs)\n                    node_output = [output for output in node_output if output != \"\"]\n            assert (\n                len(node_output) == outputs_num\n            ), \"Number of output mismatch {} vs {} in {}.\".format(\n                len(node_output), outputs_num, op_name\n            )\n\n            if outputs_num == 1:\n                self._nodes[node_output[0]] = op\n            else:\n                for k, i in zip(list(node_output), range(len(node_output))):\n                    self._nodes[k] = op[i]\n\n    def _parse_value_proto(self, value_proto):\n        \"\"\"Parse ValueProto or raw str.\"\"\"\n        try:\n            name = value_proto.name\n        except AttributeError:\n            name = value_proto\n        return name\n\n    def _parse_array(self, tensor_proto):\n        np_array = get_numpy(tensor_proto).reshape(tuple(tensor_proto.dims))\n        return _nd.array(np_array)\n\n    def _parse_attr(self, attr_proto):\n        \"\"\"Convert a list of AttributeProto to a dict, with names as keys.\"\"\"\n        attrs = {}\n        for a in attr_proto:\n            for f in [\"f\", \"i\", \"s\", \"g\"]:\n                if a.HasField(f):\n                    attrs[a.name] = getattr(a, f)\n            for f in [\"floats\", \"ints\", \"strings\"]:\n                if list(getattr(a, f)):\n                    assert a.name not in attrs, \"Only one type of attr is allowed\"\n                    attrs[a.name] = tuple(getattr(a, f))\n            for f in [\"t\"]:\n                if a.HasField(f):\n                    attrs[a.name] = getattr(a, f)\n            for f in [\"tensors\"]:\n                if list(getattr(a, f)):\n                    assert a.name not in attrs, \"Only one type of attr is allowed\"\n                    attrs[a.name] = tuple(getattr(a, f))\n            for f in [\"graphs\"]:\n                if list(getattr(a, f)):\n                    raise NotImplementedError(\"Field {} is not supported in relay.\".format(f))\n            if a.name not in attrs:\n                raise ValueError(\"Cannot parse attribute: \\n{}\\n.\".format(a))\n        return attrs\n\n    def _convert_operator(self, op_name, inputs, attrs, opset):\n        \"\"\"Convert ONNX operator into a Relay operator.\n        The converter must specify conversions explicitly for incompatible name, and\n        apply handlers to operator attributes.\n\n        Parameters\n        ----------\n        op_name : str\n            Operator name, such as Convolution, FullyConnected\n        inputs : list of tvm.relay.function.Function\n            List of inputs.\n        attrs : dict\n            Dict of operator attributes\n        opset : int\n            Opset version\n\n        Returns\n        -------\n        sym : tvm.relay.function.Function\n            Converted relay function\n        \"\"\"\n        convert_map = _get_convert_map(opset)\n        if op_name in _identity_list:\n            sym = get_relay_op(op_name)(*inputs, **attrs)\n        elif op_name in convert_map:\n            sym = convert_map[op_name](inputs, attrs, self._params)\n        else:\n            raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n        return sym\n\n    def _fix_outputs(self, op_name, outputs):\n        \"\"\"A hack to handle dropout or similar operator that have more than one out\n        in ONNX.\n        \"\"\"\n        if op_name == \"Dropout\":\n            if len(outputs) == 1:\n                return outputs\n            # TODO(zhreshold): support dropout mask?\n            outputs = outputs[:-1]\n        return outputs\n\n\ndef from_onnx(\n    model, shape=None, dtype=\"float32\", opset=None, freeze_params=True, convert_config=None\n):\n    \"\"\"Convert a ONNX model into an equivalent Relay Function.\n\n    ONNX graphs are represented as Python Protobuf objects.\n    The companion parameters will be handled automatically.\n    However, the input names from onnx graph is vague, mixing inputs and\n    network weights/bias such as \"1\", \"2\"...\n    For convenience, we rename the `real` input names to \"input_0\",\n    \"input_1\"... And renaming parameters to \"param_0\", \"param_1\"...\n\n    By default, ONNX defines models in terms of dynamic shapes. The ONNX importer\n    retains that dynamism upon import, and the compiler attempts to convert the\n    model into a static shapes at compile time. If this fails, there may still\n    be dynamic operations in the model. Not all TVM kernels currently support\n    dynamic shapes, please file an issue on discuss.tvm.apache.org\n    if you hit an error with dynamic kernels.\n\n    Parameters\n    ----------\n    model : protobuf object\n        ONNX ModelProto after ONNX v1.1.0\n\n    shape : dict of str to tuple, optional\n        The input shape to the graph\n\n    dtype : str or dict of str to str\n        The input types to the graph\n\n    opset : int, optional\n        Override to autodetected opset.\n        This can be helpful for some testing.\n\n    freeze_params: bool\n        If this parameter is true, the importer will take any provided\n        onnx input values (weights, shapes, etc) and embed them into the relay model\n        as Constants instead of variables. This allows more aggressive optimizations\n        at compile time and helps in making models static if certain inputs represent\n        attributes relay would traditionally consider compile-time constants.\n\n    convert_config : Optional[Dict[str, Any]]\n        Default config:\n            use_nt_batch_matmul : bool = True\n                True to convert qualified onnx `matmul` to `nn.batch_matmul` strict to NT format\n                (transpose_a=False, transpose_b=True).\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by relay\n    \"\"\"\n    global ONNX_DEFAULT_CONFIGS\n    if convert_config is not None:\n        ONNX_DEFAULT_CONFIGS.update(convert_config)\n\n    try:\n        import onnx\n\n        if hasattr(onnx.checker, \"check_model\"):\n            # try use onnx's own model checker before converting any model\n            try:\n                onnx.checker.check_model(model)\n            except Exception as e:  # pylint: disable=c-extension-no-member, broad-except\n                # the checker is a bit violent about errors, so simply print warnings here\n                warnings.warn(str(e))\n    except ImportError:\n        pass\n    g = GraphProto(shape, dtype, freeze_params)\n    graph = model.graph\n\n    try:\n        opset_in_model = 1\n        if model.opset_import:\n            # TODO: for now we only really support ai.onnx op set\n            # TODO: handle other namespaces well see https://github.com/apache/tvm/issues/10950\n            for opset_identifier in model.opset_import:\n                # As per https://github.com/onnx/onnx/blob/main/docs/IR.md\n                # All operator sets except the default one must specify the operator version\n                if str(opset_identifier.domain) in [\"ai.onnx\", \"\"]:\n                    opset_in_model = opset_identifier.version\n                    break\n    except AttributeError:\n        opset_in_model = 1\n\n    if opset is None:\n        opset = opset_in_model\n    elif opset < opset_in_model:\n        warnings.warn(\n            \"\"\n            f\"You are overwritting original opset ver = {opset_in_model} by lower ver = {opset}. \"\n            f\"That might cause model conversion errors.\"\n        )\n\n    # Use the graph proto as a scope so that ops can access other nodes if needed.\n    with g:\n        mod, params = g.from_onnx(graph, opset)\n\n    if freeze_params:\n        mod = relay.transform.DynamicToStatic()(mod)\n\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/paddlepaddle.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, unused-argument, too-many-lines\n# pylint: disable=import-outside-toplevel\n\"\"\"Paddle: PArallel Distributed Deep LEarning.\"\"\"\n\nimport warnings\nimport numpy as np\n\nimport tvm\nfrom tvm.ir import IRModule\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import ty as _ty\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import ty as _ty\nfrom .. import op as _op\nfrom .common import (\n    autopad,\n    fold_constant,\n    get_relay_op,\n    infer_shape,\n    infer_type,\n    infer_value,\n    shape_of,\n    try_infer_value,\n    new_var,\n)\n\n__all__ = [\"from_paddle\"]\n\n\ndef _dtype_shape_promotion(inputs):\n    \"\"\"Promote data type and shape for list of tensors.\"\"\"\n\n    dtype_order = [\"bool\", \"int8\", \"int16\", \"int32\", \"int64\", \"float32\", \"float64\"]\n\n    ranks = [len(infer_shape(x)) for x in inputs]\n    if set(ranks) == set([1, 0]):\n        for i, r in enumerate(ranks):\n            if r == 0:\n                inputs[i] = _op.expand_dims(inputs[i], axis=0)\n\n    dtypes = set(dtype_order.index(infer_type(x).checked_type.dtype) for x in inputs)\n    if len(dtypes) == 1:\n        return inputs\n    max_dtype = dtype_order[max(dtypes)]\n    for i, input_op in enumerate(inputs):\n        if infer_type(input_op).checked_type.dtype != max_dtype:\n            inputs[i] = input_op.astype(max_dtype)\n    return inputs\n\n\ndef _convert_dtype_value(val):\n    \"\"\"Converts a Paddle type id to a string.\"\"\"\n\n    convert_dtype_map = {\n        21: \"int8\",\n        20: \"uint8\",\n        6: \"float64\",\n        5: \"float32\",\n        4: \"float16\",\n        3: \"int64\",\n        2: \"int32\",\n        1: \"int16\",\n        0: \"bool\",\n    }\n    if val not in convert_dtype_map:\n        msg = \"Paddle data type value %d is not handled yet.\" % (val)\n        raise NotImplementedError(msg)\n    return convert_dtype_map[val]\n\n\ndef convert_unary_op(g, op, block):\n    \"\"\"Operator converter for all the unary operators.\"\"\"\n\n    # op_map stores mapping relationship between paddlepaddle and relay\n    op_map = {\n        \"isinf_v2\": _op.isinf,\n        \"isfinite_v2\": _op.isfinite,\n        \"isnan_v2\": _op.isnan,\n    }\n    if op.type in op_map:\n        unary_func = op_map[op.type]\n    else:\n        # while paddle operator's name is same with relay\n        unary_func = get_relay_op(op.type)\n    out = unary_func(g.get_node(op.input(\"X\")[0]))\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_binary_logical_op(g, op, block):\n    \"\"\"Operator converter for logical op.\"\"\"\n\n    ipt0 = g.get_node(op.input(\"X\")[0])\n    ipt1 = g.get_node(op.input(\"Y\")[0])\n    op_func = get_relay_op(op.type)\n    out = op_func(ipt0, ipt1)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_addmm(g, op, block):\n    \"\"\"Operator converter for addmm.\"\"\"\n\n    input_x = g.get_node(op.input(\"Input\")[0])\n    x = g.get_node(op.input(\"X\")[0])\n    y = g.get_node(op.input(\"Y\")[0])\n\n    alpha = op.attr(\"Alpha\")\n    beta = op.attr(\"Beta\")\n    dtype = block.var(op.output(\"Out\")[0]).dtype\n    dtype = _convert_dtype_value(dtype)\n\n    if not isinstance(alpha, _expr.Expr) and alpha != 1:\n        alpha = _expr.const(alpha, dtype)\n        x *= alpha\n\n    if not isinstance(beta, _expr.Expr) and beta != 1:\n        beta = _expr.const(beta, dtype)\n        input_x *= beta\n\n    transposed_y = _op.transpose(y, axes=[1, 0])\n    dense_out = _op.nn.dense(x, transposed_y)\n    out = dense_out + input_x\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_arg_max_min(g, op, block):\n    \"\"\"Operator converter for arg_max and arg_min.\"\"\"\n\n    axis = op.attr(\"axis\")\n    keepdims = op.attr(\"keepdims\")\n    flatten = op.attr(\"flatten\")\n    dtype = op.attr(\"dtype\")\n    dtype = _convert_dtype_value(dtype)\n\n    func = _op.argmax if op.type == \"arg_max\" else _op.argmin\n    x = g.get_node(op.input(\"X\")[0])\n    if axis is None or flatten:\n        x = _op.reshape(x, [-1])\n        out = func(x, axis=None, keepdims=True)\n    else:\n        out = func(x, axis=axis, keepdims=keepdims)\n    if dtype != infer_type(out).checked_type.dtype:\n        out = _op.cast(out, dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_argsort(g, op, block):\n    \"\"\"Operator converter for argsort.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    axis = op.attr(\"axis\")\n    descending = op.attr(\"descending\")\n\n    out_indices = _op.argsort(x, axis, not descending, dtype=\"int64\")\n    out = _op.gather(x, axis, out_indices)\n    g.add_node(op.output(\"Out\")[0], out)\n    g.add_node(op.output(\"Indices\")[0], out_indices)\n\n\ndef convert_assign(g, op, block):\n    \"\"\"Operator converter for assign.\"\"\"\n\n    out = g.get_node(op.input(\"X\")[0])\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_assign_value(g, op, block):\n    \"\"\"Operator converter for assign_value.\"\"\"\n\n    keys = [\"bool_values\", \"fp32_values\", \"int32_values\", \"int64_values\"]\n    dtypes = [\"bool\", \"float32\", \"int32\", \"int64\"]\n    for i, key in enumerate(keys):\n        dtype = dtypes[i]\n        value = np.array(op.attr(key)).astype(dtype)\n        if value is not None and value.size >= 1:\n            break\n    shape = op.attr(\"shape\")\n    value = value.reshape(shape)\n    out = _op.const(value, dtype=dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_batch_norm(g, op, block):\n    \"\"\"Operator converter for batch_norm.\"\"\"\n\n    ipt_name = op.input(\"X\")[0]\n    scale_name = op.input(\"Scale\")[0]\n    bias_name = op.input(\"Bias\")[0]\n    mean_name = op.input(\"Mean\")[0]\n    variance_name = op.input(\"Variance\")[0]\n    epsilon = op.attr(\"epsilon\")\n    out = _op.nn.batch_norm(\n        g.get_node(ipt_name),\n        g.get_node(scale_name),\n        g.get_node(bias_name),\n        g.get_node(mean_name),\n        g.get_node(variance_name),\n        epsilon=epsilon,\n    )\n    g.add_node(op.output(\"Y\")[0], out[0])\n\n\ndef convert_bmm(g, op, block):\n    \"\"\"Operator converter for bmm.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    y = g.get_node(op.input(\"Y\")[0])\n    y = _op.transpose(y, [0, 2, 1])\n    out = _op.nn.batch_matmul(x, y)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_brelu(g, op, block):\n    \"\"\"Operator converter for brelu.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    t_max = op.attr(\"t_max\")\n    t_min = op.attr(\"t_min\")\n    out = _op.tensor.clip(x, t_min, t_max)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_cast(g, op, block):\n    \"\"\"Operator converter for cast.\"\"\"\n\n    dtype = op.attr(\"out_dtype\")\n    dtype = _convert_dtype_value(dtype)\n    x = g.get_node(op.input(\"X\")[0])\n    out = _op.cast(x, dtype=dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_clip(g, op, block):\n    \"\"\"Operator converter for clip.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    # if the min/max value is a tensor\n    min_max_is_tensor = False\n    if op.input(\"Min\"):\n        min_value = g.get_node(op.input(\"Min\")[0])\n        min_value, infered = try_infer_value(min_value, g.get_params())\n        if infered:\n            min_value = min_value.tolist()[0]\n        if isinstance(min_value, _expr.Expr):\n            min_max_is_tensor = True\n    else:\n        min_value = op.attr(\"min\")\n\n    if op.input(\"Max\"):\n        max_value = g.get_node(op.input(\"Max\")[0])\n        max_value, infered = try_infer_value(max_value, g.get_params())\n        if infered:\n            max_value = max_value.tolist()[0]\n        if isinstance(max_value, _expr.Expr):\n            min_max_is_tensor = True\n    else:\n        max_value = op.attr(\"max\")\n\n    if min_max_is_tensor:\n        if not isinstance(min_value, _expr.Expr):\n            min_value = _op.const(min_value, dtype)\n        if not isinstance(max_value, _expr.Expr):\n            max_value = _op.const(max_value, dtype)\n        out = _op.maximum(x, min_value)\n        out = _op.minimum(out, max_value)\n    else:\n        out = _op.clip(x, min_value, max_value)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_concat(g, op, block):\n    \"\"\"Operator converter for concat.\"\"\"\n\n    inputs = [g.get_node(op.input(\"X\")[i]) for i in range(len(op.input(\"X\")))]\n    axis = op.attr(\"axis\")\n    inputs = _dtype_shape_promotion(inputs)\n    out = _op.concatenate(inputs, axis=axis)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_conv2d(g, op, block):\n    \"\"\"Operator converter for conv2d.\"\"\"\n\n    dilations = op.attr(\"dilations\")\n    groups = op.attr(\"groups\")\n    paddings = op.attr(\"paddings\")\n    padding_algorithm = op.attr(\"padding_algorithm\")\n    strides = op.attr(\"strides\")\n\n    kernel = g.get_node(op.input(\"Filter\")[0])\n    input_x = g.get_node(op.input(\"Input\")[0])\n    out_channels, _, k_h, k_w = infer_shape(kernel)\n    if padding_algorithm == \"VALID\":\n        paddings = [0, 0]\n    elif padding_algorithm == \"SAME\":\n        # Handle history issue of PaddlePaddle\n        # while padding_algorithm == \"SAME\"\n        # dilations will be set to [1, 1]\n        dilations = [1, 1]\n        input_x = autopad(input_x, strides, [k_h, k_w], dilations)\n        paddings = [0, 0]\n    elif padding_algorithm == \"EXPLICIT\":\n        if len(paddings) == 2:\n            paddings = [paddings[0], paddings[1], paddings[0], paddings[1]]\n        elif len(paddings) == 4:\n            paddings = [paddings[0], paddings[2], paddings[1], paddings[3]]\n    else:\n        msg = 'Value {} in attribute \"padding\" of operator Conv is not \"valid.\"'\n        raise tvm.error.OpAttributeInvalid(msg.format(padding_algorithm))\n\n    out = _op.nn.conv2d(\n        input_x,\n        kernel,\n        strides=strides,\n        padding=paddings,\n        dilation=dilations,\n        groups=groups,\n        channels=out_channels,\n        kernel_size=[k_h, k_w],\n    )\n    g.add_node(op.output(\"Output\")[0], out)\n\n\ndef convert_conv2d_transpose(g, op, block):\n    \"\"\"Operator converter for conv2d_transpose.\"\"\"\n\n    dilations = op.attr(\"dilations\")\n    groups = op.attr(\"groups\")\n    paddings = op.attr(\"paddings\")\n    padding_algorithm = op.attr(\"padding_algorithm\")\n    strides = op.attr(\"strides\")\n    output_padding = op.attr(\"output_padding\") if op.attr(\"output_padding\") else [0, 0]\n\n    kernel = g.get_node(op.input(\"Filter\")[0])\n    input_x = g.get_node(op.input(\"Input\")[0])\n    _, out_channels, k_h, k_w = infer_shape(kernel)\n    k_size = [k_h, k_w]\n    if padding_algorithm == \"VALID\":\n        paddings = [0, 0]\n    elif padding_algorithm == \"SAME\":\n        # SAME padding of conv2d_transpose is not same with conv2d\n        # We cannot use auto_pad here, only static shape is supported now\n        dilations = [1, 1]\n        input_shape = shape_of(input_x)\n        h_w = _op.strided_slice(input_shape, [2], [4])\n        try:\n            h_w = infer_value(h_w, g.get_params()).numpy().tolist()\n        except Exception as e:\n            msg = \"The SAME padding algorithm of conv2d_transpose not support dynamic shape\"\n            raise tvm.error.OpAttributeInvalid(msg) from e\n        paddings = []\n        for i in range(2):\n            if strides[i] == 1 or h_w[i] % strides[i] == 0:\n                pad = max(k_size[i] - strides[i], 0)\n            else:\n                pad = max(k_size[i] - (h_w[i] % strides[i]), 0)\n            pad_before = pad // 2\n            pad_after = pad - pad_before\n            paddings.insert(-1, pad_before)\n            paddings.append(pad_after)\n    elif padding_algorithm == \"EXPLICIT\":\n        if len(paddings) == 2:\n            paddings = [paddings[0], paddings[1], paddings[0], paddings[1]]\n        elif len(paddings) == 4:\n            paddings = [paddings[0], paddings[2], paddings[1], paddings[3]]\n    else:\n        msg = 'Value {} in attribute \"padding\" of operator Conv is not \"valid.\"'\n        raise tvm.error.OpAttributeInvalid(msg.format(padding_algorithm))\n\n    out = _op.nn.conv2d_transpose(\n        input_x,\n        kernel,\n        strides=strides,\n        padding=paddings,\n        dilation=dilations,\n        groups=groups,\n        channels=out_channels * groups,\n        kernel_size=k_size,\n        output_padding=output_padding,\n    )\n    g.add_node(op.output(\"Output\")[0], out)\n\n\ndef convert_cumsum(g, op, block):\n    \"\"\"Operator converter for cumsum.\"\"\"\n\n    axis = op.attr(\"axis\")\n    exclusive = op.attr(\"exclusive\")\n    flatten = op.attr(\"flatten\")\n    reverse = op.attr(\"reverse\")\n\n    x = g.get_node(op.input(\"X\")[0])\n    if axis is None or flatten:\n        x = _op.reshape(x, [-1])\n    if reverse:\n        x = _op.reverse(x, axis=axis)\n        out = _op.cumsum(x, axis=axis, exclusive=exclusive)\n        out = _op.reverse(out, axis=axis)\n    else:\n        out = _op.cumsum(x, axis=axis, exclusive=exclusive)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_dropout(g, op, block):\n    \"\"\"Operator converter for dropout.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    g.add_node(op.output(\"Out\")[0], x)\n\n\ndef convert_dot(g, op, block):\n    \"\"\"Operator converter for dot.\"\"\"\n\n    # x, y should be 1D or 2D tensor\n    # when it's 2D tensor, the first dimension means batch dimension\n    x = g.get_node(op.input(\"X\")[0])\n    y = g.get_node(op.input(\"Y\")[0])\n\n    out = _op.sum(_op.multiply(x, y), axis=[-1], keepdims=True)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_elementwise_op(g, op, block):\n    \"\"\"Operator converter for all the elementwise operators.\"\"\"\n\n    op_map = {\n        \"elementwise_div\": \"divide\",\n        \"elementwise_add\": \"add\",\n        \"elementwise_mul\": \"multiply\",\n        \"elementwise_sub\": \"subtract\",\n        \"elementwise_mod\": \"mod\",\n        \"elementwise_max\": \"maximum\",\n        \"elementwise_min\": \"minimum\",\n        \"elementwise_pow\": \"power\",\n        \"elementwise_floordiv\": \"floor_divide\",\n        \"equal\": \"equal\",\n        \"greater_equal\": \"greater_equal\",\n        \"greater_than\": \"greater\",\n        \"less_equal\": \"less_equal\",\n        \"less_than\": \"less\",\n        \"not_equal\": \"not_equal\",\n    }\n    op_func = op_map[op.type]\n    ipt0 = g.get_node(op.input(\"X\")[0])\n    ipt1 = g.get_node(op.input(\"Y\")[0])\n    ipt0_shape = infer_shape(ipt0)\n    ipt1_shape = infer_shape(ipt1)\n    axis = op.attr(\"axis\")\n    if len(ipt0_shape) != len(ipt1_shape):\n        if axis < 0:\n            axis = axis + len(ipt0_shape)\n        if axis != len(ipt0_shape) - 1:\n            ipt1 = _op.expand_dims(ipt1, axis=axis, num_newaxis=(len(ipt0_shape) - axis - 1))\n    op_func = get_relay_op(op_func)\n    out = op_func(ipt0, ipt1)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_elu(g, op, block):\n    \"\"\"Operator converter for elu.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    alpha = op.attr(\"alpha\")\n    alpha = _expr.const(-1.0 * alpha, dtype=dtype)\n    out = alpha * _op.nn.relu(_expr.const(1, dtype=dtype) - _op.exp(x)) + _op.nn.relu(x)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_expand(g, op, block):\n    \"\"\"Operator converter for expand.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    if op.input(\"Shape\"):\n        sizes = g.get_node(op.input(\"Shape\")[0])\n    else:\n        sizes = op.attr(\"shape\")\n\n    if isinstance(sizes, _expr.Expr):\n        sizes = try_infer_value(sizes, parameters=g.get_params())[0]\n\n    if isinstance(sizes, np.ndarray):\n        sizes = sizes.tolist()\n\n    out = _op.broadcast_to(x, sizes)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_expand_as(g, op, block):\n    \"\"\"Operator converter for expand_as.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    target_shape = op.attr(\"target_shape\")\n    out = _op.broadcast_to(x, target_shape)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_feed(g, op, block):\n    \"\"\"Converter for model input node.\"\"\"\n\n    if block is not None:\n        ipt_name = op.output(\"Out\")[0]\n        ipt_shape = block.var(ipt_name).shape\n        ipt_dtype = block.var(ipt_name).dtype\n        ipt_dtype = str(ipt_dtype).strip().split(\".\")[1]\n    else:\n        ipt_shape = op.shape\n        ipt_dtype = str(op.dtype).strip().split(\".\")[1]\n        ipt_name = op.name\n    if g.shape_dict is not None:\n        ipt_shape = g.shape_dict[ipt_name]\n\n    if isinstance(ipt_shape, tuple):\n        ipt_shape = list(ipt_shape)\n    for i, s in enumerate(ipt_shape):\n        if s < 0:\n            ipt_shape[i] = _ty.Any()\n    out = new_var(ipt_name, shape=ipt_shape, dtype=ipt_dtype)\n    g.add_node(ipt_name, out)\n\n\ndef convert_fill_any_like(g, op, block):\n    \"\"\"Operator converter for fill_any_like.\"\"\"\n\n    dtype = op.attr(\"dtype\")\n    dtype = _convert_dtype_value(dtype)\n    x = g.get_node(op.input(\"X\")[0])\n    value = _expr.const(op.attr(\"value\"), dtype=dtype)\n    out = _op.transform.full_like(x, value).astype(dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_fill_constant(g, op, block):\n    \"\"\"Operator converter for fill_constant.\"\"\"\n\n    value = op.attr(\"value\")\n    shape = block.var(op.output(\"Out\")[0]).shape\n    dtype = op.attr(\"dtype\")\n    dtype = _convert_dtype_value(dtype)\n    value = _expr.const(value).astype(dtype)\n    if \"ValueTensor\" in op.input_names and op.input(\"ValueTensor\"):\n        shape = g.get_node(op.input(\"ValueTensor\")[0])\n    if \"ShapeTensor\" in op.input_names and op.input(\"ShapeTensor\"):\n        shape = g.get_node(op.input(\"ShapeTensor\")[0])\n\n    if isinstance(shape, _expr.Expr):\n        shape = try_infer_value(shape, parameters=g.get_params())[0]\n\n    if isinstance(shape, np.ndarray):\n        shape = shape.tolist()\n\n    out = _op.full(value, shape=shape, dtype=dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_fill_constant_batch_size_like(g, op, block):\n    \"\"\"Operator converter for fill_constant_batch_size_like.\"\"\"\n\n    x = g.get_node(op.input(\"Input\")[0])\n    value = op.attr(\"value\")\n    shape = op.attr(\"shape\")\n    input_dim_idx = op.attr(\"input_dim_idx\")\n    output_dim_idx = op.attr(\"output_dim_idx\")\n    dtype = op.attr(\"dtype\")\n\n    dtype = _convert_dtype_value(dtype)\n    input_shape = shape_of(x)\n    batch = _op.strided_slice(input_shape, begin=[input_dim_idx], end=[input_dim_idx + 1]).astype(\n        \"int32\"\n    )\n    shape_before = shape[:output_dim_idx]\n    shape_before = _expr.const(shape_before, dtype=\"int32\")\n    shape_after = shape[output_dim_idx + 1 :]\n    shape_after = _expr.const(shape_after, dtype=\"int32\")\n\n    out_shape = _op.concatenate([shape_before, batch, shape_after], axis=0)\n    out_shape, infered = try_infer_value(out_shape, g.get_params())\n    if infered:\n        out_shape = out_shape.tolist()\n    constant = _expr.const(value, dtype=dtype).astype(dtype)\n    out = _op.full(constant, out_shape, dtype=dtype)\n\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_flatten(g, op, block):\n    \"\"\"Operator converter for flatten.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    input_shape = list(infer_shape(x))\n\n    start = op.attr(\"start_axis\")\n    end = op.attr(\"stop_axis\")\n    ndim = len(input_shape)\n    if end < 0:\n        end += ndim\n    new_shape = [0] * start\n\n    new_shape.append(-1)\n    squeeze_axes = []\n    for i in range(start + 1, end + 1):\n        new_shape.append(1)\n        squeeze_axes.append(i)\n    for _ in range(end + 1, ndim):\n        new_shape.append(0)\n    out = _op.reshape(x, new_shape)\n    if squeeze_axes:\n        out = _op.squeeze(out, axis=squeeze_axes)\n\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_gather(g, op, block):\n    \"\"\"Operator converter for gather.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    index = g.get_node(op.input(\"Index\")[0])\n    axis = op.attr(\"axis\")\n    out = _op.take(x, index, axis)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_gather_nd(g, op, block):\n    \"\"\"Operator converter for gather_nd.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    index = g.get_node(op.input(\"Index\")[0])\n    shape = infer_shape(index)\n    perm = list(range(0, len(shape) - 1))\n    perm.insert(0, len(shape) - 1)\n    index = _op.transpose(index, axes=perm)\n    out = _op.gather_nd(x, index, 0, shape[-1])\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_gelu(g, op, block):\n    \"\"\"Operator converter for gelu.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    out = x * (\n        _expr.const(0.5, dtype=\"float32\")\n        + _op.erf(x * _expr.const(0.5**0.5, dtype=\"float32\")) * _expr.const(0.5, dtype=\"float32\")\n    )\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_group_norm(g, op, block):\n    \"\"\"Operator converter for group_norm.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    num_groups = op.attr(\"groups\")\n    epsilon = op.attr(\"epsilon\")\n    gamma = g.get_node(op.input(\"Scale\")[0])\n    beta = g.get_node(op.input(\"Bias\")[0])\n    out = _op.nn.group_norm(\n        x,\n        gamma=gamma,\n        beta=beta,\n        num_groups=num_groups,\n        axis=1,\n        epsilon=epsilon,\n        center=True,\n        scale=True,\n    )\n    g.add_node(op.output(\"Y\")[0], out)\n\n\ndef convert_hard_shrink(g, op, block):\n    \"\"\"Operator converter for hard_shrink.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    threshold = op.attr(\"threshold\")\n    threshold = _op.const(threshold, dtype)\n    out = _op.logical_or(x < _op.const(-1.0, dtype) * threshold, x > threshold)\n    out = _op.cast(out, dtype) * x\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_hard_sigmoid(g, op, block):\n    \"\"\"Operator converter for hard_sigmoid.\"\"\"\n\n    slope = op.attr(\"slope\")\n    x = g.get_node(op.input(\"X\")[0])\n    out = x * _expr.const(slope) + _expr.const(0.5)\n    out = _op.clip(out, 0, 1)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_hard_swish(g, op, block):\n    \"\"\"Operator converter for hard_swish.\"\"\"\n\n    offset = op.attr(\"offset\")\n    scale = op.attr(\"scale\")\n    threshold = op.attr(\"threshold\")\n    assert np.isclose(offset, 3.0), \"Only support offset==3.0 for PaddlePaddle's hard_swish\"\n    assert np.isclose(scale, 6.0), \"Only support scale==6.0 for PaddlePaddle's hard_swish\"\n    assert np.isclose(threshold, 6.0), \"Only support threshold==6.0 for PaddlePaddle's hard_swish\"\n    x = g.get_node(op.input(\"X\")[0])\n    out = _op.clip(x, -1 * offset, offset)\n    out = out / _expr.const(threshold) + _expr.const(0.5)\n    out = x * out\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_interpolate(g, op, block):\n    \"\"\"Operator converter for interpolate.\"\"\"\n\n    def get_interpolate_mode(op):\n        \"\"\"Get parameters for interpolation methods.\"\"\"\n\n        interp_method = op.attr(\"interp_method\")\n        align_corners = op.attr(\"align_corners\")\n        align_mode = op.attr(\"align_mode\")\n\n        rounding_method = \"\"\n        if interp_method == \"nearest\":\n            interp_method = \"nearest_neighbor\"\n            coordinate_transformation_mode = \"asymmetric\"\n            rounding_method = \"floor\"\n        elif interp_method == \"bilinear\":\n            interp_method = \"linear\"\n            if not align_corners and align_mode == 0:\n                coordinate_transformation_mode = \"half_pixel\"\n            else:\n                if align_corners:\n                    coordinate_transformation_mode = \"align_corners\"\n                else:\n                    coordinate_transformation_mode = \"asymmetric\"\n        elif interp_method == \"bicubic\":\n            interp_method = \"cubic\"\n            if align_corners:\n                coordinate_transformation_mode = \"align_corners\"\n            else:\n                coordinate_transformation_mode = \"half_pixel\"\n        else:\n            msg = \"interp_method {} is not supported for PaddlePaddle's interpolate\"\n            raise tvm.error.OpAttributeInvalid(msg.format(interp_method))\n        return rounding_method, interp_method, coordinate_transformation_mode\n\n    layout = op.attr(\"data_layout\")\n    out_h = op.attr(\"out_h\")\n    out_w = op.attr(\"out_w\")\n    scale = op.attr(\"scale\")\n    if not isinstance(scale, (list, tuple)):\n        scale = [scale, scale]\n\n    x = g.get_node(op.input(\"X\")[0])\n    x_shape = infer_shape(x)\n    assert len(x_shape) == 4, \"Only 4D input tensor is supported for PaddlePaddle's interpolate\"\n    input_out_size = op.input(\"OutSize\")\n    input_size_tensor = op.input(\"SizeTensor\")\n    input_scale = op.input(\"Scale\")\n    rounding_method, interp_method, coordinate_transformation_mode = get_interpolate_mode(op)\n\n    if input_size_tensor:\n        # if out_size is a list of tensor\n        out_size = list()\n        for name in input_size_tensor:\n            size = g.get_node(name)\n            if len(infer_shape(size)) == 0:\n                size = _op.reshape(size, [-1])\n            out_size.append(size)\n        out_size = _op.concatenate(out_size, axis=0)\n        out_size, infered = try_infer_value(out_size, parameters=g.get_params())\n        if infered:\n            out_size = out_size.tolist()\n    elif input_scale:\n        # if out_size is not defined, but scale is defined\n        input_scale = g.get_node(input_scale[0])\n        input_shape = shape_of(x).astype(\"float32\")\n        if layout.startswith(\"NC\"):\n            out_size = _op.strided_slice(input_shape, begin=[2], end=[4]) * input_scale\n        else:\n            out_size = _op.strided_slice(input_shape, begin=[1], end=[3]) * input_scale\n        out_size = out_size.astype(\"int32\")\n        out_size, infered = try_infer_value(out_size, parameters=g.get_params())\n        if infered:\n            out_size = out_size.tolist()\n    elif scale and scale[0] > 0 and scale[1] > 0:\n        # use attribute scale\n        input_shape = shape_of(x).astype(\"float32\")\n        input_scale = _expr.const(np.array([scale[0], scale[1]]).astype(\"float32\"))\n        if layout.startswith(\"NC\"):\n            out_size = _op.strided_slice(input_shape, begin=[2], end=[4]) * input_scale\n        else:\n            out_size = _op.strided_slice(input_shape, begin=[1], end=[3]) * input_scale\n        out_size = out_size.astype(\"int32\")\n        out_size, infered = try_infer_value(out_size, parameters=g.get_params())\n        if infered:\n            out_size = out_size.tolist()\n    elif input_out_size:\n        # if out_size is a tensor\n        out_size = g.get_node(input_out_size[0])\n        out_size, infered = try_infer_value(out_size, parameters=g.get_params())\n        if infered:\n            out_size = out_size.tolist()\n    else:\n        # if out_size is a constant value\n        out_size = [out_h, out_w]\n\n    out = _op.image.resize2d(\n        x,\n        size=out_size,\n        layout=layout,\n        method=interp_method,\n        coordinate_transformation_mode=coordinate_transformation_mode,\n        rounding_method=rounding_method,\n        cubic_alpha=-0.75,\n    )\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_instance_norm(g, op, block):\n    \"\"\"Operator converter for instance_norm.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    gamma = g.get_node(op.input(\"Scale\")[0])\n    beta = g.get_node(op.input(\"Bias\")[0])\n    epsilon = op.attr(\"epsilon\")\n\n    scale = center = True\n    out = _op.nn.instance_norm(x, gamma, beta, axis=1, epsilon=epsilon, center=center, scale=scale)\n    g.add_node(op.output(\"Y\")[0], out)\n\n\ndef convert_layer_norm(g, op, block):\n    \"\"\"Operator converter for layer_norm.\"\"\"\n\n    begin_norm_axis = op.attr(\"begin_norm_axis\")\n    epsilon = op.attr(\"epsilon\")\n    x = g.get_node(op.input(\"X\")[0])\n    bias_input = op.input(\"Bias\")\n    scale_input = op.input(\"Scale\")\n\n    x_shape = infer_shape(x)\n    assert begin_norm_axis in (\n        len(x_shape) - 1,\n        -1,\n    ), \"Support only normalization over last one dimension.\"\n\n    if bias_input:\n        bias = g.get_node(bias_input[0])\n    else:\n        bias = _expr.const(np.zeros(x_shape[begin_norm_axis]))\n\n    if scale_input:\n        scale = g.get_node(scale_input[0])\n    else:\n        scale = _expr.const(np.ones(x_shape[begin_norm_axis]))\n\n    out = _op.nn.layer_norm(\n        x, gamma=scale, beta=bias, axis=begin_norm_axis, epsilon=epsilon, center=True, scale=True\n    )\n    g.add_node(op.output(\"Y\")[0], out)\n\n\ndef convert_leaky_relu(g, op, block):\n    \"\"\"Operator converter for leaky_relu.\"\"\"\n\n    alpha = op.attr(\"alpha\")\n    x = g.get_node(op.input(\"X\")[0])\n    out = _op.nn.leaky_relu(x, alpha=alpha)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_log1p(g, op, block):\n    \"\"\"Operator converter for log1p.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    one = _expr.const(1, dtype=dtype)\n    out = _op.log(x + one)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_logical_not(g, op, block):\n    \"\"\"Operator converter for logical_not op.\"\"\"\n\n    ipt0 = g.get_node(op.input(\"X\")[0])\n    op_func = get_relay_op(op.type)\n    out = op_func(ipt0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_logsigmoid(g, op, block):\n    \"\"\"Operator converter for logsigmoid.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    out = _op.log(_op.tensor.sigmoid(x))\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_logsoftmax(g, op, block):\n    \"\"\"Operator converter for logsoftmax.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    axis = op.attr(\"axis\")\n    ndim = len(infer_shape(x))\n    if axis < 0:\n        axis += ndim\n    m = _op.max(x, [axis], keepdims=True)\n    e = _op.exp(x - m)\n    s = _op.sum(e, [axis], keepdims=True)\n    out = x - m - _op.log(s)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_logsumexp(g, op, block):\n    \"\"\"Operator converter for logsumexp.\"\"\"\n\n    input_x = g.get_node(op.input(\"X\")[0])\n    axis = op.attr(\"axis\")\n    if op.attr(\"reduce_all\"):\n        axis = None\n    keepdims = op.attr(\"keepdim\")\n    out = get_relay_op(\"logsumexp\")(input_x, axis=axis, keepdims=keepdims)\n    if not axis and not keepdims:\n        out = _op.expand_dims(out, axis=0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_lookup_table(g, op, block):\n    \"\"\"Operator converter for lookup_table_v2.\"\"\"\n\n    indices = g.get_node(op.input(\"Ids\")[0])\n    padding_idx = op.attr(\"padding_idx\")\n    weights = g.get_node(op.input(\"W\")[0])\n    if padding_idx != -1:\n        if op.input(\"W\")[0] in g.get_params():\n            weights = g.get_params(op.input(\"W\")[0])\n            weights[padding_idx] = 0.0\n            weights = _expr.const(weights)\n        else:\n            shape, infered = try_infer_value(shape_of(weights), g.get_params())\n            if infered:\n                shape = shape.tolist()\n            assert not isinstance(\n                shape, _expr.Expr\n            ), \"Shape of weight has to be fixed for PaddlePaddle's lookup_table\"\n            filters = np.ones(shape).astype(infer_type(weights).checked_type.dtype)\n            filters[padding_idx] = 0.0\n            filters = _expr.const(filters)\n            weights = weights * filters\n    out = _op.take(weights, indices.astype(\"int32\"), axis=0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_matmul(g, op, block):\n    \"\"\"Operator converter for matmul.\"\"\"\n\n    inputs = [g.get_node(op.input(\"X\")[0]), g.get_node(op.input(\"Y\")[0])]\n    a_shape = infer_shape(inputs[0])\n    b_shape = infer_shape(inputs[1])\n    if op.has_attr(\"trans_x\"):\n        # for matmul_v2\n        trans_x = op.attr(\"trans_x\")\n        trans_y = op.attr(\"trans_y\")\n    else:\n        # for matmul\n        trans_x = op.attr(\"transpose_X\")\n        trans_y = op.attr(\"transpose_Y\")\n    if trans_x:\n        perm = list(range(len(a_shape)))\n        perm[-2] = len(a_shape) - 1\n        perm[-1] = len(a_shape) - 2\n        inputs[0] = _op.transpose(inputs[0], axes=perm)\n    if trans_y:\n        perm = list(range(len(b_shape)))\n        perm[-2] = len(b_shape) - 1\n        perm[-1] = len(b_shape) - 2\n        inputs[1] = _op.transpose(inputs[1], axes=perm)\n\n    # This implemention almost keeps same with ONNX\n    # Need to check input shape as batch matmul must be supported.\n    a_shape = shape_of(inputs[0], dtype=\"int32\")\n    a_rank = infer_shape(a_shape)[0]\n    b_shape = shape_of(inputs[1], dtype=\"int32\")\n    b_rank = infer_shape(b_shape)[0]\n    # When performing a batch matmul, we need to properly handle N-dim shapes.\n    if a_rank > 2 or b_rank > 2:\n\n        def flatten_to_nd(x, x_shape, nd=3):\n            ndims = infer_shape(x_shape)[0]\n            if ndims == nd:\n                return x\n            newshape = _op.concatenate(\n                [\n                    _expr.const([-1], dtype=infer_type(x_shape).checked_type.dtype),\n                    _op.strided_slice(x_shape, [ndims - nd + 1], [ndims]),\n                ],\n                0,\n            )\n            out = _op.reshape(x, fold_constant(newshape))\n            return out\n\n        b_type = infer_type(inputs[1])\n        # Convert to dense if the second matrix is 2d and non-dynamic\n        if b_rank == 2 and not _ty.is_dynamic(b_type.checked_type):\n            a = flatten_to_nd(inputs[0], a_shape, 2)\n            b = _op.transpose(inputs[1])\n            output = _op.nn.dense(a, b)\n        else:\n            # Convert a and b into 3 dimensional tensors.\n            a = flatten_to_nd(inputs[0], a_shape, 3)\n            b = flatten_to_nd(inputs[1], b_shape, 3)\n            # Transpose matrix dimensions of b.\n            b = _op.transpose(b, [0, 2, 1])\n            # Perform a batch matmul.\n            output = _op.nn.batch_matmul(a, b)\n        # Determine the output batch dimension.\n        if a_rank > b_rank:\n            out_batch = _op.strided_slice(a_shape, [0], [a_rank - 2])\n        elif a_rank < b_rank:\n            out_batch = _op.strided_slice(b_shape, [0], [b_rank - 2])\n        # If its unclear how broadcasting should be applied, the output\n        # shape is determined by choosing the maximum value from each input.\n        else:\n            out_batch = _op.concatenate(\n                [\n                    _op.maximum(\n                        _op.strided_slice(a_shape, [i], [i + 1]),\n                        _op.strided_slice(b_shape, [i], [i + 1]),\n                    )\n                    for i in range(a_rank - 2)\n                ],\n                0,\n            )\n        # Reshape output to original dimensions.\n        final_shape = _op.concatenate(\n            [\n                out_batch,\n                _op.strided_slice(\n                    a_shape, [infer_shape(a_shape)[0] - 2], [infer_shape(a_shape)[0] - 1]\n                ),\n                _op.strided_slice(\n                    b_shape, [infer_shape(b_shape)[0] - 1], [infer_shape(b_shape)[0]]\n                ),\n            ],\n            0,\n        )\n        out = _op.reshape(output, fold_constant(final_shape))\n    else:\n        if b_rank == 1:\n            inputs[1] = _op.expand_dims(inputs[1], 1, 1)\n        # Otherwise a simple dense op will get the job done.\n        input_1_t = _op.transpose(inputs[1], axes=(1, 0))\n        out = _op.nn.dense(inputs[0], input_1_t)\n        if b_rank == 1:\n            out = _op.squeeze(out, axis=[-1])\n    if op.has_attr(\"alpha\"):\n        alpha = op.attr(\"alpha\")\n        if not np.isclose(alpha, 1.0):\n            out = out * _expr.const(alpha).astype(\"float32\")\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_meshgrid(g, op, block):\n    \"\"\"Operator converter for meshgrid.\"\"\"\n\n    inputs = op.input(\"X\")\n    x = [g.get_node(i) for i in inputs]\n    outs = _op.meshgrid(x, indexing=\"ij\")\n    for i, out in enumerate(outs):\n        g.add_node(op.output(\"Out\")[i], out)\n\n\ndef convert_mul(g, op, block):\n    \"\"\"Operator converter for mul.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    y = g.get_node(op.input(\"Y\")[0])\n    x_num_col_dims = op.attr(\"x_num_col_dims\")\n    y_num_col_dims = op.attr(\"y_num_col_dims\")\n    x_shape = shape_of(x, dtype=\"int32\")\n    y_shape = shape_of(y, dtype=\"int32\")\n    x_dim = infer_shape(x_shape)[0]\n    y_dim = infer_shape(y_shape)[0]\n    if x_num_col_dims < 0:\n        x_num_col_dims += x_dim\n    if y_num_col_dims < 0:\n        y_num_col_dims += y_dim\n    if x_num_col_dims == 1:\n        x = _op.nn.batch_flatten(x)\n    else:\n        pre_shape = _op.prod(_op.strided_slice(x_shape, [0], [x_num_col_dims], [1]), keepdims=True)\n        post_shape = _op.prod(\n            _op.strided_slice(x_shape, [x_num_col_dims], [x_dim], [1]), keepdims=True\n        )\n        new_shape = _op.concatenate([pre_shape, post_shape], axis=0)\n        new_shape = fold_constant(new_shape)\n        x = _op.reshape(x, new_shape)\n    if y_num_col_dims == 1:\n        y = _op.nn.batch_flatten(y)\n    else:\n        pre_shape = _op.prod(_op.strided_slice(y_shape, [0], [y_num_col_dims], [1]), keepdims=True)\n        post_shape = _op.prod(\n            _op.strided_slice(y_shape, [y_num_col_dims], [y_dim], [1]), keepdims=True\n        )\n        new_shape = _op.concatenate([pre_shape, post_shape], axis=0)\n        new_shape = fold_constant(new_shape)\n        y = _op.reshape(y, new_shape)\n    y = _op.transpose(y)\n    out = _op.nn.dense(x, y)\n    out_pre_shape = _op.strided_slice(x_shape, [0], [x_num_col_dims], [1])\n    out_post_shape = _op.strided_slice(y_shape, [y_num_col_dims], [y_dim], [1])\n    out_shape = _op.concatenate([out_pre_shape, out_post_shape], axis=0)\n    out_shape = fold_constant(out_shape)\n    out = _op.reshape(out, out_shape)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_mv(g, op, block):\n    \"\"\"Operator converter for mv.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    y = g.get_node(op.input(\"Vec\")[0])\n    y = _op.expand_dims(y, axis=-1)\n    y = _op.transpose(y)\n    out = _op.nn.dense(x, y)\n    out = _op.squeeze(out, axis=[-1])\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_padding(g, op, block):\n    \"\"\"Operator converter for padding.\"\"\"\n\n    input_x = g.get_node(op.input(\"X\")[0])\n    input_padding = op.input(\"Paddings\")\n    if input_padding:\n        padding = g.get_node(input_padding[0])\n        padding = infer_value(padding, g.get_params()).numpy().tolist()\n    else:\n        padding = op.attr(\"paddings\")\n    padding = op.attr(\"paddings\")\n    value = op.attr(\"value\")\n    data_format = op.attr(\"data_format\")\n    mode = op.attr(\"mode\")\n    assert mode != \"circular\", \"Don't support mod='circular' for PaddlePaddle's padding\"\n    if mode == \"replicate\":\n        mode = \"edge\"\n\n    pad_len = len(padding)\n    new_paddings = [0] * (pad_len + 4)\n    for i in range(0, pad_len, 2):\n        index = -1 - i\n        if data_format[:2] != \"NC\":\n            index = -3 - i\n        new_paddings[index] = padding[i + 1]\n        new_paddings[index - 1] = padding[i]\n\n    new_paddings = [new_paddings[i : i + 2] for i in range(0, len(new_paddings), 2)]\n\n    out = _op.nn.pad(input_x, new_paddings, pad_value=value, pad_mode=mode)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_pixel_shuffle(g, op, block):\n    \"\"\"Operator converter for pixel_shuffle.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    upscale_factor = op.attr(\"upscale_factor\")\n    out = _op.nn.depth_to_space(x, upscale_factor, mode=\"CRD\")\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_pool2d(g, op, block):\n    \"\"\"Operator converter for pool2d.\"\"\"\n\n    adaptive = op.attr(\"adaptive\")\n    ceil_mode = op.attr(\"ceil_mode\")\n    global_pooling = op.attr(\"global_pooling\")\n    ksize = op.attr(\"ksize\")\n    paddings = op.attr(\"paddings\")\n    padding_algorithm = op.attr(\"padding_algorithm\")\n    pooling_type = op.attr(\"pooling_type\")\n    data_format = op.attr(\"data_format\")\n\n    if global_pooling:\n        adaptive = True\n        ksize = [1, 1]\n\n    input_x = g.get_node(op.input(\"X\")[0])\n    _, _, in_h, in_w = infer_shape(input_x)\n\n    op_map = {\n        \"avg\": \"avg_pool2d\",\n        \"max\": \"max_pool2d\",\n    }\n\n    strides = op.attr(\"strides\")\n    if isinstance(strides, int):\n        strides = [strides, strides]\n    if isinstance(ksize, int):\n        ksize = [ksize, ksize]\n    if isinstance(paddings, int):\n        paddings = [paddings] * 2\n\n    if padding_algorithm == \"VALID\":\n        paddings = [0, 0]\n    elif padding_algorithm == \"SAME\":\n        input_x = autopad(input_x, strides, ksize)\n        paddings = [0, 0]\n    elif padding_algorithm == \"EXPLICIT\":\n        if len(paddings) == 2:\n            paddings = [paddings[0], paddings[1], paddings[0], paddings[1]]\n        elif len(paddings) == 4:\n            paddings = [paddings[0], paddings[2], paddings[1], paddings[3]]\n    else:\n        msg = 'Value {} in attribute \"padding\" of operator Pool2d is not \"valid.\"'\n        raise tvm.error.OpAttributeInvalid(msg.format(padding_algorithm))\n\n    # handle with special case\n    # while kernel size less than input size\n    # shrink kernel size to input size\n    if (\n        not isinstance(in_h, _op.Expr)\n        and padding_algorithm == \"EXPLICIT\"\n        and in_h + paddings[0] + paddings[2] < ksize[0]\n    ):\n        ksize[0] = in_h\n    if (\n        not isinstance(in_w, _op.Expr)\n        and padding_algorithm == \"EXPLICIT\"\n        and in_w + paddings[1] + paddings[3] < ksize[1]\n    ):\n        ksize[1] = in_w\n\n    if not adaptive:\n        if pooling_type == \"avg\":\n            exclusive = op.attr(\"exclusive\")\n            out = _op.nn.avg_pool2d(\n                input_x,\n                pool_size=ksize,\n                strides=strides,\n                padding=paddings,\n                ceil_mode=ceil_mode,\n                count_include_pad=not exclusive,\n            )\n        else:\n            out = getattr(_op.nn, op_map[pooling_type])(\n                input_x, pool_size=ksize, strides=strides, padding=paddings, ceil_mode=ceil_mode\n            )\n    else:\n        out = getattr(_op.nn, \"adaptive_\" + op_map[pooling_type])(\n            input_x, output_size=ksize, layout=data_format\n        )\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_pow(g, op, block):\n    \"\"\"Operator converter for pow.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = block.var(op.output(\"Out\")[0]).dtype\n    dtype = _convert_dtype_value(dtype)\n    factor = op.attr(\"factor\")\n    factor = _expr.const(factor, dtype=dtype)\n    out = _op.power(x, factor)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_prelu(g, op, block):\n    \"\"\"Operator converter for prelu.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    alpha = g.get_node(op.input(\"Alpha\")[0])\n    ndims = len(infer_shape(x))\n    axis = 0 if ndims <= 1 else 1\n    mode = op.attr(\"mode\")\n    if mode == \"all\":\n        if ndims == 1:\n            shape = _op.strided_slice(shape_of(x), [0], [1])\n        else:\n            shape = _op.strided_slice(shape_of(x), [1], [2])\n        alpha = _op.broadcast_to(alpha, fold_constant(shape))\n    out = _op.nn.prelu(x, alpha, axis)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_range(g, op, block):\n    \"\"\"Operator converter for range.\"\"\"\n\n    start = g.get_node(op.input(\"Start\")[0])\n    stop = g.get_node(op.input(\"End\")[0])\n    step = g.get_node(op.input(\"Step\")[0])\n    dtype = infer_type(start).checked_type.dtype\n\n    params = []\n    for param in (start, stop, step):\n        param, infered = try_infer_value(param, g.get_params())\n        if infered:\n            param = param.tolist()\n        if isinstance(param, list):\n            param = param[0]\n        if isinstance(param, _expr.Expr):\n            param = _op.squeeze(param)\n        else:\n            param = _op.const(param, dtype=dtype)\n        params.append(param)\n\n    out = _op.transform.arange(params[0], params[1], params[2], dtype=dtype)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_reciprocal(g, op, block):\n    \"\"\"Operator converter for reciprocal.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    out = _expr.const(1.0, dtype) / x\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_reduce(g, op, block):\n    \"\"\"Operator converter for series of reduce operators.\"\"\"\n\n    op_map = {\n        \"reduce_all\": \"all\",\n        \"reduce_any\": \"any\",\n        \"reduce_max\": \"max\",\n        \"reduce_min\": \"min\",\n        \"reduce_prod\": \"prod\",\n        \"reduce_sum\": \"sum\",\n        \"reduce_mean\": \"mean\",\n    }\n    op_name = op_map[op.type]\n    input_x = g.get_node(op.input(\"X\")[0])\n    axis = op.attr(\"dim\")\n    if op.attr(\"reduce_all\"):\n        axis = None\n    keepdims = op.attr(\"keep_dim\")\n    out = get_relay_op(op_name)(input_x, axis=axis, keepdims=keepdims)\n    if not axis and not keepdims:\n        # use `expand_dims` to solve the following situation\n        # for TVM, the shape of `out` will be (, )\n        # for Paddle, the shape of `out` will be [1]\n        out = _op.expand_dims(out, axis=0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_relu6(g, op, block):\n    \"\"\"Operator converter for relu6.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    out = _op.clip(x, 0.0, 6.0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_reshape(g, op, block):\n    \"\"\"Operator converter for reshape.\"\"\"\n\n    input_shape = op.input(\"Shape\")\n    input_shape_tensor = op.input(\"ShapeTensor\")\n    data = g.get_node(op.input(\"X\")[0])\n    if input_shape:\n        new_shape = g.get_node(input_shape[0])\n    elif input_shape_tensor:\n        new_shape = []\n        for shape_name in input_shape_tensor:\n            shape = g.get_node(shape_name)\n            if len(infer_shape(shape)) == 0:\n                shape = _op.reshape(shape, [-1])\n            new_shape.append(shape)\n        new_shape = _op.concatenate(new_shape, axis=0)\n        new_shape, infered = try_infer_value(new_shape, parameters=g.get_params())\n        if infered:\n            new_shape = new_shape.tolist()\n    else:\n        new_shape = op.attr(\"shape\")\n    out = _op.reshape(data, new_shape)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_rnn(g, op, block):\n    \"\"\"Operator converter for rnn.\"\"\"\n\n    def generate_lstm(\n        input_seqs,\n        hidden_state,\n        cell_state,\n        w_inp,\n        w_hid,\n        b_inp,\n        b_hid,\n        f_act,\n        g_act,\n        h_act,\n        backwards=False,\n    ):\n        \"\"\"Implementation of LSTM cell for paddlepaddle of TVM\"\"\"\n\n        h_list = []\n        seq_length = len(input_seqs)\n        for i in range(seq_length):\n            step = input_seqs[i] if not backwards else input_seqs[seq_length - (i + 1)]\n            step = _op.squeeze(step, axis=[0])\n            gates = _op.nn.dense(step, w_inp) + _op.nn.dense(hidden_state, w_hid)\n            if b_inp is not None:\n                gates += b_inp\n            if b_hid is not None:\n                gates += b_hid\n            i, f, c, o = _op.split(gates, 4, axis=-1)\n\n            i = f_act(i)\n            f = f_act(f)\n\n            c = g_act(c)\n            C = f * cell_state + i * c\n\n            o = f_act(o)\n\n            H = o * h_act(C)\n\n            hidden_state = H\n            cell_state = C\n            h_list.append(_op.expand_dims(H, axis=0))\n\n        if backwards:\n            h_list = h_list[::-1]\n\n        # Concatenate outputs and add back in direction axis.\n        concatenated = _op.concatenate(h_list, 0)\n        output = _op.expand_dims(concatenated, axis=1)\n        hidden_state = _op.expand_dims(hidden_state, axis=0)\n        cell_state = _op.expand_dims(cell_state, axis=0)\n\n        return output, hidden_state, cell_state\n\n    def generate_gru(\n        input_seqs, hidden_state, w_inp, w_hid, b_inp, b_hid, rz_act, n_act, backwards=False\n    ):\n        \"\"\"Implementation of GRU cell for paddlepaddle of TVM\"\"\"\n\n        h_list = []\n        seq_length = len(input_seqs)\n        for i in range(seq_length):\n            step = input_seqs[i] if not backwards else input_seqs[seq_length - (i + 1)]\n            step = _op.squeeze(step, axis=[0])\n            xwt = _op.nn.dense(step, w_inp)\n            hwt = _op.nn.dense(hidden_state, w_hid)\n            if b_inp is not None:\n                xwt += b_inp\n            if b_hid is not None:\n                hwt += b_hid\n            i_r, i_z, i_n = _op.split(xwt, 3, axis=-1)\n            h_r, h_z, h_n = _op.split(hwt, 3, axis=-1)\n\n            r_gate = rz_act(i_r + h_r)\n            z_gate = rz_act(i_z + h_z)\n            n_gate = n_act(i_n + r_gate * h_n)\n\n            hidden_state = (hidden_state - n_gate) * z_gate + n_gate\n            h_list.append(_op.expand_dims(hidden_state, axis=0))\n\n        if backwards:\n            h_list = h_list[::-1]\n\n        # Concatenate outputs and add back in direction axis.\n        concatenated = _op.concatenate(h_list, 0)\n        output = _op.expand_dims(concatenated, axis=1)\n        hidden_state = _op.expand_dims(hidden_state, axis=0)\n\n        return output, hidden_state\n\n    def generate_simplernn(\n        input_seqs, hidden_state, w_inp, w_hid, b_inp, b_hid, n_act, backwards=False\n    ):\n        \"\"\"Implementation of SimpleRNN cell for paddlepaddle of TVM\"\"\"\n\n        h_list = []\n        seq_length = len(input_seqs)\n        for i in range(seq_length):\n            step = input_seqs[i] if not backwards else input_seqs[seq_length - (i + 1)]\n            step = _op.squeeze(step, axis=[0])\n            xwt = _op.nn.dense(step, w_inp)\n            hwt = _op.nn.dense(hidden_state, w_hid)\n            if b_inp is not None:\n                xwt += b_inp\n            if b_hid is not None:\n                hwt += b_hid\n\n            n_gate = n_act(xwt + hwt)\n\n            hidden_state = n_gate\n            h_list.append(_op.expand_dims(hidden_state, axis=0))\n\n        if backwards:\n            h_list = h_list[::-1]\n\n        # Concatenate outputs and add back in direction axis.\n        concatenated = _op.concatenate(h_list, 0)\n        output = _op.expand_dims(concatenated, axis=1)\n        hidden_state = _op.expand_dims(hidden_state, axis=0)\n\n        return output, hidden_state\n\n    def make_param_inputs(g, node, layer, hidden_size, num_layers):\n        \"\"\"Param for weight and bias.\"\"\"\n\n        bidirect_len = 4 if node.attr(\"is_bidirec\") else 2\n        all_layer_param_len = len(node.input(\"WeightList\"))\n        weight_list = node.input(\"WeightList\")[: all_layer_param_len // 2]\n        bias_list = node.input(\"WeightList\")[all_layer_param_len // 2 :]\n\n        layer_weight_list = weight_list[layer * bidirect_len : layer * bidirect_len + bidirect_len]\n        layer_bias_list = bias_list[layer * bidirect_len : layer * bidirect_len + bidirect_len]\n        param_list = layer_weight_list + layer_bias_list\n        param_list_len = len(param_list)\n\n        input_weights = param_list[0 : param_list_len // 2 : 2]\n        hidden_weights = param_list[1 : param_list_len // 2 : 2]\n\n        input_bias = param_list[param_list_len // 2 : param_list_len : 2]\n        hidden_bias = param_list[param_list_len // 2 + 1 : param_list_len : 2]\n\n        return input_weights, hidden_weights, input_bias, hidden_bias\n\n    def make_init_param_inputs(g, node, layer):\n        \"\"\"Init param for inputs.\"\"\"\n\n        mode = node.attr(\"mode\")\n        if mode == \"LSTM\":\n            all_init_h, all_init_c = node.input(\"PreState\")\n            bidirect_len = 2 if node.attr(\"is_bidirec\") else 1\n            init_h = _op.strided_slice(\n                g.get_node(all_init_h),\n                [layer * bidirect_len],\n                [layer * bidirect_len + bidirect_len],\n                axes=[0],\n            )\n            init_c = _op.strided_slice(\n                g.get_node(all_init_c),\n                [layer * bidirect_len],\n                [layer * bidirect_len + bidirect_len],\n                axes=[0],\n            )\n            return init_h, init_c\n        all_init_h = node.input(\"PreState\")[0]\n        bidirect_len = 2 if node.attr(\"is_bidirec\") else 1\n        init_h = _op.strided_slice(\n            g.get_node(all_init_h),\n            [layer * bidirect_len],\n            [layer * bidirect_len + bidirect_len],\n            axes=[0],\n        )\n        return init_h\n\n    hidden_size = op.attr(\"hidden_size\")\n    num_layers = op.attr(\"num_layers\")\n    is_bidirec = op.attr(\"is_bidirec\")\n    mode = op.attr(\"mode\")\n\n    input_x = g.get_node(op.input(\"Input\")[0])\n\n    num_directions = 1\n    if is_bidirec:\n        num_directions = 2\n\n    x_shape = infer_shape(input_x)\n    time_steps = x_shape[0]\n    x_steps = _op.split(input_x, indices_or_sections=time_steps, axis=0)\n    for layer in range(num_layers):\n        input_weights, hidden_weights, input_bias, hidden_bias = make_param_inputs(\n            g, op, layer, hidden_size, num_layers\n        )\n        if mode == \"LSTM\":\n            init_h, init_c = make_init_param_inputs(g, op, layer)\n            init_hs = _op.split(init_h, num_directions)\n            init_cs = _op.split(init_c, num_directions)\n            result_output = []\n            result_H = []\n            result_C = []\n            for i in range(num_directions):\n                H_t = _op.squeeze(init_hs[i], axis=[0])\n                C_t = _op.squeeze(init_cs[i], axis=[0])\n                W = g.get_node(input_weights[i])\n                R = g.get_node(hidden_weights[i])\n                WB = g.get_node(input_bias[i])\n                RB = g.get_node(hidden_bias[i])\n                output, H, C = generate_lstm(\n                    input_seqs=x_steps,\n                    hidden_state=H_t,\n                    cell_state=C_t,\n                    w_inp=W,\n                    w_hid=R,\n                    b_inp=WB,\n                    b_hid=RB,\n                    f_act=_op.sigmoid,\n                    g_act=_op.tanh,\n                    h_act=_op.tanh,\n                    backwards=i == 1,\n                )\n                result_output.append(output)\n                result_H.append(H)\n                result_C.append(C)\n            output = _op.concatenate(result_output, axis=1)\n            H = _op.concatenate(result_H, axis=0)\n            C = _op.concatenate(result_C, axis=0)\n        elif mode == \"GRU\":\n            init_h = make_init_param_inputs(g, op, layer)\n            init_hs = _op.split(init_h, num_directions)\n            result_output = []\n            result_H = []\n            for i in range(num_directions):\n                H_t = _op.squeeze(init_hs[i], axis=[0])\n                W = g.get_node(input_weights[i])\n                R = g.get_node(hidden_weights[i])\n                WB = g.get_node(input_bias[i])\n                RB = g.get_node(hidden_bias[i])\n                output, H = generate_gru(\n                    input_seqs=x_steps,\n                    hidden_state=H_t,\n                    w_inp=W,\n                    w_hid=R,\n                    b_inp=WB,\n                    b_hid=RB,\n                    rz_act=_op.sigmoid,\n                    n_act=_op.tanh,\n                    backwards=i == 1,\n                )\n                result_output.append(output)\n                result_H.append(H)\n            output = _op.concatenate(result_output, axis=1)\n            H = _op.concatenate(result_H, axis=0)\n        elif mode == \"RNN_TANH\":\n            init_h = make_init_param_inputs(g, op, layer)\n            init_hs = _op.split(init_h, num_directions)\n            result_output = []\n            result_H = []\n            for i in range(num_directions):\n                H_t = _op.squeeze(init_hs[i], axis=[0])\n                W = g.get_node(input_weights[i])\n                R = g.get_node(hidden_weights[i])\n                WB = g.get_node(input_bias[i])\n                RB = g.get_node(hidden_bias[i])\n                output, H = generate_simplernn(\n                    input_seqs=x_steps,\n                    hidden_state=H_t,\n                    w_inp=W,\n                    w_hid=R,\n                    b_inp=WB,\n                    b_hid=RB,\n                    n_act=_op.tanh,\n                    backwards=i == 1,\n                )\n                result_output.append(output)\n                result_H.append(H)\n            output = _op.concatenate(result_output, axis=1)\n            H = _op.concatenate(result_H, axis=0)\n\n        output = _op.transpose(output, axes=[0, 2, 1, 3])\n        output = _op.reshape(output, newshape=(0, 0, -1))\n        x_steps = _op.split(output, indices_or_sections=time_steps, axis=0)\n\n    g.add_node(op.output(\"Out\")[0], output)\n\n\ndef convert_scale(g, op, block):\n    \"\"\"Operator converter for scale.\"\"\"\n\n    scale = op.attr(\"scale\")\n    bias = op.attr(\"bias\")\n    bias_after_scale = op.attr(\"bias_after_scale\")\n    x = g.get_node(op.input(\"X\")[0])\n    if np.isclose(scale, 1.0) and np.isclose(bias, 0.0):\n        out = x\n    else:\n        if np.isclose(bias, 0.0):\n            out = x * _expr.const(np.array(scale).astype(\"float32\"))\n        elif np.isclose(scale, 1.0):\n            out = x + _expr.const(np.array(bias).astype(\"float32\"))\n        else:\n            if bias_after_scale:\n                out = x * _expr.const(np.array(scale).astype(\"float32\")) + _expr.const(\n                    np.array(bias).astype(\"float32\")\n                )\n            else:\n                out = (x + _expr.const(np.array(bias).astype(\"float32\"))) * _expr.const(\n                    np.array(scale).astype(\"float32\")\n                )\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_scatter(g, op, block):\n    \"\"\"Operator converter for scatter.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    index = g.get_node(op.input(\"Ids\")[0])\n    updates = g.get_node(op.input(\"Updates\")[0])\n    overwrite = op.attr(\"overwrite\")\n\n    shape = infer_shape(updates)\n    ndims = len(shape)\n    index = _op.expand_dims(index, axis=-1, num_newaxis=ndims - 1)\n    index = _op.transform.broadcast_to(index, shape)\n\n    if overwrite:\n        out = _op.scatter(x, index, updates, axis=0)\n    else:\n        out = _op.scatter_add(_op.zeros_like(x), index, updates, axis=0)\n        out += _op.scatter(x, index, _op.zeros_like(updates), axis=0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_scatter_nd_add(g, op, block):\n    \"\"\"Operator converter for scatter_nd_add.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    index = g.get_node(op.input(\"Index\")[0])\n    updates = g.get_node(op.input(\"Updates\")[0])\n    indices_dim = len(infer_shape(index))\n    axes = list(range(indices_dim))\n    index = _op.transpose(index, axes[-1:] + axes[:-1])\n    out = _op.scatter_nd(x, index, updates, mode=\"add\")\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_selu(g, op, block):\n    \"\"\"Operator converter for selu.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    alpha = _op.const(op.attr(\"alpha\"), dtype)\n    scale = _op.const(op.attr(\"scale\"), dtype)\n    out = (\n        _expr.const(-1.0, dtype=dtype)\n        * alpha\n        * _op.nn.relu(_expr.const(1.0, dtype=dtype) - _op.exp(x))\n    )\n    out = scale * (out + _op.nn.relu(x))\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_shape(g, op, block):\n    \"\"\"Operator converter for shape.\"\"\"\n\n    x = g.get_node(op.input(\"Input\")[0])\n    out = shape_of(x, dtype=\"int32\")\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_size(g, op, block):\n    \"\"\"Operator converter for size.\"\"\"\n\n    input_x = g.get_node(op.input(\"Input\")[0])\n    out = _op.ndarray_size(input_x, dtype=\"int64\")\n    out = _op.expand_dims(out, axis=0)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_slice(g, op, block):\n    \"\"\"Operator converter for slice.\"\"\"\n\n    data = g.get_node(op.input(\"Input\")[0])\n    dims = len(infer_shape(data))\n\n    axes = op.attr(\"axes\")\n    indices = _expr.const(axes, dtype=\"int64\")\n\n    decrease_axis = op.attr(\"decrease_axis\")\n    if isinstance(decrease_axis, int):\n        decrease_axis = [decrease_axis]\n\n    if op.input(\"StartsTensor\"):\n        starts = g.get_node(op.input(\"StartsTensor\")[0])\n        starts, infered = try_infer_value(starts, g.get_params())\n        if infered:\n            starts = starts.tolist()\n    elif op.input(\"StartsTensorList\"):\n        starts = []\n        for start_index in op.input(\"StartsTensorList\"):\n            start_index = g.get_node(start_index).astype(\"int64\")\n            starts.append(start_index)\n        starts = _op.concatenate(starts, axis=0)\n        starts, infered = try_infer_value(starts, g.get_params())\n        if infered:\n            starts = starts.tolist()\n    else:\n        starts = op.attr(\"starts\")\n\n    if len(axes) < dims:\n        if isinstance(starts, _expr.Expr):\n            starts = _op.scatter(\n                _op.const([0] * dims, dtype=infer_type(starts).checked_type.dtype),\n                indices,\n                starts,\n                axis=0,\n            )\n        else:\n            base = [0] * dims\n            for i, axis in enumerate(axes):\n                base[axis] = starts[i]\n            starts = base\n\n    if op.input(\"EndsTensor\"):\n        ends = g.get_node(op.input(\"EndsTensor\")[0])\n        ends, infered = try_infer_value(ends, g.get_params())\n        if infered:\n            ends = ends.tolist()\n    elif op.input(\"EndsTensorList\"):\n        ends = []\n        for end_index in op.input(\"EndsTensorList\"):\n            end_index = g.get_node(end_index).astype(\"int64\")\n            ends.append(end_index)\n        ends = _op.concatenate(ends, axis=0)\n        ends, infered = try_infer_value(ends, g.get_params())\n        if infered:\n            ends = ends.tolist()\n    else:\n        ends = op.attr(\"ends\")\n\n    if len(axes) < dims:\n        if isinstance(ends, _expr.Expr):\n            ends = _op.scatter(\n                _expr.const(\n                    np.array([np.iinfo(np.int32).max] * dims),\n                    dtype=infer_type(ends).checked_type.dtype,\n                ),\n                indices,\n                ends,\n                axis=0,\n            )\n        else:\n            base = [np.iinfo(np.int32).max] * dims\n            for i, axis in enumerate(axes):\n                base[axis] = ends[i]\n            ends = base\n\n    strides = None\n    if \"StridesTensor\" in op.input_names and op.input(\"StridesTensor\"):\n        strides = g.get_node(op.input(\"StridesTensor\")[0])\n        strides, infered = try_infer_value(strides, g.get_params())\n        if infered:\n            strides = strides.tolist()\n    elif \"StridesTensorList\" in op.input_names and op.input(\"StridesTensorList\"):\n        strides = []\n        for strides_index in op.input(\"StridesTensorList\"):\n            strides_index = g.get_node(strides_index).astype(\"int64\")\n            strides.append(strides_index)\n        strides = _op.concatenate(strides, axis=0)\n        strides, infered = try_infer_value(strides, g.get_params())\n        if infered:\n            strides = strides.tolist()\n    elif op.has_attr(\"strides\"):\n        strides = op.attr(\"strides\")\n\n    if len(axes) < dims:\n        if isinstance(strides, _expr.Expr):\n            strides = _op.scatter(\n                _expr.const(\n                    np.array([1] * dims),\n                    dtype=infer_type(strides).checked_type.dtype,\n                ),\n                indices,\n                strides,\n                axis=0,\n            )\n        elif strides:\n            base = [1] * dims\n            for i, axis in enumerate(axes):\n                base[axis] = strides[i]\n            strides = base\n    if not strides:\n        strides = _op.const([1] * dims, dtype=\"int64\")\n\n    out = _op.strided_slice(data, begin=starts, end=ends, strides=strides)\n    if decrease_axis:\n        out = _op.squeeze(out, axis=decrease_axis)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_softmax(g, op, block):\n    \"\"\"Operator converter for softmax.\"\"\"\n\n    axis = op.attr(\"axis\")\n    input_shape = block.var(op.input(\"X\")[0]).shape\n    if axis < 0:\n        axis = len(input_shape) + axis\n    x = g.get_node(op.input(\"X\")[0])\n    m = _op.max(x, axis, keepdims=True)\n    e = _op.exp(x - m)\n    out = e / _op.sum(e, axis, keepdims=True)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_softplus(g, op, block):\n    \"\"\"Operator converter for softplus.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    beta = op.attr(\"beta\")\n    beta = _expr.const(beta, dtype=dtype)\n    out = _op.log(_op.exp(x * beta) + _expr.const(1.0, dtype=dtype)) / beta\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_softsign(g, op, block):\n    \"\"\"Operator converter for softsign.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = infer_type(x).checked_type.dtype\n    out = x / (_op.const(1.0, dtype) + _op.abs(x))\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_split(g, op, block):\n    \"\"\"Operator converter for split.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    axis = op.input(\"AxisTensor\")\n    if axis:\n        axis = g.get_node(axis[0])\n        axis, infered = try_infer_value(axis, g.get_params())\n        if infered:\n            axis = axis.tolist()[0]\n    else:\n        axis = op.attr(\"axis\")\n\n    sections = op.input(\"SectionsTensorList\")\n    if sections:\n        tmp_section = []\n        for i in sections:\n            i = g.get_node(i)\n            i, infered = try_infer_value(i, g.get_params())\n            if infered:\n                i = i.tolist()\n            else:\n                raise ValueError(\"Dynamic Split not yet supported.\")\n            tmp_section.extend(i)\n        sections = tmp_section\n    else:\n        sections = op.attr(\"sections\")\n    if sections:\n        indices = []\n        split_index = 0\n        for i in sections[:-1]:\n            if i == -1:\n                input_shape = infer_shape(x)[axis]\n                i = input_shape - np.sum(sections) - 1\n            split_index += i\n            indices.append(split_index)\n    else:\n        indices = op.attr(\"num\")\n\n    out = _op.split(x, indices, axis)\n    for i, out_i in enumerate(out):\n        g.add_node(op.output(\"Out\")[i], out_i)\n\n\ndef convert_square(g, op, block):\n    \"\"\"Operator converter for square.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    dtype = block.var(op.output(\"Out\")[0]).dtype\n    dtype = _convert_dtype_value(dtype)\n    out = _op.power(x, _expr.const(2, dtype))\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_squeeze(g, op, block):\n    \"\"\"Operator converter for squeeze2.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    axes = op.attr(\"axes\")\n    if not axes:\n        axes = None\n    x = _op.squeeze(x, axis=axes)\n    g.add_node(op.output(\"Out\")[0], x)\n\n\ndef convert_swish(g, op, block):\n    \"\"\"Operator converter for swish.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    beta = op.attr(\"beta\")\n    assert beta == 1.0, \"Only support beta==1.0 for PaddlePaddle's swish\"\n    out = x * _op.tensor.sigmoid(x)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_transpose(g, op, block):\n    \"\"\"Operator converter for transpose.\"\"\"\n\n    perm = op.attr(\"axis\")\n    out = _op.transpose(g.get_node(op.input(\"X\")[0]), axes=perm)\n    g.add_node(op.output(\"Out\")[0], out)\n\n\ndef convert_unsqueeze(g, op, block):\n    \"\"\"Operator converter for unsqueeze.\"\"\"\n\n    x = g.get_node(op.input(\"X\")[0])\n    axes = sorted(op.attr(\"axes\"))\n    for axis in axes:\n        x = _op.expand_dims(x, axis=axis, num_newaxis=1)\n    g.add_node(op.output(\"Out\")[0], x)\n\n\n_convert_map = {\n    \"abs\": convert_unary_op,\n    \"acos\": convert_unary_op,\n    \"addmm\": convert_addmm,\n    \"arg_max\": convert_arg_max_min,\n    \"arg_min\": convert_arg_max_min,\n    \"argsort\": convert_argsort,\n    \"asin\": convert_unary_op,\n    \"assign\": convert_assign,\n    \"assign_value\": convert_assign_value,\n    \"atan\": convert_unary_op,\n    \"batch_norm\": convert_batch_norm,\n    \"bicubic_interp_v2\": convert_interpolate,\n    \"bilinear_interp_v2\": convert_interpolate,\n    \"bmm\": convert_bmm,\n    \"brelu\": convert_brelu,\n    \"cast\": convert_cast,\n    \"ceil\": convert_unary_op,\n    \"clip\": convert_clip,\n    \"concat\": convert_concat,\n    \"conv2d\": convert_conv2d,\n    \"conv2d_transpose\": convert_conv2d_transpose,\n    \"cos\": convert_unary_op,\n    \"cosh\": convert_unary_op,\n    \"cumsum\": convert_cumsum,\n    \"depthwise_conv2d\": convert_conv2d,\n    \"depthwise_conv2d_transpose\": convert_conv2d_transpose,\n    \"dot\": convert_dot,\n    \"dropout\": convert_dropout,\n    \"elementwise_add\": convert_elementwise_op,\n    \"elementwise_div\": convert_elementwise_op,\n    \"elementwise_floordiv\": convert_elementwise_op,\n    \"elementwise_max\": convert_elementwise_op,\n    \"elementwise_min\": convert_elementwise_op,\n    \"elementwise_mod\": convert_elementwise_op,\n    \"elementwise_mul\": convert_elementwise_op,\n    \"elementwise_pow\": convert_elementwise_op,\n    \"elementwise_prod\": convert_elementwise_op,\n    \"elementwise_sub\": convert_elementwise_op,\n    \"elu\": convert_elu,\n    \"equal\": convert_elementwise_op,\n    \"erf\": convert_unary_op,\n    \"exp\": convert_unary_op,\n    \"expand_v2\": convert_expand,\n    \"expand_as_v2\": convert_expand_as,\n    \"feed\": convert_feed,\n    \"fill_any_like\": convert_fill_any_like,\n    \"fill_constant\": convert_fill_constant,\n    \"fill_constant_batch_size_like\": convert_fill_constant_batch_size_like,\n    \"flatten_contiguous_range\": convert_flatten,\n    \"floor\": convert_unary_op,\n    \"floor_mod\": convert_elementwise_op,\n    \"gather\": convert_gather,\n    \"gather_nd\": convert_gather_nd,\n    \"gelu\": convert_gelu,\n    \"greater_equal\": convert_elementwise_op,\n    \"greater_than\": convert_elementwise_op,\n    \"group_norm\": convert_group_norm,\n    \"hard_shrink\": convert_hard_shrink,\n    \"hard_sigmoid\": convert_hard_sigmoid,\n    \"hard_swish\": convert_hard_swish,\n    \"instance_norm\": convert_instance_norm,\n    \"isfinite_v2\": convert_unary_op,\n    \"isinf_v2\": convert_unary_op,\n    \"isnan_v2\": convert_unary_op,\n    \"layer_norm\": convert_layer_norm,\n    \"leaky_relu\": convert_leaky_relu,\n    \"less_equal\": convert_elementwise_op,\n    \"less_than\": convert_elementwise_op,\n    \"log\": convert_unary_op,\n    \"log2\": convert_unary_op,\n    \"log10\": convert_unary_op,\n    \"log1p\": convert_log1p,\n    \"logical_and\": convert_binary_logical_op,\n    \"logical_not\": convert_logical_not,\n    \"logical_or\": convert_binary_logical_op,\n    \"logical_xor\": convert_binary_logical_op,\n    \"logsigmoid\": convert_logsigmoid,\n    \"log_softmax\": convert_logsoftmax,\n    \"logsumexp\": convert_logsumexp,\n    \"lookup_table_v2\": convert_lookup_table,\n    \"matmul\": convert_matmul,\n    \"matmul_v2\": convert_matmul,\n    \"meshgrid\": convert_meshgrid,\n    \"mul\": convert_mul,\n    \"mv\": convert_mv,\n    \"nearest_interp_v2\": convert_interpolate,\n    \"not_equal\": convert_elementwise_op,\n    \"pad1d\": convert_padding,\n    \"pad2d\": convert_padding,\n    \"pad3d\": convert_padding,\n    \"pixel_shuffle\": convert_pixel_shuffle,\n    \"pool2d\": convert_pool2d,\n    \"pow\": convert_pow,\n    \"prelu\": convert_prelu,\n    \"range\": convert_range,\n    \"relu\": convert_unary_op,\n    \"relu6\": convert_relu6,\n    \"reshape2\": convert_reshape,\n    \"round\": convert_unary_op,\n    \"reciprocal\": convert_reciprocal,\n    \"reduce_all\": convert_reduce,\n    \"reduce_any\": convert_reduce,\n    \"reduce_max\": convert_reduce,\n    \"reduce_min\": convert_reduce,\n    \"reduce_prod\": convert_reduce,\n    \"reduce_sum\": convert_reduce,\n    \"reduce_mean\": convert_reduce,\n    \"rnn\": convert_rnn,\n    \"rsqrt\": convert_unary_op,\n    \"scale\": convert_scale,\n    \"scatter\": convert_scatter,\n    \"scatter_nd_add\": convert_scatter_nd_add,\n    \"selu\": convert_selu,\n    \"shape\": convert_shape,\n    \"sigmoid\": convert_unary_op,\n    \"sign\": convert_unary_op,\n    \"sin\": convert_unary_op,\n    \"sinh\": convert_unary_op,\n    \"size\": convert_size,\n    \"slice\": convert_slice,\n    \"softmax\": convert_softmax,\n    \"softplus\": convert_softplus,\n    \"softsign\": convert_softsign,\n    \"split\": convert_split,\n    \"strided_slice\": convert_slice,\n    \"sqrt\": convert_unary_op,\n    \"square\": convert_square,\n    \"squeeze2\": convert_squeeze,\n    \"swish\": convert_swish,\n    \"tan\": convert_unary_op,\n    \"tanh\": convert_unary_op,\n    \"transpose2\": convert_transpose,\n    \"unsqueeze2\": convert_unsqueeze,\n}\n\n\nclass GraphProto:\n    \"\"\"A helper class for handling relay functions from PaddlePaddle model.\"\"\"\n\n    def __init__(self):\n        self.nodes = {}\n        self.params = {}\n        self.shape_dict = None\n\n    def get_node(self, name):\n        \"\"\"get node from graph\"\"\"\n\n        assert name in self.nodes\n        return self.nodes[name]\n\n    def add_node(self, name, node):\n        \"\"\"add a node to graph\"\"\"\n\n        self.nodes[name] = fold_constant(node)\n\n    def get_params(self, name=None):\n        \"\"\"Get params from graph.\"\"\"\n\n        if name is None:\n            return self.params\n        assert name in self.params\n        return self.params[name]\n\n    def extract_parameters(self, program, scope=None):\n        \"\"\"Extract all the weights from PaddlePaddle program.\"\"\"\n\n        self.params = {}\n        variables = program.global_block().vars\n        for name in variables:\n            var = program.global_block().var(name)\n            if name.endswith(\"feed\") or name.endswith(\"fetch\"):\n                continue\n            if not var.persistable:\n                continue\n            if isinstance(scope, dict):\n                self.params[name] = _nd.array(scope[name])\n            else:\n                self.params[name] = _nd.array(np.array(scope.var(name).get_tensor()))\n            shape = self.params[name].shape\n            dtype = self.params[name].dtype\n            self.nodes[name] = new_var(name, shape=shape, dtype=dtype)\n\n    def check_input_shape(self, op, block):\n        \"\"\"Check the shape information of model's inputs, fixed shape is recommended.\"\"\"\n\n        ipt_name = op.input(op.input_names[0])\n        ipt_shape = block.var(ipt_name).shape\n        for i in ipt_shape:\n            if i < 0:\n                warning_msg = \"Input {}(shape={}) has unkown dimension shapes. \\\n                               Specifying static values may improve performance\".format(\n                    ipt_name, ipt_shape\n                )\n                warnings.warn(warning_msg)\n\n    def check_unsupported_ops(self, program):\n        \"\"\"Check whether all the operators are supported.\"\"\"\n\n        unsupported_ops = set()\n        for block in program.blocks:\n            for op in block.ops:\n                if op.type == \"fetch\":\n                    continue\n                if op.type not in _convert_map:\n                    unsupported_ops.add(op.type)\n        if len(unsupported_ops) > 0:\n            msg = \"The following operators are not supported for frontend Paddle: \"\n            msg += \", \".join(unsupported_ops)\n            raise tvm.error.OpNotImplemented(msg)\n\n    def ops_to_relay(self, program, input_specs=None):\n        \"\"\"Convert PaddlePaddle operators to TVM relay functions.\"\"\"\n\n        if input_specs is not None:\n            for input_spec in input_specs:\n                convert_feed(self, input_spec, None)\n        for block in program.blocks:\n            for op in block.ops:\n                if op.type == \"fetch\":\n                    continue\n                convert_func = _convert_map[op.type]\n                convert_func(self, op, block)\n\n    def from_program(self, program, shape_dict, scope):\n        \"\"\"Construct the TVM relay expression from PaddlePaddle program.\"\"\"\n\n        self.shape_dict = shape_dict\n        if scope is None:\n            import paddle\n\n            scope = paddle.fluid.global_scope()\n        self.check_unsupported_ops(program)\n        self.extract_parameters(program, scope)\n        self.ops_to_relay(program)\n\n        output_names = list()\n        for block in program.blocks:\n            for op in block.ops:\n                if op.type == \"fetch\":\n                    output_names.append(op.input(\"X\")[0])\n\n        outputs = [self.nodes[name] for name in output_names]\n        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n\n        free_vars = analysis.free_vars(outputs)\n        func = _function.Function(free_vars, outputs)\n        mod = IRModule.from_expr(func)\n        return mod, self.params\n\n    def from_translated_layer(self, layer, shape_dict):\n        \"\"\"Construct the TVM relay expression from PaddlePaddle TranslatedLayer.\"\"\"\n\n        self.shape_dict = shape_dict\n        program = layer.program()\n        parameters = dict()\n        for param in layer.parameters() + layer.buffers():\n            parameters[param.name] = np.array(param.value().get_tensor())\n        self.check_unsupported_ops(program)\n        self.extract_parameters(program, parameters)\n\n        input_specs = layer._input_spec()\n        self.ops_to_relay(program, input_specs)\n\n        output_names = [x.name for x in layer._output_spec()]\n\n        outputs = [self.nodes[name] for name in output_names]\n        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n\n        free_vars = analysis.free_vars(outputs)\n        func = _function.Function(free_vars, outputs)\n        mod = IRModule.from_expr(func)\n        # remove unused parameters\n        final_params = dict()\n        for var in free_vars:\n            if var.name_hint in self.params:\n                final_params[var.name_hint] = self.params[var.name_hint]\n        self.params = final_params\n        return mod, self.params\n\n\ndef from_paddle(program_or_layer, shape_dict=None, scope=None):\n    \"\"\"Convert a PaddlePaddle model into an equivalent Relay Function.\n    PaddlePaddle Program/TranslatedLayer represent the computation graph of PaddlePaddle model,\n    and PaddlePaddle scope stores all the weights of PaddlePaddle model.\n\n    Parameters\n    ----------\n    program_or_layer : object of `paddle.static.Program` or `paddle.jit.TranslatedLayer`\n        Loaded model by `paddle.static.load_inference_model` or `paddle.jit.load`\n\n    shape_dict : dict of str to tuple/list, optional\n        The input shape of model\n\n    scope : object of `paddle.static.Scope`, optional\n        The scope that saves all the weights of model, use `paddle.static.global_scope` by default\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation\n\n    params : dict of str to tvm.nd.NDArray\n    \"\"\"\n\n    import paddle\n\n    # disable system signal capturing in paddle framework\n    # the signal capturing may cause conflict while running autotvm with paddle frontend\n    paddle.disable_signal_handler()\n\n    g = GraphProto()\n    if isinstance(program_or_layer, paddle.jit.TranslatedLayer):\n        # model is loaded by `paddle.jit.load`\n        mod, params = g.from_translated_layer(program_or_layer, shape_dict)\n    elif isinstance(program_or_layer, paddle.static.Program):\n        # model is loaded by `paddle.static.load_inference_model`\n        mod, params = g.from_program(program_or_layer, shape_dict, scope)\n    else:\n        raise Exception(\"Only PaddlePaddle's Program and TranslatedLayer are supported.\")\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/pytorch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, too-many-lines, len-as-condition, no-else-return, unused-variable, too-many-nested-blocks\n# pylint: disable=consider-iterating-dictionary, invalid-name, unused-argument, unused-variable, broad-except\n# pylint: disable=import-outside-toplevel, simplifiable-if-expression, cell-var-from-loop, unnecessary-lambda\n# pylint: disable=missing-function-docstring, redefined-builtin\n\"\"\"PT: PyTorch frontend.\"\"\"\nimport functools\nimport itertools\nimport math\nimport sys\n\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom .. import analysis as _analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .. import qnn, transform\nfrom ..expr_functor import ExprMutator\nfrom ..loops import while_loop\nfrom ..prelude import Prelude, StaticTensorArrayOps\nfrom ..ty import Any, TensorType, TupleType\nfrom . import qnn_torch\nfrom .common import AttrCvt, get_relay_op, gru_cell, logger, rnn_cell\nfrom .common import infer_shape as _infer_shape\nfrom .common import infer_value as _infer_value\nfrom .common import infer_value_simulated as _infer_value_simulated\nfrom .common import lstm_cell, try_infer_value, unbind, fold_constant\nfrom .pytorch_utils import is_version_greater_than, getattr_attr_name\n\n__all__ = [\"from_pytorch\"]\n\n# This returns a \"subgraph\" which puts variables whenever\n# the type is known. It also records things to map the input\n# nodes to the extracted graph's nodes.\n# As Python objects are not round-trippable through C++, and\n# our type annotations only live in Python, we need to map\n# the we need to map the nodes we get in visiting to the nodes\n# we used to construct the graph (they are the same in C++,\n# match each other in dictionary lookups, but are not the same\n# in Python) by using the hint dictionary filled as\n# {node: node for node in nodes} to get the type annotations.\n# https://discuss.tvm.apache.org/t/round-tripping-objects-through-the-ffi/8440\nclass _TypeFinder(ExprMutator):\n    def __init__(self, types):\n        super().__init__()\n        self.counter = 0\n        self.vars = {}\n        self.types = types\n        self.leave = set()  # some variables are not inputs\n\n    def visit_let(self, let):\n        self.leave.add(let.var)\n        return super().visit_let(let)\n\n    def visit_function(self, fn):\n        self.leave.update(fn.params)\n        return super().visit_function(fn)\n\n    def visit(self, expr):\n        if expr in self.leave:\n            return super().visit(expr)\n        if expr in self.vars:\n            return self.vars[expr]\n        if isinstance(expr, tvm.relay.Var):\n            self.vars[expr] = expr\n            return expr\n        if expr in self.types:\n            ty = self.types[expr]\n            v = tvm.relay.var(f\"_{self.counter}\", type_annotation=ty)\n            self.counter += 1\n            self.vars[expr] = v\n            return v\n        v = super().visit(expr)\n        return v\n\n\ndef _should_construct_dynamic_list(list_construct_node):\n    # if this list is element-accessed or modified at runtime, generate List ADT\n    def inplace_add_to_add(op_name):\n        if op_name == \"aten::add_\":\n            return \"aten::add\"\n        else:\n            return op_name\n\n    uses = _get_uses(list_construct_node)\n\n    for loop_use in filter(lambda use: use.user.kind() == \"prim::Loop\", uses):\n        block_input_index = loop_use.offset - 1\n        block = list(loop_use.user.blocks())[0]\n        list_loop_var = list(block.inputs())[block_input_index]\n        uses += _get_uses(list_loop_var.node())\n\n    op_names = map(inplace_add_to_add, set(use.user.kind() for use in uses))\n\n    list_ops = set([\"aten::add\", \"aten::__getitem__\"])\n    intersect = list_ops.intersection(op_names)\n\n    if len(intersect) > 0 and intersect != set([\"aten::add\"]):\n        return True\n\n    # if add op outputs list, it is dynamic so we need to construct List ADT\n    for use in filter(lambda use: use.user.kind() in [\"aten::add\", \"aten::add_\"], uses):\n        output_type = _get_node_type(use.user)\n        if output_type == \"ListType\":\n            return True\n\n    return False\n\n\ndef _is_int_seq(seq):\n    # TODO (t-vi): handle non-int constants? (like numpy.intXX)\n    return len(seq) > 0 and all([isinstance(i, int) for i in seq])\n\n\n# operator implementation\nclass PyTorchOpConverter:\n    \"\"\"A helper class for holding PyTorch op converters.\"\"\"\n\n    def __init__(self, prelude, default_dtype):\n        self.prelude = prelude\n        self.default_dtype = default_dtype\n        self.create_convert_map()\n        self.types = {}  # map from nodes to (Relay) type annotations\n\n    # this incrementally infers the type, see the comments on the type visitor\n    # above.\n    def infer_type(self, node, mod=None):\n        \"\"\"An incremental method to infer the type of a node in the relay graph.\"\"\"\n\n        if node in self.types:\n            return self.types[node]\n        if isinstance(node, tvm.relay.Var):\n            return node.type_annotation\n\n        tf = _TypeFinder(types=self.types)\n        new_node = tf.visit(node)\n        fn = _function.Function(list(tf.vars.values()), new_node)\n        new_mod = IRModule({\"main\": fn})\n        if mod is not None:\n            new_mod.update(mod)\n        new_mod = transform.RemoveUnusedFunctions()(new_mod)\n        new_mod = transform.InferType()(new_mod)\n        entry = new_mod[\"main\"]\n        ty = entry.body.checked_type\n        self.types[node] = ty\n        return self.types[node]\n\n    def infer_type_with_prelude(self, val):\n        body = self.infer_type(val, self.prelude.mod)\n        return body\n\n    # list ADT utilities\n    def convert_to_list_adt(self, py_lst):\n        elem_tys = [self.infer_type_with_prelude(elem) for elem in py_lst]\n        msg = \"List elements should have identical types\"\n        assert all(map(lambda ty: ty == elem_tys[0], elem_tys)), msg\n\n        # get_type returns type_name, ctor1, ..., ctorN\n        # 1 is nil\n        _, cons, nil = self.prelude.mod.get_type(\"List\")\n        adt_lst = nil()\n        for elem in reversed(py_lst):\n            adt_lst = cons(elem, adt_lst)\n        return adt_lst\n\n    def map_tensor_array_constructor(self, adt_lst, shape):\n        static_tensor_array_ops = StaticTensorArrayOps(self.prelude, \"float32\", shape)\n        static_tensor_array_ops.register()\n        tensor_create = self.prelude.get_tensor_ctor_static(\"tensor_constructor\", \"float32\", shape)\n        return self.prelude.map(tensor_create, adt_lst)\n\n    def convert_to_tensor_array(self, adt_lst):\n        _, cons, nil = self.prelude.mod.get_type(\"List\")\n        if self.prelude.length(adt_lst) == 0:\n            return nil()\n\n        checked_type = self.infer_type_with_prelude(self.prelude.hd(adt_lst))\n        shape = checked_type.shape\n        tensor_array = self.map_tensor_array_constructor(adt_lst, shape)\n        return tensor_array, tuple(shape)\n\n    def infer_shape(self, inputs, mod=None):\n        \"\"\"A method to get the output type of an intermediate node in the graph.\"\"\"\n        typ = self.infer_type(inputs, mod=mod)\n        if hasattr(typ, \"shape\"):\n            # Regular operator that outputs tensors\n            return get_const_tuple(typ.shape)\n        # The return type is not a tensor, for example List\n        return typ\n\n    def infer_shape_with_prelude(self, inputs):\n        return self.infer_shape(inputs, mod=self.prelude.mod)\n\n    def record_output_type(self, output):\n        if isinstance(output, tuple):\n            cleaned_output = [o for o in output if o is not None]\n            types = self.infer_type_with_prelude(_expr.Tuple(cleaned_output))\n            for o, t in zip(cleaned_output, types.fields):\n                self.types[o] = t\n        elif isinstance(output, _expr.Expr):\n            self.infer_type_with_prelude(output)\n        # it can also happen that the type is int or so\n\n    def pytorch_promote_types(self, inputs, dtypes):\n        \"\"\"This promotes TVM inputs with TVM dtypes passed like PyTorch would\"\"\"\n        actual_dtypes = []\n        for i, inp in enumerate(inputs):\n            if isinstance(inp, _expr.Expr):\n                idt = self.infer_type(inp).dtype\n                actual_dtypes.append(idt)\n            else:\n                actual_dtypes.append(dtypes[i])\n        dtypes = actual_dtypes\n        tensor_dtypes = [dt for inp, dt in zip(inputs, dtypes) if not np.isscalar(inp)]\n        non_tensor_inputs = [inp for inp in inputs if np.isscalar(inp)]\n        result_type = _pytorch_result_type(tensor_dtypes, non_tensor_inputs)\n        results = []\n        for inp, dt in zip(inputs, dtypes):\n            if np.isscalar(inp):\n                results.append(_expr.const(inp, dtype=result_type))\n            elif dt == result_type:\n                results.append(inp)\n            else:\n                results.append(_op.cast(inp, result_type))\n        return results\n\n    def is_quantized_tensor(self, data):\n        # If a quantized Torch module is saved and loaded back, dtype will be dropped\n        # Since dtypes from Torch tensors are not reliable in such cases, we use\n        # Relay's type inference result to decide if an input tensor is quantized\n        ty = self.infer_type_with_prelude(data)\n        return ty.dtype == \"uint8\"\n\n    # Operator implementations\n    def make_elemwise(self, name):\n        def elemwise(inputs, input_types):\n            if name == \"divide\":\n                # https://pytorch.org/docs/stable/generated/torch.div.html#torch.div\n                # None - default behavior. Performs no rounding and, if both input and\n                # other are integer types, promotes the inputs to the default scalar type.\n                if all([\"int\" in input_type for input_type in input_types[:2]]):\n                    input_types[:2] = [\"float32\"] * 2\n                    cast_inputs = []\n                    for inp in inputs[:2]:\n                        if np.isscalar(inp):\n                            cast_inputs.append(_expr.const(inp, dtype=\"float32\"))\n                        else:\n                            cast_inputs.append(_op.cast(inp, \"float32\"))\n                    inputs[:2] = cast_inputs\n\n            data0, data1 = self.pytorch_promote_types(inputs[:2], input_types[:2])\n            return get_relay_op(name)(data0, data1)\n\n        return elemwise\n\n    def min_max_common(self, name_elemwise, name_reduce, inputs, input_types):\n        if len(inputs) == 1:\n            data = self.pytorch_promote_types(inputs[:1], input_types[:1])\n            return get_relay_op(name_reduce)(data[0])\n        elif len(inputs) >= 2 and isinstance(inputs[1], (list, int)):\n            data = self.pytorch_promote_types(inputs[:1], input_types[:1])\n            dim = inputs[1]\n            keepdims = inputs[2] if len(inputs) > 2 else False\n            # also return dummy indices\n            return get_relay_op(name_reduce)(data[0], axis=dim, keepdims=keepdims), None\n        else:\n            data0, data1 = self.pytorch_promote_types(inputs[:2], input_types[:2])\n            return get_relay_op(name_elemwise)(data0, data1)\n\n    def max(self, inputs, input_types):\n        return self.min_max_common(\"maximum\", \"max\", inputs, input_types)\n\n    def min(self, inputs, input_types):\n        return self.min_max_common(\"minimum\", \"min\", inputs, input_types)\n\n    def maximum(self, inputs, input_types):\n        data0, data1 = self.pytorch_promote_types(inputs[:2], input_types[:2])\n        return _op.maximum(data0, data1)\n\n    def minimum(self, inputs, input_types):\n        data0, data1 = self.pytorch_promote_types(inputs[:2], input_types[:2])\n        return _op.minimum(data0, data1)\n\n    def make_unary(self, name):\n        def unary(inputs, input_types):\n            # this is just to ensure tensor input\n            (data,) = self.pytorch_promote_types(inputs[:1], input_types[:1])\n            return get_relay_op(name)(data)\n\n        return unary\n\n    def log1p(self, inputs, input_types):\n        # 1_plus_log x = log(x + 1)\n        (dtype,) = input_types\n        one = _expr.const(1, dtype=dtype)\n        return _op.log(inputs[0] + one)\n\n    def square(self, inputs, input_types):\n        (dtype,) = input_types\n        return _op.power(inputs[0], _expr.const(2, dtype))\n\n    def lerp(self, inputs, input_types):\n        if len(inputs) != 3:\n            msg = \"Wrong number of arguments (%d) to parse.\" % (len(inputs))\n            raise AssertionError(msg)\n\n        start = inputs[0]\n        end = inputs[1]\n        weight = inputs[2]\n        return start + weight * (end - start)\n\n    def arange(self, inputs, input_types):\n        def _get_value(val, dtype):\n            # dtype is a tvm dtype\n            if isinstance(val, _expr.Expr):\n                inp = _op.cast(val, dtype)\n                ret, _ = try_infer_value(inp, lambda ret: _expr.const(ret, dtype))\n            else:\n                ret = _create_typed_const(val, dtype)\n            return ret\n\n        def _get_type(val, inp_type):\n            if isinstance(val, _expr.Expr):\n                dtype = str(self.infer_type(val))\n                return dtype\n            return inp_type\n\n        # PyTorch arange uses the following type semantics:\n        # - if a dtype is given, start, stop, step are converted to that dtype\n        # - if no dtype is given and all args are integral, dtype is int64\n        # - if no dtype is given and there is a float arg, dtype is float32\n        if len(inputs) in {5, 6, 7}:\n            # inputs look like [_,_,_,dtype,layout,device,requires_grad]\n            # therefore dtype_idx is always the length of inputs minus 4\n            dtype_idx = len(inputs) - 4\n            types = [_get_type(inputs[i], input_types[i]) for i in range(dtype_idx)]\n            if inputs[dtype_idx] is not None:\n                dtype = _convert_dtype_value(inputs[dtype_idx])\n            elif any([t.startswith(\"float\") for t in types]):\n                dtype = \"float32\"\n            else:\n                dtype = \"int64\"\n\n            # - if len(inputs) == 5, inputs = [stop, dtype, ...]\n            # - if len(inputs) == 6, inputs = [start, stop, dtype, ...]\n            # - if len(inputs) == 7, inputs = [start, stop, step, dtype, ...]\n            start = _get_value(inputs[0], dtype) if len(inputs) > 5 else _expr.const(0, dtype)\n            stop = _get_value(inputs[1 if len(inputs) > 5 else 0], dtype)\n            step = _get_value(inputs[2], dtype) if len(inputs) > 6 else _expr.const(1, dtype)\n        else:\n            msg = \"Unknown number of arguments (%d) to parse.\" % (len(inputs))\n            raise AssertionError(msg)\n\n        return _op.transform.arange(start=start, stop=stop, step=step, dtype=dtype)\n\n    def squeeze(self, inputs, input_types):\n        data = inputs[0]\n        if len(inputs) == 1:\n            axis = None\n        else:\n            # TODO (t-vi): why is the cast to int needed? similarly elsewhere\n            axis = [int(inputs[1])]\n\n        return _op.transform.squeeze(data, axis)\n\n    def unsqueeze(self, inputs, input_types):\n        data = inputs[0]\n        axis = inputs[1]\n\n        return _op.transform.expand_dims(data, int(axis), 1)\n\n    def concatenate(self, inputs, input_types):\n        def tensor_array_concat(lst, axis):\n            assert axis == 0, \"Tensor array concat supported only for axis 0\"\n            tensor_array, shape = self.convert_to_tensor_array(lst)\n            concat_shape = (Any(),) + shape[1:]\n            concat = self.prelude.get_global_var_static(\"tensor_array_concat\", \"float32\", shape)\n            concatenated = concat(tensor_array)\n\n            static_tensor_array_ops = StaticTensorArrayOps(self.prelude, \"float32\", concat_shape)\n            static_tensor_array_ops.register()\n            get_tensor = self.prelude.get_global_var_static(\n                \"tensor_get_data\", \"float32\", concat_shape\n            )\n            return get_tensor(concatenated)\n\n        data = inputs[0]\n        axis = inputs[1]\n\n        if not isinstance(data, list):\n            return tensor_array_concat(data, axis)\n\n        if isinstance(data, _expr.Expr):\n            data = [data]\n\n        return _op.tensor.concatenate(data, int(axis))\n\n    def slice(self, inputs, input_types):\n        axis_dtype = \"int64\"\n        index_size_limit = sys.maxsize\n        data = inputs[0]\n        dshape = self.infer_shape(data)\n        ndim = len(dshape)\n        dim = int(inputs[1])\n        stride = inputs[4]\n\n        target_begin, is_begin_const = try_infer_value(\n            inputs[2], lambda ret: ret.astype(np.int).item(0)\n        )\n        target_end, is_end_const = try_infer_value(\n            inputs[3], lambda ret: ret.astype(np.int).item(0)\n        )\n\n        # A fast path when slicing is nop.\n        if (\n            isinstance(target_begin, int)\n            and isinstance(target_end, int)\n            and target_begin == 0\n            and target_end >= index_size_limit\n            and stride == 1\n        ):\n            return data\n\n        if target_begin is None and target_end is None:\n            return data\n\n        # Process begin\n        begin = [0] * ndim\n\n        if target_begin is not None:\n            begin[dim] = target_begin\n\n        if target_begin is not None and not isinstance(begin[dim], int):\n            tmp = []\n            for b in begin:\n                if isinstance(b, int):\n                    tmp.append(_op.expand_dims(_expr.const(b, axis_dtype), axis=0))\n                else:\n                    tmp.append(_op.cast(_op.expand_dims(b, axis=0), axis_dtype))\n            begin = _op.concatenate(tmp, axis=0)\n            btype = self.infer_type(begin).dtype\n            if str(btype) != axis_dtype:\n                begin = _op.cast(begin, axis_dtype)\n\n        # Process end\n        if isinstance(target_end, int) and target_end >= index_size_limit:\n            target_end = dshape[dim]\n\n        if any([isinstance(d, tvm.tir.Any) for d in dshape]):\n            end = _op.shape_of(data)\n        else:\n            end = dshape\n\n        if isinstance(target_end, int):\n            if isinstance(end, list):\n                end[dim] = target_end\n            else:\n                all_static = True\n                for i, shape_dim in enumerate(dshape):\n                    if i != dim and isinstance(shape_dim, tvm.tir.Any):\n                        all_static = False\n\n                if all_static:\n                    end = list(get_const_tuple(dshape))\n                    end[dim] = target_end\n                else:\n                    target_end = _expr.const(target_end)\n                    end = _op.scatter(\n                        end,\n                        _op.expand_dims(_expr.const(dim), axis=0),\n                        _op.expand_dims(target_end, axis=0),\n                        axis=0,\n                    )\n        else:\n            end = _op.cast(_op.shape_of(data), axis_dtype)\n            if target_end is not None and not isinstance(target_end, tvm.tir.Any):\n                ttype = self.infer_type(target_end).dtype\n                if str(ttype) != axis_dtype:\n                    target_end = _op.cast(target_end, axis_dtype)\n                end = _op.scatter(\n                    end,\n                    _op.expand_dims(_expr.const(dim), axis=0),\n                    _op.expand_dims(target_end, axis=0),\n                    axis=0,\n                )\n\n        if not isinstance(end, list):\n            etype = self.infer_type(end).dtype\n            if str(etype) != axis_dtype:\n                end = _op.cast(end, axis_dtype)\n\n        strides = [1] * ndim\n        strides[dim] = stride\n\n        return _op.transform.strided_slice(\n            data, begin=begin, end=end, strides=strides, slice_mode=\"end\"\n        )\n\n    def narrow(self, inputs, input_types):\n        # Inputs are:\n        # 0 - the tensor to narrow\n        # 1 - the dimension along which to narrow\n        # 2 - the starting dimension\n        # 3 - the distance to the ending dimension\n        # Lets find the ending dimension\n        end = self.add(inputs[2:4], input_types[2:4])\n        stride = 1\n        slice_input = inputs[:3] + [end, stride]\n        slice_types = input_types + [\"int32\"]\n        return self.slice(slice_input, slice_types)\n\n    def split(self, inputs, input_types):\n        data = inputs[0]\n        split_size = int(inputs[1])\n        dim = int(inputs[2])\n\n        split_index = split_size\n        indices = []\n        while split_index < self.infer_shape(data)[dim]:\n            indices.append(split_index)\n            split_index += split_size\n\n        return _op.split(data, indices, dim)\n\n    def split_with_sizes(self, inputs, input_types):\n        data = inputs[0]\n        sections = inputs[1]\n        dim = int(inputs[2])\n\n        if len(sections) == 1:\n            # a special case used in torchvision detection models\n            return _expr.TupleWrapper(_expr.Tuple([data]), 1)\n\n        split_index = 0\n        indices = []\n        for i in range(len(sections) - 1):\n            index, _ = try_infer_value(sections[i], lambda ret: int(ret))\n            split_index += index\n            indices.append(split_index)\n\n        return _op.split(data, indices, dim)\n\n    def tensor_split(self, inputs, input_types):\n        # Reference: https://pytorch.org/docs/stable/generated/torch.tensor_split.html\n        import torch\n\n        if not isinstance(inputs[1], (int, list, tuple, torch.Tensor)):\n            msg = \"indices_or_sections type %s could not be parsed in tensor_split op\" % (\n                type(inputs[1])\n            )\n            raise AssertionError(msg)\n\n        if isinstance(inputs[1], torch.Tensor) and not (\n            list(inputs[1].shape) == [] or list(inputs[1].shape) == 1\n        ):\n            msg = \"indices_or_sections must be a zero-dimensional or one-dimensional long tensor\"\n            raise AssertionError(msg)\n\n        if isinstance(inputs[1], int) or (\n            isinstance(inputs[1], torch.Tensor) and list(inputs[1].shape) == []\n        ):\n            data = inputs[0]\n            n = int(inputs[1])\n            dim = int(inputs[2])\n\n            split_size = int(self.infer_shape(data)[dim] / n)\n            split_rest = int(self.infer_shape(data)[dim] % n)\n\n            indices = []\n            split_index = split_size\n            if split_rest == 0:\n                for i in range(n - 1):\n                    indices.append(split_index)\n                    split_index += split_size\n            else:\n                for i in range(split_rest):\n                    indices.append(split_index + 1)\n                    split_index = (i + 1) * (split_index + 1)\n                for i in range(n - split_rest - 1):\n                    split_index += split_size\n                    indices.append(split_index)\n\n            return _op.split(data, indices, dim)\n        else:\n            data = inputs[0]\n            sections = inputs[1]\n            dim = int(inputs[2])\n\n            if isinstance(sections, tuple):\n                sections = list(sections)\n            elif isinstance(sections, torch.Tensor):\n                sections = sections.cpu().numpy().tolist()\n\n            return _op.split(data, sections, dim)\n\n    def select(self, inputs, input_types):\n        data = inputs[0]\n        dim = int(inputs[1])\n        index = _wrap_const(inputs[2])\n        return _op.transform.take(data, index, axis=dim, mode=\"wrap\")\n\n    def take(self, inputs, input_types):\n        data = inputs[0]\n        indices = _op.cast(inputs[1], \"int32\")\n\n        return _op.transform.take(data, indices=indices, mode=\"wrap\")\n\n    def topk(self, inputs, input_types):\n        data = inputs[0]\n        axis = int(inputs[2])\n        is_ascend = not bool(inputs[3])\n        sort = bool(inputs[4])\n\n        if isinstance(inputs[1], _expr.Expr):\n            k, _ = try_infer_value(inputs[1], lambda ret: ret.tolist())\n        else:\n            k = inputs[1]\n\n        if not sort:\n            msg = \"Currently supports only sorted output for topk operator.\"\n            raise AssertionError(msg)\n\n        outs = _op.topk(data, k=k, axis=axis, is_ascend=is_ascend, ret_type=\"both\", dtype=\"int64\")\n\n        return outs[0], outs[1]\n\n    def reciprocal(self, inputs, input_types):\n        data = inputs[0]\n        return _expr.const(1.0, dtype=input_types[0]) / data\n\n    def repeat(self, inputs, input_types):\n        data = inputs[0]\n        reps = []\n        for r in inputs[1]:\n            if isinstance(r, int):\n                reps.append(r)\n            else:\n                reps.append(int(_infer_value(r, {}).numpy()))\n\n        return _op.transform.tile(data, reps=reps)\n\n    def repeat_interleave(self, inputs, input_types):\n        data = inputs[0]\n        if isinstance(inputs[1], int):\n            repeats = inputs[1]\n            axis = inputs[2]\n        elif isinstance(inputs[1], _expr.Expr):\n            if isinstance(inputs[1], _expr.Constant):\n                repeats = int(inputs[1].data.numpy())\n            else:\n                repeats, _ = try_infer_value(inputs[1], lambda ret: ret.tolist())\n            axis = inputs[2]\n        else:\n            msg = \"Only repeat with one value as repeat is currently supported.\"\n            raise AssertionError(msg)\n        if axis is None:  # Flatten the data if no axis is given from torch\n            data = _op.transform.reshape(data, [-1])\n            axis = 0\n        return _op.transform.repeat(data, repeats=repeats, axis=axis)\n\n    def addcdiv(self, inputs, input_types):\n        data, t1, t2, c = self.pytorch_promote_types(inputs[:4], input_types[:4])\n        return data + (c * (t1 / t2))\n\n    def addcmul(self, inputs, input_types):\n        data, t1, t2, c = self.pytorch_promote_types(inputs[:4], input_types[:4])\n        return data + (c * (t1 * t2))\n\n    def where(self, inputs, input_types):\n        if len(inputs) == 1:\n            return self.nonzero([inputs[0], True], input_types)\n\n        cond = inputs[0]\n        x, y = self.pytorch_promote_types(inputs[1:3], input_types[1:3])\n        return _op.where(cond, x, y)\n\n    def full_impl(self, data, fill_value, dtype):\n        size = []\n        need_reshape = False\n        new_shape = []\n        for dim in data:\n            if isinstance(dim, _expr.Expr):\n                if isinstance(dim, _expr.Constant):\n                    dim = int(dim.data.numpy())\n                    if isinstance(size, list):\n                        size.append(dim)\n                    new_shape.append(dim)\n                else:\n                    dim, success = try_infer_value(dim, lambda ret: int(ret), lambda: 0)\n                    new_shape.append(dim)\n\n                    if success:\n                        if isinstance(size, list):\n                            size.append(dim)\n                    else:\n                        size = None\n                        need_reshape = True\n            else:\n                if isinstance(size, list):\n                    size.append(dim)\n                new_shape.append(dim)\n\n        if size is None:\n            tmp = []\n            for dim in data:\n                tmp.append(_op.cast(_op.expand_dims(dim, axis=0), \"int64\"))\n            size = _op.concatenate(tmp, axis=0)\n\n        if not isinstance(fill_value, _expr.Constant):\n            fill_value = _expr.const(fill_value, dtype=dtype)\n        out = _op.full(fill_value, size, dtype=dtype)\n        if need_reshape:\n            out = _op.reshape(out, new_shape)\n        return out\n\n    def ones(self, inputs, input_types):\n        data = inputs[0]\n\n        import torch\n\n        if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)):\n            msg = \"Data type %s could not be parsed in ones op\" % (type(data))\n            raise AssertionError(msg)\n\n        if inputs[1] is not None:\n            dtype = _convert_dtype_value(inputs[1])\n        else:\n            dtype = self.default_dtype\n        return self.full_impl(data, 1, dtype)\n\n    def ones_like(self, inputs, input_types):\n        data = inputs[0]\n        out = _op.ones_like(data)\n\n        # If the input and the output datatype is different, do a cast\n        if inputs[1] is not None:\n            dtype = _convert_dtype_value(inputs[1])\n        else:\n            dtype = self.default_dtype\n        if input_types[0] != dtype:\n            out = _op.cast(out, dtype)\n\n        return out\n\n    def new_ones(self, inputs, input_types):\n        size = inputs[1]\n\n        import torch\n\n        if not isinstance(size, (_expr.Expr, list, tuple, torch.Size, np.ndarray)):\n            msg = \"Data type %s could not be parsed in ones op\" % (type(size))\n            raise AssertionError(msg)\n\n        if inputs[2] is not None:\n            dtype = _convert_dtype_value(inputs[2])\n        else:\n            dtype = input_types[0]\n        return self.full_impl(size, 1, dtype)\n\n    def zeros(self, inputs, input_types):\n        data = inputs[0]\n\n        import torch\n\n        if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)):\n            msg = \"Data type %s could not be parsed in zeros op\" % (type(data))\n            raise AssertionError(msg)\n\n        if inputs[1] is not None:\n            dtype = _convert_dtype_value(inputs[1])\n        else:\n            dtype = self.default_dtype\n        return self.full_impl(data, 0, dtype)\n\n    def zero_(self, inputs, input_types):\n        data = inputs[0]\n        return self.full_impl(self.infer_shape(data), 0, input_types[0])\n\n    def zeros_like(self, inputs, input_types):\n        data = inputs[0]\n        out = _op.zeros_like(data)\n\n        # If the input and the output datatype is different, do a cast\n        if inputs[1] is not None:\n            dtype = _convert_dtype_value(inputs[1])\n        else:\n            dtype = self.default_dtype\n        if input_types[0] not in dtype:\n            out = _op.cast(out, dtype)\n\n        return out\n\n    def full(self, inputs, input_types):\n        data = inputs[0]\n        fill_value = inputs[1]\n\n        import torch\n\n        if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)):\n            msg = \"Data type %s could not be parsed in full op\" % (type(data))\n            raise AssertionError(msg)\n\n        if inputs[2] is not None:  # dtype given\n            dtype = _convert_dtype_value(inputs[2])\n        else:\n            # if dtype is None, torch uses a global default set by torch.set_default_tensor_type()\n            dtype = self.default_dtype\n\n        return self.full_impl(data, fill_value, dtype)\n\n    def full_like(self, inputs, input_types):\n        data = inputs[0]\n        fill_value = inputs[1]\n\n        out = _op.full_like(data, _expr.const(fill_value))\n\n        # If the input and the output datatype is different, do a cast\n        if inputs[2] is not None:  # dtype given\n            dtype = _convert_dtype_value(inputs[2])\n        else:\n            # if dtype is None, torch uses a global default set by torch.set_default_tensor_type()\n            dtype = self.default_dtype\n        if input_types[0] not in dtype:\n            out = _op.cast(out, dtype)\n\n        return out\n\n    def new_full(self, inputs, input_types):\n        data = inputs[1]\n        fill_value = inputs[2]\n        import torch\n\n        if not isinstance(data, (_expr.Expr, list, tuple, torch.Size)):\n            msg = \"Data type %s could not be parsed in full op\" % (type(data))\n            raise AssertionError(msg)\n\n        if inputs[3] is not None:  # dtype given\n            dtype = _convert_dtype_value(inputs[3])\n        else:\n            # if dtype is None, use the dtype of the input tensor\n            dtype = self.infer_type(input[0])\n\n        return self.full_impl(data, fill_value, dtype)\n\n    def fill_(self, inputs, input_types):\n        data = inputs[0]\n        fill_value = inputs[1]\n        if not isinstance(fill_value, (bool, int, float, complex)):\n            fill_value = fold_constant(fill_value)\n        return self.full_impl(self.infer_shape(data), fill_value, input_types[0])\n\n    def linspace(self, inputs, input_types):\n        start = inputs[0]\n        stop = inputs[1]\n        step = inputs[2]\n\n        # Find the spacing between values as step\n        if step != 1:\n            step = (stop - start) / (step - 1)\n            stop = stop + step\n        else:\n            stop = start + step\n\n        if inputs[3] is None:\n            import torch\n\n            dtype = _convert_data_type(str(torch.get_default_dtype()))\n        else:\n            dtype = _convert_dtype_value(inputs[3])\n\n        start = _create_typed_const(start, dtype)\n        stop = _create_typed_const(stop, dtype)\n        step = _create_typed_const(step, dtype)\n\n        return _op.transform.arange(start=start, stop=stop, step=step, dtype=dtype)\n\n    def relu(self, inputs, input_types):\n        data = inputs[0]\n        if self.is_quantized_tensor(data):\n            assert len(inputs) == 3, \"Input quant param not found in op inputs\"\n            input_zero_point = _expr.const(inputs[2], dtype=\"int32\")\n            return qnn_torch.quantized_relu(data, input_zero_point)\n        return _op.nn.relu(data)\n\n    def relu6(self, inputs, input_types):\n        data = inputs[0]\n        return _op.tensor.clip(data, 0.0, 6.0)\n\n    def prelu(self, inputs, input_types):\n        # Reference: https://pytorch.org/docs/stable/generated/torch.nn.PReLU.html#torch.nn.PReLU\n        data = inputs[0]\n        dim = self.get_dims(data)\n        ndims = len(dim)\n        axis = 0 if ndims == 1 else 1\n        alpha = _op.broadcast_to(inputs[1], (dim[axis]))\n        return _op.nn.prelu(data, alpha, axis)\n\n    def leaky_relu(self, inputs, input_types):\n        data = inputs[0]\n        alpha = float(inputs[1])\n        return _op.nn.leaky_relu(data, alpha)\n\n    def elu(self, inputs, input_types):\n        data = inputs[0]\n        dtype = input_types[0]\n        alpha = _expr.const(-float(inputs[1]), dtype=dtype)\n        return alpha * _op.nn.relu(_expr.const(1, dtype=dtype) - _op.exp(data)) + _op.nn.relu(data)\n\n    def celu(self, inputs, input_types):\n        data = inputs[0]\n        dtype = input_types[0]\n        alpha = _expr.const(float(inputs[1]), dtype=dtype)\n        return alpha * _op.nn.relu(\n            _expr.const(1, dtype=dtype) - _op.exp(data / alpha)\n        ) + _op.nn.relu(data)\n\n    def gelu(self, inputs, input_types):\n        data = inputs[0]\n        dtype = input_types[0]\n        # gelu is data  * normcdf(data)\n        # normcdf expressed as erf because we don't currently have that intrinsic\n        # note that there is also a fastgelu variant approximating normcdf\n        # with tanh and third order polynomials, but this is \"true\" gelu\n        return data * (\n            _expr.const(0.5, dtype=dtype)\n            + _op.erf(data * _expr.const(0.5**0.5, dtype=dtype)) * _expr.const(0.5, dtype=dtype)\n        )\n\n    def selu(self, inputs, input_types):\n        data = inputs[0]\n        # https://pytorch.org/docs/stable/nn.html#selu\n        dtype = input_types[0]\n        alpha = _expr.const(-1.6732632423543772848170429916717, dtype=dtype)\n        gamma = _expr.const(1.0507009873554804934193349852946, dtype=dtype)\n        return gamma * (\n            alpha * _op.nn.relu(_expr.const(1.0, dtype=dtype) - _op.exp(data)) + _op.nn.relu(data)\n        )\n\n    def silu(self, inputs, input_types):\n        data = inputs[0]\n        return data * _op.tensor.sigmoid(data)\n\n    def glu(self, inputs, input_types):\n        \"\"\"\n        Applies the gated linear unit function GLU(a,b)= a * sigmoid(b)\n        where a is the first half of the input matrices and b is the second half.\n        Link: https://pytorch.org/docs/stable/generated/torch.nn.GLU.html\n        \"\"\"\n        data = inputs[0]\n        dim = inputs[1]\n        relay_tup = _op.transform.split(data, 2, dim)\n        return relay_tup[0] * _op.tensor.sigmoid(relay_tup[1])\n\n    def log_sigmoid(self, inputs, input_types):\n        data = inputs[0]\n        mn = _op.minimum(_op.const(0, dtype=input_types[0]), data)\n        z = _op.exp(-_op.abs(data))\n        return mn - self.log1p([z], input_types)\n\n    def cross_entropy_loss_with_logits(self, inputs, input_types):\n        input = inputs[0]\n        target = inputs[1]\n        weights = inputs[2]\n        reduction = inputs[3]\n        ignore_index = inputs[4]\n        label_smoothing = inputs[5]\n        input_shape = self.infer_shape(input)\n        target_shape = self.infer_shape(target)\n        if input_shape != target_shape:\n            if reduction == 0:\n                reduction = \"none\"\n            elif reduction == 1:\n                reduction = \"mean\"\n            else:\n                reduction = \"sum\"\n            num_class = self.infer_shape(input)[1]\n            if weights is None:\n                weights = _op.full(_expr.const(1), (num_class,), dtype=input_types[0])\n            return _op.nn.nll_loss(\n                _op.nn.log_softmax(input), target, weights, reduction, ignore_index\n            )\n        assert reduction == 1, \"reduction not supported in cross_entropy_loss\"\n        assert ignore_index == -100, \"ignore_index not supported in cross_entropy_loss\"\n        assert label_smoothing == 0.0, \"label_smoothing not supported in cross_entropy_loss\"\n        assert weights is None, \"weight not supported in cross_entropy_loss\"\n        return _op.nn.cross_entropy_with_logits(_op.nn.log_softmax(input), target)\n\n    def l1_loss(self, inputs, input_types):\n        assert len(inputs) == 3\n        [predictions, targets, reduction] = inputs\n        delta = _op.abs(_op.subtract(predictions, targets))\n        if reduction == 0:\n            # reduction = \"none\"\n            return delta\n        elif reduction == 1:\n            # reduction = \"mean\"\n            return _op.mean(delta)\n        else:\n            # reduction = \"sum\"\n            return _op.sum(delta)\n\n    def mse_loss(self, inputs, input_types):\n        assert len(inputs) == 3\n        [predictions, targets, reduction] = inputs\n        delta = _op.subtract(predictions, targets)\n        delta = _op.power(delta, _expr.const(2, input_types[0]))\n        if reduction == 0:\n            # reduction = \"none\"\n            return delta\n        elif reduction == 1:\n            # reduction = \"mean\"\n            return _op.mean(delta)\n        else:\n            # reduction = \"sum\"\n            return _op.sum(delta)\n\n    def hard_sigmoid(self, inputs, input_types):\n        def _relu6(x):\n            return _op.tensor.clip(x, 0.0, 6.0)\n\n        def func(x):\n            return _relu6(x + _expr.const(3.0)) / _expr.const(6.0)\n\n        if self.is_quantized_tensor(inputs[0]):\n            input_scale = _expr.const(inputs[1])\n            input_zero_point = _expr.const(inputs[2])\n            # PyTorch seems to use the following output qparams, but accuracy\n            # is broken if we use this.\n            # TODO(masahi): Revisit this parameter choice\n            #\n            # Taken from src/ATen/native/quantized/cpu/kernels/QuantizedOpKernels.cpp\n            # output_scale = _expr.const(0.00390625)  # 1.0 / 2^8\n            # output_zero_point = _expr.const(-128)\n            output_scale = input_scale\n            output_zero_point = input_zero_point\n\n            data = qnn.op.dequantize(inputs[0], input_scale, input_zero_point, axis=1)\n            out = func(data)\n            return qnn.op.quantize(out, output_scale, output_zero_point, out_dtype=\"uint8\")\n\n        return func(inputs[0])\n\n    def hard_swish(self, inputs, input_types):\n        data = inputs[0]\n        return data * self.hard_sigmoid(inputs, input_types)\n\n    def adaptive_avg_pool(self, op, inputs, input_types):\n        data = inputs[0]\n        output_size = inputs[1]\n\n        def func(x):\n            return op(x, output_size=output_size)\n\n        if self.is_quantized_tensor(data):\n            return qnn_torch.apply_with_upcast(data, func)\n\n        return func(data)\n\n    def adaptive_max_pool(self, op, inputs, input_types):\n        data = inputs[0]\n        output_size = inputs[1]\n        # returns dummy indices too\n        return op(data, output_size=output_size), None\n\n    @staticmethod\n    def convert_const_list(data):\n        if isinstance(data, list):\n            for i, _ in enumerate(data):\n                if isinstance(data[i], _expr.Expr):\n                    data[i] = int(_infer_value_simulated(data[i], {}).numpy())\n        return data\n\n    def maxpool_2d(self, inputs, input_types):\n        data = inputs[0]\n\n        pool_size = self.convert_const_list(inputs[1])\n        strides = self.convert_const_list(inputs[2] if inputs[2] else pool_size)\n        padding = inputs[3]\n        dilation = inputs[4]\n        ceil_mode = int(inputs[5])\n\n        return _op.nn.max_pool2d(\n            data,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=\"NCHW\",\n            ceil_mode=ceil_mode,\n        )\n\n    def maxpool_2d_with_indices(self, inputs, input_types):\n        # returns dummy indices too\n        return self.maxpool_2d(inputs, input_types), None\n\n    def maxpool_1d(self, inputs, input_types):\n        data = inputs[0]\n\n        pool_size = inputs[1]\n        strides = inputs[2] if inputs[2] else pool_size\n        padding = inputs[3]\n        dilation = inputs[4]\n        ceil_mode = int(inputs[5])\n\n        return _op.nn.max_pool1d(\n            data,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=\"NCW\",\n            ceil_mode=ceil_mode,\n        )\n\n    def maxpool_3d(self, inputs, input_types):\n        data = inputs[0]\n\n        need_squeeze = False\n        if len(self.get_dims(data)) == 4:\n            need_squeeze = True\n            data = _op.expand_dims(data, 0)\n        pool_size = inputs[1]\n        strides = inputs[2] if inputs[2] else pool_size\n        padding = inputs[3]\n        dilation = inputs[4]\n        ceil_mode = int(inputs[5])\n\n        res = _op.nn.max_pool3d(\n            data,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            ceil_mode=ceil_mode,\n        )\n        return res if not need_squeeze else _op.squeeze(res, [0])\n\n    def hardtanh(self, inputs, input_types):\n        a = inputs[0]\n        tanh_min = float(inputs[1])\n        tanh_max = float(inputs[2])\n        return _op.tensor.clip(a, tanh_min, tanh_max)\n\n    def convolution(self, inputs, input_types):\n        # Use transpose or normal\n        use_transpose = True if inputs[6] == 1 else False\n\n        data = inputs[0]\n        weight = inputs[1]\n        bias = inputs[2]\n        strides = tuple(inputs[3])\n        padding = tuple(inputs[4])\n        dilation = tuple(inputs[5])\n\n        if isinstance(weight, _expr.Expr):\n            inferred_shape = self.infer_shape(weight)\n            weight_shape = []\n            for infer in inferred_shape:\n                weight_shape.append(infer)\n        else:\n            msg = \"Data type %s could not be parsed in conv op\" % (type(weight))\n            raise AssertionError(msg)\n\n        groups = int(inputs[8])\n\n        if use_transpose:\n            channels = weight_shape[1] * groups\n            in_channels = weight_shape[0]\n        else:\n            channels = weight_shape[0]\n            in_channels = weight_shape[1]\n\n        # Check if this is depth wise convolution\n        # We need to reshape weight so that Relay could recognize this is depth wise\n        # weight_shape[1] is always in_channels // groups\n        # For depthwise, in_channels == groups, so weight_shape[1] == 1\n        # If groups > 1 but weight_shape[1] != 1, this is group convolution\n        if groups > 1 and in_channels == 1:\n            channel_multiplier = channels // groups\n            new_weight_shape = (groups, channel_multiplier) + tuple(weight_shape[2:])\n            weight = _op.transform.reshape(weight, new_weight_shape)\n\n        kernel_size = weight_shape[2:]\n        use_bias = isinstance(bias, _expr.Expr)\n\n        # We are trying to invoke various relay operations through a single conv_op variable.\n        # However the function signatures for some operations have additional attributes so we\n        # pass these in along with the standard ones.\n        additional_arguments = dict()\n\n        if use_transpose:\n            if len(kernel_size) == 3:\n                conv_op = _op.nn.conv3d_transpose\n            elif len(kernel_size) == 2:\n                conv_op = _op.nn.conv2d_transpose\n            else:\n                conv_op = _op.nn.conv1d_transpose\n            output_padding = tuple(inputs[7])\n            additional_arguments[\"output_padding\"] = output_padding\n\n        else:\n            if len(kernel_size) == 3:\n                conv_op = _op.nn.conv3d\n            elif len(kernel_size) == 2:\n                conv_op = _op.nn.conv2d\n            else:\n                conv_op = _op.nn.conv1d\n\n        if len(kernel_size) == 3:\n            data_layout = \"NCDHW\"\n            kernel_layout = \"OIDHW\"\n        elif len(kernel_size) == 2:\n            data_layout = \"NCHW\"\n            kernel_layout = \"OIHW\"\n            if use_transpose:\n                # Transposed convolutions have IOHW layout.\n                kernel_layout = \"IOHW\"\n        else:\n            data_layout = \"NCW\"\n            kernel_layout = \"OIW\"\n\n        # Conv1d does not currently support grouped convolution so we convert it to conv2d\n        is_grouped_conv1d = False\n        if groups > 1 and len(kernel_size) == 1 and not use_transpose:\n            is_grouped_conv1d = True\n            conv_op = _op.nn.conv2d\n            kernel_size = [1] + kernel_size\n            strides = (1,) + strides\n            padding = (0,) + padding\n            dilation = (1,) + dilation\n            data = _op.expand_dims(data, axis=2)\n            weight = _op.expand_dims(weight, axis=2)\n            data_layout = \"NCHW\"\n            kernel_layout = \"OIHW\"\n\n        conv_out = conv_op(\n            data,\n            weight,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n            channels=channels,\n            kernel_size=kernel_size,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            out_layout=\"\",\n            out_dtype=\"\",\n            **additional_arguments,\n        )\n        if use_bias:\n            res = _op.nn.bias_add(conv_out, bias)\n        else:\n            res = conv_out\n        if is_grouped_conv1d:\n            # Because we conducted grouped conv1d convolution through conv2d we must\n            # squeeze the output to get the correct result.\n            res = _op.squeeze(res, axis=[2])\n        return res\n\n    def softmax(self, inputs, input_types):\n        data = inputs[0]\n        axis = inputs[1]\n        if isinstance(axis, str):\n            axis = int(axis)\n\n        return _op.nn.softmax(data, axis=axis)\n\n    def threshold(self, inputs, input_types):\n        data = inputs[0]\n        return _op.nn.relu(data)\n\n    def contiguous(self, inputs, input_types):\n        return inputs[0]\n\n    def batch_norm(self, inputs, input_types):\n        data = inputs[0]\n        data_type = input_types[0]\n\n        channels = self.infer_shape(data)\n\n        if isinstance(inputs[1], _expr.Expr) and isinstance(inputs[2], _expr.Expr):\n            scale = center = True\n            weight = inputs[1]\n            beta = inputs[2]\n            gamma = weight\n        else:\n            scale = center = False\n\n        if not scale:\n            gamma = _create_typed_const(np.ones([int(channels[1])]), data_type)\n\n        if not center:\n            beta = _create_typed_const(np.zeros([int(channels[1])]), data_type)\n\n        moving_mean = inputs[3]\n        moving_var = inputs[4]\n        epsilon = float(inputs[7])\n\n        return _op.nn.batch_norm(\n            data,\n            gamma,\n            beta,\n            moving_mean,\n            moving_var,\n            axis=1,\n            epsilon=epsilon,\n            center=center,\n            scale=scale,\n        )[0]\n\n    def instance_norm(self, inputs, input_types):\n        data = inputs[0]\n        data_type = input_types[0]\n        channels = self.infer_shape(data)\n\n        if isinstance(inputs[1], _expr.Expr) and isinstance(inputs[2], _expr.Expr):\n            scale = center = True\n            weight = inputs[1]\n            beta = inputs[2]\n            gamma = weight\n        else:\n            scale = center = False\n\n        if not scale:\n            gamma = _create_typed_const(np.ones([int(channels[1])]), data_type)\n\n        if not center:\n            beta = _create_typed_const(np.zeros([int(channels[1])]), data_type)\n\n        epsilon = float(inputs[7])\n        return _op.nn.instance_norm(\n            data, gamma, beta, axis=1, epsilon=epsilon, center=center, scale=scale\n        )\n\n    def get_dims(self, data):\n        import torch\n\n        if isinstance(data, _expr.Expr):\n            dims = self.infer_shape(data)\n        elif isinstance(data, list):\n            dims = data\n        elif isinstance(data, (torch.Tensor, np.ndarray)):\n            dims = data.shape\n        else:\n            msg = \"Data type %s could not be parsed\" % type(data)\n            raise AssertionError(msg)\n        return dims\n\n    def layer_norm(self, inputs, input_types):\n        data = inputs[0]\n        ndims = len(self.get_dims(inputs[1]))\n        assert ndims == 1, \"Support only normalization over last one dimension.\"\n\n        return _op.nn.layer_norm(\n            data,\n            gamma=inputs[2],\n            beta=inputs[3],\n            axis=-1,\n            epsilon=float(inputs[4]),\n            center=True,\n            scale=True,\n        )\n\n    def group_norm(self, inputs, input_types):\n        data = inputs[0]\n        gamma = inputs[2]\n        beta = inputs[3]\n        num_groups = inputs[1]\n        epsilon = float(inputs[4])\n\n        return _op.nn.group_norm(\n            data,\n            gamma=gamma,\n            beta=beta,\n            num_groups=num_groups,\n            axis=1,\n            epsilon=epsilon,\n            center=True,\n            scale=True,\n        )\n\n    def transpose(self, inputs, input_types):\n        data = inputs[0]\n\n        import torch\n\n        if isinstance(data, _expr.Expr):\n            ndims = len(self.infer_shape_with_prelude(data))\n        elif isinstance(data, list):\n            ndims = data\n        elif isinstance(data, (torch.Tensor, np.ndarray)):\n            ndims = data.shape\n        else:\n            msg = \"Data type %s could not be parsed in transpose op\" % (type(data))\n            raise AssertionError(msg)\n\n        if isinstance(data, tvm.runtime.NDArray):\n            ndims = len(data.shape)\n        axes = list(range(ndims))\n\n        num_inputs = len(inputs)\n\n        if num_inputs == 1:\n            if ndims >= 2:\n                axes[-1] = ndims - 2\n                axes[-2] = ndims - 1\n            if not isinstance(data, _expr.Expr):\n                data = _expr.const(data)\n\n        elif num_inputs == 3:\n            parse = lambda i: ndims * (i < 0) + i\n            src, dst = [parse(int(inputs[i])) for i in [1, 2]]\n            axes[src] = dst\n            axes[dst] = src\n        else:\n            axes = inputs[1]\n        return _op.transform.transpose(data, axes)\n\n    def numpy_T(self, inputs, input_types):\n        data = inputs[0]\n        shape = self.infer_shape(data)\n        if len(shape) != 2:\n            logger.warning(\n                \"The use of Tensor.T on tensors of dimensions != 2 is deprecated\"\n                \"and will be removed in a future release of PyTorch.\"\n            )\n        return _op.transform.transpose(data)\n\n    def flatten(self, inputs, input_types):\n        data = inputs[0]\n        start = int(inputs[1])\n        end = int(inputs[2])\n        dshape = get_const_tuple(self.infer_shape_with_prelude(data))\n        ndim = len(dshape)\n        if start < 0:\n            start += ndim\n        if end < 0:\n            end += ndim\n        assert start <= end, \"start dim cannot come after end dim\"\n        new_shape = [0] * start\n\n        new_shape.append(-1)\n        squeeze_axes = []\n        for i in range(start + 1, end + 1):\n            new_shape.append(1)\n            squeeze_axes.append(i)\n        for _ in range(end + 1, ndim):\n            new_shape.append(0)\n        out = _op.reshape(data, new_shape)\n        if squeeze_axes:\n            out = _op.squeeze(out, axis=squeeze_axes)\n        return out\n\n    def addmm(self, inputs, input_types):\n        input_mat = inputs[0]\n        mat1 = inputs[1]\n        data_type = input_types[1]\n        mat2 = inputs[2]\n\n        beta = inputs[3]\n        alpha = inputs[4]\n\n        if not isinstance(alpha, _expr.Expr) and alpha != 1:\n            alpha = _create_typed_const(alpha, data_type)\n            mat1 *= alpha\n\n        if not isinstance(beta, _expr.Expr) and beta != 1:\n            beta = _create_typed_const(beta, data_type)\n            mat2 *= beta\n\n        transposed_mat2 = _op.transform.transpose(mat2, axes=[1, 0])\n\n        units = self.infer_shape(transposed_mat2)[0]\n        dense_out = _op.nn.dense(mat1, transposed_mat2, units=units)\n\n        return dense_out + input_mat\n\n    def size(self, inputs, input_types):\n        shape = self.infer_shape_with_prelude(inputs[0])\n        axis = None\n        if len(inputs) > 1:\n            axis = int(inputs[1])\n\n        if any(map(lambda s: isinstance(s, tvm.tir.expr.Any), shape)):\n            if axis is None or isinstance(shape[axis], tvm.tir.expr.Any):\n                shape_dynamic = _op.shape_of(inputs[0], dtype=\"int32\")\n                if axis is not None:\n                    return _op.take(shape_dynamic, _expr.const(axis), 0)\n                return shape_dynamic\n\n        if axis is not None:\n            return _expr.const(shape[axis])\n        return _expr.const(shape)\n\n    def numtotensor(self, inputs, input_types):\n        val = inputs[0]\n        dtype = input_types[0]\n\n        if isinstance(val, _expr.Expr):\n            return val\n\n        if isinstance(val, tvm.tir.IntImm):\n            val = val.__int__()\n            dtype = int\n\n        arr = val * np.ones([]).astype(dtype)\n        return arr\n\n    def tensortonum(self, inputs, input_types):\n        return inputs[0]\n\n    def view(self, inputs, input_types):\n        data = inputs[0]\n\n        if len(inputs) == 3:\n            shape_inp = [inputs[1], self.infer_shape(inputs[2])[0]]\n        else:\n            if isinstance(inputs[1], list):\n                shape_inp = inputs[1]\n            else:\n                shape_inp = self.infer_shape(inputs[1])\n        new_shape = shape_inp\n        for i, shape in enumerate(shape_inp):\n            if isinstance(shape, _expr.Expr):\n                val = _infer_value_simulated(shape, {})\n                new_shape[i] = val.numpy().item(0)\n\n        return _op.transform.reshape(data, new_shape)\n\n    def reshape(self, inputs, input_types):\n        data = inputs[0]\n        new_shape = inputs[1]\n\n        tmp_shape = []\n        is_dyn = False\n        for s in new_shape:\n            if isinstance(s, _expr.Constant):\n                tmp_shape.append(int(s.data.numpy()))\n            elif isinstance(s, _expr.Expr):\n                dim, success = try_infer_value(s, lambda ret: int(ret))\n                tmp_shape.append(dim)\n\n                if not success:\n                    is_dyn = True\n            else:\n                tmp_shape.append(s)\n\n        if is_dyn:\n            new_shape = []\n            for i, s in enumerate(tmp_shape):\n                if not isinstance(s, _expr.Expr):\n                    s = _expr.const(s, \"int64\")\n                else:\n                    s = _op.cast(s, \"int64\")\n                new_shape.append(_op.expand_dims(s, axis=0))\n            new_shape = _op.concatenate(new_shape, axis=0)\n        else:\n            new_shape = tmp_shape\n        return _op.transform.reshape(data, new_shape)\n\n    def reshape_as(self, inputs, input_types):\n        data = inputs[0]\n        new_shape = self.infer_shape(inputs[1])\n        return _op.transform.reshape(data, new_shape)\n\n    def pixel_shuffle(self, inputs, input_types):\n        data = inputs[0]\n        upscale_factor = inputs[1]\n        upscale_squared = upscale_factor * upscale_factor\n        b, c, h, w = self.infer_shape(data)\n        assert (\n            c % upscale_squared == 0\n        ), \"input channel should be divisible by square of upscale_factor\"\n\n        ndims = len(self.infer_shape_with_prelude(data))\n        axes = list(range(ndims))\n        num_inputs = len(inputs)\n        oc = c // upscale_squared\n        oh = h * upscale_factor\n        ow = w * upscale_factor\n\n        new_shape = [b, oc, upscale_factor, upscale_factor, h, w]\n        out_shape = [b, oc, oh, ow]\n\n        data = _op.transform.reshape(data, new_shape)\n        # The data will be transposed to\n        # [b, oc, h, upscale_factor, w, upscale_factor]\n        # for further reshape\n        axes = [0, 1, 4, 2, 5, 3]\n        data = _op.transform.transpose(data, axes)\n        return _op.transform.reshape(data, out_shape)\n\n    def clone(self, inputs, input_types):\n        data = inputs[0]\n        return _op.tensor.copy(data)\n\n    def log_softmax(self, inputs, input_types):\n        data = inputs[0]\n        axis = int(inputs[1])\n        return _op.nn.log_softmax(data, axis)\n\n    def sigmoid(self, inputs, input_types):\n        data = inputs[0]\n\n        def func(x):\n            return _op.tensor.sigmoid(x)\n\n        if self.is_quantized_tensor(data):\n            assert len(inputs) == 5, \"Input/Ouput quant param not found in op inputs\"\n            return qnn_torch.quantized_sigmoid(inputs)\n\n        return func(data)\n\n    def softplus(self, inputs, input_types):\n        dtype = input_types[0]\n        beta = _expr.const(float(inputs[1]), dtype=dtype)\n        return _op.log(_op.exp(inputs[0] * beta) + _expr.const(1.0, dtype=dtype)) / beta\n\n    def make_avg_pool(self, dim):\n        def avg_pool(inputs, input_types):\n            data = inputs[0]\n\n            pool_size = self.convert_const_list(inputs[1])\n            strides = self.convert_const_list(inputs[2] if inputs[2] else pool_size)\n            padding = inputs[3]\n            ceil_mode = int(inputs[4])\n            count_include_pad = int(inputs[5])\n\n            def func(x):\n                if dim == 1:\n                    return _op.nn.avg_pool1d(\n                        x,\n                        pool_size=pool_size,\n                        strides=strides,\n                        padding=padding,\n                        dilation=(1,),\n                        ceil_mode=ceil_mode,\n                        count_include_pad=count_include_pad,\n                    )\n                elif dim == 2:\n                    return _op.nn.avg_pool2d(\n                        x,\n                        pool_size=pool_size,\n                        strides=strides,\n                        padding=padding,\n                        dilation=(1, 1),\n                        ceil_mode=ceil_mode,\n                        count_include_pad=count_include_pad,\n                    )\n                elif dim == 3:\n                    return _op.nn.avg_pool3d(\n                        x,\n                        pool_size=pool_size,\n                        strides=strides,\n                        padding=padding,\n                        dilation=(1, 1, 1),\n                        ceil_mode=ceil_mode,\n                        count_include_pad=count_include_pad,\n                    )\n                else:\n                    msg = \"Average Pooling dimension should be between 1 and 3\"\n                    raise RuntimeError(msg)\n\n            if self.is_quantized_tensor(data):\n                return qnn_torch.apply_with_upcast(data, func)\n\n            return func(data)\n\n        return avg_pool\n\n    def linear(self, inputs, input_types):\n        # https://pytorch.org/docs/stable/nn.functional.html#linear\n        # 0 - input\n        # 1 - weight\n        bias = inputs[2]\n        a_shape = self.infer_shape_with_prelude(inputs[0])\n        b_shape = self.infer_shape_with_prelude(inputs[1])\n        if len(a_shape) == 2 and len(b_shape) == 2:\n            mm_out = _op.nn.dense(inputs[0], inputs[1])\n        elif len(b_shape) == 1:\n            mm_out = self.matmul([inputs[0], inputs[1]], input_types[:2])\n        else:\n            mm_out = self.matmul(\n                [inputs[0], _op.transpose(inputs[1], axes=(1, 0))], input_types[:2]\n            )\n        if isinstance(bias, _expr.Expr):\n            bias_ndims = len(self.infer_shape_with_prelude(bias))\n            if bias_ndims == 1:\n                return _op.nn.bias_add(mm_out, bias, axis=-1)\n            mm_dtype = self.infer_type_with_prelude(mm_out).dtype\n            return self.add([mm_out, bias], [mm_dtype, input_types[2]])\n        return mm_out\n\n    def dropout(self, inputs, input_types):\n        data = inputs[0]\n        rate = float(inputs[1])\n\n        return _op.nn.dropout(data, rate)\n\n    def make_reduce(self, name):\n        def reduce(inputs, input_types):\n            data = inputs[0]\n            axis = None\n            keepdims = False\n\n            if len(inputs) > 2:  # default, torch have only data, axis=None, keepdims=False\n                if isinstance(inputs[1], int):\n                    axis = int(inputs[1])\n                elif _is_int_seq(inputs[1]):\n                    axis = inputs[1]\n                else:\n                    axis = list(self.infer_shape(inputs[1]))\n                keepdims = bool(inputs[2])\n\n            return get_relay_op(name)(data, axis=axis, keepdims=keepdims)\n\n        return reduce\n\n    def norm(self, inputs, input_types):\n        data = inputs[0]\n        dtype = input_types[0]\n        axis = None\n        keepdims = False\n        if len(inputs) > 3:\n            axis = inputs[2]\n            keepdims = bool(inputs[3])\n\n        order = inputs[1]\n        if order == np.inf:\n            return _op.reduce.max(_op.abs(data), axis=axis, keepdims=keepdims)\n        elif order == np.NINF:\n            return _op.reduce.min(_op.abs(data), axis=axis, keepdims=keepdims)\n        else:\n            reci_order = _expr.const(1.0 / order, dtype=dtype)\n            order = _expr.const(order)\n            return _op.power(\n                _op.reduce.sum(_op.power(_op.abs(data), order), axis=axis, keepdims=keepdims),\n                reci_order,\n            )\n\n    def frobenius_norm(self, inputs, input_types):\n        data = inputs[0]\n        axis = None\n        keepdims = False\n        if len(inputs) > 2:\n            axis = inputs[1] if len(inputs[1]) > 0 else None\n            keepdims = bool(inputs[2])\n\n        return _op.sqrt(_op.reduce.sum((data * data), axis=axis, keepdims=keepdims))\n\n    def std(self, inputs, input_types):\n        data = inputs[0]\n        if len(inputs) == 2:\n            axis = None\n            keepdims = False\n            unbiased = bool(inputs[1])\n        else:\n            axis = inputs[1]\n            keepdims = bool(inputs[3])\n            unbiased = bool(inputs[2])\n\n        return _op.reduce.std(data, axis=axis, keepdims=keepdims, unbiased=unbiased)\n\n    def variance(self, inputs, input_types):\n        data = inputs[0]\n        if len(inputs) == 2:\n            axis = None\n            keepdims = False\n            unbiased = bool(inputs[1])\n        else:\n            axis = inputs[1]\n            keepdims = bool(inputs[3])\n            unbiased = bool(inputs[2])\n\n        return _op.reduce.variance(data, axis=axis, keepdims=keepdims, unbiased=unbiased)\n\n    def mean(self, inputs, input_types):\n        data = inputs[0]\n\n        if inputs[1]:\n            axis = inputs[1]\n        else:\n            axis = None\n\n        if len(inputs) > 2 and inputs[2]:\n            keepdims = int(inputs[2])\n        else:\n            keepdims = False\n        if len(inputs) > 3 and inputs[3]:\n            exclude = int(inputs[3])\n        else:\n            exclude = False\n\n        def func(x):\n            return _op.mean(x, axis, keepdims, exclude)\n\n        if self.is_quantized_tensor(data):\n            assert len(inputs) == 6, \"Input quant param not found in op inputs\"\n            input_scale = _expr.const(inputs[4])\n            input_zero_point = _expr.const(inputs[5])\n            # refer to aten/src/ATen/native/quantized/cpu/qreduction.cpp\n            return qnn_torch.apply_with_fp32_fallback(data, input_scale, input_zero_point, func)\n\n        return func(data)\n\n    def var_mean(self, inputs, input_types):\n        data = inputs[0]\n        if len(inputs) == 2:\n            axis = None\n            keepdims = False\n            unbiased = bool(inputs[1])\n        else:\n            axis = inputs[1]\n            keepdims = bool(inputs[3])\n            unbiased = bool(inputs[2])\n\n        m, v = _op.reduce.mean_variance(data, axis, keepdims, False, unbiased)\n        return v, m\n\n    def chunk(self, inputs, input_types):\n        data = inputs[0]\n\n        num_chunks = int(inputs[1])\n        axis = int(inputs[2])\n\n        if isinstance(data, _expr.Expr):\n            inferred_shape = self.infer_shape_with_prelude(data)\n\n        shape = []\n        for infer in inferred_shape:\n            shape.append(infer)\n\n        dim = int(shape[axis])\n\n        if dim % num_chunks:\n            unif_size = int(dim / (num_chunks - 1))\n        else:\n            unif_size = int(dim / num_chunks)\n\n        indeces = []\n        for i in range(unif_size, dim, unif_size):\n            indeces.append(i)\n\n        return _op.split(data, indeces, axis)\n\n    def matmul(self, inputs, input_types):\n\n        inputs_0 = inputs[0]\n        inputs_1 = inputs[1]\n\n        # Need to check input shape as batch matmul must be supported.\n        a_shape = self.infer_shape_with_prelude(inputs_0)\n        b_shape = self.infer_shape_with_prelude(inputs_1)\n\n        # When performing a batch matmul, we need to properly handle N-dim shapes.\n        if len(a_shape) > 2 and len(b_shape) > 2:\n            # Convert a into a 3 dimensional tensors.\n            need_reshape_output = False\n            if len(a_shape) != 3:\n                a = _op.reshape(inputs_0, [-1, a_shape[-2], a_shape[-1]])\n                need_reshape_output = True\n            else:\n                a = inputs_0\n\n            # Transpose matrix dimensions of b.\n            trans_axes = list(range(len(b_shape)))\n            trans_axes[-2], trans_axes[-1] = trans_axes[-1], trans_axes[-2]\n            b = _op.transpose(inputs_1, trans_axes)\n\n            # Convert b into a 3 dimensional tensor. Note that the last two dimensions\n            # are transposed.\n            if len(b_shape) != 3:\n                b = _op.reshape(b, [-1, b_shape[-1], b_shape[-2]])\n\n            # Perform a batch matmul.\n            output = _op.nn.batch_matmul(a, b)\n\n            # Reshape output to original dimensions.\n            if need_reshape_output:\n                return _op.reshape(output, [*a_shape[:-2], a_shape[-2], b_shape[-1]])\n            return output\n        elif len(a_shape) > 2:\n            inputs_0 = _op.reshape(inputs_0, [-1, a_shape[-1]])\n        elif len(a_shape) == 1:\n            return _op.squeeze(_op.nn.matmul(_op.expand_dims(inputs_0, axis=0), inputs_1), axis=[0])\n\n        if len(b_shape) > 2:\n            trans_axes = list(range(len(b_shape)))\n            trans_axes[-2], trans_axes[-1] = trans_axes[-1], trans_axes[-2]\n            input_1 = _op.reshape(_op.transpose(inputs_1, trans_axes), [-1, b_shape[-2]])\n        elif len(b_shape) == 2:\n            input_1 = _op.transpose(inputs_1, axes=(1, 0))\n        elif len(b_shape) == 1:\n            input_1 = _op.expand_dims(inputs_1, 0, 1)\n\n        out = _op.nn.dense(inputs_0, input_1)\n\n        if len(b_shape) == 1:\n            out = _op.squeeze(out, axis=[-1])\n\n        # Reshape output into a N dimensional tensor when a or b dim > 2\n        if len(a_shape) > 2:\n            out = _op.reshape(out, [*a_shape[:-1], b_shape[-1]])\n        elif len(b_shape) > 2:\n            out = _op.reshape(out, [a_shape[-2], -1, b_shape[-1]])\n            out = _op.reshape(\n                _op.transpose(out, [1, 0, 2]), [*b_shape[:-2], a_shape[-2], b_shape[-1]]\n            )\n\n        return out\n\n    def expand(self, inputs, input_types):\n        data_in = inputs[0]\n        shape = list(self.infer_shape(data_in))\n\n        ndims = len(shape)\n        sizes = inputs[1]\n        out = data_in\n\n        out_dims = len(sizes)\n        if ndims < out_dims:\n            num_newaxis = out_dims - ndims\n            out = _op.expand_dims(out, axis=0, num_newaxis=num_newaxis)\n            shape = [1] * num_newaxis + shape\n\n        for i in range(out_dims):\n            if sizes[i] != -1 and shape[i] == 1:\n                if not isinstance(sizes[i], int):\n                    sizes[i] = int(_infer_value(sizes[i], {}).numpy())\n                out = _op.repeat(out, sizes[i], axis=i)\n\n        return out\n\n    def int(self, inputs, input_types):\n        if isinstance(inputs[0], _expr.Expr):\n            return inputs[0]\n        return int(inputs[0])\n\n    def identity(self, inputs, input_types):\n        return inputs[0]\n\n    def none(self, inputs, input_types):\n        return None\n\n    def pad_common(self, mode, pad_value, inputs, input_types):\n        data = inputs[0]\n        if isinstance(inputs[1], list):\n            pad_list = inputs[1]\n        else:\n            pad_list = list(self.infer_shape(inputs[1]))\n\n        # initialize paddings based on input len\n        pad_len = len(self.infer_shape(data)) * 2\n        paddings = [0] * pad_len\n\n        if len(pad_list) >= 2:\n            paddings[-1] = pad_list[1]\n            paddings[-2] = pad_list[0]\n        if len(pad_list) >= 4:\n            paddings[-3] = pad_list[3]\n            paddings[-4] = pad_list[2]\n        if len(pad_list) >= 6:\n            paddings[-5] = pad_list[5]\n            paddings[-6] = pad_list[4]\n\n        # group into tuple of 2 ints\n        paddings = [paddings[i : i + 2] for i in range(0, len(paddings), 2)]\n\n        const_paddings = []\n        non_zero_found = False\n        for pad in paddings:\n            const_paddings.append([])\n            for p in pad:\n                if isinstance(p, _expr.Expr):\n                    p = int(_infer_value(p, {}).numpy())\n                elif not isinstance(p, int):\n                    raise NotImplementedError(\"pad width should be int/expr\")\n                const_paddings[-1].append(p)\n                if p != 0:\n                    non_zero_found = True\n\n        if not non_zero_found:\n            return data\n        elif mode == \"constant\":\n            return _op.nn.pad(data, const_paddings, pad_value=pad_value, pad_mode=mode)\n        else:\n            return _op.nn.pad(data, const_paddings, pad_mode=mode)\n\n    def pad(self, inputs, input_types):\n        # mode: Optional default \"constant\"\n        if len(inputs) > 2 and inputs[2] is not None:\n            mode = inputs[2]\n        else:\n            mode = \"constant\"\n\n        # pad_value: Optional default 0\n        if len(inputs) == 4 and inputs[3] is not None:\n            pad_value = inputs[3]\n        else:\n            pad_value = 0\n\n        # replicate is edge in TVM's padding mode\n        if mode == \"replicate\":\n            mode = \"edge\"\n        elif mode == \"circular\":\n            raise ValueError(\"circular mode for torch.nn.functional.pad are not supported in TVM\")\n        return self.pad_common(mode, pad_value, inputs, input_types)\n\n    def constant_pad_nd(self, inputs, input_types):\n        return self.pad_common(\"constant\", _expr.const(inputs[2]), inputs, input_types)\n\n    def reflection_pad1d(self, inputs, input_types):\n        return self.pad_common(\"reflect\", 0, inputs, input_types)\n\n    def reflection_pad2d(self, inputs, input_types):\n        return self.pad_common(\"reflect\", 0, inputs, input_types)\n\n    def replication_pad1d(self, inputs, input_types):\n        return self.pad_common(\"edge\", 0, inputs, input_types)\n\n    def replication_pad2d(self, inputs, input_types):\n        return self.pad_common(\"edge\", 0, inputs, input_types)\n\n    def replication_pad3d(self, inputs, input_types):\n        return self.pad_common(\"edge\", 0, inputs, input_types)\n\n    def clamp_common(self, data, min=None, max=None):\n        def get_v(v, default_v):\n            if isinstance(v, _expr.Constant):\n                return float(v.data.numpy())\n            if isinstance(v, _expr.Expr):\n                infer_v, success = try_infer_value(v, lambda ret: float(ret))\n                if success:\n                    return infer_v\n            if v is not None:\n                return v\n            return default_v\n\n        dtype = self.infer_type(data).dtype\n\n        type_info = np.finfo(dtype) if \"float\" in dtype else np.iinfo(dtype)\n\n        # TODO(masahi): Properly handle inf in a one-way clamp case.\n        if min is not None and max is not None:\n            amin = get_v(min, type_info.min)\n            amax = get_v(max, type_info.max)\n        elif min is not None:\n            amin = get_v(min, type_info.min)\n            amax = type_info.max\n        else:\n            amin = type_info.min\n            amax = get_v(max, type_info.max)\n\n        return _op.clip(data, amin, amax)\n\n    def clamp(self, inputs, _):\n        return self.clamp_common(inputs[0], min=inputs[1], max=inputs[2])\n\n    def clamp_min(self, inputs, input_types):\n        return self.clamp_common(inputs[0], min=inputs[1])\n\n    def clamp_max(self, inputs, input_types):\n        return self.clamp_common(inputs[0], max=inputs[1])\n\n    def to(self, inputs, input_types):\n        data = inputs[0]\n        dtype = inputs[1] if inputs[1] is not None and not isinstance(inputs[1], str) else inputs[2]\n        # special handling for aten::to(data, 6, _, _, _) case\n        # 6 means dtype = float\n        # this happens when converting upsampling with scale factor\n        cast_map = {\n            5: \"float16\",\n            6: \"float32\",\n            7: \"float64\",\n            3: \"int32\",\n            4: \"int64\",\n        }\n\n        cast_func = {5: float, 6: float, 7: float, 3: int, 4: int}\n\n        ret = data\n        if isinstance(data, _expr.Expr):\n            actual_dtype = str(self.infer_type(data).dtype)\n            if dtype in cast_map and cast_map[dtype] != actual_dtype:\n                ret = _op.cast(data, cast_map[dtype])\n        elif dtype in cast_map:\n            ret = cast_func[dtype](data)\n\n        return ret\n\n    def get_upsample_out_size(self, inputs, method):\n        # This assumes a static shape\n        out_size = []\n        if inputs[1] is not None:\n            for size in inputs[1]:\n                if not isinstance(size, int):\n                    out_size.append(int(_infer_value(size, {}).numpy()))\n                else:\n                    out_size.append(size)\n        else:\n            scale_index = 3 if method != \"nearest_neighbor\" else 2\n            scales = inputs[scale_index]\n            assert scales is not None, \"neither out size nor scale provided\"\n            assert isinstance(scales, list)\n            ishape = self.infer_shape(inputs[0])\n            for i, scale in enumerate(scales):\n                out_size.append(int(math.floor(float(ishape[2 + i]) * scale)))\n\n        return out_size\n\n    def make_upsample(self, method):\n        def upsample(inputs, input_types):\n            data = inputs[0]\n            out_size = self.get_upsample_out_size(inputs, method)\n\n            if len(inputs) > 2 and method != \"nearest_neighbor\":\n                align_corners = inputs[2]\n            else:\n                align_corners = False\n\n            if method == \"nearest_neighbor\":\n                coord_trans = \"asymmetric\"\n            elif align_corners:\n                coord_trans = \"align_corners\"\n            else:\n                coord_trans = \"half_pixel\"\n\n            def func(x):\n                return _op.image.resize2d(\n                    x, out_size, None, \"NCHW\", method, coord_trans, cubic_alpha=-0.75\n                )\n\n            if self.is_quantized_tensor(data):\n                # input qparams are manually appended by us\n                assert isinstance(inputs[-2], float)\n                assert isinstance(inputs[-1], int)\n                input_scale = _expr.const(inputs[-2])\n                input_zero_point = _expr.const(inputs[-1])\n                # currently piggy backs to fp32, it gets identical output as torch\n                return qnn_torch.apply_with_fp32_fallback(data, input_scale, input_zero_point, func)\n\n            return func(data)\n\n        return upsample\n\n    def make_upsample3d(self, method):\n        def upsample3d(inputs, input_types):\n            data = inputs[0]\n            out_size = self.get_upsample_out_size(inputs, method)\n\n            if len(inputs) > 2 and method == \"linear\":\n                align_corners = inputs[2]\n            else:\n                align_corners = False\n\n            if method == \"nearest_neighbor\":\n                coord_trans = \"asymmetric\"\n            elif align_corners:\n                coord_trans = \"align_corners\"\n            else:\n                coord_trans = \"half_pixel\"\n\n            return _op.image.resize3d(data, out_size, None, \"NCDHW\", method, coord_trans)\n\n        return upsample3d\n\n    def expand_as(self, inputs, input_types):\n        target = inputs[1]\n        t0 = self.infer_type(inputs[0]).dtype\n        t1 = self.infer_type(inputs[1]).dtype\n        if str(t0) != str(t1):\n            target = _op.cast(target, t0)\n        return _op.broadcast_to_like(inputs[0], target)\n\n    def broadcast_tensors(self, inputs, input_types):\n        tensor_list = inputs[0]\n        import torch\n\n        res_shape = list(torch.broadcast_shapes(*[self.infer_shape(t) for t in tensor_list]))\n        return [_op.broadcast_to(tensor, res_shape) for tensor in tensor_list]\n\n    def Bool(self, inputs, input_types):\n        assert len(inputs) == 1\n        return inputs[0]\n\n    def Float(self, inputs, input_types):\n        assert len(inputs) == 1\n        return _op.cast(inputs[0], \"float32\")\n\n    def bitwise_not(self, inputs, input_types):\n        data = inputs[0]\n        # The input tensor must be of integral or Boolean types.\n        # For bool tensors, it computes the logical NOT\n        if input_types[0] == \"bool\":\n            out = _op.logical_not(_op.cast(data, \"bool\"))\n        else:\n            out = _op.bitwise_not(_op.cast(data, \"int\"))\n\n        return out\n\n    def bitwise_xor(self, inputs, input_types):\n        lhs = inputs[0]\n        rhs = inputs[1]\n        lhs = _op.cast(lhs, \"bool\") if input_types[0] == \"bool\" else _op.cast(lhs, \"int\")\n        rhs = _op.cast(rhs, \"bool\") if input_types[1] == \"bool\" else _op.cast(rhs, \"int\")\n\n        return _op.bitwise_xor(lhs, rhs)\n\n    def logical_not(self, inputs, input_types):\n        data = _wrap_const(inputs[0])\n        return _op.logical_not(_op.cast(data, \"bool\"))\n\n    def logical_xor(self, inputs, input_types):\n        lhs = _op.cast(inputs[0], \"bool\")\n        rhs = _op.cast(inputs[1], \"bool\")\n\n        return _op.logical_xor(lhs, rhs)\n\n    def list_getitem(self, inputs, input_types):\n        return self.prelude.nth(inputs[0], _wrap_const(inputs[1]))\n\n    def list_len(self, inputs, input_types):\n        return self.prelude.length(inputs[0])\n\n    def type_as(self, inputs, input_types):\n        assert len(inputs) == 2\n        assert len(input_types) == 2\n        return _op.cast(inputs[0], input_types[1])\n\n    def gather(self, inputs, input_types):\n        data = inputs[0]\n        axis = inputs[1]\n        indices = inputs[2]\n\n        return _op.gather(data, axis, indices)\n\n    def add(self, inputs, input_types):\n        # add_ is overloaded for tensor add and list concat\n        if input_types[0] == \"ListType\":\n            return self.prelude.concat(inputs[0], inputs[1])\n        return self.make_elemwise(\"add\")(inputs, input_types)\n\n    def tensor_array_stack(self, inputs, input_types):\n        dim = inputs[1]\n        assert dim == 0, \"stacking on a dynamic tensor list only supported on a first axis\"\n        tensor_array, shape = self.convert_to_tensor_array(inputs[0])\n\n        stacked_shape = (Any(),) + shape\n        stack = self.prelude.get_global_var_static(\"tensor_array_stack\", \"float32\", shape)\n        stacked = stack(tensor_array)\n\n        static_tensor_array_ops = StaticTensorArrayOps(self.prelude, \"float32\", stacked_shape)\n        static_tensor_array_ops.register()\n        get_tensor = self.prelude.get_global_var_static(\"tensor_get_data\", \"float32\", stacked_shape)\n        return get_tensor(stacked)\n\n    def stack(self, inputs, input_types):\n        if isinstance(inputs[0], list):\n            # a static python list of tensors\n            dim = inputs[1]\n            return _op.stack(inputs[0], dim)\n        else:\n            # List ADT case\n            assert isinstance(inputs[0], _expr.Expr)\n            ty = self.infer_type_with_prelude(inputs[0])\n            list_ty = self.prelude.mod.get_global_type_var(\"List\")\n            msg = \"The input list is expected to be List ADT\"\n            assert isinstance(ty, tvm.ir.TypeCall) and ty.func == list_ty, msg\n            return self.tensor_array_stack(inputs, input_types)\n\n    def sub(self, inputs, input_types):\n        if len(inputs) == 3:\n            data0, data1, alpha = self.pytorch_promote_types(inputs, input_types)\n            return get_relay_op(\"subtract\")(data0, alpha * data1)\n        else:\n            data0, data1 = self.pytorch_promote_types(inputs, input_types)\n            return get_relay_op(\"subtract\")(data0, data1)\n\n    def rsub(self, inputs, input_types):\n        data0, data1, alpha = self.pytorch_promote_types(inputs, input_types)\n\n        # note: rsub means data0 and data1 swap places\n        return get_relay_op(\"subtract\")(data1, alpha * data0)\n\n    def embedding(self, inputs, input_types):\n        weight = inputs[0]\n        indices = inputs[1]\n\n        return _op.take(weight, indices.astype(\"int32\"), axis=0)\n\n    def one_hot(self, inputs, input_types):\n        indices = inputs[0].astype(\"int32\")\n        num_classes = inputs[1]\n        if num_classes == -1:\n            msg = \"Inferring the number of classes is not yet supported.\"\n            raise NotImplementedError(msg)\n\n        dtype = \"int32\"\n        on_value = tvm.relay.const(1.0, dtype)\n        off_value = tvm.relay.const(0.0, dtype)\n\n        return _op.one_hot(indices, on_value, off_value, num_classes, -1, dtype)\n\n    def index(self, inputs, input_types):\n        data = inputs[0]\n        indices_list = []\n\n        for indices in inputs[1]:\n            if self.infer_type(indices).dtype == \"bool\":\n                # adv_index does not support a mask as the index tensor (it will treat 0/1 as\n                # an index rather than a flag).\n                # So we use argwhere to turn the mask into indices, which will also take care\n                # of the dynamism in the indexing by mask.\n                indices_list.append(_op.squeeze(_op.transform.argwhere(indices), axis=[1]))\n            else:\n                indices_list.append(indices)\n\n        return _op.adv_index([data] + indices_list)\n\n    def meshgrid(self, inputs, input_types):\n        data = inputs[0]\n        return _op.meshgrid(data, indexing=\"ij\")\n\n    def nms(self, inputs, input_types):\n        boxes = inputs[0]\n        scores = inputs[1]\n        iou_threshold = inputs[2]\n\n        # TVM NMS assumes score > 0\n        scores = scores - _op.min(scores) + _op.const(1.0)\n\n        num_boxes = _op.shape_of(scores)\n        # PyTorch NMS doesn't have score_threshold, so no need to run get_valid_count\n        indices = _op.transform.arange(_op.squeeze(num_boxes), dtype=\"int32\")\n        indices = _op.expand_dims(indices, 0, 1)\n\n        # Generate data with shape (1, num_anchors, 5)\n        scores = AttrCvt(op_name=\"expand_dims\", extras={\"axis\": -1, \"num_newaxis\": 1})([scores], {})\n        data = _op.concatenate([scores, boxes], -1)\n        data = _op.expand_dims(data, 0, 1)\n\n        # Perform Non-Maximum Suppression,\n        # PyTorch NMS doesn't have parameter top_k and max_output_size\n        score_index = 0\n        top_k = max_out_size = -1\n        nms_ret = get_relay_op(\"non_max_suppression\")(\n            data=data,\n            valid_count=num_boxes,\n            indices=indices,\n            max_output_size=max_out_size,\n            iou_threshold=iou_threshold,\n            force_suppress=True,\n            top_k=top_k,\n            coord_start=1,\n            score_index=score_index,\n            id_index=-1,\n            return_indices=True,\n            invalid_to_bottom=False,\n        )\n\n        # squeeze the two outputs of nms for strided_slice\n        size = get_relay_op(\"squeeze\")(nms_ret[1], axis=[1])\n        data_slice = get_relay_op(\"squeeze\")(nms_ret[0], axis=[0])\n\n        # strided slice to get the dynamic result\n        ret = get_relay_op(\"strided_slice\")(\n            data_slice, begin=_expr.const([0]), end=size, slice_mode=\"size\"\n        )\n        # in torchvision, indices from nms are int64\n        return _op.cast(ret, \"int64\")\n\n    def logsumexp(self, inputs, input_types):\n        data = self.pytorch_promote_types(inputs[:1], input_types[:1])\n        dim_list = inputs[1]\n        keepdim = inputs[2] if len(inputs) > 2 else False\n        # dim is output of prim::ListConstruct, even if it is int in python code\n        assert isinstance(dim_list, list), \"dim is expected to be a list\"\n        return _op.logsumexp(data[0], axis=dim_list, keepdims=keepdim)\n\n    def roi_align(self, inputs, input_types):\n        data = inputs[0]\n        boxes = inputs[1]\n\n        output_size = (inputs[3], inputs[4])\n        spatial_scale = inputs[2]\n        sample_ratio = inputs[5]\n        aligned = False if len(inputs) < 7 else inputs[6]\n\n        if aligned:\n            boxes -= _expr.const(0.5 / spatial_scale)\n\n        return _op.vision.roi_align(data, boxes, output_size, spatial_scale, sample_ratio)\n\n    def deform_conv2d(self, inputs, input_types):\n        data = inputs[0]\n        weight = inputs[1]\n        offset = inputs[2]\n\n        if len(inputs) > 12:\n            strides_offset = 5\n            bias = inputs[4]\n            logger.warning(\"mask argument in deformable conv2d is not supported and ignored\")\n        else:\n            strides_offset = 4\n            bias = inputs[3]\n\n        strides = (inputs[strides_offset], inputs[strides_offset + 1])\n        padding = (inputs[strides_offset + 2], inputs[strides_offset + 3])\n        dilation = (inputs[strides_offset + 4], inputs[strides_offset + 5])\n        groups = inputs[strides_offset + 6]\n        deformable_groups = inputs[strides_offset + 7]\n        weight_shape = self.infer_shape(weight)\n        output_channels = weight_shape[0]\n        kernel_size = (weight_shape[2], weight_shape[3])\n\n        conv_out = _op.nn.deformable_conv2d(\n            data,\n            offset,\n            weight,\n            strides,\n            padding,\n            dilation,\n            deformable_groups,\n            groups,\n            output_channels,\n            kernel_size,\n        )\n\n        return _op.nn.bias_add(conv_out, bias)\n\n    def stft(self, inputs, input_types):\n        data = inputs[0]\n        n_fft = inputs[1]\n        hop_length = inputs[2]\n        win_length = inputs[3]\n        window = inputs[4]\n        normalized = inputs[5]\n        onesided = inputs[6]\n\n        return _op.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n\n    def unbind(self, inputs, input_types):\n        data = inputs[0]\n        axis = int(inputs[1])\n        return unbind(data, axis)\n\n    def shape_as_tensor(self, inputs, input_types):\n        is_symbolic_shape = False\n        input_shape = self.infer_shape(inputs[0], self.prelude.mod)\n        for axis in input_shape:\n            if not isinstance(axis, (int, tvm.tir.IntImm)):\n                is_symbolic_shape = True\n                break\n\n        if is_symbolic_shape:\n            ret = _op.shape_of(inputs[0], dtype=\"int64\")\n        else:\n            ret = _expr.const(np.array(input_shape), dtype=\"int64\")\n\n        return ret\n\n    def logical_and(self, inputs, input_types):\n        lhs = _op.cast(inputs[0], \"bool\")\n        rhs = _op.cast(inputs[1], \"bool\")\n\n        return _op.logical_and(lhs, rhs)\n\n    def nonzero(self, inputs, input_types, is_numpy_style=False):\n        data = inputs[0]\n        ret = _op.transform.argwhere(data)\n        if is_numpy_style or (len(inputs) > 1 and inputs[1]):\n            return unbind(ret, 1)\n        return ret\n\n    def nonzero_numpy(self, inputs, input_types):\n        return self.nonzero(inputs, input_types, is_numpy_style=False)\n\n    def scatter(self, inputs, input_types):\n        data = inputs[0]\n        axis = int(inputs[1])\n        index = inputs[2]\n        src = inputs[3]\n        return _op.transform.scatter(data, index, src, axis)\n\n    def index_put(self, inputs, input_types):\n        in_tensor = inputs[0]\n        indices = inputs[1]\n        values = inputs[2]\n        accumulate = inputs[3]\n        if not accumulate:\n            mode = \"update\"\n        else:\n            mode = \"add\"\n        # Combine array of index tensors into one index tensor with shape (N,_)\n        index_tensor = _op.stack(indices, axis=0)\n        return _op.transform.scatter_nd(in_tensor, index_tensor, values, mode)\n\n    def scalar_tensor(self, inputs, input_types):\n        data = inputs[0]\n        cast_map = {\n            6: \"float32\",\n            7: \"float64\",\n            3: \"int32\",\n            4: \"int64\",\n        }\n        type_key = inputs[1]\n        if isinstance(data, _expr.Constant):\n            data = data.data.numpy().tolist()\n        return _expr.const(data, cast_map[type_key])\n\n    def interpolate(self, inputs, input_types):\n        if isinstance(inputs[1], _expr.Expr):\n            out_size = inputs[1]\n        elif isinstance(inputs[1], list):\n            out_size = []\n            for i in [0, 1]:\n                size, _ = try_infer_value(\n                    inputs[1][i],\n                    lambda ret: ret.astype(np.int),\n                    lambda: _op.expand_dims(inputs[1][i], axis=0),\n                )\n                out_size.append(size)\n            out_size = _op.concatenate(out_size, axis=0)\n\n        data = inputs[0]\n        align_corners = inputs[4]\n        method = inputs[3]\n        if method.startswith(\"nearest\"):\n            method = \"nearest_neighbor\"\n        elif method[0:2] == \"bi\":\n            method = method[2:]\n\n        if method == \"nearest_neighbor\":\n            coord_trans = \"asymmetric\"\n        elif align_corners:\n            coord_trans = \"align_corners\"\n        else:\n            coord_trans = \"half_pixel\"\n\n        return _op.image.resize2d(\n            data, out_size, None, \"NCHW\", method, coord_trans, cubic_alpha=-0.75\n        )\n\n    def numel(self, inputs, input_types):\n        return _op.ndarray_size(inputs[0])\n\n    def empty(self, inputs, input_types):\n        shape = inputs[0]\n        return _op.zeros(shape, _convert_dtype_value(inputs[1]))\n\n    def empty_like(self, inputs, input_types):\n        shape = self.infer_shape(inputs[0])\n        if inputs[1] is not None:\n            dtype = _convert_dtype_value(inputs[1])\n        else:\n            dtype = input_types[0]\n        return _op.zeros(shape, dtype)\n\n    def new_empty(self, inputs, input_types):\n        size = inputs[1]\n\n        import torch\n\n        if not isinstance(size, (_expr.Expr, list, tuple, torch.Size, np.ndarray)):\n            msg = \"Data type %s could not be parsed in empty op\" % (type(size))\n            raise AssertionError(msg)\n\n        if inputs[2] is not None:\n            dtype = _convert_dtype_value(inputs[2])\n        else:\n            dtype = input_types[0]\n        return _op.zeros(size, dtype)\n\n    def randn(self, inputs, input_types):\n        import time  # use current time as seed\n\n        shape = inputs[0]\n        output = _op.random.normal(_op.random.threefry_key(int(time.time())), shape)\n        _, values = _expr.TupleWrapper(output, 2)\n        return values\n\n    def bincount(self, inputs, input_types):\n        data = inputs[0]\n        weights = inputs[1]\n        input_type = self.infer_type(data).dtype\n        if input_type == \"int64\":\n            logger.warning(\n                \"Casting an int64 input to int32, since we do not have int64 atomic add\"\n                \"needed for bincount yet.\"\n            )\n            data = _op.cast(data, \"int32\")\n        maximum = _op.max(data)\n        dim = maximum + _expr.const(1, dtype=\"int32\")\n        if weights:\n            weight_type = self.infer_type(weights)\n            out_dtype = weight_type.dtype\n            updates = weights\n        else:\n            out_dtype = \"int32\"\n            updates = _op.ones_like(data)\n\n        counts = _op.zeros(_op.reshape(dim, [1]), out_dtype)\n        out = _op.scatter_add(counts, data, updates, axis=0)\n        if input_type == \"int32\":\n            # Torch always outputs int64 results for bincount\n            return _op.cast(out, \"int64\")\n        return out\n\n    def scatter_add(self, inputs, input_types):\n        data = inputs[0]\n        axis = inputs[1]\n        index = inputs[2]\n        src = inputs[3]\n        return _op.scatter_add(data, index, src, axis=axis)\n\n    def cumsum(self, inputs, input_types):\n        data = inputs[0]\n        dim = inputs[1]\n        dtype = inputs[2]\n\n        if inputs[2] is not None:\n            dtype = _convert_dtype_value(inputs[2])\n\n        return _op.cumsum(data, axis=dim, dtype=dtype)\n\n    def masked_fill(self, inputs, input_types):\n        mask = inputs[1]\n        value = _op.cast(_wrap_const(inputs[2]), input_types[0])\n        return _op.where(mask, value, inputs[0])\n\n    def masked_select(self, inputs, input_types):\n        mask = inputs[1]\n        indices = self.nonzero([mask], input_types, is_numpy_style=True)\n        return _op.adv_index([inputs[0]] + [indices[i] for i in range(indices.size)])\n\n    def sort(self, inputs, input_types):\n        data = inputs[0]\n        dim = inputs[1]\n        is_descending = inputs[2]\n        # pytorch sort returns both sorted indices and values\n        indices = _op.argsort(data, dim, not is_descending)\n        return _op.gather(data, dim, indices), indices\n\n    def argsort(self, inputs, input_types):\n        data = inputs[0]\n        dim = inputs[1]\n        is_descending = inputs[2]\n        return _op.argsort(data, dim, not is_descending)\n\n    def is_floating_point(self, inputs, input_types):\n        assert len(inputs) == 1\n\n        if isinstance(inputs[0], _expr.Expr):\n            input_type = self.infer_type(inputs[0]).dtype\n        else:\n            input_type = input_types[0]\n\n        is_float = input_type in [\"float32\", \"float64\", \"float16\", \"bfloat16\"]\n        return _expr.const(is_float)\n\n    def unique(self, inputs, input_types):\n        assert len(inputs) == 4\n        [data, is_sorted, return_inverse, return_counts] = inputs\n        if not is_sorted:\n            logger.warning(\"TVM always assumes sorted=True for torch.unique\")\n            is_sorted = True\n        if return_counts:\n            [unique, indices, inverse_indices, num_uniq, counts] = _op.unique(\n                data, is_sorted=is_sorted, return_counts=True\n            )\n            unique_sliced = _op.strided_slice(unique, begin=[0], end=num_uniq, slice_mode=\"size\")\n            counts_sliced = _op.strided_slice(counts, begin=[0], end=num_uniq, slice_mode=\"size\")\n            return (unique_sliced, inverse_indices, counts_sliced)\n        else:\n            [unique, indices, inverse_indices, num_uniq] = _op.unique(\n                data, is_sorted=is_sorted, return_counts=False\n            )\n            unique_sliced = _op.strided_slice(unique, begin=[0], end=num_uniq, slice_mode=\"size\")\n            return (unique_sliced, inverse_indices)\n\n    def nll_loss(self, inputs, input_types):\n        assert len(inputs) == 5\n        [predictions, targets, weights, reduction, ignore_index] = inputs\n        num_class = self.infer_shape(predictions)[1]\n        if reduction == 0:\n            reduction = \"none\"\n        elif reduction == 1:\n            reduction = \"mean\"\n        else:\n            reduction = \"sum\"\n        if weights is None:\n            weights = _op.full(_expr.const(1), (num_class,), dtype=input_types[0])\n        return _op.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)\n\n    def flip(self, inputs, input_types):\n        data = inputs[0]\n        axis = inputs[1]\n        return _op.transform.reverse(data, axis=axis[0])\n\n    def bidir_rnn_cell(self, input_seqs, weights_dicts, act=_op.tanh):\n        \"\"\"\n        Bidirectional RNN cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t = rnn_cell(input_seqs, **weights_dicts[0], backwards=False, act=act)\n\n        reverse_outputs, rev_H_t = rnn_cell(input_seqs, **weights_dicts[1], backwards=True, act=act)\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.concatenate([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=-1)\n            )\n\n        return final_outputs, _op.stack([fw_H_t, rev_H_t], axis=0)\n\n    def rnn_layers(self, input_data, layer_weights_dicts, bidirectional, act, dropout_p=0.0):\n        \"\"\"\n        Methods iterates layers for Stacked RNN\n        \"\"\"\n        layers_num = len(layer_weights_dicts)\n        # split input sequence to samples set\n        input_seqs = unbind(input_data, 0)  # [seq_num, (batch, feature_size)]\n        output_hiddens = []\n        for i in range(layers_num):\n            weights_dicts = layer_weights_dicts[i]\n            # input_seqs shape = [seq_num, (batch, feature_size)] or\n            # [seq_num, (batch, 2*feature_size)] for bidirectional\n            if bidirectional:\n                input_seqs, H_t = self.bidir_rnn_cell(input_seqs, weights_dicts, act=act)\n            else:\n                input_seqs, H_t = rnn_cell(input_seqs, **weights_dicts[0], act=act)\n\n            output_hiddens.append(H_t)\n\n            # TODO (yuanfz98): in pytorch implementation train is also checked\n            # see https://github.com/pytorch/pytorch/blob/70c8daf43946b53af6493d058899ef952d27d339\n            # /aten/src/ATen/native/RNN.cpp#L1054\n            if dropout_p != 0 and i < layers_num - 1:\n                # for input in input_seqs:\n                #     input = _op.dropout(input, dropout_p)\n                raise NotImplementedError(\"Dropout for GRU has not been supported yet!\")\n        output_hiddens = (\n            _op.concatenate(output_hiddens, 0) if bidirectional else _op.stack(output_hiddens, 0)\n        )\n        return _op.stack(input_seqs, 0), output_hiddens\n\n    def rnn(self, inputs, input_types, nonlinearity):\n        \"\"\"\n        Description of RNN in pytorch:\n        https://pytorch.org/docs/stable/generated/torch.nn.RNN.html#torch.nn.RNN\n        Description of inputs:\n        https://github.com/pytorch/pytorch/blob/736fb7d22cc948b739db2c35aeb5ad4d19aea4f4/torch/overrides.py#L937\n        \"\"\"\n        # TODO (yuanfz98): support dropout\n        assert len(inputs) == 9, \"Input of size 9 is expected\"\n        # Unpack inputs, note that if optional and not provided then value will be None.\n        _X = inputs[0]\n        # _X shape (seq_num, batch, feature_size) or (batch, seq_num, feature_size)\n\n        hidden_state = inputs[1]\n        # Hidden state shape (hidden_layers_num, batch, hidden_size)\n\n        _weights = inputs[2]\n        # Wi layer[0] shape (hidden_size, feature_size)\n        # Wh layer[0] shape (hidden_size, hidden_size)\n        # Bi layer[0] shape (hidden_size)\n        # Bh layer[0] shape (hidden_size)\n\n        # Wi layer[>0] shape (hidden_size, hidden_size * num_directions)\n        # Wh layer[>0] shape (hidden_size, hidden_size)\n        # Bi layer[>0] shape (hidden_size)\n        # Bh layer[>0] shape (hidden_size)\n\n        # Scalar inputs\n        has_biases = inputs[3]\n        num_layers = inputs[4]\n        dropout_p = inputs[5]  # dropout probability, if 0.0 it means there is no dropout\n        # train = inputs[6]\n        bidirectional = inputs[7]\n        batch_first = inputs[8]\n\n        num_directions = 1\n        if bidirectional:\n            num_directions = 2\n\n        rsd = len(_weights) % num_layers\n        assert rsd == 0, \"The number of weights must be a multiple of the number of layers!\"\n        rsd = (len(_weights) / num_layers) % num_directions\n        assert (\n            rsd == 0\n        ), \"The number of weights in layer must be a multiple of the number of directions!\"\n\n        weights_num = int(len(_weights) / num_layers / num_directions)\n        if has_biases:\n            assert weights_num == 4, \"The weights number in layer is expected equal to 4\"\n        else:\n            assert weights_num == 2, \"The weights number in layer is expected equal to 2\"\n        if nonlinearity == \"tanh\":\n            act = _op.tanh\n        elif nonlinearity == \"relu\":\n            act = _op.nn.relu\n        assert act, \"The nonlinearity is unknown\"\n        X = (\n            _op.transpose(_X, (1, 0, 2)) if batch_first else _X\n        )  # always (seq_num, batch, feature_size)\n        # TODO (yuanfz98): Which data type should be used? from input or weights?\n        # Instead of it _infer_type(X).checked_type.dtype can be used\n        X_dtype = input_types[0]\n        X_shape = _infer_shape(X)  # (seq_num, batch, feature_size)\n\n        hidden_size = int(_infer_shape(_weights[0])[0])\n        batch_size = X_shape[1]\n\n        # Initialize hidden states if not provided.\n        layers_h = []\n        hidden_layers_num = num_directions * num_layers\n        if hidden_state is None:\n            h_0 = _op.zeros((batch_size, hidden_size), X_dtype)\n            for i in range(hidden_layers_num):\n                layers_h.append(h_0)\n        else:\n            layers_h = unbind(hidden_state, 0)\n\n        layer_weights_dicts = []\n        k = 0  # layer counter\n        if has_biases:\n            names = [\"hidden_state\", \"w_inp\", \"w_hid\", \"b_inp\", \"b_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of RNN weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], *_weights[j : j + 4]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of GRU weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        else:\n            names = [\"hidden_state\", \"w_inp\", \"w_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of RNN weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], *_weights[j : j + 2]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of RNN weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        assert (\n            len(layer_weights_dicts) == num_layers and k == num_layers\n        ), \"For stacked RNN number of weights sets should be the same as number of layers!\"\n        output, out_hidden_state = self.rnn_layers(\n            X,\n            layer_weights_dicts,\n            bidirectional,\n            act,\n            dropout_p=dropout_p,\n        )\n\n        # output shape = (seq_num, batch, hidden_size) or\n        # (seq_num, batch, 2*feature_size) for bidirectional\n        if batch_first:\n            output = _op.transpose(output, (1, 0, 2))\n\n        return (output, out_hidden_state)\n\n    def bidir_gru_cell(\n        self,\n        input_seqs,\n        weights_dicts,\n    ):\n        \"\"\"\n        Bidirectional GRU cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t = gru_cell(\n            input_seqs,\n            **weights_dicts[0],\n        )\n\n        reverse_outputs, rev_H_t = gru_cell(\n            input_seqs,\n            **weights_dicts[1],\n            backwards=True,\n        )\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.concatenate([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=-1)\n            )\n\n        return final_outputs, _op.stack([fw_H_t, rev_H_t], axis=0)\n\n    def gru_layers(self, input_data, layer_weights_dicts, bidirectional, dropout_p=0.0):\n        \"\"\"\n        Methods iterates layers for Stacked GRU\n        \"\"\"\n        layers_num = len(layer_weights_dicts)\n        # split input sequence to samples set\n        input_seqs = unbind(input_data, 0)  # [seq_num, (batch, feature_size)]\n        output_hiddens = []\n        for i in range(layers_num):\n            weights_dicts = layer_weights_dicts[i]\n            # input_seqs shape = [seq_num, (batch, feature_size)] or\n            # [seq_num, (batch, 2*feature_size)] for bidirectional\n            if bidirectional:\n                input_seqs, H_t = self.bidir_gru_cell(input_seqs, weights_dicts)\n            else:\n                input_seqs, H_t = gru_cell(input_seqs, **weights_dicts[0])\n\n            output_hiddens.append(H_t)\n\n            # TODO (vvchernov): in pytorch implementation train is also checked\n            # see https://github.com/pytorch/pytorch/blob/70c8daf43946b53af6493d058899ef952d27d339\n            # /aten/src/ATen/native/RNN.cpp#L1054\n            if dropout_p != 0 and i < layers_num - 1:\n                # for input in input_seqs:\n                #     input = _op.dropout(input, dropout_p)\n                raise NotImplementedError(\"Dropout for GRU has not been supported yet!\")\n\n        return _op.stack(input_seqs, 0), _op.stack(output_hiddens, 0)\n\n    def gru(self, inputs, input_types):\n        \"\"\"\n        Description of GRU in pytorch:\n        https://pytorch.org/docs/stable/generated/torch.nn.GRU.html?highlight=gru#torch.nn.GRU\n        \"\"\"\n        # TODO (vvchernov): support dropout\n        assert len(inputs) == 9, \"Input of size 9 is expected\"\n        # Unpack inputs, note that if optional and not provided then value will be None.\n        _X = inputs[0]\n        # _X shape (seq_num, batch, feature_size) or (batch, seq_num, feature_size)\n\n        hidden_state = inputs[1]\n        # Hidden state shape (hidden_layers_num, batch, hidden_size)\n\n        _weights = inputs[2]\n        # Wi layer[0] shape (3 * hidden_size, feature_size)\n        # Wh layer[0] shape (3 * hidden_size, hidden_size)\n        # Bi layer[0] shape (3 * hidden_size)\n        # Bh layer[0] shape (3 * hidden_size)\n\n        # Wi layer[>0] shape (3 * hidden_size, hidden_size * num_directions)\n        # Wh layer[>0] shape (3 * hidden_size, hidden_size)\n        # Bi layer[>0] shape (3 * hidden_size)\n        # Bh layer[>0] shape (3 * hidden_size)\n\n        # Scalar inputs\n        has_biases = inputs[3]\n        num_layers = inputs[4]\n        dropout_p = inputs[5]  # dropout probability, if 0.0 it means there is no dropout\n        # train = inputs[6]\n        bidirectional = inputs[7]\n        batch_first = inputs[8]\n\n        num_directions = 1\n        if bidirectional:\n            num_directions = 2\n\n        rsd = len(_weights) % num_layers\n        assert rsd == 0, \"The number of weights must be a multiple of the number of layers!\"\n        rsd = (len(_weights) / num_layers) % num_directions\n        assert (\n            rsd == 0\n        ), \"The number of weights in layer must be a multiple of the number of directions!\"\n\n        weights_num = int(len(_weights) / num_layers / num_directions)\n        if has_biases:\n            assert weights_num == 4, \"The weights number in layer is expected equal to 4\"\n        else:\n            assert weights_num == 2, \"The weights number in layer is expected equal to 2\"\n\n        X = _op.transpose(_X, (1, 0, 2)) if batch_first else _X\n        # TODO (vvchernov): Which data type should be used? from input or weights?\n        # Instead of it _infer_type(X).checked_type.dtype can be used\n        X_dtype = input_types[0]\n        X_shape = _infer_shape(X)  # (seq_num, batch, feature_size)\n\n        hidden_size = int(_infer_shape(_weights[0])[0] / 3)\n        batch_size = X_shape[1]\n\n        # Initialize hidden states if not provided.\n        layers_h = []\n        hidden_layers_num = num_directions * num_layers\n        if hidden_state is None:\n            h_0 = _op.zeros((batch_size, hidden_size), X_dtype)\n            for i in range(hidden_layers_num):\n                layers_h.append(h_0)\n        else:\n            layers_h = unbind(hidden_state, 0)\n\n        layer_weights_dicts = []\n        k = 0  # layer counter\n        if has_biases:\n            names = [\"hidden_state\", \"w_inp\", \"w_hid\", \"b_inp\", \"b_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of GRU weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], *_weights[j : j + 4]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of GRU weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        else:\n            names = [\"hidden_state\", \"w_inp\", \"w_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of GRU weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], *_weights[j : j + 2]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of GRU weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        assert (\n            len(layer_weights_dicts) == num_layers and k == num_layers\n        ), \"For stacked GRU number of weights sets should be the same as number of layers!\"\n\n        output, out_hidden_state = self.gru_layers(\n            X,\n            layer_weights_dicts,\n            bidirectional,\n            dropout_p=dropout_p,\n        )\n\n        # output shape = (seq_num, batch, hidden_size) or\n        # (seq_num, batch, 2*feature_size) for bidirectional\n        if batch_first:\n            output = _op.transpose(output, (1, 0, 2))\n\n        return (output, out_hidden_state)\n\n    def bidir_lstm_cell(\n        self,\n        input_seqs,\n        weights_dicts,\n    ):\n        \"\"\"\n        Bidirectional LSTM cell\n        \"\"\"\n        seq_len = len(input_seqs)\n        forward_outputs, fw_H_t, fw_C_t = lstm_cell(\n            input_seqs,\n            **weights_dicts[0],\n        )\n\n        reverse_outputs, rev_H_t, rev_C_t = lstm_cell(\n            input_seqs,\n            **weights_dicts[1],\n            backwards=True,\n        )\n\n        final_outputs = []\n        for i in range(seq_len):\n            final_outputs.append(\n                _op.concatenate([forward_outputs[i], reverse_outputs[seq_len - 1 - i]], axis=-1)\n            )\n\n        return final_outputs, (fw_H_t, fw_C_t), (rev_H_t, rev_C_t)\n\n    def lstm_layers(self, input_data, layer_weights_dicts, bidirectional, dtype, dropout_p=0.0):\n        \"\"\"\n        Methods iterates layers for Stacked LSTM\n        \"\"\"\n        layers_num = len(layer_weights_dicts)\n        # split input sequence to samples set\n        input_seqs = unbind(input_data, 0)  # [seq_num, (batch, feature_size)]\n        output_hiddens = []\n        for i in range(layers_num):\n            weights_dicts = layer_weights_dicts[i]\n            # input_seqs shape = [seq_num, (batch, feature_size)] or\n            # [seq_num, (batch, 2*feature_size)] for bidirectional\n            if bidirectional:\n                input_seqs, H_t, C_t = self.bidir_lstm_cell(input_seqs, weights_dicts)\n            else:\n                input_seqs, H_t, C_t = lstm_cell(input_seqs, **weights_dicts[0])\n\n            output_hiddens.append((H_t, C_t))\n\n            # TODO (vvchernov): in pytorch implementation train is also checked\n            # see https://github.com/pytorch/pytorch/blob/70c8daf43946b53af6493d058899ef952d27d339\n            # /aten/src/ATen/native/RNN.cpp#L1054\n            if dropout_p != 0 and i < layers_num - 1:\n                # for input in input_seqs:\n                #     input = _op.dropout(input, dropout_p)\n                raise NotImplementedError(\"Dropout for LSTM has not been supported yet!\")\n        final_hiddens = []\n        if bidirectional:\n            for output_hidden in output_hiddens:\n                final_hiddens.append(output_hidden[0])\n                final_hiddens.append(output_hidden[1])\n        else:\n            final_hiddens = output_hiddens\n\n        return _op.stack(input_seqs, 0), final_hiddens\n\n    def lstm(self, inputs, input_types):\n        \"\"\"\n        Description of LSTM in pytorch:https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html\n        Native implementation for torch version less than 1.8.0 (projection is unsupported):\n        https://github.com/pytorch/pytorch/blob/70c8daf43946b53af6493d058899ef952d27d339/aten/ \\\n        src/ATen/native/RNN.cpp#L1396\n        Native implementation for torch version from 1.8.0 and higher (projection is supported):\n        https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/RNN.cpp#L1483\n        \"\"\"\n        # TODO (vvchernov): support dropout\n        assert len(inputs) == 9, \"Input of size 9 is expected\"\n        # Unpack inputs, note that if optional and not provided then value will be None.\n        _X = inputs[0]\n        # _X shape (seq_num, batch, feature_size) or (batch, seq_num, feature_size)\n\n        hidden_states = inputs[1]\n        assert len(hidden_states) == 2, \"lstm expects two hidden states\"\n        h_0 = hidden_states[0]\n        c_0 = hidden_states[1]\n        # H0 shape (hidden_layers_num, batch, proj_size) if projection\n        # else (hidden_layers_num, batch, hidden_size)\n        # C0 shape (hidden_layers_num, batch, hidden_size)\n\n        _weights = inputs[2]\n        # If no projection\n        # Wi layer[0] shape (4 * hidden_size, feature_size)\n        # Wh layer[0] shape (4 * hidden_size, hidden_size)\n        # Bi layer[0] shape (4 * hidden_size)\n        # Bh layer[0] shape (4 * hidden_size)\n\n        # Wi layer[>0] shape (4 * hidden_size, hidden_size * num_directions)\n        # Wh layer[>0] shape (4 * hidden_size, hidden_size)\n        # Bi layer[>0] shape (4 * hidden_size)\n        # Bh layer[>0] shape (4 * hidden_size)\n\n        # If projection\n        # Wi layer[0] shape (4 * hidden_size, feature_size)\n        # Wh layer[0] shape (4 * hidden_size, proj_size)\n        # Bi layer[0] shape (4 * hidden_size)\n        # Bh layer[0] shape (4 * hidden_size)\n        # P  layer[0] shape (proj_size, hidden_size)\n\n        # Wi layer[>0] shape (4 * hidden_size, proj_size * num_directions)\n        # Wh layer[>0] shape (4 * hidden_size, proj_size)\n        # Bi layer[>0] shape (4 * hidden_size)\n        # Bh layer[>0] shape (4 * hidden_size)\n        # P  layer[>0] shape (proj_size, hidden_size)\n\n        # Scalar inputs\n        has_biases = inputs[3]\n        num_layers = inputs[4]\n        dropout_p = inputs[5]  # dropout probability, if 0.0 it means there is no dropout\n        # train = inputs[6]\n        bidirectional = inputs[7]\n        batch_first = inputs[8]\n\n        num_directions = 1\n        if bidirectional:\n            num_directions = 2\n\n        rsd = len(_weights) % num_layers\n        assert rsd == 0, \"The number of weights must be a multiple of the number of layers!\"\n        rsd = (len(_weights) / num_layers) % num_directions\n        assert (\n            rsd == 0\n        ), \"The number of weights in layer must be a multiple of the number of directions!\"\n        has_proj = False\n        proj_size = 0\n        weights_num = int(len(_weights) / num_layers / num_directions)\n        if has_biases:\n            if weights_num == 5:\n                has_proj = True\n                proj_size = _infer_shape(_weights[4])[0]\n            else:\n                assert weights_num == 4, \"The weights number in layer is expected equal to 4\"\n        else:\n            if weights_num == 3:\n                has_proj = True\n                proj_size = _infer_shape(_weights[2])[0]\n            else:\n                assert weights_num == 2, \"The weights number in layer is expected equal to 2\"\n\n        X = _op.transpose(_X, (1, 0, 2)) if batch_first else _X\n        # TODO (vvchernov): Which data type should be used? from input or weights?\n        # Instead of it _infer_type(X).checked_type.dtype can be used\n        X_dtype = input_types[0]\n        X_shape = _infer_shape(X)  # (seq_num, batch, feature_size)\n\n        hidden_size = _infer_shape(_weights[0])[0] / 4\n        batch_size = X_shape[1]\n\n        # Initialize hidden states if not provided.\n        layers_h = []\n        layers_c = []\n        hidden_layers_num = num_directions * num_layers\n        if h_0 is None:\n            if has_proj:\n                h_0 = _op.zeros((batch_size, proj_size), X_dtype)\n            else:\n                h_0 = _op.zeros((batch_size, hidden_size), X_dtype)\n            for i in range(hidden_layers_num):\n                layers_h.append(h_0)\n        else:\n            layers_h = unbind(h_0, 0)\n        if c_0 is None:\n            c_0 = _op.zeros((batch_size, hidden_size), X_dtype)\n            for i in range(hidden_layers_num):\n                layers_c.append(c_0)\n        else:\n            layers_c = unbind(c_0, 0)\n\n        layer_weights_dicts = []\n        k = 0  # layer counter\n        if has_biases:\n            names = [\"hidden_state\", \"cell_state\", \"w_inp\", \"w_hid\", \"b_inp\", \"b_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of LSTM weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], layers_c[2 * k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    if has_proj:\n                        fw_weights_dict[\"proj\"] = _weights[i + 4]\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], layers_c[2 * k + 1], *_weights[j : j + 4]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    if has_proj:\n                        rev_weights_dict[\"proj\"] = _weights[j + 4]\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of LSTM weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], layers_c[k], *_weights[i : i + 4]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    if has_proj:\n                        fw_weights_dict[\"proj\"] = _weights[i + 4]\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        else:\n            names = [\"hidden_state\", \"cell_state\", \"w_inp\", \"w_hid\"]\n            if bidirectional:\n                rsd = len(_weights) % (2 * weights_num)\n                assert rsd == 0, \"got an incorrect number of LSTM weights\"\n                for i in range(0, len(_weights), 2 * weights_num):\n                    fw_tensors = [layers_h[2 * k], layers_c[2 * k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    if has_proj:\n                        fw_weights_dict[\"proj\"] = _weights[i + 2]\n                    j = i + weights_num\n                    rev_tensors = [layers_h[2 * k + 1], layers_c[2 * k + 1], *_weights[j : j + 2]]\n                    rev_weights_dict = dict(zip(names, rev_tensors))\n                    if has_proj:\n                        rev_weights_dict[\"proj\"] = _weights[j + 2]\n                    layer_weights_dicts.append([fw_weights_dict, rev_weights_dict])\n                    k += 1\n            else:\n                assert len(_weights) % weights_num == 0, \"got an incorrect number of LSTM weights\"\n                for i in range(0, len(_weights), weights_num):\n                    fw_tensors = [layers_h[k], layers_c[k], *_weights[i : i + 2]]\n                    fw_weights_dict = dict(zip(names, fw_tensors))\n                    if has_proj:\n                        fw_weights_dict[\"proj\"] = _weights[i + 2]\n                    layer_weights_dicts.append([fw_weights_dict])\n                    k += 1\n        assert (\n            len(layer_weights_dicts) == num_layers and k == num_layers\n        ), \"For stacked LSTM number of weights sets should be the same as number of layers!\"\n\n        outputs = self.lstm_layers(\n            X,\n            layer_weights_dicts,\n            bidirectional,\n            dtype=X_dtype,\n            dropout_p=dropout_p,\n        )\n\n        # output shape = (seq_num, batch, hidden_size) or\n        # (seq_num, batch, 2*feature_size) for bidirectional\n        output = outputs[0]\n\n        hy = []\n        cy = []\n        for hidden in outputs[1]:\n            hy.append(hidden[0])\n            cy.append(hidden[1])\n\n        if batch_first:\n            output = _op.transpose(output, (1, 0, 2))\n\n        return (output, _op.stack(hy, 0), _op.stack(cy, 0))\n\n    def all_any_common(self, op, inputs, input_types):\n        if len(inputs) >= 2:\n            dim = inputs[1]\n        else:\n            dim = None\n        if len(inputs) >= 3:\n            keepdim = inputs[2]\n        else:\n            keepdim = False\n        if self.infer_type(inputs[0]).dtype != \"bool\":\n            # The input dtype can be uint8.\n            inp = _op.cast(inputs[0], \"bool\")\n        else:\n            inp = inputs[0]\n        return op(inp, axis=dim, keepdims=keepdim)\n\n    def searchsorted_common(\n        self, sorted_sequence, values, out_int32, right, side=None, out=None, sorter=None\n    ):\n        assert side is None and out is None and sorter is None, \"unsupported parameters\"\n        dtype = \"int32\" if out_int32 else \"int64\"\n        values_shape = _infer_shape(values)\n\n        if len(values_shape) == 0:\n            values = _op.expand_dims(values, 0)\n\n        out = _op.searchsorted(sorted_sequence, values, right=right, dtype=dtype)\n\n        if len(values_shape) == 0:\n            return _op.squeeze(out)\n\n        return out\n\n    def searchsorted(self, inputs, input_types):\n        return self.searchsorted_common(*inputs)\n\n    def bucketize(self, inputs, input_types):\n        return self.searchsorted_common(inputs[1], inputs[0], inputs[2], inputs[3])\n\n    def roll(self, inputs, input_types):\n        def slide_axes(inp, shape, ax):\n            axes = list(range(len(shape)))\n            axes = axes[:ax] + [-1] + axes[ax:-1]\n            return _op.transpose(inp, axes)\n\n        x = inputs[0]\n        shifts = inputs[1]\n        dims = inputs[2]\n        shape = self.infer_shape(x)\n        start = _expr.const(0, \"int64\")\n        step = _expr.const(1, \"int64\")\n\n        out = x\n        for i, dim in enumerate(dims):\n            roll_dim = _expr.const(shape[dim], \"int64\")\n            indices_1d = _op.mod(\n                _op.transform.arange(start, roll_dim, step, \"int64\")\n                - _expr.const(shifts[i], \"int64\")\n                + roll_dim,\n                roll_dim,\n            )\n            # First fill in the last axis with roll indices, and then do transpose to\n            # bring the roll indices into the desired axis.\n            indices = slide_axes(\n                _op.tile(indices_1d, shape[:dim] + shape[dim + 1 :] + (1,)),\n                shape,\n                dim,\n            )\n            out = _op.gather(out, dim, indices)\n\n        return out\n\n    def einsum(self, inputs, input_types):\n        equation, data = inputs\n        return _op.einsum(data, equation)\n\n    def dot(self, inputs, _):\n        lhs, rhs = inputs\n        return _op.sum(_op.multiply(lhs, rhs))\n\n    def mv(self, inputs, _):\n        lhs, rhs = inputs\n\n        # Convert the 1D matrix (vector) into a 2D matrix with the extra\n        # dimension=1\n        rhs_matrix = _op.transform.expand_dims(rhs, 0)\n\n        # Run multiplication\n        dense_result = _op.nn.dense(lhs, rhs_matrix, units=None)\n\n        # Chop off the extra result dimension\n        return _op.transform.squeeze(dense_result)\n\n    def grid_sampler(self, inputs, input_types):\n        interpolate_mode = inputs[2]\n        padding_mode = inputs[3]\n        align_corners = inputs[4]\n        data_shape = self.infer_shape_with_prelude(inputs[0])\n\n        if len(data_shape) == 4:\n            layout = \"NCHW\"\n            axes = [0, 3, 1, 2]\n            grid = _op.transform.transpose(inputs[1], axes)\n        elif len(data_shape) == 5:\n            layout = \"NCDHW\"\n            axes = [0, 4, 1, 2, 3]\n            grid = _op.transform.transpose(inputs[1], axes)\n        else:\n            msg = f\"only 4D and 5D are supported.\"\n            raise ValueError(msg)\n\n        if interpolate_mode == 0:\n            interpolate_str = \"bilinear\"\n        elif interpolate_mode == 1:\n            interpolate_str = \"nearest\"\n        elif interpolate_mode == 2:\n            interpolate_str = \"bicubic\"\n        else:\n            msg = f\"interpolation method {interpolate_mode} is not supported\"\n            raise ValueError(msg)\n\n        if padding_mode == 0:\n            padding_mode_str = \"zeros\"\n        elif padding_mode == 1:\n            padding_mode_str = \"border\"\n        elif padding_mode == 2:\n            padding_mode_str = \"reflection\"\n        else:\n            msg = f\"padding_mode {padding_mode} is not supported\"\n            raise ValueError(msg)\n\n        return _op.image.grid_sample(\n            inputs[0], grid, interpolate_str, layout, padding_mode_str, align_corners\n        )\n\n    def trilu(self, inputs, input_types, mode):\n        data = inputs[0]\n        k = inputs[1] if inputs[1] else 0\n        upper = True if mode == \"triu\" else False\n        return _op.trilu(data, k, upper)\n\n    def multinomial(self, inputs, input_types):\n        probs = inputs[0]\n        num_samples = inputs[1]\n        replacement = inputs[2] if inputs[2] else True\n        assert not (\n            replacement is False and num_samples > 1\n        ), \"Multinomial without replacement is not yet supported.\"\n        # Ideally this seed would be generated by a previous threefry operation.\n        # Eventually we might want to add a global store for random keys.\n        seed = np.random.randint(1e6)\n        key = _op.random.threefry_key(seed)\n        output = _op.random.multinomial(key, probs, num_samples)\n        _, indices = _expr.TupleWrapper(output, 2)\n        return indices\n\n    # Operator mappings\n    def create_convert_map(self):\n        self.convert_map = {\n            \"aten::is_floating_point\": self.is_floating_point,\n            \"aten::pixel_shuffle\": self.pixel_shuffle,\n            \"aten::device\": self.none,\n            \"prim::device\": self.none,\n            \"aten::sub\": self.sub,\n            \"aten::max\": self.max,\n            \"aten::min\": self.min,\n            \"aten::maximum\": self.maximum,\n            \"aten::minimum\": self.minimum,\n            \"aten::amax\": self.max,\n            \"aten::amin\": self.min,\n            \"aten::stft\": self.stft,\n            \"aten::mul\": self.make_elemwise(\"multiply\"),\n            \"aten::pow\": self.make_elemwise(\"power\"),\n            \"aten::lerp\": self.lerp,\n            \"aten::arange\": self.arange,\n            \"aten::meshgrid\": self.meshgrid,\n            \"aten::div\": self.make_elemwise(\"divide\"),\n            \"aten::floor_divide\": self.make_elemwise(\"floor_divide\"),\n            \"aten::true_divide\": self.make_elemwise(\"divide\"),\n            \"aten::fmod\": self.make_elemwise(\"trunc_mod\"),\n            \"aten::remainder\": self.make_elemwise(\"floor_mod\"),\n            \"aten::addcdiv\": self.addcdiv,\n            \"aten::addcmul\": self.addcmul,\n            \"aten::ones\": self.ones,\n            \"aten::ones_like\": self.ones_like,\n            \"aten::zeros\": self.zeros,\n            \"aten::zero_\": self.zero_,\n            \"aten::zeros_like\": self.zeros_like,\n            \"aten::new_ones\": self.new_ones,\n            \"aten::full\": self.full,\n            \"aten::full_like\": self.full_like,\n            \"aten::new_full\": self.new_full,\n            \"aten::fill_\": self.fill_,\n            \"aten::linspace\": self.linspace,\n            \"aten::reciprocal\": self.reciprocal,\n            \"aten::repeat\": self.repeat,\n            \"aten::repeat_interleave\": self.repeat_interleave,\n            \"aten::to\": self.to,\n            \"aten::squeeze\": self.squeeze,\n            \"aten::unsqueeze\": self.unsqueeze,\n            \"aten::cat\": self.concatenate,\n            \"aten::slice\": self.slice,\n            \"aten::narrow\": self.narrow,\n            \"aten::split\": self.split,\n            \"aten::tensor_split\": self.tensor_split,\n            \"aten::split_with_sizes\": self.split_with_sizes,\n            \"aten::select\": self.select,\n            \"aten::take\": self.take,\n            \"aten::where\": self.where,\n            \"aten::topk\": self.topk,\n            \"aten::relu\": self.relu,\n            \"aten::relu6\": self.relu6,\n            \"aten::prelu\": self.prelu,\n            \"aten::leaky_relu\": self.leaky_relu,\n            \"aten::elu\": self.elu,\n            \"aten::celu\": self.celu,\n            \"aten::gelu\": self.gelu,\n            \"aten::selu\": self.selu,\n            \"aten::silu\": self.silu,\n            \"aten::glu\": self.glu,\n            \"aten::log_sigmoid\": self.log_sigmoid,\n            \"aten::adaptive_avg_pool1d\": functools.partial(\n                self.adaptive_avg_pool, _op.nn.adaptive_avg_pool1d\n            ),\n            \"aten::adaptive_avg_pool2d\": functools.partial(\n                self.adaptive_avg_pool, _op.nn.adaptive_avg_pool2d\n            ),\n            \"aten::adaptive_avg_pool3d\": functools.partial(\n                self.adaptive_avg_pool, _op.nn.adaptive_avg_pool3d\n            ),\n            \"aten::adaptive_max_pool1d\": functools.partial(\n                self.adaptive_max_pool, _op.nn.adaptive_max_pool1d\n            ),\n            \"aten::adaptive_max_pool2d\": functools.partial(\n                self.adaptive_max_pool, _op.nn.adaptive_max_pool2d\n            ),\n            \"aten::adaptive_max_pool3d\": functools.partial(\n                self.adaptive_max_pool, _op.nn.adaptive_max_pool3d\n            ),\n            \"aten::max_pool2d\": self.maxpool_2d,\n            \"aten::max_pool2d_with_indices\": self.maxpool_2d_with_indices,\n            \"aten::max_pool1d\": self.maxpool_1d,\n            \"aten::max_pool3d\": self.maxpool_3d,\n            \"aten::hardtanh\": self.hardtanh,\n            \"aten::_convolution\": self.convolution,\n            \"aten::softmax\": self.softmax,\n            \"aten::threshold\": self.threshold,\n            \"aten::contiguous\": self.contiguous,\n            \"aten::batch_norm\": self.batch_norm,\n            \"aten::instance_norm\": self.instance_norm,\n            \"aten::layer_norm\": self.layer_norm,\n            \"aten::group_norm\": self.group_norm,\n            \"aten::transpose\": self.transpose,\n            \"aten::t\": self.transpose,\n            \"aten::numpy_T\": self.numpy_T,\n            \"aten::flatten\": self.flatten,\n            \"aten::addmm\": self.addmm,\n            \"aten::size\": self.size,\n            \"aten::view\": self.view,\n            \"aten::reshape\": self.reshape,\n            \"aten::reshape_as\": self.reshape_as,\n            \"aten::clone\": self.clone,\n            \"aten::log_softmax\": self.log_softmax,\n            \"aten::sigmoid\": self.sigmoid,\n            \"aten::softplus\": self.softplus,\n            \"aten::avg_pool1d\": self.make_avg_pool(1),\n            \"aten::avg_pool2d\": self.make_avg_pool(2),\n            \"aten::avg_pool3d\": self.make_avg_pool(3),\n            \"aten::linear\": self.linear,\n            \"aten::dropout\": self.dropout,\n            \"aten::feature_dropout\": self.dropout,\n            \"aten::alpha_dropout\": self.dropout,\n            \"aten::mean\": self.mean,\n            \"aten::chunk\": self.chunk,\n            \"aten::unsafe_chunk\": self.chunk,\n            \"aten::matmul\": self.matmul,\n            \"aten::bmm\": self.matmul,\n            \"aten::expand\": self.expand,\n            \"aten::Int\": self.int,\n            \"prim::NumToTensor\": self.numtotensor,\n            \"prim::ImplicitTensorToNum\": self.tensortonum,\n            \"aten::ScalarImplicit\": self.tensortonum,\n            \"aten::pad\": self.pad,\n            \"aten::constant_pad_nd\": self.constant_pad_nd,\n            \"aten::reflection_pad1d\": self.reflection_pad1d,\n            \"aten::reflection_pad2d\": self.reflection_pad2d,\n            \"aten::replication_pad1d\": self.replication_pad1d,\n            \"aten::replication_pad2d\": self.replication_pad2d,\n            \"aten::replication_pad3d\": self.replication_pad3d,\n            \"aten::permute\": self.transpose,\n            \"aten::sum\": self.make_reduce(\"sum\"),\n            \"aten::prod\": self.make_reduce(\"prod\"),\n            \"aten::argmin\": self.make_reduce(\"argmin\"),\n            \"aten::argmax\": self.make_reduce(\"argmax\"),\n            \"aten::norm\": self.norm,\n            \"aten::frobenius_norm\": self.frobenius_norm,\n            \"aten::std\": self.std,\n            \"aten::var\": self.variance,\n            \"aten::var_mean\": self.var_mean,\n            \"aten::abs\": self.make_unary(\"abs\"),\n            \"aten::neg\": self.make_unary(\"negative\"),\n            \"aten::cos\": self.make_unary(\"cos\"),\n            \"aten::cosh\": self.make_unary(\"cosh\"),\n            \"aten::sin\": self.make_unary(\"sin\"),\n            \"aten::sinh\": self.make_unary(\"sinh\"),\n            \"aten::tan\": self.make_unary(\"tan\"),\n            \"aten::tanh\": self.make_unary(\"tanh\"),\n            \"aten::acos\": self.make_unary(\"acos\"),\n            \"aten::asin\": self.make_unary(\"asin\"),\n            \"aten::atan\": self.make_unary(\"atan\"),\n            \"aten::log\": self.make_unary(\"log\"),\n            \"aten::log2\": self.make_unary(\"log2\"),\n            \"aten::log10\": self.make_unary(\"log10\"),\n            \"aten::log1p\": self.log1p,\n            \"aten::exp\": self.make_unary(\"exp\"),\n            \"aten::erf\": self.make_unary(\"erf\"),\n            \"aten::trunc\": self.make_unary(\"trunc\"),\n            \"aten::sign\": self.make_unary(\"sign\"),\n            \"aten::sqrt\": self.make_unary(\"sqrt\"),\n            \"aten::rsqrt\": self.make_unary(\"rsqrt\"),\n            \"aten::square\": self.square,\n            \"aten::tril\": functools.partial(self.trilu, mode=\"tril\"),\n            \"aten::triu\": functools.partial(self.trilu, mode=\"triu\"),\n            \"aten::ceil\": self.make_unary(\"ceil\"),\n            \"aten::floor\": self.make_unary(\"floor\"),\n            \"aten::round\": self.make_unary(\"round\"),\n            \"aten::isfinite\": self.make_unary(\"isfinite\"),\n            \"aten::isinf\": self.make_unary(\"isinf\"),\n            \"aten::isnan\": self.make_unary(\"isnan\"),\n            \"aten::clamp\": self.clamp,\n            \"aten::clamp_min\": self.clamp_min,\n            \"aten::clamp_max\": self.clamp_max,\n            \"aten::detach\": self.identity,\n            \"aten::upsample_bilinear2d\": self.make_upsample(\"linear\"),\n            \"aten::upsample_bicubic2d\": self.make_upsample(\"cubic\"),\n            \"aten::upsample_nearest2d\": self.make_upsample(\"nearest_neighbor\"),\n            \"aten::upsample_trilinear3d\": self.make_upsample3d(\"linear\"),\n            \"aten::upsample_nearest3d\": self.make_upsample3d(\"nearest_neighbor\"),\n            \"aten::expand_as\": self.expand_as,\n            \"aten::broadcast_tensors\": self.broadcast_tensors,\n            \"aten::lt\": self.make_elemwise(\"less\"),\n            \"aten::gt\": self.make_elemwise(\"greater\"),\n            \"aten::le\": self.make_elemwise(\"less_equal\"),\n            \"aten::ge\": self.make_elemwise(\"greater_equal\"),\n            \"aten::ne\": self.make_elemwise(\"not_equal\"),\n            \"aten::eq\": self.make_elemwise(\"equal\"),\n            \"aten::logical_not\": self.logical_not,\n            \"aten::logical_xor\": self.logical_xor,\n            \"aten::bitwise_not\": self.bitwise_not,\n            \"aten::bitwise_xor\": self.bitwise_xor,\n            \"aten::Bool\": self.Bool,\n            \"aten::Float\": self.Float,\n            \"aten::rsub\": self.rsub,\n            \"aten::embedding\": self.embedding,\n            \"aten::one_hot\": self.one_hot,\n            \"aten::mm\": self.matmul,\n            \"aten::add\": self.add,\n            \"aten::stack\": self.stack,\n            \"aten::__getitem__\": self.list_getitem,\n            \"aten::len\": self.list_len,\n            \"aten::type_as\": self.type_as,\n            \"aten::gather\": self.gather,\n            \"aten::index_select\": self.select,\n            \"aten::index\": self.index,\n            \"torchvision::nms\": self.nms,\n            \"aten::logsumexp\": self.logsumexp,\n            \"torchvision::roi_align\": self.roi_align,\n            \"torchvision::deform_conv2d\": self.deform_conv2d,\n            \"aten::unbind\": self.unbind,\n            \"aten::__and__\": self.logical_and,\n            \"aten::logical_and\": self.logical_and,\n            \"aten::_shape_as_tensor\": self.shape_as_tensor,\n            \"aten::nonzero\": self.nonzero,\n            \"aten::nonzero_numpy\": self.nonzero_numpy,\n            \"aten::scatter\": self.scatter,\n            \"aten::index_put\": self.index_put,\n            \"aten::scalar_tensor\": self.scalar_tensor,\n            \"aten::__interpolate\": self.interpolate,\n            \"aten::IntImplicit\": self.identity,\n            \"aten::tensor\": self.identity,  # used for example in tensor(1.0)\n            \"aten::numel\": self.numel,\n            \"aten::empty\": self.empty,\n            \"aten::empty_like\": self.empty_like,\n            \"aten::new_empty\": self.new_empty,\n            \"aten::randn\": self.randn,\n            \"aten::bincount\": self.bincount,\n            \"aten::scatter_add\": self.scatter_add,\n            \"aten::__not__\": self.logical_not,\n            \"aten::hardswish\": self.hard_swish,\n            \"aten::hardsigmoid\": self.hard_sigmoid,\n            \"aten::cumsum\": self.cumsum,\n            \"aten::masked_fill\": self.masked_fill,\n            \"aten::masked_select\": self.masked_select,\n            \"aten::argsort\": self.argsort,\n            \"aten::sort\": self.sort,\n            \"aten::_unique2\": self.unique,\n            \"aten::nll_loss\": self.nll_loss,\n            \"aten::nll_loss2d\": self.nll_loss,\n            \"aten::nll_loss_nd\": self.nll_loss,\n            \"aten::cross_entropy_loss\": self.cross_entropy_loss_with_logits,\n            \"aten::l1_loss\": self.l1_loss,\n            \"aten::mse_loss\": self.mse_loss,\n            \"aten::flip\": self.flip,\n            \"aten::rnn_tanh\": functools.partial(self.rnn, nonlinearity=\"tanh\"),\n            \"aten::rnn_relu\": functools.partial(self.rnn, nonlinearity=\"relu\"),\n            \"aten::gru\": self.gru,\n            \"aten::lstm\": self.lstm,\n            \"aten::all\": functools.partial(self.all_any_common, _op.all),\n            \"aten::any\": functools.partial(self.all_any_common, _op.any),\n            \"aten::searchsorted\": self.searchsorted,\n            \"aten::bucketize\": self.bucketize,\n            \"aten::roll\": self.roll,\n            \"aten::einsum\": self.einsum,\n            \"aten::dot\": self.dot,\n            \"aten::mv\": self.mv,\n            \"aten::grid_sampler\": self.grid_sampler,\n            \"aten::__ior__\": self.make_elemwise(\"bitwise_or\"),\n            \"aten::__iand__\": self.make_elemwise(\"bitwise_and\"),\n            \"aten::__ixor__\": self.make_elemwise(\"bitwise_xor\"),\n            \"aten::__lshift__\": self.make_elemwise(\"left_shift\"),\n            \"aten::__rshift__\": self.make_elemwise(\"right_shift\"),\n            \"aten::multinomial\": self.multinomial,\n        }\n\n    def update_convert_map(self, custom_map):\n        self.convert_map.update(custom_map)\n\n    def report_missing_conversion(self, op_names):\n        \"\"\"Check if all ops in an input graph are supported by TVM\"\"\"\n        known_ops = [\n            \"prim::Constant\",\n            \"prim::GetAttr\",\n            \"prim::ListConstruct\",\n            \"prim::ListUnpack\",\n            \"prim::TupleConstruct\",\n            \"prim::TupleUnpack\",\n            \"prim::RaiseException\",\n            \"prim::If\",\n            \"prim::Loop\",\n        ]\n        known_ops += list(self.convert_map.keys())\n        known_ops += list(qnn_torch.convert_map.keys())\n\n        missing = []\n\n        for op_name in op_names:\n            # Also take care of in-place variant ops like aten::relu_\n            if op_name not in known_ops and not (\n                op_name.endswith(\"_\") and op_name[:-1] in known_ops\n            ):\n                missing.append(op_name)\n\n        if missing:\n            msg = \"The following operators are not implemented: {}\".format(missing)\n            raise NotImplementedError(msg)\n\n    def convert_block(self, block, outputs):\n        \"\"\"Translate Torch \"Block\", used for prim::If and prim::Loop\"\"\"\n        ops = _get_operator_nodes(block.nodes())\n        ret_names = _get_input_names(block.returnNode())\n        return self.convert_operators(ops, outputs, ret_names)\n\n    def convert_if(self, if_node, outputs):\n        \"\"\"Translate Torch prim::If to Relay If\"\"\"\n        cond = outputs[if_node.inputsAt(0).debugName()]\n        blocks = list(if_node.blocks())\n        true_branch = self.convert_block(blocks[0], outputs)\n        false_branch = self.convert_block(blocks[1], outputs)\n        assert len(true_branch) == 1 and len(false_branch) == 1\n        return _expr.If(cond, true_branch[0], false_branch[0])\n\n    def convert_loop(self, loop_node, outputs):\n        \"\"\"Translate Torch prim::Loop to Relay while_loop\"\"\"\n\n        def get_input(index):\n            ivalue = loop_node.inputsAt(index)\n            inode = ivalue.node()\n            if inode.kind() == \"prim::Constant\":\n                return _expr.const(_get_constant(inode))\n            var_name = ivalue.debugName()\n            assert var_name in outputs\n            return _wrap_const(outputs[var_name])\n\n        # Refer to the spec for prim::Loop below\n        # https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/OVERVIEW.md#loops\n        # The first input: %max_trip_count\n        # The second input: %initial_condition\n        # The rest of input: loop variables\n        max_loop_count = get_input(0)\n        init_cond = get_input(1)\n        num_loop_var = len(list(loop_node.inputs())) - 2\n        init_vals = [get_input(i + 2) for i in range(num_loop_var)]\n\n        # while loop has always max_loop_count being int64 max\n        # max_loop_count.data (tvm.runtime.NDArray) is -1, so _get_constant again\n        is_while_loop = (\n            isinstance(max_loop_count, _expr.Constant)\n            and _get_constant(loop_node.inputsAt(0).node()) == sys.maxsize\n        )\n\n        if is_while_loop:\n            loop_iter_dtype = \"bool\"\n            # while loop with non input dependent condition such as while i < 10:\n            # init_cond is int, need to cast to bool to type check\n            if isinstance(init_cond, _expr.Constant):\n                init_cond = _op.cast(init_cond, \"bool\")\n            init_loop_iter_val = init_cond\n        else:\n            loop_iter_dtype = \"int32\"\n            # always count from 0\n            init_loop_iter_val = _expr.const(0, dtype=\"int32\")\n\n        body_block = list(loop_node.blocks())[0]\n        block_input_names = _get_input_names(body_block)\n        num_block_inputs = len(block_input_names)\n        name_val_pairs = list(zip(block_input_names, [init_loop_iter_val] + init_vals))\n        outputs.update(name_val_pairs)\n\n        def get_var(name, val):\n            if val:\n                checked_type = self.infer_type_with_prelude(val)\n                if hasattr(checked_type, \"shape\"):\n                    shape = get_const_tuple(checked_type.shape)\n                    actual_shape = []\n                    for dim in shape:\n                        if isinstance(dim, int) and dim == 0:\n                            actual_shape.append(Any())\n                        else:\n                            actual_shape.append(dim)\n                    return _expr.var(name, shape=actual_shape, dtype=checked_type.dtype)\n                else:\n                    return _expr.var(name, type_annotation=checked_type)\n            return _expr.var(name)\n\n        loop_iter_var = _expr.var(block_input_names[0], shape=(), dtype=loop_iter_dtype)\n        loop_vars = [get_var(name, val) for name, val in name_val_pairs[1:]]\n\n        # Add non constant free variables to loop variables to prevent code blow up\n        # Without this, if there are two for loops in a row, which often happens\n        # if the outer loop is unrolled, the computation corresponding to the first for loop\n        # is inlined inside loop body, turning O(N) + O(N) computation into O(N^2).\n        # This issue was found when converting from Stacked LSTM test. Torch does not add the\n        # outputof the eariler loop into loop variables of the next loop.\n        # So the variable corresponding to the first loop output appears free in the second\n        # loop body.\n        free_vars = [\n            var\n            for var in _get_free_vars_from_block(body_block)\n            if var in outputs\n            and not isinstance(outputs[var], (_expr.Constant, int, float, str))\n            and outputs[var]\n        ]\n\n        prev_outputs = {}\n        for name in free_vars:\n            prev_output = outputs[name]\n            new_loop_var = get_var(name, prev_output)\n            prev_outputs[name] = prev_output\n            outputs[name] = new_loop_var\n            loop_vars.append(new_loop_var)\n            init_vals.append(prev_output)\n\n        def cond(*current_vals):\n            i = current_vals[0]\n\n            if is_while_loop:\n                return _op.equal(i, _expr.const(True, \"bool\"))\n\n            return _op.less(i, max_loop_count)\n\n        def body(*current_vals):\n            # Update loop variables using the prev iteration outputs\n            assert len(current_vals) == num_block_inputs + len(free_vars)\n\n            for (i, val) in enumerate(current_vals):\n                if i < num_block_inputs:\n                    outputs[block_input_names[i]] = val\n                else:\n                    outputs[free_vars[i - num_block_inputs]] = val\n\n            block_outputs = self.convert_block(body_block, outputs)\n            block_outputs += [outputs[name] for name in free_vars]\n\n            if not is_while_loop:\n                # iter var increment implicit in torch, so do it manually\n                # for while loop, block_outputs[0] is already a boolean,\n                # the result of termination check\n                incr = _expr.const(1, dtype=\"int32\")\n                block_outputs[0] = current_vals[0] + incr\n\n            return block_outputs\n\n        loop = while_loop(cond, [loop_iter_var] + loop_vars, body)\n        loop_val = loop(init_loop_iter_val, *init_vals)\n\n        # restore original output values for free vars\n        outputs.update(prev_outputs)\n\n        # The first element is a loop counter or boolean condition, ignore it\n        return [_expr.TupleGetItem(loop_val, i + 1) for i in range(num_loop_var)]\n\n    def convert_operators(self, operators, outputs, ret_names):\n        \"\"\"Convert each Torch IR operators to Relay equivalent\"\"\"\n        for node_name, op_node in operators:\n            operator = op_node.kind()\n            inputs = _get_op_inputs(op_node, outputs)\n\n            if operator == \"prim::Constant\":\n                outputs[node_name] = _get_constant(op_node)\n            elif operator == \"prim::ListConstruct\" and _should_construct_dynamic_list(op_node):\n                outputs[node_name] = self.convert_to_list_adt(inputs)\n            elif operator == \"prim::ListConstruct\":\n                # This assumes that no more elements will be appended to this list\n                # In this case, we keep the Python list\n                outputs[node_name] = inputs\n            elif operator == \"prim::TupleConstruct\":\n\n                def _handel_nested_input(inputs):\n                    inputs_list = []\n                    for i, _ in enumerate(inputs):\n                        if isinstance(inputs[i], list):\n                            inputs_list.append(_handel_nested_input(inputs[i]))\n                        else:\n                            assert isinstance(inputs[i], _expr.Expr)\n                            inputs_list.append(inputs[i])\n                    return _expr.Tuple(inputs_list)\n\n                outputs[node_name] = _handel_nested_input(inputs)\n            elif operator in [\"prim::ListUnpack\", \"prim::TupleUnpack\"]:\n                assert len(inputs) == 1\n                if isinstance(inputs[0], (list, _expr.TupleWrapper)):\n                    unpacked = inputs[0]\n                else:\n                    unpacked = _unpack_tuple(inputs[0])\n                outputs.update(zip(_get_output_names(op_node), unpacked))\n            elif operator == \"prim::prim::RaiseException\":\n                logger.warning(\"raising exceptions is ignored\")\n                outputs[node_name] = None\n            elif operator == \"prim::If\":\n                if_out = self.convert_if(op_node, outputs)\n                outputs[node_name] = if_out\n            elif operator == \"prim::Loop\":\n                loop_out = self.convert_loop(op_node, outputs)\n                unpacked_names = _get_output_names(op_node)\n                assert len(loop_out) == len(unpacked_names)\n                outputs.update(zip(unpacked_names, loop_out))\n            else:\n                if operator not in self.convert_map:\n                    # At this point, the only possible ops that are not in convert_map are\n                    # in-place variant of ops like aten::relu_\n                    assert operator.endswith(\"_\")\n                    logger.warning(\n                        \"An in-place op %s found, the result will not be correct \"\n                        \"if the model depends on side-effects by this op.\",\n                        operator,\n                    )\n                    relay_op = self.convert_map[operator[:-1]]\n                else:\n                    relay_op = self.convert_map[operator]\n\n                relay_out = relay_op(\n                    inputs, _get_input_types(op_node, outputs, default_dtype=self.default_dtype)\n                )\n                self.record_output_type(relay_out)\n\n                if isinstance(relay_out, tuple):\n                    # This is for torch operators that return multiple outputs\n                    # See _adaptive_max_2d above for example\n                    out_names = _get_output_names(op_node)\n                    outputs.update(zip(out_names, relay_out))\n                else:\n                    assert op_node.outputsSize() == 1\n                    outputs[node_name] = relay_out\n\n        return [_wrap_const(outputs[ret_name]) for ret_name in ret_names]\n\n\ndef _pytorch_result_type(dtypes, non_tensor_inputs):\n    \"\"\"This promotes TVM dtypes like PyTorch would\"\"\"\n    import torch\n\n    dtype_map = {\n        \"float64\": torch.float64,\n        \"float32\": torch.float32,\n        \"float16\": torch.float16,\n        \"bfloat16\": torch.bfloat16,\n        \"int64\": torch.int64,\n        \"int32\": torch.int32,\n        \"int16\": torch.int16,\n        \"int8\": torch.int8,\n        \"uint8\": torch.uint8,\n        \"bool\": torch.bool,\n    }\n    if len(dtypes) > 0:\n        result_type = dtypes[0]\n        for dt in dtypes[1:]:\n            if dt != result_type:  # we don't want to work with same types as we\n                # don't do quantized here (which cannot be promoted?)\n                result_type = _convert_data_type(\n                    str(\n                        torch.result_type(\n                            torch.zeros((), dtype=dtype_map[result_type]),\n                            torch.zeros((), dtype=dtype_map[dt]),\n                        )\n                    )\n                )\n    else:\n        result_type = \"bool\"  # this is the smallest type...\n    for inp in non_tensor_inputs:\n        result_type = _convert_data_type(\n            str(torch.result_type(torch.zeros((), dtype=dtype_map[result_type]), inp))\n        )\n    return result_type\n\n\n# Helper functions for operator implementation\ndef _convert_dtype_value(val):\n    \"\"\"converts a PyTorch the PyTorch numeric type id to a torch scalar type.\"\"\"\n    convert_torch_dtype_map = {\n        11: \"torch.bool\",\n        7: \"torch.float64\",\n        6: \"torch.float32\",\n        5: \"torch.float16\",\n        4: \"torch.int64\",\n        3: \"torch.int32\",\n        2: \"torch.int16\",\n        1: \"torch.int8\",\n        0: \"torch.uint8\",\n        None: \"torch.int64\",\n    }  # Default is torch.int64\n    if val in convert_torch_dtype_map:\n        return _convert_data_type(convert_torch_dtype_map[val])\n    else:\n        msg = \"Torch data type value %d is not handled yet.\" % (val)\n        raise NotImplementedError(msg)\n\n\ndef _convert_data_type(input_type, default_dtype=None):\n    \"\"\"converts the PyTorch scalar type input_type to a TVM dtype.\n    optionally, default_dtype can be a TVM dtype that is used\n    if input_type is None (but not when it is unknown)\"\"\"\n    if input_type is None and default_dtype is not None:\n        return default_dtype\n\n    input_type = input_type.lower()\n    if input_type in [\"double\", \"float64\", \"torch.float64\"]:\n        return \"float64\"\n    elif input_type in [\"float\", \"float32\", \"torch.float32\"]:\n        return \"float32\"\n    elif input_type in [\"half\", \"float16\", \"torch.float16\"]:\n        return \"float16\"\n    elif input_type in [\"long\", \"int64\", \"torch.int64\"]:\n        return \"int64\"\n    elif input_type in [\"int\", \"int32\", \"torch.int32\"]:\n        return \"int32\"\n    elif input_type in [\"short\", \"int16\", \"torch.int16\"]:\n        return \"int16\"\n    elif input_type in [\"char\", \"int8\", \"torch.int8\"]:\n        return \"int8\"\n    elif input_type in [\"byte\", \"uint8\", \"torch.uint8\"]:\n        return \"uint8\"\n    elif input_type in [\"quint8\", \"torch.quint8\"]:\n        return \"quint8\"\n    elif input_type in [\"qint8\", \"torch.qint8\"]:\n        return \"qint8\"\n    elif input_type in [\"qint32\", \"torch.qint32\"]:\n        return \"qint32\"\n    elif input_type in [\"bool\", \"torch.bool\"]:\n        return \"bool\"\n    elif input_type in [\"str\"]:\n        return \"str\"\n    else:\n        raise NotImplementedError(\"input_type {} is not handled yet\".format(input_type))\n    return \"float32\"  # Never reached\n\n\ndef _create_typed_const(data, dtype):\n    \"\"\"create a (scalar) constant of given value and dtype.\n    dtype should be a TVM dtype\"\"\"\n\n    if dtype == \"float64\":\n        typed_data = _expr.const(np.float64(data), dtype=dtype)\n    elif dtype == \"float32\":\n        typed_data = _expr.const(np.float32(data), dtype=dtype)\n    elif dtype == \"float16\":\n        typed_data = _expr.const(np.float16(data), dtype=dtype)\n    elif dtype == \"int64\":\n        typed_data = _expr.const(np.int64(data), dtype=dtype)\n    elif dtype == \"int32\":\n        typed_data = _expr.const(np.int32(data), dtype=dtype)\n    elif dtype == \"int16\":\n        typed_data = _expr.const(np.int16(data), dtype=dtype)\n    elif dtype == \"int8\":\n        typed_data = _expr.const(np.int8(data), dtype=dtype)\n    elif dtype == \"uint8\":\n        typed_data = _expr.const(np.uint8(data), dtype=dtype)\n    else:\n        raise NotImplementedError(\"input_type {} is not handled yet\".format(dtype))\n    return typed_data\n\n\ndef _wrap_const(c):\n    if not isinstance(c, (_expr.Expr, list, tvm.tir.expr.Any)):\n        return _expr.const(c)\n    return c\n\n\ndef _run_jit_passes(graph, enable_lower_all_tuples=True):\n    \"\"\"The inline pass is necessary to unwrap prim::CallMethod\"\"\"\n    # pylint: disable=c-extension-no-member\n    import torch\n\n    if is_version_greater_than(\"1.5.1\"):\n        # This is required for torchvision detection models from 1.6 above\n        # It is the same as _jit_pass_inline, except that it has some special\n        # case behaviors for some ops such as aten::__interpolate()\n        torch._C._jit_pass_onnx_function_substitution(graph)\n    else:\n        torch._C._jit_pass_inline(graph)\n\n    if enable_lower_all_tuples:\n        torch._C._jit_pass_lower_all_tuples(graph)\n\n\ndef _get_tensor_and_var(torch_tensor, name):\n    tensor = tvm.nd.array(torch_tensor.cpu().numpy())\n    var = _expr.var(name, shape=tensor.shape, dtype=tensor.dtype)\n    return tensor, var\n\n\ndef _get_output_name(node):\n    assert node.outputsSize() == 1\n    return node.output().debugName()\n\n\ndef _get_output_names(node):\n    return [output.debugName() for output in node.outputs()]\n\n\ndef _get_input_names(node_or_graph):\n    return [inp.debugName() for inp in node_or_graph.inputs()]\n\n\ndef _get_op_inputs(op_node, outputs):\n    return [outputs[name] for name in _get_input_names(op_node)]\n\n\ndef _get_node_type(node):\n    assert node.outputsSize() == 1\n    return node.output().type().kind()\n\n\ndef _get_uses(node):\n    uses = []\n    for output in node.outputs():\n        uses += output.uses()\n    return uses\n\n\ndef _get_users(node):\n    return [use.user for use in _get_uses(node)]\n\n\ndef _getattr_full_name(getattrs, sep=\".\"):\n    return sep.join([getattr_attr_name(node) for node in getattrs])\n\n\ndef _get_pytorch_value_type(typ, default_dtype=\"float32\"):\n    kind = typ.kind()\n    if kind == \"TensorType\":\n        if typ.scalarType() is None:\n            # Tensor's type can be unknown if we use torch.jit.script(...)\n            # Defaults can be passed in, if not it is float32\n            logger.warning(\"Untyped Tensor found, assume it is %s\", default_dtype)\n            return default_dtype\n        else:\n            return _convert_data_type(typ.scalarType())\n\n    elif kind == \"ListType\":\n        return \"ListType\"\n    elif kind in [\"IntType\", \"FloatType\", \"BoolType\", \"StringType\", \"OptionalType\"]:\n        pt_dtype = str(typ).lower()\n        dtype = pt_dtype if pt_dtype == \"OptionalType\" else _convert_data_type(pt_dtype)\n        return dtype\n    else:\n        return \"UnsupportedType\"\n\n\ndef _get_input_types(op_node, outputs, default_dtype=\"float32\"):\n    \"\"\"Returns a TVM dtype for each input nodes derived from the torch type\"\"\"\n    in_types = []\n    for inp in op_node.inputs():\n        if inp.node().kind() == \"prim::GetAttr\":\n            # GetAttr nodes always return None when we call scalarType() on it\n            name = inp.debugName()\n            assert name in outputs\n            if isinstance(outputs[name], _expr.Var):\n                in_types.append(outputs[name].type_annotation.dtype)\n            else:\n                # For quantized modules with parameters, here we would get\n                # \"prim::GetAttr[name=\"_packed_params\"]\". Since the dtype corresponding to\n                # _packed_params is not needed by quantized ops, we return an arbitrary type.\n                in_types.append(default_dtype)\n        else:\n            in_types.append(_get_pytorch_value_type(inp.type(), default_dtype=default_dtype))\n\n    return in_types\n\n\ndef _get_constant(node):\n    \"\"\"Retrieve a constant associated with this prim::Constant node\"\"\"\n    attribute_names = node.attributeNames()\n    num_attributes = len(attribute_names)\n\n    if num_attributes == 1:\n        attr_name = attribute_names[0]\n        ty = node.output().type().kind()\n\n        if ty == \"IntType\":\n            return node.i(attr_name)\n        elif ty == \"BoolType\":\n            return bool(node.i(attr_name))\n        elif ty in [\"FloatType\", \"LongType\"]:\n            return node.f(attr_name)\n        elif ty in [\"TensorType\", \"CompleteTensorType\"]:\n            tensor = node.t(attr_name)\n            if tensor.is_cuda:\n                tensor = tensor.cpu()\n            if len(tensor.shape) == 0:  # tensor(0.1)\n                # TODO(t-vi): When is this needed?\n                return tensor.item()\n            return _wrap_const(tensor.numpy())\n        elif ty in [\"DeviceObjType\", \"StringType\"]:\n            return node.s(attr_name)\n        elif ty == \"FunctionType\":\n            return None\n        else:\n            raise NotImplementedError(\"Unsupported type: %s\" % ty)\n    else:\n        assert num_attributes == 0\n        return None\n\n\ndef _get_operator_nodes(nodes):\n    \"\"\"Returns torch IR nodes that need conversion to Relay\"\"\"\n    ops = []\n    # Traverse nodes and add to graph\n    for node in nodes:\n        if node.outputsSize() == 0:\n            continue\n        if node.outputsSize() > 1:\n            node_name = \"_\".join(_get_output_names(node))\n        else:\n            node_name = _get_output_name(node)\n\n        if node.kind() != \"prim::GetAttr\":\n            ops.append((node_name, node))\n\n    return ops\n\n\ndef _get_relay_input_vars(graph, input_infos, prelude, is_module=True, default_dtype=\"float32\"):\n    \"\"\"\n    Return Relay vars from input shapes and create entries based on\n    expected graph inputs - to allow translation\n    \"\"\"\n\n    graph_inputs = list(graph.inputs())\n    if is_module:\n        # a module has \"self\" as first input, which we do not need/want\n        graph_inputs = graph_inputs[1:]\n\n    if not isinstance(input_infos, list):\n        msg = \"Graph inputs input_infos should be a list\"\n        raise RuntimeError(msg)\n\n    if len(graph_inputs) != len(input_infos):\n        msg = \"PyTorch has {} inputs and input_infos lists {}.\".format(\n            len(graph_inputs), len(input_infos)\n        )\n        raise RuntimeError(msg)\n\n    def get_relay_ty(ishape, itype, pt_type):\n        if pt_type.kind() == \"TensorType\":\n            if not (_is_int_seq(ishape) or len(ishape) == 0):\n                msg = \"Shape for Tensors must be lists of ints\"\n                raise RuntimeError(msg)\n            if (pt_type.dim() is not None and pt_type.dim() != len(ishape)) or (\n                pt_type.sizes() is not None\n                and any([s1 != s2 for s1, s2 in zip(pt_type.sizes(), ishape)])\n            ):\n                msg = \"Shapes of input list and information in the graph do not match\"\n                raise RuntimeError(msg)\n            pt_dtype = pt_type.scalarType()\n            if not pt_dtype and itype:\n                pt_dtype = itype\n            dtype = _convert_data_type(pt_dtype, default_dtype=default_dtype)\n            return TensorType(ishape, dtype)\n        elif pt_type.kind() == \"TupleType\":\n            if not isinstance(ishape, tuple):\n                msg = \"Shapes for tuples must be tuples\"\n                raise RuntimeError(msg)\n            return TupleType(\n                [get_relay_ty(elem, itype, pt_t) for elem, pt_t in zip(ishape, pt_type.elements())]\n            )\n        elif pt_type.kind() == \"ListType\":\n            if not isinstance(ishape, list):\n                msg = \"Shapes for lists must be lists\"\n                raise RuntimeError(msg)\n            pt_elemtype = pt_type.getElementType()\n            elem_tys = [get_relay_ty(s, itype, pt_elemtype) for s in ishape]\n            if len(elem_tys) > 0 and not all(map(lambda ty: ty == elem_tys[0], elem_tys)):\n                msg = \"List elements need have identical types\"\n                raise RuntimeError(msg)\n            rlist, _, _ = prelude.mod.get_type(\"List\")\n            return rlist(elem_tys[0])\n        elif pt_type.kind() == \"OptionalType\":\n            # we do not support None yet, so we fill in the type\n            return get_relay_ty(ishape, itype, pt_type.getElementType())\n        # TODO: scalar inputs\n        raise NotImplementedError(\"unsupported input type\")\n\n    input_vars = {}\n\n    new_input_infos = []\n    for num, inp in enumerate(input_infos):\n        if not isinstance(inp, tuple):\n            msg = \"Graph input {} is not a tuple\".format(num)\n            raise RuntimeError(msg)\n        if len(inp) != 2 or not isinstance(inp[0], str):\n            msg = (\n                \"Graph input {} is not valid,\"\n                \" expected ('name', shape) or ('name', (shape, dtype))\".format(inp)\n            )\n            raise RuntimeError(msg)\n        if not isinstance(inp[1], tuple) or len(inp[1]) == 0 or not isinstance(inp[1][-1], str):\n            new_input_infos.append((inp[0], (inp[1], default_dtype)))\n        else:\n            new_input_infos.append(inp)\n\n    input_types = [\n        (name, get_relay_ty(info[0], info[1], gi.type()))\n        for (name, info), gi in zip(new_input_infos, graph_inputs)\n    ]\n\n    ir_inputs = [i.debugName() for i in graph_inputs]\n    for ir_input, (name, itype) in zip(ir_inputs, input_types):\n        inp = _expr.var(name, type_annotation=itype)\n        # Translate from graph input to user input name\n        input_vars[ir_input] = inp\n\n    return input_vars\n\n\ndef _unpack_tuple(tup):\n    def unpack(tup, num_fields):\n        return [_expr.TupleGetItem(tup, i) for i in range(num_fields)]\n\n    if isinstance(tup, _expr.Tuple):\n        return unpack(tup, len(tup.fields))\n    elif isinstance(tup.type_annotation, TupleType):\n        return unpack(tup, len(tup.type_annotation.fields))\n    # shouldn't happen\n    assert False\n\n\ndef _get_free_vars_from_block(block):\n    block_inp_names = _get_input_names(block)\n    bound_names = block_inp_names\n    free_vars = set()\n\n    for node in block.nodes():\n        inp_names = _get_input_names(node)\n        list_diff = [name for name in inp_names if name not in bound_names]\n        free_vars.update(list_diff)\n        bound_names += _get_output_names(node)\n\n    return free_vars\n\n\ndef get_use_chains(root_node, terminate=lambda _: False):\n    \"\"\"\n    Track a chain of users of this node forward, returning a list of chains\n    See get_attr_chains below for its usage\n    \"\"\"\n\n    def concat_lists(lists):\n        return itertools.chain.from_iterable(lists)\n\n    def inner(current, accum):\n        users = _get_users(current)\n\n        if not users or terminate(users):\n            return [accum]\n\n        return concat_lists([inner(nxt, accum + [nxt]) for nxt in users])\n\n    return inner(root_node, [root_node])\n\n\ndef get_attr_chains(root_getattr_node):\n    \"\"\"Returns chains of attribute access starting from root_getattr_node\n\n    For example, given attribute \"block\", as in \"self.block\" when \"self\" points\n    to the top level torch.nn.Module, it returns lists of attribute \"chains\",\n    e.g. ['block', '2'], ['block', '1'], ['block', '0', '_packed_params']\n\n    These sets of attributes form full attribute accessors. For example,\n    \"self.block.1\", \"self.block.2\" will return the second and third submodule,\n    and \"self.block.0._packed_params\" will return the parameters of the first\n    submodule.\n    \"\"\"\n\n    def terminate(users):\n        next_attrs = [user for user in users if user.kind() == \"prim::GetAttr\"]\n        return len(next_attrs) == 0\n\n    return get_use_chains(root_getattr_node, terminate)\n\n\ndef convert_params(graph, state_dict, use_parser_friendly_name=False):\n    \"\"\"\n    Return Relay vars and TVM NDArrays for input parameters\n    A chain of prim::GetAttr nodes is processed one at a time\n    \"\"\"\n    getattr_nodes = graph.findAllNodes(\"prim::GetAttr\", recurse=True)\n    params = {}\n    param_tensors = {}\n    packed_param_map = {}\n    vars_by_name = {}\n    seen = set()\n    attr_name_sep = \"_\" if use_parser_friendly_name else \".\"\n\n    for node in getattr_nodes:\n        if _get_output_name(node) in seen:\n            continue\n\n        for getattrs in get_attr_chains(node):\n            seen.update(map(_get_output_name, getattrs))\n\n            full_attr = _getattr_full_name(getattrs, attr_name_sep)\n            full_attr_node_name = _get_output_name(getattrs[-1])\n\n            if full_attr.endswith(\"_packed_params\"):  # for quantized models\n                packed_param_map[full_attr_node_name] = full_attr\n            elif full_attr in state_dict:\n                if full_attr in vars_by_name:\n                    var = vars_by_name[full_attr]\n                else:\n                    torch_tensor = state_dict[full_attr]\n                    tensor, var = _get_tensor_and_var(torch_tensor, full_attr)\n                    param_tensors[full_attr] = tensor\n                    vars_by_name[full_attr] = var\n                params[full_attr_node_name] = var\n\n    return params, param_tensors, packed_param_map\n\n\ndef get_all_op_names(graph):\n    \"\"\"Return all operator names in the input graph\"\"\"\n    nodes = list(graph.nodes())\n    prim_with_blocks = [\"prim::If\", \"prim::Loop\"]\n    for prim in prim_with_blocks:\n        prim_nodes = graph.findAllNodes(prim, recurse=True)\n        for prim_node in prim_nodes:\n            for block in prim_node.blocks():\n                nodes += block.nodes()\n    return set(node.kind() for node in nodes)\n\n\ndef from_pytorch(\n    script_module,\n    input_infos,\n    custom_convert_map=None,\n    default_dtype=\"float32\",\n    use_parser_friendly_name=False,\n    keep_quantized_weight=False,\n):\n    \"\"\"Load PyTorch model in the form of a scripted PyTorch model and convert into relay.\n    The companion parameters will be handled automatically.\n\n    Parameters\n    ----------\n    script_module : TopLevelTracedModule object\n        TorchScripted PyTorch graph\n        Note: We currently only support traces (ie: torch.jit.trace(model, input))\n\n    input_infos : List of tuples\n        Can be (input name, input shape) or (input name, (input shape, input types))\n        Graph level input shape and type list\n        The same input names need to be used for deployment, so choose easy to\n        remember names (such as: input0, input1)\n        e.g.\n        [('input0', (1, 2)), ('input1', (3, 4))]\n        or\n        [('input0', ((1, 2), 'int')), ('input1', ((3, 4), 'float'))]\n\n    custom_convert_map : Dictionary of str to Relay op\n        A custom op conversion map in the same format as _convert_map above\n\n    default_type : str\n        The default dtype to use when type information is not provided by PyTorch.\n\n    use_parser_friendly_name : bool\n        When True, replace '.' with `_' in a original parameter name.\n        The Relay text parser treats a variable name followed by a period as a tuple element access,\n        so a variable name like \"dense.weight\" cannot be parsed correctly.\n        Use this option when you want to run the AnnotateSpans pass on the imported module.\n\n    keep_quantized_weight : bool\n        Return quantized weights and bias, rather than float ones. PyTorch stores quantized weights\n        in a custom format, so we cannot directly access 8 bit weights as Numpy arrays. We use\n        a PyTorch function to unpack quantized weights into float32 arrays and quantization\n        parameters. By default, we return float32 weights and rely on the QNN lowering and the\n        Relay constant folding pass to quantize weights at compile time. In BYOC use cases, however,\n        we cannot apply the constant folding pass on a QNN graph. If keep_quantized_weight is True,\n        we quantize weights in the frontend using a function that is equivalent to\n        qnn.op.quantize(...) operating on Numpy arrays.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The module that optimizations will be performed on.\n\n    params : dict of str to tvm.runtime.NDArray\n        Dict of converted parameters stored in tvm.runtime.ndarray format\n    \"\"\"\n    import torch\n\n    mod = tvm.IRModule()\n    prelude = Prelude(mod)\n    enable_lower_all_tuples = True\n\n    converter = PyTorchOpConverter(prelude, default_dtype)\n\n    graph = script_module.graph.copy()\n\n    # Check if lower_all_tuples pass can be enabled\n    graph_inputs = list(graph.inputs())\n    for inp in graph_inputs:\n        if inp.type().kind() == \"TupleType\" or inp.type().kind() == \"ListType\":\n            enable_lower_all_tuples = False\n            break\n    _run_jit_passes(graph, enable_lower_all_tuples)\n\n    if custom_convert_map:\n        converter.update_convert_map(custom_convert_map)\n\n    op_names = get_all_op_names(graph)\n    converter.report_missing_conversion(op_names)\n\n    is_module = isinstance(script_module, torch.jit.ScriptModule)\n    params = script_module.state_dict() if is_module else {}\n    outputs = _get_relay_input_vars(\n        graph, input_infos, prelude, default_dtype=default_dtype, is_module=is_module\n    )\n\n    if use_parser_friendly_name:\n        new_names = [key.replace(\".\", \"_\") for key in params.keys()]\n        params = dict(zip(new_names, params.values()))\n\n    param_vars, tensors, packed_param_map = convert_params(graph, params, use_parser_friendly_name)\n\n    tvm_params = {k: tvm.nd.array(v) for k, v in tensors.items()}\n\n    outputs.update(param_vars)\n    ret_name = _get_input_names(graph.return_node())\n\n    # For quantized models\n    quantized_ops = set([\"aten::quantize_per_tensor\", \"quantized::linear_dynamic\"])\n    if len(quantized_ops.intersection(set(op_names))) > 0:\n        weight_quant_params = qnn_torch.get_weight_quant_params(\n            script_module, packed_param_map.values()\n        )\n        qnn_torch.inline_input_quant_params_for_fx(graph, tensors)\n        input_scales_for_bias = qnn_torch.add_input_quant_params_to_op_inputs(graph)\n        qnn_torch.add_quant_params_to_outputs(\n            outputs,\n            packed_param_map,\n            weight_quant_params,\n            input_scales_for_bias,\n            keep_quantized_weight,\n        )\n        qnn_torch.add_quant_params(tvm_params, weight_quant_params)\n        converter.update_convert_map(qnn_torch.convert_map)\n\n    outputs = converter.convert_operators(_get_operator_nodes(graph.nodes()), outputs, ret_name)\n\n    # ListConstruct kept original python list. Convert to tuple.\n    outputs = [_expr.Tuple(output) if isinstance(output, list) else output for output in outputs]\n\n    if len(outputs) > 1:\n        ret = _expr.Tuple(outputs)\n    else:\n        ret = outputs[0]\n\n    # Separate data inputs and parameters to make sure data inputs come first.\n    func_args = []\n    data_inputs = []\n    for arg in _analysis.free_vars(ret):\n        if arg.name_hint not in tvm_params.keys():\n            data_inputs.append(arg)\n        else:\n            func_args.append(arg)\n    func_args = data_inputs + func_args\n\n    mod[\"main\"] = tvm.relay.Function(func_args, ret)\n\n    return transform.RemoveUnusedFunctions()(mod), tvm_params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/pytorch_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-outside-toplevel, unused-argument, invalid-name\n\"\"\" Common utilities used by PyTorch frontend \"\"\"\nfrom .. import expr\nfrom .. import op\nfrom ..dataflow_pattern import (\n    wildcard,\n    is_constant,\n    is_op,\n    rewrite,\n    is_tuple,\n    is_tuple_get_item,\n    is_if,\n    DFPatternCallback,\n)\n\n\ndef is_version_greater_than(ver):\n    \"\"\"\n    Returns True if the local PyTorch version is greater\n    than the one given as an argument.\n    \"\"\"\n    import torch\n    from distutils.version import LooseVersion\n\n    torch_ver = torch.__version__\n    # PT version numbers can include +cu[cuda version code]\n    # and we don't want to include that in the comparison\n    if \"+cu\" in torch_ver:\n        torch_ver = torch_ver.split(\"+cu\")[0]\n\n    return LooseVersion(torch_ver) > ver\n\n\ndef getattr_attr_name(node):\n    attribute_names = node.attributeNames()\n    assert len(attribute_names) == 1\n    return node.s(attribute_names[0])\n\n\ndef dyn_strided_slice_pattern(inp, end):\n    \"\"\"A pattern to detect dynamic strided slice op.\"\"\"\n    zero = is_constant()\n    cast_like = is_op(\"cast_like\")(zero, is_constant())\n    less = is_op(\"less\")(is_constant(), cast_like)\n    shape_of = is_op(\"shape_of\")(inp)\n    cast_like = is_op(\"cast_like\")(shape_of, is_constant())\n    add = is_op(\"add\")(is_constant(), cast_like)\n    where = is_op(\"where\")(less, add, is_constant())\n\n    return is_op(\"dyn.strided_slice\")(inp, where, end, is_constant())\n\n\ndef batched_nms_pattern(boxes, scores, idxs, iou_threshold, num_boxes, indices):\n    \"\"\"A pattern to detect batched_nms function in torchvision\n\n    The inputs to this function, boxes, scores, idxs, iou_threshold are wildcard\n    patterns which can be used later in the rewriting to extract matched Relay fragments.\n\n    We want to detect the following PyTorch code snippet:\n\n    def batched_nms(boxes, scores, idxs, iou_threshold):\n        max_coordinate = boxes.max()\n        offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))\n        boxes_for_nms = boxes + offsets[:, None]\n        keep = nms(boxes_for_nms, scores, iou_threshold)\n        return keep\n\n    Here is how PyTorch frontend lowers above PyTorch code. For simplicity, Relay ops for\n    dealing with dynamic strided_slice are omitted. %num_boxes, %indices are complex\n    expressions, but since we can use the wildcard part for them, we do not need to construct\n    their patterns.\n\n    %2 = expand_dims(%scores, axis=-1);\n    %3 = cast(%idxs, dtype=\"float32\");\n    %4 = max(%boxes);\n    %5 = add(%4, 1f);\n    %6 = multiply(%3, %5);\n    %7 = strided_slice(%6, begin=[0], end=[4507], strides=[1]);\n    %8 = expand_dims(%7, axis=1);\n    %9 = add(%boxes, %8);\n    %10 = (%2, %9);\n    %11 = concatenate(%10, axis=-1);\n    %12 = expand_dims(%11, axis=0);\n    ...\n    ...\n    %17 = vision.non_max_suppression(%12, %num_boxes, %indices, -1, 0.7f, ...);\n\n    \"\"\"\n    one = is_constant()\n\n    # Equivalent PyTorch code from above snippet\n    # offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))\n    cast = is_op(\"cast\")(idxs)\n    mx = is_op(\"max\")(boxes)\n    add = is_op(\"add\")(mx, one)\n    mul = is_op(\"multiply\")(cast, add)\n\n    shape_of = is_op(\"shape_of\")(mul)\n    cast = is_op(\"cast\")(shape_of)\n\n    # Add offsets to the boxes\n    expand_dims = is_op(\"expand_dims\")(mul)\n    add = is_op(\"add\")(boxes, expand_dims)\n\n    # The rest of patterns correspond to the PyTorch frontend conversion\n    # function for torchvision::nms\n    score_expand_dims = is_op(\"expand_dims\")(scores)\n    tup = is_tuple([score_expand_dims, add])\n    concat = is_op(\"concatenate\")(tup)\n    data = is_op(\"expand_dims\")(concat)\n\n    return is_op(\"vision.non_max_suppression\")(\n        data, num_boxes, indices, is_constant(), iou_threshold\n    )\n\n\ndef topk_after_batch_nms_pattern(cond, true_branch, data, valid_count, indices, iou_threshold):\n    \"\"\"\n    Detect the following pattern used in torchvision detection models.\n\n    def batched_nms(...):\n        if boxes.numel() == 0:\n            return torch.empty((0,), dtype=torch.int64, device=boxes.device)\n        else:\n            ...\n            return nms(boxes_for_nms, scores, iou_threshold)\n\n    keep = batched_nms(boxes, scores, lvl, self.nms_thresh)\n    keep = keep[:post_nms_top_k] # keep only topk scoring predictions\n\n    An equivalent Relay subgraph:\n\n    %1184 = if (%1117) {\n      ...\n    } else {\n      ...\n      %1172 = vision.non_max_suppression(%1167, %1168, %1171, -1, 0.7f, ...);\n      ...\n      %1183 = dyn.strided_slice(%1174, %1180, %1182, ...);\n      cast(%1183, dtype=\"int64\")\n    };\n    %1185 = strided_slice(%1184, begin=[0], end=[1000], strides=[1]);\n\n    \"\"\"\n    nms = is_op(\"vision.non_max_suppression\")(\n        data, valid_count, indices, is_constant(), iou_threshold\n    )\n    indices = is_op(\"squeeze\")(is_tuple_get_item(nms, 0))\n    size = is_op(\"squeeze\")(is_tuple_get_item(nms, 1))\n    dyn_strided_slice = dyn_strided_slice_pattern(indices, size)\n    cast_i64 = is_op(\"cast\")(dyn_strided_slice)\n\n    batched_nms_result = is_if(cond, true_branch, cast_i64)\n\n    return is_op(\"strided_slice\")(batched_nms_result)\n\n\nclass MulticlassNMSRewrite(DFPatternCallback):\n    \"\"\"A callback to rewrite nms and restore batched nms.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        # exprs to extract\n        self.boxes = wildcard()\n        self.scores = wildcard()\n        self.idxs = wildcard()\n        self.iou_threshold = wildcard()\n        self.num_boxes = wildcard()\n        self.indices = wildcard()\n\n        self.pattern = batched_nms_pattern(\n            self.boxes,\n            self.scores,\n            self.idxs,\n            self.iou_threshold,\n            self.num_boxes,\n            self.indices,\n        )\n\n    def convert_batched_nms(self, boxes, scores, idxs, iou_thres, num_boxes, indices):\n        \"\"\"Restore class-aware NMS using extracted class indices\"\"\"\n        scores = op.expand_dims(scores, axis=-1, num_newaxis=1)\n        idxs = op.expand_dims(idxs, axis=-1, num_newaxis=1)\n        idxs = op.cast(idxs, \"float32\")\n        data = op.concatenate([idxs, scores, boxes], -1)\n        data = op.expand_dims(data, 0, 1)\n\n        top_k = max_out_size = -1\n        out = op.vision.non_max_suppression(\n            data=data,\n            valid_count=num_boxes,\n            indices=indices,\n            max_output_size=max_out_size,\n            iou_threshold=iou_thres,\n            force_suppress=False,\n            top_k=top_k,\n            coord_start=2,\n            score_index=1,\n            id_index=0,\n            return_indices=True,\n            invalid_to_bottom=False,\n        )\n        return out.tuple_value\n\n    def callback(self, pre, post, node_map):\n        boxes = node_map[self.boxes][0]\n        scores = node_map[self.scores][0]\n        idxs = node_map[self.idxs][0]\n        iou_thres = node_map[self.iou_threshold][0]\n        num_boxes = node_map[self.num_boxes][0]\n        indices = node_map[self.indices][0]\n        return self.convert_batched_nms(boxes, scores, idxs, iou_thres, num_boxes, indices)\n\n\nclass PostNMSTopKRewrite(DFPatternCallback):\n    \"\"\"A callback to rewrite nms to exploit max_out_size parameter.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.cond = wildcard()\n        self.true_branch = wildcard()\n        self.data = wildcard()\n        self.valid_count = wildcard()\n        self.indices = wildcard()\n        self.iou_threshold = wildcard()\n\n        self.pattern = topk_after_batch_nms_pattern(\n            self.cond,\n            self.true_branch,\n            self.data,\n            self.valid_count,\n            self.indices,\n            self.iou_threshold,\n        )\n\n    def rewrite_batch_nms_with_max_out_size(\n        self, cond, true_branch, data, valid_count, indices, iou_threshold, post_nms_topk\n    ):\n        \"\"\"Use the detected post NMS topk parameter in NMS op.\"\"\"\n        nms_ret = op.vision.non_max_suppression(\n            data=data,\n            valid_count=valid_count,\n            indices=indices,\n            max_output_size=post_nms_topk,\n            iou_threshold=iou_threshold,\n            force_suppress=False,\n            top_k=-1,\n            coord_start=2,\n            score_index=1,\n            id_index=0,\n            return_indices=True,\n            invalid_to_bottom=False,\n        )\n\n        size = op.squeeze(nms_ret[1], axis=[1])\n        data_slice = op.squeeze(nms_ret[0], axis=[0])\n\n        ret = op.strided_slice(data_slice, begin=expr.const([0]), end=size, slice_mode=\"size\")\n\n        nms_result = op.cast(ret, \"int64\")\n\n        return expr.If(cond, true_branch, nms_result)\n\n    def callback(self, pre, post, node_map):\n        post_nms_topk = post.attrs.end[0].value\n        return self.rewrite_batch_nms_with_max_out_size(\n            node_map[self.cond][0],\n            node_map[self.true_branch][0],\n            node_map[self.data][0],\n            node_map[self.valid_count][0],\n            node_map[self.indices][0],\n            node_map[self.iou_threshold][0],\n            post_nms_topk,\n        )\n\n\ndef scatter_roi_align_result_pattern(levels, roi_align_results, num_scales):\n    \"\"\"Detect the Relay subgraph corresponding to the following PyTorch code\n\n    first_result = roi_align_results[0]\n    dtype, device = first_result.dtype, first_result.device\n    res = torch.zeros((levels.size(0), first_result.size(1),\n                       first_result.size(2), first_result.size(3)),\n                      dtype=dtype, device=device)\n    for level in range(len(roi_align_results)):\n        index = torch.where(levels == level)[0].view(-1, 1, 1, 1)\n        index = index.expand(index.size(0),\n                             roi_align_results[level].size(1),\n                             roi_align_results[level].size(2),\n                             roi_align_results[level].size(3))\n        res = res.scatter(0, index, roi_align_results[level])\n    return res\n    \"\"\"\n\n    def do_where(levels, _):\n        idx_in_level = is_op(\"argwhere\")(is_op(\"equal\")(levels, is_constant()))\n        idx_in_level = is_op(\"split\")(idx_in_level)\n        idx_in_level = is_tuple_get_item(idx_in_level, 0)\n        idx_in_level = is_op(\"squeeze\")(idx_in_level)\n        idx_in_level = is_tuple_get_item(is_tuple([idx_in_level]), 0)\n        return idx_in_level\n\n    scatter_res = wildcard()\n\n    for i in range(num_scales):\n        # index = torch.where(levels == level)[0].view(-1, 1, 1, 1)\n        scatter_indices = do_where(levels, i)\n        scatter_indices = is_op(\"reshape\")(scatter_indices)\n\n        # index = index.expand(index.size(0),\n        #                      unmerged_results[level].size(1),\n        #                      unmerged_results[level].size(2),\n        #                      unmerged_results[level].size(3))\n        scatter_indices = is_op(\"repeat\")(scatter_indices)\n        scatter_indices = is_op(\"repeat\")(scatter_indices)\n        scatter_indices = is_op(\"repeat\")(scatter_indices)\n\n        scatter_res = is_op(\"scatter\")(scatter_res, scatter_indices, roi_align_results[i])\n\n    return is_op(\"reshape\")(scatter_res)\n\n\nclass ScatterRewrite(DFPatternCallback):\n    \"\"\"A callback to rewrite repeated scatters with a batched gather.\"\"\"\n\n    def __init__(self, num_scales):\n        super().__init__()\n        self.num_scales = num_scales\n        self.levels = wildcard()\n        self.roi_align_results = []\n        for _ in range(num_scales):\n            self.roi_align_results.append(wildcard())\n\n        self.pattern = scatter_roi_align_result_pattern(\n            self.levels, self.roi_align_results, num_scales\n        )\n\n    def convert_scatter_to_gather(self, levels, roi_align_results):\n        \"\"\"Replace the detected scatter loop with the following PyTorch code\n\n        indices_per_level = []\n        for level in range(num_scales):\n            idx_in_level = torch.where(levels == level)[0]\n            indices_per_leve.append(idx_in_level)\n\n        stacked_features = torch.cat(roi_align_results, dim=0)\n        stacked_indices = torch.cat(indices_per_level, dim=0)\n        argsort_indices = torch.argort(stacked_indices)\n        return stacked_features[argsort_indices, :]\n        \"\"\"\n\n        # Collect inidices and concat them\n        indices_per_level = []\n        for i in range(self.num_scales):\n            equal = op.equal(levels, expr.const(i, dtype=\"int64\"))\n            argwhere = op.argwhere(equal)\n            split = op.split(argwhere, indices_or_sections=1, axis=1)\n            squeeze = op.squeeze(split[0], axis=[1])\n            indices = op.cast(squeeze, dtype=\"int64\")\n            indices_per_level.append(indices)\n\n        indices_concat = op.concatenate(indices_per_level, 0)\n\n        # Concat roi align results per level, and argsort indices\n        # To prepare for a batched gather\n        roi_align_results_concat = op.concatenate(roi_align_results, 0)\n        argsort_indices = op.cast(op.argsort(indices_concat), dtype=\"int64\")\n\n        # Permute rows by argsorted indices\n        permuted = op.take(roi_align_results_concat, argsort_indices, axis=0)\n\n        return op.reshape(permuted, [0, -1, 1, 1])\n\n    def callback(self, pre, post, node_map):\n        levels = node_map[self.levels][0]\n        roi_align_results = [node_map[feat][0] for feat in self.roi_align_results]\n        return self.convert_scatter_to_gather(levels, roi_align_results)\n\n\ndef rewrite_nms_to_batched_nms(mod):\n    \"\"\"Rewrite the input graph to replace non maximum surpression\n    in torchvision that does not take class id into account with the one\n    that avoids IOU tests between different classes.\n    \"\"\"\n    mod[\"main\"] = rewrite(MulticlassNMSRewrite(), mod[\"main\"])\n    return mod\n\n\ndef rewrite_batched_nms_with_max_out_size(mod):\n    \"\"\"Rewrite the input graph to detect slicing after batched nms and\n    use the slicing size as the parameter max_out_size in NMS.\n    \"\"\"\n    mod[\"main\"] = rewrite(PostNMSTopKRewrite(), mod[\"main\"])\n    return mod\n\n\ndef rewrite_scatter_to_gather(mod, num_scales):\n    \"\"\"Rewrite the input graph to replace a repeated scatter loop with\n    a batched gather. The scatter loop is used in torchvision MultiScaleRoIAlign\n    to merge roi_align results for all scales. The scatter is used to emulate\n    inplace updates.\n    \"\"\"\n    mod[\"main\"] = rewrite(ScatterRewrite(num_scales), mod[\"main\"])\n    return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/qnn_torch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-outside-toplevel\n\"\"\" Functions to convert quantized torch models to QNN \"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import expr as _expr\nfrom tvm.relay import op as _op\nfrom tvm.relay.frontend.common import infer_shape\n\nfrom .common import logger\nfrom .pytorch_utils import is_version_greater_than, getattr_attr_name\n\n\nclass QNNParam(object):\n    \"\"\"A placeholder for weight quantization parameters\"\"\"\n\n    def __init__(self, weight, bias, scale, zero_point):\n        self.weight = weight\n        self.bias = None if bias is None else bias.detach().numpy()\n        self.scale = _expr.const(scale)\n        self.zero_point = _expr.const(zero_point, dtype=\"int32\")\n\n\nclass ConvPackedParam(QNNParam):\n    \"\"\"A placeholder for quantized conv2d op attributes\n    As of PyTorch 1.6, attributes of quantized conv2d ops, like\n    stride, padding etc are stored in ConvPackedParams objects,\n    together with weights and quantization parameters\n    \"\"\"\n\n    def __init__(\n        self,\n        weight_np,\n        bias,\n        scale,\n        zero_point,\n        stride,\n        padding,\n        dilation,\n        groups,\n        output_padding,\n    ):\n        super().__init__(weight_np, bias, scale, zero_point)\n        self.stride = stride\n        self.padding = padding\n        self.dilation = dilation\n        self.groups = groups\n        # Used only for conv_transpose2d\n        self.output_padding = output_padding\n\n\ndef _get_quant_params(qweight):\n    import torch\n\n    weight_np = qweight.dequantize().numpy()\n\n    if qweight.qscheme() == torch.per_tensor_affine:\n        return weight_np, qweight.q_scale(), int(qweight.q_zero_point())\n\n    scales = qweight.q_per_channel_scales().numpy()\n    zero_points = qweight.q_per_channel_zero_points().numpy()\n    # This is an assumption posed by QNN\n    msg = \"The values of zero points should be all zero for per channel\"\n    assert np.all(zero_points == 0), msg\n    return weight_np, scales, 0\n\n\ndef make_qnn_param(qweight, bias):\n    weight_np, scale, zero_point = _get_quant_params(qweight)\n    return QNNParam(weight_np, bias, scale, zero_point)\n\n\ndef make_conv_packed_param(qweight, bias, packed_params):\n    weight_np, scale, zero_point = _get_quant_params(qweight)\n    stride = packed_params.stride()\n    padding = packed_params.padding()\n    dilation = packed_params.dilation()\n    groups = packed_params.groups()\n    output_padding = packed_params.output_padding()\n    return ConvPackedParam(\n        weight_np,\n        bias,\n        scale,\n        zero_point,\n        stride,\n        padding,\n        dilation,\n        groups,\n        output_padding,\n    )\n\n\ndef get_weight_quant_params(script_module, packed_param_names):\n    \"\"\"Retrieve and unpack weight parameters from quantized modules\"\"\"\n    import torch\n\n    param_name = \"_packed_params\"\n    quant_params = {}\n\n    def filter_func(named_module):\n        m = named_module[1]\n        return isinstance(m, torch.jit.RecursiveScriptModule) and (\n            (\"Conv\" in m.original_name) or (m.original_name == \"LinearPackedParams\")\n        )\n\n    for name, m in filter(filter_func, script_module.named_modules()):\n        key = name + \".\" + param_name\n        state_dict = m.state_dict()\n\n        if key not in packed_param_names:\n            continue\n\n        if len(state_dict) == 0 and not hasattr(m, param_name):\n            # for v1.6 and above\n            # This case seems to happen if a model is serialized\n            # and loaded back\n            # This module can be safely ignored\n            continue\n\n        if len(state_dict) == 0 and hasattr(m, param_name):\n            # for v1.6 and above\n            packed_params = m._packed_params\n        else:\n            assert len(state_dict) == 1\n            packed_params = list(state_dict.values())[0]\n\n        if \"Conv\" in m.original_name and len(state_dict) == 0:\n            qweight, bias = torch.ops.quantized.conv2d_unpack(packed_params)\n            quant_params[key] = make_conv_packed_param(qweight, bias, packed_params)\n        elif \"Conv\" in m.original_name:\n            qweight, bias = torch.ops.quantized.conv2d_unpack(packed_params)\n            quant_params[key] = make_qnn_param(qweight, bias)\n        elif m.original_name == \"LinearPackedParams\":\n            qweight, bias = torch.ops.quantized.linear_unpack(packed_params)\n            quant_params[key] = make_qnn_param(qweight, bias)\n\n    return quant_params\n\n\ndef quantize_numpy(weight, scale, zero_point, out_dtype_np):\n    iinfo = np.iinfo(out_dtype_np)\n    clip_min = iinfo.min\n    clip_max = iinfo.max\n    if len(scale.shape) > 0:\n        scale = np.reshape(scale, [weight.shape[0]] + [1] * (len(weight.shape) - 1))\n    transformed = zero_point + weight / scale\n    return np.clip(np.round(transformed), clip_min, clip_max).astype(out_dtype_np)\n\n\ndef add_quant_params_to_outputs(\n    outputs, packed_param_map, quant_params, input_scales_for_bias, keep_quantized_weight=False\n):\n    \"\"\"\n    Add quant params to outputs so that they can be referenced by other\n    ops later. Weights are quantized here.\n    \"\"\"\n    for node_name, packed_param_name in packed_param_map.items():\n        qparam = quant_params[packed_param_name]\n        weight_scale = _get_numpy(qparam.scale)\n        param_prefix = packed_param_name[: -len(\"._packed_params\")]\n\n        if keep_quantized_weight:\n            qparam.weight_var = _expr.var(\n                param_prefix + \"_weight\", shape=qparam.weight.shape, dtype=\"int8\"\n            )\n            qparam.weight = quantize_numpy(\n                qparam.weight, weight_scale, _get_numpy(qparam.zero_point), np.int8\n            )\n            qweight = qparam.weight_var\n        else:\n            qparam.weight_var = _expr.var(\n                param_prefix + \"_weight\", shape=qparam.weight.shape, dtype=\"float32\"\n            )\n            qweight = relay.qnn.op.quantize(\n                qparam.weight_var, qparam.scale, qparam.zero_point, out_dtype=\"int8\", axis=0\n            )\n\n        if qparam.bias is not None:\n            float_bias_var = _expr.var(\n                param_prefix + \"_bias\", shape=qparam.bias.shape, dtype=\"float32\"\n            )\n            if node_name not in input_scales_for_bias:\n                # This case is for dynamic quantization, where the input activation scale is\n                # unknown until runtime.\n                qparam.bias_var = float_bias_var\n                qbias = qparam.bias_var\n            elif keep_quantized_weight:\n                qparam.bias_var = _expr.var(\n                    param_prefix + \"_bias\", shape=qparam.bias.shape, dtype=\"int32\"\n                )\n                qparam.bias = quantize_numpy(\n                    qparam.bias, input_scales_for_bias[node_name] * weight_scale, 0, np.int32\n                )\n                qbias = qparam.bias_var\n            else:\n                qparam.bias_var = float_bias_var\n                qbias = relay.qnn.op.quantize(\n                    qparam.bias_var,\n                    _expr.const(input_scales_for_bias[node_name] * weight_scale),\n                    _expr.const(0, \"int32\"),\n                    out_dtype=\"int32\",\n                    axis=0,\n                )\n        else:\n            qbias = None\n\n        quant_params[packed_param_name] = qparam\n\n        params = [qweight, qparam.scale, qparam.zero_point, qbias]\n\n        if isinstance(quant_params[packed_param_name], ConvPackedParam):\n            params += [\n                qparam.stride,\n                qparam.padding,\n                qparam.dilation,\n                qparam.groups,\n                qparam.output_padding,\n            ]\n\n        outputs[node_name] = params\n\n\ndef _get_quant_param_for_input(input_value):\n    \"\"\"\n    We want to know the input scale and zp of this input_value, since\n    input quant params are not explicitly passed around in torch (they\n    are embedded in a QTensor data structure, not visible statically).\n    We know that it is quantized using output scale and zp\n    of some previous quantized op. The purpose of this function\n    is to find that pair of parameters.\n    \"\"\"\n    # Indices for output scale and zp\n    # For example, in quantized::conv2d(%input, %1, %2, %3, %4, %5, %6, %7),\n    # 6th and 7th arg are output scale and zp respectively.\n\n    # PyTorch 1.6 changed qconv API\n    if is_version_greater_than(\"1.5.1\"):\n        qconv_indices = (2, 3)\n    else:\n        qconv_indices = (6, 7)\n\n    output_quant_param_indices = {\n        \"aten::quantize_per_tensor\": (1, 2),\n        \"quantized::conv2d\": qconv_indices,\n        \"quantized::conv2d_relu\": qconv_indices,\n        \"quantized::linear\": (2, 3),\n        \"quantized::linear_relu\": (2, 3),\n        \"quantized::add_relu\": (2, 3),\n        \"quantized::add\": (2, 3),\n        \"quantized::mul_relu\": (2, 3),\n        \"quantized::mul\": (2, 3),\n        \"quantized::cat\": (2, 3),\n        \"quantized::mul_scalar\": (2, 3),\n        \"quantized::add_scalar\": (2, 3),\n        \"quantized::hardswish\": (1, 2),\n        \"quantized::conv_transpose2d\": qconv_indices,\n        \"quantized::leaky_relu\": (3, 4),\n        \"aten::sigmoid\": (1, 2),\n    }\n\n    def dfs(current_node):\n        # trace back to find the producer of this input value\n        current_op = current_node.kind()\n        if current_op in output_quant_param_indices:\n            indices = output_quant_param_indices[current_op]\n            scale = current_node.inputsAt(indices[0])\n            zp = current_node.inputsAt(indices[1])\n            return scale, zp\n\n        # Trace back eariler nodes, dfs order\n        # Assume quantized tensor comes earlier in the args\n        for arg in current_node.inputs():\n            return dfs(arg.node())\n\n        # If input_value is not quantized, we reach here.\n        return None, None\n\n    return dfs(input_value.node())\n\n\ndef _get_add_scalar_output_quant_param(input_scale, input_zero_point, scalar):\n    \"\"\"\n    Determine the output scale and zp of quantized::add_scalar op\n    This is used for mobilenet v3\n    Refer to aten/src/ATen/native/quantized/cpu/qadd.cpp\n    The names of variables are the same as torch impl\n    \"\"\"\n    q_min = 0\n    q_max = 255\n    s = input_scale\n    z = input_zero_point\n    c = scalar\n    c_q = round(c / s)\n\n    if q_min > z - c_q:\n        s_prime = (float(q_max) - (z - c_q)) / (float(q_max) - q_min) * s\n        z_prime = q_min\n    elif q_max < z - c_q:\n        s_prime = (float(z - c_q) - q_min) / (float(q_max) - q_min) * s\n        z_prime = q_max\n    else:\n        s_prime = s\n        z_prime = z - c_q\n\n    return s_prime, z_prime\n\n\ndef _get_mul_scalar_output_quant_param(input_scale, input_zero_point, scalar):\n    \"\"\"\n    Determine the output scale and zp of quantized::mul_scalar op\n    This is used for mobilenet v3\n    Refer to aten/src/ATen/native/quantized/cpu/qmul.cpp\n    The names of variables are the same as torch impl\n    \"\"\"\n    q_min = 0\n    q_max = 255\n    self_scale = input_scale\n    self_zero_point = input_zero_point\n    other_val = scalar\n\n    if other_val > 0.0:\n        s_prime = other_val * self_scale\n        z_prime = self_zero_point\n    elif other_val == 0.0:\n        s_prime = 1.0\n        z_prime = 0\n    else:\n        s_prime = abs(other_val) * self_scale\n        z_prime = q_max - (self_zero_point - q_min)\n\n    return s_prime, z_prime\n\n\ndef _add_output_quant_params_to_scalar_op(node, graph, input_scale, input_zero_point, scalar):\n    \"\"\"\n    The output scale and zp of {add,mul}_scalar op are not explicit in the IR\n    They are required for _get_quant_param_for_input above to work correctly\n    So calculate these params using the same way torch does, and make new\n    constant nodes in the input IR. Also add these params to the inputs of\n    scalar op.\n\n    For example,\n       %6 : float = prim::Constant[value=3.]()\n       %input : QUInt8(1, 3, 224, 224) = quantized::add_scalar(%x.1, %6)\n    becomes\n       %6 : float = prim::Constant[value=3.]()\n       %7 : float = prim::Constant[value=0.015686161816120148]()\n       %8 : int = prim::Constant[value=0]()\n       %input : UInt8(1, 3, 224, 224) = quantized::add_scalar(%x.1, %6, %7, %8)\n\n    %7 and %8 are newly created output scale and zp constant nodes\n    \"\"\"\n    # pylint: disable=c-extension-no-member\n    import torch\n\n    operator = node.kind()\n\n    if operator == \"quantized::mul_scalar\":\n        out_scale, out_zero_point = _get_mul_scalar_output_quant_param(\n            input_scale, input_zero_point, scalar\n        )\n    elif operator == \"quantized::add_scalar\":\n        out_scale, out_zero_point = _get_add_scalar_output_quant_param(\n            input_scale, input_zero_point, scalar\n        )\n    else:\n        raise NotImplementedError(\"unsupported scalar op: %s\" % operator)\n\n    # create new constant nodes and add them to graph\n    out_scale_node = graph.create(\"prim::Constant\")\n    out_zero_point_node = graph.create(\"prim::Constant\")\n    out_scale_node.insertBefore(node)\n    out_zero_point_node.insertBefore(node)\n    out_scale_node.f_(\"value\", out_scale)\n    out_zero_point_node.i_(\"value\", out_zero_point)\n    out_scale_node.output().setType(torch._C.FloatType.get())\n    out_zero_point_node.output().setType(torch._C.IntType.get())\n    node.addInput(out_scale_node.output())\n    node.addInput(out_zero_point_node.output())\n\n\ndef _add_output_quant_params_to_sigmoid_op(node, graph):\n    \"\"\"\n    Refer to aten/src/ATen/native/quantized/cpu/qsigmoid.cpp,\n    the output scale and zp of sigmoid op are two fixed numbers.\n    So we need to make two new constant nodes in the input IR and\n    add these params to the inputs of sigmoid op.\n    \"\"\"\n    # pylint: disable=c-extension-no-member\n    import torch\n\n    # suppose scale_type is uint8\n    out_scale = 1.0 / 256\n    out_zero_point = 0\n\n    # create new constant nodes and add them to graph\n    out_scale_node = graph.create(\"prim::Constant\")\n    out_zero_point_node = graph.create(\"prim::Constant\")\n    out_scale_node.insertBefore(node)\n    out_zero_point_node.insertBefore(node)\n    out_scale_node.f_(\"value\", out_scale)\n    out_zero_point_node.i_(\"value\", out_zero_point)\n    out_scale_node.output().setType(torch._C.FloatType.get())\n    out_zero_point_node.output().setType(torch._C.IntType.get())\n    node.addInput(out_scale_node.output())\n    node.addInput(out_zero_point_node.output())\n\n\ndef add_input_quant_params_to_op_inputs(graph):\n    \"\"\"\n    In Torch, input quant params are not explicitly passed around\n    Instead, they are stored in QTensor data structure, and retrieved\n    at runtime by each quantized ops.\n    However, they need to be known statically for QNN translation.\n    To workaround and simplify the translation of inputs, we manually add\n    input quant params to inputs of Torch quantized operators listed below.\n    See _quantized_conv2d() below for example of why this is helpful.\n\n    For example,\n      %input : QUInt8(1, 512, 7, 7) = quantized::add(%x.8, %x.9, %434, %435)\n    becomes\n      %395 : float = prim::Constant[value=0.036212071776390076]()\n      %396 : int = prim::Constant[value=0]()\n      %430 : float = prim::Constant[value=0.16080744564533234]()\n      %431 : int = prim::Constant[value=42]()\n      %input : QUInt8(1, 512, 7, 7) = quantized::add(%x.8, %x.9, %434, %435,\n                                                     %430, %431, %395, %396)\n\n    %434, %435 are output scale and zp of quantized::add op\n    %430, %431, %395, %396 are two pairs of input (scale, zp) for two tensors\n    added by this function\n    \"\"\"\n    # How many quantized tensors each op takes as inputs?\n    # A pair of (scale, zp) for each input quantized tensor will be added\n    # to the input nodes\n    num_quantized_inputs = {\n        \"quantized::conv2d\": 1,\n        \"quantized::conv2d_relu\": 1,\n        \"quantized::linear\": 1,\n        \"quantized::linear_relu\": 1,\n        \"quantized::add_relu\": 2,\n        \"quantized::add\": 2,\n        \"quantized::mul_relu\": 2,\n        \"quantized::mul\": 2,\n        \"aten::dequantize\": 1,\n        \"aten::mean\": 1,\n        \"aten::sigmoid\": 1,\n        \"aten::upsample_nearest2d\": 1,\n        \"aten::upsample_bilinear2d\": 1,\n        \"aten::relu_\": 1,\n        \"aten::relu\": 1,\n        \"quantized::add_scalar\": 1,\n        \"quantized::mul_scalar\": 1,\n        \"quantized::relu6\": 1,\n        \"quantized::hardswish\": 1,\n        \"aten::hardsigmoid\": 1,\n        \"quantized::conv_transpose2d\": 1,\n        \"quantized::leaky_relu\": 1,\n    }\n\n    need_input_quant_param = set(num_quantized_inputs.keys())\n    need_input_quant_param.add(\"quantized::cat\")\n\n    input_scales_for_bias = {}\n\n    for node in graph.nodes():\n        operator = node.kind()\n        if operator not in need_input_quant_param:\n            continue\n\n        input_scales = []\n        input_zero_points = []\n\n        if operator == \"quantized::cat\":\n            # the number of inputs to concat is not constant\n            # so handle it separately\n            inputs = node.inputsAt(0).node().inputs()\n            for inp in inputs:\n                scale, zp = _get_quant_param_for_input(inp)\n                input_scales.append(scale)\n                input_zero_points.append(zp)\n        else:\n            for i in range(num_quantized_inputs[operator]):\n                scale, zp = _get_quant_param_for_input(node.inputsAt(i))\n                if scale is not None and zp is not None:\n                    input_scales.append(scale)\n                    input_zero_points.append(zp)\n\n        if operator in [\"quantized::add_scalar\", \"quantized::mul_scalar\"]:\n            scalar = node.inputsAt(1).node().f(\"value\")\n            inp_scale = input_scales[0].node().f(\"value\")\n            inp_zero_point = input_zero_points[0].node().i(\"value\")\n\n            # see the comments in this function above\n            _add_output_quant_params_to_scalar_op(node, graph, inp_scale, inp_zero_point, scalar)\n\n        if operator == \"aten::sigmoid\":\n            _add_output_quant_params_to_sigmoid_op(node, graph)\n\n        for scale, zp in zip(input_scales, input_zero_points):\n            node.addInput(scale)\n            node.addInput(zp)\n\n        if \"quantized::conv\" in operator or \"quantized::linear\" in operator:\n            # This is required for quantizing the bias\n            assert len(input_scales) == 1, \"One quantized parameter expected for qconv or qlinear.\"\n            input_scales_for_bias[node.inputsAt(1).debugName()] = input_scales[0].node().f(\"value\")\n\n    return input_scales_for_bias\n\n\ndef add_quant_params(params, quant_params):\n    \"\"\"Add quant parameters to TVM param map\"\"\"\n    for qparam in quant_params.values():\n        params[qparam.weight_var.name_hint] = tvm.nd.array(qparam.weight)\n        if qparam.bias is not None:\n            params[qparam.bias_var.name_hint] = tvm.nd.array(qparam.bias)\n\n\ndef inline_input_quant_params_for_fx(graph, params):\n    \"\"\"\n    Canonicalize input scale and zero point access for FX-quantized graphs.\n    We expect input qparams to aten::quantize_per_tensor to be prim::Constant, but that's\n    not the case for FX-based quantized models as shown below.\n    We replace prim::GetAttr with prim::Constant so that FX-based quantized models can be\n    converted in the same way as eager-mode based quantized models.\n\n    Before:\n    %pan_input_zero_point_1 : Tensor = prim::GetAttr[name=\"pan_input_zero_point_1\"](%backbone)\n    %pan_input_scale_1 : Tensor = prim::GetAttr[name=\"pan_input_scale_1\"](%backbone)\n    ...\n    %quantize_per_tensor_2 ... = aten::quantize_per_tensor(...,\n                                       %pan_input_scale_1, %pan_input_zero_point_1, ...)\n\n    After:\n    %2402 : int = prim::Constant[value=0]()\n    %2403 : float = prim::Constant[value=1.]()\n    %quantize_per_tensor_2 ...  = aten::quantize_per_tensor(..., %2403, %2402, ...)\n    \"\"\"\n    # pylint: disable=c-extension-no-member\n    import torch\n\n    def get_full_attr_name(current):\n        current_attr = getattr_attr_name(current)\n        inputs = list(current.inputs())\n        if len(inputs) == 1 and inputs[0].node().kind() == \"prim::GetAttr\":\n            return get_full_attr_name(inputs[0].node()) + \".\" + current_attr\n        return current_attr\n\n    for node in graph.findAllNodes(\"prim::GetAttr\", recurse=True):\n        out_name = node.output().debugName()\n\n        if \"_scale\" in out_name or \"_zero_point\" in out_name:\n            full_attr = get_full_attr_name(node)\n            assert full_attr in params, \"%s not found in param dict.\" % full_attr\n            param_np = params[full_attr].numpy()\n            new_const_node = graph.create(\"prim::Constant\")\n            new_const_node.insertBefore(node)\n\n            if \"_scale\" in out_name:\n                new_const_node.f_(\"value\", param_np)\n                new_const_node.output().setType(torch._C.FloatType.get())\n            else:\n                new_const_node.i_(\"value\", param_np.item())\n                new_const_node.output().setType(torch._C.IntType.get())\n\n            node.replaceAllUsesWith(new_const_node)\n\n\ndef apply_with_upcast(data, func):\n    inp = _op.cast(data, dtype=\"int32\")\n    out = func(inp)\n    return _op.cast(out, \"uint8\")\n\n\ndef apply_with_fp32_fallback(data, input_scale, input_zero_point, func_fp32):\n    dequantized = relay.qnn.op.dequantize(data, input_scale, input_zero_point)\n    out = func_fp32(dequantized)\n    return relay.qnn.op.quantize(out, input_scale, input_zero_point, out_dtype=\"uint8\", axis=1)\n\n\ndef quantized_relu(data, input_zero_point):\n    # refer to aten/src/ATen/native/quantized/cpu/qrelu.cpp\n    zp = _op.cast(input_zero_point, dtype=\"uint8\")\n    return _op.tensor.maximum(data, zp)\n\n\ndef quantized_sigmoid(inputs):\n    data = inputs[0]\n    output_scale = _expr.const(inputs[1])\n    output_zero_point = _expr.const(inputs[2])\n    input_scale = _expr.const(inputs[3])\n    input_zero_point = _expr.const(inputs[4])\n    return relay.qnn.op.sigmoid(\n        data, input_scale, input_zero_point, output_scale, output_zero_point\n    )\n\n\ndef _quantize_per_tensor():\n    def _impl(inputs, _):\n        dim = len(infer_shape(inputs[0]))\n        if dim > 1:\n            axis = 1\n        else:\n            axis = 0\n\n        return relay.qnn.op.quantize(\n            inputs[0], _expr.const(inputs[1]), _expr.const(inputs[2]), out_dtype=\"uint8\", axis=axis\n        )\n\n    return _impl\n\n\ndef _dequantize():\n    def _impl(inputs, _):\n        assert len(inputs) == 3, \"Input quant params not found in op inputs\"\n        inp_scale = _expr.const(inputs[1])\n        inp_zero_point = _expr.const(inputs[2])\n        return relay.qnn.op.dequantize(inputs[0], inp_scale, inp_zero_point)\n\n    return _impl\n\n\ndef _get_numpy(relay_const_scalar):\n    return relay_const_scalar.data.numpy()\n\n\ndef _get_scalar(relay_const_scalar):\n    return _get_numpy(relay_const_scalar).item(0)\n\n\ndef _do_bias_and_requantize(\n    output, bias, input_scale, weight_scale, output_scale, output_zero_point, with_relu\n):\n    \"\"\"Output processing for conv and linear\"\"\"\n    # this is a vector for per channel case\n    requant_input_scale = _expr.const(_get_numpy(input_scale) * _get_numpy(weight_scale))\n    # Torch does bias add and requanize scale in fp32\n    # refer to third_party/fbgemm/include/fbgemm/OutputProcessing-inl.h\n    # Instead, we do bias add in int32 and use qnn requantize, which needs\n    # integer input.\n    # We observed no loss in accuracy in doing this way, and it is better\n    # for tvm because bias quantization can be done at compile time\n    # Instead, the torch way requires rounding of activation at runtime\n\n    if bias is not None:\n        requantize_input = _op.nn.bias_add(output, bias)\n    else:\n        requantize_input = output\n\n    requantized = relay.qnn.op.requantize(\n        requantize_input,\n        requant_input_scale,\n        relay.const(0, \"int32\"),\n        output_scale,\n        output_zero_point,\n        out_dtype=\"int32\",\n        axis=1,\n    )\n    clip_min = 0\n    if with_relu:\n        clip_min = _get_scalar(output_zero_point)\n\n    clip = _op.tensor.clip(requantized, clip_min, 255.0)\n    return _op.cast(clip, dtype=\"uint8\")\n\n\ndef _quantized_conv2d(with_relu=False):\n    def _impl(inputs, _):\n        # refer to src/ATen/native/quantized/cpu/qconv.cpp\n        # inputs[0]: input tensor\n        # inputs[1]: (weight, scale, zero_point, bias)\n        # inputs[2-5]: stride, padding, dilation, groups\n        # inputs[6]: output_scale\n        # inputs[7]: output_zero_point\n        # inputs[8]: input_scale (added manually by frontend)\n        # inputs[9]: input_zero_point (added manually by frontend)\n        conv_params = inputs[1]\n        weight = conv_params[0]\n        weight_scale = conv_params[1]\n        weight_zero_point = conv_params[2]\n        bias = conv_params[3]\n\n        if len(conv_params) > 4:\n            # Torch 1.6 or newer case\n            strides = conv_params[4]\n            padding = conv_params[5]\n            dilation = conv_params[6]\n            groups = conv_params[7]\n\n            output_scale = _expr.const(inputs[2])\n            output_zero_point = _expr.const(inputs[3])\n\n            assert len(inputs) == 6, \"Input quant params not found in op inputs\"\n\n            # These are manually added by add_input_quant_params_to_op_inputs above\n            # In torch, they are retrieved from QTensor data structure at runtime\n            input_scale = _expr.const(inputs[4])\n            input_zero_point = _expr.const(inputs[5])\n        else:\n            strides = inputs[2]\n            padding = inputs[3]\n            dilation = inputs[4]\n            groups = inputs[5]\n            output_scale = _expr.const(inputs[6])\n            output_zero_point = _expr.const(inputs[7])\n\n            assert len(inputs) == 10, \"Input quant params not found in op inputs\"\n\n            input_scale = _expr.const(inputs[8])\n            input_zero_point = _expr.const(inputs[9])\n\n        weight_shape = infer_shape(weight)\n        kernel_size = (weight_shape[2], weight_shape[3])\n        out_channels = weight_shape[0]\n\n        if padding[0] != 0 or padding[1] != 0:\n            pad_val = _get_scalar(input_zero_point)\n            inp = _op.nn.pad(\n                inputs[0],\n                pad_width=((0, 0), (0, 0), (padding[0], padding[0]), (padding[1], padding[1])),\n                pad_value=float(pad_val),\n            )\n        else:\n            inp = inputs[0]\n\n        # padding is (0, 0) because we did explicit pad op with\n        # pad value being zero point above\n        conv_out = relay.qnn.op.conv2d(\n            inp,\n            weight,\n            input_zero_point,\n            weight_zero_point,\n            input_scale,\n            weight_scale,\n            kernel_size=kernel_size,\n            dilation=dilation,\n            strides=strides,\n            padding=(0, 0),\n            groups=groups,\n            channels=out_channels,\n        )\n\n        return _do_bias_and_requantize(\n            conv_out, bias, input_scale, weight_scale, output_scale, output_zero_point, with_relu\n        )\n\n    return _impl\n\n\ndef _linear(with_relu=False):\n    # similar to conv\n    def _impl(inputs, _):\n        weight = inputs[1][0]\n        weight_scale = inputs[1][1]\n        weight_zero_point = inputs[1][2]\n        output_scale = _expr.const(inputs[2])\n        output_zero_point = _expr.const(inputs[3])\n        assert len(inputs) == 6, \"Input quant params not found in op inputs\"\n        # Manually added by add_input_quant_params_to_op_inputs above\n        input_scale = _expr.const(inputs[4])\n        input_zero_point = _expr.const(inputs[5])\n\n        weight_shape = infer_shape(weight)\n        dense = relay.qnn.op.dense(\n            inputs[0],\n            weight,\n            input_zero_point,\n            weight_zero_point,\n            input_scale,\n            weight_scale,\n            units=weight_shape[0],\n        )\n        bias_var = inputs[1][3]\n\n        return _do_bias_and_requantize(\n            dense, bias_var, input_scale, weight_scale, output_scale, output_zero_point, with_relu\n        )\n\n    return _impl\n\n\ndef _binop(relay_op, with_relu=False, fp32_piggy_back=False):\n    def qnn_impl(\n        lhs,\n        rhs,\n        input_scale_lhs,\n        input_zero_point_lhs,\n        input_scale_rhs,\n        input_zero_point_rhs,\n        output_scale,\n        output_zero_point,\n    ):\n        qnn_out = relay_op(\n            lhs,\n            rhs,\n            input_scale_lhs,\n            input_zero_point_lhs,\n            input_scale_rhs,\n            input_zero_point_rhs,\n            output_scale,\n            output_zero_point,\n        )\n        if with_relu:\n            clip_min = _get_scalar(output_zero_point)\n            return _op.tensor.clip(qnn_out, clip_min, 255)\n        return qnn_out\n\n    # refer to aten/src/ATen/native/quantized/cpu/{qadd, qmul}.cpp\n    # they piggy backs to fp32 math by dequantize -> fp32 math -> quantize\n    def torch_impl(\n        lhs,\n        rhs,\n        input_scale_lhs,\n        input_zero_point_lhs,\n        input_scale_rhs,\n        input_zero_point_rhs,\n        output_scale,\n        output_zero_point,\n    ):\n        if isinstance(lhs, _expr.Call) and lhs.op.name == \"qnn.quantize\":\n            lhs = lhs.args[0]\n        else:\n            lhs = relay.qnn.op.dequantize(lhs, input_scale_lhs, input_zero_point_lhs)\n\n        if isinstance(rhs, _expr.Call) and rhs.op.name == \"qnn.quantize\":\n            rhs = rhs.args[0]\n        else:\n            rhs = relay.qnn.op.dequantize(rhs, input_scale_rhs, input_zero_point_rhs)\n        fp32_out = relay_op(lhs, rhs)\n\n        if with_relu:\n            fp32_out = _op.nn.relu(fp32_out)\n\n        return relay.qnn.op.quantize(\n            fp32_out, output_scale, output_zero_point, axis=-1, out_dtype=\"uint8\"\n        )\n\n    def _impl(inputs, _):\n        lhs = inputs[0]\n        rhs = inputs[1]\n        output_scale = _expr.const(inputs[2])\n        output_zero_point = _expr.const(inputs[3])\n        assert len(inputs) == 8, \"Input quant params not found in op inputs\"\n        # Manually added by add_input_quant_params_to_op_inputs above\n        input_scale_lhs = _expr.const(inputs[4])\n        input_zero_point_lhs = _expr.const(inputs[5])\n        input_scale_rhs = _expr.const(inputs[6])\n        input_zero_point_rhs = _expr.const(inputs[7])\n\n        if fp32_piggy_back:\n            logger.info(\"Piggy backing to FP32 op (PyTorch way)\")\n            return torch_impl(\n                lhs,\n                rhs,\n                input_scale_lhs,\n                input_zero_point_lhs,\n                input_scale_rhs,\n                input_zero_point_rhs,\n                output_scale,\n                output_zero_point,\n            )\n\n        return qnn_impl(\n            lhs,\n            rhs,\n            input_scale_lhs,\n            input_zero_point_lhs,\n            input_scale_rhs,\n            input_zero_point_rhs,\n            output_scale,\n            output_zero_point,\n        )\n\n    return _impl\n\n\ndef _cat(fp32_piggy_back=False):\n    # refer to aten/src/ATen/native/quantized/cpu/qconcat.cpp\n    # for concat they also piggy backs to fp32(!)\n    # dequantize -> fp32 math -> quantize\n    def torch_impl(inputs, input_scales, input_zero_points, output_scale, output_zero_point, axis):\n        dequantized = []\n        for inp, inp_scale, inp_zp in zip(inputs, input_scales, input_zero_points):\n            dequantized.append(relay.qnn.op.dequantize(inp, inp_scale, inp_zp))\n\n        concat = _op.tensor.concatenate(dequantized, axis=axis)\n        return relay.qnn.op.quantize(\n            concat, output_scale, output_zero_point, axis=axis, out_dtype=\"uint8\"\n        )\n\n    def _impl(inputs, _):\n        axis = inputs[1]\n        output_scale = _expr.const(inputs[2])\n        output_zero_point = _expr.const(inputs[3])\n        num_inputs = (len(inputs) - 4) // 2\n\n        input_scales = []\n        input_zero_points = []\n\n        for i in range(0, num_inputs):\n            input_scales.append(_expr.const(inputs[4 + i * 2]))\n            input_zero_points.append(_expr.const(inputs[4 + i * 2 + 1]))\n\n        if fp32_piggy_back:\n            return torch_impl(\n                inputs[0], input_scales, input_zero_points, output_scale, output_zero_point, axis\n            )\n\n        return relay.qnn.op.concatenate(\n            inputs[0], input_scales, input_zero_points, output_scale, output_zero_point, axis\n        )\n\n    return _impl\n\n\ndef _add_scalar():\n    # this is used for mobilenet v3\n    def _impl(inputs, _):\n        # refer to aten/src/ATen/native/quantized/cpu/qadd.cpp\n        assert len(inputs) == 6, \"Input quant params not found in op inputs\"\n        s = inputs[4]\n        z = inputs[5]\n        c = inputs[1]\n        c_q = round(c / s)\n        q_min = 0\n        q_max = 255\n\n        # math for calculating output scale and zp are already done\n        # during _add_output_quant_params_to_scalar_op above\n        out_scale = _expr.const(inputs[2])\n        out_zp = _expr.const(inputs[3])\n\n        if q_min > z - c_q or q_max < z - c_q:\n            # TODO(masahi): Replace this with integer only compute\n            dequant = relay.qnn.op.dequantize(inputs[0], _expr.const(s), _expr.const(z))\n            dequantized_add = _op.tensor.add(dequant, _expr.const(c_q * s))\n            return relay.qnn.op.quantize(\n                dequantized_add, out_scale, out_zp, axis=1, out_dtype=\"uint8\"\n            )\n        # only scale change\n        return inputs[0]\n\n    return _impl\n\n\ndef quantize_scalar(data, scale, zero_point):\n    # used to quantize 6., in mobilenet v3\n    transformed = zero_point + data / scale\n    return max(0, min(round(transformed), 255))\n\n\ndef _relu6():\n    # refer to src/ATen/native/quantized/cpu/qrelu.cpp\n    def _impl(inputs, _):\n        assert len(inputs) == 4, \"Input quant params not found in op inputs\"\n        input_scale = inputs[2]\n        input_zero_point = inputs[3]\n        six = quantize_scalar(6.0, input_scale, input_zero_point)\n        return _op.tensor.clip(inputs[0], input_zero_point, six)\n\n    return _impl\n\n\ndef _leaky_relu(fp32_piggy_back=False):\n    # refer to src/ATen/native/quantized/cpu/qrelu.cpp\n    def _impl_fp32(inputs, _):\n        alpha = inputs[1]\n        output_scale = _expr.const(inputs[3])\n        output_zero_point = _expr.const(inputs[4])\n        input_scale = _expr.const(inputs[5])\n        input_zero_point = _expr.const(inputs[6])\n        dequant = relay.qnn.op.dequantize(inputs[0], input_scale, input_zero_point)\n        dequantized = _op.nn.leaky_relu(dequant, alpha)\n        return relay.qnn.op.quantize(\n            dequantized, output_scale, output_zero_point, out_dtype=\"uint8\"\n        )\n\n    def _impl_int8(inputs, _):\n        alpha = inputs[1]\n        output_scale = _expr.const(inputs[3])\n        output_zero_point = _expr.const(inputs[4])\n        input_scale = _expr.const(inputs[5])\n        input_zero_point = _expr.const(inputs[6])\n        return relay.qnn.op.leaky_relu(\n            inputs[0], alpha, input_scale, input_zero_point, output_scale, output_zero_point\n        )\n\n    def _impl(inputs, _):\n        assert len(inputs) == 7, \"Input quant params not found in op inputs\"\n        if fp32_piggy_back:\n            return _impl_fp32(inputs, _)\n        return _impl_int8(inputs, _)\n\n    return _impl\n\n\ndef _mul_scalar():\n    # this is used for mobilenet v3\n    def _impl(inputs, _):\n        # refer to aten/src/ATen/native/quantized/cpu/qmul.cpp\n        # math for calculating output scale and zp are already done\n        # during _add_output_quant_params_to_scalar_op above\n        assert len(inputs) == 6, \"Input quant params not found in op inputs\"\n        other_val = inputs[1]  # scalar\n\n        if other_val > 0.0:\n            # only scale change\n            return inputs[0]\n        if other_val == 0.0:\n            shape = infer_shape(inputs[0])\n            return _op.full(_expr.const(0), shape, dtype=\"uint8\")\n\n        # negative scale case\n        q_min = 0\n        q_max = 255\n        bias = _expr.const(q_max + q_min, dtype=\"int8\")\n        int8 = bias - _op.cast(inputs[0], \"int8\")\n        return _op.cast(int8, \"uint8\")\n\n    return _impl\n\n\ndef _hswish(fp32_piggy_back=False):\n    def _impl_fp32(inputs):\n        # refer to src/ATen/native/quantized/cpu/kernels/QuantizedOpKernels.cpp\n        # They fallback to fp32\n        def relu6(x):\n            return _op.tensor.clip(x, 0.0, 6.0)\n\n        def hardsigmoid(x):\n            dtype = \"float32\"\n            return relu6(x + _expr.const(3.0, dtype=dtype)) / _expr.const(6.0, dtype=dtype)\n\n        output_scale = _expr.const(inputs[1])\n        output_zero_point = _expr.const(inputs[2])\n        input_scale = _expr.const(inputs[3])\n        input_zero_point = _expr.const(inputs[4])\n\n        dequant = relay.qnn.op.dequantize(inputs[0], input_scale, input_zero_point, axis=1)\n        dequantized_hswish = dequant * hardsigmoid(dequant)\n        return relay.qnn.op.quantize(\n            dequantized_hswish, output_scale, output_zero_point, out_dtype=\"uint8\"\n        )\n\n    def _impl_int8(inputs):\n        output_scale = _expr.const(inputs[1])\n        output_zero_point = _expr.const(inputs[2])\n        input_scale = _expr.const(inputs[3])\n        input_zero_point = _expr.const(inputs[4])\n        return relay.qnn.op.hardswish(\n            inputs[0], input_scale, input_zero_point, output_scale, output_zero_point\n        )\n\n    def _impl(inputs, _):\n        assert len(inputs) == 5, \"Input quant params not found in op inputs\"\n        if fp32_piggy_back:\n            return _impl_fp32(inputs)\n        return _impl_int8(inputs)\n\n    return _impl\n\n\ndef _linear_dynamic():\n    def _calculate_qparam(inp):\n        # reference ATen/native/quantized/cpu/qlinear_dynamic.cpp\n        # ChooseQuantizationParams function\n        mn = _op.min(inp)\n        mx = _op.max(inp)\n\n        # Ensure that the interval contains 0\n        mn = _op.minimum(mn, _op.const(0.0, dtype=\"float32\"))\n        mx = _op.maximum(mx, _op.const(0.0, dtype=\"float32\"))\n\n        qmax = 255\n\n        # reduce_range became True in v1.6\n        if is_version_greater_than(\"1.5.1\"):\n            qmax = 127\n\n        scale = (mx - mn) / _expr.const(qmax, dtype=\"float32\")\n\n        zero_point_from_min = -(mn / scale)\n        zero_point = _op.cast(_op.round(_op.clip(zero_point_from_min, 0.0, qmax)), \"int32\")\n\n        return scale, zero_point\n\n    def _impl(inputs, _):\n        weight = inputs[1][0]\n        weight_scale = inputs[1][1]\n        weight_zero_point = inputs[1][2]\n\n        inp = inputs[0]\n\n        input_scale, input_zero_point = _calculate_qparam(inp)\n        qinp = relay.qnn.op.quantize(inp, input_scale, input_zero_point, out_dtype=\"uint8\")\n\n        data_shape = infer_shape(inp)\n\n        if len(data_shape) > 2:\n            qinp = _op.reverse_reshape(qinp, [-1, 0])\n\n        weight_shape = infer_shape(weight)\n        units = weight_shape[0]\n        dense = relay.qnn.op.dense(\n            qinp,\n            weight,\n            input_zero_point,\n            weight_zero_point,\n            input_scale,\n            weight_scale,\n            units=units,\n        )\n        bias_var = inputs[1][3]\n\n        dequant_scale = input_scale * weight_scale\n        dense_out = relay.qnn.op.dequantize(\n            dense, dequant_scale, input_zero_point=relay.const(0, \"int32\"), axis=1\n        )\n\n        if len(data_shape) > 2:\n            new_shape = list(data_shape[:-1])\n            new_shape.append(units)\n            dense_out = _op.reshape(dense_out, new_shape)\n\n        if bias_var is not None:\n            return dense_out + bias_var\n\n        return dense_out\n\n    return _impl\n\n\ndef _quantized_conv_transpose2d(with_relu=False):\n    def _impl(inputs, _):\n        # Refer to aten/src/ATen/native/quantized/cpu/qconv.cpp\n        # Supported in Torch 1.7 or newer\n        conv_params = inputs[1]\n        weight = conv_params[0]\n        weight_scale = conv_params[1]\n        weight_zero_point = conv_params[2]\n        bias = conv_params[3]\n\n        strides = conv_params[4]\n        padding = conv_params[5]\n        dilation = conv_params[6]\n        groups = conv_params[7]\n        output_padding = conv_params[8]\n\n        output_scale = _expr.const(inputs[2])\n        output_zero_point = _expr.const(inputs[3])\n\n        assert len(inputs) == 6, \"Input quant params not found in op inputs\"\n\n        # These are manually added by add_input_quant_params_to_op_inputs above\n        # In torch, they are retrieved from QTensor data structure at runtime\n        input_scale = _expr.const(inputs[4])\n        input_zero_point = _expr.const(inputs[5])\n\n        weight_shape = list(infer_shape(weight))\n\n        kernel_size = (weight_shape[2], weight_shape[3])\n        out_channels = weight_shape[1]\n\n        conv_out = relay.qnn.op.conv2d_transpose(\n            inputs[0],\n            weight,\n            input_zero_point,\n            weight_zero_point,\n            input_scale,\n            weight_scale,\n            kernel_size=kernel_size,\n            dilation=dilation,\n            strides=strides,\n            padding=padding,\n            groups=groups,\n            channels=out_channels,\n            output_padding=output_padding,\n            out_dtype=\"int32\",\n            kernel_layout=\"IOHW\",\n        )\n\n        return _do_bias_and_requantize(\n            conv_out, bias, input_scale, weight_scale, output_scale, output_zero_point, with_relu\n        )\n\n    return _impl\n\n\nconvert_map = {\n    \"aten::quantize_per_tensor\": _quantize_per_tensor(),\n    \"quantized::conv2d_relu\": _quantized_conv2d(with_relu=True),\n    \"aten::dequantize\": _dequantize(),\n    \"quantized::conv2d\": _quantized_conv2d(),\n    \"quantized::add_relu\": _binop(relay.qnn.op.add, with_relu=True),\n    \"quantized::add\": _binop(relay.qnn.op.add),\n    \"quantized::mul_relu\": _binop(relay.qnn.op.mul, with_relu=True),\n    \"quantized::mul\": _binop(relay.qnn.op.mul),\n    \"quantized::linear\": _linear(),\n    \"quantized::linear_relu\": _linear(with_relu=True),\n    \"quantized::cat\": _cat(),\n    \"quantized::add_scalar\": _add_scalar(),\n    \"quantized::mul_scalar\": _mul_scalar(),\n    \"quantized::relu6\": _relu6(),\n    \"quantized::leaky_relu\": _leaky_relu(),\n    \"quantized::linear_dynamic\": _linear_dynamic(),\n    \"quantized::hardswish\": _hswish(fp32_piggy_back=False),\n    \"quantized::conv_transpose2d\": _quantized_conv_transpose2d(),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tensorflow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n# pylint: disable=import-outside-toplevel, redefined-builtin\n\"\"\"TF: Tensorflow frontend.\"\"\"\nimport warnings\nfrom collections import defaultdict\n\n# Numpy support\nimport numpy as np\nimport tvm\n\nfrom tvm.ir import IRModule\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.transform import InferType\n\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom ..ty import Any\nfrom ..expr_functor import ExprMutator, ExprVisitor\nfrom .common import get_relay_op\nfrom .common import infer_type as _infer_type\nfrom .common import infer_shape as _infer_shape\nfrom .common import infer_value as _infer_value\n\nfrom .tensorflow_ops import _convert_map\nfrom .tensorflow_ops import _need_prelude_for_shape_inference\nfrom .tensorflow_ops import _get_more_static_shape\n\n__all__ = [\"from_tensorflow\"]\n\n# The default configurations of Relay TensorFlow frontend.\nTF_DEFAULT_CONFIGS = {\n    # By default, TVM converts `tf.matmul` to `transpose(weight) + nn.dense`, which introduces\n    # unnecessary overhead in weight transpose. Change this flag to False to directly convert to\n    # `nn.matmul` to get rid of the overhead.\n    # However, please note that `nn.matmul` is in experimental so it may have some performance\n    # issues.\n    \"use_dense\": True,\n    # By default, TVM converts `tf.batch_matmul` to `transpose(weight) + nn.batch_matmul_NT`.\n    # Change this flag to False to directly convert to `nn.batch_matmul`.\n    # Note that `nn.batch_matmul` with format other than NT is in experimental, it may have some\n    # performance issues.\n    \"use_nt_batch_matmul\": True,\n}\n\n# compatible operators that do NOT require any conversion.\n_identity_list = []\n\n# Operators that get pruned away when the complete graph is frozen.\n# These operators are not needed for inference.\n_freezed_graph_pruned_op_list = [\n    \"ReadVariableOp\",\n    \"ResourceGather\",\n    \"Variable\",\n    \"VariableV2\",\n    \"VarHandleOp\",\n    \"Assign\",\n    \"AssignVariableOp\",\n]\n\n# An internal list to contain all the control flow primitives used in Tensorflow\n# 1.x.\n_control_flow_nodes = [\"Merge\", \"Switch\", \"NextIteration\", \"Exit\", \"Enter\", \"LoopCond\"]\n\n# A map to record tensor array write ops and input ta/tensor indices\n# Value is (index of tensor array, index of written node)\n_tensor_array_write_ops = {\n    \"TensorArrayWrite\": (3, 2),\n    \"TensorArrayScatter\": (0, 2),\n    \"TensorArraySplit\": (0, 1),\n}\n\n\ndef is_tensor_array_constuctor(tf_node):\n    \"\"\"Check whether is tensor array constructor node.\"\"\"\n    is_ta = False\n    ta_start = \"TensorArrayV\"\n    if tf_node.op.startswith(ta_start):\n        is_ta = tf_node.op[len(ta_start)].isnumeric()\n    return is_ta\n\n\ndef find_parent_loop_name(node_name, while_loop_name_set):\n    \"\"\"Find name of direct parent while loop.\"\"\"\n    ploop_name = \"\"\n    name_prefix = node_name.rsplit(\"/\", 1)[0]\n    if name_prefix.startswith(\"^\"):\n        name_prefix = name_prefix[1:]\n    for lname in while_loop_name_set:\n        if name_prefix.startswith(lname) and len(ploop_name) < len(lname):\n            ploop_name = lname\n\n    if len(ploop_name) == 0:\n        ploop_name = name_prefix\n\n    return ploop_name\n\n\ndef _in_while_loop(control_flow_node_map, op_name):\n    \"\"\"\n    Check if a given control flow operator is part of a while loop execution\n    frame. This is based on the fact that there is only one occurrence of\n    `LoopCond` for a loop execution frame and it is only presented in the loop\n    construct.\n\n    Parameters\n    ----------\n    control_flow_node_map : Dict[str, Set[str]]\n        A dictionary contains the unique control flow execution frame name to\n        a set of primitive operators mapping.\n\n    op_name : str\n        The name of a control flow primitive.\n\n    Returns\n    -------\n    ret : bool\n        Return true if the operator is in a while loop execution frame,\n    otherwise, return false.\n    \"\"\"\n    return op_name in control_flow_node_map and \"LoopCond\" in control_flow_node_map[op_name]\n\n\nclass RewriteSubgraph(ExprMutator):\n    \"\"\"\n    A helper class to rewrite expr in while loop function to variable.\n\n    Parameters\n    ----------\n    rewrite_map : Dict[expr, expr]\n        A dictionary contains a set of expr to var mapping.\n    \"\"\"\n\n    def __init__(self, rewrite_map):\n        ExprMutator.__init__(self)\n        self.rewrite_map = rewrite_map\n\n    def visit(self, expr):\n        if expr in self.rewrite_map:\n            return self.rewrite_map[expr]\n        return super().visit(expr)\n\n\ndef rewrite_subgraph(expr, rewrites):\n    \"\"\"Rewrite loop body.\"\"\"\n    return RewriteSubgraph(rewrites).visit(expr)\n\n\nclass Branch:\n    \"\"\"A class contains the components that are used to build up a Relay if\n    node.\n\n    Parameters\n    ----------\n    cond : tvm.relay.Expr\n        The condition of a if node.\n\n    true_branch : tvm.relay.Expr\n        The body of the true branch of a if expression.\n\n    false_branch: tvm.relay.Expr\n        The body of the false branch of a if expression.\n\n    _if : tvm.relay.Expr\n        An internal variable indicates where an if expression is already created\n        for a matched TF condition construct.\n\n    Examples\n    --------\n    The following is a cond statement written in TensorFlow:\n\n    .. code-block:: python\n\n        def vanilla_cond():\n            i = tf.constant(1)\n            j = tf.constant(4)\n\n             def f1():\n                return tf.multiply(1, 17)\n\n             def f2():\n                return tf.add(4, 23)\n            r = tf.cond(tf.less(i, j), f1, f2)\n\n    This condition statement should be converted into Relay in the following\n    form:\n\n    .. code-block:: python\n\n        fn (%Const: Tensor[(1,), int32],\n            %Const_1: Tensor[(1,), int32],\n            %cond/Mul/x: Tensor[(1,), int32],\n            %cond/Mul/y: Tensor[(1,), int32],\n            %cond/Add/x: Tensor[(1,), int32],\n            %cond/Add/y: Tensor[(1,), int32]) {\n          %0 = less(%Const, %Const_1) # ty=Tensor[(1,), bool]\n          %1 = min(%0)\n          if (%1) {\n            %2 = multiply(%cond/Mul/x, %cond/Mul/y)\n            %2\n          }  else {\n            %3 = add(%cond/Add/x, %cond/Add/y)\n            %3\n          }\n        }\n    \"\"\"\n\n    def __init__(self):\n        self._if = None\n        self.cond = None\n        self.true_branch = None\n        self.false_branch = None\n\n    def _if_node(self):\n        \"\"\"An internal API to create a relay if node from the matched TF\n        condition construct.\n        \"\"\"\n        # `cond`  returns a tensor that contains boolean values. We add a `min`\n        # operator to checks if there is any false value. If so, this condition\n        # doesn't not hold.\n        cond = tvm.relay.op.min(self.cond)\n        return tvm.relay.If(cond, self.true_branch, self.false_branch)\n\n    def if_node(self):\n        \"\"\"Create an tvm.relay.If node if it hasn't been created yet.\"\"\"\n        if self._if is None:\n            self._if = self._if_node()\n        return self._if\n\n\nclass VarChecker(ExprVisitor):\n    \"\"\"Check whether a Variable is used in loop body.\n\n    Parameters\n    ----------\n    var : relay.expr.Var\n        Relay Variable to be checked.\n    \"\"\"\n\n    def __init__(self, var):\n        ExprVisitor.__init__(self)\n        self._var = var\n        self.used = False\n\n    def visit(self, expr):\n        if self._var == expr:\n            self.used = True\n        super().visit(expr)\n\n\nclass Loop:\n    \"\"\"\n    A class contains the components that are used to build up a Relay\n    recursive call.\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        Module for current parsed IR.\n\n    loop_name : str\n        Name prefix of while loop in TensorFlow graph.\n\n    lvar2expr : dict from str to dict from Relay.expr.Var to Relay.expr\n        A dictionary recording all loop vars and corresponding\n        relay expression.\n\n    Examples\n    --------\n    The following is a vanilla loop from TensorFlow:\n    .. code-block:: python\n        i = tf.constant(0)\n        c = lambda i: tf.less(i, 10)\n        b = lambda i: tf.add(i, 1)\n        r = tf.while_loop(c, b, [i])\n    It will be converted to the following recursive call in Relay:\n    .. code-block:: python\n        fn (%while/Less/y: Tensor[(1,), int32],\n            %while/Add/y: Tensor[(1,), int32],\n            %Const: Tensor[(1,), int32]) {\n          %0 = fn(%loop_var0: Tensor[(1,), int32]) {\n            %1 = less(%loop_var0, %while/Less/y)\n            %2 = min(%1)\n            if (%2) {\n              %3 = add(%loop_var0, %while/Add/y)\n              free_var %while_loop\n              %4 = %while_loop(%3)\n              %4\n            }    else {\n              %5 = (%loop_var0,)\n              %5\n            }\n          }\n          let %while_loop1 = %0\n          %6 = %while_loop1(%Const)\n          %6\n        }\n    \"\"\"\n\n    def __init__(self, mod, loop_name, lvar2expr):\n        self.cond = None\n        self.body = []\n        self._loop = None\n        self._mod = mod\n        self._loop_name = loop_name\n        self._lvar2expr = lvar2expr\n        self.loop_vars = []\n\n        self.aligned = False\n\n    def _while_loop(self):\n        \"\"\"An internal API to create a Relay recursive call for a matched TF\n        `while_loop` construct.\n        \"\"\"\n        bind_map = {}\n        wl = tvm.relay.var(\"while_loop\")\n        sb = tvm.relay.scope_builder.ScopeBuilder()\n\n        lv_list = []\n        expr_list = []\n        extra_vars = []\n\n        for i, lv in enumerate(self.loop_vars):\n            if self._loop_name not in self._lvar2expr:\n                self._lvar2expr[self._loop_name] = {}\n\n            # Handle the case when loop var is not properly lifted.\n            # This can happen when loop var node name is set accidentally\n            # beginning with loop name.\n            if lv not in self._lvar2expr[self._loop_name]:\n                var_name = \"{}_loop_var_{}\".format(self._loop_name, i)\n                var_type = _infer_type(lv, self._mod).checked_type\n                loop_var = tvm.relay.var(var_name, type_annotation=var_type)\n                self._lvar2expr[self._loop_name][loop_var] = lv\n                bind_map[lv] = loop_var\n                self.loop_vars[i] = loop_var\n                lv = loop_var\n\n            lv_list.append(lv)\n            expr_list.append(self._lvar2expr[self._loop_name][lv])\n\n        if bind_map:\n            self.cond = rewrite_subgraph(self.cond, bind_map)\n            self.body = [rewrite_subgraph(b, bind_map) for b in self.body]\n\n        cond = tvm.relay.op.min(self.cond)\n\n        for lv, exp in self._lvar2expr[self._loop_name].items():\n            if lv not in self.loop_vars:\n                var_checker = VarChecker(lv)\n                for bd in self.body + [cond]:\n                    var_checker.visit(bd)\n                    if var_checker.used:\n                        lv_list.append(lv)\n                        expr_list.append(exp)\n                        extra_vars.append(lv)\n                        break\n\n        with sb.if_scope(cond):\n            sb.ret(wl(*list(self.body + extra_vars)))\n        with sb.else_scope():\n            sb.ret(tvm.relay.Tuple(lv_list))\n\n        loop_fn = tvm.relay.Function(lv_list, sb.get())\n        sb = tvm.relay.scope_builder.ScopeBuilder()\n        sb.let(wl, loop_fn)\n        loop_ret = wl(*expr_list)\n\n        sb.ret(loop_ret)\n        ret = sb.get()\n        return ret\n\n    def while_loop(self):\n        \"\"\"Instantiate a while loop if it has not been created yet.\"\"\"\n        if self._loop is None:\n            self._loop = self._while_loop()\n            return self._loop\n        return self._loop\n\n\nclass GraphProto(object):\n    \"\"\"A helper class for handling relay graph copying from Tensorflow GraphDef.\n    Definition:\n        https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/graph.proto\n    \"\"\"\n\n    def __init__(self):\n        self._nodes = {}\n        self._tf_node_map = {}\n        self._params = {}\n        self._input_shapes = {}\n        self._output_shapes = {}\n        self._num_rnn_layer = False\n        self._input_shapes = {}\n        self._loops = {}\n        self._branches = {}\n        self._mod = IRModule({})\n        self._prelude = Prelude(self._mod)\n        self._control_flow_node_map = defaultdict(set)\n        self._loop_body_order = {}\n        self._loop_var_order = {}\n        self._lvar2expr = {}\n        self._lname_map = {}\n        self._sorted_cf_node_names = []\n        self._while_loop_name_set = set()\n        self._main_graph_proto = self\n        self._tensor_array_shapes = {}\n        self._tensor_array_shape_nodes = {}\n\n    def _get_relay_func(self, graph, layout=\"NHWC\", shape=None, outputs=None):\n        \"\"\"Construct relay nodes from tensorflow graph definition - GraphDef.\n\n        Follow the tensorflow graph definition to parse and convert it to Relay.\n        Some of the assumptions listed below.\n\n            -> All Placeholders are considered as graph input.\n            -> All Const nodes are params.\n            -> Last node is assumed as graph output.\n            -> _output_shapes : Graph should be frozen with add_shapes=True.\n                                Or user can pass input shape dictionary optionally.\n            -> DecodeJpeg, ResizeBilinear: These are dummy operators.\n                                           Hence user should handle preprocessing outside.\n            -> CheckNumerics: No implementation as of now for this.\n                              Just copies input to output.\n\n        Parameters\n        ----------\n        graph : tensorflow graph definition object\n            The loaded tensorflow GraphDef\n\n        layout : target layout to be used (Optional)\n            NCHW only supported now to enable NHWC models on GPU.\n\n        shape : Dictionary of input dimensions (Optional)\n            Graph level input shape dictionary.\n\n        outputs : List of output tensor names (Optional)\n            if not specified then the last node is assumed as graph output.\n\n        Returns\n        -------\n        mod : tvm.IRModule\n            The module that optimizations will be performed on.\n\n        params : dict\n            A dict of name: tvm.nd.array pairs, used as pretrained weights\n        \"\"\"\n        try:\n            from tensorflow.python.framework import tensor_util\n        except ImportError as e:\n            raise ImportError(\"Unable to import tensorflow which is required {}\".format(e))\n\n        missing_operators = self._parse_import_prerequisites(graph)\n        control_flow_nodes = []\n        ta_write_nodes = []\n        ta_gather_nodes = []\n        ta_construct_nodes = []\n        self._in_shape = shape\n        self._layout = layout\n        self._graph = graph\n\n        if missing_operators:\n            freezed_ops = [op for op in missing_operators if op in _freezed_graph_pruned_op_list]\n            if freezed_ops:\n                raise Exception(\n                    \"Graph is not frozen. Provide a frozen graph. \"\n                    \"Found operators {}\".format(freezed_ops)\n                )\n\n            raise NotImplementedError(\n                \"The following operators are not implemented: {}\".format(missing_operators)\n            )\n\n        for node in graph.node:\n            node_name_prefix = node.name.rsplit(\"/\", 1)[0]\n            self._control_flow_node_map[node_name_prefix].add(node.op)\n            self._tf_node_map[node.name] = node\n\n            # Parse output_shapes attribute\n            parsed_attr = self._parse_attr(node.attr)\n            if \"_output_shapes\" in parsed_attr:\n                self._output_shapes[node.name] = [\n                    tensor_util.TensorShapeProtoToList(tshape)\n                    for tshape in parsed_attr[\"_output_shapes\"]\n                ]\n            else:\n                self._output_shapes[node.name] = [None]\n\n            # Parse placeholder and const here since input shape info is required.\n            if node.op == \"Placeholder\" or node.op == \"PlaceholderWithDefault\":\n                # Give priority to user argument.\n                if shape and node.name in shape:\n                    self._input_shapes[node.name] = list(shape[node.name])\n                else:\n                    self._input_shapes[node.name] = tensor_util.TensorShapeProtoToList(\n                        node.attr[\"shape\"].shape\n                    )\n                    for idx, dim in enumerate(self._input_shapes[node.name]):\n                        if dim < 0:\n                            self._input_shapes[node.name][idx] = Any()\n\n                self._output_shapes[node.name] = [self._input_shapes[node.name]]\n                attr = self._parse_attr(node.attr)\n                self._nodes[node.name] = [\n                    _expr.var(\n                        node.name, shape=self._input_shapes[node.name], dtype=attr[\"dtype\"].name\n                    )\n                ]\n\n                # Ignore user's input shape for Non placeholder\n            elif node.op == \"Const\":\n                tensor_value = node.attr[\"value\"].tensor\n                self._input_shapes[node.name] = tensor_util.TensorShapeProtoToList(\n                    tensor_value.tensor_shape\n                )\n                self._output_shapes[node.name] = [self._input_shapes[node.name]]\n                if shape and node.name in shape:\n                    warnings.warn(\n                        \"Ignore the passed shape. Shape in graphdef \"\n                        \"will be used for operator %s.\" % node.name\n                    )\n                for key, value in node.attr.items():\n                    self._parse_param(key, value, node.name, self._in_shape)\n            elif node.op in _control_flow_nodes:\n                # We assume that the direct parent node of Exit is a while loop block\n                if node.op == \"Exit\":\n                    self._while_loop_name_set.add(node_name_prefix)\n                control_flow_nodes.append(node)\n            elif node.op.startswith(\"TensorArray\"):\n                if is_tensor_array_constuctor(node):\n                    ta_construct_nodes.append(node)\n                else:\n                    for ta_write_name, idx in _tensor_array_write_ops.items():\n                        if node.op.startswith(ta_write_name):\n                            ta_write_nodes.append((node, idx))\n                            break\n                    if node.op.startswith(\"TensorArrayGather\"):\n                        ta_gather_nodes.append(node)\n\n        # Use tensor array gather to infer static tensor array shape\n        for gather_node in ta_gather_nodes:\n            input_ta_name = gather_node.input[0]\n            input_ta_node = self._tf_node_map[input_ta_name]\n            if is_tensor_array_constuctor(input_ta_node):\n                gather_attr = self._parse_attr(gather_node.attr)\n                if \"element_shape\" not in gather_attr:\n                    continue\n                raw_elem_shape = tensor_util.TensorShapeProtoToList(gather_attr[\"element_shape\"])\n                elem_shape = []\n                for dim in raw_elem_shape:\n                    if dim < 0:\n                        elem_shape.append(Any())\n                    else:\n                        elem_shape.append(int(dim))\n                self._tensor_array_shapes[input_ta_node.name] = elem_shape\n\n        # Fetch node contains static tensor array shape\n        for item in ta_write_nodes:\n            wnode = item[0]\n            ta_idx, inode_idx = item[1]\n\n            stack = [self._tf_node_map[wnode.input[ta_idx].split(\":\")[0]]]\n            while stack:\n                cnode = stack.pop(0)\n                if not cnode.op.startswith(\"TensorArray\"):\n                    for iname in cnode.input:\n                        stack.append(self._tf_node_map[iname.split(\":\")[0]])\n                elif cnode.name != wnode.name:\n                    if is_tensor_array_constuctor(cnode):\n                        inode = self._tf_node_map[wnode.input[inode_idx].split(\":\")[0]]\n                        tn = wnode.input[inode_idx].split(\":\")\n                        output_index = int(tn[1]) if len(tn) > 1 else 0\n                        self._tensor_array_shape_nodes[cnode.name] = (inode, wnode.op, output_index)\n                    break\n\n        # First, parse all control flow nodes.\n        # Convert tf.cond to Branch and tf.while_loop to Loop.\n        sorted_cf_nodes = []\n        exit_pos_map = {}\n        ordered_prefix = []\n        # Sort control flow nodes to move all Exit nodes to the end\n        # of corresponding while_loop block.\n        for node in control_flow_nodes:\n            loop_name = find_parent_loop_name(node.name, self._while_loop_name_set)\n            if node.op == \"Exit\":\n                if loop_name not in exit_pos_map:\n                    ordered_prefix.append(loop_name)\n                    exit_pos_map[loop_name] = len(sorted_cf_nodes)\n                sorted_cf_nodes.append(node)\n            elif loop_name in self._while_loop_name_set:\n                if loop_name not in exit_pos_map:\n                    sorted_cf_nodes.append(node)\n                else:\n                    sorted_cf_nodes.insert(exit_pos_map[loop_name], node)\n                    for j in range(ordered_prefix.index(loop_name), len(ordered_prefix)):\n                        exit_pos_map[ordered_prefix[j]] += 1\n            else:\n                sorted_cf_nodes.append(node)\n\n        for node in sorted_cf_nodes:\n            self._sorted_cf_node_names.append(node.name)\n\n        for node in sorted_cf_nodes:\n            self._backtrack_construct(node.name)\n\n        # Second, parse other nodes to re-create TF graph using Relay operators.\n        for node in graph.node:\n            self._backtrack_construct(node.name)\n\n        out = []\n        if outputs is None:\n            last_node = graph.node[-1]\n            op = self._nodes[last_node.name.split(\":\")[0]]\n            if last_node.op == \"Exit\":\n                out = [op[0].tuple_value]\n            else:\n                out = op\n        else:\n            for out_name in outputs:\n                if \":\" in out_name:\n                    out_name, out_num = out_name.split(\":\")\n                    out_num = int(out_num)\n                    out.append(self._nodes[out_name][out_num])\n                else:\n                    out.append(self._nodes[out_name][0])\n\n        if isinstance(out, _expr.TupleWrapper):\n            out = out.tuple_value\n        else:\n            out = out[0] if len(out) == 1 else _expr.Tuple(out)\n        fvars = analysis.free_vars(out)\n        func = _function.Function(fvars, out)\n        final_params = {}\n        for fv in fvars:\n            if fv.name_hint in self._params:\n                final_params[fv.name_hint] = self._params[fv.name_hint]\n        self._params = final_params\n        return func\n\n    def from_tensorflow(self, graph, layout=\"NHWC\", shape=None, outputs=None):\n        \"\"\"Wrapper to _get_relay_func which converts Tensorflow graph to Relay function\n        which is used as main function for the Relay module\n        \"\"\"\n        func = self._get_relay_func(graph, layout=layout, shape=shape, outputs=outputs)\n        self._mod[\"main\"] = func\n        return self._mod, self._params\n\n    def _parse_import_prerequisites(self, graph):\n        \"\"\"Calculate the named preconditions from TensorFlow `graph`.\n        Return prerequisites for parsing:\n        a. Set of operator names which don't have their mapping in TVM, i.e.\n            which are not supported\n        \"\"\"\n        missing_operators = set()\n        from tensorflow.python.framework import op_def_registry\n\n        for node in graph.node:\n            getOpDef = (\n                op_def_registry._registered_ops.get\n                if hasattr(op_def_registry, \"_registered_ops\")\n                else op_def_registry.get\n            )\n            op_def = getOpDef(node.op)\n            if node.op == \"Placeholder\" or node.op == \"PlaceholderWithDefault\":\n                pass\n            elif node.op == \"Const\":\n                pass\n            elif node.op in [\"PartitionedCall\", \"StatefulPartitionedCall\"]:\n                pass\n            else:\n                if any([node.op in t for t in [_identity_list, _convert_map, _control_flow_nodes]]):\n                    pass\n                elif op_def is not None and op_def.is_stateful:\n                    missing_operators.add(node.op)\n                else:\n                    missing_operators.add(node.op)\n\n        return missing_operators\n\n    def _parse_param(self, key, value, name, shape):\n        try:\n            from tensorflow.python.framework import tensor_util\n        except ImportError as e:\n            raise ImportError(\"Unable to import tensorflow which is required {}\".format(e))\n\n        if key == \"value\":\n            np_array = tensor_util.MakeNdarray(value.tensor)\n\n            if np_array.dtype == np.dtype(object):\n                # Object types are generally tensorflow DT_STRING (DecodeJpeg op).\n                # Just leave it as placeholder.\n                if shape and name in shape:\n                    var_shape = shape[name]\n                else:\n                    var_shape = tensor_util.TensorShapeProtoToList(value.tensor.tensor_shape)\n                self._nodes[name] = [_expr.var(name, shape=var_shape, dtype=\"uint8\")]\n                return\n\n            array_ndim = len(np_array.shape)\n            if array_ndim == 0:\n                self._nodes[name] = [tvm.relay.const(np_array, np_array.dtype)]\n            else:\n                self._params[name] = tvm.nd.array(np_array)\n                self._nodes[name] = [\n                    _expr.var(name, shape=self._params[name].shape, dtype=self._params[name].dtype)\n                ]\n        else:\n            if key not in (\"dtype\", \"_output_shapes\", \"_class\"):\n                raise NotImplementedError(\n                    \"Other attributes for a Const(param) Node {} ? .\".format(key)\n                )\n\n    def _get_attr(self, buf):\n        \"\"\"Returns the value of the attr of this buf with the given `name`.\n\n        Args:\n          buf: attrvalue protobuf.\n\n        Returns:\n          The value of the attr, as a Python object.\n\n        Raises:\n          ValueError: If this op does not have an attr with the given `name`.\n        \"\"\"\n        fields = [\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\", \"func\"]\n\n        x = buf\n\n        ret = []\n\n        try:\n            from tensorflow.python.framework import dtypes\n        except ImportError as e:\n            raise ImportError(\"Unable to import tensorflow which is required {}\".format(e))\n\n        # Treat an empty oneof value as an empty list.\n        if not x.WhichOneof(\"value\"):\n            return ret\n        if x.HasField(\"list\"):\n            for f in fields:\n                if getattr(x.list, f):\n                    if f == \"type\":\n                        ret += [dtypes.as_dtype(x) for x in list(getattr(x.list, f))]\n                    else:\n                        ret += list(getattr(x.list, f))\n        else:\n            for f in fields:\n                if x.HasField(f):\n                    if f == \"type\":\n                        ret = dtypes.as_dtype(getattr(x, f))\n                    else:\n                        ret = getattr(x, f)\n        return ret\n\n    def _parse_attr(self, attr_proto):\n        \"\"\"Convert a list of AttributeProto to a dict, with names as keys.\"\"\"\n        attrs = {}\n        for key, value in attr_proto.items():\n            attrs[key] = self._get_attr(value)\n\n        return attrs\n\n    def _convert_control_flow_operator(self, node, inputs, attrs, control_flow_node_map):\n        \"\"\"\n        Convert the Relay control flow primitive into corresponding component\n        of a Relay control flow construct, i.e. `tf.cond` and `tf.while_loop`\n        are converted in Relay `If` and recusrive call, respectively.\n\n        Parameters\n        ----------\n        node: TensorFlow graph node object.\n            A TensorFlow graph node object.\n\n        inputs : List[tvm.relay.Expr]\n            List of input symbols.\n\n        attrs : Dict[tvm.Attrs]\n            Dict of operator attributes.\n\n        control_flow_node_map : Dict[str, Set[str]]\n            A dictionary contains the execution frame name to primitives\n            mapping.\n\n        Returns\n        -------\n        op : tvm.relay.Expr\n            Converted relay expression.\n        \"\"\"\n        node_name_prefix = node.name.rsplit(\"/\", 1)[0]\n        plname = find_parent_loop_name(node.name, self._while_loop_name_set)\n        if node.op == \"Merge\":\n            if _in_while_loop(self._control_flow_node_map, node_name_prefix):\n                op = self._licm_construct(plname, node.input[0])\n                if node_name_prefix not in self._loops:\n                    self._loops[node_name_prefix] = Loop(self._mod, plname, self._lvar2expr)\n            else:\n                if node_name_prefix not in self._branches:\n                    switch_prefix = node_name_prefix + \"/Switch\"\n                    merge_idx = self._sorted_cf_node_names.index(node.name)\n                    for i in range(merge_idx - 1, -1, -1):\n                        cf_name = self._sorted_cf_node_names[i]\n                        if cf_name.startswith(switch_prefix):\n                            self._backtrack_construct(cf_name)\n                            break\n\n                branch = self._branches[node_name_prefix]\n                false_br = self._licm_construct(plname, node.input[0])\n                true_br = self._licm_construct(plname, node.input[1])\n                branch.true_branch = true_br\n                branch.false_branch = false_br\n                op = branch.if_node()\n                if node_name_prefix not in self._while_loop_name_set:\n                    try:\n                        cond_val = np.all(\n                            _infer_value(branch.cond, self._params, self._mod).numpy()\n                        )\n                        if cond_val:\n                            op = branch.true_branch\n                        else:\n                            op = branch.false_branch\n                    except Exception:\n                        op = branch.if_node()\n        elif node.op == \"Exit\":\n            loop = self._loops[node_name_prefix]\n\n            # Check whether the order of loop variables aligns\n            # with loop body. If not, create new loop variable list\n            # with correct order.\n            if not loop.aligned:\n                loop_vars = []\n                for i in self._loop_body_order[node_name_prefix]:\n                    for j, k in enumerate(self._loop_var_order[node_name_prefix]):\n                        if k == i:\n                            loop_vars.append(loop.loop_vars[j])\n                loop.loop_vars = loop_vars\n                loop.aligned = True\n            exit_name = node.name.split(\"/\")[-1]\n            if \"_\" in exit_name:\n                exit_number = int(exit_name[5:])\n            else:\n                exit_number = 0\n            expr = loop.while_loop()\n            body_pos = exit_number\n            for i, j in enumerate(self._loop_body_order[node_name_prefix]):\n                if exit_number == j:\n                    body_pos = i\n                    break\n            op = _expr.TupleGetItem(expr, body_pos)\n        elif node.op == \"Enter\":\n            op = self._licm_construct(plname, node.input[0])\n        elif node.op == \"LoopCond\":\n            op = self._licm_construct(plname, node.input[0])\n            self._loops[node_name_prefix].cond = op\n        elif node.op == \"Switch\":\n            op = self._licm_construct(plname, node.input[0])\n            cond = self._licm_construct(plname, node.input[1])\n            if _in_while_loop(self._control_flow_node_map, node_name_prefix):\n                if node_name_prefix not in self._loop_var_order:\n                    self._loop_var_order[node_name_prefix] = []\n                if node.name.endswith(\"Switch\"):\n                    self._loop_var_order[node_name_prefix].append(0)\n                else:\n                    self._loop_var_order[node_name_prefix].append(\n                        int(node.name.split(\"Switch_\")[-1])\n                    )\n                self._loops[node_name_prefix].loop_vars.append(op)\n            else:\n                if node_name_prefix not in self._branches:\n                    self._branches[node_name_prefix] = Branch()\n                self._branches[node_name_prefix].cond = cond\n        elif node.op == \"NextIteration\":\n            if node_name_prefix not in self._loop_body_order:\n                self._loop_body_order[node_name_prefix] = []\n            if node.name.endswith(\"NextIteration\"):\n                self._loop_body_order[node_name_prefix].append(0)\n            else:\n                self._loop_body_order[node_name_prefix].append(\n                    int(node.name.split(\"NextIteration_\")[-1])\n                )\n            op = self._licm_construct(plname, node.input[0])\n            self._loops[node_name_prefix].body.append(op)\n        else:\n            raise Exception(\"Cannot identify control flow operator: \" + \"{}\".format(node.op))\n\n        return op\n\n    def _partition_call_operator(self, inputs, attr):\n        \"\"\"\n        Convert the Relay Partition call ops into Relay Function calls and\n        function definitions from Tensorflow graph library attribute to Relay global\n        functions\n\n        Parameters\n        ----------\n        node: TensorFlow graph node object.\n            A TensorFlow graph node object.\n\n        inputs : List[tvm.relay.Expr]\n            List of input symbols.\n\n        attrs : Dict[tvm.Attrs]\n            Dict of operator attributes.\n\n        Returns\n        -------\n        op : tvm.relay.Expr\n            Converted relay expression.\n        \"\"\"\n\n        try:\n            from tensorflow.python.framework import function_def_to_graph\n        except ImportError as e:\n            raise ImportError(\"Unable to import tensorflow which is required {}\".format(e))\n\n        main_graph_proto = self._main_graph_proto\n        outer_graph_def = main_graph_proto._graph\n\n        node_func_name = attr.get(\"f\").name\n        func = next(\n            (f for f in outer_graph_def.library.function if f.signature.name == node_func_name),\n            None,\n        )\n        if func:\n            devices = set(node.device for node in func.node_def)\n            if len(devices) > 1:\n                raise Exception(\n                    \"Found inconsistent Device assignment in the \"\n                    \"Stateful Partitioned SubGraph. Rejecting \"\n                    \"the subgraph \"\n                )\n            # Convert function definition to graph\n            func_input_shapes = func.attr[\"_input_shapes\"].list.shape\n            subgraph, _ = function_def_to_graph.function_def_to_graph_def(func, func_input_shapes)\n\n            # Computing subgraph's input shape dictionary\n            subgraph_shape_dict, input_expr_dict = {}, {}\n            for f_arg, input in zip(func.signature.input_arg, inputs):\n                input_expr_dict[f_arg.name] = input\n                subgraph_shape_dict[f_arg.name] = _infer_shape(input, main_graph_proto._mod)\n\n            func_name = \"func_{}\".format(func.signature.name)\n            try:\n                global_func = main_graph_proto._mod[func_name]\n                sub_func = global_func\n                sub_params = main_graph_proto._params\n            except ValueError:\n                # Construct relay nodes from the subgraph\n                g1 = SubGraphProto(main_graph_proto)\n                sub_func, sub_params = g1.from_tensorflow(subgraph, shape=subgraph_shape_dict)\n                main_graph_proto._params.update(sub_params)\n                func_expr = _function.Function(sub_func.params, sub_func.body)\n                global_func = tvm.relay.GlobalVar(func_name)\n                main_graph_proto._mod[global_func] = func_expr\n                main_graph_proto._mod = InferType()(main_graph_proto._mod)\n\n            param_exprs = []\n            for param_expr in sub_func.params:\n                # sub_params is subset of sub_func.params\n                param_name = param_expr.vid.name_hint\n                if param_name in input_expr_dict.keys():\n                    param_exprs.append(input_expr_dict[param_name])\n                elif param_name in sub_params.keys():\n                    param_exprs.append(param_expr)\n                else:\n                    raise Exception(\"Input parameter {} not found\".format(param_name))\n\n            sb = tvm.relay.scope_builder.ScopeBuilder()\n            loop_ret = global_func(*param_exprs)\n            sb.ret(loop_ret)\n            ret = sb.get()\n        else:\n            raise Exception(\"Function not found - {}\".format(node_func_name))\n        return ret\n\n    def _convert_operator(\n        self, op_name, node_name, inputs, attrs, identity_list=None, convert_map=None\n    ):\n        \"\"\"Convert from Tensorflow operator to relay operator.\n        The converter must specify conversions explicitly for incompatible name, and\n        apply handlers to operator attributes.\n\n        Parameters\n        ----------\n        op_name : str\n            Operator name, such as Conv2D, AvgPool\n        inputs : list of relay.op\n            List of input symbols.\n        attrs : dict\n            Dict of operator attributes\n        identity_list : list\n            List of operators that don't require conversion\n        convert_map : dict\n            Dict of name : callable, where name is the op's name that\n            require conversion to relay, callable are functions which\n            take attrs and return (new_op_name, new_attrs)\n\n        Returns\n        -------\n        sym : relay.op\n            Converted relay operator\n        \"\"\"\n        identity_list = identity_list if identity_list else _identity_list\n        convert_map = convert_map if convert_map else _convert_map\n        if op_name in identity_list:\n            sym = get_relay_op(op_name)(*inputs, **attrs)\n        elif op_name in convert_map:\n            if _need_prelude_for_shape_inference(op_name):\n                sym = convert_map[op_name](inputs, attrs, self._params, self._prelude)\n            else:\n                sym = convert_map[op_name](inputs, attrs, self._params, self._mod)\n        elif op_name in [\"PartitionedCall\", \"StatefulPartitionedCall\"]:\n            sym = self._partition_call_operator(inputs, attrs)\n        else:\n            raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n\n        sym = self._set_span(sym, node_name)\n\n        return sym\n\n    @staticmethod\n    def _set_span(sym, node_name):\n        span = tvm.relay.Span(tvm.relay.SourceName(node_name), 0, 0, 0, 0)\n        if isinstance(sym, _expr.Call) and sym.span is None:\n            sym = _expr.Call(sym.op, sym.args, sym.attrs, sym.type_args, span)\n        elif isinstance(sym, _expr.TupleWrapper):\n            tuple_value = sym.tuple_value\n            if isinstance(tuple_value, _expr.Call) and tuple_value.span is None:\n                tuple_value = _expr.Call(\n                    tuple_value.op, tuple_value.args, tuple_value.attrs, tuple_value.type_args, span\n                )\n                sym = _expr.TupleWrapper(tuple_value, sym.size)\n        return sym\n\n    def _licm_construct(self, loop_name, node_name):\n        \"\"\"Construct a node by considering whether it is\n        loop invariant with the given while loop. If yes, we\n        generate a loop Variable. Otherwise, return regular\n        converted relay expression.\n\n        Parameters\n        ----------\n        loop_name : str\n            TensorFlow while loop name to be checked.\n\n        node_name : str\n            TensorFlow node name.\n\n        Returns\n        -------\n        out : relay.Expr or relay.Var\n            Converted relay expression or loop var.\n        \"\"\"\n        actual_expr = self._backtrack_construct(node_name)\n        tn = node_name.split(\":\")\n        node_name = tn[0].split(\"^\")[-1]\n        cloop_name = find_parent_loop_name(node_name, self._while_loop_name_set)\n\n        if loop_name in self._while_loop_name_set and not cloop_name.startswith(loop_name):\n            if loop_name not in self._lvar2expr:\n                self._lvar2expr[loop_name] = {}\n            if loop_name not in self._lname_map:\n                self._lname_map[loop_name] = {}\n\n            if node_name not in self._lname_map[loop_name]:\n                var_name = \"{}_loop_var\".format(node_name)\n                var_type = _infer_type(actual_expr, self._mod).checked_type\n                loop_var = tvm.relay.var(var_name, type_annotation=var_type)\n                try:\n                    extra_param = _infer_value(actual_expr, self._params, self._mod)\n                    self._params[var_name] = extra_param\n                except Exception:\n                    pass\n                self._lvar2expr[loop_name][loop_var] = actual_expr\n                self._lname_map[loop_name][node_name] = loop_var\n                ret = loop_var\n            else:\n                ret = self._lname_map[loop_name][node_name]\n        else:\n            ret = actual_expr\n\n        return ret\n\n    def _backtrack_construct(self, node_name):\n        \"\"\"Convert a specific tensorflow node to relay expression.\n\n        If any of its ancestor node is not converted yet, backtrack as\n        far as input node and covert all nodes on the path.\n\n        This is required when parsing control flow nodes, since the parsing\n        order may not follow the original graph def.\n\n        Parameters\n        ----------\n        node_name : str\n            TensorFlow node name.\n\n        Returns\n        -------\n        op : relay.Expr\n            Converted relay expression\n        \"\"\"\n        try:\n            from tensorflow.python.framework import tensor_util\n        except ImportError as e:\n            raise ImportError(\"Unable to import tensorflow which is required {}\".format(e))\n\n        input_op_name = node_name.split(\":\")[0].split(\"^\")[-1]\n        if input_op_name not in self._nodes:\n            node = self._tf_node_map[input_op_name]\n            attr = self._parse_attr(node.attr)\n\n            if node.op in _control_flow_nodes:\n                attr = self._parse_attr(node.attr)\n                op = self._convert_control_flow_operator(\n                    node, [], attr, self._control_flow_node_map\n                )\n            else:\n                attr[\"_output_shapes\"] = self._output_shapes[input_op_name]\n                attr[\"_node_name\"] = node.name\n                attr[\"_target_layout\"] = self._layout\n\n                inputs = [self._backtrack_construct(iname) for iname in node.input]\n\n                plname = find_parent_loop_name(node_name, self._while_loop_name_set)\n\n                # For TensorArrayV3 op, we need to infer shape first\n                if is_tensor_array_constuctor(node):\n                    raw_elem_shape = tensor_util.TensorShapeProtoToList(attr[\"element_shape\"])\n                    elem_shape = []\n                    for dim in raw_elem_shape:\n                        if dim < 0:\n                            elem_shape.append(Any())\n                        else:\n                            elem_shape.append(dim)\n\n                    if elem_shape:\n                        attr[\"shape\"] = elem_shape\n                    if attr[\"identical_element_shapes\"] or elem_shape:\n                        shape_node, wnode_op, output_index = self._tensor_array_shape_nodes[\n                            node.name\n                        ]\n                        name = shape_node.name\n                        if output_index > 0:\n                            name += \":\" + str(output_index)\n                        converted = self._backtrack_construct(name)\n                        shape = _infer_shape(converted, self._mod)\n                        if wnode_op.startswith(\"TensorArraySplit\"):\n                            shape = (Any(),) + shape[1:]\n                        elif wnode_op.startswith(\"TensorArrayScatter\"):\n                            shape = shape[1:]\n\n                        if node.name in self._tensor_array_shapes:\n                            preset_shape = self._tensor_array_shapes[node.name]\n                            shape = _get_more_static_shape(shape, preset_shape)\n\n                        if \"shape\" in attr:\n                            attr[\"shape\"] = _get_more_static_shape(shape, attr[\"shape\"])\n                        else:\n                            attr[\"shape\"] = shape\n\n                # LICM\n                if plname in self._while_loop_name_set:\n                    for i, iname in enumerate(node.input):\n                        actual_input = self._licm_construct(plname, iname)\n                        inputs[i] = actual_input\n\n                op = self._convert_operator(node.op, node.name, inputs, attr)\n            if isinstance(op, np.ndarray):\n                self._params[node.name] = tvm.nd.array(op)\n                op = [\n                    _expr.var(\n                        node.name,\n                        shape=self._params[node.name].shape,\n                        dtype=self._params[node.name].dtype,\n                    )\n                ]\n\n            elif isinstance(op, (_expr.Expr, _expr.TupleGetItem)):\n                op = [op]\n\n            self._nodes[input_op_name] = op\n\n        out = self._nodes[input_op_name]\n\n        if isinstance(out, _expr.TupleWrapper):\n            tn = node_name.split(\":\")\n            tensor_slot = int(tn[1]) if len(tn) > 1 else 0\n            return out[tensor_slot]\n        return out[0]\n\n\nclass SubGraphProto(GraphProto):\n    \"\"\"A helper class for handling relay subgraph copying from Tensorflow GraphDef.\"\"\"\n\n    def __init__(self, main_graph_proto):\n        super().__init__()\n        self._main_graph_proto = main_graph_proto  # holds main graph proto object\n\n    def from_tensorflow(self, graph, layout=\"NHWC\", shape=None, outputs=None):\n        \"\"\"Wrapper to _get_relay_func which converts Tensorflow graph to Relay function.\n        Return Relay function and params\n        \"\"\"\n        func = self._get_relay_func(graph, layout=layout, shape=shape, outputs=outputs)\n        return func, self._params\n\n\ndef from_tensorflow(graph, layout=\"NHWC\", shape=None, outputs=None, convert_config=None):\n    \"\"\"Load tensorflow graph which is a python tensorflow graph object into relay.\n    The companion parameters will be handled automatically.\n\n    Parameters\n    ----------\n    graph : GraphDef object\n        Tensorflow GraphDef\n\n    layout : target layout to be used (Optional)\n        NCHW only supported now to enable NHWC models on GPU.\n\n    shape : Dictionary of input dimensions (Optional)\n        Graph level input shape dictionary.\n\n    outputs : List of output tensor names (Optional)\n        if not specified then the last node is assumed as graph output.\n\n    convert_config : Optional[Dict[str, Any]]\n        Default config:\n            use_dense : bool = True\n                Ture to convert `tf.matmul` to `nn.dense`, else to `nn.matmul`.\n                The `nn.dense` op requires the data tensor to be non-transposed and weight tensor\n                to be transposed, may insert extra `transpose` to the original graph.\n            use_nt_batch_matmul : bool = True\n                True to convert `tf.batch_matmul` to `nn.batch_matmul` strict to NT format\n                (transpose_a=False, transpose_b=True).\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The module that optimizations will be performed on.\n\n    params : dict of str to tvm.nd.NDArray\n        Dict of converted parameters stored in tvm.nd.NDArray format\n    \"\"\"\n    global TF_DEFAULT_CONFIGS\n    if convert_config is not None:\n        TF_DEFAULT_CONFIGS.update(convert_config)\n\n    g = GraphProto()\n    mod, params = g.from_tensorflow(graph, layout, shape, outputs)\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tensorflow2.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except, too-many-nested-blocks\n\"\"\"Tensorflow2.x graph to relay converter.\n\nIf model is constructed using tf2.x API, then use this converter:\n    from tvm.relay.frontend.tensorflow2 import from_tensorflow\nOtherwise use the tf1.x converter:\n    from tvm.relay.frontend.tensorflow import from_tensorflow\n\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import function_def_to_graph, tensor_util, dtypes\n\nimport tvm\nfrom tvm.relay.transform import InferType\nfrom tvm.relay.prelude import Prelude\nfrom tvm.ir import IRModule\nfrom .. import expr as _expr\nfrom .. import analysis\nfrom .. import function as _function\nfrom ..loops import while_loop as _while_loop\nfrom .common import infer_type as _infer_type\n\nfrom .tensorflow_ops import _convert_map as _convert_map_common\nfrom .tensorflow_ops import _get_more_static_shape_rank\nfrom .tensorflow2_ops import _convert_map as _convert_map_tf2\nfrom .tensorflow2_ops import _need_prelude_for_shape_inference\n\nfrom ..ty import Any\n\n__all__ = [\"from_tensorflow\"]\n\n# A map to record tensor list write ops and input tl/tensor indices\n# Value is (index of tensor list, index of written node)\n_tensor_list_write_ops = {\n    \"TensorListSetItem\": (0, 2),\n}\n\n\ndef _infer_type_with_prelude(val, prelude):\n    body = _infer_type(val, prelude.mod)\n    return body.checked_type\n\n\ndef set_span(sym, node_name):\n    \"\"\"set span of symbol\"\"\"\n\n    span = tvm.relay.Span(tvm.relay.SourceName(node_name), 0, 0, 0, 0)\n    if isinstance(sym, _expr.Call):\n        sym = _expr.Call(sym.op, sym.args, sym.attrs, sym.type_args, span)\n    elif isinstance(sym, _expr.TupleWrapper):\n        tuple_value = sym.tuple_value\n        if isinstance(tuple_value, _expr.Call):\n            tuple_value = _expr.Call(\n                tuple_value.op, tuple_value.args, tuple_value.attrs, tuple_value.type_args, span\n            )\n            sym = _expr.TupleWrapper(tuple_value, sym.size)\n    return sym\n\n\ndef is_tensor_list_constuctor(tf_node):\n    \"\"\"Check whether is tensor list constructor node.\"\"\"\n    return tf_node.op == \"TensorListReserve\"\n\n\ndef convert_const_node(node, shape):\n    \"\"\"convert tf const node into relay const or var\"\"\"\n\n    # get the value of the constant\n    tensor_value = node.attr[\"value\"].tensor\n    np_array = tensor_util.MakeNdarray(tensor_value)\n\n    if np_array.dtype == np.dtype(object):\n        if shape and node.name in shape:\n            var_shape = shape[node.name]\n        else:\n            var_shape = tensor_util.TensorShapeProtoToList(tensor_value.tensor_shape)\n        param = None\n        sym = [_expr.var(node.name, shape=var_shape, dtype=\"uint8\")]\n        return sym, param\n\n    if len(np_array.shape) == 0:\n        param = None\n        sym = [tvm.relay.const(np_array, np_array.dtype)]\n    else:\n        param = tvm.nd.array(np_array)\n        sym = [_expr.var(node.name, shape=param.shape, dtype=param.dtype)]\n\n    return sym, param\n\n\ndef get_attr(buf):\n    \"\"\"convert value of a node attribute. node attribute is part of a node in a graph.\n\n    Parameters\n    ----------\n    buf: attrvalue protobuf.  <class 'tensorflow.core.framework.attr_value_pb2.AttrValue'>\n\n    Returns\n    -------\n    The value of the attr, as a Python object.\n\n    Raises:\n    -------\n    ValueError: If this op does not have an attr with the given `name`.\n    \"\"\"\n\n    fields = [\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\", \"func\"]\n\n    ret = []\n\n    if not buf.WhichOneof(\"value\"):\n        return ret\n\n    if buf.HasField(\"list\"):\n        for f in fields:\n            if getattr(buf.list, f):\n                if f == \"type\":\n                    ret += [dtypes.as_dtype(x) for x in list(getattr(buf.list, f))]\n                else:\n                    ret += list(getattr(buf.list, f))\n    else:\n        for f in fields:\n            if buf.HasField(f):\n                if f == \"type\":\n                    ret = dtypes.as_dtype(getattr(buf, f))\n                else:\n                    ret = getattr(buf, f)\n    return ret\n\n\ndef parse_attr(attr_proto):\n    \"\"\"Convert node attributes (a serialized map of key-value pairs) in a node to a dict\n\n    Parameters\n    ----------\n    attr_proto: <class 'google.protobuf.pyext._message.MessageMapContainer'>\n\n    Returns\n    -------\n    Dict {string: python object}\n\n    \"\"\"\n    attrs = {}\n    for key, value in attr_proto.items():\n        attrs[key] = get_attr(value)\n\n    return attrs\n\n\ndef convert_placeholder(shape, node, in_type=None):\n    \"\"\"convert tf placeholder into relay var.\n\n    Example\n    --------\n    a tf placeholder with name \"x\" is converted to [Var(x, ty=TensorType([], float32))]\n    \"\"\"\n\n    if shape and node.name in shape:\n        input_shape = list(shape[node.name])\n    else:\n        input_shape = tensor_util.TensorShapeProtoToList(node.attr[\"shape\"].shape)\n        for idx, dim in enumerate(input_shape):\n            if dim < 0:\n                input_shape[idx] = Any()\n    attr = parse_attr(node.attr)\n    if in_type is not None:\n        sym = [_expr.var(node.name, type_annotation=in_type)]\n    else:\n        sym = [_expr.var(node.name, shape=input_shape, dtype=attr[\"dtype\"].name)]\n    return input_shape, sym\n\n\nclass RelayModule:\n    \"\"\"states related to the entire relay module (multiple functions)\n    after converted from tf graphdef\"\"\"\n\n    def __init__(self):\n        self.mod = IRModule({})\n        self.params = {}\n        self.prelude = Prelude(self.mod)\n\n\nclass GraphProto:\n    \"\"\"Capturing states when converting a tf graph to a single relay function.\"\"\"\n\n    def __init__(self, module):\n        self._module = module\n        self._prelude = self._module.prelude\n        self._params = {}\n        self._nodes = {}\n        self._input_shapes = {}\n        self._output_shapes = {}\n        self._tf_node_map = {}\n        self._gdef_lib = {}\n        self._tensor_list_shapes = {}\n        self._tensor_list_shape_nodes = {}\n        self._sub_map = {}\n        self._sub_input_idx_map = {}\n\n    def from_tensorflow(\n        self, graph, layout=\"NHWC\", shape=None, outputs=None, input_types=None, gdef_lib=None\n    ):\n        \"\"\"Wrapper to _get_relay_func which converts Tensorflow graph to Relay function\n        which is used as main function for the Relay module\n        \"\"\"\n        if input_types is None:\n            input_types = {}\n\n        if gdef_lib is None:\n            gdef_lib = {}\n\n        self._gdef_lib = gdef_lib\n        func = self._get_relay_func(\n            graph, layout=layout, shape=shape, outputs=outputs, input_types=input_types\n        )\n        return func, self._params\n\n    def _analysis_tensor_list_op(\n        self,\n        graph,\n        node,\n        tl_write_nodes,\n        tl_stack_nodes,\n        tl_construct_nodes,\n        sub_func_name=\"\",\n        root_node=\"\",\n    ):\n        if sub_func_name and sub_func_name not in self._sub_input_idx_map:\n            self._sub_input_idx_map[sub_func_name] = {}\n\n        if node.op == \"Placeholder\":\n            # record placeholder node in sub functions\n            self._sub_map[sub_func_name] = node\n            self._sub_input_idx_map[sub_func_name][node.name] = len(\n                self._sub_input_idx_map[sub_func_name]\n            )\n\n        if node.op.startswith(\"TensorList\"):\n            if is_tensor_list_constuctor(node):\n                tl_construct_nodes.append(node)\n            else:\n                for tl_write_name, idx in _tensor_list_write_ops.items():\n                    if node.op.startswith(tl_write_name):\n                        tl_write_nodes.append((node, idx, sub_func_name, root_node))\n                if node.op.startswith(\"TensorListStack\"):\n                    tl_stack_nodes.append(node)\n        elif node.op.startswith(\"StatelessWhile\"):\n            root_node = node.name\n            cond_fn_name, body_fn_name = [\n                parse_attr(node.attr).get(x).name for x in [\"cond\", \"body\"]\n            ]\n            for fn_name in [cond_fn_name, body_fn_name]:\n                subfunction = self._gdef_lib[fn_name]\n                sub_func_name = fn_name\n                for sub_node in subfunction.node:\n                    # bypass const node\n                    if sub_node.op == \"Const\":\n                        continue\n                    self._tf_node_map[sub_node.name] = sub_node\n                    self._analysis_tensor_list_op(\n                        subfunction,\n                        sub_node,\n                        tl_write_nodes,\n                        tl_stack_nodes,\n                        tl_construct_nodes,\n                        sub_func_name=sub_func_name,\n                        root_node=root_node,\n                    )\n\n    def _infer_static_shape_stack_node(self, tl_stack_nodes):\n        for stack_node in tl_stack_nodes:\n            if len(stack_node.input) < 2:\n                # Stack node does not have shape\n                continue\n            input_shape_name = stack_node.input[1].split(\":\")[0]\n            input_shape_node = self._tf_node_map[input_shape_name]\n            stack = [self._tf_node_map[stack_node.input[0].split(\":\")[0]]]\n            in_idx = -1\n            while stack:\n                cnode = stack.pop(0)\n                if not cnode.op.startswith(\"TensorList\"):\n                    if in_idx and cnode.op.startswith(\"StatelessWhile\"):\n                        stack.append(self._tf_node_map[cnode.input[in_idx].split(\":\")[0]])\n                    else:\n                        for iname in cnode.input:\n                            if self._tf_node_map[iname.split(\":\")[0]].op.startswith(\n                                \"StatelessWhile\"\n                            ):\n                                # identify input index based on output index\n                                if iname.split(\":\")[1]:\n                                    in_idx = int(iname.split(\":\")[1])\n                            stack.append(self._tf_node_map[iname.split(\":\")[0]])\n                # identify the corresponding constructor node and add shape to _tensor_list_shapes\n                elif cnode.name != stack_node.name:\n                    if is_tensor_list_constuctor(cnode):\n                        shape_attr = parse_attr(input_shape_node.attr)\n                        if \"value\" not in shape_attr:\n                            continue\n                        raw_elem_shape = tensor_util.MakeNdarray(shape_attr[\"value\"])\n                        elem_shape = []\n                        for dim in raw_elem_shape:\n                            if dim < 0:\n                                elem_shape.append(Any())\n                            else:\n                                elem_shape.append(int(dim))\n                        self._tensor_list_shapes[cnode.name] = elem_shape\n                    break\n\n    def _infer_static_shape_write_node(self, tl_write_nodes):\n        for item in tl_write_nodes:\n            wnode = item[0]\n            ta_idx, inode_idx = item[1]\n            sub_func_name = item[2]\n            root_name = item[3]\n            stack = [self._tf_node_map[wnode.input[ta_idx].split(\":\")[0]]]\n            while stack:\n                cnode = stack.pop(0)\n\n                if not cnode.op.startswith(\"TensorList\"):\n                    if cnode.op == \"Placeholder\" and sub_func_name:\n                        # need to map subfunction\n                        input_idx = self._sub_input_idx_map[sub_func_name][cnode.name]\n                        stack.append(\n                            self._tf_node_map[\n                                self._tf_node_map[root_name].input[input_idx].split(\":\")[0]\n                            ]\n                        )\n                    else:\n                        for iname in cnode.input:\n                            stack.append(self._tf_node_map[iname.split(\":\")[0]])\n                # identify the corresponding constructor node and add it to _tensor_list_shape_nodes\n                elif cnode.name != wnode.name:\n                    if is_tensor_list_constuctor(cnode):\n                        inode = self._tf_node_map[wnode.input[inode_idx].split(\":\")[0]]\n                        tn = wnode.input[inode_idx].split(\":\")\n                        output_index = int(tn[1]) if len(tn) > 1 else 0\n                        self._tensor_list_shape_nodes[cnode.name] = (inode, wnode.op, output_index)\n                    break\n\n    def _get_relay_func(self, graph, layout=\"NHWC\", shape=None, outputs=None, input_types=None):\n        if input_types is None:\n            input_types = {}\n        tl_write_nodes = []\n        tl_stack_nodes = []\n        tl_construct_nodes = []\n        self._layout = layout\n        for node in graph.node:\n            name = node.name\n            self._tf_node_map[name] = node\n            if node.op == \"Placeholder\":\n                in_type = None\n                if node.name in input_types:\n                    in_type = input_types[node.name]\n                self._input_shapes[name], self._nodes[name] = convert_placeholder(\n                    shape, node, in_type\n                )\n            elif node.op == \"Const\":\n                sym, param = convert_const_node(node, shape)\n                self._nodes[node.name] = sym\n                if param:\n                    self._params[node.name] = param\n            # recursivly iterate tensorlist op if seen while loop\n            else:\n                self._analysis_tensor_list_op(\n                    graph, node, tl_write_nodes, tl_stack_nodes, tl_construct_nodes\n                )\n\n        # Use tensor list stack to infer static tensor list shape\n        self._infer_static_shape_stack_node(tl_stack_nodes)\n\n        # Fetch node contains static tensor list shape\n        self._infer_static_shape_write_node(tl_write_nodes)\n\n        for node in graph.node:\n            self._backtrack_construct(graph, node.name)\n\n        return self._func(graph, outputs)\n\n    def _func(self, graph, outputs):\n        out = []\n        if outputs is None:\n            last_node = graph.node[-1]\n            op = self._nodes[last_node.name.split(\":\")[0]]\n            if last_node.op == \"Exit\":\n                out = [op[0].tuple_value]\n            else:\n                out = op\n        else:\n            for out_name in outputs:\n                if \":\" in out_name:\n                    out_name = out_name.split(\":\")\n                    out_name, out_num = out_name[0], out_name[-1]\n                    out_num = int(out_num)\n                    out.append(self._nodes[out_name][out_num])\n                else:\n                    out.append(self._nodes[out_name][0])\n\n        if isinstance(out, _expr.TupleWrapper):\n            out = out.astuple()\n        else:\n            out = out[0] if len(out) == 1 else _expr.Tuple(out)\n\n        fvars = analysis.free_vars(out)\n        func = _function.Function(fvars, out)\n        final_params = {}\n        for fv in fvars:\n            if fv.name_hint in self._params:\n                final_params[fv.name_hint] = self._params[fv.name_hint]\n        self._params = final_params\n        return func\n\n    def _convert_operator(self, graph, op_name, node_name, inputs, attrs):\n        \"\"\"Convert from Tensorflow operator to relay operator.\n        The converter must specify conversions explicitly for incompatible name, and\n        apply handlers to operator attributes.\n\n        Parameters\n        ----------\n        graph: <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n            TF2 frozen graph def\n        op_name : str\n            Operator name, such as Conv2D, AvgPool\n        node_name: str\n             Name of the node in TF2 graph, such as Identity:0\n        inputs : list of relay.op\n            List of input symbols.\n        attrs : dict\n            Dict of operator attributes\n\n        Returns\n        -------\n        sym : relay.op\n            Converted relay operator\n        \"\"\"\n        if op_name in [\"PartitionedCall\", \"StatefulPartitionedCall\"]:\n            sym = _partition_call_operator(\n                self._module,\n                graph,\n                inputs,\n                attrs,\n                self._prelude,\n                gdef_lib=self._gdef_lib,\n            )\n        elif op_name in [\"StatelessIf\", \"If\"]:\n            sym = _convert_if(\n                self._module, graph, inputs, attrs, self._prelude, gdef_lib=self._gdef_lib\n            )\n        elif op_name in [\"StatelessWhile\", \"While\"]:\n            sym = _convert_loop(\n                self._module,\n                graph,\n                inputs,\n                attrs,\n                node_name,\n                self._tf_node_map,\n                self._prelude,\n                gdef_lib=self._gdef_lib,\n            )\n        elif op_name in _convert_map_common:\n            # assert op are exclusive\n            assert not set(_convert_map_common.keys()) & set(_convert_map_tf2.keys())\n            if _need_prelude_for_shape_inference(op_name):\n                sym = _convert_map_common[op_name](inputs, attrs, self._params, self._prelude)\n            else:\n                sym = _convert_map_common[op_name](inputs, attrs, self._params, self._module.mod)\n        elif op_name in _convert_map_tf2:\n            if _need_prelude_for_shape_inference(op_name):\n                sym = _convert_map_tf2[op_name](inputs, attrs, self._params, self._prelude)\n            else:\n                sym = _convert_map_tf2[op_name](inputs, attrs, self._params, self._module.mod)\n        else:\n            raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n\n        sym = set_span(sym, node_name)\n        return sym\n\n    def _parse_element_shape(self, elem_shape, shape_attr):\n        if \"value\" in shape_attr:\n            raw_elem_shape = tensor_util.MakeNdarray(shape_attr[\"value\"])\n\n            if raw_elem_shape.size == 1 and raw_elem_shape == -1:\n                elem_shape.append(Any())\n            else:\n                for dim in raw_elem_shape:\n                    if dim < 0:\n                        elem_shape.append(Any())\n                    else:\n                        elem_shape.append(dim)\n\n    def _backtrack_construct(self, graph, node_name):\n        \"\"\"Convert a specific tensorflow node to relay expression.\n\n        If any of its ancestor node is not converted yet, backtrack as\n        far as input node and covert all nodes on the path. resurion is used here.\n\n        This is required when parsing control flow nodes, since the parsing\n        order may not follow the original graph def.\n\n        to discover input node, current tf node's input is iterated:\n\n        tensorflow/core/framework/node_def.proto\n            message NodeDef {\n                repeated string input = 3;\n            }\n\n        a node has many inputs (other nodes). each input has the following format:\n            data input is \"node:src_output\".  node is the string name.\n            control input is \"^node\".\n\n        Parameters\n        ----------\n        graph : <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n            TF2 frozen graph def\n\n        node_name : str\n            node name\n\n        Returns\n        -------\n        op : relay.Expr\n            Converted relay expression.\n\n        Examples\n        --------\n        tf expression \"x+1\" is converted to relay expression:\n            CallNode(Op(add), [Var(x, ty=TensorType([], float32)), Constant(1.0)], (nullptr), [])\n\n        \"\"\"\n        input_op_name = node_name.split(\":\")[0].split(\"^\")[-1]\n\n        if input_op_name not in self._nodes:\n            node = self._tf_node_map[input_op_name]\n            attr = parse_attr(node.attr)\n            if \"_output_shapes\" in attr:\n                self._output_shapes[node.name] = [\n                    tensor_util.TensorShapeProtoToList(tshape) for tshape in attr[\"_output_shapes\"]\n                ]\n            else:\n                self._output_shapes[node.name] = [None]\n\n            attr[\"_output_shapes\"] = self._output_shapes[input_op_name]\n            attr[\"_node_name\"] = node.name\n            attr[\"_target_layout\"] = self._layout\n            inputs = [self._backtrack_construct(graph, iname) for iname in node.input]\n\n            # infer shape for TensorList op\n            if is_tensor_list_constuctor(node):\n                input_shape_name = (\n                    node.input[1] if \"TensorListFromTensor\" in node.op else node.input[0]\n                )\n                input_shape_name = input_shape_name.split(\":\")[0]\n                input_shape_node = self._tf_node_map[input_shape_name]\n                shape_attr = parse_attr(input_shape_node.attr)\n                elem_shape = []\n\n                self._parse_element_shape(elem_shape, shape_attr)\n\n                if elem_shape:\n                    attr[\"shape\"] = elem_shape\n                if (\n                    \"identical_element_shapes\" in attr and attr[\"identical_element_shapes\"]\n                ) or elem_shape:\n                    shape = elem_shape\n                    if node.name in self._tensor_list_shapes:\n                        preset_shape = self._tensor_list_shapes[node.name]\n                        shape = _get_more_static_shape_rank(shape, preset_shape)\n                    attr[\"shape\"] = shape\n\n            op = self._convert_operator(graph, node.op, node.name, inputs, attr)\n            if isinstance(op, np.ndarray):\n                self._params[node.name] = tvm.nd.array(op)\n                op = [\n                    _expr.var(\n                        node.name,\n                        shape=self._params[node.name].shape,\n                        dtype=self._params[node.name].dtype,\n                    )\n                ]\n            elif isinstance(op, (_expr.Expr, _expr.TupleGetItem)):\n                op = [op]\n            self._nodes[input_op_name] = op\n\n        out = self._nodes[input_op_name]\n        if isinstance(out, _expr.TupleWrapper):\n            tn = node_name.split(\":\")\n            tensor_slot = int(tn[1]) if len(tn) > 1 else 0\n            return out[tensor_slot]\n\n        return out[0]\n\n\ndef _partition_call_operator(module, graph, inputs, attr, prelude, gdef_lib):\n    \"\"\"convert tf PartitionedCall node to a relay function call\"\"\"\n    node_func_name = attr.get(\"f\").name\n    return _convert_function(\n        module, graph, inputs, attr, node_func_name, prelude, gdef_lib=gdef_lib\n    )\n\n\ndef _convert_if(module, graph, inputs, attr, prelude, gdef_lib):\n    \"\"\"Convert tf If/StatelessIf to Relay If\"\"\"\n    cond_expr = inputs[0]\n    branch_names = [attr.get(x).name for x in [\"then_branch\", \"else_branch\"]]\n    then_fn, else_fn = [\n        _convert_function(module, graph, inputs[1:], attr, name, prelude, gdef_lib=gdef_lib)\n        for name in branch_names\n    ]\n    out = _expr.If(cond_expr, then_fn, else_fn)\n    return out\n\n\ndef _convert_loop(module, graph, inputs, attr, node_name, nodes, prelude, gdef_lib):\n    \"\"\"convert tf while_loop to Relay loop\"\"\"\n    input_size = len(inputs)\n    cond_fn_name, body_fn_name = [attr.get(x).name for x in [\"cond\", \"body\"]]\n\n    def convert_vars(loop_inputs, input_signature):\n        \"\"\"convert inputs to relay vars to be used as loop variables\n        Loop inputs are packed as:\n            [iteration_number, max_iterations, loop_variables...]\n        \"\"\"\n        new_vars = []\n        for i, v in enumerate(loop_inputs):\n            if isinstance(v, _expr.Constant):\n                vtype = _infer_type(v).checked_type.dtype\n                new_vars.append(_expr.var(input_signature[i].name, shape=(), dtype=vtype))\n            else:\n                vtype = _infer_type_with_prelude(v, prelude)\n                new_vars.append(_expr.var(input_signature[i].name, type_annotation=vtype))\n        return new_vars\n\n    while_func = next(\n        (f for f in graph.library.function if f.signature.name == attr[\"body\"].name),\n        None,\n    )\n    loop_inputs = convert_vars(inputs, while_func.signature.input_arg)\n\n    def cond_fn(*loop_inputs):\n        return _convert_function(\n            module, graph, loop_inputs, attr, cond_fn_name, prelude, gdef_lib=gdef_lib\n        )\n\n    # Define the loop body, in this function we need to unpack loop inputs,\n    # convert the loop subgraph, and pack outputs for the next iteration.\n    def body_fn(*loop_inputs):\n        # Increment loop iteration counter\n        loop_count = loop_inputs[0] + _expr.const(1, dtype=\"int32\")\n        max_count = loop_inputs[1]\n        fn = _convert_function(\n            module, graph, loop_inputs, attr, body_fn_name, prelude, gdef_lib=gdef_lib\n        )\n\n        # Repack loop variables\n        out = [loop_count, max_count] + [_expr.TupleGetItem(fn, i) for i in range(2, input_size)]\n        return out\n\n    loop = _while_loop(cond_fn, loop_inputs, body_fn)\n    outputs = loop(*inputs)\n    outputs = _expr.TupleWrapper(\n        _expr.Tuple([_expr.TupleGetItem(outputs, i) for i in range(input_size)]), input_size\n    )\n    return outputs\n\n\ndef _convert_function(\n    module, graph, inputs, attr, node_func_name, prelude, gdef_lib, in_shapes=None\n):\n    \"\"\"Convert given tf node to a relay function call\n\n    Parameters\n    ----------\n    module : IRModule\n        where converted function is stored\n\n    graph: <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n        top level tf graphdef\n\n    inputs : List[tvm.relay.Expr]\n        List of input symbols. Parameters for the function.\n\n    attrs : Dict[tvm.Attrs]\n        Dict of operator attributes.\n\n    node_func_name : str\n        Name of tf2 node to be converted\n\n    Returns\n    -------\n    op : tvm.relay.Expr\n        <class 'tvm.relay.expr.Call'>\n\n    Examples\n    --------\n    a tf function \"x+1\", is implemented as a subgraph in the library section of the graph.\n    this subgraph is converted to a relay function such as\n        fn (%x: float32) {\n        add(%x, 1f) /* Identity */\n        }\n\n    the subgraph has a function name such as __inference_add_95\n    the tf function call operator is returned as relay expression, such as:\n        free_var %x: float32;\n        @func___inference_add_95(%x)\n\n    \"\"\"\n    func = next(\n        (f for f in graph.library.function if f.signature.name == node_func_name),\n        None,\n    )\n    if func is None:\n        raise Exception(\"Function not found - {}\".format(node_func_name))\n    devices = set(node.device for node in func.node_def)\n    if len(devices) > 1:\n        raise Exception(\n            \"node_def in function {} contains > 1 types of devices {}\".format(\n                node_func_name, devices\n            )\n        )\n\n    subgraph = gdef_lib[node_func_name]\n    # preserve library functions in subgraphs to make them available to nested functions\n    for fn in graph.library.function:\n        subgraph.library.function.add().CopyFrom(fn)\n\n    # Computing subgraph's input shape and type dictionaries\n    input_expr_dict = {}\n    input_types = {}\n    for f_arg, input_ in zip(func.signature.input_arg, inputs):\n        input_expr_dict[f_arg.name] = input_\n        input_types[f_arg.name] = _infer_type_with_prelude(input_, prelude)\n\n    func_name = \"func_{}\".format(func.signature.name)\n    try:\n        global_func = module.mod[func_name]\n        sub_func = global_func\n        sub_params = module.params\n    except ValueError:\n        # Construct relay nodes from the subgraph\n        g1 = GraphProto(module)\n        output_sig = [func.ret[f.name] for f in func.signature.output_arg]\n        # TODO: unify prelude and main IRModules\n        sub_func, sub_params = g1.from_tensorflow(\n            subgraph, outputs=output_sig, input_types=input_types, gdef_lib=gdef_lib\n        )\n        module.params.update(sub_params)\n        func_expr = _function.Function(sub_func.params, sub_func.body)\n        global_func = tvm.relay.GlobalVar(func_name)\n        module.mod[global_func] = func_expr\n        module.mod = InferType()(module.mod)\n        prelude.mod = module.mod\n\n    param_exprs = []\n    for param_expr in sub_func.params:\n        # sub_params is subset of sub_func.params\n        param_name = param_expr.vid.name_hint\n        if param_name in input_expr_dict.keys():\n            param_exprs.append(input_expr_dict[param_name])\n        elif param_name in sub_params.keys():\n            param_exprs.append(param_expr)\n        else:\n            raise Exception(\"Input parameter {} not found\".format(param_name))\n\n    sb = tvm.relay.scope_builder.ScopeBuilder()\n    loop_ret = global_func(*param_exprs)\n    sb.ret(loop_ret)\n    ret = sb.get()\n    return ret\n\n\ndef from_tensorflow(graph_def, layout=\"NHWC\", shape=None, outputs=None):\n    \"\"\"convert tensorflow2.x graph into relay function.\n\n    Parameters\n    ----------\n    graph_def : must be frozen graph (no variables allowed).\n        Placeholders are assumed to be inputs to the graph.\n\n        tensorflow/core/framework/graph.proto\n            message GraphDef {\n              repeated NodeDef node = 1;\n              FunctionDefLibrary library = 2;\n            }\n        tensorflow/core/framework/function.proto\n            message FunctionDef {\n              repeated NodeDef node_def = 3;\n            }\n\n    layout : str\n        The layout for the model.\n\n    shape : List[str, List[int]]\n        Input to the model. It is a key and shape vector mapping. Applies to placeholders.\n\n    outputs : List[str]\n        The list of output nodes. The last node is treated as the output if not\n        specified.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The module that optimizations will be performed on.\n\n    params : dict of str to tvm.nd.NDArray\n        Dict of converted parameters stored in tvm.nd.NDArray format.\n\n    Examples\n    --------\n    \"x+1\" tf module where x has a shape of (2,2) is converted as follows:\n\n    mod : tvm.IRModule\n        def @func___inference_add_95(%x: Tensor[(2, 2), float32], %add/y: Tensor[(2, 2), float32])\n        -> Tensor[(2, 2), float32] {\n        add(%x, %add/y) /* Identity */ /* ty=Tensor[(2, 2), float32] */\n        }\n\n        def @main(%x1: Tensor[(2, 2), float32], %add/y1: Tensor[(2, 2), float32]) {\n        @func___inference_add_95(%x1, %add/y1) /* Identity */\n        }\n\n    params : dict of str to tvm.nd.NDArray\n        {'add/y': <tvm.nd.NDArray shape=(2, 2), cpu(0)>\n\n    \"\"\"\n\n    with tf.Graph().as_default():\n        tf.import_graph_def(graph_def, name=\"\")\n        # Subgraph graph_defs are cached here to avoid a TF error when parsing after prelude init\n        graph_def_library = {}\n        for func in graph_def.library.function:\n            inshape = func.attr[\"_input_shapes\"].list.shape\n            (\n                graph_def_library[func.signature.name],\n                _,\n            ) = function_def_to_graph.function_def_to_graph_def(func, inshape)\n        module = RelayModule()\n        g = GraphProto(module)\n        func, params = g.from_tensorflow(\n            graph_def, layout, shape, outputs, gdef_lib=graph_def_library\n        )\n        module.mod[\"main\"] = func\n        module.params.update(params)\n        return module.mod, module.params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tensorflow2_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n\"\"\"Tensorflow2.x to relay converter ops and helper\"\"\"\nimport tvm\nfrom tvm.relay.prelude import StaticTensorArrayOps, get_tensor_array_shape\n\nfrom .. import op as _op\nfrom ..ty import Any\nfrom .common import infer_value as _infer_value\nfrom .common import infer_type as _infer_type\nfrom .tensorflow_ops import _get_more_static_shape_rank\n\n\ndef _infer_type_with_prelude(val, prelude):\n    body = _infer_type(val, prelude.mod)\n    return body.checked_type\n\n\ndef _need_prelude_for_shape_inference(op):\n    return \"TensorList\" in op or \"TensorArray\" in op\n\n\ndef _tensorlist_reserve():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"element_dtype\").name\n        elem_shape = _infer_value(inputs[0], params, prelude.mod)\n        elem_shape = tuple(elem_shape.numpy().astype(\"int32\").flatten())\n\n        if elem_shape or \"shape\" in attr:\n            shape = attr[\"shape\"] if \"shape\" in attr else elem_shape\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, shape)\n            static_tensor_array_ops.register()\n            tensor_array_constructor = static_tensor_array_ops.get_global_var(\"tensor_array\")\n            tensor_array = tensor_array_constructor(inputs[1])\n        else:\n            tensor_array_constructor = prelude.get_global_var(\"tensor_array\", dtype_str)\n            tensor_array = tensor_array_constructor(inputs[1])\n        return tensor_array\n\n    return _impl\n\n\ndef _tensorlist_set_item():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"element_dtype\").name\n        input_ta = inputs[0]\n        input_ta_shape = get_tensor_array_shape(input_ta, dtype_str, prelude)\n        input_t_shape = _infer_type_with_prelude(inputs[2], prelude).shape\n        input_rank = len(input_t_shape)\n\n        if input_ta_shape is None:\n            tensor_name = \"tensor{}\".format(input_rank)\n            tensor_func = prelude.get_tensor_ctor(tensor_name, dtype_str)\n            v = tensor_func(inputs[2])\n            write_func = prelude.get_global_var(\"tensor_array_write\", dtype_str)\n            out = write_func(input_ta, inputs[1], v)\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_ta_shape)\n            static_tensor_array_ops.register()\n            tensor_func = static_tensor_array_ops.get_ctor(\"tensor_constructor\")\n            v = tensor_func(inputs[2])\n            # Write tensor with more static shape\n            # convert shape with -1 to any()\n            input_ta_shape_a = []\n            for dim in input_ta_shape:\n                if isinstance(dim, (int, tvm.tir.expr.IntImm)):\n                    if dim < 0:\n                        input_ta_shape_a.append(Any())\n                    else:\n                        input_ta_shape_a.append(dim)\n                else:\n                    input_ta_shape_a.append(dim)\n            actual_shape = _get_more_static_shape_rank(input_t_shape, input_ta_shape_a)\n            if actual_shape != input_ta_shape_a:\n                new_shape = []\n                num_any_dim = 0\n                for dim in actual_shape:\n                    if not isinstance(dim, int):\n                        num_any_dim += 1\n                    new_shape.append(dim if isinstance(dim, int) else -1)\n                if num_any_dim <= 1:\n                    v = tensor_func(_op.reshape(inputs[2], new_shape))\n            write_func = prelude.get_global_var_static(\n                \"tensor_array_write\", dtype_str, input_ta_shape_a\n            )\n            out = write_func(input_ta, inputs[1], v)\n        return out\n\n    return _impl\n\n\ndef _tensorlist_get_item():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr[\"element_dtype\"].name\n        input_shape = get_tensor_array_shape(inputs[0], dtype_str, prelude)\n\n        if input_shape is None:\n            read_func = prelude.get_global_var(\"tensor_array_read\", dtype_str)\n            out = read_func(inputs[0], _op.take(inputs[1], tvm.relay.const(0)))\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_shape)\n            static_tensor_array_ops.register()\n            read_func = static_tensor_array_ops.get_global_var(\"tensor_array_read\")\n            out_tensor = read_func(inputs[0], _op.take(inputs[1], tvm.relay.const(0)))\n            get_data_func = static_tensor_array_ops.get_global_var(\"tensor_get_data\")\n            out = get_data_func(out_tensor)\n        return out\n\n    return _impl\n\n\ndef _tensorlist_stack():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr[\"element_dtype\"].name\n        input_ta_shape = get_tensor_array_shape(inputs[0], dtype_str, prelude)\n\n        if input_ta_shape is None:\n            stack_func = prelude.get_global_var(\"tensor_array_stack\", dtype_str)\n            out = stack_func(inputs[0])\n        else:\n            if \"num_elements\" in attr:\n                num_elements = attr[\"num_elements\"]\n            static_tensor_array_ops = StaticTensorArrayOps(\n                prelude, dtype_str, input_ta_shape, num_elements\n            )\n            static_tensor_array_ops.register()\n            stack_func = prelude.get_global_var_static(\n                \"tensor_array_stack\", dtype_str, input_ta_shape, num_elements\n            )\n            out_tensor = stack_func(inputs[0])\n            out_shape = (\n                (num_elements,) + input_ta_shape\n                if num_elements and num_elements == 1\n                else (Any(),) + input_ta_shape\n            )\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, out_shape)\n            static_tensor_array_ops.register()\n            get_data_func = prelude.get_global_var_static(\"tensor_get_data\", dtype_str, out_shape)\n            out = get_data_func(out_tensor)\n\n        return out\n\n    return _impl\n\n\ndef _tensorlist_from_tensor():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr[\"element_dtype\"].name\n        input_ta_shape = _infer_type_with_prelude(inputs[0], prelude).shape\n\n        if input_ta_shape is None:\n            unstack_func = prelude.get_global_var(\"tensor_array_unstack\", dtype_str)\n            out = unstack_func(inputs[0])\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_ta_shape)\n            static_tensor_array_ops.register()\n            unstack_func = prelude.get_global_var_static(\n                \"tensor_array_unstack\", dtype_str, input_ta_shape\n            )\n            out = unstack_func(inputs[0])\n        return out\n\n    return _impl\n\n\n_convert_map = {\n    \"TensorListFromTensor\": _tensorlist_from_tensor(),\n    \"TensorListGetItem\": _tensorlist_get_item(),\n    \"TensorListReserve\": _tensorlist_reserve(),\n    \"TensorListSetItem\": _tensorlist_set_item(),\n    \"TensorListStack\": _tensorlist_stack(),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tensorflow_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n# pylint: disable=import-outside-toplevel, redefined-builtin\n\"\"\"TF: Tensorflow frontend.\"\"\"\nimport warnings\nfrom collections import deque\n\n# Numpy support\nimport numpy as np\nimport tvm\n\nfrom tvm.relay.prelude import StaticTensorArrayOps, get_tensor_array_shape\nfrom tvm.topi.utils import get_const_tuple\n\nfrom .. import expr as _expr\nfrom .. import op as _op\nfrom ..ty import Any\nfrom .common import AttrCvt, get_relay_op\nfrom .common import infer_type as _infer_type\nfrom .common import infer_shape as _infer_shape\nfrom .common import infer_channels as _infer_channels\nfrom .common import infer_value as _infer_value\n\n\ndef check_symbolic_shape(shape):\n    return not all([isinstance(dim, (int, tvm.tir.IntImm)) for dim in shape])\n\n\ndef list_shape_of(tensor, ndim):\n    shape_tensor = _op.shape_of(tensor)\n    return [\n        _op.strided_slice(shape_tensor, begin=[i], end=[i + 1], strides=[1]) for i in range(ndim)\n    ]\n\n\ndef _get_pad_pair(input1d, kernel1d, stride1d):\n    if isinstance(input1d, tvm.tir.Any) and stride1d != 1:\n        raise tvm.error.OpAttributeUnImplemented(\n            \"SAME padding is not supported in combination with dynamic height or width when stride\"\n            \" is not 1.\"\n        )\n    if stride1d == 1 or input1d % stride1d == 0:\n        pad = max(kernel1d - stride1d, 0)\n    else:\n        pad = max(kernel1d - (input1d % stride1d), 0)\n\n    pad_before = pad // 2\n    pad_after = pad - pad_before\n\n    return [pad_before, pad_after]\n\n\ndef _math_name_picker(surfix):\n    def _impl(attr):\n        return \"broadcast_\" + surfix\n\n    return _impl\n\n\ndef _dimension_picker(prefix, surfix=\"\"):\n    def _impl(attr):\n        kernel = attr[\"kernel_shape\"]\n        if len(kernel) == 2:\n            return prefix + \"2d\" + surfix\n        if len(kernel) == 3:\n            return prefix + \"3d\" + surfix\n        raise tvm.error.OpAttributeInvalid(\n            \"Only 2D or 3D kernels are supported for operator {}\".format(prefix + \"2d or 3d\")\n        )\n\n    return _impl\n\n\ndef _dimension_constraint():\n    def _dim_check(attrs):\n        if len(attrs[\"kernel_shape\"]) in (2, 3):\n            return True\n        return False\n\n    return _dim_check, \"Only 2d or 3d kernel supported.\"\n\n\ndef _get_param(params, input_node):\n    if isinstance(input_node, _expr.Constant):\n        return np.atleast_1d(input_node.data.numpy())\n    return params[input_node.name_hint].numpy()\n\n\ndef _get_num_param(params, input_node):\n    return _get_param(params, input_node).item()\n\n\ndef _get_list_param(params, input_node, mod):\n    try:\n        return _get_param(params, input_node).tolist()\n    except (IndexError, KeyError, AttributeError):\n        return _infer_value(input_node, params, mod).numpy().tolist()\n\n\ndef _get_tuple_param(params, input_node):\n    return tuple(_get_param(params, input_node))\n\n\ndef _need_prelude_for_shape_inference(op):\n    return \"TensorArray\" in op\n\n\ndef _get_more_static_shape(shape0, shape1):\n    \"\"\"Compare two shapes with the same rank,\n    and return the one with fewer symbolic dimension.\n    \"\"\"\n    assert len(shape0) == len(shape1)\n    num_sym_dim0 = 0\n    num_sym_dim1 = 0\n    for dim0, dim1 in zip(list(shape0), list(shape1)):\n        if not isinstance(dim0, int):\n            num_sym_dim0 += 1\n        if not isinstance(dim1, int):\n            num_sym_dim1 += 1\n\n    if num_sym_dim0 < num_sym_dim1:\n        return shape0\n    return shape1\n\n\ndef _get_more_static_shape_rank(shape0, shape1):\n    \"\"\"Compare two shapes with different rank,\n    and return the one with fewer symbolic dimension.\n    \"\"\"\n    num_sym_dim0 = sum([not isinstance(dim, (int, tvm.tir.expr.IntImm)) for dim in list(shape0)])\n    num_sym_dim1 = sum([not isinstance(dim, (int, tvm.tir.expr.IntImm)) for dim in list(shape1)])\n\n    if num_sym_dim0 < num_sym_dim1:\n        return shape0\n    return shape1\n\n\ndef _rsqrt():\n    def _impl(inputs, attr, params, mod):\n        inputs.append(tvm.relay.const(-0.5, attr[\"T\"].name))\n        return AttrCvt(op_name=\"power\")(inputs, attr)\n\n    return _impl\n\n\ndef _argx(func, func_name):\n    \"\"\"A common wrapper for argmin and argmax operations\"\"\"\n\n    def _impl(inputs, attr, params, mod):\n        try:\n            # In Tensorflow, `axis` argument is a Tensor, not attribute. We\n            # support the case where it inputs from a scalar constant.\n            axis_input_value = [_get_num_param(params, inputs[1])]\n        except (IndexError, KeyError):\n            raise TypeError(\n                \"Unsupported argument for `{}` : `axis` should be a constant\".format(func_name)\n            )\n        out = func(inputs[0], axis=axis_input_value, keepdims=False)\n        dtype = attr[\"output_type\"].name\n        if dtype != \"int32\":\n            out = _op.cast(out, dtype=dtype)\n        return out\n\n    return _impl\n\n\ndef _elemwise(name):\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 2, \"{} take 2 inputs, {} given\".format(name, len(inputs))\n        return get_relay_op(name)(*inputs)\n\n    return _impl\n\n\ndef _pool3d(name):\n    def _impl(inputs, attr, params, mod):\n        attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n        flip_layout = False\n\n        input_shape = _infer_shape(inputs[0], mod)\n\n        if attr[\"data_format\"] == \"NDHWC\":\n            attr[\"kernel_shape\"] = (attr[\"ksize\"][1], attr[\"ksize\"][2], attr[\"ksize\"][3])\n            attr[\"strides\"] = (attr[\"strides\"][1], attr[\"strides\"][2], attr[\"strides\"][3])\n        elif attr[\"data_format\"] == \"NCDHW\":\n            attr[\"kernel_shape\"] = (attr[\"ksize\"][2], attr[\"ksize\"][3], attr[\"ksize\"][4])\n            attr[\"strides\"] = (attr[\"strides\"][2], attr[\"strides\"][3], attr[\"strides\"][4])\n        else:\n            msg = 'Value {} of attribute \"data_format\" of operator Pooling ' \"is not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"data_format\"]))\n        if attr[\"data_format\"] == \"NDHWC\":\n            input_shape = [_infer_shape(inputs[0], mod)[i] for i in (0, 4, 1, 2, 3)]\n            inputs[0] = _op.transpose(inputs[0], axes=(0, 4, 1, 2, 3))\n            attr[\"data_format\"] = \"NCDHW\"\n            flip_layout = True\n\n        attr[\"padding\"] = attr[\"padding\"].decode(\"utf-8\")\n\n        if attr[\"padding\"] == \"VALID\":\n            attr[\"padding\"] = [0, 0, 0, 0, 0, 0]\n        elif attr[\"padding\"] == \"SAME\":\n            stride_d, stride_h, stride_w = attr[\"strides\"]\n            kernel_d, kernel_h, kernel_w = attr[\"kernel_shape\"]\n            if attr[\"data_format\"] == \"NDHWC\":\n                in_d = input_shape[1]\n                in_h = input_shape[2]\n                in_w = input_shape[3]\n            else:\n                in_d = input_shape[2]\n                in_h = input_shape[3]\n                in_w = input_shape[4]\n            pad_d = _get_pad_pair(in_d, kernel_d, stride_d)\n            pad_v = _get_pad_pair(in_h, kernel_h, stride_h)\n            pad_h = _get_pad_pair(in_w, kernel_w, stride_w)\n\n            attr[\"padding\"] = [pad_d[0], pad_v[0], pad_h[0], pad_d[1], pad_v[1], pad_h[1]]\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Pooling is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"padding\"]))\n\n        if name == \"avg_pool\":\n            attr[\"count_include_pad\"] = False\n        attr[\"ceil_mode\"] = False\n        out = AttrCvt(\n            op_name=name,\n            transforms={\"kernel_shape\": \"pool_size\", \"data_format\": \"layout\"},\n            ignores=[\"ksize\"],\n        )(inputs, attr)\n        if flip_layout:\n            out = _op.transpose(out, axes=(0, 2, 3, 4, 1))\n        return out\n\n    return _impl\n\n\ndef _pooling(name):\n    def _impl(inputs, attr, params, mod):\n\n        attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n        flip_layout = False\n\n        input_shape = _infer_shape(inputs[0], mod)\n\n        if attr[\"data_format\"] == \"NHWC\":\n            attr[\"kernel_shape\"] = (attr[\"ksize\"][1], attr[\"ksize\"][2])\n            attr[\"strides\"] = (attr[\"strides\"][1], attr[\"strides\"][2])\n        elif attr[\"data_format\"] == \"NCHW\":\n            attr[\"kernel_shape\"] = (attr[\"ksize\"][2], attr[\"ksize\"][3])\n            attr[\"strides\"] = (attr[\"strides\"][2], attr[\"strides\"][3])\n        else:\n            msg = 'Value {} of attribute \"data_format\" of operator Pooling ' \"is not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"data_format\"]))\n\n        if attr[\"_target_layout\"] == \"NCHW\" and attr[\"data_format\"] == \"NHWC\":\n            tmp_shape = _infer_shape(inputs[0], mod)\n            input_shape = [tmp_shape[ii] for ii in (0, 3, 1, 2)]\n            inputs[0] = _op.transpose(inputs[0], axes=(0, 3, 1, 2))\n            attr[\"data_format\"] = \"NCHW\"\n            flip_layout = True\n\n        # Fix padding\n        attr[\"padding\"] = attr[\"padding\"].decode(\"utf-8\")\n\n        if attr[\"padding\"] == \"VALID\":\n            attr[\"padding\"] = [0, 0]\n        elif attr[\"padding\"] == \"SAME\":\n            stride_h, stride_w = attr[\"strides\"]\n            kernel_h, kernel_w = attr[\"kernel_shape\"]\n            if attr[\"data_format\"] == \"NHWC\":\n                in_h = input_shape[1]\n                in_w = input_shape[2]\n            else:\n                in_h = input_shape[2]\n                in_w = input_shape[3]\n\n            pad_v = _get_pad_pair(in_h, kernel_h, stride_h)\n            pad_h = _get_pad_pair(in_w, kernel_w, stride_w)\n\n            attr[\"padding\"] = [pad_v[0], pad_h[0], pad_v[1], pad_h[1]]\n        elif attr[\"padding\"] == \"EXPLICIT\":\n            paddings = attr[\"explicit_paddings\"]\n            assert len(paddings) == 8\n            if flip_layout or attr[\"data_format\"] == \"NHWC\":\n                attr[\"padding\"] = [paddings[2], paddings[4], paddings[3], paddings[5]]\n            else:\n                attr[\"padding\"] = [paddings[4], paddings[6], paddings[5], paddings[7]]\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Pooling is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"padding\"]))\n\n        if name == \"avg_pool\":\n            attr[\"count_include_pad\"] = False\n\n        out = AttrCvt(\n            op_name=_dimension_picker(name),\n            transforms={\"kernel_shape\": \"pool_size\", \"data_format\": \"layout\"},\n            ignores=[\"ksize\", \"explicit_paddings\"],\n            extras={\"ceil_mode\": False},\n            custom_check=_dimension_constraint(),\n        )(inputs, attr)\n\n        if flip_layout:\n            out = _op.transpose(out, axes=(0, 2, 3, 1))\n\n        return out\n\n    return _impl\n\n\ndef _conv(opname):\n    def _impl(inputs, attr, params, mod):\n        attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n        flip_layout = False\n\n        if opname == \"conv_transpose\" and attr[\"data_format\"] == \"NHWC\":\n            # transform to NCHW for TVM backend compatible and set 'flip_layout'\n            # to have output flip back to NHWC\n            inputs[2] = _op.transpose(inputs[2], axes=(0, 3, 1, 2))\n            attr[\"strides\"][1], attr[\"strides\"][2], attr[\"strides\"][3] = (\n                attr[\"strides\"][3],\n                attr[\"strides\"][1],\n                attr[\"strides\"][2],\n            )\n            attr[\"data_format\"] = \"NCHW\"\n\n            # Check whether output shapes attribute is set and not None\n            if (\n                opname == \"conv_transpose\"\n                and len(attr[\"_output_shapes\"]) > 0\n                and attr[\"_output_shapes\"][0]\n            ):\n                tmp_shape = attr[\"_output_shapes\"][0]\n                tmp_shape = [tmp_shape[ii] for ii in (0, 3, 1, 2)]\n                attr[\"_output_shapes\"][0] = tmp_shape\n\n            flip_layout = True\n\n        inputs_data = inputs[0] if opname != \"conv_transpose\" else inputs[2]\n\n        # NCHW Layout require weights transpose\n        weights_shape = _infer_shape(inputs[1], mod)\n        if attr[\"data_format\"] == \"NCHW\":\n            tmp_shape = weights_shape\n            if opname in [\"conv\", \"conv_transpose\"]:\n                tmp_shape = [tmp_shape[ii] for ii in (3, 2, 0, 1)]\n                inputs[1] = _op.transpose(inputs[1], axes=(3, 2, 0, 1))\n            else:\n                tmp_shape = [tmp_shape[ii] for ii in (2, 3, 0, 1)]\n                inputs[1] = _op.transpose(inputs[1], axes=(2, 3, 0, 1))\n            weights_shape = tmp_shape\n\n        input_shape = _infer_shape(inputs_data, mod)\n        if attr[\"_target_layout\"] == \"NCHW\" and attr[\"data_format\"] == \"NHWC\":\n            input_shape = [input_shape[ii] for ii in (0, 3, 1, 2)]\n            inputs_data = _op.transpose(inputs_data, axes=(0, 3, 1, 2))\n            if opname in [\"conv\", \"conv_transpose\"]:\n                weights_shape = [weights_shape[ii] for ii in (3, 2, 0, 1)]\n                inputs[1] = _op.transpose(inputs[1], axes=(3, 2, 0, 1))\n            else:\n                weights_shape = [weights_shape[ii] for ii in (2, 3, 0, 1)]\n                inputs[1] = _op.transpose(inputs[1], axes=(2, 3, 0, 1))\n\n            attr[\"data_format\"] = \"NCHW\"\n            attr[\"strides\"] = [attr[\"strides\"][ii] for ii in (0, 3, 1, 2)]\n            flip_layout = True\n\n        if attr[\"data_format\"] == \"NHWC\":\n            in_channels = input_shape[3]\n            kernel_h, kernel_w, _, depth_mult = weights_shape\n            attr[\"kernel_shape\"] = (weights_shape[0], weights_shape[1])\n            if opname == \"conv\":\n                attr[\"channels\"] = weights_shape[3]\n            elif opname == \"conv_transpose\":\n                attr[\"channels\"] = weights_shape[2]\n            else:\n                attr[\"channels\"] = input_shape[3] * depth_mult\n\n            if \"dilations\" in attr:\n                attr[\"dilations\"] = (attr[\"dilations\"][1], attr[\"dilations\"][2])\n            attr[\"strides\"] = (attr[\"strides\"][1], attr[\"strides\"][2])\n        elif attr[\"data_format\"] == \"NCHW\":\n            in_channels = input_shape[1]\n            _, depth_mult, kernel_h, kernel_w = weights_shape\n            attr[\"kernel_shape\"] = (weights_shape[2], weights_shape[3])\n            if opname == \"conv\":\n                attr[\"channels\"] = weights_shape[0]\n            elif opname == \"conv_transpose\":\n                attr[\"channels\"] = weights_shape[1]\n            else:\n                attr[\"channels\"] = input_shape[1] * depth_mult\n                if attr[\"channels\"] < 0:\n                    attr[\"channels\"] *= -1\n\n            if \"dilations\" in attr:\n                attr[\"dilations\"] = (attr[\"dilations\"][2], attr[\"dilations\"][3])\n            attr[\"strides\"] = (attr[\"strides\"][2], attr[\"strides\"][3])\n        else:\n            msg = 'Value {} in attribute \"data_format\" of operator Conv is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"data_format\"]))\n\n        if opname == \"depthwise\":\n            attr[\"groups\"] = in_channels\n\n        # Fix padding\n        attr[\"padding\"] = attr[\"padding\"].decode(\"utf-8\")\n\n        if attr[\"padding\"] == \"VALID\":\n            attr[\"padding\"] = [0, 0]\n        elif attr[\"padding\"] == \"SAME\":\n            stride_h, stride_w = attr[\"strides\"]\n            kernel_h, kernel_w = attr[\"kernel_shape\"]\n\n            pdata_shape = input_shape\n            # Check whether output shapes attribute is set and not None\n            if (\n                opname == \"conv_transpose\"\n                and len(attr[\"_output_shapes\"]) > 0\n                and attr[\"_output_shapes\"][0]\n            ):\n                pdata_shape = attr[\"_output_shapes\"][0]\n\n            if attr[\"data_format\"] == \"NHWC\":\n                in_h = pdata_shape[1]\n                in_w = pdata_shape[2]\n            else:\n                in_h = pdata_shape[2]\n                in_w = pdata_shape[3]\n\n            dilation_h = attr[\"dilations\"][0]\n            dilation_w = attr[\"dilations\"][1]\n            dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n            dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n            pad_v = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n            pad_h = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n\n            attr[\"padding\"] = [pad_v[0], pad_h[0], pad_v[1], pad_h[1]]\n        elif attr[\"padding\"] == \"EXPLICIT\":\n            paddings = attr[\"explicit_paddings\"]\n            assert len(paddings) == 8\n            if flip_layout or attr[\"data_format\"] == \"NHWC\":\n                attr[\"padding\"] = [paddings[2], paddings[4], paddings[3], paddings[5]]\n            else:\n                attr[\"padding\"] = [paddings[4], paddings[6], paddings[5], paddings[7]]\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Conv is not ' \"valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"padding\"]))\n\n        if \"kernel_layout\" not in attr:\n            if opname == \"conv\":\n                attr[\"kernel_layout\"] = \"HWIO\" if attr[\"data_format\"] == \"NHWC\" else \"OIHW\"\n            elif opname == \"conv_transpose\":\n                # conv_transpose in TVM has weights be IOHW for NCHW\n                attr[\"kernel_layout\"] = \"HWIO\" if attr[\"data_format\"] == \"NHWC\" else \"IOHW\"\n            else:\n                attr[\"kernel_layout\"] = \"HWOI\" if attr[\"data_format\"] == \"NHWC\" else \"OIHW\"\n\n        # Ignore the new attributes from TF2.0, for now.\n        out = AttrCvt(\n            op_name=_dimension_picker(\n                \"conv\", surfix=\"_transpose\" if opname == \"conv_transpose\" else \"\"\n            ),\n            ignores=[\"explicit_paddings\"],\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"data_format\": \"data_layout\",\n                \"dilations\": (\"dilation\", (0, 0)),\n                \"group\": (\"groups\", 1),\n            },\n            custom_check=_dimension_constraint(),\n        )([inputs_data, inputs[1]], attr)\n\n        if flip_layout:\n            out = _op.transpose(out, axes=(0, 2, 3, 1))\n\n        return out\n\n    return _impl\n\n\n# Dilation2d\ndef _dilation2d():\n    def _impl(inputs, attr, params, mod):\n        if \"data_format\" not in attr:\n            attr[\"data_format\"] = \"NHWC\"\n\n        input_shape = _infer_shape(inputs[0], mod)\n        weights_shape = _infer_shape(inputs[1], mod)\n\n        if attr[\"_target_layout\"] == \"NCHW\" and attr[\"data_format\"] == \"NHWC\":\n            input_shape = [input_shape[ii] for ii in (0, 3, 1, 2)]\n            inputs[0] = _op.transpose(inputs[0], axes=(0, 3, 1, 2))\n            weights_shape = [weights_shape[ii] for ii in (2, 0, 1)]\n            inputs[1] = _op.transpose(inputs[1], axes=(2, 0, 1))\n            attr[\"data_format\"] = \"NCHW\"\n\n        if attr[\"data_format\"] in [\"NHWC\", \"NCHW\"]:\n            if \"rates\" in attr:\n                attr[\"dilations\"] = attr[\"rates\"]\n            if \"dilations\" in attr:\n                attr[\"dilations\"] = (attr[\"dilations\"][1], attr[\"dilations\"][2])\n            attr[\"strides\"] = (attr[\"strides\"][1], attr[\"strides\"][2])\n        else:\n            msg = 'Value {} in attribute \"data_format\" of operator Dilation2D is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"data_format\"]))\n\n        attr[\"padding\"] = attr[\"padding\"].decode(\"utf-8\")\n        if attr[\"padding\"] == \"VALID\":\n            attr[\"padding\"] = [0, 0]\n        elif attr[\"padding\"] == \"SAME\":\n            stride_h, stride_w = attr[\"strides\"]\n            if attr[\"data_format\"] == \"NHWC\":\n                kernel_h, kernel_w = weights_shape[0], weights_shape[1]\n            else:\n                kernel_h, kernel_w = weights_shape[1], weights_shape[2]\n            if attr[\"data_format\"] == \"NHWC\":\n                in_h = input_shape[1]\n                in_w = input_shape[2]\n            else:\n                in_h = input_shape[2]\n                in_w = input_shape[3]\n\n            dilation_h = attr[\"dilations\"][0]\n            dilation_w = attr[\"dilations\"][1]\n            dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n            dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n            pad_v = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n            pad_h = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n\n            if attr[\"data_format\"] == \"NHWC\":\n                inputs[0] = _op.nn.pad(\n                    data=inputs[0],\n                    pad_width=((0, 0), (pad_v[0], pad_v[1]), (pad_h[0], pad_h[1]), (0, 0)),\n                )\n            else:\n                inputs[0] = _op.nn.pad(\n                    data=inputs[0],\n                    pad_width=((0, 0), (0, 0), (pad_v[0], pad_v[1]), (pad_h[0], pad_h[1])),\n                )\n\n            attr[\"padding\"] = [0, 0]\n\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Dilation2d is not ' \"valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"padding\"]))\n\n        attr[\"kernel_layout\"] = \"HWI\" if attr[\"data_format\"] == \"NHWC\" else \"IHW\"\n        out = AttrCvt(\n            op_name=\"dilation2d\",\n            ignores=[\"explicit_paddings\", \"rates\"],\n            transforms={\n                \"data_format\": \"data_layout\",\n            },\n        )([inputs[0], inputs[1]], attr)\n        if attr[\"_target_layout\"] == \"NCHW\":\n            out = _op.transpose(out, axes=(0, 2, 3, 1))\n        return out\n\n    return _impl\n\n\ndef _conv3d(opname):\n    def _impl(inputs, attr, params, mod):\n        attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n        flip_layout = False\n\n        inputs_data = inputs[0] if opname != \"conv_transpose\" else inputs[2]\n\n        # NCDHW Layout require weights transpose\n        weights_shape = _infer_shape(inputs[1], mod)\n        if attr[\"data_format\"] == \"NCDHW\":\n            tmp_shape = weights_shape\n            tmp_shape = [tmp_shape[ii] for ii in (4, 3, 0, 1, 2)]\n            inputs[1] = _op.transpose(inputs[1], axes=(4, 3, 0, 1, 2))\n            weights_shape = tmp_shape\n\n        input_shape = _infer_shape(inputs_data, mod)\n\n        if attr[\"_target_layout\"] == \"NCDHW\" and attr[\"data_format\"] == \"NDHWC\":\n            input_shape = [input_shape[ii] for ii in (0, 4, 1, 2, 3)]\n            inputs_data = _op.transpose(inputs_data, axes=(0, 4, 1, 2, 3))\n            weights_shape = [weights_shape[ii] for ii in (4, 3, 0, 1, 2)]\n            inputs[1] = _op.transpose(inputs[1], axes=(4, 3, 0, 1, 2))\n\n            attr[\"data_format\"] = \"NCDHW\"\n            attr[\"strides\"] = [attr[\"strides\"][ii] for ii in (0, 4, 1, 2, 3)]\n            flip_layout = True\n\n        if attr[\"data_format\"] == \"NDHWC\":\n            kernel_d, kernel_h, kernel_w, _, _ = weights_shape\n            attr[\"kernel_shape\"] = (kernel_d, kernel_h, kernel_w)\n            if opname == \"conv\":\n                attr[\"channels\"] = weights_shape[4]\n            elif opname == \"conv_transpose\":\n                attr[\"channels\"] = weights_shape[3]\n\n            if \"dilations\" in attr:\n                attr[\"dilations\"] = (\n                    attr[\"dilations\"][1],\n                    attr[\"dilations\"][2],\n                    attr[\"dilations\"][3],\n                )\n            attr[\"strides\"] = (attr[\"strides\"][1], attr[\"strides\"][2], attr[\"strides\"][3])\n        elif attr[\"data_format\"] == \"NCDHW\":\n            _, _, kernel_d, kernel_h, kernel_w = weights_shape\n            attr[\"kernel_shape\"] = (kernel_d, kernel_h, kernel_w)\n            if opname == \"conv\":\n                attr[\"channels\"] = weights_shape[0]\n            elif opname == \"conv_transpose\":\n                attr[\"channels\"] = weights_shape[1]\n\n            if \"dilations\" in attr:\n                attr[\"dilations\"] = (\n                    attr[\"dilations\"][2],\n                    attr[\"dilations\"][3],\n                    attr[\"dilations\"][4],\n                )\n            attr[\"strides\"] = (attr[\"strides\"][2], attr[\"strides\"][3], attr[\"strides\"][4])\n        else:\n            msg = 'Value {} in attribute \"data_format\" of operator Conv is ' \"not valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"data_format\"]))\n\n        # Fix padding\n        attr[\"padding\"] = attr[\"padding\"].decode(\"utf-8\")\n\n        if attr[\"padding\"] == \"VALID\":\n            attr[\"padding\"] = [0, 0, 0]\n        elif attr[\"padding\"] == \"SAME\":\n            stride_d, stride_h, stride_w = attr[\"strides\"]\n            kernel_d, kernel_h, kernel_w = attr[\"kernel_shape\"]\n\n            pdata_shape = input_shape\n            if opname == \"conv_transpose\" and len(attr[\"_output_shapes\"]) > 0:\n                pdata_shape = attr[\"_output_shapes\"][0]\n\n            if attr[\"data_format\"] == \"NDHWC\":\n                in_d = pdata_shape[1]\n                in_h = pdata_shape[2]\n                in_w = pdata_shape[3]\n            else:\n                in_d = pdata_shape[2]\n                in_h = pdata_shape[3]\n                in_w = pdata_shape[4]\n\n            dilation_d = attr[\"dilations\"][0]\n            dilation_h = attr[\"dilations\"][1]\n            dilation_w = attr[\"dilations\"][2]\n            dilated_kernel_d = (kernel_d - 1) * dilation_d + 1\n            dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n            dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n            pad_d = _get_pad_pair(in_d, dilated_kernel_d, stride_d)\n            pad_v = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n            pad_h = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n\n            attr[\"padding\"] = [pad_d[0], pad_v[0], pad_h[0], pad_d[1], pad_v[1], pad_h[1]]\n        elif attr[\"padding\"] == \"EXPLICIT\":\n            paddings = attr[\"explicit_paddings\"]\n            assert len(paddings) == 10\n            if flip_layout or attr[\"data_format\"] == \"NDHWC\":\n                attr[\"padding\"] = [\n                    paddings[2],\n                    paddings[4],\n                    paddings[6],\n                    paddings[3],\n                    paddings[5],\n                    paddings[7],\n                ]\n            else:\n                attr[\"padding\"] = [\n                    paddings[4],\n                    paddings[6],\n                    paddings[8],\n                    paddings[5],\n                    paddings[7],\n                    paddings[9],\n                ]\n        else:\n            msg = 'Value {} in attribute \"padding\" of operator Conv is not ' \"valid.\"\n            raise tvm.error.OpAttributeInvalid(msg.format(attr[\"padding\"]))\n\n        if \"kernel_layout\" not in attr:\n            attr[\"kernel_layout\"] = \"DHWIO\" if attr[\"data_format\"] == \"NDHWC\" else \"OIDHW\"\n\n        use_bias = len(inputs) == (3 if opname != \"conv_transpose\" else 4)\n        channel_axis = 1 if attr[\"data_format\"] == \"NCDHW\" else 4\n\n        # Ignore the new attributes from TF2.0, for now.\n        out = AttrCvt(\n            op_name=_dimension_picker(\n                \"conv\", surfix=\"_transpose\" if opname == \"conv_transpose\" else \"\"\n            ),\n            ignores=[\"explicit_paddings\", \"Tshape\"],\n            transforms={\n                \"kernel_shape\": \"kernel_size\",\n                \"data_format\": \"data_layout\",\n                \"dilations\": (\"dilation\", (0, 0)),\n                \"group\": (\"groups\", 1),\n            },\n            custom_check=_dimension_constraint(),\n        )([inputs_data, inputs[1]], attr)\n\n        if use_bias:\n            out = _op.nn.bias_add(\n                out, inputs[2] if opname != \"conv_transpose\" else inputs[3], axis=channel_axis\n            )\n\n        if flip_layout:\n            out = _op.transpose(out, axes=(0, 2, 3, 4, 1))\n\n        return out\n\n    return _impl\n\n\ndef _nms(return_scores=False):\n    def _impl(inputs, attr, params, mod):\n        # Get parameter values\n        try:\n            max_output_size = int(np.atleast_1d(inputs[2].data.numpy().astype(\"int64\"))[0])\n        except Exception:\n            try:\n                max_output_size = (\n                    _infer_value(inputs[2], params, mod).numpy().astype(\"int64\").tolist()[0]\n                )\n            except Exception:\n                max_output_size = inputs[2]\n        iou_threshold = np.atleast_1d(inputs[3].data.numpy())[0]\n        # score_threshold was introduced from V3\n        score_threshold = np.atleast_1d(inputs[4].data.numpy())[0] if len(inputs) > 4 else 0.0\n        pad_output = \"pad_to_max_output_size\"\n\n        # Generate data with shape (1, num_anchors, 5)\n        scores = AttrCvt(\n            op_name=\"expand_dims\",\n            ignores=[\"T_threshold\", pad_output],\n            extras={\"axis\": -1, \"num_newaxis\": 1},\n        )([inputs[1]], attr)\n        data = get_relay_op(\"concatenate\")([scores, inputs[0]], -1)\n        data = get_relay_op(\"expand_dims\")(data, 0, 1)\n\n        # reason why using get_valid_counts is for inference performance\n        ct, data, indices = get_relay_op(\"get_valid_counts\")(\n            data, score_threshold=score_threshold, id_index=-1, score_index=0\n        )\n        # TensorFlow NMS doesn't have parameter top_k\n        top_k = -1\n        # TF doesn't have class id for nms input\n        score_index = 0\n        nms_ret = get_relay_op(\"non_max_suppression\")(\n            data=data,\n            valid_count=ct,\n            indices=indices,\n            max_output_size=max_output_size,\n            iou_threshold=iou_threshold,\n            force_suppress=True,\n            top_k=top_k,\n            coord_start=1,\n            score_index=score_index,\n            id_index=-1,\n            return_indices=True,\n            invalid_to_bottom=False,\n        )\n\n        if pad_output in attr and attr[pad_output]:\n            return nms_ret\n        # squeeze it, TF NMS is not batched\n        size = get_relay_op(\"squeeze\")(nms_ret[1], axis=[1])\n        data_slice = get_relay_op(\"squeeze\")(nms_ret[0], axis=[0])\n\n        # slice to get the dynamic result\n        ret = get_relay_op(\"strided_slice\")(\n            data_slice, begin=_expr.const([0]), end=size, slice_mode=\"size\"\n        )\n\n        # NonMaxSuppressionV5 returns scores. pad_output is always False for NMSv5.\n        if return_scores:\n            if \"soft_nms_sigma\" in attr and attr[\"soft_nms_sigma\"] != 0.0:\n                raise tvm.error.OpAttributeUnImplemented(\n                    \"soft_nms_sigma for NonMaxSuppressionV5 is not supported\"\n                )\n            ret_scores = _op.take(inputs[1], ret, axis=0)\n            return _expr.TupleWrapper(_expr.Tuple([ret, ret_scores, size]), 3)\n\n        return ret\n\n    return _impl\n\n\ndef convert_combined_nms_with_all_class_nms(\n    batch_size,\n    max_output_boxes_per_batch,\n    num_class,\n    boxes,\n    scores,\n    max_output_boxes_per_class,\n    iou_threshold,\n    score_threshold,\n    max_total_size,\n    clip_boxes,\n):\n    \"\"\"Converts TF combined_nms using Relay all_class_max_suppression op\"\"\"\n    (selected_indices, selected_scores, num_detections,) = _op.vision.all_class_non_max_suppression(\n        boxes,\n        scores,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        output_format=\"tensorflow\",\n    )\n    box_range = _op.arange(\n        _op.const(0, dtype=\"int64\"), _op.const(max_total_size, dtype=\"int64\"), dtype=\"int64\"\n    )\n    assert isinstance(batch_size, int), \"dynamic batch size not supported yet.\"\n    tile_batch_reps = _op.const([batch_size, 1])\n    box_range_2d = _op.tile(box_range, tile_batch_reps)\n    valid_mask = _op.cast(\n        _op.less(box_range_2d, _op.expand_dims(num_detections, axis=1)), \"float32\"\n    )\n\n    def select_topk(do_zero_pad):\n        def true_branch():\n            arange = _op.arange(\n                _op.const(0, dtype=\"int64\"),\n                _op.const(max_output_boxes_per_batch, dtype=\"int64\"),\n                dtype=\"int64\",\n            )\n            pad = _op.full(\n                _op.const(0, dtype=\"int64\"), (max_total_size - max_output_boxes_per_batch,)\n            )\n            topk_indices = _op.tile(_op.concatenate([arange, pad], 0), tile_batch_reps)\n            nmsed_scores = _op.gather(selected_scores, 1, topk_indices)\n            nmsed_scores = nmsed_scores * valid_mask\n            return nmsed_scores, topk_indices\n\n        def false_branch():\n            if isinstance(max_output_boxes_per_class, int):\n                # Do topk on smaller input if possible\n                slice_mx = _op.const([max_output_boxes_per_class * num_class], dtype=\"int64\")\n                selected_scores_slice = _op.strided_slice(\n                    selected_scores, begin=_op.const([0], dtype=\"int64\"), end=slice_mx, axes=[1]\n                )\n            else:\n                selected_scores_slice = selected_scores\n            return _op.topk(selected_scores_slice, k=max_total_size, axis=1, ret_type=\"both\")\n\n        # TODO(masahi): support dynamic num_boxes\n        # return _expr.If(do_zero_pad, true_branch(), false_branch())\n        return true_branch() if do_zero_pad else false_branch()\n\n    assert isinstance(max_output_boxes_per_batch, int), \"dynamic number of boxes not supported yet.\"\n    nmsed_scores, topk_indices = select_topk(max_output_boxes_per_batch < max_total_size)\n\n    indices = _op.take(selected_indices, topk_indices, axis=1, batch_dims=1)\n    nmsed_box_indices = _op.take(indices, _op.const(1), axis=2)\n    nmsed_classes = _op.take(indices, _op.const(0), axis=2)\n    nmsed_classes = _op.cast(nmsed_classes, \"float32\")\n    nmsed_boxes = _op.take(boxes, nmsed_box_indices, axis=1, batch_dims=1)\n    num_detections = _op.minimum(num_detections, _op.const(max_total_size, dtype=\"int64\"))\n\n    if clip_boxes:\n        nmsed_boxes = _op.maximum(nmsed_boxes, _expr.const(0, dtype=\"float32\"))\n        nmsed_boxes = _op.minimum(nmsed_boxes, _expr.const(1, dtype=\"float32\"))\n\n    nmsed_boxes = nmsed_boxes * _op.expand_dims(valid_mask, axis=2)\n\n    return _expr.TupleWrapper(\n        _expr.Tuple([nmsed_boxes, nmsed_scores, nmsed_classes, num_detections]), 4\n    )\n\n\ndef _combined_nms():\n    def _impl(inputs, attr, params, mod):\n        # Get parameter values\n        boxes = inputs[0]\n        scores = inputs[1]\n        try:\n            max_output_size = int(np.atleast_1d(inputs[2].data.numpy().astype(\"int64\"))[0])\n        except Exception:\n            try:\n                max_output_size = (\n                    _infer_value(inputs[2], params, mod).numpy().astype(\"int64\").tolist()[0]\n                )\n            except Exception:\n                max_output_size = inputs[2]\n        max_total_size = inputs[3]\n        iou_threshold = np.atleast_1d(inputs[4].data.numpy())[0]\n        score_threshold = np.atleast_1d(inputs[5].data.numpy())[0]\n        if attr[\"pad_per_class\"]:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"pad_per_class for CombinedNonMaxSuppression is not supported\"\n            )\n        boxes_shape = _infer_shape(inputs[0], mod)\n        scores_shape = _infer_shape(inputs[1], mod)\n        batch_size = boxes_shape[0]\n        num_anchors = boxes_shape[1]\n        q = boxes_shape[2]\n        num_classes = scores_shape[2]\n\n        assert isinstance(batch_size, int) and isinstance(\n            num_anchors, int\n        ), \"Dynamic inputs not supported yet\"\n\n        if q == 1:\n            boxes = _op.squeeze(boxes, axis=[2])\n            scores_trans = _op.transpose(scores, [0, 2, 1])\n            max_output_boxes_per_batch = num_anchors * num_classes\n            return convert_combined_nms_with_all_class_nms(\n                batch_size,\n                max_output_boxes_per_batch,\n                num_classes,\n                boxes,\n                scores_trans,\n                max_output_size,\n                iou_threshold,\n                score_threshold,\n                max_total_size.data.numpy().item(),\n                attr[\"clip_boxes\"],\n            )\n\n        boxes = _op.reshape(boxes, newshape=[batch_size, num_anchors * num_classes, 4])\n        scores = _op.reshape(scores, newshape=[batch_size, num_anchors * num_classes, 1])\n\n        # In TF, class is specified by memory layout only.\n        ids = _op.arange(_op.const(num_classes, dtype=\"float32\"))\n        ids = _op.broadcast_to(ids, (batch_size, num_anchors, num_classes))\n        ids = _op.reshape(ids, newshape=[batch_size, num_anchors * num_classes, 1])\n\n        data = _op.concatenate([ids, scores, boxes], -1)\n        ct, data, indices = _op.vision.get_valid_counts(\n            data, score_threshold=score_threshold, id_index=0, score_index=1\n        )\n        nms_ret = _op.vision.non_max_suppression(\n            data=data,\n            valid_count=ct,\n            indices=indices,\n            max_output_size=max_output_size,\n            iou_threshold=iou_threshold,\n            force_suppress=False,\n            top_k=-1,\n            coord_start=2,\n            score_index=1,\n            id_index=0,\n            return_indices=False,\n            invalid_to_bottom=True,\n        )\n        # Dynamic slice to max_total_size\n        neg_one = _expr.const([-1])\n        slice_end = _op.concatenate(\n            [neg_one, _op.expand_dims(max_total_size, axis=0), neg_one], axis=0\n        )\n        nms_ret = _op.strided_slice(\n            nms_ret, begin=[0, 0, 0], end=slice_end, strides=[1, 1, 1], slice_mode=\"size\"\n        )\n\n        # Slice output into boxes, scores, classes\n        nmsed_boxes = _op.strided_slice(\n            nms_ret, begin=[0, 0, 2], end=[-1, -1, 4], slice_mode=\"size\"\n        )\n        if attr[\"clip_boxes\"]:\n            nmsed_boxes = _op.maximum(nmsed_boxes, _expr.const(0, dtype=\"float32\"))\n            nmsed_boxes = _op.minimum(nmsed_boxes, _expr.const(1, dtype=\"float32\"))\n        nmsed_scores = _op.strided_slice(\n            nms_ret, begin=[0, 0, 1], end=[-1, -1, 1], slice_mode=\"size\"\n        )\n        nmsed_scores = _op.squeeze(nmsed_scores, axis=[2])\n        nmsed_classes = _op.strided_slice(\n            nms_ret, begin=[0, 0, 0], end=[-1, -1, 1], slice_mode=\"size\"\n        )\n        nmsed_classes = _op.squeeze(nmsed_classes, axis=[2])\n        # Get number of valid boxes\n        nms_count = _op.sum(\n            _op.cast(_op.greater(nmsed_scores, _expr.const(0, dtype=\"float32\")), \"int32\"), axis=1\n        )\n\n        # TVM uses -1 for invalid outputs while TF uses 0\n        box_range = _op.arange(_expr.const(0, dtype=\"int32\"), max_total_size, dtype=\"int32\")\n        shape = _op.strided_slice(_op.shape_of(nmsed_boxes), begin=[0], end=[2])\n        box_range = _op.broadcast_to(box_range, shape)\n        valid_mask = _op.cast(_op.less(box_range, _op.expand_dims(nms_count, axis=1)), \"float32\")\n        nmsed_boxes = nmsed_boxes * _op.expand_dims(valid_mask, axis=2)\n        # Could instead use mask for scores, classes if negative values are possible.\n        nmsed_scores = _op.maximum(nmsed_scores, _expr.const(0, dtype=\"float32\"))\n        nmsed_classes = _op.maximum(nmsed_classes, _expr.const(0, dtype=\"float32\"))\n\n        return _expr.TupleWrapper(\n            _expr.Tuple([nmsed_boxes, nmsed_scores, nmsed_classes, nms_count]), 4\n        )\n\n    return _impl\n\n\ndef _decode_image():\n    def _impl(inputs, attr, params, mod):\n        # Image decode wrapper: Expecting user to feed decoded input to next layer drop this layer.\n        warnings.warn(\"DecodeJpeg: It's a pass through, please handle preprocessing before input\")\n        return inputs[0]\n\n    return _impl\n\n\ndef _unravel_index():\n    def _impl(inputs, attr, params, mod):\n        return _op.unravel_index(inputs[0], inputs[1])\n\n    return _impl\n\n\ndef _crop_and_resize():\n    def _impl(inputs, attr, params, mod):\n        # input image is a 4-D tensor of shape [batch, image_height, image_width, depth]\n        # boxes is a 2-D tensor of shape [num_boxes, 4], 4 is for [y1, x1, y2, x2]\n        crop_size = _get_list_param(params, inputs[3], mod)\n\n        method = attr[\"method\"].decode()\n        method = \"nearest_neighbor\" if method == \"nearest\" else method\n        if method not in [\"bilinear\", \"nearest_neighbor\"]:\n            raise tvm.error.OpAttributeUnImplemented(\"Method {} is not supported\".format(method))\n        layout = attr[\"layout\"] if \"layout\" in attr else \"NHWC\"\n        extrapolation_value = attr[\"extrapolation_value\"]\n\n        return get_relay_op(\"crop_and_resize\")(\n            inputs[0], inputs[1], inputs[2], crop_size, layout, method, extrapolation_value\n        )\n\n    return _impl\n\n\ndef _cast():\n    def _impl(inputs, attr, params, mod):\n        return inputs[0].astype(attr[\"DstT\"].name)\n\n    return _impl\n\n\ndef _expand_dims():\n    def _impl(inputs, attr, params, mod):\n        dim_input = inputs.pop(1)\n        axis = _get_num_param(params, dim_input)\n        return AttrCvt(\n            op_name=\"expand_dims\",\n            ignores=[\"Tdim\", \"N\"],\n            extras={\"axis\": int(axis), \"num_newaxis\": 1},\n        )(inputs, attr)\n\n    return _impl\n\n\ndef _expm1():\n    # op description: https://www.tensorflow.org/api_docs/python/tf/math/expm1\n    def _impl(inputs, attr, params, mod):\n        exp_out = get_relay_op(\"exp\")(inputs[0])\n        return exp_out - tvm.relay.const(1.0)\n\n    return _impl\n\n\ndef _resize(method):\n    def _impl(inputs, attr, params, mod):\n        if attr[\"_output_shapes\"][0] is not None:\n            size = attr[\"_output_shapes\"][0][1:3]\n            # Important that the size is defined. If an axis is not, we need to infer what\n            # the shape should be.\n            if -1 in size:\n                size = _infer_value(inputs[1], params, mod).numpy().reshape([-1]).tolist()\n        else:\n            size = _infer_value(inputs[1], params, mod).numpy().reshape([-1]).tolist()\n\n        attr[\"size\"] = size\n        inputs.pop(1)\n        # NHWC\n        attr[\"layout\"] = \"NHWC\"\n        if attr.pop(\"align_corners\") is True:\n            attr[\"coordinate_transformation_mode\"] = \"align_corners\"\n        else:\n            attr[\"coordinate_transformation_mode\"] = \"asymmetric\"\n\n        # Ignore the new attributes from TF2.0, for now.\n        return AttrCvt(\n            op_name=\"resize2d\",\n            ignores=[\"Tdim\", \"half_pixel_centers\"],\n            extras={\"method\": method, \"roi\": None},\n        )(inputs, attr)\n\n    return _impl\n\n\ndef _check_numerics():\n    def _impl(inputs, attr, params, mod):\n        # Making a copy node assuming no need to verify\n        return AttrCvt(op_name=\"copy\", ignores=[\"message\"])(inputs, attr)\n\n    return _impl\n\n\ndef _assert():\n    # ToDo: In general people want asserts to be gone from TensorFlow graphs\n    # when they are optimizing them, so converting it to a no-op is\n    # reasonable. However, it would be nice to have the option to keep them\n    # once Relay gets a Halt or Assert op.\n    return _no_op()\n\n\ndef _no_op():\n    def _impl(inputs, attr, params, mod):\n        # ToDo: This should really be an op that returns nothing, which could\n        # be represented as an empty tuple. It turns out that TVM\n        # infrastructure doesn't like running functions that return None and\n        # also don't like running functions that return an empty tuple. So it\n        # doesn't work, but it should be made to work and then this could be\n        # improved. In the mean time, it is hard to imagine a case where it\n        # matters in any real way that a no-op is converted to a constant 0.\n        return tvm.relay.const(0)\n\n    return _impl\n\n\ndef _matmul():\n    def _impl(inputs, attr, params, mod):\n        from .tensorflow import TF_DEFAULT_CONFIGS\n\n        channels = _infer_channels(inputs[1], not attr[\"transpose_b\"])\n        if TF_DEFAULT_CONFIGS[\"use_dense\"]:\n            if attr[\"transpose_a\"]:\n                inputs[0] = _op.transpose(inputs[0], axes=(1, 0))\n            if not attr[\"transpose_b\"]:\n                inputs[1] = _op.transpose(inputs[1], axes=(1, 0))\n            return AttrCvt(\n                op_name=\"dense\",\n                extras={\"units\": channels},\n                ignores=[\"transpose_a\", \"transpose_b\", \"T\"],\n            )(inputs, attr)\n        return AttrCvt(\n            op_name=\"matmul\",\n            extras={\"units\": channels},\n            ignores=[\"T\"],\n        )(inputs, attr)\n\n    return _impl\n\n\ndef _batch_matmul():\n    def _impl(inputs, attr, params, mod):\n        from .tensorflow import TF_DEFAULT_CONFIGS\n\n        input_x = inputs[0]\n        input_y = inputs[1]\n        orig_shape_x = _infer_shape(input_x, mod)\n        orig_shape_y = _infer_shape(input_y, mod)\n        ndim = len(orig_shape_x)\n        ndim_y = len(orig_shape_y)\n\n        is_static = not check_symbolic_shape(orig_shape_x)\n\n        # reshape n-dimensional batch matmul into 3d\n        if ndim > 3:\n            outer_dims = [orig_shape_x[i] for i in range(0, len(orig_shape_x) - 2)]\n            if is_static:\n                num_outer_elts = np.prod(outer_dims)\n                new_shape_x = (num_outer_elts, orig_shape_x[-2], orig_shape_x[-1])\n                if ndim_y > 2:\n                    new_shape_y = (num_outer_elts, orig_shape_y[-2], orig_shape_y[-1])\n                elif ndim_y == 2:\n                    new_shape_y = (1, orig_shape_y[-2], orig_shape_y[-1])\n            else:  # handle dynamic shape (dyn.reshape op)\n                shape_of_x = list_shape_of(inputs[0], ndim)\n                shape_of_y = list_shape_of(inputs[1], ndim)\n                new_shape_x = [_op.const(1), shape_of_x[-2], shape_of_x[-1]]\n                new_shape_y = [_op.const(1), shape_of_y[-2], shape_of_y[-1]]\n                for i in range(ndim - 2):\n                    new_shape_x[0] *= shape_of_x[i]\n                    new_shape_y[0] *= shape_of_y[i]\n                new_shape_x = _op.concatenate(_op.Tuple(new_shape_x), axis=0)\n                new_shape_y = _op.concatenate(_op.Tuple(new_shape_y), axis=0)\n\n            input_x = _op.reshape(input_x, newshape=new_shape_x)\n            input_y = _op.reshape(input_y, newshape=new_shape_y)\n        elif ndim_y == 2:\n            input_y = _op.reshape(input_y, (1, orig_shape_y[-2], orig_shape_y[-1]))\n        adj_x = attr[\"adj_x\"]\n        adj_y = attr[\"adj_y\"]\n\n        if TF_DEFAULT_CONFIGS[\"use_nt_batch_matmul\"]:\n            # Strictly convert all batch_matmul to NT format\n            input_x = _op.transpose(input_x, axes=[0, 2, 1]) if adj_x else input_x\n            input_y = _op.transpose(input_y, axes=[0, 2, 1]) if not adj_y else input_y\n            ret = get_relay_op(\"batch_matmul\")(input_x, input_y)\n        else:\n            ret = get_relay_op(\"batch_matmul\")(\n                input_x, input_y, transpose_a=adj_x, transpose_b=adj_y\n            )\n\n        # reshape result back to n-dimensional\n        if ndim > 3:\n            if is_static:\n                final_shape = list(orig_shape_x)\n                final_shape[-2] = orig_shape_x[-1] if adj_x else orig_shape_x[-2]\n                final_shape[-1] = orig_shape_y[-2] if adj_y else orig_shape_y[-1]\n            else:\n                # calculate the resulting shape = [shape[:-2], 0, 0]\n                final_shape = list(shape_of_x)\n                final_shape[-2] = shape_of_x[-1] if adj_x else shape_of_x[-2]\n                final_shape[-1] = shape_of_y[-2] if adj_y else shape_of_y[-1]\n                final_shape = _op.concatenate(_op.Tuple(final_shape), axis=0)\n\n            ret = _op.reshape(ret, newshape=final_shape)\n        return ret\n\n    return _impl\n\n\ndef _sparse_tensor_dense_matmul():\n    def _impl(inputs, attr, params, mod):\n        # Loading this by default causes TVM to not be loadable from other languages.\n        # Sparse utility from scipy\n        from scipy.sparse import csr_matrix\n\n        assert len(inputs) == 4, \"There should be 4 input tensors\"\n\n        indices_tensor = _infer_value(inputs[0], params, mod).numpy()\n        values_tensor = _infer_value(inputs[1], params, mod).numpy()\n        dense_shape_tensor = _infer_value(inputs[2], params, mod).numpy()\n\n        data = inputs[3]\n\n        rows = [x[0] for x in indices_tensor]\n        cols = [x[1] for x in indices_tensor]\n\n        # Create scipy sparse Tensor(CSR)\n        weight_sp = csr_matrix(\n            (values_tensor, (rows, cols)), shape=tuple(dense_shape_tensor.tolist())\n        )\n\n        # As per tensorflow implementation, we have 4 possible input combination\n        # and the first input(A) is always sparse and second input(B) is always dense.\n        # Case 1: A , B , adjoint_a=False, adjoint_b=False  --> A * B\n        # Case 2: A , B , adjoint_a=True,   adjoint_b=False  --> A.T * B\n        # Case 3: A , B , adjoint_a=False, adjoint_b=True    --> A * B.T\n        # Case 4: A , B , adjoint_a=True,   adjoint_b=True    --> A.T * B.T\n        #\n        # Topi implementation for sparse_dense(matmul) has 2 possible input\n        # combination where first input(A) is always dense\n        # and second input(B) is always sparse.\n        # Case 1: A , B, sparse_lhs = False  --> A * B.T\n        # Case 2: A , B, sparse_lhs = True    --> B * A.T\n        #\n        # The mapping would be as below:\n        # TF Case 1: A , B , adjoint_a=False, adjoint_b=False\n        #           --> In TF: A * B   --> In Topi: A * B.T.T\n        #           --> sparse_dense(transpose(B), A, sparse_lhs=True)\n        #\n        # TF Case 2: A , B , adjoint_a=True, adjoint_b=False\n        #           --> In TF: A.T * B   --> In Topi: A.T * B.T.T\n        #           --> sparse_dense(transpose(B), transpose(A), sparse_lhs=True)\n        #\n        # TF Case 3: A , B , adjoint_a=False, adjoint_b=True\n        #           --> In TF: A * B.T   --> In Topi: A * B\n        #           --> sparse_dense(B, A, sparse_lhs=True)\n        #\n        # TF Case 4: A , B , adjoint_a=True, adjoint_b=True\n        #           --> In TF: A.T * B.T   --> In Topi: (B * A.T).T\n        #           --> transpose(sparse_dense(B, transpose(A), sparse_lhs=False))\n\n        # By default, in tensorflow the first input ,i.e., data is sparse\n        sparse_lhs = True\n\n        # TF Case 1:\n        if not attr.get(\"adjoint_a\") and not attr.get(\"adjoint_b\"):\n            data = _op.transpose(data)\n        # TF Case 2:\n        elif attr.get(\"adjoint_a\") and not attr.get(\"adjoint_b\"):\n            data = _op.transpose(data)\n            weight_sp = csr_matrix(weight_sp.transpose())\n        # TF Case 3:\n        elif not attr.get(\"adjoint_a\") and attr.get(\"adjoint_b\"):\n            pass\n        # TF Case 4:\n        # attr.get(\"adjoint_a\") and attr.get(\"adjoint_b\"):\n        else:\n            sparse_lhs = False\n            weight_sp = csr_matrix(weight_sp.transpose())\n\n        weight_data = _expr.const(weight_sp.data, weight_sp.data.dtype)\n        weight_indptrs = _expr.const(weight_sp.indptr, weight_sp.indptr.dtype)\n        weight_indices = _expr.const(weight_sp.indices, weight_sp.indices.dtype)\n\n        ret = _op.nn.sparse_dense(data, [weight_data, weight_indices, weight_indptrs], sparse_lhs)\n\n        if not sparse_lhs:\n            # TF Case 4\n            ret = _op.transpose(ret)\n\n        return ret\n\n    return _impl\n\n\ndef _sparse_fill_empty_rows():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 4, \"There should be 4 input tensors\"\n        sparse_indices = inputs[0]\n        sparse_values = inputs[1]\n        sparse_indices_num_cols = _infer_shape(sparse_indices, mod)[1]\n        first_column = _op.split(sparse_indices, sparse_indices_num_cols, axis=1)[0]\n        sorted_indices = _op.argsort(_op.squeeze(first_column))\n        sorted_sparse_indices = _op.take(sparse_indices, sorted_indices, axis=0)\n        sorted_sparse_values = _op.take(sparse_values, sorted_indices, axis=0)\n        new_sparse_indices, new_sparse_values, empty_row_indicator = _op.sparse_fill_empty_rows(\n            sorted_sparse_indices, sorted_sparse_values, inputs[2], inputs[3]\n        )\n\n        return _expr.TupleWrapper(\n            _expr.Tuple([new_sparse_indices, new_sparse_values, empty_row_indicator]),\n            3,\n        )\n\n    return _impl\n\n\ndef _sparse_reshape():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 3, \"There should be 3 input tensors\"\n        new_indices, new_shape = get_relay_op(\"sparse_reshape\")(inputs[0], inputs[1], inputs[2])\n        return _expr.TupleWrapper(_expr.Tuple([new_indices, new_shape]), 2)\n\n    return _impl\n\n\ndef _math_segment_sum():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 2, \"There should be 2 input tensors\"\n        return get_relay_op(\"segment_sum\")(inputs[0], inputs[1])\n\n    return _impl\n\n\ndef _sparse_segment_sum():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 3, \"There should be 3 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        return _op.segment_sum(data, inputs[2])\n\n    return _impl\n\n\ndef _sparse_segment_sum_with_num_segments():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 4, \"There should be 4 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        num_segments = int(inputs[3].data.numpy().item())\n        return _op.segment_sum(data, inputs[2], num_segments)\n\n    return _impl\n\n\ndef row_wise_divide(multi_dim_tensor, one_dim_vector):\n    \"\"\"\n    This function enables row-wise division of multi_dim_tensor and one_dim_vector.\n    To achieve this, it is first tiled to the appropriate shape and then elemwise_division\n    \"\"\"\n    multi_dim_tensor_offrow_shape = _op.strided_slice(\n        _op.shape_of(multi_dim_tensor, \"int32\"), [1], [-1], slice_mode=\"size\"\n    )\n    one_dim_vector_tiled_shape = _op.concatenate(\n        [_op.reverse(multi_dim_tensor_offrow_shape, 0), _expr.const([1])], axis=0\n    )\n    one_dim_vector_tiled = _op.transpose(_op.tile(one_dim_vector, one_dim_vector_tiled_shape))\n    return _op.divide(multi_dim_tensor, one_dim_vector_tiled)\n\n\ndef count_all_indices(segment_ids, counts_dtype, num_segments=None):\n    \"\"\"\n    This snippet calculates the sqrt count of each index among all valid indices\n    Valid indices are from 0 to max of [segment ids, num_segments]\n    \"\"\"\n\n    max_segments = _op.reshape(_op.max(segment_ids), -1) + _expr.const([1])\n    if num_segments:\n        max_segments = _op.maximum(max_segments, _expr.const([num_segments]))\n    max_ones = _op.maximum(max_segments, _op.shape_of(segment_ids))\n    counts = _op.segment_sum(\n        _op.ones(max_ones, counts_dtype), segment_ids, num_segments=num_segments\n    )\n    real_counts = _op.clip(counts, 1, 2147483647)  # Clip max doesn't work over int32\n    return real_counts\n\n\ndef _sparse_segment_sum_sqrtn():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 3, \"There should be 3 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        real_counts = count_all_indices(inputs[2], attr[\"T\"].name)\n        real_sqrt_counts = _op.sqrt(_op.cast_like(real_counts, data))\n\n        # Calculate regular segment sum\n        segment_sum = _op.segment_sum(data, inputs[2])\n\n        return row_wise_divide(segment_sum, real_sqrt_counts)\n\n    return _impl\n\n\ndef _sparse_segment_sum_sqrtn_with_num_segments():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 4, \"There should be 4 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        num_segments = int(inputs[3].data.numpy().item())\n        real_counts = count_all_indices(inputs[2], attr[\"T\"].name, num_segments=num_segments)\n        real_sqrt_counts = _op.sqrt(_op.cast_like(real_counts, data))\n\n        # Calculate regular segment sum\n        segment_sum = _op.segment_sum(data, inputs[2], num_segments=num_segments)\n\n        return row_wise_divide(segment_sum, real_sqrt_counts)\n\n    return _impl\n\n\ndef _sparse_segment_mean():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 3, \"There should be 3 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        real_counts = count_all_indices(inputs[2], attr[\"T\"].name)\n\n        # Calculate regular segment sum\n        segment_sum = _op.segment_sum(data, inputs[2])\n\n        return row_wise_divide(segment_sum, real_counts)\n\n    return _impl\n\n\ndef _sparse_segment_mean_with_num_segments():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 4, \"There should be 4 input tensors\"\n        data = _op.take(inputs[0], inputs[1], axis=0)\n        num_segments = int(inputs[3].data.numpy().item())\n        real_counts = count_all_indices(inputs[2], attr[\"T\"].name, num_segments=num_segments)\n\n        # Calculate regular segment sum\n        segment_sum = _op.segment_sum(data, inputs[2], num_segments=num_segments)\n\n        return row_wise_divide(segment_sum, real_counts)\n\n    return _impl\n\n\ndef _sparse_tensor_dense_add():\n    # Sparse utility from scipy\n    from scipy.sparse import csr_matrix\n\n    def _impl(inputs, attr, params, mod):\n        assert (\n            len(inputs) == 4\n        ), \"There should be 4 input tensors [sparse_indices, sparse_values, sparse_shape, dense].\"\n\n        indices_tensor = _infer_value(inputs[0], params, mod).numpy()\n        values_tensor = _infer_value(inputs[1], params, mod).numpy()\n        dense_shape_tensor = _infer_value(inputs[2], params, mod).numpy()\n\n        data = inputs[3]\n\n        rows = [x[0] for x in indices_tensor]\n        cols = [x[1] for x in indices_tensor]\n\n        # Create scipy sparse Tensor(CSR)\n        weight_sp = csr_matrix(\n            (values_tensor, (rows, cols)), shape=tuple(dense_shape_tensor.tolist())\n        )\n\n        weight_data = _expr.const(weight_sp.data, weight_sp.data.dtype)\n        weight_indptrs = _expr.const(weight_sp.indptr, weight_sp.indptr.dtype)\n        weight_indices = _expr.const(weight_sp.indices, weight_sp.indices.dtype)\n\n        ret = _op.nn.sparse_add(data, [weight_data, weight_indices, weight_indptrs])\n\n        return ret\n\n    return _impl\n\n\ndef _identity():\n    def _impl(inputs, attr, params, mod):\n        return inputs[0]\n\n    return _impl\n\n\ndef _identityn():\n    def _impl(inputs, attr, params, mod):\n        return inputs\n\n    return _impl\n\n\ndef _concatV2():\n    def _impl(inputs, attr, params, mod):\n        pop_node = inputs.pop(len(inputs) - 1)\n        try:\n            axis = int(_get_num_param(params, pop_node))\n        except (IndexError, KeyError, AttributeError):\n            try:\n                axis = int(_infer_value(pop_node, params, mod).numpy())\n            except Exception:\n                axis = int(pop_node)\n        return AttrCvt(op_name=\"concatenate\", ignores=[\"T\", \"N\", \"Tidx\"], extras={\"axis\": axis})(\n            [inputs], attr\n        )\n\n    return _impl\n\n\ndef _concat():\n    def _impl(inputs, attr, params, mod):\n        pop_node = inputs.pop(0)\n        axis = int(_get_num_param(params, pop_node))\n        return AttrCvt(op_name=\"concatenate\", ignores=[\"N\"], extras={\"axis\": axis})([inputs], attr)\n\n    return _impl\n\n\ndef _pack():\n    def _impl(inputs, attr, params, mod):\n        axis = int(attr[\"axis\"])\n        inputs_reshaped = [_op.expand_dims(i, axis=axis, num_newaxis=1) for i in inputs]\n        return _op.concatenate(inputs_reshaped, axis)\n\n    return _impl\n\n\ndef _tensor_array():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"dtype\").name\n        assert not attr[\"dynamic_size\"], \"Dynamic size tensor array is \" \"not supported in TVM yet.\"\n\n        if \"shape\" in attr:\n            shape = attr[\"shape\"]\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, shape)\n            static_tensor_array_ops.register()\n            tensor_array_constructor = static_tensor_array_ops.get_global_var(\"tensor_array\")\n            tensor_array = tensor_array_constructor(inputs[0])\n        else:\n            tensor_array_constructor = prelude.get_global_var(\"tensor_array\", dtype_str)\n            tensor_array = tensor_array_constructor(inputs[0])\n        return tensor_array\n\n    return _impl\n\n\ndef _tensor_array_scatter():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"T\").name\n        input_ta = inputs[0]\n        input_shape = get_tensor_array_shape(input_ta, dtype_str, prelude)\n        values_shape = _infer_shape(inputs[2], prelude.mod)\n        input_t_shape = values_shape[1:]\n        indices_shape = _infer_shape(inputs[1], prelude.mod)\n\n        if input_shape is None:\n            values_rank = len(values_shape)\n            unstack_name = \"tensor_array_unstack_tensor{}\".format(values_rank)\n            unstack_function = prelude.get_global_var(unstack_name, dtype_str)\n            values = unstack_function(inputs[2])\n            tensor_array_scatter_func = prelude.get_global_var(\"tensor_array_scatter\", dtype_str)\n        else:\n            input_t_shape = _get_more_static_shape(input_t_shape, input_shape)\n            values_shape = (values_shape[0],) + input_t_shape\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_t_shape)\n            static_tensor_array_ops.register()\n            # Register static indices shape\n            if isinstance(indices_shape[0], int):\n                static_tensor_array_ops.define_tensor_array_scatter(indices_shape, True)\n            tensor_array_scatter_func = prelude.get_global_var_static(\n                \"tensor_array_scatter\", dtype_str, input_t_shape\n            )\n\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, values_shape)\n            static_tensor_array_ops.register()\n            unstack_function = prelude.get_global_var_static(\n                \"tensor_array_unstack\", dtype_str, values_shape\n            )\n            values = unstack_function(inputs[2])\n        ret = tensor_array_scatter_func(input_ta, inputs[1], values)\n        return ret\n\n    return _impl\n\n\ndef _tensor_array_gather():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"dtype\").name\n        input_shape = get_tensor_array_shape(inputs[2], dtype_str, prelude)\n        indices_shape = _infer_shape(inputs[1], prelude.mod)\n\n        if input_shape is None:\n            gather_func = prelude.get_var(\"tensor_array_gather\", dtype_str)\n            out = gather_func(inputs[2], inputs[1])\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_shape)\n            static_tensor_array_ops.register()\n\n            if not isinstance(indices_shape[0], int):\n                gather_function = prelude.get_global_var_static(\n                    \"tensor_array_gather\", dtype_str, input_shape\n                )\n                out_tensor_t = gather_function(inputs[2], inputs[1])\n                out_shape = (indices_shape[0],) + input_shape\n                static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, out_shape)\n                static_tensor_array_ops.register()\n\n                # Output shape is (indices_shape[0],) + input_shape\n                get_data_func = prelude.get_global_var_static(\n                    \"tensor_get_data\", dtype_str, out_shape\n                )\n                out = get_data_func(out_tensor_t)\n            else:\n                # For fixed length indices, directly generate static shape output\n                read_func = prelude.get_global_var_static(\n                    \"tensor_array_read\", dtype_str, input_shape\n                )\n                get_data_func = prelude.get_global_var_static(\n                    \"tensor_get_data\", dtype_str, input_shape\n                )\n                tensor_list = []\n                for i in range(indices_shape[0]):\n                    index = _op.take(inputs[1], tvm.relay.const(i))\n                    out_tensor = get_data_func(read_func(inputs[2], index))\n                    tensor_list.append(_op.expand_dims(out_tensor, axis=0))\n\n                if indices_shape[0] > 1:\n                    out = _op.concatenate(tensor_list, axis=0)\n                else:\n                    out = tensor_list[0]\n\n        return out\n\n    return _impl\n\n\ndef _tensor_array_size():\n    def _impl(inputs, attr, params, prelude):\n        return prelude.length(inputs[0])\n\n    return _impl\n\n\ndef _tensor_array_write():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"T\").name\n        input_ta = inputs[3]\n        input_ta_shape = get_tensor_array_shape(input_ta, dtype_str, prelude)\n        input_t_shape = _infer_shape(inputs[2], prelude.mod)\n        input_rank = len(input_t_shape)\n\n        if input_ta_shape is None:\n            tensor_name = \"tensor{}\".format(input_rank)\n            tensor_func = prelude.get_tensor_ctor(tensor_name, dtype_str)\n            v = tensor_func(inputs[2])\n            write_func = prelude.get_global_var(\"tensor_array_write\", dtype_str)\n        else:\n            input_ta_rank = len(input_ta_shape)\n            assert input_ta_rank == input_rank, \"Shape rank mismatch: {} vs {}\".format(\n                input_ta_rank, input_rank\n            )\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_ta_shape)\n            static_tensor_array_ops.register()\n            tensor_func = static_tensor_array_ops.get_ctor(\"tensor_constructor\")\n            v = tensor_func(inputs[2])\n            # Write tensor with more static shape\n            actual_shape = _get_more_static_shape(input_t_shape, input_ta_shape)\n            if actual_shape != input_t_shape:\n                new_shape = []\n                num_any_dim = 0\n                for dim in actual_shape:\n                    if not isinstance(dim, int):\n                        num_any_dim += 1\n                    new_shape.append(dim if isinstance(dim, int) else -1)\n                if num_any_dim <= 1:\n                    v = tensor_func(_op.reshape(inputs[2], new_shape))\n\n            write_func = prelude.get_global_var_static(\n                \"tensor_array_write\", dtype_str, input_ta_shape\n            )\n\n        return write_func(input_ta, _op.take(inputs[1], tvm.relay.const(0)), v)\n\n    return _impl\n\n\ndef _tensor_array_read():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr[\"dtype\"].name\n        input_shape = get_tensor_array_shape(inputs[2], dtype_str, prelude)\n\n        if input_shape is None:\n            read_func = prelude.get_global_var(\"tensor_array_read\", dtype_str)\n            out = read_func(inputs[2], _op.take(inputs[1], tvm.relay.const(0)))\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_shape)\n            static_tensor_array_ops.register()\n            read_func = static_tensor_array_ops.get_global_var(\"tensor_array_read\")\n            out_tensor = read_func(inputs[2], _op.take(inputs[1], tvm.relay.const(0)))\n            get_data_func = static_tensor_array_ops.get_global_var(\"tensor_get_data\")\n            out = get_data_func(out_tensor)\n\n        return out\n\n    return _impl\n\n\ndef _tensor_array_split():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr.get(\"T\").name\n        input_ta = inputs[0]\n        input_ta_shape = get_tensor_array_shape(input_ta, dtype_str, prelude)\n        lengths = _op.cast(inputs[2], \"int32\")\n        lengths_shape = _infer_shape(lengths, prelude.mod)\n        value_shape = _infer_shape(inputs[1], prelude.mod)\n        input_rank = len(value_shape)\n\n        if input_ta_shape is None:\n            tensor_name = \"tensor{}\".format(input_rank)\n            tensor_ctor = prelude.get_tensor_ctor(tensor_name, dtype_str)\n            v = tensor_ctor(inputs[1])\n            split_func = prelude.get_global_var(\"tensor_array_split\", dtype_str)\n        else:\n            input_ta_rank = len(input_ta_shape)\n            assert input_ta_rank == input_rank, \"Shape rank mismatch: {} vs {}\".format(\n                input_ta_rank, input_rank\n            )\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_ta_shape)\n            static_tensor_array_ops.register()\n\n            # Check static value/indices shape\n            if isinstance(value_shape[0], int) or isinstance(lengths_shape[0], int):\n                static_tensor_array_ops.define_tensor_array_split(value_shape, lengths_shape, True)\n\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, value_shape)\n            static_tensor_array_ops.register()\n            tensor_ctor = static_tensor_array_ops.get_ctor(\"tensor_constructor\")\n            v = tensor_ctor(inputs[1])\n            split_func = prelude.get_global_var_static(\n                \"tensor_array_split\", dtype_str, input_ta_shape\n            )\n\n        return split_func(input_ta, v, lengths)\n\n    return _impl\n\n\ndef _tensor_array_concat():\n    def _impl(inputs, attr, params, prelude):\n        dtype_str = attr[\"dtype\"].name\n        input_shape = get_tensor_array_shape(inputs[1], dtype_str, prelude)\n\n        if input_shape is None:\n            concat_func = prelude.get_global_var(\"tensor_array_concat\", dtype_str)\n            out = concat_func(inputs[1])\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, input_shape)\n            static_tensor_array_ops.register()\n            concat_func = prelude.get_global_var_static(\n                \"tensor_array_concat\", dtype_str, input_shape\n            )\n            out_tensor = concat_func(inputs[1])\n            out_shape = (Any(),) + input_shape[1:]\n            static_tensor_array_ops = StaticTensorArrayOps(prelude, dtype_str, out_shape)\n            static_tensor_array_ops.register()\n            get_data_func = prelude.get_global_var_static(\"tensor_get_data\", dtype_str, out_shape)\n            out = get_data_func(out_tensor)\n\n        return out\n\n    return _impl\n\n\ndef _tile():\n    def _impl(inputs, attr, params, mod):\n        reps_input = inputs.pop()\n        if isinstance(reps_input, _expr.Call):\n            np_reps = _infer_value(reps_input, params, mod).numpy()\n            reps = [np_reps.flatten()[i] for i in range(np_reps.flatten().shape[0])]\n        else:\n            reps = _get_list_param(params, reps_input, mod)\n        new_input = [inputs.pop(0)]\n\n        return AttrCvt(op_name=\"tile\", extras={\"reps\": tuple(reps)}, ignores=[\"Tmultiples\"])(\n            new_input, attr\n        )\n\n    return _impl\n\n\ndef _slice():\n    def _impl(inputs, attr, params, mod):\n        try:\n            begin = _get_list_param(params, inputs[1], mod)\n        except Exception:\n            # Handle symbolic begin\n            begin = inputs[1]\n        try:\n            size = _get_list_param(params, inputs[2], mod)\n        except Exception:\n            # Handle symbolic size\n            size = inputs[2]\n\n        # Align begin and strides for dynamic shape.\n        data_dim = len(_infer_shape(inputs[0], mod))\n        strides = [1] * data_dim\n        if not isinstance(begin, (_expr.Call, _expr.Var)):\n            for _ in range(len(begin), data_dim):\n                begin.append(0)\n        elif not isinstance(size, (_expr.Call, _expr.Var)):\n            for _ in range(len(size), data_dim):\n                size.append(-1)\n        return _op.strided_slice(\n            inputs[0], begin=begin, end=size, strides=strides, slice_mode=\"size\"\n        )\n\n    return _impl\n\n\ndef _reshape():\n    def _impl(inputs, attr, params, mod):\n        pop_node = inputs.pop(1)\n\n        try:\n            shape_arg = _get_tuple_param(params, pop_node)\n        except AttributeError:\n            # Shape operator is already pruned, hence\n            # try to infer shape by precompute prune if possible.\n            try:\n                params_new = _infer_value(pop_node, params, mod)\n                shape_arg = tuple(params_new.numpy().astype(\"int32\").flatten())\n            except Exception:\n                # Deal with symbolic shape case.\n                if isinstance(pop_node, _expr.Call) and \"shape_of\" in str(pop_node.op):\n                    # shape_of is the direct ancestor.\n                    return _op.reshape_like(inputs[0], pop_node.args[0])\n                shape_arg = pop_node\n\n        return AttrCvt(op_name=\"reshape\", extras={\"newshape\": shape_arg}, ignores=[\"Tshape\"])(\n            inputs, attr\n        )\n\n    return _impl\n\n\ndef _depth_to_space():\n    def _impl(inputs, attr, params, mod):\n        block_size = int(attr[\"block_size\"])\n        layout = attr[\"data_format\"].decode(\"utf-8\")\n        return _op.nn.depth_to_space(inputs[0], block_size, layout)\n\n    return _impl\n\n\ndef _space_to_depth():\n    def _impl(inputs, attr, params, mod):\n        block_size = int(attr[\"block_size\"])\n        layout = attr[\"data_format\"].decode(\"utf-8\")\n        return _op.nn.space_to_depth(inputs[0], block_size, layout)\n\n    return _impl\n\n\ndef _sparse_to_dense():\n    def _impl(inputs, attr, params, mod):\n        sparse_indices = inputs[0]\n        output_shape = inputs[1]\n        sparse_values = inputs[2]\n        default_value = inputs[3]\n\n        return _op.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value)\n\n    return _impl\n\n\ndef _bias_add():\n    def _impl(inputs, attr, params, mod):\n        # Must expand for proper broadcasting in NCHW.\n        if \"data_format\" in attr and attr[\"data_format\"].decode(\"utf-8\") == \"NCHW\":\n            bias = _op.reshape(inputs[1], newshape=(1, -1, 1, 1))\n        else:\n            bias = inputs[1]\n        return _op.add(inputs[0], bias)\n\n    return _impl\n\n\ndef _broadcast_args():\n    def _impl(inputs, attr, params, mod):\n        if isinstance(inputs[0], _expr.Var):\n            s0 = params[inputs[0].name_hint]\n        else:\n            s0 = _infer_value(inputs[0], params, mod)\n        if isinstance(inputs[1], _expr.Var):\n            s1 = params[inputs[1].name_hint]\n        else:\n            s1 = _infer_value(inputs[1], params, mod)\n        s0 = list(s0.numpy().reshape([-1]))\n        s1 = list(s1.numpy().reshape([-1]))\n        s0_size, s1_size = len(s0), len(s1)\n\n        out = deque([])\n        for i in range(1, min(s0_size, s1_size) + 1):\n            if s0[s0_size - i] == s1[s1_size - i]:\n                out.appendleft(s0[s0_size - i])\n            elif s0[s0_size - i] == 1:\n                out.appendleft(s1[s1_size - i])\n            else:\n                assert s1[s1_size - i] == 1, \"Incompatible broadcast type %s and %s\" % (\n                    s0[s0_size - i],\n                    s1[s1_size - i],\n                )\n                out.appendleft(s0[s0_size - i])\n        if s0_size < s1_size:\n            for i in range(s0_size + 1, s1_size + 1):\n                out.appendleft(s1[s1_size - i])\n        if s1_size < s0_size:\n            for i in range(s1_size + 1, s0_size + 1):\n                out.appendleft(s0[s0_size - i])\n        return _expr.const(list(out), attr[\"T\"].name)\n\n    return _impl\n\n\ndef _broadcast_to():\n    def _impl(inputs, attr, params, mod):\n        if isinstance(inputs[1], _expr.Var):\n            shape = params[inputs[1].name_hint]\n        else:\n            shape = _infer_value(inputs[1], params, mod)\n        shape = list(shape.numpy().reshape([-1]))\n        return _op.broadcast_to(inputs[0], shape)\n\n    return _impl\n\n\ndef _squeeze():\n    def _impl(inputs, attr, params, mod):\n        if len(attr[\"squeeze_dims\"]) == 0:\n            attr[\"squeeze_dims\"] = None\n        return AttrCvt(\n            op_name=\"squeeze\", transforms={\"squeeze_dims\": \"axis\"}, ignores=[\"T\", \"_cloned\"]\n        )(inputs, attr)\n\n    return _impl\n\n\ndef _fused_batch_norm():\n    def _impl(inputs, attr, params, mod):\n        # Tensorflow: (data, gamma, beta, moving_mean, moving_variance)\n        # Relay:       (data, gamma, beta, moving_mean, moving_varience)\n        assert len(inputs) == 5\n        axis = 3\n        need_cast = False\n\n        if \"data_format\" in attr:\n            attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n            if attr[\"data_format\"] == \"NCHW\":\n                axis = 1\n        if \"U\" in attr and attr[\"U\"].name != attr[\"T\"].name:\n            need_cast = True\n            inputs[0] = _op.cast(inputs[0], dtype=attr[\"U\"].name)\n        # Check if mean and variance are empty\n        # If so, replace them with Mean and Variance Ops\n        # For run-time calculation\n        moving_mean_shape = [int(n) for n in inputs[3].type_annotation.shape]\n        moving_variance_shape = [int(n) for n in inputs[4].type_annotation.shape]\n        if moving_mean_shape[0] == 0 and moving_variance_shape[0] == 0:\n            inputs[3] = _op.mean(inputs[0], axis=axis, keepdims=False, exclude=True)\n            inputs[4] = _op.variance(inputs[0], axis=axis, keepdims=False, exclude=True)\n        out = AttrCvt(\n            op_name=\"batch_norm\",\n            transforms={\"scale_after_normalization\": \"scale\", \"variance_epsilon\": \"epsilon\"},\n            extras={\"axis\": axis},\n            ignores=[\"data_format\", \"U\", \"exponential_avg_factor\"],\n            disables=[\"momentum\"],\n        )(inputs, attr)\n\n        if need_cast:\n            out = _expr.TupleGetItem(out.astuple(), 0)\n            out = _op.cast(out, dtype=attr[\"T\"].name)\n        return out\n\n    return _impl\n\n\ndef _batch_norm():\n    def _impl(inputs, attr, params, mod):\n        # Rearrange inputs from\n        # (data, moving_mean, moving_variance, beta, gamma)\n        #     to\n        # (data, gamma, beta, moving_mean, moving_var)\n        new_inputs = [inputs[0], inputs[4], inputs[3], inputs[1], inputs[2]]\n\n        axis = 3\n        if \"data_format\" in attr:\n            attr[\"data_format\"] = attr[\"data_format\"].decode(\"utf-8\")\n            if attr[\"data_format\"] == \"NCHW\":\n                axis = 1\n\n        return AttrCvt(\n            op_name=\"batch_norm\",\n            transforms={\"scale_after_normalization\": \"scale\", \"variance_epsilon\": \"epsilon\"},\n            extras={\"axis\": axis},\n            ignores=[\"data_format\", \"exponential_avg_factor\"],\n            disables=[\"momentum\"],\n        )(new_inputs, attr)\n\n    return _impl\n\n\ndef _relu6():\n    def _impl(inputs, attr, params, mod):\n        return _op.clip(inputs[0], a_min=0, a_max=6)\n\n    return _impl\n\n\ndef _shape():\n    def _impl(inputs, attr, params, mod):\n        is_symbolic_shape = False\n        input_shape = _infer_shape(inputs[0], mod)\n        for axis in input_shape:\n            if not isinstance(axis, (int, tvm.tir.IntImm)):\n                is_symbolic_shape = True\n                break\n\n        if is_symbolic_shape:\n            ret = _op.shape_of(inputs[0], dtype=attr[\"out_type\"].name)\n        else:\n            ret = np.array(input_shape, dtype=attr[\"out_type\"].name)\n        return ret\n\n    return _impl\n\n\ndef _fill():\n    def _impl(inputs, attr, params, mod):\n        try:\n            output_shape = _infer_value(inputs[0], params, mod).numpy().tolist()\n        except Exception:\n            output_shape = inputs[0]\n\n        return _op.full(inputs[1], output_shape, attr[\"T\"].name)\n\n    return _impl\n\n\ndef _lrn():\n    def _impl(inputs, attr, params, mod):\n        attr_new = {}\n        depth_radius = attr.get(\"depth_radius\", 5)\n        size = (depth_radius * 2) + 1\n        attr_new[\"axis\"] = 3  # Fix axis, NHWC format\n        attr_new[\"size\"] = size\n        attr_new[\"bias\"] = attr.get(\"bias\", 1)\n        attr_new[\"alpha\"] = attr.get(\"alpha\", 1) * size\n        attr_new[\"beta\"] = attr.get(\"beta\", 0.5)\n        return AttrCvt(op_name=\"lrn\")(inputs, attr_new)\n\n    return _impl\n\n\ndef _sum():\n    def _impl(inputs, attr, params, mod):\n        axis = _get_tuple_param(params, inputs[1])\n        return AttrCvt(\n            op_name=\"sum\",\n            extras={\"axis\": axis},\n            transforms={\"keep_dims\": \"keepdims\"},\n            ignores=[\"name\", \"Tidx\"],\n        )([inputs[0]], attr)\n\n    return _impl\n\n\ndef _reduce(op):\n    def _impl(inputs, attr, params, mod):\n        axis = _get_list_param(params, inputs[1], mod)\n        axis = tuple(axis)\n        if not axis:\n            axis = None\n        return AttrCvt(\n            op_name=op,\n            extras={\"axis\": axis},\n            transforms={\"keep_dims\": \"keepdims\"},\n            ignores=[\"name\", \"Tidx\"],\n        )([inputs[0]], attr)\n\n    return _impl\n\n\ndef _euclidean_norm():\n    def _impl(inputs, attr, params, mod):\n        axis = tuple(_get_list_param(params, inputs[1], mod))\n        keep_dims = bool(attr.get(\"keep_dims\", False))\n        return _op.sqrt(\n            _op.cast(_op.reduce.sum(_op.multiply(inputs[0], inputs[0]), axis, keep_dims), \"float32\")\n        )\n\n    return _impl\n\n\ndef _square():\n    def _impl(inputs, attr, params, mod):\n        return _op.multiply(inputs[0], inputs[0])\n\n    return _impl\n\n\ndef _gather():\n    \"GatherV2, Gather\"\n\n    def _impl(inputs, attr, params, mod):\n        if len(inputs) > 2:\n            axis = _get_num_param(params, inputs.pop(2))\n        else:\n            axis = 0\n        batch_dims = 0\n        if int(attr.get(\"batch_dims\", 0)) != 0:\n            batch_dims = int(attr.get(\"batch_dims\", 0))\n        new_input = inputs[0:2]\n        op_ = AttrCvt(\n            op_name=\"take\",\n            extras={\n                \"axis\": tvm.tir.const(axis, \"int32\"),\n                \"batch_dims\": tvm.tir.const(batch_dims, \"int32\"),\n            },\n            ignores=[\"Tindices\", \"Tparams\", \"validate_indices\", \"Taxis\", \"_class\"],\n        )(new_input, attr)\n        return op_\n\n    return _impl\n\n\ndef _gather_nd():\n    \"\"\"GatherNd\"\"\"\n\n    def _impl(inputs, attr, params, mod):\n        indices_dims = len(_infer_shape(inputs[1], mod))\n        indices = _op.transpose(inputs[1], axes=[-1] + list(range(indices_dims - 1)))\n        return AttrCvt(op_name=\"gather_nd\", ignores=[\"Tindices\", \"Tparams\", \"Taxis\", \"_class\"])(\n            [inputs[0], indices], attr\n        )\n\n    return _impl\n\n\ndef _stridedSlice():\n    def _impl(inputs, attr, params, mod):\n        \"\"\"Strided Slice.\n        Operator description: https://www.tensorflow.org/api_docs/python/tf/strided_slice\n        Tensorflow mask validation: https://github.com/tensorflow/tensorflow/blob/master/\n        tensorflow/core/util/strided_slice_op.cc#L147-L368\n        \"\"\"\n        begin = _get_list_param(params, inputs[1], mod)\n        end = _get_list_param(params, inputs[2], mod)\n        stride = _get_list_param(params, inputs[3], mod)\n\n        begin_mask = int(attr.get(\"begin_mask\", 0))\n        end_mask = int(attr.get(\"end_mask\", 0))\n        ellipsis_mask = int(attr.get(\"ellipsis_mask\", 0))\n        new_axis_mask = int(attr.get(\"new_axis_mask\", 0))\n        shrink_axis_mask = int(attr.get(\"shrink_axis_mask\", 0))\n        in_type = _infer_type(inputs[0], mod)\n        data_shape = get_const_tuple(in_type.checked_type.shape)\n        data_dim = len(data_shape)\n        stride_dim = len(stride)\n        if data_dim == 0 and isinstance(inputs[0], _expr.Constant):\n            new_data = inputs[0].data.numpy().reshape(1)\n            return _expr.const(new_data, inputs[0].data.dtype)\n\n        # This is a special routine to handle strided_slice after shape_of.\n        # We need this since in some cases we want to do strided_slice on\n        # a partial symbolic shape, such as (1, ?), and get a static shape\n        # (1,). Directly slice on shape_of will result in fully dynamic shape.\n        # TODO(kevinthesun): Can we generalize this process with partial eval?\n        if isinstance(inputs[0], _expr.Call) and inputs[0].op == _op.get(\"shape_of\"):\n            bg = begin[0]\n            ed = end[0]\n            st = stride[0]\n\n            if ed <= 0 < st:\n                ed += data_shape[0]\n\n            in_shape = _infer_shape(inputs[0].args[0], mod)\n            dtype = in_type.checked_type.dtype\n            out_data = []\n            idx = bg\n            while idx < ed:\n                if isinstance(in_shape[idx], int):\n                    out_data.append(in_shape[idx])\n                else:\n                    break\n                idx += st\n\n            # Only return when in_shape is fully static in the range from begin to end.\n            if idx >= ed:\n                ret = _expr.const(out_data, dtype)\n                if shrink_axis_mask:\n                    ret = _op.squeeze(ret)\n\n                return ret\n\n        def _transform_mask(stride_dim, ellipsis_mask):\n            \"\"\"Handle mask inputs to create new begin, end, stride and output shape\"\"\"\n            m_begin = [0] * data_dim\n            m_end = [0] * data_dim\n            m_stride = [0] * data_dim\n            fshape_indices = []\n            # Count new axis after ellipsis_mask, consider while applying ellipsis_mask.\n            ellipsis_seen = False\n            new_axes_after_ellipsis = 0\n            for i in range(stride_dim):\n                mask = 1 << i\n                if ellipsis_seen and (mask & new_axis_mask) != 0:\n                    new_axes_after_ellipsis += 1\n                if (mask & ellipsis_mask) != 0:\n                    ellipsis_seen = True\n            if not ellipsis_seen:\n                # Used later for extending the stride attributes in the below loop.\n                ellipsis_mask |= 1 << stride_dim\n                stride_dim += 1\n            final_index = 0\n            for index in range(stride_dim):\n                mask = 1 << index\n                if mask & ellipsis_mask:\n                    # Identify the end index for applying ellipsis_mask\n                    to_index = min(\n                        ((data_dim - (stride_dim - index)) + 1 + new_axes_after_ellipsis), data_dim\n                    )\n                    for i in range(final_index, to_index):\n                        m_begin[final_index] = 0\n                        m_end[final_index] = data_shape[final_index]\n                        m_stride[final_index] = 1\n                        fshape_indices.append(final_index)\n                        final_index += 1\n                elif mask & new_axis_mask:\n                    fshape_indices.append(-1)\n                elif not mask & new_axis_mask:\n                    if final_index == len(m_begin):\n                        break\n                    if mask & begin_mask:\n                        m_begin[final_index] = -1 if stride[index] < 0 else 0\n                    elif begin[index]:\n                        m_begin[final_index] = begin[index]\n                    if mask & end_mask:\n                        m_end[final_index] = (\n                            -(data_shape[final_index] + 1)\n                            if stride[index] < 0\n                            else data_shape[final_index]\n                        )\n                    elif end[index]:\n                        m_end[final_index] = end[index]\n                    m_stride[final_index] = stride[index]\n                    if mask & shrink_axis_mask:\n                        # Tensorflow make axis with shrink_axis_mask as dimension 1\n                        m_begin[final_index] = (\n                            data_shape[final_index] + begin[index]\n                            if begin[index] < 0\n                            else begin[index]\n                        )\n                        m_end[final_index] = m_begin[final_index] + 1\n                        m_stride[final_index] = 1\n                        fshape_indices.append(-2)\n                    else:\n                        fshape_indices.append(final_index)\n\n                    final_index += 1\n            return m_begin, m_end, m_stride, fshape_indices\n\n        fshape_indices = None\n        if begin_mask or end_mask or ellipsis_mask or new_axis_mask or shrink_axis_mask:\n            begin, end, stride, fshape_indices = _transform_mask(stride_dim, ellipsis_mask)\n        out = _op.strided_slice(inputs[0], begin=begin, end=end, strides=stride)\n        out_shape = _infer_shape(out, mod=mod)\n        if not fshape_indices:\n            fshape_indices = range(len(out_shape))\n\n        # Create final output shape.\n        final_output = []\n        for gather_index in fshape_indices:\n            if gather_index == -1:\n                final_output.append(1)\n            elif gather_index == -2:\n                pass\n            else:\n                final_output.append(out_shape[gather_index])\n\n        if not final_output:\n            if not shrink_axis_mask:\n                ret = out\n            else:\n                final_shape = []\n                for dim in out_shape:\n                    if dim != 1:\n                        final_shape.append(dim)\n                if len(final_shape) == 0:\n                    ret = _op.squeeze(out)\n                else:\n                    # We need reshape to handle dynamic shape.\n                    ret = _op.reshape(out, newshape=tuple(final_shape))\n        else:\n            ret = _op.reshape(out, newshape=tuple(final_output))\n        return ret\n\n    return _impl\n\n\ndef _pad(name):\n    def _impl(inputs, attr, params, mod):\n        try:\n            padlist = _get_param(params, inputs[1])\n        except (IndexError, KeyError, AttributeError):\n            try:\n                padlist = _infer_value(inputs[1], params, mod).numpy().tolist()\n            except Exception:\n                padlist = inputs[1]\n\n        if isinstance(padlist, _expr.Expr):\n            paddings = padlist\n        else:\n            paddings = tuple(tuple(l) for l in padlist)\n        attr[\"pad_width\"] = paddings\n        attr[\"pad_value\"] = 0\n        new_inputs = [inputs[0]]\n        if name == \"PadV2\":\n            try:\n                attr[\"pad_value\"] = _get_num_param(params, inputs[2])\n            except (IndexError, KeyError, AttributeError):\n                attr[\"pad_value\"] = inputs[2]\n        return AttrCvt(\n            op_name=\"pad\",\n            ignores=[\"Tpaddings\"],\n        )(new_inputs, attr)\n\n    return _impl\n\n\ndef _mirror_pad():\n    def _impl(inputs, attr, params, mod):\n        padlist = _get_param(params, inputs[1])\n        paddings = tuple(tuple(l) for l in padlist)\n        attr[\"pad_width\"] = paddings\n        mode = attr[\"mode\"].decode(\"utf-8\")\n        attr[\"mode\"] = mode\n        new_inputs = [inputs[0]]\n        return AttrCvt(\n            op_name=\"mirror_pad\",\n            ignores=[\"Tpaddings\"],\n        )(new_inputs, attr)\n\n    return _impl\n\n\ndef _transpose():\n    def _impl(inputs, attr, params, mod):\n        # If perm is not specified, axes is left empty,\n        # otherwise its value is get from params\n        axes = _get_list_param(params, inputs[1], mod)\n        return _op.transpose(inputs[0], axes=axes)\n\n    return _impl\n\n\ndef _where():\n    def _impl(inputs, attr, params, mod):\n        if len(inputs) == 1:\n            return AttrCvt(op_name=\"argwhere\")(inputs, attr)\n        return AttrCvt(op_name=\"where\")(inputs, attr)\n\n    return _impl\n\n\ndef _clip_by_value():\n    def _impl(inputs, attr, params, mod):\n        a_min = _get_num_param(params, inputs[1])\n        a_max = _get_num_param(params, inputs[2])\n        return _op.clip(inputs[0], a_min=a_min, a_max=a_max)\n\n    return _impl\n\n\ndef _reverse_v2():\n    def _impl(inputs, attr, params, mod):\n        axis = _get_num_param(params, inputs[1])\n        return AttrCvt(op_name=\"reverse\", ignores=[\"Tidx\"], extras={\"axis\": int(axis)})(\n            [inputs[0]], attr\n        )\n\n    return _impl\n\n\ndef _rank():\n    def _impl(inputs, attr, params, mod):\n        input_shape = _infer_shape(inputs[0], mod)\n\n        name = attr[\"_node_name\"]\n        params[name] = tvm.nd.array(np.array([len(input_shape)]).astype(\"int32\"))\n        return [_expr.var(name, shape=params[name].shape, dtype=\"int32\")]\n\n    return _impl\n\n\ndef _range():\n    def _impl(inputs, attr, params, mod):\n        try:\n            start = _get_param(params, inputs[0])[0]\n        except (IndexError, KeyError, AttributeError):\n            try:\n                start = _infer_value(inputs[1], params, mod).numpy().tolist()\n                start = start if not isinstance(start, list) else start[0]\n            except Exception:\n                # Symbolic start\n                start = inputs[0]\n\n        try:\n            limit = (\n                _get_param(params, inputs[1])[0]\n                if hasattr(inputs[1], \"name_hint\") or isinstance(inputs[1], _expr.Constant)\n                else params.pop(\"Rank\").numpy()[0]\n            )\n        except (IndexError, KeyError, AttributeError):\n            try:\n                limit = _infer_value(inputs[1], params, mod).numpy().tolist()\n                limit = limit if not isinstance(limit, list) else limit[0]\n            except Exception:\n                limit = inputs[1]\n\n        try:\n            delta = _get_param(params, inputs[2])[0]\n        except (IndexError, KeyError, AttributeError):\n            try:\n                delta = _infer_value(inputs[2], params, mod).numpy().tolist()\n                delta = delta if not isinstance(delta, list) else delta[0]\n            except Exception:\n                # Symbolic delta\n                delta = inputs[2]\n\n        # if all attributes are constant, evalute the range function and return relay.const\n        dtype = attr[\"Tidx\"].name if \"Tidx\" in attr else str(start.dtype)\n        if all(\n            [\n                isinstance(start, (np.int32, np.int64, int, np.float32, np.float64, float)),\n                isinstance(limit, (np.int32, np.int64, int, np.float32, np.float64, float)),\n                isinstance(delta, (np.int32, np.int64, int, np.float32, np.float64, float)),\n            ]\n        ):\n            return tvm.relay.const(list(range(int(start), int(limit), int(delta))), dtype=dtype)\n\n        if isinstance(start, (np.int32, np.int64, int, np.float32, np.float64, float)):\n            start = _expr.const(start, dtype=dtype)\n        if isinstance(limit, (np.int32, np.int64, int, np.float32, np.float64, float)):\n            limit = _expr.const(limit, dtype=dtype)\n        if isinstance(delta, (np.int32, np.int64, int, np.float32, np.float64, float)):\n            delta = _expr.const(delta, dtype=dtype)\n\n        return AttrCvt(\n            op_name=\"arange\",\n            ignores=[\"Tidx\", \"_class\"],\n            extras={\"start\": start, \"stop\": limit, \"step\": delta, \"dtype\": dtype},\n        )([], attr)\n\n    return _impl\n\n\ndef _einsum():\n    def _impl(inputs, attr, params, mod):\n        einsum_attr = dict(attr)\n        einsum_attr[\"equation\"] = einsum_attr[\"equation\"].decode(\"utf-8\")\n        return AttrCvt(op_name=\"einsum\", ignores=[\"N\"])([inputs], einsum_attr)\n\n    return _impl\n\n\ndef _elu():\n    def _impl(inputs, attr, params, mod):\n        dtype = attr[\"T\"].name\n        alpha = tvm.relay.const(-1.0, dtype)\n        return alpha * _op.nn.relu(tvm.relay.const(1, dtype) - _op.exp(inputs[0])) + _op.nn.relu(\n            inputs[0]\n        )\n\n    return _impl\n\n\ndef _selu():\n    def _impl(inputs, attr, params, mod):\n        dtype = attr[\"T\"].name\n        alpha = tvm.relay.const(-1.6732632423543772848170429916717, dtype)\n        gamma = tvm.relay.const(1.0507009873554804934193349852946, dtype)\n        return gamma * (\n            alpha * _op.nn.relu(tvm.relay.const(1, dtype) - _op.exp(inputs[0]))\n            + _op.nn.relu(inputs[0])\n        )\n\n    return _impl\n\n\ndef _mean():\n    def _impl(inputs, attr, params, mod):\n        axis = _get_tuple_param(params, inputs[1])\n        return AttrCvt(\n            op_name=\"mean\",\n            ignores=[\"Tdim\", \"Tidx\"],\n            transforms={\"keep_dims\": \"keepdims\"},\n            extras={\"axis\": axis},\n        )([inputs[0]], attr)\n\n    return _impl\n\n\ndef _broadcast(name):\n    def _impl(inputs, attr, params, mod):\n        return AttrCvt(op_name=name, ignores=[\"name\", \"incompatible_shape_error\", \"Tidx\"])(\n            inputs, attr\n        )\n\n    return _impl\n\n\ndef _split(has_size_vector):\n    # TF documentation https://www.tensorflow.org/api_docs/python/tf/split\n    def _impl(inputs, attr, params, mod):\n        try:\n            # order and number of inputs are different:\n            # if has_size_vector:\n            #     https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/split-v\n            # else:\n            #     https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/split\n\n            # in addition, `axis` and `num_or_size_splits` can be tensors in TensorFlow,\n            # we can only support constants\n            if has_size_vector:\n                input_node_index = 0\n                input_axis_index = 2\n                size_splits = _get_param(params, inputs[1])\n                section_beginnings = np.cumsum(size_splits)[:-1]\n                indices_or_sections = tuple(section_beginnings)\n            else:\n                input_node_index = 1\n                input_axis_index = 0\n                indices_or_sections = attr[\"num_split\"]\n            input_node = inputs[input_node_index]\n            axis_input_value = _get_num_param(params, inputs[input_axis_index])\n        except (IndexError, KeyError, AttributeError):\n            raise TypeError(\n                \"Unsupported argument for split: `axis` and `num_or_size_splits` \"\n                \"should be constants\"\n            )\n        return _op.split(\n            input_node, indices_or_sections=indices_or_sections, axis=int(axis_input_value)\n        )\n\n    return _impl\n\n\ndef _unpack():\n    def _impl(inputs, attr, params, mod):\n        input_node = inputs[0]\n        axis = attr[\"axis\"]\n        input_shape = _infer_shape(input_node, mod)\n        axis_length = input_shape[axis]\n        if axis_length < 0:\n            raise TypeError(\"Unstack with unknown axis length\")\n        splitted = _op.split(input_node, indices_or_sections=axis_length, axis=axis)\n        axis = [axis]\n        return _expr.TupleWrapper(\n            _expr.Tuple([_op.squeeze(split_item, axis=axis) for split_item in splitted]),\n            len(splitted),\n        )\n\n    return _impl\n\n\ndef _softmax():\n    def _impl(inputs, attr, params, mod):\n        return AttrCvt(op_name=\"softmax\", transforms={\"axis\": (\"axis\", 1)})([inputs[0]], attr)\n\n    return _impl\n\n\ndef _softsign():\n    # op description: https://www.tensorflow.org/api_docs/python/tf/math/softsign\n    def _impl(inputs, attr, params, mod):\n        abs_out = get_relay_op(\"abs\")(inputs[0])\n        add_out = abs_out + tvm.relay.const(1, attr[\"T\"].name)\n        return inputs[0] / add_out\n\n    return _impl\n\n\ndef _softplus():\n    # op description: https://www.tensorflow.org/api_docs/python/tf/math/softplus\n    def _impl(inputs, attr, params, mod):\n        exp_out = AttrCvt(\"exp\")(inputs, attr)\n        inputs.append(tvm.relay.const(1, attr[\"T\"].name))\n        rh = tvm.relay.const(1, attr[\"T\"].name)\n        add_out = get_relay_op(\"add\")(exp_out, rh)\n        return get_relay_op(\"log\")(add_out)\n\n    return _impl\n\n\ndef _topk():\n    def _impl(inputs, attr, params, mod):\n        k_input = inputs.pop(1)\n        try:\n            k = int(_get_num_param(params, k_input))\n        except (IndexError, KeyError, AttributeError):\n            try:\n                k = int(_infer_value(k_input, params, mod).numpy().tolist())\n            except Exception:\n                k = k_input\n        if isinstance(k, int):\n            if k < 1:\n                raise tvm.error.OpAttributeInvalid(\n                    \"Attribute k must be positive in operator TopKV2\"\n                )\n            k = _expr.const(k)\n        if attr[\"sorted\"] is False:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Attribute sorted=False is not supported in operator TopKV2\"\n            )\n        return AttrCvt(\n            op_name=\"topk\",\n            ignores=[\"sorted\"],\n            extras={\"k\": k, \"is_ascend\": False, \"dtype\": \"int32\"},\n        )([inputs[0]], attr)\n\n    return _impl\n\n\ndef _floordiv():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 2\n        return AttrCvt(\"floor_divide\")(inputs, attr)\n\n    return _impl\n\n\ndef _floormod():\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 2\n        return AttrCvt(\"floor_mod\")(inputs, attr)\n\n    return _impl\n\n\ndef _logical(name):\n    def _impl(inputs, attr, params, mod):\n        return AttrCvt(op_name=name)(inputs, attr)\n\n    return _impl\n\n\ndef _space_to_batch_nd():\n    def _impl(inputs, attr, params, mod):\n        block_shape = _get_list_param(params, inputs[1], mod)\n\n        paddings = _get_list_param(params, inputs[2], mod)\n        paddings = np.squeeze(paddings)\n        if len(paddings.shape) == 1:\n            paddings = np.expand_dims(paddings, axis=0)\n        paddings = paddings.tolist()\n\n        attr[\"block_shape\"] = block_shape\n        attr[\"paddings\"] = paddings\n        out = AttrCvt(\"space_to_batch_nd\", ignores=[\"Tblock_shape\", \"Tpaddings\"])([inputs[0]], attr)\n\n        return out\n\n    return _impl\n\n\ndef _batch_to_space_nd():\n    def _impl(inputs, attr, params, mod):\n        block_shape = _get_list_param(params, inputs[1], mod)\n\n        crops = _get_list_param(params, inputs[2], mod)\n        crops = np.squeeze(crops)\n        if len(crops.shape) == 1:\n            crops = np.expand_dims(crops, axis=0)\n        crops = crops.tolist()\n\n        attr[\"block_shape\"] = block_shape\n        attr[\"crops\"] = crops\n        out = AttrCvt(\"batch_to_space_nd\", ignores=[\"Tblock_shape\", \"Tcrops\"])([inputs[0]], attr)\n\n        return out\n\n    return _impl\n\n\ndef _atan2():\n    def _impl(inputs, attr, params, mod):\n        divide = _elemwise(\"divide\")(inputs, attr, params, mod)\n        return get_relay_op(\"atan\")(divide)\n\n    return _impl\n\n\ndef _prod():\n    def _impl(inputs, attr, params, mod):\n        axis = _get_num_param(params, inputs[1])\n        keepdims = attr[\"keep_dims\"]\n        return _op.prod(inputs[0], int(axis), keepdims=keepdims)\n\n    return _impl\n\n\ndef _log1p():\n    # op description: https://www.tensorflow.org/api_docs/python/tf/math/log1p\n    def _impl(inputs, attr, params, mod):\n        one = tvm.relay.const(1, attr[\"T\"].name)\n        add_out = get_relay_op(\"add\")(inputs[0], one)\n        return get_relay_op(\"log\")(add_out)\n\n    return _impl\n\n\ndef _one_hot():\n    def _impl(inputs, attr, params, mod):\n        depth = int(_get_num_param(params, inputs[1]))\n        dtype = attr[\"T\"].name\n\n        on_value = _get_num_param(params, inputs[2])\n        off_value = _get_num_param(params, inputs[3])\n        new_inputs = [\n            inputs[0],\n            tvm.relay.const(on_value, dtype),\n            tvm.relay.const(off_value, dtype),\n        ]\n        return AttrCvt(\"one_hot\", ignores=[\"TI\"], extras={\"depth\": depth, \"dtype\": dtype})(\n            new_inputs, attr\n        )\n\n    return _impl\n\n\ndef _squared_difference():\n    def _impl(inputs, attr, params, mod):\n        difference = _op.subtract(inputs[0], inputs[1])\n        return _op.multiply(difference, difference)\n\n    return _impl\n\n\ndef _size():\n    def _impl(inputs, attr, params, mod):\n        new_attr = attr\n        new_attr[\"out_type\"] = attr[\"out_type\"].name\n        return AttrCvt(\"ndarray_size\", transforms={\"out_type\": \"dtype\"})(inputs, new_attr)\n\n    return _impl\n\n\ndef _add_n():\n    def _impl(inputs, attr, params, mod):\n        if not isinstance(inputs, tuple):\n            inputs = list(inputs)\n        assert len(inputs) > 0, \"add_n take >=1 inputs, but 0 given.\"\n        _res = inputs[0]\n        for each in inputs[1:]:\n            _res = _op.add(_res, each)\n        return _res\n\n    return _impl\n\n\ndef _LSTMBlockCell():\n    def _impl(inputs, attr, params, mod):\n        \"\"\"LSTM Block cell.\n        Calculations and return values are described in:\n        https://github.com/tensorflow/tensorflow/blob/\n        r1.8/tensorflow/contrib/rnn/python/ops/lstm_ops.py#L41-L114\n\n        Parameters\n        ----------\n        inputs : relay.Expr\n            Input data\n        in_state_c: list of relay.Expr\n            Cell state input values for all the layers\n        in_state_h: list of relay.Expr\n            Hidden state input values for all the layers\n        attrs : dict\n            Dict of operator attributes\n        params : dict\n            List of pretrained weights and bias\n\n        Returns\n        -------\n        relay.Expr.TupleWapper\n            [i, cs, f, o, ci, co, h]\n        \"\"\"\n        in_data = inputs[0]\n        in_state_c = inputs[1]\n        in_state_h = inputs[2]\n        in_weight = inputs[3]\n        in_bias = inputs[7]\n        forget_bias = attr.pop(\"forget_bias\")\n        input_shape = _infer_shape(inputs[0], mod)\n        weight_shape = _infer_shape(inputs[3], mod)\n        batch_size, input_size = input_shape[0], input_shape[1]\n        num_hidden_layers = weight_shape[1]\n\n        in_data = _op.reshape(in_data, newshape=(batch_size, input_size))\n        ixh = _op.concatenate([in_data, in_state_h], axis=1)\n        in_weight = _op.transpose(in_weight, axes=None)\n        gates = _op.nn.dense(ixh, in_weight, units=num_hidden_layers)\n        gates_bias = _op.add(gates, in_bias)\n        gate_list = _op.split(gates_bias, indices_or_sections=4, axis=1)\n        in_gate = _op.sigmoid(gate_list[0])\n        in_transform = _op.tanh(gate_list[1])\n        forget_gate = _op.add(gate_list[2], tvm.relay.const(forget_bias, attr[\"T\"].name))\n        forget_gate = _op.sigmoid(forget_gate)\n        out_gate = _op.sigmoid(gate_list[3])\n        next_c = _op.add(_op.multiply(forget_gate, in_state_c), _op.multiply(in_gate, in_transform))\n        co = _op.tanh(next_c)\n        next_h = out_gate * co\n\n        return tvm.relay.TupleWrapper(\n            tvm.relay.Tuple([in_gate, next_c, forget_gate, out_gate, in_transform, co, next_h]), 7\n        )\n\n    return _impl\n\n\ndef _unique(return_counts=True):\n    def _impl(inputs, attr, params, mod):\n        assert len(inputs) == 1\n        data = inputs[0]\n        if return_counts:\n            [unique, _, inverse_indices, num_uniq, counts] = _op.unique(\n                data, is_sorted=False, return_counts=True\n            )\n            unique_sliced = _op.strided_slice(unique, begin=[0], end=num_uniq, slice_mode=\"size\")\n            counts_sliced = _op.strided_slice(counts, begin=[0], end=num_uniq, slice_mode=\"size\")\n            return _expr.TupleWrapper(\n                _expr.Tuple([unique_sliced, inverse_indices, counts_sliced]),\n                3,\n            )\n        [unique, _, inverse_indices, num_uniq] = _op.unique(\n            data, is_sorted=False, return_counts=False\n        )\n        unique_sliced = _op.strided_slice(unique, begin=[0], end=num_uniq, slice_mode=\"size\")\n        return _expr.TupleWrapper(\n            _expr.Tuple([unique_sliced, inverse_indices]),\n            2,\n        )\n\n    return _impl\n\n\ndef _bincount():\n    def _impl(inputs, attr, params, mod):\n        input = inputs[0]  # arr: int32 Tensor\n        size = inputs[1]  # size: non-negative int scalar Tensor\n        # weights: int32, int64, float32, or float64 Tensor with the same shape as arr\n        # or a length-0 Tensor, in which case it acts as all weights equal to 1.\n        weights = inputs[2]\n        # Returns: Output: 1D Tensor with length equal to size\n        # The counts or summed weights for each value in the range [0, size).\n\n        input_shape = _infer_shape(input, mod)\n        if len(input_shape) > 1:\n            input = _op.reshape(input, [-1])\n\n        is_weights_zero_tensor = True\n        if weights:\n            weights_shape = _infer_shape(weights, mod)\n            is_weights_zero_tensor = weights_shape == (0,)\n            if len(weights_shape) > 1:\n                weights = _op.reshape(weights, [-1])\n\n        # Output should have the same dtype as weights.\n        if is_weights_zero_tensor:\n            # if weights are length-0 Tensor - output dtype is float32\n            out_dtype = \"float32\"\n            updates = _op.cast(_op.ones_like(input), out_dtype)\n        else:\n            out_dtype = _infer_type(weights, mod).checked_type.dtype\n            updates = weights\n\n        counts_shape = _op.reshape(size, [1])\n        counts = _op.zeros(counts_shape, out_dtype)\n        out = _op.scatter_add(counts, input, updates, axis=0)\n        return out\n\n    return _impl\n\n\ndef _dense_bincount():\n    def _impl(inputs, attr, params, mod):\n        input = inputs[0]  # input: int32, int64. 1D or 2D int Tensor\n        size = inputs[1]  # size: non-negative int scalar Tensor\n        # weights: int32, int64, float32, or float64 Tensor with the same shape as input\n        # or a length-0 Tensor, in which case it acts as all weights equal to 1.\n        weights = inputs[2]\n        # Returns: Output: 1D Tensor with length equal to size\n        # or 2D Tensor with [batch_size, size].\n        # The counts or summed weights for each value in the range [0, size).\n\n        input_dtype = _infer_type(input, mod).checked_type.dtype\n        input_shape = _infer_shape(input, mod)\n        is_2d_input = len(input_shape) == 2\n\n        if input_dtype == \"int64\":\n            warnings.warn(\n                \"Casting an int64 input to int32, since we do not have int64 atomic add\"\n                \"needed for bincount yet.\"\n            )\n            input = _op.cast(input, \"int32\")\n\n        is_weights_zero_tensor = True\n        if weights:\n            weights_shape = _infer_shape(weights, mod)\n            is_weights_zero_tensor = weights_shape == (0,)\n\n        # Output should have the same dtype as weights.\n        if is_weights_zero_tensor:\n            # if weights are length-0 Tensor - output dtype is float32\n            out_dtype = \"float32\"\n            updates = _op.cast(_op.ones_like(input), out_dtype)\n        else:\n            out_dtype = _infer_type(weights, mod).checked_type.dtype\n            updates = weights\n\n        if is_2d_input:\n            batch_arr = _op.take(_op.shape_of(input), _expr.const([0]))\n            size_arr = _op.reshape(size, [1])\n            counts_shape = _op.concatenate([batch_arr, size_arr], axis=0)\n            counts = _op.zeros(counts_shape, out_dtype)\n            out = _op.scatter_add(counts, input, updates, axis=1)\n        else:\n            counts_shape = _op.reshape(size, [1])\n            counts = _op.zeros(counts_shape, out_dtype)\n            out = _op.scatter_add(counts, input, updates, axis=0)\n\n        if attr[\"binary_output\"]:\n            out = _op.cast(_op.cast(out, \"bool\"), out_dtype)\n        return out\n\n    return _impl\n\n\n# _convert_map defines maps of name to converter functor(callable)\n# for 1 to 1 mapping, use Renamer if nothing but name is different\n# use AttrCvt if attributes need to be converted\n# for 1 to N mapping(composed), use custom callable functions\n# for N to 1 mapping, currently not supported(?)\n_convert_map = {\n    \"Abs\": AttrCvt(\"abs\"),\n    \"Acos\": AttrCvt(\"acos\"),\n    \"Acosh\": AttrCvt(\"acosh\"),\n    \"Add\": _elemwise(\"add\"),\n    \"AddN\": _add_n(),\n    \"AddV2\": _elemwise(\"add\"),\n    \"All\": _reduce(\"all\"),\n    \"Any\": _reduce(\"any\"),\n    \"ArgMax\": _argx(_op.argmax, \"argmax\"),\n    \"ArgMin\": _argx(_op.argmin, \"argmin\"),\n    \"Asin\": AttrCvt(\"asin\"),\n    \"Asinh\": AttrCvt(\"asinh\"),\n    \"Assert\": _assert(),\n    \"Atan\": AttrCvt(\"atan\"),\n    \"Atanh\": AttrCvt(\"atanh\"),\n    \"Atan2\": _atan2(),\n    \"AvgPool\": _pooling(\"avg_pool\"),\n    \"AvgPool3D\": _pool3d(\"avg_pool3d\"),\n    \"BatchMatMul\": _batch_matmul(),\n    \"BatchMatMulV2\": _batch_matmul(),\n    \"BatchNormWithGlobalNormalization\": _batch_norm(),\n    \"BatchToSpaceND\": _batch_to_space_nd(),\n    \"BiasAdd\": _bias_add(),\n    \"Bincount\": _bincount(),\n    \"BroadcastTo\": _broadcast_to(),\n    \"BroadcastArgs\": _broadcast_args(),\n    \"Cast\": _cast(),\n    \"Ceil\": AttrCvt(\"ceil\"),\n    \"CheckNumerics\": _check_numerics(),\n    \"ClipByValue\": _clip_by_value(),\n    \"Concat\": _concat(),\n    \"ConcatV2\": _concatV2(),\n    \"Conv2D\": _conv(\"conv\"),\n    \"Conv2DBackpropInput\": _conv(\"conv_transpose\"),\n    \"Conv3D\": _conv3d(\"conv\"),\n    \"Conv3DBackpropInputV2\": _conv3d(\"conv_transpose\"),\n    \"Cos\": AttrCvt(\"cos\"),\n    \"Cosh\": AttrCvt(\"cosh\"),\n    \"CropAndResize\": _crop_and_resize(),\n    \"DecodeJpeg\": _decode_image(),\n    \"DenseBincount\": _dense_bincount(),\n    \"DepthToSpace\": _depth_to_space(),\n    \"DepthwiseConv2dNative\": _conv(\"depthwise\"),\n    \"Dilation2D\": _dilation2d(),\n    \"Einsum\": _einsum(),\n    \"Elu\": _elu(),\n    \"Equal\": _broadcast(\"equal\"),\n    \"Erf\": AttrCvt(\"erf\"),\n    \"EuclideanNorm\": _euclidean_norm(),\n    \"Exp\": AttrCvt(\"exp\"),\n    \"ExpandDims\": _expand_dims(),\n    \"Expm1\": _expm1(),\n    \"Fill\": _fill(),\n    \"Floor\": AttrCvt(\"floor\"),\n    \"FloorDiv\": _floordiv(),\n    \"FloorMod\": _floormod(),\n    \"FusedBatchNorm\": _fused_batch_norm(),\n    \"FusedBatchNormV2\": _fused_batch_norm(),\n    \"FusedBatchNormV3\": _fused_batch_norm(),\n    \"Gather\": _gather(),\n    \"GatherNd\": _gather_nd(),\n    \"GatherV2\": _gather(),\n    \"Greater\": _broadcast(\"greater\"),\n    \"GreaterEqual\": _broadcast(\"greater_equal\"),\n    \"Identity\": _identity(),\n    \"IdentityN\": _identityn(),\n    \"InvertPermutation\": AttrCvt(\"invert_permutation\"),\n    \"IsFinite\": AttrCvt(\"isfinite\"),\n    \"IsInf\": AttrCvt(\"isinf\"),\n    \"IsNan\": AttrCvt(\"isnan\"),\n    \"LeakyRelu\": AttrCvt(\"leaky_relu\"),\n    \"LeftShift\": AttrCvt(\"left_shift\"),\n    \"Less\": _broadcast(\"less\"),\n    \"LessEqual\": _broadcast(\"less_equal\"),\n    \"Log\": AttrCvt(\"log\"),\n    \"Log1p\": _log1p(),\n    \"LogicalAnd\": _logical(\"logical_and\"),\n    \"LogicalNot\": _logical(\"logical_not\"),\n    \"LogicalOr\": _logical(\"logical_or\"),\n    \"LogSoftmax\": AttrCvt(\"log_softmax\"),\n    \"LRN\": _lrn(),\n    \"LSTMBlockCell\": _LSTMBlockCell(),\n    \"MatMul\": _matmul(),\n    \"Max\": _reduce(\"max\"),\n    \"Maximum\": _elemwise(\"maximum\"),\n    \"MaxPool\": _pooling(\"max_pool\"),\n    \"MaxPool3D\": _pool3d(\"max_pool3d\"),\n    \"Mean\": _mean(),\n    \"Min\": _reduce(\"min\"),\n    \"Minimum\": _elemwise(\"minimum\"),\n    \"MirrorPad\": _mirror_pad(),\n    \"Mod\": _elemwise(\"mod\"),\n    \"Mul\": _elemwise(\"multiply\"),\n    \"Neg\": AttrCvt(\"negative\"),\n    \"NonMaxSuppressionV2\": _nms(),\n    \"NonMaxSuppressionV3\": _nms(),\n    \"NonMaxSuppressionV4\": _nms(),\n    \"NonMaxSuppressionV5\": _nms(True),\n    \"CombinedNonMaxSuppression\": _combined_nms(),\n    \"NoOp\": _no_op(),\n    \"NotEqual\": _broadcast(\"not_equal\"),\n    \"OneHot\": _one_hot(),\n    \"Pack\": _pack(),\n    \"Pad\": _pad(\"Pad\"),\n    \"PadV2\": _pad(\"PadV2\"),\n    \"Pow\": _elemwise(\"power\"),\n    \"Prod\": _prod(),\n    \"Range\": _range(),\n    \"Rank\": _rank(),\n    \"RealDiv\": _elemwise(\"divide\"),\n    \"Relu\": AttrCvt(\"relu\"),\n    \"Relu6\": _relu6(),\n    \"Reshape\": _reshape(),\n    \"ResizeBicubic\": _resize(\"cubic\"),\n    \"ResizeBilinear\": _resize(\"linear\"),\n    \"ResizeNearestNeighbor\": _resize(\"nearest_neighbor\"),\n    \"ReverseV2\": _reverse_v2(),\n    \"RightShift\": AttrCvt(\"right_shift\"),\n    \"Rint\": AttrCvt(\"round\"),\n    \"Round\": AttrCvt(\"round\"),\n    \"Rsqrt\": _rsqrt(),\n    \"Select\": _where(),\n    \"SelectV2\": _where(),\n    \"Selu\": _selu(),\n    \"Shape\": _shape(),\n    \"Sigmoid\": AttrCvt(\"sigmoid\"),\n    \"Sign\": AttrCvt(\"sign\"),\n    \"Sin\": AttrCvt(\"sin\"),\n    \"Sinh\": AttrCvt(\"sinh\"),\n    \"Size\": _size(),\n    \"Slice\": _slice(),\n    \"Softmax\": _softmax(),\n    \"Softplus\": _softplus(),\n    \"Softsign\": _softsign(),\n    \"SpaceToBatchND\": _space_to_batch_nd(),\n    \"SpaceToDepth\": _space_to_depth(),\n    \"SparseToDense\": _sparse_to_dense(),\n    \"SparseTensorDenseMatMul\": _sparse_tensor_dense_matmul(),\n    \"SparseFillEmptyRows\": _sparse_fill_empty_rows(),\n    \"SparseReshape\": _sparse_reshape(),\n    \"SegmentSum\": _math_segment_sum(),\n    \"SparseSegmentSum\": _sparse_segment_sum(),\n    \"SparseSegmentSumWithNumSegments\": _sparse_segment_sum_with_num_segments(),\n    \"SparseSegmentSqrtN\": _sparse_segment_sum_sqrtn(),\n    \"SparseSegmentSqrtNWithNumSegments\": _sparse_segment_sum_sqrtn_with_num_segments(),\n    \"SparseSegmentMean\": _sparse_segment_mean(),\n    \"SparseSegmentMeanWithNumSegments\": _sparse_segment_mean_with_num_segments(),\n    \"SparseTensorDenseAdd\": _sparse_tensor_dense_add(),\n    \"Split\": _split(False),\n    \"SplitV\": _split(True),\n    \"Sqrt\": AttrCvt(\"sqrt\"),\n    \"Square\": _square(),\n    \"SquaredDifference\": _squared_difference(),\n    \"Squeeze\": _squeeze(),\n    \"StopGradient\": _identity(),\n    \"StridedSlice\": _stridedSlice(),\n    \"Sub\": _elemwise(\"subtract\"),\n    \"Sum\": _sum(),\n    \"Tan\": AttrCvt(\"tan\"),\n    \"Tanh\": AttrCvt(\"tanh\"),\n    \"TensorArrayConcatV3\": _tensor_array_concat(),\n    \"TensorArrayGatherV3\": _tensor_array_gather(),\n    \"TensorArrayReadV3\": _tensor_array_read(),\n    \"TensorArrayScatterV3\": _tensor_array_scatter(),\n    \"TensorArraySizeV3\": _tensor_array_size(),\n    \"TensorArraySplitV3\": _tensor_array_split(),\n    \"TensorArrayV3\": _tensor_array(),\n    \"TensorArrayWriteV3\": _tensor_array_write(),\n    \"Tile\": _tile(),\n    \"TopKV2\": _topk(),\n    \"Transpose\": _transpose(),\n    \"TruncateMod\": _elemwise(\"mod\"),\n    \"Unique\": _unique(False),\n    \"UniqueWithCounts\": _unique(True),\n    \"Unpack\": _unpack(),\n    \"UnravelIndex\": _unravel_index(),\n    \"Where\": _where(),\n    \"ZerosLike\": AttrCvt(\"zeros_like\"),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tensorflow_parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TF: Tensorflow parser\"\"\"\n# pylint: disable=import-outside-toplevel, assignment-from-no-return\n\nimport os\nfrom tvm.contrib import utils\n\n\nclass TFParser(object):\n    \"\"\"\n    A Wrapper to handle tensorflow models parsing, TensorFlow is needed\n\n    Parameters\n    ----------\n    model_dir : tensorflow frozen pb file or a directory that contains saved\n    model or checkpoints.\n\n    outputs : List of output tensor names (Optional)\n        Optional output node names. This will be protected for saved model\n        when we do remove training nodes.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        parser = TFParser(model_dir)\n        graphdef = parser.parse()\n    \"\"\"\n\n    def __init__(self, model_dir, outputs=None):\n        from tensorflow.core.framework import graph_pb2\n\n        self._tmp_dir = utils.tempdir()\n        self._model_dir = model_dir\n        self._graph = graph_pb2.GraphDef()\n        self._outputs = outputs or []\n\n    def _set_graph(self, graph):\n        \"\"\"Set Graph\"\"\"\n        self._graph = graph\n\n    def _get_graph(self):\n        \"\"\"Get Graph\"\"\"\n        return self._graph\n\n    def _load_pb_file(self):\n        \"\"\"Load single pb file\"\"\"\n        graph = self._get_graph()\n        with open(self._model_dir, \"rb\") as f:\n            graph.ParseFromString(f.read())\n        return graph\n\n    def _get_tag_set(self):\n        \"\"\"Return the tag set of saved model, multiple metagraphs are not supported\"\"\"\n        try:\n            from tensorflow.contrib.saved_model.python.saved_model.reader import (\n                get_saved_model_tag_sets,\n            )\n        except ImportError:\n            try:\n                from tensorflow.python.tools.saved_model_utils import get_saved_model_tag_sets\n            except ImportError:\n                raise ImportError(\n                    \"InputConfiguration: Unable to import get_saved_model_tag_sets which is \"\n                    \"required to get tag set from saved model.\"\n                )\n        tag_sets = get_saved_model_tag_sets(self._model_dir)\n        return tag_sets[0]\n\n    def _get_output_names(self):\n        \"\"\"Return the concatenated output names\"\"\"\n        try:\n            import tensorflow.compat.v1 as tf\n        except ImportError:\n            raise ImportError(\n                \"InputConfiguration: Unable to import tensorflow which is \"\n                \"required to restore from saved model.\"\n            )\n        tags = self._get_tag_set()\n        output_names = set()\n        with tf.Session() as sess:\n            meta_graph_def = tf.saved_model.loader.load(sess, tags, self._model_dir)\n            for sig_def in meta_graph_def.signature_def.values():\n                for output_tensor in sig_def.outputs.values():\n                    output_names.add(output_tensor.name.replace(\":0\", \"\"))\n        tf.reset_default_graph()\n        return \",\".join(output_names)\n\n    def _load_saved_model(self):\n        \"\"\"Load the tensorflow saved model.\"\"\"\n        try:\n            from tensorflow.python.tools import freeze_graph\n            from tensorflow.python.framework import ops\n            from tensorflow.python.framework import graph_util\n            from tensorflow.core.framework import graph_pb2\n        except ImportError:\n            raise ImportError(\n                \"InputConfiguration: Unable to import tensorflow which is \"\n                \"required to restore from saved model.\"\n            )\n\n        saved_model_dir = self._model_dir\n        output_graph_filename = self._tmp_dir.relpath(\"tf_frozen_model.pb\")\n        input_saved_model_dir = saved_model_dir\n        output_node_names = self._get_output_names()\n\n        input_binary = False\n        input_saver_def_path = False\n        restore_op_name = None\n        filename_tensor_name = None\n        clear_devices = True\n        input_meta_graph = False\n        checkpoint_path = None\n        input_graph_filename = None\n        saved_model_tags = \",\".join(self._get_tag_set())\n\n        freeze_graph.freeze_graph(\n            input_graph_filename,\n            input_saver_def_path,\n            input_binary,\n            checkpoint_path,\n            output_node_names,\n            restore_op_name,\n            filename_tensor_name,\n            output_graph_filename,\n            clear_devices,\n            \"\",\n            \"\",\n            \"\",\n            input_meta_graph,\n            input_saved_model_dir,\n            saved_model_tags,\n        )\n\n        with ops.Graph().as_default():  # pylint: disable=not-context-manager\n            output_graph_def = graph_pb2.GraphDef()\n            with open(output_graph_filename, \"rb\") as f:\n                output_graph_def.ParseFromString(f.read())\n            output_graph_def = graph_util.remove_training_nodes(\n                output_graph_def, protected_nodes=self._outputs\n            )\n            return output_graph_def\n\n    def _load_ckpt(self):\n        \"\"\"TODO: Load checkpoint model.\"\"\"\n        raise RuntimeError(\n            \"InputConfiguration: Loading tf checkpoint model is \" \"not supported yet.\"\n        )\n\n    def parse(self):\n        \"\"\"\n        Parse tensorflow models: checkpoints, saved models, and single frozen pb file.\n\n        Returns\n        -------\n        GraphDef of the passed model\n        \"\"\"\n\n        graph = None\n\n        if os.path.isdir(self._model_dir):\n            ckpt = os.path.join(self._model_dir, \"checkpoint\")\n            if not os.path.isfile(ckpt):\n                if not os.path.isdir(os.path.join(self._model_dir, \"variables\")):\n                    raise RuntimeError(\"InputConfiguration: Invalid model path.\")\n                graph = self._load_saved_model()\n            else:\n                graph = self._load_ckpt()\n        elif os.path.isfile(self._model_dir):\n            # Only .pb or .pbtxt is a valid suffix name.\n            if self._model_dir.endswith(\".pb\") or self._model_dir.endswith(\".pbtxt\"):\n                cur_dir = os.path.dirname(self._model_dir)\n            else:\n                raise RuntimeError(\"InputConfiguration: Invalid model format.\")\n\n            # It is a saved model if `variables` directory is present at the\n            # same directory with the pb or pbtxt file.\n            if os.path.isdir(os.path.join(cur_dir, \"variables\")):\n                self._model_dir = cur_dir\n                graph = self._load_saved_model()\n            else:\n                graph = self._load_pb_file()\n        else:\n            raise RuntimeError(\"InputConfiguration: Unrecognized model \" \"file or path.\")\n\n        self._set_graph(graph)\n        return graph\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tflite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, too-many-lines, import-outside-toplevel\n\"\"\"Tensorflow lite frontend.\"\"\"\nimport itertools\nimport math\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import IRModule\nfrom tvm.runtime.name_transforms import sanitize_name\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .. import qnn as _qnn\nfrom .common import ExprTable\nfrom .common import infer_shape as _infer_shape\nfrom .common import lstm_cell, to_int_list, shape_of, try_infer_value\nfrom .tflite_flexbuffer import FlexBufferDecoder\n\n__all__ = [\"from_tflite\"]\n\n\nclass TensorWrapper(object):\n    \"\"\"Tensor wrapper for TFLite Tensor\"\"\"\n\n    def __init__(self, tensor_idx, tensor, buffer, qnn_params=None):\n        self.tensor_idx = tensor_idx\n        self.tensor = tensor\n        self.buffer = buffer\n        self.qnn_params = qnn_params\n\n\nclass OperatorConverter(object):\n    \"\"\"Operator Converted for converting TFLite ops to Relay ops\"\"\"\n\n    def __init__(self, model, subgraph, exp_tab):\n\n        try:\n            from tflite.ActivationFunctionType import ActivationFunctionType\n            from tflite.BuiltinOperator import BuiltinOperator\n            from tflite.BuiltinOptions import BuiltinOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        self.model = model\n        self.subgraph = subgraph\n        self.exp_tab = exp_tab\n        self.builtin_op_code = build_str_map(BuiltinOperator())\n        self.activation_fn_type = build_str_map(ActivationFunctionType())\n        self.builtin_options = build_str_map(BuiltinOptions())\n        self.prefetched_nodes = {}\n        self.allow_custom_ops = False\n\n        # Add more operators\n        self.convert_map = {\n            \"ABS\": self.convert_abs,\n            \"ADD\": self.convert_add,\n            \"ADD_N\": self.convert_add_n,\n            \"ARG_MAX\": self.convert_arg_max,\n            \"ARG_MIN\": self.convert_arg_min,\n            \"AVERAGE_POOL_2D\": self.convert_average_pool2d,\n            \"BATCH_TO_SPACE_ND\": self.convert_batch_to_space_nd,\n            \"CAST\": self.convert_cast,\n            \"CEIL\": self.convert_ceil,\n            \"CONCATENATION\": self.convert_concatenation,\n            \"CONV_2D\": self.convert_conv2d,\n            \"COS\": self.convert_cos,\n            \"DENSIFY\": self.convert_densify,\n            \"DEPTH_TO_SPACE\": self.convert_depth_to_space,\n            \"DEPTHWISE_CONV_2D\": self.convert_depthwise_conv2d,\n            \"DEQUANTIZE\": self.convert_dequantize,\n            \"DETECTION_POSTPROCESS\": self.convert_detection_postprocess,\n            \"DIV\": self.convert_div,\n            \"ELU\": self.convert_elu,\n            \"EQUAL\": self.convert_equal,\n            \"EXP\": self.convert_exp,\n            \"EXPAND_DIMS\": self.convert_expand_dims,\n            \"FAKE_QUANT\": self.convert_fake_quant,\n            \"FILL\": self.convert_fill,\n            \"FLOOR_DIV\": self.convert_floor_div,\n            \"FLOOR_MOD\": self.convert_floor_mod,\n            \"FLOOR\": self.convert_floor,\n            \"FULLY_CONNECTED\": self.convert_fully_connected,\n            \"GATHER\": self.convert_gather,\n            \"GATHER_ND\": self.convert_gather_nd,\n            \"GREATER_EQUAL\": self.convert_greater_equal,\n            \"GREATER\": self.convert_greater,\n            \"HARD_SWISH\": self.convert_hard_swish,\n            \"L2_NORMALIZATION\": self.convert_l2_normalization,\n            \"L2_POOL_2D\": self.convert_l2_pool2d,\n            \"LEAKY_RELU\": self.convert_leaky_relu,\n            \"LESS_EQUAL\": self.convert_less_equal,\n            \"LESS\": self.convert_less,\n            \"LOCAL_RESPONSE_NORMALIZATION\": self.convert_lrn,\n            \"LOG\": self.convert_log,\n            \"LOG_SOFTMAX\": self.convert_log_softmax,\n            \"LOGICAL_AND\": self.convert_logical_and,\n            \"LOGICAL_NOT\": self.convert_logical_not,\n            \"LOGICAL_OR\": self.convert_logical_or,\n            \"LOGISTIC\": self.convert_logistic,\n            \"MATRIX_DIAG\": self.convert_matrix_diag,\n            \"MATRIX_SET_DIAG\": self.convert_matrix_set_diag,\n            \"MAX_POOL_2D\": self.convert_max_pool2d,\n            \"MAXIMUM\": self.convert_maximum,\n            \"MEAN\": self.convert_reduce_mean,\n            \"MINIMUM\": self.convert_minimum,\n            \"MIRROR_PAD\": self.convert_mirror_pad,\n            \"MUL\": self.convert_mul,\n            \"NEG\": self.convert_neg,\n            \"NOT_EQUAL\": self.convert_not_equal,\n            \"ONE_HOT\": self.convert_one_hot,\n            \"PACK\": self.convert_pack,\n            \"PAD\": self.convert_pad,\n            \"PADV2\": self.convert_pad,\n            \"POW\": self.convert_pow,\n            \"PRELU\": self.convert_prelu,\n            \"RANGE\": self.convert_range,\n            \"QUANTIZE\": self.convert_quantize,\n            \"REDUCE_ANY\": self.convert_reduce_any,\n            \"REDUCE_MAX\": self.convert_reduce_max,\n            \"REDUCE_MIN\": self.convert_reduce_min,\n            \"REDUCE_PROD\": self.convert_reduce_prod,\n            \"RELU\": self.convert_relu,\n            \"RELU6\": self.convert_relu6,\n            \"RELU_N1_TO_1\": self.convert_relu_n1_to_1,\n            \"RESHAPE\": self.convert_reshape,\n            \"RESIZE_BILINEAR\": self.convert_resize_bilinear,\n            \"RESIZE_NEAREST_NEIGHBOR\": self.convert_resize_nearest_neighbor,\n            \"ROUND\": self.convert_round,\n            \"RSQRT\": self.convert_rsqrt,\n            \"REVERSE_SEQUENCE\": self.convert_reverse_sequence,\n            \"REVERSE_V2\": self.convert_reverse_v2,\n            \"SELECT\": self.convert_select,\n            \"SHAPE\": self.convert_shape,\n            \"SIN\": self.convert_sin,\n            \"SLICE\": self.convert_slice,\n            \"SOFTMAX\": self.convert_softmax,\n            \"SPACE_TO_BATCH_ND\": self.convert_space_to_batch_nd,\n            \"SPACE_TO_DEPTH\": self.convert_space_to_depth,\n            \"SPARSE_TO_DENSE\": self.convert_sparse_to_dense,\n            \"SPLIT\": self.convert_split,\n            \"SPLIT_V\": self.convert_split_v,\n            \"SQRT\": self.convert_sqrt,\n            \"SQUARE\": self.convert_square,\n            \"SQUARED_DIFFERENCE\": self.convert_squared_difference,\n            \"SQUEEZE\": self.convert_squeeze,\n            \"STRIDED_SLICE\": self.convert_strided_slice,\n            \"SUB\": self.convert_sub,\n            \"SUM\": self.convert_reduce_sum,\n            \"TAN\": self.convert_tan,\n            \"TANH\": self.convert_tanh,\n            \"TILE\": self.convert_tile,\n            \"TOPK_V2\": self.convert_topk_v2,\n            \"TRANSPOSE_CONV\": self.convert_transpose_conv,\n            \"TRANSPOSE\": self.convert_transpose,\n            \"UNPACK\": self.convert_unpack,\n            \"UNIDIRECTIONAL_SEQUENCE_LSTM\": self.convert_unidirectional_sequence_lstm,\n            \"WHERE\": self.convert_select,\n            \"ZEROS_LIKE\": self.convert_zeros_like,\n            \"NON_MAX_SUPPRESSION_V5\": self.convert_nms_v5,\n        }\n\n    def check_unsupported_ops(self):\n        \"\"\"Check unsupported TFLite ops in our converter.\"\"\"\n        unsupported_ops_set = set()\n        dynamic_range_ops_set = set()\n        for op_idx in range(self.subgraph.OperatorsLength()):\n            op = self.subgraph.Operators(op_idx)\n            op_code_str = self.get_op_code_str(op)\n            if op_code_str not in self.convert_map:\n                unsupported_ops_set.add(op_code_str)\n                continue\n\n            # Trying to exclude \"dynamic range quantization\" optimized ops as not supported in TVM\n            qnn_in_cnt = len(\n                [_.qnn_params for _ in self.get_input_tensors(op)[0:1] if _.qnn_params is not None]\n            )\n            qnn_weight_cnt = len(\n                [_.qnn_params for _ in self.get_input_tensors(op)[1:] if _.qnn_params is not None]\n            )\n            qnn_out_cnt = len(\n                [_.qnn_params for _ in self.get_output_tensors(op) if _.qnn_params is not None]\n            )\n\n            if qnn_in_cnt == 0 and qnn_out_cnt == 0 and qnn_weight_cnt > 0:\n                dynamic_range_ops_set.add(op_code_str)\n\n        raise_msg = \"\"\n\n        if unsupported_ops_set:\n            msg = \"The following operators are not supported in frontend \" \"TFLite: {}\\n\"\n            ops = str(list(unsupported_ops_set)).strip(\"[,]\")\n            raise_msg += msg.format(ops)\n\n        if dynamic_range_ops_set:\n            msg = (\n                \"The following operators are likely to have dynamic range quantization: {}. \"\n                \"If you are running an optimized graph, please turn off dynamic range quantization \"\n                \"or use full integer quantization\"\n            )\n            raise_msg += msg.format(str(list(dynamic_range_ops_set)).strip(\"[,]\"))\n\n        if len(raise_msg) > 0:\n            raise tvm.error.OpNotImplemented(raise_msg)\n\n    def unbind(self, data, axis=1):\n        \"\"\"\n        This is a modified version compared to the one in common.py.\n        The onnx version takes a relay.Expr.Call, the tflite\n        version a TensorWrapper. Also this version by default splits\n        along axis 1 and not axis 0 as the onnx version.\n\n         Parameters\n         ----------\n         data : tvm.relay.frontend.tflite.TensorWrapper\n             Input tensor\n         axis : int\n             Axis along which tensor is split.\n         Returns\n         -------\n         result : List[relay.Expr]\n             The sequence of computed tensors\n        \"\"\"\n        shape = to_int_list(self.get_tensor_shape(data))\n        if axis >= len(shape):\n            msg = \"Please check input dim, it shouldn't be greater than or equal to rank.\"\n            raise AttributeError(msg)\n\n        selections = shape[axis]\n        shape.pop(axis)\n        timestep = 0  # Reshape to make time step as the first dim\n        shape.insert(timestep, selections)\n        res_split = _op.split(\n            _op.reshape(self.get_expr(data.tensor_idx), tuple(shape)), selections, timestep\n        )\n        ret = []\n        for i in range(selections):\n            ret.append(_op.squeeze(res_split[i], axis=[timestep]))\n        return _expr.TupleWrapper(_expr.Tuple(ret), selections)\n\n    def convert_op_to_relay(self):\n        \"\"\"Convert TFLite ops to relay ops\"\"\"\n        for op_idx in range(self.subgraph.OperatorsLength()):\n            op = self.subgraph.Operators(op_idx)\n            op_code_str = self.get_op_code_str(op)\n            output_tensors = self.get_output_tensors(op)\n            try:\n                from tflite.Operator import Operator\n            except ImportError:\n                raise ImportError(\"The tflite package must be installed\")\n\n            assert isinstance(op, Operator)\n            ret = self.convert_map[op_code_str](op)\n\n            # In case the Op can be prefetched, the output can be optimized out\n            if ret is None:\n                continue\n\n            if len(output_tensors) == 1:\n                tensor_idx = output_tensors[0].tensor_idx\n                self.exp_tab.set_expr(get_tensor_name(self.subgraph, tensor_idx), ret)\n            else:\n                for idx, output_tensor in enumerate(output_tensors):\n                    self.exp_tab.set_expr(\n                        get_tensor_name(self.subgraph, output_tensor.tensor_idx), ret[idx]\n                    )\n\n    def get_op_code_str(self, op):\n        \"\"\"Get TFLite ops string representation\"\"\"\n        try:\n            from tflite.BuiltinOperator import BuiltinOperator\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        op_code_list_idx = op.OpcodeIndex()\n\n        op_c = self.model.OperatorCodes(op_code_list_idx)\n        # In TFlite 2.4.x there was a change where the type of the field that contained\n        # the builtin code changed from int8 to int32 in the flat buffer representation.\n        # However, to retain support for old flat buffers that were created, they retained\n        # the original 8 bit field, but named it \"deprecated_builtin_code\" in TFLite 2.4.\n        # This means that the API function BuiltinCode() which originally returned the value\n        # of the 8 bit field would now look for the value in the new int32 field in the\n        # schema and DeprecatedBuiltinCode() will look at the old 8 bit field.\n        # In TFLite 2.4, if the opcode value is less than 127, it can be in either field\n        # (however, if it is only in the \"builtin_code\" field, the model is not backward\n        # compatible), so similarly to TFLite 2.4 reader, we'll pick the higher value of the\n        # two fields.\n        # Remember however that this value came into existence only after Tensorflow\n        # lite 2.4.x and hence encase it in a try -except block.\n        # Phew !\n        try:\n            opc = max(op_c.DeprecatedBuiltinCode(), op_c.BuiltinCode())\n        except AttributeError:\n            # In versions before 2.4 the int8 field that holds the builtin code is accessed\n            # by BuiltinCode() and DeprecatedBuiltinCode() doesn't exist\n            opc = op_c.BuiltinCode()\n\n        op_code_id = opc\n        try:\n            op_code_str = self.builtin_op_code[op_code_id]\n        except KeyError:\n            raise NotImplementedError(\n                \"TFLite operator with code \"\n                + str(op_code_id)\n                + \" is not supported by this version of the fbs schema.\"\n            )\n        if op_code_id == BuiltinOperator.CUSTOM:\n            # Custom operator\n            custom_op_code_str = self.model.OperatorCodes(op_code_list_idx).CustomCode()\n\n            if self.allow_custom_ops:\n                return \"CUSTOM\"\n\n            if custom_op_code_str == b\"TFLite_Detection_PostProcess\":\n                return \"DETECTION_POSTPROCESS\"\n\n            raise NotImplementedError(\"Custom operators are currently not supported\")\n        return op_code_str\n\n    def get_input_tensors(self, op):\n        operator_inputs = op.InputsAsNumpy()\n        return self.get_tensors(operator_inputs)\n\n    def get_output_tensors(self, op):\n        operator_outputs = op.OutputsAsNumpy()\n        return self.get_tensors(operator_outputs)\n\n    def get_tensors(self, tensors_idx_list):\n        \"\"\"Get tensor wrapper list from given TFLite tensor index list\"\"\"\n        return_list = list()\n        for tensor_idx in tensors_idx_list:\n            if tensor_idx < 0:\n                return_list.append(TensorWrapper(tensor_idx, 0, 0))\n                continue\n\n            tensor = self.subgraph.Tensors(tensor_idx)\n            buffer_idx = tensor.Buffer()\n            buffer = self.model.Buffers(buffer_idx)\n\n            # Check if the tensors are quantized. Parse if yes.\n            qnn_params = None\n            tflite_qnn_params = tensor.Quantization()\n            if tflite_qnn_params is not None:\n                # TFLite supports both per-tensor and per-axis (aka channel) quantization.  For\n                # per-tensor quantization, scale and zero points are scalar values.  For per-axis\n                # quantization, scale and zero points for the weights are tensors (activations are\n                # per-tensor quantized). However, the TFLite quantization spec puts restrictions on\n                # zero points for per-axis quantization.  Specifically, the zero point is a tensor\n                # but all values are 0. More information can be found here -\n                # https://www.tensorflow.org/lite/performance/quantization_spec\n\n                tflite_scale = tflite_qnn_params.ScaleAsNumpy()\n                tflite_zero_point = tflite_qnn_params.ZeroPointAsNumpy()\n                is_qnn_params_valid = True\n\n                # Handle Per-axis and per-tensor cases\n                if isinstance(tflite_scale, np.ndarray):\n                    assert isinstance(tflite_zero_point, np.ndarray)\n\n                    # Tensor - Per-axis quantization\n                    if tflite_scale.size != 1 and tflite_zero_point.size != 1:\n                        scale = tflite_scale\n                        # Ensure that all zero points are zeros\n                        zero_point = tflite_zero_point\n                        if not np.all(zero_point == 0):\n                            raise tvm.error.OpAttributeInvalid(\n                                \"TFLite per-axis quantization restricts all zero points to be\"\n                                + \" 0, but a non-zero value is observed\"\n                            )\n                        zero_point = int(zero_point[0])\n\n                    # Scalar - Per-tensor quantization\n                    elif tflite_scale.size == 1 and tflite_zero_point.size == 1:\n                        scale = float(tflite_scale[0])\n                        zero_point = int(tflite_zero_point[0])\n\n                    else:\n                        raise NotImplementedError(\n                            \"Quantized type {} (scale) and  {} (zero point) not supported\".format(\n                                type(tflite_scale), type(tflite_zero_point)\n                            )\n                        )\n                elif tflite_scale == 0 and tflite_zero_point == 0:\n                    # Handle corner case for ops like quantized reshape whose second operand (shape)\n                    # has zero scale and zero zero point. This is not used.\n                    is_qnn_params_valid = False\n                else:\n                    raise NotImplementedError(\n                        \"Quantized type {} not supported\".format(type(tflite_scale))\n                    )\n\n                # Check that the scale and zero points are valid.\n                if is_qnn_params_valid:\n                    qnn_params = dict()\n                    qnn_params[\"scale\"] = relay.const(scale, \"float32\")\n                    qnn_params[\"zero_point\"] = relay.const(zero_point, \"int32\")\n            return_list.append(TensorWrapper(tensor_idx, tensor, buffer, qnn_params))\n        return return_list\n\n    def get_tensor_type_as_numpy(self, tensor_wrapper):\n        \"\"\"Returns np.dtype out of TensorType\"\"\"\n        assert isinstance(tensor_wrapper, TensorWrapper)\n\n        try:\n            from tflite.TensorType import TensorType\n\n            return {\n                TensorType.UINT8: np.uint8,\n                TensorType.INT8: np.int8,\n                TensorType.INT16: np.int16,\n                TensorType.FLOAT16: np.float16,\n                TensorType.FLOAT32: np.float32,\n                TensorType.INT32: np.int32,\n                TensorType.INT64: np.int64,\n                TensorType.BOOL: np.bool_,\n            }[tensor_wrapper.tensor.Type()]\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n        except KeyError:\n            raise NotImplementedError(\n                \"Tensor type '{}' currently not supported\".format(tensor_wrapper.tensor.Type())\n            )\n\n    # pylint: disable=no-else-return\n    def get_tensor_value(self, tensor_wrapper, is_sparse=False):\n        \"\"\"Get tensor buffer value from given tensor wrapper\"\"\"\n        assert isinstance(tensor_wrapper, TensorWrapper)\n\n        dtype = self.get_tensor_type_as_numpy(tensor_wrapper)\n        data = tensor_wrapper.buffer.DataAsNumpy()\n\n        if tensor_wrapper.tensor.ShapeLength() != 0:\n            shape = to_int_list(self.get_tensor_shape(tensor_wrapper))\n        else:\n            shape = []\n\n        if is_sparse:\n            return np.frombuffer(data, dtype=dtype)\n        else:\n            return np.frombuffer(data, dtype=dtype).reshape(shape)\n\n    def get_tensor_type_str(self, tensor_type):\n        \"\"\"Get tensor type string representation when given TFLite tensor type\"\"\"\n        try:\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        if tensor_type == TensorType.INT8:\n            return \"int8\"\n        if tensor_type == TensorType.INT16:\n            return \"int16\"\n        if tensor_type == TensorType.UINT8:\n            return \"uint8\"\n        if tensor_type == TensorType.FLOAT16:\n            return \"float16\"\n        if tensor_type == TensorType.FLOAT32:\n            return \"float32\"\n        if tensor_type == TensorType.INT32:\n            return \"int32\"\n        if tensor_type == TensorType.INT64:\n            return \"int64\"\n        if tensor_type == TensorType.BOOL:\n            return \"bool\"\n        raise NotImplementedError(\n            \"Tensor type {} is currently not supported\".format(str(tensor_type))\n        )\n\n    def has_same_qnn_params(self, lhs_tensor, rhs_tensor):\n        lhs_scale = lhs_tensor.qnn_params[\"scale\"]\n        rhs_scale = rhs_tensor.qnn_params[\"scale\"]\n        lhs_zero_point = lhs_tensor.qnn_params[\"zero_point\"]\n        rhs_zero_point = rhs_tensor.qnn_params[\"zero_point\"]\n        # 0.1 + 0.2 != 0.3\n        return np.allclose(\n            lhs_scale.data.numpy(), rhs_scale.data.numpy(), rtol=1e-5, atol=1e-5\n        ) and np.allclose(\n            lhs_zero_point.data.numpy(), rhs_zero_point.data.numpy(), rtol=1e-5, atol=1e-5\n        )\n\n    def is_quantized(self, op):\n        \"\"\"Check if an input tensor is quantized.\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        first_tensor = input_tensors[0]\n        return first_tensor.qnn_params is not None\n\n    def quantize(self, expr, tensor_to_quantize):\n        \"\"\"Helper function to quantize a tensor with Relay\"\"\"\n        tensor_type = tensor_to_quantize.tensor.Type()\n        tensor_type_str = self.get_tensor_type_str(tensor_type)\n        quantized = _qnn.op.quantize(\n            data=expr,\n            output_scale=tensor_to_quantize.qnn_params[\"scale\"],\n            output_zero_point=tensor_to_quantize.qnn_params[\"zero_point\"],\n            out_dtype=tensor_type_str,\n        )\n        return quantized\n\n    def dequantize(self, expr, tensor):\n        \"\"\"Helper function to dequantize a tensor with Relay\"\"\"\n        dequantized = _qnn.op.dequantize(\n            data=expr,\n            input_scale=tensor.qnn_params[\"scale\"],\n            input_zero_point=tensor.qnn_params[\"zero_point\"],\n        )\n        return dequantized\n\n    def convert_qnn_fused_activation_function(\n        self, expr, fused_activation_fn, scale, zero_point, dtype\n    ):\n        \"\"\"Convert TFLite fused activation function. The expr is an input quantized tensor with\n        scale and zero point\"\"\"\n        try:\n            from tflite.ActivationFunctionType import ActivationFunctionType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        # Quantize a float value to an quantized integer value\n        quantize = lambda x: float(int(round(x / scale)) + zero_point)\n\n        # Get min/max of the output dtype. This will be used to ensure that clip a_min/a_max are not\n        # beyond the dtype range.\n        qmin = float(tvm.tir.op.min_value(dtype).value)\n        qmax = float(tvm.tir.op.max_value(dtype).value)\n\n        # The input expr is a quantized tensor with its scale and zero point. We calculate the\n        # suitable clip off points based on these scale and zero point.\n        if fused_activation_fn == ActivationFunctionType.NONE:\n            return expr\n        if fused_activation_fn == ActivationFunctionType.RELU6:\n            return _op.clip(expr, a_min=max(qmin, quantize(0)), a_max=min(qmax, quantize(6.0)))\n        if fused_activation_fn == ActivationFunctionType.RELU_N1_TO_1:\n            return _op.clip(expr, a_min=max(qmin, quantize(-1.0)), a_max=min(qmax, quantize(1.0)))\n        if fused_activation_fn == ActivationFunctionType.RELU:\n            return _op.clip(expr, a_min=max(qmin, quantize(0.0)), a_max=qmax)\n\n        fused_activation_fn_str = self.activation_fn_type[fused_activation_fn]\n        raise tvm.error.OpNotImplemented(\n            \"Quantized activation {} is not supported yet.\".format(fused_activation_fn_str)\n        )\n\n    def convert_conv2d(self, op):\n        \"\"\"Convert TFLite conv2d\"\"\"\n        return self.convert_conv(op, \"conv2d\")\n\n    def convert_depthwise_conv2d(self, op):\n        \"\"\"Convert TFLite depthwise conv2d\"\"\"\n        return self.convert_conv(op, \"depthwise\")\n\n    def convert_average_pool2d(self, op):\n        \"\"\"Convert TFLite average pool2d\"\"\"\n        return self.convert_pool2d(op, \"average\")\n\n    def convert_max_pool2d(self, op):\n        \"\"\"Convert TFLite max pool2d\"\"\"\n        return self.convert_pool2d(op, \"max\")\n\n    def convert_l2_pool2d(self, op):\n        \"\"\"Convert TFLite l2 pool2d\"\"\"\n        return self.convert_pool2d(op, \"l2\")\n\n    def convert_reshape(self, op):\n        \"\"\"Convert TFLite reshape\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ReshapeOptions import ReshapeOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) in (1, 2), \"input tensors should not be empty\"\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"There should be only 1 output tensor\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        if len(input_tensors) == 2:\n            shape_tensor = input_tensors[1]\n            if self.has_expr(shape_tensor.tensor_idx):\n                target_expr = self.get_expr(shape_tensor.tensor_idx)\n                target_value, success = try_infer_value(\n                    target_expr,\n                    parameters={k: _nd.array(np.array(v)) for k, v in self.exp_tab.params.items()},\n                )\n                if success:\n                    # convert to flattened list\n                    from itertools import chain\n\n                    try:\n                        target_shape = list(chain(*target_value))\n                    except TypeError:\n                        target_shape = list(chain(target_value))\n                else:\n                    target_shape = target_expr\n            else:\n                target_shape = self.get_tensor_value(shape_tensor)\n                # convert to flattened list\n                from itertools import chain\n\n                try:\n                    target_shape = list(chain(*target_shape))\n                except TypeError:\n                    target_shape = list(chain(target_shape))\n\n        else:\n            assert op.BuiltinOptionsType() == BuiltinOptions.ReshapeOptions\n            op_options = op.BuiltinOptions()\n            reshape_options = ReshapeOptions()\n            reshape_options.Init(op_options.Bytes, op_options.Pos)\n            target_shape = to_int_list(reshape_options.NewShapeAsNumpy())\n\n        in_expr = self.get_expr(input_tensor_idx)\n\n        # If the tensors are quantized, ensure that input/output qnn params are same.\n\n        input_tensor_type_str = self.get_tensor_type_str(input_tensor.tensor.Type())\n        if input_tensor.qnn_params and input_tensor_type_str == \"int8\":\n            # TFLite 2.x quantization spec requires qnn params to be same and dtype to be int8.\n            # For TFLite 1.x, dtype can be uint8 and qnn params can be different\n            output_tensor = output_tensors[0]\n            assert self.has_same_qnn_params(\n                input_tensor, output_tensor\n            ), \"TFLite reshape requires input and output scale and zero points to be equal\"\n\n        out = _op.reshape(in_expr, newshape=target_shape)\n        if input_tensor.qnn_params and input_tensor_type_str == \"uint8\":\n            output_tensor = output_tensors[0]\n            if not self.has_same_qnn_params(input_tensor, output_tensor):\n                output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n                out = _qnn.op.requantize(\n                    out,\n                    input_scale=input_tensor.qnn_params[\"scale\"],\n                    input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                    output_scale=output_tensor.qnn_params[\"scale\"],\n                    output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                    out_dtype=output_tensor_type_str,\n                )\n\n        return out\n\n    def _convert_resize(self, method, op):\n        \"\"\"Generic method to Convert TFLite RESIZE operators\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ResizeBilinearOptions import ResizeBilinearOptions\n\n            # ResizeNearestNeighborOptions was added in tflite v1.13\n            tflite_ver = 1120\n            if \"ResizeNearestNeighborOptions\" in dir(BuiltinOptions):\n                from tflite.ResizeNearestNeighborOptions import ResizeNearestNeighborOptions\n\n                tflite_ver = 1130\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        # images, 4-D Tensor with shape NHWC.\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        # size - 1-D int32 Tensor of 2 elements: new_height, new_width\n        target_size = tuple(self.get_tensor_value(input_tensors[1]))\n\n        # Options - align_corners (bool)\n        resize_options = None\n        align_corners = False\n        bilinear_method = method == \"linear\"\n        if bilinear_method:\n            assert op.BuiltinOptionsType() == BuiltinOptions.ResizeBilinearOptions\n            resize_options = ResizeBilinearOptions()\n        elif tflite_ver >= 1130:\n            assert op.BuiltinOptionsType() == BuiltinOptions.ResizeNearestNeighborOptions\n            resize_options = ResizeNearestNeighborOptions()\n\n        if resize_options is not None:\n            op_options = op.BuiltinOptions()\n            resize_options.Init(op_options.Bytes, op_options.Pos)\n            align_corners = resize_options.AlignCorners()\n            half_pixel_centers = resize_options.HalfPixelCenters()\n\n        # Use layout NHWC\n        coord_trans = \"align_corners\" if align_corners else \"asymmetric\"\n        coord_trans = \"half_pixel\" if half_pixel_centers else coord_trans\n\n        rounding_method = \"\"\n        if method == \"nearest_neighbor\":\n            if not align_corners and half_pixel_centers:\n                rounding_method = \"round_prefer_ceil\"\n\n        if bilinear_method and input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = _op.image.resize2d(\n            in_expr, target_size, None, \"NHWC\", method, coord_trans, rounding_method\n        )\n        if bilinear_method and output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n        return out\n\n    def convert_resize_bilinear(self, op):\n        \"\"\"Convert TFLite RESIZE_BILINEAR\"\"\"\n        return self._convert_resize(\"linear\", op)\n\n    def convert_resize_nearest_neighbor(self, op):\n        \"\"\"Convert TFLite RESIZE_NEAREST_NEIGHBOR\"\"\"\n        return self._convert_resize(\"nearest_neighbor\", op)\n\n    def convert_l2_normalization(self, op):\n        \"\"\"Convert TFLite L2_NORMALIZATION\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.L2NormOptions import L2NormOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.L2NormOptions\n        op_options = op.BuiltinOptions()\n        l2_norm_options = L2NormOptions()\n        l2_norm_options.Init(op_options.Bytes, op_options.Pos)\n        fused_activation_fn = l2_norm_options.FusedActivationFunction()\n\n        # TFLite supports normalization only over the last dim\n        input_tensor_rank = len(input_tensor.tensor.ShapeAsNumpy())\n\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFLite quantized L2_NORMALIZATION operator is not supported yet.\"\n            )\n\n        # TFL uses only the default epsilon value\n        out = _op.nn.l2_normalize(in_expr, eps=1e-12, axis=[input_tensor_rank - 1])\n\n        # if we have fused activation fn\n        if output_tensor.qnn_params:\n            raise tvm.error.OpNotImplemented(\n                \"TFLite quantized L2_NORMALIZATION operator is not supported yet.\"\n            )\n        out = self.convert_fused_activation_function(out, fused_activation_fn)\n\n        return out\n\n    def convert_lrn(self, op):\n        \"\"\"Convert TFLite LOCAL_RESPONSE_NORMALIZATION\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.LocalResponseNormalizationOptions import LocalResponseNormalizationOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\"TFlite quantized LRN operator is not supported yet.\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.LocalResponseNormalizationOptions\n        op_options = op.BuiltinOptions()\n        lrn_options = LocalResponseNormalizationOptions()\n        lrn_options.Init(op_options.Bytes, op_options.Pos)\n        radius = lrn_options.Radius()\n        bias = lrn_options.Bias()\n        alpha = lrn_options.Alpha()\n        beta = lrn_options.Beta()\n        size = (radius * 2) + 1\n        alpha = alpha * size\n        axis = 3  # NHWC format\n        out = _op.nn.lrn(in_expr, size=size, axis=axis, bias=bias, alpha=alpha, beta=beta)\n\n        return out\n\n    def convert_logistic(self, op):\n        \"\"\"Convert TFLite LOGISTIC\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = _op.sigmoid(in_expr)\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n\n        return out\n\n    def convert_softmax(self, op):\n        \"\"\"Convert TFLite softmax\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        params = {\"axis\": -1}  # -1 is channel\n        in_expr = self.get_expr(input_tensor_idx)\n\n        # TODO - Naive softmax int8 implementation leads to bad accuracy. Currently, we can\n        # dequantize to FP32 and perform softmax on FP32. We can investigate an integer only softmax\n        # implementation in future.\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n\n        out = _op.nn.softmax(in_expr, **params)\n\n        # Go back to integer dataype if the original operator was quantized.\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n\n        return out\n\n    def convert_tanh(self, op):\n        \"\"\"Convert TFLite TANH\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = _op.tanh(in_expr)\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n        return out\n\n    def convert_range(self, op):\n        \"\"\"Convert TFLite Range\"\"\"\n        try:\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 3, \"input tensors length should be 3\"\n\n        start, limit, delta = input_tensors[0], input_tensors[1], input_tensors[2]\n\n        expressions = [self.get_tensor_expr(t) for t in [start, limit, delta]]\n\n        # out type inference\n        if delta.tensor.Type() == TensorType.FLOAT32:\n            out_type = self.get_tensor_type_str(delta.tensor.Type())\n        else:\n            out_type = self.get_tensor_type_str(start.tensor.Type())\n\n        out = _op.arange(expressions[0], expressions[1], expressions[2], out_type)\n\n        return out\n\n    def convert_shape(self, op):\n        \"\"\"Convert TFLite Shape\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ShapeOptions import ShapeOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.ShapeOptions\n        op_options = op.BuiltinOptions()\n        shape_options = ShapeOptions()\n        shape_options.Init(op_options.Bytes, op_options.Pos)\n\n        out_type = self.get_tensor_type_str(shape_options.OutType())\n        out = shape_of(self.get_tensor_expr(input_tensors[0]), dtype=out_type)\n\n        return out\n\n    def convert_relu(self, op):\n        \"\"\"Convert TFLite ReLU\"\"\"\n        try:\n            from tflite.ActivationFunctionType import ActivationFunctionType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            # Quantize a float value to an quantized integer value\n            scale_val = get_scalar_from_constant(input_tensor.qnn_params[\"scale\"])\n            zero_point_val = get_scalar_from_constant(input_tensor.qnn_params[\"zero_point\"])\n\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = self.convert_qnn_fused_activation_function(\n                expr=in_expr,\n                fused_activation_fn=ActivationFunctionType.RELU,\n                scale=scale_val,\n                zero_point=zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n        else:\n            out = _op.nn.relu(in_expr)\n\n        if output_tensor.qnn_params:\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = _qnn.op.requantize(\n                out,\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n\n        return out\n\n    def convert_hard_swish(self, op):\n        \"\"\"Convert TFLite Hard swish\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        def _relu6(data):\n            return _op.tensor.clip(data, 0.0, 6.0)\n\n        def _hard_swish(data):\n            return data * _relu6(data + relay.const(3.0)) / relay.const(6.0)\n\n        # Dequantize if the input is quantized.\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n\n        # Perform hardswish\n        out = _hard_swish(in_expr)\n\n        # Go back to integer dataype if the original operator was quantized.\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n\n        return out\n\n    def convert_relu6(self, op):\n        \"\"\"Convert TFLite ReLU6\"\"\"\n        try:\n            from tflite.ActivationFunctionType import ActivationFunctionType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            # Quantize a float value to an quantized integer value\n            scale_val = get_scalar_from_constant(input_tensor.qnn_params[\"scale\"])\n            zero_point_val = get_scalar_from_constant(input_tensor.qnn_params[\"zero_point\"])\n\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = self.convert_qnn_fused_activation_function(\n                expr=in_expr,\n                fused_activation_fn=ActivationFunctionType.RELU6,\n                scale=scale_val,\n                zero_point=zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n        else:\n            out = _op.clip(in_expr, a_min=0, a_max=6)\n\n        if output_tensor.qnn_params:\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = _qnn.op.requantize(\n                out,\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n\n        return out\n\n    def convert_leaky_relu(self, op):\n        \"\"\"Convert TFLite LEAKY_RELU\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.LeakyReluOptions import LeakyReluOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.LeakyReluOptions\n        op_options = op.BuiltinOptions()\n        leaky_relu_options = LeakyReluOptions()\n        leaky_relu_options.Init(op_options.Bytes, op_options.Pos)\n        alpha_tensor = leaky_relu_options.Alpha()\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = _op.nn.leaky_relu(in_expr, alpha_tensor)\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n\n        return out\n\n    def convert_relu_n1_to_1(self, op):\n        \"\"\"Convert TFLite RELU_N1_TO_1\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            # Quantize a float value to an quantized integer value\n            scale_val = get_scalar_from_constant(input_tensor.qnn_params[\"scale\"])\n            zero_point_val = get_scalar_from_constant(input_tensor.qnn_params[\"zero_point\"])\n            quantize = lambda x: float(int(round(x / scale_val)) + zero_point_val)\n\n            # Get min/max of the input dtype. This will be used to ensure that\n            # clip a_min/a_max are not beyond the dtype range.\n            input_tensor_type_str = self.get_tensor_type_str(input_tensor.tensor.Type())\n            qmin = float(tvm.tir.op.min_value(input_tensor_type_str).value)\n            qmax = float(tvm.tir.op.max_value(input_tensor_type_str).value)\n\n            out = _op.clip(in_expr, a_min=max(qmin, quantize(-1.0)), a_max=min(qmax, quantize(1.0)))\n        else:\n            out = _op.clip(in_expr, a_min=-1, a_max=1)\n\n        if output_tensor.qnn_params:\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = _qnn.op.requantize(\n                out,\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n\n        return out\n\n    def convert_log_softmax(self, op):\n        \"\"\"Convert TFLite LOG_SOFTMAX\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = _op.nn.log_softmax(in_expr)\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n\n        return out\n\n    def convert_concatenation(self, op):\n        \"\"\"Convert TFLite concatenation\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ConcatenationOptions import ConcatenationOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) >= 1, \"input tensors should greater than 1\"\n        in_exprs = [self.get_tensor_expr(_) for _ in input_tensors]\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.ConcatenationOptions\n        op_options = op.BuiltinOptions()\n        concatenation_options = ConcatenationOptions()\n        concatenation_options.Init(op_options.Bytes, op_options.Pos)\n        concatenation_axis = concatenation_options.Axis()\n        fused_activation_fn = concatenation_options.FusedActivationFunction()\n\n        if not input_tensors[0].qnn_params:\n            out = _op.concatenate(in_exprs, axis=concatenation_axis)\n        else:\n            input_scales = [input_tensor.qnn_params[\"scale\"] for input_tensor in input_tensors]\n            input_zero_points = [\n                input_tensor.qnn_params[\"zero_point\"] for input_tensor in input_tensors\n            ]\n            out = _qnn.op.concatenate(\n                in_exprs,\n                input_scales=input_scales,\n                input_zero_points=input_zero_points,\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                axis=concatenation_axis,\n            )\n\n        # Handle fused activations\n        if output_tensor.qnn_params:\n            scale_val = get_scalar_from_constant(output_tensor.qnn_params[\"scale\"])\n            zero_point_val = get_scalar_from_constant(output_tensor.qnn_params[\"zero_point\"])\n            output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n            out = self.convert_qnn_fused_activation_function(\n                expr=out,\n                fused_activation_fn=fused_activation_fn,\n                scale=scale_val,\n                zero_point=zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n        else:\n            out = self.convert_fused_activation_function(out, fused_activation_fn)\n\n        return out\n\n    def _convert_unary_elemwise(self, relay_op, op):\n        \"\"\"Generic method to convert TFLite unary elemwise functions\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if input_tensor.qnn_params:\n            in_expr = self.dequantize(in_expr, input_tensor)\n        out = relay_op(in_expr)\n        if output_tensor.qnn_params:\n            out = self.quantize(out, output_tensor)\n        return out\n\n    def convert_abs(self, op):\n        \"\"\"Convert TFLite ABS\"\"\"\n        return self._convert_unary_elemwise(_op.abs, op)\n\n    def convert_ceil(self, op):\n        \"\"\"Convert TFLite CEIL\"\"\"\n        return self._convert_unary_elemwise(_op.ceil, op)\n\n    def convert_floor(self, op):\n        \"\"\"Convert TFLite FLOOR\"\"\"\n        return self._convert_unary_elemwise(_op.floor, op)\n\n    def convert_round(self, op):\n        \"\"\"Convert TFLite ROUND\"\"\"\n        return self._convert_unary_elemwise(_op.round, op)\n\n    def convert_exp(self, op):\n        \"\"\"Convert TFLite EXP\"\"\"\n        return self._convert_unary_elemwise(_op.exp, op)\n\n    def convert_log(self, op):\n        \"\"\"Convert TFLite LOG\"\"\"\n        return self._convert_unary_elemwise(_op.log, op)\n\n    def convert_sin(self, op):\n        \"\"\"Convert TFLite SIN\"\"\"\n        return self._convert_unary_elemwise(_op.sin, op)\n\n    def convert_tan(self, op):\n        \"\"\"Convert TFLite TAN\"\"\"\n        return self._convert_unary_elemwise(_op.tan, op)\n\n    def convert_cos(self, op):\n        \"\"\"Convert TFLite COS\"\"\"\n        return self._convert_unary_elemwise(_op.cos, op)\n\n    def convert_sqrt(self, op):\n        \"\"\"Convert TFLite SQRT\"\"\"\n        return self._convert_unary_elemwise(_op.sqrt, op)\n\n    def convert_rsqrt(self, op):\n        \"\"\"Convert TFLite RSQRT\"\"\"\n        return self._convert_unary_elemwise(_op.rsqrt, op)\n\n    def convert_neg(self, op):\n        \"\"\"Convert TFLite NEG\"\"\"\n        return self._convert_unary_elemwise(_op.negative, op)\n\n    def convert_elu(self, op):\n        \"\"\"Convert TFLite ELU\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\"TFlite quantized ELU operator is not supported yet.\")\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n        exp_type = self.get_tensor_type_str(input_tensor.tensor.Type())\n        out = relay.const(-1.0, exp_type) * _op.nn.relu(\n            relay.const(1.0, exp_type) - _op.exp(in_expr)\n        ) + _op.nn.relu(in_expr)\n\n        return out\n\n    def convert_square(self, op):\n        \"\"\"Convert TFLite SQUARE\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized SQUARE operator is not supported yet.\"\n            )\n\n        exp_type = self.get_tensor_type_str(output_tensor.tensor.Type())\n        out = _op.power(in_expr, relay.const(2, exp_type))\n\n        return out\n\n    def _convert_elemwise(\n        self,\n        relay_op,\n        op,\n        ignore_qnn_params=False,\n        comparison_op=False,\n    ):\n        \"\"\"Generic method to Convert TFLite elemwise\"\"\"\n        try:\n            from tflite.AddOptions import AddOptions\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.DivOptions import DivOptions\n            from tflite.MulOptions import MulOptions\n            from tflite.SubOptions import SubOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        lhs_tensor = input_tensors[0]\n        rhs_tensor = input_tensors[1]\n        lhs_expr = self.get_tensor_expr(lhs_tensor)\n        rhs_expr = self.get_tensor_expr(rhs_tensor)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        # TFLite format demands equal scale and zero_point tuple parameters for some operations\n        # to allow us to use non-quantized operation instead of quantized if ignore_qnn_params=True\n        if ignore_qnn_params and not comparison_op:\n            assert (\n                lhs_tensor.qnn_params\n                and self.has_same_qnn_params(lhs_tensor, output_tensor)\n                and self.has_same_qnn_params(rhs_tensor, output_tensor)\n            ), \"All tensors should be quantized with the same (scale,zero-point) tuple parameters\"\n\n        # If quantized, extracts qnn params and call QNN add operator.\n        if not ignore_qnn_params and lhs_tensor.qnn_params:\n            assert rhs_tensor.qnn_params, \"Both tensors should be quantized.\"\n            assert output_tensor.qnn_params, \"Output tensor should be quantized.\"\n            out = relay_op(\n                lhs=lhs_expr,\n                rhs=rhs_expr,\n                lhs_scale=lhs_tensor.qnn_params[\"scale\"],\n                lhs_zero_point=lhs_tensor.qnn_params[\"zero_point\"],\n                rhs_scale=rhs_tensor.qnn_params[\"scale\"],\n                rhs_zero_point=rhs_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n            )\n        else:\n            out = relay_op(lhs_expr, rhs_expr)\n\n        # Options (fused_activation_function)\n        options = None\n        if op.BuiltinOptionsType() == BuiltinOptions.AddOptions:\n            options = AddOptions()\n        elif op.BuiltinOptionsType() == BuiltinOptions.SubOptions:\n            options = SubOptions()\n        elif op.BuiltinOptionsType() == BuiltinOptions.MulOptions:\n            options = MulOptions()\n        elif op.BuiltinOptionsType() == BuiltinOptions.DivOptions:\n            options = DivOptions()\n\n        if options is not None:\n            op_options = op.BuiltinOptions()\n            options.Init(op_options.Bytes, op_options.Pos)\n            fused_activation_fn = options.FusedActivationFunction()\n\n            # Handle fused activations\n            if not ignore_qnn_params and output_tensor.qnn_params:\n                scale_val = get_scalar_from_constant(output_tensor.qnn_params[\"scale\"])\n                zero_point_val = get_scalar_from_constant(output_tensor.qnn_params[\"zero_point\"])\n                output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n                out = self.convert_qnn_fused_activation_function(\n                    expr=out,\n                    fused_activation_fn=fused_activation_fn,\n                    scale=scale_val,\n                    zero_point=zero_point_val,\n                    dtype=output_tensor_type_str,\n                )\n            else:\n                out = self.convert_fused_activation_function(out, fused_activation_fn)\n        return out\n\n    def convert_add(self, op):\n        \"\"\"Convert TFLite ADD\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            return self._convert_elemwise(_qnn.op.add, op)\n        return self._convert_elemwise(_op.add, op)\n\n    def convert_add_n(self, op):\n        \"\"\"Convert TFLite ADD_N\"\"\"\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n\n        input_tensors = self.get_input_tensors(op)\n        assert not input_tensors[0].qnn_params, \"TFLite does not support quantized ADD_N.\"\n        lhs_expr = self.get_tensor_expr(input_tensors[0])\n        for rhs_tensor in input_tensors[1:]:\n            assert not rhs_tensor.qnn_params, \"TFLite does not support quantized ADD_N\"\n            rhs_expr = self.get_tensor_expr(rhs_tensor)\n            lhs_expr = _op.add(lhs_expr, rhs_expr)\n        return lhs_expr\n\n    def convert_sub(self, op):\n        \"\"\"Convert TFLite SUB\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            return self._convert_elemwise(_qnn.op.subtract, op)\n        return self._convert_elemwise(_op.subtract, op)\n\n    def convert_mul(self, op):\n        \"\"\"Convert TFLite MUL\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            return self._convert_elemwise(_qnn.op.mul, op)\n        return self._convert_elemwise(_op.multiply, op)\n\n    def convert_div(self, op):\n        \"\"\"Convert TFLite DIV\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\"TFlite quantized DIV operator is not supported yet.\")\n        return self._convert_elemwise(_op.divide, op)\n\n    def convert_pow(self, op):\n        \"\"\"Convert TFLite POW\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\"TFlite quantized POW operator is not supported yet.\")\n        return self._convert_elemwise(_op.power, op)\n\n    def convert_maximum(self, op):\n        \"\"\"Convert TFLite MAXIMUM\"\"\"\n        return self._convert_elemwise(_op.maximum, op, self.is_quantized(op))\n\n    def convert_minimum(self, op):\n        \"\"\"Convert TFLite MINIMUM\"\"\"\n        return self._convert_elemwise(_op.minimum, op, self.is_quantized(op))\n\n    def convert_greater(self, op):\n        \"\"\"Convert TFLite GREATER\"\"\"\n        return self._convert_elemwise(_op.greater, op, self.is_quantized(op), comparison_op=True)\n\n    def convert_squared_difference(self, op):\n        \"\"\"Convert TFLite SQUARED DIFFERENCE\"\"\"\n        # Check if the input tensor is quantized, call QNN op\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized squared difference operator is not supported yet.\"\n            )\n        difference = self._convert_elemwise(_op.subtract, op)\n        # _convert_elemwise has guaranteed only have one output tensor\n        exp_type = self.get_tensor_type_str(self.get_output_tensors(op)[0].tensor.Type())\n        out = _op.power(difference, relay.const(2, exp_type))\n        return out\n\n    def convert_greater_equal(self, op):\n        \"\"\"Convert TFLite GREATER_EQUAL\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized GREATER_EQUAL operator is not supported yet.\"\n            )\n        return self._convert_elemwise(_op.greater_equal, op)\n\n    def convert_less(self, op):\n        \"\"\"Convert TFLite LESS\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\"TFlite quantized LESS operator is not supported yet.\")\n        return self._convert_elemwise(_op.less, op)\n\n    def convert_less_equal(self, op):\n        \"\"\"Convert TFLite LESS_EQUAL\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized LESS_EQUAL operator is not supported yet.\"\n            )\n        return self._convert_elemwise(_op.less_equal, op)\n\n    def convert_equal(self, op):\n        \"\"\"Convert TFLite EQUAL\"\"\"\n        return self._convert_elemwise(_op.equal, op, self.is_quantized(op), comparison_op=True)\n\n    def convert_not_equal(self, op):\n        \"\"\"Convert TFLite NOT_EQUAL\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized NOT_EQUAL operator is not supported yet.\"\n            )\n        return self._convert_elemwise(_op.not_equal, op)\n\n    def _convert_logical_binary(self, relay_op, op):\n        \"\"\"Generic method to convert logical binary ops\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        lhs_tensor = input_tensors[0]\n        lhs_expr = self.get_tensor_expr(lhs_tensor)\n        rhs_tensor = input_tensors[1]\n        rhs_expr = self.get_tensor_expr(rhs_tensor)\n        out = relay_op(lhs_expr, rhs_expr)\n\n        return out\n\n    def convert_logical_and(self, op):\n        \"\"\"Convert tflite LOGICAL_AND\"\"\"\n        return self._convert_logical_binary(_op.logical_and, op)\n\n    def convert_logical_or(self, op):\n        \"\"\"Convert tflite LOGICAL_OR\"\"\"\n        return self._convert_logical_binary(_op.logical_or, op)\n\n    def convert_logical_not(self, op):\n        \"\"\"Convert tflite LOGICAL_NOT\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        data = self.get_expr(input_tensors[0].tensor_idx)\n        out = _op.logical_not(data)\n\n        return out\n\n    def convert_gather(self, op):\n        \"\"\"Method to Convert TFLite GATHER operator\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.GatherOptions import GatherOptions\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        data = self.get_tensor_expr(input_tensors[0])\n        indices = input_tensors[1]\n        indices_type = indices.tensor.Type()\n        assert indices_type in (TensorType.INT32, TensorType.INT64)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.GatherOptions\n        op_options = op.BuiltinOptions()\n        gather_options = GatherOptions()\n        gather_options.Init(op_options.Bytes, op_options.Pos)\n        axis = gather_options.Axis()\n\n        # Check the indices are with in bounds.\n        data_shape = to_int_list(self.get_tensor_shape(input_tensors[0]))\n        data_dim = len(data_shape)\n\n        axis = data_dim + axis if axis < 0 else axis\n        assert axis >= 0, \"Axis out of bounds\"\n        assert axis < data_dim, \"Axis out of bounds\"\n\n        if self.has_expr(indices.tensor_idx):\n            indices_expr = self.get_expr(indices.tensor_idx)\n        else:\n            indices_val = self.get_tensor_value(indices)\n            indices_expr = self.exp_tab.new_const(\n                indices_val, dtype=self.get_tensor_type_str(indices_type)\n            )\n            indices_shape = list(indices_val.shape)\n            indices_len = len(indices_shape)\n\n            out_shape = data_shape[:axis] + indices_shape[:] + data_shape[axis + 1 :]\n\n            loopover = [range(s) for s in out_shape]\n            for idx in list(itertools.product(*loopover)):\n                real_indices = (\n                    list(idx[:axis])\n                    + [indices_val[idx[axis : axis + indices_len]]]\n                    + list(idx[axis + indices_len :])\n                )\n                if np.any(np.subtract(data_shape, real_indices) < 0):\n                    raise ValueError(\"TFLite out of bound indices are not supported.\")\n\n        # Use mode 'fast' since indices are already checked within bounds.\n        out = _op.take(data, indices_expr, axis=axis, mode=\"fast\")\n        return out\n\n    def convert_gather_nd(self, op):\n        \"\"\"Method to Convert TFLite GATHER_ND operator\"\"\"\n        try:\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        for t in input_tensors:\n            assert not t.qnn_params, \"Quantized input is not expected.\"\n\n        data = self.get_tensor_expr(input_tensors[0])\n        indices = self.get_tensor_expr(input_tensors[1])\n\n        indices_type = input_tensors[1].tensor.Type()\n        assert indices_type in (TensorType.INT32, TensorType.INT64)\n\n        indices_dims = len(_infer_shape(indices))\n        indices_t = _op.transpose(indices, axes=[-1] + list(range(indices_dims - 1)))\n\n        out = _op.gather_nd(data, indices_t)\n        return out\n\n    def convert_strided_slice(self, op):\n        \"\"\"Method to Convert TFLite STRIDED_SLICE operator.\n        NOTE: Eventhough tensorflow supports begin_mask, end_mask, ellipsis_mask, new_axis_mask\n        and shrink_axis_mask, tflite doesn't support these and expect these values to be zero.\n        But in future, they may open up the mask implementation, so kept the implementation\n        same as tensorflow.\n\n        This op extracts a slice of size (end - begin) / stride from the given input tensor.\n        Starting at the location specified by begin the slice continues by adding stride to the\n        index until all dimensions are not less than end. Note that a stride can be negative,\n        which causes a reverse slice.\n\n        For slice input[val0, val1, ..., valn], begin/end/strides will be vectors of length n.\n\n        In each mask field(begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask)\n        the ith bit will correspond to the ith val.\n\n        If the ith bit of begin_mask is set, begin[i] is ignored and the fullest possible range\n        in that dimension is used instead.\n\n        If the ith bit of ellipsis_mask is set, as many unspecified dimensions as needed will be\n        inserted between other dimensions. Only one non-zero bit is allowed in ellipsis_mask.\n\n        If the ith bit of new_axis_mask is set, then begin, end, and stride are ignored and a\n        new length 1 dimension is added at this point in the output tensor.\n\n        If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks\n        the dimensionality by 1, taking on the value at index begin[i]. end[i] and strides[i]\n        are ignored in this case.\n        begin and end are zero-indexed. strides entries must be non-zero.\n\n        TVM Relay implementation of doesn't support mask, so the mask values are processed in\n        this function and begin/end/strides are updated accordingly. If any mask is present, and\n        since tvm doesn't support mask computation directly, the output need a final reshape.\n        \"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.StridedSliceOptions import StridedSliceOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 4, \"input tensors length should be 4\"\n\n        data_expr = self.get_expr(input_tensors[0].tensor_idx)\n\n        begin = list(self.get_tensor_value(input_tensors[1]))\n        end = list(self.get_tensor_value(input_tensors[2]))\n        stride = list(self.get_tensor_value(input_tensors[3]))\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.StridedSliceOptions\n        op_options = op.BuiltinOptions()\n        options = StridedSliceOptions()\n        options.Init(op_options.Bytes, op_options.Pos)\n        begin_mask = options.BeginMask()\n        end_mask = options.EndMask()\n        ellipsis_mask = options.EllipsisMask()\n        new_axis_mask = options.NewAxisMask()\n        shrink_axis_mask = options.ShrinkAxisMask()\n\n        data_shape = to_int_list(self.get_tensor_shape(input_tensors[0]))\n        data_dim = len(data_shape)\n        stride_dim = len(stride)\n\n        def _transform_mask(stride_dim, ellipsis_mask):\n            \"\"\"Handle mask inputs to create new begin, end, stride and output shape\"\"\"\n            m_begin = [0] * data_dim\n            m_end = [0] * data_dim\n            m_stride = [0] * data_dim\n            fshape_indices = []\n            # Count new axis after ellipsis_mask, consider while applying ellipsis_mask.\n            ellipsis_seen = False\n            new_axes_after_ellipsis = 0\n            for i in range(stride_dim):\n                mask = 1 << i\n                if ellipsis_seen and (mask & new_axis_mask) != 0:\n                    new_axes_after_ellipsis += 1\n                if (mask & ellipsis_mask) != 0:\n                    ellipsis_seen = True\n            if not ellipsis_seen:\n                # Used later for extending the stride attributes in the below loop.\n                ellipsis_mask |= 1 << stride_dim\n                stride_dim += 1\n            final_index = 0\n            for index in range(stride_dim):\n                mask = 1 << index\n                if mask & ellipsis_mask:\n                    # Identify the end index for applying ellipsis_mask\n                    to_index = min(\n                        ((data_dim - (stride_dim - index)) + 1 + new_axes_after_ellipsis), data_dim\n                    )\n                    for i in range(final_index, to_index):\n                        m_begin[final_index] = 0\n                        m_end[final_index] = data_shape[final_index]\n                        m_stride[final_index] = 1\n                        fshape_indices.append(final_index)\n                        final_index += 1\n                elif mask & new_axis_mask:\n                    fshape_indices.append(-1)\n                elif not mask & new_axis_mask:\n                    if final_index == len(m_begin):\n                        break\n                    if mask & begin_mask:\n                        m_begin[final_index] = data_shape[final_index] if stride[index] < 0 else 0\n                    elif begin[index]:\n                        m_begin[final_index] = begin[index]\n                    if mask & end_mask:\n                        m_end[final_index] = 0 if stride[index] < 0 else data_shape[final_index]\n                    elif end[index]:\n                        m_end[final_index] = end[index]\n                    m_stride[final_index] = stride[index]\n                    if mask & shrink_axis_mask:\n                        # Tensorflow make axis with shrink_axis_mask as dimension 1\n                        m_begin[final_index] = (\n                            data_shape[final_index] + begin[index]\n                            if begin[index] < 0\n                            else begin[index]\n                        )\n                        m_end[final_index] = m_begin[final_index] + 1\n                        m_stride[final_index] = 1\n                        fshape_indices.append(-2)\n                    else:\n                        fshape_indices.append(final_index)\n\n                    final_index += 1\n            return m_begin, m_end, m_stride, fshape_indices\n\n        fshape_indices = None\n        if begin_mask or end_mask or ellipsis_mask or new_axis_mask or shrink_axis_mask:\n            begin, end, stride, fshape_indices = _transform_mask(stride_dim, ellipsis_mask)\n\n        out = _op.strided_slice(data_expr, begin=begin, end=end, strides=stride)\n        out_shape = _infer_shape(out)\n        if not fshape_indices:\n            fshape_indices = range(len(out_shape))\n\n        # Create final output shape.\n        final_output = []\n        final_len = len(fshape_indices)\n        for gather_index in fshape_indices:\n            if gather_index == -1:\n                final_output.append(1)\n                final_len += 1\n            elif gather_index == -2:\n                final_len -= 1\n            else:\n                final_output.append(out_shape[gather_index])\n\n        if final_len == 0:\n            return _op.squeeze(out, axis=tuple(range(len(fshape_indices))))\n\n        if not final_output:\n            return out\n        return _op.reshape(out, newshape=tuple(final_output))\n\n    def convert_zeros_like(self, op):\n        \"\"\"Convert TFLite ZEROS LIKE\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n        out = _op.zeros_like(in_expr)\n\n        return out\n\n    def convert_fill(self, op):\n        \"\"\"Convert TFLite FILL\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        if self.has_expr(input_tensors[0].tensor_idx):\n            raise tvm.error.OpNotImplemented(\n                \"For dims parameter of Fill operator,\" \" only constant values are supported.\"\n            )\n\n        in_dims = list(self.get_tensor_value(input_tensors[0]))\n        in_value_expr = self.get_expr(input_tensors[1].tensor_idx)\n        out = _op.full(in_value_expr, in_dims)\n\n        return out\n\n    def _convert_reduce(self, relay_op, op):\n        \"\"\"Generic method to Convert TFLite REDUCE operators\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ReducerOptions import ReducerOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        # input_tensor\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # axis\n        axis_value = self.get_tensor_value(input_tensors[1])\n        axis = tuple(axis_value) if len(axis_value.shape) > 0 else tuple((axis_value.item(),))\n\n        # Options - keep_dims (bool)\n        # In case Options are not present, set keep_dims to False(default)\n        if op.BuiltinOptionsType():\n            assert op.BuiltinOptionsType() == BuiltinOptions.ReducerOptions\n            reduce_options = ReducerOptions()\n            op_options = op.BuiltinOptions()\n            reduce_options.Init(op_options.Bytes, op_options.Pos)\n            keep_dims = reduce_options.KeepDims()\n        else:\n            keep_dims = False\n\n        if input_tensor.qnn_params:\n            in_expr = _op.cast(in_expr, \"int32\")\n\n        out = relay_op(in_expr, axis, keep_dims)\n\n        # Finally if the reduce is quantized. Add a requantize at the end.\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n        if output_tensor.qnn_params:\n            out = _qnn.op.requantize(\n                out,\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n\n        return out\n\n    def convert_reduce_min(self, op):\n        return self._convert_reduce(_op.reduce.min, op)\n\n    def convert_reduce_max(self, op):\n        return self._convert_reduce(_op.reduce.max, op)\n\n    def convert_reduce_mean(self, op):\n        return self._convert_reduce(_op.reduce.mean, op)\n\n    def convert_reduce_prod(self, op):\n        return self._convert_reduce(_op.reduce.prod, op)\n\n    def convert_reduce_sum(self, op):\n        return self._convert_reduce(_op.reduce.sum, op)\n\n    def convert_reduce_any(self, op):\n        return self._convert_reduce(_op.reduce.any, op)\n\n    def _convert_arg_min_max(self, relay_op, op):\n        \"\"\"Generic method converting TFLite arg_min_max\"\"\"\n        try:\n            from tflite.ArgMaxOptions import ArgMaxOptions\n            from tflite.ArgMinOptions import ArgMinOptions\n            from tflite.BuiltinOptions import BuiltinOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"two input tensor arguments expected\"\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"one output tensor expected\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n        axis_tensor = input_tensors[1]\n        # In Tensorflow, `axis` argument is a Tensor, not attribute. We\n        # support the case where it inputs from a scalar constant.\n        axis_value = self.get_tensor_value(axis_tensor)\n        assert axis_value.size == 1\n        axis_value = axis_value.item()\n\n        if op.BuiltinOptionsType() == BuiltinOptions.ArgMinOptions:\n            arg_min_max_options = ArgMinOptions()\n        elif op.BuiltinOptionsType() == BuiltinOptions.ArgMaxOptions:\n            arg_min_max_options = ArgMaxOptions()\n        op_options = op.BuiltinOptions()\n        arg_min_max_options.Init(op_options.Bytes, op_options.Pos)\n\n        # set keepdims to True since tflite 1.13 removes all dims of size 1\n        # WARNING: all other versions of tflite > 1.13 need keepdims=False\n        out = relay_op(in_expr, axis=axis_value, keepdims=False, exclude=False)\n\n        return out\n\n    def convert_arg_min(self, op):\n        \"\"\"Convert TFLite ARG_MIN\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized ARG_MIN operator is not supported yet.\"\n            )\n        return self._convert_arg_min_max(_op.argmin, op)\n\n    def convert_arg_max(self, op):\n        \"\"\"Convert TFLite ARG_MAX\"\"\"\n        return self._convert_arg_min_max(_op.argmax, op)\n\n    def convert_fully_connected(self, op):\n        \"\"\"Convert TFLite fully connected\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.FullyConnectedOptions import FullyConnectedOptions\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) in (2, 3), \"input tensors length should be two or three\"\n\n        input_tensor = input_tensors[0]\n        weight_tensor = input_tensors[1]\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type = output_tensor.tensor.Type()\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor_type)\n\n        weight_tensor_shape = to_int_list(self.get_tensor_shape(weight_tensor))\n\n        # Weight should have only 2 dimensions(TFLite convention)\n        assert len(weight_tensor_shape) == 2, \"Weight should be only 2-dim\"\n\n        # Input shape: [i_batch_size, ..., n_inputs]\n        # Filter shape: [n_inputs, n_units]\n        #\n        # As we will transform Fully_Connected Input to Dense Op inputs as below\n        # Dense expected Input shape: [batch_size, n_units]\n        # Dense expected Weight shape: [out_dim, n_units]\n        # Dense output shape: [batch_size, out_dim]\n        target_shape = tuple((-1, weight_tensor_shape[1]))\n        in_expr = self.get_tensor_expr(input_tensor)\n        in_expr = _op.reshape(in_expr, target_shape)\n\n        # TODO: Change the output shape calculation based on keep_dim option\n        assert op.BuiltinOptionsType() == BuiltinOptions.FullyConnectedOptions\n        op_options = op.BuiltinOptions()\n        fully_connected_options = FullyConnectedOptions()\n        fully_connected_options.Init(op_options.Bytes, op_options.Pos)\n        fused_activation_fn = fully_connected_options.FusedActivationFunction()\n        keep_num_dims = fully_connected_options.KeepNumDims()\n\n        # weight tensor type should be INT8/UINT8 (quantization) or FLOAT32\n        weight_tensor_type = weight_tensor.tensor.Type()\n        assert weight_tensor_type in (TensorType.INT8, TensorType.UINT8, TensorType.FLOAT32)\n        weight_tensor_type_str = self.get_tensor_type_str(weight_tensor_type)\n\n        if self.has_expr(weight_tensor.tensor_idx):\n            weight_expr = self.get_expr(weight_tensor.tensor_idx)\n        else:\n            weight_value = self.get_tensor_value(weight_tensor)\n            weight_expr = self.exp_tab.new_const(weight_value, dtype=weight_tensor_type_str)\n        weight_shape = _infer_shape(weight_expr)\n\n        if input_tensor.qnn_params:\n            out = _qnn.op.dense(\n                in_expr,\n                weight_expr,\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                kernel_zero_point=weight_tensor.qnn_params[\"zero_point\"],\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                kernel_scale=weight_tensor.qnn_params[\"scale\"],\n                units=weight_shape[0],\n                out_dtype=\"int32\",\n            )\n        else:\n            out = _op.nn.dense(in_expr, weight_expr, units=weight_shape[0])\n\n        # if we have bias\n        if len(input_tensors) == 3:\n            bias_tensor = input_tensors[2]\n            if bias_tensor.tensor_idx != -1:\n                bias_tensor_type = bias_tensor.tensor.Type()\n                # bias tensor type should be INT32 (quantization) or FLOAT32\n                assert bias_tensor_type in (TensorType.INT32, TensorType.FLOAT32)\n                bias_tensor_type_str = self.get_tensor_type_str(bias_tensor_type)\n                if self.has_expr(bias_tensor.tensor_idx):\n                    bias_expr = self.get_expr(bias_tensor.tensor_idx)\n                else:\n                    bias_expr = self.exp_tab.new_const(\n                        self.get_tensor_value(bias_tensor), dtype=bias_tensor_type_str\n                    )\n                out = _op.nn.bias_add(out, bias_expr)\n\n        # Finally if the dense is quantized. Add a requantize at the end.\n        if output_tensor.qnn_params:\n            data_scale = input_tensor.qnn_params[\"scale\"]\n            weight_scale = weight_tensor.qnn_params[\"scale\"]\n            data_scale_val = get_scalar_from_constant(data_scale)\n            weight_scale_val = get_scalar_from_constant(weight_scale)\n            new_input_scale_val = data_scale_val * weight_scale_val\n            new_input_scale = relay.const(new_input_scale_val, \"float32\")\n            new_input_zero_point = relay.const(0, \"int32\")\n\n            # Requantize\n            out = _qnn.op.requantize(\n                out,\n                input_scale=new_input_scale,\n                input_zero_point=new_input_zero_point,\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n\n            # Call activation function\n            output_scale_val = get_scalar_from_constant(output_tensor.qnn_params[\"scale\"])\n            output_zero_point_val = get_scalar_from_constant(output_tensor.qnn_params[\"zero_point\"])\n            out = self.convert_qnn_fused_activation_function(\n                expr=out,\n                fused_activation_fn=fused_activation_fn,\n                scale=output_scale_val,\n                zero_point=output_zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n\n        else:\n            out = self.convert_fused_activation_function(out, fused_activation_fn)\n\n        # Change the output shape calculation based on keep_dim option\n        if keep_num_dims:\n            input_shape = _infer_shape(self.get_tensor_expr(input_tensor))\n            output_shape = input_shape[:-1] + tuple([weight_tensor_shape[0]])\n            out = _op.reshape(out, output_shape)\n\n        return out\n\n    def convert_squeeze(self, op):\n        \"\"\"Convert TFLite squeeze\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.SqueezeOptions import SqueezeOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        output_tensors = self.get_output_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.SqueezeOptions\n        op_options = op.BuiltinOptions()\n        squeeze_options = SqueezeOptions()\n        squeeze_options.Init(op_options.Bytes, op_options.Pos)\n        squeeze_axis = squeeze_options.SqueezeDimsAsNumpy()\n\n        in_expr = self.get_expr(input_tensor_idx)\n        out = _op.squeeze(in_expr, axis=tuple(squeeze_axis))\n\n        return out\n\n    def convert_fused_activation_function(self, in_expr, fused_activation_fn):\n        \"\"\"Convert TFLite fused activation function\"\"\"\n        try:\n            from tflite.ActivationFunctionType import ActivationFunctionType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        if fused_activation_fn == ActivationFunctionType.NONE:\n            return in_expr\n        if fused_activation_fn == ActivationFunctionType.RELU6:\n            return _op.clip(in_expr, a_min=0, a_max=6)\n        if fused_activation_fn == ActivationFunctionType.RELU:\n            return _op.nn.relu(in_expr)\n        if fused_activation_fn == ActivationFunctionType.RELU_N1_TO_1:\n            return _op.clip(in_expr, a_min=-1, a_max=1)\n        if fused_activation_fn == ActivationFunctionType.TANH:\n            return _op.tanh(in_expr)\n        fused_activation_fn_str = self.activation_fn_type[fused_activation_fn]\n        raise tvm.error.OpNotImplemented(\n            \"Fused activation {} is not supported yet.\".format(fused_activation_fn_str)\n        )\n\n    def convert_conv(self, op, conv_type):\n        \"\"\"convolution implementation.\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.Conv2DOptions import Conv2DOptions\n            from tflite.DepthwiseConv2DOptions import DepthwiseConv2DOptions\n            from tflite.Padding import Padding\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) >= 2, \"input tensors length should be >= 2\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n        weight_tensor = input_tensors[1]\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type = output_tensor.tensor.Type()\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor_type)\n\n        is_depthwise_conv = False\n        if conv_type == \"conv2d\":\n            assert op.BuiltinOptionsType() == BuiltinOptions.Conv2DOptions\n            op_options = op.BuiltinOptions()\n            conv_options = Conv2DOptions()\n            conv_options.Init(op_options.Bytes, op_options.Pos)\n        elif conv_type == \"depthwise\":\n            is_depthwise_conv = True\n            assert op.BuiltinOptionsType() == BuiltinOptions.DepthwiseConv2DOptions\n            op_options = op.BuiltinOptions()\n            conv_options = DepthwiseConv2DOptions()\n            conv_options.Init(op_options.Bytes, op_options.Pos)\n            depth_multiplier = conv_options.DepthMultiplier()\n        else:\n            raise tvm.error.OpNotImplemented(\n                \"Operator {} is not supported for frontend TFLite.\".format(conv_type)\n            )\n\n        stride_h = conv_options.StrideH()\n        stride_w = conv_options.StrideW()\n        dilation_h = conv_options.DilationHFactor()\n        dilation_w = conv_options.DilationWFactor()\n        padding = conv_options.Padding()\n        fused_activation_fn = conv_options.FusedActivationFunction()\n\n        _, input_h, input_w, input_c = to_int_list(self.get_tensor_shape(input_tensor))\n\n        if is_depthwise_conv:\n            # TFLite depthwise convolution kernel layout is:\n            # 1 KH KW C(input_c * depth_multiplier)\n            _, kernel_h, kernel_w, in_channels = to_int_list(self.get_tensor_shape(weight_tensor))\n            assert in_channels == input_c * depth_multiplier\n        else:\n            output_channels, kernel_h, kernel_w, _ = to_int_list(\n                self.get_tensor_shape(weight_tensor)\n            )\n\n        dilated_kernel_h = dilation_h * (kernel_h - 1) + 1\n        dilated_kernel_w = dilation_w * (kernel_w - 1) + 1\n\n        params = {\n            \"kernel_size\": [kernel_h, kernel_w],\n            \"strides\": [stride_h, stride_w],\n            \"dilation\": [dilation_h, dilation_w],\n            \"padding\": [0, 0],\n            \"data_layout\": \"NHWC\",\n        }\n\n        if is_depthwise_conv:\n            params[\"channels\"] = int(in_channels)\n            params[\"groups\"] = int(input_c)\n            # If number of input channels is 1, treat as normal\n            # convolution.\n            params[\"kernel_layout\"] = \"HWIO\" if input_c == 1 else \"HWOI\"\n        else:\n            params[\"channels\"] = int(output_channels)\n            params[\"kernel_layout\"] = \"HWIO\"\n\n        # weight tensor type should be INT8/UINT8 (quantization) or FLOAT32\n        weight_tensor_type = weight_tensor.tensor.Type()\n        assert weight_tensor_type in (TensorType.INT8, TensorType.UINT8, TensorType.FLOAT32)\n        weight_tensor_type_str = self.get_tensor_type_str(weight_tensor_type)\n\n        in_expr = self.get_expr(input_tensor_idx)\n\n        # TFLite converts float32 models to float16 models by introducing\n        # a Dequantize op in every op that contains a float32 values.\n        # (weights, biases, and constants etc. )\n        # So conv op may have weight and bias as tensors instead of values.\n        if self.has_expr(weight_tensor.tensor_idx):\n            weight_expr = self.get_expr(weight_tensor.tensor_idx)\n            if is_depthwise_conv:\n                weight_expr = _op.reshape(\n                    weight_expr, (kernel_h, kernel_w, input_c, depth_multiplier)\n                )\n            else:\n                weight_expr = _op.transpose(weight_expr, axes=(1, 2, 3, 0))\n        else:\n            if self.is_prefetched(weight_tensor.tensor_idx):\n                weight_value = self.get_prefetched_node(weight_tensor.tensor_idx)\n            else:\n                weight_value = self.get_tensor_value(weight_tensor)\n\n            # TFLite kernel layout:\n            # convolution:\n            # OC KH KW IC, we require KH KW IC OC (HWIO)\n            # depthwise convolution:\n            # 1 KH KW C(input_c * depth_multiplier), we require\n            # KH KW IC M (depth_multiplier) (HWOI)\n            if is_depthwise_conv:\n                weight_value = weight_value.reshape(kernel_h, kernel_w, input_c, depth_multiplier)\n            else:\n                weight_value = weight_value.transpose((1, 2, 3, 0))\n\n            weight_expr = self.exp_tab.new_const(weight_value, dtype=weight_tensor_type_str)\n\n        if padding == Padding.VALID:\n            pass\n        elif padding == Padding.SAME:\n            pad_top, pad_bottom = get_pad_value(input_h, dilated_kernel_h, stride_h)\n\n            pad_left, pad_right = get_pad_value(input_w, dilated_kernel_w, stride_w)\n            do_pad = not (pad_top == 0 and pad_bottom == 0 and pad_left == 0 and pad_right == 0)\n            if do_pad:\n                params[\"padding\"] = [pad_top, pad_left, pad_bottom, pad_right]\n\n        else:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Padding format {} is not supported for operator Conv.\".format(padding)\n            )\n\n        if input_tensor.qnn_params:\n            qnn_conv2d_params = dict(params)\n            qnn_conv2d_params[\"input_zero_point\"] = input_tensor.qnn_params[\"zero_point\"]\n            qnn_conv2d_params[\"kernel_zero_point\"] = weight_tensor.qnn_params[\"zero_point\"]\n            qnn_conv2d_params[\"out_dtype\"] = (\n                \"int64\" if output_tensor_type_str == \"int16\" else \"int32\"\n            )\n            qnn_conv2d_params[\"input_scale\"] = input_tensor.qnn_params[\"scale\"]\n            qnn_conv2d_params[\"kernel_scale\"] = weight_tensor.qnn_params[\"scale\"]\n            out = _qnn.op.conv2d(in_expr, weight_expr, **qnn_conv2d_params)\n        else:\n            out = _op.nn.conv2d(in_expr, weight_expr, **params)\n\n        # if we have bias\n        if len(input_tensors) == 3:\n            bias_tensor = input_tensors[2]\n            bias_tensor_type = bias_tensor.tensor.Type()\n            # bias tensor type should be INT32 (int8 qnn) or INT64 (int16 qnn) or FLOAT32\n            assert bias_tensor_type in (TensorType.INT32, TensorType.INT64, TensorType.FLOAT32)\n            bias_tensor_type_str = self.get_tensor_type_str(bias_tensor_type)\n            if self.has_expr(bias_tensor.tensor_idx):\n                bias_expr = self.get_expr(bias_tensor.tensor_idx)\n            else:\n                bias_expr = self.exp_tab.new_const(\n                    self.get_tensor_value(bias_tensor), dtype=bias_tensor_type_str\n                )\n            channel_axis = 3\n            out = _op.nn.bias_add(out, bias_expr, axis=channel_axis)\n\n        # Handle fused activation.\n        if output_tensor.qnn_params:\n            # Calculate the intermediate scale and zero point of the int32 output.\n            data_scale = input_tensor.qnn_params[\"scale\"]\n            data_scale_val = get_scalar_from_constant(data_scale)\n\n            weight_scale = weight_tensor.qnn_params[\"scale\"]\n            # If weight scale is scalar, it is per-tensor quantization\n            if isinstance(weight_scale, float):\n                weight_scale_val = get_scalar_from_constant(weight_scale)\n            else:\n                weight_scale_val = get_tensor_from_constant(weight_scale)\n\n            new_input_scale_val = data_scale_val * weight_scale_val\n            new_input_scale = relay.const(new_input_scale_val, \"float32\")\n            new_input_zero_point = relay.const(0, \"int32\")\n\n            # Finally requantize\n            out = _qnn.op.requantize(\n                out,\n                input_scale=new_input_scale,\n                input_zero_point=new_input_zero_point,\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n                axis=3,\n            )\n\n            # Call activation function\n            output_scale_val = get_scalar_from_constant(output_tensor.qnn_params[\"scale\"])\n            output_zero_point_val = get_scalar_from_constant(output_tensor.qnn_params[\"zero_point\"])\n            out = self.convert_qnn_fused_activation_function(\n                expr=out,\n                fused_activation_fn=fused_activation_fn,\n                scale=output_scale_val,\n                zero_point=output_zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n        else:\n            out = self.convert_fused_activation_function(out, fused_activation_fn)\n        return out\n\n    def convert_split(self, op):\n        \"\"\"split implementation.\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.SplitOptions import SplitOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n\n        assert len(input_tensors) == 2, \"input tensors length should be == 2\"\n\n        axis_tensor = input_tensors[0]\n        split_axis = self.get_tensor_value(axis_tensor)\n        input_tensor = input_tensors[1]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.SplitOptions\n        op_options = op.BuiltinOptions()\n        split_options = SplitOptions()\n        split_options.Init(op_options.Bytes, op_options.Pos)\n        num_splits = split_options.NumSplits()\n\n        in_expr = self.get_expr(input_tensor_idx)\n        out = _op.split(in_expr, num_splits, axis=int(split_axis))\n        # Relay does not like a TupleWrapper of 1 element, further this\n        # only shows up with tf1.13 if we use a split with num_splits==1.\n        # In tf 1.14 this doesn't appear as it is automatically a reshape\n        # operation.\n        if isinstance(out, _expr.TupleWrapper):\n            if out.size == 1:\n                out = out[0]\n\n        return out\n\n    def convert_split_v(self, op):\n        \"\"\"SPLIT_V implementation.\"\"\"\n        input_tensors = self.get_input_tensors(op)\n\n        assert len(input_tensors) == 3, \"input tensors length should be 3\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n        in_expr = self.get_expr(input_tensor_idx)\n\n        if self.has_expr(input_tensors[1].tensor_idx):\n            raise tvm.error.OpNotImplemented(\n                \"For size_splits parameter of SPLIT_V operator, \"\n                \"only constant values are supported.\"\n            )\n        size_splits = list(self.get_tensor_value(input_tensors[1]))\n        size_splits = tuple(np.cumsum(size_splits)[:-1])\n\n        axis_tensor = input_tensors[2]\n        split_axis = self.get_tensor_value(axis_tensor)\n\n        out = _op.split(in_expr, size_splits, axis=int(split_axis))\n        # Relay does not like a TupleWrapper of 1 element, further this\n        # only shows up with tf1.13 if we use a split with num_splits==1.\n        # In tf 1.14 this doesn't appear as it is automatically a reshape\n        # operation.\n        if isinstance(out, _expr.TupleWrapper) and out.size == 1:\n            out = out[0]\n\n        return out\n\n    def convert_slice(self, op):\n        \"\"\"Convert TFLite SLICE\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 3, \"input tensors length should be == 3\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        begin = list(self.get_tensor_value(input_tensors[1]))\n        size = list(self.get_tensor_value(input_tensors[2]))\n        # strided_slice(Relay) needs the slice's end indices, not the size\n        end = size\n        input_tensor_shape = to_int_list(self.get_tensor_shape(input_tensor))\n        input_tensor_rank = len(input_tensor_shape)\n        for i in range(input_tensor_rank):\n            if size[i] == -1:\n                end[i] = input_tensor_shape[i]\n            else:\n                end[i] += begin[i]\n\n        out = _op.strided_slice(in_expr, begin, end)\n\n        return out\n\n    def convert_select(self, op):\n        \"\"\"Convert TFLite SELECT\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 3, \"input tensors length should be == 3\"\n        cond = self.get_tensor_expr(input_tensors[0])\n        x = self.get_tensor_expr(input_tensors[1])\n        y = self.get_tensor_expr(input_tensors[2])\n\n        out = _op.where(cond, x, y)\n\n        return out\n\n    def convert_transpose(self, op):\n        \"\"\"transpose implementation.\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        in_expr = self.get_expr(input_tensor_idx)\n\n        # axis\n        in_axis = tuple(self.get_tensor_value(input_tensors[1]))\n\n        if not in_axis:\n            out = _op.transpose(in_expr)\n        else:\n            out = _op.transpose(in_expr, in_axis)\n\n        return out\n\n    def convert_reverse_sequence(self, op):\n        \"\"\"Convert TFLite REVERSE_SEQUENCE\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.ReverseSequenceOptions import ReverseSequenceOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFLite does not support quantized REVERSE_SEQUENCE operator yet.\"\n            )\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        in_expr = self.get_tensor_expr(input_tensors[0])\n        length_expr = self.get_tensor_expr(input_tensors[1])\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.ReverseSequenceOptions\n        op_options = op.BuiltinOptions()\n        options = ReverseSequenceOptions()\n        options.Init(op_options.Bytes, op_options.Pos)\n        batch_axis = options.BatchDim()\n        seq_axis = options.SeqDim()\n\n        return _op.reverse_sequence(in_expr, length_expr, seq_axis, batch_axis)\n\n    def convert_cast(self, op):\n        \"\"\"Convert TFLite CAST\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.CastOptions import CastOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # MLIR-based converter outputs no BuiltinOptions for Cast operator. In this\n        # case the output type can be derived from the Cast operator output tensor.\n        # When TOCO converter is used there will be \"normal\" BuiltinOptions.CastOptions\n        # with output type.\n        if op.BuiltinOptions() is not None:\n            assert op.BuiltinOptionsType() == BuiltinOptions.CastOptions\n            op_options = op.BuiltinOptions()\n            cast_options = CastOptions()\n            cast_options.Init(op_options.Bytes, op_options.Pos)\n            cast_dtype = cast_options.OutDataType()\n        else:\n            cast_dtype = self.get_output_tensors(op)[0].tensor.Type()\n\n        out = _op.cast(in_expr, self.get_tensor_type_str(cast_dtype))\n\n        return out\n\n    def convert_tile(self, op):\n        \"\"\"tile implementation.\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        in_expr = self.get_expr(input_tensor_idx)\n\n        # reps (tuple of int) \u2013 The number of times repeating the tensor data.\n        reps = tuple(self.get_tensor_value(input_tensors[1]))\n\n        out = _op.tile(in_expr, reps)\n\n        return out\n\n    def convert_topk_v2(self, op):\n        \"\"\"Convert TFLite TOPK_v2\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n        in_expr = self.get_expr(input_tensor_idx)\n        k = self.get_tensor_value(input_tensors[1])\n        out = _op.topk(in_expr, int(k))\n\n        return out\n\n    def convert_pool2d(self, op, pool_type):\n        \"\"\"pool2d implementation.\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.Padding import Padding\n            from tflite.Pool2DOptions import Pool2DOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type = output_tensor.tensor.Type()\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor_type)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.Pool2DOptions\n        op_options = op.BuiltinOptions()\n        pool2d_options = Pool2DOptions()\n        pool2d_options.Init(op_options.Bytes, op_options.Pos)\n        stride_h = pool2d_options.StrideH()\n        stride_w = pool2d_options.StrideW()\n        padding = pool2d_options.Padding()\n        filter_h = pool2d_options.FilterHeight()\n        filter_w = pool2d_options.FilterWidth()\n        fused_activation_fn = pool2d_options.FusedActivationFunction()\n\n        params = {\n            \"pool_size\": (filter_h, filter_w),\n            \"strides\": (stride_h, stride_w),\n            \"padding\": [0, 0],\n            \"layout\": \"NHWC\",\n        }\n\n        in_expr = self.get_expr(input_tensor_idx)\n\n        _, input_h, input_w, _ = to_int_list(self.get_tensor_shape(input_tensor))\n\n        if padding == Padding.VALID:\n            pass\n        elif padding == Padding.SAME:\n            pad_top, pad_bottom = get_pad_value(input_h, filter_h, stride_h)\n            pad_left, pad_right = get_pad_value(input_w, filter_w, stride_w)\n            params[\"padding\"] = [pad_top, pad_left, pad_bottom, pad_right]\n        else:\n            raise tvm.error.OpAttributeUnImplemented(\n                \"Padding format {} for operator Pool2D is not supported.\".format(padding)\n            )\n\n        if pool_type == \"average\":\n            if input_tensor.qnn_params:\n                assert self.has_same_qnn_params(input_tensor, output_tensor), (\n                    \"TFLite avg_pool2dreshape requires input and output scale\"\n                    \"and zero points to be equal\"\n                )\n                out = _op.cast(in_expr, dtype=\"int32\")\n                out = _op.nn.avg_pool2d(out, **params)\n                out = _op.cast(out, dtype=output_tensor_type_str)\n            else:\n                out = _op.nn.avg_pool2d(in_expr, **params)\n        elif pool_type == \"max\":\n            if input_tensor.qnn_params:\n                assert self.has_same_qnn_params(\n                    input_tensor, output_tensor\n                ), \"qnn.op.max_pool2d requires input and output qnn params to be same\"\n            out = _op.nn.max_pool2d(in_expr, **params)\n        elif pool_type == \"l2\":\n            # L2_POOL_2D is equivalent to square_root(avg_pool(square(in_data)))\n            # TFLite does not have support for quantised L2_POOL_2D op.\n            assert (\n                not input_tensor.qnn_params\n            ), \"As TFLite does not have support for quantized L2_POOL_2D, \\\n                Quantized input is not expected.\"\n            exp_type = self.get_tensor_type_str(output_tensor.tensor.Type())\n            square_exp = _op.power(in_expr, relay.const(2, exp_type))\n            avg_pool_exp = _op.nn.avg_pool2d(square_exp, **params)\n            out = _op.sqrt(avg_pool_exp)\n        else:\n            raise tvm.error.OpNotImplemented(\n                \"Operator {} is not supported for frontend TFLite.\".format(pool_type + \" pool\")\n            )\n\n        # Handle fused activations\n        if output_tensor.qnn_params:\n            scale_val = get_scalar_from_constant(output_tensor.qnn_params[\"scale\"])\n            zero_point_val = get_scalar_from_constant(output_tensor.qnn_params[\"zero_point\"])\n            out = self.convert_qnn_fused_activation_function(\n                expr=out,\n                fused_activation_fn=fused_activation_fn,\n                scale=scale_val,\n                zero_point=zero_point_val,\n                dtype=output_tensor_type_str,\n            )\n        else:\n            out = self.convert_fused_activation_function(out, fused_activation_fn)\n\n        return out\n\n    def convert_pad(self, op):\n        \"\"\"Convert TFLite PAD/PADV2 \\\n           TFLite treats PAD and PADV2 operators identically\"\"\"\n\n        input_tensors = self.get_input_tensors(op)\n\n        # TFLite PAD/PADV2 only supports CONSTANT mode\n        assert (\n            len(input_tensors) == 2 or len(input_tensors) == 3\n        ), \"input tensor's length should be 2 for PAD and 3 for PADV2\"\n\n        if len(input_tensors) == 3:\n            assert (\n                input_tensors[0].tensor.Type() == input_tensors[2].tensor.Type()\n            ), \"constant_values tensor must be of same type as input tensor\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # paddings\n        pad_list = self.get_tensor_value(input_tensors[1])\n\n        # convert list of lists to tuple of tuples\n        paddings = tuple(tuple(l) for l in pad_list)\n\n        # Set the pad value, by default 0, unless constant_values parameter is provided\n        pad_value = 0\n\n        if input_tensor.qnn_params:\n            # Check that input and output tensor have same qnn params.\n            output_tensors = self.get_output_tensors(op)\n            output_tensor = output_tensors[0]\n            assert self.has_same_qnn_params(\n                input_tensor, output_tensor\n            ), \"TFLite PADV2 requires input and output scale and zero points to be equal\"\n\n            # The pad value for quantized pad is the input zero point by default.\n            pad_value = float(input_tensor.qnn_params[\"zero_point\"].data.numpy())\n\n        if len(input_tensors) == 3:\n            pad_value = self.get_tensor_value(input_tensors[2])\n            if isinstance(pad_value, np.ndarray):\n                pad_value = pad_value.tolist()\n            if isinstance(pad_value, list):\n                assert len(pad_value) == 1, \"Only one constant value is expected.\"\n                pad_value = pad_value[0]\n            if input_tensor.qnn_params:\n                # Check that input tensor and constant_values have same qnn params.\n                assert self.has_same_qnn_params(\n                    input_tensor, input_tensors[2]\n                ), \"TFLite PADV2 requires input and constant_values tensors' \\\n                        scale and zero points to be equal\"\n\n        out = _op.nn.pad(in_expr, pad_width=paddings, pad_value=pad_value)\n        return out\n\n    def convert_floor_div(self, op):\n        \"\"\"Convert TFLite FLOOR_DIV\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized FLOOR DIV operator is not supported yet.\"\n            )\n        return self._convert_elemwise(_op.floor_divide, op)\n\n    def convert_floor_mod(self, op):\n        \"\"\"Convert TFLite FLOOR_MOD\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized FLOOR MOD operator is not supported yet.\"\n            )\n        return self._convert_elemwise(_op.floor_mod, op)\n\n    def convert_mirror_pad(self, op):\n        \"\"\"Convert TFLite MIRROR_PAD\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.MirrorPadOptions import MirrorPadOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        # the quantized form MirrorPad is not yet implemented in TFLite.\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized MIRROR_PAD operator is not supported yet.\"\n            )\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        # tensor\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # paddings\n        pad_list = self.get_tensor_value(input_tensors[1])\n        # convert list of lists to tuple of tuples\n        paddings = tuple(tuple(l.astype(np.int32)) for l in pad_list)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.MirrorPadOptions\n        op_options = op.BuiltinOptions()\n        mirror_pad_options = MirrorPadOptions()\n        mirror_pad_options.Init(op_options.Bytes, op_options.Pos)\n        mode_byte = mirror_pad_options.Mode()\n\n        mode = \"REFLECT\" if mode_byte == 0 else \"SYMMETRIC\"\n        out = _op.nn.mirror_pad(in_expr, paddings, mode)\n\n        return out\n\n    def convert_pack(self, op):\n        \"\"\"Convert TFLite pack\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.PackOptions import PackOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n\n        if input_tensors[0].qnn_params:\n            output_tensor = output_tensors[0]\n            assert self.has_same_qnn_params(\n                input_tensors[0], output_tensor\n            ), \"TFLite pack requires input and output scale and zero points to be equal\"\n\n            for input_tensor in input_tensors:\n                assert self.has_same_qnn_params(\n                    input_tensors[0], input_tensor\n                ), \"TFLite pack requires all input tensors to have same scale and zero point\"\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.PackOptions\n        op_options = op.BuiltinOptions()\n        pack_options = PackOptions()\n        pack_options.Init(op_options.Bytes, op_options.Pos)\n        pack_axis = pack_options.Axis()\n        pack_values_count = pack_options.ValuesCount()\n        assert len(input_tensors) == pack_values_count, \"Discordance in input values count\"\n\n        in_exprs = [self.get_tensor_expr(_) for _ in input_tensors]\n        in_exprs_reshaped = [_op.expand_dims(_, axis=pack_axis, num_newaxis=1) for _ in in_exprs]\n        out = _op.concatenate(in_exprs_reshaped, pack_axis)\n        return out\n\n    def convert_unpack(self, op):\n        \"\"\"Convert TFLite unpack\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.UnpackOptions import UnpackOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n        assert op.BuiltinOptionsType() == BuiltinOptions.UnpackOptions\n        op_options = op.BuiltinOptions()\n        unpack_options = UnpackOptions()\n        unpack_options.Init(op_options.Bytes, op_options.Pos)\n        num_unpacks = unpack_options.Num()\n        unpack_axis = unpack_options.Axis()\n\n        # Relay doesn't support 'unpack' operator so we use 'split' & 'squeeze' instead.\n        # We have to do 'squeeze' along the split axis.\n        # Relay expects squeeze_axis to be List.\n        squeeze_axis = [unpack_axis]\n\n        # Relay doesn't like TupleWrapper of 1 element so we isolate the case of unpacking\n        # a tensor by an axis with len(axis) == 1. For reference see convert_split().\n        # Such unpacking will result in the same tensor so we omit 'split' and only squeeze\n        # along the axis of dim == 1.\n        if num_unpacks == 1:\n            squeezed = _op.squeeze(in_expr, axis=squeeze_axis)\n            if isinstance(squeezed, _expr.TupleWrapper):\n                squeezed = squeezed[0]\n        else:\n            splitted = _op.split(in_expr, indices_or_sections=num_unpacks, axis=unpack_axis)\n            squeezed = _expr.TupleWrapper(\n                _expr.Tuple(\n                    [_op.squeeze(split_item, axis=squeeze_axis) for split_item in splitted]\n                ),\n                len(splitted),\n            )\n\n        return squeezed\n\n    def convert_unidirectional_sequence_lstm(self, op):\n        \"\"\"Long Short Term Memory for TFLite implementation.\"\"\"\n        if self.is_quantized(op):\n            raise tvm.error.OpNotImplemented(\n                \"TFlite quantized UNIDIRECTIONALSEQUENCELSTM operator is not supported yet.\"\n            )\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 24, \"input tensors length should be == 24\"\n\n        # Extract input tensor from saved model\n        input_tensor = input_tensors[0]\n\n        # Extract tensors from input tensors from saved model\n        # Input weights\n        input_input_weights = input_tensors[1]\n        input_forget_weights = input_tensors[2]\n        input_cell_weights = input_tensors[3]\n        input_output_weights = input_tensors[4]\n        # Recurrent weights\n        recurrent_input_weights = input_tensors[5]\n        recurrent_forget_weights = input_tensors[6]\n        recurrent_cell_weights = input_tensors[7]\n        recurrent_output_weights = input_tensors[8]\n        # inputs 9, 10, 11, 16, 17, 20, 21, 22, 23 are not occupied\n        # there locations are -1 in the flatbuffer\n        # Bias weights\n        input_gate_bias = input_tensors[12]\n        forget_gate_bias = input_tensors[13]\n        cell_gate_bias = input_tensors[14]\n        output_gate_bias = input_tensors[15]\n\n        # State input\n        output_state_in = input_tensors[18]\n        cell_state_in = input_tensors[19]\n\n        # Extract output tensor from saved model\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        X_steps = self.unbind(input_tensor, axis=1)\n        weights_dict = {}\n\n        # hidden_state_weights is equivalent to output_state_in in tflite model\n        out_state_in_shape = tuple(self.get_tensor_shape(output_state_in))\n        out_state_in_dtype = self.get_tensor_type_str(output_state_in.tensor.Type())\n        out_state_in_expr = _op.zeros(out_state_in_shape, dtype=out_state_in_dtype)\n        weights_dict[\"hidden_state\"] = _op.split(out_state_in_expr, 1)[0]\n\n        # cell_state_weights is equivalent to output_state_in tflite model\n        cell_state_in_shape = tuple(self.get_tensor_shape(cell_state_in))\n        cell_state_in_dtype = self.get_tensor_type_str(cell_state_in.tensor.Type())\n        cell_state_in_expr = _op.zeros(cell_state_in_shape, dtype=cell_state_in_dtype)\n        weights_dict[\"cell_state\"] = _op.split(cell_state_in_expr, 1)[0]\n\n        # Process weight matrix of input: w_inp\n        # Concatenate of [input_input_weight, input_forget_weights,\n        # input_cell_weights, input_output_weights]\n        input_input_weights_default_values = self.get_tensor_value(input_input_weights)\n        input_input_weights_op = _op.split(\n            _op.const(input_input_weights_default_values.tolist()), 1\n        )\n        input_output_weights_default_values = self.get_tensor_value(input_output_weights)\n        input_output_weights_op = _op.split(\n            _op.const(input_output_weights_default_values.tolist()), 1\n        )\n        input_forget_weights_default_values = self.get_tensor_value(input_forget_weights)\n        input_forget_weights_op = _op.split(\n            _op.const(input_forget_weights_default_values.tolist()), 1\n        )\n        input_cell_weights_default_values = self.get_tensor_value(input_cell_weights)\n        input_cell_weights_op = _op.split(_op.const(input_cell_weights_default_values.tolist()), 1)\n        weights_dict[\"w_inp\"] = _op.concatenate(\n            [\n                _op.squeeze(input_input_weights_op[0]),\n                _op.squeeze(input_forget_weights_op[0]),\n                _op.squeeze(input_cell_weights_op[0]),\n                _op.squeeze(input_output_weights_op[0]),\n            ],\n            axis=0,\n        )\n\n        # Process weight matrix of hidden state:\n        # w_hid to support lstm_cell function. Not used in tflite\n        recurrent_input_weights_values = self.get_tensor_value(recurrent_input_weights)\n        recurrent_input_weights_op = _op.split(\n            _op.const(recurrent_input_weights_values.tolist()), 1\n        )\n        recurrent_output_weights_values = self.get_tensor_value(recurrent_output_weights)\n        recurrent_output_weights_op = _op.split(\n            _op.const(recurrent_output_weights_values.tolist()), 1\n        )\n        recurrent_forget_weights_values = self.get_tensor_value(recurrent_forget_weights)\n        recurrent_forget_weights_op = _op.split(\n            _op.const(recurrent_forget_weights_values.tolist()), 1\n        )\n        recurrent_cell_weights_values = self.get_tensor_value(recurrent_cell_weights)\n        recurrent_cell_weights_op = _op.split(_op.const(recurrent_cell_weights_values.tolist()), 1)\n        weights_dict[\"w_hid\"] = _op.concatenate(\n            [\n                recurrent_input_weights_op[0],\n                recurrent_forget_weights_op[0],\n                recurrent_cell_weights_op[0],\n                recurrent_output_weights_op[0],\n            ],\n            axis=0,\n        )\n\n        # Process weight matrix of bias: b_inp\n        input_gate_bias_values = self.get_tensor_value(input_gate_bias)\n        input_gate_bias_op = _op.split(_op.const(input_gate_bias_values.tolist()), 1)\n        output_gate_bias_values = self.get_tensor_value(output_gate_bias)\n        output_gate_bias_op = _op.split(_op.const(output_gate_bias_values.tolist()), 1)\n        forget_gate_bias_values = self.get_tensor_value(forget_gate_bias)\n        forget_gate_bias_op = _op.split(_op.const(forget_gate_bias_values.tolist()), 1)\n        cell_gate_bias_values = self.get_tensor_value(cell_gate_bias)\n        cell_gate_bias_op = _op.split(_op.const(cell_gate_bias_values.tolist()), 1)\n        weights_dict[\"b_inp\"] = _op.concatenate(\n            [\n                input_gate_bias_op[0],\n                forget_gate_bias_op[0],\n                cell_gate_bias_op[0],\n                output_gate_bias_op[0],\n            ],\n            axis=0,\n        )\n\n        # Process weight matrix of hidden bias:\n        # b_hid (with the same shape as b_inp)\n        gate_bias_dtype = self.get_tensor_type_str(input_gate_bias.tensor.Type())\n        weights_dict[\"b_hid\"] = _op.split(\n            _op.const(\n                np.zeros(_infer_shape(weights_dict[\"b_inp\"]), dtype=gate_bias_dtype),\n                dtype=gate_bias_dtype,\n            ),\n            1,\n        )[0]\n\n        outputs, _, _ = lstm_cell(input_seqs=X_steps, **weights_dict)\n\n        output = _op.stack(outputs, axis=1)\n        return output\n\n    def convert_batch_to_space_nd(self, op):\n        \"\"\"batch_to_space_nd implementation.\"\"\"\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 3, \"input tensors length should be 3\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n        in_expr = self.get_expr(input_tensor_idx)\n\n        block_shape = list(self.get_tensor_value(input_tensors[1]))\n        crops = self.get_tensor_value(input_tensors[2]).tolist()\n\n        out = _op.nn.batch_to_space_nd(in_expr, block_shape, crops)\n\n        return out\n\n    def convert_space_to_batch_nd(self, op):\n        \"\"\"space_to_batch_nd implementation.\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 3, \"input tensors length should be 3\"\n\n        input_tensor = input_tensors[0]\n        input_tensor_idx = input_tensor.tensor_idx\n        in_expr = self.get_expr(input_tensor_idx)\n\n        block_shape = list(self.get_tensor_value(input_tensors[1]))\n        paddings = self.get_tensor_value(input_tensors[2]).tolist()\n\n        out = _op.nn.space_to_batch_nd(in_expr, block_shape, paddings)\n\n        return out\n\n    def convert_depth_to_space(self, op):\n        \"\"\"Convert TFLite DEPTH_TO_SPACE\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.DepthToSpaceOptions import DepthToSpaceOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.DepthToSpaceOptions\n        op_options = op.BuiltinOptions()\n        depth_to_space_options = DepthToSpaceOptions()\n        depth_to_space_options.Init(op_options.Bytes, op_options.Pos)\n        block_size = depth_to_space_options.BlockSize()\n        out = _op.nn.depth_to_space(in_expr, block_size, layout=\"NHWC\")\n\n        return out\n\n    def convert_space_to_depth(self, op):\n        \"\"\"Convert TFLite SPACE_TO_DEPTH\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.SpaceToDepthOptions import SpaceToDepthOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.SpaceToDepthOptions\n        op_options = op.BuiltinOptions()\n        space_to_depth_options = SpaceToDepthOptions()\n        space_to_depth_options.Init(op_options.Bytes, op_options.Pos)\n        block_size = space_to_depth_options.BlockSize()\n        out = _op.nn.space_to_depth(in_expr, block_size, layout=\"NHWC\")\n\n        return out\n\n    def convert_sparse_to_dense(self, op):\n        \"\"\"Convert TFLite SPARSE_TO_DENSE\"\"\"\n        try:\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 4, \"input tensors length should be 4\"\n\n        indices, values = input_tensors[0], input_tensors[2]\n        default_value = input_tensors[3]\n        output_shape = input_tensors[1]\n\n        for t in input_tensors:\n            assert not t.qnn_params, \"Quantized input is not expected.\"\n\n        for t in [indices, output_shape]:\n            t_type = t.tensor.Type()\n            assert t_type in (TensorType.INT32, TensorType.INT64)\n\n        out = _op.sparse_to_dense(\n            self.get_tensor_expr(indices),\n            list(self.get_tensor_value(output_shape)),\n            self.get_tensor_expr(values),\n            self.get_tensor_expr(default_value),\n        )\n\n        return out\n\n    def convert_prelu(self, op):\n        \"\"\"Convert TFLite PReLU\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        input_tensor = input_tensors[0]\n        alpha_tensor = input_tensors[1]\n        if self.has_expr(alpha_tensor.tensor_idx):\n            alpha_expr = self.get_expr(alpha_tensor.tensor_idx)\n        else:\n            alpha_tensor_type = alpha_tensor.tensor.Type()\n            alpha_tensor_type_str = self.get_tensor_type_str(alpha_tensor_type)\n            alpha_expr = self.exp_tab.new_const(\n                self.get_tensor_value(alpha_tensor), dtype=alpha_tensor_type_str\n            )\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n        data_shape = to_int_list(self.get_tensor_shape(input_tensor))\n\n        alpha_expr = _op.broadcast_to(alpha_expr, data_shape)\n        alpha_expr = _op.reshape(alpha_expr, [-1])\n        out = _op.nn.prelu(_op.reshape(in_expr, [-1]), alpha_expr, axis=0)\n        out = _op.reshape(out, data_shape)\n        return out\n\n    def convert_transpose_conv(self, op):\n        \"\"\"Convert TFLite TRANSPOSE_CONV\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.Padding import Padding\n            from tflite.TensorType import TensorType\n            from tflite.TransposeConvOptions import TransposeConvOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) >= 3, \"input tensors length should be >= 3\"\n\n        # Input (data) Tensor. NHWC layout\n        input_tensor = input_tensors[2]\n        _, _, _, input_c = to_int_list(self.get_tensor_shape(input_tensor))\n        # Weights tensor. TFLite uses OHWI layout\n        weights_tensor = input_tensors[1]\n        out_channels, kernel_h, kernel_w, in_channels = to_int_list(\n            self.get_tensor_shape(weights_tensor)\n        )\n\n        assert (\n            input_c == in_channels\n        ), \"Input channel in the filter should match to channel in the input\"\n        # output_shape Tensor. NHWC layout\n        output_shape_tensor = input_tensors[0]\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type = output_tensor.tensor.Type()\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor_type)\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.TransposeConvOptions\n        op_options = op.BuiltinOptions()\n        deconv_options = TransposeConvOptions()\n        deconv_options.Init(op_options.Bytes, op_options.Pos)\n\n        padding = deconv_options.Padding()\n        stride_h = deconv_options.StrideH()\n        stride_w = deconv_options.StrideW()\n        assert padding in (\n            Padding.VALID,\n            Padding.SAME,\n        ), \"Padding format {} is not supported for operator TRANSPOSE_CONV\".format(padding)\n\n        # Data\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # Weights\n        weights_tensor_type = weights_tensor.tensor.Type()\n        # weights tensor type should be UINT8 (quantization) or FLOAT32\n        assert weights_tensor_type in (TensorType.INT8, TensorType.UINT8, TensorType.FLOAT32)\n        weight_tensor_type_str = self.get_tensor_type_str(weights_tensor_type)\n\n        if self.has_expr(weights_tensor.tensor_idx):\n            weight_expr_iohw = self.get_expr(weights_tensor.tensor_idx)\n            weight_expr_iohw = _op.transpose(weight_expr_iohw, axes=(3, 0, 1, 2))\n        else:\n            weight_value_ohwi = self.get_tensor_value(weights_tensor)\n            # Relay kernel_layout should be OIHW\n            # Relay weights layout should be different from kernel_layout - it should be IOHW\n            weight_value_iohw = np.transpose(weight_value_ohwi, (3, 0, 1, 2))\n            weight_expr_iohw = self.exp_tab.new_const(\n                weight_value_iohw, dtype=weight_tensor_type_str\n            )\n\n        # Output shape value\n        output_shape_value = self.get_tensor_value(output_shape_tensor)\n        # Relay expects filter output channel to match to output tensor channel.\n        assert (\n            out_channels == output_shape_value[3]\n        ), \"Output channel in the filter should match to channel in the output_shape\"\n\n        if padding == Padding.SAME:\n            output_h, output_w = output_shape_value[1], output_shape_value[2]\n            pad_top, pad_bottom = get_pad_value(output_h, kernel_h, stride_h)\n            pad_left, pad_right = get_pad_value(output_w, kernel_w, stride_w)\n            padding = (pad_top, pad_left, pad_bottom, pad_right)\n        else:\n            padding = (0, 0, 0, 0)\n\n        if input_tensor.qnn_params:\n            input_zero_point = input_tensor.qnn_params[\"zero_point\"]\n            kernel_zero_point = weights_tensor.qnn_params[\"zero_point\"]\n            input_scale = input_tensor.qnn_params[\"scale\"]\n            kernel_scale = weights_tensor.qnn_params[\"scale\"]\n            out = _qnn.op.conv2d_transpose(\n                in_expr,\n                weight_expr_iohw,\n                input_zero_point,\n                kernel_zero_point,\n                input_scale,\n                kernel_scale,\n                strides=(stride_h, stride_w),\n                padding=padding,\n                channels=int(out_channels),\n                kernel_size=(int(kernel_h), int(kernel_w)),\n                data_layout=\"NHWC\",\n                kernel_layout=\"IOHW\",\n                out_dtype=\"int32\",\n            )\n        else:\n            out = _op.nn.conv2d_transpose(\n                in_expr,\n                weight_expr_iohw,\n                strides=(stride_h, stride_w),\n                padding=padding,\n                channels=int(out_channels),\n                kernel_size=(int(kernel_h), int(kernel_w)),\n                data_layout=\"NHWC\",\n                kernel_layout=\"IOHW\",\n                out_dtype=output_tensor_type_str,\n            )\n\n        # Checking if there is a fused bias\n        if len(input_tensors) == 4:\n            bias_tensor = input_tensors[3]\n            bias_tensor_type = bias_tensor.tensor.Type()\n            # bias tensor type should be INT32 (quantization) or FLOAT32\n            assert bias_tensor_type in (TensorType.INT32, TensorType.FLOAT32)\n            bias_tensor_type_str = self.get_tensor_type_str(bias_tensor_type)\n            if self.has_expr(bias_tensor.tensor_idx):\n                bias_expr = self.get_expr(bias_tensor.tensor_idx)\n            else:\n                bias_expr = self.exp_tab.new_const(\n                    self.get_tensor_value(bias_tensor), dtype=bias_tensor_type_str\n                )\n            channel_axis = 3\n            out = _op.nn.bias_add(out, bias_expr, axis=channel_axis)\n\n        if output_tensor.qnn_params:\n            # Calculate the intermediate scale and zero point of the int32 output.\n            data_scale = input_tensor.qnn_params[\"scale\"]\n            data_scale_val = get_scalar_from_constant(data_scale)\n\n            weight_scale = weights_tensor.qnn_params[\"scale\"]\n            # If weight scale is scalar, it is per-tensor quantization\n            if isinstance(weight_scale, float):\n                weight_scale_val = get_scalar_from_constant(weight_scale)\n            else:\n                weight_scale_val = get_tensor_from_constant(weight_scale)\n\n            new_input_scale_val = data_scale_val * weight_scale_val\n            new_input_scale = relay.const(new_input_scale_val, \"float32\")\n            new_input_zero_point = relay.const(0, \"int32\")\n\n            out = _qnn.op.requantize(\n                out,\n                input_scale=new_input_scale,\n                input_zero_point=new_input_zero_point,\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n                axis=3,\n            )\n        return out\n\n    def convert_quantize(self, op):\n        \"\"\"Convert TFLite Quantize\"\"\"\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n        input_tensor_type_str = self.get_tensor_type_str(input_tensor.tensor.Type())\n        in_expr = self.get_tensor_expr(input_tensor)\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n        output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())\n\n        # The output must be quantized\n        assert output_tensor.qnn_params\n\n        # TFLite Quantize op can also act as Requantize op\n        if input_tensor_type_str == \"float32\":\n            out = self.quantize(in_expr, output_tensor)\n        else:\n            out = _qnn.op.requantize(\n                in_expr,\n                input_scale=input_tensor.qnn_params[\"scale\"],\n                input_zero_point=input_tensor.qnn_params[\"zero_point\"],\n                output_scale=output_tensor.qnn_params[\"scale\"],\n                output_zero_point=output_tensor.qnn_params[\"zero_point\"],\n                out_dtype=output_tensor_type_str,\n            )\n        return out\n\n    def convert_dequantize(self, op):\n        \"\"\"Convert TFLite Dequantize\"\"\"\n        try:\n            from tflite.TensorType import TensorType\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n        input_tensor = input_tensors[0]\n\n        if input_tensor.tensor.Type() == TensorType.FLOAT16:\n            dtype = self.get_tensor_type_str(input_tensor.tensor.Type())\n            input_value = self.get_tensor_value(input_tensor)\n            in_expr = self.exp_tab.new_const(input_value, dtype=dtype)\n            out = relay.cast(in_expr, dtype=\"float32\")\n            return out\n\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        # The input must be quantized\n        assert input_tensor.qnn_params\n        # Dequantize the input.\n        out = self.dequantize(in_expr, input_tensor)\n\n        return out\n\n    def convert_detection_postprocess(self, op):\n        \"\"\"Convert TFLite_Detection_PostProcess\"\"\"\n        flexbuffer = op.CustomOptionsAsNumpy().tobytes()\n        custom_options = FlexBufferDecoder(flexbuffer).decode()\n\n        if \"use_regular_nms\" in custom_options:\n            if custom_options[\"use_regular_nms\"]:\n                raise tvm.error.OpAttributeUnImplemented(\n                    \"use_regular_nms=True is not yet supported for operator {}.\".format(\n                        \"TFLite_Detection_PostProcess\"\n                    )\n                )\n\n        inputs = self.get_input_tensors(op)\n        assert len(inputs) == 3, \"inputs length should be 3\"\n        cls_pred = self.get_expr(inputs[1].tensor_idx)\n        loc_prob = self.get_expr(inputs[0].tensor_idx)\n        batch_size = inputs[1].tensor.Shape(0)\n        anchor_values = self.get_tensor_value(inputs[2])\n        anchor_boxes = len(anchor_values)\n        anchor_type = self.get_tensor_type_str(inputs[2].tensor.Type())\n        anchor_expr = self.exp_tab.new_const(anchor_values, dtype=anchor_type)\n\n        if inputs[0].qnn_params:\n            loc_prob = _qnn.op.dequantize(\n                data=loc_prob,\n                input_scale=inputs[0].qnn_params[\"scale\"],\n                input_zero_point=inputs[0].qnn_params[\"zero_point\"],\n            )\n        if inputs[1].qnn_params:\n            cls_pred = _qnn.op.dequantize(\n                data=cls_pred,\n                input_scale=inputs[1].qnn_params[\"scale\"],\n                input_zero_point=inputs[1].qnn_params[\"zero_point\"],\n            )\n        if inputs[2].qnn_params:\n            anchor_expr = _qnn.op.dequantize(\n                data=anchor_expr,\n                input_scale=inputs[2].qnn_params[\"scale\"],\n                input_zero_point=inputs[2].qnn_params[\"zero_point\"],\n            )\n\n        # reshape the cls_pred and loc_prob tensors so\n        # they can be consumed by multibox_transform_loc\n        cls_pred = _op.transpose(cls_pred, [0, 2, 1])\n        # loc_prob coords are in yxhw format\n        # need to convert to xywh\n        loc_coords = _op.split(loc_prob, 4, axis=2)\n        loc_prob = _op.concatenate(\n            [loc_coords[1], loc_coords[0], loc_coords[3], loc_coords[2]], axis=2\n        )\n        loc_prob = _op.reshape(loc_prob, [batch_size, anchor_boxes * 4])\n\n        # anchor coords are in yxhw format\n        # need to convert to ltrb\n        anchor_coords = _op.split(anchor_expr, 4, axis=1)\n        anchor_y = anchor_coords[0]\n        anchor_x = anchor_coords[1]\n        anchor_h = anchor_coords[2]\n        anchor_w = anchor_coords[3]\n        plus_half = _expr.const(0.5, dtype=\"float32\")\n        minus_half = _expr.const(-0.5, dtype=\"float32\")\n        anchor_l = _op.add(anchor_x, _op.multiply(anchor_w, minus_half))\n        anchor_r = _op.add(anchor_x, _op.multiply(anchor_w, plus_half))\n        anchor_t = _op.add(anchor_y, _op.multiply(anchor_h, minus_half))\n        anchor_b = _op.add(anchor_y, _op.multiply(anchor_h, plus_half))\n        anchor_expr = _op.concatenate([anchor_l, anchor_t, anchor_r, anchor_b], axis=1)\n        anchor_expr = _op.expand_dims(anchor_expr, 0)\n\n        # attributes for multibox_transform_loc\n        multibox_transform_loc_attrs = {}\n        multibox_transform_loc_attrs[\"clip\"] = False\n        multibox_transform_loc_attrs[\"threshold\"] = custom_options[\"nms_score_threshold\"]\n        multibox_transform_loc_attrs[\"variances\"] = (\n            1 / custom_options[\"x_scale\"],\n            1 / custom_options[\"y_scale\"],\n            1 / custom_options[\"w_scale\"],\n            1 / custom_options[\"h_scale\"],\n        )\n\n        # attributes for non_max_suppression\n        non_max_suppression_attrs = {}\n        non_max_suppression_attrs[\"return_indices\"] = False\n        non_max_suppression_attrs[\"iou_threshold\"] = custom_options[\"nms_iou_threshold\"]\n        non_max_suppression_attrs[\"force_suppress\"] = True\n        non_max_suppression_attrs[\"top_k\"] = anchor_boxes\n        non_max_suppression_attrs[\"max_output_size\"] = custom_options[\"max_detections\"]\n        non_max_suppression_attrs[\"invalid_to_bottom\"] = False\n\n        ret = _op.vision.multibox_transform_loc(\n            cls_pred, loc_prob, anchor_expr, **multibox_transform_loc_attrs\n        )\n        ret = _op.vision.non_max_suppression(ret[0], ret[1], ret[1], **non_max_suppression_attrs)\n        ret = _op.vision.get_valid_counts(ret, 0)\n        valid_count = ret[0]\n        # keep only the top 'max_detections' rows\n        ret = _op.strided_slice(\n            ret[1], [0, 0, 0], [batch_size, custom_options[\"max_detections\"], 6]\n        )\n        # the output needs some reshaping to match tflite\n        ret = _op.split(ret, 6, axis=2)\n        cls_ids = _op.reshape(ret[0], [batch_size, -1])\n        scores = _op.reshape(ret[1], [batch_size, -1])\n        boxes = _op.concatenate([ret[3], ret[2], ret[5], ret[4]], axis=2)\n        ret = _expr.TupleWrapper(_expr.Tuple([boxes, cls_ids, scores, valid_count]), size=4)\n        return ret\n\n    def convert_nms_v5(self, op):\n        \"\"\"Convert TFLite NonMaxSuppressionV5\"\"\"\n        # https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/non-max-suppression-v5\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 6, \"input tensor length should be 6\"\n        boxes = self.get_expr(input_tensors[0].tensor_idx)\n        scores = self.get_expr(input_tensors[1].tensor_idx)\n        max_output_size = self.get_tensor_value(input_tensors[2])\n        iou_threshold = self.get_tensor_value(input_tensors[3])\n        score_threshold = self.get_tensor_value(input_tensors[4])\n        soft_nms_sigma = self.get_tensor_value(input_tensors[5])\n\n        if isinstance(max_output_size, np.ndarray):\n            assert max_output_size.size == 1, \"only one value is expected.\"\n            max_output_size = int(max_output_size)\n\n        if isinstance(iou_threshold, np.ndarray):\n            assert iou_threshold.size == 1, \"only one value is expected.\"\n            iou_threshold = float(iou_threshold)\n\n        if isinstance(score_threshold, np.ndarray):\n            assert score_threshold.size == 1, \"only one value is expected.\"\n            score_threshold = float(score_threshold)\n\n        if isinstance(soft_nms_sigma, np.ndarray):\n            assert soft_nms_sigma.size == 1, \"only one value is expected.\"\n            soft_nms_sigma = float(soft_nms_sigma)\n        if soft_nms_sigma != 0.0:\n            raise tvm.error.OpNotImplemented(\n                \"It is soft_nms when soft_nms_sigma != 0, which is not supported!\"\n            )\n\n        scores_expand = _op.expand_dims(scores, axis=-1, num_newaxis=1)\n        data = _op.concatenate([scores_expand, boxes], -1)\n        data = _op.expand_dims(data, axis=0, num_newaxis=1)\n\n        count, data, indices = _op.vision.get_valid_counts(\n            data, score_threshold=score_threshold, id_index=-1, score_index=0\n        )\n\n        nms_ret = _op.vision.non_max_suppression(\n            data=data,\n            valid_count=count,\n            indices=indices,\n            max_output_size=max_output_size,\n            iou_threshold=iou_threshold,\n            force_suppress=True,\n            top_k=-1,\n            coord_start=1,\n            score_index=0,\n            id_index=-1,\n            return_indices=True,\n            invalid_to_bottom=False,\n        )\n\n        selected_indices = _op.squeeze(nms_ret[0], axis=[0])\n        selected_indices = _op.strided_slice(selected_indices, [0], [max_output_size])\n        valide_num = _op.squeeze(nms_ret[1], axis=[1])\n        selected_scores = _op.take(scores, selected_indices, axis=0)\n        out = _expr.TupleWrapper(_expr.Tuple([selected_indices, selected_scores, valide_num]), 3)\n        return out\n\n    def convert_expand_dims(self, op):\n        \"\"\"Convert TFLite EXPAND_DIMS\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n        if input_tensors[0].qnn_params:\n            # Check that input and output tensor have same qnn params.\n            output_tensors = self.get_output_tensors(op)\n            assert self.has_same_qnn_params(\n                input_tensors[0], output_tensors[0]\n            ), \"TFLite EXPAND_DIMS requires input and output tensors' \\\n                    scale and zero points to be equal\"\n\n        input_expr = self.get_tensor_expr(input_tensors[0])\n        axis = self.get_tensor_value(input_tensors[1])\n        if isinstance(axis, np.ndarray):\n            assert axis.size == 1, \"only one value is expected.\"\n            axis = int(axis)\n\n        ndims = len(input_tensors[0].tensor.ShapeAsNumpy())\n        assert -1 - ndims <= axis <= ndims, \"axis out of range\"\n\n        out = _op.expand_dims(input_expr, axis, 1)\n\n        return out\n\n    def convert_one_hot(self, op):\n        \"\"\"Convert TFLite ONE_HOT\"\"\"\n        try:\n            from tflite.BuiltinOptions import BuiltinOptions\n            from tflite.OneHotOptions import OneHotOptions\n        except ImportError:\n            raise ImportError(\"The tflite package must be installed\")\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 4, \"Input tensor's length should be 4\"\n\n        # Ensuring input isn't quantized\n        assert all(not i.qnn_params for i in input_tensors), \"Quantized input is not expected.\"\n\n        # TFlite ONE_HOT requires both on_value\n        # and off_value, making dtype redundant.\n        indices = input_tensors[0]\n        depth = input_tensors[1]\n        on_value = input_tensors[2]\n        off_value = input_tensors[3]\n\n        assert (\n            on_value.tensor.Type() == off_value.tensor.Type()\n        ), \"on_value and off_value should be the same type\"\n\n        # Getting relay expr\n        indices_expr = self.get_expr(indices.tensor_idx)\n        on_value_expr = self.get_expr(on_value.tensor_idx)\n        off_value_expr = self.get_expr(off_value.tensor_idx)\n\n        # Getting depth value\n        depth = self.get_tensor_value(depth)\n        if isinstance(depth, np.ndarray):\n            depth = int(depth)\n\n        # Getting Axis from Option (Attributes)\n        assert op.BuiltinOptionsType() == BuiltinOptions.OneHotOptions\n        op_options = op.BuiltinOptions()\n        one_hot_options = OneHotOptions()\n        one_hot_options.Init(op_options.Bytes, op_options.Pos)\n        axis = one_hot_options.Axis()\n\n        # Setting dtype\n        dtype = self.get_tensor_type_str(on_value.tensor.Type())\n\n        out = _op.one_hot(indices_expr, on_value_expr, off_value_expr, depth, axis, dtype)\n\n        return out\n\n    def convert_reverse_v2(self, op):\n        \"\"\"Convert TFLite REVERSE_V2\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensor's length should be 2\"\n\n        input_expr = self.get_expr(input_tensors[0].tensor_idx)\n\n        # Getting axis value\n        axis = self.get_tensor_value(input_tensors[1])\n        if isinstance(axis, np.ndarray):\n            assert len(axis) == 1, \"TFLite does not support multi-axis yet\"\n            axis = int(axis)\n\n        out = _op.reverse(input_expr, axis)\n        return out\n\n    def convert_matrix_set_diag(self, op):\n        \"\"\"Convert TFLite MATRIX_SET_DIAG\"\"\"\n\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 2, \"input tensor's length should be 2\"\n\n        assert (\n            input_tensors[0].tensor.Type() == input_tensors[1].tensor.Type()\n        ), \"input and diagonal should be the same type of tensors\"\n\n        if input_tensors[0].qnn_params:\n            # Check that input and output tensor have same qnn params.\n            output_tensors = self.get_output_tensors(op)\n            assert self.has_same_qnn_params(\n                input_tensors[0], output_tensors[0]\n            ), \"TFLite MATRIX_SET_DIAG requires input and output tensors' \\\n                    scale and zero points to be equal\"\n\n            # Check that input and diagonal tensor have same qnn params.\n            assert self.has_same_qnn_params(\n                input_tensors[0], input_tensors[1]\n            ), \"TFLite MATRIX_SET_DIAG requires input and diagonal tensors' \\\n                    scale and zero points to be equal\"\n\n        input_expr = self.get_tensor_expr(input_tensors[0])\n        diagonal_expr = self.get_tensor_expr(input_tensors[1])\n\n        out = _op.matrix_set_diag(input_expr, diagonal_expr)\n        return out\n\n    def convert_matrix_diag(self, op):\n        \"\"\"Convert TFLite MATRIX_DIAG\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensor's length should be 1\"\n\n        diagonal = input_tensors[0]\n\n        if diagonal.qnn_params:\n            # Check that diagonal and output tensor have same qnn params.\n            output_tensors = self.get_output_tensors(op)\n            assert self.has_same_qnn_params(\n                diagonal, output_tensors[0]\n            ), \"TFLite MATRIX_DIAG requires diagonal and output tensors' \\\n                    scale and zero points to be equal\"\n\n        shape = to_int_list(self.get_tensor_shape(diagonal))\n        shape = np.append(shape, shape[-1])\n        dtype = self.get_tensor_type_str(diagonal.tensor.Type())\n\n        input_expr = _op.zeros(tuple(shape), dtype)\n        diagonal_expr = self.get_tensor_expr(diagonal)\n\n        out = _op.matrix_set_diag(input_expr, diagonal_expr)\n        return out\n\n    def convert_densify(self, op):\n        \"\"\"Convert TFLite DENSIFY\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        output_tensors = self.get_output_tensors(op)\n        assert len(output_tensors) == 1, \"output tensors length should be 1\"\n        output_tensor = output_tensors[0]\n\n        sparse_weight_tensor = input_tensors[0]\n        sparse_weight_tensor_type_str = self.get_tensor_type_str(sparse_weight_tensor.tensor.Type())\n\n        # NOTE: With current implementation in TFLite, Densify Op does not need to be present\n        # in runtime.\n        # TODO(ANSHUMAN87): we need to use the sparse_indices output\n        # from below function and use that in sparse_to_dense Op.\n        # Once the stack corruption issue is resolved in sparse_to_dense Op.\n        _, dense_weight = prepare_dense_matrix_from_sparse(\n            sparse_weight_tensor.tensor,\n            self.get_tensor_value(sparse_weight_tensor, is_sparse=True),\n            sparse_weight_tensor_type_str,\n        )\n\n        self.set_prefetched_node(output_tensor.tensor_idx, dense_weight)\n\n    def convert_fake_quant(self, op):\n        \"\"\"Convert TFLite FAKE_QUANT\"\"\"\n        input_tensors = self.get_input_tensors(op)\n        assert len(input_tensors) == 1, \"input tensors length should be 1\"\n\n        input_tensor = input_tensors[0]\n        in_expr = self.get_expr(input_tensor.tensor_idx)\n\n        from tflite.BuiltinOptions import BuiltinOptions\n        from tflite.FakeQuantOptions import FakeQuantOptions\n\n        assert op.BuiltinOptionsType() == BuiltinOptions.FakeQuantOptions\n\n        op_options = op.BuiltinOptions()\n        fake_quant_options = FakeQuantOptions()\n        fake_quant_options.Init(op_options.Bytes, op_options.Pos)\n\n        opt_min = fake_quant_options.Min()\n        opt_max = fake_quant_options.Max()\n        narrow_range = fake_quant_options.NarrowRange()\n        num_bits = fake_quant_options.NumBits()\n\n        assert 2 <= num_bits <= 16\n\n        quant_min = 1 if narrow_range else 0\n        quant_max = (1 << num_bits) - 1\n        scale = (opt_max - opt_min) / (quant_max - quant_min)\n\n        zero_point_from_min = quant_min - opt_min / scale\n        if zero_point_from_min <= quant_min:\n            nudged_zero_point = quant_min\n        elif zero_point_from_min >= quant_max:\n            nudged_zero_point = quant_max\n        else:\n            nudged_zero_point = round(zero_point_from_min)\n\n        nudged_min = (quant_min - nudged_zero_point) * scale\n        nudged_max = (quant_max - nudged_zero_point) * scale\n\n        nudged_min_expr = _op.const(nudged_min)\n        clamped = _op.clip(in_expr, nudged_min, nudged_max)\n        clamped_shifted = _op.subtract(clamped, nudged_min_expr)\n\n        half = _op.const(0.5)\n        one = _op.const(1.0)\n        scale_expr = _op.const(scale)\n        inv_scale = _op.divide(one, scale_expr)\n        rounded = _op.floor(_op.add(_op.multiply(clamped_shifted, inv_scale), half))\n        return _op.add(_op.multiply(rounded, scale_expr), nudged_min_expr)\n\n    def get_expr(self, input_tensor_idx):\n        return self.exp_tab.get_expr(get_tensor_name(self.subgraph, input_tensor_idx))\n\n    def has_expr(self, input_tensor_idx):\n        return self.exp_tab.has_expr(get_tensor_name(self.subgraph, input_tensor_idx))\n\n    def is_prefetched(self, input_tensor_idx):\n        return (\n            self.prefetched_nodes.get(get_tensor_name(self.subgraph, input_tensor_idx)) is not None\n        )\n\n    def set_prefetched_node(self, input_tensor_idx, value):\n        self.prefetched_nodes[get_tensor_name(self.subgraph, input_tensor_idx)] = value\n\n    def get_prefetched_node(self, input_tensor_idx):\n        return self.prefetched_nodes[get_tensor_name(self.subgraph, input_tensor_idx)]\n\n    def get_tensor_expr(self, tensor, is_sparse=False):\n        \"\"\"Return the Relay expr for tensor.\"\"\"\n        if self.has_expr(tensor.tensor_idx):\n            expr = self.get_expr(tensor.tensor_idx)\n        else:\n            type_str = self.get_tensor_type_str(tensor.tensor.Type())\n            expr = self.exp_tab.new_const(self.get_tensor_value(tensor, is_sparse), dtype=type_str)\n        return expr\n\n    def get_tensor_shape(self, tensor_wrapper):\n        \"\"\"Returns tensor shape. Infers shape if the shape is empty.\"\"\"\n        assert isinstance(tensor_wrapper, TensorWrapper), \"Expecting TensorWrapper here\"\n        return (\n            tensor_wrapper.tensor.ShapeAsNumpy()\n            if tensor_wrapper.tensor.ShapeLength() > 0\n            else _infer_shape(self.get_tensor_expr(tensor_wrapper))\n        )\n\n\n# pylint: disable=no-else-return\ndef prepare_dense_matrix_from_sparse(sparse_tensor, sparse_tensor_value, sparse_tensor_type):\n    \"\"\"Prepare sparse indices and dense matrix from TFLite sparse parameters.\"\"\"\n    # The function is implemented based on TFLite sparse parameter specifications\n    # Please refer\n    # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/schema/schema.fbs#L89\n    # for details about each parameters\n    sparsity = sparse_tensor.Sparsity()\n    dense_shape = sparse_tensor.ShapeAsNumpy()\n    orig_rank = len(dense_shape)\n\n    # The traversal order of the dimensions defined in the `shape` field of the to be dense tensor.\n    traversal_order = sparsity.TraversalOrderAsNumpy()\n\n    # For an n-dimensional tensor with a k-dimensional block (0 <= k <= n),\n    # stores how a block dimension in (dn, ..., dn+k-1) maps to the original\n    # tensor dimension in (d0, ..., dn). It's stored in the order of (dn, ..., dn+k-1).\n    # If not block-sparse, this field is NULL.\n    block_map = sparsity.BlockMapAsNumpy()\n\n    total_rank = sparsity.TraversalOrderLength()\n    dense_mat = np.full(shape=dense_shape, fill_value=0, dtype=sparse_tensor_type).flatten()\n\n    from enum import Enum\n\n    # NOTE: Here the Vector term is borrowed from TFLite spec.\n    class VectorType(Enum):\n        Empty = 0\n        Int32 = 1\n        Uint16 = 2\n        Uint8 = 3\n\n    def _get_vector_flag(v_type):\n        if VectorType(v_type) == VectorType.Int32:\n            return N.Int32Flags\n        elif VectorType(v_type) == VectorType.Uint16:\n            return N.Uint16Flags\n        elif VectorType(v_type) == VectorType.Uint8:\n            return N.Uint8Flags\n        else:\n            raise tvm.error.OpNotImplemented(\"The provided type {} is not supported\".format(v_type))\n\n    def _get_flattened_index(indices, shape):\n        index = 0\n        sub_elements = 1\n        for i in reversed(range(0, len(dense_shape))):\n            index += indices[i] * sub_elements\n            sub_elements *= shape[i]\n        return index\n\n    # DimensionMetadata per dimension: the metadata needed for\n    #     each dimension to locate the non-zero values in the original dense tensor\n    #     inline with traversal order parameter.\n    #\n    # sp_format has 2 possible values: {DENSE = 0, SPARSE_CSR = 1}\n    # If format = DENSE{0} : DenseSize represents size of that dimension\n    # If format = SPARSE_CSR{1} : array_segments represents how to segment the indices array,\n    #      each segment corresponds to one element in the previous dimension. array_indices\n    #      represents the index of the non-zero elements within this dimension\n    #      (as those in the CSR matrix format, where the first array is row pointers\n    #       and the second array is column indices).\n    sp_format = np.zeros(sparsity.DimMetadataLength())\n    dim_metadata = [None] * (2 * sparsity.DimMetadataLength())\n\n    # Below loop will fetch all meta data per dimension based on format type\n    # Dense or Sparse and will put it in an agnostic array for easy access\n    # while preparing dense buffer or indices.\n    for i in range(sparsity.DimMetadataLength()):\n        sp_format[i] = sparsity.DimMetadata(i).Format()\n        if sp_format[i] == 0:\n            dim_metadata[2 * i] = [sparsity.DimMetadata(i).DenseSize()]\n        else:\n            from flatbuffers import number_types as N\n\n            dim_metadata[2 * i] = (\n                sparsity.DimMetadata(i)\n                .ArraySegments()\n                .GetVectorAsNumpy(\n                    flags=_get_vector_flag(sparsity.DimMetadata(i).ArraySegmentsType()), off=4\n                )\n            )\n            dim_metadata[2 * i + 1] = (\n                sparsity.DimMetadata(i)\n                .ArrayIndices()\n                .GetVectorAsNumpy(\n                    flags=_get_vector_flag(sparsity.DimMetadata(i).ArrayIndicesType()), off=4\n                )\n            )\n\n    block_dim = 0\n    block_size = np.zeros(sparsity.BlockMapLength())\n\n    # Block size parameter if encoded in BSR format\n    for i in range(orig_rank):\n        if block_dim < sparsity.BlockMapLength() and block_map[block_dim] == i:\n            orig_dim = traversal_order[orig_rank + block_dim]\n            block_size[block_dim] = sparsity.DimMetadata(orig_dim).DenseSize()\n            block_dim += 1\n\n    indices_list = []\n\n    # Below function iterates through each applicable indices per dimension\n    # based on format type specified and finally produce the dense matrix and the NZ indices.\n    def _def_prepare_dense_matrix_from_sparse(indices, level, prev_idx):\n        if level == len(indices):\n            start_pos = 0\n            orig_idx = np.zeros(orig_rank, dtype=\"int32\")\n            while start_pos < orig_rank:\n                orig_idx[traversal_order[start_pos]] = indices[start_pos]\n                start_pos += 1\n            while start_pos < len(indices):\n                block_idx = traversal_order[start_pos] - orig_rank\n                orig_dim = block_map[block_idx]\n                orig_idx[orig_dim] = orig_idx[orig_dim] * block_size[block_idx] + indices[start_pos]\n                start_pos += 1\n            indices_list.append(orig_idx)\n            nonlocal value_idx\n            dense_mat[_get_flattened_index(orig_idx, dense_shape)] = sparse_tensor_value[value_idx]\n            value_idx += 1\n        else:\n            metadata_idx = 2 * level\n            if sp_format[level] == 0:\n                shape_of_level = dim_metadata[metadata_idx][0]\n                for idx in range(shape_of_level):\n                    indices[level] = idx\n                    _def_prepare_dense_matrix_from_sparse(\n                        indices, level + 1, prev_idx * shape_of_level + idx\n                    )\n            else:\n                array_segments = dim_metadata[metadata_idx]\n                array_indices = dim_metadata[metadata_idx + 1]\n                for idx in range(array_segments[prev_idx], array_segments[prev_idx + 1]):\n                    indices[level] = array_indices[idx]\n                    _def_prepare_dense_matrix_from_sparse(indices, level + 1, idx)\n\n    indices = np.zeros(total_rank)\n    value_idx = 0\n    _def_prepare_dense_matrix_from_sparse(indices, 0, 0)\n    return np.array(indices_list, dtype=\"int32\"), dense_mat.reshape(dense_shape)\n\n\ndef get_scalar_from_constant(expr):\n    \"\"\"Returns scalar value from Relay constant scalar.\"\"\"\n    assert (\n        isinstance(expr, _expr.Constant) and not expr.data.shape\n    ), \"Expr is not a constant scalar.\"\n    value = expr.data.numpy()\n    assert value.dtype == np.dtype(np.int32) or value.dtype == np.dtype(\n        np.float32\n    ), \"value must be float32/int32\"\n    return value.item(0)\n\n\ndef get_tensor_from_constant(expr):\n    \"\"\"Returns tensor of values from Relay constant node.\"\"\"\n    assert isinstance(expr, _expr.Constant)\n    value = expr.data.numpy()\n    assert value.dtype == np.dtype(np.int32) or value.dtype == np.dtype(\n        np.float32\n    ), \"value must be float32/int32\"\n    return value\n\n\ndef build_str_map(obj):\n    \"\"\"Build string map of TFLite enum int value\n\n    Parameters\n    ----------\n    obj:\n        TFLite class which contains enum int value, such as BuiltInOptions\n\n    Returns\n    -------\n        String representation map of TFLite class enum int value\n    \"\"\"\n    ret = {}\n    for field_name in dir(obj):\n        if not field_name.startswith(\"_\"):\n            field_value = getattr(obj, field_name)\n            if isinstance(field_value, int):\n                ret[field_value] = field_name\n    return ret\n\n\n# SAME padding: https://www.tensorflow.org/api_guides/python/nn\ndef get_pad_value(data, kernel, stride):\n    \"\"\"Get the pad tuple of value for SAME padding\n\n    Parameters\n    ----------\n    data:\n        1D input data\n\n    kernel:\n        1D input kernel\n\n    stride:\n        1D input stride\n\n    Returns\n    -------\n        pad tuple of value\n    \"\"\"\n\n    out = int(math.ceil(float(data) / float(stride)))\n    pad = max(0, (out - 1) * stride + kernel - data)\n    pad_before = pad // 2\n    pad_after = pad - pad_before\n    return pad_before, pad_after\n\n\ndef get_tensor_name(subgraph, tensor_idx):\n    \"\"\"Get the tensor name.\n\n    Parameters\n    ----------\n    subgraph:\n        tflite.Subgraph.Subgraph\n\n    tensor:\n        tensor index in subgraph\n\n    Returns\n    -------\n        tensor name in UTF-8 encoding\n    \"\"\"\n    return subgraph.Tensors(tensor_idx).Name().decode(\"utf-8\")\n\n\ndef _decode_type(n):\n    _tflite_m = {\n        0: \"float32\",\n        1: \"float16\",\n        2: \"int32\",\n        3: \"uint8\",\n        4: \"int64\",\n        5: \"string\",\n        6: \"bool\",\n        7: \"int16\",\n        8: \"complex64\",\n        9: \"int8\",\n    }\n    return _tflite_m[n]\n\n\ndef _input_type(model):\n    subgraph_count = model.SubgraphsLength()\n    assert subgraph_count > 0\n    shape_dict = {}\n    dtype_dict = {}\n    for subgraph_index in range(subgraph_count):\n        subgraph = model.Subgraphs(subgraph_index)\n        inputs_count = subgraph.InputsLength()\n        assert inputs_count >= 1\n        for input_index in range(inputs_count):\n            input_ = subgraph.Inputs(input_index)\n            assert subgraph.TensorsLength() > input_\n            tensor = subgraph.Tensors(input_)\n            input_shape = tuple(tensor.ShapeAsNumpy())\n            tensor_type = tensor.Type()\n            input_name = tensor.Name().decode(\"utf8\")\n            shape_dict[input_name] = input_shape\n            dtype_dict[input_name] = _decode_type(tensor_type)\n\n    return shape_dict, dtype_dict\n\n\ndef from_tflite(model, shape_dict=None, dtype_dict=None, op_converter=OperatorConverter):\n    \"\"\"Convert from tflite model into compatible relay Function.\n\n    Parameters\n    ----------\n    model:\n        tflite.Model or tflite.Model.Model (depending on tflite version)\n\n    shape_dict : dict of str to int list/tuple\n        Input shapes of the model.\n\n    dtype_dict : dict of str to str\n        Input types of the model.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module for compilation.\n\n    params : dict of str to tvm.nd.NDArray\n        The parameter dict to be used by relay\n    \"\"\"\n    try:\n        import tflite.BuiltinOperator\n        import tflite.SubGraph\n    except ImportError:\n        raise ImportError(\"The tflite package must be installed\")\n\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite\n\n        assert isinstance(model, tflite.Model)\n    except TypeError:\n        import tflite.Model\n\n        assert isinstance(model, tflite.Model.Model)\n\n    _shape_dict, _dtype_dict = _input_type(model)\n    if shape_dict is not None:\n        _shape_dict.update(shape_dict)\n    if dtype_dict is not None:\n        _dtype_dict.update(dtype_dict)\n\n    # keep the same as tflite\n    assert model.SubgraphsLength() == 1, \"only support one subgraph (main subgraph)\"\n    subgraph = model.Subgraphs(0)\n\n    # model inputs / outputs\n    model_inputs = subgraph.InputsAsNumpy()\n    model_outputs = subgraph.OutputsAsNumpy()\n\n    exp_tab = ExprTable()\n    for model_input in model_inputs:\n        model_input_name = get_tensor_name(subgraph, model_input)\n        shape = _shape_dict[model_input_name] if model_input_name in _shape_dict else None\n        dtype = _dtype_dict[model_input_name] if model_input_name in _dtype_dict else \"float32\"\n        exp_tab.set_expr(model_input_name, _expr.var(model_input_name, shape=shape, dtype=dtype))\n\n    # op code in model\n    op_converter = op_converter(model, subgraph, exp_tab)\n    op_converter.check_unsupported_ops()\n    op_converter.convert_op_to_relay()\n\n    # params and outputs\n    params = {k: _nd.array(np.array(v)) for k, v in exp_tab.params.items()}\n    outputs = [exp_tab.get_expr(get_tensor_name(subgraph, i)) for i in model_outputs]\n    outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n    attrs = tvm.ir.make_node(\n        \"DictAttrs\",\n        **{\n            \"output_tensor_names\": [\n                sanitize_name(get_tensor_name(subgraph, model_output))\n                for model_output in model_outputs\n            ]\n        },\n    )\n    func = _function.Function(analysis.free_vars(outputs), outputs, attrs=attrs)\n    mod = IRModule.from_expr(func)\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/frontend/tflite_flexbuffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, too-many-lines, import-outside-toplevel\n\"\"\"Tensorflow lite frontend helper to parse custom options in Flexbuffer format.\"\"\"\n\nimport struct\nfrom enum import IntEnum\n\n\nclass BitWidth(IntEnum):\n    \"\"\"Flexbuffer bit width schema from flexbuffers.h\"\"\"\n\n    BIT_WIDTH_8 = 0\n    BIT_WIDTH_16 = 1\n    BIT_WIDTH_32 = 2\n    BIT_WIDTH_64 = 3\n\n\nclass FlexBufferType(IntEnum):\n    \"\"\"Flexbuffer type schema from flexbuffers.h\"\"\"\n\n    FBT_NULL = 0\n    FBT_INT = 1\n    FBT_UINT = 2\n    FBT_FLOAT = 3\n    # Types above stored inline, types below store an offset.\n    FBT_KEY = 4\n    FBT_STRING = 5\n    FBT_INDIRECT_INT = 6\n    FBT_INDIRECT_UINT = 7\n    FBT_INDIRECT_FLOAT = 8\n    FBT_MAP = 9\n    FBT_VECTOR = 10  # Untyped.\n    FBT_VECTOR_INT = 11  # Typed any size (stores no type table).\n    FBT_VECTOR_UINT = 12\n    FBT_VECTOR_FLOAT = 13\n    FBT_VECTOR_KEY = 14\n    FBT_VECTOR_STRING = 15\n    FBT_VECTOR_INT2 = 16  # Typed tuple (no type table, no size field).\n    FBT_VECTOR_UINT2 = 17\n    FBT_VECTOR_FLOAT2 = 18\n    FBT_VECTOR_INT3 = 19  # Typed triple (no type table, no size field).\n    FBT_VECTOR_UINT3 = 20\n    FBT_VECTOR_FLOAT3 = 21\n    FBT_VECTOR_INT4 = 22  # Typed quad (no type table, no size field).\n    FBT_VECTOR_UINT4 = 23\n    FBT_VECTOR_FLOAT4 = 24\n    FBT_BLOB = 25\n    FBT_BOOL = 26\n    FBT_VECTOR_BOOL = 36  # To Allow the same type of conversion of type to vector type\n\n\nclass FlexBufferDecoder(object):\n    \"\"\"\n    This implements partial flexbuffer deserialization to be able\n    to read custom options. It is not intended to be a general\n    purpose flexbuffer deserializer and as such only supports a\n    limited number of types and assumes the data is a flat map.\n    \"\"\"\n\n    def __init__(self, buffer):\n        self.buffer = buffer\n\n    def indirect_jump(self, offset, byte_width):\n        \"\"\"Helper function to read the offset value and jump\"\"\"\n        unpack_str = \"\"\n        if byte_width == 1:\n            unpack_str = \"<B\"\n        elif byte_width == 4:\n            unpack_str = \"<i\"\n        assert unpack_str != \"\"\n        back_jump = struct.unpack(unpack_str, self.buffer[offset : offset + byte_width])[0]\n        return offset - back_jump\n\n    def decode_keys(self, end, size, byte_width):\n        \"\"\"Decodes the flexbuffer type vector. Map keys are stored in this form\"\"\"\n        # Keys are strings here. The format is all strings separated by null, followed by back\n        # offsets for each of the string. For example, (str1)\\0(str1)\\0(offset1)(offset2) The end\n        # pointer is pointing at the end of all strings\n        keys = list()\n        for i in range(0, size):\n            offset_pos = end + i * byte_width\n            start_index = self.indirect_jump(offset_pos, byte_width)\n            str_size = self.buffer[start_index:].find(b\"\\0\")\n            assert str_size != -1\n            s = self.buffer[start_index : start_index + str_size].decode(\"utf-8\")\n            keys.append(s)\n        return keys\n\n    def decode_vector(self, end, size, byte_width):\n        \"\"\"Decodes the flexbuffer vector\"\"\"\n        # Each entry in the vector can have different datatype. Each entry is of fixed length. The\n        # format is a sequence of all values followed by a sequence of datatype of all values. For\n        # example - (4)(3.56)(int)(float) The end here points to the start of the values.\n        values = list()\n        for i in range(0, size):\n            value_type_pos = end + size * byte_width + i\n            value_type = FlexBufferType(self.buffer[value_type_pos] >> 2)\n            value_bytes = self.buffer[end + i * byte_width : end + (i + 1) * byte_width]\n            if value_type == FlexBufferType.FBT_BOOL:\n                value = bool(value_bytes[0])\n            elif value_type == FlexBufferType.FBT_INT:\n                value = struct.unpack(\"<i\", value_bytes)[0]\n            elif value_type == FlexBufferType.FBT_UINT:\n                value = struct.unpack(\"<I\", value_bytes)[0]\n            elif value_type == FlexBufferType.FBT_FLOAT:\n                value = struct.unpack(\"<f\", value_bytes)[0]\n            else:\n                raise Exception\n            values.append(value)\n        return values\n\n    def decode_map(self, end, byte_width, parent_byte_width):\n        \"\"\"Decodes the flexbuffer map and returns a dict\"\"\"\n        mid_loc = self.indirect_jump(end, parent_byte_width)\n        map_size = struct.unpack(\"<i\", self.buffer[mid_loc - byte_width : mid_loc])[0]\n\n        # Find keys\n        keys_offset = mid_loc - byte_width * 3\n        keys_end = self.indirect_jump(keys_offset, byte_width)\n        keys = self.decode_keys(keys_end, map_size, 1)\n\n        # Find values\n        values_end = self.indirect_jump(end, parent_byte_width)\n        values = self.decode_vector(values_end, map_size, byte_width)\n        return dict(zip(keys, values))\n\n    def decode(self):\n        \"\"\"Decode the buffer. Decoding is partially implemented\"\"\"\n        root_end = len(self.buffer) - 1\n        root_byte_width = self.buffer[root_end]\n        root_end -= 1\n        root_packed_type = self.buffer[root_end]\n        root_end -= root_byte_width\n\n        root_type = FlexBufferType(root_packed_type >> 2)\n        byte_width = 1 << BitWidth(root_packed_type & 3)\n\n        if root_type == FlexBufferType.FBT_MAP:\n            return self.decode_map(root_end, byte_width, root_byte_width)\n        raise NotImplementedError(\"Flexbuffer Decoding is partially imlpemented.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/function.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, invalid-name, unused-import\n\"\"\"The expression nodes of Relay.\"\"\"\nfrom __future__ import absolute_import\n\nimport tvm._ffi\nfrom tvm.runtime import convert\nfrom tvm.ir import BaseFunc\n\nfrom .expr import Call\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"relay.Function\")\nclass Function(BaseFunc):\n    \"\"\"A function declaration expression.\n\n    Parameters\n    ----------\n    params: List[tvm.relay.Var]\n        List of input parameters to the function.\n\n    body: tvm.relay.Expr\n        The body of the function.\n\n    ret_type: Optional[tvm.relay.Type]\n        The return type annotation of the function.\n\n    type_params: Optional[List[tvm.relay.TypeParam]]\n        The additional type parameters, this is only\n        used in advanced usecase of template functions.\n    \"\"\"\n\n    def __init__(self, params, body, ret_type=None, type_params=None, attrs=None):\n        if type_params is None:\n            type_params = convert([])\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.Function, params, body, ret_type, type_params, attrs\n        )\n\n    def __call__(self, *args):\n        \"\"\"Invoke the global function.\n\n        Parameters\n        ----------\n        args: List[relay.Expr]\n            Arguments.\n        \"\"\"\n        return Call(self, args, None, None)\n\n\n@tvm._ffi.register_func(\"relay.FunctionWithFields\")\ndef FunctionWithFields(\n    function,\n    params=None,\n    body=None,\n    ret_type=None,\n    ty_params=None,\n    attrs=None,\n    virtual_device=None,\n    span=None,\n):\n    \"\"\"\n    Returns function with the given properties. A None property denotes 'no change'.\n    Returns function if all properties are unchanged. Otherwise, returns a copy with the new\n    fields.\n    \"\"\"\n    return _ffi_api.FunctionWithFields(\n        function, params, body, ret_type, ty_params, attrs, virtual_device, span\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/loops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"\nUtilities for building Relay loops.\n\"\"\"\nfrom .scope_builder import ScopeBuilder\nfrom . import expr as _expr\nfrom . import function as _function\n\n\ndef while_loop(cond, loop_vars, loop_bodies):\n    \"\"\"\n    Construct a while loop.\n\n    Parameters\n    ----------\n\n    cond: Callable[Tuple[relay.Expr], relay.Expr]\n        The condition of the loop.\n\n    loop_vars:  Tuple[relay.Expr]\n        The variables being looped over.\n        The initial values of the loop, will be used to\n        construct the loop variables.\n\n    loop_bodies: Callable[Tuple[relay.Expr], Tuple[relay.Expr]]\n        The body of the loop, should be a function which\n        given loop variables produces the output result\n        also as a tuple\n\n    Returns\n    -------\n    loop: relay.Expr\n        The loop expression.\n    \"\"\"\n    sb = ScopeBuilder()\n    loop = _expr.Var(\"while_loop\")\n    fresh_vars = []\n\n    for i, loop_var in enumerate(loop_vars):\n        name = loop_var.name_hint if isinstance(loop_var, _expr.Var) else \"arg{}\".format(i)\n        new_var = _expr.var(name, type_annotation=sb.type_of(loop_var))\n        fresh_vars.append(new_var)\n\n    with sb.if_scope(cond(*fresh_vars)):\n        sb.ret(loop(*loop_bodies(*fresh_vars)))\n    with sb.else_scope():\n        sb.ret(_expr.Tuple(fresh_vars))\n\n    func = _function.Function(fresh_vars, sb.get())\n    let = _expr.Let(loop, func, loop)\n    return let\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin\n\"\"\"Relay core operators.\"\"\"\n# operator defs\nfrom .op import (\n    get,\n    register_compute,\n    register_gradient,\n    register_pattern,\n    register_alter_op_layout,\n    register_legalize,\n    OpPattern,\n    OpStrategy,\n    debug,\n    register_external_compiler,\n    register_fake_quantization_to_integer,\n    register_mixed_precision_conversion,\n)\nfrom . import strategy\n\n# Operators\nfrom .reduce import *\nfrom .tensor import *\nfrom .transform import *\nfrom .algorithm import *\nfrom . import vm\nfrom . import nn\nfrom . import annotation\nfrom . import memory\nfrom . import image\nfrom . import vision\nfrom . import op_attrs\nfrom . import random\n\n\n# operator registry\nfrom . import _tensor\nfrom . import _tensor_grad\nfrom . import _transform\nfrom . import _reduce\nfrom . import _algorithm\nfrom . import _math\n\n\ndef _register_op_make():\n    # pylint: disable=import-outside-toplevel\n    from . import _make\n    from .. import expr\n\n    expr._op_make = _make\n\n\n_register_op_make()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_algorithm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"Definition of classic algorithms\"\n# pylint: disable=invalid-name,unused-argument\nfrom __future__ import absolute_import\n\nfrom tvm.te.hybrid import script\nfrom tvm.runtime import convert\n\nfrom . import strategy\nfrom . import op as _reg\nfrom .op import OpPattern, register_pattern\nfrom .op import register_strategy, register_shape_func\nfrom ._tensor import elemwise_shape_func\n\n# sort\nregister_strategy(\"sort\", strategy.sort_strategy)\nregister_pattern(\"sort\", OpPattern.OPAQUE)\nregister_shape_func(\"sort\", False, elemwise_shape_func)\n\n# argsort\nregister_strategy(\"argsort\", strategy.argsort_strategy)\nregister_pattern(\"argsort\", OpPattern.OPAQUE)\nregister_shape_func(\"argsort\", False, elemwise_shape_func)\n\n# topk\nregister_strategy(\"topk\", strategy.topk_strategy)\nregister_pattern(\"topk\", OpPattern.OPAQUE)\n\n# searchsorted\nregister_strategy(\"searchsorted\", strategy.searchsorted_strategy)\nregister_pattern(\"searchsorted\", OpPattern.OPAQUE)\n\n\n@script\ndef _topk_shape_func_input_shape(data_shape, k, axis):\n    ndim = data_shape.shape[0]\n    val_out = output_tensor((ndim,), \"int64\")\n    indices_out = output_tensor((ndim,), \"int64\")\n\n    for i in const_range(ndim):\n        if i != axis:\n            val_out[i] = int64(data_shape[i])\n            indices_out[i] = int64(data_shape[i])\n        else:\n            if k < 1:\n                val_out[i] = int64(data_shape[i])\n                indices_out[i] = int64(data_shape[i])\n            else:\n                val_out[i] = int64(k)\n                indices_out[i] = int64(k)\n    return val_out, indices_out\n\n\n@_reg.register_shape_func(\"topk\", False)\ndef topk_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for topk.\n    \"\"\"\n    axis = attrs.axis\n    if axis < 0:\n        axis += inputs[0].shape[0]\n    val_out, indices_out = _topk_shape_func_input_shape(inputs[0], attrs.k, convert(axis))\n    ret_type = attrs.ret_type\n    if ret_type == \"both\":\n        ret = [val_out, indices_out]\n    elif ret_type == \"values\":\n        ret = [val_out]\n    else:\n        ret = [indices_out]\n\n    return ret\n\n\n@script\ndef _searchsorted_shape(sorted_sequence_shape, values_shape):\n    out_shape = output_tensor((values_shape.shape[0],), \"int64\")\n    if sorted_sequence_shape.shape[0] > 1:\n        assert (\n            sorted_sequence_shape.shape[0] == values_shape.shape[0]\n        ), \"Ranks of `sorted_sequence` and values must be the same if `sorted_sequence` is not 1-D.\"\n    for i in range(values_shape.shape[0]):\n        if sorted_sequence_shape.shape[0] > 1 and i < values_shape.shape[0] - 1:\n            assert (\n                sorted_sequence_shape[i] == values_shape[i]\n            ), \"`sorted_sequence and `values` do not have the same shape along outer axes.\"\n\n        out_shape[i] = values_shape[i]\n    return out_shape\n\n\n@_reg.register_shape_func(\"searchsorted\", False)\ndef searchsorted_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for searchsorted operator.\n    \"\"\"\n    return [_searchsorted_shape(inputs[0], inputs[1])]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom . import op as _reg\nfrom . import strategy\n\n# einsum\n_reg.register_strategy(\"einsum\", strategy.einsum_strategy)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom __future__ import absolute_import\n\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\nfrom tvm.topi.utils import get_const_int, get_const_tuple\nfrom . import op as _reg\n\n_reg.register_reduce_schedule(\"argmax\")\n_reg.register_reduce_schedule(\"argmin\")\n_reg.register_reduce_schedule(\"sum\")\n_reg.register_reduce_schedule(\"all\")\n_reg.register_reduce_schedule(\"any\")\n_reg.register_reduce_schedule(\"max\")\n_reg.register_reduce_schedule(\"min\")\n_reg.register_reduce_schedule(\"prod\")\n_reg.register_reduce_schedule(\"mean\")\n_reg.register_reduce_schedule(\"variance\")\n\n\ndef _create_axis_record(attrs, inputs):\n    axes = attrs.axis if attrs.axis is None else list(get_const_tuple(attrs.axis))\n    exclude = get_const_int(attrs.exclude) > 0\n    keepdims = get_const_int(attrs.keepdims) > 0\n    data_shape = inputs[0]\n    shape_size = data_shape.shape[0].value\n    axis_record = [-1] * shape_size\n    if axes is None:\n        axes = list(range(shape_size))\n\n    for i, axis in enumerate(axes):\n        if axis < 0:\n            axes[i] = shape_size + axis\n\n    if exclude:\n        ex_axes = []\n        for i in range(shape_size):\n            if i not in axes:\n                ex_axes.append(i)\n        axes = ex_axes\n\n    for i in range(shape_size):\n        if i not in axes:\n            axis_record[i] = i\n\n    if not keepdims:\n        tmp = []\n        for i in axis_record:\n            if i >= 0:\n                tmp.append(i)\n        axis_record = tmp\n\n    return axis_record\n\n\n@script\ndef _reduce_shape_func(data_shape, axis_record):\n    out = output_tensor((len(axis_record),), \"int64\")\n    for i in const_range(len(axis_record)):\n        if axis_record[i] >= 0:\n            out[i] = data_shape[axis_record[i]]\n        else:\n            out[i] = int64(1)\n\n    return out\n\n\ndef reduce_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for reduce op.\n    \"\"\"\n    axis_record = _create_axis_record(attrs, inputs)\n    return [_reduce_shape_func(inputs[0], convert(axis_record))]\n\n\n_reg.register_shape_func(\"argmax\", False, reduce_shape_func)\n_reg.register_shape_func(\"argmin\", False, reduce_shape_func)\n_reg.register_shape_func(\"all\", False, reduce_shape_func)\n_reg.register_shape_func(\"sum\", False, reduce_shape_func)\n_reg.register_shape_func(\"max\", False, reduce_shape_func)\n_reg.register_shape_func(\"min\", False, reduce_shape_func)\n_reg.register_shape_func(\"prod\", False, reduce_shape_func)\n_reg.register_shape_func(\"mean\", False, reduce_shape_func)\n_reg.register_shape_func(\"variance\", False, reduce_shape_func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, len-as-condition\n\"\"\"Backend compiler related feature registration\"\"\"\n\nfrom tvm.te.hybrid import script\nfrom tvm import topi\nfrom tvm.runtime import convert\n\nfrom .op import register_compute, register_shape_func, register_legalize\nfrom .op import register_broadcast_schedule, register_injective_schedule\nfrom .op import register_pattern, OpPattern\n\n\nregister_broadcast_schedule(\"log\")\nregister_broadcast_schedule(\"log2\")\nregister_broadcast_schedule(\"log10\")\nregister_broadcast_schedule(\"tan\")\nregister_broadcast_schedule(\"cos\")\nregister_broadcast_schedule(\"cosh\")\nregister_broadcast_schedule(\"sin\")\nregister_broadcast_schedule(\"sinh\")\nregister_broadcast_schedule(\"acos\")\nregister_broadcast_schedule(\"acosh\")\nregister_broadcast_schedule(\"asin\")\nregister_broadcast_schedule(\"asinh\")\nregister_broadcast_schedule(\"atan\")\nregister_broadcast_schedule(\"atanh\")\nregister_broadcast_schedule(\"exp\")\nregister_broadcast_schedule(\"erf\")\nregister_broadcast_schedule(\"sqrt\")\nregister_broadcast_schedule(\"rsqrt\")\nregister_broadcast_schedule(\"sigmoid\")\nregister_broadcast_schedule(\"floor\")\nregister_broadcast_schedule(\"ceil\")\nregister_broadcast_schedule(\"trunc\")\nregister_broadcast_schedule(\"round\")\nregister_broadcast_schedule(\"sign\")\nregister_broadcast_schedule(\"abs\")\nregister_broadcast_schedule(\"tanh\")\nregister_broadcast_schedule(\"add\")\nregister_broadcast_schedule(\"subtract\")\nregister_broadcast_schedule(\"multiply\")\nregister_broadcast_schedule(\"divide\")\nregister_broadcast_schedule(\"floor_divide\")\nregister_broadcast_schedule(\"trunc_divide\")\nregister_broadcast_schedule(\"power\")\nregister_broadcast_schedule(\"copy\")\nregister_broadcast_schedule(\"logical_not\")\nregister_broadcast_schedule(\"logical_and\")\nregister_broadcast_schedule(\"logical_or\")\nregister_broadcast_schedule(\"logical_xor\")\nregister_broadcast_schedule(\"bitwise_not\")\nregister_broadcast_schedule(\"bitwise_and\")\nregister_broadcast_schedule(\"bitwise_or\")\nregister_broadcast_schedule(\"bitwise_xor\")\nregister_broadcast_schedule(\"negative\")\nregister_broadcast_schedule(\"mod\")\nregister_broadcast_schedule(\"floor_mod\")\nregister_broadcast_schedule(\"trunc_mod\")\nregister_broadcast_schedule(\"equal\")\nregister_broadcast_schedule(\"not_equal\")\nregister_broadcast_schedule(\"less\")\nregister_broadcast_schedule(\"less_equal\")\nregister_broadcast_schedule(\"greater\")\nregister_broadcast_schedule(\"greater_equal\")\nregister_broadcast_schedule(\"isnan\")\nregister_broadcast_schedule(\"isfinite\")\nregister_broadcast_schedule(\"isinf\")\nregister_injective_schedule(\"maximum\")\nregister_injective_schedule(\"minimum\")\nregister_injective_schedule(\"right_shift\")\nregister_injective_schedule(\"left_shift\")\nregister_injective_schedule(\"shape_of\")\nregister_injective_schedule(\"ndarray_size\")\nregister_injective_schedule(\"device_copy\")\nregister_broadcast_schedule(\"fast_exp\")\nregister_broadcast_schedule(\"fast_tanh\")\nregister_broadcast_schedule(\"fast_erf\")\n\n\n@register_legalize(\"erf\")\ndef legalize_erf(attrs, inputs, types):\n    \"\"\"Legalize ERF op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.math.erf_legalize(attrs, inputs, types)\n\n\n# zeros\n@register_compute(\"zeros\")\ndef zeros_compute(attrs, inputs, output_type):\n    assert not inputs\n    return [topi.full(output_type.shape, output_type.dtype, 0.0)]\n\n\nregister_broadcast_schedule(\"zeros\")\nregister_pattern(\"zeros\", OpPattern.ELEMWISE)\n\n# zeros_like\n@register_compute(\"zeros_like\")\ndef zeros_like_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.full_like(inputs[0], 0.0)]\n\n\nregister_broadcast_schedule(\"zeros_like\")\n\n# ones\n@register_compute(\"ones\")\ndef ones_compute(attrs, inputs, output_type):\n    assert not inputs\n    return [topi.full(output_type.shape, output_type.dtype, 1.0)]\n\n\nregister_broadcast_schedule(\"ones\")\nregister_pattern(\"ones\", OpPattern.ELEMWISE)\n\n# ones_like\n@register_compute(\"ones_like\")\ndef ones_like_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.full_like(inputs[0], 1.0)]\n\n\nregister_broadcast_schedule(\"ones_like\")\n\n# clip\n@register_compute(\"clip\")\ndef clip_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.clip(inputs[0], attrs.a_min, attrs.a_max)]\n\n\nregister_injective_schedule(\"clip\")\n\n# fixed point multiply\n@register_compute(\"fixed_point_multiply\")\ndef fixed_point_multiply_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.fixed_point_multiply(inputs[0], attrs.multiplier, attrs.shift)]\n\n\nregister_injective_schedule(\"fixed_point_multiply\")\n\n# per-channel/per-axis fixed point multiply\n@register_compute(\"fixed_point_multiply_per_axis\")\ndef fixed_point_multiply_per_axis_compute(attrs, inputs, output_type):\n    assert len(inputs) == 4\n    return [\n        topi.fixed_point_multiply_per_axis(\n            *inputs, attrs.is_lshift_required, attrs.is_rshift_required, attrs.axes\n        )\n    ]\n\n\nregister_broadcast_schedule(\"fixed_point_multiply_per_axis\")\n\n# full\n@script\ndef _full_shape_func(shape):\n    out_ndim = shape.shape[0]\n    out = output_tensor((out_ndim,), \"int64\")\n    for i in const_range(out_ndim):\n        out[i] = int64(shape[i])\n    return out\n\n\n@script\ndef _convert_shape(shape):\n    out = output_tensor((len(shape),), \"int64\")\n    for i in const_range(len(shape)):\n        out[i] = int64(shape[i])\n    return out\n\n\ndef full_shape_func(attrs, inputs, out_ndims):\n    \"\"\"\n    Shape func for full.\n    \"\"\"\n    if len(inputs) > 1:\n        return [_full_shape_func(inputs[1])]\n\n    return [_convert_shape(convert(attrs.shape))]\n\n\ndef no_data_full_shape_func(attrs, inputs, out_ndims):\n    \"\"\"\n    Shape func for zeros and ones.\n    \"\"\"\n    if len(inputs) == 0:\n        return [_convert_shape(convert(attrs.shape))]\n    return [_full_shape_func(inputs[0])]\n\n\n@script\ndef _broadcast_shape_func(x, y, ndim):\n    out = output_tensor((ndim,), \"int64\")\n    if len(x.shape) == 0:\n        for i in const_range(ndim):\n            out[i] = y[i]\n    elif len(y.shape) == 0:\n        for i in const_range(ndim):\n            out[i] = x[i]\n    else:\n        ndim1 = x.shape[0]\n        ndim2 = y.shape[0]\n        for i in const_range(1, min(ndim1, ndim2) + 1):\n            if x[ndim1 - i] == y[ndim2 - i]:\n                out[ndim - i] = x[ndim1 - i]\n            elif x[ndim1 - i] == 1:\n                out[ndim - i] = y[ndim2 - i]\n            else:\n                assert y[ndim2 - i] == 1, \"Incompatible broadcast type %s and %s\" % (\n                    x[ndim1 - i],\n                    y[ndim2 - i],\n                )\n                out[ndim - i] = x[ndim1 - i]\n        for i in const_range(min(ndim1, ndim2) + 1, ndim + 1):\n            if ndim1 >= ndim2:\n                out[ndim - i] = x[ndim1 - i]\n            else:\n                out[ndim - i] = y[ndim2 - i]\n    return out\n\n\ndef broadcast_shape_func(attrs, inputs, out_ndims):\n    \"\"\"\n    Shape function for broadcast op.\n    \"\"\"\n    return [_broadcast_shape_func(*inputs, out_ndims[0])]\n\n\ndef elemwise_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for elemwise op.\n    \"\"\"\n    return [topi.math.identity(inputs[0])]\n\n\nregister_shape_func(\"cast\", False, elemwise_shape_func)\nregister_shape_func(\"cast_like\", False, elemwise_shape_func)\nregister_shape_func(\"round\", False, elemwise_shape_func)\nregister_shape_func(\"zeros\", False, no_data_full_shape_func)\nregister_shape_func(\"zeros_like\", False, elemwise_shape_func)\nregister_shape_func(\"ones\", False, no_data_full_shape_func)\nregister_shape_func(\"ones_like\", False, elemwise_shape_func)\nregister_shape_func(\"full\", False, full_shape_func)\nregister_shape_func(\"full_like\", False, elemwise_shape_func)\nregister_shape_func(\"broadcast_to\", True, full_shape_func)\n\nregister_shape_func(\"add\", False, broadcast_shape_func)\nregister_shape_func(\"subtract\", False, broadcast_shape_func)\nregister_shape_func(\"multiply\", False, broadcast_shape_func)\nregister_shape_func(\"divide\", False, broadcast_shape_func)\nregister_shape_func(\"floor_divide\", False, broadcast_shape_func)\nregister_shape_func(\"trunc_divide\", False, broadcast_shape_func)\nregister_shape_func(\"power\", False, broadcast_shape_func)\nregister_shape_func(\"mod\", False, broadcast_shape_func)\nregister_shape_func(\"floor_mod\", False, broadcast_shape_func)\nregister_shape_func(\"trunc_mod\", False, broadcast_shape_func)\nregister_shape_func(\"logical_and\", False, broadcast_shape_func)\nregister_shape_func(\"logical_or\", False, broadcast_shape_func)\nregister_shape_func(\"logical_xor\", False, broadcast_shape_func)\nregister_shape_func(\"bitwise_not\", False, broadcast_shape_func)\nregister_shape_func(\"bitwise_and\", False, broadcast_shape_func)\nregister_shape_func(\"bitwise_or\", False, broadcast_shape_func)\nregister_shape_func(\"bitwise_xor\", False, broadcast_shape_func)\nregister_shape_func(\"equal\", False, broadcast_shape_func)\nregister_shape_func(\"not_equal\", False, broadcast_shape_func)\nregister_shape_func(\"less\", False, broadcast_shape_func)\nregister_shape_func(\"less_equal\", False, broadcast_shape_func)\nregister_shape_func(\"greater\", False, broadcast_shape_func)\nregister_shape_func(\"greater_equal\", False, broadcast_shape_func)\nregister_shape_func(\"maximum\", False, broadcast_shape_func)\nregister_shape_func(\"minimum\", False, broadcast_shape_func)\nregister_shape_func(\"left_shift\", False, broadcast_shape_func)\nregister_shape_func(\"right_shift\", False, broadcast_shape_func)\n\nregister_shape_func(\"sqrt\", False, elemwise_shape_func)\nregister_shape_func(\"rsqrt\", False, elemwise_shape_func)\nregister_shape_func(\"negative\", False, elemwise_shape_func)\nregister_shape_func(\"exp\", False, elemwise_shape_func)\nregister_shape_func(\"tan\", False, elemwise_shape_func)\nregister_shape_func(\"fast_exp\", False, elemwise_shape_func)\nregister_shape_func(\"fast_tanh\", False, elemwise_shape_func)\nregister_shape_func(\"fast_erf\", False, elemwise_shape_func)\nregister_shape_func(\"floor\", False, elemwise_shape_func)\nregister_shape_func(\"log\", False, elemwise_shape_func)\nregister_shape_func(\"device_copy\", False, elemwise_shape_func)\nregister_shape_func(\"clip\", False, elemwise_shape_func)\nregister_shape_func(\"log2\", False, elemwise_shape_func)\nregister_shape_func(\"sigmoid\", False, elemwise_shape_func)\nregister_shape_func(\"tanh\", False, elemwise_shape_func)\nregister_shape_func(\"logical_not\", False, elemwise_shape_func)\nregister_shape_func(\"ceil\", False, elemwise_shape_func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_tensor_grad.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Gradient definitions for Relay operators\"\"\"\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.error import OpError\n\n\nfrom ..expr import Tuple, TupleGetItem, const, Var\nfrom ..ty import TensorType\nfrom ..loops import while_loop\nfrom . import nn as _nn\nfrom .op import register_gradient\nfrom .reduce import sum as _sum\nfrom .tensor import (\n    cos,\n    cosh,\n    exp,\n    less,\n    negative,\n    ones_like,\n    power,\n    sin,\n    sinh,\n    sqrt,\n    zeros_like,\n    equal,\n    shape_of,\n    log,\n    concatenate,\n)\nfrom .transform import (\n    broadcast_to_like,\n    collapse_sum_like,\n    cast_like,\n    reshape,\n    reshape_like,\n    strided_slice,\n    take,\n    transpose,\n    where,\n    repeat,\n    expand_dims,\n    full_like,\n    split,\n    squeeze,\n    strided_set,\n    arange,\n    scatter_nd,\n)\n\n\n@register_gradient(\"log\")\ndef log_grad(orig, grad):\n    \"\"\"Returns [grad * (1 / x)]\"\"\"\n    x = orig.args[0]\n    return [grad * ones_like(x) / x]\n\n\n@register_gradient(\"log2\")\ndef log2_grad(orig, grad):\n    \"\"\"Returns [grad * 1 / (log(2) * x)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    two = const(2.0, dtype=x.checked_type.dtype)\n    return [grad * ones / (log(two) * x)]\n\n\n@register_gradient(\"log10\")\ndef log10_grad(orig, grad):\n    \"\"\"Returns [grad * 1 / (log(10) * x)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    ten = const(10.0, dtype=x.checked_type.dtype)\n    return [grad * ones / (log(ten) * x)]\n\n\n@register_gradient(\"tan\")\ndef tan_grad(orig, grad):\n    \"\"\"Returns [grad / (cos^2(x))]\"\"\"\n    x = orig.args[0]\n    return [grad / (cos(x) * cos(x))]\n\n\n@register_gradient(\"cos\")\ndef cos_grad(orig, grad):\n    \"\"\"Returns [grad * (-sin(x))]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * (-ones * sin(x))]\n\n\n@register_gradient(\"cosh\")\ndef cosh_grad(orig, grad):\n    \"\"\"Returns [grad * sinh(x)]\"\"\"\n    x = orig.args[0]\n    return [grad * sinh(x)]\n\n\n@register_gradient(\"sin\")\ndef sin_grad(orig, grad):\n    \"\"\"Returns [grad * cos(x)]\"\"\"\n    x = orig.args[0]\n    return [grad * cos(x)]\n\n\n@register_gradient(\"sinh\")\ndef sinh_grad(orig, grad):\n    \"\"\"Returns [grad * cosh(x)]\"\"\"\n    x = orig.args[0]\n    return [grad * cosh(x)]\n\n\n@register_gradient(\"acos\")\ndef acos_grad(orig, grad):\n    \"\"\"Returns [grad * -1/((1 - (x ^ 2)) ^ 1/2)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * (-ones / sqrt(ones - (x * x)))]\n\n\n@register_gradient(\"acosh\")\ndef acosh_grad(orig, grad):\n    \"\"\"Returns [grad * 1/((x - 1) ^ 1/2 * (x + 1) ^ 1/2)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * ones / sqrt((x * x) - ones)]\n\n\n@register_gradient(\"asin\")\ndef asin_grad(orig, grad):\n    \"\"\"Returns [grad * 1/((1 - (x ^ 2)) ^ (1/2))]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * ones / sqrt(ones - (x * x))]\n\n\n@register_gradient(\"asinh\")\ndef asinh_grad(orig, grad):\n    \"\"\"Returns [grad * 1/((1 + (x ^ 2)) ^ (1/2))]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * ones / sqrt(ones + (x * x))]\n\n\n@register_gradient(\"atan\")\ndef atan_grad(orig, grad):\n    \"\"\"Returns [grad * 1 / (1 + x ^ 2)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * ones / (ones + (x * x))]\n\n\n@register_gradient(\"atanh\")\ndef atanh_grad(orig, grad):\n    \"\"\"Returns [grad * 1 / (1 - x ^ 2)]\"\"\"\n    x = orig.args[0]\n    ones = ones_like(x)\n    return [grad * ones / (ones - (x * x))]\n\n\n@register_gradient(\"exp\")\ndef exp_grad(orig, grad):\n    \"\"\"Returns [grad * exp(x)]\"\"\"\n    return [grad * exp(orig.args[0])]\n\n\n@register_gradient(\"sqrt\")\ndef sqrt_grad(orig, grad):\n    \"\"\"Returns [grad * 0.5 * (x ^ -0.5)]\"\"\"\n    x = orig.args[0]\n    a = const(0.5, dtype=x.checked_type.dtype)\n    return [grad * a * power(x, negative(a))]\n\n\n@register_gradient(\"sigmoid\")\ndef sigmoid_grad(orig, grad):\n    \"\"\"Returns [grad * sigmoid(x) * (1 - sigmoid(x))].\"\"\"\n    return [grad * orig * (ones_like(orig) - orig)]\n\n\n@register_gradient(\"tanh\")\ndef tanh_grad(orig, grad):\n    \"\"\"Returns grad * (1 - tanh(x) * tanh(x)).\"\"\"\n    return [grad * (ones_like(orig) - orig * orig)]\n\n\n@register_gradient(\"nn.relu\")\ndef relu_grad(orig, grad):\n    \"\"\"Returns grad * (select(x < 0, 0, 1)).\"\"\"\n    x = orig.args[0]\n    zeros = zeros_like(x)\n    ones = ones_like(x)\n    return [where(less(x, zeros), zeros, ones * grad)]\n\n\n@register_gradient(\"add\")\ndef add_grad(orig, grad):\n    \"\"\"Returns [grad, grad]\"\"\"\n    return [collapse_sum_like(grad, orig.args[0]), collapse_sum_like(grad, orig.args[1])]\n\n\n@register_gradient(\"subtract\")\ndef subtract_grad(orig, grad):\n    \"\"\"Returns [grad, -grad]\"\"\"\n    return [collapse_sum_like(grad, orig.args[0]), collapse_sum_like(negative(grad), orig.args[1])]\n\n\n@register_gradient(\"multiply\")\ndef multiply_grad(orig, grad):\n    \"\"\"Returns [grad * y, grad * x]\"\"\"\n    x, y = orig.args\n    return [collapse_sum_like(grad * y, x), collapse_sum_like(grad * x, y)]\n\n\n@register_gradient(\"divide\")\ndef divide_grad(orig, grad):\n    \"\"\"Returns [grad / y,  - grad * (x / y) / y]\"\"\"\n    x, y = orig.args\n    return [collapse_sum_like(grad / y, x), collapse_sum_like(-(grad * orig / y), y)]\n\n\n@register_gradient(\"zeros\")\ndef zeros_grad(orig, grad):\n    \"\"\"Returns []\"\"\"\n    return []\n\n\n@register_gradient(\"dyn.zeros\")\ndef dyn_zeros_grad(orig, grad):\n    \"\"\"Returns the gradient of dyn.zeros which is just zero.\"\"\"\n    assert len(orig.args) == 1\n    return [zeros_like(orig.args[0])]\n\n\n@register_gradient(\"ones\")\ndef ones_grad(orig, grad):\n    \"\"\"Returns []\"\"\"\n    return []\n\n\n@register_gradient(\"dyn.ones\")\ndef dyn_ones_grad(orig, grad):\n    \"\"\"Returns the gradient of dyn.ones which is just zero.\"\"\"\n    assert len(orig.args) == 1\n    return [zeros_like(orig.args[0])]\n\n\n@register_gradient(\"zeros_like\")\ndef zeros_like_grad(orig, grad):\n    \"\"\"Returns [0]\"\"\"\n    return [orig]\n\n\n@register_gradient(\"ones_like\")\ndef ones_like_grad(orig, grad):\n    \"\"\"Returns [0]\"\"\"\n    return [zeros_like(orig.args[0])]\n\n\n@register_gradient(\"collapse_sum_like\")\ndef collapse_sum_like_grad(orig, grad):\n    \"\"\"Returns [broadcast_to_like(grad, x), 0]\"\"\"\n    x, y = orig.args\n    return [broadcast_to_like(grad, x), zeros_like(y)]\n\n\n@register_gradient(\"collapse_sum_to\")\ndef collapse_sum_to_grad(orig, grad):\n    \"\"\"Returns [broadcast_to_like(grad, x), 0]\"\"\"\n    x, y = orig.args\n    return [broadcast_to_like(grad, x), zeros_like(y)]\n\n\n@register_gradient(\"abs\")\ndef abs_grad(orig, grad):\n    \"\"\"Returns grad * (select(x < 0, -1, 1)).\"\"\"\n    x = orig.args[0]\n    zeros = zeros_like(x)\n    ones = ones_like(x)\n    return [where(less(x, zeros), -ones * grad, ones * grad)]\n\n\n@register_gradient(\"erf\")\ndef erf_grad(orig, grad):\n    # c_2_div_sqrt_pi = 2.0 / math.sqrt(math.pi)\n    (inp,) = orig.args\n    c_2_div_sqrt_pi = const(1.1283791670955126, dtype=inp.checked_type.dtype)\n    return [c_2_div_sqrt_pi * exp(-inp * inp) * grad]\n\n\n@register_gradient(\"clip\")\ndef clip_grad(orig, grad):\n    \"\"\"Returns grad * (select(x < min || max < x , 0, 1)).\"\"\"\n    x = orig.args[0]\n    a_min = orig.attrs.get_int(\"a_min\")\n    a_max = orig.attrs.get_int(\"a_max\")\n    a_mins = broadcast_to_like(const(a_min, dtype=x.checked_type.dtype), x)\n    a_maxs = broadcast_to_like(const(a_max, dtype=x.checked_type.dtype), x)\n    zeros = zeros_like(x)\n    ones = ones_like(x)\n    return [where(less(x, a_mins), zeros, where(less(a_maxs, x), zeros, ones * grad))]\n\n\n@register_gradient(\"nn.max_pool2d\")\ndef max_pool2d_grad(orig, grad):\n    \"\"\"Returns the gradient of max_pool2d.\"\"\"\n    attrs = orig.attrs\n    pool_grad = _nn.max_pool2d_grad(\n        grad,\n        orig.args[0],\n        pool_size=attrs.pool_size,\n        strides=attrs.strides,\n        padding=attrs.padding,\n        layout=attrs.layout,\n        ceil_mode=attrs.ceil_mode,\n    )\n    return [pool_grad]\n\n\n@register_gradient(\"nn.avg_pool2d\")\ndef avg_pool2d_grad(orig, grad):\n    \"\"\"Returns the gradient of avg_pool2d.\"\"\"\n    attrs = orig.attrs\n    pool_grad = _nn.avg_pool2d_grad(\n        grad,\n        orig.args[0],\n        pool_size=attrs.pool_size,\n        strides=attrs.strides,\n        padding=attrs.padding,\n        layout=attrs.layout,\n        ceil_mode=attrs.ceil_mode,\n        count_include_pad=attrs.count_include_pad,\n    )\n    return [pool_grad]\n\n\n@register_gradient(\"nn.global_avg_pool2d\")\ndef global_avg_pool2d_grad(orig, grad):\n    \"\"\"Returns the gradient of global_avg_pool2d.\"\"\"\n    data = orig.args[0]\n    shape = data.checked_type.shape\n    layout = orig.attrs.layout\n\n    # we assume NCHW or NHWC layout for now, but easy to add more\n    assert layout in [\"NCHW\", \"NHWC\"]\n    if layout == \"NCHW\":\n        pool_size = shape[2], shape[3]\n    elif layout == \"NHWC\":\n        pool_size = shape[1], shape[2]\n\n    pool_grad = _nn.avg_pool2d_grad(\n        grad, data, pool_size=pool_size, strides=(1, 1), padding=(0, 0), layout=layout\n    )\n    return [pool_grad]\n\n\n@register_gradient(\"concatenate\")\ndef concatenate_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of concatenate, which is just the downstream gradient\n    split across the inputs.\n    \"\"\"\n    assert len(orig.args) == 1\n    t = orig.args[0]\n\n    # calculate split indices. TODO(@altanh): support Any?\n    axis_dims = [ty.shape[orig.attrs.axis] for ty in t.checked_type.fields]\n    splits, cumsum = [], 0\n    for dim in axis_dims[:-1]:\n        cumsum += dim\n        splits.append(cumsum)\n\n    grads = split(grad, tuple(splits), axis=orig.attrs.axis).tuple_value\n    return [grads]\n\n\n@register_gradient(\"nn.conv2d\")\ndef conv2d_grad(orig, grad):\n    \"\"\"Gradient of conv2d\"\"\"\n    attrs = orig.attrs\n    data, weight = orig.args\n    data_shape = get_const_tuple(data.checked_type.shape)\n    weight_shape = get_const_tuple(weight.checked_type.shape)\n    _, _, grad_h, grad_w = get_const_tuple(orig.checked_type.shape)\n    _, _, in_h, in_w = data_shape\n    _, _, filter_h, filter_w = weight_shape\n\n    # infer output_padding\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(\n        get_const_tuple(attrs.padding), (filter_h, filter_w)\n    )\n    stride_h, stride_w = get_const_tuple(attrs.strides)\n    out_h = (grad_h - 1) * stride_h - fpad_top - fpad_bottom + filter_h\n    out_w = (grad_w - 1) * stride_w - fpad_left - fpad_right + filter_w\n    output_padding = (in_h - out_h, in_w - out_w)\n\n    assert attrs.data_layout == \"NCHW\", \"only support NCHW data layout\"\n    assert attrs.kernel_layout == \"OIHW\", \"only support OIHW kernel layout\"\n    assert attrs.out_layout in [\"\", \"NCHW\"], \"only support NCHW output layout\"\n\n    if attrs.out_dtype in [\"\", None]:\n        assert data.checked_type, \"Call InferType first.\"\n        out_dtype = data.checked_type.dtype\n    else:\n        out_dtype = attrs.out_dtype\n\n    backward_data = _nn.conv2d_transpose(\n        grad,\n        weight,\n        strides=attrs.strides,\n        padding=attrs.padding,\n        dilation=attrs.dilation,\n        groups=attrs.groups,\n        output_padding=output_padding,\n        out_dtype=out_dtype,\n    )\n\n    backward_weight = _nn.conv2d_backward_weight(\n        grad,\n        data,\n        strides=attrs.strides,\n        padding=attrs.padding,\n        dilation=attrs.dilation,\n        groups=attrs.groups,\n        channels=attrs.channels,\n        kernel_size=(filter_h, filter_w),\n        grad_layout=attrs.out_layout if attrs.out_layout else attrs.data_layout,\n        data_layout=attrs.data_layout,\n        kernel_layout=attrs.kernel_layout,\n        out_dtype=out_dtype,\n    )\n\n    return [backward_data, backward_weight]\n\n\ndef _get_reduce_axis(call):\n    \"\"\"Helper function that returns the reduce axis of the call as plain python ints.\"\"\"\n    x, axis = call.args[0], call.attrs.axis\n    shape = x.checked_type.concrete_shape\n\n    # should never exclude when axis is None\n    assert not (axis is None and call.attrs.exclude)\n\n    if axis is None:\n        return None\n\n    # convert to nonnegative integers and sort\n    axis = sorted([ax if ax >= 0 else len(shape) + ax for ax in map(int, axis)])\n    if call.attrs.exclude:\n        axis = [ax for ax in range(len(shape)) if ax not in axis]\n    return axis\n\n\ndef _unreduce_expand(x, axis):\n    \"\"\"Helper function that returns x expanded on the reduced dimensions in axis.\"\"\"\n    # assume axis is sorted nonnegative ints\n    for ax in axis:\n        x = expand_dims(x, ax)\n    return x\n\n\n@register_gradient(\"max\")\ndef max_grad(orig, grad):\n    \"\"\"Returns the gradient of max\"\"\"\n    x, axis = orig.args[0], _get_reduce_axis(orig)\n    shape = x.checked_type.concrete_shape\n\n    repeated = orig\n    if axis is None:\n        repeated = full_like(x, repeated)\n    else:\n        # expand dims (if necessary) and repeat along each axis\n        if not orig.attrs.keepdims:\n            repeated = _unreduce_expand(repeated, axis)\n            grad = _unreduce_expand(grad, axis)\n        for ax in axis:\n            repeated = repeat(repeated, shape[ax], ax)\n\n    indicators = cast_like(equal(repeated, x), grad)\n    num_selected = _sum(indicators, axis, keepdims=True)\n    # spread error across all max weights\n    return [indicators * grad / num_selected]\n\n\n@register_gradient(\"nn.softmax\")\ndef softmax_grad(orig, grad):\n    \"\"\"Gradient of softmax\"\"\"\n    return [(grad - _sum(grad * orig, orig.attrs.axis, True)) * orig]\n\n\n@register_gradient(\"nn.log_softmax\")\ndef log_softmax_grad(orig, grad):\n    \"\"\"Gradient of log_softmax\"\"\"\n    return [grad - _sum(grad, axis=orig.attrs.axis, keepdims=True) * exp(orig)]\n\n\n@register_gradient(\"nn.bias_add\")\ndef bias_add_grad(orig, grad):\n    \"\"\"Returns gradient of bias_add\"\"\"\n    data = orig.args[0]\n    return [\n        collapse_sum_like(grad, data),\n        _sum(grad, orig.attrs.axis, keepdims=False, exclude=True),\n    ]\n\n\n@register_gradient(\"nn.dense\")\ndef dense_grad(orig, grad):\n    \"\"\"Returns [grad' @ weight, data @ grad']\"\"\"\n    data, weight = orig.args\n    return [\n        collapse_sum_like(\n            _nn.dense(grad, transpose(weight), units=weight.checked_type.shape[1]), data\n        ),\n        collapse_sum_like(\n            _nn.dense(transpose(grad), transpose(data), units=data.checked_type.shape[1]), weight\n        ),\n    ]\n\n\n@register_gradient(\"nn.matmul\")\ndef matmul_grad(orig, grad):\n    \"\"\"Returns [grad' @ tensor_b, tensor_a @ grad']\"\"\"\n    tensor_a, tensor_b = orig.args\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (True, True):\n        return [\n            collapse_sum_like(\n                _nn.matmul(tensor_b, grad, transpose_a=True, transpose_b=True), tensor_a\n            ),\n            collapse_sum_like(\n                _nn.matmul(grad, tensor_a, transpose_a=True, transpose_b=True), tensor_b\n            ),\n        ]\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (True, False):\n        return [\n            collapse_sum_like(_nn.matmul(tensor_b, grad, transpose_b=True), tensor_a),\n            collapse_sum_like(_nn.matmul(tensor_a, grad), tensor_b),\n        ]\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (False, True):\n        # Keep using Dense op here for not involving extra ops\n        # TODO(jcf94): Merge all to nn.matmul when it is finally ready\n        return dense_grad(orig, grad)\n    # (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (False, False)\n    return [\n        collapse_sum_like(_nn.matmul(grad, tensor_b, transpose_b=True), tensor_a),\n        collapse_sum_like(_nn.matmul(tensor_a, grad, transpose_a=True), tensor_b),\n    ]\n\n\n@register_gradient(\"nn.batch_matmul\")\ndef batch_matmul_grad(orig, grad):\n    \"\"\"gradient for nn.batch_matmul: in einsum LHS_bik,RHS_bjk->RES_bij\n    grads: GRAD_OUT_bij,RHS_bjk->GRAD_IN_LHS_bik\n           GRAD_OUT_bij,LHS_bik->GRAD_IN_RHS_bjk\n    \"\"\"\n    lhs, rhs = orig.args\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (True, True):\n        # ki,   jk  ->  ij\n        # jk,   ij  ->  ki\n        # ij,   ki  ->  jk\n        return [\n            collapse_sum_like(_nn.batch_matmul(rhs, grad, transpose_a=True, transpose_b=True), lhs),\n            collapse_sum_like(_nn.batch_matmul(grad, lhs, transpose_a=True, transpose_b=True), rhs),\n        ]\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (True, False):\n        # ki,   kj  ->  ij\n        # kj,   ij  ->  ki\n        # ki,   ij  ->  kj\n        return [\n            collapse_sum_like(\n                _nn.batch_matmul(rhs, grad, transpose_a=False, transpose_b=True), lhs\n            ),\n            collapse_sum_like(\n                _nn.batch_matmul(lhs, grad, transpose_a=False, transpose_b=False), rhs\n            ),\n        ]\n    if (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (False, True):\n        # ik,   jk  ->  ij\n        # ij,   jk  ->  ik\n        # ij,   ik  ->  jk\n        # Keep using NT format batch_matmul here for not involving extra ops\n        # TODO(jcf94): Merge all to normal batch_matmul when it is finally ready\n        return [\n            collapse_sum_like(\n                _nn.batch_matmul(\n                    grad,\n                    transpose(rhs, [0, 2, 1]),\n                    transpose_a=False,\n                    transpose_b=True,\n                ),\n                lhs,\n            ),\n            collapse_sum_like(\n                _nn.batch_matmul(\n                    transpose(grad, [0, 2, 1]),\n                    transpose(lhs, [0, 2, 1]),\n                    transpose_a=False,\n                    transpose_b=True,\n                ),\n                rhs,\n            ),\n        ]\n    # (orig.attrs[\"transpose_a\"], orig.attrs[\"transpose_b\"]) == (False, False)\n    # ik,   kj  ->  ij\n    # ij,   kj  ->  ik\n    # ik,   ij  ->  kj\n    return [\n        collapse_sum_like(_nn.batch_matmul(grad, rhs, transpose_a=False, transpose_b=True), lhs),\n        collapse_sum_like(_nn.batch_matmul(lhs, grad, transpose_a=True, transpose_b=False), rhs),\n    ]\n\n\n@register_gradient(\"reshape\")\ndef reshape_grad(orig, grad):\n    \"\"\"Gradient of reshape\"\"\"\n    return [reshape_like(grad, orig.args[0])]\n\n\n@register_gradient(\"dyn.reshape\")\ndef dyn_reshape_grad(orig, grad):\n    \"\"\"Gradient of dyn_reshape\"\"\"\n    return [reshape_like(grad, orig.args[0]), zeros_like(orig.args[1])]\n\n\n@register_gradient(\"shape_of\")\ndef shape_of_grad(orig, grad):\n    \"\"\"Gradient of shape_of\"\"\"\n    return [zeros_like(orig.args[0])]\n\n\n@register_gradient(\"cast\")\ndef cast_grad(orig, grad):\n    x = orig.args[0]\n    return [cast_like(grad, x)]\n\n\n@register_gradient(\"cast_like\")\ndef cast_like_grad(orig, grad):\n    x, like = orig.args\n    return [cast_like(grad, x), zeros_like(like)]\n\n\n@register_gradient(\"nn.batch_flatten\")\ndef batch_flatten_grad(orig, grad):\n    \"\"\"Returns grad reshaped to data dims\"\"\"\n    data = orig.args[0]\n    return [reshape_like(grad, data)]\n\n\n@register_gradient(\"transpose\")\ndef transpose_grad(orig, grad):\n    \"\"\"Returns grad transposed over the complement of original transpose axes\"\"\"\n    orig_axes = orig.attrs.axes\n    if orig_axes:\n        dims = len(orig_axes)\n        new_axes = [0] * dims\n        for i in range(dims):\n            new_axes[int(orig_axes[i])] = i\n    else:\n        new_axes = None\n    return [transpose(grad, axes=new_axes)]\n\n\n@register_gradient(\"negative\")\ndef negative_grad(orig, grad):\n    \"\"\"Returns -grad\"\"\"\n    return [-grad]\n\n\n@register_gradient(\"sum\")\ndef sum_grad(orig, grad):\n    \"\"\"Returns grad broadcasted to data dims\"\"\"\n    data, axis = orig.args[0], _get_reduce_axis(orig)\n    if not orig.attrs.keepdims:\n        if axis is None:\n            axis = list(range(len(data.checked_type.concrete_shape)))\n        grad = _unreduce_expand(grad, axis)\n    return [broadcast_to_like(grad, data)]\n\n\n@register_gradient(\"mean\")\ndef mean_grad(orig, grad):\n    \"\"\"Returns grad broadcasted to data dims\"\"\"\n    data, axis = orig.args[0], _get_reduce_axis(orig)\n    shape = data.checked_type.concrete_shape\n    if axis is None:\n        axis = list(range(len(data.checked_type.concrete_shape)))\n    if not orig.attrs.keepdims:\n        grad = _unreduce_expand(grad, axis)\n    mult = 1.0\n    for a in axis:\n        mult /= shape[a]\n    return [broadcast_to_like(grad * const(mult, dtype=data.checked_type.dtype), data)]\n\n\n@register_gradient(\"variance\")\ndef variance_grad(orig, grad):\n    \"\"\"Note that we take mean as an argument in the variance node\"\"\"\n    data, data_mean, axis = orig.args[0], orig.args[1], _get_reduce_axis(orig)\n    unbiased = orig.attrs.unbiased\n    shape = data.checked_type.concrete_shape\n    if axis is None:\n        axis = list(range(len(data.checked_type.concrete_shape)))\n    if not orig.attrs.keepdims:\n        grad = _unreduce_expand(grad, axis)\n    mult1 = 2.0\n    mult2 = -2.0\n    count = 1\n    for a in axis:\n        count *= shape[a]\n    if unbiased:\n        mult2 = mult2 * count / (count - 1)\n        count -= 1\n    mult1 /= count\n    return [\n        (grad * const(mult1, dtype=data.checked_type.dtype)) * data,\n        const(mult2, dtype=data.checked_type.dtype) * grad * data_mean,\n    ]\n\n\n@register_gradient(\"copy\")\ndef copy_grad(orig, grad):\n    return [grad]\n\n\n@register_gradient(\"nn.cross_entropy\")\ndef cross_entropy_grad(orig, grad):\n    x, y = orig.args\n    shape = shape_of(x)\n    batch_size = take(shape, const(0, dtype=\"int32\"), axis=0)\n    grad = grad / batch_size.astype(x.checked_type.dtype)\n    return [-grad * y / x, -grad * log(x)]\n\n\n@register_gradient(\"nn.cross_entropy_with_logits\")\ndef cross_entropy_with_logits_grad(orig, grad):\n    x, y = orig.args\n    shape = shape_of(x)\n    batch_size = take(shape, const(0, dtype=\"int32\"), axis=0)\n    grad = grad / batch_size.astype(x.checked_type.dtype)\n    return [-grad * y, -grad * x]\n\n\n@register_gradient(\"take\")\ndef take_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of take.\n    \"\"\"\n\n    def make_scalar_tensor(v):\n        if isinstance(v, int):\n            v = const(v, dtype=\"int32\")\n        return reshape(v, (1,))\n\n    # TODO(@altanh): we currently assume indices are in range\n    data, indices = orig.args\n    axis = orig.attrs.axis\n    batch_dims = orig.attrs.batch_dims\n    zero, one = map(make_scalar_tensor, [0, 1])\n    data_grad = zeros_like(data)\n    try:\n        data_shape = data.checked_type.concrete_shape\n    except TypeError as ty_err:\n        raise OpError(\"currently take_grad only supports data with concrete shape\") from ty_err\n    if axis is None:\n        axis = 0\n        data_grad = reshape(data_grad, (-1,))\n        data_shape = 1\n        for dim in data.checked_type.concrete_shape:\n            data_shape *= dim\n        data_shape = (data_shape,)\n    else:\n        axis = int(axis)\n    if batch_dims is None:\n        batch_dims = 0\n    else:\n        batch_dims = int(batch_dims)\n    if batch_dims != 0:\n        raise OpError(\"take_grad only supports batch_dims equales to 0\")\n    strides = [1] * len(data_shape)\n\n    if len(indices.checked_type.shape) == 0:\n        # axis on grad has been squeezed in this case\n        num_indices = one\n        indices = reshape(indices, (1,))\n        grad = expand_dims(grad, int(axis))\n    elif len(indices.checked_type.shape) == 1:\n        num_indices = take(shape_of(indices), zero, axis=0)\n    else:\n        raise OpError(\"take_grad only supports scalar or 1D indices\")\n\n    def loop_cond(data_grad, i):\n        return squeeze(less(i, num_indices))\n\n    def loop_body(data_grad, i):\n        index = take(indices, i, axis=0)\n        grad_slice = take(grad, i, axis=axis)\n        begin, end = [], []\n        for ax, size in enumerate(data_shape):\n            size = make_scalar_tensor(size)\n            begin.append(zero if ax != axis else index)\n            end.append(size if ax != axis else index + one)\n        begin, end = concatenate(begin, axis=0), concatenate(end, axis=0)\n        # data_grad[:,...,index at axis,...,:] += grad_slice\n        update = strided_slice(data_grad, begin, end, strides=strides)\n        update = update + grad_slice  # no need to expand grad_slice since i has shape (1,)\n        next_data_grad = strided_set(data_grad, update, begin, end, strides=strides)\n        return (next_data_grad, i + one)\n\n    loop_vars = [\n        Var(\"data_grad\", type_annotation=TensorType(data_shape, data.checked_type.dtype)),\n        Var(\"i\", type_annotation=TensorType((1,), \"int32\")),\n    ]\n\n    loop = while_loop(loop_cond, loop_vars, loop_body)\n    result = loop(data_grad, zero)\n    data_grad = TupleGetItem(result, 0)\n\n    if orig.attrs.axis is None:\n        data_grad = reshape_like(data_grad, data)\n\n    return [data_grad, zeros_like(orig.args[1])]\n\n\n@register_gradient(\"contrib_reverse_reshape\")\ndef reverse_reshape_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of reverse_reshape (same as reshape).\n    \"\"\"\n    return [reshape_like(grad, orig.args[0])]\n\n\n@register_gradient(\"stack\")\ndef stack_grad(orig, grad):\n    \"\"\"\n    Returns grad split across stacked inputs.\n    \"\"\"\n    stack_axis = int(orig.attrs.axis)\n    sections = len(orig.args[0].checked_type.fields)\n    splits = split(grad, sections, stack_axis)\n    splits = Tuple([squeeze(x, axis=[stack_axis]) for x in splits])\n    return [splits]\n\n\n@register_gradient(\"squeeze\")\ndef squeeze_grad(orig, grad):\n    \"\"\"\n    Returns grad expanded to input size.\n    \"\"\"\n    # this should work, can't use expand_dims since we lose\n    # squeeze information when axis=None\n    return [reshape_like(grad, orig.args[0])]\n\n\n@register_gradient(\"expand_dims\")\ndef expand_dims_grad(orig, grad):\n    \"\"\"\n    Returns grad squeezed on expanded dims.\n    \"\"\"\n    axis = int(orig.attrs.axis)\n    for _ in range(orig.attrs.num_newaxis):\n        grad = squeeze(grad, axis=[axis])\n    return [grad]\n\n\n@register_gradient(\"arange\")\ndef arange_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of arange.\n    \"\"\"\n    start, stop, step = orig.args\n    length = take(shape_of(orig), const(0, dtype=\"int32\"), axis=0)\n\n    grad_start = cast_like(_sum(grad), start)\n    grad_stop = zeros_like(stop)\n    grad_step = cast_like(arange(length, dtype=\"int32\"), grad) * grad\n    grad_step = cast_like(_sum(grad_step), step)\n\n    return [grad_start, grad_stop, grad_step]\n\n\n@register_gradient(\"gather_nd\")\ndef gather_nd_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of gather_nd, which is simply scatter_nd.\n    \"\"\"\n    data, indices = orig.args\n    return [scatter_nd(zeros_like(data), indices, grad, mode=\"add\"), zeros_like(indices)]\n\n\n@register_gradient(\"reshape_like\")\ndef reshape_like_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of reshape_like.\n    \"\"\"\n    data, shape_like = orig.args\n    return [reshape_like(grad, data), zeros_like(shape_like)]\n\n\n@register_gradient(\"where\")\ndef where_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of where.\n    \"\"\"\n    cond, x, y = orig.args\n    g_zeros = zeros_like(grad)\n\n    grad_x = collapse_sum_like(where(cond, grad, g_zeros), x)\n    grad_y = collapse_sum_like(where(cond, g_zeros, grad), y)\n\n    return [zeros_like(cond), grad_x, grad_y]\n\n\n@register_gradient(\"less_equal\")\ndef less_equal_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of less_equal.\n    \"\"\"\n    return [zeros_like(orig.args[0]), zeros_like(orig.args[1])]\n\n\n@register_gradient(\"not_equal\")\ndef not_equal_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of not_equal (just zeros).\n    \"\"\"\n    return [zeros_like(orig.args[0]), zeros_like(orig.args[1])]\n\n\n@register_gradient(\"strided_slice\")\ndef strided_slice_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of strided_slice, which is equal to grad where the\n    input was sliced and zero elsewhere.\n    \"\"\"\n    assert orig.attrs.axes is None, \"grad for strided_slice with axes is not yet supported\"\n    x = orig.args[0]\n    begin = get_const_tuple(orig.attrs.begin)\n    end = get_const_tuple(orig.attrs.end)\n    strides = get_const_tuple(orig.attrs.strides)\n    if orig.attrs.slice_mode == \"size\":\n        # convert sizes to ending indices and ignore strides\n        end = list(end)\n        for i, (start, size) in enumerate(zip(begin, end)):\n            if size == -1:\n                end[i] = int(x.checked_type.shape[i])\n            else:\n                end[i] = start + size\n        strides = None\n    else:\n        assert orig.attrs.slice_mode == \"end\"\n    return [strided_set(zeros_like(x), grad, begin, end, strides)]\n\n\n@register_gradient(\"one_hot\")\ndef one_hot_grad(orig, grad):\n    \"\"\"\n    Returns the gradient of one_hot, which is the sum of grad at on and off\n    indices for on_value and off_value respectively.\n    \"\"\"\n    indices, on_value, off_value = orig.args\n\n    g_zeros = zeros_like(grad)\n    on_mask = equal(orig, on_value)\n    grad_on = _sum(where(on_mask, grad, g_zeros))\n    grad_off = _sum(where(on_mask, g_zeros, grad))\n\n    return [zeros_like(indices), cast_like(grad_on, on_value), cast_like(grad_off, off_value)]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend compiler related feature registration\"\"\"\n# pylint: disable=invalid-name,unused-argument, len-as-condition, too-many-nested-blocks,\n# pylint: disable=too-many-local-variables, too-many-arguments, no-else-return\n\nfrom __future__ import absolute_import\n\nimport tvm\nfrom tvm import te, topi\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\nfrom tvm.topi.utils import get_const_int, get_const_tuple\n\nfrom . import op as _reg\nfrom . import strategy\nfrom ._tensor import elemwise_shape_func\nfrom .op import OpPattern\n\n_reg.register_broadcast_schedule(\"broadcast_to\")\n_reg.register_broadcast_schedule(\"broadcast_to_like\")\n_reg.register_broadcast_schedule(\"expand_dims\")\n_reg.register_broadcast_schedule(\"repeat\")\n_reg.register_broadcast_schedule(\"tile\")\n_reg.register_broadcast_schedule(\"where\")\n_reg.register_injective_schedule(\"squeeze\")\n_reg.register_injective_schedule(\"reshape\")\n_reg.register_injective_schedule(\"reshape_like\")\n_reg.register_injective_schedule(\"full\")\n_reg.register_injective_schedule(\"full_like\")\n_reg.register_injective_schedule(\"arange\")\n_reg.register_injective_schedule(\"meshgrid\")\n_reg.register_injective_schedule(\"reverse\")\n_reg.register_injective_schedule(\"reverse_sequence\")\n_reg.register_injective_schedule(\"cast\")\n_reg.register_injective_schedule(\"cast_like\")\n_reg.register_injective_schedule(\"reinterpret\")\n_reg.register_injective_schedule(\"strided_slice\")\n_reg.register_injective_schedule(\"slice_like\")\n_reg.register_injective_schedule(\"split\")\n_reg.register_injective_schedule(\"take\")\n_reg.register_injective_schedule(\"stack\")\n_reg.register_injective_schedule(\"contrib_reverse_reshape\")\n_reg.register_injective_schedule(\"gather\")\n_reg.register_injective_schedule(\"gather_nd\")\n_reg.register_injective_schedule(\"sequence_mask\")\n_reg.register_injective_schedule(\"one_hot\")\n_reg.register_reduce_schedule(\"collapse_sum_like\")\n_reg.register_reduce_schedule(\"collapse_sum_to\")\n_reg.register_injective_schedule(\"unravel_index\")\n_reg.register_injective_schedule(\"sparse_to_dense\")\n_reg.register_injective_schedule(\"matrix_set_diag\")\n_reg.register_injective_schedule(\"adv_index\")\n\n\n# concatenate\n@_reg.register_compute(\"concatenate\")\ndef compute_concat(attrs, inputs, output_type):\n    return [topi.concatenate(inputs, attrs.axis)]\n\n\n_reg.register_strategy(\"concatenate\", strategy.concatenate_strategy)\n\n# sliding_window\n@_reg.register_compute(\"sliding_window\")\ndef compute_sliding_window(attrs, inputs, output_type):\n    \"\"\"Compute definition of sliding_window\"\"\"\n    return [topi.sliding_window(inputs[0], attrs.axis, attrs.window_shape, attrs.strides)]\n\n\n_reg.register_strategy(\"sliding_window\", strategy.sliding_window_strategy)\n\n# strided_set\n@_reg.register_compute(\"strided_set\")\ndef compute_strided_set(attrs, inputs, output_type):\n    \"\"\"Compute definition of strided_set\"\"\"\n    return [topi.strided_set(inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])]\n\n\n_reg.register_injective_schedule(\"strided_set\")\n\n# layout_transform\n_reg.register_injective_schedule(\"layout_transform\")\n_reg.register_pattern(\"layout_transform\", OpPattern.INJECTIVE)\n_reg.register_injective_schedule(\"auto_scheduler_layout_transform\")\n_reg.register_pattern(\"auto_scheduler_layout_transform\", OpPattern.INJECTIVE)\n_reg.register_injective_schedule(\"meta_schedule_layout_transform\")\n_reg.register_pattern(\"meta_schedule_layout_transform\", OpPattern.INJECTIVE)\n\n# argwhere\n_reg.register_strategy(\"argwhere\", strategy.argwhere_strategy)\n\n# scatter\n@_reg.register_compute(\"scatter\")\ndef compute_scatter(attrs, inputs, output_type):\n    \"\"\"Compute definition of scatter\"\"\"\n    return [topi.scatter(inputs[0], inputs[1], inputs[2], attrs.axis)]\n\n\n_reg.register_strategy(\"scatter\", strategy.scatter_strategy)\n\n# sparse_fill_empty_rows\n@_reg.register_compute(\"sparse_fill_empty_rows\")\ndef compute_sparse_fill_empty_rows(attrs, inputs, output_type):\n    \"\"\"Compute definition of sparse_fill_empty_rows\"\"\"\n\n    return topi.sparse_fill_empty_rows(\n        inputs[0],\n        inputs[1],\n        inputs[2],\n        inputs[3],\n        output_type.fields[0].shape,\n        output_type.fields[1].shape,\n        output_type.fields[2].shape,\n    )\n\n\n_reg.register_strategy(\"sparse_fill_empty_rows\", strategy.sparse_fill_empty_rows_strategy)\n\n# sparse_reshape\n@_reg.register_compute(\"sparse_reshape\")\ndef compute_reshape(attrs, inputs, output_type):\n    \"\"\"Compute definition of sparse_reshape\"\"\"\n\n    return topi.sparse_reshape(\n        inputs[0],\n        inputs[1],\n        inputs[2],\n        output_type.fields[0].shape,\n        output_type.fields[1].shape,\n    )\n\n\n_reg.register_strategy(\"sparse_reshape\", strategy.sparse_reshape_strategy)\n\n# stft\n@_reg.register_compute(\"stft\")\ndef compute_stft(attrs, inputs, output_type):\n    \"\"\"Compute definition of stft\"\"\"\n    return topi.stft(\n        inputs[0],\n        attrs.n_fft,\n        attrs.hop_length,\n        attrs.win_length,\n        attrs.window,\n        attrs.normalized,\n        attrs.onesided,\n        output_type.shape,\n    )\n\n\n_reg.register_strategy(\"stft\", strategy.stft_strategy)\n\n\n@script\ndef _stft_shape_func(data, n_fft, hop_length, onesided):\n    output_shape = output_tensor((4,), \"int64\")\n    output_shape[0] = int64(data.shape[0])\n    if onesided:\n        output_shape[1] = int64(int64(n_fft) // int64(2)) + int64(1)\n    else:\n        output_shape[1] = int64(n_fft)\n    output_shape[2] = int64(int64(data.shape[1] - n_fft) // int64(hop_length)) + int64(1)\n    output_shape[3] = int64(2)\n    return output_shape\n\n\n@_reg.register_shape_func(\"stft\", True)\ndef stft_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for stft.\n    \"\"\"\n    return [\n        _stft_shape_func(\n            inputs[0], convert(attrs.n_fft), convert(attrs.hop_length), convert(attrs.onesided)\n        )\n    ]\n\n\n# trilu\n_reg.register_strategy(\"trilu\", strategy.trilu_strategy)\n\n\n# scatter_add\n@_reg.register_compute(\"scatter_add\")\ndef compute_scatter_add(attrs, inputs, output_type):\n    \"\"\"Compute definition of scatter_add\"\"\"\n    return [topi.scatter_add(inputs[0], inputs[1], inputs[2], attrs.axis)]\n\n\n_reg.register_strategy(\"scatter_add\", strategy.scatter_add_strategy)\n\n# scatter_nd\n@_reg.register_compute(\"scatter_nd\")\ndef compute_scatter_nd(attrs, inputs, output_type):\n    \"\"\"Compute definition of scatter_nd\"\"\"\n    return [topi.scatter_nd(inputs[0], inputs[1], inputs[2], attrs.mode)]\n\n\n_reg.register_strategy(\"scatter_nd\", strategy.scatter_nd_strategy)\n\n# cumsum\n@_reg.register_compute(\"cumsum\")\ndef compute_cumsum(attrs, inputs, output_type):\n    \"\"\"Compute definition of cumsum\"\"\"\n    return [topi.cumsum(inputs[0], attrs.axis, attrs.dtype, attrs.exclusive)]\n\n\n_reg.register_strategy(\"cumsum\", strategy.cumsum_strategy)\n_reg.register_shape_func(\"cumsum\", False, elemwise_shape_func)\n\n# cumprod\n@_reg.register_compute(\"cumprod\")\ndef compute_cumprod(attrs, inputs, output_type):\n    \"\"\"Compute definition of cumprod\"\"\"\n    return [topi.cumprod(inputs[0], attrs.axis, attrs.dtype, attrs.exclusive)]\n\n\n_reg.register_strategy(\"cumprod\", strategy.cumprod_strategy)\n_reg.register_shape_func(\"cumprod\", False, elemwise_shape_func)\n\n\n@_reg.register_compute(\"unique\")\ndef compute_unique(attrs, inputs, output_type):\n    \"\"\"Compute definition of unique\"\"\"\n    return topi.unique(inputs[0], attrs.sorted, attrs.return_counts)\n\n\n_reg.register_strategy(\"unique\", strategy.unique_strategy)\n\n# invert_permutation\n_reg.register_strategy(\"invert_permutation\", strategy.invert_permutation_strategy)\n_reg.register_shape_func(\"invert_permutation\", False, elemwise_shape_func)\n\n\n#####################\n#  Shape functions  #\n#####################\n\n\n@script\ndef _arange_shape_func(start, stop, step):\n    out = output_tensor((1,), \"int64\")\n    if step[()] < 0:\n        out[0] = int64(ceil_div((int64(start[()]) - int64(stop[()])), int64(-step[()])))\n    else:\n        out[0] = int64(ceil_div((int64(stop[()]) - int64(start[()])), int64(step[()])))\n    return out\n\n\n@_reg.register_shape_func(\"arange\", True)\ndef arange_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for arange\n    \"\"\"\n    return [_arange_shape_func(*inputs)]\n\n\n@script\ndef _strided_slice_shape_func_input_shape(data_shape, begin, end, strides, slice_mode):\n    ndim = len(data_shape)\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        dim_size = int64(data_shape[i])\n        cbegin = int64(0)\n        cend = dim_size\n        cstride = int64(1)\n\n        if len(strides) > i:\n            cstride = int64(strides[i])\n\n        if len(begin) > i:\n            cbegin = int64(begin[i])\n        elif cstride < 0:\n            cbegin = dim_size\n\n        if len(end) <= i:\n            if cstride < 0:\n                cend = int64(0)\n        elif slice_mode != 0:\n            cstride = int64(1)\n            if end[i] < 0:\n                cend = dim_size\n            else:\n                cend = cbegin + int64(end[i])\n        else:\n            if end[i] > data_shape[i]:\n                cend = dim_size\n            else:\n                cend = int64(end[i])\n\n        assert cstride != 0, \"Strides can't be zero.\"\n\n        if cbegin < 0:\n            cbegin += dim_size\n        if cend < 0:\n            cend += dim_size\n\n        if cstride < 0:\n            if cend < 0:\n                cend = int64(-1)\n            if cbegin > dim_size - 1:\n                cbegin = dim_size - 1\n            slice_range = cbegin - cend\n            step = -cstride\n        else:\n            slice_range = cend - cbegin\n            step = cstride\n        out[i] = int64(ceil_div(slice_range, step))\n    return out\n\n\n@script\ndef _strided_slice_shape_func_with_axes(data_shape, begin, end, strides, slice_mode, axes):\n    ndim = data_shape.shape[0]\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        out[i] = data_shape[i]\n\n    for i in const_range(len(axes)):\n        dim_size = int64(data_shape[axes[i]])\n        cbegin = int64(0)\n        cend = dim_size\n        cstride = int64(1)\n\n        if len(strides) > i:\n            cstride = int64(strides[i])\n\n        if len(begin) > i:\n            cbegin = int64(begin[i])\n        elif cstride < 0:\n            cbegin = dim_size\n\n        if len(end) <= i:\n            cend = dim_size\n        elif slice_mode != 0:\n            cstride = int64(1)\n            if end[i] < 0:\n                cend = dim_size\n            else:\n                cend = cbegin + int64(end[i])\n        else:\n            if end[i] > data_shape[axes[i]]:\n                cend = dim_size\n            else:\n                cend = int64(end[i])\n\n        assert cstride != 0, \"Strides can't be zero.\"\n\n        if cbegin < 0:\n            cbegin += dim_size\n        if cend < 0:\n            cend += dim_size\n\n        if cstride < 0:\n            if cend < 0:\n                cend = int64(-1)\n            if cbegin > dim_size - 1:\n                cbegin = dim_size - 1\n            slice_range = cbegin - cend\n            step = -cstride\n        else:\n            slice_range = cend - cbegin\n            step = cstride\n\n        out[axes[i]] = int64(ceil_div(slice_range, step))\n    return out\n\n\n@_reg.register_shape_func(\"strided_slice\", False)\ndef strided_slice_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for strided_slice\n    \"\"\"\n    slice_mode = convert(0 if attrs.slice_mode == \"end\" else 1)\n    if attrs.axes is None:\n        return [\n            _strided_slice_shape_func_input_shape(\n                inputs[0], attrs.begin, attrs.end, attrs.strides, slice_mode\n            )\n        ]\n    return [\n        _strided_slice_shape_func_with_axes(\n            inputs[0], attrs.begin, attrs.end, attrs.strides, slice_mode, attrs.axes\n        )\n    ]\n\n\n@script\ndef _one_hot_shape_func(indices_shape, depth, axis):\n    in_ndim = indices_shape.shape[0]\n    out_ndim = in_ndim + 1\n    true_axis = in_ndim if axis == -1 else axis\n    indices_i = 0\n    out = output_tensor((out_ndim,), \"int64\")\n    for i in range(out_ndim):\n        if i == true_axis:\n            out[i] = int64(depth)\n        else:\n            out[i] = int64(indices_shape[indices_i])\n            indices_i += 1\n    return out\n\n\n@_reg.register_shape_func(\"one_hot\", False)\ndef one_hot_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for one_hot\n    \"\"\"\n    shape_func = [_one_hot_shape_func(inputs[0], convert(attrs.depth), convert(attrs.axis))]\n    return shape_func\n\n\n@script\ndef _concatenate_shape_func(inputs, axis):\n    ndim = inputs[0].shape[0]\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        if i != axis:\n            out[i] = inputs[0][i]\n            for j in const_range(1, len(inputs)):\n                assert out[i] == inputs[j][i], \"Dims mismatch in the inputs of concatenate.\"\n        else:\n            out[i] = int64(0)\n            for j in const_range(len(inputs)):\n                out[i] += inputs[j][i]\n    return out\n\n\n@_reg.register_shape_func(\"concatenate\", False)\ndef concatenate_shape_func(attrs, inputs, _):\n    axis = get_const_int(attrs.axis)\n    if axis < 0:\n        axis += inputs[0].shape[0]\n    return [_concatenate_shape_func(inputs, convert(axis))]\n\n\n@script\ndef _reshape_shape_func_input_shape(data_shape, newshape, ndim, allowzero):\n    out = output_tensor((ndim,), \"int64\")\n    src_idx = 0\n    dst_idx = 0\n    infer_idx = -1\n    copy = False\n    skip = 0\n    for i in const_range(len(newshape)):\n        if skip > 0:\n            skip -= 1\n        elif newshape[i] > 0:\n            out[dst_idx] = int64(newshape[i])\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == 0:\n            if allowzero:\n                out[dst_idx] = int64(newshape[i])\n            else:\n                out[dst_idx] = data_shape[src_idx]\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == -1:\n            assert infer_idx < 0, \"One and only one dim can be inferred\"\n            out[dst_idx] = int64(1)\n            infer_idx = i\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == -2:\n            copy = True\n        elif newshape[i] == -3:\n            assert data_shape.shape[0] - src_idx > 1, \"Not enough dims in input shape for -3\"\n            out[dst_idx] = data_shape[src_idx] * data_shape[src_idx + 1]\n            src_idx += 2\n            dst_idx += 1\n        elif newshape[i] == -4:\n            assert len(newshape) - i > 2, \"Not enough dims in new shape for -4\"\n            if newshape[i + 1] == -1:\n                assert newshape[i + 2] != -1, \"Split dims cannot both be -1.\"\n                out[dst_idx] = data_shape[src_idx] // int64(newshape[i + 2])\n                out[dst_idx + 1] = int64(newshape[i + 2])\n            else:\n                out[dst_idx] = int64(newshape[i + 1])\n                if newshape[i + 2] == -1:\n                    out[dst_idx + 1] = data_shape[src_idx] // int64(newshape[i + 1])\n                else:\n                    out[dst_idx + 1] = int64(newshape[i + 2])\n            assert (\n                data_shape[src_idx] == out[dst_idx] * out[dst_idx + 1]\n            ), \"Product of split dims doesn't match to input dim\"\n            src_idx += 1\n            dst_idx += 2\n            skip = 2\n        else:\n            assert False, \"Invalid special values in new shape\"\n    if len(data_shape.shape) > 0:\n        # if data is not constant, we can then handle -1 and -2\n        if copy:\n            for i in range(src_idx, data_shape.shape[0]):\n                out[dst_idx] = data_shape[i]\n                dst_idx += 1\n        if infer_idx >= 0:\n            old_size = int64(1)\n            for i in const_range(data_shape.shape[0]):\n                old_size *= data_shape[i]\n            new_size = int64(1)\n            for i in const_range(out.shape[0]):\n                new_size *= out[i]\n            out[infer_idx] = old_size // new_size\n    return out\n\n\n@_reg.register_shape_func(\"reshape\", False)\ndef reshape_shape_func(attrs, inputs, out_ndims):\n    newshape = get_const_tuple(attrs.newshape)\n    allowzero = attrs.allowzero\n    return [\n        _reshape_shape_func_input_shape(\n            inputs[0], convert(newshape), out_ndims[0], convert(allowzero)\n        )\n    ]\n\n\n@script\ndef _take_no_axis_shape_func(indices_shape, out_ndim):\n    out = output_tensor((out_ndim,), \"int64\")\n    for i in const_range(out_ndim):\n        out[i] = indices_shape[i]\n    return out\n\n\n@script\ndef _take_with_axis_shape_func(data_shape, indices_shape, axis, batch_dims, out_ndim):\n    out = output_tensor((out_ndim,), \"int64\")\n    for i in const_range(axis):\n        out[i] = data_shape[i]\n    if len(indices_shape.shape) == 0:\n        # indices is constant\n        for i in const_range(axis + 1, len(data_shape)):\n            out[i - 1] = data_shape[i]\n    else:\n        for i in const_range(len(indices_shape) - batch_dims):\n            out[axis + i] = indices_shape[i + batch_dims]\n        for i in const_range(axis + 1, len(data_shape)):\n            out[len(indices_shape) + i - 1 - batch_dims] = data_shape[i]\n    return out\n\n\n@_reg.register_shape_func(\"take\", False)\ndef take_shape_func(attrs, inputs, out_ndims):\n    \"\"\"\n    Shape function for take op.\n    \"\"\"\n    if attrs.axis is None:\n        return [_take_no_axis_shape_func(inputs[1], out_ndims[0])]\n    axis = get_const_int(attrs.axis)\n    batch_dims = get_const_int(attrs.batch_dims)\n    data_ndim = int(inputs[0].shape[0])\n    if inputs[1].shape:\n        indices_ndim = int(inputs[1].shape[0])\n    if axis < 0:\n        axis += data_ndim\n    assert 0 <= axis < data_ndim\n    if batch_dims < 0:\n        batch_dims += indices_ndim\n    return [_take_with_axis_shape_func(*inputs, convert(axis), convert(batch_dims), out_ndims[0])]\n\n\n@_reg.register_legalize(\"take\")\ndef legalize_dyn_topk(attrs, inputs, types):\n    \"\"\"Legalize take op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.take_legalize(attrs, inputs, types)\n\n\n@script\ndef _argwhere_shape_func_1d(condition):\n    out = output_tensor((2,), \"int64\")\n    out[0] = int64(0)\n    out[1] = int64(1)\n    for i1 in range(condition.shape[0]):\n        if condition[i1] != 0:\n            out[0] += int64(1)\n    return out\n\n\n@script\ndef _argwhere_shape_func_2d(condition):\n    out = output_tensor((2,), \"int64\")\n    out[0] = int64(0)\n    out[1] = int64(2)\n    for i1 in range(condition.shape[0]):\n        for i2 in range(condition.shape[1]):\n            if condition[i1, i2] != 0:\n                out[0] += int64(1)\n    return out\n\n\n@script\ndef _argwhere_shape_func_3d(condition):\n    out = output_tensor((2,), \"int64\")\n    out[0] = int64(0)\n    out[1] = int64(3)\n    for i1 in range(condition.shape[0]):\n        for i2 in range(condition.shape[1]):\n            for i3 in range(condition.shape[2]):\n                if condition[i1, i2, i3] != 0:\n                    out[0] += int64(1)\n    return out\n\n\n@script\ndef _argwhere_shape_func_4d(condition):\n    out = output_tensor((2,), \"int64\")\n    out[0] = int64(0)\n    out[1] = int64(4)\n    for i1 in range(condition.shape[0]):\n        for i2 in range(condition.shape[1]):\n            for i3 in range(condition.shape[2]):\n                for i4 in range(condition.shape[3]):\n                    if condition[i1, i2, i3, i4] != 0:\n                        out[0] += int64(1)\n    return out\n\n\n@script\ndef _argwhere_shape_func_5d(condition):\n    out = output_tensor((2,), \"int64\")\n    out[0] = int64(0)\n    out[1] = int64(5)\n    for i1 in range(condition.shape[0]):\n        for i2 in range(condition.shape[1]):\n            for i3 in range(condition.shape[2]):\n                for i4 in range(condition.shape[3]):\n                    for i5 in range(condition.shape[4]):\n                        if condition[i1, i2, i3, i4, i5] != 0:\n                            out[0] += int64(1)\n    return out\n\n\n@_reg.register_shape_func(\"argwhere\", True)\ndef argwhere_shape_func(attrs, inputs, out_ndims):\n    \"\"\"\n    Shape function for argwhere.\n    \"\"\"\n    if len(inputs[0].shape) == 1:\n        return [_argwhere_shape_func_1d(inputs[0])]\n    if len(inputs[0].shape) == 2:\n        return [_argwhere_shape_func_2d(inputs[0])]\n    if len(inputs[0].shape) == 3:\n        return [_argwhere_shape_func_3d(inputs[0])]\n    if len(inputs[0].shape) == 4:\n        return [_argwhere_shape_func_4d(inputs[0])]\n    if len(inputs[0].shape) == 5:\n        return [_argwhere_shape_func_5d(inputs[0])]\n    return ValueError(\"Does not support rank higher than 5 in argwhere\")\n\n\n_reg.register_shape_func(\"scatter\", False, elemwise_shape_func)\n_reg.register_shape_func(\"scatter_add\", False, elemwise_shape_func)\n_reg.register_shape_func(\"scatter_nd\", False, elemwise_shape_func)\n\n\n@script\ndef _sparse_fill_empty_rows_shape_func(sparse_indices, dense_shape):\n\n    new_sparse_indices_shape = output_tensor((2,), \"int64\")\n    new_sparse_values_shape = output_tensor((1,), \"int64\")\n    empty_row_indicator_shape = output_tensor((1,), \"int64\")\n    num_dense_rows = int64(dense_shape[0])\n\n    if int64(sparse_indices.shape[0]) == int64(0):  # Handle Empty Case\n        #  Total rows will equal dense_shape[0]\n        new_sparse_indices_shape[0] = num_dense_rows\n        new_sparse_indices_shape[1] = int64(sparse_indices.shape[1])\n        new_sparse_values_shape[0] = num_dense_rows\n        empty_row_indicator_shape[0] = num_dense_rows\n        return (new_sparse_indices_shape, new_sparse_values_shape, empty_row_indicator_shape)\n\n    else:\n        count = int64(sparse_indices.shape[0])  # Add count of all rows already in sparse_indices\n        for i in range(1, int64(sparse_indices.shape[0])):\n            index = int64(sparse_indices[i, 0])\n            prev_index = int64(sparse_indices[i - 1, 0] + 1)\n\n            if index > prev_index:\n                count += index - prev_index  # Add count of all rows between two consecutive indices\n\n        count += int64(sparse_indices[0, 0])  # Add count from 0 to first row id in sparse_indices\n        count += int64(\n            num_dense_rows - 1 - sparse_indices[sparse_indices.shape[0] - 1, 0]\n        )  # Add count from last row id to dense_shape - 1\n        new_sparse_indices_shape[0] = int64(count)\n        new_sparse_indices_shape[1] = int64(sparse_indices.shape[1])\n        new_sparse_values_shape[0] = int64(count)\n        empty_row_indicator_shape[0] = num_dense_rows\n        return (new_sparse_indices_shape, new_sparse_values_shape, empty_row_indicator_shape)\n\n\n@_reg.register_shape_func(\"sparse_fill_empty_rows\", True)\ndef sparse_fill_empty_rows_func(attrs, inputs, _):\n    return _sparse_fill_empty_rows_shape_func(inputs[0], inputs[2])\n\n\n@script\ndef _sparse_reshape_shape_func(sparse_indices_shape, prev_shape_shape, new_shape_shape):\n    indices_shape = output_tensor((2,), \"int64\")\n    indices_shape[0] = int64(sparse_indices_shape[0])\n    indices_shape[1] = int64(new_shape_shape[0])\n    shape_tensor = output_tensor((1,), \"int64\")\n    shape_tensor[0] = int64(new_shape_shape[0])\n    return (indices_shape, shape_tensor)\n\n\n@_reg.register_shape_func(\"sparse_reshape\", False)\ndef sparse_reshape_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for sparse_reshape.\n    \"\"\"\n    return _sparse_reshape_shape_func(inputs[0], inputs[1], inputs[2])\n\n\n@script\ndef _layout_transform_shape_func(\n    data_shape, out_layout_len, dst_equal_list, dst_mul_list, dst_div_list, dst_mix_list\n):\n    out = output_tensor((out_layout_len,), \"int64\")\n    for i in const_range(len(dst_equal_list)):\n        out[dst_equal_list[i][0]] = data_shape[dst_equal_list[i][1]]\n    for i in const_range(len(dst_mul_list)):\n        out[dst_mul_list[i][0]] = data_shape[dst_mul_list[i][1]] * data_shape[dst_mul_list[i][2]]\n    for i in const_range(len(dst_div_list)):\n        out[dst_div_list[i][0]] = data_shape[dst_div_list[i][1]] // dst_div_list[i][3]\n        out[dst_div_list[i][2]] = int64(dst_div_list[i][3])\n    for i in const_range(len(dst_mix_list)):\n        out[dst_mix_list[i][0]] = (\n            data_shape[dst_mix_list[i][1]] * dst_mix_list[i][2] // dst_mix_list[i][4]\n        )\n        out[dst_mix_list[i][3]] = int64(dst_mix_list[i][4])\n\n    return out\n\n\n@_reg.register_shape_func(\"layout_transform\", False)\ndef layout_transform_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for layout_transform op.\n    \"\"\"\n\n    def _fetch_axis(layout):\n        major_axes = []\n        minor_axes = {}\n        num_start = -1\n        for i, item in enumerate(layout):\n            if \"A\" <= item <= \"Z\":\n                major_axes.append(item)\n            elif \"a\" <= item <= \"z\":\n                last_num = int(layout[num_start:i])\n                minor_axes[item] = last_num\n                num_start = -1\n            elif num_start < 0:\n                num_start = i\n        return major_axes, minor_axes\n\n    _, src_minor_axes = _fetch_axis(attrs.src_layout)\n    dst_major_axes, dst_minor_axes = _fetch_axis(attrs.dst_layout)\n    src_letter_list = []\n    dst_letter_list = []\n    for item in attrs.src_layout:\n        if \"A\" <= item <= \"Z\" or \"a\" <= item <= \"z\":\n            src_letter_list.append(item)\n    for item in attrs.dst_layout:\n        if \"A\" <= item <= \"Z\" or \"a\" <= item <= \"z\":\n            dst_letter_list.append(item)\n    out_layout_len = len(dst_major_axes) + len(dst_minor_axes)\n    dst_equal_list = []\n    dst_mul_list = []\n    dst_div_list = []\n    dst_mix_list = []\n\n    for key in dst_major_axes:\n        if key.lower() not in dst_minor_axes:\n            if key.lower() not in src_minor_axes:\n                dst_equal_list.append((dst_letter_list.index(key), src_letter_list.index(key)))\n            else:\n                dst_mul_list.append(\n                    (\n                        dst_letter_list.index(key),\n                        src_letter_list.index(key),\n                        src_letter_list.index(key.lower()),\n                    )\n                )\n        else:\n            if key.lower() not in src_minor_axes:\n                dst_div_list.append(\n                    (\n                        dst_letter_list.index(key),\n                        src_letter_list.index(key),\n                        dst_letter_list.index(key.lower()),\n                        dst_minor_axes[key.lower()],\n                    )\n                )\n            else:\n                dst_mix_list.append(\n                    (\n                        dst_letter_list.index(key),\n                        src_letter_list.index(key),\n                        src_minor_axes[key.lower()],\n                        dst_letter_list.index(key.lower()),\n                        dst_minor_axes[key.lower()],\n                    )\n                )\n\n    return [\n        _layout_transform_shape_func(\n            inputs[0],\n            convert(out_layout_len),\n            convert(dst_equal_list),\n            convert(dst_mul_list),\n            convert(dst_div_list),\n            convert(dst_mix_list),\n        )\n    ]\n\n\n@script\ndef _expand_dim_shape_func(data_shape, ndim, axis, num_newaxis):\n    out = output_tensor((ndim + num_newaxis,), \"int64\")\n    for i in const_range(out.shape[0]):\n        if i < axis:\n            out[i] = data_shape[i]\n        elif i < axis + num_newaxis:\n            out[i] = int64(1)\n        else:\n            out[i] = data_shape[i - num_newaxis]\n\n    return out\n\n\n@_reg.register_shape_func(\"expand_dims\", False)\ndef expand_dim_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for expand_dim op.\n    \"\"\"\n    axis = get_const_int(attrs.axis)\n    num_newaxis = get_const_int(attrs.num_newaxis)\n    if axis < 0:\n        axis = inputs[0].shape[0] + axis + 1\n    ndim = inputs[0].shape[0] if inputs[0].shape else 0\n    return [_expand_dim_shape_func(inputs[0], convert(ndim), convert(axis), convert(num_newaxis))]\n\n\n@script\ndef _transpose_shape_func(data_shape, axes):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(len(axes)):\n        out[i] = data_shape[axes[i]]\n\n    return out\n\n\n@_reg.register_shape_func(\"transpose\", False)\ndef transpose_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for transpose op.\n    \"\"\"\n    axes = attrs.axes if attrs.axes is None else get_const_tuple(attrs.axes)\n    if axes is None:\n        axes = list(range(inputs[0].shape[0].value))\n        axes.reverse()\n    axes = list(axes)\n    for i, axis in enumerate(axes):\n        if axis < 0:\n            axes[i] = inputs[0].shape[0] + axis\n    return [_transpose_shape_func(inputs[0], convert(axes))]\n\n\n_reg.register_schedule(\"transpose\", strategy.schedule_transpose)\n\n\n@script\ndef _squeeze_shape_func(data_shape, keep_axes, remove_axes):\n    out = output_tensor((len(keep_axes),), \"int64\")\n    for i in const_range(len(keep_axes)):\n        out[i] = data_shape[keep_axes[i]]\n\n    for i in const_range(len(remove_axes)):\n        assert data_shape[remove_axes[i]] == 1, \"Removed dimension must have size 1\"\n\n    return out\n\n\n@_reg.register_shape_func(\"squeeze\", False)\ndef squeeze_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for squeeze op.\n    \"\"\"\n    axis = attrs.axis if attrs.axis is None else get_const_tuple(attrs.axis)\n    keep_axes = []\n    remove_axes = []\n    if axis is not None:\n        for i in range(inputs[0].shape[0].value):\n            if i not in axis:\n                keep_axes.append(i)\n            else:\n                remove_axes.append(i)\n\n    # Due to current relay type system, it is possible even\n    # a static kernel function needs shape function. To handle\n    # this case, we allow axis to be None in squeeze shape func\n    # for now.\n    # TODO(kevinthesun): Enhance relay type system to avoid this.\n    if keep_axes:\n        out = _squeeze_shape_func(inputs[0], convert(keep_axes), convert(remove_axes))\n    else:\n        out = te.compute((), lambda *indices: 0)\n    return [out]\n\n\n@script\ndef _reshape_like_shape_func(target_shape):\n    out = output_tensor((target_shape.shape[0],), \"int64\")\n    for i in const_range(target_shape.shape[0]):\n        out[i] = target_shape[i]\n\n    return out\n\n\n@_reg.register_shape_func(\"reshape_like\", False)\ndef reshape_like_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for reshape_like op.\n    \"\"\"\n    return [_reshape_like_shape_func(inputs[1])]\n\n\n@script\ndef _tile_shape_func(data, reps, ndim, tndim, rndim):\n    out = output_tensor((tndim,), \"int64\")\n\n    if ndim == rndim:\n        for i in const_range(tndim):\n            out[i] = data[i] * int64(reps[i])\n    elif ndim > rndim:\n        ngap = ndim - rndim\n        for i in const_range(ndim):\n            if i < ngap:\n                out[i] = data[i]\n            else:\n                out[i] = data[i] * int64(reps[i - ngap])\n    else:\n        rgap = rndim - ndim\n        for i in const_range(rndim):\n            if i < rgap:\n                out[i] = int64(reps[i])\n            else:\n                out[i] = int64(reps[i]) * data[i - rgap]\n    return out\n\n\n@_reg.register_shape_func(\"tile\", False)\ndef tile_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for tile op.\n    \"\"\"\n    reps = get_const_tuple(attrs.reps)\n    ndim = inputs[0].shape[0].value\n    rndim = len(reps)\n    tndim = ndim if ndim > rndim else rndim\n    return [\n        _tile_shape_func(inputs[0], convert(reps), convert(ndim), convert(tndim), convert(rndim))\n    ]\n\n\n@script\ndef _split_shape_func(data_shape, index, indices_or_sections, param_is_indices, axis):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    if param_is_indices:\n        for i in const_range(data_shape.shape[0]):\n            if i == axis:\n                assert (\n                    data_shape[axis] % indices_or_sections[0] == 0\n                ), \"num_sections must be an integer factor of the size of axis\"\n                out[i] = ceil_div(data_shape[axis], indices_or_sections[0])\n            else:\n                out[i] = data_shape[i]\n    else:\n        start = int64(0)\n        if index > 0:\n            start = int64(indices_or_sections[index - 1])\n        end = data_shape[axis]\n        if index < len(indices_or_sections):\n            end = int64(indices_or_sections[index])\n        for i in const_range(data_shape.shape[0]):\n            if i == axis:\n                out[i] = end - start\n            else:\n                out[i] = data_shape[i]\n    return out\n\n\n@_reg.register_shape_func(\"split\", False)\ndef split_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for split op.\n    \"\"\"\n    if isinstance(attrs.indices_or_sections, (int, tvm.tir.IntImm)):\n        indices_or_sections = get_const_int(attrs.indices_or_sections)\n        assert indices_or_sections > 0, \"Slice count must be > 0\"\n    else:\n        indices_or_sections = list(get_const_tuple(attrs.indices_or_sections))\n        assert sorted(indices_or_sections)[0] > 0 and indices_or_sections == sorted(\n            indices_or_sections\n        ), \"split_indices must be sorted\"\n\n    axis = get_const_int(attrs.axis)\n\n    if axis < 0:\n        axis += get_const_int(inputs[0].shape[0])\n\n    num_out = (\n        indices_or_sections\n        if isinstance(indices_or_sections, int)\n        else len(indices_or_sections) + 1\n    )\n\n    param_is_indices = isinstance(indices_or_sections, int)\n    if param_is_indices:\n        indices_or_sections = [indices_or_sections]\n    return [\n        _split_shape_func(\n            inputs[0],\n            convert(i),\n            convert(indices_or_sections),\n            convert(param_is_indices),\n            convert(axis),\n        )\n        for i in range(num_out)\n    ]\n\n\n@script\ndef _repeat_shape_func(data_shape, repeats, axis):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n\n    for i in const_range(data_shape.shape[0]):\n        if i == axis:\n            out[i] = int64(data_shape[i] * repeats)\n        else:\n            out[i] = data_shape[i]\n\n    return out\n\n\n@_reg.register_shape_func(\"repeat\", False)\ndef repeat_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for repeat.\n    \"\"\"\n    axis = get_const_int(attrs.axis)\n    if axis < 0:\n        axis = inputs[0].shape[0] + axis\n    return [_repeat_shape_func(inputs[0], attrs.repeats, convert(axis))]\n\n\n@_reg.register_shape_func(\"broadcast_to_like\", False)\ndef broadcast_to_like_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for broadcast_to_like.\n    \"\"\"\n    return [topi.math.identity(inputs[1])]\n\n\n@script\ndef _stack_shape_func(data_shape, axis, num_inputs):\n    out = output_tensor((data_shape.shape[0] + 1,), \"int64\")\n\n    for i in const_range(data_shape.shape[0] + 1):\n        if i == axis:\n            out[i] = int64(num_inputs)\n        elif i < axis:\n            out[i] = data_shape[i]\n        else:\n            out[i] = data_shape[i - 1]\n\n    return out\n\n\n@_reg.register_shape_func(\"stack\", False)\ndef stack_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for stack.\n    \"\"\"\n    axis = get_const_int(attrs.axis)\n    if axis < 0:\n        axis += inputs[0].shape[0] + 1\n    return [_stack_shape_func(inputs[0], convert(axis), convert(len(inputs)))]\n\n\n@script\ndef _broadcast_shape_tensors(shape_tensor1, shape_tensor2):\n    rank1 = shape_tensor1.shape[0]\n    rank2 = shape_tensor2.shape[0]\n    out_rank = max(rank1, rank2)\n    bcast_shape_tensor = output_tensor((out_rank,), \"int64\")\n\n    for index in const_range(out_rank):\n        dim1 = int64(1)\n        dim2 = int64(1)\n\n        if rank1 == out_rank:\n            dim1 = shape_tensor1[index]\n        elif rank1 - (out_rank - index) >= 0:\n            dim1 = shape_tensor1[rank1 - (out_rank - index)]\n\n        if rank2 == out_rank:\n            dim2 = shape_tensor2[index]\n        elif rank2 - (out_rank - index) >= 0:\n            dim2 = shape_tensor2[rank2 - (out_rank - index)]\n\n        assert dim1 == dim2 or dim1 == 1 or dim2 == 1, \"Invalid broadcast shapes\"\n        bcast_shape_tensor[index] = max(dim1, dim2)\n\n    return bcast_shape_tensor\n\n\n@_reg.register_shape_func(\"where\", False)\ndef where_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for where.\n    \"\"\"\n\n    def ensure_tensor(tensor):\n        if len(tensor.shape) == 0:\n            return topi.full((1,), \"int64\", 1)\n        return tensor\n\n    cond_shape = ensure_tensor(inputs[0])\n    x_shape = ensure_tensor(inputs[1])\n    y_shape = ensure_tensor(inputs[2])\n\n    bcast_shape = _broadcast_shape_tensors(x_shape, y_shape)\n    out_shape = _broadcast_shape_tensors(bcast_shape, cond_shape)\n\n    return [out_shape]\n\n\n@script\ndef _adv_index_post_process(data_shape, bcast_shape, num_indices):\n    data_rank = data_shape.shape[0]\n    bcast_rank = bcast_shape.shape[0]\n    out = output_tensor((data_rank + bcast_rank - num_indices,), \"int64\")\n\n    for i in const_range(bcast_rank):\n        out[i] = bcast_shape[i]\n    for i in const_range(data_rank - num_indices):\n        out[i + bcast_rank] = data_shape[i + num_indices]\n    return out\n\n\n@_reg.register_shape_func(\"adv_index\", False)\ndef adv_index_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for adv_index.\n    \"\"\"\n    bcast_shape = inputs[1]\n    for i in inputs[2:]:\n        bcast_shape = _broadcast_shape_tensors(bcast_shape, i)\n    return [_adv_index_post_process(inputs[0], bcast_shape, convert(len(inputs) - 1))]\n\n\n@script\ndef _unique_shape(data_shape):\n    unique_shape = output_tensor((1,), \"int64\")\n    indices_shape = output_tensor((1,), \"int64\")\n    inverse_indices_shape = output_tensor((1,), \"int64\")\n    num_unique_shape = output_tensor((1,), \"int64\")\n    unique_shape[0] = data_shape[0]\n    indices_shape[0] = data_shape[0]\n    inverse_indices_shape[0] = data_shape[0]\n    num_unique_shape[0] = int64(1)\n    return (unique_shape, indices_shape, inverse_indices_shape, num_unique_shape)\n\n\n@script\ndef _unique_with_counts_shape(data_shape):\n    unique_shape = output_tensor((1,), \"int64\")\n    indices_shape = output_tensor((1,), \"int64\")\n    inverse_indices_shape = output_tensor((1,), \"int64\")\n    num_unique_shape = output_tensor((1,), \"int64\")\n    counts_shape = output_tensor((1,), \"int64\")\n    unique_shape[0] = data_shape[0]\n    indices_shape[0] = data_shape[0]\n    inverse_indices_shape[0] = data_shape[0]\n    num_unique_shape[0] = int64(1)\n    counts_shape[0] = data_shape[0]\n    return (unique_shape, indices_shape, inverse_indices_shape, num_unique_shape, counts_shape)\n\n\n@_reg.register_shape_func(\"unique\", False)\ndef unique_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for unique operator.\n    \"\"\"\n    if attrs.return_counts:\n        return _unique_with_counts_shape(inputs[0])\n    else:\n        return _unique_shape(inputs[0])\n\n\n@script\ndef _gather_nd_shape(data_shape, indices_shape, batch_dims, index_rank):\n    ndim = data_shape.shape[0]\n    # using mdim = indices_shape[0] wouldn't work because a rank cannot\n    # depend on a runtime shape dimension of indices tensor, even if the\n    # dimension is always a known, fixed value. As a workaround, we assume that\n    # the fixed gather dimension (the size of an indexing tuple) is recorded\n    # in gather_nd op attributes.\n    mdim = index_rank\n    kdim = indices_shape.shape[0] - 1\n    out_shape = output_tensor((kdim + ndim - (mdim + batch_dims),), \"int64\")\n    for i in range(1, kdim + 1):\n        out_shape[i - 1] = indices_shape[i]\n    for i in range(mdim + batch_dims, ndim):\n        out_shape[kdim + i - (mdim + batch_dims)] = data_shape[i]\n    return out_shape\n\n\n@_reg.register_shape_func(\"gather_nd\", False)\ndef gather_nd_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for gather_nd operator.\n    \"\"\"\n    batch_dims = get_const_int(attrs.batch_dims)\n    index_rank = get_const_int(attrs.index_rank)\n\n    assert index_rank > 0, \"index_rank needs to be specified for dynamic gather_nd\"\n\n    return [_gather_nd_shape(inputs[0], inputs[1], convert(batch_dims), convert(index_rank))]\n\n\n@script\ndef _gather_shape(data_shape, indices_shape, axis):\n    out_shape = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in range(data_shape.shape[0]):\n        if i != axis:\n            assert (\n                data_shape[i] == indices_shape[i]\n            ), \"data and indices size at non-gather axes must be the same\"\n        out_shape[i] = indices_shape[i]\n    return out_shape\n\n\n@_reg.register_shape_func(\"gather\", False)\ndef gather_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for gather operator.\n    \"\"\"\n    return [_gather_shape(inputs[0], inputs[1], attrs.axis)]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/algorithm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Classic algorithm operation\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom ..expr import Constant, Expr, TupleWrapper\nfrom . import _make\nfrom .dyn import _make as _dyn_make\n\n\ndef sort(data, axis=-1, is_ascend=1):\n    \"\"\"Performs sorting along the given axis and returns data in sorted order.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data tensor.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    Returns\n    -------\n    out : relay.Expr\n        Tensor with same shape as data.\n    \"\"\"\n    return _make.sort(data, axis, is_ascend)\n\n\ndef argsort(data, axis=-1, is_ascend=1, dtype=\"int32\"):\n    \"\"\"Performs sorting along the given axis and returns an array of indices\n    having same shape as an input array that index data in sorted order.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data tensor.\n\n    valid_count : tvm.te.Tensor\n        The number of valid elements to be sorted.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        The data type of the output indices.\n\n    Returns\n    -------\n    out : relay.Expr\n        Tensor with same shape as data.\n    \"\"\"\n    return _make.argsort(data, axis, is_ascend, dtype)\n\n\ndef topk(data, k=1, axis=-1, ret_type=\"both\", is_ascend=False, dtype=\"int32\"):\n    \"\"\"Get the top k elements in an input tensor along the given axis.\n\n    ret_type specifies the return type, can be one of (\"both\", \"values\", \"indices\").\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data tensor.\n\n    k : int or relay.Expr, optional\n        Number of top elements to select. Return all elements if k < 1.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    ret_type: str, optional\n        The return type [both, values, indices].\n        \"both\": return both top k data and indices.\n        \"values\": return top k data only.\n        \"indices\": return top k indices only.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        The data type of the indices output.\n\n    Returns\n    -------\n    out : relay.Expr or List[relay.Expr]\n        The computed result.\n    \"\"\"\n    if isinstance(k, Constant):\n        k = k.data.numpy().item()\n    if isinstance(k, Expr):\n        out = _dyn_make.topk(data, k, axis, ret_type, is_ascend, dtype)\n    else:\n        out = _make.topk(data, k, axis, ret_type, is_ascend, dtype)\n    if ret_type == \"both\":\n        return TupleWrapper(out, 2)\n    return out\n\n\ndef searchsorted(sorted_sequence, values, right=False, dtype=\"int32\"):\n    \"\"\"Find indices where elements should be inserted to maintain order.\n       If `sorted_sequence` is N-dimensional, the innermost dimension of\n       `values` are searched in the corresponding dimension of `sorted_sequence`.\n\n    Parameters\n    ----------\n    sorted_sequence : relay.Expr\n        N-D or 1-D Tensor, containing monotonically increasing sequence\n        on the innermost dimension.\n\n    values : relay.Expr\n        N-D Tensor containing the search values. When `sorted_sequence` is 1-D,\n        the shape of `values` can be arbitrary. Otherwise, ranks of `sorted_sequence`\n        and `values` must be the same, and outer N-1 axes must have the same size.\n\n    right : bool, optional\n        Controls which index is returned if a value lands exactly on one of sorted values. If\n        False, the index of the first suitable location found is given. If true, return the\n        last such index. If there is no suitable index, return either 0 or N (where N is the\n        size of the innermost dimension).\n\n    dtype : string, optional\n        The data type of the output indices.\n\n    Returns\n    -------\n    indices : relay.Expr\n        Tensor with same shape as values, representing the indices of\n        elements of `values` if they are inserted in `sorted_sequence`.\n    \"\"\"\n    return _make.searchsorted(sorted_sequence, values, right, dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/annotation/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Annotation related operators.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .annotation import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/annotation/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.annotation._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/annotation/annotation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Annotation operations.\"\"\"\nfrom tvm import target\nfrom tvm.runtime import ndarray as _nd\nfrom tvm.runtime import Device as _Device\n\nfrom . import _make\nfrom .. import op as reg\n\n\ndef _make_virtual_device(device):\n    if isinstance(device, _Device):\n        return target.VirtualDevice(device)\n    if isinstance(device, str):\n        return target.VirtualDevice(_nd.device(device))\n    if isinstance(device, target.VirtualDevice):\n        return device\n    raise ValueError(\"expecting a Device or device name, but received a %s\" % (type(device)))\n\n\ndef on_device(body, device, constrain_result=False, constrain_body=True):\n    \"\"\"Annotates a body expression with device constraints. The constraint influences\n    how the body is compiled, where the body is evaluated, and where the result of\n    evaluation is stored.\n\n    Note that the defaults for the constrain_body and constrain_result parameters should\n    almost never need to be overridden by the user. These parameters are exposed here\n    to help unit tests exercise the PlanDevices pass machinery.\n\n    Parameters\n    ----------\n    body : tvm.relay.Expr\n        The expression to be annotated.\n\n    device : Union[:py:class:`Device`, str]\n        The device to annotate with.\n\n    constrain_result  : bool\n        If false (the default), the result of the on_device is not constrained to be on device.\n\n    constrain_body : bool\n        If true (the default), the body of the on_device is constrained to be on device.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The annotated expression.\n    \"\"\"\n    return _make.OnDevice(body, _make_virtual_device(device), constrain_result, constrain_body)\n\n\ndef function_on_device(function, param_devices, result_device):\n    \"\"\"Annotates a Relay function with the device types on which its parameters and result should\n    be stored.\n\n    Parameters\n    ----------\n    function : tvm.relay.Function\n        The function to be annotated.\n\n    param_devices : Array[Union[:py:class:`Device`, str]]\n        The devices for each parameter.\n\n    result_device: Union[:py:class:`Device`, str]\n        The device for the function result.\n\n    Returns\n    -------\n    result : tvm.relay.Function\n        The annotated function.\n    \"\"\"\n    return _make.FunctionOnDevice(\n        function,\n        [_make_virtual_device(d) for d in param_devices],\n        _make_virtual_device(result_device),\n    )\n\n\ndef stop_fusion(data):\n    \"\"\"Annotate an expression to prevent it being fused with following expressions.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The expression to be annotated.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The annotated expression.\n    \"\"\"\n    return _make.stop_fusion(data)\n\n\ndef checkpoint(data):\n    \"\"\"Annotate an expression to be a checkpoint for the checkpointing memory optimization.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The expression to be annotated.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The annotated expression.\n    \"\"\"\n    return _make.checkpoint(data)\n\n\nreg.register_injective_schedule(\"annotation.checkpoint\")\n\n\ndef compiler_begin(data, compiler):\n    \"\"\"Annotate an expression to indicate that it is the beginning of\n    a regeion that will be handled by the given compiler.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The expression to be annotated.\n\n    compiler : Str\n        The compiler used to generate code of the annotated region.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The annotated expression.\n    \"\"\"\n    return _make.compiler_begin(data, compiler)\n\n\ndef compiler_end(data, compiler):\n    \"\"\"Annotate an expression to indicate that it is the end of a region that\n    is handled by the provided compiler.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The expression to be annotated.\n\n    compiler : Str\n        The compiler used to generate code of the annotated region.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The annotated expression.\n    \"\"\"\n    return _make.compiler_end(data, compiler)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Contrib modules.\"\"\"\nfrom .register import get_pattern_table, register_pattern_table\n\nfrom .arm_compute_lib import *\nfrom .dnnl import *\nfrom .tachikoma import *\nfrom .bnns import *\nfrom .coreml import *\nfrom .ethosn import *\nfrom .libtorch import *\nfrom .tensorrt import *\nfrom .cutlass import *\nfrom .clml import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/_ethosn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Expose 'is supported' functions to Python.\"\"\"\n\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.ethos-n.support\", __name__)\ntvm._ffi._init_api(\"relay.backend.contrib.ethos-n\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/arm_compute_lib.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, dangerous-default-value\n\"\"\"Arm Compute Library supported operators.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm._ffi import register_func\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.expr import const\n\nfrom ...dataflow_pattern import is_constant, is_expr, is_op, is_tuple, wildcard\nfrom ..strategy.generic import is_depthwise_conv2d\nfrom .register import register_pattern_table\n\n\ndef is_arm_compute_runtime_enabled():\n    \"\"\"Check if the ACL graph executor is present.\n\n    Returns\n    -------\n    ret: bool\n        True if present, False if not.\n    \"\"\"\n    check_enabled = tvm.get_global_func(\"relay.op.is_arm_compute_runtime_enabled\", True)\n    if check_enabled:\n        return check_enabled()\n    return False\n\n\ndef partition_for_arm_compute_lib(mod, params=None, disabled_ops=[\"concatenate\"], **opts):\n    \"\"\"Partition the graph greedily offloading supported\n    operators to Arm Compute Library.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n    disabled_ops : Optional[list]\n        Ops do not want to offload to ACL.\n\n    Returns\n    -------\n    ret : annotated and partitioned module.\n    \"\"\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.MergeComposite(arm_compute_lib_pattern_table(disabled_ops)),\n            transform.AnnotateTarget(\"arm_compute_lib\", False),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    return seq(mod)\n\n\n@register_func(\"relay.ext.arm_compute_lib.optimize\")\ndef preprocess_module(mod):\n    \"\"\"\n    Pre-process a module containing functions ready for ACL codegen. For now we enforce OHWI\n    kernel layout and fold the transforms away.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n\n    Returns\n    -------\n    preprocessed_mod : The processed module.\n    \"\"\"\n\n    def convert_layout_conv2d(conv2d_function):\n        def convert_conv(attrs, inputs, tinfos, desired_layouts):\n            new_attrs = dict(attrs)\n            data_info = tinfos[0]\n            weight_info = tinfos[1]\n            desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n            new_attrs[\"data_layout\"] = desired_data_layout\n            new_attrs[\"kernel_layout\"] = desired_kernel_layout\n\n            if is_depthwise_conv2d(\n                data_info.shape,\n                attrs[\"data_layout\"],\n                weight_info.shape,\n                attrs[\"kernel_layout\"],\n                attrs[\"groups\"],\n            ):\n                dkl = desired_kernel_layout\n                new_attrs[\"kernel_layout\"] = dkl[3] + dkl[1:3] + dkl[0]\n            return conv2d_function(*inputs, **new_attrs)\n\n        return convert_conv\n\n    with OpAttrContext(\n        \"nn.conv2d\", \"FTVMConvertOpLayout\", convert_layout_conv2d(tvm.relay.nn.conv2d)\n    ), OpAttrContext(\n        \"qnn.conv2d\", \"FTVMConvertOpLayout\", convert_layout_conv2d(tvm.relay.qnn.op.conv2d)\n    ):\n        seq = tvm.transform.Sequential(\n            [\n                transform.ConvertLayout(\n                    {\"nn.conv2d\": [\"NHWC\", \"OHWI\"], \"qnn.conv2d\": [\"NHWC\", \"OHWI\"]}\n                ),\n                transform.FoldConstant(),\n            ]\n        )\n        preprocessed_mod = seq(mod)\n    return preprocessed_mod\n\n\n@register_pattern_table(\"arm_compute_lib\")\ndef arm_compute_lib_pattern_table(disabled_ops=[\"concatenate\"]):\n    \"\"\"Get the ACL pattern table.\"\"\"\n\n    def conv_pattern():\n        \"\"\"Create a convolution pattern.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"nn.pad\")(wildcard(), wildcard()) | wildcard()\n        pattern = is_op(\"nn.conv2d\")(pattern, is_constant())\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        pattern = pattern.optional(is_op(\"nn.relu\"))\n        return pattern\n\n    def qnn_conv_pattern():\n        \"\"\"Create a quantized convolution pattern.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"nn.pad\")(wildcard(), wildcard()) | wildcard()\n        pattern = is_op(\"qnn.conv2d\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        pattern = pattern.optional(is_op(\"nn.relu\"))\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, wildcard(), wildcard(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def dense_pattern():\n        \"\"\"Create a dense (fully-connected) pattern.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"nn.dense\")(wildcard(), is_constant())\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        return pattern\n\n    def qnn_dense_pattern():\n        \"\"\"Create a quantized dense (fully-connected) pattern.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"qnn.dense\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, wildcard(), wildcard(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def avg_pool2d_pattern():\n        \"\"\"Creates a pattern that matches either quantized\n        avg_pool2d or quantized global_avg_pool2d.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"cast\")(wildcard())\n        pattern = is_op(\"nn.avg_pool2d\")(pattern) | is_op(\"nn.global_avg_pool2d\")(pattern)\n        pattern = is_op(\"cast\")(pattern)\n        return pattern\n\n    def l2_pool2d_pattern():\n        \"\"\"Create an l2 pooling pattern from equivalent relay operators.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the convolution pattern.\n        \"\"\"\n        pattern = is_op(\"power\")(wildcard(), is_expr(const(2.0)))\n        pattern = is_op(\"nn.avg_pool2d\")(pattern)\n        pattern = is_op(\"sqrt\")(pattern)\n        return pattern\n\n    def concatenate_pattern():\n        \"\"\"Create an concatenate pattern from equivalent relay operators.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the concatenate pattern.\n        \"\"\"\n        pattern = is_op(\"concatenate\")(is_tuple(None))\n        return pattern\n\n    def check_conv(extract):\n        \"\"\"Check conv pattern is supported by ACL.\"\"\"\n        call = extract\n        while call.op.name != \"nn.conv2d\":\n            call = call.args[0]\n        return conv2d(call)\n\n    def check_qnn_conv(extract):\n        \"\"\"Check qnn conv pattern is supported by ACL.\"\"\"\n        if extract.attrs.out_dtype != \"uint8\":\n            return False\n        call = extract\n        while call.op.name != \"qnn.conv2d\":\n            call = call.args[0]\n        return qnn_conv2d(call)\n\n    def check_dense(extract):\n        \"\"\"Check conv pattern is supported by ACL.\"\"\"\n        call = extract\n        while call.op.name != \"nn.dense\":\n            call = call.args[0]\n        return dense(call)\n\n    def check_qnn_dense(extract):\n        \"\"\"Check qnn conv pattern is supported by ACL.\"\"\"\n        if extract.attrs.out_dtype != \"uint8\":\n            return False\n        call = extract\n        while call.op.name != \"qnn.dense\":\n            call = call.args[0]\n        return qnn_dense(call)\n\n    def check_avg_pool2d(extract):\n        \"\"\"Check average pool2d pattern is supported by ACL.\"\"\"\n        if extract.attrs.dtype != \"uint8\":\n            return False\n        pool = extract.args[0]\n        if pool.args[0].attrs.dtype != \"int32\":\n            return False\n        return avg_pool2d(pool, from_quantized_composite=True)\n\n    def check_l2_pool2d(extract):\n        \"\"\"Check l2 pool2d pattern is supported by ACL.\"\"\"\n        pool = extract.args[0]\n        return avg_pool2d(pool)\n\n    def check_concatenate(expr):\n        \"\"\"Check concatenate pattern is supported by ACL.\"\"\"\n        if \"concatenate\" in disabled_ops:\n            return False\n        attrs, type_args = expr.attrs, expr.type_args\n        for idx in range(len(type_args[0].fields)):\n            if type_args[0].fields[idx].dtype not in [\"float32\", \"uint8\"]:\n                return False\n        # ACL concatenate only supports maximum 4 dimensions input tensor\n        if attrs.axis not in [-4, -3, -2, -1, 0, 1, 2, 3]:\n            return False\n        return True\n\n    return [\n        (\"arm_compute_lib.conv2d\", conv_pattern(), check_conv),\n        (\"arm_compute_lib.qnn_conv2d\", qnn_conv_pattern(), check_qnn_conv),\n        (\"arm_compute_lib.dense\", dense_pattern(), check_dense),\n        (\"arm_compute_lib.qnn_dense\", qnn_dense_pattern(), check_qnn_dense),\n        (\"arm_compute_lib.qnn_conv2d\", qnn_conv_pattern(), check_qnn_conv),\n        (\"arm_compute_lib.avg_pool2d\", avg_pool2d_pattern(), check_avg_pool2d),\n        (\"arm_compute_lib.l2_pool2d\", l2_pool2d_pattern(), check_l2_pool2d),\n        (\"arm_compute_lib.concatenate\", concatenate_pattern(), check_concatenate),\n    ]\n\n\ndef _register_external_op_helper(op_name, supported=True):\n    @tvm.ir.register_op_attr(op_name, \"target.arm_compute_lib\")\n    def _func_wrapper(expr):\n        return supported\n\n    return _func_wrapper\n\n\n_register_external_op_helper(\"reshape\")\n\n\n@tvm.ir.register_op_attr(\"nn.conv2d\", \"target.arm_compute_lib\")\ndef conv2d(expr):\n    \"\"\"Check if the external ACL codegen for conv2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    if attrs.data_layout != \"NHWC\":\n        return False\n    if attrs.out_dtype != \"float32\" and attrs.out_dtype != \"\":\n        return False\n    data_typ = args[0].checked_type\n    if len(data_typ.shape) != 4 or data_typ.shape[0] != 1 or data_typ.dtype != \"float32\":\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 4 or kernel_typ.dtype != \"float32\":\n        return False\n    is_depthwise = is_depthwise_conv2d(\n        data_typ.shape,\n        attrs[\"data_layout\"],\n        kernel_typ.shape,\n        attrs[\"kernel_layout\"],\n        attrs[\"groups\"],\n    )\n    if is_depthwise:\n        return depthwise_conv2d(attrs, args)\n    # ACL doesn't support grouped convolution\n    if attrs.groups != 1 and not is_depthwise:\n        return False\n    return True\n\n\ndef qnn_conv2d(expr):\n    \"\"\"Check if the external ACL codegen for qnn.conv2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n\n    if attrs.data_layout != \"NHWC\":\n        return False\n    if attrs.out_dtype != \"int32\" and attrs.out_dtype != \"\":\n        return False\n    data_typ = args[0].checked_type\n    if len(data_typ.shape) != 4 or data_typ.shape[0] != 1 or data_typ.dtype != \"uint8\":\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 4 or kernel_typ.dtype != \"uint8\":\n        return False\n    is_depthwise = is_depthwise_conv2d(\n        data_typ.shape,\n        attrs[\"data_layout\"],\n        kernel_typ.shape,\n        attrs[\"kernel_layout\"],\n        attrs[\"groups\"],\n    )\n    if is_depthwise:\n        return depthwise_conv2d(attrs, args)\n    # ACL doesn't support grouped convolution\n    if attrs.groups != 1 and not is_depthwise:\n        return False\n    return True\n\n\ndef depthwise_conv2d(attrs, args):\n    \"\"\"Check if the external ACL codegen for depthwise convolution should be used.\n\n    Note\n    ----\n    Relay does not have a depthwise conv2d operator whilst ACL does. We simply\n    separate the checks for depthwise for clarity.\n    \"\"\"\n    kernel_typ = args[1].checked_type\n    # Only supports 3x3, 5x5 depthwise\n    if (\n        kernel_typ.shape[0] not in [3, 5]\n        or kernel_typ.shape[1] not in [3, 5]\n        or kernel_typ.shape[0] != kernel_typ.shape[1]\n    ):\n        return False\n    # Stride must be (1, 1) or (2, 2)\n    if (attrs.strides[0], attrs.strides[1]) not in [(1, 1), (2, 2)]:\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.dense\", \"target.arm_compute_lib\")\ndef dense(expr):\n    \"\"\"Check if the external ACL codegen for dense should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    if data_typ.dtype != \"float32\":\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 2 or kernel_typ.dtype != \"float32\":\n        return False\n    if attrs.out_dtype != \"float32\" and attrs.out_dtype != \"\":\n        return False\n    return True\n\n\ndef qnn_dense(expr):\n    \"\"\"Check if the external ACL codegen for qnn.dense should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    if data_typ.dtype != \"uint8\":\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 2 or kernel_typ.dtype != \"uint8\":\n        return False\n    if attrs.out_dtype != \"int32\":\n        return False\n    return True\n\n\ndef check_dilation(attrs):\n    \"\"\"Prevents offloading if dilation other than (1, 1)\"\"\"\n    if not isinstance(attrs, relay.op.op_attrs.GlobalPool2DAttrs):\n        if not (len(attrs.dilation) == 2 and attrs.dilation[0] == 1 and attrs.dilation[1] == 1):\n            return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.max_pool2d\", \"target.arm_compute_lib\")\ndef max_pool2d(expr):\n    \"\"\"Check if the external ACL codegen for maxpool2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    if attrs.layout != \"NHWC\":\n        return False\n    typ = args[0].checked_type\n    if typ.dtype not in [\"float32\", \"uint8\"]:\n        return False\n    return check_dilation(attrs)\n\n\n@tvm.ir.register_op_attr(\"nn.avg_pool2d\", \"target.arm_compute_lib\")\ndef avg_pool2d(expr, from_quantized_composite=False):\n    \"\"\"Check if the external ACL codegen for avgpool2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    typ = args[0].checked_type\n\n    if from_quantized_composite:\n        if typ.dtype != \"int32\":\n            return False\n    else:\n        if typ.dtype not in [\"float32\"]:\n            return False\n    if attrs.layout != \"NHWC\":\n        return False\n\n    return check_dilation(attrs)\n\n\n@tvm.ir.register_op_attr(\"nn.global_max_pool2d\", \"target.arm_compute_lib\")\ndef global_max_pool2d(expr):\n    \"\"\"Check if the external ACL codegen for gloval_maxpool2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    typ = args[0].checked_type\n    if typ.dtype not in [\"float32\", \"uint8\"]:\n        return False\n    if attrs.layout != \"NHWC\":\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.global_avg_pool2d\", \"target.arm_compute_lib\")\ndef global_avg_pool2d(expr):\n    \"\"\"Check if the external ACL codegen for global_avgpool2d should be used.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    typ = args[0].checked_type\n    if typ.dtype not in [\"float32\"]:\n        return False\n    if attrs.layout != \"NHWC\":\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"maximum\", \"target.arm_compute_lib\")\ndef maximum(expr):\n    \"\"\"Check if the external ACL codegen for maximum should be used.\"\"\"\n    args = expr.args\n    type_a = args[0].checked_type\n    type_b = args[0].checked_type\n    return (type_a.dtype == \"float32\") and (type_b.dtype == \"float32\")\n\n\n@tvm.ir.register_op_attr(\"add\", \"target.arm_compute_lib\")\ndef add(expr):\n    \"\"\"Check if the external ACL codegen for add should be used.\"\"\"\n    args = expr.args\n    for typ in [args[0].checked_type, args[1].checked_type]:\n        if typ.dtype != \"float32\":\n            return False\n\n    return True\n\n\n@tvm.ir.register_op_attr(\"qnn.add\", \"target.arm_compute_lib\")\ndef qnn_add(expr):\n    \"\"\"Check if the external ACL codegen for add should be used.\"\"\"\n    args = expr.args\n    for typ in [args[0].checked_type, args[1].checked_type]:\n        if typ.dtype != \"uint8\":\n            return False\n\n    return True\n\n\nclass OpAttrContext(object):\n    \"\"\"Temporarily changes the attr of an op.\"\"\"\n\n    def __init__(self, op_name, attr_key, attr_value):\n        \"\"\"Saves the required info for RAII pattern usage.\n\n        Parameters\n        ----------\n        op_name : str\n            The op name.\n\n        attr_key : str\n            The attribute name.\n\n        attr_value : object\n            The attribute value.\n        \"\"\"\n        self.op = relay.op.get(op_name)\n        self.attr_key = attr_key\n        self.attr_value = attr_value\n\n    def __enter__(self):\n        self.older_attr = self.op.get_attr(self.attr_key)\n        self.op.reset_attr(self.attr_key)\n        self.op.set_attr(self.attr_key, self.attr_value)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        self.op.reset_attr(self.attr_key)\n        if self.older_attr:\n            self.op.set_attr(self.attr_key, self.older_attr)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/bnns.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"BNNS library supported operators.\nIs a part of Accelerate framework on macOS/iOS platforms. Apple provide several APIs\nto handle tensor processing. Particularly:\n * BNNS (basic neural )\n * vDSP (1D and 2D tensor processing)\n\"\"\"\nimport math\nimport tvm.ir\n\nfrom tvm.relay import transform\nfrom tvm.relay.expr import const\nfrom tvm.relay.build_module import bind_params_by_name\n\nfrom .register import register_pattern_table, get_pattern_table\nfrom ...dataflow_pattern import wildcard, is_op, is_expr\n\n\ndef partition_for_bnns(mod, params=None):\n    \"\"\"Partition the graph greedily offloading supported\n    operators to BNNS.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n\n    Returns\n    -------\n    ret : annotated and partitioned module.\n    \"\"\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.FoldConstant(),\n            transform.FoldScaleAxis(),\n            transform.DynamicToStatic(),\n            transform.AlterOpLayout(),\n            # TODO(apeskov): WA. AlterOpLayout call lead to constants shape transformation\n            #   Some expand_dims op may appears after constants. It breaks BNNS fusing.\n            #   So we have to call FoldConstant right before bnns composite passes.\n            transform.FoldConstant(),\n            transform.MergeComposite(get_pattern_table(\"bnns\")),\n            transform.AnnotateTarget(\"bnns\"),\n            #   If you no need in per layer performance statistic you can\n            #   uncomment next line\n            # transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    return seq(mod)\n\n\ndef _register_external_op_helper(op_name, supported=True):\n    \"\"\"The helper function to indicate that a given operator can be supported\n    by BNNS.\n\n    Parameters\n    ----------\n    op_name : Str\n        The name of supported operator that will be registered.\n\n    Returns\n    -------\n    f : callable\n        A function that returns if the operator is supported by BNNS.\n    \"\"\"\n\n    @tvm.ir.register_op_attr(op_name, \"target.bnns\")\n    def _func_wrapper(expr):\n        return supported\n\n    return _func_wrapper\n\n\n_register_external_op_helper(\"nn.batch_matmul\")\n\n\n@tvm.ir.register_op_attr(\"nn.max_pool2d\", \"target.bnns\")\ndef max_pool2d_check(expr):\n    \"\"\"Check if the nn.max_pool2d can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    rank = len(data_typ.shape)\n    if rank < 3 or rank > 4 or data_typ.dtype != \"float32\":\n        return False\n    if attrs.layout != \"NCHW\":\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.avg_pool2d\", \"target.bnns\")\ndef avg_pool2d_check(expr):\n    \"\"\"Check if the nn.avg_pool2d can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    rank = len(data_typ.shape)\n    if rank < 3 or rank > 4 or data_typ.dtype != \"float32\":\n        return False\n    if attrs.layout != \"NCHW\":\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.global_max_pool2d\", \"target.bnns\")\ndef global_max_pool2d_check(expr):\n    \"\"\"Check if the nn.global_max_pool2d can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    rank = len(data_typ.shape)\n    if rank < 3 or rank > 4 or data_typ.dtype != \"float32\":\n        return False\n    if attrs.layout != \"NCHW\":\n        return False\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.global_avg_pool2d\", \"target.bnns\")\ndef global_avg_pool2d_check(expr):\n    \"\"\"Check if the nn.global_avg_pool2d can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    rank = len(data_typ.shape)\n    if rank < 3 or rank > 4 or data_typ.dtype != \"float32\":\n        return False\n    if attrs.layout != \"NCHW\":\n        return False\n    return True\n\n\ndef dtype_is_supported(dtype):\n    \"\"\"Check if data type is supported by BNNS backend\"\"\"\n    return dtype in (\"\", \"float32\")\n\n\n@tvm.ir.register_op_attr(\"nn.conv2d\", \"target.bnns\")\ndef conv2d_check(expr):\n    \"\"\"Check if the conv2d can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    if len(data_typ.shape) != 4 or data_typ.dtype != \"float32\":\n        return False\n    if not isinstance(args[1], tvm.relay.expr.Constant):\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 4 or kernel_typ.dtype != \"float32\":\n        return False\n    if attrs.data_layout != \"NCHW\":\n        return False\n    if not dtype_is_supported(attrs.out_dtype):\n        return False\n    return True\n\n\ndef bias_check(expr):\n    \"\"\"Check is bias added through the correct dimension\"\"\"\n    attrs, args = expr.attrs, expr.args\n    if not isinstance(args[1], tvm.relay.expr.Constant):\n        return False\n    if expr.op.name == \"nn.bias_add\":\n        return attrs.axis == 1\n    if expr.op.name == \"add\":\n        b_shape = args[1].checked_type.shape\n        if len(b_shape) == 4:\n            return bool(b_shape[0] == 1 and b_shape[2] == 1 and b_shape[3] == 1)\n        if len(b_shape) == 3:\n            return bool(b_shape[1] == 1 and b_shape[2] == 1)\n\n    return False\n\n\n@tvm.ir.register_op_attr(\"nn.dense\", \"target.bnns\")\ndef dense(expr):\n    \"\"\"Check if the dense can be used in BNNS.\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    if data_typ.dtype != \"float32\":\n        return False\n    if not isinstance(args[1], tvm.relay.expr.Constant):\n        return False\n    kernel_typ = args[1].checked_type\n    if len(kernel_typ.shape) != 2 or kernel_typ.dtype != \"float32\":\n        return False\n    if attrs.out_dtype != \"float32\" and attrs.out_dtype != \"\":\n        return False\n    return True\n\n\ndef make_conv_pattern(with_bias=True, activation=\"none\"):\n    \"\"\"Make pattern for bnns.conv2d primitive\"\"\"\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    pat = is_op(\"nn.conv2d\")(data, weight)\n    if with_bias:\n        pat = is_op(\"add\")(pat, bias) | is_op(\"nn.bias_add\")(pat, bias)\n    if activation == \"relu\":\n        pat = is_op(\"nn.relu\")(pat)\n    elif activation == \"sigmoid\":\n        pat = is_op(\"sigmoid\")(pat)\n    return pat\n\n\ndef check_conv(extract):\n    \"\"\"Check conv pattern is supported by BNNS.\"\"\"\n    bias_is_ok = True\n    call = extract\n    while call.op.name != \"nn.conv2d\":\n        if call.op.name in (\"nn.bias_add\", \"add\"):\n            bias_is_ok &= bias_check(call)\n        call = call.args[0]\n    return conv2d_check(call) and bias_is_ok\n\n\ndef make_dense_bias_pattern():\n    \"\"\"Make pattern for bnns.dense primitive\"\"\"\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    d = is_op(\"nn.dense\")(data, weight)\n    return is_op(\"add\")(d, bias)\n\n\ndef make_dense_bias_gelu_pattern():\n    \"\"\"Make pattern for bnns.dense primitive with fused bias and gelu activation\"\"\"\n    dense_bias = make_dense_bias_pattern()\n    const1 = is_expr(const(0.044715))\n    const2 = is_expr(const(math.sqrt(2 / math.pi)))\n\n    gelu = is_op(\"power\")(dense_bias, is_expr(const(3, dtype=\"float32\")))\n    gelu = is_op(\"multiply\")(gelu, const1)\n    gelu = is_op(\"add\")(gelu, dense_bias)\n    gelu = is_op(\"multiply\")(gelu, const2)\n    gelu = is_op(\"tanh\")(gelu)\n    gelu = is_op(\"add\")(gelu, is_expr(const(1, dtype=\"float32\")))\n    gelu = is_op(\"multiply\")(gelu, is_expr(const(0.5)))\n    gelu = is_op(\"multiply\")(gelu, dense_bias)\n    return gelu\n\n\ndef check_dense(extract):\n    \"\"\"Check dense pattern is supported by BNNS.\"\"\"\n    call = extract\n    while call.op.name != \"nn.dense\":\n        call = call.args[0]\n    return dense(call)\n\n\n@tvm.ir.register_op_attr(\"nn.instance_norm\", \"target.bnns\")\ndef instance_norm_check(expr):\n    \"\"\"Check if the nn.instance_norm can be executed in BNNS\"\"\"\n    attrs, args = expr.attrs, expr.args\n    data_typ = args[0].checked_type\n    rank = len(data_typ.shape)\n    if rank < 3 or rank > 4 or data_typ.dtype != \"float32\":\n        return False\n    if not isinstance(args[1], tvm.relay.expr.Constant) or not isinstance(\n        args[2], tvm.relay.expr.Constant\n    ):\n        return False\n    if attrs.axis == 0 and rank == 3 or attrs.axis == 1 and rank == 4:\n        return True\n    return False\n\n\n@register_pattern_table(\"bnns\")\ndef pattern_table():\n    \"\"\"Get BNNS specific fusing patterns collection\"\"\"\n    conv2d_bias_pat = (\n        \"bnns.conv2d_bias\",\n        make_conv_pattern(with_bias=True),\n        check_conv,\n    )\n    conv2d_bias_relu_pat = (\n        \"bnns.conv2d_bias_relu\",\n        make_conv_pattern(with_bias=True, activation=\"relu\"),\n        check_conv,\n    )\n    conv2d_relu_pat = (\n        \"bnns.conv2d_relu\",\n        make_conv_pattern(with_bias=False, activation=\"relu\"),\n        check_conv,\n    )\n    conv2d_bias_sigmoid_pat = (\n        \"bnns.conv2d_bias_sigmoid\",\n        make_conv_pattern(with_bias=True, activation=\"sigmoid\"),\n        check_conv,\n    )\n    conv2d_sigmoid_pat = (\n        \"bnns.conv2d_sigmoid\",\n        make_conv_pattern(with_bias=False, activation=\"sigmoid\"),\n        check_conv,\n    )\n    dense_bias_gelu = (\"bnns.dense_bias_gelu\", make_dense_bias_gelu_pattern(), check_dense)\n    dense_bias = (\"bnns.dense_bias\", make_dense_bias_pattern(), check_dense)\n    bnns_patterns = [\n        conv2d_bias_relu_pat,\n        conv2d_relu_pat,\n        conv2d_bias_sigmoid_pat,\n        conv2d_sigmoid_pat,\n        conv2d_bias_pat,\n        dense_bias_gelu,\n        dense_bias,\n    ]\n    return bnns_patterns\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/clml.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"CLML Library supported operators.\"\"\"\nimport tvm\n\nfrom tvm import relay\nfrom tvm._ffi import register_func\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\n\nfrom ...dataflow_pattern import wildcard, is_op, is_constant, is_tuple_get_item, is_tuple\nfrom .register import register_pattern_table\nfrom ..strategy.generic import is_depthwise_conv2d\n\n\ndef is_clml_runtime_enabled():\n    \"\"\"Check if the CLML graph runtime is present.\n\n    Returns\n    -------\n    ret: bool\n        True if present, False if not.\n    \"\"\"\n    check_enabled = tvm.get_global_func(\"relay.op.is_clml_runtime_enabled\", True)\n    if check_enabled:\n        return check_enabled()\n    return False\n\n\ndef partition_for_clml(mod, params=None):\n    \"\"\"Partition the graph greedily offloading supported\n    operators to CLML Library.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n\n    Returns\n    -------\n    ret : annotated and partitioned module.\n    \"\"\"\n\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.FoldConstant(),\n            transform.MergeComposite(clml_pattern_table()),\n            transform.AnnotateTarget(\"clml\", False),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    result_mod = seq(mod)\n    return result_mod\n\n\n@register_func(\"relay.ext.clml.optimize\")\ndef preprocess_module(mod):\n    \"\"\"\n    Pre-process a module containing functions ready for CLML codegen. For now we enforce OIHW\n    kernel layout and fold the transforms away.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n\n    Returns\n    -------\n    preprocessed_mod : The processed module.\n    \"\"\"\n\n    def convert_layout_conv2d(conv2d_function):\n        def convert_conv(attrs, inputs, tinfos, desired_layouts):\n            new_attrs = dict(attrs)\n            data_info = tinfos[0]\n            weight_info = tinfos[1]\n            desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n            new_attrs[\"data_layout\"] = desired_data_layout\n            new_attrs[\"kernel_layout\"] = desired_kernel_layout\n\n            if is_depthwise_conv2d(\n                data_info.shape,\n                attrs[\"data_layout\"],\n                weight_info.shape,\n                attrs[\"kernel_layout\"],\n                attrs[\"groups\"],\n            ):\n                dkl = desired_kernel_layout\n                new_attrs[\"kernel_layout\"] = dkl[1] + dkl[0] + dkl[2] + dkl[3]\n            return conv2d_function(*inputs, **new_attrs)\n\n        return convert_conv\n\n    with OpAttrContext(\n        \"nn.conv2d\", \"FTVMConvertOpLayout\", convert_layout_conv2d(tvm.relay.nn.conv2d)\n    ):\n        seq = tvm.transform.Sequential(\n            [\n                transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"OIHW\"]}),\n                transform.FoldConstant(),\n            ]\n        )\n        preprocessed_mod = seq(mod)\n    return preprocessed_mod\n\n\n@register_pattern_table(\"clml\")\ndef clml_pattern_table():\n    \"\"\"Get the CLML pattern table.\"\"\"\n\n    def conv_pattern():\n        \"\"\"Create a convolution pattern.\"\"\"\n        pattern = is_op(\"nn.conv2d\")(wildcard(), is_constant())\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        pattern = pattern.optional(lambda x: is_op(\"add\")(x, is_constant()))\n        pattern = pattern.optional(\n            lambda x: is_op(\"nn.batch_norm\")(\n                x, is_constant(), is_constant(), is_constant(), is_constant()\n            )\n        )\n        pattern = pattern.optional(is_tuple_get_item)\n        pattern = pattern.optional(is_op(\"nn.relu\"))\n        pattern = pattern.optional(is_op(\"clip\"))\n        return pattern\n\n    def batch_norm_pattern():\n        \"\"\"Create a batch norm pattern.\"\"\"\n        pattern = is_op(\"nn.batch_norm\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        pattern = is_tuple_get_item(pattern)\n        return pattern\n\n    def concat_pattern():\n        \"\"\"Create a concat pattern.\n\n        Returns\n        -------\n        pattern : dataflow_pattern.AltPattern\n            Denotes the concat pattern.\n        \"\"\"\n        pattern = is_tuple(None)\n        pattern = is_op(\"concatenate\")(pattern)\n\n        return pattern\n\n    def dense_pattern():\n        \"\"\"Create a dense pattern.\"\"\"\n        pattern = is_op(\"nn.dense\")(wildcard(), is_constant())\n        pattern = pattern.optional(lambda x: is_op(\"add\")(x, is_constant()))\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        return pattern\n\n    def pad_pattern():\n        \"\"\"Create a pad pattern.\"\"\"\n        pattern = is_op(\"nn.pad\")(wildcard(), wildcard())\n        return pattern\n\n    def check_conv(extract):\n        \"\"\"Check conv pattern is supported by CLML.\"\"\"\n        call = extract\n        if isinstance(call, tvm.relay.expr.TupleGetItem):\n            call = call.tuple_value\n        elif call.op.name == \"nn.relu\":\n            call = call.args[0]\n            if isinstance(call, tvm.relay.expr.TupleGetItem):\n                call = call.tuple_value\n        elif call.op.name == \"clip\":\n            if call.attrs[\"a_min\"] != 0.0 or call.attrs[\"a_max\"] != 6.0:\n                return False\n            call = call.args[0]\n            if isinstance(call, tvm.relay.expr.TupleGetItem):\n                call = call.tuple_value\n\n        while call.op.name != \"nn.conv2d\":\n            call = call.args[0]\n        attrs, args = call.attrs, call.args\n        if attrs.data_layout != \"NCHW\":\n            return False\n        data_typ = args[0].checked_type\n        kernel_typ = args[1].checked_type\n        is_depthwise = is_depthwise_conv2d(\n            data_typ.shape,\n            attrs[\"data_layout\"],\n            kernel_typ.shape,\n            attrs[\"kernel_layout\"],\n            attrs[\"groups\"],\n        )\n        if attrs.groups != 1 and not is_depthwise:\n            return False\n        return True\n\n    return [\n        (\"clml.conv2d\", conv_pattern(), check_conv),\n        (\"clml.dense\", dense_pattern()),\n        (\"clml.pad\", pad_pattern()),\n        (\"clml.concat\", concat_pattern()),\n        (\"clml.batch_norm\", batch_norm_pattern()),\n    ]\n\n\ndef _register_external_op_helper(op_name, supported=True):\n    @tvm.ir.register_op_attr(op_name, \"target.clml\")\n    def _func_wrapper(expr):\n        return supported\n\n    return _func_wrapper\n\n\n_register_external_op_helper(\"clip\")\n_register_external_op_helper(\"nn.relu\")\n_register_external_op_helper(\"nn.global_avg_pool2d\")\n_register_external_op_helper(\"nn.global_max_pool2d\")\n_register_external_op_helper(\"nn.avg_pool2d\")\n_register_external_op_helper(\"nn.max_pool2d\")\n_register_external_op_helper(\"nn.softmax\")\n_register_external_op_helper(\"reshape\")\n_register_external_op_helper(\"add\")\n_register_external_op_helper(\"subtract\")\n_register_external_op_helper(\"multiply\")\n_register_external_op_helper(\"minimum\")\n_register_external_op_helper(\"maximum\")\n\n\nclass OpAttrContext(object):\n    \"\"\"Temporarily changes the attr of an op.\"\"\"\n\n    def __init__(self, op_name, attr_key, attr_value):\n        \"\"\"Saves the required info for RAII pattern usage.\n\n        Parameters\n        ----------\n        op_name : str\n            The op name.\n\n        attr_key : str\n            The attribute name.\n\n        attr_value : object\n            The attribute value.\n        \"\"\"\n        self.op = relay.op.get(op_name)\n        self.attr_key = attr_key\n        self.attr_value = attr_value\n\n    def __enter__(self):\n        self.older_attr = self.op.get_attr(self.attr_key)\n        self.op.reset_attr(self.attr_key)\n        self.op.set_attr(self.attr_key, self.attr_value)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        self.op.reset_attr(self.attr_key)\n        if self.older_attr:\n            self.op.set_attr(self.attr_key, self.older_attr)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/cmsisnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Arm(R) CMSIS-NN supported operators for Cortex-M.\"\"\"\nimport tvm.ir\nfrom tvm.target import Target\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\n\nfrom ...dataflow_pattern import is_constant, is_op, wildcard\nfrom .register import register_pattern_table\n\ntvm._ffi._init_api(\"relay.ext.cmsisnn.transform\", __name__)\n\n\ndef enabled():\n    return \"cmsis-nn\" in Target.list_kinds()\n\n\ndef partition_for_cmsisnn(mod, params=None, mod_name=\"default\", **opts):\n    \"\"\"Partition the graph greedily offloading supported\n    operators on Cortex-M using CMSIS-NN\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n    mod_name: str, optional\n        The module name\n\n    Returns\n    -------\n    ret : Module\n        annotated and partitioned module.\n    \"\"\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.MergeComposite(pattern_table()),\n            transform.AnnotateTarget(\"cmsis-nn\"),\n            transform.PartitionGraph(mod_name=mod_name),\n            GenerateCMSISNNConstants(),\n            CMSISNNFusePads(),\n            ScalarToTensorConstants(),\n            ExtractConstantsFromPartitionedFunction(),\n            transform.InferType(),\n        ]\n    )\n    return seq(mod)\n\n\n@register_pattern_table(\"cmsis-nn\")\ndef pattern_table():\n    \"\"\"Get the CMSIS-NN compiler pattern table.\"\"\"\n\n    def qnn_softmax_pattern():\n        \"\"\"Create pattern for quantized softmax\"\"\"\n        pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n        pattern = is_op(\"nn.softmax\")(pattern)\n        pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n        return pattern\n\n    def check_qnn_softmax(pattern):\n        \"\"\"Check if softmax is supported by CMSIS-NN.\"\"\"\n        dequantize_call = pattern.args[0].args[0]\n        scale = pattern.args[1].data.numpy().item(0)\n        zero_point = pattern.args[2].data.numpy().item(0)\n\n        # check for dtypes of quantize and dequantize\n        return (\n            (scale == 1.0 / 256 and zero_point == -128)\n            and pattern.attrs.out_dtype == \"int8\"\n            and dequantize_call.args[0].checked_type.dtype == \"int8\"\n        )\n\n    def qnn_conv2d_pattern(with_pad):\n        \"\"\"Create pattern for qnn.conv2D with optional pad and/or optional fused relu.\"\"\"\n        conv2d_input = wildcard()\n        if with_pad:\n            conv2d_input = is_op(\"nn.pad\")(wildcard(), is_constant())\n        qnn_conv2d = is_op(\"qnn.conv2d\")(\n            conv2d_input,\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n        )\n        bias_add = is_op(\"nn.bias_add\")(qnn_conv2d, is_constant())\n        req = is_op(\"qnn.requantize\")(\n            qnn_conv2d | bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        clip_or_req = req.optional(is_op(\"clip\"))\n        return clip_or_req\n\n    def check_qnn_conv2d(pattern):\n        \"\"\"Check if the Conv2D is supported by CMSIS-NN.\"\"\"\n        if str(pattern.op.name) == \"clip\":\n            relu = pattern\n            requantize = relu.args[0]\n        else:\n            requantize = pattern\n        requantize_input = requantize.args[0]\n        bias_add = None\n        if str(requantize_input.op.name) == \"nn.bias_add\":\n            bias_add = requantize_input\n            conv2d = bias_add.args[0]\n        else:\n            conv2d = requantize_input\n        conv2d_input = conv2d.args[0]\n        conv2d_weight = conv2d.args[1]\n\n        # check if depthwise Conv2D\n        kernel_layout = conv2d.attrs.kernel_layout\n        pos_o = kernel_layout.index(\"O\")\n        groups = conv2d.attrs.groups\n        is_depthwise = False\n        if groups == int(conv2d_input.checked_type.shape[3]) and groups == int(\n            conv2d_weight.checked_type.shape[pos_o]\n        ):\n            is_depthwise = True\n\n        # check if dtypes are supported for the following entities\n        # (input_dtype, weight_dtype, bias_dtype, out_dtype, pattern_dtype)\n        are_dtypes_valid = False\n        conv2d_input_dtype = conv2d_input.checked_type.dtype\n        if bias_add:\n            bias_dtype = bias_add.args[1].checked_type.dtype\n        else:\n            # this is only to enable to following check that validates all sorts of dtypes\n            bias_dtype = \"int32\" if conv2d_input_dtype == \"int8\" else \"int64\"\n        valid_dtypes = None\n        if conv2d_input_dtype == \"int8\":\n            valid_dtypes = (\"int8\", \"int8\", \"int32\", \"int32\", \"int8\")\n        elif conv2d_input_dtype == \"int16\":\n            valid_dtypes = (\"int16\", \"int8\", \"int64\", \"int64\", \"int16\")\n\n        if (\n            conv2d_input_dtype,\n            conv2d_weight.checked_type.dtype,\n            bias_dtype,\n            conv2d.attrs.out_dtype,\n            pattern.checked_type.dtype,\n        ) == valid_dtypes:\n            are_dtypes_valid = True\n\n        # input_zero_point should be 0 when int16\n        valid_input_zp = True\n        if conv2d_input_dtype == \"int16\" and conv2d.args[2].data.numpy().item(0) != 0:\n            valid_input_zp = False\n\n        # kernel zero_point should be 0\n        kernel_zp = conv2d.args[3].data.numpy()\n        kernel_zp = [kernel_zp] if kernel_zp.ndim == 0 else kernel_zp\n\n        # combination of all checks to decide if pattern is eligible for partitioning\n        ret = (\n            are_dtypes_valid\n            and valid_input_zp\n            and all([zp == 0 for zp in kernel_zp])\n            and (not is_depthwise or bias_add is not None)\n        )\n        return ret\n\n    def check_qnn_conv2d_pad(pattern):\n        \"\"\"Check if the Pad followed by Conv2D is supported by CMSIS-NN.\"\"\"\n        if str(pattern.op.name) == \"clip\":\n            relu = pattern\n            requantize = relu.args[0]\n        else:\n            requantize = pattern\n        requantize_input = requantize.args[0]\n        if str(requantize_input.op.name) == \"nn.bias_add\":\n            bias_add = requantize_input\n            conv2d = bias_add.args[0]\n        else:\n            conv2d = requantize_input\n        conv2d_input = conv2d.args[0]\n\n        # check if sum of paddings from pad() and conv2d() satisfies CMSIS-NN constraints\n        can_pad_be_fused = True\n        if isinstance(conv2d_input, tvm.relay.expr.Call) and str(conv2d_input.op.name) == \"nn.pad\":\n            pad_top, pad_left, pad_bottom, pad_right = GetEffectiveConv2DPadding(\n                conv2d, conv2d_input\n            )\n            # check if difference in the side paddings is 1 along each dimension\n            pad_w_diff = int(pad_right - pad_left)\n            pad_h_diff = int(pad_bottom - pad_top)\n            can_pad_be_fused = pad_w_diff in [0, 1] and pad_h_diff in [0, 1]\n\n        ret = check_qnn_conv2d(pattern) and can_pad_be_fused\n        return ret\n\n    def qnn_fully_connected_pattern():\n        \"\"\"Create pattern for qnn.dense with optional Relu.\"\"\"\n        qnn_fc = is_op(\"qnn.dense\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        bias_add = is_op(\"nn.bias_add\")(qnn_fc, is_constant())\n        req = is_op(\"qnn.requantize\")(\n            qnn_fc | bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        clip_or_req = req.optional(is_op(\"clip\"))\n        return clip_or_req\n\n    def check_qnn_fully_connected(pattern):\n        \"\"\"Check if the fully connected is supported by CMSIS-NN.\"\"\"\n        if str(pattern.op.name) == \"clip\":\n            relu = pattern\n            requantize = relu.args[0]\n        else:\n            requantize = pattern\n        requantize_input = requantize.args[0]\n        bias_add = None\n        bias_dtype = \"int32\"\n        if str(requantize_input.op.name) == \"nn.bias_add\":\n            bias_add = requantize_input\n            fc = bias_add.args[0]\n            bias_dtype = bias_add.args[1].checked_type.dtype\n        else:\n            fc = requantize_input\n        fc_input = fc.args[0]\n        fc_weight = fc.args[1]\n\n        # kernel zero_point should be 0\n        kernel_zp = fc.args[3].data.numpy().item(0)\n\n        return (\n            fc.attrs.out_dtype == \"int32\"\n            and fc_input.checked_type.dtype == \"int8\"\n            and fc_weight.checked_type.dtype == \"int8\"\n            and pattern.checked_type.dtype == \"int8\"\n            and bias_dtype == \"int32\"\n            and kernel_zp == 0\n        )\n\n    def qnn_avg_pool2d_pattern():\n        \"\"\"Matches average pooling with optional Relu\"\"\"\n        pattern = is_op(\"cast\")(wildcard())\n        pattern = is_op(\"nn.avg_pool2d\")(pattern)\n        pattern = is_op(\"cast\")(pattern)\n        pattern = pattern.optional(is_op(\"clip\"))\n        return pattern\n\n    def check_qnn_avg_pool2d(pattern):\n        \"\"\"Check if avg pool2d is supported by CMSIS-NN.\"\"\"\n        output = pattern\n\n        if str(pattern.op.name) == \"clip\":\n            pooling = pattern.args[0].args[0]\n        else:\n            pooling = pattern.args[0]\n        input_op = pooling.args[0].args[0]\n\n        return (\n            pooling.attrs.layout == \"NHWC\"\n            and int(input_op.checked_type.shape[0]) == 1\n            and input_op.checked_type.dtype == \"int8\"\n            and output.checked_type.dtype == \"int8\"\n        )\n\n    def qnn_max_pool2d_pattern():\n        \"\"\"Matches max pool2d with optional Relu\"\"\"\n        pattern = is_op(\"nn.max_pool2d\")(wildcard())\n        pattern = pattern.optional(is_op(\"clip\"))\n        return pattern\n\n    def check_qnn_max_pool2d(pattern):\n        \"\"\"Check if max pool2d is supported by CMSIS-NN.\"\"\"\n        output = pattern\n\n        if str(pattern.op.name) == \"clip\":\n            pooling = pattern.args[0]\n        else:\n            pooling = pattern\n        input_op = pooling.args[0]\n\n        return (\n            pooling.attrs.layout == \"NHWC\"\n            and int(input_op.checked_type.shape[0]) == 1\n            and input_op.checked_type.dtype == \"int8\"\n            and output.checked_type.dtype == \"int8\"\n        )\n\n    def binary_op_pattern(op):\n        \"\"\"Matches QNN binary operation\"\"\"\n        pattern = is_op(f\"qnn.{op}\")(\n            wildcard(),\n            wildcard(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n        )\n        return pattern.optional(is_op(\"clip\"))\n\n    def check_qnn_binary_op(pattern):\n        \"\"\"Check if binary op is supported by CMSIS-NN.\"\"\"\n        binary_op = pattern\n        if str(pattern.op.name) == \"clip\":\n            binary_op = pattern.args[0]\n\n        arg0 = binary_op.args[0]\n        arg1 = binary_op.args[1]\n        both_args_scalar = False\n        if (\n            isinstance(arg0, tvm.relay.expr.Constant)\n            and len(arg0.checked_type.shape) == 0\n            and isinstance(arg1, tvm.relay.expr.Constant)\n            and len(arg1.checked_type.shape) == 0\n        ):\n            both_args_scalar = True\n\n        return (\n            arg0.checked_type.dtype == \"int8\"\n            and arg1.checked_type.dtype == \"int8\"\n            and not both_args_scalar\n        )\n\n    return [\n        (\"cmsis-nn.qnn_conv2d\", qnn_conv2d_pattern(with_pad=True), check_qnn_conv2d_pad),\n        (\"cmsis-nn.qnn_conv2d\", qnn_conv2d_pattern(with_pad=False), check_qnn_conv2d),\n        (\"cmsis-nn.qnn_fully_connected\", qnn_fully_connected_pattern(), check_qnn_fully_connected),\n        (\"cmsis-nn.qnn_avg_pool2d\", qnn_avg_pool2d_pattern(), check_qnn_avg_pool2d),\n        (\"cmsis-nn.qnn_max_pool2d\", qnn_max_pool2d_pattern(), check_qnn_max_pool2d),\n        (\"cmsis-nn.qnn_mul\", binary_op_pattern(\"mul\"), check_qnn_binary_op),\n        (\"cmsis-nn.qnn_add\", binary_op_pattern(\"add\"), check_qnn_binary_op),\n        (\"cmsis-nn.qnn_softmax\", qnn_softmax_pattern(), check_qnn_softmax),\n    ]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/coreml.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"CoreML codegen supported operators.\"\"\"\nimport tvm.ir\nfrom tvm.contrib.target.coreml import _convert_map\nfrom ...expr import Constant\n\n\ndef _register_coreml_op(op_name):\n    \"\"\"Register a function to check the given operator is supported by Core ML.\n\n    Paramters\n    ---------\n    op_name : Str\n        The name of operator that will be registered.\n\n    \"\"\"\n\n    def _check_supported(expr):\n        attrs, args = expr.attrs, expr.args\n        if op_name == \"nn.conv2d\":\n            if not isinstance(args[1], Constant):\n                return False\n            if attrs[\"kernel_layout\"] not in [\"HWIO\", \"OIHW\"]:\n                return False\n        return True\n\n    tvm.ir.register_op_attr(op_name, \"target.coremlcompiler\", _check_supported)\n\n\nfor op in _convert_map:\n    _register_coreml_op(op)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/cublas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"cuBLAS Relay integration.\"\"\"\nfrom typing import Callable, List, Tuple, Dict, Optional\n\nimport tvm\nimport tvm.ir\nfrom tvm import relay\nfrom tvm import te\nfrom tvm.relay import transform\nfrom tvm.contrib import cublas\n\nfrom ...dataflow_pattern import is_op, wildcard\nfrom .te_target import lower_composite, relay_to_runtime\nfrom .register import register_pattern_table\n\n\ntvm._ffi.register_func(\"relay.ext.cublas\", relay_to_runtime(tvm.target.cuda()))\n\n\ndef partition_for_cublas(\n    mod: tvm.IRModule, params: Optional[Dict[str, tvm.runtime.NDArray]] = None\n) -> tvm.IRModule:\n    \"\"\"Partition the graph to offload for cuBLAS.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The module to partition.\n    params : Optional[Dict[str, tvm.runtime.NDArray]]\n        Constant input parameters.\n\n    Returns\n    -------\n    tvm.IRModule\n        The partitioned module.\n    \"\"\"\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.MergeComposite(pattern_table()),\n            transform.AnnotateTarget(\"cublas\"),\n            transform.PartitionGraph(),\n            transform.InferType(),\n        ]\n    )\n    return seq(mod)\n\n\n@register_pattern_table(\"cublas\")\ndef pattern_table() -> List[Tuple[str, relay.Pattern, Callable[[relay.Call], bool]]]:\n    \"\"\"Get the cuBLAS pattern table.\"\"\"\n\n    def matmul_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for matmul.\"\"\"\n        return is_op(\"nn.matmul\")(wildcard(), wildcard())\n\n    def batch_matmul_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for batch_matmul.\"\"\"\n        return is_op(\"nn.batch_matmul\")(wildcard(), wildcard())\n\n    def dense_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for dense.\"\"\"\n        return is_op(\"nn.dense\")(wildcard(), wildcard())\n\n    def check_matmul_like(matched: relay.Call) -> bool:\n        \"\"\"Check if matmul is supported by cuBLAS.\"\"\"\n        # Input data types can't be mixed\n        if matched.args[0].checked_type.dtype != matched.args[1].checked_type.dtype:\n            return False\n\n        in_dtype = matched.args[0].checked_type.dtype\n        out_dtype = matched.checked_type.dtype\n        # Only the following data type combinations are supported\n        if (in_dtype, out_dtype) not in [\n            (\"float32\", \"float32\"),\n            (\"float16\", \"float16\"),\n            (\"float16\", \"float32\"),\n            (\"int8\", \"int32\"),\n            (\"float64\", \"float64\"),\n            (\"int8\", \"float32\"),\n        ]:\n            return False\n\n        # If inputs are int8, input column strides must be a multiple of 4\n        if in_dtype == \"int8\":\n            if (\n                matched.args[0].checked_type.shape[-1] % 4 != 0\n                or matched.args[1].checked_type.shape[-1] % 4 != 0\n            ):\n                return False\n\n        return True\n\n    return [\n        (\"cublas.matmul\", matmul_pattern(), check_matmul_like),\n        (\"cublas.batch_matmul\", batch_matmul_pattern(), check_matmul_like),\n        (\"cublas.dense\", dense_pattern(), check_matmul_like),\n    ]\n\n\n@lower_composite(\"cublas.matmul\")\ndef _lower_matmul(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a matmul using cuBLAS.\"\"\"\n    return cublas.matmul(\n        inputs[0],\n        inputs[1],\n        transa=op.attrs[\"transpose_a\"],\n        transb=op.attrs[\"transpose_b\"],\n        dtype=op.checked_type.dtype,\n    )\n\n\n@lower_composite(\"cublas.batch_matmul\")\ndef _lower_batch_matmul(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a batch_matmul using cuBLAS.\"\"\"\n    return cublas.batch_matmul(\n        inputs[0],\n        inputs[1],\n        transa=op.attrs[\"transpose_a\"],\n        transb=op.attrs[\"transpose_b\"],\n        dtype=op.checked_type.dtype,\n    )\n\n\n@lower_composite(\"cublas.dense\")\ndef _lower_dense(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a dense using cuBLAS.\"\"\"\n    return cublas.matmul(\n        inputs[0], inputs[1], transa=False, transb=True, dtype=op.checked_type.dtype\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/cudnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"cuDNN Relay integration.\"\"\"\nfrom typing import Callable, List, Tuple\n\nimport tvm\nimport tvm.ir\nfrom tvm import relay\nfrom tvm import te\nfrom tvm.relay import transform\nfrom tvm.contrib import cudnn\n\nfrom ...dataflow_pattern import is_op, wildcard\nfrom .te_target import lower_composite, relay_to_runtime\nfrom .register import register_pattern_table\n\n\ntvm._ffi.register_func(\"relay.ext.cudnn\", relay_to_runtime(tvm.target.cuda()))\n\n\ndef partition_for_cudnn(mod: tvm.IRModule) -> tvm.IRModule:\n    \"\"\"Partition the graph to offload for cuDNN.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The module to partition.\n\n    Returns\n    -------\n    tvm.IRModule\n        The partitioned module.\n    \"\"\"\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.MergeComposite(pattern_table()),\n            transform.AnnotateTarget(\"cudnn\"),\n            transform.PartitionGraph(),\n            transform.InferType(),\n        ]\n    )\n    return seq(mod)\n\n\n@register_pattern_table(\"cudnn\")\ndef pattern_table() -> List[Tuple[str, relay.Pattern, Callable[[relay.Call], bool]]]:\n    \"\"\"Get the cuDNN pattern table.\"\"\"\n\n    def softmax_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for softmax.\"\"\"\n        return is_op(\"nn.softmax\")(wildcard())\n\n    def log_softmax_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for log_softmax.\"\"\"\n        return is_op(\"nn.log_softmax\")(wildcard())\n\n    def conv2d_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for conv2d.\"\"\"\n        return is_op(\"nn.conv2d\")(wildcard(), wildcard())\n\n    def conv2d_bias_act_pattern() -> relay.Pattern:\n        \"\"\"Create pattern for fused conv2d+bias+activation.\"\"\"\n        conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n        bias = is_op(\"nn.bias_add\")(conv2d, wildcard())\n        return bias.optional(is_op(\"nn.relu\"))\n\n    def check_softmax(matched: relay.Call) -> bool:\n        \"\"\"Check if softmax is supported by cuDNN.\"\"\"\n        if matched.args[0].checked_type.dtype not in [\"float64\", \"float32\", \"float16\"]:\n            return False\n\n        return True\n\n    def check_log_softmax(matched: relay.Call) -> bool:\n        \"\"\"Check if log_softmax is supported by cuDNN.\"\"\"\n        if matched.args[0].checked_type.dtype not in [\"float64\", \"float32\", \"float16\"]:\n            return False\n\n        if len(matched.args[0].checked_type.shape) != 2:\n            return False\n\n        if matched.attrs[\"axis\"] not in (1, -1):\n            return False\n\n        return True\n\n    def check_conv2d(matched: relay.Call) -> bool:\n        if matched.args[0].checked_type.dtype not in [\"float64\", \"float32\", \"float16\"]:\n            return False\n\n        if matched.attrs[\"data_layout\"] != \"NCHW\" or matched.attrs[\"kernel_layout\"] != \"OIHW\":\n            return False\n\n        padding = matched.attrs[\"padding\"]\n        if padding[0] != padding[2] or padding[1] != padding[3]:\n            return False\n\n        return True\n\n    def check_conv2d_bias_act(matched: relay.Call) -> bool:\n        return True\n\n    return [\n        (\"cudnn.softmax\", softmax_pattern(), check_softmax),\n        (\"cudnn.log_softmax\", log_softmax_pattern(), check_log_softmax),\n        (\"cudnn.conv2d_bias_act\", conv2d_bias_act_pattern(), check_conv2d_bias_act),\n        (\"cudnn.conv2d\", conv2d_pattern(), check_conv2d),\n    ]\n\n\n@lower_composite(\"cudnn.softmax\")\ndef _lower_softmax(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a softmax using cuDNN.\"\"\"\n    return cudnn.softmax(inputs[0], axis=op.attrs[\"axis\"])\n\n\n@lower_composite(\"cudnn.log_softmax\")\ndef _lower_log_softmax(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a log_softmax using cuDNN.\"\"\"\n    return cudnn.log_softmax(inputs[0], axis=op.attrs[\"axis\"])\n\n\n@lower_composite(\"cudnn.conv2d_bias_act\")\ndef _lower_conv2d_bias_act(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a fused conv2d+bias+activation using cuDNN.\"\"\"\n    conv_dtype = op.checked_type.dtype\n    if op.op.name == \"nn.relu\":\n        activation_mode = 1  # Relu\n        conv2d = op.args[0].args[0]\n    else:\n        activation_mode = 5  # Identity\n        conv2d = op.args[0]\n\n    conv_mode = 1\n    tensor_format = 0\n    algo = 1\n    pad = conv2d.attrs[\"padding\"]\n    strides = conv2d.attrs[\"strides\"]\n    dilation = conv2d.attrs[\"dilation\"]\n    groups = conv2d.attrs[\"groups\"]\n\n    oshape = cudnn.conv_output_shape(\n        tensor_format,\n        pad,\n        strides,\n        dilation,\n        inputs[0].shape,\n        inputs[1].shape,\n        inputs[0].dtype,\n        conv_dtype,\n        groups,\n    )\n\n    return te.extern(\n        oshape,\n        inputs,\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cudnn.conv2d+bias+act.forward\",\n            conv_mode,\n            tensor_format,\n            algo,\n            pad[0],\n            pad[1],\n            strides[0],\n            strides[1],\n            dilation[0],\n            dilation[1],\n            activation_mode,\n            0,\n            ins[0],\n            ins[1],\n            ins[2],\n            outs[0],\n            conv_dtype,\n            groups,\n        ),\n        name=\"y\",\n    )\n\n\n@lower_composite(\"cudnn.conv2d\")\ndef _lower_conv2d(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:\n    \"\"\"Lower a conv2d using cuDNN.\"\"\"\n    return cudnn.conv_forward(\n        inputs[0],\n        inputs[1],\n        pad=op.attrs[\"padding\"],\n        stride=op.attrs[\"strides\"],\n        dilation=op.attrs[\"dilation\"],\n        conv_mode=1,\n        tensor_format=0,\n        algo=1,\n        conv_dtype=op.checked_type.dtype,\n        groups=op.attrs[\"groups\"],\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/cutlass.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Patterns supported CUTLASS.\"\"\"\nfrom functools import partial\nfrom tvm import relay\nfrom tvm.ir.transform import Sequential, PassContext\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.contrib.register import register_pattern_table  # type: ignore\nfrom ...dataflow_pattern import wildcard, is_op, is_constant\n\n\ndef make_gelu_pattern(bias_out, out_dtype=\"float16\"):\n    mul = is_op(\"multiply\")(bias_out, is_constant() | wildcard())\n    if out_dtype == \"float16\":\n        erf = is_op(\"cast\")(is_op(\"erf\")(is_op(\"cast\")(mul)))\n    else:\n        erf = is_op(\"erf\")(mul)\n    mul_half = is_op(\"multiply\")(erf, is_constant() | wildcard())\n    add = is_op(\"add\")(mul_half, is_constant() | wildcard())\n    return is_op(\"multiply\")(add, bias_out)\n\n\ndef make_gemm_pattern(with_bias=True, with_act=None, out_dtype=\"float16\"):\n    \"\"\"Create a pattern for dense op followed by activations.\"\"\"\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    gemm = is_op(\"nn.dense\")(data, weight)\n    if with_bias:\n        add_or_bias_add = is_op(\"add\") | is_op(\"nn.bias_add\")\n        gemm_out = add_or_bias_add(gemm, bias)\n    else:\n        gemm_out = gemm\n\n    if with_act is None:\n        return gemm_out\n    if isinstance(with_act, str) and with_act == \"relu\":\n        return is_op(\"nn.relu\")(gemm_out)\n\n    assert isinstance(with_act, str) and with_act == \"gelu\"\n    return make_gelu_pattern(gemm_out, out_dtype)\n\n\ndef make_batch_matmul_pattern():\n    return is_op(\"nn.batch_matmul\")(wildcard(), wildcard())\n\n\ndef make_conv2d_pattern(with_bias=False, with_act=None):\n    \"\"\"Create a pattern for dense op followed by activations.\"\"\"\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    conv2d = is_op(\"nn.conv2d\")(data, weight)\n    if with_bias:\n        add_or_bias_add = is_op(\"add\") | is_op(\"nn.bias_add\")\n        conv2d_out = add_or_bias_add(conv2d, bias)\n    else:\n        conv2d_out = conv2d\n\n    if with_act is not None:\n        if with_act == \"relu\":\n            return is_op(\"nn.relu\")(conv2d_out)\n        if with_act == \"sigmoid\":\n            return is_op(\"sigmoid\")(conv2d_out)\n        if with_act == \"silu\":\n            return is_op(\"multiply\")(conv2d_out, is_op(\"sigmoid\")(conv2d_out))\n        if with_act == \"hardswish\":\n            rhs = is_op(\"divide\")(\n                is_op(\"clip\")(is_op(\"add\")(conv2d_out, is_constant())), is_constant()\n            )\n            return is_op(\"multiply\")(conv2d_out, rhs)\n\n        raise ValueError(\"Unknown activation %s.\" % with_act)\n\n    return conv2d_out\n\n\ndef make_conv2d_transpose_pattern():\n    return is_op(\"nn.conv2d_transpose\")(wildcard(), wildcard())\n\n\ndef make_conv2d_backward_weight_pattern():\n    return is_op(\"nn.conv2d_backward_weight\")(wildcard(), wildcard())\n\n\ndef make_residual_block_pattern(tensor_op_out, binary_op=\"add\", with_act=\"relu\"):\n    \"\"\"Add pattern for residual blocks.\"\"\"\n    residual_input = wildcard()\n    binary_out = is_op(binary_op)(tensor_op_out, residual_input) | is_op(binary_op)(\n        residual_input, tensor_op_out\n    )\n\n    if with_act is not None and with_act == \"relu\":\n        return is_op(\"nn.relu\")(binary_out)\n\n    return binary_out\n\n\ndef check_dtype(lhs, rhs):\n    \"\"\"Check if dtypes in the given workload are supported by CUTLASS.\"\"\"\n    return (\n        (lhs.dtype == \"float16\" and rhs.dtype == \"float16\")\n        or (lhs.dtype == \"float32\" and rhs.dtype == \"float32\")\n        or (lhs.dtype in [\"int8\", \"uint8\"] and rhs.dtype in [\"int8\", \"uint8\"])\n    )\n\n\ndef get_root_call(call, root_op_name):\n    if not isinstance(call, relay.Call):\n        return None\n    if str(call.op) == root_op_name:\n        return call\n    return get_root_call(call.args[0], root_op_name)\n\n\ndef check_gemm(call):\n    \"\"\"Check if the given dense workload can be offloaded to CUTLASS.\"\"\"\n    dense = get_root_call(call, \"nn.dense\")\n    lhs = dense.args[0].checked_type\n    rhs = dense.args[1].checked_type\n    return check_dtype(lhs, rhs)\n\n\ndef check_batch_matmul(call):\n    \"\"\"Check if the given batch_matmul workload can be offloaded to CUTLASS.\"\"\"\n    batch_matmul = get_root_call(call, \"nn.batch_matmul\")\n    lhs = batch_matmul.args[0].checked_type\n    rhs = batch_matmul.args[1].checked_type\n    transpose_a = batch_matmul.attrs.transpose_a\n    transpose_b = batch_matmul.attrs.transpose_b\n    return check_dtype(lhs, rhs) and not transpose_a and transpose_b\n\n\ndef is_depthwise_conv2d(ic, oc, groups):\n    return ic == oc == groups\n\n\ndef check_conv2d_common(op_name, expected_kernel_layout, call):\n    \"\"\"Check if the given conv2d workload can be offloaded to CUTLASS.\"\"\"\n    conv2d = get_root_call(call, op_name)\n    data_layout = conv2d.attrs.data_layout\n    kernel_layout = conv2d.attrs.kernel_layout\n    data = conv2d.args[0].checked_type\n    weight = conv2d.args[1].checked_type\n    if (\n        data_layout != \"NHWC\"\n        or kernel_layout != expected_kernel_layout\n        or not check_dtype(data, weight)\n    ):\n        return False\n    IC = data.shape[3]\n    OC = weight.shape[0]\n    return not is_depthwise_conv2d(IC, OC, conv2d.attrs.groups)\n\n\ndef check_conv2d(call):\n    return check_conv2d_common(\"nn.conv2d\", \"OHWI\", call)\n\n\ndef check_conv2d_transpose(call):\n    # conv2d_transpose is implemented as dgrad, needs to swap the roles of C and K\n    return check_conv2d_common(\"nn.conv2d_transpose\", \"IHWO\", call)\n\n\ndef check_conv2d_backward_weight(call):\n    return check_conv2d_common(\"nn.conv2d_backward_weight\", \"NHWC\", call)\n\n\ndef check_conv2d_residual(call, binary_op):\n    \"\"\"Check if the given conv2d workload can be offloaded to CUTLASS.\"\"\"\n    conv2d = get_root_call(call, \"nn.conv2d\")\n    if not check_conv2d(call):\n        return False\n\n    residual_binop = get_root_call(call, binary_op)\n    lhs = residual_binop.args[0]\n    rhs = residual_binop.args[1]\n\n    # residual_input is pattern-matched as a wildcard. Make sure it does not sit between\n    # residual binary op and the root conv2d of this pattern.\n    # If the root conv2d is the parent of both lhs and rhs, we should reject this pattern.\n    if get_root_call(lhs, \"nn.conv2d\") == conv2d and get_root_call(rhs, \"nn.conv2d\") == conv2d:\n        return False\n\n    return all(x == y for (x, y) in zip(lhs.checked_type.shape, rhs.checked_type.shape))\n\n\n@register_pattern_table(\"cutlass\")\ndef pattern_table():\n    \"\"\"Returns list of triples describing the name, dataflow pattern and predicate for all\n    the CUTLASS-supported operators.\"\"\"\n    dense_pat = (\"cutlass.dense\", make_gemm_pattern(False, None), check_gemm)\n    dense_bias_pat = (\"cutlass.dense_bias\", make_gemm_pattern(True, None), check_gemm)\n    dense_bias_relu_pat = (\"cutlass.dense_bias_relu\", make_gemm_pattern(True, \"relu\"), check_gemm)\n    dense_bias_gelu_fp16_pat = (\n        \"cutlass.dense_bias_gelu_fp16\",\n        make_gemm_pattern(True, \"gelu\"),\n        check_gemm,\n    )\n    dense_bias_gelu_fp32_pat = (\n        \"cutlass.dense_bias_gelu_fp32\",\n        make_gemm_pattern(True, \"gelu\", out_dtype=\"float32\"),\n        check_gemm,\n    )\n\n    dense_patterns = [\n        dense_bias_gelu_fp16_pat,\n        dense_bias_gelu_fp32_pat,\n        dense_bias_relu_pat,\n        dense_bias_pat,\n        dense_pat,\n        (\"cutlass.batch_matmul\", make_batch_matmul_pattern(), check_batch_matmul),\n    ]\n\n    conv2d_patterns = [\n        (\n            \"cutlass.conv2d_bias_hardswish\",\n            make_conv2d_pattern(with_bias=True, with_act=\"hardswish\"),\n            check_conv2d,\n        ),\n        (\n            \"cutlass.conv2d_bias_silu\",\n            make_conv2d_pattern(with_bias=True, with_act=\"silu\"),\n            check_conv2d,\n        ),\n        (\n            \"cutlass.conv2d_bias_relu\",\n            make_conv2d_pattern(with_bias=True, with_act=\"relu\"),\n            check_conv2d,\n        ),\n        (\n            \"cutlass.conv2d_bias_sigmoid\",\n            make_conv2d_pattern(with_bias=True, with_act=\"sigmoid\"),\n            check_conv2d,\n        ),\n        (\"cutlass.conv2d_bias\", make_conv2d_pattern(with_bias=True), check_conv2d),\n        (\"cutlass.conv2d\", make_conv2d_pattern(), check_conv2d),\n    ]\n\n    # For now, no fusion for grad kernels\n    conv2d_grad_patterns = [\n        (\"cutlass.conv2d_transpose\", make_conv2d_transpose_pattern(), check_conv2d_transpose),\n        (\n            \"cutlass.conv2d_backward_weight\",\n            make_conv2d_backward_weight_pattern(),\n            check_conv2d_backward_weight,\n        ),\n    ]\n\n    residual_block_patterns = []\n\n    for with_act, postfix in [(\"relu\", \"_relu\"), (None, \"\")]:\n        for name, pat, _ in conv2d_patterns[:-1]:\n            for bin_op in [\"add\", \"multiply\"]:\n                residual_block_patterns.append(\n                    (\n                        name + \"_residual_\" + bin_op + postfix,\n                        make_residual_block_pattern(pat, bin_op, with_act=with_act),\n                        partial(check_conv2d_residual, binary_op=bin_op),\n                    )\n                )\n\n    return residual_block_patterns + dense_patterns + conv2d_patterns + conv2d_grad_patterns\n\n\ndef partition_for_cutlass(mod, params=None):\n    \"\"\"Partition the input module into CUTLASS-supported subgraphs.\"\"\"\n\n    if params is not None:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n        remove_bn_pass = Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        with PassContext(opt_level=3):\n            mod = remove_bn_pass(mod)\n\n    cutlass_patterns = relay.op.contrib.get_pattern_table(\"cutlass\")\n\n    seq = Sequential(\n        [\n            transform.InferType(),\n            transform.MergeComposite(cutlass_patterns),\n            transform.AnnotateTarget([\"cutlass\"], include_non_call_ops=False),\n            transform.PartitionGraph(bind_constants=False),\n        ]\n    )\n\n    return seq(mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/cvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\nimport logging\n\nimport tvm\n\nfrom ... import dataflow_pattern as dp\nfrom ...dataflow_pattern import wildcard, is_op, is_constant, is_expr, rewrite, DFPatternCallback\nfrom .register import register_pattern_table\n\ndef _register_external_op_helper(op_name, supported=True):\n    \"\"\"The helper function to indicate that a given operator can be supported\n    by CVMRuntime.\n\n    Parameters\n    ----------\n    op_name : Str\n        The name of operator that will be registered.\n\n    Returns\n    -------\n    f : callable\n        A function that returns if the operator is supported by DNNL.\n    \"\"\"\n\n    @tvm.ir.register_op_attr(op_name, \"target.cvm\")\n    def _func_wrapper(expr: tvm.relay.expr.ExprWithOp):\n        # DNNL does not support pooling with ceil_mode = True.\n        if \"pool\" in op_name:\n            attrs = dict(get_attrs(expr))\n            if \"ceil_mode\" in attrs.keys() and attrs[\"ceil_mode\"]:\n                return False\n        return supported\n\n    return _func_wrapper\n\n_register_external_op_helper(\"nn.conv2d\")\n_register_external_op_helper(\"nn.dense\")\n_register_external_op_helper(\"nn.max_pool2d\")\n_register_external_op_helper(\"nn.relu\")\n_register_external_op_helper(\"abs\")\n_register_external_op_helper(\"clip\")\n_register_external_op_helper(\"add\")\n_register_external_op_helper(\"bias_add\")\n_register_external_op_helper(\"multiply\")\n\ndef make_nn_pattern(op_name, with_bias=False):\n    pat = op_name.replace(\"nn\", \"cvm\")\n    data, weight = wildcard(), wildcard()\n    out = dp.is_op(op_name)(data, weight)\n    if with_bias:\n        bias = wildcard()\n        bias_out = dp.is_op(\"add\")(out, bias)\n        bias_out = dp.is_op(\"nn.bias_add\")(out, bias) | bias_out\n        return [(pat, bias_out), (pat, out)]\n    return [(pat, out)]\n\ndef make_unary_pattern(op_name):\n    pat = \"cvm.\" + op_name\n    data = wildcard()\n    out = dp.is_op(op_name)(data)\n    return [(pat, out)]\n\ndef make_binary_pattern(op_name):\n    pat = \"cvm.\" + op_name\n    A, B = wildcard(), wildcard()\n    out = dp.is_op(op_name)(A, B)\n    return [(pat, out)]\n\n\n@register_pattern_table(\"cvm\")\ndef pattern_table():\n    cvm_patterns = list()\n    for op_name in [\"nn.conv2d\", \"nn.dense\"]:\n        cvm_patterns.extend(make_nn_pattern(\n            op_name, with_bias=True))\n    for op_name in [\"nn.relu\", \"nn.max_pool2d\"]:\n        cvm_patterns.extend(make_nn_pattern(op_name))\n\n    for op_name in [\"abs\", \"clip\"]:\n        cvm_patterns.extend(make_unary_pattern(op_name))\n    for op_name in [\"add\", \"bias_add\", \"multiply\"]:\n        cvm_patterns.extend(make_binary_pattern(op_name))\n    return cvm_patterns\n\n\ndef get_op_name(expr):\n    \"\"\"Get the operator name from an expression.\"\"\"\n    if isinstance(expr, Op):\n        return expr.name\n    if isinstance(expr, Call):\n        return get_op_name(expr.op)\n    if isinstance(expr, TupleGetItem):\n        return get_op_name(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return get_op_name(expr.fields[0])\n    return \"\"\n\n\ndef get_args(expr):\n    \"\"\"Get the arguments from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.args\n    if isinstance(expr, TupleGetItem):\n        return get_args(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return [arg for args in map(get_args, expr.fields) for arg in args]\n    return []\n\n\ndef get_attrs(expr):\n    \"\"\"Get the attributes from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.attrs\n    if isinstance(expr, TupleGetItem):\n        return get_attrs(expr.tuple_value)\n    return {}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/dnnl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"DNNL library supported operators.\nThere are two ways to registering a function for an op to indicate if it is\nsupported by DNNL.\n\n- The first and simplest way is to use the helper so that\nusers only need to provide the operator name and a boolean value to indicate if\nit is supported. For example:\n\n    .. code-block:: python\n\n      add = _register_external_op_helper(\"add\")\n      add = _register_external_op_helper(\"add\", True)\n      add = _register_external_op_helper(\"add\", False)\n\n- The other way is to implement the function by themselves to\ncheck the attributes of the op and decide if it should be offloaded to DNNL.\n\"\"\"\nimport logging\nfrom functools import reduce\n\nimport tvm.ir\nfrom tvm.ir import Op\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.expr import GlobalVar\nfrom tvm.relay.expr_functor import ExprMutator, ExprVisitor\nfrom tvm.relay.expr import const\n\nfrom tvm.relay.analysis import analysis as _analysis\nfrom tvm.relay import expr as _expr\n\nfrom tvm.relay.expr import Call, TupleGetItem\nfrom ... import _ffi_api\nfrom ...dataflow_pattern import wildcard, is_op, is_constant, is_expr, rewrite, DFPatternCallback\nfrom .register import register_pattern_table\n\n\nlogger = logging.getLogger(\"DNNL\")\nsupported_post_elts = [\"nn.relu\", \"tanh\", \"sigmoid\", \"clip\", \"gelu\", \"swish\", \"mish\", None]\n\n\ndef _register_external_op_helper(op_name, supported=True):\n    \"\"\"The helper function to indicate that a given operator can be supported\n    by DNNL.\n\n    Parameters\n    ----------\n    op_name : Str\n        The name of operator that will be registered.\n\n    Returns\n    -------\n    f : callable\n        A function that returns if the operator is supported by DNNL.\n    \"\"\"\n\n    @tvm.ir.register_op_attr(op_name, \"target.dnnl\")\n    def _func_wrapper(expr):\n        args = expr.args\n        if any([x.checked_type.dtype == \"int64\" for x in args]):\n            logger.info(\"DNNL does not support int64.\")\n            return False\n        # DNNL does not support pooling with ceil_mode = True.\n        if \"pool\" in op_name:\n            attrs = dict(get_attrs(expr))\n            if \"ceil_mode\" in attrs.keys() and attrs[\"ceil_mode\"]:\n                return False\n        return supported\n\n    return _func_wrapper\n\n\n_register_external_op_helper(\"nn.batch_norm\")\n_register_external_op_helper(\"nn.conv1d\")\n_register_external_op_helper(\"nn.conv2d\")\n_register_external_op_helper(\"nn.conv3d\")\n_register_external_op_helper(\"nn.conv2d_transpose\")\n_register_external_op_helper(\"nn.conv3d_transpose\")\n_register_external_op_helper(\"nn.dense\")\n_register_external_op_helper(\"nn.max_pool2d\")\n_register_external_op_helper(\"nn.avg_pool2d\")\n_register_external_op_helper(\"nn.global_avg_pool2d\")\n_register_external_op_helper(\"nn.max_pool3d\")\n_register_external_op_helper(\"nn.avg_pool3d\")\n_register_external_op_helper(\"abs\")\n_register_external_op_helper(\"clip\")\n_register_external_op_helper(\"exp\")\n_register_external_op_helper(\"log\")\n_register_external_op_helper(\"sqrt\")\n_register_external_op_helper(\"round\")\n_register_external_op_helper(\"nn.relu\")\n_register_external_op_helper(\"nn.leaky_relu\")\n_register_external_op_helper(\"tanh\")\n_register_external_op_helper(\"sigmoid\")\n_register_external_op_helper(\"nn.softmax\")\n_register_external_op_helper(\"add\")\n_register_external_op_helper(\"multiply\")\n_register_external_op_helper(\"nn.layer_norm\")\n_register_external_op_helper(\"nn.batch_matmul\")\n\n\ndef append_eltwise_ops(op, eltwise):\n    \"\"\"Append element-wise post-ops to conv / conv_transpose / dense\n\n    Parameters\n    ----------\n    op : str\n        The op name to be attached with element-wise post-op.\n    eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    pattern : CallPattern\n        Call node sequence.\n    \"\"\"\n    if eltwise == \"gelu\":\n        const1 = wildcard()\n        const2 = wildcard()\n        const3 = wildcard()\n        div = is_op(\"divide\")(op, const1)\n        erf_val = is_op(\"erf\")(div)\n        added_erf_val = is_op(\"add\")(erf_val, const2)\n        mul_val = is_op(\"multiply\")(op, added_erf_val)\n        op = is_op(\"multiply\")(mul_val, const3)\n    elif eltwise == \"swish\":\n        sig_out = is_op(\"sigmoid\")(op)\n        op = is_op(\"multiply\")(op, sig_out)\n    elif eltwise == \"mish\":\n        const1 = wildcard()\n        exp = is_op(\"exp\")(op)\n        add = is_op(\"add\")(exp, const1)\n        log = is_op(\"log\")(add)\n        tanh = is_op(\"tanh\")(log)\n        op = is_op(\"multiply\")(op, tanh)\n    elif eltwise:\n        op = is_op(eltwise)(op)\n    return op\n\n\ndef make_conv_pattern(conv_name, with_bias=True, with_eltwise=None):\n    \"\"\"Create patterns related to conv and conv_transpose.\n\n    Parameters\n    ----------\n    with_bias : bool\n        Whether attach `bias_add` to `conv / conv_transpose`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    conv_out : CallPattern\n        Call node sequence.\n    \"\"\"\n    if with_eltwise not in supported_post_elts:\n        raise ValueError(\"Unsupported eltwise post-op: %s\" % with_eltwise)\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    conv = is_op(conv_name)(data, weight)\n    if with_bias:\n        conv_out = is_op(\"add\")(conv, bias)\n    else:\n        conv_out = conv\n    return append_eltwise_ops(conv_out, with_eltwise)\n\n\ndef make_conv_bias_sum_relu_pattern(conv_type, has_relu=True):\n    \"\"\"Create patterns with sum op.\n\n    Parameters\n    ----------\n    conv_type : str\n        Should be nn.conv1d / nn.conv2d / nn.conv3d.\n    has_relu : bool\n        Whether attach relu.\n    Returns\n    -------\n    out : CallPattern\n        Call node sequence.\n    \"\"\"\n    data1 = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    data2 = wildcard()\n    out = is_op(conv_type)(data1, weight)\n    out = is_op(\"add\")(out, bias)\n    out = is_op(\"add\")(out, data2)\n    if has_relu:\n        out = is_op(\"nn.relu\")(out)\n    return out\n\n\ndef get_op_name(expr):\n    \"\"\"Get the operator name from an expression.\"\"\"\n    if isinstance(expr, Op):\n        return expr.name\n    if isinstance(expr, Call):\n        return get_op_name(expr.op)\n    if isinstance(expr, TupleGetItem):\n        return get_op_name(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return get_op_name(expr.fields[0])\n    return \"\"\n\n\ndef get_args(expr):\n    \"\"\"Get the arguments from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.args\n    if isinstance(expr, TupleGetItem):\n        return get_args(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return [arg for args in map(get_args, expr.fields) for arg in args]\n    return []\n\n\ndef get_attrs(expr):\n    \"\"\"Get the attributes from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.attrs\n    if isinstance(expr, TupleGetItem):\n        return get_attrs(expr.tuple_value)\n    return {}\n\n\ndef make_sum_pattren_predicate(checker):\n    \"\"\"Check whether the conv_bias_add_sum pattern is as expected.\"\"\"\n\n    def predicate(expr):\n        if get_op_name(expr) == \"nn.relu\":\n            expr = expr.args[0]\n        for e, op_name in zip([expr, expr.args[0]], [\"sum\", \"bias_add\"]):\n            args = get_args(e)\n            attrs = get_attrs(e.args[0])\n            if not checker(attrs, args, op_name):\n                return False\n        return True\n\n    return predicate\n\n\ndef make_bias_add_pattren_predicate(checker):\n    \"\"\"Check whether the conv_bias pattern is as expected.\"\"\"\n\n    def predicate(expr):\n        if get_op_name(expr) == \"nn.relu\":\n            expr = expr.args[0]\n        if get_op_name(expr) == \"add\":\n            args = get_args(expr)\n            attrs = get_attrs(expr.args[0])\n            if not checker(attrs, args, \"bias_add\"):\n                return False\n        return True\n\n    return predicate\n\n\ndef add_checker(attrs, args, op_name):\n    \"\"\"Check if add is aligned with elementwise_add and bias_add.\"\"\"\n    if op_name == \"sum\":\n        if not isinstance(args[0].op, tvm.ir.op.Op):\n            return False\n        if args[0].op.name != \"add\":\n            return False\n        if tuple(get_shape(args[0])) != tuple(get_shape(args[1])):\n            return False\n    if op_name == \"bias_add\":\n        if attrs is None:\n            return False\n        if not isinstance(args[0].op, tvm.ir.op.Op):\n            return False\n        if args[0].op.name != \"nn.conv2d\":\n            return False\n        channel = dict(attrs)[\"channels\"]\n        const_shape = get_shape(args[1])\n        if channel != reduce(lambda x, y: x * y, const_shape):\n            return False\n    return True\n\n\ndef make_dense_pattern(with_bias=True, with_eltwise=None):\n    \"\"\"Create patterns related to nn.dense.\n\n    Parameters\n    ----------\n    with_bias : bool\n        Whether attach `bias_add` to `nn.dense`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    dense_out : CallPattern\n        Call node sequence.\n    \"\"\"\n    if with_eltwise not in supported_post_elts:\n        raise ValueError(\"Unsupported eltwise post-op: %s\" % with_eltwise)\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n\n    dense = is_op(\"nn.dense\")(data, weight)\n    if with_bias:\n        dense_out = is_op(\"add\")(dense, bias)\n    else:\n        dense_out = dense\n    return append_eltwise_ops(dense_out, with_eltwise)\n\n\ndef make_dnnl_pattern(op_name, with_bias, with_eltwise):\n    \"\"\"Create dnnl patterns.\n\n    Parameters\n    ----------\n    op_name : str\n        The first call node's op name.\n    with_bias : bool\n        Whether attach `bias_add` to `nn.dense`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    pat_name = op_name.replace(\"nn\", \"dnnl\")\n    if \"_transpose\" in op_name:\n        pat_name = \"dnnl.deconv\" + op_name.split(\"_\")[0][-2::]\n    pat_name += \"_bias\" if with_bias else \"\"\n    pat_name += (\"_\" + with_eltwise.split(\".\")[-1]) if with_eltwise else \"\"\n    if \"conv\" in op_name:\n        dnnl_pattern = (\n            pat_name,\n            make_conv_pattern(op_name, with_bias, with_eltwise),\n            make_bias_add_pattren_predicate(add_checker),\n        )\n    elif op_name == \"nn.dense\":\n        dnnl_pattern = (pat_name, make_dense_pattern(with_bias, with_eltwise))\n    else:\n        logger.warning(\n            \"Currently, only conv1d, conv2d, conv2d_transpose, conv3d_transpose, \"\n            \"dense op are supported, but got %s.\",\n            op_name,\n        )\n        dnnl_pattern = ()\n    return dnnl_pattern\n\n\ndef make_qnn_conv2d_pattern():\n    \"\"\"Make qnn.conv2d based pattern supported by DNNL\n\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    data = wildcard()\n    weight = is_constant()\n    bias = is_constant()\n    o_scl = is_constant()\n    dst_zp = is_constant()\n    act_scl = is_constant()\n    sum_scl = is_constant()\n    sum_src = wildcard()\n\n    zero_zp = is_expr(const(0, dtype=\"int32\"))\n\n    pat = is_op(\"qnn.conv2d\")(data, weight, zero_zp, zero_zp, is_constant(), is_constant())\n    pat = is_op(\"cast\")(pat)\n    pat = is_op(\"add\")(pat, bias) | pat  # optional bias\n    pat = is_op(\"multiply\")(pat, o_scl)\n    pat = is_op(\"clip\")(pat)  # TBD, not only clip\n    pat = is_op(\"multiply\")(pat, act_scl) | pat  # optional multiply. Ex: act_scl == 1\n    pat = is_op(\"add\")(pat, sum_scl * is_op(\"cast\")(sum_src)) | pat  # optional sum\n    pat = is_op(\"add\")(pat, dst_zp) | pat  # optional dst_zp, can be dst_zp == 0\n    pat = is_op(\"cast\")(pat)\n\n    return \"dnnl.qnn.conv2d\", pat\n\n\ndef make_qnn_dense_pattern():\n    \"\"\"Make qnn.dense based pattern supported by DNNL\n\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    data = wildcard()\n    weight = is_constant()\n    bias = is_constant()\n    o_scl = is_constant()\n    dst_zp = is_constant()\n    act_scl = is_constant()\n    sum_scl = is_constant()\n    sum_src = wildcard()\n\n    zero_zp = is_expr(const(0, dtype=\"int32\"))\n\n    pat = is_op(\"qnn.dense\")(data, weight, zero_zp, zero_zp, is_constant(), is_constant())\n    pat = is_op(\"cast\")(pat)\n    pat = is_op(\"add\")(pat, bias) | pat  # optional bias\n    pat = is_op(\"multiply\")(pat, o_scl)\n    pat = is_op(\"clip\")(pat)  # TBD, not only clip\n    pat = is_op(\"multiply\")(pat, act_scl) | pat  # optional multiply. ex act_scl == 1\n    pat = is_op(\"add\")(pat, sum_scl * is_op(\"cast\")(sum_src)) | pat  # optional sum\n    pat = is_op(\"add\")(pat, dst_zp) | pat  # optional dst_zp, can be dst_zp == 0\n    pat = is_op(\"cast\")(pat)\n\n    return \"dnnl.qnn.dense\", pat\n\n\n@register_pattern_table(\"dnnl\")\ndef pattern_table():\n    \"\"\"Create dnnl patterns.\n\n    Returns\n    -------\n    dnnl_patterns : List[dnnl_pattern]\n        Created patterns.\n    \"\"\"\n    dnnl_patterns = list()\n    dnnl_patterns.append(make_qnn_conv2d_pattern())\n    dnnl_patterns.append(make_qnn_dense_pattern())\n    dnnl_patterns.append(\n        (\n            \"dnnl.conv2d_bias_sum_relu\",\n            make_conv_bias_sum_relu_pattern(\"nn.conv2d\"),\n            make_sum_pattren_predicate(add_checker),\n        )\n    )\n    dnnl_patterns.append(\n        (\n            \"dnnl.conv2d_bias_sum\",\n            make_conv_bias_sum_relu_pattern(\"nn.conv2d\", False),\n            make_sum_pattren_predicate(add_checker),\n        )\n    )\n\n    elt_list = [\"nn.relu\", \"tanh\", \"sigmoid\", \"clip\", \"gelu\", \"swish\", \"mish\", None]\n    for with_bias in [True, False]:\n        for elt in elt_list:\n            if not with_bias and not elt:\n                continue\n            for conv_name in [\n                \"nn.conv1d\",\n                \"nn.conv2d\",\n                \"nn.conv3d\",\n                \"nn.conv2d_transpose\",\n                \"nn.conv3d_transpose\",\n            ]:\n                dnnl_patterns.append(make_dnnl_pattern(conv_name, with_bias, elt))\n            dnnl_patterns.append(make_dnnl_pattern(\"nn.dense\", with_bias, elt))\n    return dnnl_patterns\n\n\ndef get_optimal_layout_for_conv(\n    data_layout, kernel_layout, weight_shape, out_shape, paddings, strides, dilates, groups, dtype\n):\n    \"\"\"Get the optimal layout of dnnl, given shape of conv2d.\n\n    Parameters\n    ----------\n    data_layout, kernel_layout,weight_shape, out_shape, paddings, strides, dilates, groups\n        : String\n          Input argument.\n\n    Returns\n    -------\n    layouts : string\n              The result.\n    \"\"\"\n    return _ffi_api.get_optimal_layout_for_conv(\n        data_layout,\n        kernel_layout,\n        weight_shape,\n        out_shape,\n        paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n\n\ndef get_optimal_layout_for_conv_transpose(\n    data_layout,\n    kernel_layout,\n    weight_shape,\n    out_shape,\n    paddings,\n    output_paddings,\n    strides,\n    dilates,\n    groups,\n    dtype,\n):\n    \"\"\"Get the optimal layout of dnnl, given shape of tranposed conv2d.\n\n    Parameters\n    ----------\n    data_layout, kernel_layout, weight_shape, out_shape, paddings, output_paddings, strides,\n    dilates, groups\n        : Int, String\n          Input argument.\n\n    Returns\n    -------\n    layouts : string\n              The result.\n    \"\"\"\n    return _ffi_api.get_optimal_layout_for_conv_transpose(\n        data_layout,\n        kernel_layout,\n        weight_shape,\n        out_shape,\n        paddings,\n        output_paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n\n\ndef get_shape(tensor):\n    \"\"\"Get tensor's shape.\"\"\"\n    if isinstance(tensor, relay.expr.Var):\n        return tensor.type_annotation.concrete_shape\n    if isinstance(tensor, relay.expr.Constant):\n        return tensor.data.shape\n    if isinstance(tensor, tvm.ir.tensor_type.TensorType):\n        return tensor.concrete_shape\n    if isinstance(tensor, tvm.ir.container.Array):\n        return tensor[-1].shape\n    if isinstance(tensor, relay.expr.Call):\n        if tensor.op.name == \"multiply\":\n            return tensor.type_args[0].shape\n        return tensor.checked_type.shape\n    raise TypeError(\"Unsupport data type: %s\" % type(tensor))\n\n\ndef get_dtype(tensor):\n    \"\"\"Get tensor's dtype.\"\"\"\n    if isinstance(tensor, relay.expr.Var):\n        return tensor.type_annotation.dtype\n    if isinstance(tensor, relay.expr.Constant):\n        return tensor.data.dtype\n    if isinstance(tensor, tvm.ir.tensor_type.TensorType):\n        return tensor.dtype\n    if isinstance(tensor, tvm.ir.container.Array):\n        return tensor[-1].dtype\n    if isinstance(tensor, relay.expr.Call):\n        if tensor.op.name == \"multiply\":\n            return tensor.type_args[0].dtype\n        return tensor.checked_type.dtype\n    raise TypeError(\"Unsupport data type: %s\" % type(tensor))\n\n\ndef tag2layout(input_data, is_weight=False, conv_type=\"Conv1D\"):\n    \"\"\"Transfer layout, denoted with `a, b, c, d, e`,\n    into valid layout (NCHW / OIHW) of TVM.\"\"\"\n    if \"Conv1D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"W\", \"d\": \"G\"}\n    elif \"Conv2D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"H\", \"d\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"H\", \"d\": \"W\"}\n        if \"e\" in input_data:\n            weight_dic = {\"a\": \"G\", \"b\": \"O\", \"c\": \"I\", \"d\": \"H\", \"e\": \"W\"}\n    elif \"Conv3D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"D\", \"d\": \"H\", \"e\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"D\", \"d\": \"H\", \"e\": \"W\", \"f\": \"G\"}\n\n    dic = weight_dic if is_weight else data_dic\n    res = \"\"\n\n    for i in input_data:\n        if i.isupper():\n            i = i.lower()\n            res += dic[i]\n            dic[i] = dic[i].lower()\n        elif i.islower():\n            res += dic[i]\n        elif i.isdigit():\n            res += i\n        else:\n            raise ValueError(\"Unsupport layout format: %s\" % input_data)\n\n    return res\n\n\ndef legalize_pad_avg_pool(attrs, inputs, types):\n    \"\"\"Legalize pad->avg_pool2d pattern.\n    Fuse this pattern into one avg_pool2d with padding = (1, 1),\n    and count_include_pad = True\"\"\"\n    data = inputs[0]\n    new_attrs = dict(attrs)\n    if isinstance(data, relay.expr.Call) and data.op.name == \"nn.pad\":\n        new_attrs[\"padding\"] = (1, 1)\n        new_attrs[\"count_include_pad\"] = True\n        return relay.nn.avg_pool2d(data.args[0], **new_attrs)\n    return relay.nn.avg_pool2d(data, **attrs)\n\n\ndef legalize_group_conv(attrs, inputs, types):\n    \"\"\"Legalize group conv / conv_transpose calculation.\n    Alter weight layout from OIHW to GOIHW / IOHW to GIOHW\"\"\"\n    groups = attrs.groups\n    data, weight = inputs\n    if groups == 1:\n        if \"Transpose\" not in type(attrs).__name__:\n            return relay.nn.conv2d(data, weight, **attrs)\n        return relay.nn.conv2d_transpose(data, weight, **attrs)\n    OC, IC, H, W = get_shape(weight)\n    new_attrs = dict(attrs)\n    weight = relay.reshape(weight, (groups, OC // groups, IC, H, W))\n    if \"Transpose\" not in type(attrs).__name__:\n        new_attrs[\"kernel_layout\"] = \"GOIHW\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    new_attrs[\"kernel_layout\"] = \"GIOHW\"\n    return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n\n\ndef alter_conv(attrs, inputs, tinfos, out_type):\n    \"\"\"The convolution's layout auto-query func for dnnl.\"\"\"\n\n    data, weight = inputs\n    groups = str(attrs.groups)\n    weight_shape = \",\".join([str(x) for x in get_shape(weight)])\n    out_shape = \",\".join([str(x) for x in get_shape(out_type)])\n    paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"padding\")])\n    strides = \",\".join([str(x) for x in attrs.get_int_tuple(\"strides\")])\n    dilates = \",\".join([str(x) for x in attrs.get_int_tuple(\"dilation\")])\n    dtype = get_dtype(weight)\n    new_attrs = dict(attrs)\n    conv_type = type(attrs).__name__.split(\"Attrs\")[0]\n\n    res = get_optimal_layout_for_conv(\n        attrs[\"data_layout\"],\n        attrs[\"kernel_layout\"],\n        weight_shape,\n        out_shape,\n        paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n    src_df, weight_df, dst_df = res.split(\",\")\n    new_attrs[\"data_layout\"] = tag2layout(src_df, is_weight=False, conv_type=conv_type)\n    new_attrs[\"kernel_layout\"] = tag2layout(weight_df, is_weight=True, conv_type=conv_type)\n    new_attrs[\"out_layout\"] = tag2layout(dst_df, is_weight=False, conv_type=conv_type)\n\n    if conv_type == \"Conv1D\":\n        return relay.nn.conv1d(data, weight, **new_attrs)\n    if conv_type == \"Conv2D\":\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    return relay.nn.conv3d(data, weight, **new_attrs)\n\n\ndef alter_conv_transpose(attrs, inputs, tinfos, out_type):\n    \"\"\"The transposed convolution's layout auto-query func for dnnl.\"\"\"\n\n    data, weight = inputs\n    weight_shape = \",\".join([str(x) for x in get_shape(weight)])\n    out_shape = \",\".join([str(x) for x in get_shape(out_type)])\n    paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"padding\")])\n    output_paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"output_padding\")])\n    strides = \",\".join([str(x) for x in attrs.get_int_tuple(\"strides\")])\n    dilates = \",\".join([str(x) for x in attrs.get_int_tuple(\"dilation\")])\n    groups = str(attrs.groups)\n    dtype = get_dtype(weight)\n    new_attrs = dict(attrs)\n    conv_type = type(attrs).__name__.split(\"Attrs\")[0]\n\n    res = get_optimal_layout_for_conv_transpose(\n        attrs[\"data_layout\"],\n        attrs[\"kernel_layout\"],\n        weight_shape,\n        out_shape,\n        paddings,\n        output_paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n    src_df, weight_df, dst_df = res.split(\",\")\n    new_attrs[\"data_layout\"] = tag2layout(src_df, is_weight=False, conv_type=conv_type)\n    new_attrs[\"kernel_layout\"] = tag2layout(weight_df, is_weight=True, conv_type=conv_type)\n    new_attrs[\"out_layout\"] = tag2layout(dst_df, is_weight=False, conv_type=conv_type)\n\n    if conv_type == \"Conv1DTranspose\":\n        return relay.nn.conv1d_transpose(data, weight, **new_attrs)\n    if conv_type == \"Conv2DTranspose\":\n        return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n    return relay.nn.conv3d_transpose(data, weight, **new_attrs)\n\n\nclass IsComputeIntensiveGraph(ExprVisitor):\n    \"\"\"\n    Visits the Graph recursively and checks if it contains compute heavy ops like convolutions and\n    its transpose and dense.\n    \"\"\"\n\n    def __init__(self):\n        ExprVisitor.__init__(self)\n        self.is_compute_intensive = False\n\n    def visit_call(self, call):\n        compute_intensive_ops = set(\n            [\n                \"nn.conv1d\",\n                \"nn.conv2d\",\n                \"nn.conv2d_transpose\",\n                \"nn.conv3d\",\n                \"nn.conv3d_transpose\",\n                \"nn.dense\",\n                \"nn.layer_norm\",\n                \"nn.batch_matmul\",\n                \"nn.global_avg_pool2d\",\n            ]\n        )\n        if isinstance(call.op, tvm.tir.op.Op):\n            if str(call.op) in compute_intensive_ops:\n                self.is_compute_intensive = True\n\n        return super().visit_call(call)\n\n    def is_graph_compute_intensive(self, subgraph) -> bool:\n        \"\"\"\n        This function recursively visits the graph and checks if it's compute intensive\"\n        \"\"\"\n        self.visit(subgraph)\n        return self.is_compute_intensive\n\n\ndef is_valid_subgraph(body):\n    \"\"\"Final check on whether the subgraph is valid and should be offloaded to DNNL.\"\"\"\n    return IsComputeIntensiveGraph().is_graph_compute_intensive(body)\n\n\ndef prune_dnnl_subgraphs(mod):\n    \"\"\"\n    Removes invalid subgraphs, which does not contain compute intensive dnnl ops.\n    \"\"\"\n\n    class SubgraphRemover(ExprMutator):\n        \"\"\"\n        Reverts subgraphs in subgraphs_to_remove back to TVM instead of using an external codegen.\n        \"\"\"\n\n        def __init__(self, subgraphs_to_remove, mod, new_mod):\n            ExprMutator.__init__(self)\n            self.subgraphs_to_remove = subgraphs_to_remove\n            self.mod = mod\n            self.new_mod = new_mod\n\n        def visit_call(self, call):\n            if isinstance(call.op, GlobalVar):\n                name = call.op.name_hint\n                if name in self.subgraphs_to_remove:\n                    # \"Inline\" the subgraph back into new main function.\n                    func = self.mod[name]\n                    var_map = {}\n                    for arg, param in zip(call.args, func.params):\n                        var_map[param] = super().visit(arg)\n                    new_body = relay.bind(func.body, var_map)\n                    return new_body\n                if name != \"main\":\n                    args = []\n                    for arg in call.args:\n                        args.append(super().visit(arg))\n                    return call.op(*args)\n            return super().visit_call(call)\n\n    subgraphs_to_remove = []\n    # If only one subgraph, do nothing.\n    if len(mod.get_global_vars()) <= 2:\n        return mod\n    # Remove invalid subgraphs\n    for subgraph in mod.get_global_vars():\n        name = subgraph.name_hint\n        if not mod[name].attrs or mod[name].attrs[\"Compiler\"] != \"dnnl\":\n            continue\n        if not is_valid_subgraph(mod[name].body):\n            subgraphs_to_remove.append(name)\n    # Create new pruned module\n    new_mod = tvm.IRModule(mod.functions, mod.type_definitions)\n    new_mod[\"main\"] = SubgraphRemover(subgraphs_to_remove, mod, new_mod).visit(mod[\"main\"])\n    new_mod = transform.RemoveUnusedFunctions()(new_mod)\n    return new_mod\n\n\nclass LayerNormRewrite(DFPatternCallback):\n    \"\"\"\n    A callback to rewrite the following operators into a single layer normalization operator.\n\n    Pattern #1:\n    1   %4 = mean(%3, axis=[-1], keepdims=True) /* ty=Tensor[(1, 3136, 1), float32] */;\n    2   %5 = subtract(%3, %4) /* ty=Tensor[(1, 3136, 64), float32] */;\n    3   %6 = cast(%5, dtype=\"float32\") /* ty=Tensor[(1, 3136, 64), float32] */;\n    4   %7 = power(%6, 2f /* ty=float32 */) /* ty=Tensor[(1, 3136, 64), float32] */;\n    5   %8 = mean(%7, axis=[-1], keepdims=True) /* ty=Tensor[(1, 3136, 1), float32] */;\n    6   %9 = add(%8, 1e-05f /* ty=float32 */) /* ty=Tensor[(1, 3136, 1), float32] */;\n    7   %10 = sqrt(%9) /* ty=Tensor[(1, 3136, 1), float32] */;\n    8   %11 = divide(%5, %10) /* ty=Tensor[(1, 3136, 64), float32] */;\n    9   %12 = multiply(%11, meta[relay.Constant][2] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 3136, 64), float32] */;\n    10   %13 = add(%12, meta[relay.Constant][3] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 3136, 64), float32] */;\n\n    Pattern #2:\n    1   %0 = mean(%input, axis=[-1], keepdims=True);\n    2   %1 = variance(%input, %0, axis=[-1], keepdims=True);\n    3   %2 = add(%1, 1e-05f /* ty=float32 */) /* ty=Tensor[(1, 49, 1), float32] */;\n    4   %3 = subtract(%input, %0);\n    5   %4 = sqrt(%2) /* ty=Tensor[(1, 49, 1), float32] */;\n    6   %5 = divide(%3, %4);\n    7   %6 = multiply(%5, meta[relay.Constant][0] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 49, 64), float32] */;\n    8   %7 = add(%6, meta[relay.Constant][1] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 49, 64), float32] */\n\n    \"\"\"\n\n    def __init__(self):\n        super(LayerNormRewrite, self).__init__()\n        self.data = wildcard()\n        self.gamma = wildcard()\n        self.beta = wildcard()\n        mu = is_op(\"mean\")(self.data)\n        diff = is_op(\"subtract\")(self.data, mu)\n        cdiff = diff | is_op(\"cast\")(diff)\n        const_two = is_expr(relay.const(2)) | is_expr(relay.const(2.0))\n        p1 = is_op(\"power\")(cdiff, const_two)\n        mp1 = is_op(\"mean\")(p1) | is_op(\"variance\")(self.data, mu)\n        eps = is_expr(relay.const(1e-5)) | is_expr(relay.const(1e-6))\n        added_eps = is_op(\"add\")(mp1, eps)\n        deno = is_op(\"sqrt\")(added_eps)\n        div_out = is_op(\"divide\")(diff, deno)\n        div_out2 = diff * is_op(\"rsqrt\")(added_eps)\n        weighted = is_op(\"multiply\")(div_out | div_out2, self.gamma)\n        added_bias = is_op(\"add\")(weighted, self.beta)\n        self.pattern = added_bias\n\n    def callback(self, pre, post, node_map):\n        data = node_map[self.data][0]\n        gamma = node_map[self.gamma][0]\n        beta = node_map[self.beta][0]\n        return relay.op.nn.layer_norm(data=data, gamma=gamma, beta=beta)\n\n\ndef rewrite_layer_norm(mod):\n    \"\"\"Rewrite the input graph to replace multiple operators with a TVM native layer normalization\n    operator so that we can offload them to dnnl layer normalization byoc part.\n    \"\"\"\n    mod[\"main\"] = rewrite(LayerNormRewrite(), mod[\"main\"])\n    return mod\n\n\nclass DenseReshapeBiasGeluRewrite(DFPatternCallback):\n    \"\"\"\n    A callback to reorder reshape operators when the patterns are as below:\n\n    Pattern #1:\n    1   %62 = nn.dense(%61, meta[relay.Constant][13] /* ty=Tensor[(64, 64), float32] */,\n                units=None, out_dtype=\"float32\") /* ty=Tensor[(3136, 64), float32] */;\n    2   %63 = reshape(%62, newshape=[1, 3136, 64]) /* ty=Tensor[(1, 3136, 64), float32] */;\n    3   %64 = add(meta[relay.Constant][4] /* ty=Tensor[(64), float32] */, %63)\n                /* ty=Tensor[(1, 3136, 64), float32] */;\n\n    Pattern #2:\n    1   %76 = nn.dense(%75, meta[relay.Constant][18] /* ty=Tensor[(512, 64), float32] */,\n                units=None, out_dtype=\"float32\") /*  ty=Tensor[(3136, 512), float32] */;\n    2   %77 = reshape(%76, newshape=[1, 3136, 512]) /* ty=Tensor[(1, 3136, 512), float32] */;\n    3   %78 = add(meta[relay.Constant][15] /* ty=Tensor[(512), float32] */, %77)\n                /* ty=Tensor[(1, 3136, 512), float32] */;\n    4   %79 = divide(%78, 1.41421f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    5   %80 = erf(%79) /* ty=Tensor[(1, 3136, 512), float32] */;\n    6   %81 = add(%80, 1f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    7   %82 = multiply(%78, %81) /* ty=Tensor[(1, 3136, 512), float32] */;\n    8   %83 = multiply(%82, 0.5f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    \"\"\"\n\n    def __init__(self, has_gelu=True):\n        super(DenseReshapeBiasGeluRewrite, self).__init__()\n        self.data = wildcard()\n        self.weight = wildcard()\n        self.bias = wildcard()\n        self.const1 = wildcard()\n        self.const2 = wildcard()\n        self.const3 = wildcard()\n\n        self.attr_map = {}\n        self.has_gelu = has_gelu\n\n        den = is_op(\"nn.dense\")(self.data, self.weight)\n        re_den = is_op(\"reshape\")(den)\n        added = is_op(\"add\")(self.bias, re_den)\n        if self.has_gelu:\n            divisor = is_op(\"divide\")(added, self.const1)\n            val_erf = is_op(\"erf\")(divisor)\n            added_erf = is_op(\"add\")(val_erf, self.const2)\n            mul1 = is_op(\"multiply\")(added, added_erf)\n            mul2 = is_op(\"multiply\")(mul1, self.const3)\n            self.pattern = mul2\n        else:\n            self.pattern = added\n\n    def get_attr(self, pre):\n        \"\"\"Recursively retrieve attributes from reshape operator.\"\"\"\n\n        def visit_func(expr):\n            if isinstance(expr, _expr.Call) and expr.op == relay.op.get(\"reshape\"):\n                new_attrs = {}\n                for k in expr.attrs.keys():\n                    new_attrs[k] = expr.attrs[k]\n                self.attr_map[\"reshape\"] = new_attrs\n\n        _analysis.post_order_visit(pre, visit_func)\n\n    def callback(self, pre, post, node_map):\n        self.get_attr(pre)\n\n        data = node_map[self.data][0]\n        weight = node_map[self.weight][0]\n        bias = node_map[self.bias][0]\n\n        den = relay.op.nn.dense(data, weight)\n        added = relay.op.add(bias, den)\n        if not self.has_gelu:\n            return relay.op.reshape(added, self.attr_map[\"reshape\"][\"newshape\"])\n\n        const1 = node_map[self.const1][0]\n        const2 = node_map[self.const2][0]\n        const3 = node_map[self.const3][0]\n\n        divisor = relay.op.divide(added, const1)\n        val_erf = relay.op.erf(divisor)\n        added_erf = relay.op.add(val_erf, const2)\n        mul1 = relay.op.multiply(added, added_erf)\n        mul2 = relay.op.multiply(mul1, const3)\n        return relay.op.reshape(mul2, self.attr_map[\"reshape\"][\"newshape\"])\n\n\ndef rewrite_dense_bias_gelu_reshape_last(mod):\n    \"\"\"Rewrite the input graph to reorder reshape operators so that\n    we can perform dense_bias_gelu/dense_bias fusion and then offload\n    them to byoc part.\n    \"\"\"\n    mod[\"main\"] = rewrite(\n        [DenseReshapeBiasGeluRewrite(), DenseReshapeBiasGeluRewrite(has_gelu=False)], mod[\"main\"]\n    )\n    return mod\n\n\nclass ResNetV1Rewrite(DFPatternCallback):\n    \"\"\"\n    A callback to advance downsize operation when the patterns are as pattern1,\n    and the result is written in pattern2:\n    Pattern #1:\n    %26 = nn.conv2d(%25, ty=Tensor[(64, 256, 1, 1));\n    %27 = add(%26, ty=Tensor[(64, 1, 1));\n    %28 = nn.relu(%27);\n\n    %29 = nn.conv2d(%28, ty=Tensor[(64, 64, 3, 3));\n    %30 = add(%29, ty=Tensor[(64, 1, 1));\n    %31 = nn.relu(%30);\n\n    %32 = nn.conv2d(%31, ty=Tensor[(256, 64, 1, 1));\n    %33 = add(%32, ty=Tensor[(256, 1, 1));\n    %34 = add(%33, %25);\n    %35 = nn.relu(%34);\n\n    %36 = nn.conv2d(%35, ty=Tensor[(128, 256, 1, 1), strides=[2, 2]);\n    %37 = add(%36, ty=Tensor[(128, 1, 1));\n    %38 = nn.relu(%37);\n\n    %39 = nn.conv2d(%38, ty=Tensor[(128, 128, 3, 3));\n    %40 = add(%39, ty=Tensor[(128, 1, 1)]);\n    %41 = nn.relu(%40);\n\n    %42 = nn.conv2d(%41, ty=Tensor[(512, 128, 1, 1));\n    %43 = nn.conv2d(%35, ty=Tensor[(512, 256, 1, 1), strides=[2, 2]);\n    %44 = add(%42, ty=Tensor[(512, 1, 1));\n    %45 = add(%43, ty=Tensor[(512, 1, 1));\n\n    %46 = add(%44, %45);\n    %47 = nn.relu(%46);\n    Pattern #2:\n    %26 = nn.conv2d(%25, ty=Tensor[(64, 256, 1, 1));\n    %27 = add(%26, ty=Tensor[(64, 1, 1));\n    %28 = nn.relu(%27);\n\n    %29 = nn.conv2d(%28, ty=Tensor[(64, 64, 3, 3), strides=[2, 2]);\n    %30 = add(%29, ty=Tensor[(64, 1, 1));\n    %31 = nn.relu(%30);\n\n    %32 = nn.conv2d(%31, ty=Tensor[(256, 64, 1, 1));\n    %33 = add(%32, ty=Tensor[(256, 1, 1));\n    %34 = nn.max_pool2d(%25, pool_size=[1, 1], strides=[2, 2], padding=[0, 0, 0, 0]);\n    %35 = add(%33, %34);\n    %36 = nn.relu(%35);\n\n    %37 = nn.conv2d(%36, ty=Tensor[(128, 256, 1, 1));\n    %38 = add(%37, ty=Tensor[(128, 1, 1));\n    %39 = nn.relu(%38);\n\n    %40 = nn.conv2d(%39, ty=Tensor[(128, 128, 3, 3));\n    %41 = add(%40, ty=Tensor[(128, 1, 1));\n    %42 = nn.relu(%41);\n\n    %43 = nn.conv2d(%42, ty=Tensor[(512, 128, 1, 1));\n    %44 = nn.conv2d(%36, ty=Tensor[(512, 256, 1, 1));\n    %45 = add(%43, ty=Tensor[(512, 1, 1));\n    %46 = add(%44, ty=Tensor[(512, 1, 1));\n    %47 = add(%45, %46);\n    %48 = nn.relu(%47);\n    \"\"\"\n\n    def __init__(self):\n        super(ResNetV1Rewrite, self).__init__()\n        self.attr_lst = []\n        self.data = wildcard()\n        self.w1, self.b1 = wildcard(), wildcard()\n        self.w2, self.b2 = wildcard(), wildcard()\n        self.w3, self.b3 = wildcard(), wildcard()\n        self.w4, self.b4 = wildcard(), wildcard()\n        self.w5, self.b5 = wildcard(), wildcard()\n        self.w6, self.b6 = wildcard(), wildcard()\n        self.w7, self.b7 = wildcard(), wildcard()\n\n        conv1 = is_op(\"nn.conv2d\")(self.data, self.w1).has_attr({\"kernel_size\": [1, 1]})\n        conv1 = is_op(\"add\")(conv1, self.b1)\n        conv1 = is_op(\"nn.relu\")(conv1)\n\n        conv2 = is_op(\"nn.conv2d\")(conv1, self.w2).has_attr({\"kernel_size\": [3, 3]})\n        conv2 = is_op(\"add\")(conv2, self.b2)\n        conv2 = is_op(\"nn.relu\")(conv2)\n\n        conv3 = is_op(\"nn.conv2d\")(conv2, self.w3).has_attr({\"kernel_size\": [1, 1]})\n        conv3 = is_op(\"add\")(conv3, self.b3)\n        conv3 = is_op(\"add\")(conv3, self.data)\n        conv3 = is_op(\"nn.relu\")(conv3)\n\n        left_conv4 = is_op(\"nn.conv2d\")(conv3, self.w4).has_attr({\"strides\": [2, 2]})\n        left_conv4 = is_op(\"add\")(left_conv4, self.b4)\n        left_conv4 = is_op(\"nn.relu\")(left_conv4)\n\n        left_conv5 = is_op(\"nn.conv2d\")(left_conv4, self.w5).has_attr({\"kernel_size\": [3, 3]})\n        left_conv5 = is_op(\"add\")(left_conv5, self.b5)\n        left_conv5 = is_op(\"nn.relu\")(left_conv5)\n\n        left_conv6 = is_op(\"nn.conv2d\")(left_conv5, self.w6).has_attr({\"kernel_size\": [1, 1]})\n        left_conv6 = is_op(\"add\")(left_conv6, self.b6)\n\n        right_conv7 = is_op(\"nn.conv2d\")(conv3, self.w7).has_attr({\"strides\": [2, 2]})\n        right_conv7 = is_op(\"add\")(right_conv7, self.b7)\n\n        out = is_op(\"add\")(left_conv6, right_conv7)\n        out = is_op(\"nn.relu\")(out)\n        self.pattern = out\n\n    def get_attr(self, pre):\n        \"\"\"Recursively retrieve attributes from reshape operator.\"\"\"\n\n        def visit_func(expr):\n            if isinstance(expr, _expr.Call) and expr.op == relay.op.get(\"nn.conv2d\"):\n                self.attr_lst.append(expr.attrs)\n\n        _analysis.post_order_visit(pre, visit_func)\n\n    def callback(self, pre, post, node_map):\n        self.get_attr(pre)\n        data = node_map[self.data][0]\n        w1, b1 = node_map[self.w1][0], node_map[self.b1][0]\n        w2, b2 = node_map[self.w2][0], node_map[self.b2][0]\n        w3, b3 = node_map[self.w3][0], node_map[self.b3][0]\n        w4, b4 = node_map[self.w4][0], node_map[self.b4][0]\n        w5, b5 = node_map[self.w5][0], node_map[self.b5][0]\n        w6, b6 = node_map[self.w6][0], node_map[self.b6][0]\n        w7, b7 = node_map[self.w7][0], node_map[self.b7][0]\n\n        new_attrs = self.attr_lst[-7]\n        conv1 = relay.op.nn.conv2d(data, w1, **new_attrs)\n        conv1 = relay.op.add(conv1, b1)\n        conv1 = relay.op.nn.relu(conv1)\n\n        new_attrs = dict(self.attr_lst[-6])\n        new_attrs[\"strides\"] = [2, 2]\n        conv2 = relay.op.nn.conv2d(conv1, w2, **new_attrs)\n        conv2 = relay.op.add(conv2, b2)\n        conv2 = relay.op.nn.relu(conv2)\n\n        new_attrs = self.attr_lst[-5]\n        conv3 = relay.op.nn.conv2d(conv2, w3, **new_attrs)\n        conv3 = relay.op.add(conv3, b3)\n        max_pool = relay.op.nn.max_pool2d(\n            data, pool_size=(1, 1), strides=(2, 2), layout=new_attrs[\"data_layout\"]\n        )\n        conv3 = relay.op.add(conv3, max_pool)\n        conv3 = relay.op.nn.relu(conv3)\n\n        new_attrs = dict(self.attr_lst[-4])\n        new_attrs[\"strides\"] = [1, 1]\n        left_conv4 = relay.op.nn.conv2d(conv3, w4, **new_attrs)\n        left_conv4 = relay.op.add(left_conv4, b4)\n        left_conv4 = relay.op.nn.relu(left_conv4)\n\n        new_attrs = self.attr_lst[-3]\n        left_conv5 = relay.op.nn.conv2d(left_conv4, w5, **new_attrs)\n        left_conv5 = relay.op.add(left_conv5, b5)\n        left_conv5 = relay.op.nn.relu(left_conv5)\n\n        new_attrs = self.attr_lst[-2]\n        left_conv6 = relay.op.nn.conv2d(left_conv5, w6, **new_attrs)\n        left_conv6 = relay.op.add(left_conv6, b6)\n\n        new_attrs = dict(self.attr_lst[-1])\n        new_attrs[\"strides\"] = [1, 1]\n        right_conv7 = relay.op.nn.conv2d(conv3, w7, **new_attrs)\n        right_conv7 = relay.op.add(right_conv7, b7)\n\n        out = relay.op.add(left_conv6, right_conv7)\n        out = relay.op.nn.relu(out)\n        self.attr_lst = []\n        return out\n\n\ndef rewrite_resnetv1(mod):\n    \"\"\"Rewrite the the ResNetV1 downsize block to reduce the computation complexity.\"\"\"\n    mod[\"main\"] = rewrite(ResNetV1Rewrite(), mod[\"main\"])\n    return mod\n\n\nclass LegalizeQnnOpForDnnl(DFPatternCallback):\n    \"\"\"Legalize QNN based patterns to match DNNL\n\n    original pattern:\n      OP = qnn.dense | qnn.conv2d\n      %1 = OP<int>(SRC, WGH) - OP<int>(src_zp, WGH)   // qnn.conv2d\n      %2 = %1 + orig_bias                             // bias\n      %2 = (%1 - rq_in_zp) * rq_in_scl / rq_out_scl + rq_out_zp  // qnn.requantize\n      %3 = act(%2)                                               // activation == clip\n      %4 = ((%3 - sum_lh_zp) * sum_lh_scl + (SRC2 - sum_rh_zp) * sum_rh_scl)  // qnn.add\n           / sum_out_scl + sum_out_zp\n\n    transform to DNNL compatible:\n      %1 = OP<int>(SRC, WGH)\n      %2 = cast(%1, dtype=\"float\")\n      %2 = (%1 + bias) * o_scl\n      %3 = act(%2) * act_scl\n      %4 = %3 + SRC2 * sum_scl\n      %5 = %4 + dst_zp\n      %6 = cast(%5, dtype=\"float\")\n\n    where:\n      o_scl = rq_in_scl / rq_out_scl\n      act_scl = sum_lhs_scl / sum_out_scl\n      sum_scl = sum_rhs_scl / sum_out_scl\n      bias = orig_bias - OP(src_zp, WGH) - rq_in_zp + rq_out_zp * rq_out_scl / rq_in_scl\n      dst_zp = sum_out_zp - sum_lhs_zp * sum_lhs_scl / sum_out_scl -\n               sum_rhs_zp * sum_rhs_scl / sum_out_scl\n    \"\"\"\n\n    def __init__(self):\n        super(LegalizeQnnOpForDnnl, self).__init__()\n        self.src = wildcard()\n        self.wgh = wildcard()\n        self.bias = wildcard()\n        self.sum_src = wildcard()\n\n        self.src_scl = is_constant()\n        self.src_zp = is_constant()\n        self.wgh_scl = is_constant()\n        self.wgh_zp = is_expr(const(0))\n\n        self.rq_in_scl = is_constant()\n        self.rq_in_zp = is_constant()\n        self.rq_out_scl = is_constant()\n        self.rq_out_zp = is_constant()\n\n        self.sum_lhs_scl = is_constant()\n        self.sum_lhs_zp = is_constant()\n        self.sum_rhs_scl = is_constant()\n        self.sum_rhs_zp = is_constant()\n        self.sum_out_scl = is_constant()\n        self.sum_out_zp = is_constant()\n\n        self.root = (is_op(\"qnn.conv2d\") | is_op(\"qnn.dense\"))(\n            self.src, self.wgh, self.src_zp, self.wgh_zp, self.src_scl, self.wgh_scl\n        )\n        pat = is_op(\"add\")(self.root, self.bias) | self.root  # optional bias\n        pat = is_op(\"qnn.requantize\")(\n            pat, self.rq_in_scl, self.rq_in_zp, self.rq_out_scl, self.rq_out_zp\n        )\n        pat = is_op(\"clip\")(pat)\n        cast = is_op(\"cast\")(pat)\n        pat = is_op(\"qnn.add\")(\n            cast,\n            self.sum_src,\n            self.sum_lhs_scl,\n            self.sum_lhs_zp,\n            self.sum_rhs_scl,\n            self.sum_rhs_zp,\n            self.sum_out_scl,\n            self.sum_out_zp,\n        )\n        pat = is_op(\"clip\")(pat)\n        self.pattern = pat | cast\n\n    def callback(self, pre, post, node_map):\n        root = node_map[self.root][0]\n        src = node_map[self.src][0]\n        wgh = node_map[self.wgh][0]\n        bias = node_map.get(self.bias, default=[relay.const(0, dtype=\"int32\")])[0]\n        src_zp = node_map[self.src_zp][0]\n        rq_in_scl = node_map[self.rq_in_scl][0]\n        rq_in_zp = node_map[self.rq_in_zp][0]\n        rq_out_scl = node_map[self.rq_out_scl][0]\n        rq_out_zp = node_map[self.rq_out_zp][0]\n\n        final_dtype = node_map[self.pattern][0].checked_type.dtype\n\n        if root.op == relay.op.get(\"qnn.conv2d\"):\n            dst_layout = root.attrs.out_layout\n            dst_layout = root.attrs.data_layout if dst_layout == \"\" else dst_layout\n            wgh_layout = root.attrs.kernel_layout\n        else:\n            # qnn.dense has no layout attributes. Assume that is plain\n            dst_layout = \"NC\"\n            wgh_layout = \"OI\"\n\n        # TODO(@apeskov): dst_layout may ne blocked\n        bias_rank = len(dst_layout) - dst_layout.index(\"C\")\n\n        sum_src = node_map[self.sum_src][0] if self.sum_src in node_map else None\n        # Default values if qnn.sum is not present\n        sum_lhs_scl = node_map[self.sum_lhs_scl][0] if sum_src else relay.const(1, dtype=\"float32\")\n        sum_lhs_zp = node_map[self.sum_lhs_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n        sum_rhs_scl = node_map[self.sum_rhs_scl][0] if sum_src else relay.const(0, dtype=\"float32\")\n        sum_rhs_zp = node_map[self.sum_rhs_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n        sum_out_scl = node_map[self.sum_out_scl][0] if sum_src else relay.const(1, dtype=\"float32\")\n        sum_out_zp = node_map[self.sum_out_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n\n        def cast_fp(op):\n            return relay.op.cast(op, dtype=\"float32\")\n\n        # recalculate some factors\n        o_scl = rq_in_scl / rq_out_scl\n        act_scl = sum_lhs_scl / sum_out_scl\n        sum_scl = sum_rhs_scl / sum_out_scl\n        dst_zp = (\n            cast_fp(sum_out_zp)\n            - cast_fp(sum_lhs_zp) * sum_lhs_scl / sum_out_scl\n            - cast_fp(sum_rhs_zp) * sum_rhs_scl / sum_out_scl\n        )\n        bias = self.squeeze_bias(bias, dst_layout)\n        bias = (\n            cast_fp(bias)\n            - cast_fp(self.fake_op(src_zp, wgh, wgh_layout))\n            - cast_fp(rq_in_zp)\n            + cast_fp(rq_out_zp) * rq_out_scl / rq_in_scl\n        )\n        bias = self.broadcast_to_rank(bias, bias_rank)\n\n        zero_zp = relay.const(0, dtype=\"int32\")\n        one_scl = relay.const(1.0, dtype=\"float32\")\n\n        # construct new graph with proper post op ordering\n        gr = tvm.relay.Call(\n            root.op,\n            [src, wgh, zero_zp, zero_zp, one_scl, one_scl],\n            root.attrs,\n            root.type_args,\n            root.span,\n        )\n        gr = relay.op.cast(gr, dtype=\"float32\")\n        gr = gr + bias\n        gr = gr * o_scl\n        gr = relay.op.clip(gr, 0, 255) * act_scl\n        gr = gr + sum_scl * cast_fp(sum_src) if sum_src else gr\n        gr = gr + dst_zp\n        gr = relay.op.cast(gr, dtype=final_dtype)\n        return gr\n\n    @staticmethod\n    def fake_op(zp, wgh, layout):\n        \"\"\"Fake operator implementation for zp broadcast input\"\"\"\n        # Conv:  reduce kernel {OC, IC, KH, KW} -> {OC} in case of group that is still correct\n        # Dense: reduce kernel {OC, IC} -> {OC}\n        wgh_int = relay.op.cast(wgh, dtype=\"int32\")\n        reduced_kernel = relay.op.sum(\n            wgh_int, axis=[layout.index(\"O\")], keepdims=False, exclude=True\n        )\n        return zp * reduced_kernel\n\n    @staticmethod\n    def squeeze_bias(bias, layout):\n        shape = transform.InferTypeLocal(bias).concrete_shape\n        c_position = layout.index(\"C\") - len(layout) + len(shape)\n        squeeze_idxs = [i for i in range(len(shape)) if i != c_position]\n        return relay.op.squeeze(bias, squeeze_idxs)\n\n    @staticmethod\n    def broadcast_to_rank(op, rank):\n        \"\"\"Scalar or 1D tensor are supported\"\"\"\n        shape = transform.InferTypeLocal(op).concrete_shape\n        if len(shape) == 0:\n            return op\n        if len(shape) == 1:\n            return relay.op.expand_dims(op, 1, rank - 1)\n        raise ValueError(\"Unexpected bias rank to broadcast. Only 0 and 1 are supported.\")\n\n\ndef legalize_qnn_for_dnnl(mod):\n    \"\"\"Transform qnn primitives to DNNL compatible form. Eliminate source zero point and apply\n    strict sequence of post ops.\"\"\"\n    mod[\"main\"] = rewrite(LegalizeQnnOpForDnnl(), mod[\"main\"])\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            # transform.SimplifyInference(),  # TODO: this pass decompose nn.layer_norm\n            # transform.FoldScaleAxis(),  # TODO: fail inside TVM in case of grouped convolutions.\n            transform.FoldConstant(),\n        ]\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/ethosn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Arm(R) Ethos(TM)-N NPU supported operators.\"\"\"\nfrom enum import Enum\nfrom distutils.version import LooseVersion\n\nimport tvm.ir\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\n\nfrom ...dataflow_pattern import is_constant, is_op, wildcard\nfrom . import _ethosn\nfrom .register import register_pattern_table\n\n\nclass Available(Enum):\n    UNAVAILABLE = 0\n    SW_ONLY = 1\n    SW_AND_HW = 2\n\n    def __bool__(self):\n        return self != Available.UNAVAILABLE\n\n\ndef ethosn_available():\n    \"\"\"Return whether Ethos-N software and hardware support is available\"\"\"\n    if not tvm.get_global_func(\"relay.ethos-n.query\", True):\n        print(\"skip because Ethos-N module is not available\")\n        return Available.UNAVAILABLE\n    hw = tvm.get_global_func(\"relay.ethos-n.query\")()\n    return Available.SW_AND_HW if hw else Available.SW_ONLY\n\n\ndef ethosn_api_version() -> str:\n    \"\"\"\n    Returns the semantic version of the driver stack api that is\n    being used.\n\n    Returns\n    -------\n    str\n        Semantic version string (e.g. 3.0.1).\n    \"\"\"\n    return tvm.get_global_func(\"relay.ethos-n.api.version\")()\n\n\ndef ConvertEquivalents() -> tvm.ir.IRModule:  # pylint: disable=invalid-name\n    \"\"\"Converts operations into a numerically equivalent form\n    that can be understood by the NPU codegen.\n\n    Returns\n    -------\n    Pass\n        The module pass.\n    \"\"\"\n    return _ethosn.ConvertEquivalents()\n\n\ndef InlineNonComputeIntensivePartitions() -> tvm.ir.IRModule:  # pylint: disable=invalid-name\n    \"\"\"This pass checks whether functions partitioned for the NPU are considered\n    non-compute intensive. If they are not, they will be unpartitioned and passed onto\n    other backends to consider.\n\n    A partitioned function is currently considered non-compute intensive if it contains\n    no multiply accumulate operations.\n\n    Returns\n    -------\n    Pass\n        The module pass.\n    \"\"\"\n    return _ethosn.InlineNonComputeIntensivePartitions()\n\n\ndef is_inline_non_compute_intensive_partitions_enabled() -> bool:\n    \"\"\"\n    Determine whether to inline none-compute-intensive partitions.\n\n    Returns\n    -------\n    True if inlining should happen, False if not.\n    \"\"\"\n    compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-n.get_compiler_attrs\")()\n    if not compiler_attrs:\n        return False\n    return compiler_attrs.inline_non_compute_intensive_partitions\n\n\ndef partition_for_ethosn(mod, params=None, **opts):\n    \"\"\"Partition the graph greedily offloading supported\n    operators to Arm Ethos-N NPU.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n\n    Returns\n    -------\n    ret : annotated and partitioned module.\n    \"\"\"\n    api_version = ethosn_api_version()\n    supported_api_versions = [\"3.1.0\"]\n    if all(api_version != LooseVersion(exp_ver) for exp_ver in supported_api_versions):\n        raise ValueError(\n            f\"Driver stack version {api_version} is unsupported. \"\n            f\"Please use version in {supported_api_versions}.\"\n        )\n\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    passes = [\n        transform.InferType(),\n        transform.MergeComposite(pattern_table()),\n        transform.AnnotateTarget(\"ethos-n\"),\n        transform.MergeCompilerRegions(),\n        transform.PartitionGraph(),\n        ConvertEquivalents(),\n    ]\n    if is_inline_non_compute_intensive_partitions_enabled():\n        passes.append(InlineNonComputeIntensivePartitions())\n\n    return tvm.transform.Sequential(passes)(mod)\n\n\n@register_pattern_table(\"ethos-n\")\ndef pattern_table():\n    \"\"\"Get the Ethos-N compiler pattern table.\"\"\"\n\n    def qnn_conv_pattern():\n        pattern = is_op(\"nn.pad\")(wildcard(), wildcard()) | wildcard()\n        pattern = is_op(\"qnn.conv2d\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        pattern = is_op(\"nn.bias_add\")(pattern, is_constant())\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def qnn_fc_pattern():\n        pattern = is_op(\"qnn.dense\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        pattern = is_op(\"nn.bias_add\")(pattern, is_constant())\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def qnn_avg_pool2d_pattern():\n        pattern = is_op(\"cast\")(wildcard())\n        pattern = is_op(\"nn.avg_pool2d\")(pattern)\n        pattern = is_op(\"cast\")(pattern)\n        return pattern\n\n    def qnn_sigmoid_pattern():\n        pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n        pattern = is_op(\"sigmoid\")(pattern)\n        pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n        return pattern\n\n    def qnn_mean_pattern():\n        pattern = is_op(\"cast\")(wildcard())\n        pattern = is_op(\"mean\")(pattern)\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def qnn_tanh_pattern():\n        pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n        pattern = is_op(\"tanh\")(pattern)\n        pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n        return pattern\n\n    def qnn_leaky_relu_pattern():\n        pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n        pattern = is_op(\"nn.leaky_relu\")(pattern)\n        pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n        return pattern\n\n    def qnn_requantize_pattern():\n        pattern = is_op(\"qnn.requantize\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def qnn_resize_pattern():\n        pattern = is_op(\"image.resize2d\")(wildcard()).has_attr({\"method\": \"nearest_neighbor\"})\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def qnn_mul_pattern():\n        \"\"\"\n        Multiply is supported when one input is a constant of shape [1, ..., C],\n        where C matches the number of channels of the other input.\n        \"\"\"\n        mul_op = is_op(\"qnn.mul\")\n        gen_mul_inputs = lambda x, y: mul_op(\n            x,\n            y,\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n        )\n        input_is_left = gen_mul_inputs(wildcard(), is_constant())\n        input_is_right = gen_mul_inputs(is_constant(), wildcard())\n        return input_is_left | input_is_right\n\n    def qnn_add_pattern(has_constant_input=False):\n        add_op = is_op(\"qnn.add\")\n        gen_add_inputs = lambda x, y: add_op(\n            x,\n            y,\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n            is_constant(),\n        )\n\n        if has_constant_input:\n            input_is_left = gen_add_inputs(wildcard(), is_constant())\n            input_is_right = gen_add_inputs(is_constant(), wildcard())\n            return input_is_left | input_is_right\n        else:\n            return gen_add_inputs(wildcard(), wildcard())\n\n    def qnn_conv2d_transpose_pattern():\n        pattern = is_op(\"qnn.conv2d_transpose\")(\n            wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n        ).has_attr({\"data_layout\": \"NHWC\"})\n        pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n        pattern = is_op(\"qnn.requantize\")(\n            pattern, is_constant(), is_constant(), is_constant(), is_constant()\n        )\n        return pattern\n\n    def check_conv2d(extract):\n        \"\"\"Check if a conv2d is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.conv2d(extract)\n\n    def check_fc(extract):\n        \"\"\"Check if a fully connected is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.fc(extract)\n\n    def check_avg_pool2d(extract):\n        \"\"\"Check if a avg pool2d is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.avg_pool2d(extract)\n\n    def check_mean(extract):\n        \"\"\"Check if mean is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.mean(extract)\n\n    def check_conv2d_transpose(extract):\n        \"\"\"Check if conv2d_transpose is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.conv2d_transpose(extract)\n\n    def check_sigmoid(extract):\n        \"\"\"Check if a sigmoid is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.sigmoid(extract)\n\n    def check_tanh(extract):\n        \"\"\"Check if tanh is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.tanh(extract)\n\n    def check_leaky_relu(extract):\n        \"\"\"Check if Leaky ReLU is supported.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.leaky_relu(extract)\n\n    def check_mul_to_reinterpret_quantize(extract):\n        \"\"\"Check if Mul is supported by converting to reinterpret quantize\"\"\"\n        if not ethosn_available():\n            return False\n\n        converted_extract = _ethosn.ConvertQnnMultiplyToReinterpretQuantize(extract)\n        if converted_extract:\n            return _ethosn.reinterpret_quantize(converted_extract)\n        return False\n\n    def check_mul_to_depthwise(extract):\n        \"\"\"Check if Mul is supported by converting to a depthwise operation.\"\"\"\n        if not ethosn_available():\n            return False\n        converted_extract = _ethosn.ConvertQnnMultiplyToDepthwise(extract)\n        if converted_extract:\n            return _ethosn.conv2d(converted_extract)\n        return False\n\n    def check_requantize(extract):\n        \"\"\"Check if requantize is supported.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.requantize(extract)\n\n    def check_resize(extract):\n        \"\"\"Check if resize (nearest neighbor) is supported.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.resize(extract)\n\n    def check_add(extract):\n        \"\"\"Check if an addition is supported by Ethos-N.\"\"\"\n        if not ethosn_available():\n            return False\n\n        return _ethosn.addition(extract)\n\n    def check_add_to_reinterpret_quantize(extract):\n        \"\"\"Check if addition can be converted to a reinterpret quantize operation.\"\"\"\n        if not ethosn_available():\n            return False\n        converted_extract = _ethosn.ConvertQnnAddToReinterpretQuantize(extract)\n        if converted_extract:\n            return _ethosn.reinterpret_quantize(converted_extract)\n        return False\n\n    def check_add_to_depthwise(extract):\n        \"\"\"Check if addition can be converted to a depthwise operation.\"\"\"\n        if not ethosn_available():\n            return False\n        converted_extract = _ethosn.ConvertQnnAddToDepthwise(extract)\n        if converted_extract:\n            return _ethosn.conv2d(converted_extract)\n        return False\n\n    return [\n        (\n            \"ethos-n.qnn_mul_to_reinterpret_quantize\",\n            qnn_mul_pattern(),\n            check_mul_to_reinterpret_quantize,\n        ),\n        (\"ethos-n.qnn_mul_to_depthwise\", qnn_mul_pattern(), check_mul_to_depthwise),\n        (\n            \"ethos-n.qnn_add_to_reinterpret_quantize\",\n            qnn_add_pattern(True),\n            check_add_to_reinterpret_quantize,\n        ),\n        (\"ethos-n.qnn_add_to_depthwise\", qnn_add_pattern(True), check_add_to_depthwise),\n        (\"ethos-n.qnn_add\", qnn_add_pattern(), check_add),\n        (\"ethos-n.qnn_conv2d\", qnn_conv_pattern(), check_conv2d),\n        (\"ethos-n.qnn_conv2d_transpose\", qnn_conv2d_transpose_pattern(), check_conv2d_transpose),\n        (\"ethos-n.qnn_avg_pool2d\", qnn_avg_pool2d_pattern(), check_avg_pool2d),\n        (\"ethos-n.qnn_sigmoid\", qnn_sigmoid_pattern(), check_sigmoid),\n        (\"ethos-n.qnn_fc\", qnn_fc_pattern(), check_fc),\n        (\"ethos-n.qnn_mean\", qnn_mean_pattern(), check_mean),\n        (\"ethos-n.qnn_tanh\", qnn_tanh_pattern(), check_tanh),\n        (\"ethos-n.qnn_leaky_relu\", qnn_leaky_relu_pattern(), check_leaky_relu),\n        (\"ethos-n.qnn_resize\", qnn_resize_pattern(), check_resize),\n        (\"ethos-n.qnn_requantize\", qnn_requantize_pattern(), check_requantize),\n    ]\n\n\n@tvm.ir.register_op_attr(\"nn.max_pool2d\", \"target.ethos-n\")\ndef max_pool2d(expr):\n    \"\"\"Check if a max pool2d is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n\n    return _ethosn.max_pool2d(expr)\n\n\n@tvm.ir.register_op_attr(\"reshape\", \"target.ethos-n\")\ndef reshape(expr):\n    \"\"\"Check if a reshape is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n\n    return _ethosn.reshape(expr)\n\n\n@tvm.ir.register_op_attr(\"qnn.concatenate\", \"target.ethos-n\")\ndef qnn_concatenate(expr):\n    \"\"\"Check if a concatenate is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n    if not _ethosn.concatenate(expr):\n        return False\n\n    # Support library has some unenforced restrictions on qnn params\n    args = expr.args\n    min_range = 1e9\n    max_range = -1e9\n    qnn_params = []\n    for i in range(len(args[1].fields)):\n        scale = args[1].fields[i].data.numpy()\n        zero_point = args[2].fields[i].data.numpy()\n        min_range = min(-1 * zero_point * scale, min_range)\n        max_range = max((255 - zero_point) * scale, max_range)\n        qnn_params.append((scale, zero_point))\n\n    scale = (max_range - min_range) / 255\n    zero_point = int(-min_range / scale)\n    if (scale, zero_point) in qnn_params:\n        return True\n\n    return False\n\n\n@tvm.ir.register_op_attr(\"split\", \"target.ethos-n\")\ndef split(expr):\n    \"\"\"Check if a split is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n    if ethosn_api_version() == LooseVersion(\"3.0.1\"):\n        return False\n    if not _ethosn.split(expr):\n        return False\n\n    return True\n\n\n@tvm.ir.register_op_attr(\"nn.depth_to_space\", \"target.ethos-n\")\ndef depth_to_space(expr):\n    \"\"\"Check if a depth_to_space is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n    if not _ethosn.depth_to_space(expr):\n        return False\n\n    return True\n\n\n@tvm.ir.register_op_attr(\"clip\", \"target.ethos-n\")\ndef clip(expr):\n    \"\"\"Check if a clip is supported by Ethos-N.\"\"\"\n    if not ethosn_available():\n        return False\n    if not _ethosn.relu(expr):\n        return False\n\n    return True\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/ethosu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=ungrouped-imports, import-outside-toplevel\n\"\"\"Arm(R) Ethos(TM)-U NPU supported operators.\"\"\"\nimport functools\nfrom typing import Dict, List, Tuple, Callable, Optional\n\nimport numpy as np  # type: ignore\n\nimport tvm  # type: ignore\nfrom tvm import relay\nfrom tvm.relay.expr import Constant, Call  # type: ignore\nfrom tvm.relay.op.contrib.register import register_pattern_table  # type: ignore\nfrom tvm.relay.dataflow_pattern import wildcard, is_op, is_constant, is_tuple  # type: ignore\nfrom tvm.relay.build_module import bind_params_by_name  # type: ignore\n\ntry:\n    # As ethos-u-vela package is an optional TVM dependency, we want to lazy load it\n    # and check whether it is installed or not.\n    #\n    # In order to show the appropriate error messages when we try to invoke code that\n    # rely on imports from ethos-u-vela, we protect them with the decorator @requires_vela\n    # implemented below.\n    from ethosu.vela import api as vapi  # type: ignore\nexcept ImportError:\n    vapi = None\n\n\ndef requires_vela(func):\n    \"\"\"Decorator to check whether we have the required dependency ethos-u-vela\n    installed as a python package\"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if not vapi:\n            raise ImportError(\n                \"The 'ethos-u-vela' python package is required for the Arm(R) Ethos(TM)-U NPU \"\n                \"backend. Please install the dependency using your Python package manager.\"\n            ) from None\n        return func(*args, **kwargs)\n\n    return wrapper\n\n\nclass TensorParams:\n    \"\"\"\n    This class will parse a tvm Expr along with quantization scale\n    and zero point to populate parameters that are required\n    for the creation of tensors in Vela.\n    \"\"\"\n\n    @requires_vela\n    def __init__(self, tensor, layout=None, scale=None, zero_point=None):\n        self.tensor = tensor\n        if isinstance(tensor, Constant):\n            self.values = tensor.data.asnumpy()\n        else:\n            self.values = None\n        self.dtype = tensor.checked_type.dtype\n        self.shape = [int(i) for i in tensor.checked_type.shape]\n        self.layout = layout\n\n        if scale is not None and zero_point is not None:\n            self.q_params = vapi.NpuQuantization(\n                scale.data.asnumpy().astype(\"float32\"), zero_point.data.asnumpy().astype(self.dtype)\n            )\n        else:\n            # put default values\n            self.q_params = vapi.NpuQuantization(1.0, 0)\n\n\ndef check_strides(strides: List[int], stride_range=None) -> bool:\n    \"\"\"This function checks whether strides are within the limits supported by the NPU\"\"\"\n    if stride_range is None:\n        stride_range = (1, 3)\n    smin, smax = stride_range\n    if not smax >= strides[0] >= smin:\n        return False\n    if not smax >= strides[1] >= smin:\n        return False\n    return True\n\n\ndef check_valid_dtypes(tensor_params: List[TensorParams], supported_dtypes: List[type]) -> bool:\n    \"\"\"This function checks whether dtypes are supported by the NPU\"\"\"\n    for tep in tensor_params:\n        # Check for dtypes\n        if np.dtype(tep.dtype) not in supported_dtypes:\n            return False\n        # Check for shape sizes\n        if any(dimlen > 65536 for dimlen in tep.shape):\n            return False\n    return True\n\n\ndef check_weights(weights: TensorParams, dilation: List[int]):\n    \"\"\"This function checks whether weight tensor is compatible with the NPU\"\"\"\n    from tvm.relay.backend.contrib.ethosu.util import get_dim_value\n\n    dilated_height_range = (1, 64)\n    dilated_hxw_range = (1, 64 * 64)\n    weights_limit = 127 * 65536\n    dilated_width = (weights.shape[get_dim_value(weights.layout, \"W\")] - 1) * dilation[0] + 1\n    dilated_height = (weights.shape[get_dim_value(weights.layout, \"H\")] - 1) * dilation[1] + 1\n    dh_min, dh_max = dilated_height_range\n    if not dh_min <= dilated_height <= dh_max:\n        return False\n    dilated_hxw = dilated_height * dilated_width\n    dhxw_min, dhxw_max = dilated_hxw_range\n    if not dhxw_min <= dilated_hxw <= dhxw_max:\n        return False\n    # A saturation upper bound check for accumulators\n    weights.values = weights.values - weights.q_params.zero_point\n    axis = (\n        get_dim_value(weights.layout, \"H\"),\n        get_dim_value(weights.layout, \"W\"),\n        get_dim_value(weights.layout, \"I\"),\n    )\n    sum_weights = np.amax(np.sum(np.absolute(weights.values), axis=axis))\n    return sum_weights <= weights_limit\n\n\ndef check_bias(bias: TensorParams):\n    \"\"\"This function checks whether the bias values fit in 40 bits\"\"\"\n    if bias and bias.dtype == np.dtype(\"int64\"):\n        valid = all(len(bin(bias_value)[2:]) <= 40 for bias_value in bias.values)\n        return valid\n    return True\n\n\ndef check_batch_size(ifm: TensorParams):\n    \"\"\"This function checks for the number of batches vela currently supports\"\"\"\n    return ifm.shape[0] == 1\n\n\ndef check_dilation(dilation: List[int], dilation_range=None):\n    \"\"\"This function checks whether dilation is within the limits supported by the NPU\"\"\"\n    if dilation_range is None:\n        dilation_range = (1, 2)\n    dmin, dmax = dilation_range\n    if not dmin <= dilation[0] <= dmax:\n        return False\n    if not dmin <= dilation[1] <= dmax:\n        return False\n    return True\n\n\ndef check_padding(padding: List[int], bounds: List[int]):\n    \"\"\"This function checks whether padding is within the limits supported by the NPU\"\"\"\n    if len(padding) != 4 or len(bounds) != 4:\n        return False\n    top, left, bottom, right = padding\n    topb, leftb, bottomb, rightb = bounds\n    return not (top > topb or left > leftb or bottom > bottomb or right > rightb)\n\n\ndef check_pool_shape(pool_shape: tvm.ir.container.Array) -> bool:\n    if len(pool_shape) != 2:\n        return False\n    if pool_shape[1] > 256:\n        return False\n    if pool_shape[0] * pool_shape[1] > 256 * 256:\n        return False\n    return True\n\n\ndef check_dimensions(tensor: TensorParams):\n    \"\"\"This function checks that the tensor has no more than 4 dimensions\"\"\"\n    return len(tensor.shape) <= 4\n\n\nclass QnnConv2DParams:\n    \"\"\"\n    This class will parse a Call to a ethosu.qnn_conv2d composite function\n    and extract quantization information of all the associated tensors.\n    \"\"\"\n\n    composite_name = \"ethos-u.qnn_conv2d\"\n    # The NPU only supports padding upto the numbers as follows\n    padding_bounds = [31, 31, 32, 32]\n    activation_map = {\"clip\": \"CLIP\"}\n\n    @requires_vela\n    def __init__(self, func_body: tvm.relay.Function):\n        from tvm.relay.backend.contrib.ethosu.util import QConv2DArgs  # type: ignore\n        from tvm.relay.backend.contrib.ethosu.util import BiasAddArgs\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        activation = None\n        separate_padding = None\n\n        if str(func_body.op) in self.activation_map.keys():\n            activation = func_body\n            requantize_op = activation.args[0]\n        else:\n            requantize_op = func_body\n        bias_add = requantize_op.args[0]\n        qnn_conv2d = bias_add.args[0]\n        if isinstance(qnn_conv2d.args[0], relay.Call) and str(qnn_conv2d.args[0].op) == \"nn.pad\":\n            separate_padding = qnn_conv2d.args[0]\n        data_layout = qnn_conv2d.attrs.data_layout\n        self.kernel_layout = qnn_conv2d.attrs.kernel_layout\n\n        # We consider the weights & biases as params as it should be a Constant\n        self.weights = TensorParams(\n            qnn_conv2d.args[QConv2DArgs.WEIGHTS.value],\n            self.kernel_layout,\n            qnn_conv2d.args[QConv2DArgs.WEIGHTS_SCALE.value],\n            qnn_conv2d.args[QConv2DArgs.WEIGHTS_ZERO_POINT.value],\n        )\n\n        self.biases = TensorParams(\n            bias_add.args[BiasAddArgs.BIASES.value],\n            data_layout,\n            requantize_op.args[RequantArgs.IFM_SCALE.value],\n            requantize_op.args[RequantArgs.IFM_ZERO_POINT.value],\n        )\n        ifm_tensor = (\n            separate_padding.args[0] if separate_padding else qnn_conv2d.args[QConv2DArgs.IFM.value]\n        )\n        self.ifm = TensorParams(\n            ifm_tensor,\n            data_layout,\n            qnn_conv2d.args[QConv2DArgs.IFM_SCALE.value],\n            qnn_conv2d.args[QConv2DArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            func_body,\n            data_layout,\n            requantize_op.args[RequantArgs.OFM_SCALE.value],\n            requantize_op.args[RequantArgs.OFM_ZERO_POINT.value],\n        )\n        attrs = qnn_conv2d.attrs\n\n        pad_value = int(qnn_conv2d.args[QConv2DArgs.IFM_ZERO_POINT.value].data.asnumpy())\n        self.padding = self.extract_padding(attrs.padding, separate_padding, pad_value)\n\n        self.strides = attrs.strides\n        self.dilation = attrs.dilation\n        self.activation = activation\n        self.channels = attrs.channels\n\n        # If groups are equal to channel, its a depthwise_conv2d\n        self.groups = attrs.groups\n        self.is_depthwise = False\n        channels_axis = {\"HWIO\": 3, \"HWOI\": 2}\n        if self.groups == self.weights.shape[channels_axis[self.kernel_layout]]:\n            self.is_depthwise = True\n\n    @staticmethod\n    def extract_padding(\n        operator_padding: Tuple[int, int, int, int],\n        separate_padding: relay.Call,\n        pad_value: int,\n    ) -> Optional[Tuple[int, int, int, int]]:\n        \"\"\"\n        Convolution operations can sometimes have padding represented as a separate\n        padding operation before the convolution operation itself. Here we can check\n        whether these representations can be combined into a single padding attribute\n        as part of the NPU convolution itself. If the padding specified by the separate\n        nn.pad operation is not supported, None will be returned. This will cause the\n        nn.pad to be offloaded separately.\n        \"\"\"\n        if separate_padding is None:\n            return operator_padding\n        if pad_value != int(separate_padding.args[1].data.asnumpy()):\n            return None\n        pad_width = separate_padding.attrs[\"pad_width\"]\n        if len(pad_width) != 4:\n            return None\n        if list(pad_width[0]) != [0, 0] or list(pad_width[3]) != [0, 0]:\n            return None\n        top, left, bottom, right = operator_padding\n        return [\n            top + pad_width[1][0],\n            left + pad_width[2][0],\n            bottom + pad_width[1][1],\n            right + pad_width[2][1],\n        ]\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        This function checks whether QnnConv2D has compatible attributes with the NPU\n        \"\"\"\n        tensor_params = [self.weights, self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.uint8, np.int8]):\n            return False\n        if not check_weights(self.weights, self.dilation):\n            return False\n        if not check_bias(self.biases):\n            return False\n        if not check_strides(self.strides):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        if not check_dilation(self.dilation):\n            return False\n        if not self.padding or not check_padding(self.padding, self.padding_bounds):\n            return False\n        legal_groups = [1, self.ofm.shape[3]]\n        if self.groups not in legal_groups:\n            return False\n        # This should be a valid QnnDepthwiseConv2DParams, not QnnConv2DParams\n        return not self.is_depthwise\n\n\nclass QnnConv2DTransposeParams:\n    \"\"\"\n    This class will parse a Call to a ethosu.qnn_conv2d_transpose composite\n    function and extract quantization information of all the associated tensors.\n    \"\"\"\n\n    composite_name = \"ethos-u.qnn_conv2d_transpose\"\n    # The NPU only supports padding upto the numbers as follows\n    padding_bounds = [31, 31, 32, 32]\n\n    @requires_vela\n    def __init__(self, func_body: tvm.relay.Function):\n        from tvm.relay.backend.contrib.ethosu.util import QConv2DTransposeArgs  # type: ignore\n        from tvm.relay.backend.contrib.ethosu.util import BiasAddArgs\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        requantize = func_body\n        call = func_body.args[0]\n        if str(call.op) == \"nn.bias_add\":\n            bias_add = call\n            call = call.args[0]\n        else:\n            bias_add = None\n        qnn_conv2d_transpose = call\n\n        data_layout = qnn_conv2d_transpose.attrs.data_layout\n        self.kernel_layout = qnn_conv2d_transpose.attrs.kernel_layout\n\n        self.weights = TensorParams(\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.WEIGHTS.value],\n            self.kernel_layout,\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.WEIGHTS_SCALE.value],\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.WEIGHTS_ZERO_POINT.value],\n        )\n        self.biases = (\n            TensorParams(\n                bias_add.args[BiasAddArgs.BIASES.value],\n                data_layout,\n                requantize.args[RequantArgs.IFM_SCALE.value],\n                requantize.args[RequantArgs.IFM_ZERO_POINT.value],\n            )\n            if bias_add\n            else None\n        )\n        self.ifm = TensorParams(\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.IFM.value],\n            data_layout,\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.IFM_SCALE.value],\n            qnn_conv2d_transpose.args[QConv2DTransposeArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            func_body,\n            data_layout,\n            requantize.args[RequantArgs.OFM_SCALE.value],\n            requantize.args[RequantArgs.OFM_ZERO_POINT.value],\n        )\n\n        attrs = qnn_conv2d_transpose.attrs\n        self.strides = attrs.strides\n        self.dilation = attrs.dilation\n        self.padding = attrs.padding\n        self.channels = attrs.channels\n        self.groups = attrs.groups\n        self.output_padding = attrs.output_padding\n\n        kernel_size_map = {\n            \"IOHW\": self.weights.shape[2:4],\n        }\n        self.kernel_shape = kernel_size_map[str(self.weights.layout)]\n\n        # Different padding is used in the legalization from conv2d_transpose\n        # to conv2d, so we to calculate it here to check that the new size fits\n        # within the bounds of the NPU before offloading.\n        pad_top = int(self.kernel_shape[0]) - 1 - int(self.padding[0])\n        pad_left = int(self.kernel_shape[1]) - 1 - int(self.padding[1])\n        pad_bottom = int(self.kernel_shape[0]) - 1 - int(self.padding[2])\n        pad_right = int(self.kernel_shape[1]) - 1 - int(self.padding[3])\n        if self.strides == [2, 2]:\n            pad_bottom -= 1\n            pad_right -= 1\n        self.legalize_padding = [pad_top, pad_left, pad_bottom, pad_right]\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        This function checks whether QnnConv2D has compatible attributes with the NPU\n        \"\"\"\n\n        def check_compatible_output_size(ifm_shape, ofm_shape, padding, strides, kernel_shape):\n            is_valid_padding = padding == [0, 0, 0, 0]\n            if is_valid_padding:\n                expected_height = ifm_shape[1] * strides[0] + (kernel_shape[0] - strides[0])\n                expected_width = ifm_shape[2] * strides[1] + (kernel_shape[1] - strides[1])\n            else:\n                expected_height = ifm_shape[1] * strides[0]\n                expected_width = ifm_shape[2] * strides[1]\n            return ofm_shape[1] == expected_height and ofm_shape[2] == expected_width\n\n        tensor_params = [self.weights, self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8]):\n            return False\n        if not check_weights(self.weights, self.dilation):\n            return False\n        if self.biases and not check_bias(self.biases):\n            return False\n        if not check_strides(self.strides, stride_range=(2, 2)):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        if not check_dilation(self.dilation, dilation_range=(1, 1)):\n            return False\n        if not check_compatible_output_size(\n            self.ifm.shape,\n            self.ofm.shape,\n            [int(x) for x in self.padding],\n            self.strides,\n            self.kernel_shape,\n        ):\n            return False\n        if not check_padding(self.legalize_padding, self.padding_bounds):\n            return False\n        if self.kernel_shape[0] - 2 - int(self.padding[2]) < 0:\n            return False\n        if self.kernel_shape[1] - 2 - int(self.padding[3]) < 0:\n            return False\n        if self.groups != 1:\n            return False\n        if list(self.output_padding) != [0, 0]:\n            return False\n        return True\n\n\nclass QnnDepthwiseConv2DParams(QnnConv2DParams):\n    \"\"\"\n    This class will parse a call to a ethosu.depthwise_conv2d composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.depthwise_conv2d\"\n    # The hardware only supports padding upto the numbers as follows\n    padding_bounds = [31, 31, 32, 32]\n\n    def __init__(self, func_body: tvm.relay.expr.Call):\n        QnnConv2DParams.__init__(self, func_body)\n\n    def is_valid(self):\n        \"\"\"\n        Checks whether QnnDepthwiseConv2D + activation function has compatible attributes with HW\n        \"\"\"\n        tensor_params = [self.weights, self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.uint8, np.int8]):\n            return False\n        if not check_weights(self.weights, self.dilation):\n            return False\n        if not check_bias(self.biases):\n            return False\n        if not check_strides(self.strides):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        if not check_dilation(self.dilation):\n            return False\n        if not self.padding or not check_padding(self.padding, self.padding_bounds):\n            return False\n        if self.weights.layout != \"HWOI\":\n            return False\n        # only depth multiplier of size 1 is supported\n        if self.weights.shape[3] != 1:\n            return False\n        if not self.is_depthwise:\n            return False\n        return True\n\n\ndef qnn_conv2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.conv2D with optional fused RELU activation.\n    \"\"\"\n    optional_pad = is_op(\"nn.pad\")(wildcard(), is_constant())\n    qnn_conv2d = is_op(\"qnn.conv2d\")(\n        optional_pad | wildcard(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n    ).has_attr({\"kernel_layout\": \"HWIO\"})\n    bias_add = is_op(\"nn.bias_add\")(qnn_conv2d, is_constant())\n    req = is_op(\"qnn.requantize\")(\n        bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    clip_or_req = req.optional(is_op(\"clip\"))\n    return clip_or_req\n\n\ndef qnn_depthwise_conv2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for depthwise qnn.conv2D with optional fused RELU activation.\n    \"\"\"\n    optional_pad = is_op(\"nn.pad\")(wildcard(), is_constant())\n    qnn_conv2d = is_op(\"qnn.conv2d\")(\n        optional_pad | wildcard(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n    ).has_attr({\"kernel_layout\": \"HWOI\"})\n    bias_add = is_op(\"nn.bias_add\")(qnn_conv2d, is_constant())\n    req = is_op(\"qnn.requantize\")(\n        bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    clip_or_req = req.optional(is_op(\"clip\"))\n    return clip_or_req\n\n\ndef qnn_conv2d_transpose_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.conv2d_transpose.\n    \"\"\"\n    qnn_conv2d_transpose = is_op(\"qnn.conv2d_transpose\")(\n        wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n    ).has_attr({\"kernel_layout\": \"IOHW\"})\n    optional_bias_add = (\n        is_op(\"nn.bias_add\")(qnn_conv2d_transpose, is_constant()) | qnn_conv2d_transpose\n    )\n    req = is_op(\"qnn.requantize\")(\n        optional_bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    return req\n\n\nclass MaxPool2DParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.maxpool2d composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.maxpool2d\"\n    # The hardware only supports padding upto the numbers as follows\n    padding_bounds = [127, 127, 128, 128]\n\n    def __init__(self, func_body: Call):\n        clip = None\n        if str(func_body.op) == \"clip\":\n            clip = func_body\n            pool_op = clip.args[0]\n        else:\n            pool_op = func_body\n\n        attrs = pool_op.attrs\n        self.ifm = TensorParams(pool_op.args[0], attrs.layout)\n        self.ofm = TensorParams(pool_op, attrs.layout)\n        self.pool_shape = attrs.pool_size\n        self.strides = attrs.strides\n        self.padding = attrs.padding\n        self.activation = clip\n        self.pooling_type = \"MAX\"\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether MaxPool2D has compatible attributes with the NPU\n        \"\"\"\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.uint8, np.int8]):\n            return False\n        if self.ifm.dtype != self.ofm.dtype:\n            return False\n        if not check_strides(self.strides):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        if not check_padding(self.padding, self.padding_bounds):\n            return False\n        if not check_pool_shape(self.pool_shape):\n            return False\n        return True\n\n\ndef qnn_maxpool2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for nn.max_pool2d with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"nn.max_pool2d\")(wildcard())\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass AvgPool2DParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.avgpool2d composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.avgpool2d\"\n    # The hardware only supports padding upto the numbers as follows\n    padding_bounds = [3, 3, 4, 4]\n\n    def __init__(self, func_body: Call):\n        clip = None\n        if str(func_body.op) == \"clip\":\n            clip = func_body\n            cast2 = clip.args[0]\n        else:\n            cast2 = func_body\n\n        avgpool = cast2.args[0]\n        cast1 = avgpool.args[0]\n\n        attrs = avgpool.attrs\n        self.ifm = TensorParams(cast1.args[0], attrs.layout)\n        self.ofm = TensorParams(cast2, attrs.layout)\n        self.pool_shape = attrs.pool_size\n        self.strides = attrs.strides\n        self.padding = attrs.padding\n        self.count_include_pad = attrs.count_include_pad\n        self.activation = clip\n        self.pooling_type = \"AVG\"\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether AvgPool2D has compatible attributes with the NPU\n        \"\"\"\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.uint8, np.int8]):\n            return False\n        if self.ifm.dtype != self.ofm.dtype:\n            return False\n        if not check_strides(self.strides):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        if self.count_include_pad:\n            return False\n        if not check_padding(self.padding, self.padding_bounds):\n            return False\n        if not check_pool_shape(self.pool_shape):\n            return False\n        # Averge pool with padding only supports 1 <= pool_shape <= 8\n        if list(self.padding) != [0, 0, 0, 0] and (\n            self.pool_shape[0] > 8 or self.pool_shape[1] > 8\n        ):\n            return False\n        return True\n\n\ndef qnn_avgpool2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for nn.avg_pool2d with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"cast\")(wildcard())\n    pattern = is_op(\"nn.avg_pool2d\")(pattern)\n    pattern = is_op(\"cast\")(pattern)\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass BinaryElementwiseParams:\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise composite function\n    and extract the parameter information.\n    \"\"\"\n\n    def __init__(self, func_body: Call, operator_type: str, is_quantized_operation: bool):\n        from tvm.relay.backend.contrib.ethosu.util import BinaryElementwiseArgs\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        current_call = func_body\n        clip = None\n        requantize = None\n\n        if is_quantized_operation:\n            if str(current_call.op) == \"clip\":\n                clip = current_call\n                current_call = clip.args[0]\n        else:\n            if str(current_call.op) == \"qnn.requantize\":\n                requantize = current_call\n                clip = current_call.args[0]\n                current_call = clip.args[0]\n        binary_op = current_call\n\n        layout = \"NHWC\"\n\n        if is_quantized_operation:\n            self.ifm = TensorParams(\n                binary_op.args[BinaryElementwiseArgs.IFM.value],\n                layout,\n                binary_op.args[BinaryElementwiseArgs.IFM_SCALE.value],\n                binary_op.args[BinaryElementwiseArgs.IFM_ZERO_POINT.value],\n            )\n            self.ifm2 = TensorParams(\n                binary_op.args[BinaryElementwiseArgs.IFM2.value],\n                layout,\n                binary_op.args[BinaryElementwiseArgs.IFM2_SCALE.value],\n                binary_op.args[BinaryElementwiseArgs.IFM2_ZERO_POINT.value],\n            )\n            self.ofm = TensorParams(\n                binary_op,\n                layout,\n                binary_op.args[BinaryElementwiseArgs.OFM_SCALE.value],\n                binary_op.args[BinaryElementwiseArgs.OFM_ZERO_POINT.value],\n            )\n        else:\n            self.ifm = TensorParams(\n                binary_op.args[BinaryElementwiseArgs.IFM.value],\n                layout,\n                requantize.args[RequantArgs.IFM_SCALE.value] if requantize else None,\n                requantize.args[RequantArgs.IFM_ZERO_POINT.value] if requantize else None,\n            )\n            self.ifm2 = TensorParams(\n                binary_op.args[BinaryElementwiseArgs.IFM2.value],\n                layout,\n                requantize.args[RequantArgs.IFM_SCALE.value] if requantize else None,\n                requantize.args[RequantArgs.IFM_ZERO_POINT.value] if requantize else None,\n            )\n            self.ofm = TensorParams(\n                func_body,\n                layout,\n                requantize.args[RequantArgs.OFM_SCALE.value] if requantize else None,\n                requantize.args[RequantArgs.OFM_ZERO_POINT.value] if requantize else None,\n            )\n        self.activation = clip\n        self.operator_type = operator_type\n\n        def can_broadcast(ifm, ifm2):\n            if len(ifm.shape) < len(ifm2.shape):\n                return False\n            for m, n in zip(ifm.shape[::-1], ifm2.shape[::-1]):\n                if m != n and m == 1:\n                    return False\n            return True\n\n        if can_broadcast(self.ifm, self.ifm2):\n            self.reversed_operands = False\n            self.valid_broadcast = True\n        elif can_broadcast(self.ifm2, self.ifm):\n            self.reversed_operands = True\n            self.ifm, self.ifm2 = self.ifm2, self.ifm\n            self.valid_broadcast = True\n        else:\n            self.valid_broadcast = False\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether BinaryElementwise has compatible attributes with the NPU\n        \"\"\"\n        if np.dtype(self.ofm) == np.int32 and self.activation is not None:\n            return False\n        # Due to identity operator requiring ofm != int32 for now\n        if np.dtype(self.ofm) == np.int32 and len(self.ofm.shape) < 4:\n            return False\n        if len(self.ifm.shape) > 4 or len(self.ifm2.shape) > 4:\n            return False\n        if len(self.ifm.shape) == 4 and self.ifm.shape[0] != 1:\n            return False\n        if len(self.ifm2.shape) == 4 and self.ifm2.shape[0] != 1:\n            return False\n        if not self.valid_broadcast:\n            return False\n        return True\n\n\nclass AddParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Add composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.add\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"ADD\", True)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Add has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if not check_valid_dtypes(\n            [self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.uint8, np.int8, np.int32]\n        ):\n            return False\n        return True\n\n\ndef qnn_add_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.add with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"qnn.add\")(\n        wildcard(),\n        wildcard(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n    )\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass SubParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Sub composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.sub\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"SUB\", True)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Sub has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if not check_valid_dtypes(\n            [self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.uint8, np.int8, np.int32]\n        ):\n            return False\n        return True\n\n\ndef qnn_subtract_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.subtract with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"qnn.subtract\")(\n        wildcard(),\n        wildcard(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n    )\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass MulParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Mul composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.mul\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"MUL\", True)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Mul has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if not check_valid_dtypes(\n            [self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.uint8, np.int8, np.int32]\n        ):\n            return False\n        return True\n\n\ndef qnn_mul_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.mul with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"qnn.mul\")(\n        wildcard(),\n        wildcard(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n        is_constant(),\n    )\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass MinParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Min composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.min\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"MIN\", False)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Min has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if self.ifm.dtype != self.ifm2.dtype:\n            return False\n        if not check_valid_dtypes(\n            [self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.uint8, np.int8]\n        ):\n            return False\n        return True\n\n\ndef minimum_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for minimum with optional fused RELU activation.\n    \"\"\"\n    minimum = is_op(\"minimum\")(wildcard(), wildcard())\n    optional_min_clip = is_op(\"clip\")(minimum)\n    optional_min_clip = is_op(\"qnn.requantize\")(\n        optional_min_clip, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    return minimum | optional_min_clip\n\n\nclass MaxParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Max composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.max\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"MAX\", False)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Max has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if self.ifm.dtype != self.ifm2.dtype:\n            return False\n        if not check_valid_dtypes(\n            [self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.uint8, np.int8]\n        ):\n            return False\n        return True\n\n\ndef maximum_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for maximum with optional fused RELU activation.\n    \"\"\"\n    maximum = is_op(\"maximum\")(wildcard(), wildcard())\n    optional_max_clip = is_op(\"clip\")(maximum)\n    optional_max_clip = is_op(\"qnn.requantize\")(\n        optional_max_clip, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    return maximum | optional_max_clip\n\n\nclass ShlParams(BinaryElementwiseParams):\n    \"\"\"\n    This class will parse a call to a ethosu.binary_elementwise Shl composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.shl\"\n\n    def __init__(self, func_body: Call):\n        BinaryElementwiseParams.__init__(self, func_body, \"SHL\", False)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether Shl has compatible attributes with the NPU\n        \"\"\"\n        if not super().is_valid():\n            return False\n        if not check_valid_dtypes([self.ifm, self.ifm2, self.ofm], supported_dtypes=[np.int32]):\n            return False\n        return True\n\n\ndef shl_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for left_shift with optional fused RELU activation.\n    \"\"\"\n    pattern = is_op(\"left_shift\")(wildcard(), wildcard())\n    pattern = pattern.optional(is_op(\"clip\"))\n    return pattern\n\n\nclass ReshapeParams:\n    \"\"\"\n    This class will parse a call to a ethosu.reshape composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.reshape\"\n\n    def __init__(self, func_body: Call):\n        self.new_shape = func_body.attrs.newshape\n        self.ifm = TensorParams(func_body.args[0])\n        self.ofm = TensorParams(func_body)\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether reshape has compatible attributes with the NPU\n        \"\"\"\n        if not check_dimensions(self.ifm) or not check_dimensions(self.ofm):\n            return False\n        if not check_valid_dtypes([self.ifm, self.ofm], supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\ndef reshape_pattern():\n    \"\"\"Create pattern for reshape\"\"\"\n    pattern = is_op(\"reshape\")(wildcard())\n    return pattern\n\n\nclass StridedSliceParams:\n    \"\"\"\n    This class will parse a call to a ethosu.strided_slice composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.strided_slice\"\n\n    def __init__(self, func_body: Call):\n        self.ifm = TensorParams(func_body.args[0])\n        self.ofm = TensorParams(func_body)\n\n        attrs = func_body.attrs\n        # The indices where we begin the slice\n        self.begin = attrs.begin\n        # The indices where we end the slice\n        self.end = attrs.end\n        self.strides = attrs.strides\n        self.axes = attrs.axes\n        self.slice_mode = attrs.slice_mode\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether reshape has compatible attributes with the NPU\n        \"\"\"\n        if not check_dimensions(self.ifm) or not check_dimensions(self.ofm):\n            return False\n        if not check_valid_dtypes([self.ifm, self.ofm], supported_dtypes=[np.int8]):\n            return False\n        if len(self.begin) != len(self.end):\n            return False\n\n        for begin_idx, end_idx in zip(self.begin, self.end):\n            if begin_idx > end_idx:\n                return False\n\n        # Only strides of 1 are supported\n        if self.strides:\n            if not all([i == 1 for i in self.strides]):\n                return False\n        return True\n\n\ndef strided_slice_pattern():\n    \"\"\"Create pattern for strided_slice\"\"\"\n    pattern = is_op(\"strided_slice\")(wildcard())\n    return pattern\n\n\nclass AbsParams:\n    \"\"\"\n    This class will parse a call to a ethosu.unary_elementwise Abs composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.abs\"\n\n    def __init__(self, func_body: Call):\n        from tvm.relay.backend.contrib.ethosu.util import QuantizeArgs\n        from tvm.relay.backend.contrib.ethosu.util import DequantizeArgs\n\n        quantize = func_body\n        abs_op = quantize.args[0]\n        dequantize = abs_op.args[0]\n\n        layout = \"NHWC\"\n\n        self.ifm = TensorParams(\n            dequantize.args[DequantizeArgs.IFM.value],\n            layout,\n            dequantize.args[DequantizeArgs.IFM_SCALE.value],\n            dequantize.args[DequantizeArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            quantize,\n            layout,\n            quantize.args[QuantizeArgs.OFM_SCALE.value],\n            quantize.args[QuantizeArgs.OFM_ZERO_POINT.value],\n        )\n\n        self.operator_type = \"ABS\"\n        self.activation = None\n\n    def is_valid(self):\n        \"\"\"Checks whether Abs has compatible attributes with HW\"\"\"\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8, np.uint8]):\n            return False\n        if self.ifm.dtype != self.ofm.dtype:\n            return False\n        if not check_dimensions(self.ifm):\n            return False\n        if len(self.ifm.shape) == 4 and self.ifm.shape[0] != 1:\n            return False\n        if self.ifm.shape != self.ofm.shape:\n            return False\n        return True\n\n\ndef abs_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"Create pattern for abs\"\"\"\n    pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    pattern = is_op(\"abs\")(pattern)\n    pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n    return pattern\n\n\nclass LutActivationParams:\n    \"\"\"\n    A parent class for LUT based activation functions that extract the input and\n    output tensors and check whether they are valid.\n    \"\"\"\n\n    def __init__(self, func_body: Call):\n        from tvm.relay.backend.contrib.ethosu.util import QuantizeArgs\n        from tvm.relay.backend.contrib.ethosu.util import DequantizeArgs\n\n        layout = \"NHWC\"\n\n        quantize = func_body\n        activation = quantize.args[0]\n        dequantize = activation.args[0]\n        in_var = dequantize.args[0]\n\n        self.ifm = TensorParams(\n            in_var,\n            layout=layout,\n            scale=dequantize.args[DequantizeArgs.IFM_SCALE.value],\n            zero_point=dequantize.args[DequantizeArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            quantize,\n            layout=layout,\n            scale=quantize.args[QuantizeArgs.OFM_SCALE.value],\n            zero_point=quantize.args[QuantizeArgs.OFM_ZERO_POINT.value],\n        )\n\n    def is_valid(self):\n        \"\"\"\n        This function checks whether activation has compatible attributes with the NPU\n        \"\"\"\n        if not check_valid_dtypes([self.ifm, self.ofm], supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\nclass TanhParams(LutActivationParams):\n\n    composite_name = \"ethos-u.tanh\"\n\n\ndef tanh_pattern():\n    \"\"\"Create pattern for tanh\"\"\"\n    dequant = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    tanh = is_op(\"tanh\")(dequant)\n    quant = is_op(\"qnn.quantize\")(tanh, is_constant(), is_constant())\n    return quant\n\n\nclass SigmoidParams(LutActivationParams):\n    \"\"\"\n    This class will parse a call to a ethos-u.sigmoid composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.sigmoid\"\n\n\ndef sigmoid_pattern():\n    \"\"\"Create pattern for sigmoid\"\"\"\n    dequant = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    sigmoid = is_op(\"sigmoid\")(dequant)\n    quant = is_op(\"qnn.quantize\")(sigmoid, is_constant(), is_constant())\n    return quant\n\n\nclass LeakyReLUParams(LutActivationParams):\n    \"\"\"\n    This class will parse a call to ethos-u.leaky_relu composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.leaky_relu\"\n\n    def __init__(self, func_body: Call):\n        super().__init__(func_body)\n        self.alpha = func_body.args[0].attrs.alpha\n\n\ndef leaky_relu_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for leaky relu.\n    \"\"\"\n    dequantize = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    leaky_relu = is_op(\"nn.leaky_relu\")(dequantize)\n    return is_op(\"qnn.quantize\")(leaky_relu, is_constant(), is_constant())\n\n\nclass MeanParams:\n    \"\"\"\n    This class will parse a call to ethosu.mean composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.mean\"\n\n    def __init__(self, func_body: Call):\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        requantize = func_body\n        mean_op = requantize.args[0]\n        attrs = mean_op.attrs\n        cast = mean_op.args[0]\n\n        layout = \"NHWC\"\n        self.ifm = TensorParams(\n            cast.args[0],\n            layout,\n            requantize.args[RequantArgs.IFM_SCALE.value],\n            requantize.args[RequantArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            requantize,\n            layout,\n            requantize.args[RequantArgs.OFM_SCALE.value],\n            requantize.args[RequantArgs.OFM_ZERO_POINT.value],\n        )\n\n        ifm_shape = self.ifm.shape\n        self.height = ifm_shape[0] if len(ifm_shape) in (2, 3) else ifm_shape[1]\n        self.width = ifm_shape[1] if len(ifm_shape) in (2, 3) else ifm_shape[2]\n        self.keepdims = attrs.keepdims\n\n        self.axis = list(sorted(attrs.axis))\n        if attrs.exclude:\n            self.axis = [i for i in range(len(self.ifm.shape)) if i not in self.axis]\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        Checks whether Mean has compatible attributes with HW.\n        \"\"\"\n\n        def check_axis(num_dims, axis):\n            if num_dims in (2, 3):\n                return axis in ([0], [1], [0, 1])\n            return axis in ([1], [2], [1, 2])\n\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8]):\n            return False\n        if self.ifm.dtype != self.ofm.dtype:\n            return False\n        if not len(self.ifm.shape) in [2, 3, 4]:\n            return False\n        if not check_axis(len(self.ifm.shape), self.axis):\n            return False\n\n        # MEAN has further restrictions on the input size, depending on legalization method.\n        input_size = self.height * self.width\n        if input_size > 65536:\n            return False\n        if (\n            self.ifm.q_params.scale_f32 != self.ofm.q_params.scale_f32\n            or self.ifm.q_params.zero_point != self.ofm.q_params.zero_point\n        ) and input_size > 4096:\n            return False\n        if self.axis == [1, 2] and self.keepdims and self.ifm.dtype == \"int8\" and input_size > 256:\n            return False\n        # Large kernel height reshape only when axis is [1, 2]\n        if self.axis != [1, 2] and self.height > 64:\n            return False\n        return True\n\n\ndef mean_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for mean.\n    \"\"\"\n    pattern = is_op(\"cast\")(wildcard())\n    pattern = is_op(\"mean\")(pattern)\n    pattern = is_op(\"qnn.requantize\")(\n        pattern, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    return pattern\n\n\nclass ConcatParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.concat composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.concat\"\n\n    def __init__(self, func_body):\n        self.concat = func_body\n        self.is_qnn_variant = self.concat.op.name == \"qnn.concatenate\"\n        self.input_tensors = [TensorParams(tensor) for tensor in list(func_body.args[0])]\n        self.axis = func_body.attrs.axis\n\n        if self.is_qnn_variant:\n            self.input_scales = [s.data.asnumpy() for s in list(func_body.args[1])]\n            self.input_zero_points = [zp.data.asnumpy() for zp in list(func_body.args[2])]\n\n    def is_valid(self):\n        \"\"\"Checks whether Concatenate has compatible attributes with the hardware\"\"\"\n        if not check_valid_dtypes(self.input_tensors, supported_dtypes=[np.int8]):\n            return False\n        # Check that the scales and zero points of input tensors are the same\n        if self.is_qnn_variant and not all(self.input_scales == self.input_scales[0]):\n            return False\n        if self.is_qnn_variant and not all(self.input_zero_points == self.input_zero_points[0]):\n            return False\n\n        input_dim = len(self.input_tensors[0].shape)\n        for tensor in self.input_tensors:\n            if len(tensor.shape) != input_dim:\n                return False\n\n        if self.axis is None:\n            return False\n        if self.axis < 0:\n            return False\n        if self.axis >= input_dim:\n            return False\n\n        output_shape = self.concat.checked_type.shape\n        if len(output_shape) != input_dim:\n            return False\n        if len(output_shape) > 3 and output_shape[0] != 1:\n            return False\n        return True\n\n\ndef concat_pattern():\n    \"\"\"Create pattern for concat\"\"\"\n    tensors = is_tuple(None)\n    scales = is_tuple(None)\n    zero_points = is_tuple(None)\n    qnn_concat = is_op(\"qnn.concatenate\")(\n        tensors, scales, zero_points, is_constant(), is_constant()\n    )\n    concat = is_op(\"concatenate\")(tensors)\n    return concat | qnn_concat\n\n\nclass SplitParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.split composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.split\"\n\n    def __init__(self, func_body):\n        self.split = func_body\n        self.input = TensorParams(func_body.args[0])\n        self.axis = func_body.attrs.axis\n        self.indices_or_sections = self.convert_indices_or_sections(\n            func_body.attrs.indices_or_sections\n        )\n\n    def convert_indices_or_sections(self, indices_or_sections):\n        # split_v\n        if isinstance(indices_or_sections, tvm.ir.container.Array):\n            values = [i.value for i in indices_or_sections]\n        # split\n        else:\n            values = indices_or_sections.value\n        return values\n\n    def is_valid(self):\n        \"\"\"Checks whether split has compatible attributes with the hardware\"\"\"\n        if not check_valid_dtypes([self.input], supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\ndef split_pattern():\n    \"Create the pattern for split\"\n    split = is_op(\"split\")(wildcard())\n    return split\n\n\nclass RequantizeParams:\n    \"\"\"\n    This class will parse a call to ethos-u.requantize composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.requantize\"\n\n    def __init__(self, func_body: Call):\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        layout = \"NHWC\"\n        in_var = func_body.args[0]\n        requantize = func_body\n\n        self.ifm = TensorParams(\n            in_var,\n            layout=layout,\n            scale=requantize.args[RequantArgs.IFM_SCALE.value],\n            zero_point=requantize.args[RequantArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            requantize,\n            layout=layout,\n            scale=requantize.args[RequantArgs.OFM_SCALE.value],\n            zero_point=requantize.args[RequantArgs.OFM_ZERO_POINT.value],\n        )\n\n        attrs = requantize.attrs\n        self.out_dtype = attrs.out_dtype\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        Checks whether qnn.requantize has compatible attributes with HW.\n        \"\"\"\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8]):\n            return False\n        if not check_dimensions(self.ifm) or not check_dimensions(self.ofm):\n            return False\n        if self.out_dtype and self.out_dtype != \"int8\":\n            return False\n        return True\n\n\ndef requantize_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for qnn.requantize.\n    \"\"\"\n    return is_op(\"qnn.requantize\")(\n        wildcard(), is_constant(), is_constant(), is_constant(), is_constant()\n    )\n\n\nclass Resize2dParams:\n    \"\"\"\n    This class will parse a call to ethos-u.resize2d composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.resize2d\"\n\n    def __init__(self, func_body: Call):\n        layout = \"NHWC\"\n\n        resize_2d = func_body\n        in_var = func_body.args[0]\n        if (\n            isinstance(resize_2d, tvm.relay.expr.Call)\n            and isinstance(resize_2d.op, tvm.ir.Op)\n            and resize_2d.op.name == \"qnn.quantize\"\n        ):\n            resize_2d = resize_2d.args[0]\n            in_var = in_var.args[0].args[0]\n        out_var = func_body\n\n        self.ifm = TensorParams(in_var, layout=layout)\n        self.ofm = TensorParams(out_var, layout=layout)\n\n        attrs = resize_2d.attrs\n        self.size = attrs.size\n        self.method = attrs.method\n        self.roi = attrs.roi\n        self.coordinate_transformation_mode = attrs.coordinate_transformation_mode\n        self.rounding_method = attrs.rounding_method\n        self.out_dtype = attrs.out_dtype\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        Checks whether image.resize2d has compatible attributes with HW.\n        \"\"\"\n\n        def check_compatible_size(mode, method, upscale_size, ifm_size):\n            \"\"\"Checking the provided upscale_size is compatible with the NPU. The NPU only\n            supports upsampling when the upsampling size is 2 * input_size, or when there is\n            no upsampling to be done, so check that this is the case. In the special case of\n            resize_bilinear with align_corners=True, the NPU only supports an upsampling\n            size of 2 * input_size - 1.\"\"\"\n            delta = 1 if mode == \"align_corners\" and method == \"linear\" else 0\n            upscale_size = np.array(upscale_size)\n            ifm_size = np.array(ifm_size)\n            ifm_upscaled = ifm_size * 2 - delta\n            return (ifm_upscaled == upscale_size).all() or (ifm_size == upscale_size).all()\n\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8]):\n            return False\n        if len(self.ifm.shape) != 4 or len(self.ofm.shape) != 4:\n            return False\n        if list(float(x) for x in self.roi) != [0.0] * 4:\n            return False\n        if self.method not in (\"nearest_neighbor\", \"linear\"):\n            return False\n        if self.coordinate_transformation_mode not in (\"asymmetric\", \"align_corners\"):\n            return False\n        if not check_compatible_size(\n            self.coordinate_transformation_mode,\n            self.method,\n            self.size,\n            self.ifm.shape[1:3],\n        ):\n            return False\n        if self.rounding_method != \"\":\n            return False\n        if self.out_dtype and self.out_dtype != \"int8\":\n            return False\n        return True\n\n\ndef resize2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern:\n    \"\"\"\n    This function creates the pattern for image.resize2d.\n    \"\"\"\n    dequant = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    resize_2d = is_op(\"image.resize2d\")(dequant).has_attr({\"method\": \"linear\"})\n    quant = is_op(\"qnn.quantize\")(resize_2d, is_constant(), is_constant())\n    return quant | is_op(\"image.resize2d\")(wildcard()).has_attr({\"method\": \"nearest_neighbor\"})\n\n\nclass ExpandDimsParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.expand_dims composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.expand_dims\"\n\n    def __init__(self, func_body):\n        self.expand_dims = func_body\n        self.input = TensorParams(func_body.args[0])\n        self.output = TensorParams(func_body)\n\n    def is_valid(self):\n        \"\"\"Checks whether expand_dims has compatible attributes with the hardware.\"\"\"\n        if not check_dimensions(self.input) or not check_dimensions(self.output):\n            return False\n        if not check_valid_dtypes([self.input, self.output], supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\ndef expand_dims_pattern():\n    \"\"\"Create the pattern for expand_dims.\"\"\"\n    return is_op(\"expand_dims\")(wildcard())\n\n\nclass SqueezeParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.squeeze composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.squeeze\"\n\n    def __init__(self, func_body):\n        self.squeeze = func_body\n        self.input = TensorParams(func_body.args[0])\n        self.output = TensorParams(func_body)\n\n    def is_valid(self):\n        \"\"\"Checks whether squeeze has compatible attributes with the hardware.\"\"\"\n        if not check_dimensions(self.output):\n            return False\n        if not check_valid_dtypes([self.input, self.output], supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\ndef squeeze_pattern():\n    \"\"\"Create the pattern for squeeze.\"\"\"\n    return is_op(\"squeeze\")(wildcard())\n\n\nclass FullyConnectedParams:\n    \"\"\"\n    This class will parse a call to an ethos-u.fully_connected composite\n    function and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.fully_connected\"\n\n    @requires_vela\n    def __init__(self, func_body):\n        from tvm.relay.backend.contrib.ethosu.util import QDenseArgs  # type: ignore\n        from tvm.relay.backend.contrib.ethosu.util import BiasAddArgs\n        from tvm.relay.backend.contrib.ethosu.util import RequantArgs\n\n        self.activation = None\n        if str(func_body.op) == \"clip\":\n            self.activation = func_body\n            requantize_op = self.activation.args[0]\n        else:\n            requantize_op = func_body\n\n        call = requantize_op.args[0]\n        if str(requantize_op.args[0].op) == \"nn.bias_add\":\n            bias_add = call\n            qnn_dense = call.args[0]\n        else:\n            bias_add = None\n            qnn_dense = call\n\n        # weights & biases are params as they should be constant\n        self.weights = TensorParams(\n            qnn_dense.args[QDenseArgs.WEIGHTS.value],\n            None,\n            qnn_dense.args[QDenseArgs.WEIGHTS_SCALE.value],\n            qnn_dense.args[QDenseArgs.WEIGHTS_ZERO_POINT.value],\n        )\n        self.biases = (\n            TensorParams(\n                bias_add.args[BiasAddArgs.BIASES.value],\n                None,\n                requantize_op.args[RequantArgs.IFM_SCALE.value],\n                requantize_op.args[RequantArgs.IFM_ZERO_POINT.value],\n            )\n            if bias_add\n            else None\n        )\n        self.ifm = TensorParams(\n            qnn_dense.args[QDenseArgs.IFM.value],\n            None,\n            qnn_dense.args[QDenseArgs.IFM_SCALE.value],\n            qnn_dense.args[QDenseArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            func_body,\n            None,\n            requantize_op.args[RequantArgs.OFM_SCALE.value],\n            requantize_op.args[RequantArgs.OFM_ZERO_POINT.value],\n        )\n\n    def is_valid(self) -> bool:\n        \"\"\"\n        Checks whether Fully Connected has compatible attributes with HW\n        \"\"\"\n\n        def check_weights_fc(weights):\n            \"\"\"Checks whether weight tensor is compatible with HW\"\"\"\n            weights_limit = 127 * 65536\n            # A saturation upper bound check for accumulators\n            weights.values = weights.values - weights.q_params.zero_point\n            axis = 1\n            sum_weights = np.amax(np.sum(np.absolute(weights.values), axis=axis))\n            if not sum_weights <= weights_limit:\n                return False\n            return True\n\n        if not check_valid_dtypes([self.ifm, self.ofm], supported_dtypes=[np.int8]):\n            return False\n        if not check_weights_fc(self.weights):\n            return False\n        if not check_bias(self.biases):\n            return False\n        if not check_batch_size(self.ifm):\n            return False\n        # Check input shape\n        if not len(self.ifm.shape) == 2:\n            return False\n        # Check output shape\n        if not len(self.ofm.shape) == 2:\n            return False\n        return True\n\n\ndef qnn_fc_pattern():\n    dense = is_op(\"qnn.dense\")(\n        wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    optional_bias_add = is_op(\"nn.bias_add\")(dense, is_constant())\n    req = is_op(\"qnn.requantize\")(\n        dense | optional_bias_add, is_constant(), is_constant(), is_constant(), is_constant()\n    )\n    optional_clip = req.optional(is_op(\"clip\"))\n    return optional_clip\n\n\nclass HardSwishParams:\n    \"\"\"\n    This class will parse a call to a ethos-u.hard_swish composite function\n    and extract the parameter information.\n    \"\"\"\n\n    composite_name = \"ethos-u.hard_swish\"\n\n    def __init__(self, func_body):\n        from tvm.relay.backend.contrib.ethosu.util import QuantizeArgs\n        from tvm.relay.backend.contrib.ethosu.util import DequantizeArgs\n\n        quantize = func_body\n        divide = quantize.args[0]\n        multiply = divide.args[0]\n        clip = multiply.args[1]\n        add = clip.args[0]\n        dequantize = add.args[0]\n\n        self.ifm = TensorParams(\n            dequantize.args[0],\n            scale=dequantize.args[DequantizeArgs.IFM_SCALE.value],\n            zero_point=dequantize.args[DequantizeArgs.IFM_ZERO_POINT.value],\n        )\n        self.ofm = TensorParams(\n            quantize,\n            scale=quantize.args[QuantizeArgs.OFM_SCALE.value],\n            zero_point=quantize.args[QuantizeArgs.OFM_ZERO_POINT.value],\n        )\n\n    def is_valid(self):\n        tensor_params = [self.ifm, self.ofm]\n        if not check_valid_dtypes(tensor_params, supported_dtypes=[np.int8]):\n            return False\n        return True\n\n\ndef hard_swish_pattern():\n    \"\"\"Create the pattern for hard swish.\"\"\"\n    dequantize = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n    add = is_op(\"add\")(dequantize, is_constant())\n    clip = is_op(\"clip\")(add)\n    multiply = is_op(\"multiply\")(dequantize, clip)\n    divide = is_op(\"divide\")(multiply, is_constant())\n    quantize = is_op(\"qnn.quantize\")(divide, is_constant(), is_constant())\n    return quantize\n\n\n@register_pattern_table(\"ethos-u\")\ndef pattern_table() -> List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Callable]]:\n    return [\n        (\n            QnnConv2DParams.composite_name,\n            qnn_conv2d_pattern(),\n            lambda pat: QnnConv2DParams(pat).is_valid(),\n        ),\n        (\n            QnnDepthwiseConv2DParams.composite_name,\n            qnn_depthwise_conv2d_pattern(),\n            lambda pat: QnnDepthwiseConv2DParams(pat).is_valid(),\n        ),\n        (\n            QnnConv2DTransposeParams.composite_name,\n            qnn_conv2d_transpose_pattern(),\n            lambda pat: QnnConv2DTransposeParams(pat).is_valid(),\n        ),\n        (\n            FullyConnectedParams.composite_name,\n            qnn_fc_pattern(),\n            lambda pat: FullyConnectedParams(pat).is_valid(),\n        ),\n        (\n            MaxPool2DParams.composite_name,\n            qnn_maxpool2d_pattern(),\n            lambda pat: MaxPool2DParams(pat).is_valid(),\n        ),\n        (\n            AvgPool2DParams.composite_name,\n            qnn_avgpool2d_pattern(),\n            lambda pat: AvgPool2DParams(pat).is_valid(),\n        ),\n        (\n            AddParams.composite_name,\n            qnn_add_pattern(),\n            lambda pat: AddParams(pat).is_valid(),\n        ),\n        (\n            SubParams.composite_name,\n            qnn_subtract_pattern(),\n            lambda pat: SubParams(pat).is_valid(),\n        ),\n        (\n            MulParams.composite_name,\n            qnn_mul_pattern(),\n            lambda pat: MulParams(pat).is_valid(),\n        ),\n        (\n            MinParams.composite_name,\n            minimum_pattern(),\n            lambda pat: MinParams(pat).is_valid(),\n        ),\n        (\n            MaxParams.composite_name,\n            maximum_pattern(),\n            lambda pat: MaxParams(pat).is_valid(),\n        ),\n        (\n            ShlParams.composite_name,\n            shl_pattern(),\n            lambda pat: ShlParams(pat).is_valid(),\n        ),\n        (\n            ReshapeParams.composite_name,\n            reshape_pattern(),\n            lambda pat: ReshapeParams(pat).is_valid(),\n        ),\n        (\n            StridedSliceParams.composite_name,\n            strided_slice_pattern(),\n            lambda pat: StridedSliceParams(pat).is_valid(),\n        ),\n        (\n            AbsParams.composite_name,\n            abs_pattern(),\n            lambda pat: AbsParams(pat).is_valid(),\n        ),\n        (TanhParams.composite_name, tanh_pattern(), lambda pat: TanhParams(pat).is_valid()),\n        (\n            MeanParams.composite_name,\n            mean_pattern(),\n            lambda pat: MeanParams(pat).is_valid(),\n        ),\n        (\n            LeakyReLUParams.composite_name,\n            leaky_relu_pattern(),\n            lambda pat: LeakyReLUParams(pat).is_valid(),\n        ),\n        (ConcatParams.composite_name, concat_pattern(), lambda pat: ConcatParams(pat).is_valid()),\n        (\n            SigmoidParams.composite_name,\n            sigmoid_pattern(),\n            lambda pat: SigmoidParams(pat).is_valid(),\n        ),\n        (\n            SplitParams.composite_name,\n            split_pattern(),\n            lambda pat: SplitParams(pat).is_valid(),\n        ),\n        (\n            RequantizeParams.composite_name,\n            requantize_pattern(),\n            lambda pat: RequantizeParams(pat).is_valid(),\n        ),\n        (\n            Resize2dParams.composite_name,\n            resize2d_pattern(),\n            lambda pat: Resize2dParams(pat).is_valid(),\n        ),\n        (\n            ExpandDimsParams.composite_name,\n            expand_dims_pattern(),\n            lambda pat: ExpandDimsParams(pat).is_valid(),\n        ),\n        (\n            SqueezeParams.composite_name,\n            squeeze_pattern(),\n            lambda pat: SqueezeParams(pat).is_valid(),\n        ),\n        (\n            HardSwishParams.composite_name,\n            hard_swish_pattern(),\n            lambda pat: HardSwishParams(pat).is_valid(),\n        ),\n    ]\n\n\n# pylint: disable=unused-argument\n@requires_vela\ndef partition_for_ethosu(\n    mod: tvm.ir.IRModule,\n    params: Optional[Dict[str, tvm.runtime.NDArray]] = None,\n    mod_name: str = \"default\",\n    **opts,\n):\n    \"\"\"This helper function partition the relay graph as produced by the\n    relay frontend for a given model into external functions\n    to be presented to the codegen.\n\n    Parameters\n    ----------\n    mod : tvm.ir.IRModule\n        The IRModule that gets generated from a relay frontend\n    params : Optional[Dict[str, tvm.runtime.NDArray]]\n        Constant input parameters.\n    mod_name: str, optional\n        The module name\n\n    Returns\n    -------\n    mod : IRModule\n        The partitioned IRModule with external global functions\n    \"\"\"\n    from tvm.relay.backend.contrib.ethosu import preprocess\n\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    pattern = relay.op.contrib.get_pattern_table(\"ethos-u\")\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.MergeComposite(pattern)(mod)\n    mod = relay.transform.AnnotateTarget(\"ethos-u\")(mod)\n    mod = relay.transform.MergeCompilerRegions()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.PartitionGraph(mod_name)(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = preprocess.preprocess_ext_io()(mod)\n    return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/libtorch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, no-else-return, E1102\n\"\"\"Torch codegen operators\"\"\"\n\nfrom tvm import relay\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\n\n\ndef torchop(script_fn, *params):\n    \"\"\"Insert an Operation executed in the PyTorch JIT\n\n    The operation includes backend annotation\n\n    Currently, only tensors are supported. The shape inferrence\n    assumes that input shapes (and not values) determine output shapes.\"\"\"\n    return compiler_end(\n        relay.op._make.torchop(\n            [compiler_begin(p, \"torch\") for p in params], script_fn.save_to_buffer()\n        ),\n        \"torch\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/register.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Register utilities for external codegen.\"\"\"\n_PATTERN_TABLES = {}\n\n\ndef register_pattern_table(compiler, table=None):\n    \"\"\"Register a pattern table for an external compiler.\n\n    Pattern tables are used to create composite functions.\n    See the MergeComposite pass.\n\n    Parameters\n    ----------\n    compiler : str\n        The name of compiler\n\n    table : function, optional\n        A function that returns the pattern table\n\n    Returns\n    -------\n    fregister : function\n        Register function if value is not specified.\n    \"\"\"\n\n    def _register(t):\n        \"\"\"internal register function\"\"\"\n        _PATTERN_TABLES[compiler] = t()\n        return t\n\n    return _register(table) if table is not None else _register\n\n\ndef get_pattern_table(compiler):\n    \"\"\"Get the pattern table associated with a compiler (if it's registered).\"\"\"\n    return _PATTERN_TABLES[compiler] if compiler in _PATTERN_TABLES else None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/tachikoma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Tachikoma library supported operators.\n\nFrom TVM's perspective, Tachikoma is an extension of DNNL. The code below\nis adapted from that of DNNL:\n\nThere are two ways to registering a function for an op to indicate if it is\nsupported by Tachikoma.\n- The first and simplest way is to use the helper so that\nusers only need to provide the operator name and a boolean value to indicate if\nit is supported. For example:\n    .. code-block:: python\n      add = _register_external_op_helper(\"add\")\n      add = _register_external_op_helper(\"add\", True)\n      add = _register_external_op_helper(\"add\", False)\n- The other way is to implement the function by themselves to\ncheck the attributes of the op and decide if it should be offloaded to Tachikoma.\n\"\"\"\nimport logging\nfrom functools import reduce\n\nimport tvm.ir\nfrom tvm.ir import Op\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.expr import GlobalVar\nfrom tvm.relay.expr_functor import ExprMutator, ExprVisitor\nfrom tvm.relay.expr import const\n\nfrom tvm.relay.analysis import analysis as _analysis\nfrom tvm.relay import expr as _expr\n\nfrom tvm.relay.expr import Call, TupleGetItem\nfrom ... import _ffi_api\nfrom ...dataflow_pattern import wildcard, is_op, is_constant, is_expr, rewrite, DFPatternCallback\nfrom .register import register_pattern_table\n\n\nlogger = logging.getLogger(\"Tachikoma\")\nsupported_post_elts = [\"nn.relu\", \"tanh\", \"sigmoid\", \"clip\", \"gelu\", \"swish\", \"mish\", None]\n\n\ndef _register_external_op_helper(op_name, supported=True):\n    \"\"\"The helper function to indicate that a given operator can be supported\n    by Tachikoma.\n    Parameters\n    ----------\n    op_name : Str\n        The name of operator that will be registered.\n    Returns\n    -------\n    f : callable\n        A function that returns if the operator is supported by Tachikoma.\n    \"\"\"\n\n    @tvm.ir.register_op_attr(op_name, \"target.tachikoma\")\n    def _func_wrapper(expr):\n        args = expr.args\n        if any([x.checked_type.dtype == \"int64\" for x in args]):\n            logger.info(\"Tachikoma does not support int64.\")\n            return False\n        # Tachikoma does not support pooling with ceil_mode = True.\n        if \"pool\" in op_name:\n            attrs = dict(get_attrs(expr))\n            if \"ceil_mode\" in attrs.keys() and attrs[\"ceil_mode\"]:\n                return False\n        return supported\n\n    return _func_wrapper\n\n\n_register_external_op_helper(\"nn.batch_norm\")\n_register_external_op_helper(\"nn.conv1d\")\n_register_external_op_helper(\"nn.conv2d\")\n_register_external_op_helper(\"nn.conv3d\")\n_register_external_op_helper(\"nn.conv2d_transpose\")\n_register_external_op_helper(\"nn.conv3d_transpose\")\n_register_external_op_helper(\"nn.dense\")\n_register_external_op_helper(\"nn.max_pool2d\")\n_register_external_op_helper(\"nn.avg_pool2d\")\n_register_external_op_helper(\"nn.global_avg_pool2d\")\n_register_external_op_helper(\"nn.max_pool3d\")\n_register_external_op_helper(\"nn.avg_pool3d\")\n_register_external_op_helper(\"abs\")\n_register_external_op_helper(\"clip\")\n_register_external_op_helper(\"exp\")\n_register_external_op_helper(\"log\")\n_register_external_op_helper(\"sqrt\")\n_register_external_op_helper(\"round\")\n_register_external_op_helper(\"nn.relu\")\n_register_external_op_helper(\"nn.leaky_relu\")\n_register_external_op_helper(\"tanh\")\n_register_external_op_helper(\"sigmoid\")\n_register_external_op_helper(\"nn.softmax\")\n_register_external_op_helper(\"add\")\n_register_external_op_helper(\"multiply\")\n_register_external_op_helper(\"nn.layer_norm\")\n_register_external_op_helper(\"nn.batch_matmul\")\n\n\ndef append_eltwise_ops(op, eltwise):\n    \"\"\"Append element-wise post-ops to conv / conv_transpose / dense\n    Parameters\n    ----------\n    op : str\n        The op name to be attached with element-wise post-op.\n    eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    pattern : CallPattern\n        Call node sequence.\n    \"\"\"\n    if eltwise == \"gelu\":\n        const1 = wildcard()\n        const2 = wildcard()\n        const3 = wildcard()\n        div = is_op(\"divide\")(op, const1)\n        erf_val = is_op(\"erf\")(div)\n        added_erf_val = is_op(\"add\")(erf_val, const2)\n        mul_val = is_op(\"multiply\")(op, added_erf_val)\n        op = is_op(\"multiply\")(mul_val, const3)\n    elif eltwise == \"swish\":\n        sig_out = is_op(\"sigmoid\")(op)\n        op = is_op(\"multiply\")(op, sig_out)\n    elif eltwise == \"mish\":\n        const1 = wildcard()\n        exp = is_op(\"exp\")(op)\n        add = is_op(\"add\")(exp, const1)\n        log = is_op(\"log\")(add)\n        tanh = is_op(\"tanh\")(log)\n        op = is_op(\"multiply\")(op, tanh)\n    elif eltwise:\n        op = is_op(eltwise)(op)\n    return op\n\n\ndef make_conv_pattern(conv_name, with_bias=True, with_eltwise=None):\n    \"\"\"Create patterns related to conv and conv_transpose.\n    Parameters\n    ----------\n    with_bias : bool\n        Whether attach `bias_add` to `conv / conv_transpose`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    conv_out : CallPattern\n        Call node sequence.\n    \"\"\"\n    if with_eltwise not in supported_post_elts:\n        raise ValueError(\"Unsupported eltwise post-op: %s\" % with_eltwise)\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    conv = is_op(conv_name)(data, weight)\n    if with_bias:\n        conv_out = is_op(\"add\")(conv, bias)\n    else:\n        conv_out = conv\n    return append_eltwise_ops(conv_out, with_eltwise)\n\n\ndef make_conv_bias_sum_relu_pattern(conv_type, has_relu=True):\n    \"\"\"Create patterns with sum op.\n    Parameters\n    ----------\n    conv_type : str\n        Should be nn.conv1d / nn.conv2d / nn.conv3d.\n    has_relu : bool\n        Whether attach relu.\n    Returns\n    -------\n    out : CallPattern\n        Call node sequence.\n    \"\"\"\n    data1 = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n    data2 = wildcard()\n    out = is_op(conv_type)(data1, weight)\n    out = is_op(\"add\")(out, bias)\n    out = is_op(\"add\")(out, data2)\n    if has_relu:\n        out = is_op(\"nn.relu\")(out)\n    return out\n\n\ndef get_op_name(expr):\n    \"\"\"Get the operator name from an expression.\"\"\"\n    if isinstance(expr, Op):\n        return expr.name\n    if isinstance(expr, Call):\n        return get_op_name(expr.op)\n    if isinstance(expr, TupleGetItem):\n        return get_op_name(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return get_op_name(expr.fields[0])\n    return \"\"\n\n\ndef get_args(expr):\n    \"\"\"Get the arguments from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.args\n    if isinstance(expr, TupleGetItem):\n        return get_args(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return [arg for args in map(get_args, expr.fields) for arg in args]\n    return []\n\n\ndef get_attrs(expr):\n    \"\"\"Get the attributes from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.attrs\n    if isinstance(expr, TupleGetItem):\n        return get_attrs(expr.tuple_value)\n    return {}\n\n\ndef make_sum_pattren_predicate(checker):\n    \"\"\"Check whether the conv_bias_add_sum pattern is as expected.\"\"\"\n\n    def predicate(expr):\n        if get_op_name(expr) == \"nn.relu\":\n            expr = expr.args[0]\n        for e, op_name in zip([expr, expr.args[0]], [\"sum\", \"bias_add\"]):\n            args = get_args(e)\n            attrs = get_attrs(e.args[0])\n            if not checker(attrs, args, op_name):\n                return False\n        return True\n\n    return predicate\n\n\ndef make_bias_add_pattren_predicate(checker):\n    \"\"\"Check whether the conv_bias pattern is as expected.\"\"\"\n\n    def predicate(expr):\n        if get_op_name(expr) == \"nn.relu\":\n            expr = expr.args[0]\n        if get_op_name(expr) == \"add\":\n            args = get_args(expr)\n            attrs = get_attrs(expr.args[0])\n            if not checker(attrs, args, \"bias_add\"):\n                return False\n        return True\n\n    return predicate\n\n\ndef add_checker(attrs, args, op_name):\n    \"\"\"Check if add is aligned with elementwise_add and bias_add.\"\"\"\n    if op_name == \"sum\":\n        if not isinstance(args[0].op, tvm.ir.op.Op):\n            return False\n        if args[0].op.name != \"add\":\n            return False\n        if tuple(get_shape(args[0])) != tuple(get_shape(args[1])):\n            return False\n    if op_name == \"bias_add\":\n        if not isinstance(args[0].op, tvm.ir.op.Op):\n            return False\n        if args[0].op.name != \"nn.conv2d\":\n            return False\n        channel = dict(attrs)[\"channels\"]\n        const_shape = get_shape(args[1])\n        if channel != reduce(lambda x, y: x * y, const_shape):\n            return False\n    return True\n\n\ndef make_dense_pattern(with_bias=True, with_eltwise=None):\n    \"\"\"Create patterns related to nn.dense.\n    Parameters\n    ----------\n    with_bias : bool\n        Whether attach `bias_add` to `nn.dense`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    dense_out : CallPattern\n        Call node sequence.\n    \"\"\"\n    if with_eltwise not in supported_post_elts:\n        raise ValueError(\"Unsupported eltwise post-op: %s\" % with_eltwise)\n    data = wildcard()\n    weight = wildcard()\n    bias = wildcard()\n\n    dense = is_op(\"nn.dense\")(data, weight)\n    if with_bias:\n        dense_out = is_op(\"add\")(dense, bias)\n    else:\n        dense_out = dense\n    return append_eltwise_ops(dense_out, with_eltwise)\n\n\ndef make_tachikoma_pattern(op_name, with_bias, with_eltwise):\n    \"\"\"Create tachikoma patterns.\n    Parameters\n    ----------\n    op_name : str\n        The first call node's op name.\n    with_bias : bool\n        Whether attach `bias_add` to `nn.dense`.\n    with_eltwise : str\n        The attached elementwise post-op name.\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    pat_name = op_name.replace(\"nn\", \"tachikoma\")\n    if \"_transpose\" in op_name:\n        pat_name = \"tachikoma.deconv\" + op_name.split(\"_\")[0][-2::]\n    pat_name += \"_bias\" if with_bias else \"\"\n    pat_name += (\"_\" + with_eltwise.split(\".\")[-1]) if with_eltwise else \"\"\n    if \"conv\" in op_name:\n        tachikoma_pattern = (\n            pat_name,\n            make_conv_pattern(op_name, with_bias, with_eltwise),\n            make_bias_add_pattren_predicate(add_checker),\n        )\n    elif op_name == \"nn.dense\":\n        tachikoma_pattern = (pat_name, make_dense_pattern(with_bias, with_eltwise))\n    else:\n        logger.warning(\n            \"Currently, only conv1d, conv2d, conv2d_transpose, conv3d_transpose, \"\n            \"dense op are supported, but got %s.\",\n            op_name,\n        )\n        tachikoma_pattern = ()\n    return tachikoma_pattern\n\n\ndef make_qnn_conv2d_pattern():\n    \"\"\"Make qnn.conv2d based pattern supported by Tachikoma\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    data = wildcard()\n    weight = is_constant()\n    bias = is_constant()\n    o_scl = is_constant()\n    dst_zp = is_constant()\n    act_scl = is_constant()\n    sum_scl = is_constant()\n    sum_src = wildcard()\n\n    zero_zp = is_expr(const(0, dtype=\"int32\"))\n\n    pat = is_op(\"qnn.conv2d\")(data, weight, zero_zp, zero_zp, is_constant(), is_constant())\n    pat = is_op(\"cast\")(pat)\n    pat = is_op(\"add\")(pat, bias) | pat  # optional bias\n    pat = is_op(\"multiply\")(pat, o_scl)\n    pat = is_op(\"clip\")(pat)  # TBD, not only clip\n    pat = is_op(\"multiply\")(pat, act_scl) | pat  # optional multiply. Ex: act_scl == 1\n    pat = is_op(\"add\")(pat, sum_scl * is_op(\"cast\")(sum_src)) | pat  # optional sum\n    pat = is_op(\"add\")(pat, dst_zp) | pat  # optional dst_zp, can be dst_zp == 0\n    pat = is_op(\"cast\")(pat)\n\n    return \"tachikoma.qnn.conv2d\", pat\n\n\ndef make_qnn_dense_pattern():\n    \"\"\"Make qnn.dense based pattern supported by Tachikoma\n    Returns\n    -------\n    pattern : Tuple(pattern_name, CallPattern)\n        Created pattern name, along with its CallPattern.\n    \"\"\"\n    data = wildcard()\n    weight = is_constant()\n    bias = is_constant()\n    o_scl = is_constant()\n    dst_zp = is_constant()\n    act_scl = is_constant()\n    sum_scl = is_constant()\n    sum_src = wildcard()\n\n    zero_zp = is_expr(const(0, dtype=\"int32\"))\n\n    pat = is_op(\"qnn.dense\")(data, weight, zero_zp, zero_zp, is_constant(), is_constant())\n    pat = is_op(\"cast\")(pat)\n    pat = is_op(\"add\")(pat, bias) | pat  # optional bias\n    pat = is_op(\"multiply\")(pat, o_scl)\n    pat = is_op(\"clip\")(pat)  # TBD, not only clip\n    pat = is_op(\"multiply\")(pat, act_scl) | pat  # optional multiply. ex act_scl == 1\n    pat = is_op(\"add\")(pat, sum_scl * is_op(\"cast\")(sum_src)) | pat  # optional sum\n    pat = is_op(\"add\")(pat, dst_zp) | pat  # optional dst_zp, can be dst_zp == 0\n    pat = is_op(\"cast\")(pat)\n\n    return \"tachikoma.qnn.dense\", pat\n\n\n@register_pattern_table(\"tachikoma\")\ndef pattern_table():\n    \"\"\"Create tachikoma patterns.\n    Returns\n    -------\n    tachikoma_patterns : List[tachikoma_pattern]\n        Created patterns.\n    \"\"\"\n    tachikoma_patterns = list()\n    tachikoma_patterns.append(make_qnn_conv2d_pattern())\n    tachikoma_patterns.append(make_qnn_dense_pattern())\n    tachikoma_patterns.append(\n        (\n            \"tachikoma.conv2d_bias_sum_relu\",\n            make_conv_bias_sum_relu_pattern(\"nn.conv2d\"),\n            make_sum_pattren_predicate(add_checker),\n        )\n    )\n    tachikoma_patterns.append(\n        (\n            \"tachikoma.conv2d_bias_sum\",\n            make_conv_bias_sum_relu_pattern(\"nn.conv2d\", False),\n            make_sum_pattren_predicate(add_checker),\n        )\n    )\n\n    elt_list = [\"nn.relu\", \"tanh\", \"sigmoid\", \"clip\", \"gelu\", \"swish\", \"mish\", None]\n    for with_bias in [True, False]:\n        for elt in elt_list:\n            if not with_bias and not elt:\n                continue\n            for conv_name in [\n                \"nn.conv1d\",\n                \"nn.conv2d\",\n                \"nn.conv3d\",\n                \"nn.conv2d_transpose\",\n                \"nn.conv3d_transpose\",\n            ]:\n                tachikoma_patterns.append(make_tachikoma_pattern(conv_name, with_bias, elt))\n            tachikoma_patterns.append(make_tachikoma_pattern(\"nn.dense\", with_bias, elt))\n    return tachikoma_patterns\n\n\ndef get_optimal_layout_for_conv(\n    data_layout, kernel_layout, weight_shape, out_shape, paddings, strides, dilates, groups, dtype\n):\n    \"\"\"Get the optimal layout of tachikoma, given shape of conv2d.\n    Parameters\n    ----------\n    data_layout, kernel_layout,weight_shape, out_shape, paddings, strides, dilates, groups\n        : String\n          Input argument.\n    Returns\n    -------\n    layouts : string\n              The result.\n    \"\"\"\n    return _ffi_api.get_optimal_layout_for_conv(\n        data_layout,\n        kernel_layout,\n        weight_shape,\n        out_shape,\n        paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n\n\ndef get_optimal_layout_for_conv_transpose(\n    data_layout,\n    kernel_layout,\n    weight_shape,\n    out_shape,\n    paddings,\n    output_paddings,\n    strides,\n    dilates,\n    groups,\n    dtype,\n):\n    \"\"\"Get the optimal layout of tachikoma, given shape of tranposed conv2d.\n    Parameters\n    ----------\n    data_layout, kernel_layout, weight_shape, out_shape, paddings, output_paddings, strides,\n    dilates, groups\n        : Int, String\n          Input argument.\n    Returns\n    -------\n    layouts : string\n              The result.\n    \"\"\"\n    return _ffi_api.get_optimal_layout_for_conv_transpose(\n        data_layout,\n        kernel_layout,\n        weight_shape,\n        out_shape,\n        paddings,\n        output_paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n\n\ndef get_shape(tensor):\n    \"\"\"Get tensor's shape.\"\"\"\n    if isinstance(tensor, relay.expr.Var):\n        return tensor.type_annotation.concrete_shape\n    if isinstance(tensor, relay.expr.Constant):\n        return tensor.data.shape\n    if isinstance(tensor, tvm.ir.tensor_type.TensorType):\n        return tensor.concrete_shape\n    if isinstance(tensor, tvm.ir.container.Array):\n        return tensor[-1].shape\n    if isinstance(tensor, relay.expr.Call):\n        if tensor.op.name == \"multiply\":\n            return tensor.type_args[0].shape\n        return tensor.checked_type.shape\n    raise TypeError(\"Unsupport data type: %s\" % type(tensor))\n\n\ndef get_dtype(tensor):\n    \"\"\"Get tensor's dtype.\"\"\"\n    if isinstance(tensor, relay.expr.Var):\n        return tensor.type_annotation.dtype\n    if isinstance(tensor, relay.expr.Constant):\n        return tensor.data.dtype\n    if isinstance(tensor, tvm.ir.tensor_type.TensorType):\n        return tensor.dtype\n    if isinstance(tensor, tvm.ir.container.Array):\n        return tensor[-1].dtype\n    if isinstance(tensor, relay.expr.Call):\n        if tensor.op.name == \"multiply\":\n            return tensor.type_args[0].dtype\n        return tensor.checked_type.dtype\n    raise TypeError(\"Unsupport data type: %s\" % type(tensor))\n\n\ndef tag2layout(input_data, is_weight=False, conv_type=\"Conv1D\"):\n    \"\"\"Transfer layout, denoted with `a, b, c, d, e`,\n    into valid layout (NCHW / OIHW) of TVM.\"\"\"\n    if \"Conv1D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"W\", \"d\": \"G\"}\n    elif \"Conv2D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"H\", \"d\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"H\", \"d\": \"W\"}\n        if \"e\" in input_data:\n            weight_dic = {\"a\": \"G\", \"b\": \"O\", \"c\": \"I\", \"d\": \"H\", \"e\": \"W\"}\n    elif \"Conv3D\" in conv_type:\n        data_dic = {\"a\": \"N\", \"b\": \"C\", \"c\": \"D\", \"d\": \"H\", \"e\": \"W\"}\n        weight_dic = {\"a\": \"O\", \"b\": \"I\", \"c\": \"D\", \"d\": \"H\", \"e\": \"W\", \"f\": \"G\"}\n\n    dic = weight_dic if is_weight else data_dic\n    res = \"\"\n\n    for i in input_data:\n        if i.isupper():\n            i = i.lower()\n            res += dic[i]\n            dic[i] = dic[i].lower()\n        elif i.islower():\n            res += dic[i]\n        elif i.isdigit():\n            res += i\n        else:\n            raise ValueError(\"Unsupport layout format: %s\" % input_data)\n\n    return res\n\n\ndef legalize_pad_avg_pool(attrs, inputs, types):\n    \"\"\"Legalize pad->avg_pool2d pattern.\n    Fuse this pattern into one avg_pool2d with padding = (1, 1),\n    and count_include_pad = True\"\"\"\n    data = inputs[0]\n    new_attrs = dict(attrs)\n    if isinstance(data, relay.expr.Call) and data.op.name == \"nn.pad\":\n        new_attrs[\"padding\"] = (1, 1)\n        new_attrs[\"count_include_pad\"] = True\n        return relay.nn.avg_pool2d(data.args[0], **new_attrs)\n    return relay.nn.avg_pool2d(data, **attrs)\n\n\ndef legalize_group_conv(attrs, inputs, types):\n    \"\"\"Legalize group conv / conv_transpose calculation.\n    Alter weight layout from OIHW to GOIHW / IOHW to GIOHW\"\"\"\n    groups = attrs.groups\n    data, weight = inputs\n    if groups == 1:\n        if \"Transpose\" not in type(attrs).__name__:\n            return relay.nn.conv2d(data, weight, **attrs)\n        return relay.nn.conv2d_transpose(data, weight, **attrs)\n    OC, IC, H, W = get_shape(weight)\n    new_attrs = dict(attrs)\n    weight = relay.reshape(weight, (groups, OC // groups, IC, H, W))\n    if \"Transpose\" not in type(attrs).__name__:\n        new_attrs[\"kernel_layout\"] = \"GOIHW\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    new_attrs[\"kernel_layout\"] = \"GIOHW\"\n    return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n\n\ndef alter_conv(attrs, inputs, tinfos, out_type):\n    \"\"\"The convolution's layout auto-query func for tachikoma.\"\"\"\n\n    data, weight = inputs\n    groups = str(attrs.groups)\n    weight_shape = \",\".join([str(x) for x in get_shape(weight)])\n    out_shape = \",\".join([str(x) for x in get_shape(out_type)])\n    paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"padding\")])\n    strides = \",\".join([str(x) for x in attrs.get_int_tuple(\"strides\")])\n    dilates = \",\".join([str(x) for x in attrs.get_int_tuple(\"dilation\")])\n    dtype = get_dtype(weight)\n    new_attrs = dict(attrs)\n    conv_type = type(attrs).__name__.split(\"Attrs\")[0]\n\n    res = get_optimal_layout_for_conv(\n        attrs[\"data_layout\"],\n        attrs[\"kernel_layout\"],\n        weight_shape,\n        out_shape,\n        paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n    src_df, weight_df, dst_df = res.split(\",\")\n    new_attrs[\"data_layout\"] = tag2layout(src_df, is_weight=False, conv_type=conv_type)\n    new_attrs[\"kernel_layout\"] = tag2layout(weight_df, is_weight=True, conv_type=conv_type)\n    new_attrs[\"out_layout\"] = tag2layout(dst_df, is_weight=False, conv_type=conv_type)\n\n    if conv_type == \"Conv1D\":\n        return relay.nn.conv1d(data, weight, **new_attrs)\n    if conv_type == \"Conv2D\":\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    return relay.nn.conv3d(data, weight, **new_attrs)\n\n\ndef alter_conv_transpose(attrs, inputs, tinfos, out_type):\n    \"\"\"The transposed convolution's layout auto-query func for tachikoma.\"\"\"\n\n    data, weight = inputs\n    weight_shape = \",\".join([str(x) for x in get_shape(weight)])\n    out_shape = \",\".join([str(x) for x in get_shape(out_type)])\n    paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"padding\")])\n    output_paddings = \",\".join([str(x) for x in attrs.get_int_tuple(\"output_padding\")])\n    strides = \",\".join([str(x) for x in attrs.get_int_tuple(\"strides\")])\n    dilates = \",\".join([str(x) for x in attrs.get_int_tuple(\"dilation\")])\n    groups = str(attrs.groups)\n    dtype = get_dtype(weight)\n    new_attrs = dict(attrs)\n    conv_type = type(attrs).__name__.split(\"Attrs\")[0]\n\n    res = get_optimal_layout_for_conv_transpose(\n        attrs[\"data_layout\"],\n        attrs[\"kernel_layout\"],\n        weight_shape,\n        out_shape,\n        paddings,\n        output_paddings,\n        strides,\n        dilates,\n        groups,\n        dtype,\n    )\n    src_df, weight_df, dst_df = res.split(\",\")\n    new_attrs[\"data_layout\"] = tag2layout(src_df, is_weight=False, conv_type=conv_type)\n    new_attrs[\"kernel_layout\"] = tag2layout(weight_df, is_weight=True, conv_type=conv_type)\n    new_attrs[\"out_layout\"] = tag2layout(dst_df, is_weight=False, conv_type=conv_type)\n\n    if conv_type == \"Conv1DTranspose\":\n        return relay.nn.conv1d_transpose(data, weight, **new_attrs)\n    if conv_type == \"Conv2DTranspose\":\n        return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n    return relay.nn.conv3d_transpose(data, weight, **new_attrs)\n\n\nclass IsComputeIntensiveGraph(ExprVisitor):\n    \"\"\"\n    Visits the Graph recursively and checks if it contains compute heavy ops like convolutions and\n    its transpose and dense.\n    \"\"\"\n\n    def __init__(self):\n        ExprVisitor.__init__(self)\n        self.is_compute_intensive = False\n\n    def visit_call(self, call):\n        compute_intensive_ops = set(\n            [\n                \"nn.conv1d\",\n                \"nn.conv2d\",\n                \"nn.conv2d_transpose\",\n                \"nn.conv3d\",\n                \"nn.conv3d_transpose\",\n                \"nn.dense\",\n                \"nn.layer_norm\",\n                \"nn.batch_matmul\",\n                \"nn.global_avg_pool2d\",\n            ]\n        )\n        if isinstance(call.op, tvm.tir.op.Op):\n            if str(call.op) in compute_intensive_ops:\n                self.is_compute_intensive = True\n\n        return super().visit_call(call)\n\n    def is_graph_compute_intensive(self, subgraph) -> bool:\n        \"\"\"\n        This function recursively visits the graph and checks if it's compute intensive\"\n        \"\"\"\n        self.visit(subgraph)\n        return self.is_compute_intensive\n\n\ndef is_valid_subgraph(body):\n    \"\"\"Final check on whether the subgraph is valid and should be offloaded to Tachikoma.\"\"\"\n    return IsComputeIntensiveGraph().is_graph_compute_intensive(body)\n\n\ndef prune_tachikoma_subgraphs(mod):\n    \"\"\"\n    Removes invalid subgraphs, which does not contain compute intensive tachikoma ops.\n    \"\"\"\n\n    class SubgraphRemover(ExprMutator):\n        \"\"\"\n        Reverts subgraphs in subgraphs_to_remove back to TVM instead of using an external codegen.\n        \"\"\"\n\n        def __init__(self, subgraphs_to_remove, mod, new_mod):\n            ExprMutator.__init__(self)\n            self.subgraphs_to_remove = subgraphs_to_remove\n            self.mod = mod\n            self.new_mod = new_mod\n\n        def visit_call(self, call):\n            if isinstance(call.op, GlobalVar):\n                name = call.op.name_hint\n                if name in self.subgraphs_to_remove:\n                    # \"Inline\" the subgraph back into new main function.\n                    func = self.mod[name]\n                    var_map = {}\n                    for arg, param in zip(call.args, func.params):\n                        var_map[param] = super().visit(arg)\n                    new_body = relay.bind(func.body, var_map)\n                    return new_body\n                if name != \"main\":\n                    args = []\n                    for arg in call.args:\n                        args.append(super().visit(arg))\n                    return call.op(*args)\n            return super().visit_call(call)\n\n    subgraphs_to_remove = []\n    # If only one subgraph, do nothing.\n    if len(mod.get_global_vars()) <= 2:\n        return mod\n    # Remove invalid subgraphs\n    for subgraph in mod.get_global_vars():\n        name = subgraph.name_hint\n        if not mod[name].attrs or mod[name].attrs[\"Compiler\"] != \"tachikoma\":\n            continue\n        if not is_valid_subgraph(mod[name].body):\n            subgraphs_to_remove.append(name)\n    # Create new pruned module\n    new_mod = tvm.IRModule(mod.functions, mod.type_definitions)\n    new_mod[\"main\"] = SubgraphRemover(subgraphs_to_remove, mod, new_mod).visit(mod[\"main\"])\n    new_mod = transform.RemoveUnusedFunctions()(new_mod)\n    return new_mod\n\n\nclass LayerNormRewrite(DFPatternCallback):\n    \"\"\"\n    A callback to rewrite the following operators into a single layer normalization operator.\n    Pattern #1:\n    1   %4 = mean(%3, axis=[-1], keepdims=True) /* ty=Tensor[(1, 3136, 1), float32] */;\n    2   %5 = subtract(%3, %4) /* ty=Tensor[(1, 3136, 64), float32] */;\n    3   %6 = cast(%5, dtype=\"float32\") /* ty=Tensor[(1, 3136, 64), float32] */;\n    4   %7 = power(%6, 2f /* ty=float32 */) /* ty=Tensor[(1, 3136, 64), float32] */;\n    5   %8 = mean(%7, axis=[-1], keepdims=True) /* ty=Tensor[(1, 3136, 1), float32] */;\n    6   %9 = add(%8, 1e-05f /* ty=float32 */) /* ty=Tensor[(1, 3136, 1), float32] */;\n    7   %10 = sqrt(%9) /* ty=Tensor[(1, 3136, 1), float32] */;\n    8   %11 = divide(%5, %10) /* ty=Tensor[(1, 3136, 64), float32] */;\n    9   %12 = multiply(%11, meta[relay.Constant][2] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 3136, 64), float32] */;\n    10   %13 = add(%12, meta[relay.Constant][3] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 3136, 64), float32] */;\n    Pattern #2:\n    1   %0 = mean(%input, axis=[-1], keepdims=True);\n    2   %1 = variance(%input, %0, axis=[-1], keepdims=True);\n    3   %2 = add(%1, 1e-05f /* ty=float32 */) /* ty=Tensor[(1, 49, 1), float32] */;\n    4   %3 = subtract(%input, %0);\n    5   %4 = sqrt(%2) /* ty=Tensor[(1, 49, 1), float32] */;\n    6   %5 = divide(%3, %4);\n    7   %6 = multiply(%5, meta[relay.Constant][0] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 49, 64), float32] */;\n    8   %7 = add(%6, meta[relay.Constant][1] /* ty=Tensor[(64), float32] */)\n            /* ty=Tensor[(1, 49, 64), float32] */\n    \"\"\"\n\n    def __init__(self):\n        super(LayerNormRewrite, self).__init__()\n        self.data = wildcard()\n        self.gamma = wildcard()\n        self.beta = wildcard()\n        mu = is_op(\"mean\")(self.data)\n        diff = is_op(\"subtract\")(self.data, mu)\n        cdiff = diff | is_op(\"cast\")(diff)\n        const_two = is_expr(relay.const(2)) | is_expr(relay.const(2.0))\n        p1 = is_op(\"power\")(cdiff, const_two)\n        mp1 = is_op(\"mean\")(p1) | is_op(\"variance\")(self.data, mu)\n        eps = is_expr(relay.const(1e-5)) | is_expr(relay.const(1e-6))\n        added_eps = is_op(\"add\")(mp1, eps)\n        deno = is_op(\"sqrt\")(added_eps)\n        div_out = is_op(\"divide\")(diff, deno)\n        div_out2 = diff * is_op(\"rsqrt\")(added_eps)\n        weighted = is_op(\"multiply\")(div_out | div_out2, self.gamma)\n        added_bias = is_op(\"add\")(weighted, self.beta)\n        self.pattern = added_bias\n\n    def callback(self, pre, post, node_map):\n        data = node_map[self.data][0]\n        gamma = node_map[self.gamma][0]\n        beta = node_map[self.beta][0]\n        return relay.op.nn.layer_norm(data=data, gamma=gamma, beta=beta)\n\n\ndef rewrite_layer_norm(mod):\n    \"\"\"Rewrite the input graph to replace multiple operators with a TVM native layer normalization\n    operator so that we can offload them to tachikoma layer normalization byoc part.\n    \"\"\"\n    mod[\"main\"] = rewrite(LayerNormRewrite(), mod[\"main\"])\n    return mod\n\n\nclass DenseReshapeBiasGeluRewrite(DFPatternCallback):\n    \"\"\"\n    A callback to reorder reshape operators when the patterns are as below:\n    Pattern #1:\n    1   %62 = nn.dense(%61, meta[relay.Constant][13] /* ty=Tensor[(64, 64), float32] */,\n                units=None, out_dtype=\"float32\") /* ty=Tensor[(3136, 64), float32] */;\n    2   %63 = reshape(%62, newshape=[1, 3136, 64]) /* ty=Tensor[(1, 3136, 64), float32] */;\n    3   %64 = add(meta[relay.Constant][4] /* ty=Tensor[(64), float32] */, %63)\n                /* ty=Tensor[(1, 3136, 64), float32] */;\n    Pattern #2:\n    1   %76 = nn.dense(%75, meta[relay.Constant][18] /* ty=Tensor[(512, 64), float32] */,\n                units=None, out_dtype=\"float32\") /*  ty=Tensor[(3136, 512), float32] */;\n    2   %77 = reshape(%76, newshape=[1, 3136, 512]) /* ty=Tensor[(1, 3136, 512), float32] */;\n    3   %78 = add(meta[relay.Constant][15] /* ty=Tensor[(512), float32] */, %77)\n                /* ty=Tensor[(1, 3136, 512), float32] */;\n    4   %79 = divide(%78, 1.41421f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    5   %80 = erf(%79) /* ty=Tensor[(1, 3136, 512), float32] */;\n    6   %81 = add(%80, 1f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    7   %82 = multiply(%78, %81) /* ty=Tensor[(1, 3136, 512), float32] */;\n    8   %83 = multiply(%82, 0.5f /* ty=float32 */) /* ty=Tensor[(1, 3136, 512), float32] */;\n    \"\"\"\n\n    def __init__(self, has_gelu=True):\n        super(DenseReshapeBiasGeluRewrite, self).__init__()\n        self.data = wildcard()\n        self.weight = wildcard()\n        self.bias = wildcard()\n        self.const1 = wildcard()\n        self.const2 = wildcard()\n        self.const3 = wildcard()\n\n        self.attr_map = {}\n        self.has_gelu = has_gelu\n\n        den = is_op(\"nn.dense\")(self.data, self.weight)\n        re_den = is_op(\"reshape\")(den)\n        added = is_op(\"add\")(self.bias, re_den)\n        if self.has_gelu:\n            divisor = is_op(\"divide\")(added, self.const1)\n            val_erf = is_op(\"erf\")(divisor)\n            added_erf = is_op(\"add\")(val_erf, self.const2)\n            mul1 = is_op(\"multiply\")(added, added_erf)\n            mul2 = is_op(\"multiply\")(mul1, self.const3)\n            self.pattern = mul2\n        else:\n            self.pattern = added\n\n    def get_attr(self, pre):\n        \"\"\"Recursively retrieve attributes from reshape operator.\"\"\"\n\n        def visit_func(expr):\n            if isinstance(expr, _expr.Call) and expr.op == relay.op.get(\"reshape\"):\n                new_attrs = {}\n                for k in expr.attrs.keys():\n                    new_attrs[k] = expr.attrs[k]\n                self.attr_map[\"reshape\"] = new_attrs\n\n        _analysis.post_order_visit(pre, visit_func)\n\n    def callback(self, pre, post, node_map):\n        self.get_attr(pre)\n\n        data = node_map[self.data][0]\n        weight = node_map[self.weight][0]\n        bias = node_map[self.bias][0]\n\n        den = relay.op.nn.dense(data, weight)\n        added = relay.op.add(bias, den)\n        if not self.has_gelu:\n            return relay.op.reshape(added, self.attr_map[\"reshape\"][\"newshape\"])\n\n        const1 = node_map[self.const1][0]\n        const2 = node_map[self.const2][0]\n        const3 = node_map[self.const3][0]\n\n        divisor = relay.op.divide(added, const1)\n        val_erf = relay.op.erf(divisor)\n        added_erf = relay.op.add(val_erf, const2)\n        mul1 = relay.op.multiply(added, added_erf)\n        mul2 = relay.op.multiply(mul1, const3)\n        return relay.op.reshape(mul2, self.attr_map[\"reshape\"][\"newshape\"])\n\n\ndef rewrite_dense_bias_gelu_reshape_last(mod):\n    \"\"\"Rewrite the input graph to reorder reshape operators so that\n    we can perform dense_bias_gelu/dense_bias fusion and then offload\n    them to byoc part.\n    \"\"\"\n    mod[\"main\"] = rewrite(\n        [DenseReshapeBiasGeluRewrite(), DenseReshapeBiasGeluRewrite(has_gelu=False)], mod[\"main\"]\n    )\n    return mod\n\n\nclass ResNetV1Rewrite(DFPatternCallback):\n    \"\"\"\n    A callback to advance downsize operation when the patterns are as pattern1,\n    and the result is written in pattern2:\n    Pattern #1:\n    %26 = nn.conv2d(%25, ty=Tensor[(64, 256, 1, 1));\n    %27 = add(%26, ty=Tensor[(64, 1, 1));\n    %28 = nn.relu(%27);\n    %29 = nn.conv2d(%28, ty=Tensor[(64, 64, 3, 3));\n    %30 = add(%29, ty=Tensor[(64, 1, 1));\n    %31 = nn.relu(%30);\n    %32 = nn.conv2d(%31, ty=Tensor[(256, 64, 1, 1));\n    %33 = add(%32, ty=Tensor[(256, 1, 1));\n    %34 = add(%33, %25);\n    %35 = nn.relu(%34);\n    %36 = nn.conv2d(%35, ty=Tensor[(128, 256, 1, 1), strides=[2, 2]);\n    %37 = add(%36, ty=Tensor[(128, 1, 1));\n    %38 = nn.relu(%37);\n    %39 = nn.conv2d(%38, ty=Tensor[(128, 128, 3, 3));\n    %40 = add(%39, ty=Tensor[(128, 1, 1)]);\n    %41 = nn.relu(%40);\n    %42 = nn.conv2d(%41, ty=Tensor[(512, 128, 1, 1));\n    %43 = nn.conv2d(%35, ty=Tensor[(512, 256, 1, 1), strides=[2, 2]);\n    %44 = add(%42, ty=Tensor[(512, 1, 1));\n    %45 = add(%43, ty=Tensor[(512, 1, 1));\n    %46 = add(%44, %45);\n    %47 = nn.relu(%46);\n    Pattern #2:\n    %26 = nn.conv2d(%25, ty=Tensor[(64, 256, 1, 1));\n    %27 = add(%26, ty=Tensor[(64, 1, 1));\n    %28 = nn.relu(%27);\n    %29 = nn.conv2d(%28, ty=Tensor[(64, 64, 3, 3), strides=[2, 2]);\n    %30 = add(%29, ty=Tensor[(64, 1, 1));\n    %31 = nn.relu(%30);\n    %32 = nn.conv2d(%31, ty=Tensor[(256, 64, 1, 1));\n    %33 = add(%32, ty=Tensor[(256, 1, 1));\n    %34 = nn.max_pool2d(%25, pool_size=[1, 1], strides=[2, 2], padding=[0, 0, 0, 0]);\n    %35 = add(%33, %34);\n    %36 = nn.relu(%35);\n    %37 = nn.conv2d(%36, ty=Tensor[(128, 256, 1, 1));\n    %38 = add(%37, ty=Tensor[(128, 1, 1));\n    %39 = nn.relu(%38);\n    %40 = nn.conv2d(%39, ty=Tensor[(128, 128, 3, 3));\n    %41 = add(%40, ty=Tensor[(128, 1, 1));\n    %42 = nn.relu(%41);\n    %43 = nn.conv2d(%42, ty=Tensor[(512, 128, 1, 1));\n    %44 = nn.conv2d(%36, ty=Tensor[(512, 256, 1, 1));\n    %45 = add(%43, ty=Tensor[(512, 1, 1));\n    %46 = add(%44, ty=Tensor[(512, 1, 1));\n    %47 = add(%45, %46);\n    %48 = nn.relu(%47);\n    \"\"\"\n\n    def __init__(self):\n        super(ResNetV1Rewrite, self).__init__()\n        self.attr_lst = []\n        self.data = wildcard()\n        self.w1, self.b1 = wildcard(), wildcard()\n        self.w2, self.b2 = wildcard(), wildcard()\n        self.w3, self.b3 = wildcard(), wildcard()\n        self.w4, self.b4 = wildcard(), wildcard()\n        self.w5, self.b5 = wildcard(), wildcard()\n        self.w6, self.b6 = wildcard(), wildcard()\n        self.w7, self.b7 = wildcard(), wildcard()\n\n        conv1 = is_op(\"nn.conv2d\")(self.data, self.w1).has_attr({\"kernel_size\": [1, 1]})\n        conv1 = is_op(\"add\")(conv1, self.b1)\n        conv1 = is_op(\"nn.relu\")(conv1)\n\n        conv2 = is_op(\"nn.conv2d\")(conv1, self.w2).has_attr({\"kernel_size\": [3, 3]})\n        conv2 = is_op(\"add\")(conv2, self.b2)\n        conv2 = is_op(\"nn.relu\")(conv2)\n\n        conv3 = is_op(\"nn.conv2d\")(conv2, self.w3).has_attr({\"kernel_size\": [1, 1]})\n        conv3 = is_op(\"add\")(conv3, self.b3)\n        conv3 = is_op(\"add\")(conv3, self.data)\n        conv3 = is_op(\"nn.relu\")(conv3)\n\n        left_conv4 = is_op(\"nn.conv2d\")(conv3, self.w4).has_attr({\"strides\": [2, 2]})\n        left_conv4 = is_op(\"add\")(left_conv4, self.b4)\n        left_conv4 = is_op(\"nn.relu\")(left_conv4)\n\n        left_conv5 = is_op(\"nn.conv2d\")(left_conv4, self.w5).has_attr({\"kernel_size\": [3, 3]})\n        left_conv5 = is_op(\"add\")(left_conv5, self.b5)\n        left_conv5 = is_op(\"nn.relu\")(left_conv5)\n\n        left_conv6 = is_op(\"nn.conv2d\")(left_conv5, self.w6).has_attr({\"kernel_size\": [1, 1]})\n        left_conv6 = is_op(\"add\")(left_conv6, self.b6)\n\n        right_conv7 = is_op(\"nn.conv2d\")(conv3, self.w7).has_attr({\"strides\": [2, 2]})\n        right_conv7 = is_op(\"add\")(right_conv7, self.b7)\n\n        out = is_op(\"add\")(left_conv6, right_conv7)\n        out = is_op(\"nn.relu\")(out)\n        self.pattern = out\n\n    def get_attr(self, pre):\n        \"\"\"Recursively retrieve attributes from reshape operator.\"\"\"\n\n        def visit_func(expr):\n            if isinstance(expr, _expr.Call) and expr.op == relay.op.get(\"nn.conv2d\"):\n                self.attr_lst.append(expr.attrs)\n\n        _analysis.post_order_visit(pre, visit_func)\n\n    def callback(self, pre, post, node_map):\n        self.get_attr(pre)\n        data = node_map[self.data][0]\n        w1, b1 = node_map[self.w1][0], node_map[self.b1][0]\n        w2, b2 = node_map[self.w2][0], node_map[self.b2][0]\n        w3, b3 = node_map[self.w3][0], node_map[self.b3][0]\n        w4, b4 = node_map[self.w4][0], node_map[self.b4][0]\n        w5, b5 = node_map[self.w5][0], node_map[self.b5][0]\n        w6, b6 = node_map[self.w6][0], node_map[self.b6][0]\n        w7, b7 = node_map[self.w7][0], node_map[self.b7][0]\n\n        new_attrs = self.attr_lst[-7]\n        conv1 = relay.op.nn.conv2d(data, w1, **new_attrs)\n        conv1 = relay.op.add(conv1, b1)\n        conv1 = relay.op.nn.relu(conv1)\n\n        new_attrs = dict(self.attr_lst[-6])\n        new_attrs[\"strides\"] = [2, 2]\n        conv2 = relay.op.nn.conv2d(conv1, w2, **new_attrs)\n        conv2 = relay.op.add(conv2, b2)\n        conv2 = relay.op.nn.relu(conv2)\n\n        new_attrs = self.attr_lst[-5]\n        conv3 = relay.op.nn.conv2d(conv2, w3, **new_attrs)\n        conv3 = relay.op.add(conv3, b3)\n        max_pool = relay.op.nn.max_pool2d(\n            data, pool_size=(1, 1), strides=(2, 2), layout=new_attrs[\"data_layout\"]\n        )\n        conv3 = relay.op.add(conv3, max_pool)\n        conv3 = relay.op.nn.relu(conv3)\n\n        new_attrs = dict(self.attr_lst[-4])\n        new_attrs[\"strides\"] = [1, 1]\n        left_conv4 = relay.op.nn.conv2d(conv3, w4, **new_attrs)\n        left_conv4 = relay.op.add(left_conv4, b4)\n        left_conv4 = relay.op.nn.relu(left_conv4)\n\n        new_attrs = self.attr_lst[-3]\n        left_conv5 = relay.op.nn.conv2d(left_conv4, w5, **new_attrs)\n        left_conv5 = relay.op.add(left_conv5, b5)\n        left_conv5 = relay.op.nn.relu(left_conv5)\n\n        new_attrs = self.attr_lst[-2]\n        left_conv6 = relay.op.nn.conv2d(left_conv5, w6, **new_attrs)\n        left_conv6 = relay.op.add(left_conv6, b6)\n\n        new_attrs = dict(self.attr_lst[-1])\n        new_attrs[\"strides\"] = [1, 1]\n        right_conv7 = relay.op.nn.conv2d(conv3, w7, **new_attrs)\n        right_conv7 = relay.op.add(right_conv7, b7)\n\n        out = relay.op.add(left_conv6, right_conv7)\n        out = relay.op.nn.relu(out)\n        self.attr_lst = []\n        return out\n\n\ndef rewrite_resnetv1(mod):\n    \"\"\"Rewrite the the ResNetV1 downsize block to reduce the computation complexity.\"\"\"\n    mod[\"main\"] = rewrite(ResNetV1Rewrite(), mod[\"main\"])\n    return mod\n\n\nclass LegalizeQnnOpForTachikoma(DFPatternCallback):\n    \"\"\"Legalize QNN based patterns to match Tachikoma\n    original pattern:\n      OP = qnn.dense | qnn.conv2d\n      %1 = OP<int>(SRC, WGH) - OP<int>(src_zp, WGH)   // qnn.conv2d\n      %2 = %1 + orig_bias                             // bias\n      %2 = (%1 - rq_in_zp) * rq_in_scl / rq_out_scl + rq_out_zp  // qnn.requantize\n      %3 = act(%2)                                               // activation == clip\n      %4 = ((%3 - sum_lh_zp) * sum_lh_scl + (SRC2 - sum_rh_zp) * sum_rh_scl)  // qnn.add\n           / sum_out_scl + sum_out_zp\n    transform to Tachikoma compatible:\n      %1 = OP<int>(SRC, WGH)\n      %2 = cast(%1, dtype=\"float\")\n      %2 = (%1 + bias) * o_scl\n      %3 = act(%2) * act_scl\n      %4 = %3 + SRC2 * sum_scl\n      %5 = %4 + dst_zp\n      %6 = cast(%5, dtype=\"float\")\n    where:\n      o_scl = rq_in_scl / rq_out_scl\n      act_scl = sum_lhs_scl / sum_out_scl\n      sum_scl = sum_rhs_scl / sum_out_scl\n      bias = orig_bias - OP(src_zp, WGH) - rq_in_zp + rq_out_zp * rq_out_scl / rq_in_scl\n      dst_zp = sum_out_zp - sum_lhs_zp * sum_lhs_scl / sum_out_scl -\n               sum_rhs_zp * sum_rhs_scl / sum_out_scl\n    \"\"\"\n\n    def __init__(self):\n        super(LegalizeQnnOpForTachikoma, self).__init__()\n        self.src = wildcard()\n        self.wgh = wildcard()\n        self.bias = wildcard()\n        self.sum_src = wildcard()\n\n        self.src_scl = is_constant()\n        self.src_zp = is_constant()\n        self.wgh_scl = is_constant()\n        self.wgh_zp = is_expr(const(0))\n\n        self.rq_in_scl = is_constant()\n        self.rq_in_zp = is_constant()\n        self.rq_out_scl = is_constant()\n        self.rq_out_zp = is_constant()\n\n        self.sum_lhs_scl = is_constant()\n        self.sum_lhs_zp = is_constant()\n        self.sum_rhs_scl = is_constant()\n        self.sum_rhs_zp = is_constant()\n        self.sum_out_scl = is_constant()\n        self.sum_out_zp = is_constant()\n\n        self.root = (is_op(\"qnn.conv2d\") | is_op(\"qnn.dense\"))(\n            self.src, self.wgh, self.src_zp, self.wgh_zp, self.src_scl, self.wgh_scl\n        )\n        pat = is_op(\"add\")(self.root, self.bias) | self.root  # optional bias\n        pat = is_op(\"qnn.requantize\")(\n            pat, self.rq_in_scl, self.rq_in_zp, self.rq_out_scl, self.rq_out_zp\n        )\n        pat = is_op(\"clip\")(pat)\n        cast = is_op(\"cast\")(pat)\n        pat = is_op(\"qnn.add\")(\n            cast,\n            self.sum_src,\n            self.sum_lhs_scl,\n            self.sum_lhs_zp,\n            self.sum_rhs_scl,\n            self.sum_rhs_zp,\n            self.sum_out_scl,\n            self.sum_out_zp,\n        )\n        pat = is_op(\"clip\")(pat)\n        self.pattern = pat | cast\n\n    def callback(self, pre, post, node_map):\n        root = node_map[self.root][0]\n        src = node_map[self.src][0]\n        wgh = node_map[self.wgh][0]\n        bias = node_map.get(self.bias, default=[relay.const(0, dtype=\"int32\")])[0]\n        src_zp = node_map[self.src_zp][0]\n        rq_in_scl = node_map[self.rq_in_scl][0]\n        rq_in_zp = node_map[self.rq_in_zp][0]\n        rq_out_scl = node_map[self.rq_out_scl][0]\n        rq_out_zp = node_map[self.rq_out_zp][0]\n\n        final_dtype = node_map[self.pattern][0].checked_type.dtype\n\n        if root.op == relay.op.get(\"qnn.conv2d\"):\n            dst_layout = root.attrs.out_layout\n            dst_layout = root.attrs.data_layout if dst_layout == \"\" else dst_layout\n            wgh_layout = root.attrs.kernel_layout\n        else:\n            # qnn.dense has no layout attributes. Assume that is plain\n            dst_layout = \"NC\"\n            wgh_layout = \"OI\"\n\n        # TODO(@liaopeiyuan): dst_layout may be blocked\n        bias_rank = len(dst_layout) - dst_layout.index(\"C\")\n\n        sum_src = node_map[self.sum_src][0] if self.sum_src in node_map else None\n        # Default values if qnn.sum is not present\n        sum_lhs_scl = node_map[self.sum_lhs_scl][0] if sum_src else relay.const(1, dtype=\"float32\")\n        sum_lhs_zp = node_map[self.sum_lhs_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n        sum_rhs_scl = node_map[self.sum_rhs_scl][0] if sum_src else relay.const(0, dtype=\"float32\")\n        sum_rhs_zp = node_map[self.sum_rhs_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n        sum_out_scl = node_map[self.sum_out_scl][0] if sum_src else relay.const(1, dtype=\"float32\")\n        sum_out_zp = node_map[self.sum_out_zp][0] if sum_src else relay.const(0, dtype=\"int32\")\n\n        def cast_fp(op):\n            return relay.op.cast(op, dtype=\"float32\")\n\n        def cast_to_constant(fn):\n            res = relay.create_executor(\n                kind=\"vm\", mod=tvm.IRModule.from_expr(fn)\n            ).evaluate()()\n            return relay.Constant(res)\n    \n        # recalculate some factors\n        o_scl = rq_in_scl / rq_out_scl\n        act_scl = sum_lhs_scl / sum_out_scl\n        sum_scl = sum_rhs_scl / sum_out_scl\n        dst_zp = (\n            cast_fp(sum_out_zp)\n            - cast_fp(sum_lhs_zp) * sum_lhs_scl / sum_out_scl\n            - cast_fp(sum_rhs_zp) * sum_rhs_scl / sum_out_scl\n        )\n        bias = self.squeeze_bias(bias, dst_layout)\n        bias = (\n            cast_fp(bias)\n            - cast_fp(self.fake_op(src_zp, wgh, wgh_layout))\n            - cast_fp(rq_in_zp)\n            + cast_fp(rq_out_zp) * rq_out_scl / rq_in_scl\n        )\n        bias = self.broadcast_to_rank(bias, bias_rank)\n        o_scl = self.broadcast_to_rank(o_scl, bias_rank)\n        act_scl = self.broadcast_to_rank(act_scl, bias_rank)\n        sum_scl = self.broadcast_to_rank(sum_scl, bias_rank)\n\n        zero_zp = relay.const(0, dtype=\"int32\")\n        one_scl = relay.const(1.0, dtype=\"float32\")\n\n        # construct new graph with proper post op ordering\n        gr = tvm.relay.Call(\n            root.op,\n            [src, wgh, zero_zp, zero_zp, one_scl, one_scl],\n            root.attrs,\n            root.type_args,\n            root.span,\n        )\n        gr = relay.op.cast(gr, dtype=\"float32\")\n        gr = gr + bias\n        gr = gr * o_scl\n        gr = relay.op.clip(gr, 0, 255) * act_scl\n        gr = gr + sum_scl * cast_fp(sum_src) if sum_src else gr\n        gr = gr + dst_zp\n        gr = relay.op.cast(gr, dtype=final_dtype)\n        return gr\n\n    @staticmethod\n    def fake_op(zp, wgh, layout):\n        \"\"\"Fake operator implementation for zp broadcast input\"\"\"\n        # Conv:  reduce kernel {OC, IC, KH, KW} -> {OC} in case of group that is still correct\n        # Dense: reduce kernel {OC, IC} -> {OC}\n        wgh_int = relay.op.cast(wgh, dtype=\"int32\")\n        reduced_kernel = relay.op.sum(\n            wgh_int, axis=[layout.index(\"O\")], keepdims=False, exclude=True\n        )\n        return zp * reduced_kernel\n\n    @staticmethod\n    def squeeze_bias(bias, layout):\n        shape = transform.InferTypeLocal(bias).concrete_shape\n        c_position = layout.index(\"C\") - len(layout) + len(shape)\n        squeeze_idxs = [i for i in range(len(shape)) if i != c_position]\n        return relay.op.squeeze(bias, squeeze_idxs)\n\n    @staticmethod\n    def broadcast_to_rank(op, rank):\n        \"\"\"Scalar or 1D tensor are supported\"\"\"\n        shape = transform.InferTypeLocal(op).concrete_shape\n        if len(shape) == 0:\n            return op\n        if len(shape) == 1:\n            return relay.op.expand_dims(op, 1, rank - 1)\n        raise ValueError(\"Unexpected bias rank to broadcast. Only 0 and 1 are supported.\")\n\n\ndef legalize_qnn_for_tachikoma(mod):\n    \"\"\"Transform qnn primitives to Tachikoma compatible form. Eliminate source zero point and apply\n    strict sequence of post ops.\"\"\"\n    mod[\"main\"] = rewrite(LegalizeQnnOpForTachikoma(), mod[\"main\"])\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            # transform.SimplifyInference(),  # TODO: this pass decompose nn.layer_norm\n            # transform.FoldScaleAxis(),  # TODO: fail inside TVM in case of grouped convolutions.\n            transform.FoldConstant(),\n        ]\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    return mod"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/te_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Support a Relay partitioning target using Tensor Expressions.\"\"\"\nfrom typing import Callable, List, Dict\n\nimport tvm\nimport tvm.ir\nfrom tvm import relay\nfrom tvm import te\n\n\n_LowerFunc = Callable[[relay.Call, List[te.Tensor]], te.Tensor]\n_LOWER_MAP: Dict[str, _LowerFunc] = {}\n\n\ndef lower_composite(comp_name: str) -> Callable[[_LowerFunc], _LowerFunc]:\n    \"\"\"Register a lowering function for a given composite function name.\"\"\"\n\n    def _register(f: _LowerFunc) -> _LowerFunc:\n        _LOWER_MAP[comp_name] = f\n        return f\n\n    return _register\n\n\ndef relay_to_runtime(target: tvm.target.Target) -> Callable[[relay.Function], tvm.runtime.Module]:\n    \"\"\"Create a Relay to runtime module lowering function using Tensor Expressions for lowering.\"\"\"\n\n    def _relay_to_runtime(partition: relay.Function) -> tvm.runtime.Module:\n        \"\"\"Compile Relay functions to a runtime module using Tensor Expressions.\"\"\"\n        assert isinstance(partition, relay.Function)\n        assert isinstance(partition.body, relay.Call)\n        assert isinstance(partition.body.op, relay.Function)\n\n        global_name = str(partition.attrs.global_symbol)\n        comp_func = partition.body.op\n        comp_name = comp_func.attrs[\"Composite\"]\n        assert comp_name in _LOWER_MAP\n        assert isinstance(comp_func.body, relay.Call)\n\n        op = comp_func.body\n        inputs = []\n        for i, param in enumerate(comp_func.params):\n            inputs.append(\n                te.placeholder(\n                    param.checked_type.shape,\n                    name=f\"input_{i}\",\n                    dtype=param.checked_type.dtype,\n                )\n            )\n\n        output = _LOWER_MAP[comp_name](op, inputs)\n        prim_func = te.create_prim_func(inputs + [output])\n        return tvm.build(prim_func, target=target, name=global_name)\n\n    return _relay_to_runtime\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/tensorrt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, logging-format-interpolation\n\"\"\"TensorRT supported operators.\"\"\"\nimport logging\nfrom typing import Tuple, List, Dict, Union, Optional, Any, Callable\n\nimport numpy as np  # type: ignore\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import Op\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.dataflow_pattern import is_op, wildcard, is_constant, is_tuple, is_tuple_get_item\nfrom tvm.relay.expr import Call, Constant, TupleGetItem\nfrom tvm.relay.expr_functor import ExprMutator, ExprVisitor\nfrom tvm.relay.op.contrib.register import register_pattern_table\n\nlogger = logging.getLogger(\"TensorRT\")\n\n\ndef is_tensorrt_compiler_enabled() -> bool:\n    return tvm.get_global_func(\"relay.ext.tensorrt.is_runtime_enabled\", True) is not None\n\n\ndef is_tensorrt_runtime_enabled() -> bool:\n    \"\"\"Check if the TensorRT graph executor is present.\n    Returns\n    -------\n    ret: bool\n        True if present, False if not.\n    \"\"\"\n    check_enabled = tvm.get_global_func(\"relay.ext.tensorrt.is_runtime_enabled\", True)\n    if check_enabled:\n        return check_enabled()\n    return False\n\n\ndef get_tensorrt_target() -> tvm.target.Target:\n    \"\"\"Returns the current Target, which must be of kind \"tensorrt\".\"\"\"\n    target = tvm.target.Target.current()\n    if target is None or target.kind.name != \"tensorrt\":\n        # Create the default target.\n        return tvm.target.Target(\"tensorrt\")\n    return target\n\n\ndef get_tensorrt_version() -> Tuple[int, int, int]:\n    \"\"\"Returns the version of TensorRT to assume during compilation.\n    In order of preference this is taken from:\n     - The current \"tensorrt\" target's \"tensorrt_version\" attribute string.\n     - The version linked to the TVM runtime.\n     - (6, 0, 1)\n\n    Returns\n    -------\n    ret: Tuple[int, int, int]\n        TensorRT version as a tuple of (major, minor, patch).\n    \"\"\"\n    # cf logic in tensorrt/codegen.cc::SaveGlobalAttributes\n    # First check for version in target.\n    target = get_tensorrt_target()\n    version = target.attrs[\"tensorrt_version\"]\n    if len(version) == 3:\n        return int(version[0]), int(version[1]), int(version[2])\n    assert len(version) == 0\n\n    # Next, ask runtime for its version.\n    if is_tensorrt_runtime_enabled():\n        get_version = tvm.get_global_func(\"relay.ext.tensorrt.get_version\")\n        version = get_version()\n        assert len(version) == 3\n        return int(version[0]), int(version[1]), int(version[2])\n\n    # Finally, use default.\n    logger.warning(\n        \"TVM was not built against TensorRT and no version was provided in the 'tensorrt' target.\"\n        \"Defaulting to 6.0.1.\"\n    )\n    return (6, 0, 1)\n\n\ndef get_tensorrt_use_implicit_batch_mode() -> bool:\n    \"\"\"Returns the \"use_implicit_batch\" attribute of the current \"tensorrt\" target.\"\"\"\n    target = get_tensorrt_target()\n    return target.attrs[\"use_implicit_batch\"]\n\n\ndef get_tensorrt_remove_no_mac_subgraphs() -> bool:\n    \"\"\"Returns the \"remove_no_mac_subgraphs\" attribute of the current \"tensorrt\" target.\"\"\"\n    target = get_tensorrt_target()\n    return target.attrs[\"remove_no_mac_subgraphs\"]\n\n\ndef get_tensorrt_use_fp16() -> bool:\n    \"\"\"Returns the \"use_fp16\" attribute of the current \"tensorrt\" target.\"\"\"\n    target = get_tensorrt_target()\n    return target.attrs[\"use_fp16\"]\n\n\ndef partition_for_tensorrt(\n    mod: tvm.IRModule,\n    params: Optional[Dict[str, tvm.nd.NDArray]] = None,\n    # CAUTION: Can't use default Target(\"tensorrt\") here since the target kind is only available\n    #          if is_tensorrt_compiler_enabled() == True.\n    target: Optional[tvm.target.Target] = None,\n) -> tvm.IRModule:\n    \"\"\"Partition all functions in mod to greedily offload supported operators to TensorRT.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The module to partition.\n    target : tvm.target.Target\n        A target of kind \"tensorrt\" describing additional partitioning and compilation options.\n    params : Optional[Dict[str, tvm.nd.NDArray]]\n        Constant input parameters.\n\n    Returns\n    -------\n    partitioned_mod : tvm.IRModule\n        The partitioned module.\n\n    \"\"\"\n    assert is_tensorrt_compiler_enabled(), \"Can only partition for TensorRT if it is enabled\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    if target is None:\n        # Use a default target. The get_tensorrt_target() function will similarly create an\n        # equivalent default target when compilation continues after partitioning.\n        target = tvm.target.Target(\"tensorrt\")\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            RemoveDropoutPass(),\n            transform.RemoveUnusedFunctions(),\n            transform.ConvertLayout(\n                {\n                    \"nn.conv1d\": [\"NCW\", \"default\"],\n                    \"nn.conv2d\": [\"NCHW\", \"default\"],\n                    \"nn.conv3d\": [\"NCDHW\", \"default\"],\n                    \"nn.conv2d_transpose\": [\"NCHW\", \"default\"],\n                }\n            ),\n            transform.FoldConstant(),\n            transform.MergeComposite(pattern_table()),\n            transform.AnnotateTarget(\"tensorrt\"),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n            transform.InferType(),\n        ]\n    )\n    with target:\n        mod = seq(mod)\n        mod = prune_tensorrt_subgraphs(mod)\n    return mod\n\n\ndef is_supported_trt_type(typ: Union[tvm.ir.TensorType, tvm.ir.TupleType], op_name: str) -> bool:\n    \"\"\"Check whether a type is supported by TensorRT.\"\"\"\n    supported_dtypes = [\"float32\"]\n    if get_tensorrt_use_fp16():\n        supported_dtypes.append(\"float16\")\n    if isinstance(typ, tvm.ir.TensorType):\n        if typ.dtype not in supported_dtypes:\n            logger.info(f\"{op_name}: Only {supported_dtypes} tensor dtypes are supported.\")\n            return False\n        dims = typ.shape\n        if get_tensorrt_use_implicit_batch_mode():\n            # The first dimension can be Any.\n            dims = dims[1:]\n        for dim in dims:\n            if isinstance(dim, tvm.tir.expr.Any):\n                logger.info(f\"{op_name}: Only statically known tensor shapes are supported.\")\n                return False\n    elif isinstance(typ, tvm.ir.TupleType):\n        for field_type in typ.fields:\n            if not is_supported_trt_type(field_type, op_name):\n                return False\n    else:\n        logger.info(f\"{op_name}: Type {typ} is not supported.\")\n        return False\n    return True\n\n\ndef get_op_name(expr: relay.expr.Expr) -> str:\n    \"\"\"Get the operator name from an expression.\"\"\"\n    if isinstance(expr, Op):\n        return expr.name\n    if isinstance(expr, Call):\n        return get_op_name(expr.op)\n    if isinstance(expr, TupleGetItem):\n        return get_op_name(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return get_op_name(expr.fields[0])\n    return \"\"\n\n\ndef get_args(expr: relay.expr.Expr) -> List[relay.expr.Expr]:\n    \"\"\"Get the arguments from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.args\n    if isinstance(expr, TupleGetItem):\n        return get_args(expr.tuple_value)\n    if isinstance(expr, relay.Tuple):\n        return [arg for args in map(get_args, expr.fields) for arg in args]\n    return []\n\n\ndef get_attrs(expr: relay.expr.Expr) -> Any:\n    \"\"\"Get the attributes from an expression.\"\"\"\n    if isinstance(expr, Call):\n        return expr.attrs\n    if isinstance(expr, TupleGetItem):\n        return get_attrs(expr.tuple_value)\n    return {}\n\n\nCheckFunc = Callable[[Any, List[relay.expr.Expr], str], bool]\n\n\ndef make_predicate(checker: CheckFunc) -> Callable[[relay.expr.Expr], bool]:\n    \"\"\"Returns the pattern predicate which performs the standard checks, then invokes the\n    more primitive checker.\"\"\"\n\n    def predicate(expr: relay.expr.Expr) -> bool:\n        op_name = get_op_name(expr)\n        attrs = get_attrs(expr)\n        args = get_args(expr)\n        if not all([is_supported_trt_type(arg.checked_type, op_name) for arg in args]):\n            return False\n        if not checker(attrs, args, op_name):\n            return False\n        logger.info(f\"{op_name}: Predicate passes\")\n        return True\n\n    return predicate\n\n\nstandard_predicate = make_predicate(lambda attrs, args, op_name: True)\n\n\ndef make_trt_version_checker(version: Tuple[int, int, int]) -> CheckFunc:\n    \"\"\"Helper for ops which require a minimum TRT version\"\"\"\n\n    def checker(attrs: Any, args: List[relay.expr.Expr], op_name: str) -> bool:\n        if get_tensorrt_version() < version:\n            logger.info(\n                f\"{op_name}: requires TensorRT version {'.'.join(map(str, version))} or higher.\"\n            )\n            return False\n        return True\n\n    return checker\n\n\ndef make_and_checker(*checkers: CheckFunc) -> CheckFunc:\n    def checker(attrs: Any, args: List[relay.expr.Expr], op_name: str) -> bool:\n        return all([c(attrs, args, op_name) for c in checkers])\n\n    return checker\n\n\ndef multiply_checker(attrs: Any, args: List[relay.expr.Expr], op_name: str) -> bool:\n    \"\"\"Helper for multiply operations.\"\"\"\n    shapes = [\n        [int(x) if not isinstance(x, tvm.tir.expr.Any) else -1 for x in arg.checked_type.shape]\n        for arg in args\n    ]\n    # TODO(mbs): Follow up\n    # Batched multiply operations don't work in implicit batch mode. The following shapes\n    # have been excluded because they occur in PT MaskRCNN model. The long term solution is\n    # to switch to explicit batch mode after performance regressions are solved.\n    if all([list(map(int, shape)) in [[300, 64, 7, 7], [300, 1, 1, 1]] for shape in shapes]):\n        logger.info(f\"{op_name}: Excluding since problematic in implicit batch mode\")\n        return False\n    return True\n\n\ndef reduce_checker(attrs: Any, args: List[relay.expr.Expr], op_name: str) -> bool:\n    \"\"\"Helper for reduce operations.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and (not attrs.axis or len(attrs.axis) == 0):\n        logger.info(f\"{op_name}: cannot reduce to scalar.\")\n        return False\n    if attrs.exclude:\n        logger.info(f\"{op_name}: exclude not supported.\")\n        return False\n    if get_tensorrt_use_implicit_batch_mode() and any([x == 0 for x in map(int, attrs.axis)]):\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef add_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if add is supported by TensorRT.\"\"\"\n    shapes = [\n        [int(x) if not isinstance(x, tvm.tir.expr.Any) else -1 for x in arg.checked_type.shape]\n        for arg in args\n    ]\n\n    # Scalars require explicit batch mode.\n    if get_tensorrt_use_implicit_batch_mode() and any([len(shape) < 1 for shape in shapes]):\n        logger.info(f\"{op_name}: Scalars not supported in implicit batch mode\")\n        return False\n\n    if (\n        not get_tensorrt_use_implicit_batch_mode()\n        and (isinstance(args[0], Constant) or isinstance(args[1], Constant))\n        and len(shapes[0]) > 0\n        and len(shapes[1]) > 0\n        and shapes[0][0] == shapes[1][0]\n        and shapes[0][0] != 1\n        and (len(shapes[0]) > 3 or len(shapes[1]) > 3)\n    ):\n        logger.info(f\"{op_name}: bug in TRT with adding batched constants.\")\n        return False\n    return True\n\n\ndef batch_norm_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.batch_norm is supported by TensorRT.\"\"\"\n    if len(args[0].checked_type.shape) == 5 and get_tensorrt_version() < (6, 0, 1):\n        logger.info(f\"{op_name}: TensorRT 6.0.1 or higher is required for rank 5 inputs.\")\n        return False\n    if len(args[0].checked_type.shape) > 5:\n        logger.info(f\"{op_name}: Input rank must be 5 or less.\")\n        return False\n    if int(attrs.axis) not in (1, 3):\n        logger.info(f\"{op_name}: axis is {int(attrs.axis)} but must be 1 or 3.\")\n        return False\n    return True\n\n\ndef softmax_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.softmax is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and int(attrs.axis) == 0:\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef conv1d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.conv1d is supported by TensorRT.\"\"\"\n    if not isinstance(args[1], Constant):\n        logger.info(f\"{op_name}: kernel argument must be constant.\")\n        return False\n    if attrs.data_layout != \"NCW\":\n        logger.info(f\"{op_name}: data_layout is {attrs.data_layout} but must be NCW.\")\n        return False\n    if attrs.kernel_layout != \"OIW\":\n        logger.info(f\"{op_name}: kernel_layout is {attrs.kernel_layout} but must be OIW.\")\n        return False\n    return True\n\n\ndef conv2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.conv2d is supported by TensorRT.\"\"\"\n    assert len(args) == 2\n    if not isinstance(args[1], Constant):\n        logger.info(f\"{op_name}: kernel argument must be constant.\")\n        return False\n    if attrs.data_layout != \"NCHW\":\n        logger.info(f\"{op_name}: data_layout is {attrs.data_layout} but must be NCHW.\")\n        return False\n    if attrs.kernel_layout != \"OIHW\":\n        logger.info(f\"{op_name}: kernel_layout is {attrs.kernel_layout} but must be OIHW.\")\n        return False\n    if attrs.out_layout and attrs.out_layout != \"NCHW\":\n        logger.info(f\"{op_name}: out_layout is {attrs.out_layout} but must be NCHW.\")\n        return False\n    return True\n\n\ndef dense_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if dense is supported by TensorRT.\"\"\"\n    if not isinstance(args[1], Constant):\n        logger.info(f\"{op_name}: weight must be constant\")\n        return False\n    input_rank = len(args[0].checked_type.shape)\n    weight_rank = len(args[1].checked_type.shape)\n    if input_rank not in (2, 3, 4):\n        logger.info(f\"{op_name}: input has rank {input_rank} but must be 2, 3 or 4.\")\n        return False\n    if weight_rank != 2:\n        logger.info(f\"{op_name}: weight has rank {weight_rank} but must be 2.\")\n        return False\n    return True\n\n\ndef batch_matmul_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if dense is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and len(args[0].checked_type.shape) != len(\n        args[1].checked_type.shape\n    ):\n        logger.info(f\"{op_name}: requires use_implict_batch=False.\")\n        return False\n    return True\n\n\ndef layer_norm_checker(attrs: Any, args: List[relay.expr.Expr], op_name: str) -> bool:\n    \"\"\"Check if dense is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and int(attrs.axis) == 0:\n        logger.info(f\"{op_name}: requires use_implict_batch=False.\")\n        return False\n    return True\n\n\ndef bias_add_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.bias_add is supported by TensorRT.\"\"\"\n    input_rank = len(args[0].checked_type.shape)\n    if input_rank not in (2, 3, 4):\n        logger.info(f\"{op_name}: input rank is {input_rank} but must be 2, 3 or 4.\")\n        return False\n    return True\n\n\ndef max_pool_2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.max_pool2d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCHW.\")\n        return False\n    if attrs.ceil_mode and get_tensorrt_version() < (5, 1, 5):\n        logger.info(f\"{op_name}: ceil_mode=True requires TensorRT 5.1.5 or greater.\")\n        return False\n    return True\n\n\ndef avg_pool_2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.avg_pool2d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCHW.\")\n        return False\n    if (\n        attrs.count_include_pad\n        and len(attrs.padding) == 4\n        and (\n            int(attrs.padding[0]) != int(attrs.padding[2])\n            or int(attrs.padding[1]) != int(attrs.padding[3])\n        )\n    ):\n        logger.info(\n            f\"{op_name}: inclusive-counted blended or average \"\n            \"pooling is not supported in combination with asymmetric padding\"\n        )\n        return False\n    if attrs.ceil_mode and get_tensorrt_version() < (5, 1, 5):\n        logger.info(f\"{op_name}: ceil_mode=True requires TensorRT 5.1.5 or greater.\")\n        return False\n    return True\n\n\ndef global_max_pool_2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.global_max_pool2d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCHW.\")\n        return False\n    return True\n\n\ndef global_avg_pool_2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.global_avg_pool2d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCHW.\")\n        return False\n    return True\n\n\ndef expand_dims_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if expand_dims is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and int(attrs.axis) == 0:\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef squeeze_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if squeeze is supported by TensorRT.\"\"\"\n    if not attrs.axis:\n        logger.info(f\"{op_name}: must explicitly set axis.\")\n        return False\n    if get_tensorrt_use_implicit_batch_mode() and any([axis == 0 for axis in map(int, attrs.axis)]):\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef concatenate_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if concatenate is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode():\n        if int(attrs.axis) == 0:\n            logger.info(f\"{op_name}: can't modify batch dimension.\")\n            return False\n\n    if not isinstance(args[0], relay.Tuple):\n        logger.info(\"f{op_name}: concatenate must be applied to a literal tuple\")\n        return False\n\n    for tuple_input in args[0].fields:\n        if isinstance(tuple_input, Constant):\n            logger.info(f\"{op_name}: can't concatenate tensors with constants.\")\n            return False\n\n    return True\n\n\ndef split_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if split is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and int(attrs.axis) == 0:\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef conv2d_transpose_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.conv2d_transpose is supported by TensorRT.\"\"\"\n    if attrs.data_layout != \"NCHW\":\n        logger.info(f\"{op_name}: data_layout is {attrs.data_layout} but must be NCHW.\")\n        return False\n    if attrs.kernel_layout != \"OIHW\":\n        logger.info(f\"{op_name}: kernel_layout is {attrs.kernel_layout} but must be OIHW.\")\n        return False\n    if attrs.out_layout and attrs.out_layout != \"NCHW\":\n        logger.info(f\"{op_name}: out_layout is {attrs.out_layout} but must be NCHW.\")\n        return False\n    if attrs.dilation and any([rate != 1 for rate in map(int, attrs.dilation)]):\n        logger.info(f\"{op_name}: dilation rate must be 1.\")\n        return False\n    return True\n\n\ndef transpose_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if transpose is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode() and int(attrs.axes[0]) != 0:\n        logger.info(f\"{op_name}: can't modify batch dimension.\")\n        return False\n    return True\n\n\ndef layout_transform_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if layout_transform is supported by TensorRT.\"\"\"\n    if (attrs.src_layout, attrs.dst_layout) not in [\n        (\"NCHW\", \"NHWC\"),\n        (\"NHWC\", \"NCHW\"),\n        (\"NDHWC\", \"NCDHW\"),\n        (\"NCDHW\", \"NDHWC\"),\n    ]:\n        logger.info(f\"{op_name}: {attrs.src_layout} to {attrs.dst_layout} is not supported.\")\n        return False\n    return True\n\n\ndef reshape_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if reshape is supported by TensorRT.\"\"\"\n    if any([x < -1 for x in map(int, attrs.newshape)]):\n        logger.info(f\"{op_name}: new shape dims must be explicit.\")\n        return False\n    if get_tensorrt_use_implicit_batch_mode():\n        shape = args[0].checked_type.shape\n        new_shape = attrs.newshape\n        if len(new_shape) == 0 or len(shape) == 0:\n            logger.info(f\"{op_name}: Can't reshape to or from scalar.\")\n            return False\n        dynamic_reshape = any([isinstance(x, tvm.tir.expr.Any) for x in shape])\n\n        if dynamic_reshape:\n            # Make sure that the batch dim is unmodified.\n            if int(new_shape[0]) < 0:\n                for shape_val, new_shape_val in zip(shape[1:], new_shape[1:]):\n                    if not (\n                        isinstance(shape_val, (int, tvm.tir.expr.IntImm))\n                        and isinstance(new_shape_val, (int, tvm.tir.expr.IntImm))\n                        and int(shape_val) == int(new_shape_val)\n                    ):\n                        logger.info(f\"{op_name}: can't modify batch dimension\")\n                        return False\n            elif int(new_shape[0]) > 0:\n                # Currently we only allow dim[0] to be Any, so this branch will always be False\n                if not (\n                    isinstance(shape[0], (int, tvm.tir.expr.IntImm))\n                    and isinstance(new_shape[0], (int, tvm.tir.expr.IntImm))\n                    and int(shape[0]) == int(new_shape[0])\n                ):\n                    logger.info(f\"{op_name}: can't modify batch dimension\")\n                    return False\n        else:\n            shape = list(map(int, shape))\n            new_shape = list(map(int, new_shape))\n\n            # TRT cannot modify batch dimension.\n            original_volume = np.prod(shape)\n            # First, resolve 0.\n            for i, value in enumerate(new_shape):\n                if value == 0:\n                    new_shape[i] = shape[i]\n            # Resolve -1.\n            for i, value in enumerate(new_shape):\n                if value == -1:\n                    new_shape[i] = original_volume // np.prod([x for x in new_shape if x != -1])\n            # Remove batch dimension and see if volumes match\n            if shape[0] != new_shape[0]:\n                logger.info(f\"{op_name}: can't modify batch dimension.\")\n                return False\n    return True\n\n\ndef pad_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.pad is supported by TensorRT.\"\"\"\n    pad_value = args[1]\n    if not isinstance(pad_value, relay.Constant):\n        logger.info(f\"{op_name}: pad argument must be constant\")\n        return False\n    pad_value = pad_value.data.numpy().item()\n    if attrs.pad_mode != \"constant\":\n        logger.info(f\"{op_name}: pad mode is {attrs.pad_mode} but must be constant.\")\n        return False\n    if pad_value > 0.0:\n        logger.info(f\"{op_name}: pad value is {pad_value} but must be 0.0.\")\n        return False\n    if len(attrs.pad_width) not in [4, 5]:\n        logger.info(f\"{op_name}: can only pad 4D or 5D inputs\")\n        return False\n    if any([x != 0 for x in attrs.pad_width[0]]) or any([x != 0 for x in attrs.pad_width[1]]):\n        logger.info(f\"{op_name}: can't pad batch or channel dimensions.\")\n        return False\n    if len(attrs.pad_width) == 5 and any([x != 0 for x in attrs.pad_width[2]]):\n        logger.info(f\"{op_name}: can only pad last two dimensions for 5D inputs.\")\n        return False\n    return True\n\n\ndef strided_slice_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if strided_slice is supported by TensorRT.\"\"\"\n    if get_tensorrt_use_implicit_batch_mode():\n        batch_dim_begin_modified = attrs.begin[0] is not None and int(attrs.begin[0]) != 0\n        batch_dim_end_modified = (\n            attrs.end[0] is not None\n            and int(attrs.end[0]) != -1\n            and int(attrs.end[0]) != int(args[0].checked_type.shape[0])\n        )\n        if batch_dim_begin_modified or batch_dim_end_modified:\n            logger.info(f\"{op_name}: can't modify batch dimension.\")\n            return False\n    if any([x is not None and x <= 0 for x in attrs.strides]):\n        logger.info(f\"{op_name}: stride must be positive\")\n        return False\n    for i in range(0, len(args[0].checked_type.shape)):\n        begin = int(attrs.begin[i])\n        if attrs.slice_mode == \"end\":\n            end = (\n                int(attrs.end[i])\n                if attrs.end[i] is not None and int(attrs.end[i]) != -1\n                else args[0].checked_type.shape[i]\n            )\n            size = int(end) - int(begin)\n        elif attrs.slice_mode == \"size\":\n            size = (\n                int(attrs.end[i])\n                if attrs.end[i] is not None and int(attrs.end[i]) != -1\n                else args[0].checked_type.shape[i] - begin\n            )\n        else:\n            logger.warning(f\"{op_name}: unknown slice mode encountered\")\n            size = 1\n\n        if int(size) < 1:\n            logger.info(f\"{op_name}: size of slice must be at least 1\")\n            return False\n\n    return True\n\n\ndef adaptive_max_pool2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.adaptive_max_pool2d is supported by TensorRT.\"\"\"\n    if len(attrs.output_size) == 0 or any([size != 1 for size in map(int, attrs.output_size)]):\n        logger.info(f\"{op_name}: output size must be (1, 1).\")\n        return False\n    return True\n\n\ndef adaptive_avg_pool2d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.adaptive_avg_pool2d is supported by TensorRT.\"\"\"\n    if len(attrs.output_size) == 0 or any([size != 1 for size in map(int, attrs.output_size)]):\n        logger.info(f\"{op_name}: output size must be (1, 1).\")\n        return False\n    return True\n\n\ndef conv3d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.conv3d is supported by TensorRT.\"\"\"\n    if not isinstance(args[1], Constant):\n        logger.info(f\"{op_name}: kernel argument must be constant.\")\n        return False\n    if attrs.data_layout != \"NCDHW\":\n        logger.info(f\"{op_name}: data_layout is {attrs.data_layout} but must be NCDHW.\")\n        return False\n    if attrs.kernel_layout != \"OIDHW\":\n        logger.info(f\"{op_name}: kernel_layout is {attrs.kernel_layout} but must be OIDHW.\")\n        return False\n    if attrs.out_layout and attrs.out_layout != \"NCDHW\":\n        logger.info(f\"{op_name}: out_layout is {attrs.out_layout} but must be NCDHW.\")\n        return False\n    return True\n\n\ndef max_pool_3d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.max_pool3d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCDHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCDHW.\")\n        return False\n    return True\n\n\ndef avg_pool_3d_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.avg_pool3d is supported by TensorRT.\"\"\"\n    if attrs.layout != \"NCDHW\":\n        logger.info(f\"{op_name}: layout is {attrs.layout} but must be NCDHW.\")\n        return False\n    return True\n\n\ndef conv3d_transpose_checker(\n    attrs: Any, args: List[relay.expr.Expr], op_name: str\n) -> bool:  # pylint: disable=unused-variable\n    \"\"\"Check if nn.conv3d_transpose is supported by TensorRT.\"\"\"\n    if attrs.data_layout != \"NCDHW\":\n        logger.info(f\"{op_name}: data_layout is {attrs.data_layout} but must be NCDHW.\")\n        return False\n    if attrs.kernel_layout != \"OIDHW\":\n        logger.info(f\"{op_name}: kernel_layout is {attrs.kernel_layout} but must be OIDHW.\")\n        return False\n    if attrs.out_layout and attrs.out_layout != \"NCDHW\":\n        logger.info(f\"{op_name}: out_layout is {attrs.out_layout} but must be NCDHW.\")\n        return False\n    if attrs.dilation and any([rate != 1 for rate in map(int, attrs.dilation)]):\n        logger.info(f\"{op_name}: dilation rate must be 1.\")\n        return False\n    if attrs.output_padding and any([x != 0 for x in map(int, attrs.output_padding)]):\n        logger.info(f\"{op_name}: output padding is not supported.\")\n        return False\n    return True\n\n\ndef unary_op_pattern(op: relay.expr.Expr) -> relay.dataflow_pattern.DFPattern:\n    \"\"\"Matches unary operation\"\"\"\n    return is_op(op)(wildcard())\n\n\ndef unary_op_pattern_with_any_tuple(op: relay.expr.Expr) -> relay.dataflow_pattern.DFPattern:\n    \"\"\"Matches unary operation with literal tuple argument\"\"\"\n    return is_op(op)(is_tuple(None))\n\n\ndef binary_op_pattern(op: relay.expr.Expr) -> relay.dataflow_pattern.DFPattern:\n    \"\"\"Matches binary operation\"\"\"\n    return is_op(op)(wildcard(), wildcard())\n\n\ndef binary_op_pattern_with_const(op: relay.expr.Expr) -> relay.dataflow_pattern.DFPattern:\n    \"\"\"Matches binary operation with rhs arg a constant\"\"\"\n    return is_op(op)(wildcard(), is_constant())\n\n\ndef proj_five_op_pattern_with_const(op: relay.expr.Expr) -> relay.dataflow_pattern.DFPattern:\n    return is_tuple_get_item(\n        is_op(op)(wildcard(), is_constant(), is_constant(), is_constant(), is_constant()), 0\n    )\n\n\n@register_pattern_table(\"tensorrt\")\ndef pattern_table() -> List[\n    Tuple[str, relay.dataflow_pattern.DFPattern, Callable[[relay.expr.Call], bool]]\n]:\n    \"\"\"Get the Tensorrt compiler pattern table for supported ops.\"\"\"\n\n    return [\n        (\n            \"tensorrt.nn.conv3d\",\n            binary_op_pattern_with_const(\"nn.conv3d\"),\n            make_predicate(make_and_checker(make_trt_version_checker((6, 0, 1)), conv3d_checker)),\n        ),\n        (\n            \"tensorrt.nn.conv2d\",\n            binary_op_pattern_with_const(\"nn.conv2d\"),\n            make_predicate(conv2d_checker),\n        ),\n        (\n            \"tensorrt.nn.conv1d\",\n            binary_op_pattern_with_const(\"nn.conv1d\"),\n            make_predicate(conv1d_checker),\n        ),\n        (\n            \"tensorrt.nn.conv2d_transpose\",\n            binary_op_pattern(\"nn.conv2d_transpose\"),\n            make_predicate(conv2d_transpose_checker),\n        ),\n        (\"tensorrt.squeeze\", binary_op_pattern(\"squeeze\"), make_predicate(squeeze_checker)),\n        (\"tensorrt.add\", binary_op_pattern(\"add\"), make_predicate(add_checker)),\n        (\n            \"tensorrt.nn.dense\",\n            binary_op_pattern_with_const(\"nn.dense\"),\n            make_predicate(dense_checker),\n        ),\n        (\n            \"tensorrt.nn.bias_add\",\n            binary_op_pattern(\"nn.bias_add\"),\n            make_predicate(bias_add_checker),\n        ),\n        (\n            \"tensorrt.nn.batch_matmul\",\n            binary_op_pattern(\"nn.batch_matmul\"),\n            make_predicate(batch_matmul_checker),\n        ),\n        (\"tensorrt.divide\", binary_op_pattern(\"divide\"), standard_predicate),\n        (\"tensorrt.multiply\", binary_op_pattern(\"multiply\"), make_predicate(multiply_checker)),\n        (\"tensorrt.subtract\", binary_op_pattern(\"subtract\"), standard_predicate),\n        (\"tensorrt.power\", binary_op_pattern(\"power\"), standard_predicate),\n        (\"tensorrt.maximum\", binary_op_pattern(\"maximum\"), standard_predicate),\n        (\"tensorrt.minimum\", binary_op_pattern(\"minimum\"), standard_predicate),\n        (\"tensorrt.nn.relu\", unary_op_pattern(\"nn.relu\"), standard_predicate),\n        (\n            \"tensorrt.nn.leaky_relu\",\n            unary_op_pattern(\"nn.leaky_relu\"),\n            make_predicate(make_trt_version_checker((5, 1, 5))),\n        ),\n        (\"tensorrt.nn.pad\", unary_op_pattern(\"nn.pad\"), standard_predicate),\n        (\"tensorrt.sigmoid\", unary_op_pattern(\"sigmoid\"), standard_predicate),\n        (\"tensorrt.tanh\", unary_op_pattern(\"tanh\"), standard_predicate),\n        (\"tensorrt.exp\", unary_op_pattern(\"exp\"), standard_predicate),\n        (\"tensorrt.log\", unary_op_pattern(\"log\"), standard_predicate),\n        (\"tensorrt.sqrt\", unary_op_pattern(\"sqrt\"), standard_predicate),\n        (\"tensorrt.abs\", unary_op_pattern(\"abs\"), standard_predicate),\n        (\"tensorrt.negative\", unary_op_pattern(\"negative\"), standard_predicate),\n        (\"tensorrt.nn.batch_flatten\", unary_op_pattern(\"nn.batch_flatten\"), standard_predicate),\n        (\"tensorrt.clip\", unary_op_pattern(\"clip\"), standard_predicate),\n        (\n            \"tensorrt.sin\",\n            unary_op_pattern(\"sin\"),\n            make_predicate(make_trt_version_checker((5, 1, 5))),\n        ),\n        (\n            \"tensorrt.cos\",\n            unary_op_pattern(\"cos\"),\n            make_predicate(make_trt_version_checker((5, 1, 5))),\n        ),\n        (\n            \"tensorrt.atan\",\n            unary_op_pattern(\"atan\"),\n            make_predicate(make_trt_version_checker((5, 1, 5))),\n        ),\n        (\n            \"tensorrt.ceil\",\n            unary_op_pattern(\"ceil\"),\n            make_predicate(make_trt_version_checker((5, 1, 5))),\n        ),\n        (\"tensorrt.floor\", unary_op_pattern(\"floor\"), standard_predicate),\n        (\n            \"tensorrt.erf\",\n            unary_op_pattern(\"erf\"),\n            make_predicate(make_trt_version_checker((7, 0, 0))),\n        ),\n        (\"tensorrt.sum\", unary_op_pattern(\"sum\"), make_predicate(reduce_checker)),\n        (\"tensorrt.prod\", unary_op_pattern(\"prod\"), make_predicate(reduce_checker)),\n        (\"tensorrt.max\", unary_op_pattern(\"max\"), make_predicate(reduce_checker)),\n        (\"tensorrt.min\", unary_op_pattern(\"min\"), make_predicate(reduce_checker)),\n        (\"tensorrt.max\", unary_op_pattern(\"max\"), make_predicate(reduce_checker)),\n        (\"tensorrt.mean\", unary_op_pattern(\"mean\"), make_predicate(reduce_checker)),\n        (\n            \"tensorrt.concatenate\",\n            unary_op_pattern_with_any_tuple(\"concatenate\"),\n            make_predicate(concatenate_checker),\n        ),\n        (\n            \"tensorrt.expand_dims\",\n            unary_op_pattern(\"expand_dims\"),\n            make_predicate(expand_dims_checker),\n        ),\n        (\n            \"tensorrt.layout_transform\",\n            unary_op_pattern(\"layout_transform\"),\n            make_predicate(layout_transform_checker),\n        ),\n        (\"tensorrt.transpose\", unary_op_pattern(\"transpose\"), make_predicate(transpose_checker)),\n        (\"tensorrt.reshape\", unary_op_pattern(\"reshape\"), make_predicate(reshape_checker)),\n        (\"tensorrt.split\", unary_op_pattern(\"split\"), make_predicate(split_checker)),\n        (\"tensorrt.nn.pad\", unary_op_pattern(\"nn.pad\"), make_predicate(pad_checker)),\n        (\n            \"tensorrt.strided_slice\",\n            unary_op_pattern(\"strided_slice\"),\n            make_predicate(\n                make_and_checker(make_trt_version_checker((5, 1, 5)), strided_slice_checker)\n            ),\n        ),\n        (\n            \"tensorrt.nn.adaptive_avg_pool2d\",\n            unary_op_pattern(\"nn.adaptive_avg_pool2d\"),\n            make_predicate(adaptive_avg_pool2d_checker),\n        ),\n        (\n            \"tensorrt.nn.adaptive_max_pool2d\",\n            unary_op_pattern(\"nn.adaptive_max_pool2d\"),\n            make_predicate(adaptive_max_pool2d_checker),\n        ),\n        (\n            \"tensorrt.nn.max_pool3d\",\n            unary_op_pattern(\"nn.max_pool3d\"),\n            make_predicate(\n                make_and_checker(make_trt_version_checker((6, 0, 1)), max_pool_3d_checker)\n            ),\n        ),\n        (\n            \"tensorrt.nn.avg_pool3d\",\n            unary_op_pattern(\"nn.avg_pool3d\"),\n            make_predicate(\n                make_and_checker(make_trt_version_checker((6, 0, 1)), avg_pool_3d_checker)\n            ),\n        ),\n        (\n            \"tensorrt.nn.conv3d_transpose\",\n            unary_op_pattern(\"nn.conv3d_transpose\"),\n            make_predicate(\n                make_and_checker(make_trt_version_checker((6, 0, 1)), conv3d_transpose_checker)\n            ),\n        ),\n        (\"tensorrt.nn.softmax\", unary_op_pattern(\"nn.softmax\"), make_predicate(softmax_checker)),\n        (\n            \"tensorrt.nn.layer_norm\",\n            unary_op_pattern(\"nn.layer_norm\"),\n            make_predicate(layer_norm_checker),\n        ),\n        (\n            \"tensorrt.nn.max_pool2d\",\n            unary_op_pattern(\"nn.max_pool2d\"),\n            make_predicate(max_pool_2d_checker),\n        ),\n        (\n            \"tensorrt.nn.avg_pool2d\",\n            unary_op_pattern(\"nn.avg_pool2d\"),\n            make_predicate(avg_pool_2d_checker),\n        ),\n        (\n            \"tensorrt.nn.global_max_pool2d\",\n            unary_op_pattern(\"nn.global_max_pool2d\"),\n            make_predicate(global_max_pool_2d_checker),\n        ),\n        (\n            \"tensorrt.nn.global_avg_pool2d\",\n            unary_op_pattern(\"nn.global_avg_pool2d\"),\n            make_predicate(global_avg_pool_2d_checker),\n        ),\n        (\n            \"tensorrt.nn.batch_norm\",\n            proj_five_op_pattern_with_const(\"nn.batch_norm\"),\n            make_predicate(batch_norm_checker),\n        ),\n    ]\n\n\nclass IsComputeIntensiveGraph(ExprVisitor):\n    \"\"\"\n    Visits the Graph recursively and checks if it contains compute heavy ops like convolutions and\n    its transpose, dense and batch mat-mul.\n    \"\"\"\n\n    def __init__(self) -> None:\n        ExprVisitor.__init__(self)\n        self.is_compute_intensive = False\n\n    def visit_call(self, call: relay.expr.Call) -> None:\n        compute_intensive_ops = {\n            \"nn.conv1d\",\n            \"nn.conv2d\",\n            \"nn.conv2d_transpose\",\n            \"nn.conv3d\",\n            \"nn.conv3d_transpose\",\n            \"nn.dense\",\n            \"nn.batch_matmul\",\n            \"sum\",\n            \"prod\",\n            \"max\",\n            \"min\",\n            \"mean\",\n        }\n        if isinstance(call.op, tvm.tir.op.Op):\n            if str(call.op) in compute_intensive_ops:\n                self.is_compute_intensive = True\n\n        return super().visit_call(call)\n\n    def is_graph_compute_intensive(self, subgraph: relay.expr.Expr) -> bool:\n        \"\"\"\n        This function recursively visits the graph and checks if it's compute intensive\"\n        \"\"\"\n        self.visit(subgraph)\n        return self.is_compute_intensive\n\n\ndef is_valid_subgraph(params: List[relay.expr.Var], body: relay.expr.Expr) -> bool:\n    \"\"\"Final check on whether the subgraph is valid and should be offloaded to TensorRT.\"\"\"\n    # Remove invalid subgraphs for implicit batch mode.\n    if get_tensorrt_use_implicit_batch_mode():\n        input_batch_sizes = []\n        for var in params:\n            # In implicit batch mode, all inputs must have same batch size\n            # TODO: (codeislife99) : Fix different dynamic batch size inputs\n            if isinstance(var.checked_type, relay.TupleType):\n                for tupe_type in var.checked_type.fields:\n                    # Scalar inputs not allowed\n                    if len(tupe_type.shape) == 0:\n                        logger.info(\"tensorrt: scalar inputs not supported\")\n                        return False\n\n                    if not isinstance(tupe_type.shape[0], tvm.tir.expr.Any):\n                        input_batch_sizes.append(int(tupe_type.shape[0]))\n            else:\n                # Scalar inputs not allowed\n                if len(var.checked_type.shape) == 0:\n                    logger.info(\"tensorrt: scalar inputs not supported\")\n                    return False\n                if not isinstance(var.checked_type.shape[0], tvm.tir.expr.Any):\n                    input_batch_sizes.append(int(var.checked_type.shape[0]))\n\n        if len(input_batch_sizes) > 1 and len(set(input_batch_sizes)) != 1:\n            logger.info(\"tensorrt: inputs have different batch sizes: %s\", input_batch_sizes)\n            return False\n\n    if get_tensorrt_remove_no_mac_subgraphs():\n        if not IsComputeIntensiveGraph().is_graph_compute_intensive(body):\n            logger.info(\"tensorrt: not a compute-intensize sub-graph\")\n            return False\n\n    return True\n\n\ndef prune_tensorrt_subgraphs(mod: tvm.IRModule) -> tvm.IRModule:\n    \"\"\"\n    Un-partition those partitions which:\n     - have no multiply-accumulates (if remove_no_mac_subgraphs is True)\n     - can't actually be supported by TensorRT now that we see the whole partition.\"\"\"\n    global_vars_to_inline = [\n        gv\n        for gv in mod.get_global_vars()\n        if mod[gv].attrs\n        and mod[gv].attrs[\"Compiler\"] == \"tensorrt\"\n        and not is_valid_subgraph(mod[gv].params, mod[gv].body)\n    ]\n    return relay.transform.InlineCompilerFunctionsBoundTo(global_vars_to_inline)(mod)\n\n\nclass RemoveDropout(ExprMutator):\n    \"\"\"\n    Removes all nn.dropout from an expr.\n    \"\"\"\n\n    def visit_tuple_getitem(self, op: TupleGetItem) -> relay.expr.Expr:\n        visit = super().visit_tuple_getitem(op)\n        if visit.index != 0:\n            return visit\n        if (\n            isinstance(visit.tuple_value, Call)\n            and isinstance(visit.tuple_value.op, Op)\n            and visit.tuple_value.op.name == \"nn.dropout\"\n            and visit.index == 0\n        ):\n            return visit.tuple_value.args[0]\n        return visit\n\n\n@transform.function_pass(opt_level=0)\nclass RemoveDropoutPass:\n    def transform_function(\n        self, func: relay.function.Function, mod: tvm.IRModule, _: tvm.transform.PassContext\n    ) -> relay.function.Function:\n        return RemoveDropout().visit(func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/contrib/vitis_ai.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, no-else-return, E1102\n\"\"\"Vitis-AI codegen annotation of supported operators\"\"\"\n\nimport warnings\nimport numpy as np\n\nfrom tvm import relay\nimport tvm._ffi\nfrom tvm.relay import transform\nfrom tvm.relay.expr import Tuple, TupleGetItem\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\n\n# Placeholder for PyXIR module\npyxir = None\n\n\ndef enabled():\n    \"\"\"Return whether Vitis-AI support is available\"\"\"\n    if not tvm.get_global_func(\"relay.ext.vitis_ai.available\", True):\n        print(\"Skip because Vitis-AI codegen is not available.\")\n        return False\n    return True\n\n\n@transform.function_pass(opt_level=0)\nclass VitisAIAnnotationPass:\n    \"\"\"Responsible for annotating Relay expressions for Vitis-AI DPU accelerators\n\n    Parameters\n    ----------\n    compiler : str\n        The compiler name used for annotations (`vitis_ai`).\n    dpu_target : str\n        The Vitis AI DPU target identifier.\n    params : dict\n        A dictionary containing the module's parameters.\n    \"\"\"\n\n    def __init__(self, compiler, dpu_target, params):\n        global pyxir\n        try:\n            if pyxir is None:\n                pyxir = __import__(\"pyxir\")\n                __import__(\"pyxir.frontend.tvm\")\n        except ImportError:\n            # add \"from None\" to silence\n            # \"During handling of the above exception, another exception occurred\"\n            raise ImportError(\n                \"The pyxir package is required for the Vitis AI backend. \"\n                \"Please install it first. \"\n                \"Help: (https://tvm.apache.org/docs/deploy/vitis_ai.html) \"\n            ) from None\n\n        self.compiler = compiler\n        self.dpu_target = dpu_target\n        self.params = params\n\n    def transform_function(self, func, mod, ctx):\n        \"\"\"Transform function for annotating Relay module\"\"\"\n        annotator = self\n\n        class Annotator(tvm.relay.ExprMutator):\n            \"\"\"Annotator for Vitis-AI DPU accelerators\"\"\"\n\n            def visit_tuple(self, tup):\n                \"\"\"Add compiler_begin and compiler_end annotations to Tuple\"\"\"\n                field_list = []\n                cond = int(hash(tup))\n                for field in tup.fields:\n                    if cond in annotator.relay_ids:\n                        field_list.append(compiler_begin(super().visit(field), annotator.compiler))\n                    else:\n                        field_list.append(super().visit(field))\n                if cond in annotator.relay_ids:\n                    return compiler_end(Tuple(field_list), annotator.compiler)\n                else:\n                    return Tuple(field_list)\n\n            def visit_tuple_getitem(self, op):\n                \"\"\"Add compiler_begin and compiler_end annotations to TupleGetItem\"\"\"\n                if int(hash(op.tuple_value)) in annotator.relay_ids:\n                    tuple_value = compiler_begin(super().visit(op.tuple_value), annotator.compiler)\n                    return compiler_end(TupleGetItem(tuple_value, op.index), annotator.compiler)\n                else:\n                    tuple_value = super().visit(op.tuple_value)\n                    return TupleGetItem(tuple_value, op.index)\n\n            def visit_call(self, call):\n                \"\"\"Add compiler_begin and compiler_end annotations to the Call expr\"\"\"\n                if int(hash(call)) in annotator.relay_ids:\n                    new_args = []\n                    for arg in call.args:\n                        ann = compiler_begin(super().visit(arg), annotator.compiler)\n                        new_args.append(ann)\n                    new_call = relay.Call(call.op, new_args, call.attrs, call.type_args)\n                    return compiler_end(new_call, annotator.compiler)\n\n                else:\n                    return super().visit_call(call)\n\n        xgraph = pyxir.frontend.tvm.from_relay(mod, self.params, postprocessing=None)\n        xgraph = pyxir.partition(xgraph, targets=[self.dpu_target])\n\n        layers = xgraph.get_layers()\n        relay_ids = [\n            list(np.array(layer.attrs[\"relay_id\"]).flatten())\n            for layer in layers\n            if layer.target == self.dpu_target\n        ]\n        self.relay_ids = [item for sublist in relay_ids for item in sublist]\n\n        return Annotator().visit(func)\n\n\ndef annotation(mod, params, target):\n    \"\"\"DEPRECATED\n\n    Annotate Relay expression for offloading operators to Vitis AI DPU accelerators\n    NOTE: This function does the same as the next one (`partition_for_vitis_ai`) but is\n    still here for backward compatibility\"\"\"\n    # We need type information for supporting models that contain operations that don't\n    #   have a Relay to XLayer translation\n    warnings.warn(\n        \"tvm.relay.op.contrib.vitis_ai.annotation() is being deprecated.\"\n        \" Please use tvm.relay.op.contrib.vitis_ai.partition_for_vitis_ai() instead. \"\n        \" Check out https://tvm.apache.org/docs/deploy/vitis_ai.html for documentation. \"\n    )\n    mod = relay.transform.InferType()(mod)\n    mod = VitisAIAnnotationPass(\"vitis_ai\", target, params)(mod)\n    return mod\n\n\ndef partition_for_vitis_ai(mod, params=None, dpu=None, **opts):\n    \"\"\"Partition the Relay expression for offloading operators to Vitis AI DPU\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n    dpu : str\n        The DPU identifier (e.g. DPUCZDX8G-zcu104, DPUCADF8H)\n\n    Returns\n    -------\n    ret : Module\n    \"\"\"\n\n    if dpu is None:\n        raise ValueError(\"Please pass Vitis AI DPU identifier to the partitioning function\")\n\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    desired_layouts_in_partition = {\n        \"nn.conv2d\": [\"NHWC\", \"default\"],\n        \"nn.upsampling\": [\"NHWC\"],\n        \"image.resize2d\": [\"NHWC\"],\n    }\n    desired_layouts_in_main = {\n        \"nn.conv2d\": [\"NCHW\", \"default\"],\n        \"nn.upsampling\": [\"NCHW\"],\n        \"image.resize2d\": [\"NCHW\"],\n    }\n    seq = tvm.transform.Sequential(\n        [\n            transform.RemoveUnusedFunctions(),\n            transform.ConvertLayout(desired_layouts_in_partition),\n            transform.FoldConstant(),\n            transform.InferType(),\n            VitisAIAnnotationPass(\"vitis_ai\", dpu, params),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n            transform.RemoveUnusedFunctions(),\n            transform.ConvertLayout(desired_layouts_in_main),\n            transform.FoldConstant(),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        return seq(mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay namespace containing dynamic ops.\"\"\"\n\nfrom . import _algorithm\nfrom . import _transform\nfrom . import _tensor\n\nfrom . import image\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/_algorithm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"Definition of classic algorithms\"\n# pylint: disable=invalid-name,unused-argument\nfrom __future__ import absolute_import\n\nfrom tvm.te.hybrid import script\nfrom tvm.runtime import convert\n\nfrom .. import strategy\nfrom .. import op as _reg\nfrom ..op import OpPattern, register_pattern\nfrom ..op import register_strategy\n\n# topk\nregister_strategy(\"dyn.topk\", strategy.topk_strategy)\nregister_pattern(\"dyn.topk\", OpPattern.OPAQUE)\n\n\n@script\ndef _topk_shape_func_input_data(data, k, axis):\n    ndim = len(data.shape)\n    val_out = output_tensor((ndim,), \"int64\")\n    indices_out = output_tensor((ndim,), \"int64\")\n\n    for i in const_range(ndim):\n        if i != axis:\n            val_out[i] = int64(data.shape[i])\n            indices_out[i] = int64(data.shape[i])\n        else:\n            if k[0] < 1:\n                val_out[i] = int64(data.shape[i])\n                indices_out[i] = int64(data.shape[i])\n            else:\n                val_out[i] = int64(k[0])\n                indices_out[i] = int64(k[0])\n    return val_out, indices_out\n\n\n@_reg.register_shape_func(\"dyn.topk\", True)\ndef topk_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for topk.\n    \"\"\"\n    axis = attrs.axis\n    if axis < 0:\n        axis += len(inputs[0].shape)\n    val_out, indices_out = _topk_shape_func_input_data(inputs[0], inputs[1], convert(axis))\n\n    ret_type = attrs.ret_type\n    if ret_type == \"both\":\n        ret = [val_out, indices_out]\n    elif ret_type == \"values\":\n        ret = [val_out]\n    else:\n        ret = [indices_out]\n\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.dyn._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/_tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, len-as-condition\n\"\"\"Backend compiler related feature registration for dynamic ops\"\"\"\n\nfrom tvm import topi\n\nfrom ..op import register_shape_func, register_compute\nfrom ..op import register_broadcast_schedule\nfrom ..op import register_pattern, OpPattern\nfrom .._tensor import full_shape_func, no_data_full_shape_func\n\n# ones\n@register_compute(\"dyn.ones\")\ndef ones_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.full(output_type.shape, output_type.dtype, 1.0)]\n\n\nregister_broadcast_schedule(\"dyn.ones\")\nregister_pattern(\"dyn.ones\", OpPattern.ELEMWISE)\n\n\n@register_compute(\"dyn.zeros\")\ndef zeros_compute(attrs, inputs, output_type):\n    assert len(inputs) == 1\n    return [topi.full(output_type.shape, output_type.dtype, 0.0)]\n\n\nregister_broadcast_schedule(\"dyn.zeros\")\nregister_pattern(\"dyn.zeros\", OpPattern.ELEMWISE)\n\nregister_shape_func(\"dyn.broadcast_to\", True, full_shape_func)\nregister_shape_func(\"dyn.ones\", True, no_data_full_shape_func)\nregister_shape_func(\"dyn.zeros\", True, no_data_full_shape_func)\nregister_shape_func(\"dyn.full\", True, full_shape_func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Backend compiler related feature registration\"\"\"\n# pylint: disable=invalid-name,unused-argument, len-as-condition, too-many-nested-blocks, too-many-local-variables, too-many-arguments\nfrom __future__ import absolute_import\n\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\n\nfrom .. import op as _reg\n\n_reg.register_broadcast_schedule(\"dyn.broadcast_to\")\n_reg.register_injective_schedule(\"dyn.reshape\")\n_reg.register_injective_schedule(\"dyn.expand_dims\")\n_reg.register_injective_schedule(\"dyn.squeeze\")\n_reg.register_broadcast_schedule(\"dyn.tile\")\n_reg.register_injective_schedule(\"dyn.one_hot\")\n_reg.register_injective_schedule(\"dyn.full\")\n_reg.register_injective_schedule(\"dyn.strided_slice\")\n_reg.register_injective_schedule(\"dyn.sparse_to_dense\")\n\n\n@script\ndef _reshape_shape_func_input_data(data_shape, newshape, ndim, allowzero):\n    out = output_tensor((ndim,), \"int64\")\n    src_idx = 0\n    dst_idx = 0\n    infer_idx = -1\n    copy = False\n    skip = 0\n    for i in const_range(len(newshape)):\n        if skip > 0:\n            skip -= 1\n        elif newshape[i] > 0:\n            out[dst_idx] = int64(newshape[i])\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == 0:\n            if allowzero:\n                out[dst_idx] = int64(newshape[i])\n            else:\n                out[dst_idx] = data_shape[src_idx]\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == -1:\n            assert infer_idx < 0, \"One and only one dim can be inferred\"\n            out[dst_idx] = int64(1)\n            infer_idx = i\n            src_idx += 1\n            dst_idx += 1\n        elif newshape[i] == -2:\n            assert False, \"Value -2 is not valid in newshape argument of dynamic reshape\"\n        elif newshape[i] == -3:\n            assert data_shape.shape[0] - src_idx > 1, \"Not enough dims in input shape for -3\"\n            out[dst_idx] = data_shape[src_idx] * data_shape[src_idx + 1]\n            src_idx += 2\n            dst_idx += 1\n        elif newshape[i] == -4:\n            assert False, \"Value -4 is not valid in newshape argument of dynamic reshape\"\n        else:\n            assert False, \"Invalid special values in new shape\"\n    if len(data_shape.shape) > 0:\n        # if data is not constant, we can then handle -1 and -2\n        if copy:\n            for i in range(src_idx, data_shape.shape[0]):\n                out[dst_idx] = data_shape[i]\n                dst_idx += 1\n        if infer_idx >= 0:\n            old_size = int64(1)\n            for i in const_range(data_shape.shape[0]):\n                old_size *= data_shape[i]\n            new_size = int64(1)\n            for i in const_range(out.shape[0]):\n                new_size *= out[i]\n            out[infer_idx] = old_size // new_size\n    return out\n\n\n@_reg.register_shape_func(\"dyn.reshape\", [False, True])\ndef dynamic_reshape_shape_func(attrs, inputs, out_ndims):\n    allowzero = attrs.allowzero\n    return [_reshape_shape_func_input_data(*inputs, out_ndims[0], convert(allowzero))]\n\n\n@script\ndef _expand_dims_shape_func_input_data(data, axis, ndims, num_newaxis):\n    out = output_tensor((ndims,), \"int64\")\n\n    for i in const_range(ndims):\n        if i < axis:\n            # We multiply by a check (i < len(data.shape)) to avoid\n            # a constant folding mechanism leading to an overflow\n            out[i] = int64(data.shape[i * (i < len(data.shape))])\n        elif i - num_newaxis < axis:\n            out[i] = int64(1)\n        else:\n            out[i] = int64(\n                # We can't use axis in indices as it is not constant but we can\n                # use negative indices (kind of, have to manually do it)\n                data.shape[\n                    (i - num_newaxis) * (i - num_newaxis >= 0)\n                    + (i - num_newaxis + len(data.shape)) * (i - num_newaxis < 0)\n                ]\n            )\n\n    return out\n\n\n@_reg.register_shape_func(\"dyn.expand_dims\", [True, True])\ndef dynamic_expand_dims_shape_func(attrs, inputs, out_ndims):\n    return [\n        _expand_dims_shape_func_input_data(\n            inputs[0],\n            inputs[1],\n            out_ndims[0],\n            convert(attrs.num_newaxis),\n        )\n    ]\n\n\n@script\ndef _tile_shape_func(data, reps, ndim, tndim, rndim):\n    out = output_tensor((tndim,), \"int64\")\n\n    if ndim == rndim:\n        for i in const_range(tndim):\n            out[i] = int64(data.shape[i] * reps[i])\n    elif ndim > rndim:\n        ngap = ndim - rndim\n        for i in const_range(ndim):\n            if i < ngap:\n                out[i] = int64(data.shape[i])\n            else:\n                out[i] = int64(data.shape[i] * reps[i - ngap])\n    else:\n        rgap = rndim - ndim\n        for i in const_range(rndim):\n            if i < rgap:\n                out[i] = int64(reps[i])\n            else:\n                out[i] = int64(reps[i] * data.shape[i - rgap])\n    return out\n\n\n@_reg.register_shape_func(\"dyn.tile\", True)\ndef tile_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for dyn.tile op.\n    \"\"\"\n    reps = inputs[1]\n    ndim = len(inputs[0].shape)\n    rndim = inputs[1].shape[0].value\n    tndim = ndim if ndim > rndim else rndim\n    return [_tile_shape_func(inputs[0], reps, convert(ndim), convert(tndim), convert(rndim))]\n\n\n@script\ndef _onehot_shape_func(dshape, k, axis):\n    ndim = len(dshape) + 1\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(axis):\n        out[i] = int64(dshape[i])\n    out[axis] = int64(k[(0)])\n    for j in const_range(axis + 1, ndim):\n        out[j] = int64(dshape[j - 1])\n    return out\n\n\n@_reg.register_shape_func(\"dyn.one_hot\", True)\ndef one_hot_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for dyn.one_hot op.\n    \"\"\"\n    axis = len(inputs[0].shape) if attrs.axis == -1 else attrs.axis\n    return [_onehot_shape_func(inputs[0].shape, inputs[3], convert(axis))]\n\n\n@script\ndef _strided_slice_shape_func_input_data(data_shape, begin, end, strides, slice_mode):\n    ndim = len(data_shape)\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        dim_size = int64(data_shape[i])\n        cbegin = int64(0)\n        cend = dim_size\n        cstride = int64(1)\n\n        if strides.shape[0] > i:\n            cstride = int64(strides[i])\n\n        if begin.shape[0] > i:\n            cbegin = int64(begin[i])\n        elif cstride < 0:\n            cbegin = dim_size\n\n        if end.shape[0] <= i:\n            if cstride < 0:\n                cend = int64(0)\n        elif slice_mode != 0:\n            cstride = int64(1)\n            if end[i] < 0:\n                cend = dim_size\n            else:\n                cend = cbegin + int64(end[i])\n        else:\n            if end[i] > data_shape[i]:\n                cend = dim_size\n            else:\n                cend = int64(end[i])\n\n        assert cstride != 0, \"Strides can't be zero.\"\n\n        if cbegin < 0:\n            cbegin += dim_size\n        if cend < 0:\n            cend += dim_size\n\n        if cstride < 0:\n            if cend < 0:\n                cend = int64(-1)\n            if cbegin > dim_size - 1:\n                cbegin = dim_size - 1\n            slice_range = cbegin - cend\n            step = -cstride\n        else:\n            slice_range = cend - cbegin\n            step = cstride\n        out[i] = int64(ceil_div(slice_range, step))\n    return out\n\n\n@_reg.register_shape_func(\"dyn.strided_slice\", [False, True, True, True])\ndef strided_slice_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape func for strided_slice\n    \"\"\"\n    slice_mode = convert(0 if attrs.slice_mode == \"end\" else 1)\n    return [_strided_slice_shape_func_input_data(*inputs, slice_mode)]\n\n\n@script\ndef _sparse_to_dense_shape_func(output_shape, ndim):\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        out[i] = int64(output_shape[i])\n    return out\n\n\n@_reg.register_shape_func(\"dyn.sparse_to_dense\", True)\ndef sparse_to_dense_shape_func(attrs, inputs, out_ndims):\n    return [_sparse_to_dense_shape_func(inputs[3], out_ndims[0])]\n\n\n@script\ndef _squeeze_shape_func_input_data(data, axis, ndims):\n    out = output_tensor((ndims,), \"int64\")\n    out_i = 0\n    for i in const_range(data.shape[0]):\n        not_in_axis = True\n        for j in const_range(axis.shape[0]):\n            if i == axis[j]:\n                not_in_axis = False\n        if not_in_axis:\n            out[out_i] = int64(data[i])\n            out_i += 1\n\n    return out\n\n\n@_reg.register_shape_func(\"dyn.squeeze\", [False, True])\ndef dynamic_squeeze_shape_func(attrs, inputs, out_ndims):\n    return [_squeeze_shape_func_input_data(inputs[0], inputs[1], out_ndims[0])]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/image/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay namespace containing dynamic image ops.\"\"\"\n\nfrom . import _image\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/image/_image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom __future__ import absolute_import\n\nimport tvm.topi\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\nfrom tvm.topi.utils import nchw_pack_layout, nchw_xc_layout\nfrom ... import op as reg\n\n\n# resize\n@reg.register_compute(\"dyn.image.resize2d\")\ndef compute_resize2d(attrs, inputs, out_type):\n    \"\"\"\n    Compute function calls into topi\n    \"\"\"\n    layout = attrs.layout\n    method = attrs.method\n    coord_trans = attrs.coordinate_transformation_mode\n    rounding_method = attrs.rounding_method\n    cubic_alpha = attrs.cubic_alpha\n    cubic_exclude = attrs.cubic_exclude\n    extrapolation_value = attrs.extrapolation_value\n    out_dtype = attrs.out_dtype\n    return [\n        tvm.topi.image.resize2d(\n            inputs[0],\n            inputs[2],\n            inputs[1],\n            layout,\n            method,\n            coord_trans,\n            rounding_method,\n            cubic_alpha,\n            cubic_exclude,\n            extrapolation_value,\n            out_dtype,\n            out_type.shape,\n        )\n    ]\n\n\nreg.register_injective_schedule(\"dyn.image.resize2d\")\n\n\n@script\ndef _resize2d_shape_func(dshape, size, ndim, height_axis, width_axis):\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        out[i] = int64(dshape[i])\n    out[height_axis] = int64(size[0])\n    out[width_axis] = int64(size[1])\n    return out\n\n\n@reg.register_shape_func(\"dyn.image.resize2d\", True)\ndef resize2d_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for dyn.image.resize op.\n    \"\"\"\n    layout = attrs.layout\n    if nchw_pack_layout(layout) or nchw_xc_layout(layout):\n        out = [\n            _resize2d_shape_func(\n                inputs[0].shape, inputs[1], convert(len(inputs[0].shape)), convert(2), convert(3)\n            )\n        ]\n    else:\n        height_axis = width_axis = 1\n        for i, letter in enumerate(layout):\n            if letter == \"H\":\n                height_axis = i\n            if letter == \"W\":\n                width_axis = i\n        out = [\n            _resize2d_shape_func(\n                inputs[0].shape,\n                inputs[1],\n                convert(len(inputs[0].shape)),\n                convert(height_axis),\n                convert(width_axis),\n            )\n        ]\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/image/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.dyn.image._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/nn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay namespace containing dynamic ops.\"\"\"\n\nfrom . import _nn\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/nn/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.dyn.nn._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/dyn/nn/_nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, invalid-name, unused-argument, too-many-arguments, consider-using-in\n\"\"\"Backend compiler related feature registration for dynamic relay ops in nn namespace\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom tvm import topi\n\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\nfrom ...op import register_shape_func, register_compute\nfrom ...op import register_injective_schedule, register_broadcast_schedule\n\n# upsampling\n@register_compute(\"dyn.nn.upsampling\")\ndef compute_upsampling(attrs, inputs, out_dtype):\n    data = inputs[0]\n    scale_h = inputs[1]\n    scale_w = inputs[2]\n    layout = attrs.layout\n    method = attrs.method\n    align_corners = attrs.align_corners\n    return [\n        topi.nn.upsampling(data, scale_h, scale_w, layout, method, align_corners, out_dtype.shape)\n    ]\n\n\n# upsampling3d\n@register_compute(\"dyn.nn.upsampling3d\")\ndef compute_upsampling3d(attrs, inputs, out_dtype):\n    data = inputs[0]\n    scale_d = inputs[1]\n    scale_h = inputs[2]\n    scale_w = inputs[3]\n    layout = attrs.layout\n    method = attrs.method\n    coordinate_transformation_mode = attrs.coordinate_transformation_mode\n    return [\n        topi.nn.upsampling3d(\n            data,\n            scale_d,\n            scale_h,\n            scale_w,\n            layout,\n            method,\n            coordinate_transformation_mode,\n            out_dtype.shape,\n        )\n    ]\n\n\nregister_injective_schedule(\"dyn.nn.upsampling\")\nregister_injective_schedule(\"dyn.nn.upsampling3d\")\nregister_broadcast_schedule(\"dyn.nn.pad\")\n\n#####################\n#  Shape functions  #\n#####################\n\n# upsampling\n@script\ndef _upsampling_shape_func(dshape, scale_h, scale_w, height_axis, width_axis):\n    out = output_tensor((4,), \"int64\")\n    for i in const_range(4):\n        out[i] = int64(dshape[i])\n    out[height_axis] = int64(round(dshape[height_axis] * scale_h[()]))\n    out[width_axis] = int64(round(dshape[width_axis] * scale_w[()]))\n    return out\n\n\n@register_shape_func(\"dyn.nn.upsampling\", True)\ndef upsampling_shape_func(attrs, inputs, _):\n    \"\"\"Shape function for upsampling. Supports NCHW and NHWC layouts.\"\"\"\n    layout = attrs.layout\n    height_axis = width_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"H\":\n            height_axis = i\n        if letter == \"W\":\n            width_axis = i\n    return [\n        _upsampling_shape_func(\n            inputs[0].shape, inputs[1], inputs[2], convert(height_axis), convert(width_axis)\n        )\n    ]\n\n\n# upsampling3d\n@script\ndef _upsampling3d_shape_func(\n    dshape, scale_d, scale_h, scale_w, depth_axis, height_axis, width_axis\n):\n    out = output_tensor((5,), \"int64\")\n    for i in const_range(5):\n        out[i] = int64(dshape[i])\n    out[depth_axis] = int64(round(dshape[depth_axis] * scale_d[()]))\n    out[height_axis] = int64(round(dshape[height_axis] * scale_h[()]))\n    out[width_axis] = int64(round(dshape[width_axis] * scale_w[()]))\n    return out\n\n\n@register_shape_func(\"dyn.nn.upsampling3d\", True)\ndef upsampling3d_shape_func(attrs, inputs, _):\n    \"\"\"Shape function for upsampling. Supports NCHW and NHWC layouts.\"\"\"\n    layout = attrs.layout\n    depth_axis = height_axis = width_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"D\":\n            depth_axis = i\n        if letter == \"H\":\n            height_axis = i\n        if letter == \"W\":\n            width_axis = i\n    return [\n        _upsampling3d_shape_func(\n            inputs[0].shape,\n            inputs[1],\n            inputs[2],\n            inputs[3],\n            convert(depth_axis),\n            convert(height_axis),\n            convert(width_axis),\n        )\n    ]\n\n\n# pad\n@script\ndef _dyn_pad_shape_func(data, pad_width):\n    ndim = len(data.shape)\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        out[i] = int64(pad_width[i, 0] + pad_width[i, 1] + data.shape[i])\n    return out\n\n\n@register_shape_func(\"dyn.nn.pad\", True)\ndef pad_shape_func(attrs, inputs, data):\n    \"\"\"\n    Shape function for dynamic pad op.\n    \"\"\"\n    return [_dyn_pad_shape_func(inputs[0], inputs[1])]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/image/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Image network related operators.\"\"\"\nfrom .image import *\nfrom . import _image\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/image/_image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom __future__ import absolute_import\n\nfrom tvm.te.hybrid import script\nfrom tvm.runtime import convert\n\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nfrom .. import op as reg\nfrom .. import strategy\nfrom ..op import OpPattern\nfrom .image import resize2d\n\n\n# resize\n@reg.register_compute(\"image.resize1d\")\ndef compute_resize1d(attrs, inputs, out_type):\n    \"\"\"compute definition for resize1d op\"\"\"\n    size = attrs.size\n    roi = attrs.roi\n    layout = attrs.layout\n    method = attrs.method\n    coord_trans = attrs.coordinate_transformation_mode\n    rounding_method = attrs.rounding_method\n    cubic_alpha = attrs.cubic_alpha\n    cubic_exclude = attrs.cubic_exclude\n    extrapolation_value = attrs.extrapolation_value\n    out_dtype = attrs.out_dtype\n    return [\n        topi.image.resize1d(\n            inputs[0],\n            roi,\n            size,\n            layout,\n            method,\n            coord_trans,\n            rounding_method,\n            cubic_alpha,\n            cubic_exclude,\n            extrapolation_value,\n            out_dtype,\n        )\n    ]\n\n\nreg.register_injective_schedule(\"image.resize1d\")\n\n\n@reg.register_convert_op_layout(\"image.resize1d\")\ndef convert_image_resize1d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for image resize1d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current resize op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data input.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 1, \"Only one desired layout is expected\"\n    desired_layout = str(desired_layouts[0])\n    assert desired_layout != \"default\", \"Layout cannot be default\"\n    new_attrs[\"layout\"] = desired_layout\n    return resize1d(*inputs, **new_attrs)\n\n\n@script\ndef _resize1d_shape_func(image_shape, size, batch_axis, width_axis, channel_axis):\n    out = output_tensor((3,), \"int64\")\n    out[batch_axis] = int64(image_shape[0])\n    out[width_axis] = int64(size[1])\n    out[channel_axis] = image_shape[channel_axis]\n    return out\n\n\n@reg.register_shape_func(\"image.resize1d\", False)\ndef resize1d_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for resize2d op.\n    \"\"\"\n    layout = attrs.layout\n    width_axis = channel_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"N\":\n            batch_axis = i\n        if letter == \"W\":\n            width_axis = i\n        if letter == \"C\":\n            channel_axis = i\n    size = get_const_tuple(attrs.size)\n    return [\n        _resize1d_shape_func(\n            inputs[0],\n            convert(size),\n            convert(batch_axis),\n            convert(width_axis),\n            convert(channel_axis),\n        )\n    ]\n\n\n@reg.register_compute(\"image.resize2d\")\ndef compute_resize2d(attrs, inputs, out_type):\n    \"\"\"compute definition for resize2d op\"\"\"\n    size = attrs.size\n    roi = attrs.roi\n    layout = attrs.layout\n    method = attrs.method\n    coord_trans = attrs.coordinate_transformation_mode\n    rounding_method = attrs.rounding_method\n    cubic_alpha = attrs.cubic_alpha\n    cubic_exclude = attrs.cubic_exclude\n    extrapolation_value = attrs.extrapolation_value\n    out_dtype = attrs.out_dtype\n    return [\n        topi.image.resize2d(\n            inputs[0],\n            roi,\n            size,\n            layout,\n            method,\n            coord_trans,\n            rounding_method,\n            cubic_alpha,\n            cubic_exclude,\n            extrapolation_value,\n            out_dtype,\n        )\n    ]\n\n\nreg.register_injective_schedule(\"image.resize2d\")\n\n\n@reg.register_convert_op_layout(\"image.resize2d\")\ndef convert_image_resize2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for image resize2d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current resize op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data input.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 1, \"Only one desired layout is expected\"\n    desired_layout = str(desired_layouts[0])\n    assert desired_layout != \"default\", \"Layout cannot be default\"\n    new_attrs[\"layout\"] = desired_layout\n    return resize2d(*inputs, **new_attrs)\n\n\n@script\ndef _resize2d_shape_func(image_shape, size, batch_axis, height_axis, width_axis, channel_axis):\n    out = output_tensor((4,), \"int64\")\n    out[batch_axis] = int64(image_shape[0])\n    out[height_axis] = int64(size[0])\n    out[width_axis] = int64(size[1])\n    out[channel_axis] = image_shape[channel_axis]\n    return out\n\n\n@reg.register_shape_func(\"image.resize2d\", False)\ndef resize2d_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for resize2d op.\n    \"\"\"\n    layout = attrs.layout\n    height_axis = width_axis = channel_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"N\":\n            batch_axis = i\n        if letter == \"H\":\n            height_axis = i\n        if letter == \"W\":\n            width_axis = i\n        if letter == \"C\":\n            channel_axis = i\n    size = get_const_tuple(attrs.size)\n    return [\n        _resize2d_shape_func(\n            inputs[0],\n            convert(size),\n            convert(batch_axis),\n            convert(height_axis),\n            convert(width_axis),\n            convert(channel_axis),\n        )\n    ]\n\n\n@reg.register_compute(\"image.resize3d\")\ndef compute_resize3d(attrs, inputs, out_type):\n    \"\"\"compute definition for resize3d op\"\"\"\n    size = attrs.size\n    roi = attrs.roi\n    layout = attrs.layout\n    method = attrs.method\n    coord_trans = attrs.coordinate_transformation_mode\n    rounding_method = attrs.rounding_method\n    cubic_alpha = attrs.cubic_alpha\n    cubic_exclude = attrs.cubic_exclude\n    extrapolation_value = attrs.extrapolation_value\n    out_dtype = attrs.out_dtype\n    return [\n        topi.image.resize3d(\n            inputs[0],\n            roi,\n            size,\n            layout,\n            method,\n            coord_trans,\n            rounding_method,\n            cubic_alpha,\n            cubic_exclude,\n            extrapolation_value,\n            out_dtype,\n        )\n    ]\n\n\nreg.register_injective_schedule(\"image.resize3d\")\n\n\n# crop and resize\n@reg.register_compute(\"image.crop_and_resize\")\ndef compute_crop_and_resize(attrs, inputs, out_type):\n    crop_size = attrs.crop_size\n    layout = attrs.layout\n    method = attrs.method\n    extrapolation_value = attrs.extrapolation_value\n    out_dtype = attrs.out_dtype\n    return [\n        topi.image.crop_and_resize(\n            inputs[0],\n            inputs[1],\n            inputs[2],\n            crop_size,\n            layout,\n            method,\n            extrapolation_value,\n            out_dtype,\n        )\n    ]\n\n\nreg.register_injective_schedule(\"image.crop_and_resize\")\n\n\n@script\ndef _crop_and_resize_func(\n    image_shape, boxes_shape, crop_size, height_axis, width_axis, channel_axis\n):\n    out = output_tensor((4,), \"int64\")\n    out[0] = boxes_shape[0]\n    out[height_axis] = int64(crop_size[0])\n    out[width_axis] = int64(crop_size[1])\n    out[channel_axis] = image_shape[channel_axis]\n    return out\n\n\n@reg.register_shape_func(\"image.crop_and_resize\", False)\ndef crop_and_resize_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for crop_and_resize op.\n    \"\"\"\n    layout = attrs.layout\n    height_axis = width_axis = channel_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"H\":\n            height_axis = i\n        if letter == \"W\":\n            width_axis = i\n        if letter == \"C\":\n            channel_axis = i\n    crop_size = get_const_tuple(attrs.crop_size)\n    return [\n        _crop_and_resize_func(\n            inputs[0],\n            inputs[1],\n            convert(crop_size),\n            convert(height_axis),\n            convert(width_axis),\n            convert(channel_axis),\n        )\n    ]\n\n\n# dilation2d\nreg.register_strategy(\"image.dilation2d\", strategy.dilation2d_strategy)\nreg.register_pattern(\"image.dilation2d\", OpPattern.OUT_ELEMWISE_FUSABLE)\n\n\n# affine_grid\n@reg.register_compute(\"image.affine_grid\")\ndef compute_affine_grid(attrs, inputs, out_dtype):\n    target_shape = get_const_tuple(attrs.target_shape)\n    return [topi.image.affine_grid(inputs[0], target_shape)]\n\n\nreg.register_injective_schedule(\"image.affine_grid\")\n\n\n@script\ndef _affine_grid_func(data, target_shape):\n    out = output_tensor((4,), \"int64\")\n    out[0] = int64(data[0])\n    out[1] = int64(2)\n    out[2] = int64(target_shape[0])\n    out[3] = int64(target_shape[1])\n    return out\n\n\n@reg.register_shape_func(\"image.affine_grid\", False)\ndef affine_grid_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for affine_grid op.\n    \"\"\"\n    target_shape = get_const_tuple(attrs.target_shape)\n    return [_affine_grid_func(inputs[0], convert(target_shape))]\n\n\n# grid_sample\n@reg.register_compute(\"image.grid_sample\")\ndef compute_grid_sample(attrs, inputs, out_dtype):\n    method = attrs.method\n    layout = attrs.layout\n    padding_mode = attrs.padding_mode\n    align_corners = attrs.align_corners\n    return [\n        topi.image.grid_sample(inputs[0], inputs[1], method, layout, padding_mode, align_corners)\n    ]\n\n\nreg.register_injective_schedule(\"image.grid_sample\")\n\n\n@script\ndef _grid_sample_func_nchw(data, grid):\n    out = output_tensor((4,), \"int64\")\n    out[0] = int64(data[0])\n    out[1] = int64(data[1])\n    out[2] = int64(grid[2])\n    out[3] = int64(grid[3])\n    return out\n\n\n@script\ndef _grid_sample_func_ncdhw(data, grid):\n    out = output_tensor((5,), \"int64\")\n    out[0] = int64(data[0])\n    out[1] = int64(data[1])\n    out[2] = int64(grid[2])\n    out[3] = int64(grid[3])\n    out[4] = int64(grid[4])\n    return out\n\n\n@reg.register_shape_func(\"image.grid_sample\", False)\ndef grid_sample_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for grid_sample op.\n    \"\"\"\n    if attrs.layout == \"NCHW\":\n        script_func = _grid_sample_func_nchw\n    elif attrs.layout == \"NCDHW\":\n        script_func = _grid_sample_func_ncdhw\n    else:\n        msg = f\"layout {attrs.layout} is not supported\"\n        raise ValueError(msg)\n    return [script_func(inputs[0], inputs[1])]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/image/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.image._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/image/image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Image operations.\"\"\"\nfrom . import _make\nfrom ..dyn.image import _make as _dyn_make\nfrom ...expr import Expr, Constant, const\n\n\ndef resize1d(\n    data,\n    size,\n    roi=None,\n    layout=\"NCW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    cubic_alpha=-0.5,\n    cubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n):\n    \"\"\"Image resize1d operator.\n\n    This operator takes data as input and does 1D scaling to the given scale factor.\n    In the default case, where the data_layout is `NCW`\n    with data of shape (n, c, w)\n    out will have a shape (n, c, size[0])\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be one of (\"linear\", \"nearest_neighbor\", \"cubic\")\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    size: Tuple of Int or Expr\n        The out size to which the image will be resized.\n\n    roi: Tuple of Float or Expr, optional\n        The region of interest for cropping the input image. Expected to be of\n        size 2, and format [start_w, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method to used [nearest_neighbor, linear, cubic].\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor. Defintions can be found\n        in topi/image/resize.py.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    cubic_alpha: float\n        Spline Coefficient for cubic interpolation\n\n    cubic_exclude: int\n        Flag to exclude exterior of the image during cubic interpolation\n\n    extrapolation_value: float\n        Fill value to use when roi is outside of the image\n\n    out_dtype : str, optional\n        Type to return. If left None returns the same type as input.\n\n    Returns\n    -------\n    result: relay.Expr\n        The resized result.\n    \"\"\"\n    if roi is None:\n        roi = [0.0] * 2\n    if isinstance(size, Constant):\n        size = list(size.data.numpy().astype(\"int32\"))\n    if isinstance(roi, Constant):\n        roi = list(roi.data.numpy().astype(\"int32\"))\n    if isinstance(size, Expr) or isinstance(roi, Expr):\n        raise NotImplementedError(\n            \"dyn.resize1d is not yet implemented, got size\", size, \"and roi\", roi\n        )\n    return _make.resize1d(\n        data,\n        size,\n        roi,\n        layout,\n        method,\n        coordinate_transformation_mode,\n        rounding_method,\n        cubic_alpha,\n        cubic_exclude,\n        extrapolation_value,\n        out_dtype,\n    )\n\n\ndef resize2d(\n    data,\n    size,\n    roi=None,\n    layout=\"NCHW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    cubic_alpha=-0.5,\n    cubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n):\n    \"\"\"Image resize2d operator.\n\n    This operator takes data as input and does 2D scaling to the given scale factor.\n    In the default case, where the data_layout is `NCHW`\n    with data of shape (n, c, h, w)\n    out will have a shape (n, c, size[0], size[1])\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be one of (\"linear\", \"nearest_neighbor\", \"cubic\")\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    size: Tuple of Int or Expr\n        The out size to which the image will be resized.\n\n    roi: Tuple of Float or Expr, optional\n        The region of interest for cropping the input image. Expected to be of\n        size 4, and format [start_h, start_w, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method to used [nearest_neighbor, linear, cubic].\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor. Defintions can be found\n        in topi/image/resize.py.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    cubic_alpha: float\n        Spline Coefficient for bicubic interpolation\n\n    cubic_exclude: int\n        Flag to exclude exterior of the image during bicubic interpolation\n\n    extrapolation_value: float\n        Fill value to use when roi is outside of the image\n\n    out_dtype : str, optional\n        Type to return. If left None returns the same type as input.\n\n    Returns\n    -------\n    result: relay.Expr\n        The resized result.\n    \"\"\"\n    if roi is None:\n        roi = [0.0] * 4\n    if isinstance(size, Constant):\n        size = list(size.data.numpy().astype(\"int32\"))\n    if isinstance(roi, Constant):\n        roi = list(roi.data.numpy().astype(\"float32\"))\n    if isinstance(size, Expr) or isinstance(roi, Expr):\n        if not isinstance(size, Expr):\n            size = const(size, \"int64\")\n        if not isinstance(roi, Expr):\n            roi = const(roi, \"float32\")\n        return _dyn_make.resize2d(\n            data,\n            size,\n            roi,\n            layout,\n            method,\n            coordinate_transformation_mode,\n            rounding_method,\n            cubic_alpha,\n            cubic_exclude,\n            extrapolation_value,\n            out_dtype,\n        )\n    return _make.resize2d(\n        data,\n        size,\n        roi,\n        layout,\n        method,\n        coordinate_transformation_mode,\n        rounding_method,\n        cubic_alpha,\n        cubic_exclude,\n        extrapolation_value,\n        out_dtype,\n    )\n\n\ndef resize3d(\n    data,\n    size,\n    roi=None,\n    layout=\"NCDHW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    cubic_alpha=-0.5,\n    cubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n):\n    \"\"\"Image resize3d operator.\n\n    This operator takes data as input and does 3D scaling to the given scale factor.\n    In the default case, where the data_layout is `NCDHW`\n    with data of shape `(n, c, d, h, w)`\n    out will have a shape `(n, c, size[0], size[1], size[2])`\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be one of (\"linear\", \"nearest_neighbor\", \"cubic\")\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    size: Tuple of Int or Expr\n        The out size to which the image will be resized.\n\n    roi: Tuple of Float or Expr, optional\n        The region of interest for cropping the input image. Expected to be of\n        size 6, and format [start_d, start_h, start_w, end_d, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method to used [nearest_neighbor, linear, cubic].\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor. Defintions can be found\n        in topi/image/resize.py.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    cubic_alpha: float\n        Spline Coefficient for cubic interpolation\n\n    cubic_exclude: int\n        Flag to exclude exterior of the image during cubic interpolation\n\n    extrapolation_value: float\n        Fill value to use when roi is outside of the image\n\n    out_dtype : str, optional\n        Type to return. If left None returns the same type as input.\n\n    Returns\n    -------\n    result: relay.Expr\n        The resized result.\n    \"\"\"\n    if roi is None:\n        roi = [0.0] * 6\n    if isinstance(size, Constant):\n        size = list(size.data.numpy().astype(\"int32\"))\n    if isinstance(roi, Constant):\n        roi = list(roi.data.numpy().astype(\"int32\"))\n    if isinstance(size, Expr) or isinstance(roi, Expr):\n        raise NotImplementedError(\n            \"dyn.resize3d is not yet implemented, got size\", size, \"and roi\", roi\n        )\n    return _make.resize3d(\n        data,\n        size,\n        roi,\n        layout,\n        method,\n        coordinate_transformation_mode,\n        rounding_method,\n        cubic_alpha,\n        cubic_exclude,\n        extrapolation_value,\n        out_dtype,\n    )\n\n\ndef crop_and_resize(\n    data,\n    boxes,\n    box_indices,\n    crop_size,\n    layout,\n    method=\"bilinear\",\n    extrapolation_value=0,\n    out_dtype=None,\n):\n    \"\"\"Crop input images and resize them.\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be either \"bilinear\" or \"nearest_neighbor\".\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    boxes : relay.Expr\n        A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies\n        the coordinates of a box.\n\n    box_indices : relay.Expr\n        A 1-D tensor of shape [num_boxes], box_ind[i] specifies the data that\n        the i-th box refers to.\n\n    crop_size : Tuple of PrimExpr\n        The target size to which each box will be resized.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method, it can be either \"nearest_neighbor\" or \"bilinear\".\n\n    extrapolation_value : float, optional\n        Value used for extrapolation, when applicable.\n\n    out_dtype : str, optional\n        Type to return. If left None returns the same type as input.\n\n    Returns\n    -------\n    result: relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.crop_and_resize(\n        data, boxes, box_indices, crop_size, layout, method, extrapolation_value, out_dtype\n    )\n\n\ndef dilation2d(\n    data,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilations=(1, 1),\n    data_layout=\"NCHW\",\n    kernel_layout=\"IHW\",\n    out_dtype=\"\",\n):\n    r\"\"\"Morphological Dilation 2D.\n    This operator takes the weight as the dilation kernel and dilates it with\n    data to produce an output. In the default case, where the data_layout is `NCHW`\n    and kernel_layout is `OIHW`, dilation2d takes in a data Tensor with shape\n    `(batch_size, in_channels, height, width)`, and a weight Tensor with shape\n    `(channels, kernel_height, kernel_width)` to produce an output Tensor\n    with the following rule:\n\n    .. math::\n        \\mbox{out}[b, c, y, x] = \\max_{dy, dx}\n           \\mbox{data}[b, c, \\mbox{strides}[0] * y  + dy, \\mbox{strides}[1] * x + dx] +\n           \\mbox{weight}[c, dy, dx]\n\n    Padding and dilation are applied to data and weight respectively before the computation.\n    This operator accepts data layout specification. Semantically, the operator\n    will convert the layout to the canonical layout\n    (`NCHW` for data and `IHW` for weight) and perform the computation.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Optional[Tuple[int]]\n        The strides of convolution.\n\n    padding : Optional[Tuple[int]]\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilations : Optional[Tuple[int]]\n        Specifies the dilation rate to be used for dilated convolution.\n\n    data_layout : Optional[str]\n        Layout of the input.\n\n    kernel_layout : Optional[str]\n        Layout of the weight.\n\n    out_dtype : Optional[str]\n        Specifies the output data type.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _make.dilation2d(\n        data, weight, strides, padding, dilations, data_layout, kernel_layout, out_dtype\n    )\n\n\ndef affine_grid(data, target_shape=None):\n    \"\"\"affine_grid operator that generates 2D sampling grid.\n\n    This operation is described in https://arxiv.org/pdf/1506.02025.pdf. It generates a uniform\n    sampling grid within the target shape and normalizes it to [-1, 1]. The provided affine\n    transformation is then applied on the sampling grid.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        3-D with shape [batch, 2, 3]. The affine matrix.\n\n    target_shape: list/tuple of two int\n        Specifies the output shape (H, W).\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        4-D with shape [batch, 2, target_height, target_width]\n    \"\"\"\n    return _make.affine_grid(data, target_shape)\n\n\ndef grid_sample(\n    data, grid, method=\"bilinear\", layout=\"NCHW\", padding_mode=\"zeros\", align_corners=True\n):\n    \"\"\"Applies grid sampling to input feature map.\n\n    Given :math:`data` and :math:`grid`, then for 4-D the output is computed by\n\n    .. math::\n\n        x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\\\\n        y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\\\\n        output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src}])\n\n    :math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and\n    :math:`G()` denotes the interpolation function.\n\n    The out-boundary points will be padded with zeros if padding_mode is \"zeros\", or\n    border pixel value if padding_mode is \"border\", or\n    inner pixel value if padding_mode is \"reflection\".\n\n    The left-top corner (-1, -1) and right-bottom corner (1, 1) in grid will be map to\n    (0, 0) and (h - 1, w - 1) of data if align_corners is \"True\", or\n    (-0.5, -0.5) and (h - 0.5, w - 0.5) of data if align_corners is \"False\".\n\n    The shape of the output will be\n    4-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]), or\n    5-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3], grid.shape[4]).\n\n    The operator assumes that :math:`grid` has been normalized to [-1, 1].\n\n    grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width], or\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    grid : tvm.Tensor\n        4-D with shape [batch, 2, out_height, out_width], or\n        5-D with shape [batch, 3, out_depth, out_height, out_width]\n\n    method : str\n        The interpolation method, 4-D \"nearest\", \"bilinear\", \"bicubic\" and\n        5-D \"nearest\", \"bilinear\"(\"trilinear\") are supported.\n\n    layout : str\n        The layout of input data and the output.\n\n    padding_mode : str\n        The padding mode for outside grid values, \"zeros\", \"border\", \"reflection\" are supported.\n\n    align_corners: bool\n        Geometrically, we consider the pixels of the input as squares rather than points.\n        If set to \"True\", the extrema (\"-1\" and \"1\") are considered as referring\n        to the center points of the input corner pixels. If set to \"False\", they\n        are instead considered as referring to the corner points of the input corner\n        pixels, making the sampling more resolution agnostic.\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        4-D with shape [batch, in_channel, out_height, out_width], or\n        5-D with shape [batch, in_channel, out_depth, out_height, out_width]\n    \"\"\"\n    return _make.grid_sample(data, grid, method, layout, padding_mode, align_corners)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/memory/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Operators for manipulating low level memory.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .memory import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/memory/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.memory._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/memory/memory.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return,invalid-name,len-as-condition,too-many-nested-blocks\n\"\"\"Operators for manipulating low-level memory.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom . import _make\n\n\ndef alloc_tensor(storage, offset, shape, dtype=\"float32\", assert_shape=None):\n    \"\"\"Allocate a tensor with the provided shape, and dtype.\n\n    Parameters\n    ----------\n    storage : tvm.relay.Expr\n        The storage to allocate from.\n\n    offset : tvm.relay.Expr\n        The offset to allocate from.\n\n    shape : tvm.relay.Expr\n        The shape of the tensor to allocate.\n\n    dtype: str\n        The dtype of the tensor.\n\n    assert_shape: Control the static shape when computed by dynamic shape expression.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The alloc_tensor expression.\n    \"\"\"\n    return _make.alloc_tensor(storage, offset, shape, dtype, assert_shape)\n\n\ndef alloc_storage(size, alignment, device, dtype_hint=\"float32\"):\n    \"\"\"Allocate a piece of tensor storage.\n\n    Parameters\n    ----------\n    size : tvm.relay.Expr\n        The size of the allocation.\n    alignment : tvm.relay.Expr\n        The alignment of the allocation.\n    device : tvm.runtime.Device\n        The device of the allocation.\n    dtype_hint : str\n        The dtype hint of the allocation.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The alloc_storage expression.\n    \"\"\"\n    return _make.alloc_storage(size, alignment, device, dtype_hint)\n\n\ndef flatten_tuple_type(ty):\n    \"\"\"Return a sequence of the types contained in the tuple type in order.\n\n    Parameters\n    ----------\n    ty: tvm.Type\n        The type to flatten.\n\n    Returns\n    -------\n    result: List[tvm.Type]\n        The types in their linear order.\n    \"\"\"\n    return _make.FlattenTupleType(ty)\n\n\ndef from_tuple_type(ty, expr):\n    \"\"\"Convert an expression with the given type into a sequence of expressions.\n       Each expression maps to a field of the tuple or nested tuples in linear\n       order.\n\n    Parameters\n    ----------\n    ty: tvm.Type\n        The type to unpack.\n\n    expr: tvm.relay.Expr\n        The expression from which to extract each sub-field.\n\n    Returns\n    -------\n    result: List[tvm.relay.Expr]\n        The list of sub-expressions.\n    \"\"\"\n    return _make.FromTupleType(ty, expr)\n\n\ndef to_tuple_type(ty, exprs):\n    \"\"\"Pack the sequence of expressions into the nested tuple type.\n\n    Parameters\n    ----------\n    ty: tvm.Type\n        The type to pack with.\n\n    exprs: tvm.relay.Expr\n        The expressions to pack back into the nested tuple type.\n\n    Returns\n    -------\n    result: List[tvm.relay.Expr]\n        The packed tuple expression.\n    \"\"\"\n    return _make.ToTupleType(ty, exprs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/nn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Neural network related operators.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .nn import *\nfrom . import _nn\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/nn/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.nn._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/nn/_nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, invalid-name, unused-argument, too-many-arguments, consider-using-in\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom __future__ import absolute_import\nimport re\n\nfrom tvm import relay, topi\nfrom tvm.runtime import convert\nfrom tvm.te.hybrid import script\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\n\nfrom ....ir import container\nfrom ....tir import expr\nfrom ...transform import LayoutConfig\nfrom .. import op as reg\nfrom .. import strategy\nfrom .._tensor import elemwise_shape_func\nfrom ..strategy.generic import is_depthwise_conv2d\n\n# relu\nreg.register_broadcast_schedule(\"nn.relu\")\n\n# softmax\nreg.register_strategy(\"nn.softmax\", strategy.softmax_strategy)\n\n\n# fast softmax\nreg.register_strategy(\"nn.fast_softmax\", strategy.fast_softmax_strategy)\n\n\n# log_softmax\nreg.register_strategy(\"nn.log_softmax\", strategy.log_softmax_strategy)\n\n\n@reg.register_legalize(\"nn.matmul\")\ndef legalize_matmul(attrs, inputs, types):\n    \"\"\"Legalize matmul op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current matmul\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.matmul_legalize(attrs, inputs, types)\n\n\n# matmul\nreg.register_strategy(\"nn.matmul\", strategy.matmul_strategy)\n\n\n@reg.register_legalize(\"nn.dense\")\ndef legalize_dense(attrs, inputs, types):\n    \"\"\"Legalize dense op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.dense_legalize(attrs, inputs, types)\n\n\n# dense\nreg.register_strategy(\"nn.dense\", strategy.dense_strategy)\n\n\n@reg.register_alter_op_layout(\"nn.dense\")\ndef alter_op_layout_dense(attrs, inputs, tinfos, out_type):\n    \"\"\"Alternate the layout of dense\"\"\"\n    return topi.nn.dense_alter_layout(attrs, inputs, tinfos, out_type)\n\n\n# dense_pack\nreg.register_strategy(\"nn.contrib_dense_pack\", strategy.dense_pack_strategy)\n\n\n# fifo_buffer\n@reg.register_compute(\"nn.fifo_buffer\")\ndef compute_fifo_buffer(attrs, inputs, out_type):\n    return [topi.nn.fifo_buffer(inputs[0], inputs[1], axis=attrs.get_int(\"axis\"))]\n\n\nreg.register_injective_schedule(\"nn.fifo_buffer\")\n\n\n@reg.register_legalize(\"nn.batch_matmul\")\ndef legalize_batch_matmul(attrs, inputs, types):\n    \"\"\"Legalize batch_matmul op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.batch_matmul_legalize(attrs, inputs, types)\n\n\n# batch_matmul\nreg.register_strategy(\"nn.batch_matmul\", strategy.batch_matmul_strategy)\n\n\n# batch_norm\nreg.register_strategy(\"nn.batch_norm\", strategy.batch_norm_strategy)\n\n\n# sparse_dense\n@reg.register_compute(\"nn.sparse_dense\")\ndef compute_sparse_dense(attrs, inputs, out_type):\n    \"\"\"Compute definition of sparse_dense\"\"\"\n    return [topi.nn.sparse_dense(inputs[0], inputs[1], inputs[2], inputs[3], attrs[\"sparse_lhs\"])]\n\n\nreg.register_strategy(\"nn.sparse_dense\", strategy.sparse_dense_strategy)\n\n\n@reg.register_alter_op_layout(\"nn.sparse_dense\")\ndef alter_op_layout_sparse_dense(attrs, inputs, tinfos, out_type):\n    \"\"\"Alternate the layout of sparse_dense\"\"\"\n    return topi.nn.sparse_dense_alter_layout(attrs, inputs, tinfos, out_type)\n\n\n# sparse_add\nreg.register_strategy(\"nn.sparse_add\", strategy.sparse_add_strategy)\n\n\n@reg.register_compute(\"nn.internal.sparse_dense_padded\")\ndef compute_sparse_dense_padded(attrs, inputs, out_type):\n    \"\"\"Compute definition of sparse_dense_padded\"\"\"\n    raise NotImplementedError(\"nn.internal.sparse_dense_padded is only available on cuda\")\n\n\nreg.register_strategy(\"nn.internal.sparse_dense_padded\", strategy.sparse_dense_padded_strategy)\n\n\n# sparse_transpose\n@reg.register_compute(\"nn.sparse_transpose\")\ndef compute_sparse_transpose(attrs, inputs, out_type):\n    \"\"\"Compute definition of sparse_transpose\"\"\"\n    return topi.nn.sparse_transpose(inputs[0], inputs[1], inputs[2])\n\n\nreg.register_schedule(\"nn.sparse_transpose\", strategy.schedule_sparse_transpose)\n\n\n# sparse_conv2d\n@reg.register_compute(\"nn.sparse_conv2d\")\ndef compute_sparse_conv2d(attrs, inputs, out_type):\n    \"\"\"Compute definition of sparse_conv2d\"\"\"\n    return [\n        topi.nn.sparse_conv2d(\n            inputs[0], inputs[1], inputs[2], inputs[3], attrs[\"layout\"], attrs[\"kernel_size\"]\n        )\n    ]\n\n\nreg.register_strategy(\"nn.sparse_conv2d\", strategy.sparse_conv2d_strategy)\n\n\n# conv1d\nreg.register_strategy(\"nn.conv1d\", strategy.conv1d_strategy)\n\n\n# conv2d\nreg.register_strategy(\"nn.conv2d\", strategy.conv2d_strategy)\n\n\n@reg.register_alter_op_layout(\"nn.conv2d\")\ndef alter_op_layout_conv2d(attrs, inputs, tinfos, out_type):\n    \"\"\"Alternate the layout of conv2d\"\"\"\n    return topi.nn.conv2d_alter_layout(attrs, inputs, tinfos, out_type)\n\n\n@reg.register_legalize(\"nn.conv2d\")\ndef legalize_conv2d(attrs, inputs, types):\n    \"\"\"Legalize conv2d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.conv2d_legalize(attrs, inputs, types)\n\n\n@reg.register_convert_op_layout(\"nn.conv2d\")\ndef convert_conv2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for conv2d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    data, weight = inputs\n\n    # First check if there is a LayoutConfig scope, and if so, whether\n    # it indicates we should ignore this layer or not.\n    layout_config = LayoutConfig.current\n    if layout_config is not None:\n        skip_layer = layout_config.check_skip()\n        if skip_layer:\n            return relay.nn.conv2d(data, weight, **attrs)\n\n    # Prepare new layout.\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 2, \"A desired layout is expected for both of nn.conv2d's inputs\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    new_attrs[\"data_layout\"] = desired_data_layout\n    need_tile = re.match(r\"NCHW(\\d*)c\", desired_data_layout)\n\n    if desired_kernel_layout != \"default\" and not need_tile:\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    # Handle default kernel layouts\n    if desired_data_layout == \"NCHW\":\n        new_attrs[\"kernel_layout\"] = \"OIHW\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    elif desired_data_layout == \"NHWC\":\n        # Check for depthwise convolution.\n        data_info, weight_info = tinfos\n        if is_depthwise_conv2d(\n            data_info.shape,\n            attrs[\"data_layout\"],\n            weight_info.shape,\n            attrs[\"kernel_layout\"],\n            attrs[\"groups\"],\n        ):\n            new_attrs[\"kernel_layout\"] = \"HWOI\"\n        else:\n            new_attrs[\"kernel_layout\"] = \"HWIO\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    elif desired_data_layout == \"HWNC\":\n        new_attrs[\"kernel_layout\"] = \"HWOI\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n    elif need_tile:\n        assert desired_kernel_layout != \"default\", \"Kernel layout cannot be default.\"\n        tile = int(need_tile.group(1))\n        if isinstance(data, relay.expr.Var) and data.checked_type.shape[1] % tile != 0:\n            return relay.nn.conv2d(data, weight, **attrs)\n        else:\n            new_attrs[\"kernel_layout\"] = desired_kernel_layout\n            return relay.nn.contrib_conv2d_nchwc(data, weight, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported.\" % desired_data_layout)\n\n\n# conv2d_transpose\nreg.register_strategy(\"nn.conv2d_transpose\", strategy.conv2d_transpose_strategy)\n\n\n@reg.register_legalize(\"nn.conv2d_transpose\")\ndef legalize_conv2d_transpose(attrs, inputs, types):\n    \"\"\"Legalize conv2d_transpose op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current Transposed convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.conv2d_transpose_legalize(attrs, inputs, types)\n\n\n@reg.register_convert_op_layout(\"nn.conv2d_transpose\")\ndef convert_conv2d_transpose(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for conv2d_transpose op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    data, weight = inputs\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 2, \"A desired layout is expected for both of nn.conv2d's inputs\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    new_attrs[\"data_layout\"] = desired_data_layout\n\n    if desired_kernel_layout != \"default\":\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n\n    # Handle default kernel layouts\n    if desired_data_layout == \"NCHW\":\n        new_attrs[\"kernel_layout\"] = \"IOHW\"\n        return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n    elif desired_data_layout == \"NHWC\":\n        new_attrs[\"kernel_layout\"] = \"HWIO\"\n        return relay.nn.conv2d_transpose(data, weight, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported.\" % desired_data_layout)\n\n\n# conv3d_transpose\nreg.register_strategy(\"nn.conv3d_transpose\", strategy.conv3d_transpose_strategy)\n\n\n@reg.register_legalize(\"nn.conv3d_transpose\")\ndef legalize_conv3d_transpose(attrs, inputs, types):\n    \"\"\"Legalize conv3d_transpose op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current Transposed convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.conv3d_transpose_legalize(attrs, inputs, types)\n\n\n# conv3d\nreg.register_strategy(\"nn.conv3d\", strategy.conv3d_strategy)\n\n\n@reg.register_alter_op_layout(\"nn.conv3d\")\ndef alter_op_layout_conv3d(attrs, inputs, tinfos, out_type):\n    \"\"\"Alternate the layout of conv3d\"\"\"\n    return topi.nn.conv3d_alter_layout(attrs, inputs, tinfos, out_type)\n\n\n@reg.register_convert_op_layout(\"nn.conv3d\")\ndef convert_conv3d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for conv3d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    data, weight = inputs\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 2, \"A desired layout is expected for both of nn.conv3d's inputs\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    new_attrs[\"data_layout\"] = desired_data_layout\n\n    if desired_kernel_layout != \"default\":\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.nn.conv3d(data, weight, **new_attrs)\n\n    # Handle default kernel layouts\n    if desired_data_layout == \"NCDHW\":\n        new_attrs[\"kernel_layout\"] = \"OIDHW\"\n        return relay.nn.conv3d(data, weight, **new_attrs)\n    elif desired_data_layout == \"NDHWC\":\n        new_attrs[\"kernel_layout\"] = \"DHWIO\"\n        return relay.nn.conv3d(data, weight, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported\" % desired_data_layout)\n\n\n# conv3d_winograd related operators\nreg.register_strategy(\n    \"nn.contrib_conv3d_winograd_without_weight_transform\",\n    strategy.conv3d_winograd_without_weight_transform_strategy,\n)\n\n\n@reg.register_compute(\"nn.contrib_conv3d_winograd_weight_transform\")\ndef compute_contrib_conv3d_winograd_weight_transform(attrs, inputs, out_dtype):\n    \"\"\"Compute definition of contrib_conv3d_winograd_weight_transform\"\"\"\n    out = topi.nn.conv3d_winograd_weight_transform(inputs[0], attrs.get_int(\"tile_size\"))\n    return [out]\n\n\nreg.register_schedule(\n    \"nn.contrib_conv3d_winograd_weight_transform\",\n    strategy.schedule_conv3d_winograd_weight_transform,\n)\n\n\n# conv1d_transpose\nreg.register_strategy(\"nn.conv1d_transpose\", strategy.conv1d_transpose_strategy)\n\n\n# bias_add\nreg.register_injective_schedule(\"nn.bias_add\")\n\n\n# max_pool1d\nreg.register_schedule(\"nn.max_pool1d\", strategy.schedule_pool)\n\n\n# max_pool2d\nreg.register_schedule(\"nn.max_pool2d\", strategy.schedule_pool)\n\n\n@reg.register_convert_op_layout(\"nn.max_pool2d\")\ndef convert_max_pool2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for max_pool2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current pooling\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of one layout string\n        layout string defining our desired layout for input and output.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    new_attrs = dict(attrs)\n    new_attrs[\"layout\"] = str(desired_layouts[0])\n    new_attrs[\"out_layout\"] = str(desired_layouts[0])\n    return relay.nn.max_pool2d(*inputs, **new_attrs)\n\n\n# max_pool3d\nreg.register_schedule(\"nn.max_pool3d\", strategy.schedule_pool)\n\n\n# avg_pool1d\nreg.register_schedule(\"nn.avg_pool1d\", strategy.schedule_pool)\n\n\n# avg_pool2d\nreg.register_schedule(\"nn.avg_pool2d\", strategy.schedule_pool)\n\n\n@reg.register_convert_op_layout(\"nn.avg_pool2d\")\ndef convert_avg_pool2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for avg_pool2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current pooling\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of one layout string\n        layout string defining our desired layout for input and output.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    new_attrs = dict(attrs)\n    new_attrs[\"layout\"] = str(desired_layouts[0])\n    new_attrs[\"out_layout\"] = str(desired_layouts[0])\n    return relay.nn.avg_pool2d(*inputs, **new_attrs)\n\n\n# avg_pool3d\nreg.register_schedule(\"nn.avg_pool3d\", strategy.schedule_pool)\n\n\n# max_pool2d_grad\nreg.register_schedule(\"nn.max_pool2d_grad\", strategy.schedule_pool_grad)\n\n\n# avg_pool2d_grad\nreg.register_schedule(\"nn.avg_pool2d_grad\", strategy.schedule_pool_grad)\n\n\n# adaptive_max_pool1d\nreg.register_schedule(\"nn.adaptive_max_pool1d\", strategy.schedule_adaptive_pool)\n\n\n# adaptive_avg_pool1d\nreg.register_schedule(\"nn.adaptive_avg_pool1d\", strategy.schedule_adaptive_pool)\n\n\n# global_max_pool2d\nreg.register_schedule(\"nn.global_max_pool2d\", strategy.schedule_adaptive_pool)\n\n\n@reg.register_convert_op_layout(\"nn.global_max_pool2d\")\ndef convert_global_max_pool2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for global_max_pool2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current pooling\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of one layout string\n        layout string defining our desired layout for input and output.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    new_attrs = dict(attrs)\n    new_attrs[\"layout\"] = str(desired_layouts[0])\n    new_attrs[\"out_layout\"] = str(desired_layouts[0])\n    return relay.nn.global_max_pool2d(*inputs, **new_attrs)\n\n\n# global_avg_pool2d\nreg.register_schedule(\"nn.global_avg_pool2d\", strategy.schedule_adaptive_pool)\n\n\n@reg.register_convert_op_layout(\"nn.global_avg_pool2d\")\ndef convert_global_avg_pool2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for global_avg_pool2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current pooling\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of one layout string\n        layout string defining our desired layout for input and output.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    new_attrs = dict(attrs)\n    new_attrs[\"layout\"] = str(desired_layouts[0])\n    new_attrs[\"out_layout\"] = str(desired_layouts[0])\n    return relay.nn.global_avg_pool2d(*inputs, **new_attrs)\n\n\n# adaptive_max_pool2d\nreg.register_schedule(\"nn.adaptive_max_pool2d\", strategy.schedule_adaptive_pool)\n\n\n# adaptive_avg_pool2d\nreg.register_schedule(\"nn.adaptive_avg_pool2d\", strategy.schedule_adaptive_pool)\n\n\n# adaptive_max_pool3d\nreg.register_schedule(\"nn.adaptive_max_pool3d\", strategy.schedule_adaptive_pool)\n\n\n# adaptive_avg_pool3d\nreg.register_schedule(\"nn.adaptive_avg_pool3d\", strategy.schedule_adaptive_pool)\n\n\n# leaky_relu\nreg.register_broadcast_schedule(\"nn.leaky_relu\")\n\n\n# prelu\nreg.register_broadcast_schedule(\"nn.prelu\")\n\n\n# flatten\nreg.register_broadcast_schedule(\"nn.batch_flatten\")\n\n\n# lrn\n@reg.register_compute(\"nn.lrn\")\ndef compute_lrn(attrs, inputs, out_dtype):\n    \"\"\"Compute definition of lrn\"\"\"\n    assert len(inputs) == 1\n    return [topi.nn.lrn(inputs[0], attrs.size, attrs.axis, attrs.alpha, attrs.beta, attrs.bias)]\n\n\nreg.register_schedule(\"nn.lrn\", strategy.schedule_lrn)\n\n\n# upsampling\n@reg.register_compute(\"nn.upsampling\")\ndef compute_upsampling(attrs, inputs, out_dtype):\n    scale_h = attrs.scale_h\n    scale_w = attrs.scale_w\n    layout = attrs.layout\n    method = attrs.method\n    align_corners = attrs.align_corners\n    return [topi.nn.upsampling(inputs[0], scale_h, scale_w, layout, method, align_corners)]\n\n\nreg.register_injective_schedule(\"nn.upsampling\")\n\n\n# upsampling3d\n@reg.register_compute(\"nn.upsampling3d\")\ndef compute_upsampling3d(attrs, inputs, out_dtype):\n    scale_d = attrs.scale_d\n    scale_h = attrs.scale_h\n    scale_w = attrs.scale_w\n    layout = attrs.layout\n    method = attrs.method\n    coordinate_transformation_mode = attrs.coordinate_transformation_mode\n    return [\n        topi.nn.upsampling3d(\n            inputs[0], scale_d, scale_h, scale_w, layout, method, coordinate_transformation_mode\n        )\n    ]\n\n\nreg.register_injective_schedule(\"nn.upsampling3d\")\n\n\n# pad\nreg.register_schedule(\"nn.pad\", strategy.schedule_pad)\n\n\n# mirror_pad\n@reg.register_compute(\"nn.mirror_pad\")\ndef compute_mirror_pad(attrs, inputs, out_dtype):\n    pad_before, pad_after = list(zip(*attrs.pad_width))\n    mode = attrs.mode\n    out = topi.nn.mirror_pad(inputs[0], pad_before=pad_before, pad_after=pad_after, mode=mode)\n    return [out]\n\n\nreg.register_broadcast_schedule(\"nn.mirror_pad\")\n\n\n@script\ndef _mirror_pad_func(data_shape, pad_width):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(data_shape.shape[0]):\n        out[i] = data_shape[i] + int64(pad_width[i][0]) + int64(pad_width[i][1])\n    return out\n\n\n@reg.register_shape_func(\"nn.mirror_pad\", False)\ndef mirror_pad_func(attrs, inputs, _):\n    pad_width_tuple = [get_const_tuple(p) for p in attrs.pad_width]\n    return [_mirror_pad_func(inputs[0], convert(pad_width_tuple))]\n\n\n# conv2d_winograd related operators\nreg.register_strategy(\n    \"nn.contrib_conv2d_winograd_without_weight_transform\",\n    strategy.conv2d_winograd_without_weight_transform_strategy,\n)\n\n\n# conv2d_gemm related operators\nreg.register_strategy(\n    \"nn.contrib_conv2d_gemm_without_weight_transform\",\n    strategy.conv2d_gemm_without_weight_transform_strategy,\n)\n\n\n@reg.register_compute(\"nn.contrib_conv2d_gemm_weight_transform\")\ndef compute_contrib_conv2d_gemm_weight_transform(attrs, inputs, out_dtype):\n    \"\"\"Compute definition of contrib_conv2d_gemm_weight_transform\"\"\"\n    out = topi.nn.conv2d_gemm_weight_transform(inputs[0], attrs.tile_rows, attrs.tile_cols)\n    return [out]\n\n\nreg.register_schedule(\n    \"nn.contrib_conv2d_gemm_weight_transform\", strategy.schedule_conv2d_gemm_weight_transform\n)\n\n\n@reg.register_compute(\"nn.contrib_conv2d_winograd_weight_transform\")\ndef compute_contrib_conv2d_winograd_weight_transform(attrs, inputs, out_dtype):\n    \"\"\"Compute definition of contrib_conv2d_winograd_weight_transform\"\"\"\n    out = topi.nn.conv2d_winograd_weight_transform(inputs[0], attrs.get_int(\"tile_size\"))\n    return [out]\n\n\nreg.register_schedule(\n    \"nn.contrib_conv2d_winograd_weight_transform\",\n    strategy.schedule_conv2d_winograd_weight_transform,\n)\n\n\n@reg.register_compute(\"nn.contrib_conv2d_winograd_nnpack_weight_transform\")\ndef compute_contrib_conv2d_winograd_nnpack_weight_transform(attrs, inputs, out_dtype):\n    \"\"\"Compute definition of contrib_conv2d_winograd_nnpack_weight_transform\"\"\"\n    convolution_algorithm = attrs.get_int(\"convolution_algorithm\")\n    out = topi.nn.conv2d_winograd_nnpack_weight_transform(\n        inputs[0], convolution_algorithm, out_dtype\n    )\n    return [out]\n\n\nreg.register_schedule(\n    \"nn.contrib_conv2d_winograd_nnpack_weight_transform\",\n    strategy.schedule_conv2d_winograd_nnpack_weight_transform,\n)\n\n\n# conv2d_NCHWc\nreg.register_strategy(\"nn.contrib_conv2d_NCHWc\", strategy.conv2d_NCHWc_strategy)\n\n# depthwise_conv2d_NCHWc\nreg.register_strategy(\"nn.contrib_depthwise_conv2d_NCHWc\", strategy.depthwise_conv2d_NCHWc_strategy)\n\n\n# deformable_conv2d\nreg.register_strategy(\"nn.deformable_conv2d\", strategy.deformable_conv2d_strategy)\n\n\n@reg.register_alter_op_layout(\"nn.deformable_conv2d\")\ndef alter_op_layout_deformable_conv2d(attrs, inputs, tinfos, out_type):\n    \"\"\"Alternate the layout of deformable conv2d\"\"\"\n    return None\n\n\n@reg.register_legalize(\"nn.deformable_conv2d\")\ndef legalize_deformable_conv2d(attrs, inputs, types):\n    \"\"\"Legalize deformable conv2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return None\n\n\n@reg.register_convert_op_layout(\"nn.deformable_conv2d\")\ndef convert_deformable_conv2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for deformable conv2d op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    data, offset, weight = inputs\n    new_attrs = dict(attrs)\n    for attr in new_attrs:\n        if isinstance(new_attrs[attr], container.Array):\n            new_attrs[attr] = list(new_attrs[attr])\n        elif isinstance(new_attrs[attr], expr.IntImm):\n            new_attrs[attr] = new_attrs[attr].value\n\n    # First check if there is a LayoutConfig scope, and if so, whether\n    # it indicates we should ignore this layer or not.\n    layout_config = LayoutConfig.current\n    if layout_config is not None:\n        skip_layer = layout_config.check_skip()\n        if skip_layer:\n            return relay.nn.deformable_conv2d(data, offset, weight, **new_attrs)\n\n    # Prepare new layout.\n    assert len(desired_layouts) == 2, \"A desired layout is expected for data and kernel\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    new_attrs[\"data_layout\"] = desired_data_layout\n\n    if desired_kernel_layout != \"default\":\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.nn.deformable_conv2d(data, offset, weight, **new_attrs)\n\n    # Handle default kernel layouts\n    if desired_data_layout == \"NCHW\":\n        new_attrs[\"kernel_layout\"] = \"OIHW\"\n    elif desired_data_layout == \"NHWC\":\n        new_attrs[\"kernel_layout\"] = \"HWIO\"\n    else:\n        raise ValueError(\"Layout %s is not yet supported.\" % desired_data_layout)\n\n    return relay.nn.deformable_conv2d(data, offset, weight, **new_attrs)\n\n\n# bitpack\n@reg.register_compute(\"nn.bitpack\")\ndef compute_bitpack(attrs, inputs, out_dtype):\n    \"\"\"Compute definition for bitpack\"\"\"\n    bits = attrs.bits\n    pack_axis = attrs.pack_axis\n    bit_axis = attrs.bit_axis\n    pack_type = attrs.pack_type\n    name = attrs.name\n    out = topi.nn.bitpack(inputs[0], bits, pack_axis, bit_axis, pack_type, name)\n    return [out]\n\n\nreg.register_schedule(\"nn.bitpack\", strategy.schedule_bitpack)\n\n\n# bitserial_conv2d\nreg.register_strategy(\"nn.bitserial_conv2d\", strategy.bitserial_conv2d_strategy)\n\n\n@reg.register_legalize(\"nn.bitserial_conv2d\")\ndef legalize_bitserial_conv2d(attrs, inputs, types):\n    \"\"\"Legalize bitserial_conv2d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return topi.nn.bitserial_conv2d_legalize(attrs, inputs, types)\n\n\n# bitserial_dense\nreg.register_strategy(\"nn.bitserial_dense\", strategy.bitserial_dense_strategy)\n\n\n# cross_entropy\n@reg.register_compute(\"nn.cross_entropy\")\ndef compute_cross_entropy(attrs, inputs, out_dtype):\n    x, y = inputs\n    return [-topi.sum(topi.log(x) * y) / x.shape[0]]\n\n\nreg.register_reduce_schedule(\"nn.cross_entropy\")\n\n\n# dilate\n@reg.register_compute(\"nn.dilate\")\ndef compute_dilate(attrs, inputs, out_dtype):\n    return [topi.nn.dilate(inputs[0], attrs.strides, attrs.dilation_value)]\n\n\nreg.register_broadcast_schedule(\"nn.dilate\")\n\n\n# cross_entropy_with_logits\n@reg.register_compute(\"nn.cross_entropy_with_logits\")\ndef compute_cross_entropy_with_logits(attrs, inputs, out_dtype):\n    x, y = inputs\n    return [-topi.sum(x * y) / x.shape[0]]\n\n\nreg.register_reduce_schedule(\"nn.cross_entropy_with_logits\")\n\n\n# nll_loss\n@reg.register_compute(\"nn.nll_loss\")\ndef compute_nll_loss(attrs, inputs, out_dtype):\n    predictions, targets, weights = inputs\n    return [topi.nn.nll_loss(predictions, targets, weights, attrs.reduction, attrs.ignore_index)]\n\n\nreg.register_reduce_schedule(\"nn.nll_loss\")\n\n\n# depth_to_space\n@reg.register_compute(\"nn.depth_to_space\")\ndef compute_depth_to_space(attrs, inputs, out_dtype):\n    block_size = attrs.block_size\n    layout = attrs.layout\n    mode = attrs.mode\n    return [topi.nn.depth_to_space(inputs[0], block_size, layout=layout, mode=mode)]\n\n\nreg.register_injective_schedule(\"nn.depth_to_space\")\n\n\n# space_to_depth\n@reg.register_compute(\"nn.space_to_depth\")\ndef compute_space_to_depth(attrs, inputs, out_dtype):\n    block_size = attrs.block_size\n    layout = attrs.layout\n    return [topi.nn.space_to_depth(inputs[0], block_size, layout=layout)]\n\n\nreg.register_injective_schedule(\"nn.space_to_depth\")\n\n\n# correlation\nreg.register_strategy(\"nn.correlation\", strategy.correlation_strategy)\n\n\n# space_to_batch_nd and batch_to_space_nd\nreg.register_injective_schedule(\"nn.space_to_batch_nd\")\nreg.register_injective_schedule(\"nn.batch_to_space_nd\")\n\n\nreg.register_strategy(\"nn.conv2d_backward_weight\", strategy.conv2d_backward_weight_strategy)\n\n\n@reg.register_legalize(\"nn.conv2d_backward_weight\")\ndef legalize_conv2d_backward_weight(attrs, inputs, types):\n    \"\"\"Legalize conv2d_backward_weight op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    grad, data = inputs\n    data_shape = get_const_tuple(data.checked_type.shape)\n    weight_shape = get_const_tuple(types[2].shape)\n    _, out_channel, grad_h, grad_w = get_const_tuple(grad.checked_type.shape)\n    batch, in_channel, in_h, in_w = data_shape\n    _, _, filter_h, filter_w = weight_shape\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(\n        get_const_tuple(attrs.padding), (filter_h, filter_w)\n    )\n    stride_h, stride_w = get_const_tuple(attrs.strides)\n    dilation_h, dilation_w = get_const_tuple(attrs.dilation)\n\n    grad = relay.tile(grad, [1, in_channel // attrs.groups, 1, 1])\n    grad = relay.reshape(grad, [-1, 1, 0, 0])  # batch * oc * ic // groups, 1, oh, ow\n    data = relay.reshape(data, [1, -1, 0, 0])  # 1, batch * ic, ih, iw\n\n    backward_weight = relay.nn.conv2d(\n        data,\n        grad,\n        strides=attrs.dilation,\n        padding=attrs.padding,\n        dilation=attrs.strides,\n        groups=in_channel * batch,\n        out_dtype=attrs.out_dtype,\n    )\n\n    # infer shape of backward_weight\n    padded_weight_grad_h = (\n        in_h - (grad_h - 1) * stride_h - 1 + fpad_top + fpad_bottom\n    ) // dilation_h + 1\n    padded_weight_grad_w = (\n        in_w - (grad_w - 1) * stride_w - 1 + fpad_left + fpad_right\n    ) // dilation_w + 1\n\n    backward_weight = relay.reshape(\n        backward_weight,\n        [\n            batch,\n            in_channel // attrs.groups,\n            out_channel,\n            padded_weight_grad_h,\n            padded_weight_grad_w,\n        ],\n    )\n    backward_weight = relay.sum(backward_weight, axis=0)\n    backward_weight = relay.transpose(backward_weight, [1, 0, 2, 3])\n\n    assert padded_weight_grad_h >= filter_h\n    assert padded_weight_grad_w >= filter_w\n\n    if padded_weight_grad_h > filter_h or padded_weight_grad_w > filter_w:\n        backward_weight = relay.strided_slice(\n            backward_weight,\n            begin=[0, 0, 0, 0],\n            end=[out_channel, in_channel // attrs.groups, filter_h, filter_w],\n        )\n\n    return backward_weight\n\n\n@reg.register_convert_op_layout(\"nn.conv2d_backward_weight\")\ndef convert_conv2d_backward_weight(attrs, inputs, _, desired_layouts):\n    \"\"\"Convert Layout pass registration for conv2d_backward_weight op.\n    Note that `desired_layouts` must be a pair [`data_layout`, `kernel_layouts`],\n    where `kernel_layouts` affects the output of this op (since the output of this op\n    is the weight gradient). The layout of the output gradient (the second input to this op)\n    is assumed to be the same as `data_layout`.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    new_attrs = dict(attrs)\n    assert len(desired_layouts) == 2, \"A desired layout is expected for both of data and gradient.\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    new_attrs[\"grad_layout\"] = desired_data_layout\n    new_attrs[\"data_layout\"] = desired_data_layout\n    new_attrs[\"kernel_layout\"] = desired_kernel_layout\n    new_attrs.pop(\"out_layout\")\n    return relay.nn.conv2d_backward_weight(inputs[0], inputs[1], **new_attrs)\n\n\n#####################\n#  Shape functions  #\n#####################\n\n\n@script\ndef _conv_shape_func_nchw(dshape, kshape, strides, padding, dilation):\n    \"\"\"Shape function for conv*d op with nchw & oihw layout.\"\"\"\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    out[0] = dshape[0]\n    out[1] = kshape[0]\n\n    for i in const_range(dshape.shape[0] - 2):\n        dilated_k = (kshape[i + 2] - 1) * dilation[i] + 1\n        out[i + 2] = (dshape[i + 2] + 2 * padding[i] - dilated_k) // strides[i] + 1\n    return out\n\n\n@script\ndef _conv_shape_func_nhwc_hwio(dshape, kshape, strides, padding, dilation):\n    \"\"\"Shape function for conv*d op with nhwc & hwio layout.\"\"\"\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    out[0] = dshape[0]\n    out[dshape.shape[0] - 1] = kshape[kshape.shape[0] - 1]\n\n    for i in const_range(dshape.shape[0] - 2):\n        dilated_k = (kshape[i] - 1) * dilation[i] + 1\n        out[i + 1] = (dshape[i + 1] + 2 * padding[i] - dilated_k) // strides[i] + 1\n    return out\n\n\n@script\ndef _conv_shape_func_nhwc_hwoi(dshape, kshape, strides, padding, dilation):\n    \"\"\"Shape function for conv*d op with nhwc & hwoi layout.\"\"\"\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    out[0] = dshape[0]\n    out[dshape.shape[0] - 1] = kshape[kshape.shape[0] - 2]\n\n    for i in const_range(dshape.shape[0] - 2):\n        dilated_k = (kshape[i] - 1) * dilation[i] + 1\n        out[i + 1] = (dshape[i + 1] + 2 * padding[i] - dilated_k) // strides[i] + 1\n    return out\n\n\n@script\ndef _conv_shape_func_nhwc_ohwi(dshape, kshape, strides, padding, dilation):\n    \"\"\"Shape function for conv*d op with nhwc & ohwi layout.\"\"\"\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    out[0] = dshape[0]\n    out[dshape.shape[0] - 1] = kshape[0]\n\n    for i in const_range(dshape.shape[0] - 2):\n        dilated_k = (kshape[i + 1] - 1) * dilation[i] + 1\n        out[i + 1] = (dshape[i + 1] + 2 * padding[i] - dilated_k) // strides[i] + 1\n    return out\n\n\ndef conv_shape_func(attrs, inputs, _):\n    \"\"\"Shape function for conv*d op.\"\"\"\n    strides = get_const_tuple(attrs.strides)\n    padding = get_const_tuple(attrs.padding)\n    dilation = get_const_tuple(attrs.dilation)\n\n    shape_func = None\n    if attrs[\"data_layout\"] == \"NCHW\" and attrs[\"kernel_layout\"] == \"OIHW\":\n        shape_func = _conv_shape_func_nchw\n    elif attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWIO\":\n        shape_func = _conv_shape_func_nhwc_hwio\n    elif attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWOI\":\n        shape_func = _conv_shape_func_nhwc_hwoi\n    elif attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"OHWI\":\n        shape_func = _conv_shape_func_nhwc_ohwi\n    else:\n        raise ValueError(\n            \"Unsupported data/kernel layout: %s, %s\"\n            % (attrs[\"data_layout\"], attrs[\"kernel_layout\"])\n        )\n\n    return [shape_func(inputs[0], inputs[1], convert(strides), convert(padding), convert(dilation))]\n\n\nreg.register_shape_func(\"nn.conv1d\", False, conv_shape_func)\nreg.register_shape_func(\"nn.conv2d\", False, conv_shape_func)\nreg.register_shape_func(\"nn.conv3d\", False, conv_shape_func)\n\n\n@script\ndef _conv2d_NCHWc_shape_func(dshape, kshape, strides, padding, dilation, oc_bn):\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    ic_chunk = dshape[1]\n    height = dshape[2]\n    width = dshape[3]\n    ic_bn = dshape[4]\n    kheight = kshape[2]\n    kwidth = kshape[3]\n    dilated_kh = (kheight - 1) * dilation[0] + 1\n    dilated_kw = (kwidth - 1) * dilation[1] + 1\n    kflatten = int64(1)\n    for i in const_range(kshape.shape[0]):\n        kflatten *= kshape[i]\n\n    oc = kflatten // (kheight * kwidth * ic_chunk * ic_bn)\n    oc_chunk = oc // oc_bn\n\n    out_height = (height + 2 * padding[0] - dilated_kh) // strides[0] + 1\n    out_width = (width + 2 * padding[1] - dilated_kw) // strides[1] + 1\n\n    out[0] = dshape[0]\n    out[1] = oc_chunk\n    out[2] = out_height\n    out[3] = out_width\n    out[4] = int64(oc_bn)\n    return out\n\n\n@reg.register_shape_func(\"nn.contrib_conv2d_NCHWc\", False)\ndef conv2d_NCHWc_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for contrib_conv2d_NCHWc op.\n    \"\"\"\n    strides = get_const_tuple(attrs.strides)\n    padding = get_const_tuple(attrs.padding)\n    dilation = get_const_tuple(attrs.dilation)\n    out_layout = attrs.out_layout\n    oc_bn = int(out_layout[4:-1])\n\n    return [\n        _conv2d_NCHWc_shape_func(\n            inputs[0],\n            inputs[1],\n            convert(strides),\n            convert(padding),\n            convert(dilation),\n            convert(oc_bn),\n        )\n    ]\n\n\n@script\ndef _conv_transpose_shape_func(dshape, kshape, strides, padding, dilation, output_padding):\n    out = output_tensor((dshape.shape[0],), \"int64\")\n    out[0] = dshape[0]\n    out[1] = kshape[1]\n\n    for i in const_range(dshape.shape[0] - 2):\n        dilated_k = (kshape[i + 2] - 1) * dilation[i] + 1\n        out[i + 2] = (\n            strides[i] * (dshape[i + 2] - 1) + dilated_k - 2 * padding[i] + output_padding[i]\n        )\n    return out\n\n\ndef conv_transpose_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for contrib_conv2d_NCHWc op.\n    \"\"\"\n    strides = get_const_tuple(attrs.strides)\n    padding = get_const_tuple(attrs.padding)\n    dilation = get_const_tuple(attrs.dilation)\n    output_padding = get_const_tuple(attrs.output_padding)\n\n    return [\n        _conv_transpose_shape_func(\n            inputs[0],\n            inputs[1],\n            convert(strides),\n            convert(padding),\n            convert(dilation),\n            convert(output_padding),\n        )\n    ]\n\n\nreg.register_shape_func(\"nn.conv1d_transpose\", False, conv_transpose_shape_func)\nreg.register_shape_func(\"nn.conv2d_transpose\", False, conv_transpose_shape_func)\n\n\n@script\ndef _pool2d_shape_func(data_shape, pool_size, strides, padding, height_axis, width_axis):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(data_shape.shape[0]):\n        if i == height_axis:\n            out[i] = (data_shape[i] + padding[0] + padding[2] - pool_size[0]) // strides[0] + 1\n        elif i == width_axis:\n            out[i] = (data_shape[i] + padding[1] + padding[3] - pool_size[1]) // strides[1] + 1\n        else:\n            out[i] = data_shape[i]\n\n    return out\n\n\ndef pool2d_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for pool2d op.\n    \"\"\"\n    pool_size = get_const_tuple(attrs.pool_size)\n    strides = get_const_tuple(attrs.strides)\n    padding = get_const_tuple(attrs.padding)\n    layout = attrs.layout\n    height_axis = layout.index(\"H\")\n    width_axis = layout.index(\"W\")\n    if len(padding) == 1:\n        padding = [padding[0]] * 4\n    elif len(padding) == 2:\n        padding = [padding[0], padding[1], padding[0], padding[1]]\n\n    return [\n        _pool2d_shape_func(\n            inputs[0],\n            convert(pool_size),\n            convert(strides),\n            convert(padding),\n            convert(height_axis),\n            convert(width_axis),\n        )\n    ]\n\n\nreg.register_shape_func(\"nn.max_pool2d\", False, pool2d_shape_func)\nreg.register_shape_func(\"nn.avg_pool2d\", False, pool2d_shape_func)\n\n\n@script\ndef _global_pool2d_shape_func(data_shape, height_axis, width_axis):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(out.shape[0]):\n        if i == height_axis or i == width_axis:\n            out[i] = int64(1)\n        else:\n            out[i] = data_shape[i]\n\n    return out\n\n\ndef global_pool2d_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for global pool2d op.\n    \"\"\"\n    layout = attrs.layout\n    height_axis = width_axis = 1\n    for i, letter in enumerate(layout):\n        if letter == \"H\":\n            height_axis = i\n        if letter == \"W\":\n            width_axis = i\n    return [_global_pool2d_shape_func(inputs[0], convert(height_axis), convert(width_axis))]\n\n\nreg.register_shape_func(\"nn.global_max_pool2d\", False, global_pool2d_shape_func)\nreg.register_shape_func(\"nn.global_avg_pool2d\", False, global_pool2d_shape_func)\n\n\n@script\ndef _batch_flatten_shape_func(data_shape):\n    out = output_tensor((2,), \"int64\")\n    out[0] = data_shape[0]\n    out[1] = int64(1)\n    for i in const_range(data_shape.shape[0] - 1):\n        out[1] *= data_shape[i + 1]\n\n    return out\n\n\n@reg.register_shape_func(\"nn.batch_flatten\", False)\ndef batch_flatten_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for batch_flatten op.\n    \"\"\"\n    return [_batch_flatten_shape_func(inputs[0])]\n\n\n@script\ndef _matmul_shape_func(tensor_a_shape, tensor_b_shape, transpose_a, transpose_b):\n    out = output_tensor((tensor_a_shape.shape[0],), \"int64\")\n    for i in const_range(out.shape[0] - 1):\n        out[i] = tensor_a_shape[i]\n    if transpose_a:\n        out[out.shape[0] - 2] = out[out.shape[0] - 1]\n    out[out.shape[0] - 1] = tensor_b_shape[0] if transpose_b else tensor_b_shape[1]\n\n    return out\n\n\n@reg.register_shape_func(\"nn.matmul\", False)\ndef matmul_shape_func(attrs, inputs, _):\n    \"\"\"Shape function for matmul op.\"\"\"\n    ret = [\n        _matmul_shape_func(\n            inputs[0],\n            inputs[1],\n            expr.IntImm(\"bool\", attrs.transpose_a),\n            expr.IntImm(\"bool\", attrs.transpose_b),\n        )\n    ]\n    return ret\n\n\n@reg.register_shape_func(\"nn.dense\", False)\ndef dense_shape_func(attrs, inputs, _):\n    \"\"\"Shape function for dense op. This is an alias of matmul_nt operator for data tensor in\n    non-transposed format and weight tensor in transposed format.\n    \"\"\"\n    ret = [\n        _matmul_shape_func(\n            inputs[0],\n            inputs[1],\n            expr.IntImm(\"bool\", False),\n            expr.IntImm(\"bool\", True),\n        )\n    ]\n    return ret\n\n\n@script\ndef _dense_pack_shape_func(data_shape, weight_shape):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    assert data_shape.shape[0] == 2, \"Input data must be 2D\"\n    out[0] = data_shape[0]\n    out[1] = weight_shape[0] * weight_shape[2]\n\n    return out\n\n\n@reg.register_shape_func(\"nn.contrib_dense_pack\", False)\ndef dense_pack_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for dense_pack op.\n    \"\"\"\n    ret = [_dense_pack_shape_func(inputs[0], inputs[1])]\n    return ret\n\n\n@script\ndef _batch_matmul_shape_func(tensor_a_shape, tensor_b_shape, transpose_a, transpose_b):\n    out = output_tensor((tensor_a_shape.shape[0],), \"int64\")\n    out[0] = max(tensor_a_shape[0], tensor_b_shape[0])\n    out[1] = tensor_a_shape[2] if transpose_a else tensor_a_shape[1]\n    out[2] = tensor_b_shape[1] if transpose_b else tensor_b_shape[2]\n\n    return out\n\n\n@reg.register_shape_func(\"nn.batch_matmul\", False)\ndef batch_matmul_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for batch matmul op.\n    \"\"\"\n    ret = [\n        _batch_matmul_shape_func(\n            inputs[0],\n            inputs[1],\n            expr.IntImm(\"bool\", attrs.transpose_a),\n            expr.IntImm(\"bool\", attrs.transpose_b),\n        )\n    ]\n    return ret\n\n\n@script\ndef _pad_shape_func(data_shape, pad_width):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(out.shape[0]):\n        out[i] = data_shape[i] + pad_width[i][0] + pad_width[i][1]\n\n    return out\n\n\n@reg.register_shape_func(\"nn.pad\", False)\ndef pad_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for pad op.\n    \"\"\"\n    pad_width = []\n    for pair in attrs.pad_width:\n        pad_width.append(get_const_tuple(pair))\n    return [_pad_shape_func(inputs[0], convert(pad_width))]\n\n\n@script\ndef _dilate_shape_func(data_shape, strides):\n    out = output_tensor((data_shape.shape[0],), \"int64\")\n    for i in const_range(out.shape[0]):\n        out[i] = (data_shape[i] - 1) * strides[i] + 1\n\n    return out\n\n\n@reg.register_shape_func(\"nn.dilate\", False)\ndef dilate_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for dilate op.\n    \"\"\"\n    return [_dilate_shape_func(inputs[0], convert(attrs.strides))]\n\n\nreg.register_shape_func(\"nn.bias_add\", False, elemwise_shape_func)\nreg.register_shape_func(\"nn.softmax\", False, elemwise_shape_func)\nreg.register_shape_func(\"nn.fast_softmax\", False, elemwise_shape_func)\nreg.register_shape_func(\"nn.relu\", False, elemwise_shape_func)\nreg.register_shape_func(\"nn.leaky_relu\", False, elemwise_shape_func)\nreg.register_shape_func(\"nn.prelu\", False, elemwise_shape_func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/nn/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-lines\n\"\"\"Neural network operations.\"\"\"\nfrom tvm.relay import expr\n\nfrom ...expr import Constant, Expr, const\nfrom ..dyn.nn import _make as _dyn_make\nfrom . import _make\nfrom .utils import get_pad_tuple1d, get_pad_tuple2d, get_pad_tuple3d\n\n\ndef conv1d(\n    data,\n    weight,\n    strides=1,\n    padding=0,\n    dilation=1,\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCW\",\n    kernel_layout=\"OIW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"1D convolution.\n\n    This operator takes the weight as the convolution kernel\n    and convolves it with data to produce an output.\n\n\n    In the default case, where the data_layout is `NCW`\n    and kernel_layout is `OIW`, conv1d takes in\n    a data Tensor with shape `(batch_size, in_channels, width)`,\n    and a weight Tensor with shape `(channels, in_channels, kernel_size)`\n    to produce an output Tensor with the following rule:\n\n    .. math::\n\n        \\mbox{out}[b, c, w] = \\sum_{dw, k}\n           \\mbox{data}[b, k, \\mbox{strides}[0] * w + dw] *\n           \\mbox{weight}[c, k, dw]\n\n    Padding and dilation are applied to data and weight respectively before the computation.\n    This operator accepts data layout specification.\n    Semantically, the operator will convert the layout to the canonical layout\n    (`NCW` for data and `OIW` for weight), perform the computation,\n    then convert to the out_layout.\n\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Optional[int, Tuple[int]]\n        The strides of convolution.\n\n    padding : Optional[int, Tuple[int]]\n        The padding of convolution on both sides of the input before convolution.\n\n    dilation : Optional[int, Tuple[int]]\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : Optional[int]\n        Currently unused for 1D convolution.\n\n    channels : Optional[int]\n        Number of output channels of this convolution.\n\n    kernel_size : Optional[int, Tuple[int]]\n        The spatial dimension of the convolution kernel.\n\n    data_layout : Optional[str]\n        Layout of the input.\n\n    kernel_layout : Optional[str]\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(kernel_size, int):\n        kernel_size = (kernel_size,)\n    if isinstance(strides, int):\n        strides = (strides,)\n    if isinstance(dilation, int):\n        dilation = (dilation,)\n    padding = get_pad_tuple1d(padding)\n    return _make.conv1d(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef conv2d(\n    data,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"2D convolution.\n\n    This operator takes the weight as the convolution kernel\n    and convolves it with data to produce an output.\n\n\n    In the default case, where the data_layout is `NCHW`\n    and kernel_layout is `OIHW`, conv2d takes in\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    and a weight Tensor with shape `(channels, in_channels, kernel_size[0], kernel_size[1])`\n    to produce an output Tensor with the following rule:\n\n    .. math::\n\n        \\mbox{out}[b, c, y, x] = \\sum_{dy, dx, k}\n           \\mbox{data}[b, k, \\mbox{strides}[0] * y  + dy, \\mbox{strides}[1] * x + dx] *\n           \\mbox{weight}[c, k, dy, dx]\n\n    Padding and dilation are applied to data and weight respectively before the computation.\n    This operator accepts data layout specification.\n    Semantically, the operator will convert the layout to the canonical layout\n    (`NCHW` for data and `OIHW` for weight), perform the computation,\n    then convert to the out_layout.\n\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Optional[int, Tuple[int]]\n        The strides of convolution.\n\n    padding : Optional[int, Tuple[int]]\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : Optional[int, Tuple[int]]\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : Optional[int]\n        Number of groups for grouped convolution.\n\n    channels : Optional[int]\n        Number of output channels of this convolution.\n\n    kernel_size : Optional[int, Tuple[int]]\n        The spatial of the convolution kernel.\n\n    data_layout : Optional[str]\n        Layout of the input.\n\n    kernel_layout : Optional[str]\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(kernel_size, int):\n        kernel_size = (kernel_size, kernel_size)\n    if isinstance(strides, int):\n        strides = (strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation)\n    # TODO enforce 4-way padding in topi/nn/conv2d after #4644 merged\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.conv2d(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef conv3d(\n    data,\n    weight,\n    strides=(1, 1, 1),\n    padding=(0, 0, 0),\n    dilation=(1, 1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"3D convolution.\n\n    This operator takes the weight as the convolution kernel\n    and convolves it with data to produce an output.\n\n\n    In the default case, where the data_layout is `NCDHW`\n    and kernel_layout is `OIDHW`, conv3d takes in\n    a data Tensor with shape `(batch_size, in_channels, depth, height, width)`,\n    and a weight Tensor with shape `(channels, in_channels, kernel_size[0], kernel_size[1],\n    kernel_size[2])` to produce an output Tensor with the following rule:\n\n    .. math::\n\n        \\mbox{out}[b, c, z, y, x] = \\sum_{dz, dy, dx, k}\n           \\mbox{data}[b, k, \\mbox{strides}[0] * z  + dz, \\mbox{strides}[1] * y  + dy,\n           \\mbox{strides}[2] * x + dx] * \\mbox{weight}[c, k, dz, dy, dx]\n\n    Padding and dilation are applied to data and weight respectively before the computation.\n    This operator accepts data layout specification.\n    Semantically, the operator will convert the layout to the canonical layout\n    (`NCDHW` for data and `OIDHW` for weight), perform the computation,\n    then convert to the out_layout.\n\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Optional[Tuple[int]]\n        The strides of convolution.\n\n    padding : Optional[int, Tuple[int]]\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : Optional[int, Tuple[int]]\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : Optional[int]\n        Number of groups for grouped convolution.\n\n    channels : Optional[int]\n        Number of output channels of this convolution.\n\n    kernel_size : Optional[int, Tuple[int]]\n        The spatial of the convolution kernel.\n\n    data_layout : Optional[str]\n        Layout of the input.\n\n    kernel_layout : Optional[str]\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(kernel_size, int):\n        kernel_size = (kernel_size, kernel_size, kernel_size)\n    if isinstance(strides, int):\n        strides = (strides, strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation, dilation)\n    padding = get_pad_tuple3d(padding)\n    return _make.conv3d(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef contrib_conv3d_winograd_without_weight_transform(\n    data,\n    weight,\n    tile_size,\n    strides=(1, 1, 1),\n    padding=(0, 0, 0),\n    dilation=(1, 1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"3D convolution with winograd algorithm.\n\n    The basic parameters are the same as the ones in vanilla conv3d.\n    It assumes the weight is pre-transformed by nn.contrib_conv3d_winograd_weight_transform\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    tile_size : int\n        The Tile size of winograd. E.g. 2 for F(2x2x2, 3x3x3) and 4 for F(4x4x4, 3x3x3)\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 3-way padding to 6-way padding\n    padding = get_pad_tuple3d(padding)\n    return _make.contrib_conv3d_winograd_without_weight_transform(\n        data,\n        weight,\n        tile_size,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef conv3d_transpose(\n    data,\n    weight,\n    strides=(1, 1, 1),\n    padding=(0, 0, 0),\n    dilation=(1, 1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n    out_layout=\"\",\n    output_padding=(0, 0, 0),\n    out_dtype=\"\",\n):\n    r\"\"\"3D transpose convolution.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Optional[Tuple[int]]\n        The strides of convolution.\n\n    padding : Optional[int, Tuple[int]]\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : Optional[int, Tuple[int]]\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : Optional[int]\n        Number of groups for grouped convolution.\n\n    channels : Optional[int]\n        Number of output channels of this convolution.\n\n    kernel_size : Optional[int, Tuple[int]]\n        The spatial of the convolution kernel.\n\n    data_layout : Optional[str]\n        Layout of the input.\n\n    kernel_layout : Optional[str]\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision conv3d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    if isinstance(kernel_size, int):\n        kernel_size = (kernel_size, kernel_size, kernel_size)\n    if isinstance(strides, int):\n        strides = (strides, strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation, dilation)\n    padding = get_pad_tuple3d(padding)\n\n    return _make.conv3d_transpose(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        output_padding,\n        out_dtype,\n    )\n\n\ndef conv2d_transpose(\n    data,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"IOHW\",\n    out_layout=\"\",\n    output_padding=(0, 0),\n    out_dtype=\"\",\n):\n    \"\"\"Two dimensional transposed convolution operator.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Tuple[int], optional\n        The strides of convolution.\n\n    padding : Tuple[int], optional\n        The padding of convolution on both sides of inputs.\n\n    dilation : Tuple[int], optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    output_padding : Tuple[int], optional\n        Used to disambiguate the output shape.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.conv2d_transpose(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        output_padding,\n        out_dtype,\n    )\n\n\ndef conv1d_transpose(\n    data,\n    weight,\n    strides=(1,),\n    padding=(0,),\n    dilation=(1,),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCW\",\n    kernel_layout=\"OIW\",\n    out_layout=\"\",\n    output_padding=(0,),\n    out_dtype=\"\",\n):\n    \"\"\"One dimensional transposed convolution operator.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : Tuple[int], optional\n        The strides of convolution.\n\n    padding : Tuple[int], optional\n        The padding of convolution on both sides of inputs.\n\n    dilation : Tuple[int], optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    output_padding : Tuple[int], optional\n        Used to disambiguate the output shape.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.conv1d_transpose(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        output_padding,\n        out_dtype,\n    )\n\n\ndef softmax(data, axis=-1):\n    r\"\"\"Computes softmax.\n\n    .. math:: \\text{softmax}(x)_i = \\frac{exp(x_i)}{\\sum_j exp(x_j)}\n\n    .. note::\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data: tvm.relay.Expr\n        The input data to the operator.\n\n    axis: int, optional\n        The axis to sum over when computing softmax\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.softmax(data, axis)\n\n\ndef fast_softmax(data, axis=-1):\n    r\"\"\"Computes softmax.\n    Use approximation to compute exponent for faster speed.\n\n    .. math:: \\text{softmax}(x)_i = \\frac{exp(x_i)}{\\sum_j exp(x_j)}\n    .. note::\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data: tvm.relay.Expr\n        The input data to the operator.\n    axis: int, optional\n        The axis to sum over when computing softmax\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.fast_softmax(data, axis)\n\n\ndef log_softmax(data, axis=-1):\n    r\"\"\"Computes log softmax.\n\n    .. math::\n\n        \\text{log_softmax}(x)_i = \\log \\frac{exp(x_i)}{\\sum_j exp(x_j)}\n\n    .. note::\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data: tvm.relay.Expr\n        The input data to the operator.\n\n    axis: int, optional\n        The axis to sum over when computing log softmax\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.log_softmax(data, axis)\n\n\ndef max_pool1d(\n    data,\n    pool_size=(1,),\n    strides=(1,),\n    dilation=(1,),\n    padding=(0,),\n    layout=\"NCW\",\n    out_layout=\"\",\n    ceil_mode=False,\n):\n    r\"\"\"1D maximum pooling operator.\n\n    This operator takes data as input and does 1D max value calculation\n    with in pool_size sized window by striding defined by stride.\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, channels, width)`,\n    to produce an output Tensor.\n\n    The ceil_mode is used to take ceil or floor while computing out shape.\n    count_include_pad indicates including or excluding padded input values in computation.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : int or tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : int or tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size,)\n    if isinstance(strides, int):\n        strides = (strides,)\n    if isinstance(dilation, int):\n        dilation = (dilation,)\n    padding = get_pad_tuple1d(padding)\n    return _make.max_pool1d(\n        data, pool_size, strides, dilation, padding, layout, out_layout, ceil_mode\n    )\n\n\ndef max_pool2d(\n    data,\n    pool_size=(1, 1),\n    strides=(1, 1),\n    dilation=(1, 1),\n    padding=(0, 0),\n    layout=\"NCHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n):\n    r\"\"\"2D maximum pooling operator.\n\n    This operator takes data as input and does 2D max value calculation\n    with in pool_size sized window by striding defined by stride\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, h, w) and pool_size (kh, kw)\n\n    .. math::\n\n        \\mbox{out}(b, c, y, x)  = \\max_{m=0, \\ldots, kh-1} \\max_{n=0, \\ldots, kw-1}\n             \\mbox{data}(b, c, \\mbox{stride}[0] * y + m, \\mbox{stride}[1] * x + n)\n\n    Padding is applied to data before the computation.\n    ceil_mode is used to take ceil or floor while computing out shape.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size, pool_size)\n    if isinstance(strides, int):\n        strides = (strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation)\n    padding = get_pad_tuple2d(padding)\n    return _make.max_pool2d(\n        data, pool_size, strides, dilation, padding, layout, out_layout, ceil_mode\n    )\n\n\ndef max_pool3d(\n    data,\n    pool_size=(1, 1, 1),\n    strides=(1, 1, 1),\n    dilation=(1, 1, 1),\n    padding=(0, 0, 0),\n    layout=\"NCDHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n):\n    r\"\"\"3D maximum pooling operator.\n\n    This operator takes data as input and does 3D max value calculation\n    with in pool_size sized window by striding defined by stride.\n\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, channels, depth, height, width)`,\n    to produce an output Tensor.\n\n    The ceil_mode is used to take ceil or floor while computing out shape.\n    count_include_pad indicates including or excluding padded input values in computation.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size, pool_size, pool_size)\n    if isinstance(strides, int):\n        strides = (strides, strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation, dilation)\n    padding = get_pad_tuple3d(padding)\n    return _make.max_pool3d(\n        data, pool_size, strides, dilation, padding, layout, out_layout, ceil_mode\n    )\n\n\ndef avg_pool1d(\n    data,\n    pool_size=(1,),\n    strides=(1,),\n    dilation=(1,),\n    padding=(0,),\n    layout=\"NCW\",\n    out_layout=\"\",\n    ceil_mode=False,\n    count_include_pad=False,\n):\n    r\"\"\"1D average pooling operator.\n\n    This operator takes data as input and does 1D average value calculation\n    with in pool_size sized window by striding defined by stride\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, channels, width)`,\n    to produce an output Tensor.\n\n    The ceil_mode is used to take ceil or floor while computing out shape.\n    count_include_pad indicates including or excluding padded input values in computation.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : int or tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : int or tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    count_include_pad : bool, optional\n        To include padding to compute the average.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size,)\n    if isinstance(strides, int):\n        strides = (strides,)\n    if isinstance(dilation, int):\n        dilation = (dilation,)\n    padding = get_pad_tuple1d(padding)\n    return _make.avg_pool1d(\n        data,\n        pool_size,\n        strides,\n        dilation,\n        padding,\n        layout,\n        out_layout,\n        ceil_mode,\n        count_include_pad,\n    )\n\n\ndef avg_pool2d(\n    data,\n    pool_size=(1, 1),\n    strides=(1, 1),\n    dilation=(1, 1),\n    padding=(0, 0),\n    layout=\"NCHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n    count_include_pad=False,\n):\n    r\"\"\"2D average pooling operator.\n\n    This operator takes data as input and does 2D average value calculation\n    with in pool_size sized window by striding defined by stride\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, h, w), pool_size (kh, kw)\n\n    .. math::\n\n        \\mbox{out}(b, c, y, x)  = \\frac{1}{kh * kw} \\sum_{m=0}^{kh-1} \\sum_{n=0}^{kw-1}\n             \\mbox{data}(b, c, \\mbox{stride}[0] * y + m, \\mbox{stride}[1] * x + n)\n\n    Padding is applied to data before the computation.\n    ceil_mode is used to take ceil or floor while computing out shape.\n    count_include_pad indicates including or excluding padded input values in computation.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    count_include_pad : bool, optional\n        To include padding to compute the average.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size, pool_size)\n    if isinstance(strides, int):\n        strides = (strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation)\n    padding = get_pad_tuple2d(padding)\n    return _make.avg_pool2d(\n        data,\n        pool_size,\n        strides,\n        dilation,\n        padding,\n        layout,\n        out_layout,\n        ceil_mode,\n        count_include_pad,\n    )\n\n\ndef avg_pool3d(\n    data,\n    pool_size=(1, 1, 1),\n    strides=(1, 1, 1),\n    dilation=(1, 1, 1),\n    padding=(0, 0, 0),\n    layout=\"NCDHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n    count_include_pad=False,\n):\n    r\"\"\"3D average pooling operator.\n\n    This operator takes data as input and does 3D average value calculation\n    with in pool_size sized window by striding defined by stride\n\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, channels, depth, height, width)`,\n    to produce an output Tensor.\n\n    The ceil_mode is used to take ceil or floor while computing out shape.\n    count_include_pad indicates including or excluding padded input values in computation.\n    This operator accepts data layout specification.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    dilation : int or tuple of int, optional\n        The dilation of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    count_include_pad : bool, optional\n        To include padding to compute the average.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pool_size, int):\n        pool_size = (pool_size, pool_size, pool_size)\n    if isinstance(strides, int):\n        strides = (strides, strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation, dilation)\n    padding = get_pad_tuple3d(padding)\n    return _make.avg_pool3d(\n        data,\n        pool_size,\n        strides,\n        dilation,\n        padding,\n        layout,\n        out_layout,\n        ceil_mode,\n        count_include_pad,\n    )\n\n\ndef max_pool2d_grad(\n    out_grad,\n    data,\n    pool_size=(1, 1),\n    strides=(1, 1),\n    padding=(0, 0),\n    layout=\"NCHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n):\n    r\"\"\"Gradient of 2D maximum pooling operator.\n\n    This operator takes out_grad and data as input and calculates gradient of max_pool2d.\n\n    Parameters\n    ----------\n    out_grad : tvm.relay.Expr\n        The output gradient\n\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.max_pool2d_grad(\n        out_grad, data, pool_size, strides, padding, layout, out_layout, ceil_mode\n    )\n\n\ndef avg_pool2d_grad(\n    out_grad,\n    data,\n    pool_size=(1, 1),\n    strides=(1, 1),\n    padding=(0, 0),\n    layout=\"NCHW\",\n    out_layout=\"\",\n    ceil_mode=False,\n    count_include_pad=False,\n):\n    r\"\"\"Gradient of 2D average pooling operator.\n\n    This operator takes out_grad and data as input and calculates gradient of avg_pool2d.\n\n    Parameters\n    ----------\n    out_grad : tvm.relay.Expr\n        The output gradient\n\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    pool_size : int or tuple of int, optional\n        The size of window for pooling.\n\n    strides : tuple of int, optional\n        The strides of pooling.\n\n    padding : tuple of int, optional\n        The padding for pooling.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    ceil_mode : bool, optional\n        To enable or disable ceil while pooling.\n\n    count_include_pad : bool, optional\n        To include padding to compute the average.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.avg_pool2d_grad(\n        out_grad,\n        data,\n        pool_size,\n        strides,\n        padding,\n        layout,\n        out_layout,\n        ceil_mode,\n        count_include_pad,\n    )\n\n\ndef global_max_pool2d(data, layout=\"NCHW\", out_layout=\"\"):\n    r\"\"\"2D global maximum pooling operator.\n\n    This operator takes data as input and does 2D max value calculation\n    across each window represented by WxH.\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, h, w)\n\n    .. math::\n\n        \\mbox{out}(b, c, 1, 1)  = \\max_{m=0, \\ldots, h} \\max_{n=0, \\ldots, w}\n             \\mbox{data}(b, c, m, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.global_max_pool2d(data, layout, out_layout)\n\n\ndef global_avg_pool2d(data, layout=\"NCHW\", out_layout=\"\"):\n    r\"\"\"2D global average pooling operator.\n\n    This operator takes data as input and does 2D average value calculation\n    across each window represented by WxH.\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, h, w)\n\n    .. math::\n\n        \\mbox{out}(b, c, 1, 1)  = \\frac{1}{h * w} \\sum_{m=0}^{h-1} \\sum_{n=0}^{w-1}\n             \\mbox{data}(b, c, m, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : Optional[str]\n        Layout of the output\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.global_avg_pool2d(data, layout, out_layout)\n\n\ndef upsampling(\n    data, scale_h=1, scale_w=1, layout=\"NCHW\", method=\"nearest_neighbor\", align_corners=False\n):\n    \"\"\"Upsampling.\n\n    This operator takes data as input and does 2D scaling to the given scale factor.\n    In the default case, where the data_layout is `NCHW`\n    with data of shape (n, c, h, w)\n    out will have a shape (n, c, h*scale_h, w*scale_w)\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be one of (\"bilinear\", \"nearest_neighbor\", \"bicubic\")\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    scale_h : tvm.relay.Expr or int or float\n        The scale factor for height upsampling.\n\n    scale_w : tvm.relay.Expr or int or float\n        The scale factor for width upsampling.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method to used [nearest_neighbor, bilinear, bicubic].\n\n    align_corners : bool, optional\n        Whether to keep corners in proper place.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(scale_h, Constant):\n        scale_h = scale_h.data.numpy().item()\n    if isinstance(scale_w, Constant):\n        scale_w = scale_w.data.numpy().item()\n    if isinstance(scale_h, Expr) or isinstance(scale_w, Expr):\n        if not isinstance(scale_h, Expr):\n            scale_h = const(scale_h, \"float64\")\n        if not isinstance(scale_w, Expr):\n            scale_w = const(scale_w, \"float64\")\n        return _dyn_make.upsampling(data, scale_h, scale_w, layout, method, align_corners)\n    return _make.upsampling(data, scale_h, scale_w, layout, method, align_corners)\n\n\ndef upsampling3d(\n    data,\n    scale_d=1,\n    scale_h=1,\n    scale_w=1,\n    layout=\"NCDHW\",\n    method=\"nearest_neighbor\",\n    coordinate_transformation_mode=\"half_pixel\",\n):\n    \"\"\"3D Upsampling.\n\n    This operator takes data as input and does 3D scaling to the given scale factor.\n    In the default case, where the data_layout is `NCDHW`\n    with data of shape (n, c, d, h, w)\n    out will have a shape (n, c, d*scale_d, h*scale_h, w*scale_w)\n\n    method indicates the algorithm to be used while calculating the out value\n    and method can be one of (\"trilinear\", \"nearest_neighbor\")\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    scale_d : tvm.relay.Expr\n        The scale factor for depth upsampling.\n\n    scale_h : tvm.relay.Expr\n        The scale factor for height upsampling.\n\n    scale_w : tvm.relay.Expr\n        The scale factor for width upsampling.\n\n    layout : str, optional\n        Layout of the input.\n\n    method : str, optional\n        Scale method to used [nearest_neighbor, trilinear].\n\n    coordinate_transformation_mode: string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        Refer to the ONNX Resize operator specification for details.\n        Available options are \"half_pixel\", \"align_corners\" and \"asymmetric\".\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(scale_d, Constant):\n        scale_d = scale_d.data.numpy().item()\n    if isinstance(scale_h, Constant):\n        scale_h = scale_h.data.numpy().item()\n    if isinstance(scale_w, Constant):\n        scale_w = scale_w.data.numpy().item()\n    if isinstance(scale_d, Expr) or isinstance(scale_h, Expr) or isinstance(scale_w, Expr):\n        if not isinstance(scale_d, Expr):\n            scale_d = const(scale_d, \"float64\")\n        if not isinstance(scale_h, Expr):\n            scale_h = const(scale_h, \"float64\")\n        if not isinstance(scale_w, Expr):\n            scale_w = const(scale_w, \"float64\")\n        return _dyn_make.upsampling3d(\n            data, scale_d, scale_h, scale_w, layout, method, coordinate_transformation_mode\n        )\n    return _make.upsampling3d(\n        data, scale_d, scale_h, scale_w, layout, method, coordinate_transformation_mode\n    )\n\n\ndef batch_flatten(data):\n    \"\"\"BatchFlatten.\n\n    This operator flattens all the dimensions except for the batch dimension.\n    which results a 2D output.\n\n    For data with shape ``(d1, d2, ..., dk)``\n    batch_flatten(data) returns reshaped output of shape ``(d1, d2*...*dk)``.\n\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The Flattened result.\n    \"\"\"\n    return _make.batch_flatten(data)\n\n\ndef bias_add(data, bias, axis=1):\n    \"\"\"add_bias operator.\n\n    Add 1D bias to the axis of data.\n    This function is a special case of add which allows\n    inference of shape of the bias from data.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    bias : tvm.relay.Expr\n        The bias to be added.\n\n    axis : int, optional\n        The axis to add the bias.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The final result.\n    \"\"\"\n    return _make.bias_add(data, bias, axis)\n\n\ndef matmul(tensor_a, tensor_b, units=None, out_dtype=\"\", transpose_a=False, transpose_b=False):\n    \"\"\"Matmul operator.\n    Applies a linear transformation. The A & B can be transposed.\n\n    .. math::\n\n        `C = A * B`\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The first input of the operator,\n        of shape `(d_1, d_2, ..., d_n, units_in)` or `(d_1, d_2, ..., units_in, d_n)`.\n\n    weight : tvm.relay.Expr\n        The second input expressions, 2-D matrix,\n        of shape `(units_in, units)` or `(units, units_in)`.\n\n    units : Optional[int]\n        Number of hidden units of the matmul transformation.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision matmul,\n        of shape `(d_1, d_2, ..., d_n, units)`.\n\n    transpose_a : Optional[bool] = False\n        Whether the data tensor is in transposed format.\n\n    transpose_b : Optional[bool] = False\n        Whether the weight tensor is in transposed format.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # Since currently `nn.dense` has better topi schedule support, will prefer to use `dense`\n    # rather than `matmul` for better compatibility\n    if not transpose_a and transpose_b:\n        # TODO(jcf94): Remove this when `nn.matmul` is finnaly ready\n        return dense(tensor_a, tensor_b, units, out_dtype)\n    return _make.matmul(tensor_a, tensor_b, units, out_dtype, transpose_a, transpose_b)\n\n\ndef dense(data, weight, units=None, out_dtype=\"\"):\n    \"\"\"Dense operator.\n    Applies a linear transformation\n\n    .. math::\n\n    `Y = X * W^T`\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator,\n        of shape `(d_1, d_2, ..., d_n, units_in)`.\n\n    weight : tvm.relay.Expr\n        The weight expressions, 2-D matrix,\n        of shape `(units, units_in)`.\n\n    units : int, optional\n        Number of hidden units of the dense transformation.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision dense,\n        of shape `(d_1, d_2, ..., d_n, units)`.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.dense(data, weight, units, out_dtype)\n\n\ndef contrib_dense_pack(data, weight, weight_layout=\"NC\", units=None, out_dtype=\"\"):\n    \"\"\"Dense operator.\n    Applies a linear transformation with packed weight\n\n    .. math::\n\n    `Y = X * W^T`\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator,\n        of shape `(batch, units_in)`.\n\n    weight : tvm.relay.Expr\n        The transformed weight expressions, 3-D matrix,\n        of shape `(units // pack_weight_tile, units_in, pack_weight_tile)`.\n\n    weight_layout: str\n        The layout of weight, such as \"NC\" or \"NC8n\".\n\n    units : int, optional\n        Number of hidden units of the dense transformation.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision dense.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.contrib_dense_pack(data, weight, weight_layout, units, out_dtype)\n\n\ndef fifo_buffer(data, buffer, axis):\n    \"\"\"FIFO buffer to enable computation reuse in CNNs with sliding indow input\n\n    Compute equivalent of\n\n    .. code-block:: python\n\n        concat(buffer, data, axis=axis)\n        .slice_axis(axis=axis,\n                    begin=data.shape[axis],\n                    end=data.shape[axis]+buffer.shape[axis])\n\n    Useful for\n\n    * Encoding explicit re-use of computation in convolution ops operated on a sliding window input\n    * Implementing a FIFO queue to cache intermediate results, e.g. as in Fast WaveNet.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data\n    buffer : tvm.relay.Expr\n        Previous value of the FIFO buffer\n    axis : int\n        Specify which axis should be used for buffering\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        Updated value for the buffer\n    \"\"\"\n    return _make.fifo_buffer(data, buffer, axis)\n\n\ndef relu(data):\n    \"\"\"Rectified linear unit.\n\n    .. math::\n       out = max(x, 0)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.relu(data)\n\n\ndef leaky_relu(data, alpha=0.01):\n    \"\"\"This operator takes data as input and does Leaky version\n    of a Rectified Linear Unit.\n\n    .. math::\n\n        `y = x > 0 ? x : alpha * x`\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    alpha : float\n        Slope coefficient for the negative half axis.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.leaky_relu(data, alpha)\n\n\ndef prelu(data, alpha, axis=1):\n    \"\"\"This operator takes data as input and does Leaky version\n    of a Rectified Linear Unit.\n\n    .. math::\n\n        y = x > 0 ? x : alpha * x\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    alpha : tvm.relay.Expr\n        Slope coefficient for the negative half axis.\n\n    axis : int, optional\n        Specify which shape axis the channel is specified.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.prelu(data, alpha, axis)\n\n\ndef pad(data, pad_width, pad_value=0, pad_mode=\"constant\"):\n    r\"\"\"Padding\n\n    This operator takes in a tensor and pads each axis by the specified\n    widths using the specified value.\n\n    Parameters\n    ----------\n    data: tvm.relay.Expr\n        The input data to the operator\n    pad_width: tuple of <tuple of <int>>, or tvm.relay.Expr, required\n        Number of values padded to the edges of each axis, in the format\n        of ((before_1, after_1), ..., (before_N, after_N))\n    pad_value: float, or tvm.relay.Expr, optional, default=0\n        The value used for padding\n    pad_mode: 'constant', 'edge', 'reflect'\n        'constant' pads with constant_value pad_value\n        'edge' pads using the edge values of the input array\n        'reflect' pads by reflecting values with respect to the edge\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if isinstance(pad_width, Constant):\n        pad_width = [list(i) for i in pad_width.data.numpy()]\n    if not isinstance(pad_value, Expr):\n        pad_value = const(pad_value)\n    if isinstance(pad_width, Expr):\n        return _dyn_make.pad(data, pad_width, pad_value, pad_mode)\n    return _make.pad(data, pad_width, pad_value, pad_mode)\n\n\ndef dilate(data, strides, dilation_value=0.0):\n    \"\"\"Dilate data with given dilation value (0 by default).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        n-D, can be any layout.\n\n    strides : tuple of <int>\n        Dilation stride on each dimension, 1 means no dilation.\n\n    dilation_value : int/float, optional\n        Value used to dilate the input.\n\n    Returns\n    -------\n    Output : tvm.relay.Expr\n        The computed result\n    \"\"\"\n    return _make.dilate(data, strides, dilation_value)\n\n\ndef mirror_pad(data, pad_width, mode=\"SYMMETRIC\"):\n    r\"\"\"MirrorPadding\n\n    This operator takes in a tensor and pads each axis by the specified\n    widths using mirroring of the border pixels.\n\n    Parameters\n    ----------\n    data: tvm.relay.Expr\n        The input data to the operator\n    pad_width: tuple of <tuple of <int>>, required\n        Number of values padded to the edges of each axis, in the format\n        of ((before_1, after_1), ..., (before_N, after_N))\n    mode: string, optional, default='SYMMETRIC'\n        What type of mirroring to use, must be SYMMETRIC or REFLECT.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.mirror_pad(data, pad_width, mode)\n\n\ndef lrn(data, size=5, axis=1, bias=2, alpha=0.00001, beta=0.75):\n    \"\"\"This operator takes data as input and does local response normalization.\n\n    Normalize the input in a local region across or within feature maps.\n    Each input value is divided by (data / (bias + (alpha * sum_data ^2 /size))^beta)\n    where n is the size of each local region, and the sum is taken over the region\n    centered at that value (zero padding is added where necessary).\n\n    .. math::\n        (data / (bias + (alpha * sum_data ^2 /size))^beta)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    size : int, optional\n        The size of the local region to be considered for normalization.\n\n    axis : int, optional\n        Input data layout channel axis. Default value is 1 for NCHW format\n\n    bias : float, optional\n        The offset parameter to avoid dividing by 0.\n\n    alpha : float, optional\n        The scaling parameter.\n\n    beta : float, optional\n        The exponent parameter.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.lrn(data, size, axis, alpha, beta, bias)\n\n\ndef l2_normalize(data, eps, axis=None):\n    \"\"\"Perform L2 normalization on the input data\n\n    .. math::\n        y(i, j) = x(i, j) / sqrt(max(sum(x^2), eps))\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    eps : float\n        epsilon value\n\n    axis : list of int, optional\n        axis over the normalization applied\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.l2_normalize(data, eps, axis)\n\n\ndef dropout(data, rate=0.5):\n    \"\"\"Applies the dropout operation to the input array.\n\n    During training, each element of the input is set to zero with\n    probability ``p``. The whole array is rescaled by ``1/(1-p)``\n    to keep the expected sum of the input unchanged.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    rate : float, optional (default=0.5)\n        The probability for an element to be reset to 0.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The result of dropout\n    \"\"\"\n    return expr.TupleWrapper(dropout_raw(data, rate), 2)[0]\n\n\ndef dropout_raw(data, rate=0.5):\n    \"\"\"Applies the dropout operation to the input array.\n\n    During training, each element of the input is set to zero with\n    probability ``p``. The whole array is rescaled by ``1/(1-p)``\n    to keep the expected sum of the input unchanged.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    rate : float, optional (default=0.5)\n        The probability for an element to be reset to 0.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The result of dropout\n    \"\"\"\n    return _make.dropout(data, rate)\n\n\ndef batch_norm(\n    data, gamma, beta, moving_mean, moving_var, axis=1, epsilon=1e-5, center=True, scale=True\n):\n    r\"\"\"\n    Batch normalization layer (Ioffe and Szegedy, 2014).\n    Normalizes the input at each batch, i.e. applies a transformation\n    that maintains the mean activation close to 0 and the activation\n    standard deviation close to 1.\n\n    .. math::\n\n        data\\_mean[i] = mean(data[:,i,:,...]) \\\\\n        data\\_var[i] = var(data[:,i,:,...])\n\n    Then compute the normalized output, which has the same shape as input, as following:\n\n    .. math::\n\n        out[:,i,:,...] = \\frac{data[:,i,:,...] - data\\_mean[i]}{\\sqrt{data\\_var[i]+\\epsilon}}\n            * gamma[i] + beta[i]\n\n    Both *mean* and *var* returns a scalar by treating the input as a vector.\n\n    Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``\n    have shape *(k,)*.\n\n    Besides the inputs and the outputs, this operator accepts two auxiliary\n    states, ``moving_mean`` and ``moving_var``, which are *k*-length\n    vectors. They are global statistics for the whole dataset, which are updated by\n\n    .. code:: python\n\n        moving_mean = moving_mean * momentum + data_mean * (1 - momentum)\n        moving_var = moving_var * momentum + data_var * (1 - momentum)\n\n    The parameter ``axis`` specifies which axis of the input shape denotes\n    the 'channel' (separately normalized groups).  The default is 1.\n    Specifying -1 sets the channel axis to be the last item in the input shape.\n\n    .. note::\n\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input to which batch_norm will be applied.\n\n    gamma : tvm.relay.Expr\n        The gamma scale factor.\n\n    beta : tvm.relay.Expr\n        The beta offset factor.\n\n    moving_mean : tvm.relay.Expr\n        Running mean of input,\n\n    moving_var : tvm.relay.Expr\n        Running variance of input.\n\n    axis : int, optional, default=1\n        Specify along which shape axis the channel is specified.\n\n    epsilon : double, optional, default=1e-5\n        Small float added to variance to avoid dividing by zero.\n\n    center : boolean, optional, default=True\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : boolean, optional, default=True\n        If true, multiply by gamma. If False, gamma is not used.\n        When the next layer is piecewise linear (also e.g. nn.relu),\n        this can be disabled since the scaling will be done by the next layer.\n\n    Returns\n    -------\n    result : relay.Tuple([tvm.relay.Expr, tvm.relay.Expr, tvm.relay.Expr])\n        Tuple of normed data (same shape as input),\n        new running mean (k-length vector),\n        and new running variance (k-length vector)\n    \"\"\"\n    result = _make.batch_norm(\n        data, gamma, beta, moving_mean, moving_var, axis, epsilon, center, scale\n    )\n    return expr.TupleWrapper(result, 3)\n\n\ndef instance_norm(data, gamma, beta, axis=1, epsilon=1e-5, center=True, scale=True):\n    r\"\"\"\n    Instance Normalization (Ulyanov and et al., 2016)\n    Applies instance normalization to the n-dimensional input array.\n\n    .. math::\n\n        out = \\frac{data - mean(data)}{\\sqrt{var(data)+\\epsilon}}\n            * gamma + beta\n\n    The instance normalization is similar to batch normalization, but unlike\n    batch normalization, the mean and var are calculated per-dimension\n    separately for each object(instance) in a mini-batch, not over a batch.\n    And the same normalization is applied both at test and train time.\n\n    Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``\n    have shape *(k,)*.\n\n    The parameter ``axis`` specifies which axis of the input shape denotes\n    the 'channel'.  The default is 1. Specifying -1 sets the channel axis\n    to be the last item in the input shape.\n\n    .. note::\n\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input to which instance_norm will be applied.\n\n    gamma : tvm.relay.Expr\n        The gamma scale factor.\n\n    beta : tvm.relay.Expr\n        The beta offset factor.\n\n    axis : int, optional, default=1\n        Specify along which shape axis the channel is specified.\n\n    epsilon : double, optional, default=1e-5\n        Small float added to variance to avoid dividing by zero.\n\n    center : boolean, optional, default=True\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : boolean, optional, default=True\n        If True, multiply by gamma. If False, gamma is not used.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The normalized data.\n\n    .. _`Instance Normalization: The Missing Ingredient for Fast Stylization`:\n        https://arxiv.org/abs/1607.08022\n    \"\"\"\n    return _make.instance_norm(data, gamma, beta, axis, epsilon, center, scale)\n\n\ndef layer_norm(data, gamma, beta, axis=-1, epsilon=1e-5, center=True, scale=True):\n    r\"\"\"\n    Layer normalization (Lei Ba and et al., 2016).\n    Applies layer normalization to the n-dimensional input array.\n    This operator takes an n-dimensional input array and normalizes\n    the input using the given axis:\n\n    .. math::\n\n        out = \\frac{data - mean(data, axis)}{\\sqrt{var(data, axis)+\\epsilon}}\n            * gamma + beta\n\n    Unlike batch normalization, the mean and var are computed along the channel dimension.\n\n    Assume the input has size k on axis 1, then both gamma and beta have shape (k,).\n\n    .. note::\n\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input to which layer_norm will be applied.\n\n    gamma : tvm.relay.Expr\n        The gamma scale factor.\n\n    beta : tvm.relay.Expr\n        The beta offset factor.\n\n    axis : int, optional, default=-1\n        The axis that should be normalized, typically the axis of the channels.\n\n    epsilon : double, optional, default=1e-5\n        Small float added to variance to avoid dividing by zero.\n\n    center : boolean, optional, default=True\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : boolean, optional, default=True\n        If True, multiply by gamma. If False, gamma is not used.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The normalized data.\n    \"\"\"\n    return _make.layer_norm(data, gamma, beta, axis, epsilon, center, scale)\n\n\ndef group_norm(data, gamma, beta, num_groups, axis=1, epsilon=1e-5, center=True, scale=True):\n    r\"\"\"\n    Group normalization normalizes over group of channels for each training examples.\n    We can say that, Group Norm is in between Instance Norm and Layer Norm. When we put\n    all the channels into a single group, group normalization becomes Layer normalization.\n    And, when we put each channel into different groups it becomes Instance normalization\n\n    https://arxiv.org/pdf/1803.08494.pdf\n\n    Applies group normalization to the n-dimensional input array by seperating the input channels\n    into 'num_groups' groups, each containing 'num_channels / num_groups' channels.\n    The mean and standard-deviation are calculated separately over the each group. gamma and\n    beta are learnable per-channel affine transform parameter vectors of size num_channels.\n\n    .. math::\n\n        out = \\frac{data - mean(data, axis)}{\\sqrt{var(data, axis)+\\epsilon}}\n            * gamma + beta\n\n    Unlike batch normalization, the mean and var are computed along a group of channels.\n\n    If the input has size k on axis 1, then both gamma and beta have shape (k,).\n\n    .. note::\n\n        This operator can be optimized away for inference.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input to which group_norm will be applied.\n\n    gamma : tvm.relay.Expr\n        The gamma scale factor.\n\n    beta : tvm.relay.Expr\n        The beta offset factor.\n\n    num_groups : int\n        The number of groups to separate the channels into.\n\n    axis : int, optional, default=1\n        The axis of the channels.\n\n    epsilon : double, optional, default=1e-5\n        Small float added to variance to avoid dividing by zero.\n\n    center : boolean, optional, default=True\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : boolean, optional, default=True\n        If True, multiply by gamma. If False, gamma is not used.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The normalized data.\n    \"\"\"\n    return _make.group_norm(data, gamma, beta, num_groups, axis, epsilon, center, scale)\n\n\ndef batch_matmul(tensor_a, tensor_b, out_dtype=\"\", transpose_a=False, transpose_b=True):\n    r\"\"\"\n    Compute batch matrix multiplication of `tensor_a` and `tensor_b`.\n\n    Both `tensor_a` and `tensor_b` can be transposed. For legacy reason, we use NT format\n    (transpose_a=False, transpose_b=True) by default.\n\n    .. math::\n\n        \\mbox{batch_matmul}(A, B)[i, :, :] = \\mbox{matmul}(A[i, :, :], B[i, :, :])\n\n    Parameters\n    ----------\n    tensor_a : tvm.relay.Expr\n        The first input.\n\n    tensor_b : tvm.relay.Expr\n        The second input.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    Returns\n    -------\n    result: tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.batch_matmul(tensor_a, tensor_b, out_dtype, transpose_a, transpose_b)\n\n\n# pylint: disable=no-else-return,inconsistent-return-statements\ndef sparse_dense(dense_mat, sparse_mat, sparse_lhs=False):\n    r\"\"\"\n    Computes the matrix multiplication of `dense_mat` and `sparse_mat`, where `dense_mat` is\n    a dense matrix and `sparse_mat` is a sparse (either BSR or CSR) namedtuple with\n    fields `data`, `indices`, and `indptr`.\n\n    \\if sparse_lhs=False:\n        .. math::\n\n            \\mbox{sparse_dense}(dense_mat, sparse_mat)[m, n]\n            = \\mbox{matmul}(D, \\mbox{as_dense}(S)^T)[m, n]\n\n    \\if sparse_lhs=True:\n        .. math::\n\n            \\mbox{sparse_dense}(dense_mat, sparse_mat)[m, n]\n            = \\mbox{matmul}(\\mbox{as_dense}(S), (D)^T)[m, n]\n\n    where `as_dense` returns dense equivalent of the given S(sparse matrix)\n    while performing matmul with given D(dense matrix).\n\n    See\n    https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html\n    and\n    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.bsr_matrix.html\n    for more detail on the sparse matrix representation.\n\n    Parameters\n    ----------\n    dense_mat : tvm.relay.Expr\n        The input dense matrix for the matrix multiplication\n\n    sparse_mat : Union[namedtuple, Tuple[ndarray, ndarray, ndarray]].\n        The input sparse matrix for the matrix multiplication.\n\n    sparse_lhs : bool, optional\n        Indicates whether lhs or rhs matrix is sparse. Default value is False.\n\n    Returns\n    -------\n    result: tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    if hasattr(sparse_mat, \"indices\"):\n        return _make.sparse_dense(\n            dense_mat, sparse_mat.data, sparse_mat.indices, sparse_mat.indptr, sparse_lhs\n        )\n    else:\n        return _make.sparse_dense(\n            dense_mat, sparse_mat[0], sparse_mat[1], sparse_mat[2], sparse_lhs\n        )\n\n\ndef sparse_transpose(x):\n    r\"\"\"\n    Computes the fast matrix transpose of x,\n    where x is a sparse tensor in CSR format (represented as a namedtuple\n    with fields `data`, `indices`, and `indptr`).\n\n    ** Currently only support Square Matrices **\n\n    .. math::\n\n        \\mbox{sparse_transpose}(x)[n, n] = (x^T)[n, n]\n\n    Please refer to https://github.com/scipy/scipy/blob/v1.3.0/scipy/sparse/csr.py\n    for the algorithm implemented in this operator.\n\n    Parameters\n    ----------\n    x : Union[namedtuple, Tuple[ndarray, ndarray, ndarray]].\n        The sparse weight matrix for the fast matrix transpose.\n\n    Returns\n    -------\n    result : relay.Tuple([tvm.relay.Expr, tvm.relay.Expr, tvm.relay.Expr])\n        Tuple of output sparse tensor (same shape and format as input),\n        i.e. if CSR then output is in ([data, indices, indptr]) form\n    \"\"\"\n    if hasattr(x, \"indices\"):\n        return expr.TupleWrapper(_make.sparse_transpose(x.data, x.indices, x.indptr), 3)\n    return expr.TupleWrapper(_make.sparse_transpose(x[0], x[1], x[2]), 3)\n\n\n# pylint: disable=no-else-return,inconsistent-return-statements\ndef sparse_add(dense_mat, sparse_mat):\n    r\"\"\"\n    Computes the matrix addition of `dense_mat` and `sparse_mat`, where `dense_mat` is\n    a dense matrix and `sparse_mat` is a sparse (CSR) namedtuple with\n    fields `data`, `indices`, and `indptr`.\n\n    .. math::\n\n        \\mbox{sparse_add}(dense_mat, sparse_mat)[m, n] = \\mbox{add}(\\mbox{as_dense}(S), (D))[m, n]\n\n    where `as_dense` returns dense equivalent of the given S(sparse matrix)\n    while performing addition with given D(dense matrix).\n\n    Parameters\n    ----------\n    dense_mat : tvm.relay.Expr\n        The input dense matrix for the matrix addition\n\n    sparse_mat : Union[namedtuple, Tuple[ndarray, ndarray, ndarray]].\n        The input sparse matrix(CSR) for the matrix addition.\n\n    Returns\n    -------\n    result: tvm.relay.Expr\n        The computed result.\n\n    Examples\n    -------\n    .. code-block:: python\n\n        dense_data = [[ 3.,   4.,   4. ]\n                      [ 4.,  2.,  5. ]]\n        sparse_data = [4., 8.]\n        sparse_indices =[0, 2]\n        sparse_indptr =[0, 1, 2]\n\n        output = relay.sparse_add(dense_data, sparse_data, sparse_indices, sparse_indptr)\n\n        output = [[ 7.,   4.,   4. ]\n                  [ 4.,  2.,  13. ]]\n    \"\"\"\n    if hasattr(sparse_mat, \"indices\"):\n        return _make.sparse_add(dense_mat, sparse_mat.data, sparse_mat.indices, sparse_mat.indptr)\n    else:\n        return _make.sparse_add(dense_mat, sparse_mat[0], sparse_mat[1], sparse_mat[2])\n\n\ndef contrib_conv2d_winograd_without_weight_transform(\n    data,\n    weight,\n    tile_size,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"2D convolution with winograd algorithm.\n\n    The basic parameters are the same as the ones in vanilla conv2d.\n    It assumes the weight is pre-transformed by nn.contrib_conv2d_winograd_weight_transform\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    tile_size : int\n        The Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.contrib_conv2d_winograd_without_weight_transform(\n        data,\n        weight,\n        tile_size,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef contrib_conv2d_gemm_without_weight_transform(\n    data,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"2D convolution with gemm algorithm.\n\n    The basic parameters are the same as the ones in vanilla conv2d.\n    It assumes the weight is pre-transformed by nn.contrib_conv2d_gemm_weight_transform\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.contrib_conv2d_gemm_without_weight_transform(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef contrib_conv2d_nchwc(\n    data,\n    kernel,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW8c\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"Variant of 2D convolution.\n\n    This operator takes the weight as the convolution kernel\n    and convolves it with data to produce an output, following a specialized\n    NCHWc data layout.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    kernel : tvm.relay.Expr\n        The kernel expressions.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.contrib_conv2d_NCHWc(\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef contrib_depthwise_conv2d_nchwc(\n    data,\n    kernel,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW8c\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"Variant of 2D depthwise convolution.\n\n    This operator takes the weight as the depthwise convolution kernel\n    and depthwise convolves it with data to produce an output, following a specialized\n    NCHWc data layout.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    kernel : tvm.relay.Expr\n        The kernel expressions.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.contrib_depthwise_conv2d_NCHWc(\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef contrib_conv2d_winograd_weight_transform(weight, tile_size):\n    r\"\"\"Weight Transformation part for 2D convolution with winograd algorithm.\n\n    We separate this as a single op to enable pre-compute for inference.\n    Use this together with nn.contrib_conv2d_winograd_without_weight_transform\n\n    Parameters\n    ----------\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    tile_size : int\n        The Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.contrib_conv2d_winograd_weight_transform(weight, tile_size)\n\n\ndef contrib_conv2d_gemm_weight_transform(weights, tile_rows, tile_cols):\n    r\"\"\"Weight Transformation part for 2D convolution with gemm algorithm.\n\n    We separate this as a single op to enable pre-compute for inference.\n    Use this together with nn.contrib_conv2d_gemm_without_weight_transform\n\n    Parameters\n    ----------\n    weights : tvm.relay.Expr\n        The weight expressions.\n    tile_rows: int\n        Tile rows of the weight transformation for ConvGemm.\n    tile_cols: int\n       Tile columns of the weight transformation for ConvGemm.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.contrib_conv2d_gemm_weight_transform(weights, tile_rows, tile_cols)\n\n\ndef contrib_conv3d_winograd_weight_transform(weight, tile_size):\n    r\"\"\"Weight Transformation part for 3D convolution with winograd algorithm.\n\n    We separate this as a single op to enable pre-compute for inference.\n    Use this together with nn.contrib_conv3d_winograd_without_weight_transform\n\n    Parameters\n    ----------\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    tile_size : int\n        The Tile size of winograd. E.g. 2 for F(2x2x2, 3x3x3) and 4 for F(4x4x4, 3x3x3)\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.contrib_conv3d_winograd_weight_transform(weight, tile_size)\n\n\ndef contrib_conv2d_winograd_nnpack_weight_transform(weight, convolution_algorithm, out_dtype=\"\"):\n    r\"\"\"Weight Transformation part for 2D convolution with winograd algorithm.\n\n    We separate this as a single op to enable pre-compute for inference.\n    Use this together with nn.contrib_conv2d_winograd_without_weight_transform\n\n    Parameters\n    ----------\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    convolution_algorithm : int\n        The Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.contrib_conv2d_winograd_nnpack_weight_transform(\n        weight, convolution_algorithm, out_dtype\n    )\n\n\ndef deformable_conv2d(\n    data,\n    offset,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    deformable_groups=1,\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"\",\n):\n    r\"\"\"Deformable 2d convolution.\n\n    The deformable convolution operation is described in https://arxiv.org/abs/1703.06211\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    offset : tvm.relay.Expr\n        The offset expressions.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    deformable_groups : int, optional\n        Number of deformable groups.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.deformable_conv2d(\n        data,\n        offset,\n        weight,\n        strides,\n        padding,\n        dilation,\n        deformable_groups,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef bitpack(data, bits=1, pack_axis=1, bit_axis=2, pack_type=\"uint32\", name=\"BitPack\"):\n    \"\"\"Tensor packing for bitserial operations.\n\n    The values along the input tensor's pack_axis are quantized\n    and packed together into the specified pack_type in a new bit axis.\n\n    For example, consider bitpacking with data to be a tensor with shape `[1, 64, 128, 128]`,\n    pack_axis=1, bit_axis=4, pack_type=uint8, and bits=2. The output in this case will\n    be of shape `[1, 8, 128, 128, 2]`. The dimension of axis 1 has been reduced by a factor\n    of 8 since each value is packed into an 8-bit uint8. Axis 4 is now two bitplanes\n    representing the quantized value of the incoming data. The output tensor is now\n    ready to be used in a bitserial operation.\n\n    Parameters\n    ----------\n    data : tvm.relay.expr\n        The incoming tensor to be packed.\n\n    bits : int\n        Number of bits that should be packed.\n\n    pack_axis : int\n        Axis that should be decomposed and packed.\n\n    bit_axis : int\n        New axis containing bitplane.\n\n    pack_type : str\n        Datatype to pack bits into.\n\n    name : str, optional\n        Name of the operation.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The packed tensor.\n    \"\"\"\n    return _make.bitpack(data, bits, pack_axis, bit_axis, pack_type, name)\n\n\ndef bitserial_conv2d(\n    data,\n    weight,\n    strides=(1, 1),\n    padding=(0, 0),\n    channels=None,\n    kernel_size=(3, 3),\n    activation_bits=1,\n    weight_bits=1,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    r\"\"\"2D convolution using bitserial computation.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial of the convolution kernel.\n\n    activation_bits : int\n        Number of bits to pack for activations.\n\n    weight_bits : int\n        Number of bits to pack for weights.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the kernel\n\n    pack_dtype: str, optional\n        Datatype to pack bits into.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.bitserial_conv2d(\n        data,\n        weight,\n        strides,\n        padding,\n        channels,\n        kernel_size,\n        activation_bits,\n        weight_bits,\n        data_layout,\n        kernel_layout,\n        pack_dtype,\n        out_dtype,\n        unipolar,\n    )\n\n\ndef bitserial_dense(\n    data,\n    weight,\n    units=None,\n    data_bits=1,\n    weight_bits=1,\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    \"\"\"Bitserial Dense operator.\n    Applies matrix multiplication of two quantized matrices\n    using a fast bitserial algorithm.\n\n    .. math::\n\n    `Y = X * W`\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    units : int, optional\n        Number of hidden units of the dense transformation.\n\n    data_bits : int\n        Number of bits incoming tensor should be packed with.\n\n    weight_bits : int\n        Number of bits weight tensor should be packed with.\n\n    pack_dtype : str, optional\n        Datatype to pack individual bits into before computation.\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision dense.\n\n    unipolar : bool, optional\n        Whether to use unipolar or bipolar quantization for inputs.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.bitserial_dense(\n        data, weight, units, data_bits, weight_bits, pack_dtype, out_dtype, unipolar\n    )\n\n\ndef cross_entropy(predictions, targets):\n    \"\"\"CrossEntropy without logits.\n\n    Parameters\n    ----------\n    predictions : tvm.relay.Expr\n      The predictions.\n\n    targets : tvm.relay.Expr\n      The targets.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n      The computed result.\n    \"\"\"\n    return _make.cross_entropy(predictions, targets)\n\n\ndef cross_entropy_with_logits(predictions, targets):\n    \"\"\"CrossEntropy with logits.\n\n    Parameters\n    ----------\n    predictions : tvm.relay.Expr\n      The predictions.\n\n    targets : tvm.relay.Expr\n      The targets.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n      The computed result.\n    \"\"\"\n    return _make.cross_entropy_with_logits(predictions, targets)\n\n\ndef nll_loss(predictions, targets, weights, reduction=\"mean\", ignore_index=-100):\n    \"\"\"Negative log likelihood loss.\n\n    output{n, i_1, i_2, ..., i_k} = -p * w\n      where t = target{n, i_1, i_2, ..., i_k}\n            p = predictions{n, t, i_1, i_2, i_k}\n            w = weights{n, i_1, i_2, ..., i_k} if t != ignore_index else 0\n\n    result = reduction(output)\n\n    Parameters\n    ----------\n    predictions : tvm.relay.Expr\n      The predictions.\n\n    targets : tvm.relay.Expr\n      The target value of each prediction.\n\n    weights : tvm.relay.Expr\n      The weight of each target value.\n\n    reduction : string\n      The reduction method to apply to the output.\n      Possible values are \"mean\", \"sum\" and \"none\".\n\n    ignore_index : int\n      The target value to ignore.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n      The computed result.\n    \"\"\"\n    return _make.nll_loss(predictions, targets, weights, reduction, ignore_index)\n\n\ndef depth_to_space(data, block_size, layout=\"NCHW\", mode=\"DCR\"):\n    \"\"\"Convert channels into spatial blocks.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input data with channels divisible by block_size**2\n\n    block_size : int\n        Size of blocks to convert channels into.\n\n    layout : string\n        One of NCHW or NHWC, indicates channel axis.\n\n    mode : string\n        One of DCR or CDR, indicates which order channels\n        are accessed in.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        Tensor with shape [in_batch, in_channel / block_size * block_size,\n                           in_height * block_size, in_width * block_size]\n    \"\"\"\n    return _make.depth_to_space(data, block_size, layout, mode)\n\n\ndef space_to_depth(data, block_size, layout=\"NCHW\"):\n    \"\"\"Convert spatial blocks into channels.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        Input data with spatial dimensions divisible by block_size\n\n    block_size : int\n        Size of blocks to decompose into channels.\n\n    layout : string\n        One of NCHW or NHWC, indicates channel axis.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        Tensor with shape [in_batch, in_channel * block_size * block_size,\n                           in_height / block_size, in_width / block_size]\n    \"\"\"\n    return _make.space_to_depth(data, block_size, layout)\n\n\ndef adaptive_max_pool1d(data, output_size=None, layout=\"NCW\", out_layout=\"\"):\n    r\"\"\"1D adaptive max pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 1D max value calculation\n    across each window represented by W.\n\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, in_channels, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input height and width will be used\n        as output height and width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size) for any input (NCW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    if isinstance(output_size, int):\n        output_size = [output_size]\n    return _make.adaptive_max_pool1d(data, output_size, layout, out_layout)\n\n\ndef adaptive_avg_pool1d(data, output_size=None, layout=\"NCW\", out_layout=\"\"):\n    r\"\"\"1D adaptive average pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 1D average value calculation\n    across each window represented by W.\n\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, in_channels, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input height and width will be used\n        as output width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size) for any input (NCW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    if isinstance(output_size, int):\n        output_size = [output_size]\n    return _make.adaptive_avg_pool1d(data, output_size, layout, out_layout)\n\n\ndef adaptive_max_pool2d(data, output_size=None, layout=\"NCHW\", out_layout=\"\"):\n    r\"\"\"2D adaptive max pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 2D max value calculation\n    across each window represented by WxH.\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_height, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input height and width will be used\n        as output height and width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size x output_size) for any input (NCHW).\n\n        If a tuple of integers (height, width) are provided for output_size,\n        the output size is (N x C x height x width) for any input (NCHW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    return _make.adaptive_max_pool2d(data, output_size, layout, out_layout)\n\n\ndef adaptive_avg_pool2d(data, output_size=None, layout=\"NCHW\", out_layout=\"\"):\n    r\"\"\"2D adaptive average pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 2D average value calculation\n    across each window represented by WxH.\n\n\n    In the default case, where the data_layout is `NCHW`\n    a data Tensor with shape `(batch_size, in_channels, height, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_height, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input height and width will be used\n        as output height and width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size x output_size) for any input (NCHW).\n\n        If a tuple of integers (height, width) are provided for output_size,\n        the output size is (N x C x height x width) for any input (NCHW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    return _make.adaptive_avg_pool2d(data, output_size, layout, out_layout)\n\n\ndef adaptive_max_pool3d(data, output_size=None, layout=\"NCDHW\", out_layout=\"\"):\n    r\"\"\"3D adaptive max pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 3D max value calculation\n    across each window represented by DxWxH.\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, in_channels, depth, height, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_depth, output_height, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input depth, height and width will be used\n        as output depth, height and width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size x output_size x output_size) for any input (NCDHW).\n\n        If a tuple of integers (depth, height, width) are provided for output_size,\n        the output size is (N x C x depth x height x width) for any input (NCDHW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    return _make.adaptive_max_pool3d(data, output_size, layout, out_layout)\n\n\ndef adaptive_avg_pool3d(data, output_size=None, layout=\"NCDHW\", out_layout=\"\"):\n    r\"\"\"3D adaptive avg pooling operator. This operator is experimental.\n\n    This operator takes data as input and does 3D avg value calculation\n    across each window represented by DxWxH.\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, in_channels, depth, height, width)`,\n    to produce an output Tensor with shape\n    (batch_size, in_channels, output_depth, output_height, output_width).\n\n    The pooling kernel and stride sizes are automatically chosen for\n    desired output sizes.\n\n    For output_size:\n        If this argument is not provided, input depth, height and width will be used\n        as output depth, height and width.\n\n        If a single integer is provided for output_size, the output size is\n        (N x C x output_size x output_size x output_size) for any input (NCDHW).\n\n        If a tuple of integers (depth, height, width) are provided for output_size,\n        the output size is (N x C x depth x height x width) for any input (NCDHW).\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    output_size : tuple of int. optional\n        Output height and width.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [] or output_size\n    return _make.adaptive_avg_pool3d(data, output_size, layout, out_layout)\n\n\ndef global_max_pool1d(data, layout=\"NCW\", out_layout=\"\"):\n    r\"\"\"1D global maximum pooling operator.\n\n    This operator takes data as input and does 1D max value calculation\n    across each window represented by W.\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, in_channels, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, w)\n    .. math::\n\n        \\mbox{out}(b, c, 1)  = \\max_{n=0, \\ldots, w} \\mbox{data}(b, c, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [1]\n    return _make.adaptive_max_pool1d(data, output_size, layout, out_layout)\n\n\ndef global_avg_pool1d(data, layout=\"NCW\", out_layout=\"\"):\n    r\"\"\"1D global average pooling operator.\n\n    This operator takes data as input and does 1D average value calculation\n    across each window represented by W.\n\n    In the default case, where the data_layout is `NCW`\n    a data Tensor with shape `(batch_size, in_channels, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, w)\n\n    .. math::\n\n        \\mbox{out}(b, c, 1)  = \\frac{1}{w} \\sum_{n=0}^{w-1} \\mbox{data}(b, c, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [1]\n    return _make.adaptive_avg_pool1d(data, output_size, layout, out_layout)\n\n\ndef global_max_pool3d(data, layout=\"NCDHW\", out_layout=\"\"):\n    r\"\"\"3D global maximum pooling operator.\n\n    This operator takes data as input and does 3D max value calculation\n    across each window represented by DxWxH.\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, in_channels, depth, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, d, h, w)\n    .. math::\n\n        \\mbox{out}(b, c, 1, 1, 1)  =  \\max_{l=0, \\ldots, d},  \\max_{m=0, \\ldots, h},\n             \\max_{n=0, \\ldots, w} \\mbox{data}(b, c, l, m, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [1, 1, 1]\n    return _make.adaptive_max_pool3d(data, output_size, layout, out_layout)\n\n\ndef global_avg_pool3d(data, layout=\"NCDHW\", out_layout=\"\"):\n    r\"\"\"3D global average pooling operator.\n\n    This operator takes data as input and does 3D average value calculation\n    across each window represented by DxWxH.\n\n    In the default case, where the data_layout is `NCDHW`\n    a data Tensor with shape `(batch_size, in_channels, depth, height, width)`,\n    to produce an output Tensor with the following rule:\n\n    with data of shape (b, c, d, h, w)\n\n    .. math::\n\n        \\mbox{out}(b, c, 1, 1, 1)  = \\frac{1}{d * h * w} \\sum_{l=0}^{d-1}  \\sum_{m=0}^{h-1}\n             \\sum_{n=0}^{w-1} \\mbox{data}(b, c, l, m, n)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    layout : str, optional\n        Layout of the input.\n\n    out_layout : str, optional\n        Layout of the output.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    output_size = [1, 1, 1]\n    return _make.adaptive_avg_pool3d(data, output_size, layout, out_layout)\n\n\ndef correlation(\n    data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply, layout\n):\n    r\"\"\"Applies correlation to inputs.\n\n    The correlation layer performs multiplicative patch comparisons between two feature maps.\n    Given two multi-channel feature maps :math:`f_{1}, f_{2}`, with :math:`w`, :math:`h`, and\n    :math:`c` being their width, height, and number of channels, the correlation layer lets the\n    network compare each patch from :math:`f_{1}` with each patch from :math:`f_{2}`.\n\n    For now we consider only a single comparison of two patches. The 'correlation' of two patches\n    centered at :math:`x_{1}` in the first map and :math:`x_{2}` in the second map is then defined\n    as:\n\n    .. math::\n\n        c(x_{1}, x_{2}) = \\sum_{o \\in [-k,k] \\times [-k,k]} <f_{1}(x_{1} + o), f_{2}(x_{2} + o)>\n\n    for a square patch of size :math:`K:=2k+1`.\n\n    Note that the equation above is identical to one step of a convolution in neural networks, but\n    instead of convolving data with a filter, it convolves data with other    data. For this\n    reason, it has no training weights.\n\n    Computing :math:`c(x_{1}, x_{2})` involves :math:`c * K^{2}` multiplications. Comparing all\n    patch combinations involves :math:`w^{2}*h^{2}` such computations.\n\n    Given a maximum displacement :math:`d`, for each location :math:`x_{1}` it computes\n    correlations :math:`c(x_{1}, x_{2})` only in a neighborhood of size :math:`D:=2d+1`,\n    by limiting the range of :math:`x_{2}`. We use strides :math:`s_{1}, s_{2}`, to quantize\n    :math:`x_{1}` globally and to quantize :math:`x_{2}` within the neighborhood\n    centered around :math:`x_{1}`.\n\n    The final output is defined by the following expression:\n\n    .. math::\n\n        out[n, q, i, j] = c(x_{i, j}, x_{q})\n\n    where :math:`i` and :math:`j` enumerate spatial locations in :math:`f_{1}`, and :math:`q`\n    denotes the :math:`q^{th}` neighborhood of :math:`x_{i,j}`.\n\n    Parameters\n    ----------\n    data1 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    data2 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    kernel_size: int\n        Kernel size for correlation, must be an odd number\n\n    max_displacement: int\n        Max displacement of Correlation\n\n    stride1: int\n        Stride for data1\n\n    stride2: int\n        Stride for data2 within the neightborhood centered around data1\n\n    padding : int or a list/tuple of 2 or 4 ints\n        Padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    is_multiply: bool\n        operation type is either multiplication or substraction\n\n    layout: str\n        layout of data1, data2 and the output\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    if isinstance(padding, int):\n        padding = (padding, padding)\n    return _make.correlation(\n        data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply, layout\n    )\n\n\ndef space_to_batch_nd(data, block_shape, paddings, pad_value=0):\n    r\"\"\"Divide spatial dimensions of the data into a grid of blocks\n    and interleave them into batch dim.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D with shape [batch, spatial_shape, remaining_shape]\n\n    block_shape : relay.Expr\n        1-D of size [M] where M is number of spatial dims, specifies block size\n        for each spatial dimension.\n\n    paddings : relay.Expr\n        2-D of shape [M, 2] where M is number of spatial dims, specifies\n        [before, after] paddings for each spatial dimension.\n\n    pad_value : float, or relay.Expr, optional, default=0\n        The value used for padding.\n\n    Returns\n    -------\n    result : relay.Expr\n        N-D Tensor with shape\n        [in_batch * prod(block_shape),\n        padded_data[1] / block_shape[0], ..., padded_data[M] / block_shape[M-1],\n        remaining_shape]\n    \"\"\"\n\n    return _make.space_to_batch_nd(data, block_shape, paddings, pad_value)\n\n\ndef batch_to_space_nd(data, block_shape, crops):\n    r\"\"\"Reshape the batch dimension into spatial dimensions.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D with shape [batch, spatial_shape, remaining_shape]\n\n    block_shape : relay.Expr\n        1-D of size [M] where M is number of spatial dims, specifies block size\n        for each spatial dimension.\n\n    crops : relay.Expr\n        2-D of shape [M, 2] where M is number of spatial dims, specifies\n        [begin, end] crop size for each spatial dimension.\n\n    Returns\n    -------\n    result : relay.Expr\n        N-D Tensor with shape\n        [batch / prod(block_shape),\n        in_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], ...,\n        in_shape[M] * block_shape[M-1] - crops[M-1, 0] - crops[M-1, 1],\n        remaining_shape]\n    \"\"\"\n\n    return _make.batch_to_space_nd(data, block_shape, crops)\n\n\ndef conv2d_backward_weight(\n    grad,\n    data,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    grad_layout=\"NCHW\",\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_dtype=\"\",\n):\n    r\"\"\"The gradient of conv2d with respect to weight.\n\n    This operator takes the output gradient `grad` and convolves it with `data` as\n    the convolution kernel, to produce the gradient with respect to weight.\n\n    Note that the parameter `kernel_size` is the spatial size of the corresponding\n    forward convolution kernel, not that of `data`. `grad_layout` and\n    `kernel_layout` are the layouts of `grad` and the weight gradient respectively.\n\n    Other parameters are the same as the conv2d op. See its documentation for more\n    details.\n\n    \"\"\"\n    if isinstance(kernel_size, int):\n        kernel_size = (kernel_size, kernel_size)\n    if isinstance(strides, int):\n        strides = (strides, strides)\n    if isinstance(dilation, int):\n        dilation = (dilation, dilation)\n    padding = get_pad_tuple2d(padding)\n\n    return _make.conv2d_backward_weight(\n        grad,\n        data,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        grad_layout,\n        data_layout,\n        kernel_layout,\n        out_dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/nn/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"NN operator common utilities\"\"\"\nfrom tvm.ir import container\n\n\ndef get_pad_tuple1d(padding):\n    \"\"\"Common code to get the 1 dimensional pad option\n    Parameters\n    ----------\n    padding : Union[int, Tuple[int, ...]]\n        Padding size\n    Returns\n    -------\n    pad_left : int\n        Padding size on left\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, container.Array):\n        padding = list(padding)\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 1:\n            pad_w = padding[0] * 2\n        elif len(padding) == 2:\n            return padding[0], padding[1]\n        else:\n            raise ValueError(\"Size of padding can only be 1 or 2\")\n    elif isinstance(padding, int):\n        pad_w = padding * 2\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_left = (pad_w + 1) // 2\n    return pad_left, pad_w - pad_left\n\n\ndef get_pad_tuple2d(padding):\n    \"\"\"Common code to get the pad option\n    Parameters\n    ----------\n    padding : Union[int, Tuple[int, ...]]\n        Padding size\n    Returns\n    -------\n    pad_top : int\n        Padding size on top\n    pad_left : int\n        Padding size on left\n    pad_down : int\n        Padding size on down.\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, container.Array):\n        padding = list(padding)\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 2:\n            pad_h = padding[0] * 2\n            pad_w = padding[1] * 2\n        elif len(padding) == 4:\n            return padding[0], padding[1], padding[2], padding[3]\n        else:\n            raise ValueError(\"Size of padding can only be 2 or 4\")\n    elif isinstance(padding, int):\n        pad_h = pad_w = padding * 2\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_top = (pad_h + 1) // 2\n    pad_left = (pad_w + 1) // 2\n    return pad_top, pad_left, pad_h - pad_top, pad_w - pad_left\n\n\ndef get_pad_tuple3d(padding):\n    \"\"\"Common code to get the pad option\n    Parameters\n    ----------\n    padding : Union[int, Tuple[int, ...]]\n        Padding size\n    Returns\n    -------\n    pad_front : int\n        Padding size on front\n    pad_top : int\n        Padding size on top\n    pad_left : int\n        Padding size on left\n    pad_back : int\n        Padding size on back\n    pad_down : int\n        Padding size on down.\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, container.Array):\n        padding = list(padding)\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 3:\n            pad_d = padding[0] * 2\n            pad_h = padding[1] * 2\n            pad_w = padding[2] * 2\n        elif len(padding) == 6:\n            return padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]\n        else:\n            raise ValueError(\"Size of padding can only be 3 or 6\")\n    elif isinstance(padding, int):\n        pad_d = pad_h = pad_w = padding * 2\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_front = (pad_d + 1) // 2\n    pad_top = (pad_h + 1) // 2\n    pad_left = (pad_w + 1) // 2\n    return pad_front, pad_top, pad_left, pad_d - pad_front, pad_h - pad_top, pad_w - pad_left\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument,invalid-name\n\"\"\"The base node types for the Relay language.\"\"\"\nimport tvm._ffi\nimport tvm.ir\nimport tvm.ir._ffi_api\nfrom tvm.driver import build, lower\nfrom tvm.runtime import Object\nfrom tvm.target import GenericFunc, get_native_generic_func\n\nfrom . import _make\n\n\ndef get(op_name):\n    \"\"\"Get the Op for a given name\n\n    Parameters\n    ----------\n    op_name : str\n        The operator name\n\n    Returns\n    -------\n    op : Op\n        The op of the corresponding name\n    \"\"\"\n    return tvm.ir.Op.get(op_name)\n\n\ndef register(op_name, describe=\"\"):\n    \"\"\"Get the Op for a given name.\n    when the op_name is not registered, create a new empty op with the given name.\n    when the op_name has been registered, abort with an error message.\n\n    Parameters\n    ----------\n    op_name : str\n        The operator name\n\n    describe : Optional[str]\n        The operator description\n    \"\"\"\n\n    tvm.ir._ffi_api.RegisterOp(op_name, describe)\n\n\ndef register_stateful(op_name, stateful, level=10):\n    \"\"\"Register stateful flag for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    stateful : bool\n        The stateful flag.\n\n    level : int\n        The priority level\n    \"\"\"\n    tvm.ir.register_op_attr(op_name, \"TOpIsStateful\", stateful, level)\n\n\nclass OpPattern(object):\n    \"\"\"Operator generic patterns\n\n    See Also\n    --------\n    topi.tag : Contains explanation of the tag type.\n    \"\"\"\n\n    # Elementwise operator\n    ELEMWISE = 0\n    # Broadcast operator\n    BROADCAST = 1\n    # Injective mapping\n    INJECTIVE = 2\n    # Communication\n    COMM_REDUCE = 3\n    # Complex op, can still fuse ewise into it\n    OUT_ELEMWISE_FUSABLE = 4\n    # Represents tuple node\n    TUPLE = 7\n    # Not fusable opaque op\n    OPAQUE = 8\n\n\n@tvm._ffi.register_object(\"relay.OpImplementation\")\nclass OpImplementation(Object):\n    \"\"\"Operator implementation\"\"\"\n\n    def compute(self, attrs, inputs, out_type):\n        \"\"\"Call compute function.\n\n        Parameters\n        ----------\n        attrs : Attrs\n            Op attributes.\n\n        inputs : list[te.tensor.Tensor]\n            The input tensors.\n\n        out_type : relay.Type\n            The output type.\n\n        Returns\n        -------\n        outs : list[te.tensor.Tensor]\n            The output tensors.\n        \"\"\"\n        return _OpImplementationCompute(self, attrs, inputs, out_type)\n\n    def schedule(self, attrs, outs, target):\n        \"\"\"Call schedule function.\n\n        Parameters\n        ----------\n        attrs : Attrs\n            Op attributes.\n\n        outs : list[te.tensor.Tensor]\n            The output tensors.\n\n        target : tvm.target.Target\n            The target to schedule the op.\n\n        Returns\n        -------\n        schedule : tvm.te.Schedule\n            The schedule.\n        \"\"\"\n        return _OpImplementationSchedule(self, attrs, outs, target)\n\n\n@tvm._ffi.register_object(\"relay.OpSpecialization\")\nclass OpSpecialization(Object):\n    \"\"\"Operator specialization\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.OpStrategy\")\nclass OpStrategy(Object):\n    \"\"\"Operator strategy\"\"\"\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_make.OpStrategy)\n\n    def add_implementation(self, compute, schedule, name=\"default\", plevel=10):\n        \"\"\"Add an implementation to the strategy\n\n        Parameters\n        ----------\n        compute : function (attrs: Attrs, inputs: List[Tensor], out_type: Type)\n                           -> List[Tensor]\n            The compute function.\n\n        schedule : function (attrs: Attrs, outs: List[Tensor], target:Target) -> Schedule\n            The schedule function.\n\n        name : str\n            The name of implementation.\n\n        plevel : int\n            The priority level of implementation.\n        \"\"\"\n        _OpStrategyAddImplementation(self, compute, schedule, name, plevel)\n\n\ndef _wrap_default_fstrategy(compute, schedule, name):\n    def _fstrategy(attrs, inputs, out_type, target):\n        strategy = OpStrategy()\n        strategy.add_implementation(compute, schedule, name=name)\n        return strategy\n\n    return _fstrategy\n\n\ndef _create_fstrategy_from_schedule(op_name, schedule):\n    assert hasattr(schedule, \"dispatch_dict\")\n    compute = get(op_name).get_attr(\"FTVMCompute\")\n    assert compute is not None, \"FTVMCompute is not registered for op %s\" % op_name\n    fstrategy = get_native_generic_func(\"{}_strategy\".format(op_name))\n    name_pfx = schedule.__name__\n    name_pfx = name_pfx[name_pfx.index(\"_\") + 1 :]\n    fstrategy.set_default(\n        _wrap_default_fstrategy(compute, schedule.fdefault, \"%s.generic\" % name_pfx)\n    )\n    for key, sch in schedule.dispatch_dict.items():\n        fstrategy.register(_wrap_default_fstrategy(compute, sch, \"%s.%s\" % (name_pfx, key)), [key])\n    return fstrategy\n\n\ndef register_compute(op_name, compute=None, level=10):\n    \"\"\"Register compute function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    compute : function (attrs: Attrs, inputs: List[Tensor], out_type: Type)\n                       -> List[Tensor]\n        The compute function.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMCompute\", compute, level)\n\n\ndef register_strategy(op_name, fstrategy=None, level=10):\n    \"\"\"Register strategy function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    fstrategy : function (attrs: Attrs, inputs: List[Tensor], out_type: Type,\n                          target:Target) -> OpStrategy\n        The strategy function. Need to be native GenericFunc.\n\n    level : int\n        The priority level\n    \"\"\"\n    if not isinstance(fstrategy, GenericFunc):\n        assert hasattr(fstrategy, \"generic_func_node\")\n        fstrategy = fstrategy.generic_func_node\n    return tvm.ir.register_op_attr(op_name, \"FTVMStrategy\", fstrategy, level)\n\n\ndef register_schedule(op_name, schedule, level=10):\n    \"\"\"Register schedule function for an op.\n\n    This is used when compute function is the same for all targets and only\n    schedule is different. It requires FTVMCompute is already registered to\n    the op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    schedule : function (attrs: Attrs, outs: List[Tensor], target:Target) -> Schedule\n        The schedule function. Need to be target.generic_func.\n\n    level : int\n        The priority level\n    \"\"\"\n    fstrategy = _create_fstrategy_from_schedule(op_name, schedule)\n    return register_strategy(op_name, fstrategy, level)\n\n\ndef register_injective_schedule(op_name, level=10):\n    \"\"\"Register injective schedule function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    level : int\n        The priority level\n    \"\"\"\n    return register_schedule(op_name, _schedule_injective, level)\n\n\ndef register_broadcast_schedule(op_name, level=10):\n    \"\"\"Register broadcast schedule function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    level : int\n        The priority level\n    \"\"\"\n    return register_schedule(op_name, _schedule_injective, level)\n\n\ndef register_reduce_schedule(op_name, level=10):\n    \"\"\"Register reduce schedule function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    level : int\n        The priority level\n    \"\"\"\n    return register_schedule(op_name, _schedule_reduce, level)\n\n\ndef register_alter_op_layout(op_name, alter_layout=None, level=10):\n    \"\"\"Register alter op layout function for an op\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    alter_layout: function (attrs: Attrs, inputs: List[Expr]) -> new_expr: Expr\n        The function for changing the layout or replacing the operator\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMAlterOpLayout\", alter_layout, level)\n\n\ndef register_convert_op_layout(op_name, convert_layout=None, level=10):\n    \"\"\"Register convert op layout function for an op\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    convert_layout: function (attrs: Attrs, inputs: List[Expr]) -> new_expr: Expr\n        The function for changing the layout or replacing the operator\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMConvertOpLayout\", convert_layout, level)\n\n\ndef register_infer_correct_layout(op_name, infer_layout=None, level=10):\n    \"\"\"Register infer op layout function for an op\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    infer_layout: function (attrs: Attrs, inputs: List[Layout]) -> InferCorrectLayoutOutput\n        The function to infer correct layout\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FInferCorrectLayout\", infer_layout, level)\n\n\ndef register_legalize(op_name, legal_op=None, level=10):\n    \"\"\"Register legal transformation function for an op\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    legal_op: function (attrs: Attrs, inputs: List[Expr]) -> new_expr: Expr\n        The function for transforming an expr to another expr.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMLegalize\", legal_op, level)\n\n\ndef register_pattern(op_name, pattern, level=10):\n    \"\"\"Register operator pattern for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    pattern : int\n        The pattern being used.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"TOpPattern\", pattern, level)\n\n\ndef register_gradient(op_name, fgradient=None, level=10):\n    \"\"\"Register operator gradient function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    fgradient : function (orig_expr : Expr, output_grad : Expr) -> new_expr : Expr\n        The gradient being used.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FPrimalGradient\", fgradient, level)\n\n\ndef register_shape_func(op_name, data_dependent, shape_func=None, level=10):\n    \"\"\"Register operator shape function for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the op.\n\n    data_dependent : bool or list of bool\n        Whether the shape function depends on input data. If this is a list of bool,\n        the length of the list must be the same as the number of arguments of this op.\n        The list specifies per-input data dependence of the op.\n\n    shape_func : function (attrs: Attrs, inputs: List[Tensor], out_ndims: List[IndexExpr])\n                 -> shape_tensors: List<Tensor>\n        The function for computing the dynamic output shapes\n\n    level : int\n        The priority level\n    \"\"\"\n    if not isinstance(data_dependent, list):\n        data_dependent = [data_dependent]\n    get(op_name).set_attr(\"TShapeDataDependent\", data_dependent, level)\n    return tvm.ir.register_op_attr(op_name, \"FShapeFunc\", shape_func, level)\n\n\ndef register_external_compiler(op_name, fexternal=None, level=10):\n    \"\"\"Register the external compiler for an op.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator.\n\n    fexternal : function (attrs: Attrs, args: List[Expr], compiler: str)\n              -> new_expr: Expr\n        The function for wrapping a call expr with compiler_begin and\n        compiler_end.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMExternalCompiler\", fexternal, level)\n\n\ndef register_fake_quantization_to_integer(op_name, func=None, level=10):\n    \"\"\"Register quantize function for an op\n\n    Given an op and Affine Types on it's inputs, this function should return the op\n    in affine space/integer operators and the new type of the output, where affine\n    denotes the transformation x_real = (x_affine - zero_point) * scale\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    func: function (expr: Expr, map: Map<Expr, AffineType>) -> new_expr: Expr\n        The function for translating the op into affine space and integer operators\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMFakeQuantizationToInteger\", func, level)\n\n\ndef register_mixed_precision_conversion(op_name, func=None, level=10):\n    \"\"\"Register mixed precision conversion function for an op\n\n    Given an op the function should return information on how the value should be\n    converted. Specifically the function should take a call node and the target\n    mixed precision datatype (e.g. FP16) and return the conversion category\n    (see python/tvm/relay/transform/mixed_precision.py) as well as the accumulation\n    and output datatype of the operation in the mixed precision dtype space.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    func: function (call_node: relay.Call, target_dtype: string)\n    -> [conversion category, accumulation dtype, output dtype]: [int, string, string]\n        A function which given a call_node and target_dtype (e.g. FP16) returns the\n        conversion category and associated accumulation/output of the operation\n        when transformed into the mixed precision dtype space.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMMixedPrecisionConversionType\", func, level)\n\n\n@tvm._ffi.register_func(\"relay.op.compiler._lower\")\ndef _lower(name, schedule, inputs, outputs):\n    return lower(schedule, list(inputs) + list(outputs), name=name)\n\n\n@tvm._ffi.register_func(\"relay.op.compiler._build\")\ndef _build(lowered_funcs):\n    return build(lowered_funcs, target=\"llvm\")\n\n\n_schedule_injective = None\n_schedule_reduce = None\n\n__DEBUG_COUNTER__ = 0\n\n\ndef debug(expr, debug_func=None):\n    \"\"\"The main entry point to the debugger.\"\"\"\n    global __DEBUG_COUNTER__\n\n    if debug_func:\n        name = \"debugger_func{}\".format(__DEBUG_COUNTER__)\n        tvm._ffi.register_func(name, debug_func)\n        __DEBUG_COUNTER__ += 1\n    else:\n        name = \"\"\n\n    return _make.debug(expr, name)\n\n\ntvm._ffi._init_api(\"relay.op\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/op_attrs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The attributes node used for Relay operators\"\"\"\nfrom tvm.ir import Attrs\nimport tvm._ffi\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv1DAttrs\")\nclass Conv1DAttrs(Attrs):\n    \"\"\"Attributes for nn.conv1d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv2DAttrs\")\nclass Conv2DAttrs(Attrs):\n    \"\"\"Attributes for nn.conv2d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv2DWinogradAttrs\")\nclass Conv2DWinogradAttrs(Attrs):\n    \"\"\"Attributes for nn.contrib_conv2d_winograd_without_weight_transform\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv3DAttrs\")\nclass Conv3DAttrs(Attrs):\n    \"\"\"Attributes for nn.conv3d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv3DWinogradAttrs\")\nclass Conv3DWinogradAttrs(Attrs):\n    \"\"\"Attributes for nn.contrib_conv3d_winograd_without_weight_transform\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ConvWinogradWeightTransformAttrs\")\nclass ConvWinogradWeightTransformAttrs(Attrs):\n    \"\"\"Attributes for nn.contrib_convNd_winograd_weight_transform\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv2DWinogradNNPACKWeightTransformAttrs\")\nclass Conv2DWinogradNNPACKWeightTransformAttrs(Attrs):\n    \"\"\"Attributes for nn.contrib_conv2d_winograd_nnpack_weight_transform\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GlobalPool2DAttrs\")\nclass GlobalPool2DAttrs(Attrs):\n    \"\"\"Attributes for nn.global_pool\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BiasAddAttrs\")\nclass BiasAddAttrs(Attrs):\n    \"\"\"Atttribute of nn.bias_add\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MatmulAttrs\")\nclass MatmulAttrs(Attrs):\n    \"\"\"Attributes for nn.matmul\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DenseAttrs\")\nclass DenseAttrs(Attrs):\n    \"\"\"Attributes for nn.dense\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DensePackAttrs\")\nclass DensePackAttrs(Attrs):\n    \"\"\"Attributes for nn.contrib_dense_pack\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BatchMatmulAttrs\")\nclass BatchMatmulAttrs(Attrs):\n    \"\"\"Attributes for nn.batch_matmul\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SoftmaxAttrs\")\nclass SoftmaxAttrs(Attrs):\n    \"\"\"Attributes for nn.softmax\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.FIFOBufferAttrs\")\nclass FIFOBufferAttrs(Attrs):\n    \"\"\"Attributes for nn.fifo_buffer\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.UpSamplingAttrs\")\nclass UpSamplingAttrs(Attrs):\n    \"\"\"Attributes for nn.upsampling\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.UpSampling3DAttrs\")\nclass UpSampling3DAttrs(Attrs):\n    \"\"\"Attributes for nn.upsampling3d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.PadAttrs\")\nclass PadAttrs(Attrs):\n    \"\"\"Attributes for nn.pad\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MirrorPadAttrs\")\nclass MirrorPadAttrs(Attrs):\n    \"\"\"Attributes for nn.mirror_pad\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.LeakyReluAttrs\")\nclass LeakyReluAttrs(Attrs):\n    \"\"\"Attributes for nn.leaky_relu\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.PReluAttrs\")\nclass PReluAttrs(Attrs):\n    \"\"\"Attributes for nn.prelu\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DropoutAttrs\")\nclass DropoutAttrs(Attrs):\n    \"\"\"Attributes for nn.dropout\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BatchNormAttrs\")\nclass BatchNormAttrs(Attrs):\n    \"\"\"Attributes for nn.batch_norm\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.LRNAttrs\")\nclass LRNAttrs(Attrs):\n    \"\"\"Attributes for nn.lrn\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.L2NormalizeAttrs\")\nclass L2NormalizeAttrs(Attrs):\n    \"\"\"Attributes for nn.l2_normalize\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DeformableConv2DAttrs\")\nclass DeformableConv2DAttrs(Attrs):\n    \"\"\"Attributes for nn.deformable_conv2d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Resize1DAttrs\")\nclass Resize1DAttrs(Attrs):\n    \"\"\"Attributes for image.resize1d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Resize2DAttrs\")\nclass Resize2DAttrs(Attrs):\n    \"\"\"Attributes for image.resize2d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Resize3DAttrs\")\nclass Resize3DAttrs(Attrs):\n    \"\"\"Attributes used in resize3d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.CropAndResizeAttrs\")\nclass CropAndResizeAttrs(Attrs):\n    \"\"\"Attributes for image.crop_and_resize\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Dilation2DAttrs\")\nclass Dilation2DAttrs(Attrs):\n    \"\"\"Attributes for image.dilation2d\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ArgsortAttrs\")\nclass ArgsortAttrs(Attrs):\n    \"\"\"Attributes for algorithm.argsort\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.OnDeviceAttrs\")\nclass OnDeviceAttrs(Attrs):\n    \"\"\"Attributes for annotation.on_device\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DebugAttrs\")\nclass DebugAttrs(Attrs):\n    \"\"\"Attributes for debug\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.CompilerAttrs\")\nclass CompilerAttrs(Attrs):\n    \"\"\"Attributes for compiler\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DeviceCopyAttrs\")\nclass DeviceCopyAttrs(Attrs):\n    \"\"\"Attributes for annotation.device_copy\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.CastAttrs\")\nclass CastAttrs(Attrs):\n    \"\"\"Attributes for transform.cast\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ConcatenateAttrs\")\nclass ConcatenateAttrs(Attrs):\n    \"\"\"Attributes for tensor.concatenate\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TransposeAttrs\")\nclass TransposeAttrs(Attrs):\n    \"\"\"Attributes for transform.transpose\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ReshapeAttrs\")\nclass ReshapeAttrs(Attrs):\n    \"\"\"Attributes for transform.reshape\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ReshapeLikeAttrs\")\nclass ReshapeLikeAttrs(Attrs):\n    \"\"\"Attributes for transform.reshape_like\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GatherAttrs\")\nclass GatherAttrs(Attrs):\n    \"\"\"Attributes for transform.gather\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TakeAttrs\")\nclass TakeAttrs(Attrs):\n    \"\"\"Attributes for transform.take\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.InitOpAttrs\")\nclass InitOpAttrs(Attrs):\n    \"\"\"Attributes for ops specifying a tensor\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ArangeAttrs\")\nclass ArangeAttrs(Attrs):\n    \"\"\"Attributes used in arange operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MeshgridAttrs\")\nclass MeshgridAttrs(Attrs):\n    \"\"\"Attributes used in arange operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.StackAttrs\")\nclass StackAttrs(Attrs):\n    \"\"\"Attributes used in stack operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.RepeatAttrs\")\nclass RepeatAttrs(Attrs):\n    \"\"\"Attributes used in repeat operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TileAttrs\")\nclass TileAttrs(Attrs):\n    \"\"\"Attributes used in tile operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ReverseAttrs\")\nclass ReverseAttrs(Attrs):\n    \"\"\"Attributes used in reverse operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ReverseSequenceAttrs\")\nclass ReverseSequenceAttrs(Attrs):\n    \"\"\"Attributes used in reverse sequence operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SqueezeAttrs\")\nclass SqueezeAttrs(Attrs):\n    \"\"\"Attributes used in squeeze operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SplitAttrs\")\nclass SplitAttrs(Attrs):\n    \"\"\"Attributes for transform.split\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.StridedSliceAttrs\")\nclass StridedSliceAttrs(Attrs):\n    \"\"\"Attributes for transform.stranded_slice\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SliceLikeAttrs\")\nclass SliceLikeAttrs(Attrs):\n    \"\"\"Attributes for transform.slice_like\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ClipAttrs\")\nclass ClipAttrs(Attrs):\n    \"\"\"Attributes for transform.clip\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.LayoutTransformAttrs\")\nclass LayoutTransformAttrs(Attrs):\n    \"\"\"Attributes for transform.layout_transform\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ShapeOfAttrs\")\nclass ShapeOfAttrs(Attrs):\n    \"\"\"Attributes for tensor.shape_of\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MultiBoxPriorAttrs\")\nclass MultiBoxPriorAttrs(Attrs):\n    \"\"\"Attributes for vision.multibox_prior\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MultiBoxTransformLocAttrs\")\nclass MultiBoxTransformLocAttrs(Attrs):\n    \"\"\"Attributes for vision.multibox_transform_loc\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GetValidCountsAttrs\")\nclass GetValidCountsAttrs(Attrs):\n    \"\"\"Attributes for vision.get_valid_counts\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.NonMaximumSuppressionAttrs\")\nclass NonMaximumSuppressionAttrs(Attrs):\n    \"\"\"Attributes for vision.non_maximum_suppression\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AllClassNonMaximumSuppressionAttrs\")\nclass AllClassNonMaximumSuppressionAttrs(Attrs):\n    \"\"\"Attributes for vision.all_classnon_maximum_suppression\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ROIAlignAttrs\")\nclass ROIAlignAttrs(Attrs):\n    \"\"\"Attributes for vision.roi_align\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ROIPoolAttrs\")\nclass ROIPoolAttrs(Attrs):\n    \"\"\"Attributes for vision.roi_pool\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.YoloReorgAttrs\")\nclass YoloReorgAttrs(Attrs):\n    \"\"\"Attributes for vision.yolo_reorg\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ProposalAttrs\")\nclass ProposalAttrs(Attrs):\n    \"\"\"Attributes used in proposal operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MaxPool2DAttrs\")\nclass MaxPool2DAttrs(Attrs):\n    \"\"\"Attributes used in max_pool2d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AvgPool2DAttrs\")\nclass AvgPool2DAttrs(Attrs):\n    \"\"\"Attributes used in avg_pool2d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MaxPool1DAttrs\")\nclass MaxPool1DAttrs(Attrs):\n    \"\"\"Attributes used in max_pool1d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AvgPool1DAttrs\")\nclass AvgPool1DAttrs(Attrs):\n    \"\"\"Attributes used in avg_pool1d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MaxPool3DAttrs\")\nclass MaxPool3DAttrs(Attrs):\n    \"\"\"Attributes used in max_pool3d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AvgPool3DAttrs\")\nclass AvgPool3DAttrs(Attrs):\n    \"\"\"Attributes used in avg_pool3d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BitPackAttrs\")\nclass BitPackAttrs(Attrs):\n    \"\"\"Attributes used in bitpack operator\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BinaryConv2DAttrs\")\nclass BinaryConv2DAttrs(Attrs):\n    \"\"\"Attributes used in bitserial conv2d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BinaryDenseAttrs\")\nclass BinaryDenseAttrs(Attrs):\n    \"\"\"Attributes used in bitserial dense operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv2DTransposeAttrs\")\nclass Conv2DTransposeAttrs(Attrs):\n    \"\"\"Attributes used in Transposed Conv2D operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv3DTransposeAttrs\")\nclass Conv3DTransposeAttrs(Attrs):\n    \"\"\"Attributes used in Transposed Conv3D operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DilateAttrs\")\nclass DilateAttrs(Attrs):\n    \"\"\"Attributes used in dilate operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SubPixelAttrs\")\nclass SubPixelAttrs(Attrs):\n    \"\"\"Attributes used in depth to space and space to depth operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.CorrelationAttrs\")\nclass CorrelationAttrs(Attrs):\n    \"\"\"Attributes used in correlation operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AdaptivePool2DAttrs\")\nclass AdaptivePool2DAttrs(Attrs):\n    \"\"\"Attributes used in 2D adaptive pooling operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AdaptivePool3DAttrs\")\nclass AdaptivePool3DAttrs(Attrs):\n    \"\"\"Attributes used in 3D adaptive pooling operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AffineGridAttrs\")\nclass AffineGridAttrs(Attrs):\n    \"\"\"Attributes used in affine_grid operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AllocStorageAttrs\")\nclass AllocStorageAttrs(Attrs):\n    \"\"\"Attributes used in alloc_storage operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AllocTensorAttrs\")\nclass AllocTensorAttrs(Attrs):\n    \"\"\"Attributes used in alloc_tensor operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.CastHintAttrs\")\nclass CastHintAttrs(Attrs):\n    \"\"\"Attributes used in cast_hint annotation operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.Conv1DTransposeAttrs\")\nclass Conv1DTransposeAttrs(Attrs):\n    \"\"\"Attributes used in 1D transposed convolution operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ExpandDimsAttrs\")\nclass ExpandDimsAttrs(Attrs):\n    \"\"\"Attributes used in expand_dims operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GridSampleAttrs\")\nclass GridSampleAttrs(Attrs):\n    \"\"\"Attributes used in grid_sample operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GroupNormAttrs\")\nclass GroupNormAttrs(Attrs):\n    \"\"\"Attributes used in group norm operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.InstanceNormAttrs\")\nclass InstanceNormAttrs(Attrs):\n    \"\"\"Attributes used in instance norm operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.LayerNormAttrs\")\nclass LayerNormAttrs(Attrs):\n    \"\"\"Attributes used in layer norm operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.NdarraySizeAttrs\")\nclass NdarraySizeAttrs(Attrs):\n    \"\"\"Attributes used in ndarray_size operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.OneHotAttrs\")\nclass OneHotAttrs(Attrs):\n    \"\"\"Attributes used in one_hot operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BroadcastAttrs\")\nclass BroadcastAttrs(Attrs):\n    \"\"\"Attributes used in broadcast operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.QuantizeAttrs\")\nclass QuantizeAttrs(Attrs):\n    \"\"\"Attributes used in quantize operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DequantizeAttrs\")\nclass DequantizeAttrs(Attrs):\n    \"\"\"Attributes used in dequantize operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ReduceAttrs\")\nclass ReduceAttrs(Attrs):\n    \"\"\"Attributes used in reduction operators (e.g. sum)\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ArgReduceAttrs\")\nclass ArgReduceAttrs(Attrs):\n    \"\"\"Attributes used in reduction operators (e.g. argmin/argmax)\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.VarianceAttrs\")\nclass VarianceAttrs(Attrs):\n    \"\"\"Attributes used in reduction operators (e.g. sum)\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.RequantizeAttrs\")\nclass RequantizeAttrs(Attrs):\n    \"\"\"Attributes used in requantize operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ScatterAttrs\")\nclass ScatterAttrs(Attrs):\n    \"\"\"Attributes used in scatter operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SequenceMaskAttrs\")\nclass SequenceMaskAttrs(Attrs):\n    \"\"\"Attributes used in sequence_mask operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ShapeFuncAttrs\")\nclass ShapeFuncAttrs(Attrs):\n    \"\"\"Attributes used in shape func operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SimulatedQuantizeAttrs\")\nclass SimulatedQuantizeAttrs(Attrs):\n    \"\"\"Attributes used in simulated_quantize operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SparseDenseAttrs\")\nclass SparseDenseAttrs(Attrs):\n    \"\"\"Attributes used in sparse_dense operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SparseToDenseAttrs\")\nclass SparseToDenseAttrs(Attrs):\n    \"\"\"Attributes used in sparse_to_dense operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SparseTransposeAttrs\")\nclass SparseTransposeAttrs(Attrs):\n    \"\"\"Attributes used in sparse_transpose operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SparseConv2DAttrs\")\nclass SparseConv2DAttrs(Attrs):\n    \"\"\"Attributes used in sparse_conv2d operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TopkAttrs\")\nclass TopkAttrs(Attrs):\n    \"\"\"Attributes used in topk operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SearchSortedAttrs\")\nclass SearchSortedAttrs(Attrs):\n    \"\"\"Attributes used in searchsorted operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TupleGetItemAttrs\")\nclass TupleGetItemAttrs(Attrs):\n    \"\"\"Attributes used in tuple item access operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.WithFuncIdAttrs\")\nclass WithFuncIdAttrs(Attrs):\n    \"\"\"Attributes used in with_funcid annotation operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SpaceToBatchNDAttrs\")\nclass SpaceToBatchNDAttrs(Attrs):\n    \"\"\"Attributes used in SpaceToBatchND operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.BatchToSpaceNDAttrs\")\nclass BatchToSpaceNDAttrs(Attrs):\n    \"\"\"Attributes used in BatchToSpaceNDAttrs operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ThreefryGenerateAttrs\")\nclass ThreefryGenerateAttrs(Attrs):\n    \"\"\"Attributes used in ThreefryGenerateAttrs operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.UniformAttrs\")\nclass UniformAttrs(Attrs):\n    \"\"\"Attributes used in UniformAttrs operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.NLLLossAttrs\")\nclass NLLLossAttrs(Attrs):\n    \"\"\"Attributes for nn.nll_loss\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.FixedPointMultiplyAttrs\")\nclass FixedPointMultiplyAttrs(Attrs):\n    \"\"\"Attributes used in fixed_point_multiply operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.TriluAttrs\")\nclass TriluAttrs(Attrs):\n    \"\"\"Attributes used in trilu operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.SlidingWindowAttrs\")\nclass SlidingWindowAttrs(Attrs):\n    \"\"\"Attributes used in sliding_window operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.DynExpandDimsAttrs\")\nclass DynExpandDimsAttrs(Attrs):\n    \"\"\"Attributes used in dynamic expand_dims operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ScatterAddAttrs\")\nclass ScatterAddAttrs(Attrs):\n    \"\"\"Attributes used in scatter_add operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ScatterNDAttrs\")\nclass ScatterNDAttrs(Attrs):\n    \"\"\"Attributes used in scatter_nd operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.GatherNDAttrs\")\nclass GatherNDAttrs(Attrs):\n    \"\"\"Attributes used in gather_nd operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.AutoSchedulerLayoutTransformAttrs\")\nclass AutoSchedulerLayoutTransformAttrs(Attrs):\n    \"\"\"Attributes used in AutoSchedulerLayoutTransform operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MetaScheduleLayoutTransformAttrs\")\nclass MetaScheduleLayoutTransformAttrs(Attrs):\n    \"\"\"Attributes used in MetaScheduleLayoutTransform operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.MatrixSetDiagAttrs\")\nclass MatrixSetDiagAttrs(Attrs):\n    \"\"\"Attributes used in matrix_set_diag operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.ScanopAttrs\")\nclass ScanopAttrs(Attrs):\n    \"\"\"Attributes used in cumsum and cumprod operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.UniqueAttrs\")\nclass UniqueAttrs(Attrs):\n    \"\"\"Attributes used in unique operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.EinsumAttrs\")\nclass EinsumAttrs(Attrs):\n    \"\"\"Attributes used in einsum operators\"\"\"\n\n\n@tvm._ffi.register_object(\"relay.attrs.StftAttrs\")\nclass StftAttrs(Attrs):\n    \"\"\"Attributes used in stft operators\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/random/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"PRNG related operators.\"\"\"\nfrom .kernel import *\nfrom . import _kernel\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/random/_kernel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Splittable and parallelizable PRNG kernels.\"\"\"\n# pylint: disable=invalid-name,unused-argument\nfrom __future__ import absolute_import\n\nfrom .. import strategy\nfrom ..op import register_strategy, register_pattern, OpPattern\n\n\n# Threefry\nregister_strategy(\"random.threefry_generate\", strategy.threefry_generate_strategy)\nregister_pattern(\"random.threefry_generate\", OpPattern.OPAQUE)\nregister_strategy(\"random.threefry_split\", strategy.threefry_split_strategy)\nregister_pattern(\"random.threefry_split\", OpPattern.OPAQUE)\n\n# Distribution\nregister_strategy(\"random.uniform\", strategy.uniform_strategy)\nregister_pattern(\"random.uniform\", OpPattern.OPAQUE)\nregister_strategy(\"random.normal\", strategy.normal_strategy)\nregister_pattern(\"random.normal\", OpPattern.OPAQUE)\nregister_strategy(\"random.multinomial\", strategy.multinomial_strategy)\nregister_pattern(\"random.multinomial\", OpPattern.OPAQUE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/random/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.random._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/random/kernel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Splittable and parallelizable PRNG kernels.\"\"\"\n# pylint: disable=invalid-name,unused-argument\nfrom __future__ import absolute_import\n\nimport sys\nimport numpy as np\n\nfrom ...expr import Constant, Expr, const\nfrom .... import nd\nfrom . import _make\n\n\ndef threefry_key(seed):\n    \"\"\"Create a new Threefry random number generator key.\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        gen = threefry_key(0)\n        _, random_number = threefry_generate(gen, (4,))\n\n    Parameters\n    ----------\n    seed : int\n        Starting seed for the key\n\n    Returns\n    -------\n    key : relay.Expr\n        New key to pass to future uses of :py:func:`threefry_split` or\n        :py:func:`threefry_generate`.\n    \"\"\"\n    s = np.frombuffer(seed.to_bytes(32, sys.byteorder), dtype=\"uint64\")\n    a = np.concatenate((s, np.array([0, 0, 0, 0, 1 << 63, 0], dtype=\"uint64\")))\n    return Constant(nd.array(a))\n\n\ndef threefry_generate(key, shape):\n    \"\"\"Generate an array of random bits (`uint64`) using the Threefry algorithm\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        key = threefry_key(0)\n        new_key, random1 = threefry_generate(key, (4,))\n        _, random2 = threefry_generate(new_key, (4,))\n        # random1 and random2 are different random numbers\n\n    Parameters\n    ----------\n    key : relay.Expr\n        key that uniquely determines the random values. Multiple uses with the\n        same key will generate the same random values. This key should be\n        treated as an opaque pointer. You can create one from calling\n        :py:func:`threefry_key`, :py:func:`threefry_split`, or\n        :py:func:`threefry_generate`. **Do not use this key again after calling\n        this function.**\n\n    shape : Sequence[int]\n        Desired outputs shape of random numbers.\n\n    Returns\n    -------\n    new_key : relay.Expr\n        New key to pass to future uses of :py:func:`threefry_split` or\n        :py:func:`threefry_generate`.\n\n    random_array : relay.Expr\n        Array of random numbers. Has shape `shape`.\n    \"\"\"\n    return _make.threefry_generate(key, shape)\n\n\ndef threefry_split(key):\n    \"\"\"Split an existing Threefry key into two new ones.\n\n    This is useful if you have to subsequent calls which each need their own\n    independent random number generation.\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        def foo(key):\n            new_key, num = threefry_generate(key, (4,))\n            return num\n\n        key = threefry_key(0)\n        key1, key2 = threefry_split(key)\n        assert foo(key1) != foo(key2)\n\n    Parameters\n    ----------\n    key : relay.Expr\n        key that uniquely determines the random values. Multiple uses with the\n        same generator will generate the same random values. This generator should be\n        treated as an opaque pointer. You can create one from calling\n        :py:func:`threefry_key`, :py:func:`threefry_split`, or\n        :py:func:`threefry_generate`. **Do not use this generator again after calling\n        this function.**\n\n    Returns\n    -------\n    new_key_1 : relay.Expr\n        New key to pass to future uses of :py:func:`threefry_split` or\n        :py:func:`threefry_generate`.\n\n    new_key_2 : relay.Expr\n        New key to pass to future uses of :py:func:`threefry_split` or\n        :py:func:`threefry_generate`.\n    \"\"\"\n    return _make.threefry_split(key)\n\n\ndef uniform(key, shape, dtype=\"float32\", low=0.0, high=1.0):\n    \"\"\"Draw samples from a uniform distribution.\n\n    Samples are uniformly distributed over the half-open interval [low, high)\n    (includes low, but excludes high). In other words, any value within the\n    given interval is equally likely to be drawn by uniform.\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        key = threefry_key(0)\n        key, random_values = uniform(key, (100,), low=0, high=10)\n\n    Parameters\n    ----------\n    key : relay.Expr\n        key that uniquely determines the random values. Multiple uses with the\n        same generator will generate the same random values. This generator should be\n        treated as an opaque pointer. You can create one from calling\n        :py:func:`threefry_key`, :py:func:`threefry_split`, or\n        :py:func:`threefry_generate`. **Do not use this generator again after calling\n        this function.**\n\n    shape : Sequence[int]\n        Desired outputs shape of random numbers.\n\n    dtype : str\n        Desired outputs type of random numbers.\n\n    low : float or relay.Expr, optional\n        Lower bound of the uniform distribution.\n\n    high : float or relay.Expr, optional\n        Upper bound of the uniform distribution.\n\n    Returns\n    -------\n    new_key : relay.Expr\n        New random key to pass to future uses of random functions.\n\n    random_values : relay.Expr\n        The generated uniform distributed random numbers.\n    \"\"\"\n    if not isinstance(low, Expr):\n        low = const(low, dtype=dtype)\n    if not isinstance(high, Expr):\n        high = const(high, dtype=dtype)\n    return _make.uniform(key, low, high, shape, dtype)\n\n\ndef normal(key, shape, dtype=\"float32\", mean=0.0, scale=1.0):\n    \"\"\"Draw samples from a normal distribution.\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        key = threefry_key(0)\n        key, random_values = normal(key, (100,), low=0, high=10)\n\n    Parameters\n    ----------\n    key : relay.Expr\n        key that uniquely determines the random values. Multiple uses with the\n        same generator will generate the same random values. This generator should be\n        treated as an opaque pointer. You can create one from calling\n        :py:func:`threefry_key`, :py:func:`threefry_split`, or\n        :py:func:`threefry_generate`. **Do not use this generator again after calling\n        this function.**\n\n    shape : Sequence[int]\n        Desired outputs shape of random numbers.\n\n    dtype : str\n        Desired outputs type of random numbers.\n\n    low : float or relay.Expr, optional\n        Mean of the normal distribution.\n\n    high : float or relay.Expr, optional\n        Standard deviation of the normal distribution.\n\n    Returns\n    -------\n    new_key : relay.Expr\n        New random key to pass to future uses of random functions.\n\n    random_values : relay.Expr\n        The generated normal distributed random numbers.\n    \"\"\"\n    if not isinstance(mean, Expr):\n        mean = const(mean, dtype=dtype)\n    if not isinstance(scale, Expr):\n        scale = const(scale, dtype=dtype)\n    return _make.normal(key, mean, scale, shape, dtype)\n\n\ndef multinomial(key, probs, num_samples):\n    \"\"\"Draw samples from a multinomial distribution.\n\n    Example\n    -------\n\n    .. code-block:: python\n\n        key = threefry_key(0)\n        key, random_indices = multinomial(key, (3, 5, 10), num_samples=2)\n\n    Parameters\n    ----------\n    key : relay.Expr\n        key that uniquely determines the random values. Multiple uses with the\n        same generator will generate the same random values. This generator should be\n        treated as an opaque pointer. You can create one from calling\n        :py:func:`threefry_key`, :py:func:`threefry_split`, or\n        :py:func:`threefry_generate`. **Do not use this generator again after calling\n        this function.**\n\n    probs: relay.Expr\n        Array containing the probabilities of returning each respective index.\n        If a tensor is provided, the last dimension is treated independently.\n        Negative values in this tensor will be clipped to zero to\n        represent they have no chance of being selected.\n\n    num_samples : int\n        Number of samples to return\n\n    Returns\n    -------\n    new_key : relay.Expr\n        New random key to pass to future uses of random functions.\n\n    random_indices : relay.Expr\n        The generated indices.\n    \"\"\"\n    return _make.multinomial(key, probs, num_samples)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Reduce operators.\"\"\"\n# pylint: disable=redefined-builtin\n\nfrom ..expr import Tuple, TupleWrapper\nfrom . import _make\nfrom .tensor import exp, log, sqrt\nfrom .transform import squeeze\n\n\ndef argmax(data, axis=None, keepdims=False, exclude=False, select_last_index=False):\n    \"\"\"Returns the indices of the maximum values along an axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a argmax operation is performed.\n        The default, axis=None, will find the indices of the maximum element of the elements of\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    select_last_index : bool\n        Whether to select the last index or the first index if the max element appears in\n        multiple indices, default is False (first index).\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.argmax(data, axis, keepdims, exclude, select_last_index)\n\n\ndef argmin(data, axis=None, keepdims=False, exclude=False, select_last_index=False):\n    \"\"\"Returns the indices of the minimum values along an axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a argmin operation is performed.\n        The default, axis=None, will find the indices of minimum element all of the elements of\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    select_last_index : bool\n        Whether to select the last index or the first index if the min element appears in\n        multiple indices, default is False (first index).\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.argmin(data, axis, keepdims, exclude, select_last_index)\n\n\ndef sum(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the sum of array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a sum is performed. The default, axis=None,\n        will sum all of the elements of the input array. If axis is\n        negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as\n        dimensions with size one. With this option, the result will broadcast\n        correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.sum(data, axis, keepdims, exclude)\n\n\ndef all(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the logical AND of boolean array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input boolean tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a sum is performed. The default, axis=None,\n        will sum all of the elements of the input array. If axis is\n        negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as\n        dimensions with size one. With this option, the result will broadcast\n        correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = relay.Constant(tvm.nd.array([[[ True,  True,  True],\n                                           [ True,  True,  True],\n                                           [False,  True, False]],\n                                          [[ True, False, False],\n                                           [ True,  True, False],\n                                           [False,  True,  True]]]))\n\n        relay.all(data, axis=1)\n        # [[False,  True, False],\n        # [False, False, False]]\n\n        relay.all(data, axis=0)\n        # [[ True, False, False],\n        # [ True,  True, False],\n        # [False,  True, False]]\n\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.all(data, axis, keepdims, exclude)\n\n\ndef any(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the logical OR of boolean array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input boolean tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a sum is performed. The default, axis=None,\n        will sum all of the elements of the input array. If axis is\n        negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as\n        dimensions with size one. With this option, the result will broadcast\n        correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = relay.Constant(tvm.nd.array([[[ True,  True,  True],\n                                            [ True,  True,  True],\n                                            [False,  True, False]],\n                                            [[ True, False, False],\n                                            [ True,  True, False],\n                                            [False,  True,  True]]]))\n\n        relay.any(data, axis=1)\n        # [[True, True, True],\n        # [True,  True, True]]\n\n        relay.any(data, axis=0)\n        # [[ True, True, True],\n        # [ True,  True, True],\n        # [False,  True, True]]\n\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.any(data, axis, keepdims, exclude)\n\n\ndef max(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the max of array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which the max operation is performed.\n        The default, axis=None, will find the max element from all of the elements of the input\n        array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.max(data, axis, keepdims, exclude)\n\n\ndef min(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the min of array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a minimum operation is performed.\n        The default, axis=None, will find the minimum element from all\n        of the elements of the input array. If axis is negative it counts from\n        the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.min(data, axis, keepdims, exclude)\n\n\ndef mean(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the mean of array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a mean operation is performed.\n        The default, axis=None, will compute the mean of all elements in the input array.\n        If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.mean(data, axis, keepdims, exclude)\n\n\ndef variance(data, axis=None, keepdims=False, exclude=False, unbiased=False, with_mean=None):\n    \"\"\"Computes the variance of data over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a variance operation is performed.\n        The default, axis=None, will compute the variance of all elements in the input array.\n        If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    unbiased : bool\n        If this is set to True, the unbiased estimation will be used.\n\n    with_mean : Optional[relay.Expr]\n        To compute variance given an already computed mean\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    m = mean(data, axis, True, exclude) if with_mean is None else with_mean\n    return _make._variance(data, m, axis, keepdims, exclude, unbiased)\n\n\ndef std(data, axis=None, keepdims=False, exclude=False, unbiased=False):\n    \"\"\"Computes the standard deviation of data over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a standard deviation operation is performed.\n        The default, axis=None, will compute the standard deviation of all elements in the\n        input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    unbiased : bool\n        If this is set to True, the unbiased estimation will be used.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    m = mean(data, axis, True, exclude)\n    return sqrt(_make._variance(data, m, axis, keepdims, exclude, unbiased))\n\n\ndef mean_variance(data, axis=None, keepdims=False, exclude=False, unbiased=False):\n    \"\"\"Computes the mean and variance of data over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a mean and variance operation is performed.\n        The default, axis=None, will compute the mean and variance of all elements in\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    unbiased : bool\n        If this is set to True, the unbiased estimation will be used.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    m = mean(data, axis, True, exclude)\n    var = _make._variance(data, m, axis, keepdims, exclude, unbiased)\n    if not keepdims:\n        m = squeeze(m, axis=axis)\n    return TupleWrapper(Tuple((m, var)), 2)\n\n\ndef mean_std(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the mean and standard deviation of data over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a mean and standard deviation operation is performed.\n        The default, axis=None, will compute the mean and standard deviation of all elements in\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    m = mean(data, axis, True, exclude)\n    s = sqrt(_make._variance(data, m, axis, keepdims, exclude, False))\n    if not keepdims:\n        m = squeeze(m)\n    return TupleWrapper(Tuple((m, s)), 2)\n\n\ndef prod(data, axis=None, keepdims=False, exclude=False):\n    \"\"\"Computes the products of array elements over given axes.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a product is performed.\n        The default, axis=None, will find the indices of minimum element all of the elements of\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    exclude : bool\n        If `exclude` is true, reduction will be performed on the axes that are\n        NOT in axis instead.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    axis = [axis] if isinstance(axis, int) else axis\n    return _make.prod(data, axis, keepdims, exclude)\n\n\ndef logsumexp(data, axis=None, keepdims=False):\n    \"\"\"Compute the log of the sum of exponentials of input elements over given axes.\n\n       This function is more numerically stable than log(sum(exp(input))).\n       It avoids overflows caused by taking the exp of large inputs and underflows\n       caused by taking the log of small inputs.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    axis : None or int or tuple of int\n        Axis or axes along which a standard deviation operation is performed.\n        The default, axis=None, will compute the log of the sum of exponentials of all elements\n        in the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n\n    axis = [axis] if isinstance(axis, int) else axis\n    max_x = max(data, axis, True)\n    exp_x = exp(data - max_x)\n    sum_x = sum(exp_x, axis, True)\n    out_x = log(sum_x) + max_x\n    if not keepdims:\n        out_x = squeeze(out_x, axis)\n    return out_x\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Relay op strategies.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .generic import *\nfrom . import x86\nfrom . import arm_cpu\nfrom . import cuda\nfrom . import hls\nfrom . import mali\nfrom . import bifrost\nfrom . import rocm\nfrom . import intel_graphics\nfrom . import hexagon\nfrom . import adreno\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/adreno.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of adreno operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nfrom tvm import topi\nfrom .generic import *\nfrom .. import op as _op\n\n\n@conv2d_NCHWc_strategy.register(\"adreno\")\n@conv2d_strategy.register(\"adreno\")\ndef conv2d_strategy_adreno(attrs, inputs, out_type, target):\n    \"\"\"conv2d adreno strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    groups = attrs.groups\n    data_layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if (\n            (data_layout == \"NCHW\" and kernel_layout == \"OIHW\")\n            or (data_layout == \"NCHW4c\" and kernel_layout == \"OIHW4o\")\n            or (data_layout == \"NCHW\" and kernel_layout == \"OIHW4o\")\n        ):\n            if len(kernel.shape) == 4:\n                _, _, kh, kw = get_const_tuple(kernel.shape)\n            else:\n                _, _, kh, kw, _ = get_const_tuple(kernel.shape)\n            if (\n                (2 < kh < 8 and 2 < kw < 8 and kh == kw)\n                and (stride_h == 1 and stride_w == 1)\n                and (dilation_h == 1 and dilation_w == 1)\n                and not (data_layout == \"NCHW\" and kernel_layout == \"OIHW4o\")\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.adreno.conv2d_nchw_winograd),\n                    wrap_topi_schedule(topi.adreno.schedule_conv2d_nchw_winograd),\n                    name=\"conv2d_nchw_winograd.image2d\",\n                    plevel=5,\n                )\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.adreno.conv2d_nchwc),\n                wrap_topi_schedule(topi.adreno.schedule_conv2d_nchwc),\n                name=\"conv2d_nchwc.image2d\",\n                plevel=10,\n            )\n        elif (\n            (data_layout == \"NHWC\" and kernel_layout == \"HWIO\")\n            or (data_layout == \"NHWC4c\" and kernel_layout == \"HWIO4o\")\n            or (data_layout == \"NHWC\" and kernel_layout == \"HWIO4o\")\n        ):\n            if len(kernel.shape) == 4:\n                kh, kw, _, _ = get_const_tuple(kernel.shape)\n            else:\n                kh, kw, _, _, _ = get_const_tuple(kernel.shape)\n            if (\n                (2 < kh < 8 and 2 < kw < 8 and kh == kw)\n                and (stride_h == 1 and stride_w == 1)\n                and (dilation_h == 1 and dilation_w == 1)\n                and not (data_layout == \"NHWC\" and kernel_layout == \"HWIO4o\")\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.adreno.conv2d_nhwc_winograd),\n                    wrap_topi_schedule(topi.adreno.schedule_conv2d_nhwc_winograd),\n                    name=\"conv2d_nhwc_winograd.image2d\",\n                    plevel=5,\n                )\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.adreno.conv2d_nhwc),\n                wrap_topi_schedule(topi.adreno.schedule_conv2d_nhwc),\n                name=\"conv2d_nhwc.image2d\",\n                plevel=10,\n            )\n        else:\n            raise RuntimeError(\n                \"Layout not supported: (\"\n                + data_layout\n                + \", \"\n                + kernel_layout\n                + \") - only support NCHW4c / OIHW4o and NHWC / HWOI layouts for conv2d\"\n            )\n    else:\n        # cannot use is_depthwise_conv2d because it does not know about NHWC4c/HWOI4o layouts\n        if data_layout == \"NCHW\":\n            ic = data.shape[1]\n        elif data_layout == \"NCHW4c\":\n            ic = data.shape[1] * data.shape[4]\n        elif data_layout == \"NHWC\":\n            ic = data.shape[3]\n        elif data_layout == \"NHWC4c\":\n            ic = data.shape[3] * data.shape[4]\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d data layout {}\".format(data_layout))\n        if kernel_layout == \"OIHW\":\n            oc = kernel.shape[0]\n        elif kernel_layout == \"OIHW4o\":\n            oc = kernel.shape[0] * kernel.shape[4]\n        elif kernel_layout == \"HWOI\":\n            oc = kernel.shape[2]\n        elif kernel_layout == \"HWOI4o\":\n            oc = kernel.shape[2] * kernel.shape[4]\n        else:\n            raise RuntimeError(\n                \"Unsupported depthwise_conv2d kernel layout {}\".format(kernel_layout)\n            )\n\n        if ic == oc == groups:\n            if (data_layout == \"NCHW\" and kernel_layout == \"OIHW\") or (\n                data_layout == \"NCHW4c\" and kernel_layout == \"OIHW4o\"\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.adreno.depthwise_conv2d_nchwc),\n                    wrap_topi_schedule(topi.adreno.schedule_depthwise_conv2d_nchwc),\n                    name=\"depthwise_conv2d_nchwc.image2d\",\n                    plevel=10,\n                )\n            elif (data_layout == \"NHWC\" and kernel_layout == \"HWOI\") or (\n                data_layout == \"NHWC4c\" and kernel_layout == \"HWOI4o\"\n            ):\n                if data.shape[-1] >= 4:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.adreno.depthwise_conv2d_nhwc),\n                        wrap_topi_schedule(topi.adreno.schedule_depthwise_conv2d_nhwc),\n                        name=\"depthwise_conv2d_nhwc.image2d\",\n                        plevel=10,\n                    )\n                else:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                        wrap_topi_schedule(topi.cuda.schedule_depthwise_conv2d_nhwc),\n                        name=\"depthwise_conv2d_nhwc.cuda\",\n                    )\n            else:\n                raise RuntimeError(\n                    \"Layout not supported: (\"\n                    + data_layout\n                    + \", \"\n                    + kernel_layout\n                    + \") - only support NCHW4c / OIHW4o and NHWC / HWOI layouts for conv2d\"\n                )\n        else:\n            raise RuntimeError(\"General group convolution is not currently supported\")\n    return strategy\n\n\n@conv2d_winograd_without_weight_transform_strategy.register(\"adreno\")\ndef conv2d_winograd_without_weight_transform_strategy_adreno(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform adreno strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout in (\"NCHW\", \"NCHW4c\"):\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.adreno.conv2d_nchw_winograd_without_weight_transform),\n            wrap_topi_schedule(topi.adreno.schedule_conv2d_nchw_winograd_without_weight_transform),\n            name=\"conv2d_nchw_winograd_without_weight_transform.image2d\",\n            plevel=5,\n        )\n    elif layout in (\"NHWC\", \"NHWC4c\"):\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.adreno.conv2d_nhwc_winograd_without_weight_transform),\n            wrap_topi_schedule(topi.adreno.schedule_conv2d_nhwc_winograd_without_weight_transform),\n            name=\"conv2d_nhwc_winograd_without_weight_transform.image2d\",\n            plevel=5,\n        )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@schedule_pool.register(\"adreno\")\ndef schedule_pool_adreno(attrs, outs, target):\n    \"\"\"schedule pooling ops for adreno\"\"\"\n    with target:\n        if attrs.layout == \"NCHW4c\":\n            return topi.adreno.schedule_pool(outs, attrs.layout)\n        return topi.cuda.schedule_pool(outs, attrs.layout)\n\n\n@schedule_injective.register([\"adreno\"])\ndef schedule_injective_adreno(attrs, outs, target):\n    \"\"\"schedule injective ops for adreno\"\"\"\n    with target:\n        return topi.adreno.schedule_injective(outs)\n\n\n@schedule_reduce.register([\"adreno\"])\ndef schedule_reduce_adreno(attrs, outs, target):\n    \"\"\"schedule reduction ops for adreno GPU\"\"\"\n    with target:\n        return topi.adreno.schedule_reduce(outs)\n\n\n@concatenate_strategy.register([\"adreno\"])\ndef concatenate_strategy_adreno(attrs, inputs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_concat(topi.transform.concatenate),\n        wrap_topi_schedule(topi.adreno.schedule_injective),\n        name=\"concatenate.adreno\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/arm_cpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of ARM CPU operator strategy.\"\"\"\nfrom functools import reduce\nimport logging\n\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nimport re\n\nfrom tvm import relay, topi\n\nfrom ....auto_scheduler import is_auto_scheduler_enabled\nfrom ....meta_schedule import is_meta_schedule_enabled\nfrom ....topi.generic import conv2d as conv2d_generic\nfrom .. import op as _op\nfrom .generic import *\n\nlogger = logging.getLogger(\"strategy\")\n\n\n@schedule_reduce.register(\"arm_cpu\")\ndef schedule_reduce_cpu(attrs, outs, target):\n    \"\"\"schedule reduction ops for arm_cpu\"\"\"\n    with target:\n        return topi.x86.schedule_reduce(outs)\n\n\n@schedule_injective.register(\"arm_cpu\")\ndef schedule_injective_arm_cpu(_, outs, target):\n    \"\"\"schedule injective ops for arm cpu\"\"\"\n    with target:\n        return topi.arm_cpu.schedule_injective(outs)\n\n\n@schedule_concatenate.register(\"arm_cpu\")\ndef schedule_concatenate_arm_cpu(_, outs, target):\n    \"\"\"schedule concatenate for arm cpu\"\"\"\n    with target:\n        return topi.arm_cpu.schedule_concatenate(outs)\n\n\n@schedule_pool.register([\"arm_cpu\"])\ndef schedule_pool_arm_cpu(attrs, outs, target):\n    \"\"\"schedule pooling ops arm cpu\"\"\"\n    layout = attrs.layout\n    avg_pool = isinstance(attrs, relay.op.op_attrs.AvgPool2DAttrs)\n    with target:\n        if (\n            avg_pool\n            and target.features.has_dsp\n            and layout in (\"NCW\", \"NCHW\")\n            or not avg_pool\n            and target.features.has_dsp\n            and layout in (\"NWC\", \"NHWC\")\n        ):\n            return topi.arm_cpu.schedule_pool(outs, layout)\n        logger.warning(\"pool is not optimized for arm cpu.\")\n        return topi.generic.schedule_pool(outs, layout)\n\n\ndef _get_padding_width(padding):\n    assert isinstance(padding, tuple)\n    if len(padding) == 2:\n        _, (pad_left, pad_right) = padding\n    else:\n        _, pad_left, _, pad_right = padding\n    return pad_left + pad_right\n\n\ndef _is_simd_aligned(dtype, dimensions, padding=None):\n    if padding:\n        assert len(dimensions) == len(padding)\n        padded_dims = (sum(x) for x in zip(dimensions, padding))\n    else:\n        padded_dims = dimensions\n\n    # Multiply all elements of padded_dims together. We can't use math.prod, as it\n    # does not exist in Python 3.7.\n    size = reduce(lambda x, y: x * y, padded_dims)\n    return (\n        (dtype == \"int8\" and size % 4 == 0)\n        or (dtype == \"int16\" and size % 2 == 0)\n        or (dtype == \"int32\")\n    )\n\n\n@conv2d_strategy.register(\"arm_cpu\")\ndef conv2d_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d arm cpu strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            if kernel_layout == \"OIHW\":\n                if (\n                    topi.arm_cpu.is_int8_hw_support(data.dtype, kernel.dtype)\n                    and kernel.shape[1] >= 64\n                ):\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_int8),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_int8),\n                        name=\"conv2d_nchw_int8.arm_cpu\",\n                        plevel=15,\n                    )\n                else:\n                    # ARM conv2d spatial pack schedule.\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_spatial_pack),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_spatial_pack),\n                        name=\"conv2d_nchw_spatial_pack.arm_cpu\",\n                        plevel=10,\n                    )\n\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.x86.conv2d_nchw),\n                        wrap_topi_schedule(topi.x86.schedule_conv2d_nchw),\n                        name=\"conv2d_nchw.x86\",\n                    )\n\n                # check if winograd algorithm is applicable\n                _, _, kh, kw = get_const_tuple(kernel.shape)\n                pt, pl, pb, pr = topi.nn.get_pad_tuple(padding, (kh, kw))\n                is_winograd_applicable = (\n                    \"float\" in data.dtype\n                    and \"float\" in kernel.dtype\n                    and kh == 3\n                    and kw == 3\n                    and stride_h == 1\n                    and stride_w == 1\n                    and dilation_h == 1\n                    and dilation_w == 1\n                )\n                if is_winograd_applicable:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_winograd),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_winograd),\n                        name=\"conv2d_nchw_winograd.arm_cpu\",\n                        plevel=5,\n                    )\n                    if \"nnpack\" in target.libs and pt == 1 and pb == 1 and pl == 1 and pr == 1:\n                        strategy.add_implementation(\n                            wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_winograd_nnpack),\n                            wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_winograd_nnpack),\n                            name=\"conv2d_nchw_winograd_nnpack.arm_cpu\",\n                            plevel=15,\n                        )\n            elif re.match(r\"OIHW\\d*o\", kernel_layout):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_spatial_pack),\n                    wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_spatial_pack),\n                    name=\"conv2d_nchw_spatial_pack.arm_cpu\",\n                )\n            else:\n                raise RuntimeError(\n                    \"Unsupported weight layout {} for conv2d NCHW\".format(kernel_layout)\n                )\n        elif layout == \"HWCN\":\n            assert kernel_layout == \"HWIO\"\n            logger.warning(\"conv2d_hwcn is not optimized for arm cpu.\")\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_hwcn),\n                wrap_topi_schedule(topi.generic.schedule_conv2d_hwcn),\n                name=\"conv2d_hwcn.generic\",\n            )\n        elif layout == \"NHWC\":\n            data_width_padding = _get_padding_width(padding)\n            if (\n                target.features.has_dsp\n                and dilation_w == dilation_h == 1\n                and kernel_layout == \"OHWI\"\n                # Check SIMD alignment\n                and _is_simd_aligned(data.dtype, data.shape[2:], padding=(data_width_padding, 0))\n                and _is_simd_aligned(kernel.dtype, kernel.shape[2:])\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.arm_cpu.conv2d_nhwc_ohwi_dsp, need_out_layout=True),\n                    wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nhwc_ohwi_dsp),\n                    name=\"conv2d_nhwc_ohwi_dsp.arm_cpu\",\n                )\n            elif target.features.has_dsp and kernel_layout == \"HWOI\":\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.arm_cpu.conv2d_nhwc_dsp),\n                    wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nhwc_dsp),\n                    name=\"conv2d_nhwc_dsp.arm_cpu\",\n                )\n            elif kernel_layout == \"HWIO\":\n                has_asimd = target.features.has_asimd\n                has_dot_prod = target.features.has_dotprod\n                if has_dot_prod and data.dtype in [\"int8\", \"uint8\"]:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.compute_conv2d_NHWC_quantized_native),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_NHWC_quantized_native),\n                        name=\"conv2d_NHWC_quantized_native.arm_cpu\",\n                    )\n                if has_asimd and data.dtype in [\"int8\", \"uint8\"]:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved),\n                        name=\"conv2d_NHWC_quantized_interleaved.arm_cpu\",\n                    )\n                if (not has_asimd) or (data.dtype not in [\"int8\", \"uint8\"]):\n                    # TODO(@giuseros)\n                    # This strategy errors out for quantized data types when tuning.\n                    # Let's use this only for non-aarch64 or non-quantized cases\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.conv2d_nhwc_spatial_pack),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nhwc_spatial_pack),\n                        name=\"conv2d_nhwc_spatial_pack.arm_cpu\",\n                    )\n            else:\n                raise RuntimeError(\n                    \"Unsupported kernel layout {} for conv2d NHWC\".format(kernel_layout)\n                )\n\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {} for arm cpu\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\" or re.match(r\"OIHW\\d*o\", kernel_layout)\n            if kernel_layout == \"OIHW\":\n                data_width_padding = _get_padding_width(padding)\n                if (\n                    target.features.has_dsp\n                    and dilation_w == dilation_h == 1\n                    and _is_simd_aligned(data.dtype, data.shape[3:], padding=(data_width_padding,))\n                    and _is_simd_aligned(kernel.dtype, kernel.shape[3:])\n                ):\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(\n                            topi.arm_cpu.depthwise_conv2d_nchw_oihw_dsp, need_out_layout=True\n                        ),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_depthwise_conv2d_nchw_oihw_dsp),\n                        name=\"depthwise_conv2d_nchw_oihw_dsp.arm_cpu\",\n                    )\n                else:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.arm_cpu.depthwise_conv2d_nchw),\n                        wrap_topi_schedule(topi.arm_cpu.schedule_depthwise_conv2d_nchw),\n                        name=\"depthwise_conv2d_nchw.arm_cpu\",\n                    )\n\n            # TODO:\n            # This schedule has incorrect result on some hardware platforms (like NV Jetson TX2)\n            # Let us comment it out but not remove.\n            # see discussion:\n            # https://discuss.tvm.apache.org/t/autotuner-incorrect-result-after-tuning-mobilenetv2-on-arm-cpu/6088\n            # strategy.add_implementation(\n            #     wrap_compute_conv2d(topi.arm_cpu.depthwise_conv2d_nchw_spatial_pack),\n            #     wrap_topi_schedule(topi.arm_cpu.schedule_depthwise_conv2d_nchw_spatial_pack),\n            #     name=\"depthwise_conv2d_nchw_spatial_pack.arm_cpu\",\n            #     plevel=15)\n\n            # Intel x86 depthwise conv2d schedule.\n            channel_multiplier = get_const_tuple(inputs[1].shape)[1]\n            if channel_multiplier == 1 and dilation_h == 1 and dilation_w == 1:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.depthwise_conv2d_nchw),\n                    wrap_topi_schedule(topi.x86.schedule_depthwise_conv2d_nchw),\n                    name=\"depthwise_conv2d_nchw.x86\",\n                )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            if target.features.has_asimd:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.arm_cpu.compute_depthwise_conv2d_nhwc),\n                    wrap_topi_schedule(topi.arm_cpu.schedule_depthwise_conv2d_nhwc),\n                    name=\"depthwise_conv2d_nhwc.arm_cpu\",\n                )\n\n            # Optimized special case depthwiseConv2D operation. Requires NHWC layout,\n            # a HWOI kernel layout (which we rearrange to a custom layout) no dilation,\n            # int8/16 inputs, int32 output, and the same number of input and output channels.\n            # The int8 implementation DOES need the DSP unit (for SXTB16), but it is not\n            # possible to use the DSP unit to speed up a NHWC depthwise convolution (though\n            # an NCHW convolution would benefit).\n\n            elif (\n                dilation_w == dilation_h == 1\n                and kernel.shape[3] == 1  # channel_multiplier == 1\n                and out_type.dtype == \"int32\"\n                and (\n                    (data.shape[3] % 4 == 0 and data.dtype == \"int8\" and target.features.has_dsp)\n                    or (data.shape[3] % 2 == 0 and data.dtype == \"int16\")\n                )\n                and (padding != \"SAME\" or data.shape[1] % stride_h == data.shape[2] % stride_w == 0)\n                # Ideally we should check that kernel is a Relay constant, but strategy functions\n                # don't have access to the data needed to check this.\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.arm_cpu.depthwise_conv2d_nhwc_dsp),\n                    wrap_topi_schedule(topi.arm_cpu.schedule_depthwise_conv2d_nhwc_dsp),\n                    name=\"depthwise_conv2d_nhwc_dsp.arm_cpu\",\n                )\n\n            else:\n                logger.warning(\"depthwise_conv2d with layout NHWC is not optimized for arm cpu.\")\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                    wrap_topi_schedule(conv2d_generic.schedule_depthwise_conv2d_nhwc),\n                    name=\"depthwise_conv2d_nhwc.generic\",\n                )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {} for arm cpu\".format(layout))\n    else:  # group_conv2d\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.arm_cpu.group_conv2d_nchw, has_groups=True),\n                wrap_topi_schedule(topi.arm_cpu.schedule_group_conv2d_nchw),\n                name=\"group_conv2d_nchw.arm_cpu\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            logger.warning(\"group_conv2d with layout NHWC is not optimized for arm cpu.\")\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.group_conv2d_nhwc, has_groups=True),\n                wrap_topi_schedule(topi.generic.schedule_group_conv2d_nhwc),\n                name=\"group_conv2d_nhwc.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported group_conv2d layout {} for arm cpu\".format(layout))\n    return strategy\n\n\n@conv2d_NCHWc_strategy.register(\"arm_cpu\")\ndef conv2d_NCHWc_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc adopted from x86\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    if topi.arm_cpu.is_int8_hw_support(data.dtype, kernel.dtype):\n        strategy.add_implementation(\n            wrap_compute_conv2d(\n                topi.arm_cpu.conv2d_NCHWc_int8, need_data_layout=True, need_out_layout=True\n            ),\n            wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_NCHWc_int8),\n            name=\"conv2d_NCHWc_int8.arm_cpu\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.x86.conv2d_NCHWc, need_data_layout=True, need_out_layout=True),\n            wrap_topi_schedule(topi.x86.schedule_conv2d_NCHWc),\n            name=\"conv2d_NCHWc.x86\",\n        )\n    return strategy\n\n\n@depthwise_conv2d_NCHWc_strategy.register(\"arm_cpu\")\ndef depthwise_conv2d_NCHWc_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"depthwise_conv2d_NCHWc adopted from x86\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(\n            topi.x86.depthwise_conv2d_NCHWc, need_data_layout=True, need_out_layout=True\n        ),\n        wrap_topi_schedule(topi.x86.schedule_depthwise_conv2d_NCHWc),\n        name=\"depthwise_conv2d_NCHWc.x86\",\n    )\n    return strategy\n\n\ndef wrap_compute_conv2d_winograd_nnpack(topi_compute):\n    \"\"\"wrap topi compute for conv2d_winograd NNPack\"\"\"\n\n    def _compute_conv2d_nnpack(attrs, inputs, out_type):\n        padding = attrs.get_int_tuple(\"padding\")\n        strides = attrs.get_int_tuple(\"strides\")\n        dilation = attrs.get_int_tuple(\"dilation\")\n        out_dtype = attrs.get_str(\"out_dtype\")\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        return [topi_compute(inputs[0], inputs[1], None, strides, padding, dilation, out_dtype)]\n\n    return _compute_conv2d_nnpack\n\n\n@conv2d_winograd_without_weight_transform_strategy.register(\"arm_cpu\")\ndef conv2d_winograd_without_weight_transform_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform arm cpu strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    strides = attrs.get_int_tuple(\"strides\")\n    kernel = inputs[1]\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert strides == (1, 1), \"Do not support strides now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout == \"NCHW\":\n        if len(kernel.shape) == 5:\n            pad_kh, pad_kw, _, _, _ = get_const_tuple(inputs[1].shape)\n            tile_size = attrs.get_int(\"tile_size\")\n            kh = pad_kh - tile_size + 1\n            kw = pad_kw - tile_size + 1\n            assert kh == 3 and kw == 3\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.arm_cpu.conv2d_nchw_winograd),\n                wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_nchw_winograd),\n                name=\"conv2d_nchw_winograd.arm_cpu\",\n            )\n        elif len(kernel.shape) == 4:\n            # kernel must be packed by winograd nnpack\n            assert \"nnpack\" in target.libs\n            strategy.add_implementation(\n                wrap_compute_conv2d_winograd_nnpack(\n                    topi.arm_cpu.conv2d_nchw_winograd_nnpack_without_weight_transform\n                ),\n                wrap_topi_schedule(\n                    topi.arm_cpu.schedule_conv2d_nchw_winograd_nnpack_without_weight_transform\n                ),\n                name=\"conv2d_nchw_winograd_nnpack_withou_weight_transform.arm_cpu\",\n                plevel=15,\n            )\n        else:\n            raise RuntimeError(\"Unsupported kernel shape: {}\".format(kernel.shape))\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\ndef wrap_compute_conv2d_gemm(topi_compute):\n    \"\"\"wrap topi compute for conv2d_gemm\"\"\"\n\n    def _compute_conv2d_gemm(attrs, inputs, out_type):\n        padding = attrs.get_int_tuple(\"padding\")\n        strides = attrs.get_int_tuple(\"strides\")\n        dilation = attrs.get_int_tuple(\"dilation\")\n        out_dtype = attrs.get_str(\"out_dtype\")\n        channels = attrs[\"channels\"]\n        kernel_size = attrs[\"kernel_size\"]\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        return [\n            topi_compute(\n                inputs[0], inputs[1], strides, padding, dilation, out_dtype, kernel_size, channels\n            )\n        ]\n\n    return _compute_conv2d_gemm\n\n\n@conv2d_gemm_without_weight_transform_strategy.register(\"arm_cpu\")\ndef conv2d_gemm_without_weight_transform_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform arm cpu strategy\"\"\"\n    layout = attrs.data_layout\n    data = inputs[0]\n    strategy = _op.OpStrategy()\n\n    interleaved_compute = topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved_without_transform\n    native_compute = topi.arm_cpu.compute_conv2d_NHWC_quantized_native_without_transform\n    if layout == \"NHWC\" and data.dtype in [\"int8\", \"uint8\"]:\n        strategy.add_implementation(\n            wrap_compute_conv2d_gemm(native_compute),\n            wrap_topi_schedule(\n                topi.arm_cpu.schedule_conv2d_NHWC_quantized_native_without_transform\n            ),\n            name=\"conv2d_NHWC_quantized_native_without_transform.arm_cpu\",\n        )\n        strategy.add_implementation(\n            wrap_compute_conv2d_gemm(interleaved_compute),\n            wrap_topi_schedule(\n                topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved_without_transform\n            ),\n            name=\"conv2d_NHWC_quantized_interleaved_without_transform.arm_cpu\",\n        )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_NHWC_quantized_without_transform layout {0}\"\n            \"with datatype {1}\".format(layout, data.dtype)\n        )\n    return strategy\n\n\n@conv2d_transpose_strategy.register(\"arm_cpu\")\ndef conv2d_transpose_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose arm cpu strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCHW\", \"only support nchw for now\"\n    assert dilation == (1, 1), \"not support dilate now\"\n    assert groups == 1, \"only support groups == 1 for now\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d_transpose(topi.arm_cpu.conv2d_transpose_nchw),\n        wrap_topi_schedule(topi.arm_cpu.schedule_conv2d_transpose_nchw),\n        name=\"conv2d_tranpose_nchw.arm_cpu\",\n    )\n    return strategy\n\n\n@bitserial_conv2d_strategy.register(\"arm_cpu\")\ndef bitserial_conv2d_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"bitserial_conv2d x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.x86.bitserial_conv2d_nchw),\n            wrap_topi_schedule(topi.x86.schedule_bitserial_conv2d_nchw),\n            name=\"bitserial_conv2d_nchw.arm_cpu\",\n        )\n    elif layout == \"NHWC\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.arm_cpu.bitserial_conv2d_nhwc),\n            wrap_topi_schedule(topi.arm_cpu.schedule_bitserial_conv2d_nhwc),\n            name=\"bitserial_conv2d_nhwc.arm_cpu\",\n        )\n    else:\n        raise ValueError(\"Data layout {} not supported.\".format(layout))\n    return strategy\n\n\n@bitserial_dense_strategy.register(\"arm_cpu\")\ndef schedule_bitserial_dense_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"bitserial_dense arm cpu strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_bitserial_dense(topi.arm_cpu.bitserial_dense),\n        wrap_topi_schedule(topi.arm_cpu.schedule_bitserial_dense),\n        name=\"bitserial_dense.arm_cpu\",\n    )\n    return strategy\n\n\n@dense_strategy.register([\"arm_cpu\"])\ndef schedule_dense_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"dense arm cpu strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, _ = inputs\n\n    if target.features.has_dsp and data.dtype in [\"int8\", \"int16\"]:\n        strategy.add_implementation(\n            wrap_compute_dense(topi.arm_cpu.dense_dsp),\n            wrap_topi_schedule(topi.arm_cpu.schedule_dense_dsp),\n            name=\"dense_dsp.arm_cpu\",\n        )\n    else:\n        logger.warning(\"dense is not optimized for arm cpu.\")\n        strategy.add_implementation(\n            wrap_compute_dense(\n                topi.nn.dense,\n                need_auto_scheduler_layout=is_auto_scheduler_enabled(),\n                need_meta_schedule_layout=is_meta_schedule_enabled(),\n            ),\n            wrap_topi_schedule(topi.generic.schedule_dense),\n            name=\"dense.generic\",\n        )\n    return strategy\n\n\n@conv1d_strategy.register(\"arm_cpu\")\ndef conv1d_strategy_arm_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv1d strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    dilation = get_const_tuple(attrs.dilation)\n    if dilation[0] < 1:\n        raise ValueError(\"dilation should be a positive value\")\n\n    if kernel_layout == \"WOI\":\n        if layout == \"NWC\" and target.features.has_dsp:\n            strategy.add_implementation(\n                wrap_compute_conv1d(topi.arm_cpu.conv1d_nwc_dsp),\n                wrap_topi_schedule(topi.arm_cpu.schedule_conv1d_nwc_dsp),\n                name=\"conv1d_dsp.arm_cpu\",\n            )\n        else:\n            raise RuntimeError(\n                \"Unsupported kernel layout {} for conv1d {} for arm cpu.\".format(\n                    kernel_layout, layout\n                )\n            )\n    elif layout == \"NCW\":\n        logger.warning(\"conv1d with layout %s is not optimized for arm cpu.\", layout)\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.conv1d_ncw),\n            wrap_topi_schedule(topi.generic.schedule_conv1d_ncw),\n            name=\"conv1d_ncw.generic\",\n        )\n    elif layout == \"NWC\":\n        logger.warning(\"conv1d with layout %s is not optimized for arm cpu.\", layout)\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.conv1d_nwc),\n            wrap_topi_schedule(topi.generic.schedule_conv1d_nwc),\n            name=\"conv1d_nwc.generic\",\n        )\n    else:\n        raise RuntimeError(\n            \"Unsupported kernel layout {} for conv1d {} for arm cpu.\".format(kernel_layout, layout)\n        )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/bifrost.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of bifrost operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nimport re\nfrom tvm import topi\nfrom .generic import *\nfrom .. import op as _op\n\n\n@conv2d_strategy.register(\"bifrost\")\ndef conv2d_strategy_bifrost(attrs, inputs, out_type, target):\n    \"\"\"conv2d mali(bifrost) strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            if kernel_layout == \"OIHW\":\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.bifrost.conv2d_nchw_spatial_pack),\n                    wrap_topi_schedule(topi.bifrost.schedule_conv2d_nchw_spatial_pack),\n                    name=\"conv2d_nchw_spatial_pack.bifrost\",\n                )\n\n                _, _, kh, kw = get_const_tuple(kernel.shape)\n                if (\n                    kh == 3\n                    and kw == 3\n                    and stride_h == 1\n                    and stride_w == 1\n                    and dilation_h == 1\n                    and dilation_w == 1\n                ):\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.bifrost.conv2d_nchw_winograd),\n                        wrap_topi_schedule(topi.bifrost.schedule_conv2d_nchw_winograd),\n                        name=\"conv2d_nchw_winograd.bifrost\",\n                        plevel=5,\n                    )\n            elif re.match(r\"OIHW\\d*o\", kernel_layout):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.bifrost.conv2d_nchw_spatial_pack),\n                    wrap_topi_schedule(topi.bifrost.schedule_conv2d_nchw_spatial_pack),\n                    name=\"conv2d_nchw_spatial_pack.bifrost\",\n                )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            # For now just reuse general Mali strategy.\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.mali.conv2d_nhwc_spatial_pack),\n                wrap_topi_schedule(topi.mali.schedule_conv2d_nhwc_spatial_pack),\n                name=\"conv2d_nhwc_spatial_pack.bifrost\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {} for Mali(Bifrost)\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.bifrost.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.bifrost\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            # For now just reuse general Mali strategy.\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.mali.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.mali.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_conv2d_nchw.bifrost\",\n            )\n        else:\n            raise RuntimeError(\n                \"Unsupported depthwise_conv2d layout {} for Mali(Bifrost)\".format(layout)\n            )\n    else:  # group_conv2d\n        raise RuntimeError(\"group_conv2d is not supported for Mali(Bifrost)\")\n    return strategy\n\n\n@conv2d_winograd_without_weight_transform_strategy.register(\"bifrost\")\ndef conv2d_winograd_without_weight_transform_strategy_bifrost(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform mali(bifrost) strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    strides = attrs.get_int_tuple(\"strides\")\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert strides == (1, 1), \"Do not support strides now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.bifrost.conv2d_nchw_winograd),\n            wrap_topi_schedule(topi.bifrost.schedule_conv2d_nchw_winograd),\n            name=\"conv2d_nchw_winograd.bifrost\",\n        )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@dense_strategy.register(\"bifrost\")\ndef dense_strategy_bifrost(attrs, inputs, out_type, target):\n    \"\"\"dense mali(bifrost) strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dense(topi.bifrost.dense),\n        wrap_topi_schedule(topi.bifrost.schedule_dense),\n        name=\"dense.bifrost\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of CUDA/GPU operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nfrom tvm import topi\nfrom tvm.auto_scheduler import is_auto_scheduler_enabled\nfrom tvm.contrib import nvcc\nfrom tvm.contrib.thrust import can_use_thrust\nfrom tvm.meta_schedule import is_meta_schedule_enabled\nfrom tvm.te import SpecializedCondition\n\nfrom ....target import Target\nfrom ....tir import IntImm\nfrom .. import op as _op\nfrom .generic import *\n\n\n@schedule_injective.register([\"cuda\", \"gpu\"])\ndef schedule_injective_cuda(attrs, outs, target):\n    \"\"\"schedule injective ops for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_injective(outs)\n\n\n@schedule_reduce.register([\"cuda\", \"gpu\"])\ndef schedule_reduce_cuda(attrs, outs, target):\n    \"\"\"schedule reduction ops for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_reduce(outs)\n\n\n@concatenate_strategy.register([\"cuda\", \"gpu\"])\ndef concatenate_strategy_cuda(attrs, inputs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_concat(topi.transform.concatenate),\n        wrap_topi_schedule(topi.cuda.schedule_injective),\n        name=\"concatenate.cuda\",\n    )\n    return strategy\n\n\n@schedule_pool.register([\"cuda\", \"gpu\"])\ndef schedule_pool_cuda(attrs, outs, target):\n    \"\"\"schedule pooling ops for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_pool(outs, attrs.layout)\n\n\n@schedule_pool_grad.register([\"cuda\", \"gpu\"])\ndef schedule_pool_grad_cuda(attrs, outs, target):\n    \"\"\"schedule pooling gradient ops for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_pool_grad(outs)\n\n\n@schedule_adaptive_pool.register([\"cuda\", \"gpu\"])\ndef schedule_adaptive_pool_cuda(attrs, outs, target):\n    \"\"\"schedule adaptive pooling ops for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_adaptive_pool(outs, attrs.layout)\n\n\n@softmax_strategy.register([\"cuda\", \"gpu\"])\ndef softmax_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"softmax cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.cuda.schedule_softmax),\n        name=\"softmax.cuda\",\n    )\n    if target.kind.name == \"cuda\" and \"cudnn\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_softmax(topi.cuda.softmax_cudnn),\n            wrap_topi_schedule(topi.cuda.schedule_softmax_cudnn),\n            name=\"softmax.cudnn\",\n            plevel=15,\n        )\n    return strategy\n\n\n@fast_softmax_strategy.register([\"cuda\", \"gpu\"])\ndef fast_softmax_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"fast_softmax cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.fast_softmax),\n        wrap_topi_schedule(topi.cuda.schedule_softmax),\n        name=\"fast_softmax.cuda\",\n    )\n    return strategy\n\n\n@log_softmax_strategy.register([\"cuda\", \"gpu\"])\ndef log_softmax_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"log_softmax cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.log_softmax),\n        wrap_topi_schedule(topi.cuda.schedule_softmax),\n        name=\"log_softmax.cuda\",\n    )\n    if target.kind.name == \"cuda\" and \"cudnn\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_softmax(topi.cuda.log_softmax_cudnn),\n            wrap_topi_schedule(topi.cuda.schedule_log_softmax_cudnn),\n            name=\"log_softmax.cudnn\",\n            plevel=15,\n        )\n    return strategy\n\n\n@schedule_lrn.register([\"cuda\", \"gpu\"])\ndef schedule_lrn_cuda(attrs, outs, target):\n    \"\"\"schedule LRN for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_lrn(outs)\n\n\n@conv2d_strategy.register([\"cuda\", \"gpu\"])\ndef conv2d_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv2d cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    padding = attrs.get_int_tuple(\"padding\")\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n    if groups == 1:\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            if (\n                (target.kind.name in [\"cuda\", \"vulkan\", \"rocm\"])\n                and data.dtype in (\"int8\", \"uint8\")\n                and kernel.dtype in (\"int8\", \"uint8\")\n            ):\n                assert data.dtype == kernel.dtype\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.conv2d_nchw_int8),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_nchw_int8),\n                    name=\"conv2d_nchw_int8.cuda\",\n                )\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.conv2d_nchw),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_nchw),\n                    name=\"conv2d_nchw.cuda\",\n                )\n            N, _, H, W = get_const_tuple(data.shape)\n            CO, CI, KH, KW = get_const_tuple(kernel.shape)\n            (_, _, judge_winograd_auto_scheduler) = judge_winograd(\n                N,\n                H,\n                W,\n                KH,\n                KW,\n                CI,\n                CO,\n                padding,\n                stride_h,\n                stride_w,\n                dilation_h,\n                dilation_w,\n                data.dtype,\n                kernel.dtype,\n                pre_flag=False,\n            )\n            if is_meta_schedule_enabled() and judge_winograd_auto_scheduler:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.conv2d_winograd_nchw),\n                    naive_schedule,  # this implementation should never be picked by autotvm\n                    name=\"conv2d_nchw_winograd.cuda\",\n                    plevel=15,\n                )\n            elif (\n                (2 < KH < 8 and 2 < KW < 8 and KH == KW)\n                and (stride_h == 1 and stride_w == 1)\n                and (dilation_h == 1 and dilation_w == 1)\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.conv2d_nchw_winograd),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_nchw_winograd),\n                    name=\"conv2d_nchw_winograd.cuda\",\n                    plevel=5,\n                )\n        elif layout == \"HWCN\":\n            assert kernel_layout == \"HWIO\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.conv2d_hwcn),\n                wrap_topi_schedule(topi.cuda.schedule_conv2d_hwcn),\n                name=\"conv2d_hwcn.cuda\",\n            )\n        elif layout == \"NHWC\" and kernel_layout == \"HWIO\":\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.gpu.conv2d_nhwc),\n                wrap_topi_schedule(topi.gpu.schedule_conv2d_nhwc),\n                name=\"conv2d_nhwc.gpu\",\n            )\n\n            N, H, W, _ = get_const_tuple(data.shape)\n            KH, KW, CI, CO = get_const_tuple(kernel.shape)\n            # Winograd shape related judgment\n            (\n                judge_winograd_tensorcore,\n                judge_winograd_autotvm,\n                judge_winograd_auto_scheduler,\n            ) = judge_winograd(\n                N,\n                H,\n                W,\n                KH,\n                KW,\n                CI,\n                CO,\n                padding,\n                stride_h,\n                stride_w,\n                dilation_h,\n                dilation_w,\n                data.dtype,\n                kernel.dtype,\n                pre_flag=False,\n            )\n            if judge_winograd_autotvm:\n                if (\n                    target.kind.name == \"cuda\"\n                    and nvcc.have_tensorcore(target=target)\n                    and judge_winograd_tensorcore\n                ):\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.cuda.conv2d_nhwc_winograd_tensorcore),\n                        wrap_topi_schedule(topi.cuda.schedule_conv2d_nhwc_winograd_tensorcore),\n                        name=\"conv2d_nhwc_winograd_tensorcore.cuda\",\n                        plevel=5,\n                    )\n                else:\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.cuda.conv2d_nhwc_winograd_direct),\n                        wrap_topi_schedule(topi.cuda.schedule_conv2d_nhwc_winograd_direct),\n                        name=\"conv2d_nhwc_winograd_direct.cuda\",\n                        plevel=5,\n                    )\n            if (\n                target.kind.name == \"cuda\"\n                and nvcc.have_tensorcore(target=target)\n                and (\n                    (N % 16 == 0 and CI % 16 == 0 and CO % 16 == 0)\n                    or (N % 8 == 0 and CI % 16 == 0 and CO % 32 == 0)\n                    or (N % 32 == 0 and CI % 16 == 0 and CO % 8 == 0)\n                )\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.conv2d_nhwc_tensorcore),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_nhwc_tensorcore),\n                    name=\"conv2d_nhwc_tensorcore.cuda\",\n                    plevel=20,\n                )\n\n            # register auto-scheduler implementations\n            if is_auto_scheduler_enabled() and judge_winograd_auto_scheduler:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.conv2d_winograd_nhwc),\n                    naive_schedule,  # this implementation should never be picked by autotvm\n                    name=\"conv2d_nhwc.winograd\",\n                    plevel=15,\n                )\n            # register meta-schedule implementations\n            if is_meta_schedule_enabled() and judge_winograd_auto_scheduler:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.conv2d_winograd_nhwc),\n                    naive_schedule,  # this implementation should never be picked by autotvm\n                    name=\"conv2d_nhwc.winograd\",\n                    plevel=15,\n                )\n\n        elif layout == \"HWNC\":\n            assert kernel_layout in [\"HWOI\", \"HWOI16o16i\", \"HWOI8o32i\", \"HWOI32o16i\"]\n            _, _, N, in_channels = get_const_tuple(data.shape)\n            pre_computed = len(kernel.shape) == 6\n            if pre_computed:\n                _, _, oc_chunk, _, oc_block_factor, _ = get_const_tuple(kernel.shape)\n                out_channels = oc_chunk * oc_block_factor\n            else:\n                _, _, out_channels, _ = get_const_tuple(kernel.shape)\n\n            tensorcore_dtypes = [\"int4\", \"uint4\", \"int8\", \"uint8\"]\n            if (\n                target.kind.name == \"cuda\"\n                and nvcc.have_tensorcore(target=target)\n                and kernel.dtype in tensorcore_dtypes\n                and (\n                    (\n                        data.dtype in [\"int4\", \"uint4\"]\n                        and N % 8 == 0\n                        and in_channels % 32 == 0\n                        and out_channels % 8 == 0\n                    )\n                    or (\n                        data.dtype in [\"int8\", \"uint8\"]\n                        and N % 8 == 0\n                        and in_channels % 16 == 0\n                        and out_channels % 32 == 0\n                    )\n                )\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.conv2d_hwnc_tensorcore),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_hwnc_tensorcore),\n                    name=\"conv2d_hwnc_tensorcore_direct.cuda\",\n                    plevel=20,\n                )\n            else:\n                raise RuntimeError(\n                    \"Unsupported shape for conv2d HWNC.\\\n                                    Need to satisfy tensor core schedule.\"\n                )\n        elif (\n            (target.kind.name in [\"cuda\", \"vulkan\", \"rocm\"])\n            and layout == \"NCHW4c\"\n            and data.dtype in [\"int8\", \"uint8\"]\n        ):\n            assert kernel_layout == \"OIHW4o4i\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.conv2d_NCHWc_int8, need_data_layout=True),\n                wrap_topi_schedule(topi.cuda.schedule_conv2d_NCHWc_int8),\n                name=\"conv2d_NCHWc_int8.cuda\",\n            )\n        elif is_auto_scheduler_enabled() or is_meta_schedule_enabled():\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.nn.conv, need_data_layout=True, need_kernel_layout=True, has_groups=True\n                ),\n                naive_schedule,\n                name=\"conv2d.cuda\",\n                plevel=15,\n            )\n        elif target.kind.name == \"cuda\" and \"cudnn\" not in target.libs:\n            # No TVM native kernel applicable\n            raise RuntimeError(\"Unsupported conv2d layout {} for CUDA\".format(layout))\n\n        if (\n            target.kind.name == \"cuda\"\n            and \"cudnn\" in target.libs\n            and layout in [\"NCHW\", \"NHWC\"]\n            and padding[0] == padding[2]\n            and padding[1] == padding[3]\n            and not (data.dtype in [\"uint8\", \"int8\"] or kernel.dtype in [\"uint8\", \"int8\"])\n        ):\n            # add cudnn implementation\n            if layout == \"NHWC\":\n                assert kernel_layout == \"OHWI\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.conv2d_cudnn, need_data_layout=True, has_groups=True),\n                wrap_topi_schedule(topi.cuda.schedule_conv2d_cudnn),\n                name=\"conv2d_cudnn.cuda\",\n                plevel=25,\n            )\n\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups) and (\n        layout == \"NCHW\" or \"cudnn\" not in target.libs\n    ):  # cuDNN requires a different kernel layout for NHWC inputs.\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.cuda.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.cuda\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.cuda.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_conv2d_nhwc.cuda\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        # add cudnn implementation, if any\n        cudnn_impl = False\n        if target.kind.name == \"cuda\" and \"cudnn\" in target.libs:\n            if (\n                layout in [\"NCHW\", \"NHWC\"]\n                and padding[0] == padding[2]\n                and padding[1] == padding[3]\n                and not (data.dtype in [\"uint8\", \"int8\"] or kernel.dtype in [\"uint8\", \"int8\"])\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(\n                        topi.cuda.conv2d_cudnn, need_data_layout=True, has_groups=True\n                    ),\n                    wrap_topi_schedule(topi.cuda.schedule_conv2d_cudnn),\n                    name=\"conv2d_cudnn.cuda\",\n                    plevel=25,\n                )\n                cudnn_impl = True\n\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            _, channels, _, _ = get_const_tuple(data.shape)\n            out_channels, in_channels, _, _ = get_const_tuple(kernel.shape)\n            oc_chunk = out_channels // 4\n            ic_chunk = in_channels // 4\n\n            if (\n                (target.kind.name in [\"cuda\", \"vulkan\", \"rocm\"])\n                and data.dtype in [\"int8\", \"uint8\"]\n                and kernel.dtype in [\"int8\", \"uint8\"]\n                and channels % groups == 0\n                and out_channels % groups == 0\n                and channels % 4 == 0\n                and out_channels % 4 == 0\n                and groups <= oc_chunk\n                and groups <= ic_chunk\n            ):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.group_conv2d_nchw_int8, has_groups=True),\n                    wrap_topi_schedule(topi.cuda.schedule_group_conv2d_nchw_int8),\n                    name=\"group_conv2d_nchw_int8.cuda\",\n                )\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.cuda.group_conv2d_nchw, has_groups=True),\n                    wrap_topi_schedule(topi.cuda.schedule_group_conv2d_nchw),\n                    name=\"group_conv2d_nchw.cuda\",\n                )\n        elif layout == \"NCHW4c\" and data.dtype in [\"int8\", \"uint8\"]:\n            assert kernel_layout == \"OIHW4o4i\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.group_conv2d_NCHWc_int8, has_groups=True),\n                wrap_topi_schedule(topi.cuda.schedule_group_conv2d_NCHWc_int8),\n                name=\"group_conv2d_NCHWc_int8.cuda\",\n            )\n        elif not cudnn_impl:\n            raise RuntimeError(\"Unsupported group_conv2d layout {}\".format(layout))\n    return strategy\n\n\ndef judge_winograd(\n    N,\n    H,\n    W,\n    KH,\n    KW,\n    CI,\n    CO,\n    padding,\n    stride_h,\n    stride_w,\n    dilation_h,\n    dilation_w,\n    data_dtype,\n    kernel_dtype,\n    pre_flag,\n):\n    \"\"\"Winograd judgement about tensorcore and shape\"\"\"\n    if H % 8 == 0:\n        tile_size = 4\n    else:\n        tile_size = 2\n    if pre_flag:\n        alpha = KH\n        KH = KW = alpha + 1 - tile_size\n    pt, pl, pb, pr = topi.nn.get_pad_tuple(padding, (KH, KW))\n    OH = (H + pt + pb - KH) // stride_h + 1\n    OW = (W + pl + pr - KW) // stride_w + 1\n    nH, nW = (OH + tile_size - 1) // tile_size, (OW + tile_size - 1) // tile_size\n    if not isinstance(N, int):\n        return False, False, False\n    P = N * nH * nW\n\n    judge_winograd_tensorcore = (\n        (P % 16 == 0 and CI % 16 == 0 and CO % 16 == 0)\n        or (P % 8 == 0 and CI % 16 == 0 and CO % 32 == 0)\n        or (P % 32 == 0 and CI % 16 == 0 and CO % 8 == 0)\n    )\n\n    judge_winograd_autotvm = (\n        2 < KH < 8\n        and 2 < KW < 8\n        and KH == KW\n        and stride_h == 1\n        and stride_w == 1\n        and dilation_h == 1\n        and dilation_w == 1\n    )\n\n    judge_winograd_auto_scheduler = (\n        (\"float\" in data_dtype and \"float\" in kernel_dtype)\n        and (KH == 3 and KW == 3)\n        and (stride_h == 1 and stride_w == 1)\n        and (dilation_h == 1 and dilation_w == 1)\n    )\n\n    return judge_winograd_tensorcore, judge_winograd_autotvm, judge_winograd_auto_scheduler\n\n\n@conv2d_winograd_without_weight_transform_strategy.register([\"cuda\", \"gpu\"])\ndef conv2d_winograd_without_weight_transform_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform cuda strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    data, kernel = inputs\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout == \"NCHW\":\n        if is_meta_schedule_enabled():\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_winograd_nchw_without_weight_transform),\n                naive_schedule,  # this implementation should never be picked by autotvm\n                name=\"conv2d_nchw_winograd_without_weight_transform\",\n                plevel=15,\n            )\n        else:\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.conv2d_nchw_winograd_without_weight_transform),\n                wrap_topi_schedule(\n                    topi.cuda.schedule_conv2d_nchw_winograd_without_weight_transform\n                ),\n                name=\"conv2d_nchw_winograd_without_weight_transform.cuda\",\n            )\n    elif layout == \"NHWC\":\n        N, H, W, _ = get_const_tuple(data.shape)\n        alpha, _, CI, CO = get_const_tuple(kernel.shape)\n        dilation_h, dilation_w = dilation\n        judge_winograd_tensorcore, _, _ = judge_winograd(\n            N,\n            H,\n            W,\n            alpha,\n            alpha,\n            CI,\n            CO,\n            padding,\n            stride_h,\n            stride_w,\n            dilation_h,\n            dilation_w,\n            data.dtype,\n            kernel.dtype,\n            pre_flag=True,\n        )\n        if (\n            target.kind.name == \"cuda\"\n            and nvcc.have_tensorcore(target=target)\n            and judge_winograd_tensorcore\n        ):\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.cuda.conv2d_nhwc_winograd_tensorcore_without_weight_transform\n                ),\n                wrap_topi_schedule(\n                    topi.cuda.schedule_conv2d_nhwc_winograd_tensorcore_without_weight_transform\n                ),\n                name=\"conv2d_nhwc_winograd_tensorcore_without_weight_transform.cuda\",\n            )\n        else:\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.cuda.conv2d_nhwc_winograd_direct_without_weight_transform),\n                wrap_topi_schedule(\n                    topi.cuda.schedule_conv2d_nhwc_winograd_direct_without_weight_transform\n                ),\n                name=\"conv2d_nhwc_winograd_direct_without_weight_transform.cuda\",\n            )\n\n        if is_auto_scheduler_enabled():\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_winograd_nhwc_without_weight_transform),\n                naive_schedule,  # this implementation should never be picked by autotvm\n                name=\"conv2d_nhwc_winograd_without_weight_transform\",\n                plevel=15,\n            )\n        if is_meta_schedule_enabled():\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_winograd_nhwc_without_weight_transform),\n                naive_schedule,  # this implementation should never be picked by autotvm\n                name=\"conv2d_nhwc_winograd_without_weight_transform\",\n                plevel=15,\n            )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@deformable_conv2d_strategy.register([\"cuda\", \"gpu\"])\ndef deformable_conv2d_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"deformable_conv2d cuda strategy\"\"\"\n    layout = attrs.data_layout\n    strategy = _op.OpStrategy()\n\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_deformable_conv2d(topi.cuda.deformable_conv2d_nchw),\n            wrap_topi_schedule(topi.cuda.schedule_deformable_conv2d_nchw),\n            name=\"deformable_conv2d_nchw.cuda\",\n        )\n    elif layout == \"NHWC\":\n        # This implementation should never be picked by autotvm\n        strategy.add_implementation(\n            wrap_compute_deformable_conv2d(topi.nn.deformable_conv2d_nhwc),\n            naive_schedule,\n            name=\"deformable_conv2d_nhwc.cuda\",\n        )\n    else:\n        raise RuntimeError(\"Layout %s is not supported in deformable conv2d on CUDA\" % layout)\n    return strategy\n\n\n@conv2d_backward_weight_strategy.register([\"cuda\"])\ndef conv2d_backward_weight_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv2d_backward_weight cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    if target.kind.name == \"cuda\" and \"cudnn\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_conv2d_backward_weight(topi.cuda.conv2d_backward_weight_cudnn),\n            wrap_topi_schedule(topi.generic.schedule_extern),\n            name=\"conv2d_backward_weight_strategy.cudnn\",\n            plevel=15,\n        )\n    else:\n        raise RuntimeError(\n            \"conv2d_backward_weight on cuda is currently only supported with cudnn. \"\n            \"Please run Legalize pass to decompose this op into supported ops.\"\n        )\n    return strategy\n\n\n@conv2d_transpose_strategy.register([\"cuda\", \"gpu\"])\ndef conv2d_transpose_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose cuda strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert dilation == (1, 1), \"not support dilate now\"\n    strategy = _op.OpStrategy()\n    num_strategies = 0\n\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.cuda.conv2d_transpose_nchw, has_groups=True),\n            wrap_topi_schedule(topi.cuda.schedule_conv2d_transpose_nchw),\n            name=\"conv2d_transpose_nchw.cuda\",\n        )\n        num_strategies += 1\n\n    if (\n        target.kind.name == \"cuda\"\n        and \"cudnn\" in target.libs\n        and (\n            (layout == \"NCHW\" and attrs.kernel_layout == \"IOHW\")\n            or (layout == \"NHWC\" and attrs.kernel_layout == \"IHWO\")\n        )\n    ):\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(\n                topi.cuda.conv2d_transpose_cudnn, add_layout=True, has_groups=True\n            ),\n            wrap_topi_schedule(topi.generic.schedule_extern),\n            name=\"conv2d_transpose.cudnn.cuda\",\n            plevel=25,\n        )\n        num_strategies += 1\n\n    # TODO(masahi): Support conv2d_transpose NHWC for non-cudnn path.\n    assert num_strategies > 0, \"Unsupported conv2d_transpose workload, layout = %s, groups = %d\" % (\n        layout,\n        groups,\n    )\n    return strategy\n\n\n@conv3d_transpose_strategy.register([\"cuda\", \"gpu\"])\ndef conv3d_transpose_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv3d_transpose cuda strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCDHW\", \"only support ncdhw for now\"\n    assert dilation == (1, 1, 1), \"not support dilate now\"\n    assert groups == 1, \"only support groups == 1 for now\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv3d_transpose(topi.cuda.conv3d_transpose_ncdhw),\n        wrap_topi_schedule(topi.cuda.schedule_conv3d_transpose_ncdhw),\n        name=\"conv3d_transpose_ncdhw.cuda\",\n    )\n    return strategy\n\n\n@conv3d_strategy.register([\"cuda\", \"gpu\"])\ndef conv3d_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv3d cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    layout = attrs.data_layout\n    _, stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    _, dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    assert layout in [\"NCDHW\", \"NDHWC\"], \"Not support this layout {} yet\".format(layout)\n    if layout == \"NCDHW\":\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.cuda.conv3d_ncdhw),\n            wrap_topi_schedule(topi.cuda.schedule_conv3d_ncdhw),\n            name=\"conv3d_ncdhw.cuda\",\n            plevel=10,\n        )\n        _, _, _, kh, kw = get_const_tuple(kernel.shape)\n        if (\n            2 < kh < 8\n            and 2 < kw < 8\n            and kh == kw\n            and stride_h == 1\n            and stride_w == 1\n            and dilation_h == 1\n            and dilation_w == 1\n            and attrs[\"groups\"] == 1\n        ):\n            strategy.add_implementation(\n                wrap_compute_conv3d(topi.cuda.conv3d_ncdhw_winograd),\n                wrap_topi_schedule(topi.cuda.schedule_conv3d_ncdhw_winograd),\n                name=\"conv3d_ncdhw_winograd.cuda\",\n                plevel=5,\n            )\n    else:  # layout == \"NDHWC\":\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.cuda.conv3d_ndhwc),\n            wrap_topi_schedule(topi.cuda.schedule_conv3d_ndhwc),\n            name=\"conv3d_ndhwc.cuda\",\n            plevel=10,\n        )\n        N, _, _, _, _ = get_const_tuple(data.shape)\n        _, _, _, CI, CO = get_const_tuple(kernel.shape)\n        if target.kind.name == \"cuda\":\n            if nvcc.have_tensorcore(target=target):\n                if (\n                    (N % 16 == 0 and CI % 16 == 0 and CO % 16 == 0)\n                    or (N % 8 == 0 and CI % 16 == 0 and CO % 32 == 0)\n                    or (N % 32 == 0 and CI % 16 == 0 and CO % 8 == 0)\n                ) and out_type == \"float16\":\n                    strategy.add_implementation(\n                        wrap_compute_conv3d(topi.cuda.conv3d_ndhwc_tensorcore),\n                        wrap_topi_schedule(topi.cuda.schedule_conv3d_ndhwc_tensorcore),\n                        name=\"conv3d_ndhwc_tensorcore.cuda\",\n                        plevel=20,\n                    )\n\n    if target.kind.name == \"cuda\" and \"cudnn\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.cuda.conv3d_cudnn, True),\n            wrap_topi_schedule(topi.cuda.schedule_conv3d_cudnn),\n            name=\"conv3d_cudnn.cuda\",\n            plevel=25,\n        )\n    return strategy\n\n\n@conv3d_winograd_without_weight_transform_strategy.register([\"cuda\", \"gpu\"])\ndef conv3d_winograd_without_weight_transform_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv3d_winograd_without_weight_transform cuda strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    assert dilation == (1, 1, 1), \"Do not support dilate now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout == \"NCDHW\":\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.cuda.conv3d_ncdhw_winograd_without_weight_transform),\n            wrap_topi_schedule(topi.cuda.schedule_conv3d_ncdhw_winograd_without_weight_transform),\n            name=\"conv3d_ncdhw_winograd_without_weight_transform.cuda\",\n        )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv3d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@conv1d_strategy.register([\"cuda\", \"gpu\"])\ndef conv1d_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv1d cuda strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    if dilation[0] < 1:\n        raise ValueError(\"dilation should be a positive value\")\n    strategy = _op.OpStrategy()\n    if attrs.groups == 1:\n        if layout == \"NCW\":\n            strategy.add_implementation(\n                wrap_compute_conv1d(topi.cuda.conv1d_ncw),\n                wrap_topi_schedule(topi.cuda.schedule_conv1d_ncw),\n                name=\"conv1d_ncw.cuda\",\n            )\n        elif layout == \"NWC\":\n            strategy.add_implementation(\n                wrap_compute_conv1d(topi.cuda.conv1d_nwc),\n                wrap_topi_schedule(topi.cuda.schedule_conv1d_nwc),\n                name=\"conv1d_nwc.cuda\",\n            )\n        else:\n            raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    else:\n        if layout == \"NCW\":\n            strategy.add_implementation(\n                wrap_compute_group_conv1d(topi.cuda.group_conv1d_ncw),\n                wrap_topi_schedule(topi.cuda.schedule_group_conv1d_ncw),\n                name=\"group_conv1d_ncw.cuda\",\n            )\n        elif layout == \"NWC\":\n            strategy.add_implementation(\n                wrap_compute_group_conv1d(topi.cuda.group_conv1d_nwc),\n                wrap_topi_schedule(topi.cuda.schedule_group_conv1d_nwc),\n                name=\"group_conv1d_nwc.cuda\",\n            )\n        else:\n            raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    return strategy\n\n\n@conv1d_transpose_strategy.register([\"cuda\", \"gpu\"])\ndef conv1d_transpose_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"conv1d_transpose cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCW\", \"conv1d_transpose ncw only supported\"\n    assert dilation == (1,), \"conv1d_transpose dilation is not supported\"\n    assert groups == 1, \"conv1d_transpose groups == 1 only supported\"\n    strategy.add_implementation(\n        wrap_compute_conv1d_transpose(topi.cuda.conv1d_transpose_ncw),\n        wrap_topi_schedule(topi.cuda.schedule_conv1d_transpose_ncw),\n        name=\"conv1d_transpose_ncw.cuda\",\n    )\n    return strategy\n\n\n@matmul_strategy.register([\"cuda\", \"gpu\"])\ndef matmul_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"Matmul cuda strategy.\"\"\"\n    strategy = _op.OpStrategy()\n\n    if is_auto_scheduler_enabled():\n        strategy.add_implementation(\n            wrap_compute_matmul(topi.nn.matmul),\n            naive_schedule,\n            name=\"matmul.cuda\",\n        )\n    elif is_meta_schedule_enabled():\n        strategy.add_implementation(\n            wrap_compute_matmul(topi.nn.matmul),\n            naive_schedule,\n            name=\"matmul.cuda\",\n        )\n    else:\n        logger.warning(\n            \"Matmul is not optimized for cuda. Recommend to use cublas for better performance.\"\n        )\n        # Temporary use this as a basic schedule\n        strategy.add_implementation(\n            wrap_compute_matmul(topi.gpu.matmul_default),\n            wrap_topi_schedule(topi.gpu.schedule_matmul_default),\n            name=\"matmul_default.gpu\",\n        )\n\n    if target.kind.name == \"cuda\" and \"cublas\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_matmul(topi.cuda.matmul_cublas),\n            wrap_topi_schedule(topi.cuda.schedule_matmul_cublas),\n            name=\"matmul_cublas.cuda\",\n            plevel=25,\n        )\n    return strategy\n\n\n@dense_strategy.register([\"cuda\", \"gpu\"])\ndef dense_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"dense cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, weights = inputs\n    b, i = get_const_tuple(data.shape)\n    o, _ = get_const_tuple(weights.shape)\n    if (\n        target.kind.name in [\"cuda\", \"vulkan\", \"rocm\"]\n        and data.dtype == \"int8\"\n        and weights.dtype == \"int8\"\n        and out_type.dtype == \"int32\"\n    ):\n        strategy.add_implementation(\n            wrap_compute_dense(topi.cuda.dense_int8),\n            wrap_topi_schedule(topi.cuda.schedule_dense_int8),\n            name=\"dense_int8.cuda\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_dense(topi.gpu.dense_small_batch),\n            wrap_topi_schedule(topi.gpu.schedule_dense_small_batch),\n            name=\"dense_small_batch.gpu\",\n        )\n\n        with SpecializedCondition(b >= 32):\n            strategy.add_implementation(\n                wrap_compute_dense(topi.gpu.dense_large_batch),\n                wrap_topi_schedule(topi.gpu.schedule_dense_large_batch),\n                name=\"dense_large_batch.gpu\",\n                plevel=5,\n            )\n\n    if target.kind.name == \"cuda\":\n        if nvcc.have_tensorcore(target=target):\n            if (\n                (\n                    data.dtype in [\"float16\", \"int8\", \"uint8\"]\n                    and (\n                        (i % 16 == 0 and b % 16 == 0 and o % 16 == 0)\n                        or (i % 16 == 0 and b % 8 == 0 and o % 32 == 0)\n                        or (i % 16 == 0 and b % 32 == 0 and o % 8 == 0)\n                    )\n                )\n                or (data.dtype in [\"int4\", \"uint4\"] and i % 32 == 0 and b % 8 == 0 and o % 8 == 0)\n                or (data.dtype in [\"int1\", \"uint1\"] and i % 128 == 0 and b % 8 == 0 and o % 8 == 0)\n            ):\n                strategy.add_implementation(\n                    wrap_compute_dense(topi.cuda.dense_tensorcore),\n                    wrap_topi_schedule(topi.cuda.schedule_dense_tensorcore),\n                    name=\"dense_tensorcore.cuda\",\n                    plevel=20,\n                )\n\n    if target.kind.name == \"cuda\" and \"cublas\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_dense(topi.cuda.dense_cublas),\n            wrap_topi_schedule(topi.cuda.schedule_dense_cublas),\n            name=\"dense_cublas.cuda\",\n            plevel=25,\n        )\n    return strategy\n\n\n@batch_matmul_strategy.register([\"cuda\", \"gpu\"])\ndef batch_matmul_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"batch_matmul cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    x, y = inputs\n    if (\n        x.dtype == \"int8\"\n        and y.dtype == \"int8\"\n        and out_type.dtype == \"int32\"\n        and not attrs[\"transpose_a\"]\n        and attrs[\"transpose_b\"]\n    ):\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.cuda.batch_matmul_int8, need_out_dtype=True),\n            wrap_topi_schedule(topi.cuda.schedule_batch_matmul_int8),\n            name=\"batch_matmul_int8.cuda\",\n            plevel=10,\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.cuda.batch_matmul, need_out_dtype=True),\n            wrap_topi_schedule(topi.cuda.schedule_batch_matmul),\n            name=\"batch_matmul.cuda\",\n            plevel=10,\n        )\n    if target.kind.name == \"cuda\" and \"cublas\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.cuda.batch_matmul_cublas, need_out_dtype=True),\n            wrap_topi_schedule(topi.generic.schedule_extern),\n            name=\"batch_matmul_cublas.cuda\",\n            plevel=30,\n        )\n    if (\n        target.kind.name == \"cuda\"\n        and nvcc.have_tensorcore(target=target)\n        and not attrs[\"transpose_a\"]\n        and attrs[\"transpose_b\"]\n    ):\n        x, y = inputs\n        _, M, K = get_const_tuple(x.shape)\n        _, N, K = get_const_tuple(y.shape)\n        if (\n            x.dtype in [\"float16\", \"int8\", \"uint8\"]\n            and (\n                (M % 8 == 0 and K % 16 == 0 and N % 32 == 0)\n                or (M % 16 == 0 and K % 16 == 0 and N % 16 == 0)\n                or (M % 32 == 0 and K % 16 == 0 and N % 8 == 0)\n            )\n        ) or (x.dtype in [\"int4\", \"uint4\"] and K % 32 == 0 and M % 8 == 0 and N % 8 == 0):\n            strategy.add_implementation(\n                wrap_compute_batch_matmul(topi.cuda.batch_matmul_tensorcore, need_out_dtype=True),\n                wrap_topi_schedule(topi.cuda.schedule_batch_matmul_tensorcore),\n                name=\"batch_matmul_tensorcore.cuda\",\n                plevel=20,\n            )\n\n    return strategy\n\n\n@sparse_dense_strategy.register([\"cuda\", \"gpu\"])\ndef sparse_dense_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"sparse dense cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_dense(topi.cuda.sparse_dense),\n        wrap_topi_schedule(topi.cuda.schedule_sparse_dense),\n        name=\"sparse_dense.cuda\",\n        plevel=10,\n    )\n    return strategy\n\n\n@sparse_reshape_strategy.register([\"cuda\", \"gpu\"])\ndef sparse_reshape_strategy_cuda(attrs, inputs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_reshape(topi.cuda.sparse_reshape),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"sparse_reshape.cuda\",\n    )\n    return strategy\n\n\n@sparse_dense_padded_strategy.register([\"cuda\", \"gpu\", \"rocm\"])\ndef sparse_dense_padded_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"sparse dense cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_dense(topi.cuda.sparse_dense_padded),\n        wrap_topi_schedule(topi.cuda.schedule_sparse_dense_padded),\n        name=\"sparse_dense_padded.cuda\",\n        plevel=10,\n    )\n    return strategy\n\n\n@scatter_strategy.register([\"cuda\", \"gpu\"])\ndef scatter_cuda(attrs, inputs, out_type, target):\n    \"\"\"scatter cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter(topi.cuda.scatter),\n        wrap_topi_schedule(topi.cuda.schedule_scatter),\n        name=\"scatter.cuda\",\n        plevel=10,\n    )\n\n    rank = len(inputs[0].shape)\n\n    with SpecializedCondition(rank == 1):\n        if can_use_thrust(target, \"tvm.contrib.thrust.stable_sort_by_key\"):\n            strategy.add_implementation(\n                wrap_compute_scatter(topi.cuda.scatter_via_sort),\n                wrap_topi_schedule(topi.cuda.schedule_scatter_via_sort),\n                name=\"scatter_via_sort.cuda\",\n                plevel=9,  # use the sequential version by default\n            )\n    return strategy\n\n\n@scatter_add_strategy.register([\"cuda\", \"gpu\"])\ndef scatter_add_cuda(attrs, inputs, out_type, target):\n    \"\"\"scatter_add cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter(topi.cuda.scatter_add),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"scatter_add.cuda\",\n        plevel=10,\n    )\n    return strategy\n\n\n@scatter_nd_strategy.register([\"cuda\", \"gpu\"])\ndef scatter_nd_cuda(attrs, inputs, out_type, target):\n    \"\"\"scatter_nd cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter_nd(topi.cuda.scatter_nd),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"scatter_nd.cuda\",\n        plevel=10,\n    )\n    return strategy\n\n\n@sort_strategy.register([\"cuda\", \"gpu\"])\ndef sort_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"sort cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sort(topi.cuda.sort),\n        wrap_topi_schedule(topi.cuda.schedule_sort),\n        name=\"sort.cuda\",\n    )\n    if can_use_thrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_sort(topi.cuda.sort_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_sort),\n            name=\"sort_thrust.cuda\",\n            plevel=15,\n        )\n    return strategy\n\n\n@argsort_strategy.register([\"cuda\", \"gpu\"])\ndef argsort_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"argsort cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_argsort(topi.cuda.argsort),\n        wrap_topi_schedule(topi.cuda.schedule_argsort),\n        name=\"argsort.cuda\",\n    )\n    if can_use_thrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_argsort(topi.cuda.argsort_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_argsort),\n            name=\"argsort_thrust.cuda\",\n            plevel=15,\n        )\n    return strategy\n\n\n@topk_strategy.register([\"cuda\", \"gpu\"])\ndef topk_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"topk cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_topk(topi.cuda.topk),\n        wrap_topi_schedule(topi.cuda.schedule_topk),\n        name=\"topk.cuda\",\n    )\n    if can_use_thrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_topk(topi.cuda.topk_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_topk),\n            name=\"topk_thrust.cuda\",\n            plevel=15,\n        )\n    return strategy\n\n\n@searchsorted_strategy.register([\"cuda\", \"gpu\"])\ndef searchsorted_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"searchsorted cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_searchsorted(topi.cuda.searchsorted),\n        wrap_topi_schedule(topi.cuda.schedule_extern),\n        name=\"searchsorted.cuda\",\n    )\n    return strategy\n\n\n@multibox_prior_strategy.register([\"cuda\", \"gpu\"])\ndef multibox_prior_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"multibox_prior cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_multibox_prior(topi.cuda.multibox_prior),\n        wrap_topi_schedule(topi.cuda.schedule_multibox_prior),\n        name=\"multibox_prior.cuda\",\n    )\n    return strategy\n\n\n@multibox_transform_loc_strategy.register([\"cuda\", \"gpu\"])\ndef multibox_transform_loc_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"multibox_transform_loc cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_multibox_transform_loc(topi.cuda.multibox_transform_loc),\n        wrap_topi_schedule(topi.cuda.schedule_multibox_transform_loc),\n        name=\"multibox_transform_loc.cuda\",\n    )\n    return strategy\n\n\n@get_valid_counts_strategy.register([\"cuda\", \"gpu\"])\ndef get_valid_counts_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"get_valid_counts cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_get_valid_counts(topi.cuda.get_valid_counts),\n        wrap_topi_schedule(topi.cuda.schedule_get_valid_counts),\n        name=\"get_valid_counts.cuda\",\n    )\n    return strategy\n\n\n@nms_strategy.register([\"cuda\", \"gpu\"])\ndef nms_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"nms cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_nms(topi.cuda.non_max_suppression),\n        wrap_topi_schedule(topi.cuda.schedule_nms),\n        name=\"nms.cuda\",\n    )\n    return strategy\n\n\n@all_class_nms_strategy.register([\"cuda\", \"gpu\"])\ndef all_class_nms_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"all class nms cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_all_class_nms(topi.cuda.all_class_non_max_suppression),\n        wrap_topi_schedule(topi.cuda.schedule_nms),\n        name=\"all_class_nms.cuda\",\n    )\n    return strategy\n\n\n@roi_align_strategy.register([\"cuda\", \"gpu\"])\ndef roi_align_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"roi_align cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.layout\n\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.vision.rcnn.roi_align_nchw),\n            wrap_topi_schedule(topi.cuda.schedule_roi_align),\n            name=\"roi_align_nchw.cuda\",\n        )\n    else:\n        assert layout == \"NHWC\", \"layout must be NCHW or NHWC.\"\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.vision.rcnn.roi_align_nhwc),\n            wrap_topi_schedule(topi.cuda.schedule_roi_align),\n            name=\"roi_align_nhwc.cuda\",\n        )\n    return strategy\n\n\n@schedule_roi_pool.register([\"cuda\", \"gpu\"])\ndef schedule_roi_pool_cuda(attrs, outs, target):\n    \"\"\"schedule roi_pool for cuda\"\"\"\n    with target:\n        return topi.cuda.schedule_roi_pool(outs)\n\n\n@proposal_strategy.register([\"cuda\", \"gpu\"])\ndef proposal_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"proposal cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_proposal(topi.cuda.proposal),\n        wrap_topi_schedule(topi.cuda.schedule_proposal),\n        name=\"proposal.cuda\",\n    )\n    return strategy\n\n\n@correlation_strategy.register([\"cuda\", \"gpu\"])\ndef correlation_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"correlation cuda strategy\"\"\"\n    layout = attrs.layout\n    assert layout == \"NCHW\", \"Only support NCHW layout\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_correlation(topi.cuda.correlation_nchw),\n        wrap_topi_schedule(topi.cuda.schedule_correlation_nchw),\n        name=\"correlation.cuda\",\n    )\n    return strategy\n\n\n@argwhere_strategy.register([\"cuda\", \"gpu\"])\ndef argwhere_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"argwhere cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_argwhere(topi.cuda.argwhere),\n        wrap_topi_schedule(topi.cuda.schedule_argwhere),\n        name=\"argwhere.cuda\",\n    )\n    return strategy\n\n\n@cumsum_strategy.register([\"cuda\", \"gpu\"])\ndef cumsum_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"cumsum cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scanop(topi.cuda.cumsum),\n        wrap_topi_schedule(topi.cuda.schedule_scan),\n        name=\"cumsum.cuda\",\n    )\n    return strategy\n\n\n@cumprod_strategy.register([\"cuda\", \"gpu\"])\ndef cumprod_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"cumprod cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scanop(topi.cuda.cumprod),\n        wrap_topi_schedule(topi.cuda.schedule_scan),\n        name=\"cumprod.cuda\",\n    )\n    return strategy\n\n\n@unique_strategy.register([\"cuda\", \"gpu\"])\ndef unique_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"unique cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_unique(topi.cuda.unique),\n        wrap_topi_schedule(topi.cuda.schedule_scan),\n        name=\"unique.cuda\",\n    )\n    return strategy\n\n\n@schedule_transpose.register([\"cuda\", \"gpu\", \"rocm\"])\ndef schedule_transpose_cuda(attrs, outs, target):\n    \"\"\"\n    Transpose cuda strategy\n    Dispatches to and optimized schedule if the transpose is standalone (not fused).\n    \"\"\"\n    warp_size = int(Target.current(allow_none=False).thread_warp_size)\n    if (\n        isinstance(outs[0].op.input_tensors[0].op, te.PlaceholderOp)\n        and len(outs[0].shape) == 2\n        and (attrs.axes is None or (len(attrs.axes) == 2 and attrs.axes == [1, 0]))\n        and isinstance(outs[0].shape[0], (int, IntImm))\n        and outs[0].shape[0] >= warp_size\n        and isinstance(outs[0].shape[1], (int, IntImm))\n        and outs[0].shape[1] >= warp_size\n    ):\n        return topi.cuda.schedule_transpose(outs)\n    return schedule_injective(attrs, outs, target)\n\n\n@invert_permutation_strategy.register([\"cuda\", \"gpu\"])\ndef invert_permutation_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"invert_permutation cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_invert_permutation(topi.cuda.invert_permutation),\n        wrap_topi_schedule(topi.cuda.vision._default_schedule),\n        name=\"invert_permutation.cuda\",\n    )\n    return strategy\n\n\n@einsum_strategy.register([\"cuda\", \"gpu\"])\ndef einsum_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"einsum cuda strategy\"\"\"\n    strategy = _op.OpStrategy()\n    # TODO: Add cuda-specific op implementation for einsum\n    strategy.add_implementation(\n        wrap_compute_einsum(topi.einsum),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"einsum.cuda\",\n    )\n    return strategy\n\n\n@stft_strategy.register([\"cuda\", \"gpu\"])\ndef stft_strategy_cuda(attrs, inputs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_stft(topi.cuda.stft),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"stft.cuda\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of generic operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument\nimport logging\nimport re\n\nfrom tvm import _ffi, ir, te, topi\nfrom tvm.target import generic_func, override_native_generic_func\nfrom tvm.topi.utils import (\n    get_const_float,\n    get_const_int,\n    get_const_tuple,\n    get_float_tuple,\n)\n\nfrom .. import op as _op\n\nlogger = logging.getLogger(\"strategy\")\n\n\ndef naive_schedule(_, outs, target):\n    \"\"\"Return the naive default schedule.\n    This function acts as a placeholder for op implementations that uses auto-scheduler.\n    Implemenations using this function should only be used along with auto-scheduler.\n    \"\"\"\n    if \"gpu\" in target.keys:\n        # For GPU, we at least need thread binding to make a valid schedule.\n        # So the naive schedule cannot be compiled.\n        logger.debug(\n            \"Cannot compile for GPU targets if no tuned schedule is found. \"\n            \"Please see the warning messages above for more information about the failed workloads.\"\n        )\n    return te.create_schedule(outs[-1].op)\n\n\ndef wrap_topi_schedule(topi_schedule):\n    \"\"\"Wrap TOPI schedule which doesn't use attrs\"\"\"\n\n    def wrapper(attrs, outs, target):\n        with target:\n            return topi_schedule(outs)\n\n    return wrapper\n\n\ndef wrap_topi_compute(topi_compute):\n    \"\"\"Wrap TOPI compute which doesn't use attrs\"\"\"\n\n    def wrapper(attrs, inputs, out_type):\n        return [topi_compute(*inputs)]\n\n    return wrapper\n\n\ndef get_conv2d_in_channels(data_shape, data_layout):\n    \"\"\"Get conv2d input channels\"\"\"\n    data_shape = get_const_tuple(data_shape)\n    if len(data_shape) == 4:\n        idx = data_layout.find(\"C\")\n        assert idx >= 0, \"Invalid conv2d data layout {}\".format(data_layout)\n        return data_shape[idx]\n    if re.match(r\"NCHW\\d*c\", data_layout):\n        # NCHW[8]c\n        return data_shape[1] * data_shape[4]\n    raise ValueError(\"Unknown conv2d data layout {}\".format(data_layout))\n\n\ndef get_conv2d_out_channels(kernel_shape, kernel_layout):\n    \"\"\"Get conv2d output channels\"\"\"\n    kernel_shape = get_const_tuple(kernel_shape)\n    if len(kernel_shape) == 4:\n        idx = kernel_layout.find(\"O\")\n        assert idx >= 0, \"Invalid conv2d kernel layout {}\".format(kernel_layout)\n        return kernel_shape[idx]\n    if re.match(r\"OIHW\\d*i\\d*o\", kernel_layout):\n        return kernel_shape[0] * kernel_shape[5]\n    if re.match(r\"OIHW\\d*o\", kernel_layout):\n        return kernel_shape[0] * kernel_shape[4]\n    raise ValueError(\"Unknown conv2d kernel layout {}\".format(kernel_layout))\n\n\ndef is_depthwise_conv2d(data_shape, data_layout, kernel_shape, kernel_layout, groups):\n    ic = get_conv2d_in_channels(data_shape, data_layout)\n    oc = get_conv2d_out_channels(kernel_shape, kernel_layout)\n    return ic == oc == groups\n\n\n@generic_func\ndef schedule_injective(attrs, outs, target):\n    \"\"\"Schedule injective ops\"\"\"\n    with target:\n        return topi.generic.schedule_injective(outs)\n\n\n@generic_func\ndef schedule_reduce(attrs, outs, target):\n    \"\"\"Schedule reduction ops\"\"\"\n    with target:\n        return topi.generic.schedule_reduce(outs)\n\n\n_op._schedule_injective = schedule_injective\n_op._schedule_reduce = schedule_reduce\n\n# concatenate\n@generic_func\ndef schedule_concatenate(attrs, outs, target):\n    \"\"\"Schedule concatenate op\"\"\"\n    with target:\n        return topi.generic.schedule_injective(outs)\n\n\n# pool\n@generic_func\ndef schedule_pool(attrs, outs, target):\n    \"\"\"Schedule pooling ops\"\"\"\n    with target:\n        return topi.generic.schedule_pool(outs, attrs.layout)\n\n\n# pool_grad\n@generic_func\ndef schedule_pool_grad(attrs, outs, target):\n    \"\"\"Schedule pooling gradient ops\"\"\"\n    with target:\n        return topi.generic.schedule_pool_grad(outs)\n\n\n# adaptive pool\n@generic_func\ndef schedule_adaptive_pool(attrs, outs, target):\n    \"\"\"Schedule adaptive pooling ops\"\"\"\n    with target:\n        return topi.generic.schedule_adaptive_pool(outs)\n\n\n# softmax\ndef wrap_compute_softmax(topi_compute):\n    \"\"\"Wrap softmax topi compute\"\"\"\n\n    def _compute_softmax(attrs, inputs, out_type):\n        axis = attrs.get_int(\"axis\")\n        return [topi_compute(inputs[0], axis)]\n\n    return _compute_softmax\n\n\n@override_native_generic_func(\"softmax_strategy\")\ndef softmax_strategy(attrs, inputs, out_type, target):\n    \"\"\"softmax generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.generic.schedule_softmax),\n        name=\"softmax.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"fast_softmax_strategy\")\ndef fast_softmax_strategy(attrs, inputs, out_type, target):\n    \"\"\"fast softmax generic strategy\"\"\"\n    # NOTE: This op does not have an optimized manual schedule,\n    # so it should only be used together with auto-scheduler.\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.fast_softmax),\n        wrap_topi_schedule(topi.generic.schedule_fast_softmax),\n        name=\"fast_softmax.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"log_softmax_strategy\")\ndef log_softmax_strategy(attrs, inputs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.log_softmax),\n        wrap_topi_schedule(topi.generic.schedule_softmax),\n        name=\"log_softmax.generic\",\n    )\n    return strategy\n\n\n# lrn\n@generic_func\ndef schedule_lrn(attrs, outs, target):\n    \"\"\"Schedule LRN op\"\"\"\n    with target:\n        return topi.generic.schedule_lrn(outs)\n\n\n# pad\n@generic_func\ndef schedule_pad(attrs, outs, target):\n    \"\"\"Schedule PAD op\"\"\"\n    with target:\n        return schedule_injective(attrs, outs, target)\n\n\n# bitpack\n@generic_func\ndef schedule_bitpack(attrs, outs, target):\n    \"\"\"Schedule bitpack\"\"\"\n    with target:\n        return topi.generic.schedule_bitpack(outs)\n\n\nget_auto_scheduler_rewritten_layout = _ffi.get_global_func(\n    \"relay.attrs.get_auto_scheduler_rewritten_layout\"\n)\nget_meta_schedule_original_shape = _ffi.get_global_func(\n    \"relay.attrs.get_meta_schedule_original_shape\"\n)\n\n# conv2d\ndef wrap_compute_conv2d(\n    topi_compute,\n    *,\n    need_data_layout=False,\n    need_kernel_layout=False,\n    need_out_layout=False,\n    has_groups=False,\n    need_auto_scheduler_layout=False,\n    need_meta_schedule_layout=False,\n):\n    \"\"\"Wrap conv2d topi compute\"\"\"\n\n    def _compute_conv2d(attrs, inputs, out_type):\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        dilation = get_const_tuple(attrs.dilation)\n        data_layout = attrs.get_str(\"data_layout\")\n        kernel_layout = attrs.get_str(\"kernel_layout\")\n        out_layout = attrs.get_str(\"out_layout\")\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        args = [inputs[0], inputs[1], strides, padding, dilation]\n        if has_groups:\n            args.append(attrs.groups)\n        if need_data_layout:\n            args.append(data_layout)\n        if need_kernel_layout:\n            args.append(kernel_layout)\n        if need_out_layout:\n            args.append(out_layout)\n        args.append(out_dtype)\n        if need_auto_scheduler_layout:\n            args.append(get_auto_scheduler_rewritten_layout(attrs))\n        elif need_meta_schedule_layout:\n            args.append(\"\")\n            args.append(get_meta_schedule_original_shape(attrs))\n        return [topi_compute(*args)]\n\n    return _compute_conv2d\n\n\n@override_native_generic_func(\"conv2d_strategy\")\ndef conv2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv2d generic strategy\"\"\"\n    logger.warning(\"conv2d is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    (dilation_h, dilation_w) = dilation\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nchw),\n                wrap_topi_schedule(topi.generic.schedule_conv2d_nchw),\n                name=\"conv2d_nchw.generic\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nhwc),\n                wrap_topi_schedule(topi.generic.schedule_conv2d_nhwc),\n                name=\"conv2d_nhwc.generic\",\n            )\n        elif layout == \"HWCN\":\n            assert kernel_layout == \"HWIO\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_hwcn),\n                wrap_topi_schedule(topi.generic.schedule_conv2d_hwcn),\n                name=\"conv2d_hwcn.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {}\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.generic\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_conv2d_nhwc.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.group_conv2d_nchw, has_groups=True),\n                wrap_topi_schedule(topi.generic.schedule_group_conv2d_nchw),\n                name=\"group_conv2d_nchw.generic\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.group_conv2d_nhwc, has_groups=True),\n                wrap_topi_schedule(topi.generic.schedule_group_conv2d_nhwc),\n                name=\"group_conv2d_nhwc.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported group_conv2d layout {}\".format(layout))\n    return strategy\n\n\n# conv2d_NCHWc\n@override_native_generic_func(\"conv2d_NCHWc_strategy\")\ndef conv2d_NCHWc_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc generic strategy\"\"\"\n    logger.warning(\"conv2d_NCHWc is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    if inputs[0].dtype == \"int8\" or inputs[0].dtype == \"uint8\":\n        strategy.add_implementation(\n            wrap_compute_conv2d(\n                topi.nn.conv2d_NCHWc_int8, need_data_layout=True, need_out_layout=True\n            ),\n            wrap_topi_schedule(topi.generic.schedule_conv2d_NCHWc_int8),\n            name=\"conv2d_NCHWc_int8.generic\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.nn.conv2d_NCHWc, need_data_layout=True, need_out_layout=True),\n            wrap_topi_schedule(topi.generic.schedule_conv2d_NCHWc),\n            name=\"conv2d_NCHWc.generic\",\n        )\n    return strategy\n\n\n# depthwise_conv2d_NCHWc\n@override_native_generic_func(\"depthwise_conv2d_NCHWc_strategy\")\ndef depthwise_conv2d_NCHWc_strategy(attrs, inputs, out_type, target):\n    \"\"\"depthwise_conv2d generic strategy\"\"\"\n    logger.warning(\"depthwise_conv2d_NCHWc is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(\n            topi.nn.depthwise_conv2d_NCHWc, need_data_layout=True, need_out_layout=True\n        ),\n        wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_NCHWc),\n        name=\"depthwise_conv2d_NCHWc.generic\",\n    )\n    return strategy\n\n\n# conv2d_winograd_without_weight_transform\n@override_native_generic_func(\"conv2d_winograd_without_weight_transform_strategy\")\ndef conv2d_winograd_without_weight_transform_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform generic strategy\"\"\"\n    raise ValueError(\"No generic implemenation for conv2d_winograd_without_weight_transform\")\n\n\n# conv2d_gemm_without_weight_transform\n@override_native_generic_func(\"conv2d_gemm_without_weight_transform_strategy\")\ndef conv2d_gemm_without_weight_transform_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv2d_gemm_without_weight_transform generic strategy\"\"\"\n    raise ValueError(\"No generic implemenation for conv2d_gemm_without_weight_transform\")\n\n\n# conv2d_winograd_weight_transform\n@generic_func\ndef schedule_conv2d_winograd_weight_transform(attrs, outs, target):\n    \"\"\"Schedule conv2d_winograd_weight_transform\"\"\"\n    with target:\n        return topi.generic.schedule_conv2d_winograd_weight_transform(outs)\n\n\n# conv2d_winograd_nnpack_weight_transform\n@generic_func\ndef schedule_conv2d_winograd_nnpack_weight_transform(attrs, outs, target):\n    \"\"\"Schedule conv2d_winograd_nnpack_weight_transform\"\"\"\n    with target:\n        return topi.generic.schedule_conv2d_winograd_nnpack_weight_transform(outs)\n\n\n# conv2d_gemm_weight_transform\n@generic_func\ndef schedule_conv2d_gemm_weight_transform(attrs, outs, target):\n    \"\"\"Schedule conv2d_gemm_weight_transform\"\"\"\n    with target:\n        return topi.generic.schedule_conv2d_gemm_weight_transform(outs)\n\n\n# deformable_conv2d\ndef wrap_compute_deformable_conv2d(topi_compute):\n    \"\"\"wrap deformable_conv2d topi compute\"\"\"\n\n    def _compute_deformable_conv2d(attrs, inputs, out_dtype):\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        dilation = get_const_tuple(attrs.dilation)\n        deformable_groups = attrs.deformable_groups\n        groups = attrs.groups\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        out = topi_compute(\n            inputs[0],\n            inputs[1],\n            inputs[2],\n            strides,\n            padding,\n            dilation,\n            deformable_groups,\n            groups,\n            out_dtype,\n        )\n        return [out]\n\n    return _compute_deformable_conv2d\n\n\n@override_native_generic_func(\"deformable_conv2d_strategy\")\ndef deformable_conv2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"deformable_conv2d generic strategy\"\"\"\n    layout = attrs.data_layout\n    strategy = _op.OpStrategy()\n\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_deformable_conv2d(topi.nn.deformable_conv2d_nchw),\n            wrap_topi_schedule(topi.generic.schedule_deformable_conv2d_nchw),\n            name=\"deformable_conv2d_nchw.generic\",\n        )\n    elif layout == \"NHWC\":\n        # This implementation should never be picked by autotvm\n        strategy.add_implementation(\n            wrap_compute_deformable_conv2d(topi.nn.deformable_conv2d_nhwc),\n            naive_schedule,\n            name=\"deformable_conv2d_nhwc.generic\",\n        )\n    else:\n        raise RuntimeError(\"Layout %s is not supported in deformable conv2d\" % layout)\n    return strategy\n\n\n# conv2d_transpose\ndef wrap_compute_conv2d_transpose(topi_compute, has_groups=False, add_layout=False):\n    \"\"\"wrap conv2d_transpose topi compute\"\"\"\n\n    def compute_conv2d_transpose(attrs, inputs, out_dtype):\n        \"\"\"Compute definition of conv2d_transpose\"\"\"\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        output_padding = get_const_tuple(attrs.output_padding)\n        # out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding)\n        args = [inputs[0], inputs[1], strides, padding, out_dtype, output_padding]\n        if add_layout:\n            args.append(attrs.data_layout)\n        if has_groups:\n            args.append(attrs.groups)\n        out = topi_compute(*args)\n        return [out]\n\n    return compute_conv2d_transpose\n\n\n@override_native_generic_func(\"conv2d_transpose_strategy\")\ndef conv2d_transpose_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose generic strategy\"\"\"\n    logger.warning(\"conv2d_transpose is not optimized for this platform.\")\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCHW\", \"only support nchw for now\"\n    assert dilation == (1, 1), \"not support dilate now\"\n    strategy = _op.OpStrategy()\n    if groups == 1:\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.nn.conv2d_transpose_nchw),\n            wrap_topi_schedule(topi.generic.schedule_conv2d_transpose_nchw),\n            name=\"conv2d_transpose_nchw.generic\",\n        )\n    else:  # group_conv2d_transpose\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.nn.group_conv2d_transpose_nchw, has_groups=True),\n            wrap_topi_schedule(topi.generic.schedule_group_conv2d_transpose_nchw),\n            name=\"group_conv2d_transpose_nchw.generic\",\n        )\n    return strategy\n\n\n# conv3d_transpose\ndef wrap_compute_conv3d_transpose(topi_compute):\n    \"\"\"wrap conv3d_transpose topi compute\"\"\"\n\n    def compute_conv3d_transpose(attrs, inputs, out_dtype):\n        \"\"\"Compute definition of conv3d_transpose\"\"\"\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        output_padding = get_const_tuple(attrs.output_padding)\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding)\n        return [out]\n\n    return compute_conv3d_transpose\n\n\n@override_native_generic_func(\"conv3d_transpose_strategy\")\ndef conv3d_transpose_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv3d_transpose generic strategy\"\"\"\n    logger.warning(\"conv3d_transpose is not optimized for this platform.\")\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCDHW\", \"only support ncdhw for now\"\n    assert dilation == (1, 1, 1), \"not support dilate now\"\n    assert groups == 1, \"only support groups == 1 for now\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv3d_transpose(topi.nn.conv3d_transpose_ncdhw),\n        wrap_topi_schedule(topi.generic.schedule_conv3d_transpose_ncdhw),\n        name=\"conv3d_transpose_ncdhw.generic\",\n    )\n    return strategy\n\n\n# conv3d\ndef wrap_compute_conv3d(\n    topi_compute,\n    need_layout=False,\n    need_auto_scheduler_layout=False,\n    need_meta_schedule_layout=False,\n):\n    \"\"\"wrap conv3d topi compute\"\"\"\n\n    def _compute_conv3d(attrs, inputs, out_type):\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        dilation = get_const_tuple(attrs.dilation)\n        groups = attrs.groups\n        layout = attrs.data_layout\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n\n        (dilation_d, dilation_h, dilation_w) = dilation\n        if dilation_d < 1 or dilation_h < 1 or dilation_w < 1:\n            raise ValueError(\"Dilation should be positive value\")\n\n        args = [inputs[0], inputs[1], strides, padding, dilation, groups]\n        if need_layout:\n            args.append(layout)\n        args.append(out_dtype)\n        if need_auto_scheduler_layout:\n            args.append(get_auto_scheduler_rewritten_layout(attrs))\n        elif need_meta_schedule_layout:\n            args.append(\"\")\n            args.append(get_meta_schedule_original_shape(attrs))\n        return [topi_compute(*args)]\n\n    return _compute_conv3d\n\n\n@override_native_generic_func(\"conv3d_strategy\")\ndef conv3d_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv3d generic strategy\"\"\"\n    logger.warning(\"conv3d is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    if layout == \"NCDHW\":\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.nn.conv3d_ncdhw),\n            wrap_topi_schedule(topi.generic.schedule_conv3d_ncdhw),\n            name=\"conv3d_ncdhw.generic\",\n        )\n    elif layout == \"NDHWC\":\n        strategy.add_implementation(\n            wrap_compute_conv3d(topi.nn.conv3d_ndhwc),\n            wrap_topi_schedule(topi.generic.schedule_conv3d_ndhwc),\n            name=\"conv3d_ndhwc.generic\",\n        )\n    else:\n        raise ValueError(\"Not support this layout {} yet\".format(layout))\n    return strategy\n\n\n# conv3d_winograd_without_weight_transform\n@override_native_generic_func(\"conv3d_winograd_without_weight_transform_strategy\")\ndef conv3d_winograd_without_weight_transform_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv3d_winograd_without_weight_transform generic strategy\"\"\"\n    raise ValueError(\"No generic implemenation for conv3d_winograd_without_weight_transform\")\n\n\n# conv3d_winograd_weight_transform\n@generic_func\ndef schedule_conv3d_winograd_weight_transform(attrs, outs, target):\n    \"\"\"Schedule conv3d_winograd_weight_transform\"\"\"\n    with target:\n        return topi.generic.schedule_conv3d_winograd_weight_transform(outs)\n\n\n# conv1d\ndef wrap_compute_conv1d(topi_compute):\n    \"\"\"wrap conv1d topi compute\"\"\"\n\n    def _compute_conv1d(attrs, inputs, out_type):\n        \"\"\"Compute definition of conv1d\"\"\"\n        strides = get_const_tuple(attrs.strides)\n        padding = get_const_tuple(attrs.padding)\n        dilation = get_const_tuple(attrs.dilation)\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        return [topi_compute(inputs[0], inputs[1], strides, padding, dilation, out_dtype)]\n\n    return _compute_conv1d\n\n\n@override_native_generic_func(\"conv1d_strategy\")\ndef conv1d_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv1d generic strategy\"\"\"\n    logger.warning(\"conv1d is not optimized for this platform.\")\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    if dilation[0] < 1:\n        raise ValueError(\"dilation should be a positive value\")\n    strategy = _op.OpStrategy()\n    if layout == \"NCW\":\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.conv1d_ncw),\n            wrap_topi_schedule(topi.generic.schedule_conv1d_ncw),\n            name=\"conv1d_ncw.generic\",\n        )\n    elif layout == \"NWC\":\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.conv1d_nwc),\n            wrap_topi_schedule(topi.generic.schedule_conv1d_nwc),\n            name=\"conv1d_nwc.generic\",\n        )\n    else:\n        raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    return strategy\n\n\ndef wrap_compute_group_conv1d(topi_compute):\n    \"\"\"wrap conv1d topi compute\"\"\"\n\n    def _compute_group_conv1d(attrs, inputs, out_type):\n        \"\"\"Compute definition of conv1d\"\"\"\n        strides = get_const_tuple(attrs.strides)\n        padding = get_const_tuple(attrs.padding)\n        dilation = get_const_tuple(attrs.dilation)\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        return [\n            topi_compute(inputs[0], inputs[1], strides, padding, dilation, attrs.groups, out_dtype)\n        ]\n\n    return _compute_group_conv1d\n\n\n@override_native_generic_func(\"group_conv1d_strategy\")\ndef group_conv1d_strategy(attrs, inputs, out_type, target):\n    \"\"\"group_conv1d generic strategy\"\"\"\n    logger.warning(\"group_conv1d is not optimized for this platform.\")\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    if dilation[0] < 1:\n        raise ValueError(\"dilation should be a positive value\")\n    strategy = _op.OpStrategy()\n    if layout == \"NCW\":\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.group_conv1d_ncw),\n            wrap_topi_schedule(topi.generic.schedule_group_conv1d_ncw),\n            name=\"group_conv1d_ncw.generic\",\n        )\n    elif layout == \"NWC\":\n        strategy.add_implementation(\n            wrap_compute_conv1d(topi.nn.group_conv1d_nwc),\n            wrap_topi_schedule(topi.generic.schedule_group_conv1d_nwc),\n            name=\"group_conv1d_nwc.generic\",\n        )\n    else:\n        raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    return strategy\n\n\n# conv1d_transpose\ndef wrap_compute_conv1d_transpose(topi_compute):\n    \"\"\"wrap conv1d_transpose topi compute\"\"\"\n\n    def _compute_conv1d_tranpsoe(attrs, inputs, out_type):\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        output_padding = get_const_tuple(attrs.output_padding)\n        out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding)\n        return [out]\n\n    return _compute_conv1d_tranpsoe\n\n\n@override_native_generic_func(\"conv1d_transpose_strategy\")\ndef conv1d_transpose_strategy(attrs, inputs, out_type, target):\n    \"\"\"conv1d_transpose generic strategy\"\"\"\n    logger.warning(\"conv1d_transpose is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCW\", \"conv1d_transpose ncw only supported\"\n    assert dilation == (1,), \"conv1d_transpose dilation is not supported\"\n    assert groups == 1, \"conv1d_transpose groups == 1 only supported\"\n    strategy.add_implementation(\n        wrap_compute_conv1d_transpose(topi.nn.conv1d_transpose_ncw),\n        wrap_topi_schedule(topi.generic.schedule_conv1d_transpose_ncw),\n        name=\"conv1d_transpose_ncw.generic\",\n    )\n    return strategy\n\n\n# dilation2d\ndef wrap_compute_dilation2d(topi_compute, need_data_layout=False):\n    \"\"\"Wrap dilation2d topi compute\"\"\"\n\n    def _compute_dilation2d(attrs, inputs, out_type):\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        dilations = get_const_tuple(attrs.dilations)\n        data_layout = attrs.get_str(\"data_layout\")\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        args = [inputs[0], inputs[1], strides, padding, dilations]\n        if need_data_layout:\n            args.append(data_layout)\n        args.append(out_dtype)\n        return [topi_compute(*args)]\n\n    return _compute_dilation2d\n\n\n@override_native_generic_func(\"dilation2d_strategy\")\ndef dilation2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"dilation2d_strategy generic strategy\"\"\"\n    logger.warning(\"dilation2d_strategy is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    dilations = get_const_tuple(attrs.dilations)\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n\n    assert layout in [\"NCHW\", \"NHWC\"]\n    (dilation_h, dilation_w) = dilations\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if layout == \"NCHW\":\n        assert kernel_layout == \"IHW\"\n        strategy.add_implementation(\n            wrap_compute_dilation2d(topi.image.dilation2d_nchw),\n            wrap_topi_schedule(topi.generic.schedule_dilation2d_nchw),\n            name=\"dilation2d_nchw.generic\",\n        )\n    elif layout == \"NHWC\":\n        assert kernel_layout == \"HWI\"\n        strategy.add_implementation(\n            wrap_compute_dilation2d(topi.image.dilation2d_nhwc),\n            wrap_topi_schedule(topi.generic.schedule_dilation2d_nhwc),\n            name=\"dilation2d_nhwc.generic\",\n        )\n    else:\n        raise RuntimeError(\"Unsupported dilation2d layout {}\".format(layout))\n    return strategy\n\n\ndef copy_if_identical(tensor_a, tensor_b):\n    \"\"\"\n    When two inputs to batch_matul or dense are the same tensor, e.g. batch_matmul(x, x),\n    compilation fails because TE thinks there is only one input tensor x, and doing\n    cache_read(x) on the same tensor twice results in an error.\n    To prevent such errors, we make the second tensor be the copy of the first one\n    when two input tensors are identical.\n    \"\"\"\n    if tensor_a == tensor_b:\n        return te.compute(tensor_a.shape, lambda *ind: tensor_a[ind])\n    return tensor_b\n\n\n# matmul\ndef wrap_compute_matmul(\n    topi_compute,\n    need_auto_scheduler_layout=False,\n    need_meta_schedule_layout=False,\n):\n    \"\"\"wrap matmul topi compute\"\"\"\n\n    def _compute_matmul(attrs, inputs, out_type):\n        \"\"\"Compute definition of matmul\"\"\"\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype == \"\" else out_dtype\n        args = [\n            inputs[0],\n            inputs[1],\n            None,\n            out_dtype,\n            attrs.transpose_a,\n            attrs.transpose_b,\n        ]\n        if need_auto_scheduler_layout:\n            args.append(get_auto_scheduler_rewritten_layout(attrs))\n        elif need_meta_schedule_layout:\n            args.append(\"\")\n            args.append(get_meta_schedule_original_shape(attrs))\n        args[1] = copy_if_identical(inputs[0], inputs[1])\n        return [topi_compute(*args)]\n\n    return _compute_matmul\n\n\n@override_native_generic_func(\"matmul_strategy\")\ndef matmul_strategy(attrs, inputs, out_type, target):\n    \"\"\"matmul generic strategy\"\"\"\n    logger.warning(\"matmul is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_matmul(topi.nn.matmul),\n        wrap_topi_schedule(topi.generic.schedule_matmul),\n        name=\"matmul.generic\",\n    )\n    return strategy\n\n\n# dense\ndef wrap_compute_dense(\n    topi_compute,\n    need_auto_scheduler_layout=False,\n    need_meta_schedule_layout=False,\n):\n    \"\"\"wrap dense topi compute\"\"\"\n\n    def _compute_dense(attrs, inputs, out_type):\n        \"\"\"Compute definition of dense\"\"\"\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype == \"\" else out_dtype\n        args = [inputs[0], inputs[1], None, out_dtype]\n        if need_auto_scheduler_layout:\n            args.append(get_auto_scheduler_rewritten_layout(attrs))\n        elif need_meta_schedule_layout:\n            args.append(\"\")\n            args.append(get_meta_schedule_original_shape(attrs))\n        args[1] = copy_if_identical(inputs[0], inputs[1])\n        return [topi_compute(*args)]\n\n    return _compute_dense\n\n\n@override_native_generic_func(\"dense_strategy\")\ndef dense_strategy(attrs, inputs, out_type, target):\n    \"\"\"dense generic strategy\"\"\"\n    logger.warning(\"dense is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dense(topi.nn.dense),\n        wrap_topi_schedule(topi.generic.schedule_dense),\n        name=\"dense.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"dense_pack_strategy\")\ndef dense_pack_strategy(attrs, inputs, out_type, target):\n    \"\"\"dense_pack generic strategy\"\"\"\n    logger.warning(\"dense_pack is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dense(topi.nn.dense_pack),\n        wrap_topi_schedule(topi.generic.schedule_dense),\n        name=\"dense_pack.generic\",\n    )\n    return strategy\n\n\n# batch_matmul\ndef wrap_compute_batch_matmul(\n    topi_compute,\n    *,\n    need_auto_scheduler_layout=False,\n    need_meta_schedule_layout=False,\n    need_out_dtype=False,\n):\n    \"\"\"wrap batch_matmul topi compute\"\"\"\n\n    def _compute_batch_matmul(attrs, inputs, out_type):\n        args = [inputs[0], inputs[1], out_type.shape]\n        args.append(out_type.dtype if need_out_dtype else None)\n        args.append(attrs.transpose_a)\n        args.append(attrs.transpose_b)\n        if need_auto_scheduler_layout:\n            args.append(get_auto_scheduler_rewritten_layout(attrs))\n        elif need_meta_schedule_layout:\n            args.append(\"\")\n            args.append(get_meta_schedule_original_shape(attrs))\n        args[1] = copy_if_identical(inputs[0], inputs[1])\n        return [topi_compute(*args)]\n\n    return _compute_batch_matmul\n\n\n@override_native_generic_func(\"batch_matmul_strategy\")\ndef batch_matmul_strategy(attrs, inputs, out_type, target):\n    \"\"\"batch_matmul generic strategy\"\"\"\n    logger.warning(\"batch_matmul is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_batch_matmul(topi.nn.batch_matmul),\n        wrap_topi_schedule(topi.generic.schedule_batch_matmul),\n        name=\"batch_matmul.generic\",\n    )\n    return strategy\n\n\n# batch_norm\ndef wrap_compute_batch_norm(topi_compute):\n    \"\"\"wrap batch_norm topi compute\"\"\"\n\n    def _compute_batch_norm(attrs, inputs, out_type):\n        return topi_compute(*inputs, attrs.axis, attrs.epsilon, attrs.center, attrs.scale)\n\n    return _compute_batch_norm\n\n\n@override_native_generic_func(\"batch_norm_strategy\")\ndef batch_norm_strategy(attrs, inputs, out_type, target):\n    \"\"\"batch_norm generic strategy\"\"\"\n    logger.warning(\"batch_norm is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_batch_norm(topi.nn.batch_norm),\n        wrap_topi_schedule(topi.generic.schedule_batch_norm),\n        name=\"batch_norm.generic\",\n    )\n    return strategy\n\n\n# sparse dense\ndef wrap_compute_sparse_dense(topi_compute):\n    \"\"\"wrap sparse dense topi compute\"\"\"\n\n    def _compute_sparse_dense(attrs, inputs, out_type):\n        return [topi_compute(inputs[0], inputs[1], inputs[2], inputs[3], attrs[\"sparse_lhs\"])]\n\n    return _compute_sparse_dense\n\n\n@override_native_generic_func(\"sparse_dense_strategy\")\ndef sparse_dense_strategy(attrs, inputs, out_type, target):\n    \"\"\"sparse dense generic strategy\"\"\"\n    logger.warning(\"sparse dense is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_dense(topi.nn.sparse_dense),\n        wrap_topi_schedule(topi.generic.schedule_sparse_dense),\n        name=\"sparse_dense.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"sparse_dense_padded_strategy\")\ndef sparse_dense_padded_strategy(attrs, inputs, out_type, target):\n    \"\"\"sparse dense padded generic strategy\"\"\"\n    raise NotImplementedError(\"sparse_dense_padded is only implemented for cuda\")\n\n\n# sparse_add\ndef wrap_compute_sparse_add(topi_compute):\n    \"\"\"wrap sparse add topi compute\"\"\"\n\n    def _compute_sparse_add(attrs, inputs, out_type):\n        return [topi_compute(inputs[0], inputs[1], inputs[2], inputs[3])]\n\n    return _compute_sparse_add\n\n\n@override_native_generic_func(\"sparse_add_strategy\")\ndef sparse_add_strategy(attrs, inputs, out_type, target):\n    \"\"\"sparse add generic strategy\"\"\"\n    logger.warning(\"sparse add is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_add(topi.nn.sparse_add),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"sparse_add.generic\",\n    )\n    return strategy\n\n\n# sparse_transpose\n@generic_func\ndef schedule_sparse_transpose(attrs, outs, target):\n    \"\"\"schedule sparse_transpose\"\"\"\n    with target:\n        return topi.generic.schedule_sparse_transpose(outs)\n\n\n# sparse conv2d\ndef wrap_compute_sparse_conv2d(topi_compute):\n    \"\"\"wrap sparse conv2d topi compute\"\"\"\n\n    def _compute_sparse_conv2d(attrs, inputs, out_type):\n        return [topi_compute(inputs[0], inputs[1], inputs[2], inputs[3], attrs[\"layout\"])]\n\n    return _compute_sparse_conv2d\n\n\n@override_native_generic_func(\"sparse_conv2d_strategy\")\ndef sparse_conv2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"sparse conv2d generic strategy\"\"\"\n    logger.warning(\"sparse conv2d is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_conv2d(topi.nn.sparse_conv2d),\n        wrap_topi_schedule(topi.generic.schedule_sparse_conv2d),\n        name=\"sparse_conv2d.generic\",\n    )\n    return strategy\n\n\n# sort\ndef wrap_compute_sort(topi_compute):\n    \"\"\"Wrap sort topi compute\"\"\"\n\n    def _compute_sort(attrs, inputs, _):\n        axis = get_const_int(attrs.axis)\n        is_ascend = bool(get_const_int(attrs.is_ascend))\n        return [topi_compute(inputs[0], axis=axis, is_ascend=is_ascend)]\n\n    return _compute_sort\n\n\n@override_native_generic_func(\"sort_strategy\")\ndef sort_strategy(attrs, inputs, out_type, target):\n    \"\"\"sort generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sort(topi.sort),\n        wrap_topi_schedule(topi.generic.schedule_sort),\n        name=\"sort.generic\",\n    )\n    return strategy\n\n\n# argsort\ndef wrap_compute_argsort(topi_compute):\n    \"\"\"Wrap argsort topi compute\"\"\"\n\n    def _compute_argsort(attrs, inputs, _):\n        axis = get_const_int(attrs.axis)\n        is_ascend = bool(get_const_int(attrs.is_ascend))\n        dtype = attrs.dtype\n        return [topi_compute(inputs[0], axis=axis, is_ascend=is_ascend, dtype=dtype)]\n\n    return _compute_argsort\n\n\n@override_native_generic_func(\"argsort_strategy\")\ndef argsort_strategy(attrs, inputs, out_type, target):\n    \"\"\"argsort generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_argsort(topi.argsort),\n        wrap_topi_schedule(topi.generic.schedule_argsort),\n        name=\"argsort.generic\",\n    )\n    return strategy\n\n\n# topk\ndef wrap_compute_topk(topi_compute):\n    \"\"\"Wrap topk compute\"\"\"\n\n    def _compute_topk(attrs, inputs, out_type):\n        if attrs.k is not None:\n            k = attrs.k\n        else:\n            k = inputs[1]\n        axis = get_const_int(attrs.axis)\n        ret_type = attrs.ret_type\n        is_ascend = bool(get_const_int(attrs.is_ascend))\n        dtype = attrs.dtype\n        out = topi_compute(inputs[0], k, axis, ret_type, is_ascend, dtype)\n        out = out if isinstance(out, list) else [out]\n        return out\n\n    return _compute_topk\n\n\n@override_native_generic_func(\"topk_strategy\")\ndef topk_strategy(attrs, inputs, out_type, target):\n    \"\"\"topk generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_topk(topi.topk),\n        wrap_topi_schedule(topi.generic.schedule_topk),\n        name=\"topk.generic\",\n    )\n    return strategy\n\n\n# searchsorted\ndef wrap_compute_searchsorted(topi_compute):\n    \"\"\"Wrap searchsorted compute\"\"\"\n\n    def _compute_searchsorted(attrs, inputs, out_type):\n        right = attrs.right\n        dtype = attrs.dtype\n        return [topi_compute(inputs[0], inputs[1], right, dtype)]\n\n    return _compute_searchsorted\n\n\n# searchsorted_strategy\n@override_native_generic_func(\"searchsorted_strategy\")\ndef searchsorted_strategy(attrs, inputs, out_type, target):\n    \"\"\"searchsorted generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_searchsorted(topi.searchsorted),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"searchsorted.generic\",\n    )\n    return strategy\n\n\n# multibox_prior\ndef wrap_compute_multibox_prior(topi_compute):\n    \"\"\"Wrap multibox_prior compute\"\"\"\n\n    def _compute_multibox_prior(attrs, inputs, _):\n        \"\"\"Compute definition of multibox_prior\"\"\"\n        sizes = get_float_tuple(attrs.sizes)\n        ratios = get_float_tuple(attrs.ratios)\n        steps = get_float_tuple(attrs.steps)\n        offsets = get_float_tuple(attrs.offsets)\n        clip = bool(get_const_int(attrs.clip))\n        return [topi_compute(inputs[0], sizes, ratios, steps, offsets, clip)]\n\n    return _compute_multibox_prior\n\n\n@override_native_generic_func(\"multibox_prior_strategy\")\ndef multibox_prior_strategy(attrs, inputs, out_type, target):\n    \"\"\"multibox_prior generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_multibox_prior(topi.vision.ssd.multibox_prior),\n        wrap_topi_schedule(topi.generic.schedule_multibox_prior),\n        name=\"multibox_prior.generic\",\n    )\n    return strategy\n\n\n# multibox_transform_loc\ndef wrap_compute_multibox_transform_loc(topi_compute):\n    \"\"\"Wrap multibox_transform_loc compute\"\"\"\n\n    def _compute_multibox_transform_loc(attrs, inputs, _):\n        \"\"\"Compute definition of multibox_detection\"\"\"\n        clip = bool(get_const_int(attrs.clip))\n        threshold = get_const_float(attrs.threshold)\n        variances = get_float_tuple(attrs.variances)\n        return topi_compute(inputs[0], inputs[1], inputs[2], clip, threshold, variances)\n\n    return _compute_multibox_transform_loc\n\n\n@override_native_generic_func(\"multibox_transform_loc_strategy\")\ndef multibox_transform_loc_strategy(attrs, inputs, out_type, target):\n    \"\"\"schedule multibox_transform_loc\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_multibox_transform_loc(topi.vision.ssd.multibox_transform_loc),\n        wrap_topi_schedule(topi.generic.schedule_multibox_transform_loc),\n        name=\"multibox_transform_loc.generic\",\n    )\n    return strategy\n\n\n# get_valid_counts\ndef wrap_compute_get_valid_counts(topi_compute):\n    \"\"\"wrap get_valid_counts topi compute\"\"\"\n\n    def _compute_get_valid_counts(attrs, inputs, out_type):\n        score_threshold = inputs[1]\n        id_index = get_const_int(attrs.id_index)\n        score_index = get_const_int(attrs.score_index)\n        if attrs.score_threshold is not None:\n            score_threshold = get_const_float(attrs.score_threshold)\n        return topi_compute(inputs[0], score_threshold, id_index, score_index)\n\n    return _compute_get_valid_counts\n\n\n@override_native_generic_func(\"get_valid_counts_strategy\")\ndef get_valid_counts_strategy(attrs, inputs, out_type, target):\n    \"\"\"get_valid_counts generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_get_valid_counts(topi.vision.get_valid_counts),\n        wrap_topi_schedule(topi.generic.schedule_get_valid_counts),\n        name=\"get_valid_counts.generic\",\n    )\n    return strategy\n\n\n# non-maximum suppression\ndef wrap_compute_nms(topi_compute):\n    \"\"\"wrap nms topi compute\"\"\"\n\n    def _compute_nms(attrs, inputs, out_type):\n        max_output_size = inputs[3]\n        iou_threshold = inputs[4]\n        return_indices = bool(get_const_int(attrs.return_indices))\n        force_suppress = bool(get_const_int(attrs.force_suppress))\n        top_k = get_const_int(attrs.top_k)\n        coord_start = get_const_int(attrs.coord_start)\n        score_index = get_const_int(attrs.score_index)\n        id_index = get_const_int(attrs.id_index)\n        invalid_to_bottom = bool(get_const_int(attrs.invalid_to_bottom))\n        if return_indices:\n            return topi_compute(\n                inputs[0],\n                inputs[1],\n                inputs[2],\n                max_output_size,\n                iou_threshold,\n                force_suppress,\n                top_k,\n                coord_start,\n                score_index,\n                id_index,\n                return_indices,\n                invalid_to_bottom,\n            )\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                inputs[2],\n                max_output_size,\n                iou_threshold,\n                force_suppress,\n                top_k,\n                coord_start,\n                score_index,\n                id_index,\n                return_indices,\n                invalid_to_bottom,\n            )\n        ]\n\n    return _compute_nms\n\n\n@override_native_generic_func(\"non_max_suppression_strategy\")\ndef nms_strategy(attrs, inputs, out_type, target):\n    \"\"\"nms generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_nms(topi.vision.non_max_suppression),\n        wrap_topi_schedule(topi.generic.schedule_nms),\n        name=\"nms.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_all_class_nms(topi_compute):\n    \"\"\"wrap all class nms topi compute\"\"\"\n\n    def _compute_nms(attrs, inputs, out_type):\n        max_output_size = inputs[2]\n        iou_threshold = inputs[3]\n        score_threshold = inputs[4]\n        output_format = attrs.output_format\n        return topi_compute(\n            inputs[0],\n            inputs[1],\n            max_output_size,\n            iou_threshold,\n            score_threshold,\n            output_format,\n        )\n\n    return _compute_nms\n\n\n@override_native_generic_func(\"all_class_non_max_suppression_strategy\")\ndef all_class_nms_strategy(attrs, inputs, out_type, target):\n    \"\"\"all class nms generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_all_class_nms(topi.vision.all_class_non_max_suppression),\n        wrap_topi_schedule(topi.generic.schedule_nms),\n        name=\"all_class_nms.generic\",\n    )\n    return strategy\n\n\n# roi_align\ndef wrap_compute_roi_align(topi_compute):\n    \"\"\"wrap roi_align topi compute\"\"\"\n\n    def _compute_roi_align(attrs, inputs, out_type):\n        pooled_size = get_const_tuple(attrs.pooled_size)\n        mode = bytes(attrs.mode, \"utf-8\")\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                pooled_size=pooled_size,\n                spatial_scale=attrs.spatial_scale,\n                sample_ratio=attrs.sample_ratio,\n                mode=mode,\n            )\n        ]\n\n    return _compute_roi_align\n\n\n@override_native_generic_func(\"roi_align_strategy\")\ndef roi_align_strategy(attrs, inputs, out_type, target):\n    \"\"\"roi_align generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.vision.rcnn.roi_align_nchw),\n            wrap_topi_schedule(topi.generic.schedule_roi_align),\n            name=\"roi_align.generic\",\n        )\n    else:\n        assert layout == \"NHWC\", \"layout must be NCHW or NHWC.\"\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.vision.rcnn.roi_align_nhwc),\n            wrap_topi_schedule(topi.generic.schedule_roi_align),\n            name=\"roi_align.generic\",\n        )\n    return strategy\n\n\n# sparse_fill_empty_rows\n@override_native_generic_func(\"sparse_fill_empty_rows_strategy\")\ndef sparse_fill_empty_rows_strategy(attrs, outs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_fill_empty_rows(topi.sparse_fill_empty_rows),\n        wrap_topi_schedule(topi.generic.schedule_sparse_fill_empty_rows),\n        name=\"sparse_fill_empty_rows.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_sparse_fill_empty_rows(topi_compute):\n    \"\"\"Wrap sparse_fill_empty_rows compute\"\"\"\n\n    def _compute_sparse_fill_empty_rows(attrs, inputs, output_type):\n        return topi_compute(\n            inputs[0],\n            inputs[1],\n            inputs[2],\n            inputs[3],\n            output_type.fields[0].shape,\n            output_type.fields[1].shape,\n            output_type.fields[2].shape,\n        )\n\n    return _compute_sparse_fill_empty_rows\n\n\n# sparse_reshape\n@override_native_generic_func(\"sparse_reshape_strategy\")\ndef sparse_reshape_strategy(attrs, outs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_reshape(topi.sparse_reshape),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"sparse_reshape.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_sparse_reshape(topi_compute):\n    \"\"\"Wrap sparse_reshape compute\"\"\"\n\n    def _compute_sparse_reshape(attrs, inputs, output_type):\n        return topi_compute(\n            inputs[0],\n            inputs[1],\n            inputs[2],\n            output_type.fields[0].shape,\n            output_type.fields[1].shape,\n        )\n\n    return _compute_sparse_reshape\n\n\n# stft\n@override_native_generic_func(\"stft_strategy\")\ndef stft_strategy(attrs, outs, out_type, target):\n    \"\"\"stft generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_stft(topi.stft),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"stft.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_stft(topi_compute):\n    \"\"\"Wrap stft compute\"\"\"\n\n    def _compute_stft(attrs, inputs, output_type):\n        return [\n            topi_compute(\n                inputs[0],\n                attrs.n_fft,\n                attrs.hop_length,\n                attrs.win_length,\n                inputs[1],\n                attrs.normalized,\n                attrs.onesided,\n                output_type.shape,\n            )\n        ]\n\n    return _compute_stft\n\n\n# trilu\n@override_native_generic_func(\"trilu_strategy\")\ndef trilu_strategy(attrs, outs, out_type, target):\n    \"\"\"trilu generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_trilu(topi.trilu),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"trilu.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_trilu(topi_compute):\n    \"\"\"Wrap trilu compute\"\"\"\n\n    def _compute_trilu(attrs, inputs, output_type):\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                attrs.upper,\n            )\n        ]\n\n    return _compute_trilu\n\n\n# roi_pool\n@generic_func\ndef schedule_roi_pool(attrs, outs, target):\n    \"\"\"schedule roi_pool\"\"\"\n    with target:\n        return topi.generic.schedule_roi_pool(outs)\n\n\n# proposal\ndef wrap_compute_proposal(topi_compute):\n    \"\"\"wrap proposal topi compute\"\"\"\n\n    def _compute_proposal(attrs, inputs, out_type):\n        scales = get_float_tuple(attrs.scales)\n        ratios = get_float_tuple(attrs.ratios)\n        feature_stride = attrs.feature_stride\n        threshold = attrs.threshold\n        rpn_pre_nms_top_n = attrs.rpn_pre_nms_top_n\n        rpn_post_nms_top_n = attrs.rpn_post_nms_top_n\n        rpn_min_size = attrs.rpn_min_size\n        iou_loss = bool(get_const_int(attrs.iou_loss))\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                inputs[2],\n                scales,\n                ratios,\n                feature_stride,\n                threshold,\n                rpn_pre_nms_top_n,\n                rpn_post_nms_top_n,\n                rpn_min_size,\n                iou_loss,\n            )\n        ]\n\n    return _compute_proposal\n\n\n@override_native_generic_func(\"proposal_strategy\")\ndef proposal_strategy(attrs, inputs, out_type, target):\n    \"\"\"proposal generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_proposal(topi.vision.rcnn.proposal),\n        wrap_topi_schedule(topi.generic.schedule_proposal),\n        name=\"proposal.generic\",\n    )\n    return strategy\n\n\n# scatter\n@override_native_generic_func(\"scatter_strategy\")\ndef scatter_strategy(attrs, outs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter(topi.scatter),\n        wrap_topi_schedule(topi.generic.schedule_scatter),\n        name=\"scatter.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_scatter(topi_compute):\n    \"\"\"Wrap scatter topi compute\"\"\"\n\n    def _compute_scatter(attrs, inputs, _):\n        return [topi_compute(inputs[0], inputs[1], inputs[2], attrs.axis)]\n\n    return _compute_scatter\n\n\n@override_native_generic_func(\"scatter_add_strategy\")\ndef scatter_add_strategy(attrs, outs, out_type, target):\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter(topi.scatter_add),\n        wrap_topi_schedule(topi.generic.schedule_scatter),\n        name=\"scatter_add.generic\",\n    )\n    return strategy\n\n\n# scatter_nd\n@override_native_generic_func(\"scatter_nd_strategy\")\ndef scatter_nd_strategy(attrs, inputs, out_type, target):\n    \"\"\"scatter_nd generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter_nd(topi.scatter_nd),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"scatter_nd.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_scatter_nd(topi_compute):\n    \"\"\"Wrap scatter_nd topi compute\"\"\"\n\n    def _compute_scatter_nd(attrs, inputs, _):\n        return [topi_compute(inputs[0], inputs[1], inputs[2], attrs.mode)]\n\n    return _compute_scatter_nd\n\n\n# bitserial_conv2d\ndef wrap_compute_bitserial_conv2d(topi_compute):\n    \"\"\"wrap bitserial_conv2d topi compute\"\"\"\n\n    def compute_bitserial_conv2d(attrs, inputs, out_dtype):\n        \"\"\"Compute definition for bitserial conv2d.\"\"\"\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        activation_bits = attrs.activation_bits\n        weight_bits = attrs.weight_bits\n        pack_dtype = attrs.pack_dtype\n        out_dtype = attrs.out_dtype\n        unipolar = attrs.unipolar\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                strides,\n                padding,\n                activation_bits,\n                weight_bits,\n                pack_dtype,\n                out_dtype,\n                unipolar,\n            )\n        ]\n\n    return compute_bitserial_conv2d\n\n\n@override_native_generic_func(\"bitserial_conv2d_strategy\")\ndef bitserial_conv2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"bitserial_conv2d generic strategy\"\"\"\n    logger.warning(\"bitserial_conv2d is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nchw),\n            wrap_topi_schedule(topi.generic.schedule_bitserial_conv2d_nchw),\n            name=\"bitserial_conv2d_nchw.generic\",\n        )\n    elif layout == \"NHWC\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nhwc),\n            wrap_topi_schedule(topi.generic.schedule_bitserial_conv2d_nhwc),\n            name=\"bitserial_conv2d_nhwc.generic\",\n        )\n    else:\n        raise ValueError(\"Data layout {} not supported.\".format(layout))\n    return strategy\n\n\n# bitserial_dense\ndef wrap_compute_bitserial_dense(topi_compute):\n    \"\"\"wrap bitserial_dense topi compute\"\"\"\n\n    def compute_bitserial_dense(attrs, inputs, out_type):\n        \"\"\"Compute definition of bitserial dense\"\"\"\n        data_bits = attrs.data_bits\n        weight_bits = attrs.weight_bits\n        pack_dtype = attrs.pack_dtype\n        out_dtype = attrs.out_dtype\n        out_dtype = inputs[0].dtype if out_dtype == \"\" else out_dtype\n        unipolar = attrs.unipolar\n        return [\n            topi_compute(\n                inputs[0], inputs[1], data_bits, weight_bits, pack_dtype, out_dtype, unipolar\n            )\n        ]\n\n    return compute_bitserial_dense\n\n\n@override_native_generic_func(\"bitserial_dense_strategy\")\ndef bitserial_dense_strategy(attrs, inputs, out_type, target):\n    \"\"\"bitserial_dense generic strategy\"\"\"\n    logger.warning(\"bitserial_dense is not optimized for this platform.\")\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_bitserial_dense(topi.nn.bitserial_dense),\n        wrap_topi_schedule(topi.generic.schedule_bitserial_dense),\n        name=\"bitserial_dense.generic\",\n    )\n    return strategy\n\n\n# correlation\ndef wrap_compute_correlation(topi_compute):\n    \"\"\"wrap correlation topi compute\"\"\"\n\n    def _compute_correlation(attrs, inputs, out_type):\n        kernel_size = attrs.kernel_size\n        max_displacement = attrs.max_displacement\n        stride1 = attrs.stride1\n        stride2 = attrs.stride2\n        padding = get_const_tuple(attrs.padding)\n        is_multiply = attrs.is_multiply\n        return [\n            topi_compute(\n                inputs[0],\n                inputs[1],\n                kernel_size,\n                max_displacement,\n                stride1,\n                stride2,\n                padding,\n                is_multiply,\n            )\n        ]\n\n    return _compute_correlation\n\n\n@override_native_generic_func(\"correlation_strategy\")\ndef correlation_strategy(attrs, inputs, out_type, target):\n    \"\"\"correlation generic strategy\"\"\"\n    logger.warning(\"correlation is not optimized for this platform.\")\n    layout = attrs.layout\n    assert layout == \"NCHW\", \"Only support NCHW layout\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_correlation(topi.nn.correlation_nchw),\n        wrap_topi_schedule(topi.generic.schedule_correlation_nchw),\n        name=\"correlation.generic\",\n    )\n    return strategy\n\n\n# argwhere\ndef wrap_compute_argwhere(topi_compute):\n    \"\"\"wrap argwhere topi compute\"\"\"\n\n    def _compute_argwhere(attrs, inputs, out_type):\n        output_shape = []\n        for s in out_type.shape:\n            if hasattr(s, \"value\"):\n                output_shape.append(s)\n            else:\n                output_shape.append(te.var(\"any_dim\", \"int32\"))\n        new_output_type = ir.TensorType(output_shape, \"int32\")\n        return [topi_compute(new_output_type, inputs[0])]\n\n    return _compute_argwhere\n\n\n@override_native_generic_func(\"argwhere_strategy\")\ndef argwhere_strategy(attrs, inputs, out_type, target):\n    \"\"\"argwhere generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_argwhere(topi.argwhere),\n        wrap_topi_schedule(topi.generic.schedule_argwhere),\n        name=\"argwhere.generic\",\n    )\n    return strategy\n\n\n# threefry_generate\ndef wrap_compute_threefry_generate(topi_compute):\n    \"\"\"Wrap threefry_generate topi compute\"\"\"\n\n    def _compute_threefry_generate(attrs, inputs, _):\n        return topi_compute(inputs[0], attrs.out_shape)\n\n    return _compute_threefry_generate\n\n\n@override_native_generic_func(\"threefry_generate_strategy\")\ndef threefry_generate_strategy(attrs, inputs, out_type, target):\n    \"\"\"threefry_generate generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_threefry_generate(topi.random.threefry_generate),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"threefry_generate.generic\",\n    )\n    return strategy\n\n\n# threefry_split\ndef wrap_compute_threefry_split(topi_compute):\n    \"\"\"Wrap threefry_split topi compute\"\"\"\n\n    def _compute_threefry_split(attrs, inputs, _):\n        return topi_compute(inputs[0])\n\n    return _compute_threefry_split\n\n\n@override_native_generic_func(\"threefry_split_strategy\")\ndef threefry_split_strategy(attrs, inputs, out_type, target):\n    \"\"\"threefry_split generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_threefry_split(topi.random.threefry_split),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"threefry_split.generic\",\n    )\n    return strategy\n\n\n# uniform\ndef wrap_compute_uniform(topi_compute):\n    \"\"\"Wrap uniform topi compute\"\"\"\n\n    def _compute_uniform(attrs, inputs, _):\n        return list(topi_compute(inputs[0], inputs[1], inputs[2], attrs.out_shape, attrs.out_dtype))\n\n    return _compute_uniform\n\n\n@override_native_generic_func(\"uniform_strategy\")\ndef uniform_strategy(attrs, inputs, out_type, target):\n    \"\"\"uniform generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_uniform(topi.random.uniform),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"uniform.generic\",\n    )\n    return strategy\n\n\n# multinomial\ndef wrap_compute_multinomial(topi_compute):\n    \"\"\"Wrap multinomial topi compute\"\"\"\n\n    def _compute_multinomial(attrs, inputs, _):\n        return list(topi_compute(inputs[0], inputs[1], attrs.num_samples))\n\n    return _compute_multinomial\n\n\n# sliding_window\ndef wrap_compute_sliding_window():\n    \"\"\"Wrap sliding_window topi compute\"\"\"\n\n    def _compute_sliding_window(attrs, inputs, _):\n        return [topi.sliding_window(inputs[0], attrs.axis, attrs.window_shape, attrs.strides)]\n\n    return _compute_sliding_window\n\n\n@override_native_generic_func(\"sliding_window_strategy\")\ndef sliding_window_strategy(attrs, inputs, out_type, target):\n    \"\"\"sliding_window generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sliding_window(),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"sliding_window.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"normal_strategy\")\ndef normal_strategy(attrs, inputs, out_type, target):\n    \"\"\"normal generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_uniform(topi.random.normal),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"normal.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"multinomial_strategy\")\ndef multinomial_strategy(attrs, inputs, out_type, target):\n    \"\"\"multinomial generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_multinomial(topi.random.multinomial),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"multinomial.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_scanop(topi_compute):\n    \"\"\"Wrap scanop style topi compute\"\"\"\n\n    def _compute_scanop(attrs, inputs, _):\n        return [topi_compute(inputs[0], attrs.axis, attrs.dtype, attrs.exclusive)]\n\n    return _compute_scanop\n\n\ndef wrap_compute_concat(topi_compute):\n    \"\"\"Wrap concatenate topi compute\"\"\"\n\n    def _compute_concat(attrs, inputs, _):\n        return [topi_compute(inputs, attrs.axis)]\n\n    return _compute_concat\n\n\n@override_native_generic_func(\"cumsum_strategy\")\ndef cumsum_strategy(attrs, inputs, out_type, target):\n    \"\"\"cumsum generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scanop(topi.cumsum),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"cumsum.generic\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"concat_strategy\")\ndef concatenate_strategy(attrs, inputs, out_type, target):\n    \"\"\"concatenate generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_concat(topi.concatenate),\n        wrap_topi_schedule(topi.generic.schedule_injective),\n        name=\"concatenate\",\n    )\n    return strategy\n\n\n@override_native_generic_func(\"cumprod_strategy\")\ndef cumprod_strategy(attrs, inputs, out_type, target):\n    \"\"\"cumprod generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scanop(topi.cumprod),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"cumprod.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_unique(topi_compute):\n    \"\"\"Wrap unique topi compute\"\"\"\n\n    def _compute_unique(attrs, inputs, _):\n        return topi_compute(inputs[0], attrs.sorted, attrs.return_counts)\n\n    return _compute_unique\n\n\n@override_native_generic_func(\"unique_strategy\")\ndef unique_strategy(attrs, inputs, out_type, target):\n    \"\"\"unique generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_unique(topi.unique),\n        wrap_topi_schedule(topi.generic.schedule_unique),\n        name=\"unique.generic\",\n    )\n    return strategy\n\n\n@generic_func\ndef schedule_transpose(attrs, outs, target):\n    \"\"\"schedule transpose\"\"\"\n    with target:\n        return schedule_injective(attrs, outs, target)\n\n\n# invert_permutation\ndef wrap_compute_invert_permutation(topi_compute):\n    \"\"\"wrap invert_permutation topi compute\"\"\"\n\n    def _compute_invert_permutation(attrs, inputs, out_type):\n        return [topi_compute(inputs[0])]\n\n    return _compute_invert_permutation\n\n\n@override_native_generic_func(\"invert_permutation_strategy\")\ndef invert_permutation_strategy(attrs, inputs, out_type, target):\n    \"\"\"invert_permutation generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_invert_permutation(topi.invert_permutation),\n        wrap_topi_schedule(topi.generic.schedule_injective),\n        name=\"invert_permutation.generic\",\n    )\n    return strategy\n\n\ndef wrap_compute_einsum(topi_compute):\n    \"\"\"Wrap einsum topi compute\"\"\"\n\n    def _compute_einsum(attrs, inputs, _):\n        return [topi_compute(attrs.equation, *inputs)]\n\n    return _compute_einsum\n\n\n@override_native_generic_func(\"einsum_strategy\")\ndef einsum_strategy(attrs, inputs, out_type, target):\n    \"\"\"einsum generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_einsum(topi.einsum),\n        wrap_topi_schedule(topi.generic.schedule_einsum),\n        name=\"einsum.generic\",\n    )\n    return strategy\n\n\n# conv2d_backward_weight\ndef wrap_compute_conv2d_backward_weight(topi_compute):\n    \"\"\"wrap conv2d_backward_weight topi compute\"\"\"\n\n    def _compute_conv2d_backward_weight(attrs, inputs, out_dtype):\n        kernel_size = get_const_tuple(attrs.kernel_size)\n        padding = get_const_tuple(attrs.padding)\n        strides = get_const_tuple(attrs.strides)\n        dilation = get_const_tuple(attrs.dilation)\n        groups = attrs.groups\n        out_dtype = attrs.out_dtype\n        layout = attrs.data_layout\n        out_dtype = inputs[0].dtype if out_dtype in (\"same\", \"\") else out_dtype\n        out = topi_compute(\n            inputs[0],\n            inputs[1],\n            kernel_size,\n            padding,\n            strides,\n            dilation,\n            groups,\n            layout,\n            out_dtype,\n        )\n        return [out]\n\n    return _compute_conv2d_backward_weight\n\n\n@override_native_generic_func(\"conv2d_backward_weight_strategy\")\ndef conv2d_backward_weight_strategy(attrs, inputs, out_type, target):\n    \"\"\"wgrad generic strategy\"\"\"\n    raise RuntimeError(\n        \"conv2d_backward_weight is currently only supported with cudnn. \"\n        \"Please run Legalize pass to decompose this op into supported ops.\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/hexagon.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of Hexagon operator strategy.\"\"\"\n\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\n\nfrom tvm import topi\nfrom .generic import *\nfrom .. import op as _op\n\n# --- Op strategy registration\n\n\n@batch_matmul_strategy.register(\"hexagon\")\ndef batch_matmul_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"batch_matmul strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_batch_matmul(topi.nn.batch_matmul, need_out_dtype=True),\n        wrap_topi_schedule(topi.hexagon.schedule_batch_matmul),\n        name=\"batch_matmul.hexagon\",\n    )\n    return strategy\n\n\n@concatenate_strategy.register(\"hexagon\")\ndef concatenate_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"concatenate strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_concat(topi.concatenate),\n        wrap_topi_schedule(topi.hexagon.schedule_injective),\n        name=\"concatenate.hexagon\",\n    )\n    return strategy\n\n\n@conv2d_strategy.register(\"hexagon\")\ndef conv2d_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"Conv2d strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    data_layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    groups = attrs.groups\n    data, kernel = inputs\n    layout = attrs.data_layout\n\n    if groups == 1:\n        if data_layout == \"NHWC\" and kernel_layout == \"HWIO\":\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nhwc),\n                wrap_topi_schedule(topi.hexagon.schedule_conv2d_nhwc),\n                name=\"conv2d_nhwc.hexagon\",\n            )\n        elif data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nchw),\n                wrap_topi_schedule(topi.hexagon.schedule_conv2d_nchw),\n                name=\"conv2d_nchw.hexagon\",\n            )\n        else:\n            raise RuntimeError(\n                f\"Unsupported layouts: data_layout:{data_layout}, kernel_layout:{kernel_layout}, \"\n                f\"groups:{attrs.groups}\"\n            )\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.hexagon.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.hexagon\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.hexagon.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_conv2d_nhwc.hexagon\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        raise RuntimeError(f\"Unsupported group_conv2d layout {layout}\")\n\n    return strategy\n\n\n@dense_strategy.register(\"hexagon\")\ndef dense_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"Dense strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dense(topi.nn.dense),\n        wrap_topi_schedule(topi.hexagon.schedule_dense),\n        name=\"dense.hexagon\",\n    )\n    return strategy\n\n\n@softmax_strategy.register(\"hexagon\")\ndef softmax_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"Softmax strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.hexagon.schedule_softmax),\n        name=\"softmax.hexagon\",\n    )\n    return strategy\n\n\n@conv2d_transpose_strategy.register(\"hexagon\")\ndef conv2d_transpose_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose hexagon strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCHW\", \"only support nchw for now\"\n    assert dilation == (1, 1), \"not support dilate now\"\n    strategy = _op.OpStrategy()\n    if groups == 1:\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.nn.conv2d_transpose_nchw),\n            wrap_topi_schedule(topi.hexagon.schedule_conv2d_transpose_nchw),\n            name=\"conv2d_transpose_nchw.generic\",\n        )\n    else:\n        raise RuntimeError(\"Unsupported conv2d_transpose layout {}\".format(layout))\n    return strategy\n\n\n# --- Op schedule registration\n\n\n@schedule_adaptive_pool.register(\"hexagon\")\ndef schedule_adaptive_pool_hexagon(attrs, outs, target):\n    \"\"\"Schedule adaptive pool ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_adaptive_pool(outs)\n\n\n@schedule_injective.register(\"hexagon\")\ndef schedule_injective_hexagon(attrs, outs, target):\n    \"\"\"Schedule injective ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_injective(outs)\n\n\n@schedule_concatenate.register(\"hexagon\")\ndef schedule_concatenate_hexagon(attrs, outs, target):\n    \"\"\"Schedule concatenate ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_injective(outs)\n\n\n@schedule_pad.register(\"hexagon\")\ndef schedule_pad_hexagon(attrs, outs, target):\n    \"\"\"Schedule pad ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_pad(outs)\n\n\n@schedule_pool.register(\"hexagon\")\ndef schedule_pool_hexagon(attrs, outs, target):\n    \"\"\"Schedule pool ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_pool(outs)\n\n\n@schedule_reduce.register(\"hexagon\")\ndef schedule_reduce_hexagon(attrs, outs, target):\n    \"\"\"Schedule reduction ops for Hexagon\"\"\"\n    with target:\n        return topi.hexagon.schedule_reduce(outs)\n\n\n@conv2d_NCHWc_strategy.register(\"hexagon\")\ndef conv2d_NCHWc_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc_ hexagon strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(\n            topi.hexagon.conv2d_NCHWc_int8, need_data_layout=True, need_out_layout=True\n        ),\n        wrap_topi_schedule(topi.hexagon.schedule_conv2d_NCHWc_int8),\n        name=\"conv2d_NCHWc_int8.hexagon\",\n    )\n    return strategy\n\n\n@dense_pack_strategy.register(\"hexagon\")\ndef dense_pack_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"dense_pack hexagon strategy\"\"\"\n    strategy = _op.OpStrategy()\n\n    if (\n        inputs[0].dtype == \"uint8\"\n        and inputs[1].dtype == \"uint8\"\n        and out_type.dtype == \"int32\"\n        and attrs[\"weight_layout\"] == \"NC32n4c\"\n    ):\n        strategy.add_implementation(\n            wrap_compute_dense(topi.hexagon.dense.dense_u8u8i32_vrmpy_compute),\n            wrap_topi_schedule(topi.hexagon.dense.dense_u8u8i32_vrmpy_schedule),\n            name=\"dense_uint8.hexagon\",\n            plevel=12,\n        )\n\n    return strategy\n\n\n@fast_softmax_strategy.register(\"hexagon\")\ndef fast_softmax_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"fast_softmax hexagon strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.fast_softmax),\n        wrap_topi_schedule(topi.hexagon.schedule_softmax),\n        name=\"fast_softmax.hexagon\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/hls.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of HLS operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nfrom tvm import topi\nfrom .generic import *\nfrom .. import op as _op\n\n\n@schedule_injective.register(\"hls\")\ndef schedule_injective_hls(attrs, outs, target):\n    \"\"\"schedule injective ops for hls\"\"\"\n    with target:\n        return topi.hls.schedule_injective(outs)\n\n\n@schedule_reduce.register(\"hls\")\ndef schedule_reduce_hls(attrs, outs, target):\n    \"\"\"schedule reduction ops for hls\"\"\"\n    with target:\n        return topi.hls.schedule_reduce(outs)\n\n\n@schedule_concatenate.register(\"hls\")\ndef schedule_concatenate_hls(attrs, outs, target):\n    \"\"\"schedule concatenate for hls\"\"\"\n    with target:\n        return topi.hls.schedule_injective(outs)\n\n\n@schedule_pool.register(\"hls\")\ndef schedule_pool_hls(attrs, outs, target):\n    \"\"\"schedule pooling ops for hls\"\"\"\n    with target:\n        return topi.hls.schedule_pool(outs, attrs.layout)\n\n\n@schedule_adaptive_pool.register(\"hls\")\ndef schedule_adaptive_pool_hls(attrs, outs, target):\n    \"\"\"schedule adaptive pooling ops for hls\"\"\"\n    with target:\n        return topi.hls.schedule_adaptive_pool(outs)\n\n\n@softmax_strategy.register(\"hls\")\ndef softmax_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"softmax hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.hls.schedule_softmax),\n        name=\"softmax.hls\",\n    )\n    return strategy\n\n\n@log_softmax_strategy.register(\"hls\")\ndef log_softmax_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"log_softmax hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.log_softmax),\n        wrap_topi_schedule(topi.hls.schedule_softmax),\n        name=\"log_softmax.hls\",\n    )\n    return strategy\n\n\n@conv2d_strategy.register(\"hls\")\ndef conv2d_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"conv2d hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    (dilation_h, dilation_w) = dilation\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nchw),\n                wrap_topi_schedule(topi.hls.schedule_conv2d_nchw),\n                name=\"conv2d_nchw.hls\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_nhwc),\n                wrap_topi_schedule(topi.hls.schedule_conv2d_nhwc),\n                name=\"conv2d_nhwc.hls\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {}\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.hls.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.hls\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.hls.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_nhwc.hls\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        raise RuntimeError(\"group_conv2d is not supported for hls\")\n    return strategy\n\n\n@conv2d_NCHWc_strategy.register(\"hls\")\ndef conv2d_NCHWc_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(topi.nn.conv2d_NCHWc, need_data_layout=True, need_out_layout=True),\n        wrap_topi_schedule(topi.hls.schedule_conv2d_NCHWc),\n        name=\"conv2d_NCHWc.hls\",\n    )\n    return strategy\n\n\n@conv2d_transpose_strategy.register(\"hls\")\ndef conv2d_transpose_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose hls strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCHW\", \"only support nchw for now\"\n    assert dilation == (1, 1), \"not support dilate now\"\n    assert groups == 1, \"only support groups == 1 for now\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d_transpose(topi.nn.conv2d_transpose_nchw),\n        wrap_topi_schedule(topi.hls.schedule_conv2d_transpose_nchw),\n        name=\"conv2d_transpose_nchw.hls\",\n    )\n    return strategy\n\n\n@dense_strategy.register(\"hls\")\ndef dense_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"dense hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dense(topi.nn.dense),\n        wrap_topi_schedule(topi.hls.schedule_dense),\n        name=\"dense.hls\",\n    )\n    return strategy\n\n\n@bitserial_conv2d_strategy.register(\"hls\")\ndef bitserial_conv2d_strategy_hls(attrs, inputs, out_type, target):\n    \"\"\"bitserial_conv2d hls strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nchw),\n            wrap_topi_schedule(topi.hls.schedule_bitserial_conv2d_nchw),\n            name=\"bitserial_conv2d_nchw.hls\",\n        )\n    elif layout == \"NHWC\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nhwc),\n            wrap_topi_schedule(topi.hls.schedule_bitserial_conv2d_nhwc),\n            name=\"bitserial_conv2d_nhwc.hls\",\n        )\n    else:\n        raise ValueError(\"Data layout {} not supported.\".format(layout))\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/intel_graphics.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of x86 operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nfrom tvm import topi\nfrom .generic import *\nfrom .. import op as _op\n\n\n@conv2d_strategy.register(\"intel_graphics\")\ndef conv2d_strategy_intel_graphics(attrs, inputs, out_type, target):\n    \"\"\"conv2d intel graphics strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation_h, dilation_w = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.intel_graphics.conv2d_nchw),\n                wrap_topi_schedule(topi.intel_graphics.schedule_conv2d_nchw),\n                name=\"conv2d_nchw.intel_graphics\",\n            )\n            # conv2d_NCHWc won't work without alter op layout pass\n            # TODO(@Laurawly): fix this\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.intel_graphics.conv2d_NCHWc, need_data_layout=True, need_out_layout=True\n                ),\n                wrap_topi_schedule(topi.intel_graphics.schedule_conv2d_NCHWc),\n                name=\"conv2d_NCHWc.intel_graphics\",\n                plevel=5,\n            )\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {} for intel graphics\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.intel_graphics.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.intel_graphics.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.intel_graphics\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        raise RuntimeError(\"group_conv2d is not supported for intel graphics\")\n    return strategy\n\n\n@conv2d_NCHWc_strategy.register(\"intel_graphics\")\ndef conv2d_NCHWc_strategy_intel_graphics(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc intel_graphics strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(\n            topi.intel_graphics.conv2d_NCHWc, need_data_layout=True, need_out_layout=True\n        ),\n        wrap_topi_schedule(topi.intel_graphics.schedule_conv2d_NCHWc),\n        name=\"conv2d_NCHWc.intel_graphics\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/mali.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of mali operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nimport re\n\nfrom tvm import topi\nfrom tvm.auto_scheduler import is_auto_scheduler_enabled\nfrom tvm.meta_schedule import is_meta_schedule_enabled\n\nfrom .. import op as _op\nfrom .generic import *\n\n\n@conv2d_strategy.register(\"mali\")\ndef conv2d_strategy_mali(attrs, inputs, out_type, target):\n    \"\"\"conv2d mali strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    dilation_h, dilation_w = attrs.get_int_tuple(\"dilation\")\n    stride_h, stride_w = attrs.get_int_tuple(\"strides\")\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            if kernel_layout == \"OIHW\":\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.mali.conv2d_nchw_spatial_pack),\n                    wrap_topi_schedule(topi.mali.schedule_conv2d_nchw_spatial_pack),\n                    name=\"conv2d_nchw_spatial_pack.mali\",\n                )\n                # check if winograd algorithm is applicable\n                _, _, kh, kw = get_const_tuple(kernel.shape)\n                if (\n                    kh == 3\n                    and kw == 3\n                    and stride_h == 1\n                    and stride_w == 1\n                    and dilation_h == 1\n                    and dilation_w == 1\n                ):\n                    strategy.add_implementation(\n                        wrap_compute_conv2d(topi.mali.conv2d_nchw_winograd),\n                        wrap_topi_schedule(topi.mali.schedule_conv2d_nchw_winograd),\n                        name=\"conv2d_nchw_winograd.mali\",\n                        plevel=5,\n                    )\n            elif re.match(r\"OIHW\\d*o\", kernel_layout):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.mali.conv2d_nchw_spatial_pack),\n                    wrap_topi_schedule(topi.mali.schedule_conv2d_nchw_spatial_pack),\n                    name=\"conv2d_nchw_spatial_pack.mali\",\n                )\n            else:\n                raise RuntimeError(\n                    \"Unsupported weight layout {} for conv2d NCHW\".format(kernel_layout)\n                )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            need_auto_scheduler_layout = is_auto_scheduler_enabled()\n            need_meta_schedule_layout = is_meta_schedule_enabled()\n            if need_auto_scheduler_layout or need_meta_schedule_layout:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(\n                        topi.nn.conv2d_nhwc,\n                        need_auto_scheduler_layout=need_auto_scheduler_layout,\n                        need_meta_schedule_layout=need_meta_schedule_layout,\n                    ),\n                    naive_schedule,\n                    name=\"conv2d_nhwc.mali\",\n                )\n                is_winograd_applicable = False\n                if len(kernel.shape) == 4:\n                    kernel_h, kernel_w, _, _ = get_const_tuple(kernel.shape)\n                    is_winograd_applicable = (\n                        \"float\" in data.dtype\n                        and \"float\" in kernel.dtype\n                        and kernel_h == 3\n                        and kernel_w == 3\n                        and stride_h == 1\n                        and stride_w == 1\n                        and dilation_h == 1\n                        and dilation_w == 1\n                    )\n                if is_winograd_applicable:\n                    if need_meta_schedule_layout:\n                        strategy.add_implementation(\n                            wrap_compute_conv2d(\n                                topi.nn.conv2d_winograd_nhwc,\n                                need_auto_scheduler_layout=False,\n                                need_meta_schedule_layout=True,\n                            ),\n                            naive_schedule,  # this implementation should never be picked by autotvm\n                            name=\"conv2d_nhwc.winograd\",\n                            plevel=15,\n                        )\n                    elif need_auto_scheduler_layout:\n                        strategy.add_implementation(\n                            wrap_compute_conv2d(\n                                topi.nn.conv2d_winograd_nhwc,\n                                need_auto_scheduler_layout=True,\n                                need_meta_schedule_layout=False,\n                            ),\n                            naive_schedule,  # this implementation should never be picked by autotvm\n                            name=\"conv2d_nhwc.winograd\",\n                            plevel=15,\n                        )\n                    else:\n                        raise RuntimeError(\"Both AutoScheduler and MetaSchedule are not enabled\")\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.mali.conv2d_nhwc_spatial_pack),\n                    wrap_topi_schedule(topi.mali.schedule_conv2d_nhwc_spatial_pack),\n                    name=\"conv2d_nhwc_spatial_pack.mali\",\n                )\n\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {} for mali\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.mali.depthwise_conv2d_nchw),\n                wrap_topi_schedule(topi.mali.schedule_depthwise_conv2d_nchw),\n                name=\"depthwise_conv2d_nchw.mali\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            if is_auto_scheduler_enabled():\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                    naive_schedule,\n                    name=\"depthwise_conv2d_nhwc.mali\",\n                )\n            elif is_meta_schedule_enabled():\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                    naive_schedule,\n                    name=\"depthwise_conv2d_nhwc.mali\",\n                )\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.mali.depthwise_conv2d_nhwc),\n                    wrap_topi_schedule(topi.mali.schedule_depthwise_conv2d_nhwc),\n                    name=\"depthwise_conv2d_nhwc.mali\",\n                )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {} for mali\".format(layout))\n    else:  # group_conv2d\n        raise RuntimeError(\"group_conv2d is not supported for mali\")\n    return strategy\n\n\n@conv2d_winograd_without_weight_transform_strategy.register(\"mali\")\ndef conv2d_winograd_without_weight_transform_strategy_mali(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform mali strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    strides = attrs.get_int_tuple(\"strides\")\n    kernel = inputs[1]\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert strides == (1, 1), \"Do not support strides now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    if layout == \"NCHW\":\n        assert len(kernel.shape) == 5, \"Kernel must be packed into 5-dim\"\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.mali.conv2d_nchw_winograd),\n            wrap_topi_schedule(topi.mali.schedule_conv2d_nchw_winograd),\n            name=\"conv2d_nchw_winograd.mali\",\n        )\n    elif layout == \"NHWC\":\n        need_auto_scheduler_layout = is_auto_scheduler_enabled()\n        need_meta_schedule_layout = is_meta_schedule_enabled()\n        if need_auto_scheduler_layout or need_meta_schedule_layout:\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.nn.conv2d_winograd_nhwc_without_weight_transform,\n                    need_auto_scheduler_layout=need_auto_scheduler_layout,\n                    need_meta_schedule_layout=need_meta_schedule_layout,\n                ),\n                naive_schedule,  # this implementation should never be picked by autotvm\n                name=\"conv2d_nhwc_winograd_without_weight_transform\",\n                plevel=15,\n            )\n        else:\n            raise RuntimeError(\n                \"Winograd conv2d NHWC is not enabled for mali without auto_scheduler.\"\n            )\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@dense_strategy.register(\"mali\")\ndef dense_strategy_mali(attrs, inputs, out_type, target):\n    \"\"\"dense mali strategy\"\"\"\n    strategy = _op.OpStrategy()\n    if is_auto_scheduler_enabled():\n        strategy.add_implementation(\n            wrap_compute_dense(topi.nn.dense, need_auto_scheduler_layout=True),\n            naive_schedule,\n            name=\"dense.mali\",\n        )\n    elif is_meta_schedule_enabled():\n        strategy.add_implementation(\n            wrap_compute_dense(topi.nn.dense, need_meta_schedule_layout=True),\n            naive_schedule,\n            name=\"dense.mali\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_dense(topi.mali.dense),\n            wrap_topi_schedule(topi.mali.schedule_dense),\n            name=\"dense.mali\",\n        )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/rocm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of ROCm operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,unused-wildcard-import,wildcard-import\nfrom tvm import topi\nfrom tvm.te import SpecializedCondition\nfrom tvm.contrib.thrust import can_use_rocthrust\nfrom tvm.contrib import miopen\n\nfrom .generic import *\nfrom .. import op as _op\nfrom .cuda import batch_matmul_strategy_cuda, conv2d_strategy_cuda, dense_strategy_cuda\n\n\n@conv2d_strategy.register(\"rocm\")\ndef conv2d_strategy_rocm(attrs, inputs, out_type, target):\n    \"\"\"conv2d rocm strategy\"\"\"\n    groups = attrs.groups\n    layout = attrs.data_layout\n    padding = attrs.get_int_tuple(\"padding\")\n\n    strategy = conv2d_strategy_cuda(attrs, inputs, out_type, target)\n\n    # add miopen implementation\n    if (\n        \"miopen\" in target.libs\n        and groups == 1\n        and layout == \"NCHW\"\n        and padding[0] == padding[2]\n        and padding[1] == padding[3]\n    ):\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.rocm.conv2d_nchw_miopen, need_data_layout=True),\n            wrap_topi_schedule(topi.rocm.schedule_conv2d_nchw_miopen),\n            name=\"conv2d_nchw_miopen.rocm\",\n            plevel=50,\n        )\n\n    return strategy\n\n\n@dense_strategy.register(\"rocm\")\ndef dense_strategy_rocm(attrs, inputs, out_type, target):\n    \"\"\"Dense strategy for ROCM\"\"\"\n    assert len(inputs[0].shape) == 2 and len(inputs[1].shape) == 2, \"Only support 2-dim dense\"\n    strategy = dense_strategy_cuda(attrs, inputs, out_type, target)\n\n    if target.kind.name == \"rocm\" and \"rocblas\" in target.libs:\n        assert out_type.dtype == inputs[0].dtype, \"Mixed precision not supported.\"\n        strategy.add_implementation(\n            wrap_compute_dense(topi.rocm.dense_rocblas),\n            wrap_topi_schedule(topi.rocm.schedule_dense_rocblas),\n            name=\"dense_rocblas.rocm\",\n            plevel=15,\n        )\n    return strategy\n\n\n@batch_matmul_strategy.register(\"rocm\")\ndef batch_matmul_strategy_rocm(attrs, inputs, out_type, target):\n    \"\"\"Batch matmul strategy for ROCM\"\"\"\n    strategy = batch_matmul_strategy_cuda(attrs, inputs, out_type, target)\n\n    if target.kind.name == \"rocm\" and \"rocblas\" in target.libs:\n        assert out_type.dtype == inputs[0].dtype, \"Mixed precision not supported.\"\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.rocm.batch_matmul_rocblas),\n            wrap_topi_schedule(topi.rocm.schedule_batch_matmul_rocblas),\n            name=\"batch_matmul_rocblas.rocm\",\n            plevel=12,\n        )\n    return strategy\n\n\n@argsort_strategy.register([\"rocm\"])\ndef argsort_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"argsort rocm strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_argsort(topi.cuda.argsort),\n        wrap_topi_schedule(topi.cuda.schedule_argsort),\n        name=\"argsort.rocm\",\n    )\n    if can_use_rocthrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_argsort(topi.cuda.argsort_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_argsort),\n            name=\"argsort_thrust.rocm\",\n            plevel=15,\n        )\n    return strategy\n\n\n@scatter_strategy.register([\"rocm\"])\ndef scatter_cuda(attrs, inputs, out_type, target):\n    \"\"\"scatter rocm strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter(topi.cuda.scatter),\n        wrap_topi_schedule(topi.cuda.schedule_scatter),\n        name=\"scatter.rocm\",\n        plevel=10,\n    )\n\n    rank = len(inputs[0].shape)\n\n    with SpecializedCondition(rank == 1):\n        if can_use_rocthrust(target, \"tvm.contrib.thrust.stable_sort_by_key\"):\n            strategy.add_implementation(\n                wrap_compute_scatter(topi.cuda.scatter_via_sort),\n                wrap_topi_schedule(topi.cuda.schedule_scatter_via_sort),\n                name=\"scatter_via_sort.rocm\",\n                plevel=9,  # use the sequential version by default\n            )\n    return strategy\n\n\n@sort_strategy.register([\"rocm\"])\ndef sort_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"sort rocm strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sort(topi.cuda.sort),\n        wrap_topi_schedule(topi.cuda.schedule_sort),\n        name=\"sort.rocm\",\n    )\n    if can_use_rocthrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_sort(topi.cuda.sort_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_sort),\n            name=\"sort_thrust.cuda\",\n            plevel=15,\n        )\n    return strategy\n\n\n@topk_strategy.register([\"rocm\"])\ndef topk_strategy_cuda(attrs, inputs, out_type, target):\n    \"\"\"topk rocm strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_topk(topi.cuda.topk),\n        wrap_topi_schedule(topi.cuda.schedule_topk),\n        name=\"topk.rocm\",\n    )\n\n    if can_use_rocthrust(target, \"tvm.contrib.thrust.sort\"):\n        strategy.add_implementation(\n            wrap_compute_topk(topi.cuda.topk_thrust),\n            wrap_topi_schedule(topi.cuda.schedule_topk),\n            name=\"topk_thrust.rocm\",\n            plevel=15,\n        )\n    return strategy\n\n\n@softmax_strategy.register([\"rocm\"])\ndef softmax_strategy_rocm(attrs, inputs, out_type, target):\n    \"\"\"rocm strategy for softmax\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.cuda.schedule_softmax),\n        name=\"softmax.rocm\",\n    )\n    if \"miopen\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_softmax(miopen.softmax),\n            wrap_topi_schedule(topi.generic.schedule_extern),\n            name=\"softmax.miopen\",\n            plevel=15,\n        )\n    return strategy\n\n\n@log_softmax_strategy.register([\"rocm\"])\ndef log_softmax_strategy_rocm(attrs, inputs, out_type, target):\n    \"\"\"rocm strategy for log softmax\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.log_softmax),\n        wrap_topi_schedule(topi.cuda.schedule_softmax),\n        name=\"log_softmax.rocm\",\n    )\n    if \"miopen\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_softmax(miopen.log_softmax),\n            wrap_topi_schedule(topi.generic.schedule_extern),\n            name=\"log_softmax.miopen\",\n            plevel=15,\n        )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/strategy/x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of x86 operator strategy.\"\"\"\n# pylint: disable=invalid-name,unused-argument,wildcard-import,unused-wildcard-import\nimport logging\nimport re\n\nfrom tvm import tir, topi\nfrom tvm.auto_scheduler import is_auto_scheduler_enabled\nfrom tvm.meta_schedule import is_meta_schedule_enabled\nfrom tvm.relay.ty import is_dynamic\nfrom tvm.target import Target\nfrom tvm.te import SpecializedCondition\nfrom tvm.topi.x86.utils import target_has_vnni\n\nfrom .. import op as _op\nfrom .generic import *\n\nlogger = logging.getLogger(\"strategy\")\n\n_NCHWc_matcher = re.compile(\"^NCHW[0-9]+c$\")\n_OIHWio_matcher = re.compile(\"^OIHW[0-9]+i[0-9]+o$\")\n\n\n@schedule_injective.register(\"cpu\")\ndef schedule_injective_cpu(attrs, outs, target):\n    \"\"\"schedule injective ops for x86\"\"\"\n    with target:\n        return topi.x86.schedule_injective(outs)\n\n\n@schedule_reduce.register(\"cpu\")\ndef schedule_reduce_cpu(attrs, outs, target):\n    \"\"\"schedule reduction ops for x86\"\"\"\n    with target:\n        return topi.x86.schedule_reduce(outs)\n\n\n@schedule_pool.register(\"cpu\")\ndef schedule_pool_cpu(attrs, outs, target):\n    \"\"\"schedule pooling ops for x86\"\"\"\n    with target:\n        return topi.x86.schedule_pool(outs, attrs.layout)\n\n\n@schedule_adaptive_pool.register(\"cpu\")\ndef schedule_adaptive_pool_cpu(attrs, outs, target):\n    \"\"\"schedule adaptive pooling ops for x86\"\"\"\n    with target:\n        return topi.x86.schedule_adaptive_pool(outs)\n\n\n@softmax_strategy.register(\"cpu\")\ndef softmax_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"softmax x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.softmax),\n        wrap_topi_schedule(topi.x86.schedule_softmax),\n        name=\"softmax.x86\",\n    )\n    return strategy\n\n\n@fast_softmax_strategy.register(\"cpu\")\ndef fast_softmax_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"fast_softmax x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.fast_softmax),\n        wrap_topi_schedule(topi.x86.schedule_softmax),\n        name=\"fast_softmax.x86\",\n    )\n    return strategy\n\n\n@log_softmax_strategy.register(\"cpu\")\ndef log_softmax_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"log_softmax x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_softmax(topi.nn.log_softmax),\n        wrap_topi_schedule(topi.x86.schedule_softmax),\n        name=\"log_softmax.x86\",\n    )\n    return strategy\n\n\n@conv2d_strategy.register(\"cpu\")\ndef conv2d_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    stride_h, stride_w = get_const_tuple(attrs.strides)\n    dilation_h, dilation_w = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    if dilation_h < 1 or dilation_w < 1:\n        raise ValueError(\"dilation should be positive value\")\n\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n\n    if groups == 1:\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            if topi.x86.is_int8_hw_support(data.dtype, kernel.dtype):\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.conv2d_nchw_int8),\n                    wrap_topi_schedule(topi.x86.schedule_conv2d_nchw_int8),\n                    name=\"conv2d_nchw_int8.x86\",\n                )\n            elif \"dnnl\" in target.libs:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.conv2d_nchw_dnnl),\n                    wrap_topi_schedule(topi.x86.schedule_conv2d_nchw_dnnl),\n                    name=\"conv2d_nchw_dnnl.x86\",\n                )\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.conv2d_nchw),\n                    wrap_topi_schedule(topi.x86.schedule_conv2d_nchw),\n                    name=\"conv2d_nchw.x86\",\n                )\n        elif _NCHWc_matcher.match(layout):  # check if layout is NCHWxc\n            assert _OIHWio_matcher.match(kernel_layout)  # check if kernel is OIHWio\n            return conv2d_NCHWc_strategy_cpu(attrs, inputs, out_type, target)\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            if (not need_auto_scheduler_layout) and (not need_meta_schedule_layout):\n                logger.warning(\"conv2d NHWC layout is not optimized for x86 with autotvm.\")\n            if \"dnnl\" in target.libs:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.conv2d_nhwc_dnnl),\n                    wrap_topi_schedule(topi.x86.schedule_conv2d_nhwc_dnnl),\n                    name=\"conv2d_nhwc_dnnl.x86\",\n                )\n            else:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(\n                        topi.nn.conv2d_nhwc,\n                        need_auto_scheduler_layout=need_auto_scheduler_layout,\n                        need_meta_schedule_layout=need_meta_schedule_layout,\n                    ),\n                    wrap_topi_schedule(topi.x86.schedule_conv2d_nhwc),\n                    name=\"conv2d_nhwc.x86\",\n                )\n\n            judge_winograd_auto_scheduler = False\n            if len(kernel.shape) == 4:\n                kernel_h, kernel_w, _, co = get_const_tuple(kernel.shape)\n                judge_winograd_auto_scheduler = (\n                    \"float\" in data.dtype\n                    and \"float\" in kernel.dtype\n                    and kernel_h == 3\n                    and kernel_w == 3\n                    and stride_h == 1\n                    and stride_w == 1\n                    and dilation_h == 1\n                    and dilation_w == 1\n                    and 64 < co < 512\n                    # The last condition of co is based on our profiling of resnet workloads\n                    # on skylake avx512 machines. We found winograd is faster than direct\n                    # only when co is within this range\n                )\n\n            # register auto-scheduler implementations\n            if (\n                need_auto_scheduler_layout or need_meta_schedule_layout\n            ) and judge_winograd_auto_scheduler:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(\n                        topi.nn.conv2d_winograd_nhwc,\n                        need_auto_scheduler_layout=need_auto_scheduler_layout,\n                        need_meta_schedule_layout=need_meta_schedule_layout,\n                    ),\n                    naive_schedule,  # this implementation should never be picked by autotvm\n                    name=\"conv2d_nhwc.winograd\",\n                    plevel=15,\n                )\n        elif layout == \"HWCN\":\n            assert kernel_layout == \"HWIO\"\n            if (not need_auto_scheduler_layout) or (not need_meta_schedule_layout):\n                logger.warning(\"conv2d HWCN layout is not optimized for x86 with autotvm.\")\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.conv2d_hwcn),\n                wrap_topi_schedule(topi.generic.schedule_conv2d_hwcn),\n                name=\"conv2d_hwcn.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported conv2d layout {} for x86\".format(layout))\n    elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups):\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            channel_multiplier = get_const_tuple(inputs[1].shape)[1]\n            if channel_multiplier == 1 and dilation_h == 1 and dilation_w == 1:\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.x86.depthwise_conv2d_nchw),\n                    wrap_topi_schedule(topi.x86.schedule_depthwise_conv2d_nchw),\n                    name=\"depthwise_conv2d_nchw.x86\",\n                )\n            else:\n                logger.warning(\n                    \"For x86 target, depthwise_conv2d with channel \"\n                    \"multiplier greater than 1 is not optimized\"\n                )\n                strategy.add_implementation(\n                    wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw),\n                    wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nchw),\n                    name=\"depthwise_conv2d_nchw.generic\",\n                )\n        elif _NCHWc_matcher.match(layout):  # check if layout is NCHWxc\n            assert _OIHWio_matcher.match(kernel_layout)  # check if kernel is OIHWio\n            return depthwise_conv2d_NCHWc_strategy_cpu(attrs, inputs, out_type, target)\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWOI\"\n            if (not need_auto_scheduler_layout) and (not need_meta_schedule_layout):\n                logger.warning(\n                    \"depthwise_conv2d NHWC layout is not optimized for x86 with autotvm.\"\n                )\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc),\n                wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nhwc),\n                name=\"depthwise_conv2d_nhwc.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported depthwise_conv2d layout {}\".format(layout))\n    else:  # group_conv2d\n        if layout == \"NCHW\":\n            assert kernel_layout == \"OIHW\"\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.x86.group_conv2d_nchw, has_groups=True),\n                wrap_topi_schedule(topi.x86.schedule_group_conv2d_nchw),\n                name=\"group_conv2d_nchw.x86\",\n            )\n        elif layout == \"NHWC\":\n            assert kernel_layout == \"HWIO\"\n            if (not need_auto_scheduler_layout) and (not need_meta_schedule_layout):\n                logger.warning(\"group_conv2d is not optimized for x86 with autotvm.\")\n            strategy.add_implementation(\n                wrap_compute_conv2d(topi.nn.group_conv2d_nhwc, has_groups=True),\n                wrap_topi_schedule(topi.generic.schedule_group_conv2d_nhwc),\n                name=\"group_conv2d_nhwc.generic\",\n            )\n        else:\n            raise RuntimeError(\"Unsupported group_conv2d layout {}\".format(layout))\n    return strategy\n\n\n@conv2d_NCHWc_strategy.register(\"cpu\")\ndef conv2d_NCHWc_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_NCHWc x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    data, kernel = inputs\n    if topi.x86.is_int8_hw_support(data.dtype, kernel.dtype):\n        strategy.add_implementation(\n            wrap_compute_conv2d(\n                topi.x86.conv2d_NCHWc_int8, need_data_layout=True, need_out_layout=True\n            ),\n            wrap_topi_schedule(topi.x86.schedule_conv2d_NCHWc_int8),\n            name=\"conv2d_NCHWc_int8.x86\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_conv2d(topi.x86.conv2d_NCHWc, need_data_layout=True, need_out_layout=True),\n            wrap_topi_schedule(topi.x86.schedule_conv2d_NCHWc),\n            name=\"conv2d_NCHWc.x86\",\n        )\n    return strategy\n\n\n@depthwise_conv2d_NCHWc_strategy.register(\"cpu\")\ndef depthwise_conv2d_NCHWc_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"depthwise_conv2d x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv2d(\n            topi.x86.depthwise_conv2d_NCHWc, need_data_layout=True, need_out_layout=True\n        ),\n        wrap_topi_schedule(topi.x86.schedule_depthwise_conv2d_NCHWc),\n        name=\"depthwise_conv2d_NCHWc.x86\",\n    )\n    return strategy\n\n\n@conv2d_transpose_strategy.register(\"cpu\")\ndef conv2d_transpose_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose x86 strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCHW\", \"only support nchw for now\"\n    assert dilation == (1, 1), \"not support dilate now\"\n    strategy = _op.OpStrategy()\n    if groups == 1:\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.x86.conv2d_transpose_nchw),\n            wrap_topi_schedule(topi.x86.schedule_conv2d_transpose_nchw),\n            name=\"conv2d_transpose_nchw.x86\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_conv2d_transpose(topi.nn.group_conv2d_transpose_nchw, has_groups=True),\n            wrap_topi_schedule(topi.generic.schedule_group_conv2d_transpose_nchw),\n            name=\"group_conv2d_transpose_nchw.x86\",\n        )\n    return strategy\n\n\n@conv3d_transpose_strategy.register(\"cpu\")\ndef conv3d_transpose_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv3d_transpose x86 strategy\"\"\"\n    layout = attrs.data_layout\n    dilation = get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    assert layout == \"NCDHW\", \"only support ncdhw for now\"\n    assert dilation == (1, 1, 1), \"not support dilate now\"\n    assert groups == 1, \"only support groups == 1 for now\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_conv3d_transpose(topi.x86.conv3d_transpose_ncdhw),\n        wrap_topi_schedule(topi.x86.schedule_conv3d_transpose_ncdhw),\n        name=\"conv3d_transpose_ncdhw.x86\",\n    )\n    return strategy\n\n\n@conv3d_strategy.register(\"cpu\")\ndef conv3d_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv3d generic strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n    if need_auto_scheduler_layout or need_meta_schedule_layout:\n        # Use auto-scheduler. We should provide clear compute definition without autotvm templates\n        # or packed layouts.\n        if layout == \"NCDHW\":\n            strategy.add_implementation(\n                wrap_compute_conv3d(topi.nn.conv3d_ncdhw),\n                naive_schedule,\n                name=\"conv3d_ncdhw.x86\",\n            )\n        elif layout == \"NDHWC\":\n            strategy.add_implementation(\n                wrap_compute_conv3d(\n                    topi.nn.conv3d_ndhwc,\n                    need_auto_scheduler_layout=need_auto_scheduler_layout,\n                    need_meta_schedule_layout=need_meta_schedule_layout,\n                ),\n                naive_schedule,\n                name=\"conv3d_ndhwc.x86\",\n            )\n        else:\n            raise ValueError(\"Not support this layout {} yet\".format(layout))\n    else:\n        # Use autotvm templates\n        if layout == \"NCDHW\":\n            strategy.add_implementation(\n                wrap_compute_conv3d(topi.x86.conv3d_ncdhw),\n                wrap_topi_schedule(topi.x86.schedule_conv3d_ncdhw),\n                name=\"conv3d_ncdhw.x86\",\n            )\n        elif layout == \"NDHWC\":\n            strategy.add_implementation(\n                wrap_compute_conv3d(topi.x86.conv3d_ndhwc),\n                wrap_topi_schedule(topi.x86.schedule_conv3d_ndhwc),\n                name=\"conv3d_ndhwc.x86\",\n            )\n        else:\n            raise ValueError(\"Not support this layout {} yet\".format(layout))\n    return strategy\n\n\n@conv1d_strategy.register(\"cpu\")\ndef conv1d_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv1d x86 strategy\"\"\"\n    layout = attrs.data_layout\n    groups = attrs.groups\n    dilation = get_const_tuple(attrs.dilation)\n    if dilation[0] < 1:\n        raise ValueError(\"dilation should be a positive value\")\n    strategy = _op.OpStrategy()\n    if groups == 1:\n        if layout == \"NCW\":\n            strategy.add_implementation(\n                wrap_compute_conv1d(topi.nn.conv1d_ncw),\n                wrap_topi_schedule(topi.x86.schedule_conv1d_ncw),\n                name=\"conv1d_ncw.x86\",\n            )\n        elif layout == \"NWC\":\n            strategy.add_implementation(\n                wrap_compute_conv1d(topi.nn.conv1d_nwc),\n                wrap_topi_schedule(topi.x86.schedule_conv1d_nwc),\n                name=\"conv1d_nwc.x86\",\n            )\n        else:\n            raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    else:\n        if layout == \"NCW\":\n            strategy.add_implementation(\n                wrap_compute_group_conv1d(topi.nn.group_conv1d_ncw),\n                wrap_topi_schedule(topi.x86.schedule_group_conv1d_ncw),\n                name=\"group_conv1d_ncw.x86\",\n            )\n        elif layout == \"NWC\":\n            strategy.add_implementation(\n                wrap_compute_group_conv1d(topi.nn.group_conv1d_nwc),\n                wrap_topi_schedule(topi.x86.schedule_group_conv1d_nwc),\n                name=\"group_conv1d_nwc.x86\",\n            )\n        else:\n            raise ValueError(\"Unsupported conv1d layout {}\".format(layout))\n    return strategy\n\n\n@matmul_strategy.register(\"cpu\")\ndef matmul_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"matmul x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n\n    same_type = inputs[0].dtype == inputs[1].dtype == out_type.dtype\n    dtype = inputs[0].dtype\n    u8s8s32 = dtype == \"uint8\" and inputs[1].dtype == \"int8\" and out_type.dtype == \"int32\"\n    if \"cblas\" in target.libs:\n        length_before = len(strategy.specializations) if strategy.specializations else 0\n        with SpecializedCondition(same_type and dtype in [\"float32\", \"float64\"]):\n            strategy.add_implementation(\n                wrap_compute_matmul(topi.x86.matmul_cblas),\n                wrap_topi_schedule(topi.x86.schedule_matmul_cblas),\n                name=\"matmul_cblas.x86\",\n                plevel=13,\n            )\n        length_after = len(strategy.specializations) if strategy.specializations else 0\n        if length_before == length_after:\n            logger.warning(\n                \"Currently cblas only support the data type to be float32 or float64. Skip.\"\n            )\n    if \"mkl\" in target.libs:\n        length_before = len(strategy.specializations) if strategy.specializations else 0\n        with SpecializedCondition(same_type and dtype in [\"float32\", \"float64\"] or u8s8s32):\n            strategy.add_implementation(\n                wrap_compute_matmul(topi.x86.matmul_mkl),\n                wrap_topi_schedule(topi.x86.schedule_matmul_mkl),\n                name=\"matmul_mkl.x86\",\n                plevel=14,\n            )\n        length_after = len(strategy.specializations) if strategy.specializations else 0\n        if length_before == length_after:\n            logger.warning(\n                \"Currently mkl only support the data type to be float32, float64 or input with \"\n                \"uint8 and int8 while output wiht int32. Skip.\"\n            )\n    if \"dnnl\" in target.libs:\n        length_before = len(strategy.specializations) if strategy.specializations else 0\n        with SpecializedCondition(same_type and dtype == \"float32\"):\n            strategy.add_implementation(\n                wrap_compute_matmul(topi.x86.matmul_dnnl),\n                wrap_topi_schedule(topi.x86.schedule_matmul_dnnl),\n                name=\"matmul_dnnl.x86\",\n                plevel=15,\n            )\n        length_after = len(strategy.specializations) if strategy.specializations else 0\n        if length_before == length_after:\n            logger.warning(\"Currently dnnl only support the data type to be float32. Skip.\")\n\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n    if need_auto_scheduler_layout or need_meta_schedule_layout:\n        strategy.add_implementation(\n            wrap_compute_matmul(\n                topi.nn.matmul,\n                need_auto_scheduler_layout=need_auto_scheduler_layout,\n                need_meta_schedule_layout=need_meta_schedule_layout,\n            ),\n            naive_schedule,\n            name=\"matmul.generic\",\n            plevel=11,\n        )\n    else:\n        # If no cblas/mkl/dnnl strategy choosed\n        if not strategy.specializations:\n            logger.warning(\n                \"Matmul is not optimized for x86. \"\n                \"Recommend to use cblas/mkl/dnnl for better performance.\"\n            )\n        strategy.add_implementation(\n            wrap_compute_matmul(topi.nn.matmul),\n            naive_schedule,\n            name=\"matmul.generic\",\n        )\n    return strategy\n\n\n@dense_strategy.register(\"cpu\")\ndef dense_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"dense x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    same_type = inputs[0].dtype == inputs[1].dtype == out_type.dtype\n    dtype = inputs[0].dtype\n    u8s8s32 = dtype == \"uint8\" and inputs[1].dtype == \"int8\" and out_type.dtype == \"int32\"\n    strategy.add_implementation(\n        wrap_compute_dense(topi.x86.dense_nopack),\n        wrap_topi_schedule(topi.x86.schedule_dense_nopack),\n        name=\"dense_nopack.x86\",\n        plevel=5,\n    )\n\n    strategy.add_implementation(\n        wrap_compute_dense(topi.x86.dense_pack),\n        wrap_topi_schedule(topi.x86.schedule_dense_pack),\n        name=\"dense_pack.x86\",\n        plevel=10,\n    )\n\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n\n    if need_auto_scheduler_layout or need_meta_schedule_layout:\n        strategy.add_implementation(\n            wrap_compute_dense(\n                topi.nn.dense,\n                need_auto_scheduler_layout=need_auto_scheduler_layout,\n                need_meta_schedule_layout=need_meta_schedule_layout,\n            ),\n            naive_schedule,\n            name=\"dense.generic\",\n            plevel=11,\n        )\n\n    if \"cblas\" in target.libs:\n        with SpecializedCondition(same_type and dtype in [\"float32\", \"float64\"]):\n            strategy.add_implementation(\n                wrap_compute_dense(topi.x86.dense_cblas),\n                wrap_topi_schedule(topi.x86.schedule_dense_cblas),\n                name=\"dense_cblas.x86\",\n                plevel=13,\n            )\n    if \"mkl\" in target.libs:\n        with SpecializedCondition(same_type and dtype in [\"float32\", \"float64\"] or u8s8s32):\n            strategy.add_implementation(\n                wrap_compute_dense(topi.x86.dense_mkl),\n                wrap_topi_schedule(topi.x86.schedule_dense_mkl),\n                name=\"dense_mkl.x86\",\n                plevel=14,\n            )\n    if \"dnnl\" in target.libs:\n        with SpecializedCondition(same_type and dtype == \"float32\"):\n            strategy.add_implementation(\n                wrap_compute_dense(topi.x86.dense_dnnl),\n                wrap_topi_schedule(topi.x86.schedule_dense_dnnl),\n                name=\"dense_dnnl.x86\",\n                plevel=15,\n            )\n    return strategy\n\n\n@dense_pack_strategy.register(\"cpu\")\ndef dense_pack_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"dense_pack x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n\n    if (\n        inputs[0].dtype == \"uint8\"\n        and inputs[1].dtype == \"int8\"\n        and out_type.dtype == \"int32\"\n        and attrs[\"weight_layout\"] == \"NC16n4c\"\n    ):\n        strategy.add_implementation(\n            wrap_compute_dense(topi.x86.dense_vnni),\n            wrap_topi_schedule(topi.x86.schedule_dense_vnni),\n            name=\"dense_vnni.x86\",\n            plevel=12,\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_dense(topi.x86.dense_pack),\n            wrap_topi_schedule(topi.x86.schedule_dense_pack),\n            name=\"dense_pack.x86\",\n            plevel=10,\n        )\n\n    return strategy\n\n\n@batch_matmul_strategy.register(\"cpu\")\ndef batch_matmul_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"batch_matmul x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    mcpu = Target.current().mcpu\n\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n\n    if (\n        not attrs.transpose_a\n        and attrs.transpose_b\n        and target_has_vnni(mcpu)\n        and inputs[0].dtype == \"uint8\"\n        and inputs[1].dtype == \"int8\"\n        and inputs[1].shape[-2] % 16 == 0\n        and inputs[1].shape[-1] % 4 == 0\n    ):\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.x86.batch_matmul_vnni_compute, need_out_dtype=True),\n            wrap_topi_schedule(topi.x86.schedule_batch_matmul_vnni),\n            name=\"batch_matmul_vnni.x86\",\n            plevel=10,\n        )\n    elif is_dynamic(out_type) or need_auto_scheduler_layout or need_meta_schedule_layout:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(\n                topi.nn.batch_matmul,\n                need_out_dtype=True,\n                need_auto_scheduler_layout=need_auto_scheduler_layout,\n                need_meta_schedule_layout=need_meta_schedule_layout,\n            ),\n            wrap_topi_schedule(topi.generic.nn.schedule_batch_matmul),\n            name=\"batch_matmul.generic\",\n            plevel=10,\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.x86.batch_matmul, need_out_dtype=True),\n            wrap_topi_schedule(topi.x86.schedule_batch_matmul),\n            name=\"batch_matmul.x86\",\n            plevel=10,\n        )\n    if \"cblas\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.x86.batch_matmul_cblas),\n            wrap_topi_schedule(topi.x86.schedule_batch_matmul_cblas),\n            name=\"batch_matmul_cblas.x86\",\n            plevel=15,\n        )\n    if \"mkl\" in target.libs:\n        strategy.add_implementation(\n            wrap_compute_batch_matmul(topi.x86.batch_matmul_mkl),\n            wrap_topi_schedule(topi.x86.schedule_batch_matmul_mkl),\n            name=\"batch_matmul_mkl.x86\",\n            plevel=15,\n        )\n    return strategy\n\n\n@sparse_dense_strategy.register(\"cpu\")\ndef sparse_dense_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"sparse dense x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_sparse_dense(topi.nn.sparse_dense),\n        wrap_topi_schedule(topi.x86.schedule_sparse_dense),\n        name=\"sparse_dense.x86\",\n        plevel=10,\n    )\n    return strategy\n\n\n@sparse_conv2d_strategy.register(\"cpu\")\ndef sparse_conv2d_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"sparse conv2d x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    if attrs[\"kernel_size\"][0] == 1:\n        strategy.add_implementation(\n            wrap_compute_sparse_conv2d(topi.nn.sparse_conv2d),\n            wrap_topi_schedule(topi.generic.schedule_sparse_conv2d),\n            name=\"sparse_conv2d.generic\",\n        )\n    elif attrs[\"kernel_size\"][0] == 3:\n        if attrs[\"layout\"] == \"NHWC\":\n            strategy.add_implementation(\n                wrap_compute_sparse_conv2d(topi.x86.spconv2d_3x3_nhwc),\n                wrap_topi_schedule(topi.x86.schedule_spconv2d_3x3_nhwc),\n                name=\"conv3x3_spNHWC.x86\",\n            )\n        elif attrs[\"layout\"] == \"NCHW\":\n            strategy.add_implementation(\n                wrap_compute_sparse_conv2d(topi.x86.spconv2d_3x3_nchw),\n                wrap_topi_schedule(topi.x86.schedule_spconv2d_3x3_nchw),\n            )\n    return strategy\n\n\n@roi_align_strategy.register(\"cpu\")\ndef roi_align_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"roi_align x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.x86.roi_align_nchw),\n            wrap_topi_schedule(topi.generic.schedule_roi_align),\n            name=\"roi_align.x86\",\n        )\n    else:\n        assert layout == \"NHWC\", \"layout must be NCHW or NHWC.\"\n        strategy.add_implementation(\n            wrap_compute_roi_align(topi.vision.rcnn.roi_align_nhwc),\n            wrap_topi_schedule(topi.generic.schedule_roi_align),\n            name=\"roi_align.x86\",\n        )\n    return strategy\n\n\n@bitserial_conv2d_strategy.register(\"cpu\")\ndef bitserial_conv2d_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"bitserial_conv2d x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    layout = attrs.data_layout\n    if layout == \"NCHW\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.x86.bitserial_conv2d_nchw),\n            wrap_topi_schedule(topi.x86.schedule_bitserial_conv2d_nchw),\n            name=\"bitserial_conv2d_nchw.x86\",\n        )\n    elif layout == \"NHWC\":\n        strategy.add_implementation(\n            wrap_compute_bitserial_conv2d(topi.x86.bitserial_conv2d_nhwc),\n            wrap_topi_schedule(topi.x86.schedule_bitserial_conv2d_nhwc),\n            name=\"bitserial_conv2d_nhwc.x86\",\n        )\n    else:\n        raise ValueError(\"Data layout {} not supported.\".format(layout))\n    return strategy\n\n\n@bitserial_dense_strategy.register(\"cpu\")\ndef bitserial_dense_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"bitserial_dense x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_bitserial_dense(topi.x86.bitserial_dense),\n        wrap_topi_schedule(topi.x86.schedule_bitserial_dense),\n        name=\"bitserial_dense.x86\",\n    )\n    return strategy\n\n\n@scatter_nd_strategy.register(\"cpu\")\ndef scatter_nd_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"scatter_nd x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_scatter_nd(topi.x86.scatter_nd),\n        wrap_topi_schedule(topi.generic.schedule_extern),\n        name=\"scatter_nd.x86\",\n        plevel=10,\n    )\n    return strategy\n\n\n@conv2d_winograd_without_weight_transform_strategy.register(\"cpu\")\ndef conv2d_winograd_without_weight_transform_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"conv2d_winograd_without_weight_transform cpu strategy\"\"\"\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    layout = attrs.data_layout\n    strides = attrs.get_int_tuple(\"strides\")\n    assert dilation == (1, 1), \"Do not support dilate now\"\n    assert strides == (1, 1), \"Do not support strides now\"\n    assert groups == 1, \"Do not support arbitrary group number\"\n    strategy = _op.OpStrategy()\n    need_auto_scheduler_layout = is_auto_scheduler_enabled()\n    need_meta_schedule_layout = is_meta_schedule_enabled()\n    if layout == \"NHWC\":\n        if need_meta_schedule_layout:\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.nn.conv2d_winograd_nhwc_without_weight_transform,\n                    need_auto_scheduler_layout=False,\n                    need_meta_schedule_layout=True,\n                ),\n                naive_schedule,\n                name=\"ansor.winograd\",\n            )\n        elif need_auto_scheduler_layout:\n            strategy.add_implementation(\n                wrap_compute_conv2d(\n                    topi.nn.conv2d_winograd_nhwc_without_weight_transform,\n                    need_auto_scheduler_layout=True,\n                    need_meta_schedule_layout=False,\n                ),\n                naive_schedule,\n                name=\"ansor.winograd\",\n            )\n        else:\n            raise RuntimeError(\"Both AutoScheduler and MetaSchedule are not enabled\")\n    else:\n        raise RuntimeError(\n            \"Unsupported conv2d_winograd_without_weight_transform layout {}\".format(layout)\n        )\n    return strategy\n\n\n@concatenate_strategy.register([\"cpu\"])\ndef concatenate_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"concatenate x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    use_only_old_concat = False\n    for inpt in inputs:\n        shape = inpt.shape\n        for i in shape:\n            if not isinstance(i, tir.expr.IntImm):\n                use_only_old_concat = True\n                break\n    if use_only_old_concat:\n        strategy.add_implementation(\n            wrap_compute_concat(topi.transform.concatenate),\n            wrap_topi_schedule(topi.x86.injective.schedule_concatenate),\n            name=\"concatenate.generic\",\n        )\n    else:\n        strategy.add_implementation(\n            wrap_compute_concat(topi.x86.concatenate),\n            wrap_topi_schedule(topi.x86.schedule_concatenate_cpu),\n            name=\"concatenate.cpu\",\n        )\n        strategy.add_implementation(\n            wrap_compute_concat(topi.transform.concatenate),\n            wrap_topi_schedule(topi.x86.injective.schedule_concatenate),\n            name=\"concatenate.generic\",\n        )\n    return strategy\n\n\n@batch_norm_strategy.register([\"cpu\"])\ndef batch_norm_strategy_cpu(attrs, inputs, out_type, target):\n    \"\"\"batch_norm x86 strategy\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_batch_norm(topi.nn.batch_norm),\n        wrap_topi_schedule(topi.x86.schedule_batch_norm),\n        name=\"batch_norm.cpu\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Basic tensor operations.\"\"\"\n# pylint: disable=redefined-builtin, unused-argument\nfrom tvm import target\nfrom tvm.runtime import ndarray as _nd\nfrom tvm.runtime import Device as _Device\nfrom tvm.te.hybrid import script\n\nfrom . import _make\nfrom .dyn import _make as _dyn_make\nfrom ..expr import Tuple, Expr, Constant\nfrom . import op as reg\n\n\ndef _make_virtual_device(device):\n    if isinstance(device, _Device):\n        return target.VirtualDevice(device)\n    if isinstance(device, str):\n        return target.VirtualDevice(_nd.device(device))\n    raise ValueError(\"expecting a Device or device name, but received a %s\" % (type(device)))\n\n\n# We create a wrapper function for each operator in the\n# python side to call into the positional _make.OpName function.\n#\n# We make this decision so that we can:\n# - Have declare python docstring for each function\n# - Enable keyword arguments easily\n# - Not put too much burden on FFI to support complicated features\n#   like default value and keyword arguments\n\n\ndef log(data):\n    \"\"\"Compute elementwise log of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.log(data)\n\n\ndef log2(data):\n    \"\"\"Compute elementwise log to the base 2 of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.log2(data)\n\n\ndef log10(data):\n    \"\"\"Compute elementwise log to the base 10 of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.log10(data)\n\n\ndef tan(data):\n    \"\"\"Compute elementwise tan of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.tan(data)\n\n\ndef cos(data):\n    \"\"\"Compute elementwise cos of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.cos(data)\n\n\ndef cosh(data):\n    \"\"\"Compute elementwise cosh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.cosh(data)\n\n\ndef sin(data):\n    \"\"\"Compute elementwise sin of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.sin(data)\n\n\ndef sinh(data):\n    \"\"\"Compute elementwise sinh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.sinh(data)\n\n\ndef acos(data):\n    \"\"\"Compute elementwise acos of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.acos(data)\n\n\ndef acosh(data):\n    \"\"\"Compute elementwise acosh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.acosh(data)\n\n\ndef asin(data):\n    \"\"\"Compute elementwise asin of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.asin(data)\n\n\ndef asinh(data):\n    \"\"\"Compute elementwise asinh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.asinh(data)\n\n\ndef atan(data):\n    \"\"\"Compute elementwise atan of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.atan(data)\n\n\ndef atanh(data):\n    \"\"\"Compute elementwise atanh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.atanh(data)\n\n\ndef exp(data):\n    \"\"\"Compute elementwise exp of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.exp(data)\n\n\ndef erf(data):\n    \"\"\"Compute elementwise error function of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.erf(data)\n\n\ndef sqrt(data):\n    \"\"\"Compute elementwise sqrt of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.sqrt(data)\n\n\ndef rsqrt(data):\n    \"\"\"Compute elementwise rsqrt of data.\n\n    .. math::\n\n      1/sqrt(x)\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.rsqrt(data)\n\n\ndef sigmoid(data):\n    \"\"\"Compute elementwise sigmoid of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.sigmoid(data)\n\n\ndef floor(data):\n    \"\"\"Compute element-wise floor of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.floor(data)\n\n\ndef ceil(data):\n    \"\"\"Compute element-wise ceil of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.ceil(data)\n\n\ndef trunc(data):\n    \"\"\"Compute element-wise trunc of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.trunc(data)\n\n\ndef round(data):\n    \"\"\"Compute element-wise round of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.round(data)\n\n\ndef abs(data):\n    \"\"\"Compute element-wise absolute of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.abs(data)\n\n\ndef sign(data):\n    \"\"\"Compute element-wise absolute of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.sign(data)\n\n\ndef tanh(data):\n    \"\"\"Compute element-wise tanh of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.tanh(data)\n\n\ndef negative(data):\n    \"\"\"Compute element-wise negative of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.negative(data)\n\n\ndef logical_not(data):\n    \"\"\"Compute element-wise logical not of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.logical_not(data)\n\n\ndef bitwise_not(data):\n    \"\"\"Compute element-wise bitwise not of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.bitwise_not(data)\n\n\ndef add(lhs, rhs):\n    \"\"\"Addition with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code:: python\n\n      x = relay.Var(\"a\") # shape is [2, 3]\n      y = relay.Var(\"b\") # shape is [2, 1]\n      z = relay.add(x, y)  # result shape is [2, 3]\n    \"\"\"\n    return _make.add(lhs, rhs)\n\n\ndef subtract(lhs, rhs):\n    \"\"\"Subtraction with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.subtract(lhs, rhs)\n\n\ndef multiply(lhs, rhs):\n    \"\"\"Multiplication with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.multiply(lhs, rhs)\n\n\ndef divide(lhs, rhs):\n    \"\"\"Division with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.divide(lhs, rhs)\n\n\ndef floor_divide(lhs, rhs):\n    \"\"\"Floor division with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.floor_divide(lhs, rhs)\n\n\ndef trunc_divide(lhs, rhs):\n    \"\"\"Trunc division with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.trunc_divide(lhs, rhs)\n\n\ndef power(lhs, rhs):\n    \"\"\"Power with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.power(lhs, rhs)\n\n\ndef mod(lhs, rhs):\n    \"\"\"Mod with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.mod(lhs, rhs)\n\n\ndef floor_mod(lhs, rhs):\n    \"\"\"Floor mod with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.floor_mod(lhs, rhs)\n\n\ndef trunc_mod(lhs, rhs):\n    \"\"\"Trunc mod with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.trunc_mod(lhs, rhs)\n\n\ndef logical_and(lhs, rhs):\n    \"\"\"logical AND with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.logical_and(lhs, rhs)\n\n\ndef logical_or(lhs, rhs):\n    \"\"\"logical OR with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.logical_or(lhs, rhs)\n\n\ndef logical_xor(lhs, rhs):\n    \"\"\"logical XOR with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.logical_xor(lhs, rhs)\n\n\ndef bitwise_and(lhs, rhs):\n    \"\"\"bitwise AND with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.bitwise_and(lhs, rhs)\n\n\ndef bitwise_or(lhs, rhs):\n    \"\"\"bitwise OR with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.bitwise_or(lhs, rhs)\n\n\ndef bitwise_xor(lhs, rhs):\n    \"\"\"bitwise XOR with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.bitwise_xor(lhs, rhs)\n\n\ndef equal(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs == rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.equal(lhs, rhs)\n\n\ndef not_equal(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs != rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.not_equal(lhs, rhs)\n\n\ndef less(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs < rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.less(lhs, rhs)\n\n\ndef less_equal(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs <= rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.less_equal(lhs, rhs)\n\n\ndef greater(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs > rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.greater(lhs, rhs)\n\n\ndef greater_equal(lhs, rhs):\n    \"\"\"Broadcasted elementwise test for (lhs >= rhs).\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.greater_equal(lhs, rhs)\n\n\ndef maximum(lhs, rhs):\n    \"\"\"Maximum with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.maximum(lhs, rhs)\n\n\ndef minimum(lhs, rhs):\n    \"\"\"Minimum with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.minimum(lhs, rhs)\n\n\ndef right_shift(lhs, rhs):\n    \"\"\"Right shift with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.right_shift(lhs, rhs)\n\n\ndef left_shift(lhs, rhs):\n    \"\"\"Left shift with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side input data\n    rhs : relay.Expr\n        The right hand side input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.left_shift(lhs, rhs)\n\n\ndef zeros(shape, dtype):\n    \"\"\"Fill array with zeros.\n\n    Parameters\n    ----------\n    shape : tuple of int or relay.Expr\n        The shape of the target.\n\n    dtype : data type\n        The data type of the target.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    if isinstance(shape, Constant):\n        shape = list(shape.data.numpy())\n    if isinstance(shape, Expr):\n        return _dyn_make.zeros(shape, dtype)\n    if isinstance(shape, int):\n        shape = [shape]\n    if isinstance(shape, (list, tuple)):\n        shape = list(shape)\n    return _make.zeros(shape, dtype)\n\n\ndef zeros_like(data):\n    \"\"\"Returns an array of zeros, with same type and shape as the input.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.zeros_like(data)\n\n\ndef ones(shape, dtype):\n    \"\"\"Fill array with ones.\n\n    Parameters\n    ----------\n    shape : tuple of int or relay.Expr\n        The shape of the target.\n\n    dtype : data type\n        The data type of the target.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    if isinstance(shape, Constant):\n        shape = list(shape.data.numpy())\n    if isinstance(shape, Expr):\n        return _dyn_make.ones(shape, dtype)\n    if isinstance(shape, int):\n        shape = [shape]\n    if isinstance(shape, (list, tuple)):\n        shape = list(shape)\n    return _make.ones(shape, dtype)\n\n\ndef ones_like(data):\n    \"\"\"Returns an array of ones, with same type and shape as the input.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.ones_like(data)\n\n\ndef clip(a, a_min, a_max):\n    \"\"\"Clip the elements in `a` between `a_min` and `a_max`.\n    `a_min` and `a_max` are cast to `a`'s dtype.\n\n    Parameters\n    ----------\n    a : relay.Expr\n        The input tensor.\n    a_min : float\n        The clip minimum.\n    a_max : float\n        The clip maximum.\n\n    Returns\n    -------\n    result : relay.Expr\n        `a` with elements clipped between `a_min` and `a_max`.\n\n    Examples\n    --------\n    .. code:: python\n\n      x = relay.Constant(tvm.nd.array([0, 1, 5, 3, 4, 2]))\n      relay.clip(x, 1., 4.)\n      # [1, 1, 4, 3, 4, 2]\n    \"\"\"\n    return _make.clip(a, a_min, a_max)\n\n\ndef fixed_point_multiply(data, multiplier, shift):\n    \"\"\"Fixed point multiplication between data and a fixed point\n    constant expressed as multiplier * 2^(-shift), where multiplier\n    is a Q-number with 31 fractional bits\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n    multiplier : int\n        The integer multiplier of the fixed point constant.\n    shift : int\n        The integer shift of the fixed point constant.\n\n    Returns\n    -------\n    result : relay.Expr\n        The output of the fixed point multiplication\n    \"\"\"\n    return _make.fixed_point_multiply(data, multiplier, shift)\n\n\ndef concatenate(data, axis):\n    \"\"\"Concatenate the input tensors along the given axis.\n\n    Parameters\n    ----------\n    data : Union(List[relay.Expr], Tuple[relay.Expr])\n        A list of tensors.\n    axis : int\n        The axis along which the tensors are concatenated.\n\n    Returns\n    -------\n    result: relay.Expr\n        The concatenated tensor.\n    \"\"\"\n    data = list(data)\n    if not data:\n        raise ValueError(\"relay.concatenate requires data to be non-empty.\")\n    if not isinstance(axis, int):\n        raise ValueError(\"For now, we only support integer axis\")\n    return _make.concatenate(Tuple(data), axis)\n\n\ndef einsum(data, equation):\n    \"\"\"Evaluates the Einstein summation convention on data\n\n    Parameters\n    ----------\n    data : Union(List[relay.Expr], Tuple[relay.Expr])\n        A list of tensors.\n    equation : str\n        The einsum expression string.\n\n    Returns\n    -------\n    result : relay.Expr\n        The output tensor from the einsum op.\n    \"\"\"\n    data = list(data)\n    if not data:\n        raise ValueError(\"relay.einsum requires data to be non-empty.\")\n    if not isinstance(equation, str):\n        raise ValueError(\"einsum `equation` must be a str\")\n    return _make.einsum(Tuple(data), equation)\n\n\ndef stack(data, axis):\n    \"\"\"Join a sequence of arrays along a new axis.\n\n    Parameters\n    ----------\n    data : Union(List[relay.Expr], relay.Expr)\n        A list of tensors or a Relay expression that evaluates to a tuple of tensors.\n\n    axis : int\n        The axis in the result array along which the input arrays are stacked.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The stacked tensor.\n    \"\"\"\n    if not data:\n        raise ValueError(\"relay.stack requires data to be non-empty.\")\n    if not isinstance(axis, int):\n        raise ValueError(\"For now, we only support integer axis\")\n    if not isinstance(data, Expr):\n        data = Tuple(list(data))\n    return _make.stack(data, axis)\n\n\ndef copy(data):\n    \"\"\"Copy a tensor.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The tensor to be copied.\n\n    Returns\n    -------\n    result: relay.Expr\n        The copied result.\n    \"\"\"\n    return _make.copy(data)\n\n\n@script\ndef _copy_shape_func_tensor(data_shape):\n    ndim = data_shape.shape[0]\n    out = output_tensor((ndim,), \"int64\")\n    for i in const_range(ndim):\n        out[i] = data_shape[i]\n    return out\n\n\n@script\ndef _copy_shape_func_scalar(data_shape):\n    out = output_tensor((), \"int64\")\n    return out\n\n\n@reg.register_shape_func(\"copy\", False)\ndef copy_shape_func(attrs, inputs, _):\n    \"\"\"\n    Shape function for copy op.\n    \"\"\"\n    input = inputs[0]\n    if len(input.shape) == 0:\n        return [_copy_shape_func_scalar(input)]\n    return [_copy_shape_func_tensor(input)]\n\n\ndef device_copy(data, src_device, dst_device):\n    \"\"\"Copy data from the source device to the destination device. This\n    operator helps data transferring between difference devices for\n    heterogeneous execution.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The tensor to be copied.\n\n    src_device : Union[:py:class:`Device`, str]\n        The source device where the data is copied from.\n\n    dst_device : Union[:py:class:`Device`, str]\n        The destination device where the data is copied to.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The copied result.\n    \"\"\"\n    return _make.DeviceCopy(\n        data, _make_virtual_device(src_device), _make_virtual_device(dst_device)\n    )\n\n\ndef shape_of(data, dtype=\"int32\"):\n    \"\"\"Get shape of a tensor.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The shape tensor.\n    \"\"\"\n    return _make.shape_of(data, dtype)\n\n\ndef ndarray_size(data, dtype=\"int32\"):\n    \"\"\"Get number of elements of input tensor.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The number of elements of input tensor.\n    \"\"\"\n    return _make.ndarray_size(data, dtype)\n\n\ndef isnan(data):\n    \"\"\"Check nan in input data element-wise.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.isnan(data)\n\n\ndef isfinite(data):\n    \"\"\"Compute element-wise finiteness of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.isfinite(data)\n\n\ndef isinf(data):\n    \"\"\"Compute element-wise infiniteness of data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.isinf(data)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=import-outside-toplevel\n\"\"\"Transform operators.\"\"\"\n\nfrom ...tir import expr as _expr\nfrom ..expr import Constant, Expr, Tuple, TupleWrapper, const\nfrom . import _make\nfrom .dyn import _make as _dyn_make\nfrom .tensor import shape_of\n\n\ndef sliding_window(data, axis, window_shape, strides):\n    \"\"\"Slide a window over the data tensor.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis : int\n        What axis the window begins sliding over. Window will be slid over\n        this axis and all following axes. The axis value determines the window\n        shape (and thus, the number of strides): window shape and strides must\n        both be of length `data.ndim-axis`.\n\n    window_shape : List[int]\n        The window shape to form over the input. Window shape must be of length\n        `data.ndim-axis`.\n\n    strides : List[int]\n        How to stride the window along each dimension. Strides must be of length\n        `data.ndim-axis`.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        # Slide a window of shape (3, 4, 5) over the x tensor, beginning with\n        # dimension 1, which slides the window over the two subtensors of\n        # shape (3, 32, 32).\n        x = relay.var(\"x\", relay.TensorType((2, 3, 32, 32), \"float32\"))\n        y = relay.sliding_window(x, 1, [3, 4, 5], [1, 2, 3])\n\n        data = np.random.rand(2, 3, 32, 32).astype(\"float32\")\n        result = create_executor().evaluate(y, {x: relay.const(data)}).numpy()\n\n        # The resulting shape still has batch size 2. Each dimension in\n        # (1, 15, 10) represents the locations where we were able to\n        # form a window; that is, we were able to place the window\n        # in one place along the dimension of length 3, 15 places along\n        # the dimension of length 32 (when striding by 2), and 10 places\n        # along the second dimension of length 32 (when striding by 3).\n        # The remaining dimension (3, 4, 5) represent the formed windows.\n        assert result.shape == (2, 1, 15, 10, 3, 4, 5)\n\n        assert np.array_equal(result[0, 0, 0, 0, :, :, :], data[0, :, 0:4, 0:5])\n        assert np.array_equal(result[1, 0, 7, 3, :, :, :], data[1, :, 14:18, 9:14])\n        assert np.array_equal(result[1, 0, 14, 9, :, :, :], data[1, :, 28:32, 27:32])\n    \"\"\"\n    from .. import _ffi_api as _relay_make\n\n    return _relay_make.sliding_window(data, axis, window_shape, strides)\n\n\ndef cast(data, dtype):\n    \"\"\"Cast input tensor to data type.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    dtype: str\n        The target data type\n\n    Returns\n    -------\n    result : relay.Expr\n        The casted result.\n    \"\"\"\n    from .. import _ffi_api as _relay_make\n\n    return _relay_make.cast(data, dtype)\n\n\ndef cast_like(data, dtype_like):\n    \"\"\"Cast input tensor to data type of another tensor.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    dtype_like: relay.Expr\n        The tensor to cast to.\n\n    Returns\n    -------\n    result : relay.Expr\n        The casted result.\n    \"\"\"\n    from .. import _ffi_api as _relay_make\n\n    return _relay_make.cast_like(data, dtype_like)\n\n\ndef reinterpret(data, dtype):\n    \"\"\"Reinterpret input tensor to data type.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    dtype: str\n        The target data type\n\n    Returns\n    -------\n    result : relay.Expr\n        The reinterpreted result.\n    \"\"\"\n    from .. import _make as _relay_make\n\n    return _relay_make.reinterpret(data, dtype)\n\n\ndef expand_dims(data, axis, num_newaxis=1):\n    \"\"\"Insert `num_newaxis` axes at the position given by `axis`.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis : Union[int, Expr]\n        The axis at which the input array is expanded.\n        Should lie in range `[-data.ndim - 1, data.ndim]`.\n        If `axis < 0`, it is the first axis inserted;\n        If `axis >= 0`, it is the last axis inserted in Python's negative indexing.\n\n    num_newaxis : int\n        Number of axes to be inserted. Should be >= 0.\n\n    Returns\n    -------\n    result : relay.Expr\n        The reshaped result.\n    \"\"\"\n    if isinstance(axis, int):\n        return _make.expand_dims(data, axis, num_newaxis)\n    if isinstance(axis, Expr):\n        # TODO (AndrewZhaoLuo): investigate performance issues with consecutive\n        # dynamic expand_dims on non-llvm targets.\n        return _dyn_make.expand_dims(data, axis, num_newaxis)\n    raise ValueError(f\"Unknown type for axis: {type(axis)}\")\n\n\ndef transpose(data, axes=None):\n    \"\"\"Permutes the dimensions of an array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axes : None or List[int]\n        The target axes order, reverse order if not specified.\n\n    Returns\n    -------\n    result : relay.Expr\n        The transposed result.\n    \"\"\"\n\n    if axes is not None:\n        axes = list(axes)\n    return _make.transpose(data, axes)\n\n\ndef squeeze(data, axis=None):\n    \"\"\"Squeeze axes in the array.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    axis : None or List[int] or Expr\n        The set of axes to remove.\n        If axis = None, remove all axis of dimensions 1.\n        If any specified axis has dimension that does not equal 1, it is an error.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The squeezed result.\n    \"\"\"\n    if isinstance(axis, Constant):\n        axis = list(axis.data.numpy())\n    if isinstance(axis, Expr):\n        return _dyn_make.squeeze(data, axis)\n    return _make.squeeze(data, axis)\n\n\ndef reshape(data, newshape, allowzero=False):\n    \"\"\"Reshape the input array.\n\n    To give user more convenience in without doing manual shape inference,\n    some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}.\n    The significance of each is explained below:\n\n    ``0`` copy this dimension from the input to the output shape.\n\n        .. code-block:: python\n\n            data.shape = (2,3,4), newshape = (4,0,2), result.shape = (4,3,2)\n            data.shape = (2,3,4), newshape = (2,0,0), result.shape = (2,3,4)\n\n    Note: If the parameter allowzero is manually set to true, it specifies a\n    special case where 0 actually means a true empty tensor.\n\n    ``-1`` infers the dimension of the output shape by using the remainder of\n    the input dimensions keeping the size of the new array same as that of the input array.\n    At most one dimension of shape can be -1.\n\n        .. code-block:: python\n\n            data.shape = (2,3,4), newshape = (6,1,-1), result.shape = (6,1,4)\n            data.shape = (2,3,4), newshape = (3,-1,8), result.shape = (3,1,8)\n            data.shape = (2,3,4), newshape = (-1,), result.shape = (24,)\n\n    ``-2`` copy all/remainder of the input dimensions to the output shape.\n\n        .. code-block:: python\n\n            data.shape = (2,3,4), newshape = (-2,), result.shape = (2,3,4)\n            data.shape = (2,3,4), newshape = (2,-2), result.shape = (2,3,4)\n            data.shape = (2,3,4), newshape = (-2,1,1), result.shape = (2,3,4,1,1)\n\n    ``-3`` use the product of two consecutive dimensions of the input shape\n    as the output dimension.\n\n        .. code-block:: python\n\n            data.shape = (2,3,4), newshape = (-3,4), result.shape = (6,4)\n            data.shape = (2,3,4,5), newshape = (-3,-3), result.shape = (6,20)\n            data.shape = (2,3,4), newshape = (0,-3), result.shape = (2,12)\n            data.shape = (2,3,4), newshape = (-3,-2), result.shape = (6,4)\n\n    ``-4`` split one dimension of the input into two dimensions passed subsequent\n    to -4 in shape (can contain -1).\n\n        .. code-block:: python\n\n            data.shape = (2,3,4), newshape = (-4,1,2,-2), result.shape = (1,2,3,4)\n            data.shape = (2,3,4), newshape = (2,-4,-1,3,-2), result.shape = (2,1,3,4)\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    newshape : Union[int, Tuple[int], List[int]] or relay.Expr\n        The new shape. Should be compatible with the original shape.\n\n    allowzero : Bool, optional\n        If true, then treat zero as true empty tensor rather than a copy instruction.\n\n    Returns\n    -------\n    result : relay.Expr\n        The reshaped result.\n    \"\"\"\n    if isinstance(newshape, Constant):\n        newshape = list(newshape.data.numpy())\n    if isinstance(newshape, Expr):\n        return _dyn_make.reshape(data, newshape, allowzero)\n    if isinstance(newshape, int):\n        newshape = [newshape]\n    if isinstance(newshape, (tuple, list)):\n        tempshape = []\n        for shape in newshape:\n            if isinstance(shape, _expr.IntImm):\n                tempshape.append(shape.value)\n            else:\n                try:\n                    tempshape.append(int(shape))\n                except ValueError as err:\n                    raise RuntimeError(\"Unrecognized shape type: %s\" % err)\n        newshape = tempshape\n    return _make.reshape(data, list(newshape), allowzero)\n\n\ndef argwhere(condition):\n    \"\"\"Find the indices of elements of a tensor that are\n    non-zero.\n\n    Parameters\n    ----------\n    condition : relay.Expr\n        The input condition tensor.\n\n    Returns\n    -------\n    out : relay.Expr\n        Tensor with the indices of elements that are non-zero.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        condition = [[True, False], [False, True]]\n        relay.argwhere(condition) = [[0, 0], [1, 1]]\n    \"\"\"\n    return _make.argwhere(condition)\n\n\ndef scatter(data, indices, updates, axis):\n    \"\"\"Update data at positions defined by indices with values in updates\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.scatter(data, indices, updates, axis)\n\n\ndef scatter_add(data, indices, updates, axis):\n    \"\"\"Update data by adding values in updates at positions defined by indices\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to add.\n\n    axis : int\n        The axis to scatter_add on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.scatter_add(data, indices, updates, axis)\n\n\ndef scatter_nd(data, indices, updates, mode=\"update\"):\n    \"\"\"Scatter values from an array and update.\n\n    See :py:func:`tvm.topi.scatter` for how data is scattered.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    mode : string\n        The accumulation mode for scatter. \"update\" or \"add\"\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.scatter_nd(data, indices, updates, mode)\n\n\ndef reshape_like(data, shape_like, lhs_begin=0, lhs_end=None, rhs_begin=0, rhs_end=None):\n    \"\"\"Reshapes the input tensor by the size of another tensor.\n    For an input tensor with shape ``(d0, d1, ..., d(k-1))``, `reshape_like` operation reshapes\n    the input tensor into an output tensor with the same shape as the second input tensor,\n    in particular reshaping the dimensions of `data` in `[lhs_begin, lhs_end)` using the dimensions\n    from `shape_like` in `[rhs_begin, rhs_end)`.\n\n    .. note::\n        Sizes for `data` and the output tensor should be compatible.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    shape_like : relay.Expr\n        The tensor to reshape data like. Should be compatible with the original shape on the\n        reshaped dimensions.\n\n    lhs_begin : int, optional\n        The axis of data to begin reshaping. Default is 0.\n\n    lhs_end : int or None, optional\n        The axis of data where reshaping should stop, exclusive. Default is None which reshapes to\n        the end.\n\n    rhs_begin : int, optional\n        The axis of shape_like where the target shape begins. Default is 0.\n\n    rhs_end : int or None, optional\n        The axis of shape_like where the target shape ends, exclusive. Default is None which extends\n        to the end.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data.shape == (1, 2, 3, 4)\n        shape_like.shape == (6, 2, 2, 3)\n\n        ret = relay.reshape_like(data, shape_like, lhs_begin=1, rhs_end=3)\n        ret.shape == (1, 6, 2, 2)\n    \"\"\"\n    return _make.reshape_like(data, shape_like, lhs_begin, lhs_end, rhs_begin, rhs_end)\n\n\ndef take(data, indices, axis=None, batch_dims=0, mode=\"clip\"):\n    \"\"\"Take elements from an array along an axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source array.\n\n    indices : rely.Expr\n        The indices of the values to extract.\n\n    axis : int, optional\n        The axis over which to select values. By default,\n        the flattened input array is used.\n\n    batch_dims : int\n        The number of batch dimensions. By default is 0.\n\n    mode : str, optional\n        Specifies how out-of-bound indices will behave [clip, wrap, fast].\n        clip: clip to the range (default).\n        wrap: wrap around the indices.\n        fast: no clip or wrap around (user must make sure indices are in-bound).\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.take(data, indices, batch_dims, axis, mode)\n\n\ndef full(fill_value, shape=(), dtype=\"\"):\n    \"\"\"Fill array with scalar value.\n\n    Parameters\n    ----------\n    fill_value : relay.Expr\n        The value to fill. Must be a scalar.\n\n    shape : tuple of int or relay.Expr\n        The shape of the target.\n\n    dtype : data type, optional (defaults to data type of the fill value)\n        The data type of the target.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    if isinstance(shape, Constant):\n        shape = list(shape.data.numpy())\n    if isinstance(shape, Expr):\n        return _dyn_make.full(fill_value, shape, dtype)\n    if isinstance(shape, int):\n        shape = [shape]\n    if isinstance(shape, (list, tuple)):\n        shape = list(shape)\n    return _make.full(fill_value, shape, dtype)\n\n\ndef full_like(data, fill_value):\n    \"\"\"Return a scalar value array with the same shape and type as the input array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n\n    fill_value : relay.Expr\n        The scalar value to fill.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    return _make.full_like(data, fill_value)\n\n\ndef arange(start, stop=None, step=None, dtype=\"float32\"):\n    \"\"\"Return evenly spaced values within a given interval.\n\n    .. note::\n        Similar to ``numpy.arange``, when only one argument is given, it is used\n        as `stop` instead of `start` while `start` takes default value 0.\n\n        Warning: Undefined behavior when dtype is incompatible with start/stop/step.\n        It could lead to different results compared to numpy, MXNet, pytorch, etc.\n\n    Parameters\n    ----------\n    start : tvm.Expr, optional\n        Start of interval. The interval includes this value. The default start\n        value is 0.\n\n    stop : tvm.Expr\n        Stop of interval. The interval does not include this value.\n\n    step : tvm.Expr, optional\n        Spacing between values. The default step size is 1.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        relay.arange(5) = [0, 1, 2, 3, 4]\n        relay.arange(1, 5) = [1, 2, 3, 4]\n        relay.arange(1, 5, 1.5) = [1, 2.5, 4]\n    \"\"\"\n    if step is None:\n        step = const(1, dtype)\n\n    if stop is None:\n        stop = start\n        start = const(0, dtype=dtype)\n\n    return _make.arange(start, stop, step, dtype)\n\n\ndef meshgrid(data, indexing=\"ij\"):\n    \"\"\"Create coordinate matrices from coordinate vectors.\n\n    .. note::\n        Similar to ``numpy.meshgrid``.\n\n    Parameters\n    ----------\n    data : Union(List[relay.Expr], Tuple[relay.Expr])\n        A list of tensors, which must be either scalars or 1-D vectors.\n\n    indexing : str\n        Indexing mode, either \"ij\" for matrix indexing or \"xy\" for Cartesian indexing.\n\n    Returns\n    -------\n    ret : relay.Tuple([relay.Expr, relay.Expr])\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [1, 2, 3]\n        y = [4, 5]\n\n        gx, gy = relay.meshgrid([x, y])\n\n        gx = [[1., 1.],\n              [2., 2.],\n              [3., 3.]]\n\n        gy = [[4., 5.],\n              [4., 5.],\n              [4., 5.]]\n    \"\"\"\n    data = list(data)\n    ret_size = len(data)\n    return TupleWrapper(_make.meshgrid(Tuple(data), indexing), ret_size)\n\n\ndef repeat(data, repeats, axis):\n    \"\"\"Repeats elements of an array.\n    By default, repeat flattens the input array into 1-D and then repeats the elements.\n\n    repeats : int\n        The number of repetitions for each element.\n\n    axis: int\n        The axis along which to repeat values. The negative numbers are interpreted\n        counting from the backward. By default, use the flattened input array, and\n        return a flat output array.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[1, 2], [3, 4]]\n        relay.repeat(x, repeats=2) = [1., 1., 2., 2., 3., 3., 4., 4.]\n\n        relay.repeat(x, repeats=2, axis=1) = [[1., 1., 2., 2.],\n                                              [3., 3., 4., 4.]]\n    \"\"\"\n    return _make.repeat(data, repeats, axis)\n\n\ndef tile(data, reps):\n    \"\"\"Repeats the whole array multiple times.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    reps : tuple of int or relay.Expr\n        The number of times repeating the tensor data.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[1, 2], [3, 4]]\n        relay.tile(x, reps=(2,3)) = [[1., 2., 1., 2., 1., 2.],\n                                     [3., 4., 3., 4., 3., 4.],\n                                     [1., 2., 1., 2., 1., 2.],\n                                     [3., 4., 3., 4., 3., 4.]]\n\n        relay.tile(x, reps=(2,)) = [[1., 2., 1., 2.],\n                                    [3., 4., 3., 4.]]\n\n    Notes\n    -----\n    Each dim size of reps must be a positive integer. If reps has length d,\n    the result will have dimension of max(d, data.ndim); If data.ndim < d,\n    data is promoted to be d-dimensional by prepending new axes.\n    If data.ndim >=  d, reps is promoted to a.ndim by pre-pending 1's to it.\n    \"\"\"\n    if isinstance(reps, Constant):\n        reps = list(reps.data.numpy())\n    if isinstance(reps, Expr):\n        return _dyn_make.tile(data, reps)\n    return _make.tile(data, reps)\n\n\ndef reverse(data, axis):\n    \"\"\"Reverses the order of elements along given axis while preserving array shape.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis: int\n        The axis along which to reverse elements.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[1., 2.], [3., 4.]]\n        relay.reverse(x, axis=0) = [[3., 4.], [1., 2.]]\n\n        relay.reverse(x, axis=1) = [[2., 1.], [4., 3.]]\n    \"\"\"\n    return _make.reverse(data, axis)\n\n\ndef reverse_sequence(data, seq_lengths, seq_axis=1, batch_axis=0):\n    \"\"\"Reverse the tensor for variable length slices.\n    Input is first sliced along batch axis and then elements are reversed along seq axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The tensor to be reversed.\n\n    seq_lengths : relay.Expr\n        A 1D Tensor with length a.dims[batch_axis]\n        Must be one of the following types: int32, int64\n        if seq_lengths[i] > a.dims[seq_axis], it is rounded to a.dims[seq_axis]\n        if seq_lengths[i] < 1, it is rounded to 1\n\n    seq_axis : int, optional\n        The axis along which the elements will be reversed. Default is 1.\n\n    batch_axis : int, optional\n        The axis along which the tensor will be sliced. Default is 0.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result of same shape and type as of input.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[0, 1, 2, 3],\n             [4, 5, 6, 7],\n             [8, 9, 10, 11],\n             [12, 13, 14, 15]]\n        relay.reverse(x, [1, 2, 3, 4], 0, 1) = [[0, 5, 10, 15],\n                                                [4, 1, 6, 11],\n                                                [8, 9, 2, 7],\n                                                [12, 13, 14, 3]]\n\n        relay.reverse(x, [1, 2, 3, 4], 1, 0) = [[0, 1, 2, 3],\n                                                [5, 4, 6, 7],\n                                                [10, 9, 8, 11],\n                                                [15, 14, 13, 12]]\n    \"\"\"\n    return _make.reverse_sequence(data, seq_lengths, seq_axis, batch_axis)\n\n\ndef where(condition, x, y):\n    \"\"\"Selecting elements from either x or y depending on the value of the\n    condition.\n\n    .. note::\n        Shapes of condition, x, and y must be broadcastable to a common shape.\n        Semantics follow numpy where function\n        https://numpy.org/doc/stable/reference/generated/numpy.where.html\n\n    Parameters\n    ----------\n    condition : relay.Expr\n        Where True, yield x, otherwise yield y\n\n    x : relay.Expr\n        The first array or scalar to be selected.\n\n    y : relay.Expr\n        The second array or scalar to be selected.\n\n    Returns\n    -------\n    result : relay.Expr\n        The selected array. The output shape is the broadcasted shape from\n        condition, x, and y.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[1, 2], [3, 4]]\n        y = [[5, 6], [7, 8]]\n        condition = [[0, 1], [-1, 0]]\n        relay.where(conditon, x, y) = [[5, 2], [3, 8]]\n\n        condition = [[1], [0]]\n        relay.where(conditon, x, y) = [[1, 2], [7, 8]]\n    \"\"\"\n    return _make.where(condition, x, y)\n\n\ndef broadcast_to(data, shape):\n    \"\"\"Return a scalar value array with the same type, broadcast to\n    the provided shape.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n\n    shape : tuple of int or relay.Expr\n        Provide the shape to broadcast to.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    if isinstance(shape, Constant):\n        shape = list(shape.data.numpy())\n    if isinstance(shape, Expr):\n        return _dyn_make.broadcast_to(data, shape)\n    if isinstance(shape, int):\n        shape = [shape]\n    if isinstance(shape, (list, tuple)):\n        shape = list(shape)\n    return _make.broadcast_to(data, shape)\n\n\ndef broadcast_to_like(data, broadcast_type):\n    \"\"\"Return a scalar value array with the same shape and type as the input array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n\n    broadcast_type : relay.Expr\n        Provide the type to broadcast to.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    return _make.broadcast_to_like(data, broadcast_type)\n\n\ndef collapse_sum_like(data, collapse_type):\n    \"\"\"Return a scalar value array with the same shape and type as the input array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n\n    collapse_type : relay.Expr\n        Provide the type to collapse to.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    return _make.collapse_sum_like(data, collapse_type)\n\n\ndef collapse_sum_to(data, shape):\n    \"\"\"Return a summation of data to the specified shape.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input tensor.\n\n    shape : relay.Expr\n        Shape to collapse to.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    if isinstance(shape, (list, tuple)):\n        shape = const(list(shape), \"int32\")\n    return _make.collapse_sum_to(data, shape)\n\n\ndef split(data, indices_or_sections, axis=0):\n    \"\"\"Split input tensor along axis by sections or indices.\n\n    If indices_or_sections is an integer, the input will be divided equally\n    along given axis. If such a split is not possible, an error is raised.\n\n    If indices_or_sections is a tuple of sorted integers,\n    the entries indicate where along axis the array is split.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source array.\n\n    indices_or_sections : int or tuple of int\n        Indices or sections to split into. Accepts an int or a tuple\n\n    axis : int, optional\n        The axis over which to split.\n\n    Returns\n    -------\n    ret : relay.Tuple([relay.Expr, relay.Expr])\n        The computed result.\n    \"\"\"\n    if isinstance(indices_or_sections, int):\n        ret_size = indices_or_sections\n    else:\n        ret_size = len(indices_or_sections) + 1\n    return TupleWrapper(_make.split(data, indices_or_sections, axis), ret_size)\n\n\ndef strided_slice(data, begin, end, strides=None, axes=None, slice_mode=\"end\"):\n    \"\"\"Strided slice of an array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source array to be sliced.\n\n    begin : relay.Expr, Tuple[int], or List[int]\n        The indices to begin with in the slicing.\n\n    end : relay.Expr, Tuple[int], or List[int]\n        Indices indicating end of the slice.\n\n    strides : relay.Expr, Tuple[int], or List[int], optional\n        Specifies the stride values, it can be negative in that case,\n        the input tensor will be reversed in that particular axis.\n\n    axes : Tuple[int] or List[int], optional\n        Axes along which slicing is applied. When it is specified, the length of begin, end,\n        strides, and axes must be equal. Moreover, begin, end, strides, and axes must be\n        static (cannot be relay.Expr). Axes argument for dynamic parameter slicing is\n        not supported yet.\n\n    slice_mode : str, optional\n        The slice mode [end, size].\n        end: The ending indices for the slice [default].\n        size: The input strides will be ignored, input end in this mode indicates\n        the size of a slice starting at the location specified by begin. If end[i]\n        is -1, all remaining elements in that dimension are included in the slice.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    strides = strides or [1]\n    if isinstance(begin, Constant):\n        begin = list(begin.data.numpy())\n    if isinstance(end, Constant):\n        end = list(end.data.numpy())\n    if isinstance(strides, Constant):\n        strides = list(strides.data.numpy())\n    if isinstance(begin, Expr) or isinstance(end, Expr) or isinstance(strides, Expr):\n        if isinstance(begin, (tuple, list)):\n            begin = const(list(begin))\n        if isinstance(end, (tuple, list)):\n            end = const(list(end))\n        if isinstance(strides, (tuple, list)):\n            strides = const(list(strides))\n\n        ishape = cast_like(shape_of(data), begin)\n        ishape_slice = slice_like(ishape, begin)\n        begin = _make.where(begin < cast_like(const(0), begin), begin + ishape_slice, begin)\n        begin = _make.where(begin >= ishape_slice, ishape_slice, begin)\n        # TODO(masahi): Support axes argument in dynamic strided slice\n        assert axes is None, \"Axes argument for dynamic parameter slicing is not supported yet.\"\n        return _dyn_make.strided_slice(data, begin, end, strides, slice_mode)\n    return _make.strided_slice(data, begin, end, strides, slice_mode, axes)\n\n\ndef strided_set(data, v, begin, end, strides=None):\n    \"\"\"Strided set of an array.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source array to be sliced.\n\n    v : relay.Expr\n        The data to be set.\n\n    begin: relay.Expr, Tuple[int], or List[int]\n        The indices to begin with in the slicing.\n\n    end: relay.Expr, Tuple[int], or List[int]\n        Indices indicating end of the slice.\n\n    strides: relay.Expr, Tuple[int], or List[int], optional\n        Specifies the stride values, it can be negative in that case,\n        the input tensor will be reversed in that particular axis.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    strides = strides or const([1], dtype=\"int32\")\n    if isinstance(begin, (tuple, list)):\n        begin = const(list(begin))\n    if isinstance(end, (tuple, list)):\n        end = const(list(end))\n    if isinstance(strides, (tuple, list)):\n        strides = const(list(strides))\n    return _make.strided_set(data, v, begin, end, strides)\n\n\ndef slice_like(data, shape_like, axes=None):\n    \"\"\"Slice the first input with respect to the second input.\n\n    For an input array with shape ``(d1, d2, ..., dk)``, `slice_like` operation slices the\n    the input array corresponding size of second array. By default will slice on all axes.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The source array.\n\n    shape_like : tvm.relay.Expr\n        The new shape.\n\n    axes : Optional[Tuple[int]]\n        List of axes on which input data will be sliced according to the corresponding size of\n        the second input. By default will slice on all axes. Negative axes mean counting in reverse.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.slice_like(data, shape_like, axes)\n\n\ndef layout_transform(data, src_layout, dst_layout):\n    \"\"\"Transform the layout of a tensor\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source tensor to be transformed\n\n    src_layout: str\n        The source layout.  (e.g NCHW)\n\n    dst_layout: str\n        The destination layout.  (e.g. NCHW16c)\n\n    Returns\n    -------\n    ret : relay.Expr\n        The transformed tensor.\n    \"\"\"\n    return _make.layout_transform(data, src_layout, dst_layout)\n\n\ndef reverse_reshape(data, newshape):\n    \"\"\"Reshapes the input array where the special values are inferred from\n    right to left.\n\n    The special values have the same semantics as :py:class:`tvm.relay.reshape`.\n    The difference is that special values are inferred from right to left. It\n    can be explained in the example below.\n\n    .. code-block:: python\n\n        data.shape = (10,5,4), newshape = (-1,0), reshape results in (40,5)\n        data.shape = (10,5,4), newshape = (-1,0), reverse_reshape results in (40,5)\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    newshape : Union[int, Tuple[int], List[int]]\n        The new shape. Should be compatible with the original shape.\n\n    Returns\n    -------\n    result : relay.Expr\n        The reshaped result.\n    \"\"\"\n    if isinstance(newshape, int):\n        newshape = [newshape]\n    return _make.contrib_reverse_reshape(data, list(newshape))\n\n\ndef gather(data, axis, indices):\n    \"\"\"Gather values along given axis from given indices.\n\n    E.g. for a 3D tensor, output is computed as:\n\n    .. code-block:: python\n\n        out[i][j][k] = data[indices[i][j][k]][j][k]  # if axis == 0\n        out[i][j][k] = data[i][indices[i][j][k]][k]  # if axis == 1\n        out[i][j][k] = data[i][j][indices[i][j][k]]  # if axis == 2\n\n    ``indices`` must have same shape as ``data``, except at dimension ``axis``\n    which must just be not null. Output will have same shape as ``indices``.\n\n    Parameters\n    ----------\n    data: relay.Expr\n        The input data to the operator.\n\n    axis: int\n        The axis along which to index. negative axis is supported.\n\n    indices: relay.Expr\n        The indices of values to gather.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [[1, 2], [3, 4]]\n        axis = 1\n        indices = [[0, 0], [1, 0]]\n        relay.gather(data, axis, indices) = [[1, 1], [4, 3]]\n    \"\"\"\n    return _make.gather(data, axis, indices)\n\n\ndef gather_nd(data, indices, batch_dims=0, index_rank=None):\n    \"\"\"Gather elements or slices from data and store to a tensor whose shape is\n    defined by indices.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The shape of output tensor.\n\n    batch_dims : int\n        The number of batch dimensions.\n\n    index_rank : int, optional\n        The size of an indexing tuple, which is a fixed value and the same as indices.shape[0]\n        Only needed when other dimensions of indices are dynamic.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [[0, 1], [2, 3]]\n        indices = [[1, 1, 0], [0, 1, 0]]\n        relay.gather_nd(data, indices) = [2, 3, 0]\n\n        data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n        indices = [[0, 1], [1, 0]]\n        relay.gather_nd(data, indices) = [[3, 4], [5, 6]]\n\n        data    = [[[0,1],[2,3]],[[4,5],[6,7]]]\n        indices = [[1, 0]]\n        relay.gather_nd(data, indices, batch_dims=1) = [[2,3],[4,5]]\n    \"\"\"\n    return _make.gather_nd(data, indices, batch_dims, index_rank)\n\n\ndef sequence_mask(data, valid_length, mask_value=0, axis=0):\n    \"\"\"Sets all elements outside the expected length of the sequence to a constant value.\n\n    This function takes an n-dimensional input array of the form [MAX_LENGTH, batch_size, ...] or\n    [batch_size, MAX_LENGTH, ...] and returns an array of the same shape.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data.\n\n    valid_length : relay.Expr\n        The expected (valid) length of each sequence in the tensor.\n\n    mask_value : float\n        The masking value.\n\n    axis : int\n        The axis of the length dimension.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[[  1.,   2.,   3.], [  4.,   5.,   6.]],\n             [[  7.,   8.,   9.], [ 10.,  11.,  12.]],\n             [[ 13.,  14.,   15.], [ 16.,  17.,   18.]]]\n\n       relay.sequence_mask(x, valid_length=[1, 1]) =\n            [[[  1.,   2.,   3.], [  4.,   5.,   6.]],\n             [[  0.,   0.,   0.], [  0.,   0.,   0.]],\n             [[  0.,   0.,   0.], [  0.,   0.,   0.]]]\n\n       relay.sequence_mask(x, valid_length=[2, 3], mask_value=0.1) =\n            [[[  1.,   2.,   3.], [  4.,   5.,   6.]],\n             [[  7.,   8.,   9.], [  10.,  11.,  12.]],\n             [[  0.1,  0.1,  0.1], [  16.,  17.,  18.]]]\n    \"\"\"\n    return _make.sequence_mask(data, valid_length, mask_value, axis)\n\n\ndef one_hot(indices, on_value, off_value, depth, axis, dtype):\n    \"\"\"\n    Returns a one-hot tensor where the locations repsented by indices take value on_value,\n    other locations take value off_value.\n    Final dimension is <indices outer dimensions> x depth x <indices inner dimensions>.\n\n    Parameters\n    ----------\n    indices : relay.Expr\n        Locations to set to on_value.\n\n    on_value : relay.Expr\n        Value to fill at indices.\n\n    off_value : relay.Expr\n        Value to fill at all other positions besides indices.\n\n    depth : int or relay.Expr\n        Depth of the one-hot dimension.\n\n    axis : int\n        Axis to fill.\n\n    dtype : str\n        Data type of the output tensor.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The one-hot tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        indices = [0, 1, 2]\n\n        relay.one_hot(indices, 3) =\n            [[1, 0, 0],\n             [0, 1, 0],\n             [0, 0, 1]]\n    \"\"\"\n    if isinstance(depth, Constant):\n        depth = depth.data.numpy().item()\n    if isinstance(depth, Expr):\n        return _dyn_make.one_hot(indices, on_value, off_value, depth, axis, dtype)\n    return _make.one_hot(indices, on_value, off_value, depth, axis, dtype)\n\n\ndef unravel_index(indices, shape):\n    \"\"\"Convert a flat index or array of flat indices into a tuple of coordinate arrays.\n\n    Example::\n    -   unravel_index([22, 41, 37], [7, 6]) = [[3, 6, 6],[4, 5, 1]]\n\n    Parameters\n    ----------\n    indices : relay.Expr\n        An integer array containing indices.\n\n    shape : relay.Expr\n        The shape of the array.\n\n    Returns\n    -------\n    result : relay.Expr\n        The tuple of coordinate arrays.\n    \"\"\"\n\n    return _make.unravel_index(indices, shape)\n\n\ndef sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0):\n    \"\"\"Converts a sparse representation into a dense tensor.\n\n    Example::\n    -   sparse_to_dense([[0, 0], [1, 1]], [2, 2], [3, 3], 0) = [[3, 0], [0, 3]]\n\n    Parameters\n    ----------\n    sparse_indices : relay.Expr\n        A 0-D, 1-D, or 2-D tensor of integers containing location of sparse values.\n\n    output_shape : relay.Expr\n        A list of integers. Shape of the dense output tensor.\n\n    sparse_values : relay.Expr\n        A 0-D or 1-D tensor containing the sparse values for the sparse indices.\n\n    default_value : relay.Expr\n        A 0-D tensor containing the default value for the remaining locations.\n        Defaults to 0.\n\n    Returns\n    -------\n    result : relay.Expr\n        Dense tensor of shape output_shape. Has the same type as sparse_values.\n    \"\"\"\n\n    if default_value == 0:\n        default_value = const(0)\n    if isinstance(output_shape, Expr):\n        return _dyn_make.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value)\n    return _make.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value)\n\n\ndef matrix_set_diag(data, diagonal, k=0, align=\"RIGHT_LEFT\"):\n    \"\"\"\n    Returns a tensor with the diagonals of input tensor replaced with the provided diagonal values.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Input Tensor.\n\n    diagonal : relay.Expr\n        Values to be filled in the diagonal.\n\n    k : int or tuple of int, optional\n        Diagonal Offset(s). The diagonal or range of diagonals to set. (0 by default)\n        Positive value means superdiagonal, 0 refers to the main diagonal, and\n        negative value means subdiagonals. k can be a single integer (for a single diagonal)\n        or a pair of integers specifying the low and high ends of a matrix band.\n        k[0] must not be larger than k[1].\n\n    align : string, optional\n        Some diagonals are shorter than max_diag_len and need to be padded.\n        align is a string specifying how superdiagonals and subdiagonals should be aligned,\n        respectively. There are four possible alignments: \"RIGHT_LEFT\" (default), \"LEFT_RIGHT\",\n        \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals to the right\n        (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing\n        format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n    Returns\n    -------\n    result : relay.Expr\n        New tensor with given diagonal values.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [[[7, 7, 7, 7],\n                 [7, 7, 7, 7],\n                 [7, 7, 7, 7]],\n                [[7, 7, 7, 7],\n                 [7, 7, 7, 7],\n                 [7, 7, 7, 7]]]\n\n        diagonal = [[1, 2, 3],\n                    [4, 5, 6]]\n\n        relay.matrix_set_diag(input, diagonal) =\n            [[[1, 7, 7, 7],\n              [7, 2, 7, 7],\n              [7, 7, 3, 7]],\n             [[4, 7, 7, 7],\n              [7, 5, 7, 7],\n              [7, 7, 6, 7]]]\n    \"\"\"\n    if isinstance(k, (tuple, list)):\n        k_one = k[0]\n        if len(k) >= 2:\n            k_two = k[1]\n        else:\n            k_two = k[0]\n    else:\n        k_one = k\n        k_two = k\n\n    super_diag_right_align = align[:5] == \"RIGHT\"\n    sub_diag_right_align = align[-5:] == \"RIGHT\"\n\n    return _make.matrix_set_diag(\n        data, diagonal, k_one, k_two, super_diag_right_align, sub_diag_right_align\n    )\n\n\ndef adv_index(inputs):\n    \"\"\"\n    Numpy style advanced indexing. Index with a list of tensors.\n\n    Parameters\n    ----------\n    inputs : Union(List[relay.Expr], Tuple[relay.Expr])\n        Input tensor and indices.\n        The first tensor is input data and rests are indices.\n\n    Returns\n    -------\n    result: relay.Expr\n        Output tensor.\n    \"\"\"\n    return _make.adv_index(Tuple(inputs))\n\n\ndef sparse_fill_empty_rows(sparse_indices, sparse_values, dense_shape, default_value):\n    \"\"\"\n    Fill rows in a sparse matrix that do no contain any values. Values are placed in the first\n    column of empty rows. The sparse array is in COO format.\n    It returns a TupleWrapper with 3 outputs\n\n    Parameters\n    ----------\n    sparse_indices : relay.Expr\n        A 2-D tensor[N, ndims] of integers containing location of sparse values, where N is\n        the number of sparse values and n_dim is the number of dimensions of the dense_shape.\n        The first column of this relay parameter must be sorted in ascending order.\n\n    sparse_values : relay.Expr\n        A 1-D tensor[N] containing the sparse values for the sparse indices.\n\n    dense_shape : relay.Expr\n        A 1-D tensor[ndims] which contains shape of the dense output tensor.\n\n    default_value : relay.Expr\n        A 1-D tensor[1] containing the default value for the remaining locations.\n\n    Returns\n    -------\n    new_sparse_indices : relay.Expr\n        A 2-D tensor[?, ndims] of integers containing location of new sparse\n        indices. The first column outputs must be sorted in ascending order.\n\n    new_sparse_values : relay.Expr\n        A 1-D tensor[?] containing the sparse values for the sparse indices.\n\n    empty_row_indicator : relay.Expr\n        A 1-D tensor[dense_shape[0]] filled with zeros and ones\n        indicating whether the particular row is empty or full respectively\n\n    Note\n    ----\n    This op exactly follows the documentation here:\n    https://www.tensorflow.org/api_docs/python/tf/sparse/fill_empty_rows\n    There are two exceptions:\n    1. Input Sparse Indices are expected to be in row-major order.\n    2. Empty Row Indicator has int64 output type with 1(for True) and 0(for False).\n\n    Examples\n    -------\n    .. code-block:: python\n\n        sparse_indices = [[0, 1],\n                         [0, 3],\n                         [2, 0],\n                         [3, 1]]\n        sparse_values = [1, 2, 3, 4]\n        default_value = [10]\n        dense_shape = [5, 6]\n        new_sparse_indices, empty_row_indicator, new_sparse_values, slice_element_index =\n                            relay.sparse_fill_empty_rows(\n                            sparse_indices,\n                            sparse_values,\n                            default_value,\n                            dense_shape)\n        new_sparse_indices = [[0, 1],\n                             [0, 3],\n                             [1, 0],\n                             [2, 0],\n                             [3, 1],\n                             [4, 0]]\n        empty_row_indicator = [False, True, False, False, True]\n        new_sparse_values = [1, 2, 10, 3, 4, 10]\n    \"\"\"\n    new_sparse_indices, new_sparse_values, empty_row_indicator = TupleWrapper(\n        _make.sparse_fill_empty_rows(sparse_indices, sparse_values, dense_shape, default_value), 3\n    )\n    new_sparse_indices = cast_like(new_sparse_indices, sparse_indices)\n    new_sparse_values = cast_like(new_sparse_values, sparse_values)\n    empty_row_indicator = cast(empty_row_indicator, \"bool\")\n\n    return Tuple((new_sparse_indices, new_sparse_values, empty_row_indicator))\n\n\ndef sparse_reshape(sparse_indices, prev_shape, new_shape):\n    \"\"\"\n    Reshape a Sparse Tensor. The sparse array is in COO format.\n\n    Parameters\n    ----------\n    sparse_indices : relay.Expr\n        A 2-D tensor[N, n_dim] of integers containing location of sparse values, where N is the\n        number of sparse values and n_dim is the number of dimensions of the dense_shape\n    prev_shape : relay.Expr\n        A 1-D tensor containing the previous shape of the dense tensor\n    new_shape : relay.Expr\n        A 1-D tensor containing the new shape of the dense tensor\n    Returns\n    -------\n    result: relay.Expr\n        Output tensor.\n    Examples\n    --------\n    .. code-block:: python\n\n        sparse_indices = [[0, 0, 0],\n                            [0, 0, 1],\n                            [0, 1, 0],\n                            [1, 0, 0],\n                            [1, 2, 3]]\n        prev_shape = [2, 3, 4]\n        new_shape = [9, -1]\n        new_sparse_indices, new_shape = relay.sparse_reshape(sparse_indices,\n                            prev_shape,\n                            new_shape)\n        new_sparse_indices = [[0, 0],\n                              [0, 1],\n                              [1, 2],\n                              [4, 2],\n                              [8, 1]]\n        new_shape = [9, 4]\n    \"\"\"\n    return TupleWrapper(_make.sparse_reshape(sparse_indices, prev_shape, new_shape), 2)\n\n\ndef segment_sum(data, segment_ids, num_segments=None):\n    \"\"\"\n    Computes the sum along segment_ids along axis 0. If multiple segment_ids reference the same\n    location their contributions add up.\n    result[index, j, k, ...] = \u03a3i... data[i, j, k,..] where index = segment_ids[i]\n    This op is much better understood with visualization articulated in the following links and\n    examples at the end of this docstring.\n\n    https://www.tensorflow.org/api_docs/python/tf/math/unsorted_segment_sum\n    https://caffe2.ai/docs/sparse-operations.html#null__unsorted-segment-reduction-ops\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Input Tensor. It can be of any type and multi-dimensional\n    segment_ids : relay.Expr\n        A 1-D int32/int64 tensor containing the segment_ids of the rows to calculate the output\n        sum upon. It defines a mapping from the zeroth dimension of data onto segment_ids. The\n        segment_ids tensor should be the size of the first dimension, d0, with consecutive IDs\n        in the range 0 to k, where k<d0. In particular, a segmentation of a matrix tensor is a\n        mapping of rows to segments. This tensor doesn't need to be sorted\n    num_segments : Optional[int]\n        An integer describing the shape of the zeroth dimension. If unspecified, its calculated\n        equivalent to the number of unique segment_ids\n    Returns\n    -------\n    result: relay.Expr\n        Output tensor.\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [[1, 2, 3, 4],\n                [4, -3, 2, -1],\n                [5, 6, 7, 8]]\n        segment_ids = [0, 0, 1]\n        result = segment_sum(data, segment_ids)\n        result = [[5, -1, 5, 3],[5, 6, 7, 8]]\n\n        data = [[1, 2, 3, 4],\n                [4, -3, 2, -1],\n                [5, 6, 7, 8]]\n        segment_ids = [2, 0, 0]\n        num_segments = 3\n        result = segment_sum(data, segment_ids, num_segments)\n        result = [[5, 6, 7, 8],[0, 0, 0, 0], [5, -1, 5, 3]]\n    \"\"\"\n\n    one_tensor = cast_like(const([1]), segment_ids)\n    if num_segments:\n        if isinstance(num_segments, int):\n            max_segments = const([num_segments])\n            max_segments = cast_like(max_segments, segment_ids)\n        else:\n            max_segments = cast_like(num_segments, segment_ids)\n    else:\n        max_segments = _make.add(reshape(_make.max(segment_ids, [0], False, False), -1), one_tensor)\n\n    data_offrow_shape = strided_slice(_make.shape_of(data, \"int32\"), [1], [-1], slice_mode=\"size\")\n    data_offrow_shape = cast_like(data_offrow_shape, max_segments)\n    new_shape = _make.concatenate(Tuple([max_segments, data_offrow_shape]), 0)\n    segment_ids_tiled_shape = _make.concatenate(\n        Tuple([reverse(data_offrow_shape, 0), one_tensor]), 0\n    )\n    expanded_segment_ids = tile(segment_ids, segment_ids_tiled_shape)\n    scatter_add_segment_ids = transpose(expanded_segment_ids)\n    src = cast_like(_dyn_make.zeros(new_shape, \"float64\"), data)\n    return scatter_add(src, scatter_add_segment_ids, data, axis=0)\n\n\ndef cumsum(data, axis=None, dtype=None, exclusive=None):\n    \"\"\"Numpy style cumsum op. Return the cumulative inclusive sum of the elements along\n    a given axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative sum is computed. The default (None) is to compute\n        the cumsum over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are summed.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If true will return exclusive sum in which the first element is not\n        included. In other terms, if true, the j-th output element would be\n        the sum of the first (j-1) elements. Otherwise, it would be the sum of\n        the first j elements.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        a = [[1,2,3], [4,5,6]]\n\n        cumsum(a)  # if axis is not provided, cumsum is done over the flattened input.\n        -> [ 1,  3,  6, 10, 15, 21]\n\n        cumsum(a, dtype=\"float32\")\n        -> [  1.,   3.,   6.,  10.,  15.,  21.]\n\n        cumsum(a, axis=0)  # sum over rows for each of the 3 columns\n        -> [[1, 2, 3],\n            [5, 7, 9]]\n\n        cumsum(a, axis=1)\n        -> [[ 1,  3,  6],\n            [ 4,  9, 15]]\n\n        a = [1, 0, 1, 0, 1, 1, 0]  # a is a boolean array\n        cumsum(a, dtype=int32)  # dtype should be provided to get the expected results\n        -> [1, 1, 2, 2, 3, 4, 4]\n    \"\"\"\n    return _make.cumsum(data, axis, dtype, exclusive)\n\n\ndef cumprod(data, axis=None, dtype=None, exclusive=None):\n    \"\"\"Numpy style cumprod op. Return the cumulative inclusive product of the elements along\n    a given axis.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative product is computed. The default (None) is to compute\n        the cumprod over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are multiplied.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If true will return exclusive product in which the first element is not\n        included. In other terms, if true, the j-th output element would be\n        the product of the first (j-1) elements. Otherwise, it would be the product of\n        the first j elements. The product of zero elements will be 1.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        a = [[1,2,3], [4,5,6]]\n\n        cumprod(a)  # if axis is not provided, cumprod is done over the flattened input.\n        -> [ 1,  2,  6, 24, 120, 720]\n\n        cumprod(a, dtype=\"float32\")\n        -> [  1.,  2.,  6., 24., 120., 720.]\n\n        cumprod(a, axis=0)  # multiply over rows for each of the 3 columns\n        -> [[1, 2, 3],\n            [4, 10, 18]]\n\n        cumprod(a, axis=1)\n        -> [[ 1,  2,  6],\n            [ 4,  20, 120]]\n\n        a = [1, 1, 1, 0, 1, 1, 0]  # a is a boolean array\n        cumprod(a, dtype=int32)  # dtype should be provided to get the expected results\n        -> [1, 1, 1, 0, 0, 0, 0]\n    \"\"\"\n    return _make.cumprod(data, axis, dtype, exclusive)\n\n\ndef unique(data, is_sorted=True, return_counts=False):\n    \"\"\"\n    Find the unique elements of a 1-D tensor. Please note `output` and `counts` are all padded to\n    have the same length of `data` and element with index >= num_unique[0] has undefined value.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        A 1-D tensor of integers.\n\n    is_sorted : bool\n        Whether to sort the unique elements in ascending order before returning as output.\n\n    return_counts : bool\n        Whether to return the count of each unique element.\n\n    Returns\n    -------\n    unique : relay.Expr\n        A 1-D tensor containing the unique elements of the input data tensor.\n\n    indices : relay.Expr\n        A 1-D tensor containing the index of each data element in the output tensor.\n\n    inverse_indices : relay.Expr\n        A 1-D tensor. For each entry in data, it contains the index of that data element in the\n        unique array.\n\n    num_unique : relay.Expr\n        A 1-D tensor with size=1 containing the number of unique elements in the input data tensor.\n\n    counts (optional) : relay.Expr\n        A 1-D tensor containing the count of each unique element in the output.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, False)\n        output         =  [4, 5, 1, 2, 3, _, _, _]\n        indices        =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique     =  [5]\n\n        [output, indices, num_unique, counts] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, True)\n        output         =  [4, 5, 1, 2, 3, _, _, _]\n        indices        =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique     =  [5]\n        counts         =  [2, 2, 1, 1, 2, _, _, _]\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], True)\n        output         =  [1, 2, 3, 4, 5, _, _, _]\n        indices        =  [3, 4, 0, 1, 2, 2, 3, 4]\n        num_unique     =  [5]\n    \"\"\"\n    if return_counts:\n        return TupleWrapper(_make.unique(data, is_sorted, return_counts), 5)\n    return TupleWrapper(_make.unique(data, is_sorted, return_counts), 4)\n\n\ndef invert_permutation(data):\n    \"\"\"Computes the inverse permutation of data.\n    This operation computes the inverse of an index permutation.\n    It takes a 1-D integer tensor x, which represents the indices of a zero-based\n    array and swaps each value with its index position.\n\n    For an output tensor y and an input tensor x, this operation computes the following:\n    y[x[i]] = i for i in [0, 1, ..., len(x) - 1]\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The source data to be invert permuated.\n\n    Returns\n    -------\n    ret : relay.Expr\n        Invert permuated data. Has the same type as data.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [3, 4, 0, 2, 1]\n        relay.invert_permutation(data) = [2, 4, 3, 0, 1]\n    \"\"\"\n    return _make.invert_permutation(data)\n\n\ndef stft(\n    data, n_fft, hop_length=None, win_length=None, window=None, normalized=False, onesided=True\n):\n    \"\"\"\n    The STFT computes the Fourier transform of short overlapping windows of the input.\n    This gives frequency components of the signal as they change over time.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Either a 1-D tensor or a 2-D batch tensor.\n\n    n_fft : int\n        The size of Fourier transform\n\n    hop_length : int, optional\n        The distance between neighboring sliding window frames. If is None,\n        it is treated as equal to floor(n_fft / 4).\n\n    win_length : int, optional\n        The size of window frame and STFT filter. If is None, it is treated as equal to n_fft.\n\n    window : relay.Expr, optional\n        A 1-D tensor window frame. If is None (default), it is treated as if\n        having 1 everywhere in the window.\n\n    normalized : bool, optional\n        Whether to return the normalized STFT results. Default value is False.\n\n    onesided : bool, optional\n        Whether to return onesided result or fill with conjugate symmetry. Default value is True.\n\n    Returns\n    -------\n    output : relay.Expr\n        Tensor containing the STFT result with shape [batch, N, T, 2], where N is the\n        number of frequencies where STFT is applied and T is the total number of frames used.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [1, 2, 3, 4, 5, 6]\n        window = [4, 3, 2]\n        [n_fft, hop_length, win_length, normalized, onesided] = [3, 3, 3, False, True]\n        relay.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n        -> [[[15.0000,  0.0000], [34.0000,  0.0000]], [[ 4.5000,  0.8660], [ 1.0000, -1.7321]]]\n    \"\"\"\n    if hop_length is None:\n        hop_length = n_fft // 4\n\n    if win_length is None:\n        win_length = n_fft\n\n    if window is None:\n        window = _make.ones([n_fft], \"int32\")\n\n    return _make.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n\n\ndef trilu(data, k, upper=True):\n    \"\"\"\n    Given a 2-D matrix or batches of 2-D matrices, returns the\n    upper or lower triangular part of the tensor.\n\n    Parameters\n    ----------\n    data: relay.Expr\n        The tensor that trilu will be applied to. Must be either\n        a 2D matrix or a tensor of batches of 2D matrices.\n\n    k: int\n        The number of diagonals above or below the main diagonal\n        to exclude or include.\n\n    upper: bool, optional\n        If True, only upper triangular values of input are kept,\n        if False, the lower triangular values are kept.\n\n\n    Returns\n    -------\n    ret : relay.Expr\n        The new tensor with appropriate diagonals set to zero.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[0, 1, 2],\n             [3, 4, 5],\n             [6, 7, 8]]\n\n        relay.trilu(x, True, 0) =\n            [[0, 1, 2],\n             [0, 4, 5],\n             [0, 0, 8]]\n    \"\"\"\n    if not isinstance(k, Expr):\n        k = const(k, dtype=\"int32\")\n    return _make.trilu(data, k, upper)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Vision network related operators.\"\"\"\nfrom .multibox import *\nfrom .nms import *\nfrom .rcnn import *\nfrom .yolo import *\nfrom . import _rcnn\nfrom . import _yolo\nfrom . import _vision\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.vision._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/_rcnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Faster R-CNN and Mask R-CNN operations.\"\"\"\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nfrom .. import op as reg\nfrom .. import strategy\nfrom ..op import OpPattern\n\n# roi_align\nreg.register_strategy(\"vision.roi_align\", strategy.roi_align_strategy)\nreg.register_pattern(\"vision.roi_align\", OpPattern.OUT_ELEMWISE_FUSABLE)\n\n\n@reg.register_convert_op_layout(\"vision.roi_align\")\ndef convert_roi_align(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for roi_align op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current roi_align\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and rois inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    data, rois = inputs\n    new_attrs = dict(attrs)\n    assert (\n        len(desired_layouts) == 2\n    ), \"A desired layout is expected for both of vision.roi_align's inputs\"\n\n    desired_data_layout, desired_rois_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    assert desired_rois_layout == \"default\", \"Rois layout must be default\"\n\n    new_attrs[\"layout\"] = desired_data_layout\n    # rois layout not change\n    if desired_data_layout in [\"NCHW\", \"NHWC\"]:\n        return relay.vision.roi_align(data, rois, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported.\" % desired_data_layout)\n\n\n@reg.register_convert_op_layout(\"vision.roi_pool\")\ndef convert_roi_pool(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for roi_pool op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current roi_pool\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and rois inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    data, rois = inputs\n    new_attrs = dict(attrs)\n    assert (\n        len(desired_layouts) == 2\n    ), \"A desired layout is expected for both of vision.roi_pool's inputs\"\n\n    desired_data_layout, desired_rois_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n    assert desired_rois_layout == \"default\", \"Rois layout must be default\"\n\n    new_attrs[\"layout\"] = desired_data_layout\n    # rois layout not change\n    if desired_data_layout in [\"NCHW\", \"NHWC\"]:\n        return relay.vision.roi_pool(data, rois, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported.\" % desired_data_layout)\n\n\n# roi_pool\n@reg.register_compute(\"vision.roi_pool\")\ndef compute_roi_pool(attrs, inputs, _):\n    \"\"\"Compute definition of roi_pool\"\"\"\n    assert attrs.layout == \"NCHW\", \"only support nchw for now\"\n    return [\n        topi.vision.rcnn.roi_pool_nchw(\n            inputs[0],\n            inputs[1],\n            pooled_size=get_const_tuple(attrs.pooled_size),\n            spatial_scale=attrs.spatial_scale,\n        )\n    ]\n\n\nreg.register_schedule(\"vision.roi_pool\", strategy.schedule_roi_pool)\nreg.register_pattern(\"vision.roi_pool\", OpPattern.OUT_ELEMWISE_FUSABLE)\n\n# proposal\nreg.register_strategy(\"vision.proposal\", strategy.proposal_strategy)\nreg.register_pattern(\"vision.proposal\", OpPattern.OPAQUE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/_vision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Definition of vision ops\"\"\"\nfrom __future__ import absolute_import\n\nfrom tvm import topi\nfrom tvm.te.hybrid import script\nfrom tvm.runtime import convert\n\nfrom .. import op as reg\nfrom .. import strategy\nfrom ..op import OpPattern\n\n# multibox_prior\nreg.register_strategy(\"vision.multibox_prior\", strategy.multibox_prior_strategy)\nreg.register_pattern(\"vision.multibox_prior\", OpPattern.OPAQUE)\n\n\n# multibox_transform_loc\nreg.register_strategy(\"vision.multibox_transform_loc\", strategy.multibox_transform_loc_strategy)\nreg.register_pattern(\"vision.multibox_transform_loc\", OpPattern.OPAQUE)\n\n\n# Get counts of valid boxes\nreg.register_strategy(\"vision.get_valid_counts\", strategy.get_valid_counts_strategy)\nreg.register_pattern(\"vision.get_valid_counts\", OpPattern.OPAQUE)\n\n\n# non-maximum suppression\nreg.register_strategy(\"vision.non_max_suppression\", strategy.nms_strategy)\nreg.register_pattern(\"vision.non_max_suppression\", OpPattern.OPAQUE)\n\nreg.register_strategy(\"vision.all_class_non_max_suppression\", strategy.all_class_nms_strategy)\nreg.register_pattern(\"vision.all_class_non_max_suppression\", OpPattern.OPAQUE)\n\n\n@script\ndef _get_valid_counts_shape_func(data_shape):\n    valid_counts_shape = output_tensor((1,), \"int64\")\n    out_tensor_shape = output_tensor((data_shape.shape[0],), \"int64\")\n    out_indices_shape = output_tensor((2,), \"int64\")\n\n    valid_counts_shape[0] = data_shape[0]\n    for i in const_range(data_shape.shape[0]):\n        out_tensor_shape[i] = data_shape[i]\n    out_indices_shape[0] = data_shape[0]\n    out_indices_shape[1] = data_shape[1]\n\n    return valid_counts_shape, out_tensor_shape, out_indices_shape\n\n\n@reg.register_shape_func(\"vision.get_valid_counts\", False)\ndef get_valid_counts_shape_func(attrs, inputs, _):\n    return _get_valid_counts_shape_func(inputs[0])\n\n\n@script\ndef _nms_shape_func(data_shape):\n    out_shape = output_tensor((2,), \"int64\")\n    count_shape = output_tensor((2,), \"int64\")\n\n    out_shape[0] = data_shape[0]\n    out_shape[1] = data_shape[1]\n    count_shape[0] = data_shape[0]\n    count_shape[1] = int64(1)\n    return out_shape, count_shape\n\n\n@reg.register_shape_func(\"vision.non_max_suppression\", False)\ndef nms_shape_func(attrs, inputs, _):\n    if attrs.return_indices:\n        return _nms_shape_func(inputs[0])\n    return [topi.math.identity(inputs[0])]\n\n\n@script\ndef _all_class_nms_shape_func_onnx(boxes_shape, scores_shape):\n    out_shape = output_tensor((2,), \"int64\")\n    count_shape = output_tensor((1,), \"int64\")\n\n    out_shape[0] = boxes_shape[0] * scores_shape[1] * boxes_shape[1]\n    out_shape[1] = int64(3)\n    count_shape[0] = int64(1)\n    return out_shape, count_shape\n\n\n@script\ndef _all_class_nms_shape_func_tf(boxes_shape, scores_shape):\n    out_indices_shape = output_tensor((3,), \"int64\")\n    out_scores_shape = output_tensor((2,), \"int64\")\n    count_shape = output_tensor((1,), \"int64\")\n\n    out_indices_shape[0] = boxes_shape[0]\n    out_indices_shape[1] = scores_shape[1] * boxes_shape[1]\n    out_indices_shape[2] = int64(2)\n    out_scores_shape[0] = boxes_shape[0]\n    out_scores_shape[1] = scores_shape[1] * boxes_shape[1]\n    count_shape[0] = boxes_shape[0]\n\n    return out_indices_shape, out_scores_shape, count_shape\n\n\n@reg.register_shape_func(\"vision.all_class_non_max_suppression\", False)\ndef all_class_nms_shape_func(attrs, inputs, _):\n    if attrs.output_format == \"onnx\":\n        return _all_class_nms_shape_func_onnx(inputs[0], inputs[1])\n    return _all_class_nms_shape_func_tf(inputs[0], inputs[1])\n\n\n@script\ndef _roi_align_shape_func_nchw(data_shape, rois_shape, pooled_size):\n    out = output_tensor((4,), \"int64\")\n    out[0] = rois_shape[0]\n    out[1] = data_shape[1]\n    out[2] = int64(pooled_size[0])\n    out[3] = int64(pooled_size[1])\n    return out\n\n\n@script\ndef _roi_align_shape_func_nhwc(data_shape, rois_shape, pooled_size):\n    out = output_tensor((4,), \"int64\")\n    out[0] = rois_shape[0]\n    out[1] = int64(pooled_size[0])\n    out[2] = int64(pooled_size[1])\n    out[3] = data_shape[3]\n    return out\n\n\n@reg.register_shape_func(\"vision.roi_align\", False)\ndef roi_align_shape_func(attrs, inputs, _):\n    if attrs.layout == \"NCHW\":\n        return [_roi_align_shape_func_nchw(inputs[0], inputs[1], convert(attrs.pooled_size))]\n    assert attrs.layout == \"NHWC\", \"layout must be NCHW or NHWC.\"\n    return [_roi_align_shape_func_nhwc(inputs[0], inputs[1], convert(attrs.pooled_size))]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/_yolo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Backend compiler related feature registration\"\"\"\nfrom __future__ import absolute_import\nfrom ..op import register_pattern, OpPattern\nfrom ..op import register_injective_schedule\n\n# reorg\nregister_pattern(\"vision.yolo_reorg\", OpPattern.INJECTIVE)\nregister_injective_schedule(\"vision.yolo_reorg\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/multibox.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Multibox operations.\"\"\"\nfrom tvm.relay import expr\nfrom . import _make\n\n\ndef multibox_prior(\n    data, sizes=(1.0,), ratios=(1.0,), steps=(-1.0, -1.0), offsets=(0.5, 0.5), clip=False\n):\n    \"\"\"Generate prior(anchor) boxes from data, sizes and ratios.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data tensor.\n\n    sizes : tuple of float, optional\n        Tuple of sizes for anchor boxes.\n\n    ratios : tuple of float, optional\n        Tuple of ratios for anchor boxes.\n\n    steps : Tuple of float, optional\n        Priorbox step across y and x, -1 for auto calculation.\n\n    offsets : tuple of int, optional\n        Priorbox center offsets, y and x respectively.\n\n    clip : boolean, optional\n        Whether to clip out-of-boundary boxes.\n\n    Returns\n    -------\n    out : relay.Expr\n        3-D tensor with shape [1, h_in * w_in * (num_sizes + num_ratios - 1), 4]\n    \"\"\"\n    return _make.multibox_prior(data, sizes, ratios, steps, offsets, clip)\n\n\ndef multibox_transform_loc(\n    cls_prob, loc_pred, anchor, clip=True, threshold=0.01, variances=(0.1, 0.1, 0.2, 0.2)\n):\n    \"\"\"Location transformation for multibox detection\n\n    Parameters\n    ----------\n    cls_prob : tvm.relay.Expr\n        Class probabilities.\n\n    loc_pred : tvm.relay.Expr\n        Location regression predictions.\n\n    anchor : tvm.relay.Expr\n        Prior anchor boxes.\n\n    clip : boolean, optional\n        Whether to clip out-of-boundary boxes.\n\n    threshold : double, optional\n        Threshold to be a positive prediction.\n\n    variances : Tuple of float, optional\n        variances to be decoded from box regression output.\n\n    Returns\n    -------\n    ret : tuple of tvm.relay.Expr\n    \"\"\"\n    return expr.TupleWrapper(\n        _make.multibox_transform_loc(cls_prob, loc_pred, anchor, clip, threshold, variances), 2\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/nms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Non-maximum suppression operations.\"\"\"\nfrom tvm.relay import expr\nfrom . import _make\n\n\ndef get_valid_counts(data, score_threshold, id_index=0, score_index=1):\n    \"\"\"Get valid count of bounding boxes given a score threshold.\n    Also moves valid boxes to the top of input data.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Input data. 3-D tensor with shape [batch_size, num_anchors, 6].\n\n    score_threshold : optional, float\n        Lower limit of score for valid bounding boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    score_index: optional, int\n        Index of the scores/confidence of boxes.\n\n    Returns\n    -------\n    valid_count : relay.Expr\n        1-D tensor for valid number of boxes.\n\n    out_tensor : relay.Expr\n        Rearranged data tensor.\n\n    out_indices: relay.Expr\n        Indices in input data\n    \"\"\"\n    if not isinstance(score_threshold, expr.Expr):\n        score_threshold = expr.const(score_threshold, \"float32\")\n    return expr.TupleWrapper(\n        _make.get_valid_counts(data, score_threshold, id_index, score_index), 3\n    )\n\n\ndef non_max_suppression(\n    data,\n    valid_count,\n    indices,\n    max_output_size=-1,\n    iou_threshold=0.5,\n    force_suppress=False,\n    top_k=-1,\n    coord_start=2,\n    score_index=1,\n    id_index=0,\n    return_indices=True,\n    invalid_to_bottom=False,\n):\n    \"\"\"Non-maximum suppression operator for object detection.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        3-D tensor with shape [batch_size, num_anchors, 6]\n        or [batch_size, num_anchors, 5].\n        The last dimension should be in format of\n        [class_id, score, box_left, box_top, box_right, box_bottom]\n        or [score, box_left, box_top, box_right, box_bottom]. It could\n        be the second output out_tensor of get_valid_counts.\n\n    valid_count : relay.Expr\n        1-D tensor for valid number of boxes. It could be the output\n        valid_count of get_valid_counts.\n\n    indices: relay.Expr\n        2-D tensor with shape [batch_size, num_anchors], represents\n        the index of box in original data. It could be the third\n        output out_indices of get_valid_counts. The values in the\n        second dimension are like the output of arange(num_anchors)\n        if get_valid_counts is not used before non_max_suppression.\n\n    max_output_size : int or relay.Expr, optional\n        Max number of output valid boxes for each instance.\n        Return all valid boxes if the value of max_output_size is less than 0.\n\n    iou_threshold : float or relay.Expr, optional\n        Non-maximum suppression threshold.\n\n    force_suppress : bool, optional\n        Suppress all detections regardless of class_id.\n\n    top_k : int, optional\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    coord_start : int, optional\n        The starting index of the consecutive 4 coordinates.\n\n    score_index : int, optional\n        Index of the scores/confidence of boxes.\n\n    id_index : int, optional\n        index of the class categories, -1 to disable.\n\n    return_indices : bool, optional\n        Whether to return box indices in input data.\n\n    invalid_to_bottom : bool, optional\n        Whether to move all valid bounding boxes to the top.\n\n    Returns\n    -------\n    out : relay.Expr or relay.Tuple\n        return relay.Expr if return_indices is disabled, a 3-D tensor\n        with shape [batch_size, num_anchors, 6] or [batch_size, num_anchors, 5].\n        If return_indices is True, return relay.Tuple of two 2-D tensors, with\n        shape [batch_size, num_anchors] and [batch_size, num_valid_anchors] respectively.\n    \"\"\"\n    if not isinstance(max_output_size, expr.Expr):\n        max_output_size = expr.const(max_output_size, \"int32\")\n    if not isinstance(iou_threshold, expr.Expr):\n        iou_threshold = expr.const(iou_threshold, \"float32\")\n    out = _make.non_max_suppression(\n        data,\n        valid_count,\n        indices,\n        max_output_size,\n        iou_threshold,\n        force_suppress,\n        top_k,\n        coord_start,\n        score_index,\n        id_index,\n        return_indices,\n        invalid_to_bottom,\n    )\n    if return_indices:\n        return expr.TupleWrapper(out, 2)\n    return out\n\n\ndef all_class_non_max_suppression(\n    boxes,\n    scores,\n    max_output_boxes_per_class=-1,\n    iou_threshold=-1.0,\n    score_threshold=-1.0,\n    output_format=\"onnx\",\n):\n    \"\"\"Non-maximum suppression operator for object detection, corresponding to ONNX\n    NonMaxSuppression and TensorFlow combined_non_max_suppression.\n    NMS is performed for each class separately.\n\n    Parameters\n    ----------\n    boxes : relay.Expr\n        3-D tensor with shape (batch_size, num_boxes, 4)\n\n    scores: relay.Expr\n        3-D tensor with shape (batch_size, num_classes, num_boxes)\n\n    max_output_boxes_per_class : int or relay.Expr, optional\n        The maxinum number of output selected boxes per class\n\n    iou_threshold : float or relay.Expr, optionaIl\n        IoU test threshold\n\n    score_threshold : float or relay.Expr, optional\n        Score threshold to filter out low score boxes early\n\n    output_format : string, optional\n        \"onnx\" or \"tensorflow\". Specify by which frontends the outputs are\n        intented to be consumed.\n\n    Returns\n    -------\n    out : relay.Tuple\n        If `output_format` is \"onnx\", the output is a relay.Tuple of two tensors, the first is\n        `indices` of size `(batch_size * num_class* num_boxes , 3)` and the second is a scalar\n        tensor `num_total_detection` of shape `(1,)` representing the total number of selected\n        boxes. The three values in `indices` encode batch, class, and box indices.\n        Rows of `indices` are ordered such that selected boxes from batch 0, class 0 come first,\n        in descending of scores, followed by boxes from batch 0, class 1 etc. Out of\n        `batch_size * num_class* num_boxes` rows of indices,  only the first `num_total_detection`\n        rows are valid.\n\n        If `output_format` is \"tensorflow\", the output is a relay.Tuple of three tensors, the first\n        is `indices` of size `(batch_size, num_class * num_boxes , 2)`, the second is `scores` of\n        size `(batch_size, num_class * num_boxes)`, and the third is `num_total_detection` of size\n        `(batch_size,)` representing the total number of selected boxes per batch. The two values\n        in `indices` encode class and box indices. Of num_class * num_boxes boxes in `indices` at\n        batch b, only the first `num_total_detection[b]` entries are valid. The second axis of\n        `indices` and `scores` are sorted within each class by box scores, but not across classes.\n        So the box indices and scores for the class 0 come first in a sorted order, followed by\n        the class 1 etc.\n    \"\"\"\n    if not isinstance(max_output_boxes_per_class, expr.Expr):\n        max_output_boxes_per_class = expr.const(max_output_boxes_per_class, \"int32\")\n    if not isinstance(iou_threshold, expr.Expr):\n        iou_threshold = expr.const(iou_threshold, \"float32\")\n    if not isinstance(score_threshold, expr.Expr):\n        score_threshold = expr.const(score_threshold, \"float32\")\n\n    out = _make.all_class_non_max_suppression(\n        boxes,\n        scores,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        output_format,\n    )\n\n    if output_format == \"onnx\":\n        return expr.TupleWrapper(out, 2)\n\n    return expr.TupleWrapper(out, 3)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/rcnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Faster R-CNN and Mask R-CNN operations.\"\"\"\nfrom . import _make\n\n\ndef roi_align(data, rois, pooled_size, spatial_scale, sample_ratio=-1, layout=\"NCHW\", mode=\"avg\"):\n    \"\"\"ROI align operator.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        4-D tensor with shape [batch, channel, height, width]\n\n    rois : relay.Expr\n        2-D tensor with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : list/tuple of two ints\n        output size\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    sample_ratio : int\n        Optional sampling ratio of ROI align, using adaptive size by default.\n\n    mode : str, Optional\n        The pooling method. Relay supports two methods, 'avg' and 'max'. Default is 'avg'.\n\n    Returns\n    -------\n    output : relay.Expr\n        4-D tensor with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    return _make.roi_align(data, rois, pooled_size, spatial_scale, sample_ratio, layout, mode)\n\n\ndef roi_pool(data, rois, pooled_size, spatial_scale, layout=\"NCHW\"):\n    \"\"\"ROI pool operator.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        4-D tensor with shape [batch, channel, height, width]\n\n    rois : relay.Expr\n        2-D tensor with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : list/tuple of two ints\n        output size\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    Returns\n    -------\n    output : relay.Expr\n        4-D tensor with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    return _make.roi_pool(data, rois, pooled_size, spatial_scale, layout)\n\n\ndef proposal(\n    cls_prob,\n    bbox_pred,\n    im_info,\n    scales,\n    ratios,\n    feature_stride,\n    threshold,\n    rpn_pre_nms_top_n,\n    rpn_post_nms_top_n,\n    rpn_min_size,\n    iou_loss,\n):\n    \"\"\"Proposal operator.\n\n    Parameters\n    ----------\n    cls_prob : relay.Expr\n        4-D tensor with shape [batch, 2 * num_anchors, height, width].\n\n    bbox_pred : relay.Expr\n        4-D tensor with shape [batch, 4 * num_anchors, height, width].\n\n    im_info : relay.Expr\n        2-D tensor with shape [batch, 3]. The last dimension should be in format of\n        [im_height, im_width, im_scale]\n\n    scales : list/tuple of float\n        Scales of anchor windows.\n\n    ratios : list/tuple of float\n        Ratios of anchor windows.\n\n    feature_stride : int\n        The size of the receptive field each unit in the convolution layer of the rpn, for example\n        the product of all stride's prior to this layer.\n\n    threshold : float\n        Non-maximum suppression threshold.\n\n    rpn_pre_nms_top_n : int\n        Number of top scoring boxes to apply NMS. -1 to use all boxes.\n\n    rpn_post_nms_top_n : int\n        Number of top scoring boxes to keep after applying NMS to RPN proposals.\n\n    rpn_min_size : int\n        Minimum height or width in proposal.\n\n    iou_loss : bool\n        Usage of IoU loss.\n\n    Returns\n    -------\n    output : relay.Expr\n        2-D tensor with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of\n        [batch_index, w_start, h_start, w_end, h_end].\n    \"\"\"\n    return _make.proposal(\n        cls_prob,\n        bbox_pred,\n        im_info,\n        scales,\n        ratios,\n        feature_stride,\n        threshold,\n        rpn_pre_nms_top_n,\n        rpn_post_nms_top_n,\n        rpn_min_size,\n        iou_loss,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vision/yolo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Yolo operations.\"\"\"\nfrom . import _make\n\n\ndef yolo_reorg(data, stride):\n    \"\"\"Yolo reorg operation used in darknet models.\n    This layer shuffles the input tensor values based on the stride value.\n    Along with the shuffling, it does the shape transform.\n    If '(n, c, h, w)' is the data shape and 's' is stride, output shape is '(n, c*s*s, h/s, w/s)'.\n\n    Example:\n\n    .. code-block:: python\n\n        data(1, 4, 2, 2) = [[[[ 0  1] [ 2  3]]\n                            [[ 4  5] [ 6  7]]\n                            [[ 8  9] [10 11]]\n                            [[12 13] [14 15]]]]\n        stride = 2\n        ret(1, 16, 1, 1) = [[[[ 0]]  [[ 2]]  [[ 8]]  [[10]]\n                            [[ 1]]  [[ 3]]  [[ 9]]  [[11]]\n                            [[ 4]]  [[ 6]]  [[12]]  [[14]]\n                            [[ 5]]  [[ 7]]  [[13]]  [[15]]]]\n\n    .. note::\n\n        stride=1 has no significance for reorg operation.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data tensor.\n\n    stride : int\n        The stride value for reorganisation.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.yolo_reorg(data, stride)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vm/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Dialect operators for Relay VM.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .vm import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vm/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for relay.op.vm\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.op.vm\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/op/vm/vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return,invalid-name,len-as-condition,too-many-nested-blocks\n\"\"\"Dialect operators for Relay VM.\"\"\"\nfrom . import _ffi_api\n\n\ndef shape_of(expr):\n    \"\"\"Invoke a function to get the shape of a tensor.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The expr used to evaluate its tensor shape.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The expression with the evaluated tensor shape.\n    \"\"\"\n    return _ffi_api.shape_of(expr)\n\n\ndef invoke_tvm_op(func, inputs, outputs):\n    \"\"\"Call a primitive function with the TVM operator calling convention.\n\n    Parameters\n    ----------\n    func : tvm.relay.Expr\n        The input expr.\n\n    inputs : tvm.relay.Expr\n        A tuple of the inputs to pass to the TVM function.\n\n    outputs : tvm.relay.Expr\n        A tuple of the outputs to pass to the TVM function.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The invoke_tvm_op call node.\n    \"\"\"\n    return _ffi_api.invoke_tvm_op(func, inputs, outputs)\n\n\ndef shape_func(func, inputs, outputs, is_inputs):\n    \"\"\"Invoke the shape function of the passed function.\n\n    Parameters\n    ----------\n    func : tvm.relay.Expr\n        The primitive function from which to compute the shape function.\n\n    inputs : tvm.relay.Tuple\n        The tupled inputs.\n\n    outputs : tvm.relay.Tuple\n        The tupled outputs.\n\n    is_inputs : List[bool]\n        A boolean list indicating whether the shape function should expect\n        shape or input at each position.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The shape function expression.\n    \"\"\"\n    return _ffi_api.shape_func(func, inputs, outputs, is_inputs)\n\n\ndef reshape_tensor(data, shape, newshape):\n    \"\"\"Invoke the VM ReshapeTensor instruction.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data.\n\n    shape : tvm.relay.Expr\n        The newshape tensor.\n\n    newshape : List[tvm.ir.PrimExpr]\n        The new shape.\n    \"\"\"\n    return _ffi_api.reshape_tensor(data, shape, newshape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/param_dict.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Helper utility to save parameter dicts.\"\"\"\nimport tvm.runtime\n\n\ndef save_param_dict(params):\n    \"\"\"Save parameter dictionary to binary bytes.\n\n    The result binary bytes can be loaded by the\n    GraphModule with API \"load_params\".\n\n    .. deprecated:: 0.9.0\n        Use :py:func:`tvm.runtime.save_param_dict` instead.\n\n    Parameters\n    ----------\n    params : dict of str to NDArray\n        The parameter dictionary.\n\n    Returns\n    -------\n    param_bytes: bytearray\n        Serialized parameters.\n\n    Examples\n    --------\n    .. code-block:: python\n\n       # set up the parameter dict\n       params = {\"param0\": arr0, \"param1\": arr1}\n       # save the parameters as byte array\n       param_bytes = tvm.runtime.save_param_dict(params)\n       # We can serialize the param_bytes and load it back later.\n       # Pass in byte array to module to directly set parameters\n       tvm.runtime.load_param_dict(param_bytes)\n    \"\"\"\n    return tvm.runtime.save_param_dict(params)\n\n\ndef load_param_dict(param_bytes):\n    \"\"\"Load parameter dictionary to binary bytes.\n\n    .. deprecated:: 0.9.0\n        Use :py:func:`tvm.runtime.load_param_dict` instead.\n\n    Parameters\n    ----------\n    param_bytes: bytearray\n        Serialized parameters.\n\n    Returns\n    -------\n    params : dict of str to NDArray\n        The parameter dictionary.\n    \"\"\"\n    return tvm.runtime.load_param_dict(param_bytes)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/prelude.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name\n\"\"\"A prelude containing useful global functions and ADT definitions.\"\"\"\nfrom tvm.ir import IRModule, TypeCall\nfrom tvm.tir import Any\nfrom tvm.relay.transform import ToANormalFormExpr\n\nfrom .ty import GlobalTypeVar, TensorType, scalar_type\nfrom .expr import Var, GlobalVar, If, const\nfrom .function import Function\nfrom .op.tensor import add, subtract, equal\nfrom .adt import Constructor, TypeData, Clause, Match\nfrom .adt import PatternConstructor, PatternVar, PatternWildcard\nfrom . import op, transform\nfrom .analysis import free_vars\n\n\ndef get_tensor_array_shape(expr, dtype, prelude):\n    \"\"\"Get the static shape of a tensor array if it has fixed rank shape.\n\n    By design, static ADT tensor in TVM has type name in the format\n    of static_tensor_dim0_dim1_..._dimN_t.\n\n    Parameters\n    ----------\n    expr : Relay Expr\n        Input expression.\n\n    dtype : str\n        Data type.\n\n    prelude : Prelude\n        Tensor array prelude\n\n    Returns\n    -------\n    shape : tuple of (int, Any) or None\n        The output shape. None if input tensor array\n        has dynamic shape.\n    \"\"\"\n    mod = prelude.mod\n    mod[\"main\"] = Function(free_vars(expr), expr)\n    mod = transform.InferType()(mod)\n    checked_type = mod[\"main\"].body.checked_type\n    assert isinstance(checked_type, TypeCall), \"Input must be a tensor array.\"\n    ta_type_str = checked_type.args[0].func.name_hint\n    static_ta_ty_start = \"static_tensor_{}\".format(dtype)\n    if ta_type_str.startswith(static_ta_ty_start):\n        shape_str = ta_type_str.replace(\"{}_\".format(static_ta_ty_start), \"\").replace(\"_t\", \"\")\n        shape = []\n        if \"scalar\" not in shape_str:\n            for dim_str in shape_str.split(\"_\"):\n                if dim_str in [\"?\", \"any\"]:\n                    shape.append(Any())\n                else:\n                    shape.append(int(dim_str))\n        return tuple(shape)\n    return None\n\n\ndef _get_name_static(canonical, dtype, shape, batch_dim=None, extra_shapes=None):\n    \"\"\"Get name for static shape tensor array op\n\n    By design, static ADT tensor in TVM has type name in the format\n    of static_tensor_dim0_dim1_..._dimN_t\n    or static_tensor_batch1_dim0_dim1_..._dimN_t if tensorlist stack only have one item.\n\n    Parameters\n    ----------\n    canonical : String\n        Tensor array op name\n\n    dtype : str\n        Data type.\n\n    shape : tuple of (int, Any) or None\n        Tensor array shape\n\n    batch_dim: None or int\n        1 if tensorlist stack only have one item.\n        None by default\n\n    Returns\n    -------\n    name : String\n        The tensor array op name\n    \"\"\"\n    shape_str = _to_str(shape)\n\n    if extra_shapes is not None:\n        for n, s in extra_shapes.items():\n            extra_shape_str = \"_{}_{}\".format(n, _to_str(s))\n            shape_str += extra_shape_str\n\n    if len(shape_str) == 0:\n        shape_str = \"scalar\"\n    if canonical == \"tensor_t\":\n        return \"static_tensor_{}_{}_t\".format(dtype, shape_str)\n    if batch_dim is None or canonical in [\"tensor_constructor\", \"tensor_nil\"]:\n        return \"{}_{}_{}\".format(canonical, dtype, shape_str)\n    if batch_dim != 1:\n        return \"{}_{}_{}\".format(canonical, dtype, shape_str)\n    return \"{}_{}_batch{}_{}\".format(canonical, dtype, str(batch_dim), shape_str)\n\n\ndef _to_str(shape):\n    dim_names = []\n    for dim in shape:\n        if isinstance(dim, Any):\n            dim_names.append(\"any\")\n        else:\n            dim_names.append(str(dim))\n    return \"_\".join(dim_names)\n\n\nclass StaticTensorArrayOps(object):\n    \"\"\"Contains tensor array related ops for fixed rank tensor array\"\"\"\n\n    def __init__(self, prelude, dtype, shape, batch_dim=None):\n        \"\"\"Create tensor array ops registry\"\"\"\n        self.prelude = prelude\n        self.dtype = dtype\n        self.shape = shape\n        self.batch_dim = batch_dim\n        self.list, self.cons, self.nil = self.prelude.mod.get_type(\"List\")\n\n    def get_name(self, canonical, extra_shapes=None):\n        \"\"\"Get name corresponding to the canonical name\"\"\"\n        return _get_name_static(canonical, self.dtype, self.shape, self.batch_dim, extra_shapes)\n\n    def get_global_var(self, canonical):\n        \"\"\"Get global corresponding to the canonical name\"\"\"\n        return self.prelude.get_global_var_static(canonical, self.dtype, self.shape, self.batch_dim)\n\n    def get_type(self, canonical):\n        \"\"\"Get type corresponding to the canonical name\"\"\"\n        return self.prelude.get_type_static(canonical, self.dtype, self.shape)\n\n    def get_ctor(self, canonical):\n        \"\"\"Get ctor corresponding to the canonical name\"\"\"\n        return self.prelude.get_ctor_static(\"tensor_t\", canonical, self.dtype, self.shape)\n\n    def define_tensor_adt(self):\n        \"\"\"Defines the static tensor ADT, which is the container for tensors\n        with fixed shapes.\"\"\"\n        tensor_type_name = self.get_name(\"tensor_t\")\n\n        # This is effectively functioning as a monomorphizer.\n        # TODO(@jroesch): we should add full shape polymoprhism\n        # and do monomorphization.\n        #\n        # Skip register if tensor type is already registered.\n        global_type_names = set()\n        for g_ty_var in self.prelude.mod.get_global_type_vars():\n            global_type_names.add(g_ty_var.name_hint)\n\n        if tensor_type_name in global_type_names:\n            self.tensor_type_var = self.get_type(\"tensor_t\")\n            return\n\n        self.tensor_type_var = GlobalTypeVar(tensor_type_name)\n\n        tensor_type = TensorType(self.shape, self.dtype)\n        tensor_constructor_name = self.get_name(\"tensor_constructor\")\n\n        tensor_nil_name = self.get_name(\"tensor_nil\")\n        tensor_nil_case = Constructor(tensor_nil_name, [], self.tensor_type_var)\n        tensor_case = Constructor(tensor_constructor_name, [tensor_type], self.tensor_type_var)\n\n        self.prelude.mod[self.tensor_type_var] = TypeData(\n            self.tensor_type_var, [], [tensor_nil_case, tensor_case]\n        )\n\n    def define_tensor_array(self):\n        \"\"\"Defines a function to create a tensor array with size n.\n        tensor_array(n) : Tensor[(), int32] -> list[tensor_t]\n        \"\"\"\n        tensor_array_constructor_name = self.get_name(\"tensor_array\")\n        tensor_array_constructor_var = self._create_global_var(tensor_array_constructor_name)\n\n        tensor_nil_var = self.get_ctor(\"tensor_nil\")\n        tensor_type_var = self.get_ctor(\"tensor_t\")\n        n = Var(\"x\", scalar_type(\"int32\"))\n        body = If(\n            equal(n, const(0)),\n            self.nil(),\n            self.cons(tensor_nil_var(), tensor_array_constructor_var(subtract(n, const(1)))),\n        )\n        self.prelude.mod[tensor_array_constructor_var] = Function(\n            [n], body, self.list(tensor_type_var()), []\n        )\n\n    def define_tensor_take(self):\n        \"\"\"Defines a function to return a range of tensor_t on axis 0.\n        tensor_take(t, lower, upper) :\n        tensor_t -> Tensor[(), int32] -> Tensor[(), int32] -> tensor_t\n        \"\"\"\n        # We don't register take for scalar tensor.\n        ndim = len(self.shape)\n        if ndim == 0:\n            return\n\n        take_name = self.get_name(\"tensor_take\")\n\n        if self.is_cached(take_name):\n            return\n\n        take_var = GlobalVar(take_name)\n\n        origin_tensor_constructor = self.get_ctor(\"tensor_constructor\")\n\n        output_shape = [\n            Any(),\n        ] + list(self.shape[1:])\n        tensor_type_var, tensor_constructor, _ = self._get_adt_by_shape(output_shape)\n\n        t = Var(\"tensor\", self.tensor_type_var())\n        lower = Var(\"lower\", scalar_type(\"int32\"))\n        upper = Var(\"upper\", scalar_type(\"int32\"))\n        tvar = Var(\"t\")\n        case = Clause(\n            PatternConstructor(origin_tensor_constructor, [PatternVar(tvar)]),\n            tensor_constructor(op.take(tvar, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        self.prelude.mod[take_var] = Function(\n            [t, lower, upper], Match(t, [case], False), tensor_type_var(), []\n        )\n\n    def define_tensor_concatenate(self):\n        \"\"\"Defines a function to concatenate two tensor_t on axis 0.\n        tensor_concatenate(t) : tensor_t -> tensor_t -> tensor_t\n        \"\"\"\n        # We don't register concatenate for scalar tensor.\n        ndim = len(self.shape)\n        if ndim == 0:\n            return\n\n        concat_name = self.get_name(\"tensor_concatenate\")\n        concat_var = GlobalVar(concat_name)\n        if self.is_cached(concat_name):\n            return\n\n        output_shape = [\n            Any(),\n        ] + list(self.shape[1:])\n        tensor_type_var, tensor_constructor, _ = self._get_adt_by_shape(output_shape)\n\n        origin_tensor_constructor = self.get_ctor(\"tensor_constructor\")\n        origin_tensor_type_var = self.tensor_type_var\n        x = Var(\"x\", origin_tensor_type_var())\n        y = Var(\"y\", origin_tensor_type_var())\n        t1 = Var(\"t1\")\n        t2 = Var(\"t2\")\n\n        case = Clause(\n            PatternConstructor(origin_tensor_constructor, [PatternVar(t1)]),\n            Match(\n                y,\n                [\n                    Clause(\n                        PatternConstructor(origin_tensor_constructor, [PatternVar(t2)]),\n                        tensor_constructor(op.concatenate([t1, t2], axis=0)),\n                    )\n                ],\n                False,\n            ),\n        )\n\n        self.prelude.mod[concat_var] = Function(\n            [x, y], Match(x, [case], False), tensor_type_var(), []\n        )\n\n    def define_tensor_expand_dims(self):\n        \"\"\"Defines a function to grow a tensor_t's rank by adding one dimension in front\n        of the original tensor_t.\n        tensor_expand_dims(t) : tensor_t -> tensor_t\n        \"\"\"\n        expand_dims_name = self.get_name(\"tensor_expand_dims\")\n        expand_dims_var = self._create_global_var(expand_dims_name)\n        setattr(self.prelude, expand_dims_name, expand_dims_var)\n        origin_tensor_type_var = self.tensor_type_var\n        origin_tensor_constructor = self.get_ctor(\"tensor_constructor\")\n        x = Var(\"x\", origin_tensor_type_var())\n\n        # Note: we set the added axis to be Any() instead of 1 due to\n        # in stack op, we need to recursively concatenate.\n        new_axis = Any() if self.batch_dim is None or self.batch_dim != 1 else self.batch_dim\n        tensor_type_var, tensor_constructor, _ = self._get_adt_by_shape(\n            [\n                new_axis,\n            ]\n            + list(self.shape)\n        )\n        t = Var(\"t\")\n        case = Clause(\n            PatternConstructor(origin_tensor_constructor, [PatternVar(t)]),\n            tensor_constructor(op.expand_dims(t, 0, 1)),\n        )\n\n        self.prelude.mod[expand_dims_var] = Function(\n            [x], Match(x, [case], False), tensor_type_var(), []\n        )\n\n    def define_tensor_array_read(self):\n        \"\"\"Defines a function to get the nth element of a list. Assume the list has at least one\n        element.\n        tensor_array_read(ta, n) : list[static_tensor_t] -> Tensor[(), int32] ->\n        Tensor[self.shape, self.dtype]\n        \"\"\"\n        read_name = self.get_name(\"tensor_array_read\")\n\n        if self.is_cached(read_name):\n            return\n\n        read_var = GlobalVar(read_name)\n\n        tensor_array = Var(\"tensor_array\", self.list(self.tensor_type_var()))\n        n = Var(\"x\", scalar_type(\"int32\"))\n        self.prelude.mod[read_var] = Function(\n            [tensor_array, n], self.prelude.nth(tensor_array, n), self.tensor_type_var(), []\n        )\n\n    def is_cached(self, name):\n        try:\n            self.prelude.mod.get_global_var(name)\n            return True\n        except ValueError:\n            return False\n\n    def define_tensor_array_write(self):\n        \"\"\"Defines a function to update a tensor array at index n with value v.\n        tensor_array_write(ta, n, v) :\n            list[static_tensor_t] -> Tensor[(), int32] -> Tensor[self.shape, self.dtype] ->\n            list[static_tensor_t]\n        \"\"\"\n        write_name = self.get_name(\"tensor_array_write\")\n        if self.is_cached(write_name):\n            return\n\n        write_var = GlobalVar(write_name)\n        tensor_array = Var(\"tensor_array\", self.list(self.tensor_type_var()))\n        n = Var(\"x\", scalar_type(\"int32\"))\n        v = Var(\"v\", self.tensor_type_var())\n        self.prelude.mod[write_var] = Function(\n            [tensor_array, n, v],\n            self.prelude.update(tensor_array, n, v),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t in a tensor array.\n        tensor_array_unstack_tensor(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        ndim = len(self.shape)\n        # We don't register unstack for scalar tensor array\n        if ndim == 0:\n            return\n\n        helper_name = self.get_name(\"tensor_array_unstack_helper\")\n        helper_var = self._create_global_var(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType(self.shape, self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n        tensor_var = Var(\"tensor\", TensorType(self.shape, self.dtype))\n\n        reduced_tensor_type_var, tensor_constructor, _ = self._get_adt_by_shape(self.shape[1:])\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                tensor_constructor(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(reduced_tensor_type_var()), []\n        )\n\n        unstack_name = self.get_name(\"tensor_array_unstack\")\n        unstack_var = self._create_global_var(unstack_name)\n        setattr(self.prelude, unstack_name, unstack_var)\n        shape = op.shape_of(tensor_var)\n        unstack_length = op.take(shape, const(0))\n        self.prelude.mod[unstack_var] = Function(\n            [tensor_var],\n            helper_var(const(0), unstack_length, tensor_var),\n            self.list(reduced_tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_scatter(self, indices_shape=None, force_update=False):\n        \"\"\"Defines a function to scatter the values of a tensor_t in indices of a tensor array.\n        tensor_array_scatter(ta, indices, value) :\n            list[tensor_t] -> Tensor[(Any), int32] -> tensor_t -> list[tensor_t]\n\n        Set static indices shape by specifying indices_shape.\n        Set force_update to get static indices shape operator.\n        \"\"\"\n        # When this operator has already been registered, only update\n        # when force_update is set. This should be used only when we need to\n        # redefine this op for static indices shape.\n\n        extra_shapes = {\"indices\": indices_shape} if indices_shape is not None else None\n        tensor_array_scatter_name = self.get_name(\"tensor_array_scatter\", extra_shapes)\n        if hasattr(self.prelude, tensor_array_scatter_name) and not force_update:\n            return\n\n        tensor_array_scatter_helper_name = self.get_name(\n            \"tensor_array_scatter_helper\", extra_shapes\n        )\n\n        tensor_array_scatter_helper_var = self._create_global_var(tensor_array_scatter_helper_name)\n        ta = Var(\"ta\", self.list(self.tensor_type_var()))\n        current = Var(\"current\", scalar_type(\"int32\"))\n        limit = Var(\"limit\", scalar_type(\"int32\"))\n        indices_ = Var(\"indices_\", TensorType(indices_shape or [Any()], \"int32\"))\n        values_ = Var(\"values_\", self.list(self.tensor_type_var()))\n        write_var = self.get_global_var(\"tensor_array_write\")\n        read_var = self.get_global_var(\"tensor_array_read\")\n        helper_body = If(\n            equal(current, limit),\n            ta,\n            tensor_array_scatter_helper_var(\n                write_var(ta, op.take(indices_, current), read_var(values_, current)),\n                add(current, const(1)),\n                limit,\n                indices_,\n                values_,\n            ),\n        )\n        self.prelude.mod[tensor_array_scatter_helper_var] = Function(\n            [ta, current, limit, indices_, values_],\n            helper_body,\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n        tensor_array_scatter_var = self._create_global_var(tensor_array_scatter_name)\n        setattr(self.prelude, tensor_array_scatter_name, tensor_array_scatter_var)\n        tensor_array = Var(\"tensor_array\", self.list(self.tensor_type_var()))\n\n        indices = Var(\"indices\", TensorType(indices_shape or [Any()], \"int32\"))\n        values = Var(\"values\", self.list(self.tensor_type_var()))\n        if indices_shape is None:\n            indices_shape = op.shape_of(indices)\n            limit = op.take(indices_shape, const(0))\n        else:\n            limit = const(indices_shape[0])\n\n        body = tensor_array_scatter_helper_var(tensor_array, const(0), limit, indices, values)\n        self.prelude.mod[tensor_array_scatter_var] = Function(\n            [tensor_array, indices, values], body, self.list(self.tensor_type_var()), []\n        )\n\n    def define_tensor_array_split(self, value_shape=None, lengths_shape=None, force_update=False):\n        \"\"\"Defines a function to split the values of a tensor_t into a tensor array.\n        tensor_array_split(ta, value, lengths) :\n            list[tensor_t] -> tensor_t -> Tensor[(Any), int32] -> list[tensor_t]\n\n        Set static value and lengths shapes by specifying value_shape and lengths_shape.\n        Set force_update to get static value and lengths shape operator.\n        \"\"\"\n        # Skip scalar case\n        ndim = len(self.shape)\n        if ndim == 0:\n            return\n\n        # When this operator has already been registered, only update\n        # when force_update is set. This should be used only when we need to\n        # redefine this op for static value/indices shape.\n        split_name = self.get_name(\"tensor_array_split\")\n\n        if self.is_cached(split_name):\n            if not force_update:\n                return\n            tensor_array_split_helper_var = self.get_global_var(\"ta_split_helper\")\n            split_var = self.get_global_var(\"tensor_array_split\")\n        else:\n            tensor_array_split_helper_name = self.get_name(\"ta_split_helper\")\n            tensor_array_split_helper_var = GlobalVar(tensor_array_split_helper_name)\n            split_var = GlobalVar(split_name)\n\n        output_shape = [\n            Any(),\n        ] + list(self.shape[1:])\n        output_tensor_type_var, _, output_ops = self._get_adt_by_shape(output_shape)\n        output_ops.define_tensor_array_write()\n        write_var = output_ops.get_global_var(\"tensor_array_write\")\n\n        if value_shape is None:\n            value_type_var = self.tensor_type_var\n            take_var = self.get_global_var(\"tensor_take\")\n        else:\n            value_type_var, _, value_adts = self._get_adt_by_shape(value_shape)\n            value_adts.define_tensor_take()\n            take_var = value_adts.get_global_var(\"tensor_take\")\n\n        ta1 = Var(\"tensor_array\", self.list(output_tensor_type_var()))\n        value1 = Var(\"value1\", value_type_var())\n        offset1 = Var(\"offset1\", scalar_type(\"int32\"))\n        current1 = Var(\"current1\", scalar_type(\"int32\"))\n        limit1 = Var(\"limit1\", scalar_type(\"int32\"))\n        lengths1 = Var(\"lengths\", TensorType(lengths_shape or [Any()], \"int32\"))\n\n        helper1_body = If(\n            equal(current1, limit1),\n            ta1,\n            write_var(\n                tensor_array_split_helper_var(\n                    ta1,\n                    value1,\n                    add(offset1, op.take(lengths1, current1)),\n                    add(current1, const(1)),\n                    limit1,\n                    lengths1,\n                ),\n                current1,\n                take_var(value1, offset1, add(op.take(lengths1, current1), offset1)),\n            ),\n        )\n\n        self.prelude.mod[tensor_array_split_helper_var] = Function(\n            [ta1, value1, offset1, current1, limit1, lengths1],\n            helper1_body,\n            self.list(output_tensor_type_var()),\n            [],\n        )\n        tensor_array = Var(\"tensor_array\", self.list(output_tensor_type_var()))\n\n        value = Var(\"value\", value_type_var())\n        lengths = Var(\"lengths\", TensorType(lengths_shape or [Any()], \"int32\"))\n        if lengths_shape is None:\n            lengths_shape = op.shape_of(lengths)\n            lengths_limit = op.take(lengths_shape, const(0))\n        else:\n            lengths_limit = const(lengths_shape[0])\n        body = tensor_array_split_helper_var(\n            tensor_array, value, const(0), const(0), lengths_limit, lengths\n        )\n\n        self.prelude.mod[split_var] = Function(\n            [tensor_array, value, lengths], body, self.list(output_tensor_type_var()), []\n        )\n\n    def define_tensor_array_concat(self):\n        \"\"\"Defines a function to return the values in the tensor array as concatenated tensor_t.\n        tensor_array_concat(ta) : list[tensor_t] -> tensor_t\n        \"\"\"\n        # We don't register concat for scalar tensor array.\n        ndim = len(self.shape)\n        if ndim == 0:\n            return\n\n        concat_name = self.get_name(\"tensor_array_concat\")\n\n        if self.is_cached(concat_name):\n            return\n\n        concat_var = GlobalVar(concat_name)\n\n        output_shape = [\n            Any(),\n        ] + list(self.shape[1:])\n\n        tensor_type_var, _, output_ops = self._get_adt_by_shape(output_shape)\n\n        # Register tensor concatenate and get tensor_nil var for output shape\n        output_ops.define_tensor_concatenate()\n        tensor_concat_var = output_ops.get_global_var(\"tensor_concatenate\")\n        tensor_nil_var = output_ops.get_ctor(\"tensor_nil\")\n\n        tensor_array = Var(\"tensor_array\", self.list(tensor_type_var()))\n        hd = Var(\"hd\")\n        tl = Var(\"tl\")\n        nil_case = Clause(PatternConstructor(self.nil), tensor_nil_var())\n        cons_case = Clause(\n            PatternConstructor(self.cons, [PatternVar(hd), PatternVar(tl)]),\n            Match(\n                tl,\n                [\n                    Clause(PatternConstructor(self.nil), hd),\n                    Clause(PatternWildcard(), tensor_concat_var(hd, concat_var(tl))),\n                ],\n                False,\n            ),\n        )\n        self.prelude.mod[concat_var] = Function(\n            [tensor_array], Match(tensor_array, [nil_case, cons_case], False), tensor_type_var(), []\n        )\n\n    def define_tensor_array_stack(self):\n        \"\"\"Defines a function to get the values in the tensor array as a stack tensor_t.\n        tensor_array_stack(l) : list[tensor_t] -> tensor_t\n        \"\"\"\n        stack_name = self.get_name(\"tensor_array_stack\")\n        stack_var = self._create_global_var(stack_name)\n        setattr(self.prelude, stack_name, stack_var)\n        tensor_array = Var(\"tensor_array\", self.list(self.tensor_type_var()))\n        expand_dims_var = self.get_global_var(\"tensor_expand_dims\")\n\n        # Register tensor_concatenate for output_shape\n        new_axis = Any() if not self.batch_dim or self.batch_dim != 1 else self.batch_dim\n        output_shape = [\n            new_axis,\n        ] + list(self.shape)\n        _, _, output_ops = self._get_adt_by_shape(output_shape)\n        output_ops.define_tensor_concatenate()\n        concat_var = output_ops.get_global_var(\"tensor_concatenate\")\n\n        tensor_array_expand_dims = self.prelude.map(expand_dims_var, tensor_array)\n        if self.batch_dim is not None and self.batch_dim == 1:\n            # only one element\n            tensors = self.prelude.id(\n                self.prelude.hd(tensor_array_expand_dims),\n            )\n        else:\n            tensors = self.prelude.foldl(\n                concat_var,\n                self.prelude.hd(tensor_array_expand_dims),\n                self.prelude.tl(tensor_array_expand_dims),\n            )\n\n        output_tensor_type_var, _, _ = self._get_adt_by_shape(output_shape)\n        self.prelude.mod[stack_var] = Function(\n            [tensor_array], tensors, output_tensor_type_var(), []\n        )\n\n    def define_tensor_array_gather(self):\n        \"\"\"Defines a function to return the selected values in a tensor array as tensor_t.\n        tensor_array_gather(ta, indices) : list[tensor_t] -> Tensor[(Any), int32] -> tensor_t\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_gather_helper\")\n        helper_var = self._create_global_var(helper_name)\n\n        new_axis = Any() if self.batch_dim is None or self.batch_dim != 1 else self.batch_dim\n        output_shape = [\n            new_axis,\n        ] + list(self.shape)\n        output_tensor_type_var, _, _ = self._get_adt_by_shape(output_shape)\n        stack_var = self.get_global_var(\"tensor_array_stack\")\n        read_var = self.get_global_var(\"tensor_array_read\")\n        ta = Var(\"ta\", self.list(self.tensor_type_var()))\n        accu = Var(\"accu\", self.list(self.tensor_type_var()))\n        current = Var(\"current\", scalar_type(\"int32\"))\n        limit = Var(\"limit\", scalar_type(\"int32\"))\n        indices_ = Var(\"indices_\", TensorType([Any()], \"int32\"))\n        helper_body = If(\n            equal(current, const(0)),\n            stack_var(accu),\n            helper_var(\n                ta,\n                self.cons(read_var(ta, op.take(indices_, subtract(current, const(1)))), accu),\n                subtract(current, const(1)),\n                limit,\n                indices_,\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [ta, accu, current, limit, indices_], helper_body, output_tensor_type_var(), []\n        )\n        gather_name = self.get_name(\"tensor_array_gather\")\n        gather_var = self._create_global_var(gather_name)\n\n        tensor_array = Var(\"tensor_array\", self.list(self.tensor_type_var()))\n        indices = Var(\"indices\", TensorType([Any()], \"int32\"))\n        indices_shape = op.shape_of(indices)\n        limit = op.take(indices_shape, const(0))\n        body = helper_var(tensor_array, self.nil(), limit, limit, indices)\n        self.prelude.mod[gather_var] = Function(\n            [tensor_array, indices], body, output_tensor_type_var(), []\n        )\n\n    def define_tensor_get_data(self):\n        \"\"\"Defines a function to get a Tensor from tensor_t with given shape.\"\"\"\n        tensor_get_data_name = self.get_name(\"tensor_get_data\")\n        tensor_get_data_var = self._create_global_var(tensor_get_data_name)\n\n        tensor_constructor = self.get_ctor(\"tensor_constructor\")\n        t = Var(\"tensor\", self.tensor_type_var())\n        tvar = Var(\"t\")\n        case = Clause(PatternConstructor(tensor_constructor, [PatternVar(tvar)]), tvar)\n        self.prelude.mod[tensor_get_data_var] = Function(\n            [t], Match(t, [case], False), TensorType(self.shape, self.dtype), []\n        )\n\n    def register(self):\n        \"\"\"Register all tensor array ops in Prelude\"\"\"\n        self.define_tensor_adt()\n        self.define_tensor_take()\n        self.define_tensor_concatenate()\n        self.define_tensor_expand_dims()\n        self.define_tensor_array()\n        self.define_tensor_array_read()\n        self.define_tensor_array_write()\n        self.define_tensor_array_unstack()\n        self.define_tensor_array_scatter()\n        self.define_tensor_array_split()\n        self.define_tensor_array_concat()\n        self.define_tensor_array_stack()\n        self.define_tensor_array_gather()\n        self.define_tensor_get_data()\n\n    def _get_adt_by_shape(self, shape):\n        \"\"\"Get ADT type and constructor with given shape.\"\"\"\n        adt_ops = StaticTensorArrayOps(self.prelude, self.dtype, shape, self.batch_dim)\n        adt_ops.define_tensor_adt()\n        tensor_type_var = adt_ops.get_type(\"tensor_t\")\n        tensor_constructor = adt_ops.get_ctor(\"tensor_constructor\")\n        return tensor_type_var, tensor_constructor, adt_ops\n\n    def _create_global_var(self, name):\n        \"\"\"Create a GlobalVar if doesn't exist in prelude.\"\"\"\n        global_var_name_set = set()\n        for g_var_name in self.prelude.mod.get_global_vars():\n            global_var_name_set.add(g_var_name.name_hint)\n        if name not in global_var_name_set:\n            gvar = GlobalVar(name)\n        else:\n            gvar = self.prelude.mod.get_global_var(name)\n\n        return gvar\n\n\nclass TensorArrayOps(object):\n    \"\"\"Contains tensor array related ops\"\"\"\n\n    def __init__(self, prelude, dtype):\n        \"\"\"Create tensor array ops registry\"\"\"\n        self.prelude = prelude\n        self.dtype = dtype\n        self.list, self.cons, self.nil = self.prelude.mod.get_type(\"List\")\n\n    def get_name(self, canonical):\n        \"\"\"Get name corresponding to the canonical name\"\"\"\n        return self.prelude.get_name(canonical, self.dtype)\n\n    def get_global_var(self, canonical):\n        \"\"\"Get global corresponding to the canonical name\"\"\"\n        return self.prelude.get_global_var(canonical, self.dtype)\n\n    def get_type(self, canonical):\n        \"\"\"Get type corresponding to the canonical name\"\"\"\n        return self.prelude.get_type(canonical, self.dtype)\n\n    def get_ctor(self, canonical):\n        \"\"\"Get ctor corresponding to the canonical name\"\"\"\n        return self.prelude.get_ctor(self.tensor_type_var.name_hint, canonical, self.dtype)\n\n    def define_tensor_adt(self):\n        \"\"\"Defines the dynamic tensor ADT, which is the container for tensors\n        with variable shapes.\"\"\"\n        tensor_type_name = self.get_name(\"tensor_t\")\n        self.tensor_type_var = tensor_type_var = GlobalTypeVar(tensor_type_name)\n\n        tensor0_type = TensorType([], self.dtype)\n        tensor1_type = TensorType([Any()], self.dtype)\n        tensor2_type = TensorType([Any(), Any()], self.dtype)\n        tensor3_type = TensorType([Any(), Any(), Any()], self.dtype)\n        tensor4_type = TensorType([Any(), Any(), Any(), Any()], self.dtype)\n        tensor5_type = TensorType([Any(), Any(), Any(), Any(), Any()], self.dtype)\n        tensor6_type = TensorType([Any(), Any(), Any(), Any(), Any(), Any()], self.dtype)\n        tensor_nil_name = self.get_name(\"tensor_nil\")\n        tensor0_name = self.get_name(\"tensor0\")\n        tensor1_name = self.get_name(\"tensor1\")\n        tensor2_name = self.get_name(\"tensor2\")\n        tensor3_name = self.get_name(\"tensor3\")\n        tensor4_name = self.get_name(\"tensor4\")\n        tensor5_name = self.get_name(\"tensor5\")\n        tensor6_name = self.get_name(\"tensor6\")\n        tensor_nil_case = Constructor(tensor_nil_name, [], tensor_type_var)\n        tensor0_case = Constructor(tensor0_name, [tensor0_type], tensor_type_var)\n        tensor1_case = Constructor(tensor1_name, [tensor1_type], tensor_type_var)\n        tensor2_case = Constructor(tensor2_name, [tensor2_type], tensor_type_var)\n        tensor3_case = Constructor(tensor3_name, [tensor3_type], tensor_type_var)\n        tensor4_case = Constructor(tensor4_name, [tensor4_type], tensor_type_var)\n        tensor5_case = Constructor(tensor5_name, [tensor5_type], tensor_type_var)\n        tensor6_case = Constructor(tensor6_name, [tensor6_type], tensor_type_var)\n\n        self.prelude.mod[tensor_type_var] = TypeData(\n            tensor_type_var,\n            [],\n            [\n                tensor_nil_case,\n                tensor0_case,\n                tensor1_case,\n                tensor2_case,\n                tensor3_case,\n                tensor4_case,\n                tensor5_case,\n                tensor6_case,\n            ],\n        )\n\n    def define_tensor_take(self):\n        \"\"\"Defines a function to return a range of tensor_t on axis 0.\n        tensor_take(t, lower, upper) :\n        tensor_t -> Tensor[(), int32] -> Tensor[(), int32] -> tensor_t\n        \"\"\"\n        take_name = self.get_name(\"tensor_take\")\n        take_var = GlobalVar(take_name)\n\n        tensor_t = self.tensor_type_var\n        tensor1_var = self.get_ctor(\"tensor1\")\n        tensor2_var = self.get_ctor(\"tensor2\")\n        tensor3_var = self.get_ctor(\"tensor3\")\n        tensor4_var = self.get_ctor(\"tensor4\")\n        tensor5_var = self.get_ctor(\"tensor5\")\n        tensor6_var = self.get_ctor(\"tensor6\")\n\n        t = Var(\"tensor\", tensor_t())\n        lower = Var(\"lower\", scalar_type(\"int32\"))\n        upper = Var(\"upper\", scalar_type(\"int32\"))\n        t1 = Var(\"t1\")\n        t2 = Var(\"t2\")\n        t3 = Var(\"t3\")\n        t4 = Var(\"t4\")\n        t5 = Var(\"t5\")\n        t6 = Var(\"t6\")\n        tensor1_case = Clause(\n            PatternConstructor(tensor1_var, [PatternVar(t1)]),\n            tensor1_var(op.take(t1, op.arange(lower, upper, dtype=\"int32\"))),\n        )\n        tensor2_case = Clause(\n            PatternConstructor(tensor2_var, [PatternVar(t2)]),\n            tensor2_var(op.take(t2, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        tensor3_case = Clause(\n            PatternConstructor(tensor3_var, [PatternVar(t3)]),\n            tensor3_var(op.take(t3, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        tensor4_case = Clause(\n            PatternConstructor(tensor4_var, [PatternVar(t4)]),\n            tensor4_var(op.take(t4, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        tensor5_case = Clause(\n            PatternConstructor(tensor5_var, [PatternVar(t5)]),\n            tensor5_var(op.take(t5, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        tensor6_case = Clause(\n            PatternConstructor(tensor6_var, [PatternVar(t6)]),\n            tensor6_var(op.take(t6, op.arange(lower, upper, dtype=\"int32\"), axis=0)),\n        )\n        self.prelude.mod[take_var] = Function(\n            [t, lower, upper],\n            Match(\n                t,\n                [\n                    tensor1_case,\n                    tensor2_case,\n                    tensor3_case,\n                    tensor4_case,\n                    tensor5_case,\n                    tensor6_case,\n                ],\n                False,\n            ),\n            tensor_t(),\n            [],\n        )\n\n    def define_tensor_expand_dims(self):\n        \"\"\"Defines a function to grow a tensor_t's rank by adding one dimension in front\n        of the original tensor_t.\n        tensor_expand_dims(t) : tensor_t -> tensor_t\n        \"\"\"\n        expand_dims_name = self.get_name(\"tensor_expand_dims\")\n        expand_dims_var = GlobalVar(expand_dims_name)\n        tensor_type_var = self.tensor_type_var\n\n        x = Var(\"x\", tensor_type_var())\n        t0 = Var(\"t0\")\n        t1 = Var(\"t1\")\n        t2 = Var(\"t2\")\n        t3 = Var(\"t3\")\n        t4 = Var(\"t4\")\n        t5 = Var(\"t5\")\n        tensor0_var = self.get_ctor(\"tensor0\")\n        tensor1_var = self.get_ctor(\"tensor1\")\n        tensor2_var = self.get_ctor(\"tensor2\")\n        tensor3_var = self.get_ctor(\"tensor3\")\n        tensor4_var = self.get_ctor(\"tensor4\")\n        tensor5_var = self.get_ctor(\"tensor5\")\n        tensor6_var = self.get_ctor(\"tensor6\")\n        tensor0_case = Clause(\n            PatternConstructor(tensor0_var, [PatternVar(t0)]), tensor1_var(op.expand_dims(t0, 0, 1))\n        )\n        tensor1_case = Clause(\n            PatternConstructor(tensor1_var, [PatternVar(t1)]), tensor2_var(op.expand_dims(t1, 0, 1))\n        )\n        tensor2_case = Clause(\n            PatternConstructor(tensor2_var, [PatternVar(t2)]), tensor3_var(op.expand_dims(t2, 0, 1))\n        )\n        tensor3_case = Clause(\n            PatternConstructor(tensor3_var, [PatternVar(t3)]), tensor4_var(op.expand_dims(t3, 0, 1))\n        )\n        tensor4_case = Clause(\n            PatternConstructor(tensor4_var, [PatternVar(t4)]), tensor5_var(op.expand_dims(t4, 0, 1))\n        )\n        tensor5_case = Clause(\n            PatternConstructor(tensor5_var, [PatternVar(t5)]), tensor6_var(op.expand_dims(t5, 0, 1))\n        )\n        self.prelude.mod[expand_dims_var] = Function(\n            [x],\n            Match(\n                x,\n                [\n                    tensor0_case,\n                    tensor1_case,\n                    tensor2_case,\n                    tensor3_case,\n                    tensor4_case,\n                    tensor5_case,\n                ],\n                False,\n            ),\n            tensor_type_var(),\n        )\n\n    def define_tensor_concat(self):\n        \"\"\"Defines a function to concatenate two tensor_t on the first axis\n\n        tensor_concatenate(t) : tensor_t -> tensor_t -> tensor_t\n        \"\"\"\n        concat_name = self.get_name(\"tensor_concatenate\")\n        concat_var = GlobalVar(concat_name)\n\n        tensor_type_var = self.tensor_type_var\n        x = Var(\"x\", tensor_type_var())\n        y = Var(\"y\", tensor_type_var())\n\n        tensor1_var = self.get_ctor(\"tensor1\")\n        tensor2_var = self.get_ctor(\"tensor2\")\n        tensor3_var = self.get_ctor(\"tensor3\")\n        tensor4_var = self.get_ctor(\"tensor4\")\n        t11 = Var(\"t11\")\n        t12 = Var(\"t12\")\n        t21 = Var(\"t21\")\n        t22 = Var(\"t22\")\n        t31 = Var(\"t31\")\n        t32 = Var(\"t32\")\n        t41 = Var(\"t41\")\n        t42 = Var(\"t42\")\n        tensor1_case = Clause(\n            PatternConstructor(tensor1_var, [PatternVar(t11)]),\n            Match(\n                y,\n                [\n                    Clause(\n                        PatternConstructor(tensor1_var, [PatternVar(t12)]),\n                        tensor1_var(op.concatenate([t11, t12], axis=0)),\n                    )\n                ],\n                False,\n            ),\n        )\n        tensor2_case = Clause(\n            PatternConstructor(tensor2_var, [PatternVar(t21)]),\n            Match(\n                y,\n                [\n                    Clause(\n                        PatternConstructor(tensor2_var, [PatternVar(t22)]),\n                        tensor2_var(op.concatenate([t21, t22], axis=0)),\n                    )\n                ],\n                False,\n            ),\n        )\n        tensor3_case = Clause(\n            PatternConstructor(tensor3_var, [PatternVar(t31)]),\n            Match(\n                y,\n                [\n                    Clause(\n                        PatternConstructor(tensor3_var, [PatternVar(t32)]),\n                        tensor3_var(op.concatenate([t31, t32], axis=0)),\n                    )\n                ],\n                False,\n            ),\n        )\n        tensor4_case = Clause(\n            PatternConstructor(tensor4_var, [PatternVar(t41)]),\n            Match(\n                y,\n                [\n                    Clause(\n                        PatternConstructor(tensor4_var, [PatternVar(t42)]),\n                        tensor4_var(op.concatenate([t41, t42], axis=0)),\n                    )\n                ],\n                False,\n            ),\n        )\n        # op.concatenate does not support tensor with rank higher than 4\n        self.prelude.mod[concat_var] = Function(\n            [x, y],\n            Match(x, [tensor1_case, tensor2_case, tensor3_case, tensor4_case], False),\n            tensor_type_var(),\n        )\n\n    def define_tensor_array(self):\n        \"\"\"Defines a function to create a tensor array with size n.\n        tensor_array(n) : Tensor[(), int32] -> list[tensor_t]\n        \"\"\"\n        tensor_array_constructor_name = self.get_name(\"tensor_array\")\n        tensor_array_constructor_var = GlobalVar(tensor_array_constructor_name)\n        setattr(self.prelude, tensor_array_constructor_name, tensor_array_constructor_var)\n        tensor_nil_var = self.get_ctor(\"tensor_nil\")\n        tensor_type_var = self.get_ctor(\"tensor_t\")\n        n = Var(\"x\", scalar_type(\"int32\"))\n        body = If(\n            equal(n, const(0)),\n            self.nil(),\n            self.cons(tensor_nil_var(), tensor_array_constructor_var(subtract(n, const(1)))),\n        )\n        self.prelude.mod[tensor_array_constructor_var] = Function(\n            [n], body, self.list(tensor_type_var()), []\n        )\n\n    def define_tensor_array_read(self):\n        \"\"\"Defines a function to get the head of a list. Assume the list has at least one\n        element.\n\n        tensor_array_read(ta, n) : list[tensor_t] -> Tensor[(), int32] -> tensor_t\n        \"\"\"\n        read_name = self.get_name(\"tensor_array_read\")\n        read_var = GlobalVar(read_name)\n        setattr(self.prelude, read_name, read_var)\n        tensor_type_var = self.tensor_type_var\n\n        tensor_array = Var(\"tensor_array\", self.list(tensor_type_var()))\n        n = Var(\"x\", scalar_type(\"int32\"))\n        self.prelude.mod[read_var] = Function(\n            [tensor_array, n], self.prelude.nth(tensor_array, n), tensor_type_var(), []\n        )\n\n    def define_tensor_array_write(self):\n        \"\"\"Defines a function to update a tensor array at index n with value v.\n        tensor_array_write(ta, n, v) :\n            list[tensor_t] -> Tensor[(), int32] -> tensor_t -> list[tensor_t]\n        \"\"\"\n        write_name = self.get_name(\"tensor_array_write\")\n        write_var = GlobalVar(write_name)\n\n        tensor_type_var = self.tensor_type_var\n        tensor_array = Var(\"tensor_array\", self.list(tensor_type_var()))\n        n = Var(\"x\", scalar_type(\"int32\"))\n        v = Var(\"v\", tensor_type_var())\n        self.prelude.mod[write_var] = Function(\n            [tensor_array, n, v],\n            self.prelude.update(tensor_array, n, v),\n            self.list(tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack_tensor1(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 1 in a tensor array.\n        tensor_array_unstack_tensor1(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor1_helper\")\n        helper_var = GlobalVar(helper_name)\n        tensor = Var(\"t\", TensorType([Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n        tensor_type_var = self.tensor_type_var\n        tensor0_var = self.get_ctor(\"tensor0\")\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(tensor0_var(op.take(tensor, i)), helper_var(add(i, const(1)), up, tensor)),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(tensor_type_var()), []\n        )\n        unstack_name = self.get_name(\"tensor_array_unstack_tensor1\")\n        unstack_var = GlobalVar(unstack_name)\n        tensor1 = Var(\"tensor\", TensorType([Any()], self.dtype))\n        shape = op.shape_of(tensor1)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[unstack_var] = Function(\n            [tensor1], helper_var(const(0), ndim, tensor1), self.list(tensor_type_var()), []\n        )\n\n    def define_tensor_array_unstack_tensor2(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 2 in a tensor array.\n\n        tensor_array_unstack_tensor2(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor2_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType([Any(), Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                self.get_ctor(\"tensor1\")(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(self.tensor_type_var()), []\n        )\n\n        tensor_array_unstack_tensor2_name = self.get_name(\"tensor_array_unstack_tensor2\")\n        tensor_array_unstack_tensor2_var = GlobalVar(tensor_array_unstack_tensor2_name)\n        setattr(self.prelude, tensor_array_unstack_tensor2_name, tensor_array_unstack_tensor2_var)\n        tensor2 = Var(\"tensor\", TensorType([Any(), Any()], self.dtype))\n        shape = op.shape_of(tensor2)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[tensor_array_unstack_tensor2_var] = Function(\n            [tensor2],\n            helper_var(const(0), ndim, tensor2),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack_tensor3(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 3 in a tensor array.\n\n        tensor_array_unstack_tensor3(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor3_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType([Any(), Any(), Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                self.get_ctor(\"tensor2\")(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(self.tensor_type_var()), []\n        )\n\n        tensor_array_unstack_tensor3_name = self.get_name(\"tensor_array_unstack_tensor3\")\n        tensor_array_unstack_tensor3_var = GlobalVar(tensor_array_unstack_tensor3_name)\n        setattr(self.prelude, tensor_array_unstack_tensor3_name, tensor_array_unstack_tensor3_var)\n        tensor3 = Var(\"tensor\", TensorType([Any(), Any(), Any()], self.dtype))\n        shape = op.shape_of(tensor3)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[tensor_array_unstack_tensor3_var] = Function(\n            [tensor3],\n            helper_var(const(0), ndim, tensor3),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack_tensor4(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 4 in a tensor array.\n\n        tensor_array_unstack_tensor4(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor4_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType([Any(), Any(), Any(), Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                self.get_ctor(\"tensor3\")(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(self.tensor_type_var()), []\n        )\n\n        tensor_array_unstack_tensor4_name = self.get_name(\"tensor_array_unstack_tensor4\")\n        tensor_array_unstack_tensor4_var = GlobalVar(tensor_array_unstack_tensor4_name)\n        setattr(self.prelude, tensor_array_unstack_tensor4_name, tensor_array_unstack_tensor4_var)\n        tensor4 = Var(\"tensor\", TensorType([Any(), Any(), Any(), Any()], self.dtype))\n        shape = op.shape_of(tensor4)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[tensor_array_unstack_tensor4_var] = Function(\n            [tensor4],\n            helper_var(const(0), ndim, tensor4),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack_tensor5(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 5 in a tensor array.\n\n        tensor_array_unstack_tensor5(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor5_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType([Any(), Any(), Any(), Any(), Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                self.get_ctor(\"tensor4\")(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(self.tensor_type_var()), []\n        )\n\n        tensor_array_unstack_tensor5_name = self.get_name(\"tensor_array_unstack_tensor5\")\n        tensor_array_unstack_tensor5_var = GlobalVar(tensor_array_unstack_tensor5_name)\n        setattr(self.prelude, tensor_array_unstack_tensor5_name, tensor_array_unstack_tensor5_var)\n        tensor5 = Var(\"tensor\", TensorType([Any(), Any(), Any(), Any(), Any()], self.dtype))\n        shape = op.shape_of(tensor5)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[tensor_array_unstack_tensor5_var] = Function(\n            [tensor5],\n            helper_var(const(0), ndim, tensor5),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_unstack_tensor6(self):\n        \"\"\"Defines a function to unstack the values of a tensor_t with rank 6 in a tensor array.\n\n        tensor_array_unstack_tensor6(t) : tensor_t -> list[tensor_t]\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_unstack_tensor6_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor = Var(\"t\", TensorType([Any(), Any(), Any(), Any(), Any(), Any()], self.dtype))\n        up = Var(\"up\", scalar_type(\"int32\"))\n        i = Var(\"i\", scalar_type(\"int32\"))\n\n        helper_body = If(\n            equal(i, up),\n            self.nil(),\n            self.cons(\n                self.get_ctor(\"tensor5\")(op.take(tensor, i, axis=0)),\n                helper_var(add(i, const(1)), up, tensor),\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [i, up, tensor], helper_body, self.list(self.tensor_type_var()), []\n        )\n\n        tensor_array_unstack_tensor6_name = self.get_name(\"tensor_array_unstack_tensor6\")\n        tensor_array_unstack_tensor6_var = GlobalVar(tensor_array_unstack_tensor6_name)\n        setattr(self.prelude, tensor_array_unstack_tensor6_name, tensor_array_unstack_tensor6_var)\n        tensor6 = Var(\"tensor\", TensorType([Any(), Any(), Any(), Any(), Any(), Any()], self.dtype))\n        shape = op.shape_of(tensor6)\n        ndim = op.take(shape, const(0))\n        self.prelude.mod[tensor_array_unstack_tensor6_var] = Function(\n            [tensor6],\n            helper_var(const(0), ndim, tensor6),\n            self.list(self.tensor_type_var()),\n            [],\n        )\n\n    def define_tensor_array_scatter(self):\n        \"\"\"Defines a function to scatter the values of a tensor_t in indices of a tensor array.\n        tensor_array_scatter(ta, indices, value) :\n            list[tensor_t] -> Tensor[(Any), int32] -> tensor_t -> list[tensor_t]\n        \"\"\"\n        tensor_array_scatter_helper_name = self.get_name(\"tensor_array_scatter_helper\")\n        tensor_array_scatter_helper_var = GlobalVar(tensor_array_scatter_helper_name)\n        tensor_t = self.tensor_type_var\n        ta = Var(\"ta\", self.list(tensor_t()))\n        current = Var(\"current\", scalar_type(\"int32\"))\n        limit = Var(\"limit\", scalar_type(\"int32\"))\n        indices_ = Var(\"indices_\", TensorType([Any()], \"int32\"))\n        values_ = Var(\"values_\", self.list(tensor_t()))\n        write_var = self.get_global_var(\"tensor_array_write\")\n        read_var = self.get_global_var(\"tensor_array_read\")\n        helper_body = If(\n            equal(current, limit),\n            ta,\n            tensor_array_scatter_helper_var(\n                write_var(ta, op.take(indices_, current), read_var(values_, current)),\n                add(current, const(1)),\n                limit,\n                indices_,\n                values_,\n            ),\n        )\n        self.prelude.mod[tensor_array_scatter_helper_var] = Function(\n            [ta, current, limit, indices_, values_], helper_body, self.list(tensor_t()), []\n        )\n        tensor_array_scatter_name = self.get_name(\"tensor_array_scatter\")\n        tensor_array_scatter_var = GlobalVar(tensor_array_scatter_name)\n        setattr(self.prelude, tensor_array_scatter_name, tensor_array_scatter_var)\n        tensor_array = Var(\"tensor_array\", self.list(tensor_t()))\n        indices = Var(\"indices\", TensorType([Any()], \"int32\"))\n        values = Var(\"values\", self.list(tensor_t()))\n        indices_shape = op.shape_of(indices)\n        limit = op.take(indices_shape, const(0))\n        body = tensor_array_scatter_helper_var(tensor_array, const(0), limit, indices, values)\n        self.prelude.mod[tensor_array_scatter_var] = Function(\n            [tensor_array, indices, values], body, self.list(tensor_t()), []\n        )\n\n    def define_tensor_array_split(self):\n        \"\"\"Defines a function to split the values of a tensor_t into a tensor array.\n        tensor_array_split(ta, value, lengths) :\n            list[tensor_t] -> tensor_t -> Tensor[(Any), int32] -> list[tensor_t]\n        \"\"\"\n        tensor_t = self.tensor_type_var\n        tensor_array_split_helper_name = self.get_name(\"ta_split_helper\")\n        tensor_array_split_helper_var = GlobalVar(tensor_array_split_helper_name)\n        setattr(self.prelude, tensor_array_split_helper_name, tensor_array_split_helper_var)\n        ta1 = Var(\"tensor_array\", self.list(tensor_t()))\n        value1 = Var(\"value1\", tensor_t())\n        offset1 = Var(\"offset1\", scalar_type(\"int32\"))\n        current1 = Var(\"current1\", scalar_type(\"int32\"))\n        limit1 = Var(\"limit1\", scalar_type(\"int32\"))\n        lengths1 = Var(\"lengths\", TensorType([Any()], \"int32\"))\n        write_var = self.get_global_var(\"tensor_array_write\")\n        take_var = self.get_global_var(\"tensor_take\")\n        helper1_body = If(\n            equal(current1, limit1),\n            ta1,\n            write_var(\n                tensor_array_split_helper_var(\n                    ta1,\n                    value1,\n                    add(offset1, op.take(lengths1, current1)),\n                    add(current1, const(1)),\n                    limit1,\n                    lengths1,\n                ),\n                current1,\n                take_var(value1, offset1, add(op.take(lengths1, current1), offset1)),\n            ),\n        )\n        self.prelude.mod[tensor_array_split_helper_var] = Function(\n            [ta1, value1, offset1, current1, limit1, lengths1],\n            helper1_body,\n            self.list(tensor_t()),\n            [],\n        )\n        split_name = self.get_name(\"tensor_array_split\")\n        split_var = GlobalVar(split_name)\n        setattr(self.prelude, split_name, split_var)\n        tensor_array = Var(\"tensor_array\", self.list(tensor_t()))\n        value = Var(\"value\", tensor_t())\n        lengths = Var(\"lengths\", TensorType([Any()], \"int32\"))\n        lengths_shape = op.shape_of(lengths)\n        lengths_limit = op.take(lengths_shape, const(0))\n        body = tensor_array_split_helper_var(\n            tensor_array, value, const(0), const(0), lengths_limit, lengths\n        )\n        self.prelude.mod[split_var] = Function(\n            [tensor_array, value, lengths], body, self.list(tensor_t()), []\n        )\n\n    def define_tensor_array_concat(self):\n        \"\"\"Defines a function to return the values in the tensor array as concatenated tensor_t.\n        tensor_array_concat(ta) : list[tensor_t] -> tensor_t\n        \"\"\"\n        concat_name = self.get_name(\"tensor_array_concat\")\n        concat_var = GlobalVar(concat_name)\n        setattr(self.prelude, concat_name, concat_var)\n        tensor_concat_var = self.get_global_var(\"tensor_concatenate\")\n        tensor_t = self.tensor_type_var\n        tensor_nil_var = self.get_ctor(\"tensor_nil\")\n        tensor_array = Var(\"tensor_array\", self.list(tensor_t()))\n        hd = Var(\"hd\")\n        tl = Var(\"tl\")\n        nil_case = Clause(PatternConstructor(self.nil), tensor_nil_var())\n        cons_case = Clause(\n            PatternConstructor(self.cons, [PatternVar(hd), PatternVar(tl)]),\n            Match(\n                tl,\n                [\n                    Clause(PatternConstructor(self.nil), hd),\n                    Clause(PatternWildcard(), tensor_concat_var(hd, concat_var(tl))),\n                ],\n                False,\n            ),\n        )\n        self.prelude.mod[concat_var] = Function(\n            [tensor_array], Match(tensor_array, [nil_case, cons_case], False), tensor_t(), []\n        )\n\n    def define_tensor_array_gather(self):\n        \"\"\"Defines a function to return the selected values in a tensor array as tensor_t.\n        tensor_array_gather(ta, indices) : list[tensor_t] -> Tensor[(Any), int32] -> tensor_t\n        \"\"\"\n        helper_name = self.get_name(\"tensor_array_gather_helper\")\n        helper_var = GlobalVar(helper_name)\n        setattr(self.prelude, helper_name, helper_var)\n        tensor_type_var = self.tensor_type_var\n        stack_var = self.get_var(\"tensor_array_stack\")\n        read_var = self.get_var(\"tensor_array_read\")\n        ta = Var(\"ta\", self.list(tensor_type_var()))\n        accu = Var(\"accu\", self.list(tensor_type_var()))\n        current = Var(\"current\", scalar_type(\"int32\"))\n        limit = Var(\"limit\", scalar_type(\"int32\"))\n        indices_ = Var(\"indices_\", TensorType([Any()], \"int32\"))\n        helper_body = If(\n            equal(current, const(0)),\n            stack_var(accu),\n            helper_var(\n                ta,\n                self.cons(read_var(ta, op.take(indices_, subtract(current, const(1)))), accu),\n                subtract(current, const(1)),\n                limit,\n                indices_,\n            ),\n        )\n        self.prelude.mod[helper_var] = Function(\n            [ta, accu, current, limit, indices_], helper_body, tensor_type_var(), []\n        )\n        gather_name = self.get_name(\"tensor_array_gather\")\n        gather_var = GlobalVar(gather_name)\n        setattr(self.prelude, gather_name, gather_var)\n        tensor_array = Var(\"tensor_array\", self.list(tensor_type_var()))\n        indices = Var(\"indices\", TensorType([Any()], \"int32\"))\n        indices_shape = op.shape_of(indices)\n        limit = op.take(indices_shape, const(0))\n        body = helper_var(tensor_array, self.nil(), limit, limit, indices)\n        self.prelude.mod[gather_var] = Function(\n            [tensor_array, indices], body, tensor_type_var(), []\n        )\n\n    def define_tensor_array_stack(self):\n        \"\"\"Defines a function to get the values in the tensor array as a stack tensor_t.\n        tensor_array_stack(l) : list[tensor_t] -> tensor_t\n        \"\"\"\n        stack_name = self.get_name(\"tensor_array_stack\")\n        stack_var = GlobalVar(stack_name)\n        setattr(self.prelude, stack_name, stack_var)\n        tensor_type_var = self.tensor_type_var\n        tensor_array = Var(\"tensor_array\", self.list(tensor_type_var()))\n        expand_dims_var = self.get_global_var(\"tensor_expand_dims\")\n        concat_var = self.get_global_var(\"tensor_concatenate\")\n\n        tensor_array_expand_dims = self.prelude.map(expand_dims_var, tensor_array)\n        tensors = self.prelude.foldl(\n            concat_var,\n            self.prelude.hd(tensor_array_expand_dims),\n            self.prelude.tl(tensor_array_expand_dims),\n        )\n        self.prelude.mod[stack_var] = Function(\n            [tensor_array], ToANormalFormExpr(tensors), tensor_type_var(), []\n        )\n\n    def register(self):\n        \"\"\"Register all tensor array ops in Prelude\"\"\"\n        self.define_tensor_adt()\n        self.define_tensor_take()\n        self.define_tensor_expand_dims()\n        self.define_tensor_concat()\n        self.define_tensor_array()\n        self.define_tensor_array_read()\n        self.define_tensor_array_write()\n        self.define_tensor_array_unstack_tensor1()\n        self.define_tensor_array_unstack_tensor2()\n        self.define_tensor_array_unstack_tensor3()\n        self.define_tensor_array_unstack_tensor4()\n        self.define_tensor_array_unstack_tensor5()\n        self.define_tensor_array_unstack_tensor6()\n        self.define_tensor_array_scatter()\n        self.define_tensor_array_split()\n        self.define_tensor_array_concat()\n        self.define_tensor_array_stack()\n        # TODO(wweic): Gather fails in PartialEvaluate\n        # self.define_tensor_array_gather()\n\n\nclass Prelude:\n    \"\"\"Contains standard definitions.\"\"\"\n\n    def __init__(self, mod=None):\n        if mod is None:\n            mod = IRModule()\n        self.mod = mod\n        self.load_prelude()\n\n    def get_name(self, canonical, dtype):\n        \"\"\"Get name corresponding to the canonical name\"\"\"\n        if canonical == \"tensor_t\":\n            return \"tensor_{}_t\".format(dtype)\n        return \"{}_{}\".format(canonical, dtype)\n\n    def get_global_var(self, canonical, dtype):\n        \"\"\"Get global var corresponding to the canonical name\"\"\"\n        name = self.get_name(canonical, dtype)\n        return self.mod.get_global_var(name)\n\n    def get_type(self, canonical, dtype):\n        \"\"\"Get type corresponding to the canonical name\"\"\"\n        name = self.get_name(canonical, dtype)\n        return self.mod.get_global_type_var(name)\n\n    def get_ctor(self, ty_name, canonical, dtype):\n        \"\"\"Get constructor corresponding to the canonical name\"\"\"\n        name = self.get_name(canonical, dtype)\n        ctors = self.mod.get_type(ty_name)\n        for ctor in ctors:\n            if ctor.name_hint == name:\n                return ctor\n        raise Exception(f\"could not find {name}\")\n\n    def get_tensor_ctor(self, canonical, dtype):\n        ty = self.get_type(\"tensor_t\", dtype)\n        return self.get_ctor(ty.name_hint, canonical, dtype)\n\n    def get_name_static(self, canonical, dtype, shape, batch_dim=None):\n        \"\"\"Get name corresponding to the canonical name\"\"\"\n        return _get_name_static(canonical, dtype, shape, batch_dim)\n\n    def get_global_var_static(self, canonical, dtype, shape, batch_dim=None):\n        \"\"\"Get var corresponding to the canonical name\"\"\"\n        name = self.get_name_static(canonical, dtype, shape, batch_dim)\n        return self.mod.get_global_var(name)\n\n    def get_type_static(self, canonical, dtype, shape):\n        \"\"\"Get type corresponding to the canonical name\"\"\"\n        name = self.get_name_static(canonical, dtype, shape)\n        return self.mod.get_global_type_var(name)\n\n    def get_ctor_static(self, ty_name, name, dtype, shape):\n        \"\"\"Get constructor corresponding to the canonical name\"\"\"\n        ty_name = self.get_name_static(ty_name, dtype, shape)\n        name = self.get_name_static(name, dtype, shape)\n        ctors = self.mod.get_type(ty_name)\n        for ctor in ctors:\n            if ctor.name_hint == name:\n                return ctor\n        raise Exception(f\"could not find {name}\")\n\n    def get_tensor_ctor_static(self, name, dtype, shape):\n        \"\"\"Get constructor corresponding to the canonical name\"\"\"\n        return self.get_ctor_static(\"tensor_t\", name, dtype, shape)\n\n    def load_prelude(self):\n        \"\"\"Parses the Prelude from Relay's text format into a module.\"\"\"\n        # TODO(@jroesch): we should remove this helper when we port over prelude\n        self.mod.import_from_std(\"prelude.rly\")\n\n        GLOBAL_DEFS = [\n            \"id\",\n            \"compose\",\n            \"flip\",\n            \"hd\",\n            \"tl\",\n            \"nth\",\n            \"update\",\n            \"map\",\n            \"foldl\",\n            \"foldr\",\n            \"foldr1\",\n            \"concat\",\n            \"filter\",\n            \"zip\",\n            \"rev\",\n            \"map_accuml\",\n            \"map_accumr\",\n            \"unfoldl\",\n            \"unfoldr\",\n            \"sum\",\n            \"length\",\n            \"tmap\",\n            \"size\",\n            \"iterate\",\n        ]\n\n        for global_def in GLOBAL_DEFS:\n            setattr(self, global_def, self.mod.get_global_var(global_def))\n\n        for dtype in [\n            \"float32\",\n            \"float16\",\n            \"float64\",\n            \"int32\",\n            \"uint8\",\n            \"int8\",\n            \"int16\",\n            \"uint16\",\n            \"int64\",\n        ]:\n            tensor_array_ops = TensorArrayOps(self, dtype)\n            tensor_array_ops.register()\n\n        # Renamer doesn't properly deal with constructors, etc\n        # self.mod = AnnotateSpans()(self.mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"QNN dialect operators and IR passes.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom . import op\nfrom . import transform\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin\n\n\"\"\"QNN dialect related operators.\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .qnn import *\nfrom .op import register_qnn_legalize, register_qnn_canonicalize\nfrom . import _qnn, legalizations, layout_conversions, canonicalizations\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/_make.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Constructor APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.qnn.op._make\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/_qnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, len-as-condition\n\"\"\"QNN operator feature registration\"\"\"\n\nfrom tvm import topi\n\nfrom .. import strategy\nfrom ...op.op import register_compute\nfrom ...op.op import register_injective_schedule\nfrom ...op.op import register_strategy, register_pattern, OpPattern\n\n\n@register_compute(\"qnn.simulated_quantize\")\ndef simulated_quantize_compute(attrs, inputs, output_type):\n    assert len(inputs) == 4\n    return [\n        topi.nn.simulated_quantize(\n            inputs[0], inputs[1], inputs[2], inputs[3], axis=attrs.get_int(\"axis\")\n        )\n    ]\n\n\nregister_injective_schedule(\"qnn.simulated_quantize\")\nregister_pattern(\"qnn.simulated_quantize\", OpPattern.ELEMWISE)\n\n\n@register_compute(\"qnn.simulated_dequantize\")\ndef simulated_dequantize_compute(attrs, inputs, output_type):\n    assert len(inputs) == 4\n    return [\n        topi.nn.simulated_dequantize(\n            inputs[0], inputs[1], inputs[2], inputs[3], axis=attrs.get_int(\"axis\")\n        )\n    ]\n\n\nregister_injective_schedule(\"qnn.simulated_dequantize\")\nregister_pattern(\"qnn.simulated_dequantize\", OpPattern.ELEMWISE)\n\n# qnn.quantize\nregister_strategy(\"qnn.quantize\", strategy.qnn_quantize_strategy)\nregister_pattern(\"qnn.quantize\", OpPattern.ELEMWISE)\n\n# qnn.dequantize\nregister_strategy(\"qnn.dequantize\", strategy.qnn_dequantize_strategy)\nregister_pattern(\"qnn.dequantize\", OpPattern.ELEMWISE)\n\n# qnn.requantize\nregister_strategy(\"qnn.requantize\", strategy.qnn_requantize_strategy)\nregister_pattern(\"qnn.requantize\", OpPattern.ELEMWISE)\n\n# qnn.add\nregister_strategy(\"qnn.add\", strategy.qnn_add_strategy)\nregister_pattern(\"qnn.add\", OpPattern.BROADCAST)\n\n# qnn.concatenate\nregister_strategy(\"qnn.concatenate\", strategy.qnn_concatenate_strategy)\nregister_pattern(\"qnn.concatenate\", OpPattern.INJECTIVE)\n\n# qnn.conv2d\nregister_strategy(\"qnn.conv2d\", strategy.qnn_conv2d_strategy)\nregister_pattern(\"qnn.conv2d\", OpPattern.OUT_ELEMWISE_FUSABLE)\n\n# qnn.dense\nregister_strategy(\"qnn.dense\", strategy.qnn_dense_strategy)\nregister_pattern(\"qnn.dense\", OpPattern.OUT_ELEMWISE_FUSABLE)\n\n# qnn.batch_matmul\nregister_strategy(\"qnn.batch_matmul\", strategy.qnn_batch_matmul_strategy)\nregister_pattern(\"qnn.batch_matmul\", OpPattern.OUT_ELEMWISE_FUSABLE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/_requantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Internal module for qnn requantization.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay._requantize\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/canonicalizations.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Consist of utilities and methods for lowering QNN into mainline relay.\"\"\"\nfrom typing import Callable\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\n\n\ndef run_const_expr(expr: \"relay.Expr\") -> np.ndarray:\n    \"\"\"Evaluate a const expression, receiving result as np array.\"\"\"\n    mod = tvm.IRModule.from_expr(expr)\n    vm_exe = relay.create_executor(\"vm\", mod=mod)\n    return vm_exe.evaluate()().asnumpy()\n\n\ndef create_integer_lookup_table(\n    floating_point_func: Callable[[np.ndarray], np.ndarray],\n    input_scale: \"relay.Expr\",\n    input_zero_point: \"relay.Expr\",\n    output_scale: \"relay.Expr\",\n    output_zero_point: \"relay.Expr\",\n    in_axis: int = -1,\n    out_axis: int = -1,\n    in_dtype: str = \"uint8\",\n    out_dtype: str = \"uint8\",\n) -> np.ndarray:\n    \"\"\"\n    Return a table where each input indexes to the output quantizing the given function.\n\n    Note this also supports mapping unsigned and signed integers to each other.\n\n    Args:\n      floating_point_func: The numpy function which this table is to approximate\n      input_scale: The scale of the quantized input tensor.\n      input_zero_point: The zero point of the quantized input tensor.\n      output_scale: The scale of the quantized output tensor.\n      output_zero_point: The zero point of the quantized output tensor.\n      in_axis: The axis for multi-channel quantization of the input if applicable.\n      out_axis: The axis for multi-channel quantization of the output if applicable.\n      in_dtype: The dtype of the input tensor.\n      out_dtype: The wanted dtype of the output tensor.\n\n    Returns:\n      A numpy array where values in quantized space will index to the output in quantized space\n      approximating the given function.\n    \"\"\"\n    if not np.issubdtype(np.dtype(in_dtype), np.integer) or not np.issubdtype(\n        np.dtype(out_dtype), np.integer\n    ):\n        raise ValueError(\n            f\"Only integer dtypes allowed got {in_dtype} and {out_dtype} for in and out dtypes.\"\n        )\n\n    dtype_info = np.iinfo(in_dtype)\n\n    num_bits = dtype_info.bits\n\n    # Use TVMs quantization methods via relay to be consistent\n    # inputs_quantized = np.array(range(dtype_info.min, dtype_info.max + 1)).astype(in_dtype)\n\n    # First generate a list of all num_bit integer patterns\n    inputs_quantized = np.array(range(0, 2**num_bits), dtype=f\"uint{num_bits}\")\n\n    # Reinterpret bits as the real datatype\n    # Note what we are doing here is a bit tricky, the canonical view of our lookup table\n    # is using the uintX version. When we run the lookup in the relay graph, we cast the\n    # bit pattern back into this form.\n    inputs_quantized = inputs_quantized.view(in_dtype)\n    inputs_quantized = relay.const(inputs_quantized, dtype=in_dtype)\n    inputs_dequantized = run_const_expr(\n        relay.qnn.op.dequantize(\n            inputs_quantized,\n            input_scale=input_scale,\n            input_zero_point=input_zero_point,\n            axis=in_axis,\n        )\n    )\n\n    output_dequantized = relay.const(floating_point_func(inputs_dequantized))\n    output_quantized = run_const_expr(\n        relay.qnn.op.quantize(\n            output_dequantized, output_scale, output_zero_point, out_axis, out_dtype\n        )\n    )\n\n    return output_quantized\n\n\ndef create_integer_lookup_op(\n    input_arg: \"relay.Expr\",\n    floating_point_func: Callable[[np.array], np.array],\n    in_scale: \"relay.Expr\",\n    in_zero_point: \"relay.Expr\",\n    out_scale: \"relay.Expr\",\n    out_zero_point: \"relay.Expr\",\n    in_axis: int = -1,\n    out_axis: int = -1,\n    in_dtype: str = \"uint8\",\n    out_dtype: str = \"uint8\",\n) -> \"relay.Expr\":\n    \"\"\"\n    Create a quantized version of the given floating point unary operation using table lookup.\n\n    Args:\n      input_arg: The quantized input to the final function.\n      floating_point_func: The numpy function which this table is to approximate\n      in_scale: The scale of the quantized input tensor.\n      in_zero_point: The zero point of the quantized input tensor.\n      out_scale: The scale of the quantized output tensor.\n      out_zero_point: The zero point of the quantized output tensor.\n      in_axis: The axis for multi-channel quantization of the input if applicable.\n      out_axis: The axis for multi-channel quantization of the output if applicable.\n      in_dtype: The dtype of the input tensor.\n      out_dtype: The wanted dtype of the output tensor.\n\n    Returns:\n      A Relay expression representing a quantized version of the given function.\n    \"\"\"\n\n    # TODO: handle multi-channel q, below will fail with multi-channel q\n    in_scale = in_scale.data.numpy().item()\n    in_zero_point = in_zero_point.data.numpy().item()\n    out_scale = out_scale.data.numpy().item()\n    out_zero_point = out_zero_point.data.numpy().item()\n\n    lookup_table = create_integer_lookup_table(\n        floating_point_func,\n        relay.const(in_scale),\n        relay.const(in_zero_point, dtype=\"int32\"),\n        relay.const(out_scale),\n        relay.const(out_zero_point, dtype=\"int32\"),\n        in_axis=in_axis,\n        in_dtype=in_dtype,\n        out_axis=out_axis,\n        out_dtype=out_dtype,\n    )\n\n    in_dtype_info = np.iinfo(in_dtype)\n    in_dtype_num_bits = in_dtype_info.bits\n\n    lookup_table = relay.const(lookup_table)\n    index_tensor = relay.reinterpret(input_arg, f\"uint{in_dtype_num_bits}\")\n    result = relay.take(lookup_table, index_tensor, axis=0, mode=\"fast\")\n    return result\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/layout_conversions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Convert layout related registration\"\"\"\nfrom __future__ import absolute_import\n\nfrom tvm.relay.op import op as reg\n\nfrom ...op.strategy.generic import is_depthwise_conv2d\n\n\n@reg.register_convert_op_layout(\"qnn.conv2d\")\ndef convert_qnn_conv2d(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for QNN conv2d op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    assert len(desired_layouts) == 2, \"A desired layout is expected for both of qnn.conv2d's inputs\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n\n    new_attrs = dict(attrs)\n    new_attrs[\"data_layout\"] = desired_data_layout\n\n    if desired_kernel_layout != \"default\":\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.qnn.op.conv2d(*inputs, **new_attrs)\n\n    if desired_data_layout == \"NCHW\":\n        new_attrs[\"kernel_layout\"] = \"OIHW\"\n        return relay.qnn.op.conv2d(*inputs, **new_attrs)\n    if desired_data_layout == \"NHWC\":\n        # Check for depthwise convolution.\n        data_info = tinfos[0]\n        weight_info = tinfos[1]\n        if is_depthwise_conv2d(\n            data_info.shape,\n            attrs[\"data_layout\"],\n            weight_info.shape,\n            attrs[\"kernel_layout\"],\n            attrs[\"groups\"],\n        ):\n            new_attrs[\"kernel_layout\"] = \"HWOI\"\n        else:\n            new_attrs[\"kernel_layout\"] = \"HWIO\"\n        return relay.qnn.op.conv2d(*inputs, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported\" % desired_data_layout)\n\n\n@reg.register_convert_op_layout(\"qnn.conv2d_transpose\")\ndef convert_qnn_conv2d_transpose(attrs, inputs, tinfos, desired_layouts):\n    \"\"\"Convert Layout pass registration for QNN conv2d_transpose op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    tinfos : list of types\n        List of input and output types\n    desired_layouts : list of layout strings\n        List of layouts defining our desired\n        layout for the data and kernel inputs respectively.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The transformed expr\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm import relay\n\n    assert (\n        len(desired_layouts) == 2\n    ), \"A desired layout is expected for both of qnn.conv2d_transpose's inputs\"\n    desired_data_layout, desired_kernel_layout = map(str, desired_layouts)\n    assert desired_data_layout != \"default\", \"Data layout cannot be default\"\n\n    new_attrs = dict(attrs)\n    new_attrs[\"data_layout\"] = desired_data_layout\n\n    if desired_kernel_layout != \"default\":\n        new_attrs[\"kernel_layout\"] = desired_kernel_layout\n        return relay.qnn.op.conv2d_transpose(*inputs, **new_attrs)\n\n    # Handle default kernel layouts\n    if desired_data_layout == \"NCHW\":\n        new_attrs[\"kernel_layout\"] = \"IOHW\"\n        return relay.qnn.op.conv2d_transpose(*inputs, **new_attrs)\n    if desired_data_layout == \"NHWC\":\n        new_attrs[\"kernel_layout\"] = \"HWIO\"\n        return relay.qnn.op.conv2d_transpose(*inputs, **new_attrs)\n\n    raise ValueError(\"Layout %s is not yet supported\" % desired_data_layout)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/legalizations.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Backend QNN related feature registration\"\"\"\nimport numpy as np\nfrom scipy import special\nimport tvm\nfrom tvm import relay\nfrom tvm._ffi.base import TVMError\nfrom tvm.relay.qnn.op.canonicalizations import create_integer_lookup_op\n\nfrom ....topi.x86.utils import target_has_sse42\nfrom ....topi.utils import is_target\nfrom .. import op as reg\n\n#################################################\n# Register the functions for different operators.\n#################################################\n\n# Registering QNN Conv2D legalization function.\n\n\n@reg.register_qnn_legalize(\"qnn.conv2d\")\ndef legalize_qnn_conv2d(attrs, inputs, types):\n    return qnn_conv2d_legalize(attrs, inputs, types)\n\n\n# Registering QNN Conv2DTranspose legalization function.\n@reg.register_qnn_legalize(\"qnn.conv2d_transpose\")\ndef legalize_qnn_conv2d_transpose(attrs, inputs, types):\n    return qnn_conv2d_transpose_legalize(attrs, inputs, types)\n\n\n# Registering QNN dense legalization function.\n@reg.register_qnn_legalize(\"qnn.dense\")\ndef legalize_qnn_dense(attrs, inputs, types):\n    return qnn_dense_legalize(attrs, inputs, types)\n\n\ndef register_qnn_unary_op_legalize(op_name, floating_point_func):\n    \"\"\"Register unary qnn op for legalization via table lookup op.\"\"\"\n\n    def legalize_qnn_unary_op(attrs, inputs, types):\n        return create_integer_lookup_op(\n            input_arg=inputs[0],\n            floating_point_func=floating_point_func,\n            in_scale=inputs[1],\n            in_zero_point=inputs[2],\n            out_scale=inputs[3],\n            out_zero_point=inputs[4],\n            in_dtype=types[0].dtype,\n            out_dtype=types[0].dtype,\n        )\n\n    return reg.register_qnn_legalize(op_name, legalize_qnn_unary_op)\n\n\ndef hardswish_func(x):\n    x2 = x + 3.0\n    x2 = np.clip(x2, 0.0, 6.0)\n    return x * x2 / 6.0\n\n\nregister_qnn_unary_op_legalize(\"qnn.sqrt\", np.sqrt)\nregister_qnn_unary_op_legalize(\"qnn.rsqrt\", lambda arr: 1 / np.sqrt(arr))\nregister_qnn_unary_op_legalize(\"qnn.exp\", np.exp)\nregister_qnn_unary_op_legalize(\"qnn.erf\", special.erf)\nregister_qnn_unary_op_legalize(\"qnn.sigmoid\", lambda arr: 1 / (1 + np.exp(-arr)))\nregister_qnn_unary_op_legalize(\"qnn.hardswish\", hardswish_func)\nregister_qnn_unary_op_legalize(\"qnn.tanh\", np.tanh)\nregister_qnn_unary_op_legalize(\"qnn.log\", np.log)\nregister_qnn_unary_op_legalize(\"qnn.abs\", np.abs)\n\n\n# Default to None. If overridden by target, this will not be run.\n# Generic QNN Conv2D legalization function.\n@tvm.target.generic_func\ndef qnn_conv2d_legalize(attrs, inputs, types):\n    \"\"\"Default legalization is None.\"\"\"\n    return None\n\n\n# Generic QNN Conv2DTranspose legalization function.\n@tvm.target.generic_func\ndef qnn_conv2d_transpose_legalize(attrs, inputs, types):\n    \"\"\"Convert kernel and data to int16, subtract offsets upfront\n    and calls into relay.nn.conv2d_transpose.\"\"\"\n\n    # Collect the input exprs.\n    data, kernel, input_zero_point, kernel_zero_point, _, _ = inputs\n\n    # If input zero point is a scalar, we can directly subtract it.\n    if len(types[2].shape) == 0:\n        shift_data = relay.subtract(\n            relay.cast(data, dtype=\"int16\"), relay.cast(input_zero_point, \"int16\")\n        )\n    # Otherwise it needs to be broadcast.\n    else:\n        shift_data = relay.nn.bias_add(\n            relay.cast(data, dtype=\"int16\"),\n            -relay.cast(input_zero_point, dtype=\"int16\"),\n        )\n\n    # If kernel zero point is a scalar, we can directly subtract it.\n    if len(types[3].shape) == 0:\n        shift_kernel = relay.subtract(\n            relay.cast(kernel, dtype=\"int16\"), relay.cast(kernel_zero_point, \"int16\")\n        )\n    # Otherwise it needs to be broadcast.\n    else:\n        shift_kernel = relay.nn.bias_add(\n            relay.cast(kernel, dtype=\"int16\"),\n            -relay.cast(kernel_zero_point, dtype=\"int16\"),\n        )\n\n    return relay.nn.conv2d_transpose(shift_data, shift_kernel, **attrs)\n\n\n# Generic QNN Conv2D legalization function.\n@tvm.target.generic_func\ndef qnn_dense_legalize(attrs, inputs, types):\n    \"\"\"Default legalization is None.\"\"\"\n    return None\n\n\n###################\n# Helper functions.\n###################\n\n\ndef get_scalar_from_constant(expr):\n    \"\"\"Returns scalar value from Relay constant scalar.\"\"\"\n    assert (\n        isinstance(expr, relay.Constant) and not expr.data.shape\n    ), \"Expr is not a constant scalar.\"\n    value = expr.data.numpy()\n    assert value.dtype == np.dtype(np.int32) or value.dtype == np.dtype(\n        np.float32\n    ), \"value must be float32/int32\"\n    return value.item(0)\n\n\ndef _shift(data, zero_point, out_dtype):\n    \"\"\"Shifts (add/subtracts) the qnn tensor with +/-128)\"\"\"\n    if out_dtype == \"uint8\":\n        shift = 128\n    elif out_dtype == \"int8\":\n        shift = -128\n    else:\n        raise ValueError(\"Unsupported out dtype.\")\n    data_modified = relay.cast(data, \"int32\")\n    data_modified = relay.add(data_modified, relay.const(shift, \"int32\"))\n    data_modified = relay.cast(data_modified, out_dtype)\n    if isinstance(zero_point, relay.Constant):\n        zero_point_val = get_scalar_from_constant(zero_point)\n        zero_point_modified = relay.const(zero_point_val + shift, \"int32\")\n    else:\n        zero_point_modified = zero_point + relay.const(shift, \"int32\")\n    return (data_modified, zero_point_modified)\n\n\n# Helper function for lowering in the abscence of fast Int8 arithmetic units.\ndef helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay_op):\n    \"\"\"Converts QNN operators into a sequence of Relay operators that are friendly to HW that do\n    not have fast Int8 arithmetic. For example, for ARM, LLVM utilizes the assembly instructions\n    much more efficiently if the convolution or dense operator input datatypes are int16 instead of\n    int8. More details are present at https://github.com/apache/tvm/pull/4277.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n\n    # Collect the input exprs.\n    data, kernel, input_zero_point, kernel_zero_point, _, _ = inputs\n\n    shift_data = relay.subtract(\n        relay.cast(data, dtype=\"int16\"), relay.cast(input_zero_point, dtype=\"int16\")\n    )\n    # If kernel zero point is a scalar we can directly subtract it.\n    if len(types[3].shape) == 0:\n        shift_kernel = relay.subtract(\n            relay.cast(kernel, dtype=\"int16\"), relay.cast(kernel_zero_point, dtype=\"int16\")\n        )\n    # Otherwise it needs to be broadcast.\n    else:\n        # Determine output axis of kernel for spatial operations.\n        if hasattr(attrs, \"kernel_layout\"):\n            output_axis = tvm.tir.layout(attrs[\"kernel_layout\"]).index_of(\"O\")\n        # For dense operations, broadcast to [N, K] layout.\n        elif isinstance(attrs, relay.op.op_attrs.DenseAttrs):\n            output_axis = 0\n        # For matrix multiplication instead expand to [K, N] layout.\n        elif isinstance(attrs, relay.op.op_attrs.MatmulAttrs):\n            output_axis = 1\n        else:\n            raise TVMError(\n                \"Legalization of %s is not yet supported with per channel parameters\"\n                % str(type(attrs))\n            )\n\n        shift_kernel = relay.nn.bias_add(\n            relay.cast(kernel, dtype=\"int16\"),\n            -relay.cast(kernel_zero_point, dtype=\"int16\"),\n            output_axis,\n        )\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    return relay_op(shift_data, shift_kernel, **new_attrs)\n\n\n# Helper function to change dtypes to uint8 x int8. Intel VNNI instructions prefer this setting.\ndef helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay_op):\n    \"\"\"Legalizes QNN conv2d/dense op for Intel HW. VNNI supports u8 x i8 fast conv/MM. If the dtypes\n    are already good, we dont transform. Else, we shift the tensor values and zero points to change\n    the dtype.\n\n    Converting from int8 to uint8 can be done in following manner.\n\n    Original equation\n      scale * (QA - zp_a)\n      scale * (QA + 128 - 128 - zp_a)\n      scale * ( (QA + 128) - (zp_a + 128))\n\n    Replacing QA + 128 with QA' and (zp_a + 128) with zp_a'\n    We get our new quantized uint8 tensor - scale * (QA' - zp_a')\n\n    Similarly we can convert from int8 to uint8.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Collect the dtypes.\n    data_dtype = types[0].dtype\n    kernel_dtype = types[1].dtype\n\n    # Collect the input exprs.\n    data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale = inputs\n\n    # VNNI supports u8 x i8 fast conv/MM. Don't do anything if it is already satisfied.\n    if data_dtype == \"uint8\" and kernel_dtype == \"int8\":\n        return None\n\n    # Shift input if necessary.\n    if data_dtype == \"int8\":\n        # Compute (QA + 128) and (zp_a + 128)\n        data, input_zero_point = _shift(data, input_zero_point, \"uint8\")\n\n    # Shift kernel if necessary.\n    if kernel_dtype == \"uint8\":\n        # Compute (QA - 128) and (zp_a - 128)\n        kernel, kernel_zero_point = _shift(kernel, kernel_zero_point, \"int8\")\n\n    # Call qnn.conv2d with modified inputs and zero points.\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    return relay_op(\n        data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale, **new_attrs\n    )\n\n\n# Helper function to change dtypes to int8 x int8. Cuda dp4a instructions prefer this setting.\ndef helper_change_dtypes_to_int8(attrs, inputs, types, relay_op):\n    \"\"\"Legalizes QNN conv2d/dense op for Nvidia HW. dp4a supports i8 x i8 fast conv/MM. If the\n    dtypes are already good, we dont transform. Else, we shift the tensor values and zero points\n    to change the dtype.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Collect the dtypes.\n    data_dtype = types[0].dtype\n    kernel_dtype = types[1].dtype\n\n    # Collect the input exprs.\n    data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale = inputs\n\n    # dp4a supports i8 x i8 fast conv/MM. Don't do anything if it is already satisfied.\n    if data_dtype == \"int8\" and kernel_dtype == \"int8\":\n        return None\n\n    # Shift input if necessary.\n    if data_dtype == \"uint8\":\n        # Compute (QA + 128) and (zp_a + 128)\n        data, input_zero_point = _shift(data, input_zero_point, \"int8\")\n\n    # Shift kernel if necessary.\n    if kernel_dtype == \"uint8\":\n        # Compute (QA - 128) and (zp_a - 128)\n        kernel, kernel_zero_point = _shift(kernel, kernel_zero_point, \"int8\")\n\n    # Call qnn.conv2d with modified inputs and zero points.\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    return relay_op(\n        data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale, **new_attrs\n    )\n\n\n# Helper function to change dtypes to be same. ARM dotprod instructions prefer this setting.\ndef helper_change_dtypes_to_be_same(attrs, inputs, types, relay_op):\n    \"\"\"Sometimes MxNet + MLDNN can lead to uint8 x int8 datatypes for the conv inputs. However,\n    many devices like ARM prefer the datatypes to be same for the HW units. This helper transforms\n    conv2d/dense such that both the dtypes are same.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n\n    def _shift(data, zero_point, out_dtype):\n        \"\"\"Shifts (adds/subtracts) the qnn tensor by 128)\"\"\"\n        if out_dtype == \"uint8\":\n            shift = 128\n        elif out_dtype == \"int8\":\n            shift = -128\n        else:\n            raise ValueError(\"Unsupported out dtype.\")\n        data_modified = relay.cast(data, \"int32\")\n        data_modified = relay.add(data_modified, relay.const(shift, \"int32\"))\n        data_modified = relay.cast(data_modified, out_dtype)\n        zero_point_val = get_scalar_from_constant(zero_point)\n        zero_point_modified = relay.const(zero_point_val + shift, \"int32\")\n        return (data_modified, zero_point_modified)\n\n    # Collect the dtypes.\n    data_dtype = types[0].dtype\n    kernel_dtype = types[1].dtype\n\n    if data_dtype == kernel_dtype:\n        return None\n\n    # Collect the input exprs.\n    data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale = inputs\n\n    assert (\n        \"int8\" in data_dtype and \"int8\" in kernel_dtype\n    ), \"Qnn Conv2D/Dense only accepts uint8 or int8 inputs\"\n\n    # Shift input if necessary.\n    data, input_zero_point = _shift(data, input_zero_point, kernel_dtype)\n\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    return relay_op(\n        data, kernel, input_zero_point, kernel_zero_point, input_scale, kernel_scale, **new_attrs\n    )\n\n\ndef is_fast_int8_on_intel():\n    \"\"\"Checks whether the hardware has support for fast Int8 arithmetic operations.\"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    return target_has_sse42(target.mcpu)\n\n\n########################\n# ARM CPU legalizations.\n########################\n\n\n@qnn_conv2d_legalize.register(\"arm_cpu\")\ndef _qnn_conv2d_legalize_arm_cpu(attrs, inputs, types):\n    target = tvm.target.Target.current(allow_none=False)\n    is_depthwise = relay.op.strategy.is_depthwise_conv2d(\n        types[0].shape,\n        attrs[\"data_layout\"],\n        types[1].shape,\n        attrs[\"kernel_layout\"],\n        attrs[\"groups\"],\n    )\n    use_int8_on_arm = (not is_depthwise) and attrs[\"data_layout\"] == \"NHWC\"\n    other_options = use_int8_on_arm or target.features.has_dotprod\n    if target.features.has_asimd and not other_options:\n        return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.conv2d)\n    # ARM prefers the dtypes to be same.\n    return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.conv2d)\n\n\n@qnn_dense_legalize.register(\"arm_cpu\")\ndef _qnn_dense_legalize_arm_cpu(attrs, inputs, types):\n    target = tvm.target.Target.current(allow_none=False)\n    if target.features.has_asimd and not target.features.has_dotprod:\n        return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.dense)\n    # ARM prefers the dtypes to be same.\n    return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.dense)\n\n\n##########################\n# Intel CPU legalizations.\n##########################\n\n\n@qnn_conv2d_legalize.register(\"cpu\")\ndef _qnn_conv2d_legalize_intel_cpu(attrs, inputs, types):\n    # The VNNI transformations prefer uint8 x int8 datatypes.\n    if is_fast_int8_on_intel():\n        return helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay.qnn.op.conv2d)\n    return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.conv2d)\n\n\n@qnn_dense_legalize.register(\"cpu\")\ndef _qnn_dense_legalize_intel_cpu(attrs, inputs, types):\n    # The VNNI transformations prefer uint8 x int8 datatypes.\n    if is_fast_int8_on_intel():\n        return helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay.qnn.op.dense)\n    return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.dense)\n\n\n#####################\n# CUDA and vulkan legalizations.\n#####################\n\n\n@qnn_conv2d_legalize.register([\"cuda\", \"gpu\"])\ndef _qnn_conv2d_legalize_cuda(attrs, inputs, types):\n    if is_target(\"vulkan\"):\n        # prefers the dtypes to be same. Mixed type is not yet supported.\n        return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.conv2d)\n    if is_target([\"cuda\", \"rocm\"]):\n        # CUDA prefers both datatypes to be int8.\n        return helper_change_dtypes_to_int8(attrs, inputs, types, relay.qnn.op.conv2d)\n    return None\n\n\n@qnn_dense_legalize.register([\"cuda\", \"gpu\"])\ndef _qnn_dense_legalize_cuda(attrs, inputs, types):\n    if is_target(\"vulkan\"):\n        # prefers the dtypes to be same. Mixed type is not yet supported.\n        return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.dense)\n    if is_target([\"cuda\", \"rocm\"]):\n        # CUDA prefers both datatypes to be the int8.\n        return helper_change_dtypes_to_int8(attrs, inputs, types, relay.qnn.op.dense)\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"The register functions for the QNN dialect.\"\"\"\nimport tvm.ir\n\n\ndef register_qnn_legalize(op_name, legal_op=None, level=10):\n    \"\"\"Register legal transformation function for a QNN op.\n\n    This helps QNN match hardware intrinsics better and is run before\n    canonicalization.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    legal_op: function (attrs: Attrs, inputs: List[Expr]) -> new_expr: Expr\n        The function for transforming an expr to another expr.\n\n    level : int\n        The priority level\n    \"\"\"\n    return tvm.ir.register_op_attr(op_name, \"FTVMQnnLegalize\", legal_op, level)\n\n\ndef register_qnn_canonicalize(op_name, legal_op=None, level=10):\n    \"\"\"Register canonicalization function for a QNN op.\n\n    This transforms QNN ops to mainline Relay components.\n\n    Parameters\n    ----------\n    op_name : str\n        The name of the operator\n\n    legal_op: function (Attrs, List[Expr], List[relay.Type]) -> Expr\n        The function for transforming an expr to another expr.\n\n    level : int\n        The priority level\n    \"\"\"\n\n    return tvm.ir.register_op_attr(op_name, \"FTVMQnnCanonicalize\", legal_op, level)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/op/qnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument, not-context-manager\n\"\"\"QNN dialect operators.\"\"\"\n\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nimport tvm.ir\nfrom tvm import relay\nfrom tvm.relay.expr import Tuple, TupleWrapper\nfrom tvm.relay.op.nn.utils import get_pad_tuple2d\nfrom tvm.runtime import Object\nfrom tvm.target import Target\nfrom tvm.topi.nn.qnn import SQNN_DTYPE_TO_CODE\nfrom tvm.topi.x86.utils import target_has_sse41\n\nfrom . import _make, _requantize\n\n\n@tvm._ffi.register_object(\"relay.qnn.op.RequantizeConfig\")\nclass RequantizeConfig(Object):\n    \"\"\"Configure the requantization behavior by setting config variables.\n\n    Note\n    ----\n    This object is backed by node system in C++, with arguments that can be\n    exchanged between python and C++.\n\n    Do not construct directly, use requantize_config instead.\n\n    The fields that are backed by the C++ node are immutable once an instance\n    is constructed. Use _node_defaults getters to get results for the fields.\n    \"\"\"\n\n    @staticmethod\n    def _get_node_default_rounding():\n        return \"UPWARD\"\n\n    @staticmethod\n    def _get_node_default_compute_dtype():\n        target = Target.current(True)\n        if target and str(target.kind) == \"llvm\" and target_has_sse41(target.mcpu):\n            return \"float32\"\n\n        return \"int64\"\n\n    _node_defaults = {\n        \"rounding\": _get_node_default_rounding.__func__,\n        \"compute_dtype\": _get_node_default_compute_dtype.__func__,\n    }\n\n    # pylint: disable=no-member\n    def __init__(self, handle):\n        \"\"\"Initialize the function with handle\n\n        Parameters\n        ----------\n        handle : SymbolHandle\n            the handle to the underlying C++ Symbol\n        \"\"\"\n        super(RequantizeConfig, self).__init__(handle)\n        self.handle = handle\n\n    def __enter__(self):\n        # pylint: disable=protected-access\n        _requantize._EnterRequantizeConfigScope(self)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        _requantize._ExitRequantizeConfigScope()\n\n    def __setattr__(self, name, value):\n        if name in RequantizeConfig._node_defaults:\n            raise AttributeError(\"'%s' object cannot set attribute '%s'\" % (str(type(self)), name))\n        return super(RequantizeConfig, self).__setattr__(name, value)\n\n\ndef current_requantize_config():\n    \"\"\"Get the current requantization configuration.\"\"\"\n    return _requantize._GetCurrentRequantizeConfig()\n\n\ndef requantize_config(**kwargs):\n    \"\"\"Configure the requantization behavior by setting config variables.\n\n    Parameters\n    ---------\n    rounding: \"UPWARD\" or \"TONEAREST\"\n        Rounding direction for fixed point multiplications.\n    compute_dtype:\n        Specifies the data type used during requantize.\n        Supported options: \\\"int64\\\", \\\"float32\\\", \\\"float64\\\"\n\n    Returns\n    -------\n    config: RequantizeConfig\n        The requantization configuration\n    \"\"\"\n    node_args = {\n        k: v() if k not in kwargs else kwargs[k] for k, v in RequantizeConfig._node_defaults.items()\n    }\n    return tvm.ir.make_node(\"relay.qnn.op.RequantizeConfig\", **node_args)\n\n\ndef requantize(\n    data,\n    input_scale,\n    input_zero_point,\n    output_scale,\n    output_zero_point,\n    axis=-1,\n    rounding=\"None\",\n    compute_dtype=\"None\",\n    out_dtype=\"int8\",\n):\n    r\"\"\"Requantized operator.\n\n    The requantize operator converts one quantized tensor representation to\n    another quantized tensor representation. For the output tensor, we are\n    provided with output scale and zero point. The computation is as follows\n\n    Q_output = zp_output +  (scale_input)/(scale_output) * (Q_input - zp_input)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    input_scale: tvm.relay.Expr\n        The quantization scale for the input tensor.\n\n    input_zero_point: tvm.relay.Expr\n        The zero point of the input tensor.\n\n    output_scale: tvm.relay.Expr\n        The quantization scale for the output tensor.\n\n    output_zero_point: tvm.relay.Expr\n        The zero point of the output tensor.\n\n    axis : int\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    rounding : string, optional\n        Defines the rounding direction when the value is midway between two\n        representable values.\n    compute_dtype:\n        Specifies the data type used during requantize.\n        Supported options: \\\"int64\\\", \\\"float32\\\", \\\"float64\\\"\n    out_dtype : str, optional\n        Specifies the output data type.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _make.requantize(\n        data,\n        input_scale,\n        input_zero_point,\n        output_scale,\n        output_zero_point,\n        axis,\n        rounding,\n        compute_dtype,\n        out_dtype,\n    )\n\n\ndef quantize(data, output_scale, output_zero_point, axis=-1, out_dtype=\"int8\"):\n    r\"\"\"Quantize op\n    This operator takes float32 as input and produces quantized int8 or unit8 as output.\n    The input tensor can be of any shape. The output shape is the same as input shape.\n\n    Q_output = clamp((round(input_tensor/output_scale) + output_zero_point),\n                     out_dtype::min,\n                     out_dtype::max)\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n\n    output_scale : tvm.relay.Expr\n        The output scale.\n\n    output_zero_point : tvm.relay.Expr\n        The output zero_point.\n\n    axis : int\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n    out_dtype : str, optional\n        The data type of the input tensor. Can be [int8, uint8, int32]\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _make.quantize(data, output_scale, output_zero_point, axis, out_dtype)\n\n\ndef simulated_quantize(data, output_scale, output_zero_point, axis=-1, out_dtype=\"int8\"):\n    r\"\"\"Simulated Quantize op\n    Mimics the quantize op but has more flexibility in valid inputs and always\n    outputs the same type as the input. This can be useful for\n    calibrating or training a quantized network.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be quantized. Can be of type float32.\n\n    out_dtype : string or tvm.relay.Expr\n        A string or tensor indicating which datatype to quantize to.\n\n    output_scale : tvm.relay.Expr\n        The output scale.\n\n    output_zero_point : tvm.relay.Expr\n        The output zero_point.\n\n    axis : int\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # Convert string dtype to a constant if needed.\n    if isinstance(out_dtype, str):\n        type_code = SQNN_DTYPE_TO_CODE[out_dtype]\n        out_dtype = relay.const(type_code, dtype=\"int32\")\n    # Wrap reshapes around qnn parameter tensors to guarantee shape compatibility.\n    output_scale = relay.op.reshape(output_scale, [-1])\n    output_zero_point = relay.op.reshape(output_zero_point, [-1])\n    return _make.simulated_quantize(data, out_dtype, output_scale, output_zero_point, axis)\n\n\ndef dequantize(data, input_scale, input_zero_point, axis=-1):\n    r\"\"\"Dequantize op\n    This operator takes quantized int8 and unit8 as input and produces\n    dequantized float32 as output. The output shape is the same as input shape. The input\n    tensor can be of any shape.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be dequantized. Can be of type [int8, uint8, int32].\n\n    input_scale : tvm.relay.Expr\n        The input scale.\n\n    input_zero_point : tvm.relay.Expr\n        The input zero_point.\n\n    axis : int\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _make.dequantize(data, input_scale, input_zero_point, axis)\n\n\ndef simulated_dequantize(data, input_scale, input_zero_point, axis=-1, in_dtype=\"int8\"):\n    r\"\"\"Simulated Dequantize op\n    Mimics the dequantize op but has more flexibility in valid inputs and always\n    outputs the same type as the input. This can be useful for calibrating or\n    training a quantized network.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input tensor to be dequantized.\n\n    in_dtype : string or tvm.relay.Expr\n        A string or tensor indicating which datatype to dequantize from.\n\n    input_scale : tvm.relay.Expr\n        The input scale.\n\n    input_zero_point : tvm.relay.Expr\n        The input zero_point.\n\n    axis : int\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # Convert string dtype to a constant if needed.\n    if isinstance(in_dtype, str):\n        type_code = SQNN_DTYPE_TO_CODE[in_dtype]\n        in_dtype = relay.const(type_code, dtype=\"int32\")\n    # Wrap reshapes around qnn parameter tensors to guarantee shape compatibility.\n    input_scale = relay.op.reshape(input_scale, [-1])\n    input_zero_point = relay.op.reshape(input_zero_point, [-1])\n    return _make.simulated_dequantize(data, in_dtype, input_scale, input_zero_point, axis)\n\n\ndef concatenate(data, input_scales, input_zero_points, output_scale, output_zero_point, axis):\n    \"\"\"Concatenate the quantized input tensors along the given axis.\n\n    Parameters\n    ----------\n    data : Union(List[relay.Expr], Tuple[relay.Expr], TupleWrapper[relay.Expr])\n        The list of quantized tensors.\n\n    input_scales : List[relay.Expr]\n        The list of scales of input quantized tensors.\n\n    input_zero_points : List[relay.Expr]\n        The list of zero points of input quantized tensors.\n\n    output_scale : relay.Expr\n        The scale of the output quantized tensor.\n\n    output_zero_point : relay.Expr\n        The zero point of the output quantized tensor.\n\n    axis : int\n        The axis along which the tensors are concatenated.\n\n    Returns\n    -------\n    result: relay.Expr\n        The concatenated quantized tensor.\n    \"\"\"\n\n    if isinstance(data, (list, tuple)):\n        data = Tuple(data)\n    elif isinstance(data, TupleWrapper):\n        data = data.tuple_value\n    if not isinstance(axis, int):\n        raise ValueError(\"For now, we only support integer axis\")\n    input_scales = list(input_scales)\n    input_zero_points = list(input_zero_points)\n\n    return _make.concatenate(\n        data, Tuple(input_scales), Tuple(input_zero_points), output_scale, output_zero_point, axis\n    )\n\n\ndef conv2d(\n    data,\n    kernel,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    channels,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    out_layout=\"\",\n    out_dtype=\"int32\",\n):\n    r\"\"\"Quantized 2D convolution.\n\n    This operator convolves quantized data with quantized kernel.\n    If doing Per-channel quantization, qnn expects the kernel_zero_scale\n    and optionally the kernel_zero_point will be 1-D vectors instead of scalars.\n    The scale of the output quantized tensor is the product of the kernel_scale and\n    input_scale of the input quantized tensors. The zero point of the output\n    quantized tensor is 0. By default, the dtype of output is int32. Please also\n    refer to Requantize operator to understand how to scale back the int32\n    output to (u)int8.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    kernel : tvm.relay.Expr\n        The kernel expressions.\n\n    input_zero_point: tvm.relay.Expr\n           The zero point of the data distribution.\n\n    kernel_zero_point: tvm.relay.Expr\n           The zero point of the quantized_kernel distribution.\n\n    input_scale: tvm.relay.Expr\n           The scale for the input tensor. The scale for the input tensor is\n           stored purely for convenience here. See more commentary below.\n\n    kernel_scale: tvm.relay.Expr\n           The scale for the weight tensor. The scale for the weight tensor is\n           stored for access to this during relay. This information is not\n           needed in the pass pipeline after qnn.conv2d is lowered to the\n           sequence of steps as in nn.conv2d. See also input_scale in Requantize.\n\n    kernel_size : tuple of int\n        The spatial width and height of the convolution kernel.\n\n    channels : int\n        Number of output channels of this convolution.\n\n    strides : tuple of int, optional\n        The strides of convolution.\n\n    padding : tuple of int, optional\n        The padding of convolution on both sides of inputs before convolution.\n\n    dilation : tuple of int, optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the kernel.\n\n    out_layout : str, optional\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    # TODO enforce 4-way padding in topi/nn/conv2d after #4644 merged\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.conv2d(\n        data,\n        kernel,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        out_dtype,\n    )\n\n\ndef conv2d_transpose(\n    data,\n    weight,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    strides=(1, 1),\n    padding=(0, 0),\n    dilation=(1, 1),\n    groups=1,\n    channels=None,\n    kernel_size=None,\n    data_layout=\"NCHW\",\n    kernel_layout=\"IOHW\",\n    out_layout=\"\",\n    output_padding=(0, 0),\n    out_dtype=\"int32\",\n):\n    \"\"\"This operator deconvolves quantized data with quantized kernel. The scale of\n    the output quantized tensor is the product of the kernel_scale and\n    input_scale of the input quantized tensors. The zero point of the output\n    quantized tensor is 0. By default, the dtype of output is int32. Please also\n    refer to Requantize operator to understand how to scale back the int32\n    output to (u)int8.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The input data to the operator.\n\n    weight : tvm.relay.Expr\n        The weight expressions.\n\n    input_zero_point: tvm.relay.Expr\n           The zero point of the data distribution.\n\n    kernel_zero_point: tvm.relay.Expr\n           The zero point of the quantized_kernel distribution.\n\n    input_scale: tvm.relay.Expr\n           The scale for the input tensor. The scale for the input tensor is\n           stored purely for convenience here. See more commentary below.\n\n    kernel_scale: tvm.relay.Expr\n           The scale for the weight tensor. The scale for the weight tensor is\n           stored for access to this during relay. This information is not\n           needed in the pass pipeline after qnn.conv2d_transpose is lowered to the\n           sequence of steps as in nn.conv2d_transpose. See also input_scale in Requantize.\n\n    strides : Tuple[int], optional\n        The strides of convolution.\n\n    padding : Tuple[int], optional\n        The padding of convolution.\n\n    dilation : Tuple[int], optional\n        Specifies the dilation rate to be used for dilated convolution.\n\n    channels : int, optional\n        Number of output channels of this convolution.\n\n    kernel_size : tuple of int, optional\n        The spatial dimensions of the convolution kernel.\n\n    groups : int, optional\n        Number of groups for grouped convolution.\n\n    data_layout : str, optional\n        Layout of the input.\n\n    kernel_layout : str, optional\n        Layout of the weight.\n\n    out_layout : Optional[str]\n        Layout of the output, by default, out_layout is the same as data_layout\n\n    output_padding : Tuple[int], optional\n        Used to identify the padding within the output shape\n        (only used in training, where transpose_conv represents the gradient of a convolution )\n\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision conv2d.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    # convert 2-way padding to 4-way padding\n    padding = get_pad_tuple2d(padding)\n    return _make.conv2d_transpose(\n        data,\n        weight,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        strides,\n        padding,\n        dilation,\n        groups,\n        channels,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        output_padding,\n        out_dtype,\n    )\n\n\ndef add(\n    lhs,\n    rhs,\n    lhs_scale,\n    lhs_zero_point,\n    rhs_scale,\n    rhs_zero_point,\n    output_scale,\n    output_zero_point,\n    lhs_axis=-1,\n    rhs_axis=-1,\n):\n    \"\"\"Quantized addition with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side quantized input data.\n\n    rhs : relay.Expr\n        The right hand side quantized input data.\n\n    lhs_scale: relay.Expr\n        The scale of the lhs quantized expr.\n\n    lhs_zero_point: relay.Expr\n       The zero point of lhs quantized expr.\n\n    rhs_scale: relay.Expr\n        The scale of the rhs quantized expr.\n\n    rhs_zero_point: relay.Expr\n       The zero point of rhs quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    lhs_axis: int\n        The channel axis for lhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    rhs_axis: int\n        The channel axis for rhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.add(\n        lhs,\n        rhs,\n        lhs_scale,\n        lhs_zero_point,\n        rhs_scale,\n        rhs_zero_point,\n        output_scale,\n        output_zero_point,\n        lhs_axis,\n        rhs_axis,\n    )\n\n\ndef dense(\n    data,\n    weight,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    units,\n    out_dtype=\"int32\",\n):\n    \"\"\"Qnn Dense operator.\n    Applies a quantized linear transformation\n\n     .. math::\n\n     `Y = X * W`\n\n    If doing Per-channel quantization, qnn expects the kernel_zero_scale\n    and optionally the kernel_zero_point will be 1-D vectors instead of scalars.\n\n    Parameters\n    ----------\n    data : tvm.relay.Expr\n        The quantized input data to the operator.\n    weight : tvm.relay.Expr\n        The quantized weight expressions.\n    input_zero_point: tvm.relay.Expr\n        The input zero point.\n    kernel_zero_point: tvm.relay.Expr\n        The kernel zero point.\n    input_scale: tvm.relay.Expr\n        The scale for the input tensor.\n    kernel_scale: tvm.relay.Expr\n        The scale for the weight tensor. The scale for the weight tensor is\n        stored for access to this during relay. This information is not\n        needed in the pass pipeline after qnn.conv2d is lowered to the\n        sequence of steps as in nn.conv2d. See also input_scale in Requantize.\n    units : int\n        Number of hidden units of the dense transformation.\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision dense can be int32 or int16.\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The computed result.\n    \"\"\"\n\n    return _make.dense(\n        data,\n        weight,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        units,\n        out_dtype,\n    )\n\n\ndef mul(\n    lhs,\n    rhs,\n    lhs_scale,\n    lhs_zero_point,\n    rhs_scale,\n    rhs_zero_point,\n    output_scale,\n    output_zero_point,\n    lhs_axis=-1,\n    rhs_axis=-1,\n):\n    \"\"\"Quantized multiplication with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side quantized input data.\n\n    rhs : relay.Expr\n        The right hand side quantized input data.\n\n    lhs_scale: relay.Expr\n        The scale of the lhs quantized expr.\n\n    lhs_zero_point: relay.Expr\n       The zero point of lhs quantized expr.\n\n    rhs_scale: relay.Expr\n        The scale of the rhs quantized expr.\n\n    rhs_zero_point: relay.Expr\n       The zero point of rhs quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    lhs_axis: int\n        The channel axis for lhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    rhs_axis: int\n        The channel axis for rhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.mul(\n        lhs,\n        rhs,\n        lhs_scale,\n        lhs_zero_point,\n        rhs_scale,\n        rhs_zero_point,\n        output_scale,\n        output_zero_point,\n        lhs_axis,\n        rhs_axis,\n    )\n\n\ndef tanh(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized tanh.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.tanh(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef exp(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized exponential function.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.exp(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef sqrt(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized square root.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.sqrt(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef rsqrt(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized reciprocal square root.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.rsqrt(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef erf(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized error function.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.erf(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\n# pylint: disable=redefined-builtin\n\n\ndef abs(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized abs function.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.abs(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef sigmoid(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized sigmoid.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.sigmoid(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef hardswish(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized hardswish.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.hardswish(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef log(x, scale, zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized log.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n\n    scale: relay.Expr\n        The scale of the quantized expr.\n\n    zero_point: relay.Expr\n       The zero point of quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.log(\n        x,\n        scale,\n        zero_point,\n        output_scale,\n        output_zero_point,\n    )\n\n\ndef subtract(\n    lhs,\n    rhs,\n    lhs_scale,\n    lhs_zero_point,\n    rhs_scale,\n    rhs_zero_point,\n    output_scale,\n    output_zero_point,\n    lhs_axis=-1,\n    rhs_axis=-1,\n):\n    \"\"\"Quantized subtraction with numpy-style broadcasting.\n\n    Parameters\n    ----------\n    lhs : relay.Expr\n        The left hand side quantized input data.\n\n    rhs : relay.Expr\n        The right hand side quantized input data.\n\n    lhs_scale: relay.Expr\n        The scale of the lhs quantized expr.\n\n    lhs_zero_point: relay.Expr\n       The zero point of lhs quantized expr.\n\n    rhs_scale: relay.Expr\n        The scale of the rhs quantized expr.\n\n    rhs_zero_point: relay.Expr\n       The zero point of rhs quantized expr.\n\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n\n    lhs_axis: int\n        The channel axis for lhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    rhs_axis: int\n        The channel axis for rhs quantization. Default value is -1 which corresponds\n        to the last axis.\n\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n\n    \"\"\"\n    return _make.subtract(\n        lhs,\n        rhs,\n        lhs_scale,\n        lhs_zero_point,\n        rhs_scale,\n        rhs_zero_point,\n        output_scale,\n        output_zero_point,\n        lhs_axis,\n        rhs_axis,\n    )\n\n\ndef batch_matmul(x, y, x_zero_point, y_zero_point, x_scale, y_scale, out_dtype=\"int32\"):\n    r\"\"\"\n    Computes batch matrix multiplication of `x` and `y` when `x` and `y` are data\n    in batch.\n\n    .. math::\n\n        \\mbox{batch_matmul}(x, y)[i, :, :] = \\mbox{matmul}(x[i, :, :], y[i, :, :]^T)\n\n    Parameters\n    ----------\n    x : tvm.relay.Expr\n        The first quantized input.\n        A quantized tensor is represented in following manner\n        `A = scale_a x (QA - zp_A)`\n        where QA is quantized tensor, scale_a and zp_A are quantization\n        params.\n    y : tvm.relay.Expr\n        The second quantized input.\n    x_zero_point: tvm.relay.Expr\n        The first input zero point.\n    y_zero_point: tvm.relay.Expr\n        The second input zero point.\n    x_scale: tvm.relay.Expr\n        The scale for the first input tensor.\n    y_scale: tvm.relay.Expr\n        The scale for the second input tensor.\n    out_dtype : str, optional\n        Specifies the output data type for mixed precision dense can be int32 or int16.\n\n    Returns\n    -------\n    result: tvm.relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.batch_matmul(x, y, x_zero_point, y_zero_point, x_scale, y_scale, out_dtype)\n\n\ndef leaky_relu(x, alpha, input_scale, input_zero_point, output_scale, output_zero_point):\n    \"\"\"Quantized leaky relu.\n\n    Parameters\n    ----------\n    x : relay.Expr\n        The quantized input tensor.\n    alpha: double\n        The alpha value.\n    input_scale: relay.Expr\n        The scale of the input quantized expr.\n    input_zero_point: relay.Expr\n       The zero point of input quantized expr.\n    output_scale: relay.Expr\n        The scale of the output quantized expr.\n    output_zero_point: relay.Expr\n       The zero point of output quantized expr.\n    Returns\n    -------\n    result : relay.Expr\n        The computed result.\n    \"\"\"\n    return _make.leaky_relu(\n        x,\n        alpha,\n        input_scale,\n        input_zero_point,\n        output_scale,\n        output_zero_point,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/strategy/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"QNN op strategies.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .generic import *\nfrom . import hexagon\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/strategy/generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of generic operator strategy.\"\"\"\n\nfrom tvm.target import override_native_generic_func\n\n\ndef wrap_topi_schedule(topi_schedule):\n    \"\"\"Wrap TOPI schedule which doesn't use attrs\"\"\"\n\n    def wrapper(_attrs, outs, target):\n        with target:\n            return topi_schedule(outs)\n\n    return wrapper\n\n\ndef wrap_topi_compute(topi_compute):\n    \"\"\"Wrap TOPI compute which doesn't use attrs\"\"\"\n\n    def wrapper(_attrs, inputs, _out_type):\n        return [topi_compute(*inputs)]\n\n    return wrapper\n\n\ndef wrap_compute_quantize(topi_compute):\n    \"\"\"Wrap TOPI compute which use axis and out data type from attrs\"\"\"\n\n    def wrapper(attrs, inputs, _out_type):\n        axis = attrs.axis\n        out_dtype = attrs.out_dtype\n        args = [*inputs, axis, out_dtype]\n        return [topi_compute(*args)]\n\n    return wrapper\n\n\ndef wrap_compute_dequantize(topi_compute):\n    \"\"\"Wrap TOPI compute which use axis from attrs\"\"\"\n\n    def wrapper(attrs, inputs, _out_type):\n        args = [*inputs, attrs.axis]\n        return [topi_compute(*args)]\n\n    return wrapper\n\n\ndef wrap_topi_qnn_conv2d(topi_compute):\n    \"\"\"Wrap TOPI compute which use conv2d attrs and output data type\"\"\"\n\n    def wrapper(attrs, inputs, out_type):\n        out_dtype = out_type.dtype\n        oshape = out_type.shape\n        strides = attrs.strides\n        padding = attrs.padding\n        dilation = attrs.dilation\n        if len([*inputs]) == 11:\n            args = [*inputs, strides, padding, dilation, oshape, out_dtype]\n        elif len([*inputs]) == 10:\n            args = [  # QNN Conv2d params:\n                inputs[0],\n                inputs[1],\n                inputs[2],\n                inputs[3],\n                inputs[4],\n                inputs[5],\n                # Bias argument\n                None,\n                # Requantization params:\n                inputs[6],\n                inputs[7],\n                inputs[8],\n                inputs[9],\n                # Conv2d attrs:\n                strides,\n                padding,\n                dilation,\n                oshape,\n                out_dtype,\n            ]\n        else:\n            assert len([*inputs]) == 6\n            args = [  # QNN Conv2d params:\n                *inputs,\n                # Bias argument:\n                None,\n                # Requantization params:\n                None,\n                None,\n                None,\n                None,\n                strides,\n                padding,\n                dilation,\n                oshape,\n                out_dtype,\n            ]\n        return [topi_compute(*args)]\n\n    return wrapper\n\n\ndef wrap_topi_qnn_dense(topi_compute):\n    \"\"\"Wrap TOPI compute which use qnn.dense attrs\"\"\"\n\n    def wrapper(_attrs, inputs, out_type):\n        out_dtype = out_type.dtype\n        if len([*inputs]) == 11:\n            args = [*inputs, out_dtype]\n        elif len([*inputs]) == 10:\n            args = [  # QNN Dense params:\n                inputs[0],\n                inputs[1],\n                inputs[2],\n                inputs[3],\n                inputs[4],\n                inputs[5],\n                # Bias argument\n                None,\n                # Requantization params:\n                inputs[6],\n                inputs[7],\n                inputs[8],\n                inputs[9],\n                out_dtype,\n            ]\n        else:\n            assert len([*inputs]) == 6\n            args = [  # QNN Dense params:\n                *inputs,\n                # Bias argument:\n                None,\n                # Requantization params:\n                None,\n                None,\n                None,\n                None,\n                out_dtype,\n            ]\n        return [topi_compute(*args)]\n\n    return wrapper\n\n\ndef wrap_topi_concatenate(topi_compute):\n    \"\"\"Wrap TOPI compute which use qnn.concatenate attrs\"\"\"\n\n    def wrapper(attrs, inputs, out_type):\n        return [topi_compute(inputs, attrs.axis, out_type.dtype)]\n\n    return wrapper\n\n\ndef wrap_topi_qnn_batch_matmul(topi_compute):\n    \"\"\"Wrap TOPI compute which use qnn.batch_matmul attrs\"\"\"\n\n    def wrapper(attrs, inputs, _out_type):\n        assert len([*inputs]) == 6\n        args = [*inputs, attrs.transpose_a, attrs.transpose_b, attrs.out_dtype]\n        return [topi_compute(*args)]\n\n    return wrapper\n\n\n@override_native_generic_func(\"qnn_quantize_strategy\")\ndef qnn_quantize_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.quantize generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.quantize is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_dequantize_strategy\")\ndef qnn_dequantize_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.dequantize generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.dequantize is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_requantize_strategy\")\ndef qnn_requantize_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.requantize generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.requantize is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_add_strategy\")\ndef qnn_add_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.add generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.add is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_concatenate_strategy\")\ndef qnn_concatenate_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.concatenate generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.concatenate is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_conv2d_strategy\")\ndef qnn_conv2d_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.conv2d generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.conv2d is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_dense_strategy\")\ndef qnn_dense_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.dense generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.dense is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n\n\n@override_native_generic_func(\"qnn_batch_matmul_strategy\")\ndef qnn_batch_matmul_strategy(attrs, inputs, out_type, target):\n    \"\"\"qnn.batch_matmul generic strategy\"\"\"\n    raise RuntimeError(\n        \"qnn.batch_matmul is currently only supported with Hexagon. \"\n        \"Please run QNN Canonicalize pass to decompose this op into supported ops.\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/strategy/hexagon.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of Hexagon operator strategy.\"\"\"\n# pylint: disable=unused-argument,wildcard-import,unused-wildcard-import\n\nfrom tvm import topi\nfrom .generic import *\nfrom ... import op as _op\nfrom ...op.strategy.generic import is_depthwise_conv2d\n\n\n@qnn_quantize_strategy.register(\"hexagon\")\ndef qnn_quantize_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.quantize strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_quantize(topi.hexagon.qnn_quantize),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_quantize),\n        name=\"qnn_quantize.hexagon\",\n    )\n    return strategy\n\n\n@qnn_dequantize_strategy.register(\"hexagon\")\ndef qnn_dequantize_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.dequantize strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_dequantize(topi.hexagon.qnn_dequantize),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_dequantize),\n        name=\"qnn_dequantize.hexagon\",\n    )\n    return strategy\n\n\n@qnn_requantize_strategy.register(\"hexagon\")\ndef qnn_requantize_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.requantize strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_compute_quantize(topi.hexagon.qnn_requantize),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_requantize),\n        name=\"qnn_requantize.hexagon\",\n    )\n    return strategy\n\n\n@qnn_add_strategy.register(\"hexagon\")\ndef qnn_add_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.add strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_topi_compute(topi.hexagon.qnn_add),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_add),\n        name=\"qnn_add.hexagon\",\n    )\n    return strategy\n\n\n@qnn_concatenate_strategy.register(\"hexagon\")\ndef qnn_concatenate_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.concatenate strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_topi_concatenate(topi.hexagon.qnn_concatenate),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_concatenate),\n        name=\"qnn_concatenate.hexagon\",\n    )\n    return strategy\n\n\n@qnn_conv2d_strategy.register(\"hexagon\")\ndef qnn_conv2d_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.conv2d strategy for Hexagon\"\"\"\n    data = inputs[0]\n    kernel = inputs[1]\n    data_layout = attrs.data_layout\n    kernel_layout = attrs.kernel_layout\n    groups = attrs.groups\n    strategy = _op.OpStrategy()\n    if groups == 1:\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            strategy.add_implementation(\n                wrap_topi_qnn_conv2d(topi.hexagon.qnn_conv2d),\n                wrap_topi_schedule(topi.hexagon.schedule_qnn_conv2d),\n                name=\"qnn_conv2d.hexagon\",\n            )\n    elif is_depthwise_conv2d(data.shape, data_layout, kernel.shape, kernel_layout, groups):\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            strategy.add_implementation(\n                wrap_topi_qnn_conv2d(topi.hexagon.qnn_depthwise_conv2d),\n                wrap_topi_schedule(topi.hexagon.schedule_qnn_depthwise_conv2d),\n                name=\"qnn_depthwise_conv2d.hexagon\",\n            )\n    else:\n        raise RuntimeError(\"Unsupported strategy for group qnn.conv2d\")\n\n    return strategy\n\n\n@qnn_dense_strategy.register(\"hexagon\")\ndef qnn_dense_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.dense strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_topi_qnn_dense(topi.hexagon.qnn_dense),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_dense),\n        name=\"qnn_dense.hexagon\",\n    )\n    return strategy\n\n\n@qnn_batch_matmul_strategy.register(\"hexagon\")\ndef qnn_batch_matmul_strategy_hexagon(attrs, inputs, out_type, target):\n    \"\"\"qnn.batch_matmul strategy for Hexagon\"\"\"\n    strategy = _op.OpStrategy()\n    strategy.add_implementation(\n        wrap_topi_qnn_batch_matmul(topi.hexagon.qnn_batch_matmul),\n        wrap_topi_schedule(topi.hexagon.schedule_qnn_batch_matmul),\n        name=\"qnn_batch_matmul.hexagon\",\n    )\n    return strategy\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/qnn/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,arguments-differ,no-else-return,unused-argument,missing-docstring\n\"\"\"\nQNN pass transformation infrastructure.\n\"\"\"\nfrom tvm import relay\n\n\ndef CanonicalizeOps():\n    \"\"\"Converts/Lowers an expression containing QNN ops to an expression containing only core\n    (non-Dialect) Relay ops. Each QNN op is lowered to a sequence of existing Relay ops. This is a\n    target-independent pass. One can register the lowering/transformation function for this op using\n    FTVMQnnCanonicalize attr_name for FTVMLegalize op attribute.  An example of this transformation\n    is below\n\n    Examples\n    ________\n\n    .. code-block:: python\n\n        # Original expression\n        qnn_expr = relay.qnn.op.requantize(y,\n                                           input_scale=1,\n                                           input_zero_point=0,\n                                           output_scale=1,\n                                           output_zero_point=0,\n                                           out_dtype='int8')\n\n        # We want to utilize all the existing Relay infrastructure. So, instead of supporting this\n        # QNN requantize op, we convert it into a sequence of existing Relay operators.\n        mod = tvm.IRModule.from_expr(qnn_expr)\n        mod = relay.qnn.transform.CanonicalizeOps()(mod)\n        relay_expr = mod['main']\n        print(relay_expr)\n\n        def @main(%quantized_data: Tensor[(200), int32]) -> Tensor[(200), int8] {\n          %0 = cast(%quantized_data, dtype=\"int64\") /* ty=Tensor[(200), int64] */;\n          %1 = multiply(%0, 2 /* ty=int64 */) /* ty=Tensor[(200), int64] */;\n          %2 = multiply(%1, 1073741824 /* ty=int64 */) /* ty=Tensor[(200), int64] */;\n          %3 = add(%2, 1073741824 /* ty=int64 */) /* ty=Tensor[(200), int64] */;\n          %4 = right_shift(%3, 31 /* ty=int64 */) /* ty=Tensor[(200), int64] */;\n          %5 = add(0 /* ty=int64 */, %4) /* ty=Tensor[(200), int64] */;\n          %6 = clip(%5, a_min=-128f, a_max=127f) /* ty=Tensor[(200), int64] */;\n          cast(%6, dtype=\"int8\") /* ty=Tensor[(200), int8] */\n        }\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that canonicalizes QNN ops to Relay ops.\n    \"\"\"\n\n    return relay.transform.Legalize(\"FTVMQnnCanonicalize\")\n\n\ndef Legalize():\n    \"\"\"Legalizes QNN ops. As opposed to Relay Legalize, this one legalizes only QNN ops. One can\n    register a transformation/legalization function for an op by using the FTVMQnnLegalize attr_name\n    for FTVMLegalize op attribute. The isolation of QNN and Relay Legalize gives us separation of\n    concerns, leading to a better software practice. The legalization can be configured to happen\n    per target. An example of this type of legalization is shown below.\n\n    Examples\n    ________\n\n    Suppose the original graph is as follows\n\n            data(u8)  weight(u8)\n                |       |\n                |       |\n               qnn.conv2d (int32)\n                   |\n                   |\n                nn.relu (int32)\n\n    Now, we know that Intel Cascade Lake has VNNI instructions to speedup convolution. However, it\n    only works on u8 x i8 inputs. So, here, we can use QNN Legalize to transform the above graph as\n    follows\n\n            data(u8)  weight(u8)\n               |          |\n               |          |\n               |     requantize(i8)\n               |        |\n               |        |\n               qnn.conv2d (int32)\n                   |\n                   |\n                 nn.relu (int32)\n\n    In this legalization, since we have isolated legalization for QNN ops, it will only trigger the\n    transformation for qnn.conv2d (and not nn.relu). This pass can be followed by CanonicalizeOps to\n    further lower the qnn.requantize and qnn.conv2d into an expr containing only Relay ops.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that legalizes QNN ops.\n    \"\"\"\n\n    return relay.transform.Legalize(\"FTVMQnnLegalize\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin\n\"\"\"Automatic quantization utilities.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .quantize import *\nfrom ._partition import register_partition_function\nfrom ._annotate import register_annotate_function\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/_annotate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument,inconsistent-return-statements\n\"\"\"Internal module for registering attribute for annotation.\"\"\"\nimport warnings\nfrom tvm import topi\nimport tvm._ffi\nfrom tvm.relay.op import op as _reg\nfrom .. import expr as _expr\nfrom .. import analysis as _analysis\nfrom .. import op as _op\nfrom . import _quantize\nfrom .quantize import QAnnotateKind, current_qconfig, quantize_context\nfrom .quantize import _forward_op\n\n\n@_op.register_compute(\"relay.op.annotation.simulated_quantize\")\ndef simulated_quantize_compute(attrs, inputs, out_type):\n    \"\"\"Compiler for simulated_quantize.\"\"\"\n    assert len(inputs) == 4\n    assert attrs.sign\n    assert attrs.rounding == \"round\"\n\n    data, scale, clip_min, clip_max = inputs\n\n    if attrs.kind == QAnnotateKind.IDENTITY:\n        return [topi.identity(data)]\n\n    # simulate rounding error\n    scaled_data = topi.divide(data, scale)\n    clipped_data = topi.maximum(topi.minimum(scaled_data, clip_max), clip_min)\n    round_data = topi.round(clipped_data)\n\n    # recover data\n    rdata = topi.multiply(round_data, scale)\n    return [rdata]\n\n\n_reg.register_injective_schedule(\"relay.op.annotation.simulated_quantize\")\n_reg.register_pattern(\"relay.op.annotation.simulated_quantize\", _reg.OpPattern.ELEMWISE)\n_reg.register_injective_schedule(\"annotation.cast_hint\")\n\n\n@tvm._ffi.register_object(\"relay.QAnnotateExpr\")\nclass QAnnotateExpr(_expr.TempExpr):\n    \"\"\"A special kind of Expr for Annotating.\n\n    Parameters\n    ---------\n    expr: Expr\n        the original relay ir expr.\n\n    kind: QAnnotateKind\n        the kind of annotation field.\n    \"\"\"\n\n    def __init__(self, expr, kind):\n        self.__init_handle_by_constructor__(_quantize.make_annotate_expr, expr, kind)\n\n\ndef _get_expr_kind(anno):\n    \"\"\"Get the expression and QAnnotateKind from QAnnotateExpr or Expr\"\"\"\n    if isinstance(anno, QAnnotateExpr):\n        return anno.expr, anno.kind\n    return anno, None\n\n\ndef register_annotate_function(op_name, frewrite=None, level=10):\n    \"\"\"register a rewrite function for operator, used by annotation.\n\n    Parameters\n    ---------\n    op_name: str\n        The name of operation\n\n    frewrite : function, optional\n        The function to be registered.\n\n    level : int, optional\n        The priority level\n    \"\"\"\n\n    def default_rewrite(ref_call, new_args, ctx):\n        # recover from QAnnotateExpr\n        args = [_get_expr_kind(x)[0] for x in new_args]\n        return _forward_op(ref_call, args)\n\n    def _register(func):\n        \"\"\"internal register function\"\"\"\n\n        def frewrite_with_guard(ref_call, new_args, ctx):\n            if not current_qconfig().guard(ref_call):\n                return default_rewrite(ref_call, new_args, ctx)\n            return func(ref_call, new_args, ctx)\n\n        return tvm.ir.register_op_attr(op_name, \"FQAnnotateRewrite\", frewrite_with_guard, level)\n\n    return _register(frewrite) if frewrite is not None else _register\n\n\ndef attach_simulated_quantize(data, kind, sign=True, rounding=\"round\"):\n    \"\"\"Attach a simulated quantize operation after input data expr.\n\n    Parameters\n    ---------\n    data: Expr\n        the original data expr.\n\n    kind: QAnnotateKind\n        the kind of annotation field.\n    \"\"\"\n    quantize_op = _op.get(\"relay.op.annotation.simulated_quantize\")\n    if isinstance(data, _expr.Call) and data.op == quantize_op:\n        if data.attrs.kind == kind and data.attrs.sign == sign and data.attrs.rounding == rounding:\n            return data\n\n    qctx = quantize_context()\n    key = tuple([data, kind, sign, rounding])\n    if key in qctx.qnode_map:\n        return qctx.qnode_map[key]\n\n    dom_scale = _expr.var(\"dom_scale\")\n    clip_min = _expr.var(\"clip_min\")\n    clip_max = _expr.var(\"clip_max\")\n    qnode = _quantize.simulated_quantize(data, dom_scale, clip_min, clip_max, kind, sign, rounding)\n    qctx.qnode_map[key] = qnode\n    return qnode\n\n\ntvm._ffi.register_func(\"relay.quantize.attach_simulated_quantize\", attach_simulated_quantize)\n\n\n@register_annotate_function(\"nn.contrib_conv2d_NCHWc\")\ndef conv2d_nchwc_rewrite(ref_call, new_args, ctx):\n    warnings.warn(\n        \"NCHWc layout Conv2D detected, please use a lower \"\n        \"optimization level before applying the quantization \"\n        \"pass as quantization will have no effect here...\"\n    )\n\n\n@register_annotate_function(\"nn.conv2d\")\ndef conv2d_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for conv2d. Lhs of conv will be quantized to\n    input field, and rhs of conv will be quantized to weight field.\n    Output would be in activation field\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None or lhs_kind == QAnnotateKind.ACTIVATION:\n        lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n\n    assert rhs_kind is None\n    rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n\n    expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n\n    return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n\n@register_annotate_function(\"nn.conv1d\")\ndef conv1d_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for conv1d. Lhs of conv will be quantized to\n    input field, and rhs of conv will be quantized to weight field.\n    Output would be in activation field\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None or lhs_kind == QAnnotateKind.ACTIVATION:\n        lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n\n    assert rhs_kind is None\n    rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n\n    expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n\n    return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n\n@register_annotate_function(\"nn.dense\")\ndef dense_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for dense. Lhs of dense will be quantized to input field, and rhs of\n    dense will be quantized to weight field. Output would be in activation field.\"\"\"\n\n    if current_qconfig().skip_dense_layer:\n        return None\n\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None or lhs_kind == QAnnotateKind.ACTIVATION:\n        lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n\n    assert rhs_kind is None\n    rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n\n    expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n\n    return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n\n@register_annotate_function(\"multiply\")\ndef multiply_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for multiply.\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None and rhs_kind is None:\n        return None\n\n    if lhs_kind in [QAnnotateKind.ACTIVATION, QAnnotateKind.INPUT] and rhs_kind is None:\n        # quantize lhs to INPUT field\n        if lhs_kind == QAnnotateKind.ACTIVATION:\n            lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n        if _analysis.check_constant(rhs_expr):\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n        else:\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.INPUT)\n        expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n        return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n    raise ValueError\n\n\n@register_annotate_function(\"add\")\ndef add_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for add.\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None and rhs_kind is None:\n        # trivial case\n        return None\n\n    if lhs_kind is None and rhs_kind is not None:\n        # quantize lhs to INPUT field if it is normal expression\n        assert rhs_kind in [QAnnotateKind.INPUT, QAnnotateKind.ACTIVATION]\n        lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n        expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n        return QAnnotateExpr(expr, QAnnotateKind.INPUT)\n\n    if lhs_kind is not None and rhs_kind is None:\n        if _analysis.check_constant(rhs_expr):\n            # - introduced by batch_norm: add(out, const)\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n        else:\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.INPUT)\n        expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n        return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n    if lhs_kind is not None and rhs_kind is not None:\n        if lhs_kind == QAnnotateKind.INPUT and rhs_kind == QAnnotateKind.INPUT:\n            expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n            return QAnnotateExpr(expr, QAnnotateKind.INPUT)\n        if lhs_kind == QAnnotateKind.ACTIVATION and rhs_kind == QAnnotateKind.ACTIVATION:\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.INPUT)\n            expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n            return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n        if (lhs_kind == QAnnotateKind.ACTIVATION and rhs_kind == QAnnotateKind.INPUT) or (\n            lhs_kind == QAnnotateKind.INPUT and rhs_kind == QAnnotateKind.ACTIVATION\n        ):\n            expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n            return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n    raise ValueError()\n\n\ndef identity_rewrite(ref_call, new_args, ctx):\n    \"\"\"Simply forward the original operation\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    x_expr, x_kind = _get_expr_kind(new_args[0])\n    if x_kind is None:\n        return None\n\n    ret_expr = _forward_op(ref_call, [x_expr])\n    return QAnnotateExpr(ret_expr, x_kind)\n\n\nregister_annotate_function(\"reshape\", identity_rewrite)\nregister_annotate_function(\"clip\", identity_rewrite)\nregister_annotate_function(\"nn.relu\", identity_rewrite)\nregister_annotate_function(\"strided_slice\", identity_rewrite)\nregister_annotate_function(\"nn.avg_pool2d\", identity_rewrite)\nregister_annotate_function(\"nn.batch_flatten\", identity_rewrite)\nregister_annotate_function(\"transpose\", identity_rewrite)\nregister_annotate_function(\"annotation.stop_fusion\", identity_rewrite)\n\n\ndef pool2d_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for max pool2d\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    expr, x_kind = _get_expr_kind(new_args[0])\n\n    if x_kind is None:\n        return None\n    if x_kind == QAnnotateKind.ACTIVATION:\n        expr = attach_simulated_quantize(expr, QAnnotateKind.INPUT)\n\n    expr = _forward_op(ref_call, [expr])\n    return QAnnotateExpr(expr, QAnnotateKind.INPUT)\n\n\nregister_annotate_function(\"nn.max_pool2d\", pool2d_rewrite)\n\n\ndef pool1d_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for max pool1d\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    expr, x_kind = _get_expr_kind(new_args[0])\n\n    if x_kind is None:\n        return None\n    if x_kind == QAnnotateKind.ACTIVATION:\n        expr = attach_simulated_quantize(expr, QAnnotateKind.INPUT)\n\n    expr = _forward_op(ref_call, [expr])\n    return QAnnotateExpr(expr, QAnnotateKind.INPUT)\n\n\nregister_annotate_function(\"nn.max_pool1d\", pool1d_rewrite)\n\n\n@register_annotate_function(\"annotation.cast_hint\")\ndef cast_hint_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function to force cast\"\"\"\n    expr, x_kind = _get_expr_kind(new_args[0])\n\n    if quantize_context().check_to_skip(ref_call):\n        return expr\n\n    if x_kind is None:\n        return new_args[0]\n    if x_kind == QAnnotateKind.ACTIVATION:\n        expr = attach_simulated_quantize(expr, QAnnotateKind.INPUT)\n\n    expr = _forward_op(ref_call, [expr])\n    return QAnnotateExpr(expr, QAnnotateKind.INPUT)\n\n\n@register_annotate_function(\"concatenate\")\ndef concatenate_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for concatenate\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    input_tuple = new_args[0]\n    expr_list = [_get_expr_kind(x)[0] for x in input_tuple]\n    kind_list = [_get_expr_kind(x)[1] for x in input_tuple]\n\n    # make sure the inputs of concatenate are all normal\n    # expression or annotate expression\n    if all([k is None for k in kind_list]):\n        return None\n    for i, k in enumerate(kind_list):\n        if k is None:\n            expr_list[i] = attach_simulated_quantize(expr_list[i], QAnnotateKind.ACTIVATION)\n    expr = _forward_op(ref_call, [_expr.Tuple(expr_list)])\n    return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n\n\n@register_annotate_function(\"nn.global_avg_pool2d\")\ndef global_avg_pool2d_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for global_avg_pool2d for stopping quantize\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    expr, x_kind = _get_expr_kind(new_args[0])\n\n    if x_kind is None:\n        return None\n    expr = _forward_op(ref_call, [new_args[0].realize()])\n\n    # stop quantize after global_avg_pool2d\n    quantize_context().stop_quantize()\n    return expr\n\n\n@register_annotate_function(\"nn.batch_matmul\")\ndef batch_matmul_rewrite(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for batch_matmul\"\"\"\n    if quantize_context().check_to_skip(ref_call):\n        return None\n\n    lhs_expr, lhs_kind = _get_expr_kind(new_args[0])\n    rhs_expr, rhs_kind = _get_expr_kind(new_args[1])\n\n    if lhs_kind is None or lhs_kind == QAnnotateKind.ACTIVATION:\n        if _analysis.check_constant(lhs_expr):\n            lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.WEIGHT)\n        else:\n            lhs_expr = attach_simulated_quantize(lhs_expr, QAnnotateKind.INPUT)\n\n    if rhs_kind is None or rhs_kind == QAnnotateKind.ACTIVATION:\n        if _analysis.check_constant(rhs_expr):\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.WEIGHT)\n        else:\n            rhs_expr = attach_simulated_quantize(rhs_expr, QAnnotateKind.INPUT)\n\n    expr = _forward_op(ref_call, [lhs_expr, rhs_expr])\n    return QAnnotateExpr(expr, QAnnotateKind.ACTIVATION)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/_calibrate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Find scales for quantization on the dataset.\"\"\"\nfrom __future__ import absolute_import\nimport logging\nimport multiprocessing as mp\nimport numpy as np\nimport tvm\nimport tvm.driver\nfrom tvm.ir import IRModule\n\nfrom . import _quantize\nfrom . import quantize\nfrom .. import op as _op\nfrom .. import expr as _expr\nfrom .. import analysis as _analysis\nfrom .. import build_module as _build_module\nfrom ...contrib import graph_executor\nfrom .kl_divergence import _find_scale_by_kl\n\n\ndef _get_profile_runtime(mod):\n    func = mod[\"main\"]\n    func = _quantize.CreateStatsCollector(func)\n\n    if tvm.target.Target.current():\n        target = tvm.target.Target.current()\n        dev = tvm.device(target.kind.name)\n    else:\n        target = \"llvm\"\n        dev = tvm.device(target)\n\n    with tvm.transform.PassContext(opt_level=3):\n        lib = _build_module.build(func, target=target)\n    runtime = graph_executor.GraphModule(lib[\"default\"](dev))\n\n    return runtime\n\n\ndef collect_stats(mod, dataset, chunk_by=-1):\n    \"\"\"Given an annotated graph, create a profile graph to collect profile data from the\n    calibration dataset. This pass collects simulated_quantize op input into a tuple.\n    Simulated_quantize ops are rewritten to identity mode. The tuple is the output of the profile\n    graph.\n\n    Parameters\n    ----------\n    mod: Module\n        The simulation graph after annotation.\n\n    dataset: Iterable[NDArray]\n        The calibration dataset.\n\n    chunk_by: optional, int\n        The size of chunk to be returned in one iteration. It is meant to be\n        used for reducing memory usage. If not specified, return samples for\n        all layers in one chunk.\n\n    Returns\n    -------\n    ret: Iterable[list of ndarray]\n        List of output data of each layer, chunked by the chunk_by parameter\n    \"\"\"\n    logging.info(\"collecting statistics for calibration...\")\n    runtime = _get_profile_runtime(mod)\n    num_outputs = runtime.get_num_outputs()\n    chunk_by = num_outputs if chunk_by == -1 else chunk_by\n\n    for i in range(0, num_outputs, chunk_by):\n        outputs = [[] for i in range(min(chunk_by, num_outputs - i))]\n        for batch in dataset:\n            runtime.set_input(**batch)\n            runtime.run()\n            for j in range(i, min(i + chunk_by, num_outputs)):\n                outputs[j - i].append(runtime.get_output(j).numpy())\n        yield [np.concatenate(output).reshape(-1) for output in outputs]\n\n\ndef _kl_scale(mod, dataset):\n    cfg = quantize.current_qconfig()\n    chunk_by = cfg.calibrate_chunk_by\n    scales = []\n    for samples in collect_stats(mod, dataset, chunk_by):\n        logging.info(\"finding threshold with kl for calibration...\")\n        with mp.Pool() as pool:\n            scales += list(pool.map(_find_scale_by_kl, samples))\n\n    def func(_):\n        scale = scales[func.scale_idx]\n        func.scale_idx += 1\n        return scale\n\n    func.scale_idx = 0\n\n    return func\n\n\ndef _find_scale_by_percentile(arr, percentile=0.99999):\n    assert isinstance(arr, np.ndarray)\n    x = np.abs(arr)\n    max_k = int(x.size * percentile)\n    return np.partition(x, max_k)[max_k]\n\n\ndef _percentile_scale(mod, dataset):\n    cfg = quantize.current_qconfig()\n    chunk_by = cfg.calibrate_chunk_by\n    scales = []\n    for samples in collect_stats(mod, dataset, chunk_by):\n        logging.info(\"finding threshold with percentile for calibration...\")\n        with mp.Pool() as pool:\n            scales += list(pool.map(_find_scale_by_percentile, samples))\n\n    def func(_):\n        scale = scales[func.scale_idx]\n        func.scale_idx += 1\n        return scale\n\n    func.scale_idx = 0\n\n    return func\n\n\ndef _set_params(mod, input_scale_func, weight_scale_func):\n    quantize_op = _op.get(\"relay.op.annotation.simulated_quantize\")\n    cfg = quantize.current_qconfig()\n    const_params = {}\n\n    def visit_func(expr):\n        \"\"\"visitor function for traverse\"\"\"\n        if isinstance(expr, _expr.Call) and expr.op == quantize_op:\n            _, ndom_scale, nclip_min, nclip_max = expr.args\n            attrs = expr.attrs\n            kind = attrs.kind\n            nbit = cfg.get_nbit_by_kind(kind)\n            valid_bit = nbit - attrs.sign\n\n            # set scale\n            if kind == quantize.QAnnotateKind.WEIGHT:\n                assert isinstance(expr.args[0], _expr.Constant)\n                scale = weight_scale_func(expr)\n            else:\n                scale = input_scale_func(expr)\n\n            def _make_const(val):\n                return _expr.const(val, \"float32\")\n\n            valid_range = 2**valid_bit\n            const_params[ndom_scale] = _make_const(scale / valid_range)\n            const_params[nclip_min] = _make_const(-(valid_range - 1))\n            const_params[nclip_max] = _make_const((valid_range - 1))\n\n    main_func = mod[\"main\"]\n    _analysis.post_order_visit(main_func, visit_func)\n    main_func = _expr.bind(main_func, const_params)\n    func_dict = {}\n    for global_var, func in mod.functions.items():\n        if global_var.name_hint != \"main\":\n            func_dict[global_var] = func\n    return IRModule.from_expr(main_func, func_dict)\n\n\n# weight scale functions\ndef _power2_scale(sq_call):  # pylint: disable=unused-argument\n    \"\"\"calculate weight scale with nearest mode-2 scale\"\"\"\n    var = sq_call.args[0]\n    assert isinstance(var, _expr.Constant)\n    val = np.amax(np.abs(var.data.numpy()))\n    return 2 ** np.math.ceil(np.math.log(val, 2)) if val > 0 else 1.0\n\n\ndef _max_scale(sq_call):\n    \"\"\"calculate weight scale with maximum absolute value\"\"\"\n    var = sq_call.args[0]\n    assert isinstance(var, _expr.Constant)\n    val = np.amax(np.abs(var.data.numpy()))\n    return val\n\n\n# input scale functions\ndef _global_scale(sq_call):  # pylint: disable=unused-argument\n    cfg = quantize.current_qconfig()\n    return cfg.global_scale\n\n\ndef calibrate(dataset=None):\n    \"\"\"The calibrate procedure will try to calculate the content of\n    dom_scale, nbit, clip_min, clip_max for every `simulated_quantize`\n    operator.\n\n    Parameters\n    ---------\n    dataset: Optional[Iterable[NDArray]]\n        The calibration dataset.\n\n    Returns\n    -------\n    ret: Function\n        The module pass function.\n    \"\"\"\n\n    def wrapped_func(mod, _):\n        \"\"\"make transform.module pass happy\"\"\"\n        cfg = quantize.current_qconfig()\n\n        if cfg.calibrate_mode == \"kl_divergence\":\n            input_scale_func = _kl_scale(mod, dataset)\n        elif cfg.calibrate_mode == \"global_scale\":\n            input_scale_func = _global_scale\n        elif cfg.calibrate_mode == \"percentile\":\n            input_scale_func = _percentile_scale(mod, dataset)\n        else:\n            raise ValueError(\"Unknown calibrate mode {}\".format(cfg.calibrate_mode))\n\n        if cfg.weight_scale == \"max\":\n            weight_scale_func = _max_scale\n        elif cfg.weight_scale == \"power2\":\n            weight_scale_func = _power2_scale\n        else:\n            raise ValueError(\"Unknown weight scale mode {}\".format(cfg.weight_scale))\n\n        return _set_params(mod, input_scale_func, weight_scale_func)\n\n    return wrapped_func\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/_partition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument,inconsistent-return-statements\n\"\"\"Internal module for registering attribute for annotation.\"\"\"\nimport tvm\nfrom .. import expr as _expr\nfrom .. import analysis as _analysis\nfrom . import _quantize\nfrom .quantize import _forward_op\n\n\ndef register_partition_function(op_name, frewrite=None, level=10):\n    return tvm.ir.register_op_attr(op_name, \"FQPartitionRewrite\", frewrite, level)\n\n\n@tvm._ffi.register_object(\"relay.QPartitionExpr\")\nclass QPartitionExpr(_expr.TempExpr):\n    def __init__(self, expr):\n        self.__init_handle_by_constructor__(_quantize.make_partition_expr, expr)\n\n\ndef partition_expr_check(expr):\n    if isinstance(expr, QPartitionExpr):\n        return True, expr.expr\n    return False, expr\n\n\n@register_partition_function(\"nn.conv2d\")\ndef conv2d_partition_function(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for conv2d for partition\"\"\"\n    data_cond, data = partition_expr_check(new_args[0])\n    kernel_cond, kernel = partition_expr_check(new_args[1])\n\n    assert not kernel_cond\n    if data_cond:\n        data = new_args[0].realize()\n    ret = _forward_op(ref_call, [data, kernel])\n    return QPartitionExpr(ret)\n\n\ndef identity_partition_function(ref_call, new_args, ctx):\n    cond, expr = partition_expr_check(new_args[0])\n    if cond:\n        return QPartitionExpr(_forward_op(ref_call, [expr]))\n    return None\n\n\nregister_partition_function(\"clip\", identity_partition_function)\nregister_partition_function(\"nn.relu\", identity_partition_function)\nregister_partition_function(\"nn.max_pool2d\", identity_partition_function)\n\n\ndef add_partition_generic(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for ewise add for partition for generic devices\"\"\"\n    lhs_cond, lhs = partition_expr_check(new_args[0])\n    rhs_cond, rhs = partition_expr_check(new_args[1])\n    if lhs_cond and rhs_cond:\n        # - introduced by ResNet, when for the first residual connection\n        #     ...\n        #     %0 = nn.conv2d(%data, %meta[relay.Constant])\n        #     %1 = add(%0, %meta[relay.Constant])\n        #     %2 = nn.relu(%1)\n        #     %3 = nn.max_pool2d(%2)\n        #     ...\n        #     %9 = nn.conv2d(%8, %meta[relay.Constant])\n        #     %10 = add(%9, %meta[relay.Constant])\n        #     %11 = add(%3, %10)  <- need to insert annotations for %3, %10\n        #     ...\n        lhs = new_args[0].realize()\n        rhs = new_args[1].realize()\n        return QPartitionExpr(_forward_op(ref_call, [lhs, rhs]))\n    if not lhs_cond and rhs_cond:\n        # - introduced by residual connection in ResNet\n        #     ...\n        #     %13 = nn.conv2d(%12, %meta[relay.Constant])\n        #     %14 = add(%13, %meta[relay.Constant])\n        #     %15 = annotation.cast_hint(%15, 'int8')\n        #     %16 = annotation.stop_fusion(%16)\n        #     %17 = add(%5, %16)\n        #     %18 = nn.relu(%17)\n        #     ...\n        #     %24 = nn.conv2d(%23, %meta[relay.Constant])\n        #     %25 = add(%24, %meta[relay.Constant])\n        #     %26 = add(%18, %25)  <- need to insert annotations for %25\n        #     ...\n        rhs = new_args[1].realize()\n        return _forward_op(ref_call, [lhs, rhs])\n    if lhs_cond and not rhs_cond:\n        if _analysis.check_constant(rhs):\n            # - introduced by batch_norm: add(out, bias)\n            return QPartitionExpr(_forward_op(ref_call, [lhs, rhs]))\n        # - introduced by residual connection in MobileNetV2\n        #     ...\n        #     %81 = add(%80, meta[relay.Constant])\n        #     %82 = annotation.cast_hint(%81, 'int8')\n        #     %83 = annotation.stop_fusion(%82)\n        #     %84 = add(%79, %83)\n        #     ...\n        #     %96 = nn.conv2d(%94, %meta[relay.Constant])\n        #     %96 = add(%95, %meta[relay.Constant])\n        #     %97 = add(%96, %84)  <- need to insert annotations for %96\n        #     ...\n        lhs = new_args[0].realize()\n        return _forward_op(ref_call, [lhs, rhs])\n    if not lhs_cond and not rhs_cond:\n        # trivial case\n        return None\n\n    raise ValueError\n\n\ndef mul_partition_generic(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for ewise mul for partition for generic devices\"\"\"\n    lhs_cond, lhs = partition_expr_check(new_args[0])\n    rhs_cond, rhs = partition_expr_check(new_args[1])\n\n    if lhs_cond:\n        # introduced by bn: multiply(out, scale)\n        lhs = new_args[0].realize()\n        return QPartitionExpr(_forward_op(ref_call, [lhs, rhs]))\n\n    if not lhs_cond and not rhs_cond:\n        # trivial case\n        return None\n\n    raise ValueError\n\n\n# TODO(ziheng) enhance `register_partition_function` to dispatch\n# for target automatically\n@register_partition_function(\"add\")\ndef add_partition_function(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for ewise add for partition\"\"\"\n    target = tvm.target.Target.current()\n    if target and \"cuda\" in target.keys:\n        # TODO(wuwei/ziheng) cuda specific rules\n        return add_partition_generic(ref_call, new_args, ctx)\n    return add_partition_generic(ref_call, new_args, ctx)\n\n\n@register_partition_function(\"multiply\")\ndef multiply_partition_function(ref_call, new_args, ctx):\n    \"\"\"Rewrite function for ewise multiply for partition\"\"\"\n    return mul_partition_generic(ref_call, new_args, ctx)\n\n\n# add cast after the relu op to make it run on vta\n@register_partition_function(\"nn.global_avg_pool2d\")\ndef global_avg_pool2d_partition_function(ref_call, new_args, ctx):\n    cond, expr = partition_expr_check(new_args[0])\n    if cond:\n        expr = new_args[0].realize()\n    else:\n        expr = QPartitionExpr(new_args[0]).realize()\n\n    return _forward_op(ref_call, [expr])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/_partition_conversions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Utilities for partitioning input quantization and output dequantization expressions.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.expr_functor import ExprMutator, ExprVisitor\n\n# operators that are allowed in prefix/suffix partitions, because they are used\n# to quantize/dequantize\nALLOWED_CONVERSION_OPS = [\"add\", \"multiply\", \"right_shift\", \"clip\", \"round\", \"cast\"]\n\n\ndef partition_conversions(mod, quantized_dtypes, ensure_fully_integral):\n    \"\"\"Partition mod into input quantization, core quantized inference, and output dequantization.\n\n    The resulting module includes an additional `main` that fuses all three\n    partitions together.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        Quantized module to partition\n\n    quantized_dtypes : Set[str]\n        Set of data types allowed in quantized operators\n\n    ensure_fully_integral : bool\n        Whether to raise an exception if there are unquantized operators in the result\n\n    Returns\n    -------\n    fused_mod : tvm.IRModule\n        Module containing the input quantization (`quantize_inputs`), core\n        quantized inference (`quantized_main`), output dequantization\n        (`dequantize_outputs`), and full quantized inference functions\n    \"\"\"\n    # Partitioning is implemented as in the diagram below:\n    #\n    #   +----------------------------+\n    #   |Quantized Inference Function|\n    #   +--------------+-------------+\n    #                  |\n    #           partition_prefix\n    #                  |\n    #            +-----+-------------------------+\n    #            |                               |\n    #   +--------v---------+   +-----------------v------------------+\n    #   |Input Quantization|   |Rest of Quantized Inference Function|\n    #   +------------------+   +-----------------+------------------+\n    #                                            |\n    #                                    partition_suffix\n    #                                            |\n    #                                     +------+---------------------+\n    #                                     |                            |\n    #   +------------------+   +----------v------------+   +-----------v---------+\n    #   |Input Quantization|   |Core Quantized Function|   |Output Dequantization|\n    #   +------------------+   +-----------------------+   +---------------------+\n    #\n    # The final module contains all three partitions, as well as a\n    # `main` function that composes these three functions (depicted below).\n    #\n    # +--------------------+-------------------------+-----------------------+\n    # | Input Quantization | Core Quantized Function | Output Dequantization |\n    # +--------------------+-------------------------+-----------------------+\n    assert len(mod.functions) == 1\n    pre_mod, mid_mod = partition_prefix(mod, quantized_dtypes)\n    mid_mod, post_mod = partition_suffix(mid_mod, quantized_dtypes)\n    if ensure_fully_integral:\n        assert has_only_conversion_ops(pre_mod[\"main\"])\n        assert relay.analysis.all_dtypes(mid_mod[\"main\"]).issubset(quantized_dtypes)\n        assert has_only_conversion_ops(post_mod[\"main\"])\n    return fuse_partitions(pre_mod, mid_mod, post_mod)\n\n\ndef fuse_partitions(pre_mod, mid_mod, post_mod):\n    \"\"\"Combine prefix, middle, and suffix modules into a single module.\n\n    The combined module includes an additional `main` that fuses all three\n    partitions together.\n\n    Parameters\n    ----------\n    pre_mod : tvm.IRModule\n        Module containing an input quantization function\n\n    mid_mod : tvm.IRModule\n        Module containing core of a quantized inference function\n\n    post_mod : tvm.IRModule\n        Module containing an output dequantization function\n\n    Returns\n    -------\n    fused_mod : tvm.IRModule\n        Module containing the input quantization, core quantized inference,\n        output dequantization, and full quantized inference functions\n    \"\"\"\n    pre_func = pre_mod[\"main\"]\n    mid_func = mid_mod[\"main\"]\n    post_func = post_mod[\"main\"]\n    # create a module containing the prefix, middle, and suffix partitions\n    fused_mod = tvm.IRModule(\n        functions={\n            relay.GlobalVar(\"quantize_inputs\"): pre_func,\n            relay.GlobalVar(\"quantized_main\"): mid_func,\n            relay.GlobalVar(\"dequantize_outputs\"): post_func,\n        }\n    )\n\n    # construct a `main` that strings together the partitions, such that its\n    # behaviour is equivalent to `main` in an *unpartitioned* module\n    scope_builder = relay.ScopeBuilder()\n    fused_mod_main_params = [relay.Var(param.name_hint) for param in pre_func.params]\n    quantized_inputs = scope_builder.let(\n        \"quantized_inputs\",\n        relay.Call(fused_mod.get_global_var(\"quantize_inputs\"), fused_mod_main_params),\n    )\n    quantized_outputs = scope_builder.let(\n        \"quantized_outputs\",\n        relay.Call(\n            fused_mod.get_global_var(\"quantized_main\"),\n            [relay.TupleGetItem(quantized_inputs, i) for i in range(len(pre_func.ret_type.fields))],\n        ),\n    )\n    dequantized_outputs = scope_builder.let(\n        \"dequantized_outputs\",\n        relay.Call(fused_mod.get_global_var(\"dequantize_outputs\"), [quantized_outputs]),\n    )\n    scope_builder.ret(dequantized_outputs)\n    fused_mod[\"main\"] = relay.Function(fused_mod_main_params, scope_builder.get())\n    return relay.transform.InferType()(fused_mod)\n\n\nclass PrefixCutter(ExprMutator):\n    \"\"\"A mutator for extracting input quantization expressions from a function\n\n    The result of `visit` is the core function, and the input quantization\n    expressions are stored in the `prefix_sb` scope builder.\n    \"\"\"\n\n    def __init__(self, params, quantized_dtypes):\n        ExprMutator.__init__(self)\n        self.params = set(params)\n        self.quantized_dtypes = quantized_dtypes\n        self.subtree_params = set()\n        self.new_func_params = []\n        self.prefix_sb = relay.ScopeBuilder()\n        self.prefix_binding_map = {}\n\n    def visit_var(self, var):\n        if var in self.params:\n            self.subtree_params.add(var)\n        return var\n\n    def visit_call(self, call):\n        # TODO(weberlo) use graph pattern matching?\n        if not hasattr(call.op, \"name\") or call.op.name not in ALLOWED_CONVERSION_OPS:\n            new_args = []\n            for arg in call.args:\n                new_arg = self.visit(arg)\n                if len(self.subtree_params) == 0:\n                    new_args.append(new_arg)\n                else:\n                    assert len(self.subtree_params) == 1\n                    param = next(iter(self.subtree_params))\n                    pre_param = self.prefix_sb.let(param.name_hint, new_arg)\n                    self.subtree_params.clear()\n                    mid_param = relay.Var(param.name_hint, arg.checked_type)\n                    self.prefix_binding_map[mid_param] = pre_param\n                    # return new parameter, then we can use\n                    # relay.analysis.free_vars at the end of the pass to generate\n                    # new `mid_func` type signature\n                    new_args.append(mid_param)\n            return relay.Call(call.op, new_args, call.attrs)\n\n        return super().visit_call(call)\n\n\ndef partition_prefix(mod, quantized_dtypes):\n    \"\"\"Extract input quantization expressions from `mod['main']`.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        Module containing a quantized inference function\n\n    quantized_dtypes : Set[str]\n        Set of data types allowed in quantized operators\n\n    Returns\n    -------\n    pre_mod : tvm.IRModule\n        Module containing the input quantization function\n\n    mid_mod : tvm.IRModule\n        Module containing a function with everything except for input quantization\n    \"\"\"\n    assert len(mod.functions) == 1\n    func = mod[\"main\"]\n    prefix_cutter = PrefixCutter(func.params, quantized_dtypes)\n    mid_body = prefix_cutter.visit(func.body)\n    assert not func.type_params, \"unimplemented\"\n    assert func.attrs is None, \"unimplemented\"\n    mid_func = relay.Function(relay.analysis.free_vars(mid_body), mid_body)\n    mid_mod = tvm.IRModule.from_expr(mid_func)\n    mid_mod = relay.transform.InferType()(mid_mod)\n\n    scope_builder = prefix_cutter.prefix_sb\n    # make sure we pass through all inputs in the prefix function's return expr\n    # (even those that don't require quantization)\n    ret_expr = []\n    for param in mid_func.params:\n        if param in prefix_cutter.prefix_binding_map:\n            # this param required a conversion, so we collected it in the\n            # prefix cutter pass, and we can use the pass's mapping from mid\n            # func params to pre func params\n            ret_expr.append(prefix_cutter.prefix_binding_map[param])\n        else:\n            # there was no detected conversion for this argument, so we thread\n            # it through the prefix function untouched\n            ret_expr.append(relay.Var(param.name_hint, param.checked_type))\n    ret_expr = relay.Tuple(ret_expr)\n    scope_builder.ret(ret_expr)\n    pre_func_body = scope_builder.get()\n    pre_func = relay.Function(relay.analysis.free_vars(pre_func_body), pre_func_body)\n    pre_mod = tvm.IRModule.from_expr(pre_func)\n    pre_mod = relay.transform.InferType()(pre_mod)\n\n    return pre_mod, mid_mod\n\n\nclass SuffixCutter(ExprMutator):\n    \"\"\"A mutator for extracting output dequantization expressions from a function\n\n    The result of `visit` is a function containing the output dequantization\n    expressions, and the middle of the function is stored in `mid_body`.\n    \"\"\"\n\n    def __init__(self, quantized_dtypes):\n        ExprMutator.__init__(self)\n        self.mid_body = None\n        self.quantized_dtypes = quantized_dtypes\n\n    def visit(self, expr):\n        if hasattr(expr, \"checked_type\") and expr.checked_type.dtype in self.quantized_dtypes:\n            self.mid_body = expr\n            return relay.Var(\"input\", expr.checked_type)\n\n        return super().visit(expr)\n\n\ndef partition_suffix(mod, quantized_dtypes):\n    \"\"\"Extract output dequantization expressions from `mod['main']`.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        Module containing a quantized inference function\n\n    quantized_dtypes : Set[str]\n        Set of data types allowed in quantized operators\n\n    Returns\n    -------\n    pre_mod : tvm.IRModule\n        Module containing the input quantization function\n\n    mid_mod : tvm.IRModule\n        Module containing a function with everything except for input quantization\n    \"\"\"\n    assert len(mod.functions) == 1\n    func = mod[\"main\"]\n    suffix_cutter = SuffixCutter(quantized_dtypes)\n    post_body = suffix_cutter.visit(func.body)\n    assert not func.type_params, \"unimplemented\"\n    assert func.attrs is None, \"unimplemented\"\n    post_func = relay.Function(relay.analysis.free_vars(post_body), post_body, func.ret_type)\n    post_mod = tvm.IRModule.from_expr(post_func)\n    post_mod = relay.transform.InferType()(post_mod)\n\n    mid_body = suffix_cutter.mid_body\n    if mid_body is None:\n        # The suffix contains the entire function, meaning there was no\n        # quantization boundary in the given mod.  In this case, we use the\n        # suffix mod as the middle mod and make the suffix an identity function.\n        mid_mod = post_mod\n        post_body = relay.Var(\"input\", mid_mod[\"main\"].ret_type)\n        post_func = relay.Function([post_body], post_body)\n        post_mod = tvm.IRModule.from_expr(post_func)\n        post_mod = relay.transform.InferType()(post_mod)\n    else:\n        mid_func = relay.Function(func.params, mid_body)\n        mid_mod = tvm.IRModule.from_expr(mid_func)\n        mid_mod = relay.transform.InferType()(mid_mod)\n\n    return mid_mod, post_mod\n\n\nclass ConversionOpChecker(ExprVisitor):\n    \"\"\"A pass for checking that the visited function contains only conversion ops\"\"\"\n\n    def __init__(self):\n        ExprVisitor.__init__(self)\n        self.valid = True\n\n    def visit_call(self, call):\n        if not hasattr(call.op, \"name\") or call.op.name not in ALLOWED_CONVERSION_OPS:\n            self.valid = False\n        super().visit_call(call)\n\n\ndef has_only_conversion_ops(func):\n    \"\"\"Return true iff the given function contains only quantization/dequantization ops.\n\n    Parameters\n    ----------\n    func : relay.Function\n        Function being checked\n\n    Returns\n    -------\n    valid : bool\n        Whether the function contains only conversion ops\n    \"\"\"\n    checker = ConversionOpChecker()\n    checker.visit(func)\n    return checker.valid\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/_quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Internal module for quantization.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay._quantize\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/kl_divergence.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Find optimal scale for quantization by minimizing KL-divergence\"\"\"\n\nimport ctypes\nimport numpy as np\n\nfrom . import _quantize\n\n\ndef _find_scale_by_kl(arr, quantized_dtype=\"int8\", num_bins=8001, num_quantized_bins=255):\n    \"\"\"Given a tensor, find the optimal threshold for quantizing it.\n    The reference distribution is `q`, and the candidate distribution is `p`.\n    `q` is a truncated version of the original distribution.\n\n    Ref:\n    http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf\n    \"\"\"\n    assert isinstance(arr, np.ndarray)\n    min_val = np.min(arr)\n    max_val = np.max(arr)\n    thres = max(abs(min_val), abs(max_val))\n\n    if min_val >= 0 and quantized_dtype in [\"uint8\"]:\n        # We need to move negative bins to positive bins to fit uint8 range.\n        num_quantized_bins = num_quantized_bins * 2 + 1\n\n    def get_pointer(arr, ctypes_type):\n        ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes_type))\n        return ctypes.cast(ptr, ctypes.c_void_p)\n\n    hist, hist_edges = np.histogram(arr, bins=num_bins, range=(-thres, thres))\n    hist_ptr = get_pointer(hist.astype(np.int32), ctypes.c_int)\n    hist_edges_ptr = get_pointer(hist_edges, ctypes.c_float)\n\n    return _quantize.FindScaleByKLMinimization(\n        hist_ptr, hist_edges_ptr, num_bins, num_quantized_bins\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/quantize/quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, not-context-manager\n\"\"\"Automatic quantization toolkit.\"\"\"\nimport tvm.ir\nimport tvm\nfrom tvm.runtime import Object\n\nfrom . import _quantize\nfrom ._calibrate import calibrate\nfrom ._partition_conversions import partition_conversions\nfrom .. import expr as _expr\nfrom .. import transform as _transform\n\n\nclass QAnnotateKind(object):\n    \"\"\"Denote the kind of annotation field, corresponding\n    to different nbit configure.\"\"\"\n\n    IDENTITY = 0\n    INPUT = 1\n    WEIGHT = 2\n    ACTIVATION = 3\n\n\ndef kind2str(kind):\n    \"\"\"Convert a `QAnnotateKind` to string\"\"\"\n    str_map = {\n        QAnnotateKind.INPUT: \"input\",\n        QAnnotateKind.WEIGHT: \"weight\",\n        QAnnotateKind.ACTIVATION: \"activation\",\n        QAnnotateKind.IDENTITY: \"identity\",\n    }\n    assert kind in str_map\n    return str_map[kind]\n\n\ndef _forward_op(ref_call, args):\n    \"\"\"forward the operator of ref_call with provided arguments\"\"\"\n    return _expr.Call(ref_call.op, args, ref_call.attrs, ref_call.type_args, ref_call.span)\n\n\n@tvm._ffi.register_object(\"relay.quantize.QConfig\")\nclass QConfig(Object):\n    \"\"\"Configure the quantization behavior by setting config variables.\n\n    Note\n    ----\n    This object is backed by node system in C++, with arguments that can be\n    exchanged between python and C++.\n\n    Do not construct directly, use qconfig instead.\n\n    The fields that are backed by the C++ node are immutable once an instance\n    is constructed. See _node_defaults for the fields.\n    \"\"\"\n\n    _node_defaults = {\n        \"nbit_input\": 8,\n        \"nbit_weight\": 8,\n        \"nbit_activation\": 32,\n        \"dtype_input\": \"int8\",\n        \"dtype_weight\": \"int8\",\n        \"dtype_activation\": \"int32\",\n        \"calibrate_mode\": \"global_scale\",\n        \"global_scale\": 8.0,\n        \"weight_scale\": \"power2\",\n        \"skip_dense_layer\": True,\n        \"skip_conv_layers\": [0],\n        \"do_simulation\": False,\n        \"round_for_shift\": True,\n        \"debug_enabled_ops\": None,\n        \"rounding\": \"UPWARD\",\n        \"calibrate_chunk_by\": -1,\n        \"partition_conversions\": \"disabled\",\n    }\n\n    # pylint: disable=no-member\n    def __init__(self, handle):\n        \"\"\"Initialize the function with handle\n\n        Parameters\n        ----------\n        handle : SymbolHandle\n            the handle to the underlying C++ Symbol\n        \"\"\"\n        super(QConfig, self).__init__(handle)\n        self.handle = handle\n\n    def guard(self, ref_call):\n        \"\"\"Return true if op is enabled, otherwise return false\"\"\"\n        op_name = ref_call.op.name\n        if self.debug_enabled_ops is not None:\n            name_list = [x.value for x in self.debug_enabled_ops]\n            if op_name not in name_list:\n                return False\n        return True\n\n    def get_nbit_by_kind(self, kind):\n        name = kind2str(kind)\n        return getattr(self, \"nbit_\" + name)\n\n    def get_dtype_by_kind(self, kind):\n        name = kind2str(kind)\n        return getattr(self, \"dtype_\" + name)\n\n    def __enter__(self):\n        # pylint: disable=protected-access\n        _quantize._EnterQConfigScope(self)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        _quantize._ExitQConfigScope()\n\n    def __setattr__(self, name, value):\n        if name in QConfig._node_defaults:\n            raise AttributeError(\"'%s' object cannot set attribute '%s'\" % (str(type(self)), name))\n        return super(QConfig, self).__setattr__(name, value)\n\n\ndef current_qconfig():\n    \"\"\"Get the current quantization configuration.\"\"\"\n    return _quantize._GetCurrentQConfig()\n\n\ndef qconfig(**kwargs):\n    \"\"\"Configure the quantization behavior by setting config variables.\n\n    Parameters\n    ---------\n    nbit_dict: dict of QAnnotateKind -> int\n        Number of bit for every kind of annotate field.\n\n    calibrate_mode: str\n        The calibration mode. 'global_scale' or 'kl_divergence'.\n        global_scale: use global scale\n        kl_divergence: find scales by kl divergence on the dataset.\n\n    global_scale: float\n        The global scale for calibration.\n\n    weight_scale: str\n        The way to calculate scales for weights (annotated with QAnnotateKind.WEIGHT).\n        power2: Find the maximum of the absolute value of the tensor, and then round up to power\n        of two.\n        max: Find the maximum of the absolute value of the tensor\n\n    skip_dense_layer: boolean\n        Whether to skip all nn.dense layer type. By default are skipped.\n\n    skip_conv_layers: list\n        Specifying which layers to be skipped. Provide a list of indices\n        that indicate which conv2d layers to leave untouched. Start from 0.\n\n    do_simulation: boolean\n        Whether to do simulation with float operation only.\n\n    round_for_shift: boolean\n        Whether to add bias for rounding during shift.\n\n    debug_enabled_ops: None or list of str\n        Partially quantize specified operators for debugging. The default value\n        is None, which means will try to call all operartors' annotate rewrite\n        function.\n\n    rounding: \"UPWARD\" or \"TONEAREST\"\n        Rounding direction for fixed point multiplications.\n\n    partition_conversions: 'disabled', 'enabled', or 'fully_integral'\n        If set to 'enabled' or 'fully_integral', partitions a quantized\n        result into a module containing\n        a prefix function (consisting of input conversion into the quantized data space),\n        a middle function (consisting of the core quantized network),\n        a suffix function (consisting of output dequantization),\n        and a main function (that calls the prefix, middle, and suffix functions in succession).\n        If set to 'fully_integral' and there are unquantized operators in the result,\n        an exception is raised.\n        The default value is 'disabled'.\n\n    Returns\n    -------\n    config: QConfig\n        The quantization configuration\n    \"\"\"\n    node_args = {k: v if k not in kwargs else kwargs[k] for k, v in QConfig._node_defaults.items()}\n    return tvm.ir.make_node(\"relay.quantize.QConfig\", **node_args)\n\n\nclass QuantizeContext(object):\n    \"\"\"An internal used global context object for annotation,\n    for putting some state variables like `conv2d_counter`.\"\"\"\n\n    Current = None\n\n    def __init__(self):\n        self.qnode_map = dict()\n        self._conv2d_counter = 0\n        self._stop_quantize = False\n\n    def check_to_skip(self, ref_call):\n        \"\"\"Check the index of conv2d layer to decide whether to\n        skip the current operator.\"\"\"\n        if self._stop_quantize:\n            return True\n\n        if current_qconfig().skip_conv_layers is not None:\n            # check skip conv layers\n            skipped_indices = [int(x) for x in current_qconfig().skip_conv_layers]\n            if self._conv2d_counter in skipped_indices and ref_call.op.name == \"nn.conv2d\":\n                self._conv2d_counter += 1\n                return True\n            if ref_call.op.name == \"nn.conv2d\":\n                self._conv2d_counter += 1\n\n        return False\n\n    def stop_quantize(self):\n        self._stop_quantize = True\n\n    def reset(self):\n        self._conv2d_counter = 0\n        self._stop_quantize = False\n\n    def __enter__(self):\n        self.reset()\n        return self\n\n    def __exit__(self, ptype, value, traceback):\n        pass\n\n\ndef quantize_context():\n    \"\"\"Get the global singleton scope\"\"\"\n    if QuantizeContext.Current is None:\n        QuantizeContext.Current = QuantizeContext()\n    return QuantizeContext.Current\n\n\ndef partition():\n    \"\"\"Partition graph into small low-precision sections by `cast_hint` and\n    `stop_fusion`.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass for VTA rewrite.\n    \"\"\"\n    return _quantize.QuantizePartition()\n\n\ndef annotate():\n    \"\"\"Given a float32 graph, this pass will rewrite the graph and return\n    a graph which simulates the error brought by the current quantization\n    scheme.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass for quantization annotation.\n    \"\"\"\n    return _quantize.QuantizeAnnotate()\n\n\ndef realize():\n    \"\"\"The realize pass will transform the simulated quantized graph, which\n    actually computes with float32, to a real low-bit integer graph. It will\n    replace the `simulated_quantize` with several fine-grained operators like\n    add, multiply, and shift as much as possible for better performance.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass for quantization realization.\n    \"\"\"\n    return _quantize.QuantizeRealize()\n\n\ndef _bind_params(func, params):\n    \"\"\"Bind the params to the expression.\"\"\"\n    name_dict = {}\n    for arg in func.params:\n        name = arg.name_hint\n        if name in name_dict:\n            name_dict[name] = None\n        else:\n            name_dict[name] = arg\n    bind_dict = {}\n    for k, v in params.items():\n        if k not in name_dict:\n            continue\n        arg = name_dict[k]\n        if arg is None:\n            raise ValueError(\"Multiple args in the function have name %s\" % k)\n        bind_dict[arg] = _expr.const(v)\n    return _expr.bind(func, bind_dict)\n\n\ndef prerequisite_optimize(mod, params=None):\n    \"\"\"Prerequisite optimization passes for quantization. Perform\n    \"SimplifyInference\", \"FoldScaleAxis\", \"FoldConstant\", and\n    \"CanonicalizeOps\" optimization before quantization.\"\"\"\n    optimize = tvm.transform.Sequential(\n        [\n            _transform.SimplifyInference(),\n            _transform.FoldConstant(),\n            _transform.FoldScaleAxis(),\n            _transform.CanonicalizeOps(),\n            _transform.FoldConstant(),\n        ]\n    )\n\n    if params:\n        mod[\"main\"] = _bind_params(mod[\"main\"], params)\n\n    mod = optimize(mod)\n    return mod\n\n\ndef quantize(mod, params=None, dataset=None):\n    \"\"\"The quantization procedure. Before running the three main\n    procedure of quantization, \"annotate\", \"calibrate\" and \"realize\"\n    , we need to do \"SimplifyInference\", \"FoldScaleAxis\", \"FoldConstant\"\n    first for optimizing.\n\n    Parameters\n    ---------\n    mod: Module\n        The original module.\n\n    params : dict of str to NDArray\n        Input parameters to the graph that do not change\n        during inference time. Used for constant folding.\n\n    dataset: list of dict of Var -> NDArray\n        The calibration dataset.\n\n    Returns\n    -------\n    ret: Function\n        The graph after quantization\n    \"\"\"\n    mod = prerequisite_optimize(mod, params)\n\n    calibrate_pass = tvm.transform.module_pass(\n        calibrate(dataset), opt_level=1, name=\"QuantizeCalibrate\"\n    )\n    quant_passes = [partition(), annotate(), calibrate_pass, tvm.relay.transform.InferType()]\n    if not current_qconfig().do_simulation:\n        quant_passes.append(realize())\n    quant_passes.append(_transform.FoldConstant())\n    quantize_seq = tvm.transform.Sequential(quant_passes)\n    with tvm.transform.PassContext(\n        opt_level=3, required_pass=[\"QuantizeAnnotate\", \"QuantizeCalibrate\", \"QuantizeRealize\"]\n    ):\n        with quantize_context():\n            mod = quantize_seq(mod)\n\n    q_cfg = current_qconfig()\n    assert q_cfg.partition_conversions in [\"disabled\", \"enabled\", \"fully_integral\"]\n    if q_cfg.partition_conversions != \"disabled\":\n        quantized_dtypes = {q_cfg.dtype_input, q_cfg.dtype_weight, q_cfg.dtype_activation}\n        ensure_fully_integral = q_cfg.partition_conversions == \"fully_integral\"\n        return partition_conversions(mod, quantized_dtypes, ensure_fully_integral)\n\n    return mod\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/scope_builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"The scope builder interface.\"\"\"\nfrom __future__ import absolute_import\n\nfrom . import ty as _ty\nfrom . import expr as _expr\nfrom .._ffi import base as _base\n\n\nclass WithScope(object):\n    \"\"\"A wrapper for builder methods which introduce scoping.\n\n    Parameters\n    ----------\n    enter_value: object\n        The value returned by enter.\n    \"\"\"\n\n    def __init__(self, enter_value, exit_cb):\n        self._enter_value = enter_value\n        self._exit_cb = exit_cb\n\n    def __enter__(self):\n        return self._enter_value\n\n    def __exit__(self, ptype, value, trace):\n        if value:\n            raise value\n        self._exit_cb()\n\n\ndef _make_lets(bindings, ret_value):\n    \"\"\"Make a nested let expressions.\n\n    Parameters\n    ----------\n    bindings: List[Tuple[tvm.relay.Var,tvm.relay.Expr]]\n        The sequence of let bindings\n\n    ret_value: tvm.relay.Expr\n        The final value of the expression.\n\n    Returns\n    -------\n    lets: tvm.relay.Expr\n        A nested let expression.\n    \"\"\"\n    if ret_value is None:\n        raise RuntimeError(\"ret is not called in this scope\")\n    if isinstance(ret_value, _expr.If) and ret_value.false_branch is None:\n        raise RuntimeError(\"Creating an If expression without else.\")\n    let_expr = ret_value\n    for var, value in reversed(bindings):\n        let_expr = _expr.Let(var, value, let_expr)\n    return let_expr\n\n\nclass ScopeBuilder(object):\n    \"\"\"Scope builder class.\n\n    Enables users to build up a nested\n    scope(let, if) expression easily.\n\n    Examples\n    --------\n    .. code-block: python\n\n        sb = relay.ScopeBuilder()\n        cond = relay.var(\"cond\", 'bool')\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n\n        with sb.if_scope(cond):\n            one = relay.const(1, \"float32\")\n            t1 = sb.let(t1, relay.add(x, one))\n            sb.ret(t1)\n        with sb.else_scope():\n            sb.ret(y)\n\n        print(sb.get().astext())\n    \"\"\"\n\n    def __init__(self):\n        self._bindings = [[]]\n        self._ret_values = [None]\n\n    def _enter_scope(self):\n        self._bindings.append([])\n        self._ret_values.append(None)\n\n    def _exit_scope(self):\n        bindings = self._bindings.pop()\n        ret_value = self._ret_values.pop()\n        return bindings, ret_value\n\n    def let(self, var, value):\n        \"\"\"Create a new let binding.\n\n        Parameters\n        ----------\n        var: Union[Tuple[str, relay.Type], tvm.relay.Var]\n            The variable or name of variable.\n\n        value: tvm.relay.Expr\n            The value to be bound\n        \"\"\"\n        if isinstance(var, (tuple, list)):\n            if len(var) > 2:\n                raise ValueError(\"Expect var to be Tuple[str, relay.Type]\")\n            var = _expr.var(*var)\n        elif isinstance(var, _base.string_types):\n            var = _expr.var(var)\n        self._bindings[-1].append((var, value))\n        return var\n\n    def if_scope(self, cond):\n        \"\"\"Create a new if scope.\n\n        Parameters\n        ----------\n        cond: tvm.relay.expr.Expr\n            The condition\n\n        Returns\n        -------\n        scope: WithScope\n            The if scope.\n\n        Note\n        ----\n        The user must follows with an else scope.\n        \"\"\"\n        self._enter_scope()\n\n        def _on_exit():\n            bindings, ret_value = self._exit_scope()\n            if self._ret_values[-1] is not None:\n                raise RuntimeError(\"result already returned before if scope\")\n            true_branch = _make_lets(bindings, ret_value)\n            self._ret_values[-1] = _expr.If(cond, true_branch, None)\n\n        return WithScope(None, _on_exit)\n\n    def else_scope(self):\n        \"\"\"Create a new else scope.\n\n        Returns\n        -------\n        scope: WithScope\n            The if scope.\n        \"\"\"\n        self._enter_scope()\n\n        def _on_exit():\n            bindings, ret_value = self._exit_scope()\n            partial_if = self._ret_values[-1]\n            no_else = not isinstance(partial_if, _expr.If) or partial_if.false_branch is not None\n            if no_else:\n                raise RuntimeError(\"else scope must follows\")\n            false_branch = _make_lets(bindings, ret_value)\n            self._ret_values[-1] = _expr.If(partial_if.cond, partial_if.true_branch, false_branch)\n\n        return WithScope(None, _on_exit)\n\n    def type_of(self, expr):\n        \"\"\"\n        Compute the type of an expression.\n\n        Parameters\n        ----------\n        expr: relay.Expr\n            The expression to compute the type of.\n        \"\"\"\n        if isinstance(expr, _expr.Var):\n            return expr.type_annotation\n\n        ity = _ty.IncompleteType()\n        var = _expr.var(\"unify\", ity)\n        self.let(var, expr)\n        return ity\n\n    def ret(self, value):\n        \"\"\"Set the return value of this scope.\n\n        Parameters\n        ----------\n        value: tvm.relay.expr.Expr\n            The return value.\n        \"\"\"\n        if self._ret_values[-1] is not None:\n            raise RuntimeError(\"ret value is already set in this scope.\")\n        self._ret_values[-1] = value\n\n    def get(self):\n        \"\"\"Get the generated result.\n\n        Returns\n        -------\n        value: tvm.relay.expr.Expr\n            The final result of the expression.\n        \"\"\"\n        if len(self._bindings) != 1:\n            raise RuntimeError(\"can only call get at the outmost scope\")\n        return _make_lets(self._bindings[-1], self._ret_values[-1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Utilities for testing and benchmarks\"\"\"\nfrom __future__ import absolute_import as _abs\nimport collections\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import op\nfrom tvm.relay.prelude import Prelude\nfrom tvm.testing import enabled_targets\n\nfrom . import mlp\nfrom . import resnet\nfrom . import resnet_3d\nfrom . import dqn\nfrom . import dcgan\nfrom . import mobilenet\nfrom . import lstm\nfrom . import inception_v3\nfrom . import squeezenet\nfrom . import vgg\nfrom . import densenet\nfrom . import yolo_detection\nfrom . import temp_op_attr\nfrom . import synthetic\n\nfrom .init import create_workload\nfrom .nat import count, make_nat_value, make_nat_expr\nfrom .py_converter import to_python, run_as_python\nfrom ..transform import gradient\n\n\ndef run_opt_pass(expr, opt_pass, import_prelude=False):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    if import_prelude:\n        Prelude(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef run_infer_type(expr):\n    return run_opt_pass(expr, relay.transform.InferType())\n\n\ndef _np_randn_from_type(t, scale=1, mean=0):\n    res = mean + (scale * np.random.randn(*(int(d) for d in t.shape)))\n    # if t.shape == (), then randn returns a scalar so we need to wrap for dtype conversion\n    if np.isscalar(res):\n        res = np.array(res)\n    return res.astype(t.dtype)\n\n\ndef check_grad(\n    func,\n    inputs=None,\n    test_inputs=None,\n    eps=1e-6,\n    atol=1e-5,\n    rtol=1e-3,\n    scale=None,\n    mean=0,\n    mode=\"higher_order\",\n    target_devices=None,\n    executor_kind=\"debug\",\n):\n    \"\"\"Perform numerical gradient checking given a relay function.\n\n    Compare analytical gradients to numerical gradients derived from two-sided approximation. Note\n    that this test may fail if your function input types are not of high enough precision.\n\n    Parameters\n    ----------\n    func : tvm.relay.Function\n        The relay function to test.\n\n    inputs: List[np.array]\n        Optional user-provided input parameters to use. If not given, will generate random normal\n        inputs scaled to be close to the chosen epsilon value to avoid numerical precision loss.\n\n    test_inputs: List[np.array]\n        The inputs to test for gradient matching. Useful in cases where some inputs are not\n        differentiable, such as symbolic inputs to dynamic ops. If not given, all inputs are\n        tested.\n\n    eps: float\n        The epsilon value to use for computing numerical gradient approximation.\n\n    atol: float\n        The absolute tolerance on difference between numerical and analytical gradients. Note that\n        this needs to be scaled appropriately relative to the chosen eps and inputs.\n\n    rtol: float\n        The relative tolerance on difference between numerical and analytical gradients. Note that\n        this needs to be scaled appropriately relative to the chosen eps.\n\n    scale: float\n        The standard deviation of the inputs.\n\n    mean: float\n        The mean of the inputs.\n\n    target_devices: Optional[List[Tuple[tvm.target.Target, tvm.runtime.Device]]]\n        A list of targets/devices on which the gradient should be\n        tested.  If not specified, will default to `tvm.testing.enabled_targets()`.\n\n    \"\"\"\n\n    fwd_func = run_infer_type(func)\n    bwd_func = run_infer_type(gradient(fwd_func, mode=mode))\n    bwd_func = run_opt_pass(bwd_func, relay.transform.Legalize())\n\n    if scale is None:\n        scale = 10 * eps\n\n    if inputs is None:\n        params = fwd_func.params\n        # Generate random inputs on the same scale as epsilon to avoid numerical precision loss.\n        inputs = [_np_randn_from_type(x.checked_type, scale=scale, mean=mean) for x in params]\n\n    if test_inputs is None:\n        test_inputs = inputs\n\n    if target_devices is None:\n        target_devices = enabled_targets()\n\n    for target, dev in target_devices:\n        # Eval the backward and forward functions\n        # TODO(mbs): Evaluate a pair of functions so can share preparation between them.\n        bwd_func_compiled = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(bwd_func)\n        fwd_func_compiled = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(fwd_func)\n\n        # Get analytic gradients.\n        _, grads = bwd_func_compiled(*inputs)\n        grads = [grad.numpy().astype(\"float64\") for grad in grads]\n\n        # Throw out gradients we aren't testing\n        if inputs != test_inputs:\n            tmp = []\n            # find the gradient that corresponds to every test input\n            for test_input in test_inputs:\n                for i, grad in enumerate(grads):\n                    if inputs[i] is test_input:\n                        tmp.append(grad)\n                        break\n            grads = tmp\n\n        assert len(grads) > 0, \"You must test at least one gradient.\"\n\n        # Get numeric gradients for each dimension of each param, using two-sided approximation.\n        approx_grads = []\n        for x in test_inputs:\n            approx_grad = np.zeros(x.shape)\n            for i in np.ndindex(*x.shape):\n                x_i = x[i]\n                x[i] = x_i + eps\n                fwd_plus = fwd_func_compiled(*inputs).numpy().astype(\"float64\")\n                x[i] = x_i - eps\n                fwd_minus = fwd_func_compiled(*inputs).numpy().astype(\"float64\")\n                x[i] = x_i\n                approx_grad[i] = np.sum((fwd_plus - fwd_minus) / (2 * eps))\n            approx_grads.append(approx_grad)\n        # Compare gradients by checking that relative difference is below tolerance.\n        for grad, approx_grad in zip(grads, approx_grads):\n            np.testing.assert_allclose(grad, approx_grad, atol=atol, rtol=rtol)\n\n\ndef rand(dtype, *shape):\n    return tvm.nd.array(np.random.rand(*shape).astype(dtype))\n\n\ndef count_ops(expr):\n    \"\"\"count number of times a given op is called in the graph\"\"\"\n\n    class OpCounter(tvm.relay.ExprVisitor):\n        \"\"\"OpCounter\"\"\"\n\n        def visit_call(self, call):\n            if hasattr(call, \"op\"):\n                self.node_counter[call.op.name] += 1\n            return super().visit_call(call)\n\n        def count(self, expr):\n            self.node_set = {}\n            self.node_counter = collections.Counter()\n            self.visit(expr)\n            return self.node_counter\n\n    return OpCounter().count(expr)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/byoc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines test utilties useful for testing BYOC flows.\"\"\"\n\nfrom tvm import relay\nfrom tvm.relay.expr_functor import ExprMutator\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\n\n\nclass CcompilerAnnotator(ExprMutator):\n    \"\"\"\n    This is used to create external functions for ccompiler.\n    A simple annotator that creates the following program:\n           |\n      -- begin --\n           |\n          add\n           |\n        subtract\n           |\n        multiply\n           |\n       -- end --\n           |\n    \"\"\"\n\n    def __init__(self):\n        super(CcompilerAnnotator, self).__init__()\n        self.in_compiler = 0\n\n    def visit_call(self, call):\n        if call.op.name == \"add\":  # Annotate begin at args\n            if self.in_compiler == 1:\n                lhs = compiler_begin(super().visit(call.args[0]), \"ccompiler\")\n                rhs = compiler_begin(super().visit(call.args[1]), \"ccompiler\")\n                op = relay.add(lhs, rhs)\n                self.in_compiler = 2\n                return op\n        elif call.op.name == \"subtract\":\n            if self.in_compiler == 1:\n                lhs = super().visit(call.args[0])\n                rhs = super().visit(call.args[1])\n                if isinstance(lhs, relay.expr.Var):\n                    lhs = compiler_begin(lhs, \"ccompiler\")\n                if isinstance(rhs, relay.expr.Var):\n                    rhs = compiler_begin(rhs, \"ccompiler\")\n                return relay.subtract(lhs, rhs)\n        elif call.op.name == \"multiply\":  # Annotate end at output\n            self.in_compiler = 1\n            lhs = super().visit(call.args[0])\n            rhs = super().visit(call.args[1])\n            if isinstance(lhs, relay.expr.Var):\n                lhs = compiler_begin(lhs, \"ccompiler\")\n            if isinstance(rhs, relay.expr.Var):\n                rhs = compiler_begin(rhs, \"ccompiler\")\n            op = relay.multiply(lhs, rhs)\n            if self.in_compiler == 2:\n                op = compiler_end(op, \"ccompiler\")\n            self.in_compiler = 0\n            return op\n        return super().visit_call(call)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/darknet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, no-init\n\"\"\"\nCompile DarkNet Models\n====================\nDarkNet helper functions for darknet model parsing and image loading.\nThis functions will not be loaded by default.\nThese are utility functions used for testing and tutorial file.\n\"\"\"\nfrom __future__ import division\nfrom cffi import FFI\nimport numpy as np\nimport cv2\n\n\ndef convert_image(image):\n    \"\"\"Convert the image with numpy.\"\"\"\n    imagex = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    imagex = np.array(imagex)\n    imagex = imagex.transpose((2, 0, 1))\n    imagex = np.divide(imagex, 255.0)\n    imagex = np.flip(imagex, 0)\n    return imagex\n\n\ndef load_image_color(test_image):\n    \"\"\"To load the image using opencv api and do preprocessing.\"\"\"\n    imagex = cv2.imread(test_image)\n    return convert_image(imagex)\n\n\ndef _letterbox_image(img, w_in, h_in):\n    \"\"\"To get the image in boxed format.\"\"\"\n    imh, imw, imc = img.shape\n    if (w_in / imw) < (h_in / imh):\n        new_w = w_in\n        new_h = imh * w_in // imw\n    else:\n        new_h = h_in\n        new_w = imw * h_in // imh\n    dim = (new_w, new_h)\n    # Default interpolation method is INTER_LINEAR\n    # Other methods are INTER_AREA, INTER_NEAREST, INTER_CUBIC and INTER_LANCZOS4\n    # For more information see:\n    # https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#resize\n    resized = cv2.resize(src=img, dsize=dim, interpolation=cv2.INTER_CUBIC)\n    resized = convert_image(resized)\n    boxed = np.full((imc, h_in, w_in), 0.5, dtype=float)\n    _, resizedh, resizedw = resized.shape\n    boxed[\n        :,\n        int((h_in - new_h) / 2) : int((h_in - new_h) / 2) + resizedh,\n        int((w_in - new_w) / 2) : int((w_in - new_w) / 2) + resizedw,\n    ] = resized\n    return boxed\n\n\ndef load_image(img, resize_width, resize_height):\n    \"\"\"Load the image and convert to the darknet model format.\n    The image processing of darknet is different from normal.\n    Parameters\n    ----------\n    image : string\n        The image file name with path\n\n    resize_width : integer\n        The width to which the image needs to be resized\n\n    resize_height : integer\n        The height to which the image needs to be resized\n\n    Returns\n    -------\n    img : Float array\n        Array of processed image\n    \"\"\"\n    imagex = cv2.imread(img)\n    return _letterbox_image(imagex, resize_width, resize_height)\n\n\nclass LAYERTYPE(object):\n    \"\"\"Darknet LAYERTYPE Class constant.\"\"\"\n\n    CONVOLUTIONAL = 0\n    DECONVOLUTIONAL = 1\n    CONNECTED = 2\n    MAXPOOL = 3\n    SOFTMAX = 4\n    DETECTION = 5\n    DROPOUT = 6\n    CROP = 7\n    ROUTE = 8\n    COST = 9\n    NORMALIZATION = 10\n    AVGPOOL = 11\n    LOCAL = 12\n    SHORTCUT = 13\n    ACTIVE = 14\n    RNN = 15\n    GRU = 16\n    LSTM = 17\n    CRNN = 18\n    BATCHNORM = 19\n    NETWORK = 20\n    XNOR = 21\n    REGION = 22\n    YOLO = 23\n    REORG = 24\n    UPSAMPLE = 25\n    LOGXENT = 26\n    L2NORM = 27\n    BLANK = 28\n\n\nclass ACTIVATION(object):\n    \"\"\"Darknet ACTIVATION Class constant.\"\"\"\n\n    LOGISTIC = 0\n    RELU = 1\n    RELIE = 2\n    LINEAR = 3\n    RAMP = 4\n    TANH = 5\n    PLSE = 6\n    LEAKY = 7\n    ELU = 8\n    LOGGY = 9\n    STAIR = 10\n    HARDTAN = 11\n    LHTAN = 12\n\n\n__darknetffi__ = FFI()\n\n__darknetffi__.cdef(\n    \"\"\"\ntypedef struct network network;\ntypedef struct layer layer;\n\ntypedef struct{\n    int *leaf;\n    int n;\n    int *parent;\n    int *child;\n    int *group;\n    char **name;\n\n    int groups;\n    int *group_size;\n    int *group_offset;\n} tree;\n\ntypedef enum{\n    LOGISTIC, RELU, RELIE, LINEAR, RAMP, TANH, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN\n} ACTIVATION;\n\n\ntypedef enum {\n    CONVOLUTIONAL,\n    DECONVOLUTIONAL,\n    CONNECTED,\n    MAXPOOL,\n    SOFTMAX,\n    DETECTION,\n    DROPOUT,\n    CROP,\n    ROUTE,\n    COST,\n    NORMALIZATION,\n    AVGPOOL,\n    LOCAL,\n    SHORTCUT,\n    ACTIVE,\n    RNN,\n    GRU,\n    LSTM,\n    CRNN,\n    BATCHNORM,\n    NETWORK,\n    XNOR,\n    REGION,\n    YOLO,\n    REORG,\n    UPSAMPLE,\n    LOGXENT,\n    L2NORM,\n    BLANK\n} LAYERTYPE;\n\ntypedef enum{\n    SSE, MASKED, L1, SEG, SMOOTH, WGAN\n} COSTTYPE;\n\n\nstruct layer{\n    LAYERTYPE type;\n    ACTIVATION activation;\n    COSTTYPE cost_type;\n    void (*forward);\n    void (*backward);\n    void (*update);\n    void (*forward_gpu);\n    void (*backward_gpu);\n    void (*update_gpu);\n    int batch_normalize;\n    int shortcut;\n    int batch;\n    int forced;\n    int flipped;\n    int inputs;\n    int outputs;\n    int nweights;\n    int nbiases;\n    int extra;\n    int truths;\n    int h,w,c;\n    int out_h, out_w, out_c;\n    int n;\n    int max_boxes;\n    int groups;\n    int size;\n    int side;\n    int stride;\n    int reverse;\n    int flatten;\n    int spatial;\n    int pad;\n    int sqrt;\n    int flip;\n    int index;\n    int binary;\n    int xnor;\n    int steps;\n    int hidden;\n    int truth;\n    float smooth;\n    float dot;\n    float angle;\n    float jitter;\n    float saturation;\n    float exposure;\n    float shift;\n    float ratio;\n    float learning_rate_scale;\n    float clip;\n    int softmax;\n    int classes;\n    int coords;\n    int background;\n    int rescore;\n    int objectness;\n    int joint;\n    int noadjust;\n    int reorg;\n    int log;\n    int tanh;\n    int *mask;\n    int total;\n\n    float alpha;\n    float beta;\n    float kappa;\n\n    float coord_scale;\n    float object_scale;\n    float noobject_scale;\n    float mask_scale;\n    float class_scale;\n    int bias_match;\n    int random;\n    float ignore_thresh;\n    float truth_thresh;\n    float thresh;\n    float focus;\n    int classfix;\n    int absolute;\n\n    int onlyforward;\n    int stopbackward;\n    int dontload;\n    int dontsave;\n    int dontloadscales;\n\n    float temperature;\n    float probability;\n    float scale;\n\n    char  * cweights;\n    int   * indexes;\n    int   * input_layers;\n    int   * input_sizes;\n    int   * map;\n    float * rand;\n    float * cost;\n    float * state;\n    float * prev_state;\n    float * forgot_state;\n    float * forgot_delta;\n    float * state_delta;\n    float * combine_cpu;\n    float * combine_delta_cpu;\n\n    float * concat;\n    float * concat_delta;\n\n    float * binary_weights;\n\n    float * biases;\n    float * bias_updates;\n\n    float * scales;\n    float * scale_updates;\n\n    float * weights;\n    float * weight_updates;\n\n    float * delta;\n    float * output;\n    float * loss;\n    float * squared;\n    float * norms;\n\n    float * spatial_mean;\n    float * mean;\n    float * variance;\n\n    float * mean_delta;\n    float * variance_delta;\n\n    float * rolling_mean;\n    float * rolling_variance;\n\n    float * x;\n    float * x_norm;\n\n    float * m;\n    float * v;\n\n    float * bias_m;\n    float * bias_v;\n    float * scale_m;\n    float * scale_v;\n\n\n    float *z_cpu;\n    float *r_cpu;\n    float *h_cpu;\n    float * prev_state_cpu;\n\n    float *temp_cpu;\n    float *temp2_cpu;\n    float *temp3_cpu;\n\n    float *dh_cpu;\n    float *hh_cpu;\n    float *prev_cell_cpu;\n    float *cell_cpu;\n    float *f_cpu;\n    float *i_cpu;\n    float *g_cpu;\n    float *o_cpu;\n    float *c_cpu;\n    float *dc_cpu;\n\n    float * binary_input;\n\n    struct layer *input_layer;\n    struct layer *self_layer;\n    struct layer *output_layer;\n\n    struct layer *reset_layer;\n    struct layer *update_layer;\n    struct layer *state_layer;\n\n    struct layer *input_gate_layer;\n    struct layer *state_gate_layer;\n    struct layer *input_save_layer;\n    struct layer *state_save_layer;\n    struct layer *input_state_layer;\n    struct layer *state_state_layer;\n\n    struct layer *input_z_layer;\n    struct layer *state_z_layer;\n\n    struct layer *input_r_layer;\n    struct layer *state_r_layer;\n\n    struct layer *input_h_layer;\n    struct layer *state_h_layer;\n\n    struct layer *wz;\n    struct layer *uz;\n    struct layer *wr;\n    struct layer *ur;\n    struct layer *wh;\n    struct layer *uh;\n    struct layer *uo;\n    struct layer *wo;\n    struct layer *uf;\n    struct layer *wf;\n    struct layer *ui;\n    struct layer *wi;\n    struct layer *ug;\n    struct layer *wg;\n\n    tree *softmax_tree;\n\n    size_t workspace_size;\n};\n\n\ntypedef enum {\n    CONSTANT, STEP, EXP, POLY, STEPS, SIG, RANDOM\n} LEARNINGRATEPOLICY;\n\ntypedef struct network{\n    int n;\n    int batch;\n    size_t *seen;\n    int *t;\n    float epoch;\n    int subdivisions;\n    layer *layers;\n    float *output;\n    LEARNINGRATEPOLICY policy;\n\n    float learning_rate;\n    float momentum;\n    float decay;\n    float gamma;\n    float scale;\n    float power;\n    int time_steps;\n    int step;\n    int max_batches;\n    float *scales;\n    int   *steps;\n    int num_steps;\n    int burn_in;\n\n    int adam;\n    float B1;\n    float B2;\n    float eps;\n\n    int inputs;\n    int outputs;\n    int truths;\n    int notruth;\n    int h, w, c;\n    int max_crop;\n    int min_crop;\n    float max_ratio;\n    float min_ratio;\n    int center;\n    float angle;\n    float aspect;\n    float exposure;\n    float saturation;\n    float hue;\n    int random;\n\n    int gpu_index;\n    tree *hierarchy;\n\n    float *input;\n    float *truth;\n    float *delta;\n    float *workspace;\n    int train;\n    int index;\n    float *cost;\n    float clip;\n} network;\n\n\ntypedef struct {\n    int w;\n    int h;\n    int c;\n    float *data;\n} image;\n\nnetwork *load_network(char *cfg, char *weights, int clear);\nimage letterbox_image(image im, int w, int h);\nint resize_network(network *net, int w, int h);\nvoid top_predictions(network *net, int n, int *index);\nvoid free_image(image m);\nimage load_image_color(char *filename, int w, int h);\nfloat *network_predict_image(network *net, image im);\nfloat *network_predict(network *net, float *input);\nnetwork *make_network(int n);\nlayer make_convolutional_layer(\n    int batch,\n    int h, int w, int c, int n,\n    int groups, int size, int stride, int padding,\n    ACTIVATION activation, int batch_normalize, int binary, int xnor, int adam);\nlayer make_connected_layer(int batch, int inputs, int outputs,\n    ACTIVATION activation, int batch_normalize, int adam);\nlayer make_maxpool_layer(int batch, int h, int w, int c, int size, int stride, int padding);\nlayer make_avgpool_layer(int batch, int w, int h, int c);\nlayer make_shortcut_layer(int batch, int index, int w, int h, int c, int w2, int h2, int c2);\nlayer make_batchnorm_layer(int batch, int w, int h, int c);\nlayer make_reorg_layer(\n    int batch, int w, int h, int c,\n    int stride, int reverse, int flatten, int extra);\nlayer make_region_layer(int batch, int w, int h, int n, int classes, int coords);\nlayer make_softmax_layer(int batch, int inputs, int groups);\nlayer make_rnn_layer(int batch, int inputs, int outputs,\n    int steps, ACTIVATION activation, int batch_normalize, int adam);\nlayer make_yolo_layer(int batch, int w, int h, int n, int total, int *mask, int classes);\nlayer make_crnn_layer(\n    int batch, int h, int w, int c,\n    int hidden_filters, int output_filters, int steps,\n    ACTIVATION activation, int batch_normalize);\nlayer make_lstm_layer(\n    int batch, int inputs, int outputs, int steps,\n    int batch_normalize, int adam);\nlayer make_gru_layer(int batch, int inputs,\n    int outputs, int steps, int batch_normalize, int adam);\nlayer make_upsample_layer(int batch, int w, int h, int c, int stride);\nlayer make_l2norm_layer(int batch, int inputs);\nvoid free_network(network *net);\n\"\"\"\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/dcgan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"\nNet of the generator of DCGAN\n\nAdopted from:\nhttps://github.com/tqchen/mxnet-gan/blob/main/mxgan/generator.py\n\nReference:\nRadford, Alec, Luke Metz, and Soumith Chintala.\n\"Unsupervised representation learning with deep convolutional generative adversarial networks.\"\narXiv preprint arXiv:1511.06434 (2015).\n\"\"\"\nfrom tvm import relay\n\nfrom . import layers\nfrom .init import create_workload\n\n\ndef deconv2d(data, ishape, oshape, kshape, layout, name, stride=(2, 2)):\n    \"\"\"a deconv layer that enlarges the feature map\"\"\"\n    target_shape = (oshape[-2], oshape[-1])\n\n    pad_y = (kshape[0] - 1) // 2\n    pad_x = (kshape[1] - 1) // 2\n    adj_y = (target_shape[0] + 2 * pad_y - kshape[0]) % stride[0]\n    adj_x = (target_shape[1] + 2 * pad_x - kshape[1]) % stride[1]\n\n    if layout == \"NCHW\":\n        kernel_layout = \"IOHW\"\n    elif layout == \"NHWC\":\n        kernel_layout = \"HWOI\"\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    net = layers.conv2d_transpose(\n        data,\n        kernel_size=kshape,\n        strides=stride,\n        channels=oshape[0],\n        padding=(pad_y, pad_x),\n        output_padding=(adj_y, adj_x),\n        data_layout=layout,\n        kernel_layout=kernel_layout,\n        name=name,\n    )\n    return net\n\n\ndef deconv2d_bn_relu(data, prefix, **kwargs):\n    \"\"\"a block of deconv + batch norm + relu\"\"\"\n    eps = 1e-5 + 1e-12\n    net = deconv2d(data, name=\"%s_deconv\" % prefix, **kwargs)\n    bn_axis = kwargs.get(\"layout\", \"NCHW\").index(\"C\")\n    net = layers.batch_norm_infer(\n        net, epsilon=eps, scale=False, axis=bn_axis, name=\"%s_batch_norm\" % prefix\n    )\n    net = relay.nn.relu(net)\n    return net\n\n\ndef get_net(\n    batch_size,\n    random_len=100,\n    oshape=(3, 64, 64),\n    ngf=128,\n    code=None,\n    layout=\"NCHW\",\n    dtype=\"float32\",\n):\n    \"\"\"get net of dcgan generator\"\"\"\n    assert oshape[-1] == 64, \"Only support 64x64 image\"\n    assert oshape[-2] == 64, \"Only support 64x64 image\"\n\n    code = relay.var(\"data\", dtype=dtype, shape=(batch_size, random_len)) if code is None else code\n    dense_weight = relay.var(\"dense_weight\")\n    dense = relay.nn.dense(code, weight=dense_weight, units=4 * 4 * ngf * 8)\n    relu = relay.nn.relu(dense)\n    # 4 x 4\n    if layout == \"NCHW\":\n        reshape = relay.reshape(relu, newshape=(-1, ngf * 8, 4, 4))\n    elif layout == \"NHWC\":\n        reshape = relay.reshape(relu, newshape=(-1, 4, 4, ngf * 8))\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n    # 8 x 8\n    dc8 = deconv2d_bn_relu(\n        reshape,\n        ishape=(ngf * 8, 4, 4),\n        oshape=(ngf * 4, 8, 8),\n        kshape=(4, 4),\n        layout=layout,\n        prefix=\"g2\",\n    )\n    # 16x16\n    dc16 = deconv2d_bn_relu(\n        dc8,\n        ishape=(ngf * 4, 8, 8),\n        oshape=(ngf * 2, 16, 16),\n        kshape=(4, 4),\n        layout=layout,\n        prefix=\"g3\",\n    )\n    # 32x32\n    dc32 = deconv2d_bn_relu(\n        dc16,\n        ishape=(ngf * 2, 16, 16),\n        oshape=(ngf, 32, 32),\n        kshape=(4, 4),\n        layout=layout,\n        prefix=\"g4\",\n    )\n    # 64x64\n    dc64 = deconv2d(\n        dc32,\n        ishape=(ngf, 32, 32),\n        oshape=oshape[-3:],\n        kshape=(4, 4),\n        layout=layout,\n        name=\"g5_deconv\",\n    )\n    tanh = relay.tanh(dc64)\n\n    args = relay.analysis.free_vars(tanh)\n    return relay.Function(args, tanh)\n\n\ndef get_workload(\n    batch_size, oshape=(3, 64, 64), ngf=128, random_len=100, layout=\"NCHW\", dtype=\"float32\"\n):\n    \"\"\"Get benchmark workload for a DCGAN generator\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n    oshape : tuple, optional\n        The shape of output image, layout=\"CHW\"\n    ngf: int, optional\n        The number of final feature maps in the generator\n    random_len : int, optional\n        The length of random input\n    layout: str, optional\n        The layout of conv2d transpose\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a DCGAN network.\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(batch_size, random_len, oshape=oshape, ngf=ngf, layout=layout, dtype=dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/densenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, line-too-long\n\"\"\"\nPort of MxNet version of Densenet to Relay.\nhttps://github.com/apache/incubator-mxnet/blob/master/python/mxnet/gluon/model_zoo/vision/densenet.py\n\"\"\"\n# pylint: enable=line-too-long\nfrom tvm import relay\nfrom . import layers\nfrom .init import create_workload\n\n\ndef _make_dense_layer(data, growth_rate, bn_size, index):\n    \"\"\"Single densenet layer.\"\"\"\n    bn1 = layers.batch_norm_infer(data, name=\"batch_1_%s\" % index)\n    relu1 = relay.nn.relu(bn1)\n    conv1 = layers.conv2d(\n        relu1, channels=bn_size * growth_rate, kernel_size=(1, 1), name=\"conv2d_1_%s\" % index\n    )\n    bn2 = layers.batch_norm_infer(conv1, name=\"batch_2_\" + index)\n    relu2 = relay.nn.relu(bn2)\n    conv2 = layers.conv2d(\n        relu2, channels=growth_rate, kernel_size=(3, 3), padding=(1, 1), name=\"conv2d_2_%s\" % index\n    )\n    return conv2\n\n\ndef _make_dense_block(data, num_layers, bn_size, growth_rate, index):\n    \"\"\"Makes a block of dense layers of the specified size.\"\"\"\n    layer_out = data\n    blocks = []\n    for i in range(num_layers):\n        layer_out = _make_dense_layer(layer_out, growth_rate, bn_size, \"%s_%s\" % (index, i))\n        blocks.append(layer_out)\n    block_out = relay.concatenate(blocks, 1)\n    return block_out\n\n\ndef _make_transition(data, num_output_features, index):\n    \"\"\"Transition between layers.\"\"\"\n    bn = layers.batch_norm_infer(data, name=\"batch_t_%s\" % index)\n    relu = relay.nn.relu(bn)\n    conv = layers.conv2d(\n        relu, channels=num_output_features, kernel_size=(1, 1), name=\"conv_t_%s\" % index\n    )\n    return relay.nn.avg_pool2d(conv, pool_size=(2, 2), strides=(2, 2))\n\n\ndef _make_dense_net(\n    num_init_features, growth_rate, block_config, data_shape, data_dtype, bn_size=4, classes=1000\n):\n    \"\"\"Builds up a densenet.\"\"\"\n    data = relay.Var(\n        \"data\", relay.TensorType(data_shape, data_dtype)\n    )  # (batch_size, 3, 224, 224)))\n    conv1 = layers.conv2d(\n        data,\n        channels=num_init_features,\n        kernel_size=(7, 7),\n        strides=(2, 2),\n        padding=(3, 3),\n        name=\"conv1\",\n    )\n    bn1 = layers.batch_norm_infer(conv1, name=\"batch1\")\n    relu1 = relay.nn.relu(bn1)\n    mp = relay.nn.max_pool2d(relu1, pool_size=(3, 3), strides=(2, 2), padding=(1, 1))\n\n    num_features = num_init_features\n    layer_out = mp\n    for i, num_layers in enumerate(block_config):\n        layer_out = _make_dense_block(layer_out, num_layers, bn_size, growth_rate, i)\n        num_features = num_features + num_layers * growth_rate\n        if i != len(block_config) - 1:\n            layer_out = _make_transition(layer_out, num_features // 2, i)\n            num_features = num_features // 2\n    bn2 = layers.batch_norm_infer(layer_out, name=\"batch2\")\n    relu2 = relay.nn.relu(bn2)\n    avg = relay.nn.avg_pool2d(relu2, pool_size=(7, 7))\n    flat = relay.nn.batch_flatten(avg)\n\n    ret = layers.dense_add_bias(flat, units=classes, name=\"dense\")\n\n    return relay.Function(relay.analysis.free_vars(ret), ret)\n\n\ndef get_workload(\n    densenet_size=121, classes=1000, batch_size=4, image_shape=(3, 224, 224), dtype=\"float32\"\n):\n    \"\"\"Gets benchmark workload for densenet.\n\n    Parameters\n    ----------\n    densenet_size : int, optional (default 121)\n        Parameter for the network size. The supported sizes\n        are 121, 161, 169, and 201.\n\n    classes : int, optional (default 1000)\n        The number of classes.\n\n    batch_size : int, optional (detault 4)\n        The batch size for the network.\n\n    image_shape : shape, optional (default (3, 224, 224))\n        The shape of the input data.\n\n    dtype : data type, optional (default 'float32')\n        The data type of the input data.\n\n    Returns\n    -------\n    mod: tvm.IRModule\n        The relay module that contains a DenseNet network.\n\n    params : dict of str to NDArray\n        The benchmark paraeters.\n    \"\"\"\n    specs = {\n        121: (64, 32, [6, 12, 24, 16]),\n        161: (96, 48, [6, 12, 36, 24]),\n        169: (69, 32, [6, 12, 32, 32]),\n        201: (64, 32, [6, 12, 48, 32]),\n    }\n    bn_size = 4\n    num_init_features, growth_rate, block_config = specs[densenet_size]\n    data_shape = tuple([batch_size] + list(image_shape))\n    net = _make_dense_net(\n        num_init_features, growth_rate, block_config, data_shape, dtype, bn_size, classes\n    )\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/dqn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nNet of Nature DQN\nReference:\nMnih, Volodymyr, et al. \"Human-level control through deep reinforcement learning.\"\nNature 518.7540 (2015): 529.\n\"\"\"\n\nfrom tvm import relay\nfrom . import layers\nfrom .init import create_workload\n\n\ndef get_net(batch_size, num_actions=18, image_shape=(4, 84, 84), dtype=\"float32\", layout=\"NCHW\"):\n    \"\"\"get symbol of nature dqn\"\"\"\n    data_shape = (batch_size,) + image_shape\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n\n    bias_axis = layout.index(\"C\")\n\n    conv1_bias = relay.var(\"conv1_bias\")\n    conv1 = layers.conv2d(\n        data,\n        kernel_size=(8, 8),\n        strides=(4, 4),\n        padding=(0, 0),\n        channels=32,\n        name=\"conv1\",\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout),\n    )\n    conv1 = relay.nn.bias_add(conv1, conv1_bias, bias_axis)\n    relu1 = relay.nn.relu(conv1)\n\n    conv2_bias = relay.var(\"conv2_bias\")\n    conv2 = layers.conv2d(\n        relu1,\n        kernel_size=(4, 4),\n        strides=(2, 2),\n        padding=(0, 0),\n        channels=64,\n        name=\"conv2\",\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout),\n    )\n    conv2 = relay.nn.bias_add(conv2, conv2_bias, bias_axis)\n    relu2 = relay.nn.relu(conv2)\n\n    conv3_bias = relay.var(\"conv3_bias\")\n    conv3 = layers.conv2d(\n        relu2,\n        kernel_size=(3, 3),\n        strides=(1, 1),\n        padding=(0, 0),\n        channels=64,\n        name=\"conv3\",\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout),\n    )\n    conv3 = relay.nn.bias_add(conv3, conv3_bias, bias_axis)\n    relu3 = relay.nn.relu(conv3)\n\n    bf1 = relay.nn.batch_flatten(relu3)\n    dense1 = layers.dense_add_bias(bf1, units=512, name=\"dense1\")\n    relu4 = relay.nn.relu(dense1)\n    dense2 = layers.dense_add_bias(relu4, units=num_actions, name=\"dense2\")\n\n    args = relay.analysis.free_vars(dense2)\n    return relay.Function(args, dense2)\n\n\ndef get_workload(\n    batch_size, num_actions=18, image_shape=(4, 84, 84), dtype=\"float32\", layout=\"NCHW\"\n):\n    \"\"\"Get benchmark workload for a Deep Q Network\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n    num_actions : int, optional\n        Number of actions\n    image_shape : tuple, optional\n        The input image shape\n    dtype : str, optional\n        The data type\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a DQN network.\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(\n        batch_size, num_actions=num_actions, image_shape=image_shape, dtype=dtype, layout=layout\n    )\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/inception_v3.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nInception V3, suitable for images with around 299 x 299\n\nReference:\nSzegedy, Christian, et al. \"Rethinking the Inception Architecture for Computer Vision.\"\narXiv preprint arXiv:1512.00567 (2015).\n\nAdopted from https://github.com/apache/incubator-mxnet/blob/master/\n             example/image-classification/symbols/inception-v3.py\n\"\"\"\n# pylint: disable=invalid-name,missing-docstring,unused-argument\nfrom tvm import relay\nfrom .init import create_workload\nfrom . import layers\n\n\ndef Conv(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), name=None, suffix=\"\"):\n    conv = layers.conv2d(\n        data=data,\n        channels=int(num_filter),\n        kernel_size=kernel,\n        strides=stride,\n        padding=pad,\n        name=\"%s%s_conv1\" % (name, suffix),\n    )\n\n    bn = layers.batch_norm_infer(\n        data=conv, epsilon=2e-5, scale=False, name=\"%s%s_bn\" % (name, suffix)\n    )\n    act = relay.nn.relu(data=bn)\n    return act\n\n\ndef Pooling(data, kernel, stride, pad, pool_type, name):\n    if pool_type == \"max\":\n        return relay.nn.max_pool2d(data=data, pool_size=kernel, strides=stride, padding=pad)\n    if pool_type == \"avg\":\n        return relay.nn.avg_pool2d(\n            data=data, pool_size=kernel, strides=stride, padding=pad, count_include_pad=True\n        )\n    raise ValueError(\"Invalid pooling type: \" + pool_type)\n\n\ndef Inception7A(\n    data, num_1x1, num_3x3_red, num_3x3_1, num_3x3_2, num_5x5_red, num_5x5, pool, proj, name\n):\n    tower_1x1 = Conv(data, num_1x1, name=(\"%s_conv\" % name))\n    tower_5x5 = Conv(data, num_5x5_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_5x5 = Conv(\n        tower_5x5, num_5x5, kernel=(5, 5), pad=(2, 2), name=(\"%s_tower\" % name), suffix=\"_conv_1\"\n    )\n    tower_3x3 = Conv(data, num_3x3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\")\n    tower_3x3 = Conv(\n        tower_3x3,\n        num_3x3_1,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_3x3 = Conv(\n        tower_3x3,\n        num_3x3_2,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    pooling = Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n\n    cproj = Conv(pooling, proj, name=(\"%s_tower_2\" % name), suffix=\"_conv\")\n    concat = relay.concatenate((tower_1x1, tower_5x5, tower_3x3, cproj), axis=1)\n    return concat\n\n\n# First Downsample\ndef Inception7B(data, num_3x3, num_d3x3_red, num_d3x3_1, num_d3x3_2, pool, name):\n    tower_3x3 = Conv(\n        data, num_3x3, kernel=(3, 3), pad=(0, 0), stride=(2, 2), name=(\"%s_conv\" % name)\n    )\n    tower_d3x3 = Conv(data, num_d3x3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d3x3 = Conv(\n        tower_d3x3,\n        num_d3x3_1,\n        kernel=(3, 3),\n        pad=(1, 1),\n        stride=(1, 1),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d3x3 = Conv(\n        tower_d3x3,\n        num_d3x3_2,\n        kernel=(3, 3),\n        pad=(0, 0),\n        stride=(2, 2),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_2\",\n    )\n    pooling = Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(2, 2),\n        pad=(0, 0),\n        pool_type=\"max\",\n        name=(\"max_pool_%s_pool\" % name),\n    )\n    concat = relay.concatenate((tower_3x3, tower_d3x3, pooling), axis=1)\n    return concat\n\n\ndef Inception7C(\n    data,\n    num_1x1,\n    num_d7_red,\n    num_d7_1,\n    num_d7_2,\n    num_q7_red,\n    num_q7_1,\n    num_q7_2,\n    num_q7_3,\n    num_q7_4,\n    pool,\n    proj,\n    name,\n):\n    tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=(\"%s_conv\" % name))\n    tower_d7 = Conv(data=data, num_filter=num_d7_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d7 = Conv(\n        data=tower_d7,\n        num_filter=num_d7_1,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7 = Conv(\n        data=tower_d7,\n        num_filter=num_d7_2,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_q7 = Conv(data=data, num_filter=num_q7_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\")\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_1,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_2,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_3,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_3\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_4,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_4\",\n    )\n    pooling = Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    cproj = Conv(\n        data=pooling, num_filter=proj, kernel=(1, 1), name=(\"%s_tower_2\" % name), suffix=\"_conv\"\n    )\n    # concat\n    concat = relay.concatenate((tower_1x1, tower_d7, tower_q7, cproj), axis=1)\n    return concat\n\n\ndef Inception7D(\n    data, num_3x3_red, num_3x3, num_d7_3x3_red, num_d7_1, num_d7_2, num_d7_3x3, pool, name\n):\n    tower_3x3 = Conv(data=data, num_filter=num_3x3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_3x3 = Conv(\n        data=tower_3x3,\n        num_filter=num_3x3,\n        kernel=(3, 3),\n        pad=(0, 0),\n        stride=(2, 2),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7_3x3 = Conv(\n        data=data, num_filter=num_d7_3x3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\"\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_1,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_2,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_3x3,\n        kernel=(3, 3),\n        stride=(2, 2),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_3\",\n    )\n    pooling = Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(2, 2),\n        pool_type=pool,\n        pad=(0, 0),\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    # concat\n    concat = relay.concatenate((tower_3x3, tower_d7_3x3, pooling), axis=1)\n    return concat\n\n\ndef Inception7E(\n    data,\n    num_1x1,\n    num_d3_red,\n    num_d3_1,\n    num_d3_2,\n    num_3x3_d3_red,\n    num_3x3,\n    num_3x3_d3_1,\n    num_3x3_d3_2,\n    pool,\n    proj,\n    name,\n):\n    tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=(\"%s_conv\" % name))\n    tower_d3 = Conv(data=data, num_filter=num_d3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d3_a = Conv(\n        data=tower_d3,\n        num_filter=num_d3_1,\n        kernel=(1, 3),\n        pad=(0, 1),\n        name=(\"%s_tower\" % name),\n        suffix=\"_mixed_conv\",\n    )\n    tower_d3_b = Conv(\n        data=tower_d3,\n        num_filter=num_d3_2,\n        kernel=(3, 1),\n        pad=(1, 0),\n        name=(\"%s_tower\" % name),\n        suffix=\"_mixed_conv_1\",\n    )\n    tower_3x3_d3 = Conv(\n        data=data, num_filter=num_3x3_d3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\"\n    )\n    tower_3x3_d3 = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_3x3_d3_a = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3_d3_1,\n        kernel=(1, 3),\n        pad=(0, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_mixed_conv\",\n    )\n    tower_3x3_d3_b = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3_d3_2,\n        kernel=(3, 1),\n        pad=(1, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_mixed_conv_1\",\n    )\n    pooling = Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    cproj = Conv(\n        data=pooling, num_filter=proj, kernel=(1, 1), name=(\"%s_tower_2\" % name), suffix=\"_conv\"\n    )\n    # concat\n    concat = relay.concatenate(\n        (tower_1x1, tower_d3_a, tower_d3_b, tower_3x3_d3_a, tower_3x3_d3_b, cproj), axis=1\n    )\n    return concat\n\n\ndef get_net(batch_size, num_classes, image_shape, dtype):\n    \"\"\"Get network a Inception v3 network.\n\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of claseses\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    net : relay.Function\n        The dataflow.\n    \"\"\"\n    data_shape = (batch_size,) + image_shape\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n\n    # stage 1\n    conv = Conv(data, 32, kernel=(3, 3), stride=(2, 2), name=\"conv\")\n    conv_1 = Conv(conv, 32, kernel=(3, 3), name=\"conv_1\")\n    conv_2 = Conv(conv_1, 64, kernel=(3, 3), pad=(1, 1), name=\"conv_2\")\n    pool = Pooling(\n        data=conv_2, kernel=(3, 3), stride=(2, 2), pool_type=\"max\", pad=(0, 0), name=\"pool\"\n    )\n    # stage 2\n    conv_3 = Conv(pool, 80, kernel=(1, 1), name=\"conv_3\")\n    conv_4 = Conv(conv_3, 192, kernel=(3, 3), name=\"conv_4\")\n    pool1 = Pooling(\n        data=conv_4, kernel=(3, 3), stride=(2, 2), pool_type=\"max\", pad=(0, 0), name=\"pool1\"\n    )\n\n    # stage 3\n    in3a = Inception7A(pool1, 64, 64, 96, 96, 48, 64, \"avg\", 32, \"mixed\")\n\n    in3b = Inception7A(in3a, 64, 64, 96, 96, 48, 64, \"avg\", 64, \"mixed_1\")\n    in3c = Inception7A(in3b, 64, 64, 96, 96, 48, 64, \"avg\", 64, \"mixed_2\")\n    in3d = Inception7B(in3c, 384, 64, 96, 96, \"max\", \"mixed_3\")\n    # stage 4\n    in4a = Inception7C(in3d, 192, 128, 128, 192, 128, 128, 128, 128, 192, \"avg\", 192, \"mixed_4\")\n    in4b = Inception7C(in4a, 192, 160, 160, 192, 160, 160, 160, 160, 192, \"avg\", 192, \"mixed_5\")\n    in4c = Inception7C(in4b, 192, 160, 160, 192, 160, 160, 160, 160, 192, \"avg\", 192, \"mixed_6\")\n    in4d = Inception7C(in4c, 192, 192, 192, 192, 192, 192, 192, 192, 192, \"avg\", 192, \"mixed_7\")\n    in4e = Inception7D(in4d, 192, 320, 192, 192, 192, 192, \"max\", \"mixed_8\")\n    # stage 5\n    in5a = Inception7E(in4e, 320, 384, 384, 384, 448, 384, 384, 384, \"avg\", 192, \"mixed_9\")\n    in5b = Inception7E(in5a, 320, 384, 384, 384, 448, 384, 384, 384, \"max\", 192, \"mixed_10\")\n\n    # pool\n    pool = Pooling(\n        data=in5b, kernel=(8, 8), stride=(1, 1), pool_type=\"avg\", pad=(0, 0), name=\"global_pool\"\n    )\n\n    flatten = relay.nn.batch_flatten(pool)\n    fc1 = relay.nn.dense(flatten, relay.var(\"fc1_weight\"), units=num_classes)\n    fc1 = relay.nn.bias_add(fc1, relay.var(\"fc2_bias\"), axis=-1)\n    inception_v3 = relay.nn.softmax(data=fc1)\n    args = relay.analysis.free_vars(inception_v3)\n    return relay.Function(args, inception_v3)\n\n\ndef get_workload(batch_size=1, num_classes=1000, image_shape=(3, 299, 299), dtype=\"float32\"):\n    \"\"\"Get benchmark workload for InceptionV3\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains an Inception V3 network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(batch_size, num_classes, image_shape, dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/init.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Initializer of parameters.\"\"\"\nfrom functools import reduce\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\n\n\nclass Initializer(object):\n    \"\"\"The base class of an initializer.\"\"\"\n\n    def __init__(self, **kwargs):\n        self._kwargs = kwargs\n\n    def __call__(self, desc, arr):\n        \"\"\"Initialize an array\n\n        Parameters\n        ----------\n        desc : str\n            Initialization pattern descriptor.\n\n        arr : NDArray\n            The array to be initialized.\n        \"\"\"\n        if desc.endswith(\"weight\"):\n            self._init_weight(desc, arr)\n        elif desc.endswith(\"bias\"):\n            self._init_bias(desc, arr)\n        elif desc.endswith(\"gamma\"):\n            self._init_gamma(desc, arr)\n        elif desc.endswith(\"beta\"):\n            self._init_beta(desc, arr)\n        elif desc.endswith(\"mean\"):\n            self._init_mean(desc, arr)\n        elif desc.endswith(\"var\"):\n            self._init_var(desc, arr)\n        else:\n            self._init_default(desc, arr)\n\n    def _init_bias(self, _, arr):\n        arr[:] = 0.0\n\n    def _init_gamma(self, _, arr):\n        arr[:] = 1.0\n\n    def _init_beta(self, _, arr):\n        arr[:] = 0.0\n\n    def _init_mean(self, _, arr):\n        arr[:] = 0.0\n\n    def _init_var(self, _, arr):\n        arr[:] = 1.0\n\n    def _init_weight(self, name, arr):\n        \"\"\"Abstract method to Initialize weight.\"\"\"\n        raise NotImplementedError(\"Must override it\")\n\n    def _init_default(self, name, _):\n        raise ValueError(\n            \"Unknown initialization pattern for %s. \"\n            \"Default initialization is now limited to \"\n            '\"weight\", \"bias\", \"gamma\" (1.0), and \"beta\" (0.0).'\n            \"Please use mx.sym.Variable(init=mx.init.*) to set initialization pattern\" % name\n        )\n\n\nclass Xavier(Initializer):\n    \"\"\" \"Xavier\" initialization for weights\n\n    Parameters\n    ----------\n    rnd_type: str, optional\n        Random generator type, can be ``'gaussian'`` or ``'uniform'``.\n\n    factor_type: str, optional\n        Can be ``'avg'``, ``'in'``, or ``'out'``.\n\n    magnitude: float, optional\n        Scale of random number.\n    \"\"\"\n\n    def __init__(self, rnd_type=\"uniform\", factor_type=\"avg\", magnitude=3):\n        super(Xavier, self).__init__(\n            rnd_type=rnd_type, factor_type=factor_type, magnitude=magnitude\n        )\n        self.rnd_type = rnd_type\n        self.factor_type = factor_type\n        self.magnitude = float(magnitude)\n\n    def _init_weight(self, name, arr):\n        shape = arr.shape\n        hw_scale = 1.0\n        if len(shape) < 2:\n            raise ValueError(\n                \"Xavier initializer cannot be applied to vector {0}. It requires at\"\n                \" least 2D.\".format(name)\n            )\n        if len(shape) > 2:\n            hw_scale = np.prod(shape[2:])\n        fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale\n        factor = 1.0\n        if self.factor_type == \"avg\":\n            factor = (fan_in + fan_out) / 2.0\n        elif self.factor_type == \"in\":\n            factor = fan_in\n        elif self.factor_type == \"out\":\n            factor = fan_out\n        else:\n            raise ValueError(\"Incorrect factor type\")\n        # Hack for mobilenet, because there is less connectivity\n        if \"depthwise\" in name:\n            factor = hw_scale\n        scale = np.sqrt(self.magnitude / factor)\n        if self.rnd_type == \"uniform\":\n            arr[:] = np.random.uniform(-scale, scale, size=arr.shape)\n        else:\n            raise ValueError(\"Unknown random type\")\n\n\nclass Constant(Initializer):\n    \"\"\"Constant initialization of weights. Sum of weights in the matrix is 1.\"\"\"\n\n    def _init_weight(self, name, arr):\n        num_elements = reduce(lambda x, y: x * y, arr.shape)\n        arr[:] = 1.0 / num_elements\n\n\ndef create_workload(net, initializer=None, seed=0):\n    \"\"\"Helper function to create benchmark image classification workload.\n\n    Parameters\n    ----------\n    net : tvm.relay.Function\n        The selected function of the network.\n\n    initializer : Initializer\n        The initializer used\n\n    seed : int\n        The seed used in initialization.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The created relay module.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    mod = tvm.IRModule.from_expr(net)\n    mod = relay.transform.InferType()(mod)\n    shape_dict = {v.name_hint: v.checked_type for v in mod[\"main\"].params}\n    np.random.seed(seed)\n    initializer = initializer if initializer else Xavier()\n    params = {}\n    for k, v in shape_dict.items():\n        if k == \"data\":\n            continue\n        init_value = np.zeros(v.concrete_shape).astype(v.dtype)\n        initializer(k, init_value)\n        params[k] = tvm.nd.array(init_value, device=tvm.cpu(0))\n    return mod, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/layers.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Simple Layer DSL wrapper to ease creation of neural nets.\"\"\"\nfrom tvm import relay\n\n\ndef batch_norm_infer(data, gamma=None, beta=None, moving_mean=None, moving_var=None, **kwargs):\n    \"\"\"Wrapper of batch_norm.\n\n    This function automatically creates weights and return\n    the first output(normalized result).\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input expression.\n\n    gamma : relay.Expr\n        The gamma scale factor.\n\n    beta : relay.Expr\n        The beta offset factor.\n\n    moving_mean : relay.Expr\n        Running mean of input,\n\n    moving_var : relay.Expr\n        Running variance of input.\n\n    kwargs : dict\n        Additional arguments.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result.\n    \"\"\"\n    name = kwargs.get(\"name\")\n    kwargs.pop(\"name\")\n    if not gamma:\n        gamma = relay.var(name + \"_gamma\")\n    if not beta:\n        beta = relay.var(name + \"_beta\")\n    if not moving_mean:\n        moving_mean = relay.var(name + \"_moving_mean\")\n    if not moving_var:\n        moving_var = relay.var(name + \"_moving_var\")\n    return relay.nn.batch_norm(\n        data, gamma=gamma, beta=beta, moving_mean=moving_mean, moving_var=moving_var, **kwargs\n    )[0]\n\n\ndef conv2d(data, weight=None, **kwargs):\n    \"\"\"Wrapper of conv2d which automatically creates weights if not given.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input expression.\n\n    weight : relay.Expr\n        The weight to conv2d.\n\n    kwargs : dict\n        Additional arguments.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result.\n    \"\"\"\n    name = kwargs.get(\"name\")\n    kwargs.pop(\"name\")\n    if not weight:\n        weight = relay.var(name + \"_weight\")\n    return relay.nn.conv2d(data, weight, **kwargs)\n\n\ndef conv3d(data, weight=None, **kwargs):\n    \"\"\"Wrapper of conv3d which automatically creates weights if not given.\n    Parameters\n    ----------\n    data : relay.Expr\n        The input expression.\n    weight : relay.Expr\n        The weight to conv3d.\n    kwargs : dict\n        Additional arguments.\n    Returns\n    -------\n    result : relay.Expr\n        The result.\n    \"\"\"\n    name = kwargs.get(\"name\")\n    kwargs.pop(\"name\")\n    if not weight:\n        weight = relay.var(name + \"_weight\")\n    return relay.nn.conv3d(data, weight, **kwargs)\n\n\ndef conv2d_transpose(data, weight=None, **kwargs):\n    \"\"\"Wrapper of conv2d_transpose which automatically creates weights if not given.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input expression.\n\n    weight : relay.Expr\n        The weight to conv2d_transpose.\n\n    kwargs : dict\n        Additional arguments.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result.\n    \"\"\"\n    name = kwargs.get(\"name\")\n    kwargs.pop(\"name\")\n    if not weight:\n        weight = relay.var(name + \"_weight\")\n    return relay.nn.conv2d_transpose(data, weight, **kwargs)\n\n\ndef dense_add_bias(data, weight=None, bias=None, units=None, **kwargs):\n    \"\"\"Wrapper of dense which automatically creates weights if not given.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input expression.\n\n    weight : relay.Expr\n        The weight to conv2d.\n\n    bias : relay.Expr\n        The bias.\n\n    kwargs : dict\n        Additional arguments.\n\n    Returns\n    -------\n    result : relay.Expr\n        The result.\n    \"\"\"\n    name = kwargs.get(\"name\")\n    kwargs.pop(\"name\")\n    if not weight:\n        weight = relay.var(name + \"_weight\")\n    if not bias:\n        bias = relay.var(name + \"_bias\")\n    data = relay.nn.dense(data, weight, units, **kwargs)\n    data = relay.nn.bias_add(data, bias, axis=-1)\n    return data\n\n\ndef conv_kernel_layout(data_layout, is_depthwise=False):\n    \"\"\"Map the data layout to corresponding kernel layout.\n\n    Arbitrary layout is not fully supported in TOPI yet.\n\n    Parameters\n    ----------\n    data_layout : str\n        The data_layout, can be 'NCHW', 'NHWC'.\n\n    is_depthwise : bool, optional\n        Whether the conv is a depthwise convolution.\n\n    Returns\n    -------\n    result : str\n        The corresponding kernel layout.\n    \"\"\"\n    conv_layout_map = {\n        \"NCHW\": \"OIHW\",\n        \"NHWC\": \"HWIO\",\n    }\n    depthwise_conv_layout_map = {\n        \"NCHW\": \"OIHW\",\n        \"NHWC\": \"HWOI\",\n    }\n    mapping = depthwise_conv_layout_map if is_depthwise else conv_layout_map\n    assert data_layout in mapping, \"Unknown data layout %s\" % data_layout\n    return mapping[data_layout]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nImplementation of a Long Short-Term Memory (LSTM) cell.\n\nAdapted from:\nhttps://gist.github.com/merrymercy/5eb24e3b019f84200645bd001e9caae9\n\"\"\"\n\nfrom tvm import relay\nfrom . import layers\nfrom .init import create_workload\n\n\ndef lstm_cell(num_hidden, batch_size=1, dtype=\"float32\", name=\"\"):\n    \"\"\"Long-Short Term Memory (LSTM) network cell.\n\n    Parameters\n    ----------\n    num_hidden : int\n        Number of units in output symbol.\n\n    batch_size : int\n        Batch size (length of states).\n\n    Returns\n    -------\n    result : tvm.relay.Function\n        A Relay function that evaluates an LSTM cell.\n        The function takes in a tensor of input data, a tuple of two\n        states, and weights and biases for dense operations on the\n        inputs and on the state. It returns a tuple with two members,\n        an output tensor and a tuple of two new states.\n    \"\"\"\n    builder = relay.ScopeBuilder()\n\n    input_type = relay.TensorType((batch_size, num_hidden), dtype)\n    weight_type = relay.TensorType((4 * num_hidden, num_hidden), dtype)\n    bias_type = relay.TensorType((4 * num_hidden,), dtype)\n\n    dense_type = relay.TensorType((batch_size, 4 * num_hidden), dtype)\n    slice_type = relay.TupleType([input_type, input_type, input_type, input_type])\n    ret_type = relay.TupleType([input_type, relay.TupleType([input_type, input_type])])\n\n    inputs = relay.Var(\"inputs\", input_type)\n    states = relay.Var(\"states\", relay.TupleType([input_type, input_type]))\n\n    i2h_weight = relay.Var(\"i2h_weight\", weight_type)\n    i2h_bias = relay.Var(\"i2h_bias\", bias_type)\n\n    h2h_weight = relay.Var(\"h2h_weight\", weight_type)\n    h2h_bias = relay.Var(\"h2h_bias\", bias_type)\n\n    i2h = builder.let(\n        (\"i2h\", dense_type),\n        layers.dense_add_bias(\n            data=inputs, units=num_hidden * 4, weight=i2h_weight, bias=i2h_bias, name=\"%si2h\" % name\n        ),\n    )\n    h2h = builder.let(\n        (\"h2h\", dense_type),\n        layers.dense_add_bias(\n            data=relay.TupleGetItem(states, 0),\n            units=num_hidden * 4,\n            weight=h2h_weight,\n            bias=h2h_bias,\n            name=\"%sh2h\" % name,\n        ),\n    )\n\n    gates = builder.let((\"gates\", dense_type), relay.add(i2h, h2h))\n    slice_gates = builder.let(\n        (\"slice_gates\", slice_type), relay.split(gates, indices_or_sections=4, axis=1).astuple()\n    )\n\n    in_gate = builder.let(\n        (\"in_gate\", input_type), relay.sigmoid(relay.TupleGetItem(slice_gates, 0))\n    )\n    forget_gate = builder.let(\n        (\"forget_gate\", input_type), relay.sigmoid(relay.TupleGetItem(slice_gates, 1))\n    )\n    in_transform = builder.let(\n        (\"in_transform\", input_type), relay.tanh(relay.TupleGetItem(slice_gates, 2))\n    )\n    out_gate = builder.let(\n        (\"out_gate\", input_type), relay.sigmoid(relay.TupleGetItem(slice_gates, 3))\n    )\n\n    next_c = builder.let(\n        (\"next_c\", input_type),\n        relay.add(\n            relay.multiply(forget_gate, relay.TupleGetItem(states, 1)),\n            relay.multiply(in_gate, in_transform),\n        ),\n    )\n    next_h = builder.let((\"next_h\", input_type), relay.multiply(out_gate, relay.tanh(next_c)))\n    ret = builder.let((\"ret\", ret_type), relay.Tuple([next_h, relay.Tuple([next_h, next_c])]))\n    builder.ret(ret)\n\n    body = builder.get()\n\n    return relay.Function(\n        [inputs, states, i2h_weight, i2h_bias, h2h_weight, h2h_bias], body, ret_type\n    )\n\n\ndef get_net(iterations, num_hidden, batch_size=1, dtype=\"float32\"):\n    \"\"\"Constructs an unrolled RNN with LSTM cells\"\"\"\n    input_type = relay.TensorType((batch_size, num_hidden), dtype)\n    weight_type = relay.TensorType((4 * num_hidden, num_hidden), dtype)\n    bias_type = relay.TensorType((4 * num_hidden,), dtype)\n\n    state_type = relay.TupleType([input_type, input_type])\n    cell_type = relay.TupleType([input_type, state_type])\n\n    builder = relay.ScopeBuilder()\n\n    zeros = builder.let((\"zeros\", input_type), relay.zeros((batch_size, num_hidden), dtype))\n    init_states = builder.let((\"init_states\", state_type), relay.Tuple([zeros, zeros]))\n\n    states = init_states\n    out = None\n\n    for i in range(iterations):\n        inputs = relay.Var(\"data\", input_type)\n        i2h_weight = relay.Var(\"i2h_%s_weight\" % i, weight_type)\n        i2h_bias = relay.Var(\"i2h_%i_bias\" % i, bias_type)\n        h2h_weight = relay.Var(\"h2h_%s_weight\" % i, weight_type)\n        h2h_bias = relay.Var(\"h2h_%s_bias\" % i, bias_type)\n\n        cell_fn = lstm_cell(num_hidden, batch_size, dtype, \"lstm_%s\" % i)\n\n        call = builder.let(\n            (\"call_%s\" % i, cell_type),\n            relay.Call(cell_fn, [inputs, states, i2h_weight, i2h_bias, h2h_weight, h2h_bias]),\n        )\n        new_out = builder.let((\"out_%s\" % i, input_type), relay.TupleGetItem(call, 0))\n        new_states = builder.let((\"states_%s\" % i, state_type), relay.TupleGetItem(call, 1))\n        states = new_states\n        out = new_out\n\n    builder.ret(out)\n    body = builder.get()\n    args = relay.analysis.free_vars(body)\n    return relay.Function(args, body, input_type)\n\n\ndef get_workload(iterations, num_hidden, batch_size=1, dtype=\"float32\"):\n    \"\"\"Get benchmark workload for an LSTM RNN.\n\n    Parameters\n    ----------\n    iterations : int\n        The number of iterations in the desired LSTM RNN.\n    num_hidden : int\n        The size of the hiddxen state\n    batch_size : int, optional (default 1)\n        The batch size used in the model\n    dtype : str, optional (default \"float32\")\n        The data type\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a LSTM network.\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(iterations, num_hidden, batch_size, dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/mlp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\na simple multilayer perceptron\n\"\"\"\nfrom __future__ import absolute_import\nfrom tvm import relay\nfrom .init import create_workload\n\n\ndef get_net(batch_size, num_classes=10, image_shape=(1, 28, 28), dtype=\"float32\"):\n    \"\"\"Get network a simple multilayer perceptron.\n\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of claseses\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    net : relay.Function\n        The dataflow.\n    \"\"\"\n    data_shape = (batch_size,) + image_shape\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    data = relay.nn.batch_flatten(data)\n    fc1 = relay.nn.dense(data, relay.var(\"fc1_weight\"), units=128)\n    fc1 = relay.nn.bias_add(fc1, relay.var(\"fc1_bias\"), axis=-1)\n    act1 = relay.nn.relu(fc1)\n    fc2 = relay.nn.dense(act1, relay.var(\"fc2_weight\"), units=64)\n    fc2 = relay.nn.bias_add(fc2, relay.var(\"fc2_bias\"), axis=-1)\n    act2 = relay.nn.relu(fc2)\n    fc3 = relay.nn.dense(act2, relay.var(\"fc3_weight\"), units=num_classes)\n    fc3 = relay.nn.bias_add(fc3, relay.var(\"fc3_bias\"), axis=-1)\n    mlp = relay.nn.softmax(data=fc3)\n    args = relay.analysis.free_vars(mlp)\n    return relay.Function(args, mlp)\n\n\ndef get_workload(batch_size, num_classes=10, image_shape=(1, 28, 28), dtype=\"float32\"):\n    \"\"\"Get benchmark workload for a simple multilayer perceptron.\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of claseses\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a mlp network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(batch_size, num_classes, image_shape, dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/mobilenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nPort of NNVM version of MobileNet to Relay.\n\"\"\"\n# pylint: disable=invalid-name\n\nfrom tvm import relay\nfrom . import layers\nfrom .init import create_workload\n\n\ndef conv_block(\n    data,\n    name,\n    channels,\n    kernel_size=(3, 3),\n    strides=(1, 1),\n    padding=(1, 1),\n    epsilon=1e-5,\n    layout=\"NCHW\",\n):\n    \"\"\"Helper function to construct conv_bn-relu\"\"\"\n    # convolution + bn + relu\n    conv = layers.conv2d(\n        data=data,\n        channels=channels,\n        kernel_size=kernel_size,\n        strides=strides,\n        padding=padding,\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout),\n        name=name + \"_conv\",\n    )\n    bn = layers.batch_norm_infer(data=conv, epsilon=epsilon, name=name + \"_bn\")\n    act = relay.nn.relu(data=bn)\n    return act\n\n\ndef separable_conv_block(\n    data,\n    name,\n    depthwise_channels,\n    pointwise_channels,\n    kernel_size=(3, 3),\n    downsample=False,\n    padding=(1, 1),\n    epsilon=1e-5,\n    layout=\"NCHW\",\n    dtype=\"float32\",\n):\n    \"\"\"Helper function to get a separable conv block\"\"\"\n    if downsample:\n        strides = (2, 2)\n    else:\n        strides = (1, 1)\n\n    # depthwise convolution + bn + relu\n    if layout == \"NCHW\":\n        wshape = (depthwise_channels, 1) + kernel_size\n    elif layout == \"NHWC\":\n        wshape = kernel_size + (depthwise_channels, 1)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n    bn_axis = layout.index(\"C\")\n    weight = relay.var(name + \"_weight\", shape=wshape, dtype=dtype)\n    conv1 = layers.conv2d(\n        data=data,\n        weight=weight,\n        channels=depthwise_channels,\n        groups=depthwise_channels,\n        kernel_size=kernel_size,\n        strides=strides,\n        padding=padding,\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout, True),\n        name=name + \"_depthwise_conv1\",\n    )\n    bn1 = layers.batch_norm_infer(data=conv1, epsilon=epsilon, axis=bn_axis, name=name + \"_bn1\")\n    act1 = relay.nn.relu(data=bn1)\n    # pointwise convolution + bn + relu\n    conv2 = layers.conv2d(\n        data=act1,\n        channels=pointwise_channels,\n        kernel_size=(1, 1),\n        strides=(1, 1),\n        padding=(0, 0),\n        data_layout=layout,\n        kernel_layout=layers.conv_kernel_layout(layout),\n        name=name + \"_conv2\",\n    )\n    bn2 = layers.batch_norm_infer(data=conv2, epsilon=epsilon, axis=bn_axis, name=name + \"_bn2\")\n    act2 = relay.nn.relu(data=bn2)\n    return act2\n\n\ndef mobile_net(\n    num_classes=1000,\n    data_shape=(1, 3, 224, 224),\n    dtype=\"float32\",\n    alpha=1.0,\n    is_shallow=False,\n    layout=\"NCHW\",\n):\n    \"\"\"Function to construct a MobileNet\"\"\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    body = conv_block(data, \"conv_block_1\", int(32 * alpha), strides=(2, 2), layout=layout)\n    body = separable_conv_block(\n        body, \"separable_conv_block_1\", int(32 * alpha), int(64 * alpha), layout=layout, dtype=dtype\n    )\n    body = separable_conv_block(\n        body,\n        \"separable_conv_block_2\",\n        int(64 * alpha),\n        int(128 * alpha),\n        downsample=True,\n        layout=layout,\n        dtype=dtype,\n    )\n    body = separable_conv_block(\n        body,\n        \"separable_conv_block_3\",\n        int(128 * alpha),\n        int(128 * alpha),\n        layout=layout,\n        dtype=dtype,\n    )\n    body = separable_conv_block(\n        body,\n        \"separable_conv_block_4\",\n        int(128 * alpha),\n        int(256 * alpha),\n        downsample=True,\n        layout=layout,\n        dtype=dtype,\n    )\n    body = separable_conv_block(\n        body,\n        \"separable_conv_block_5\",\n        int(256 * alpha),\n        int(256 * alpha),\n        layout=layout,\n        dtype=dtype,\n    )\n    body = separable_conv_block(\n        body,\n        \"separable_conv_block_6\",\n        int(256 * alpha),\n        int(512 * alpha),\n        downsample=True,\n        layout=layout,\n        dtype=dtype,\n    )\n    if is_shallow:\n        body = separable_conv_block(\n            body,\n            \"separable_conv_block_7\",\n            int(512 * alpha),\n            int(1024 * alpha),\n            downsample=True,\n            layout=layout,\n            dtype=dtype,\n        )\n        body = separable_conv_block(\n            body,\n            \"separable_conv_block_8\",\n            int(1024 * alpha),\n            int(1024 * alpha),\n            downsample=True,\n            layout=layout,\n            dtype=dtype,\n        )\n    else:\n        for i in range(7, 12):\n            body = separable_conv_block(\n                body,\n                \"separable_conv_block_%d\" % i,\n                int(512 * alpha),\n                int(512 * alpha),\n                layout=layout,\n                dtype=dtype,\n            )\n        body = separable_conv_block(\n            body,\n            \"separable_conv_block_12\",\n            int(512 * alpha),\n            int(1024 * alpha),\n            downsample=True,\n            layout=layout,\n            dtype=dtype,\n        )\n        body = separable_conv_block(\n            body,\n            \"separable_conv_block_13\",\n            int(1024 * alpha),\n            int(1024 * alpha),\n            layout=layout,\n            dtype=dtype,\n        )\n    pool = relay.nn.global_avg_pool2d(data=body, layout=layout)\n    flatten = relay.nn.batch_flatten(data=pool)\n    weight = relay.var(\"fc_weight\")\n    bias = relay.var(\"fc_bias\")\n    fc = relay.nn.dense(data=flatten, weight=weight, units=num_classes)\n    fc = relay.nn.bias_add(fc, bias)\n    softmax = relay.nn.softmax(data=fc)\n    return relay.Function(relay.analysis.free_vars(softmax), softmax)\n\n\ndef get_workload(\n    batch_size=1, num_classes=1000, image_shape=(3, 224, 224), dtype=\"float32\", layout=\"NCHW\"\n):\n    \"\"\"Get benchmark workload for mobilenet\n\n    Parameters\n    ----------\n    batch_size : int, optional\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    image_shape : tuple, optional\n        The input image shape, cooperate with layout\n\n    dtype : str, optional\n        The data type\n\n    layout : str, optional\n        The data layout of image_shape and the operators\n        cooperate with image_shape\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a MobileNet network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    data_shape = tuple([batch_size] + list(image_shape))\n    net = mobile_net(\n        num_classes=num_classes,\n        data_shape=data_shape,\n        dtype=dtype,\n        alpha=1.0,\n        is_shallow=False,\n        layout=layout,\n    )\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/nat.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Defines a unary natural number (Peano natural number) abstract\ndata type for Relay and provides some utility functions for it.\nNats are useful for testing purposes, as they make it easy to write\ntest cases for recursion and pattern matching.\"\"\"\n\nfrom tvm.relay.backend.interpreter import ConstructorValue\n\n\ndef get_type(prelude, name):\n    ty_var = prelude.mod.get_global_type_var(name)\n    ty_data = prelude.mod.type_definitions[ty_var]\n    return tuple([ty_var] + list(ty_data.constructors))\n\n\ndef count(prelude, n):\n    \"\"\"Takes a ConstructorValue corresponding to a nat ADT\n    and converts it into a Python integer. This is an example of\n    using an ADT value in Python.\n    \"\"\"\n    assert isinstance(n, ConstructorValue)\n    _, z, s = prelude.mod.get_type(\"nat\")\n    if n.tag == z.tag:\n        return 0\n    assert n.tag == s.tag\n    return 1 + count(prelude, n.fields[0])\n\n\ndef make_nat_value(prelude, n):\n    \"\"\"The inverse of count(): Given a non-negative Python integer,\n    constructs a ConstructorValue representing that value as a nat.\n    \"\"\"\n    _, z, s = prelude.mod.get_type(\"nat\")\n    if n == 0:\n        return ConstructorValue(z.tag, [], z)\n    return ConstructorValue(s.tag, [make_nat_value(prelude, n - 1)], s)\n\n\ndef make_nat_expr(prelude, n):\n    \"\"\"Given a non-negative Python integer, constructs a Python\n    expression representing that integer's value as a nat.\n    \"\"\"\n    assert n >= 0\n    _, z, s = prelude.mod.get_type(\"nat\")\n    ret = z()\n    while n > 0:\n        ret = s(ret)\n        n = n - 1\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/py_converter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return\n\"\"\"Utility for converting Relay code into a Python script with equivalent semantics\"\"\"\nimport sys\nimport ast\nfrom ast import alias, Assign, Load, Name, NameConstant, Num, Return, Store, Str\nimport re\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.adt import Pattern\nfrom tvm.relay.backend import te_compiler\nfrom tvm.relay.expr import Expr, GlobalVar, Var\nfrom tvm.relay.function import Function\nfrom tvm.relay.expr_functor import ExprFunctor\n\n__MAJOR__, __MINOR__, _, _, _ = sys.version_info\n\nOUTPUT_VAR_NAME = \"_py_out\"\n\n# corresponds to:\n#     import numpy\n#     import tvm\n#     from tvm import relay\n#     from tvm import nd\n#     from tvm.runtime import import container as _container\n#     from tvm.relay.backend.interpreter import RefValue, ConstructorValue\nPROLOGUE = [\n    ast.Import([alias(\"numpy\", None)]),\n    ast.Import([alias(\"tvm\", None)]),\n    ast.ImportFrom(\"tvm\", [alias(\"relay\", None)], 0),\n    ast.ImportFrom(\"tvm\", [alias(\"nd\", None)], 0),\n    ast.ImportFrom(\"tvm.runtime\", [alias(\"container\", \"_container\")], 0),\n    ast.ImportFrom(\n        \"tvm.relay.backend.interpreter\",\n        [alias(\"RefValue\", None), alias(\"ConstructorValue\", None)],\n        0,\n    ),\n]\n\n\nclass PythonConverter(ExprFunctor):\n    \"\"\"Functor for translating Relay programs into Python ASTs.\"\"\"\n\n    def __init__(self, mod, target) -> None:\n        super().__init__()\n        self.mod = mod\n        self.tgt = target\n        self.tec = te_compiler.get()\n        self.fun_no = 0\n        self.var_no = 0\n        self.var_map = {}\n\n    def convert(self, prog: Expr):\n        \"\"\"This method converts the passed Relay expression into a Python\n        AST object with equivalent semantics.\n\n        The Python AST can be executed using exec(); it can be turned\n        into text and inspected using astor.\n        \"\"\"\n        optimized = self.optimize(prog)\n\n        # start with conversion prelude (imports) and convert global defs\n        body = []\n        body += PROLOGUE\n        body += self.convert_module()\n\n        prog_body, extra_defs = self.visit(optimized)\n        body += extra_defs\n\n        # we finally must assign the final expression to the output var\n        # so it can be read after running EXEC\n        body.append(Assign([Name(OUTPUT_VAR_NAME, Store())], prog_body))\n        global __MAJOR__, __MINOR__\n\n        if __MAJOR__ == 3 and __MINOR__ == 8:\n            return ast.fix_missing_locations(ast.Module(body=body, type_ignores=[]))\n        else:\n            return ast.fix_missing_locations(ast.Module(body=body))\n\n    def optimize(self, prog: Expr):\n        \"\"\"Performs optimizations necessary to be able to generate code for prog.\"\"\"\n        # unwrap tuple wrappers (some op calls produce them)\n        unwrapped = prog.astuple() if isinstance(prog, relay.TupleWrapper) else prog\n        assert relay.analysis.well_formed(unwrapped)\n        mod = self.mod.from_expr(unwrapped, self.mod.functions, self.mod.type_definitions)\n\n        # necessary pass: SimplifyInference (otherwise we can't generate code for some operators)\n        # and fusion (to get primitive functions)\n        opts = tvm.transform.Sequential(\n            [relay.transform.SimplifyInference(), relay.transform.FuseOps(fuse_opt_level=0)]\n        )\n        mod = opts(mod)\n        optimized = mod[\"main\"]\n        return optimized if isinstance(unwrapped, Function) else optimized.body\n\n    def sanitize(self, name: str) -> str:\n        \"\"\"Removes any invalid characters (only underscores, numbers, and letters permitted)\n        from the given name. Since we append a number and underscore to var names anyway,\n        it doesn't matter if the name is the empty string.\"\"\"\n        return re.sub(r\"\\W\", \"\", name)\n\n    def generate_var_name(self, name_hint: str) -> str:\n        \"\"\"Generates a unique variable name starting from the hint.\"\"\"\n        name = \"{}_var_{}\".format(self.sanitize(name_hint), self.var_no)\n        self.var_no += 1\n        return name\n\n    def generate_function_name(self, name_hint: str) -> str:\n        \"\"\"Generates a unique function name starting from the hint.\"\"\"\n        name = \"{}_fun_{}\".format(self.sanitize(name_hint), self.fun_no)\n        self.fun_no += 1\n        return name\n\n    def get_var_name(self, var: Expr) -> str:\n        \"\"\"Returns the var name for the given Realy variable.\"\"\"\n        if var in self.var_map:\n            return self.var_map[var]\n        name = self.generate_var_name(var.name_hint)\n        self.var_map[var] = name\n        return name\n\n    def include_var(self, var: Expr, assign=False):\n        \"\"\"Returns a variable AST node for the given Relay var depending on\n        whether it must appear in an assignment or not.\"\"\"\n        name = self.get_var_name(var)\n        return Name(name, Store() if assign else Load())\n\n    def parse_name(self, name: str):\n        \"\"\"Given the name of a Python method with dots (e.g., 'relay.var'),\n        returns an appropriate AST object corresponding to that name.\"\"\"\n        attributes = name.split(\".\")\n        ret = Name(attributes[0], Load())\n        for i in range(len(attributes) - 1):\n            ret = ast.Attribute(ret, attributes[i + 1], Load())\n        return ret\n\n    def parse_numpy_array(self, arr):\n        \"\"\"Given a Numpy array, produces an appropriate Python array\n        or numerical literal representing its contents.\"\"\"\n\n        def parse_single(i):\n            return NameConstant(i) if isinstance(i, bool) else Num(i)\n\n        if arr.ndim == 0:\n            return parse_single(arr.item())\n        if arr.ndim == 1:\n            return ast.List([parse_single(i.item()) for i in arr], Load())\n\n        elts = []\n        for row in arr:\n            elts.append(self.parse_numpy_array(row))\n        return ast.List(elts, Load())\n\n    def convert_fields(self, fields: [Expr]):\n        \"\"\"Given a list of call args or tuple fields, converts\n        each and returns their ASTs and their defs lists (in order).\"\"\"\n        bodies = []\n        defs = []\n        for field in fields:\n            member_body, member_defs = self.visit(field)\n            bodies.append(member_body)\n            defs += member_defs\n        return (bodies, defs)\n\n    def convert_to_thunk(self, name_hint: str, expr: Expr):\n        \"\"\"Wraps the passed expression in a thunk.\"\"\"\n        body, defs = self.visit(expr)\n        thunk_name = self.generate_function_name(name_hint)\n        thunk = self.create_def(thunk_name, [], defs + [Return(body)])\n        return (thunk, thunk_name)\n\n    def convert_func_node(self, func: Function, name_var=None):\n        \"\"\"Converts the given Relay function into a Python function, with\n        special for named functions (locally or globally)\"\"\"\n        if name_var is None:\n            func_name = self.generate_function_name(\"_anon_func\")\n        if isinstance(name_var, GlobalVar):\n            func_name = str(name_var.name_hint)\n        if isinstance(name_var, Var):\n            func_name = self.get_var_name(name_var)\n\n        var_names = [self.get_var_name(var) for var in func.params]\n        body, defs = self.visit(func.body)\n        ret = self.create_def(func_name, var_names, defs + [Return(body)])\n        return (ret, func_name)\n\n    def convert_module(self):\n        \"\"\"Converts all the global functions defined in the module and returns\n        them as a list of definitions\"\"\"\n        defs = []\n        for var, func in self.mod.functions.items():\n            # optimize the definition so any operators used are lowered\n            opt_func = self.optimize(func)\n            try:\n                converted_func, _ = self.convert_func_node(opt_func, var)\n                defs.append(converted_func)\n            except TypeError:\n                # TODO(wweic): fix conversion for Any\n                pass\n        return defs\n\n    def create_call(self, func_name: str, arguments):\n        \"\"\"Creates a simple function call.\"\"\"\n        return ast.Call(self.parse_name(func_name), arguments, [])\n\n    def create_def(self, func_name: str, arguments: [str], body):\n        \"\"\"Wrapper over function definition AST node, whose constructor is inconvenient.\"\"\"\n        inner_args = [ast.arg(argument, None) for argument in arguments]\n\n        global __MAJOR__, __MINOR__\n        if __MAJOR__ == 3 and __MINOR__ == 8:\n            arguments = ast.arguments([], inner_args, None, [], [], None, [])\n        else:\n            arguments = ast.arguments(inner_args, None, [], [], None, [])\n\n        return ast.FunctionDef(\n            func_name,\n            arguments,\n            body,\n            [],\n            None,\n        )\n\n    def create_op_call(self, op: Function, relay_args, py_args):\n        \"\"\"Lowers the passed primitive function, registers it in TVM's\n        global compiler, and produces a call to the lowered function in\n        the generated Python code.\"\"\"\n\n        # compile the function and register globally\n        cc_key = te_compiler.CCacheKey(op, self.tgt)\n        func_hash = tvm.ir.structural_hash(op)\n        op_name = \"_lowered_op_{}\".format(func_hash)\n        if not tvm.get_global_func(op_name, allow_missing=True):\n            jitted = self.tec.jit(cc_key, self.tgt)\n            tvm.register_func(op_name, jitted)\n\n        def convert_input(py_input, arg_type):\n            \"\"\"Use the types of the function arguments to determine whether we expect\n            a tensor or tuple (returns list of inputs to the lowered op call)\"\"\"\n            # equivalent: input.data\n            if isinstance(arg_type, relay.TensorType):\n                return [py_input]\n            assert isinstance(arg_type, relay.TupleType)\n            # convert each input.fields[i]\n            ret = []\n            for i in range(len(arg_type.fields)):\n                ret += convert_input(\n                    ast.Subscript(py_input, ast.Index(Num(i)), Load()), arg_type.fields[i]\n                )\n            return ret\n\n        def convert_output(ret_type):\n            \"\"\"Use the function return type to produce auxiliary variables to store outputs.\n            Returns ([assignments of output vars], [extra arguments to pass to op call],\n            expression collecting output)\"\"\"\n            if isinstance(ret_type, relay.TensorType):\n                output_var_name = self.generate_var_name(\"_out\")\n                output_var = Name(output_var_name, Load())\n                shape = ast.Tuple([Num(dim) for dim in ret_type.concrete_shape], Load())\n                # create a new NDArray of the right shape and dtype\n                assign_output = Assign(\n                    [Name(output_var_name, Store())],\n                    self.create_call(\n                        \"nd.array\", [self.create_call(\"numpy.empty\", [shape, Str(ret_type.dtype)])]\n                    ),\n                )\n                return ([assign_output], [output_var], output_var)\n            assert isinstance(ret_type, relay.TupleType)\n            assignments = []\n            extra_args = []\n            fields = []\n            for t in ret_type.fields:\n                inner_assignments, inner_args, inner_output = convert_output(t)\n                assignments += inner_assignments\n                extra_args += inner_args\n                fields.append(inner_output)\n            fields = [ast.List(fields, Load())]\n            return (assignments, extra_args, self.create_call(\"_container.tuple_object\", fields))\n\n        # create a function to wrap the call of the lowered op and return\n        # a call to that function\n        wrap_name = self.generate_function_name(\"_{}_wrapper\".format(op_name))\n        wrap_args = [self.generate_var_name(\"_arg_{}\".format(i)) for i in range(len(py_args))]\n\n        inner_call_args = []\n        for i in range(len(py_args)):\n            inner_call_args += convert_input(Name(wrap_args[i], Load()), relay_args[i].checked_type)\n        output_assignments, aux_args, output = convert_output(op.checked_type.ret_type)\n        # equiv: _op = tvm.get_global_func(op_name)\n        op_var = self.generate_var_name(\"_op\")\n        op_call = self.create_call(\"tvm.get_global_func\", [Str(op_name)])\n        op_assign = Assign([Name(op_var, Store())], op_call)\n        # equiv: _op(args)\n        inner_call = self.create_call(op_var, inner_call_args + aux_args)\n        body = output_assignments + [op_assign, ast.Expr(inner_call), Return(output)]\n        wrap_def = self.create_def(wrap_name, wrap_args, body)\n        return wrap_def, self.create_call(wrap_name, py_args)\n\n    def create_match_check(self, pattern: Pattern, data):\n        \"\"\"Given an ADT match pattern and a (Python) expression pointing to\n        an ADT value, this generates a Python expression that checks if the\n        ADT value matches the given pattern (returning True or False).\"\"\"\n\n        # wildcard or var match everything\n        if isinstance(pattern, (relay.PatternWildcard, relay.PatternVar)):\n            return NameConstant(True)\n\n        conds = []\n\n        if isinstance(pattern, relay.PatternConstructor):\n            # constructor patterns check whether the constructors match\n            # and also the matches of any nested patterns\n\n            # equiv: (arg.tag == patern_constructor.tag)\n            conds.append(\n                ast.Compare(\n                    ast.Attribute(data, \"tag\", Load()),\n                    [ast.Eq()],\n                    [ast.Num(pattern.constructor.tag)],\n                )\n            )\n\n        assert isinstance(pattern, (relay.PatternConstructor, relay.PatternTuple))\n        # now check for any nested patterns\n        for i in range(len(pattern.patterns)):\n            nested_pat = pattern.patterns[i]\n            # can safely skip var or wildcard patterns: they will\n            # never cause a check to fail\n            if not isinstance(nested_pat, relay.PatternConstructor):\n                continue\n\n            # index into the value corresponding to the subpattern\n            field_index = ast.Subscript(\n                ast.Attribute(data, \"fields\", Load()), ast.Index(Num(i)), Load()\n            )\n            conds.append(self.create_match_check(nested_pat, field_index))\n\n        # if we do not need to check nested pattern, just return the single check\n        if len(conds) == 1:\n            return conds[0]\n        # otherwise AND together any nested checks\n        return ast.BoolOp(ast.And(), conds)\n\n    def create_match_clause_body(self, pattern: Pattern, body: Expr):\n        \"\"\"Given a match clause pattern and a clause body,\n        generates a Python function that when called with an ADT\n        that matches the pattern, returns the result of evaluating\n        the clause body. This function returns a function definition\n        and the name of the generated function.\"\"\"\n\n        def collect_var_assignments(pat, val):\n            \"\"\"This helper function ensures that the pattern is used to\n            properly assign all subfields of the given AST for use\n            in the clause body\n\n            E.g., for PatternConstructor(A, PatternVar(v), PatternWildcard(),\n            PatternConstructor(B, PatternVar(w)))\n            we would want to have\n            v = a.fields[0]\n            w = a.fields[2].fields[0]\n            \"\"\"\n            if isinstance(pat, relay.PatternWildcard):\n                return []\n            if isinstance(pat, relay.PatternVar):\n                return [Assign([self.include_var(pat.var, assign=True)], val)]\n            # constructor pattern: assign each field of the value\n            # based on subpatterns\n            assignments = []\n            for i in range(len(pat.patterns)):\n                # we want the assignments for val.fields[i]\n                field = ast.Subscript(\n                    ast.Attribute(val, \"fields\", Load()), ast.Index(Num(i)), Load()\n                )\n                assignments += collect_var_assignments(pat.patterns[i], field)\n            return assignments\n\n        func_name = self.generate_function_name(\"_match_clause_body\")\n        arg_name = self.generate_var_name(\"_match_clause_body\")\n\n        clause_body, defs = self.visit(body)\n        assignments = collect_var_assignments(pattern, Name(arg_name, Load()))\n\n        func_def = self.create_def(\n            func_name, [arg_name], defs + assignments + [Return(clause_body)]\n        )\n        return (func_def, func_name)\n\n    # Convention for the expr visitor: Each visit function returns a tuple of two members.\n    #\n    # The first is a Python AST comprised of a single *expression* that evaluates to an equivalent\n    # result to the desired Relay expression (and executes all effects in the right order).\n    #\n    # The second is a list of function definition *statements* defining thunks and other\n    # auxiliary functions needed in the translated AST object. The defs in the second object\n    # will always have unique names and will never perform any effects, so as long as they\n    # appear in the Python program before the first statement is executed, there should not\n    # be any problems.\n\n    def visit_var(self, var: Expr):\n        return (self.include_var(var, assign=False), [])\n\n    def visit_global_var(self, gvar: Expr):\n        # we don't need to add numbers to global var names because\n        # the *names* are checked for uniqueness in the mod\n        return (Name(str(gvar.name_hint), Load()), [])\n\n    def visit_let(self, letexp: Expr):\n        # To properly account for scoping and ensure that the entire node produces an expression,\n        # we translate the let binding as a function that we call with the value we intend to bind.\n        # Yes, this is somewhat ugly.\n        \"\"\"\n        let var = value in body\n        =======================\n        def let_thunk(var):\n            return body\n        let_thunk(value)\n        \"\"\"\n        bind_body, bind_defs = self.visit(letexp.body)\n\n        func_name = self.generate_function_name(\"_let_func\")\n        binding_func = self.create_def(\n            func_name, [self.get_var_name(letexp.var)], bind_defs + [Return(bind_body)]\n        )\n\n        # we call the binding func with the intended value for the bound variable\n\n        # special case: if the value is a function literal, we must ensure it can be\n        # recursive by naming it after the var\n        if isinstance(letexp.value, Function):\n            value_def, value_name = self.convert_func_node(letexp.value, letexp.var)\n            return (\n                self.create_call(func_name, [Name(value_name, Load())]),\n                [value_def, binding_func],\n            )\n\n        value_body, value_defs = self.visit(letexp.value)\n        value_defs.append(binding_func)\n        binding_call = self.create_call(func_name, [value_body])\n        return (binding_call, value_defs)\n\n    def visit_tuple(self, tup: Expr):\n        fields, ret_defs = self.convert_fields(tup.fields)\n        fields = [ast.List(fields, Load())]\n        return (self.create_call(\"_container.tuple_object\", fields), ret_defs)\n\n    def visit_tuple_getitem(self, tgi: Expr):\n        tup, tup_defs = self.visit(tgi.tuple_value)\n        ret = ast.Subscript(tup, ast.Index(Num(tgi.index)), Load())\n        return (ret, tup_defs)\n\n    def visit_if(self, if_block: Expr):\n        cond_body, cond_defs = self.visit(if_block.cond)\n        true_body, true_defs = self.visit(if_block.true_branch)\n        false_body, false_defs = self.visit(if_block.false_branch)\n\n        # need to get the value out of a NDArray to check the condition\n        # equvialent to: val.numpy()\n        cond_check = ast.Call(ast.Attribute(cond_body, \"asnumpy\", Load()), [], [])\n        ret = ast.IfExp(cond_check, true_body, false_body)\n        return (ret, cond_defs + true_defs + false_defs)\n\n    def visit_constant(self, constant: Expr):\n        \"\"\"Proceeds by converting constant value to a numpy array\n        and converting it to the appropriate value in the generated\n        code (whether it be a Python scalar or a Numpy array)\"\"\"\n        value = constant.data.numpy()\n        const_expr = ast.Call(\n            ast.Attribute(Name(\"numpy\", Load()), \"array\", Load()),\n            [self.parse_numpy_array(value)],\n            [ast.keyword(\"dtype\", Str(constant.checked_type.dtype))],\n        )\n        return (self.create_call(\"nd.array\", [const_expr]), [])\n\n    def visit_function(self, func: Expr):\n        # Python's lambdas are very restrictive, so we do \"name\" inline functions\n        converted_func, func_name = self.convert_func_node(func)\n        return (Name(func_name, Load()), [converted_func])\n\n    def visit_call(self, call: Expr):\n        \"\"\"For calls, we must distinguish between ordinary functions,\n        operators, and constructor calls.\"\"\"\n        func = call.op\n        fields, field_defs = self.convert_fields(call.args)\n\n        if isinstance(func, tvm.ir.Op):\n            raise Exception(\"Operators should have been lowered and eliminated\")\n\n        if isinstance(func, relay.Constructor):\n            # produce a constructor value\n            return (\n                self.create_call(\n                    \"ConstructorValue\",\n                    [ast.Num(func.tag), ast.List(fields, Load()), NameConstant(None)],\n                ),\n                field_defs,\n            )\n\n        # lowered operator: generate a call to a function that gets the PackedFunc\n        # from TVM's registry\n        if isinstance(func, Function) and func.attrs and func.attrs.Primitive.value == 1:\n            op_call_def, op_call = self.create_op_call(func, call.args, fields)\n            return (op_call, field_defs + [op_call_def])\n\n        # ordinary function\n        converted_func, defs = self.visit(func)\n        defs += field_defs\n        return (ast.Call(converted_func, fields, []), defs)\n\n    def visit_ref_create(self, ref: Expr):\n        val, defs = self.visit(ref.value)\n        return (self.create_call(\"RefValue\", [val]), defs)\n\n    def visit_ref_read(self, read: Expr):\n        ref, defs = self.visit(read.ref)\n        return (ast.Attribute(ref, \"value\", Load()), defs)\n\n    def visit_ref_write(self, write: Expr):\n        \"\"\"For writing refs, we wrap the update in a thunk\n        (returning an empty tuple to match Relay's semantics)\n        that we execute at the right time. This ensures such assignments\n        can be properly nested, since assignments are statements\n        in Python but expressions in Relay\"\"\"\n        ref, ref_defs = self.visit(write.ref)\n        val, val_defs = self.visit(write.value)\n        thunk_name = self.generate_function_name(\"_ref_write_thunk\")\n        thunk = self.create_def(\n            thunk_name,\n            [],\n            ref_defs\n            + val_defs\n            + [\n                Assign([ast.Attribute(ref, \"value\", Store())], val),\n                Return(self.create_call(\"_container.tuple_object\", [])),\n            ],\n        )\n        return (self.create_call(thunk_name, []), [thunk])\n\n    def visit_match(self, match: Expr):\n        \"\"\"For matches, we wrap the entire expression in a thunk\n        because it is easiest to implement them using if statements.\n        For each clause, we generate a function that checks if the\n        pattern matches. If yes, we call a function that assigns\n        the variables appropriately and invokes the clause body.\"\"\"\n        data, defs = self.visit(match.data)\n        data_var = self.generate_var_name(\"_match_data\")\n\n        # must ensure the data clause is executed exactly once\n        thunk_body = [Assign([Name(data_var, Store())], data)]\n        for clause in match.clauses:\n            check_expr = self.create_match_check(clause.lhs, Name(data_var, Load()))\n            body_def, body_name = self.create_match_clause_body(clause.lhs, clause.rhs)\n            defs.append(body_def)\n\n            # equiv: if check(data): return body(data)\n            thunk_body.append(\n                ast.If(\n                    check_expr, [Return(self.create_call(body_name, [Name(data_var, Load())]))], []\n                )\n            )\n\n        # finally if nothing matches we have a failed assert (should never happen)\n        thunk_body.append(ast.Assert(NameConstant(False), Str(\"Match was not exhaustive\")))\n\n        thunk_name = self.generate_function_name(\"_match_thunk\")\n        thunk_def = self.create_def(thunk_name, [], defs + thunk_body)\n        return (self.create_call(thunk_name, []), [thunk_def])\n\n    # these are both handled in the \"call\" case\n    def visit_constructor(self, _):\n        pass\n\n    def visit_op(self, _):\n        pass\n\n\ndef to_python(expr: Expr, mod=None, target=tvm.target.Target(\"llvm\")):\n    \"\"\"Converts the given Relay expression into a Python script (as a Python AST object).\n    For easiest debugging, import the astor package and use to_source().\"\"\"\n    mod = mod if mod is not None else tvm.IRModule()\n    mod = relay.transform.InferType()(mod)\n    converter = PythonConverter(mod, target)\n    python = converter.convert(expr)\n    assert python\n    return python\n\n\ndef run_as_python(expr: Expr, mod=None, target=tvm.target.Target(\"llvm\")):\n    \"\"\"Converts the given Relay expression into a Python script and\n    executes it.\"\"\"\n    mod = mod if mod is not None else tvm.IRModule()\n    py_ast = to_python(expr, mod, target)\n    code = compile(py_ast, \"<string>\", \"exec\")\n    var_map = {OUTPUT_VAR_NAME: None}\n    # pylint: disable=exec-used\n    exec(code, var_map, var_map)\n    return var_map[OUTPUT_VAR_NAME]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/resnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAdapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py\nOriginal author Wei Wu\n\nImplemented the following paper:\n\nKaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. \"Identity Mappings in Deep Residual Networks\"\n\"\"\"\n# pylint: disable=unused-argument\nfrom tvm import relay\nfrom .init import create_workload\nfrom . import layers\n\n\ndef residual_unit(\n    data,\n    num_filter,\n    stride,\n    dim_match,\n    name,\n    bottle_neck=True,\n    data_layout=\"NCHW\",\n    kernel_layout=\"IOHW\",\n):\n    \"\"\"Return ResNet Unit symbol for building ResNet\n\n    Parameters\n    ----------\n    data : str\n        Input data\n\n    num_filter : int\n        Number of output channels\n\n    bnf : int\n        Bottle neck channels factor with regard to num_filter\n\n    stride : tuple\n        Stride used in convolution\n\n    dim_match : bool\n        True means channel number between input and output is the same,\n        otherwise means differ\n\n    name : str\n        Base name of the operators\n    \"\"\"\n    bn_axis = data_layout.index(\"C\")\n    if bottle_neck:\n        bn1 = layers.batch_norm_infer(data=data, epsilon=2e-5, axis=bn_axis, name=name + \"_bn1\")\n        act1 = relay.nn.relu(data=bn1)\n        conv1 = layers.conv2d(\n            data=act1,\n            channels=int(num_filter * 0.25),\n            kernel_size=(1, 1),\n            strides=stride,\n            padding=(0, 0),\n            name=name + \"_conv1\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        bn2 = layers.batch_norm_infer(data=conv1, epsilon=2e-5, axis=bn_axis, name=name + \"_bn2\")\n        act2 = relay.nn.relu(data=bn2)\n        conv2 = layers.conv2d(\n            data=act2,\n            channels=int(num_filter * 0.25),\n            kernel_size=(3, 3),\n            strides=(1, 1),\n            padding=(1, 1),\n            name=name + \"_conv2\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        bn3 = layers.batch_norm_infer(data=conv2, epsilon=2e-5, axis=bn_axis, name=name + \"_bn3\")\n        act3 = relay.nn.relu(data=bn3)\n        conv3 = layers.conv2d(\n            data=act3,\n            channels=num_filter,\n            kernel_size=(1, 1),\n            strides=(1, 1),\n            padding=(0, 0),\n            name=name + \"_conv3\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = layers.conv2d(\n                data=act1,\n                channels=num_filter,\n                kernel_size=(1, 1),\n                strides=stride,\n                name=name + \"_sc\",\n                data_layout=data_layout,\n                kernel_layout=kernel_layout,\n            )\n        return relay.add(conv3, shortcut)\n\n    bn1 = layers.batch_norm_infer(data=data, epsilon=2e-5, axis=bn_axis, name=name + \"_bn1\")\n    act1 = relay.nn.relu(data=bn1)\n    conv1 = layers.conv2d(\n        data=act1,\n        channels=num_filter,\n        kernel_size=(3, 3),\n        strides=stride,\n        padding=(1, 1),\n        name=name + \"_conv1\",\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    bn2 = layers.batch_norm_infer(data=conv1, epsilon=2e-5, axis=bn_axis, name=name + \"_bn2\")\n    act2 = relay.nn.relu(data=bn2)\n    conv2 = layers.conv2d(\n        data=act2,\n        channels=num_filter,\n        kernel_size=(3, 3),\n        strides=(1, 1),\n        padding=(1, 1),\n        name=name + \"_conv2\",\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    if dim_match:\n        shortcut = data\n    else:\n        shortcut = layers.conv2d(\n            data=act1,\n            channels=num_filter,\n            kernel_size=(1, 1),\n            strides=stride,\n            name=name + \"_sc\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n    return relay.add(conv2, shortcut)\n\n\ndef resnet(\n    units,\n    num_stages,\n    filter_list,\n    num_classes,\n    data_shape,\n    bottle_neck=True,\n    layout=\"NCHW\",\n    dtype=\"float32\",\n):\n    \"\"\"Return ResNet Program.\n\n    Parameters\n    ----------\n    units : list\n        Number of units in each stage\n\n    num_stages : int\n        Number of stages\n\n    filter_list : list\n        Channel size of each stage\n\n    num_classes : int\n        Output size of symbol\n\n    data_shape : tuple of int.\n        The shape of input data.\n\n    bottle_neck : bool\n        Whether apply bottleneck transformation.\n\n    layout: str\n        The data layout for conv2d\n\n    dtype : str\n        The global data type.\n    \"\"\"\n\n    data_layout = layout\n    kernel_layout = \"OIHW\" if layout == \"NCHW\" else \"HWIO\"\n    bn_axis = data_layout.index(\"C\")\n\n    num_unit = len(units)\n    assert num_unit == num_stages\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    data = layers.batch_norm_infer(\n        data=data, epsilon=2e-5, axis=bn_axis, scale=False, name=\"bn_data\"\n    )\n    (_, _, height, _) = data_shape\n    if layout == \"NHWC\":\n        (_, height, _, _) = data_shape\n    if height <= 32:  # such as cifar10\n        body = layers.conv2d(\n            data=data,\n            channels=filter_list[0],\n            kernel_size=(3, 3),\n            strides=(1, 1),\n            padding=(1, 1),\n            name=\"conv0\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n    else:  # often expected to be 224 such as imagenet\n        body = layers.conv2d(\n            data=data,\n            channels=filter_list[0],\n            kernel_size=(7, 7),\n            strides=(2, 2),\n            padding=(3, 3),\n            name=\"conv0\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        body = layers.batch_norm_infer(data=body, epsilon=2e-5, axis=bn_axis, name=\"bn0\")\n        body = relay.nn.relu(data=body)\n        body = relay.nn.max_pool2d(\n            data=body, pool_size=(3, 3), strides=(2, 2), padding=(1, 1), layout=data_layout\n        )\n\n    for i in range(num_stages):\n        body = residual_unit(\n            body,\n            filter_list[i + 1],\n            (1 if i == 0 else 2, 1 if i == 0 else 2),\n            False,\n            name=\"stage%d_unit%d\" % (i + 1, 1),\n            bottle_neck=bottle_neck,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        for j in range(units[i] - 1):\n            body = residual_unit(\n                body,\n                filter_list[i + 1],\n                (1, 1),\n                True,\n                name=\"stage%d_unit%d\" % (i + 1, j + 2),\n                bottle_neck=bottle_neck,\n                data_layout=data_layout,\n                kernel_layout=kernel_layout,\n            )\n    bn1 = layers.batch_norm_infer(data=body, epsilon=2e-5, axis=bn_axis, name=\"bn1\")\n    relu1 = relay.nn.relu(data=bn1)\n    # Although kernel is not used here when global_pool=True, we should put one\n    pool1 = relay.nn.global_avg_pool2d(data=relu1, layout=data_layout)\n    flat = relay.nn.batch_flatten(data=pool1)\n    fc1 = layers.dense_add_bias(data=flat, units=num_classes, name=\"fc1\")\n    net = relay.nn.softmax(data=fc1)\n    return relay.Function(relay.analysis.free_vars(net), net)\n\n\ndef get_net(\n    batch_size,\n    num_classes,\n    num_layers=50,\n    image_shape=(3, 224, 224),\n    layout=\"NCHW\",\n    dtype=\"float32\",\n    **kwargs,\n):\n    \"\"\"\n    Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py\n    Original author Wei Wu\n    \"\"\"\n    (_, height, _) = image_shape\n    if layout == \"NHWC\":\n        (height, _, _) = image_shape\n    data_shape = (batch_size,) + image_shape\n    if height <= 28:\n        num_stages = 3\n        if (num_layers - 2) % 9 == 0 and num_layers >= 164:\n            per_unit = [(num_layers - 2) // 9]\n            filter_list = [16, 64, 128, 256]\n            bottle_neck = True\n        elif (num_layers - 2) % 6 == 0 and num_layers < 164:\n            per_unit = [(num_layers - 2) // 6]\n            filter_list = [16, 16, 32, 64]\n            bottle_neck = False\n        else:\n            raise ValueError(\"no experiments done on num_layers {}\".format(num_layers))\n        units = per_unit * num_stages\n    else:\n        if num_layers >= 50:\n            filter_list = [64, 256, 512, 1024, 2048]\n            bottle_neck = True\n        else:\n            filter_list = [64, 64, 128, 256, 512]\n            bottle_neck = False\n        num_stages = 4\n        if num_layers == 18:\n            units = [2, 2, 2, 2]\n        elif num_layers == 34:\n            units = [3, 4, 6, 3]\n        elif num_layers == 50:\n            units = [3, 4, 6, 3]\n        elif num_layers == 101:\n            units = [3, 4, 23, 3]\n        elif num_layers == 152:\n            units = [3, 8, 36, 3]\n        elif num_layers == 200:\n            units = [3, 24, 36, 3]\n        elif num_layers == 269:\n            units = [3, 30, 48, 8]\n        else:\n            raise ValueError(\"no experiments done on num_layers {}\".format(num_layers))\n\n    return resnet(\n        units=units,\n        num_stages=num_stages,\n        filter_list=filter_list,\n        num_classes=num_classes,\n        data_shape=data_shape,\n        bottle_neck=bottle_neck,\n        layout=layout,\n        dtype=dtype,\n    )\n\n\ndef get_workload(\n    batch_size=1,\n    num_classes=1000,\n    num_layers=18,\n    image_shape=(3, 224, 224),\n    layout=\"NCHW\",\n    dtype=\"float32\",\n    **kwargs,\n):\n    \"\"\"Get benchmark workload for resnet\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    num_layers : int, optional\n        Number of layers\n\n    image_shape : tuple, optional\n        The input image shape\n\n    layout: str\n        The data layout for conv2d\n\n    dtype : str, optional\n        The data type\n\n    kwargs : dict\n        Extra arguments\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a ResNet network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(\n        batch_size=batch_size,\n        num_classes=num_classes,\n        num_layers=num_layers,\n        image_shape=image_shape,\n        dtype=dtype,\n        layout=layout,\n        **kwargs,\n    )\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/resnet_3d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nNetwork definition of 3D ResNet for Action Recognition (CVPR 2018)\n\nReference : https://github.com/kenshohara/3D-ResNets-PyTorch\n\"\"\"\n\n# pylint: disable=unused-argument\nfrom tvm import relay\nfrom .init import create_workload\nfrom . import layers\n\n\ndef residual_unit(\n    data,\n    num_filter,\n    stride,\n    dim_match,\n    name,\n    bottle_neck=True,\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n):\n    \"\"\"Return ResNet Unit symbol for building ResNet\n\n    Parameters\n    ----------\n    data : str\n        Input data\n\n    num_filter : int\n        Number of output channels\n\n    bnf : int\n        Bottle neck channels factor with regard to num_filter\n\n    stride : tuple\n        Stride used in convolution\n\n    dim_match : bool\n        True means channel number between input and output is the same,\n        otherwise means differ\n\n    name : str\n        Base name of the operators\n    \"\"\"\n    if bottle_neck:\n        bn1 = layers.batch_norm_infer(data=data, epsilon=2e-5, name=name + \"_bn1\")\n        act1 = relay.nn.relu(data=bn1)\n        conv1 = layers.conv3d(\n            data=act1,\n            channels=int(num_filter * 0.25),\n            kernel_size=(1, 1, 1),\n            strides=stride,\n            padding=(0, 0, 0),\n            name=name + \"_conv1\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        bn2 = layers.batch_norm_infer(data=conv1, epsilon=2e-5, name=name + \"_bn2\")\n        act2 = relay.nn.relu(data=bn2)\n        conv2 = layers.conv3d(\n            data=act2,\n            channels=int(num_filter * 0.25),\n            kernel_size=(3, 3, 3),\n            strides=(1, 1, 1),\n            padding=(1, 1, 1),\n            name=name + \"_conv2\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        bn3 = layers.batch_norm_infer(data=conv2, epsilon=2e-5, name=name + \"_bn3\")\n        act3 = relay.nn.relu(data=bn3)\n        conv3 = layers.conv3d(\n            data=act3,\n            channels=num_filter,\n            kernel_size=(1, 1, 1),\n            strides=(1, 1, 1),\n            padding=(0, 0, 0),\n            name=name + \"_conv3\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = layers.conv3d(\n                data=act1,\n                channels=num_filter,\n                kernel_size=(1, 1, 1),\n                strides=stride,\n                name=name + \"_sc\",\n                data_layout=data_layout,\n                kernel_layout=kernel_layout,\n            )\n        return relay.add(conv3, shortcut)\n\n    bn1 = layers.batch_norm_infer(data=data, epsilon=2e-5, name=name + \"_bn1\")\n    act1 = relay.nn.relu(data=bn1)\n    conv1 = layers.conv3d(\n        data=act1,\n        channels=num_filter,\n        kernel_size=(3, 3, 3),\n        strides=stride,\n        padding=(1, 1, 1),\n        name=name + \"_conv1\",\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    bn2 = layers.batch_norm_infer(data=conv1, epsilon=2e-5, name=name + \"_bn2\")\n    act2 = relay.nn.relu(data=bn2)\n    conv2 = layers.conv3d(\n        data=act2,\n        channels=num_filter,\n        kernel_size=(3, 3, 3),\n        strides=(1, 1, 1),\n        padding=(1, 1, 1),\n        name=name + \"_conv2\",\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    if dim_match:\n        shortcut = data\n    else:\n        shortcut = layers.conv3d(\n            data=act1,\n            channels=num_filter,\n            kernel_size=(1, 1, 1),\n            strides=stride,\n            name=name + \"_sc\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n    return relay.add(conv2, shortcut)\n\n\ndef resnet(\n    units,\n    num_stages,\n    filter_list,\n    num_classes,\n    data_shape,\n    bottle_neck=True,\n    layout=\"NCDHW\",\n    dtype=\"float32\",\n):\n    \"\"\"Return ResNet Program.\n\n    Parameters\n    ----------\n    units : list\n        Number of units in each stage\n\n    num_stages : int\n        Number of stages\n\n    filter_list : list\n        Channel size of each stage\n\n    num_classes : int\n        Output size of symbol\n\n    data_shape : tuple of int.\n        The shape of input data.\n\n    bottle_neck : bool\n        Whether apply bottleneck transformation.\n\n    layout: str\n        The data layout for conv3d\n\n    dtype : str\n        The global data type.\n    \"\"\"\n\n    data_layout = layout\n    kernel_layout = \"OIDHW\" if layout == \"NCDHW\" else \"DHWIO\"\n\n    num_unit = len(units)\n    assert num_unit == num_stages\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    data = layers.batch_norm_infer(data=data, epsilon=2e-5, scale=False, name=\"bn_data\")\n    if layout == \"NCDHW\":\n        (_, _, _, height, _) = data_shape\n    else:\n        (_, _, height, _, _) = data_shape\n    if height <= 32:  # such as cifar10\n        body = layers.conv3d(\n            data=data,\n            channels=filter_list[0],\n            kernel_size=(3, 3, 3),\n            strides=(1, 1, 1),\n            padding=(1, 1, 1),\n            name=\"conv0\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n    else:  # often expected to be 224 such as imagenet\n        body = layers.conv3d(\n            data=data,\n            channels=filter_list[0],\n            kernel_size=(3, 7, 7),\n            strides=(1, 2, 2),\n            padding=(1, 3, 3),\n            name=\"conv0\",\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        body = layers.batch_norm_infer(data=body, epsilon=2e-5, name=\"bn0\")\n        body = relay.nn.relu(data=body)\n        # body = relay.nn.max_pool3d(data=body, pool_size=(3, 3), strides=(2, 2), padding=(1, 1),\n        #                           layout=data_layout)\n\n    for i in range(num_stages):\n        body = residual_unit(\n            body,\n            filter_list[i + 1],\n            (1 if i == 0 else 2, 1 if i == 0 else 2, 1 if i == 0 else 2),\n            False,\n            name=\"stage%d_unit%d\" % (i + 1, 1),\n            bottle_neck=bottle_neck,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        for j in range(units[i] - 1):\n            body = residual_unit(\n                body,\n                filter_list[i + 1],\n                (1, 1, 1),\n                True,\n                name=\"stage%d_unit%d\" % (i + 1, j + 2),\n                bottle_neck=bottle_neck,\n                data_layout=data_layout,\n                kernel_layout=kernel_layout,\n            )\n    bn1 = layers.batch_norm_infer(data=body, epsilon=2e-5, name=\"bn1\")\n    relu1 = relay.nn.relu(data=bn1)\n    # Although kernel is not used here when global_pool=True, we should put one\n    pool1 = relay.nn.global_avg_pool3d(data=relu1, layout=data_layout)\n    flat = relay.nn.batch_flatten(data=pool1)\n    fc1 = layers.dense_add_bias(data=flat, units=num_classes, name=\"fc1\")\n    net = relay.nn.softmax(data=fc1)\n    return relay.Function(relay.analysis.free_vars(net), net)\n\n\ndef get_net(\n    batch_size,\n    num_classes,\n    num_layers=50,\n    image_shape=(3, 16, 112, 112),\n    layout=\"NCDHW\",\n    dtype=\"float32\",\n    **kwargs,\n):\n    \"\"\"\n    Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py\n    Original author Wei Wu\n    \"\"\"\n    if layout == \"NCDHW\":\n        (_, _, height, _) = image_shape\n    else:\n        (_, height, _, _) = image_shape\n    data_shape = (batch_size,) + image_shape\n    if height <= 28:\n        num_stages = 3\n        if (num_layers - 2) % 9 == 0 and num_layers >= 164:\n            per_unit = [(num_layers - 2) // 9]\n            filter_list = [16, 64, 128, 256]\n            bottle_neck = True\n        elif (num_layers - 2) % 6 == 0 and num_layers < 164:\n            per_unit = [(num_layers - 2) // 6]\n            filter_list = [16, 16, 32, 64]\n            bottle_neck = False\n        else:\n            raise ValueError(\"no experiments done on num_layers {}\".format(num_layers))\n        units = per_unit * num_stages\n    else:\n        if num_layers >= 50:\n            filter_list = [64, 256, 512, 1024, 2048]\n            bottle_neck = True\n        else:\n            filter_list = [64, 64, 128, 256, 512]\n            bottle_neck = False\n        num_stages = 4\n        if num_layers == 18:\n            units = [2, 2, 2, 2]\n        elif num_layers == 34:\n            units = [3, 4, 6, 3]\n        elif num_layers == 50:\n            units = [3, 4, 6, 3]\n        elif num_layers == 101:\n            units = [3, 4, 23, 3]\n        elif num_layers == 152:\n            units = [3, 8, 36, 3]\n        elif num_layers == 200:\n            units = [3, 24, 36, 3]\n        elif num_layers == 269:\n            units = [3, 30, 48, 8]\n        else:\n            raise ValueError(\"no experiments done on num_layers {}\".format(num_layers))\n\n    return resnet(\n        units=units,\n        num_stages=num_stages,\n        filter_list=filter_list,\n        num_classes=num_classes,\n        data_shape=data_shape,\n        bottle_neck=bottle_neck,\n        layout=layout,\n        dtype=dtype,\n    )\n\n\ndef get_workload(\n    batch_size=1,\n    num_classes=1000,\n    num_layers=18,\n    image_shape=(3, 16, 112, 112),\n    layout=\"NCDHW\",\n    dtype=\"float32\",\n    **kwargs,\n):\n    \"\"\"Get benchmark workload for resnet\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    num_layers : int, optional\n        Number of layers\n\n    image_shape : tuple, optional\n        The input image shape\n\n    layout: str\n        The data layout for conv3d\n\n    dtype : str, optional\n        The data type\n\n    kwargs : dict\n        Extra arguments\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a ResNet network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(\n        batch_size=batch_size,\n        num_classes=num_classes,\n        num_layers=num_layers,\n        image_shape=image_shape,\n        dtype=dtype,\n        layout=layout,\n        **kwargs,\n    )\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/squeezenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# coding: utf-8\n# pylint: disable=unused-argument\n\n\"\"\"\nSymbol of SqueezeNet\n\nReference:\nIandola, Forrest N., et al.\n\"Squeezenet: Alexnet-level accuracy with 50x fewer parameters and< 0.5 mb model size.\" (2016).\n\"\"\"\n\nfrom tvm import relay\nfrom .init import create_workload\nfrom . import layers\n\n# Helpers\ndef _make_fire(net, squeeze_channels, expand1x1_channels, expand3x3_channels, prefix):\n    net = _make_fire_conv(net, squeeze_channels, 1, 0, \"%s_input\" % prefix)\n\n    left = _make_fire_conv(net, expand1x1_channels, 1, 0, \"%s_left\" % prefix)\n    right = _make_fire_conv(net, expand3x3_channels, 3, 1, \"%s_right\" % prefix)\n    # NOTE : Assume NCHW layout here\n    net = relay.concatenate((left, right), axis=1)\n    return net\n\n\ndef _make_fire_conv(net, channels, kernel_size, padding=0, prefix=\"\"):\n    net = layers.conv2d(\n        net,\n        channels=channels,\n        kernel_size=(kernel_size, kernel_size),\n        padding=(padding, padding),\n        name=\"%s_conv\" % prefix,\n    )\n    net = relay.nn.bias_add(net, relay.var(\"%s_conv_bias\" % prefix))\n    net = relay.nn.relu(net)\n    return net\n\n\n# Net\ndef get_net(batch_size, image_shape, num_classes, version, dtype):\n    \"\"\"Get symbol of SqueezeNet\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    image_shape : tuple, optional\n        The input image shape\n\n    num_classes: int\n        The number of classification results\n\n    version : str, optional\n        \"1.0\" or \"1.1\" of SqueezeNet\n    \"\"\"\n    assert version in [\n        \"1.0\",\n        \"1.1\",\n    ], \"Unsupported SqueezeNet version {version}:\" \"1.0 or 1.1 expected\".format(version=version)\n    data_shape = (batch_size,) + image_shape\n    net = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    if version == \"1.0\":\n        net = layers.conv2d(\n            net, channels=96, kernel_size=(7, 7), strides=(2, 2), padding=(3, 3), name=\"conv1\"\n        )\n        net = relay.nn.bias_add(net, relay.var(\"conv1_bias\"))\n        net = relay.nn.relu(net)\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 16, 64, 64, \"fire1\")\n        net = _make_fire(net, 16, 64, 64, \"fire2\")\n        net = _make_fire(net, 32, 128, 128, \"fire3\")\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 32, 128, 128, \"fire4\")\n        net = _make_fire(net, 48, 192, 192, \"fire5\")\n        net = _make_fire(net, 48, 192, 192, \"fire6\")\n        net = _make_fire(net, 64, 256, 256, \"fire7\")\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 64, 256, 256, \"fire8\")\n    else:\n        net = layers.conv2d(\n            net, channels=64, kernel_size=(3, 3), strides=(2, 2), padding=(1, 1), name=\"conv1\"\n        )\n        net = relay.nn.bias_add(net, relay.var(\"conv1_bias\"))\n        net = relay.nn.relu(net)\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 16, 64, 64, \"fire1\")\n        net = _make_fire(net, 16, 64, 64, \"fire2\")\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 32, 128, 128, \"fire3\")\n        net = _make_fire(net, 32, 128, 128, \"fire4\")\n        net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n        net = _make_fire(net, 48, 192, 192, \"fire5\")\n        net = _make_fire(net, 48, 192, 192, \"fire6\")\n        net = _make_fire(net, 64, 256, 256, \"fire7\")\n        net = _make_fire(net, 64, 256, 256, \"fire8\")\n    net = relay.nn.dropout(net, rate=0.5)\n    net = layers.conv2d(net, channels=num_classes, kernel_size=(1, 1), name=\"conv_final\")\n    net = relay.nn.bias_add(net, relay.var(\"conv_final_bias\"))\n    net = relay.nn.relu(net)\n    net = relay.nn.global_avg_pool2d(net)\n    net = relay.nn.batch_flatten(net)\n    net = relay.nn.softmax(net)\n    args = relay.analysis.free_vars(net)\n    return relay.Function(args, net)\n\n\ndef get_workload(\n    batch_size=1, num_classes=1000, version=\"1.0\", image_shape=(3, 224, 224), dtype=\"float32\"\n):\n    \"\"\"Get benchmark workload for SqueezeNet\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    version : str, optional\n        \"1.0\" or \"1.1\" of SqueezeNet\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a SqueezeNet network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n\n    net = get_net(batch_size, image_shape, num_classes, version, dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/synthetic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nSynthetic networks for testing purposes. Ideally, these networks are similar in\nstructure to real world networks, but are much smaller in order to make testing\nfaster.\n\"\"\"\nfrom __future__ import absolute_import\nfrom tvm import relay\nfrom .init import create_workload, Constant\nfrom . import layers\n\n\ndef get_net(input_shape=(1, 3, 24, 12), dtype=\"float32\", wtype=None):\n    \"\"\"Get synthetic testing network.\n\n    Parameters\n    ----------\n    image_shape : tuple, optional\n        The input shape as (batch_size, channels, height, width).\n\n    dtype : str, optional\n        The data type for the input.\n\n    wtype : str, optional\n        The data type for weights. Defaults to `dtype`.\n\n    Returns\n    -------\n    net : relay.Function\n        The dataflow.\n    \"\"\"\n    if wtype is None:\n        wtype = dtype\n    data = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    dense_shape = [-1, input_shape[3]]\n    dense = relay.nn.relu(\n        relay.nn.dense(\n            relay.reshape(data, dense_shape),\n            relay.var(\"dense_weight\", shape=[input_shape[3], dense_shape[1]], dtype=wtype),\n        )\n    )\n    dense = relay.reshape_like(dense, data)\n    conv_shape = [input_shape[1], input_shape[1], 3, 3]\n    conv = relay.nn.softmax(\n        relay.nn.conv2d(\n            data,\n            relay.var(\"conv_weight\", shape=conv_shape, dtype=wtype),\n            padding=1,\n            kernel_size=3,\n        )\n    )\n    added = relay.add(dense, conv)\n    biased = layers.batch_norm_infer(\n        relay.nn.bias_add(added, relay.var(\"bias\", dtype=wtype)), name=\"batch_norm\"\n    )\n    dense = relay.nn.relu(\n        relay.nn.dense(\n            relay.reshape(biased, dense_shape),\n            relay.var(\"dense2_weight\", shape=[input_shape[3], dense_shape[1]], dtype=wtype),\n        )\n    )\n    dense = relay.reshape_like(dense, data)\n    conv = relay.nn.softmax(\n        relay.nn.conv2d(\n            biased,\n            relay.var(\"conv2_weight\", shape=conv_shape, dtype=wtype),\n            padding=1,\n            kernel_size=3,\n        )\n    )\n    added = relay.add(dense, conv)\n    args = relay.analysis.free_vars(added)\n    return relay.Function(args, added)\n\n\ndef get_workload(input_shape=(1, 3, 24, 12), dtype=\"float32\", wtype=None):\n    \"\"\"Get benchmark workload for the synthetic net.\n\n    Parameters\n    ----------\n    image_shape : tuple, optional\n        The input shape as (batch_size, channels, height, width).\n\n    dtype : str, optional\n        The data type for the input.\n\n    wtype : str, optional\n        The data type for weights. Defaults to `dtype`.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a synthetic network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    return create_workload(\n        get_net(input_shape=input_shape, dtype=dtype, wtype=wtype),\n        initializer=Constant(),\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/temp_op_attr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Defines a TempOpAttr class that allows temporarily changing an attr of the\noperator to allow unit testing. This is useful for AlterOpLayout and Legalize\ntests.\"\"\"\n\nfrom tvm import relay\n\n\nclass TempOpAttr(object):\n    \"\"\"Temporarily changes the attr of an op.\"\"\"\n\n    def __init__(self, op_name, attr_key, attr_value):\n        \"\"\"Saves the required info for RAII pattern usage.\n\n        Parameters\n        ----------\n        op_name : str\n            The op name.\n\n        attr_key : str\n            The attribute name.\n\n        attr_value : object\n            The attribute value.\n\n        Examples\n        --------\n        .. code-block:: python\n\n        # Temporarily update FTVMAlterOpLayout to a user-defined packed function.\n        # After the test is finished, the attr value will be set back to the original value.\n\n        with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n            my_mod = relay.transform.AlterOpLayout()(my_mod)\n\n        \"\"\"\n        self.op = relay.op.get(op_name)\n        self.attr_key = attr_key\n        self.attr_value = attr_value\n\n    def __enter__(self):\n        self.older_attr = self.op.get_attr(self.attr_key)\n        self.op.reset_attr(self.attr_key)\n        self.op.set_attr(self.attr_key, self.attr_value)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        self.op.reset_attr(self.attr_key)\n        if self.older_attr:\n            self.op.set_attr(self.attr_key, self.older_attr)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/tf.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, no-init, import-outside-toplevel\n\"\"\"\nTensorflow Model Helpers\n========================\nSome helper definitions for tensorflow models.\n\"\"\"\nimport re\nimport os.path\nimport collections\nimport numpy as np\n\n# Tensorflow imports\nimport tensorflow as tf\nfrom tensorflow.core.framework import graph_pb2\n\nimport tvm\nfrom tvm.contrib.download import download_testdata\n\ntry:\n    tf_compat_v1 = tf.compat.v1\nexcept (ImportError, AttributeError):\n    tf_compat_v1 = tf\n\n######################################################################\n# Some helper functions\n# ---------------------\n\n\ndef ProcessGraphDefParam(graph_def):\n    \"\"\"Type-checks and possibly canonicalizes `graph_def`.\n\n    Parameters\n    ----------\n    graph_def : Obj\n        tensorflow graph definition.\n\n    Returns\n    -------\n    graph_def : Obj\n        tensorflow graph definition\n\n    \"\"\"\n\n    if not isinstance(graph_def, graph_pb2.GraphDef):\n        # `graph_def` could be a dynamically-created message, so try a duck-typed\n        # approach\n        try:\n            old_graph_def = graph_def\n            graph_def = graph_pb2.GraphDef()\n            graph_def.MergeFrom(old_graph_def)\n        except TypeError:\n            raise TypeError(\"graph_def must be a GraphDef proto.\")\n    return graph_def\n\n\ndef convert_to_list(x):\n    if not isinstance(x, list):\n        x = [x]\n    return x\n\n\ndef vmobj_to_list(o):\n    \"\"\"Converts TVM objects returned by VM execution to Python List.\n\n    Parameters\n    ----------\n    o : Obj\n        VM Object as output from VM runtime executor.\n\n    Returns\n    -------\n    result : list\n        Numpy objects as list with equivalent values to the input object.\n\n    \"\"\"\n\n    if isinstance(o, tvm.nd.NDArray):\n        result = [o.numpy()]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(f))\n    elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):\n        if o.constructor.name_hint == \"Cons\":\n            tl = vmobj_to_list(o.fields[1])\n            hd = vmobj_to_list(o.fields[0])\n            hd.extend(tl)\n            result = hd\n        elif o.constructor.name_hint == \"Nil\":\n            result = []\n        elif \"tensor_nil\" in o.constructor.name_hint:\n            result = [0]\n        elif \"tensor\" in o.constructor.name_hint:\n            result = [o.fields[0].numpy()]\n        else:\n            raise RuntimeError(\"Unknown object type: %s\" % o.constructor.name_hint)\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n    return result\n\n\ndef AddShapesToGraphDef(session, out_node):\n    \"\"\"Add shapes attribute to nodes of the graph.\n        Input graph here is the default graph in context.\n\n    Parameters\n    ----------\n    session : tf.Session\n        Tensorflow session\n    out_node : String or List\n        Final output node of the graph.\n\n    Returns\n    -------\n    graph_def : Obj\n        tensorflow graph definition with shapes attribute added to nodes.\n\n    \"\"\"\n\n    graph_def = tf_compat_v1.graph_util.convert_variables_to_constants(\n        session,\n        session.graph.as_graph_def(add_shapes=True),\n        convert_to_list(out_node),\n    )\n    return graph_def\n\n\nclass NodeLookup(object):\n    \"\"\"Converts integer node ID's to human readable labels.\"\"\"\n\n    def __init__(self, label_lookup_path=None, uid_lookup_path=None):\n        self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\n\n    def load(self, label_lookup_path, uid_lookup_path):\n        \"\"\"Loads a human readable English name for each softmax node.\n\n        Parameters\n        ----------\n        label_lookup_path: String\n            File containing String UID to integer node ID mapping .\n\n        uid_lookup_path: String\n            File containing String UID to human-readable string mapping.\n\n        Returns\n        -------\n        node_id_to_name: dict\n            dict from integer node ID to human-readable string.\n\n        \"\"\"\n        if not tf_compat_v1.gfile.Exists(uid_lookup_path):\n            tf.logging.fatal(\"File does not exist %s\", uid_lookup_path)\n        if not tf_compat_v1.gfile.Exists(label_lookup_path):\n            tf.logging.fatal(\"File does not exist %s\", label_lookup_path)\n\n        # Loads mapping from string UID to human-readable string\n        proto_as_ascii_lines = tf_compat_v1.gfile.GFile(uid_lookup_path).readlines()\n        uid_to_human = {}\n        p = re.compile(r\"[n\\d]*[ \\S,]*\")\n        for line in proto_as_ascii_lines:\n            parsed_items = p.findall(line)\n            uid = parsed_items[0]\n            human_string = parsed_items[2]\n            uid_to_human[uid] = human_string\n\n        # Loads mapping from string UID to integer node ID.\n        node_id_to_uid = {}\n        proto_as_ascii = tf_compat_v1.gfile.GFile(label_lookup_path).readlines()\n        for line in proto_as_ascii:\n            if line.startswith(\"  target_class:\"):\n                target_class = int(line.split(\": \")[1])\n            if line.startswith(\"  target_class_string:\"):\n                target_class_string = line.split(\": \")[1]\n                node_id_to_uid[target_class] = target_class_string[1:-2]\n\n        # Loads the final mapping of integer node ID to human-readable string\n        node_id_to_name = {}\n        for key, val in node_id_to_uid.items():\n            if val not in uid_to_human:\n                tf.logging.fatal(\"Failed to locate: %s\", val)\n            name = uid_to_human[val]\n            node_id_to_name[key] = name\n\n        return node_id_to_name\n\n    def id_to_string(self, node_id):\n        if node_id not in self.node_lookup:\n            return \"\"\n        return self.node_lookup[node_id]\n\n\ndef get_workload_official(model_url, model_sub_path, retries=5):\n    \"\"\"Import workload from tensorflow official\n\n    Parameters\n    ----------\n    model_url: str\n        URL from where it will be downloaded.\n\n    model_sub_path:\n        Sub path in extracted tar for the ftozen protobuf file.\n\n    retries: int\n        The number of retries to attempt downloading and uncompressing\n        the model in the CI, due to possible network and CI node issues.\n\n    Returns\n    -------\n    model_path: str\n        Full path to saved model file\n\n    \"\"\"\n    attempts = retries + 1\n    error = None\n    for current_attempt_idx in range(attempts):\n        try:\n            model_tar_name = os.path.basename(model_url)\n            model_path = download_testdata(model_url, model_tar_name, module=[\"tf\", \"official\"])\n            dir_path = os.path.dirname(model_path)\n\n            if model_path.endswith(\"tgz\") or model_path.endswith(\"gz\"):\n                import tarfile\n\n                tar = tarfile.open(model_path)\n                tar.extractall(path=dir_path)\n                tar.close()\n            elif model_path.endswith(\"zip\"):\n                import zipfile\n\n                zip_object = zipfile.ZipFile(model_path)\n                zip_object.extractall(path=dir_path)\n                zip_object.close()\n            else:\n                raise RuntimeError(\"Could not decompress the file: \" + model_path)\n            return os.path.join(dir_path, model_sub_path)\n        except (EOFError, RuntimeError) as err:\n            error = err\n            print(f\"Raised : {str(error)}, current attempt : {current_attempt_idx} ...\")\n    raise error\n\n\ndef get_workload(model_path, model_sub_path=None, inputs_dict=None, output=None):\n    \"\"\"Import workload from frozen protobuf\n\n    Parameters\n    ----------\n    model_path: str\n        model_path on remote repository to download from.\n\n    model_sub_path: str\n        Model path in the compressed archive.\n\n    Returns\n    -------\n    graph_def: graphdef\n        graph_def is the tensorflow workload.\n\n    \"\"\"\n\n    if model_sub_path:\n        path_model = get_workload_official(model_path, model_sub_path)\n    else:\n        repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/\"\n        model_url = os.path.join(repo_base, model_path)\n        path_model = download_testdata(model_url, model_path, module=\"tf\")\n\n    # Creates graph from saved graph_def.pb.\n    with tf_compat_v1.gfile.FastGFile(path_model, \"rb\") as f:\n        graph_def = tf_compat_v1.GraphDef()\n        graph_def.ParseFromString(f.read())\n        graph = tf_compat_v1.import_graph_def(graph_def, name=\"\", input_map=inputs_dict)\n\n    if inputs_dict is not None:\n        # graph is changed so generate graph_def again\n        with tf_compat_v1.Session(graph=graph) as sess:\n            graph_def = AddShapesToGraphDef(sess, output)\n\n    return graph_def\n\n\n#######################################################################\n# PTB LSTMBlockCell Model\n# -----------------------\n\n\nclass PTBSmallConfig(object):\n    \"\"\"Small config.\n    This configurations are used when training the model\n    \"\"\"\n\n    num_layers = 2\n    num_steps = 1\n    hidden_size = 200\n    batch_size = 1\n    vocab_size = 10000\n    init_scale = 0.1\n\n\ndef get_config():\n    \"\"\"Configuration used for training the model\"\"\"\n    return PTBSmallConfig()\n\n\ndef pick_from_weight(weight, pows=1.0):\n    \"\"\"Identify token from Softmax output.\n    This token will be mapped to word in the vocabulary.\n    \"\"\"\n    weight = weight**pows\n    t = np.cumsum(weight)\n    s = np.sum(weight)\n    return int(np.searchsorted(t, 0.5 * s))\n\n\ndef do_tf_sample(session, data, in_states, num_samples):\n    \"\"\"Sampled from the model\"\"\"\n    samples = []\n    sample = None\n    # Cell inputs c and h should be passed for each layer explicitly.\n    state_input_name = [\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros_1:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros_1:0\",\n    ]\n    state = in_states\n\n    # Graph nodes to be fetched as run output. Tensorflow LSTMBlockCell create internal\n    # nodes for intermediate operations (gates) in the cell during run.\n    # Cell state (c) is ':1'and cell output (h) is ':6' for each layer.\n    fetches = [\n        [\n            \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell:1\",\n            \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell:6\",\n            \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_1:1\",\n            \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_1:6\",\n        ],\n        \"Model/Softmax:0\",\n    ]\n\n    def _get_feed_dict(input_name, input_data):\n        \"\"\"Create feed dict\"\"\"\n        feed_dict = {}\n        if isinstance(input_data, list):\n            for i, e in enumerate(input_name):\n                feed_dict[e] = input_data[i]\n        else:\n            feed_dict[input_name] = input_data\n        return feed_dict\n\n    for x in data:\n        feed_dict = _get_feed_dict(state_input_name, state)\n        feed_dict[\"Model/Placeholder:0\"] = [[x]]\n        state, probs = session.run(fetches, feed_dict)\n        sample = pick_from_weight(probs[0])\n    if sample is not None:\n        samples.append(sample)\n    else:\n        samples.append(0)\n\n    k = 1\n    while k < num_samples:\n        feed_dict = _get_feed_dict(state_input_name, state)\n        feed_dict[\"Model/Placeholder:0\"] = [[samples[-1]]]\n        state, probs = session.run(fetches, feed_dict)\n        sample = pick_from_weight(probs[0])\n        samples.append(sample)\n        k += 1\n    return samples, state\n\n\ndef _create_ptb_vocabulary(data_dir):\n    \"\"\"Read the PTB sample data input to create vocabulary\"\"\"\n    data_path = os.path.join(data_dir, \"simple-examples/data/\")\n    file_name = \"ptb.train.txt\"\n\n    def _read_words(filename):\n        \"\"\"Read the data for creating vocabulary\"\"\"\n        with tf_compat_v1.gfile.GFile(filename, \"r\") as f:\n            return f.read().encode(\"utf-8\").decode(\"utf-8\").replace(\"\\n\", \"<eos>\").split()\n\n    def _build_vocab(filename):\n        \"\"\"Create vocabulary\"\"\"\n        data = _read_words(filename)\n        counter = collections.Counter(data)\n        count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))\n        words, _ = list(zip(*count_pairs))\n        word_to_id = dict(zip(words, range(len(words))))\n        # for python 3.x\n        id_to_word = dict((v, k) for k, v in word_to_id.items())\n        return word_to_id, id_to_word\n\n    def ptb_raw_data(data_path, file_name):\n        \"\"\"Read the sample data and create vocabulary\"\"\"\n        train_path = os.path.join(data_path, file_name)\n        word_to_id, id_2_word = _build_vocab(train_path)\n        return word_to_id, id_2_word\n\n    return ptb_raw_data(data_path, file_name)\n\n\ndef get_workload_ptb():\n    \"\"\"Import ptb workload from frozen protobuf\n\n    Parameters\n    ----------\n        Nothing.\n\n    Returns\n    -------\n    graph_def: graphdef\n        graph_def is the tensorflow workload for ptb.\n\n    word_to_id : dict\n        English word to integer id mapping\n\n    id_to_word : dict\n        Integer id to English word mapping\n    \"\"\"\n    sample_repo = \"http://www.fit.vutbr.cz/~imikolov/rnnlm/\"\n    sample_data_file = \"simple-examples.tgz\"\n    sample_url = sample_repo + sample_data_file\n    ptb_model_file = \"RNN/ptb/ptb_model_with_lstmblockcell.pb\"\n    # pylint: disable=import-outside-toplevel\n    import tarfile\n\n    file_path = download_testdata(sample_url, sample_data_file, module=[\"data\", \"ptb_data\"])\n    dir_path = os.path.dirname(file_path)\n    t = tarfile.open(file_path, \"r\")\n    t.extractall(dir_path)\n\n    word_to_id, id_to_word = _create_ptb_vocabulary(dir_path)\n    dtype = \"float32\"\n    shape = (1, 200)\n\n    # Convert states of LSTMBlockCell to placeholder, so TVM can feed data\n    state_name = [\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros_1:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros:0\",\n        \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros_1:0\",\n    ]\n\n    inputs_dict = {\n        state_name[0]: tf_compat_v1.placeholder(dtype, shape, state_name[0].split(\":\")[0]),\n        state_name[1]: tf_compat_v1.placeholder(dtype, shape, state_name[1].split(\":\")[0]),\n        state_name[2]: tf_compat_v1.placeholder(dtype, shape, state_name[2].split(\":\")[0]),\n        state_name[3]: tf_compat_v1.placeholder(dtype, shape, state_name[3].split(\":\")[0]),\n    }\n    return (\n        word_to_id,\n        id_to_word,\n        get_workload(ptb_model_file, inputs_dict=inputs_dict, output=\"Model/Softmax\"),\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/tflite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common utilities for creating TFLite models\"\"\"\nfrom distutils.version import LooseVersion\nimport numpy as np\nimport pytest\nimport tvm\n\npytest.importorskip(\"tflite\")\npytest.importorskip(\"tensorflow\")\nimport tflite.Model  # pylint: disable=wrong-import-position\nimport tensorflow as tf  # pylint: disable=wrong-import-position\n\n\nclass TFLiteModel:\n    \"\"\"Creates TFLite Model and facilitates reference data generation\"\"\"\n\n    def __init__(self, dtype):\n        self.serial_model = None  # This is what TFLite convert() provides\n        self.dtype = dtype  # This is the dtype of graph inputs\n        self.shape_dict = {}\n        self.dtype_dict = {}\n\n    def create_conv2d_single(self, kernel_shape, strides, padding, dilation, activation):\n        \"\"\"Returns tf.function that creates TFLite Conv2d layer\"\"\"\n\n        @tf.function\n        def conv2d_single_function(ifm_tensor):\n            \"\"\"Returns TFLite Conv2d layer\"\"\"\n            op = tf.nn.conv2d(\n                ifm_tensor,\n                filters=tf.constant(\n                    np.random.uniform(size=[kernel_shape[0], kernel_shape[1], 3, 3]),\n                    dtype=tf.float32,\n                ),\n                strides=[1, strides[0], strides[1], 1],\n                padding=padding,\n                dilations=dilation,\n            )\n            if activation == \"RELU\":\n                op = tf.nn.relu(op)\n            elif activation == \"NONE\":\n                pass\n            else:\n                assert False, \"Unsupported activation {}\".format(activation)\n            return op\n\n        return conv2d_single_function\n\n    def create_tflite_model(self, tfl_function, shapes, ranges=None):\n        \"\"\"Creates TFLite serial graph\"\"\"\n        tensor_specs = []\n        for i, shape in enumerate(shapes):\n            input_name = \"input_\" + str(i)\n            self.shape_dict.update({input_name: shape})\n            self.dtype_dict.update({input_name: self.dtype})\n            tensor_specs.append(tf.TensorSpec(shape, dtype=tf.float32, name=input_name))\n        concrete_func = tfl_function.get_concrete_function(*tensor_specs)\n\n        if not ranges:\n            ranges = [(0, 1) for _ in shapes]\n\n        def representative_dataset():\n            for _ in range(100):\n                inputs = []\n                for i, shape in enumerate(shapes):\n                    data = np.random.uniform(\n                        low=ranges[i][0], high=ranges[i][1], size=tuple(shape)\n                    ).astype(\"float32\")\n                    inputs.append(data)\n\n                yield inputs\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        self.serial_model = converter.convert()\n\n    def convert_to_relay(self):\n        \"\"\"Converts TFLite serialized graph into Relay\"\"\"\n        assert self.serial_model is not None, \"TFLite model is empty!\"\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(self.serial_model, 0)\n        relay_module, relay_params = tvm.relay.frontend.from_tflite(\n            tflite_model, self.shape_dict, self.dtype_dict\n        )\n        return relay_module, relay_params\n\n    def generate_randomized_input_data(self, seed, shape, dtype):\n        \"\"\"Generates randomized input numpy arrays based on shape and dtype.\"\"\"\n        random_state = np.random.RandomState(seed)\n        random_data = None\n        if dtype == np.float32:\n            random_data = random_state.uniform(-1, 1, size).astype(dtype)\n        else:\n            low = np.iinfo(dtype).min\n            high = np.iinfo(dtype).max + 1\n            random_data = random_state.randint(low, high, shape, dtype)\n        return random_data\n\n    # pylint: disable=import-outside-toplevel\n    def generate_reference_data(self):\n        \"\"\"\n        This method uses TFLite reference kernels to generate reference output.\n        It returns randomized inputs and reference outputs.\n        \"\"\"\n        assert self.serial_model is not None, \"TFLite model was not created.\"\n\n        output_tolerance = None\n        if tf.__version__ < LooseVersion(\"2.5.0\"):\n            output_tolerance = 1\n            interpreter = tf.lite.Interpreter(model_content=self.serial_model)\n        else:\n            output_tolerance = 0\n            interpreter = tf.lite.Interpreter(\n                model_content=self.serial_model,\n                experimental_op_resolver_type=tf.lite.experimental.OpResolverType.BUILTIN_REF,\n                experimental_preserve_all_tensors=False,\n            )\n\n        interpreter.allocate_tensors()\n        input_details = interpreter.get_input_details()\n        output_details = interpreter.get_output_details()\n\n        # Generate predictable randomized input\n        seed = 0\n        input_data = {}\n        for input_detail in input_details:\n            input_values = self.generate_randomized_input_data(\n                seed, input_detail[\"shape\"], input_detail[\"dtype\"]\n            )\n            interpreter.set_tensor(input_detail[\"index\"], input_values)\n            input_data.update({input_detail[\"name\"]: input_values})\n\n        interpreter.invoke()\n\n        # Obtain the expected output from interpreter\n        expected_output_data = {}\n        for output_detail in output_details:\n            expected_output_data.update(\n                {output_detail[\"name\"]: interpreter.get_tensor(output_detail[\"index\"])}\n            )\n\n        return input_data, expected_output_data, output_tolerance\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/vgg.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"References:\n\nSimonyan, Karen, and Andrew Zisserman. \"Very deep convolutional networks for\nlarge-scale image recognition.\" arXiv preprint arXiv:1409.1556 (2014).\n\"\"\"\nfrom tvm import relay\nfrom .init import create_workload\nfrom . import layers as wrapper\n\n\ndef get_feature(internal_layer, layers, filters, batch_norm=False):\n    \"\"\"Get VGG feature body as stacks of convolutions.\"\"\"\n    for i, num in enumerate(layers):\n        for j in range(num):\n            internal_layer = wrapper.conv2d(\n                data=internal_layer,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                channels=filters[i],\n                name=\"conv%s_%s\" % (i + 1, j + 1),\n            )\n            internal_layer = relay.nn.bias_add(\n                internal_layer, relay.var(\"conv%s_%s_bias\" % (i + 1, j + 1))\n            )\n            if batch_norm:\n                internal_layer = wrapper.batch_norm_infer(\n                    data=internal_layer, name=\"bn%s_%s\" % (i + 1, j + 1)\n                )\n            internal_layer = relay.nn.relu(data=internal_layer)\n        internal_layer = relay.nn.max_pool2d(data=internal_layer, pool_size=(2, 2), strides=(2, 2))\n    return internal_layer\n\n\ndef get_classifier(input_data, num_classes):\n    \"\"\"Get VGG classifier layers as fc layers.\"\"\"\n    flatten = relay.nn.batch_flatten(data=input_data)\n    fc6 = wrapper.dense_add_bias(data=flatten, units=4096, name=\"fc6\")\n    relu6 = relay.nn.relu(data=fc6)\n    drop6 = relay.nn.dropout(data=relu6, rate=0.5)\n    fc7 = wrapper.dense_add_bias(data=drop6, units=4096, name=\"fc7\")\n    relu7 = relay.nn.relu(data=fc7)\n    drop7 = relay.nn.dropout(data=relu7, rate=0.5)\n    fc8 = wrapper.dense_add_bias(data=drop7, units=num_classes, name=\"fc8\")\n    return fc8\n\n\ndef get_net(batch_size, image_shape, num_classes, dtype, num_layers=11, batch_norm=False):\n    \"\"\"\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    image_shape : tuple, optional\n        The input image shape\n\n    num_classes : int, optional\n        Number of claseses\n\n    dtype : str, optional\n        The data type\n\n    num_layers : int\n        Number of layers for the variant of vgg. Options are 11, 13, 16, 19.\n\n    batch_norm : bool, default False\n        Use batch normalization.\n    \"\"\"\n    vgg_spec = {\n        11: ([1, 1, 2, 2, 2], [64, 128, 256, 512, 512]),\n        13: ([2, 2, 2, 2, 2], [64, 128, 256, 512, 512]),\n        16: ([2, 2, 3, 3, 3], [64, 128, 256, 512, 512]),\n        19: ([2, 2, 4, 4, 4], [64, 128, 256, 512, 512]),\n    }\n    if num_layers not in vgg_spec:\n        raise ValueError(\"Invalide num_layers {}. Choices are 11,13,16,19.\".format(num_layers))\n    layers, filters = vgg_spec[num_layers]\n    data_shape = (batch_size,) + image_shape\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    feature = get_feature(data, layers, filters, batch_norm)\n    classifier = get_classifier(feature, num_classes)\n    symbol = relay.nn.softmax(data=classifier)\n    args = relay.analysis.free_vars(symbol)\n    return relay.Function(args, symbol)\n\n\ndef get_workload(\n    batch_size,\n    num_classes=1000,\n    image_shape=(3, 224, 224),\n    dtype=\"float32\",\n    num_layers=11,\n    batch_norm=False,\n):\n    \"\"\"Get benchmark workload for VGG nets.\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of claseses\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    num_layers : int\n        Number of layers for the variant of vgg. Options are 11, 13, 16, 19.\n\n    batch_norm : bool\n        Use batch normalization.\n\n    Returns\n    -------\n    mod : tvm.IRModule\n        The relay module that contains a VGG network.\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n    net = get_net(batch_size, image_shape, num_classes, dtype, num_layers, batch_norm)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/testing/yolo_detection.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, no-init,\n\"\"\"\nYolo detection boxes helper functions\n====================\nDarkNet helper functions for yolo and image loading.\nThis functions will not be loaded by default.\nThese are utility functions used for testing and tutorial file.\n\"\"\"\nfrom __future__ import division\nimport math\nfrom collections import namedtuple\nfrom functools import cmp_to_key\nimport numpy as np\n\nBox = namedtuple(\"Box\", [\"x\", \"y\", \"w\", \"h\"])\n\n\ndef nms_comparator(a, b):\n    if \"sort_class\" in b and b[\"sort_class\"] >= 0:\n        diff = a[\"prob\"][b[\"sort_class\"]] - b[\"prob\"][b[\"sort_class\"]]\n    else:\n        diff = a[\"objectness\"] - b[\"objectness\"]\n    return diff\n\n\ndef _correct_boxes(dets, w, h, netw, neth, relative):\n    new_w, new_h = (netw, (h * netw) // w) if (netw / w < neth / h) else ((w * neth // h), neth)\n    for det in dets:\n        b = det[\"bbox\"]\n        b = b._replace(x=(b.x - (netw - new_w) / 2 / netw) / (new_w / netw))\n        b = b._replace(y=(b.y - (neth - new_h) / 2 / neth) / (new_h / neth))\n        b = b._replace(w=b.w * netw / new_w)\n        b = b._replace(h=b.h * neth / new_h)\n        if not relative:\n            b = b._replace(x=b.x * w)\n            b = b._replace(w=b.w * w)\n            b = b._replace(y=b.y * h)\n            b = b._replace(h=b.h * h)\n        det[\"bbox\"] = b\n    return dets\n\n\ndef _overlap(x1, w1, x2, w2):\n    l1 = x1 - w1 / 2\n    l2 = x2 - w2 / 2\n    left = l1 if l1 > l2 else l2\n    r1 = x1 + w1 / 2\n    r2 = x2 + w2 / 2\n    right = r1 if r1 < r2 else r2\n    return right - left\n\n\ndef _box_intersection(a, b):\n    w = _overlap(a.x, a.w, b.x, b.w)\n    h = _overlap(a.y, a.h, b.y, b.h)\n    if w < 0 or h < 0:\n        return 0\n    return w * h\n\n\ndef _box_union(a, b):\n    i = _box_intersection(a, b)\n    u = a.w * a.h + b.w * b.h - i\n    return u\n\n\ndef _box_iou(a, b):\n    return _box_intersection(a, b) / _box_union(a, b)\n\n\ndef _get_box(data, biases, n, location, lw, lh, w, h):\n    bx = (location[2] + data[location[0]][0][location[1]][location[2]]) / lw\n    by = (location[1] + data[location[0]][1][location[1]][location[2]]) / lh\n    bw = np.exp(data[location[0]][2][location[1]][location[2]]) * biases[2 * n] / w\n    bh = np.exp(data[location[0]][3][location[1]][location[2]]) * biases[2 * n + 1] / h\n    return Box(bx, by, bw, bh)\n\n\ndef _get_yolo_detections(l, im_shape, net_shape, thresh, relative, dets):\n    data = l[\"output\"]\n    active_data_loc = np.asarray(np.where(data[:, 4, :, :] > thresh))\n    before_correct_dets = []\n    for i in range(active_data_loc.shape[1]):\n        location = [active_data_loc[0][i], active_data_loc[1][i], active_data_loc[2][i]]\n        box_b = _get_box(\n            data,\n            l[\"biases\"],\n            np.asarray(l[\"mask\"])[location[0]],\n            location,\n            data.shape[3],\n            data.shape[2],\n            net_shape[0],\n            net_shape[1],\n        )\n        objectness = data[location[0]][4][location[1]][location[2]]\n        classes = l[\"classes\"]\n        prob = objectness * data[location[0], 5 : 5 + 1 + classes, location[1], location[2]]\n        prob[prob < thresh] = 0\n        detection = {}\n        detection[\"bbox\"] = box_b\n        detection[\"classes\"] = classes\n        detection[\"prob\"] = prob\n        detection[\"objectness\"] = objectness\n        before_correct_dets.append(detection)\n    dets.extend(\n        _correct_boxes(\n            before_correct_dets, im_shape[0], im_shape[1], net_shape[0], net_shape[1], relative\n        )\n    )\n\n\ndef _get_region_detections(l, im_shape, net_shape, thresh, relative, dets):\n    data = l[\"output\"]\n    before_correct_dets = []\n    for row in range(data.shape[2]):\n        for col in range(data.shape[3]):\n            for n in range(data.shape[0]):\n                prob = [0] * l[\"classes\"]\n                scale = data[n, l[\"coords\"], row, col] if not l[\"background\"] else 1\n                location = [n, row, col]\n                box_b = _get_box(\n                    data,\n                    l[\"biases\"],\n                    n,\n                    location,\n                    data.shape[3],\n                    data.shape[2],\n                    data.shape[3],\n                    data.shape[2],\n                )\n                objectness = scale if scale > thresh else 0\n                if objectness:\n                    prob = (\n                        scale * data[n, l[\"coords\"] + 1 : l[\"coords\"] + 1 + l[\"classes\"], row, col]\n                    )\n                    prob[prob < thresh] = 0\n                detection = {}\n                detection[\"bbox\"] = box_b\n                detection[\"prob\"] = prob\n                detection[\"objectness\"] = objectness\n                before_correct_dets.append(detection)\n    _correct_boxes(\n        before_correct_dets, im_shape[0], im_shape[1], net_shape[0], net_shape[1], relative\n    )\n    dets.extend(before_correct_dets)\n\n\ndef fill_network_boxes(net_shape, im_shape, thresh, relative, tvm_out):\n    dets = []\n    for layer in tvm_out:\n        if layer[\"type\"] == \"Yolo\":\n            _get_yolo_detections(layer, im_shape, net_shape, thresh, relative, dets)\n        elif layer[\"type\"] == \"Region\":\n            _get_region_detections(layer, im_shape, net_shape, thresh, relative, dets)\n    return dets\n\n\ndef do_nms_sort(dets, classes, thresh):\n    \"Does the sorting based on the threshold values\"\n    k = len(dets) - 1\n    cnt = 0\n    while cnt < k:\n        if dets[cnt][\"objectness\"] == 0:\n            dets[k], dets[cnt] = dets[cnt], dets[k]\n            k = k - 1\n        else:\n            cnt = cnt + 1\n    total = k + 1\n    for k in range(classes):\n        for i in range(total):\n            dets[i][\"sort_class\"] = k\n        dets[0:total] = sorted(dets[0:total], key=cmp_to_key(nms_comparator), reverse=True)\n        for i in range(total):\n            if dets[i][\"prob\"][k] == 0:\n                continue\n            a = dets[i][\"bbox\"]\n            for j in range(i + 1, total):\n                b = dets[j][\"bbox\"]\n                if _box_iou(a, b) > thresh:\n                    dets[j][\"prob\"][k] = 0\n\n\ndef get_detections(im, det, thresh, names, classes):\n    \"Draw the markings around the detected region\"\n    labelstr = []\n    category = -1\n    detection = None\n    valid = False\n    for j in range(classes):\n        if det[\"prob\"][j] > thresh:\n            if category == -1:\n                category = j\n            labelstr.append(names[j] + \" \" + str(round(det[\"prob\"][j], 4)))\n\n    if category > -1:\n        valid = True\n        imc, imh, imw = im.shape\n        width = int(imh * 0.006)\n        offset = category * 123457 % classes\n        red = _get_color(2, offset, classes)\n        green = _get_color(1, offset, classes)\n        blue = _get_color(0, offset, classes)\n        rgb = [red, green, blue]\n        b = det[\"bbox\"]\n        left = int((b.x - b.w / 2.0) * imw)\n        right = int((b.x + b.w / 2.0) * imw)\n        top = int((b.y - b.h / 2.0) * imh)\n        bot = int((b.y + b.h / 2.0) * imh)\n\n        if left < 0:\n            left = 0\n        if right > imw - 1:\n            right = imw - 1\n        if top < 0:\n            top = 0\n        if bot > imh - 1:\n            bot = imh - 1\n\n        detection = {\n            \"category\": category,\n            \"labelstr\": labelstr,\n            \"left\": left,\n            \"top\": top,\n            \"right\": right,\n            \"bot\": bot,\n            \"width\": width,\n            \"rgb\": rgb,\n        }\n\n    return valid, detection\n\n\ndef draw_detections(font_path, im, dets, thresh, names, classes):\n    \"Draw the markings around the detected region\"\n    for det in dets:\n        valid, detection = get_detections(im, det, thresh, names, classes)\n        if valid:\n            rgb = detection[\"rgb\"]\n            label = _get_label(font_path, \"\".join(detection[\"labelstr\"]), rgb)\n            _draw_box_width(\n                im,\n                detection[\"left\"],\n                detection[\"top\"],\n                detection[\"right\"],\n                detection[\"bot\"],\n                detection[\"width\"],\n                rgb[0],\n                rgb[1],\n                rgb[2],\n            )\n            _draw_label(im, detection[\"top\"] + detection[\"width\"], detection[\"left\"], label, rgb)\n\n\ndef show_detections(im, dets, thresh, names, classes):\n    \"Print the markings and the detected region\"\n    for det in dets:\n        valid, detection = get_detections(im, det, thresh, names, classes)\n        if valid:\n            print(\n                \"class:{} left:{} top:{} right:{} bottom:{}\".format(\n                    detection[\"labelstr\"],\n                    detection[\"left\"],\n                    detection[\"top\"],\n                    detection[\"right\"],\n                    detection[\"bot\"],\n                )\n            )\n\n\ndef _get_pixel(im, x, y, c):\n    return im[c][y][x]\n\n\ndef _set_pixel(im, x, y, c, val):\n    if x < 0 or y < 0 or c < 0 or x >= im.shape[2] or y >= im.shape[1] or c >= im.shape[0]:\n        return\n    im[c][y][x] = val\n\n\ndef _draw_label(im, r, c, label, rgb):\n    w = label.shape[2]\n    h = label.shape[1]\n    if (r - h) >= 0:\n        r = r - h\n\n    for j in range(h):\n        if j < h and (j + r) < im.shape[1]:\n            for i in range(w):\n                if i < w and (i + c) < im.shape[2]:\n                    for k in range(label.shape[0]):\n                        val = _get_pixel(label, i, j, k)\n                        _set_pixel(im, i + c, j + r, k, val)  # rgb[k] * val)\n\n\ndef _get_label(font_path, labelstr, rgb):\n    # pylint: disable=import-outside-toplevel\n    from PIL import Image\n    from PIL import ImageDraw\n    from PIL import ImageFont\n\n    text = labelstr\n    colorText = \"black\"\n    testDraw = ImageDraw.Draw(Image.new(\"RGB\", (1, 1)))\n    font = ImageFont.truetype(font_path, 25)\n    width, height = testDraw.textsize(labelstr, font=font)\n    img = Image.new(\n        \"RGB\", (width, height), color=(int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))\n    )\n    d = ImageDraw.Draw(img)\n    d.text((0, 0), text, fill=colorText, font=font)\n    opencvImage = np.divide(np.asarray(img), 255)\n    return opencvImage.transpose(2, 0, 1)\n\n\ndef _get_color(c, x, max_value):\n    c = int(c)\n    colors = [[1, 0, 1], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 0, 0]]\n    ratio = (float(x) / float(max_value)) * 5\n    i = int(math.floor(ratio))\n    j = int(math.ceil(ratio))\n    ratio -= i\n    r = (1 - ratio) * colors[i][c] + ratio * colors[j][c]\n    return r\n\n\ndef _draw_box(im, x1, y1, x2, y2, r, g, b):\n    y1 = int(y1)\n    y2 = int(y2)\n    x1 = int(x1)\n    x2 = int(x2)\n    ac, ah, aw = im.shape\n    if x1 < 0:\n        x1 = 0\n    if x1 >= aw:\n        y1 = 0\n    if y1 >= ah:\n        y1 = ah - 1\n    if y2 < 0:\n        y2 = 0\n    if y2 >= ah:\n        y2 = ah - 1\n\n    for i in range(x1, x2):\n        im[0][y1][i] = r\n        im[0][y2][i] = r\n        im[1][y1][i] = g\n        im[1][y2][i] = g\n        im[2][y1][i] = b\n        im[2][y2][i] = b\n\n    for i in range(y1, y2):\n        im[0][i][x1] = r\n        im[0][i][x2] = r\n        im[1][i][x1] = g\n        im[1][i][x2] = g\n        im[2][i][x1] = b\n        im[2][i][x2] = b\n\n\ndef _draw_box_width(im, x1, y1, x2, y2, w, r, g, b):\n    for i in range(int(w)):\n        _draw_box(im, x1 + i, y1 + i, x2 - i, y2 - i, r, g, b)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import, redefined-builtin, invalid-name\n\"\"\"The Relay IR namespace containing transformations.\"\"\"\n# transformation passes\nfrom .transform import *\nfrom .recast import recast\nfrom . import fake_quantization_to_integer, mixed_precision\nfrom .flexible_shape import FlexibleShapeDispatch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for Relay transformation passes.\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay._transform\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/fake_quantization_to_integer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Relay functions for rewriting fake quantized ops.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import TensorAffineType, TupleAffineType\n\n# import to register canonicalization funcs for fq2i\n# pylint: disable=unused-import\nfrom tvm.relay.qnn.op import canonicalizations\nfrom tvm.tir import bijective_layout\n\nfrom ..op import register_fake_quantization_to_integer\n\n\ndef fold_constant(expr):\n    return relay.transform.FoldConstantExpr(expr, tvm.IRModule())\n\n\ndef get_zeros(scale):\n    return fold_constant(relay.op.cast(relay.op.zeros_like(scale), \"int32\"))\n\n\ndef infer_shape(expr):\n    return relay.transform.InferType()(tvm.IRModule.from_expr(expr))[\"main\"].body.checked_type.shape\n\n\ndef approx_equal(x, y):\n    x = fold_constant(x)\n    y = fold_constant(y)\n    if isinstance(x, relay.Constant) and isinstance(y, relay.Constant):\n        equal = np.allclose(x.data.asnumpy(), y.data.asnumpy())\n    else:\n        equal = tvm.ir.structural_equal(x, y)\n    return equal\n\n\n@register_fake_quantization_to_integer(\"qnn.dequantize\")\ndef dequantize(expr, type_map):\n    \"\"\"Remove dequantize op\"\"\"\n    out = expr.args[0]\n    t = type_map[expr]\n    return [out, t]\n\n\n@register_fake_quantization_to_integer(\"qnn.quantize\")\ndef quantize(expr, type_map):\n    \"\"\"Turn a quantize op into requantize or remove it\"\"\"\n    out = expr.args[0]\n    t = type_map[out]\n    in_scale = fold_constant(t.scale)\n    in_zero_point = fold_constant(t.zero_point)\n    if not (\n        approx_equal(in_scale, expr.args[1])\n        and approx_equal(in_zero_point, expr.args[2])\n        and tvm.ir.structural_equal(t.dtype, expr.attrs.out_dtype)\n    ):\n        out = relay.qnn.op.requantize(\n            out,\n            in_scale,\n            in_zero_point,\n            expr.args[1],\n            expr.args[2],\n            out_dtype=expr.attrs.out_dtype,\n            axis=t.axis,\n        )\n    return [\n        out,\n        TensorAffineType(expr.args[1], expr.args[2], expr.attrs.out_dtype, expr.attrs.axis),\n    ]\n\n\ndef register_unary_identity(op_name):\n    def identity(expr, type_map):\n        assert len(expr.args) == 1\n        arg = expr.args[0]\n        t = type_map[arg]\n        return [expr, t]\n\n    return register_fake_quantization_to_integer(op_name, identity)\n\n\nregister_unary_identity(\"reshape\")\nregister_unary_identity(\"squeeze\")\nregister_unary_identity(\"strided_slice\")\nregister_unary_identity(\"transpose\")\nregister_unary_identity(\"expand_dims\")\nregister_unary_identity(\"nn.max_pool2d\")\nregister_unary_identity(\"nn.batch_flatten\")\nregister_unary_identity(\"nn.depth_to_space\")\nregister_unary_identity(\"max\")\nregister_unary_identity(\"min\")\nregister_unary_identity(\"image.resize2d\")\n\n\n@register_fake_quantization_to_integer(\"nn.adaptive_avg_pool1d\")\ndef adaptive_avgpool1d(expr, type_map):\n    \"\"\"Rewrite an adaptive avgpool op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    out_t = type_map[expr]\n    if not (\n        approx_equal(t.scale, out_t.scale)\n        and approx_equal(t.zero_point, out_t.zero_point)\n        and tvm.ir.structural_equal(t.dtype, out_t.dtype)\n    ):\n        arg = relay.qnn.op.requantize(\n            arg,\n            t.scale,\n            t.zero_point,\n            out_t.scale,\n            out_t.zero_point,\n            out_dtype=\"int32\",\n            axis=t.axis,\n        )\n    else:\n        arg = relay.op.cast(arg, \"int32\")\n    output_size = expr.attrs.output_size\n    out = relay.op.nn.adaptive_avg_pool1d(arg, output_size)\n    return [out, TensorAffineType(out_t.scale, out_t.zero_point, \"int32\", out_t.axis)]\n\n\n@register_fake_quantization_to_integer(\"nn.avg_pool2d\")\ndef avgpool2d(expr, type_map):\n    \"\"\"Rewrite a avgpool op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    out_t = type_map[expr]\n    # Cast (or requantize) to int32.\n    if not (\n        approx_equal(t.scale, out_t.scale)\n        and approx_equal(t.zero_point, out_t.zero_point)\n        and tvm.ir.structural_equal(t.dtype, out_t.dtype)\n    ):\n        arg = relay.qnn.op.requantize(\n            arg,\n            t.scale,\n            t.zero_point,\n            out_t.scale,\n            out_t.zero_point,\n            out_dtype=\"int32\",\n            axis=t.axis,\n        )\n    else:\n        arg = relay.op.cast(arg, \"int32\")\n    out = relay.op.nn.avg_pool2d(arg, **expr.attrs)\n    if out_t.dtype != \"int32\":\n        # Cast back to output dtype to preserve input dtype == output dtype for AvgPool2d.\n        out = relay.op.clip(out, a_min=np.iinfo(out_t.dtype).min, a_max=np.iinfo(out_t.dtype).max)\n        out = relay.op.cast(out, out_t.dtype)\n    return [out, TensorAffineType(out_t.scale, out_t.zero_point, out_t.dtype, out_t.axis)]\n\n\n@register_fake_quantization_to_integer(\"nn.global_avg_pool2d\")\ndef global_avgpool2d(expr, type_map):\n    \"\"\"Rewrite a global_avgpool op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    out_t = type_map[expr]\n    out_t = type_map[expr]\n    if not (\n        approx_equal(t.scale, out_t.scale)\n        and approx_equal(t.zero_point, out_t.zero_point)\n        and tvm.ir.structural_equal(t.dtype, out_t.dtype)\n    ):\n        arg = relay.qnn.op.requantize(\n            arg,\n            t.scale,\n            t.zero_point,\n            out_t.scale,\n            out_t.zero_point,\n            out_dtype=\"int32\",\n            axis=t.axis,\n        )\n    else:\n        arg = relay.op.cast(arg, \"int32\")\n    out = relay.op.nn.global_avg_pool2d(arg)\n    return [out, TensorAffineType(out_t.scale, out_t.zero_point, \"int32\", out_t.axis)]\n\n\n@register_fake_quantization_to_integer(\"broadcast_to\")\ndef broadcast_to(expr, type_map):\n    \"\"\"Rewrite a broadcast_to op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    shape = expr.attrs.shape\n    out = relay.op.broadcast_to(arg, shape)\n    return [out, t]\n\n\n@register_fake_quantization_to_integer(\"nn.bias_add\")\ndef bias_add(expr, type_map):\n    \"\"\"Rewrite a bias_add op\"\"\"\n    x, b = expr.args\n    x_t = type_map[x]\n    if b in type_map:\n        # Ensure bias matches the previous op\n        b_t = type_map[b]\n        in_scale = fold_constant(x_t.scale)\n        in_zero_point = fold_constant(x_t.zero_point)\n        if not (\n            approx_equal(x_t.scale, b_t.scale)\n            and approx_equal(x_t.zero_point, b_t.zero_point)\n            and tvm.ir.structural_equal(x_t.dtype, b_t.dtype)\n        ):\n            b = relay.qnn.op.requantize(\n                b,\n                b_t.scale,\n                b_t.zero_point,\n                in_scale,\n                in_zero_point,\n                out_dtype=x_t.dtype,\n                axis=0,\n            )\n    else:\n        # If the bias is a constant, we need to quantize it\n        assert isinstance(b, relay.expr.Constant)\n        assert b.checked_type.dtype in [\"float32\", \"float64\", \"float16\", \"bfloat16\"]\n        b = relay.qnn.op.quantize(b, x_t.scale, x_t.zero_point, axis=0, out_dtype=x_t.dtype)\n    out = relay.op.nn.bias_add(x, b, **expr.attrs)\n    return [out, x_t]\n\n\n@register_fake_quantization_to_integer(\"nn.conv2d\")\ndef conv2d(expr, type_map):\n    \"\"\"Rewrite a conv2d op\"\"\"\n    attrs = {**expr.attrs}\n    attrs.pop(\"out_dtype\")\n    x, weight = expr.args\n    x_t = type_map[x]\n    w_t = type_map[weight]\n    conv_scale = fold_constant(x_t.scale * w_t.scale)\n    conv_zp = get_zeros(conv_scale)\n    out = relay.qnn.op.conv2d(\n        x, weight, x_t.zero_point, w_t.zero_point, x_t.scale, w_t.scale, **attrs\n    )\n    out_layout = attrs[\"out_layout\"] if attrs[\"out_layout\"] != \"\" else attrs[\"data_layout\"]\n    out_axis = bijective_layout(out_layout, \"NCHW\").backward_index(list(range(4)))[1]\n    return [out, TensorAffineType(conv_scale, conv_zp, out.attrs.out_dtype, out_axis.value)]\n\n\n@register_fake_quantization_to_integer(\"nn.conv2d_transpose\")\ndef conv2d_transpose(expr, type_map):\n    \"\"\"Rewrite a conv2d_transpose op\"\"\"\n    attrs = {**expr.attrs}\n    attrs.pop(\"out_dtype\")\n    x, weight = expr.args\n    x_t = type_map[x]\n    w_t = type_map[weight]\n    conv_scale = fold_constant(x_t.scale * w_t.scale)\n    conv_zp = get_zeros(conv_scale)\n\n    out = relay.qnn.op.conv2d_transpose(\n        x, weight, x_t.zero_point, w_t.zero_point, x_t.scale, w_t.scale, **attrs\n    )\n    out_layout = attrs[\"out_layout\"] if attrs[\"out_layout\"] != \"\" else attrs[\"data_layout\"]\n    out_axis = bijective_layout(out_layout, \"NCHW\").backward_index(list(range(4)))[1]\n    return [out, TensorAffineType(conv_scale, conv_zp, out.attrs.out_dtype, out_axis.value)]\n\n\n@register_fake_quantization_to_integer(\"nn.dense\")\ndef dense(expr, type_map):\n    \"\"\"Rewrite a dense op\"\"\"\n    attrs = {**expr.attrs}\n    attrs.pop(\"out_dtype\")\n    x, weight = expr.args\n    x_t = type_map[x]\n    w_t = type_map[weight]\n    dense_scale = fold_constant(x_t.scale * w_t.scale)\n    dense_zp = get_zeros(dense_scale)\n    out = relay.qnn.op.dense(\n        x, weight, x_t.zero_point, w_t.zero_point, x_t.scale, w_t.scale, **attrs\n    )\n    return [out, TensorAffineType(dense_scale, dense_zp, out.attrs.out_dtype, 1)]\n\n\n@register_fake_quantization_to_integer(\"nn.batch_matmul\")\ndef batch_matmul(expr, type_map):\n    \"\"\"Rewrite a batch_matmul op\"\"\"\n    x, y = expr.args\n    x_t = type_map[x]\n    y_t = type_map[y]\n    matmul_scale = fold_constant(x_t.scale * y_t.scale)\n    matmul_zp = relay.const(0)\n    out = relay.qnn.op.batch_matmul(x, y, x_t.zero_point, y_t.zero_point, x_t.scale, y_t.scale)\n    return [out, TensorAffineType(matmul_scale, matmul_zp, out.attrs.out_dtype, x_t.axis)]\n\n\n@register_fake_quantization_to_integer(\"concatenate\")\ndef concat(expr, type_map):\n    \"\"\"Rewrite a concat op\"\"\"\n    scales = []\n    zps = []\n\n    tuple_type = type_map[expr.args[0]]\n    for t in tuple_type.types:\n        scales.append(t.scale)\n        zps.append(t.zero_point)\n\n    out_type = type_map[expr]\n\n    out = relay.qnn.op.concatenate(\n        expr.args[0],\n        relay.Tuple(scales),\n        relay.Tuple(zps),\n        out_type.scale,\n        out_type.zero_point,\n        **expr.attrs,\n    )\n    return [out, out_type]\n\n\n@register_fake_quantization_to_integer(\"topk\")\ndef topk(expr, type_map):\n    \"\"\"Rewrite a topk op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    attrs = {**expr.attrs}\n    assert \"ret_type\" in attrs and attrs[\"ret_type\"] == \"values\"\n    return [expr, t]\n\n\n@register_fake_quantization_to_integer(\"split\")\ndef split(expr, type_map):\n    \"\"\"Rewrite a split op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    attrs = {**expr.attrs}\n    if isinstance(attrs[\"indices_or_sections\"], tvm.tir.IntImm):\n        num_split = attrs[\"indices_or_sections\"].value\n        attrs[\"indices_or_sections\"] = num_split\n    else:\n        num_split = len(attrs[\"indices_or_sections\"]) + 1\n    return [expr, TupleAffineType([t] * num_split)]\n\n\n@register_fake_quantization_to_integer(\"clip\")\ndef clip(expr, type_map):\n    \"\"\"Rewrite a clip op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    amin = expr.attrs.a_min\n    amax = expr.attrs.a_max\n    scale = fold_constant(t.scale)\n    z_p = fold_constant(t.zero_point)\n    if (\n        isinstance(scale, relay.expr.Constant)\n        and scale.data.numpy().size == 1\n        and isinstance(z_p, relay.expr.Constant)\n        and z_p.data.numpy().size == 1\n    ):\n        scale = scale.data.numpy().item()\n        z_p = z_p.data.numpy().item()\n        new_min = int(amin / scale + z_p)\n        new_max = int(amax / scale + z_p)\n        out = relay.op.clip(arg, new_min, new_max)\n    else:\n        if not isinstance(amin, relay.expr.Constant):\n            amin = relay.op.const(amin)\n        if not isinstance(amax, relay.expr.Constant):\n            amax = relay.op.const(amax)\n\n        scale_shape = infer_shape(scale)\n        if len(scale_shape) > 0 and scale_shape[0] > 1:\n            b_shape = [1] * len(infer_shape(arg))\n            b_shape[t.axis] = -1\n            amin = relay.op.reshape(relay.op.broadcast_to(amin, scale_shape), b_shape)\n            amax = relay.op.reshape(relay.op.broadcast_to(amax, scale_shape), b_shape)\n        amin = relay.qnn.op.quantize(amin, scale, z_p, t.axis, t.dtype)\n        amax = relay.qnn.op.quantize(amax, scale, z_p, t.axis, t.dtype)\n        out = relay.op.minimum(relay.op.maximum(arg, fold_constant(amin)), fold_constant(amax))\n\n    return [out, t]\n\n\n@register_fake_quantization_to_integer(\"nn.relu\")\ndef relu(expr, type_map):\n    \"\"\"Rewrite a relu op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    scale_shape = infer_shape(t.scale)\n    z_p = t.zero_point\n    assert len(scale_shape) <= 1\n    if len(scale_shape) == 1 and scale_shape[0] > 1:\n        b_shape = [1] * len(infer_shape(arg))\n        b_shape[t.axis] = -1\n        z_p = relay.op.reshape(relay.op.broadcast_to(z_p, scale_shape), b_shape)\n    zero = relay.op.cast(z_p, t.dtype)\n    return [relay.op.maximum(arg, fold_constant(zero)), t]\n\n\n@register_fake_quantization_to_integer(\"nn.leaky_relu\")\ndef leaky_relu(expr, type_map):\n    \"\"\"Rewrite a leaky relu op\"\"\"\n    arg = expr.args[0]\n    x_t = type_map[arg]\n    out_t = type_map[expr]\n    alpha = expr.attrs.alpha\n    output = relay.qnn.op.leaky_relu(\n        expr, alpha, x_t.scale, x_t.zero_point, out_t.scale, out_t.zero_point\n    )\n    return [output, x_t]\n\n\n@register_fake_quantization_to_integer(\"nn.pad\")\ndef pad(expr, type_map):\n    \"\"\"Rewite an nn.pad op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n    pad_value = expr.args[1]\n    # TF2ONNX will sometimes implement the pad_value as a constant without a quantize\n    # To support that, the pass lets branches that terminate in a constant through\n    if pad_value in type_map:\n        # if the pad value is calcuated from a dequantize op, it should be in the type map\n        # and we need to make sure it's affine type matches the arg\n        pad_t = type_map[pad_value]\n        if not tvm.ir.structural_equal(t, pad_t):\n            pad_value = relay.qnn.op.requantize(\n                pad_value,\n                pad_t.scale,\n                pad_t.zero_point,\n                t.scale,\n                t.zero_point,\n                out_dtype=t.dtype,\n                axis=pad_t.axis,\n            )\n    else:\n        # If the pad-value is a constant, we need to quantize it\n        assert isinstance(pad_value, relay.expr.Constant)\n        assert pad_value.checked_type.dtype in [\"float32\", \"float64\", \"float16\", \"bfloat16\"]\n        pad_value = relay.qnn.op.quantize(pad_value, t.scale, t.zero_point)\n\n    out = relay.op.nn.pad(arg, pad_value=pad_value, **expr.attrs)\n    return [out, t]\n\n\n@register_fake_quantization_to_integer(\"mean\")\ndef mean(expr, type_map):\n    \"\"\"Rewrite a mean op\"\"\"\n    arg = expr.args[0]\n    t = type_map[arg]\n\n    arg = relay.op.cast(arg, \"int32\")\n    out = relay.op.mean(arg, **expr.attrs)\n    out = relay.op.cast(out, t.dtype)\n    return [out, t]\n\n\ndef get_binary_types(expr, type_map):\n    \"\"\"Get Affine types of a binary op's inputs and unify them\"\"\"\n    # Support the case where one input is quantized and the other is a constant float\n    left = expr.args[0]\n    right = expr.args[1]\n    left_t = None\n    right_t = None\n\n    if left in type_map:\n        left_t = type_map[left]\n    if right in type_map:\n        right_t = type_map[right]\n\n    out_t = type_map[expr]\n    if left_t is None and right_t is None:\n        raise TypeError(\"neither input is quantized!\")\n    if left_t is None:\n        assert isinstance(left, relay.expr.Constant)\n        left = relay.qnn.op.quantize(\n            left, right_t.scale, right_t.zero_point, out_dtype=right_t.dtype\n        )\n        left_t = right_t\n    if right_t is None:\n        assert isinstance(right, relay.expr.Constant)\n        right = relay.qnn.op.quantize(\n            right, left_t.scale, left_t.zero_point, out_dtype=left_t.dtype\n        )\n        right_t = left_t\n\n    # Handle the case of mismatched inputs\n    if not left_t.dtype == out_t.dtype:\n        out_t = left_t\n\n    return left, right, left_t, right_t, out_t\n\n\ndef register_binary_qnn(op_name, op):\n    \"\"\"Register a Binary Op that converts to QNN\"\"\"\n\n    def binary(expr, type_map):\n        left, right, left_t, right_t, out_t = get_binary_types(expr, type_map)\n        out = op(\n            left,\n            right,\n            left_t.scale,\n            left_t.zero_point,\n            right_t.scale,\n            right_t.zero_point,\n            out_t.scale,\n            out_t.zero_point,\n            left_t.axis,\n            right_t.axis,\n        )\n\n        return [out, out_t]\n\n    return register_fake_quantization_to_integer(op_name, binary)\n\n\n# Use lambdas here to avoid a circular import problem\n# pylint: disable=unnecessary-lambda\nregister_binary_qnn(\"add\", lambda *args: relay.qnn.op.add(*args))\nregister_binary_qnn(\"multiply\", lambda *args: relay.qnn.op.mul(*args))\nregister_binary_qnn(\"subtract\", lambda *args: relay.qnn.op.subtract(*args))\n\n\ndef register_binary_identity(op_name, op):\n    \"\"\"Register a binary op that works directly on int8\"\"\"\n\n    def binary(expr, type_map):\n        left, right, left_t, right_t, out_t = get_binary_types(expr, type_map)\n        if left_t != out_t:\n            left = relay.qnn.op.requantize(\n                left,\n                left_t.scale,\n                left_t.zero_point,\n                out_t.scale,\n                out_t.zero_point,\n                out_dtype=out_t.dtype,\n                axis=left_t.axis,\n            )\n\n        if right_t != out_t:\n            right = relay.qnn.op.requantize(\n                right,\n                right_t.scale,\n                right_t.zero_point,\n                out_t.scale,\n                out_t.zero_point,\n                out_dtype=out_t.dtype,\n                axis=right_t.axis,\n            )\n        out = op(left, right)\n        return [out, out_t]\n\n    return register_fake_quantization_to_integer(op_name, binary)\n\n\nregister_binary_identity(\"minimum\", relay.op.minimum)\nregister_binary_identity(\"maximum\", relay.op.maximum)\n\n\ndef register_unary_qnn(op_name, op):\n    \"\"\"Rewrite a unary op\"\"\"\n\n    def unary(expr, type_map):\n        arg = expr.args[0]\n        x_t = type_map[arg]\n        out_t = type_map[expr]\n        out = op(\n            arg,\n            x_t.scale,\n            x_t.zero_point,\n            out_t.scale,\n            out_t.zero_point,\n        )\n        return [out, out_t]\n\n    return register_fake_quantization_to_integer(op_name, unary)\n\n\nregister_unary_qnn(\"sqrt\", relay.qnn.op.sqrt)\nregister_unary_qnn(\"rsqrt\", relay.qnn.op.rsqrt)\nregister_unary_qnn(\"exp\", relay.qnn.op.exp)\nregister_unary_qnn(\"erf\", relay.qnn.op.erf)\nregister_unary_qnn(\"sigmoid\", relay.qnn.op.sigmoid)\nregister_unary_qnn(\"hardswish\", relay.qnn.op.hardswish)\nregister_unary_qnn(\"tanh\", relay.qnn.op.tanh)\nregister_unary_qnn(\"abs\", relay.qnn.op.abs)\nregister_unary_qnn(\"log\", relay.qnn.op.log)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/flexible_shape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Relay functions for wrapping a module with flexible shape dispatch.\"\"\"\nimport tvm\nfrom tvm import relay\n\n\ndef override_shape(tensor_type, axis, dim):\n    \"\"\"Change a dimension in a tensor shape.\"\"\"\n    # Handle multiple tensors by overriding the shape of each.\n    if isinstance(tensor_type, relay.TupleType):\n        tensor_type = tensor_type.fields\n    else:\n        tensor_type = [tensor_type]\n\n    # Create new tensortypes for each input.\n    new_types = []\n    for t_type in tensor_type:\n        new_dims = list(t_type.shape)\n        new_dims[axis] = dim\n        new_types.append(relay.TensorType(new_dims, t_type.dtype))\n\n    # Dont return a tuple if there is a single tensor.\n    if len(new_types) == 1:\n        return new_types[0]\n    return relay.TupleType(tvm.runtime.convert(new_types))\n\n\ndef specialize_body(mod, function, axis, dim, input_indices, affects_output=True):\n    \"\"\"\n    Create a subgraph to handle specific input shapes\n\n    This function takes in a module and one of it's functions and creates a\n    similar function with a specific input shape. It then attaches the new function\n    to the module. Calling this function multiple times results in a module that\n    contains several similar functions each specialized to a specific input shape.\n    This allows a dispatch handler to be built on top of the module to deal with\n    flexible shapes.\n\n    There are a few modes to this function. When the specialized function has multiple\n    flexible inputs, the index of those inputs must be provided to the input_indices argument.\n    In this case, the axis of the flexible dimension for each of those inputs must be the same.\n\n    By default, this function assumes that the output shape is dependent on the input\n    shape (as is the case in dynamic batching) and will also specialize the output type\n    accordingly. If this is not true, the affects_output argument must be set to False.\n\n    Parameters\n    ----------\n    mod: IRModule\n        The module that contains specialized functions and the dispatcher.\n    function: Function\n        The original non-specialized function that will be transformed.\n    axis: int\n        Which axis the flexible shape is on.\n    dim: int\n        The shape to specialize the new subgraph for along the axis dim.\n    input_indices: List[int]\n        Which inputs should be dispatched dynamically, provided by index. All inputs\n        must share the same dynamic axis.\n    affects_output: Optional[bool]\n        Whether the change in input shape has a corresponding effect on the output shape.\n        Batching for example effects both the input and output whereas changing sequence\n        length in an NLP model typically does not.\n\n    Returns\n    -------\n    gvar : GlobalVar\n        The new variable for the specialized subgraph.\n    spec_types : List[TensorType]\n        A list of the new specialized types for each input in the graph.\n    \"\"\"\n    # Iterate through specified inputs and construct specialized shapes for each.\n    new_params = list(function.params)\n    data_binding = {}\n    dyn_data_array = []\n    for inp in input_indices:\n        data = function.params[inp]\n        flex_ty = override_shape(data.type_annotation, axis, dim)\n        dyn_data = relay.Var(data.name_hint, type_annotation=flex_ty)\n        new_params[inp] = dyn_data\n        data_binding[data] = dyn_data\n        dyn_data_array.append(dyn_data)\n\n    # Create a new function body for the modified shapes.\n    new_body = relay.expr.bind(function.body, data_binding)\n    # Only change the output shape if the input shape affects it.\n    if affects_output:\n        new_ret_ty = override_shape(function.ret_type, axis, dim)\n    else:\n        new_ret_ty = function.ret_type\n    gvar = relay.GlobalVar(\"main_\" + str(dim))\n    # Add the new function to the main IRModule.\n    mod[gvar] = relay.Function(\n        new_params, new_body, new_ret_ty, function.type_params, function.attrs\n    )\n    return gvar, [d.type_annotation for d in dyn_data_array]\n\n\ndef flexible_dispatch(\n    mod, buckets, axis=0, auto_pad=False, pad_value=0, input_indices=None, affects_output=True\n):\n    \"\"\"\n    Enable inference of multiple shaped inputs in one module.\n\n    This transformation adds a handler around a module that\n    checks input shapes and dispatches to a subgraph specialized\n    to handle the specific shapes of that input. If no exactly matching\n    subgraph is available, the input will be run using full dynamism.\n    For best performance, specify all the sizes the module will\n    be likely to see using the buckets argument.\n\n    By default, this function will dispatch shapes that exactly match one\n    of the buckets to a corresponding subgraph. All non-matching shapes\n    use the same fully dynamic fallback. This can be detrimental to performance\n    for those non-matching shapes. Setting auto_pad to True causes this\n    function to round-up the shape of non-matching inputs to the closest\n    bucket. This allows them to use the tuned kernels of bucket shapes\n    which can improve performance.\n\n    Functions that have multiple inputs sharing a dynamic axis, which\n    is common for batch size or sequence length dynamism, are supported\n    through the input_indices argument.\n\n    Many types of dynamism such as batching affect both the input and output\n    shape, however this is not always the case. If the output shape\n    is independent of the input, the affects_output argument of this\n    function must be set to False.\n\n    Parameters\n    ----------\n    buckets: list[int]\n        The sizes of the input dimension that should be explicitly handled.\n        Each value in buckets will have a corresponding subgraph constructed to\n        handle it.\n    axis: int\n        The dimension of the input that should be made flexible. This will\n        most often be used for the batch dimension.\n    auto_pad: Optional[bool]\n        If True, then padding will be inserted to values that don't match one of\n        the provided buckets.\n    pad_value: Optional[float]\n        When auto_pad is true, padding will be done with this value.\n    input_indices: Optional[List[int]]\n        Which inputs should be dispatched dynamically, provided by index. All inputs\n        must share the same dynamic axis.\n    affects_output: Optional[bool]\n        Whether the change in input shape has a corresponding effect on the output shape.\n        Batching for example effects both the input and output whereas changing sequence\n        length in an NLP model typically does not.\n\n    Returns\n    -------\n    mod : IRModule\n        The new module wrapped with a flexible shape dispatch handler.\n    \"\"\"\n    main_fn = mod[\"main\"]\n\n    # Default to single input if not specified.\n    if input_indices is None:\n        input_indices = [0]\n\n    # Extract all input data and create a new dynamic variable for each.\n    data = []\n    dyn_data = []\n    for i in input_indices:\n        data.append(main_fn.params[i])\n        dyn_shape = override_shape(data[i].type_annotation, axis, relay.Any())\n        dyn_data.append(relay.Var(data[i].name_hint, type_annotation=dyn_shape))\n\n    # Extract the dynamic shape value from one of the inputs.\n    rt_sh = relay.op.shape_of(dyn_data[0])\n    flex_value = relay.op.take(rt_sh, relay.const(axis))\n\n    if_exprs = []\n\n    for i, bucket in enumerate(buckets):\n        input_data = dyn_data\n        check_dim = flex_value\n\n        # Apply automatic padding if specified.\n        if auto_pad:\n            input_data = []\n            # Construct padding expression for inputs.\n            for j, inp in enumerate(dyn_data):\n                pad_width = relay.const(bucket) - flex_value\n                rank = len(data[j].type_annotation.shape)\n                pads = relay.zeros([rank, 2], \"int32\")\n                pads = relay.scatter_nd(pads, relay.const([axis, 1]), pad_width)\n                padded_value = relay.nn.pad(inp, pads, pad_value)\n\n                # Determine if this is the proper bucket to pad to. Do this by checking if the\n                # input shape is between this bucket and the previous.\n                if i == 0:\n                    padded_value = relay.If(\n                        relay.op.less_equal(flex_value, relay.const(bucket)), padded_value, inp\n                    )\n                else:\n                    padded_value = relay.If(\n                        relay.op.logical_and(\n                            relay.op.less_equal(flex_value, relay.const(bucket)),\n                            relay.op.greater(flex_value, relay.const(buckets[i - 1])),\n                        ),\n                        padded_value,\n                        inp,\n                    )\n                # Update input value and test dimension to reflect possible padding.\n                input_data.append(padded_value)\n            # Grab the new possibly padded shape for checking bucket size.\n            check_dim = relay.op.take(relay.op.shape_of(input_data[0]), relay.const(axis))\n\n        # Create a specialized subgraph for the current bucket.\n        spec_call, spec_ty = specialize_body(\n            mod, main_fn, axis, bucket, input_indices=input_indices, affects_output=affects_output\n        )\n        # Apply hard casting to shape to create statically typed graphs.\n        spec_data = []\n        for j, inp in enumerate(input_data):\n            spec_data.append(relay.op.reshape(inp, spec_ty[j].shape))\n\n        # Create a dispatch statement for the current specialized graph.\n        call_args = list(main_fn.params)\n        for j, inp in enumerate(input_indices):\n            call_args[inp] = spec_data[j]\n        new_call = spec_call(*call_args)\n\n        # Remove meaningless padded outputs if applicable.\n        if auto_pad and affects_output:\n            new_call = relay.take(\n                new_call,\n                relay.arange(start=relay.const(0), stop=flex_value, dtype=\"int32\"),\n                axis=axis,\n            )\n\n        # Add this new case to the dispatch handler.\n        if_exprs.append((relay.op.equal(check_dim, relay.const(bucket)), new_call))\n\n    # Create a subgraph to handle all other shapes.\n    default_dyn_call, _ = specialize_body(\n        mod, main_fn, axis, relay.Any(), input_indices=input_indices, affects_output=affects_output\n    )\n    call_args = list(main_fn.params)\n    for j, inp in enumerate(input_indices):\n        call_args[inp] = dyn_data[j]\n    new_body = default_dyn_call(*call_args)\n\n    # Create an If chain to dispatch shapes to the appropriate specialized subgraph.\n    for cond, true_branch in if_exprs:\n        new_body = relay.If(cond, true_branch, new_body)\n\n    # Assign new parameters to the function.\n    new_params = list(main_fn.params)\n    for j, inp in enumerate(input_indices):\n        new_params[inp] = dyn_data[j]\n\n    # Update the output shape to be dynamic if needed.\n    if affects_output:\n        dyn_ret_type = override_shape(main_fn.ret_type, axis, relay.Any())\n    else:\n        dyn_ret_type = main_fn.ret_type\n\n    # Assign the handler as the new entrypoint in the module.\n    new_main = relay.Function(\n        new_params, new_body, dyn_ret_type, main_fn.type_params, main_fn.attrs\n    )\n    mod[\"main\"] = new_main\n    # Do type inference to make sure everything worked.\n    mod = relay.transform.InferType()(mod)\n    return mod\n\n\nclass FlexibleShapeDispatch(object):\n    \"\"\"Enable inference of multiple shaped inputs in one module.\n\n    This transformation adds a handler around a module that\n    checks input shapes and dispatches to a subgraph specialized\n    to handle the specific shapes of that input. If no exactly matching\n    subgraph is available, the input will be run using full dynamism.\n    For best performance, specify all the sizes the module will\n    be likely to see using the buckets argument.\n\n    By default, this pass will dispatch shapes that exactly match one\n    of the buckets to a corresponding subgraph. All non-matching shapes\n    use the same fully dynamic fallback. This can be detrimental to performance\n    for those non-matching shapes. Setting auto_pad to True causes this\n    pass to round-up the shape of non-matching inputs to the closest\n    bucket. This allows them to use the tuned kernels of bucket shapes\n    which can improve performance.\n\n    Models that have multiple inputs sharing a dynamic axis, which\n    is common for batch size or sequence length dynamism, are supported\n    through the input_indices argument.\n\n    Many types of dynamism such as batching affect both the input and output\n    shape, however this is not always the case. If the output shape\n    is independent of the input, the affects_output argument of this\n    pass must be set to False.\n\n    Parameters\n    ----------\n    buckets: list[int]\n        The sizes of the input dimension that should be explicitly handled.\n        Each value in buckets will have a corresponding subgraph constructed to\n        handle it.\n    axis: int\n        The dimension of the input that should be made flexible. This will\n        most often be used for the batch dimension.\n    auto_pad: Optional[bool]\n        If True, then padding will be inserted to values that don't match one of\n        the provided buckets.\n    pad_value: Optional[float]\n        When auto_pad is true, padding will be done with this value.\n    input_indices: Optional[List[int]]\n        Which inputs should be dispatched dynamically, provided by index. All inputs\n        must share the same dynamic axis.\n    affects_output: Optional[bool]\n        Whether the change in input shape has a corresponding effect on the output shape.\n        Batching for example effects both the input and output whereas changing sequence\n        length in an NLP model typically does not.\n\n    Returns\n    -------\n    ret : FlexibleShapeDispatch\n        A pass that can be applied to a module to add flexible shape handling.\n    \"\"\"\n\n    def __init__(\n        self,\n        buckets,\n        axis=0,\n        auto_pad=False,\n        pad_value=0,\n        input_indices=None,\n        affects_output=True,\n    ):\n        self.axis = axis\n        self.buckets = buckets\n        self.auto_pad = auto_pad\n        self.pad_value = pad_value\n        self.input_indices = input_indices\n        self.affects_output = affects_output\n        super(FlexibleShapeDispatch, self).__init__()\n\n    def __call__(self, mod):\n        # Shape information is required for this pass.\n        mod = relay.transform.InferType()(mod)\n        return flexible_dispatch(\n            mod,\n            self.buckets,\n            self.axis,\n            self.auto_pad,\n            self.pad_value,\n            self.input_indices,\n            self.affects_output,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/infer_layout_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, missing-docstring, unused-import\n\"\"\"\nRelay infer correct layout pass.\n\"\"\"\nimport tvm\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"relay._transform.InferCorrectLayoutOutput\")\nclass InferCorrectLayoutOutput(Object):\n    \"\"\"An output structure to hold results from FInferCorrectLayout calls.\"\"\"\n\n    def __init__(self, input_layouts, output_layouts, new_attrs):\n        self.__init_handle_by_constructor__(\n            _ffi_api.InferCorrectLayoutOutput, input_layouts, output_layouts, new_attrs\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/memory_plan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return,invalid-name,len-as-condition,too-many-nested-blocks\n\"\"\"\nA pass for manifesting explicit memory allocations.\n\"\"\"\nfrom typing import Optional, Dict, List, Tuple\nfrom collections import defaultdict\nimport attr\n\nfrom ..expr_functor import ExprMutator\nfrom .. import op, expr\nfrom ..function import Function\nfrom ... import register_func, ir, cpu\nfrom ..._ffi.runtime_ctypes import Device\nfrom ... import IRModule\nfrom .. import transform\nfrom . import function_pass\n\n\ndef is_primitive(call):\n    return (\n        hasattr(call, \"op\")\n        and hasattr(call.op, \"attrs\")\n        and hasattr(call.op.attrs, \"Primitive\")\n        and int(call.op.attrs.Primitive) == 1\n    )\n\n\n@attr.s(auto_attribs=True)\nclass Region:\n    \"\"\"\n    Represents a control-free allocation region.\n\n    The below pass groups sets of allocations into regions,\n    then replaces the region with a single allocation.\n    \"\"\"\n\n    var: expr.Var\n    size: expr.Expr\n    alignment: Optional[expr.Expr]\n    dtype: Optional[str]\n    device: Device\n    offsets: Dict[expr.Var, Tuple[expr.Expr, expr.Expr]]\n\n    @staticmethod\n    def empty(region_no):\n        zero = expr.const(0, dtype=\"int64\")\n        assert len(zero.data.shape) == 0\n        region_var = expr.var(f\"region{region_no}\")\n        return Region(region_var, zero, None, None, None, {})\n\n    def grow(\n        self,\n        old_storage: expr.Var,\n        size: expr.Expr,\n        alignment: expr.Expr,\n        dev: Device,\n        dtype: str,\n    ) -> None:\n        \"\"\"Grow the region by a given allocation as well as track the old storage\n        for later rewriting the program to use the allocated region.\n        \"\"\"\n        if self.dtype:\n            assert self.dtype == dtype, \"must have matching dtypes in a region\"\n        else:\n            self.dtype = dtype\n\n        if self.alignment:\n            assert ir.structural_equal(\n                self.alignment, alignment\n            ), \"must have matching alignments in a region\"\n        else:\n            self.alignment = alignment\n\n        if self.device:\n            assert (\n                self.device.device_type == dev.device_type\n                and self.device.device_id == dev.device_id\n            ), \"must have matching device\"\n        else:\n            assert dev\n            self.device = dev\n\n        new_size = (\n            (size + self.alignment - expr.const(1, \"int64\")) / self.alignment * self.alignment\n        )\n\n        # Record the offset at which we allocate the storage.\n        offset_var: expr.RelayExpr = expr.var(f\"offset{len(self.offsets)}\")\n        self.offsets[old_storage] = (offset_var, self.size)\n\n        self.size = self.size + new_size\n\n    def offset_for(self, alloc: expr.Expr) -> expr.Expr:\n        return self.offsets.get(alloc, [None])[0]\n\n    def to_expr(self, body: expr.Expr) -> expr.Expr:\n        \"\"\"\n        Generate the prelude code for a region, wrapping the body in it.\n\n        The prelude contains the single allocation for a region, and\n        all offset computations.\n        \"\"\"\n\n        if self.device is None:\n            self.device = cpu(0)\n\n        # Generate bindings for each and every size computation\n        # we must do this to maintain ANF.\n        bindings: List[Tuple[expr.Expr, expr.Expr]] = []\n\n        # First compute the total size.\n        total_size = expr.var(f\"total_size{hash(body)}\")\n        bindings.append((total_size, self.size))\n\n        # Allocate the entire region with a single call.\n        alloc = op.memory.alloc_storage(total_size, self.alignment, self.device, self.dtype)\n        bindings.append((self.var, alloc))\n\n        # Generate variables which contain all of the offset math.\n        # Ensure we constant evaluate away all the math here.\n        #\n        # In theory we can support dynamic offsets but this\n        # requires another round of memory planning and\n        # potentially colaescing.\n        for alloc in self.offsets:\n            (var, offset) = self.offsets[alloc]\n            bindings.append((var, offset))\n\n        body = mk_let(bindings, body)\n        return body\n\n\ndef iterative_let(let, each_binding, kont):\n    bindings = []\n    while isinstance(let, expr.Let):\n        lhs = let.var\n        rhs = let.value\n        bindings.append(each_binding(lhs, rhs))\n        let = let.body\n\n    return kont(bindings, let)\n\n\ndef mk_let(bindings, body):\n    for var, value in reversed(bindings):\n        assert var\n        assert value\n        assert body\n        body = expr.Let(var, value, body)\n\n    return body\n\n\ndef const_eval(mod, exp):\n    mod = IRModule.from_expr(exp, type_defs=mod.type_definitions)\n    mod = transform.FoldConstant()(mod)\n    return mod[\"main\"]\n\n\nclass StorageCoalesce(ExprMutator):\n    \"\"\"\n    A pass for coalescing allocations into region/arena allocations.\n\n    After this pass each allocation comes from the same backing storage,\n    but will never overlap even in time, i.e. the allocations are just\n    packed into a contiguous block of memory.\n\n    A secondary part of memory planning will perform liveness analysis to\n    overlap these in time, i.e when an early tensor dies we will attempt\n    to reuse its slot.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.regions = []\n\n    def enter_scope(self) -> None:\n        region_no = len(self.regions)\n        self.regions.append(defaultdict(lambda: Region.empty(region_no)))\n\n    def exit_scope(self, body: expr.Expr) -> expr.Expr:\n        \"\"\"When leaving a scope build a region allocation for the scope.\"\"\"\n        dtype_region = self.regions.pop()\n        for _, region in reversed(list(dtype_region.items())):\n            if len(region.offsets) != 0:\n                body = region.to_expr(body)\n\n        return body\n\n    def current_region(self, dtype) -> Region:\n        current_scope = self.regions[-1]\n        return current_scope[dtype]\n\n    def new_region_and_offset(self, old_storage):\n        for dtype_region in reversed(self.regions):\n            for dtype in dtype_region:\n                region = dtype_region[dtype]\n                offset = region.offset_for(old_storage)\n                if offset:\n                    return region, offset\n\n        raise Exception(\"could not find offset in any valid region\")\n\n    def visit_function(self, fn):\n        \"\"\"Transform the function body to use region allocation scheme.\"\"\"\n        func = fn\n        if getattr(func.attrs, \"Primitive\", 0) == 1:\n            return super().visit_function(func)\n        else:\n            self.enter_scope()\n            body = self.visit(func.body)\n            body = self.exit_scope(body)\n            return Function(\n                func.params,\n                body,\n                func.ret_type,\n                func.type_params,\n                func.attrs,\n            )\n\n    def visit_if(self, ite):\n        self.enter_scope()\n        true_branch = self.visit(ite.true_branch)\n        true_branch = self.exit_scope(true_branch)\n\n        self.enter_scope()\n        false_branch = self.visit(ite.false_branch)\n        false_branch = self.exit_scope(false_branch)\n\n        return expr.If(ite.cond, true_branch, false_branch)\n\n    def mk_let(self, dynamic_regions):\n        \"\"\"Let bind the dynamic regions\"\"\"\n\n        def _mk_let(bindings, body):\n            for var, value in reversed(bindings):\n                assert var\n                assert value is not None\n                assert body\n                body = expr.Let(var, value, body)\n                if var in dynamic_regions:\n                    body = self.exit_scope(body)\n\n            return body\n\n        return _mk_let\n\n    def visit_let(self, let):\n        dynamic_regions = []\n\n        def _each_binding(lhs, rhs):\n            if isinstance(rhs, expr.Call) and rhs.op == op.op.get(\"memory.alloc_storage\"):\n                return self.process_alloc_storage(dynamic_regions, lhs, rhs)\n            elif isinstance(rhs, expr.Call) and rhs.op == op.op.get(\"memory.alloc_tensor\"):\n                return self.process_alloc_tensor(lhs, rhs)\n            else:\n                return lhs, rhs\n\n        result = iterative_let(let, _each_binding, self.mk_let(dynamic_regions))\n        assert result\n        return result\n\n    def process_alloc_storage(self, dynamic_regions, lhs, call):\n        \"\"\"Process alloc_storage\"\"\"\n        size, alignment = call.args\n        dtype = call.attrs.dtype\n        dev = Device(call.attrs.device_type, call.attrs.device_id)\n\n        if not isinstance(size, expr.Constant):\n            self.enter_scope()\n            dynamic_regions.append(lhs)\n        else:\n            # A new scope is created when entering a new region with different\n            # device device.\n            region = self.current_region(dtype)\n            if region.device and region.device.device_type != dev.device_type:\n                self.enter_scope()\n                dynamic_regions.append(lhs)\n\n        region = self.current_region(dtype)\n        region.grow(lhs, size, alignment, dev, dtype)\n        return lhs, region.var\n\n    def process_alloc_tensor(self, lhs, call):\n        \"\"\"Process alloc tensor. Region and offset are computed\"\"\"\n        storage, old_offset, shape = call.args\n        region, offset = self.new_region_and_offset(storage)\n\n        assert old_offset.data.numpy().item() == 0, \"no offsets should yet be allocated\"\n        return (\n            lhs,\n            expr.Call(call.op, [region.var, offset, shape], call.attrs),\n        )\n\n\nclass LiftConst(ExprMutator):\n    \"\"\"An internal pass to lift constants to the top level of function.\"\"\"\n\n    def __init__(self):\n        self.i = 0\n        self.constants = []\n        self.top_level = True\n        super().__init__()\n\n    def visit_constant(self, const):\n        var = expr.var(f\"const{self.i}\")\n        self.i += 1\n        self.constants.append((var, const))\n        return var\n\n    def visit_function(self, fn):\n        if int(getattr(fn.attrs, \"Primitive\", 0)) == 1:\n            return fn\n\n        outer_constant = self.constants\n        self.constants = []\n        # Populates self.constants.\n        body = self.visit(fn.body)\n        body = mk_let(self.constants, body)\n        self.constants = outer_constant\n\n        return Function(fn.params, body, fn.ret_type, fn.type_params, fn.attrs)\n\n    def visit_let(self, let):\n        bindings = []\n        while isinstance(let, expr.Let):\n            new_var = self.visit(let.var)\n            new_val = self.visit(let.value)\n            bindings.append((new_var, new_val))\n            let = let.body\n\n        new_body = self.visit(let)\n        return mk_let(bindings, new_body)\n\n\n@function_pass(opt_level=0)\nclass MemoryPlan:\n    \"\"\"An explicit pass wrapper around StorageCoalesce.\"\"\"\n\n    def transform_function(self, func, mod, _):\n        mod.import_from_std(\"core.rly\")\n        sc = StorageCoalesce()\n        func = sc.visit(func)\n        return func\n\n\nregister_func(\"relay.transform.MemoryPlan\", MemoryPlan)\n\n\n@function_pass(opt_level=0)\nclass LiftConstants:\n    \"\"\"An explicit pass wrapper around LiftConst.\"\"\"\n\n    def transform_function(self, func, mod, _):\n        mod.import_from_std(\"core.rly\")\n        func = LiftConst().visit(func)\n        return func\n\n\nregister_func(\"relay.transform.LiftConstants\", LiftConstants)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/mixed_precision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long,unused-argument\n\"\"\"Default behavior for ops in mixed_precision pass. Import this file to use.\"\"\"\nfrom typing import List\n\nfrom tvm.relay.op import register_mixed_precision_conversion\n\n# MIXED_PRECISION_ALWAYS ops should always be done in lower precision due to the speed and memory\n# savings. MIXED_PRECISION_FOLLOW ops can be done in lower precision but don't have speedups to\n# justify a cast. MIXED_PRECISION_NEVER colored ops should not be done in lower precision due to\n# numerical reasons.\nMIXED_PRECISION_ALWAYS = 0\nMIXED_PRECISION_FOLLOW = 1\nMIXED_PRECISION_NEVER = 2\n\n# Default lists inspired from TF's classifications:\n# github.com/tensorflow/tensorflow/blob/v2.5.0/tensorflow/core/grappler/optimizers/auto_mixed_precision_lists.h\n# They have a bias toward Nvidia Tensor Cores so modify lists per your hardware choice.\nDEFAULT_ALWAYS_LIST = [\n    \"nn.conv1d\",\n    \"nn.conv2d\",\n    \"nn.conv3d\",\n    \"nn.conv1d_transpose\",\n    \"nn.conv2d_transpose\",\n    \"nn.conv3d_transpose\",\n    \"nn.dense\",\n    \"nn.batch_matmul\",\n]\nDEFAULT_FOLLOW_LIST = [\n    # These ops add new data or change shape\n    \"nn.pad\",\n    \"nn.batch_flatten\",\n    \"concatenate\",\n    \"zeros\",\n    \"split\",\n    \"squeeze\",\n    \"transpose\",\n    \"expand_dims\",\n    \"reshape\",\n    \"dyn.reshape\",\n    \"broadcast_to_like\",\n    \"dyn.broadcast_to\",\n    \"strided_slice\",\n    \"dyn.strided_slice\",\n    \"take\",\n    \"argwhere\",\n    \"where\",\n    \"tile\",\n    \"dyn.tile\",\n    \"scatter\",\n    \"full\",\n    \"dyn.full\",\n    \"nn.depth_to_space\",\n    # Comparison\n    \"less\",\n    \"greater\",\n    \"less_equal\",\n    \"greater_equal\",\n    # By definition copy and cast will depend on inputs for output.\n    \"copy\",\n    \"cast\",\n    \"cast_like\",\n    # Simple arithmetic\n    \"add\",\n    \"subtract\",\n    \"multiply\",\n    \"divide\",\n    \"nn.bias_add\",\n    \"nn.batch_norm\",\n    \"sqrt\",\n    \"shape_of\",\n    # Simple activations\n    \"max\",\n    \"min\",\n    \"maximum\",\n    \"minimum\",\n    \"argmax\",\n    \"argmin\",\n    \"nn.relu\",\n    \"nn.leaky_relu\",\n    \"nn.prelu\",\n    \"nn.dropout\",\n    # Complicated activations which saturate in a narrow range\n    \"sigmoid\",\n    \"tanh\",\n    \"fast_tanh\",  # Some coefficients outside of representable range, but probably ok\n    \"fast_exp\",\n    \"fast_erf\",\n    \"clip\",  # Usually safe, may result in oddity if clip greater than fp16 range\n    # Pooling operations\n    \"nn.max_pool1d\",\n    \"nn.max_pool2d\",\n    \"nn.max_pool3d\",\n    \"nn.avg_pool1d\",\n    \"nn.avg_pool2d\",\n    \"nn.avg_pool3d\",\n    # \"nn.global_max_pool1d\", # does not exist yet\n    \"nn.global_max_pool2d\",\n    # \"nn.global_max_pool3d\", # does not exist yet\n    \"nn.adaptive_max_pool1d\",\n    \"nn.adaptive_max_pool2d\",\n    \"nn.adaptive_max_pool3d\",\n    \"image.resize2d\",\n]\nDEFAULT_NEVER_LIST = [\n    # In general if |f(x)| >> |x| for expected inputs then put the op here.\n    \"exp\",\n    \"power\",\n    \"nn.cross_entropy\",\n    \"nn.cross_entropy_with_logits\",\n    \"nn.softmax\",\n    \"nn.l2_normalize\",\n    # Error function doesn't seem to be able to be lowered into fp16 version in llvm.\n    # Move to follow list when it does.\n    \"erf\",\n    # Do not allow arange arguments (begin/end) to be fp16. \"end\" can be a big fp32 number\n    # not representable in fp16.\n    \"arange\",\n    # Ops that could involve a large summation are not allowed in fp16.\n    \"nn.global_avg_pool2d\",\n    \"nn.adaptive_avg_pool1d\",\n    \"nn.adaptive_avg_pool2d\",\n    \"nn.adaptive_avg_pool3d\",\n    \"sum\",\n    \"mean\",\n    \"variance\",\n    \"nn.layer_norm\",\n]\n\n# Returns a decorator which registers for every given op, the function under FTVMMixedPrecisionConversionType\ndef register_func_to_op_list(list_ops: List):\n    def decorator(func):\n        for op_name in list_ops:\n            register_mixed_precision_conversion(op_name, func=func)\n\n    return decorator\n\n\ndef get_generic_out_dtypes(call_node: \"relay.Call\", mixed_precision_type: str) -> List[str]:\n    \"\"\"A function which returns output dtypes in a way which works for most ops.\n\n    Parameters\n    ---------\n    call_node: relay.Call\n        The call node containing the op.\n    mixed_precision_type: str\n        The target type to run the operation in.\n    Returns\n    -------\n    output_dtypes : [str, str]\n        A list of two strings. The first represents the datatype used for accumulation\n        in the operation. The second represents the actual output datatype.\n    \"\"\"\n    # Assume support accumulation dtypes <---> has out_dtype attr.\n    # This is because there is no better way right now to tell which ops support accumulating\n    # at different data types.\n    # Some discussion here about making this better is here:\n    # https://discuss.tvm.apache.org/t/rfc-relay-fp32-fp16-model-support/9994/4?u=andrewzhaoluo\n    if hasattr(call_node.attrs, \"out_dtype\"):\n        # TODO (AndrewZhaoLuo): evaluate consistent support for mixed_type accumulators\n        # return [\"float32\", mixed_precision_type]\n        return [mixed_precision_type, mixed_precision_type]\n\n    # [accumulation_dtype, output_dtype] for the operations\n    return [mixed_precision_type, mixed_precision_type]\n\n\n# Functions for FTVMMixedPrecisionConversionType which\n# Take in CallNodes and a DType and returns a conversion type,\n# an accumulation dtype, and an output_dtype.\n@register_func_to_op_list(list_ops=DEFAULT_ALWAYS_LIST)\ndef generic_always_op(call_node: \"relay.Call\", mixed_precision_type: str) -> List:\n    return [MIXED_PRECISION_ALWAYS] + get_generic_out_dtypes(call_node, mixed_precision_type)\n\n\n@register_func_to_op_list(list_ops=DEFAULT_FOLLOW_LIST)\ndef generic_follow_op(call_node: \"relay.Call\", mixed_precision_type: str) -> List:\n    return [MIXED_PRECISION_FOLLOW] + get_generic_out_dtypes(call_node, mixed_precision_type)\n\n\n@register_func_to_op_list(list_ops=DEFAULT_NEVER_LIST)\ndef generic_never_op(call_node: \"relay.Call\", mixed_precision_type: str) -> List:\n    return [MIXED_PRECISION_NEVER] + get_generic_out_dtypes(call_node, mixed_precision_type)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/recast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Relay type recasting pass\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.ir import IRModule\nfrom .transform import InferType\nfrom ..analysis import count_layers\nfrom ..expr_functor import ExprMutator, Call\n\n\nclass RecastMutator(ExprMutator):\n    \"\"\"Cast operations to the target type.\"\"\"\n\n    def __init__(self, dtype, out_dtype, valid_ops, valid_op_count, skip_layers):\n        self.dtype = dtype\n        self.out_dtype = out_dtype\n        self.depth_count = 0\n        self.valid_ops = [relay.op.get(op) for op in valid_ops]\n        self.valid_op_count = valid_op_count\n        self.skip_layers = skip_layers\n        # Convert negative indices to positive ones.\n        for i, layer in enumerate(skip_layers):\n            if layer < 0:\n                skip_layers[i] = self.valid_op_count + layer\n        super().__init__()\n\n    def visit_call(self, call):\n        # Keep track of our current depth and layer count\n        # so we can know whether to skip this layer or not.\n        current_depth = self.depth_count\n        current_layer = self.valid_op_count - current_depth - 1\n        if call.op in self.valid_ops:\n            self.depth_count += 1\n        # Visit current call operation\n        new_fn = self.visit(call.op)\n        # Visit current arguments\n        args = []\n        for arg in call.args:\n            args.append(self.visit(arg))\n            self.depth_count = current_depth\n\n        # Downcast this op if its the correct type and not skipped.\n        if call.op in self.valid_ops and current_layer not in self.skip_layers:\n            # Recast inputs to specified type.\n            if call.op == relay.op.get(\"concatenate\"):\n                if len(call.args) != 1 or not isinstance(call.args[0], relay.expr.Tuple):\n                    return Call(new_fn, args, call.attrs)\n\n                tuple_args = [self.visit(arg) for arg in call.args[0].fields]\n                new_args = list()\n                for arg in tuple_args:\n                    new_args.append(relay.cast(arg, dtype=self.dtype))\n                new_args = [relay.expr.Tuple(new_args)]\n            else:\n                args = [self.visit(arg) for arg in call.args]\n                new_args = list()\n                for arg in args:\n                    new_args.append(relay.cast(arg, dtype=self.dtype))\n\n            # If out_dtype is in the attributes, we need to update it.\n            orig_dtype = None\n            if call.attrs is not None and \"out_dtype\" in call.attrs.keys():\n                new_attr_dict = {}\n                for attr in call.attrs.keys():\n                    attr_value = call.attrs[attr]\n                    if isinstance(attr_value, tvm.ir.container.Array):\n                        attr_value = tuple(attr_value)\n                    new_attr_dict[str(attr)] = attr_value\n                new_attr_dict[\"out_dtype\"] = self.out_dtype\n                attr_type = str(call.attrs).split(\"(\")[0]\n                new_attrs = tvm.ir.make_node(attr_type, **new_attr_dict)\n                if call.attrs[\"out_dtype\"] != \"\":\n                    orig_dtype = call.attrs[\"out_dtype\"]\n            else:\n                new_attrs = call.attrs\n\n            if orig_dtype is None:\n                # Perform type inference to determine the original type.\n                new_mod = IRModule.from_expr(call)\n                new_mod = InferType()(new_mod)\n                checked_arg = new_mod[\"main\"].body\n                orig_dtype = checked_arg.checked_type.dtype\n            # Recast the output for compatibility with other graph operations.\n            return relay.cast(Call(new_fn, new_args, new_attrs), orig_dtype)\n\n        # Otherwise return the unchanged call.\n        return Call(new_fn, args, call.attrs)\n\n\ndef recast(expr, dtype, out_dtype, ops=None, skip_layers=None):\n    \"\"\"Convert the types of operations in a graph to a new value.\n    Note that this is primarily useful for testing performance of individual\n    operations at the new datatype. In a real setting, this pass will\n    almost certainly do a poor job converting from one datatype to another\n    as it just applies hard casting. For example, when recasting from float\n    to integer, many small values will simply be set to 0. Although this will\n    allow autotuning and benchmarking to produce proper timings at the new\n    data type, the output of the model will of course be heavily impacted.\n\n    Parameters\n    ---------\n    expr: tvm.relay.Expr, tvm.relay.Function, or tvm.ir.IRModule\n        The original function that will have its type changed.\n    dtype: str\n        The target type to cast to.\n    out_dtype: str\n        The output type to cast to.\n    ops: List[str]\n        A list of operations that should have their type changed,\n        others will be left as is.\n    skip_layers: List[int]\n        A list of integers indicating operations that should\n        not have their type changed, counted starting with the\n        first valid operation encountered. Negative indices are\n        allowed and indicate starting at the last layer.\n    Returns\n    -------\n    output_expr : tvm.relay.Expr, tvm.relay.Function, or tvm.ir.IRModule\n        The graph after recasting to the specified datatype.\n    \"\"\"\n    return_mod = False\n    if isinstance(expr, tvm.ir.IRModule):\n        expr = expr[\"main\"]\n        return_mod = True\n    if ops is None:\n        ops = [\"nn.conv2d\"]\n    if skip_layers is None:\n        skip_layers = []\n    layer_depth = count_layers(expr, ops)\n    recast_pass = RecastMutator(dtype, out_dtype, ops, layer_depth, skip_layers)\n    expr = recast_pass.visit(expr)\n    if return_mod:\n        return tvm.IRModule.from_expr(expr)\n    return expr\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/transform/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, missing-docstring, unused-import\n\"\"\"\nRelay pass transformation infrastructure.\n\"\"\"\nimport functools\nimport inspect\nimport types\nimport warnings\n\nimport tvm.ir\nfrom tvm import relay, te\nfrom tvm.runtime import ndarray as _nd\n\nfrom ..backend.utils import mangle_module_name\nfrom . import _ffi_api\n\n\ndef build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None):\n    \"\"\"Configure the build behavior by setting config variables. This function\n    will be deprecated in TVM v0.7. Instead, we should directly use\n    tvm.transform.PassContext.\n\n    Parameters\n    ----------\n    opt_level: int, optional\n        Optimization level. The optimization pass name and level are as the\n        following:\n\n        .. code-block:: python\n\n            OPT_PASS_LEVEL = {\n                \"SimplifyInference\": 0,\n                \"OpFusion\": 1,\n                \"FoldConstant\": 2,\n                \"FoldScaleAxis\": 3,\n                \"AlterOpLayout\": 3,\n                \"CanonicalizeOps\": 3,\n                \"CanonicalizeCast\": 3,\n                \"EliminateCommonSubexpr\": 3,\n                \"CombineParallelConv2D\": 4,\n                \"CombineParallelDense\": 4,\n                \"CombineParallelBatchMatmul\": 4,\n                \"FastMath\": 4\n            }\n\n    required_pass: set of str, optional\n        Optimization passes that are required regardless of optimization level.\n\n    disabled_pass: set of str, optional\n        Optimization passes to be disabled during optimization.\n\n    trace: Callable[[IRModule, PassInfo, bool], None]\n        A tracing function for debugging or introspection.\n\n    Returns\n    -------\n    pass_context: PassContext\n        The pass context for optimizations.\n    \"\"\"\n    warnings.warn(\n        \"relay.build_config will be deprecated. Please use \\\n                  tvm.transform.PassContext directly\",\n        DeprecationWarning,\n    )\n    return tvm.transform.PassContext(opt_level, required_pass, disabled_pass, trace)\n\n\n@tvm._ffi.register_object(\"relay.FunctionPass\")\nclass FunctionPass(tvm.ir.transform.Pass):\n    \"\"\"A pass that works on each tvm.relay.Function in a module. A function\n    pass class should be created through `function_pass`.\n    \"\"\"\n\n\ndef InferType():\n    \"\"\"Infer the type of an expr.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered type inference pass.\n    \"\"\"\n    return _ffi_api.InferType()\n\n\ndef InferTypeLocal(expr):\n    \"\"\"Infer the type of a single expr, reusing type information to do so.\n\n    This populates the checked_type field in expr. We assume existing type information\n    in the graph is correct!\n\n    Parameters\n    ----------\n    expr: relay.Expr\n        The expression we want to know the type of\n\n    Returns\n    -------\n    type: relay.Type\n        The type of the expression\n    \"\"\"\n    return _ffi_api.InferTypeLocal(expr)\n\n\ndef FoldScaleAxis():\n    \"\"\"Fold the scaling of axis into weights of conv2d/dense. This pass will\n    invoke both forward and backward scale folding.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass to fold expressions.\n\n    Note\n    ----\n    Internally, we will call backward_fold_scale_axis before using\n    forward_fold_scale_axis as backward folding targets the common conv->bn\n    pattern.\n    \"\"\"\n    return _ffi_api.FoldScaleAxis()\n\n\ndef BackwardFoldScaleAxis():\n    \"\"\"Backward fold axis scaling into weights of conv2d/dense.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass to backward fold expressions.\n\n    Note\n    ----\n    It is recommended to call backward_fold_scale_axis\n    before using forward_fold_scale_axis as backward folding targets the common\n    conv->bn pattern.\n    \"\"\"\n    return _ffi_api.BackwardFoldScaleAxis()\n\n\ndef RemoveUnusedFunctions(entry_functions=None):\n    \"\"\"Remove unused global relay functions in a relay module.\n\n    Parameters\n    ----------\n    entry_functions: list[string]\n        The set of entry functions to start from.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass to remove unused functions.\n    \"\"\"\n    if entry_functions is None:\n        entry_functions = [\"main\"]\n    return _ffi_api.RemoveUnusedFunctions(entry_functions)\n\n\ndef ForwardFoldScaleAxis():\n    \"\"\"Fold the scaling of axis into weights of conv2d/dense.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass to forward fold expressions.\n\n    Note\n    ----\n    It is recommended to call backward_fold_scale_axis\n    before using forward_fold_scale_axis, as backward folding targets the\n    common conv->bn pattern.\n    \"\"\"\n    return _ffi_api.ForwardFoldScaleAxis()\n\n\ndef SimplifyInference():\n    \"\"\"Simplify the data-flow graph for inference phase. An simplified expression\n    which is semantically equal to the input expression will be returned.\n\n    Note that batch norms will only be simplified if their result is indexed at\n    tuple index 0.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass to perform operator simplification.\n\n    \"\"\"\n    return _ffi_api.SimplifyInference()\n\n\ndef FastMath():\n    \"\"\"Converts the expensive non linear functions to their fast but approximate counterparts.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass to perform fast math operations.\n    \"\"\"\n    return _ffi_api.FastMath()\n\n\ndef CanonicalizeOps():\n    \"\"\"Canonicalize special operators to basic operators.\n    This can simplify followed analysis, e.g. expanding bias_add to\n    expand_dims and broadcast_add.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass performing the canonicalization.\n    \"\"\"\n    return _ffi_api.CanonicalizeOps()\n\n\ndef DeadCodeElimination(inline_once=False, ignore_impurity=False):\n    \"\"\"Remove expressions that do not have any users (dead code).\n\n    Parameters\n    ----------\n    inline_once: Optional[Bool]\n        Whether to inline a binding that is referenced exactly once.\n    ignore_impurity: Optional[Bool]\n        Whether to ignore possible side-effects in let-bound expressions.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that eliminates the dead code in a Relay program.\n    \"\"\"\n    return _ffi_api.DeadCodeElimination(inline_once, ignore_impurity)\n\n\ndef LazyGradientInit():\n    \"\"\"Reduces memory usage of gradient tensors\n\n    Parameters\n    ----------\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        A pass which delays and/or reduces memory allocation,\n        by lazily allocating 0 or one filled tensors.\n    \"\"\"\n    return _ffi_api.LazyGradientInit()\n\n\ndef FoldConstantExpr(expr, mod, fold_qnn=False):\n    \"\"\"Fold the constant expressions in a Relay program.\n    Parameters\n    ----------\n    expr: Expr\n        The expression to fold\n    mod: IRModule\n        The module the expr lives in (for global calls)\n    fold_qnn: bool\n        Whether to fold constants for QNN operations.\n\n    Returns\n    -------\n    new_expr: Expr\n        The expr after Constant Folding\n    \"\"\"\n    return _ffi_api.FoldConstantExpr(expr, mod, fold_qnn)\n\n\ndef FoldConstant(fold_qnn=False):\n    \"\"\"Fold the constant expressions in a Relay program.\n\n    Because of backward compatibility reason it skips QNN primitives from folding by default.\n    There are some transformation passes like FakeQuantizationToInteger, which requires to keep QNN\n    primitives for constant subgraphs. Uncontrolled constant folding of QNN primitives may break\n    applicability of FakeQuantizationToInteger. We suggest to use FoldConstant pass with none\n    default fold_qnn=True value only when all other QNN sensitive passes were already applied.\n\n    Parameters\n    ----------\n    fold_qnn: bool\n        Whether to fold constants for QNN operations.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass for constant folding.\n    \"\"\"\n    return _ffi_api.FoldConstant(fold_qnn)\n\n\ndef FuseOps(fuse_opt_level=-1):\n    \"\"\"Fuse operators in an expr to a larger operator according to some rules.\n\n    Parameters\n    ----------\n    fuse_opt_level : int\n        The level of fuse optimization. -1 indicates that the level will be\n        inferred from pass context.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass for operator fusion.\n    \"\"\"\n    return _ffi_api.FuseOps(fuse_opt_level)\n\n\ndef DefuseOps():\n    \"\"\"The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the\n    program before FuseOps. (i.e., x == DefuseOps(FuseOps(x)))\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass for operator defusion.\n    \"\"\"\n    return _ffi_api.DefuseOps()\n\n\ndef CombineParallelConv2D(min_num_branches=3):\n    \"\"\"Combine multiple conv2d operators into one.\n\n    Parameters\n    ----------\n    min_num_branches : int\n        The minimum number of required parallel branches for performing this\n        optimization.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that combines parallel conv2d operators.\n    \"\"\"\n    return _ffi_api.CombineParallelConv2D(min_num_branches)\n\n\ndef CombineParallelDense(min_num_branches=3, to_batch=True):\n    \"\"\"Combine multiple dense operators into one. For example:\n\n    .. code-block\n                    data\n            /              \\\n        dense (2,2)         dense (2,2)\n            |                 |\n        elemwise/bcast (2,2)  elemwise/bcast (2,2)\n\n    Would become:\n\n    .. code-block\n\n                data\n                |\n            batch_matmul+elemwise/bcast (2,2,2)\n\n    or (if to_batch=False)\n\n    .. code-block\n\n                data\n                |\n            dense+elemwise/bcast (2,2+2)\n\n    Parameters\n    ----------\n    min_num_branches : int\n        The minimum number of required parallel branches for performing this\n        optimization.\n\n    to_batch_matmul : bool\n        If True, combine parallel dense ops into batch_matmul op.\n        If False, combine parallel dense ops into dense op.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that combines parallel dense operators.\n    \"\"\"\n    return _ffi_api.CombineParallelDense(min_num_branches, to_batch)\n\n\ndef CombineParallelBatchMatmul(min_num_branches=3):\n    \"\"\"Combine multiple batch matmul operators into one. For example:\n\n    .. code-block\n                             data (1, 2, 3)\n                         /                  \\\n        batch_matmul(data, (1, 4, 3))    batch_matmul(data, (1, 5, 3))\n            |                                |\n        elemwise/bcast (1, 2, 4)         elemwise/bcast (1, 2, 5)\n\n    Would become:\n\n    .. code-block\n\n                data (1, 2, 3)\n                |\n            batch_matmul(data, (1, 4+5, 3))\n                |\n            elemwise/bcast (1 ,2, 4+5)\n\n    Parameters\n    ----------\n    min_num_branches : int\n        The minimum number of required parallel branches for performing this\n        optimization.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that combines parallel dense operators.\n    \"\"\"\n    return _ffi_api.CombineParallelBatchMatmul(min_num_branches)\n\n\ndef BatchingOps():\n    \"\"\"Batching parallel operators into one for Conv2D, Dense and BatchMatmul.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The sequential pass which apply batching for different operator types.\n    \"\"\"\n    return tvm.transform.Sequential(\n        [CombineParallelConv2D(), CombineParallelDense(), CombineParallelBatchMatmul()]\n    )\n\n\ndef AlterOpLayout():\n    \"\"\"Alternate the layouts of operators or replace primitive operators with\n    other expressions.\n    This pass can be used for computing convolution in custom layouts or\n    other general weight pre-transformation.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that alters the layout of operators.\n    \"\"\"\n    return _ffi_api.AlterOpLayout()\n\n\nclass LayoutConfig(object):\n    \"\"\"A structure for customizing the ConvertLayout pass.\"\"\"\n\n    current = None\n\n    def __init__(self, skip_layers=None):\n        self.skip_counter = 0\n        self.skip_layers = skip_layers if skip_layers is not None else []\n\n    def check_skip(self):\n        skip = self.skip_counter in self.skip_layers\n        self.skip_counter += 1\n        return skip\n\n    def reset(self):\n        self.skip_counter = 0\n        self.skip_layers = []\n\n    def __enter__(self):\n        self._old_manager = LayoutConfig.current\n        LayoutConfig.current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        LayoutConfig.current = self._old_manager\n\n\ndef ConvertLayout(desired_layouts):\n    \"\"\"Given a dest layout, this pass transforms the expr such that most of the ops input data\n    layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms,\n    one at the start and one at the end.\n\n    This pass is not a part of relay.build and is expected to be called between framework-relay\n    parser and relay.build call. This is very helpful for hardware backends that support/prefer only\n    type of data layout.\n\n    RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009\n\n    This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define\n    new layouts for conv2d ops for now. Most of the other operators try to adapt to their input\n    layout using the InferCorrectLayout infrastructure.\n\n    Parameters\n    ----------\n    desired_layouts : map of op_name to list of layouts\n        Specify a mapping of operator names to a list of layouts to convert to, in the order\n        defined by the operator. An example for nn.conv2d could be: {\"nn.conv2d\", [\"NHWC\", \"OHWI]},\n        where the first item in the list specifies the data layout and the second specifies the\n        kernel layout.\n\n    Returns\n    -------\n    pass: FunctionPass\n      The pass.\n    \"\"\"\n    return _ffi_api.ConvertLayout(desired_layouts)\n\n\ndef Legalize(legalize_map_attr_name=\"FTVMLegalize\"):\n    \"\"\"Legalizes an expression with another expression.\n    This pass can be used to replace an expr with another expr for target\n    dependent optimizations. For example, one expr, though semnatically\n    equivalent to the other, can have better performance on a target. This pass\n    can be used to legalize the expr in a target-dependent manner.\n\n    Parameters\n    ----------\n    legalize_map_attr_name : str\n        The Op's attr name which corresponds to the legalize rule function.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that rewrites an expr.\n    \"\"\"\n    return _ffi_api.Legalize(legalize_map_attr_name)\n\n\ndef MergeComposite(pattern_table):\n    \"\"\"Merge multiple operators into a single composite relay function.\n\n    Parameters\n    ----------\n    pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]]\n        A list of (pattern_name, pattern, check) tuples.\n        The order of the patterns in the list will determine the order\n        of priority in which they are matched.\n        'check' is a function to check whether an extracted pattern matches.\n        It can be implemented by pattern writer but if not specified it will\n        always return True.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that merges operators into a single composite\n        relay function.\n    \"\"\"\n    pattern_names = []\n    patterns = []\n    checks = []\n    for tup in pattern_table:\n        if len(tup) == 2:\n            pattern_name, pattern = tup\n            check = lambda extract: True\n        elif len(tup) == 3:\n            pattern_name, pattern, check = tup\n\n        pattern_names.append(pattern_name)\n        patterns.append(pattern)\n        checks.append(check)\n\n    return _ffi_api.MergeComposite(pattern_names, patterns, *checks)\n\n\ndef MergeCompilerRegions():\n    \"\"\"Merge together compiler regions.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that merges compiler regions.\n    \"\"\"\n    return _ffi_api.MergeCompilerRegions()\n\n\ndef ToANormalForm():\n    \"\"\"Turn Graph Normal Form expression into A Normal Form Expression.\n    The scope of the root expression is the global scope.\n    The scope of any non root expression is the least common ancestor of all it's scope.\n    Values are ordered by post-DFS order in each scope.\n\n    Returns\n    -------\n    ret : Union[tvm.transform.Pass, tvm.relay.Expr]\n        The registered pass that transforms an expression into A Normal Form.\n    \"\"\"\n    return _ffi_api.ToANormalForm()\n\n\ndef ToANormalFormExpr(e):\n    \"\"\"ToANormalForm, but on expression level.\n\n    Parameters\n    ----------\n    e : Expr\n        The graph expression.\n\n    Returns\n    -------\n    ret : Expr\n        The transformed expresion.\n    \"\"\"\n    return _ffi_api.ToANormalFormExpr(e)\n\n\ndef ToBasicBlockNormalForm():\n    \"\"\"Turn an expression to Basic Block Normal Form.\n    We define a block as a group of expressions implied by the scope structure.\n    Each graph node can only belong to a single block.\n    For any value that is being used in multiple blocks, it has to be referred\n    by a Var which is defined in a block, whose scope is the least common ancestor\n    of blocks this value is used.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that transforms an expression into Basic Block Normal Form.\n    \"\"\"\n    return _ffi_api.ToBasicBlockNormalForm()\n\n\ndef ToCPS(expr, mod=None):\n    \"\"\"\n    Turn expression into continuation passing style(CPS).\n\n    Every intermediate compute will be passed to a continuation.\n\n    Returns\n    -------\n    result: tvm.transform.Pass\n        The registered pass that transforms an expression into CPS.\n    \"\"\"\n    return _ffi_api.to_cps(expr, mod)\n\n\ndef EtaExpand(expand_constructor=False, expand_global_var=False):\n    \"\"\"Add abstraction over a constructor or global variable bound to a function\n\n    Parameters\n    ----------\n    expand_constructor: bool\n        Whether to expand constructors.\n\n    expand_global_var: bool\n        Whether to expand global variables.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that eta expands an expression.\n    \"\"\"\n    return _ffi_api.EtaExpand(expand_constructor, expand_global_var)\n\n\ndef ToGraphNormalForm():\n    \"\"\"Turn a Relay program in A Normal Form into Graph Normal Form\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that transforms an expression into Graph Normal Form.\n    \"\"\"\n    return _ffi_api.ToGraphNormalForm()\n\n\ndef EliminateCommonSubexpr(fskip=None):\n    \"\"\"Eliminate common subexpressions.\n\n    Parameters\n    ----------\n    fskip: Callable\n        The callback function that decides whether an expression should be\n        skipped.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that eliminates common subexpressions.\n    \"\"\"\n    return _ffi_api.EliminateCommonSubexpr(fskip)\n\n\ndef PartialEvaluate():\n    \"\"\"Evaluate the static fragment of the code.\n\n    Note\n    ----\n    This transformation could be either `Module -> Module` or `Expr -> Expr`.\n    It will directly transform the input expression to a new one if the target\n    expression is provided. Otherwise, it will rely on the pass manager to\n    carry out transformation.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that performs partial evaluation on an expression.\n    \"\"\"\n    return _ffi_api.PartialEvaluate()\n\n\ndef CanonicalizeCast():\n    \"\"\"\n    Canonicalize cast expressions to make operator fusion more efficient.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that canonicalizes cast expression.\n    \"\"\"\n    return _ffi_api.CanonicalizeCast()\n\n\ndef LambdaLift():\n    \"\"\"\n    Lift the closure to global function.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass that lifts the lambda function.\n    \"\"\"\n    return _ffi_api.LambdaLift()\n\n\ndef PartitionGraph(mod_name=\"default\", bind_constants=True):\n    \"\"\"Partition a Relay program into regions that can be executed on different\n    backends.\n\n    Parameters\n    ----------\n    mod_name : string\n        Controls the prefix of the name of each partitioned subraph.\n        If `mod_name` is None, then `tvmgen_` prefix is used.\n        Otherwise, `tvmgen_mod_name_` prefix is used.\n\n    bind_constants: bool\n        Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs\n        to maintain the bound constants; Otherwise the constants will be maintained by\n        the metadata module. So it is recommended for C-source based codegens to\n        set bind_constants=False to avoid embedding large constants in a C source file.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that partitions the Relay program.\n    \"\"\"\n    mod_name = mangle_module_name(mod_name)\n    return _ffi_api.PartitionGraph(mod_name, bind_constants)\n\n\ndef AnnotateTarget(targets, include_non_call_ops=True):\n    \"\"\"Annotate ops in an experession with a provied compiler/target and then\n    use it for codegen.\n\n    Parameters\n    ----------\n    targets : str or List[str]\n        The list of target compilers used for codegen.\n    include_non_call_ops : boolean\n        If True then non-call ops also will be annotated with targets\n        If False then non-call ops will not be processed\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The annotated pass that wrapps ops with subgraph_start and\n        subgraph_end.\n    \"\"\"\n    if isinstance(targets, str):\n        targets = [targets]\n    return _ffi_api.AnnotateTarget(\n        [tvm.runtime.container.String(t) for t in targets], include_non_call_ops\n    )\n\n\ndef DynamicToStatic():\n    \"\"\"If possible, convert tvm.relay.dynamic* ops to static versions\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass for dynamic->static conversion.\n    \"\"\"\n    return _ffi_api.DynamicToStatic()\n\n\ndef Inline():\n    \"\"\"Perform inlining on the given Relay IR module. The global functions that\n    are marked as `inline` should be always inlined. A cost model will be\n    needed in the future to decide if it is profitable to inline the function.\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that performs inlining for a Relay IR module.\n    \"\"\"\n    return _ffi_api.Inline()\n\n\ndef gradient(expr, mod=None, mode=\"higher_order\"):\n    \"\"\"\n    Transform the input function,\n    returning a function that calculate the original result,\n    paired with gradient of the input.\n\n    Parameters\n    ----------\n    expr : tvm.relay.Expr\n        The input expression, which is a Function or a GlobalVar.\n\n    mod : Optional[tvm.IRModule]\n\n    mode : Optional[String]\n        The mode of the automatic differentiation algorithm.\n        'first_order' only works on first order code, but will not produce\n        reference nor closure.\n        'higher_order' works on all code using reference and closure.\n\n    Returns\n    -------\n    expr : tvm.relay.Expr\n      The transformed expression.\n    \"\"\"\n    if mode == \"first_order\":\n        warnings.warn(\n            \"using transform.gradient for first-order AD is deprecated, please use the\"\n            \"FirstOrderGradient module pass\",\n            DeprecationWarning,\n        )\n        if mod is not None:\n            raise RuntimeError(\n                \"to run first-order AD on a module, please use the FirstOrderGradient module pass.\"\n            )\n        return FirstOrderGradient()(tvm.IRModule.from_expr(expr))[\"main\"]\n    if mode == \"higher_order\":\n        return _ffi_api.gradient(expr, mod)\n    raise Exception(\"unknown mode\")\n\n\ndef FirstOrderGradient():\n    \"\"\"\n    Transforms all global functions in the module to return the original result, paired with the\n    gradients of the inputs. This pass transforms each global function independently and does not\n    support interprocedural AD. Additionally, this pass does not support any control-flow or\n    references, and should only be used on pure data-flow graphs.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered FirstOrderGradient pass.\n    \"\"\"\n    return _ffi_api.FirstOrderGradient()\n\n\ndef Defunctionalization(func, mod):\n    \"\"\"\n    Performs defunctionalization on func,\n    transforming func from a higher-order program to a first-order program.\n\n    At each call site, the function is cloned and type parameters are substituted in.\n    Function arguments are encoded as datatypes\n    and additional apply functions are used for application.\n\n    Parameters\n    ----------\n    func : tvm.relay.Function\n        The input function, which should not be polymorphic or be higher-order.\n        This is because all types must be known and we can't encode function arguments\n        to the program itself.\n\n    mod : tvm.IRModule\n        The IRModule containing function and type definitions,\n        which is also mutated during this pass.\n\n    Returns\n    -------\n    expr : tvm.relay.Function\n      The output function.\n    \"\"\"\n    return _ffi_api.Defunctionalization(func, mod)\n\n\ndef to_cps(func, mod=None):\n    \"\"\"\n    Turn expression into CPS expression.\n\n    Every intermediate compute will be passed to a continuation.\n\n    Parameters\n    ----------\n    func: tvm.relay.Function\n        The input function.\n\n    mod: Optional[tvm.IRModule]\n        The global module.\n\n    Returns\n    -------\n    result: tvm.relay.Function\n      The output function.\n    \"\"\"\n    use_mod = mod if mod is not None else tvm.ir.IRModule()\n    return _ffi_api.to_cps(func, use_mod)\n\n\ndef un_cps(func):\n    \"\"\"\n    Turn an cps function into a Function without the continuation argument.\n\n    Note that this will not give the exact same interface as before cps:\n      If the input/output is higher order, they will still be in cps form.\n\n    Parameters\n    ----------\n    func: tvm.relay.Function\n        The input function\n\n    Returns\n    -------\n    result: tvm.relay.Function\n        The output function\n    \"\"\"\n    return _ffi_api.un_cps(func)\n\n\ndef _wrap_class_function_pass(pass_cls, pass_info):\n    \"\"\"Wrap a python class as function pass\"\"\"\n\n    class PyFunctionPass(FunctionPass):\n        \"\"\"Internal wrapper class to create a class instance.\"\"\"\n\n        def __init__(self, *args, **kwargs):\n            # initialize handle in cass pass_cls creation failed.fg\n            self.handle = None\n            inst = pass_cls(*args, **kwargs)\n\n            # it is important not to capture self to\n            # avoid a cyclic dependency\n            def _pass_func(func, mod, ctx):\n                return inst.transform_function(func, mod, ctx)\n\n            self.__init_handle_by_constructor__(_ffi_api.MakeFunctionPass, _pass_func, pass_info)\n            self._inst = inst\n\n        def __getattr__(self, name):\n            # fall back to instance attribute if there is not any\n            return self._inst.__getattribute__(name)\n\n    functools.update_wrapper(PyFunctionPass.__init__, pass_cls.__init__)\n    PyFunctionPass.__name__ = pass_cls.__name__\n    PyFunctionPass.__doc__ = pass_cls.__doc__\n    PyFunctionPass.__module__ = pass_cls.__module__\n    return PyFunctionPass\n\n\ndef function_pass(pass_func=None, opt_level=None, name=None, required=None):\n    \"\"\"Decorate a function pass.\n\n    This function returns a callback when pass_func\n    is provided. Otherwise, it returns the created function pass using the\n    given optimization function.\n\n    Parameters\n    ----------\n    pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]]\n        The transformation function or class.\n\n    opt_level : int\n        The optimization level of this module pass.\n\n    name : Optional[str]\n        The name of the function pass. The name could be empty. In this case, the\n        name of the optimization function will be used as the pass name.\n\n    required : Optional[List[str]]\n        The list of passes that the module pass is dependent on.\n\n    Returns\n    -------\n    create_function_pass : Union[Callable, FunctionPass]\n\n        A decorator will be returned if pass_func is not provided,\n        otherwise return the decorated result.\n        The returned decorator has two behaviors depending on the input:\n        A new FunctionPass will be returned when we decorate a pass function.\n        A new FunctionPass class will be returned when we decorate a class type.\n\n    Examples\n    --------\n    The following code block decorates a function pass class.\n\n    .. code-block:: python\n\n        @relay.transform.function_pass(opt_level=1)\n        class TestReplaceFunc:\n            def __init__(self, new_func):\n                self.new_func = new_func\n\n            def transform_function(self, func, mod, ctx):\n                # just for demo purposes\n                # transform func to new_func\n                return self.new_func\n\n        x = relay.var(\"x\", shape=(10, 20))\n        f1 = relay.Function([x], x)\n        f2 = relay.Function([x], relay.log(x))\n        # fpass is now a special pass that replaces every\n        # function to f1\n        fpass = TestReplaceFunc(f1)\n        # now every function in input_mod is replaced by f1\n        res_mod = fpass(input_mod)\n\n\n    The following code creates a function pass by decorating\n    a user defined transform function.\n\n    .. code-block:: python\n\n        @relay.transform.function_pass(opt_level=2)\n        def transform(func, mod, ctx):\n            # my transformations here.\n            return func\n\n        function_pass = transform\n        assert isinstance(function_pass, transform.FunctionPass)\n        assert function_pass.info.opt_level == 2\n\n        # Given a module m, the optimization could be invoked as the follwoing:\n        updated_mod = function_pass(m)\n        # Now constant folding should have been applied to every function in\n        # the provided module m. And the updated module will be returned.\n    \"\"\"\n\n    if opt_level is None:\n        raise ValueError(\"Please provide opt_level for the function pass.\")\n\n    required = required if required else []\n    if not isinstance(required, (list, tuple)):\n        raise TypeError(\"Required is expected to be the type of \" + \"list/tuple.\")\n\n    def create_function_pass(pass_arg):\n        \"\"\"Internal function that creates a function pass\"\"\"\n        fname = name if name else pass_arg.__name__\n        info = tvm.transform.PassInfo(opt_level, fname, required)\n        if inspect.isclass(pass_arg):\n            return _wrap_class_function_pass(pass_arg, info)\n        if not isinstance(pass_arg, (types.FunctionType, types.LambdaType)):\n            raise TypeError(\"pass_func must be a callable for Module pass\")\n        return _ffi_api.MakeFunctionPass(pass_arg, info)\n\n    if pass_func:\n        return create_function_pass(pass_func)\n    return create_function_pass\n\n\n@function_pass(opt_level=1)\nclass ChangeBatch:\n    \"\"\"\n    Change the batch size.\n\n    Parameters\n    ----------\n    data: Dict[relay.Var, int]\n      A dictionary of all the params to change.\n      The keys are all params, and the values are which dimension hold the batch.\n\n    batch_size: int\n      The batch size to change to.\n\n    Returns\n    -------\n    pass: FunctionPass\n      The pass.\n    \"\"\"\n\n    def __init__(self, data, batch_size=16):\n        self.data = data\n        self.batch_size = batch_size\n\n    def transform_function(self, func, mod, ctx):\n        func = relay.Function(func.params, func.body, None, func.type_params, func.attrs)\n        change_batch = self\n\n        class ChangeBatchMutator(tvm.relay.ExprMutator):\n            def visit_var(self, var):\n                if var in change_batch.data:\n                    ty = var.type_annotation\n                    new_shape = list(ty.shape)\n                    new_shape[change_batch.data[var]] = change_batch.batch_size\n                    return relay.Var(var.name_hint, relay.TensorType(new_shape, ty.dtype))\n                return var\n\n        return ChangeBatchMutator().visit(func)\n\n\ndef DenseToSparse(weight_name, weight_shape):\n    \"\"\"\n    Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense```\n    This pass is used in ```data_dep_optimization.bsr_dense```\n    Parameters of this pass is generated by ```analysis.sparse_dense.process_params```\n\n    Parameters\n    ----------\n    weight_name: Array[String]\n      Names of weights which qualified sparse contrains\n\n    weight_shape: Array[Array[IntImm]]\n      Weights shape in BSR format.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered DenseToSparse pass.\n    \"\"\"\n    return _ffi_api.DenseToSparse(weight_name, weight_shape)\n\n\ndef Conv2dToSparse(weight_name, weight_shape, layout, kernel_size):\n    \"\"\"\n    Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d```\n\n    Parameters\n    ----------\n    weight_name: Array[String]\n      Names of weights which qualified sparse contrains\n\n    weight_shape: Array[Array[IntImm]]\n      Weights shape in BSR format.\n\n    layout : str\n        layout of data\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered DenseToSparse pass.\n    \"\"\"\n    return _ffi_api.Conv2dToSparse(weight_name, weight_shape, layout, kernel_size)\n\n\ndef Conv2dToSparse2(layout, kernel_size, blocksize, sparsity_threshold):\n    \"\"\"\n    Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d```\n\n    Parameters\n    ----------\n    layout : str\n        layout of data\n\n    kernel_size : int\n        kernel size of conv2d\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered DenseToSparse pass.\n    \"\"\"\n    return _ffi_api.Conv2dToSparse2(layout, kernel_size, *blocksize, sparsity_threshold)\n\n\ndef SimplifyFCTranspose(target_weight_name):\n    \"\"\"\n    Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)```\n    This pass is used in ```data_dep_optimization.simplify_fc_transpose```\n\n    Parameters\n    ----------\n    weight_name: Array[String]\n      Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))```\n      This parameter is generated by ```analysis.search_fc_transpose``` function\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered SimplifyFCTranspose pass.\n    \"\"\"\n    return _ffi_api.SimplifyFCTranspose(target_weight_name)\n\n\ndef SimplifyExpr():\n    \"\"\"\n    Simplify the Relay expression, including merging consecutive reshapes.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered SimplifyExpr pass.\n    \"\"\"\n    return _ffi_api.SimplifyExpr()\n\n\ndef PlanDevices(config):\n    \"\"\"\n    Uses existing \"on_device\" and \"device_copy\" calls to infer the virtual device on which\n    every Relay sub-expression should run and the result stored. Captures the result of that\n    analysis using new \"on_device\" and \"device_copy\" calls. Sub-expressions which are\n    not otherwise constrained are assigned to the default primitive virtual device describe by\n    config. However data and computations which must be hosted on a CPU (such as shapes and\n    shape functions) use the host virtual device of the config.\n\n    Parameters\n    ----------\n    config : tvm.CompilationConfig\n        The compilation configuration, specifying available targets and default devices.\n\n    Returns\n    -------\n    ret : tvm.transforms.Pass\n        The pass.\n    \"\"\"\n    return _ffi_api.PlanDevices(config)\n\n\ndef ManifestLifetimes():\n    \"\"\"\n    Manifest the lifetimes of variables after allocations have been manifested, by inserting kill\n    operations once variables become dead.\n    \"\"\"\n    return _ffi_api.ManifestLifetimes()\n\n\ndef FoldExplicitPadding():\n    \"\"\"\n    FoldExplicitPadding finds explict padding before an op that can support\n    implicit padding and fuses them.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered ImplicitPadding pass.\n    \"\"\"\n    return _ffi_api.FoldExplicitPadding()\n\n\ndef AnnotateSpans():\n    \"\"\"\n    Annotate a program with span information by first generating its textual\n    representation and then parsing it back into a Relay AST annotated with\n    span information.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered AnnotateSpans pass.\n    \"\"\"\n    return _ffi_api.AnnotateSpans()\n\n\ndef FakeQuantizationToInteger(hard_fail=False, use_qat=False):\n    # pylint: disable=anomalous-backslash-in-string\n    \"\"\"\n    Find regions of the graph of the form\n\n    .. code-block:: text\n\n        x    w\n        |    |\n        dq   dq\n         \\\\   /\n          op1\n           |\n          op2\n           |\n           q\n\n    where ``q == qnn.quantize`` and ``dq = qnn.dequantize``\n    and rewrite them into integer versions of ``op1`` and ``op2``\n\n    Rules for rewriting indivdual ops are in fake_quantization_to_integer.py\n\n    Parameters\n    ----------\n    hard_fail : boolean\n        How do deal with errors during graph rewriting.\n        If true, raise an error.\n        If false, skip rewriting the subgraph.\n\n    use_qat : boolean\n        To perform an additional QAT pass - convert enabled operations with dequantized inputs.\n        Example: in the graph above op2 is not registered with the FakeQuantizationToInteger\n        attribute, op1 operation can still be converted. Converted pattern below:\n\n        .. code-block:: text\n\n            x    w\n            |    |\n            \\\\   /\n              op1\n              |\n              dq\n              |\n              op2\n              |\n              q\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered FakeQuantizationToInteger pass.\n    \"\"\"\n    return _ffi_api.FakeQuantizationToInteger(hard_fail, use_qat)\n\n\ndef FlattenAtrousConv():\n    # pylint: disable=anomalous-backslash-in-string\n    \"\"\"\n    The purpose of this pass is to find a sequence of space_to_batch_nd-conv2d-batch_to_space_nd\n    operations:\n\n    .. code-block:: text\n\n      x     w\n      |     |\n      s2b   |\n       \\\\   /\n        conv2d\n         |\n         b2s\n\n    and convert them into subgraphs with a convolution with the modified \"dilation\" and\n    recalculated \"padding\" parameters.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered FlattenAtrousConv pass.\n    \"\"\"\n    return _ffi_api.FlattenAtrousConv()\n\n\ndef ToMixedPrecision(mixed_precision_type=\"float16\", missing_op_mode=1):\n    \"\"\"\n    Automatic mixed precision rewriter. Rewrite an FP32 relay graph into a version\n    where as many operations as possible are in the target mixed_precision_type.\n\n    Parameters\n    ----------\n    mixed_precision_type: str\n      The target datatype to transform operations in the graph to use.\n\n    missing_op_mode: int\n      Determines how to handle ops not registered with FTVMMixedPrecisionConversionType\n        0: Does not allow any missing ops. Will throw errors when encountering any.\n        1: Allow missing ops but emit warnings.\n        2: Allow missing ops and silently ignore them.\n\n    relay.ToMixedPrecision.keep_orig_output_dtype: boolean\n      Defines if outputs should be retained in original data type or convert to\n      mixed_precision_type. By default this parameter is False and transformation\n      modifies the data types of outputs to mixed_precision_type.\n      This parameter is not part of explicit arguments of the transformation, but should\n      be passed through tvm.transform.PassContext.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass.\n    \"\"\"\n    if missing_op_mode < 0 or missing_op_mode > 2:\n        raise ValueError(\"Missing op mode is either 0, 1, or 2\")\n    return _ffi_api.ToMixedPrecision(mixed_precision_type, missing_op_mode)\n\n\ndef SplitArgs(max_function_args):\n    \"\"\"Split function with huge number of arguments to smaller pieces.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The registered pass for constant folding.\n    \"\"\"\n    return _ffi_api.SplitArgs(max_function_args)\n\n\ndef OutlineCompilerFunctionsWithExistingGlobalSymbols(compiler_filter=\"\"):\n    \"\"\"Outlines all literal functions in direct call positions which have a \"Compiler\"\n    attribute.\n\n    The outlined functions are bound to unique global vars according to their existing\n    \"global_symbol\" attribute. At most one function with the same global symbol is outlined.\n\n    If compiler_filter is non-empty only functions with that as their attribute value are\n    outlined.\n\n    This pass may be useful for external codegen using the \"RelayToTIR\" custom pass mechanism\n    to prepare the IRModule before custom lowering.\n\n    Parameters\n    ----------\n    compiler_filter : String\n        If non-empty, the \"Compiler\" attribute to filter on.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The pass.\n    \"\"\"\n    return _ffi_api.OutlineCompilerFunctionsWithExistingGlobalSymbols(compiler_filter)\n\n\ndef MarkCompilerFunctionsAsExtern(compiler_filter=\"\"):\n    \"\"\"Marks all global functions which have a \"Compiler\" attribute matching\n    compiler_filter as 'extern'.\n\n    The function's attributes are replaced with a single \"Extern\" attribute, and\n    all calls to the function are switched to use the 'call_lowered' calling convention.\n\n    If compiler_filter is non-empty only functions with that as their attribute value are\n    outlined.\n\n    This pass may be useful for external codegen using the \"RelayToTIR\" custom pass mechanism to\n    cleanup the IRModule after custom lowering.\n\n    Parameters\n    ----------\n    compiler_filter : String\n        If non-empty, the \"Compiler\" attribute to filter on.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The pass.\n    \"\"\"\n    return _ffi_api.MarkCompilerFunctionsAsExtern(compiler_filter)\n\n\ndef CapturePostDfsIndexInSpans():\n    \"\"\"Captures the post-dfs index and dominator post-dfs index of (most) expression nodes in\n    their span, in the form \"index:<post-dfs index>:<dominator post-dfs index>\".\n\n    This is useful for debugging since a) it helps identify pretty-printed sub-expressions within\n    the overall model and b) the indexes are heavily used by Collage for its compact representation\n    of sub-graphs.\n\n    Note that Op and Constructor nodes are not changed even though they are assigned an\n    post-dfs index.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The pass.\n    \"\"\"\n    return _ffi_api.CapturePostDfsIndexInSpans()\n\n\ndef InlineCompilerFunctionsBoundTo(global_vars):\n    \"\"\"Inlines all global functions bound to a global var in global_vars.\n\n    Both the global \"Compiler\" attributed function, and any calls to \"Composite\" functions it its\n    body are inlined.\n\n    This pass may be useful for external codegen which needs to undo partitioning based on\n    properties of the entire partition.\n\n    Parameters\n    ----------\n    global_vars : Array[tvm.relay.GlobalVar]\n        The global vars of all 'Compiler' functions to inline.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The pass.\n    \"\"\"\n    return _ffi_api.InlineCompilerFunctionsBoundTo(global_vars)\n\n\ndef CollagePartition(config, cost_estimator=None):\n    \"\"\"Partition the bodies of all functions according to the available targets so as to\n    minimize model latency. See https://github.com/apache/tvm-rfcs/blob/main/rfcs/0062-collage.md.\n\n    Parameters\n    ----------\n    config : CompilationConfig\n        The available targets.\n    cost_estimator : CostEstimator, optional\n        The custom cost estimator to use for costing each candidate partition.\n\n    Returns\n    -------\n    ret : tvm.transform.Pass\n        The pass.\n\n    \"\"\"\n    if cost_estimator is None:\n        cost_estimator = relay.collage.CostEstimator()\n\n    return _ffi_api.CollagePartition(config, cost_estimator)\n\n\ndef DivToMul():\n    \"\"\"Transform division by a constant to multiplication by the inverse of the constant\"\"\"\n    return _ffi_api.DivToMul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/ty.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-import\n\"\"\"The type nodes of the Relay language.\"\"\"\nfrom tvm.ir import Type, TypeKind, TypeVar, GlobalTypeVar\nfrom tvm.ir import TypeConstraint, FuncType, TupleType, IncompleteType\nfrom tvm.ir import TypeCall, TypeRelation, TensorType, RelayRefType as RefType\n\nfrom .base import RelayNode\nfrom . import _ffi_api\n\nAny = _ffi_api.Any\n\n\ndef is_dynamic(tensor_type):\n    \"\"\"Check whether type has any or symbolic variables as a shape.\n\n    tensor_type : Type\n        The type to be inspected\n\n    Returns\n    -------\n    has_any : bool\n        The check result.\n    \"\"\"\n    return _ffi_api.IsDynamic(tensor_type)\n\n\ndef ShapeVar(name):\n    \"\"\"A helper which constructs a type var of which the shape kind.\n\n    Parameters\n    ----------\n    name : str\n\n    Returns\n    -------\n    type_var : tvm.relay.TypeVar\n        The shape variable.\n    \"\"\"\n    return TypeVar(name, kind=TypeKind.ShapeVar)\n\n\ndef scalar_type(dtype):\n    \"\"\"Creates a scalar type.\n\n    This function returns TensorType((), dtype)\n\n    Parameters\n    ----------\n    dtype : str\n        The content data type.\n\n    Returns\n    -------\n    s_type : tvm.relay.TensorType\n        The result type.\n    \"\"\"\n    return TensorType((), dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/relay/type_functor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The type functor of Relay.\"\"\"\nfrom .ty import (\n    TypeVar,\n    IncompleteType,\n    TensorType,\n    FuncType,\n    TupleType,\n    TypeRelation,\n    RefType,\n    GlobalTypeVar,\n    TypeCall,\n)\nfrom .adt import TypeData\n\n\nclass TypeFunctor:\n    \"\"\"\n    An abstract visitor defined over Type.\n\n    Defines the default dispatch over types.\n    \"\"\"\n\n    def __init__(self):\n        # TODO(weberlo): make type vars hashable, so we can memoize\n        pass\n\n    # pylint: disable=no-else-return\n    def visit(self, typ):\n        \"\"\"Apply the visitor to a type.\"\"\"\n        if isinstance(typ, TypeVar):\n            return self.visit_type_var(typ)\n        elif isinstance(typ, IncompleteType):\n            return self.visit_incomplete_type(typ)\n        elif isinstance(typ, TensorType):\n            return self.visit_tensor_type(typ)\n        elif isinstance(typ, FuncType):\n            return self.visit_func_type(typ)\n        elif isinstance(typ, TupleType):\n            return self.visit_tuple_type(typ)\n        elif isinstance(typ, TypeRelation):\n            return self.visit_type_relation(typ)\n        elif isinstance(typ, RefType):\n            return self.visit_ref_type(typ)\n        elif isinstance(typ, GlobalTypeVar):\n            return self.visit_global_type_var(typ)\n        elif isinstance(typ, TypeCall):\n            return self.visit_type_call(typ)\n        elif isinstance(typ, TypeData):\n            return self.visit_type_data(typ)\n        else:\n            raise Exception(\"unhandled case: {0}\".format(type(typ)))\n\n    def visit_type_var(self, _):\n        raise NotImplementedError()\n\n    def visit_incomplete_type(self, _):\n        raise NotImplementedError()\n\n    def visit_tensor_type(self, _):\n        raise NotImplementedError()\n\n    def visit_func_type(self, _):\n        raise NotImplementedError()\n\n    def visit_tuple_type(self, _):\n        raise NotImplementedError()\n\n    def visit_type_relation(self, _):\n        raise NotImplementedError()\n\n    def visit_ref_type(self, _):\n        raise NotImplementedError()\n\n    def visit_global_type_var(self, _):\n        raise NotImplementedError()\n\n    def visit_type_call(self, _):\n        raise NotImplementedError()\n\n    def visit_type_data(self, _):\n        raise NotImplementedError()\n\n\nclass TypeVisitor(TypeFunctor):\n    \"\"\"\n    A visitor over Type.\n\n    The default behavior recursively traverses the AST.\n    \"\"\"\n\n    def visit_type_var(self, tv):\n        pass\n\n    def visit_incomplete_type(self, it):\n        pass\n\n    def visit_tensor_type(self, tt):\n        pass\n\n    def visit_func_type(self, ft):\n        for arg_type in ft.arg_types:\n            self.visit(arg_type)\n        self.visit(ft.ret_type)\n        for type_param in getattr(ft, \"type_params\", []):\n            self.visit(type_param)\n        for type_constraint in getattr(ft, \"type_constraints\", []):\n            self.visit(type_constraint)\n\n    def visit_tuple_type(self, tt):\n        for field in tt.fields:\n            self.visit(field)\n\n    def visit_type_relation(self, tr):\n        for arg in tr.args:\n            self.visit(arg)\n\n    def visit_ref_type(self, rt):\n        self.visit(rt.value)\n\n    def visit_global_type_var(self, gtv):\n        pass\n\n    def visit_type_call(self, tc):\n        self.visit(tc.func)\n        for arg in tc.args:\n            self.visit(arg)\n\n    def visit_type_data(self, td):\n        self.visit(td.header)\n        for type_var in td.type_vars:\n            self.visit(type_var)\n\n\nclass TypeMutator(TypeFunctor):\n    \"\"\"\n    A functional visitor over Type.\n\n    The default behavior recursively traverses the AST\n    and reconstructs the AST.\n    \"\"\"\n\n    def visit_type_var(self, tv):\n        return TypeVar(tv.name_hint, tv.kind)\n\n    def visit_incomplete_type(self, it):\n        return IncompleteType(it.kind)\n\n    def visit_tensor_type(self, tt):\n        return TensorType(tt.shape, tt.dtype)\n\n    def visit_func_type(self, ft):\n        new_arg_types = [self.visit(arg_type) for arg_type in ft.arg_types]\n        new_ret_type = self.visit(ft.ret_type)\n        new_type_params = [self.visit(type_param) for type_param in getattr(ft, \"type_params\", [])]\n        new_type_constraints = [\n            self.visit(type_constraint) for type_constraint in getattr(ft, \"type_constraints\", [])\n        ]\n        return FuncType(new_arg_types, new_ret_type, new_type_params, new_type_constraints)\n\n    def visit_tuple_type(self, tt):\n        return TupleType([self.visit(field) for field in tt.fields])\n\n    def visit_type_relation(self, tr):\n        return TypeRelation(tr.func, [self.visit(arg) for arg in tr.args], tr.num_inputs, tr.attrs)\n\n    def visit_ref_type(self, rt):\n        return RefType(self.visit(rt.value))\n\n    def visit_global_type_var(self, gtv):\n        return GlobalTypeVar(gtv.name_hint, gtv.kind)\n\n    def visit_type_call(self, tc):\n        return TypeCall(self.visit(tc.func), [self.visit(arg) for arg in tc.args])\n\n    def visit_type_data(self, td):\n        return TypeData(\n            self.visit(td.header),\n            [self.visit(type_var) for type_var in td.type_vars],\n            td.constructors,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Lightweight TVM RPC module.\n\nRPC enables connect to a remote server, upload and launch functions.\nThis is useful to for cross-compile and remote testing,\nThe compiler stack runs on local server, while we use RPC server\nto run on remote runtime which don't have a compiler available.\n\nThe test program compiles the program on local server,\nupload and run remote RPC server, get the result back to verify correctness.\n\"\"\"\n\nfrom .server import Server\nfrom .client import connect, connect_tracker\nfrom .client import RPCSession, LocalSession, PopenSession, TrackerSession\nfrom .minrpc import with_minrpc\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.rpc\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"rpc\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Base definitions for RPC.\"\"\"\n# pylint: disable=invalid-name\n\nimport socket\nimport time\nimport json\nimport errno\nimport struct\nimport random\nimport logging\n\nfrom .._ffi.base import py_str\n\n# Magic header for RPC data plane\nRPC_MAGIC = 0xFF271\n# magic header for RPC tracker(control plane)\nRPC_TRACKER_MAGIC = 0x2F271\n# sucess response\nRPC_CODE_SUCCESS = RPC_MAGIC + 0\n# duplicate key in proxy\nRPC_CODE_DUPLICATE = RPC_MAGIC + 1\n# cannot found matched key in server\nRPC_CODE_MISMATCH = RPC_MAGIC + 2\n\nlogger = logging.getLogger(\"RPCServer\")\n\n\nclass TrackerCode(object):\n    \"\"\"Enumeration code for the RPC tracker\"\"\"\n\n    FAIL = -1\n    SUCCESS = 0\n    PING = 1\n    STOP = 2\n    PUT = 3\n    REQUEST = 4\n    UPDATE_INFO = 5\n    SUMMARY = 6\n    GET_PENDING_MATCHKEYS = 7\n\n\nRPC_SESS_MASK = 128\n\n# Use \"127.0.0.1\" or \"::1\" if there is a need to force ip4 or ip6\n# connection for \"localhost\".\ndef get_addr_family(addr):\n    res = socket.getaddrinfo(addr[0], addr[1], 0, 0, socket.IPPROTO_TCP)\n    return res[0][0]\n\n\ndef recvall(sock, nbytes):\n    \"\"\"Receive all nbytes from socket.\n\n    Parameters\n    ----------\n    sock: Socket\n       The socket\n\n    nbytes : int\n       Number of bytes to be received.\n    \"\"\"\n    res = []\n    nread = 0\n    while nread < nbytes:\n        chunk = sock.recv(min(nbytes - nread, 1024))\n        if not chunk:\n            raise IOError(\"connection reset\")\n        nread += len(chunk)\n        res.append(chunk)\n    return b\"\".join(res)\n\n\ndef sendjson(sock, data):\n    \"\"\"send a python value to remote via json\n\n    Parameters\n    ----------\n    sock : Socket\n        The socket\n\n    data : object\n        Python value to be sent.\n    \"\"\"\n    data = json.dumps(data)\n    sock.sendall(struct.pack(\"<i\", len(data)))\n    sock.sendall(data.encode(\"utf-8\"))\n\n\ndef recvjson(sock):\n    \"\"\"receive python value from remote via json\n\n    Parameters\n    ----------\n    sock : Socket\n        The socket\n\n    Returns\n    -------\n    value : object\n        The value received.\n    \"\"\"\n    size = struct.unpack(\"<i\", recvall(sock, 4))[0]\n    data = json.loads(py_str(recvall(sock, size)))\n    return data\n\n\ndef random_key(prefix, cmap=None):\n    \"\"\"Generate a random key\n\n    Parameters\n    ----------\n    prefix : str\n        The string prefix\n\n    cmap : dict\n        Conflict map\n\n    Returns\n    -------\n    key : str\n        The generated random key\n    \"\"\"\n    if cmap:\n        while True:\n            key = prefix + str(random.random())\n            if key not in cmap:\n                return key\n    else:\n        return prefix + str(random.random())\n\n\ndef connect_with_retry(addr, timeout=60, retry_period=5):\n    \"\"\"Connect to a TPC address with retry\n\n    This function is only reliable to short period of server restart.\n\n    Parameters\n    ----------\n    addr : tuple\n        address tuple\n\n    timeout : float\n         Timeout during retry\n\n    retry_period : float\n         Number of seconds before we retry again.\n    \"\"\"\n    tstart = time.time()\n    while True:\n        try:\n            sock = socket.socket(get_addr_family(addr), socket.SOCK_STREAM)\n            sock.connect(addr)\n            return sock\n        except socket.error as sock_err:\n            if sock_err.args[0] not in (errno.ECONNREFUSED,):\n                raise sock_err\n            period = time.time() - tstart\n            if period > timeout:\n                raise RuntimeError(\"Failed to connect to server %s\" % str(addr))\n            logger.warning(\n                \"Cannot connect to tracker %s, retry in %g secs...\", str(addr), retry_period\n            )\n            time.sleep(retry_period)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/client.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC client tools\"\"\"\nimport os\nimport socket\nimport stat\nimport struct\nimport time\n\nimport tvm._ffi\nfrom tvm._ffi.base import TVMError\nfrom tvm.contrib import utils\nfrom tvm.runtime import ndarray as nd\nfrom tvm._ffi.runtime_ctypes import Device\n\nfrom . import _ffi_api, base, server\n\n\nclass RPCSession(object):\n    \"\"\"RPC Client session module\n\n    Do not directly create the object, call connect\n    \"\"\"\n\n    # pylint: disable=invalid-name\n    def __init__(self, sess):\n        self._sess = sess\n        self._tbl_index = _ffi_api.SessTableIndex(sess)\n        self._remote_funcs = {}\n\n    def system_lib(self):\n        \"\"\"Get system-wide library module.\n\n        Returns\n        -------\n        module : runtime.Module\n            The system-wide library module.\n\n        See Also\n        --------\n        tvm.runtime.system_lib\n        \"\"\"\n        return self.get_function(\"runtime.SystemLib\")()\n\n    def get_function(self, name):\n        \"\"\"Get function from the session.\n\n        Parameters\n        ----------\n        name : str\n            The name of the function\n\n        Returns\n        -------\n        f : Function\n            The result function.\n        \"\"\"\n        return self._sess.get_function(name)\n\n    def device(self, dev_type, dev_id=0):\n        \"\"\"Construct a remote device.\n\n        Parameters\n        ----------\n        dev_type: int or str\n\n        dev_id: int, optional\n\n        Returns\n        -------\n        dev: Device\n            The corresponding encoded remote device.\n        \"\"\"\n        dev = nd.device(dev_type, dev_id)\n        encode = (self._tbl_index + 1) * base.RPC_SESS_MASK\n        dev.device_type += encode\n        dev._rpc_sess = self\n        return dev\n\n    def upload(self, data, target=None):\n        \"\"\"Upload file to remote runtime temp folder\n\n        Parameters\n        ----------\n        data : str or bytearray\n            The file name or binary in local to upload.\n\n        target : str, optional\n            The path in remote\n        \"\"\"\n        if isinstance(data, bytearray):\n            if not target:\n                raise ValueError(\"target must present when file is a bytearray\")\n            blob = data\n        else:\n            blob = bytearray(open(data, \"rb\").read())\n            if not target:\n                target = os.path.basename(data)\n\n        if \"upload\" not in self._remote_funcs:\n            self._remote_funcs[\"upload\"] = self.get_function(\"tvm.rpc.server.upload\")\n        self._remote_funcs[\"upload\"](target, blob)\n\n    def download(self, path):\n        \"\"\"Download file from remote temp folder.\n\n        Parameters\n        ----------\n        path : str\n            The relative location to remote temp folder.\n\n        Returns\n        -------\n        blob : bytearray\n            The result blob from the file.\n        \"\"\"\n        if \"download\" not in self._remote_funcs:\n            self._remote_funcs[\"download\"] = self.get_function(\"tvm.rpc.server.download\")\n        return self._remote_funcs[\"download\"](path)\n\n    def remove(self, path):\n        \"\"\"Remove file from remote temp folder.\n\n        Parameters\n        ----------\n        path: str\n            The relative location to remote temp folder.\n        \"\"\"\n        if \"remove\" not in self._remote_funcs:\n            self._remote_funcs[\"remove\"] = self.get_function(\"tvm.rpc.server.remove\")\n        self._remote_funcs[\"remove\"](path)\n\n    def load_module(self, path):\n        \"\"\"Load a remote module, the file need to be uploaded first.\n\n        Parameters\n        ----------\n        path : str\n            The relative location to remote temp folder.\n\n        Returns\n        -------\n        m : Module\n            The remote module containing remote function.\n        \"\"\"\n        return _ffi_api.LoadRemoteModule(self._sess, path)\n\n    def download_linked_module(self, path):\n        \"\"\"Link a module in the remote and download it.\n\n        Parameters\n        ----------\n        path : str\n            The relative location to remote temp folder.\n\n        Returns\n        -------\n        blob : bytearray\n            The result blob from the file.\n\n        Note\n        ----\n        This function can be helpful when a linker\n        is not available on the local client.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            mod = build_module_with_cross_compilation()\n            # export the module as tar because a local linker is not available\n            mod.export_library(\"lib.tar\")\n            remote.upload(\"lib.tar\")\n            # invoke the linker on the remote to link the module as a library\n            # note that the library can only run on the same env as the remote\n            with open(\"lib.so\", \"wb\") as file:\n                file.write(remote.download_linked_module(\"lib.tar\"))\n        \"\"\"\n        if \"download_linked_module\" not in self._remote_funcs:\n            self._remote_funcs[\"download_linked_module\"] = self.get_function(\n                \"tvm.rpc.server.download_linked_module\"\n            )\n        return self._remote_funcs[\"download_linked_module\"](path)\n\n    def cpu(self, dev_id=0):\n        \"\"\"Construct CPU device.\"\"\"\n        return self.device(Device.kDLCPU, dev_id)\n\n    def cuda(self, dev_id=0):\n        \"\"\"Construct CUDA GPU device.\"\"\"\n        return self.device(Device.kDLCUDA, dev_id)\n\n    def cl(self, dev_id=0):\n        \"\"\"Construct OpenCL device.\"\"\"\n        return self.device(Device.kDLOpenCL, dev_id)\n\n    def vulkan(self, dev_id=0):\n        \"\"\"Construct Vulkan device.\"\"\"\n        return self.device(Device.kDLVulkan, dev_id)\n\n    def metal(self, dev_id=0):\n        \"\"\"Construct Metal device.\"\"\"\n        return self.device(Device.kDLMetal, dev_id)\n\n    def rocm(self, dev_id=0):\n        \"\"\"Construct ROCm device.\"\"\"\n        return self.device(Device.kDLROCM, dev_id)\n\n    def ext_dev(self, dev_id=0):\n        \"\"\"Construct extension device.\"\"\"\n        return self.device(Device.kDLExtDev, dev_id)\n\n    def hexagon(self, dev_id=0):\n        \"\"\"Construct Hexagon device.\"\"\"\n        return self.device(Device.kDLHexagon, dev_id)\n\n    def webgpu(self, dev_id=0):\n        \"\"\"Construct WebGPU device.\"\"\"\n        return self.device(Device.kDLWebGPU, dev_id)\n\n\nclass LocalSession(RPCSession):\n    \"\"\"RPCSession interface backed by local environment.\n\n    This class can be used to implement functions that\n    need to be ran both locally and remotely.\n    \"\"\"\n\n    def __init__(self):\n        self._temp = server._server_env([])\n        RPCSession.__init__(self, _ffi_api.LocalSession())\n\n\n@tvm._ffi.register_func(\"rpc.PopenSession\")\ndef _popen_session(binary):\n    temp = utils.tempdir()\n\n    if isinstance(binary, (bytes, bytearray)):\n        path_exec = temp.relpath(\"server.minrpc\")\n        with open(path_exec, \"wb\") as outfile:\n            outfile.write(binary)\n        os.chmod(path_exec, stat.S_IXUSR | stat.S_IRUSR)\n        path_exec = os.path.abspath(path_exec)\n    else:\n        path_exec = os.path.abspath(binary)\n        if not os.path.isfile(path_exec):\n            raise RuntimeError(f\"{path_exec} does not exist.\")\n        if not os.access(path_exec, os.X_OK):\n            raise RuntimeError(f\"{path_exec} is not executable.\")\n\n    sess = _ffi_api.CreatePipeClient(path_exec)\n    return sess\n\n\nclass PopenSession(RPCSession):\n    \"\"\"RPCSession interface backed by popen.\n\n    Parameters\n    ----------\n    binary : List[Union[str, bytes]]\n        The binary to be executed.\n    \"\"\"\n\n    def __init__(self, binary):\n        RPCSession.__init__(self, _popen_session(binary))\n\n\nclass TrackerSession(object):\n    \"\"\"Tracker client session.\n\n    Parameters\n    ----------\n    addr : tuple\n        The address tuple\n    \"\"\"\n\n    def __init__(self, addr):\n        self._addr = addr\n        self._sock = None\n        self._connect()\n\n    def __del__(self):\n        self.close()\n\n    def _connect(self):\n        self._sock = base.connect_with_retry(self._addr)\n        self._sock.sendall(struct.pack(\"<i\", base.RPC_TRACKER_MAGIC))\n        magic = struct.unpack(\"<i\", base.recvall(self._sock, 4))[0]\n        if magic != base.RPC_TRACKER_MAGIC:\n            raise RuntimeError(\"%s is not RPC Tracker\" % str(self._addr))\n\n    def close(self):\n        \"\"\"Close the tracker connection.\"\"\"\n        if self._sock:\n            self._sock.close()\n            self._sock = None\n\n    def summary(self):\n        \"\"\"Get the summary dict of the tracker.\"\"\"\n        base.sendjson(self._sock, [base.TrackerCode.SUMMARY])\n        value = base.recvjson(self._sock)\n        if value[0] != base.TrackerCode.SUCCESS:\n            raise RuntimeError(\"Invalid return value %s\" % str(value))\n        return value[1]\n\n    def text_summary(self):\n        \"\"\"Get a text summary of the tracker.\"\"\"\n        data = self.summary()\n\n        total_ct = {}\n\n        res = \"\"\n        res += \"Server List\\n\"\n        res += \"------------------------------\\n\"\n        res += \"server-address           key\\n\"\n        res += \"------------------------------\\n\"\n        sorted_server = sorted(data[\"server_info\"], key=lambda x: x[\"key\"])\n        for item in sorted_server:\n            addr = item[\"addr\"]\n            res += \"%21s    \" % \":\".join(map(str, addr))\n            res += item[\"key\"] + \"\\n\"\n            key = item[\"key\"].split(\":\")[1]  # 'server:rasp3b` -> 'rasp3b'\n            if key not in total_ct:\n                total_ct[key] = 0\n            total_ct[key] += 1\n        res += \"------------------------------\\n\"\n        res += \"\\n\"\n\n        # compute max length of device key\n        queue_info = data[\"queue_info\"]\n        keys = list(queue_info.keys())\n        if keys:\n            keys.sort()\n            max_key_len = max([len(k) for k in keys])\n        else:\n            max_key_len = 0\n\n        res += \"Queue Status\\n\"\n        title = (\"%%-%ds\" % max_key_len + \"   total  free  pending\\n\") % \"key\"\n        separate_line = \"-\" * len(title) + \"\\n\"\n        res += separate_line + title + separate_line\n        for k in keys:\n            total = total_ct.get(k, 0)\n            free, pending = queue_info[k][\"free\"], queue_info[k][\"pending\"]\n            if total or pending:\n                res += (\"%%-%ds\" % max_key_len + \"   %-5d  %-4d  %-7d\\n\") % (\n                    k,\n                    total,\n                    free,\n                    pending,\n                )\n        res += separate_line\n        return res\n\n    def request(\n        self, key, priority=1, session_timeout=0, max_retry=5, session_constructor_args=None\n    ):\n        \"\"\"Request a new connection from the tracker.\n\n        Parameters\n        ----------\n        key : str\n            The type key of the device.\n\n        priority : int, optional\n            The priority of the request.\n\n        session_timeout : float, optional\n            The duration of the session, allows server to kill\n            the connection when duration is longer than this value.\n            When duration is zero, it means the request must always be kept alive.\n\n        max_retry : int, optional\n            Maximum number of times to retry before give up.\n\n        session_constructor_args : list, optional\n            List of additional arguments to passed as the remote session constructor.\n            The first element of the list is always a string specifying the name of\n            the session constructor, the following args are the positional args to that function.\n        \"\"\"\n        last_err = None\n        for _ in range(max_retry):\n            try:\n                if self._sock is None:\n                    self._connect()\n                base.sendjson(self._sock, [base.TrackerCode.REQUEST, key, \"\", priority])\n                value = base.recvjson(self._sock)\n                if value[0] != base.TrackerCode.SUCCESS:\n                    raise RuntimeError(\"Invalid return value %s\" % str(value))\n                url, port, matchkey = value[1]\n                return connect(\n                    url,\n                    port,\n                    matchkey,\n                    session_timeout,\n                    session_constructor_args=session_constructor_args,\n                )\n            except socket.error as err:\n                self.close()\n                last_err = err\n            except TVMError as err:\n                last_err = err\n        raise RuntimeError(\n            \"Cannot request %s after %d retry, last_error:%s\" % (key, max_retry, str(last_err))\n        )\n\n    def request_and_run(self, key, func, priority=1, session_timeout=0, max_retry=2):\n        \"\"\"Request a resource from tracker and run the func.\n\n        This function safe-guard rare server node dropout during execution.\n        In such case, a new resource will be requested and func will be ran again.\n\n        Parameters\n        ----------\n        key : str\n            The type key of the device.\n\n        func : function of session -> value\n            A stateless function\n\n        priority : int, optional\n            The priority of the request.\n\n        session_timeout : float, optional\n            The duration of the session, allows server to kill\n            the connection when duration is longer than this value.\n            When duration is zero, it means the request must always be kept alive.\n\n        max_retry : int, optional\n            Maximum number of times to retry the function before give up.\n        \"\"\"\n        last_err = None\n        for _ in range(max_retry):\n            try:\n                sess = self.request(key, priority=priority, session_timeout=session_timeout)\n                tstart = time.time()\n                return func(sess)\n            except TVMError as err:\n                duration = time.time() - tstart\n                # roughly estimate if the error is due to timeout termination\n                if session_timeout and duration >= session_timeout * 0.95:\n                    raise RuntimeError(\"Session timeout when running %s\" % func.__name__)\n                last_err = err\n        raise RuntimeError(\n            \"Failed to run on %s after %d retry, last_error:%s\" % (key, max_retry, str(last_err))\n        )\n\n\ndef connect(\n    url, port, key=\"\", session_timeout=0, session_constructor_args=None, enable_logging=False\n):\n    \"\"\"Connect to RPC Server\n\n    Parameters\n    ----------\n    url : str\n        The url of the host\n\n    port : int\n        The port to connect to\n\n    key : str, optional\n        Additional key to match server\n\n    session_timeout : float, optional\n        The duration of the session in seconds, allows server to kill\n        the connection when duration is longer than this value.\n        When duration is zero, it means the request must always be kept alive.\n\n    session_constructor_args: List\n        List of additional arguments to passed as the remote session constructor.\n        The first element of the list is always a string specifying the name of\n        the session constructor, the following args are the positional args to that function.\n\n    enable_logging: boolean\n        flag to enable/disable logging. Logging is disabled by default.\n\n    Returns\n    -------\n    sess : RPCSession\n        The connected session.\n\n    Examples\n    --------\n    Normal usage\n    .. code-block:: python\n\n        client = rpc.connect(server_url, server_port, server_key)\n\n    Session_constructor can be used to customize the session in the remote\n    The following code connects to a remote internal server via a proxy\n    by constructing another RPCClientSession on the proxy machine and use that\n    as the serving session of the proxy endpoint.\n\n    .. code-block:: python\n\n        client_via_proxy = rpc.connect(\n            proxy_server_url, proxy_server_port, proxy_server_key, enable_logging\n            session_constructor_args=[\n                \"rpc.Connect\", internal_url, internal_port, internal_key, internal_logging])\n\n    \"\"\"\n    try:\n        if session_timeout:\n            key += \" -timeout=%s\" % str(session_timeout)\n        session_constructor_args = session_constructor_args if session_constructor_args else []\n        if not isinstance(session_constructor_args, (list, tuple)):\n            raise TypeError(\"Expect the session constructor to be a list or tuple\")\n        sess = _ffi_api.Connect(url, port, key, enable_logging, *session_constructor_args)\n    except NameError:\n        raise RuntimeError(\"Please compile with USE_RPC=1\")\n    return RPCSession(sess)\n\n\ndef connect_tracker(url, port):\n    \"\"\"Connect to a RPC tracker\n\n    Parameters\n    ----------\n    url : str\n        The url of the host\n\n    port : int\n        The port to connect to\n\n    Returns\n    -------\n    sess : TrackerSession\n        The connected tracker session.\n    \"\"\"\n    return TrackerSession((url, port))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/minrpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utils to path.\"\"\"\nimport os\nfrom tvm._ffi import libinfo\nfrom tvm.contrib import cc\n\n\ndef find_minrpc_server_libpath(server=\"posix_popen_server\"):\n    \"\"\"Get the path of minrpc server libary.\n\n    Parameters\n    ----------\n    server : str\n        The kind of built in minrpc server.\n\n    Returns\n    -------\n    path : str\n        The path to the min server library.\n    \"\"\"\n    curr_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n    source_dir = os.path.abspath(os.path.join(curr_dir, \"..\", \"..\", \"..\"))\n    minrpc_dir = os.path.join(source_dir, \"src\", \"runtime\", \"minrpc\")\n    path = os.path.join(minrpc_dir, server, (\"%s.cc\" % server))\n\n    candidates = [path]\n    if not os.path.isfile(path):\n        raise RuntimeError(\"Cannot find minserver %s, in candidates %s\" % (server, candidates))\n    return minrpc_dir, path\n\n\ndef with_minrpc(compile_func, server=\"posix_popen_server\", runtime=\"libtvm\"):\n    \"\"\"Attach the compiler function with minrpc related options.\n\n    Parameters\n    ----------\n    compile_func : Union[str, Callable[[str, str, Optional[str]], None]]\n        The compilation function to decorate.\n\n    server : str\n        The server type.\n\n    runtime : str\n        The runtime library.\n\n    Returns\n    -------\n    fcompile : function\n        The return compilation.\n    \"\"\"\n    minrpc_dir, server_path = find_minrpc_server_libpath(server)\n    runtime_path = libinfo.find_lib_path([runtime, runtime + \".so\", runtime + \".dylib\"])[0]\n\n    runtime_dir = os.path.abspath(os.path.dirname(runtime_path))\n    options = [\"-std=c++17\"]\n    # Make sure the rpath to the libtvm is set so we can do local tests.\n    # Note that however, this approach won't work on remote.\n    # Always recommend to link statically.\n    options += [\"-Wl,-rpath=\" + runtime_dir]\n    options += [\"-I\" + path for path in libinfo.find_include_path()]\n    options += [\"-I\" + minrpc_dir]\n    fcompile = cc.cross_compiler(\n        compile_func, options=options, add_files=[server_path, runtime_path]\n    )\n    fcompile.__name__ = \"with_minrpc\"\n    fcompile.need_system_lib = True\n    return fcompile\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/proxy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC proxy, allows both client/server to connect and match connection.\n\nIn normal RPC, client directly connect to server's IP address.\nSometimes this cannot be done when server do not have a static address.\nRPCProxy allows both client and server connect to the proxy server,\nthe proxy server will forward the message between the client and server.\n\"\"\"\n# pylint: disable=unused-variable, unused-argument\nimport os\nimport asyncio\nimport logging\nimport socket\nimport threading\nimport errno\nimport struct\nimport time\n\ntry:\n    import tornado\n    from tornado import gen\n    from tornado import websocket\n    from tornado import ioloop\n    from . import tornado_util\nexcept ImportError as error_msg:\n    raise ImportError(\n        \"RPCProxy module requires tornado package %s. Try 'pip install tornado'.\" % error_msg\n    )\n\nfrom tvm.contrib.popen_pool import PopenWorker\nfrom . import _ffi_api\nfrom . import base\nfrom .base import TrackerCode\nfrom .server import _server_env\nfrom .._ffi.base import py_str\n\n\nclass ForwardHandler(object):\n    \"\"\"Forward handler to forward the message.\"\"\"\n\n    def _init_handler(self):\n        \"\"\"Initialize handler.\"\"\"\n        self._init_message = bytes()\n        self._init_req_nbytes = 4\n        self._magic = None\n        self.timeout = None\n        self._rpc_key_length = None\n        self._done = False\n        self._proxy = ProxyServerHandler.current\n        assert self._proxy\n        self.rpc_key = None\n        self.match_key = None\n        self.forward_proxy = None\n        self.alloc_time = None\n\n    def __del__(self):\n        logging.info(\"Delete %s...\", self.name())\n\n    def name(self):\n        \"\"\"Name of this connection.\"\"\"\n        return \"RPCConnection\"\n\n    def _init_step(self, message):\n        if self._magic is None:\n            assert len(message) == 4\n            self._magic = struct.unpack(\"<i\", message)[0]\n            if self._magic != base.RPC_MAGIC:\n                logging.info(\"Invalid RPC magic from %s\", self.name())\n                self.close()\n            self._init_req_nbytes = 4\n        elif self._rpc_key_length is None:\n            assert len(message) == 4\n            self._rpc_key_length = struct.unpack(\"<i\", message)[0]\n            self._init_req_nbytes = self._rpc_key_length\n        elif self.rpc_key is None:\n            assert len(message) == self._rpc_key_length\n            self.rpc_key = py_str(message)\n            # match key is used to do the matching\n            self.match_key = self.rpc_key[7:].split()[0]\n            self.on_start()\n        else:\n            assert False\n\n    def on_start(self):\n        \"\"\"Event when the initialization is completed\"\"\"\n        self._proxy.handler_ready(self)\n\n    def on_data(self, message):\n        \"\"\"on data\"\"\"\n        assert isinstance(message, bytes)\n        if self.forward_proxy:\n            self.forward_proxy.send_data(message)\n        else:\n            while message and self._init_req_nbytes > len(self._init_message):\n                nbytes = self._init_req_nbytes - len(self._init_message)\n                self._init_message += message[:nbytes]\n                message = message[nbytes:]\n                if self._init_req_nbytes == len(self._init_message):\n                    temp = self._init_message\n                    self._init_req_nbytes = 0\n                    self._init_message = bytes()\n                    self._init_step(temp)\n            if message:\n                logging.info(\"Invalid RPC protocol, too many bytes %s\", self.name())\n                self.close()\n\n    def on_error(self, err):\n        logging.info(\"%s: Error in RPC %s\", self.name(), err)\n        self.close_pair()\n\n    def close_pair(self):\n        if self.forward_proxy:\n            self.forward_proxy.signal_close()\n            self.forward_proxy = None\n        self.close()\n\n    def on_close_event(self):\n        \"\"\"on close event\"\"\"\n        assert not self._done\n        logging.info(\"RPCProxy:on_close_event %s ...\", self.name())\n        if self.match_key:\n            key = self.match_key\n            if self._proxy._client_pool.get(key, None) == self:\n                self._proxy._client_pool.pop(key)\n            if self._proxy._server_pool.get(key, None) == self:\n                self._proxy._server_pool.pop(key)\n        self._done = True\n        self.forward_proxy = None\n\n\nclass TCPHandler(tornado_util.TCPHandler, ForwardHandler):\n    \"\"\"Event driven TCP handler.\"\"\"\n\n    def __init__(self, sock, addr):\n        super(TCPHandler, self).__init__(sock)\n        self._init_handler()\n        self.addr = addr\n\n    def name(self):\n        return \"TCPSocketProxy:%s:%s\" % (str(self.addr[0]), self.rpc_key)\n\n    def send_data(self, message, binary=True):\n        self.write_message(message, True)\n\n    def on_message(self, message):\n        self.on_data(message)\n\n    def on_close(self):\n        logging.info(\"RPCProxy: on_close %s ...\", self.name())\n        self._close_process = True\n\n        if self.forward_proxy:\n            self.forward_proxy.signal_close()\n            self.forward_proxy = None\n        self.on_close_event()\n\n\nclass WebSocketHandler(websocket.WebSocketHandler, ForwardHandler):\n    \"\"\"Handler for websockets.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super(WebSocketHandler, self).__init__(*args, **kwargs)\n        self._init_handler()\n\n    def name(self):\n        return \"WebSocketProxy:%s\" % (self.rpc_key)\n\n    def on_message(self, message):\n        self.on_data(message)\n\n    def data_received(self, _):\n        raise NotImplementedError()\n\n    def send_data(self, message):\n        try:\n            self.write_message(message, True)\n        except websocket.WebSocketClosedError as err:\n            self.on_error(err)\n\n    def on_close(self):\n        logging.info(\"RPCProxy: on_close %s ...\", self.name())\n        if self.forward_proxy:\n            self.forward_proxy.signal_close()\n            self.forward_proxy = None\n        self.on_close_event()\n\n    def signal_close(self):\n        self.close()\n\n\nclass RequestHandler(tornado.web.RequestHandler):\n    \"\"\"Handles html request.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        file_path = kwargs.pop(\"file_path\")\n        if file_path.endswith(\"html\"):\n            self.page = open(file_path).read()\n            web_port = kwargs.pop(\"rpc_web_port\", None)\n            if web_port:\n                self.page = self.page.replace(\n                    \"ws://localhost:9190/ws\", \"ws://localhost:%d/ws\" % web_port\n                )\n        else:\n            self.page = open(file_path, \"rb\").read()\n        super(RequestHandler, self).__init__(*args, **kwargs)\n\n    def data_received(self, _):\n        pass\n\n    def get(self, *args, **kwargs):\n        self.write(self.page)\n\n\nclass ProxyServerHandler(object):\n    \"\"\"Internal proxy server handler class.\"\"\"\n\n    current = None\n\n    def __init__(\n        self,\n        sock,\n        listen_port,\n        web_port,\n        timeout_client,\n        timeout_server,\n        tracker_addr,\n        index_page=None,\n        resource_files=None,\n    ):\n        assert ProxyServerHandler.current is None\n        ProxyServerHandler.current = self\n        if web_port:\n            handlers = [\n                (r\"/ws\", WebSocketHandler),\n            ]\n            if index_page:\n                handlers.append(\n                    (r\"/\", RequestHandler, {\"file_path\": index_page, \"rpc_web_port\": web_port})\n                )\n                logging.info(\"Serving RPC index html page at http://localhost:%d\", web_port)\n            resource_files = resource_files if resource_files else []\n            for fname in resource_files:\n                basename = os.path.basename(fname)\n                pair = (r\"/%s\" % basename, RequestHandler, {\"file_path\": fname})\n                handlers.append(pair)\n                logging.info(pair)\n            self.app = tornado.web.Application(handlers)\n            self.app.listen(web_port)\n\n        self.sock = sock\n        self.sock.setblocking(0)\n        self.loop = ioloop.IOLoop.current()\n\n        def event_handler(_, events):\n            self._on_event(events)\n\n        self.loop.add_handler(self.sock.fileno(), event_handler, self.loop.READ)\n        self._client_pool = {}\n        self._server_pool = {}\n        self.timeout_alloc = 5\n        self.timeout_client = timeout_client\n        self.timeout_server = timeout_server\n        # tracker information\n        self._listen_port = listen_port\n        self._tracker_addr = tracker_addr\n        self._tracker_conn = None\n        self._tracker_pending_puts = []\n        self._key_set = set()\n        self.update_tracker_period = 2\n        if tracker_addr:\n            logging.info(\"Tracker address:%s\", str(tracker_addr))\n\n            def _callback():\n                self._update_tracker(True)\n\n            self.loop.call_later(self.update_tracker_period, _callback)\n        logging.info(\"RPCProxy: Websock port bind to %d\", web_port)\n\n    def _on_event(self, _):\n        while True:\n            try:\n                conn, addr = self.sock.accept()\n                TCPHandler(conn, addr)\n            except socket.error as err:\n                if err.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):\n                    break\n\n    def _pair_up(self, lhs, rhs):\n        lhs.forward_proxy = rhs\n        rhs.forward_proxy = lhs\n\n        lhs.send_data(struct.pack(\"<i\", base.RPC_CODE_SUCCESS))\n        lhs.send_data(struct.pack(\"<i\", len(rhs.rpc_key)))\n        lhs.send_data(rhs.rpc_key.encode(\"utf-8\"))\n\n        rhs.send_data(struct.pack(\"<i\", base.RPC_CODE_SUCCESS))\n        rhs.send_data(struct.pack(\"<i\", len(lhs.rpc_key)))\n        rhs.send_data(lhs.rpc_key.encode(\"utf-8\"))\n        logging.info(\"Pairup connect %s  and %s\", lhs.name(), rhs.name())\n\n    def _regenerate_server_keys(self, keys):\n        \"\"\"Regenerate keys for server pool\"\"\"\n        keyset = set(self._server_pool.keys())\n        new_keys = []\n        # re-generate the server match key, so old information is invalidated.\n        for key in keys:\n            rpc_key, _ = key.split(\":\")\n            handle = self._server_pool[key]\n            del self._server_pool[key]\n            new_key = base.random_key(rpc_key + \":\", keyset)\n            self._server_pool[new_key] = handle\n            keyset.add(new_key)\n            new_keys.append(new_key)\n        return new_keys\n\n    def _update_tracker(self, period_update=False):\n        \"\"\"Update information on tracker.\"\"\"\n        try:\n            if self._tracker_conn is None:\n                self._tracker_conn = socket.socket(\n                    base.get_addr_family(self._tracker_addr), socket.SOCK_STREAM\n                )\n                self._tracker_conn.connect(self._tracker_addr)\n                self._tracker_conn.sendall(struct.pack(\"<i\", base.RPC_TRACKER_MAGIC))\n                magic = struct.unpack(\"<i\", base.recvall(self._tracker_conn, 4))[0]\n                if magic != base.RPC_TRACKER_MAGIC:\n                    self.loop.stop()\n                    raise RuntimeError(\"%s is not RPC Tracker\" % str(self._tracker_addr))\n                # just connect to tracker, need to update all keys\n                self._tracker_pending_puts = self._server_pool.keys()\n\n            if self._tracker_conn and period_update:\n                # periodically update tracker information\n                # regenerate key if the key is not in tracker anymore\n                # and there is no in-coming connection after timeout_alloc\n                base.sendjson(self._tracker_conn, [TrackerCode.GET_PENDING_MATCHKEYS])\n                pending_keys = set(base.recvjson(self._tracker_conn))\n                update_keys = []\n                for k, v in self._server_pool.items():\n                    if k not in pending_keys:\n                        if v.alloc_time is None:\n                            v.alloc_time = time.time()\n                        elif time.time() - v.alloc_time > self.timeout_alloc:\n                            update_keys.append(k)\n                            v.alloc_time = None\n                if update_keys:\n                    logging.info(\n                        \"RPCProxy: No incoming conn on %s, regenerate keys...\", str(update_keys)\n                    )\n                    new_keys = self._regenerate_server_keys(update_keys)\n                    self._tracker_pending_puts += new_keys\n\n            need_update_info = False\n            # report new connections\n            for key in self._tracker_pending_puts:\n                rpc_key = key.split(\":\")[0]\n                base.sendjson(\n                    self._tracker_conn, [TrackerCode.PUT, rpc_key, (self._listen_port, key), None]\n                )\n                assert base.recvjson(self._tracker_conn) == TrackerCode.SUCCESS\n                if rpc_key not in self._key_set:\n                    self._key_set.add(rpc_key)\n                    need_update_info = True\n\n            if need_update_info:\n                keylist = \"[\" + \",\".join(self._key_set) + \"]\"\n                cinfo = {\"key\": \"server:proxy\" + keylist, \"addr\": [None, self._listen_port]}\n                base.sendjson(self._tracker_conn, [TrackerCode.UPDATE_INFO, cinfo])\n                assert base.recvjson(self._tracker_conn) == TrackerCode.SUCCESS\n            self._tracker_pending_puts = []\n        except (socket.error, IOError) as err:\n            logging.info(\n                \"Lost tracker connection: %s, try reconnect in %g sec\",\n                str(err),\n                self.update_tracker_period,\n            )\n            self._tracker_conn.close()\n            self._tracker_conn = None\n            self._regenerate_server_keys(self._server_pool.keys())\n\n        if period_update:\n\n            def _callback():\n                self._update_tracker(True)\n\n            self.loop.call_later(self.update_tracker_period, _callback)\n\n    def _handler_ready_tracker_mode(self, handler):\n        \"\"\"tracker mode to handle handler ready.\"\"\"\n        if handler.rpc_key.startswith(\"server:\"):\n            key = base.random_key(handler.match_key + \":\", self._server_pool)\n            handler.match_key = key\n            self._server_pool[key] = handler\n            self._tracker_pending_puts.append(key)\n            self._update_tracker()\n        else:\n            if handler.match_key in self._server_pool:\n                self._pair_up(self._server_pool.pop(handler.match_key), handler)\n            else:\n                handler.send_data(struct.pack(\"<i\", base.RPC_CODE_MISMATCH))\n                handler.signal_close()\n\n    def _handler_ready_proxy_mode(self, handler):\n        \"\"\"Normal proxy mode when handler is ready.\"\"\"\n        if handler.rpc_key.startswith(\"server:\"):\n            pool_src, pool_dst = self._client_pool, self._server_pool\n            timeout = self.timeout_server\n        else:\n            pool_src, pool_dst = self._server_pool, self._client_pool\n            timeout = self.timeout_client\n\n        key = handler.match_key\n        if key in pool_src:\n            self._pair_up(pool_src.pop(key), handler)\n            return\n        if key not in pool_dst:\n            pool_dst[key] = handler\n\n            def cleanup():\n                \"\"\"Cleanup client connection if timeout\"\"\"\n                if pool_dst.get(key, None) == handler:\n                    logging.info(\n                        \"Timeout client connection %s, cannot find match key=%s\",\n                        handler.name(),\n                        key,\n                    )\n                    pool_dst.pop(key)\n                    handler.send_data(struct.pack(\"<i\", base.RPC_CODE_MISMATCH))\n                    handler.signal_close()\n\n            self.loop.call_later(timeout, cleanup)\n        else:\n            logging.info(\"Duplicate connection with same key=%s\", key)\n            handler.send_data(struct.pack(\"<i\", base.RPC_CODE_DUPLICATE))\n            handler.signal_close()\n\n    def handler_ready(self, handler):\n        \"\"\"Report handler to be ready.\"\"\"\n        logging.info(\"Handler ready %s\", handler.name())\n        if self._tracker_addr:\n            self._handler_ready_tracker_mode(handler)\n        else:\n            self._handler_ready_proxy_mode(handler)\n\n    def run(self):\n        \"\"\"Run the proxy server\"\"\"\n        ioloop.IOLoop.current().start()\n\n\ndef _proxy_server(\n    listen_sock,\n    listen_port,\n    web_port,\n    timeout_client,\n    timeout_server,\n    tracker_addr,\n    index_page,\n    resource_files,\n):\n    asyncio.set_event_loop(asyncio.new_event_loop())\n    handler = ProxyServerHandler(\n        listen_sock,\n        listen_port,\n        web_port,\n        timeout_client,\n        timeout_server,\n        tracker_addr,\n        index_page,\n        resource_files,\n    )\n    handler.run()\n\n\nclass PopenProxyServerState(object):\n    \"\"\"Internal PopenProxy State for Popen\"\"\"\n\n    current = None\n\n    def __init__(\n        self,\n        host,\n        port=9091,\n        port_end=9199,\n        web_port=0,\n        timeout_client=600,\n        timeout_server=600,\n        tracker_addr=None,\n        index_page=None,\n        resource_files=None,\n    ):\n\n        sock = socket.socket(base.get_addr_family((host, port)), socket.SOCK_STREAM)\n        self.port = None\n        for my_port in range(port, port_end):\n            try:\n                sock.bind((host, my_port))\n                self.port = my_port\n                break\n            except socket.error as sock_err:\n                if sock_err.errno in [errno.EADDRINUSE]:\n                    continue\n                raise sock_err\n        if not self.port:\n            raise ValueError(\"cannot bind to any port in [%d, %d)\" % (port, port_end))\n        logging.info(\"RPCProxy: client port bind to %s:%d\", host, self.port)\n        sock.listen(1)\n        self.thread = threading.Thread(\n            target=_proxy_server,\n            args=(\n                sock,\n                self.port,\n                web_port,\n                timeout_client,\n                timeout_server,\n                tracker_addr,\n                index_page,\n                resource_files,\n            ),\n        )\n        # start the server in a different thread\n        # so we can return the port directly\n        self.thread.start()\n\n\ndef _popen_start_proxy_server(\n    host,\n    port=9091,\n    port_end=9199,\n    web_port=0,\n    timeout_client=600,\n    timeout_server=600,\n    tracker_addr=None,\n    index_page=None,\n    resource_files=None,\n):\n    # This is a function that will be sent to the\n    # Popen worker to run on a separate process.\n    # Create and start the server in a different thread\n    state = PopenProxyServerState(\n        host,\n        port,\n        port_end,\n        web_port,\n        timeout_client,\n        timeout_server,\n        tracker_addr,\n        index_page,\n        resource_files,\n    )\n    PopenProxyServerState.current = state\n    # returns the port so that the main can get the port number.\n    return state.port\n\n\nclass Proxy(object):\n    \"\"\"Start RPC proxy server on a separate process.\n\n    Python implementation based on PopenWorker.\n\n    Parameters\n    ----------\n    host : str\n        The host url of the server.\n\n    port : int\n        The TCP port to be bind to\n\n    port_end : int, optional\n        The end TCP port to search\n\n    web_port : int, optional\n        The http/websocket port of the server.\n\n    timeout_client : float, optional\n        Timeout of client until it sees a matching connection.\n\n    timeout_server : float, optional\n        Timeout of server until it sees a matching connection.\n\n    tracker_addr: Tuple (str, int) , optional\n        The address of RPC Tracker in tuple (host, ip) format.\n        If is not None, the server will register itself to the tracker.\n\n    index_page : str, optional\n        Path to an index page that can be used to display at proxy index.\n\n    resource_files : str, optional\n        Path to local resources that can be included in the http request\n    \"\"\"\n\n    def __init__(\n        self,\n        host,\n        port=9091,\n        port_end=9199,\n        web_port=0,\n        timeout_client=600,\n        timeout_server=600,\n        tracker_addr=None,\n        index_page=None,\n        resource_files=None,\n    ):\n        self.proc = PopenWorker()\n        # send the function\n        self.proc.send(\n            _popen_start_proxy_server,\n            [\n                host,\n                port,\n                port_end,\n                web_port,\n                timeout_client,\n                timeout_server,\n                tracker_addr,\n                index_page,\n                resource_files,\n            ],\n        )\n        # receive the port\n        self.port = self.proc.recv()\n        self.host = host\n\n    def terminate(self):\n        \"\"\"Terminate the server process\"\"\"\n        if self.proc:\n            logging.info(\"Terminating Proxy Server...\")\n            self.proc.kill()\n            self.proc = None\n\n    def __del__(self):\n        self.terminate()\n\n\ndef websocket_proxy_server(url, key=\"\"):\n    \"\"\"Create a RPC server that uses an websocket that connects to a proxy.\n\n    Parameters\n    ----------\n    url : str\n        The url to be connected.\n\n    key : str\n        The key to identify the server.\n    \"\"\"\n\n    def create_on_message(conn):\n        def _fsend(data):\n            data = bytes(data)\n            conn.write_message(data, binary=True)\n            return len(data)\n\n        on_message = _ffi_api.CreateEventDrivenServer(_fsend, \"WebSocketProxyServer\", \"%toinit\")\n        return on_message\n\n    @gen.coroutine\n    def _connect(key):\n        conn = yield websocket.websocket_connect(url)\n        on_message = create_on_message(conn)\n        temp = _server_env(None)\n        # Start connecton\n        conn.write_message(struct.pack(\"<i\", base.RPC_MAGIC), binary=True)\n        key = \"server:\" + key\n        conn.write_message(struct.pack(\"<i\", len(key)), binary=True)\n        conn.write_message(key.encode(\"utf-8\"), binary=True)\n        msg = yield conn.read_message()\n        assert len(msg) >= 4\n        magic = struct.unpack(\"<i\", msg[:4])[0]\n        if magic == base.RPC_CODE_DUPLICATE:\n            raise RuntimeError(\"key: %s has already been used in proxy\" % key)\n        if magic == base.RPC_CODE_MISMATCH:\n            logging.info(\"RPCProxy do not have matching client key %s\", key)\n        elif magic != base.RPC_CODE_SUCCESS:\n            raise RuntimeError(\"%s is not RPC Proxy\" % url)\n        msg = msg[4:]\n\n        logging.info(\"Connection established with remote\")\n\n        if msg:\n            on_message(bytearray(msg), 3)\n\n        while True:\n            try:\n                msg = yield conn.read_message()\n                if msg is None:\n                    break\n                on_message(bytearray(msg), 3)\n            except websocket.WebSocketClosedError as err:\n                break\n        logging.info(\"WebSocketProxyServer closed...\")\n        temp.remove()\n        ioloop.IOLoop.current().stop()\n\n    ioloop.IOLoop.current().spawn_callback(_connect, key)\n    ioloop.IOLoop.current().start()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC server implementation.\n\nNote\n----\nServer is TCP based with the following protocol:\n- Initial handshake to the peer\n  - [RPC_MAGIC, keysize(int32), key-bytes]\n- The key is in format\n   - {server|client}:device-type[:random-key] [-timeout=timeout]\n\"\"\"\n# pylint: disable=invalid-name\nimport ctypes\nimport socket\nimport select\nimport struct\nimport logging\nimport threading\nimport multiprocessing\nimport time\nimport errno\nimport tvm._ffi\n\nfrom tvm._ffi.base import py_str\nfrom tvm._ffi.libinfo import find_lib_path\nfrom tvm.runtime.module import load_module as _load_module\nfrom tvm.contrib import utils\nfrom tvm.contrib.popen_pool import PopenWorker\nfrom . import _ffi_api\nfrom . import base\n\n# pylint: disable=unused-import\nfrom . import testing\nfrom .base import TrackerCode\n\nlogger = logging.getLogger(\"RPCServer\")\nconsole_handler = logging.StreamHandler()\nconsole_handler.setFormatter(\n    logging.Formatter(\n        fmt=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n    )\n)\nlogger.addHandler(console_handler)\nlogger.setLevel(logging.INFO)\nlogger.propagate = False\n\n\ndef _server_env(load_library, work_path=None):\n    \"\"\"Server environment function return temp dir\"\"\"\n    if work_path:\n        temp = work_path\n    else:\n        temp = utils.tempdir()\n\n    # pylint: disable=unused-variable\n    @tvm._ffi.register_func(\"tvm.rpc.server.workpath\", override=True)\n    def get_workpath(path):\n        return temp.relpath(path)\n\n    @tvm._ffi.register_func(\"tvm.rpc.server.load_module\", override=True)\n    def load_module(file_name):\n        \"\"\"Load module from remote side.\"\"\"\n        path = temp.relpath(file_name)\n        m = _load_module(path)\n        logger.info(\"load_module %s\", path)\n        return m\n\n    @tvm._ffi.register_func(\"tvm.rpc.server.download_linked_module\", override=True)\n    def download_linked_module(file_name):\n        \"\"\"Load module from remote side.\"\"\"\n        # pylint: disable=import-outside-toplevel\n        path = temp.relpath(file_name)\n\n        if path.endswith(\".o\"):\n            # Extra dependencies during runtime.\n            from tvm.contrib import cc as _cc\n\n            _cc.create_shared(path + \".so\", path)\n            path += \".so\"\n        elif path.endswith(\".tar\"):\n            # Extra dependencies during runtime.\n            from tvm.contrib import cc as _cc, tar as _tar\n\n            tar_temp = utils.tempdir(custom_path=path.replace(\".tar\", \"\"))\n            _tar.untar(path, tar_temp.temp_dir)\n            files = [tar_temp.relpath(x) for x in tar_temp.listdir()]\n            _cc.create_shared(path + \".so\", files)\n            path += \".so\"\n        elif path.endswith(\".dylib\") or path.endswith(\".so\"):\n            pass\n        else:\n            raise RuntimeError(\"Do not know how to link %s\" % file_name)\n        logger.info(\"Send linked module %s to client\", path)\n        return bytearray(open(path, \"rb\").read())\n\n    libs = []\n    load_library = load_library.split(\":\") if load_library else []\n    for file_name in load_library:\n        file_name = find_lib_path(file_name)[0]\n        libs.append(ctypes.CDLL(file_name, ctypes.RTLD_GLOBAL))\n        logger.info(\"Load additional library %s\", file_name)\n    temp.libs = libs\n    return temp\n\n\ndef _serve_loop(sock, addr, load_library, work_path=None):\n    \"\"\"Server loop\"\"\"\n    sockfd = sock.fileno()\n    temp = _server_env(load_library, work_path)\n    _ffi_api.ServerLoop(sockfd)\n    if not work_path:\n        temp.remove()\n    logger.info(\"Finish serving %s\", addr)\n\n\ndef _parse_server_opt(opts):\n    # parse client options\n    ret = {}\n    for kv in opts:\n        if kv.startswith(\"-timeout=\"):\n            ret[\"timeout\"] = float(kv[9:])\n    return ret\n\n\ndef _listen_loop(sock, port, rpc_key, tracker_addr, load_library, custom_addr):\n    \"\"\"Listening loop of the server.\"\"\"\n\n    def _accept_conn(listen_sock, tracker_conn, ping_period=2):\n        \"\"\"Accept connection from the other places.\n\n        Parameters\n        ----------\n        listen_sock: Socket\n            The socket used by listening process.\n\n        tracker_conn : connection to tracker\n            Tracker connection\n\n        ping_period : float, optional\n            ping tracker every k seconds if no connection is accepted.\n        \"\"\"\n        old_keyset = set()\n        # Report resource to tracker\n        if tracker_conn:\n            matchkey = base.random_key(rpc_key + \":\")\n            base.sendjson(tracker_conn, [TrackerCode.PUT, rpc_key, (port, matchkey), custom_addr])\n            assert base.recvjson(tracker_conn) == TrackerCode.SUCCESS\n        else:\n            matchkey = rpc_key\n\n        unmatch_period_count = 0\n        unmatch_timeout = 4\n        # Wait until we get a valid connection\n        while True:\n            if tracker_conn:\n                trigger = select.select([listen_sock], [], [], ping_period)\n                if not listen_sock in trigger[0]:\n                    base.sendjson(tracker_conn, [TrackerCode.GET_PENDING_MATCHKEYS])\n                    pending_keys = base.recvjson(tracker_conn)\n                    old_keyset.add(matchkey)\n                    # if match key not in pending key set\n                    # it means the key is acquired by a client but not used.\n                    if matchkey not in pending_keys:\n                        unmatch_period_count += 1\n                    else:\n                        unmatch_period_count = 0\n                    # regenerate match key if key is acquired but not used for a while\n                    if unmatch_period_count * ping_period > unmatch_timeout + ping_period:\n                        logger.info(\"no incoming connections, regenerate key ...\")\n                        matchkey = base.random_key(rpc_key + \":\", old_keyset)\n                        base.sendjson(\n                            tracker_conn, [TrackerCode.PUT, rpc_key, (port, matchkey), custom_addr]\n                        )\n                        assert base.recvjson(tracker_conn) == TrackerCode.SUCCESS\n                        unmatch_period_count = 0\n                    continue\n            conn, addr = listen_sock.accept()\n            magic = struct.unpack(\"<i\", base.recvall(conn, 4))[0]\n            if magic != base.RPC_MAGIC:\n                conn.close()\n                continue\n            keylen = struct.unpack(\"<i\", base.recvall(conn, 4))[0]\n            key = py_str(base.recvall(conn, keylen))\n            arr = key.split()\n            expect_header = \"client:\" + matchkey\n            server_key = \"server:\" + rpc_key\n            if arr[0] != expect_header:\n                conn.sendall(struct.pack(\"<i\", base.RPC_CODE_MISMATCH))\n                conn.close()\n                logger.warning(\"mismatch key from %s\", addr)\n                continue\n            conn.sendall(struct.pack(\"<i\", base.RPC_CODE_SUCCESS))\n            conn.sendall(struct.pack(\"<i\", len(server_key)))\n            conn.sendall(server_key.encode(\"utf-8\"))\n            return conn, addr, _parse_server_opt(arr[1:])\n\n    # Server logic\n    tracker_conn = None\n    while True:\n        try:\n            # step 1: setup tracker and report to tracker\n            if tracker_addr and tracker_conn is None:\n                tracker_conn = base.connect_with_retry(tracker_addr)\n                tracker_conn.sendall(struct.pack(\"<i\", base.RPC_TRACKER_MAGIC))\n                magic = struct.unpack(\"<i\", base.recvall(tracker_conn, 4))[0]\n                if magic != base.RPC_TRACKER_MAGIC:\n                    raise RuntimeError(\"%s is not RPC Tracker\" % str(tracker_addr))\n                # report status of current queue\n                cinfo = {\"key\": \"server:\" + rpc_key, \"addr\": (custom_addr, port)}\n                base.sendjson(tracker_conn, [TrackerCode.UPDATE_INFO, cinfo])\n                assert base.recvjson(tracker_conn) == TrackerCode.SUCCESS\n\n            # step 2: wait for in-coming connections\n            conn, addr, opts = _accept_conn(sock, tracker_conn)\n        except (socket.error, IOError):\n            # retry when tracker is dropped\n            if tracker_conn:\n                tracker_conn.close()\n                tracker_conn = None\n            continue\n        except RuntimeError as exc:\n            raise exc\n\n        # step 3: serving\n        work_path = utils.tempdir()\n        logger.info(\"connection from %s\", addr)\n        server_proc = multiprocessing.Process(\n            target=_serve_loop, args=(conn, addr, load_library, work_path)\n        )\n\n        server_proc.start()\n        # close from our side.\n        conn.close()\n        # wait until server process finish or timeout\n        server_proc.join(opts.get(\"timeout\", None))\n\n        if server_proc.is_alive():\n            logger.info(\"Timeout in RPC session, kill..\")\n            # pylint: disable=import-outside-toplevel\n            import psutil\n\n            parent = psutil.Process(server_proc.pid)\n            # terminate worker children\n            for child in parent.children(recursive=True):\n                child.terminate()\n            # terminate the worker\n            server_proc.terminate()\n        work_path.remove()\n\n\ndef _connect_proxy_loop(addr, key, load_library):\n    key = \"server:\" + key\n    retry_count = 0\n    max_retry = 5\n    retry_period = 5\n    while True:\n        try:\n            sock = socket.socket(base.get_addr_family(addr), socket.SOCK_STREAM)\n            sock.connect(addr)\n            sock.sendall(struct.pack(\"<i\", base.RPC_MAGIC))\n            sock.sendall(struct.pack(\"<i\", len(key)))\n            sock.sendall(key.encode(\"utf-8\"))\n            magic = struct.unpack(\"<i\", base.recvall(sock, 4))[0]\n            if magic == base.RPC_CODE_DUPLICATE:\n                raise RuntimeError(\"key: %s has already been used in proxy\" % key)\n\n            if magic == base.RPC_CODE_MISMATCH:\n                logger.warning(\"RPCProxy do not have matching client key %s\", key)\n            elif magic != base.RPC_CODE_SUCCESS:\n                raise RuntimeError(\"%s is not RPC Proxy\" % str(addr))\n            keylen = struct.unpack(\"<i\", base.recvall(sock, 4))[0]\n            remote_key = py_str(base.recvall(sock, keylen))\n            opts = _parse_server_opt(remote_key.split()[1:])\n            logger.info(\"connected to %s\", str(addr))\n            process = multiprocessing.Process(target=_serve_loop, args=(sock, addr, load_library))\n            process.start()\n            sock.close()\n            process.join(opts.get(\"timeout\", None))\n            if process.is_alive():\n                logger.info(\"Timeout in RPC session, kill..\")\n                process.terminate()\n            retry_count = 0\n        except (socket.error, IOError) as err:\n            retry_count += 1\n            logger.warning(\"Error encountered %s, retry in %g sec\", str(err), retry_period)\n            if retry_count > max_retry:\n                raise RuntimeError(\"Maximum retry error: last error: %s\" % str(err))\n            time.sleep(retry_period)\n\n\nclass PopenRPCServerState(object):\n    \"\"\"Internal PopenRPCServer State\"\"\"\n\n    current = None\n\n    def __init__(\n        self,\n        host,\n        port=9091,\n        port_end=9199,\n        is_proxy=False,\n        tracker_addr=None,\n        key=\"\",\n        load_library=None,\n        custom_addr=None,\n        silent=False,\n    ):\n\n        # start update\n        self.host = host\n        self.port = port\n        self.libs = []\n        self.custom_addr = custom_addr\n\n        if silent:\n            logger.setLevel(logging.ERROR)\n\n        if not is_proxy:\n            sock = socket.socket(base.get_addr_family((host, port)), socket.SOCK_STREAM)\n            self.port = None\n            for my_port in range(port, port_end):\n                try:\n                    sock.bind((host, my_port))\n                    self.port = my_port\n                    break\n                except socket.error as sock_err:\n                    if sock_err.errno in [errno.EADDRINUSE]:\n                        continue\n                    raise sock_err\n            if not self.port:\n                raise ValueError(\"cannot bind to any port in [%d, %d)\" % (port, port_end))\n            logger.info(\"bind to %s:%d\", host, self.port)\n            sock.listen(1)\n            self.sock = sock\n            self.thread = threading.Thread(\n                target=_listen_loop,\n                args=(self.sock, self.port, key, tracker_addr, load_library, self.custom_addr),\n            )\n            self.thread.start()\n        else:\n            self.thread = threading.Thread(\n                target=_connect_proxy_loop, args=((host, port), key, load_library)\n            )\n            self.thread.start()\n\n\ndef _popen_start_rpc_server(\n    host,\n    port=9091,\n    port_end=9199,\n    is_proxy=False,\n    tracker_addr=None,\n    key=\"\",\n    load_library=None,\n    custom_addr=None,\n    silent=False,\n    no_fork=False,\n    server_init_callback=None,\n):\n    if no_fork:\n        multiprocessing.set_start_method(\"spawn\")\n\n    if server_init_callback:\n        server_init_callback()\n\n    # This is a function that will be sent to the\n    # Popen worker to run on a separate process.\n    # Create and start the server in a different thread\n    state = PopenRPCServerState(\n        host, port, port_end, is_proxy, tracker_addr, key, load_library, custom_addr, silent\n    )\n    PopenRPCServerState.current = state\n    # returns the port so that the main can get the port number.\n    return state.port\n\n\nclass Server(object):\n    \"\"\"Start RPC server on a separate process.\n\n    This is a simple python implementation based on multi-processing.\n    It is also possible to implement a similar C based server with\n    TVM runtime which does not depend on the python.\n\n    Parameters\n    ----------\n    host : str\n        The host url of the server.\n\n    port : int\n        The port to be bind to\n\n    port_end : int, optional\n        The end port to search\n\n    is_proxy : bool, optional\n        Whether the address specified is a proxy.\n        If this is true, the host and port actually corresponds to the\n        address of the proxy server.\n\n    tracker_addr: Tuple (str, int) , optional\n        The address of RPC Tracker in tuple(host, ip) format.\n        If is not None, the server will register itself to the tracker.\n\n    key : str, optional\n        The key used to identify the device type in tracker.\n\n    load_library : str, optional\n        List of additional libraries to be loaded during execution.\n\n    custom_addr: str, optional\n        Custom IP Address to Report to RPC Tracker\n\n    silent: bool, optional\n        Whether run this server in silent mode.\n\n    no_fork: bool, optional\n        Whether forbid fork in multiprocessing.\n\n    server_init_callback: Callable, optional\n        Additional initialization function when starting the server.\n\n    Note\n    ----\n    The RPC server only sees functions in the tvm namespace.\n    To bring additional custom functions to the server env, you can use server_init_callback.\n\n    .. code:: python\n\n        def server_init_callback():\n            import tvm\n            # must import mypackage here\n            import mypackage\n\n            tvm.register_func(\"function\", mypackage.func)\n\n        server = rpc.Server(host, server_init_callback=server_init_callback)\n    \"\"\"\n\n    def __init__(\n        self,\n        host=\"0.0.0.0\",\n        port=9091,\n        port_end=9199,\n        is_proxy=False,\n        tracker_addr=None,\n        key=\"\",\n        load_library=None,\n        custom_addr=None,\n        silent=False,\n        no_fork=False,\n        server_init_callback=None,\n    ):\n        try:\n            if _ffi_api.ServerLoop is None:\n                raise RuntimeError(\"Please compile with USE_RPC=1\")\n        except NameError:\n            raise RuntimeError(\"Please compile with USE_RPC=1\")\n        self.proc = PopenWorker()\n        # send the function\n        self.proc.send(\n            _popen_start_rpc_server,\n            [\n                host,\n                port,\n                port_end,\n                is_proxy,\n                tracker_addr,\n                key,\n                load_library,\n                custom_addr,\n                silent,\n                no_fork,\n                server_init_callback,\n            ],\n        )\n        # receive the port\n        self.port = self.proc.recv()\n        self.host = host\n\n    def terminate(self):\n        \"\"\"Terminate the server process\"\"\"\n        if self.proc:\n            self.proc.kill()\n            self.proc = None\n\n    def __del__(self):\n        self.terminate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/server_ios_launcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nPython wrapper for running a RPC Server through iOS RPC\non the iOS simulator using the simctl command line tool.\n\"\"\"\n# pylint: disable=invalid-name\nimport os\nimport json\nimport time\nimport threading\nimport subprocess\nfrom enum import Enum\nfrom typing import Dict, List, AnyStr\n\n\nclass OSName(Enum):\n    \"\"\"The names of the operating systems available on the simulator.\"\"\"\n\n    iOS = \"iOS\"\n    tvOS = \"tvOS\"\n    watchOS = \"watchOS\"\n\n\nclass IOSDevice(Enum):\n    \"\"\"The names of available iOS devices.\"\"\"\n\n    iPhone = \"iPhone\"\n    iPod = \"iPod\"\n    iPad = \"iPad\"\n\n\nclass RPCServerMode(Enum):\n    \"\"\"Server modes available in the iOS RPC application.\"\"\"\n\n    standalone = \"standalone\"\n    proxy = \"proxy\"\n    tracker = \"tracker\"\n\n\ndef get_list_of_available_simulators() -> Dict[AnyStr, List]:\n    \"\"\"\n    List of simulators available on the system. Simulators are presented as a dictionary.\n    The dictionary key is the name of the operating system of the simulator.\n    The dictionary value is a list of all simulators with a given operating system.\n    \"\"\"\n\n    with subprocess.Popen(\n        \"xcrun simctl list devices available --json\",\n        shell=True,\n        stdin=subprocess.PIPE,\n        stdout=subprocess.PIPE,\n    ) as proc:\n        out, _ = proc.communicate()\n        available_simulators = json.loads(out)[\"devices\"]\n        available_simulators = {\n            key: value for key, value in available_simulators.items() if value != []\n        }\n    return available_simulators\n\n\ndef grep_by_system(available_devices: Dict[AnyStr, List], system_name: OSName) -> List[Dict]:\n    \"\"\"Search for simulators that use the target operating system.\"\"\"\n\n    def find_index_of_substr(search_field: List[AnyStr], target: AnyStr) -> int:\n        for i, item in enumerate(search_field):\n            if target in item:\n                return i\n        raise ValueError(\"Search field doesn't content target\")\n\n    keys = list(available_devices.keys())\n\n    return available_devices[keys[find_index_of_substr(keys, system_name.value)]]\n\n\ndef grep_by_device(available_devices: List[Dict], device_name: IOSDevice) -> List[Dict]:\n    \"\"\"Search for simulators that emulate a given device.\"\"\"\n\n    return [item for item in available_devices if device_name.value in item[\"name\"]]\n\n\ndef get_device_uid(target_device: Dict) -> AnyStr:\n    \"\"\"Get a unique device ID.\"\"\"\n\n    return target_device[\"udid\"]\n\n\ndef check_call_with_runtime_error(cmd: AnyStr, error_message: AnyStr) -> None:\n    \"\"\"Calling the function `subprocess.check_call` and catching its possible thrown exception.\"\"\"\n\n    try:\n        subprocess.check_call(cmd.split(\" \"))\n    except subprocess.CalledProcessError as called_process_error:\n        raise called_process_error from RuntimeError(error_message)\n\n\ndef boot_device(udid: AnyStr) -> None:\n    \"\"\"Boot the device by its unique ID.\"\"\"\n\n    cmd = f\"xcrun simctl boot {udid}\"\n    error_message = f\"Failed to boot device with unique id: {udid}\"\n    check_call_with_runtime_error(cmd, error_message)\n    if not is_booted(udid):\n        raise RuntimeError(error_message)\n\n\ndef shutdown_device(udid: AnyStr) -> None:\n    \"\"\"Shutdown the device by its unique ID.\"\"\"\n\n    cmd = f\"xcrun simctl shutdown {udid}\"\n    error_message = f\"Failed to shut down device with unique id: {udid}\"\n    check_call_with_runtime_error(cmd, error_message)\n    if not is_turned_off(udid):\n        raise RuntimeError(error_message)\n\n\ndef deploy_bundle_to_simulator(udid: AnyStr, bundle_path: AnyStr) -> None:\n    \"\"\"Deploy iOS RPC bundle <bundle_path> to simulator with its unique ID <udid>.\"\"\"\n\n    check_call_with_runtime_error(\n        cmd=f\"xcrun simctl install {udid} {bundle_path}\",\n        error_message=f\"Failed to deploy bundle <{bundle_path}> to device with unique id: {udid}\",\n    )\n\n\ndef delete_bundle_from_simulator(udid: AnyStr, bundle_id: AnyStr) -> None:\n    \"\"\"Delete iOS RPC bundle <bundle_id> from simulator with its unique ID <udid>.\"\"\"\n\n    check_call_with_runtime_error(\n        cmd=f\"xcrun simctl uninstall {udid} {bundle_id}\",\n        error_message=f\"Failed to uninstall bundle <{bundle_id}> \"\n        f\"from device with unique id: {udid}\",\n    )\n\n\ndef launch_ios_rpc(\n    udid: AnyStr, bundle_id: AnyStr, host_url: AnyStr, host_port: int, key: AnyStr, mode: AnyStr\n):  # pylint: disable=too-many-arguments, consider-using-with\n    \"\"\"\n    Launch iOS RPC application on simulator with No UI interconnection.\n\n    udid : str\n        Unique device ID.\n\n    bundle_id : str\n        iOS RPC bundle ID.\n\n    host_url : str\n        The tracker/proxy address.\n\n    host_port : int\n        The tracker/proxy port.\n\n    key : str\n        The key used to identify the device type in tracker.\n\n    mode : str\n        Server mode. See RPCServerMode.\n    \"\"\"\n\n    cmd = (\n        f\"xcrun simctl launch --console {udid} {bundle_id}\"\n        f\" --immediate_connect\"\n        f\" --host_url={host_url}\"\n        f\" --host_port={host_port}\"\n        f\" --key={key}\"\n        f\" --server_mode={mode}\"\n        f\" --verbose\"\n    )\n    proc = subprocess.Popen(\n        cmd.split(\" \"),\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n        bufsize=1,\n        universal_newlines=True,\n    )\n    return proc\n\n\ndef terminate_ios_rpc(udid: AnyStr, bundle_id: AnyStr) -> None:\n    \"\"\"Terminate iOS RPC application.\"\"\"\n\n    check_call_with_runtime_error(\n        cmd=f\"xcrun simctl terminate {udid} {bundle_id}\",\n        error_message=f\"Failed to terminate bundle <{bundle_id}> \"\n        f\"from device with unique id: {udid}\",\n    )\n\n\ndef is_booted(udid: AnyStr) -> bool:\n    \"\"\"Check that the device has booted.\"\"\"\n\n    device = find_device(udid)\n    return device[\"state\"] == \"Booted\"\n\n\ndef is_turned_off(udid: AnyStr) -> bool:\n    \"\"\"Check that the device has turned off.\"\"\"\n\n    device = find_device(udid)\n    return device[\"state\"] == \"Shutdown\"\n\n\ndef check_booted_device(devices: List[Dict]) -> Dict:\n    \"\"\"Check if there is already a booted device. If so, return this device.\"\"\"\n\n    for device in devices:\n        if device[\"state\"] == \"Booted\":\n            return device\n    return {}\n\n\ndef find_device(udid: AnyStr) -> Dict:\n    \"\"\"Find device by its unique ID.\"\"\"\n\n    return_value = {}\n    available_devices = get_list_of_available_simulators()\n    for devices in available_devices.values():\n        for device in devices:\n            if device[\"udid\"] == udid:\n                return_value = device\n    return return_value\n\n\nclass ServerIOSLauncher:\n    \"\"\"\n    Python wrapper for launch iOS RPC to simulator.\n\n    mode : str\n        Server mode. See RPCServerMode.\n\n    host : str\n        The tracker/proxy address.\n\n    port : int\n        The tracker/proxy port.\n\n    key : str\n        The key used to identify the device type in tracker.\n    \"\"\"\n\n    booted_devices = []\n    bundle_id = os.environ.get(\"BUNDLE_ID\")\n    bundle_path = os.environ.get(\"BUNDLE_PATH\")\n\n    class ConsoleMarkers(Enum):\n        \"\"\"\n        Marker-messages that iOS RPC Server should print to the console output\n        when its states change (see apps/ios_rpc/tvmrpc/RPCServer.mm).\n\n        STOPPED : str\n            iOS RPC Server process was stopped\n\n        CALLSTACK : str\n            Call stack if RPC Server was stopped with an error.\n\n        CONNECTED : str\n            RPC Server reports that it successfully connected.\n\n        SERVER_IP : str\n            IP on which RPC Server started (for standalone mode).\n\n        SERVER_PORT : str\n            HOST on which RPC Server started (for standalone mode).\n        \"\"\"\n\n        STOPPED = \"PROCESS_STOPPED\"\n        CALLSTACK = \"First throw call stack\"\n        CONNECTED = \"[IOS-RPC] STATE: 2\"\n        SERVER_IP = \"[IOS-RPC] IP: \"\n        SERVER_PORT = \"[IOS-RPC] PORT: \"\n\n    def __init__(self, mode, host, port, key):\n        if not ServerIOSLauncher.is_compatible_environment():\n            raise RuntimeError(\n                \"Can't create ServerIOSLauncher instance.\"\n                \" No environment variables set for iOS RPC Server.\"\n            )\n\n        self.host = host\n        self.port = port\n\n        self.external_booted_device = None\n        if not ServerIOSLauncher.booted_devices:\n            self._boot_or_find_booted_device()\n\n        self.udid = get_device_uid(\n            self.external_booted_device\n            if self.external_booted_device is not None\n            else ServerIOSLauncher.booted_devices[-1]\n        )\n\n        self.bundle_was_deployed = False\n        deploy_bundle_to_simulator(self.udid, self.bundle_path)\n        self.bundle_was_deployed = True\n\n        self.server_was_started = False\n        self.launch_process = launch_ios_rpc(self.udid, self.bundle_id, host, port, key, mode)\n        self._wait_launch_complete(\n            waiting_time=60,\n            hz=10,\n            should_print_host_and_port=mode == RPCServerMode.standalone.value,\n        )\n        self.server_was_started = True\n\n    def terminate(self):\n        \"\"\"Terminate iOS RPC server.\"\"\"\n\n        if self.bundle_was_deployed and self.server_was_started:\n            try:\n                terminate_ios_rpc(self.udid, self.bundle_id)\n                self.launch_process.terminate()\n                self.server_was_started = False\n            except RuntimeError as e:\n                print(e)\n        if self.bundle_was_deployed:\n            try:\n                delete_bundle_from_simulator(self.udid, self.bundle_id)\n                self.bundle_was_deployed = False\n            except RuntimeError as e:\n                print(e)\n\n    def __del__(self):\n        self.terminate()\n\n    @staticmethod\n    def is_compatible_environment():\n        \"\"\"Check that the current environment has the required variables.\"\"\"\n\n        return bool(os.environ.get(\"BUNDLE_ID\")) and bool(os.environ.get(\"BUNDLE_PATH\"))\n\n    @staticmethod\n    def shutdown_booted_devices():\n        \"\"\"Shutdown simulators that have been booted using this class.\"\"\"\n\n        for device_meta in ServerIOSLauncher.booted_devices:\n            try:\n                shutdown_device(get_device_uid(device_meta))\n            except RuntimeError as e:\n                print(e)\n        ServerIOSLauncher.booted_devices = []\n\n    def _boot_or_find_booted_device(self):\n        \"\"\"\n        Boot the required simulator if there is no suitable booted simulator\n        among the available simulators. If there is a suitable booted simulator,\n        then take it as a simulator to which the iOS RPC application will be deployed.\n        \"\"\"\n\n        target_system = OSName.iOS\n        target_device_type = IOSDevice.iPhone\n        available_devices = get_list_of_available_simulators()\n        if not available_devices:\n            raise ValueError(\"No devices available in this environment\")\n        target_devices = grep_by_system(available_devices, target_system)\n        if not target_devices:\n            raise ValueError(f\"No available simulators for target system: {target_system.value}\")\n        target_devices = grep_by_device(target_devices, target_device_type)\n        if not target_devices:\n            raise ValueError(\n                f\"No available simulators for target device type: {target_device_type.value}\"\n            )\n\n        maybe_booted = check_booted_device(target_devices)\n        if maybe_booted:\n            self.external_booted_device = maybe_booted\n        else:\n            take_latest_model = True\n            target_device = target_devices[-1 if take_latest_model else 0]\n            boot_device(get_device_uid(target_device))\n            ServerIOSLauncher.booted_devices.append(target_device)\n\n    def _wait_launch_complete(self, waiting_time, hz, should_print_host_and_port=False):\n        # pylint: disable=too-many-locals\n        \"\"\"\n        Wait for the iOS RPC server to start.\n\n        waiting_time : int\n            The maximum waiting time during which it is necessary\n            to receive a message from RPC Server.\n\n        hz : int\n            The frequency of checking (in hertz) messages from RPC Server.\n            Checks for messages from the server will occur every 1 / hz second.\n\n        should_print_host_and_port : bool\n            A flag that indicates that RPC Server should print the host and port\n            on which it was started.\n            Used for standalone mode.\n        \"\"\"\n\n        class Switch:\n            \"\"\"A simple helper class for boolean switching.\"\"\"\n\n            def __init__(self):\n                self._on = False\n\n            def toggle(self):\n                \"\"\"Toggle flag.\"\"\"\n                self._on = not self._on\n\n            @property\n            def on(self):\n                \"\"\"Flag of this switch.\"\"\"\n                return self._on\n\n        def watchdog():\n            for _ in range(waiting_time * hz):\n                time.sleep(1.0 / hz)\n                if switch_have_data.on:\n                    break\n            if not switch_have_data.on:\n                self.launch_process.terminate()\n                switch_process_was_terminated.toggle()\n\n        switch_have_data = Switch()\n        switch_process_was_terminated = Switch()\n        watchdog_thread = threading.Thread(target=watchdog)\n\n        host, port = None, None\n        watchdog_thread.start()\n        for line in self.launch_process.stdout:\n            if not switch_have_data.on:\n                switch_have_data.toggle()\n\n            found = str(line).find(ServerIOSLauncher.ConsoleMarkers.STOPPED.value)\n            if found != -1:\n                raise RuntimeError(\"[ERROR] Crash during RCP Server launch.. \")\n\n            found = str(line).find(ServerIOSLauncher.ConsoleMarkers.CALLSTACK.value)\n            if found != -1:\n                raise RuntimeError(\"[ERROR] Crash during RCP Server launch.. \")\n\n            found = str(line).find(ServerIOSLauncher.ConsoleMarkers.SERVER_IP.value)\n            if found != -1:\n                ip = str(line)[\n                    found + len(ServerIOSLauncher.ConsoleMarkers.SERVER_IP.value) :\n                ].rstrip(\"\\n\")\n                host = ip\n\n            found = str(line).find(ServerIOSLauncher.ConsoleMarkers.SERVER_PORT.value)\n            if found != -1:\n                port = str(line)[\n                    found + len(ServerIOSLauncher.ConsoleMarkers.SERVER_PORT.value) :\n                ].rstrip(\"\\n\")\n                port = int(port)\n\n            if str(line).find(ServerIOSLauncher.ConsoleMarkers.CONNECTED.value) != -1:\n                # rpc server reports that it successfully connected\n                break\n        watchdog_thread.join()\n\n        if switch_process_was_terminated.on:\n            raise TimeoutError(\"Can't get a response from the iOS Server.\")\n        if should_print_host_and_port:\n            if host is None or port is None:\n                raise RuntimeError(\"No messages with actual host and port.\")\n            self.port = port\n\n\nclass ServerIOSContextManager:\n    \"\"\"\n    Context manager for ServerIOSLauncher.\n    To work with ServerIOSLauncher, it is preferable to use this class\n    so that the terminate method is called in any case.\n    \"\"\"\n\n    def __init__(self, mode, host, port, key):\n        self.__mode = mode\n        self.__host = host\n        self.__port = port\n        self.__key = key\n        self.__ios_rpc_server_launcher = None\n\n    def __enter__(self):\n        self.__ios_rpc_server_launcher = ServerIOSLauncher(\n            self.__mode, self.__host, self.__port, self.__key\n        )\n        return self.__ios_rpc_server_launcher\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if self.__ios_rpc_server_launcher is not None:\n            self.__ios_rpc_server_launcher.terminate()\n            self.__ios_rpc_server_launcher = None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/testing.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,unnecessary-comprehension\n\"\"\" Testing functions for the RPC server.\"\"\"\nimport numpy as np\nimport tvm\n\n\n# RPC test functions to be registered for unit-tests purposes\n@tvm.register_func(\"rpc.test.addone\")\ndef _addone(x):\n    return x + 1\n\n\n@tvm.register_func(\"rpc.test.strcat\")\ndef _strcat(name, x):\n    return \"%s:%d\" % (name, x)\n\n\n@tvm.register_func(\"rpc.test.except\")\ndef _remotethrow(name):\n    raise ValueError(\"%s\" % name)\n\n\n@tvm.register_func(\"rpc.test.runtime_str_concat\")\ndef _strcat(x, y):\n    return x + y\n\n\n@tvm.register_func(\"rpc.test.remote_array_func\")\ndef _remote_array_func(y):\n    x = np.ones((3, 4))\n    np.testing.assert_equal(y.numpy(), x)\n\n\n@tvm.register_func(\"rpc.test.add_to_lhs\")\ndef _add_to_lhs(x):\n    return lambda y: x + y\n\n\n@tvm.register_func(\"rpc.test.remote_return_nd\")\ndef _my_module(name):\n    # Use closure to check the ref counter correctness\n    nd = tvm.nd.array(np.zeros(10).astype(\"float32\"))\n\n    if name == \"get_arr\":\n        return lambda: nd\n    if name == \"ref_count\":\n        return lambda: tvm.testing.object_use_count(nd)\n    if name == \"get_elem\":\n        return lambda idx: nd.numpy()[idx]\n    if name == \"get_arr_elem\":\n        return lambda arr, idx: arr.numpy()[idx]\n    raise RuntimeError(\"unknown name\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/tornado_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities used in tornado.\"\"\"\n\nimport socket\nimport errno\nfrom tornado import ioloop\n\n\nclass TCPHandler(object):\n    \"\"\"TCP socket handler backed tornado event loop.\n\n    Parameters\n    ----------\n    sock : Socket\n        The TCP socket, will set it to non-blocking mode.\n    \"\"\"\n\n    def __init__(self, sock):\n        self._sock = sock\n        self._ioloop = ioloop.IOLoop.current()\n        self._sock.setblocking(0)\n        self._pending_write = []\n        self._signal_close = False\n\n        def _event_handler(_, events):\n            self._event_handler(events)\n\n        self._ioloop.add_handler(\n            self._sock.fileno(), _event_handler, self._ioloop.READ | self._ioloop.ERROR\n        )\n\n    def signal_close(self):\n        \"\"\"Signal the handler to close.\n\n        The handler will be closed after the existing\n        pending message are sent to the peer.\n        \"\"\"\n        if not self._pending_write:\n            self.close()\n        else:\n            self._signal_close = True\n\n    def close(self):\n        \"\"\"Close the socket\"\"\"\n        if self._sock is not None:\n            try:\n                self._ioloop.remove_handler(self._sock.fileno())\n                self._sock.close()\n            except socket.error:\n                pass\n            self._sock = None\n            self.on_close()\n\n    def write_message(self, message, binary=True):\n        assert binary\n        if self._sock is None:\n            raise IOError(\"socket is already closed\")\n        self._pending_write.append(message)\n        self._update_write()\n\n    def _event_handler(self, events):\n        \"\"\"centeral event handler\"\"\"\n        if (events & self._ioloop.ERROR) or (events & self._ioloop.READ):\n            if self._update_read() and (events & self._ioloop.WRITE):\n                self._update_write()\n        elif events & self._ioloop.WRITE:\n            self._update_write()\n\n    def _update_write(self):\n        \"\"\"Update the state on write\"\"\"\n        while self._pending_write:\n            try:\n                msg = self._pending_write[0]\n                if self._sock is None:\n                    return\n                nsend = self._sock.send(msg)\n                if nsend != len(msg):\n                    self._pending_write[0] = msg[nsend:]\n                else:\n                    self._pending_write.pop(0)\n            except socket.error as err:\n                if err.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):\n                    break\n                self.on_error(err)\n\n        if self._pending_write:\n            self._ioloop.update_handler(\n                self._sock.fileno(), self._ioloop.READ | self._ioloop.ERROR | self._ioloop.WRITE\n            )\n        else:\n            if self._signal_close:\n                self.close()\n            else:\n                self._ioloop.update_handler(\n                    self._sock.fileno(), self._ioloop.READ | self._ioloop.ERROR\n                )\n\n    def _update_read(self):\n        \"\"\"Update state when there is read event\"\"\"\n        try:\n            msg = bytes(self._sock.recv(4096))\n            if msg:\n                self.on_message(msg)\n                return True\n            # normal close, remote is closed\n            self.close()\n        except socket.error as err:\n            if err.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):\n                pass\n            else:\n                self.on_error(err)\n        return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/rpc/tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"RPC Tracker, tracks and distributes the TVM RPC resources.\n\nThis folder implements the tracker server logic.\n\nNote\n----\nTracker is a TCP based rest api with the following protocol:\n- Initial handshake to the peer\n  - RPC_TRACKER_MAGIC\n- Normal message: [size(int32), json-data]\n- Each message is initiated by the client, and the tracker replies with a json.\n\nList of available APIs:\n\n- PING: check if tracker is alive\n  - input: [TrackerCode.PING]\n  - return: TrackerCode.SUCCESS\n- PUT: report resource to tracker\n  - input: [TrackerCode.PUT, [port, match-key]]\n  - return: TrackerCode.SUCCESS\n  - note: match-key is a randomly generated identify the resource during connection.\n- REQUEST: request a new resource from tracker\n  - input: [TrackerCode.REQUEST, [key, user, priority]]\n  - return: [TrackerCode.SUCCESS, [url, port, match-key]]\n\"\"\"\n# pylint: disable=invalid-name\n\nimport asyncio\nimport heapq\nimport logging\nimport socket\nimport threading\nimport errno\nimport struct\nimport json\nfrom tvm.contrib.popen_pool import PopenWorker\n\ntry:\n    from tornado import ioloop\n    from . import tornado_util\nexcept ImportError as error_msg:\n    raise ImportError(\n        \"RPCTracker module requires tornado package %s. Try 'pip install tornado'.\" % error_msg\n    )\n\nfrom .._ffi.base import py_str\nfrom . import base\nfrom .base import RPC_TRACKER_MAGIC, TrackerCode\n\nlogger = logging.getLogger(\"RPCTracker\")\nconsole_handler = logging.StreamHandler()\nconsole_handler.setFormatter(\n    logging.Formatter(\n        fmt=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n    )\n)\nlogger.addHandler(console_handler)\nlogger.setLevel(logging.INFO)\nlogger.propagate = False\n\n\nclass Scheduler(object):\n    \"\"\"Abstract interface of scheduler.\"\"\"\n\n    def put(self, value):\n        \"\"\"Push a resource into the scheduler.\n\n        This function can trigger callbacks in the scheduler.\n\n        Parameters\n        ----------\n        value : object\n            The resource to be put in the scheduler.\n        \"\"\"\n        raise NotImplementedError()\n\n    def request(self, user, priority, callback):\n        \"\"\"Request a resource.\n\n        Parameters\n        ----------\n        user : str\n            The user who is requesting the resource.\n\n        priority : int\n            The job priority\n\n        callback : function: value->bool\n            Callback function to receive an resource when ready\n            returns True if the resource is consumed.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove(self, value):\n        \"\"\"Remove a resource in the scheduler\n\n        Parameters\n        ----------\n        value: object\n            The resource to remove\n        \"\"\"\n\n    def summary(self):\n        \"\"\"Get summary information of the scheduler.\"\"\"\n        raise NotImplementedError()\n\n\nclass PriorityScheduler(Scheduler):\n    \"\"\"Priority based scheduler, FIFO based on request order\"\"\"\n\n    def __init__(self, key):\n        self._key = key\n        self._request_cnt = 0\n        self._lock = threading.Lock()\n        self._values = []\n        self._requests = []\n\n    def _schedule(self):\n        while self._requests and self._values:\n            value = self._values.pop(0)\n            item = heapq.heappop(self._requests)\n            callback = item[-1]\n            if callback(value[1:]):\n                value[0].pending_matchkeys.remove(value[-1])\n            else:\n                self._values.append(value)\n\n    def put(self, value):\n        self._values.append(value)\n        self._schedule()\n\n    def request(self, user, priority, callback):\n        with self._lock:\n            heapq.heappush(self._requests, (-priority, self._request_cnt, callback))\n            self._request_cnt += 1\n        self._schedule()\n\n    def remove(self, value):\n        if value in self._values:\n            self._values.remove(value)\n            self._schedule()\n\n    def summary(self):\n        \"\"\"Get summary information of the scheduler.\"\"\"\n        return {\"free\": len(self._values), \"pending\": len(self._requests)}\n\n\nclass TCPEventHandler(tornado_util.TCPHandler):\n    \"\"\"Base asynchronize message handler.\n\n    The tracker and client follows a simple message protocol.\n    The message is in form [nbytes(int32)] [json-str].\n    All the information is packed in json-str\n    \"\"\"\n\n    def __init__(self, tracker, sock, addr):\n        super(TCPEventHandler, self).__init__(sock)\n        self._data = bytearray()\n        self._tracker = tracker\n        self._msg_size = 0\n        self._addr = addr\n        self._init_req_nbytes = 4\n        self._info = {}\n        # list of pending match keys that has not been used.\n        self.pending_matchkeys = set()\n        self._tracker._connections.add(self)\n        self.put_values = []\n\n    def name(self):\n        \"\"\"name of connection\"\"\"\n        return \"TCPSocket: %s\" % str(self._addr)\n\n    def summary(self):\n        \"\"\"Summary of this connection\"\"\"\n        return self._info\n\n    def _init_conn(self, message):\n        \"\"\"Initialize the connection\"\"\"\n        if len(message) != 4:\n            logger.warning(\"Invalid connection from %s\", self.name())\n            self.close()\n        magic = struct.unpack(\"<i\", message)[0]\n        if magic != RPC_TRACKER_MAGIC:\n            logger.warning(\"Invalid magic from %s\", self.name())\n            self.close()\n        self.write_message(struct.pack(\"<i\", RPC_TRACKER_MAGIC), binary=True)\n        self._init_req_nbytes = 0\n\n    def on_message(self, message):\n        \"\"\"Callback when a message is received.\n\n        Parameters\n        ----------\n        message : bytearray\n            The bytes received\n        \"\"\"\n        assert isinstance(message, bytes)\n        if self._init_req_nbytes:\n            self._init_conn(message)\n            return\n\n        self._data += message\n\n        while True:\n            if self._msg_size == 0:\n                if len(self._data) >= 4:\n                    self._msg_size = struct.unpack(\"<i\", self._data[:4])[0]\n                else:\n                    return\n            if self._msg_size != 0 and len(self._data) >= self._msg_size + 4:\n                msg = py_str(bytes(self._data[4 : 4 + self._msg_size]))\n                del self._data[: 4 + self._msg_size]\n                self._msg_size = 0\n                # pylint: disable=broad-except\n                self.call_handler(json.loads(msg))\n            else:\n                return\n\n    def ret_value(self, data):\n        \"\"\"return value to the output\"\"\"\n        data = json.dumps(data)\n        self.write_message(struct.pack(\"<i\", len(data)), binary=True)\n        self.write_message(data.encode(\"utf-8\"), binary=True)\n\n    def call_handler(self, args):\n        \"\"\"Event handler when json request arrives.\"\"\"\n        code = args[0]\n        if code == TrackerCode.PUT:\n            key = args[1]\n            port, matchkey = args[2]\n            self.pending_matchkeys.add(matchkey)\n            # got custom address (from rpc server)\n            if len(args) >= 4 and args[3] is not None:\n                value = (self, args[3], port, matchkey)\n            else:\n                value = (self, self._addr[0], port, matchkey)\n            self._tracker.put(key, value)\n            self.put_values.append(value)\n            self.ret_value(TrackerCode.SUCCESS)\n        elif code == TrackerCode.REQUEST:\n            key = args[1]\n            user = args[2]\n            priority = args[3]\n\n            def _cb(value):\n                # if the connection is already closed\n                if not self._sock:\n                    return False\n                try:\n                    self.ret_value([TrackerCode.SUCCESS, value])\n                except (socket.error, IOError):\n                    return False\n                return True\n\n            self._tracker.request(key, user, priority, _cb)\n        elif code == TrackerCode.PING:\n            self.ret_value(TrackerCode.SUCCESS)\n        elif code == TrackerCode.GET_PENDING_MATCHKEYS:\n            self.ret_value(list(self.pending_matchkeys))\n        elif code == TrackerCode.STOP:\n            # safe stop tracker\n            if self._tracker._stop_key == args[1]:\n                self.ret_value(TrackerCode.SUCCESS)\n                self._tracker.stop()\n            else:\n                self.ret_value(TrackerCode.FAIL)\n        elif code == TrackerCode.UPDATE_INFO:\n            info = args[1]\n            assert isinstance(info, dict)\n            if info[\"addr\"][0] is None:\n                info[\"addr\"][0] = self._addr[0]\n            self._info.update(info)\n            self.ret_value(TrackerCode.SUCCESS)\n        elif code == TrackerCode.SUMMARY:\n            status = self._tracker.summary()\n            self.ret_value([TrackerCode.SUCCESS, status])\n        else:\n            logger.warning(\"Unknown tracker code %d\", code)\n            self.close()\n\n    def on_close(self):\n        self._tracker.close(self)\n\n    def on_error(self, err):\n        logger.warning(\"%s: Error in RPC Tracker: %s\", self.name(), err)\n        self.close()\n\n\nclass TrackerServerHandler(object):\n    \"\"\"Tracker that tracks the resources.\"\"\"\n\n    def __init__(self, sock, stop_key):\n        self._scheduler_map = {}\n        self._sock = sock\n        self._sock.setblocking(0)\n        self._ioloop = ioloop.IOLoop.current()\n        self._stop_key = stop_key\n        self._connections = set()\n\n        def _event_handler(_, events):\n            self._on_event(events)\n\n        self._ioloop.add_handler(self._sock.fileno(), _event_handler, self._ioloop.READ)\n\n    def _on_event(self, _):\n        while True:\n            try:\n                conn, addr = self._sock.accept()\n                TCPEventHandler(self, conn, addr)\n            except socket.error as err:\n                if err.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):\n                    break\n\n    def create_scheduler(self, key):\n        \"\"\"Create a new scheduler.\"\"\"\n        return PriorityScheduler(key)\n\n    def put(self, key, value):\n        \"\"\"Report a new resource to the tracker.\"\"\"\n        if key not in self._scheduler_map:\n            self._scheduler_map[key] = self.create_scheduler(key)\n        self._scheduler_map[key].put(value)\n\n    def request(self, key, user, priority, callback):\n        \"\"\"Request a new resource.\"\"\"\n        if key not in self._scheduler_map:\n            self._scheduler_map[key] = self.create_scheduler(key)\n        self._scheduler_map[key].request(user, priority, callback)\n\n    def close(self, conn):\n        self._connections.remove(conn)\n        if \"key\" in conn._info:\n            for value in conn.put_values:\n                _, _, _, key = value\n                rpc_key = key.split(\":\")[0]\n                self._scheduler_map[rpc_key].remove(value)\n\n    def stop(self):\n        \"\"\"Safely stop tracker.\"\"\"\n        for conn in list(self._connections):\n            conn.close()\n        self._sock.close()\n        self._ioloop.stop()\n\n    def summary(self):\n        \"\"\"Return a dict summarizing current status.\"\"\"\n        qinfo = {}\n        for k, v in self._scheduler_map.items():\n            qinfo[k] = v.summary()\n        cinfo = []\n        # ignore client connections without key\n        for conn in self._connections:\n            res = conn.summary()\n            if res.get(\"key\", \"\").startswith(\"server\"):\n                cinfo.append(res)\n        return {\"queue_info\": qinfo, \"server_info\": cinfo}\n\n    def run(self):\n        \"\"\"Run the tracker server\"\"\"\n        self._ioloop.start()\n\n\ndef _tracker_server(listen_sock, stop_key):\n    asyncio.set_event_loop(asyncio.new_event_loop())\n    handler = TrackerServerHandler(listen_sock, stop_key)\n    handler.run()\n\n\nclass PopenTrackerServerState(object):\n    \"\"\"Internal PopenTrackerServer State\"\"\"\n\n    current = None\n\n    def __init__(self, host, port=9190, port_end=9199, silent=False):\n        if silent:\n            logger.setLevel(logging.WARN)\n\n        sock = socket.socket(base.get_addr_family((host, port)), socket.SOCK_STREAM)\n        self.port = None\n        self.stop_key = base.random_key(\"tracker\")\n        for my_port in range(port, port_end):\n            try:\n                sock.bind((host, my_port))\n                self.port = my_port\n                break\n            except socket.error as sock_err:\n                if sock_err.errno in [errno.EADDRINUSE]:\n                    continue\n                raise sock_err\n        if not self.port:\n            raise ValueError(\"cannot bind to any port in [%d, %d)\" % (port, port_end))\n        logger.info(\"bind to %s:%d\", host, self.port)\n        sock.listen(1)\n        self.thread = threading.Thread(target=_tracker_server, args=(sock, self.stop_key))\n        self.thread.start()\n        self.host = host\n\n\ndef _popen_start_tracker_server(host, port=9190, port_end=9199, silent=False):\n    # This is a function that will be sent to the\n    # Popen worker to run on a separate process.\n    # Create and start the server in a different thread\n    state = PopenTrackerServerState(host, port, port_end, silent)\n    PopenTrackerServerState.current = state\n    # returns the port so that the main can get the port number.\n    return (state.port, state.stop_key)\n\n\nclass Tracker(object):\n    \"\"\"Start RPC tracker on a separate process.\n\n    Python implementation based on PopenWorker.\n\n    Parameters\n    ----------\n    host : str\n        The host url of the server.\n\n    port : int\n        The TCP port to be bind to\n\n    port_end : int, optional\n        The end TCP port to search\n\n    silent: bool, optional\n        Whether run in silent mode\n    \"\"\"\n\n    def __init__(self, host=\"0.0.0.0\", port=9190, port_end=9199, silent=False):\n        if silent:\n            logger.setLevel(logging.WARN)\n        self.proc = PopenWorker()\n        # send the function\n        self.proc.send(\n            _popen_start_tracker_server,\n            [\n                host,\n                port,\n                port_end,\n                silent,\n            ],\n        )\n        # receive the port\n        self.port, self.stop_key = self.proc.recv()\n        self.host = host\n\n    def _stop_tracker(self):\n        sock = socket.socket(base.get_addr_family((self.host, self.port)), socket.SOCK_STREAM)\n        sock.connect((\"127.0.0.1\", self.port))\n        sock.sendall(struct.pack(\"<i\", base.RPC_TRACKER_MAGIC))\n        magic = struct.unpack(\"<i\", base.recvall(sock, 4))[0]\n        assert magic == base.RPC_TRACKER_MAGIC\n        base.sendjson(sock, [TrackerCode.STOP, self.stop_key])\n        assert base.recvjson(sock) == TrackerCode.SUCCESS\n        sock.close()\n\n    def terminate(self):\n        \"\"\"Terminate the server process\"\"\"\n        if self.proc:\n            if self.proc.is_alive():\n                self._stop_tracker()\n            self.proc.join(0.1)\n            if self.proc.is_alive():\n                logger.info(\"Terminating Tracker Server...\")\n                self.proc.kill()\n            self.proc = None\n\n    def __del__(self):\n        try:\n            self.terminate()\n        except TypeError:\n            pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM runtime namespace.\"\"\"\n\n# class exposures\nfrom .packed_func import PackedFunc\nfrom .object import Object\nfrom .object_path import ObjectPath, ObjectPathPair\nfrom .object_generic import ObjectGeneric, ObjectTypes\nfrom .ndarray import NDArray, DataType, DataTypeCode, Device\nfrom .module import Module, num_threads\nfrom .profiling import Report\n\n# function exposures\nfrom .object_generic import convert_to_object, convert, const\nfrom .ndarray import device, cpu, cuda, gpu, opencl, cl, vulkan, metal, mtl\nfrom .ndarray import vpi, rocm, ext_dev\nfrom .module import load_module, enabled, system_lib, load_static_library\nfrom .container import String, ShapeTuple\nfrom .params import save_param_dict, load_param_dict\n\nfrom . import executor\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.runtime\"\"\"\nimport tvm._ffi\n\n# Exports functions registered via TVM_REGISTER_GLOBAL with the \"runtime\" prefix.\n# e.g. TVM_REGISTER_GLOBAL(\"runtime.ModuleLoadFromFile\")\ntvm._ffi._init_api(\"runtime\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/_ffi_node_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-argument\n\"\"\"FFI for tvm.node\"\"\"\nimport tvm._ffi\n\n# The implementations below are default ones when the corresponding\n# functions are not available in the runtime only mode.\n# They will be overriden via _init_api to the ones registered\n# via TVM_REGISTER_GLOBAL in the compiler mode.\ndef AsRepr(obj):\n    return obj.type_key() + \"(\" + obj.handle.value + \")\"\n\n\ndef NodeListAttrNames(obj):\n    return lambda x: 0\n\n\ndef NodeGetAttr(obj, name):\n    raise AttributeError()\n\n\ndef SaveJSON(obj):\n    raise RuntimeError(\"Do not support object serialization in runtime only mode\")\n\n\ndef LoadJSON(json_str):\n    raise RuntimeError(\"Do not support object serialization in runtime only mode\")\n\n\n# Exports functions registered via TVM_REGISTER_GLOBAL with the \"node\" prefix.\n# e.g. TVM_REGISTER_GLOBAL(\"node.AsRepr\")\ntvm._ffi._init_api(\"node\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/container.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Runtime container structures.\"\"\"\nimport tvm._ffi\nfrom .object import Object, PyNativeObject\nfrom .object_generic import ObjectTypes\nfrom . import _ffi_api\n\n\ndef getitem_helper(obj, elem_getter, length, idx):\n    \"\"\"Helper function to implement a pythonic getitem function.\n\n    Parameters\n    ----------\n    obj: object\n        The original object\n\n    elem_getter : function\n        A simple function that takes index and return a single element.\n\n    length : int\n        The size of the array\n\n    idx : int or slice\n        The argument passed to getitem\n\n    Returns\n    -------\n    result : object\n        The result of getitem\n    \"\"\"\n    if isinstance(idx, slice):\n        start = idx.start if idx.start is not None else 0\n        stop = idx.stop if idx.stop is not None else length\n        step = idx.step if idx.step is not None else 1\n        if start < 0:\n            start += length\n        if stop < 0:\n            stop += length\n        return [elem_getter(obj, i) for i in range(start, stop, step)]\n\n    if idx < -length or idx >= length:\n        raise IndexError(\"Index out of range. size: {}, got index {}\".format(length, idx))\n    if idx < 0:\n        idx += length\n    return elem_getter(obj, idx)\n\n\n@tvm._ffi.register_object(\"runtime.ADT\")\nclass ADT(Object):\n    \"\"\"Algebatic data type(ADT) object.\n\n    Parameters\n    ----------\n    tag : int\n        The tag of ADT.\n\n    fields : list[Object] or tuple[Object]\n        The source tuple.\n    \"\"\"\n\n    def __init__(self, tag, fields):\n        for f in fields:\n            assert isinstance(\n                f, ObjectTypes\n            ), \"Expect object or \" \"tvm NDArray type, but received : {0}\".format(type(f))\n        self.__init_handle_by_constructor__(_ffi_api.ADT, tag, *fields)\n\n    @property\n    def tag(self):\n        return _ffi_api.GetADTTag(self)\n\n    def __getitem__(self, idx):\n        return getitem_helper(self, _ffi_api.GetADTFields, len(self), idx)\n\n    def __len__(self):\n        return _ffi_api.GetADTSize(self)\n\n\ndef tuple_object(fields=None):\n    \"\"\"Create a ADT object from source tuple.\n\n    Parameters\n    ----------\n    fields : list[Object] or tuple[Object]\n        The source tuple.\n\n    Returns\n    -------\n    ret : ADT\n        The created object.\n    \"\"\"\n    fields = fields if fields else []\n    for f in fields:\n        assert isinstance(\n            f, ObjectTypes\n        ), \"Expect object or tvm \" \"NDArray type, but received : {0}\".format(type(f))\n    return _ffi_api.Tuple(*fields)\n\n\n@tvm._ffi.register_object(\"runtime.String\")\nclass String(str, PyNativeObject):\n    \"\"\"TVM runtime.String object, represented as a python str.\n\n    Parameters\n    ----------\n    content : str\n        The content string used to construct the object.\n    \"\"\"\n\n    __slots__ = [\"__tvm_object__\"]\n\n    def __new__(cls, content):\n        \"\"\"Construct from string content.\"\"\"\n        val = str.__new__(cls, content)\n        val.__init_tvm_object_by_constructor__(_ffi_api.String, content)\n        return val\n\n    # pylint: disable=no-self-argument\n    def __from_tvm_object__(cls, obj):\n        \"\"\"Construct from a given tvm object.\"\"\"\n        content = _ffi_api.GetFFIString(obj)\n        val = str.__new__(cls, content)\n        val.__tvm_object__ = obj\n        return val\n\n\n@tvm._ffi.register_object(\"runtime.ShapeTuple\")\nclass ShapeTuple(Object):\n    \"\"\"TVM runtime ShapeTuple object.\n    Parameters\n    ----------\n    shape : list[int]\n        The shape list used to construct the object.\n    \"\"\"\n\n    def __init__(self, shape):\n        assert isinstance(shape, (list, tuple)), \"Expect list of tuple, but received : {0}\".format(\n            type(shape)\n        )\n        for x in shape:\n            assert isinstance(x, int), \"Expect int type, but received : {0}\".format(type(x))\n        self.__init_handle_by_constructor__(_ffi_api.ShapeTuple, *shape)\n\n    def __len__(self):\n        return _ffi_api.GetShapeTupleSize(self)\n\n    def __getitem__(self, idx):\n        return getitem_helper(self, _ffi_api.GetShapeTupleElem, len(self), idx)\n\n    def __eq__(self, other):\n        if self.same_as(other):\n            return True\n        if len(self) != len(other):\n            return False\n        for a, b in zip(self, other):\n            if a != b:\n                return False\n\n        return True\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/executor/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"This module contains Python wrappers for the TVM C++ Executor implementations.\n\nNOTE: at present, only AOT Executor is contained here. The others are:\n - GraphExecutor, in python/tvm/contrib/graph_executor.py\n - VM Executor, in python/tvm/runtime/vm.py\n\nTODO(areusch): Consolidate these into this module.\n\"\"\"\nfrom .aot_executor import AotModule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/executor/aot_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A Python wrapper for the Module-based Model Runtime Interface for Ahead-of-Time compilation.\"\"\"\n\nimport numpy as np\n\n\nclass AotModule(object):\n    \"\"\"Wraps the AOT executor runtime.Module.\n\n    This is a thin wrapper of the underlying TVM module.\n    you can also directly call set_input, run, and get_output\n    of underlying module functions\n\n    Parameters\n    ----------\n    module : tvm.runtime.Module\n        The internal tvm module that holds the implemented model functions.\n\n    Attributes\n    ----------\n    module : tvm.runtime.Module\n        The internal tvm module that holds the implemented model functions.\n\n    Examples\n    --------\n\n    .. code-block:: python\n\n        import tvm\n        from tvm import relay\n        from tvm.contrib import graph_executor\n\n        # build the library using graph executor\n        lib = relay.build(...)\n        lib.export_library(\"compiled_lib.so\")\n        # load it back as a runtime\n        lib: tvm.runtime.Module = tvm.runtime.load_module(\"compiled_lib.so\")\n        # Call the library factory function for default and create\n        # a new runtime.Module, wrap with aot module.\n        gmod = tvm.runtime.executor.AotModule(lib[\"default\"](dev))\n        # use the aot  module.\n        gmod.set_input(\"x\", data)\n        gmod.run()\n    \"\"\"\n\n    def __init__(self, module):\n        self.module = module\n        self._set_input = module[\"set_input\"]\n        self._run = module[\"run\"]\n        self._get_output = module[\"get_output\"]\n        self._get_input = module[\"get_input\"]\n        self._get_num_outputs = module[\"get_num_outputs\"]\n        self._get_input_index = module[\"get_input_index\"]\n        self._get_num_inputs = module[\"get_num_inputs\"]\n\n    def set_input(self, key=None, value=None, **params):\n        \"\"\"Set inputs to the module via kwargs\n\n        Parameters\n        ----------\n        key : int or str\n           The input key\n\n        value : the input value.\n           The input key\n\n        params : dict of str to NDArray\n           Additional arguments\n        \"\"\"\n        if key is not None:\n            v = self._get_input(key)\n            if v is None:\n                raise RuntimeError(\"Could not find '%s' in model's inputs\" % key)\n            v.copyfrom(value)\n\n        if params:\n            # upload big arrays first to avoid memory issue in rpc mode\n            keys = list(params.keys())\n            keys.sort(key=lambda x: -np.prod(params[x].shape))\n            for k in keys:\n                # TODO(zhiics) Skip the weights for submodule in a better way.\n                # We should use MetadataModule for initialization and remove\n                # params from set_input\n                val = self._get_input(k)\n                if val:\n                    self._get_input(k).copyfrom(params[k])\n\n    def run(self, **input_dict):\n        \"\"\"Run forward execution of the model\n\n        Parameters\n        ----------\n        input_dict: dict of str to NDArray\n            List of input values to be feed to\n        \"\"\"\n        if input_dict:\n            self.set_input(**input_dict)\n        self._run()\n\n    def get_num_outputs(self):\n        \"\"\"Get the number of outputs from the model\n\n        Returns\n        -------\n        count : int\n            The number of outputs.\n        \"\"\"\n        return self._get_num_outputs()\n\n    def get_num_inputs(self):\n        \"\"\"Get the number of inputs to the model\n\n        Returns\n        -------\n        count : int\n            The number of inputs.\n        \"\"\"\n        return self._get_num_inputs()\n\n    def get_input(self, index, out=None):\n        \"\"\"Get index-th input to out\n\n        Parameters\n        ----------\n        index : int\n            The input index\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        if out:\n            self._get_input(index).copyto(out)\n            return out\n\n        return self._get_input(index)\n\n    def get_input_index(self, name):\n        \"\"\"Get inputs index via input name.\n\n        Parameters\n        ----------\n        name : str\n           The input key name\n\n        Returns\n        -------\n        index: int\n            The input index. -1 will be returned if the given input name is not found.\n        \"\"\"\n        return self._get_input_index(name)\n\n    def get_output(self, index, out=None):\n        \"\"\"Get index-th output to out\n\n        Parameters\n        ----------\n        index : int\n            The output index\n\n        out : NDArray\n            The output array container\n        \"\"\"\n        if out:\n            self._get_output(index, out)\n            return out\n\n        return self._get_output(index)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-import, import-outside-toplevel, inconsistent-return-statements\n\"\"\"Runtime Module namespace.\"\"\"\nimport os\nimport ctypes\nimport struct\nfrom typing import Sequence\nimport numpy as np\n\nimport tvm._ffi\nfrom tvm._ffi.base import _LIB, check_call, c_str, string_types, _RUNTIME_ONLY\nfrom tvm._ffi.libinfo import find_include_path\nfrom .packed_func import PackedFunc, PackedFuncHandle, _set_class_module\n\nfrom . import _ffi_api\n\n\nclass BenchmarkResult:\n    \"\"\"Runtimes from benchmarking\"\"\"\n\n    def __init__(self, results: Sequence[float]):\n        \"\"\"Construct a new BenchmarkResult from a sequence of runtimes.\n\n        Parameters\n        ----------\n        results : Sequence[float]\n            Raw times from benchmarking\n\n        Attributes\n        ----------\n        min : float\n            Minimum runtime in seconds of all results.\n        mean : float\n            Mean runtime in seconds of all results. If py:meth:`Module.time_evaluator` or\n            `benchmark` is called with `number` > 0, then each result is already the mean of a\n            `number` of runtimes, so this becomes the mean of means.\n        median : float\n            Median runtime in seconds of all results. If py:meth:`Module.time_evaluator` is called\n            with `number` > 0, then each result is already the mean of a `number` of runtimes, so\n            this becomes the median of means.\n        max : float\n            Maximum runtime in seconds of all results. If py:meth:`Module.time_evaluator` is called\n            with `number` > 0, then each result is already the mean of a `number` of runtimes, so\n            this becomes the maximum of those means.\n        std : float\n            Standard deviation in seconds of runtimes. If py:meth:`Module.time_evaluator` is called\n            with `number` > 0, then each result is already the mean of a `number` of runtimes, so\n            this becomes the standard deviation of means.\n        results : Sequence[float]\n            The collected runtimes (in seconds). This may be a series of mean runtimes if\n            py:meth:`Module.time_evaluator` or `benchmark` was run with `number` > 1.\n        \"\"\"\n        self.results = results\n        self.mean = np.mean(self.results)\n        self.std = np.std(self.results)\n        self.median = np.median(self.results)\n        self.min = np.min(self.results)\n        self.max = np.max(self.results)\n\n    def __repr__(self):\n        return \"BenchmarkResult(min={}, mean={}, median={}, max={}, std={}, results={})\".format(\n            self.min, self.mean, self.median, self.max, self.std, self.results\n        )\n\n    def __str__(self):\n        return \"\"\"Execution time summary:\n{:^12} {:^12} {:^12} {:^12} {:^12}\n{:^12.4f} {:^12.4f} {:^12.4f} {:^12.4f} {:^12.4f}\n               \"\"\".format(\n            \"mean (ms)\",\n            \"median (ms)\",\n            \"max (ms)\",\n            \"min (ms)\",\n            \"std (ms)\",\n            self.mean * 1000,\n            self.median * 1000,\n            self.max * 1000,\n            self.min * 1000,\n            self.std * 1000,\n        )\n\n\nclass Module(object):\n    \"\"\"Runtime Module.\"\"\"\n\n    __slots__ = [\"handle\", \"_entry\", \"entry_name\"]\n\n    def __init__(self, handle):\n        self.handle = handle\n        self._entry = None\n        self.entry_name = \"__tvm_main__\"\n\n    def __del__(self):\n        if _LIB:\n            check_call(_LIB.TVMModFree(self.handle))\n\n    def __hash__(self):\n        return ctypes.cast(self.handle, ctypes.c_void_p).value\n\n    @property\n    def entry_func(self):\n        \"\"\"Get the entry function\n\n        Returns\n        -------\n        f : tvm.runtime.PackedFunc\n            The entry function if exist\n        \"\"\"\n        if self._entry:\n            return self._entry\n        self._entry = self.get_function(self.entry_name)\n        return self._entry\n\n    def implements_function(self, name, query_imports=False):\n        \"\"\"Returns True if the module has a definition for the global function with name. Note\n        that has_function(name) does not imply get_function(name) is non-null since the module\n        may be, eg, a CSourceModule which cannot supply a packed-func implementation of the function\n        without further compilation. However, get_function(name) non null should always imply\n        has_function(name).\n\n        Parameters\n        ----------\n        name : str\n            The name of the function\n\n        query_imports : bool\n            Whether to also query modules imported by this module.\n\n        Returns\n        -------\n        b : Bool\n            True if module (or one of its imports) has a definition for name.\n        \"\"\"\n        return _ffi_api.ModuleImplementsFunction(self, name, query_imports)\n\n    def get_function(self, name, query_imports=False):\n        \"\"\"Get function from the module.\n\n        Parameters\n        ----------\n        name : str\n            The name of the function\n\n        query_imports : bool\n            Whether also query modules imported by this module.\n\n        Returns\n        -------\n        f : tvm.runtime.PackedFunc\n            The result function.\n        \"\"\"\n        ret_handle = PackedFuncHandle()\n        check_call(\n            _LIB.TVMModGetFunction(\n                self.handle, c_str(name), ctypes.c_int(query_imports), ctypes.byref(ret_handle)\n            )\n        )\n        if not ret_handle.value:\n            raise AttributeError(\"Module has no function '%s'\" % name)\n        return PackedFunc(ret_handle, False)\n\n    def import_module(self, module):\n        \"\"\"Add module to the import list of current one.\n\n        Parameters\n        ----------\n        module : tvm.runtime.Module\n            The other module.\n        \"\"\"\n        check_call(_LIB.TVMModImport(self.handle, module.handle))\n\n    def __getitem__(self, name):\n        if not isinstance(name, string_types):\n            raise ValueError(\"Can only take string as function name\")\n        return self.get_function(name)\n\n    def __eq__(self, other):\n        return self.handle.value == other.handle.value\n\n    def __call__(self, *args):\n        if self._entry:\n            return self._entry(*args)\n        # pylint: disable=not-callable\n        return self.entry_func(*args)\n\n    def __repr__(self):\n        return \"Module(%s, %x)\" % (self.type_key, self.handle.value)\n\n    @property\n    def type_key(self):\n        \"\"\"Get type key of the module.\"\"\"\n        return _ffi_api.ModuleGetTypeKey(self)\n\n    @property\n    def format(self):\n        \"\"\"Get the format of the module.\"\"\"\n        return _ffi_api.ModuleGetFormat(self)\n\n    def get_source(self, fmt=\"\"):\n        \"\"\"Get source code from module, if available.\n\n        Parameters\n        ----------\n        fmt : str, optional\n            The specified format.\n\n        Returns\n        -------\n        source : str\n            The result source code.\n        \"\"\"\n        return _ffi_api.ModuleGetSource(self, fmt)\n\n    @property\n    def imported_modules(self):\n        \"\"\"Get imported modules\n\n        Returns\n        ----------\n        modules : list of Module\n            The module\n        \"\"\"\n        nmod = _ffi_api.ModuleImportsSize(self)\n        return [_ffi_api.ModuleGetImport(self, i) for i in range(nmod)]\n\n    @property\n    def is_dso_exportable(self):\n        \"\"\"Returns true if module is 'DSO exportable', ie can be included in result of\n        export_library by the external compiler directly.\n\n        Returns\n        -------\n        b : Bool\n            True if the module is DSO exportable.\n        \"\"\"\n        return _ffi_api.ModuleIsDSOExportable(self)\n\n    def save(self, file_name, fmt=\"\"):\n        \"\"\"Save the module to file.\n\n        This do not save the dependent device modules.\n        See also export_shared\n\n        Parameters\n        ----------\n        file_name : str\n            The name of the file.\n        fmt : str\n            The format of the file.\n\n        See Also\n        --------\n        runtime.Module.export_library : export the module to shared library.\n        \"\"\"\n        _ffi_api.ModuleSaveToFile(self, file_name, fmt)\n\n    def time_evaluator(\n        self,\n        func_name,\n        dev,\n        number=10,\n        repeat=1,\n        min_repeat_ms=0,\n        limit_zero_time_iterations=100,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n        f_preproc=\"\",\n    ):\n        \"\"\"Get an evaluator that measures time cost of running function.\n\n        Parameters\n        ----------\n        func_name: str\n            The name of the function in the module.\n\n        dev: Device\n            The device we should run this function on.\n\n        number: int\n            The number of times to run this function for taking average.\n            We call these runs as one `repeat` of measurement.\n\n        repeat: int, optional\n            The number of times to repeat the measurement.\n            In total, the function will be invoked (1 + number x repeat) times,\n            where the first one is warm up and will be discarded.\n            The returned result contains `repeat` costs,\n            each of which is an average of `number` costs.\n\n        min_repeat_ms: int, optional\n            The minimum duration of one `repeat` in milliseconds.\n            By default, one `repeat` contains `number` runs. If this parameter is set,\n            the parameters `number` will be dynamically adjusted to meet the\n            minimum duration requirement of one `repeat`.\n            i.e., When the run time of one `repeat` falls below this time, the `number` parameter\n            will be automatically increased.\n\n        limit_zero_time_iterations: int, optional\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        cooldown_interval_ms: int, optional\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: int, optional\n            The number of repeats before the cooldown is activated.\n\n        f_preproc: str, optional\n            The preprocess function name we want to execute before executing the time evaluator.\n\n        Note\n        ----\n        The function will be invoked  (1 + number x repeat) times,\n        with the first call discarded in case there is lazy initialization.\n\n        Returns\n        -------\n        ftimer : function\n            The function that takes same argument as func and returns a BenchmarkResult.\n            The ProfileResult reports `repeat` time costs in seconds.\n        \"\"\"\n        try:\n            feval = _ffi_api.RPCTimeEvaluator(\n                self,\n                func_name,\n                dev.device_type,\n                dev.device_id,\n                number,\n                repeat,\n                min_repeat_ms,\n                limit_zero_time_iterations,\n                cooldown_interval_ms,\n                repeats_to_cooldown,\n                f_preproc,\n            )\n\n            def evaluator(*args):\n                \"\"\"Internal wrapped evaluator.\"\"\"\n                # Wrap feval so we can add more stats in future.\n                blob = feval(*args)\n                fmt = \"@\" + (\"d\" * repeat)\n                results = struct.unpack(fmt, blob)\n                return BenchmarkResult(results)\n\n            return evaluator\n        except NameError:\n            raise NameError(\"time_evaluator is only supported when RPC is enabled\")\n\n    def _collect_from_import_tree(self, filter_func):\n        \"\"\"Helper function to collect modules from the tree matching a filter_func, then return it.\n\n        Parameters\n        ----------\n        filter_func : Callable[[Module], bool]\n            A function which is invoked for each Module discovered in the import tree (including\n            self).\n\n        Returns\n        -------\n        list[Module] :\n            A list of matching Module.\n        \"\"\"\n        visited, stack, dso_modules = set(), [], []\n        # append root module\n        visited.add(self)\n        stack.append(self)\n        while stack:\n            module = stack.pop()\n            if filter_func(module):\n                dso_modules.append(module)\n            for m in module.imported_modules:\n                if m not in visited:\n                    visited.add(m)\n                    stack.append(m)\n        return dso_modules\n\n    def _collect_dso_modules(self):\n        return self._collect_from_import_tree(lambda m: m.is_dso_exportable)\n\n    def export_library(self, file_name, fcompile=None, addons=None, workspace_dir=None, **kwargs):\n        \"\"\"\n        Export the module and all imported modules into a single device library.\n\n        This function only works on host LLVM modules, other runtime::Module\n        subclasses will work with this API but they must support implement\n        the save and load mechanisms of modules completely including saving\n        from streams and files. This will pack your non-shared library module\n        into a single shared library which can later be loaded by TVM.\n\n        Parameters\n        ----------\n        file_name : str\n            The name of the shared library.\n\n        fcompile : function(target, file_list, kwargs), optional\n            The compilation function to use create the final library object during\n            export.\n\n            For example, when fcompile=_cc.create_shared, or when it is not supplied but\n            module is \"llvm,\" this is used to link all produced artifacts\n            into a final dynamic library.\n\n            This behavior is controlled by the type of object exported.\n            If fcompile has attribute object_format, will compile host library\n            to that format. Otherwise, will use default format \"o\".\n\n        workspace_dir : str, optional\n            The path of the directory used to create the intermediate\n            artifacts when exporting the module.\n            If this is not provided a temporary dir will be created.\n\n        kwargs : dict, optional\n            Additional arguments passed to fcompile\n\n        Returns\n        -------\n        result of fcompile()  : unknown, optional\n            If the compilation function returns an artifact it would be returned via\n            export_library, if any.\n        \"\"\"\n        # NOTE: this function depends on contrib library features\n        # which are only available in when TVM function is available.\n        if _RUNTIME_ONLY:\n            raise RuntimeError(\"Cannot call export_library in runtime only mode\")\n        # Extra dependencies during runtime.\n        from pathlib import Path\n        from tvm.contrib import cc as _cc, tar as _tar, utils as _utils\n\n        if isinstance(file_name, Path):\n            file_name = str(file_name)\n\n        if self.type_key == \"stackvm\":\n            if not file_name.endswith(\".stackvm\"):\n                raise ValueError(\n                    \"Module[%s]: can only be saved as stackvm format.\"\n                    \"did you build with LLVM enabled?\" % self.type_key\n                )\n            self.save(file_name)\n            return\n\n        modules = self._collect_dso_modules()\n        if workspace_dir is None:\n            temp = _utils.tempdir()\n            workspace_dir = temp.temp_dir\n        files = addons if addons else []\n        is_system_lib = False\n        has_c_module = False\n        llvm_target_string = None\n        for index, module in enumerate(modules):\n            if fcompile is not None and hasattr(fcompile, \"object_format\"):\n                if module.type_key == \"c\":\n                    assert module.format in [\n                        \"c\",\n                        \"cc\",\n                        \"cpp\",\n                        \"cu\",\n                    ], \"The module.format needs to be either c, cc, cpp or cu.\"\n                    object_format = module.format\n                    has_c_module = True\n                else:\n                    object_format = fcompile.object_format\n            else:\n                if module.type_key == \"c\":\n                    if len(module.format) > 0:\n                        assert module.format in [\n                            \"c\",\n                            \"cc\",\n                            \"cpp\",\n                            \"cu\",\n                        ], \"The module.format needs to be either c, cc, cpp, or cu.\"\n                        object_format = module.format\n                    else:\n                        object_format = \"c\"\n                    if \"cc\" in kwargs:\n                        if kwargs[\"cc\"] == \"nvcc\":\n                            object_format = \"cu\"\n                    has_c_module = True\n                else:\n                    assert module.type_key == \"llvm\" or module.type_key == \"static_library\"\n                    object_format = \"o\"\n            path_obj = os.path.join(workspace_dir, f\"lib{index}.{object_format}\")\n            module.save(path_obj)\n            files.append(path_obj)\n            is_system_lib = (\n                module.type_key == \"llvm\" and module.get_function(\"__tvm_is_system_module\")()\n            )\n            llvm_target_string = (\n                module.type_key == \"llvm\" and module.get_function(\"_get_target_string\")()\n            )\n        if not fcompile:\n            if file_name.endswith(\".tar\"):\n                fcompile = _tar.tar\n            else:\n                fcompile = _cc.create_shared\n\n        if llvm_target_string is None and hasattr(fcompile, \"get_target_triple\"):\n            triple = fcompile.get_target_triple()\n            assert triple, \"Target triple should not be empty\"\n            llvm_target_string = \"llvm -mtriple \" + triple\n\n        if getattr(fcompile, \"need_system_lib\", False) and not is_system_lib:\n            raise ValueError(\"%s need --system-lib option\" % str(fcompile))\n\n        if self.imported_modules:\n            if enabled(\"llvm\") and llvm_target_string:\n                path_obj = os.path.join(workspace_dir, f\"devc.{object_format}\")\n                m = _ffi_api.ModulePackImportsToLLVM(self, is_system_lib, llvm_target_string)\n                m.save(path_obj)\n                files.append(path_obj)\n            else:\n                path_cc = os.path.join(workspace_dir, \"devc.c\")\n                with open(path_cc, \"w\") as f:\n                    f.write(_ffi_api.ModulePackImportsToC(self, is_system_lib))\n                files.append(path_cc)\n\n        # The imports could contain a c module but the object format could be tar\n        # Thus, it would not recognize the following include paths as options\n        # which are there assuming a c compiler is the fcompile.\n        if has_c_module and not file_name.endswith(\".tar\"):\n            options = []\n            if \"options\" in kwargs:\n                opts = kwargs[\"options\"]\n                options = opts if isinstance(opts, (list, tuple)) else [opts]\n            opts = options + [\"-I\" + path for path in find_include_path()]\n            kwargs.update({\"options\": opts})\n\n        return fcompile(file_name, files, **kwargs)\n\n\ndef system_lib():\n    \"\"\"Get system-wide library module singleton.\n\n    System lib is a global module that contains self register functions in startup.\n    Unlike normal dso modules which need to be loaded explicitly.\n    It is useful in environments where dynamic loading api like dlopen is banned.\n\n    To build system lib function, simply specify target option ```llvm --system-lib```\n    The system lib will be available as long as the result code is linked by the program.\n\n    The system lib is intended to be linked and loaded during the entire life-cyle of the program.\n    If you want dynamic loading features, use dso modules instead.\n\n    Returns\n    -------\n    module : runtime.Module\n        The system-wide library module.\n    \"\"\"\n    return _ffi_api.SystemLib()\n\n\ndef load_module(path, fmt=\"\"):\n    \"\"\"Load module from file.\n\n    Parameters\n    ----------\n    path : str\n        The path to the module file.\n\n    fmt : str, optional\n        The format of the file, if not specified\n        it will be inferred from suffix of the file.\n\n    Returns\n    -------\n    module : runtime.Module\n        The loaded module\n\n    Note\n    ----\n    This function will automatically call\n    cc.create_shared if the path is in format .o or .tar\n    \"\"\"\n    if os.path.isfile(path):\n        path = os.path.realpath(path)\n    else:\n        raise ValueError(\"cannot find file %s\" % path)\n\n    # High level handling for .o and .tar file.\n    # We support this to be consistent with RPC module load.\n    if path.endswith(\".o\"):\n        # Extra dependencies during runtime.\n        from tvm.contrib import cc as _cc\n\n        _cc.create_shared(path + \".so\", path)\n        path += \".so\"\n    elif path.endswith(\".tar\"):\n        # Extra dependencies during runtime.\n        from tvm.contrib import cc as _cc, utils as _utils, tar as _tar\n\n        tar_temp = _utils.tempdir(custom_path=path.replace(\".tar\", \"\"))\n        _tar.untar(path, tar_temp.temp_dir)\n        files = [tar_temp.relpath(x) for x in tar_temp.listdir()]\n        _cc.create_shared(path + \".so\", files)\n        path += \".so\"\n    # Redirect to the load API\n    return _ffi_api.ModuleLoadFromFile(path, fmt)\n\n\ndef load_static_library(path, func_names):\n    \"\"\"Load the .o library at path which implements functions with func_names.\n    Unlike the generic load_module the result will remain as a static_library\n    and will not be relinked on-the-fly into a .so library.\"\"\"\n    return _ffi_api.ModuleLoadStaticLibrary(path, func_names)\n\n\ndef enabled(target):\n    \"\"\"Whether module runtime is enabled for target\n\n    Parameters\n    ----------\n    target : str\n        The target device type.\n\n    Returns\n    -------\n    enabled : bool\n        Whether runtime is enabled.\n\n    Examples\n    --------\n    The following code checks if gpu is enabled.\n\n    >>> tvm.runtime.enabled(\"gpu\")\n    \"\"\"\n    return _ffi_api.RuntimeEnabled(target)\n\n\ndef num_threads() -> int:\n    \"\"\"Get the number of threads in use by the TVM runtime.\n\n    Returns\n    -------\n    int\n        Number of threads in use.\n    \"\"\"\n    return _ffi_api.NumThreads()\n\n\n_set_class_module(Module)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/name_transforms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nName transformation functions shared in Backend and Runtime\n\"\"\"\n\nfrom . import _ffi_api\n\n\ndef sanitize_name(original_name: str):\n    \"\"\"Sanitize name for output into compiler artifacts\n\n    Parameters\n    ----------\n    original_name : str\n        Original name to sanitize\n    \"\"\"\n    return _ffi_api.SanitizeName(original_name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/ndarray.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-import, redefined-outer-name\n\"\"\"Runtime NDArray API\"\"\"\nimport ctypes\nimport warnings\nimport numpy as np\nimport tvm._ffi\n\nfrom tvm._ffi.base import _LIB, check_call, c_array, string_types, _FFI_MODE\nfrom tvm._ffi.runtime_ctypes import DataType, Device, TVMArray, TVMArrayHandle\nfrom tvm._ffi.runtime_ctypes import DataTypeCode, tvm_shape_index_t\nfrom . import _ffi_api\n\ntry:\n    # pylint: disable=wrong-import-position\n    if _FFI_MODE == \"ctypes\":\n        raise ImportError()\n    from tvm._ffi._cy3.core import _set_class_ndarray, _make_array, _from_dlpack\n    from tvm._ffi._cy3.core import NDArrayBase\nexcept (RuntimeError, ImportError) as error:\n    # pylint: disable=wrong-import-position\n    if _FFI_MODE == \"cython\":\n        raise error\n    from tvm._ffi._ctypes.ndarray import _set_class_ndarray, _make_array, _from_dlpack\n    from tvm._ffi._ctypes.ndarray import NDArrayBase\n\n\n@tvm._ffi.register_object(\"runtime.NDArray\")\nclass NDArray(NDArrayBase):\n    \"\"\"Lightweight NDArray class of TVM runtime.\n\n    Strictly this is only an Array Container (a buffer object)\n    No arthimetic operations are defined.\n    All operations are performed by TVM functions.\n\n    The goal is not to re-build yet another array library.\n    Instead, this is a minimal data structure to demonstrate\n    how can we use TVM in existing project which might have their own array containers.\n    \"\"\"\n\n    @property\n    def dtype(self):\n        \"\"\"Type of this array\"\"\"\n        return str(self.handle.contents.dtype)\n\n    @property\n    def device(self):\n        \"\"\"Device of this array\"\"\"\n        return self.handle.contents.device\n\n    def __dlpack__(self, stream=None):  # pylint: disable=unused-argument\n        \"\"\"Export the array for consumption by from_dlpack() as a DLPack capsule.\n\n        Parameters\n        ----------\n        stream : int, optional\n            A Python integer representing a pointer to a stream.\n            Stream is provided by the consumer to the producer to instruct the producer\n            to ensure that operations can safely be performed on the array.\n\n        Returns\n        -------\n        capsule : PyCapsule\n            A DLPack capsule for the array, containing a DLPackManagedTensor.\n        \"\"\"\n        return self.to_dlpack()\n\n    def __dlpack_device__(self):\n        \"\"\"Return a tuple of device_type, device_id in DLPack convention\"\"\"\n        return (self.handle.contents.device.device_type, self.handle.contents.device.device_id)\n\n    def __hash__(self):\n        return ctypes.cast(self.handle, ctypes.c_void_p).value\n\n    def __eq__(self, other):\n        return self.same_as(other)\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def same_as(self, other):\n        \"\"\"Check object identity equality\n\n        Parameters\n        ----------\n        other : object\n            The other object to compare to\n\n        Returns\n        -------\n        same : bool\n            Whether other is same as self.\n        \"\"\"\n        if not isinstance(other, NDArrayBase):\n            return False\n        return self.__hash__() == other.__hash__()\n\n    def __setitem__(self, in_slice, value):\n        \"\"\"Set ndarray value\"\"\"\n        if (\n            not isinstance(in_slice, slice)\n            or in_slice.start is not None\n            or in_slice.stop is not None\n        ):\n            raise ValueError(\"Array only support set from numpy array\")\n        if isinstance(value, NDArrayBase):\n            if value.handle is not self.handle:\n                value.copyto(self)\n        elif isinstance(value, (np.ndarray, np.generic)):\n            self.copyfrom(value)\n        else:\n            raise TypeError(\"type %s not supported\" % str(type(value)))\n\n    def copyfrom(self, source_array):\n        \"\"\"Perform a synchronous copy from the array.\n\n        Parameters\n        ----------\n        source_array : array_like\n            The data source we should like to copy from.\n\n        Returns\n        -------\n        arr : NDArray\n            Reference to self.\n        \"\"\"\n        if isinstance(source_array, NDArrayBase):\n            source_array.copyto(self)\n            return self\n\n        if not isinstance(source_array, np.ndarray):\n            try:\n                source_array = np.array(source_array, dtype=self.dtype)\n            except:\n                raise TypeError(\n                    \"array must be an array_like data,\"\n                    + \"type %s is not supported\" % str(type(source_array))\n                )\n\n        t = DataType(self.dtype)\n        shape, dtype = self.shape, self.dtype\n        if t.lanes > 1:\n            shape = shape + (t.lanes,)\n            t.lanes = 1\n            dtype = str(t)\n\n        if source_array.shape != shape:\n            raise ValueError(\n                \"array shape do not match the shape of NDArray {0} vs {1}\".format(\n                    source_array.shape, shape\n                )\n            )\n        numpy_str_map = DataType.NUMPY2STR\n        np_dtype_str = (\n            numpy_str_map[source_array.dtype]\n            if source_array.dtype in numpy_str_map\n            else str(source_array.dtype)\n        )\n        if (not source_array.flags[\"C_CONTIGUOUS\"]) or (\n            dtype == \"bfloat16\" or dtype != np_dtype_str\n        ):\n            source_array = np.ascontiguousarray(\n                source_array, dtype=\"uint16\" if dtype == \"bfloat16\" else dtype\n            )\n        assert source_array.flags[\"C_CONTIGUOUS\"]\n        data = source_array.ctypes.data_as(ctypes.c_void_p)\n        nbytes = ctypes.c_size_t(source_array.size * source_array.dtype.itemsize)\n        check_call(_LIB.TVMArrayCopyFromBytes(self.handle, data, nbytes))\n        return self\n\n    def __repr__(self):\n        res = \"<tvm.nd.NDArray shape={0}, {1}>\\n\".format(self.shape, self.device)\n        res += self.numpy().__repr__()\n        return res\n\n    def __str__(self):\n        return str(self.numpy())\n\n    def asnumpy(self):\n        \"\"\"Convert this array to numpy array. This API will be deprecated in TVM v0.8 release.\n        Please use `numpy` instead.\"\"\"\n        warnings.warn(\n            \"NDArray.asnumpy() will be deprecated in TVM v0.8 release. \"\n            \"Please use NDArray.numpy() instead.\",\n            DeprecationWarning,\n        )\n        return self.numpy()\n\n    def numpy(self):\n        \"\"\"Convert this array to numpy array\n\n        Returns\n        -------\n        np_arr : numpy.ndarray\n            The corresponding numpy array.\n        \"\"\"\n        t = DataType(self.dtype)\n        shape, dtype = self.shape, self.dtype\n        old_dtype = dtype\n        if t.lanes > 1:\n            shape = shape + (t.lanes,)\n            t.lanes = 1\n            dtype = str(t)\n        if dtype == \"int4\":\n            dtype = \"int8\"\n        if dtype == \"bfloat16\":\n            dtype = \"uint16\"\n        np_arr = np.empty(shape, dtype=dtype)\n        assert np_arr.flags[\"C_CONTIGUOUS\"]\n        data = np_arr.ctypes.data_as(ctypes.c_void_p)\n        nbytes = ctypes.c_size_t(np_arr.size * np_arr.dtype.itemsize)\n        check_call(_LIB.TVMArrayCopyToBytes(self.handle, data, nbytes))\n        if old_dtype == \"int4\":\n            length = np_arr.size\n            np_arr_ret = np.empty((length,), dtype=\"int8\")\n            np_arr = np_arr.reshape((length,))\n            old_index = np.bitwise_and(np_arr, 0x0F)\n            even_index = np.bitwise_and(np_arr >> 4, 0x0F)\n            np_arr_ret[1::2] = old_index[0 : length // 2]\n            np_arr_ret[0::2] = even_index[0 : length // 2]\n            return np_arr_ret.reshape(shape)\n        return np_arr\n\n    def copyto(self, target, mem_scope=None):\n        \"\"\"Copy array to target\n\n        Parameters\n        ----------\n        target : NDArray\n            The target array to be copied, must have same shape as this array.\n\n        mem_scope : Optional[str]\n            The memory scope of the array.\n        \"\"\"\n        if isinstance(target, NDArrayBase):\n            return self._copyto(target)\n        if isinstance(target, Device):\n            res = empty(self.shape, self.dtype, target, mem_scope)\n            return self._copyto(res)\n        raise ValueError(\"Unsupported target type %s\" % str(type(target)))\n\n    def _create_view(self, shape):\n        \"\"\"Create a view into an existing array.\n\n        The view shares the same allocation and datatype as the\n        existing array, but can have a different array shape.  This is\n        useful for runtimes that support non-flat memory, where both\n        the physical shape of an allocation and the logical shape of\n        the tensor it represents may need to be independently\n        specified.\n\n        Warning: This function should not be used outside of low-level\n        manipulations, as it breaks non-aliasing assumptions made by\n        TVM.  This function may also be removed/replaced in the\n        future.\n\n        Parameters\n        ----------\n        shape: Union[tvm.runtime.ShapeTuple, Sequence[typing.SupportsInt]]\n\n            The shape of the view.\n        \"\"\"\n\n        if not isinstance(shape, tvm.runtime.ShapeTuple):\n            shape = tvm.runtime.ShapeTuple([int(dim) for dim in shape])\n\n        return _ffi_api.TVMArrayCreateView(self, shape)\n\n\ndef device(dev_type, dev_id=0):\n    \"\"\"Construct a TVM device with given device type and id.\n\n    Parameters\n    ----------\n    dev_type: int or str\n        The device type mask or name of the device.\n\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev: tvm.runtime.Device\n        The corresponding device.\n\n    Examples\n    --------\n    Device can be used to create reflection of device by\n    string representation of the device type.\n\n    .. code-block:: python\n\n      assert tvm.device(\"cpu\", 1) == tvm.cpu(1)\n      assert tvm.device(\"cuda\", 0) == tvm.cuda(0)\n    \"\"\"\n    if isinstance(dev_type, string_types):\n        dev_type = dev_type.split()[0]\n        if dev_type not in Device.STR2MASK:\n            raise ValueError(\"Unknown device type %s\" % dev_type)\n        dev_type = Device.STR2MASK[dev_type]\n    return Device(dev_type, dev_id)\n\n\ndef numpyasarray(np_data):\n    \"\"\"Return a TVMArray representation of a numpy array.\"\"\"\n    data = np_data\n    assert data.flags[\"C_CONTIGUOUS\"]\n    arr = TVMArray()\n    shape = c_array(tvm_shape_index_t, data.shape)\n    arr.data = data.ctypes.data_as(ctypes.c_void_p)\n    arr.shape = shape\n    arr.strides = None\n    arr.dtype = DataType(np.dtype(data.dtype).name)\n    arr.ndim = data.ndim\n    # CPU device\n    arr.device = device(Device.kDLCPU, 0)\n    return arr, shape\n\n\ndef empty(shape, dtype=\"float32\", device=device(Device.kDLCPU, 0), mem_scope=None):\n    \"\"\"Create an empty array given shape and device\n\n    Parameters\n    ----------\n    shape : Union[tvm.runtime.ShapeTuple, Sequence[typing.SupportsInt]]\n        The shape of the array.\n\n    dtype : type or str\n        The data type of the array.\n\n    device : Device\n        The device of the array.\n\n    mem_scope : Optional[str]\n        The memory scope of the array.\n\n    Returns\n    -------\n    arr : tvm.nd.NDArray\n        The array tvm supported.\n    \"\"\"\n    if not isinstance(shape, tvm.runtime.ShapeTuple):\n        shape = tvm.runtime.ShapeTuple([int(dim) for dim in shape])\n    dtype = DataType(dtype)\n    arr = _ffi_api.TVMArrayAllocWithScope(shape, dtype, device, mem_scope)\n    return arr\n\n\ndef from_dlpack(dltensor):\n    \"\"\"Produces an array from an object with __dlpack__ method or a DLPack tensor w/o memory copy.\n    Retreives the underlying DLPack tensor's pointer to create an array from the\n    data. Removes the original DLPack tensor's destructor as now the array is\n    responsible for destruction.\n\n    Parameters\n    ----------\n    dltensor : object with __dlpack__ attribute or a DLPack capsule\n\n    Returns\n    -------\n    arr: tvm.nd.NDArray\n        The array view of the tensor data.\n    \"\"\"\n    t = type(dltensor)\n    if t.__module__ == \"builtins\" and t.__name__ == \"PyCapsule\":\n        return _from_dlpack(dltensor)\n\n    if hasattr(dltensor, \"__dlpack__\"):\n        dlpack_caps = dltensor.__dlpack__()\n        return _from_dlpack(dlpack_caps)\n    raise AttributeError(\"Required attribute __dlpack__ not found\")\n\n\ndef cpu(dev_id=0):\n    \"\"\"Construct a CPU device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLCPU, dev_id)\n\n\ndef cuda(dev_id=0):\n    \"\"\"Construct a CUDA GPU device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLCUDA, dev_id)\n\n\ndef gpu(dev_id=0):\n    \"\"\"Construct a CUDA GPU device\n\n        deprecated:: 0.9.0\n        Use :py:func:`tvm.cuda` instead.\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    warnings.warn(\n        \"Please use tvm.cuda() instead of tvm.gpu(). tvm.gpu() is going to be deprecated in 0.9.0\",\n    )\n    return Device(Device.kDLCUDA, dev_id)\n\n\ndef rocm(dev_id=0):\n    \"\"\"Construct a ROCM device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLROCM, dev_id)\n\n\ndef opencl(dev_id=0):\n    \"\"\"Construct a OpenCL device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLOpenCL, dev_id)\n\n\ndef metal(dev_id=0):\n    \"\"\"Construct a metal device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLMetal, dev_id)\n\n\ndef vpi(dev_id=0):\n    \"\"\"Construct a VPI simulated device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLVPI, dev_id)\n\n\ndef vulkan(dev_id=0):\n    \"\"\"Construct a Vulkan device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLVulkan, dev_id)\n\n\ndef ext_dev(dev_id=0):\n    \"\"\"Construct a extension device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n\n    Note\n    ----\n    This API is reserved for quick testing of new\n    device by plugin device API as ext_dev.\n    \"\"\"\n    return Device(Device.kDLExtDev, dev_id)\n\n\ndef hexagon(dev_id=0):\n    \"\"\"Construct a Hexagon device\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLHexagon, dev_id)\n\n\ndef webgpu(dev_id=0):\n    \"\"\"Construct a webgpu device.\n\n    Parameters\n    ----------\n    dev_id : int, optional\n        The integer device id\n\n    Returns\n    -------\n    dev : Device\n        The created device\n    \"\"\"\n    return Device(Device.kDLWebGPU, dev_id)\n\n\ncl = opencl\nmtl = metal\n\n\ndef array(arr, device=cpu(0), mem_scope=None):\n    \"\"\"Create an array from source arr.\n\n    Parameters\n    ----------\n    arr : numpy.ndarray\n        The array to be copied from\n\n    device : Device, optional\n        The device device to create the array\n\n    mem_scope : Optional[str]\n        The memory scope of the array\n\n    Returns\n    -------\n    ret : NDArray\n        The created array\n    \"\"\"\n    if isinstance(arr, tvm.ir.container.Array):\n        raise AttributeError(\"arr is an instance of\", type(arr))\n\n    if not isinstance(arr, (np.ndarray, NDArray)):\n        arr = np.array(arr)\n    return empty(arr.shape, arr.dtype, device, mem_scope).copyfrom(arr)\n\n\n# Register back to FFI\n_set_class_ndarray(NDArray)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/object.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-import\n\"\"\"Runtime Object API\"\"\"\nimport ctypes\n\nfrom tvm._ffi.base import _FFI_MODE, _RUNTIME_ONLY, check_call, _LIB, c_str\nfrom tvm._ffi.runtime_ctypes import ObjectRValueRef\nfrom . import _ffi_api, _ffi_node_api\n\ntry:\n    # pylint: disable=wrong-import-position,unused-import\n    if _FFI_MODE == \"ctypes\":\n        raise ImportError()\n    from tvm._ffi._cy3.core import _set_class_object, _set_class_object_generic\n    from tvm._ffi._cy3.core import ObjectBase, PyNativeObject\nexcept (RuntimeError, ImportError) as error:\n    # pylint: disable=wrong-import-position,unused-import\n    if _FFI_MODE == \"cython\":\n        raise error\n    from tvm._ffi._ctypes.packed_func import _set_class_object, _set_class_object_generic\n    from tvm._ffi._ctypes.object import ObjectBase, PyNativeObject\n\n\ndef _new_object(cls):\n    \"\"\"Helper function for pickle\"\"\"\n    return cls.__new__(cls)\n\n\nclass Object(ObjectBase):\n    \"\"\"Base class for all tvm's runtime objects.\"\"\"\n\n    __slots__ = []\n\n    def __repr__(self):\n        return _ffi_node_api.AsRepr(self)\n\n    def __dir__(self):\n        class_names = dir(self.__class__)\n        fnames = _ffi_node_api.NodeListAttrNames(self)\n        size = fnames(-1)\n        return sorted([fnames(i) for i in range(size)] + class_names)\n\n    def __getattr__(self, name):\n        # specially check handle since\n        # this is required for PackedFunc calls\n        if name == \"handle\":\n            raise AttributeError(\"handle is not set\")\n\n        try:\n            return _ffi_node_api.NodeGetAttr(self, name)\n        except AttributeError:\n            raise AttributeError(\"%s has no attribute %s\" % (str(type(self)), name)) from None\n\n    def __hash__(self):\n        return _ffi_api.ObjectPtrHash(self)\n\n    def __eq__(self, other):\n        return self.same_as(other)\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def __reduce__(self):\n        cls = type(self)\n        return (_new_object, (cls,), self.__getstate__())\n\n    def __getstate__(self):\n        handle = self.handle\n        if handle is not None:\n            return {\"handle\": _ffi_node_api.SaveJSON(self)}\n        return {\"handle\": None}\n\n    def __setstate__(self, state):\n        # pylint: disable=assigning-non-slot, assignment-from-no-return\n        handle = state[\"handle\"]\n        self.handle = None\n        if handle is not None:\n            self.__init_handle_by_constructor__(_ffi_node_api.LoadJSON, handle)\n\n    def _move(self):\n        \"\"\"Create an RValue reference to the object and mark the object as moved.\n\n        This is a advanced developer API that can be useful when passing an\n        unique reference to an Object that you no longer needed to a function.\n\n        A unique reference can trigger copy on write optimization that avoids\n        copy when we transform an object.\n\n        Note\n        ----\n        All the reference of the object becomes invalid after it is moved.\n        Be very careful when using this feature.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n           x = tvm.tir.Var(\"x\", \"int32\")\n           x0 = x\n           some_packed_func(x._move())\n           # both x0 and x will points to None after the function call.\n\n        Returns\n        -------\n        rvalue : The rvalue reference.\n        \"\"\"\n        return ObjectRValueRef(self)\n\n\n_set_class_object(Object)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/object_generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common implementation of object generic related logic\"\"\"\n# pylint: disable=unused-import, invalid-name\nfrom numbers import Number, Integral\nfrom tvm._ffi.base import string_types\nfrom tvm._ffi.runtime_ctypes import ObjectRValueRef\n\nfrom . import _ffi_node_api, _ffi_api\nfrom .object import ObjectBase, PyNativeObject, _set_class_object_generic\nfrom .ndarray import NDArrayBase\nfrom .packed_func import PackedFuncBase, convert_to_tvm_func\nfrom .module import Module\n\n\nclass ObjectGeneric(object):\n    \"\"\"Base class for all classes that can be converted to object.\"\"\"\n\n    def asobject(self):\n        \"\"\"Convert value to object\"\"\"\n        raise NotImplementedError()\n\n\nObjectTypes = (ObjectBase, NDArrayBase, Module, ObjectRValueRef, PyNativeObject)\n\n\ndef convert_to_object(value, span=None):\n    \"\"\"Convert a Python value to corresponding object type.\n\n    Parameters\n    ----------\n    value : str\n        The value to be inspected.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n\n    Returns\n    -------\n    obj : Object\n        The corresponding object value.\n    \"\"\"\n    if isinstance(value, ObjectTypes):\n        return value\n    if isinstance(value, bool):\n        return const(value, \"uint1x1\", span=span)\n    if isinstance(value, Number):\n        return const(value, span=span)\n    if isinstance(value, string_types):\n        return _ffi_api.String(value)\n    if isinstance(value, (list, tuple)):\n        value = [convert_to_object(x) for x in value]\n        return _ffi_api.Array(*value)\n    if isinstance(value, dict):\n        vlist = []\n        for item in value.items():\n            if (\n                not isinstance(item[0], ObjectTypes)\n                and not isinstance(item[0], string_types)\n                and not isinstance(item[0], Number)\n            ):\n                raise ValueError(\"key of map must already been a container type\")\n            vlist.append(convert_to_object(item[0]))\n            vlist.append(convert_to_object(item[1]))\n        return _ffi_api.Map(*vlist)\n    if isinstance(value, ObjectGeneric):\n        return value.asobject()\n    if value is None:\n        return None\n\n    raise ValueError(\"don't know how to convert type %s to object\" % type(value))\n\n\ndef convert(value, span=None):\n    \"\"\"Convert value to TVM object or function.\n\n    Parameters\n    ----------\n    value : python value\n\n    span : Optional[Span]\n        The location of this statement in the source code.\n\n    Returns\n    -------\n    tvm_val : Object or Function\n        Converted value in TVM\n    \"\"\"\n    if isinstance(value, (PackedFuncBase, ObjectBase)):\n        return value\n\n    if callable(value):\n        return convert_to_tvm_func(value)\n\n    return convert_to_object(value, span=span)\n\n\ndef _scalar_type_inference(value):\n    if hasattr(value, \"dtype\"):\n        dtype = str(value.dtype)\n    elif isinstance(value, bool):\n        dtype = \"bool\"\n    elif isinstance(value, float):\n        # We intentionally prefer convert the float to float32 since it's more common in DL.\n        if -3.40282347e38 <= value <= 3.40282347e38:\n            dtype = \"float32\"\n        else:\n            dtype = \"float64\"\n    elif isinstance(value, int):\n        # We intentionally prefer convert the python int to int32 since it's more common in DL.\n        if -2147483648 <= value <= 2147483647:\n            dtype = \"int32\"\n        else:\n            dtype = \"int64\"\n    else:\n        raise NotImplementedError(\n            \"Cannot automatically inference the type.\" \" value={}\".format(value)\n        )\n    return dtype\n\n\ndef const(value, dtype=None, span=None):\n    \"\"\"construct a constant\n\n    Parameters\n    ----------\n    value : number\n        The content of the constant number.\n\n    dtype : str or None, optional\n        The data type.\n\n    span : Optional[Span]\n        The location of the constant value in the source.\n\n    Returns\n    -------\n    const_val: tvm.Expr\n        The result expression.\n    \"\"\"\n    if dtype is None:\n        dtype = _scalar_type_inference(value)\n    if dtype == \"uint64\" and value >= (1 << 63):\n        return _ffi_node_api.LargeUIntImm(dtype, value & ((1 << 32) - 1), value >> 32, span)\n    return _ffi_node_api._const(value, dtype, span)\n\n\n_set_class_object_generic(ObjectGeneric, convert_to_object)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/object_path.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nObjectPath class that represents a path from a root object to one of its descendants\nvia attribute access, array indexing etc.\n\"\"\"\n\nimport tvm._ffi\nfrom tvm.runtime import Object\nfrom . import _ffi_node_api\n\n\n__all__ = (\n    \"ObjectPath\",\n    \"RootPath\",\n    \"AttributeAccessPath\",\n    \"UnknownAttributeAccessPath\",\n    \"ArrayIndexPath\",\n    \"MissingArrayElementPath\",\n    \"MapValuePath\",\n    \"MissingMapEntryPath\",\n    \"ObjectPathPair\",\n)\n\n\n@tvm._ffi.register_object(\"ObjectPath\")\nclass ObjectPath(Object):\n    \"\"\"\n    Path to an object from some root object.\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        raise ValueError(\n            \"ObjectPath can't be initialized directly. \"\n            \"Use ObjectPath.root() to create a path to the root object\"\n        )\n\n    @staticmethod\n    def root() -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathRoot()\n\n    def __eq__(self, other):\n        return _ffi_node_api.ObjectPathEqual(self, other)\n\n    def __ne__(self, other):\n        return not _ffi_node_api.ObjectPathEqual(self, other)\n\n    @property\n    def parent(self) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathGetParent(self)\n\n    def __len__(self) -> int:\n        return _ffi_node_api.ObjectPathLength(self)\n\n    def get_prefix(self, length) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathGetPrefix(self, length)\n\n    def is_prefix_of(self, other) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathIsPrefixOf(self, other)\n\n    def attr(self, attr_key) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathAttr(self, attr_key)\n\n    def array_index(self, index) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathArrayIndex(self, index)\n\n    def missing_array_element(self, index) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathMissingArrayElement(self, index)\n\n    def map_value(self, key) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathMapValue(self, tvm.runtime.convert(key))\n\n    def missing_map_entry(self) -> \"ObjectPath\":\n        return _ffi_node_api.ObjectPathMissingMapEntry(self)\n\n\n@tvm._ffi.register_object(\"RootPath\")\nclass RootPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"AttributeAccessPath\")\nclass AttributeAccessPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"UnknownAttributeAccessPath\")\nclass UnknownAttributeAccessPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"ArrayIndexPath\")\nclass ArrayIndexPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"MissingArrayElementPath\")\nclass MissingArrayElementPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"MapValuePath\")\nclass MapValuePath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"MissingMapEntryPath\")\nclass MissingMapEntryPath(ObjectPath):\n    pass\n\n\n@tvm._ffi.register_object(\"ObjectPathPair\")\nclass ObjectPathPair(Object):\n    \"\"\"\n    Pair of ObjectPaths, one for each object being tested for structural equality.\n    \"\"\"\n\n    @property\n    def lhs_path(self) -> ObjectPath:\n        return _ffi_node_api.ObjectPathPairLhsPath(self)\n\n    @property\n    def rhs_path(self) -> ObjectPath:\n        return _ffi_node_api.ObjectPathPairRhsPath(self)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/packed_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-import\n\"\"\"Packed Function namespace.\"\"\"\nimport ctypes\nfrom tvm._ffi.base import _LIB, check_call, c_str, string_types, _FFI_MODE\n\ntry:\n    # pylint: disable=wrong-import-position\n    if _FFI_MODE == \"ctypes\":\n        raise ImportError()\n    from tvm._ffi._cy3.core import _set_class_packed_func, _set_class_module\n    from tvm._ffi._cy3.core import PackedFuncBase\n    from tvm._ffi._cy3.core import convert_to_tvm_func\nexcept (RuntimeError, ImportError) as error:\n    # pylint: disable=wrong-import-position\n    if _FFI_MODE == \"cython\":\n        raise error\n    from tvm._ffi._ctypes.packed_func import _set_class_packed_func, _set_class_module\n    from tvm._ffi._ctypes.packed_func import PackedFuncBase\n    from tvm._ffi._ctypes.packed_func import convert_to_tvm_func\n\n\nPackedFuncHandle = ctypes.c_void_p\n\n\nclass PackedFunc(PackedFuncBase):\n    \"\"\"The PackedFunc object used in TVM.\n\n    Function plays an key role to bridge front and backend in TVM.\n    Function provide a type-erased interface, you can call function with positional arguments.\n\n    The compiled module returns Function.\n    TVM backend also registers and exposes its API as Functions.\n\n    The following are list of common usage scenario of tvm.runtime.PackedFunc.\n\n    - Automatic exposure of C++ API into python\n    - To call PackedFunc from python side\n    - To call python callbacks to inspect results in generated code\n    - Bring python hook into C++ backend\n\n    See Also\n    --------\n    tvm.register_func: How to register global function.\n    tvm.get_global_func: How to get global function.\n    \"\"\"\n\n\n_set_class_packed_func(PackedFunc)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/params.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Helper utility to save and load parameter dicts.\"\"\"\nfrom . import _ffi_api, ndarray\n\n\ndef save_param_dict(params):\n    \"\"\"Save parameter dictionary to binary bytes.\n\n    The result binary bytes can be loaded by the\n    GraphModule with API \"load_params\".\n\n    Parameters\n    ----------\n    params : dict of str to NDArray\n        The parameter dictionary.\n\n    Returns\n    -------\n    param_bytes: bytearray\n        Serialized parameters.\n\n    Examples\n    --------\n    .. code-block:: python\n\n       # set up the parameter dict\n       params = {\"param0\": arr0, \"param1\": arr1}\n       # save the parameters as byte array\n       param_bytes = tvm.runtime.save_param_dict(params)\n       # We can serialize the param_bytes and load it back later.\n       # Pass in byte array to module to directly set parameters\n       tvm.runtime.load_param_dict(param_bytes)\n    \"\"\"\n    transformed = {k: ndarray.array(v) for (k, v) in params.items()}\n    return _ffi_api.SaveParams(transformed)\n\n\ndef load_param_dict(param_bytes):\n    \"\"\"Load parameter dictionary to binary bytes.\n\n    Parameters\n    ----------\n    param_bytes: bytearray\n        Serialized parameters.\n\n    Returns\n    -------\n    params : dict of str to NDArray\n        The parameter dictionary.\n    \"\"\"\n    if isinstance(param_bytes, (bytes, str)):\n        param_bytes = bytearray(param_bytes)\n    return _ffi_api.LoadParams(param_bytes)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/profiler_vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name, redefined-builtin\n\"\"\"\nThe Relay Virtual Machine profiler.\n\nProvides extra APIs for profiling vm execution.\n\"\"\"\nimport warnings\nfrom tvm.runtime import _ffi_api\nfrom tvm.rpc import base as rpc_base\nfrom . import vm\nfrom .profiling import Report\n\n\ndef enabled():\n    \"\"\"Whether vm profiler is enabled.\"\"\"\n    return hasattr(_ffi_api, \"_VirtualMachineDebug\")\n\n\nclass VirtualMachineProfiler(vm.VirtualMachine):\n    \"\"\"Relay profile VM runtime.\"\"\"\n\n    def __init__(self, exe, device, memory_cfg=None):\n        super(VirtualMachineProfiler, self).__init__(exe, device, memory_cfg)\n\n        # Make sure the constructor of the VM module is on the proper device\n        # Remote devices have device_type of their actual device_type + RPC_SESS_MASK\n        if device.device_type >= rpc_base.RPC_SESS_MASK:\n            self.module = device._rpc_sess.get_function(\"runtime._VirtualMachineDebug\")(exe)\n        else:\n            self.module = _ffi_api._VirtualMachineDebug(exe.module)\n\n        self._init = self.module[\"init\"]\n        self._invoke = self.module[\"invoke\"]\n        self._profile = self.module[\"profile\"]\n        self._profile_rpc = self.module[\"profile_rpc\"]\n        self._set_input = self.module[\"set_input\"]\n        self._setup_device(device, memory_cfg)\n\n    def get_stat(self, sort_by_time=True):  # pylint: disable=unused-argument\n        \"\"\"Get the statistics of executed ops.\n\n        REMOVED, use profile method instead.\n        \"\"\"\n        warnings.warn(\"get_stat has been removed, use profile instead\")\n        return \"\"\n\n    def profile(self, *args, func_name=\"main\", collectors=None, **kwargs):\n        \"\"\"Profile a function call.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n\n        collectors : Optional[Sequence[MetricCollector]]\n            Extra metrics to collect. If profiling over RPC, collectors must be `None`.\n\n        args : list[tvm.runtime.NDArray] or list[np.ndarray]\n            The arguments to the function.\n\n        kwargs: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n\n        Returns\n        -------\n        timing_results : str\n            Overall and per-op timing results formatted in a table.\n        \"\"\"\n        if args or kwargs:\n            self.set_input(func_name, *args, **kwargs)\n        if self.module.type_key == \"rpc\":\n            # We cannot serialize MetricCollectors over RPC\n            assert collectors is None, \"Profiling with collectors is not supported over RPC\"\n            return Report.from_json(self._profile_rpc(func_name))\n        return self._profile(func_name, collectors)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/profiling/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Registration of profiling objects in python.\"\"\"\n\nfrom typing import Dict, Sequence, Optional\nfrom ... import _ffi\nfrom . import _ffi_api\nfrom .. import Object, Device\n\n\n@_ffi.register_object(\"runtime.profiling.Report\")\nclass Report(Object):\n    \"\"\"A container for information gathered during a profiling run.\n\n    Attributes\n    ----------\n    calls : Array[Dict[str, Object]]\n        Per-call profiling metrics (function name, runtime, device, ...).\n\n    device_metrics : Dict[Device, Dict[str, Object]]\n        Per-device metrics collected over the entire run.\n    \"\"\"\n\n    def __init__(\n        self,\n        calls: Sequence[Dict[str, Object]],\n        device_metrics: Dict[str, Dict[str, Object]],\n        configuration: Dict[str, Object],\n    ):\n        \"\"\"Construct a profiling report from a list of metrics and per-device metrics.\n\n        Parameters\n        ----------\n        calls : Sequence[Dict[str, Object]]\n            Per function call metrics.\n\n        device_metrics : Dict[str, Dict[str, Object]]\n            Per device metrics.\n\n        configuration : Dict[str, Object]\n            Configuration of TVM for this profiling run. Includes number of\n            threads, executor.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.Report, calls, device_metrics, configuration)\n\n    def csv(self):\n        \"\"\"Convert this profiling report into CSV format.\n\n        This only includes calls and not overall metrics.\n\n        Returns\n        -------\n        csv : str\n            `calls` in CSV format.\n        \"\"\"\n        return _ffi_api.AsCSV(self)\n\n    def table(self, sort=True, aggregate=True, col_sums=True):\n        \"\"\"Generate a human-readable table\n\n        Parameters\n        ----------\n        sort : bool\n\n            If aggregate is true, whether to sort call frames by\n            descending duration.  If aggregate is False, whether to\n            sort frames by order of appearancei n the program.\n\n        aggregate : bool\n\n            Whether to join multiple calls to the same op into a\n            single line.\n\n        col_sums : bool\n\n            Whether to include the sum of each column.\n\n        Returns\n        -------\n        table : str\n\n            A human-readable table\n\n        \"\"\"\n        return _ffi_api.AsTable(self, sort, aggregate, col_sums)\n\n    def json(self):\n        \"\"\"Convert this profiling report into JSON format.\n\n        Example output:\n\n        .. code-block:\n\n            {\n              \"calls\": [\n                {\n                  \"Duration (us)\": {\n                    \"microseconds\": 12.3\n                  },\n                  \"Name\": \"fused_dense\",\n                  \"Count\": {\n                    \"count\": 1\n                  },\n                  \"Percent\": {\n                    \"percent\": 10.3\n                  }\n                }\n              ],\n              \"device_metrics\": {\n                \"cpu\": {\n                  \"Duration (us)\": {\n                    \"microseconds\": 334.2\n                  },\n                  \"Percent\": {\n                    \"percent\": 100\n                  }\n                }\n              }\n            }\n\n           {\"calls\":\n              [\n                {\"Duration (us)\": {\"microseconds\": 12.3}\n                 ,\"Name\": \"fused_dense\"\n                 ,\"Count\": {\"count\":1}\n                 ,\"Percent\": {\"percent\": 10.3}\n                 }\n              ],\n            \"device_metrics\":\n              {\"cpu\":\n                {\"Duration (us)\": {\"microseconds\": 334.2}\n                ,\"Percent\": {\"percent\": 100.0}\n                }\n              }\n           }\n\n        Returns\n        -------\n        json : str\n            Formatted JSON\n        \"\"\"\n        return _ffi_api.AsJSON(self)\n\n    @classmethod\n    def from_json(cls, s):\n        \"\"\"Deserialize a report from JSON.\n\n        Parameters\n        ----------\n        s : str\n            Report serialize via :py:meth:`json`.\n\n        Returns\n        -------\n        report : Report\n            The deserialized report.\n        \"\"\"\n        return _ffi_api.FromJSON(s)\n\n\n@_ffi.register_object(\"runtime.profiling.Count\")\nclass Count(Object):\n    \"\"\"A integer count of something\"\"\"\n\n    def __init__(self, count: int):\n        self.__init_handle_by_constructor__(_ffi_api.Count, count)\n\n\n@_ffi.register_object(\"runtime.profiling.Duration\")\nclass Duration(Object):\n    \"\"\"A duration of something\"\"\"\n\n    def __init__(self, duration: float):\n        self.__init_handle_by_constructor__(_ffi_api.Duration, duration)\n\n\n@_ffi.register_object(\"runtime.profiling.Percent\")\nclass Percent(Object):\n    \"\"\"A Percent of something\"\"\"\n\n    def __init__(self, percent: float):\n        self.__init_handle_by_constructor__(_ffi_api.Percent, percent)\n\n\n@_ffi.register_object(\"runtime.profiling.Ratio\")\nclass Ratio(Object):\n    \"\"\"A Ratio of two things\"\"\"\n\n    def __init__(self, ratio: float):\n        self.__init_handle_by_constructor__(_ffi_api.Ratio, ratio)\n\n\n@_ffi.register_object(\"runtime.profiling.MetricCollector\")\nclass MetricCollector(Object):\n    \"\"\"Interface for user defined profiling metric collection.\"\"\"\n\n\n@_ffi.register_object(\"runtime.profiling.DeviceWrapper\")\nclass DeviceWrapper(Object):\n    \"\"\"Wraps a tvm.runtime.Device\"\"\"\n\n    def __init__(self, dev: Device):\n        self.__init_handle_by_constructor__(_ffi_api.DeviceWrapper, dev)\n\n\ndef profile_function(mod, dev, collectors, func_name=None, warmup_iters=10):\n    \"\"\"Collect performance information of a function execution. Usually used with\n    a compiled PrimFunc.\n\n    This information can include performance counters like cache hits and FLOPs\n    that are useful in debugging performance issues of individual PrimFuncs.\n    Different metrics can be collected depending on which MetricCollector is\n    used.\n\n    Example\n    -------\n\n    .. code-block: python\n        f = tvm.build(my_func, target=\"llvm\", name=\"my_func\")\n        prof = tvm.runtime.profiling.profile_function(\n            f,\n            tvm.cpu(),\n            [tvm.runtime.profiling.PAPIMetricCollector({tvm.cpu(): [\"PAPI_FP_OPS\"]}),\n        )\n        counters = prof(*args)\n        print(counters)\n\n    Parameters\n    ----------\n    mod: Module\n        Module containing the function to profile.\n    dev: Device\n        Device to run the function on.\n\n    collectors: List[MetricCollector]\n        :py:class:`MetricCollector`s which will collect performance information.\n    func_name: Optional[str]\n        Name of the function in `mod` to profile. Defaults to the `entry_name` of `mod`.\n    warmup_iters: int\n        Number of iterations to run the function before collecting performance\n        information. Recommended to set this larger than 0 for consistent cache\n        effects. Defaults to 10.\n\n    Returns\n    -------\n    prof: PackedFunc[args, Dict[str, ObjectRef]]\n        PackedFunc which takes the same arguments as the `mod[func_name]` and\n        returns performance metrics as a `Dict[str, ObjectRef]` where values\n        can be `CountNode`, `DurationNode`, `PercentNode`.\n    \"\"\"\n    if func_name is None:\n        func_name = mod.entry_name\n    return _ffi_api.ProfileFunction(\n        mod, func_name, dev.device_type, dev.device_id, warmup_iters, collectors\n    )\n\n\n# We only enable this class when TVM is build with PAPI support\nif _ffi.get_global_func(\"runtime.profiling.PAPIMetricCollector\", allow_missing=True) is not None:\n\n    @_ffi.register_object(\"runtime.profiling.PAPIMetricCollector\")\n    class PAPIMetricCollector(MetricCollector):\n        \"\"\"Collects performance counter information using the Performance\n        Application Programming Interface (PAPI).\n        \"\"\"\n\n        def __init__(self, metric_names: Optional[Dict[Device, Sequence[str]]] = None):\n            \"\"\"\n            Parameters\n            ----------\n            metric_names : Optional[Dict[Device, Sequence[str]]]\n                List of per-device metrics to collect. You can find a list of valid\n                metrics by runing `papi_native_avail` from the command line.\n            \"\"\"\n            metric_names = {} if metric_names is None else metric_names\n            wrapped = dict()\n            for dev, names in metric_names.items():\n                wrapped[DeviceWrapper(dev)] = names\n            self.__init_handle_by_constructor__(_ffi_api.PAPIMetricCollector, wrapped)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/profiling/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for profiling\"\"\"\nfrom ... import _ffi\n\n_ffi._init_api(\"runtime.profiling\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/runtime/vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name, redefined-builtin\n\"\"\"\nThe Relay Virtual Machine runtime.\n\nImplements a Python interface to executing the compiled VM object.\n\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm.runtime import Module\nfrom tvm._ffi.runtime_ctypes import TVMByteArray\nfrom tvm._ffi import base as _base\nfrom .object import Object\nfrom . import _ffi_api, container\nfrom ..rpc.base import RPC_SESS_MASK\n\n\ndef _convert(arg, cargs):\n    def _gettype(arg):\n        if isinstance(arg, np.float16):\n            return \"float16\"\n        elif isinstance(arg, (_base.integer_types, bool)):\n            return \"int32\"\n        else:\n            return \"float32\"\n\n    if isinstance(arg, Object):\n        cargs.append(arg)\n    elif arg is None:\n        cargs.append(tvm.nd.array([], device=tvm.cpu(0)))\n    elif isinstance(arg, np.ndarray):\n        nd_arr = tvm.nd.array(arg, device=tvm.cpu(0))\n        cargs.append(nd_arr)\n    elif isinstance(arg, tvm.runtime.NDArray):\n        cargs.append(arg)\n    elif isinstance(arg, (tuple, list)):\n        field_args = []\n        for field in arg:\n            _convert(field, field_args)\n        cargs.append(container.tuple_object(field_args))\n    elif isinstance(arg, (_base.numeric_types, bool)):\n        dtype = _gettype(arg)\n        value = tvm.nd.array(np.array(arg, dtype=dtype), device=tvm.cpu(0))\n        cargs.append(value)\n    elif isinstance(arg, str):\n        cargs.append(arg)\n    else:\n        raise TypeError(\"Unsupported type: %s\" % (type(arg)))\n\n\ndef convert(args):\n    cargs = []\n    for arg in args:\n        _convert(arg, cargs)\n\n    return cargs\n\n\nclass Executable(object):\n    \"\"\"Relay VM executable\"\"\"\n\n    def __init__(self, mod):\n        self.mod = mod\n        self._function_params = {}\n        self._save = self.mod[\"save\"]\n        self._get_lib = self.mod[\"get_lib\"]\n        self._get_bytecode = self.mod[\"get_bytecode\"]\n        self._get_constants = self.mod[\"get_constants\"]\n        self._get_virtual_devices = self.mod[\"get_virtual_devices\"]\n        self._get_primitives = self.mod[\"get_primitives\"]\n        self._get_stats = self.mod[\"get_stats\"]\n        self._get_function_arity = self.mod[\"get_function_arity\"]\n        self._get_function_param_name = self.mod[\"get_function_param_name\"]\n        self._move_late_bound_consts = self.mod[\"move_late_bound_consts\"]\n        self._get_late_bound_consts = self.mod[\"get_late_bound_consts\"]\n        self._load_late_bound_consts = self.mod[\"load_late_bound_consts\"]\n        self._load_late_bound_consts_from_map = self.mod[\"load_late_bound_consts_from_map\"]\n\n    def save(self):\n        \"\"\"Save the Relay VM Executable.\n\n        Returns\n        -------\n        code : bytearray\n            The binary blob representing a serialized Relay VM executable. It\n            can then be saved to disk and later deserialized into a new\n            Executable.\n\n        lib : :py:class:`~tvm.runtime.Module`\n            The runtime module that contains the generated code. It is\n            basically a library that is composed of hardware dependent code.\n\n        Notes\n        -----\n        The returned code is organized with the following sections in order.\n         - Global section. This section contains the globals used by the\n         virtual machine.\n\n         - Constant section. This section is used to store the constant pool of\n         a virtual machine.\n\n         - Primitive name section. This section is introduced to accommodate\n         the list of primitive operator names that will be invoked by the\n         virtual machine.\n\n         - Code section. The VM functions, including bytecode, are sitting in\n         this section.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n            import numpy as np\n            import tvm\n            from tvm import te\n            from tvm import relay\n            # define a simple network.\n            x = relay.var('x', shape=(10, 10))\n            f = relay.Function([x], x + x)\n            mod = tvm.IRModule({\"main\": f})\n            # create a Relay VM.\n            dev = tvm.cpu()\n            target = \"llvm\"\n            executable = relay.vm.compile(mod, target)\n            code, lib = executable.save()\n            # save and load the code and lib file.\n            tmp = tvm.contrib.utils.tempdir()\n            path_lib = tmp.relpath(\"lib.so\")\n            lib.export_library(path_lib)\n            with open(tmp.relpath(\"code.ro\"), \"wb\") as fo:\n                fo.write(code)\n            loaded_lib = tvm.runtime.load_module(path_lib)\n            loaded_code = bytearray(open(tmp.relpath(\"code.ro\"), \"rb\").read())\n            # deserialize.\n            des_exec = tvm.runtime.vm.Executable.load_exec(loaded_code, loaded_lib)\n            # execute the deserialized executable.\n            x_data = np.random.rand(10, 10).astype('float32')\n            des_vm = tvm.runtime.vm.VirtualMachine(des_exec, dev)\n            res = des_vm.run(x_data)\n            print(res.numpy())\n        \"\"\"\n        return self._save(), self._get_lib()\n\n    @staticmethod\n    def load_exec(bytecode, lib):\n        \"\"\"Construct an executable from saved artifacts.\n\n        Parameters\n        ----------\n        bytecode : bytearray\n            The binary blob representing a the Relay VM bytecode.\n\n        lib : :py:class:`~tvm.runtime.Module`\n            The runtime module that contains the generated code.\n\n        Returns\n        -------\n        exec: Executable\n            An executable constructed using the provided artifacts.\n        \"\"\"\n        if isinstance(bytecode, (bytes, str)):\n            bytecode = bytearray(bytecode)\n        elif not isinstance(bytecode, (bytearray, TVMByteArray)):\n            raise TypeError(\n                \"bytecode is expected to be the type of bytearray \"\n                + \"or TVMByteArray, but received {}\".format(type(bytecode))\n            )\n\n        if lib is not None and not isinstance(lib, tvm.runtime.Module):\n            raise TypeError(\n                \"lib is expected to be the type of tvm.runtime.Module\"\n                + \", but received {}\".format(type(lib))\n            )\n\n        return Executable(_ffi_api.Load_Executable(bytecode, lib))\n\n    @property\n    def lib(self):\n        \"\"\"Get the library that contains hardware dependent code.\n\n        Returns\n        -------\n        ret : :py:class:`~tvm.runtime.Module`\n            The runtime module that contains hardware dependent code.\n        \"\"\"\n        return self._get_lib()\n\n    @property\n    def stats(self):\n        \"\"\"Get the statistics of the Relay VM executable.\n\n        Returns\n        -------\n        ret : String\n            The statistic information of the VM executable.\n        \"\"\"\n        return self._get_stats()\n\n    @property\n    def primitive_ops(self):\n        \"\"\"Get the name of the primitive ops contained in the executable.\n\n        Returns\n        -------\n        ret : List[String]\n            The list of primitive ops.\n        \"\"\"\n        ret = []\n        num_primitives = _ffi_api.GetNumOfPrimitives(self.module)\n        for i in range(num_primitives):\n            ret.append(_ffi_api.GetPrimitiveFields(self.module, i))\n        return ret\n\n    @property\n    def bytecode(self):\n        \"\"\"Get the bytecode of the Relay VM executable.\n\n        Returns\n        -------\n        ret : String\n            The bytecode of the executable.\n\n        Notes\n        -----\n        The bytecode is in the following format:\n          func_name reg_file_size num_instructions\n\n          param1 param2 ... paramM\n\n          instruction1\n\n          instruction2\n\n          ...\n\n          instructionN\n\n        Each instruction is printed in the following format:\n          hash opcode field1 ... fieldX # The text format.\n\n        The part starting from # is only used for visualization and debugging.\n        The real serialized code doesn't contain it, therefore the deserializer\n        doesn't need to deal with it as well.\n        \"\"\"\n        return self._get_bytecode()\n\n    @property\n    def constants(self):\n        \"\"\"Returns a human-readable description of all the constants in the executable.\n        Useful for debugging and diffing generated executables in unit tests.\"\"\"\n        return self._get_constants()\n\n    @property\n    def virtual_devices(self):\n        \"\"\"Returns a human-readable description of all the (virtual) devices in the executable.\"\"\"\n        return self._get_virtual_devices()\n\n    @property\n    def primitives(self):\n        \"\"\"Returns a human-readable description of all the primitives (ie PackedFuncs) in the\n        executable\"\"\"\n        return self._get_primitives()\n\n    @property\n    def globals(self):\n        \"\"\"Get the globals used by the Relay VM executable.\n\n        Returns\n        -------\n        ret : List[String]\n            The globals contained in the executable.\n        \"\"\"\n        ret = []\n        num_globals = _ffi_api.GetNumOfGlobals(self.module)\n        for i in range(num_globals):\n            ret.append(_ffi_api.GetGlobalFields(self.module, i))\n        return ret\n\n    @property\n    def module(self):\n        \"\"\"Return the runtime module contained in a virtual machine executable.\"\"\"\n        return self.mod\n\n    def get_function_params(self, func_name):\n        \"\"\"Get VM Function parameters\"\"\"\n        if func_name in self._function_params:\n            return self._function_params[func_name]\n        arity = self._get_function_arity(func_name)\n        assert arity >= 0\n        params = []\n        for i in range(arity):\n            p = self._get_function_param_name(func_name, i)\n            assert p\n            params.append(p)\n        self._function_params[func_name] = params\n        return params\n\n    def move_late_bound_consts(self, path, byte_limit):\n        \"\"\"Move all constants of byte size greater or equal to byte_limit to file at path\"\"\"\n        return self._move_late_bound_consts(path, byte_limit)\n\n    def get_late_bound_consts(self, byte_limit):\n        \"\"\"Return all constants of byte size greater or equal to byte_limit\"\"\"\n        return self._get_late_bound_consts(byte_limit)\n\n    def load_late_bound_consts(self, path):\n        \"\"\"Re-load constants previously saved to file at path\"\"\"\n        return self._load_late_bound_consts(path)\n\n    def load_late_bound_consts_from_map(self, map):\n        \"\"\"Re-load constants supplied in map\"\"\"\n        return self._load_late_bound_consts_from_map(map)\n\n\nclass VirtualMachine(object):\n    \"\"\"Relay VM runtime.\n\n    Parameters\n    ----------\n    exe : Executable\n        The VM executable.\n\n    device : tvm.runtime.Device or List[tvm.runtime.Device]\n        The device(s) on which the model will run.\n        Currently at most one device per device type is supported.\n\n    memory_cfg : str or Dict[tvm.runtime.Device, str], optional\n        Config the type of memory allocator. The allocator type can be [\"naive\",\n        \"pooled\"]. If memory_cfg is None, all devices will use pooled allocator\n        by default. If memory_cfg is string, all devices will use the specified\n        allocator type. If memory_cfg is a dict, each device uses the allocator\n        type specified in the dict, or pooled allocator if not specified in the\n        dict.\n    \"\"\"\n\n    NAIVE_ALLOCATOR = 1\n    POOLED_ALLOCATOR = 2\n\n    def __init__(self, exe, device, memory_cfg=None):\n        \"\"\"\n        Construct a VirtualMachine wrapper class which provides a simple\n        interface over the raw C++ Module based API.\n\n        Parameters\n        ----------\n        exe: Union[Executable, Module]\n            The executable either with the wrapper Python type or the raw runtime.Module.\n\n            In most cases this will be the Python wrapper class tvm.runtime.vm.Executable but\n            if you instead get the underlying runtime.Module subclass (i.e `exe.mod`) you\n            can directly pass it to this method.\n\n            This case can occur when doing things such as RPC where TVM's module APIs\n            return the raw modules, not the wrapped modules. This constructor will\n            handle this internally.\n\n        device: Union[Device, List[Device]]\n            The device, or devices on which to execute the VM code.\n\n        memory_cfg: Optional[str]\n            The allocator behavior to use for the VM.\n\n        Returns\n        -------\n        vm: VirtualMachine\n            A VM wrapper object.\n        \"\"\"\n        if not isinstance(exe, Executable) and not isinstance(exe, Module):\n            raise TypeError(\n                \"exe is expected to be the type of Executable, \"\n                + \"but received {}\".format(type(exe))\n            )\n\n        if not isinstance(exe, Executable):\n            exe = Executable(exe)\n\n        self.module = exe.mod[\"vm_load_executable\"]()\n        self._exec = exe\n        self._init = self.module[\"init\"]\n        self._invoke = self.module[\"invoke\"]\n        self._invoke_stateful = self.module[\"invoke_stateful\"]\n        self._get_output = self.module[\"get_output\"]\n        self._get_num_outputs = self.module[\"get_num_outputs\"]\n        self._get_input_index = self.module[\"get_input_index\"]\n        self._set_input = self.module[\"set_input\"]\n        self._set_one_input = self.module[\"set_one_input\"]\n        self._set_outputs = self.module[\"set_outputs\"]\n        self._setup_device(device, memory_cfg)\n\n    def _setup_device(self, dev, memory_cfg):\n        \"\"\"Init devices and allocators.\"\"\"\n        devs = dev\n        if not isinstance(dev, (list, tuple)):\n            if not isinstance(dev, tvm.runtime.Device):\n                raise TypeError(\"dev is expected to be Device or List[Device]\")\n            devs = [dev]\n\n        # CPU is required for executing shape functions\n        if not any(c.device_type % RPC_SESS_MASK == tvm.cpu().device_type for c in devs):\n            devs.append(tvm.cpu())\n\n        default_alloc_type = VirtualMachine.POOLED_ALLOCATOR\n        if memory_cfg is None:\n            memory_cfg = {}\n        elif isinstance(memory_cfg, str):\n            assert memory_cfg in [\"naive\", \"pooled\"]\n            if memory_cfg == \"naive\":\n                default_alloc_type = VirtualMachine.NAIVE_ALLOCATOR\n            memory_cfg = {}\n        elif not isinstance(memory_cfg, dict):\n            raise TypeError(\n                \"memory_cfg is expected be string or dictionary, \"\n                + \"but received {}\".format(type(memory_cfg))\n            )\n        init_args = []\n        for device in devs:\n            init_args.append(device.device_type % RPC_SESS_MASK)\n            init_args.append(device.device_id)\n            alloc_type = memory_cfg[device] if device in memory_cfg else default_alloc_type\n            init_args.append(alloc_type)\n        self._init(*init_args)\n\n    def set_input(self, func_name, *args, **kwargs):\n        \"\"\"Set the input to a function.\n        If device type and device id for input tensor are the same as\n        for target one the zero copy is used. It means that internal\n        tensor is reference to memory allocated by input one.\n        Otherwise new internal NDarray is created and data is copied\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n\n        args : list[tvm.runtime.NDArray] or list[np.ndarray]\n            The arguments to the function.\n\n        kwargs: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n        \"\"\"\n        if kwargs:\n            # kwargs is a super set of the required function parameters. We\n            # only find the ones that are needed.\n            func_params = self._exec.get_function_params(func_name)\n            new_args = [None] * len(func_params)\n            cnt = 0\n            for k in kwargs:\n                if k in func_params:\n                    idx = func_params.index(k)\n                    new_args[idx] = kwargs[k]\n                    cnt += 1\n            assert len(args) + cnt == len(func_params)\n            idx = 0\n            for i, arg in enumerate(new_args):\n                if arg is None:\n                    new_args[i] = args[idx]\n                    idx += 1\n            args = new_args\n        cargs = convert(args)\n        self._set_input(func_name, *cargs)\n\n    def set_one_input(self, func_name, *args, **kwargs):\n        \"\"\"Set the one input tensor with tag to a function.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n        args : [str or int, tvm.runtime.NDArray]\n            name or index of tensor and input tensor, optional\n        kwargs: dict of str or int to tvm.runtime.NDArray, optional\n            taged arguments to the function.\n        Only args or kwargs should exist\n        \"\"\"\n        if kwargs:\n            assert len(kwargs) == 1\n            tag = next(iter(kwargs))\n            if isinstance(tag, str):\n                func_params = self._exec.get_function_params(func_name)\n                assert tag in func_params\n            self._set_one_input(func_name, tag, kwargs[tag])\n        else:\n            assert len(args) == 2\n            self._set_one_input(func_name, args[0], args[1])\n\n    def invoke(self, func_name, *args, **kwargs):\n        \"\"\"Invoke a function.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n\n        args : list[tvm.runtime.NDArray] or list[np.ndarray]\n            The arguments to the function.\n\n        kwargs: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n\n        Returns\n        -------\n        result : Object\n            The output.\n        \"\"\"\n        if args or kwargs:\n            self.set_input(func_name, *args, **kwargs)\n        return self._invoke(func_name)\n\n    def run(self, *args, **kwargs):\n        \"\"\"Run the main function.\n\n        Parameters\n        ----------\n        args : list[tvm.runtime.NDArray] or list[np.ndarray]\n            The arguments to the function.\n\n        kwargs: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n\n        Returns\n        -------\n        result : Object\n            The output.\n        \"\"\"\n        return self.invoke(\"main\", *args, **kwargs)\n\n    def invoke_stateful(self, func_name, *args, **kwargs):\n        \"\"\"Invoke a function and ignore the returned result.\n\n        Use this function when running over rpc because it is currently\n        impossible to return a ADT object over rpc. To get the outputs, use\n        :py:func`get_outputs`.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n\n        args : list[tvm.runtime.NDArray] or list[np.ndarray]\n            The arguments to the function.\n\n        kwargs: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n        \"\"\"\n        if args or kwargs:\n            self.set_input(func_name, *args, **kwargs)\n        self._invoke_stateful(func_name)\n\n    def invoke_with_outputs(self, func_name, input_args, output_args):\n        # TODO(vvchernov): consider scenario then output tensors set once\n        \"\"\"Invoke a function with pre-allocated output tensors.\n        The output tensors should be set every invocation.\n        input_args can be None if set_input method was used before.\n\n        This invoke method allows to avoid excess copying if memory for output tensors\n        was allocated before inference.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function.\n\n        input_args: dict of str to tvm.runtime.NDArray or np.ndarray\n            Named arguments to the function.\n\n        output_args : list[tvm.runtime.NDArray] or list[DLTensor]\n            The output tensors of the function.\n        \"\"\"\n        if input_args:\n            func_params = self._exec.get_function_params(func_name)\n            new_args = [None] * len(func_params)\n            cnt = 0\n            for k in input_args:\n                if k in func_params:\n                    idx = func_params.index(k)\n                    new_args[idx] = input_args[k]\n                    cnt += 1\n            assert cnt == len(func_params)\n        cargs = convert(new_args)\n        self._set_input(func_name, *cargs)\n        self._set_outputs(func_name, *output_args)\n        self._invoke(func_name)\n\n    def get_outputs(self):\n        \"\"\"Get the outputs from a call to :py:func`invoke_stateful`.\n\n        Returns\n        -------\n        outputs : List[NDArray]\n        \"\"\"\n        return [self._get_output(i) for i in range(self._get_num_outputs())]\n\n    def get_input_index(self, input_name, func_name=\"main\"):\n        \"\"\"Get inputs index via input name.\n        Parameters\n        ----------\n        name : str\n          The input key name\n        func_name : str\n          The function name\n\n        Returns\n        -------\n        index: int\n          The input index. -1 will be returned if the given input name is not found.\n        \"\"\"\n        return self._get_input_index(input_name, func_name)\n\n    def benchmark(\n        self,\n        device,\n        *args,\n        func_name=\"main\",\n        repeat=5,\n        number=5,\n        min_repeat_ms=None,\n        limit_zero_time_iterations=100,\n        end_to_end=False,\n        cooldown_interval_ms=0,\n        repeats_to_cooldown=1,\n        **kwargs,\n    ):\n        \"\"\"Calculate runtime of a function by repeatedly calling it.\n\n        Use this function to get an accurate measurement of the runtime of a function. The function\n        is run multiple times in order to account for variability in measurements, processor speed\n        or other external factors.  Mean, median, standard deviation, min and max runtime are all\n        reported. On GPUs, CUDA and ROCm specifically, special on-device timers are used so that\n        synchonization and data transfer operations are not counted towards the runtime. This allows\n        for fair comparison of runtimes across different functions and models. The `end_to_end` flag\n        switches this behavior to include data transfer operations in the runtime.\n\n        The benchmarking loop looks approximately like so:\n\n        .. code-block:: python\n\n            for r in range(repeat):\n                time_start = now()\n                for n in range(number):\n                    func_name()\n                time_end = now()\n                total_times.append((time_end - time_start)/number)\n\n\n        Parameters\n        ----------\n        func_name : str\n            The function to benchmark\n\n        repeat : int\n            Number of times to run the outer loop of the timing code (see above). The output will\n            contain `repeat` number of datapoints.\n\n        number : int\n            Number of times to run the inner loop of the timing code. This inner loop is run in\n            between the timer starting and stopping. In order to amortize any timing overhead,\n            `number` should be increased when the runtime of the function is small (less than a 1/10\n            of a millisecond).\n\n        min_repeat_ms : Optional[int]\n            If set, the inner loop will be run until it takes longer than `min_repeat_ms`\n            milliseconds. This can be used to ensure that the function is run enough to get an\n            accurate measurement.\n\n        limit_zero_time_iterations : Optional[int]\n            The maximum number of repeats when measured time is equal to 0.\n            It helps to avoid hanging during measurements.\n\n        end_to_end : bool\n            If set, include time to transfer input tensors to the device and time to transfer\n            returned tensors in the total runtime. This will give accurate timings for end to end\n            workloads.\n\n        cooldown_interval_ms: Optional[int]\n            The cooldown interval in milliseconds between the number of repeats defined by\n            `repeats_to_cooldown`.\n\n        repeats_to_cooldown: Optional[int]\n            The number of repeats before the cooldown is activated.\n\n        args : Sequence[Object]\n            Arguments to the function. These are cached before running timing code, so that data\n            transfer costs are not counted in the runtime.\n\n        kwargs : Dict[str, Object]\n            Named arguments to the function. These are cached like `args`.\n\n        Returns\n        -------\n        timing_results : BenchmarkResult\n            Runtimes of the function. Use `.mean` to access the mean runtime, use `.results` to\n            access the individual runtimes (in seconds).\n        \"\"\"\n        min_repeat_ms = 0 if min_repeat_ms is None else min_repeat_ms\n        if end_to_end:\n            # We need to unpack keyword arguments into positional arguments\n            packed_args = list(args)\n            for k, v in kwargs.items():\n                i = self.get_input_index(k, func_name)\n                if i < 0:\n                    raise TypeError(f\"{func_name}() got an unexpected keyword argument '{k}'\")\n                while i >= len(packed_args):\n                    packed_args.append(None)\n                packed_args[i] = v\n            return self.module.time_evaluator(\n                \"invoke_return_to_device\",\n                device,\n                repeat=repeat,\n                number=number,\n                min_repeat_ms=min_repeat_ms,\n                limit_zero_time_iterations=limit_zero_time_iterations,\n            )(func_name, device.device_type % RPC_SESS_MASK, device.device_id, *packed_args)\n        if args or kwargs:\n            self.set_input(func_name, *args, **kwargs)\n        return self.module.time_evaluator(\n            \"invoke\",\n            device,\n            repeat=repeat,\n            number=number,\n            min_repeat_ms=min_repeat_ms,\n            limit_zero_time_iterations=limit_zero_time_iterations,\n            cooldown_interval_ms=cooldown_interval_ms,\n            repeats_to_cooldown=repeats_to_cooldown,\n        )(func_name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script APIs of TVM Python Package\"\"\"\nfrom .parser import ir, ir_module, parse as from_source, tir\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/highlight.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Highlight printed TVM script.\n\"\"\"\n\nimport sys\nimport warnings\nfrom typing import Optional, Union\n\nfrom tvm.ir import IRModule\nfrom tvm.tir import PrimFunc\n\n\ndef cprint(printable: Union[IRModule, PrimFunc, str], style: Optional[str] = None) -> None:\n    \"\"\"\n    Print highlighted TVM script string with Pygments\n    Parameters\n    ----------\n    printable : Union[IRModule, PrimFunc, str]\n        The TVM script to be printed\n    style : str, optional\n        Printing style, auto-detected if None.\n    Notes\n    -----\n    The style parameter follows the Pygments style names or Style objects. Three\n    built-in styles are extended: \"light\", \"dark\" and \"ansi\". By default, \"light\"\n    will be used for notebook environment and terminal style will be \"ansi\" for\n    better style consistency. As an fallback when the optional Pygment library is\n    not installed, plain text will be printed with a one-time warning to suggest\n    installing the Pygment library. Other Pygment styles can be found in\n    https://pygments.org/styles/\n    \"\"\"\n    if isinstance(printable, (IRModule, PrimFunc)):\n        printable = printable.script()\n    try:\n        # pylint: disable=import-outside-toplevel\n        import pygments\n        from packaging import version\n        from pygments import highlight\n        from pygments.formatters import HtmlFormatter, Terminal256Formatter\n        from pygments.lexers.python import Python3Lexer\n        from pygments.style import Style\n        from pygments.token import Comment, Keyword, Name, Number, Operator, String\n\n        if version.parse(pygments.__version__) < version.parse(\"2.4.0\"):\n            raise ImportError(\"Required Pygments version >= 2.4.0 but got \" + pygments.__version__)\n    except ImportError as err:\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"once\", UserWarning)\n            install_cmd = sys.executable + ' -m pip install \"Pygments>=2.4.0\" --upgrade --user'\n            warnings.warn(\n                str(err)\n                + \"\\n\"\n                + \"To print highlighted TVM script, please install Pygments:\\n\"\n                + install_cmd,\n                category=UserWarning,\n            )\n        print(printable)\n    else:\n\n        class JupyterLight(Style):\n            \"\"\"A Jupyter-Notebook-like Pygments style configuration (aka. \"light\")\"\"\"\n\n            background_color = \"\"\n            styles = {\n                Keyword: \"bold #008000\",\n                Keyword.Type: \"nobold #008000\",\n                Name.Function: \"#0000FF\",\n                Name.Class: \"bold #0000FF\",\n                Name.Decorator: \"#AA22FF\",\n                String: \"#BA2121\",\n                Number: \"#008000\",\n                Operator: \"bold #AA22FF\",\n                Operator.Word: \"bold #008000\",\n                Comment: \"italic #007979\",\n            }\n\n        class VSCDark(Style):\n            \"\"\"A VSCode-Dark-like Pygments style configuration (aka. \"dark\")\"\"\"\n\n            background_color = \"\"\n            styles = {\n                Keyword: \"bold #c586c0\",\n                Keyword.Type: \"#82aaff\",\n                Keyword.Namespace: \"#4ec9b0\",\n                Name.Class: \"bold #569cd6\",\n                Name.Function: \"bold #dcdcaa\",\n                Name.Decorator: \"italic #fe4ef3\",\n                String: \"#ce9178\",\n                Number: \"#b5cea8\",\n                Operator: \"#bbbbbb\",\n                Operator.Word: \"#569cd6\",\n                Comment: \"italic #6a9956\",\n            }\n\n        class AnsiTerminalDefault(Style):\n            \"\"\"The default style for terminal display with ANSI colors (aka. \"ansi\")\"\"\"\n\n            background_color = \"\"\n            styles = {\n                Keyword: \"bold ansigreen\",\n                Keyword.Type: \"nobold ansigreen\",\n                Name.Class: \"bold ansiblue\",\n                Name.Function: \"bold ansiblue\",\n                Name.Decorator: \"italic ansibrightmagenta\",\n                String: \"ansiyellow\",\n                Number: \"ansibrightgreen\",\n                Operator: \"bold ansimagenta\",\n                Operator.Word: \"bold ansigreen\",\n                Comment: \"italic ansibrightblack\",\n            }\n\n        is_in_notebook = \"ipykernel\" in sys.modules  # in notebook env (support html display).\n\n        if style is None:\n            # choose style automatically according to the environment:\n            style = JupyterLight if is_in_notebook else AnsiTerminalDefault\n        elif style == \"light\":\n            style = JupyterLight\n        elif style == \"dark\":\n            style = VSCDark\n        elif style == \"ansi\":\n            style = AnsiTerminalDefault\n\n        if is_in_notebook:  # print with HTML display\n            from IPython.display import (  # pylint: disable=import-outside-toplevel\n                HTML,\n                display,\n            )\n\n            formatter = HtmlFormatter(style=JupyterLight)\n            formatter.noclasses = True  # inline styles\n            html = highlight(printable, Python3Lexer(), formatter)\n            display(HTML(html))\n        else:\n            print(highlight(printable, Python3Lexer(), Terminal256Formatter(style=style)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"tvm.script.ir_builder is a generic IR builder for TVM.\"\"\"\nfrom .base import IRBuilder\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.script.ir_builder\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"script.ir_builder\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"A generic IRBuilder across the TVM stack\"\"\"\nfrom typing import Any, Callable, List\n\nfrom tvm._ffi import register_object as _register_object\nfrom tvm.runtime import Object as _Object\n\nfrom . import _ffi_api\n\n\n@_register_object(\"script.ir_builder.IRBuilderFrame\")\nclass IRBuilderFrame(_Object):\n    \"\"\"A stack frame of the IRBuilder used to keep track of the current scope.\n    Furthermore, the information stored in each stack frame can be useful for context-dependent\n    IR construction.\n\n    Examples\n    --------\n\n    The `T.match_buffer` below instead an element in the buffer map of `PrimFuncFrame`:\n\n    .. code-block:: python\n\n    from tvm.script.ir_builder import tir as T\n    from tvm.script.ir_builder import IRBuilder\n\n    with IRBuilder() as builder:\n        with T.prim_func(...):  # pushes a PrimFuncFrame (subclass of IRBuilderFrame)\n                                # to `builder`'s stack of frames\n            buffer = T.match_buffer(...)\n\n\n    The `T.match_buffer` below instead generates `MatchBufferRegion` in a TIR block:\n\n    .. code-block:: python\n\n    from tvm.script.ir_builder import tir as T\n    from tvm.script.ir_builder import IRBuilder\n\n    with IRBuilder() as builder:\n        with T.prim_func(...):  # pushes a PrimFuncFrame (subclass of IRBuilderFrame)\n                                # to `builder`'s stack of frames\n            with T.block(...):  # pushes a BlockFrame (subclass of IRBuilderFrame)\n                                # to `builder`'s stack of frames\n                buffer = T.match_buffer(...)\n    \"\"\"\n\n    def __enter__(self) -> \"IRBuilderFrame\":\n        _ffi_api.IRBuilderFrameEnter(self)  # type: ignore[attr-defined] # pylint: disable=no-member\n        return self\n\n    def __exit__(self, ptype, value, trace) -> None:  # pylint: disable=unused-argument\n        _ffi_api.IRBuilderFrameExit(self)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        \"\"\"Add a callback method invoked when exiting the with-scope.\n\n        Parameters\n        ----------\n        callback : Callable[[], None]\n            The callback method to be invoked.\n        \"\"\"\n        _ffi_api.IRBuilderFrameAddCallback(  # type: ignore[attr-defined] # pylint: disable=no-member\n            self, callback\n        )\n\n\n@_register_object(\"script.ir_builder.IRBuilder\")\nclass IRBuilder(_Object):\n    \"\"\"A dialect-agnostic IRBuilder that constructs any IR of TVM.\n\n    Examples\n    --------\n    An idiomatic use of this class is to put this inside the with-scope,\n    call dialect-specific methods accordingly. Upon exiting the scope.\n\n    .. code-block:: python\n    from tvm.script.ir_builder import tir as T\n    from tvm.script.ir_builder import IRBuilder\n\n    with IRBuilder() as builder:\n        with T.prim_func(...):  # pushes a PrimFuncFrame (subclass of IRBuilderFrame)\n                                # to `builder`'s stack of frames\n            buffer = T.match_buffer(...)\n\n    return builder.get()        # returns the constructed IR, i.e. tir.PrimFunc\n    \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Construct an IRBuilder.\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.IRBuilder  # type: ignore[attr-defined] # pylint: disable=no-member\n        )\n\n    def __enter__(self) -> \"IRBuilder\":\n        \"\"\"Enter the with-scope for IRBuilder, which allows the IRBuilder to be discoverable\n        using `IRBuilder.current()`.\n\n        Examples\n        --------\n        .. code-block:: python\n        from tvm.script.ir_builder import IRBuilder\n\n        with IRBuilder() as builder:\n            assert IRBuilder.current() == builder\n        \"\"\"\n        _ffi_api.IRBuilderEnter(self)  # type: ignore[attr-defined] # pylint: disable=no-member\n        return self\n\n    def __exit__(self, ptype, value, trace) -> None:  # pylint: disable=unused-argument\n        _ffi_api.IRBuilderExit(self)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n    @staticmethod\n    def current() -> \"IRBuilder\":\n        \"\"\"Get the current IRBuilder put in the with-scope.\n\n        Returns\n        -------\n        builder : IRBuilder\n            The current IRBuilder.\n        \"\"\"\n        return _ffi_api.IRBuilderCurrent()  # type: ignore[attr-defined] # pylint: disable=no-member\n\n    def get(self) -> _Object:\n        \"\"\"Get the constructed IR.\"\"\"\n        return _ffi_api.IRBuilderGet(self)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n    @staticmethod\n    def name(s: str, v: Any) -> Any:\n        \"\"\"Set the name of an object.\n\n        Parameters\n        ----------\n        s : str\n            The name of the object.\n        v : Any\n            The object to name.\n\n        Returns\n        -------\n        v : Any\n            The same object with the name set.\n        \"\"\"\n        return _ffi_api.IRBuilderName(s, v)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n    @staticmethod\n    def name_many(  # pylint: disable=invalid-name\n        s: List[str],\n        vs: List[Any],\n    ) -> List[Any]:\n        \"\"\"Set the name of a list of objects.\n\n        Parameters\n        ----------\n        s : List[str]\n            The names of the objects.\n        vs : List[Any]\n            The objects to name.\n\n        Returns\n        -------\n        vs : List[Any]\n            The same objects with the names set.\n        \"\"\"\n        assert len(s) == len(vs)\n        return [IRBuilder.name(i, v) for i, v in zip(s, vs)]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/ir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package tvm.script.ir_builder.ir\"\"\"\nfrom .frame import IRModuleFrame\nfrom .ir import ir_module\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/ir/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"script.ir_builder.ir\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/ir/frame.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package tvm.script.ir_builder.ir.frame\"\"\"\n\nfrom tvm._ffi import register_object as _register_object\n\nfrom ..base import IRBuilderFrame\n\n\n@_register_object(\"script.ir_builder.IRModuleFrame\")\nclass IRModuleFrame(IRBuilderFrame):\n    ...\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/ir/ir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package tvm.script.ir_builder.ir.ir\"\"\"\n\nfrom . import _ffi_api\nfrom .frame import IRModuleFrame\n\n\ndef ir_module() -> IRModuleFrame:\n    return _ffi_api.IRModule()  # type: ignore[attr-defined] # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/tir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Package tvm.script.ir_builder.tir\"\"\"\nfrom .ir import *  # pylint: disable=wildcard-import,redefined-builtin\nfrom .ir import boolean as bool  # pylint: disable=redefined-builtin\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/tir/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"script.ir_builder.tir\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/tir/frame.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"IRBuilder for TIR\"\"\"\nfrom typing import List, Union\n\nfrom tvm._ffi import register_object as _register_object\nfrom tvm.tir import Buffer, Var\n\nfrom ..base import IRBuilderFrame\n\n\n@_register_object(\"script.ir_builder.tir.TIRFrame\")\nclass TIRFrame(IRBuilderFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.PrimFuncFrame\")\nclass PrimFuncFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.BlockFrame\")\nclass BlockFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.BlockInitFrame\")\nclass BlockInitFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.ForFrame\")\nclass ForFrame(TIRFrame):\n    def __enter__(self) -> Union[Var, List[Var]]:  # type: ignore[override]\n        super().__enter__()\n        return self.vars if len(self.vars) > 1 else self.vars[0]\n\n\n@_register_object(\"script.ir_builder.tir.AssertFrame\")\nclass AssertFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.LetFrame\")\nclass LetFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.RealizeFrame\")\nclass RealizeFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.AllocateFrame\")\nclass AllocateFrame(TIRFrame):\n    def __enter__(self) -> Buffer:\n        super().__enter__()\n        return self.buffer_var\n\n\n@_register_object(\"script.ir_builder.tir.AllocateConstFrame\")\nclass AllocateConstFrame(TIRFrame):\n    def __enter__(self) -> Buffer:\n        super().__enter__()\n        return self.buffer_var\n\n\n@_register_object(\"script.ir_builder.tir.AttrFrame\")\nclass AttrFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.WhileFrame\")\nclass WhileFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.IfFrame\")\nclass IfFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.ThenFrame\")\nclass ThenFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.ElseFrame\")\nclass ElseFrame(TIRFrame):\n    ...\n\n\n@_register_object(\"script.ir_builder.tir.DeclBufferFrame\")\nclass DeclBufferFrame(TIRFrame):\n    def __enter__(self) -> Buffer:\n        super().__enter__()\n        return self.buffer\n\n\n@_register_object(\"script.ir_builder.tir.LaunchThreadFrame\")\nclass LaunchThreadFrame(TIRFrame):\n    ...\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/ir_builder/tir/ir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"IRBuilder for TIR\"\"\"\n\nimport functools\nimport inspect\nfrom numbers import Integral\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\n# isort: off\nfrom typing_extensions import Literal\n\n# isort: on\n\nimport numpy as np  # type: ignore\nfrom tvm.ir import Range, Type\nfrom tvm.runtime import convert, ndarray\nfrom tvm.target import Target\n\n# pylint: disable=unused-import\nfrom tvm.target.codegen import llvm_lookup_intrinsic_id\nfrom tvm.tir import Buffer, BufferRegion, PrimExpr\nfrom tvm.tir import op as _tir_op\nfrom tvm.tir import type_annotation\n\n# import tir.expr for direct ir construction to pass structural_equal comparison\nfrom tvm.tir.expr import (\n    EQ,\n    GE,\n    GT,\n    LE,\n    LT,\n    NE,\n    Add,\n    And,\n    Broadcast,\n    BufferLoad,\n    Call,\n    CallEffectKind,\n    Cast,\n    CommReducer,\n    Div,\n    FloatImm,\n    FloorDiv,\n    FloorMod,\n    IntImm,\n    IterVar,\n    Let,\n    Load,\n    Max,\n    Min,\n    Mod,\n    Mul,\n    Not,\n    Or,\n    ProducerLoad,\n    Ramp,\n    Reduce,\n    Select,\n    Shuffle,\n    SizeVar,\n    StringImm,\n    Sub,\n    Var,\n)\nfrom tvm.tir.generic import cast\n\nfrom . import _ffi_api, frame\n\n# pylint: enable=unused-import\n\n\ndef buffer_decl(\n    shape: Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral],\n    dtype: str = \"float32\",\n    data: Var = None,\n    strides: List[PrimExpr] = None,\n    elem_offset: PrimExpr = None,\n    scope: str = \"global\",\n    align: int = 0,\n    offset_factor: int = 0,\n    buffer_type: str = \"\",\n    axis_separators: List[int] = None,\n) -> Buffer:\n    \"\"\"The buffer declaration function.\n\n    Parameters\n    ----------\n    shape : Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral]\n        The type of the buffer prior to flattening.\n\n    dtype : str\n        The data type in the content of the buffer.\n\n    data : Var\n        The pointer to the head of the data.\n\n    strides : List[PrimExpr]\n        The strides of each dimension.\n\n    elem_offset : PrimExpr\n        The offset in terms of number of dtype elements (including lanes).\n\n    scope : str\n        The optional storage scope of buffer data pointer.\n\n    align : int\n        The alignment requirement of data pointer in bytes.\n\n    offset_factor : int\n        The factor of elem_offset field.\n\n    buffer_type : str\n        The buffer type.\n\n    axis_separators : List[int]\n        The separators between input axes when generating flattened output axes.\n\n    Returns\n    -------\n    res : Buffer\n        The declared buffer.\n    \"\"\"\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    return _ffi_api.BufferDecl(  # type: ignore[attr-defined] # pylint: disable=no-member\n        shape,\n        dtype,\n        \"\",\n        data,\n        strides,\n        elem_offset,\n        scope,\n        align,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n    )\n\n\ndef prim_func() -> frame.PrimFuncFrame:\n    \"\"\"The primitive function statement.\n\n    Returns\n    -------\n    res : frame.PrimFuncFrame\n        The PrimFuncFrame.\n    \"\"\"\n    return _ffi_api.PrimFunc()  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef arg(name: str, obj: Union[Var, Buffer]) -> Union[Var, Buffer]:\n    \"\"\"The PrimFunc arguments adding function.\n\n    Parameters\n    ----------\n    name : str\n        The name of the argument.\n\n    var : Union[Var, Buffer]\n        The argument of Var or Buffer.\n\n    Returns\n    -------\n    res : Union[Var, Buffer]\n        The argument.\n    \"\"\"\n    return _ffi_api.Arg(name, obj)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef func_name(name: str) -> None:\n    \"\"\"The PrimFunc naming statement.\n\n    Parameters\n    ----------\n    name : str\n        The name of the PrimFunc.\n    \"\"\"\n    _ffi_api.FuncName(name)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef func_attr(attrs: Dict[str, Any]) -> None:\n    \"\"\"The PrimFunc annotation statement.\n\n    Parameters\n    ----------\n    attrs : Dict[str, Any]\n        The annotations of the PrimFunc.\n    \"\"\"\n    _ffi_api.FuncAttrs(attrs)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef func_ret(ret_type: Type) -> Type:\n    \"\"\"The PrimFunc return type statement.\n\n    Parameters\n    ----------\n    ret_type : Type\n        The return type of the PrimFunc.\n\n    Returns\n    -------\n    res : Type\n        The return type.\n    \"\"\"\n    return _ffi_api.FuncRet(ret_type)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef match_buffer(\n    param: Union[Var, BufferLoad, BufferRegion],\n    shape: Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral] = None,\n    dtype: str = \"float32\",\n    data: Var = None,\n    strides: List[PrimExpr] = None,\n    elem_offset: PrimExpr = None,\n    scope: str = \"global\",\n    align: int = -1,\n    offset_factor: int = 0,\n    buffer_type: str = \"default\",\n    axis_separators: List[int] = None,\n) -> Buffer:\n    \"\"\"The buffer match function.\n\n    Note\n    ----\n    This function will perform different behavior, depending on the type of param.\n    If the param is a var in function parameter, it will create a buffer from DLTensor.\n    Else if the param is a subregion of other buffers, then create a subregion match inside a block.\n\n    Example\n    -------\n    Match buffer from function parameter\n    .. code-block:: python\n        A = T.match_buffer(a, (128, 128), dtype=\"float32\")\n\n    Match buffer from Buffer subregion\n    .. code-block:: python\n        A = T.match_buffer(B[0:128, i * 128 : i * 128 + 128], (128, 128), dtype=\"float32\")\n\n    Parameters\n    ----------\n    param : Union[Var, BufferLoad, BufferRegion]\n        The parameter of the PrimFunc to match.\n\n    shape : Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral]\n        The type of the buffer prior to flattening.\n\n    dtype : str\n        The data type in the content of the buffer.\n\n    data : Var\n        The pointer to the head of the data.\n\n    strides : List[PrimExpr]\n        The strides of each dimension.\n\n    elem_offset : PrimExpr\n        The offset in terms of number of dtype elements (including lanes).\n\n    scope : str\n        The optional storage scope of buffer data pointer.\n\n    align : int\n        The alignment requirement of data pointer in bytes.\n\n    offset_factor : int\n        The factor of elem_offset field.\n\n    buffer_type : str\n        The buffer type.\n\n    axis_separators : List[int]\n        The separators between input axes when generating flattened output axes.\n\n    Returns\n    -------\n    res : Buffer\n        The matched buffer.\n    \"\"\"\n    if shape is None:\n        if isinstance(param, BufferRegion):\n            dtype = param.buffer.dtype\n            shape = [region.extent for region in param.region]\n        else:\n            raise ValueError(\"Shape must be specified when binding input param\")\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    if strides is None:\n        strides = []\n    return _ffi_api.MatchBuffer(  # type: ignore[attr-defined] # pylint: disable=no-member\n        param,\n        shape,\n        dtype,\n        data,\n        strides,\n        elem_offset,\n        scope,\n        align,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n    )\n\n\ndef preflattened_buffer(\n    postflattened: Buffer,\n    shape: Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral],\n    dtype: str = \"float32\",\n    data: Var = None,\n    strides: List[PrimExpr] = None,\n    elem_offset: PrimExpr = None,\n    scope: str = \"global\",\n    align: int = -1,\n    offset_factor: int = 0,\n    buffer_type: str = \"default\",\n    axis_separators: List[int] = None,\n) -> None:\n    \"\"\"The pre-flattened buffer statement.\n\n    Parameters\n    ----------\n    postflattened : Buffer\n        The original buffer to be flattened.\n\n    shape : Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral]\n        The type of the buffer prior to flattening.\n\n    dtype : str\n        The data type in the content of the buffer.\n\n    data : Var\n        The pointer to the head of the data.\n\n    strides : List[PrimExpr]\n        The strides of each dimension.\n\n    elem_offset : PrimExpr\n        The offset in terms of number of dtype elements (including lanes).\n\n    scope : str\n        The optional storage scope of buffer data pointer.\n\n    align : int\n        The alignment requirement of data pointer in bytes.\n\n    offset_factor : int\n        The factor of elem_offset field.\n\n    buffer_type : str\n        The buffer type.\n\n    axis_separators : List[int]\n        The separators between input axes when generating flattened output axes.\n    \"\"\"\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    if strides is None:\n        strides = []\n    _ffi_api.PreflattenedBuffer(  # type: ignore[attr-defined] # pylint: disable=no-member\n        postflattened,\n        shape,\n        dtype,\n        data,\n        strides,\n        elem_offset,\n        scope,\n        align,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n    )\n\n\ndef block(name: str = \"\", no_realize: bool = False) -> frame.BlockFrame:\n    \"\"\"The block declaration statement.\n\n    Parameters\n    ----------\n    name : str\n        The name of the block.\n\n    no_realize : bool\n        The flag whether to construct BlockRealize or Block.\n\n    Returns\n    -------\n    res : frame.BlockFrame\n        The BlockFrame.\n    \"\"\"\n    return _ffi_api.Block(name, no_realize)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef init() -> frame.BlockInitFrame:\n    \"\"\"The block initialization statement.\n\n    Returns\n    -------\n    res : frame.BlockInitFrame\n        The BlockInitFrame.\n    \"\"\"\n    return _ffi_api.Init()  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef where(predicate: Union[PrimExpr, int]) -> None:\n    \"\"\"The block predicate statement.\n\n    Parameters\n    ----------\n    predicate : Union[PrimExpr, Literal[0, 1]]\n        The predicate condition.\n    \"\"\"\n    if isinstance(predicate, bool):\n        predicate = IntImm(\"bool\", predicate)\n    if isinstance(predicate, int):\n        if predicate in [0, 1]:\n            predicate = IntImm(\"bool\", predicate)\n        else:\n            raise ValueError(f\"Invalid value for predicate: {predicate}\")\n    _ffi_api.Where(predicate)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef reads(*buffer_slices: List[Union[BufferRegion, BufferLoad]]) -> None:\n    \"\"\"The block buffer region reading statement.\n\n    Parameters\n    ----------\n    buffer_slices : List[Union[BufferRegion, BufferLoad]]\n        The array of buffer regions to read.\n    \"\"\"\n    if len(buffer_slices) == 1:\n        if isinstance(buffer_slices[0], tuple):\n            buffer_slices = list(buffer_slices[0])\n        elif isinstance(buffer_slices[0], list):\n            buffer_slices = buffer_slices[0]  # type: ignore[assignment]\n        else:\n            buffer_slices = [buffer_slices[0]]\n    else:\n        buffer_slices = list(buffer_slices)  # type: ignore[assignment]\n    _ffi_api.Reads(buffer_slices)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef writes(*buffer_slices: List[Union[BufferRegion, BufferLoad]]) -> None:\n    \"\"\"The block buffer region writing statement.\n\n    Parameters\n    ----------\n    buffer_slices : List[Union[BufferRegion, BufferLoad]]\n        The array of buffer regions to write.\n    \"\"\"\n    if len(buffer_slices) == 1:\n        if isinstance(buffer_slices[0], tuple):\n            buffer_slices = list(buffer_slices[0])\n        elif isinstance(buffer_slices[0], list):\n            buffer_slices = buffer_slices[0]  # type: ignore[assignment]\n        else:\n            buffer_slices = [buffer_slices[0]]\n    else:\n        buffer_slices = list(buffer_slices)  # type: ignore[assignment]\n    _ffi_api.Writes(buffer_slices)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef block_attr(attrs: Dict[str, Any]) -> None:\n    \"\"\"The block annotation statement.\n\n    Parameters\n    ----------\n    attrs : Dict[str, Any]\n        The annotation of the block.\n    \"\"\"\n    return _ffi_api.BlockAttrs(attrs)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef alloc_buffer(\n    shape: Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral],\n    dtype: str = \"float32\",\n    data: Var = None,\n    strides: List[PrimExpr] = None,\n    elem_offset: PrimExpr = None,\n    scope: str = \"global\",\n    align: int = -1,\n    offset_factor: int = 0,\n    buffer_type: str = \"default\",\n    axis_separators: List[int] = None,\n) -> Buffer:\n    \"\"\"The buffer alllocation function.\n\n    Parameters\n    ----------\n    shape : Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral]\n        The type of the buffer prior to flattening.\n\n    dtype : str\n        The data type in the content of the buffer.\n\n    data : Var\n        The pointer to the head of the data.\n\n    strides : List[PrimExpr]\n        The strides of each dimension.\n\n    elem_offset : PrimExpr\n        The offset in terms of number of dtype elements (including lanes).\n\n    scope : str\n        The optional storage scope of buffer data pointer.\n\n    align : int\n        The alignment requirement of data pointer in bytes.\n\n    offset_factor : int\n        The factor of elem_offset field.\n\n    buffer_type : str\n        The buffer type.\n\n    axis_separators : List[int]\n        The separators between input axes when generating flattened output axes.\n\n    Returns\n    -------\n    res : Buffer\n        The allocated buffer.\n    \"\"\"\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    if strides is None:\n        strides = []\n    return _ffi_api.AllocBuffer(  # type: ignore[attr-defined] # pylint: disable=no-member\n        shape,\n        dtype,\n        data,\n        strides,\n        elem_offset,\n        scope,\n        align,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n    )\n\n\ndef _as_range(dom: Union[Range, List[PrimExpr]]) -> Range:\n    \"\"\"The range constructor.\n\n    Parameters\n    ----------\n    dom : Union[Range, List[PrimExpr]]\n        The domain.\n\n    Returns\n    -------\n    res : Range\n        The Range.\n    \"\"\"\n    if isinstance(dom, Range):\n        return dom\n    if isinstance(dom, (list, tuple)):\n        return Range(dom[0], dom[1])\n    if hasattr(dom, \"dtype\"):\n        return Range(IntImm(dom.dtype, 0), dom)\n    return Range(0, dom)\n\n\nclass axis:  # pylint: disable=invalid-name\n    \"\"\"The axis class\"\"\"\n\n    @staticmethod\n    def spatial(\n        dom: Union[Range, List[PrimExpr], Tuple[PrimExpr]], binding: PrimExpr, dtype: str = \"int32\"\n    ) -> Var:\n        \"\"\"The spatial block axis defining function.\n\n        Parameters\n        ----------\n        dom : Union[Range, List[PrimExpr], Tuple[PrimExpr]]\n            The domain of the iteration variable.\n\n        binding : PrimExpr\n            The binding value of the iteration variable.\n\n        dtype : str\n            The data type of the iteration variable.\n\n        Returns\n        -------\n        res : Var\n            The iteration variable.\n        \"\"\"\n        return _ffi_api.AxisSpatial(  # type: ignore[attr-defined] # pylint: disable=no-member\n            _as_range(dom), binding, dtype\n        )\n\n    @staticmethod\n    def reduce(\n        dom: Union[Range, List[PrimExpr], Tuple[PrimExpr]], binding: PrimExpr, dtype: str = \"int32\"\n    ) -> Var:\n        \"\"\"The reduced block axis defining function.\n\n        Parameters\n        ----------\n        dom : Union[Range, List[PrimExpr], Tuple[PrimExpr]]\n            The domain of the iteration variable.\n\n        binding : PrimExpr\n            The binding value of the iteration variable.\n\n        dtype : str\n            The data type of the iteration variable.\n\n        Returns\n        -------\n        res : Var\n            The iteration variable.\n        \"\"\"\n        return _ffi_api.AxisReduce(  # type: ignore[attr-defined] # pylint: disable=no-member\n            _as_range(dom), binding, dtype\n        )\n\n    @staticmethod\n    def scan(\n        dom: Union[Range, List[PrimExpr], Tuple[PrimExpr]], binding: PrimExpr, dtype: str = \"int32\"\n    ) -> Var:\n        \"\"\"The scanning block axis defining function.\n\n        Parameters\n        ----------\n        dom : Union[Range, List[PrimExpr], Tuple[PrimExpr]]\n            The domain of the iteration variable.\n\n        binding : PrimExpr\n            The binding value of the iteration variable.\n\n        dtype : str\n            The data type of the iteration variable.\n\n        Returns\n        -------\n        res : Var\n            The iteration variable.\n        \"\"\"\n        return _ffi_api.AxisScan(  # type: ignore[attr-defined] # pylint: disable=no-member\n            _as_range(dom), binding, dtype\n        )\n\n    @staticmethod\n    def opaque(\n        dom: Union[Range, List[PrimExpr], Tuple[PrimExpr]], binding: PrimExpr, dtype: str = \"int32\"\n    ) -> Var:\n        \"\"\"The opaque block axis defining function.\n\n        Parameters\n        ----------\n        dom : Union[Range, List[PrimExpr], Tuple[PrimExpr]]\n            The domain of the iteration variable.\n\n        binding : PrimExpr\n            The binding value of the iteration variable.\n\n        dtype : str\n            The data type of the iteration variable.\n\n        Returns\n        -------\n        res : Var\n            The iteration variable.\n        \"\"\"\n        return _ffi_api.AxisOpaque(  # type: ignore[attr-defined] # pylint: disable=no-member\n            _as_range(dom), binding, dtype\n        )\n\n    @staticmethod\n    def remap(kinds: str, bindings: List[PrimExpr], dtype: str = \"int32\") -> Union[List[Var], Var]:\n        \"\"\"The block axis remapping function.\n\n        Parameters\n        ----------\n        kinds : str\n            The types of the iteration variables.\n\n        bindings : List[PrimExpr]\n            The binding values of the iteration variables.\n\n        dtype : str\n            The data types of the iteration variables.\n\n        Returns\n        -------\n        res : Var\n            The iteration variables.\n        \"\"\"\n        iter_vars = _ffi_api.AxisRemap(  # type: ignore[attr-defined] # pylint: disable=no-member\n            kinds, bindings, dtype\n        )\n        return iter_vars[0] if len(iter_vars) == 1 else iter_vars\n\n    S = spatial  # pylint: disable=invalid-name\n    R = reduce  # pylint: disable=invalid-name\n\n\ndef serial(\n    start: PrimExpr, stop: PrimExpr = None, *, annotations: Dict[str, Any] = None\n) -> frame.ForFrame:\n    \"\"\"The serial For statement.\n\n    Parameters\n    ----------\n    start : PrimExpr\n        The minimum value of iteration.\n\n    stop : PrimExpr\n        The maximum value of iteration.\n\n    annotations : Dict[str, Any]\n        The optional annotations of the For statement.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    if stop is None:\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    return _ffi_api.Serial(start, stop, annotations)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef parallel(\n    start: PrimExpr, stop: PrimExpr = None, *, annotations: Dict[str, Any] = None\n) -> frame.ForFrame:\n    \"\"\"The parallel For statement.\n\n    Parameters\n    ----------\n    start : PrimExpr\n        The minimum value of iteration.\n\n    stop : PrimExpr\n        The maximum value of iteration.\n\n    annotations : Dict[str, Any]\n        The optional annotations of the For statement.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    if stop is None:\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    return _ffi_api.Parallel(start, stop, annotations)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef vectorized(\n    start: PrimExpr, stop: PrimExpr = None, *, annotations: Dict[str, Any] = None\n) -> frame.ForFrame:\n    \"\"\"The vectorized For statement.\n\n    Parameters\n    ----------\n    start : PrimExpr\n        The minimum value of iteration.\n\n    stop : PrimExpr\n        The maximum value of iteration.\n\n    annotations : Dict[str, Any]\n        The optional annotations of the For statement.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    if stop is None:\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    return _ffi_api.Vectorized(start, stop, annotations)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef unroll(\n    start: PrimExpr, stop: PrimExpr = None, *, annotations: Dict[str, Any] = None\n) -> frame.ForFrame:\n    \"\"\"The unrolled For statement.\n\n    Parameters\n    ----------\n    start : PrimExpr\n        The minimum value of iteration.\n\n    stop : PrimExpr\n        The maximum value of iteration.\n\n    annotations : Dict[str, Any]\n        The optional annotations of the For statement.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    if stop is None:\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    return _ffi_api.Unroll(start, stop, annotations)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef thread_binding(\n    start: PrimExpr,\n    stop: PrimExpr = None,\n    thread: str = None,\n    *,\n    annotations: Dict[str, Any] = None,\n) -> frame.ForFrame:\n    \"\"\"The thread-binding For statement.\n\n    Parameters\n    ----------\n    start : PrimExpr\n        The minimum value of iteration.\n\n    stop : PrimExpr\n        The maximum value of iteration.\n\n    thread : str\n        The thread for loop variable to bind.\n\n    annotations : Dict[str, Any]\n        The optional annotations of the For statement.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    if thread is None:\n        if not isinstance(stop, str):\n            raise ValueError(\"Thread cannot be None for thread_binding\")\n        thread = stop\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    elif stop is None:\n        stop = start\n        if hasattr(start, \"dtype\"):\n            start = IntImm(start.dtype, 0)\n        else:\n            start = 0\n    return _ffi_api.ThreadBinding(  # type: ignore[attr-defined] # pylint: disable=no-member\n        start, stop, thread, annotations\n    )\n\n\ndef grid(*extents: PrimExpr) -> frame.ForFrame:\n    \"\"\"The grid For statement.\n\n    Parameters\n    ----------\n    extents : PrimExpr\n        The extents of the iteration.\n\n    Returns\n    -------\n    res : frame.ForFrame\n        The ForFrame.\n    \"\"\"\n    return _ffi_api.Grid(extents)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef Assert(condition: PrimExpr, message: str) -> frame.AssertFrame:  # pylint: disable=invalid-name\n    \"\"\"Create an assertion statement.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The PrimExpr to test.\n\n    message : str\n        The output error message when the assertion fails.\n\n    Returns\n    -------\n    res : frame.AssertFrame\n        The result AssertFrame.\n    \"\"\"\n    return _ffi_api.Assert(condition, message)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef let(\n    v: Var,\n    value: PrimExpr,\n    body: PrimExpr = None,\n) -> frame.LetFrame:\n    \"\"\"Create a new let binding.\n\n    Parameters\n    ----------\n    v : Var\n        The variable to bind.\n\n    value : PrimExpr\n        The value to be bound.\n\n    body : PrimExpr\n        The body expression, None will be used if it was not specified.\n\n    Returns\n    -------\n    res : frame.LetFrame\n        The result LetFrame.\n    \"\"\"\n    if body is None:\n        return _ffi_api.Let(v, value)  # type: ignore[attr-defined] # pylint: disable=no-member\n    return Let(v, value, body)\n\n\ndef realize(\n    buffer_slice: BufferRegion,\n    storage_scope: str,\n    condition: PrimExpr = True,\n) -> frame.RealizeFrame:\n    \"\"\"Create a realization.\n\n    Parameters\n    ----------\n    buffer_slice : BufferRegion\n        The region of buffer access.\n\n    storage_scope : str\n        The storage scope associated with this realization.\n\n    condition: PrimExpr\n        The condition expression, the default is True.\n\n    Returns\n    -------\n    res : frame.RealizeFrame\n        The result RealizeFrame.\n    \"\"\"\n    return _ffi_api.Realize(  # type: ignore[attr-defined] # pylint: disable=no-member\n        buffer_slice, storage_scope, condition\n    )\n\n\ndef allocate(\n    extents: List[PrimExpr],\n    dtype: str,\n    scope: str = \"global\",\n    condition: PrimExpr = None,\n    annotations=None,\n) -> frame.AllocateFrame:\n    \"\"\"Allocate node.\n\n    Parameters\n    ----------\n    extents : List[PrimExpr]\n        The extents of the allocate.\n\n    dtype : str\n        The data type of the buffer.\n\n    scope : str\n        The storage scope.\n\n    condition : PrimExpr\n        The condition.\n\n    annotations: Optional[Mapping[str, Object]]\n        Additional annotation hints.\n    \"\"\"\n    if isinstance(condition, bool):\n        condition = IntImm(\"bool\", condition)\n    return _ffi_api.Allocate(  # type: ignore[attr-defined] # pylint: disable=no-member\n        extents, dtype, scope, condition, annotations\n    )\n\n\ndef allocate_const(\n    data: List[PrimExpr],\n    dtype: str,\n    extents: List[PrimExpr],\n    annotations=None,\n) -> frame.AllocateConstFrame:\n    \"\"\"Allocate constant node.\n\n    Parameters\n    ----------\n    data : List[PrimExpr]\n        The data associated with the constant.\n\n    dtype : str\n        The data type of the buffer.\n\n    extents : List[PrimExpr]\n        The extents of the allocate.\n\n    annotations : Optional[Map]\n        Additional annotations about the allocation.\n    \"\"\"\n    np_data = np.asarray(data, dtype=dtype)\n    prod_extent = 1\n    for extent in extents:\n        prod_extent *= extent\n    prod_shape = 1\n    for shape in np_data.shape:\n        prod_shape *= shape\n    if prod_extent == prod_shape:\n        np_data = np_data.reshape(extents)\n\n    return _ffi_api.AllocateConst(  # type: ignore[attr-defined] # pylint: disable=no-member\n        ndarray.array(np_data), dtype, extents, annotations\n    )\n\n\ndef attr(node: Any, attr_key: str, value: Union[PrimExpr, str]) -> frame.AttrFrame:\n    \"\"\"Create an attribute node.\n\n    Parameters\n    ----------\n    node : Any\n        The node to annotate the attribute.\n\n    attr_key : str\n        Attribute type key.\n\n    value : Union[PrimExpr, str]\n        The value of the attribute.\n\n    Returns\n    -------\n    res : frame.AttrFrame\n        The result AttrFrame.\n    \"\"\"\n    node = convert(node)\n    value = convert(value)\n    return _ffi_api.Attr(node, attr_key, value)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef While(condition: PrimExpr) -> frame.WhileFrame:  # pylint: disable=invalid-name\n    \"\"\"Create a while node.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The termination condition of the loop.\n\n    Returns\n    -------\n    res : frame.WhileFrame\n        The result WhileFrame.\n    \"\"\"\n    if isinstance(condition, bool):\n        condition = IntImm(\"bool\", condition)\n    return _ffi_api.While(condition)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef If(condition: PrimExpr) -> frame.IfFrame:  # pylint: disable=invalid-name\n    \"\"\"Create an if node.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The condition of if statement, executes the true branch if the condition is true,\n        otherwise jump into the false branch.\n\n    Returns\n    -------\n    res : frame.IfFrame\n        The result IfFrame.\n    \"\"\"\n    if isinstance(condition, bool):\n        condition = IntImm(\"bool\", condition)\n    return _ffi_api.If(condition)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef Then() -> frame.ThenFrame:  # pylint: disable=invalid-name\n    \"\"\"Create a then.\n\n    Returns\n    -------\n    res : frame.ThenFrame\n        The result ThenFrame.\n    \"\"\"\n    return _ffi_api.Then()  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef Else() -> frame.ElseFrame:  # pylint: disable=invalid-name\n    \"\"\"Create an else.\n\n    Returns\n    -------\n    res : frame.ElseFrame\n        The result ElseFrame.\n    \"\"\"\n    return _ffi_api.Else()  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef decl_buffer(\n    shape,\n    dtype=\"float32\",\n    data=None,\n    strides=None,\n    elem_offset=None,\n    scope=\"global\",\n    align=0,\n    offset_factor=0,\n    buffer_type=\"\",\n    axis_separators=None,\n) -> frame.DeclBufferFrame:\n    \"\"\"Create a buffer declaration node.\n\n    Parameters\n    ----------\n    shape : Union[List[PrimExpr], Tuple[PrimExpr], PrimExpr, Integral]\n        The type of the buffer prior to flattening.\n\n    dtype : str\n        The data type in the content of the buffer.\n\n    data : Var\n        The pointer to the head of the data.\n\n    strides : List[PrimExpr]\n        The strides of each dimension.\n\n    elem_offset : PrimExpr\n        The offset in terms of number of dtype elements (including lanes).\n\n    scope : str\n        The optional storage scope of buffer data pointer.\n\n    align : int\n        The alignment requirement of data pointer in bytes.\n\n    offset_factor : int\n        The factor of elem_offset field.\n\n    buffer_type : str\n        The buffer type.\n\n    axis_separators : List[int]\n        The separators between input axes when generating flattened output axes.\n\n    Returns\n    -------\n    res : frame.DeclBufferFrame\n        The result DeclBufferFrame.\n    \"\"\"\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    return _ffi_api.DeclBuffer(  # type: ignore[attr-defined] # pylint: disable=no-member\n        shape,\n        dtype,\n        \"\",\n        data,\n        strides,\n        elem_offset,\n        scope,\n        align,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n    )\n\n\ndef launch_thread(\n    iter_var: IterVar,  # pylint: disable=redefined-outer-name\n    extent: PrimExpr,\n) -> frame.LaunchThreadFrame:\n    \"\"\"Launch a thread.\n\n    Parameters\n    ----------\n    iter_var : IterVar\n        The iteration variable.\n\n    extent : PrimExpr\n        The extent of environment thread.\n\n    Returns\n    -------\n    res : frame.LaunchThreadFrame\n        The result LaunchThreadFrame.\n\n    Examples\n    --------\n\n    .. code-block:: python\n\n    from tvm.script.ir_builder import tir as T\n    brow = T.env_thread(\"blockIdx.y\")\n    T.launch_thread(brow, 1)\n\n    \"\"\"\n    return _ffi_api.LaunchThread(iter_var, extent)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef env_thread(thread_tag: str) -> IterVar:\n    \"\"\"Bind a var to thread env\"\n\n    Parameters\n    ----------\n    thread_tag : str\n        The thread type tag.\n\n    Returns\n    -------\n    res : IterVar\n        The result iteration variable gets bound to the thread env.\n\n    \"\"\"\n    return _ffi_api.EnvThread(thread_tag)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef buffer_store(buffer: Buffer, value: PrimExpr, indices: List[Union[PrimExpr, slice]]) -> None:\n    \"\"\"Buffer store node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer.\n\n    value : PrimExpr\n        The value to be stored.\n\n    indices : List[Union[PrimExpr, slice]]\n        The indices location to be stored.\n    \"\"\"\n    from tvm.arith import Analyzer  # pylint: disable=import-outside-toplevel\n\n    expr_indices = []\n    for index in indices:\n        if isinstance(index, slice):\n            step = 1 if index.step is None else index.step\n            lanes = Analyzer().simplify((index.stop - index.start + step - 1) // step)\n            if lanes == 1:\n                expr_indices.append(index.start)\n            else:\n                expr_indices.append(ramp(index.start, step, int(lanes)))\n        else:\n            expr_indices.append(index)\n    if isinstance(value, bool) and buffer.dtype == \"bool\":\n        value = IntImm(\"bool\", value)\n    return _ffi_api.BufferStore(  # type: ignore[attr-defined] # pylint: disable=no-member\n        buffer, value, expr_indices\n    )\n\n\ndef prefetch(buffer: Buffer, indices: List[PrimExpr]) -> None:\n    \"\"\"The prefetch hint for a buffer.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer to be prefetched.\n    indices : List[PrimExpr]\n        The indices of the buffer to extract.\n    \"\"\"\n    return _ffi_api.Prefetch(buffer, indices)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef evaluate(value: PrimExpr) -> None:\n    \"\"\"Evaluate the input expression.\n\n    Parameters\n    ----------\n    value: PrimExpr\n        The input expression to evaluate.\n    \"\"\"\n    if isinstance(value, str):\n        value = StringImm(value)\n    if isinstance(value, bool):\n        value = cast(value, \"bool\")\n    return _ffi_api.Evaluate(value)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\n__all__ = []\nfor _dtype in [\"Float\", \"UInt\", \"Int\"]:\n    for _size in [\"8\", \"16\", \"32\", \"64\"]:\n        for _lanes in [\"\", \"x4\", \"x8\", \"x16\", \"x32\", \"x64\"]:\n            _name = _dtype + _size + _lanes  # pylint: disable=invalid-name\n\n            def func_gen(name: str):\n                \"\"\"Generate a function for each PrimExpr dtype.\n\n                Parameters\n                ----------\n                name: str\n                    The ffi function name to call.\n                \"\"\"\n\n                def func(\n                    expr: Union[\n                        None,\n                        PrimExpr,\n                        Literal[\"inf\", \"-inf\", \"nan\"],\n                    ] = None\n                ) -> PrimExpr:\n                    if isinstance(expr, str):\n                        expr = float(expr)\n                    return getattr(_ffi_api, name)(expr)\n\n                return func\n\n            globals()[_name.lower()] = func_gen(_name)\n            __all__.append(_name.lower())\n\n\ndef boolean(expr: Optional[PrimExpr] = None) -> PrimExpr:\n    \"\"\"Construct a new tir.Var with type boolean or cast expression to type boolean.\n\n    Parameters\n    ----------\n    expr: PrimExpr\n        The expression to be cast.\n\n    Returns\n    -------\n    res : PrimExpr\n        The new tir.Var with type boolean or casted expression with type boolean.\n    \"\"\"\n    return _ffi_api.Boolean(expr)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef handle(expr: Optional[PrimExpr] = None) -> PrimExpr:\n    \"\"\"Construct a new tir.Var with type handle or cast expression to type handle.\n\n    Parameters\n    ----------\n    expr: PrimExpr\n        The expression to be cast.\n\n    Returns\n    -------\n    res : PrimExpr\n        The new tir.Var with type handle or casted expression with type handle.\n    \"\"\"\n    return _ffi_api.Handle(expr)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef void(expr: Optional[PrimExpr] = None) -> PrimExpr:\n    \"\"\"Construct a new tir.Var with type void or cast expression to type void.\n\n    Parameters\n    ----------\n    expr: PrimExpr\n        The expression to be cast.\n\n    Returns\n    -------\n    res : PrimExpr\n        The new tir.Var with type void or casted expression with type void.\n    \"\"\"\n    return _ffi_api.Void(expr)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef var(dtype: str, name: str = \"\") -> Var:\n    \"\"\"Construct a new tir.Var.\n\n    Parameters\n    ----------\n    dtype: str\n        The dtype of the Var.\n\n    name: str\n        The name of the Var.\n\n    Returns\n    -------\n    res : Var\n        The result tir.Var.\n    \"\"\"\n    return Var(name, dtype)  # pylint: disable=no-member\n\n\ndef ptr(dtype: str, storage_scope: str = \"global\") -> Var:\n    \"\"\"The pointer declaration function.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the pointer.\n\n    storage_scope : str\n        The storage scope of the pointer.\n\n    Returns\n    -------\n    res : Var\n        The pointer.\n    \"\"\"\n    return _ffi_api.Ptr(dtype, storage_scope)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef min(a: PrimExpr, b: PrimExpr) -> PrimExpr:  # pylint: disable=redefined-builtin\n    \"\"\"Compute the minimum value of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n    \"\"\"\n    return _ffi_api.min(a, b)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef max(a: PrimExpr, b: PrimExpr) -> PrimExpr:  # pylint: disable=redefined-builtin\n    \"\"\"Compute the maximum value of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n    \"\"\"\n    return _ffi_api.max(a, b)  # type: ignore[attr-defined] # pylint: disable=no-member\n\n\ndef iter_var(v: Union[Var, str], dom: Range, iter_type: str, thread_tag: str) -> IterVar:\n    \"\"\"The iteration variable.\n\n    Parameters\n    ----------\n    var : Union[Var, str]\n        The internal variable that is used for iteration.\n\n    dom : Range\n        The domain of the iteration.\n\n    iter_type : str\n        The iteration type.\n\n    thread_tag : str\n        The thread type tag.\n\n    Returns\n    -------\n    res : IterVar\n        The iteration variable.\n    \"\"\"\n    iter_type = getattr(IterVar, iter_type)\n    return IterVar(dom, v, iter_type, thread_tag)\n\n\ndef comm_reducer(combiner: Callable, identity: List[PrimExpr]) -> CommReducer:\n    \"\"\"\n    Create a CommReducer from lambda inputs/outputs and the identities\n\n    Parameters\n    ----------\n    combiner : Callable\n        A binary function which takes two PrimExpr as input to return a PrimExpr.\n\n    identity : List[PrimExpr]\n        A list of types of output PrimExpr.\n\n    Returns\n    -------\n    res : CommReducer\n        The CommReducer.\n    \"\"\"\n    params = inspect.signature(combiner).parameters\n    num_args = len(params)\n    args = []\n    for name, i in zip(params.keys(), identity + identity):\n        if isinstance(i, int):\n            args.append(Var(name, \"int32\"))\n        else:\n            args.append(Var(name, i.dtype))\n    res = combiner(*args)\n    if not isinstance(res, tuple):\n        res = (res,)\n    return CommReducer(args[: num_args // 2], args[num_args // 2 :], res, identity)\n\n\ndef target(target_config: Union[Dict, str]) -> Target:\n    \"\"\"\n    Create a target\n\n    Parameters\n    ----------\n    target_config : Union[Dict, str]\n        The target configuration.\n\n    Returns\n    -------\n    res : Target\n        The target.\n    \"\"\"\n    if not isinstance(target_config, (str, dict)):\n        raise ValueError(\n            f\"T.target expected a config dict or string, but got {type(target_config)}\"\n        )\n    return Target(target_config)\n\n\ndef _op_wrapper(func):\n    @functools.wraps(func)\n    def wrapped(*args, **kwargs):\n        if \"dtype\" in kwargs:\n            kwargs.pop(\"dtype\")\n        return func(*args, **kwargs)\n\n    return wrapped\n\n\ndef _dtype_forward(func):\n    @functools.wraps(func)\n    def wrapped(*args, **kwargs):\n        if \"dtype\" in kwargs:\n            args = (kwargs.pop(\"dtype\"),) + args\n        return func(*args, **kwargs)\n\n    return wrapped\n\n\n# pylint: disable=invalid-name\n\nbroadcast = Broadcast\nramp = Ramp\n\nbuffer_var = ptr\nabs = _op_wrapper(_tir_op.abs)  # pylint: disable=redefined-builtin\nfabs = abs\nacos = _op_wrapper(_tir_op.acos)\nacosh = _op_wrapper(_tir_op.acosh)\naddress_of = _op_wrapper(_tir_op.address_of)\nasin = _op_wrapper(_tir_op.asin)\nasinh = _op_wrapper(_tir_op.asinh)\natan = _op_wrapper(_tir_op.atan)\natan2 = _op_wrapper(_tir_op.atan2)\natanh = _op_wrapper(_tir_op.atanh)\nceil = _op_wrapper(_tir_op.ceil)\nclz = _op_wrapper(_tir_op.clz)\ncopysign = _op_wrapper(_tir_op.copysign)\ncos = _op_wrapper(_tir_op.cos)\ncosh = _op_wrapper(_tir_op.cosh)\nerf = _op_wrapper(_tir_op.erf)\nexp = _op_wrapper(_tir_op.exp)\nexp2 = _op_wrapper(_tir_op.exp2)\nexp10 = _op_wrapper(_tir_op.exp10)\nfloor = _op_wrapper(_tir_op.floor)\nceildiv = _op_wrapper(_tir_op.ceildiv)\nfloordiv = _op_wrapper(_tir_op.floordiv)\nfloormod = _op_wrapper(_tir_op.floormod)\nfmod = _op_wrapper(_tir_op.fmod)\nhypot = _op_wrapper(_tir_op.hypot)\nif_then_else = _op_wrapper(_tir_op.if_then_else)\ninfinity = _op_wrapper(_tir_op.infinity)\nisfinite = _op_wrapper(_tir_op.isfinite)\nisinf = _op_wrapper(_tir_op.isinf)\nisnan = _op_wrapper(_tir_op.isnan)\nisnullptr = _op_wrapper(_tir_op.isnullptr)\nldexp = _op_wrapper(_tir_op.ldexp)\nlikely = _op_wrapper(_tir_op.likely)\nlog = _op_wrapper(_tir_op.log)\nlog1p = _op_wrapper(_tir_op.log1p)\nlog2 = _op_wrapper(_tir_op.log2)\nlog10 = _op_wrapper(_tir_op.log10)\nlookup_param = _op_wrapper(_tir_op.lookup_param)\nmax_value = _op_wrapper(_tir_op.max_value)\nmin_value = _op_wrapper(_tir_op.min_value)\nnearbyint = _op_wrapper(_tir_op.nearbyint)\nnextafter = _op_wrapper(_tir_op.nextafter)\npopcount = _op_wrapper(_tir_op.popcount)\npower = _op_wrapper(_tir_op.power)\nq_multiply_shift = _op_wrapper(_tir_op.q_multiply_shift)\nq_multiply_shift_per_axis = _op_wrapper(_tir_op.q_multiply_shift_per_axis)\nret = _op_wrapper(_tir_op.ret)\nreinterpret = _dtype_forward(_tir_op.reinterpret)\nround = _op_wrapper(_tir_op.round)  # pylint: disable=redefined-builtin\nrsqrt = _op_wrapper(_tir_op.rsqrt)\nshift_left = _op_wrapper(_tir_op.shift_left)\nshift_right = _op_wrapper(_tir_op.shift_right)\nsigmoid = _op_wrapper(_tir_op.sigmoid)\nsin = _op_wrapper(_tir_op.sin)\nsinh = _op_wrapper(_tir_op.sinh)\nsqrt = _op_wrapper(_tir_op.sqrt)\ntan = _op_wrapper(_tir_op.tan)\ntanh = _op_wrapper(_tir_op.tanh)\ntrunc = _op_wrapper(_tir_op.trunc)\ntruncdiv = _op_wrapper(_tir_op.truncdiv)\ntruncmod = _op_wrapper(_tir_op.truncmod)\ntvm_access_ptr = _op_wrapper(_tir_op.tvm_access_ptr)\ntvm_throw_last_error = _op_wrapper(_tir_op.tvm_throw_last_error)\ntvm_stack_alloca = _op_wrapper(_tir_op.tvm_stack_alloca)\ntvm_stack_make_shape = _op_wrapper(_tir_op.tvm_stack_make_shape)\ntvm_stack_make_array = _op_wrapper(_tir_op.tvm_stack_make_array)\ntvm_check_return = _op_wrapper(_tir_op.tvm_check_return)\ncall_packed = _op_wrapper(_tir_op.call_packed)\ncall_cpacked = _op_wrapper(_tir_op.call_cpacked)\ncall_packed_lowered = _op_wrapper(_tir_op.call_packed_lowered)\ncall_cpacked_lowered = _op_wrapper(_tir_op.call_cpacked_lowered)\ncall_extern = _dtype_forward(_tir_op.call_extern)\ncall_intrin = _dtype_forward(_tir_op.call_intrin)\ncall_llvm_intrin = _dtype_forward(_tir_op.call_llvm_intrin)\ncall_llvm_pure_intrin = _dtype_forward(_tir_op.call_llvm_pure_intrin)\ncall_pure_extern = _dtype_forward(_tir_op.call_pure_extern)\ntvm_tuple = _op_wrapper(_tir_op.tvm_tuple)\ntvm_struct_set = _op_wrapper(_tir_op.tvm_struct_set)\ntvm_struct_get = _tir_op.tvm_struct_get\ntvm_thread_allreduce = _op_wrapper(_tir_op.tvm_thread_allreduce)\ntvm_load_matrix_sync = _op_wrapper(_tir_op.tvm_load_matrix_sync)\ntvm_mma_sync = _op_wrapper(_tir_op.tvm_mma_sync)\ntvm_bmma_sync = _op_wrapper(_tir_op.tvm_bmma_sync)\ntvm_fill_fragment = _op_wrapper(_tir_op.tvm_fill_fragment)\ntvm_store_matrix_sync = _op_wrapper(_tir_op.tvm_store_matrix_sync)\nptx_mma = _dtype_forward(_tir_op.ptx_mma)\nptx_mma_sp = _dtype_forward(_tir_op.ptx_mma_sp)\nptx_ldmatrix = _dtype_forward(_tir_op.ptx_ldmatrix)\nptx_cp_async = _dtype_forward(_tir_op.ptx_cp_async)\nptx_wait_group = _op_wrapper(_tir_op.ptx_wait_group)\nptx_commit_group = _op_wrapper(_tir_op.ptx_commit_group)\nmma_store = _dtype_forward(_tir_op.mma_store)\nmma_fill = _dtype_forward(_tir_op.mma_fill)\nvectorlow = _dtype_forward(_tir_op.vectorlow)\nvectorhigh = _dtype_forward(_tir_op.vectorhigh)\nvectorcombine = _dtype_forward(_tir_op.vectorcombine)\nassume = _op_wrapper(_tir_op.assume)\nundef = _op_wrapper(_tir_op.undef)\ntvm_call_packed = call_packed\ntvm_call_cpacked = call_cpacked\ntvm_call_packed_lowered = call_packed_lowered\ntvm_call_cpacked_lowered = call_cpacked_lowered\nTVMBackendAllocWorkspace = _op_wrapper(_tir_op.TVMBackendAllocWorkspace)\nTVMBackendFreeWorkspace = _op_wrapper(_tir_op.TVMBackendFreeWorkspace)\nstart_profile_intrinsic = _op_wrapper(_tir_op.start_profile_intrinsic)\nend_profile_intrinsic = _op_wrapper(_tir_op.end_profile_intrinsic)\n\n\nclass meta_var:\n    \"\"\"A meta variable used in TVMScript metaprogramming. It means that the value of the variable\n    does not appear in the final TIR, but only stays in the parser.\n\n    Parameters\n    ----------\n    value: Any\n        The meta variable.\n    \"\"\"\n\n    def __init__(self, value: Any) -> None:\n        self.value = value\n\n    def __iter__(self):\n        def f():\n            for i in self.value:\n                yield meta_var(i)\n\n        return f()\n\n\n# pylint: enable=invalid-name\n\n\n__all__ += [\n    \"buffer_decl\",\n    \"prim_func\",\n    \"arg\",\n    \"func_name\",\n    \"func_attr\",\n    \"func_ret\",\n    \"match_buffer\",\n    \"preflattened_buffer\",\n    \"block\",\n    \"init\",\n    \"where\",\n    \"reads\",\n    \"writes\",\n    \"block_attr\",\n    \"alloc_buffer\",\n    \"axis\",\n    \"serial\",\n    \"parallel\",\n    \"vectorized\",\n    \"unroll\",\n    \"thread_binding\",\n    \"grid\",\n    \"Assert\",\n    \"let\",\n    \"realize\",\n    \"allocate\",\n    \"allocate_const\",\n    \"attr\",\n    \"While\",\n    \"If\",\n    \"Then\",\n    \"Else\",\n    \"decl_buffer\",\n    \"launch_thread\",\n    \"env_thread\",\n    \"buffer_store\",\n    \"prefetch\",\n    \"evaluate\",\n    \"boolean\",\n    \"handle\",\n    \"void\",\n    \"var\",\n    \"ptr\",\n    \"min\",\n    \"max\",\n    \"iter_var\",\n    \"comm_reducer\",\n    \"target\",\n    \"buffer_var\",\n    \"abs\",\n    \"fabs\",\n    \"acos\",\n    \"acosh\",\n    \"address_of\",\n    \"asin\",\n    \"asinh\",\n    \"atan\",\n    \"atan2\",\n    \"atanh\",\n    \"ceil\",\n    \"clz\",\n    \"copysign\",\n    \"cos\",\n    \"cosh\",\n    \"erf\",\n    \"exp\",\n    \"exp2\",\n    \"exp10\",\n    \"floor\",\n    \"ceildiv\",\n    \"floordiv\",\n    \"floormod\",\n    \"fmod\",\n    \"hypot\",\n    \"if_then_else\",\n    \"infinity\",\n    \"isfinite\",\n    \"isinf\",\n    \"isnan\",\n    \"isnullptr\",\n    \"ldexp\",\n    \"likely\",\n    \"log\",\n    \"log1p\",\n    \"log2\",\n    \"log10\",\n    \"lookup_param\",\n    \"max_value\",\n    \"min_value\",\n    \"nearbyint\",\n    \"nextafter\",\n    \"popcount\",\n    \"power\",\n    \"q_multiply_shift\",\n    \"q_multiply_shift_per_axis\",\n    \"ret\",\n    \"reinterpret\",\n    \"round\",\n    \"rsqrt\",\n    \"shift_left\",\n    \"shift_right\",\n    \"sigmoid\",\n    \"sin\",\n    \"sinh\",\n    \"sqrt\",\n    \"tan\",\n    \"tanh\",\n    \"trunc\",\n    \"truncdiv\",\n    \"truncmod\",\n    \"tvm_access_ptr\",\n    \"tvm_throw_last_error\",\n    \"tvm_stack_alloca\",\n    \"tvm_stack_make_shape\",\n    \"tvm_stack_make_array\",\n    \"tvm_check_return\",\n    \"call_packed\",\n    \"call_cpacked\",\n    \"call_packed_lowered\",\n    \"call_cpacked_lowered\",\n    \"call_extern\",\n    \"call_intrin\",\n    \"call_llvm_intrin\",\n    \"call_llvm_pure_intrin\",\n    \"call_pure_extern\",\n    \"tvm_tuple\",\n    \"tvm_struct_set\",\n    \"tvm_struct_get\",\n    \"tvm_thread_allreduce\",\n    \"tvm_load_matrix_sync\",\n    \"tvm_mma_sync\",\n    \"tvm_bmma_sync\",\n    \"tvm_fill_fragment\",\n    \"tvm_store_matrix_sync\",\n    \"ptx_mma\",\n    \"ptx_mma_sp\",\n    \"ptx_ldmatrix\",\n    \"ptx_cp_async\",\n    \"ptx_wait_group\",\n    \"ptx_commit_group\",\n    \"mma_store\",\n    \"mma_fill\",\n    \"vectorlow\",\n    \"vectorhigh\",\n    \"vectorcombine\",\n    \"assume\",\n    \"undef\",\n    \"tvm_call_packed\",\n    \"tvm_call_cpacked\",\n    \"tvm_call_packed_lowered\",\n    \"tvm_call_cpacked_lowered\",\n    \"TVMBackendAllocWorkspace\",\n    \"TVMBackendFreeWorkspace\",\n    \"start_profile_intrinsic\",\n    \"end_profile_intrinsic\",\n    \"meta_var\",\n    \"llvm_lookup_intrinsic_id\",\n    \"type_annotation\",\n    \"broadcast\",\n    \"ramp\",\n    \"cast\",\n    # tvm.tir.expr\n    \"Var\",\n    \"SizeVar\",\n    \"Reduce\",\n    \"FloatImm\",\n    \"IntImm\",\n    \"StringImm\",\n    \"Cast\",\n    \"Add\",\n    \"Sub\",\n    \"Mul\",\n    \"Div\",\n    \"Mod\",\n    \"FloorDiv\",\n    \"FloorMod\",\n    \"Min\",\n    \"Max\",\n    \"EQ\",\n    \"NE\",\n    \"LT\",\n    \"LE\",\n    \"GT\",\n    \"GE\",\n    \"And\",\n    \"Or\",\n    \"Not\",\n    \"Select\",\n    \"BufferLoad\",\n    \"ProducerLoad\",\n    \"Load\",\n    \"Ramp\",\n    \"Broadcast\",\n    \"Shuffle\",\n    \"Call\",\n    \"CallEffectKind\",\n    \"Let\",\n    \"IterVar\",\n    \"CommReducer\",\n]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the Licens.\n\"\"\"The parser\"\"\"\nfrom . import _core, ir, tir\nfrom ._core import parse\nfrom .ir import ir_module\nfrom .tir import prim_func\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/_core.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the Licens.\n\"\"\"The core parser infra\"\"\"\n# pylint: disable=unused-import\nfrom .core import dispatch, doc, utils\nfrom .core.dispatch import OpMethod, register_op\nfrom .core.entry import parse\nfrom .core.parser import Parser\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The core parser infra\"\"\"\nfrom . import diagnostics, dispatch, doc, doc_core, entry, evaluator, parser, utils\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/diagnostics.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Source and diagnostics\"\"\"\n\nimport inspect\nimport sys\nfrom typing import Union\n\nfrom tvm.ir import IRModule, SourceName, Span, diagnostics\n\nfrom . import doc\n\n\nclass Source:\n    \"\"\"Source code class for TVMScript.\n\n    It is constructed by source code str or doc AST tree.\n\n    Parameters\n    ----------\n    source_name : str\n        The filename of the file where the source code locates.\n\n    start_line : int\n        The first line number of the source code.\n\n    start_column : int\n        The first column number of the first line of the source code.\n\n    source : str\n        The source code str of source code.\n\n    full_source : str\n        The complete source code of the file where the source code locates.\n    \"\"\"\n\n    source_name: str\n    start_line: int\n    start_column: int\n    source: str\n    full_source: str\n\n    def __init__(self, program: Union[str, doc.AST]):\n        if isinstance(program, str):\n            self.source_name = \"<str>\"\n            self.start_line = 1\n            self.start_column = 0\n            self.source = program\n            self.full_source = program\n            return\n\n        self.source_name = inspect.getsourcefile(program)  # type: ignore\n        lines, self.start_line = getsourcelines(program)  # type: ignore\n        if lines:\n            self.start_column = len(lines[0]) - len(lines[0].lstrip())\n        else:\n            self.start_column = 0\n        if self.start_column and lines:\n            self.source = \"\\n\".join([l[self.start_column :].rstrip() for l in lines])\n        else:\n            self.source = \"\".join(lines)\n        try:\n            # It will cause a problem when running in Jupyter Notebook.\n            # `mod` will be <module '__main__'>, which is a built-in module\n            # and `getsource` will throw a TypeError\n            mod = inspect.getmodule(program)\n            if mod:\n                self.full_source = inspect.getsource(mod)\n            else:\n                self.full_source = self.source\n        except TypeError:\n            # It's a work around for Jupyter problem.\n            # Since `findsource` is an internal API of inspect, we just use it\n            # as a fallback method.\n            src, _ = inspect.findsource(program)  # type: ignore\n            self.full_source = \"\".join(src)\n\n    def as_ast(self) -> doc.AST:\n        \"\"\"Parse the source code into AST.\n\n        Returns\n        -------\n        res : doc.AST\n            The AST of source code.\n        \"\"\"\n        return doc.parse(self.source)\n\n\n_getfile = inspect.getfile  # pylint: disable=invalid-name\n_findsource = inspect.findsource  # pylint: disable=invalid-name\n\n\ndef _patched_inspect_getfile(obj):\n    \"\"\"Work out which source or compiled file an object was defined in.\"\"\"\n    if not inspect.isclass(obj):\n        return _getfile(obj)\n    mod = getattr(obj, \"__module__\", None)\n    if mod is not None:\n        file = getattr(sys.modules[mod], \"__file__\", None)\n        if file is not None:\n            return file\n    for _, member in inspect.getmembers(obj):\n        if inspect.isfunction(member):\n            if obj.__qualname__ + \".\" + member.__name__ == member.__qualname__:\n                return inspect.getfile(member)\n    raise TypeError(f\"Source for {obj:!r} not found\")\n\n\ndef findsource(obj):\n    \"\"\"Return the entire source file and starting line number for an object.\"\"\"\n    import linecache  # pylint: disable=import-outside-toplevel\n\n    if not inspect.isclass(obj):\n        return _findsource(obj)\n\n    file = inspect.getsourcefile(obj)\n    if file:\n        linecache.checkcache(file)\n    else:\n        file = inspect.getfile(obj)\n        if not (file.startswith(\"<\") and file.endswith(\">\")):\n            raise OSError(\"source code not available\")\n\n    module = inspect.getmodule(obj, file)\n    if module:\n        lines = linecache.getlines(file, module.__dict__)\n    else:\n        lines = linecache.getlines(file)\n    if not lines:\n        raise OSError(\"could not get source code\")\n    qual_names = obj.__qualname__.replace(\".<locals>\", \"<locals>\").split(\".\")\n    in_comment = 0\n    scope_stack = []\n    indent_info = {}\n    for i, line in enumerate(lines):\n        n_comment = line.count('\"\"\"')\n        if n_comment:\n            # update multi-line comments status\n            in_comment = in_comment ^ (n_comment & 1)\n            continue\n        if in_comment:\n            # skip lines within multi-line comments\n            continue\n        indent = len(line) - len(line.lstrip())\n        tokens = line.split()\n        if len(tokens) > 1:\n            name = None\n            if tokens[0] == \"def\":\n                name = tokens[1].split(\":\")[0].split(\"(\")[0] + \"<locals>\"\n            elif tokens[0] == \"class\":\n                name = tokens[1].split(\":\")[0].split(\"(\")[0]\n            if name:\n                while scope_stack and indent_info[scope_stack[-1]] >= indent:\n                    scope_stack.pop()\n                scope_stack.append(name)\n                indent_info[name] = indent\n                if scope_stack == qual_names:\n                    return lines, i\n\n    raise OSError(\"could not find class definition\")\n\n\ndef getsourcelines(obj):\n    \"\"\"Extract the block of code at the top of the given list of lines.\"\"\"\n    obj = inspect.unwrap(obj)\n    lines, l_num = findsource(obj)\n    return inspect.getblock(lines[l_num:]), l_num + 1\n\n\ninspect.getfile = _patched_inspect_getfile\n\n\nclass Diagnostics:\n    \"\"\"Diagnostics class for error reporting in parser.\n\n    Parameters\n    ----------\n    source : Source\n        The source code.\n\n    ctx : diagnostics.DiagnosticContext\n        The diagnostic context for diagnostics.\n    \"\"\"\n\n    source: Source\n    ctx: diagnostics.DiagnosticContext\n\n    def __init__(self, source: Source):\n        mod = IRModule()\n        mod.source_map.add(source.source_name, source.full_source)\n        self.source = source\n        self.ctx = diagnostics.DiagnosticContext(mod, diagnostics.get_renderer())\n\n    def _emit(self, node: doc.AST, message: str, level: diagnostics.DiagnosticLevel) -> None:\n        \"\"\"Emit a diagnostic.\n\n        Parameters\n        ----------\n        node : doc.AST\n            The node with diagnostic information.\n\n        message : str\n            The diagnostic message.\n\n        level : diagnostics.DiagnosticLevel\n            The diagnostic level.\n        \"\"\"\n        lineno = node.lineno or self.source.start_line\n        col_offset = node.col_offset or self.source.start_column\n        end_lineno = node.end_lineno or lineno\n        end_col_offset = node.end_col_offset or col_offset\n        lineno += self.source.start_line - 1\n        end_lineno += self.source.start_line - 1\n        col_offset += self.source.start_column + 1\n        end_col_offset += self.source.start_column + 1\n        self.ctx.emit(\n            diagnostics.Diagnostic(\n                level=level,\n                span=Span(\n                    source_name=SourceName(self.source.source_name),\n                    line=lineno,\n                    end_line=end_lineno,\n                    column=col_offset,\n                    end_column=end_col_offset,\n                ),\n                message=message,\n            )\n        )\n\n    def error(self, node: doc.AST, message: str) -> None:\n        \"\"\"Emit a diagnostic error.\n\n        Parameters\n        ----------\n        node : doc.AST\n            The node with diagnostic error.\n\n        message : str\n            The diagnostic message.\n        \"\"\"\n        self._emit(node, message, diagnostics.DiagnosticLevel.ERROR)\n        self.ctx.render()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/dispatch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Parser dispatching infrastructure\"\"\"\n\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type\n\nfrom .doc import AST\n\nif TYPE_CHECKING:\n    from .parser import Parser\n\n\nParseMethod = Callable[[\"Parser\", AST], None]\nParseVTable: Dict[Tuple[str, str], ParseMethod] = {}\n\nOpMethod = Callable[..., Any]\nOpVTable: Dict[Tuple[Type, AST, int], OpMethod] = {}\n\n\ndef register(token: str, type_name: str):\n    \"\"\"Register a method for a dispatch token and type name.\n\n    Parameters\n    ----------\n    token : str\n        The token for IR, e.g., T for TIR and R for Relax.\n\n    type_name : str\n        The type name of AST node, e.g., FunctionDef, With, For.\n\n    Returns\n    -------\n    func : callable\n        The function to register dispatched method of parsing\n        corresponding token and AST node type.\n    \"\"\"\n\n    def func(method: ParseMethod):\n        \"\"\"Register a method in parser virtual table.\n\n        Parameters\n        ----------\n        method : ParseMethod\n            The dispatched method to be registered in parser virtual table.\n        \"\"\"\n        ParseVTable[(token, type_name)] = method\n\n    return func\n\n\ndef get(\n    token: str,\n    type_name: str,\n    default: Optional[ParseMethod] = None,\n) -> Optional[ParseMethod]:\n    \"\"\"Get a registered method for a dispatch token and type name,\n    or return a default method if no registered methods with this dispatch token and type name.\n\n    Parameters\n    ----------\n    token : str\n        The token for IR, e.g., T for TIR and R for Relax.\n\n    type_name : str\n        The type name of AST node, e.g., FunctionDef, With, For.\n\n    default : Optional[ParseMethod]\n        The default method when no registered methods with this dispatch token and type name.\n\n    Returns\n    -------\n    func : Optional[ParseMethod]\n        The dispatched method of parsing corresponding token and AST node type.\n    \"\"\"\n    return ParseVTable.get((token, type_name), default)\n\n\ndef register_op(operand_type: Type, op_node_type: AST, operand_index: int):\n    \"\"\"Register a method for a operand type, AST operator node and operand index.\n\n    Parameters\n    ----------\n    operand_type : Type\n        The type of operands, e.g., tir.PrimExpr, tir.IterVar.\n\n    op_node_type : AST\n        The doc AST operator node type, e.g., doc.Add, doc.Eq.\n\n    operand_index : int\n        The operand index, i.e., 0 for left operand and 1 for right operand.\n\n    Returns\n    -------\n    func : callable\n        The function to register dispatched method of parsing\n        corresponding a operand type, AST operator node and operand index.\n    \"\"\"\n\n    def func(method: OpMethod):\n        \"\"\"Register a method in parser operator virtual table.\n\n        Parameters\n        ----------\n        method : ParseMethod\n            The dispatched method to be registered in parser operator virtual table.\n        \"\"\"\n        OpVTable[(operand_type, op_node_type, operand_index)] = method\n\n    return func\n\n\ndef get_op(\n    operand_type: Type,\n    op_node_type: Type,\n    operand_index: int,\n    default: Optional[OpMethod] = None,\n) -> Optional[OpMethod]:\n    \"\"\"Register a method for a operand type, AST operator node and operand index.\n\n    Parameters\n    ----------\n    operand_type : Type\n        The type of operands, e.g., tir.PrimExpr, tir.IterVar.\n\n    op_node_type : AST\n        The doc AST operator node type, e.g., doc.Add, doc.Eq.\n\n    operand_index : int\n        The operand index, i.e., 0 for left operand and 1 for right operand.\n\n\n    default : Optional[OpMethod]\n        The default method when no registered methods with this operand type,\n        AST operator node and operand index.\n\n    Returns\n    -------\n    func : Optional[OpMethod]\n        The function to register dispatched method of parsing\n        corresponding a operand type, AST operator node and operand index.\n    \"\"\"\n    return OpVTable.get((operand_type, op_node_type, operand_index), default)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/doc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser doc AST\"\"\"\n\nimport ast\nimport inspect\nimport sys\nimport typing\nfrom collections import defaultdict\n\nfrom . import doc_core as doc\nfrom .doc_core import *  # pylint: disable=unused-import,wildcard-import,redefined-builtin,W0614\n\nFnToDoc = typing.Callable[[ast.AST], doc.AST]\nFnFromDoc = typing.Callable[[doc.AST], ast.AST]\n\n\nclass Entry:\n    \"\"\"Mapping entry between python AST node type str and doc AST.\n\n    Parameters\n    ----------\n    to_doc : typing.Optional[FnToDoc]\n        The callable methods for converting python AST node to doc AST.\n\n    from_doc : typing.Optional[FnFromDoc]\n        The callable methods for converting doc AST to python AST node.\n    \"\"\"\n\n    to_doc: typing.Optional[FnToDoc]\n    from_doc: typing.Optional[FnFromDoc]\n\n    def __init__(self):\n        self.to_doc = None\n        self.from_doc = None\n\n\nclass Registry:\n    \"\"\"Registration map from python AST node type str to methods of conversion\n    between python AST node and doc AST node.\n\n    Parameters\n    ----------\n    _inst : typing.Optional[\"Registry\"]\n        The instance of Registry.\n\n    table : typing.Dict[str, Entry]\n        The registration map from python AST node type str to methods of conversion\n        between python AST node and doc AST node.\n    \"\"\"\n\n    _inst: typing.Optional[\"Registry\"] = None\n    table: typing.Dict[str, Entry]\n\n    def __init__(self):\n        self.table = defaultdict(Entry)\n\n\ndef register_to_doc(name: str):\n    \"\"\"Register the to_doc method for python AST node type.\n\n    Parameters\n    ----------\n    name : str\n        The type of python AST node.\n\n    Returns\n    -------\n    f : Callable[[FnToDoc], None]\n        The function of registering the to_doc method for python AST node type.\n    \"\"\"\n\n    def f(to_doc: FnToDoc):  # pylint: disable=redefined-outer-name\n        reg = Registry._inst  # pylint: disable=protected-access\n        reg.table[name].to_doc = to_doc\n\n    return f\n\n\ndef register_from_doc(name: str):\n    \"\"\"Register the from_doc method for python AST node type.\n\n    Parameters\n    ----------\n    name : str\n        The type of python AST node.\n\n    Returns\n    -------\n    f : Callable[[FnFromDoc], None]\n        The function of registering the from_doc method for python AST node type.\n    \"\"\"\n\n    def f(to_doc: FnFromDoc):  # pylint: disable=redefined-outer-name\n        reg = Registry._inst  # pylint: disable=protected-access\n        reg.table[name].from_doc = to_doc\n\n    return f\n\n\ndef _is_atomic_type(node):\n    return (\n        node is None\n        or node in [..., True, False]\n        or isinstance(\n            node,\n            (\n                int,\n                float,\n                str,\n                bool,\n                bytes,\n                complex,\n            ),\n        )\n    )\n\n\ndef _get_registry_entry(cls_name, attr):\n    cls_name = cls_name.split(\".\")[-1]\n    reg = Registry._inst  # pylint: disable=protected-access\n    if cls_name in reg.table:\n        entry = reg.table[cls_name]\n        return getattr(entry, attr, None)\n    return None\n\n\ndef from_doc(node):\n    \"\"\"Get original python AST node from doc AST node.\n\n    Parameters\n    ----------\n    node : doc.AST\n        The doc AST node.\n\n    Returns\n    -------\n    res : ast.AST\n        The corresponding AST node.\n    \"\"\"\n    if _is_atomic_type(node):\n        return node\n    if isinstance(node, tuple):\n        return tuple(from_doc(n) for n in node)\n    if isinstance(node, list):\n        return [from_doc(n) for n in node]\n    func = _get_registry_entry(node.__class__.__name__, \"from_doc\")\n    if not func:\n        raise NotImplementedError(f\"from_doc is not implemented for: {node.__class__.__name__}\")\n    return func(node)\n\n\ndef to_doc(node):\n    \"\"\"Get doc AST node from python AST node.\n\n    Parameters\n    ----------\n    node : ast.AST\n        The AST node.\n\n    Returns\n    -------\n    res : doc.AST\n        The corresponding doc AST node.\n    \"\"\"\n    if _is_atomic_type(node):\n        return node\n    if isinstance(node, tuple):\n        return tuple(to_doc(n) for n in node)\n    if isinstance(node, list):\n        return [to_doc(n) for n in node]\n    func = _get_registry_entry(node.__class__.__name__, \"to_doc\")\n    if not func:\n        raise NotImplementedError(f\"to_doc is not implemented for: {node.__class__.__name__}\")\n    return func(node)\n\n\ndef parse(\n    source: str,\n    filename: str = \"<unknown>\",\n    mode: str = \"exec\",\n) -> doc.AST:\n    \"\"\"Parse TVMScript source code str to doc AST.\n\n    Its interface is consistent with python built-in ast.parse.\n    And it will parse by python 3.8 first if possible,\n    or it will parse with python version in current environment.\n\n    Parameters\n    ----------\n    source : str\n        The TVMScript source code.\n\n    filename : str\n        The optional filename of the file where source code locates.\n\n    mode : str\n        The parsing mode for ast.parse.\n\n    Returns\n    -------\n    res : doc.AST\n        The parsed doc AST.\n    \"\"\"\n    try:\n        program = ast.parse(  # pylint: disable=unexpected-keyword-arg\n            source=source,\n            filename=filename,\n            mode=mode,\n            feature_version=(3, 8),\n        )\n    except:  # pylint: disable=bare-except\n        program = ast.parse(\n            source=source,\n            filename=filename,\n            mode=mode,\n        )\n    return to_doc(program)\n\n\nclass NodeVisitor:\n    \"\"\"Node visitor for doc AST\"\"\"\n\n    def visit(self, node: doc.AST) -> None:\n        if isinstance(node, (list, tuple)):\n            for item in node:\n                self.visit(item)\n            return\n        if not isinstance(node, doc.AST):\n            return\n        getattr(\n            self,\n            \"visit_\" + node.__class__.__name__.split(\".\")[-1],\n            self.generic_visit,\n        )(node)\n\n    def generic_visit(self, node: doc.AST) -> None:\n        for field in node.__class__._FIELDS:  # pylint: disable=protected-access\n            value = getattr(node, field, None)\n            if value is None:\n                pass\n            elif isinstance(value, (doc.AST, list, tuple)):\n                self.visit(value)\n\n\nclass NodeTransformer:\n    \"\"\"Node transformer for doc AST\"\"\"\n\n    def visit(self, node: doc.AST) -> doc.AST:\n        if isinstance(node, list):\n            return [self.visit(item) for item in node]\n        if isinstance(node, tuple):\n            return tuple(self.visit(item) for item in node)\n        if not isinstance(node, doc.AST):\n            return node\n        return getattr(\n            self,\n            \"visit_\" + node.__class__.__name__.split(\".\")[-1],\n            self.generic_visit,\n        )(node)\n\n    def generic_visit(self, node: doc.AST) -> doc.AST:\n        kv: typing.Dict[str, typing.Any] = {}\n        for field in node.__class__._FIELDS:  # pylint: disable=protected-access\n            value = getattr(node, field, None)\n            if value is None:\n                pass\n            elif isinstance(value, (doc.AST, list, tuple)):\n                value = self.visit(value)\n            kv[field] = value\n        return node.__class__(**kv)\n\n\ndef _register_default():\n    class DefaultTranslator:\n        def __init__(self, doc_cls, func, fields):\n            self.doc_cls = doc_cls  # getattr(doc, name)\n            self.func = func\n            self.fields = fields\n\n        def __call__(self, node):\n            kv = {attr: self.func(getattr(node, attr, None)) for attr in self.fields}\n            return self.doc_cls(**kv)\n\n    Registry._inst = Registry()  # pylint: disable=protected-access\n    for cls_name in dir(doc):\n        doc_cls = getattr(doc, cls_name)\n        if not hasattr(ast, cls_name):\n            continue\n        if inspect.isclass(doc_cls) and issubclass(doc_cls, doc.AST):\n            assert \".\" not in cls_name\n            register_to_doc(cls_name)(\n                DefaultTranslator(\n                    getattr(doc, cls_name),\n                    to_doc,\n                    doc_cls._FIELDS,  # pylint: disable=protected-access\n                )\n            )\n            register_from_doc(cls_name)(\n                DefaultTranslator(\n                    getattr(ast, cls_name),\n                    from_doc,\n                    doc_cls._FIELDS,  # pylint: disable=protected-access\n                )\n            )\n\n\ndef _py_version() -> typing.Tuple[int, int]:\n    return (sys.version_info.major, sys.version_info.minor)\n\n\ndef _register_constant_handling():\n    if _py_version() not in [(3, 6), (3, 7)]:\n        return\n\n    def as_constant(f) -> doc.Constant:\n        def to_doc_func(x: ast.AST) -> doc.Constant:\n            return doc.Constant(\n                value=getattr(x, f) if isinstance(f, str) else f(x),\n                kind=None,\n                s=None,\n                n=None,\n                lineno=x.lineno,\n                col_offset=x.col_offset,\n                end_lineno=x.lineno,\n                end_col_offset=x.col_offset,\n            )\n\n        return to_doc_func\n\n    register_to_doc(\"Str\")(as_constant(\"s\"))\n    register_to_doc(\"NameConstant\")(as_constant(\"value\"))\n    register_to_doc(\"Num\")(as_constant(\"n\"))\n    register_to_doc(\"Bytes\")(as_constant(\"s\"))\n    register_to_doc(\"Ellipsis\")(as_constant(lambda _: ...))\n\n\ndef _register_subscription_handling():\n    if _py_version() >= (3, 9):\n        return\n\n    def subscript_to_doc(x: ast.Subscript) -> doc.Subscript:\n        if isinstance(x.slice, ast.Slice):\n            return doc.Subscript(\n                value=to_doc(x.value),\n                slice=doc.Slice(\n                    lower=to_doc(x.slice.lower),\n                    upper=to_doc(x.slice.upper),\n                    step=to_doc(x.slice.step),\n                    lineno=getattr(x.slice, \"lineno\", None),\n                    col_offset=getattr(x.slice, \"col_offset\", None),\n                    end_lineno=getattr(x.slice, \"end_lineno\", None),\n                    end_col_offset=getattr(x.slice, \"end_col_offset\", None),\n                ),\n                ctx=to_doc(x.ctx),\n                lineno=getattr(x, \"lineno\", None),\n                col_offset=getattr(x, \"col_offset\", None),\n                end_lineno=getattr(x, \"end_lineno\", None),\n                end_col_offset=getattr(x, \"end_col_offset\", None),\n            )\n        if isinstance(x.slice, ast.ExtSlice):\n            return doc.Subscript(\n                value=to_doc(x.value),\n                slice=doc.Tuple(\n                    elts=[to_doc(i) for i in x.slice.dims],\n                    ctx=doc.Load(\n                        lineno=None,\n                        col_offset=None,\n                        end_lineno=None,\n                        end_col_offset=None,\n                    ),\n                    lineno=getattr(x, \"lineno\", None),\n                    col_offset=getattr(x, \"col_offset\", None),\n                    end_lineno=getattr(x, \"end_lineno\", None),\n                    end_col_offset=getattr(x, \"end_col_offset\", None),\n                ),\n                ctx=to_doc(x.ctx),\n                lineno=getattr(x, \"lineno\", None),\n                col_offset=getattr(x, \"col_offset\", None),\n                end_lineno=getattr(x, \"end_lineno\", None),\n                end_col_offset=getattr(x, \"end_col_offset\", None),\n            )\n        if isinstance(x.slice, ast.Index):\n            return doc.Subscript(\n                value=to_doc(x.value),\n                slice=to_doc(x.slice.value),\n                ctx=to_doc(x.ctx),\n                lineno=getattr(x, \"lineno\", None),\n                col_offset=getattr(x, \"col_offset\", None),\n                end_lineno=getattr(x, \"end_lineno\", None),\n                end_col_offset=getattr(x, \"end_col_offset\", None),\n            )\n        raise TypeError(f\"Unknown subscript type: {type(x.slice)}\")\n\n    def subscript_from_doc(x: doc.Subscript) -> ast.Subscript:\n        if isinstance(x.slice, doc.Slice):\n            result = ast.Subscript(\n                value=from_doc(x.value),\n                slice=from_doc(x.slice),\n                ctx=from_doc(x.ctx),\n            )\n        elif isinstance(x.slice, doc.Tuple):\n            result = ast.Subscript(\n                value=from_doc(x.value),\n                slice=ast.ExtSlice(\n                    dims=[from_doc(i) for i in x.slice.elts],\n                ),\n                ctx=from_doc(x.ctx),\n            )\n        else:\n            result = ast.Subscript(\n                value=from_doc(x.value),\n                slice=ast.Index(value=from_doc(x.slice)),\n                ctx=from_doc(x.ctx),\n            )\n        result.lineno = x.lineno\n        result.col_offset = x.col_offset\n        result.end_lineno = x.end_lineno\n        result.end_col_offset = x.end_col_offset\n        return result\n\n    register_to_doc(\"Subscript\")(subscript_to_doc)\n    register_from_doc(\"Subscript\")(subscript_from_doc)\n\n\ndef _register_index_handling():\n    if _py_version() >= (3, 9):\n        return\n\n    def index_to_doc(x: ast.Index) -> doc.Expr:\n        return to_doc(x.value)\n\n    def index_from_doc(x: doc.Expr) -> ast.Index:\n        result = ast.Index(value=from_doc(x), ctx=from_doc(x.ctx))\n        result.lineno = x.lineno\n        result.col_offset = x.col_offset\n        result.end_lineno = x.end_lineno\n        result.end_col_offset = x.end_col_offset\n        return result\n\n    register_to_doc(\"Index\")(index_to_doc)\n    register_from_doc(\"Index\")(index_from_doc)\n\n\n_register_default()\n_register_constant_handling()\n_register_subscription_handling()\n_register_index_handling()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/doc_core.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-outer-name,missing-docstring,invalid-name\n# pylint: disable=useless-super-delegation,redefined-builtin\n# pylint: disable=too-few-public-methods,too-many-arguments\nclass AST:\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__()\n        self.lineno = lineno\n        self.col_offset = col_offset\n        self.end_lineno = end_lineno\n        self.end_col_offset = end_col_offset\n\n\nclass mod(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Module(mod):\n    _FIELDS = [\"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.body = body\n\n\nclass Interactive(mod):\n    _FIELDS = [\"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.body = body\n\n\nclass Expression(mod):\n    _FIELDS = [\"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.body = body\n\n\nclass stmt(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass FunctionDef(stmt):\n    _FIELDS = [\n        \"name\",\n        \"args\",\n        \"body\",\n        \"decorator_list\",\n        \"returns\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self,\n        name,\n        args,\n        body,\n        decorator_list,\n        returns,\n        lineno,\n        col_offset,\n        end_lineno,\n        end_col_offset,\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.name = name\n        self.args = args\n        self.body = body\n        self.decorator_list = decorator_list\n        self.returns = returns\n\n\nclass ClassDef(stmt):\n    _FIELDS = [\n        \"name\",\n        \"bases\",\n        \"keywords\",\n        \"body\",\n        \"decorator_list\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self,\n        name,\n        bases,\n        keywords,\n        body,\n        decorator_list,\n        lineno,\n        col_offset,\n        end_lineno,\n        end_col_offset,\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.name = name\n        self.bases = bases\n        self.keywords = keywords\n        self.body = body\n        self.decorator_list = decorator_list\n\n\nclass Return(stmt):\n    _FIELDS = [\"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n\n\nclass Delete(stmt):\n    _FIELDS = [\"targets\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, targets, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.targets = targets\n\n\nclass Assign(stmt):\n    _FIELDS = [\"targets\", \"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, targets, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.targets = targets\n        self.value = value\n\n\nclass AugAssign(stmt):\n    _FIELDS = [\"target\", \"op\", \"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, target, op, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.target = target\n        self.op = op\n        self.value = value\n\n\nclass AnnAssign(stmt):\n    _FIELDS = [\n        \"target\",\n        \"annotation\",\n        \"value\",\n        \"simple\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self, target, annotation, value, simple, lineno, col_offset, end_lineno, end_col_offset\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.target = target\n        self.annotation = annotation\n        self.value = value\n        self.simple = simple\n\n\nclass For(stmt):\n    _FIELDS = [\n        \"target\",\n        \"iter\",\n        \"body\",\n        \"orelse\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(self, target, iter, body, orelse, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.target = target\n        self.iter = iter\n        self.body = body\n        self.orelse = orelse\n\n\nclass While(stmt):\n    _FIELDS = [\"test\", \"body\", \"orelse\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, test, body, orelse, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.test = test\n        self.body = body\n        self.orelse = orelse\n\n\nclass If(stmt):\n    _FIELDS = [\"test\", \"body\", \"orelse\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, test, body, orelse, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.test = test\n        self.body = body\n        self.orelse = orelse\n\n\nclass With(stmt):\n    _FIELDS = [\"items\", \"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, items, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.items = items\n        self.body = body\n\n\nclass Raise(stmt):\n    _FIELDS = [\"exc\", \"cause\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, exc, cause, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.exc = exc\n        self.cause = cause\n\n\nclass Try(stmt):\n    _FIELDS = [\n        \"body\",\n        \"handlers\",\n        \"orelse\",\n        \"finalbody\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self, body, handlers, orelse, finalbody, lineno, col_offset, end_lineno, end_col_offset\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.body = body\n        self.handlers = handlers\n        self.orelse = orelse\n        self.finalbody = finalbody\n\n\nclass Assert(stmt):\n    _FIELDS = [\"test\", \"msg\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, test, msg, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.test = test\n        self.msg = msg\n\n\nclass Import(stmt):\n    _FIELDS = [\"names\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, names, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.names = names\n\n\nclass ImportFrom(stmt):\n    _FIELDS = [\"module\", \"names\", \"level\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, module, names, level, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.module = module\n        self.names = names\n        self.level = level\n\n\nclass Global(stmt):\n    _FIELDS = [\"names\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, names, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.names = names\n\n\nclass Nonlocal(stmt):\n    _FIELDS = [\"names\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, names, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.names = names\n\n\nclass Expr(stmt):\n    _FIELDS = [\"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n\n\nclass Pass(stmt):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Break(stmt):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Continue(stmt):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass expr(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass BoolOp(expr):\n    _FIELDS = [\"op\", \"values\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, op, values, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.op = op\n        self.values = values\n\n\nclass BinOp(expr):\n    _FIELDS = [\"left\", \"op\", \"right\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, left, op, right, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.left = left\n        self.op = op\n        self.right = right\n\n\nclass UnaryOp(expr):\n    _FIELDS = [\"op\", \"operand\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, op, operand, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.op = op\n        self.operand = operand\n\n\nclass Lambda(expr):\n    _FIELDS = [\"args\", \"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, args, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.args = args\n        self.body = body\n\n\nclass IfExp(expr):\n    _FIELDS = [\"test\", \"body\", \"orelse\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, test, body, orelse, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.test = test\n        self.body = body\n        self.orelse = orelse\n\n\nclass Dict(expr):\n    _FIELDS = [\"keys\", \"values\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, keys, values, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.keys = keys\n        self.values = values\n\n\nclass Set(expr):\n    _FIELDS = [\"elts\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elts, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elts = elts\n\n\nclass ListComp(expr):\n    _FIELDS = [\"elt\", \"generators\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elt, generators, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elt = elt\n        self.generators = generators\n\n\nclass SetComp(expr):\n    _FIELDS = [\"elt\", \"generators\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elt, generators, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elt = elt\n        self.generators = generators\n\n\nclass DictComp(expr):\n    _FIELDS = [\"key\", \"value\", \"generators\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, key, value, generators, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.key = key\n        self.value = value\n        self.generators = generators\n\n\nclass GeneratorExp(expr):\n    _FIELDS = [\"elt\", \"generators\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elt, generators, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elt = elt\n        self.generators = generators\n\n\nclass Yield(expr):\n    _FIELDS = [\"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n\n\nclass YieldFrom(expr):\n    _FIELDS = [\"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n\n\nclass Compare(expr):\n    _FIELDS = [\"left\", \"ops\", \"comparators\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, left, ops, comparators, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.left = left\n        self.ops = ops\n        self.comparators = comparators\n\n\nclass Call(expr):\n    _FIELDS = [\"func\", \"args\", \"keywords\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, func, args, keywords, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.func = func\n        self.args = args\n        self.keywords = keywords\n\n\nclass FormattedValue(expr):\n    _FIELDS = [\n        \"value\",\n        \"conversion\",\n        \"format_spec\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self, value, conversion, format_spec, lineno, col_offset, end_lineno, end_col_offset\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n        self.conversion = conversion\n        self.format_spec = format_spec\n\n\nclass JoinedStr(expr):\n    _FIELDS = [\"values\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, values, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.values = values\n\n\nclass Constant(expr):\n    _FIELDS = [\"value\", \"kind\", \"s\", \"n\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, kind, s, n, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n        self.kind = kind\n        self.s = s\n        self.n = n\n\n\nclass NamedExpr(expr):\n    _FIELDS = [\"target\", \"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, target, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.target = target\n        self.value = value\n\n\nclass Attribute(expr):\n    _FIELDS = [\"value\", \"attr\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, attr, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n        self.attr = attr\n        self.ctx = ctx\n\n\nclass slice(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Slice(slice):\n    _FIELDS = [\"lower\", \"upper\", \"step\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lower, upper, step, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.lower = lower\n        self.upper = upper\n        self.step = step\n\n\nclass ExtSlice(slice):\n    _FIELDS = [\"dims\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, dims, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.dims = dims\n\n\nclass Index(slice):\n    _FIELDS = [\"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n\n\nclass Subscript(expr):\n    _FIELDS = [\"value\", \"slice\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, slice, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n        self.slice = slice\n        self.ctx = ctx\n\n\nclass Starred(expr):\n    _FIELDS = [\"value\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, value, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.value = value\n        self.ctx = ctx\n\n\nclass Name(expr):\n    _FIELDS = [\"id\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, id, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.id = id\n        self.ctx = ctx\n\n\nclass List(expr):\n    _FIELDS = [\"elts\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elts, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elts = elts\n        self.ctx = ctx\n\n\nclass Tuple(expr):\n    _FIELDS = [\"elts\", \"ctx\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, elts, ctx, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.elts = elts\n        self.ctx = ctx\n\n\nclass expr_context(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass AugLoad(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass AugStore(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Param(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Suite(mod):\n    _FIELDS = [\"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.body = body\n\n\nclass Del(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Load(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Store(expr_context):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass boolop(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass And(boolop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Or(boolop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass operator(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Add(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass BitAnd(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass BitOr(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass BitXor(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Div(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass FloorDiv(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass LShift(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Mod(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Mult(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass MatMult(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Pow(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass RShift(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Sub(operator):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass unaryop(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Invert(unaryop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Not(unaryop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass UAdd(unaryop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass USub(unaryop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass cmpop(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Eq(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Gt(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass GtE(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass In(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Is(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass IsNot(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass Lt(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass LtE(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass NotEq(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass NotIn(cmpop):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass comprehension(AST):\n    _FIELDS = [\n        \"target\",\n        \"iter\",\n        \"ifs\",\n        \"is_async\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(self, target, iter, ifs, is_async, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.target = target\n        self.iter = iter\n        self.ifs = ifs\n        self.is_async = is_async\n\n\nclass excepthandler(AST):\n    _FIELDS = [\"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n\n\nclass ExceptHandler(excepthandler):\n    _FIELDS = [\"type\", \"name\", \"body\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, type, name, body, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.type = type\n        self.name = name\n        self.body = body\n\n\nclass arguments(AST):\n    _FIELDS = [\n        \"args\",\n        \"vararg\",\n        \"kwonlyargs\",\n        \"kw_defaults\",\n        \"kwarg\",\n        \"defaults\",\n        \"posonlyargs\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(\n        self,\n        args,\n        vararg,\n        kwonlyargs,\n        kw_defaults,\n        kwarg,\n        defaults,\n        posonlyargs,\n        lineno,\n        col_offset,\n        end_lineno,\n        end_col_offset,\n    ):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.args = args\n        self.vararg = vararg\n        self.kwonlyargs = kwonlyargs\n        self.kw_defaults = kw_defaults\n        self.kwarg = kwarg\n        self.defaults = defaults\n        self.posonlyargs = posonlyargs\n\n\nclass arg(AST):\n    _FIELDS = [\"arg\", \"annotation\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, arg, annotation, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.arg = arg\n        self.annotation = annotation\n\n\nclass keyword(AST):\n    _FIELDS = [\"arg\", \"value\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, arg, value, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.arg = arg\n        self.value = value\n\n\nclass alias(AST):\n    _FIELDS = [\"name\", \"asname\", \"lineno\", \"col_offset\", \"end_lineno\", \"end_col_offset\"]\n\n    def __init__(self, name, asname, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.name = name\n        self.asname = asname\n\n\nclass withitem(AST):\n    _FIELDS = [\n        \"context_expr\",\n        \"optional_vars\",\n        \"lineno\",\n        \"col_offset\",\n        \"end_lineno\",\n        \"end_col_offset\",\n    ]\n\n    def __init__(self, context_expr, optional_vars, lineno, col_offset, end_lineno, end_col_offset):\n        super().__init__(lineno, col_offset, end_lineno, end_col_offset)\n        self.context_expr = context_expr\n        self.optional_vars = optional_vars\n\n\n__all__ = [\n    \"AST\",\n    \"mod\",\n    \"Module\",\n    \"Interactive\",\n    \"Expression\",\n    \"stmt\",\n    \"FunctionDef\",\n    \"ClassDef\",\n    \"Return\",\n    \"Delete\",\n    \"Assign\",\n    \"AugAssign\",\n    \"AnnAssign\",\n    \"For\",\n    \"While\",\n    \"If\",\n    \"With\",\n    \"Raise\",\n    \"Try\",\n    \"Assert\",\n    \"Import\",\n    \"ImportFrom\",\n    \"Global\",\n    \"Nonlocal\",\n    \"Expr\",\n    \"Pass\",\n    \"Break\",\n    \"Continue\",\n    \"expr\",\n    \"BoolOp\",\n    \"BinOp\",\n    \"UnaryOp\",\n    \"Lambda\",\n    \"IfExp\",\n    \"Dict\",\n    \"Set\",\n    \"ListComp\",\n    \"SetComp\",\n    \"DictComp\",\n    \"GeneratorExp\",\n    \"Yield\",\n    \"YieldFrom\",\n    \"Compare\",\n    \"Call\",\n    \"FormattedValue\",\n    \"JoinedStr\",\n    \"Constant\",\n    \"NamedExpr\",\n    \"Attribute\",\n    \"slice\",\n    \"Slice\",\n    \"ExtSlice\",\n    \"Index\",\n    \"Subscript\",\n    \"Starred\",\n    \"Name\",\n    \"List\",\n    \"Tuple\",\n    \"expr_context\",\n    \"AugLoad\",\n    \"AugStore\",\n    \"Param\",\n    \"Suite\",\n    \"Del\",\n    \"Load\",\n    \"Store\",\n    \"boolop\",\n    \"And\",\n    \"Or\",\n    \"operator\",\n    \"Add\",\n    \"BitAnd\",\n    \"BitOr\",\n    \"BitXor\",\n    \"Div\",\n    \"FloorDiv\",\n    \"LShift\",\n    \"Mod\",\n    \"Mult\",\n    \"MatMult\",\n    \"Pow\",\n    \"RShift\",\n    \"Sub\",\n    \"unaryop\",\n    \"Invert\",\n    \"Not\",\n    \"UAdd\",\n    \"USub\",\n    \"cmpop\",\n    \"Eq\",\n    \"Gt\",\n    \"GtE\",\n    \"In\",\n    \"Is\",\n    \"IsNot\",\n    \"Lt\",\n    \"LtE\",\n    \"NotEq\",\n    \"NotIn\",\n    \"comprehension\",\n    \"excepthandler\",\n    \"ExceptHandler\",\n    \"arguments\",\n    \"arg\",\n    \"keyword\",\n    \"alias\",\n    \"withitem\",\n]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/entry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The entry point of TVM parser.\"\"\"\n\nfrom typing import Any, Dict, Union\n\nfrom ...ir_builder import IRBuilder\nfrom . import doc\nfrom .diagnostics import Source\nfrom .parser import Parser\n\n\ndef parse(program: Union[doc.AST, Any, str], extra_vars: Dict[str, Any] = None) -> Any:\n    \"\"\"Register a method for a operand type, AST operator node and operand index.\n\n    Parameters\n    ----------\n    program : Union[doc.AST, Any, str]\n        The TVMScript code to parse.\n\n    extra_vars : Dict[str, Any]\n        The extra variable table for parsing.\n\n    Returns\n    -------\n    func : Any\n        The parsed TVMScript program.\n    \"\"\"\n    if extra_vars is None:\n        from tvm.script.parser import ir  # pylint: disable=import-outside-toplevel\n        from tvm.script.parser import tir  # pylint: disable=import-outside-toplevel\n\n        extra_vars = {\n            \"I\": ir,\n            \"ir\": ir,\n            \"T\": tir,\n            \"tir\": tir,\n        }\n\n    source = Source(program)\n    parser = Parser(source)\n    with IRBuilder() as builder:\n        parser.parse(extra_vars=extra_vars)\n    return builder.get()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/evaluator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"AST Evaluation\"\"\"\n\nimport ast\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union\n\nfrom . import dispatch, doc\n\nif TYPE_CHECKING:\n    from .parser import Parser\n\nDEFAULT_OP: Dict[Type, Callable[..., Any]] = {\n    doc.Add: lambda a, b: a + b,\n    doc.Sub: lambda a, b: a - b,\n    doc.Mult: lambda a, b: a * b,\n    doc.Div: lambda a, b: a / b,\n    doc.FloorDiv: lambda a, b: a // b,\n    doc.Mod: lambda a, b: a % b,\n    doc.LShift: lambda a, b: a << b,\n    doc.RShift: lambda a, b: a >> b,\n    doc.BitOr: lambda a, b: a | b,\n    doc.BitXor: lambda a, b: a ^ b,\n    doc.BitAnd: lambda a, b: a & b,\n    doc.MatMult: lambda a, b: a @ b,\n    doc.Pow: lambda a, b: a**b,\n    doc.Eq: lambda a, b: a == b,\n    doc.NotEq: lambda a, b: a != b,\n    doc.Lt: lambda a, b: a < b,\n    doc.LtE: lambda a, b: a <= b,\n    doc.Gt: lambda a, b: a > b,\n    doc.GtE: lambda a, b: a >= b,\n    doc.Is: lambda a, b: a is b,\n    doc.IsNot: lambda a, b: a is not b,\n    doc.In: lambda a, b: a in b,\n    doc.NotIn: lambda a, b: a not in b,\n    doc.And: lambda a, b: a and b,\n    doc.Or: lambda a, b: a or b,\n    doc.Invert: lambda a: ~a,\n    doc.Not: lambda a: not a,\n    doc.UAdd: lambda a: +a,\n    doc.USub: lambda a: -a,\n}\n\n\nclass ExprEvaluator:\n    \"\"\"Expression evaluator for TVMScript parser.\n\n    Parameters\n    ----------\n    parser : Parser\n        The parser bound with the evaluator.\n\n    value_table : Dict[str, Any]\n        The value table for expression evaluation.\n\n    new_value_count : int\n        The count for ntermediate result added during evaluation.\n    \"\"\"\n\n    parser: \"Parser\"\n    value_table: Dict[str, Any]\n    new_value_count: int\n\n    def __init__(self, parser: \"Parser\", value_table: Dict[str, Any]) -> None:\n        super().__init__()\n        self.parser = parser\n        self.value_table = value_table\n        self.new_value_count = 0\n\n    @staticmethod\n    def eval(parser: \"Parser\", value_table: Dict[str, Any], node: doc.AST) -> Any:\n        \"\"\"Expression evaluation for TVMScript parser.\n\n        Parameters\n        ----------\n        parser : Parser\n            The parser bound with the evaluator.\n\n        value_table : Dict[str, Any]\n            The value table for expression evaluation.\n\n        node : doc.AST\n            The root node of AST tree node of expression to evaluate.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        self = ExprEvaluator(parser, value_table)\n        result = self._visit(node)  # pylint: disable=protected-access\n        if isinstance(result, doc.Name):\n            if result.id not in self.value_table:\n                self.parser.report_error(result, f\"Undefined variable: {result.id}\")\n            return self.value_table[result.id]\n        if isinstance(result, doc.Constant):\n            return result.value\n        raise TypeError(f\"Unexpected result type: {type(result)}\")\n\n    def _add_intermediate_result(self, value: Any) -> doc.Name:\n        \"\"\"Add intermediate result during evaluation into value table.\n\n        Parameters\n        ----------\n        value : Any\n            The intermediate result.\n\n        Returns\n        -------\n        name : doc.Name\n            The doc AST name node with intermediate name for intermediate result.\n        \"\"\"\n        name = f\"__tvm_tmp_value_{self.new_value_count}\"\n        self.new_value_count += 1\n        self.value_table[name] = value\n        lineno = 0\n        col_offset = 0\n        return doc.Name(\n            id=name,\n            ctx=doc.Load(\n                lineno=lineno,\n                col_offset=col_offset,\n                end_lineno=None,\n                end_col_offset=None,\n            ),\n            lineno=lineno,\n            col_offset=col_offset,\n            end_lineno=None,\n            end_col_offset=None,\n        )\n\n    def _visit(self, node: doc.AST) -> Any:\n        \"\"\"General doc AST node visiting method for expression evaluation.\n\n        Parameters\n        ----------\n        node : doc.AST\n            The root node of AST tree node of expression to evaluate.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        if isinstance(node, list):\n            return [self._visit(n) for n in node]\n        if isinstance(node, tuple):\n            return tuple(self._visit(n) for n in node)\n        assert isinstance(node, doc.AST)\n        if isinstance(node, doc.Name):\n            if node.id not in self.value_table:\n                self.parser.report_error(node, f\"Undefined variable: {node.id}\")\n            return node\n        if isinstance(\n            node,\n            (\n                doc.Constant,\n                doc.expr_context,\n                doc.operator,\n                doc.boolop,\n                doc.unaryop,\n                doc.cmpop,\n            ),\n        ):\n            return node\n        if not isinstance(node, (doc.expr, doc.slice)):\n            return node\n        if isinstance(node, doc.Lambda):\n            return self._eval_lambda(node)\n        fields = {}\n        for field in node.__class__._FIELDS:  # pylint: disable=protected-access\n            attr = getattr(node, field)\n            if isinstance(attr, (doc.AST, tuple, list)):\n                fields[field] = self._visit(attr)\n            else:\n                fields[field] = attr\n        try:\n            if isinstance(node, doc.BoolOp):\n                value = self._eval_bool_op(fields)\n            elif isinstance(node, doc.Compare):\n                value = self._eval_compare(fields)\n            elif isinstance(node, doc.UnaryOp):\n                value = self._eval_unary_op(fields)\n            elif isinstance(node, doc.BinOp):\n                value = self._eval_bin_op(fields)\n            elif isinstance(node, doc.Slice):\n                value = self._eval_slice(fields)\n            else:\n                value = self._eval_expr(node.__class__(**fields))\n        except Exception as e:  # pylint: disable=broad-except,invalid-name\n            self.parser.report_error(node, str(e))\n        return self._add_intermediate_result(value)\n\n    def _eval_lambda(self, node: doc.Lambda) -> Any:\n        \"\"\"The doc AST lambda node evaluating method.\n\n        Parameters\n        ----------\n        node : doc.Lambda\n            The root node of AST tree node of expression to evaluate.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        try:\n            value = self._eval_expr(node)\n        except Exception as e:  # pylint: disable=broad-except,invalid-name\n            self.parser.report_error(node, str(e))\n        return self._add_intermediate_result(value)\n\n    def _eval_bool_op(self, fields: Dict[str, Any]) -> Any:\n        \"\"\"The doc AST boolean operator node evaluating method.\n\n        Parameters\n        ----------\n        fields : Dict[str, Any]\n            The dictionary of boolean operation information,\n            e.g., operator types, operand values.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        op = fields[\"op\"]\n        if not isinstance(op, (doc.And, doc.Or)):\n            raise TypeError(f\"Unexpected operator: {op}\")\n        value = self._eval_expr(fields[\"values\"][0])\n        for rhs in fields[\"values\"][1:]:\n            value = _eval_op(op, values=[value, self._eval_expr(rhs)])\n        return value\n\n    def _eval_compare(self, fields: Dict[str, Any]) -> Any:\n        \"\"\"The doc AST comparison operation node evaluating method.\n\n        Parameters\n        ----------\n        fields : Dict[str, Any]\n            The dictionary of comparison operation information,\n            e.g., operator types, operand values.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        value = self._eval_expr(fields[\"left\"])\n        for op, rhs in zip(fields[\"ops\"], fields[\"comparators\"]):\n            value = _eval_op(op, values=[value, self._eval_expr(rhs)])\n        return value\n\n    def _eval_unary_op(self, fields: Dict[str, Any]) -> Any:\n        \"\"\"The doc AST unary operation node evaluating method.\n\n        Parameters\n        ----------\n        fields : Dict[str, Any]\n            The dictionary of unary operation information,\n            e.g., operator types, operand values.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        value = self._eval_expr(fields[\"operand\"])\n        value = _eval_op(fields[\"op\"], values=[value])\n        return value\n\n    def _eval_bin_op(self, fields: Dict[str, Any]) -> Any:\n        \"\"\"The doc AST binary operation node evaluating method.\n\n        Parameters\n        ----------\n        fields : Dict[str, Any]\n            The dictionary of binary operation information,\n            e.g., operator types, operand values.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        return _eval_op(\n            fields[\"op\"],\n            values=[\n                self._eval_expr(fields[\"left\"]),\n                self._eval_expr(fields[\"right\"]),\n            ],\n        )\n\n    def _eval_slice(self, fields: Dict[str, Any]) -> slice:\n        \"\"\"The doc AST slice node evaluating method.\n\n        Parameters\n        ----------\n        fields : Dict[str, Any]\n            The dictionary of slice information,\n            e.g., lower bound, upper bound, step.\n\n        Returns\n        -------\n        res : slice\n            The evaluation result.\n        \"\"\"\n        lower, upper, step = fields[\"lower\"], fields[\"upper\"], fields[\"step\"]\n\n        lower = self._eval_expr(lower) if lower is not None else None\n        upper = self._eval_expr(upper) if upper is not None else None\n        step = self._eval_expr(step) if step is not None else None\n\n        return slice(lower, upper, step)\n\n    def _eval_expr(self, v: Any) -> Any:\n        \"\"\"The doc AST expression node evaluating method.\n\n        Parameters\n        ----------\n        v : Any\n            The root node of AST tree node of expression to evaluate.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        return _eval_expr(v, self.value_table)\n\n\ndef eval_expr(\n    parser: \"Parser\",\n    node: Union[doc.expr, doc.Expression],\n    dict_globals: Optional[Dict[str, Any]],\n) -> Any:\n    \"\"\"Expression evaluation for TVMScript parser.\n\n    Parameters\n    ----------\n    parser : Parser\n        The parser bound with the evaluator.\n\n    node : Union[doc.expr, doc.Expression]\n        The root node of AST tree node of expression to evaluate.\n\n    dict_globals : Optional[Dict[str, Any]]\n        The optional global value table for expression evaluation.\n\n    Returns\n    -------\n    res : Any\n        The evaluation result.\n    \"\"\"\n    value_table = {}\n    if dict_globals is not None:\n        value_table.update(dict_globals)\n    return ExprEvaluator.eval(parser, value_table, node)\n\n\ndef eval_assign(\n    parser: \"Parser\",\n    target: doc.expr,\n    source: Any,\n) -> Dict[str, Any]:\n    \"\"\"Expression assignment evaluation for TVMScript parser.\n\n    Parameters\n    ----------\n    parser : Parser\n        The parser bound with the evaluator.\n\n    target : doc.expr\n        The root node of AST tree node of assigned expression to evaluate.\n\n    source : Any\n        The source to be assigned with evaluated expression.\n\n    Returns\n    -------\n    res : Any\n        The evaluation result.\n    \"\"\"\n    try:\n        return _eval_assign(target, source)\n    except Exception as e:  # pylint: disable=broad-except,invalid-name\n        parser.report_error(target, f\"Failed to evaluate assignment: {str(e)}\")\n        raise\n\n\ndef _eval_expr(\n    node: Union[doc.expr, doc.Expression],\n    dict_globals: Optional[Dict[str, Any]],\n) -> Any:\n    \"\"\"Expression evaluation implementation for TVMScript parser.\n\n    Parameters\n    ----------\n    node : Union[doc.expr, doc.Expression]\n        The root node of AST tree node of expression to evaluate.\n\n    dict_globals : Optional[Dict[str, Any]]\n        The optional global value table for expression evaluation.\n\n    Returns\n    -------\n    res : Any\n        The evaluation result.\n    \"\"\"\n    node = doc.from_doc(node)\n    if isinstance(node, ast.expr):\n        node = ast.Expression(body=node)\n    assert isinstance(node, ast.Expression), \"Expects an ast.Expression, but gets: \" + str(node)\n    if dict_globals is None:\n        dict_globals = {}\n    node = ast.fix_missing_locations(node)\n    exe = compile(node, filename=\"<ast>\", mode=\"eval\")\n    return eval(exe, dict_globals)  # pylint: disable=eval-used\n\n\ndef _eval_op(\n    op: doc.AST,\n    values: List[Any],\n):\n    \"\"\"Operation expression evaluation implementation for TVMScript parser.\n\n    Parameters\n    ----------\n    op : doc.AST\n        The root node of AST tree node of operation expression to evaluate.\n\n    values : List[Any]\n        The list of values of operands.\n\n    Returns\n    -------\n    res : Any\n        The evaluation result.\n    \"\"\"\n    op_type = type(op)  # pylint: disable=protected-access\n    for i, v in enumerate(values):\n        v_type = getattr(type(v), \"_dispatch_type\", None)\n        if v_type is None:\n            continue\n        f = dispatch.get_op(\n            operand_type=v_type, op_node_type=op_type, operand_index=i, default=None\n        )\n        if f is not None:\n            return f(*values)\n    return DEFAULT_OP[op_type](*values)\n\n\ndef _eval_assign(\n    target: doc.expr,\n    source: Any,\n) -> Dict[str, Any]:\n    \"\"\"Expression assignment evaluation implementation for TVMScript parser.\n\n    Parameters\n    ----------\n    target : doc.expr\n        The root node of AST tree node of assigned expression to evaluate.\n\n    source : Any\n        The source to be assigned with evaluated expression.\n\n    Returns\n    -------\n    res : Any\n        The evaluation result.\n    \"\"\"\n    target = doc.from_doc(target)\n    assert isinstance(target, ast.expr)\n    RHS_VAR_NAME = \"__tvm_rhs_var__\"  # pylint: disable=invalid-name\n    rhs_var_name = RHS_VAR_NAME\n    dict_locals = {rhs_var_name: source}\n    mod = ast.fix_missing_locations(\n        ast.Module(\n            body=[\n                ast.Assign(\n                    targets=[target],\n                    value=ast.Name(\n                        id=rhs_var_name,\n                        ctx=ast.Load(),\n                    ),\n                )\n            ],\n            type_ignores=[],\n        )\n    )\n    exe = compile(mod, filename=\"<ast>\", mode=\"exec\")\n    exec(exe, {}, dict_locals)  # pylint: disable=exec-used\n    del dict_locals[rhs_var_name]\n    return dict_locals\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The core parser\"\"\"\n\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nfrom typing import Any, Callable, Dict, List, Optional, Set, Union\nfrom tvm._ffi.base import TVMError\n\nfrom tvm.error import DiagnosticError\n\nfrom . import dispatch, doc\nfrom .diagnostics import Diagnostics, Source\nfrom .evaluator import eval_assign, eval_expr\n\nDEFAULT_VISIT = {\n    \"Interactive\",\n    \"Module\",\n    \"Expression\",\n    \"Pass\",\n}\n\n\ndef _deferred(exit_f: Callable[[], None]):\n    \"\"\"Created context with certain exit function.\n\n    Parameters\n    ----------\n    exit_f : Callable[[], None]\n        The function to call when exiting the context.\n\n    Returns\n    -------\n    res : Any\n        The created context.\n    \"\"\"\n\n    @contextmanager\n    def context():\n        try:\n            yield\n        finally:\n            exit_f()\n\n    return context()\n\n\nclass VarTableFrame:\n    \"\"\"The variable table frame.\n    A frame of variable table stores the variables created in one block or scope.\n\n    Parameters\n    ----------\n    vars : Set[str]\n        The set of variable names in the variable table frame.\n    \"\"\"\n\n    vars: Set[str]\n\n    def __init__(self):\n        self.vars = set()\n\n    def add(self, var: str):\n        \"\"\"Add a new variable into variable table frame.\n\n        Parameters\n        ----------\n        var : str\n            The name of new variable.\n        \"\"\"\n        if var in self.vars:\n            raise ValueError(f\"Variable {var} already defined in current scope\")\n        self.vars.add(var)\n\n    def pop_all(self, fn_pop: Callable[[str], None]):\n        \"\"\"Pop out all variable in variable table frame.\n\n        Parameters\n        ----------\n        fn_pop : Callable[[str], None]\n            The methods to call when popping each variable.\n        \"\"\"\n        for var in self.vars:\n            fn_pop(var)\n        self.vars.clear()\n\n\nclass VarTable:\n    \"\"\"The variable table.\n    A variable table stores the all variables when parsing TVMScript.\n\n    Parameters\n    ----------\n    frames : List[VarTableFrame]\n        The list or stack of variable table frame.\n\n    name2value : Dict[str, List[Any]]\n        The dictionary for variable table name-based query.\n    \"\"\"\n\n    frames: List[VarTableFrame]\n    name2value: Dict[str, List[Any]]\n\n    def __init__(self):\n        self.frames = []\n        self.name2value = defaultdict(list)\n\n    def with_frame(self):\n        \"\"\"Create a new variable table frame as with statement.\n\n        Returns\n        -------\n        res : Any\n            The context with new variable table frame.\n        \"\"\"\n\n        def pop_frame():\n            frame = self.frames.pop()\n            frame.pop_all(lambda name: self.name2value[name].pop())\n\n        self.frames.append(VarTableFrame())\n        return _deferred(pop_frame)\n\n    def add(self, var: str, value: Any, allow_shadowing: bool = False):\n        \"\"\"Add a new variable to variable table.\n\n        Parameters\n        ----------\n        var : str\n            The name of variable.\n\n        value : Any\n            The value of variable.\n\n        allow_shadowing : bool\n            The options of whether variable shadowing allwed for this variable.\n        \"\"\"\n        # Skip if the key and value are equal to those in the var_table\n        if self.name2value[var] and self.name2value[var][-1] == value:\n            return\n        if allow_shadowing and var in self.frames[-1].vars:\n            # Shadowing\n            self.name2value[var][-1] = value\n        else:\n            self.frames[-1].add(var)\n            self.name2value[var].append(value)\n\n    def get(self) -> Dict[str, Any]:\n        \"\"\"Get a variable dictionary of latest variables.\n\n        Returns\n        -------\n        res : Any\n            The variable dictionary copy of latest variables.\n        \"\"\"\n        return {key: values[-1] for key, values in self.name2value.items() if values}\n\n    def exist(self, value: Any) -> bool:\n        \"\"\"Check if any value exists in variable table.\n\n        Parameters\n        ----------\n        value : Any\n            The value of variable.\n\n        Returns\n        -------\n        res : bool\n            The existence of the value.\n        \"\"\"\n        for v in self.name2value.values():\n            if v is value:\n                return True\n        return False\n\n\ndef _dispatch_wrapper(func: dispatch.ParseMethod) -> dispatch.ParseMethod:\n    def _wrapper(self: \"Parser\", node: doc.AST) -> None:\n        try:\n            return func(self, node)\n        except DiagnosticError:\n            raise\n        except Exception as e:  # pylint: disable=broad-except,invalid-name\n            self.report_error(node, e)\n            raise\n\n    return _wrapper\n\n\ndef _dispatch(self: \"Parser\", type_name: str) -> dispatch.ParseMethod:\n    for token in [self.dispatch_tokens[-1], \"default\"]:\n        func = dispatch.get(token=token, type_name=type_name, default=None)\n        if func is not None:\n            return _dispatch_wrapper(func)\n    return _dispatch_wrapper(lambda self, node: self.generic_visit(node))\n\n\nclass Parser(doc.NodeVisitor):\n    \"\"\"The TVMScript parser\n\n    Parameters\n    ----------\n    diag : Diagnostics\n        The diagnostics for error reporting.\n\n    dispatch_tokens : List[str]\n        The list of dispatching tokens to dispatching parsing method\n        of different IRs and different doc AST structure.\n\n    var_table : VarTable\n        The variable table for parsing.\n    \"\"\"\n\n    diag: Diagnostics\n    dispatch_tokens: List[str]\n    var_table: VarTable\n\n    def __init__(self, source: Source) -> None:\n        self.diag = Diagnostics(source)\n        self.dispatch_tokens = [\"default\"]\n        self.var_table = VarTable()\n\n    def parse(self, extra_vars: Optional[Dict[str, Any]] = None) -> Any:\n        \"\"\"The main parse method for parser.\n\n        Parameters\n        ----------\n        extra_vars : Optional[Dict[str, Any]]\n            The optional global value table for parsing.\n\n        Returns\n        -------\n        res : Any\n            The doc AST node visiting result.\n        \"\"\"\n        if extra_vars is None:\n            extra_vars = {}\n        with self.var_table.with_frame():\n            for k, v in extra_vars.items():\n                self.var_table.add(k, v)\n            node = self.diag.source.as_ast()\n            self.visit(node)\n\n    def with_dispatch_token(self, token: str):\n        \"\"\"Add a new dispatching token as with statement.\n\n        Parameters\n        ----------\n        token : str\n            The dispathing token.\n\n        Returns\n        -------\n        res : Any\n            The context with new dispatching token.\n        \"\"\"\n\n        def pop_token():\n            self.dispatch_tokens.pop()\n\n        self.dispatch_tokens.append(token)\n        return _deferred(pop_token)\n\n    def eval_expr(\n        self,\n        node: Union[doc.Expression, doc.expr],\n        extra_vars: Optional[Dict[str, Any]] = None,\n    ) -> Any:\n        \"\"\"Expression evaluation when parsing.\n\n        Parameters\n        ----------\n        node : Union[doc.expr, doc.Expression]\n            The root node of AST tree node of expression to evaluate.\n\n        extra_vars : Optional[Dict[str, Any]]\n            The optional global value table for expression evaluation.\n\n        Returns\n        -------\n        res : Any\n            The evaluation result.\n        \"\"\"\n        var_values = self.var_table.get()\n        if extra_vars is not None:\n            for k, v in extra_vars.items():\n                var_values[k] = v\n        return eval_expr(self, node, var_values)\n\n    def _duplicate_lhs_check(self, target: doc.expr) -> Union[bool, Set[str]]:\n        \"\"\"Check whether duplicate lhs exists in assignment.\n\n        Parameters\n        ----------\n        target : doc.expr\n            The doc AST expr node for lhs.\n\n        Returns\n        -------\n        res : Union[bool, Set[str]]\n            The result of true if duplicate lhs exists,\n            or the set of lhs names if no duplicate lhs exists.\n        \"\"\"\n        if isinstance(target, (doc.Tuple, doc.List)):\n            vars: Set[str] = set()  # pylint: disable=redefined-builtin\n            for i in target.elts:\n                res = self._duplicate_lhs_check(i)\n                if isinstance(res, bool) and res:\n                    return True\n                assert isinstance(res, set)\n                if vars & res:\n                    return True\n                vars = vars.union(res)\n            return vars\n        elif isinstance(target, doc.Name):\n            return {target.id}\n        else:\n            self.report_error(target, \"Invalid type in assign statement\")\n            raise NotImplementedError\n\n    def eval_assign(\n        self,\n        target: doc.expr,\n        source: Any,\n        bind_value: Callable[[\"Parser\", doc.expr, str, Any], Any],\n        allow_shadowing: bool = False,\n    ) -> Dict[str, Any]:\n        \"\"\"Expression assignment evaluation when parsing.\n\n        Parameters\n        ----------\n        target : doc.expr\n            The root node of AST tree node of assigned expression to evaluate.\n\n        source : Any\n            The source to be assigned with evaluated expression.\n\n        bind_value : Callable[[\"Parser\", doc.expr, str, Any], Any]\n            The value binding method when assigning the values to variables.\n\n        allow_shadowing : bool\n            The options of whether variable shadowing allwed for assignment.\n\n        Returns\n        -------\n        res : Dict[str, Any]\n            The dirctionary of assignment result.\n        \"\"\"\n        if self._duplicate_lhs_check(target) is True:\n            self.report_error(target, \"Duplicate vars assigned.\")\n        var_values = eval_assign(self, target, source)\n        for k, v in var_values.items():\n            var = bind_value(self, target, k, v)\n            self.var_table.add(k, var, allow_shadowing)\n        return var_values\n\n    def report_error(\n        self, node: doc.AST, err: Union[Exception, str]\n    ) -> None:  # pylint: disable=no-self-use\n        \"\"\"The error reporting when parsing.\n\n        Parameters\n        ----------\n        node : doc.AST\n            The doc AST node with errors.\n\n        err: Union[Exception, str]\n            The error to report.\n        \"\"\"\n        # Only take the last line of the error message\n        if isinstance(err, TVMError):\n            msg = list(filter(None, str(err).split(\"\\n\")))[-1]\n        else:\n            msg = str(err)\n        self.diag.error(node, msg)\n\n    def visit(self, node: doc.AST) -> None:\n        \"\"\"The general visiting method.\n\n        Parameters\n        ----------\n        node : doc.AST\n            The doc AST node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        if isinstance(node, (list, tuple)):\n            for item in node:\n                self.visit(item)\n            return\n        if not isinstance(node, doc.AST):\n            return\n        name = node.__class__.__name__.split(\".\")[-1]\n        if name in DEFAULT_VISIT:\n            func = self.generic_visit\n        else:\n            func = getattr(self, \"visit_\" + name, None)\n        if func is None:\n            raise NotImplementedError(f\"Visitor of AST node is not implemented: {name}\")\n        try:\n            func(node)\n        except DiagnosticError:\n            raise\n        except Exception as e:  # pylint: disable=broad-except,invalid-name\n            self.report_error(node, str(e))\n            raise\n\n    def visit_body(self, node: List[doc.stmt]) -> Any:\n        \"\"\"The general body visiting method.\n\n        Parameters\n        ----------\n        node : List[doc.stmt]\n            The list of statements in body.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        for stmt in node:\n            self.visit(stmt)\n\n    def visit_tvm_annotation(self, node: doc.expr) -> Any:\n        \"\"\"The general TVM annotation visiting method.\n\n        Parameters\n        ----------\n        node : doc.expr\n            The doc AST expr node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"tvm_annotation\")(self, node)\n\n    def visit_FunctionDef(self, node: doc.FunctionDef) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general function definition visiting method.\n\n        Parameters\n        ----------\n        node : doc.FunctionDef\n            The doc AST function definition node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        if not node.decorator_list:\n            self.report_error(node, \"Function must be decorated\")\n        # TODO: only the last decorator is parsed\n        decorator = self.eval_expr(node.decorator_list[-1])\n        if not hasattr(decorator, \"dispatch_token\"):\n            self.report_error(node, \"The parser does not understand the decorator\")\n        token = decorator.dispatch_token\n        func = dispatch.get(token=token, type_name=\"FunctionDef\", default=None)\n        if func is None:\n            self.report_error(node, \"The parser does not understand the decorator\")\n        _dispatch_wrapper(func)(self, node)\n\n    def visit_ClassDef(self, node: doc.ClassDef) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general class definition visiting method.\n\n        Parameters\n        ----------\n        node : doc.ClassDef\n            The doc AST class definition node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        func = dispatch.get(token=\"ir\", type_name=\"ClassDef\", default=None)\n        if func is None:\n            self.report_error(node, \"The parser does not understand the decorator\")\n        _dispatch_wrapper(func)(self, node)\n\n    def visit_arguments(self, node: doc.arguments) -> Any:\n        \"\"\"The general arguments visiting method.\n\n        Parameters\n        ----------\n        node : doc.arguments\n            The doc AST arguments node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"arguments\")(self, node)\n\n    def visit_For(self, node: doc.For) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general for visiting method.\n\n        Parameters\n        ----------\n        node : doc.For\n            The doc AST for node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"For\")(self, node)\n\n    def visit_While(self, node: doc.While) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general while visiting method.\n\n        Parameters\n        ----------\n        node : doc.While\n            The doc AST while node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"While\")(self, node)\n\n    def visit_With(self, node: doc.With) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general with visiting method.\n\n        Parameters\n        ----------\n        node : doc.With\n            The doc AST with node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"With\")(self, node)\n\n    def visit_Assign(self, node: doc.Assign) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general assign visiting method.\n\n        Parameters\n        ----------\n        node : doc.Assign\n            The doc AST assign node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"Assign\")(self, node)\n\n    def visit_AnnAssign(self, node: doc.AnnAssign) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general annotated assign visiting method.\n\n        Parameters\n        ----------\n        node : doc.Assign\n            The doc AST annotated assign node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"AnnAssign\")(self, node)\n\n    def visit_Expr(self, node: doc.Expr) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general expression visiting method.\n\n        Parameters\n        ----------\n        node : doc.Expr\n            The doc AST exprssion node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"Expr\")(self, node)\n\n    def visit_If(self, node: doc.If) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general if visiting method.\n\n        Parameters\n        ----------\n        node : doc.If\n            The doc AST if node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"If\")(self, node)\n\n    def visit_AugAssign(self, node: doc.AugAssign) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general augmented assignment visiting method.\n\n        Parameters\n        ----------\n        node : doc.AugAssign\n            The doc AST augmented assignment node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"AugAssign\")(self, node)\n\n    def visit_Assert(self, node: doc.Assert) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general assert visiting method.\n\n        Parameters\n        ----------\n        node : doc.Assert\n            The doc AST assert node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"Assert\")(self, node)\n\n    def visit_Return(self, node: doc.Return) -> Any:  # pylint: disable=invalid-name\n        \"\"\"The general return visiting method.\n\n        Parameters\n        ----------\n        node : doc.Return\n            The doc AST return node.\n\n        Returns\n        -------\n        res : Any\n            The visiting result.\n        \"\"\"\n        return _dispatch(self, \"Return\")(self, node)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/core/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser utils\"\"\"\n\nimport inspect\nfrom types import FrameType\nfrom typing import Any, Callable, Dict, List\n\nfrom .diagnostics import findsource\n\n\ndef inspect_function_capture(func: Callable) -> Dict[str, Any]:\n    \"\"\"Capture function non-locals and global variables.\n\n    Parameters\n    ----------\n    func : Callable\n        The function to inspect.\n\n    Returns\n    -------\n    res : Dict[str, Any]\n        The function variables map with non-local or global variables.\n    \"\"\"\n    captured = {\n        **inspect.getclosurevars(func).nonlocals,\n        **func.__globals__,  # type: ignore\n    }\n    return captured\n\n\ndef inspect_class_capture(cls: type) -> Dict[str, Any]:\n    \"\"\"Capture class non-locals and global variables.\n\n    Parameters\n    ----------\n    cls : type\n        The class to inspect.\n\n    Returns\n    -------\n    res : Dict[str, Any]\n        The class variables map with non-local or global variables.\n    \"\"\"\n    result: Dict[str, Any] = {}\n    for _, v in cls.__dict__.items():\n        if inspect.isfunction(v):\n            func_vars = inspect_function_capture(v)\n            result.update(**func_vars)\n    return result\n\n\ndef is_defined_in_class(frames: List[FrameType], obj: Any) -> bool:\n    \"\"\"Check whether a object is defined in a class scope.\n\n    Parameters\n    ----------\n    frames : List[FrameType]\n        The frame stack of the object, obtained by `inspect.stack()`.\n\n    Returns\n    -------\n    res : bool\n        The result if the object is defined in a class scope.\n    \"\"\"\n    if len(frames) > 2:\n        frame_info = frames[2]\n        code_context = frame_info.code_context\n        if code_context is None:\n            return False\n        line = code_context[0].strip()\n        if line.startswith(\"@\") and \"ir_module\" in line:\n            return True\n        if line.startswith(\"class\"):\n            lineno = frame_info.lineno\n            if lineno >= 2:\n                source, _ = findsource(obj)\n                line = source[lineno - 2].strip()\n                if line.startswith(\"@\") and \"ir_module\" in line:\n                    return True\n    return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/ir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The ir module parser\"\"\"\n\nfrom . import parser as _parser\nfrom .entry import ir_module\n\n__all__ = [\"ir_module\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/ir/entry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The entry point of TVM parser for ir module.\"\"\"\n\nimport inspect\nfrom typing import Type\n\nfrom tvm.ir import IRModule\n\nfrom .._core import parse, utils\n\n\ndef ir_module(mod: Type) -> IRModule:\n    \"\"\"The parsing method for ir module, by using `@ir_module` as decorator.\n\n    Parameters\n    ----------\n    mod : Type\n        The class to be parsed as ir module.\n\n    Returns\n    -------\n    ir_module : IRModule\n        The parsed ir module.\n    \"\"\"\n    if not inspect.isclass(mod):\n        raise TypeError(f\"Expect a class, but got: {mod}\")\n\n    return parse(mod, utils.inspect_class_capture(mod))\n\n\nsetattr(ir_module, \"dispatch_token\", \"ir\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/ir/parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The base parser for ir module\"\"\"\n\nfrom ...ir_builder import ir as I\nfrom .._core import Parser, dispatch, doc\n\n\n@dispatch.register(token=\"ir\", type_name=\"ClassDef\")\ndef _visit_class_def(self: Parser, node: doc.ClassDef) -> None:\n    \"\"\"The class definition visiting method for ir module.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.ClassDef\n        The doc AST class definition node.\n    \"\"\"\n    with self.var_table.with_frame():\n        with I.ir_module():\n            with self.with_dispatch_token(\"ir\"):\n                self.visit_body(node.body)\n\n\n@dispatch.register(token=\"ir\", type_name=\"Assign\")\ndef _visit_assign(_self: Parser, _node: doc.Assign) -> None:\n    \"\"\"The assign visiting method for ir module.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.ClassDef\n        The doc AST assign node.\n    \"\"\"\n\n\n@dispatch.register(token=\"ir\", type_name=\"Expr\")\ndef _visit_expr(_self: Parser, _node: doc.Expr) -> None:\n    \"\"\"The expression visiting method for ir module.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.ClassDef\n        The doc AST expression node.\n    \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/tir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The tir parser\"\"\"\n\nfrom ...ir_builder.tir import *  # pylint: disable=redefined-builtin\nfrom ...ir_builder.tir import ir as _tir\nfrom . import operation as _operation\nfrom . import parser as _parser\nfrom .entry import Buffer, Ptr, prim_func\n\n__all__ = _tir.__all__ + [\"Buffer\", \"Ptr\", \"prim_func\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/tir/entry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The entry point of TVM parser for tir.\"\"\"\nimport inspect\nfrom typing import Callable, Union\n\nfrom tvm.tir import Buffer, PrimFunc\n\nfrom ...ir_builder.tir import buffer_decl, ptr\nfrom .._core import parse, utils\n\n\ndef prim_func(func: Callable) -> Union[PrimFunc, Callable]:\n    \"\"\"The parsing method for tir prim func, by using `@prim_func` as decorator.\n\n    Parameters\n    ----------\n    func : Callable\n        The function to be parsed as prim func.\n\n    Returns\n    -------\n    res : Union[PrimFunc, Callable]\n        The parsed tir prim func.\n    \"\"\"\n    if not inspect.isfunction(func):\n        raise TypeError(f\"Expect a function, but got: {func}\")\n    if utils.is_defined_in_class(inspect.stack(), func):\n        return func\n    return parse(func, utils.inspect_function_capture(func))\n\n\nsetattr(prim_func, \"dispatch_token\", \"tir\")\n\n\nclass BufferProxy:\n    \"\"\"Buffer proxy class for constructing tir buffer.\n    Overload __call__ and __getitem__ to support syntax as T.Buffer() and T.Buffer[].\n    \"\"\"\n\n    def __call__(\n        self,\n        shape,\n        dtype=None,\n        data=None,\n        strides=None,\n        elem_offset=None,\n        scope=\"global\",\n        align=0,\n        offset_factor=0,\n        buffer_type=\"\",\n        axis_separators=None,\n    ) -> Buffer:\n        if dtype is None:\n            raise ValueError(\"Data type must be specified when constructing buffer\")\n        return buffer_decl(\n            shape,\n            dtype=dtype,\n            data=data,\n            strides=strides,\n            elem_offset=elem_offset,\n            scope=scope,\n            align=align,\n            offset_factor=offset_factor,\n            buffer_type=buffer_type,\n            axis_separators=axis_separators,\n        )\n\n    def __getitem__(self, keys) -> Buffer:\n        if not isinstance(keys, tuple):\n            return self(keys)\n        if len(keys) >= 2 and not isinstance(keys[1], str):\n            return self(keys)\n        return self(*keys)  # pylint: disable=no-member # type: ignore\n\n\nclass PtrProxy:\n    \"\"\"Ptr proxy class for constructing tir pointer.\n    Overload __call__ and __getitem__ to support syntax as T.Ptr() and T.Ptr[].\n    \"\"\"\n\n    def __call__(self, dtype, storage_scope=\"global\"):\n        if callable(dtype):\n            dtype = dtype().dtype\n        return ptr(dtype, storage_scope)  # pylint: disable=no-member # type: ignore\n\n    def __getitem__(self, keys):\n        if not isinstance(keys, tuple):\n            return self(keys)\n        return self(*keys)\n\n\nBuffer = BufferProxy()  # pylint: disable=invalid-name\nPtr = PtrProxy()  # pylint: disable=invalid-name\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/tir/operation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The tir expression operation registration\"\"\"\n\nfrom typing import Type\n\nfrom tvm import tir\nfrom tvm.tir import IntImm\n\nfrom .._core import OpMethod, doc, register_op\n\n\ndef _register_expr_op(ty: Type):  # pylint: disable=invalid-name\n    ty._dispatch_type = ty  # pylint: disable=protected-access\n\n    def _and(a, b):\n        if isinstance(a, bool):\n            a = IntImm(\"bool\", a)\n        if isinstance(b, bool):\n            b = IntImm(\"bool\", b)\n        return tir.And(a, b)\n\n    def _or(a, b):\n        if isinstance(a, bool):\n            a = IntImm(\"bool\", a)\n        if isinstance(b, bool):\n            b = IntImm(\"bool\", b)\n        return tir.Or(a, b)\n\n    def r(op: Type, i: int, m: OpMethod):  # pylint: disable=invalid-name\n        register_op(ty, op, i)(m)\n\n    for i in [0, 1]:\n        # Case 1. binop\n        r(doc.Add, i, tir.Add)\n        r(doc.Sub, i, tir.Sub)\n        r(doc.Mult, i, tir.Mul)\n        r(doc.Div, i, tir.Div)\n        r(doc.FloorDiv, i, tir.FloorDiv)\n        r(doc.Mod, i, tir.FloorMod)\n        r(doc.LShift, i, lambda a, b: a << b)\n        r(doc.RShift, i, lambda a, b: a >> b)\n        r(doc.BitOr, i, lambda a, b: a | b)\n        r(doc.BitXor, i, lambda a, b: a ^ b)\n        r(doc.BitAnd, i, lambda a, b: a & b)\n        # doc.MatMult <-- not implemented\n        # doc.Pow <-- not implemented\n        # Case 2. cmpop\n        r(doc.Eq, i, tir.EQ)\n        r(doc.NotEq, i, tir.NE)\n        r(doc.Lt, i, tir.LT)\n        r(doc.LtE, i, tir.LE)\n        r(doc.Gt, i, tir.GT)\n        r(doc.GtE, i, tir.GE)\n        # doc.Is <-- not implemented\n        # doc.IsNot <-- not implemented\n        # doc.In <-- not implemented\n        # doc.NotIn <-- not implemented\n        # Case 3. boolop\n        r(doc.And, i, _and)\n        r(doc.Or, i, _or)\n    for i in [0]:\n        #  Case 4. unaryop\n        r(doc.Invert, i, lambda a: ~a)\n        r(doc.Not, i, tir.Not)\n        r(doc.UAdd, i, lambda a: +a)\n        r(doc.USub, i, lambda a: -a)\n\n\n_register_expr_op(tir.PrimExpr)\n_register_expr_op(tir.IterVar)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser/tir/parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The base parser for tir\"\"\"\n\nimport contextlib\nfrom functools import partial\nfrom typing import Any\n\nfrom tvm.ir import PrimType\nfrom tvm.tir import Buffer, IterVar, PrimExpr, Var\n\nfrom ...ir_builder import tir as T\nfrom ...ir_builder.base import IRBuilder\nfrom ...ir_builder.base import IRBuilderFrame as Frame\nfrom .._core import Parser, dispatch, doc\n\n\ndef bind_with_value(self: Parser, node: doc.expr, var_name: str, value: Any) -> Any:\n    \"\"\"Value binding methods when parsing with statement.\n    e.g. binding i, j, k with T.grid(128, 128, 128), when parsing\n        with T.grid(128, 128, 18) as i, j, k.\n\n    Parameters\n    ----------\n    self : Parser\n        The current parser.\n\n    node : doc.expr\n        The doc AST expression node for error reporting.\n\n    var_name : str\n        The variable name.\n\n    value : Any\n        The value to be bound with.\n\n    Returns\n    -------\n    res : Any\n        The bound value.\n    \"\"\"\n    if isinstance(value, (list, tuple)):\n        for i, v in enumerate(value):\n            bind_with_value(self, node, f\"{var_name}_{i}\", v)\n        return value\n    elif isinstance(value, (Buffer, Var)):\n        IRBuilder.name(var_name, value)\n        return value\n    else:\n        self.report_error(node, f\"Do not know how to bind type: {type(value)} in with statement\")\n        raise NotImplementedError\n\n\ndef bind_for_value(self: Parser, node: doc.expr, var_name: str, value: Any) -> Any:\n    \"\"\"Value binding methods when parsing for statement.\n    e.g. binding i, j, k with T.grid(128, 128, 128), when parsing\n        for i, j, k in T.grid(128, 128, 128).\n\n    Parameters\n    ----------\n    self : Parser\n        The current parser.\n\n    node : doc.expr\n        The doc AST expression node for error reporting.\n\n    var_name : str\n        The variable name.\n\n    value : Any\n        The value to be bound with.\n\n    Returns\n    -------\n    res : Any\n        The bound value.\n    \"\"\"\n    if isinstance(value, (list, tuple)):\n        for i, v in enumerate(value):\n            bind_for_value(self, node, f\"{var_name}_{i}\", v)\n        return value\n    elif isinstance(value, Var):\n        IRBuilder.name(var_name, value)\n        return value\n    else:\n        self.report_error(node, f\"Do not know how to bind type: {type(value)} in for statement\")\n        raise NotImplementedError\n\n\ndef bind_assign_value(self: Parser, node: doc.expr, var_name: str, value: Any) -> Any:\n    \"\"\"Value binding methods when parsing assign statement.\n    e.g. binding vi, vj, vk with T.axis.remap(\"SSR\", [i, j, k]), when parsing\n        vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k]).\n\n    Parameters\n    ----------\n    self : Parser\n        The current parser.\n\n    node : doc.expr\n        The doc AST expression node for error reporting.\n\n    var_name : str\n        The variable name.\n\n    value : Any\n        The value to be bound with.\n\n    Returns\n    -------\n    res : Any\n        The bound value.\n    \"\"\"\n    if isinstance(value, T.meta_var):\n        return value.value\n    elif isinstance(value, (list, tuple)):\n        for i, v in enumerate(value):\n            bind_assign_value(self, node, f\"{var_name}_{i}\", v)\n        return value\n    elif isinstance(value, Frame):\n        value.add_callback(partial(value.__exit__, None, None, None))\n        res = value.__enter__()\n        IRBuilder.name(var_name, res)\n        return res\n    elif isinstance(value, (Buffer, IterVar)) or (\n        isinstance(value, Var) and not self.var_table.exist(value)\n    ):\n        IRBuilder.name(var_name, value)\n        return value\n    elif isinstance(value, PrimExpr):\n        var = T.var(value.dtype)\n        IRBuilder.name(var_name, var)\n        frame = T.let(var, value)\n        frame.add_callback(partial(frame.__exit__, None, None, None))\n        frame.__enter__()\n        return var\n    return value\n\n\n@dispatch.register(token=\"tir\", type_name=\"For\")\ndef visit_for(self: Parser, node: doc.For) -> None:\n    \"\"\"The for visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.For\n        The doc AST for node.\n    \"\"\"\n    for_frame = self.eval_expr(node.iter)\n    if not isinstance(for_frame, T.frame.ForFrame):\n        self.report_error(\n            node.iter,\n            \"Expect the for loop to be one of the following: \"\n            \"range, T.serial, T.grid, T.parallel, T.vectorized, T.unroll, T.thread_binding\",\n        )\n    with self.var_table.with_frame():\n        with for_frame as iters:\n            self.eval_assign(target=node.target, source=iters, bind_value=bind_for_value)\n            self.visit_body(node.body)\n\n\n@dispatch.register(token=\"tir\", type_name=\"While\")\ndef visit_while(self: Parser, node: doc.While) -> None:\n    \"\"\"The while visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.While\n        The doc AST while node.\n    \"\"\"\n    with self.var_table.with_frame():\n        cond = self.eval_expr(node.test)\n        with T.While(cond):\n            self.visit_body(node.body)\n\n\n@dispatch.register(token=\"tir\", type_name=\"Assign\")\ndef visit_assign(self: Parser, node: doc.Assign) -> None:\n    \"\"\"The assign visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.Assign\n        The doc AST assign node.\n    \"\"\"\n    if len(node.targets) != 1:\n        self.report_error(node, \"Consequential assignments like 'a = b = c' are not supported.\")\n    lhs = node.targets[0]\n    rhs = self.eval_expr(node.value)\n    if isinstance(lhs, doc.Subscript):\n        if isinstance(lhs.slice, doc.Tuple):\n            indices = []\n            for index in lhs.slice.elts:\n                indices.append(self.eval_expr(index))\n        else:\n            indices = [self.eval_expr(lhs.slice)]\n        T.buffer_store(self.eval_expr(lhs.value), rhs, indices)\n    else:\n        self.eval_assign(target=lhs, source=rhs, bind_value=bind_assign_value)\n\n\n@dispatch.register(token=\"tir\", type_name=\"AugAssign\")\ndef visit_aug_assign(self: Parser, node: doc.AugAssign) -> None:\n    \"\"\"The augmented assign visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.AugAssign\n        The doc AST augmented assign node.\n    \"\"\"\n    lhs_pos = (\n        node.target.lineno,\n        node.target.col_offset,\n        node.target.end_lineno,\n        node.target.end_col_offset,\n    )\n    rhs_pos = (\n        node.value.lineno,\n        node.value.col_offset,\n        node.value.end_lineno,\n        node.value.end_col_offset,\n    )\n    node.target.ctx = doc.Load(*lhs_pos)\n    with self.var_table.with_frame():\n        lhs_name = \"__tvm_tmp_value_aug_assign_lhs\"\n        rhs_name = \"__tvm_tmp_value_aug_assign_rhs\"\n        lhs_expr = self.eval_expr(node.target)\n        rhs_expr = self.eval_expr(node.value)\n        self.var_table.add(lhs_name, lhs_expr)\n        self.var_table.add(rhs_name, rhs_expr)\n        op = doc.BinOp(\n            doc.Name(lhs_name, doc.Load(*lhs_pos), *lhs_pos),\n            node.op,\n            doc.Name(rhs_name, doc.Load(*rhs_pos), *rhs_pos),\n            *lhs_pos,\n        )\n        rhs = self.eval_expr(op)\n    lhs = node.target\n    lhs.ctx = doc.Store(*lhs_pos)\n    if isinstance(lhs, doc.Subscript):\n        if isinstance(lhs.slice, doc.Tuple):\n            indices = []\n            for index in lhs.slice.elts:\n                indices.append(self.eval_expr(index))\n        else:\n            indices = [self.eval_expr(lhs.slice)]\n        T.buffer_store(self.eval_expr(lhs.value), rhs, indices)\n    else:\n        self.eval_assign(target=lhs, source=rhs, bind_value=bind_assign_value)\n\n\n@dispatch.register(token=\"tir\", type_name=\"AnnAssign\")\ndef visit_ann_assign(self: Parser, node: doc.AnnAssign) -> None:\n    \"\"\"The annotated assign visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.AnnAssign\n        The doc AST annotated assign node.\n    \"\"\"\n    lhs = node.target\n    rhs = self.eval_expr(node.value)\n    ann_var = self.visit_tvm_annotation(node.annotation)\n    if not isinstance(ann_var, Var):\n        self.report_error(node.annotation, \"Annotation should be Var\")\n    self.eval_assign(target=lhs, source=ann_var, bind_value=bind_assign_value)\n    frame = T.let(ann_var, rhs)\n    frame.add_callback(partial(frame.__exit__, None, None, None))\n    frame.__enter__()\n\n\n@dispatch.register(token=\"tir\", type_name=\"With\")\ndef visit_with(self: Parser, node: doc.With) -> None:\n    \"\"\"The with visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.With\n        The doc AST with node.\n    \"\"\"\n    with contextlib.ExitStack() as stack:\n        stack.enter_context(self.var_table.with_frame())\n        for item in node.items:\n            frame = self.eval_expr(item.context_expr)\n            if not isinstance(frame, Frame):\n                self.report_error(\n                    item.context_expr, \"Invalid context expression in the with-statement.\"\n                )\n            rhs = stack.enter_context(frame)\n            if item.optional_vars is not None:\n                self.eval_assign(target=item.optional_vars, source=rhs, bind_value=bind_with_value)\n        self.visit_body(node.body)\n\n\n@dispatch.register(token=\"tir\", type_name=\"FunctionDef\")\ndef visit_function_def(self: Parser, node: doc.FunctionDef) -> None:\n    \"\"\"The function definition visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.FunctionDef\n        The doc AST function definition node.\n    \"\"\"\n    with self.var_table.with_frame():\n        self.var_table.add(\"range\", T.serial)\n        with T.prim_func():\n            T.func_name(node.name)\n            if node.returns is not None:\n                ret_type = self.eval_expr(node.returns)\n                if callable(ret_type):\n                    ret_type = PrimType(ret_type().dtype)\n                T.func_ret(ret_type)\n            with self.with_dispatch_token(\"tir\"):\n                self.visit(node.args)\n                self.visit_body(node.body)\n\n\n@dispatch.register(token=\"tir\", type_name=\"arguments\")\ndef visit_arguments(self: Parser, node: doc.arguments) -> None:\n    \"\"\"The arguments visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.arguments\n        The doc AST arguments node.\n    \"\"\"\n    # TODO: handle different types of arguments:\n    # - vararg: arg | None\n    # - kwonlyargs: list[arg]\n    # - kw_defaults: list[expr | None]\n    # - kwarg: arg | None\n    # - defaults: list[expr]\n    # - posonlyargs: list[arg]\n    arg: doc.arg\n    for arg in node.args:\n        if arg.annotation is None:\n            self.report_error(arg, \"Type annotation is required for function parameters.\")\n        param = T.arg(arg.arg, self.visit_tvm_annotation(arg.annotation))\n        self.var_table.add(arg.arg, param)\n\n\n@dispatch.register(token=\"tir\", type_name=\"tvm_annotation\")\ndef visit_tvm_annotation(self: Parser, node: doc.expr):\n    \"\"\"The TVM annotation visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.expr\n        The doc AST expr node.\n    \"\"\"\n    annotation = self.eval_expr(node)\n    if callable(annotation):\n        annotation = annotation()\n    return annotation\n\n\n@dispatch.register(token=\"tir\", type_name=\"Expr\")\ndef visit_expr_stmt(self: Parser, node: doc.Expr) -> None:\n    \"\"\"The expr statement visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.Expr\n        The doc AST Expr node.\n    \"\"\"\n    res = self.eval_expr(node.value)\n    if isinstance(res, Frame):\n        res.add_callback(partial(res.__exit__, None, None, None))\n        res.__enter__()\n\n\n@dispatch.register(token=\"tir\", type_name=\"If\")\ndef visit_if(self: Parser, node: doc.If) -> None:\n    \"\"\"The if visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.If\n        The doc AST if node.\n    \"\"\"\n    with self.var_table.with_frame():\n        with T.If(self.eval_expr(node.test)):\n            with T.Then():\n                self.visit_body(node.body)\n            if node.orelse:\n                with T.Else():\n                    self.visit_body(node.orelse)\n\n\n@dispatch.register(token=\"tir\", type_name=\"Assert\")\ndef visit_assert(self: Parser, node: doc.Assert) -> None:\n    \"\"\"The assert visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.Assert\n        The doc AST assert node.\n    \"\"\"\n    cond = self.eval_expr(node.test)\n    msg = self.eval_expr(node.msg)\n    frame = T.Assert(cond, msg)\n    frame.add_callback(partial(frame.__exit__, None, None, None))\n    frame.__enter__()\n\n\n@dispatch.register(token=\"tir\", type_name=\"Return\")\ndef visit_return(self: Parser, node: doc.Return) -> None:\n    \"\"\"The return visiting method for tir.\n\n    Parameters\n    ----------\n    self : Parser\n        The visiting parser.\n\n    node : doc.Return\n        The doc AST return node.\n    \"\"\"\n    self.report_error(node, \"Return is not allowed.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script APIs of TVM Python Package, aimed to support TIR\"\"\"\n\nfrom . import tir\n\nfrom .parser import ir_module, from_source\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.script\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"script\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/context_maintainer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Context Maintainer for TIR\"\"\"\n\nfrom typing import List, Mapping, Union, Optional, Dict, Callable\nimport synr\n\n\nimport tvm\nfrom tvm.ir import Span\nfrom tvm.ir.expr import Range\nfrom tvm.tir import Var, Buffer, PrimExpr, Stmt, MatchBufferRegion\nfrom tvm.runtime import Object\nfrom tvm.tir.expr import IterVar\nfrom .tir.node import BufferSlice\n\n\nclass BlockInfo:\n    \"\"\"Information for block and block_realize signature\n\n    Examples\n    ----------\n    .. code-block:: python\n\n        @T.prim_func\n        def example_func(a: T.handle, b: T.handle, c: T.handle) -> None:\n            A = T.match_buffer(a, (16, 16), \"float32\")\n            B = T.match_buffer(b, (16, 16), \"float32\")\n            C = T.match_buffer(a, (16, 16), \"float32\")\n\n            for i, j, k in T.grid(16, 16, 16):\n                with T.block(\"matmul\"):\n                    vi = T.axis.S(16, i)\n                    vj = T.axis.S(16, j)\n                    vk = T.axis.R(16, k)         # iter_bindings = {vj: i, vj: j, vk: k}\n\n                    T.where(True)         # predicate of the block_realize\n\n                    T.reads(A[0:16, 0:16], B[0: 16, 0: 16])      # reads region of the block\n                    T.writes(C[0: 16, 0: 16])                    # writes region of the block\n                    T.block_attr({\"attr_key\": \"attr_value\"})     # block annotations\n\n                    # alloc_buffers inside the block\n                    CC = T.alloc_buffer((1, 1), dtype=\"float32\")\n\n                    # match_buffers of the block,\n                    # which bind a sub-region of source buffer into a new buffer\n                    D = T.match_buffer(C[vi, vj], ())\n\n                    # init part of the block, executed when all reduce axes are the beginning value\n                    with T.init():\n                        C[vi, vj] = T.float32(0)\n\n                    # block body\n                    CC[0, 0] = A[vi, vk] * B[vj, vk]\n                    D[()] += CC[0, 0]         # The same as C[vi, vj] += CC[0, 0]\n    \"\"\"\n\n    alloc_buffers: List[Buffer] = []\n    \"\"\"List[Buffer]: list of T.alloc_buffer statements in the block signature\"\"\"\n    match_buffers: List[MatchBufferRegion] = []\n    \"\"\"List[MatchBufferRegion]: list of T.match_buffer statements in the block signature\"\"\"\n    iter_values: List[PrimExpr] = []\n    \"\"\"List[PrimExpr]: list of binding values for iter vars\"\"\"\n    iter_vars: List[IterVar] = []\n    \"\"\"List[PrimExpr]: list of iter vars in the block\"\"\"\n    reads: Optional[List[BufferSlice]] = None\n    \"\"\"Optional[List[BufferSlice]]:\n    list of T.reads statements in the block signature, None for not-visited\"\"\"\n    writes: Optional[List[BufferSlice]] = None\n    \"\"\"Optional[List[BufferSlice]]:\n    list of T.writes statements in the block signature, None for not-visited\"\"\"\n    annotations: Optional[Mapping[str, Object]] = None\n    \"\"\"Optional[Mapping[str, Object]]:\n    list of T.block_attr statements in the block signature, None for not-visited\"\"\"\n    predicate: Optional[PrimExpr] = None\n    \"\"\"Optional[PrimExpr]: block realize predicate, None for not-visited\"\"\"\n    init: Optional[Stmt] = None\n    \"\"\"Optional[Stmt]: init part of the block, None for not-visited\"\"\"\n\n    def __init__(self):\n        self.alloc_buffers = []\n        self.match_buffers = []\n        self.iter_values = []\n        self.iter_vars = []\n        self.reads = None\n        self.writes = None\n        self.annotations = None\n        self.predicate = None\n        self.init = None\n\n\nclass ContextMaintainer:\n    \"\"\"Maintain all the necessary context info\n    Parameters\n    ----------\n    _report_error : Callable[[str, Union[Span, synr.ast.Span]], None]\n        The report error function handle\n    \"\"\"\n\n    # scope context\n    node_stack: List[List[synr.ast.Node]] = []\n    \"\"\"List[List[synr.ast.Node]]: The ast nodes insides the current scope\"\"\"\n    block_info_stack: List[BlockInfo] = []\n    \"\"\"List[BlockInfo]: The block info for the current block scope\"\"\"\n    loop_stack: Dict[Var, Range] = {}\n    \"\"\"Dict[Var, Range]: The dict from loop var to its domain outside the block\"\"\"\n    symbols: List[Dict[str, Union[Var, Buffer]]] = []\n    \"\"\"List[Dict[str, Union[Var, Buffer]]]: Symbol map from name to object for the current scope\"\"\"\n    closure_vars: Dict[str, Object] = {}\n    \"\"\"ClosureVars: The closure vars defined in Python interpreter\"\"\"\n\n    # function context\n    func_params: List[Var] = []\n    \"\"\"List[Var]: The function parameters\"\"\"\n    func_buffer_map: Mapping[Var, Buffer] = {}\n    \"\"\"Mapping[Var, Buffer]: The function buffer map\"\"\"\n    func_preflattened_buffer_map: Mapping[Var, Buffer] = {}\n    \"\"\"Mapping[Var, Buffer]: The function buffer map, prior to any flattening.\"\"\"\n    func_dict_attr: Mapping[str, Object] = {}\n    \"\"\"Mapping[str, Object]: The function attrs\"\"\"\n    func_var_env_dict: Mapping[Var, str] = {}\n    \"\"\"Mapping[Var, str]: The map from var to env thread\"\"\"\n\n    # parser and analyzer\n    analyzer: tvm.arith.Analyzer = tvm.arith.Analyzer()\n    \"\"\"tvm.arith.Analyzer: The analyzer for simplifying\"\"\"\n    _report_error: Callable[[str, Union[Span, synr.ast.Span]], None]\n    \"\"\"Callable[[str, Union[Span, synr.ast.Span]], None]: The report error function handle\"\"\"\n\n    # root alloc_buffer\n    root_alloc_buffers: List[Buffer] = []\n    \"\"\"List[Buffer]: The buffers allocated under root block\"\"\"\n\n    def __init__(\n        self,\n        _report_error: Callable[[str, Union[Span, synr.ast.Span]], None],\n        closure_vars: Dict[str, Object],\n    ):\n        # scope context\n        self.node_stack = []\n        self.block_info_stack = []\n        self.loop_stack = {}\n        self.symbols = []\n        self.closure_vars = closure_vars\n        # function context\n        self.func_params = []\n        self.func_buffer_map = {}\n        self.func_preflattened_buffer_map = {}\n        self.func_dict_attr = {}\n        self.func_var_env_dict = {}\n        # parser and analyzer\n        self._report_error = _report_error\n        self.analyzer = tvm.arith.Analyzer()\n        # root alloc_buffer\n        self.root_alloc_buffers = []\n\n    def enter_scope(self, nodes: Optional[List[synr.ast.Node]] = None):\n        \"\"\"Creates a new scope\n\n        Note\n        ----\n        This function is used for normal scopes that do not involve\n        a `with block` scope. Use `enter_block_scope`\n        for block scope cases.\n\n        Parameters\n        ----------\n        nodes : Optional[List[synr.ast.Node]]\n            The synr AST nodes in new scope\n        \"\"\"\n        if nodes is None:\n            nodes = []\n        self.node_stack.append(list(reversed(nodes)))\n        self.symbols.append(dict())\n\n    def enter_block_scope(self, nodes: Optional[List[synr.ast.Node]] = None):\n        \"\"\"Creates a new block scope, the function will call `enter_scope` implicitly\n        Besides the behaviors of `enter_scope`, it will update loop_stack and block_info_stack\n        to maintain block info.\n\n        Note\n        ----\n        This function should be used to handle a block scope,\n        aka the blocks that involve a `with block` scope.\n\n        Parameters\n        ----------\n        nodes : Optional[List[synr.ast.Node]]\n            The synr AST nodes in new scope\n        \"\"\"\n        self.enter_scope(nodes)\n        # Create a new BlockInfo for the new block\n        self.block_info_stack.append(BlockInfo())\n\n    def exit_scope(self):\n        \"\"\"Pop the inner most scope\"\"\"\n        self.symbols.pop()\n        self.node_stack.pop()\n\n    def exit_block_scope(self):\n        \"\"\"Pop the inner most block scope, the function will call `exit_scope` implicitly\"\"\"\n        self.exit_scope()\n        # Pop block_info\n        self.block_info_stack.pop()\n\n    def update_symbol(self, name: str, symbol: Union[Buffer, Var], node: synr.ast.Node):\n        \"\"\"Append a symbol into current scope\"\"\"\n        if isinstance(symbol, Buffer):\n            if name in self.symbols[0]:\n                self.report_error(\"Duplicate Buffer name: \" + symbol.name, node.span)\n            self.symbols[0][name] = symbol\n        else:\n            self.symbols[-1][name] = symbol\n\n    def remove_symbol(self, name: str):\n        \"\"\"Remove a symbol\"\"\"\n        for symbols in reversed(self.symbols):\n            if name in symbols:\n                symbols.pop(name)\n                return\n        raise RuntimeError(\"Internal error of tvm script parser: no symbol named \" + name)\n\n    def lookup_symbol(self, name: str) -> Optional[Union[Buffer, Var]]:\n        \"\"\"Look up symbol by name\"\"\"\n        for symbols in reversed(self.symbols):\n            if name in symbols:\n                return symbols[name]\n        return self.closure_vars.get(name)\n\n    def report_error(self, message: str, span: Union[Span, synr.ast.Span]):\n        self._report_error(message, span)\n\n    def current_block_scope(self) -> BlockInfo:\n        if self.block_info_stack:\n            return self.block_info_stack[-1]\n        return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/diagnostics.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Bridge from synr's (the library used for parsing the python AST)\n   DiagnosticContext to TVM's diagnostics\n\"\"\"\nfrom synr import DiagnosticContext, ast\n\nimport tvm\nfrom tvm.ir.diagnostics import DiagnosticContext as TVMCtx\nfrom tvm.ir.diagnostics import get_renderer, DiagnosticLevel, Diagnostic\n\n\nclass TVMDiagnosticCtx(DiagnosticContext):\n    \"\"\"TVM diagnostics for synr\"\"\"\n\n    diag_ctx: TVMCtx\n\n    def __init__(self) -> None:\n        self.diag_ctx = TVMCtx(tvm.IRModule(), get_renderer())\n        self.source_name = None\n\n    def to_tvm_span(self, src_name, ast_span: ast.Span) -> tvm.ir.Span:\n        return tvm.ir.Span(\n            src_name,\n            ast_span.start_line,\n            ast_span.end_line,\n            ast_span.start_column,\n            ast_span.end_column,\n        )\n\n    def add_source(self, name: str, source: str) -> None:\n        src_name = self.diag_ctx.module.source_map.add(name, source)\n        self.source_name = src_name\n\n    def emit(self, _level, message, span):\n        span = self.to_tvm_span(self.source_name, span)\n        self.diag_ctx.emit(Diagnostic(DiagnosticLevel.ERROR, span, message))\n        self.diag_ctx.render()  # Raise exception on the first error we hit. TODO remove\n\n    def render(self):\n        self.diag_ctx.render()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/meta_unparser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unparse meta AST node into a dict\"\"\"\n# pylint: disable=invalid-name\n\nfrom synr import Transformer\n\n\nclass MetaUnparser(Transformer):\n    \"\"\"Python AST Visitor to unparse meta AST node into a dict\"\"\"\n\n    def transform(self, node):\n        method = \"transform_\" + node.__class__.__name__\n        visitor = getattr(self, method, None)\n        if visitor is None:\n            self.error(f\"Unexpected node type {type(node)} when parsing __tvm_meta__\", node.span)\n        return visitor(node)\n\n    def transform_DictLiteral(self, node):\n        keys = [self.visit(key) for key in node.keys]\n        values = [self.visit(value) for value in node.values]\n        return dict(zip(keys, values))\n\n    def transform_Tuple(self, node):\n        return tuple(self.visit(element) for element in node.elts)\n\n    def transform_ArrayLiteral(self, node):\n        return [self.visit(element) for element in node.elts]\n\n    def transform_Constant(self, node):\n        return node.value\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser For TIR\n\nWe use [synr](https://synr.readthedocs.io) to get an AST that is stable over\ndifferent python versions. Synr also provides an error handling context that we\nuse for error reporting.\n\"\"\"\n# pylint: disable=invalid-name, inconsistent-return-statements, no-else-return, broad-except\nimport types\nimport json\nimport operator\nimport inspect\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom synr import ast, Transformer, to_ast\n\nimport tvm\nfrom tvm import IRModule\nfrom tvm._ffi.base import TVMError\nfrom tvm.ir import GlobalVar\nfrom tvm.ir.function import BaseFunc\nfrom tvm.tir import buffer\nfrom tvm.tir.function import PrimFunc\nfrom . import _ffi_api\nfrom . import tir\n\nfrom .context_maintainer import ContextMaintainer\nfrom .meta_unparser import MetaUnparser\nfrom .registry import Registry\nfrom .diagnostics import TVMDiagnosticCtx\nfrom .utils import tvm_span_from_synr, synr_span_from_tvm, call_with_error_reporting\n\nfrom .tir.intrin import Intrin\nfrom .tir.node import Slice, BufferSlice\nfrom .tir.scope_handler import ScopeHandler, WithScopeHandler, ForScopeHandler\nfrom .tir.special_stmt import SpecialStmt\nfrom .tir import ty\n\n\nclass CallArgumentReader(object):\n    \"\"\"Helper class to read required arguments from passed arguments.\n\n    When parsing a function call, we need to match the arguments provided in\n    the AST to the required arguments of the function. This class makes sure\n    all the positional arguments are filled and also fill keyword arguments\n    with thier default value if a different value was not provided.\n    \"\"\"\n\n    def __init__(self, func_name, args, kwargs, parser, node):\n        self.func_name = func_name\n        self.args = args\n        self.kwargs = kwargs\n        self.parser = parser\n        self.node = node\n\n    def get_pos_only_arg(self, pos, name):\n        \"\"\"Get corresponding position only function argument from argument list\"\"\"\n        if len(self.args) >= pos:\n            arg = self.args[pos - 1]\n        elif name not in self.kwargs:\n            # If no positional argument was found in the AST, we see if it was\n            # defined by name instead.\n            # TODO(tkonolige): this error message is not quite correct. The\n            # number of required arguments is >= pos\n            self.parser.report_error(\n                f\"{self.func_name} requires {pos} arguments, but only {len(self.args)} were given.\",\n                self.node.span,\n            )\n        else:\n            arg = self.kwargs[name]\n\n        return arg\n\n    def get_kwarg(self, pos, name, default):\n        \"\"\"Get corresponding keyword function argument from argument list.\n\n        If the user hasn't provided the argument, set it to the default value.\n        \"\"\"\n        if len(self.args) >= pos:\n            arg = self.args[pos - 1]\n        elif name in self.kwargs:\n            arg = self.kwargs[name]\n        else:\n            return default\n\n        return arg\n\n    def get_varargs(self, pos):\n        \"\"\"Get corresponding variable argument from argument list\"\"\"\n        if len(self.args) >= pos and len(self.kwargs) == 0:\n            return self.args[pos - 1 :]\n        return []\n\n\nclass TVMScriptParser(Transformer):\n    \"\"\"Synr AST visitor pass which finally lowers to TIR.\n\n    Notes for Extension\n    -------------------\n    1. To support a new type of AST node, add a function transform_xxx().\n    2. To support new functions, add the function to the appropriate registry:\n        We divide allowed function calls in TVM script into 3 categories,\n        intrin, scope_handler and special_stmt.\n        1. intrin functions are low level functions like mod, load, and\n           constants. They correspond to a tir `IRNode`. They must have a\n           return value. The user can register intrin functions for the parser to\n           use.\n        2. scope_handler functions have no return value. They take two\n           arguments: the parser and the AST node. scope_handler functions are\n           used in with and for statements.\n        3. special_stmt functions handle cases that do not have a corresponding\n           tir `IRNode`. These functions take the parser and the AST node as\n           arguments and may return a value.\n        When visiting a Call node, we check the special_stmt registry first. If\n        no registered function is found, we then check the intrin registry.\n        When visiting With node, we check the with_scope registry.\n        When visiting For node, we check the for_scope registry.\n    \"\"\"\n\n    _binop_maker = {\n        ast.BuiltinOp.Add: tvm.tir.Add,\n        ast.BuiltinOp.Sub: tvm.tir.Sub,\n        ast.BuiltinOp.Mul: tvm.tir.Mul,\n        ast.BuiltinOp.Div: tvm.tir.Div,\n        ast.BuiltinOp.FloorDiv: tvm.tir.FloorDiv,\n        ast.BuiltinOp.Mod: tvm.tir.FloorMod,\n        ast.BuiltinOp.BitOr: lambda lhs, rhs, span: operator.or_(lhs, rhs),\n        ast.BuiltinOp.BitAnd: lambda lhs, rhs, span: operator.and_(lhs, rhs),\n        ast.BuiltinOp.BitXor: lambda lhs, rhs, span: operator.xor(lhs, rhs),\n        ast.BuiltinOp.GT: tvm.tir.GT,\n        ast.BuiltinOp.GE: tvm.tir.GE,\n        ast.BuiltinOp.LT: tvm.tir.LT,\n        ast.BuiltinOp.LE: tvm.tir.LE,\n        ast.BuiltinOp.Eq: tvm.tir.EQ,\n        ast.BuiltinOp.NotEq: tvm.tir.NE,\n        ast.BuiltinOp.And: tvm.tir.And,\n        ast.BuiltinOp.Or: tvm.tir.Or,\n    }\n\n    _unaryop_maker = {\n        ast.BuiltinOp.USub: lambda rhs, span: operator.neg(rhs),\n        ast.BuiltinOp.Invert: lambda rhs, span: operator.invert(rhs),\n        ast.BuiltinOp.Not: tvm.tir.Not,\n    }\n\n    # pylint gets confused here with synr.Transformer which doesn't have a\n    # custom init, so just disable it\n    def __init__(\n        self, base_lineno, tir_namespace, closure_vars\n    ):  # pylint: disable=super-init-not-called\n        self.context = None\n\n        self.base_lineno = base_lineno\n        self.current_lineno = 0\n        self.current_col_offset = 0\n        self.tir_namespace = tir_namespace\n        self.closure_vars = closure_vars\n        self.meta = None\n        self._inside_buffer_sugar = False\n\n    def init_function_parsing_env(self):\n        \"\"\"Initialize function parsing environment\"\"\"\n        self.context = ContextMaintainer(self.report_error, self.closure_vars)  # scope emitter\n\n    def init_meta(self, meta_dict):\n        if meta_dict is not None:\n            self.meta = tvm.ir.load_json(json.dumps(meta_dict))\n\n    def transform(self, node):\n        \"\"\"Generic transformation for visiting the AST. Dispatches to\n        `transform_ClassName` for the appropriate ClassName.\"\"\"\n        old_lineno, old_col_offset = self.current_lineno, self.current_col_offset\n\n        if hasattr(node, \"lineno\"):\n            self.current_lineno = self.base_lineno + node.lineno - 1\n        if hasattr(node, \"col_offset\"):\n            self.current_col_offset = node.col_offset\n\n        method = \"transform_\" + node.__class__.__name__\n        visitor = getattr(self, method, self.generic_visit)\n        transform_res = visitor(node)\n\n        self.current_lineno, self.current_col_offset = old_lineno, old_col_offset\n\n        return transform_res\n\n    def match_tir_namespace(self, identifier: str) -> bool:\n        \"\"\"Check if the namespace is equal to tvm.script.tir\"\"\"\n        return identifier in self.tir_namespace\n\n    def report_error(self, message: str, span: Union[ast.Span, tvm.ir.Span]):\n        \"\"\"Report an error occuring at a location.\n\n        This just dispatches to synr's DiagnosticContext.\n\n        Parameters\n        ----------\n        message : str\n            Error message\n        span : Union[synr.ast.Span, tvm.ir.Span]\n            Location of the error\n        \"\"\"\n        if isinstance(span, tvm.ir.Span):\n            span = synr_span_from_tvm(span)\n        self.error(message, span)\n\n    def parse_body(self, parent):\n        \"\"\"Parse remaining statements in this scope.\n\n        Parameters\n        ----------\n        parent : synr.ast.Node\n            Parent node of this scope. Errors will be reported here.\n        \"\"\"\n        body = []\n        spans = []\n        stmt = parent\n        while len(self.context.node_stack[-1]) > 0:\n            stmt = self.context.node_stack[-1].pop()\n            spans.append(stmt.span)\n            res = self.transform(stmt)\n            if res is not None:\n                body.append(res)\n        if len(body) == 0:\n            self.report_error(\n                \"Expected another statement at the end of this block. Perhaps you \"\n                \"used a concise statement and forgot to include a body afterwards.\",\n                stmt.span,\n            )\n        else:\n            return (\n                tvm.tir.SeqStmt(body, tvm_span_from_synr(ast.Span.union(spans)))\n                if len(body) > 1\n                else body[0]\n            )\n\n    def parse_arg_list(self, func, node_call):\n        \"\"\"Match the arguments of a function call in the AST to the required\n        arguments of the function. This handles positional arguments,\n        positional arguments specified by name, keyword arguments, and varargs.\n\n        Parameters\n        ----------\n        func : Function\n            The function that provides the signature\n\n        node_call: Union[ast.Call, ast.TypeApply, ast.TypeCall]\n            The AST call node that calls into the function.\n\n        Returns\n        -------\n        arg_list : list\n            The parsed positional argument.\n        \"\"\"\n        assert isinstance(node_call, (ast.Call, ast.TypeApply, ast.TypeCall))\n        # collect arguments\n        args = [self.transform(arg) for arg in node_call.params]\n        if isinstance(node_call, ast.TypeApply):\n            kw_args = {}  # TypeApply (e.g. foo[bar]) doesn't have kwargs defined in synr\n        else:\n            kw_args = {\n                self.transform(k): self.transform(v) for k, v in node_call.keyword_params.items()\n            }\n        # get the name and parameter list of func\n        if isinstance(func, (Intrin, ScopeHandler, SpecialStmt)):\n            func_name, param_list = func.signature()\n        else:\n            self.report_error(\n                \"Internal Error: function must be of type Intrin, ScopeHandler or SpecialStmt, \"\n                f\"but it is {type(func).__name__}\",\n                node_call.span,\n            )\n        # check arguments and parameter list and get a list of arguments\n        reader = CallArgumentReader(func_name, args, kw_args, self, node_call)\n        pos_only, kwargs, varargs = param_list\n        internal_args = list()\n\n        for i, arg_name in enumerate(pos_only):\n            internal_args.append(reader.get_pos_only_arg(i + 1, arg_name))\n        for i, arg_info in enumerate(kwargs):\n            arg_name, default = arg_info\n            internal_args.append(reader.get_kwarg(i + 1 + len(pos_only), arg_name, default=default))\n        if varargs is not None:\n            internal_args.extend(reader.get_varargs(len(pos_only) + len(kwargs) + 1))\n        elif len(args) + len(kw_args) > len(pos_only) + len(kwargs):\n            self.report_error(\n                \"Arguments mismatched. \"\n                + f\"Expected {len(pos_only) + len(kwargs)} args but got \"\n                + f\"{len(args) + len(kw_args)}\",\n                node_call.span,\n            )\n        return internal_args\n\n    def parse_type(self, type_node, parent):\n        \"\"\"Parse a type annotation.\n\n        We require the parent object to the type so that we have a place to\n        report the error message if the type does not exist.\n        \"\"\"\n        if type_node is None:\n            self.report_error(\"A type annotation is required\", parent.span)\n        res_type = self.transform(type_node)\n        return tvm.ir.TupleType([]) if res_type is None else res_type.evaluate()\n\n    def generic_visit(self, node):\n        \"\"\"Fallback visitor if node type is not handled. Reports an error.\"\"\"\n\n        self.report_error(type(node).__name__ + \" AST node is not supported\", node.span)\n\n    def transform_Module(self, node):\n        \"\"\"Module visitor\n\n        Right now, we only support two formats for TVM Script.\n\n        Example\n        -------\n        1. Generate a PrimFunc (If the code is printed, then it may also contain metadata)\n        .. code-block:: python\n\n            import tvm\n\n            @tvm.script\n            def A(...):\n                ...\n\n            # returns a PrimFunc\n            func = A\n\n        2. Generate an IRModule\n        .. code-block:: python\n\n            import tvm\n\n            @tvm.script.ir_module\n            class MyMod():\n                @T.prim_func\n                def A(...):\n                    ...\n                @T.prim_func\n                def B(...):\n                    ...\n\n                __tvm_meta__ = ...\n\n            # returns an IRModule\n            mod = MyMod\n        \"\"\"\n        if len(node.funcs) == 1:\n            return self.transform(next(iter(node.funcs.values())))\n        elif len(node.funcs) == 0:\n            self.report_error(\n                \"You must supply at least one class or function definition\", node.span\n            )\n        else:\n            self.report_error(\n                \"Only one-function, one-class or function-with-meta source code is allowed\",\n                ast.Span.union([x.span for x in list(node.funcs.values())[1:]]),\n            )\n\n    def transform_Class(self, node):\n        \"\"\"Class definition visitor.\n\n        A class can have multiple function definitions and a single\n        :code:`__tvm_meta__` statement. Each class corresponds to a single\n        :code:`IRModule`.\n\n        Example\n        -------\n        .. code-block:: python\n\n            @tvm.script.ir_module\n            class MyClass:\n                __tvm_meta__ = {}\n                def A():\n                    T.evaluate(0)\n        \"\"\"\n        if len(node.assignments) == 1:\n            if not (\n                len(node.assignments[0].lhs) == 1\n                and isinstance(node.assignments[0].lhs[0], ast.Var)\n                and node.assignments[0].lhs[0].id.name == \"__tvm_meta__\"\n            ):\n                self.report_error(\n                    \"The only top level assignments allowed are `__tvm_meta__ = ...`\",\n                    node.assignments[0].span,\n                )\n            self.init_meta(\n                MetaUnparser().do_transform(node.assignments[0].rhs, self._diagnostic_context)\n            )\n        elif len(node.assignments) > 1:\n            self.report_error(\n                \"Only a single top level `__tvm_meta__` is allowed\",\n                ast.Span.union([x.span for x in node.assignments[1:]]),\n            )\n\n        return IRModule(\n            {GlobalVar(name): self.transform(func) for name, func in node.funcs.items()}\n        )\n\n    def transform_Function(self, node):\n        \"\"\"Function definition visitor.\n\n        Each function definition is translated to a single :code:`PrimFunc`.\n\n        There are a couple restrictions on TVM Script functions:\n        1. Function arguments must have their types specified.\n        2. The body of the function can contain :code:`func_attr` to specify\n           attributes of the function (like it's name).\n        3. The body of the function can also contain multiple :code:`buffer_bind`s,\n           which give shape and dtype information to arguments.\n        4. Return statements are implicit.\n\n        Example\n        -------\n        .. code-block:: python\n\n            @T.prim_func\n            def my_function(x: T.handle):  # 1. Argument types\n                T.func_attr({\"global_symbol\": \"mmult\"})  # 2. Function attributes\n                X_1 = tir.buffer_bind(x, [1024, 1024])  # 3. Buffer binding\n                T.evaluate(0)  # 4. This function returns 0\n        \"\"\"\n\n        def check_as_torch_decorator(decorator: Union[ast.Call, ast.Var]):\n            if isinstance(decorator, ast.Call):\n                if len(decorator.params) != 1:\n                    return False\n                func_name = decorator.func_name\n            else:\n                func_name = decorator\n            if isinstance(func_name, ast.Var):\n                return func_name.id.name == \"as_torch\"\n\n        def check_decorator(decorators: List[ast.Expr]) -> bool:\n            \"\"\"Check the decorator is `T.prim_func\"\"\"\n            if len(decorators) > 2 or len(decorators) == 0:\n                return False\n            if len(decorators) == 2 and not check_as_torch_decorator(decorators[0]):\n                return False\n            d: ast.Expr = decorators[-1]\n            return (\n                isinstance(d, ast.Attr)\n                and isinstance(d.object, ast.Var)\n                and self.match_tir_namespace(d.object.id.name)\n                and d.field.name == \"prim_func\"\n            )\n\n        self.init_function_parsing_env()\n        self.context.enter_scope(nodes=node.body.stmts)\n\n        # add parameters of function\n        for arg in node.params:\n            # Note that this case is for T.match_buffer syntax sugar\n            if isinstance(arg.ty, (ast.TypeCall, ast.TypeApply)) and isinstance(\n                self.transform(arg.ty.func_name), ty.GenericBufferType\n            ):\n                result = self.handle_match_buffer_type(arg.ty, arg.name)\n                if not isinstance(result, buffer.Buffer):\n                    self.report_error(\n                        \"The result type of evaluating TypeCall and TypeApply stmt\"\n                        f\" is wrong: {type(result)}. It should be a Buffer\",\n                        node.span,\n                    )\n                arg_name_with_handle = arg.name + \"_handle\"\n                arg_var = tvm.te.var(arg_name_with_handle, tvm.ir.PrimType(\"handle\"))\n                self.context.func_buffer_map[arg_var] = result\n                self.context.update_symbol(arg.name, result, node)\n            else:\n                arg_var = tvm.te.var(arg.name, self.parse_type(arg.ty, arg))\n                self.context.update_symbol(arg.name, arg_var, node)\n            self.context.func_params.append(arg_var)\n\n        if not check_decorator(node.decorators):\n            self.report_error(\n                \"All functions should be decorated by `T.prim_func`\",\n                node.span,\n            )\n\n        # fetch the body of root block\n        body = self.parse_body(node.body)\n\n        # return a tir.PrimFunc\n        dict_attr = self.context.func_dict_attr\n        ret_type = self.parse_type(node.ret_type, node) if node.ret_type is not None else None\n        func = tvm.tir.PrimFunc(\n            self.context.func_params,\n            body,\n            ret_type,\n            buffer_map=self.context.func_buffer_map,\n            preflattened_buffer_map=self.context.func_preflattened_buffer_map,\n            attrs=tvm.ir.make_node(\"DictAttrs\", **dict_attr) if dict_attr else None,\n            span=tvm_span_from_synr(node.span),\n        )\n\n        # New Scope : Implicit root block\n        # Each function contains an implicit root block in TensorIR,\n        # so here we need a block scope for it.\n        # If the PrimFunc is not a TensorIR func (e.g. TE scheduled func or low-level func),\n        # the root block will not be added. The logic to add root block is in `_ffi_api.Complete`\n\n        # Fix the PrimFunc\n        # 1. generate root block if necessary\n        # 2. generate surrounding loops for blocks if necessary\n\n        func = call_with_error_reporting(\n            self.report_error,\n            node.span,\n            _ffi_api.Complete,\n            func,\n            self.context.root_alloc_buffers,\n        )\n\n        self.context.exit_scope()\n        return func\n\n    def transform_Lambda(self, node):\n        \"\"\"Lambda visitor\n\n        Return an array of input parameters and the transformed lambda body.\n        \"\"\"\n\n        self.context.enter_scope(nodes=[node.body])\n\n        # add parameters of the lambda\n        arg_vars = []\n        for arg in node.params:\n            # Use \"void\" for dtype here. The actual type is not yet known and will be\n            # determined later. Using void type will allow IRSubstitute to do the\n            # replacement without flagging a type-mismatch error.\n            arg_var = tvm.te.var(arg.name, dtype=\"\")\n            arg_vars.append(arg_var)\n            self.context.update_symbol(arg.name, arg_var, node)\n\n        # the body of a lambda must be an expr\n        if not isinstance(node.body, ast.Expr):\n            self.report_error(\"The body of a lambda must be an expression\", node.span)\n\n        # transform the body of the lambda\n        body = self.transform(node.body)\n\n        self.context.exit_scope()\n        return arg_vars, body\n\n    def transform_Assign(self, node):\n        \"\"\"Assign visitor\n        AST abstract grammar:\n            Assign(expr* targets, expr value, string? type_comment)\n\n        By now 5 patterns of Assign is supported:\n            1. special stmts with return value\n                1.1 Buffer = T.match_buffer()/T.buffer_decl()\n                1.2 Var = T.var()\n                1.3 Var = T.env_thread()\n            2. (BufferStore) Buffer[PrimExpr, PrimExpr, ..., PrimExpr] = PrimExpr\n            3. (Store)       Var[PrimExpr] = PrimExpr\n            4. with scope handlers with concise scoping and var def\n                4.1 var = T.allocate()\n            5. A call to a pure python function, consuming and producing TVMScript values.\n               The outputs are inlined into the following body (no variable is created).\n               x, y = f(...)\n        \"\"\"\n\n        if isinstance(node.rhs, ast.Call):\n            # Pattern 1 & Pattern 4\n            if isinstance(node.rhs.func_name, ast.Op):\n                func = None\n            else:\n                func = self.transform(node.rhs.func_name)\n\n            if isinstance(func, WithScopeHandler):\n                if not func.concise_scope or not func.def_symbol:\n                    self.report_error(\n                        \"with scope handler \" + func.signature()[0] + \" is not suitable here\",\n                        node.rhs.span,\n                    )\n                # Pattern 4\n                arg_list = self.parse_arg_list(func, node.rhs)\n                func.enter_scope(node, self.context, arg_list, node.rhs.func_name.span)\n                func.body = self.parse_body(node)\n                return func.exit_scope(node, self.context, arg_list, node.rhs.func_name.span)\n            elif isinstance(func, SpecialStmt):\n                # Pattern 1\n                arg_list = self.parse_arg_list(func, node.rhs)\n                func.handle(node, self.context, arg_list, node.rhs.func_name.span)\n                return self.parse_body(node)\n            elif isinstance(func, types.FunctionType):\n                # Pattern 5\n                args = [self.transform(arg) for arg in node.rhs.params]\n                try:\n                    out = func(*args)\n                except Exception as e:\n                    self.report_error(\n                        \"Error occurred when invoking the function \"\n                        + func.__name__\n                        + \": \\n\"\n                        + str(e),\n                        node.rhs.span,\n                    )\n\n                if len(node.lhs) == 1 and not isinstance(out, list):\n                    out = [out]\n\n                assert len(out) == len(node.lhs)\n\n                for var, value in zip(node.lhs, out):\n                    self.context.update_symbol(var.id.name, value, node)\n\n                body = self.parse_body(node)\n\n                for var, value in zip(node.lhs, out):\n                    self.context.remove_symbol(var.id.name)\n\n                return body\n\n        if isinstance(node.rhs, (ast.Call, ast.Constant)):\n            # Pattern 4 of let binding\n            value = self.transform(node.rhs)\n            if len(node.lhs) == 1 and not isinstance(node.lhs[0], ast.Var):\n                # This is a little confusing because it only is true when\n                # we have taken this branch. We might need to clarify what\n                # exectly is allowed in Assignments in tvmscript.\n                self.report_error(\n                    \"Left hand side of assignment must be an unqualified variable\",\n                    node.span,\n                )\n            ast_var = node.lhs[0]\n\n            if node.ty is None and hasattr(value, \"dtype\"):\n                var_ty = value.dtype\n            else:\n                var_ty = self.parse_type(node.ty, ast_var)\n\n            var = tvm.te.var(\n                ast_var.id.name,\n                var_ty,\n                span=tvm_span_from_synr(ast_var.span),\n            )\n            self.context.update_symbol(var.name, var, node)\n            body = self.parse_body(node)\n            self.context.remove_symbol(var.name)\n            return tvm.tir.LetStmt(var, value, body, span=tvm_span_from_synr(node.span))\n\n        self.report_error(\n            \"\"\"Assignments should be one of:\n            1. A \"special statement\" with return value\n                1.1 Buffer = T.match_buffer()/T.buffer_decl()\n                1.2 Var = T.var()\n                1.3 Var = T.env_thread()\n            2. A store into a buffer: Buffer[PrimExpr, PrimExpr, ..., PrimExpr] = PrimExpr\n            3. A store into a variable: Var[PrimExpr] = PrimExpr\n            4. A with scope handler with concise scoping and var def\n                4.1 var = T.allocate()\n            5. The right-hand side being a call to a pure python function, consuming and\n               producing TVMScript values.\n               x, y = f(...)\"\"\",\n            node.span,\n        )\n\n    def transform_SubscriptAssign(self, node):\n        \"\"\"Visitor for statements of the form :code:`x[1] = 2`.\"\"\"\n        symbol = self.transform(node.params[0])\n        indexes = self.transform(node.params[1])\n        rhs = self.transform(node.params[2])\n        rhs_span = tvm_span_from_synr(node.params[2].span)\n        if isinstance(symbol, tvm.tir.Buffer):\n            if len(indexes) != len(symbol.shape):\n                self.report_error(\n                    f\"Buffer {symbol.name} is {len(symbol.shape)}-dimensional, \"\n                    f\"cannot be indexed by {len(indexes)}-dimensional indices.\",\n                    node.params[1].span,\n                )\n\n            def __convert_index(x):\n                if isinstance(x, Slice):\n                    return x.as_index_expr(self.report_error)\n                return x\n\n            # BufferStore\n            indexes = [__convert_index(x) for x in indexes]\n            return tvm.tir.BufferStore(\n                symbol,\n                tvm.runtime.convert(rhs, span=rhs_span),\n                indexes,\n                span=tvm_span_from_synr(node.span),\n            )\n        else:\n            if symbol.dtype == \"handle\" and len(indexes) != 1:\n                self.report_error(\n                    \"Handles only support one-dimensional indexing. Use `T.match_buffer` to \"\n                    \"construct a multidimensional buffer from a handle.\",\n                    node.params[0].span,\n                )\n            if len(indexes) != 1:\n                self.report_error(\n                    f\"Store is only allowed with one index, but {len(indexes)} were provided.\",\n                    node.params[1].span,\n                )\n            self.report_error(\n                \"Use of tir.Store has been deprecated in favor of tir.BufferStore.\", node.span\n            )\n\n    def transform_AttrAssign(self, node):\n        \"\"\"Visitor for statements of the form :code:`x.y = 2`.\"\"\"\n        obj = self.transform(node.params[0])\n        field = node.params[1]\n        value = self.transform(node.params[2])\n\n        if not hasattr(obj, field.name):\n            self.error(f\"Field {field.name} does not exist\", field.span)\n\n        var = getattr(obj, field.name)\n\n        if not isinstance(var, tvm.tir.Var):\n            self.error(\n                f\"Can only assign to tir.Var attributes, not {type(var).__name__}\", node.span\n            )\n\n        body = self.parse_body(node)\n        return tvm.tir.LetStmt(var, value, body, span=tvm_span_from_synr(node.span))\n\n    def transform_Assert(self, node):\n        \"\"\"Assert visitor\n\n        Pattern corresponds to concise mode of :code:`with T.Assert()`.\n        \"\"\"\n\n        condition = self.transform(node.condition)\n        if node.msg is None:\n            self.report_error(\"Assert statements must have an error message.\", node.span)\n        message = self.transform(node.msg)\n        body = self.parse_body(node)\n        return tvm.tir.AssertStmt(\n            condition, tvm.runtime.convert(message), body, span=tvm_span_from_synr(node.span)\n        )\n\n    def transform_For(self, node):\n        \"\"\"For visitor\n        AST abstract grammar:\n            For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n        By now 1 pattern of For is supported:\n            1. for scope handler\n                for name in T.serial()/T.parallel()/T.vectorized()/T.unroll()/range()/\n                            T.grid()/T.thread_binding()\n        \"\"\"\n\n        if not isinstance(node.rhs, ast.Call):\n            self.report_error(\"The loop iterator should be a function call.\", node.rhs.span)\n        func = self.transform(node.rhs.func_name)\n        if not isinstance(func, ForScopeHandler):\n            self.report_error(\n                \"Only For scope handlers can be used in a for statement.\", node.rhs.func_name.span\n            )\n        # prepare for new for scope\n        old_lineno, old_col_offset = self.current_lineno, self.current_col_offset\n        self.current_lineno = node.span.start_line\n        self.current_col_offset = node.span.start_column\n        self.context.enter_scope(nodes=node.body.stmts)\n        # for scope handler process the scope\n        arg_list = [\n            tvm.runtime.convert(arg, span=tvm_span_from_synr(node.rhs.span))\n            for arg in self.parse_arg_list(func, node.rhs)\n        ]\n        func.enter_scope(node, self.context, arg_list, node.rhs.func_name.span)\n        func.body = self.parse_body(node)\n        res = func.exit_scope(node, self.context, arg_list, node.rhs.func_name.span)\n        # exit the scope\n        self.context.exit_scope()\n        self.current_lineno, self.current_col_offset = old_lineno, old_col_offset\n        return res\n\n    def transform_While(self, node):\n        \"\"\"While visitor\n        AST abstract grammar:\n            While(expr condition, stmt* body)\n        \"\"\"\n        condition = self.transform(node.condition)\n        # body\n        self.context.enter_scope(nodes=node.body.stmts)\n        body = self.parse_body(node)\n        self.context.exit_scope()\n\n        return tvm.tir.While(condition, body, span=tvm_span_from_synr(node.span))\n\n    def transform_With(self, node):\n        \"\"\"With visitor\n        AST abstract grammar:\n            With(withitem* items, stmt* body, string? type_comment)\n            withitem = (expr context_expr, expr? optional_vars)\n        By now 2 patterns of With is supported:\n            1. with scope handler with symbol def\n                with T.allocate() as targets:\n            2. with scope handler without symbol def\n                with T.block(*axes)/T.let()/T.Assert()/T.attr()/T.realize()\n        \"\"\"\n\n        if not isinstance(node.rhs, ast.Call):\n            self.report_error(\n                \"The context expression of a `with` statement should be a function call.\",\n                node.rhs.span,\n            )\n\n        func = self.transform(node.rhs.func_name)\n\n        if not isinstance(func, WithScopeHandler):\n            self.report_error(\n                f\"Function {func} cannot be used in a `with` statement.\", node.rhs.func_name.span\n            )\n        # prepare for new block scope\n        old_lineno, old_col_offset = self.current_lineno, self.current_col_offset\n        self.current_lineno = node.body.span.start_line\n        self.current_col_offset = node.body.span.start_column\n        self.context.enter_block_scope(nodes=node.body.stmts)\n        # with scope handler process the scope\n        arg_list = self.parse_arg_list(func, node.rhs)\n        func.enter_scope(node, self.context, arg_list, node.rhs.func_name.span)\n        func.body = self.parse_body(node)\n        res = func.exit_scope(node, self.context, arg_list, node.rhs.func_name.span)\n        # exit the scope\n        self.context.exit_block_scope()\n        self.current_lineno, self.current_col_offset = old_lineno, old_col_offset\n        return res\n\n    def transform_If(self, node):\n        \"\"\"If visitor\n        AST abstract grammar:\n            If(expr test, stmt* body, stmt* orelse)\n        \"\"\"\n\n        condition = self.transform(node.condition)\n        # then body\n        self.context.enter_scope(nodes=node.true.stmts)\n        then_body = self.parse_body(node)\n        self.context.exit_scope()\n\n        # else body\n        if len(node.false.stmts) > 0:\n            self.context.enter_scope(nodes=node.false.stmts)\n            else_body = self.parse_body(node)\n            self.context.exit_scope()\n        else:\n            else_body = None\n\n        return tvm.tir.IfThenElse(\n            condition, then_body, else_body, span=tvm_span_from_synr(node.span)\n        )\n\n    def transform_Call(self, node):\n        \"\"\"Call visitor\n\n        3 different Call patterns are allowed:\n            1. Intrin representing a PrimExpr/IterVar\n                1.1 tir.int/uint/float8/16/32/64/floormod/floordiv/load/cast/ramp/broadcast/max\n                1.2 tir.range/reduce_axis/scan_axis/opaque_axis\n            2. tir.Op(dtype, ...)\n            3. other callable functions\n        \"\"\"\n\n        if isinstance(node.func_name, ast.Op):\n            if node.func_name.name == ast.BuiltinOp.Subscript:\n                return self.transform_Subscript(node)\n            if node.func_name.name in self._binop_maker:\n                lhs = self.transform(node.params[0])\n                # There is no supertype for everything that can appear in\n                # an expression, so we manually add what we might get here.\n                if not isinstance(lhs, (tvm.tir.PrimExpr, BufferSlice)):\n                    # We would really like to report a more specific\n                    # error here, but this parser contains no distinction\n                    # between parsing statements and parsing expressions. All\n                    # rules just call `transform`.\n                    self.report_error(\n                        f\"Left hand side of binary op must be a PrimExpr, \"\n                        \"but it is a {type(lhs).__name__}\",\n                        node.params[0].span,\n                    )\n                rhs = self.transform(node.params[1])\n                if not isinstance(rhs, (tvm.tir.PrimExpr, BufferSlice)):\n                    self.report_error(\n                        f\"Right hand side of binary op must be a PrimExpr, \"\n                        \"but it is a {type(rhs).__name__}\",\n                        node.params[1].span,\n                    )\n                return call_with_error_reporting(\n                    self.report_error,\n                    node.span,\n                    lambda node, lhs, rhs, span: self._binop_maker[node.func_name.name](\n                        lhs, rhs, span=span\n                    ),\n                    node,\n                    lhs,\n                    rhs,\n                    tvm_span_from_synr(node.span),\n                )\n            if node.func_name.name in self._unaryop_maker:\n                rhs = self.transform(node.params[0])\n                if node.func_name.name == ast.BuiltinOp.USub and isinstance(\n                    node.params[0], ast.Constant\n                ):\n                    # '-literal' should be parsed together for proper literal type inference\n                    if not isinstance(rhs, (tvm.tir.IntImm, tvm.tir.FloatImm)):\n                        self.report_error(\"The literal is illegal after -\", node.params[0].span)\n                    return tvm.tir.const(-rhs.value)\n                return self._unaryop_maker[node.func_name.name](\n                    rhs, span=tvm_span_from_synr(node.span)\n                )\n            self.report_error(f\"Unsupported operator {node.func_name.name}.\", node.func_name.span)\n        else:\n            func = self.transform(node.func_name)\n            if isinstance(func, Intrin) and not func.stmt:\n                # pattern 1\n                arg_list = self.parse_arg_list(func, node)\n                return call_with_error_reporting(\n                    self.report_error,\n                    node.func_name.span,\n                    func.handle,\n                    arg_list,\n                    node.func_name.span,\n                )\n            else:\n                args = [self.transform(arg) for arg in node.params]\n                kw_args = {\n                    self.transform(k): self.transform(v) for k, v in node.keyword_params.items()\n                }\n                if isinstance(func, tvm.tir.op.Op):\n                    if not \"dtype\" in kw_args.keys():\n                        self.report_error(f\"{func} requires a dtype keyword argument.\", node.span)\n                    # pattern 2\n                    return tvm.tir.Call(\n                        kw_args[\"dtype\"], func, args, span=tvm_span_from_synr(node.span)\n                    )\n                elif callable(func):\n                    # pattern 3\n                    return func(*args, **kw_args)\n                else:\n                    self.report_error(\n                        f\"Function is neither callable nor a tvm.tir.op.Op (it is a {type(func)}).\",\n                        node.func_name.span,\n                    )\n\n    def transform_UnassignedCall(self, node):\n        \"\"\"Visitor for statements that are function calls.\n\n        This handles function calls that appear on thier own line like `tir.realize`.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            @T.prim_func\n            def f():\n                A = T.buffer_decl([10, 10])\n                T.realize(A[1:2, 1:2], \"\")  # This is an UnassignedCall\n                A[1, 1] = 2  # This is also an UnassignedCall\n        \"\"\"\n        # Only allowed builtin operator that can be a statement is x[1] = 3 i.e. subscript assign.\n        if isinstance(node.call.func_name, ast.Op):\n            if node.call.func_name.name == ast.BuiltinOp.SubscriptAssign:\n                return self.transform_SubscriptAssign(node.call)\n\n            if node.call.func_name.name == ast.BuiltinOp.AttrAssign:\n                return self.transform_AttrAssign(node.call)\n\n            self.report_error(\n                \"Binary and unary operators are not allowed as a statement\", node.span\n            )\n\n        # handle a regular function call\n        func = self.transform(node.call.func_name)\n        arg_list = self.parse_arg_list(func, node.call)\n\n        if isinstance(func, tir.scope_handler.AssertHandler):\n            self.report_error(\n                \"A standalone `T.Assert` is not allowed. Use `assert condition, message` \"\n                \"instead.\",\n                node.call.func_name.span,\n            )\n\n        if isinstance(func, Intrin):\n            if func.stmt:\n                return call_with_error_reporting(\n                    self.report_error,\n                    node.call.func_name.span,\n                    func.handle,\n                    arg_list,\n                    node.call.func_name.span,\n                )\n            else:\n                self.report_error(f\"This intrinsic cannot be used as a statement.\", node.call.span)\n        elif isinstance(func, WithScopeHandler) and func.concise_scope and not func.def_symbol:\n            func.enter_scope(node, self.context, arg_list, node.call.func_name.span)\n            func.body = self.parse_body(node)\n            return func.exit_scope(node, self.context, arg_list, node.call.func_name.span)\n        elif isinstance(func, SpecialStmt) and not func.def_symbol:\n            func.handle(node, self.context, arg_list, node.call.func_name.span)\n            return\n\n        self.report_error(\n            \"Unexpected statement. Expected an assert, an intrinsic, a with statement, or a \"\n            f\"special statement, but got {type(func).__name__}.\",\n            node.call.func_name.span,\n        )\n\n    def transform_Slice(self, node):\n        \"\"\"Index slice visitor.\"\"\"\n        start = self.transform(node.start)\n        end = self.transform(node.end)\n        if not (\n            isinstance(node.step, ast.Constant)\n            and isinstance(node.step.value, int)\n            and node.step.value > 0\n        ):\n            self.report_error(\n                \"Only positive integer step size is supported for slices.\", node.step.span\n            )\n        return Slice(start, end, node.step.value, tvm_span_from_synr(node.span))\n\n    def transform_Subscript(self, node):\n        \"\"\"Array access visitor.\n\n        By now only 3 types of Subscript are supported:\n            1. Buffer[index, index, ...], Buffer element access(BufferLoad & BufferStore)\n               Var[index] Buffer element access()\n            2. Buffer[start: stop, start: stop, ...], BufferRealize(realize(buffer[...]))\n            3. Array[index], Buffer element access\n        \"\"\"\n\n        symbol = self.transform(node.params[0])\n        if symbol is None:\n            self.report_error(\n                f\"Variable {node.params[0].id.name} is not defined.\", node.params[0].span\n            )\n\n        indexes = [self.transform(x) for x in node.params[1].values]\n        if isinstance(symbol, tvm.tir.expr.Var):\n            if symbol.dtype == \"handle\":\n                self.report_error(\n                    \"Cannot read directly from a handle, use `T.match_buffer` \"\n                    \"to create a buffer to read from.\",\n                    node.params[0].span,\n                )\n            if len(indexes) > 1:\n                self.report_error(\n                    \"Only a single index can be provided when indexing into a `var`.\",\n                    node.params[1].span,\n                )\n            index = indexes[0]\n            if not isinstance(index, (tvm.tir.PrimExpr, int)):\n                self.report_error(\n                    \"Var load index should be an int or PrimExpr, but it is a\" + type(index),\n                    node.span,\n                )\n\n            self.report_error(\n                \"Use of tir.Load has been deprecated in favor of tir.BufferLoad\", node.span\n            )\n        elif isinstance(symbol, tvm.tir.Buffer):\n            return BufferSlice(\n                symbol, indexes, self.report_error, span=tvm_span_from_synr(node.span)\n            )\n        elif isinstance(symbol, tvm.container.Array):\n            if len(indexes) > 1:\n                self.report_error(\n                    \"Array access should be one-dimension access, but the indices are \"\n                    + str(indexes),\n                    node.span,\n                )\n            index = indexes[0]\n            if not isinstance(index, (int, tvm.tir.expr.IntImm)):\n                self.report_error(\n                    \"Array access index expected int or IntImm, but got \" + type(index),\n                    node.span,\n                )\n            if int(index) >= len(symbol):\n                self.report_error(\n                    f\"Array access out of bound, size: {len(symbol)}, got index {index}.\",\n                    node.span,\n                )\n            return symbol[int(index)]\n        else:\n            self.report_error(\n                f\"Cannot subscript from a {type(symbol).__name__}. Only variables and \"\n                \"buffers are supported.\",\n                node.params[0].span,\n            )\n\n    def transform_Attr(self, node):\n        \"\"\"Visitor for field access of the form `x.y`.\n\n        This visitor is used to lookup function and symbol names. We have two\n        cases to handle here:\n        1. If we have a statement of the form `tir.something`, then we lookup\n           `tir.something` in the `Registry`. If the function is not in the\n           registry, then we try to find a `tvm.ir.op.Op` with the same name.\n        2. All other names `tvm.something` are lookup up in this current python\n           namespace.\n        \"\"\"\n\n        def get_full_attr_name(node: ast.Attr) -> str:\n            reverse_field_names = [node.field.name]\n            while isinstance(node.object, ast.Attr):\n                node = node.object\n                reverse_field_names.append(node.field.name)\n            if isinstance(node.object, ast.Var):\n                reverse_field_names.append(node.object.id.name)\n            return \".\".join(reversed(reverse_field_names))\n\n        if isinstance(node.object, (ast.Var, ast.Attr)):\n            full_attr_name = get_full_attr_name(node)\n            attr_object, fields = full_attr_name.split(\".\", maxsplit=1)\n            if self.match_tir_namespace(attr_object):\n                func_name = \"tir.\" + fields\n                res = Registry.lookup(func_name)\n                if res is not None:\n                    return res\n                try:\n                    return tvm.ir.op.Op.get(func_name)\n                except TVMError as e:\n                    # Check if we got an attribute error\n                    if e.args[0].find(\"AttributeError\"):\n                        self.report_error(f\"Unregistered function `tir.{fields}`.\", node.span)\n                    else:\n                        raise e\n\n        symbol = self.transform(node.object)\n        if symbol is None:\n            self.report_error(\"Unsupported Attribute expression.\", node.object.span)\n        if not hasattr(symbol, node.field.name):\n            self.report_error(\n                f\"Type {type(symbol)} does not have a field called `{node.field.name}`.\", node.span\n            )\n        res = getattr(symbol, node.field.name)\n        return res\n\n    def transform_TypeAttr(self, node):\n        \"\"\"Visitor for field access of the form `x.y` for types.\n\n        We have two cases here:\n        1. If the type is of the form `T.something`, we look up the type in\n           the `tir` namespace in this module.\n        2. If the type is of the form `tvm.x.something` then we look up\n           `tvm.x.something` in this modules namespace.\n        \"\"\"\n        if isinstance(node.object, ast.TypeVar):\n            if self.match_tir_namespace(node.object.id.name):\n                if not hasattr(tir, node.field.name):\n                    self.report_error(\n                        f\"Invalid type annotation `tir.{node.field.name}`.\", node.span\n                    )\n                return getattr(tir, node.field.name)\n\n        symbol = self.transform(node.object)\n        if symbol is None:\n            self.report_error(\"Unsupported Attribute expression\", node.object.span)\n        if not hasattr(symbol, node.field):\n            self.report_error(\n                f\"Type {type(symbol)} does not have a field called `{node.field}`.\", node.span\n            )\n        res = getattr(symbol, node.field)\n        return res\n\n    def transform_DictLiteral(self, node):\n        \"\"\"Dictionary literal visitor.\n\n        Handles dictionary literals of the form `{x:y, z:2}`.\n        \"\"\"\n\n        keys = [self.transform(key) for key in node.keys]\n        values = [self.transform(value) for value in node.values]\n\n        return dict(zip(keys, values))\n\n    def transform_Tuple(self, node):\n        \"\"\"Tuple visitor.\n\n        Handles tuples of the form `(x, y, 2)`.\n        \"\"\"\n\n        return tuple(self.transform(element) for element in node.values)\n\n    def transform_ArrayLiteral(self, node):\n        \"\"\"List literal visitor.\n\n        Handles lists of the form `[x, 2, 3]`.\n        \"\"\"\n\n        return [self.transform(element) for element in node.values]\n\n    def transform_Var(self, node):\n        \"\"\"Variable visitor\n\n        Handles variables like `x` in `x = 2`.\n        \"\"\"\n\n        name = node.id.name\n        if name == \"meta\":\n            return self.meta\n        symbol = Registry.lookup(name)\n        if symbol is not None:\n            return symbol\n        symbol = self.context.lookup_symbol(name)\n        if symbol is not None:\n            return symbol\n        self.report_error(f\"Unknown identifier {name}.\", node.span)\n\n    def transform_TypeVar(self, node):\n        \"\"\"Type variable visitor.\n\n        Equivalent to `transform_Var` but for types.\n        \"\"\"\n        name = node.id.name\n        symbol = Registry.lookup(name) or self.context.lookup_symbol(name)\n        if symbol is not None:\n            return symbol\n        self.report_error(f\"Unknown identifier {name}.\", node.span)\n\n    def transform_Constant(self, node):\n        \"\"\"Constant value visitor.\n\n        Constant values include `None`, `\"strings\"`, `2` (integers), `4.2`\n        (floats), and `true` (booleans).\n        \"\"\"\n        return tvm.runtime.convert(node.value, span=tvm_span_from_synr(node.span))\n\n    def transform_TypeConstant(self, node):\n        \"\"\"Constant value visitor for types.\n\n        See `transform_Constant`.\n        \"\"\"\n        if self._inside_buffer_sugar:\n            return self.transform_Constant(node)\n\n        return node.value\n\n    def transform_TypeTuple(self, node):\n        \"\"\"Tuple value visitor for types.\n\n        Mostly used in `transform_TypeCall` and `transform_TypeApply`.\n        \"\"\"\n        return [self.transform(value) for value in node.values]\n\n    def transform_TypeCall(self, node):\n        \"\"\"TypeCall visitor\n\n        This occurs when an expression is used inside a T.Buffer\n        parameter annotation.\n        \"\"\"\n\n        # ast.Call has the BuiltinOp as node.func_name.name, where\n        # ast.TypeCall has the BuiltinOp as node.func_name.  So we can\n        # delegate to self.transform_Call, but the error messages for\n        # unsupported operations will highlight the entire expression\n        # and not just the function itself.\n        op = ast.Op(node.span, node.func_name)\n        call = ast.Call(node.span, op, node.params, node.keyword_params)\n        return self.transform_Call(call)\n\n    def transform_TypeApply(self, node):\n        \"\"\"Visitor for Type[Type] expressions.\n\n        Mostly used for ``T.Ptr`` expressions.\n        \"\"\"\n        func = self.transform(node.func_name)\n\n        if not isinstance(func, ty.TypeGeneric) or not hasattr(func, \"__getitem__\"):\n            self.report_error(\n                f\"Use of type arguments requires a type that accepts type arguments (e.g. T.Ptr), \"\n                f\"but found {type(func).__name__} instead.\",\n                node.span,\n            )\n\n        param_types = []\n        for idx, param in enumerate(node.params):\n            param_type = self.transform(param)\n            if not isinstance(param_type, ty.TypeGeneric) and func.require_type_generic_at(idx):\n                self.report_error(\n                    f\"Expected a type but found {type(param).__name__} \"\n                    f\"at {idx}th type argument\",\n                    param.span,\n                )\n\n            param_types.append(param_type)\n\n        if len(param_types) == 1:\n            return func[param_types[0]]\n        else:\n            return func[param_types]\n\n    def handle_match_buffer_type(self, node, buffer_name):\n        \"\"\"special function to handle syntax sugar for match buffer.\n\n        This method is for buffer declarations in the function parameters.\n        \"\"\"\n        func = self.transform(node.func_name)\n        assert isinstance(func, SpecialStmt)\n\n        # parse args and kwargs for TypeCall and TypeApply\n        self._inside_buffer_sugar = True\n        try:\n            arg_list = self.parse_arg_list(func, node)\n        finally:\n            self._inside_buffer_sugar = False\n\n        # Note that the third element in arg_list would always be the 'name'\n        # TODO: This index is hardcoded as a workaround. Better to make it programmatic\n        if arg_list[2] is None:\n            arg_list[2] = buffer_name\n        buf = func.handle(node, self.context, arg_list, node.func_name.span)\n        return buf\n\n    def transform_Return(self, node):\n        self.report_error(\n            \"TVM script does not support return statements. Instead the last statement in any \"\n            \"block is implicitly returned.\",\n            node.span,\n        )\n\n\ndef get_tir_namespace(script: Union[Callable, type]) -> List[str]:\n    assert inspect.isfunction(script) or inspect.isclass(script)\n    env: Dict[str, Any] = script.__globals__\n    return [key for key in env.keys() if env[key] == tir]\n\n\ndef from_source(\n    input_func: Union[str, Callable], tir_prefix: Optional[List[str]] = None\n) -> Union[PrimFunc, IRModule]:\n    \"\"\"Parse function or string into PrimFunc or IRModule.\n\n    If possible, pass the TVM script in as a function so that line numbers and\n    filename will be accurate.\n\n    Parameters\n    ----------\n    input_module : Union[str, Callable]\n        The python function to be parsed.\n\n    tir_prefix : Optional[List[str]]\n        The tir prefix list. Only works for str input, default by \"tir\" and \"T\".\n\n    Returns\n    -------\n    output : Union[Function, Module]\n        The Function or Module in IR.\n    \"\"\"\n    if isinstance(input_func, str):\n        tir_prefix = [\"T\", \"tir\"] if tir_prefix is None else tir_prefix\n        return to_ast(input_func, TVMDiagnosticCtx(), TVMScriptParser(0, tir_prefix, {}))\n    elif inspect.isfunction(input_func):\n        _, start_line = inspect.getsourcelines(input_func)\n        env: Dict[str, Any] = input_func.__globals__\n        namespace = [key for key in env.keys() if env[key] is tir]\n        _closure_vars = inspect.getclosurevars(input_func)\n        closure_vars = {**_closure_vars.nonlocals, **_closure_vars.globals}\n        parser = TVMScriptParser(start_line, namespace, closure_vars)\n        result = to_ast(input_func, TVMDiagnosticCtx(), parser)\n        return result\n    else:\n        raise TypeError(\"Only function definitions are supported.\")\n\n\ndef ir_module(input_module: type) -> IRModule:\n    \"\"\"Decorate a python class as tvm IRModule.\n\n    Parameters\n    ----------\n    input_module : type\n        The python class to be parsed.\n\n    Returns\n    -------\n    output : IRModule\n        The result IRModule.\n    \"\"\"\n    if inspect.isclass(input_module):\n        func_dict = {\n            name: f for name, f in input_module.__dict__.items() if isinstance(f, BaseFunc)\n        }\n        return IRModule(func_dict)\n    raise TypeError(\"Only class definitions are supported.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/registry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Function Registry \"\"\"\n# pylint: disable=inconsistent-return-statements, relative-beyond-top-level, import-outside-toplevel\nimport types\nfrom typing import Union, Callable, Dict, Optional, Any\n\n\nclass Registry(object):\n    \"\"\"Registration map\n    All these maps are static\n    \"\"\"\n\n    registrations: Dict[str, type] = dict()\n\n    @staticmethod\n    def lookup(name: str) -> Optional[Any]:\n        if name in Registry.registrations:\n            # every time we create a new handler\n            # since we may want to keep some local info inside it\n            return Registry.registrations[name]()\n        return None\n\n\ndef register(inputs: Union[Callable, type]) -> type:\n    \"\"\"Register Intrin/ScopeHandler/SpecialStmt\"\"\"\n    registration: type\n    if isinstance(inputs, types.FunctionType):\n        # is function\n        from .tir.intrin import Intrin\n\n        def create_new_intrin(func) -> type:\n            class NewIntrin(Intrin):\n                def __init__(self):\n                    super().__init__(func)\n\n            return NewIntrin\n\n        registration = create_new_intrin(inputs)\n    elif isinstance(inputs, type):\n        # is class\n        registration = inputs\n    else:\n        raise ValueError()\n\n    key: str = registration().signature()[0]\n    Registry.registrations[key] = registration\n    return registration\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVMScript for TIR\"\"\"\n\n# Type system\nfrom .ty import void, boolean, handle, Ptr, Tuple, Buffer\nfrom .ty import bool  # pylint: disable=redefined-builtin\n\nfrom .prim_func import prim_func\n\n# add all floating point and integer datatypes to the module\nfor _dtype in [\"float\", \"uint\", \"int\"]:\n    for _size in [\"8\", \"16\", \"32\", \"64\"]:\n        for _lanes in [\"\", \"x4\", \"x8\", \"x16\", \"x32\", \"x64\"]:\n            from . import ty\n\n            _name = _dtype + _size + _lanes\n            if hasattr(ty, _name):\n                globals()[_name] = getattr(ty, _name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Intrinsic Classes\"\"\"\n# pylint: disable=redefined-builtin, relative-beyond-top-level\nimport builtins\nfrom typing import Any, List\n\nimport tvm.tir\nfrom tvm.tir import FloatImm\n\nfrom ....target import codegen\nfrom ..registry import register\nfrom ..utils import get_param_list, tvm_span_from_synr\n\n\nclass Intrin:\n    def __init__(self, intrin, stmt=False):\n        self.intrin = intrin\n        self.stmt = stmt\n\n    def signature(self):\n        return \"tir.\" + self.intrin.__name__, get_param_list(self.intrin)\n\n    def handle(self, arg_list: List[Any], span: tvm.ir.Span):\n        return self.intrin(*arg_list, span=tvm_span_from_synr(span))\n\n\n@register\ndef bool(imm, span):\n    return imm.astype(\"bool\", span)\n\n\n# register all datatypes\nfor _dtype in [\"float\", \"uint\", \"int\"]:\n    for _size in [\"8\", \"16\", \"32\", \"64\"]:\n        for _lanes in [\"\", \"x4\", \"x8\", \"x16\", \"x32\"]:\n            _name = _dtype + _size + _lanes\n\n            # nest closures so we copy the name string\n            def wrap(name):\n                def f(imm, span):\n                    if name.startswith(\"float\"):\n                        if imm in {\"inf\", \"-inf\", \"nan\"}:\n                            return FloatImm(dtype=name, value=float(imm), span=span)\n                    return imm.astype(name, span)\n\n                f.__name__ = name\n                return f\n\n            _intrin = wrap(_name)\n            register(_intrin)\n\n\n@register\ndef min_value(dtype, span):\n    return tvm.tir.min_value(dtype, span)\n\n\n@register\ndef max_value(dtype, span):\n    return tvm.tir.max_value(dtype, span)\n\n\n@register\ndef floordiv(x, y, span):\n    return tvm.tir.floordiv(x, y, span)\n\n\n@register\ndef floormod(x, y, span):\n    return tvm.tir.floormod(x, y, span)\n\n\n@register\ndef truncmod(x, y, span):\n    return tvm.tir.truncmod(x, y, span)\n\n\n@register\ndef truncdiv(x, y, span):\n    return tvm.tir.truncdiv(x, y, span)\n\n\n@register\ndef ceildiv(x, y, span):\n    return tvm.tir.ceildiv(x, y, span)\n\n\n@register\ndef abs(x, span):\n    return tvm.tir.abs(x, span)\n\n\n@register\ndef load(dtype, var, index, predicate=None, span=None):\n    return tvm.tir.Load(dtype, var, index, predicate, span)\n\n\n@register\ndef cast(value, dtype, span):\n    return tvm.tir.Cast(dtype, value, span)\n\n\n@register\ndef ramp(base, stride, lanes, span):\n    return tvm.tir.Ramp(base, stride, lanes.value, span)\n\n\n@register\ndef broadcast(value, lanes, span):\n    return tvm.tir.Broadcast(value, lanes.value, span)\n\n\n@register\ndef iter_var(var, dom, iter_type, thread_tag, span):\n    iter_type = getattr(tvm.tir.IterVar, iter_type)\n    return tvm.tir.IterVar(dom, var, iter_type, thread_tag, span)\n\n\n@register\ndef max(a, b, span):  # pylint: disable=redefined-builtin\n    return tvm.tir.Max(a, b, span)\n\n\n@register\ndef min(a, b, span):  # pylint: disable=redefined-builtin\n    return tvm.tir.Min(a, b, span)\n\n\ndef get_axis(begin, end, iter_type, span):\n    ana = tvm.arith.Analyzer()\n    extent = ana.simplify(end - begin)\n    block_var_dom = tvm.ir.Range.from_min_extent(begin, extent)\n\n    iter_type_dict = {\"data_par\": 0, \"reduce\": 2, \"scan\": 3, \"opaque\": 4}\n    return tvm.tir.IterVar(block_var_dom, \"bv\", iter_type_dict[iter_type], span=span)\n\n\n@register\ndef range(begin, end, span):\n    return get_axis(begin, end, \"data_par\", span)\n\n\n@register\ndef reduce_axis(begin, end, span):\n    return get_axis(begin, end, \"reduce\", span)\n\n\n@register\ndef scan_axis(begin, end, span):\n    return get_axis(begin, end, \"scan\", span)\n\n\n@register\ndef opaque_axis(begin, end, span):\n    return get_axis(begin, end, \"opaque\", span)\n\n\n@register\ndef Select(cond, if_body, else_body, span):  # pylint: disable=invalid-name\n    return tvm.tir.Select(cond, if_body, else_body, span)\n\n\n@register\ndef Let(var, value, body, span):  # pylint: disable=invalid-name\n    return tvm.tir.Let(var, value, body, span)\n\n\n@register\nclass EvaluateIntrin(Intrin):\n    def __init__(self):\n        def evaluate(value, span):\n            return tvm.tir.Evaluate(value, span)\n\n        super().__init__(evaluate, stmt=True)\n\n\n@register\nclass StoreIntrin(Intrin):\n    def __init__(self):\n        def store(var, index, value, predicate=True, span=None):\n            return tvm.tir.Store(var, value, index, predicate, span)\n\n        super().__init__(store, stmt=True)\n\n\n@register\nclass AssumeIntrin(Intrin):\n    def __init__(self):\n        def assume(constraint, span):\n            return tvm.tir.Evaluate(\n                tvm.tir.call_intrin(\"bool\", \"tir.assume\", constraint, span=span)\n            )\n\n        super().__init__(assume, stmt=True)\n\n\n@register\ndef comm_reducer(lambda_io, identities, span):\n    \"\"\"Create a CommReducer from lambda inputs/outputs and the identities\"\"\"\n    lambda_input = lambda_io[0]\n    lambda_output = lambda_io[1]\n\n    num_args = len(lambda_input)\n    num_arg_per_group = num_args // 2\n    x = [lambda_input[i] for i in builtins.range(0, num_arg_per_group)]\n    y = [lambda_input[i] for i in builtins.range(num_arg_per_group, num_args)]\n\n    if not isinstance(lambda_output, tuple):\n        lambda_output = (lambda_output,)\n\n    return tvm.tir.CommReducer(x, y, lambda_output, identities, span)\n\n\n@register\ndef llvm_lookup_intrinsic_id(name, span):\n    # pylint: disable=unused-argument\n    return codegen.llvm_lookup_intrinsic_id(name)\n\n\n@register\ndef FloorMod(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.FloorMod(x, y, span)\n\n\n@register\ndef FloorDiv(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.FloorDiv(x, y, span)\n\n\n@register\ndef Mul(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.Mul(x, y, span)\n\n\n@register\ndef Div(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.Div(x, y, span)\n\n\n@register\ndef Add(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.Add(x, y, span)\n\n\n@register\ndef Sub(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.Sub(x, y, span)\n\n\n@register\ndef LT(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.LT(x, y, span)\n\n\n@register\ndef LE(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.LE(x, y, span)\n\n\n@register\ndef GT(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.GT(x, y, span)\n\n\n@register\ndef GE(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.GE(x, y, span)\n\n\n@register\ndef EQ(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.EQ(x, y, span)\n\n\n@register\ndef NE(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.NE(x, y, span)\n\n\n@register\ndef And(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.And(x, y, span)\n\n\n@register\ndef Or(x, y, span):  # pylint: disable=invalid-name\n    return tvm.tir.Or(x, y, span)\n\n\n@register\ndef Cast(dtype, value, span):  # pylint: disable=invalid-name\n    return tvm.tir.Cast(dtype, value, span)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/node.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin\n\"\"\"TVM Script nodes.\"\"\"\n\nfrom typing import Optional, Union, List, Callable\nimport synr\nfrom tvm.arith import Analyzer\nfrom tvm.runtime import ObjectGeneric, convert\nfrom tvm.tir import PrimExpr, Buffer, BufferLoad, IntImm, Ramp, BufferRegion\nfrom tvm.ir import Span, Range\n\n\nclass Slice:\n    \"\"\"A helper class to present slice information for BufferSlice\n\n    Parameters\n    ----------\n    start : Union[PrimExpr, int]\n        The start index.\n\n    stop : Optional[Union[PrimExpr, int]]\n        The stop index, None means the Slice is an element-wise index\n\n    step : int\n        The slice step\n\n    span : Optional[Span]\n        The location of the slice in the source.\n    \"\"\"\n\n    start: Union[PrimExpr, int]\n    stop: Optional[Union[PrimExpr, int]]\n    step: int\n    span: Optional[Span]\n\n    def __init__(\n        self,\n        start: Union[PrimExpr, int],\n        stop: Optional[Union[PrimExpr, int]] = None,\n        step: int = 1,\n        span: Optional[Span] = None,\n    ):\n        self.start = start\n        self.stop = stop\n        self.step = step\n        self.span = span\n\n    def as_index_expr(self, report_error: Callable[[str, Union[Span, synr.ast.Span]], None]):\n        \"\"\"Helper to create index PrimExpr from slice object\n        Parameters\n        ----------\n        report_error: Callable[[str, Union[Span, synr.ast.Span]], None]\n            The error report func\n        \"\"\"\n        if self.stop is None:\n            # scalar index\n            return self.start\n        if self.step < 1:\n            report_error(\"Slice's step should be positive integer\", self.span)\n        lanes = Analyzer().simplify((self.stop - self.start + self.step - 1) // self.step)\n        if not isinstance(lanes, (int, IntImm)):\n            report_error(\"Slice's lanes should be constant for buffer indices\", self.span)\n        if lanes == 1:\n            return self.start\n        return Ramp(self.start, self.step, int(lanes), self.span)\n\n\nclass BufferSlice(ObjectGeneric):\n    \"\"\"A generic object for representing general buffer access. Following cases are supported:\n        - element wise access buffer[i, j], which can be converted to BufferLoad if necessary\n        - slice access buffer[i: i + 1, j : j + 2]\n        - union of element and slice buffer[i, j: j + 2]\n\n        This node is used in TVMScript to parse BufferLoad, BufferRegion and Realize\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer.\n\n    indices : List[Union[Slice, PrimExpr, int]]\n        The access indexes can be slice, PrimExpr or int.\n\n    report_error: Callable[[str, Union[Span, synr.ast.Span]], None]\n        The error report func\n\n    span : Optional[Span]\n        The location of the buffer access in the source.\n    \"\"\"\n\n    buffer: Buffer\n    slices: List[Slice]\n    report_error: Callable[[str, Union[Span, synr.ast.Span]], None]\n    span: Optional[Span]\n\n    def __init__(\n        self,\n        buffer: Buffer,\n        indices: List[Union[Slice, PrimExpr, int]],\n        report_error: Callable[[str, Union[Span, synr.ast.Span]], None],\n        span: Optional[Span] = None,\n    ):\n        def check_index(index: Union[int, PrimExpr]):\n            \"\"\"Check input index is non-negative integer or PrimExpr\"\"\"\n            if isinstance(index, int):\n                if index < 0:\n                    report_error(\"Negative index is not allowed during buffer access\", span)\n            elif isinstance(index, PrimExpr):\n                element_dtype = index.dtype.split(\"x\", maxsplit=1)[0]\n                if element_dtype[:3] != \"int\":\n                    report_error(\n                        \"index expected an integer type PrimExpr but got \" + str(index.dtype),\n                        index.span,\n                    )\n            else:\n                report_error(\n                    \"Unsupported index type, expected int or tvm.tir.PrimExpr, but got \"\n                    + str(type(index)),\n                    span,\n                )\n\n        slices: List[Union[Slice, BufferSlice]] = []\n        for index in indices:\n            if isinstance(index, Slice):\n                index.start, index.stop = [convert(_) for _ in [index.start, index.stop]]\n                check_index(index.start)\n                check_index(index.stop)\n                slices.append(index)\n            elif isinstance(index, (PrimExpr, int)):\n                check_index(index)\n                slices.append(Slice(index))\n            elif isinstance(index, BufferSlice):\n                buffer_load = index.asobject()\n                check_index(buffer_load)\n                slices.append(Slice(buffer_load))\n            else:\n                report_error(\n                    \"Unsupported index type for BufferSlice, \"\n                    + \"expected int, tvm.tir.PrimExpr, tvm.tir.Slice, but got \"\n                    + str(type(index)),\n                    span,\n                )\n\n        self.buffer = buffer\n        self.slices = slices\n        self.report_error = report_error\n        self.span = span\n\n    def __str__(self):\n        regions: List[str] = []\n        for s in self.slices:\n            if s.stop is None:\n                regions.append(str(s.start))\n            else:\n                regions.append(str(s.start) + \": \" + str(s.stop))\n\n        return self.buffer.name + \"[\" + \", \".join(regions) + \"]\"\n\n    def asobject(self) -> BufferLoad:\n        \"\"\"Convert object.\"\"\"\n        indices = [s.as_index_expr(self.report_error) for s in self.slices]\n        return BufferLoad(self.buffer, indices, span=self.span)\n\n    def as_buffer_region(self, analyzer: Optional[Analyzer] = None) -> BufferRegion:\n        \"\"\"Construct BufferRegion from BufferSlice\n\n        Parameters\n        ----------\n        analyzer : Optional[tvm.arith.Analyzer]\n            The analyzer for simplifying. If not provided, the method will construct a new one\n\n        Returns\n        -------\n        buffer_region : BufferRegion\n            The constructed BufferRegion.\n        \"\"\"\n        region: List[Range] = []\n        for s in self.slices:\n            start = s.start if isinstance(s.start, PrimExpr) else IntImm(\"int32\", s.start)\n            extent = IntImm(start.dtype, 1) if s.stop is None else s.stop - s.start\n            if not analyzer:\n                analyzer = Analyzer()\n            if isinstance(extent, PrimExpr):\n                extent = analyzer.simplify(extent)\n            if s.step != 1:\n                self.report_error(\"BufferRegion do not support non-trivial stride\", s.span)\n            region.append(Range.from_min_extent(start, extent, span=s.span))\n        return BufferRegion(self.buffer, region)\n\n    def astype(self, dtype: str, span: Optional[Span] = None) -> PrimExpr:\n        return self.asobject().astype(dtype, span)\n\n    @property\n    def dtype(self) -> str:\n        \"\"\"Return the dtype referenced by the slice.\n\n        Implemented as a property so that ``slice.dtype`` has the same\n        calling convention as ``primexpr.dtype``.  This allows a\n        BufferSlice object can be assigned to a variable without\n        requiring a type annotation on the variable, similar to other\n        expressions.\n        \"\"\"\n        return self.asobject().dtype\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/prim_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Interface for PrimFunc\"\"\"\n\nimport inspect\nfrom typing import Callable\n\nfrom tvm.tir.function import PrimFunc\nfrom ..parser import from_source\n\n\ndef prim_func(input_func: Callable) -> PrimFunc:\n    \"\"\"Decorate a python function as tvm script.\n\n    Parameters\n    ----------\n    func : input_func\n        The function to be parsed.\n\n    Returns\n    -------\n    output : PrimFunc\n        The result functions.\n    \"\"\"\n    if inspect.isfunction(input_func):\n        result = from_source(input_func)\n        result.__name__ = input_func.__name__\n        result.__qualname__ = input_func.__qualname__\n        return result\n\n    raise TypeError(\"Only function definitions are supported.\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/scope_handler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Scope Handler Classes\"\"\"\n# pylint: disable=redefined-builtin, unused-argument, invalid-name, relative-beyond-top-level\nfrom typing import Tuple, Any, Callable, Optional, List, Union, Mapping\n\nimport synr\nimport numpy as np\nimport tvm.tir\nfrom tvm.runtime import Object, String, convert\nfrom tvm.ir import Span, Range\nfrom tvm.tir import Stmt, PrimExpr, IterVar, Var, Buffer, BufferRegion, ForKind\n\nfrom .node import BufferSlice\n\nfrom ..context_maintainer import ContextMaintainer\nfrom ..registry import register\nfrom ..utils import (\n    get_param_list,\n    tvm_span_from_synr,\n    call_with_error_reporting,\n)\n\n\nclass ScopeHandler:\n    \"\"\"Base class for all scope handlers\"\"\"\n\n    def __init__(self, func: Callable):\n        self.func: Callable = func\n        self.body: Optional[Stmt] = None\n        self.node: Optional[synr.ast.Node] = None\n        self.context: Optional[ContextMaintainer] = None\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.\" + self.func.__name__, get_param_list(self.func)\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        pass\n\n    def exit_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        self.node = node\n        self.context = context\n        return call_with_error_reporting(\n            context.report_error, span, self.func, *arg_list, span=tvm_span_from_synr(span)\n        )\n\n\nclass WithScopeHandler(ScopeHandler):\n    \"\"\"Base class for all with scope handlers\"\"\"\n\n    def __init__(self, func, concise_scope, def_symbol):\n        super().__init__(func)\n        self.concise_scope = concise_scope\n        self.def_symbol = def_symbol\n\n    @staticmethod\n    def get_optional_vars(node, context):\n        \"\"\"Get a list synr.ast.With's optional_vars\"\"\"\n        assert isinstance(\n            node, synr.ast.With\n        ), f\"WithScopeHandler expected synr.ast.With but got {type(node)}\"\n\n        if isinstance(node.lhs, list):\n            for var in node.lhs:\n                if not isinstance(var, synr.ast.Var):\n                    context.report_error(\n                        f\"Invalid optional var definition, expected Var but got {type(var)}\",\n                        node.span,\n                    )\n            vars = node.lhs\n        else:\n            context.report_error(\n                f\"Invalid optional var definition, expected list of Var but got {type(node.lhs)}\",\n                node.span,\n            )\n        return vars\n\n\n@register\nclass Allocate(WithScopeHandler):\n    \"\"\"With scope handler T.allocate(extents, dtype, scope, condition, annotations)\"\"\"\n\n    def __init__(self):\n        def allocate(extents, dtype, scope, condition=True, annotations=None, span=None):\n            condition = tvm.runtime.convert(condition)\n            scope = tvm.runtime.convert(scope)\n\n            return tvm.tir.Allocate(\n                self.buffer_var,\n                dtype,\n                extents,\n                condition,\n                self.body,\n                annotations=annotations,\n                span=span,\n            )\n\n        super().__init__(allocate, concise_scope=True, def_symbol=True)\n        self.buffer_var = None\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        # define buffer vars in symbol table\n        if isinstance(node, synr.ast.With):\n            vars = WithScopeHandler.get_optional_vars(node, context)\n            if len(vars) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(vars)}\", node.span)\n            name = vars[0].id.name\n            var_span = vars[0].id.span\n        elif isinstance(node, synr.ast.Assign):\n            if len(node.lhs) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(node.lhs)}\", node.span)\n            name = node.lhs[0].id.name\n            var_span = node.lhs[0].id.span\n        else:\n            raise Exception(\"Internal Bug\")\n\n        def setup_buffer_var(\n            extents, dtype, scope, condition=True, annotations=None, span: Span = None\n        ):\n            \"\"\"Setup buffer var for a given type.\"\"\"\n            buffer_ptr_type = tvm.ir.PointerType(tvm.ir.PrimType(dtype), scope)\n            self.buffer_var = tvm.tir.Var(name, buffer_ptr_type, span)\n\n        setup_buffer_var(*arg_list, span=tvm_span_from_synr(var_span))\n        context.update_symbol(name, self.buffer_var, node)\n\n\n@register\nclass AllocateConst(WithScopeHandler):\n    \"\"\"With scope handler T.allocate_const(data, extents, dtype, condition)\n\n    TIR constant node to represent non-scalar constant\n    \"\"\"\n\n    def __init__(self):\n        def allocate_const(raw_data, dtype, shape, annotations=None, span=None):\n            list_data = []\n            for i in raw_data:\n                list_data.append(i.value)\n            nd_data = tvm.nd.array(np.asarray(list_data, dtype=dtype))\n            n = tvm.tir.AllocateConst(\n                self.buffer_var,\n                dtype,\n                shape,\n                nd_data,\n                self.body,\n                annotations=annotations,\n                span=span,\n            )\n            return n\n\n        super().__init__(allocate_const, concise_scope=True, def_symbol=True)\n        self.buffer_var = None\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        # define buffer vars in symbol table\n        if isinstance(node, synr.ast.With):\n            vars = WithScopeHandler.get_optional_vars(node, context)\n            if len(vars) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(vars)}\", node.span)\n            name = vars[0].id.name\n            var_span = vars[0].id.span\n        elif isinstance(node, synr.ast.Assign):\n            if len(node.lhs) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(node.lhs)}\", node.span)\n            name = node.lhs[0].id.name\n            var_span = node.lhs[0].id.span\n        else:\n            raise Exception(\"Internal Bug\")\n\n        def setup_buffer_var(data, dtype, shape, annotations: dict = None, span: Span = None):\n            \"\"\"Setup buffer var for a given type.\"\"\"\n            buffer_ptr_type = tvm.ir.PointerType(tvm.ir.PrimType(dtype))\n            self.buffer_var = tvm.tir.Var(name, buffer_ptr_type, span)\n\n        setup_buffer_var(*arg_list, span=tvm_span_from_synr(var_span))\n        context.update_symbol(name, self.buffer_var, node)\n\n\n@register\nclass DeclBuffer(WithScopeHandler):\n    \"\"\"Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,\n                                offset_factor, buffer_type, axis_separators)\n    Example\n    -------\n    .. code-block:: python\n        A = T.decl_buffer((128, 128), dtype=\"float32\")\n    \"\"\"\n\n    def __init__(self):\n        def decl_buffer(\n            shape,\n            dtype=\"float32\",\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            axis_separators=None,\n            span=None,\n        ):\n            decl_buffer = tvm.tir.DeclBuffer(self.buffer, self.body, span=span)\n            if data is None:\n                # when data is not specified, the buffer is implicitly allocated\n                return tvm.tir.Allocate(\n                    self.buffer.data,\n                    dtype,\n                    shape,\n                    tvm.runtime.convert(True),\n                    decl_buffer,\n                    span=span,\n                )\n            return decl_buffer\n\n        super().__init__(decl_buffer, concise_scope=True, def_symbol=True)\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        # define buffer vars in symbol table\n        if isinstance(node, synr.ast.With):\n            vars = WithScopeHandler.get_optional_vars(node, context)\n            if len(vars) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(vars)}\", node.span)\n            name = vars[0].id.name\n            var_span = vars[0].id.span\n        elif isinstance(node, synr.ast.Assign):\n            if len(node.lhs) != 1:\n                context.report_error(f\"Unexpected number of vars: 1 vs. {len(node.lhs)}\", node.span)\n            name = node.lhs[0].id.name\n            var_span = node.lhs[0].id.span\n        else:\n            raise Exception(\"Internal Bug\")\n\n        def setup_buffer(\n            shape,\n            dtype,\n            data,\n            strides,\n            elem_offset,\n            scope,\n            align,\n            offset_factor,\n            buffer_type,\n            axis_separators,\n            span: Span = None,\n        ):\n            self.buffer = tvm.tir.decl_buffer(\n                shape=shape,\n                dtype=dtype,\n                data=data,\n                strides=strides,\n                elem_offset=elem_offset,\n                scope=scope,\n                data_alignment=align,\n                offset_factor=offset_factor,\n                buffer_type=buffer_type,\n                axis_separators=axis_separators,\n                name=name,\n                span=span,\n            )\n\n        setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))\n        context.update_symbol(name, self.buffer, node)\n\n\n@register\nclass LaunchThread(WithScopeHandler):\n    \"\"\"With scope handler T.launch_thread(env_var, extent)\"\"\"\n\n    def __init__(self):\n        def launch_thread(env_var, extent, span):\n            extent = tvm.runtime.convert(extent, span=span)\n            thread_id = self.context.func_var_env_dict[env_var]\n            attr_key = \"virtual_thread\" if thread_id == \"vthread\" else \"thread_extent\"\n            return tvm.tir.AttrStmt(\n                IterVar(\n                    (0, extent),\n                    env_var,\n                    getattr(IterVar, \"ThreadIndex\"),\n                    thread_id,\n                    span=span,\n                ),\n                attr_key,\n                extent,\n                self.body,\n                span=span,\n            )\n\n        super().__init__(launch_thread, concise_scope=True, def_symbol=False)\n\n\n@register\nclass Realize(WithScopeHandler):\n    \"\"\"With scope handler T.realize(buffer_bounds, scope, condition)\"\"\"\n\n    def __init__(self):\n        def realize(\n            buffer_slice: BufferSlice, scope: str, condition: bool = True, span: bool = None\n        ):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            buffer: Buffer = buffer_slice.buffer\n            bounds: List[Range] = []\n            for s in buffer_slice.slices:\n                min: Union[PrimExpr, int] = s.start\n                extent: Union[PrimExpr, int] = 1 if s.stop is None else s.stop - s.start\n                if isinstance(extent, PrimExpr):\n                    extent = self.context.analyzer.simplify(extent)\n                bounds.append(Range.from_min_extent(min, extent, span=s.span))\n\n            scope = tvm.runtime.convert(scope, span=span)\n            return tvm.tir.AttrStmt(\n                buffer,\n                \"realize_scope\",\n                scope,\n                tvm.tir.BufferRealize(buffer, bounds, condition, self.body, span=span),\n                span=span,\n            )\n\n        super().__init__(realize, concise_scope=True, def_symbol=False)\n\n\n@register\nclass Attr(WithScopeHandler):\n    \"\"\"With scope handler T.attr(attr_node, attr_key, value)\"\"\"\n\n    def __init__(self):\n        def attr(attr_node, attr_key, value, span):\n            attr_node = tvm.runtime.convert(attr_node, span=span)\n            value = tvm.runtime.convert(value, span=span)\n            return tvm.tir.AttrStmt(attr_node, attr_key, value, self.body, span=span)\n\n        super().__init__(attr, concise_scope=True, def_symbol=False)\n\n\n@register\nclass AssertHandler(WithScopeHandler):\n    \"\"\"With scope handler T.Assert(condition, message)\"\"\"\n\n    def __init__(self):\n        def Assert(condition, message, span):\n            return tvm.tir.AssertStmt(condition, tvm.runtime.convert(message), self.body, span=span)\n\n        super().__init__(Assert, concise_scope=True, def_symbol=False)\n\n\n@register\nclass Let(WithScopeHandler):\n    \"\"\"With scope handler T.let(var, value)\"\"\"\n\n    def __init__(self):\n        def let(var, value, span):\n            return tvm.tir.LetStmt(var, value, self.body, span=span)\n\n        super().__init__(let, concise_scope=False, def_symbol=False)\n\n    def __call__(self, var: tvm.tir.Var, value: tvm.tir.PrimExpr, body: tvm.tir.PrimExpr):\n        return tvm.tir.Let(var, value, body)\n\n\n@register\nclass Block(WithScopeHandler):\n    \"\"\"With scope handler T.block(name)\"\"\"\n\n    def __init__(self):\n        def block(name_hint: str = \"\", span: Optional[Span] = None):\n            assert (\n                self.node and self.context and self.body\n            ), \"call 'exit_scope' before 'enter_scope'\"\n            block_info = self.context.block_info_stack[-1]\n\n            # create block read/write regions\n            reads: List[BufferRegion] = (\n                [read.as_buffer_region() for read in block_info.reads] if block_info.reads else []\n            )\n            writes: List[BufferRegion] = (\n                [write.as_buffer_region() for write in block_info.writes]\n                if block_info.writes\n                else []\n            )\n\n            region_detect_mask: int = (block_info.reads is None) | (\n                (block_info.writes is None) << 1\n            )\n            annotations = {} if block_info.annotations is None else block_info.annotations\n            if region_detect_mask != 0:\n                annotations[\"tir.script_parsing_detect_access\"] = region_detect_mask\n            inner = tvm.tir.Block(\n                block_info.iter_vars,\n                reads,\n                writes,\n                name_hint,\n                self.body,\n                block_info.init,\n                block_info.alloc_buffers,\n                block_info.match_buffers,\n                annotations,\n                span,\n            )\n            assert len(block_info.iter_vars) == len(block_info.iter_values)\n            predicate = (\n                tvm.tir.const(True, \"bool\")\n                if block_info.predicate is None\n                else block_info.predicate\n            )\n            body = tvm.tir.BlockRealize(block_info.iter_values, predicate, inner, span)\n            return body\n\n        super().__init__(func=block, concise_scope=False, def_symbol=True)\n        self.block_vars = None\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        # define block vars\n        assert isinstance(\n            node, synr.ast.With\n        ), f\"BlockScopeHandler expected to work on synr.ast.With but got {type(node)}\"\n\n        optional_vars = [var.id.name for var in WithScopeHandler.get_optional_vars(node, context)]\n        if optional_vars:\n            context.report_error(\n                f\"Block expected no optional_vars (e.g., `x` in `with block() as x`), \"\n                f\"but got {optional_vars}\",\n                node.span,\n            )\n\n\n@register\nclass InitBlock(WithScopeHandler):\n    \"\"\"With scope handler T.init()\"\"\"\n\n    def __init__(self):\n        def init(span: Span = None):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            if self.context.block_info_stack[-2].init is not None:\n                self.context.report_error(\"Duplicate init block declaration\", span)\n            self.context.block_info_stack[-2].init = self.body\n\n        super().__init__(func=init, concise_scope=False, def_symbol=True)\n\n\nclass LoopInfo:\n    \"\"\"Helper class for loop information\"\"\"\n\n    loop_var: Var\n    begin: PrimExpr\n    extent: PrimExpr\n    kind: ForKind\n    thread_binding: Optional[str]\n    annotations: Optional[Mapping[str, Object]]\n\n    def __init__(\n        self,\n        begin: PrimExpr,\n        extent: PrimExpr,\n        kind: ForKind,\n        thread_binding: Optional[str] = None,\n        annotations: Optional[Mapping[str, Object]] = None,\n    ) -> None:\n        self.begin = begin\n        self.extent = extent\n        self.kind = kind\n        self.thread_binding = thread_binding\n        self.annotations = annotations\n\n\nclass ForScopeHandler(ScopeHandler):\n    \"\"\"Base class for all for scope handlers\"\"\"\n\n    def __init__(self, func):\n        super().__init__(func)\n        self.loop_vars: List[Var] = []\n        self.loop_info: List[LoopInfo] = []\n\n    def enter_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        assert isinstance(\n            node, synr.ast.For\n        ), f\"ForScopeHandler expected synr.ast.For but got {type(node)}\"\n\n        loop_var_names = list()\n        spans = list()\n        if isinstance(node.lhs, synr.ast.Var):\n            loop_var_names.append(node.lhs.id.name)\n            spans.append(tvm_span_from_synr(node.lhs.id.span))\n        elif isinstance(node.lhs, list):\n            for elt in node.lhs:\n                if not isinstance(elt, synr.ast.Var):\n                    context.report_error(\n                        f\"Invalid loop var. Expected a var, but got {type(elt)}\", elt.span\n                    )\n                loop_var_names.append(elt.id.name)\n                spans.append(tvm_span_from_synr(elt.id.span))\n        else:\n            context.report_error(\n                f\"Invalid loop var. Expected var or list of vars as lhs, but got {type(node.lhs)}\",\n                span,\n            )\n\n        self.node = node\n        self.context = context\n        # collect loop infos by calling self.func\n        call_with_error_reporting(context.report_error, span, self.func, *arg_list)\n        if len(loop_var_names) != len(self.loop_info):\n            self.context.report_error(\n                f\"Inconsistent number of vars and loops, got {len(loop_var_names)} \"\n                + f\"vs {len(self.loop_info)}\",\n                self.node.span,\n            )\n        # generate loop vars\n        self.loop_vars = []\n        for name, lv_span, li in zip(loop_var_names, spans, self.loop_info):\n            if not li.begin.dtype.startswith(\"int\"):\n                raise NotImplementedError(f\"Unsupported dtype in loop begin: {li.begin.dtype}\")\n            if not li.extent.dtype.startswith(\"int\"):\n                raise NotImplementedError(f\"Unsupported dtype in loop extent: {li.extent.dtype}\")\n            dtype = \"int64\" if \"int64\" in [li.begin.dtype, li.extent.dtype] else \"int32\"\n            self.loop_vars.append(tvm.te.var(name, dtype=dtype, span=lv_span))\n\n        for loop_var, loop_info in zip(self.loop_vars, self.loop_info):\n            context.update_symbol(loop_var.name, loop_var, node)\n            context.loop_stack[loop_var] = Range.from_min_extent(loop_info.begin, loop_info.extent)\n\n    def exit_scope(\n        self,\n        node: synr.ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        assert self.loop_vars, \"call 'exit_scope' before 'enter_scope'\"\n        for loop_var in self.loop_vars:\n            context.loop_stack.pop(loop_var)\n        # Use assert here since we have check it in `enter_scope`\n        assert len(self.loop_vars) == len(self.loop_info)\n\n        body = self.body\n        for var, info in zip(reversed(self.loop_vars), reversed(self.loop_info)):\n            body = tvm.tir.For(\n                var,\n                info.begin,\n                info.extent,\n                info.kind,\n                body,\n                info.thread_binding,\n                info.annotations,\n                span=tvm_span_from_synr(span),\n            )\n\n        return body\n\n    def create_loop_info(\n        self,\n        begin: Optional[PrimExpr],\n        end: PrimExpr,\n        kind: ForKind,\n        thread_binding: Optional[str] = None,\n        annotations: Optional[Mapping[str, Object]] = None,\n    ) -> None:\n        \"\"\"\n        Helper function for creating For in TVM Script parser.\n\n        Parameters\n        ----------\n        begin : Optional[PrimExpr]\n            The beginning value. If None, it will be set to 0.\n\n        end : PrimExpr\n            The endding value.\n\n        kind : ForKind\n            The type of the for.\n\n        thread_binding: Optional[str]\n            The thread this loop binds to.\n\n        annotations : Optional[Mapping[str, Object]]\n            Additional annotation hints.\n\n        span : Optional[Span]\n            The location of this for in the source code.\n\n        Returns\n        -------\n        for : For\n            The constructed For.\n        \"\"\"\n        end = convert(end)\n        if begin is None:\n            begin = tvm.tir.const(0, end.dtype)\n        else:\n            begin = convert(begin)\n        assert self.context and self.node, \"call 'exit_scope' before 'enter_scope'\"\n        extent = (\n            end\n            if self.context.analyzer.can_prove_equal(begin, 0)\n            else self.context.analyzer.simplify(end - begin)\n        )\n        self.annotations: Mapping[str, Object] = {}\n        if annotations is not None:\n            self.annotations = {\n                key: String(val) if isinstance(val, str) else val\n                for key, val in annotations.items()\n            }\n\n        self.loop_info.append(LoopInfo(begin, extent, kind, thread_binding, annotations))\n\n\n@register\nclass Serial(ForScopeHandler):\n    \"\"\"For scope handler T.serial(begin, end, annotations)\"\"\"\n\n    def __init__(self):\n        def serial(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if end is None:\n                end, begin = begin, end\n            self.create_loop_info(begin, end, ForKind.SERIAL, annotations=annotations)\n\n        super().__init__(serial)\n\n\n@register\nclass Parallel(ForScopeHandler):\n    \"\"\"For scope handler T.parallel(begin, end, annotations)\"\"\"\n\n    def __init__(self):\n        def parallel(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if end is None:\n                end, begin = begin, end\n            self.create_loop_info(begin, end, ForKind.PARALLEL, annotations=annotations)\n\n        super().__init__(parallel)\n\n\n@register\nclass Vectorized(ForScopeHandler):\n    \"\"\"For scope handler T.vectorized(begin, end, annotations)\"\"\"\n\n    def __init__(self):\n        def vectorized(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if end is None:\n                end, begin = begin, end\n            self.create_loop_info(begin, end, ForKind.VECTORIZED, annotations=annotations)\n\n        super().__init__(vectorized)\n\n\n@register\nclass Unroll(ForScopeHandler):\n    \"\"\"For scope handler T.unroll(begin, end, annotations)\"\"\"\n\n    def __init__(self):\n        def unroll(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if end is None:\n                end, begin = begin, end\n            self.create_loop_info(begin, end, ForKind.UNROLLED, annotations=annotations)\n\n        super().__init__(unroll)\n\n\n@register\nclass ThreadBinding(ForScopeHandler):\n    \"\"\"For scope handler T.thread_binding(begin, end, thread, annotations)\"\"\"\n\n    def __init__(self):\n        def thread_binding(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            thread: str = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if thread is None:\n                if isinstance(end, str):  # handle case like thread_binding(128, \"threadIdx.x\")\n                    thread = end\n                    end = None\n                else:\n                    raise ValueError(\"Thread cannot be None for thread_binding\")\n            if end is None:\n                end, begin = begin, end\n            thread_iter_var = IterVar(None, None, IterVar.ThreadIndex, thread)\n            self.create_loop_info(\n                begin,\n                end,\n                ForKind.THREAD_BINDING,\n                thread_binding=thread_iter_var,\n                annotations=annotations,\n            )\n\n        super().__init__(thread_binding)\n\n\n@register\nclass RangeHandler(ForScopeHandler):\n    \"\"\"For scope handler range(begin, end, annotations)\n    Note that tir.range is totally the same as T.serial\n    \"\"\"\n\n    def __init__(self):\n        def for_range(\n            begin: PrimExpr,\n            end: PrimExpr = None,\n            annotations: Optional[Mapping[str, Object]] = None,\n        ):\n            if end is None:\n                end, begin = begin, end\n            self.create_loop_info(begin, end, ForKind.SERIAL, annotations=annotations)\n\n        super().__init__(for_range)\n\n    def signature(self):\n        return \"range\", get_param_list(self.func)\n\n\n@register\nclass Grid(ForScopeHandler):\n    \"\"\"For scope handler T.grid(extents)\"\"\"\n\n    def __init__(self):\n        def grid(*extents: List[PrimExpr]):\n            for extent in extents:\n                self.create_loop_info(None, extent, ForKind.SERIAL)\n\n        super().__init__(grid)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/special_stmt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Special Stmt Classes\"\"\"\n# pylint: disable=unused-argument, no-self-argument, inconsistent-return-statements\n# pylint: disable=relative-beyond-top-level\nfrom typing import Callable, List, Optional, Tuple, Any, Mapping, Union\n\nimport synr\nfrom synr import ast\nfrom tvm.ir.expr import PrimExpr, Range\n\nimport tvm.tir\nfrom tvm.runtime import Object, String\nfrom tvm.target import Target\nfrom tvm.ir import Span\nfrom tvm.tir import IntImm, IterVar, Var\n\nfrom .node import BufferSlice\n\nfrom ..context_maintainer import BlockInfo, ContextMaintainer\nfrom ..registry import register\nfrom ..utils import (\n    get_param_list,\n    tvm_span_from_synr,\n    call_with_error_reporting,\n)\n\n\ndef convert_to_int(\n    value: Union[IntImm, int],\n    arg_name: str,\n    report_error: Callable,\n    span: Union[Span, synr.ast.Span],\n) -> int:\n    \"\"\"convert a const int or TVM IntImm to Python int.\n    Reports an error when input cannot be converted to int.\n\n    Parameters\n    ----------\n    value : Union[tvm.tir.IntImm, int]\n        The input value to be converted.\n    arg_name : str\n        Function argument name for error reporting.\n    report_error: Callable\n        The report error function handle\n    span : Union[synr.ast.Span, tvm.ir.Span]\n        Location of the error\n    \"\"\"\n    if isinstance(value, IntImm):\n        return value.value\n    if isinstance(value, int):\n        return value\n    report_error(\n        f\"Expected int or IntImm for {arg_name}, but got {str(type(value))}\",\n        span,\n    )\n\n\nclass SpecialStmt:\n    \"\"\"Base class for all Special Stmts\"\"\"\n\n    def __init__(self, func: Callable, def_symbol: bool):\n        self.func: Callable = func\n        self.def_symbol: bool = def_symbol\n        self.node: Optional[synr.ast.Node] = None\n        self.context: Optional[ContextMaintainer] = None\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.\" + self.func.__name__, get_param_list(self.func)\n\n    def handle(\n        self,\n        node: ast.Node,\n        context: ContextMaintainer,\n        arg_list: List[Any],\n        span: synr.ast.Span,\n    ):\n        self.node = node\n        self.context = context\n        return call_with_error_reporting(\n            context.report_error, span, self.func, *arg_list, span=tvm_span_from_synr(span)\n        )\n\n\n@register\nclass MatchBuffer(SpecialStmt):\n    \"\"\"Special Stmt match_buffer(param, shape, dtype, data, strides, elem_offset, scope, align,\n                                 offset_factor, buffer_type, axis_separators)\n\n    Note\n    ----\n    This Special Stmt will perform different behavior depends on the type of param.\n    If the param is a var in function parameter, it will create a buffer from DLTensor.\n    Else if the param is a subregion of other buffers, then create a subregion match inside a block.\n\n    Example\n    -------\n    Match buffer from function parameter\n    .. code-block:: python\n        A = T.match_buffer(a, (128, 128), dtype=\"float32\")\n\n    Match buffer from Buffer subregion\n    .. code-block:: python\n        A = T.match_buffer(B[0:128, i * 128 : i * 128 + 128], (128, 128), dtype=\"float32\")\n    \"\"\"\n\n    def __init__(self):\n        def match_buffer(\n            param,\n            shape=None,\n            dtype=None,\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            axis_separators=None,\n            span=None,\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`match_buffer` must be assigned to a single buffer, \"\n                    \"e.g. A = match_buffer(...)\",\n                    self.node.span,\n                )\n            if strides is None:\n                strides = []\n            align = convert_to_int(align, \"align\", self.context.report_error, self.node.span)\n            offset_factor = convert_to_int(\n                offset_factor, \"offset_factor\", self.context.report_error, self.node.span\n            )\n            buffer_name: str = self.node.lhs[0].id.name\n\n            if isinstance(param, tvm.tir.Var):\n                if shape is None:\n                    self.context.report_error(\n                        \"Shape must be specified when binding input param\",\n                        self.node.rhs.span,\n                    )\n\n                if dtype is None:\n                    dtype = \"float32\"\n\n                buffer = tvm.tir.decl_buffer(\n                    shape,\n                    dtype,\n                    buffer_name,\n                    data,\n                    strides,\n                    elem_offset,\n                    scope,\n                    align,\n                    offset_factor,\n                    buffer_type,\n                    axis_separators,\n                    span=span,\n                )\n                if param not in self.context.func_params:\n                    self.context.report_error(\n                        \"Can not bind non-input param to buffer\", self.node.rhs.params[0].span\n                    )\n                self.context.func_buffer_map[param] = buffer\n\n            elif isinstance(param, BufferSlice):\n                buffer_region = param.as_buffer_region()\n\n                if shape is None:\n                    shape = [dim.extent for dim in buffer_region.region]\n\n                if dtype is None:\n                    dtype = buffer_region.buffer.dtype\n\n                if elem_offset is None and offset_factor == 0:\n                    offset_factor = 1\n\n                buffer = tvm.tir.decl_buffer(\n                    shape,\n                    dtype,\n                    buffer_name,\n                    data,\n                    strides,\n                    elem_offset,\n                    scope,\n                    align,\n                    offset_factor,\n                    buffer_type,\n                    axis_separators,\n                    span=span,\n                )\n\n                self.context.current_block_scope().match_buffers.append(\n                    tvm.tir.MatchBufferRegion(buffer, buffer_region)\n                )\n            else:\n                self.context.report_error(\n                    \"The source of match_buffer expected Var or BufferSlice, but got \"\n                    + str(type(param)),\n                    self.node.rhs.params[0].span,\n                )\n            self.context.update_symbol(buffer_name, buffer, self.node)\n\n        super().__init__(match_buffer, def_symbol=True)\n\n\n@register\nclass BufferDeclare(SpecialStmt):\n    \"\"\"Special Stmt buffer_decl(shape, dtype, data, strides, elem_offset, scope, align,\n                                offset_factor, buffer_type, axis_separators)\n    Example\n    -------\n    .. code-block:: python\n        A = T.buffer_decl((128, 128), dtype=\"float32\")\n    \"\"\"\n\n    def __init__(self):\n        def buffer_decl(\n            shape,\n            dtype=\"float32\",\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            axis_separators=None,\n            span=None,\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`buffer_decl` must be assigned to a single buffer, e.g. A = buffer_decl(...)\",\n                    self.node.span,\n                )\n\n            if strides is None:\n                strides = []\n            align = convert_to_int(align, \"align\", self.context.report_error, self.node.span)\n            offset_factor = convert_to_int(\n                offset_factor, \"offset_factor\", self.context.report_error, self.node.span\n            )\n            buffer_name: str = self.node.lhs[0].id.name\n            buffer = tvm.tir.decl_buffer(\n                shape,\n                dtype,\n                buffer_name,\n                data,\n                strides,\n                elem_offset,\n                scope,\n                align,\n                offset_factor,\n                buffer_type,\n                axis_separators,\n                span=span,\n            )\n            self.context.update_symbol(buffer_name, buffer, self.node)\n            return buffer\n\n        super().__init__(buffer_decl, def_symbol=True)\n\n\n@register\nclass AllocBuffer(SpecialStmt):\n    \"\"\"Special function alloc_buffer(shape, dtype, data, strides, elem_offset, scope, align,\n                                     offset_factor, buffer_type, axis_separators)\n\n    Example\n    -------\n    .. code-block:: python\n\n        A = T.alloc_buffer((128, 128), dtype=\"float32\")\n    \"\"\"\n\n    def __init__(self):\n        def alloc_buffer(\n            shape,\n            dtype=\"float32\",\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            axis_separators=None,\n            span=None,\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`alloc_buffer` must be assigned to a single buffer, \"\n                    \"e.g. A = alloc_buffer(...)\",\n                    self.node.span,\n                )\n\n            if strides is None:\n                strides = []\n            align = convert_to_int(align, \"align\", self.context.report_error, self.node.span)\n            offset_factor = convert_to_int(\n                offset_factor, \"offset_factor\", self.context.report_error, self.node.span\n            )\n            buffer_name: str = self.node.lhs[0].id.name\n            buffer = tvm.tir.decl_buffer(\n                shape,\n                dtype,\n                buffer_name,\n                data,\n                strides,\n                elem_offset,\n                scope,\n                align,\n                offset_factor,\n                buffer_type,\n                axis_separators,\n                span=span,\n            )\n            if self.context.current_block_scope():\n                self.context.current_block_scope().alloc_buffers.append(buffer)\n            else:\n                # If it is allocated outside all blocks, allocate it under root block.\n                self.context.root_alloc_buffers.append(buffer)\n            self.context.update_symbol(buffer_name, buffer, self.node)\n\n        super().__init__(alloc_buffer, def_symbol=True)\n\n\n@register\nclass BlockReads(SpecialStmt):\n    \"\"\"Special function reads([read_regions], *other_regions)\n\n    Note\n    ----\n    *other_region is an unpackable list of BufferSlice to support\n    reads syntax sugar like reads(BufferRegion1, BufferRegion2, ...)\n\n    Example\n    -------\n    .. code-block:: python\n\n        T.reads([A[vi: vi + 4, vk: vk + 4], B[vk: vk + 4, vj]])\n    \"\"\"\n\n    def __init__(self):\n        def reads(\n            *read_regions: Union[BufferSlice, List[BufferSlice]],\n            span: Span = None,\n        ):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            block_scope = self.context.current_block_scope()\n            if block_scope is None:\n                self.context.report_error(\n                    \"Expected to declare read regions inside a block.\",\n                    span,\n                )\n            if block_scope.reads is not None:\n                self.context.report_error(\n                    \"Duplicate write region declaration, \"\n                    + \"previous one is \"\n                    + str(\", \".join(str(x) for x in block_scope.reads)),\n                    span,\n                )\n            if len(read_regions) > 1:\n                for read_region in read_regions:\n                    if not isinstance(read_region, BufferSlice):\n                        self.context.report_error(\n                            \"Incorrect input type. Expected *BufferSlice or List[BufferSlice],\"\n                            + f\" but got {type(read_regions)}\",\n                            span,\n                        )\n            elif len(read_regions) == 1:\n                if isinstance(read_regions[0], list):\n                    read_regions = read_regions[0]\n\n            block_scope.reads = read_regions\n\n        super().__init__(reads, def_symbol=False)\n\n\n@register\nclass BlockWrites(SpecialStmt):\n    \"\"\"Special function writes([write_regions], *other_regions)\n\n    Note\n    ----\n    *other_region is an unpackable list of BufferSlice to support\n    writes syntax sugar like writes(BufferRegion1, BufferRegion2, ...)\n\n    Example\n    -------\n    .. code-block:: python\n\n        T.writes([C[vi: vi + 4, vj])\n    \"\"\"\n\n    def __init__(self):\n        def writes(\n            *write_regions: Union[BufferSlice, List[BufferSlice]],\n            span: Span = None,\n        ):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            block_scope = self.context.current_block_scope()\n            if block_scope is None:\n                self.context.report_error(\n                    \"Expected to declare write regions inside a block.\",\n                    span,\n                )\n            if block_scope.writes is not None:\n                self.context.report_error(\n                    \"Duplicate write region declaration, \"\n                    + \"previous one is \"\n                    + str(\", \".join(str(x) for x in block_scope.writes)),\n                    span,\n                )\n            if len(write_regions) > 1:\n                for write_region in write_regions:\n                    if not isinstance(write_region, BufferSlice):\n                        self.context.report_error(\n                            \"Incorrect input type. Expected *BufferSlice or List[BufferSlice],\"\n                            + f\" but got {type(write_regions)}\",\n                            span,\n                        )\n            elif len(write_regions) == 1:\n                if isinstance(write_regions[0], list):\n                    write_regions = write_regions[0]\n            block_scope.writes = write_regions\n\n        super().__init__(writes, def_symbol=False)\n\n\n@register\nclass BlockAttr(SpecialStmt):\n    \"\"\"Special function block_attr({attr_key: attr_value})\n\n    Example\n    -------\n    .. code-block:: python\n\n        T.block_attr({\"double_buffer_scope\": 1})\n    \"\"\"\n\n    def __init__(self):\n        def block_attr(attrs: Mapping[str, Object], span: Span = None):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            block_scope = self.context.current_block_scope()\n            if block_scope is None:\n                self.context.report_error(\n                    \"Expected to declare block annotations inside a block.\",\n                    span,\n                )\n            if block_scope.annotations is not None:\n                self.context.report_error(\n                    \"Duplicate block annotations declaration, \"\n                    + \"previous one is \"\n                    + str(block_scope.annotations),\n                    span,\n                )\n            attrs = {\n                key: String(val) if isinstance(val, str) else val for key, val in attrs.items()\n            }\n            block_scope.annotations = attrs\n\n        super().__init__(block_attr, def_symbol=False)\n\n\nclass BlockAxis(SpecialStmt):\n    \"\"\"Special stmt for defining a spatial block axis\n    axis.S(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.S(128, i * 4 + j)\n    \"\"\"\n\n    def axis(\n        self,\n        var_name: str,\n        dom: Union[PrimExpr, Range],\n        value: PrimExpr,\n        iter_type: int,\n        span: Optional[Span] = None,\n    ) -> None:\n        \"\"\"\n        Helper function for creating block axis\n\n        Parameters\n        ----------\n        var_name : str\n            The name_hint of var\n\n        dom : Union[PrimExpr, Range]\n            The iter domain.\n\n        value : PrimExpr\n            The binding value\n\n        iter_type : int\n            The iteration type.\n\n        span : Optional[Span]\n            The location of this for in the source code.\n        \"\"\"\n        assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n        block_scope: BlockInfo = self.context.current_block_scope()\n        if block_scope is None:\n            self.context.report_error(\n                \"Expected to declare block axes inside a block.\",\n                self.node.span,\n            )\n        if var_name in [iter_var.var.name for iter_var in block_scope.iter_vars]:\n            self.context.report_error(\"Duplicate block axis \" + var_name, self.node.span)\n\n        dom = tvm.runtime.convert(dom)\n        if isinstance(dom, PrimExpr):\n            dom = tvm.ir.Range(dom)\n        elif isinstance(dom, tvm.ir.container.Array) and len(dom) == 2:\n            dom = tvm.ir.Range(dom[0], dom[1])\n        elif not isinstance(dom, tvm.ir.Range):\n            self.context.report_error(\n                f\"Block axis domain expected PrimExpr or Range, but got {type(dom)}\",\n                self.node.span,\n            )\n        block_var = tvm.tir.Var(var_name, dtype=dom.extent.dtype)\n        value = tvm.runtime.convert(value)\n        if not isinstance(value, PrimExpr):\n            self.context.report_error(\n                f\"Block axis value expected PrimExpr, but got {type(value)}\",\n                self.node.span,\n            )\n        iter_var = tvm.tir.IterVar(dom, block_var, iter_type)\n        block_scope.iter_vars.append(iter_var)\n        block_scope.iter_values.append(value)\n        self.context.update_symbol(var_name, block_var, self.node)\n\n\n@register\nclass BlockAxisSpatial(BlockAxis):\n    \"\"\"Special stmt for defining a spatial block axis\n    axis.spatial(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.spatial(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_spatial(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.spatial` must be assigned to a var, e.g. vi = axis.spatial(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.DataPar)\n\n        super().__init__(axis_spatial, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.spatial\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisS(BlockAxis):\n    \"\"\"The sugar special stmt for defining a spatial block axis\n    axis.S(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.S(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_spatial(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.S` must be assigned to a var, e.g. vi = axis.S(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.DataPar)\n\n        super().__init__(axis_spatial, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.S\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisReduce(BlockAxis):\n    \"\"\"Special stmt for defining a reduce block axis\n    axis.reduce(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.reduce(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_reduce(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.reduce` must be assigned` to a var, e.g. vi = axis.reduce(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.CommReduce)\n\n        super().__init__(axis_reduce, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.reduce\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisR(BlockAxis):\n    \"\"\"The sugar special stmt for defining a reduce block axis\n    axis.R(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.R(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_reduce(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.R` must be assigned to a var, e.g. vi = axis.R(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.CommReduce)\n\n        super().__init__(axis_reduce, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.R\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisScan(BlockAxis):\n    \"\"\"Special stmt for defining a ordered block axis\n    axis.scan(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.scan(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_scan(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.scan` must be assigned to a var, e.g. vi = axis.scan(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.Ordered)\n\n        super().__init__(axis_scan, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.scan\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisOpaque(BlockAxis):\n    \"\"\"Special stmt for defining a opaque block axis\n    axis.opaque(dom, iter_value)\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi = T.axis.opaque(128, k)\n    \"\"\"\n\n    def __init__(self):\n        def axis_opaque(\n            dom: Union[PrimExpr, Tuple[PrimExpr, PrimExpr]], value: PrimExpr, span: Span = None\n        ):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) == 1:\n                self.context.report_error(\n                    \"`axis.opaque` must be assigned to a var, e.g. vi = axis.opaque(...)\",\n                    self.node.span,\n                )\n            self.axis(self.node.lhs[0].id.name, dom, value, IterVar.DimInfo)\n\n        super().__init__(axis_opaque, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.opaque\", get_param_list(self.func)\n\n\n@register\nclass BlockAxisRemap(BlockAxis):\n    \"\"\"Special stmt for remapping loops vars to block axes.\n    axis.remap(iter_type, iter_value)\n\n    Note\n    ----\n    Iter_type is a string consisting of 'S' and 'R', where 'S' means\n    for spatial and 'R' means for reduce.\n\n    Example\n    -------\n    .. code-block:: python\n\n        vi, vj = T.axis.remap(\"SS\", [i, j])\n    \"\"\"\n\n    def __init__(self):\n        def axis_remap(iter_types: str, loop_vars: List[tvm.tir.expr.Var], span: Span = None):\n            if not isinstance(self.node, ast.Assign) or not len(self.node.lhs) >= 1:\n                self.context.report_error(\n                    \"`axis.remap` must be assigned to one or more vars, \"\n                    \"e.g. vi, vj = axis.remap(...)\",\n                    self.node.span,\n                )\n            var_num: int = len(self.node.lhs)\n            if var_num != len(iter_types):\n                self.context.report_error(\n                    f\"`iter_type` expected {var_num} charactor(s), \"\n                    f\"but got {len(iter_types)}: {iter_types}\",\n                    span,\n                )\n            if var_num != len(loop_vars):\n                self.context.report_error(\n                    f\"`iter_type` expected {var_num} loop var(s), \"\n                    f\"but got {len(loop_vars)}: {loop_vars}\",\n                    span,\n                )\n            for var, iter_ty, loop_var in zip(self.node.lhs, iter_types, loop_vars):\n                iter_type: int\n                if iter_ty == \"S\":\n                    iter_type = IterVar.DataPar\n                elif iter_ty == \"R\":\n                    iter_type = IterVar.CommReduce\n                else:\n                    self.context.report_error(\n                        f'`iter_type` only expected \"S\" (for spatial) or \"R\" (for reduce), '\n                        f'but got \"{iter_ty}\"',\n                        span,\n                    )\n\n                if not isinstance(loop_var, tvm.tir.expr.Var):\n                    self.context.report_error(\n                        f\"Values of `axis.remap` expected single loop var, but got {loop_var}\",\n                        loop_var.span,\n                    )\n                loops = self.context.loop_stack\n                if loop_var not in loops:\n                    self.context.report_error(\n                        f\"Cannot find loop var {loop_var} in loop nesting.\",\n                        span,\n                    )\n                self.axis(var.id.name, loops[loop_var], loop_var, iter_type)\n\n        super().__init__(axis_remap, def_symbol=True)\n\n    def signature(self) -> Tuple[str, Tuple[list, list, Any]]:\n        return \"tir.axis.remap\", get_param_list(self.func)\n\n\n@register\nclass BlockPredicate(SpecialStmt):\n    \"\"\"Special function where(predicate)\n\n    Example\n    -------\n    .. code-block:: python\n\n        T.where(i < 4)\n    \"\"\"\n\n    def __init__(self):\n        def where(predicate, span=None):\n            assert self.context, \"call 'exit_scope' before 'enter_scope'\"\n            block_scope = self.context.current_block_scope()\n            if block_scope is None:\n                self.context.report_error(\n                    \"Expected to declare the predicate inside a block.\",\n                    span,\n                )\n            if block_scope.predicate is not None:\n                self.context.report_error(\n                    \"Duplicate block predicate declaration, \"\n                    + \"previous one is \"\n                    + str(block_scope.predicate),\n                    span,\n                )\n\n            block_scope.predicate = predicate\n\n        super().__init__(where, def_symbol=False)\n\n\n@register\nclass VarDef(SpecialStmt):\n    \"\"\"Special function for defining a Var\"\"\"\n\n    def __init__(self):\n        def var(dtype, span):\n            assert isinstance(\n                self.node, ast.Assign\n            ), f\"VarDef expected ast.Assign but got {type(self.node)}\"\n            names = [x.id.name for x in self.node.lhs]\n            if len(names) != 1:\n                self.context.report_error(\n                    f\"VarDef expected assign to only one var, but got {names}\", span\n                )\n            v = Var(names[0], dtype, span=span)\n            self.context.update_symbol(v.name, v, self.node)\n\n        super().__init__(var, def_symbol=True)\n\n\n@register\nclass BufferVarDef(SpecialStmt):\n    \"\"\"Special function for defining a variable of pointer type\"\"\"\n\n    def __init__(self):\n        def buffer_var(dtype, storage_scope, span):\n            assert isinstance(\n                self.node, ast.Assign\n            ), f\"BufferVarDef expected ast.Assign but got {type(self.node)}\"\n            names = [x.id.name for x in self.node.lhs]\n            if len(names) != 1:\n                self.context.report_error(\n                    f\"VarDef expected assign to only one var, but got {names}\", span\n                )\n            ptr_type = tvm.ir.PointerType(tvm.ir.PrimType(dtype), storage_scope)\n            v = Var(names[0], ptr_type, span=span)\n            self.context.update_symbol(v.name, v, self.node)\n\n        super().__init__(buffer_var, def_symbol=True)\n\n\n@register\nclass EnvThread(SpecialStmt):\n    \"\"\"Bind a var to thread env\"\"\"\n\n    def __init__(self):\n        def env_thread(env_name, span):\n            assert isinstance(\n                self.node, ast.Assign\n            ), f\"EnvThread expected ast.Assign but got {type(self.node)}\"\n            names = [x.id.name for x in self.node.lhs]\n            if len(names) != 1:\n                self.context.report_error(\n                    f\"VarDef expected assign to only one var, but got {names}\", span\n                )\n            v = Var(names[0], dtype=\"int32\", span=span)\n            self.context.func_var_env_dict[v] = env_name\n            self.context.update_symbol(v.name, v, self.node)\n\n        super().__init__(env_thread, def_symbol=True)\n\n\n@register\nclass FuncAttr(SpecialStmt):\n    \"\"\"Special Stmt for declaring the DictAttr of PrimFunc\n    Example\n    -------\n    .. code-block:: python\n         T.func_attr({\"tir.noalias\": True, \"global_symbol\"})\n    \"\"\"\n\n    def __init__(self):\n        def func_attr(dict_attr, span):\n            self.context.func_dict_attr = dict_attr\n\n        super().__init__(func_attr, def_symbol=False)\n\n\n@register\nclass PreflattenedBufferMap(SpecialStmt):\n    \"\"\"Special Stmt for declaring the PrimFunc::preflattened_buffer_map\n\n    Example\n    -------\n    .. code-block:: python\n         A0 = T.match_buffer(A, (48,), dtype=\"float32\")\n         T.preflattened_buffer_map(A, (1, 4, 4, 3), elem_offset=1, align=4, dtype=\"float32\")\n    \"\"\"\n\n    def __init__(self):\n        def preflattened_buffer(\n            postflattened,\n            shape,\n            dtype=\"float32\",\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            span=None,\n        ):\n\n            param = None\n            for key, value in self.context.func_buffer_map.items():\n                if value.same_as(postflattened):\n                    param = key\n                    break\n\n            assert (\n                param is not None\n            ), f\"Post-flatten buffer {postflattened.name} does not appear in the buffer map.\"\n\n            if data is None:\n                data = self.context.func_buffer_map[param].data\n\n            buffer_name: str = f\"{postflattened.name}_preflatten\"\n            if align != -1:\n                if isinstance(align, IntImm):\n                    align = align.value\n                else:\n                    assert isinstance(align, int), f\"align: want int or IntImm, got {align!r}\"\n\n            if offset_factor != 0:\n                if isinstance(offset_factor, IntImm):\n                    offset_factor = offset_factor.value\n                else:\n                    assert isinstance(\n                        offset_factor, int\n                    ), f\"offset_factor: want int or IntImm, got {offset_factor!r}\"\n\n            preflattened = tvm.tir.decl_buffer(\n                shape,\n                dtype,\n                buffer_name,\n                data,\n                strides,\n                elem_offset,\n                scope,\n                align,\n                offset_factor,\n                buffer_type,\n                span=span,\n            )\n\n            self.context.func_preflattened_buffer_map[param] = preflattened\n\n        super().__init__(preflattened_buffer, def_symbol=False)\n\n\n@register\nclass TargetAttrValue(SpecialStmt):\n    \"\"\"Special Stmt for target attr value.\n    Example\n    -------\n    .. code-block:: python\n        T.target(\"llvm\")\n    \"\"\"\n\n    def __init__(self):\n        def target(*args, span):\n            self.context.report_error(f\"T.target should not appear as a stmt\", span)\n\n        super().__init__(target, def_symbol=False)\n\n    def __call__(self, target_config):\n        if not isinstance(target_config, (str, dict)):\n            raise ValueError(\n                f\"T.target expected a config dict or string, but got {type(target_config)}\"\n            )\n        return Target(target_config)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/tir/ty.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM Script Parser Typing Class for TIR\n\nThis module provides typing class for TVM script type annotation usage, it can be viewed as\na wrapper for uniform Type system in IR\n\"\"\"\n# pylint: disable=invalid-name\nfrom numbers import Integral\n\nimport tvm\nfrom .special_stmt import SpecialStmt, convert_to_int\n\n\nclass TypeGeneric:  # pylint: disable=too-few-public-methods\n    \"\"\"Base class for all the TVM script typing class\"\"\"\n\n    def evaluate(self):\n        \"\"\"Return an actual ir.Type Object that this Generic class wraps\"\"\"\n        raise TypeError(\"Cannot get tvm.Type from a generic type\")\n\n    def require_type_generic_at(self, idx):  # pylint: disable=unused-argument\n        \"\"\"If True, the `idx`th type argument must be TypeGeneric\"\"\"\n        return True\n\n    # This function is added here to avoid a pylint error\n    # for T.int/float below not being callable\n    def __call__(self):\n        raise NotImplementedError()\n\n\nclass ConcreteType(TypeGeneric):  # pylint: disable=too-few-public-methods, abstract-method\n    \"\"\"TVM script typing class for uniform Type objects\n\n    Params\n    ------\n    vtype: Union[str, tvm.ir.Type]\n\n        The IR type represented by the type annotation.  If a string\n        (e.g. \"float32\"), this represents a `ir.PrimType` generated\n        from that string.  If a `ir.Type` is provided, this represents\n        the type provided.\n    \"\"\"\n\n    def __init__(self, vtype):\n        if isinstance(vtype, tvm.ir.Type):\n            self.type = vtype\n        else:\n            self.type = tvm.ir.PrimType(vtype)\n\n    def __call__(self, *args):  # pylint: disable=arguments-differ\n        pass\n\n    def evaluate(self):\n        return self.type\n\n\nclass VoidType(ConcreteType):  # pylint: disable=too-few-public-methods, abstract-method\n    \"\"\"TVM script typing class for void type\"\"\"\n\n    def __init__(self):\n        super().__init__(\"\")\n\n\nclass GenericPtrType(TypeGeneric):  # pylint: disable=abstract-method\n    \"\"\"TVM script typing class generator for PtrType\n\n    [] operator is overloaded, accepts a ConcreteType and an optional storage scope string,\n    returns a ConcreteType wrapping PtrType\n    \"\"\"\n\n    def __getitem__(self, args):\n        if isinstance(args, TypeGeneric):\n            args = [args]\n        if len(args) == 1:\n            vtype, scope = args[0], \"global\"\n        elif len(args) == 2:\n            vtype, scope = args[0], args[1]\n        else:\n            raise TypeError(f\"Illegal type argument num for Ptr\")\n        if not isinstance(vtype, TypeGeneric):\n            raise TypeError(f\"Ptr expects a type argument, but received {type(vtype).__name__}\")\n        if not isinstance(scope, str):\n            raise TypeError(f\"Ptr expects storage scope argument be a string\")\n        return ConcreteType(tvm.ir.PointerType(vtype.evaluate(), scope))\n\n    def require_type_generic_at(self, idx):\n        return idx != 1  # the second argument is storage scope for Ptr\n\n\nclass GenericTupleType(TypeGeneric):  # pylint: disable=abstract-method\n    \"\"\"TVM script typing class generator for TupleType\n\n    [] operator is overloaded, accepts a list of ConcreteType and returns a ConcreteType\n    wrapping TupleType\n    \"\"\"\n\n    def __getitem__(self, vtypes):\n        if isinstance(vtypes, TypeGeneric):\n            vtypes = [vtypes]\n        return ConcreteType(tvm.ir.TupleType([vtype.evaluate() for vtype in vtypes]))\n\n\nclass GenericBufferType(SpecialStmt):  # pylint: disable=too-few-public-methods, abstract-method\n    \"\"\"TVM script typing class for uniform Type objects\"\"\"\n\n    def __init__(self, vtype):\n        def match_buffer_syntax_sugar(\n            shape,\n            dtype: str = \"float32\",\n            name: str = None,\n            data=None,\n            strides=None,\n            elem_offset=None,\n            scope=\"global\",\n            align=-1,\n            offset_factor=0,\n            buffer_type=\"default\",\n            axis_separators=None,\n            span=None,\n        ):\n            if strides is None:\n                strides = []\n            align = convert_to_int(align, \"align\", self.context.report_error, self.node.span)\n            offset_factor = convert_to_int(\n                offset_factor, \"offset_factor\", self.context.report_error, self.node.span\n            )\n            buffer = tvm.tir.decl_buffer(\n                shape,\n                dtype,\n                name,\n                data,\n                strides,\n                elem_offset,\n                scope,\n                align,\n                offset_factor,\n                buffer_type,\n                axis_separators,\n                span=span,\n            )\n            return buffer\n\n        self.type = vtype\n        super().__init__(match_buffer_syntax_sugar, def_symbol=True)\n\n    def __call__(\n        self,\n        shape,\n        dtype=\"float32\",\n        *,\n        name: str = None,\n        data=None,\n        strides=None,\n        elem_offset=None,\n        scope=\"global\",\n        align=-1,\n        offset_factor=0,\n        buffer_type=\"default\",\n        axis_separators=None,\n        span=None,\n    ):\n        \"\"\"\n        This function is for Buffer(...) syntax sugar.\n        \"\"\"\n        pass  # pylint: disable=unnecessary-pass\n\n    def __getitem__(self, args):\n        \"\"\"\n        This function is for Buffer[...] syntax sugar\n        Note that args is the list of all arguments\n        \"\"\"\n        if len(args) < 2:\n            raise ValueError(\"T.Buffer[...] needs at least two arguments: shape and dtype.\")\n\n        shape = args[0]\n        dtype = args[1]\n\n        valid_shape = isinstance(shape, (tvm.ir.PrimExpr, Integral, tuple, list))\n        valid_dtype = isinstance(dtype, str)\n        if not (valid_shape and valid_dtype):\n            raise ValueError(\n                \"The first argument of T.Buffer[...] needs to be a tuple, \"\n                \"followed by the second argument dtype as a string\"\n            )\n\n\n# add all floating point and integer datatypes to the module\nfor _dtype in [\"float\", \"uint\", \"int\"]:\n    for _size in [\"8\", \"16\", \"32\", \"64\"]:\n        for _lanes in [\"\", \"x4\", \"x8\", \"x16\", \"x32\", \"x64\"]:\n            _name = _dtype + _size + _lanes\n            globals()[_name] = ConcreteType(_name)\n\n\n# All other DataType annotations are represented with the same string\n# as is used by `tvm.runtime.DataType`.  This does redefine the Python\n# built-in bool, but only within the context of `tvm.script.tir.ty`\n# and `tvm.script.tir` modules.  The `T.boolean` alias is maintained\n# for backwards compatibility.\n\nbool = ConcreteType(\"bool\")  # pylint: disable=redefined-builtin\nboolean = bool\n\n\nhandle = ConcreteType(\"handle\")\nvoid = VoidType()\nPtr = GenericPtrType()\nTuple = GenericTupleType()\n# we don't have 'buffer' type on the cpp side\n# thus 'handle' is used here for convenience's sake\nBuffer = GenericBufferType(\"handle\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/parser_v1/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Helper functions in TVM Script Parser\"\"\"\n\nfrom typing import Callable, List, Any, Optional, Tuple\n\nimport inspect\nimport synr\n\nfrom tvm.ir import Span, SourceName\nfrom tvm.error import DiagnosticError\n\n\ndef get_param_list(\n    func: Callable,\n) -> Tuple[List[str], List[Tuple[str, Tuple[Any, ...]]], Optional[str]]:\n    \"\"\"Get the parameter list from definition of function\"\"\"\n    full_arg_spec: inspect.FullArgSpec = inspect.getfullargspec(func)\n\n    args: List[str]\n    defaults: Optional[Tuple[Any, ...]]\n    kwonlyargs: List[str]\n    args, defaults, kwonlyargs = (\n        full_arg_spec.args,\n        full_arg_spec.defaults,\n        full_arg_spec.kwonlyargs,\n    )\n\n    if defaults is None:\n        defaults = tuple()\n\n    if full_arg_spec.varkw is not None:\n        raise RuntimeError(\n            \"TVM Script register error : variable keyword argument is not supported now\"\n        )\n\n    if len(kwonlyargs) == 1 and kwonlyargs[0] == \"span\":\n        pass\n    elif not len(kwonlyargs) == 0:\n        raise RuntimeError(\"TVM Script register error : keyword only argument is not supported now\")\n\n    pos_only: List[str] = list()\n    for arg in args[: len(args) - len(defaults)]:\n        if arg != \"span\":\n            pos_only.append(arg)\n    kwargs: List[Tuple[str, Tuple[Any, ...]]] = list()\n    for default, arg in zip(defaults, args[len(args) - len(defaults) :]):\n        if arg != \"span\":\n            kwargs.append((arg, default))\n\n    return pos_only, kwargs, full_arg_spec.varargs\n\n\ndef tvm_span_from_synr(span: synr.ast.Span) -> Span:\n    \"\"\"Convert a synr span to a TVM span\"\"\"\n    return Span(\n        SourceName(span.filename),\n        span.start_line,\n        span.end_line,\n        span.start_column,\n        span.end_column,\n    )\n\n\ndef synr_span_from_tvm(span: Span) -> synr.ast.Span:\n    \"\"\"Convert a TVM span to a synr span\"\"\"\n    return synr.ast.Span(\n        span.source_name.name,\n        span.line,\n        span.column,\n        span.end_line,\n        span.end_column,\n    )\n\n\ndef call_with_error_reporting(\n    report_error,\n    node_span,\n    func,\n    *args,\n    **kwargs,\n):\n    \"\"\"Call function with exception handling and report error using node_span\"\"\"\n    try:\n        return func(*args, **kwargs)\n    except DiagnosticError:\n        raise\n    except Exception as err:  # pylint: disable=broad-except\n        # printing last non-empty row of error message.\n        error_msg = list(filter(None, str(err).split(\"\\n\")))[-1]\n        report_error(error_msg, node_span)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTVMScript Unified Printer\n\nThis package provides a set of APIs to print supported TVM IR into TVMScript\nin a roundtrippable way.\n\nhttps://github.com/apache/tvm-rfcs/blob/main/rfcs/0074-tvmscript-unified-printer.md\n\"\"\"\n\nfrom . import _ffi_api\nfrom .entry import script\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.script.printer\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"script.printer\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/doc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Doc types for TVMScript Unified Printer\"\"\"\n\nfrom enum import IntEnum, unique\nfrom typing import Dict, List, Optional, Sequence, Tuple, Union\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object, ObjectPath\nfrom tvm.tir import FloatImm, IntImm\n\nfrom . import _ffi_api\n\n\nclass Doc(Object):\n    \"\"\"Base class of all Docs\"\"\"\n\n    @property\n    def source_paths(self) -> Sequence[ObjectPath]:\n        \"\"\"\n        The list of object paths of the source IR node.\n\n        This is used to trace back to the IR node position where\n        this Doc is generated, in order to position the diagnostic\n        message.\n        \"\"\"\n        return self.__getattr__(\"source_paths\")  # pylint: disable=unnecessary-dunder-call\n\n    @source_paths.setter\n    def source_paths(self, value):\n        return _ffi_api.DocSetSourcePaths(self, value)  # type: ignore # pylint: disable=no-member\n\n\nclass ExprDoc(Doc):\n    \"\"\"Base class of all expression Docs\"\"\"\n\n    def attr(self, name: str) -> \"AttrAccessDoc\":\n        \"\"\"\n        Create a doc that represents attribute access on self.\n\n        Parameters\n        ----------\n        name : str\n            The attribute name to access\n\n        Returns\n        -------\n        doc : AttrAccessDoc\n        \"\"\"\n        return _ffi_api.ExprDocAttr(self, name)  # type: ignore # pylint: disable=no-member\n\n    def call(self, *args: Tuple[\"ExprDoc\"], **kwargs: Dict[str, \"ExprDoc\"]) -> \"CallDoc\":\n        \"\"\"\n        Create a doc that represents function call, with self as callee.\n\n        Parameters\n        ----------\n        *args : ExprDoc\n            The positional arguments of the function call.\n        **kwargs\n            The keyword arguments of the function call.\n\n        Returns\n        -------\n        doc : CallDoc\n        \"\"\"\n        kwargs_keys = list(kwargs.keys())\n        kwargs_values = list(kwargs.values())\n        return _ffi_api.ExprDocCall(self, args, kwargs_keys, kwargs_values)  # type: ignore # pylint: disable=no-member\n\n    _IndexType = Union[\"ExprDoc\", \"SliceDoc\"]\n\n    def __getitem__(self, indices: Union[Tuple[_IndexType], _IndexType]) -> \"IndexDoc\":\n        \"\"\"\n        Create a doc that represents index access on self.\n\n        Parameters\n        ----------\n        indices : Union[Tuple[Union[\"ExprDoc\", \"SliceDoc\"]], Union[\"ExprDoc\", \"SliceDoc\"]]\n            The indices to access\n\n        Returns\n        -------\n        doc : IndexDoc\n        \"\"\"\n        if not isinstance(indices, tuple):\n            indices = (indices,)\n        return _ffi_api.ExprDocIndex(self, indices)  # type: ignore # pylint: disable=no-member\n\n    def __iter__(self):\n        \"\"\"\n        This is implemented to prevent confusing error message when trying to use ExprDoc\n        as iterable. According to PEP-234, An object can be iterated over if it\n        implements __iter__() or __getitem__(). If an object has only __getitem__\n        but not __iter__, interpreter will iterate the object by calling\n        __getitem__ with 0, 1, 2, ..., until an IndexError is raised.\n\n        https://peps.python.org/pep-0234/#python-api-specification\n        \"\"\"\n        raise RuntimeError(f\"{self.__class__} cannot be used as iterable.\")\n\n\nclass StmtDoc(Doc):\n    \"\"\"Base class of statement doc\"\"\"\n\n    @property\n    def comment(self) -> Optional[str]:\n        \"\"\"\n        The comment of this doc.\n\n        The actual position of the comment depends on the type of Doc\n        and also the DocPrinter implementation. It could be on the same\n        line as the statement, or the line above, or inside the statement\n        if it spans over multiple lines.\n        \"\"\"\n        # It has to call the dunder method to avoid infinite recursion\n        return self.__getattr__(\"comment\")  # pylint: disable=unnecessary-dunder-call\n\n    @comment.setter\n    def comment(self, value):\n        return _ffi_api.StmtDocSetComment(self, value)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.StmtBlockDoc\")\nclass StmtBlockDoc(Doc):\n    \"\"\"The container doc that holds a list of StmtDoc.\n\n    Note: `StmtBlockDoc` is never used in the IR, but a temporary container that allows holding a\n    list of StmtDoc.\n    \"\"\"\n\n    stmts: Sequence[StmtDoc]\n\n    def __init__(self, stmts: List[StmtDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.StmtBlockDoc, stmts)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.LiteralDoc\")\nclass LiteralDoc(ExprDoc):\n    \"\"\"Doc that represents literal value\"\"\"\n\n    value: Union[str, IntImm, FloatImm, None]\n\n    def __init__(self, value: Union[str, float, bool, int, None]):\n        if value is None:\n            self.__init_handle_by_constructor__(_ffi_api.LiteralDocNone)  # type: ignore # pylint: disable=no-member\n        elif isinstance(value, str):\n            self.__init_handle_by_constructor__(_ffi_api.LiteralDocStr, value)  # type: ignore # pylint: disable=no-member\n        elif isinstance(value, float):\n            self.__init_handle_by_constructor__(_ffi_api.LiteralDocFloat, value)  # type: ignore # pylint: disable=no-member\n        elif isinstance(value, bool):\n            self.__init_handle_by_constructor__(_ffi_api.LiteralDocBoolean, value)  # type: ignore # pylint: disable=no-member\n        elif isinstance(value, int):\n            self.__init_handle_by_constructor__(_ffi_api.LiteralDocInt, value)  # type: ignore # pylint: disable=no-member\n        else:\n            raise TypeError(f\"Unsupported type {type(value)} for LiteralDoc\")\n\n\n@register_object(\"script.printer.IdDoc\")\nclass IdDoc(ExprDoc):\n    \"\"\"Doc that represents identifier\"\"\"\n\n    name: str\n\n    def __init__(self, name: str):\n        self.__init_handle_by_constructor__(_ffi_api.IdDoc, name)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.AttrAccessDoc\")\nclass AttrAccessDoc(ExprDoc):\n    \"\"\"Doc that represents attribute access on an expression\"\"\"\n\n    value: ExprDoc\n    name: str\n\n    def __init__(self, value: ExprDoc, name: str):\n        self.__init_handle_by_constructor__(_ffi_api.AttrAccessDoc, value, name)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.IndexDoc\")\nclass IndexDoc(ExprDoc):\n    \"\"\"Doc that represents index access on an expression\"\"\"\n\n    value: ExprDoc\n    indices: Sequence[Union[ExprDoc, \"SliceDoc\"]]\n\n    def __init__(self, value: ExprDoc, indices: List[Union[ExprDoc, \"SliceDoc\"]]):\n        self.__init_handle_by_constructor__(_ffi_api.IndexDoc, value, indices)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.CallDoc\")\nclass CallDoc(ExprDoc):\n    \"\"\"Doc that represents function call\"\"\"\n\n    callee: ExprDoc\n    args: Sequence[ExprDoc]\n    kwargs_keys: Sequence[str]\n    kwargs_values: Sequence[ExprDoc]\n\n    def __init__(self, callee: ExprDoc, *args: Tuple[ExprDoc], **kwargs: Dict[str, ExprDoc]):\n        kwargs_keys = list(kwargs.keys())\n        kwargs_values = list(kwargs.values())\n        self.__init_handle_by_constructor__(\n            _ffi_api.CallDoc,  # type: ignore # pylint: disable=no-member\n            callee,\n            args,\n            kwargs_keys,\n            kwargs_values,\n        )\n\n\n@unique\nclass OperationKind(IntEnum):\n    \"\"\"\n    This enum represents the kind of operation (operator) in OperationDoc\n\n    It's mirrored from OperationDocNode::Kind at include/tvm/script/printer/doc.h\n    \"\"\"\n\n    # The name convention follows https://docs.python.org/3/library/ast.html\n    # pylint: disable=invalid-name\n\n    _UnaryStart = 0\n    USub = 1\n    Invert = 2\n    Not = 3\n    _UnaryEnd = 4\n\n    _BinaryStart = 5\n    Add = 6\n    Sub = 7\n    Mult = 8\n    Div = 9\n    FloorDiv = 10\n    Mod = 11\n    Pow = 12\n    LShift = 13\n    RShift = 14\n    BitAnd = 15\n    BitOr = 16\n    BitXor = 17\n    Lt = 18\n    LtE = 19\n    Eq = 20\n    NotEq = 21\n    Gt = 22\n    GtE = 23\n    And = 24\n    Or = 25\n    _BinaryEnd = 26\n\n    _SpecialStart = 27\n    IfThenElse = 28\n    _SpecialEnd = 29\n\n    # pylint: enable=invalid-name\n\n\n@register_object(\"script.printer.OperationDoc\")\nclass OperationDoc(ExprDoc):\n    \"\"\"\n    Doc that represents operation\n\n    It can be unary, binary and other special operators (for example, the\n    if-then-else expression).\n    \"\"\"\n\n    kind: OperationKind\n    operands: Sequence[ExprDoc]\n\n    def __init__(self, kind: OperationKind, operands: List[ExprDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.OperationDoc, kind, operands)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.LambdaDoc\")\nclass LambdaDoc(ExprDoc):\n    \"\"\"Doc that represents lambda function\"\"\"\n\n    args: Sequence[IdDoc]\n    body: ExprDoc\n\n    def __init__(self, args: List[IdDoc], body: ExprDoc):\n        self.__init_handle_by_constructor__(_ffi_api.LambdaDoc, args, body)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.TupleDoc\")\nclass TupleDoc(ExprDoc):\n    \"\"\"Doc that represents tuple literal\"\"\"\n\n    elements: Sequence[ExprDoc]\n\n    def __init__(self, elements: List[ExprDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.TupleDoc, elements)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.ListDoc\")\nclass ListDoc(ExprDoc):\n    \"\"\"Doc that represents list literal\"\"\"\n\n    elements: Sequence[ExprDoc]\n\n    def __init__(self, elements: List[ExprDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.ListDoc, elements)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.DictDoc\")\nclass DictDoc(ExprDoc):\n    \"\"\"Doc that represents dict literal\"\"\"\n\n    keys: Sequence[ExprDoc]\n    values: Sequence[ExprDoc]\n\n    def __init__(self, content: Dict[ExprDoc, ExprDoc]):\n        keys = list(content.keys())\n        values = list(content.values())\n        self.__init_handle_by_constructor__(_ffi_api.DictDoc, keys, values)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.SliceDoc\")\nclass SliceDoc(ExprDoc):\n    \"\"\"\n    Doc that represents slice in Index expression\n\n    This doc can only appear in `IndexDoc.indices`.\n    \"\"\"\n\n    start: Optional[ExprDoc]\n    stop: Optional[ExprDoc]\n    step: Optional[ExprDoc]\n\n    def __init__(\n        self,\n        start: Optional[ExprDoc] = None,\n        stop: Optional[ExprDoc] = None,\n        step: Optional[ExprDoc] = None,\n    ):\n        self.__init_handle_by_constructor__(_ffi_api.SliceDoc, start, stop, step)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.AssignDoc\")\nclass AssignDoc(StmtDoc):\n    \"\"\"Doc that represents assign statement.\"\"\"\n\n    lhs: ExprDoc\n    rhs: Optional[ExprDoc]\n    annotation: Optional[ExprDoc]\n\n    def __init__(self, lhs: ExprDoc, rhs: Optional[ExprDoc], annotation: Optional[ExprDoc] = None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.AssignDoc,  # type: ignore # pylint: disable=no-member\n            lhs,\n            rhs,\n            annotation,\n        )\n\n\n@register_object(\"script.printer.IfDoc\")\nclass IfDoc(StmtDoc):\n    \"\"\"Doc that represent if-then-else statement.\"\"\"\n\n    predicate: ExprDoc\n    then_branch: Sequence[StmtDoc]\n    else_branch: Sequence[StmtDoc]\n\n    def __init__(self, predicate: ExprDoc, then_branch: List[StmtDoc], else_branch: List[StmtDoc]):\n        self.__init_handle_by_constructor__(\n            _ffi_api.IfDoc,  # type: ignore # pylint: disable=no-member\n            predicate,\n            then_branch,\n            else_branch,\n        )\n\n\n@register_object(\"script.printer.WhileDoc\")\nclass WhileDoc(StmtDoc):\n    \"\"\"Doc that represents while statement.\"\"\"\n\n    predicate: ExprDoc\n    body: Sequence[StmtDoc]\n\n    def __init__(self, predicate: ExprDoc, body: List[StmtDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.WhileDoc, predicate, body)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.ForDoc\")\nclass ForDoc(StmtDoc):\n    \"\"\"Doc that represents for statement.\"\"\"\n\n    lhs: ExprDoc\n    rhs: ExprDoc\n    body: Sequence[StmtDoc]\n\n    def __init__(self, lhs: ExprDoc, rhs: ExprDoc, body: List[StmtDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.ForDoc, lhs, rhs, body)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.ScopeDoc\")\nclass ScopeDoc(StmtDoc):\n    \"\"\"\n    Doc that represents special scopes.\n\n    Specifically, this means the with statement in Python:\n\n    with <rhs> as <lhs>:\n        <body...>\n    \"\"\"\n\n    lhs: Optional[ExprDoc]\n    rhs: ExprDoc\n    body: Sequence[StmtDoc]\n\n    def __init__(self, lhs: Optional[ExprDoc], rhs: ExprDoc, body: List[StmtDoc]):\n        self.__init_handle_by_constructor__(_ffi_api.ScopeDoc, lhs, rhs, body)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.ExprStmtDoc\")\nclass ExprStmtDoc(StmtDoc):\n    \"\"\"Doc that represents an expression as statement.\"\"\"\n\n    expr: ExprDoc\n\n    def __init__(self, expr: ExprDoc):\n        self.__init_handle_by_constructor__(_ffi_api.ExprStmtDoc, expr)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.AssertDoc\")\nclass AssertDoc(StmtDoc):\n    \"\"\"Doc that represents assert statement.\"\"\"\n\n    test: ExprDoc\n    msg: Optional[ExprDoc]\n\n    def __init__(self, test: ExprDoc, msg: Optional[ExprDoc] = None):\n        self.__init_handle_by_constructor__(_ffi_api.AssertDoc, test, msg)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.ReturnDoc\")\nclass ReturnDoc(StmtDoc):\n    \"\"\"Doc that represents return statement.\"\"\"\n\n    value: ExprDoc\n\n    def __init__(self, value: ExprDoc):\n        self.__init_handle_by_constructor__(_ffi_api.ReturnDoc, value)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.FunctionDoc\")\nclass FunctionDoc(StmtDoc):\n    \"\"\"Doc that represents function definition.\"\"\"\n\n    name: IdDoc\n    args: Sequence[AssignDoc]\n    decorators: Sequence[ExprDoc]\n    return_type: Optional[ExprDoc]\n    body: Sequence[StmtDoc]\n\n    def __init__(\n        self,\n        name: IdDoc,\n        args: List[AssignDoc],\n        decorators: List[ExprDoc],\n        return_type: Optional[ExprDoc],\n        body: List[StmtDoc],\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.FunctionDoc,  # type: ignore # pylint: disable=no-member\n            name,\n            args,\n            decorators,\n            return_type,\n            body,\n        )\n\n\n@register_object(\"script.printer.ClassDoc\")\nclass ClassDoc(StmtDoc):\n    \"\"\"Doc that represents class definition.\"\"\"\n\n    name: IdDoc\n    decorators: Sequence[ExprDoc]\n    body: Sequence[StmtDoc]\n\n    def __init__(self, name: IdDoc, decorators: List[ExprDoc], body: List[StmtDoc]):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ClassDoc,  # type: ignore # pylint: disable=no-member\n            name,\n            decorators,\n            body,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/doc_printer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Functions to print doc into text format\"\"\"\n\nfrom typing import Optional\nfrom tvm.runtime.object_path import ObjectPath\nfrom . import _ffi_api\nfrom .doc import Doc\n\n\ndef to_python_script(\n    doc: Doc,\n    indent_spaces: int = 4,\n    print_line_numbers: bool = False,\n    num_context_lines: Optional[int] = None,\n    path_to_underline: Optional[ObjectPath] = None,\n) -> str:\n    \"\"\"Convert Doc into Python script.\n\n    Parameters\n    ----------\n    doc : Doc\n        The doc to convert into Python script\n    indent_spaces : int\n        The number of indent spaces to use in the output\n    print_line_numbers: bool\n        Whether to print line numbers\n    num_context_lines : Optional[int]\n        Number of context lines to print around the underlined text\n    path_to_underline : Optional[ObjectPath]\n        Object path to be underlined\n\n    Returns\n    -------\n    script : str\n        The text representation of Doc in Python syntax\n    \"\"\"\n    if num_context_lines is None:\n        num_context_lines = -1\n    return _ffi_api.DocToPythonScript(  # type: ignore\n        doc, indent_spaces, print_line_numbers, num_context_lines, path_to_underline\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/entry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file contains the entry point of TVMScript Unified Printer.\n\"\"\"\n\nfrom typing import Dict, Optional\n\nfrom tvm.runtime import Object, ObjectPath\n\nfrom . import _ffi_api\n\n\ndef script(  # pylint: disable=too-many-arguments\n    root_node: Object,\n    ir_name: str,\n    ir_prefix: Dict[str, str],\n    indent_spaces: int = 4,\n    print_line_numbers: bool = False,\n    num_context_lines: int = -1,\n    path_to_underline: Optional[ObjectPath] = None,\n) -> str:\n    \"\"\"\n    Print IR graph as TVMScript code\n\n    Parameters\n    ----------\n    root_node : Object\n        The root node to print.\n    ir_name : str\n        The dispatch token of the target IR, e.g., \"tir\", \"relax\".\n    ir_prefix : Dict[str, str]\n        The symbol name for TVMScript IR namespaces. For example,\n        {\"tir\": \"T\"}.\n    indent_spaces : int\n        The number of indent spaces to use in the output\n    print_line_numbers: bool\n        Whether to print line numbers\n    num_context_lines : Optional[int]\n        Number of context lines to print around the underlined text\n    path_to_underline : Optional[ObjectPath]\n        Object path to be underlined\n\n    Returns\n    -------\n    script : str\n        The TVMScript code of the root_node\n    \"\"\"\n    return _ffi_api.Script(  # type: ignore # pylint: disable=no-member\n        root_node,\n        ir_name,\n        ir_prefix,\n        indent_spaces,\n        print_line_numbers,\n        num_context_lines,\n        path_to_underline,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/frame.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nFrame is the core data structure for semantic information when printing\nIR graph into TVMScript code.\n\"\"\"\n\nfrom typing import Callable, Sequence\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.script.printer.doc import StmtDoc\n\nfrom . import _ffi_api\n\n\nclass Frame(Object):\n    \"\"\"\n    Frame is the core data structure for semantic information\n    when printing IR graph into TVMScript code.\n\n    Frame base class manages a list of callbacks to be executed\n    when frame goes out of scope.\n    \"\"\"\n\n    def add_exit_callback(self, callback: Callable[[], None]) -> None:\n        \"\"\"\n        Adds a callback function to be executed when frame goes out of scope.\n\n        Parameters\n        ----------\n        callback : Callable[[], None]\n            The callback function.\n        \"\"\"\n        _ffi_api.FrameAddExitCallback(self, callback)  # type: ignore # pylint: disable=no-member\n\n    def __enter__(self):\n        _ffi_api.FrameEnterWithScope(self)  # type: ignore # pylint: disable=no-member\n        return self\n\n    def __exit__(self, *exception_info):\n        _ffi_api.FrameExitWithScope(self)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.MetadataFrame\")\nclass MetadataFrame(Frame):\n    \"\"\"\n    MetadataFrame contains information like contant parameter array.\n    \"\"\"\n\n    metadata: Sequence[Object]\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_ffi_api.MetadataFrame)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.VarDefFrame\")\nclass VarDefFrame(Frame):\n    \"\"\"\n    VarDefFrame contains information about the free variables that needs to\n    be defined at the beginning of the printed snippet.\n    \"\"\"\n\n    stmts: Sequence[StmtDoc]\n\n    def __init__(self):\n        self.__init_handle_by_constructor__(_ffi_api.VarDefFrame)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/ir_docsifier.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nIRDocsifier is the top-level interface in the process of transforming\nIR graph into Doc tree, during printing IR graph as TVMScript code.\n\"\"\"\n\nimport atexit\nfrom contextlib import ExitStack, contextmanager\nfrom typing import Callable, Dict, Generator, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar\n\nfrom tvm._ffi import get_object_type_index, register_object\nfrom tvm.runtime import Object, ObjectPath\n\nfrom . import _ffi_api\nfrom .doc import Doc\nfrom .frame import Frame\nfrom .var_table import VarTable\n\n_REGISTERED_TYPES: Set[Tuple[str, int]] = set()  # {(dispatch_token, type_index)}\n\n\ndef _cleanup_dispatch_function():\n    for dispatch_token, type_index in _REGISTERED_TYPES:\n        _ffi_api.IRDocsifierRemoveDispatch(dispatch_token, type_index)  # type: ignore # pylint: disable=no-member\n\n\n_CLEANUP_REGISTERED = False\n\n\ndef _ensure_cleanup_function_registered():\n    \"\"\"\n    Add a cleanup function to be called on interpreter termination,\n    to remove all dispatch functions registered on the Python side.\n\n    Without cleaning up those dispatch functions, program will segfault\n    on termination. It's because dispatch functions are referenced from the\n    static memory of libtvm, thus they will be cleaned up at the very end,\n    making calls to Py_DecRef after Python interpreter terminates.\n    \"\"\"\n    global _CLEANUP_REGISTERED  # pylint: disable=global-statement\n\n    if not _CLEANUP_REGISTERED:\n        atexit.register(_cleanup_dispatch_function)\n        _CLEANUP_REGISTERED = True\n\n\n@register_object(\"script.printer.RootNodeContainer\")\nclass RootNodeContainer(Object):\n    \"\"\"\n    A wrapper object to provide injection point for printer of each IR.\n\n    This class shouldn't be used directly. `IRDocsifier.set_root_dispatch`\n    should be used instead.\n    \"\"\"\n\n    root_node: Object\n\n    def __init__(self, root_node: Object):\n        self.__init_handle_by_constructor__(_ffi_api.RootNodeContainer, root_node)  # type: ignore # pylint: disable=no-member\n\n\n@register_object(\"script.printer.IRDocsifier\")\nclass IRDocsifier(Object):\n    \"\"\"\n    IRDocsifier is the top-level interface in the IR->Doc process.\n\n    It provides methods to convert IR node object to Doc, operate on Frame\n    objects and change dispatch tokens.\n    \"\"\"\n\n    ir_prefix: Mapping[str, str]\n    vars: VarTable\n    frames: Sequence[Frame]\n    dispatch_tokens: Sequence[str]\n\n    def __init__(self, ir_prefix: Dict[str, str]):\n        \"\"\"\n        Create a new IRDocsifier.\n\n        Parameters\n        ----------\n        ir_prefix : Dict[str, str]\n            The ir prefix to use. Key is the IR dispatch token and\n            value is the name of identifier for this IR's namespace in TVMScript.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.IRDocsifier, ir_prefix)  # type: ignore # pylint: disable=no-member\n\n    _TObject = TypeVar(\"_TObject\", bound=Object)\n\n    @classmethod\n    def set_dispatch(\n        cls,\n        node_type: Type[_TObject],\n        dispatch_function: Callable[[_TObject, ObjectPath, \"IRDocsifier\"], Doc],\n        dispatch_token: str = \"\",\n    ) -> None:\n        \"\"\"\n        Set the dispatch function to transform a particular IR node type to Doc\n\n        Parameters\n        ----------\n        node_type : Type[_TObject]\n            The type of object to dispatch on.\n        dispatch_function : Callable[[_TObject, ObjectPath, \"IRDocsifier\"], Doc]\n            The dispatch function. It's called to transform IR node object to Doc.\n        dispatch_token : str\n            Function will only be called when this dispatch_token is the same as the one\n            on the top of IRDocsifier's dispatch_tokens stack. An empty dispatch token\n            means registering as default dispatch function, which will be called when\n            there is no dispatch function registered with the current dispatch token.\n        \"\"\"\n        type_index = get_object_type_index(node_type)\n        if type_index is None:\n            raise TypeError(f\"{type(node_type)} is not a registered TVM object type.\")\n\n        _ensure_cleanup_function_registered()\n        _ffi_api.IRDocsifierSetDispatch(  # type: ignore # pylint: disable=no-member\n            dispatch_token, type_index, dispatch_function\n        )\n        _REGISTERED_TYPES.add((dispatch_token, type_index))\n\n    @classmethod\n    def set_root_dispatch(\n        cls, dispatch_token: str, root_dispatch_function: Callable[[Object, \"IRDocsifier\"], Doc]\n    ) -> None:\n        \"\"\"\n        Set the root dispatch function for an IR.\n\n        The root dispatch function will be called with the root node of an IR graph\n        that's being transformed to Doc. This provides an injection point for\n        each IR's printer implemention to add specialized logic, for example,\n        pushing a special Frame to the IRDocsifier before doing actual IR->Doc\n        transformation.\n\n        The simplest root dispatch function is\n        ```\n        def f(obj, ir_docsifier)\n            return ir_docsifier.as_doc(obj, ObjectPath.root())\n        ```\n\n        Parameters\n        ----------\n        root_dispatch_function : Callable[[_TObject, \"IRDocsifier\"], Doc]\n            The root dispatch function. It's called with the root node to be printed.\n        dispatch_token : str\n            The dispatch token of the IR that root_dispatch_funnction applies to.\n        \"\"\"\n\n        def dispatch_function(obj: RootNodeContainer, _, ir_docsifier):\n            return root_dispatch_function(obj.root_node, ir_docsifier)\n\n        cls.set_dispatch(RootNodeContainer, dispatch_function, dispatch_token)\n\n    def as_doc(self, obj: Object, object_path: ObjectPath) -> Doc:\n        \"\"\"\n        Transform the input object into Doc.\n\n        Parameters\n        ----------\n        obj : Object\n            The IR node object.\n        object_path : ObjectPath\n            The object path of this object. It's used for locating diagnostic message.\n\n        Returns\n        -------\n        doc : Doc\n            The doc for this object.\n        \"\"\"\n        return _ffi_api.IRDocsifierAsDoc(self, obj, object_path)  # type: ignore # pylint: disable=no-member\n\n    def get_frame(self, frame_type: Type[Frame]) -> Optional[Frame]:\n        \"\"\"\n        Get the top frame with type `frame_type`.\n\n        Parameters\n        ----------\n        frame_type : Type[Frame]\n            The target frame type.\n\n        Returns\n        -------\n        frame : Optional[Frame]\n            The frame if found, otherwise None.\n        \"\"\"\n        for i in range(len(self.frames) - 1, -1, -1):\n            if isinstance(self.frames[i], frame_type):\n                return self.frames[i]\n        return None\n\n    @contextmanager\n    def dispatch_token(self, token: str):\n        \"\"\"\n        Push a new dispatch token to the stack.\n\n        Parameters\n        ----------\n        token : str\n            The token to push.\n\n        Returns\n        -------\n        A context manager that pops this dispatch token when exits.\n        \"\"\"\n        with ExitStack() as stack:\n            _ffi_api.IRDocsifierPushDispatchToken(self, token)  # type: ignore # pylint: disable=no-member\n            stack.callback(_ffi_api.IRDocsifierPopDispatchToken, self)  # type: ignore # pylint: disable=no-member\n            yield\n\n    _TFrame = TypeVar(\"_TFrame\", bound=Frame)\n\n    @contextmanager\n    def frame(self, frame: _TFrame) -> Generator[_TFrame, None, None]:\n        \"\"\"\n        Push a new frame to the stack.\n\n        Parameters\n        ----------\n        frame : Frame\n            The frame to push.\n\n        Returns\n        -------\n        A context manager that pops this frame when exits.\n        \"\"\"\n        with ExitStack() as stack:\n            stack.enter_context(frame)\n            _ffi_api.IRDocsifierPushFrame(self, frame)  # type: ignore # pylint: disable=no-member\n            stack.callback(_ffi_api.IRDocsifierPopFrame, self)  # type: ignore # pylint: disable=no-member\n            yield frame\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/script/printer/var_table.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Functions to print doc into text format\"\"\"\n\nfrom typing import Callable, Optional\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object, ObjectPath\n\nfrom . import _ffi_api\nfrom .doc import ExprDoc, IdDoc\nfrom .frame import Frame\n\n\n@register_object(\"script.printer.VarTable\")\nclass VarTable(Object):\n    \"\"\"\n    Variable Table manages mapping from variable object to ExprDoc during\n    the process of printing TVMScript.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Create an empty VarTable.\n        \"\"\"\n        self.__init_handle_by_constructor__(_ffi_api.VarTable)  # type: ignore # pylint: disable=no-member\n\n    def define(self, obj: Object, name_hint: str, object_path: ObjectPath, frame: Frame) -> IdDoc:\n        \"\"\"\n        Define a variable by name.\n\n        Parameters\n        ----------\n        obj : Object\n            The variable object.\n        name_hint : str\n            The hint for variable name.\n        object_path : ObjectPath\n            The object path to be associated with the returned ExprDoc.\n        frame : Frame\n            Then frame that this variable is defined in.\n\n        Returns\n        -------\n        doc : IdDoc\n            The doc for this variable.\n        \"\"\"\n        return _ffi_api.VarTableDefine(self, obj, name_hint, object_path, frame)  # type: ignore # pylint: disable=no-member\n\n    def define_by_doc(self, obj: Object, doc_factory: Callable[[], ExprDoc], frame: Frame) -> None:\n        \"\"\"\n        Define a variable by ExprDoc.\n\n        Parameters\n        ----------\n        obj : Object\n            The variable object.\n        doc_factory : Callable[[], ExprDoc]\n            The hint for variable name.\n        frame : Frame\n            Then frame that this variable is defined in.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        _ffi_api.VarTableDefineByDoc(self, obj, doc_factory, frame)  # type: ignore # pylint: disable=no-member\n\n    def get_var_doc(self, obj: Object, object_path: ObjectPath) -> Optional[ExprDoc]:\n        \"\"\"\n        Get the doc for a variable.\n\n        Parameters\n        ----------\n        obj : Object\n            The variable object.\n        object_path : ObjectPath\n            The object path to be associated with the returned ExprDoc.\n\n        Returns\n        -------\n        doc : ExprDoc\n            The doc for this variable.\n        \"\"\"\n        return _ffi_api.VarTableGetVarDoc(self, obj, object_path)  # type: ignore # pylint: disable=no-member\n\n    def is_var_defined(self, obj: Object) -> bool:\n        \"\"\"\n        Check whether a variable is defined.\n\n        Parameters\n        ----------\n        obj : Object\n            The variable object.\n\n        Returns\n        -------\n        is_defined : bool\n            Whether the variable is defined.\n        \"\"\"\n        return _ffi_api.VarTableIsVarDefined(self, obj)  # type: ignore # pylint: disable=no-member\n\n    def __contains__(self, obj: Object) -> bool:\n        return self.is_var_defined(obj)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/support.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Support infra of TVM.\"\"\"\nimport json\nimport textwrap\nimport ctypes\nimport os\nimport sys\n\nimport tvm\nimport tvm._ffi\nfrom .runtime.module import Module\nfrom . import get_global_func\n\n\ndef libinfo():\n    \"\"\"Returns a dictionary containing compile-time info, including cmake flags and git commit hash\n\n    Returns\n    -------\n    info: Dict[str, str]\n        The dictionary of compile-time info.\n    \"\"\"\n    get_lib_info_func = get_global_func(\"support.GetLibInfo\", allow_missing=True)\n    if get_lib_info_func is not None:\n        lib_info = get_lib_info_func()\n        if lib_info is None:\n            return {}\n    else:\n        return {}\n    return dict(lib_info.items())\n\n\ndef describe():\n    \"\"\"\n    Print out information about TVM and the current Python environment\n    \"\"\"\n    info = list((k, v) for k, v in libinfo().items())\n    info = dict(sorted(info, key=lambda x: x[0]))\n    print(\"Python Environment\")\n    sys_version = sys.version.replace(\"\\n\", \" \")\n    uname = os.uname()\n    uname = f\"{uname.sysname} {uname.release} {uname.version} {uname.machine}\"\n    lines = [\n        f\"TVM version    = {tvm.__version__}\",\n        f\"Python version = {sys_version} ({sys.maxsize.bit_length() + 1} bit)\",\n        f\"os.uname()     = {uname}\",\n    ]\n    print(textwrap.indent(\"\\n\".join(lines), prefix=\"  \"))\n    print(\"CMake Options:\")\n    print(textwrap.indent(json.dumps(info, indent=2), prefix=\"  \"))\n\n\nclass FrontendTestModule(Module):\n    \"\"\"A tvm.runtime.Module whose member functions are PackedFunc.\"\"\"\n\n    def __init__(self, entry_name=None):\n        underlying_mod = get_global_func(\"testing.FrontendTestModule\")()\n        handle = underlying_mod.handle\n\n        # Set handle to NULL to avoid cleanup in c++ runtime, transferring ownership.\n        # Both cython and ctypes FFI use c_void_p, so this is safe to assign here.\n        underlying_mod.handle = ctypes.c_void_p(0)\n\n        super(FrontendTestModule, self).__init__(handle)\n        if entry_name is not None:\n            self.entry_name = entry_name\n\n    def add_function(self, name, func):\n        self.get_function(\"__add_function\")(name, func)\n\n    def __setitem__(self, key, value):\n        self.add_function(key, value)\n\n\ntvm._ffi._init_api(\"support\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Target description and codgen module.\n\nTVM's target string is in format ``<target_kind> [-option=value]...``.\n\nNote\n----\nThe list of options include:\n\n- **-device=<device name>**\n\n   The device name.\n\n- **-mtriple=<target triple>**\n\n   Specify the target triple, which is useful for cross\n   compilation.\n\n- **-mcpu=<cpuname>**\n\n   Specify a specific chip in the current architecture to\n   generate code for. By default this is infered from the\n   target triple and autodetected to the current architecture.\n\n- **-mattr=a1,+a2,-a3,...**\n\n   Override or control specific attributes of the target,\n   such as whether SIMD operations are enabled or not. The\n   default set of attributes is set by the current CPU.\n\n- **-mabi=<abi>**\n\n   Generate code for the specified ABI, for example \"lp64d\".\n\n- **-system-lib**\n\n   Build TVM system library module. System lib is a global module that contains\n   self registered functions in program startup. User can get the module using\n   :any:`tvm.runtime.system_lib`.\n   It is useful in environments where dynamic loading api like dlopen is banned.\n   The system lib will be available as long as the result code is linked by the program.\n\nWe can use :py:func:`tvm.target.Target` to create a tvm.target.Target from the target string.\nWe can also use other specific function in this module to create specific targets.\n\"\"\"\nfrom .target import Target, create, TargetKind\nfrom .target import (\n    cuda,\n    rocm,\n    mali,\n    intel_graphics,\n    arm_cpu,\n    rasp,\n    vta,\n    bifrost,\n    riscv_cpu,\n    hexagon,\n    stm32,\n)\nfrom .virtual_device import VirtualDevice\nfrom .compilation_config import make_compilation_config\nfrom .tag import list_tags\nfrom .generic_func import GenericFunc\nfrom .generic_func import generic_func, get_native_generic_func, override_native_generic_func\nfrom . import datatype\nfrom . import codegen\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.target\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"target\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Code generation related functions.\"\"\"\nfrom . import _ffi_api\nfrom .target import Target\n\n\ndef build_module(mod, target):\n    \"\"\"Build IRModule into Module.\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        The ir module.\n\n    target : str\n        The target module type.\n\n    Returns\n    -------\n    module : runtime.Module\n        The corressponding module.\n    \"\"\"\n    target = Target(target) if isinstance(target, str) else target\n    return _ffi_api.Build(mod, target)\n\n\ndef llvm_lookup_intrinsic_id(name):\n    \"\"\"Lookup LLVM intrinsic id by name.\n\n    Parameters\n    ----------\n    name : str\n        The name of the intrinsic.\n\n    Returns\n    -------\n    intrin_id : int\n        The intrinsic id.\n    \"\"\"\n    return _ffi_api.llvm_lookup_intrinsic_id(name)\n\n\ndef llvm_get_intrinsic_name(intrin_id: int) -> str:\n    \"\"\"Get the name of an intrinsic for a given id.\n\n    Parameters\n    ----------\n    intrin_id : int\n        The id of the intrinsic.\n\n    Returns\n    -------\n    name : str\n        The name of the intrinsic.\n    \"\"\"\n    return _ffi_api.llvm_get_intrinsic_name(intrin_id)\n\n\ndef llvm_version_major(allow_none=False):\n    \"\"\"Get the major LLVM version.\n\n    Parameters\n    ----------\n    allow_none : bool\n        Whether do we allow none.\n\n    Returns\n    -------\n    major : int\n        The major LLVM version.\n    \"\"\"\n    try:\n        return _ffi_api.llvm_version_major()\n    except AttributeError:\n        if allow_none:\n            return None\n        raise RuntimeError(\"LLVM version is not available, please check if you built TVM with LLVM\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/compilation_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Python bindings for creating CompilationConfigs.\"\"\"\nimport tvm\nfrom . import _ffi_api\n\n\ndef make_compilation_config(ctxt, target, target_host=None):\n    \"\"\"Returns a CompilationConfig appropriate for target and target_host, using the same\n    representation conventions as for the standard build interfaces. Intended only for unit\n    testing.\"\"\"\n    raw_targets = tvm.target.Target.canon_multi_target_and_host(target, target_host)\n    return _ffi_api.MakeCompilationConfig(ctxt, raw_targets)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/datatype.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Bring Your Own Datatypes custom datatype framework\n\nTODO(@gussmith23 @hypercubestart) link to BYODT docs when they exist\"\"\"\nimport tvm\nfrom tvm.runtime import convert, DataType\nfrom tvm.tir.expr import (\n    Call as _Call,\n    Cast as _Cast,\n    FloatImm as _FloatImm,\n    BinaryOpExpr as _BinaryOpExpr,\n)\nfrom tvm.tir.op import call_pure_extern\nfrom tvm._ffi import register_func as _register_func\nfrom tvm.tir import call_intrin\n\n\ndef register(type_name, type_code):\n    \"\"\"Register a custom datatype with the given type name and type code\n\n    Currently, the type code is manually allocated by the user, and the user\n    must ensure that no two custom types share the same code. Generally, this\n    should be straightforward, as the user will be manually registering all of\n    their custom types.\n\n    Example:\n\n    .. code-block:: python\n\n        # Register a dtype named 'posites2' under type code 130.\n        tvm.target.datatype.register('posites2', 130)\n\n\n    Parameters\n    ----------\n    type_name : str\n        The name of the custom datatype.\n\n    type_code : int\n        The type's code, which should be >= kCustomBegin. See\n        include/tvm/runtime/data_type.h.\n    \"\"\"\n    tvm.runtime._ffi_api._datatype_register(type_name, type_code)\n\n\ndef get_type_name(type_code):\n    \"\"\"Get the type name of a custom datatype from the type code.\n\n    Note that this only works for custom datatypes registered with\n    tvm.target.datatype.register(). It does not work for TVM-native types.\n\n    Example:\n\n    .. code-block:: python\n\n        tvm.target.datatype.register('posites2', 130)\n        assert tvm.target.datatype.get_type_name(130) == 'posites2'\n\n    Parameters\n    ----------\n    type_code : int\n        The type code of the custom datatype.\n\n    Returns\n    -------\n    type_name : String\n        The name of the custom datatype.\n\n    \"\"\"\n    return tvm.runtime._ffi_api._datatype_get_type_name(type_code)\n\n\ndef get_type_code(type_name):\n    \"\"\"Get the type code of a custom datatype from its type name\n\n    Note that this only works for custom datatypes registered with\n    tvm.target.datatype.register(). It does not work for TVM-native types.\n\n    Example:\n\n    .. code-block:: python\n\n        tvm.target.datatype.register('posites2', 130)\n        assert tvm.target.datatype.get_type_code('posites2') == 130\n\n    Parameters\n    ----------\n    type_name : str\n        The type name\n\n    Returns\n    -------\n    type_code : int\n        The type code of the custom datatype.\n    \"\"\"\n    return tvm.runtime._ffi_api._datatype_get_type_code(type_name)\n\n\ndef get_type_registered(type_code):\n    \"\"\"Returns true if a custom datatype is registered under the given type code\n\n    Example:\n\n    .. code-block:: python\n\n        tvm.target.datatype.register('posites2', 130)\n        assert tvm.target.datatype.get_type_registered(130)\n\n    Parameters\n    ----------\n    type_code: int\n        The type code\n\n    Returns\n    -------\n    type_registered : bool\n        True if a custom datatype is registered under this type code, and false\n        otherwise.\n    \"\"\"\n    return tvm.runtime._ffi_api._datatype_get_type_registered(type_code)\n\n\ndef register_op(\n    lower_func, op_name, target, src_type_name, dest_type_name=None, intrinsic_name=None\n):\n    \"\"\"Register a lowering function for a specific operator of a custom datatype\n\n    At build time, Relay must lower operators over custom datatypes into\n    operators it understands how to compile. For each custom datatype operator\n    which Relay finds while lowering custom datatypes, Relay expects to find a\n    user-defined lowering function. Users register their user-defined lowering\n    functions using this function.\n\n    Users should use create_lower_func to create their lowering function. It\n    should serve most use-cases.\n\n    Currently, this will work with Casts, intrinsics (e.g. sqrt, sigmoid), and\n    binary expressions (e.g. Add, Sub, Mul, Div).\n\n    See the LowerCustomDatatypes pass to see how registered functions are used.\n\n    Lowering Functions\n    ------------------\n    TODO(@gussmith23) Get the terminology right here.\n    Lowering functions take in a Relay node, and should return a semantically\n    equivalent Relay node which Relay can build. This means that the returned\n    node should not contain any custom datatypes. Users should likely not need\n    to define lowering functions by hand -- see the helper function\n    create_lower_func.\n\n    Parameters\n    ----------\n    lower_func : function\n        The lowering function to call. See create_lower_func.\n\n    op_name : str\n        The name of the operation which the function computes, given by its\n        class name (e.g. Add, LE, Cast, Call).\n\n    target : str\n        The name of codegen target.\n\n    src_type_name : str\n        The name of the custom datatype, e.g. posites2 (but not custom[posites2]32).\n        If op_name is not \"Cast\", then target type is guaranteed to be the same as src_type_name.\n\n    dest_type_name : str\n        If op_name is \"Cast\", then this is required and should be set to the dest datatype of\n        the argument to the Cast. If op_name is not \"Cast\", this is unused.\n\n    intrinsic_name : str\n        If op_name is \"Call\" and intrinsic_name is not None, then we assume the\n        op is a Call to an Intrinsic, and intrinsic_name is the intrinsic's\n        name.\n    \"\"\"\n\n    if op_name == \"Cast\":\n        assert dest_type_name is not None\n        lower_func_name = (\n            \"tvm.datatype.lower.\"\n            + target\n            + \".\"\n            + op_name\n            + \".\"\n            + dest_type_name\n            + \".\"\n            + src_type_name\n        )\n    elif op_name == \"Call\" and intrinsic_name is not None:\n        lower_func_name = (\n            \"tvm.datatype.lower.\"\n            + target\n            + \".\"\n            + op_name\n            + \".intrin.\"\n            + intrinsic_name\n            + \".\"\n            + src_type_name\n        )\n    else:\n        lower_func_name = \"tvm.datatype.lower.\" + target + \".\" + op_name + \".\" + src_type_name\n    tvm._ffi.register_func(lower_func_name, lower_func)\n\n\ndef register_min_func(func, type_name):\n    \"\"\"Register the function that returns the minimum representable value of type_name.\n\n    Operators such as max pooling and argmax require the minimum\n    finite value representable by the datatype the op operating on.\n    Users can use this function to register a function that returns a TIR expression node\n    outputting the minimum representable value of their custom data type.\n\n    Users should use create_min_lower_func to create their lowering function. It\n    should serve most use-cases.\n\n    Note: for special cases when it is known that the custom datatype is representable\n    by a float, the user can create their own lowering func that returns a FloatImm.\n    The benefits are allowing optimizations such as rewrites to work as expected on custom\n    datatypes.\n\n    Parameters\n    ----------\n    func : function\n        Input is an integer num_bits, should return a TIR expression node that\n        represents a scalar tensor of type custom[type_name]num_bits with the minimum\n        representable value.\n\n    type_name : str\n        The name of the custom datatype, e.g. posites2 (but not custom[posites2]32).\n    \"\"\"\n    _register_func(\"tvm.datatype.min.\" + type_name, func)\n\n\ndef create_min_lower_func(extern_func_map, type_name):\n    \"\"\"Returns a lowering function for getting the minimum value of a custom datatype.\n\n    Parameters\n    ----------\n    extern_func_map : map\n        A map from bit lengths to the name of the extern \"C\" function to lower to.\n\n    type_name : string\n        The name of the custom datatype, e.g. posites2 (but not custom[posites2]32).\n    \"\"\"\n\n    def lower(num_bits):\n        dtype = f\"custom[{type_name}]{num_bits}\"\n\n        if num_bits not in extern_func_map:\n            raise RuntimeError(\"missing minimum function for {dtype}\")\n\n        return call_pure_extern(dtype, extern_func_map[num_bits])\n\n    return lower\n\n\ndef create_lower_func(extern_func_map):\n    \"\"\"Returns a function which lowers an operation to a function call.\n\n    Parameters\n    ----------\n    extern_func_map : map\n        If lowering a Cast, extern_func_map should be a map from tuples of\n        (src_bit_length, dest_bit_length) to the name of the extern \"C\" function to lower to.\n\n        Otherwise, for unary and binary ops, it should simply be a map\n        from bit_length to the name of the extern \"C\" function to lower to.\n    \"\"\"\n\n    def lower(op):\n        \"\"\"\n        Takes an op---either a Cast, Call, or a binary op (e.g. an Add) and returns a\n        call to the specified external function, passing the op's argument\n        or arguments. The return type of the call depends\n        on the type of the op: if it is a custom type, then a uint of the same\n        width as the custom type is returned. Otherwise, the type is\n        unchanged.\"\"\"\n        dtype = op.dtype\n        t = DataType(dtype)\n        if get_type_registered(t.type_code):\n            dtype = \"uint\" + str(t.bits)\n            if t.lanes > 1:\n                dtype += \"x\" + str(t.lanes)\n\n        key = t.bits\n        if isinstance(op, _Cast):\n            src_bits = DataType(op.value.dtype).bits\n            key = (src_bits, t.bits)\n\n        if key not in extern_func_map:\n            raise RuntimeError(f\"missing key {key} in extern_func_map for {op.astext()}\")\n\n        if isinstance(op, _Cast):\n            return call_pure_extern(dtype, extern_func_map[key], op.value)\n        if isinstance(op, _FloatImm):\n            return call_pure_extern(dtype, extern_func_map[key], op.value)\n        if isinstance(op, _Call):\n            return call_pure_extern(dtype, extern_func_map[key], *op.args)\n        if isinstance(op, _BinaryOpExpr):\n            return call_pure_extern(dtype, extern_func_map[key], op.a, op.b)\n\n        raise RuntimeError(f\"lowering unsupported op: {op.astext()}\")\n\n    return lower\n\n\ndef lower_ite(ite_op):\n    \"\"\"Lowered if then else function that calls intrinsic if_then_else.\n    Unlike a function lowered by create_lower_func, this function\n    calls the tvm intrinsic if_then_else.\n\n    Parameters\n    ----------\n    ite_op : Op\n        Takes an if then else op and returns a\n        call to tir.if_then_else function, passing the op's\n        arguments. The return type of the call if a uint of the same\n        width as the custom type is returned.\n    \"\"\"\n    dtype = ite_op.dtype\n    t = tvm.DataType(dtype)\n    assert get_type_registered(t.type_code)\n    dtype = \"uint\" + str(t.bits)\n    if t.lanes > 1:\n        dtype += \"x\" + str(t.lanes)\n    return call_intrin(\n        dtype,\n        \"tir.if_then_else\",\n        convert(ite_op.args[0]),\n        convert(ite_op.args[1]),\n        convert(ite_op.args[2]),\n    )\n\n\ndef lower_call_pure_extern(op):\n    \"\"\"Lowered call pure extern function that calls intrinsic call_pure_extern.\n    Unlike a function lowered by create_lower_func, this function\n    calls the tvm intrinsic call_pure_extern.\n\n    Parameters\n    ----------\n    ite_op : Op\n        Takes a call_pure_extern op and returns a\n        call to tir.call_pure_extern function, passing the op's\n        arguments. The return type of the call if a uint of the same\n        width as the custom type is returned.\n    \"\"\"\n    dtype = op.dtype\n    t = tvm.DataType(dtype)\n    assert get_type_registered(t.type_code)\n    dtype = \"uint\" + str(t.bits)\n    if t.lanes > 1:\n        dtype += \"x\" + str(t.lanes)\n    return call_intrin(dtype, \"tir.call_pure_extern\", *op.args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/generic_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Generic function.\"\"\"\n\nimport tvm._ffi\n\ntry:\n    from decorator import decorate\nexcept ImportError:\n    # Allow decorator to be missing in runtime\n    if not tvm._ffi.base._RUNTIME_ONLY:\n        raise\n\nfrom tvm.runtime import Object\nfrom .target import Target\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object\nclass GenericFunc(Object):\n    \"\"\"GenericFunc node reference. This represents a generic function\n    that may be specialized for different targets. When this object is\n    called, a specialization is chosen based on the current target.\n\n    Note\n    ----\n    Do not construct an instance of this object, it should only ever be\n    used as a return value from calling into C++.\n    \"\"\"\n\n    def __call__(self, *args):\n        return _ffi_api.GenericFuncCallFunc(self, *args)\n\n    def set_default(self, func, allow_override=False):\n        \"\"\"Set the default function to be used if no specializations match\n        the current target.\n\n        Parameters\n        ----------\n        func : function\n            The default function\n\n        allow_override : bool\n            Whether to allow the current default to be overridden\n        \"\"\"\n        _ffi_api.GenericFuncSetDefault(self, func, allow_override)\n\n    def register(self, func, key_list, allow_override=False):\n        \"\"\"Register a specialization for this GenericFunc.\n\n        Parameters\n        ----------\n        func : function\n            The function to be registered.\n\n        key : str or list of str\n            The key to be registered.\n\n        allow_override : bool, optional\n            Whether to allow existing keys to be overridden.\n        \"\"\"\n        key_list = [key_list] if isinstance(key_list, str) else key_list\n        _ffi_api.GenericFuncRegisterFunc(self, func, key_list, allow_override)\n\n    def get_packed_func(self):\n        \"\"\"Get the packed function specified for the current target.\n\n        Returns\n        -------\n        func : PackedFunc\n            The function specified for the current target. Return the default\n            function if no specializations match the current target.\n        \"\"\"\n        return _ffi_api.GenericFuncGetPackedFunc(self)\n\n\ndef get_native_generic_func(name):\n    \"\"\"Get a generic function from the global registry. If no\n    function is registered under the given name, a new generic\n    function is created.\n\n    Parameters\n    ----------\n    name : string\n        The name of the generic function to get\n\n    Returns\n    -------\n    func : GenericFunc\n        The generic function for the given name\n    \"\"\"\n    return _ffi_api.GenericFuncGetGlobal(name)\n\n\ndef override_native_generic_func(func_name):\n    \"\"\"Override a generic function defined in C++\n\n    Generic function allows registration of further functions\n    that can be dispatched on current target context.\n    If no registered dispatch is matched, the fdefault will be called.\n\n    Parameters\n    ----------\n    func_name : string\n        The name of the generic func to be overridden\n\n    Returns\n    -------\n    fgeneric : function\n        A wrapped generic function.\n\n    Example\n    -------\n    .. code-block:: python\n\n      import tvm\n      # wrap function as target generic\n      @tvm.target.override_native_generic_func(\"my_func\")\n      def my_func(a):\n          return a + 1\n      # register specialization of my_func under target cuda\n      @my_func.register(\"cuda\")\n      def my_func_cuda(a):\n          return a + 2\n      # displays 3, because my_func is called\n      print(my_func(2))\n      # displays 4, because my_func_cuda is called\n      with tvm.target.cuda():\n          print(my_func(2))\n    \"\"\"\n    generic_func_node = get_native_generic_func(func_name)\n\n    def fdecorate(fdefault):\n        \"\"\"Wrap a target generic function, overriding the previous\n        default that was set for the generic function.\n\n        Parameters\n        ----------\n        fdefault : function\n            The default function.\n\n        Returns\n        -------\n        fgeneric : function\n            A wrapped generic function.\n\n        \"\"\"\n        generic_func_node.set_default(fdefault, allow_override=True)\n\n        def register(key, func=None, override=True):\n            \"\"\"Register function to be the dispatch function.\n\n            Parameters\n            ----------\n            key : str or list of str\n                The key to be registered.\n\n            func : function\n                The function to be registered.\n\n            override : bool, optional\n                Whether override existing registration.\n\n            Returns\n            -------\n            The register function is necessary.\n            \"\"\"\n\n            def _do_reg(myf):\n                generic_func_node.register(myf, key, override)\n                return myf\n\n            if func:\n                return _do_reg(func)\n            return _do_reg\n\n        def dispatch_func(func, *args, **kwargs):\n            # pylint: disable=unused-argument\n            \"\"\"The wrapped dispath function\"\"\"\n            if kwargs:\n                raise RuntimeError(\n                    \"Keyword arguments cannot be used when invoking generic_func %s\" % func_name\n                )\n            return generic_func_node(*args)\n\n        fresult = decorate(fdefault, dispatch_func)\n        fresult.fdefault = fdefault\n        fresult.register = register\n        fresult.generic_func_node = generic_func_node\n        return fresult\n\n    return fdecorate\n\n\ndef generic_func(fdefault):\n    \"\"\"Wrap a target generic function.\n\n    Generic function allows registration of further functions\n    that can be dispatched on current target context.\n    If no registered dispatch is matched, the fdefault will be called.\n\n    Parameters\n    ----------\n    fdefault : function\n        The default function.\n\n    Returns\n    -------\n    fgeneric : function\n        A wrapped generic function.\n\n    Example\n    -------\n    .. code-block:: python\n\n      import tvm\n      # wrap function as target generic\n      @tvm.target.generic_func\n      def my_func(a):\n          return a + 1\n      # register specialization of my_func under target cuda\n      @my_func.register(\"cuda\")\n      def my_func_cuda(a):\n          return a + 2\n      # displays 3, because my_func is called\n      print(my_func(2))\n      # displays 4, because my_func_cuda is called\n      with tvm.target.cuda():\n          print(my_func(2))\n    \"\"\"\n    dispatch_dict = {}\n    func_name = fdefault.__name__\n\n    def register(key, func=None, override=False):\n        \"\"\"Register function to be the dispatch function.\n\n        Parameters\n        ----------\n        key : str or list of str\n            The key to be registered.\n\n        func : function\n            The function to be registered.\n\n        override : bool\n            Whether override existing registration.\n\n        Returns\n        -------\n        The register function is necessary.\n        \"\"\"\n\n        def _do_reg(myf):\n            key_list = [key] if isinstance(key, str) else key\n            for k in key_list:\n                if k in dispatch_dict and not override:\n                    raise ValueError(\"Key is already registered for %s\" % func_name)\n                dispatch_dict[k] = myf\n            return myf\n\n        if func:\n            return _do_reg(func)\n        return _do_reg\n\n    def dispatch_func(func, *args, **kwargs):\n        \"\"\"The wrapped dispatch function\"\"\"\n        target = Target.current()\n        if target is None:\n            return func(*args, **kwargs)\n        for k in target.keys:\n            if k in dispatch_dict:\n                return dispatch_dict[k](*args, **kwargs)\n        return func(*args, **kwargs)\n\n    def get_packed_func():\n        \"\"\"The wrapped to get dispatched function\"\"\"\n        target = Target.current()\n        if target is None:\n            return fdefault\n        for k in target.keys:\n            if k in dispatch_dict:\n                return dispatch_dict[k]\n        return fdefault\n\n    fdecorate = decorate(fdefault, dispatch_func)\n    fdecorate.register = register\n    fdecorate.fdefault = fdefault\n    fdecorate.dispatch_dict = dispatch_dict\n    fdecorate.get_packed_func = get_packed_func\n    return fdecorate\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Target dependent intrinsic registration.\"\"\"\nfrom tvm.ir import register_intrin_lowering\nfrom tvm.tir import call_pure_extern\n\n\ndef _rule_float_suffix(op):\n    \"\"\"Intrinsic rule: Add float suffix if it is float32.\n\n    This is an example intrinsic generation rule.\n\n    Parameters\n    ----------\n    op : PrimExpr\n        The call expression of original intrinsic.\n\n    Returns\n    -------\n    ret : PrimExpr\n        The translated intrinsic rule.\n        Return same op if no translation is possible.\n\n    See Also\n    --------\n    register_intrin_lowering : The registration function for intrinsic lowering rule.\n    \"\"\"\n    name = op.op.name\n    assert name.startswith(\"tir.\")\n    prefix = name[4:]\n\n    if op.dtype == \"float32\":\n        return call_pure_extern(op.dtype, \"%sf\" % prefix, *op.args)\n    if op.dtype == \"float64\":\n        return call_pure_extern(op.dtype, prefix, *op.args)\n    return op\n\n\ndef _rule_float_direct(op):\n    \"\"\"Intrinsic rule: Directly call pure extern function for floats.\n\n    This is an example intrinsic generation rule.\n\n    Parameters\n    ----------\n    op : PrimExpr\n        The call expression of original intrinsic.\n\n    Returns\n    -------\n    ret : PrimExpr\n        The translated intrinsic rule.\n        Return same op if no translation is possible.\n\n    See Also\n    --------\n    register_intrin_lowering : The registration function for intrinsic lowering rule.\n    \"\"\"\n    if str(op.dtype).startswith(\"float\"):\n        return call_pure_extern(op.dtype, op.op.name[4:], *op.args)\n    return None\n\n\n# opencl pattern for exp\nregister_intrin_lowering(\"tir.exp\", target=\"opencl\", f=_rule_float_direct, level=99)\n# default pattern for exp\nregister_intrin_lowering(\"tir.exp\", target=\"default\", f=_rule_float_suffix, level=99)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/tag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Target tags\"\"\"\nfrom typing import Any, Dict, Optional\nfrom . import _ffi_api\nfrom .target import Target\n\n\ndef list_tags() -> Optional[Dict[str, Target]]:\n    \"\"\"Returns a dict of tags, which maps each tag name to its corresponding target.\n\n    Returns\n    -------\n    tag_dict : Optional[Dict[str, Target]]\n        The dict of tags mapping each tag name to its corresponding target.\n        None if TVM is built in runtime-only mode.\n    \"\"\"\n    if hasattr(_ffi_api, \"TargetTagListTags\"):\n        return _ffi_api.TargetTagListTags()\n    return None\n\n\ndef register_tag(name: str, config: Dict[str, Any], override: bool = False) -> Optional[Target]:\n    \"\"\"Add a user-defined tag into the target tag registry.\n\n    Parameters\n    ----------\n    name: str\n        Name of the target, e.g. \"nvidia/gtx1080ti\"\n    config : Dict[str, Any]\n        The config dict used to create the target\n    override: bool\n        A boolean flag indicating if overriding existing tags are allowed.\n        If False and the tag has been registered already, an exception will be thrown.\n\n    Returns\n    -------\n    target : Optional[Target]\n        The target corresponding to the tag\n        None if TVM is built in runtime-only mode.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        register_tag(\"nvidia/gtx1080ti\", config={\n            \"kind\": \"cuda\",\n            \"arch\": \"sm_61\",\n        })\n    \"\"\"\n    if hasattr(_ffi_api, \"TargetTagAddTag\"):\n        return _ffi_api.TargetTagAddTag(name, config, override)\n    return None\n\n\n# To check the correctness of all registered tags, the call is made in library loading time.\nlist_tags()\n\n# We purposely maintain all tags in the C++ side to support pure C++ use cases,\n# and the Python API is only used for fast prototyping.\nregister_tag(\n    \"nvidia/gtx1080ti\",\n    config={\n        \"kind\": \"cuda\",\n        \"arch\": \"sm_61\",\n    },\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Target data structure.\"\"\"\nimport json\nimport re\nimport warnings\n\nimport tvm._ffi\nfrom tvm._ffi import register_func as _register_func\nfrom tvm.runtime import Object, convert\nfrom tvm.runtime.container import String\nfrom tvm.ir.container import Map, Array\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object\nclass TargetKind(Object):\n    \"\"\"Kind of a compilation target\"\"\"\n\n    @property\n    def options(self):\n        \"\"\"Returns the dict of available option names and types\"\"\"\n        return dict(_ffi_api.ListTargetKindOptions(self))\n\n    @staticmethod\n    def options_from_name(kind_name: str):\n        \"\"\"Returns the dict of available option names and types from a name of TargetKind\"\"\"\n        return dict(_ffi_api.ListTargetKindOptionsFromName(kind_name))\n\n\nclass TargetFeatures:\n    def __init__(self, target):\n        self.target = target\n\n    def __getattr__(self, name: str):\n        return _ffi_api.TargetGetFeature(self.target, name)\n\n\n@tvm._ffi.register_object\nclass Target(Object):\n    \"\"\"Target device information, use through TVM API.\n\n    Note\n    ----\n    You can create target using the constructor or the following functions\n\n    - :py:func:`tvm.target.arm_cpu` create arm_cpu target\n    - :py:func:`tvm.target.cuda` create CUDA target\n    - :py:func:`tvm.target.rocm` create ROCM target\n    - :py:func:`tvm.target.mali` create Mali target\n    - :py:func:`tvm.target.intel_graphics` create Intel Graphics target\n    \"\"\"\n\n    def __init__(self, target, host=None):\n        \"\"\"Construct a TVM target object from\n        1) Raw target string\n        2) Target config dict\n        3) Target tag\n\n        Parameters\n        ----------\n        target : Union[str, Dict[str, Any]]\n            Can be one of a literal target string, a json string describing\n            a configuration, or a dictionary of configuration options.\n            When using a dictionary or json string to configure target, the\n            possible values are:\n\n            kind :  str (required)\n                Which codegen path to use, for example 'llvm' or 'cuda'.\n            keys : List of str (optional)\n                A set of strategies that can be dispatched to. When using\n                \"kind=opencl\" for example, one could set keys to [\"mali\", \"opencl\", \"gpu\"].\n            device : str (optional)\n                A single key that corresponds to the actual device being run on.\n                This will be effectively appended to the keys.\n            libs : List of str (optional)\n                The set of external libraries to use. For example ['cblas', 'mkl'].\n            system-lib : bool (optional)\n                If True, build a module that contains self registered functions.\n                Useful for environments where dynamic loading like dlopen is banned.\n            mcpu : str (optional)\n                The specific cpu being run on. Serves only as an annotation.\n            model : str (optional)\n                An annotation indicating what model a workload came from.\n            runtime : str (optional)\n                An annotation indicating which runtime to use with a workload.\n            mtriple : str (optional)\n                The llvm triplet describing the target, for example \"arm64-linux-android\".\n            mattr : List of str (optional)\n                The llvm features to compile with, for example [\"+avx512f\", \"+mmx\"].\n            mfloat-abi : str (optional)\n                An llvm setting that is one of 'hard' or 'soft' indicating whether to use\n                hardware or software floating-point operations.\n            mabi : str (optional)\n                An llvm setting. Generate code for the specified ABI, for example \"lp64d\".\n            host : Union[str, Dict[str, Any]] (optional)\n                Description for target host. Can be recursive. Similar to target.\n        host : Optional[Union[str, Dict[str, Any]]]\n            Similar to target but for target host. Can be one of a literal target host string,\n            a json string describing a configuration, or a dictionary of configuration options.\n            When using a dictionary or json string to configure target, the possible values are\n            same as target.\n        \"\"\"\n        if isinstance(target, str) and \"-libs=mkldnn\" in target:\n            target = target.replace(\"mkldnn\", \"dnnl\")\n            warnings.warn(\n                \"Legacy support of mkldnn is going to be deprecated. \"\n                \"Please use -libs=dnnl instead.\",\n            )\n        if isinstance(target, (dict, str)):\n            target = convert(target)\n        if isinstance(host, (dict, str)):\n            host = convert(host)\n        if target is None or not isinstance(target, (Map, String, Target)):\n            raise ValueError(\"target has to be a string or dictionary.\")\n        if host is not None:\n            if not isinstance(host, (Map, String, Target)):\n                raise ValueError(\"target host has to be a string or dictionary.\")\n            self.__init_handle_by_constructor__(_ffi_api.Target, Target(target), Target(host))\n        else:\n            self.__init_handle_by_constructor__(_ffi_api.Target, target)\n\n    def __enter__(self):\n        _ffi_api.TargetEnterScope(self)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        _ffi_api.TargetExitScope(self)\n\n    def export(self):\n        return _ffi_api.TargetExport(self)\n\n    def with_host(self, host=None):\n        return _ffi_api.WithHost(self, Target(host))\n\n    @staticmethod\n    def current(allow_none=True):\n        \"\"\"Returns the current target.\n\n        Parameters\n        ----------\n        allow_none : bool\n            Whether allow the current target to be none\n\n        Raises\n        ------\n        ValueError if current target is not set.\n        \"\"\"\n        return _ffi_api.TargetCurrent(allow_none)\n\n    @property\n    def arch(self):\n        \"\"\"Returns the cuda arch from the target if it exists.\"\"\"\n        return str(self.attrs.get(\"arch\", \"\"))\n\n    @property\n    def max_num_threads(self):\n        \"\"\"Returns the max_num_threads from the target if it exists.\"\"\"\n        return int(self.attrs[\"max_num_threads\"])\n\n    @property\n    def thread_warp_size(self):\n        \"\"\"Returns the thread_warp_size from the target if it exists.\"\"\"\n        return int(self.attrs[\"thread_warp_size\"])\n\n    @property\n    def max_function_args(self):\n        return int(self.attrs.get(\"max_function_args\", -1))\n\n    @property\n    def device_name(self):\n        return str(self.attrs.get(\"device\", \"\"))\n\n    @property\n    def model(self):\n        \"\"\"Returns model from the target if it exists.\"\"\"\n        return str(self.attrs.get(\"model\", \"unknown\"))\n\n    @property\n    def mcpu(self):\n        \"\"\"Returns the mcpu from the target if it exists.\"\"\"\n        return str(self.attrs.get(\"mcpu\", \"\"))\n\n    @property\n    def mattr(self):\n        \"\"\"Returns the mattr from the target if it exists.\"\"\"\n        return list(self.attrs.get(\"mattr\", []))\n\n    @property\n    def supports_integer_dot_product(self):\n        if self.attrs.get(\"supports_integer_dot_product\", []):\n            return bool(self.attrs[\"supports_integer_dot_product\"])\n        if self.kind.name == \"cuda\":\n            sm_version = int(self.arch.split(\"_\")[1])\n            if sm_version >= 61:\n                return True\n        return False\n\n    @property\n    def libs(self):\n        return list(self.attrs.get(\"libs\", []))\n\n    @property\n    def features(self):\n        return TargetFeatures(self)\n\n    def get_kind_attr(self, attr_name):\n        \"\"\"Get additional attribute about the target kind.\n\n        Parameters\n        ----------\n        attr_name : str\n            The attribute name.\n\n        Returns\n        -------\n        value : object\n            The attribute value\n        \"\"\"\n        return _ffi_api.TargetKindGetAttr(self.kind, attr_name)\n\n    def get_target_device_type(self):\n        \"\"\"Returns the device_type for this target.\"\"\"\n        return _ffi_api.TargetGetDeviceType(self)\n\n    @staticmethod\n    def list_kinds():\n        \"\"\"Returns the list of available target names.\"\"\"\n        return list(_ffi_api.ListTargetKinds())\n\n    @staticmethod\n    def canon_target(target):\n        \"\"\"Given a single target-like object, returns the TVM Target object representing it.\n        Can convert from:\n        - None (to None).\n        - An existing TVM Target object.\n        - A string, eg \"cuda\" or \"cuda -arch=sm_80\"\n        - A Python dictionary, eg {\"kind\": \"cuda\", \"arch\": \"sm_80\" }\n        \"\"\"\n        if target is None:\n            return None\n        if isinstance(target, Target):\n            return target\n        return Target(target)\n\n    @staticmethod\n    def canon_target_and_host(target, target_host=None):\n        \"\"\"Returns a TVM Target capturing target and target_host. Also returns the host in\n        canonical form. The given target can be in any form recognized by\n        Target.canon_target. If given, target_host can be in any form recognized by\n        Target.canon_target. If target_host is given it will be set as the 'host' in the\n        result Target object (and a warning given).\n\n        Note that this method does not support heterogeneous compilation targets.\n        \"\"\"\n        target = Target.canon_target(target)\n        if target is None:\n            assert target_host is None, \"Target host is not empty when target is empty.\"\n            return target, target_host\n        if target.host is None and target_host is not None:\n            warnings.warn(\n                \"target_host parameter is going to be deprecated. \"\n                \"Please pass in tvm.target.Target(target, host=target_host) instead.\"\n            )\n            target_host = Target.canon_target(target_host)\n            target = target.with_host(target_host)\n        if target is not None:\n            # In case the target already had a host, extract it here.\n            target_host = target.host\n        return target, target_host\n\n    @staticmethod\n    def canon_multi_target(multi_targets):\n        \"\"\"Given a single target-like object, or a collection-like object of target-like objects,\n        returns a TVM Array of TVM Target objects representing then. Can convert from:\n        - None (to None).\n        - A single target-like object in a form recognized by canon_target.\n        - A Python list or TVM Array of target-like objects in a form recognized by\n        canon_target.\n        - A Python dict or TVM Map from TVM IntImm objects representing device types to\n        a target-like object in a form recognized by canon_target. (This is a legacy\n        method to represent heterogeneous targets. The keys are ignored.)\n        \"\"\"\n        if multi_targets is None:\n            return None\n        if isinstance(multi_targets, (dict, Map)) and \"kind\" not in multi_targets:\n            # Convert legacy heterogeneous map representation to ordinary list of targets.\n            return Target.canon_multi_target(list(multi_targets.values()))\n        if isinstance(multi_targets, (list, Array)):\n            # Multiple Target results.\n            return convert([Target.canon_target(tgt) for tgt in multi_targets])\n        # Single Target result.\n        return convert([Target.canon_target(multi_targets)])\n\n    @staticmethod\n    def canon_multi_target_and_host(target, target_host=None):\n        \"\"\"Returns a TVM Array<Target> capturing target and target_host. The given target can be in\n        any form recognized by Target.canon_multi_target. If given, target_host can be in\n        any form recognized by Target.canon_target. If target_host is given it will be set\n        as the 'host' in each result Target object (and a warning given).\n        \"\"\"\n        # Convert target to Array<Target>, but not yet accounting for any host.\n        raw_targets = Target.canon_multi_target(target)\n        assert raw_targets is not None and len(raw_targets) > 0\n        # Convert host to Target, if given.\n        if raw_targets[0].host is None and target_host is not None:\n            warnings.warn(\n                \"target_host parameter is going to be deprecated. \"\n                \"Please pass in tvm.target.Target(target, host=target_host) instead.\"\n            )\n            # Make sure the (canonical) host is captured in all the (canonical) targets.\n            target_host = Target.canon_target(target_host)\n            raw_targets = convert([tgt.with_host(target_host) for tgt in raw_targets])\n        return raw_targets\n\n    @staticmethod\n    def canon_target_map_and_host(target_map, target_host=None):\n        \"\"\"Returns target_map as a map from TVM Target's in canonical form to IRModules. The keys\n        of the input target_map can be in any form recognized by Target.canon_target.\n        Similarly, if given, target_host can be in any form recognized by\n        Target.canon_target. The final target_map keys will capture the target_host in\n        canonical form. Also returns the target_host in canonical form.\"\"\"\n        new_target_map = {}\n        canonical_target_host = None\n        for tgt, mod in target_map.items():\n            tgt = Target.canon_target(tgt)\n            assert tgt is not None\n            if canonical_target_host is None:\n                if tgt.host is not None:\n                    canonical_target_host = tgt.host\n                elif target_host is not None:\n                    # No deprecation warning in this case since host may have been manufactured\n                    # behind the scenes in build_module.py build.\n                    canonical_target_host = Target.canon_target(target_host)\n            if tgt.host is None and canonical_target_host is not None:\n                tgt = tgt.with_host(canonical_target_host)\n            new_target_map[tgt] = mod\n        return new_target_map, canonical_target_host\n\n    @staticmethod\n    def target_or_current(target):\n        \"\"\"Returns target, or the current target in the environment if target is None\"\"\"\n        if target is None:\n            target = Target.current()\n        if target is None:\n            raise ValueError(\"Target is not set in env or passed as argument.\")\n        return target\n\n\n# TODO(@tvm-team): Deprecate the helper functions below. Encourage the usage of config dict instead.\ndef _merge_opts(opts, new_opts):\n    \"\"\"Helper function to merge options\"\"\"\n    if isinstance(new_opts, str):\n        new_opts = new_opts.split()\n    if new_opts:\n        opt_set = set(opts)\n        new_opts = [opt for opt in new_opts if opt not in opt_set]\n        return opts + new_opts\n    return opts\n\n\ndef cuda(model=\"unknown\", arch=None, options=None):\n    \"\"\"Returns a cuda target.\n\n    Parameters\n    ----------\n    model: str\n        The model of cuda device (e.g. 1080ti)\n    arch: str\n        The cuda architecture (e.g. sm_61)\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = _merge_opts([\"-model=%s\" % model], options)\n    if arch:\n        opts = _merge_opts([\"-arch=%s\" % arch], opts)\n    if not any([\"-arch\" in opt for opt in opts]):\n        warnings.warn(\"Try specifying cuda arch by adding 'arch=sm_xx' to your target.\")\n    return Target(\" \".join([\"cuda\"] + opts))\n\n\ndef rocm(model=\"unknown\", options=None):\n    \"\"\"Returns a ROCM target.\n\n    Parameters\n    ----------\n    model: str\n        The model of this device\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = _merge_opts([\"-model=%s\" % model], options)\n    return Target(\" \".join([\"rocm\"] + opts))\n\n\ndef mali(model=\"unknown\", options=None):\n    \"\"\"Returns a ARM Mali GPU target.\n\n    Parameters\n    ----------\n    model: str\n        The model of this device\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = [\"-device=mali\", \"-model=%s\" % model]\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"opencl\"] + opts))\n\n\ndef intel_graphics(model=\"unknown\", options=None):\n    \"\"\"Returns an Intel Graphics target.\n\n    Parameters\n    ----------\n    model: str\n        The model of this device\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = [\"-device=intel_graphics\", \"-model=%s\" % model, \"-thread_warp_size=16\"]\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"opencl\"] + opts))\n\n\nMICRO_SUPPORTED_MODELS = {\n    \"host\": [],\n    \"atsamd51\": [\"-mcpu=cortex-m4\"],\n    \"cxd5602gg\": [\"-mcpu=cortex-m4\"],\n    \"esp32\": [],\n    \"imxrt10xx\": [\"-mcpu=cortex-m7\"],\n    \"mps2_an521\": [\"-mcpu=cortex-m33\"],\n    \"mps3_an547\": [\"-mcpu=cortex-m55\"],\n    \"nrf52840\": [\"-mcpu=cortex-m4+nodsp\"],\n    \"nrf5340dk\": [\"-mcpu=cortex-m33\"],\n    \"rp2040\": [\"-mcpu=cortex-m0\"],\n    \"sam3x8e\": [\"-mcpu=cortex-m3\"],\n    \"stm32f746xx\": [\"-mcpu=cortex-m7\", \"-march=armv7e-m\"],\n    \"stm32h7xx\": [\"-mcpu=cortex-m7\"],\n    \"stm32l4r5zi\": [\"-mcpu=cortex-m4\"],\n    \"stm32u5xx\": [\"-mcpu=cortex-m33\"],\n    \"zynq_mp_r5\": [\"-mcpu=cortex-r5\"],\n}\n\n\ndef micro(model=\"unknown\", options=None):\n    \"\"\"Returns a microTVM target.\n\n    Parameters\n    ----------\n    model : str\n        Canonically identifies the target device. This is typically a device board level name.\n        The allowed values are MICRO_SUPPORTED_MODELS.keys().\n    options : str or list of str\n        Additional options\n    \"\"\"\n    if model not in MICRO_SUPPORTED_MODELS:\n        raise ValueError(f\"Model {model} not supported by tvm.target.micro.\")\n    opts = _merge_opts(\n        MICRO_SUPPORTED_MODELS[model] + [f\"-model={model}\"],\n        options,\n    )\n\n    # NOTE: in the future, the default micro target will be LLVM except when\n    # external dependencies are present.\n    return Target(\" \".join([\"c\"] + opts))\n\n\ndef arm_cpu(model=\"unknown\", options=None):\n    \"\"\"Returns a ARM CPU target.\n    This function will also download pre-tuned op parameters when there is none.\n\n    Parameters\n    ----------\n    model: str\n        SoC name or phone name of the arm board.\n    options : str or list of str\n        Additional options\n    \"\"\"\n    trans_table = {\n        \"pixel2\": [\"-model=snapdragon835\", \"-mtriple=arm64-linux-android\", \"-mattr=+neon\"],\n        \"mate10\": [\"-model=kirin970\", \"-mtriple=arm64-linux-android\", \"-mattr=+neon\"],\n        \"mate10pro\": [\"-model=kirin970\", \"-mtriple=arm64-linux-android\", \"-mattr=+neon\"],\n        \"p20\": [\"-model=kirin970\", \"-mtriple=arm64-linux-android\", \"-mattr=+neon\"],\n        \"p20pro\": [\"-model=kirin970\", \"-mtriple=arm64-linux-android\", \"-mattr=+neon\"],\n        \"rasp3b\": [\"-model=bcm2837\", \"-mtriple=armv7l-linux-gnueabihf\", \"-mattr=+neon\"],\n        \"rasp4b\": [\n            \"-model=bcm2711\",\n            \"-mtriple=armv8l-linux-gnueabihf\",\n            \"-mattr=+neon\",\n            \"-mcpu=cortex-a72\",\n        ],\n        \"rasp4b64\": [\n            \"-model=bcm2711\",\n            \"-mtriple=aarch64-linux-gnu\",\n            \"-mattr=+neon\",\n            \"-mcpu=cortex-a72\",\n        ],\n        \"rk3399\": [\"-model=rk3399\", \"-mtriple=aarch64-linux-gnu\", \"-mattr=+neon\"],\n        \"pynq\": [\"-model=pynq\", \"-mtriple=armv7a-linux-eabi\", \"-mattr=+neon\"],\n        \"ultra96\": [\"-model=ultra96\", \"-mtriple=aarch64-linux-gnu\", \"-mattr=+neon\"],\n        \"beagleai\": [\n            \"-model=beagleai\",\n            \"-mtriple=armv7a-linux-gnueabihf\",\n            \"-mattr=+neon,+vfp4,+thumb2\",\n            \"-mcpu=cortex-a15\",\n        ],\n        \"stm32mp1\": [\n            \"-model=stm32mp1\",\n            \"-mtriple=armv7a-linux-gnueabihf\",\n            \"-mattr=+neon,+vfp4,+thumb2\",\n            \"-mcpu=cortex-a7\",\n        ],\n        \"thunderx\": [\n            \"-model=thunderx\",\n            \"-mtriple=aarch64-linux-gnu\",\n            \"-mattr=+neon,+crc,+lse\",\n            \"-mcpu=thunderxt88\",\n        ],\n    }\n    pre_defined_opt = trans_table.get(model, [\"-model=%s\" % model])\n\n    opts = [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\"] + pre_defined_opt\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"llvm\"] + opts))\n\n\ndef rasp(options=None):\n    \"\"\"Return a Raspberry 3b target.\n\n    Parameters\n    ----------\n    options : str or list of str\n        Additional options\n    \"\"\"\n    warnings.warn(\n        \"tvm.target.rasp() is going to be deprecated. \" 'Please use tvm.target.arm_cpu(\"rasp3b\")'\n    )\n    return arm_cpu(\"rasp3b\", options)\n\n\ndef vta(model=\"unknown\", options=None):\n    opts = [\"-device=vta\", \"-keys=vta,cpu\", \"-model=%s\" % model]\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"ext_dev\"] + opts))\n\n\ndef bifrost(model=\"unknown\", options=None):\n    \"\"\"Return an ARM Mali GPU target (Bifrost architecture).\n\n    Parameters\n    ----------\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = [\"-device=bifrost\", \"-model=%s\" % model]\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"opencl\"] + opts))\n\n\ndef riscv_cpu(model=\"sifive-u54\", options=None):\n    \"\"\"Returns a RISC-V CPU target.\n    Default: sifive-u54 rv64gc\n\n    Parameters\n    ----------\n    model: str\n        CPU name.\n    options : str or list of str\n        Additional options\n    \"\"\"\n    trans_table = {\n        \"sifive-e31\": [\n            \"-model=sifive-e31\",\n            \"-mtriple=riscv32-unknown-linux-gnu\",\n            \"-mcpu=sifive-e31\",\n            \"-mabi=ilp32\",\n            # cc: riscv64-unknown-linux-gnu-g++ -march=rv32imac -mabi=ilp32 -mcpu=sifive-e31\n        ],\n        \"sifive-e76\": [\n            \"-model=sifive-e76\",\n            \"-mtriple=riscv32-unknown-linux-gnu\",\n            \"-mcpu=sifive-e76\",\n            \"-mabi=ilp32\",\n            # cc: riscv64-unknown-linux-gnu-g++ -march=rv32imafc -mabi=ilp32 -mcpu=sifive-e76\n        ],\n        \"sifive-u54\": [\n            \"-model=sifive-u54\",\n            \"-mtriple=riscv64-unknown-linux-gnu\",\n            \"-mcpu=sifive-u54\",\n            \"-mabi=lp64d\",\n            # cc: riscv64-unknown-linux-gnu-g++ -march=rv64gc -mabi=lp64d -mcpu=sifive-u54\n        ],\n        \"sifive-u74\": [\n            \"-model=sifive-u74\",\n            \"-mtriple=riscv64-unknown-linux-gnu\",\n            \"-mcpu=sifive-u74\",\n            \"-mabi=lp64d\",\n            # cc: riscv64-unknown-linux-gnu-g++ -march=rv64gc -mabi=lp64d -mcpu=sifive-u74\n        ],\n    }\n    pre_defined_opt = trans_table.get(model, [\"-model=%s\" % model])\n\n    opts = [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\"] + pre_defined_opt\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"llvm\"] + opts))\n\n\ndef hexagon(cpu_ver=\"v66\", **kwargs):\n    \"\"\"Returns a Hexagon target.\n\n    Parameters\n    ----------\n    cpu_ver : str (default: \"v66\")\n        CPU version used for code generation. Not all allowed cpu str\n        will be valid, LLVM will throw an error.\n\n    Recognized keyword parameters\n    -----------------------------\n    hvx : int (default: 128)\n        Size of HVX vector in bytes. Value of 0 disables HVX codegen.\n    llvm_options : str or list of str (default: None)\n        User defined compiler arguments.\n    use_qfloat : bool (default: True for cpu_ver >= v68, False otherwise)\n        Whether to use QFloat HVX instructions.\n    use_ieee_fp : bool (default: False)\n        Whether to use IEEE HVX instructions\n    num_cores : int (default: 4)\n        The number of HVX threads. This attribute is required by meta scheduler.\n\n    Note: Floating point support in HVX requires LLVM 14+.\n    \"\"\"\n\n    # Some of the target parameters correspond to target kind attributes\n    # listed in src/target/target_kind.cc. For those parameters, their\n    # names follow the attribute names with the exception of '_' being used\n    # in place of '-'.\n\n    # Example compiler arguments\n    # llvm -mtriple=hexagon -mcpu=hexagonv66 -mattr=+hvxv66,+hvx-length128b\n\n    def get_arch_version(cpu_ver):\n        m = re.match(r\"v([0-9]+).*\", cpu_ver)\n        assert m\n        return int(m.group(1))\n\n    # Check for valid codegen cpu\n    valid_hex = [\"v65\", \"v66\", \"v67\", \"v67t\", \"v68\", \"v69\"]\n    try:\n        cpu_ver = cpu_ver[cpu_ver.index(\"v\") :].lower()\n        assert cpu_ver in valid_hex\n    except:\n        msg = \"{} is not a valid Hexagon version\\nvalid versions include {}\"\n        raise ValueError(msg.format(cpu_ver, valid_hex)) from None\n\n    # Target configuration:\n    arch_version = get_arch_version(cpu_ver)\n    config = {\n        \"hvx\": 128,\n        \"llvm_options\": None,\n        \"use_qfloat\": arch_version >= 68,\n        \"use_ieee_fp\": False,\n    }\n    config.update(kwargs)\n\n    # Warn about obsolete parameter names.\n    if config.get(\"sim_args\") or config.get(\"sim_options\"):\n        msg = (\n            \"Setting simulator options in target is deprecated, set environment variable \"\n            \"HEXAGON_SIM_ARGS instead\"\n        )\n        warnings.warn(msg, stacklevel=2)\n    if config.get(\"llvm_args\"):\n        msg = \"The keyword parameter 'llvm_args' is deprecated, use 'llvm_options' instead\"\n        warnings.warn(msg, stacklevel=2)\n        config.update({\"llvm_options\": config[\"llvm_args\"]})\n\n    # LLVM target string\n    def create_llvm_target(cpu_ver, config):\n        \"\"\"Create LLVM target string.\"\"\"\n\n        target = \" -mtriple=hexagon\"\n        mcpu = \" -mcpu=hexagon\" + cpu_ver\n\n        # Process the options that affect target features and return the\n        # target feature string.\n        def create_target_features(config):\n            features = {\n                \"use_qfloat\": \"hvx-qfloat\",\n                \"use_ieee_fp\": \"hvx-ieee-fp\",\n            }\n            tfs = []\n            if config[\"hvx\"] > 0:\n                valid_hvx = [0, 64, 128]\n                if not config[\"hvx\"] in valid_hvx:\n                    raise ValueError(\"Invalid hvx value, should be one of \" + str(valid_hvx))\n                tfs += [\"+hvx\" + cpu_ver, \"+hvx-length\" + str(config[\"hvx\"]) + \"b\"]\n            else:\n                tfs += [\"-hvx\"]\n            # All the additional features happen to only apply to v68+.\n            # Don't bother applying them (even with '-') to lower versions.\n            if arch_version >= 68:\n                tfs += [\"-+\"[config[f]] + features[f] for f in features]\n\n            return \"-mattr=\" + \",\".join(tfs) if tfs else \"\"\n\n        return target + mcpu + \" \" + create_target_features(config)\n\n    # LLVM options string\n    def create_llvm_options(cpu_ver, config):  # pylint: disable=unused-argument\n        \"\"\"Create LLVM options string.\"\"\"\n\n        llvm_options = config[\"llvm_options\"]\n\n        # To enable auto-vectorization for v68 target added the below llvm-option by default\n        if arch_version == 68:\n            if not llvm_options:\n                llvm_options = \"\"\n            llvm_options += \" -force-hvx-float\"\n\n        # TVM's option parser doesn't allow '=' in values, but '=' can\n        # appear in LLVM flags. Replace it with '@', since it's unlikely\n        # that '@' will be used in another context.\n        if llvm_options is None or len(llvm_options.strip()) == 0:\n            return \"\"\n        args = [s.replace(\"=\", \"@\") for s in llvm_options.split()]\n        return \"--llvm-options=\" + \",\".join(args)\n\n    target_str = create_llvm_target(cpu_ver, config)\n    llvm_str = create_llvm_options(cpu_ver, config)\n\n    args_list = target_str.split() + llvm_str.split()\n\n    num_cores = config[\"num_cores\"] if \"num_cores\" in kwargs else 4\n    args_list.append(\"--num-cores=%d\" % num_cores)\n\n    return Target(\" \".join([\"hexagon\"] + args_list))\n\n\nSTM32_SUPPORTED_SERIES = {\n    # High-Performance\n    \"stm32H7xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m7\", \"-march=armv7e-m\"],\n    \"stm32F7xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m7\"],\n    \"stm32F4xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m4\"],\n    \"stm32F2xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m3\"],\n    # Mainstream\n    \"stm32G0xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m0+\"],\n    \"stm32F0xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m0\"],\n    \"stm32F1xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m3\"],\n    \"stm32G4xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m4\"],\n    \"stm32F3xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m4\"],\n    # Low-power\n    \"stm32U5xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m33\"],\n    \"stm32L5xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m33\"],\n    \"stm32L4xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m4\"],\n    \"stm32L1xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m3\"],\n    \"stm32L0xx\": [\"-keys=arm_cpu,cpu\", \"-device=arm_cpu\", \"-mcpu=cortex-m0+\"],\n}\n\n\ndef stm32(series=\"unknown\", options=None):\n    \"\"\"Returns a STM32 target.\n\n    Parameters\n    ----------\n    series: str\n        Series name of a STM32 board series, eg. stm32H7xx or stm32F4xx\n    options : str or list of str\n        Additional options\n    \"\"\"\n\n    if series not in STM32_SUPPORTED_SERIES:\n        raise ValueError(f\"Series {series} is not supported by tvm.target.stm32.\")\n    opts = _merge_opts(STM32_SUPPORTED_SERIES[series], options)\n    return Target(\" \".join([\"c\"] + opts))\n\n\ndef adreno(model=\"unknown\", options=None):\n    \"\"\"Returns a Qualcomm GPU target.\n    Parameters\n    ----------\n    model: str\n        The model of this device\n    options : str or list of str\n        Additional options\n    \"\"\"\n    opts = [\"-device=adreno\", \"-model=%s\" % model]\n    opts = _merge_opts(opts, options)\n    return Target(\" \".join([\"opencl\"] + opts))\n\n\ndef create(target):\n    \"\"\"Deprecated. Use the constructor of :py:mod:`tvm.target.Target` directly.\"\"\"\n    warnings.warn(\"tvm.target.create() is being deprecated. Please use tvm.target.Target() instead\")\n    return Target(target)\n\n\n@_register_func(\"target._load_config_dict\")\ndef _load_config_dict(config_dict_str):\n    try:\n        config = json.loads(config_dict_str)\n    except json.decoder.JSONDecodeError:\n        return None\n    if not isinstance(config, dict):\n        return None\n    for key in config.keys():\n        if not isinstance(key, str):\n            return None\n    return config\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/target/virtual_device.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Python bindings for creating VirtualDevices.\"\"\"\n\nimport tvm\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object\nclass VirtualDevice(Object):\n    \"\"\"A compile time representation for where data is to be stored at runtime,\n    and how to compile code to compute it.\"\"\"\n\n    def __init__(self, device=None, target=None, memory_scope=\"\") -> None:\n        if device is None:\n            # The 'unconstrained' device has device type -1 and device id -1.\n            device = tvm.device(-1, -1)\n        self.__init_handle_by_constructor__(\n            _ffi_api.VirtualDevice_ForDeviceTargetAndMemoryScope, device, target, memory_scope\n        )\n\n    @property\n    def device_type(self) -> int:\n        return self.device_type_int\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin, wildcard-import\n\"\"\"Namespace for Tensor Expression Language\n\"\"\"\n# expose all operators in tvm tir.op\nfrom tvm.tir import any, all, min_value, max_value, trace\nfrom tvm.tir import exp, erf, tanh, sigmoid, log, tan, cos, sin, sqrt, rsqrt, floor, ceil\nfrom tvm.tir import sinh, cosh, log2, log10\nfrom tvm.tir import asin, asinh, acos, acosh, atan, atanh\nfrom tvm.tir import trunc, abs, round, nearbyint, power, popcount, fmod, if_then_else\nfrom tvm.tir import isnan, isfinite, isinf\nfrom tvm.tir import div, indexdiv, indexmod, truncdiv, truncmod, floordiv, floormod\nfrom tvm.tir import comm_reducer, min, max, sum\nfrom tvm.tir import add, subtract, multiply\n\nfrom .schedule import (\n    Schedule,\n    Stage,\n    create_schedule,\n    SpecializedCondition,\n    AXIS_SEPARATOR,\n)\nfrom .tensor import TensorSlice, Tensor\nfrom .tensor_intrin import decl_tensor_intrin\nfrom .tag import tag_scope\nfrom .operation import placeholder, compute, scan, extern, var, size_var, const\nfrom .operation import thread_axis, reduce_axis\nfrom .operation import create_prim_func\nfrom .operation import extern_primfunc\n\nfrom .tensor import PlaceholderOp, ComputeOp, TensorComputeOp, ScanOp, ExternOp, HybridOp\nfrom .autodiff import gradient\nfrom . import hybrid\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.te\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"te\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/autodiff.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Automatic differentiation of tensor expressions.\"\"\"\nfrom . import _ffi_api\n\n\ndef gradient(output, inputs, head=None):\n    \"\"\"Perform reverse-mode automatic differentiation.\n\n    Parameters\n    ----------\n    output : Tensor\n        The tensor to differentiate.\n\n    inputs : List[Tensor]\n        The list of input tensors to be differentiated wrt.\n\n    head : Tensor\n        The adjoint of the output, in other words, some tensor, by which the Jacobians\n        will be multiplied. Its shape must be of the form `prefix + output.shape`.\n        If `None` is passed, the identity tensor of shape `output.shape + output.shape`\n        will be used.\n\n    Returns\n    -------\n    tensors: List[Tensor]\n        The result gradient, in the same order as the inputs\n\n    Example\n    -------\n    .. code-block:: python\n\n        x = tvm.placeholder((32, 3, 28, 28), name='x')\n        w1 = tvm.placeholder((10, 3, 3, 3), name='w1')\n        w2 = tvm.placeholder((10, 10, 3, 3), name='w2')\n        z1 = topi.nn.conv2d(x, w1, 1, 1, 1)\n        z2 = topi.nn.conv2d(z1, w2, 1, 1, 1)\n        y = topi.sum(z2)\n\n        # produce gradients\n        [dw1, dw2] = tvm.gradient(y, [w1, w2])\n\n        # produce Jacobians\n        [jw1, jw2] = tvm.gradient(z2, [w1, w2])\n\n        # produce gradients, the head adjoint for z2 is provided manually\n        [dw1, dw2] = tvm.gradient(z2, [w1, w2], topi.full_like(z2, 1.0))\n\n    \"\"\"\n    if not isinstance(inputs, list):\n        inputs = [inputs]\n    return _ffi_api.Gradient(output, inputs, head)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hybrid Programming APIs of TVM Python Package.\n\nThis package maps a subset of python to HalideIR so that:\n1. Users can write some preliminary versions of the computation patterns\nhave not been supported yet and verify it across the real execution and\npython semantic emulation.\n2. So far, it is a text format dedicated to HalideIR Phase 0. Refer tvm.lower\nfor more details. A larger ambition of this module is to support all levels of\nHalideIR.\n\"\"\"\n\n# TODO(@were): Make this module more complete.\n# 1. Support HalideIR dumping to Hybrid Script\n# 2. Support multi-level HalideIR\nimport inspect\nimport tvm._ffi\nimport tvm.te.schedule\nfrom tvm._ffi.base import decorate\n\nfrom .module import HybridModule\nfrom .parser import source_to_op\nfrom .utils import _pruned_source\n\n\ndef script(pyfunc):\n    \"\"\"Decorate a python function function as hybrid script.\n\n    The hybrid function support emulation mode and parsing to\n    the internal language IR.\n\n    Returns\n    -------\n    hybrid_func : function\n        A decorated hybrid script function.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel, missing-docstring\n    def wrapped_func(func, *args, **kwargs):\n        from .utils import _is_tvm_arg_types\n\n        if _is_tvm_arg_types(args):\n            src = _pruned_source(func)\n            closure_vars = inspect.getclosurevars(func).nonlocals\n            closure_vars.update(inspect.getclosurevars(func).globals)\n            return source_to_op(src, args, func.__globals__, closure_vars)\n\n        from .runtime import _enter_hybrid_runtime, _restore_runtime\n\n        intersect = _enter_hybrid_runtime(func)\n        value = func(*args, **kwargs)\n        _restore_runtime(func, intersect)\n        return value\n\n    return decorate(pyfunc, wrapped_func)\n\n\ndef build(sch, inputs, outputs, name=\"hybrid_func\"):\n    \"\"\"Dump the current schedule to hybrid module\n\n    Parameters\n    ----------\n    sch: tvm.te.Schedule\n        The schedule to be dumped\n\n    inputs: An array of Tensors or Vars\n        The inputs of the function body\n\n    outputs: An array of Tensors\n        The outputs of the function body\n\n    Returns\n    -------\n    module: HybridModule\n        The built results is wrapped in a HybridModule.\n        The usage of HybridModule is roughly the same as normal TVM-built modules.\n    \"\"\"\n    sch = sch.normalize()\n    bounds = tvm.te.schedule.InferBound(sch)\n    stmt = tvm.te.schedule.ScheduleOps(sch, bounds)\n\n    src = _Dump(stmt, inputs, outputs, name)\n\n    return HybridModule(src, name)\n\n\ntvm._ffi._init_api(\"tvm.hybrid\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/calls.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Intrinsics of TVM-Python Hybrid Script for Python compilation time\nsemantic support.\"\"\"\n\nfrom tvm.runtime import const, convert\nimport tvm.te\nfrom tvm.ir.container import Array\nfrom tvm.target import Target\nfrom tvm.tir import expr as _expr\nfrom tvm.tir import call_intrin\nfrom tvm.tir.stmt import ForKind\n\nfrom .utils import _internal_assert\n\n# pylint: disable=redefined-builtin,invalid-name\n\nLOOP_INTRIN = {\n    \"range\": ForKind.SERIAL,\n    \"unroll\": ForKind.UNROLLED,\n    \"parallel\": ForKind.PARALLEL,\n    \"vectorize\": ForKind.VECTORIZED,\n    \"const_range\": (ForKind.UNROLLED,),\n}\n\n\ndef _range(annotation, args):\n    \"\"\"Handling TVM loop types\"\"\"\n    n = args.__len__()\n    if n == 1:\n        low, ext = const(0, dtype=\"int32\"), args[0]\n    else:\n        _internal_assert(n == 2, \"A loop intrinsic should only have 1 or 2 arguments!\")\n        low, ext = args[0], args[1]\n    if not tvm.tir.analysis.expr_deep_equal(low, const(0, dtype=\"int32\")):\n        ext = ext - low\n    kind = LOOP_INTRIN[annotation]\n    iter_var = None\n    return iter_var, low, ext, kind\n\n\nrange = unroll = vectorize = parallel = const_range = _range  # pylint: disable=invalid-name\n\n\ndef bind(func_id, args):\n    \"\"\"Handling TVM thread binding\"\"\"\n    _internal_assert(func_id == \"bind\", \"This function cannot be directly invoked!\")\n    _internal_assert(args.__len__() == 2, \"A loop bind should only have 2 arguments!\")\n    _internal_assert(isinstance(args[0], str), \"A loop bind's first argument should be a string!\")\n    low, ext = const(0, \"int32\"), args[1]\n    iter_var = tvm.te.thread_axis((low, ext), args[0])\n    kind = None\n    return iter_var, low, ext, kind\n\n\ndef _math_intrin(func_id, args):\n    # pylint: disable=import-outside-toplevel\n    from tvm.tir import op\n\n    return getattr(op, func_id)(*args)\n\n\nsqrt = (\n    log\n) = exp = tanh = sigmoid = power = popcount = round = _math_intrin  # pylint: disable=invalid-name\n\n\ndef _min_max(func_id, args):\n    _internal_assert(args.__len__() == 2, \"Max/Min function should have 2 elements\")\n    return getattr(_expr, func_id.title())(args[0], args[1])\n\n\nmin = max = _min_max  # pylint: disable=invalid-name\n\n\ndef _allocate_tensor(func_id, args):\n    \"\"\"Handling TVM tensor allocation.\n    You may refer hybrid.intrin.allocate for more details.\"\"\"\n    n = args.__len__()\n    _internal_assert(\n        isinstance(convert(args[0]), Array), \"allocate's first argument should be a tuple of shape!\"\n    )\n    shape = args[0]\n    for i in shape:\n        _internal_assert(isinstance(i, _expr.PrimExpr), \"The shape should be an expression\")\n    if n > 1:\n        _internal_assert(isinstance(args[1], str), \"The data type should be an str\")\n        _internal_assert(\n            args[1].startswith(\"int\") or args[1].startswith(\"float\"),\n            \"The data type should be either int or float!\",\n        )\n        dtype = args[1]\n    else:\n        dtype = \"float32\"\n    if n > 2:\n        _internal_assert(isinstance(args[2], str), \"The data scope should be an string\")\n        _internal_assert(func_id != \"output_tensor\", \"Output tensor cannot specify scope\")\n        scope = args[2]\n    else:\n        scope = \"global\" if func_id != \"output_tensor\" else \"output\"\n    return (shape, dtype, scope)\n\n\noutput_tensor = allocate = _allocate_tensor  # pylint: disable=invalid-name\n\n\ndef len(func_id, args):\n    \"\"\"Iterpret the len function\"\"\"\n    _internal_assert(args.__len__() == 1, \"Only 1 argument is expected!\")\n    _internal_assert(func_id == \"len\", \"This function cannot be directly invoked!\")\n    try:\n        return convert(args[0].__len__())\n    except:  # pylint: disable=bare-except\n        _internal_assert(args[0].shape.__len__() == 1, \"Only one-dimension array can get len\")\n        return convert(args[0].shape[0])\n\n\ndef _cast(func_id, args):\n    _internal_assert(\n        args.__len__() == 1 and isinstance(args[0], _expr.PrimExpr),\n        \"Only one expression can be cast\",\n    )\n    return _expr.Cast(func_id, args[0])\n\n\nfloat16 = float32 = float64 = _cast  # pylint: disable=invalid-name\nint8 = int16 = int32 = int64 = _cast  # pylint: disable=invalid-name\nuint8 = uint16 = uint32 = uint64 = _cast  # pylint: disable=invalid-name\n\n\ndef ceil_div(func_id, args):\n    _internal_assert(func_id == \"ceil_div\", \"This function cannot be directly invoked!\")\n    _internal_assert(args.__len__() == 2, \"2 arguments expected for division!\")\n    _internal_assert(isinstance(args[0], _expr.PrimExpr), \"Only expressions can div\")\n    _internal_assert(isinstance(args[1], _expr.PrimExpr), \"Only expressions can div\")\n    a, b = args[0], args[1]\n    return (a + b - 1) // b\n\n\ndef likely(func_id, args):\n    _internal_assert(args.__len__() == 1, \"Only one expression can be likely\")\n    _internal_assert(func_id == \"likely\", \"This function cannot be directly invoked!\")\n    return call_intrin(args[0].dtype, \"tir.likely\", *args)\n\n\ndef max_num_threads(func_id, args):\n    \"\"\"Set the maximum number of threads.\"\"\"\n    _internal_assert(func_id == \"max_num_threads\", \"This function cannot be directly invoked!\")\n    _internal_assert(args.__len__() <= 1, \"At most one argument accepted!\")\n    if args.__len__() == 0:\n        res = Target.current().max_num_threads\n    else:\n        _internal_assert(isinstance(args[0], _expr.IntImm), \"In tvm bool should be uint\")\n        res = Target.current(args[0].value).max_num_threads\n    return convert(res)\n\n\ndef inf(func_id, args):\n    \"\"\"Infinity\"\"\"\n    _internal_assert(func_id == \"inf\", \"This function cannot be directly invoked!\")\n    _internal_assert(args.__len__() == 1, \"One argument accepted!\")\n    return tvm.tir.max_value(args[0])\n\n\ndef ninf(func_id, args):\n    \"\"\"Negative infinity\"\"\"\n    _internal_assert(func_id == \"ninf\", \"This function cannot be directly invoked!\")\n    _internal_assert(args.__len__() == 1, \"One argument accepted!\")\n    return tvm.tir.min_value(args[0])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Methods and data structures to support dumping HalideIR to Hybrid Script.\nThis allows users to do quick hack to generated HalideIR and cast it back to\nTVM modules.\n\nTo enable this feature, you need to build with -DUSE_HYBRID_DUMP=ON.\n\"\"\"\n\nimport ast\n\nfrom tvm.contrib import utils\nfrom .utils import _internal_assert\nfrom .utils import _is_tvm_arg_types\nfrom .parser import source_to_op\n\n\nclass HybridModule(object):\n    \"\"\"The usage of Hybrid Module is very similar to conventional TVM module,\n    but conventional TVM module requires a function body which is already fully\n    lowered. This contradicts to the fact that Hybrid Module is originally a text\n    format for Phase 0 HalideIR. Thus, a totally separated module is defined.\"\"\"\n\n    def __init__(self, src=None, name=None):\n        \"\"\"The constructor of this a hybrid module\n\n        Parameters\n        ----------\n        src : str\n            The source code of this module\n\n        name : str\n            The name of this module\n        \"\"\"\n        self.src_ = self.name = self.func_ = self.root_ = None\n        if src is not None:\n            temp = utils.tempdir()\n            dst = temp.relpath(\"script.py\")\n            with open(dst, \"w\") as f:\n                f.write(\"import tvm\\n@tvm.te.hybrid.script\\n%s\" % src)\n\n            if name is not None:\n                self.name = name\n            self.load(dst)\n\n    def __call__(self, *args):\n        if _is_tvm_arg_types(args):\n            return source_to_op(self.root_, args, globals(), {})\n        return self.func_(*args)\n\n    def get_source(self):\n        return self.src_\n\n    def save(self, path):\n        if not path.endswith(\".py\"):\n            path = path + \".py\"\n        with open(path, \"w\") as f:\n            f.write(self.src_)\n\n    def load(self, path):\n        \"\"\"Load the module from a python file\n\n        Parameters\n        ----------\n        path : str\n            Path to the given python file\n        \"\"\"\n        with open(path, \"r\") as f:\n            self.src_ = f.read()\n\n        src = self.src_\n\n        class FindFunc(ast.NodeVisitor):\n            \"\"\"Find the function in module to be loaded module.\"\"\"\n\n            # pylint: disable=invalid-name\n            def __init__(self):\n                self.name = None\n                self.root = None\n\n            def visit_FunctionDef(self, node):\n                _internal_assert(self.name is None, \"For now, only one function supported!\")\n                self.name = node.name\n                _internal_assert(self.root is None, \"For now, only one function supported!\")\n                self.root = node\n\n        root = ast.parse(src)\n        finder = FindFunc()\n        finder.visit(root)\n        _internal_assert(finder.name is not None and finder.root is not None, \"No function found!\")\n        if self.name is None:\n            self.name = finder.name\n        self.root_ = finder.root\n\n        _, local_ = {}, {}\n        exec(self.src_, _, local_)  # pylint: disable=exec-used\n        local_.pop(\"tvm\")\n        assert len(local_) == 1\n        self.func_ = list(local_.values())[0]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hybrid Script Parser\"\"\"\n\nimport ast\nimport operator\nimport logging\nimport sys\nimport types\nimport numbers\n\nfrom enum import Enum\nfrom tvm.ir import Array, Range\nimport tvm.runtime\nimport tvm.tir\nimport tvm.te\nimport tvm.te._ffi_api\nimport tvm.arith\n\nfrom tvm.tir import expr as _expr\nfrom tvm.tir import stmt as _stmt\nfrom tvm.te.tensor import Tensor, Operation\nfrom tvm.tir import all as _all\nfrom tvm.tir import any as _any\n\nfrom .utils import _internal_assert\nfrom . import calls\nfrom . import utils\nfrom .preprocessor import determine_variable_usage\n\n\ndef concat_list_to_block(lst):\n    \"\"\"Concatenate a list of Python IR nodes to HalideIR Block\"\"\"\n    if not lst:\n        return utils.make_nop()\n    n = len(lst)\n    if n == 1:\n        return lst[0]\n    return _stmt.SeqStmt(lst)\n\n\ndef visit_list_to_block(visit, lst):\n    \"\"\"Visit and concatenate a list of Python IR nodes to HalideIR Block\"\"\"\n    lst = [visit(stmt) for stmt in lst if not utils.is_docstring(stmt)]\n    lst = [stmt for stmt in lst if not tvm.ir.structural_equal(stmt, utils.make_nop())]\n    if not lst:\n        return utils.make_nop()\n    return concat_list_to_block(lst)\n\n\nclass Symbol(Enum):\n    \"\"\"Enumerates types in the symbol table\"\"\"\n\n    Callable = 0\n    Input = 1\n    OutputBuffer = 2\n    GlobalBuffer = 3\n    LocalBuffer = 4\n    SharedBuffer = 5\n    ConstVar = 6\n    BufferVar = 7\n    LoopVar = 8\n    ConstLoopVar = 9\n    ThreadBind = 10\n\n\ndef _floordiv(x, y):\n    if isinstance(x, _expr.ExprOp) or isinstance(y, _expr.ExprOp):\n        return tvm.tir.floordiv(x, y)\n    return operator.floordiv(x, y)\n\n\ndef _floormod(x, y):\n    if isinstance(x, _expr.ExprOp) or isinstance(y, _expr.ExprOp):\n        return tvm.tir.floormod(x, y)\n    return operator.mod(x, y)\n\n\nclass HybridParser(ast.NodeVisitor):\n    \"\"\"Python AST visitor pass which finally lowers it to HalideIR\"\"\"\n\n    _binop_maker = {\n        ast.Add: operator.add,\n        ast.Sub: operator.sub,\n        ast.Mult: operator.mul,\n        ast.Div: operator.div if sys.version_info[0] == 2 else operator.truediv,\n        ast.FloorDiv: _floordiv,\n        ast.Mod: _floormod,\n        ast.BitOr: operator.or_,\n        ast.BitAnd: operator.and_,\n        ast.BitXor: operator.xor,\n        ast.Gt: operator.gt,\n        ast.GtE: operator.ge,\n        ast.Lt: operator.lt,\n        ast.LtE: operator.le,\n        ast.Eq: operator.eq,\n        ast.NotEq: operator.ne,\n        ast.And: _all,\n        ast.Or: _any,\n    }\n\n    _unaryop_maker = {ast.USub: operator.neg, ast.Invert: operator.invert, ast.Not: operator.not_}\n\n    def __init__(self, args, usage, symbols, closure_vars, func_name=None):\n        \"\"\"\n        Parameters\n        ----------\n        args: A list of tvm.te.placeholder or te.var\n            Provided by the user, the argument list of the function to be lowered.\n\n        usage: A dict of variables used in last in this function\n            Provided by last lower pass, which collects this information\n\n        symbols : list of str\n            The symbol list of the global context of the function.\n\n        closure_vars: dict\n            A dict of external name reference captured by this function.\n\n        Returns\n        -------\n        func_name: str\n            The name of the function to be lowered; if not provided,\n            the compiler will use the name in the AST\n        \"\"\"\n        self.args = list(args)\n        self.usage = usage.copy()\n\n        self.symbols = {}  # Symbol table\n        for k, v in symbols.items():\n            if isinstance(v, types.FunctionType):\n                self.add_symbol(k, Symbol.Callable, v)\n\n        self.closure_vars = closure_vars\n\n        self.binds = {}  # Thread binds\n        self.device = 0  # Is it generating device\n\n        self.func_name = func_name  # The name of the function to be lowered\n        self.outputs = []  # Output tensors' name\n        self.side_effect = set()  # Tensors with side effects\n        self.parsed_body = None  # The parsed HalideIR body\n        self.analyzer = tvm.arith.Analyzer()\n        self.returned = False  # If this function has a valid return\n\n    def add_symbol(self, key, ty, val):  # pylint: disable=invalid-name\n        \"\"\"Add value to the symbol table context\"\"\"\n        if key in self.symbols.keys():\n            old = str(self.symbols[key])\n            new = str((ty, val))\n            _internal_assert(\n                False, \"Name conflict in symbol table! [%s] %s -> %s\" % (key, old, new)\n            )\n\n        self.symbols[key] = ty, val\n\n        if ty == Symbol.ThreadBind:\n            if val.var.name not in self.binds.keys():\n                self.binds[val.var.name] = val\n                return\n            val_ = self.binds[val.var.name]\n            _internal_assert(\n                tvm.tir.analysis.expr_deep_equal(val_.dom.extent, val.dom.extent),\n                \"Thread extents should be uniform!\",\n            )\n            self.symbols[key] = ty, val_\n\n    def wrap_up_realize(self, node, body):\n        \"\"\"Wrap up all the variables which will no longer be used\"\"\"\n        to_pop = []\n        for key, val in self.usage.items():\n            _, level, _ = val\n            if key not in self.symbols:\n                # don't realize the symbols that are never visited\n                continue\n            if level != node:\n                continue\n            _internal_assert(key in self.symbols.keys(), \"Unknown symbol %s!\" % key)\n\n            ty, entry = self.symbols[key]  # pylint: disable=invalid-name\n            if ty in [Symbol.Input, Symbol.OutputBuffer]:\n                continue\n            if \"Buffer\" in ty.name:\n                _buf = entry\n                _scope = \"global\" if ty is Symbol.BufferVar else ty.name[:-6].lower()\n                to_pop.append(key)\n            else:\n                continue\n\n            if _scope == \"global\":\n                body = self.wrap_up_binds(body)\n\n            _domain = [Range.from_min_extent(0, i) for i in _buf.shape]\n            _dtype = _buf.dtype\n            _true = tvm.runtime.convert(True)\n            body = tvm.tir.ProducerRealize(_buf, _domain, _true, body, tvm.runtime.convert(_scope))\n\n        for elem in to_pop:\n            self.symbols.pop(elem)\n\n        return body\n\n    def wrap_up_binds(self, body):\n        for _, iter_var in self.binds.items():\n            ext = iter_var.dom.extent\n            body = tvm.tir.AttrStmt(iter_var, \"thread_extent\", ext, body)\n        self.binds = {}\n        return body\n\n    # pylint: disable=invalid-name, missing-docstring\n    def visit_Module(self, node):\n        _internal_assert(\n            len(node.body) == 1, \"Only one-function source code will be fed to this parser!\"\n        )\n        return self.visit(node.body[0])\n\n    def visit_FunctionDef(self, node):\n        _internal_assert(\n            len(node.args.args) == len(self.args),\n            \"The number of arguments passed to the \\\n                         function should be the same as it is defined!\",\n        )\n        if self.func_name is None:\n            self.func_name = node.name\n        for idx, arg in enumerate(node.args.args):\n            _attr = \"id\" if sys.version_info[0] < 3 else \"arg\"  # To make py2 and 3 compatible\n            self.add_symbol(getattr(arg, _attr), Symbol.Input, self.args[idx])\n        res = visit_list_to_block(self.visit, node.body)\n        res = self.wrap_up_realize(node, res)\n        return self.wrap_up_binds(res)\n\n    def visit_Expr(self, node):\n        return self.visit(node.value)\n\n    def visit_Name(self, node):\n        name = node.id\n        if sys.version_info[0] == 2 and name in [\"True\", \"False\"]:\n            return tvm.runtime.convert(ast.literal_eval(name))\n\n        if name in self.closure_vars:\n            return tvm.runtime.convert(self.closure_vars[name])\n\n        ty, entry = self.symbols[name]\n        _internal_assert(name in self.symbols, \"Unknown symbol %s!\" % name)\n        if ty in [Symbol.LoopVar, Symbol.Input, Symbol.ConstLoopVar]:\n            return entry\n        if ty is Symbol.ThreadBind:\n            return entry.var\n        if ty is Symbol.ConstVar:\n            return entry if isinstance(node.ctx, ast.Load) else None\n        if ty is Symbol.BufferVar:\n            if isinstance(node.ctx, ast.Load):\n                return tvm.tir.ProducerLoad(entry, [tvm.runtime.const(0, \"int32\")])\n            return entry, [tvm.runtime.const(0, \"int32\")]\n        # Do I need any assertion here?\n        return entry\n\n    def visit_Num(self, node):\n        if isinstance(node.n, numbers.Integral):\n            dtype = \"int32\"\n        elif isinstance(node.n, float):\n            dtype = \"float32\"\n        else:\n            _internal_assert(\n                isinstance(node.n, bool), \"The data type should be one of (int, float, bool)\"\n            )\n            dtype = \"bool\"\n        return tvm.runtime.const(node.n, dtype)\n\n    def visit_NameConstant(self, node):\n        return tvm.runtime.convert(node.value)\n\n    def visit_AugAssign(self, node):\n        buf = self.visit(node.target)\n        rhs = self.visit(node.value)\n        if isinstance(buf, tuple):\n            _internal_assert(len(buf) == 2, \"LHS is supposed to be (buf, args)!\")\n            buf, args = buf\n        else:\n            args = [tvm.runtime.const(0, \"int32\")]\n        _internal_assert(isinstance(buf, Tensor), \"LHS is supposed to be Tensor!\")\n\n        read = tvm.tir.ProducerLoad(buf, args)\n        value = HybridParser._binop_maker[type(node.op)](read, rhs)\n\n        return tvm.tir.ProducerStore(buf, value, args)\n\n    def visit_Assign(self, node):\n        rhs = self.visit(node.value)\n        if isinstance(rhs, Operation):\n            rmap = {}\n            _internal_assert(\n                len(node.targets) == rhs.num_outputs, \"Unable to detuple the outs to targets\"\n            )\n            for i in range(rhs.num_outputs):\n                _internal_assert(\n                    isinstance(node.targets[i], ast.Name),\n                    \"You should bind a pure name to the tensors\",\n                )\n                self.add_symbol(node.targets[i].id, Symbol.GlobalBuffer, rhs.output(i))\n                rmap[rhs.outputs[i].op] = rhs.output(i)\n            return utils.replace_io(rhs.body, rmap)\n\n        _internal_assert(len(node.targets) == 1, \"So far only one-valued assignment is supported!\")\n        lhs = node.targets[0]\n        if isinstance(rhs, _expr.PrimExpr):\n            rhs = self.analyzer.simplify(rhs)\n        if isinstance(lhs, ast.Name):\n            # TODO: support defined intermediate buffer later\n            lhs_ = lhs\n            lhs = lhs.id\n            if lhs in self.symbols.keys():\n                ty, _ = self.symbols[lhs]\n                _internal_assert(ty != Symbol.LoopVar, \"Loop variable cannot be overwritten!\")\n            decl, _, rw = self.usage[lhs]\n            if decl == lhs_:\n                _internal_assert(\n                    lhs not in self.symbols.keys(),\n                    \"This value should not be defined before this point!\",\n                )\n                if isinstance(rhs, tuple):\n                    shape, dtype, scope = rhs\n                    ph = tvm.te.placeholder(shape, dtype=dtype, name=lhs)\n                    self.add_symbol(lhs, getattr(Symbol, scope.title() + \"Buffer\"), ph)\n                    if scope == \"output\":\n                        self.outputs.append(lhs)\n                    return utils.make_nop()\n                if isinstance(rhs, utils.halide_imm_types) and ast.Store not in rw:\n                    self.add_symbol(lhs, Symbol.ConstVar, rhs)\n                else:\n                    _internal_assert(\n                        self.device == 0,\n                        \"Single variable not supported in devices' side!\\n\"\n                        + \"If you are using GPU, please allocate a 'local' spad \"\n                        + \"outside the bind body\",\n                    )\n                    ph = tvm.te.placeholder((1,), dtype=rhs.dtype, name=lhs)\n                    self.add_symbol(lhs, Symbol.BufferVar, ph)\n            lhs = self.visit(lhs_)\n            if lhs is not None:\n                buf, args = lhs\n                return tvm.tir.ProducerStore(buf, rhs, args)\n            return utils.make_nop()\n\n        lhs, args = self.visit(lhs)\n        _internal_assert(\n            isinstance(lhs, Tensor), \"An array access's LHS is expected to be a expr.Call!\"\n        )\n        res = tvm.tir.ProducerStore(lhs, rhs, args)\n        return res\n\n    def visit_Index(self, node):\n        if isinstance(node.value, ast.Tuple):\n            return self.visit(node.value)\n        return [self.visit(node.value)]\n\n    def visit_Attribute(self, node):\n        buf = self.visit(node.value)\n        return getattr(buf, node.attr)\n\n    def visit_Subscript(self, node):\n        args = self.visit(node.slice)\n        if sys.version_info >= (3, 9):\n            if not isinstance(node.slice, ast.Tuple):\n                args = [args]\n\n        arr = self.visit(node.value)\n        if isinstance(arr, Array):\n            for i in args:\n                if isinstance(i, numbers.Integral):\n                    arr = arr[i]\n                else:\n                    _internal_assert(\n                        isinstance(i, (_expr.IntImm,)), \"All indices are supposed to be constants\"\n                    )\n                    arr = arr[i.value]\n            return arr\n        if isinstance(node.ctx, ast.Load):\n            return tvm.tir.ProducerLoad(arr, args)\n        return arr, args\n\n    def visit_With(self, node):\n        if sys.version_info[0] < 3:\n            context = node.context_expr\n            option = node.optional_vars\n        else:\n            _internal_assert(len(node.items) == 1, \"Only one with element is supported so far!\")\n            context = node.items[0].context_expr\n            option = node.items[0].optional_vars\n        _internal_assert(isinstance(context, ast.Call), \"The object must be a Python func call!\")\n        _internal_assert(isinstance(option, ast.Name), \"The object after 'as' must be an id!\")\n        self.annotation[option.id] = context.func.id\n        return visit_list_to_block(self.visit, node.body)\n\n    def visit_If(self, node):\n        cond = self.analyzer.simplify(self.visit(node.test))\n\n        # Return no IfThenElse if proven\n        if isinstance(cond, _expr.IntImm):\n            if cond.value:\n                return visit_list_to_block(self.visit, node.body)\n            if node.orelse:\n                return visit_list_to_block(self.visit, node.orelse)\n            return utils.make_nop()\n\n        if_body = visit_list_to_block(self.visit, node.body)\n\n        if node.orelse:\n            else_body = visit_list_to_block(self.visit, node.orelse)\n        else:\n            else_body = None\n        return tvm.tir.IfThenElse(cond, if_body, else_body)\n\n    def visit_IfExp(self, node):\n        cond = self.visit(node.test)\n        if_body = self.visit(node.body)\n        else_body = self.visit(node.orelse)\n        return tvm.tir.Select(cond, if_body, else_body)\n\n    def visit_Compare(self, node):\n        _internal_assert(len(node.ops) == len(node.comparators), \"#compare ops != #comparators\")\n        ops = [self.visit(node.left)]\n        ops += [self.visit(i) for i in node.comparators]\n        res = []\n        for i in range(len(node.ops)):\n            lhs = ops[i]\n            rhs = ops[i + 1]\n            res.append(HybridParser._binop_maker[type(node.ops[i])](lhs, rhs))\n        return _all(*res)\n\n    def visit_BoolOp(self, node):\n        n = len(node.values)\n        if n == 1:\n            _internal_assert(isinstance(node.op, ast.Not), \"Unary is supposed to be not!\")\n            return operator.not_(self.visit(node.values[0]))\n        _internal_assert(isinstance(node.op, (ast.And, ast.Or)), \"Binary is supposed to be and/or!\")\n        values = [self.visit(i) for i in node.values]\n        return HybridParser._binop_maker[type(node.op)](*values)\n\n    def visit_UnaryOp(self, node):\n        operand = self.visit(node.operand)\n        return HybridParser._unaryop_maker[type(node.op)](operand)\n\n    def visit_BinOp(self, node):\n        lhs = self.visit(node.left)\n        rhs = self.visit(node.right)\n        return HybridParser._binop_maker[type(node.op)](lhs, rhs)\n\n    def visit_Call(self, node):\n        # Yet, no function pointer supported\n        _internal_assert(\n            isinstance(node.func, ast.Name), \"Only id-function function call is supported so far!\"\n        )\n\n        func_id = node.func.id\n        args = [self.visit(i) for i in node.args]\n        # Intrinsics'\n        if hasattr(calls, func_id):\n            return getattr(calls, func_id)(func_id, args)\n        # Contexts'\n        _internal_assert(\n            func_id in self.symbols.keys(),\n            \"The function called (%s) is not in the context either!\" % func_id,\n        )\n        ty, entry = self.symbols[func_id]\n        _internal_assert(ty is Symbol.Callable, \"Are you sure what you call is a function?!\")\n        outs = entry(*args)\n        op = outs.op if isinstance(outs, Tensor) else outs[0].op\n        return op\n\n    def visit_For(self, node):\n        iter_var, low, ext, kind = self.visit(node.iter)\n        _internal_assert(\n            isinstance(node.target, ast.Name), \"The loop iterator should be a variable!\"\n        )\n\n        _name = node.target.id\n\n        if isinstance(kind, tuple):\n            low = self.analyzer.simplify(low)\n            ext = self.analyzer.simplify(ext)\n            _internal_assert(\n                isinstance(low, _expr.ConstExpr) and isinstance(ext, _expr.ConstExpr),\n                \"Const range should start from a const \" + \"and iterate const times\",\n            )\n\n            low, ext = low.value, ext.value\n            if ext > 114514:\n                logging.log(\n                    logging.CRITICAL, \"[Warning] Are you sure to unroll a large loop in Python?\"\n                )\n\n            bodies = []\n            for i in range(low, low + ext):\n                self.add_symbol(_name, Symbol.ConstLoopVar, i)\n                body = visit_list_to_block(self.visit, node.body)\n                body = self.wrap_up_realize(node, body)\n                bodies.append(body)\n                self.symbols.pop(_name)\n            return concat_list_to_block(bodies)\n\n        if iter_var is None:\n            _internal_assert(kind is not None, \"The loop iterating function parse error!\")\n            if isinstance(ext, _expr.PrimExpr):\n                dtype = ext.dtype\n            elif isinstance(ext, int):\n                dtype = \"int32\"\n            else:\n                raise NotImplementedError(f\"Unsupported type of ext: {type(ext)}\")\n            offset = iter_var = tvm.te.var(_name, dtype=dtype)\n            if not tvm.tir.analysis.expr_deep_equal(low, tvm.runtime.const(0, \"int32\")):\n                offset = iter_var + low\n            self.add_symbol(_name, Symbol.LoopVar, offset)\n            _body = visit_list_to_block(self.visit, node.body)\n        else:\n            _internal_assert(kind is None, \"The loop bind function parse error!\")\n            self.add_symbol(_name, Symbol.ThreadBind, iter_var)\n            self.device += 1\n            _body = visit_list_to_block(self.visit, node.body)\n            self.device -= 1\n\n        _body = self.wrap_up_realize(node, _body)\n\n        if kind is None:\n            res = _body\n        else:\n            _internal_assert(\n                not isinstance(kind, tuple), \"Micro expansion should be handled before!\"\n            )\n            res = tvm.tir.For(iter_var, tvm.runtime.const(0, \"int32\"), ext, kind, _body)\n\n        self.symbols.pop(_name)\n        return res\n\n    def visit_Return(self, node):\n        _internal_assert(\n            all(ty != Symbol.LoopVar for ty, _ in self.symbols.values()),\n            \"Return should not be in a loop body!\",\n        )\n        ids = []\n        if isinstance(node.value, ast.Name):\n            ids = [node.value.id]\n        else:\n            _internal_assert(\n                isinstance(node.value, ast.Tuple),\n                \"You should return either a single tensor or a tuple\",\n            )\n            _internal_assert(\n                all(isinstance(i, ast.Name) for i in node.value.elts), \"What do you return?\"\n            )\n            ids = [i.id for i in node.value.elts]\n        _internal_assert(len(set(ids)) == len(ids), \"Duplicated tensors in the return tuples\")\n        if len(ids) < len(self.outputs):\n            logging.log(logging.CRITICAL, \"[Warning] Not all the output buffers returned!\")\n        self.outputs = [self.symbols[i][1] for i in ids]\n        self.returned = True\n        return utils.make_nop()\n\n    def visit_Tuple(self, node):\n        return tuple(self.visit(i) for i in node.elts)\n\n    def visit_Str(self, node):\n        return node.s\n\n    def visit_Assert(self, node):\n        test = self.visit(node.test)\n        mesg = tvm.runtime.convert(self.visit(node.msg))\n        return tvm.tir.AssertStmt(test, mesg, utils.make_nop())\n\n\ndef parse_python(src, args, symbols, closure_vars):\n    \"\"\"The helper function of calling the AST visitor\n\n    Parameters\n    ----------\n    src : ast.node or str\n        If an ast.node, then directly lower it.\n        If a str, then parse it to ast and lower it.\n\n    args : list of Tensors or Vars\n        The argument lists to the function.\n        It is NOT encouraged to write a function without arguments.\n        It is NOT encouraged to write a function with side effect.\n\n    symbols : list of str\n        The symbol list of the global context of the function.\n\n    closure_vars: dict\n        A dict of external name reference captured by this function.\n\n    Returns\n    -------\n    root : Stmt\n        The result Halide IR and the parser class instance.\n    \"\"\"\n    root = ast.parse(src) if isinstance(src, str) else src\n    _internal_assert(root, ast.AST)\n    var_usage = determine_variable_usage(root, args, symbols, closure_vars)\n    parser = HybridParser(args, var_usage, symbols, closure_vars)\n    parser.parsed_body = parser.visit(root)\n    _internal_assert(parser.returned, \"No valid return found in the function body!\")\n    return parser\n\n\ndef source_to_op(src, args, symbols, closure_vars):\n    \"\"\"Another level of wrapper\n\n    Parameters\n    ----------\n    src : ast.node or str\n        If an ast.node, then directly lower it.\n        If a str, then parse it to ast and lower it.\n\n    args : list of Tensors or Vars\n        The argument lists to the function.\n        It is NOT encouraged to write a function without arguments.\n        It is NOT encouraged to write a function with side effect.\n\n    symbols : list of str\n        The symbol list of the global context of the function.\n\n    closure_vars: dict\n        A dict of external name reference captured by this function.\n\n    Returns\n    -------\n    res : list of output tensors\n        The result of output tensors of the formed OpNode.\n    \"\"\"\n    parser = parse_python(src, args, symbols, closure_vars)\n\n    input_tensors = []\n\n    def get_input_tensors(arg):\n        if isinstance(arg, Tensor):\n            input_tensors.append(arg)\n        elif isinstance(arg, Array):\n            for i in arg:\n                get_input_tensors(i)\n\n    for i in args:\n        get_input_tensors(i)\n    op = tvm.te._ffi_api.HybridOp(\n        parser.func_name, \"HybridOp\", None, input_tensors, parser.outputs, parser.parsed_body\n    )\n    res = [op.output(i) for i in range(len(parser.outputs))]\n    return res[0] if len(res) == 1 else res\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/preprocessor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Determines the declaration, r/w status, and last use of each variable\"\"\"\n\nimport ast\nimport sys\nfrom .runtime import HYBRID_GLOBALS\nfrom .utils import _internal_assert\n\n\nclass PyVariableUsage(ast.NodeVisitor):\n    \"\"\"The vistor class to determine the declaration, r/w status, and last use of each variable\"\"\"\n\n    # pylint: disable=invalid-name\n    # pylint: disable=missing-docstring\n    def __init__(self, args, symbols, closure_vars):\n        self.status = {}\n        self.scope_level = []\n        self._args = {}\n        self.args = args\n        self.aug_assign_ = False\n        self.symbols = symbols\n        self.closure_vars = closure_vars\n\n    def visit_FunctionDef(self, node):\n        self.scope_level.append(node)\n        _internal_assert(\n            len(node.args.args) == len(self.args),\n            \"#arguments passed should be the same as #arguments defined\",\n        )\n        for idx, arg in enumerate(node.args.args):\n            _attr = \"id\" if sys.version_info[0] < 3 else \"arg\"  # To make py2 and 3 compatible\n            self._args[getattr(arg, _attr)] = self.args[idx]\n        for i in node.body:\n            self.visit(i)\n\n    def visit_For(self, node):\n        _internal_assert(isinstance(node.target, ast.Name), \"For's iterator should be an id\")\n        self.visit(node.iter)\n        self.scope_level.append(node)\n        for i in node.body:\n            self.visit(i)\n        self.scope_level.pop()\n\n    def visit_Call(self, node):\n        # No function pointer supported so far\n        _internal_assert(isinstance(node.func, ast.Name), \"Function call should be an id\")\n        func_id = node.func.id\n        _internal_assert(\n            func_id\n            in list(HYBRID_GLOBALS.keys())\n            + [\"range\", \"max\", \"min\", \"len\"]\n            + list(self.symbols.keys()),\n            \"Function call id \" + func_id + \" not in intrinsics' list\",\n        )\n        for elem in node.args:\n            self.visit(elem)\n\n    def visit_AugAssign(self, node):\n        self.aug_assign_ = True\n        self.generic_visit(node)\n        self.aug_assign_ = False\n\n    def visit_Name(self, node):\n        # If it is True or False, we do not worry about it!\n        if sys.version_info[0] == 2 and node.id in [\"True\", \"False\"]:\n            return\n        # If it is from the argument list or loop variable, we do not worry about it!\n        if node.id in self._args.keys():\n            return\n        fors = [loop.target.id for loop in self.scope_level if isinstance(loop, ast.For)]\n        if node.id in fors:\n            return\n        # The loop variable cannot be overwritten when iteration\n        _internal_assert(\n            not isinstance(node.ctx, ast.Store) or node.id not in fors,\n            \"Iter var cannot be overwritten\",\n        )\n\n        if node.id not in self.status.keys():\n            # It is a captured value in closure\n            if node.id in self.closure_vars:\n                try:\n                    ast.literal_eval(str(self.closure_vars[node.id]))\n                except ValueError:\n                    raise ValueError(\"Only support capturing constant values in closure\")\n                return\n\n            _internal_assert(isinstance(node.ctx, ast.Store), \"Undeclared variable %s\" % node.id)\n            if self.aug_assign_:\n                raise ValueError('\"First store\" cannot be an AugAssign')\n            self.status[node.id] = (node, self.scope_level[-1], set())\n        else:\n            decl, loop, usage = self.status[node.id]\n            usage.add(type(node.ctx))\n            _internal_assert(\n                loop in self.scope_level, \"%s is used out of the scope it is defined!\" % node.id\n            )\n            self.status[node.id] = (decl, loop, usage)\n\n\ndef determine_variable_usage(root, args, symbols, closure_vars):\n    \"\"\"The helper function for calling the dedicated visitor.\"\"\"\n    visitor = PyVariableUsage(args, symbols, closure_vars)\n    visitor.visit(root)\n    return visitor.status\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Intrinsics of TVM-Python Hybrid Script for Python emulation runtime\"\"\"\n\nimport numpy\nfrom tvm.target import Target\n\n\nclass bind(object):  # pylint: disable=invalid-name\n    \"\"\"GPU bind software emulataion runtime.\"\"\"\n\n    def __init__(self, _, ext):\n        self.ext = ext\n\n    def __iter__(self):\n        i = 0\n        while i < self.ext:\n            yield i\n            i += 1\n\n\ndef allocate(shape, dtype=\"float32\", scope=\"global\"):  # pylint: disable=unused-argument\n    \"\"\"Allocate a buffer with given shape\n\n    Parameters\n    ----------\n    shape: Tuple\n        The shape of the tensor to be allocated\n    dtype: string\n        The data type of the tensor\n    scope: string\n        The storage scope of the tensor\n\n    Returns\n    -------\n    tensor: numpy.array\n        The tensor allocated\n    \"\"\"\n    return numpy.zeros(shape).astype(dtype)\n\n\ndef rsqrt(x):\n    \"\"\"\n    Computes reciprocal of square root of x element-wise\n\n    Parameters\n    ----------\n    x: Tensor\n\n    Returns\n    -------\n    res: Tensor\n        The result of reciprocal of square root of x\n    \"\"\"\n    return numpy.ones_like(x) / numpy.sqrt(x)\n\n\ndef popcount(x):\n    \"\"\"\n    Count ones in the binary representation of number x\n\n    Parameters\n    ----------\n    x: Integer\n        The number to be counted\n\n    Returns\n    -------\n    cnt: Integer\n        The number of ones in the binary representation of number x\n    \"\"\"\n    cnt = 0\n    while x:\n        x -= x & -x\n        cnt += 1\n    return cnt\n\n\ndef sigmoid(x):\n    \"\"\"\n    Sigmoid function of x, aka 1/(1+exp(-x)).\n\n    Parameters\n    ----------\n    x: a real number\n\n    Returns\n    -------\n    res: a real number\n        The result of sigmoid function\n    \"\"\"\n    return 1 / (1 + numpy.exp(-x))\n\n\ndef max_num_threads(allow_none=True):\n    \"\"\"Get max number of threads for GPU targets.\"\"\"\n    return Target.current(allow_none).max_num_threads\n\n\ndef inf(dtype):\n    return numpy.iinfo(dtype).max\n\n\ndef ninf(dtype):\n    return numpy.iinfo(dtype).min\n\n\nHYBRID_GLOBALS = {\n    \"unroll\": range,\n    \"vectorize\": range,\n    \"parallel\": range,\n    \"const_range\": range,\n    \"bind\": bind,\n    \"allocate\": allocate,\n    \"output_tensor\": allocate,\n    \"sqrt\": numpy.sqrt,\n    \"rsqrt\": rsqrt,\n    \"log\": numpy.log,\n    \"tanh\": numpy.tanh,\n    \"power\": numpy.power,\n    \"exp\": numpy.exp,\n    \"sigmoid\": sigmoid,\n    \"popcount\": popcount,\n    \"round\": round,\n    \"likely\": lambda cond: cond,\n    \"uint8\": numpy.uint8,\n    \"uint16\": numpy.uint16,\n    \"uint32\": numpy.uint32,\n    \"uint64\": numpy.uint64,\n    \"int8\": numpy.int8,\n    \"int16\": numpy.int16,\n    \"int32\": numpy.int32,\n    \"int64\": numpy.int64,\n    \"float16\": numpy.float16,\n    \"float32\": numpy.float32,\n    \"float64\": numpy.float64,\n    \"ceil_div\": lambda a, b: (a + b - 1) // b,\n    \"max_num_threads\": max_num_threads,\n    \"inf\": inf,\n    \"ninf\": inf,\n}\n\n\ndef _enter_hybrid_runtime(func):\n    \"\"\"Put hybrid runtime variables into the global scope\"\"\"\n    _globals = func.__globals__\n    intersect = []\n    for elem in list(HYBRID_GLOBALS.keys()):\n        if elem in _globals.keys():\n            intersect.append((elem, _globals[elem]))\n        _globals[elem] = HYBRID_GLOBALS[elem]\n    return intersect\n\n\ndef _restore_runtime(func, intersect):\n    \"\"\"Rollback the modification caused by hybrid runtime\"\"\"\n    _globals = func.__globals__\n    for elem in list(HYBRID_GLOBALS.keys()):\n        _globals.pop(elem)\n    for k, v in intersect:\n        _globals[k] = v\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/hybrid/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Internal utilities for parsing Python subset to TIR\"\"\"\n\nimport ast\nimport inspect\nimport logging\nimport sys\nimport numpy\n\nimport tvm.runtime\nfrom tvm._ffi.base import numeric_types\nfrom tvm.ir.container import Array\n\nfrom tvm.tir import expr as _expr\nfrom tvm.tir import stmt as _stmt\nfrom tvm.te.tensor import Tensor\n\n\n# pylint: disable=invalid-name\nnp_arg_types = tuple(list(numeric_types) + [numpy.ndarray])\ntvm_arg_types = (Tensor, Array, _expr.Var, _expr.ConstExpr)\nhalide_imm_types = (_expr.IntImm, _expr.FloatImm)\n\n\ndef _internal_assert(cond, err):\n    \"\"\"Simplify the code segment like if not XXX then raise an error\"\"\"\n    if not cond:\n        raise ValueError(err)\n\n\n# Useful constants. In avoid of runtime dependences, we use function calls to return them.\ndef make_nop():\n    \"\"\"Returns a 'no operation' node in HalideIR.\"\"\"\n    return _stmt.Evaluate(tvm.runtime.const(0, dtype=\"int32\"))\n\n\ndef is_docstring(node):\n    \"\"\"Checks if a Python AST node is a docstring\"\"\"\n    return isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)\n\n\ndef _pruned_source(func):\n    \"\"\"Prune source code's extra leading spaces\"\"\"\n    try:\n        lines = inspect.getsource(func).split(\"\\n\")\n        leading_space = len(lines[0]) - len(lines[0].lstrip(\" \"))\n        lines = [line[leading_space:] for line in lines]\n        return \"\\n\".join(lines)\n    except IOError as err:\n        if sys.version_info[0] == 2 and str(err) == \"could not get source code\":\n            logging.log(\n                logging.CRITICAL,\n                \"This module is not fully operated under Python2... \" \"Please move to Python3!\",\n            )\n            raise err\n\n\ndef replace_io(body, rmap):\n    \"\"\"Replacing tensors usage according to the dict given\"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm.tir import stmt_functor\n\n    def replace(op):\n        if isinstance(op, _stmt.ProducerStore) and op.producer.op in rmap.keys():\n            buf = rmap[op.producer.op]\n            return _stmt.ProducerStore(buf, op.value, op.indices)\n        if isinstance(op, _expr.ProducerLoad) and op.producer.op in rmap.keys():\n            buf = rmap[op.producer.op]\n            return _expr.ProducerLoad(buf, op.indices)\n        return None\n\n    return stmt_functor.ir_transform(body, None, replace, [\"tir.ProducerStore\", \"tir.ProducerLoad\"])\n\n\ndef _is_tvm_arg_types(args):\n    \"\"\"Determine a list of element is either a list of tvm arguments of a list of numpy arguments.\n    If neither is true, raise a value error.\"\"\"\n    if isinstance(args[0], tvm_arg_types):\n        for elem in args[1:]:\n            _internal_assert(\n                isinstance(elem, tvm_arg_types),\n                \"Expecting a Var, Tensor or ConstExpr instance but %s get!\" % str(type(elem)),\n            )\n        return True\n\n    _internal_assert(\n        isinstance(args[0], np_arg_types), \"Expect a numpy type but %s get!\" % str(type(args[0]))\n    )\n    for elem in args[1:]:\n        _internal_assert(\n            isinstance(elem, np_arg_types), \"Expect a numpy type but %s get!\" % str(type(elem))\n        )\n    return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/operation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Operation class for computation declaration.\"\"\"\nimport inspect\n\n# pylint: disable=invalid-name\nfrom numbers import Integral as _Integral\nfrom typing import List\n\nimport tvm._ffi\nimport tvm.arith._ffi_api\nimport tvm.tir\nimport tvm.tir._ffi_api\nfrom tvm._ffi.base import string_types\nfrom tvm.ir import Array\nfrom tvm.runtime import convert\n\nfrom . import _ffi_api\nfrom . import tag as _tag\nfrom . import tensor as _tensor\n\n\ndef placeholder(shape, dtype=None, name=\"placeholder\"):\n    \"\"\"Construct an empty tensor object.\n\n    Parameters\n    ----------\n    shape: Tuple of Expr\n        The shape of the tensor\n\n    dtype: str, optional\n        The data type of the tensor\n\n    name: str, optional\n        The name hint of the tensor\n\n    Returns\n    -------\n    tensor: Tensor\n        The created tensor\n    \"\"\"\n    shape = (shape,) if isinstance(shape, tvm.tir.PrimExpr) else shape\n    dtype = \"float32\" if dtype is None else dtype\n    return _ffi_api.Placeholder(shape, dtype, name)\n\n\ndef compute(shape, fcompute, name=\"compute\", tag=\"\", attrs=None, varargs_names=None):\n    \"\"\"Construct a new tensor by computing over the shape domain.\n\n    The compute rule is result[axis] = fcompute(axis)\n\n    Parameters\n    ----------\n    shape: Tuple of Expr\n        The shape of the tensor\n\n    fcompute: lambda function of indices-> value\n        Specifies the input source expression\n\n    name: str, optional\n        The name hint of the tensor\n\n    tag: str, optional\n        Additional tag information about the compute.\n\n    attrs: dict, optional\n        The additional auxiliary attributes about the compute.\n\n    varargs_names: list, optional\n        The names to use for each of the varargs. If not supplied, the varargs\n        will be called i1, i2, ...\n\n    Returns\n    -------\n    tensor: Tensor\n        The created tensor\n    \"\"\"\n    if _tag.TagScope.get_current() is not None:\n        if tag != \"\":\n            raise ValueError(\"nested tag is not allowed for now\")\n        tag = _tag.TagScope.get_current().tag\n    shape = (shape,) if isinstance(shape, tvm.tir.PrimExpr) else shape\n    # for python3\n    shape = tuple([int(s) if isinstance(s, float) else s for s in shape])\n    out_ndim = len(shape)\n\n    argspec = inspect.getfullargspec(fcompute)\n    if len(argspec.args) == 0 and argspec.varargs is None:\n        arg_names = [\"i%d\" % i for i in range(out_ndim)]\n    elif argspec.varargs is not None:\n        # if there is a varargs, it takes the remaining dimensions of out_ndim\n        num_remaining_args = out_ndim - len(argspec.args)\n        if varargs_names is not None:\n            if len(varargs_names) != num_remaining_args:\n                raise RuntimeError(\n                    f\"Number of varargs ({num_remaining_args}) does not match number\"\n                    f\"of varargs_names ({len(varargs_names)})\"\n                )\n            arg_names = argspec.args + varargs_names\n        else:\n            arg_names = argspec.args + [f\"i{i}\" for i in range(out_ndim - len(argspec.args))]\n    else:\n        arg_names = argspec.args\n        # if there are fewer args than out dimensions, the remaining dimensions\n        # are implicitly broadcast\n        out_ndim = len(arg_names)\n    assert argspec.varkw is None, \"Variable keyword arguments not supported in fcompute\"\n    assert argspec.defaults is None, \"Default arguments not supported in fcompute\"\n    assert len(argspec.kwonlyargs) == 0, \"Keyword arguments are not supported in fcompute\"\n\n    if out_ndim != len(arg_names):\n        raise ValueError(\n            \"Number of args to fcompute does not match dimension, \"\n            \"args=%d, dimension=%d\" % (len(arg_names), out_ndim)\n        )\n\n    dim_var = [tvm.tir.IterVar((0, s), x, 0) for x, s in zip(arg_names, shape[:out_ndim])]\n    body = fcompute(*[v.var for v in dim_var])\n\n    if isinstance(body, _tensor.TensorIntrinCall):\n        for i, s in enumerate(shape[out_ndim:]):\n            var_name = \"ax\" + str(i)\n            dim_var.append(tvm.tir.IterVar((0, s), var_name, 4))\n        op_node = _ffi_api.TensorComputeOp(\n            name,\n            tag,\n            dim_var,\n            body.reduce_axis,\n            out_ndim,\n            body.intrin,\n            body.tensors,\n            body.regions,\n            body.scalar_inputs,\n        )\n    else:\n        if not isinstance(body, (list, tuple)):\n            body = [body]\n        body = convert(body)\n        op_node = _ffi_api.ComputeOp(name, tag, attrs, dim_var, body)\n\n    num = op_node.num_outputs\n    outputs = tuple(op_node.output(i) for i in range(num))\n    return outputs[0] if num == 1 else outputs\n\n\ndef scan(init, update, state_placeholder, inputs=None, name=\"scan\", tag=\"\", attrs=None):\n    \"\"\"Construct new tensors by scanning over axis.\n\n    Parameters\n    ----------\n    init: Tensor or list of Tensor\n        The initial condition of first init.shape[0] timestamps\n\n    update: Tensor or list of Tensor\n        The update rule of the scan given by symbolic tensor.\n\n    state_placeholder: Tensor or list of Tensor\n        The placeholder variables used by update.\n\n    inputs: Tensor or list of Tensor, optional\n        The list of inputs to the scan. This is not required, but can\n        be useful for the compiler to detect scan body faster.\n\n    name: str, optional\n        The name hint of the tensor\n\n    tag: str, optional\n        Additonal tag information about the compute.\n\n    attrs: dict, optional\n        The additional auxiliary attributes about the compute.\n\n    Returns\n    -------\n    tensor: Tensor or list of Tensors\n        The created tensor or tuple of tensors contains multiple outputs.\n\n    Example\n    -------\n    .. code-block:: python\n\n      # The following code is equivalent to numpy.cumsum\n      m = te.var(\"m\")\n      n = te.var(\"n\")\n      X = te.placeholder((m, n), name=\"X\")\n      s_state = te.placeholder((m, n))\n      s_init = te.compute((1, n), lambda _, i: X[0, i])\n      s_update = te.compute((m, n), lambda t, i: s_state[t-1, i] + X[t, i])\n      res = tvm.te.scan(s_init, s_update, s_state, X)\n    \"\"\"\n    if _tag.TagScope.get_current() is not None:\n        if tag != \"\":\n            raise ValueError(\"nested tag is not allowed for now\")\n        tag = _tag.TagScope.get_current().tag\n    if isinstance(init, _tensor.Tensor):\n        init = [init]\n    if isinstance(update, _tensor.Tensor):\n        update = [update]\n    if isinstance(state_placeholder, _tensor.Tensor):\n        state_placeholder = [state_placeholder]\n    if isinstance(inputs, _tensor.Tensor):\n        inputs = [inputs]\n    if inputs is None:\n        inputs = []\n    if len(init) != len(update) or len(init) != len(state_placeholder):\n        raise ValueError(\"init, update, state_placeholder must have same length\")\n    axis = tvm.tir.IterVar((init[0].shape[0], update[0].shape[0]), \"%s.idx\" % name, 3)\n    op = _ffi_api.ScanOp(name, tag, attrs, axis, init, update, state_placeholder, inputs)\n    res = [op.output(i) for i in range(len(update))]\n    return res[0] if len(res) == 1 else res\n\n\ndef extern(\n    shape,\n    inputs,\n    fcompute,\n    name=\"extern\",\n    dtype=None,\n    in_buffers=None,\n    out_buffers=None,\n    tag=\"\",\n    attrs=None,\n):\n    \"\"\"Compute several tensors via an extern function.\n\n    Parameters\n    ----------\n    shape: tuple or list of tuples.\n        The shape of the outputs.\n\n    inputs: list of Tensor\n        The inputs\n\n    fcompute: lambda function of inputs, outputs-> stmt\n        Specifies the IR statement to do the computation.\n        See the following note for function signature of fcompute\n\n        .. note::\n             **Parameters**\n\n             - **ins** (list of :any:`tvm.tir.Buffer`) - Placeholder for each inputs\n             - **outs** (list of :any:`tvm.tir.Buffer`) - Placeholder for each outputs\n\n             **Returns**\n\n             - **stmt** (:any:`tvm.tir.Stmt`) - The statement that carries out array computation.\n\n    name: str, optional\n        The name hint of the tensor\n\n    dtype: str or list of str, optional\n        The data types of outputs,\n        by default dtype will be same as inputs.\n\n    in_buffers: tvm.tir.Buffer or list of tvm.tir.Buffer, optional\n        Input buffers.\n\n    out_buffers: tvm.tir.Buffer or list of tvm.tir.Buffer, optional\n        Output buffers.\n\n\n    tag: str, optional\n        Additonal tag information about the compute.\n\n    attrs: dict, optional\n        The additional auxiliary attributes about the compute.\n\n    Returns\n    -------\n    tensor: Tensor or list of Tensors\n        The created tensor or tuple of tensors contains multiple outputs.\n\n    Example\n    -------\n    In the code below, C is generated by calling external PackedFunc\n    `tvm.contrib.cblas.matmul`\n\n    .. code-block:: python\n\n        A = te.placeholder((n, l), name=\"A\")\n        B = te.placeholder((l, m), name=\"B\")\n        C = te.extern((n, m), [A, B],\n                       lambda ins, outs: tvm.tir.call_packed(\n                          \"tvm.contrib.cblas.matmul\",\n                            ins[0], ins[1], outs[0], 0, 0), name=\"C\")\n    \"\"\"\n    if _tag.TagScope.get_current() is not None:\n        if tag != \"\":\n            raise ValueError(\"nested tag is not allowed for now\")\n        tag = _tag.TagScope.get_current().tag\n    shape = (shape,) if isinstance(shape, (tvm.tir.PrimExpr, _Integral)) else shape\n    if shape == () or isinstance(shape[0], (tvm.tir.PrimExpr, _Integral)):\n        shape = [shape]\n    if in_buffers is not None:\n        in_buffers = [in_buffers] if not isinstance(in_buffers, list) else in_buffers\n        if len(inputs) != len(in_buffers):\n            raise RuntimeError(\n                \"Number of inputs and in_buffers mismatch: %d vs %d.\"\n                % (len(inputs), len(in_buffers))\n            )\n    if out_buffers is not None:\n        out_buffers = [out_buffers] if not isinstance(out_buffers, list) else out_buffers\n        if len(shape) != len(out_buffers):\n            raise RuntimeError(\n                \"Number of outputs and out_buffers mismatch: %d vs %d.\"\n                % (len(shape), len(out_buffers))\n            )\n    input_placeholders = in_buffers or []\n    output_placeholders = out_buffers or []\n    types = set()\n    for t in inputs:\n        if not isinstance(t, _tensor.Tensor):\n            raise ValueError(\"expect inputs to be tensor\")\n        if in_buffers is None:\n            input_placeholders.append(\n                tvm.tir.decl_buffer(\n                    t.shape, t.dtype, t.op.name, elem_offset=tvm.tir.Var(\"elem_offset\", \"int32\")\n                )\n            )\n        types.add(t.dtype)\n\n    if dtype is None:\n        if len(types) != 1:\n            raise ValueError(\"Cannot infer output type, please provide dtype argument\")\n        infered_type = types.pop()\n        dtype = [infered_type for _ in shape]\n    if isinstance(dtype, str):\n        dtype = [dtype]\n\n    if out_buffers is None:\n        for shp, dt in zip(shape, dtype):\n            output_placeholders.append(\n                tvm.tir.decl_buffer(shp, dt, name, elem_offset=tvm.tir.Var(\"elem_offset\", \"int32\"))\n            )\n    body = fcompute(input_placeholders, output_placeholders)\n    if isinstance(body, tvm.tir.PrimExpr):\n        body = tvm.tir.Evaluate(body)\n    if not isinstance(body, tvm.tir.Stmt):\n        raise ValueError(\n            \"Function '{}' should return PrimExpr or Stmt, but it returned '{}'\".format(\n                fcompute.__name__, type(body)\n            )\n        )\n\n    op = _ffi_api.ExternOp(name, tag, attrs, inputs, input_placeholders, output_placeholders, body)\n    res = [op.output(i) for i in range(len(output_placeholders))]\n    return res[0] if len(res) == 1 else res\n\n\ndef extern_primfunc(input_tensors: List[_tensor.Tensor], primfunc: tvm.tir.PrimFunc, **kwargs):\n    \"\"\"Compute tensors via a schedulable TIR PrimFunc\n\n    Parameters\n    ----------\n    input_tensors: list of Tensor\n        Input tensors that map to the corresponding primfunc input params.\n\n    primfunc: PrimFunc\n        The TIR PrimFunc\n\n    Returns\n    -------\n    tensor: Tensor or list of Tensors\n        The created tensor or tuple of tensors if it contains multiple outputs.\n\n    Example\n    -------\n    In the code below, a TVMScript defined TIR PrimFunc is inlined into\n    a TE ExternOp. Applying te.create_prim_func on this\n\n    .. code-block:: python\n\n        A = te.placeholder((128, 128), name=\"A\")\n        B = te.placeholder((128, 128), name=\"B\")\n\n        @T.prim_func\n        def before_split(a: T.handle, b: T.handle) -> None:\n            A = T.match_buffer(a, (128, 128))\n            B = T.match_buffer(b, (128, 128))\n            for i, j in T.grid(128, 128):\n                with T.block(\"B\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    B[vi, vj] = A[vi, vj] * 2.0\n\n        C = te.extern_primfunc([A, B], func)\n    \"\"\"\n    access_map = {\n        k: tuple(v) for k, v in tvm.arith._ffi_api.DomainTouchedAccessMap(primfunc).items()\n    }\n    in_buffers = [buf for buf, access in access_map.items() if len(access[0])]\n    out_buffers = [buf for buf, access in access_map.items() if len(access[1])]\n    assert in_buffers, \"PrimFunc has no input buffers\"\n    assert out_buffers, \"PrimFunc has no output buffers\"\n\n    outputs = []\n    inplace = []\n    input_buffers = in_buffers\n    for obuf in out_buffers:\n        if obuf in in_buffers:\n            inplace.append(obuf)\n        else:\n            outputs.append(obuf)\n\n    if not outputs:\n        iobuf = inplace.pop()\n        input_buffers.remove(iobuf)\n        outputs = [iobuf]\n\n    assert len(input_buffers) == len(input_tensors), (\n        \"The number of provided input input_tensors does not match the number of \",\n        \"input buffers in the primfunc\",\n    )\n    for tensor, buffer in zip(input_tensors, input_buffers):\n        # TODO(csullivan): Can a stronger comparison between Tensor<>Buffer be made?\n        assert len(tensor.shape) == len(buffer.shape)\n        for d1, d2 in zip(tensor.shape, buffer.shape):\n            assert d1 == d2, (\n                \"The input input_tensors provided do not match the input buffers in the \",\n                \"primfunc. Please check that the order of input te.Input_Tensors and the \",\n                \"order of the primfunc variables in the params list agree.\",\n            )\n    output = extern(\n        [buf.shape for buf in outputs],\n        input_tensors,\n        lambda ins, outs: primfunc.body,\n        in_buffers=input_buffers,\n        out_buffers=outputs,\n        **kwargs,\n    )\n    return output\n\n\ndef var(name=\"tindex\", dtype=\"int32\", span=None):\n    \"\"\"Create a new variable with specified name and dtype\n\n    Parameters\n    ----------\n    name : str\n        The name\n\n    dtype : str\n        The data type\n\n    span : Optional[Span]\n        The location of this variable in the source.\n\n    Returns\n    -------\n    var : Var\n        The result symbolic variable.\n    \"\"\"\n    return tvm.tir.Var(name, dtype, span)\n\n\ndef const(dtype=\"int32\", span=None):\n    \"\"\"Create a new constant with specified name and dtype\n\n    Parameters\n    ----------\n    name : str\n        The name\n\n    dtype : str\n        The data type\n\n    span : Optional[Span]\n        The location of this variable in the source.\n\n    Returns\n    -------\n    var : Var\n        The result symbolic variable.\n    \"\"\"\n    return tvm.tir.const(dtype, span)\n\n\ndef size_var(name=\"size\", dtype=\"int32\", span=None):\n    \"\"\"Create a new variable represents a tensor shape size, which is non-negative.\n\n    Parameters\n    ----------\n    name : str\n        The name\n\n    dtype : str\n        The data type\n\n    span : Optional[Span]\n        The location of this variable in the source.\n\n    Returns\n    -------\n    var : SizeVar\n        The result symbolic shape variable.\n    \"\"\"\n    return tvm.tir.SizeVar(name, dtype, span)\n\n\ndef thread_axis(dom=None, tag=\"\", name=\"\", span=None):\n    \"\"\"Create a new IterVar to represent thread index.\n\n    Parameters\n    ----------\n    dom : Range or str\n        The domain of iteration\n        When str is passed, dom is set to None and str is used as tag\n\n    tag : str, optional\n        The thread tag\n\n    name : str, optional\n        The name of the var.\n\n    span : Optional[Span]\n        The location of this variable in the source.\n\n    Returns\n    -------\n    axis : IterVar\n        The thread itervar.\n    \"\"\"\n    if isinstance(dom, string_types):\n        tag, dom = dom, None\n    if not tag:\n        raise ValueError(\"tag must be given as Positional or keyword argument\")\n    name = name if name else tag\n    return tvm.tir.IterVar(dom, name, 1, tag, span)\n\n\ndef reduce_axis(dom, name=\"rv\", thread_tag=\"\", span=None):\n    \"\"\"Create a new IterVar for reduction.\n\n    Parameters\n    ----------\n    dom : Range\n        The domain of iteration.\n\n    name : str\n        The name of the variable.\n\n    thread_tag : Optional[str]\n        The name of the thread_tag.\n\n    span : Optional[Span]\n        The location of this variable in the source.\n\n    Returns\n    -------\n    axis : IterVar\n        An iteration variable representing the value.\n    \"\"\"\n    return tvm.tir.IterVar(dom, name, 2, thread_tag, span)\n\n\ndef create_prim_func(ops: List[_tensor.Tensor]) -> tvm.tir.PrimFunc:\n    \"\"\"Create a TensorIR PrimFunc from tensor expression\n\n    Parameters\n    ----------\n    ops : List[Tensor]\n        The source expression.\n\n    Example\n    -------\n    We define a matmul kernel using following code:\n\n    .. code-block:: python\n\n        import tvm\n        from tvm import te\n        from tvm.te import create_prim_func\n        import tvm.script\n\n        A = te.placeholder((128, 128), name=\"A\")\n        B = te.placeholder((128, 128), name=\"B\")\n        k = te.reduce_axis((0, 128), \"k\")\n        C = te.compute((128, 128), lambda x, y: te.sum(A[x, k] * B[y, k], axis=k), name=\"C\")\n        func = create_prim_func([A, B, C])\n        print(func.script())\n\n    If we want to use TensorIR schedule to do transformations on such kernel,\n    we need to use `create_prim_func([A, B, C])` to create a schedulable PrimFunc.\n    The generated function looks like:\n\n    .. code-block:: python\n\n        @T.prim_func\n        def tir_matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n            A = T.match_buffer(a, (128, 128))\n            B = T.match_buffer(b, (128, 128))\n            C = T.match_buffer(c, (128, 128))\n\n            for i, j, k in T.grip(128, 128, 128):\n                with T.block():\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    with T.init():\n                        C[vi, vj] = 0.0\n                    C[vi, vj] += A[vi, vk] * B[vj, vk]\n\n    Returns\n    -------\n    func : tir.PrimFunc\n        The created function.\n    \"\"\"\n    if not isinstance(ops, (list, tuple, Array)):\n        ops = [ops]\n    return _ffi_api.CreatePrimFunc(ops)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/schedule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import\n\"\"\"The computation schedule api of TVM.\"\"\"\nimport collections\nimport inspect\nfrom typing import Callable, List\n\nimport tvm._ffi\nfrom tvm._ffi.base import string_types\n\nfrom tvm.runtime import Object, convert\nfrom tvm.ir import container as _container\nfrom tvm.tir import IterVar, Buffer, Var, IndexMap\n\nfrom . import tensor as _tensor\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object\nclass Split(Object):\n    \"\"\"Split operation on axis.\"\"\"\n\n\n@tvm._ffi.register_object\nclass Fuse(Object):\n    \"\"\"Fuse operation on axis.\"\"\"\n\n\n@tvm._ffi.register_object\nclass Singleton(Object):\n    \"\"\"Singleton axis.\"\"\"\n\n\ndef create_schedule(ops):\n    \"\"\"Create a schedule for list of ops\n\n    Parameters\n    ----------\n    ops : list of Operations\n        The source expression.\n\n    Returns\n    -------\n    sch : schedule.Schedule\n        The created schedule.\n    \"\"\"\n    if not isinstance(ops, (list, _container.Array)):\n        ops = [ops]\n    return _ffi_api.CreateSchedule(ops)\n\n\n@tvm._ffi.register_object\nclass Schedule(Object):\n    \"\"\"Schedule for all the stages.\"\"\"\n\n    def __getitem__(self, k):\n        if isinstance(k, _tensor.Tensor):\n            k = k.op\n        if not isinstance(k, _tensor.Operation):\n            raise ValueError(\"Expect schedule key to be Tensor or Operation\")\n        if k not in self.stage_map:\n            raise ValueError(\"Cannot find the operation %s in schedule\" % (str(k)))\n        return self.stage_map[k]\n\n    def normalize(self):\n        \"\"\"Build a normalized schedule from the current schedule.\n\n        Insert necessary rebase to make certain iter var to start from 0.\n        This is needed before bound inference and followup step.\n\n        Returns\n        -------\n        sch : Schedule\n            The normalized schedule.\n        \"\"\"\n        return _ffi_api.ScheduleNormalize(self)\n\n    def create_group(self, outputs, inputs, include_inputs=False):\n        \"\"\"Create stage group by giving output and input boundary.\n\n        The operators between outputs and inputs are placed as member of group.\n        outputs are include in the group, while inputs are not included.\n\n        Parameters\n        ----------\n        outputs : list of Tensors\n            The outputs of the group.\n\n        inputs : list of Tensors\n            The inputs of the group.\n\n        include_inputs : boolean, optional\n            Whether include input operations in the group if they are used by outputs.\n\n        Returns\n        -------\n        group : Stage\n            A virtual stage represents the group, user can use compute_at to move\n            the attachment point of the group.\n        \"\"\"\n        if isinstance(outputs, _tensor.Tensor):\n            outputs = [outputs]\n        if isinstance(inputs, _tensor.Tensor):\n            inputs = [inputs]\n        return _ffi_api.ScheduleCreateGroup(self, outputs, inputs, include_inputs)\n\n    def cache_read(self, tensor, scope, readers):\n        \"\"\"Create a cache read of original tensor for readers.\n\n        This will mutate the body of the readers.\n        A new cache stage will be created for the tensor.\n        Call this before doing any split/fuse schedule.\n\n        Parameters\n        ----------\n        tensor : Tensor\n            The tensor to be cached.\n        scope : str\n            The scope of cached\n        readers : list of Tensor or Operation\n            The readers to read the cache.\n\n        Returns\n        -------\n        cache : Tensor\n            The created cache tensor.\n        \"\"\"\n        if isinstance(readers, (_tensor.Tensor, _tensor.Operation)):\n            readers = [readers]\n        readers = [t.op if isinstance(t, _tensor.Tensor) else t for t in readers]\n        return _ffi_api.ScheduleCacheRead(self, tensor, scope, readers)\n\n    def cache_write(self, tensor, scope):\n        \"\"\"Create a cache write of original tensor, before storing into tensor.\n\n        This will mutate the body of the tensor.\n        A new cache stage will created before feed into the tensor.\n\n        This function can be used to support data layout transformation.\n        If there is a split/fuse/reorder on the data parallel axis of tensor\n        before cache_write is called. The intermediate cache stores\n        the data in the layout as the iteration order of leave axis.\n        The data will be transformed back to the original layout in the original tensor.\n        User can further call compute_inline to inline the original layout and keep\n        the data stored in the transformed layout.\n\n        Parameters\n        ----------\n        tensor : Tensor, list or tuple\n            The tensors to be feed to. All the tensors must be produced by one computeOp\n        scope : str\n            The scope of cached\n\n        Returns\n        -------\n        cache : Tensor\n            The created cache tensor.\n        \"\"\"\n        return _ffi_api.ScheduleCacheWrite(self, tensor, scope)\n\n    def rfactor(self, tensor, axis, factor_axis=0):\n        \"\"\"Factor a reduction axis in tensor's schedule to be an explicit axis.\n\n        This will create a new stage that generated the new tensor with axis\n        as the first dimension. The tensor's body will be rewritten as a reduction\n        over the factored tensor.\n\n        Parameters\n        ----------\n        tensor : Tensor\n            The tensor to be factored.\n        axis : IterVar\n            The reduction axis in the schedule to be factored.\n        factor_axis : int\n            The position where the new axis is placed.\n\n        Returns\n        -------\n        tfactor : Tensor or Array of Tensor\n            The created factored tensor.\n        \"\"\"\n        factored = _ffi_api.ScheduleRFactor(self, tensor, axis, factor_axis)\n        return factored[0] if len(factored) == 1 else factored\n\n\n@tvm._ffi.register_object\nclass Stage(Object):\n    \"\"\"A Stage represents schedule for one operation.\"\"\"\n\n    def split(self, parent, factor=None, nparts=None):\n        \"\"\"Split the stage either by factor providing outer scope, or both\n\n        Parameters\n        ----------\n        parent : IterVar\n             The parent iter var.\n\n        factor : Expr, optional\n             The splitting factor\n\n        nparts : Expr, optional\n             The number of outer parts.\n\n        Returns\n        -------\n        outer : IterVar\n            The outer variable of iteration.\n\n        inner : IterVar\n            The inner variable of iteration.\n        \"\"\"\n        if nparts is not None:\n            if factor is not None:\n                raise ValueError(\"Do not need to provide both outer and nparts\")\n            outer, inner = _ffi_api.StageSplitByNParts(self, parent, nparts)\n        else:\n            if factor is None:\n                raise ValueError(\"Either nparts or factor need to be provided\")\n            outer, inner = _ffi_api.StageSplitByFactor(self, parent, factor)\n        return outer, inner\n\n    def fuse(self, *args):\n        \"\"\"Fuse multiple consecutive iteration variables into a single iteration variable.\n\n        fused = fuse(...fuse(fuse(args[0], args[1]), args[2]),..., args[-1])\n        The order is from outer to inner.\n\n        Parameters\n        ----------\n        args : list of IterVars\n            Itervars that proceeds each other\n\n        Returns\n        -------\n        fused : IterVar\n            The fused variable of iteration.\n        \"\"\"\n        fused = _ffi_api.StageFuse(self, args)\n        return fused\n\n    def set_scope(self, scope):\n        \"\"\"Set the thread scope of this stage\n\n        Parameters\n        ----------\n        scope : str\n            The thread scope of this stage\n        \"\"\"\n        return _ffi_api.StageSetScope(self, scope)\n\n    def bind(self, ivar, thread_ivar):\n        \"\"\"Bind ivar to thread index thread_ivar\n\n        Parameters\n        ----------\n        ivar : IterVar\n            The iteration to be binded to thread.\n\n        thread_ivar : IterVar\n            The thread to be binded.\n        \"\"\"\n        _ffi_api.StageBind(self, ivar, thread_ivar)\n\n    def env_threads(self, threads):\n        \"\"\"Mark threads to be launched at the outer scope of composed op.\n\n        Parameters\n        ----------\n        threads : list of threads\n            The threads to be launched.\n        \"\"\"\n        if isinstance(threads, IterVar):\n            threads = [threads]\n        _ffi_api.StageEnvThreads(self, threads)\n\n    def set_store_predicate(self, predicate):\n        \"\"\"Set predicate under which store to the array can be performed.\n\n        Use this when there are duplicated threads doing the same store and we only\n        need one of them to do the store.\n\n        Parameters\n        ----------\n        predicate : Expr\n            The guard condition fo store.\n        \"\"\"\n        _ffi_api.StageSetStorePredicate(self, predicate)\n\n    def compute_at(self, parent, scope):\n        \"\"\"Attach the stage at parent's scope\n\n        Parameters\n        ----------\n        parent : Stage\n            The parent stage\n\n        scope : IterVar\n            The loop scope t be attached to.\n        \"\"\"\n        _ffi_api.StageComputeAt(self, parent, scope)\n\n    def compute_inline(self):\n        \"\"\"Mark stage as inline\n\n        Parameters\n        ----------\n        parent : Stage\n            The parent stage\n        \"\"\"\n        _ffi_api.StageComputeInline(self)\n\n    def compute_root(self):\n        \"\"\"Attach the stage at parent, and mark it as root\n\n        Parameters\n        ----------\n        parent : Stage\n            The parent stage\n        \"\"\"\n        _ffi_api.StageComputeRoot(self)\n\n    def reorder(self, *args):\n        \"\"\"reorder the arguments in the specified order.\n\n        Parameters\n        ----------\n        args : list of IterVar\n            The order to be ordered\n        \"\"\"\n        _ffi_api.StageReorder(self, args)\n\n    def tile(self, x_parent, y_parent, x_factor, y_factor):\n        \"\"\"Perform tiling on two dimensions\n\n        The final loop order from outmost to inner most are\n        [x_outer, y_outer, x_inner, y_inner]\n\n        Parameters\n        ----------\n        x_parent : IterVar\n            The original x dimension\n        y_parent : IterVar\n            The original y dimension\n        x_factor : Expr\n            The stride factor on x axis\n        y_factor : Expr\n            The stride factor on y axis\n\n        Returns\n        -------\n        x_outer : IterVar\n            Outer axis of x dimension\n        y_outer : IterVar\n            Outer axis of y dimension\n        x_inner : IterVar\n            Inner axis of x dimension\n        p_y_inner : IterVar\n            Inner axis of y dimension\n        \"\"\"\n        x_outer, y_outer, x_inner, y_inner = _ffi_api.StageTile(\n            self, x_parent, y_parent, x_factor, y_factor\n        )\n        return x_outer, y_outer, x_inner, y_inner\n\n    def vectorize(self, var):\n        \"\"\"Vectorize the iteration.\n\n        Parameters\n        ----------\n        var : IterVar\n            The iteration to be vectorize\n        \"\"\"\n        _ffi_api.StageVectorize(self, var)\n\n    def tensorize(self, var, tensor_intrin):\n        \"\"\"Tensorize the computation enclosed by var with tensor_intrin\n\n        Parameters\n        ----------\n        var : IterVar\n            The iteration boundary of tensorization.\n\n        tensor_intrin : TensorIntrin\n            The tensor intrinsic used for computation.\n        \"\"\"\n        _ffi_api.StageTensorize(self, var, tensor_intrin)\n\n    def unroll(self, var):\n        \"\"\"Unroll the iteration.\n\n        Parameters\n        ----------\n        var : IterVar\n            The iteration to be unrolled.\n        \"\"\"\n        _ffi_api.StageUnroll(self, var)\n\n    def parallel(self, var):\n        \"\"\"Parallelize the iteration.\n\n        Parameters\n        ----------\n        var : IterVar\n            The iteration to be parallelized.\n        \"\"\"\n        _ffi_api.StageParallel(self, var)\n\n    def pragma(self, var, pragma_type, pragma_value=None):\n        \"\"\"Annotate the iteration with pragma\n\n        This will translate to a pragma_scope surrounding\n        the corresponding loop generated.\n        Useful to support experimental features and extensions.\n\n        Parameters\n        ----------\n        var : IterVar\n            The iteration to be anotated\n\n        pragma_type : str\n             The pragma string to be annotated\n\n        pragma_value : Expr, optional\n             The pragma value to pass along the pragma\n\n        Note\n        ----\n        Most pragmas are advanced/experimental features\n        and may subject to change. List of supported pragmas:\n\n        - **debug_skip_region**\n\n          Force skip the region marked by the axis and turn it into no-op.\n          This is useful for debug purposes.\n\n        - **parallel_launch_point**\n\n          Specify to launch parallel threads outside the\n          specified iteration loop. By default the threads\n          launch at the point of parallel construct.\n          This pragma moves the launching point to even outer scope.\n          The threads are launched once and reused across multiple\n          parallel constructs as BSP style program.\n\n        - **parallel_barrier_when_finish**\n\n          Insert a synchronization barrier between working threads\n          after the specified loop iteration finishes.\n\n        - **parallel_stride_pattern**\n\n          Hint parallel loop to execute in strided pattern.\n          :code:`for (int i = task_id; i < end; i += num_task)`\n\n        \"\"\"\n        if isinstance(pragma_value, string_types):\n            pragma_value = convert(pragma_value)\n        _ffi_api.StagePragma(self, var, pragma_type, pragma_value)\n\n    def prefetch(self, tensor, var, offset):\n        \"\"\"Prefetch the specified variable\n\n        Parameters\n        ----------\n        tensor : Tensor\n            The tensor to be prefetched\n        var : IterVar\n            The loop point at which the prefetching is applied\n        offset : Expr\n            The number of iterations to be prefetched before actual execution\n        \"\"\"\n        _ffi_api.StagePrefetch(self, tensor, var, offset)\n\n    def storage_align(self, axis, factor, offset):\n        \"\"\"Set alignment requirement for specific axis\n\n        This ensures that stride[axis] == k * factor + offset for some k.\n        This is useful to set memory layout to for more friendly memory\n        access pattern. For example, we can set alignment to be\n        factor=2, offset=1 to avoid bank conflict for thread access on\n        higher dimension in GPU shared memory.\n\n        Parameters\n        ----------\n        axis : IterVar\n            The axis dimension to be aligned.\n        factor : int\n            The factor in alignment specification.\n        offset : int\n            The offset in the alignment specification.\n        \"\"\"\n        _ffi_api.StageStorageAlign(self, axis, factor, offset)\n\n    def double_buffer(self):\n        \"\"\"Compute the current stage via double buffering.\n\n        This can only be applied to intermediate stage.\n        This will double the storage cost of the current stage.\n        Can be useful to hide load latency.\n        \"\"\"\n        _ffi_api.StageDoubleBuffer(self)\n\n    def rolling_buffer(self):\n        \"\"\"Compute the current stage via rolling buffering.\n\n        This can only be applied to intermediate stage.\n        This will change the storage cost of the current stage.\n        \"\"\"\n        _ffi_api.StageRollingBuffer(self)\n\n    def transform_layout(self, mapping_function: Callable[..., List[tvm.tir.PrimExpr]]):\n        \"\"\"Defines the layout transformation for the current stage's tensor.\n\n        The map from initial_indices to final_indices must be an\n        invertible affine transformation.  This method may be called\n        more than once for a given tensor, in which case each\n        transformation is applied sequentially.\n\n        If the stage is a ComputeOp, then the iteration order of the\n        compute stage is rewritten to be a row-major traversal of the\n        tensor, and the new loop iteration variables are returned.\n        For all other stages, the loop iteration order is unmodified,\n        and the return value is None.\n\n        Parameters\n        ----------\n        mapping_function : Callable[..., List[tvm.tir.PrimExpr]]\n\n            A callable that accepts N arguments of type tvm.tir.Var,\n            and outputs a list of PrimExpr.  The input arguments\n            represent the location of a value in the current stage's\n            tensor, using the pre-transformation layout.  The return\n            value of the function gives the location of that value in\n            the current stage's tensor, using the post-transformation\n            layout.\n\n        Returns\n        -------\n        new_iter_vars : Optional[List[tvm.tir.IterVar]]\n\n            If the stage is a ComputeOp, then the return will be the\n            updated loop iteration variables over the data array, in\n            the same order as the output values from the\n            `mapping_function`.\n\n            Otherwise, the return value is None.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            # ``A`` is a tensor whose compute definition is in NHWC\n            # format, and should be transformed into NCHWc format.\n\n            s[A].transform_layout(\n                lambda n,h,w,c: [n, c//4, h, w, c%4]\n            )\n\n\n        .. code-block:: python\n\n            # ``A`` is a tensor whose compute definition is in an\n            # arbitrary format, and should be transformed such that\n            # the last index is split, with the slower-changing index\n            # of the split placed at the slowest changing dimension.\n\n            s[A].transform_layout(\n                lambda *indices, i: [i//4, *indices, i%4]\n            )\n\n        .. code-block:: python\n\n            # ``B`` is a tensor defined by te.compute to be a copy of\n            # ``A`, and should be transformed such that ``B``'s layout\n            # is a transpose of ``A``'s layout.  The loop iteration\n            # that computes ``B`` will correspond to ``B``'s memory\n            # layout.\n\n            A = te.placeholder([n,m])\n            B = te.compute(A.shape, lambda i,j: A[i,j])\n            s = te.create_schedule(B.op)\n\n            s[B].transform_layout(lambda i,j: [j,i])\n\n        \"\"\"\n\n        ndim = len(self.op.output(0).shape)\n        index_map, axis_separators = IndexMap.from_func_with_separators(mapping_function, ndim=ndim)\n\n        new_iter_vars = _ffi_api.StageTransformLayout(\n            self, index_map.initial_indices, index_map.final_indices\n        )\n        _ffi_api.StageSetAxisSeparators(self, axis_separators)\n\n        return new_iter_vars or None\n\n\n@tvm._ffi.register_object\nclass SpecializedCondition(Object):\n\n    \"\"\"Specialized condition to enable op specialization.\"\"\"\n\n    def __init__(self, conditions):\n        \"\"\"Create a specialized condition.\n\n        .. note::\n            Conditions are represented in conjunctive joint form (CNF).\n            Each condition should be a simple expression, e.g., n > 16,\n            m % 8 == 0, etc., where n, m are tvm.Var that represents a\n            dimension in the tensor shape.\n\n        Parameters\n        ----------\n        conditions : List of tvm.Expr\n            List of conditions in conjunctive joint form (CNF).\n        \"\"\"\n        if not isinstance(conditions, (list, _container.Array)):\n            conditions = [conditions]\n        self.__init_handle_by_constructor__(_ffi_api.CreateSpecializedCondition, conditions)\n\n    @staticmethod\n    def current():\n        \"\"\"Returns the current specialized condition\"\"\"\n        return _ffi_api.GetCurrentSpecialization()\n\n    def __enter__(self):\n        _ffi_api.EnterSpecializationScope(self)\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        _ffi_api.ExitSpecializationScope(self)\n\n\n# Sentinel value used to indicate which groups of pre-flattening axes\n# should be used to post-flattening axes axes.  Moved from\n# te.AXIS_SEPARATOR to tir.IndexMap.AXIS_SEPARATOR for general use,\n# maintained here for backwards compatibility.\nAXIS_SEPARATOR = IndexMap.AXIS_SEPARATOR\n\n\ntvm._ffi._init_api(\"schedule\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/tag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tag class for TVM operators.\"\"\"\nimport warnings\nfrom tvm._ffi.base import decorate\n\n\nclass TagScope(object):\n    \"\"\"Tag scope object to set tag for operators, working as context\n    manager and decorator both. See also tag_scope.\n    \"\"\"\n\n    _current = None\n\n    @classmethod\n    def get_current(cls):\n        if cls._current:\n            cls._current.accessed = True\n        return cls._current\n\n    def __init__(self, tag):\n        self._old_scope = None\n        self.tag = tag\n        self.accessed = False\n\n    def __enter__(self):\n        if TagScope._current is not None:\n            raise ValueError(\"nested op_tag is not allowed for now\")\n        self._old_scope = TagScope._current\n        TagScope._current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        assert self._old_scope is None\n        if not self.accessed:\n            warnings.warn(\"Tag '%s' declared via TagScope was not used.\" % (self.tag,))\n        TagScope._current = self._old_scope\n\n    def __call__(self, fdecl):\n        def tagged_fdecl(func, *args, **kwargs):\n            with self:\n                return func(*args, **kwargs)\n\n        return decorate(fdecl, tagged_fdecl)\n\n\ndef tag_scope(tag):\n    \"\"\"The operator tag scope.\n\n    Parameters\n    ----------\n    tag: str\n        The tag name.\n\n    Returns\n    -------\n    tag_scope: TagScope\n        The tag scope object, which can be used as decorator or\n        context manger.\n\n    Example\n    -------\n    .. code-block:: python\n\n        n = te.var('n')\n        m = te.var('m')\n        l = te.var('l')\n        A = te.placeholder((n, l), name='A')\n        B = te.placeholder((m, l), name='B')\n        k = te.reduce_axis((0, l), name='k')\n\n        with tvm.te.tag_scope(tag='matmul'):\n            C = te.compute((n, m), lambda i, j: te.sum(A[i, k] * B[j, k], axis=k))\n\n        # or use tag_scope as decorator\n        @tvm.te.tag_scope(tag=\"conv\")\n        def compute_relu(data):\n            return te.compute(data.shape, lambda *i: tvm.tir.Select(data(*i) < 0, 0.0, data(*i)))\n    \"\"\"\n    return TagScope(tag)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tensor class for computation declaration.\"\"\"\n# pylint: disable=invalid-name\nimport tvm._ffi\n\nfrom tvm.runtime import Object, ObjectGeneric, convert_to_object\nfrom tvm.tir import expr as _expr, DataProducer\n\nfrom . import _ffi_api\n\n\nclass TensorSlice(ObjectGeneric, _expr.ExprOp):\n    \"\"\"Auxiliary data structure for enable slicing syntax from tensor.\"\"\"\n\n    def __init__(self, tensor, indices):\n        if not isinstance(indices, tuple):\n            indices = (indices,)\n        self.tensor = tensor\n        self.indices = indices\n\n    def __getitem__(self, indices):\n        if not isinstance(indices, tuple):\n            indices = (indices,)\n        return TensorSlice(self.tensor, self.indices + indices)\n\n    def asobject(self):\n        \"\"\"Convert slice to object.\"\"\"\n        return self.tensor.__call__(*self.indices)\n\n    @property\n    def dtype(self):\n        \"\"\"Data content of the tensor.\"\"\"\n        return self.tensor.dtype\n\n\n@tvm._ffi.register_object\nclass TensorIntrinCall(Object):\n    \"\"\"Intermediate structure for calling a tensor intrinsic.\"\"\"\n\n\n@tvm._ffi.register_object\nclass Tensor(DataProducer, _expr.ExprOp):\n    \"\"\"Tensor object, to construct, see function.Tensor\"\"\"\n\n    def __call__(self, *indices):\n        ndim = self.ndim\n        if len(indices) != ndim:\n            raise ValueError(\n                \"Need to provide %d index in tensor but %d was provided\" % (ndim, len(indices))\n            )\n        indices = convert_to_object(indices)\n        args = []\n        for x in indices:\n            if isinstance(x, _expr.PrimExpr):\n                args.append(x)\n            elif isinstance(x, _expr.IterVar):\n                args.append(x.var)\n            else:\n                raise ValueError(\"The indices must be expression\")\n\n        return _expr.ProducerLoad(self, args)\n\n    def __getitem__(self, indices):\n        return TensorSlice(self, indices)\n\n    def __hash__(self):\n        return _ffi_api.TensorHash(self)\n\n    def __eq__(self, other):\n        if not isinstance(other, Tensor):\n            if isinstance(other, _expr.ExprOp):\n                return _expr.EqualOp(self, other)\n            return False\n        if self.ndim == 0 and other.ndim == 0:\n            raise ValueError(\n                \"Equal == comparison among rank-0 tensor is ambiguous, \"\n                \"use Tensor.equal for content expression equvalence, \"\n                \"use Tensor.same_as for exact reference comparison\"\n            )\n        return _ffi_api.TensorEqual(self, other)\n\n    @property\n    def ndim(self):\n        \"\"\"Dimension of the tensor.\"\"\"\n        return len(self.shape)\n\n    @property\n    def axis(self):\n        \"\"\"Axis of the tensor.\"\"\"\n        return self.__getattr__(\"axis\")\n\n    @property\n    def op(self):\n        \"\"\"The corressponding :py:class:`Operation`.\"\"\"\n        return self.__getattr__(\"op\")\n\n    @property\n    def value_index(self):\n        \"\"\"The output value index the tensor corresponds to.\"\"\"\n        return self.__getattr__(\"value_index\")\n\n    @property\n    def shape(self):\n        \"\"\"The output shape of the tensor.\"\"\"\n        return self.__getattr__(\"shape\")\n\n    @property\n    def name(self):\n        op = self.op\n        if op.num_outputs == 1:\n            return op.name\n        return \"%s.v%d\" % (op.name, self.value_index)\n\n\nclass Operation(Object):\n    \"\"\"Represent an operation that generates a tensor\"\"\"\n\n    def output(self, index):\n        \"\"\"Get the index-th output of the operation\n\n        Parameters\n        ----------\n        index : int\n            The index size.\n\n        Returns\n        -------\n        out : Tensor\n            The i-th output.\n        \"\"\"\n        return _ffi_api.OpGetOutput(self, index)\n\n    @property\n    def num_outputs(self):\n        \"\"\"Number of outputs from this op.\"\"\"\n        return _ffi_api.OpNumOutputs(self)\n\n    @property\n    def input_tensors(self):\n        \"\"\"List of input tensors to this op.\"\"\"\n        return _ffi_api.OpInputTensors(self)\n\n\n@tvm._ffi.register_object\nclass PlaceholderOp(Operation):\n    \"\"\"Placeholder operation.\"\"\"\n\n\n@tvm._ffi.register_object\nclass BaseComputeOp(Operation):\n    \"\"\"Compute operation.\"\"\"\n\n    @property\n    def axis(self):\n        \"\"\"Represent the IterVar axis, defined when it is a ComputeOp\"\"\"\n        return self.__getattr__(\"axis\")\n\n    @property\n    def reduce_axis(self):\n        \"\"\"Represent axis of reductions, only defined when it is a ComputeOp\"\"\"\n        return self.__getattr__(\"reduce_axis\")\n\n\n@tvm._ffi.register_object\nclass ComputeOp(BaseComputeOp):\n    \"\"\"Scalar operation.\"\"\"\n\n\n@tvm._ffi.register_object\nclass TensorComputeOp(BaseComputeOp):\n    \"\"\"Tensor operation.\"\"\"\n\n\n@tvm._ffi.register_object\nclass ScanOp(Operation):\n    \"\"\"Scan operation.\"\"\"\n\n    @property\n    def scan_axis(self):\n        \"\"\"Represent the scan axis, only defined when it is a ScanOp\"\"\"\n        return self.__getattr__(\"scan_axis\")\n\n\n@tvm._ffi.register_object\nclass ExternOp(Operation):\n    \"\"\"External operation.\"\"\"\n\n\n@tvm._ffi.register_object\nclass HybridOp(Operation):\n    \"\"\"Hybrid operation.\"\"\"\n\n    @property\n    def axis(self):\n        \"\"\"Represent the IterVar axis, also defined when it is a HybridOp\"\"\"\n        return self.__getattr__(\"axis\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/te/tensor_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tensor intrinsics\"\"\"\nimport tvm._ffi\nimport tvm.tir\n\nfrom tvm.runtime import Object, convert\nfrom tvm.ir import Range\nfrom .tensor import PlaceholderOp\n\nfrom . import tensor as _tensor\nfrom . import _ffi_api\n\n\ndef _get_region(tslice):\n    region = []\n    for idx in tslice.indices:\n        if isinstance(idx, slice):\n            assert idx.step is None\n            region.append(Range(idx.start, idx.stop))\n        else:\n            if isinstance(idx, tvm.tir.IterVar):\n                begin = idx.var\n            else:\n                begin = idx\n            region.append(Range.from_min_extent(begin, 1))\n    return region\n\n\n@tvm._ffi.register_object\nclass TensorIntrin(Object):\n    \"\"\"Tensor intrinsic functions for certain computation.\n\n    See Also\n    --------\n    decl_tensor_intrin: Construct a TensorIntrin\n    \"\"\"\n\n    def __call__(self, *args, **kwargs):\n        tensors = [x.tensor for x in args if isinstance(x, _tensor.TensorSlice)]\n        scalar_inputs = [x for x in args if not isinstance(x, _tensor.TensorSlice)]\n        regions = [_get_region(x) for x in args if isinstance(x, _tensor.TensorSlice)]\n        reduce_axis = []\n        if \"reduce_axis\" in kwargs:\n            reduce_axis = kwargs[\"reduce_axis\"]\n            if not isinstance(reduce_axis, (list, tuple)):\n                reduce_axis = [reduce_axis]\n            reduce_axis = convert(reduce_axis)\n        if scalar_inputs:\n            scalar_inputs = convert(scalar_inputs)\n        return _ffi_api.TensorIntrinCall(self, tensors, regions, reduce_axis, scalar_inputs)\n\n\ndef decl_tensor_intrin(\n    op, fcompute, name=\"tensor_intrin\", binds=None, scalar_params=None, default_buffer_params=None\n):\n    \"\"\"Declare a tensor intrinsic function.\n\n    Parameters\n    ----------\n    op: Operation\n        The symbolic description of the intrinsic operation\n\n    fcompute: lambda function of inputs, outputs-> stmt\n        Specifies the IR statement to do the computation.\n        See the following note for function signature of fcompute\n\n        .. note::\n             **Parameters**\n\n             - **ins** (list of :any:`tvm.tir.Buffer`) - Placeholder for each inputs\n             - **outs** (list of :any:`tvm.tir.Buffer`) - Placeholder for each outputs\n\n             **Returns**\n\n             - **stmt** (:any:`tvm.tir.Stmt`, or tuple of three stmts)\n             - If a single stmt is returned, it represents the body\n             - If tuple of three stmts are returned they corresponds to body,\n               reduce_init, reduce_update\n\n    name: str, optional\n        The name of the intrinsic.\n\n    binds: dict of :any:`Tensor` to :any:`tvm.tir.Buffer`, optional\n        Dictionary that maps the Tensor to Buffer which specified the data layout\n        requirement of the function. By default, a new compact buffer is created\n        for each tensor in the argument.\n\n    scalar_params: a list of variables used by op, whose values will be passed\n                   as scalar_inputs when the tensor intrinsic is called.\n\n    default_buffer_params: Optional[dict]\n        Dictionary of buffer arguments to be passed when constructing a buffer.\n\n    Returns\n    -------\n    intrin: TensorIntrin\n        A TensorIntrin that can be used in tensorize schedule.\n    \"\"\"\n    if not isinstance(op, _tensor.Operation):\n        raise TypeError(\"expect Operation\")\n    inputs = op.input_tensors\n    binds = binds if binds else {}\n    tensors = list(inputs)\n    for i in range(op.num_outputs):\n        tensors.append(op.output(i))\n\n    binds_list = []\n    for t in inputs:\n        if not isinstance(t.op, PlaceholderOp):\n            raise ValueError(\"Do not yet support composition op\")\n\n    default_buffer_params = {} if default_buffer_params is None else default_buffer_params\n    for t in tensors:\n        buf = (\n            binds[t]\n            if t in binds\n            else tvm.tir.decl_buffer(t.shape, t.dtype, t.op.name, **default_buffer_params)\n        )\n        binds_list.append(buf)\n\n    if scalar_params:\n        body = fcompute(binds_list[: len(inputs)], binds_list[len(inputs) :], scalar_params)\n    else:\n        body = fcompute(binds_list[: len(inputs)], binds_list[len(inputs) :])\n        scalar_params = []\n    if isinstance(body, (tvm.tir.PrimExpr, tvm.tir.Stmt)):\n        body = [body]\n    body = [tvm.tir.Evaluate(x) if isinstance(x, tvm.tir.PrimExpr) else x for x in body]\n    if len(body) < 3:\n        body += [None] * (3 - len(body))\n    return _ffi_api.TensorIntrin(name, op, inputs, binds_list, scalar_params, *body)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"Utility Python functions for TVM testing\"\"\"\n\nfrom .utils import *\n\nfrom ._ffi_api import nop, echo, device_test, run_check_signal, object_use_count\nfrom ._ffi_api import test_wrap_callback, test_raise_error_callback, test_check_eq_callback\nfrom ._ffi_api import ErrorTest, FrontendTestModule, identity_cpp\n\nfrom .popen_pool import initializer, after_initializer, register_ffi, call_cpp_ffi\nfrom .popen_pool import call_py_ffi, call_cpp_py_ffi, fast_summation, slow_summation\nfrom .popen_pool import timeout_job\n\nfrom . import auto_scheduler\nfrom . import autotvm\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.testing\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"testing\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common functions for AOT test cases\"\"\"\nimport sys\nimport datetime\nimport os\nimport pathlib\nimport re\nimport shutil\nimport subprocess\nimport tarfile\nimport logging\nfrom typing import Any, NamedTuple, Union, Optional, List, Dict\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.contrib import utils, graph_executor\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.relay.backend.utils import mangle_module_name\nfrom tvm.micro import export_model_library_format\nfrom tvm.micro.testing.utils import mlf_extract_workspace_size_bytes\n\n_LOG = logging.getLogger(__name__)\n\nNP_TYPE_TO_C = {\n    \"int8\": \"int8_t\",\n    \"uint8\": \"uint8_t\",\n    \"int16\": \"int16_t\",\n    \"uint16\": \"uint16_t\",\n    \"int32\": \"int32_t\",\n    \"uint32\": \"uint32_t\",\n    \"float32\": \"float\",\n}\n\nAOT_SUCCESS_TOKEN = \"AOT_TEST_SUCCESS\"\nAOT_FAILURE_TOKEN = \"AOT_TEST_FAILURE\"\n\n\nclass AOTTestModel(NamedTuple):\n    \"\"\"Class to describe a model under test\n\n    Parameters\n    ----------\n    module: tvm.IRModule\n        IRModule to generate AOT executor for\n    inputs: Dict[str, np.array]\n        Dict of input names to value arrays\n    outputs: List[np.array]\n        Dict of output names to value arrays\n    output_tolerance: Optional[Union[int, float]]\n        Allowed tolerance of the output\n    name: str\n        Name to use for this model\n    params: Optional[Dict[str, np.array]]\n        Dict of parameter names to value arrays\n    extra_memory_in_bytes: int\n        Extra memory to allocate after planned memory\n    \"\"\"\n\n    module: tvm.IRModule\n    inputs: Dict[str, np.array]\n    outputs: Dict[str, np.array]\n    output_tolerance: Optional[Union[int, float]] = None\n    name: str = \"default\"\n    params: Optional[Dict[str, np.array]] = None\n    extra_memory_in_bytes: int = 0\n\n\nclass AOTCompiledTestModel(NamedTuple):\n    \"\"\"A compiled AOTTestModel with associated module\n\n    Parameters\n    ----------\n    model: AOTTestModel\n        Input model to be compiled\n    module: tvm.runtime.Module\n        The compiled Module for the associated AOTTestModel\n    \"\"\"\n\n    model: AOTTestModel\n    executor_factory: tvm.relay.backend.executor_factory.AOTExecutorFactoryModule\n\n\nclass AOTDataLinkage(NamedTuple):\n    \"\"\"A compiled AOTTestModel with associated module\n\n    Parameters\n    ----------\n    section: str\n        Named section to place data into\n    alignment: int\n        Section alignment\n    \"\"\"\n\n    section: str\n    alignment: int\n\n\nclass AOTTestRunner(NamedTuple):\n    \"\"\"Class to describe a test runner for AOT code\n\n    Parameters\n    ----------\n    makefile: str\n        Premade Makefile to use from the AOT test folder\n    prologue: str\n        Code to prepend to the main function\n    epilogue: str\n        Code to append to the main function\n    includes: List[str]\n        Additional includes required to run the AOT test runner\n    parameters: Dict[str, str]\n        Additional parameters to pass to the make command\n    pass_config: Dict[str, Any]\n        Additional pass configuration when building the model\n    \"\"\"\n\n    makefile: str = \"default\"\n    prologue: str = \"\"\n    epilogue: str = \"\"\n    includes: List[str] = []\n    parameters: Dict[str, str] = {}\n    pass_config: Dict[str, Any] = {}\n\n\ndef _subprocess_check_log_output(cmd, cwd, logfile):\n    \"\"\"\n    This method runs a process and logs the output to both a log file and stdout\n    \"\"\"\n    _LOG.info(\"Execute (%s): %s\", cwd, cmd)\n    cmd_base = cmd[0] if isinstance(cmd, (list, tuple)) else cmd.split(\" \", 1)[0]\n    proc = subprocess.Popen(\n        cmd,\n        cwd=cwd,\n        shell=True,\n        bufsize=0,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n        encoding=\"utf-8\",\n    )\n    stdout = \"\"\n    with open(logfile, \"a\") as f:\n        msg = (\n            \"\\n\"\n            + \"-\" * 80\n            + f\"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: Execute ({cwd}): {cmd}\\n\"\n            + \"-\" * 80\n        )\n        f.write(msg)\n        stdout += msg + \"\\n\"\n        while True:\n            data = proc.stdout.readline()\n            stdout += data\n            _LOG.debug(\"%s: %s\", cmd_base, data.rstrip(\"\\n\"))\n            f.write(data)\n\n            # process is done if there is no data and the result is valid\n            if not data:  # EOF\n                break\n\n    proc.wait()\n    if proc.returncode != 0:\n        raise RuntimeError(f\"Subprocess failed: {cmd}\\nstdout:\\n{stdout}\")\n\n\ndef _mangle_name(mod_name, name):\n    mod_name = mangle_module_name(mod_name)\n    return mod_name + \"_\" + name\n\n\n# TODO: Move to linker script with list of symbols rather than coding into source\ndef _emit_data_linkage(output_file, data_linkage):\n    if data_linkage is not None:\n        output_file.write(\n            f'__attribute__((section(\"{data_linkage.section}\"), '\n            f\"aligned({data_linkage.alignment}))) \"\n        )\n\n\ndef _emit_main_prologue(\n    main_file,\n    custom_prologue,\n    workspace_bytes,\n    data_linkage,\n    compiled_models,\n    interface_api,\n    use_stack_allocator=True,\n):\n    if use_stack_allocator:\n        workspace_define = f\"#define WORKSPACE_SIZE ({workspace_bytes}\"\n        if interface_api == \"c\":\n            for compiled_model in compiled_models:\n                model = compiled_model.model\n                workspace_define += f\" + TVMGEN_{model.name.upper()}_WORKSPACE_SIZE\"\n        # Add TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES because of memory alignment.\n        workspace_define += \" + TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)\\n\"\n        main_file.write(workspace_define)\n        _emit_data_linkage(main_file, data_linkage)\n        main_file.write(\"static uint8_t g_aot_memory[WORKSPACE_SIZE];\\n\")\n        main_file.write(\"tvm_workspace_t app_workspace;\\n\")\n        main_file.write(\n            \"\"\"\\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n    return StackMemoryManager_Allocate(&app_workspace, num_bytes, out_ptr);\n}\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n    return StackMemoryManager_Free(&app_workspace,ptr);\n}\n        \"\"\"\n        )\n    else:\n        # An implementation is not needed for these if the stack allocator is not used\n        main_file.write(\n            \"\"\"\\n\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n    return kTvmErrorFunctionCallNotImplemented;\n}\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n    return kTvmErrorFunctionCallNotImplemented;\n}\n            \"\"\"\n        )\n    main_file.write(\n        \"\"\"\\n\nvoid TVMPlatformAbort(tvm_crt_error_t code) { exit(-1); }\nvoid TVMLogf(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  vfprintf(stdout, msg, args);\n  va_end(args);\n}\\n\nTVM_DLL int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) {}\nint main(){\\n\n    \"\"\"\n    )\n    main_file.write(custom_prologue)\n\n\ndef _emit_main_data(main_file, input_map, output_map, mod_name):\n    for key in input_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(\n            f'#include \"{_mangle_name(mod_name,\"input_data\")}_{sanitized_tensor_name}.h\"\\n'\n        )\n\n    for key in output_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(\n            f'#include \"{_mangle_name(mod_name,\"expected_output_data\")}_'\n            f'{sanitized_tensor_name}.h\"\\n'\n            f'#include \"{_mangle_name(mod_name,\"output_data\")}_'\n            f'{sanitized_tensor_name}.h\"\\n'\n        )\n\n\ndef _emit_main_device_structs(main_file, devices, mod_name):\n    if devices:\n        main_file.write(\n            f\"struct {_mangle_name(mod_name, 'devices')} {_mangle_name(mod_name, 'devices')} = {{\"\n        )\n        for device in devices:\n            main_file.write(f\"\\t.{device} = {device},\\n\")\n        main_file.write(\"};\\n\")\n\n\ndef _emit_main_workspace_pool_structs(main_file, workspace_pool_names, mod_name):\n    if workspace_pool_names and len(workspace_pool_names) > 0:\n        main_file.write(\n            f\"struct {_mangle_name(mod_name, 'workspace_pools')} \"\n            f\"{_mangle_name(mod_name, 'workspace_pools')} = {{\"\n        )\n        for workspace_pool_name in workspace_pool_names.keys():\n            main_file.write(\n                f\"\\t.{workspace_pool_name} = {workspace_pool_names[workspace_pool_name]}\"\n                f\"{workspace_pool_name},\\n\"\n            )\n        main_file.write(\"};\\n\")\n\n\ndef _emit_main_data_structs(main_file, input_map, output_map, mod_name):\n    main_file.write(\n        f\"struct {_mangle_name(mod_name, 'inputs')} {_mangle_name(mod_name, 'inputs')} = {{\"\n    )\n    for key in input_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(\n            f\"\\t.{sanitized_tensor_name} = \"\n            f\"{_mangle_name(mod_name, 'input_data')}_{sanitized_tensor_name},\\n\"\n        )\n    main_file.write(\"};\\n\")\n\n    main_file.write(\n        f\"struct {_mangle_name(mod_name, 'outputs')} {_mangle_name(mod_name, 'outputs')} = {{\"\n    )\n    for key in output_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(\n            f\"\\t.{sanitized_tensor_name} = {_mangle_name(mod_name, 'output_data')}_\"\n            f\"{sanitized_tensor_name},\\n\"\n        )\n    main_file.write(\"};\\n\")\n\n\ndef _emit_main_data_setup(main_file, input_map, output_map, mod_name):\n    num_outputs = len(output_map)\n    num_inputs = len(input_map)\n    main_file.write(f'void* {_mangle_name(mod_name,\"inputs\")}[{num_inputs}] = {{ ')\n    for key in input_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(f'{_mangle_name(mod_name,\"input_data\")}_{sanitized_tensor_name}, ')\n    main_file.write(\"};\\n\")\n    main_file.write(f'void* {_mangle_name(mod_name,\"outputs\")}[{num_outputs}]  = {{ ')\n    for key in output_map:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        main_file.write(f'{_mangle_name(mod_name, \"output_data\")}_{sanitized_tensor_name}, ')\n    main_file.write(\"};\\n\")\n\n\ndef _emit_main_c_interface_call(\n    main_file, devices, workspace_pool_names, mod_name, use_workspace_io\n):\n    sub_strings = list()\n    sub_strings.append(f'{_mangle_name(mod_name,\"run\")}(')\n    if not use_workspace_io:\n        sub_strings.append(f'&{_mangle_name(mod_name,\"inputs\")}, ')\n        sub_strings.append(f'&{_mangle_name(mod_name,\"outputs\")}, ')\n    if workspace_pool_names:\n        sub_strings.append(f'&{_mangle_name(mod_name,\"workspace_pools\")}, ')\n    if devices:\n        sub_strings.append(f'&{_mangle_name(mod_name,\"devices\")}, ')\n    # Removing the last two characters that is a comma and a space\n    sub_strings[-1] = sub_strings[-1][:-2]\n    # Adding brackets and newline instead\n    sub_strings[-1] = sub_strings[-1] + \");\\n\"\n\n    main_file_string = \"\".join(sub_strings)\n    main_file.write(main_file_string)\n\n\ndef _emit_main_fake_packed_values(main_file):\n    main_file.write(\n        \"\"\"\n    static DLDevice fake_device = {kDLCPU, 0};\n    static int64_t fake_dims = 0;\n    static int64_t fake_shape = {0};\n    \"\"\"\n    )\n\n\ndef _emit_main_packed_call(main_file, input_map, output_list, mod_name):\n    tensors_name = _mangle_name(mod_name, \"tensors\")\n    values_name = _mangle_name(mod_name, \"values\")\n    typeids_name = _mangle_name(mod_name, \"typeids\")\n\n    def fake_tensor(source, source_index, packed_index):\n        main_file.write(\n            f\"\"\"\n        {tensors_name}[{packed_index}].device = fake_device;\n        {tensors_name}[{packed_index}].data = {source}[{source_index}];\n        {tensors_name}[{packed_index}].shape = &fake_shape;\n        {tensors_name}[{packed_index}].ndim = fake_dims;\n        {tensors_name}[{packed_index}].byte_offset = 0;\n        {tensors_name}[{packed_index}].strides = NULL;\n        {values_name}[{packed_index}].v_handle = &{tensors_name}[{packed_index}];\n        \"\"\"\n        )\n\n    num_outputs = len(output_list)\n    num_inputs = len(input_map)\n    num_tensors = num_inputs + num_outputs\n    main_file.write(\n        f\"\"\"\n    DLTensor {tensors_name}[{num_tensors}];\n    TVMValue {values_name}[{num_tensors}];\n    int32_t {typeids_name}[{num_tensors}];\n    \"\"\"\n    )\n\n    for i in range(0, num_inputs):\n        fake_tensor(_mangle_name(mod_name, \"inputs\"), i, i)\n    for i in range(0, num_outputs):\n        fake_tensor(_mangle_name(mod_name, \"outputs\"), i, i + num_inputs)\n\n    main_file.write(\n        f'{_mangle_name(mod_name, \"run\")}({values_name}, {typeids_name}, 0, NULL, 0, NULL);\\n'\n    )\n    main_file.write(\"\\n\")\n\n\ndef _emit_main_compare(main_file, outputs, output_tolerance, mod_name, use_interface_c=False):\n    for key in outputs:\n        sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n        expected_data_name = _mangle_name(mod_name, f\"expected_output_data_{sanitized_tensor_name}\")\n        is_float_dtype = outputs[key].dtype == \"float32\"\n\n        comparison_function = \"abs\"\n        tolerance = output_tolerance or 0\n        if is_float_dtype:\n            comparison_function = \"fabs\"\n            tolerance = output_tolerance or 0.001\n\n        data_length_var_name = (\n            _mangle_name(mod_name, f\"output_data_{sanitized_tensor_name}\") + \"_len\"\n        )\n        if use_interface_c:\n            c_type = NP_TYPE_TO_C[str(outputs[key].dtype)]\n            actual_data_name = f\"(({c_type}*)\" + _mangle_name(\n                mod_name, f\"outputs.{sanitized_tensor_name})\"\n            )\n        else:\n            actual_data_name = _mangle_name(mod_name, f\"output_data_{sanitized_tensor_name}\")\n        main_file.write(\n            f\"for (int i = 0; i<{data_length_var_name}; i++) {{\\n\"\n            f\"\\tif ({comparison_function}({actual_data_name}[i]-\"\n            f\"{expected_data_name}[i]) > {tolerance}) {{\\n\"\n            f'\\t\\tprintf(\"{AOT_FAILURE_TOKEN}\\\\n\");\\n'\n            f\"\\t\\treturn -1;\\n\"\n            f\"\\t}}\\n\"\n            f\"}}\"\n        )\n\n\ndef _emit_main_init_memory_manager(main_file):\n    main_file.write(\"StackMemoryManager_Init(&app_workspace, g_aot_memory, WORKSPACE_SIZE);\")\n    main_file.write(\"\\n\")\n\n\ndef _emit_main_epilogue(main_file, custom_epilogue):\n    main_file.write(custom_epilogue)\n    main_file.write(f'printf(\"{AOT_SUCCESS_TOKEN}\\\\n\");')\n    main_file.write(\"return 0;\")\n    main_file.write(\"}\\n\")\n\n\ndef _emit_main_common_includes(main_file, custom_includes):\n    main_file.write(\"#include <stdio.h>\\n\")\n    main_file.write(\"#include <stdarg.h>\\n\")\n    main_file.write(\"#include <stdlib.h>\\n\")\n    main_file.write(\"#include <math.h>\\n\")\n    main_file.write('#include \"tvm/runtime/c_runtime_api.h\"\\n')\n    main_file.write('#include \"tvm/runtime/crt/stack_allocator.h\"\\n')\n    for include in custom_includes:\n        main_file.write(f'#include \"{include}\"\\n')\n\n\ndef _emit_main_micro_include(main_file, mod_name):\n    main_file.write(f\"#include <{mangle_module_name(mod_name)}.h>\\n\")\n\n\ndef _create_main(\n    test_name,\n    compiled_models,\n    output_path,\n    custom_includes,\n    custom_prologue,\n    custom_epilogue,\n    data_linkage,\n    interface_api,\n    workspace_bytes,\n    use_stack_allocator=True,\n    use_workspace_io=False,\n):\n    file_path = pathlib.Path(f\"{output_path}/\" + test_name).resolve()\n    # create header file\n    raw_path = file_path.with_suffix(\".c\").resolve()\n    with open(raw_path, \"w\") as main_file:\n        _emit_main_common_includes(main_file, custom_includes)\n\n        if interface_api == \"c\":\n            for compiled_model in compiled_models:\n                model = compiled_model.model\n                _emit_main_micro_include(main_file, model.name)\n        for compiled_model in compiled_models:\n            model = compiled_model.model\n            _emit_main_data(main_file, model.inputs, model.outputs, model.name)\n\n        _emit_main_prologue(\n            main_file,\n            custom_prologue,\n            workspace_bytes,\n            data_linkage,\n            compiled_models,\n            interface_api,\n            use_stack_allocator,\n        )\n        if use_stack_allocator:\n            _emit_main_init_memory_manager(main_file)\n\n        if interface_api == \"c\":\n            for compiled_model in compiled_models:\n                model = compiled_model.model\n                executor_codegen_metadata = (\n                    compiled_model.executor_factory.executor_codegen_metadata\n                )\n                devices = compiled_model.executor_factory.get_devices()\n                workspace_pool_names = {}\n                if executor_codegen_metadata.pool_inputs:\n                    workspace_pool_names = {\n                        allocated_pool.pool_info.pool_name: \"&\"\n                        if isinstance(\n                            allocated_pool.pool_info, tvm.ir.memory_pools.ConstantPoolInfo\n                        )\n                        else \"\"\n                        for allocated_pool in dict(executor_codegen_metadata.pool_inputs).values()\n                        if not allocated_pool.pool_info.is_internal\n                    }\n                _emit_main_device_structs(main_file, devices, model.name)\n                if not use_workspace_io:\n                    _emit_main_workspace_pool_structs(main_file, workspace_pool_names, model.name)\n                    _emit_main_data_structs(main_file, model.inputs, model.outputs, model.name)\n                _emit_main_c_interface_call(\n                    main_file,\n                    devices,\n                    list(workspace_pool_names.keys()),\n                    model.name,\n                    use_workspace_io,\n                )\n        else:\n            _emit_main_fake_packed_values(main_file)\n            for compiled_model in compiled_models:\n                model = compiled_model.model\n                _emit_main_data_setup(main_file, model.inputs, model.outputs, model.name)\n                _emit_main_packed_call(main_file, model.inputs, model.outputs, model.name)\n\n        for compiled_model in compiled_models:\n            model = compiled_model.model\n            _emit_main_compare(\n                main_file, model.outputs, model.output_tolerance, model.name, interface_api == \"c\"\n            )\n        _emit_main_epilogue(main_file, custom_epilogue)\n\n\ndef _create_header_file(tensor_name, npy_data, output_path, data_linkage):\n    \"\"\"\n    This method generates a header file containing the data contained in the numpy array provided.\n    It is used to capture the tensor data (for both inputs and expected outputs)\n    to be bundled into the standalone application.\n    \"\"\"\n    file_path = pathlib.Path(f\"{output_path}/\" + tensor_name).resolve()\n    # create header file\n    raw_path = file_path.with_suffix(\".h\").resolve()\n    with open(raw_path, \"w\") as header_file:\n        header_file.write(\"#include <stddef.h>\\n\")\n        header_file.write(\"#include <stdint.h>\\n\")\n        header_file.write(\"#include <dlpack/dlpack.h>\\n\")\n        header_file.write(f\"const size_t {tensor_name}_len = {npy_data.size};\\n\")\n\n        _emit_data_linkage(header_file, data_linkage)\n\n        header_file.write(f\"{NP_TYPE_TO_C[str(npy_data.dtype)]} {tensor_name}[] =\")\n\n        header_file.write(\"{\")\n        for i in np.ndindex(npy_data.shape):\n            header_file.write(f\"{npy_data[i]}, \")\n        header_file.write(\"};\\n\\n\")\n\n\ndef convert_to_relay(tflite_model_buf, bind_params_by_name=True):\n    \"\"\"Convert a tflite model buffer in a Relay module\"\"\"\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite.Model  # pylint: disable=import-outside-toplevel\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite  # pylint: disable=import-outside-toplevel\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except ImportError:\n        raise ImportError(\"The tflite package must be installed\")\n\n    mod, params = relay.frontend.from_tflite(tflite_model)\n    if bind_params_by_name:\n        mod[\"main\"] = relay.build_module.bind_params_by_name(mod[\"main\"], params)\n    return mod, params\n\n\ndef compile_models(\n    models: Union[List[AOTTestModel], AOTTestModel],\n    interface_api: str,\n    use_unpacked_api: bool,\n    workspace_byte_alignment: int = 8,\n    constant_byte_alignment: int = 8,\n    enable_op_fusion: bool = True,\n    pass_config: Dict[str, Any] = None,\n    use_runtime_executor: bool = True,\n    target: tvm.target.Target = tvm.target.Target(\"c\"),\n    workspace_memory_pools=None,\n    constant_memory_pools=None,\n    schedule_name: str = None,\n) -> List[AOTCompiledTestModel]:\n    \"\"\"\n    This method generates runtime.Modules for the tests\n    \"\"\"\n    if not isinstance(models, list):\n        models = [models]\n\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": workspace_byte_alignment,\n            \"constant-byte-alignment\": constant_byte_alignment,\n            \"interface-api\": interface_api,\n            \"unpacked-api\": use_unpacked_api,\n        },\n    )\n\n    config = {\"tir.disable_vectorize\": True}\n    if pass_config:\n        config = {**config, **pass_config}\n    if not enable_op_fusion:\n        config[\"relay.FuseOps.max_depth\"] = 1\n\n    compiled_mods = list()\n    for model in models:\n        if schedule_name:\n            # Testing with deterministic schedule\n            task_list = autotvm.task.extract_from_program(\n                model.module, target=target, params=model.params\n            )\n            with tvm.autotvm.apply_fixed_config(task_list, schedule_name):\n                with tvm.transform.PassContext(opt_level=3, config=config):\n                    if use_runtime_executor:\n                        executor_factory = tvm.relay.build(\n                            model.module,\n                            target,\n                            executor=executor,\n                            runtime=runtime,\n                            workspace_memory_pools=workspace_memory_pools,\n                            constant_memory_pools=constant_memory_pools,\n                            params=model.params,\n                            mod_name=model.name,\n                        )\n                        compiled_mods.append(\n                            AOTCompiledTestModel(model=model, executor_factory=executor_factory)\n                        )\n                    else:\n                        executor_factory = tvm.relay.build(\n                            model.module,\n                            tvm.target.Target(target, host=target),\n                            params=model.params,\n                            mod_name=model.name,\n                        )\n                        compiled_mods.append(\n                            AOTCompiledTestModel(model=model, executor_factory=executor_factory)\n                        )\n        else:\n            with tvm.transform.PassContext(opt_level=3, config=config):\n                # TODO(Mousius) - Remove once executor/runtime are fully removed from Target\n                if use_runtime_executor:\n                    executor_factory = tvm.relay.build(\n                        model.module,\n                        target,\n                        executor=executor,\n                        runtime=runtime,\n                        workspace_memory_pools=workspace_memory_pools,\n                        constant_memory_pools=constant_memory_pools,\n                        params=model.params,\n                        mod_name=model.name,\n                    )\n                    compiled_mods.append(\n                        AOTCompiledTestModel(model=model, executor_factory=executor_factory)\n                    )\n                else:\n                    executor_factory = tvm.relay.build(\n                        model.module,\n                        tvm.target.Target(target, host=target),\n                        params=model.params,\n                        mod_name=model.name,\n                    )\n                    compiled_mods.append(\n                        AOTCompiledTestModel(model=model, executor_factory=executor_factory)\n                    )\n    return compiled_mods\n\n\ndef run_and_check(\n    models: List[AOTCompiledTestModel],\n    runner: AOTTestRunner,\n    interface_api: str,\n    debug_calculated_workspaces=False,\n    workspace_byte_alignment=8,\n    constant_byte_alignment=8,\n    data_linkage: AOTDataLinkage = None,\n    test_dir: str = None,\n    verbose: bool = False,\n    use_workspace_io: bool = False,\n):\n    \"\"\"\n    This method uses the original test data and compiled runtime.Modules\n    to run in the test runner to verify the results.\n    \"\"\"\n\n    def run_and_check_body(base_path):\n        cflags = (\n            f\"-DTVM_RUNTIME_ALLOC_ALIGNMENT_BYTES={workspace_byte_alignment} \"\n            f\" -DTVM_RUNTIME_CONST_ALLOC_ALIGNMENT_BYTES={constant_byte_alignment} \"\n        )\n        # The calculated workspaces will not account for stack allocator tags used for debugging\n        if debug_calculated_workspaces:\n            cflags += \"-DTVM_CRT_STACK_ALLOCATOR_ENABLE_LIFO_CHECK \"\n\n        base_path = os.path.abspath(base_path)\n        build_path = os.path.join(base_path, \"build\")\n        os.makedirs(build_path, exist_ok=True)\n\n        include_path = os.path.join(base_path, \"include\")\n        os.mkdir(include_path)\n        crt_root = tvm.micro.get_standalone_crt_dir()\n        shutil.copy2(\n            os.path.join(crt_root, \"template\", \"crt_config-template.h\"),\n            os.path.join(include_path, \"crt_config.h\"),\n        )\n\n        workspace_bytes = 0\n        for compiled_model in models:\n            model = compiled_model.model\n            tar_file = os.path.join(base_path, f\"{model.name}.tar\")\n            export_model_library_format(compiled_model.executor_factory, tar_file)\n            t = tarfile.open(tar_file)\n            t.extractall(base_path)\n\n            # Interface C APIs does not need compiler generated\n            # workspace to generate the test application, because\n            # workspace size is codegen'd as a macro to\n            # tvmgen_<model_name>.h.\n            if interface_api != \"c\":\n                workspace_bytes += mlf_extract_workspace_size_bytes(tar_file)\n\n            workspace_bytes += model.extra_memory_in_bytes\n            for key in model.inputs:\n                sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n                _create_header_file(\n                    f'{_mangle_name(model.name, \"input_data\")}_{sanitized_tensor_name}',\n                    model.inputs[key],\n                    include_path,\n                    data_linkage,\n                )\n\n            for key in model.outputs:\n                sanitized_tensor_name = re.sub(r\"\\W\", \"_\", key)\n                _create_header_file(\n                    f'{_mangle_name(model.name, \"output_data\")}_{sanitized_tensor_name}',\n                    np.zeros(model.outputs[key].shape, model.outputs[key].dtype),\n                    include_path,\n                    data_linkage,\n                )\n                _create_header_file(\n                    f'{_mangle_name(model.name, \"expected_output_data\")}_{sanitized_tensor_name}',\n                    model.outputs[key],\n                    include_path,\n                    data_linkage,\n                )\n\n        use_usmp = runner.pass_config.get(\"tir.usmp.enable\", False)\n        # We only need the stack allocator if USMP is not used\n        use_stack_allocator = not use_usmp\n\n        _create_main(\n            \"test.c\",\n            models,\n            build_path,\n            runner.includes,\n            runner.prologue,\n            runner.epilogue,\n            data_linkage,\n            interface_api,\n            workspace_bytes,\n            use_stack_allocator,\n            use_workspace_io,\n        )\n\n        # Verify that compiles fine\n        file_dir = os.path.dirname(os.path.abspath(__file__))\n        makefile_dir = os.path.join(file_dir, \"../../../tests/python/relay/aot\")\n        codegen_path = os.path.join(base_path, \"codegen\")\n        makefile = os.path.join(makefile_dir, f\"{runner.makefile}.mk\")\n        fvp_dir = \"/opt/arm/FVP_Corstone_SSE-300/models/Linux64_GCC-6.4/\"\n        # TODO(@grant-arm): Remove once ci_cpu docker image has been updated to FVP_Corstone_SSE\n        if not os.path.isdir(fvp_dir):\n            fvp_dir = \"/opt/arm/FVP_Corstone_SSE-300_Ethos-U55/models/Linux64_GCC-6.4/\"\n        custom_params = \" \".join(\n            [f\" {param}='{value}'\" for param, value in runner.parameters.items()]\n        )\n        make_command = (\n            f\"make -f {makefile} build_dir={build_path}\"\n            + f\" CFLAGS='{cflags}'\"\n            + f\" TVM_ROOT={file_dir}/../../..\"\n            + f\" AOT_TEST_ROOT={makefile_dir}\"\n            + f\" CODEGEN_ROOT={codegen_path}\"\n            + f\" STANDALONE_CRT_DIR={tvm.micro.get_standalone_crt_dir()}\"\n            + f\" FVP_DIR={fvp_dir}\"\n            + custom_params\n        )\n\n        compile_log_path = os.path.join(build_path, \"test_compile.log\")\n        compile_command = f\"{make_command} aot_test_runner\"\n        if verbose:\n            print(\"Compile command:\\n\", compile_command)\n        _subprocess_check_log_output(compile_command, \".\", compile_log_path)\n\n        # Verify that runs fine\n        run_log_path = os.path.join(build_path, \"test_run.log\")\n        run_command = f\"{make_command} run\"\n        if verbose:\n            print(\"Run command:\\n\", run_command)\n\n        # TODO(lhutton1) This is a quick and dirty work around to help temporarily reduce\n        # the flakyness of the tests. Will remove once #10300 and #10314 are resolved.\n        try:\n            _subprocess_check_log_output(run_command, build_path, run_log_path)\n        except RuntimeError as err:\n            print(\"Failed to run the module, having a second attempt...\", file=sys.stderr)\n            print(err, file=sys.stderr)\n            _subprocess_check_log_output(run_command, build_path, run_log_path)\n\n        with open(run_log_path) as run_log:\n            assert AOT_SUCCESS_TOKEN in run_log.read()\n\n    if test_dir is None:\n        tmpdir = utils.tempdir()\n        run_and_check_body(os.path.join(tmpdir.path, \"test\"))\n    else:\n        run_and_check_body(test_dir)\n\n\ndef compile_and_run(\n    models: Union[List[AOTTestModel], AOTTestModel],\n    runner: AOTTestRunner,\n    interface_api: str,\n    use_unpacked_api: bool,\n    debug_calculated_workspaces: bool = False,\n    workspace_byte_alignment: int = 8,\n    constant_byte_alignment: int = 8,\n    enable_op_fusion: bool = True,\n    data_linkage: AOTDataLinkage = None,\n    use_runtime_executor: bool = True,\n    target: Union[str, tvm.target.Target, List[tvm.target.Target]] = \"c\",\n    target_opts: Dict = None,\n    test_dir: str = None,\n    verbose: bool = False,\n    schedule_name: str = None,\n):\n    \"\"\"This is a wrapper API to compile and run models as test for AoT\n\n    Parameters\n    ----------\n    test_dir : str\n        This path will contain build, codegen, include directories\n    verbose: bool\n        Prints commands to build and run AOT test runner\n    \"\"\"\n\n    if target_opts:\n        for key, val in target_opts.items():\n            target += f\" {key}={val}\"\n\n    if isinstance(target, str):\n        target = tvm.target.Target(target)\n\n    compiled_test_mods = compile_models(\n        models=models,\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        workspace_byte_alignment=workspace_byte_alignment,\n        constant_byte_alignment=constant_byte_alignment,\n        enable_op_fusion=enable_op_fusion,\n        pass_config=runner.pass_config,\n        use_runtime_executor=use_runtime_executor,\n        target=target,\n        schedule_name=schedule_name,\n    )\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=runner,\n        interface_api=interface_api,\n        debug_calculated_workspaces=debug_calculated_workspaces,\n        workspace_byte_alignment=workspace_byte_alignment,\n        constant_byte_alignment=constant_byte_alignment,\n        data_linkage=data_linkage,\n        test_dir=test_dir,\n        verbose=verbose,\n    )\n\n\ndef generate_ref_data(mod, input_data, params=None, target=\"llvm\"):\n    \"\"\"Generate reference data through executing the relay module\"\"\"\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lib = relay.build(mod, target=target, params=params)\n\n    lib_name = \"mod.so\"\n    temp = utils.tempdir()\n    lib_path = temp.relpath(lib_name)\n    lib.export_library(lib_path)\n    lib = tvm.runtime.load_module(lib_path)\n    grt_mod = graph_executor.GraphModule(lib[\"default\"](tvm.cpu()))\n    grt_mod.set_input(**input_data)\n    grt_mod.run()\n    output_count = grt_mod.get_num_outputs()\n    out = [grt_mod.get_output(i).numpy() for i in range(output_count)]\n    if isinstance(mod, tvm.relay.Function):\n        main = mod\n    else:\n        main = mod[\"main\"]\n    if main.attrs is None or main.attrs[\"output_tensor_names\"] is None:\n        output_tensor_names = (\n            [\"output\"] if output_count == 1 else [f\"output{i}\" for i in range(output_count)]\n        )\n    else:\n        output_tensor_names = main.attrs[\"output_tensor_names\"]\n\n    return dict(zip(output_tensor_names, out))\n\n\ndef create_relay_module_and_inputs_from_tflite_file(tflite_model_file, bind_params_by_name=True):\n    \"\"\"A helper function to create a Relay IRModule with inputs\n    and params from a tflite file\"\"\"\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    mod, params = convert_to_relay(tflite_model_buf, bind_params_by_name)\n\n    inputs = dict()\n    for param in mod[\"main\"].params:\n        name = str(param.name_hint)\n        data_shape = [int(i) for i in param.type_annotation.shape]\n        dtype = str(param.type_annotation.dtype)\n        if np.issubdtype(dtype, np.floating):\n            # Since np.random.uniform only allows the ranges of float32,\n            # at first float16 is used and scaled afterwards, if necessary.\n            in_min, in_max = (np.finfo(\"float16\").min, np.finfo(\"float16\").max)\n            data = np.random.uniform(low=in_min, high=in_max, size=data_shape).astype(dtype)\n            scale = np.finfo(dtype).min / np.finfo(\"float16\").min\n            data *= scale\n        elif np.issubdtype(dtype, np.integer):\n            in_min, in_max = (np.iinfo(dtype).min, np.iinfo(dtype).max)\n            data = np.random.randint(in_min, high=in_max, size=data_shape, dtype=dtype)\n        else:\n            raise TypeError(f\"Type {dtype} not supported\")\n        inputs[name] = data\n\n    return mod, inputs, params\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/auto_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-function-docstring\n\"\"\"Common functions for auto_scheduler test cases\"\"\"\nimport tvm\nfrom tvm import auto_scheduler, te, topi\nfrom tvm.topi.nn.winograd_util import winograd_transform_matrices\nfrom tvm.topi.utils import get_const_tuple\n\n\n@auto_scheduler.register_workload\ndef matmul_auto_scheduler_test(N, M, K):\n    A = te.placeholder((N, K), name=\"A\")\n    B = te.placeholder((K, M), name=\"B\")\n    k = te.reduce_axis((0, K), name=\"k\")\n    C = te.compute(\n        (N, M),\n        lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]),\n        name=\"C\",\n        attrs={\"layout_free_placeholders\": [B]},\n    )\n    return [A, B, C]\n\n\n@auto_scheduler.register_workload\ndef double_matmul_auto_scheduler_test(N):\n    A = te.placeholder((N, N), name=\"A\", dtype=\"float32\")\n    B = te.placeholder((N, N), name=\"B\", dtype=\"float32\")\n    C = te.placeholder((N, N), name=\"C\", dtype=\"float32\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    D = te.compute((N, N), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"D\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    E = te.compute((N, N), lambda i, j: te.sum(D[i][k] * C[k][j], axis=[k]), name=\"E\")\n\n    return [A, B, C, E]\n\n\n@auto_scheduler.register_workload\ndef parallel_matmul_auto_scheduler_test(N):\n    \"\"\"Two parallel matmuls with shared A.\"\"\"\n    A = te.placeholder((N, N), name=\"A\", dtype=\"float32\")\n    B = te.placeholder((N, N), name=\"B\", dtype=\"float32\")\n    C = te.placeholder((N, N), name=\"C\", dtype=\"float32\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    D = te.compute((N, N), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"D\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    E = te.compute((N, N), lambda i, j: te.sum(A[i][k] * C[k][j], axis=[k]), name=\"E\")\n\n    return [A, B, C, D, E]\n\n\n# Test for register_workload with different name\n@auto_scheduler.register_workload(\"matmul_auto_scheduler_test_rename_1\")\ndef matmul_auto_scheduler_test_rename_0(N, M, K):\n    A = te.placeholder((N, K), name=\"A\")\n    B = te.placeholder((K, M), name=\"B\")\n    k = te.reduce_axis((0, K), name=\"k\")\n    C = te.compute((N, M), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n    return [A, B, C]\n\n\n@auto_scheduler.register_workload\ndef conv2d_nchw_bn_relu_auto_scheduler_test(\n    N, H, W, CI, CO, kernel_size, strides, padding, dilation=1\n):\n    data = te.placeholder((N, CI, H, W), name=\"Data\")\n    kernel = te.placeholder((CO, CI, kernel_size, kernel_size), name=\"Kernel\")\n    bias = te.placeholder((CO, 1, 1), name=\"Bias\")\n    bn_scale = te.placeholder((CO, 1, 1), name=\"Bn_scale\")\n    bn_offset = te.placeholder((CO, 1, 1), name=\"Bn_offset\")\n\n    OH = (H + 2 * padding - (kernel_size - 1) * dilation - 1) // strides + 1\n    OW = (W + 2 * padding - (kernel_size - 1) * dilation - 1) // strides + 1\n\n    conv = topi.nn.conv2d_nchw(data, kernel, strides, padding, dilation)\n    conv = te.compute(\n        (N, CO, OH, OW), lambda i, j, k, l: conv[i, j, k, l] + bias[j, 0, 0], name=\"Bias_add\"\n    )\n    conv = te.compute(\n        (N, CO, OH, OW), lambda i, j, k, l: conv[i, j, k, l] * bn_scale[j, 0, 0], name=\"Bn_mul\"\n    )\n    conv = te.compute(\n        (N, CO, OH, OW), lambda i, j, k, l: conv[i, j, k, l] + bn_offset[j, 0, 0], name=\"Bn_add\"\n    )\n    out = topi.nn.relu(conv)\n\n    return [data, kernel, bias, bn_offset, bn_scale, out]\n\n\n@auto_scheduler.register_workload\ndef max_pool2d_auto_scheduler_test(N, H, W, CI, padding):\n    data = te.placeholder((N, CI, H, W), name=\"Data\")\n    out = topi.nn.pool2d(data, [2, 2], [1, 1], [1, 1], [padding, padding, padding, padding], \"max\")\n\n    return [data, out]\n\n\n@auto_scheduler.register_workload\ndef min_nm_auto_scheduler_test(N, M):\n    A = te.placeholder((N, M), name=\"A\")\n    B = topi.min(A, axis=-1)\n\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef softmax_nm_auto_scheduler_test(N, M):\n    A = te.placeholder((N, M), name=\"A\")\n    B = topi.nn.softmax(A, axis=1)\n\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef softmax_abcd_auto_scheduler_test(a, b, c, d):\n    A = te.placeholder((a, b, c, d), name=\"A\")\n    B = topi.nn.softmax(A, axis=-1)\n\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef invalid_compute_definition():\n    A = te.placeholder((10, 10), name=\"A\")\n    # The names of the following two iterators are the same.\n    # This is invalid.\n    r1 = te.reduce_axis((0, 2), name=\"r1\")\n    r2 = te.reduce_axis((0, 2), name=\"r1\")\n    B = te.compute((10,), lambda i: te.sum(A[i][r1 + r2], axis=[r1, r2]), name=\"B\")\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef zero_rank_reduce_auto_scheduler_test(N):\n    A = tvm.te.placeholder((N,), name=\"A\")\n    k = tvm.te.reduce_axis((0, N), name=\"k\")\n    B = tvm.te.compute((), lambda: tvm.te.sum(A[k], k), name=\"B\")\n\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef zero_rank_compute_auto_scheduler_test(N):\n    A = tvm.te.placeholder((N,), name=\"A\")\n    B = tvm.te.compute((), lambda: A[0], name=\"B\")\n\n    return [A, B]\n\n\n@auto_scheduler.register_workload\ndef conv2d_winograd_nhwc_auto_scheduler_test(\n    N, H, W, CI, CO, kernel_size=3, stride=1, padding=0, dilation=1\n):\n    tile_size = 4\n    inputs = te.placeholder((N, H, W, CI), name=\"inputs\")\n    N, H, W, CI = get_const_tuple(inputs.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n\n    KH = KW = kernel_size\n    HPAD, WPAD, _, _ = topi.nn.get_pad_tuple(padding, (KH, KW))\n    HSTR, WSTR = (stride, stride) if isinstance(stride, int) else stride\n    assert HSTR == 1 and WSTR == 1 and KH == KW\n\n    data_pad = topi.nn.pad(inputs, (0, HPAD, WPAD, 0), (0, HPAD, WPAD, 0), name=\"data_pad\")\n\n    r = KW\n    m = tile_size\n    alpha = m + r - 1\n    A, B, _ = winograd_transform_matrices(m, r, \"float32\")\n\n    H = (H + 2 * HPAD - KH) // HSTR + 1\n    W = (W + 2 * WPAD - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n    kshape = (alpha, alpha, CI, CO)\n    kernel_pack = te.placeholder(kshape, inputs.dtype, name=\"weight\")\n\n    idxdiv = te.indexdiv\n    idxmod = te.indexmod\n    # pack input tile\n    input_tile = te.compute(\n        (alpha, alpha, P, CI),\n        lambda eps, nu, p, ci: data_pad[idxdiv(p, (nH * nW))][idxmod(idxdiv(p, nW), nH) * m + eps][\n            idxmod(p, nW) * m + nu\n        ][ci],\n        name=\"input_tile\",\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    data_pack = te.compute(\n        (alpha, alpha, P, CI),\n        lambda eps, nu, p, ci: te.sum(\n            input_tile[r_a][r_b][p][ci] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"data_pack\",\n        attrs={\"auto_scheduler_simplify_const_tensor_indices\": [\"eps\", \"nu\", \"r_a\", \"r_b\"]},\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, P, CO),\n        lambda eps, nu, p, co: te.sum(\n            data_pack[eps][nu][p][ci] * kernel_pack[eps][nu][ci][co], axis=[ci]\n        ),\n        name=\"bgemm\",\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    inverse = te.compute(\n        (m, m, P, CO),\n        lambda vh, vw, p, co: te.sum(\n            bgemm[r_a][r_b][p][co] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]\n        ),\n        name=\"inverse\",\n        attrs={\"auto_scheduler_simplify_const_tensor_indices\": [\"vh\", \"vw\", \"r_a\", \"r_b\"]},\n    )\n\n    # output\n    output = te.compute(\n        (N, H, W, CO),\n        lambda n, h, w, co: inverse[\n            idxmod(h, m), idxmod(w, m), n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), co\n        ],\n        name=\"conv2d_winograd\",\n    )\n\n    return [inputs, kernel_pack, output]\n\n\ndef get_tiled_matmul():\n    \"\"\"Get a compute dag and a state for tiled matmul\"\"\"\n    A, B, C = matmul_auto_scheduler_test(512, 512, 512)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n\n    s0 = dag.get_init_state()\n    its0 = s0.split(C, s0[C].iters[0], [4, 8, 8])\n    its1 = s0.split(C, s0[C].iters[4], [8, 4, 4])\n    s0.reorder(\n        C, [its0[0], its1[0], its0[1], its1[1], its0[2], its1[2], its0[3], its1[3], s0[C].iters[8]]\n    )\n\n    return dag, s0\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/autotvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-function-docstring, missing-class-docstring\n\"\"\"Common utilities for testing autotvm\"\"\"\nimport time\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm import MeasureInput, MeasureResult\nfrom tvm.autotvm.measure.measure import Runner\n\n\nclass DummyRunner(Runner):\n    def __init__(self):\n        super(DummyRunner, self).__init__(1, 1)\n\n    def run(self, measure_inputs, build_results):\n        return [\n            MeasureResult((np.random.random(),), 0, 0.2, time.time())\n            for _ in range(len(measure_inputs))\n        ]\n\n    def get_build_kwargs(self):\n        return {}\n\n\n@autotvm.template(\"testing/matmul\")\ndef matmul(N, L, M, dtype):\n    A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n    B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n\n    k = te.reduce_axis((0, L), name=\"k\")\n    C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    # schedule\n    y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    ##### define space begin #####\n    cfg = autotvm.get_config()\n    cfg.define_split(\"tile_y\", y, num_outputs=2)\n    cfg.define_split(\"tile_x\", x, num_outputs=2)\n    ##### define space end #####\n\n    # schedule according to config\n    yo, yi = cfg[\"tile_y\"].apply(s, C, y)\n    # Make sure configurations have a varied number of itervars. Splitting adds\n    # new itervars, so conditionally splitting with cause the number of\n    # itervars to depend on the tile size.\n    if cfg[\"tile_x\"].size[-1] > 1:\n        xo, xi = cfg[\"tile_x\"].apply(s, C, x)\n        s[C].reorder(yo, xo, k, yi, xi)\n    else:\n        s[C].reorder(yo, k, yi, x)\n\n    return s, [A, B, C]\n\n\n@autotvm.template(\"testing/bad_matmul\")\ndef bad_matmul(N, L, M, dtype):\n    if \"bad_device\" in tvm.target.Target.current().keys:\n        A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n        B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n\n        k = te.reduce_axis((0, L - 1), name=\"k\")\n        C = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"C\")\n        s = te.create_schedule(C.op)\n\n        # schedule\n        y, x = s[C].op.axis\n        cfg = autotvm.get_config()\n        cfg.define_split(\"tile_y\", y, num_outputs=2)\n        cfg.define_split(\"tile_x\", x, num_outputs=2)\n        return s, [A, B, C]\n\n    return matmul(N, L, M, dtype)\n\n\ndef get_sample_task(n=128):\n    \"\"\"return a sample task for testing\"\"\"\n    target = tvm.target.Target(\"llvm\")\n    task = autotvm.task.create(\"testing/matmul\", args=(n, n, n, \"float32\"), target=target)\n    return task, target\n\n\ndef get_sample_records(n):\n    \"\"\"get sample records for testing\"\"\"\n    tsk, target = get_sample_task()\n\n    inps, ress = [], []\n    for i in range(n):\n        inps.append(MeasureInput(target, tsk, tsk.config_space.get(i % len(tsk.config_space))))\n        ress.append(MeasureResult((i + 1,), 0, i, time.time()))\n    return list(zip(inps, ress))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/plugin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Pytest plugin for using tvm testing extensions.\n\nTVM provides utilities for testing across all supported targets, and\nto more easily parametrize across many inputs.  For more information\non usage of these features, see documentation in the tvm.testing\nmodule.\n\nThese are enabled by default in all pytests provided by tvm, but may\nbe useful externally for one-off testing.  To enable, add the\nfollowing line to the test script, or to the conftest.py in the same\ndirectory as the test scripts.\n\n     pytest_plugins = ['tvm.testing.plugin']\n\n\"\"\"\n\nimport pytest\nimport _pytest\n\nimport tvm\nfrom tvm.testing import utils\n\ntry:\n    from xdist.scheduler.loadscope import LoadScopeScheduling\n\n    HAVE_XDIST = True\nexcept ImportError:\n    HAVE_XDIST = False\n\n\nMARKERS = {\n    \"gpu\": \"mark a test as requiring a gpu\",\n    \"tensorcore\": \"mark a test as requiring a tensorcore\",\n    \"cuda\": \"mark a test as requiring cuda\",\n    \"opencl\": \"mark a test as requiring opencl\",\n    \"rocm\": \"mark a test as requiring rocm\",\n    \"vulkan\": \"mark a test as requiring vulkan\",\n    \"metal\": \"mark a test as requiring metal\",\n    \"llvm\": \"mark a test as requiring llvm\",\n    \"ethosn\": \"mark a test as requiring ethosn\",\n    \"hexagon\": \"mark a test as requiring hexagon\",\n    \"corstone300\": \"mark a test as requiring Corstone300 FVP\",\n}\n\n\ndef pytest_configure(config):\n    \"\"\"Runs at pytest configure time, defines marks to be used later.\"\"\"\n\n    for feature in utils.Feature._all_features.values():\n        feature._register_marker(config)\n\n    print(\"enabled targets:\", \"; \".join(map(lambda x: x[0], utils.enabled_targets())))\n    print(\"pytest marker:\", config.option.markexpr)\n\n\ndef pytest_addoption(parser):\n    \"\"\"Add pytest options.\"\"\"\n    parser.addoption(\"--gtest_args\", action=\"store\", default=\"\")\n\n\ndef pytest_generate_tests(metafunc):\n    \"\"\"Called once per unit test, modifies/parametrizes it as needed.\"\"\"\n    _parametrize_correlated_parameters(metafunc)\n    _auto_parametrize_target(metafunc)\n    _add_target_specific_marks(metafunc)\n\n    # Process gtest arguments\n    option_value = metafunc.config.option.gtest_args\n    if \"gtest_args\" in metafunc.fixturenames and option_value is not None:\n        metafunc.parametrize(\"gtest_args\", [option_value])\n\n\ndef pytest_collection_modifyitems(config, items):\n    \"\"\"Called after all tests are chosen, currently used for bookkeeping.\"\"\"\n    # pylint: disable=unused-argument\n    _count_num_fixture_uses(items)\n    _remove_global_fixture_definitions(items)\n    _sort_tests(items)\n\n\n@pytest.fixture\ndef dev(target):\n    \"\"\"Give access to the device to tests that need it.\"\"\"\n    return tvm.device(target)\n\n\ndef pytest_sessionfinish(session, exitstatus):\n    # Don't exit with an error if we select a subset of tests that doesn't\n    # include anything\n    if session.config.option.markexpr != \"\":\n        if exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED:\n            session.exitstatus = pytest.ExitCode.OK\n\n\ndef _auto_parametrize_target(metafunc):\n    \"\"\"Automatically applies parametrize_targets\n\n    Used if a test function uses the \"target\" fixture, but isn't\n    already marked with @tvm.testing.parametrize_targets.  Intended\n    for use in the pytest_generate_tests() handler of a conftest.py\n    file.\n\n    \"\"\"\n\n    if \"target\" in metafunc.fixturenames:\n        # Check if any explicit parametrizations exist, and apply one\n        # if they do not.  If the function is marked with either\n        # excluded or known failing targets, use these to determine\n        # the targets to be used.\n        parametrized_args = [\n            arg.strip()\n            for mark in metafunc.definition.iter_markers(\"parametrize\")\n            for arg in mark.args[0].split(\",\")\n        ]\n        if \"target\" not in parametrized_args:\n            excluded_targets = getattr(metafunc.function, \"tvm_excluded_targets\", [])\n\n            # Add a parametrize marker instead of calling\n            # metafunc.parametrize so that the parametrize rewriting\n            # can still occur.\n            mark = pytest.mark.parametrize(\n                \"target\",\n                [\n                    t[\"target\"]\n                    for t in utils._get_targets()\n                    if t[\"target_kind\"] not in excluded_targets\n                ],\n                scope=\"session\",\n            )\n            metafunc.definition.add_marker(mark)\n\n\ndef _add_target_specific_marks(metafunc):\n    \"\"\"Add any target-specific marks to parametrizations over target\"\"\"\n\n    def update_parametrize_target_arg(\n        mark,\n        argnames,\n        argvalues,\n        *args,\n        **kwargs,\n    ):\n        args = [arg.strip() for arg in argnames.split(\",\") if arg.strip()]\n        if \"target\" in args:\n            target_i = args.index(\"target\")\n\n            new_argvalues = []\n            for argvalue in argvalues:\n\n                if isinstance(argvalue, _pytest.mark.structures.ParameterSet):\n                    # The parametrized value is already a\n                    # pytest.param, so track any marks already\n                    # defined.\n                    param_set = argvalue.values\n                    target = param_set[target_i]\n                    additional_marks = argvalue.marks\n                elif len(args) == 1:\n                    # Single value parametrization, argvalue is a list of values.\n                    target = argvalue\n                    param_set = (target,)\n                    additional_marks = []\n                else:\n                    # Multiple correlated parameters, argvalue is a list of tuple of values.\n                    param_set = argvalue\n                    target = param_set[target_i]\n                    additional_marks = []\n\n                if mark in metafunc.definition.own_markers:\n                    xfail_targets = getattr(metafunc.function, \"tvm_known_failing_targets\", [])\n                    target_kind = target.split()[0] if isinstance(target, str) else target.kind.name\n                    if target_kind in xfail_targets:\n                        additional_marks.append(\n                            pytest.mark.xfail(\n                                reason=f'Known failing test for target \"{target_kind}\"'\n                            )\n                        )\n\n                new_argvalues.append(\n                    pytest.param(\n                        *param_set, marks=_target_to_requirement(target) + additional_marks\n                    )\n                )\n\n            try:\n                argvalues[:] = new_argvalues\n            except TypeError as err:\n                pyfunc = metafunc.definition.function\n                filename = pyfunc.__code__.co_filename\n                line_number = pyfunc.__code__.co_firstlineno\n                msg = (\n                    f\"Unit test {metafunc.function.__name__} ({filename}:{line_number}) \"\n                    \"is parametrized using a tuple of parameters instead of a list \"\n                    \"of parameters.\"\n                )\n                raise TypeError(msg) from err\n\n    if \"target\" in metafunc.fixturenames:\n        # Update any explicit use of @pytest.mark.parmaetrize to\n        # parametrize over targets.  This adds the appropriate\n        # @tvm.testing.requires_* markers for each target.\n        for mark in metafunc.definition.iter_markers(\"parametrize\"):\n            update_parametrize_target_arg(mark, *mark.args, **mark.kwargs)\n\n\ndef _count_num_fixture_uses(items):\n    # Helper function, counts the number of tests that use each cached\n    # fixture.  Should be called from pytest_collection_modifyitems().\n    for item in items:\n        is_skipped = item.get_closest_marker(\"skip\") or any(\n            mark.args[0] for mark in item.iter_markers(\"skipif\")\n        )\n        if is_skipped:\n            continue\n\n        for fixturedefs in item._fixtureinfo.name2fixturedefs.values():\n            # Only increment the active fixturedef, in a name has been overridden.\n            fixturedef = fixturedefs[-1]\n            if hasattr(fixturedef.func, \"num_tests_use_this_fixture\"):\n                fixturedef.func.num_tests_use_this_fixture[0] += 1\n\n\ndef _remove_global_fixture_definitions(items):\n    # Helper function, removes fixture definitions from the global\n    # variables of the modules they were defined in.  This is intended\n    # to improve readability of error messages by giving a NameError\n    # if a test function accesses a pytest fixture but doesn't include\n    # it as an argument.  Should be called from\n    # pytest_collection_modifyitems().\n\n    modules = set(item.module for item in items)\n\n    for module in modules:\n        for name in dir(module):\n            obj = getattr(module, name)\n            if hasattr(obj, \"_pytestfixturefunction\") and isinstance(\n                obj._pytestfixturefunction, _pytest.fixtures.FixtureFunctionMarker\n            ):\n                delattr(module, name)\n\n\ndef _sort_tests(items):\n    \"\"\"Sort tests by file/function.\n\n    By default, pytest will sort tests to maximize the re-use of\n    fixtures.  However, this assumes that all fixtures have an equal\n    cost to generate, and no caches outside of those managed by\n    pytest.  A tvm.testing.parameter is effectively free, while\n    reference data for testing may be quite large.  Since most of the\n    TVM fixtures are specific to a python function, sort the test\n    ordering by python function, so that\n    tvm.testing.utils._fixture_cache can be cleared sooner rather than\n    later.\n\n    Should be called from pytest_collection_modifyitems.\n\n    \"\"\"\n\n    def sort_key(item):\n        filename, lineno, test_name = item.location\n        test_name = test_name.split(\"[\")[0]\n        return filename, lineno, test_name\n\n    items.sort(key=sort_key)\n\n\ndef _target_to_requirement(target):\n    if isinstance(target, str):\n        target = tvm.target.Target(target)\n\n    # mapping from target to decorator\n    if target.kind.name == \"cuda\" and \"cudnn\" in target.attrs.get(\"libs\", []):\n        return utils.requires_cudnn.marks()\n    if target.kind.name == \"cuda\" and \"cublas\" in target.attrs.get(\"libs\", []):\n        return utils.requires_cublas.marks()\n    if target.kind.name == \"cuda\":\n        return utils.requires_cuda.marks()\n    if target.kind.name == \"rocm\":\n        return utils.requires_rocm.marks()\n    if target.kind.name == \"vulkan\":\n        return utils.requires_vulkan.marks()\n    if target.kind.name == \"nvptx\":\n        return utils.requires_nvptx.marks()\n    if target.kind.name == \"metal\":\n        return utils.requires_metal.marks()\n    if target.kind.name == \"opencl\":\n        return utils.requires_opencl.marks()\n    if target.kind.name == \"llvm\":\n        return utils.requires_llvm.marks()\n    if target.kind.name == \"hexagon\":\n        return utils.requires_hexagon.marks()\n\n    return []\n\n\ndef _parametrize_correlated_parameters(metafunc):\n    parametrize_needed = {}\n\n    for name, fixturedefs in metafunc.definition._fixtureinfo.name2fixturedefs.items():\n        fixturedef = fixturedefs[-1]\n        if hasattr(fixturedef.func, \"parametrize_group\") and hasattr(\n            fixturedef.func, \"parametrize_values\"\n        ):\n            group = fixturedef.func.parametrize_group\n            values = fixturedef.func.parametrize_values\n            ids = fixturedef.func.parametrize_ids\n            if group in parametrize_needed:\n                assert ids == parametrize_needed[group][\"ids\"]\n            else:\n                parametrize_needed[group] = {\"ids\": ids, \"params\": []}\n            parametrize_needed[group][\"params\"].append((name, values))\n\n    for parametrize_group in parametrize_needed.values():\n        params = parametrize_group[\"params\"]\n        ids = parametrize_group[\"ids\"]\n        if len(params) == 1:\n            name, values = params[0]\n            metafunc.parametrize(name, values, indirect=True, ids=ids)\n        else:\n            names = \",\".join(name for name, values in params)\n            value_sets = zip(*[values for name, values in params])\n            metafunc.parametrize(names, value_sets, indirect=True, ids=ids)\n\n\n# pytest-xdist isn't required but is used in CI, so guard on its presence\nif HAVE_XDIST:\n\n    def pytest_xdist_make_scheduler(config, log):\n        \"\"\"\n        Serialize certain tests for pytest-xdist that have inter-test\n        dependencies\n        \"\"\"\n\n        class TvmTestScheduler(LoadScopeScheduling):\n            \"\"\"\n            Scheduler to serializer tests\n            \"\"\"\n\n            def _split_scope(self, nodeid):\n                \"\"\"\n                Returns a specific string for classes of nodeids\n                \"\"\"\n                # NOTE: these tests contain inter-test dependencies and must be\n                # serialized\n                items = {\n                    \"test_tvm_testing_features\": \"functional-tests\",\n                    \"tests/python/unittest/test_crt\": \"crt-tests\",\n                    \"tests/python/driver/tvmc\": \"tvmc-tests\",\n                }\n\n                for nodeid_pattern, suite_name in items.items():\n                    if nodeid_pattern in nodeid:\n                        return suite_name\n\n                return nodeid\n\n        return TvmTestScheduler(config, log)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/popen_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-function-docstring\n\"\"\"Common functions for popen_pool test cases\"\"\"\nimport tvm\nfrom . import _ffi_api\n\nTEST_GLOBAL_STATE_1 = 0\nTEST_GLOBAL_STATE_2 = 0\nTEST_GLOBAL_STATE_3 = 0\n\n\ndef initializer(test_global_state_1, test_global_state_2, test_global_state_3):\n    global TEST_GLOBAL_STATE_1, TEST_GLOBAL_STATE_2, TEST_GLOBAL_STATE_3\n    TEST_GLOBAL_STATE_1 = test_global_state_1\n    TEST_GLOBAL_STATE_2 = test_global_state_2\n    TEST_GLOBAL_STATE_3 = test_global_state_3\n\n\ndef after_initializer():\n    global TEST_GLOBAL_STATE_1, TEST_GLOBAL_STATE_2, TEST_GLOBAL_STATE_3\n    return TEST_GLOBAL_STATE_1, TEST_GLOBAL_STATE_2, TEST_GLOBAL_STATE_3\n\n\n@tvm._ffi.register_func(\"testing.identity_py\")\ndef identity_py(arg):\n    return arg\n\n\ndef register_ffi():\n    @tvm._ffi.register_func(\"testing.nested_identity_py\")\n    def _identity_py(arg):  # pylint: disable=unused-variable\n        return arg\n\n\ndef call_py_ffi(arg):\n    _identity_py = tvm._ffi.get_global_func(\"testing.nested_identity_py\")\n    return _identity_py(arg)\n\n\ndef call_cpp_ffi(arg):\n    return tvm.testing.echo(arg)\n\n\ndef call_cpp_py_ffi(arg):\n    return tvm.testing.identity_cpp(arg)\n\n\ndef fast_summation(n):\n    return n * (n + 1) // 2\n\n\ndef slow_summation(n):\n    r = 0\n    for i in range(0, n + 1):\n        r += i\n    return r\n\n\ndef timeout_job(n):\n    _ffi_api.sleep_in_ffi(n * 1.5)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/tir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-outside-toplevel, unused-variable\n\"\"\"Common utility functions in TVM tir\"\"\"\n\n\ndef mma_schedule(\n    workload,\n    k_inner,\n    in_dtype,\n    b_transposed,\n    i_factors,\n    j_factors,\n    k_factors,\n    index_map_A,\n    index_map_B,\n    index_map_C,\n    ldmatrix_a_intrin,\n    ldmatrix_b_intrin,\n    mma_intrin,\n    mma_fill_intrin,\n    mma_store_intrin,\n    shared_scope=\"shared\",\n):\n    \"\"\"Create a tensorized schedule for GEMM with MMA intrinsics.\"\"\"\n    import tvm  # pylint: disable=import-outside-toplevel\n\n    ir_module = tvm.IRModule({\"main\": workload})\n    sch = tvm.tir.Schedule(ir_module)\n\n    block = sch.get_block(\"C\")\n    i, j, k = sch.get_loops(block)\n    i, i_tc = sch.split(i, factors=[None, 16])\n    j, j_tc = sch.split(j, factors=[None, 16])\n    k, k_tc = sch.split(k, factors=[None, k_inner])\n\n    sch.reorder(i, j, k, i_tc, j_tc, k_tc)\n\n    block_inner = sch.blockize(i_tc)\n    block_outer, block_inner = block_inner, block\n\n    num_ty = i_factors[2] * j_factors[2]\n\n    i0, i1, i2, i3, i4 = sch.split(i, factors=i_factors)\n    j0, j1, j2, j3, j4 = sch.split(j, factors=j_factors)\n    k0, k1, k2 = sch.split(k, k_factors)\n\n    sch.reorder(i0, j0, i1, j1, j2, i2, k0, k1, i3, j3, k2, i4, j4)\n\n    block_idx = sch.fuse(i0, j0)\n    block_idy = sch.fuse(i1, j1)\n    thread_idy = sch.fuse(j2, i2)\n    sch.bind(block_idx, \"blockIdx.x\")\n    sch.bind(block_idy, \"blockIdx.y\")\n    sch.bind(thread_idy, \"threadIdx.y\")\n\n    def fetch_to_shared(block, idx, ndim):\n        block_read = sch.cache_read(block, idx, shared_scope)\n        sch.compute_at(block_read, k0)\n        vector_size = 16 if in_dtype == \"int8\" else 8\n        warp_size = 32\n        fused = sch.fuse(*sch.get_loops(block_read)[-ndim:])\n        _, f_1, f_2, f_3 = sch.split(fused, factors=[None, num_ty, warp_size, vector_size])\n        sch.bind(f_2, \"threadIdx.x\")\n        sch.bind(f_1, \"threadIdx.y\")\n        sch.vectorize(f_3)\n        offset = 8 if in_dtype == \"float16\" else 16\n        sch.storage_align(block_read, 0, axis=-2, factor=32, offset=offset)\n\n        return block_read\n\n    fetch_to_shared(block_outer, 0, 2)\n    fetch_to_shared(block_outer, 1, 2)\n\n    A_warp = sch.cache_read(block_outer, 0, \"warp\")\n    B_warp = sch.cache_read(block_outer, 1, \"warp\")\n\n    sch.compute_at(A_warp, k1)\n    sch.compute_at(B_warp, k1)\n\n    C_warp = sch.cache_write(block_outer, 0, \"warp\")\n    sch.reverse_compute_at(C_warp, thread_idy)\n\n    ii, jj = sch.get_loops(C_warp)[-2:]\n    io, ii = sch.split(ii, factors=[None, 16])\n    jo, ji = sch.split(jj, factors=[None, 16])\n    sch.reorder(io, jo, ii, ji)\n\n    sch.decompose_reduction(block_outer, sch.get_loops(block_outer)[3])\n    block_init_c = sch.get_block(\"C_init\")\n\n    def tile_wmma_fragment(block_read, height, width):\n        i, j = sch.get_loops(block_read)[-2:]\n        i0, i1 = sch.split(i, factors=[None, height])\n        j0, j1 = sch.split(j, factors=[None, width])\n        sch.reorder(i0, j0, i1, j1)\n        return i1\n\n    loop_a = tile_wmma_fragment(A_warp, 16, k_inner)\n\n    if b_transposed:\n        loop_b = tile_wmma_fragment(B_warp, 16, k_inner)\n    else:\n        loop_b = tile_wmma_fragment(B_warp, k_inner, 16)\n\n    sch.transform_layout(A_warp, (\"write\", 0), index_map_A)\n    sch.transform_layout(B_warp, (\"write\", 0), index_map_B)\n    sch.transform_layout(C_warp, (\"read\", 0), index_map_C)\n\n    sch.tensorize(loop_a, ldmatrix_a_intrin)\n    sch.tensorize(loop_b, ldmatrix_b_intrin)\n    sch.tensorize(sch.get_loops(block_inner)[-3], mma_intrin)\n    sch.tensorize(sch.get_loops(block_init_c)[-2], mma_fill_intrin)\n    sch.tensorize(sch.get_loops(C_warp)[-2], mma_store_intrin)\n\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/usmp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" This file contains USMP tests harnesses.\"\"\"\n\nimport tvm\n\n\ndef is_tvm_backendallocworkspace_calls(mod: tvm.runtime.module) -> bool:\n    \"\"\"TVMBackendAllocWorkspace call check.\n\n    This checker checks whether any c-source produced has TVMBackendAllocWorkspace calls.\n    If USMP is invoked, none of them should have TVMBAW calls\n    \"\"\"\n    dso_modules = mod._collect_dso_modules()\n    for dso_mod in dso_modules:\n        if dso_mod.type_key not in [\"c\", \"llvm\"]:\n            assert (\n                False\n            ), 'Current AoT codegen flow should only produce type \"c\" or \"llvm\" runtime modules'\n\n        source = dso_mod.get_source()\n        if source.count(\"TVMBackendAllocWorkspace\") != 0:\n            return True\n\n    return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/testing/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,unnecessary-comprehension\n\"\"\"TVM testing utilities\n\nOrganization\n************\n\nThis file contains functions expected to be called directly by a user\nwhile writing unit tests.  Integrations with the pytest framework\nare in plugin.py.\n\nTesting Markers\n***************\n\nWe use pytest markers to specify the requirements of test functions. Currently\nthere is a single distinction that matters for our testing environment: does\nthe test require a gpu. For tests that require just a gpu or just a cpu, we\nhave the decorator :py:func:`requires_gpu` that enables the test when a gpu is\navailable. To avoid running tests that don't require a gpu on gpu nodes, this\ndecorator also sets the pytest marker `gpu` so we can use select the gpu subset\nof tests (using `pytest -m gpu`).\n\nUnfortunately, many tests are written like this:\n\n.. python::\n\n    def test_something():\n        for target in all_targets():\n            do_something()\n\nThe test uses both gpu and cpu targets, so the test needs to be run on both cpu\nand gpu nodes. But we still want to only run the cpu targets on the cpu testing\nnode. The solution is to mark these tests with the gpu marker so they will be\nrun on the gpu nodes. But we also modify all_targets (renamed to\nenabled_targets) so that it only returns gpu targets on gpu nodes and cpu\ntargets on cpu nodes (using an environment variable).\n\nInstead of using the all_targets function, future tests that would like to\ntest against a variety of targets should use the\n:py:func:`tvm.testing.parametrize_targets` functionality. This allows us\ngreater control over which targets are run on which testing nodes.\n\nIf in the future we want to add a new type of testing node (for example\nfpgas), we need to add a new marker in `tests/python/pytest.ini` and a new\nfunction in this module. Then targets using this node should be added to the\n`TVM_TEST_TARGETS` environment variable in the CI.\n\n\"\"\"\nimport inspect\nimport copy\nimport copyreg\nimport ctypes\nimport functools\nimport hashlib\nimport itertools\nimport logging\nimport os\nimport pickle\nimport platform\nimport sys\nimport textwrap\nimport time\nimport shutil\nimport subprocess\n\nfrom pathlib import Path\nfrom typing import Optional, Callable, Union, List, Tuple\n\nimport pytest\nimport numpy as np\n\nimport tvm\nimport tvm.arith\nimport tvm.tir\nimport tvm.te\nimport tvm._ffi\n\nfrom tvm.contrib import nvcc, cudnn\nimport tvm.contrib.hexagon._ci_env_check as hexagon\nfrom tvm.driver.tvmc.frontends import load_model\nfrom tvm.error import TVMError\n\n\nSKIP_SLOW_TESTS = os.getenv(\"SKIP_SLOW_TESTS\", \"\").lower() in {\"true\", \"1\", \"yes\"}\nIS_IN_CI = os.getenv(\"CI\", \"\") == \"true\"\n\nskip_if_wheel_test = pytest.mark.skipif(\n    os.getenv(\"WHEEL_TEST\", \"\").lower() in {\"true\", \"1\", \"yes\"},\n    reason=\"Test not supported in wheel.\",\n)\n\n\ndef assert_allclose(actual, desired, rtol=1e-7, atol=1e-7):\n    \"\"\"Version of np.testing.assert_allclose with `atol` and `rtol` fields set\n    in reasonable defaults.\n\n    Arguments `actual` and `desired` are not interchangeable, since the function\n    compares the `abs(actual-desired)` with `atol+rtol*abs(desired)`.  Since we\n    often allow `desired` to be close to zero, we generally want non-zero `atol`.\n    \"\"\"\n    actual = np.asanyarray(actual)\n    desired = np.asanyarray(desired)\n    np.testing.assert_allclose(actual.shape, desired.shape)\n    np.testing.assert_allclose(actual, desired, rtol=rtol, atol=atol, verbose=True)\n\n\ndef check_numerical_grads(\n    function, input_values, grad_values, function_value=None, delta=1e-3, atol=1e-2, rtol=0.1\n):\n    \"\"\"A helper function that checks that numerical gradients of a function are\n    equal to gradients computed in some different way (analytical gradients).\n\n    Numerical gradients are computed using finite difference approximation. To\n    reduce the number of function evaluations, the number of points used is\n    gradually increased if the error value is too high (up to 5 points).\n\n    Parameters\n    ----------\n    function\n        A function that takes inputs either as positional or as keyword\n        arguments (either `function(*input_values)` or `function(**input_values)`\n        should be correct) and returns a scalar result. Should accept numpy\n        ndarrays.\n\n    input_values : Dict[str, numpy.ndarray] or List[numpy.ndarray]\n        A list of values or a dict assigning values to variables. Represents the\n        point at which gradients should be computed.\n\n    grad_values : Dict[str, numpy.ndarray] or List[numpy.ndarray]\n        Gradients computed using a different method.\n\n    function_value : float, optional\n        Should be equal to `function(**input_values)`.\n\n    delta : float, optional\n        A small number used for numerical computation of partial derivatives.\n        The default 1e-3 is a good choice for float32.\n\n    atol : float, optional\n        Absolute tolerance. Gets multiplied by `sqrt(n)` where n is the size of a\n        gradient.\n\n    rtol : float, optional\n        Relative tolerance.\n    \"\"\"\n    # If input_values is a list then function accepts positional arguments\n    # In this case transform it to a function taking kwargs of the form {\"0\": ..., \"1\": ...}\n    if not isinstance(input_values, dict):\n        input_len = len(input_values)\n        input_values = {str(idx): val for idx, val in enumerate(input_values)}\n\n        def _function(_input_len=input_len, _orig_function=function, **kwargs):\n            return _orig_function(*(kwargs[str(i)] for i in range(input_len)))\n\n        function = _function\n\n        grad_values = {str(idx): val for idx, val in enumerate(grad_values)}\n\n    if function_value is None:\n        function_value = function(**input_values)\n\n    # a helper to modify j-th element of val by a_delta\n    def modify(val, j, a_delta):\n        val = val.copy()\n        val.reshape(-1)[j] = val.reshape(-1)[j] + a_delta\n        return val\n\n    # numerically compute a partial derivative with respect to j-th element of the var `name`\n    def derivative(x_name, j, a_delta):\n        modified_values = {\n            n: modify(val, j, a_delta) if n == x_name else val for n, val in input_values.items()\n        }\n        return (function(**modified_values) - function_value) / a_delta\n\n    def compare_derivative(j, n_der, grad):\n        der = grad.reshape(-1)[j]\n        return np.abs(n_der - der) < atol + rtol * np.abs(n_der)\n\n    for x_name, grad in grad_values.items():\n        if grad.shape != input_values[x_name].shape:\n            raise AssertionError(\n                \"Gradient wrt '{}' has unexpected shape {}, expected {} \".format(\n                    x_name, grad.shape, input_values[x_name].shape\n                )\n            )\n\n        ngrad = np.zeros_like(grad)\n\n        wrong_positions = []\n\n        # compute partial derivatives for each position in this variable\n        for j in range(np.prod(grad.shape)):\n            # forward difference approximation\n            nder = derivative(x_name, j, delta)\n\n            # if the derivative is not equal to the analytical one, try to use more\n            # precise and expensive methods\n            if not compare_derivative(j, nder, grad):\n                # central difference approximation\n                nder = (derivative(x_name, j, -delta) + nder) / 2\n\n                if not compare_derivative(j, nder, grad):\n                    # central difference approximation using h = delta/2\n                    cnder2 = (\n                        derivative(x_name, j, delta / 2) + derivative(x_name, j, -delta / 2)\n                    ) / 2\n                    # five-point derivative\n                    nder = (4 * cnder2 - nder) / 3\n\n            # if the derivatives still don't match, add this position to the\n            # list of wrong positions\n            if not compare_derivative(j, nder, grad):\n                wrong_positions.append(np.unravel_index(j, grad.shape))\n\n            ngrad.reshape(-1)[j] = nder\n\n        wrong_percentage = int(100 * len(wrong_positions) / np.prod(grad.shape))\n\n        dist = np.sqrt(np.sum((ngrad - grad) ** 2))\n        grad_norm = np.sqrt(np.sum(ngrad**2))\n\n        if not (np.isfinite(dist) and np.isfinite(grad_norm)):\n            raise ValueError(\n                \"NaN or infinity detected during numerical gradient checking wrt '{}'\\n\"\n                \"analytical grad = {}\\n numerical grad = {}\\n\".format(x_name, grad, ngrad)\n            )\n\n        # we multiply atol by this number to make it more universal for different sizes\n        sqrt_n = np.sqrt(float(np.prod(grad.shape)))\n\n        if dist > atol * sqrt_n + rtol * grad_norm:\n            raise AssertionError(\n                \"Analytical and numerical grads wrt '{}' differ too much\\n\"\n                \"analytical grad = {}\\n numerical grad = {}\\n\"\n                \"{}% of elements differ, first 10 of wrong positions: {}\\n\"\n                \"distance > atol*sqrt(n) + rtol*grad_norm\\n\"\n                \"distance {} > {}*{} + {}*{}\".format(\n                    x_name,\n                    grad,\n                    ngrad,\n                    wrong_percentage,\n                    wrong_positions[:10],\n                    dist,\n                    atol,\n                    sqrt_n,\n                    rtol,\n                    grad_norm,\n                )\n            )\n\n        max_diff = np.max(np.abs(ngrad - grad))\n        avg_diff = np.mean(np.abs(ngrad - grad))\n        logging.info(\n            \"Numerical grad test wrt '%s' of shape %s passes, \"\n            \"dist = %f, max_diff = %f, avg_diff = %f\",\n            x_name,\n            grad.shape,\n            dist,\n            max_diff,\n            avg_diff,\n        )\n\n\ndef assert_prim_expr_equal(lhs, rhs):\n    \"\"\"Assert lhs and rhs equals to each iother.\n\n    Parameters\n    ----------\n    lhs : tvm.tir.PrimExpr\n        The left operand.\n\n    rhs : tvm.tir.PrimExpr\n        The left operand.\n    \"\"\"\n    ana = tvm.arith.Analyzer()\n    if not ana.can_prove_equal(lhs, rhs):\n        raise ValueError(\"{} and {} are not equal\".format(lhs, rhs))\n\n\ndef check_bool_expr_is_true(bool_expr, vranges, cond=None):\n    \"\"\"Check that bool_expr holds given the condition cond\n    for every value of free variables from vranges.\n\n    for example, 2x > 4y solves to x > 2y given x in (0, 10) and y in (0, 10)\n    here bool_expr is x > 2y, vranges is {x: (0, 10), y: (0, 10)}, cond is 2x > 4y\n    We creates iterations to check,\n    for x in range(10):\n      for y in range(10):\n        assert !(2x > 4y) || (x > 2y)\n\n    Parameters\n    ----------\n    bool_expr : tvm.ir.PrimExpr\n        Boolean expression to check\n    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]\n        Free variables and their ranges\n    cond: tvm.ir.PrimExpr\n        extra conditions needs to be satisfied.\n    \"\"\"\n    if cond is not None:\n        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)\n\n    def _run_expr(expr, vranges):\n        \"\"\"Evaluate expr for every value of free variables\n        given by vranges and return the tensor of results.\n        \"\"\"\n\n        def _compute_body(*us):\n            vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)}\n            return tvm.tir.stmt_functor.substitute(expr, vmap)\n\n        A = tvm.te.compute([r.extent.value for v, r in vranges.items()], _compute_body)\n        args = [tvm.nd.empty(A.shape, A.dtype)]\n        sch = tvm.te.create_schedule(A.op)\n        mod = tvm.build(sch, [A])\n        mod(*args)\n        return args[0].numpy()\n\n    res = _run_expr(bool_expr, vranges)\n    if not np.all(res):\n        indices = list(np.argwhere(res == 0)[0])\n        counterex = [(str(v), i + r.min) for (v, r), i in zip(vranges.items(), indices)]\n        counterex = sorted(counterex, key=lambda x: x[0])\n        counterex = \", \".join([v + \" = \" + str(i) for v, i in counterex])\n        ana = tvm.arith.Analyzer()\n        raise AssertionError(\n            \"Expression {}\\nis not true on {}\\n\"\n            \"Counterexample: {}\".format(ana.simplify(bool_expr), vranges, counterex)\n        )\n\n\ndef check_int_constraints_trans_consistency(constraints_trans, vranges=None):\n    \"\"\"Check IntConstraintsTransform is a bijective transformation.\n\n    Parameters\n    ----------\n    constraints_trans : arith.IntConstraintsTransform\n        Integer constraints transformation\n    vranges: Dict[tvm.tir.Var, tvm.ir.Range]\n        Free variables and their ranges\n    \"\"\"\n    if vranges is None:\n        vranges = {}\n\n    def _check_forward(constraints1, constraints2, varmap, backvarmap):\n        ana = tvm.arith.Analyzer()\n        all_vranges = vranges.copy()\n        all_vranges.update({v: r for v, r in constraints1.ranges.items()})\n\n        # Check that the transformation is injective\n        cond_on_vars = tvm.tir.const(1, \"bool\")\n        for v in constraints1.variables:\n            if v in varmap:\n                # variable mapping is consistent\n                v_back = ana.simplify(tvm.tir.stmt_functor.substitute(varmap[v], backvarmap))\n                cond_on_vars = tvm.te.all(cond_on_vars, v == v_back)\n        # Also we have to check that the new relations are true when old relations are true\n        cond_subst = tvm.tir.stmt_functor.substitute(\n            tvm.te.all(tvm.tir.const(1, \"bool\"), *constraints2.relations), backvarmap\n        )\n        # We have to include relations from vranges too\n        for v in constraints2.variables:\n            if v in constraints2.ranges:\n                r = constraints2.ranges[v]\n                range_cond = tvm.te.all(v >= r.min, v < r.min + r.extent)\n                range_cond = tvm.tir.stmt_functor.substitute(range_cond, backvarmap)\n                cond_subst = tvm.te.all(cond_subst, range_cond)\n        cond_subst = ana.simplify(cond_subst)\n        check_bool_expr_is_true(\n            tvm.te.all(cond_subst, cond_on_vars),\n            all_vranges,\n            cond=tvm.te.all(tvm.tir.const(1, \"bool\"), *constraints1.relations),\n        )\n\n    _check_forward(\n        constraints_trans.src,\n        constraints_trans.dst,\n        constraints_trans.src_to_dst,\n        constraints_trans.dst_to_src,\n    )\n    _check_forward(\n        constraints_trans.dst,\n        constraints_trans.src,\n        constraints_trans.dst_to_src,\n        constraints_trans.src_to_dst,\n    )\n\n\ndef _get_targets(target_names=None):\n    if target_names is None:\n        target_names = _tvm_test_targets()\n\n    if not target_names:\n        target_names = DEFAULT_TEST_TARGETS\n\n    targets = []\n    for target in target_names:\n        target_kind = target.split()[0]\n\n        if target_kind == \"cuda\" and \"cudnn\" in tvm.target.Target(target).attrs.get(\"libs\", []):\n            is_enabled = tvm.support.libinfo()[\"USE_CUDNN\"].lower() in [\"on\", \"true\", \"1\"]\n            is_runnable = is_enabled and cudnn.exists()\n        elif target_kind == \"hexagon\":\n            is_enabled = tvm.support.libinfo()[\"USE_HEXAGON\"].lower() in [\"on\", \"true\", \"1\"]\n            # If Hexagon has compile-time support, we can always fall back\n            is_runnable = is_enabled and \"ANDROID_SERIAL_NUMBER\" in os.environ\n        else:\n            is_enabled = tvm.runtime.enabled(target_kind)\n            is_runnable = is_enabled and tvm.device(target_kind).exist\n\n        targets.append(\n            {\n                \"target\": target,\n                \"target_kind\": target_kind,\n                \"is_enabled\": is_enabled,\n                \"is_runnable\": is_runnable,\n            }\n        )\n\n    if all(not t[\"is_runnable\"] for t in targets):\n        if tvm.runtime.enabled(\"llvm\"):\n            logging.warning(\n                \"None of the following targets are supported by this build of TVM: %s.\"\n                \" Try setting TVM_TEST_TARGETS to a supported target. Defaulting to llvm.\",\n                target_names,\n            )\n            return _get_targets([\"llvm\"])\n\n        raise TVMError(\n            \"None of the following targets are supported by this build of TVM: %s.\"\n            \" Try setting TVM_TEST_TARGETS to a supported target.\"\n            \" Cannot default to llvm, as it is not enabled.\" % target_names\n        )\n\n    return targets\n\n\nDEFAULT_TEST_TARGETS = [\n    \"llvm\",\n    \"cuda\",\n    \"nvptx\",\n    \"vulkan -from_device=0\",\n    \"opencl\",\n    \"opencl -device=mali,aocl_sw_emu\",\n    \"opencl -device=intel_graphics\",\n    \"metal\",\n    \"rocm\",\n    \"hexagon\",\n]\n\n\ndef device_enabled(target):\n    \"\"\"Check if a target should be used when testing.\n\n    It is recommended that you use :py:func:`tvm.testing.parametrize_targets`\n    instead of manually checking if a target is enabled.\n\n    This allows the user to control which devices they are testing against. In\n    tests, this should be used to check if a device should be used when said\n    device is an optional part of the test.\n\n    Parameters\n    ----------\n    target : str\n        Target string to check against\n\n    Returns\n    -------\n    bool\n        Whether or not the device associated with this target is enabled.\n\n    Example\n    -------\n    >>> @tvm.testing.uses_gpu\n    >>> def test_mytest():\n    >>>     for target in [\"cuda\", \"llvm\"]:\n    >>>         if device_enabled(target):\n    >>>             test_body...\n\n    Here, `test_body` will only be reached by with `target=\"cuda\"` on gpu test\n    nodes and `target=\"llvm\"` on cpu test nodes.\n    \"\"\"\n    assert isinstance(target, str), \"device_enabled requires a target as a string\"\n    # only check if device name is found, sometime there are extra flags\n    target_kind = target.split(\" \")[0]\n    return any(target_kind == t[\"target_kind\"] for t in _get_targets() if t[\"is_runnable\"])\n\n\ndef enabled_targets():\n    \"\"\"Get all enabled targets with associated devices.\n\n    In most cases, you should use :py:func:`tvm.testing.parametrize_targets` instead of\n    this function.\n\n    In this context, enabled means that TVM was built with support for\n    this target, the target name appears in the TVM_TEST_TARGETS\n    environment variable, and a suitable device for running this\n    target exists.  If TVM_TEST_TARGETS is not set, it defaults to\n    variable DEFAULT_TEST_TARGETS in this module.\n\n    If you use this function in a test, you **must** decorate the test with\n    :py:func:`tvm.testing.uses_gpu` (otherwise it will never be run on the gpu).\n\n    Returns\n    -------\n    targets: list\n        A list of pairs of all enabled devices and the associated context\n\n    \"\"\"\n    return [(t[\"target\"], tvm.device(t[\"target\"])) for t in _get_targets() if t[\"is_runnable\"]]\n\n\nclass Feature:\n\n    \"\"\"A feature that may be required to run a test.\n\n    Parameters\n    ----------\n    name: str\n\n        The short name of the feature.  Should match the name in the\n        requires_* decorator.  This is applied as a mark to all tests\n        using this feature, and can be used in pytests ``-m``\n        argument.\n\n    long_name: Optional[str]\n\n        The long name of the feature, to be used in error messages.\n\n        If None, defaults to the short name.\n\n    cmake_flag: Optional[str]\n\n        The flag that must be enabled in the config.cmake in order to\n        use this feature.\n\n        If None, no flag is required to use this feature.\n\n    target_kind_enabled: Optional[str]\n\n        The target kind that must be enabled to run tests using this\n        feature.  If present, the target_kind must appear in the\n        TVM_TEST_TARGETS environment variable, or in\n        tvm.testing.DEFAULT_TEST_TARGETS if TVM_TEST_TARGETS is\n        undefined.\n\n        If None, this feature does not require a specific target to be\n        enabled.\n\n    compile_time_check: Optional[Callable[[], Union[bool,str]]]\n\n        A check that returns True if the feature can be used at\n        compile-time.  (e.g. Validating the version number of the nvcc\n        compiler.)  If the feature does not have support to perform\n        compile-time tests, the check should returns False to display\n        a generic error message, or a string to display a more\n        specific error message.\n\n        If None, no additional check is performed.\n\n    target_kind_hardware: Optional[str]\n\n        The target kind that must have available hardware in order to\n        run tests using this feature.  This is checked using\n        tvm.device(target_kind_hardware).exist.  If a feature requires\n        a different check, this should be implemented using\n        run_time_check.\n\n        If None, this feature does not require a specific\n        tvm.device to exist.\n\n    run_time_check: Optional[Callable[[], Union[bool,str]]]\n\n        A check that returns True if the feature can be used at\n        run-time.  (e.g. Validating the compute version supported by a\n        GPU.)  If the feature does not have support to perform\n        run-time tests, the check should returns False to display a\n        generic error message, or a string to display a more specific\n        error message.\n\n        If None, no additional check is performed.\n\n    parent_features: Optional[Union[str,List[str]]]\n\n        The short name of a feature or features that are required in\n        order to use this feature.  (e.g. Using cuDNN requires using\n        CUDA) This feature should inherit all checks of the parent\n        feature, with the exception of the `target_kind_enabled`\n        checks.\n\n        If None, this feature does not require any other parent\n        features.\n\n    \"\"\"\n\n    _all_features = {}\n\n    def __init__(\n        self,\n        name: str,\n        long_name: Optional[str] = None,\n        cmake_flag: Optional[str] = None,\n        target_kind_enabled: Optional[str] = None,\n        compile_time_check: Optional[Callable[[], Union[bool, str]]] = None,\n        target_kind_hardware: Optional[str] = None,\n        run_time_check: Optional[Callable[[], Union[bool, str]]] = None,\n        parent_features: Optional[Union[str, List[str]]] = None,\n    ):\n        self.name = name\n        self.long_name = long_name or name\n        self.cmake_flag = cmake_flag\n        self.target_kind_enabled = target_kind_enabled\n        self.compile_time_check = compile_time_check\n        self.target_kind_hardware = target_kind_hardware\n        self.run_time_check = run_time_check\n\n        if parent_features is None:\n            self.parent_features = []\n        elif isinstance(parent_features, str):\n            self.parent_features = [parent_features]\n        else:\n            self.parent_features = parent_features\n\n        self._all_features[self.name] = self\n\n    def _register_marker(self, config):\n        config.addinivalue_line(\"markers\", f\"{self.name}: Mark a test as using {self.long_name}\")\n\n    def _uses_marks(self):\n        for parent in self.parent_features:\n            yield from self._all_features[parent]._uses_marks()\n\n        yield getattr(pytest.mark, self.name)\n\n    def _compile_only_marks(self):\n        for parent in self.parent_features:\n            yield from self._all_features[parent]._compile_only_marks()\n\n        if self.compile_time_check is not None:\n            res = self.compile_time_check()\n            if isinstance(res, str):\n                yield pytest.mark.skipif(True, reason=res)\n            else:\n                yield pytest.mark.skipif(\n                    not res, reason=f\"Compile-time support for {self.long_name} not present\"\n                )\n\n        if self.target_kind_enabled is not None:\n            target_kind = self.target_kind_enabled.split()[0]\n            yield pytest.mark.skipif(\n                all(enabled.split()[0] != target_kind for enabled in _tvm_test_targets()),\n                reason=(\n                    f\"{self.target_kind_enabled} tests disabled \"\n                    f\"by TVM_TEST_TARGETS environment variable\"\n                ),\n            )\n\n        if self.cmake_flag is not None:\n            yield pytest.mark.skipif(\n                not _cmake_flag_enabled(self.cmake_flag),\n                reason=(\n                    f\"{self.long_name} support not enabled.  \"\n                    f\"Set {self.cmake_flag} in config.cmake to enable.\"\n                ),\n            )\n\n    def _run_only_marks(self):\n        for parent in self.parent_features:\n            yield from self._all_features[parent]._run_only_marks()\n\n        if self.run_time_check is not None:\n            res = self.run_time_check()\n            if isinstance(res, str):\n                yield pytest.mark.skipif(True, reason=res)\n            else:\n                yield pytest.mark.skipif(\n                    not res, reason=f\"Run-time support for {self.long_name} not present\"\n                )\n\n        if self.target_kind_hardware is not None:\n            yield pytest.mark.skipif(\n                not tvm.device(self.target_kind_hardware).exist,\n                reason=f\"No device exists for target {self.target_kind_hardware}\",\n            )\n\n    def marks(self, support_required=\"compile-and-run\"):\n        \"\"\"Return a list of marks to be used\n\n        Parameters\n        ----------\n\n        support_required: str\n\n            Allowed values: \"compile-and-run\" (default),\n            \"compile-only\", or \"optional\".\n\n            See Feature.__call__ for details.\n        \"\"\"\n        if support_required not in [\"compile-and-run\", \"compile-only\", \"optional\"]:\n            raise ValueError(f\"Unknown feature support type: {support_required}\")\n\n        if support_required == \"compile-and-run\":\n            marks = itertools.chain(\n                self._run_only_marks(), self._compile_only_marks(), self._uses_marks()\n            )\n        elif support_required == \"compile-only\":\n            marks = itertools.chain(self._compile_only_marks(), self._uses_marks())\n        elif support_required == \"optional\":\n            marks = self._uses_marks()\n        else:\n            raise ValueError(f\"Unknown feature support type: {support_required}\")\n\n        return list(marks)\n\n    def __call__(self, func=None, *, support_required=\"compile-and-run\"):\n        \"\"\"Mark a pytest function as requiring this feature\n\n        Can be used either as a bare decorator, or as a decorator with\n        arguments.\n\n        Parameters\n        ----------\n\n        func: Callable\n\n            The pytest test function to be marked\n\n        support_required: str\n\n            Allowed values: \"compile-and-run\" (default),\n            \"compile-only\", or \"optional\".\n\n            If \"compile-and-run\", the test case is marked as using the\n            feature, and is skipped if the environment lacks either\n            compile-time or run-time support for the feature.\n\n            If \"compile-only\", the test case is marked as using the\n            feature, and is skipped if the environment lacks\n            compile-time support.\n\n            If \"optional\", the test case is marked as using the\n            feature, but isn't skipped.  This is kept for backwards\n            compatibility for tests that use `enabled_targets()`, and\n            should be avoided in new test code.  Instead, prefer\n            parametrizing over the target using the `target` fixture.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n          @feature\n          def test_compile_and_run():\n              ...\n\n          @feature(compile_only=True)\n          def test_compile_only():\n              ...\n\n        \"\"\"\n\n        if support_required not in [\"compile-and-run\", \"compile-only\", \"optional\"]:\n            raise ValueError(f\"Unknown feature support type: {support_required}\")\n\n        def wrapper(func):\n            for mark in self.marks(support_required=support_required):\n                func = mark(func)\n            return func\n\n        if func is None:\n            return wrapper\n\n        return wrapper(func)\n\n    @classmethod\n    def require(cls, name, support_required=\"compile-and-run\"):\n        \"\"\"Returns a decorator that marks a test as requiring a feature\n\n        Parameters\n        ----------\n\n        name: str\n\n            The name of the feature that is used by the test\n\n        support_required: str\n\n            Allowed values: \"compile-and-run\" (default),\n            \"compile-only\", or \"optional\".\n\n            See Feature.__call__ for details.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n          @Feature.require(\"cuda\")\n          def test_compile_and_run():\n              ...\n\n          @Feature.require(\"cuda\", compile_only=True)\n          def test_compile_only():\n              ...\n        \"\"\"\n        return cls._all_features[name](support_required=support_required)\n\n\ndef _any_gpu_exists():\n    return (\n        tvm.cuda().exist\n        or tvm.rocm().exist\n        or tvm.opencl().exist\n        or tvm.metal().exist\n        or tvm.vulkan().exist\n    )\n\n\n# Mark a test as requiring llvm to run\nrequires_llvm = Feature(\n    \"llvm\", \"LLVM\", cmake_flag=\"USE_LLVM\", target_kind_enabled=\"llvm\", target_kind_hardware=\"llvm\"\n)\n\n# Mark a test as requiring a GPU to run.\nrequires_gpu = Feature(\"gpu\", run_time_check=_any_gpu_exists)\n\n# Mark to differentiate tests that use the GPU in some capacity.\n#\n# These tests will be run on CPU-only test nodes and on test nodes with GPUs.\n# To mark a test that must have a GPU present to run, use\n# :py:func:`tvm.testing.requires_gpu`.\nuses_gpu = requires_gpu(support_required=\"optional\")\n\n# Mark a test as requiring the x86 Architecture to run.\nrequires_x86 = Feature(\n    \"x86\", \"x86 Architecture\", run_time_check=lambda: platform.machine() == \"x86_64\"\n)\n\n# Mark a test as requiring the CUDA runtime.\nrequires_cuda = Feature(\n    \"cuda\",\n    \"CUDA\",\n    cmake_flag=\"USE_CUDA\",\n    target_kind_enabled=\"cuda\",\n    target_kind_hardware=\"cuda\",\n    parent_features=\"gpu\",\n)\n\n# Mark a test as requiring a tensorcore to run\nrequires_tensorcore = Feature(\n    \"tensorcore\",\n    \"NVIDIA Tensor Core\",\n    run_time_check=lambda: tvm.cuda().exist and nvcc.have_tensorcore(tvm.cuda().compute_version),\n    parent_features=\"cuda\",\n)\n\n# Mark a test as requiring the cuDNN library.\nrequires_cudnn = Feature(\"cudnn\", \"cuDNN\", cmake_flag=\"USE_CUDNN\", parent_features=\"cuda\")\n\n# Mark a test as requiring the cuBLAS library.\nrequires_cublas = Feature(\"cublas\", \"cuBLAS\", cmake_flag=\"USE_CUBLAS\", parent_features=\"cuda\")\n\n# Mark a test as requiring the NVPTX compilation on the CUDA runtime\nrequires_nvptx = Feature(\n    \"nvptx\",\n    \"NVPTX\",\n    target_kind_enabled=\"nvptx\",\n    target_kind_hardware=\"nvptx\",\n    parent_features=[\"llvm\", \"cuda\"],\n)\n\n# Mark a test as requiring the CUDA Graph Feature\nrequires_cudagraph = Feature(\n    \"cudagraph\",\n    \"CUDA Graph\",\n    target_kind_enabled=\"cuda\",\n    compile_time_check=nvcc.have_cudagraph,\n    parent_features=\"cuda\",\n)\n\n# Mark a test as requiring the OpenCL runtime\nrequires_opencl = Feature(\n    \"opencl\",\n    \"OpenCL\",\n    cmake_flag=\"USE_OPENCL\",\n    target_kind_enabled=\"opencl\",\n    target_kind_hardware=\"opencl\" if \"RPC_TARGET\" not in os.environ else None,\n    parent_features=\"gpu\" if \"RPC_TARGET\" not in os.environ else None,\n)\n\n# Mark a test as requiring the rocm runtime\nrequires_rocm = Feature(\n    \"rocm\",\n    \"ROCm\",\n    cmake_flag=\"USE_ROCM\",\n    target_kind_enabled=\"rocm\",\n    target_kind_hardware=\"rocm\",\n    parent_features=\"gpu\",\n)\n\n# Mark a test as requiring the metal runtime\nrequires_metal = Feature(\n    \"metal\",\n    \"Metal\",\n    cmake_flag=\"USE_METAL\",\n    target_kind_enabled=\"metal\",\n    target_kind_hardware=\"metal\",\n    parent_features=\"gpu\",\n)\n\n# Mark a test as requiring the vulkan runtime\nrequires_vulkan = Feature(\n    \"vulkan\",\n    \"Vulkan\",\n    cmake_flag=\"USE_VULKAN\",\n    target_kind_enabled=\"vulkan\",\n    target_kind_hardware=\"vulkan\",\n    parent_features=\"gpu\",\n)\n\n# Mark a test as requiring OpenCLML support in build.\nrequires_openclml = Feature(\n    \"OpenCLML\",\n    \"CLML\",\n    cmake_flag=\"USE_CLML\",\n    target_kind_enabled=\"opencl\",\n)\n\n\n# Mark a test as requiring microTVM to run\nrequires_micro = Feature(\"micro\", \"MicroTVM\", cmake_flag=\"USE_MICRO\")\n\n# Mark a test as requiring CUTLASS to run\nrequires_cutlass = Feature(\"cutlass\", \"CUTLASS\", cmake_flag=\"USE_CUTLASS\")\n\n# Mark a test as requiring rpc to run\nrequires_rpc = Feature(\"rpc\", \"RPC\", cmake_flag=\"USE_RPC\")\n\n# Mark a test as requiring Arm(R) Ethos(TM)-N to run\nrequires_ethosn = Feature(\"ethosn\", \"Arm(R) Ethos(TM)-N\", cmake_flag=\"USE_ETHOSN\")\n\n# Mark a test as requiring libtorch to run\nrequires_libtorch = Feature(\"libtorch\", \"LibTorch\", cmake_flag=\"USE_LIBTORCH\")\n\n# Mark a test as requiring Hexagon to run\nrequires_hexagon = Feature(\n    \"hexagon\",\n    \"Hexagon\",\n    cmake_flag=\"USE_HEXAGON\",\n    target_kind_enabled=\"hexagon\",\n    compile_time_check=hexagon._compile_time_check,\n    run_time_check=hexagon._run_time_check,\n    parent_features=\"llvm\",\n)\n\n# Mark a test as requiring the CMSIS NN library\nrequires_cmsisnn = Feature(\"cmsisnn\", \"CMSIS NN\", cmake_flag=\"USE_CMSISNN\")\n\n\ndef _corstone300_compile_time_check():\n    if shutil.which(\"arm-none-eabi-gcc\") is None:\n        return \"ARM embedded toolchain unavailable\"\n    return True\n\n\n# Mark a test as requiring the corstone300 FVP\nrequires_corstone300 = Feature(\n    \"corstone300\",\n    \"Corstone-300\",\n    compile_time_check=_corstone300_compile_time_check,\n    parent_features=\"cmsisnn\",\n)\n\n# Mark a test as requiring Vitis AI to run\nrequires_vitis_ai = Feature(\"vitis_ai\", \"Vitis AI\", cmake_flag=\"USE_VITIS_AI\")\n\n\ndef _arm_dot_supported():\n    arch = platform.machine()\n\n    if arch not in [\"arm64\", \"aarch64\"]:\n        return False\n\n    if sys.platform.startswith(\"darwin\"):\n        cpu_info = subprocess.check_output(\"sysctl -a\", shell=True).strip().decode()\n        for line in cpu_info.split(\"\\n\"):\n            if line.startswith(\"hw.optional.arm.FEAT_DotProd\"):\n                return bool(int(line.split(\":\", 1)[1]))\n    elif sys.platform.startswith(\"linux\"):\n        return True\n\n    return False\n\n\ndef _is_intel():\n    # Only linux is supported for now.\n    if sys.platform.startswith(\"linux\"):\n        with open(\"/proc/cpuinfo\", \"r\") as content:\n            return \"Intel\" in content.read()\n\n    return False\n\n\ndef _has_vnni():\n    arch = platform.machine()\n    # Only linux is supported for now.\n    if arch == \"x86_64\" and sys.platform.startswith(\"linux\"):\n        with open(\"/proc/cpuinfo\", \"r\") as content:\n            return \"avx512_vnni\" in content.read()\n\n    return False\n\n\nrequires_arm_dot = Feature(\"arm_dot\", \"ARM dot product\", run_time_check=_arm_dot_supported)\n\n\nrequires_cascadelake = Feature(\n    \"cascadelake\", \"x86 CascadeLake\", run_time_check=lambda: _has_vnni() and _is_intel()\n)\n\n\ndef _cmake_flag_enabled(flag):\n    flag = tvm.support.libinfo()[flag]\n\n    # Because many of the flags can be library flags, we check if the\n    # flag is not disabled, rather than checking if it is enabled.\n    return flag.lower() not in [\"off\", \"false\", \"0\"]\n\n\ndef _tvm_test_targets():\n    target_str = os.environ.get(\"TVM_TEST_TARGETS\", \"\").strip()\n    if target_str:\n        # Use dict instead of set for de-duplication so that the\n        # targets stay in the order specified.\n        return list({t.strip(): None for t in target_str.split(\";\") if t.strip()})\n\n    return DEFAULT_TEST_TARGETS\n\n\ndef _compose(args, decs):\n    \"\"\"Helper to apply multiple markers\"\"\"\n    if len(args) > 0:\n        f = args[0]\n        for d in reversed(decs):\n            f = d(f)\n        return f\n    return decs\n\n\nslow = pytest.mark.skipif(\n    SKIP_SLOW_TESTS,\n    reason=\"Skipping slow test since the SKIP_SLOW_TESTS environment variable is 'true'\",\n)\n\n\ndef requires_nvcc_version(major_version, minor_version=0, release_version=0):\n    \"\"\"Mark a test as requiring at least a specific version of nvcc.\n\n    Unit test marked with this decorator will run only if the\n    installed version of NVCC is at least `(major_version,\n    minor_version, release_version)`.\n\n    This also marks the test as requiring a cuda support.\n\n    Parameters\n    ----------\n    major_version: int\n\n        The major version of the (major,minor,release) version tuple.\n\n    minor_version: int\n\n        The minor version of the (major,minor,release) version tuple.\n\n    release_version: int\n\n        The release version of the (major,minor,release) version tuple.\n\n    \"\"\"\n\n    try:\n        nvcc_version = nvcc.get_cuda_version()\n    except RuntimeError:\n        nvcc_version = (0, 0, 0)\n\n    min_version = (major_version, minor_version, release_version)\n    version_str = \".\".join(str(v) for v in min_version)\n    requires = [\n        pytest.mark.skipif(nvcc_version < min_version, reason=f\"Requires NVCC >= {version_str}\"),\n        *requires_cuda.marks(),\n    ]\n\n    def inner(func):\n        return _compose([func], requires)\n\n    return inner\n\n\ndef requires_cuda_compute_version(major_version, minor_version=0):\n    \"\"\"Mark a test as requiring at least a compute architecture\n\n    Unit test marked with this decorator will run only if the CUDA\n    compute architecture of the GPU is at least `(major_version,\n    minor_version)`.\n\n    This also marks the test as requiring a cuda support.\n\n    Parameters\n    ----------\n    major_version: int\n\n        The major version of the (major,minor) version tuple.\n\n    minor_version: int\n\n        The minor version of the (major,minor) version tuple.\n    \"\"\"\n    min_version = (major_version, minor_version)\n    try:\n        arch = tvm.contrib.nvcc.get_target_compute_version()\n        compute_version = tvm.contrib.nvcc.parse_compute_version(arch)\n    except ValueError:\n        # No GPU present.  This test will be skipped from the\n        # requires_cuda() marks as well.\n        compute_version = (0, 0)\n\n    min_version_str = \".\".join(str(v) for v in min_version)\n    compute_version_str = \".\".join(str(v) for v in compute_version)\n    requires = [\n        pytest.mark.skipif(\n            compute_version < min_version,\n            reason=f\"Requires CUDA compute >= {min_version_str}, but have {compute_version_str}\",\n        ),\n        *requires_cuda.marks(),\n    ]\n\n    def inner(func):\n        return _compose([func], requires)\n\n    return inner\n\n\ndef skip_if_32bit(reason):\n    def decorator(*args):\n        if \"32bit\" in platform.architecture()[0]:\n            return _compose(args, [pytest.mark.skip(reason=reason)])\n\n        return _compose(args, [])\n\n    return decorator\n\n\ndef requires_package(*packages):\n    \"\"\"Mark a test as requiring python packages to run.\n\n    If the packages listed are not available, tests marked with\n    `requires_package` will appear in the pytest results as being skipped.\n    This is equivalent to using ``foo = pytest.importorskip('foo')`` inside\n    the test body.\n\n    Parameters\n    ----------\n    packages : List[str]\n\n        The python packages that should be available for the test to\n        run.\n\n    Returns\n    -------\n    mark: pytest mark\n\n        The pytest mark to be applied to unit tests that require this\n\n    \"\"\"\n\n    def has_package(package):\n        try:\n            __import__(package)\n            return True\n        except ImportError:\n            return False\n\n    marks = [\n        pytest.mark.skipif(not has_package(package), reason=f\"Cannot import '{package}'\")\n        for package in packages\n    ]\n\n    def wrapper(func):\n        for mark in marks:\n            func = mark(func)\n        return func\n\n    return wrapper\n\n\ndef parametrize_targets(*args):\n\n    \"\"\"Parametrize a test over a specific set of targets.\n\n    Use this decorator when you want your test to be run over a\n    specific set of targets and devices.  It is intended for use where\n    a test is applicable only to a specific target, and is\n    inapplicable to any others (e.g. verifying target-specific\n    assembly code matches known assembly code).  In most\n    circumstances, :py:func:`tvm.testing.exclude_targets` or\n    :py:func:`tvm.testing.known_failing_targets` should be used\n    instead.\n\n    If used as a decorator without arguments, the test will be\n    parametrized over all targets in\n    :py:func:`tvm.testing.enabled_targets`.  This behavior is\n    automatically enabled for any target that accepts arguments of\n    ``target`` or ``dev``, so the explicit use of the bare decorator\n    is no longer needed, and is maintained for backwards\n    compatibility.\n\n    Parameters\n    ----------\n    f : function\n        Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:,\n        where `xxxxxxxxx` is any name.\n    targets : list[str], optional\n        Set of targets to run against. If not supplied,\n        :py:func:`tvm.testing.enabled_targets` will be used.\n\n    Example\n    -------\n    >>> @tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\n    >>> def test_mytest(target, dev):\n    >>>     ...  # do something\n    \"\"\"\n\n    # Backwards compatibility, when used as a decorator with no\n    # arguments implicitly parametrizes over \"target\".  The\n    # parametrization is now handled by _auto_parametrize_target, so\n    # this use case can just return the decorated function.\n    if len(args) == 1 and callable(args[0]):\n        return args[0]\n\n    return pytest.mark.parametrize(\"target\", list(args), scope=\"session\")\n\n\ndef exclude_targets(*args):\n    \"\"\"Exclude a test from running on a particular target.\n\n    Use this decorator when you want your test to be run over a\n    variety of targets and devices (including cpu and gpu devices),\n    but want to exclude some particular target or targets.  For\n    example, a test may wish to be run against all targets in\n    tvm.testing.enabled_targets(), except for a particular target that\n    does not support the capabilities.\n\n    Applies pytest.mark.skipif to the targets given.\n\n    Parameters\n    ----------\n    f : function\n        Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:,\n        where `xxxxxxxxx` is any name.\n    targets : list[str]\n        Set of targets to exclude.\n\n    Example\n    -------\n    >>> @tvm.testing.exclude_targets(\"cuda\")\n    >>> def test_mytest(target, dev):\n    >>>     ...  # do something\n\n    Or\n\n    >>> @tvm.testing.exclude_targets(\"llvm\", \"cuda\")\n    >>> def test_mytest(target, dev):\n    >>>     ...  # do something\n\n    \"\"\"\n\n    def wraps(func):\n        func.tvm_excluded_targets = args\n        return func\n\n    return wraps\n\n\ndef known_failing_targets(*args):\n    \"\"\"Skip a test that is known to fail on a particular target.\n\n    Use this decorator when you want your test to be run over a\n    variety of targets and devices (including cpu and gpu devices),\n    but know that it fails for some targets.  For example, a newly\n    implemented runtime may not support all features being tested, and\n    should be excluded.\n\n    Applies pytest.mark.xfail to the targets given.\n\n    Parameters\n    ----------\n    f : function\n        Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:,\n        where `xxxxxxxxx` is any name.\n    targets : list[str]\n        Set of targets to skip.\n\n    Example\n    -------\n    >>> @tvm.testing.known_failing_targets(\"cuda\")\n    >>> def test_mytest(target, dev):\n    >>>     ...  # do something\n\n    Or\n\n    >>> @tvm.testing.known_failing_targets(\"llvm\", \"cuda\")\n    >>> def test_mytest(target, dev):\n    >>>     ...  # do something\n\n    \"\"\"\n\n    def wraps(func):\n        func.tvm_known_failing_targets = args\n        return func\n\n    return wraps\n\n\ndef parameter(*values, ids=None, by_dict=None):\n    \"\"\"Convenience function to define pytest parametrized fixtures.\n\n    Declaring a variable using ``tvm.testing.parameter`` will define a\n    parametrized pytest fixture that can be used by test\n    functions. This is intended for cases that have no setup cost,\n    such as strings, integers, tuples, etc.  For cases that have a\n    significant setup cost, please use :py:func:`tvm.testing.fixture`\n    instead.\n\n    If a test function accepts multiple parameters defined using\n    ``tvm.testing.parameter``, then the test will be run using every\n    combination of those parameters.\n\n    The parameter definition applies to all tests in a module.  If a\n    specific test should have different values for the parameter, that\n    test should be marked with ``@pytest.mark.parametrize``.\n\n    Parameters\n    ----------\n    values : Any\n\n       A list of parameter values.  A unit test that accepts this\n       parameter as an argument will be run once for each parameter\n       given.\n\n    ids : List[str], optional\n\n       A list of names for the parameters.  If None, pytest will\n       generate a name from the value.  These generated names may not\n       be readable/useful for composite types such as tuples.\n\n    by_dict : Dict[str, Any]\n\n       A mapping from parameter name to parameter value, to set both the\n       values and ids.\n\n    Returns\n    -------\n    function\n       A function output from pytest.fixture.\n\n    Example\n    -------\n    >>> size = tvm.testing.parameter(1, 10, 100)\n    >>> def test_using_size(size):\n    >>>     ... # Test code here\n\n    Or\n\n    >>> shape = tvm.testing.parameter((5,10), (512,1024), ids=['small','large'])\n    >>> def test_using_size(shape):\n    >>>     ... # Test code here\n\n    Or\n\n    >>> shape = tvm.testing.parameter(by_dict={'small': (5,10), 'large': (512,1024)})\n    >>> def test_using_size(shape):\n    >>>     ... # Test code here\n\n    \"\"\"\n\n    if by_dict is not None:\n        if values or ids:\n            raise RuntimeError(\n                \"Use of the by_dict parameter cannot be used alongside positional arguments\"\n            )\n\n        ids, values = zip(*by_dict.items())\n\n    # Optional cls parameter in case a parameter is defined inside a\n    # class scope.\n    @pytest.fixture(params=values, ids=ids)\n    def as_fixture(*_cls, request):\n        return request.param\n\n    return as_fixture\n\n\n_parametrize_group = 0\n\n\ndef parameters(*value_sets, ids=None):\n    \"\"\"Convenience function to define pytest parametrized fixtures.\n\n    Declaring a variable using tvm.testing.parameters will define a\n    parametrized pytest fixture that can be used by test\n    functions. Like :py:func:`tvm.testing.parameter`, this is intended\n    for cases that have no setup cost, such as strings, integers,\n    tuples, etc.  For cases that have a significant setup cost, please\n    use :py:func:`tvm.testing.fixture` instead.\n\n    Unlike :py:func:`tvm.testing.parameter`, if a test function\n    accepts multiple parameters defined using a single call to\n    ``tvm.testing.parameters``, then the test will only be run once\n    for each set of parameters, not for all combinations of\n    parameters.\n\n    These parameter definitions apply to all tests in a module.  If a\n    specific test should have different values for some parameters,\n    that test should be marked with ``@pytest.mark.parametrize``.\n\n    Parameters\n    ----------\n    values : List[tuple]\n\n       A list of parameter value sets.  Each set of values represents\n       a single combination of values to be tested.  A unit test that\n       accepts parameters defined will be run once for every set of\n       parameters in the list.\n\n    ids : List[str], optional\n\n       A list of names for the parameter sets.  If None, pytest will\n       generate a name from each parameter set.  These generated names may\n       not be readable/useful for composite types such as tuples.\n\n    Returns\n    -------\n    List[function]\n       Function outputs from pytest.fixture.  These should be unpacked\n       into individual named parameters.\n\n    Example\n    -------\n    >>> size, dtype = tvm.testing.parameters( (16,'float32'), (512,'float16') )\n    >>> def test_feature_x(size, dtype):\n    >>>     # Test code here\n    >>>     assert( (size,dtype) in [(16,'float32'), (512,'float16')])\n\n    \"\"\"\n    global _parametrize_group\n    parametrize_group = _parametrize_group\n    _parametrize_group += 1\n\n    outputs = []\n    for param_values in zip(*value_sets):\n\n        # Optional cls parameter in case a parameter is defined inside a\n        # class scope.\n        def fixture_func(*_cls, request):\n            return request.param\n\n        fixture_func.parametrize_group = parametrize_group\n        fixture_func.parametrize_values = param_values\n        fixture_func.parametrize_ids = ids\n        outputs.append(pytest.fixture(fixture_func))\n\n    return outputs\n\n\ndef fixture(func=None, *, cache_return_value=False):\n    \"\"\"Convenience function to define pytest fixtures.\n\n    This should be used as a decorator to mark functions that set up\n    state before a function.  The return value of that fixture\n    function is then accessible by test functions as that accept it as\n    a parameter.\n\n    Fixture functions can accept parameters defined with\n    :py:func:`tvm.testing.parameter`.\n\n    By default, the setup will be performed once for each unit test\n    that uses a fixture, to ensure that unit tests are independent.\n    If the setup is expensive to perform, then the\n    cache_return_value=True argument can be passed to cache the setup.\n    The fixture function will be run only once (or once per parameter,\n    if used with tvm.testing.parameter), and the same return value\n    will be passed to all tests that use it.  If the environment\n    variable TVM_TEST_DISABLE_CACHE is set to a non-zero value, it\n    will disable this feature and no caching will be performed.\n\n    Example\n    -------\n    >>> @tvm.testing.fixture\n    >>> def cheap_setup():\n    >>>     return 5 # Setup code here.\n    >>>\n    >>> def test_feature_x(target, dev, cheap_setup)\n    >>>     assert(cheap_setup == 5) # Run test here\n\n    Or\n\n    >>> size = tvm.testing.parameter(1, 10, 100)\n    >>>\n    >>> @tvm.testing.fixture\n    >>> def cheap_setup(size):\n    >>>     return 5*size # Setup code here, based on size.\n    >>>\n    >>> def test_feature_x(cheap_setup):\n    >>>     assert(cheap_setup in [5, 50, 500])\n\n    Or\n\n    >>> @tvm.testing.fixture(cache_return_value=True)\n    >>> def expensive_setup():\n    >>>     time.sleep(10) # Setup code here\n    >>>     return 5\n    >>>\n    >>> def test_feature_x(target, dev, expensive_setup):\n    >>>     assert(expensive_setup == 5)\n\n    \"\"\"\n\n    force_disable_cache = bool(int(os.environ.get(\"TVM_TEST_DISABLE_CACHE\", \"0\")))\n    cache_return_value = cache_return_value and not force_disable_cache\n\n    # Deliberately at function scope, so that caching can track how\n    # many times the fixture has been used.  If used, the cache gets\n    # cleared after the fixture is no longer needed.\n    scope = \"function\"\n\n    def wraps(func):\n        if cache_return_value:\n            func = _fixture_cache(func)\n        func = pytest.fixture(func, scope=scope)\n        return func\n\n    if func is None:\n        return wraps\n\n    return wraps(func)\n\n\nclass _DeepCopyAllowedClasses(dict):\n    def __init__(self, allowed_class_list):\n        self.allowed_class_list = allowed_class_list\n        super().__init__()\n\n    def get(self, key, *args, **kwargs):\n        \"\"\"Overrides behavior of copy.deepcopy to avoid implicit copy.\n\n        By default, copy.deepcopy uses a dict of id->object to track\n        all objects that it has seen, which is passed as the second\n        argument to all recursive calls.  This class is intended to be\n        passed in instead, and inspects the type of all objects being\n        copied.\n\n        Where copy.deepcopy does a best-effort attempt at copying an\n        object, for unit tests we would rather have all objects either\n        be copied correctly, or to throw an error.  Classes that\n        define an explicit method to perform a copy are allowed, as\n        are any explicitly listed classes.  Classes that would fall\n        back to using object.__reduce__, and are not explicitly listed\n        as safe, will throw an exception.\n\n        \"\"\"\n        obj = ctypes.cast(key, ctypes.py_object).value\n        cls = type(obj)\n        if (\n            cls in copy._deepcopy_dispatch\n            or issubclass(cls, type)\n            or getattr(obj, \"__deepcopy__\", None)\n            or copyreg.dispatch_table.get(cls)\n            or cls.__reduce__ is not object.__reduce__\n            or cls.__reduce_ex__ is not object.__reduce_ex__\n            or cls in self.allowed_class_list\n        ):\n            return super().get(key, *args, **kwargs)\n\n        rfc_url = (\n            \"https://github.com/apache/tvm-rfcs/blob/main/rfcs/0007-parametrized-unit-tests.md\"\n        )\n        raise TypeError(\n            (\n                f\"Cannot copy fixture of type {cls.__name__}.  TVM fixture caching \"\n                \"is limited to objects that explicitly provide the ability \"\n                \"to be copied (e.g. through __deepcopy__, __getstate__, or __setstate__),\"\n                \"and forbids the use of the default `object.__reduce__` and \"\n                \"`object.__reduce_ex__`.  For third-party classes that are \"\n                \"safe to use with copy.deepcopy, please add the class to \"\n                \"the arguments of _DeepCopyAllowedClasses in tvm.testing._fixture_cache.\\n\"\n                \"\\n\"\n                f\"For discussion on this restriction, please see {rfc_url}.\"\n            )\n        )\n\n\ndef _fixture_cache(func):\n    cache = {}\n\n    # Can't use += on a bound method's property.  Therefore, this is a\n    # list rather than a variable so that it can be accessed from the\n    # pytest_collection_modifyitems().\n    num_tests_use_this_fixture = [0]\n\n    num_times_fixture_used = 0\n\n    # Using functools.lru_cache would require the function arguments\n    # to be hashable, which wouldn't allow caching fixtures that\n    # depend on numpy arrays.  For example, a fixture that takes a\n    # numpy array as input, then calculates uses a slow method to\n    # compute a known correct output for that input.  Therefore,\n    # including a fallback for serializable types.\n    def get_cache_key(*args, **kwargs):\n        try:\n            hash((args, kwargs))\n            return (args, kwargs)\n        except TypeError as e:\n            pass\n\n        try:\n            return pickle.dumps((args, kwargs))\n        except TypeError as e:\n            raise TypeError(\n                \"TVM caching of fixtures requires arguments to the fixture \"\n                \"to be either hashable or serializable\"\n            ) from e\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if num_tests_use_this_fixture[0] == 0:\n            raise RuntimeError(\n                \"Fixture use count is 0.  \"\n                \"This can occur if tvm.testing.plugin isn't registered.  \"\n                \"If using outside of the TVM test directory, \"\n                \"please add `pytest_plugins = ['tvm.testing.plugin']` to your conftest.py\"\n            )\n\n        try:\n            cache_key = get_cache_key(*args, **kwargs)\n\n            try:\n                cached_value = cache[cache_key]\n            except KeyError:\n                cached_value = cache[cache_key] = func(*args, **kwargs)\n\n            yield copy.deepcopy(\n                cached_value,\n                # allowed_class_list should be a list of classes that\n                # are safe to copy using copy.deepcopy, but do not\n                # implement __deepcopy__, __reduce__, or\n                # __reduce_ex__.\n                _DeepCopyAllowedClasses(allowed_class_list=[]),\n            )\n\n        finally:\n            # Clear the cache once all tests that use a particular fixture\n            # have completed.\n            nonlocal num_times_fixture_used\n            num_times_fixture_used += 1\n            if num_times_fixture_used >= num_tests_use_this_fixture[0]:\n                cache.clear()\n\n    # Set in the pytest_collection_modifyitems(), by _count_num_fixture_uses\n    wrapper.num_tests_use_this_fixture = num_tests_use_this_fixture\n\n    return wrapper\n\n\ndef identity_after(x, sleep):\n    \"\"\"Testing function to return identity after sleep\n\n    Parameters\n    ----------\n    x : int\n        The input value.\n\n    sleep : float\n        The amount of time to sleep\n\n    Returns\n    -------\n    x : object\n        The original value\n    \"\"\"\n    if sleep:\n        time.sleep(sleep)\n    return x\n\n\ndef terminate_self():\n    \"\"\"Testing function to terminate the process.\"\"\"\n    sys.exit(-1)\n\n\ndef is_ampere_or_newer():\n    \"\"\"Check if the target environment has an NVIDIA Ampere GPU or newer.\"\"\"\n    arch = tvm.contrib.nvcc.get_target_compute_version()\n    major, _ = tvm.contrib.nvcc.parse_compute_version(arch)\n    return major >= 8\n\n\ndef install_request_hook(depth: int) -> None:\n    \"\"\"Add a wrapper around urllib.request for CI tests\"\"\"\n    if not IS_IN_CI:\n        return\n\n    # https://sphinx-gallery.github.io/stable/faq.html#why-is-file-not-defined-what-can-i-use\n    base = None\n    msg = \"\"\n    try:\n        base = __file__\n        msg += f\"found file {__file__}\\n\"\n    except NameError:\n        msg += f\"no file\\n\"\n\n    if base is None:\n        hook_script_dir = Path.cwd().resolve()\n        msg += \"used path.cwd()\\n\"\n    else:\n        hook_script_dir = Path(base).resolve().parent\n        msg += \"used base()\\n\"\n\n    msg += f\"using depth {depth}\\n\"\n    if depth <= 0:\n        raise ValueError(f\"depth less than 1 not supported, found: {depth}\")\n\n    # Go up the parent directories\n    while depth > 0:\n        msg += f\"[depth={depth}] dir={hook_script_dir}\\n\"\n        hook_script_dir = hook_script_dir.parent\n        depth -= 1\n\n    # Ensure the specified dir is valid\n    hook_script_dir = hook_script_dir / \"tests\" / \"scripts\" / \"request_hook\"\n    if not hook_script_dir.exists():\n        raise RuntimeError(f\"Directory {hook_script_dir} does not exist:\\n{msg}\")\n\n    # Import the hook and start it up (it's not included here directly to avoid\n    # keeping a database of URLs inside the tvm Python package\n    sys.path.append(str(hook_script_dir))\n    # This import is intentionally delayed since it should only happen in CI\n    import request_hook  # pylint: disable=import-outside-toplevel\n\n    request_hook.init()\n\n\ndef fetch_model_from_url(\n    url: str,\n    model_format: str,\n    sha256: str,\n) -> Tuple[tvm.ir.module.IRModule, dict]:\n    \"\"\"Testing function to fetch a model from a URL and return it as a Relay\n    model. Downloaded files are cached for future re-use.\n\n    Parameters\n    ----------\n    url : str\n        The URL or list of URLs to try downloading the model from.\n\n    model_format: str\n        The file extension of the model format used.\n\n    sha256 : str\n        The sha256 hex hash to compare the downloaded model against.\n\n    Returns\n    -------\n    (mod, params) : object\n        The Relay representation of the downloaded model.\n    \"\"\"\n\n    rel_path = f\"model_{sha256}.{model_format}\"\n    file = tvm.contrib.download.download_testdata(url, rel_path, overwrite=False)\n\n    # Check SHA-256 hash\n    file_hash = hashlib.sha256()\n    with open(file, \"rb\") as f:\n        for block in iter(lambda: f.read(2**24), b\"\"):\n            file_hash.update(block)\n\n    if file_hash.hexdigest() != sha256:\n        raise FileNotFoundError(\"SHA-256 hash for model does not match\")\n\n    tvmc_model = load_model(file, model_format)\n    return tvmc_model.mod, tvmc_model.params\n\n\ndef _mark_parameterizations(*params, marker_fn, reason):\n    \"\"\"\n    Mark tests with a nodeid parameters that exactly matches one in params.\n    Useful for quickly marking tests as xfail when they have a large\n    combination of parameters.\n    \"\"\"\n    params = set(params)\n\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(request, *args, **kwargs):\n            if \"[\" in request.node.name and \"]\" in request.node.name:\n                # Strip out the test name and the [ and ] brackets\n                params_from_name = request.node.name[len(request.node.originalname) + 1 : -1]\n                if params_from_name in params:\n                    marker_fn(\n                        reason=f\"{marker_fn.__name__} on nodeid {request.node.nodeid}: \" + reason\n                    )\n\n            return func(request, *args, **kwargs)\n\n        return wrapper\n\n    return decorator\n\n\ndef xfail_parameterizations(*xfail_params, reason):\n    return _mark_parameterizations(*xfail_params, marker_fn=pytest.xfail, reason=reason)\n\n\ndef skip_parameterizations(*skip_params, reason):\n    return _mark_parameterizations(*skip_params, marker_fn=pytest.skip, reason=reason)\n\n\ndef main():\n    test_file = inspect.getsourcefile(sys._getframe(1))\n    sys.exit(pytest.main([test_file] + sys.argv[1:]))\n\n\nclass CompareBeforeAfter:\n    \"\"\"Utility for comparing before/after of TIR transforms\n\n    A standard framework for writing tests that take a TIR PrimFunc as\n    input, apply a transformation, then either compare against an\n    expected output or assert that the transformation raised an error.\n    A test should subclass CompareBeforeAfter, defining class members\n    `before`, `transform`, and `expected`.  CompareBeforeAfter will\n    then use these members to define a test method and test fixture.\n\n    `transform` may be one of the following.\n\n    - An instance of `tvm.ir.transform.Pass`\n\n    - A method that takes no arguments and returns a `tvm.ir.transform.Pass`\n\n    - A pytest fixture that returns a `tvm.ir.transform.Pass`\n\n    `before` may be any one of the following.\n\n    - An instance of `tvm.tir.PrimFunc`.  This is allowed, but is not\n      the preferred method, as any errors in constructing the\n      `PrimFunc` occur while collecting the test, preventing any other\n      tests in the same file from being run.\n\n    - An TVMScript function, without the ``@T.prim_func`` decoration.\n      The ``@T.prim_func`` decoration will be applied when running the\n      test, rather than at module import.\n\n    - A method that takes no arguments and returns a `tvm.tir.PrimFunc`\n\n    - A pytest fixture that returns a `tvm.tir.PrimFunc`\n\n    `expected` may be any one of the following.  The type of\n    `expected` defines the test being performed.  If `expected`\n    provides a `tvm.tir.PrimFunc`, the result of the transformation\n    must match `expected`.  If `expected` is an exception, then the\n    transformation must raise that exception type.\n\n    - Any option supported for `before`.\n\n    - The `Exception` class object, or a class object that inherits\n      from `Exception`.\n\n    - A method that takes no arguments and returns `Exception` or a\n      class object that inherits from `Exception`.\n\n    - A pytest fixture that returns `Exception` or an class object\n      that inherits from `Exception`.\n\n    Examples\n    --------\n\n    .. python::\n\n        class TestRemoveIf(tvm.testing.CompareBeforeAfter):\n            transform = tvm.tir.transform.Simplify()\n\n            def before(A: T.Buffer[1, \"int32\"]):\n                if True:\n                    A[0] = 42\n                else:\n                    A[0] = 5\n\n            def expected(A: T.Buffer[1, \"int32\"]):\n                A[0] = 42\n\n    \"\"\"\n\n    def __init_subclass__(cls):\n        if hasattr(cls, \"before\"):\n            cls.before = cls._normalize_before(cls.before)\n        if hasattr(cls, \"expected\"):\n            cls.expected = cls._normalize_expected(cls.expected)\n        if hasattr(cls, \"transform\"):\n            cls.transform = cls._normalize_transform(cls.transform)\n\n    @classmethod\n    def _normalize_ir_module(cls, func):\n        if isinstance(func, tvm.tir.PrimFunc):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                return func\n\n        elif cls._is_method(func):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                return func(self)\n\n        elif inspect.isclass(func):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                func_dict = {}\n                for name, method in func.__dict__.items():\n                    if name.startswith(\"_\"):\n                        pass\n                    elif isinstance(method, tvm.ir.function.BaseFunc):\n                        func_dict[name] = method\n                    else:\n                        source_code = \"@T.prim_func\\n\" + textwrap.dedent(inspect.getsource(method))\n                        prim_func = tvm.script.from_source(source_code)\n                        func_dict[name] = prim_func\n                return tvm.IRModule(func_dict)\n\n        else:\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                source_code = \"@T.prim_func\\n\" + textwrap.dedent(inspect.getsource(func))\n                return tvm.script.from_source(source_code)\n\n        return pytest.fixture(inner)\n\n    @classmethod\n    def _normalize_before(cls, func):\n        if hasattr(func, \"_pytestfixturefunction\"):\n            return func\n        else:\n            return cls._normalize_ir_module(func)\n\n    @classmethod\n    def _normalize_expected(cls, func):\n        if hasattr(func, \"_pytestfixturefunction\"):\n            return func\n\n        elif inspect.isclass(func) and issubclass(func, Exception):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                return func\n\n            return pytest.fixture(inner)\n\n        else:\n            return cls._normalize_ir_module(func)\n\n    @classmethod\n    def _normalize_transform(cls, transform):\n        def apply(module_transform):\n            def inner(obj):\n                if isinstance(obj, tvm.IRModule):\n                    return module_transform(obj)\n                elif isinstance(obj, tvm.tir.PrimFunc):\n                    mod = tvm.IRModule({\"main\": obj})\n                    mod = module_transform(mod)\n                    return mod[\"main\"]\n                else:\n                    raise TypeError(f\"Expected IRModule or PrimFunc, but received {type(obj)}\")\n\n            return inner\n\n        if hasattr(transform, \"_pytestfixturefunction\"):\n\n            if not hasattr(cls, \"_transform_orig\"):\n                cls._transform_orig = transform\n\n            def inner(self, _transform_orig):\n                # pylint: disable=unused-argument\n                return apply(_transform_orig)\n\n        elif isinstance(transform, tvm.ir.transform.Pass):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                return apply(transform)\n\n        elif cls._is_method(transform):\n\n            def inner(self):\n                # pylint: disable=unused-argument\n                return apply(transform(self))\n\n        else:\n\n            raise TypeError(\n                \"Expected transform to be a tvm.ir.transform.Pass, or a method returning a Pass\"\n            )\n\n        return pytest.fixture(inner)\n\n    @staticmethod\n    def _is_method(func):\n        sig = inspect.signature(func)\n        return \"self\" in sig.parameters\n\n    def test_compare(self, before, expected, transform):\n        \"\"\"Unit test to compare the expected TIR PrimFunc to actual\"\"\"\n\n        def pprint(name, obj):\n            script = obj.script()\n            if isinstance(obj, tvm.IRModule):\n                return script.replace(\"class Module\", f\"class {name}\")\n            else:\n                return script.replace(\"def func\", f\"def {name}\")\n\n        if inspect.isclass(expected) and issubclass(expected, Exception):\n            with pytest.raises(expected):\n                after = transform(before)\n\n                # This portion through pytest.fail isn't strictly\n                # necessary, but gives a better error message that\n                # includes the before/after.\n                before_str = pprint(\"before\", before)\n                after_str = pprint(\"after\", after)\n\n                pytest.fail(\n                    msg=(\n                        f\"Expected {expected.__name__} to be raised from transformation, \"\n                        f\"instead received TIR\\n:{before_str}\\n{after_str}\"\n                    )\n                )\n\n        elif isinstance(expected, (tvm.tir.PrimFunc, tvm.ir.IRModule)):\n            after = transform(before)\n\n            try:\n                tvm.ir.assert_structural_equal(after, expected)\n            except ValueError as err:\n                before_str = pprint(\"before\", before)\n                after_str = pprint(\"after\", after)\n                expected_str = pprint(\"expected\", expected)\n                raise ValueError(\n                    f\"TIR after transformation did not match expected:\\n\"\n                    f\"{before_str}\\n{after_str}\\n{expected_str}\"\n                ) from err\n\n        else:\n            raise TypeError(\n                f\"tvm.testing.CompareBeforeAfter requires the `expected` fixture \"\n                f\"to return either `Exception`, an `Exception` subclass, \"\n                f\"or an instance of `tvm.tir.PrimFunc`.  \"\n                f\"Instead, received {type(expected)}.\"\n            )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\"Namespace for Tensor-level IR\"\"\"\nfrom tvm.ir import PrimExpr\nfrom tvm.runtime import const\n\nfrom .buffer import Buffer, decl_buffer, DataProducer\nfrom .data_layout import Layout, BijectiveLayout, bijective_layout, layout\nfrom .expr import Var, SizeVar, Reduce, FloatImm, IntImm, StringImm, Cast\nfrom .expr import Add, Sub, Mul, Div, Mod, FloorDiv, FloorMod\nfrom .expr import Min, Max, EQ, NE, LT, LE, GT, GE, And, Or, Not\nfrom .expr import Select, BufferLoad, ProducerLoad, Load, Ramp, Broadcast, Shuffle\nfrom .expr import Call, CallEffectKind, Let, IterVar, CommReducer, Any\n\nfrom .stmt import Stmt, LetStmt, AssertStmt, ForKind, For, While\nfrom .stmt import (\n    BufferStore,\n    BufferRealize,\n    Store,\n    ProducerStore,\n    Allocate,\n    AllocateConst,\n    AttrStmt,\n    DeclBuffer,\n)\n\nfrom .stmt import ProducerRealize, SeqStmt\nfrom .stmt import IfThenElse, Evaluate, Prefetch, stmt_seq, stmt_list\nfrom .stmt import BufferRegion, MatchBufferRegion, Block, BlockRealize\n\nfrom .function import PrimFunc, TensorIntrin, IndexMap\n\nfrom .op import call_packed_lowered, call_cpacked_lowered\nfrom .op import call_packed, call_cpacked, call_intrin, call_pure_extern, call_extern\nfrom .op import call_llvm_intrin, call_llvm_pure_intrin, ret, all, any, min_value, max_value, trace\nfrom .op import tvm_check_return\nfrom .op import tvm_stack_alloca, tvm_stack_make_shape, tvm_stack_make_array\nfrom .op import tvm_tuple, tvm_struct_get, tvm_struct_set\nfrom .op import address_of, lookup_param, assume, undef\nfrom .op import tvm_thread_allreduce, type_annotation, tvm_access_ptr, tvm_throw_last_error\nfrom .op import (\n    tvm_load_matrix_sync,\n    tvm_store_matrix_sync,\n    tvm_mma_sync,\n    tvm_bmma_sync,\n    tvm_fill_fragment,\n)\nfrom .op import ptx_mma, ptx_mma_sp, mma_store, mma_fill\nfrom .op import ptx_ldmatrix, ptx_cp_async, ptx_commit_group, ptx_wait_group\nfrom .op import vectorlow, vectorhigh, vectorcombine\nfrom .op import infinity, reinterpret\nfrom .op import exp, exp2, exp10, log, log2, log10, log1p, ldexp, clz\nfrom .op import sin, sinh, asin, asinh\nfrom .op import cos, cosh, acos, acosh\nfrom .op import tan, tanh, atan, atan2, atanh\nfrom .op import erf, sigmoid, sqrt, rsqrt, floor, ceil, hypot\nfrom .op import trunc, abs, round, nextafter, nearbyint, power, popcount, fmod, if_then_else\nfrom .op import likely, isnan, isnullptr, isfinite, isinf, copysign\nfrom .op import div, indexdiv, indexmod, truncdiv, truncmod, floordiv, floormod, ceildiv\nfrom .op import comm_reducer, min, max, sum\nfrom .op import q_multiply_shift, q_multiply_shift_per_axis, shift_left, shift_right\nfrom .op import TVMBackendAllocWorkspace, TVMBackendFreeWorkspace\nfrom .op import start_profile_intrinsic, end_profile_intrinsic\nfrom .generic import add, subtract, multiply\n\nfrom .schedule import StmtSRef, BlockScope, ScheduleState, Schedule, ScheduleError\n\nfrom . import schedule\nfrom . import ir_builder\nfrom . import transform\nfrom . import analysis\nfrom . import stmt_functor\nfrom . import usmp\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/analysis/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace of all TIR analysis utils.\"\"\"\n# pylint: disable=wildcard-import, invalid-name\n\nfrom .analysis import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/analysis/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.analysis\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir.analysis\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/analysis/analysis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Wrapping existing analysis utils.\"\"\"\n# pylint: disable=invalid-name\nfrom typing import Dict, List, Union\n\nfrom tvm import Object\nfrom tvm.ir import IRModule\nfrom tvm.tir.expr import Var\nfrom tvm.tir.stmt import Block, BufferRegion, PrimExpr\n\nfrom .. import Buffer, Stmt\nfrom ..function import PrimFunc\nfrom . import _ffi_api\n\n\ndef expr_deep_equal(lhs: PrimExpr, rhs: PrimExpr) -> bool:\n    \"\"\"Deeply compare two nested expressions.\n\n    Parameters\n    ----------\n    lhs : PrimExpr\n        The left operand.\n\n    rhs : PrimExpr\n        The right operand.\n\n    Returns\n    -------\n    result : bool\n        The comparison result\n\n    Note\n    ----\n\n    This function does not remap variable bindings, it will not\n    return true for (let x = 1 in x + 1) vs (let y = 1 in y + 1), unless x.same_as(y).\n    Use py:func:`tvm.ir.structural_equal` to handle structural variable remapping.\n\n    Due to the restriction of not remapping variables, this function can run\n    faster than StructuralEqual and can be used as a utility function during arithmetic\n    simplifications.\n\n    Always consider py:func:`tvm.ir.structural_equal` first, which handles\n    the structural remapping.\n\n    See Also\n    --------\n    tvm.ir.structural_equal\n    \"\"\"\n    return _ffi_api.expr_deep_equal(lhs, rhs)  # type: ignore\n\n\ndef verify_ssa(func: PrimFunc) -> bool:\n    \"\"\"Verify if the func is in SSA form.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The module to be verified.\n\n    Returns\n    -------\n    result : bool\n        The result of verification.\n    \"\"\"\n    return _ffi_api.verify_ssa(func)  # type: ignore\n\n\ndef verify_memory(func: PrimFunc) -> bool:\n    \"\"\"Verify if func contains illegal host side direct memory access.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The module to be verified.\n\n    Returns\n    -------\n    result : bool\n        The result of verification.\n    \"\"\"\n    return _ffi_api.verify_memory(func)  # type: ignore\n\n\ndef verify_gpu_code(func: PrimFunc, constraints: Dict[str, int]) -> None:\n    \"\"\"Verify if module contains illegal host side direct memory access.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The module to be verified.\n\n    constraints : Dict[str, int]\n        The attribute constraints.\n\n    Returns\n    -------\n    result : bool\n        The result of verification.\n    \"\"\"\n    return _ffi_api.verify_gpu_code(func, constraints)  # type: ignore\n\n\ndef get_block_access_region(\n    block: Block, buffer_var_map: Dict[Var, Buffer]\n) -> List[List[BufferRegion]]:\n    \"\"\"Detect which regions of tensors in this block are read or written to.\n       Regions are sorted by order of appearance in the AST.\n\n    Parameters\n    ----------\n    block: tvm.tir.Block\n        The block in which we are detecting read/write regions.\n\n    buffer_var_map : Dict[Var, Buffer]\n        The outside buffers which may access the block. Mapping from buffer var to the buffer\n\n    Returns\n    -------\n    result : List[List[BufferRegion]]\n        Array of access regions. There are three arrays of BufferRegion:\n            - first: read regions\n            - second: write regions\n            - third: opaque regions\n    \"\"\"\n    return _ffi_api.GetBlockAccessRegion(block, buffer_var_map)  # type: ignore\n\n\ndef get_block_read_write_region(\n    block: Block, buffer_var_map: Dict[Var, Buffer]\n) -> List[List[BufferRegion]]:\n    \"\"\"Auto detect the block read/write region according to its body stmt.\n       An opaque access will be counted as both a read and a write access\n\n    Parameters\n    ----------\n    block: tvm.tir.Block\n        The block in which we are detecting read/write regions.\n\n    buffer_var_map : Dict[Var, Buffer]\n        The outside buffers which may access the block. Mapping from buffer var to the buffer\n\n    Returns\n    -------\n    result : List[List[BufferRegion]]\n        An array only consisting of the read regions and write regions of the input block\n    \"\"\"\n    return _ffi_api.GetBlockReadWriteRegion(block, buffer_var_map)  # type: ignore\n\n\ndef calculate_workspace_bytes(func: PrimFunc, workspace_byte_alignment: int) -> int:\n    \"\"\"Calculate the workspace size in bytes needed by the TIR allocates inside the TIR\n    PrimFunc.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to be detected.\n    workspace_byte_alignment : int\n        The byte alignment required for each tensor\n\n    Returns\n    -------\n    result : int\n        Workspace size in bytes.\n    \"\"\"\n    return _ffi_api.calculate_workspace_bytes(func, workspace_byte_alignment)  # type: ignore\n\n\ndef calculate_constant_bytes(func: PrimFunc, constant_byte_alignment: int) -> int:\n    \"\"\"Calculate the constant size in bytes needed by the TIR allocates inside the TIR\n    PrimFunc.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to be detected.\n    constant_byte_alignment : int\n        The byte alignment required for each tensor\n\n    Returns\n    -------\n    result : int\n        Workspace size in bytes.\n    \"\"\"\n    return _ffi_api.calculate_constant_bytes(func, constant_byte_alignment)  # type: ignore\n\n\ndef detect_buffer_access_lca(func: PrimFunc) -> Dict[Buffer, Stmt]:\n    \"\"\"Detect the lowest common ancestor(LCA) of buffer access, including both high-level\n    access(BufferLoad, BufferStore) and low-level access(Load, Store and opaque access).\n    The LCA may be a For loop or a Block.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to be detected.\n\n    Returns\n    -------\n    result : Dict[Buffer, Stmt]\n        Map from buffer to the LCA of all access to it.\n    \"\"\"\n    return _ffi_api.detect_buffer_access_lca(func)  # type: ignore # pylint: disable=no-member\n\n\ndef estimate_tir_flops(stmt_or_mod: Union[Stmt, IRModule]) -> float:\n    \"\"\"Estimate the FLOPs of a TIR fragment.\n\n    Parameters\n    ----------\n    stmt_or_mod: Union[Stmt, IRModule]\n        The TIR fragment or IRModule to be estimated.\n\n    Returns\n    -------\n    flops: float\n        The estimated FLOPs.\n    \"\"\"\n    return _ffi_api.EstimateTIRFlops(stmt_or_mod)  # type: ignore # pylint: disable=no-member\n\n\n# NOTE: relay_func_type in the following two functions should be relay.FuncType however that would\n# introduce a cycling dependency. We make do with Object.\n\n\ndef get_prim_func_arg_and_result_memory_constraints(\n    func: PrimFunc, relay_func_type: Object\n) -> List[str]:\n    \"\"\"Returns the memory (aka storage) scope constraints for all the arguments and result\n    of func. However the result will be w.r.t. the func's representation as a Relay Function\n    of relay_func_type before lowering and conversion to DPS.\n\n    Visible for testing.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to retrieve constraints from.\n\n    relay_func_type: tvm.relay.FuncType\n        The type of the Relay Function from which the func was derived.\n\n    Returns\n    -------\n    result: List[AnyStr]\n        Memory scope constraints for funcs args and result in Relay form. The empty string\n        denotes 'no constraint'.\n    \"\"\"\n    return _ffi_api.GetPrimFuncArgAndResultMemoryConstraints(  # type: ignore # pylint: disable=no-member\n        func, relay_func_type\n    )\n\n\ndef apply_prim_func_arg_and_result_memory_constraints(\n    func: PrimFunc, relay_func_type: Object, arg_and_result_memory_scopes: List[str]\n) -> PrimFunc:\n    \"\"\"Returns func written to capture the memory (aka storage) scope constraints\n    for each of the func's parameters given by arg_and_result_memory_scopes. However,\n    arg_and_result_memory_scopes should be w.r.t. the func's representation as a Relay\n    Function of relay_func_type before lowering and conversion to DPS.\n\n    Visible for testing.\n\n    CAUTION: This is experimental. The resulting PrimFunc may not have fully accounted\n    for all new memory scopes.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to retrieve constraints from.\n\n    relay_func_type: tvm.relay.FuncType\n        The type of the Relay Function from which the func was derived.\n\n    arg_and_result_memory_scopes: Array[AnyStr]\n        Memory constraints for funcs args and result in Relay form. The empty string denotes\n        'no constraint'.\n\n    Returns\n    -------\n    result: tvm.tir.PrimFunc\n        The rewritten func.\n    \"\"\"\n    return _ffi_api.ApplyPrimFuncArgAndResultMemoryConstraints(  # type: ignore # pylint: disable=no-member\n        func, relay_func_type, arg_and_result_memory_scopes\n    )\n\n\ndef verify_well_formed(func: PrimFunc, assert_mode: bool = True) -> bool:\n    \"\"\"Verify if the given TIR is well-formed. The verification includes:\n        - Check if expressions not contain vars that is defined outside the block.\n\n    Parameters\n    ----------\n    func: tvm.tir.PrimFunc\n        The function to be verified.\n\n    assert_mode: bool\n        The indicator if it raises an error when the function is not well-formed.\n\n    Returns\n    -------\n    result: bool\n        Whether it is a well-formed TIR function.\n    \"\"\"\n    return _ffi_api.VerifyWellFormed(func, assert_mode)  # type: ignore # pylint: disable=no-member\n\n\ndef OOBChecker():\n    \"\"\"Detect out of bounds memory access in arrays.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.OOBChecker()  # type: ignore\n\n\ndef find_anchor_block(mod: IRModule) -> Block:\n    \"\"\"Find the \"anchor block\" of the given module.\n\n    We define the anchor block to be the block with (1) an init statement and (2) having\n    the biggest flops count. The latter condition is only used when there are multiple blocks\n    with an init statement.\n\n    For example, if the input module is conv2d + fused spatial blocks, conv2d is the anchor block.\n    The input module may not contain more than one such block. For example, a module having\n    two conv2d is not allowed as an input.\n\n    However, a module created from winograd convolution has multiple blocks with an init statement\n    (input transform, batched GEMM, and output transform). We use the second condition, the flops\n    count, to determine that the batched GEMM block is the anchor block.\n\n    Parameters\n    ----------\n    mod: tvm.ir.IRModule\n        The input TIR module.\n    Returns\n    -------\n    anchor_block: Block\n        The anchor block if found, None otherwise.\n    \"\"\"\n    return _ffi_api.find_anchor_block(mod)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Abstraction for array data structures.\"\"\"\nfrom numbers import Integral\n\nimport tvm._ffi\nfrom tvm._ffi.base import string_types\nfrom tvm.ir import PointerType, PrimExpr, PrimType, Range\nfrom tvm.runtime import Object, convert\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"tir.Buffer\")\nclass Buffer(Object):\n    \"\"\"Symbolic data buffer in TVM.\n\n    Buffer provide a way to represent data layout\n    specialization of data structure in TVM.\n\n    Do not construct directly, use :py:func:`~decl_buffer` instead.\n    See the documentation of :py:func:`decl_buffer` for more details.\n\n    See Also\n    --------\n    decl_buffer : Declare a buffer\n    \"\"\"\n\n    READ = 1\n    WRITE = 2\n\n    def access_ptr(self, access_mask, ptr_type=\"handle\", content_lanes=1, offset=0, extent=None):\n        \"\"\"Get an access pointer to the head of buffer.\n\n        This is the recommended method to get buffer data\n        ptress when interacting with external functions.\n\n        Parameters\n        ----------\n        access_mask : int\n            The access pattern MASK. Indicate whether the\n            access will read or write to the data content.\n\n        ptr_type : str, optional\n            The data type of the result pointer. Do not specify\n            unless we want to cast pointer to specific type.\n\n        content_lanes: int, optional\n            The number of lanes for the data type. This value\n            is greater than one for vector types.\n\n        offset: Expr, optional\n            The offset of pointer. We can use it to offset by\n            the number of elements from the address of ptr.\n\n        extent: Expr, optional\n            The extent of pointer.\n\n        Examples\n        --------\n        .. code-block:: python\n\n          # Get access ptr for read\n          buffer.access_ptr(\"r\")\n          # Get access ptr for read/write with bitmask\n          buffer.access_ptr(Buffer.READ | Buffer.WRITE)\n          # Get access ptr for read/write with str flag\n          buffer.access_ptr(\"rw\")\n          # Get access ptr for read with offset\n          buffer.access_ptr(\"r\", offset = 100)\n          # Get access ptr for read with extent\n          buffer.access_ptr(\"r\", extent = 100)\n        \"\"\"\n        if isinstance(access_mask, string_types):\n            mask = 0\n            for value in access_mask:\n                if value == \"r\":\n                    mask = mask | Buffer.READ\n                elif value == \"w\":\n                    mask = mask | Buffer.WRITE\n                else:\n                    raise ValueError(\"Unknown access_mask %s\" % access_mask)\n            access_mask = mask\n        offset = convert(offset)\n        extent = convert(extent)\n        return _ffi_api.BufferAccessPtr(\n            self, access_mask, ptr_type, content_lanes, offset, extent  # type: ignore\n        )\n\n    def vload(self, begin, dtype=None):\n        \"\"\"Generate an Expr that loads dtype from begin index.\n\n        Parameters\n        ----------\n        begin : Array of Expr\n            The beginning index in unit of Buffer.dtype\n\n        dtype : str\n            The data type to be loaded,\n            can be vector type which have lanes that is multiple of Buffer.dtype\n\n        Returns\n        -------\n        load : Expr\n            The corresponding load expression.\n        \"\"\"\n        begin = (begin,) if isinstance(begin, (int, PrimExpr)) else begin\n        dtype = dtype if dtype else self.dtype\n        return _ffi_api.BufferVLoad(self, begin, dtype)  # type: ignore\n\n    def vstore(self, begin, value):\n        \"\"\"Generate a Stmt that store value into begin index.\n\n        Parameters\n        ----------\n        begin : Array of Expr\n            The beginning index in unit of Buffer.dtype\n\n        value : Expr\n            The value to be stored.\n\n        Returns\n        -------\n        store : Stmt\n            The corresponding store stmt.\n        \"\"\"\n        begin = (begin,) if isinstance(begin, (int, PrimExpr)) else begin\n        return _ffi_api.BufferVStore(self, begin, value)  # type: ignore\n\n    def scope(self):\n        \"\"\"Return the storage scope associated with this buffer.\n        Returns\n        -------\n        scope : str\n            The storage scope associated with this buffer.\n        \"\"\"\n        return _ffi_api.BufferStorageScope(self)  # type: ignore\n\n    def get_flattened_buffer(self):\n        \"\"\"Generate a Buffer that is a flattened version of this buffer.\n\n        Returns\n        -------\n        flattened : Buffer\n            The corresponding flat buffer.\n        \"\"\"\n        return _ffi_api.BufferGetFlattenedBuffer(self)  # type: ignore\n\n    def offset_of(self, indices):\n        \"\"\"Determine the offset of the provided indices in the flattened buffer.\n\n        Parameters\n        ----------\n        indices : Union[PrimExpr, List[PrimExpr]]\n\n            The indices of the element in the original buffer.\n\n        Returns\n        -------\n        flattened_indices: List[PrimExpr]\n\n            The offset indices of the element in the flattened buffer.\n        \"\"\"\n        return _ffi_api.BufferOffsetOf(self, indices)  # type: ignore\n\n    def __getitem__(self, indices):\n        from ..arith import Analyzer  # pylint: disable=import-outside-toplevel\n        from .expr import BufferLoad, Ramp  # pylint: disable=import-outside-toplevel\n        from .stmt import BufferRegion  # pylint: disable=import-outside-toplevel\n\n        if not isinstance(indices, (tuple, list)):\n            indices = [indices]\n        has_slice = any(isinstance(i, slice) for i in indices)\n        has_step = any(isinstance(i, slice) and i.step is not None for i in indices)\n        analyzer = Analyzer()\n        if has_slice and not has_step:\n            region = []\n            for i, index in enumerate(indices):\n                if isinstance(index, slice):\n                    start = 0 if index.start is None else index.start\n                    stop = self.shape[i] if index.stop is None else index.stop\n                    region.append(Range.from_min_extent(start, analyzer.simplify(stop - start)))\n                else:\n                    region.append(Range.from_min_extent(index, 1))\n            return BufferRegion(self, region)\n        else:\n            expr_indices = []\n            for index in indices:\n                if isinstance(index, slice):\n                    start = 0 if index.start is None else index.start\n                    stop = self.shape[i] if index.stop is None else index.stop\n                    step = 1 if index.step is None else index.step\n                    lanes = analyzer.simplify((stop - start + step - 1) // step)\n                    if lanes == 1:\n                        expr_indices.append(start)\n                    else:\n                        expr_indices.append(Ramp(start, step, int(lanes)))\n                else:\n                    expr_indices.append(index)\n            return BufferLoad(self, expr_indices)\n\n\ndef decl_buffer(\n    shape,\n    dtype=None,\n    name=\"buffer\",\n    data=None,\n    strides=None,\n    elem_offset=None,\n    scope=\"\",\n    data_alignment=-1,\n    offset_factor=0,\n    buffer_type=\"\",\n    axis_separators=None,\n    span=None,\n):\n    \"\"\"Declare a new symbolic buffer.\n\n    Normally buffer is created automatically during lower and build.\n    This is only needed if user want to specify their own buffer layout.\n\n    See the note below for detailed discussion on usage of buffer.\n\n    Parameters\n    ----------\n    shape : tuple of Expr\n        The shape of the buffer.\n\n    dtype : str, optional\n        The data type of the buffer.\n\n    name : str, optional\n        The name of the buffer.\n\n    data : Var, optional\n        The data pointer in the buffer.\n\n    strides: array of Expr\n        The stride of the buffer.\n\n    elem_offset: Expr, optional\n        The beginning offset of the array to data.\n        In terms of number of elements of dtype.\n\n    scope: str, optional\n        The storage scope of the buffer, if not global.\n        If scope equals empty string, it means it is global memory.\n\n    data_alignment: int, optional\n        The alignment of data pointer in bytes.\n        If -1 is passed, the alignment will be set to TVM's internal default.\n\n    offset_factor: int, optional\n        The factor of elem_offset field, when set,\n        elem_offset is required to be multiple of offset_factor.\n        If 0 is pssed, the alignment will be set to 1.\n        if non-zero is passed, we will created a Var for elem_offset if elem_offset is not None.\n\n    buffer_type: str, optional, {\"\", \"auto_broadcast\"}\n        auto_broadcast buffer allows one to implement broadcast computation\n        without considering whether dimension size equals to one.\n        TVM maps buffer[i][j][k] -> buffer[i][0][k] if dimension j's shape equals 1.\n\n    axis_separators : list of int, optional\n        If passed, a list of separators between groups of axes,\n        each of which is flattened to an output axis.  For flat\n        memory spaces, should either be None, or an empty list.\n\n    span: Optional[Span]\n        The location of the decl_buffer creation in the source.\n\n    Returns\n    -------\n    buffer : tvm.tir.Buffer\n        The created buffer\n\n    Example\n    -------\n    Here's an example of how broadcast buffer can be used to define a symbolic broadcast operation,\n\n    .. code-block:: python\n\n        m0, m1, m2 = te.var(\"m0\"), te.var(\"m1\"), te.var(\"m2\")\n        n0, n1, n2 = te.var(\"n0\"), te.var(\"n1\"), te.var(\"n2\")\n        o0, o1, o2 = te.var(\"o0\"), te.var(\"o1\"), te.var(\"o2\")\n        A = te.placeholder((m0, m1, m2), name='A')\n        B = te.placeholder((n0, n1, n2), name='B')\n        C = te.compute((o0, o1, o2), lambda i, j, k: A[i, j, k] + B[i, j, k], name='C')\n        Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name=\"Ab\", buffer_type=\"auto_broadcast\")\n        Bb = tvm.tir.decl_buffer(B.shape, B.dtype, name=\"Bb\", buffer_type=\"auto_broadcast\")\n        s = te.create_schedule(C.op)\n        fadd = tvm.build(s, [A, B, C], target='llvm', name='bcast_add', binds={A:Ab, B:Bb})\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=(2, 4, 3)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(2, 1, 3)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((2, 4, 3), dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    Note\n    ----\n    Buffer data structure reflects the DLTensor structure in dlpack.\n    While DLTensor data structure is very general, it is usually helpful\n    to create function that only handles specific case of data structure\n    and make compiled function benefit from it.\n\n    If user pass strides and elem_offset is passed as None\n    when constructing the function, then the function will be specialized\n    for the DLTensor that is compact and aligned.\n    If user pass a fully generic symbolic array to the strides,\n    then the resulting function becomes fully generic.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from .expr import Var\n\n    shape = (shape,) if isinstance(shape, (PrimExpr, Integral)) else shape\n    dtype = \"float32\" if dtype is None else dtype\n    strides = () if strides is None else strides\n\n    if axis_separators is None:\n        axis_separators = []\n\n    if offset_factor != 0 and elem_offset is None:\n        shape_dtype = shape[0].dtype if shape and hasattr(shape[0], \"dtype\") else \"int32\"\n        elem_offset = Var(\"%s_elem_offset\" % name, shape_dtype)\n    if data is None:\n        # Bool is represented as uint1 in the IR, but stored as int8\n        storage_type = PrimType(dtype)\n        storage_type = PrimType(\"int8\") if storage_type.dtype == \"bool\" else storage_type\n        data = Var(name, PointerType(storage_type, scope), span)\n    return _ffi_api.Buffer(  # type: ignore\n        data,\n        dtype,\n        shape,\n        strides,\n        elem_offset,\n        name,\n        data_alignment,\n        offset_factor,\n        buffer_type,\n        axis_separators,\n        span,\n    )\n\n\n@tvm._ffi.register_object(\"tir.DataProducer\")\nclass DataProducer(Object):\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/data_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Data layout.\"\"\"\nfrom typing import Union\n\nimport tvm._ffi\n\nfrom tvm.runtime import Object\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"tir.Layout\")\nclass Layout(Object):\n    \"\"\"Layout is composed of upper cases, lower cases and numbers,\n    where upper case indicates a primal axis and\n    the corresponding lower case with factor size indicates the subordinate axis.\n    For example, NCHW16c can describe a 5-D tensor of\n    [batch_size, channel, height, width, channel_block].\n    Here subordinate axis channel_block=16 is the factor size of the primal axis C (channel).\n\n    See Also\n    --------\n    layout : Declare a layout\n    \"\"\"\n\n    def __len__(self):\n        return _ffi_api.LayoutNdim(self)  # type: ignore\n\n    def __contains__(self, axis):\n        return len(axis) == 1 and axis[0].isalpha() and axis[0] in self.name\n\n    def __getitem__(self, index):\n        if index >= len(self):\n            raise IndexError(\"Layout index out of range\")\n        return _ffi_api.LayoutGetItem(self, index)  # type: ignore\n\n    def index_of(self, axis):\n        \"\"\"Get the index of an axis\n\n        Parameters\n        ----------\n        axis : str\n            The axis name, need to be [a-z,A-Z]\n\n        Returns\n        -------\n        index : int\n            The index of the axis, -1 if not found.\n        \"\"\"\n        return _ffi_api.LayoutIndexOf(self, axis)  # type: ignore\n\n    def factor_of(self, axis):\n        \"\"\"Get the factor size of the subordinate axis.\n\n        Parameters\n        ----------\n        axis : str\n            The axis name, need to be [a-z,A-Z]\n\n        Returns\n        -------\n        factor : int\n            the size of the subordinate-axis of axis (if axis is a primal-axis),\n            or the size of axis itself (if axis is a subordinate-axis).\n            Return -1 if axis is not in the layout.\n        \"\"\"\n        return _ffi_api.LayoutFactorOf(self, axis)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.BijectiveLayout\")\nclass BijectiveLayout(Object):\n    \"\"\"Bijective mapping for two layouts (src-layout and dst-layout).\n    It provides shape and index conversion between each other.\n\n    Do not construct directly, use :any:`bijective_layout` instead.\n    See the documentation of :any:`bijective_layout` for more details.\n\n    Parameters\n    ----------\n    src_layout : str or Layout\n        source layout.\n\n    dst_layout : str or Layout\n        destination layout.\n\n    See Also\n    --------\n    bijective_layout : Declare a layout\n    \"\"\"\n\n    def forward_index(self, index):\n        \"\"\"Given the indices of the src-layout, infer the dst index.\n\n        Parameters\n        ----------\n        index: Array of Expr\n            The indices in src-layout.\n\n        Returns\n        -------\n        dst_index: Array of Expr\n            The inferred indices in dst-layout.\n        \"\"\"\n        return _ffi_api.BijectiveLayoutForwardIndex(self, index)  # type: ignore\n\n    def backward_index(self, index):\n        \"\"\"Given the indices of the dst-layout, infer the src index.\n\n        Parameters\n        ----------\n        index: Array of Expr\n            The indices in dst-layout.\n\n        Returns\n        -------\n        src_index: Array of Expr\n            The inferred indices in src-layout.\n        \"\"\"\n        return _ffi_api.BijectiveLayoutBackwardIndex(self, index)  # type: ignore\n\n    def forward_shape(self, shape):\n        \"\"\"Given the shape of the src-layout, infer the dst shape.\n\n        Parameters\n        ----------\n        shape: Array of Expr\n            The shape in src-layout.\n\n        Returns\n        -------\n        dst_shape: Array of Expr\n            The inferred shape in dst-layout.\n        \"\"\"\n        return _ffi_api.BijectiveLayoutForwardShape(self, shape)  # type: ignore\n\n    def backward_shape(self, shape):\n        \"\"\"Given the shape of the dst-layout, infer the src shape.\n\n        Parameters\n        ----------\n        shape: Array of Expr\n            The shape in dst-layout.\n\n        Returns\n        -------\n        src_shape: Array of Expr\n            The inferred shape in src-layout.\n        \"\"\"\n        return _ffi_api.BijectiveLayoutBackwardShape(self, shape)  # type: ignore\n\n\ndef layout(layout_str: str) -> Layout:\n    \"\"\"Create a layout node from a string.\n\n    Parameters\n    ----------\n    layout_str : str\n        A layout representation is composed of upper cases, lower cases and numbers,\n        where upper case indicates a primal axis and\n        the corresponding lower case with factor size indicates the subordinate axis.\n        For example, NCHW16c can describe a 5-D tensor of\n        [batch_size, channel, height, width, channel_block].\n        Here subordinate axis channel_block=16 is the factor size of\n        the primal axis C (channel).\n\n    Returns\n    -------\n    layout : Layout\n        The created layout\n    \"\"\"\n    return _ffi_api.Layout(layout_str)  # type: ignore\n\n\ndef bijective_layout(\n    src_layout: Union[str, Layout], dst_layout: Union[str, Layout]\n) -> BijectiveLayout:\n    \"\"\"Create a bijective layout mapping.\n\n    Parameters\n    ----------\n    src_layout : str or Layout\n        source layout.\n\n    dst_layout : str or Layout\n        destination layout.\n\n    Returns\n    -------\n    bijective_layout : BijectiveLayout\n        The created bijective layout\n    \"\"\"\n    if isinstance(src_layout, str):\n        src_layout = layout(src_layout)\n    if isinstance(dst_layout, str):\n        dst_layout = layout(dst_layout)\n    return _ffi_api.BijectiveLayout(src_layout, dst_layout)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/expr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin\n\"\"\"TIR expression nodes.\n\nEach expression node have subfields that can be visited from python side.\nFor example, you can use addexp.a to get the left operand of an Add node.\n\n.. code-block:: python\n\n  x = tvm.tir.Var(\"n\", \"int32\")\n  y = x + 2\n  assert(isinstance(y, tvm.tir.Add))\n  assert(y.a == x)\n\"\"\"\nfrom typing import Optional, Union\nfrom tvm import ir\nimport tvm._ffi\nfrom tvm.ir.base import Span\n\nfrom tvm.runtime import Object, ObjectGeneric, DataType, DataTypeCode, const\nfrom tvm.ir import PrimExpr, Op\nimport tvm.ir._ffi_api\nfrom . import generic as _generic\nfrom . import _ffi_api\n\n\ndef div_ambiguity_error():\n    return RuntimeError(\n        \"TVM supports multiple types of integer divisions, \"\n        + \"please call div, indexdiv/indexmod, floordiv/floormod \"\n        + \" or truncdiv/truncmod directly to avoid ambiguity in the code.\"\n    )\n\n\ndef _dtype_is_int(value):\n    if isinstance(value, int):\n        return True\n    return (\n        isinstance(value, ExprOp) and DataType(value.dtype).type_code == DataTypeCode.INT\n    )  # type: ignore\n\n\ndef _dtype_is_float(value):\n    if isinstance(value, float):\n        return True\n    return (\n        isinstance(value, ExprOp) and DataType(value.dtype).type_code == DataTypeCode.FLOAT\n    )  # type: ignore\n\n\nclass ExprOp(object):\n    \"\"\"Operator overloading for Expr like expressions.\"\"\"\n\n    # TODO(tkonolige): use inspect to add source information to these objects\n\n    def __add__(self, other):\n        return _generic.add(self, other)\n\n    def __radd__(self, other):\n        return _generic.add(other, self)\n\n    def __sub__(self, other):\n        return _generic.subtract(self, other)\n\n    def __rsub__(self, other):\n        return _generic.subtract(other, self)\n\n    def __mul__(self, other):\n        return _generic.multiply(self, other)\n\n    def __rmul__(self, other):\n        return _generic.multiply(other, self)\n\n    def __div__(self, other):\n        if _dtype_is_int(self) and _dtype_is_int(other):\n            raise div_ambiguity_error()\n        return _generic.divide(self, other)\n\n    def __rdiv__(self, other):\n        if _dtype_is_int(self) and _dtype_is_int(other):\n            raise div_ambiguity_error()\n        return _generic.divide(other, self)\n\n    def __truediv__(self, other):\n        if _dtype_is_int(self) and _dtype_is_int(other):\n            raise div_ambiguity_error()\n        return _generic.divide(self, other)\n\n    def __rtruediv__(self, other):\n        if _dtype_is_int(self) and _dtype_is_int(other):\n            raise div_ambiguity_error()\n        return _generic.divide(other, self)\n\n    def __floordiv__(self, other):\n        return _generic.floordiv(self, other)\n\n    def __rfloordiv__(self, other):\n        return _generic.floordiv(other, self, None)\n\n    def __mod__(self, other):\n        return _ffi_api._OpFloorMod(self, other, None)  # type: ignore\n\n    def __rmod__(self, other):\n        return _ffi_api._OpFloorMod(other, self, None)  # type: ignore\n\n    def __neg__(self):\n        neg_one = const(-1, self.dtype)  # type: ignore\n        return self.__mul__(neg_one)\n\n    def __lshift__(self, other):\n        return _ffi_api.left_shift(self, other, None)  # type: ignore\n\n    def __rlshift__(self, other):\n        return _ffi_api.left_shift(other, self, None)  # type: ignore\n\n    def __rshift__(self, other):\n        return _ffi_api.right_shift(self, other, None)  # type: ignore\n\n    def __rrshift__(self, other):\n        return _ffi_api.right_shift(other, self, None)  # type: ignore\n\n    def __and__(self, other):\n        return _ffi_api.bitwise_and(self, other, None)  # type: ignore\n\n    def __rand__(self, other):\n        return _ffi_api.bitwise_and(other, self, None)  # type: ignore\n\n    def __or__(self, other):\n        return _ffi_api.bitwise_or(self, other, None)  # type: ignore\n\n    def __ror__(self, other):\n        return _ffi_api.bitwise_or(other, self, None)  # type: ignore\n\n    def __xor__(self, other):\n        return _ffi_api.bitwise_xor(self, other, None)  # type: ignore\n\n    def __rxor__(self, other):\n        return _ffi_api.bitwise_xor(other, self, None)  # type: ignore\n\n    def __invert__(self):\n        if _dtype_is_float(self):\n            raise RuntimeError(\"Cannot use ~ operator on float type Expr.\")\n        return _ffi_api.bitwise_not(self, None)  # type: ignore\n\n    def __lt__(self, other):\n        return _ffi_api._OpLT(self, other, None)  # type: ignore\n\n    def __le__(self, other):\n        return _ffi_api._OpLE(self, other, None)  # type: ignore\n\n    def __eq__(self, other):\n        return EqualOp(self, other)\n\n    def __ne__(self, other):\n        return NotEqualOp(self, other)\n\n    def __gt__(self, other):\n        return _ffi_api._OpGT(self, other, None)  # type: ignore\n\n    def __ge__(self, other):\n        return _ffi_api._OpGE(self, other, None)  # type: ignore\n\n    def __nonzero__(self):\n        raise ValueError(\n            \"Cannot use and / or / not operator to Expr, hint: \"\n            + \"use tvm.tir.all / tvm.tir.any instead\"\n        )\n\n    def __bool__(self):\n        return self.__nonzero__()\n\n    def equal(self, other, span=None):\n        \"\"\"Build an equal check expression with other expr.\n\n        Parameters\n        ----------\n        other : PrimExpr\n            The other expression\n\n        span : Optional[Span]\n            The location of the cast in the source.\n\n        Returns\n        -------\n        ret : PrimExpr\n            The equality expression.\n        \"\"\"\n        return _ffi_api._OpEQ(self, other, span)  # type: ignore\n\n    def astype(self, dtype: str, span: Optional[Span] = None):\n        \"\"\"Cast the expression to other type.\n\n        Parameters\n        ----------\n        dtype : str\n            The type of new expression\n\n        span : Optional[Span]\n            The location of the cast in the source.\n\n        Returns\n        -------\n        expr : PrimExpr\n            Expression with new type\n        \"\"\"\n        return _generic.cast(self, dtype, span)\n\n\nclass EqualOp(ObjectGeneric, ExprOp):\n    \"\"\"Deferred equal operator.\n\n    This is used to support sugar that a == b can either\n    mean Object.same_as or Object.equal.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        Left operand.\n\n    b : PrimExpr\n        Right operand.\n\n    span : Optional[Span]\n        The location of the cast in the source.\n    \"\"\"\n\n    # This class is not manipulated by C++. So use python's identity check function is sufficient\n    same_as = object.__eq__\n\n    def __init__(self, a, b, span=None):\n        self.a = a\n        self.b = b\n        self.span = span\n\n    def __nonzero__(self):\n        return self.a.same_as(self.b)\n\n    def __bool__(self):\n        return self.__nonzero__()\n\n    def asobject(self):\n        \"\"\"Convert object.\"\"\"\n        return _ffi_api._OpEQ(self.a, self.b, self.span)  # type: ignore\n\n\nclass NotEqualOp(ObjectGeneric, ExprOp):\n    \"\"\"Deferred NE operator.\n\n    This is used to support sugar that a != b can either\n    mean not Object.same_as or make.NE.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        Left operand.\n\n    b : PrimExpr\n        Right operand.\n\n    span : Optional[Span]\n        The location of the cast in the source.\n    \"\"\"\n\n    # This class is not manipulated by C++. So use python's identity check function is sufficient\n    same_as = object.__eq__\n\n    def __init__(self, a, b, span=None):\n        self.a = a\n        self.b = b\n        self.span = span\n\n    def __nonzero__(self):\n        return not self.a.same_as(self.b)\n\n    def __bool__(self):\n        return self.__nonzero__()\n\n    def asobject(self):\n        \"\"\"Convert object.\"\"\"\n        return _ffi_api._OpNE(self.a, self.b, self.span)  # type: ignore\n\n\nclass IntImmEnum(ObjectGeneric):\n    \"\"\"Lazily evaluate an IntImm in case\n    the constructor is not available in runtime.\n\n    Parameters\n    ----------\n    value : int\n        The enum value\n\n    span : Optional[Span]\n        The location of the cast in the source.\n    \"\"\"\n\n    def __init__(self, value, span=None):\n        self.value = value\n        self.span = span\n\n    def asobject(self):\n        \"\"\"Convert object.\"\"\"\n        return IntImm(\"int32\", self.value, self.span)  # type: ignore\n\n\nclass PrimExprWithOp(ExprOp, PrimExpr):\n    \"\"\"Helper base class to inherit from PrimExpr.\"\"\"\n\n    # In Python3, We have to explicitly tell interpreter to retain __hash__ if we overide __eq__\n    # https://docs.python.org/3.1/reference/datamodel.html#object.__hash__\n    __hash__ = PrimExpr.__hash__\n\n\nclass ConstExpr(PrimExprWithOp):\n    pass\n\n\nclass BinaryOpExpr(PrimExprWithOp):\n    pass\n\n\nclass CmpExpr(PrimExprWithOp):\n    pass\n\n\nclass LogicalExpr(PrimExprWithOp):\n    pass\n\n\n@tvm._ffi.register_object(\"tir.Var\")\nclass Var(PrimExprWithOp):\n    \"\"\"Symbolic variable.\n\n    Parameters\n    ----------\n    name : str\n        The name\n\n    dtype : Union[str, tvm.irType]\n        The data type\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, name: str, dtype: Union[str, ir.Type], span: Optional[Span] = None):\n        self.__init_handle_by_constructor__(_ffi_api.Var, name, dtype, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.SizeVar\")\nclass SizeVar(Var):\n    \"\"\"Symbolic variable to represent a tensor index size\n       which is greater or equal to zero.\n\n    Parameters\n    ----------\n    name : str\n        The name\n\n    dtype : int\n        The data type\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    # pylint: disable=super-init-not-called\n    def __init__(self, name, dtype, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.SizeVar, name, dtype, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.IterVar\")\nclass IterVar(Object, ExprOp):\n    \"\"\"Represent iteration variable.\n\n    IterVar represents axis iterations in the computation.\n\n    Parameters\n    ----------\n    dom : Range\n        The domain of the iteration.\n\n    var : Union[Var, str]\n        The internal variable that is used for iteration.\n\n    iter_type : int\n        The iteration type.\n\n    thread_tag : str\n        The thread type tag.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n\n    See Also\n    --------\n    te.thread_axis: Create thread axis IterVar.\n    te.reduce_axis: Create reduce axis IterVar.\n    \"\"\"\n\n    DataPar = 0\n    ThreadIndex = 1\n    CommReduce = 2\n    Ordered = 3\n    DimInfo = 4\n    Unrolled = 5\n    Vectorized = 6\n    Parallelized = 7\n    Tensorized = 8\n\n    def __init__(self, dom, var, iter_type, thread_tag=\"\", span=None):\n        if dom is not None:\n            if isinstance(dom, (list, tuple)):\n                if len(dom) != 2:\n                    raise TypeError(\"need to be list of ranges\")\n                dom = tvm.ir.Range(dom[0], dom[1])\n\n            if not isinstance(dom, tvm.ir.Range):\n                raise TypeError(\"dom need to be Range\")\n\n        name = var if var is not None else \"iter\"\n        dtype = \"int32\" if dom is None else dom.extent.dtype\n        var = Var(name, dtype=dtype, span=span) if not isinstance(var, Var) else var\n        if dom is not None:\n            assert (\n                var.dtype == dom.extent.dtype\n            ), \"IterVar's Var dtype must match its domain's extent's dtype\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.IterVar, dom, var, iter_type, thread_tag, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.CommReducer\")\nclass CommReducer(Object):\n    \"\"\"Commutative reduce operator\n\n    Parameters\n    ----------\n    lhs : List[Var]\n       The left arguments of the reducer.\n\n    rhs : List[Var]\n       The right arguments of the reducer.\n\n    result : List[PrimExpr]\n       The reduction results.\n\n    identity_element : List[PrimExpr]\n       The identity elements.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, lhs, rhs, result, identity_element, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.CommReducer, lhs, rhs, result, identity_element, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Reduce\")\nclass Reduce(PrimExprWithOp):\n    \"\"\"Reduce node.\n\n    Parameters\n    ----------\n    combiner : CommReducer\n        The combiner.\n\n    src : list of Expr\n        The source expression.\n\n    rdom : list of IterVar\n        The iteration domain\n\n    condition : PrimExpr\n        The reduce condition.\n\n    value_index : int\n        The value index.\n\n    init : list of Expr\n        The initial value for output. This can be an int, float or ProducerLoad\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, combiner, src, rdom, condition, value_index, init=None, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Reduce, combiner, src, rdom, condition, value_index, init, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object\nclass FloatImm(ConstExpr):\n    \"\"\"Float constant.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type\n\n    value : float\n        The constant value.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, dtype, value, span=None):\n        self.__init_handle_by_constructor__(\n            tvm.ir._ffi_api.FloatImm, dtype, value, span  # type: ignore\n        )\n\n    def __float__(self):\n        return self.value\n\n\n@tvm._ffi.register_object\nclass IntImm(ConstExpr):\n    \"\"\"Int constant.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type\n\n    value : int\n        The constant value.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, dtype, value, span=None):\n        self.__init_handle_by_constructor__(\n            tvm.ir._ffi_api.IntImm, dtype, value, span  # type: ignore\n        )\n\n    def __hash__(self):\n        return self.value\n\n    def __int__(self):\n        return self.value\n\n    def __nonzero__(self):\n        return self.value != 0\n\n    def __eq__(self, other):\n        return _ffi_api._OpEQ(self, other, None)  # type: ignore\n\n    def __ne__(self, other):\n        return _ffi_api._OpNE(self, other, None)  # type: ignore\n\n    def __bool__(self):\n        return self.__nonzero__()\n\n\n@tvm._ffi.register_object(\"tir.StringImm\")  # type: ignore\nclass StringImm(ConstExpr):\n    \"\"\"String constant.\n\n    Parameters\n    ----------\n    value : str\n        The value of the function.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, value, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.StringImm, value, span)  # type: ignore\n\n    def __eq__(self, other):\n        if isinstance(other, ConstExpr):\n            return self.value == other.value\n        return self.value == other\n\n    def __ne__(self, other):\n        if isinstance(other, ConstExpr):\n            return self.value != other.value\n        return self.value != other\n\n    def __hash__(self):\n        return PrimExpr.__hash__(self)\n\n\n@tvm._ffi.register_object(\"tir.Cast\")\nclass Cast(PrimExprWithOp):\n    \"\"\"Cast expression.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type\n\n    value : PrimExpr\n        The value of the function.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, dtype, value, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Cast, dtype, value, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Add\")\nclass Add(BinaryOpExpr):\n    \"\"\"Add node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Add, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Sub\")\nclass Sub(BinaryOpExpr):\n    \"\"\"Sub node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Sub, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Mul\")\nclass Mul(BinaryOpExpr):\n    \"\"\"Mul node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Mul, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Div\")\nclass Div(BinaryOpExpr):\n    \"\"\"Div node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Div, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Mod\")\nclass Mod(BinaryOpExpr):\n    \"\"\"Mod node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Mod, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.FloorDiv\")\nclass FloorDiv(BinaryOpExpr):\n    \"\"\"FloorDiv node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.FloorDiv, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.FloorMod\")\nclass FloorMod(BinaryOpExpr):\n    \"\"\"FloorMod node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.FloorMod, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Min\")\nclass Min(BinaryOpExpr):\n    \"\"\"Min node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Min, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Max\")\nclass Max(BinaryOpExpr):\n    \"\"\"Max node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Max, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.EQ\")\nclass EQ(CmpExpr):\n    \"\"\"EQ node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.EQ, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.NE\")\nclass NE(CmpExpr):\n    \"\"\"NE node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.NE, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.LT\")\nclass LT(CmpExpr):\n    \"\"\"LT node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.LT, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.LE\")\nclass LE(CmpExpr):\n    \"\"\"LE node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.LE, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.GT\")\nclass GT(CmpExpr):\n    \"\"\"GT node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.GT, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.GE\")\nclass GE(CmpExpr):\n    \"\"\"GE node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.GE, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.And\")\nclass And(LogicalExpr):\n    \"\"\"And node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.And, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Or\")\nclass Or(LogicalExpr):\n    \"\"\"Or node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand.\n\n    b : PrimExpr\n        The right hand operand.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, b, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Or, a, b, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Not\")\nclass Not(LogicalExpr):\n    \"\"\"Not node.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The input value\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, a, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Not, a, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Select\")\nclass Select(PrimExprWithOp):\n    \"\"\"Select node.\n\n    Note\n    ----\n    Select may compute both true_value and false_value.\n    Use :py:class:`tvm.tir.if_then_else` instead if you want to\n    get a conditional expression that only evaluates\n    the correct branch.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The condition expression.\n\n    true_value : PrimExpr\n        The value to take when condition is true.\n\n    false_value : PrimExpr\n        The value to take when condition is false.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, condition, true_value, false_value, span=None):\n        if isinstance(condition, bool):\n            condition = IntImm(\"bool\", condition)\n        self.__init_handle_by_constructor__(\n            _ffi_api.Select, condition, true_value, false_value, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Load\")\nclass Load(PrimExprWithOp):\n    \"\"\"Load node.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type.\n\n    buffer_var : Var\n        The buffer variable in the load expression.\n\n    index : PrimExpr\n        The index in the load.\n\n    predicate : PrimExpr\n        The load predicate.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, dtype, buffer_var, index, predicate=None, span=None):\n        if predicate is None:\n            predicate = _ffi_api.const_true(dtype, span)  # type: ignore\n        self.__init_handle_by_constructor__(\n            _ffi_api.Load, dtype, buffer_var, index, predicate, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.BufferLoad\")\nclass BufferLoad(PrimExprWithOp):\n    \"\"\"Buffer load node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer to be loaded.\n\n    indices : List[PrimExpr]\n        The buffer indices.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer, indices, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BufferLoad, buffer, indices, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.ProducerLoad\")\nclass ProducerLoad(PrimExprWithOp):\n    \"\"\"Producer load node.\n\n    Parameters\n    ----------\n    producer : DataProducer\n        The buffer to be loaded.\n\n    indices : List[PrimExpr]\n        The buffer indices.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, producer, indices, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ProducerLoad, producer, indices, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Ramp\")\nclass Ramp(PrimExprWithOp):\n    \"\"\"Ramp node.\n\n    Parameters\n    ----------\n    base : PrimExpr\n        The base expression.\n\n    stride : ramp stride\n        The stride of the ramp.\n\n    lanes : int\n        The lanes of the expression.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, base, stride, lanes, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Ramp, base, stride, lanes, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Broadcast\")\nclass Broadcast(PrimExprWithOp):\n    \"\"\"Broadcast node.\n\n    Parameters\n    ----------\n    value : PrimExpr\n        The value of the expression.\n\n    lanes : int\n        The lanes of the expression.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, value, lanes, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Broadcast, value, lanes, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Shuffle\")\nclass Shuffle(PrimExprWithOp):\n    \"\"\"Shuffle node.\n\n    Parameters\n    ----------\n    vectors : Array of Expr\n        The vectors\n\n    indices : Array of indices\n        The indices\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, vectors, indices, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.Shuffle, vectors, indices, span  # type: ignore\n        )\n\n\nclass CallEffectKind:\n    \"\"\"Possible kinds of Call effects.\"\"\"\n\n    # only expose up to opaque\n    ExprAnnotation = IntImmEnum(0)\n    Pure = IntImmEnum(1)\n    ReadState = IntImmEnum(2)\n    UpdateState = IntImmEnum(3)\n    Opaque = UpdateState\n\n\n@tvm._ffi.register_object(\"tir.Call\")\nclass Call(PrimExprWithOp):\n    \"\"\"Call node.\n\n    Parameters\n    ----------\n    dtype : str\n        The return data type\n\n    op : Union[RelayExpr, str]\n        The function to be called, or the name\n        to the global tvm.Op\n\n    args : list of Expr\n        The input arguments to the call\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, dtype, op, args, span=None):\n        if isinstance(op, str):\n            if not op.startswith(\"tir.\"):\n                raise ValueError(\n                    (\n                        \"Cannot handle str op argument %s. This function only handles str \"\n                        + \"argument with the tir namespace. If you are \"\n                        + \"certain about the intrinsic name, pass in Op.get(name) instead\"\n                    )\n                    % op\n                )\n            op = Op.get(op)\n        self.__init_handle_by_constructor__(_ffi_api.Call, dtype, op, args, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Let\")\nclass Let(PrimExprWithOp):\n    \"\"\"Let node.\n\n    Parameters\n    ----------\n    var : Var\n        The variable in the binding.\n\n    value : PrimExpr\n        The value in to be binded.\n\n    body : PrimExpr\n        The body expression.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, var, value, body, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Let, var, value, body, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Any\")\nclass Any(PrimExprWithOp):\n    \"\"\"Any node.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Any, span)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/function.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Function data types.\"\"\"\n\nimport collections\nimport inspect\nfrom typing import Callable, List, Mapping, Optional, Union, Tuple\n\nimport tvm\nimport tvm._ffi\nimport tvm.runtime\nfrom tvm.runtime import Object\nfrom tvm.ir import BaseFunc, Range\nfrom .buffer import Buffer\nfrom .expr import Var, PrimExpr\nfrom . import _ffi_api\nfrom ..runtime.ndarray import NDArray\n\n\n@tvm._ffi.register_object(\"tir.PrimFunc\")\nclass PrimFunc(BaseFunc):\n    \"\"\"A function declaration expression.\n\n    Parameters\n    ----------\n    params: List[Union[tvm.tir.Var, tvm.tir.Buffer]]\n        List of input parameters to the function.\n\n    body: tvm.tir.Stmt\n        The body of the function.\n\n    ret_type: tvm.ir.Type\n        The return type annotation of the function.\n\n    buffer_map : Map[tvm.tir.Var, tvm.tir.Buffer]\n        The buffer binding map.\n\n    preflattened_buffer_map : Optional[Map[tvm.tir.Var, tvm.tir.Buffer]]\n        The buffer binding map, prior to any flattening.\n\n    attrs: Optional[tvm.Attrs]\n        Attributes of the function, can be None\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(\n        self,\n        params,\n        body,\n        ret_type=None,\n        buffer_map=None,\n        preflattened_buffer_map=None,\n        attrs=None,\n        span=None,\n    ):\n\n        param_list = []\n        buffer_map = {} if buffer_map is None else buffer_map\n        preflattened_buffer_map = {} if preflattened_buffer_map is None else preflattened_buffer_map\n        for x in params:\n            x = tvm.runtime.convert(x) if not isinstance(x, Object) else x\n            if isinstance(x, Buffer):\n                var = Var(x.name, dtype=\"handle\")\n                param_list.append(var)\n                buffer_map[var] = x\n            elif isinstance(x, Var):\n                param_list.append(x)\n            else:\n                raise TypeError(\"params can only contain Var or Buffer\")\n\n        self.__init_handle_by_constructor__(\n            _ffi_api.PrimFunc,\n            param_list,\n            body,\n            ret_type,\n            buffer_map,\n            preflattened_buffer_map,\n            attrs,\n            span,\n        )  # type: ignore\n\n    def with_body(self, new_body, span=None):\n        \"\"\"Create a new PrimFunc with the same set signatures but a new body.\n\n        Parameters\n        ----------\n        new_body : Stmt\n            The new body.\n\n        span : Optional[Span]\n            The location of this itervar in the source code.\n\n        Returns\n        -------\n        new_func : PrimFunc\n            The created new function.\n        \"\"\"\n        return PrimFunc(\n            self.params,\n            new_body,\n            self.ret_type,\n            self.buffer_map,\n            self.preflattened_buffer_map,\n            self.attrs,\n            span,\n        )\n\n    def specialize(self, param_map: Mapping[Var, Union[PrimExpr, Buffer]]):\n        \"\"\"Specialize parameters of PrimFunc\n\n        Parameters\n        ----------\n\n        param_map : Mapping[Var, Union[PrimExpr, Buffer]]\n            The mapping from function params to the instance\n\n        Examples\n        --------\n        We can define a Meta TIR function with symbolic shape:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def mem_copy(a: T.handle, b: T.handle, m: T.int32, n: T.int32) -> None:\n                A = T.match_buffer(a, (m, n), \"float32\")\n                B = T.match_buffer(b, (m, n), \"float32\")\n\n                for i, j in T.grid(m, n):\n                    with T.block():\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj]\n\n        Then we can make it specialized with given shapes or buffers.\n\n        .. code-block:: python\n\n            a, _, m, n = mem_copy.params\n            func = mem_copy.specialize({a: tir.decl_buffer((16, 16))})\n            # or\n            func = mem_copy.specialize({n: 16, m: 16})\n\n        The specialized function:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def mem_copy_16_16(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (16, 16), \"float32\")\n                B = T.match_buffer(b, (16, 16), \"float32\")\n\n                for i, j in T.grid(16, 16):\n                    with T.block():\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj]\n\n        Returns\n        -------\n        func : PrimFunc\n            The new function with parameter specialized\n        \"\"\"\n        return _ffi_api.Specialize(self, param_map)  # type: ignore\n\n    def script(self, tir_prefix: str = \"T\", show_meta: bool = False) -> str:\n        \"\"\"Print IRModule into TVMScript\n\n        Parameters\n        ----------\n        tir_prefix : str\n            The tir namespace prefix\n\n        show_meta : bool\n            Whether to show meta information\n\n        Returns\n        -------\n        script : str\n            The TVM Script of the PrimFunc\n        \"\"\"\n        return tvm._ffi.get_global_func(\"script.AsTVMScript\")(\n            self, tir_prefix, show_meta\n        )  # type: ignore\n\n    def show(self, style: Optional[str] = None) -> None:\n        \"\"\"\n        A sugar for print highlighted TVM script.\n        Parameters\n        ----------\n        style : str, optional\n            Pygments styles extended by \"light\" (default) and \"dark\", by default \"light\"\n        \"\"\"\n        from tvm.script.highlight import cprint  # pylint: disable=import-outside-toplevel\n\n        # Use deferred import to avoid circular import while keeping cprint under tvm/script\n        cprint(self, style=style)\n\n\n@tvm._ffi.register_object(\"tir.TensorIntrin\")\nclass TensorIntrin(Object):\n    \"\"\"A tensor intrinsic.\n\n    Parameters\n    ----------\n    desc : PrimFunc\n        The function to describe the computation.\n\n    impl : PrimFunc\n        The function of the implementation for the execution.\n    \"\"\"\n\n    def __init__(self, desc, impl):\n        self.__init_handle_by_constructor__(_ffi_api.TensorIntrin, desc, impl)\n\n    @staticmethod\n    def register(name: str, desc: PrimFunc, impl: PrimFunc, override: bool = False):\n        \"\"\"Register a tensor intrinsic with its name.\n\n        Parameters\n        ----------\n        name : str\n            The name of the TensorIntrin to register.\n        desc : PrimFunc\n            The function to describe the computation.\n        impl : PrimFunc\n            The function of the implementation for the execution.\n        override: bool\n            Whether override existing intrinsic.\n        \"\"\"\n        return _ffi_api.TensorIntrinRegister(\n            name, TensorIntrin(desc, impl), override\n        )  # type: ignore\n\n    @staticmethod\n    def get(name: str, allow_missing: bool = False) -> Optional[\"TensorIntrin\"]:\n        \"\"\"Look up a tensor intrinsic by its name.\n\n        Parameters\n        ----------\n        name : str\n            The name of the TensorIntrin to look up.\n\n        allow_missing : bool\n            Whether to allow missing tensor intrin. If False, raise an error if the tensor intrin\n        doesn't exist.\n\n        Returns\n        -------\n        result : Optional[TensorIntrin]\n            The TensorIntrin with the specified name, or None if not found.\n        \"\"\"\n        return _ffi_api.TensorIntrinGet(name, allow_missing)  # pylint: type: ignore\n\n\n@tvm._ffi.register_object(\"tir.IndexMap\")\nclass IndexMap(Object):\n    \"\"\"A mapping from multi-dimensional indices to another set of multi-dimensional indices\n\n    Parameters\n    ----------\n    initial_indices : List[Var]\n        Variables representing the indices prior to remapping.\n    final_indices : List[PrimExpr]\n        Expressions defining the indices after remapping.\n    inverse_index_map : Union[Callable, Optional[IndexMap]]\n        The optional pre-defined inverse index map.\n        When this is defined, IndexMap::Inverse will return the pre-defined inverse index map.\n        Otherwise, the inverse index map will be computed on the fly.\n        It is the user's responsibility to ensure the correctness of the pre-defined inverse\n        index map.\n    \"\"\"\n\n    initial_indices: List[Var]\n    final_indices: List[PrimExpr]\n\n    # Sentinel value used to indicate which groups of pre-flattening axes\n    # should be used to post-flattening axes axes.  See\n    # Stage.transform_layout for more details.\n    AXIS_SEPARATOR = \"axis_separator\"\n\n    def __init__(self, initial_indices, final_indices, inverse_index_map):\n        if isinstance(inverse_index_map, Callable):\n            inverse_index_map = IndexMap.from_func(inverse_index_map)\n        self.__init_handle_by_constructor__(\n            _ffi_api.IndexMap, initial_indices, final_indices, inverse_index_map\n        )\n\n    @staticmethod\n    def from_func(\n        mapping_function: Callable,\n        ndim: Optional[int] = None,\n        inverse_index_map: Union[Callable, Optional[\"IndexMap\"]] = None,\n    ):\n        \"\"\"Create an index map from a function\n\n        Parameters\n        ----------\n        mapping_function : Callable\n\n            The function to map from source indices to target indices.\n            The function should accept `tir.Var` parameters and return\n            a either a `tir.PrimExpr`, or a list of `tir.PrimExpr`.\n            Returning a `tir.PrimExpr` is equivalent to returning a\n            list of length 1 containing that `tir.PrimExpr`.\n\n        ndim: Optional[int]\n\n            The dimensionality of the buffer to which this\n            transformation should be applied.  If mapping_function uses\n            variadic argument `*args`, `ndim` must be specified.  If\n            mapping_function does not use variadic arguments, ndim is\n            optional.\n\n        inverse_index_map : Union[Callable, Optional[IndexMap]]\n            The optional pre-defined inverse index map.\n            When this is defined, IndexMap::Inverse will return the pre-defined inverse index map.\n            Otherwise, the inverse index map will be computed on the fly.\n            It is the user's responsibility to ensure the correctness of the pre-defined inverse\n            index map.\n\n        Returns\n        -------\n        index_map: IndexMap\n\n            Returns an IndexMap representing the `mapping_function`.\n\n        \"\"\"\n        index_map, axis_separators = IndexMap.from_func_with_separators(\n            mapping_function, ndim, inverse_index_map\n        )\n        assert not axis_separators, (\n            \"The mapping_function provided to IndexMap.from_func \"\n            \"may not return IndexMap.AXIS_SEPARATOR.  \"\n            \"If required, please use IndexMap.from_func_with_separators instead.\"\n        )\n        return index_map\n\n    @staticmethod\n    def from_func_with_separators(\n        mapping_function: Callable,\n        ndim: Optional[int] = None,\n        inverse_index_map: Union[Callable, Optional[\"IndexMap\"]] = None,\n    ):\n        \"\"\"Create an index map from a function\n\n        Parameters\n        ----------\n        mapping_function : Callable\n\n            The function to map from source indices to target indices.\n            The function should accept tir.Var parameters and return\n            either a `tir.PrimExpr` or a list.  Each element of the\n            returned list should be either a `tir.PrimExpr` or the\n            object `IndexMap.AXIS_SEPARATOR`.  Returning a\n            `tir.PrimExpr` is equivalent to returning a list of length\n            1 containing that `tir.PrimExpr`.\n\n        ndim: Optional[int]\n\n            The dimensionality of the buffer to which this\n            transformation should be applied.  If mapping_function uses\n            variadic argument `*args`, ndim must be specified.  If\n            mapping_function does not use variadic arguments, ndim is\n            optional.\n\n        inverse_index_map : Union[Callable, Optional[IndexMap]]\n            The optional pre-defined inverse index map.\n            When this is defined, IndexMap::Inverse will return the pre-defined inverse index map.\n            Otherwise, the inverse index map will be computed on the fly.\n            It is the user's responsibility to ensure the correctness of the pre-defined inverse\n            index map.\n\n        Returns\n        -------\n        ret: Tuple[IndexMap, List[int]]\n\n            Returns a tuple whose first element is an IndexMap\n            representing the `mapping_function`, and whose second index\n            is a list of indices at which `IndexMap.AXIS_SEPARATOR`\n            occurred.\n\n        \"\"\"\n        params = inspect.signature(mapping_function).parameters\n\n        args = []\n        var_arg_name = None\n        kwargs = collections.OrderedDict()\n        default_index_dtype = \"int32\"\n\n        for name, param in params.items():\n            if param.kind in [\n                inspect.Parameter.POSITIONAL_ONLY,\n                inspect.Parameter.POSITIONAL_OR_KEYWORD,\n            ]:\n                args.append(tvm.tir.Var(name, default_index_dtype))\n\n            elif param.kind == inspect.Parameter.VAR_POSITIONAL:\n                var_arg_name = name\n\n            elif param.kind == inspect.Parameter.KEYWORD_ONLY:\n                kwargs[name] = tvm.tir.Var(name, default_index_dtype)\n\n            else:\n                raise ValueError(\"transform_layout mapping may not have *args\")\n\n        # Now that all the named arguments have been collected,\n        # everything that remains should go to the *args, if\n        # specified.\n        if var_arg_name is not None:\n            assert ndim is not None, \"ndim must be specified when *args is used\"\n            num_var_args = ndim - len(args) - len(kwargs)\n            for i in range(num_var_args):\n                args.append(tvm.tir.Var(f\"{var_arg_name}_{i}\", default_index_dtype))\n\n        mapping = mapping_function(*args, **kwargs)\n\n        initial_indices = args + list(kwargs.values())\n\n        final_indices = []\n        axis_separators = []\n\n        try:\n            iter(mapping)\n            is_iterable = True\n        except TypeError:\n            is_iterable = False\n\n        if is_iterable:\n            for val in mapping:\n                if isinstance(val, tvm.ir.PrimExpr):\n                    final_indices.append(val)\n                elif val is IndexMap.AXIS_SEPARATOR:\n                    axis_separators.append(len(final_indices))\n                else:\n                    raise TypeError(\n                        \"Expected mapping function to return list of \"\n                        \"either tvm.ir.PrimExpr or IndexMap.AXIS_SEPARATOR.  \"\n                        f\"Instead received {val} of type {type(val)}.\"\n                    )\n        else:\n            final_indices.append(mapping)\n\n        return IndexMap(initial_indices, final_indices, inverse_index_map), axis_separators\n\n    def is_equivalent_to(self, other_map: \"IndexMap\") -> bool:\n        \"\"\"Return if the index maps are equivalent.\n\n        Parameters\n        ----------\n        other_map: IndexMap\n\n            The IndexMap to which the comparison should be made.\n\n        Returns\n        -------\n        is_equivalent: bool\n\n            True if the two mappings represent the same\n            transformation, otherwise False\n        \"\"\"\n        if len(self.initial_indices) != len(other_map.initial_indices):\n            return False\n        if len(self.final_indices) != len(other_map.final_indices):\n            return False\n\n        analyzer = tvm.arith.Analyzer()\n\n        mapped_other_final_indices = other_map.map_indices(self.initial_indices)\n        for self_index, other_index in zip(self.final_indices, mapped_other_final_indices):\n            if not analyzer.can_prove_equal(self_index, other_index):\n                return False\n\n        return True\n\n    def map_indices(self, indices: List[PrimExpr]) -> List[PrimExpr]:\n        \"\"\"Apply the index map to a set of indices\n\n        Parameters\n        ----------\n        indices : List[PrimExpr]\n            The indices to be mapped\n\n        Returns\n        -------\n        result : List[PrimExpr]\n            The mapped indices\n        \"\"\"\n        return _ffi_api.IndexMapMapIndices(self, indices)\n\n    def map_shape(self, shape: List[PrimExpr]) -> List[PrimExpr]:\n        \"\"\"Apply the index map to a buffer shape\n\n        Parameters\n        ----------\n        shape : List[PrimExpr]\n            The buffer shape to be mapped\n\n        Returns\n        -------\n        result : List[PrimExpr]\n            The mapped shape\n        \"\"\"\n        return _ffi_api.IndexMapMapShape(self, shape)\n\n    def map_ndarray(self, arr_src: NDArray) -> NDArray:\n        \"\"\"Apply thie index map to transform the layout of the input NDArray\n\n        Parameters\n        ----------\n        arr_src : runtime.NDArray\n            The NDArray to be transformed\n\n        Returns\n        -------\n        arr_dst : runtime.NDArray\n            The transformed NDArray\n        \"\"\"\n        return _ffi_api.IndexMapMapNDArray(self, arr_src)\n\n    def inverse(self, shape: List[Union[Range, PrimExpr]]) -> \"IndexMap\":\n        \"\"\"Return the inverse of the map\n\n        Throws an error if the function is not bijective.\n\n        Parameters\n        ----------\n        shape: List[Union[Range,PrimExpr]]\n\n            The region over which the inverse should be determined.\n            Used for validating that the mapping is bijective over\n            this range.\n\n        Returns\n        -------\n        inverse : IndexMap\n\n            The inverse\n        \"\"\"\n\n        shape = [dim if isinstance(dim, Range) else Range(0, dim) for dim in shape]\n        return _ffi_api.IndexMapInverse(self, shape)\n\n    def non_surjective_inverse(\n        self, shape: List[Union[Range, PrimExpr]]\n    ) -> Tuple[\"IndexMap\", PrimExpr]:\n        \"\"\"Return the inverse of the map\n\n        Can be applied to transformations that introduce padding.\n\n        Parameters\n        ----------\n        shape: List[Union[Range,PrimExpr]]\n\n            The region over which the inverse should be determined.\n            Used for determining the predicate.\n\n        Returns\n        -------\n        result : Tuple[IndexMap, PrimExpr]\n\n            The inverse, and a predicate for which the inverse maps to\n            a valid index in the input range.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n            index_map = IndexMap.from_func(lambda i: [i//4, i%4])\n            inverse_map, predicate = index_map.non_surjective_inverse([14])\n            assert inverse_map.is_equivalent_to(IndexMap.from_func(lambda j,k: [4*j + k])\n            print(predicate) # Prints \"(axis0==3) && (axis2 >= 2)\"\n        \"\"\"\n\n        shape = [dim if isinstance(dim, Range) else Range(0, dim) for dim in shape]\n        return _ffi_api.IndexMapNonSurjectiveInverse(self, shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Generic opertors in TVM.\nWe follow the numpy naming convention for this interface\n(e.g., tvm.tir.generic.multitply ~ numpy.multiply).\nThe default implementation is used by tvm.ExprOp.\n\"\"\"\n# pylint: disable=unused-argument\nfrom . import _ffi_api\n\n# Operator precedence used when overloading.\n__op_priority__ = 0\n\n\ndef add(lhs, rhs, span=None):\n    \"\"\"Generic add operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of add operaton.\n    \"\"\"\n    return _ffi_api._OpAdd(lhs, rhs, span)  # type: ignore\n\n\ndef subtract(lhs, rhs, span=None):\n    \"\"\"Generic subtract operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of subtract operaton.\n    \"\"\"\n    return _ffi_api._OpSub(lhs, rhs, span)  # type: ignore\n\n\ndef multiply(lhs, rhs, span=None):\n    \"\"\"Generic multiply operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of multiply operaton.\n    \"\"\"\n    return _ffi_api._OpMul(lhs, rhs, span)  # type: ignore\n\n\ndef divide(lhs, rhs, span=None):\n    \"\"\"Generic divide operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of divide operaton.\n    \"\"\"\n    return _ffi_api._OpDiv(lhs, rhs, span)  # type: ignore\n\n\ndef floordiv(lhs, rhs, span=None):\n    \"\"\"Generic floordiv operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of floordiv operaton.\n    \"\"\"\n    return _ffi_api._OpFloorDiv(lhs, rhs, span)  # type: ignore\n\n\ndef cast(src, dtype, span=None):\n    \"\"\"Generic cast operator.\n\n    Parameters\n    ----------\n    src : object\n        The source operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of cast operaton.\n    \"\"\"\n    return _ffi_api._cast(dtype, src, span)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/ir_builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Developer API of IR node builder make function.\"\"\"\nimport tvm\nfrom tvm._ffi.base import string_types\nfrom tvm.runtime import ObjectGeneric, convert, const\nfrom tvm.ir import container as _container\n\nfrom . import stmt as _stmt\nfrom . import expr as _expr\nfrom . import buffer as _buffer\nfrom . import op\n\n\nclass WithScope(object):\n    \"\"\"Auxiliary scope  with\"\"\"\n\n    def __init__(self, enter_value, exit_cb):\n        self._enter_value = enter_value\n        self._exit_cb = exit_cb\n\n    def __enter__(self):\n        return self._enter_value\n\n    def __exit__(self, ptype, value, trace):\n        self._exit_cb()\n\n\nclass BufferVar(ObjectGeneric):\n    \"\"\"Buffer variable with content type, makes load store easily.\n\n    Do not create it directly, create use IRBuilder.\n\n    Array access through a BufferVar must use the same number of\n    indices as the underlying buffer was declared to have.\n\n    Examples\n    --------\n    In the follow example, x is BufferVar.\n    :code:`x[0] = ...` directly emit a BufferStore to the IRBuilder,\n    :code:`x[10]` translates to BufferLoad.\n\n    .. code-block:: python\n\n        # The following code generate IR for x[0] = x[10] + 1\n        ib = tvm.tir.ir_builder.create()\n        x = ib.allocate(\"float32\", 20)\n        x[0] = x[10] + 1\n\n        # Array access using a multidimensional index\n        y = ib.allocate(\"float32\", (32, 32))\n        y[2, 31] = 0.\n\n    See Also\n    --------\n    IRBuilder.pointer\n    IRBuilder.allocate\n\n    \"\"\"\n\n    def __init__(self, builder, buffer, content_type):\n        self._builder = builder\n        self._buffer = buffer\n        self._content_type = content_type\n\n    def asobject(self):\n        return self._buffer\n\n    @property\n    def dtype(self):\n        return self._content_type\n\n    def _normalize_index(self, index):\n        try:\n            index = [*index]\n        except TypeError:\n            index = [index]\n\n        index = [x.var if isinstance(x, _expr.IterVar) else x for x in index]\n\n        # Workaround to support previous behavior of ir_builder\n        # indexing by a single index, treating the buffer as if were\n        # already flattened.\n        if len(index) == 1 and len(self._buffer.shape) != 1:\n            index = tvm.topi.utils.unravel_index(index[0], self._buffer.shape)\n\n        return index\n\n    def __getitem__(self, index):\n        index = self._normalize_index(index)\n        return _expr.BufferLoad(self._buffer, index)\n\n    def __setitem__(self, index, value):\n        index = self._normalize_index(index)\n\n        value = convert(value)\n        value_element = value.dtype.split(\"x\", maxsplit=1)[0]\n        content_element = self._content_type.split(\"x\", maxsplit=1)[0]\n        if value_element != content_element:\n            raise ValueError(\n                \"data type does not match content type %s vs %s\" % (value.dtype, self._content_type)\n            )\n\n        self._builder.emit(_stmt.BufferStore(self._buffer, value, index))\n\n\nclass IRBuilder(object):\n    \"\"\"Auxiliary builder to build IR for testing and dev.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        ib = tvm.tir.ir_builder.create()\n        n = te.var(\"n\")\n        A = ib.allocate(\"float32\", n, name=\"A\")\n        with ib.for_range(0, n, name=\"i\") as i:\n            with ib.if_scope((i % 2) == 0):\n                A[i] = A[i] + 1\n        # The result stmt.\n        stmt = ib.get()\n    \"\"\"\n\n    def __init__(self):\n        self._seq_stack = [[]]  # type: ignore\n        self.nidx = 0\n\n    def _pop_seq(self):\n        \"\"\"Pop sequence from stack\"\"\"\n        seq = self._seq_stack.pop()\n        if not seq or callable(seq[-1]):\n            seq.append(_stmt.Evaluate(0))\n        seqwrap = lambda x: x[0] if len(x) == 1 else _stmt.SeqStmt(list(reversed(x)))\n        ret_seq = [seq[-1]]\n\n        for s in reversed(seq[:-1]):\n            if callable(s):\n                ret_seq = [s(seqwrap(ret_seq))]\n            else:\n                assert isinstance(s, _stmt.Stmt)\n                ret_seq.append(s)\n        return seqwrap(ret_seq)\n\n    def emit(self, stmt):\n        \"\"\"Emit a statement to the end of current scope.\n\n        Parameters\n        ----------\n        stmt : Stmt or callable.\n           The statement to be emitted or callable that build stmt given body.\n        \"\"\"\n        if isinstance(stmt, _expr.Call):\n            stmt = _stmt.Evaluate(stmt)\n        assert isinstance(stmt, _stmt.Stmt) or callable(stmt)\n        self._seq_stack[-1].append(stmt)\n\n    def scope_attr(self, node, attr_key, value):\n        \"\"\"Create an AttrStmt at current scope.\n\n        Parameters\n        ----------\n        attr_key : str\n            The key of the attribute type.\n\n        node : Node\n            The attribute node to annottate on.\n\n        value : Expr\n            Attribute value.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            ib = tvm.tir.ir_builder.create()\n            i = te.var(\"i\")\n            x = ib.pointer(\"float32\")\n            ib.scope_attr(x, \"storage_scope\", \"global\")\n            x[i] = x[i - 1] + 1\n        \"\"\"\n        if isinstance(node, string_types):\n            node = _expr.StringImm(node)\n        if isinstance(value, string_types):\n            value = _expr.StringImm(value)\n        # thread_extent could be zero for dynamic workloads\n        if attr_key == \"thread_extent\":\n            value = op.max(1, value)\n        self.emit(lambda x: _stmt.AttrStmt(node, attr_key, value, x))\n\n    def for_range(self, begin, end, name=\"i\", dtype=None, kind=\"serial\"):\n        \"\"\"Create a for iteration scope.\n\n        Parameters\n        ----------\n        begin : Expr\n            The min iteration scope.\n\n        end : Expr\n            The end iteration scope\n\n        name : str, optional\n            The name of iteration variable, if no input names,\n            using typical index names i, j, k, then i_nidx\n\n        dtype : str, optional\n            The data type of iteration variable.\n\n        kind : str, optional\n            The special tag on the for loop.\n\n        Returns\n        -------\n        loop_scope : With.Scope of Var\n            The for scope, when enters returns loop_var\n\n        Examples\n        --------\n        .. code-block:: python\n\n            ib = tvm.tir.ir_builder.create()\n            x = ib.pointer(\"float32\")\n            with ib.for_range(1, 10, name=\"i\") as i:\n                x[i] = x[i - 1] + 1\n        \"\"\"\n        if name == \"i\":\n            name = chr(ord(name) + self.nidx) if self.nidx < 3 else name + \"_\" + str(self.nidx - 3)\n            self.nidx += 1\n        self._seq_stack.append([])\n\n        # auto infer dtype when it's not specified\n        def get_dtype(expr):\n            if isinstance(expr, _expr.PrimExpr):\n                if not expr.dtype.startswith(\"int\"):\n                    raise NotImplementedError(\n                        f\"Infer loop_var dtype failed:\"\n                        f\" unsupported dtype in loop begin or end {expr.dtype}\"\n                    )\n                return expr.dtype\n            if isinstance(expr, int):\n                return \"int32\"\n            raise NotImplementedError(\n                f\"Infer loop_var dtype failed:\"\n                f\" unsupported dtype in loop begin or end {expr.dtype}\"\n            )\n\n        if dtype is None:\n            dtype = \"int64\" if \"int64\" in [get_dtype(begin), get_dtype(end)] else \"int32\"\n\n        loop_var = _expr.Var(name, dtype=dtype)\n        extent = end if begin == 0 else (end - begin)\n\n        def _exit_cb():\n            if kind == \"serial\":\n                kind_id = _stmt.ForKind.SERIAL\n            elif kind == \"parallel\":\n                kind_id = _stmt.ForKind.PARALLEL\n            elif kind == \"vectorize\":\n                kind_id = _stmt.ForKind.VECTORIZED\n            elif kind == \"unroll\":\n                kind_id = _stmt.ForKind.UNROLLED\n            else:\n                raise ValueError(\"Unknown kind\")\n            self.emit(_stmt.For(loop_var, begin, extent, kind_id, self._pop_seq()))\n\n        return WithScope(loop_var, _exit_cb)\n\n    def while_loop(self, condition):\n        \"\"\"Create a while loop scope.\n\n        Parameters\n        ----------\n        condition : Expr\n            The termination condition.\n\n        Returns\n        -------\n        loop_scope : With.Scope of Var\n            The while scope.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            ib = tvm.tir.ir_builder.create()\n            iterations = ib.allocate(\"int32\", (1,), name=\"iterations\", scope=\"local\")\n            with ib.while_loop(iterations[0] < 10):\n                iterations[0] += 1\n        \"\"\"\n        self._seq_stack.append([])\n\n        def _exit_cb():\n            self.emit(_stmt.While(condition, self._pop_seq()))\n\n        return WithScope(None, _exit_cb)\n\n    def if_scope(self, cond):\n        \"\"\"Create an if scope.\n\n        Parameters\n        ----------\n        cond : Expr\n            The condition.\n\n        Returns\n        -------\n        if_scope : WithScope\n           The result if scope.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            ib = tvm.tir.ir_builder.create()\n            i = te.var(\"i\")\n            x = ib.pointer(\"float32\")\n            with ib.if_scope((i % 2) == 0):\n                x[i] = x[i - 1] + 1\n        \"\"\"\n        self._seq_stack.append([])\n\n        def _exit_cb():\n            self.emit(_stmt.IfThenElse(cond, self._pop_seq(), None))\n\n        return WithScope(None, _exit_cb)\n\n    def else_scope(self):\n        \"\"\"Create an else scope.\n\n        This can only be used right after an if scope.\n\n        Returns\n        -------\n        else_scope : WithScope\n           The result else scope.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            ib = tvm.tir.ir_builder.create()\n            i = te.var(\"i\")\n            x = ib.pointer(\"float32\")\n            with ib.if_scope((i % 2) == 0):\n                x[i] = x[i - 1] + 1\n            with ib.else_scope():\n                x[i] = x[i - 1] + 2\n        \"\"\"\n        if not self._seq_stack[-1]:\n            raise RuntimeError(\"else_scope can only follow an if_scope\")\n        prev = self._seq_stack[-1][-1]\n        if not isinstance(prev, _stmt.IfThenElse) or prev.else_case:\n            raise RuntimeError(\"else_scope can only follow an if_scope\")\n        self._seq_stack[-1].pop()\n        self._seq_stack.append([])\n\n        def _exit_cb():\n            self.emit(_stmt.IfThenElse(prev.condition, prev.then_case, self._pop_seq()))\n\n        return WithScope(None, _exit_cb)\n\n    def new_scope(self):\n        \"\"\"Create new scope,\n\n        this is useful to set boundary of attr and allocate.\n\n        Returns\n        -------\n        new_scope : WithScope\n           The result new scope.\n        \"\"\"\n        self._seq_stack.append([])\n\n        def _exit_cb():\n            self.emit(self._pop_seq())\n\n        return WithScope(None, _exit_cb)\n\n    def let(self, var_name, value):\n        \"\"\"Create a new let stmt binding.\n\n        Parameters\n        ----------\n        var_name : str\n            The name of the variable\n\n        value : PrimExpr\n            The value to be bound\n\n        Returns\n        -------\n        var : tvm.tir.Var\n           The var that can be in for future emits.\n        \"\"\"\n        var = _expr.Var(var_name, dtype=value.dtype)\n        self.emit(lambda x: _stmt.LetStmt(var, value, x))\n        return var\n\n    def allocate(self, dtype, shape, name=\"buf\", axis_separators=None, scope=\"\"):\n        \"\"\"Create a allocate statement.\n\n        Parameters\n        ----------\n        dtype : str\n            The content data type.\n\n        shape : tuple of Expr\n            The shape of array to be allocated.\n\n        name : str, optional\n            The name of the buffer.\n\n        axis_separators : list of int, optional\n\n            If passed, a list of separators between groups of axes,\n            each of which is flattened to an output axis.  For flat\n            memory spaces, should either be None, or an empty list.\n\n        scope : str, optional\n            The scope of the buffer.\n\n\n        Returns\n        -------\n        buffer : BufferVar\n            The buffer var representing the buffer.\n\n        \"\"\"\n        if not isinstance(shape, (list, tuple, _container.Array)):\n            shape = [shape]\n\n        buffer = _buffer.decl_buffer(\n            shape, dtype, name, scope=scope, axis_separators=axis_separators\n        )\n\n        buffer_var = buffer.data\n        self.emit(lambda x: _stmt.Allocate(buffer_var, dtype, shape, const(1, dtype=\"uint1\"), x))\n        return BufferVar(self, buffer, dtype)\n\n    def pointer(self, content_type, name=\"ptr\", scope=\"\"):\n        \"\"\"Create pointer variable with content type.\n\n        Parameters\n        ----------\n        content_type : str\n            The content data type.\n\n        name : str, optional\n            The name of the pointer.\n\n        scope : str, optional\n            The scope of the pointer.\n\n        Returns\n        -------\n        ptr : BufferVar\n            The buffer var representing the buffer.\n        \"\"\"\n        buffer = _buffer.decl_buffer(shape=[1], dtype=content_type, name=name, scope=scope)\n        return BufferVar(self, buffer, content_type)\n\n    def buffer_ptr(self, buf):\n        \"\"\"Create pointer variable corresponds to buffer ptr.\n\n        Parameters\n        ----------\n        buf : Buffer\n            The buffer to be extracted.\n\n        Returns\n        -------\n        ptr : BufferVar\n            The buffer var representing the buffer.\n        \"\"\"\n        return BufferVar(self, buf, buf.dtype)\n\n    def likely(self, expr):\n        \"\"\"Add likely tag for expression.\n        Parameters\n        ----------\n        expr : Expr\n            The expression. Usually a condition expression.\n        Returns\n        -------\n        expr : Expr\n            The expression will likely tag.\n        \"\"\"\n        return _expr.Call(expr.dtype, \"tir.likely\", [expr])\n\n    def get(self):\n        \"\"\"Return the builded IR.\n\n        Returns\n        -------\n        stmt : Stmt\n           The result statement.\n        \"\"\"\n        seq = self._pop_seq()\n        if self._seq_stack:\n            raise RuntimeError(\"cannot call get inside construction scope\")\n        return seq\n\n\ndef create():\n    \"\"\"Create a new IRBuilder\n\n    Returns\n    -------\n    builder : IRBuilder\n        The created IRBuilder\n    \"\"\"\n    return IRBuilder()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin, invalid-name\n\"\"\"Operators used in TIR expression.\"\"\"\nimport warnings\nfrom typing import Any, Optional\n\nimport tvm._ffi\nfrom tvm.ir import Array, Op, PrimExpr\nfrom tvm.ir.base import Span\nfrom tvm.runtime import const, convert\n\nfrom . import _ffi_api\nfrom .buffer import Buffer\nfrom .expr import Call, CommReducer, IntImm, PrimExprWithOp, StringImm, Var\n\n\ndef _pack_buffer(buf, span=None):\n    \"\"\"Build intrinsics that packs the buffer.\"\"\"\n    shape = Call(\"handle\", \"tir.tvm_stack_make_shape\", buf.shape, span)\n    strides = Call(\"handle\", \"tir.tvm_stack_make_shape\", buf.strides, span) if buf.strides else 0\n    pack_args = [\n        buf.data,\n        shape,\n        strides,\n        len(buf.shape),\n        const(0, dtype=buf.dtype),\n        buf.elem_offset,\n    ]\n    return Call(\"handle\", Op.get(\"tir.tvm_stack_make_array\"), pack_args, span)\n\n\ndef call_packed_lowered(*args, span=None):\n    \"\"\"Lowered version of call packed.\n    The argument to packed function can be Expr or Buffer.\n    The argument is the corresponding POD type when Expr is presented.\n    When the argument is Buffer, the corresponding PackedFunc\n    will recieve an TVMArrayHandle whose content is valid during the callback period.\n    If the PackedFunc is a python callback, then the corresponding argument is NDArray.\n\n    Parameters\n    ----------\n    args : list of Expr or Buffer.\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n\n    See Also\n    --------\n    te.extern : Create tensor with extern function call.\n    \"\"\"\n    call_args = [_pack_buffer(x) if isinstance(x, Buffer) else x for x in args]\n    return Call(\"int32\", Op.get(\"tir.tvm_call_packed_lowered\"), call_args, span)\n\n\ndef call_cpacked_lowered(*args, span=None):\n    \"\"\"Lowered version of call c-packed.\n    Same as call_packed, except that the first argument is the function name\n    (as in call_extern), and the last argument is the resource handle.\n\n    Parameters\n    ----------\n    args : list of Expr or Buffer.\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n\n    See Also\n    --------\n    te.extern : Create tensor with extern function call.\n    \"\"\"\n    call_args = [_pack_buffer(x) if isinstance(x, Buffer) else x for x in args]\n    return Call(\"int32\", Op.get(\"tir.tvm_call_cpacked_lowered\"), call_args, span)\n\n\ndef call_packed(*args, span=None):\n    \"\"\"Build expression by call an external packed function.\n\n    The argument to packed function can be Expr or Buffer.\n    The argument is the corresponding POD type when Expr is presented.\n\n    When the argument is Buffer, the corresponding PackedFunc\n    will receive an TVMArrayHandle whose content is valid during the callback period.\n    If the PackedFunc is a python callback, then the corresponding argument is NDArray.\n\n    Parameters\n    ----------\n    args : list of Expr or Buffer.\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n\n    See Also\n    --------\n    te.extern : Create tensor with extern function call.\n    \"\"\"\n    call_args = [_pack_buffer(x) if isinstance(x, Buffer) else x for x in args]\n    return Call(\"int32\", Op.get(\"tir.tvm_call_packed\"), call_args, span)\n\n\ndef call_cpacked(*args, span=None):\n    \"\"\"Build expression by call an external packed function.\n\n    Same as call_packed, except that the first argument is the function name\n    (as in call_extern), and the last argument is the resource handle.\n\n    Parameters\n    ----------\n    args : list of Expr or Buffer.\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n\n    See Also\n    --------\n    te.extern : Create tensor with extern function call.\n    \"\"\"\n    call_args = [_pack_buffer(x) if isinstance(x, Buffer) else x for x in args]\n    return Call(\"int32\", Op.get(\"tir.tvm_call_cpacked\"), call_args, span)\n\n\ndef call_intrin(dtype, func_name, *args, span=None):\n    \"\"\"Build expression by calling an intrinsic function.\n\n    Intrinsics can be overloaded with multiple data types via\n    the intrinsic translation rule.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    func_name: str\n        The intrinsic function name.\n\n    args : list\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return Call(dtype, func_name, convert(args), span)\n\n\ndef call_pure_extern(dtype, func_name, *args, span=None):\n    \"\"\"Build expression by calling a pure extern function.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    func_name: str\n        The extern function name.\n\n    args : list\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return Call(\n        dtype, Op.get(\"tir.call_pure_extern\"), convert((StringImm(func_name),) + args), span\n    )\n\n\ndef call_extern(dtype, func_name, *args, span=None):\n    \"\"\"Build expression by calling a extern function.\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    func_name: str\n        The extern function name.\n\n    args : list\n        Positional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return Call(\n        dtype, Op.get(\"tir.call_extern\"), convert((StringImm(func_name),) + args), span=span\n    )\n\n\ndef call_llvm_intrin(dtype, name, *args, span=None):\n    \"\"\"Build expression by calling a llvm intrinsic function\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    name : str\n       The name of the llvm intrinsic function.\n\n    args : list\n       Poistional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm.target import codegen\n\n    if isinstance(name, str):\n        llvm_id = codegen.llvm_lookup_intrinsic_id(name)\n    elif isinstance(name, IntImm):\n        llvm_id = name.value\n    else:\n        llvm_id = name\n    if llvm_id == 0:\n        warnings.warn(f\"Unknown llvm intrinsic function {name}, falling back to 0\")\n    return call_intrin(\n        dtype,\n        Op.get(\"tir.call_llvm_intrin\"),\n        tvm.tir.const(llvm_id, \"uint32\"),\n        *args,\n        span=span,\n    )\n\n\ndef call_llvm_pure_intrin(dtype, name, *args, span=None):\n    \"\"\"Build expression by calling a pure llvm intrinsic function\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    name : str\n       The name of the llvm intrinsic function.\n\n    args : list\n       Poistional arguments.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm.target import codegen\n\n    if isinstance(name, str):\n        llvm_id = codegen.llvm_lookup_intrinsic_id(name)\n    elif isinstance(name, IntImm):\n        llvm_id = name.value\n    else:\n        llvm_id = name\n    if llvm_id == 0:\n        warnings.warn(f\"Unknown llvm intrinsic function {name}, falling back to 0\")\n    return call_intrin(\n        dtype,\n        Op.get(\"tir.call_llvm_pure_intrin\"),\n        tvm.tir.const(llvm_id, \"uint32\"),\n        *args,\n        span=span,\n    )\n\n\ndef tvm_check_return(expected, return_unexpected, nested_call):\n    \"\"\"Return new on stack dtype[num]\n    Parameters\n    ----------\n    expected : int\n        The expected return code.\n    return_unexpected : int\n        The unexpected return code.\n    nested_call : PrimExpr\n        The call expression to check return.\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"int32\", \"tir.tvm_check_return\", expected, return_unexpected, nested_call)\n\n\ndef tvm_stack_alloca(dtype_str, num):\n    \"\"\"Return new on stack dtype[num]\n\n    Parameters\n    ----------\n    dtype_str : str\n        The data type of array.\n\n    num : int\n        The size of array.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_stack_alloca\", dtype_str, num)\n\n\ndef tvm_stack_make_shape(*args):\n    \"\"\"Allocate a shape tuple on stack, return the handle\n\n    Parameters\n    ----------\n    args : int\n        The tuple shape.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_stack_make_shape\", *args)\n\n\ndef tvm_stack_make_array(data, shape, strides, ndim, arr_dtype, elem_offset):\n    \"\"\"Allocate a NDArray(DLTensor) on stack, return the handle\n\n    Parameters\n    ----------\n    data : Expr\n        The data of array.\n\n    shape : Expr\n        The shape of array.\n\n    strides : Expr\n        The strides of array.\n\n    ndim : Expr\n        The dimensions of array.\n\n    arr_dtype : Expr\n        The data type of array.\n\n    elem_offse : Expr\n        The element offset of array.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\", \"tir.tvm_stack_make_array\", data, shape, strides, ndim, arr_dtype, elem_offset\n    )\n\n\ndef assume(cond=None):\n    \"\"\"Provide a true statement that can be used for simplifications\n\n    Parameters\n    ----------\n    cond : Expr\n       The constraint condition.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"bool\", \"tir.assume\", cond)\n\n\ndef undef():\n    \"\"\"Returns an initialized but arbitrary value\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"int32\", \"tir.undef\")\n\n\ndef start_profile_intrinsic(id):\n    \"\"\"Start profile intrinsic.\n    Parameters\n    ----------\n    id : int\n        The intrinsic id.\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.start_profile_intrinsic\", id)\n\n\ndef end_profile_intrinsic(id):\n    \"\"\"End profile intrinsic.\n    Parameters\n    ----------\n    id : int\n        The intrinsic id.\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.end_profile_intrinsic\", id)\n\n\ndef tvm_tuple(*value):\n    \"\"\"Create a tuple structure in value field of AttrStmt\n\n    Parameters\n    ----------\n    value : Expr\n        The value in tuple.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_tuple\", *value)\n\n\ndef tvm_struct_get(arr, index, field, dtype):\n    \"\"\"Get struct field value in array\n\n    Parameters\n    ----------\n    dtype : str\n        The date type of the result.\n\n    arr : StructType*\n        The array of struct.\n\n    index : int\n        The index of struct.\n\n    field : int\n        The field of struct.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(dtype, \"tir.tvm_struct_get\", arr, index, field)\n\n\ndef tvm_struct_set(arr, index, field, value):\n    \"\"\"Set value in struct field in array\n\n    Parameters\n    ----------\n    arr : StructType*\n        The array of struct.\n\n    index : int\n        The index of struct.\n\n    field : int\n        The field of struct.\n\n    value : Expr\n        The value to be set in field.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_struct_set\", arr, index, field, value)\n\n\ndef address_of(buffer_load, span=None):\n    \"\"\"Returns the address of an element in the buffer\n\n    Parameters\n    ----------\n    buffer_load: BufferLoad\n        The buffer load.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.address_of\", buffer_load, span=span)\n\n\ndef lookup_param(param_name, span=None):\n    \"\"\"Returns the param by name\n\n    Parameters\n    ----------\n    param_name : str\n        The name of param.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.lookup_param\", param_name, span=span)\n\n\ndef tvm_thread_allreduce(*freduce_args):\n    \"\"\"\n    Parameters\n    ----------\n    freduce_args : Expr\n        The args.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_thread_allreduce\", *freduce_args)\n\n\ndef type_annotation(dtype):\n    \"\"\"Create a type annotation expression\n\n    Parameters\n    ----------\n    dtype : Expr\n        The data type.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(dtype, \"tir.type_annotation\")\n\n\ndef tvm_access_ptr(ptype, data, offset, extent, rw_mask):\n    \"\"\"Get head access address with memory access pattern info\n\n    Parameters\n    ----------\n    ptype : Expr\n        The data type of pointer.\n\n    data : DType*\n        The data of pointer.\n\n    offset : int\n        The offset of pointer.\n\n    extent : int\n        The extent of pointer.\n\n    rw_mask : int\n        The read write mask.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_access_ptr\", ptype, data, offset, extent, rw_mask)\n\n\ndef tvm_throw_last_error():\n    \"\"\"Throw TVMGetLastError()\n\n    Returns\n    -------\n    ret : PrimExpr\n        The return expression\n    \"\"\"\n    return call_intrin(\"handle\", \"tir.tvm_throw_last_error\")\n\n\ndef tvm_load_matrix_sync(fragment, m, n, k, index, buffer_ptr, stride, layout):\n    \"\"\"TVM intrinsic for tensor core load operators\n\n    Parameters\n    ----------\n    fragment : Var\n        The wmma fragment.\n\n    m : UIntImm\n        The shape of wmma fragment.\n\n    n : UIntImm\n        The shape of wmma fragment.\n\n    k : UIntImm\n        The shape of wmma fragment.\n\n    index : Expr\n        The fragment index.\n\n    buffer_ptr : Expr\n        The fragment buffer pointer.\n\n    stride : Expr\n        The fragment stride.\n\n    layout : Literal[\"row_major\", \"column_major\"]\n        The fragment layout.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.tvm_load_matrix_sync\",\n        fragment,\n        m,\n        n,\n        k,\n        index,\n        buffer_ptr,\n        stride,\n        layout,\n    )\n\n\ndef tvm_mma_sync(\n    fragment_d, index_d, fragment_a, index_a, fragment_b, index_b, fragment_c, index_c\n):\n    \"\"\"TVM intrinsic for tensor core mma_sync operators\n\n    Parameters\n    ----------\n    fragment_d : Var\n        The wmma fragment_d.\n\n    index_d : Expr\n        The fragment_d index.\n\n    fragment_a : Var\n        The wmma fragment_a.\n\n    index_a : Expr\n        The fragment_a index.\n\n    fragment_b : Var\n        The wmma fragment_b.\n\n    index_b : Expr\n        The fragment_b index.\n\n    fragment_c : Var\n        The wmma fragment_c.\n\n    index_c : Expr\n        The fragment_c index.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.tvm_mma_sync\",\n        fragment_d,\n        index_d,\n        fragment_a,\n        index_a,\n        fragment_b,\n        index_b,\n        fragment_c,\n        index_c,\n    )\n\n\ndef tvm_bmma_sync(\n    fragment_d, index_d, fragment_a, index_a, fragment_b, index_b, fragment_c, index_c\n):\n    \"\"\"TVM intrinsic for tensor core bmma_sync operators\n\n    Parameters\n    ----------\n    fragment_d : Var\n        The bwmma fragment_d.\n\n    index_d : Expr\n        The fragment_d index.\n\n    fragment_a : Var\n        The bwmma fragment_a.\n\n    index_a : Expr\n        The fragment_a index.\n\n    fragment_b : Var\n        The bwmma fragment_b.\n\n    index_b : Expr\n        The fragment_b index.\n\n    fragment_c : Var\n        The bwmma fragment_c.\n\n    index_c : Expr\n        The fragment_c index.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.tvm_bmma_sync\",\n        fragment_d,\n        index_d,\n        fragment_a,\n        index_a,\n        fragment_b,\n        index_b,\n        fragment_c,\n        index_c,\n    )\n\n\ndef tvm_fill_fragment(fragment, m, n, k, index, value):\n    \"\"\"TVM intrinsic for tensor core fill_fragment operators\n\n    Parameters\n    ----------\n    fragment : Var\n        The wmma fragment\n\n    m : UIntImm\n        The shape of wmma fragment.\n\n    n : UIntImm\n        The shape of wmma fragment.\n\n    k : UIntImm\n        The shape of wmma fragment.\n\n    index : Expr\n        The fragment index.\n\n    value : Expr\n        The value to be filled in fragment.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.tvm_fill_fragment\",\n        fragment,\n        m,\n        n,\n        k,\n        index,\n        value,\n    )\n\n\ndef tvm_store_matrix_sync(fragment, m, n, k, index, buffer_ptr, stride, layout):\n    \"\"\"TVM intrinsic for tensor core store operators\n\n    Parameters\n    ----------\n    fragment : Var\n        The wmma fragment.\n\n    m : UIntImm\n        The shape of wmma fragment.\n\n    n : UIntImm\n        The shape of wmma fragment.\n\n    k : UIntImm\n        The shape of wmma fragment.\n\n    index : Expr\n        The fragment index.\n\n    buffer_ptr : Expr\n        The fragment buffer pointer.\n\n    stride : Expr\n        The fragment stride.\n\n    layout : Literal[\"row_major\", \"column_major\"]\n        The fragment layout.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.tvm_store_matrix_sync\",\n        fragment,\n        m,\n        n,\n        k,\n        index,\n        buffer_ptr,\n        stride,\n        layout,\n    )\n\n\ndef ptx_mma(\n    dtype,\n    shape,\n    A_layout,\n    B_layout,\n    A_dtype,\n    B_dtype,\n    C_dtype,\n    multiplicand_a,\n    a_index,\n    multiplicand_b,\n    b_index,\n    accumulator,\n    c_index,\n    saturate,\n    operator=None,\n):\n    \"\"\"TVM intrinsic for ptx tensor core mma instructions\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#warp-level-matrix-instructions-for-mma\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    shape : str\n        The shape of mma fragment.\n\n    A_layout : Literal[\"row\", \"col\"]\n        The layout of multiplicand fragment A.\n\n    B_layout : Literal[\"row\", \"col\"]\n        The layout of multiplicand fragment B.\n\n    A_dtype : str\n        The data type of multiplicand fragment A.\n\n    B_dtype : str\n        The data type of multiplicand fragment B.\n\n    C_dtype : str\n        The data type of accumulator fragment C.\n\n    multiplicand_a : Var\n        The multiplicand fragment A variable.\n\n    a_index : Expr\n        The index of multiplicand fragment A.\n\n    multiplicand_b : Var\n        The multiplicand fragment B variable.\n\n    b_index : Expr\n        The index of multiplicand fragment A.\n\n    accumulator : Var\n        The accumulator fragment C variable.\n\n    c_index : Expr\n        The index of accumulator fragment C.\n\n    saturate : bool\n        The optional saturation at the output.\n\n\n    operator : Optional[Literal[\"xor\", \"and\"]]\n        The 1-bit operator.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    if operator is None:\n        return call_intrin(\n            dtype,\n            \"tir.ptx_mma\",\n            shape,\n            A_layout,\n            B_layout,\n            A_dtype,\n            B_dtype,\n            C_dtype,\n            multiplicand_a,\n            a_index,\n            multiplicand_b,\n            b_index,\n            accumulator,\n            c_index,\n            saturate,\n        )\n    return call_intrin(\n        dtype,\n        \"tir.ptx_mma\",\n        shape,\n        A_layout,\n        B_layout,\n        A_dtype,\n        B_dtype,\n        C_dtype,\n        multiplicand_a,\n        a_index,\n        multiplicand_b,\n        b_index,\n        accumulator,\n        c_index,\n        saturate,\n        operator,\n    )\n\n\ndef ptx_mma_sp(\n    dtype,\n    shape,\n    A_layout,\n    B_layout,\n    A_dtype,\n    B_dtype,\n    C_dtype,\n    multiplicand_a,\n    a_index,\n    multiplicand_b,\n    b_index,\n    accumulator,\n    c_index,\n    metadata,\n    meta_index,\n    sparse_selector,\n    saturate,\n):\n    \"\"\"TVM intrinsic for sparse tensor core ptx instructions\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#warp-level-matrix-instructions-for-sparse-mma\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    shape : str\n        The shape of mma fragment.\n\n    A_layout : Literal[\"row\", \"col\"]\n        The layout of multiplicand fragment A.\n\n    B_layout : Literal[\"row\", \"col\"]\n        The layout of multiplicand fragment B.\n\n    A_dtype : str\n        The data type of multiplicand fragment A.\n\n    B_dtype : str\n        The data type of multiplicand fragment B.\n\n    C_dtype : str\n        The data type of multiplicand fragment C.\n\n    multiplicand_a : Var\n        The multiplicand fragment A variable.\n\n    a_index : Expr\n        The index of multiplicand fragment A.\n\n    multiplicand_b : Var\n        The multiplicand fragment B variable.\n\n    b_index : Expr\n        The index of multiplicand fragment B.\n\n    accumulator : Var\n        The accumulator fragment C variable.\n\n    c_index : Expr\n        The index of accumulator fragment C.\n\n    metadata : Expr\n        The metadata of operand.\n\n    meta_index : Expr\n        The metadata index of operand.\n\n    sparse_selector : Expr\n        The sparse selector indicating the thread that stores the metadata.\n\n    saturate : bool\n        The optional saturation at the output.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        dtype,\n        \"tir.ptx_mma_sp\",\n        shape,\n        A_layout,\n        B_layout,\n        A_dtype,\n        B_dtype,\n        C_dtype,\n        multiplicand_a,\n        a_index,\n        multiplicand_b,\n        b_index,\n        accumulator,\n        c_index,\n        metadata,\n        meta_index,\n        sparse_selector,\n        saturate,\n    )\n\n\ndef mma_store(dtype, m, n, dst_ptr, src_ptr, src_offset, dst_stride):\n    \"\"\"TVM intrinsic for storing the result of PTX MMA into a destination pointer\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    m : IntImm\n        The shape of mma fragment.\n\n    n : IntImm\n        The shape of mma fragment.\n\n    dst_ptr : Var\n        The destination pointer variable.\n\n    src_ptr : Var\n        The source pointer variable.\n\n    src_offset : Expr\n        The source offset.\n\n    dst_stride : Var\n        The destination stride.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        dtype,\n        \"tir.mma_store\",\n        m,\n        n,\n        dst_ptr,\n        src_ptr,\n        src_offset,\n        dst_stride,\n    )\n\n\ndef mma_fill(dtype, local_size, local_ptr, offset):\n    \"\"\"TVM intrinsic for zero-initalizing an MMA accumulation registor\n\n    Parameters\n    ----------\n    dtype : str\n        The data type of the result.\n\n    local_size : IntImm\n        The number of elements.\n\n    local_ptr : Var\n        The destination pointer variable.\n\n    offset : Expr\n        The destination offset.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        dtype,\n        \"tir.mma_fill\",\n        local_size,\n        local_ptr,\n        offset,\n    )\n\n\ndef ptx_ldmatrix(dtype, trans, num, type, local_ptr, local_offset, smem_ptr, smem_offset):\n    \"\"\"TVM intrinsic for ptx load matrix from shared memory\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#warp-level-matrix-instructions-ldmatrix\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    trans : bool\n        The matrix is loaded in column-major format.\n\n    num : IntImm\n        The number of matrices.\n\n    type : Literal[\".b16\"]\n        The data type of the matrices.\n\n    local_ptr : Var\n        The local pointer variable.\n\n    local_offset : Expr\n        The offset of local pointer.\n\n    smem_ptr : Var\n        The shared memory pointer variable.\n\n    smem_offset : Expr\n        The offset of shared memort pointer.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        dtype,\n        \"tir.ptx_ldmatrix\",\n        trans,\n        num,\n        type,\n        local_ptr,\n        local_offset,\n        smem_ptr,\n        smem_offset,\n    )\n\n\ndef ptx_cp_async(dtype, shared_ptr, shared_offset, global_ptr, global_offset, bytes):\n    \"\"\"TVM intrinsic for ptx async copy from global to shared memory\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-cp-async\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    shared_ptr : Var\n        The shared memory pointer variable.\n\n    shared_offset : Expr\n        The offset of shared memory pointer.\n\n    global_ptr : Var\n        The global memory pointer variable.\n\n    global_offset : Expr\n        The offset of global memory pointer.\n\n    bytes : int\n        The data size to copy.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        dtype, \"tir.ptx_cp_async\", shared_ptr, shared_offset, global_ptr, global_offset, bytes\n    )\n\n\ndef ptx_commit_group():\n    \"\"\"TVM intrinsic for ptx async copy commit\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-cp-async-commit-group\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"\", \"tir.ptx_commit_group\")\n\n\ndef ptx_wait_group(num):\n    \"\"\"TVM intrinsic for ptx async copy wait\n    https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-cp-async-wait-group\n\n    Parameters\n    ----------\n    num : int\n        The number of the most recent uncommitted pending cp.async groups to wait.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"\", \"tir.ptx_wait_group\", num)\n\n\ndef vectorlow(dtype, vec):\n    \"\"\"Get the low level half of the vector\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    vec : list\n       The input vector.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(dtype, \"tir.vectorlow\", vec)\n\n\ndef vectorhigh(dtype, vec):\n    \"\"\"Get the high level half of the vector\n\n    Parameters\n    ----------\n    dtype : str\n       The data type of the result.\n\n    vec : list\n       The input vector.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(dtype, \"tir.vectorhigh\", vec)\n\n\ndef vectorcombine(dtype, vec1, vec2):\n    \"\"\"Concat two vectors\n\n    Parameters\n    ----------\n    vec1 : list\n       The input vector.\n\n    vec2 : list\n       The input vector.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(dtype, \"tir.vectorcombine\", vec1, vec2)\n\n\ndef ret(val):\n    \"\"\"Create a tir return expression\n\n    Parameters\n    ----------\n    val : Expr\n        The returned tir expression, whose data type is int, float or void pointer.\n\n    Returns\n    -------\n    ret : PrimExpr\n        The return expression\n    \"\"\"\n    return call_intrin(val.dtype, \"tir.ret\", val)\n\n\ndef any(*args, span=None):\n    \"\"\"Create a new experssion of the union of all conditions in the arguments\n\n    Parameters\n    ----------\n    args : list\n        List of symbolic boolean expressions\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    expr: Expr\n        Expression\n    \"\"\"\n    if not args:\n        raise ValueError(\"Any must take at least 1 argument\")\n    if len(args) == 1:\n        return args[0]\n    val = _ffi_api._OpOr(args[0], args[1], span)  # type: ignore\n    for i in range(2, len(args)):\n        val = _ffi_api._OpOr(val, args[i], span)  # type: ignore\n    return val\n\n\ndef all(*args, span=None):\n    \"\"\"Create a new expression of the intersection of all conditions in the\n      arguments\n\n    Parameters\n    ----------\n    args : list\n        List of symbolic boolean expressions\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    expr: Expr\n        Expression\n    \"\"\"\n    if not args:\n        raise ValueError(\"Any must take at least 1 argument\")\n    if len(args) == 1:\n        return args[0]\n    val = _ffi_api._OpAnd(args[0], args[1], span)  # type: ignore\n    for i in range(2, len(args)):\n        val = _ffi_api._OpAnd(val, args[i], span)  # type: ignore\n    return val\n\n\n@tvm._ffi.register_func(\"tvm.default_trace_action\")\ndef _tvm_default_trace_action(*args):\n    print(list(args))\n\n\ndef trace(args, trace_action=\"tvm.default_trace_action\"):\n    \"\"\"Trace tensor data at the runtime.\n\n    The trace function allows to trace specific tensor at the\n    runtime. The tracing value should come as last argument.\n    The trace action should be specified, by default\n    tvm.default_trace_action is used.\n\n    Parameters\n    ----------\n    args : list of Expr or Buffers.\n        Positional arguments.\n\n    trace_action : str.\n        The name of the trace action.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n\n    See Also\n    --------\n    tvm.tir.call_packed : Creates packed function.\n    \"\"\"\n    if not isinstance(args, list):\n        raise Exception(\"tvm.tir.trace consumes the args as list type\")\n    call_args = [_pack_buffer(x) if isinstance(x, Buffer) else x for x in args]\n    call_args.insert(0, trace_action)\n    return tvm.tir.Call(args[-1].dtype, Op.get(\"tir.tvm_call_trace_packed\"), call_args)\n\n\ndef min_value(dtype, span=None):\n    \"\"\"minimum value of dtype\n\n    Parameters\n    ----------\n    dtype : str\n        The data type.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    value : tvm.Expr\n        The minimum value of dtype.\n    \"\"\"\n    return _ffi_api.min_value(dtype, span)  # type: ignore\n\n\ndef max_value(dtype: str, span: Optional[Span] = None) -> Any:\n    \"\"\"maximum value of dtype\n\n    Parameters\n    ----------\n    dtype : str\n        The data type.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    value : tvm.Expr\n        The maximum value of dtype.\n    \"\"\"\n    return _ffi_api.max_value(dtype, span)  # type: ignore\n\n\ndef infinity(dtype: str, span: Optional[Span] = None) -> Any:\n    \"\"\"infinity value of dtype\n\n    Parameters\n    ----------\n    dtype : str\n        The data type.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    value : tvm.Expr\n        The infinity value of dtype.\n    \"\"\"\n    return _ffi_api.infinity(dtype, span)  # type: ignore\n\n\ndef reinterpret(dtype, value) -> Any:\n    \"\"\"infinity value of dtype\n\n    Parameters\n    ----------\n    dtype : str\n        The data type.\n\n    value : PrimExpr\n        The input value.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    value : tvm.Expr\n        The reinterpret cast value of dtype.\n    \"\"\"\n    return call_intrin(dtype, \"tir.reinterpret\", value)\n\n\ndef exp(x):\n    \"\"\"Take exponential of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.exp\", x)\n\n\ndef exp2(x):\n    \"\"\"Calculate 2**x\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.exp2\", x)\n\n\ndef exp10(x):\n    \"\"\"Calculate 10**x\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.exp10\", x)\n\n\ndef erf(x):\n    \"\"\"Take gauss error function of the input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.erf\", x)\n\n\ndef tanh(x):\n    \"\"\"Take hyperbolic tanh of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.tanh\", x)\n\n\ndef sigmoid(x):\n    \"\"\"Quick function to get sigmoid\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.sigmoid\", x)\n\n\ndef log(x):\n    \"\"\"Take log of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.log\", x)\n\n\ndef log2(x):\n    \"\"\"Take log2 of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.log2\", x)\n\n\ndef log10(x):\n    \"\"\"Take log10 of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.log10\", x)\n\n\ndef log1p(x):\n    \"\"\"Take log(x + 1) with respect to input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.log1p\", x)\n\n\ndef tan(x):\n    \"\"\"Take tan of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.tan\", x)\n\n\ndef cos(x):\n    \"\"\"Take cos of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.cos\", x)\n\n\ndef cosh(x):\n    \"\"\"Take cosh of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.cosh\", x)\n\n\ndef acos(x):\n    \"\"\"Take acos of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.acos\", x)\n\n\ndef acosh(x):\n    \"\"\"Take acos of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.acosh\", x)\n\n\ndef sin(x):\n    \"\"\"Take sin of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.sin\", x)\n\n\ndef sinh(x):\n    \"\"\"Take sinh of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.sinh\", x)\n\n\ndef asin(x):\n    \"\"\"Take asin of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.asin\", x)\n\n\ndef asinh(x):\n    \"\"\"Take asinh of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.asinh\", x)\n\n\ndef atan(x):\n    \"\"\"Take atan of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.atan\", x)\n\n\ndef atanh(x):\n    \"\"\"Take atanh of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.atanh\", x)\n\n\ndef atan2(x1, x2):\n    \"\"\"Take arctan2(x1, x2).\n\n    Parameters\n    ----------\n    x1 : PrimExpr\n        Input argument.\n\n    x2 : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x1.dtype, \"tir.atan2\", x1, x2)\n\n\ndef sqrt(x):\n    \"\"\"Take square root of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.sqrt\", x)\n\n\ndef rsqrt(x):\n    \"\"\"Take reciprocal of square root of input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.rsqrt\", x)\n\n\ndef clz(x):\n    \"\"\"Count leading zero bits of an integer x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input 32 or 64 bit integer.\n        The result is undefined if the input is 0.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(\"int32\", \"tir.clz\", x)\n\n\ndef floor(x: PrimExprWithOp, span=None):\n    \"\"\"Take floor of float input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.floor(x, span)  # type: ignore\n\n\ndef ceil(x, span=None):\n    \"\"\"Take ceil of float input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.ceil(x, span)  # type: ignore\n\n\ndef trunc(x, span=None):\n    \"\"\"Get truncated value of the input.\n\n    The truncated value of the scalar x is the\n    nearest integer i which is closer to zero than x is.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.trunc(x, span)  # type: ignore\n\n\ndef abs(x, span=None):\n    \"\"\"Get absolute value of the input element-wise.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.abs(x, span)  # type: ignore\n\n\ndef round(x, span=None):\n    \"\"\"Round elements of the array to the nearest integer.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.round(x, span)  # type: ignore\n\n\ndef nearbyint(x, span=None):\n    \"\"\"Round elements of the array to the nearest integer.\n    This intrinsic uses llvm.nearbyint instead of llvm.round\n    which is faster but will results different from te.round.\n    Notably nearbyint rounds according to the rounding mode,\n    whereas te.round (llvm.round) ignores that.\n    For differences between the two see:\n    https://en.cppreference.com/w/cpp/numeric/math/round\n    https://en.cppreference.com/w/cpp/numeric/math/nearbyint\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.nearbyint(x, span)  # type: ignore\n\n\ndef nextafter(x1, x2):\n    \"\"\"Return the next floating-point value after x1 towards x2.\n\n    Parameters\n    ----------\n    x1 : PrimExpr\n        Input argument.\n\n    x2 : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x1.dtype, \"tir.nextafter\", x1, x2)  # type: ignore\n\n\ndef hypot(x1, x2):\n    \"\"\"Equivalent to sqrt(x1**2 + x2**2), element-wise.\n\n    Parameters\n    ----------\n    x1 : PrimExpr\n        Input argument.\n\n    x2 : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x1.dtype, \"tir.hypot\", x1, x2)  # type: ignore\n\n\ndef copysign(x1, x2):\n    \"\"\"Change the sign of x1 to that of x2, element-wise.\n\n    Parameters\n    ----------\n    x1 : PrimExpr\n        Input argument.\n\n    x2 : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x1.dtype, \"tir.copysign\", x1, x2)  # type: ignore\n\n\ndef ldexp(x1, x2):\n    \"\"\"Returns x1 * (2 ** x2).\n\n    Parameters\n    ----------\n    x1 : PrimExpr\n        Input argument.\n\n    x2 : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x1.dtype, \"tir.ldexp\", x1, x2)  # type: ignore\n\n\ndef likely(cond, span=None):\n    \"\"\"Mark condition as likely.\n\n    Parameters\n    ----------\n\n    cond : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The marked expression.\n    \"\"\"\n    return _ffi_api.likely(cond, span)  # type: ignore\n\n\ndef isnan(x, span=None):\n    \"\"\"Check if input value is Nan.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.isnan(x, span)  # type: ignore\n\n\ndef isnullptr(x, span=None):\n    \"\"\"Check if input value is nullptr.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(\"bool\", \"tir.isnullptr\", x, span=span)  # type: ignore\n\n\ndef isfinite(x, span=None):\n    \"\"\"Check if input value is finite.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.isfinite(x, span)  # type: ignore\n\n\ndef isinf(x, span=None):\n    \"\"\"Check if input value is infinite.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.isinf(x, span)  # type: ignore\n\n\ndef power(x, y, span=None):\n    \"\"\"x power y\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    y : PrimExpr\n        The exponent\n\n    span : Optional[Span]\n        The location of this operator in the source code.\n\n    Returns\n    -------\n    z : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api._OpPow(convert(x), convert(y), span)  # type: ignore\n\n\ndef popcount(x):\n    \"\"\"Count the number of set bits in input x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.popcount\", x)\n\n\ndef q_multiply_shift(x, y, q, s):\n    \"\"\"Execute a multiplication between two Q-numbers x and y\n    followed by a right shift s. The mathematical expression is:\n\n       out = round(x*y*2^-s)\n\n    More about Q-numbers here: https://en.wikipedia.org/wiki/Q_(number_format)\n    The rounding rule is to the nearest value, rounding half up\n    (i.e., round(x.1) = x and round (x.5) = x+1)\n\n    Parameters\n    ----------\n    x : PrimExpr\n        First Q-number\n    y : PrimExpr\n        Second Q-number\n    q : PrimExpr\n        Number of fractional bits in x and y. Needs to be > 0\n    s : PrimExpr\n        Integer shift\n\n    Returns\n    -------\n    y : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(\"int32\", \"tir.q_multiply_shift\", x, y, q, s)\n\n\ndef q_multiply_shift_per_axis(\n    x: PrimExpr,\n    y: PrimExpr,\n    ls: PrimExpr,\n    rs: PrimExpr,\n    q: IntImm,\n    is_lshift_required: IntImm,\n    is_rshift_required: IntImm,\n):\n    \"\"\"Execute a multiplication between two Q-numbers x and y\n\n    Parameters\n    ----------\n    x : PrimExpr\n        First Q-number.\n    y : PrimExpr\n        Second Q-number.\n    ls : PrimExpr\n         Integer left shift.\n    rs : PrimExpr\n         Integer right shift.\n    q : IntImm\n        Number of fractional bits in x and y. Needs to be > 0.\n    is_lshift_required : IntImm\n                         Whether we need to do left shift or not.\n    is_rshift_required : IntImm\n                         Whether we need to do right shift or not.\n\n    Returns\n    -------\n    z : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(\n        \"int32\",\n        \"tir.q_multiply_shift_per_axis\",\n        x,\n        y,\n        ls,\n        rs,\n        q,\n        is_lshift_required,\n        is_rshift_required,\n    )\n\n\ndef shift_left(x, y, span=None):\n    \"\"\"Return the result of x left shifted by y bits.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    y : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    z : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.left_shift(x, y, span)\n\n\ndef shift_right(x, y, span=None):\n    \"\"\"Return the result of x right shifted by y bits.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n\n    y : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    z : PrimExpr\n        The result.\n    \"\"\"\n    return _ffi_api.right_shift(x, y, span)\n\n\ndef fmod(x, y):\n    \"\"\"Return the remainder of x divided by y with the same sign as x.\n\n    Parameters\n    ----------\n    x : PrimExpr\n        Input argument.\n    y : PrimExpr\n        Input argument.\n\n    Returns\n    -------\n    z : PrimExpr\n        The result.\n    \"\"\"\n    return call_intrin(x.dtype, \"tir.fmod\", x, y)\n\n\ndef if_then_else(cond, t, f, span=None):\n    \"\"\"Conditional selection expression.\n\n    Parameters\n    ----------\n    cond : PrimExpr\n        The condition\n\n    t : PrimExpr\n        The result expression if cond is true.\n\n    f : PrimExpr\n        The result expression if cond is false.\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    result : Node\n        The result of conditional expression.\n\n    Note\n    ----\n    Unlike Select, if_then_else will not execute\n    the branch that does not satisfy the condition.\n    You can use it to guard against out of bound access.\n    Unlike Select, if_then_else cannot be vectorized\n    if some lanes in the vector have different conditions.\n    \"\"\"\n    return _ffi_api._OpIfThenElse(convert(cond), convert(t), convert(f), span)  # type: ignore\n\n\ndef div(a, b, span=None):\n    \"\"\"Compute a / b as in C/C++ semantics.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand, known to be non-negative.\n\n    b : PrimExpr\n        The right hand operand, known to be non-negative.\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n    Note\n    ----\n    When operands are integers, returns truncdiv(a, b, span).\n    \"\"\"\n    return _ffi_api._OpDiv(a, b, span)  # type: ignore\n\n\ndef indexdiv(a, b, span=None):\n    \"\"\"Compute floor(a / b) where a and b are non-negative.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand, known to be non-negative.\n\n    b : PrimExpr\n        The right hand operand, known to be non-negative.\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n\n    Note\n    ----\n    Use this function to split non-negative indices.\n    This function may take advantage of operands'\n    non-negativeness.\n    \"\"\"\n    return _ffi_api._OpIndexDiv(a, b, span)  # type: ignore\n\n\ndef indexmod(a, b, span=None):\n    \"\"\"Compute the remainder of indexdiv. a and b are non-negative.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand, known to be non-negative.\n\n    b : PrimExpr\n        The right hand operand, known to be non-negative.\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n\n    Note\n    ----\n    Use this function to split non-negative indices.\n    This function may take advantage of operands'\n    non-negativeness.\n    \"\"\"\n    return _ffi_api._OpIndexMod(a, b, span)  # type: ignore\n\n\ndef truncdiv(a, b, span=None):\n    \"\"\"Compute the truncdiv of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n\n    Note\n    ----\n    This is the default integer division behavior in C.\n    \"\"\"\n    return _ffi_api._OpTruncDiv(a, b, span)  # type: ignore\n\n\ndef truncmod(a, b, span=None):\n    \"\"\"Compute the truncmod of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n\n    Note\n    ----\n    This is the default integer division behavior in C.\n    \"\"\"\n    return _ffi_api._OpTruncMod(a, b, span)  # type: ignore\n\n\ndef floordiv(a, b, span=None):\n    \"\"\"Compute the floordiv of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n    \"\"\"\n    return _ffi_api._OpFloorDiv(a, b, span)  # type: ignore\n\n\ndef floormod(a, b, span=None):\n    \"\"\"Compute the floormod of two expressions.\n\n    Parameters\n    ----------\n    a : PrimExpr\n        The left hand operand\n\n    b : PrimExpr\n        The right hand operand\n\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    res : PrimExpr\n        The result expression.\n    \"\"\"\n    return _ffi_api._OpFloorMod(a, b, span)  # type: ignore\n\n\ndef ceildiv(lhs, rhs, span=None):\n    \"\"\"Generic ceildiv operator.\n\n    Parameters\n    ----------\n    lhs : object\n        The left operand.\n    rhs : object\n        The right operand.\n    span : Optional[Span]\n        The location of this operator in the source.\n\n    Returns\n    -------\n    op : tvm.Expr\n        The result Expr of ceildiv operaton.\n    \"\"\"\n    return _ffi_api._OpCeilDiv(lhs, rhs, span)  # type: ignore\n\n\ndef comm_reducer(fcombine, fidentity, name=\"reduce\"):\n    \"\"\"Create a commutative reducer for reduction.\n\n    Parameters\n    ----------\n    fcombine : function(Expr -> Expr -> Expr)\n        A binary function which takes two Expr as input to return a Expr.\n\n    fidentity : function(str -> Expr)\n        A function which takes a type string as input to return a const Expr.\n\n    Returns\n    -------\n    reducer : function\n        A function which creates a reduce expression over axis.\n        There are two ways to use it:\n\n        1. accept (expr, axis, where) to produce an Reduce Expr on\n           specified axis;\n        2. simply use it with multiple Exprs.\n\n    Example\n    -------\n    .. code-block:: python\n\n        n = te.var(\"n\")\n        m = te.var(\"m\")\n        mysum = te.comm_reducer(lambda x, y: x+y,\n            lambda t: tvm.tir.const(0, dtype=t), name=\"mysum\")\n        A = te.placeholder((n, m), name=\"A\")\n        k = te.reduce_axis((0, m), name=\"k\")\n        B = te.compute((n,), lambda i: mysum(A[i, k], axis=k), name=\"B\")\n    \"\"\"\n\n    def _reduce_directly(*args):\n        num = len(args)\n        # process `where` is None\n        if num == 3 and args[2] is None:\n            num = 2\n        res = args[0]\n        for i in range(num - 1):\n            res = fcombine(res, args[i + 1])\n        return res\n\n    def _make_reduce(expr, axis, where=None, init=None):\n        code = fcombine.__code__\n        assert fcombine.__code__.co_argcount == 2\n        expr = convert(expr)\n        if init is not None:\n            init = convert(init)\n        if isinstance(expr, Array):\n            size = len(expr)\n            larr = []\n            rarr = []\n            dtypes = []\n            for i in range(size):\n                dtype = expr[i].dtype\n                dtypes.append(dtype)\n                lname = code.co_varnames[0] + \"_\" + str(i)\n                larr.append(Var(lname, dtype))\n                rname = code.co_varnames[1] + \"_\" + str(i)\n                rarr.append(Var(rname, dtype))\n            if init is not None:\n                init = convert(init)\n                assert isinstance(init, Array)\n                assert len(init) == size\n                for init_i in range(size):\n                    init_i = convert(init_i)\n                    assert isinstance(\n                        init_i, (tvm.tir.ProducerLoad, tvm.tir.IntImm, tvm.tir.FloatImm)\n                    )\n            else:\n                init = convert([])\n            lhs = convert(larr)\n            rhs = convert(rarr)\n            result = fcombine(lhs, rhs)\n            id_elem = fidentity(*dtypes)\n        else:\n            assert isinstance(expr, tvm.ir.PrimExpr)\n            size = 1\n            dtype = expr.dtype\n            lvar = Var(code.co_varnames[0], dtype)\n            rvar = Var(code.co_varnames[1], dtype)\n            result = [fcombine(lvar, rvar)]\n            id_elem = [fidentity(dtype)]\n            lhs = convert([lvar])\n            rhs = convert([rvar])\n            expr = convert([expr])\n            if init is not None:\n                assert isinstance(init, (tvm.tir.ProducerLoad, tvm.tir.IntImm, tvm.tir.FloatImm))\n                init = convert([init])\n        result = convert(result)\n        id_elem = convert(id_elem)\n        combiner = CommReducer(lhs, rhs, result, id_elem)\n        axis = convert(axis if isinstance(axis, (list, tuple)) else [axis])\n        if where is None:\n            where = convert(True)\n        if init is None:\n            outputs = tuple(\n                tvm.tir.Reduce(combiner, expr, axis, where, i, convert([])) for i in range(size)\n            )\n        else:\n            outputs = tuple(\n                tvm.tir.Reduce(combiner, expr, axis, where, i, init) for i in range(size)\n            )\n        return outputs[0] if size == 1 else outputs\n\n    # pylint: disable=keyword-arg-before-vararg\n    def reducer(expr, axis, where=None, init=None, *args):\n        if isinstance(axis, (tvm.tir.IterVar, list, tuple)):\n            assert not args\n            return _make_reduce(expr, axis, where, init)\n        if where is None:\n            assert not args\n            return _reduce_directly(expr, axis)\n        return _reduce_directly(expr, axis, where, *args)\n\n    doc_str = \"\"\"Create a {0} expression over axis.\n\n              Parameters\n              ----------\n              expr : PrimExpr\n                  The source expression.\n              axis : IterVar\n                  The reduction IterVar axis\n              where : optional, Expr\n                  Filtering predicate of the reduction.\n              Returns\n              -------\n              value : PrimExpr\n                  The result value.\n\n              Example\n              -------\n              .. code-block:: python\n\n                m = te.var(\"m\")\n                n = te.var(\"n\")\n                A = te.placeholder((m, n), name=\"A\")\n                k = te.reduce_axis((0, n), name=\"k\")\n\n                # there are two way to use this {0} reducer:\n                # mode 1, accept (expr, axis, where) to produce an Reduce Expr\n                # tvm.{0} represents tvm.te.{0} or tvm.tir.{0}.\n                B = te.compute((m,), lambda i: tvm.{0}(A[i, k], axis=k), name=\"B\")\n\n                # mode 2, simply use it with multiple Exprs:\n                {0}_res = tvm.{0}(m, n)\n              \"\"\"\n    reducer.__doc__ = doc_str.format(name)\n    return reducer\n\n\ndef TVMBackendAllocWorkspace(device_type, device_id, nbytes, dtype_code_hint, dtype_bits_hint):\n    \"\"\"Backend function to allocate temporal workspace\n\n    Parameters\n    ----------\n    device_type : int\n        The device type which the space will be allocated.\n\n    device_id : int\n        The device id which the space will be allocated.\n\n    nbytes : int\n        The size of the space requested.\n\n    dtype_code_hint : int\n        The type code of the array elements. Only used in certain backends such as OpenGL.\n\n    dtype_bits_hint : int\n        The type bits of the array elements. Only used in certain backends such as OpenGL.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\n        \"handle\",\n        \"tir.TVMBackendAllocWorkspace\",\n        device_type,\n        device_id,\n        nbytes,\n        dtype_code_hint,\n        dtype_bits_hint,\n    )\n\n\ndef TVMBackendFreeWorkspace(device_type, device_id, ptr):\n    \"\"\"Backend function to free temporal workspace.\n\n    Parameters\n    ----------\n    device_type : int\n        The device type which the space will be allocated.\n\n    device_id : int\n        The device id which the space will be allocated.\n\n    ptr : Var\n        The result allocated space pointer.\n\n    Returns\n    -------\n    call : PrimExpr\n        The call expression.\n    \"\"\"\n    return call_intrin(\"int32\", \"tir.TVMBackendFreeWorkspace\", device_type, device_id, ptr)\n\n\n# pylint: disable=unnecessary-lambda\nsum = comm_reducer(lambda x, y: x + y, lambda t: const(0, dtype=t), name=\"sum\")\nmin = comm_reducer(lambda x, y: _ffi_api._OpMin(x, y, None), max_value, name=\"min\")  # type: ignore\nmax = comm_reducer(lambda x, y: _ffi_api._OpMax(x, y, None), min_value, name=\"max\")  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import\n\"\"\"Namespace for the TensorIR schedule API.\"\"\"\n\nfrom .block_scope import BlockScope, Dependency, DepKind, StmtSRef\nfrom .instruction import Instruction, InstructionKind\nfrom .schedule import BlockRV, ExprRV, LoopRV, Schedule, ScheduleError\nfrom .state import ScheduleDebugMask, ScheduleState\nfrom .trace import Trace\n\nfrom . import analysis\nfrom . import transform\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.schedule\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"tir.schedule\", __name__)  # pylint: disable=protected-access\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/_type_checker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Type checking functionality\"\"\"\nimport collections\nimport collections.abc\nimport functools\nimport inspect\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union\nimport typing\n\n\ndef _is_none_type(type_: Any) -> bool:\n    return type_ is None or type_ is type(None)\n\n\nif hasattr(typing, \"_GenericAlias\"):\n    # For python versions 3.7 onward, check the __origin__ attribute.\n\n    class _Subtype:\n        @staticmethod\n        def _origin(type_: Any) -> Any:\n            if hasattr(typing, \"_SpecialGenericAlias\"):\n                if isinstance(type_, typing._SpecialGenericAlias):  # type: ignore # pylint: disable=protected-access\n                    return type_.__origin__\n\n            if isinstance(type_, typing._GenericAlias):  # type: ignore # pylint: disable=protected-access\n                return type_.__origin__\n            return None\n\n        @staticmethod\n        def list_(type_: Any) -> Any:\n            if _Subtype._origin(type_) is list:\n                if hasattr(typing, \"get_args\"):\n                    (subtype,) = typing.get_args(type_)  # type: ignore\n                else:\n                    (subtype,) = type_.__args__\n                return [subtype]\n            return None\n\n        @staticmethod\n        def dict_(type_: Any) -> Any:\n            if _Subtype._origin(type_) is dict:\n                if hasattr(typing, \"get_args\"):\n                    (ktype, vtype) = typing.get_args(type_)  # type: ignore\n                else:\n                    (ktype, vtype) = type_.__args__\n                return [ktype, vtype]\n            return None\n\n        @staticmethod\n        def tuple_(type_: Any) -> Optional[List[type]]:\n            if _Subtype._origin(type_) is tuple:\n                if hasattr(typing, \"get_args\"):\n                    subtypes = typing.get_args(type_)  # type: ignore\n                else:\n                    subtypes = type_.__args__\n                return subtypes\n            return None\n\n        @staticmethod\n        def optional(  # pylint: disable=missing-function-docstring\n            type_: Any,\n        ) -> Optional[List[type]]:\n            if _Subtype._origin(type_) is Union:\n                if hasattr(typing, \"get_args\"):\n                    subtypes = typing.get_args(type_)  # type: ignore\n                else:\n                    subtypes = type_.__args__\n                if len(subtypes) == 2 and _is_none_type(subtypes[1]):\n                    return [subtypes[0]]\n            return None\n\n        @staticmethod\n        def union(type_: Any) -> Optional[List[type]]:  # pylint: disable=missing-function-docstring\n            if _Subtype._origin(type_) is Union:\n                if hasattr(typing, \"get_args\"):\n                    subtypes = typing.get_args(type_)  # type: ignore\n                else:\n                    subtypes = type_.__args__\n                if len(subtypes) != 2 or not _is_none_type(subtypes[1]):\n                    return list(subtypes)\n            return None\n\n        @staticmethod\n        def callable(type_: Any) -> Optional[List[type]]:\n            if _Subtype._origin(type_) is collections.abc.Callable:\n                if hasattr(typing, \"get_args\"):\n                    subtypes = typing.get_args(type_)  # type: ignore\n                else:\n                    subtypes = type_.__args__\n                return subtypes\n            return None\n\nelif hasattr(typing, \"_Union\"):\n    # For python 3.6 and below, check the __name__ attribute, or CallableMeta.\n\n    class _Subtype:  # type: ignore\n        @staticmethod\n        def list_(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing.GenericMeta):  # type: ignore # pylint: disable=no-member\n                if type_.__name__ == \"List\":\n                    (subtype,) = type_.__args__  # type: ignore # pylint: disable=no-member\n                    return [subtype]\n            return None\n\n        @staticmethod\n        def dict_(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing.GenericMeta):  # type: ignore # pylint: disable=no-member\n                if type_.__name__ == \"Dict\":\n                    (ktype, vtype) = type_.__args__  # type: ignore # pylint: disable=no-member\n                    return [ktype, vtype]\n            return None\n\n        @staticmethod\n        def tuple_(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing.GenericMeta):  # type: ignore # pylint: disable=no-member\n                if type_.__name__ == \"Tuple\":\n                    subtypes = type_.__args__  # type: ignore # pylint: disable=no-member\n                    return subtypes\n            return None\n\n        @staticmethod\n        def optional(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing._Union):  # type: ignore # pylint: disable=no-member,protected-access\n                subtypes = type_.__args__\n                if len(subtypes) == 2 and _is_none_type(subtypes[1]):\n                    return [subtypes[0]]\n            return None\n\n        @staticmethod\n        def union(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing._Union):  # type: ignore # pylint: disable=no-member,protected-access\n                subtypes = type_.__args__\n                if len(subtypes) != 2 or not _is_none_type(subtypes[1]):\n                    return list(subtypes)\n            return None\n\n        @staticmethod\n        def callable(type_: Any) -> Optional[List[type]]:\n            if isinstance(type_, typing.CallableMeta):  # type: ignore # pylint: disable=no-member,protected-access\n                subtypes = type_.__args__\n                return subtypes\n            return None\n\n\ndef _dispatcher(type_: Any) -> Tuple[str, List[type]]:\n    if _is_none_type(type_):\n        return \"none\", []\n\n    subtype = _Subtype.list_(type_)\n    if subtype is not None:\n        return \"list\", subtype\n\n    subtype = _Subtype.dict_(type_)\n    if subtype is not None:\n        return \"dict\", subtype\n\n    subtype = _Subtype.tuple_(type_)\n    if subtype is not None:\n        return \"tuple\", subtype\n\n    subtype = _Subtype.optional(type_)\n    if subtype is not None:\n        return \"optional\", subtype\n\n    subtype = _Subtype.union(type_)\n    if subtype is not None:\n        return \"union\", subtype\n\n    subtype = _Subtype.callable(type_)\n    if subtype is not None:\n        return \"callable\", subtype\n\n    return \"atomic\", [type_]\n\n\ndef callable_str(*subtypes):\n    if subtypes:\n        *arg_types, return_type = subtypes\n        arg_str = \", \".join(_type2str(arg_type) for arg_type in arg_types)\n        return_type_str = _type2str(return_type)\n        return f\"Callable[[{arg_str}], {return_type_str}]\"\n    else:\n        return \"Callable\"\n\n\n_TYPE2STR: Dict[Any, Callable] = {\n    \"none\": lambda: \"None\",\n    \"atomic\": lambda t: str(t.__name__),\n    \"callable\": callable_str,\n    \"list\": lambda t: f\"List[{_type2str(t)}]\",\n    \"dict\": lambda k, v: f\"Dict[{_type2str(k)}, {_type2str(v)}]\",\n    \"tuple\": lambda *t: f\"Tuple[{', '.join([_type2str(x) for x in t])}]\",\n    \"optional\": lambda t: f\"Optional[{_type2str(t)}]\",\n    \"union\": lambda *t: f\"Union[{', '.join([_type2str(x) for x in t])}]\",\n}\n\n\ndef _type2str(type_: Any) -> str:\n    key, subtypes = _dispatcher(type_)\n    return _TYPE2STR[key](*subtypes)\n\n\ndef _val2type(value: Any):\n    if isinstance(value, list):\n        types = set(_val2type(x) for x in value)\n        if len(types) == 1:\n            return List[types.pop()]  # type: ignore\n\n        return List[Union[tuple(types)]]  # type: ignore\n\n    if isinstance(value, tuple):\n        types = tuple(_val2type(x) for x in value)  # type: ignore\n        return Tuple[types]\n\n    return type(value)\n\n\ndef _type_check_err(x: Any, name: str, expected: Any) -> str:\n    return (\n        f'\"{name}\" has wrong type. '\n        f'Expected \"{_type2str(expected)}\", '\n        f'but gets: \"{_type2str(_val2type(x))}\"'\n    )\n\n\ndef _type_check_vtable() -> Dict[str, Callable]:\n    def _type_check_none(v: Any, name: str) -> Optional[str]:\n        return None if v is None else _type_check_err(v, name, None)\n\n    def _type_check_atomic(v: Any, name: str, type_: Any) -> Optional[str]:\n        return None if isinstance(v, type_) else _type_check_err(v, name, type_)\n\n    def _type_check_callable(v: Any, name: str, *_subtypes: Any) -> Optional[str]:\n        # Current implementation only validates that the argument is\n        # callable, and doesn't validate the arguments accepted by the\n        # callable, if any.\n        return None if callable(v) else _type_check_err(v, name, Callable)\n\n    def _type_check_list(v: List[Any], name: str, type_: Any) -> Optional[str]:\n        if not isinstance(v, (list, tuple)):\n            return _type_check_err(v, name, list)\n        for i, x in enumerate(v):\n            error_msg = _type_check(x, f\"{name}[{i}]\", type_)\n            if error_msg is not None:\n                return error_msg\n        return None\n\n    def _type_check_dict(dict_obj: Dict[Any, Any], name: str, *types: Any) -> Optional[str]:\n        ktype_, vtype_ = types\n        if not isinstance(dict_obj, dict):\n            return _type_check_err(dict_obj, name, dict)\n        for k, v in dict_obj.items():\n            error_msg = _type_check(k, f\"{name}[{k}]\", ktype_)\n            if error_msg is not None:\n                return error_msg\n            error_msg = _type_check(v, f\"{name}[{k}]\", vtype_)\n            if error_msg is not None:\n                return error_msg\n        return None\n\n    def _type_check_tuple(v: Any, name: str, *types: Any) -> Optional[str]:\n        if not isinstance(v, tuple):\n            return _type_check_err(v, name, Tuple[types])\n        if len(types) != len(v):\n            return _type_check_err(v, name, Tuple[types])\n        for i, (x, type_) in enumerate(zip(v, types)):\n            error_msg = _type_check(x, f\"{name}[{i}]\", type_)\n            if error_msg is not None:\n                return error_msg\n        return None\n\n    def _type_check_optional(v: Any, name: str, type_: Any) -> Optional[str]:\n        return None if v is None else _type_check(v, name, type_)\n\n    def _type_check_union(v: Any, name: str, *types: Any) -> Optional[str]:\n        for type_ in types:\n            error_msg = _type_check(v, name, type_)\n            if error_msg is None:\n                return None\n        return _type_check_err(v, name, Union[types])\n\n    return {\n        \"none\": _type_check_none,\n        \"atomic\": _type_check_atomic,\n        \"callable\": _type_check_callable,\n        \"list\": _type_check_list,\n        \"dict\": _type_check_dict,\n        \"tuple\": _type_check_tuple,\n        \"optional\": _type_check_optional,\n        \"union\": _type_check_union,\n    }\n\n\n_TYPE_CHECK: Dict[Any, Callable] = _type_check_vtable()\n\n\ndef _type_check(v: Any, name: str, type_: Any) -> Optional[str]:\n    key, subtypes = _dispatcher(type_)\n    return _TYPE_CHECK[key](v, name, *subtypes)\n\n\nFType = TypeVar(\"FType\", bound=Callable[..., Any])\n\n\ndef type_checked(func: FType) -> FType:\n    \"\"\"Type check the input arguments of a function.\"\"\"\n    sig = inspect.signature(func)\n\n    @functools.wraps(func)\n    def wrap(*args, **kwargs):\n        bound_args = sig.bind(*args, **kwargs)\n        bound_args.apply_defaults()\n        for param in sig.parameters.values():\n            if param.annotation != inspect.Signature.empty:\n                error_msg = _type_check(\n                    bound_args.arguments[param.name],\n                    param.name,\n                    param.annotation,\n                )\n                if error_msg is not None:\n                    error_msg = f'In \"{func.__qualname__}\", {error_msg}'\n                    raise TypeError(error_msg)\n        return func(*args, **kwargs)\n\n    return wrap  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/analysis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Analysis used in TensorIR scheduling\"\"\"\nfrom typing import List, Optional\n\nimport tvm._ffi\nfrom tvm.runtime import Object\n\nfrom ..buffer import Buffer\nfrom ..stmt import For\nfrom ..expr import PrimExpr\nfrom ..function import IndexMap, PrimFunc\n\nfrom . import _ffi_api\nfrom .schedule import Schedule, BlockRV\n\n\ndef suggest_index_map(\n    buffer: Buffer,\n    indices: List[PrimExpr],\n    loops: List[For],\n    predicate: PrimExpr,\n) -> Optional[IndexMap]:\n    \"\"\"Provided the access pattern to a buffer, suggest one of the possible layout\n    transformation to maximize the locality of the access pattern.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer to be transformed.\n    indices : List[PrimExpr]\n        The access pattern to the buffer.\n    loops : List[For]\n        The loops above the buffer.\n    predicate : PrimExpr\n        The predicate of the access.\n\n    Returns\n    -------\n    index_map : Optional[IndexMap]\n        The suggested index map. None if no transformation is suggested.\n    \"\"\"\n    return _ffi_api.SuggestIndexMap(  # type: ignore # pylint: disable=no-member\n        buffer,\n        indices,\n        loops,\n        predicate,\n    )\n\n\n@tvm._ffi.register_object(\"tir.schedule.TensorizeInfo\")\nclass TensorizeInfo(Object):\n    \"\"\"Necessary information used for tensorization.\"\"\"\n\n\ndef get_tensorize_loop_mapping(\n    sch: Schedule, block: BlockRV, desc_func: PrimFunc, allow_padding: bool = False\n) -> Optional[TensorizeInfo]:\n    \"\"\"Establish a mapping between loops in a target block and an intrinsic description\n\n    Parameters\n    ----------\n    sch : Schedule\n        The schedule to be tensorized\n    block : BlockRV\n        The target block to match against\n    desc_func : PrimFunc\n        The prim func describing the computation to be tensorized\n    allow_padding : bool\n        Whether to allow padding the block iters to match the intrinsic description\n    Returns\n    -------\n    tensorize_info : Optional[TensorizeInfo]\n        TensorizeInfo structure if a valid mapping is found, None otherwise\n    \"\"\"\n    return _ffi_api.GetTensorizeLoopMapping(sch, block, desc_func, allow_padding)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.schedule.AutoTensorizeMappingInfo\")\nclass AutoTensorizeMappingInfo(Object):\n    \"\"\"Necessary information used to perform transformations for tensorization.\"\"\"\n\n\ndef get_auto_tensorize_mapping_info(\n    sch: Schedule, block: BlockRV, desc_func: PrimFunc\n) -> Optional[AutoTensorizeMappingInfo]:\n    \"\"\"Get mapping info between a target block and an intrinsic description including layout\n    transformations to apply.\n\n    Parameters\n    ----------\n    sch : Schedule\n        The schedule to be tensorized\n    block : BlockRV\n        The compute block for auto tensorization\n    desc_func : PrimFunc\n        The prim func describing the computation to be tensorized\n\n    Returns\n    -------\n    auto_tensorize_mapping_info : Optional[AutoTensorizeMappingInfo]\n        AutoTensorizeMappingInfo structure if potential mappings found, None otherwise.\n\n    Note\n    ----\n    Returning a valid AutoTensorizeMappingInfo doesn't guarantee the block can be tensorized.\n    We will need to apply the suggested layout transformations and then match against the tensor\n    intrinsics.\n    \"\"\"\n    return _ffi_api.GetAutoTensorizeMappingInfo(sch, block, desc_func)  # type: ignore\n\n\ndef has_block(sch: Schedule, block_name: str) -> bool:\n    \"\"\"Query if the given block name exists in the module associated with the provided schedule.\n\n    Parameters\n    ----------\n    sch : Schedule\n        The schedule\n    block_name : str\n        The name of the block to query\n\n    Returns\n    -------\n    yes/no: bool\n        True if the given block exists in the schedule.\n    \"\"\"\n    return _ffi_api.HasBlock(sch, block_name)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/block_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of two pillar data structure for TensorIR scheduling: StmtSRef, BlockScope.\"\"\"\nfrom enum import IntEnum\nfrom typing import List, Optional, Union\n\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom tvm.tir import Block, For\n\nfrom . import _ffi_api\n\n\n@register_object(\"tir.StmtSRef\")\nclass StmtSRef(Object):\n    \"\"\"An object that refers to schedulable elements in the TensorIR, aka \"sref\".\n\n    Glossary\n    - Block sref: An StmtSref that points to a TensorIR block.\n    - Loop sref: An StmtSRef that points to a TensorIR for loop.\n    - Parent sref: The parent sref of an sref is the block/loop sref that points to its closest\n    schedulable statement of its ancestors on the TensorIR AST.\n    - Root sref: Sref to the root block. Every sref has exactly one parent sref\n    except for root sref.\n    - Sref tree: The parent-children-relationship of srefs that forms a tree,\n    uniquely determined by the TensorIR AST.\n    \"\"\"\n\n    seq_index: int\n\n    @property\n    def stmt(self) -> Optional[Union[Block, For]]:\n        \"\"\"The block/for stmt the object refers to\"\"\"\n        return _ffi_api.StmtSRefStmt(self)  # type: ignore # pylint: disable=no-member\n\n    @property\n    def parent(self) -> Optional[\"StmtSRef\"]:\n        \"\"\"The parent sref\"\"\"\n        return _ffi_api.StmtSRefParent(self)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def inline_mark() -> \"StmtSRef\":\n        \"\"\"A special StmtSRef, which doesn't point to any stmt in the AST,\n        only serving as a \"mark\" to hint compute-at to do the work of compute-inline\"\"\"\n        return _ffi_api.StmtSRefInlineMark()  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def root_mark() -> \"StmtSRef\":\n        \"\"\"A special StmtSRef, which doesn't point to any stmt in the AST,\n        only serving as a \"mark\" to hint compute-at to do nothing\"\"\"\n        return _ffi_api.StmtSRefRootMark()  # type: ignore # pylint: disable=no-member\n\n\nclass DepKind(IntEnum):\n    \"\"\"Type of dependency.\n\n    Attributes\n    ----------\n    RAW : int = 0\n        Read-after-write dependency\n    WAW : int = 1\n        Write-after-write dependency\n    WAR : int = 2\n        Write-after-read dependency. Not supported in TensorIR for now.\n    OPAQUE: int = 3\n        Opaque dependency\n    \"\"\"\n\n    RAW = 0\n    WAW = 1\n    WAR = 2\n    OPAQUE = 3\n\n\n@register_object(\"tir.Dependency\")\nclass Dependency(Object):\n    \"\"\"A tuple (src, dst, kind) representing certain types of dependency.\n    For example, (A, B, kRAW) means block B depends on block A, and the dependency kind is\n    read-after-write, which means block B reads the result written by block A.\n\n    Parameters\n    ----------\n    src : StmtSRef\n        The source of the dependency relation\n    dst : StmtSRef\n        The destination of the dependency relation\n    kind : DepKind\n        The dependency kind\n    \"\"\"\n\n    src: StmtSRef\n    dst: StmtSRef\n    kind: DepKind\n\n\n@register_object(\"tir.BlockScope\")\nclass BlockScope(Object):\n    \"\"\"An object corresponds to each block sref in the sref tree, which\n    tracks the producer-consumer dependency between blocks.\n\n    Glossary:\n\n    - Block scope: A contiguous subtree of the sref tree, rooted at\n      each block sref, whose components are:\n\n      - scope root: a block sref\n      - internal srefs: loop srefs\n      - scope leaves: block srefs\n\n    - Child block: The scope leaf blocks under the scope root or a specific internal sref\n    \"\"\"\n\n    def get_deps_by_src(self, block: StmtSRef) -> List[Dependency]:\n        \"\"\"Get all dependencies whose `src` is the target`block`.\n\n        Parameters\n        ----------\n        block: StmtSRef\n            The queried block\n\n        Returns\n        -------\n        blocks: List[Dependency]\n            The dependencies\n        \"\"\"\n        return _ffi_api.BlockScopeGetDepsBySrc(self, block)  # type: ignore # pylint: disable=no-member\n\n    def get_deps_by_dst(self, block: StmtSRef) -> List[Dependency]:\n        \"\"\"Get all dependencies whose `dst` is the target `block`.\n\n        Parameters\n        ----------\n        block: StmtSRef\n            The queried block\n\n        Returns\n        -------\n        blocks: List[Dependency]\n            The dependencies\n        \"\"\"\n        return _ffi_api.BlockScopeGetDepsByDst(self, block)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/instruction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Schedule instructions each corresponds to a schedule primitive\"\"\"\nfrom typing import TYPE_CHECKING, Any, List, Union\n\nfrom tvm._ffi import register_object as _register_object\nfrom tvm.runtime import Object\n\nfrom . import _ffi_api\n\nif TYPE_CHECKING:\n    from .schedule import RAND_VAR_TYPE\n\n    INPUT_RV_TYPE = Union[RAND_VAR_TYPE, float, int, str, None]  # pylint: disable=invalid-name\n    OUTPUT_RV_TYPE = Union[RAND_VAR_TYPE]  # pylint: disable=invalid-name\n    ATTR_TYPE = Any\nelse:\n    INPUT_RV_TYPE = OUTPUT_RV_TYPE = ATTR_TYPE = Any\n\n\n@_register_object(\"tir.InstructionKind\")\nclass InstructionKind(Object):\n    \"\"\"Kind of an instruction, e.g. Split, Reorder, etc.\n    Besides the name, every kind of instruction has its own properties, including:\n    1) A boolean indicating if the instruction is pure, i.e. change nothing in the schedule state\n    2) A functor that applies the instruction to a TensorIR schedule\n    3) A functor that converts the instruction to a statement in python syntax\n    4) A functor that serialize its attributes to JSON\n    5) A functor that deserialize its attributes from JSON\n\n    Unlike `tvm.ir.op`, `InstructionKind` doesn't support unstructured properties,\n    mainly because there is no such usecase yet to add any other property.\n\n    Attributes\n    ----------\n    name : str\n        The name of a kind of instructions\n\n    Note\n    ----\n    The functor properties are not exposed on python side at the moment\n    \"\"\"\n\n    name: str\n\n    @property\n    def is_pure(self) -> bool:\n        \"\"\"Indicates if the instruction is pure, i.e. removing it alone doesn't mutate the schedule\n        state. For example, the instruction `GetBlock` is pure because it changes\n        nothing, while `ComputeInline` is not because removing it leads to a different resulting\n        schedule.\n\n        Returns\n        -------\n        pure : bool\n            The boolean flag indicating if the instruction is pure\n        \"\"\"\n        return bool(self._is_pure)\n\n    @staticmethod\n    def get(name: str) -> \"InstructionKind\":\n        \"\"\"Retrieve an InstructionKind using its name\n\n        Parameters\n        ----------\n        name : str\n            The registered name of the InstructionKind\n\n        Returns\n        -------\n        kind : InstructionKind\n            The InstructionKind retrieved\n        \"\"\"\n        return _ffi_api.InstructionKindGet(name)  # type: ignore # pylint: disable=no-member\n\n\n@_register_object(\"tir.Instruction\")\nclass Instruction(Object):\n    \"\"\"Schedule instructions each corresponds to a schedule primitive\n\n    Attributes\n    ----------\n    kind : InstructionKind\n        The kind of the instruction\n    inputs : List[INPUT_RV_TYPE]\n        The input random variables of the instruction,\n        and the type of each element can be one of the following:\n        - BlockRV\n        - LoopRV\n        - ExprRV\n        - float\n        - int\n        - str\n        - None\n    attrs : List[ATTR_TYPE]\n        The attributes of the instruction. Similar to attributes of an operator,\n        attributes of an instruction are arbitrary constant metadata required by the instructions.\n        For example, the name of the block to be retrieved in `GetBlock`.\n    outputs : List[OUTPUT_RV_TYPE]\n        The output random variables of the instruction,\n        and the type of each element can be one of the following:\n        - BlockRV\n        - LoopRV\n        - ExprRV, atomic variables only, won't be constants or composite PrimExpr\n    \"\"\"\n\n    kind: InstructionKind\n    inputs: List[INPUT_RV_TYPE]\n    attrs: List[ATTR_TYPE]\n    outputs: List[OUTPUT_RV_TYPE]\n\n    def __init__(\n        self,\n        kind: InstructionKind,\n        inputs: List[INPUT_RV_TYPE],\n        attrs: List[ATTR_TYPE],\n        outputs: List[OUTPUT_RV_TYPE],\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        kind : InstructionKind\n            The kind of the instruction\n        inputs : List[INPUT_RV_TYPE]\n            The input random variables of the instruction,\n            and the type of each element can be one of the following:\n            - BlockRV\n            - LoopRV\n            - ExprRV\n            - float\n            - int\n            - str\n            - None\n        attrs : List[ATTR_TYPE]\n            The attributes of the instruction. Similar to attributes of an operator,\n            attributes of an instruction are arbitrary constant metadata required by the\n            instructions. For example, the name of the block to be retrieved in `GetBlock`.\n        outputs : List[OUTPUT_RV_TYPE]\n            The output random variables of the instruction,\n            and the type of each element can be one of the following:\n            - BlockRV\n            - LoopRV\n            - ExprRV, atomic variables only, won't be constants or composite PrimExpr\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.Instruction,  # type: ignore # pylint: disable=no-member\n            kind,\n            inputs,\n            attrs,\n            outputs,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/schedule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The TensorIR schedule class\"\"\"\nfrom typing import Callable, Dict, List, Optional, Tuple, Union\n\nfrom tvm._ffi import register_object as _register_object\nfrom tvm.error import TVMError, register_error\nfrom tvm.ir import IRModule, PrimExpr\nfrom tvm.runtime import Object, String\nfrom tvm.tir import Block, Buffer, FloatImm, For, IntImm, PrimFunc\n\nfrom ..function import IndexMap\nfrom . import _ffi_api\nfrom ._type_checker import type_checked\nfrom .state import ScheduleState, StmtSRef, _parse_debug_mask, _parse_mod\nfrom .trace import Trace\n\n\n@register_error\nclass ScheduleError(TVMError):\n    \"\"\"Error that happens during TensorIR scheduling.\"\"\"\n\n\n@_register_object(\"tir.LoopRV\")\nclass LoopRV(Object):\n    \"\"\"A random variable that refers to a loop\"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Construct a new LoopRV.\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.LoopRV  # type: ignore # pylint: disable=no-member\n        )\n\n\n@_register_object(\"tir.BlockRV\")\nclass BlockRV(Object):\n    \"\"\"A random variable that refers to a block\"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Construct a new BlockRV.\"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.BlockRV  # type: ignore # pylint: disable=no-member\n        )\n\n\n# It is a workaround for mypy: https://github.com/python/mypy/issues/7866#issuecomment-549454370\n# This feature is not supported until python 3.10:\n# https://docs.python.org/3.10/whatsnew/3.10.html#pep-613-typealias\nExprRV = Union[PrimExpr]  # A random variable that evaluates to an integer\n\nRAND_VAR_TYPE = Union[ExprRV, BlockRV, LoopRV]  # pylint: disable=invalid-name\n\n# Update to `Literal[\"detail\", \"fast\", \"none\"]` once upgraded to python3.8\n_ERROR_RENDER_LEVEL: Dict[str, int] = {\n    \"detail\": 0,\n    \"fast\": 1,\n    \"none\": 2,\n}\n\n\ndef _parse_error_render_level(error_render_level: str) -> int:\n    if error_render_level not in _ERROR_RENDER_LEVEL:\n        raise ValueError(\n            'error_render_level can be \"detail\", \"fast\", or \"none\", but got: '\n            + f\"{error_render_level}\"\n        )\n    return _ERROR_RENDER_LEVEL.get(error_render_level)\n\n\ndef _parse_seed(seed: Optional[int]) -> int:\n    if seed is None:\n        return -1\n    if not isinstance(seed, int):\n        raise TypeError(f\"Expected `seed` to be int or None, but gets: {seed}\")\n    if seed < 1 or seed > 2147483647:\n        raise ValueError(f\"seed must be in the range [1, 2147483647], but gets: {seed}\")\n    return seed\n\n\n@_register_object(\"tir.Schedule\")\nclass Schedule(Object):\n    \"\"\"The user-facing schedule class\n\n    A schedule is a set of transformations that change the order of computation but\n    preserve the semantics of computation. Some example of schedules:\n    1) Split a loop into two;\n    2) Reorder two loops;\n    3) Inline the computation of a specific buffer into its consumer\n\n    The schedule class stores auxiliary information to schedule correctly and efficiently.\n\n    Link to tutorial: https://tvm.apache.org/docs/tutorials/language/schedule_primitives.html\n    \"\"\"\n\n    @type_checked\n    def __init__(\n        self,\n        mod: Union[PrimFunc, IRModule],\n        *,\n        seed: Optional[int] = None,\n        debug_mask: Union[str, int] = \"none\",\n        error_render_level: str = \"detail\",\n    ) -> None:\n        \"\"\"Construct a TensorIR schedule class from an IRModule\n\n        Parameters\n        ----------\n        mod : Union[PrimFunc, IRModule]\n            The IRModule or PrimFunc to be scheduled\n        seed: Optional[int]\n            The seed value for schedule's random state\n            Note that None and -1 means use device random, otherwise only integer between 1 and\n            2147483647 is allowed.\n        debug_mask : Union[str, int]\n            Do extra correctness checking after the class creation and each time\n            after calling the Replace method.\n            Possible choices of `debug_mask`:\n            1) \"all\" - Turn on all the checks\n            2) \"none\" - Turn off all the checks\n            3) An integer - Turn on checks according to the bitmasks provided in ScheduleDebugMask\n        error_render_level : str = \"detail\"\n            The level of error rendering. Choices: \"detail\", \"fast\", \"none\".\n            - \"detail\": Render a detailed error message, with the TIR and error locations printed\n            - \"fast: Show a simple error message without rendering or string manipulation\n            - \"none\": Do not show any error message.\n\n        Note\n        ----\n        The checks performed includes:\n        1) VerifySRefTree\n        2) VerifyCachedFlags\n        \"\"\"\n        # call the constructor\n        self.__init_handle_by_constructor__(\n            _ffi_api.TracedSchedule,  # type: ignore # pylint: disable=no-member\n            _parse_mod(mod),\n            _parse_seed(seed),\n            _parse_debug_mask(debug_mask),\n            _parse_error_render_level(error_render_level),\n        )\n\n    @staticmethod\n    def _create_non_traced(\n        mod: Union[PrimFunc, IRModule],\n        *,\n        seed: Optional[int] = None,\n        debug_mask: Union[str, int] = \"none\",\n        error_render_level: str = \"detail\",\n    ) -> \"Schedule\":\n        \"\"\"Construct a non-traced TensorIR schedule class from an IRModule.\"\"\"\n        return _ffi_api.ConcreteSchedule(  # type: ignore # pylint: disable=no-member\n            _parse_mod(mod),\n            _parse_seed(seed),\n            _parse_debug_mask(debug_mask),\n            _parse_error_render_level(error_render_level),\n        )\n\n    ########## Utilities ##########\n\n    @property\n    def mod(self) -> IRModule:\n        \"\"\"Returns the AST of the module being scheduled\"\"\"\n        return _ffi_api.ScheduleGetMod(self)  # type: ignore # pylint: disable=no-member\n\n    @property\n    def state(self) -> ScheduleState:\n        \"\"\"Returns the ScheduleState in the current schedule class\"\"\"\n        return _ffi_api.ScheduleGetState(self)  # type: ignore # pylint: disable=no-member\n\n    @property\n    def trace(self) -> Optional[Trace]:\n        \"\"\"Returns the internally maintained trace of scheduling program execution\"\"\"\n        return _ffi_api.ScheduleGetTrace(self)  # type: ignore # pylint: disable=no-member\n\n    def work_on(self, func_name: str) -> None:\n        \"\"\"Instruct the schedule to work on a function in the IRModule.\n\n        By default, the schedule works on the function with the name \"main\", or the only function in\n        the IRModule if there is only one. If there is multiple functions in the IRModule, and none\n        of their names are \"main\", users will have to call this method to explicitly specify which\n        function to work on.\n\n        This sugar function will guide the `GetBlock` method if its `func_name` is not specified.\n\n        Parameters\n        ----------\n        func_name : str\n            The name of the function to work on.\n        \"\"\"\n        _ffi_api.ScheduleWorkOn(self, func_name)  # type: ignore # pylint: disable=no-member\n\n    def copy(self) -> \"Schedule\":\n        \"\"\"Returns a copy of the schedule, including both the state and the symbol table,\n        * guaranteeing that\n        * 1) SRef tree is completely reconstructed;\n        * 2) The IRModule being scheduled is untouched;\n        * 3) All the random variables are valid in the copy, pointing to the corresponding sref\n        * reconstructed\n\n        Returns\n        -------\n        copy : Schedule\n            A new copy of the schedule\n        \"\"\"\n        return _ffi_api.ScheduleCopy(self)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def seed(self, seed: int) -> None:\n        \"\"\"Seed the randomness\n\n        Parameters\n        ----------\n        seed : int\n            The new random seed, -1 if use device random, otherwise non-negative\n        \"\"\"\n        return _ffi_api.ScheduleSeed(self, seed)  # type: ignore # pylint: disable=no-member\n\n    def fork_seed(self) -> int:\n        \"\"\"Returns a forked random state as seed for new schedules\n\n        Returns\n        -------\n        seed : int\n            The forked random state, not the same as the current random state\n        \"\"\"\n        return _ffi_api.ScheduleForkSeed(self)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def show(self, rand_var: RAND_VAR_TYPE) -> str:\n        \"\"\"Returns a string representation of the value that the random variable evaluates to\n\n        Parameters\n        ----------\n        rand_var : Union[ExprRV, BlockRV, LoopRV]\n            The random variable to be evaluated\n\n        Returns\n        -------\n        str_repr : str\n            The string representation\n        \"\"\"\n        return str(self.get(rand_var))\n\n    ########## Lookup ##########\n\n    @type_checked\n    def get(\n        self,\n        rand_var_or_sref: Union[RAND_VAR_TYPE, StmtSRef],\n    ) -> Optional[Union[int, Block, For]]:\n        \"\"\"Returns:\n        - the corresponding Block that a BlockRV evaluates to;\n        - the corresponding For that a LoopRV evaluates to;\n        - the corresponding integer that a ExprRV evaluates to;\n        - the corresponding Block that a block sref points to;\n        - the corresponding For that a loop sref points to;\n\n        Parameters\n        ----------\n        rand_var_or_sref : Union[ExprRV, BlockRV, LoopRV, StmtSRef]\n            The random variable / sref to be evaluated\n\n        Returns\n        -------\n        result : Optional[Union[int, Block, For]]\n            The corresponding result\n        \"\"\"\n        if isinstance(rand_var_or_sref, StmtSRef):\n            return rand_var_or_sref.stmt\n        result = _ffi_api.ScheduleGet(self, rand_var_or_sref)  # type: ignore # pylint: disable=no-member\n        if isinstance(result, IntImm):\n            result = result.value\n        return result\n\n    @type_checked\n    def get_sref(self, rand_var_or_stmt: Union[BlockRV, LoopRV, Block, For]) -> Optional[StmtSRef]:\n        \"\"\"Returns the corresponding sref to the given\n        1) LoopRV\n        2) BlockRV\n        3) Block\n        4) For\n\n        Parameters\n        ----------\n        rand_var_or_stmt : Union[BlockRV, LoopRV, Block, For]\n            The random variable / sref to be evaluated\n\n        Returns\n        -------\n        result : Optional[StmtSRef]\n            The corresponding result\n        \"\"\"\n        return _ffi_api.ScheduleGetSRef(  # type: ignore # pylint: disable=no-member\n            self, rand_var_or_stmt\n        )\n\n    @type_checked\n    def remove_rv(self, rand_var: RAND_VAR_TYPE) -> None:\n        \"\"\"Remove a random variable from the symbol table\n\n        Parameters\n        ----------\n        rand_var : Union[BlockRV, LoopRV, ExprRV]\n            The random variable to be removed\n        \"\"\"\n        return _ffi_api.ScheduleRemoveRV(self, rand_var)  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Sampling ##########\n\n    @type_checked\n    def sample_categorical(\n        self,\n        candidates: List[int],\n        probs: List[float],\n        decision: Optional[int] = None,\n    ) -> ExprRV:\n        \"\"\"Sample an integer given the probability distribution\n\n        Parameters\n        ----------\n        candidates : List[int]\n            The candidates to be sampled from\n        probs : List[float]\n            The probability of each candidate\n        decision : Optional[int]\n            The sampling decision, if any\n\n        Returns\n        -------\n        result : ExprRV\n            The random variable sampled from candidates\n        \"\"\"\n        return _ffi_api.ScheduleSampleCategorical(  # type: ignore # pylint: disable=no-member\n            self,\n            candidates,\n            probs,\n            decision,\n        )\n\n    @type_checked\n    def sample_perfect_tile(\n        self,\n        loop: LoopRV,\n        n: int,\n        max_innermost_factor: int = 16,\n        decision: Optional[List[int]] = None,\n    ) -> List[ExprRV]:\n        \"\"\"Sample the factors to perfect tile a specific loop\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be tiled\n        n : int\n            The number of tiles to be sampled\n        max_innermost_factor : int\n            The maximum tile size allowed to be sampled in the innermost loop\n        decision: Optional[List[int]]\n            The sampling decision, if any\n\n        Returns\n        -------\n        result : List[ExprRV]\n            A list of length `n`, the random perfect tile sizes sampled\n        \"\"\"\n        return list(\n            _ffi_api.ScheduleSamplePerfectTile(  # type: ignore  # pylint: disable=no-member\n                self,\n                loop,\n                n,\n                max_innermost_factor,\n                decision,\n            )\n        )\n\n    @type_checked\n    def sample_compute_location(\n        self,\n        block: Union[BlockRV, str],\n        decision: Optional[int] = None,\n    ) -> LoopRV:\n        \"\"\"Sample a compute-at location of the given block\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block whose compute-at location is to be sampled\n        decision : Optional[int]\n            The sampling decision\n\n        Returns\n        -------\n        result : LoopRV\n            The sampled loop where the input block is to be computed at\n        \"\"\"\n        block = self._normalize_block_arg(block)\n\n        return _ffi_api.ScheduleSampleComputeLocation(  # type: ignore  # pylint: disable=no-member\n            self,\n            block,\n            decision,\n        )\n\n    ########## Schedule: Get blocks & loops ##########\n    @type_checked\n    def get_block(\n        self,\n        name: str,\n        func_name: Optional[str] = None,\n    ) -> BlockRV:\n        \"\"\"Retrieve a block in a specific function with its name\n\n        By default, if `func_name` is not specified, the schedule will search for the block in the\n        function that is currently being \"worked on\". To switch the function to be worked on, use\n        `work_on` before calling this method.\n\n        Parameters\n        ----------\n        name : str\n            The name of the block\n        func_name : Optional[str] = None\n            The name of the function\n\n        Returns\n        -------\n        block : BlockRV\n            The block retrieved\n            IndexError is raised if 0 or multiple blocks exist with the specific name.\n        \"\"\"\n        return _ffi_api.ScheduleGetBlock(  # type: ignore # pylint: disable=no-member\n            self,\n            name,\n            func_name,\n        )\n\n    @type_checked\n    def get_loops(self, block: Union[BlockRV, str]) -> List[LoopRV]:\n        \"\"\"Get the parent loops of the block in its scope, from outer to inner\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The query block\n\n        Returns\n        -------\n        loops : List[LoopRV]\n            A list of loops above the given block in its scope, from outer to inner\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return list(_ffi_api.ScheduleGetLoops(self, block))  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def get_child_blocks(self, block_or_loop: Union[BlockRV, LoopRV]) -> List[BlockRV]:\n        \"\"\"Get the leaf blocks of a specific block/loop\n\n        Parameters\n        ----------\n        block_or_loop : Union[BlockRV, LoopRV]\n            The query block/loop\n\n        Returns\n        -------\n        blocks : List[LoopRV]\n            A list of leaf blocks inside a specific block/loop\n        \"\"\"\n        return list(_ffi_api.ScheduleGetChildBlocks(self, block_or_loop))  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def get_producers(self, block: Union[BlockRV, str]) -> List[BlockRV]:\n        \"\"\"Get the producers of a specific block\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block in the query\n\n        Returns\n        -------\n        producers : List[BlockRV]\n            A list of producers of the given block\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return list(_ffi_api.ScheduleGetProducers(self, block))  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def get_consumers(self, block: Union[BlockRV, str]) -> List[BlockRV]:\n        \"\"\"Get the consumers of a specific block\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block in the query\n\n        Returns\n        -------\n        consumers : List[BlockRV]\n            A list of consumers of the given block\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return list(_ffi_api.ScheduleGetConsumers(self, block))  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Transform loops ##########\n    @type_checked\n    def fuse(\n        self,\n        *loops: List[LoopRV],\n        preserve_unit_iters: bool = True,\n    ) -> LoopRV:\n        \"\"\"Fuse a list of consecutive loops into one. It requires:\n        1) The loops can't have annotations or thread bindings.\n        2) The (i+1)-th loop must be the only child of the i-th loop.\n        3) All loops must start with 0.\n        4) The domain of a loop to be fused cannot depend on another loop to be fused.\n\n        Parameters\n        ----------\n        *loops : List[LoopRV]\n            The loops to be fused\n\n        Returns\n        -------\n        fused_loop : LoopRV\n            The new loop after fusion\n\n        Examples\n        --------\n\n        Before applying fuse, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_fuse(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do fuse:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_fuse)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.fuse(i, j)\n            print(sch.mod[\"main\"].script())\n\n        After applying fuse, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_fuse(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                # the 2 loops are fused into 1\n                for i_j_fused in T.serial(0, 16384):\n                    with T.block(\"B\"):\n                        vi = T.axis.S(128, T.floordiv(i_j_fused, 128))\n                        vj = T.axis.S(128, T.floormod(i_j_fused, 128))\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        return _ffi_api.ScheduleFuse(self, loops, preserve_unit_iters)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def split(\n        self,\n        loop: LoopRV,\n        factors: List[Union[int, ExprRV, None]],\n        preserve_unit_iters: bool = True,\n    ) -> List[LoopRV]:\n        \"\"\"Split a loop into a list of consecutive loops. It requires:\n        1) The loop can't have annotation or thread binding.\n        2) The loop must start with 0.\n        Predicates may be added to ensure the total loop numbers keeps unchanged.\n        In `factors`, at most one of the factors can be None,\n        which will be automatically inferred.\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be split\n\n        factors: List[Union[int, ExprRV, None]]\n            The splitting factors\n            Potential inputs are:\n            - None\n            - ExprRV\n            - Positive constant integers\n\n        preserve_unit_iters : bool\n            Whether or not to preserve unit iterators in block bindings\n\n        Returns\n        -------\n        split_loops : List[LoopRV]\n            The new loops after split\n\n        Examples\n        --------\n\n        Before split, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_split(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do split:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_split)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.split(i, factors=[2, 64])\n            print(sch.mod[\"main\"].script())\n\n        After applying split, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_split(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                # the original loop is split into 2 loops\n                for i0, i1, j in T.grid(2, 64, 128):\n                    with T.block(\"B\"):\n                        vi = T.axis.S(128, i0 * 64 + i1)\n                        vj = T.axis.S(128, j)\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        # it will be checked later in C++ implementation\n        # that there is at most one None in `factors`\n        return list(\n            _ffi_api.ScheduleSplit(  # type: ignore # pylint: disable=no-member\n                self,\n                loop,\n                factors,\n                preserve_unit_iters,\n            )\n        )\n\n    @type_checked\n    def reorder(self, *ordered_loops: List[LoopRV]) -> None:\n        \"\"\"\n        Reorder a list of loops. It doesn't require the loops to be consecutive.\n        It requires:\n        1) The loops are in the same chain. That means: the loops can be ordered to [l_1, l_2, ... ,\n        l_n] where l_i is an ancestor of l_{i+1} and there are only single-branch loops between\n        l_1 and l_n (which also indicates they are under the same scope).\n        2) After reordering, the domain of an outer loop cannot depend on any of the inner loops.\n        3) For every block under the loop nests, its block binding must be affine, and the block\n        variables must be either data parallel or reduction.\n        4) No duplicated loops are allowed in the arguments.\n\n        Parameters\n        ----------\n        *ordered_loops : List[LoopRV]\n            The loops in the new order\n\n        Examples\n        --------\n\n        Before reorder, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_reorder(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do reorder:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_reorder)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.reorder(j, i)\n            print(sch.mod[\"main\"].script())\n\n        After applying reorder, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_reorder(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                # Here j and i are reordered\n                for j, i in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleReorder(self, ordered_loops)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def add_unit_loop(self, block_or_loop: Union[LoopRV, BlockRV]) -> LoopRV:\n        \"\"\"Create a new unit loop on top of the specific block or loop.\n\n        Parameters\n        ----------\n        block_or_loop : Union[LoopRV, BlockRV]\n            The block above which the new loop is created\n\n        Returns\n        -------\n        new_loop : LoopRV\n            The new unit loop\n\n        Examples\n        --------\n\n        Before add_unit_loop, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_add_unit_loop(\n                A: T.Buffer[(), \"int32\"],\n                B: T.Buffer[(), \"int32\"],\n                C: T.Buffer[(), \"int32\"],\n            ) -> None:\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(1, 0)\n                    C[()] = A[()] + B[()]\n\n        Create the schedule and do add-unit-loop:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_add_unit_loop)\n            sch.add_unit_loop(sch.get_block(\"C\"))\n            print(sch.mod[\"main\"].script())\n\n        After applying add-unit-loop, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_add_unit_loop(\n                A: T.Buffer[(), \"int32\"],\n                B: T.Buffer[(), \"int32\"],\n                C: T.Buffer[(), \"int32\"],\n            ) -> None:\n                for u in T.serial(1):\n                    with T.block(\"C\"):\n                        vi = T.axis.spatial(1, 0)\n                        C[()] = A[()] + B[()]\n        \"\"\"\n        return _ffi_api.ScheduleAddUnitLoop(self, block_or_loop)  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Manipulate ForKind ##########\n\n    @type_checked\n    def parallel(self, loop: LoopRV) -> None:\n        \"\"\"Parallelize the input loop. It requires:\n        1) The scope block that the loop is in should have stage-pipeline property\n        2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n        bindings\n        3) For each block under the loop, the loop can only be contained in data-parallel block\n        iters' bindings\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be parallelized\n\n        Examples\n        --------\n\n        Before parallel, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_parallel(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do parallel:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_parallel)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.parallel(i)\n\n        After applying parallel, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_parallel(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i in T.parallel(0, 128):\n                    for j in T.serial(0, 128):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleParallel(self, loop)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def vectorize(self, loop: LoopRV) -> None:\n        \"\"\"Vectorize the input loop. It requires:\n        1) The scope block that the loop is in should have stage-pipeline property\n        2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n        bindings\n        3) For each block under the loop, the loop can only be contained in data-parallel block\n        iters' bindings\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be vectorized\n\n        Examples\n        --------\n\n        Before vectorize, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_vectorize(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do vectorize:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_vectorize)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.vectorize(j)\n\n        After applying vectorize, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_vectorize(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i in T.serial(0, 128):\n                    for j in T.vectorized(0, 128):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleVectorize(self, loop)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def bind(self, loop: LoopRV, thread_axis: str) -> None:\n        \"\"\"Bind the input loop to the given thread axis. It requires:\n        1) The scope block that the loop is in should have stage-pipeline property\n        2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n        bindings\n        3) For each block under the loop, if the thread axis starts with \"threadIdx`, the loop can\n        only be contained in data-parallel block iter and reduction block iters' bindings. Otherwise\n        the loop can only be contained in data-parallel block iters' bindings\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be bound to the thread axis\n        thread_axis : str\n            The thread axis to be bound to the loop. Possible candidates:\n            - blockIdx.x/y/z\n            - threadIdx.x/y/z\n            - vthread.x/y/z\n            - vthread (It is a legacy behavior that will be deprecated. Please use `vthread.x/y/z`\n            instead.)\n\n        Examples\n        --------\n\n        Before bind, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_bind(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do bind:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_bind)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.bind(i, \"blockIdx.x\")\n            sch.bind(j, \"threadIdx.x\")\n\n        After applying bind, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_bind(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i in T.thread_binding(0, 128, thread = \"blockIdx.x\"):\n                    for j in T.thread_binding(0, 128, thread = \"threadIdx.x\"):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleBind(self, loop, thread_axis)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def unroll(self, loop: LoopRV) -> None:\n        \"\"\"Unroll the input loop. It requires nothing\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop to be unrolled\n\n        Examples\n        --------\n\n        Before unroll, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_unroll(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do unroll:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_unroll)\n            i, j = sch.get_loops(sch.get_block(\"B\"))\n            sch.unroll(i)\n\n        After applying unroll, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_unroll(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i in T.unroll(0, 128):\n                    for j in T.serial(0, 128):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleUnroll(self, loop)  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Insert cache stages ##########\n\n    @type_checked\n    def cache_read(\n        self,\n        block: Union[BlockRV, str],\n        read_buffer_index: Union[int, str, Buffer],\n        storage_scope: str,\n        consumer_blocks: Optional[List[Union[BlockRV, str]]] = None,\n    ) -> BlockRV:\n        \"\"\"Create a block that reads a buffer region into a read cache. It requires:\n\n        1) There is at most one block who write the buffer in the scope.\n\n        2) The scope block have stage-pipeline property.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The consumer block of the target buffer.\n\n        buffer: Union[int, str, Buffer]\n            The index of the buffer in block's read region, the unique\n            name of a read buffer in the block, or a Buffer object\n            that is within the blocks read region.\n\n        storage_scope: str\n            The target storage scope.\n\n        consumer_blocks: Optional[List[Union[BlockRV, str]]]\n            An optional list of consumers that should read from the cache. If not specified,\n            all consumers will use the cache.\n\n        Returns\n        -------\n        cached_block : BlockRV\n            The block of the cache stage\n\n        Examples\n        --------\n        Before cache_read, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_cache_read(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and cache_read:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_cache_read)\n            block_b = sch.get_block(\"B\")\n            sch.cache_read(block_b, 0, \"local\")\n            print(sch.mod[\"main\"].script())\n\n        After applying cache_read, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_cache_read(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                A_local = T.alloc_buffer((128, 128), scope=\"local\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"A_local\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        A_local[vi, vj] = A[vi, vj]\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A_local[vi, vj] * 2.0\n\n        \"\"\"\n        if consumer_blocks is None:\n            consumer_blocks = []\n\n        # Convert any string block names into Block RVs.\n        consumer_blocks = [self._normalize_block_arg(b) for b in consumer_blocks]\n        block = self._normalize_block_arg(block)\n\n        if not isinstance(read_buffer_index, int):\n            _, read_buffer_index, _ = self._normalize_buffer_arg(\n                block, read_buffer_index, required_buffer_type=\"read\"\n            )\n        return _ffi_api.ScheduleCacheRead(  # type: ignore # pylint: disable=no-member\n            self, block, read_buffer_index, storage_scope, consumer_blocks\n        )\n\n    @type_checked\n    def cache_write(\n        self,\n        block: Union[BlockRV, str],\n        write_buffer_index: Union[int, str, Buffer],\n        storage_scope: str,\n    ) -> BlockRV:\n        \"\"\"Create a block that reads a buffer region into a write cache. It requires:\n\n        1) There is only one block who write the buffer in the scope.\n\n        2) The scope block have stage-pipeline property.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The producer block of the target buffer.\n\n        write_buffer_index: int\n            The index of the buffer in block's write region, the unique\n            name of a write buffer in the block, or a Buffer object\n            that is within the blocks write region.\n\n        storage_scope: str\n            The target storage scope.\n\n\n        Returns\n        -------\n        cached_block : BlockRV\n            The block of the cache stage\n\n        Examples\n        --------\n        Before cache_write, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_cache_write(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and cache_write:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_cache_write)\n            block_b = sch.get_block(\"B\")\n            sch.cache_write(block_b, 0, \"local\")\n            print(sch.mod[\"main\"].script())\n\n        After applying cache_write, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_cache_write(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                B_local = T.alloc_buffer((128, 128), scope=\"local\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"A_local\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B_local[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = B_local[vi, vj]\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n\n        if not isinstance(write_buffer_index, int):\n            _, write_buffer_index, _ = self._normalize_buffer_arg(\n                block, write_buffer_index, required_buffer_type=\"write\"\n            )\n        return _ffi_api.ScheduleCacheWrite(  # type: ignore # pylint: disable=no-member\n            self, block, write_buffer_index, storage_scope\n        )\n\n    @type_checked\n    def cache_inplace(\n        self,\n        block: Union[BlockRV, str],\n        read_buffer_index: Union[int, str, Buffer],\n        storage_scope: str,\n    ) -> List[BlockRV]:\n        \"\"\"Create blocks that reads & write a buffer region into a cache block.\n        It requires the the target block both read & write the target buffer.\n        Mainly for inplace operation.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The target block operates on the target buffer.\n\n        read_buffer_index: int\n            The index of the buffer in block's read region, the unique\n            name of a read buffer in the block, or a Buffer object\n            that is within the blocks read region.\n\n        storage_scope: str\n            The target storage scope.\n\n\n        Returns\n        -------\n        cached_blocks : List[BlockRV]\n            The blocks of the cache stage, read cache first, write cache second\n\n        Examples\n        --------\n        Before cache_inplace, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_cache_inplace(data_io: T.Buffer[(64), \"int32\"]):\n                for i0 in T.serial(1):\n                    with T.block(\"A\"):\n                        T.reads(data_io[:64])\n                        T.writes(data_io[:64])\n                        T.evaluate(T.call_extern(\"call_impl\", data_io.data, dtype=\"\"))\n\n        Create the schedule and cache_inplace:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_cache_inplace)\n            block_a = sch.get_block(\"A\")\n            sch.cache_inplace(block_a, 0, \"local\")\n            print(sch.mod[\"main\"].script())\n\n        After applying cache_inplace, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def cache_inplace(data_io: T.Buffer[64, \"int32\"]) -> None:\n                data_io_local = T.alloc_buffer([64], dtype=\"int32\", scope=\"local\")\n                for i0 in T.serial(1):\n                    for ax0 in T.serial(64):\n                        with T.block(\"data_io_local\"):\n                            v0 = T.axis.spatial(64, ax0)\n                            T.reads(data_io[v0])\n                            T.writes(data_io_local[v0])\n                            data_io_local[v0] = data_io[v0]\n                    with T.block(\"A\"):\n                        T.reads(data_io_local[0 : 64])\n                        T.writes(data_io_local[0 : 64])\n                        T.evaluate(T.call_extern(\"call_impl\", data_io_local.data, dtype=\"\"))\n                    for ax0 in T.serial(64):\n                        with T.block(\"data_io_local\"):\n                            v0 = T.axis.spatial(64, ax0)\n                            T.reads(data_io_local[v0])\n                            T.writes(data_io[v0])\n                            data_io[v0] = data_io_local[v0]\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n\n        if not isinstance(read_buffer_index, int):\n            _, read_buffer_index, _ = self._normalize_buffer_arg(\n                block, read_buffer_index, required_buffer_type=\"read\"\n            )\n        return _ffi_api.ScheduleCacheInplace(  # type: ignore # pylint: disable=no-member\n            self, block, read_buffer_index, storage_scope\n        )\n\n    @type_checked\n    def cache_index(\n        self, block: Union[BlockRV, str], buffer_index: Union[int, str, Buffer]\n    ) -> List[BlockRV]:\n        \"\"\"Create a block to cache precomputed index for later use.\n        if there is no index computation, keep unchanged.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The target block operates on the target buffer.\n\n        buffer_index: int\n            The index of the target buffer in block's read region\n\n\n        Returns\n        -------\n        cached_blocks : List[BlockRV]\n            The blocks of the stage writing the cache buffers\n\n        Examples\n        --------\n        Before cache_inplace, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def resize(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (1, 3, 40, 40))\n                B = T.match_buffer(b, (1, 3, 80, 80))\n                for i0, i1, i2, i3 in T.grid(1, 3, 80, 80):\n                    with T.block(\"A\"):\n                        n, c, vi, vj = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                        B[n, c, vi, vj] = A[n, c, vi//4 + vj//4, vj//2]\n\n        Create the schedule and cache_index:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(resize)\n            block_a = sch.get_block(\"A\")\n            sch.cache_index(block_a, 0)\n            print(sch.mod[\"main\"].script())\n\n        After applying cache_index, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def resize_cache_index(\n                A: T.Buffer[(1, 3, 40, 40), \"float32\"], B: T.Buffer[(1, 3, 80, 80), \"float32\"]\n            ) -> None:\n                index_var_0 = T.alloc_buffer([80, 80], dtype=\"int32\", strides=[1])\n                index_var_1 = T.alloc_buffer([80], dtype=\"int32\", strides=[1])\n                for ax0, ax1 in T.grid(80, 80):\n                    with T.block(\"index_0\"):\n                        v0 = T.axis.spatial(80, ax0)\n                        v1 = T.axis.spatial(80, ax1)\n                        T.reads()\n                        T.writes(index_var_0[v0, v1])\n                        index_var_0[v0, v1] = v0 // 4 + v1 // 4\n                for ax0 in T.serial(80):\n                    with T.block(\"index_1\"):\n                        v0 = T.axis.spatial(80, ax0)\n                        T.reads()\n                        T.writes(index_var_1[v0])\n                        index_var_1[v0] = v0 // 2\n                for i0, i1, i2, i3 in T.grid(1, 3, 80, 80):\n                    with T.block(\"A\"):\n                        n, c, vi, vj = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                        T.reads(A[n, c, vi // 4 + vj // 4, vj // 2])\n                        T.writes(B[n, c, vi, vj])\n                        B[n, c, vi, vj] = A[n, c, index_var_0[vi, vj], index_var_1[vj]]\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n\n        if not isinstance(buffer_index, int):\n            _, buffer_index, _ = self._normalize_buffer_arg(\n                block, buffer_index, required_buffer_type=\"read\"\n            )\n        return _ffi_api.ScheduleCacheIndex(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index\n        )\n\n    @type_checked\n    def reindex(\n        self,\n        block: Union[BlockRV, str],\n        buffer: Union[Tuple[str, int], str, Buffer],\n    ) -> BlockRV:\n        \"\"\"Create a block that read/write a buffer region into a read/write cache with reindexing.\n        The layout of the cache will be the same as by the iterators of the block that reads/writes\n        the buffer. It requires:\n        1) There is only one block who reads/writes the target buffer\n        2) There is only one buffer load/store of this buffer in the block\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n\n            The block that accesses the target buffer.  If a string,\n            this must uniquely identify a block.\n\n        buffer: Union[Tuple[str,int], Buffer, str]\n\n            The buffer to be transformed, or a specification of how to\n            identify the buffer to be transformed.\n\n            If `buffer` if a tuple of ``(str,int)``, the first item\n            should be either \"read\" or \"write\", and the second item is\n            an index into the block's read or write regions.\n\n            If `buffer` is a string, it is the name of the buffer,\n            which must exist within the reads/writes of the block.  In\n            addition, the reads/writes of the block may not contain\n            more than one buffer with this name.\n\n            If `buffer` is a Buffer object, it must exist within the\n            reads/writes of the block.\n\n        Returns\n        -------\n        reindex_block : BlockRV\n            The block of the reindex stage\n\n        Examples\n        --------\n\n        Before transform_layout, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_reindex(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vj, vi] * 2.0\n\n        Create the schedule and do transform_layout:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_reindex)\n            block = sch.get_block(\"B\")\n            sch.reindex(block, (\"read\", 0))\n\n        After applying reindex, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_reindex(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                A_reindex = T.alloc_buffer((128, 128), \"float32\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"A_reindex\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        A_reindex[vi, vj] = A[vj, vi]\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A_reindex[vi, vj] * 2.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        buffer_index_type, buffer_index, _ = self._normalize_buffer_arg(block, buffer)\n        assert buffer_index_type in [\"read\", \"write\"], \"Invalid buffer_index_type\"\n        buffer_index_type_enum = 0 if buffer_index_type == \"read\" else 1\n        return _ffi_api.ScheduleReIndex(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index, buffer_index_type_enum\n        )\n\n    ########## Schedule: Compute location ##########\n\n    @type_checked\n    def compute_at(\n        self,\n        block: Union[BlockRV, str],\n        loop: LoopRV,\n        preserve_unit_loops: bool = False,\n        index: int = -1,\n    ) -> None:\n        \"\"\"Compute-At. Move a producer block under the specific loop, and regenerate the\n        loops induced by the block so that the buffer region produced by the producer block could\n        cover those regions consumed by its consumer blocks under the given loop. It requires:\n\n        1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n\n        2) The scope block has stage-pipeline property\n\n        3) The subtree of the scope block, where the given block is in, satisfies the compact\n        dataflow condition. i.e. all the blocks in the scope block's subtree must be either\n        complete block or reduction block\n\n        4) The block is not an output block with regard to the scope block, i.e. the buffers written\n        by the block are allocated under the scope block\n\n        5) All the consumers of the block are under the given loop\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block to be moved\n\n        loop: LoopRV\n            The loop where the block to be moved under\n\n        preserve_unit_loops: bool\n            Whether to keep the trivial loops whose extents are 1\n\n        index: int\n            The block index of the loop body subtree blocks:\n            - `index = -1` means inserted into the last possible insertion point;\n            - `index = -2` means inserted into the first possible insertion point;\n            - Otherwise, `index` is a nonnegative number that indicates the insertion point\n\n        Examples\n        --------\n\n        Before compute-at, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_compute_at(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((128, 128), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do compute-at:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_compute_at)\n            block = sch.get_block(\"B\")\n            loop, _ = sch.get_loops(sch.get_block(\"C\"))\n            sch.compute_at(block, loop, preserve_unit_loops=False)\n            print(sch.mod[\"main\"].script())\n\n        After applying compute-at, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_compute_at(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((128, 128), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i in T.serial(0, 128):\n                    for j in T.serial(0, 128):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n                    for j in T.serial(0, 128):\n                        with T.block(\"C\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            C[vi, vj] = B[vi, vj] + 1.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleComputeAt(  # type: ignore # pylint: disable=no-member\n            self,\n            block,\n            loop,\n            preserve_unit_loops,\n            index,\n        )\n\n    @type_checked\n    def reverse_compute_at(\n        self,\n        block: Union[BlockRV, str],\n        loop: LoopRV,\n        preserve_unit_loops: bool = False,\n        index: int = -1,\n    ) -> None:\n        \"\"\"Reverse-Compute-At. Move a consumer block under the specific loop, and regenerate the\n        loops induced by the block so that the buffer region consumed by the consumer block could\n        cover those regions produced by its producer blocks under the given loop. It requires:\n\n        1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n\n        2) The scope block has stage-pipeline property\n\n        3) The subtree of the scope block, where the given block is in, satisfies the compact\n        dataflow condition. i.e. all the blocks in the scope block's subtree must be either\n        complete block or reduction block\n\n        4) All the producers of the block are under the given loop\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block to be moved\n\n        loop: LoopRV\n            The loop where the block to be moved under\n\n        preserve_unit_loops: bool\n            Whether to keep the trivial loops whose extents are 1\n\n        index: int\n            The block index of the loop body subtree blocks:\n            - `index = -1` means inserted into the last possible insertion point;\n            - `index = -2` means inserted into the first possible insertion point;\n            - Otherwise, `index` is a nonnegative number that indicates the insertion point\n\n        Examples\n        --------\n\n        Before reverse-compute-at, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_reverse_compute_at(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((128, 128), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do reverse-compute-at:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_reverse_compute_at)\n            block = sch.get_block(\"C\")\n            loop, _ = sch.get_loops(sch.get_block(\"B\"))\n            sch.reverse_compute_at(block, loop, preserve_unit_loops=False)\n            print(sch.mod[\"main\"].script())\n\n        After applying reverse-compute-at, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_reverse_compute_at(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((128, 128), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i in T.serial(0, 128):\n                    for j in T.serial(0, 128):\n                        with T.block(\"B\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            B[vi, vj] = A[vi, vj] * 2.0\n                    for j in T.serial(0, 128):\n                        with T.block(\"C\"):\n                            vi, vj = T.axis.remap(\"SS\", [i, j])\n                            C[vi, vj] = B[vi, vj] + 1.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleReverseComputeAt(  # type: ignore # pylint: disable=no-member\n            self,\n            block,\n            loop,\n            preserve_unit_loops,\n            index,\n        )\n\n    @type_checked\n    def compute_inline(self, block: Union[BlockRV, str]) -> None:\n        \"\"\"Inline a block into its consumer(s). It requires:\n\n        1) The block is a complete non-root block, which only produces one buffer\n\n        2) The block must not be the only leaf in the scope.\n\n        3) The body of the block must be a BufferStore statement in\n           the form of, ``A[i, j, k, ...] = ...`` where the indices of\n           the LHS are all distinct atomic variables, and no variables\n           other than those indexing variables are allowed in the\n           statement.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block to be inlined to its consumer(s)\n\n        Examples\n        --------\n\n        Before compute-inline, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_inline(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.alloc_buffer((128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do compute-inline:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_inline)\n            sch.compute_inline(sch.get_block(\"B\"))\n            print(sch.mod[\"main\"].script())\n\n        After applying compute-inline, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_inline(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleComputeInline(self, block)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def reverse_compute_inline(self, block: Union[BlockRV, str]) -> None:\n        \"\"\"Inline a block into its only producer. It requires:\n\n        1) The block is a complete non-root block, which only produces and consumes one buffer\n\n        2) The block must not be the only leaf in the scope.\n\n        3) The only producer of the block is a read-after-write producer and a\n           complete non-root block\n\n        4) The body of the block must be a BufferStore statement in the form of,\n           ``B[f(i, j, k, ...)] = g(i, j, k, A[i, j, k, ...] ...)`` where the\n           indices of each `BufferLoad` on the RHS are all distinct atomic\n           variables, and no variables other than those indexing variables are\n           allowed in the statement.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block to be inlined to its producer\n\n        Examples\n        --------\n\n        Before reverse-compute-inline, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_inline(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.alloc_buffer((128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do reverse-compute-inline:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_inline)\n            sch.reverse_compute_inline(sch.get_block(\"C\"))\n            print(sch.mod[\"main\"].script())\n\n        After applying reverse-compute-inline, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_inline(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleReverseComputeInline(self, block)  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Reduction ##########\n\n    @type_checked\n    def decompose_reduction(self, block: Union[BlockRV, str], loop: LoopRV) -> BlockRV:\n        \"\"\"Decompose a reduction block into two separate blocks.\n\n        a) The init block, which is translated from the init statement of the reduction block;\n\n        b) The update block, which is the original block without init statement.\n\n        The init block is inserted right before the given loop.\n\n        The schedule primitive requires:\n\n        1) The input block is a reduction block.\n\n        2) The input loop is the ancestor of the block.\n\n        3) The input loop is not lower than all the loops related to reduce block var.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The reduction block to be decomposed\n        loop : LoopRV\n            The loop above which the init block is inserted before.\n\n        Returns\n        -------\n        init_block : BlockRV\n            The init block\n\n        Examples\n        --------\n        Before decompose-reduction, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_decompose(a: ty.handle, c: ty.handle) -> None:\n                A = tir.match_buffer(a, [128, 128])\n                B = tir.match_buffer(b, [128, 128])\n                C = tir.match_buffer(c, [128, 128])\n                for i, j, k in tir.grid(128, 128, 128):\n                    with tir.block([128, 128, tir.reduce_axis(0, 128)], \"C\") as [vi, vj, vk]:\n                        with tir.init():\n                            C[vi, vj] = 0.0\n                        C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n        Create the schedule and do decompose-reduction with specified loop:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_decompose)\n            C = sch.get_block(\"C\")\n            i, j, k = sch.get_loops(C)\n            sch.decompose_reduction(C, i)\n            print(sch.mod[\"main\"].script())\n\n        After applying decompose-reduction, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_decompose(a: ty.handle, c: ty.handle) -> None:\n                A = tir.match_buffer(a, [128, 128])\n                B = tir.match_buffer(b, [128, 128])\n                C = tir.match_buffer(c, [128, 128])\n                for i in tir.serial(128):\n                    for j in tir.serial(128):\n                        with tir.block([128, 128]) as [vi, vj]:\n                            C[vi, vj] = 0.0\n                for i, j, k in tir.grid(128, 128, 128):\n                    with tir.block([128, 128, tir.reduce_axis(0, 128)], \"C\") as [vi, vj, vk]:\n                        C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return _ffi_api.ScheduleDecomposeReduction(self, block, loop)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def rfactor(self, loop: LoopRV, factor_axis: int) -> LoopRV:\n        \"\"\"Factorize an associative reduction block by the specified loop.\n\n        An associative reduction cannot be parallelized directly,\n        because it leads to potential race condition during accumulation.\n        Alternatively, the reduction could be factorized on a loop with the following steps:\n        - Step 1: evenly slice the reduction into `n` separate chunks, where `n` is the loop extent\n        - Step 2: compute the chunks separately and write the result into `n` intermediate buffers;\n        - Step 3: accumulate the `n` separate buffer into the result buffer.\n        Note that the Step 2 above introduces opportunities for parallelization.\n\n        RFactor is a schedule primitive that implements the transformation described above:\n        Given a block that writes to buffer `B`, it factorizes a loop of extent `n`.\n\n        For example, the pseudocode below accumulates `B[i] = sum(A[i, : , : ])`:\n\n        .. code-block:: python\n\n            for i in range(128):                    # loop i is a data parallel loop\n                for j in range(128):                # loop j is a reduction loop\n                    for k in range(128):            # loop k is a reduction loop\n                        B[i] = B[i] + A[i, j, k]\n\n        Suppose RFactor is applied on the innermost loop `k` and `factor_axis = 1`.\n        RFactor then creates an intermediate buffer and two blocks.\n\n        1. The intermediate buffer, or \"rf-buffer\" is a buffer of rank `ndim(B) + 1` and\n        size `size(B) * n`, whose shape expands from `shape(B)` by adding an axis of `n`\n        at the position specified by `factor_axis`. For example,\n\n            * shape(B) = [1, 2, 3], factor_axis = 0  => shape(B_rf) = [n, 1, 2, 3]\n            * shape(B) = [1, 2, 3], factor_axis = 1  => shape(B_rf) = [1, n, 2, 3]\n            * shape(B) = [1, 2, 3], factor_axis = 2  => shape(B_rf) = [1, 2, n, 3]\n            * shape(B) = [1, 2, 3], factor_axis = 3  => shape(B_rf) = [1, 2, 3, n]\n\n        2. The rfactor block, or \"rf-block\", is a block that writes to the `rf-buffer` without\n        accumulating over the loop `k`, i.e. the loop `k` is converted from a reduction loop\n        to a data parallel loop. In our example, the rf-block is:\n\n        .. code-block:: python\n\n            B_rf = np.zeros((128, 128))     # the rf-buffer\n            for k in range(128):            # loop k is converted to a data parallel loop\n                for i in range(128):        # loop i is a data parallel loop (unchanged)\n                    for j in range(128):    # loop j is a reduction loop (unchanged)\n                        B_rf[i, k] = B_rf[i, k] + A[i, j, k]\n\n\n        3. The write-back block, or `wb-block`, is a block that accumulates the rf-buffer into\n        the result buffer. All the reduction loops are removed except the loop `k` for accumulation.\n        In our example, the wb-block is:\n\n        .. code-block:: python\n\n            for i in range(128):            # loop i is a data parallel loop (unchanged)\n                                            # loop j is removed because it is a reduction loop\n                for k in range(128):        # loop k is a reduction loop (unchanged)\n                    B[i] = B[i] + B_rf[i, k]\n\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The loop outside block for which we want to do rfactor\n        factor_axis : int\n            The position where the new dimension is placed in the new introduced rfactor buffer\n\n        Returns\n        -------\n        rf_block : BlockRV\n            The block which computes partial results over each slices (i.e., the first block\n            as described in the above illustration)\n\n        Examples\n        --------\n\n        Before rfactor, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_rfactor(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128, 128))\n                B = T.match_buffer(b, (128,))\n                for ii, i, j in T.grid(128, 128, 128):\n                with T.block(\"B\"):\n                    vii, vi, vj = T.axis.remap(\"SRR\", [ii, i, j])\n                    with T.init():\n                        B[vii] = 0.0\n                    B[vii] = B[vii] + A[vii, vi, vj]\n\n        Create the schedule and do rfactor:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_rfactor)\n            _, _, k = sch.get_loops(sch.get_block(\"B\"))\n            sch.rfactor(k, 0)\n            print(sch.mod[\"main\"].script())\n\n        After applying rfactor, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_rfactor(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, [128, 128, 128])\n                B = T.match_buffer(b, [128])\n                B_rf = T.alloc_buffer([128, 128])\n                for i2, ii, i in T.grid(128, 128, 128):\n                    with T.block(\"B_rf\"):\n                        vi2, vii, vi = T.axis.remap(\"SSR\", [i2, ii, i])\n                        with T.init():\n                            B_rf[vi2, vii] = 0.0\n                        B_rf[vi2, vii] = (B_rf[vi2, vii] + A[vii, vi, vi2])\n                for ii, i2 in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vii, vi2 = T.axis.remap(\"SR\", [ii, i2])\n                        with T.init():\n                            B[vii] = 0.0\n                        B[vii] = B[vii] + B_rf[vi2, vii]\n\n\n        Note\n        ----\n\n        Rfactor requires:\n        1) `loop` has only one child block, and it is a reduction block;\n        2) `loop` is a reduction loop, i.e. the loop variable is bound to only reduction variables\n        in the block binding;\n        3) `loop` is not parallelized, vectorized, unrolled or bound to any thread axis;\n        4) The block scope that `loop` is in is a staged-pipeline;\n        5) The outermost loop outside the reduction block should has the reduction block as its\n        first child block;\n        6) The outermost reduction loop should have only one child block;\n        7) An unary extent loop that is not bound to any reduction or data parallel variables in\n        the block binding should not appear under some reduction loop;\n        8) The reduction block should write to only one buffer, and its init and body are both\n        simple `BufferStore`s, and the pattern is registered as an associative reducer.\n        The pre-defined patterns include: plus, multiplication, min and max;\n        9) Each of the loops on top of the block cannot be bound to a data parallel and a\n        reduction block binding at the same time;\n        10) `factor_axis` should be in range `[-ndim(B) - 1, ndim(B)]`,\n        where `B` is the buffer that the reduction block writes to.\n        Negative indexing is normalized according to numpy convention.\n        \"\"\"\n        return _ffi_api.ScheduleRFactor(self, loop, factor_axis)  # type: ignore # pylint: disable=no-member\n\n    ######## Schedule: Block annotation ########\n\n    @type_checked\n    def storage_align(  # pylint: disable=too-many-arguments\n        self,\n        block: Union[BlockRV, str],\n        buffer_index: int,\n        axis: int,\n        factor: int,\n        offset: int,\n    ) -> None:\n        \"\"\"Set alignment requirement for specific dimension such that\n        stride[axis] == k * factor + offset for some k. This is useful to set memory layout for more\n        friendly memory access pattern. For example, we can set alignment to be factor=2, offset=1\n        to avoid bank conflict for thread access on higher dimension in GPU shared memory.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The producer block of the buffer.\n        buffer_index : int\n            The index of the buffer in block's write region.\n        axis : int\n            The dimension to be specified for alignment.\n        factor : int\n            The factor multiple of alignment.\n        offset : int\n            The required offset factor.\n\n        Examples\n        --------\n\n        Before storage_align, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_storage_align(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.alloc_buffer((128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do storage_align:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_storage_align)\n            sch.storage_align(sch.get_block(\"B\"), buffer_index=0, axis=0, factor=128, offset=1)\n            print(sch.mod[\"main\"].script())\n\n        After applying storage_align, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_storage_align(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.alloc_buffer((128, 128))\n                C = T.match_buffer(c, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        T.block_attr({\"buffer_dim_align\": [[[0, 128, 1]]]})\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        After lowering passes, buffer B will have strides as [129, 1].\n\n        Note\n        ----\n        Storage_align requires the buffer to be an intermediate buffer defined via `alloc_buffer`.\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleStorageAlign(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index, axis, factor, offset\n        )\n\n    @type_checked\n    def set_scope(self, block: Union[BlockRV, str], buffer_index: int, storage_scope: str) -> None:\n        \"\"\"Set the storage scope of a buffer, where the buffer is\n        specified by the a block and a write-index\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The producer block of the buffer\n        buffer_index : int\n            The index of the buffer in block's write region\n        storage_scope : str\n            The storage scope to be set\n\n        Examples\n        --------\n\n        Before set_scope, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_set_scope(\n                A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do set_scope:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_set_scope)\n            sch.set_scope(sch.get_block(\"B\"), buffer_index=0, storage_scope=\"shared\")\n            print(sch.mod[\"main\"].script())\n\n        After applying set_scope, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_set_scope(\n                A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                B_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B_shared[vi, vj] = A[vi, vj] * T.float32(2)\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B_shared[vi, vj] + T.float32(1)\n\n        Note\n        ----\n        Set_scope requires the buffer to be an intermediate buffer defined via `alloc_buffer`.\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        _ffi_api.ScheduleSetScope(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index, storage_scope\n        )\n\n    ########## Schedule: Blockize & Tensorize ##########\n\n    @type_checked\n    def blockize(self, loop: LoopRV) -> BlockRV:\n        \"\"\"Convert the subtree rooted at a specific loop into a block.\n\n        Parameters\n        ----------\n        loop : LoopRV\n            The root of the subtree.\n\n        Returns\n        -------\n        result : BlockRV\n            The new block.\n\n        Examples\n        --------\n\n        Before blockize, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_blockize(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                for i_0, j_0, i_1, j_1 in T.grid(8, 8, 16, 16):\n                    with T.block(\"B\"):\n                        vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                        vj = T.axis.spatial(128, j_0 * 16 + j_1)\n                        T.reads(A[vi, vj])\n                        T.writes(B[vi, vj])\n                        B[vi, vj] = A[vi, vj] * T.float32(2)\n\n        Create the schedule and do set_scope:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_blockize)\n            B = sch.get_block(\"B\")\n            _, _, i1, _ = sch.get_loops(B)\n            sch.blockize(i1)\n            print(sch.mod[\"main\"].script())\n\n        After applying blockize, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_blockize(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"]\n            )-> None:\n                for i_0, j_0 in T.grid(8, 8):\n                    with T.block(\"B_o\"):\n                        vio, vjo = T.axis.remap(\"SS\", [i_0, j_0])\n                        T.reads(A[vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16])\n                        T.writes(B[vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16])\n                        for i_1, j_1 in T.grid(16, 16):\n                            with T.block(\"B\"):\n                                vi, vj = T.axis.remap(\"SS\", [i_1, j_1])\n                                T.reads(A[vio * 16 + vi, vjo * 16 + vj])\n                                T.writes(B[vio * 16 + vi, vjo * 16 + vj])\n                                B[vio * 16 + vi, vjo * 16 + vj] = A[vio * 16 + vi, vjo * 16 + vj] \\\n                                                                  * T.float32(2)\n\n        Note\n        ----\n        blockize requires there is exactly one block under the given loop and the bindings of the\n        block are divisible by the subspace represented by the loops starting at the given loop.\n        \"\"\"\n\n        return _ffi_api.ScheduleBlockize(self, loop)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def tensorize(self, block_or_loop: Union[BlockRV, LoopRV], tensor_intrin: str) -> None:\n        \"\"\"Tensorize the computation enclosed by loop with the tensor intrinsic.\n\n        Parameters\n        ----------\n        block_or_loop : Union[BlockRV, LoopRV]\n            The loop to be tensorized.\n        tensor_intrin : str\n            The tensor intrin or the name of the tensor intrin.\n\n        Examples\n        --------\n\n        Before tensorize, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_tensorize(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"],\n                C: T.Buffer[(128, 128), \"float32\"],\n            ) -> None:\n                # body\n                # with T.block(\"root\")\n                for i_0, j_0, k_0, i_1, j_1, k_1 in T.grid(8, 8, 8, 16, 16, 16):\n                    with T.block(\"update\"):\n                        vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                        vj = T.axis.spatial(128, j_0 * 16 + j_1)\n                        vk = T.axis.reduce(128, k_0 * 16 + k_1)\n                        T.reads(C[vi, vj], A[vi, vk], B[vj, vk])\n                        T.writes(C[vi, vj])\n                        C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n        Declare and register the tensor intrinsic:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def mma_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (16, 16), align=128, offset_factor=1)\n                B = T.match_buffer(b, (16, 16), align=128, offset_factor=1)\n                C = T.match_buffer(c, (16, 16), align=128, offset_factor=1)\n\n                with T.block(\"root\"):\n                    T.reads(C[0 : 16, 0 : 16], A[0 : 16, 0 : 16], B[0 : 16, 0 : 16])\n                    T.writes(C[0 : 16, 0 : 16])\n                    for i, j, k in T.grid(16, 16, 16):\n                        with T.block(\"update\"):\n                            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n            @T.prim_func\n            def mma_intrin(a: T.handle, b: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (16, 16), align=128, offset_factor=1)\n                B = T.match_buffer(b, (16, 16), align=128, offset_factor=1)\n                C = T.match_buffer(c, (16, 16), align=128, offset_factor=1)\n\n                with T.block(\"root\"):\n                    T.reads(C[0 : 16, 0 : 16], A[0 : 16, 0 : 16], B[0 : 16, 0 : 16])\n                    T.writes(C[0 : 16, 0 : 16])\n                    T.evaluate(\n                        T.tvm_mma_sync(\n                            C.data,\n                            C.elem_offset // 256,\n                            A.data,\n                            A.elem_offset // 256,\n                            B.data,\n                            B.elem_offset // 256,\n                            C.data,\n                            C.elem_offset // 256,\n                            dtype=\"handle\",\n                        )\n                    )\n\n            tir.TensorIntrin.register(\"test_mma_intrin\", mma_desc, mma_intrin)\n\n        Create the schedule and do tensorize:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_tensorize)\n            update = sch.get_block(\"update\")\n            _, _, _, i1, _, _ = sch.get_loops(update)\n            sch.tensorize(i1, \"test_mma_intrin\")\n            print(sch.mod[\"main\"].script())\n\n        After applying tensorize, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_tensorize(\n                A: T.Buffer[(128, 128), \"float32\"],\n                B: T.Buffer[(128, 128), \"float32\"],\n                C: T.Buffer[(128, 128), \"float32\"],\n            ) -> None:\n                # body\n                # with T.block(\"root\")\n                for i_0, j_0, k_0 in T.grid(8, 8, 8):\n                    with T.block(\"update_o\"):\n                        vio, vjo, vko = T.axis.remap(\"SSR\", [i_0, j_0, k_0])\n                        T.reads(\n                            C[vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16],\n                            A[vio * 16 : vio * 16 + 16, vko * 16 : vko * 16 + 16],\n                            B[vjo * 16 : vjo * 16 + 16, vko * 16 : vko * 16 + 16],\n                        )\n                        T.writes(C[vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16])\n                        A_1 = T.match_buffer(\n                            A[vio * 16 : vio * 16 + 16, vko * 16 : vko * 16 + 16],\n                            [16, 16],\n                            dtype=\"float32\",\n                            offset_factor=1,\n                        )\n                        B_1 = T.match_buffer(\n                            B[vjo * 16 : vjo * 16 + 16, vko * 16 : vko * 16 + 16],\n                            [16, 16],\n                            dtype=\"float32\",\n                            offset_factor=1,\n                        )\n                        C_1 = T.match_buffer(\n                            C[vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16],\n                            [16, 16],\n                            dtype=\"float32\",\n                            offset_factor=1,\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                C_1.data,\n                                C_1.elem_offset // 256,\n                                A_1.data,\n                                A_1.elem_offset // 256,\n                                B_1.data,\n                                B_1.elem_offset // 256,\n                                C_1.data,\n                                C_1.elem_offset // 256,\n                                dtype=\"handle\",\n                            )\n                        )\n        \"\"\"\n        _ffi_api.ScheduleTensorize(  # type: ignore # pylint: disable=no-member\n            self, block_or_loop, tensor_intrin\n        )\n\n    ########## Schedule: Annotation ##########\n\n    PrimAnnotationValueT = Union[str, int, float, ExprRV]\n    AnnotationValueT = Union[\n        PrimAnnotationValueT,\n        List[PrimAnnotationValueT],\n        Dict[str, Union[PrimAnnotationValueT, List[PrimAnnotationValueT]]],\n    ]\n\n    @type_checked\n    def annotate(\n        self,\n        block_or_loop: Union[BlockRV, LoopRV],\n        ann_key: str,\n        ann_val: AnnotationValueT,\n    ) -> None:\n        \"\"\"Annotate a block/loop with a key value pair\n\n        Parameters\n        ----------\n        block_or_loop: Union[BlockRV, LoopRV]\n            The block/loop to be annotated\n        ann_key : str\n            The annotation key\n        ann_val : AnnotationValueT\n            The annotation value\n\n        Examples\n        --------\n\n        Before annotate, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_annotate(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do annotate:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_annotate)\n            sch.annotate(sch.get_block(\"B\"), \"ann_key\", \"ann_value\")\n            print(sch.mod[\"main\"].script())\n\n        After applying annotate, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_annotate(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        T.block_attr({\"ann_key\", \"ann_value\"})\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        if isinstance(ann_val, str):\n            ann_val = String(ann_val)\n        elif isinstance(ann_val, int):\n            ann_val = IntImm(\"int32\", ann_val)\n        elif isinstance(ann_val, float):\n            ann_val = FloatImm(\"float32\", ann_val)\n        _ffi_api.ScheduleAnnotate(  # type: ignore # pylint: disable=no-member\n            self, block_or_loop, ann_key, ann_val\n        )\n\n    @type_checked\n    def unannotate(self, block_or_loop: Union[BlockRV, LoopRV], ann_key: str) -> None:\n        \"\"\"Unannotate a block/loop's annotation with key ann_key\n\n        Parameters\n        ----------\n        block_or_loop: Union[BlockRV, LoopRV]\n            The block/loop to be unannotated\n        ann_key : str\n            The annotation key\n\n        Examples\n        --------\n\n        Before unannotate, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_unannotate(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        T.block_attr({\"ann_key\", \"ann_value\"})\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do annotate:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_unannotate)\n            sch.unannotate(sch.get_block(\"B\"), \"ann_key\")\n            print(sch.mod[\"main\"].script())\n\n        After applying unannotate, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_unannotate(a: T.handle, b: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128))\n                B = T.match_buffer(b, (128, 128))\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        \"\"\"\n        _ffi_api.ScheduleUnannotate(  # type: ignore # pylint: disable=no-member\n            self, block_or_loop, ann_key\n        )\n\n    ########## Schedule: Layout transformation ##########\n\n    def _normalize_block_arg(self, block: Union[BlockRV, str]) -> BlockRV:\n        if isinstance(block, str):\n            return self.get_block(block)\n\n        return block\n\n    def _normalize_buffer_arg(\n        self,\n        block: BlockRV,\n        buffer: Union[Tuple[str, int], int, str, Buffer],\n        required_buffer_type=None,\n    ) -> Tuple[str, int, Buffer]:\n\n        block_obj: Block = self.get(block)\n        block_name = block_obj.name_hint\n\n        def iter_buffers():\n            for i, read in enumerate(block_obj.reads):\n                yield \"read\", i, read.buffer\n            for i, write in enumerate(block_obj.writes):\n                yield \"write\", i, write.buffer\n\n        if isinstance(buffer, int):\n            buffer = (required_buffer_type, buffer)\n\n        if isinstance(buffer, str):\n            possible_buffers = {}\n            # String lookup requires ensuring that the name is unique\n            for buffer_index_type, buffer_index, buf in iter_buffers():\n                if buf.name == buffer:\n                    possible_buffers[buf] = (buffer_index_type, buffer_index)\n\n            assert possible_buffers, f\"Could not find buffer '{buffer}' in block '{block_name}'\"\n            assert (\n                len(possible_buffers) == 1\n            ), f\"Multiple buffers named '{buffer}' in block '{block_name}'\"\n            buffer_obj, (buffer_index_type, buffer_index) = next(iter(possible_buffers.items()))\n\n        elif isinstance(buffer, Buffer):\n            # Buffer lookup has unique id, can break out early\n            found = False\n            for buffer_index_type, buffer_index, buffer_obj in iter_buffers():\n                if buffer_obj.same_as(buffer):\n                    found = True\n                    break\n\n            assert found, \"Could not find buffer '{buffer.name}' in block '{block_name}'\"\n\n        elif isinstance(buffer, tuple):\n            buffer_index_type, buffer_index = buffer\n            assert buffer_index_type in [\"read\", \"write\",], (\n                f\"Invalid buffer_index_type.  \"\n                f\"Expected 'read' or 'write', \"\n                f\"but received {buffer_index_type}\"\n            )\n            buffer_list = block_obj.reads if buffer_index_type == \"read\" else block_obj.writes\n            assert 0 <= buffer_index < len(buffer_list), (\n                f\"Invalid buffer_index {buffer_index}.  \"\n                f\"Block {block_name} has only \"\n                f\"{len(buffer_list)} {buffer_index_type} buffers.\"\n            )\n            buffer_obj = buffer_list[buffer_index].buffer\n\n        else:\n            raise TypeError(f\"Invalid type for argument 'buffer': {type(buffer)}\")\n\n        if required_buffer_type is not None:\n            assert buffer_index_type == required_buffer_type, (\n                f\"Expected buffer to be read buffer, \"\n                f\"but {buffer_obj.name} was a {buffer_index_type} buffer \"\n                f\"in the specified block\"\n            )\n\n        return (buffer_index_type, buffer_index, buffer_obj)\n\n    @type_checked\n    def transform_layout(\n        self,\n        block: Union[BlockRV, str],\n        buffer: Union[Tuple[str, int], str, Buffer],\n        index_map: Union[IndexMap, Callable],\n        pad_value: Optional[Union[int, float, PrimExpr, IndexMap, Callable]] = None,\n    ) -> None:\n        \"\"\"Apply a transformation represented by IndexMap to buffer\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n\n            The block that accesses the target buffer.  If a string,\n            this must uniquely identify a block.\n\n        buffer: Union[Tuple[str,int], Buffer, str]\n\n            The buffer to be transformed, or a specification of how to\n            identify the buffer to be transformed.\n\n            If `buffer` if a tuple of ``(str,int)``, the first item\n            should be either \"read\" or \"write\", and the second item is\n            an index into the block's read or write regions.\n\n            If `buffer` is a string, it is the name of the buffer,\n            which must exist within the reads/writes of the block.  In\n            addition, the reads/writes of the block may not contain\n            more than one buffer with this name.\n\n            If `buffer` is a Buffer object, it must exist within the\n            reads/writes of the block.\n\n        index_map : Union[IndexMap, Callable]\n\n            The transformation to apply.\n\n            If `index_map` is a callable, and the returned list\n            contains IndexMap.AXIS_SEPARATOR, the SetAxisSeparators\n            primitive will be called in addition to the\n            TransformLayout primitive.\n\n        pad_value: Optional[Union[int, float, PrimExpr, IndexMap, Callable]]\n\n            The value to be used for any padding introduced by the\n            transformation.  If the schedule contains a producer block\n            for the specified buffer, the pad value will be written as\n            part of the producer block if possible, or after the producer\n            block otherwise.  Otherwise, if the buffer is an input, will\n            insert an annotation block to state that the padding contains\n            the known value.\n\n            The pad value may not contain instances of BufferLoad,\n            except where it loads a value from the buffer being\n            transformed (e.g. to create a circular buffer with\n            padding that consists of repeated elements).\n\n            Note: If applied to an input buffer, the calling scope is\n            responsible for ensuring that the pad_value is present.\n            Algebraic symplifications, branch elimination, and other\n            optimizations may assume that this precondition is met, and\n            may result in incorrect results being returned.\n\n            If None, the transformation may not introduce padding.\n\n            If an int, float or PrimExpr, the transformation is the\n            specific value to be present in the padding.\n\n            If an IndexMap or Callable, the transformation is the\n            value to be present in the padding in terms of the\n            transformed index.\n\n        Examples\n        --------\n        Before transform_layout, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_transform_layout(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((128, 128), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do transform_layout:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_storage_align)\n            sch.transform_layout(sch.get_block(\"B\"), buffer=(\"write\",0),\n                                 index_map=lambda m, n: (m // 16, n // 16, m % 16, n % 16))\n            print(sch.mod[\"main\"].script())\n\n        After applying transform_layout, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def two_elementwise_transformed_intermediate_buffer(a: T.handle, c: T.handle) -> None:\n                A = T.match_buffer(a, (128, 128), \"float32\")\n                B = T.alloc_buffer((8, 8, 16, 16), \"float32\")\n                C = T.match_buffer(c, (128, 128), \"float32\")\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi // 16, vj // 16, vi % 16, vj % 16] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi // 16, vj // 16, vi % 16, vj % 16] + 1.0\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        buffer_index_type, buffer_index, buffer_obj = self._normalize_buffer_arg(block, buffer)\n\n        ndim = len(buffer_obj.shape)\n        if callable(index_map):\n            index_map, axis_separators = IndexMap.from_func_with_separators(index_map, ndim=ndim)\n        else:\n            axis_separators = []\n\n        if pad_value is None:\n            pass\n        elif callable(pad_value):\n            pad_value = IndexMap.from_func(pad_value, ndim=len(index_map.final_indices))\n        elif not isinstance(pad_value, IndexMap):\n            # Explicitly convert python int/float arguments to the\n            # buffer's type.  If the default `tvm.runtime.convert`\n            # behavior is applied, these would be converted to\n            # int32/float32, which may not match the buffer's type.\n            if isinstance(pad_value, int):\n                pad_value = IntImm(buffer_obj.dtype, pad_value)\n            elif isinstance(pad_value, float):\n                pad_value = FloatImm(buffer_obj.dtype, pad_value)\n            pad_value = IndexMap.from_func(\n                lambda *indices: pad_value, ndim=len(index_map.final_indices)\n            )\n\n        buffer_index_type_enum = 0 if buffer_index_type == \"read\" else 1\n        _ffi_api.ScheduleTransformLayout(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index, buffer_index_type_enum, index_map, pad_value\n        )\n        if axis_separators:\n            _ffi_api.ScheduleSetAxisSeparator(  # type: ignore # pylint: disable=no-member\n                self, block, buffer_index, buffer_index_type_enum, axis_separators\n            )\n\n    @type_checked\n    def transform_block_layout(\n        self,\n        block: Union[BlockRV, str],\n        index_map: Union[IndexMap, Callable],\n    ) -> None:\n        \"\"\"Apply a transformation represented by IndexMap to block\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block to be transformed\n\n        index_map : Union[IndexMap, Callable]\n            The transformation to apply.\n\n        Examples\n        --------\n\n        Before transform_block_layout, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_transform_block_layout(\n                A: T.Buffer[(16, 16), \"float32\"],\n                B: T.Buffer[(16, 16), \"float32\"]\n            ) -> None:\n                for i, j in T.grid(16, 16):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n        Create the schedule and do transform_block_layout:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_transform_block_layout)\n            sch.transform_block_layout(sch.get_block(\"B\"), lambda i, j: (i * 16 + j,))\n            print(sch.mod[\"main\"].script())\n\n        After applying transform_block_layout, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_transform_block_layout(\n                A: T.Buffer[(16, 16), \"float32\"],\n                B: T.Buffer[(16, 16), \"float32\"]\n            ) -> None:\n                for i in range(256):\n                    with T.block(\"B\"):\n                        vi, = T.axis.remap(\"S\", [i])\n                        B[vi // 16, vi % 16] = A[vi // 16, vi % 16] * 2.0\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        if callable(index_map):\n            index_map = IndexMap.from_func(index_map)\n        _ffi_api.ScheduleTransformBlockLayout(  # type: ignore # pylint: disable=no-member\n            self, block, index_map\n        )\n\n    @type_checked\n    def set_axis_separator(\n        self,\n        block: Union[BlockRV, str],\n        buffer: Union[Tuple[str, int], str, Buffer],\n        axis_separators: Optional[List[int]],\n    ) -> None:\n        \"\"\"Set the axis separator of a buffer, where the buffer is specified by a block and a read\n        or write index.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n\n            The block that accesses the target buffer.  If a string,\n            this must uniquely identify a block.\n\n        buffer: Union[Tuple[str,int], Buffer, str]\n\n            The buffer to be transformed, or a specification of how to\n            identify the buffer to be transformed.\n\n            If `buffer` if a tuple of ``(str,int)``, the first item\n            should be either \"read\" or \"write\", and the second item is\n            an index into the block's read or write regions.\n\n            If `buffer` is a string, it is the name of the buffer,\n            which must exist within the reads/writes of the block.  In\n            addition, the reads/writes of the block may not contain\n            more than one buffer with this name.\n\n            If `buffer` is a Buffer object, it must exist within the\n            reads/writes of the block.\n\n        axis_separators : Optional[List[int]]\n\n            The axis separators.\n\n        Examples\n        --------\n\n        Before set_axis_separator, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_set_axis_separator(\n                A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + 1.0\n\n        Create the schedule and do set_axis_separator:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_set_axis_separator)\n            sch.set_axis_separators(sch.get_block(\"B\"), buffer_index=0, buffer_index_type=\"write\",\n                                    axis_separators=[1])\n            print(sch.mod[\"main\"].script())\n\n        After applying set_axis_separator, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_set_axis_separators(\n                A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n            ) -> None:\n                B = T.alloc_buffer([128, 128], dtype=\"float32\", axis_separators=[1])\n\n                for i, j in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        B[vi, vj] = A[vi, vj] * T.float32(2)\n                for i, j in T.grid(128, 128):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i, j])\n                        C[vi, vj] = B[vi, vj] + T.float32(1)\n        \"\"\"\n        axis_separators = axis_separators or []\n\n        block = self._normalize_block_arg(block)\n        buffer_index_type, buffer_index, _ = self._normalize_buffer_arg(block, buffer)\n\n        buffer_index_type_enum = 0 if buffer_index_type == \"read\" else 1\n        _ffi_api.ScheduleSetAxisSeparator(  # type: ignore # pylint: disable=no-member\n            self, block, buffer_index, buffer_index_type_enum, axis_separators\n        )\n\n    ########## Schedule: Padding decomposition #########\n    @type_checked\n    def decompose_padding(self, block: Union[BlockRV, str], loop: LoopRV) -> BlockRV:\n        \"\"\"Decompose a block of padding computation pattern into two separate blocks.\n\n        a) The block which fill const pad values into full write region;\n\n        b) The block which fill in-bound values into region where pad predicate is true.\n\n        The pad value filling block is inserted right before the given loop.\n\n        The schedule primitive requires:\n\n        1) The input block is a complete block.\n\n        2) The input loop is the ancestor of the block.\n\n        3) The input block is a block which match padding pattern.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The padding block to be decomposed.\n        loop : LoopRV\n            The loop above which the pad value filling block is inserted before.\n\n        Returns\n        -------\n        pad_value_block : BlockRV\n            The block filling const pad values.\n\n        Examples\n        --------\n        Before decompose-padding, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_decompose(x: T.Buffer[128, \"int32\"], y: T.Buffer[140, \"int32\"]):\n                for i in range(140):\n                    with T.block(\"block\"):\n                        vi = T.axis.remap(\"S\", [i])\n                        y[vi] = T.if_then_else(vi >= 6 and vi < 134, x[vi - 6], 0, dtype=\"int32\")\n\n        Create the schedule and do decompose-padding with specified loop:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_decompose, debug_mask=\"all\")\n            block = sch.get_block(\"block\")\n            sch.decompose_padding(block, sch.get_loops(block)[0])\n            print(sch.mod[\"main].script())\n\n        After applying decompose-padding, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_decompose(x: T.Buffer[128, \"int32\"], y: T.Buffer[140, \"int32\"]):\n                for i in T.serial(140):\n                    with T.block(\"block_pad_const\"):\n                        vi = T.axis.spatial(140, i)\n                        y[vi] = 0\n                for i in T.serial(128):\n                    with T.block(\"block\"):\n                        vi = T.axis.spatial(128, i)\n                        y[vi + 6] = x[vi]\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return _ffi_api.ScheduleDecomposePadding(  # type: ignore # pylint: disable=no-member\n            self, block, loop\n        )\n\n    @type_checked\n    def can_decompose_padding(self, block: Union[BlockRV, str], loop: LoopRV) -> bool:\n        \"\"\"Check whether the block match padding pattern and can be decomposed.\"\"\"\n        return _ffi_api.CanDecomposePadding(self, block, loop)  # type: ignore # pylint: disable=no-member\n\n    @type_checked\n    def pad_einsum(self, block: Union[BlockRV, str], padding: List[int]) -> None:\n        \"\"\"Pad the computation of Einsum.\n\n        This schedule primitives identifies the Einsum pattern in the block body, and find its\n        producer blocks. It then pads the computation of the Einsum pattern and its producer blocks.\n        The output buffer and the producer buffer is resized according to the padding size. It\n        requires the output buffer and the producer buffer to be allocated inside the PrimFunc.\n\n        The padding is a list of non-negative integers, each element corresponds to the padding for\n        each block iter in the order of block iters. The block and it's producer blocks should have\n        trivial bindings, i.e. each block iter is bound to a single loop variable. After padding,\n        thblock iter extent and the corresponding outer loop is extended by the padding size.\n\n        The size of the producer buffers are infered from the padding size of the Einsum\n        computation. The producer buffers are padded by the initial value of the corresponding\n        reduction.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The block that matches the Einsum pattern.\n\n        padding : List[int]\n            The padding for each block iter.\n\n        Examples\n        --------\n\n        Before applying pad-einsum, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_pad_einsum(\n                A: T.Buffer[(128, 127), \"float32\"],\n                B: T.Buffer[(127, 127), \"float32\"],\n                C: T.Buffer[(128, 127), \"float32\"],\n            ) -> None:\n                A_shared = T.alloc_buffer((128, 127), \"float32\", scope=\"shared\")\n                B_shared = T.alloc_buffer((127, 127), \"float32\", scope=\"shared\")\n                C_shared = T.alloc_buffer((128, 127), \"float32\", scope=\"shared\")\n                for i0, i1 in T.grid(128, 127):\n                    with T.block(\"A\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        A_shared[i, j] = A[i, j]\n                for i0, i1 in T.grid(127, 127):\n                    with T.block(\"B\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        B_shared[i, j] = B[i, j]\n                for i0, i1, i2 in T.grid(128, 127, 127):\n                    with T.block(\"C_shared\"):\n                        i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                        with T.init():\n                            C_shared[i, j] = T.float32(0)\n                        C_shared[i, j] = C_shared[i, j] + A_shared[i, k] * B_shared[k, j]\n                for i0, i1 in T.grid(128, 127):\n                    with T.block(\"C\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        C[i, j] = C_shared[i, j]\n\n        Create the schedule and do pad-einsum with specified block:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_pad_einsum, debug_mask=\"all\")\n            block = sch.get_block(\"C_shared\")\n            sch.pad_einsum(block, [0, 1, 1])\n            print(sch.mod[\"main\"].script())\n\n        After applying decompose-padding, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_pad_einsum(\n                A: T.Buffer[(128, 127), \"float32\"],\n                B: T.Buffer[(127, 127), \"float32\"],\n                C: T.Buffer[(128, 127), \"float32\"],\n            ) -> None:\n                A_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n                B_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n                C_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n                for i0, i1 in T.grid(128, 128):\n                    with T.block(\"A\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(A[i, j])\n                        T.writes(A_shared_padded[i, j])\n                        A_shared_padded[i, j] = T.if_then_else(\n                            j < 127, A[i, j], T.float32(0), dtype=\"float32\"\n                        )\n                for i0, i1 in T.grid(128, 128):\n                    with T.block(\"B\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(B[i, j])\n                        T.writes(B_shared_padded[i, j])\n                        B_shared_padded[i, j] = T.if_then_else(\n                            i < 127 and j < 127, B[i, j], T.float32(0), dtype=\"float32\"\n                        )\n                for i0, i1, i2 in T.grid(128, 128, 128):\n                    with T.block(\"C_shared\"):\n                        i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                        T.reads(A_shared_padded[i, k], B_shared_padded[k, j])\n                        T.writes(C_shared_padded[i, j])\n                        with T.init():\n                            C_shared_padded[i, j] = T.float32(0)\n                        C_shared_padded[i, j] = (\n                            C_shared_padded[i, j] + A_shared_padded[i, k] * B_shared_padded[k, j]\n                        )\n                for i0, i1 in T.grid(128, 127):\n                    with T.block(\"C\"):\n                        i, j = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(C_shared_padded[i, j])\n                        T.writes(C[i, j])\n                        C[i, j] = C_shared_padded[i, j]\n\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return _ffi_api.SchedulePadEinsum(  # type: ignore # pylint: disable=no-member\n            self, block, padding\n        )\n\n    ######## Schedule: Buffer transformation ########\n\n    @type_checked\n    def rolling_buffer(\n        self,\n        block: Union[BlockRV, str],\n        write_buffer_index: int,\n    ) -> None:\n        \"\"\"Compute the target buffer via rolling buffering, select the outermost rollable\n        axis with a positive bound overlap that appears in the block's ancestor loops\n        as `rolling axis`, fold and circularize the buffer along the rolling dimension,\n        append block predicate to avoid recomputing overlapping elements. It requires:\n\n        1) The block is not an output block and has only RAW dependencies.\n\n        2) The buffer to be an intermediate buffer defined via `alloc_buffer`.\n\n        3) The LCA of the producer and consumer of the buffer is a for loop, typically,\n        the producer and consumer of the buffer are cascaded through compute_at.\n\n        4) The access region of the buffer has at least one dimension that contains\n        a positive bound overlap.\n\n        Parameters\n        ----------\n        block : Union[BlockRV, str]\n            The producer block of the buffer.\n        write_buffer_index : int\n            The index of the buffer in block's write region.\n\n        Examples\n        --------\n\n        Before rolling_buffer, in TensorIR, the IR is:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def before_rolling_buffer(\n                A: T.Buffer[(12, 12), \"int8\"], C: T.Buffer[(8, 8), \"int8\"]\n            ) -> None:\n                # body\n                # with T.block(\"root\")\n                B = T.alloc_buffer([10, 10], dtype=\"int8\")\n                for i0, i1 in T.grid(2, 2):\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 3, 3):\n                        with T.block(\"B\"):\n                            ax0_1 = T.axis.spatial(10, i0 * 4 + ax0)\n                            ax1_1 = T.axis.spatial(10, i1 * 4 + ax1)\n                            rv0, rv1 = T.axis.remap(\"RR\", [ax2, ax3])\n                            B[ax0_1, ax1_1] = T.max(\n                                B[ax0_1, ax1_1], A[ax0_1 + rv0, ax1_1 + rv1]\n                            )\n                    for ax0, ax1, ax2, ax3 in T.grid(4, 4, 3, 3):\n                        with T.block(\"C\"):\n                            ax0_1 = T.axis.spatial(8, i0 * 4 + ax0)\n                            ax1_1 = T.axis.spatial(8, i1 * 4 + ax1)\n                            rv0, rv1 = T.axis.remap(\"RR\", [ax2, ax3])\n                            C[ax0_1, ax1_1] = T.max(\n                                C[ax0_1, ax1_1], B[ax0_1 + rv0, ax1_1 + rv1]\n                            )\n\n        Create the schedule and do rolling_buffer:\n\n        .. code-block:: python\n\n            sch = tir.Schedule(before_rolling_buffer)\n            sch.rolling_buffer(sch.get_block(\"B\"), write_buffer_index=0)\n            print(sch.mod[\"main\"].script())\n\n        After applying rolling_buffer, the IR becomes:\n\n        .. code-block:: python\n\n            @T.prim_func\n            def after_rolling_buffer(\n                A: T.Buffer[(12, 12), \"int8\"],\n                C: T.Buffer[(8, 8), \"int8\"]\n            ) -> None:\n                # body\n                # with T.block(\"root\")\n                B = T.alloc_buffer([6, 10], dtype=\"int8\")\n                for i0, i1 in T.grid(2, 2):\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 3, 3):\n                        with T.block(\"B\"):\n                            T.where((i0 < 1 or 2 <= ax0) and (i1 < 1 or 2 <= ax1))\n                            ax0_1 = T.axis.spatial(10, i0 * 4 + ax0)\n                            ax1_1 = T.axis.spatial(10, i1 * 4 + ax1)\n                            rv0, rv1 = T.axis.remap(\"RR\", [ax2, ax3])\n                            B[ax0_1 % 6, ax1_1] = T.max(\n                                B[ax0_1 % 6, ax1_1], A[ax0_1 + rv0, ax1_1 + rv1]\n                            )\n                    for ax0, ax1, ax2, ax3 in T.grid(4, 4, 3, 3):\n                        with T.block(\"C\"):\n                            ax0_1 = T.axis.spatial(8, i0 * 4 + ax0)\n                            ax1_1 = T.axis.spatial(8, i1 * 4 + ax1)\n                            rv0, rv1 = T.axis.remap(\"RR\", [ax2, ax3])\n                            C[ax0_1, ax1_1] = T.max(\n                                C[ax0_1, ax1_1], B[ax0_1 % 6 + rv0, ax1_1 + rv1]\n                            )\n\n        Note\n        ----\n        The region_cover property of the consumer block of the target buffer will become false.\n        \"\"\"\n        block = self._normalize_block_arg(block)\n        return _ffi_api.ScheduleRollingBuffer(self, block, write_buffer_index)  # type: ignore # pylint: disable=no-member\n\n    ########## Schedule: Misc ##########\n\n    @type_checked\n    def enter_postproc(self) -> None:\n        \"\"\"A no-op that marks the start of postprocessing phase of scheduling\"\"\"\n        _ffi_api.ScheduleEnterPostproc(self)  # type: ignore # pylint: disable=no-member\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/state.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"This file defines ScheduleState, the core data structure of TensorIR scheduling.\"\"\"\nfrom collections import namedtuple\nfrom enum import IntEnum\nfrom typing import Dict, Optional, Union\n\nfrom tvm._ffi import register_object\nfrom tvm.ir import IRModule\nfrom tvm.runtime import Object\nfrom tvm.tir import Block, BlockRealize, For, PrimFunc\n\nfrom . import _ffi_api\nfrom .block_scope import BlockScope, StmtSRef\n\nCachedFlags = namedtuple(\"CachedFlags\", [\"affine_binding\", \"region_cover\", \"stage_pipeline\"])\n\n\nclass ScheduleDebugMask(IntEnum):\n    \"\"\"The bitmask of the `debug_mask` flag in the ScheduleState class.\n\n    If the `debug_mask` flag has a certain bit on, then the correpsonding\n    verification pass will be conducted. For example, if `(debug_mask & VERIFY_SREF_TREE) != 0`,\n    then the correctness of the sref tree will be verified after each schedule instruction.\n\n    Attributes\n    ----------\n    VERIFY_SREF_TREE : int = 1\n        Verify the correctness of the sref tree\n    VERIFY_CACHED_FLAGS : int = 2\n        Verify the correctness of affine_binding, region_cover and stage_pipeline\n    \"\"\"\n\n    VERIFY_SREF_TREE = 1\n    VERIFY_CACHED_FLAGS = 2\n\n\ndef _parse_mod(mod: Union[PrimFunc, IRModule]) -> IRModule:\n    if isinstance(mod, PrimFunc):\n        mod = IRModule({\"main\": mod})\n    if not isinstance(mod, IRModule):\n        raise TypeError(f\"Expected `mod` to be PrimFunc or IRModule, but gets: {mod}\")\n    return mod\n\n\ndef _parse_debug_mask(debug_mask: Union[str, int]) -> int:\n    if isinstance(debug_mask, str):\n        if debug_mask == \"all\":\n            debug_mask = ScheduleDebugMask.VERIFY_SREF_TREE | ScheduleDebugMask.VERIFY_CACHED_FLAGS\n        elif debug_mask == \"none\":\n            debug_mask = 0\n        else:\n            raise ValueError(f\"Unrecognizable `debug_mask`: {debug_mask}\")\n    if not isinstance(debug_mask, bool) and not isinstance(debug_mask, int):\n        raise TypeError(f\"`debug_mask` should be integer or boolean, but gets: {debug_mask}\")\n    return debug_mask\n\n\n@register_object(\"tir.ScheduleState\")\nclass ScheduleState(Object):\n    \"\"\"The state of scheduling, which exposes a `Replace` method as\n    the primary resort for all the scheduling primitives to manipulate the TensorIR.\n\n    The data structure contains the following information\n    1) The AST being scheduled (mod)\n    2) The sref tree of schedulable statements (indicated by the srefs)\n    3) The dependency information of each block scope (block_info)\n    4) A reverse mapping from the AST nodes to that in the sref tree (get_sref)\n    5) A debug flag, if set, extra checking is enabled (debug_mask)\n\n    Parameters\n    ----------\n    mod : IRModule\n        The AST of the module being scheduled\n    debug_mask : int\n        Do extra correctness checking after the object construction\n        and each time after calling the Replace method.\n    \"\"\"\n\n    mod: IRModule\n    debug_mask: int\n\n    def __init__(\n        self,\n        mod: Union[PrimFunc, IRModule],\n        *,\n        debug_mask: Union[str, int] = \"none\",\n    ) -> None:\n        \"\"\"Construct a schedule state from an IRModule or a PrimFunc\n\n        Parameters\n        ----------\n        mod : Union[PrimFunc, IRModule]\n            The IRModule or PrimFunc to be scheduled\n        debug_mask : Union[str, int]\n            Do extra correctness checking after the class creation and each time\n            after calling the Replace method.\n            Possible choices of `debug_mask`:\n            1) \"all\" - Turn on all the checks\n            2) \"none\" - Turn off all the checks\n            3) An integer - Turn on checks according to the bitmasks provided in ScheduleDebugMask\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.ScheduleState,  # type: ignore # pylint: disable=no-member\n            _parse_mod(mod),\n            _parse_debug_mask(debug_mask),\n        )\n\n    def get_sref(self, stmt: Union[Block, For]) -> Optional[StmtSRef]:\n        \"\"\"Return the corresponding sref that points to the stmt\n\n        Parameters\n        ----------\n        stmt : Union[Block, For]\n            The schedulable statement in the TensorIR to be retrieved for its sref\n\n        Returns\n        -------\n        sref : StmtSRef\n            The corresponding sref\n        \"\"\"\n        return _ffi_api.ScheduleStateGetSRef(self, stmt)  # type: ignore # pylint: disable=no-member\n\n    def get_block_scope(self, block_sref: StmtSRef) -> BlockScope:\n        \"\"\"Get the BlockScope correpsonding to the block sref\n\n        Parameters\n        ----------\n        block_sref : StmtSRef\n            The block sref to be retrieved\n\n        Returns\n        -------\n        sref : StmtSRef\n            The corresponding sref\n        \"\"\"\n        return _ffi_api.ScheduleStateGetBlockScope(  # type: ignore # pylint: disable=no-member\n            self, block_sref\n        )\n\n    def _get_cached_flags(self, block_sref: StmtSRef) -> CachedFlags:\n        \"\"\"Get the cached flags of the corresponding block\n\n        Parameters\n        ----------\n        block_sref : StmtSRef\n            The block sref to be retrieved\n\n        Returns\n        -------\n        flags : CachedFlags\n            Three flags: affine_binding, region_cover, stage_pipeline\n\n        Note\n        ----\n        It is an API intended for internal testing use.\n        \"\"\"\n        (\n            affine_binding,\n            region_cover,\n            stage_pipeline,\n        ) = _ffi_api.ScheduleStateGetCachedFlags(  # type: ignore # pylint: disable=no-member\n            self, block_sref\n        )\n        return CachedFlags(\n            affine_binding=bool(affine_binding.value),\n            region_cover=bool(region_cover.value),\n            stage_pipeline=bool(stage_pipeline.value),\n        )\n\n    def replace(\n        self,\n        src_sref: StmtSRef,\n        tgt_stmt: Union[Block, For, BlockRealize],\n        block_sref_reuse: Optional[Dict[Block, Block]] = None,\n    ) -> None:\n        \"\"\"\n        Replace the part of the AST, as being pointed to by `src_sref`,\n        with a specific statement `tgt_stmt`, and maintain the sref tree accordingly.\n        Replace will try to perform copy on write as much as possible when the ScheduleState holds\n        the only copy to the IRModule and IR nodes.\n\n        Only 3 types of replacements are allowed: from `src_sref->stmt` to `tgt_stmt`.\n        1) Block -> Block\n        2) Loop -> Loop\n        3) Loop -> BlockRealize\n\n        Parameters\n        ----------\n        src_sref : StmtSRef\n            The sref to the statement to be replaced in the TensorIR AST\n\n        tgt_stmt : Union[Block, For, BlockRealize]\n            The statement to be replaced to\n\n        block_sref_reuse : Optional[Dict[Block, Block]] = None\n            Maps an old block (to be replaced in the subtree under `src_sref->stmt`)\n            to a new block (replaced to, in the subtree under `tgt_stmt`), and enforces\n            reuse of srefs between them (rather than create new srefs) i.e. after being replaced,\n            the sref that points to the old block will point to the new one\n\n        Note\n        ----\n        The reuse of loop srefs are detected automatically according to the reuse of loop vars.\n        \"\"\"\n        if block_sref_reuse is None:\n            block_sref_reuse = {}\n        _ffi_api.ScheduleStateReplace(  # type: ignore # pylint: disable=no-member\n            self,\n            src_sref,\n            tgt_stmt,\n            block_sref_reuse,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/testing.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Testing utilities for the TensorIR schedule API\"\"\"\nfrom typing import Sequence, Union\n\nimport tvm\nfrom tvm.ir import IRModule, assert_structural_equal\nfrom tvm.tir import PrimFunc\nfrom tvm.tir.schedule import Schedule, Trace\n\n\ndef verify_trace_roundtrip(\n    sch: Schedule,\n    mod: Union[PrimFunc, IRModule],\n    *,\n    debug_mask: Union[str, int] = \"all\",\n    text_format: Union[str, Sequence[str]] = [\"python\", \"json\"],\n) -> Schedule:\n    \"\"\"Serialize a traced schedule to JSON, then replay the JSON trace by applying to\n    a fresh new schedule, verifying the reproducibility of scheduling.\n\n    Parameters\n    ----------\n    sch : tir.Schedule\n        The traced TensorIR schedule to be verified\n    mod : Union[PrimFunc, IRModule]\n        The IRModule or PrimFunc to construct the fresh new schedule\n    debug_mask : Union[str, int]\n        Do extra correctness checking after the class creation and each time\n        after calling the Replace method.\n        Possible choices of `debug_mask`:\n        1) \"all\" - Turn on all the checks\n        2) \"none\" - Turn off all the checks\n        3) An integer - Turn on checks according to the bitmasks provided in ScheduleDebugMask\n    text_format: Union[str, Sequence[str]]\n        The text format or formats whose round-trip behavior should be\n        validated.  If a single string, validate round-trips through\n    \"\"\"\n    if not isinstance(text_format, str):\n        for opt in text_format:\n            new_sch = verify_trace_roundtrip(sch, mod, debug_mask=debug_mask, text_format=opt)\n        return new_sch\n\n    trace = sch.trace\n    assert trace is not None\n\n    # Step 1. Perform a round-trip through the text-format\n    new_sch = Schedule(mod=mod, debug_mask=debug_mask)\n    if text_format == \"json\":\n        json_obj = trace.as_json()\n        Trace.apply_json_to_schedule(json_obj=json_obj, sch=new_sch)\n    elif text_format == \"python\":\n        py_trace = \"\\n\".join(trace.as_python())\n        exec(py_trace, tvm.tir.__dict__, {\"sch\": new_sch})  # pylint: disable=exec-used\n    else:\n        assert text_format in (\"json\", \"python\"), f\"Unknown text format: {text_format}\"\n\n    # Step 2. Verify that the round-trip produced the same scheduling\n    assert_structural_equal(new_sch.mod, sch.mod)\n\n    # Step 3. Check the consistency of the text format between the old and new traces\n    py_repr = \"\\n\".join(trace.as_python())\n    new_py_repr = \"\\n\".join(new_sch.trace.as_python())\n    assert py_repr == new_py_repr\n\n    # Step 4. Return the new schedule in case it could be useful\n    return new_sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/trace.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"An execution trace of a scheduling program\"\"\"\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional\n\nfrom tvm._ffi import register_object as _register_object\nfrom tvm.runtime import Object\n\nfrom ...ir import Array, Map\nfrom ...runtime import String\nfrom ..expr import FloatImm, IntImm\nfrom . import _ffi_api\nfrom .instruction import ATTR_TYPE, INPUT_RV_TYPE, Instruction\n\nif TYPE_CHECKING:\n    from .schedule import Schedule\n\n\nDECISION_TYPE = Any\nJSON_TYPE = Any\n\n\ndef _json_from_tvm(obj):\n    if obj is None:\n        return None\n    if isinstance(obj, Array):\n        return [_json_from_tvm(i) for i in obj]\n    if isinstance(obj, Map):\n        return {_json_from_tvm(k): _json_from_tvm(v) for k, v in obj.items()}\n    if isinstance(obj, String):\n        return str(obj)\n    if isinstance(obj, (IntImm, FloatImm)):\n        return obj.value\n    raise TypeError(\"Not supported type: \" + str(type(obj)))\n\n\n@_register_object(\"tir.Trace\")\nclass Trace(Object):\n    \"\"\"An execution trace of a scheduling program.\n\n    A trace has two parts:\n    1) The instructions invoked so far\n    2) The random decisions made upon those instructions, if any\n\n    A trace can be serialized to:\n    1) Roundtrippable JSON format: can be saved to file and loaded back\n    2) Python syntax: allows users to copy-paste the trace to reproduce the scheduling process\n\n    A trace can be applied to a TensorIR schedule by re-applying all its instructions possibly with\n    their decisions accordingly. Re-sampling is invoked if a sampling instruction doesn't have its\n    corresponding decision; Otherwise the existing decision will be reused accordingly.\n\n    Attributes\n    ----------\n    insts : List[Instruction]\n        The instructions invoked so far in the program execution\n    decisions : Dict[Instruction, DECISION_TYPE]\n        The random decisions made upon those instructions\n    \"\"\"\n\n    insts: List[Instruction]\n    decisions: Dict[Instruction, DECISION_TYPE]\n\n    def __init__(\n        self,\n        insts: List[Instruction],\n        decisions: Dict[Instruction, DECISION_TYPE],\n    ) -> None:\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        insts : List[Instruction]\n            The instructions invoked so far in the program execution\n        decisions : Dict[Instruction, DECISION_TYPE]\n            The random decisions made upon those instructions\n        \"\"\"\n        self.__init_handle_by_constructor__(\n            _ffi_api.Trace,  # type: ignore # pylint: disable=no-member\n            insts,\n            decisions,\n        )\n\n    def get_decision(self, inst: Instruction) -> Optional[DECISION_TYPE]:\n        \"\"\"Retrieve the decision made on a specific instruction\n\n        Parameters\n        ----------\n        insts : Instruction\n            The instruction whose decision is to be retrieved\n\n        Returns\n        -------\n        decision : Optional[DECISION_TYPE]\n            The corresponding decision; None if there is no decision made on the instruction\n        \"\"\"\n        return _ffi_api.TraceGetDecision(self, inst)  # type: ignore # pylint: disable=no-member\n\n    def append(\n        self,\n        inst: Instruction,\n        decision: Optional[DECISION_TYPE] = None,\n    ) -> None:\n        \"\"\"Append a new instruction to the trace\n\n        Parameters\n        ----------\n        insts : Instruction\n            The new instruction to be appended\n        decision : Optional[DECISION_TYPE] = None\n            The random decision made on this instruction\n        \"\"\"\n        _ffi_api.TraceAppend(self, inst, decision)  # type: ignore # pylint: disable=no-member\n\n    def pop(self) -> Optional[Instruction]:\n        \"\"\"Remove the last instruction, along with the decision made on that instruction, if any\n\n        Returns\n        -------\n        popped_inst : Instruction\n            Returns the instruction removed; NullOpt if the trace is empty\n        \"\"\"\n        return _ffi_api.TracePop(self)  # type: ignore # pylint: disable=no-member\n\n    def apply_to_schedule(\n        self,\n        sch: \"Schedule\",\n        remove_postproc: bool,\n        decision_provider: Optional[\n            Callable[\n                [Instruction, List[INPUT_RV_TYPE], List[ATTR_TYPE], DECISION_TYPE], DECISION_TYPE\n            ]\n        ] = None,\n    ) -> None:\n        \"\"\"Apply the trace to a TensorIR schedule\n\n        Parameters\n        ----------\n        sch : Schedule\n            The schedule to be applied onto\n        remove_postproc : bool\n            If postprocessing instructions are removed\n        decision_provider: Optional[Callable] = None\n            A callback that allows users to mutate decisions on the fly when applying instructions.\n            The signature of the callback is:\n            - The 1st argument: The instruction\n            - The 2nd argument: The input random variables\n            - The 3rd argument: The attributes\n            - The 4th argument: The decision\n            - Return: A new decision\n        \"\"\"\n        _ffi_api.TraceApplyToSchedule(  # type: ignore # pylint: disable=no-member\n            self,\n            sch,\n            remove_postproc,\n            decision_provider,\n        )\n\n    def as_json(self, remove_postproc: bool = False) -> JSON_TYPE:\n        \"\"\"Serialize the trace as a JSON-style object\n\n        Parameters\n        ----------\n        remove_postproc : bool = False\n            If postprocessing instructions are removed\n\n        Returns\n        -------\n        json: JSON_TYPE\n            The JSON-style object\n        \"\"\"\n        obj = _ffi_api.TraceAsJSON(self, remove_postproc)  # type: ignore # pylint: disable=no-member\n        return _json_from_tvm(obj)\n\n    def as_python(self, remove_postproc: bool = False) -> List[str]:\n        \"\"\"Serialize the trace as a sequence of python statements\n\n        Parameters\n        ----------\n        remove_postproc : bool = False\n            If postprocessing instructions are removed\n\n        Returns\n        -------\n        py_stmts: List[str]\n            A sequence of python statements\n        \"\"\"\n        return _ffi_api.TraceAsPython(self, remove_postproc)  # type: ignore # pylint: disable=no-member\n\n    def with_decision(\n        self,\n        inst: Instruction,\n        decision: DECISION_TYPE,\n        remove_postproc: bool,\n    ) -> \"Trace\":\n        \"\"\"Create a new trace with an instruction whose decision is changed,\n        assuming this instruction exists in the resulting trace\n\n        Parameters\n        ----------\n        inst : Instruction\n            The instruction whose decision is to be changed\n        decision : DECISION_TYPE\n            The decision to be changed to\n        remove_postproc : bool\n            If postprocessing instructions are removed\n\n        Returns\n        -------\n        trace: Trace\n            The new trace with the decision changed\n        \"\"\"\n        return _ffi_api.TraceWithDecision(  # type: ignore # pylint: disable=no-member\n            self,\n            inst,\n            decision,\n            remove_postproc,\n        )\n\n    def simplified(self, remove_postproc: bool) -> \"Trace\":\n        \"\"\"Simplify the trace with dead-code elimination\n\n        Parameters\n        ----------\n        remove_postproc : bool\n            If postprocessing instructions are removed\n\n        Returns\n        -------\n        trace: Trace\n            A simplified trace\n        \"\"\"\n        return _ffi_api.TraceSimplified(self, remove_postproc)  # type: ignore # pylint: disable=no-member\n\n    @staticmethod\n    def apply_json_to_schedule(json_obj: JSON_TYPE, sch: \"Schedule\") -> None:\n        \"\"\"Apply a JSON-serialized trace to a TensorIR schedule\n\n        Parameters\n        ----------\n        json_obj : JSON_TYPE\n            The JSON-serialized trace\n        sch : Schedule\n            The TensorIR schedule\n        \"\"\"\n        _ffi_api.TraceApplyJSONToSchedule(json_obj, sch)  # type: ignore # pylint: disable=no-member\n\n    def show(self, style: Optional[str] = None) -> None:\n        \"\"\"A sugar for print highlighted trace.\n\n        Parameters\n        ----------\n        style : str, optional\n            Pygments styles extended by \"light\" (default) and \"dark\", by default \"light\"\n        \"\"\"\n        from tvm.script.highlight import (  # pylint: disable=import-outside-toplevel\n            cprint,\n        )\n\n        cprint(str(self), style=style)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/schedule/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Transformation on TIR schedule.\"\"\"\nfrom typing import Optional\n\nfrom tvm.tir.schedule import Schedule, BlockRV, LoopRV\nfrom . import _ffi_api\n\n\ndef tile_with_tensor_intrin(\n    sch: Schedule, block: BlockRV, intrin_name: str, allow_padding: bool = False\n) -> Optional[LoopRV]:\n    \"\"\"Tile a subset of loops in the block according to the given tensor intrinsic.\n\n    Parameters\n    ----------\n    sch : Schedule\n        The schedule to which tiling is applied\n    block : BlockRV\n        The block whose subset of loops will be tiled\n    intrin_name : str\n        The name of a tensor intrinsic, must be registerd via TensorIntrin.register(...) beforehand\n    allow_padding : bool\n        Whether to allow padding when tiling\n\n    Returns\n    -------\n    tiled_loop_rv : Optional[LoopRV]\n        LoopRV corresponding to the outermost loop of a block tiled according to the given intrin\n        NullOpt if no valid loop mapping is found\n    \"\"\"\n    return _ffi_api.TileWithTensorIntrin(sch, block, intrin_name, allow_padding)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/stmt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Statement AST Node in TVM.\n\nEach statement node have subfields that can be visited from python side.\n\n.. code-block:: python\n\n    x = tvm.tir.Var(\"n\", \"int32\")\n    a = tvm.tir.Var(\"array\", \"handle\")\n    st = tvm.tir.stmt.Store(a, x + 1, 1)\n    assert isinstance(st, tvm.tir.stmt.Store)\n    assert(st.buffer_var == a)\n\"\"\"\nfrom enum import IntEnum\nfrom typing import List, Mapping, Optional, Union\n\nimport tvm._ffi\nfrom tvm.ir import PrimExpr, Range, Span\nfrom tvm.runtime import Object, const\n\nfrom . import _ffi_api\nfrom .buffer import Buffer\nfrom .expr import IterVar\n\n\nclass Stmt(Object):\n    \"\"\"Base class of all the statements.\"\"\"\n\n\n@tvm._ffi.register_object(\"tir.LetStmt\")\nclass LetStmt(Stmt):\n    \"\"\"LetStmt node.\n\n    Parameters\n    ----------\n    var : Var\n        The variable in the binding.\n\n    value : PrimExpr\n        The value in to be binded.\n\n    body : Stmt\n        The body statement.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, var, value, body, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.LetStmt, var, value, body, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.AssertStmt\")\nclass AssertStmt(Stmt):\n    \"\"\"AssertStmt node.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The assert condition.\n\n    message : PrimExpr\n        The error message.\n\n    body : tvm.tir.Stmt\n        The body statement.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, condition, message, body, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.AssertStmt, condition, message, body, span  # type: ignore\n        )\n\n\nclass ForKind(IntEnum):\n    \"\"\"The kind of the for loop.\n\n    note\n    ----\n    ForKind can change the control flow semantics\n    of the loop and need to be considered in all TIR passes.\n    \"\"\"\n\n    SERIAL = 0\n    PARALLEL = 1\n    VECTORIZED = 2\n    UNROLLED = 3\n    THREAD_BINDING = 4\n\n\n@tvm._ffi.register_object(\"tir.For\")\nclass For(Stmt):\n    \"\"\"For node.\n\n    Parameters\n    ----------\n    loop_var : Var\n        The loop variable.\n\n    min_val : PrimExpr\n        The beginning value.\n\n    extent : PrimExpr\n        The length of the loop.\n\n    kind : ForKind\n        The type of the for.\n\n    body : Stmt\n        The body statement.\n\n    thread_binding: Optional[tir.IterVar]\n        The thread this loop binds to. Only valid\n        if kind is ThreadBinding\n\n    annotations: tvm.ir.Map\n        Additional annotation hints.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(\n        self,\n        loop_var,\n        min_val,\n        extent,\n        kind,\n        body,\n        thread_binding=None,\n        annotations=None,\n        span=None,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.For,  # type: ignore\n            loop_var,\n            min_val,\n            extent,\n            kind,\n            body,\n            thread_binding,\n            annotations,\n            span,\n        )\n\n\n@tvm._ffi.register_object(\"tir.While\")\nclass While(Stmt):\n    \"\"\"While node.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The termination condition.\n\n    body : Stmt\n        The body statement.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, condition, body, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.While,  # type: ignore\n            condition,\n            body,\n            span,\n        )\n\n\n@tvm._ffi.register_object(\"tir.Store\")\nclass Store(Stmt):\n    \"\"\"Store node.\n\n    Parameters\n    ----------\n    buffer_var : Var\n        The buffer Variable.\n\n    value : PrimExpr\n        The value we want to store.\n\n    index : PrimExpr\n        The index in the store expression.\n\n    predicate : PrimExpr\n        The store predicate.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer_var, value, index, predicate=None, span=None):\n        if predicate is None:\n            predicate = _ffi_api.const_true(value.dtype, span)  # type: ignore\n        self.__init_handle_by_constructor__(\n            _ffi_api.Store, buffer_var, value, index, predicate, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.BufferStore\")\nclass BufferStore(Stmt):\n    \"\"\"Buffer store node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer.\n\n    value : PrimExpr\n        The value we to be stored.\n\n    indices : List[PrimExpr]\n        The indices location to be stored.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer, value, indices, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BufferStore, buffer, value, indices, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.BufferRealize\")\nclass BufferRealize(Stmt):\n    \"\"\"Buffer realize node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer.\n\n    bounds : List[Range]\n        The value we to be stored.\n\n    condition : PrimExpr\n        The realize condition.\n\n    body : Stmt\n        The body of the statement.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer, bounds, condition, body, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BufferRealize, buffer, bounds, condition, body, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.ProducerStore\")\nclass ProducerStore(Stmt):\n    \"\"\"ProducerStore node.\n\n    Parameters\n    ----------\n    producer : DataProducer\n        The data producer.\n\n    value : PrimExpr\n        The value to be stored.\n\n    indices : list of Expr\n        The index arguments of the store.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, producer, value, indices, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ProducerStore, producer, value, indices, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Allocate\")\nclass Allocate(Stmt):\n    \"\"\"Allocate node.\n\n    Parameters\n    ----------\n    buffer_var : Var\n        The buffer variable.\n\n    dtype : str\n        The data type of the buffer.\n\n    extents : list of Expr\n        The extents of the allocate\n\n    condition : PrimExpr\n        The condition.\n\n    body : Stmt\n        The body statement.\n\n    annotations: Optional[Mapping[str, Object]]\n        Additional annotation hints\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer_var, dtype, extents, condition, body, annotations=None, span=None):\n        if annotations is None:\n            annotations = dict()\n        self.__init_handle_by_constructor__(\n            _ffi_api.Allocate,  # type: ignore\n            buffer_var,\n            dtype,\n            extents,\n            condition,\n            body,\n            annotations,\n            span,\n        )\n\n\n@tvm._ffi.register_object(\"tir.AllocateConst\")\nclass AllocateConst(Stmt):\n    \"\"\"Allocate constant node.\n\n    Parameters\n    ----------\n    buffer_var : Var\n        The buffer variable.\n\n    dtype : str\n        The data type of the buffer.\n\n    extents : list of Expr\n        The extents of the allocate\n\n    data_or_idx : Union[NDArray, int]\n        If an NDArray, this is the const data associated with the\n        constant.  If an integer, this is the index into the\n        \"constants\" attribute of the `IRModule` that contains the\n        `AllocateConst`.\n\n    body : Stmt\n        The body statement.\n\n    annotations : Optional[Map]\n        Additional annotations about the allocation.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=None, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.AllocateConst, buffer_var, dtype, extents, data_or_idx, body, annotations, span\n        )\n\n\n@tvm._ffi.register_object(\"tir.DeclBuffer\")\nclass DeclBuffer(Stmt):\n    \"\"\"DeclBuffer node.\n\n    Parameters\n    ----------\n    buffer: Buffer\n        The buffer being declared.\n\n    body: Stmt\n        The body statement to be executed.\n\n    span: Optional[Span]\n        The location of this DeclBuffer in the source code.\n    \"\"\"\n\n    def __init__(self, buffer, body, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)\n\n\n@tvm._ffi.register_object(\"tir.AttrStmt\")\nclass AttrStmt(Stmt):\n    \"\"\"AttrStmt node.\n\n    Parameters\n    ----------\n    node : Node\n        The node to annotate the attribute\n\n    attr_key : str\n        Attribute type key.\n\n    value : PrimExpr\n        The value of the attribute\n\n    body : Stmt\n        The body statement.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, node, attr_key, value, body, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.AttrStmt, node, attr_key, value, body, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.ProducerRealize\")\nclass ProducerRealize(Stmt):\n    \"\"\"ProducerRealize node.\n\n    Parameters\n    ----------\n    producer : DataProducer\n        The data producer.\n\n    bounds : list of range\n        The bound of realize\n\n    condition : PrimExpr\n        The realize condition.\n\n    body : Stmt\n        The realize body\n\n    storage_scope : str\n        The storage scope associated with this realization\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, producer, bounds, condition, body, storage_scope=\"\", span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.ProducerRealize,\n            producer,\n            bounds,\n            condition,\n            body,\n            storage_scope,\n            span,  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.SeqStmt\")\nclass SeqStmt(Stmt):\n    \"\"\"Sequence of statements.\n\n    Parameters\n    ----------\n    seq : List[Stmt]\n        The statements\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, seq, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.SeqStmt, seq, span)  # type: ignore\n\n    def __getitem__(self, i):\n        return self.seq[i]\n\n    def __len__(self):\n        return len(self.seq)\n\n\n@tvm._ffi.register_object(\"tir.IfThenElse\")\nclass IfThenElse(Stmt):\n    \"\"\"IfThenElse node.\n\n    Parameters\n    ----------\n    condition : PrimExpr\n        The expression\n\n    then_case : Stmt\n        The statement to execute if condition is true.\n\n    else_case : Stmt\n        The statement to execute if condition is false.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, condition, then_case, else_case, span=None):\n        self.__init_handle_by_constructor__(\n            _ffi_api.IfThenElse, condition, then_case, else_case, span  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Evaluate\")\nclass Evaluate(Stmt):\n    \"\"\"Evaluate node.\n\n    Parameters\n    ----------\n    value : PrimExpr\n        The expression to be evalued.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, value, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Evaluate, value, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.Prefetch\")\nclass Prefetch(Stmt):\n    \"\"\"Prefetch node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer to be prefetched.\n\n    bounds : list of Range\n        The bounds to be prefetched.\n\n    span : Optional[Span]\n        The location of this itervar in the source code.\n    \"\"\"\n\n    def __init__(self, buffer, bounds, span=None):\n        self.__init_handle_by_constructor__(_ffi_api.Prefetch, buffer, bounds, span)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.BufferRegion\")\nclass BufferRegion(Object):\n    \"\"\"BufferRegion node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The buffer of the buffer region\n\n    region : List[Range]\n        The region array of the buffer region\n    \"\"\"\n\n    buffer: Buffer\n    region: List[Range]\n\n    def __init__(self, buffer: Buffer, region: List[Range]):\n        self.__init_handle_by_constructor__(_ffi_api.BufferRegion, buffer, region)  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.MatchBufferRegion\")\nclass MatchBufferRegion(Object):\n    \"\"\"MatchBufferRegion node.\n\n    Parameters\n    ----------\n    buffer : Buffer\n        The target buffer\n\n    source : BufferRegion\n        The region of source buffer\n    \"\"\"\n\n    buffer: Buffer\n    source: BufferRegion\n\n    def __init__(self, buffer: Buffer, source: BufferRegion):\n        self.__init_handle_by_constructor__(\n            _ffi_api.MatchBufferRegion, buffer, source  # type: ignore\n        )\n\n\n@tvm._ffi.register_object(\"tir.Block\")\nclass Block(Stmt):\n    \"\"\"Block node.\n\n    Parameters\n    ----------\n    iter_vars : List[IterVar]\n        The block Variable.\n\n    reads : List[BufferRegion]\n        The read buffer regions of the block.\n\n    writes: List[BufferRegion]\n        The write buffer regions of the block.\n\n    name_hint: str\n        the name_hint of the block.\n\n    body: Stmt\n        The body of the block.\n\n    init: Optional[Stmt]\n        The init block of the reduction block\n\n    alloc_buffers: Optional[list[Buffer]]\n        The buffer allocations\n\n    match_buffers: Optional[List[MatchBufferRegion]]\n        The subregion buffer match\n\n    annotations: Optional[Mapping[str, Object]]\n        Additional annotation hints.\n\n    span : Optional[Span]\n        The location of this block in the source code.\n    \"\"\"\n\n    iter_vars: List[IterVar]\n    reads: List[BufferRegion]\n    writes: List[BufferRegion]\n    name_hint: str\n    body: Stmt\n    init: Optional[Stmt]\n    alloc_buffers: Optional[List[Buffer]]\n    match_buffers: Optional[List[MatchBufferRegion]]\n    annotations: Optional[Mapping[str, Object]]\n    span: Optional[Span]\n\n    def __init__(\n        self,\n        iter_vars: List[IterVar],\n        reads: List[BufferRegion],\n        writes: List[BufferRegion],\n        name_hint: str,\n        body: Stmt,\n        init: Optional[Stmt] = None,\n        alloc_buffers: Optional[List[Buffer]] = None,\n        match_buffers: Optional[List[MatchBufferRegion]] = None,\n        annotations: Optional[Mapping[str, Object]] = None,\n        span: Optional[Span] = None,\n    ):\n        if alloc_buffers is None:\n            alloc_buffers = []\n        if match_buffers is None:\n            match_buffers = []\n        if annotations is None:\n            annotations = {}\n        self.__init_handle_by_constructor__(\n            _ffi_api.Block,  # type: ignore\n            iter_vars,\n            reads,\n            writes,\n            name_hint,\n            body,\n            init,\n            alloc_buffers,\n            match_buffers,\n            annotations,\n            span,\n        )  # type: ignore\n\n\n@tvm._ffi.register_object(\"tir.BlockRealize\")\nclass BlockRealize(Stmt):\n    \"\"\"BlockRealize node.\n\n    Parameters\n    ----------\n    iter_values : List[PrimExpr]\n        The binding values of the block var.\n\n    predicate : Union[PrimExpr, bool]\n        The predicate of the block.\n\n    block : Block\n        The block to realize\n\n    span : Optional[Span]\n        The location of this block_realize in the source code.\n    \"\"\"\n\n    iter_values: List[PrimExpr]\n    predicate: PrimExpr\n    block: Block\n    span: Optional[Span]\n\n    def __init__(\n        self,\n        iter_values: List[PrimExpr],\n        predicate: Union[PrimExpr, bool],\n        block: Block,\n        span: Optional[Span] = None,\n    ):\n        if isinstance(predicate, bool):\n            predicate = const(predicate, \"bool\")\n        self.__init_handle_by_constructor__(\n            _ffi_api.BlockRealize,  # type: ignore\n            iter_values,\n            predicate,\n            block,\n            span,\n        )  # type: ignore\n\n\ndef stmt_seq(*args):\n    \"\"\"Make sequence of statements\n\n    Parameters\n    ----------\n    args : list of Expr or Var\n        List of statements to be combined as sequence.\n\n    Returns\n    -------\n    stmt : Stmt\n        The combined statement.\n    \"\"\"\n    ret = []\n    for value in args:\n        if not isinstance(value, Stmt):\n            value = Evaluate(value)\n        ret.append(value)\n    if len(ret) == 1:\n        return ret[0]\n    return SeqStmt(ret)\n\n\ndef stmt_list(stmt):\n    \"\"\"Make list of stmt from blocks.\n\n    Parameters\n    ----------\n    stmt : A block statement\n\n    Returns\n    -------\n    stmt_list : list of Stmt\n         The unpacked list of statements\n    \"\"\"\n    if isinstance(stmt, SeqStmt):\n        res = []\n        for x in stmt:\n            res += stmt_list(x)\n        return res\n    return [stmt]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/stmt_functor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Statement functor utilities for IR transformations\"\"\"\nfrom .function import PrimFunc\nfrom . import _ffi_api\n\n\ndef ir_transform(stmt, preorder, postorder, only_enable=None):\n    \"\"\"Recursively visit and transform ir nodes in post DFS order.\n\n    Parameters\n    ----------\n    stmt : tvm.tir.Stmt\n        The input to be transformed.\n\n    preorder: function\n        The function called in before recursive mutation\n        If preorder returns None, then the transform will proceed to recursive call.\n        If preorder returns a not None tvm.tir.Stmt/Expr, the transformer will simply return it and\n        won't do further recursion.\n\n    postorder : function\n        The function called after recursive mutation.\n\n    only_enable : Optional[List[str]]\n        List of types that we only enable.\n\n    Returns\n    -------\n    result : tvm.tir.Stmt\n        The result.\n    \"\"\"\n    return _ffi_api.IRTransform(stmt, preorder, postorder, only_enable)  # type: ignore\n\n\ndef post_order_visit(stmt, fvisit):\n    \"\"\"Recursively visit the ir in post DFS order node, apply fvisit\n       Each node is guaranteed to be visited only once.\n\n    Parameters\n    ----------\n    fvisit: function\n        The visitor function.\n    \"\"\"\n    return _ffi_api.PostOrderVisit(stmt, fvisit)  # type: ignore\n\n\ndef pre_order_visit(stmt, fvisit):\n    \"\"\"Recursive pre-order visit on stmt AST, applying fvisit on each node.\n       If fvisit returns False, it won't visit the children of the node.\n\n    Parameters\n    ----------\n    fvisit: function of the signature Object -> bool\n        The visitor function.\n    \"\"\"\n    return _ffi_api.PreOrderVisit(stmt, fvisit)  # type: ignore\n\n\ndef substitute(node, vmap):\n    \"\"\"Substitute the var specified by vmap.\n\n    Parameters\n    ----------\n    node: ObjectRef\n        The input.\n\n    vmap : Dict[Var, PrimExpr]\n        The variable mapping.\n\n    Returns\n    -------\n    result : tvm.tir.Stmt\n        The result.\n    \"\"\"\n    return _ffi_api.Substitute(node, vmap)  # type: ignore\n\n\ndef renew_defs(func: PrimFunc):\n    \"\"\"Re-generate the definition nodes for a TIR, including VarDef, BufferDef.\n    This pass works as a simple DeepCopy to duplicate a function with different Vars and\n    Buffers but the same behavior\n\n    Parameters\n    ----------\n    func: PrimFunc\n        The input function\n\n    Returns\n    -------\n    result : PrimFunc\n        The new generated func.\n    \"\"\"\n    return _ffi_api.RenewDefs(func)  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import\n\"\"\"Intrinsics for tensorization.\"\"\"\nfrom . import arm_cpu, cuda, rocm, x86, hexagon\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/arm_cpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Intrinsics for ARM tensorization.\"\"\"\nfrom tvm.script import tir as T\nfrom .. import TensorIntrin\nfrom .dot_product_common import DP4A_INTRIN  # pylint: disable=unused-import\n\n\n# TODO(masahi): Parametrize the TVMScript description of dot product by\n# shape and dtype, and share the common description with x86.\n\n\n@T.prim_func\ndef dot_product_4x4_i8i8i32_desc(\n    A: T.Buffer((4,), \"int8\", offset_factor=1),\n    B: T.Buffer((4, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((4,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:4], A[0:4], B[0:4, 0:4])\n        T.writes(C[0:4])\n        for i in T.serial(0, 4):\n            for k in T.serial(0, 4):\n                with T.block(\"update\"):\n                    vi, vk = T.axis.remap(\"SR\", [i, k])\n                    C[vi] = C[vi] + T.cast(A[vk], \"int32\") * T.cast(B[vi, vk], \"int32\")\n\n\n@T.prim_func\ndef dot_product_4x4_i8i8i32_neon(\n    A: T.Buffer((4,), \"int8\", offset_factor=1),\n    B: T.Buffer((4, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((4,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:4], A[0:4], B[0:4, 0:4])\n        T.writes(C[0:4])\n\n        A_int8 = A.vload([0], \"int8x4\")\n        re_int32 = T.reinterpret(A_int8, dtype=\"int32\")\n        vec_ai32 = T.broadcast(re_int32, 2)\n        vec_a = T.reinterpret(vec_ai32, dtype=\"int8x8\")\n\n        vec_b = B.vload([0, 0], dtype=\"int8x16\")\n\n        # TODO(masahi): Remove duplication when inlined function call is supported\n        vec_b_low = T.vectorlow(vec_b, dtype=\"int8x8\")\n\n        multiply_low = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.smull.v8i16\"),\n            T.uint32(2),\n            vec_a,\n            vec_b_low,\n            dtype=\"int16x8\",\n        )\n\n        pairwise_reduction_low = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.saddlp.v4i32.v8i16\"),\n            T.uint32(1),\n            multiply_low,\n            dtype=\"int32x4\",\n        )\n\n        vec_b_high = T.vectorhigh(vec_b, dtype=\"int8x8\")\n\n        multiply_high = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.smull.v8i16\"),\n            T.uint32(2),\n            vec_a,\n            vec_b_high,\n            dtype=\"int16x8\",\n        )\n\n        pairwise_reduction_high = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.saddlp.v4i32.v8i16\"),\n            T.uint32(1),\n            multiply_high,\n            dtype=\"int32x4\",\n        )\n\n        C[T.ramp(T.int32(0), 1, 4)] += T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.addp.v4i32\"),\n            T.uint32(2),\n            pairwise_reduction_low,\n            pairwise_reduction_high,\n            dtype=\"int32x4\",\n        )\n\n\n@T.prim_func\ndef dot_product_4x4_i8i8i32_sdot(\n    A: T.Buffer((4,), \"int8\", offset_factor=1),\n    B: T.Buffer((4, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((4,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:4], A[0:4], B[0:4, 0:4])\n        T.writes(C[0:4])\n\n        A_i8x4 = A.vload([0], \"int8x4\")\n        A_i32 = T.reinterpret(A_i8x4, dtype=\"int32\")\n        vec_ai32 = T.broadcast(A_i32, 4)\n        vec_a = T.reinterpret(vec_ai32, dtype=\"int8x16\")\n\n        vec_b = B.vload([0, 0], dtype=\"int8x16\")\n\n        vec_c = C.vload([0], dtype=\"int32x4\")\n\n        C[T.ramp(T.int32(0), 1, 4)] = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.aarch64.neon.sdot.v4i32.v16i8\"),\n            T.uint32(3),\n            vec_c,\n            vec_a,\n            vec_b,\n            dtype=\"int32x4\",\n        )\n\n\nARM_DOT_4x4_i8_NEON_INTRIN = \"dot_4x4_i8i8s32_neon\"\nARM_DOT_4x4_i8_SDOT_INTRIN = \"dot_4x4_i8i8s32_sdot\"\n\nTensorIntrin.register(\n    ARM_DOT_4x4_i8_NEON_INTRIN, dot_product_4x4_i8i8i32_desc, dot_product_4x4_i8i8i32_neon\n)\n\nTensorIntrin.register(\n    ARM_DOT_4x4_i8_SDOT_INTRIN, dot_product_4x4_i8i8i32_desc, dot_product_4x4_i8i8i32_sdot\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Intrinsics for tensorization on NVIDIA GPU.\"\"\"\nfrom typing import Dict, Tuple\n\nfrom tvm.script import tir as T\nfrom tvm.tir.function import PrimFunc\n\nfrom ..._ffi import register_func\nfrom ...runtime import convert\nfrom .. import Cast, IntImm, TensorIntrin\n\n\ndef shared_16x16_to_ldmatrix_32x8_layout(i, j):\n    thread_id = 4 * (i % 8) + (j % 8) // 2\n    return thread_id, 4 * (j // 8) + (i // 8) * 2 + (j % 2)\n\n\ndef shared_16x32_to_ldmatrix_32x16_layout(i, j):\n    thread_id = 4 * (i % 8) + (j % 16) // 4\n    return thread_id, 8 * (j // 16) + (i // 8) * 4 + j % 4\n\n\ndef shared_32x16_to_ldmatrix_32x16_layout(i, j):\n    thread_id = (i % 16) // 4 + 4 * (j % 8)\n    return thread_id, 8 * (j // 8) + (i // 16) * 4 + i % 4\n\n\n@register_func(\"tir.index_map.shared_16x16_to_ldmatrix_32x8_layout\")\ndef index_map_shared_16x16_to_ldmatrix_32x8_layout(ind):\n    i, j = ind[0], ind[1]\n    thread_id, local_id = shared_16x16_to_ldmatrix_32x8_layout(i, j)\n    return convert([thread_id, local_id])\n\n\nlift = convert\n\nM_DIM = 16\nN_DIM = 16\nWARP_SIZE = 32\nHALF_WARP = WARP_SIZE // 2\nHALF_WARP_expr = lift(HALF_WARP)\n\n\ndef get_ldmatrix_intrin(k_dim, dtype, is_b, transposed, shared_scope=\"shared\"):\n    local_size = (M_DIM * k_dim) // WARP_SIZE\n    shared_offset = None\n    index_map = None\n\n    if transposed:\n        assert is_b, \"Transposed A matrix not supported\"\n\n    ldmatrix_col_major = is_b and not transposed\n\n    if k_dim == 16:\n        assert dtype == \"float16\"\n\n        index_map = shared_16x16_to_ldmatrix_32x8_layout\n\n        if transposed:\n            shared_offset = (\n                lambda tx, stride: stride * 8 * (tx // HALF_WARP_expr)\n                + stride * (tx % 8)\n                + 8 * ((tx % HALF_WARP_expr) // 8)\n            )\n        else:\n            shared_offset = lambda tx, stride: stride * (tx % HALF_WARP_expr) + 8 * (\n                tx // HALF_WARP_expr\n            )\n    else:\n        assert (\n            k_dim == 32 and dtype == \"int8\"\n        ), \"Only k_dim == 16 (float16) or k_dim == 32 (int8) supported for now\"\n\n        if ldmatrix_col_major:\n            index_map = shared_32x16_to_ldmatrix_32x16_layout\n            # A dummy offset, ldmatrix cannot be used for int8 + trans case.\n            # We still use the ldmatrix intrinsic, but lower it to a manual loop in the codegen.\n            # Only the stride information is required.\n            shared_offset = lambda _, stride: stride\n        elif is_b and transposed:\n            index_map = shared_16x32_to_ldmatrix_32x16_layout\n            shared_offset = (\n                lambda tx, stride: stride * 8 * (tx // HALF_WARP_expr)\n                + (tx % 8) * stride\n                + 16 * ((tx % HALF_WARP_expr) // 8)\n            )\n        else:\n            index_map = shared_16x32_to_ldmatrix_32x16_layout\n            shared_offset = lambda tx, stride: stride * (tx % 16) + 16 * (tx // 16)\n\n    assert index_map and shared_offset\n\n    if is_b and not transposed:\n        row_dim = k_dim\n        col_dim = M_DIM\n    else:\n        row_dim = M_DIM\n        col_dim = k_dim\n\n    shmem_shape = (row_dim, col_dim)\n\n    @T.prim_func\n    def ldmatrix_desc(warp_handle: T.handle, shared_handle: T.handle) -> None:\n        shared = T.match_buffer(\n            shared_handle,\n            shmem_shape,\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=shared_scope,\n        )\n        warp = T.match_buffer(\n            warp_handle, (WARP_SIZE, local_size), dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n\n        with T.block(\"root\"):\n            T.reads(shared[0:row_dim, 0:col_dim])\n            T.writes(warp[0:WARP_SIZE, 0:local_size])\n\n            for ax0, ax1 in T.grid(row_dim, col_dim):\n                with T.block(\"shared_warp\"):\n                    v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                    T.reads(shared[v0, v1])\n\n                    thread_id, local_id = T.meta_var(index_map(v0, v1))\n                    T.writes(warp[thread_id, local_id])\n                    warp[thread_id, local_id] = shared[v0, v1]\n\n    @T.prim_func\n    def ldmatrix_impl(warp_handle: T.handle, shared_handle: T.handle) -> None:\n        s0 = T.var(\"int32\")\n        s1 = T.var(\"int32\")\n        shared = T.match_buffer(\n            shared_handle,\n            shmem_shape,\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=shared_scope,\n            strides=[s0, s1],\n        )\n        warp = T.match_buffer(\n            warp_handle, (WARP_SIZE, local_size), dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n\n        with T.block(\"root\"):\n            T.reads(shared[0:row_dim, 0:col_dim])\n            T.writes(warp[0:WARP_SIZE, 0:local_size])\n            tx = T.env_thread(\"threadIdx.x\")\n            T.launch_thread(tx, WARP_SIZE)\n\n            T.evaluate(\n                T.ptx_ldmatrix(\n                    ldmatrix_col_major,\n                    4,  # Always load 4 matrices\n                    \".b16\",\n                    warp.data,\n                    warp.elem_offset + lift(local_size) * tx,\n                    shared.access_ptr(\"r\"),\n                    shared_offset(tx, s0),\n                    dtype=dtype,\n                )\n            )\n\n    return ldmatrix_desc, ldmatrix_impl\n\n\ndef get_mma_intrin(k_dim, out_dtype, b_transposed):\n    local_size = (M_DIM * k_dim) // WARP_SIZE\n    local_size_out = (M_DIM * N_DIM) // 32\n\n    index_map_C = shared_16x16_to_ldmatrix_32x8_layout\n\n    if k_dim == 16:\n        index_map_A = shared_16x16_to_ldmatrix_32x8_layout\n        index_map_B = shared_16x16_to_ldmatrix_32x8_layout\n        mma_prefix = \"m16n8k16\"\n    elif k_dim == 32 and b_transposed:\n        index_map_A = index_map_B = shared_16x32_to_ldmatrix_32x16_layout\n        mma_prefix = \"m16n8k32\"\n    elif k_dim == 32 and not b_transposed:\n        index_map_A = shared_16x32_to_ldmatrix_32x16_layout\n        index_map_B = shared_32x16_to_ldmatrix_32x16_layout\n        mma_prefix = \"m16n8k32\"\n    else:\n        assert False\n\n    out_dtype_abbrv = {\"float16\": \"fp16\", \"float32\": \"fp32\", \"int32\": \"int32\"}[out_dtype]\n\n    if out_dtype in [\"float16\", \"float32\"]:\n        in_dtype = \"float16\"\n        in_dtype_abbrv = \"fp16\"\n    else:\n        in_dtype = \"int8\"\n        in_dtype_abbrv = \"int8\"\n\n    def maybe_cast(v):\n        if out_dtype in [\"float32\", \"int32\"]:\n            return Cast(out_dtype, v)\n        return v\n\n    def maybe_swap(i, j):\n        if b_transposed:\n            return j, i\n        return i, j\n\n    @T.prim_func\n    def mma_sync_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(\n            a, (WARP_SIZE, local_size), in_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n        B = T.match_buffer(\n            b, (WARP_SIZE, local_size), in_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n        C = T.match_buffer(\n            c, (WARP_SIZE, local_size_out), out_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n\n        with T.block(\"root\"):\n            T.reads(\n                C[0:WARP_SIZE, 0:local_size_out],\n                A[0:WARP_SIZE, 0:local_size],\n                B[0:WARP_SIZE, 0:local_size],\n            )\n            T.writes(C[0:WARP_SIZE, 0:local_size_out])\n\n            for i, j, k in T.grid(M_DIM, N_DIM, k_dim):\n                with T.block(\"C\"):\n                    i, j, k = T.axis.remap(\"SSR\", [i, j, k])\n                    b_row_ind, b_col_ind = maybe_swap(k, j)\n\n                    thread_id_C, local_id_C = T.meta_var(index_map_C(i, j))\n                    thread_id_A, local_id_A = T.meta_var(index_map_A(i, k))\n                    thread_id_B, local_id_B = T.meta_var(index_map_B(b_row_ind, b_col_ind))\n\n                    T.reads(\n                        C[thread_id_C, local_id_C],\n                        A[thread_id_A, local_id_A],\n                        B[thread_id_B, local_id_B],\n                    )\n                    T.writes(C[thread_id_C, local_id_C])\n\n                    C[thread_id_C, local_id_C] += maybe_cast(\n                        A[thread_id_A, local_id_A]\n                    ) * maybe_cast(B[thread_id_B, local_id_B])\n\n    @T.prim_func\n    def mma_sync_impl(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(\n            a, (WARP_SIZE, local_size), in_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n        B = T.match_buffer(\n            b, (WARP_SIZE, local_size), in_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n        C = T.match_buffer(\n            c, (WARP_SIZE, local_size_out), out_dtype, align=64, offset_factor=16, scope=\"warp\"\n        )\n\n        with T.block(\"root\"):\n            T.reads(\n                C[0:WARP_SIZE, 0:local_size_out],\n                A[0:WARP_SIZE, 0:local_size],\n                B[0:WARP_SIZE, 0:local_size],\n            )\n            T.writes(C[0:WARP_SIZE, 0:local_size_out])\n            tx = T.env_thread(\"threadIdx.x\")\n            T.launch_thread(tx, WARP_SIZE)\n\n            T.evaluate(\n                T.ptx_mma(\n                    mma_prefix,\n                    \"row\",\n                    \"col\",\n                    in_dtype_abbrv,\n                    in_dtype_abbrv,\n                    out_dtype_abbrv,\n                    A.data,\n                    A.elem_offset + tx * lift(local_size),\n                    B.data,\n                    B.elem_offset + tx * lift(local_size),\n                    C.data,\n                    C.elem_offset + tx * lift(local_size_out),\n                    False,\n                    dtype=out_dtype,\n                )\n            )\n\n            T.evaluate(\n                T.ptx_mma(\n                    mma_prefix,\n                    \"row\",\n                    \"col\",\n                    in_dtype_abbrv,\n                    in_dtype_abbrv,\n                    out_dtype_abbrv,\n                    A.data,\n                    A.elem_offset + tx * lift(local_size),\n                    B.data,\n                    B.elem_offset + tx * lift(local_size) + lift(local_size) // 2,\n                    C.data,\n                    C.elem_offset + tx * lift(local_size_out) + lift(local_size_out) // 2,\n                    False,\n                    dtype=out_dtype,\n                )\n            )\n\n    return mma_sync_desc, mma_sync_impl\n\n\ndef get_mma_fill_intrin(dtype, local_size):\n    zero = IntImm(\"int32\", 0).astype(dtype)\n\n    # Assume M = N = 16\n    index_map = shared_16x16_to_ldmatrix_32x8_layout\n\n    @T.prim_func\n    def mma_fill_desc(a: T.handle) -> None:\n        C_warp = T.match_buffer(a, [WARP_SIZE, local_size], dtype=dtype, scope=\"warp\")\n\n        with T.block(\"root\"):\n            T.reads()\n            T.writes(C_warp[0:WARP_SIZE, 0:local_size])\n            for i0, i1 in T.grid(M_DIM, N_DIM):\n                with T.block(\"C_warp\"):\n                    i, j = T.axis.remap(\"SS\", [i0, i1])\n                    thread_id, local_id = T.meta_var(index_map(i, j))\n                    T.reads()\n                    T.writes(C_warp[thread_id, local_id])\n                    C_warp[thread_id, local_id] = zero\n\n    @T.prim_func\n    def mma_fill_impl(a: T.handle) -> None:\n        C_warp = T.match_buffer(\n            a, [WARP_SIZE, local_size], dtype=dtype, scope=\"warp\", offset_factor=1\n        )\n\n        with T.block(\"root\"):\n            T.reads()\n            T.writes(C_warp[0:WARP_SIZE, 0:local_size])\n            tx = T.env_thread(\"threadIdx.x\")\n            T.launch_thread(tx, WARP_SIZE)\n\n            T.evaluate(T.mma_fill(local_size, C_warp.data, C_warp.elem_offset, dtype=dtype))\n\n    return mma_fill_desc, mma_fill_impl\n\n\ndef get_mma_store_intrin(dtype, local_size, scope=\"global\"):\n    # Assume M = N = 16\n    index_map = shared_16x16_to_ldmatrix_32x8_layout\n\n    @T.prim_func\n    def mma_store_desc(a: T.handle, c: T.handle) -> None:\n        C_warp = T.match_buffer(a, [WARP_SIZE, local_size], dtype=dtype, scope=\"warp\")\n        C = T.match_buffer(c, [M_DIM, N_DIM], dtype=dtype, scope=scope)\n\n        with T.block(\"root\"):\n            T.reads(C_warp[0:WARP_SIZE, 0:local_size])\n            T.writes(C[0:M_DIM, 0:N_DIM])\n            for i0, i1 in T.grid(M_DIM, N_DIM):\n                with T.block(\"C_warp\"):\n                    v0, v1 = T.axis.remap(\"SS\", [i0, i1])\n                    thread_id, local_id = T.meta_var(index_map(v0, v1))\n                    T.reads(C_warp[thread_id, local_id])\n                    T.writes(C[v0, v1])\n                    C[v0, v1] = C_warp[thread_id, local_id]\n\n    @T.prim_func\n    def mma_store_impl(a: T.handle, c: T.handle) -> None:\n        s0 = T.var(\"int32\")\n        s1 = T.var(\"int32\")\n\n        C_warp = T.match_buffer(\n            a, [WARP_SIZE, local_size], dtype=dtype, scope=\"warp\", offset_factor=1\n        )\n        C = T.match_buffer(\n            c, [M_DIM, N_DIM], dtype=dtype, scope=\"global\", offset_factor=1, strides=[s0, s1]\n        )\n\n        with T.block(\"root\"):\n            T.reads(C_warp[0:WARP_SIZE, 0:local_size])\n            T.writes(C[0:M_DIM, 0:N_DIM])\n            tx = T.env_thread(\"threadIdx.x\")\n            T.launch_thread(tx, WARP_SIZE)\n\n            T.evaluate(\n                T.mma_store(\n                    M_DIM,\n                    N_DIM,\n                    C.access_ptr(\"w\"),\n                    C_warp.data,\n                    C_warp.elem_offset,\n                    s0,\n                    dtype=dtype,\n                )\n            )\n\n    return mma_store_desc, mma_store_impl\n\n\nLDMATRIX_16x16_A_INTRIN = \"mma.ldmatrix_16x16_a\"\nTensorIntrin.register(LDMATRIX_16x16_A_INTRIN, *get_ldmatrix_intrin(16, \"float16\", False, False))\n\nLDMATRIX_16x16_B_INTRIN = \"mma.ldmatrix_16x16_b\"\nTensorIntrin.register(LDMATRIX_16x16_B_INTRIN, *get_ldmatrix_intrin(16, \"float16\", True, False))\n\nLDMATRIX_16x16_A_DYN_INTRIN = \"mma.ldmatrix_16x16_a_dyn\"\nTensorIntrin.register(\n    LDMATRIX_16x16_A_DYN_INTRIN, *get_ldmatrix_intrin(16, \"float16\", False, False, \"shared.dyn\")\n)\n\nLDMATRIX_16x16_B_DYN_INTRIN = \"mma.ldmatrix_16x16_b_dyn\"\nTensorIntrin.register(\n    LDMATRIX_16x16_B_DYN_INTRIN, *get_ldmatrix_intrin(16, \"float16\", True, False, \"shared.dyn\")\n)\n\nLDMATRIX_16x16_B_TRANS_INTRIN = \"mma.ldmatrix_16x16_b_trans\"\nTensorIntrin.register(\n    LDMATRIX_16x16_B_TRANS_INTRIN, *get_ldmatrix_intrin(16, \"float16\", True, True)\n)\n\nLDMATRIX_16x32_A_INTRIN = \"mma.ldmatrix_16x32_a\"\nTensorIntrin.register(LDMATRIX_16x32_A_INTRIN, *get_ldmatrix_intrin(32, \"int8\", False, False))\n\nLDMATRIX_32x16_B_INTRIN = \"mma.ldmatrix_32x16_b\"\nTensorIntrin.register(LDMATRIX_32x16_B_INTRIN, *get_ldmatrix_intrin(32, \"int8\", True, False))\n\nLDMATRIX_16x32_B_TRANS_INTRIN = \"mma.ldmatrix_16x32_b_trans\"\nTensorIntrin.register(LDMATRIX_16x32_B_TRANS_INTRIN, *get_ldmatrix_intrin(32, \"int8\", True, True))\n\nMMA_f16f16f32_INTRIN = \"mma_f16f16f32\"\nTensorIntrin.register(MMA_f16f16f32_INTRIN, *get_mma_intrin(16, \"float32\", False))\n\nMMA_f16f16f32_TRANS_INTRIN = \"mma_f16f16f32_trans\"\nTensorIntrin.register(MMA_f16f16f32_TRANS_INTRIN, *get_mma_intrin(16, \"float32\", True))\n\nMMA_f16f16f16_INTRIN = \"mma_f16f16f16\"\nTensorIntrin.register(MMA_f16f16f16_INTRIN, *get_mma_intrin(16, \"float16\", False))\n\nMMA_f16f16f16_TRANS_INTRIN = \"mma_f16f16f16_trans\"\nTensorIntrin.register(MMA_f16f16f16_TRANS_INTRIN, *get_mma_intrin(16, \"float16\", True))\n\nMMA_i8i8i32_INTRIN = \"mma_i8i8i32\"\nTensorIntrin.register(MMA_i8i8i32_INTRIN, *get_mma_intrin(32, \"int32\", False))\n\nMMA_i8i8i32_TRANS_INTRIN = \"mma_i8i8i32_trans\"\nTensorIntrin.register(MMA_i8i8i32_TRANS_INTRIN, *get_mma_intrin(32, \"int32\", True))\n\nMMA_fill_16x16_f32_INTRIN = \"mma_fill_16x16_f32\"\nTensorIntrin.register(MMA_fill_16x16_f32_INTRIN, *get_mma_fill_intrin(\"float32\", 8))\n\nMMA_fill_16x16_f16_INTRIN = \"mma_fill_16x16_f16\"\nTensorIntrin.register(MMA_fill_16x16_f16_INTRIN, *get_mma_fill_intrin(\"float16\", 8))\n\nMMA_fill_16x16_i32_INTRIN = \"mma_fill_16x16_i32\"\nTensorIntrin.register(MMA_fill_16x16_i32_INTRIN, *get_mma_fill_intrin(\"int32\", 8))\n\nMMA_store_16x16_f32_global_INTRIN = \"mma_store_16x16_f32_global_\"\nTensorIntrin.register(\n    MMA_store_16x16_f32_global_INTRIN, *get_mma_store_intrin(\"float32\", 8, \"global\")\n)\n\nMMA_store_16x16_f16_global_INTRIN = \"mma_store_16x16_f16_global_\"\nTensorIntrin.register(\n    MMA_store_16x16_f16_global_INTRIN, *get_mma_store_intrin(\"float16\", 8, \"global\")\n)\n\nMMA_store_16x16_i32_global_INTRIN = \"mma_store_16x16_i32_global_\"\nTensorIntrin.register(\n    MMA_store_16x16_i32_global_INTRIN, *get_mma_store_intrin(\"int32\", 8, \"global\")\n)\n\n\n######## WMMA intrinsics ########\n\n\ndef get_wmma_fragment_index(buffer, stride, m_dim, n_dim):\n    \"\"\"Compute wmma fragment index using elem_offset of the buffer\"\"\"\n    frag_index_m = buffer.elem_offset // stride // m_dim\n    frag_index_n = buffer.elem_offset % stride // n_dim\n\n    num_fragments_per_row = stride // n_dim\n    return frag_index_m * num_fragments_per_row + frag_index_n\n\n\ndef get_wmma_load_intrin(\n    m_dim: int,\n    n_dim: int,\n    k_dim: int,\n    dtype: str,\n    shared_scope: str,\n    is_b: bool,\n    is_col_major: bool,\n) -> Tuple[PrimFunc, PrimFunc]:\n    \"\"\"Generator of wmma_load intrins\"\"\"\n    wmma_fragment_scope = \"wmma.matrix_{}\".format(\"b\" if is_b else \"a\")\n    layout = \"col_major\" if is_col_major else \"row_major\"\n\n    @T.prim_func\n    def wmma_load_desc(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=shared_scope)\n        C = T.match_buffer(\n            c, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=wmma_fragment_scope\n        )\n        with T.block(\"root\"):\n            T.reads(A[0:m_dim, 0:n_dim])\n            T.writes(C[0:m_dim, 0:n_dim])\n            for i, j in T.grid(m_dim, n_dim):\n                with T.block(\"load\"):\n                    vii, vjj = T.axis.remap(\"SS\", [i, j])\n                    C[vii, vjj] = A[vii, vjj]\n\n    @T.prim_func\n    def wmma_load_impl(a: T.handle, c: T.handle) -> None:\n        s1 = T.var(\"int32\")\n        s0 = T.var(\"int32\")\n        d1 = T.var(\"int32\")\n        d0 = T.var(\"int32\")\n        A = T.match_buffer(\n            a,\n            (m_dim, n_dim),\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=shared_scope,\n            strides=[s1, s0],\n        )\n        C = T.match_buffer(\n            c,\n            (m_dim, n_dim),\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=wmma_fragment_scope,\n            strides=[d1, d0],\n        )\n        with T.block(\"root\"):\n            T.reads(A[0:m_dim, 0:n_dim])\n            T.writes(C[0:m_dim, 0:n_dim])\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    C.data,\n                    m_dim,\n                    n_dim,\n                    k_dim,\n                    get_wmma_fragment_index(C, d1, m_dim, n_dim),\n                    A.access_ptr(\"r\"),\n                    s1,\n                    layout,\n                    dtype=\"handle\",\n                )\n            )\n\n    return wmma_load_desc, wmma_load_impl\n\n\ndef get_wmma_fill_intrin(\n    m_dim: int, n_dim: int, k_dim: int, dtype: str\n) -> Tuple[PrimFunc, PrimFunc]:\n    \"\"\"Generator of wmma_fill intrins\"\"\"\n    zero = IntImm(\"int32\", 0).astype(dtype)\n\n    @T.prim_func\n    def wmma_fill_desc(c: T.handle) -> None:\n        C = T.match_buffer(\n            c, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=\"wmma.accumulator\"\n        )\n        with T.block(\"root\"):\n            T.reads()\n            T.writes(C[0:m_dim, 0:n_dim])\n            for i, j in T.grid(m_dim, n_dim):\n                with T.block(\"init\"):\n                    vii, vjj = T.axis.remap(\"SS\", [i, j])\n                    C[vii, vjj] = zero\n\n    @T.prim_func\n    def wmma_fill_impl(c: T.handle) -> None:\n        d1 = T.var(\"int32\")\n        d0 = T.var(\"int32\")\n        C = T.match_buffer(\n            c,\n            (m_dim, n_dim),\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.accumulator\",\n            strides=[d1, d0],\n        )\n        with T.block(\"root\"):\n            T.reads()\n            T.writes(C[0:m_dim, 0:n_dim])\n            T.evaluate(\n                T.tvm_fill_fragment(\n                    C.data,\n                    m_dim,\n                    n_dim,\n                    k_dim,\n                    get_wmma_fragment_index(C, d1, m_dim, n_dim),\n                    T.float32(0),\n                    dtype=\"handle\",\n                )\n            )\n\n    return wmma_fill_desc, wmma_fill_impl\n\n\ndef get_wmma_store_intrin(\n    m_dim: int, n_dim: int, k_dim: int, dtype: str, scope: str\n) -> Tuple[PrimFunc, PrimFunc]:\n    \"\"\"Generator of wmma_store intrins\"\"\"\n\n    @T.prim_func\n    def wmma_store_desc(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(\n            a, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=\"wmma.accumulator\"\n        )\n        C = T.match_buffer(c, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=scope)\n        with T.block(\"root\"):\n            T.reads(A[0:m_dim, 0:n_dim])\n            T.writes(C[0:m_dim, 0:n_dim])\n            for i, j in T.grid(m_dim, n_dim):\n                with T.block(\"store\"):\n                    vii, vjj = T.axis.remap(\"SS\", [i, j])\n                    C[vii, vjj] = A[vii, vjj]\n\n    @T.prim_func\n    def wmma_store_impl(a: T.handle, c: T.handle) -> None:\n        s1 = T.var(\"int32\")\n        s0 = T.var(\"int32\")\n        d1 = T.var(\"int32\")\n        d0 = T.var(\"int32\")\n        A = T.match_buffer(\n            a,\n            (m_dim, n_dim),\n            dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.accumulator\",\n            strides=[d1, d0],\n        )\n        C = T.match_buffer(\n            c, (m_dim, n_dim), dtype, align=64, offset_factor=16, scope=scope, strides=[s1, s0]\n        )\n        with T.block(\"root\"):\n            T.reads(A[0:m_dim, 0:n_dim])\n            T.writes(C[0:m_dim, 0:n_dim])\n            T.evaluate(\n                T.tvm_store_matrix_sync(\n                    A.data,\n                    m_dim,\n                    n_dim,\n                    k_dim,\n                    get_wmma_fragment_index(A, d1, m_dim, n_dim),\n                    C.access_ptr(\"w\"),\n                    s1,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n\n    return wmma_store_desc, wmma_store_impl\n\n\ndef get_wmma_sync_intrin(\n    m_dim: int, n_dim: int, k_dim: int, in_dtype: str, out_dtype: str, b_transposed: bool\n) -> Tuple[PrimFunc, PrimFunc]:\n    \"\"\"Generator of wmma_sync intrins\"\"\"\n\n    def maybe_cast(v):\n        if in_dtype != out_dtype:\n            return Cast(out_dtype, v)\n        return v\n\n    def maybe_swap(i, j):\n        if b_transposed:\n            return j, i\n        return i, j\n\n    b_shape_0, b_shape_1 = maybe_swap(k_dim, n_dim)\n\n    @T.prim_func\n    def wmma_sync_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(\n            a, (m_dim, k_dim), in_dtype, align=64, offset_factor=16, scope=\"wmma.matrix_a\"\n        )\n        B = T.match_buffer(\n            b,\n            maybe_swap(k_dim, n_dim),\n            in_dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.matrix_b\",\n        )\n        C = T.match_buffer(\n            c, (m_dim, n_dim), out_dtype, align=64, offset_factor=16, scope=\"wmma.accumulator\"\n        )\n\n        with T.block(\"root\"):\n            T.reads(C[0:m_dim, 0:n_dim], A[0:m_dim, 0:k_dim], B[0:b_shape_0, 0:b_shape_1])\n            T.writes(C[0:m_dim, 0:n_dim])\n            for i, j, k in T.grid(m_dim, n_dim, k_dim):\n                with T.block(\"\"):\n                    vii, vjj, vkk = T.axis.remap(\"SSR\", [i, j, k])\n                    B_index_0, B_index_1 = maybe_swap(vkk, vjj)\n                    C[vii, vjj] = C[vii, vjj] + maybe_cast(A[vii, vkk]) * maybe_cast(\n                        B[B_index_0, B_index_1]\n                    )\n\n    @T.prim_func\n    def wmma_sync_impl(a: T.handle, b: T.handle, c: T.handle) -> None:\n        a1 = T.var(\"int32\")\n        a0 = T.var(\"int32\")\n        b1 = T.var(\"int32\")\n        b0 = T.var(\"int32\")\n        c1 = T.var(\"int32\")\n        c0 = T.var(\"int32\")\n\n        A = T.match_buffer(\n            a,\n            (m_dim, k_dim),\n            in_dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.matrix_a\",\n            strides=[a1, a0],\n        )\n        B = T.match_buffer(\n            b,\n            maybe_swap(k_dim, n_dim),\n            in_dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.matrix_b\",\n            strides=[b1, b0],\n        )\n        C = T.match_buffer(\n            c,\n            (m_dim, n_dim),\n            out_dtype,\n            align=64,\n            offset_factor=16,\n            scope=\"wmma.accumulator\",\n            strides=[c1, c0],\n        )\n\n        with T.block(\"root\"):\n            T.reads(C[0:m_dim, 0:n_dim], A[0:m_dim, 0:k_dim], B[0:b_shape_0, 0:b_shape_1])\n            T.writes(C[0:m_dim, 0:n_dim])\n            T.evaluate(\n                T.tvm_mma_sync(\n                    C.data,\n                    get_wmma_fragment_index(C, c1, m_dim, n_dim),\n                    A.data,\n                    get_wmma_fragment_index(A, a1, m_dim, k_dim),\n                    B.data,\n                    get_wmma_fragment_index(B, b1, b_shape_0, b_shape_1),\n                    C.data,\n                    get_wmma_fragment_index(C, c1, m_dim, n_dim),\n                    dtype=\"handle\",\n                )\n            )\n\n    return wmma_sync_desc, wmma_sync_impl\n\n\nWMMA_SYNC_16x16x16_f16f16f32_INTRIN = \"wmma_sync_16x16x16_f16f16f32\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_f16f16f32_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"float16\", \"float32\", False),\n)\n\nWMMA_SYNC_16x16x16_f16f16f32_TRANS_INTRIN = \"wmma_sync_16x16x16_f16f16f32_trans\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_f16f16f32_TRANS_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"float16\", \"float32\", True),\n)\n\nWMMA_SYNC_16x16x16_f16f16f16_INTRIN = \"wmma_sync_16x16x16_f16f16f16\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_f16f16f16_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"float16\", \"float16\", False),\n)\n\nWMMA_SYNC_16x16x16_f16f16f16_TRANS_INTRIN = \"wmma_sync_16x16x16_f16f16f16_trans\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_f16f16f16_TRANS_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"float16\", \"float16\", True),\n)\n\nWMMA_SYNC_16x16x16_s8s8s32_INTRIN = \"wmma_sync_16x16x16_s8s8s32\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_s8s8s32_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"int8\", \"int32\", False),\n)\n\nWMMA_SYNC_16x16x16_s8s8s32_TRANS_INTRIN = \"wmma_sync_16x16x16_s8s8s32_trans\"\nTensorIntrin.register(\n    WMMA_SYNC_16x16x16_s8s8s32_TRANS_INTRIN,\n    *get_wmma_sync_intrin(16, 16, 16, \"int8\", \"int32\", True),\n)\n\nWMMA_LOAD_16x16x16_F16_A_INTRIN = \"wmma_load_16x16x16_f16_a\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_F16_A_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"float16\", \"shared\", False, False),\n)\n\nWMMA_LOAD_16x16x16_F16_B_INTRIN = \"wmma_load_16x16x16_f16_b\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_F16_B_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"float16\", \"shared\", True, False),\n)\n\nWMMA_LOAD_16x16x16_F16_A_TRANS_INTRIN = \"wmma_load_16x16x16_f16_a_trans\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_F16_A_TRANS_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"float16\", \"shared\", False, True),\n)\n\nWMMA_LOAD_16x16x16_F16_B_TRANS_INTRIN = \"wmma_load_16x16x16_f16_b_trans\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_F16_B_TRANS_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"float16\", \"shared\", True, True),\n)\n\nWMMA_LOAD_16x16x16_S8_A_INTRIN = \"wmma_load_16x16x16_s8_a\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_S8_A_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"int8\", \"shared\", False, False),\n)\n\nWMMA_LOAD_16x16x16_S8_B_INTRIN = \"wmma_load_16x16x16_s8_b\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_S8_B_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"int8\", \"shared\", True, False),\n)\n\nWMMA_LOAD_16x16x16_S8_A_TRANS_INTRIN = \"wmma_load_16x16x16_s8_a_trans\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_S8_A_TRANS_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"int8\", \"shared\", False, True),\n)\n\nWMMA_LOAD_16x16x16_S8_B_TRANS_INTRIN = \"wmma_load_16x16x16_s8_b_trans\"\nTensorIntrin.register(\n    WMMA_LOAD_16x16x16_S8_B_TRANS_INTRIN,\n    *get_wmma_load_intrin(16, 16, 16, \"int8\", \"shared\", True, True),\n)\n\n\nWMMA_FILL_16x16x16_F32_INTRIN = \"wmma_fill_16x16x16_f32\"\nTensorIntrin.register(WMMA_FILL_16x16x16_F32_INTRIN, *get_wmma_fill_intrin(16, 16, 16, \"float32\"))\n\nWMMA_FILL_16x16x16_F16_INTRIN = \"wmma_fill_16x16x16_f16\"\nTensorIntrin.register(WMMA_FILL_16x16x16_F16_INTRIN, *get_wmma_fill_intrin(16, 16, 16, \"float16\"))\n\nWMMA_FILL_16x16x16_S32_INTRIN = \"wmma_fill_16x16x16_s32\"\nTensorIntrin.register(WMMA_FILL_16x16x16_S32_INTRIN, *get_wmma_fill_intrin(16, 16, 16, \"int32\"))\n\nWMMA_STORE_16x16x16_F32_SHARED_INTRIN = \"wmma_store_16x16x16_f32_shared\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_F32_SHARED_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"float32\", \"shared\")\n)\n\nWMMA_STORE_16x16x16_F16_SHARED_INTRIN = \"wmma_store_16x16x16_f16_shared\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_F16_SHARED_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"float16\", \"shared\")\n)\n\nWMMA_STORE_16x16x16_S32_SHARED_INTRIN = \"wmma_store_16x16x16_s32_shared\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_S32_SHARED_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"int32\", \"shared\")\n)\n\nWMMA_STORE_16x16x16_F32_GLOBAL_INTRIN = \"wmma_store_16x16x16_f32_global\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_F32_GLOBAL_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"float32\", \"global\")\n)\n\nWMMA_STORE_16x16x16_F16_GLOBAL_INTRIN = \"wmma_store_16x16x16_f16_global\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_F16_GLOBAL_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"float16\", \"global\")\n)\n\nWMMA_STORE_16x16x16_S32_GLOBAL_INTRIN = \"wmma_store_16x16x16_s32_global\"\nTensorIntrin.register(\n    WMMA_STORE_16x16x16_S32_GLOBAL_INTRIN, *get_wmma_store_intrin(16, 16, 16, \"int32\", \"global\")\n)\n\n\ndef get_wmma_intrin_group(\n    store_scope: str, in_dtype: str, out_dtype: str, trans_b: bool\n) -> Dict[str, str]:\n    \"\"\"Get a group of intrinsics for wmma tensor core with the given configurations\n\n    Parameters\n    ----------\n    store_scope : str\n        Must be one of [\"global\", \"shared\"]. The memory scope of the result buffer.\n\n    in_dtype : str\n        The input data type.\n\n    out_dtype : str\n        The output data dtype.\n\n    trans_b : bool\n        Whether the input matrix B is transposed.\n\n    Returns\n    -------\n    ret : Dict[str, str]\n        A group of tensor intrinsics.\n    \"\"\"\n    assert store_scope in [\"global\", \"shared\"]\n    assert in_dtype in [\"float16\", \"int8\"]\n    assert out_dtype in [\"float16\", \"float32\", \"int32\"]\n\n    load_a_intrins = {\n        \"float16\": WMMA_LOAD_16x16x16_F16_A_INTRIN,\n        \"int8\": WMMA_LOAD_16x16x16_S8_A_INTRIN,\n    }\n    load_b_intrins = {\n        \"float16\": WMMA_LOAD_16x16x16_F16_B_TRANS_INTRIN\n        if trans_b\n        else WMMA_LOAD_16x16x16_F16_B_INTRIN,\n        \"int8\": WMMA_LOAD_16x16x16_S8_B_TRANS_INTRIN if trans_b else WMMA_LOAD_16x16x16_S8_B_INTRIN,\n    }\n    compute_intrins = {\n        \"float16\": WMMA_SYNC_16x16x16_f16f16f16_TRANS_INTRIN\n        if trans_b\n        else WMMA_SYNC_16x16x16_f16f16f16_INTRIN,\n        \"float32\": WMMA_SYNC_16x16x16_f16f16f32_TRANS_INTRIN\n        if trans_b\n        else WMMA_SYNC_16x16x16_f16f16f32_INTRIN,\n        \"int32\": WMMA_SYNC_16x16x16_s8s8s32_TRANS_INTRIN\n        if trans_b\n        else WMMA_SYNC_16x16x16_s8s8s32_INTRIN,\n    }\n    init_intrins = {\n        \"float16\": WMMA_FILL_16x16x16_F16_INTRIN,\n        \"float32\": WMMA_FILL_16x16x16_F32_INTRIN,\n        \"int32\": WMMA_FILL_16x16x16_S32_INTRIN,\n    }\n    store_intrins = {\n        \"float16\": WMMA_STORE_16x16x16_F16_SHARED_INTRIN\n        if store_scope == \"shared\"\n        else WMMA_STORE_16x16x16_F16_GLOBAL_INTRIN,\n        \"float32\": WMMA_STORE_16x16x16_F32_SHARED_INTRIN\n        if store_scope == \"shared\"\n        else WMMA_STORE_16x16x16_F32_GLOBAL_INTRIN,\n        \"int32\": WMMA_STORE_16x16x16_S32_SHARED_INTRIN\n        if store_scope == \"shared\"\n        else WMMA_STORE_16x16x16_S32_GLOBAL_INTRIN,\n    }\n    return {\n        \"init\": init_intrins[out_dtype],\n        \"load_a\": load_a_intrins[in_dtype],\n        \"load_b\": load_b_intrins[in_dtype],\n        \"compute\": compute_intrins[out_dtype],\n        \"store\": store_intrins[out_dtype],\n    }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/dot_product_common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Dot product related intrinsics.\"\"\"\nfrom tvm.script import tir as T\nfrom .. import TensorIntrin\n\n\n@T.prim_func\ndef dp4a_desc(\n    A: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    B: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    C: T.Buffer((1,), \"int32\", offset_factor=1, align=4, scope=\"local\"),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0], A[0:4], B[0:4])\n        T.writes(C[0])\n        for i in range(0, 4):\n            with T.block(\"update\"):\n                vi = T.axis.remap(\"R\", [i])\n                C[0] = C[0] + T.cast(A[vi], \"int32\") * T.cast(B[vi], \"int32\")\n\n\n@T.prim_func\ndef dp4a_impl(\n    A: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    B: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    C: T.Buffer((1,), \"int32\", offset_factor=1, align=4, scope=\"local\"),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0], A[0:4], B[0:4])\n        T.writes(C[0])\n\n        C[0] += T.call_pure_extern(\n            \"__dp4a\", A.vload([0], \"int8x4\"), B.vload([0], \"int8x4\"), T.int32(0), dtype=\"int32\"\n        )\n\n\nDP4A_INTRIN = \"dp4a\"\n\nTensorIntrin.register(DP4A_INTRIN, dp4a_desc, dp4a_impl)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/hexagon.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Intrinsics for Hexagon tensorization.\"\"\"\nfrom tvm.script import tir as T\nfrom .. import TensorIntrin\n\n\n@T.prim_func\ndef dot_product_32x4_u8u8i32_desc(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((32, 4), \"uint8\", offset_factor=1),\n    C: T.Buffer((32,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:32], A[0:4], B[0:32, 0:4])\n        T.writes(C[0:32])\n        for i in T.serial(0, 32):\n            for k in T.serial(0, 4):\n                with T.block(\"update\"):\n                    with T.init():\n                        C[i] = T.int32(0)\n                    vi, vk = T.axis.remap(\"SR\", [i, k])\n                    C[vi] = C[vi] + T.cast(A[vk], \"int32\") * T.cast(B[vi, vk], \"int32\")\n\n\n@T.prim_func\ndef dot_product_32x4_u8u8i32_vrmpy(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((32, 4), \"uint8\", offset_factor=1),\n    C: T.Buffer((32,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:32], A[0:4], B[0:32, 0:4])\n        T.writes(C[0:32])\n\n        A_u8x4 = A.vload([0], \"uint8x4\")\n        A_i32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n\n        B_i8x128 = B.vload([0, 0], dtype=\"uint8x128\")\n        B_i32x32 = T.reinterpret(B_i8x128, dtype=\"int32x32\")\n\n        C[T.ramp(T.int32(0), 1, 32)] = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyub.acc.128B\"),\n            T.uint32(3),\n            C[T.ramp(T.int32(0), 1, 32)],\n            B_i32x32,\n            A_i32,\n            dtype=\"int32x32\",\n        )\n\n\n@T.prim_func\ndef dot_product_32x4_u8i8i32_desc(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((32, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((32,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:32], A[0:4], B[0:32, 0:4])\n        T.writes(C[0:32])\n        for i in T.serial(0, 32):\n            for k in T.serial(0, 4):\n                with T.block(\"update\"):\n                    with T.init():\n                        C[i] = T.int32(0)\n                    vi, vk = T.axis.remap(\"SR\", [i, k])\n                    C[vi] = C[vi] + T.cast(A[vk], \"int32\") * T.cast(B[vi, vk], \"int32\")\n\n\n@T.prim_func\ndef dot_product_32x4_u8i8i32_vrmpy(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((32, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((32,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:32], A[0:4], B[0:32, 0:4])\n        T.writes(C[0:32])\n\n        A_u8x4 = A.vload([0], \"uint8x4\")\n        A_i32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n\n        B_i8x128 = B.vload([0, 0], dtype=\"int8x128\")\n        B_i32x32 = T.reinterpret(B_i8x128, dtype=\"int32x32\")\n\n        C[T.ramp(T.int32(0), 1, 32)] = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpybusv.acc.128B\"),\n            T.uint32(3),\n            C[T.ramp(T.int32(0), 1, 32)],\n            T.broadcast(A_i32, 32),\n            B_i32x32,\n            dtype=\"int32x32\",\n        )\n\n\nVRMPY_u8u8i32_INTRIN = \"dot_32x4_u8u8i32_vrmpy\"\n\nTensorIntrin.register(\n    VRMPY_u8u8i32_INTRIN, dot_product_32x4_u8u8i32_desc, dot_product_32x4_u8u8i32_vrmpy\n)\n\nVRMPY_u8i8i32_INTRIN = \"dot_32x4_u8i8i32_vrmpy\"\n\nTensorIntrin.register(\n    VRMPY_u8i8i32_INTRIN, dot_product_32x4_u8i8i32_desc, dot_product_32x4_u8i8i32_vrmpy\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/rocm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Intrinsics for AMDGPU tensorization.\"\"\"\nfrom tvm.script import tir as T\n\nfrom .. import TensorIntrin\nfrom .dot_product_common import dp4a_desc\n\n\n@T.prim_func\ndef sdot4(\n    A: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    B: T.Buffer((4,), \"int8\", offset_factor=1, align=4, scope=\"shared\"),\n    C: T.Buffer((1,), \"int32\", offset_factor=1, align=4, scope=\"local\"),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0], A[0:4], B[0:4])\n        T.writes(C[0])\n\n        C[0] += T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.amdgcn.sdot4\"),\n            T.uint32(4),\n            T.reinterpret(A.vload([0], \"int8x4\"), dtype=\"int32\"),\n            T.reinterpret(B.vload([0], \"int8x4\"), dtype=\"int32\"),\n            T.int32(0),\n            T.bool(1),\n            dtype=\"int32\",\n        )\n\n\nAMDGPU_SDOT4_INTRIN = \"sdot4\"\n\nTensorIntrin.register(AMDGPU_SDOT4_INTRIN, dp4a_desc, sdot4)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/tensor_intrin/x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring\n\"\"\"Intrinsics for x86 tensorization.\"\"\"\nfrom tvm.script import tir as T\nfrom .. import TensorIntrin\n\n\n# Tensorized intrinsic description and VNNI-specific implementation.\n# Equivalent to the ones in topi/x86/tensor_intrin.py\n\n\n@T.prim_func\ndef dot_product_16x4_u8i8i32_desc(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((16, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((16,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:16], A[0:4], B[0:16, 0:4])\n        T.writes(C[0:16])\n        for i in T.serial(0, 16):\n            for k in T.serial(0, 4):\n                with T.block(\"update\"):\n                    vi, vk = T.axis.remap(\"SR\", [i, k])\n                    C[vi] = C[vi] + T.cast(A[vk], \"int32\") * T.cast(B[vi, vk], \"int32\")\n\n\n@T.prim_func\ndef dot_product_16x4_u8i8i32_vnni(\n    A: T.Buffer((4,), \"uint8\", offset_factor=1),\n    B: T.Buffer((16, 4), \"int8\", offset_factor=1),\n    C: T.Buffer((16,), \"int32\", offset_factor=1),\n) -> None:\n    with T.block(\"root\"):\n        T.reads(C[0:16], A[0:4], B[0:16, 0:4])\n        T.writes(C[0:16])\n\n        A_u8x4 = A.vload([0], \"uint8x4\")\n        A_i32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n\n        B_i8x64 = B.vload([0, 0], dtype=\"int8x64\")\n        B_i32x16 = T.reinterpret(B_i8x64, dtype=\"int32x16\")\n        C_i32x16 = C.vload([0], dtype=\"int32x16\")\n\n        C[T.ramp(T.int32(0), 1, 16)] = T.call_llvm_pure_intrin(\n            T.llvm_lookup_intrinsic_id(\"llvm.x86.avx512.vpdpbusd.512\"),\n            T.uint32(0),\n            C_i32x16,\n            T.broadcast(A_i32, 16),\n            B_i32x16,\n            dtype=\"int32x16\",\n        )\n\n\nVNNI_DOT_16x4_INTRIN = \"dot_16x4_vnni\"\n\nTensorIntrin.register(\n    VNNI_DOT_16x4_INTRIN, dot_product_16x4_u8i8i32_desc, dot_product_16x4_u8i8i32_vnni\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/transform/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace of all TIR transformations\"\"\"\n# pylint: disable=wildcard-import, invalid-name\n\nfrom .function_pass import prim_func_pass, PrimFuncPass\nfrom .transform import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/transform/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.transform\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir.transform\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/transform/function_pass.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TIR specific function pass support.\"\"\"\nimport inspect\nimport types\nimport functools\nfrom typing import Callable, List, Optional, Union\n\nimport tvm._ffi\nfrom tvm.ir.transform import Pass, PassInfo\n\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"tir.PrimFuncPass\")\nclass PrimFuncPass(Pass):\n    \"\"\"A pass that works on each :py:func:`tvm.tir.PrimFunc` in a module. A function\n    pass class should be created through py:func:`tvm.tir.transform.function_pass`.\n    \"\"\"\n\n\ndef _wrap_class_function_pass(pass_cls, pass_info):\n    \"\"\"Wrap a python class as function pass\"\"\"\n\n    class PyFunctionPass(PrimFuncPass):\n        \"\"\"Internal wrapper class to create a class instance.\"\"\"\n\n        def __init__(self, *args, **kwargs):\n            # initialize handle in cass pass_cls creation failed.fg\n            self.handle = None\n            inst = pass_cls(*args, **kwargs)\n            # it is important not to capture self to\n            # avoid a cyclic dependency\n            def _pass_func(func, mod, ctx):\n                return inst.transform_function(func, mod, ctx)\n\n            self.__init_handle_by_constructor__(\n                _ffi_api.CreatePrimFuncPass, _pass_func, pass_info  # type: ignore\n            )\n\n            self._inst = inst\n\n        def __getattr__(self, name):\n            # fall back to instance attribute if there is not any\n            return self._inst.__getattribute__(name)\n\n    functools.update_wrapper(PyFunctionPass.__init__, pass_cls.__init__)\n    PyFunctionPass.__name__ = pass_cls.__name__\n    PyFunctionPass.__doc__ = pass_cls.__doc__\n    PyFunctionPass.__module__ = pass_cls.__module__\n    return PyFunctionPass\n\n\ndef prim_func_pass(\n    pass_func=None,\n    opt_level: int = None,\n    name: Optional[str] = None,\n    required: Optional[List[str]] = None,\n) -> Union[Callable, PrimFuncPass]:\n    \"\"\"Decorate a function pass.\n\n    This function returns a callback when pass_func\n    is provided. Otherwise, it returns the created function pass using the\n    given optimization function.\n\n    Parameters\n    ----------\n    pass_func : Optional[Callable[(tvm.tir.PrimFunc, IRModule, PassContext) -> tvm.tir.PrimFunc]]\n        The transformation function or class.\n\n    opt_level : int\n        The optimization level of this module pass.\n\n    name : Optional[str]\n        The name of the function pass. The name could be empty. In this case, the\n        name of the optimization function will be used as the pass name.\n\n    required : Optional[List[str]]\n        The list of passes that the function pass is dependent on.\n\n    Returns\n    -------\n    create_function_pass : Union[Callable, FunctionPass]\n\n        A decorator will be returned if pass_func is not provided,\n        otherwise return the decorated result.\n        The returned decorator has two behaviors depending on the input:\n        A new FunctionPass will be returned when we decorate a pass function.\n        A new FunctionPass class will be returned when we decorate a class type.\n\n    Examples\n    --------\n    The following code block decorates a function pass class.\n\n    .. code-block:: python\n\n        @tvm.tir.transform.prim_func_pass(opt_level=1)\n        class TestReplaceFunc:\n            def __init__(self, new_func):\n                self.new_func = new_func\n\n            def transform_function(self, func, mod, ctx):\n                # just for demo purposes\n                # transform func to new_func\n                return self.new_func\n\n    The following code creates a function pass by decorating\n    a user defined transform function.\n\n    .. code-block:: python\n\n        @tvm.tir.transform.prim_func_pass(opt_level=2)\n        def transform(func, mod, ctx):\n            # my transformations here.\n            return func\n\n        function_pass = transform\n        assert isinstance(function_pass, transform.FunctionPass)\n        assert function_pass.info.opt_level == 2\n\n        # Given a module m, the optimization could be invoked as the following:\n        updated_mod = function_pass(m)\n        # Now constant folding should have been applied to every function in\n        # the provided module m. And the updated module will be returned.\n    \"\"\"\n\n    if opt_level is None:\n        raise ValueError(\"Please provide opt_level for the function pass.\")\n\n    required = required if required else []\n    if not isinstance(required, (list, tuple)):\n        raise TypeError(\"Required is expected to be the type of \" + \"list/tuple.\")\n\n    def create_function_pass(pass_arg):\n        \"\"\"Internal function that creates a function pass\"\"\"\n        fname = name if name else pass_arg.__name__\n        info = PassInfo(opt_level, fname, required)\n        if inspect.isclass(pass_arg):\n            return _wrap_class_function_pass(pass_arg, info)\n        if not isinstance(pass_arg, (types.FunctionType, types.LambdaType)):\n            raise TypeError(\"pass_func must be a callable for Module pass\")\n        return _ffi_api.CreatePrimFuncPass(pass_arg, info)  # type: ignore\n\n    if pass_func:\n        return create_function_pass(pass_func)\n    return create_function_pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/transform/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Wrapping existing transformations.\"\"\"\n# pylint: disable=invalid-name\n\n\nimport enum\nfrom typing import Callable, Optional\n\nfrom . import _ffi_api\nfrom . import function_pass as _fpass\n\n\ndef Apply(ftransform):\n    \"\"\"Apply ftransform to each function in the Module.\n\n    This function is a thin wrapper around tvm.tir.transform.prim_func_pass\n\n    Parameters\n    ----------\n    ftransform: tvm.tir.PrimFunc -> tvm.tir.PrimFunc\n       The transformation pass.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    # pylint: disable=unused-argument\n    def _transform(func, mod, ctx):\n        return ftransform(func)\n\n    return _fpass.prim_func_pass(_transform, opt_level=0, name=\"Apply\")  # type: ignore\n\n\ndef InjectPrefetch():\n    \"\"\"Inject prefetch instructions into stmt.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectPrefetch()  # type: ignore\n\n\ndef ApplyLayoutTransforms():\n    \"\"\"Reshape buffers that appear in the \"layout_transform_map\"\n    fucntion attribute.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    \"\"\"\n    return _ffi_api.ApplyLayoutTransforms()  # type: ignore\n\n\ndef StorageFlatten(cache_line_size, create_bound_attribute: bool = False):\n    \"\"\"Flatten the multi-dimensional read/write to 1D.\n\n\n    Parameters\n    ----------\n    cache_line_size: int\n        The size of CPU cache line.\n\n    create_bound_attribute:\n        Whether to create bound attributes.\n\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.StorageFlatten(cache_line_size, create_bound_attribute)  # type: ignore\n\n\ndef TextureFlatten():\n    \"\"\"Flatten the multi-dimensional read/write to 2D.\n\n\n    Parameters\n    ----------\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.TextureFlatten()  # type: ignore\n\n\ndef InjectCopyIntrin(pragma_key: str, fintrin):\n    \"\"\"Inject virtual thread loops.\n\n    Parameters\n    ----------\n    pragma_key : str\n        The pragma key for hint of copy.\n\n    fintrin : function\n        The function with signature copyintrin(src, dst, pad_before, pad_after, pad_value)\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectCopyIntrin(pragma_key, fintrin)  # type: ignore\n\n\ndef CoProcSync():\n    \"\"\"Detect and insert sync points to co-processor.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.CoProcSync()  # type: ignore\n\n\ndef LiftAttrScope(attr_key: str):\n    \"\"\"Lift common attrs with attr_key to outer scope.\n\n    Parameters\n    ----------\n    attr_key : str\n        The attribute key to be checked.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LiftAttrScope(attr_key)  # type: ignore\n\n\ndef LoopPartition():\n    \"\"\"Inject virtual thread loops.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LoopPartition()  # type: ignore\n\n\ndef VectorizeLoop(enable_vectorize: bool = True):\n    \"\"\"Lower vectorization loops.\n\n    Parameters\n    ----------\n    enable_vectorize : bool\n        Whether vectorization is enabled.\n        Will lower to scalar loop when it is turned off.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.VectorizeLoop(enable_vectorize)  # type: ignore\n\n\ndef InjectVirtualThread():\n    \"\"\"Inject virtual thread loops.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectVirtualThread()  # type: ignore\n\n\ndef InjectDoubleBuffer():\n    \"\"\"Inject double buffer statements.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectDoubleBuffer()  # type: ignore\n\n\ndef InjectRollingBuffer():\n    \"\"\"Inject rolling buffer statements.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectRollingBuffer()  # type: ignore\n\n\ndef StorageRewrite():\n    \"\"\"Rewrite storage allocation pattern.\n\n    Moves the allocation to outer most possible scope.\n    Trying to share space between allocations to make\n    a static allocation plan when possible.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.StorageRewrite()  # type: ignore\n\n\ndef UnrollLoop():\n    \"\"\"Unroll the constant loop marked by unroll.\n\n    This pass also automatically attach pragma unroll tag to loops which meets the standard.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.UnrollLoop()  # type: ignore\n\n\ndef RemoveNoOp():\n    \"\"\"Remove No Op from the Stmt.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RemoveNoOp()  # type: ignore\n\n\ndef RemoveAssume():\n    \"\"\"Remove all instances of builtin::assume\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RemoveAssume()  # type: ignore\n\n\ndef RemoveStoreUndef():\n    \"\"\"Remove stores of undefined values from the Stmt.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RemoveStoreUndef()  # type: ignore\n\n\ndef BF16Legalize():\n    \"\"\"Legalize bf16 typed Ops.\n    Runs BF16Promote, BF16CastElimination and BF16TypeLowering\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.BF16Legalize()  # type: ignore\n\n\ndef BF16Promote():\n    \"\"\"Promote bf16 to fp32. Add a cast to fp32\n    before Ops, then add a cast back to bf16.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.BF16Promote()  # type: ignore\n\n\ndef BF16CastElimination():\n    \"\"\"Eliminate verbose casting between fp32 and bf16\n    Checks if the AST has the pattern:\n    castto32(castto16(some_fp32_op(...)))\n    The verbose casting is generated by BF16Promote for multiple\n    bf16 Ops in a row. e.g.:\n    X[i] + Y[i] + T[i] =>\n    bf16((float32(bf16((float32(X[i]) + float32(Y[i])))) + float32(T[i])))\n    After this pass:\n    bf16(float32(X[i]) + float32(Y[i]) + float32(T[i]))\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.BF16CastElimination()  # type: ignore\n\n\ndef BF16TypeLowering():\n    \"\"\"Replace all bf16 type with uint16. Also lower the casting\n    between fp32 and bf16\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.BF16TypeLowering()  # type: ignore\n\n\ndef CommonSubexprElimTIR(enable_cse_tir: bool = True, identify_equiv_terms: bool = False):\n    \"\"\"Replace redundant computations by new variables.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.CommonSubexprElimTIR(enable_cse_tir, identify_equiv_terms)  # type: ignore\n\n\ndef RewriteUnsafeSelect():\n    \"\"\"Detect and rewrite unsafe select that contains memory access.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RewriteUnsafeSelect()  # type: ignore\n\n\ndef Simplify():\n    \"\"\"Run arithmetic simplifications on the statements and expressions.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.Simplify()  # type: ignore\n\n\ndef InstrumentBoundCheckers():\n    \"\"\"Instruments bound checkers.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InstrumentBoundCheckers()  # type: ignore\n\n\ndef LowerCustomDatatypes():\n    \"\"\"Lower custom datatypes.\n\n    See tvm::datatypes::Registry for more information on adding custom datatypes.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerCustomDatatypes()  # type: ignore\n\n\ndef MakePackedAPI():\n    \"\"\"Transform the PrimFuncs in the module to a packed func API.\n\n    Prior to this pass, the PrimFunc may have Buffer arguments defined\n    in the `PrimFuncNode::buffer_map`.  This pass consumes the\n    `buffer_map`, using it to generate `TVMArgs` and `TVMRetValue*`\n    arguments that implement the `PackedFunc` API.\n\n    For static shapes, the `BufferNode::shape`, `BufferNode::strides`,\n    and `BufferNode::elem_offset` member variables are used to\n    generate runtime checks on the corresponding member variables in\n    the user-provided `DLTensor*` or `tvm.nd.array` argument.  (e.g. A\n    PrimFunc that accepts a buffer of shape `[16,32]` validates that\n    the `DLTensor::shape` array is `[16,32]`.)\n\n    For dynamic Buffers, in which one or more of these `BufferNode` member\n    variables use `tir.Var` that are not defined by other PrimFunc\n    parameters, these are instead used to define the variables based on\n    the corresponding `DLTensor` members.  (e.g. A PrimFunc that accepts a\n    buffer of shape `[tir.Var(\"n\"), tir.Var(\"m\")]`, when passed a\n    `DLTensor` of shape `[16,32]`, will define `n = 16` and `n=32`, based\n    on the argument's shape.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.MakePackedAPI()  # type: ignore\n\n\ndef MakeUnpackedAPI():\n    \"\"\"Transform the PrimFuncs in the module to a C API compatible with internal calls.\n\n    Prior to this pass, the PrimFunc may have Buffer arguments defined in\n    the `PrimFuncNode::buffer_map`.  This pass consumes the `buffer_map`,\n    using it to generate `T*` arguments (e.g. `float32*`) that can be\n    directly called by a C API.\n\n    For static shapes, no runtime validation is performed to confirm that\n    the argument buffer's shape matches the expected shape.  For dynamic\n    shapes, `MakeUnpackedAPI` requires that the dynamic parameters be\n    passed as separate `tir.Var` parameters.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.MakeUnpackedAPI()  # type: ignore\n\n\ndef SplitHostDevice():\n    \"\"\"Split the function into a host function and device functions.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.SplitHostDevice()  # type: ignore\n\n\ndef DecorateDeviceScope():\n    \"\"\"Decorate all the function's body as device function.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.DecorateDeviceScope()  # type: ignore\n\n\ndef SkipAssert():\n    \"\"\"Skip assert stmt.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.SkipAssert()  # type: ignore\n\n\ndef ThreadSync(storage_scope: str):\n    \"\"\"Insert sync between parallel read/write of shared buffers.\n\n    Parameters\n    ----------\n    storage_scope: str\n        The target storage scope.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.ThreadSync(storage_scope)  # type: ignore\n\n\ndef LowerThreadAllreduce():\n    \"\"\"Lower cross thread alleduce.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerThreadAllreduce()  # type: ignore\n\n\ndef InferFragment():\n    \"\"\"Infer the TensorCore fragment infomation using tensor intrinsics.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InferFragment()  # type: ignore\n\n\ndef LowerWarpMemory():\n    \"\"\"Lower warp memory access to low-level device related function calls.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerWarpMemory()  # type: ignore\n\n\ndef LowerTVMBuiltin():\n    \"\"\"Lower tvm builtin intrinsics.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerTVMBuiltin()  # type: ignore\n\n\ndef LegalizePackedCalls():\n    \"\"\"Legalize packed calls to have its arguments wrapped in TVMValues\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LegalizePackedCalls()  # type: ignore\n\n\ndef LowerIntrin():\n    \"\"\"Lower target specific intrinsic calls.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerIntrin()  # type: ignore\n\n\ndef LowerDeviceStorageAccessInfo():\n    \"\"\"Lower attached storage access information on device.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    Note\n    ----\n    Run this pass after all storage access analysis finish.\n    \"\"\"\n    return _ffi_api.LowerDeviceStorageAccessInfo()  # type: ignore\n\n\ndef CombineContextCall():\n    \"\"\"Combine context calls in the host function.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.CombineContextCall()  # type: ignore\n\n\ndef NarrowDataType(target_bits: int):\n    \"\"\"Narrow down PrimExpr datatype in stmt to target_bits.\n\n    Parameters\n    ----------\n    target_bits : int\n        The target bit configuration.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    Note\n    ----\n    Run this pass after StorageFlatten.\n    \"\"\"\n    return _ffi_api.NarrowDataType(target_bits)  # type: ignore\n\n\ndef VerifyMemory():\n    \"\"\"Verify if func contains illegal host side direct memory access.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.VerifyMemory()  # type: ignore\n\n\n# pylint: disable=no-else-return,inconsistent-return-statements\ndef HoistIfThenElse(variant: Optional[str] = None):\n    \"\"\"Hoist loop-invariant IfThenElse nodes to outside the eligible loops.\n\n    Parameters\n    ----------\n    variant : Optional[String]\n        The variant of the pass.\n        variant can have any one of following values [\"basic\", None(Default)].\n\n        The basic variant supports basic hoisting scenarios where it expects\n        the For & If Nodes are in place consecutively and does not involve\n        global scope variables or more advanced scenarios.\n\n        Default variant supports all hoisting scenarios,i.e., {\"Basic\" + \"Advanced\"}\n        supported with control with PassContext configs like below:\n\n            config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    if variant == \"basic\":\n        return _ffi_api.HoistIfThenElseBasic()  # type: ignore\n    elif variant is None:\n        return _ffi_api.HoistIfThenElse()  # type: ignore\n\n\nclass HoistedConditionals(enum.Flag):\n    \"\"\"Flags for use in HoistExpressionConfig.conditional_types\n\n    Each bitflag represents a type of expression that should be\n    hoisted to the outermost loop possible.\n    \"\"\"\n\n    Never = 0\n    \"\"\" No hoisting of conditionals \"\"\"\n\n    IfElseStmt = 1\n    \"\"\" If set, look for hoist candidates in IfElseStmt \"\"\"\n\n    IfElseExpr = 2\n    \"\"\" If set, look for hoist candidates in tir.if_then_else \"\"\"\n\n    BooleanExpression = 4\n    \"\"\" If set, look for hoist candidates in all boolean expressions \"\"\"\n\n    UsingBlockVar = 8\n    \"\"\" If set, allow hoisting of conditionals that use a block variable (e.g. threadIdx.x)  \"\"\"\n\n    All = IfElseStmt | IfElseExpr | BooleanExpression | UsingBlockVar\n    \"\"\" Enable all hoisting of conditionals\"\"\"\n\n\nclass HoistedLetBindings(enum.Flag):\n    \"\"\"Flags for use in HoistExpressionConfig.let_binding_types\n\n    Each bitflag represents a type of let binding expression that should be\n    hoisted to the outermost loop possible.\n    \"\"\"\n\n    Never = 0\n    \"\"\" No hoisting of let bindings \"\"\"\n\n    RequiredByConditional = 1\n    \"\"\" Bindings that are used by a hoisted conditional \"\"\"\n\n    LetStmt = 2\n    \"\"\" Bindings occuring in LetStmt \"\"\"\n\n    LetExpr = 4\n    \"\"\" Bindings occuring in Let expressions \"\"\"\n\n    All = RequiredByConditional | LetStmt | LetExpr\n    \"\"\" Enable all hoisting of let bindings \"\"\"\n\n\ndef HoistExpression():\n    \"\"\"Generalized verison of HoistIfThenElse.\n\n    Hoist loop-invariant expressions to outside the eligible loops.\n    Searches for expressions in:\n\n    * LetStmt bindings\n    * IfThenElse conditions\n    * Boolean operators\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    \"\"\"\n    return _ffi_api.HoistExpression()  # type: ignore\n\n\ndef LowerCrossThreadReduction():\n    \"\"\"Lower cross-thread reduction from thread bindings to\n    intrinsic function calls.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerCrossThreadReduction()  # type: ignore\n\n\ndef LowerInitBlock():\n    \"\"\"Lower block init stmt into IfThenElse statements.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerInitBlock()  # type: ignore\n\n\ndef PlanAndUpdateBufferAllocationLocation():\n    \"\"\"Locate the buffer allocation to the exact position (usually is\n    the lca of buffer access). This pass will inject opaque block\n    with alloc_buffers at the allocation site.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.PlanAndUpdateBufferAllocationLocation()  # type: ignore\n\n\ndef ConvertBlocksToOpaque():\n    \"\"\"Substitute all the block vars with the PrimExprs they are bound to, indicated by\n    the corresponding iter_values in BlockRealize, and then convert the blocks into\n    opaque ones by removing all the iter_values in BlockRealize and iter_vars in Block.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.ConvertBlocksToOpaque()  # type: ignore\n\n\ndef CompactBufferAllocation():\n    \"\"\"Compact the buffer access region. by removing the buffer regions\n    that are not accessed, i.e. narrowing the buffer shape and adjust\n    the access region if necessary.\n\n    Example\n    -------\n\n    Before narrowing, ``B`` is a ``[16, 16]`` buffer, but only a\n    skinny vector ``B[i, 0:16]`` is accessed.\n\n    .. code-block:: python\n\n        for i in range(0, 16):\n            with T.block():\n                B = T.alloc_buffer(16, 16)\n                for j in range(0, 16):\n                    B[i, j] = A[i, j] + 1\n                for j in range(0, 16):\n                    C[i, j] = B[i, j] + 1\n\n    This pass narrows the buffer shape and adjust its accessed region\n    accordingly.  In this particular case, because only a ``1 * 16``\n    vector of ``B`` is accessed, the pass narrows ``B`` to shape ``[1,\n    16]``, and changes the access to ``B[i, j]`` to ``B[0, j]``.\n\n    .. code-block:: python\n\n        for i in range(0, 16):\n            with T.block():\n                B = T.alloc_buffer(1, 16)\n                for j in range(0, 16):\n                    B[0, j] = A[i, j] + 1\n                for j in range(0, 16):\n                    C[i, j] = B[0, j] + 1\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    \"\"\"\n    return _ffi_api.CompactBufferAllocation()  # type: ignore\n\n\ndef LowerMatchBuffer():\n    \"\"\"Remove match buffers inside the block. Also, it will validate the binding.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerMatchBuffer()  # type: ignore\n\n\ndef LowerOpaqueBlock():\n    \"\"\"Remove the block to ensure that the TIR can not be scheduled again.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.LowerOpaqueBlock()  # type: ignore\n\n\ndef FlattenBuffer():\n    \"\"\"Flatten the multi-dimensional BufferLoad and BufferStore to single dimensional\n    BufferLoad/BufferStore for the TIR not contains opaque block.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.FlattenBuffer()  # type: ignore\n\n\ndef UnifyThreadBinding():\n    \"\"\"Unify all the thread bindings for \"blockIdx.x/y/z\",\n    \"threadIdx.x/y/z\", and \"vthread.x/y/z\". Before the unification,\n    two vars that are bound to a thread axis (e.g., \"threadIdx.x\")\n    use different IterVars and variables in their AttrStmts. After\n    the unification, we use a consolidated IterVar and a variable\n    for them.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n\n    Note\n    ----\n    `vthread` is a legacy behavior that will be deprecated, though\n    thread bindings of `vthread` are still also unified in this\n    pass. Please use `vthread.x`, `vthread.y` and `vthread.z` instead.\n    \"\"\"\n    return _ffi_api.UnifyThreadBinding()  # type: ignore\n\n\ndef MergeDynamicSharedMemoryAllocations():\n    \"\"\"This pass merges multiple TIR-level dynamic shared memory allocations\n    into one allocation.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.MergeDynamicSharedMemoryAllocations()  # type: ignore\n\n\ndef ConvertForLoopsToSerial():\n    \"\"\"Convert Parallel For Loops to Serial For Loops.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.ConvertForLoopsToSerial()  # type: ignore\n\n\ndef InjectSoftwarePipeline():\n    \"\"\"Transform annotated loops into pipelined one that parallelize producers and consumers\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectSoftwarePipeline()  # type: ignore\n\n\ndef ExtractPrimFuncConstants():\n    \"\"\"Collects and unificates tir non-scalar constants to module's attr 'Constants' array.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.ExtractPrimFuncConstants()  # type: ignore\n\n\ndef RenormalizeSplitPattern():\n    \"\"\"Renormalize the split pattern from floordiv(floormod()) to floormod(floordiv())\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RenormalizeSplitPattern()  # type: ignore\n\n\ndef BindTarget(target):\n    \"\"\"Annotate a PrimFunc with a given target.\n    Parameters\n    -------\n    target : tvm.target.Target\n        target\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.BindTarget(target)  # type: ignore\n\n\ndef AnnotateEntryFunc():\n    \"\"\"Set a PrimFunc as the entry point if it is only function in IRModule.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.AnnotateEntryFunc()  # type: ignore\n\n\ndef Filter(fcond: Callable):\n    \"\"\"Filter out PrimFuncs that does not satisfy the given condition.\n    `fcond` should be a function that takes a primfunc and returns boolean.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.Filter(fcond)  # type: ignore\n\n\ndef InjectPTXAsyncCopy():\n    \"\"\"Rewrite global to shared memory copy on CUDA with asyncronous copy.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InjectPTXAsyncCopy()  # type: ignore\n\n\ndef RemoveWeightLayoutRewriteBlock(skip_ndarray_rewrite=False):\n    \"\"\"Remove weight layout rewrite block before benchmarking during tuning stage.\n\n    Parameters\n    ----------\n    skip_ndarray_rewrite : bool\n        If True, exact rewrite of NDArray, according to the given index map, will be skipped.\n        Only the shape of the NDArray is transformed correctly, and the content of the destination\n        array will be filled with random values.\n\n        When this pass is called many times during MetaSchedule tuning, the raw data of NDArray,\n        before and after rewrite, does not matter. Since NDArray layout rewrite, using IndexMap's\n        MapNDArray, is currently slow, skipping the exact rewrite is sometimes necessary.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.RemoveWeightLayoutRewriteBlock(skip_ndarray_rewrite)  # type: ignore\n\n\ndef ManifestSharedMemoryLocalStage():\n    \"\"\"Add the explicit local stage for the shared memory access on GPU.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.ManifestSharedMemoryLocalStage()  # type: ignore\n\n\ndef InstrumentProfileIntrinsics():\n    \"\"\"Insert intrinsic calls to instrument function and loop level profiling.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The result pass\n    \"\"\"\n    return _ffi_api.InstrumentProfileIntrinsics()  # type: ignore\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\"Namespace for Unified Static Memory Planner\"\"\"\n\nfrom . import analysis\nfrom . import transform\nfrom .utils import BufferInfo\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.usmp\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir.usmp\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/analysis/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\"Namespace for Unified Static Memory Planner\"\"\"\n\nfrom .analysis import extract_buffer_info\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/analysis/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.usmp.analysis\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir.usmp.analysis\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/analysis/analysis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"USMP Analysis Python API for passes\"\"\"\n# pylint: disable=invalid-name\nfrom . import _ffi_api\nfrom ...function import PrimFunc\nfrom ....ir.module import IRModule\n\n\ndef extract_buffer_info(main_func: PrimFunc, mod: IRModule):\n    \"\"\"Convert Parallel For Loop to Serial.\n\n    Parameters\n    ----------\n    main_func: tvm.tir.PrimFunc\n        The main function containing calls to operator PrimFuncs.\n    mod : tvm.ir.IRModule\n        The full IRModule containing all PrimFuncs\n\n    Returns\n    -------\n    Map<tir::Stmt, BufferInfo>\n        extracted buffer info objects\n    \"\"\"\n    return _ffi_api.extract_buffer_info(main_func, mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/transform/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-import, redefined-builtin\n\"\"\"Namespace for Unified Static Memory Planner\"\"\"\n\nfrom .transform import convert_pool_allocations_to_offsets\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/transform/_ffi_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI APIs for tvm.tir.usmp.analysis\"\"\"\nimport tvm._ffi\n\n\ntvm._ffi._init_api(\"tir.usmp.transform\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/transform/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"USMP Transform Python API for passes\"\"\"\n# pylint: disable=invalid-name\n\nfrom typing import Dict\n\nimport tvm\nfrom tvm.tir import Stmt\nfrom tvm.tir.usmp.utils import PoolAllocation\nfrom . import _ffi_api\n\n\ndef convert_pool_allocations_to_offsets(\n    pool_allocations: Dict[Stmt, PoolAllocation], emit_tvmscript_printable: bool = False\n) -> tvm.transform.Pass:\n    \"\"\"Convert pool allocations to Load nodes with offsets from pools.\n\n    Parameters\n    ----------\n    pool_allocations : Dict[Stmt, PoolAllocation]\n        Allocate or AllocateConst node to pool allocation mapping\n    emit_tvmscript_printable : bool\n        A toggle to emit TVMScript printable IRModule for unit tests\n        removing all attributes that should be attached for integration\n\n    Returns\n    -------\n    ret: tvm.transform.Pass\n        The registered pass that converts the allocations to offsets.\n    \"\"\"\n    return _ffi_api.ConvertPoolAllocationsToOffsets(pool_allocations, emit_tvmscript_printable)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/tir/usmp/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"USMP Utilities and Data Structures\"\"\"\n# pylint: disable=invalid-name\n\nfrom typing import Optional, List\n\nimport tvm\nfrom tvm._ffi import register_object\nfrom tvm.runtime import Object\nfrom . import _ffi_api\nfrom ...ir.memory_pools import PoolInfo\n\n\n# The allocate node attribute to indicate candidate memory pools.\n# This needs to be kept in sync with CANDIDATE_MEMORY_POOL_ATTR in\n# include/tvm/tir/usmp/utils.h\nCANDIDATE_MEMORY_POOL_ATTR = \"candidate_memory_pools\"\n\n\ndef use_workspace_io_is_enabled() -> bool:\n    \"\"\"\n    Check whether placing I/O tensors in the workspace is enabled.\n    \"\"\"\n    ctx = tvm.transform.PassContext.current()\n    return bool(ctx.config.get(\"tir.usmp.use_workspace_io\", False))\n\n\n@register_object(\"tir.usmp.BufferInfo\")\nclass BufferInfo(Object):\n    \"\"\"BufferInfo object holds information related to buffers\n    that are associated with tir.allocates and tir.allocate_consts\n    that will be used with USMP\n\n    Parameters\n    ----------\n    name_hint : str\n        The name associated with the buffer (derived from TIR)\n\n    size_bytes : int\n        The size in bytes\n\n    pool_candidates : List[PoolInfo]\n        The list of candidates pools this buffer could be placed\n\n    alignment : Optional[int]\n        The byte alignment required in the workspace memory\n\n    \"\"\"\n\n    def __init__(\n        self,\n        name_hint: str,\n        size_bytes: int,\n        pool_candidates: List[PoolInfo],\n        alignment: Optional[int] = None,\n    ):\n        self.__init_handle_by_constructor__(\n            _ffi_api.BufferInfo,  # type: ignore # pylint: disable=no-member\n            name_hint,\n            size_bytes,\n            pool_candidates,\n            alignment,\n        )\n\n    def set_conflicts(self, conflicts: list):\n        \"\"\"Sets the conflicting array of buffer info objects\"\"\"\n        _ffi_api.BufferInfoSetConflicts(self, conflicts)\n\n\n@register_object(\"tir.usmp.PoolAllocation\")\nclass PoolAllocation(Object):\n    \"\"\"PoolAllocation object holds information related to an allocation\n    that indicates an offset in a pool\n\n    Parameters\n    ----------\n    pool_info : PoolInfo\n        The PoolInfo to which this allocation corresponds to\n\n    byte_offset : int\n        The offset in the pool where the allocate node should be placed\n\n    \"\"\"\n\n    def __init__(self, pool_info: PoolInfo, byte_offset: int):\n        self.__init_handle_by_constructor__(\n            _ffi_api.PoolAllocation,  # type: ignore # pylint: disable=no-member\n            pool_info,\n            byte_offset,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"TVM Operator Inventory.\n\nTOPI is the operator collection library for TVM, to provide sugars\nfor constructing compute declaration as well as optimized schedules.\n\nSome of the schedule function may have been specially optimized for a\nspecific workload.\n\"\"\"\nfrom tvm._ffi.libinfo import __version__\n\n# Ensure C++ schedules get registered first, so python schedules can\n# override them.\nfrom . import cpp\n\nfrom .math import *\nfrom .tensor import *\nfrom .generic_op_impl import *\nfrom .reduction import *\nfrom .transform import *\nfrom .broadcast import *\nfrom .sort import *\nfrom .scatter import *\nfrom .sparse_fill_empty_rows import *\nfrom .sparse_reshape import *\nfrom .scatter_add import *\nfrom .argwhere import *\nfrom .scan import *\nfrom .einsum import *\nfrom .unique import *\nfrom .searchsorted import *\nfrom .stft import *\nfrom . import generic\nfrom . import nn\nfrom . import x86\nfrom . import cuda\nfrom . import gpu\nfrom . import arm_cpu\nfrom . import mali\nfrom . import bifrost\nfrom . import intel_graphics\nfrom . import utils\nfrom . import rocm\nfrom . import vision\nfrom . import image\nfrom . import sparse\nfrom . import hls\nfrom . import random\nfrom . import hexagon\nfrom . import adreno\n\n# error reporting\nfrom .utils import InvalidShapeError\n\n# not import testing by default\n# because testing can have extra deps that are not necessary\n# we can import them from test cases explicitly\n# from . import testing\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"Qualcomm Adreno GPU specific declaration and schedules.\"\"\"\nfrom .conv2d_nchw import *\nfrom .depthwise_conv2d_nchw import *\nfrom .conv2d_nhwc import *\nfrom .depthwise_conv2d_nhwc import *\nfrom .pooling import *\nfrom .conv2d_alter_op import *\nfrom .conv2d_nchw_winograd import *\nfrom .conv2d_nhwc_winograd import *\nfrom .injective import schedule_injective\nfrom .reduction import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D alter op for Qualcomm Adreno GPU\"\"\"\n\nimport logging\n\nimport re\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple\nfrom .utils import infer_tile_size\nfrom ..nn import conv2d_alter_layout\n\nlogger = logging.getLogger(\"topi\")\n\n# Number of wildcards for matching of supported layouts to be transformed\n_NCHWc_matcher = re.compile(\"^NCHW[0-9]+c$\")\n_OIHWo_matcher = re.compile(\"^OIHW[0-9]+o$\")\n_NHWCc_matcher = re.compile(\"^NHWC[0-9]+c$\")\n_HWIOo_matcher = re.compile(\"^HWIO[0-9]+o$\")\n_HWOIo_matcher = re.compile(\"^HWOI[0-9]+o$\")\n\n\n@conv2d_alter_layout.register(\"adreno\")\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    \"\"\"\n    Prepare of the new conv2d with proper target blocked layout attributes\n    OpenCL Textures supports 1d/2d/3d/4d tetures but read happens always only for 4 elements\n    in a line. Thus way we are supporting for now only 4d conversions on the end\n    NCHW -> NCHW4c & OIHW ->OIHW4o\n    NHWC -> NHWC4c & HWIO -> HWIO4o & HWOI -> HWOI4o\n    \"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    # Parse the attributes.\n    padding = attrs.get_int_tuple(\"padding\")\n    strides = attrs.get_int_tuple(\"strides\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data_tensor, kernel_tensor = tinfos\n    data_dtype = data_tensor.dtype\n    out_dtype = out_type.dtype\n\n    if isinstance(dispatch_ctx, autotvm.task.ApplyGraphBest):\n        cfg = dispatch_ctx.query(target, None)\n        workload = cfg.workload\n    else:\n        impl, outs = relay.backend.te_compiler.select_implementation(\n            relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n        )\n        workload = autotvm.task.get_workload(outs)\n        if workload is None:\n            if impl.name.find(\"winograd\") != -1:\n                if dilation != (1, 1):\n                    logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n                    return None\n\n                assert (data_layout == \"NCHW\" and kernel_layout == \"OIHW\") or (\n                    data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n                )\n                if data_layout == \"NCHW\":\n                    N, CI, H, W = get_const_tuple(data_tensor.shape)\n                    CO, _, KH, KW = get_const_tuple(kernel_tensor.shape)\n                    weight = inputs[1]\n                else:\n                    N, H, W, CI = get_const_tuple(data_tensor.shape)\n                    KH, KW, _, CO = get_const_tuple(kernel_tensor.shape)\n                    weight = relay.layout_transform(inputs[1], \"HWIO\", \"OIHW\")\n\n                # Pre-compute weight transformation in winograd\n                tile_size = infer_tile_size(data_tensor, data_layout)\n\n                # alpha, alpha, CO, CI\n                weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n                    weight, tile_size=tile_size\n                )\n                new_attrs[\"tile_size\"] = tile_size\n                new_attrs[\"channels\"] = CO\n                return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                    inputs[0], weight, **new_attrs\n                )\n            return None\n\n        cfg = dispatch_ctx.query(target, workload)\n\n    topi_tmpl = workload[0]\n\n    if \"conv2d_nchw_winograd\" in topi_tmpl:\n        suffix = \"_acc32\" if \"acc32\" in topi_tmpl else \"\"\n        wkl_name = \"conv2d_nchw_winograd_without_weight_transform\" + suffix + \".image2d\"\n        if dilation != (1, 1):\n            logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n            return None\n\n        tile_size = infer_tile_size(data_tensor, data_layout)\n        if len(data_tensor.shape) == 5:\n            assert data_layout == \"NCHW4c\" and kernel_layout == \"OIHW4o\"\n            N, CI, H, W, CB = get_const_tuple(data_tensor.shape)\n            CO, _, KH, KW, COB = get_const_tuple(kernel_tensor.shape)\n            weight = relay.layout_transform(inputs[1], \"OIHW4o\", \"OIHW\")\n            weight = relay.nn.contrib_conv2d_winograd_weight_transform(weight, tile_size=tile_size)\n            weight = relay.layout_transform(weight, \"HWOI\", \"HWIO4o\")\n\n            new_attrs[\"tile_size\"] = tile_size\n            new_attrs[\"channels\"] = CO * COB\n\n            new_data = data_tensor\n            new_weight = te.placeholder(\n                (KH + tile_size - 1, KW + tile_size - 1, CI * CB, CO, COB),\n                dtype=kernel_tensor.dtype,\n            )\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                wkl_name,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n            return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                inputs[0], weight, **new_attrs\n            )\n\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data_tensor.shape)\n        CO, _, KH, KW = get_const_tuple(kernel_tensor.shape)\n\n        # pre-compute weight transformation in winograd\n        # alpha, alpha, CO, CI\n        weight = relay.nn.contrib_conv2d_winograd_weight_transform(inputs[1], tile_size=tile_size)\n        weight = relay.transpose(weight, axes=[2, 3, 0, 1])  # HWOI -> OIHW\n        # (oc, ic, h, w) -> (h, w, ic, oc)\n        new_attrs[\"kernel_layout\"] = \"HWIO\"\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n\n        # Store the same config for the altered operator (workload)\n        new_data = data_tensor\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO), dtype=kernel_tensor.dtype\n        )\n        in_channel_block = CI % 4\n        if in_channel_block == 0:\n            in_channel_block = 4\n        num_filter_block = CO % 4\n        if num_filter_block == 0:\n            num_filter_block = 4\n\n        if in_channel_block != 4 or num_filter_block != 4:\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                wkl_name,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n            return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                inputs[0], weight, **new_attrs\n            )\n\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % in_channel_block\n        # (oc, ic, h, w) -> (h, w, ic, oc // 4, oc % 4)\n        new_attrs[\"kernel_layout\"] = \"HWIO%do\" % num_filter_block\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % num_filter_block\n        # Store altered operator's config\n        new_data = te.placeholder(\n            (N, CI // in_channel_block, H, W, in_channel_block), dtype=data_dtype\n        )\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO // num_filter_block, num_filter_block),\n            dtype=kernel_tensor.dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_weight,\n                strides,\n                padding,\n                dilation,\n                out_dtype,\n            ],\n            wkl_name,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight, **new_attrs\n        )\n\n    if \"conv2d_nhwc_winograd\" in topi_tmpl:\n        suffix = \"_acc32\" if \"acc32\" in topi_tmpl else \"\"\n        wkl_name = \"conv2d_nhwc_winograd_without_weight_transform\" + suffix + \".image2d\"\n        if dilation != (1, 1):\n            logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n            return None\n\n        tile_size = infer_tile_size(data_tensor, data_layout)\n        if len(data_tensor.shape) == 5:\n            assert data_layout == \"NHWC4c\" and kernel_layout == \"HWIO4o\"\n            N, CI, H, W, CB = get_const_tuple(data_tensor.shape)\n            KH, KW, _, CO, COB = get_const_tuple(kernel_tensor.shape)\n            weight = relay.layout_transform(inputs[1], \"HWIO4o\", \"OIHW\")\n            weight = relay.nn.contrib_conv2d_winograd_weight_transform(weight, tile_size=tile_size)\n            weight = relay.layout_transform(weight, \"HWOI\", \"HWIO4o\")\n\n            new_attrs[\"tile_size\"] = tile_size\n            new_attrs[\"channels\"] = CO * COB\n\n            new_data = data_tensor\n            new_weight = te.placeholder(\n                (KH + tile_size - 1, KW + tile_size - 1, CI * CB, CO, COB),\n                dtype=kernel_tensor.dtype,\n            )\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                wkl_name,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n            return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                inputs[0], weight, **new_attrs\n            )\n\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n        N, H, W, CI = get_const_tuple(data_tensor.shape)\n        KH, KW, _, CO = get_const_tuple(kernel_tensor.shape)\n\n        # pre-compute weight transformation in winograd\n        weight = relay.layout_transform(inputs[1], \"HWIO\", \"OIHW\")\n        weight = relay.nn.contrib_conv2d_winograd_weight_transform(weight, tile_size=tile_size)\n        weight = relay.transpose(weight, axes=[0, 1, 3, 2])  # HWOI -> HWIO\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n\n        # Store the same config for the altered operator (workload)\n        new_data = data_tensor\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO), dtype=kernel_tensor.dtype\n        )\n        in_channel_block = CI % 4\n        if in_channel_block == 0:\n            in_channel_block = 4\n        num_filter_block = CO % 4\n        if num_filter_block == 0:\n            num_filter_block = 4\n\n        if in_channel_block != 4 or num_filter_block != 4:\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                wkl_name,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n            return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                inputs[0], weight, **new_attrs\n            )\n\n        new_attrs[\"data_layout\"] = \"NHWC%dc\" % in_channel_block\n        # (oc, ic, h, w) -> (h, w, ic, oc // 4, oc % 4)\n        new_attrs[\"kernel_layout\"] = \"HWIO%do\" % num_filter_block\n        new_attrs[\"out_layout\"] = \"NHWC%dc\" % num_filter_block\n        # Store altered operator's config\n        new_data = te.placeholder(\n            (N, H, W, CI // in_channel_block, in_channel_block), dtype=data_dtype\n        )\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO // num_filter_block, num_filter_block),\n            dtype=kernel_tensor.dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_weight,\n                strides,\n                padding,\n                dilation,\n                out_dtype,\n            ],\n            wkl_name,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight, **new_attrs\n        )\n\n    if \"conv2d_nchwc\" in topi_tmpl:  # covers both conv2d_nchwc and depthwise_conv2d_nchwc\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            batch, in_channels, in_height, in_width = data_tensor.shape\n            out_channles, _, kernel_h, kernel_w = kernel_tensor.shape\n            in_channel_block = in_channels % 4\n            if in_channel_block == 0:\n                in_channel_block = 4\n            num_filter_block = out_channles % 4\n            if num_filter_block == 0:\n                num_filter_block = 4\n\n            # no support yet for tensors that cannot be divisible by factor 4\n            if num_filter_block != 4:\n                return None\n\n            batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n            out_channel, in_filter_channel, kh, kw = get_const_tuple(kernel_tensor.shape)\n\n            # update new attrs\n            new_attrs[\"channels\"] = out_channel\n            if in_channel_block == 4:\n                new_attrs[\"data_layout\"] = \"NCHW%dc\" % in_channel_block\n            else:\n                new_attrs[\"data_layout\"] = \"NCHW\"\n            # (oc, ic, h, w) -> (OC, ic, h, w, oc)\n            new_attrs[\"kernel_layout\"] = \"OIHW%do\" % num_filter_block\n            new_attrs[\"out_layout\"] = \"NCHW%dc\" % num_filter_block\n\n            # Store altered operator's config for applying of tuned AutoTVM statistics\n            if in_channel_block == 4:\n                new_data = te.placeholder(\n                    (batch_size, in_channel // in_channel_block, height, width, in_channel_block),\n                    dtype=data_dtype,\n                )\n            else:\n                new_data = data_tensor\n            new_kernel = te.placeholder(\n                (out_channel // num_filter_block, in_filter_channel, kh, kw, num_filter_block),\n                dtype=kernel_tensor.dtype,\n            )\n            new_workload = autotvm.task.args_to_workload(\n                [\n                    new_data,\n                    new_kernel,\n                    strides,\n                    padding,\n                    dilation,\n                    out_dtype,\n                ],\n                topi_tmpl,  # \"conv2d_nchwc.image2d\",\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n        else:\n            assert _NCHWc_matcher.match(data_layout)\n            assert _OIHWo_matcher.match(kernel_layout)\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if \"conv2d_nhwc\" in topi_tmpl:  # covers both conv2d_nhwcc and depthwise_conv2d_nhwcc\n        if (data_layout == \"NHWC\" and kernel_layout == \"HWIO\") or (\n            data_layout == \"NHWC\" and kernel_layout == \"HWOI\"\n        ):\n            if kernel_layout == \"HWIO\":\n                batch_size, in_height, in_width, in_channels = data_tensor.shape\n                kernel_h, kernel_w, in_filter_channel, out_channles = kernel_tensor.shape\n            else:\n                batch_size, in_height, in_width, in_channels = data_tensor.shape\n                kernel_h, kernel_w, out_channles, in_filter_channel = kernel_tensor.shape\n            in_channel_block = in_channels % 4\n            if in_channel_block == 0:\n                in_channel_block = 4\n            num_filter_block = out_channles % 4\n            if num_filter_block == 0:\n                num_filter_block = 4\n\n            # no support yet for tensors cannot be divisible by factor 4\n            if num_filter_block != 4:\n                return None\n\n            # update new attrs\n            new_attrs[\"channels\"] = out_channles\n            if in_channel_block == 4:\n                new_attrs[\"data_layout\"] = \"NHWC%dc\" % in_channel_block\n            else:\n                new_attrs[\"data_layout\"] = \"NHWC\"\n            # (h, w, ic, oc) -> (h, w, ic, OC, oc)\n            if kernel_layout == \"HWIO\":\n                new_attrs[\"kernel_layout\"] = \"HWIO%do\" % num_filter_block\n            else:\n                new_attrs[\"kernel_layout\"] = \"HWOI%do\" % num_filter_block\n            new_attrs[\"out_layout\"] = \"NHWC%dc\" % num_filter_block\n\n            # Store altered operator's config for applying of tuned AutoTVM statistics\n            if in_channel_block == 4:\n                new_data = te.placeholder(\n                    (\n                        batch_size,\n                        in_height,\n                        in_width,\n                        in_channels // in_channel_block,\n                        in_channel_block,\n                    ),\n                    dtype=data_dtype,\n                )\n            else:\n                new_data = data_tensor\n            if kernel_layout == \"HWIO\":\n                new_kernel = te.placeholder(\n                    (\n                        kernel_h,\n                        kernel_w,\n                        in_filter_channel,\n                        out_channles // num_filter_block,\n                        num_filter_block,\n                    ),\n                    dtype=kernel_tensor.dtype,\n                )\n            else:\n                new_kernel = te.placeholder(\n                    (\n                        kernel_h,\n                        kernel_w,\n                        out_channles // num_filter_block,\n                        in_filter_channel,\n                        num_filter_block,\n                    ),\n                    dtype=kernel_tensor.dtype,\n                )\n            new_workload = autotvm.task.args_to_workload(\n                [\n                    new_data,\n                    new_kernel,\n                    strides,\n                    padding,\n                    dilation,\n                    out_dtype,\n                ],\n                topi_tmpl,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n        else:\n            assert _NHWCc_matcher.match(data_layout)\n            assert _HWIOo_matcher.match(kernel_layout) or _HWOIo_matcher.match(kernel_layout)\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"conv2d nchw schedule on Qualcomm Adreno GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .utils import (\n    split_to_chunks,\n    pack_input,\n    pack_filter,\n    expand_spatial_dimensions,\n    add_pad,\n    bind_data_copy,\n    get_default_conv2d_config,\n    get_texture_storage,\n)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchwc.image2d\")\ndef schedule_conv2d_nchwc(cfg, outs):\n    \"\"\"Create the schedule for conv2d_nchw\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"adreno_conv2d_latest_op\":\n            schedule_conv2d_NCHWc_KCRSk(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchwc.image2d\")\ndef conv2d_nchwc(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"\n    Convolution operator in NCHWc layout.\n    Algo:\n      1. Convert into blocked format if we have 4d original tensor.\n         In case of AutoTVM we override the convert by just tensors since such conversion\n         will be absent for real blocked convolution, no sense to include into tuning\n      2. Expand spatial dimensions to have width and height be dividable by factor 4\n         This leads to slightly bigger amount of compute but allow utilize GPU much better\n      3. Add paddings. This happens even if we do not need pad originaly. This is useful\n         due to work arounding of the gaps of texture annotation between Primary Functions\n         and limited support of textures in schedules. Later on this pad will be executed\n         separately and will produce texture\n      4. 5d Convolution compute with accumulating into out_dtype\n      5. Cast to the origin output data type\n      6. For case of 4d convolution: convert of output from 5d to 4d\n    \"\"\"\n\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    convert_from4d = False\n    if len(Input.shape) == 4:\n        batch, in_channels, in_height, in_width = Input.shape\n        in_channel_chunks, in_channel_block, in_channel_tail = split_to_chunks(in_channels, 4)\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            dshape = (batch, in_channel_chunks, in_height, in_width, in_channel_block)\n            Input = tvm.te.placeholder(dshape, Input.dtype, name=\"data_placeholder\")\n        else:\n            Input = pack_input(\n                Input,\n                \"NCHW\",\n                batch,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                in_height,\n                in_width,\n            )\n    else:\n        batch, in_channel_chunks, in_height, in_width, in_channel_block = Input.shape\n\n    if len(Filter.shape) == 4:\n        out_channles, in_filter_channels, kernel_h, kernel_w = Filter.shape\n        out_channel_chunks, out_channel_block, out_channel_tail = split_to_chunks(out_channles, 4)\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            kshape = (out_channel_chunks, in_filter_channels, kernel_h, kernel_w, out_channel_block)\n            Filter = tvm.te.placeholder(kshape, Filter.dtype, name=\"kernel_placeholder\")\n        else:\n            convert_from4d = True\n            Filter = pack_filter(\n                Filter,\n                \"OIHW\",\n                out_channel_chunks,\n                out_channel_block,\n                out_channel_tail,\n                in_filter_channels,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                kernel_h,\n                kernel_w,\n            )\n    else:\n        out_channel_chunks, in_filter_channels, kernel_h, kernel_w, out_channel_block = Filter.shape\n\n    out_height_orig, out_height, out_width_orig, out_width = expand_spatial_dimensions(\n        in_height, in_width, kernel_h, kernel_w, dilation_h, dilation_w, padding, stride_h, stride_w\n    )\n\n    temp = add_pad(\n        Input,\n        \"NCHW\",\n        out_height_orig,\n        out_width_orig,\n        kernel_h,\n        kernel_w,\n        dilation_h,\n        dilation_w,\n        padding,\n        stride_h,\n        stride_w,\n    )\n\n    rcc = te.reduce_axis((0, in_channel_chunks), name=\"rc\")\n    rcb = te.reduce_axis((0, in_channel_block), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    conv = te.compute(\n        (batch, out_channel_chunks, out_height, out_width, out_channel_block),\n        lambda nn, ffc, yy, xx, ffb: te.sum(\n            (\n                temp[nn, rcc, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rcb]\n                * Filter[ffc, rcc * in_channel_block + rcb, ry, rx, ffb]\n            ).astype(out_dtype),\n            axis=[rcc, rcb, ry, rx],\n        ),\n        tag=\"conv2d_nchwc\",\n    )\n\n    if convert_from4d and not autotvm.GLOBAL_SCOPE.in_tuning:\n        dummy_cast = te.compute(\n            (batch, out_channel_chunks, out_height_orig, out_width_orig, out_channel_block),\n            lambda n, fc, y, x, fb: conv[n, fc, y, x, fb].astype(out_dtype),\n            tag=\"dummy_cast\",\n        )\n        return te.compute(\n            (batch, out_channles, out_height_orig, out_width_orig),\n            lambda n, c, y, x: dummy_cast[n, c // out_channel_block, y, x, c % out_channel_block],\n            tag=\"adreno_conv2d_latest_op\",\n        )\n    else:\n        return te.compute(\n            (batch, out_channel_chunks, out_height_orig, out_width_orig, out_channel_block),\n            lambda n, ffc, y, x, ffb: conv[n, ffc, y, x, ffb].astype(out_dtype),\n            tag=\"adreno_conv2d_latest_op\",\n        )\n\n\ndef schedule_conv2d_NCHWc_KCRSk(cfg, s, output):\n    \"\"\"\n    schedule optimized for batch size = 1\n\n    Algo:\n    1. Split output axis to three parts: global work size, vthread, local worksize.\n       The limitations for tuning includes heuristics from some tuned networks to limit\n       search space and not pay much time for useles configurations.\n    2. In case of 4d convolution schedule copying of the input (and filter) into\n      5d tensors\n    4. pad should be scheduled separately to create independent opencl kernel. If pad is\n       inlined into convolution, this gives 1.5x performance drop\n    5. We are using cache_read for intermediate tensors to produce texture and guarantee\n       the best performance on the next stage.\n       The weights are managed through static texture planning mechanism and guarantied come\n       in texture memory scope.\n       Thus way we are calling cache_read only for data tensor\n    6. For 5d convolution we schedule the latest op with binding 5d axis and vectorize\n       for textures\n       For 4d tensor we are doing the same for the latest blocked stage, i.e. conversion\n       of data type\n    7. In case of 4d conv we need to schedule postops as well\n    \"\"\"\n    latest = s.outputs[0].output(0)\n    if len(latest.op.axis) == 4:\n        latest_blocked = dummy = output.op.input_tensors[0]\n        conv = dummy.op.input_tensors[0]\n    else:\n        conv = output.op.input_tensors[0]\n        latest_blocked = latest\n\n    pad_data, kernel = s[conv].op.input_tensors\n    filter_pack_rt = bool(\n        isinstance(kernel.op, tvm.te.ComputeOp) and \"filter_pack\" in kernel.op.tag\n    )\n\n    if \"pad_temp\" in pad_data.op.name:\n        input_pad_temp = pad_data.op.input_tensors[0]\n    else:\n        input_pad_temp = pad_data\n\n    input_pack_rt = bool(\n        isinstance(input_pad_temp.op, tvm.te.ComputeOp) and \"input_pack\" in input_pad_temp.op.tag\n    )\n\n    ##### space definition begin #####\n    n, fc, y, x, fb = s[conv].op.axis\n    rcc, rcb, ry, rx = s[conv].op.reduce_axis\n\n    if conv.shape[1] % 2 == 0:\n        min_threads_div = 2\n    else:\n        min_threads_div = 1\n    cfg.define_split(\n        \"tile_fc\",\n        fc,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8\n        and entity.size[2] >= min_threads_div\n        and entity.size[2] < 256,\n    )\n    cfg.define_split(\n        \"tile_y\",\n        y,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8 and entity.size[2] <= 16,\n    )\n    cfg.define_split(\n        \"tile_x\",\n        x,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8 and entity.size[2] <= 16,\n    )\n\n    cfg.define_split(\"tile_rcc\", rcc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n    cfg.multi_filter(\n        filter=lambda entity: (  # pylint: disable=chained-comparison\n            entity[\"tile_fc\"].size[1] * entity[\"tile_y\"].size[1] * entity[\"tile_x\"].size[1]\n        )\n        <= 24\n        and 32\n        <= (entity[\"tile_fc\"].size[2] * entity[\"tile_y\"].size[2] * entity[\"tile_x\"].size[2])\n        < 1024\n    )\n    if cfg.is_fallback:\n        get_default_conv2d_config(cfg, conv.shape[1], conv.shape[2], conv.shape[3])\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n    # There are several conditions that have to be handled:\n    # 1. If we are in the tuning, we always add cache read for data to main conv kernel\n    #    to get texture in tuning opencl kernel\n    # 2. If we are repacking input in runtime, we should always explicit schedule this one more\n    #    stage of data copy from 4d to 5d (referred as pack_data).\n    # 3. If we have pad (independently if we have runtime repack or not) we should inline it in the\n    #    cache_read(\"texture\")\n    if autotvm.GLOBAL_SCOPE.in_tuning or input_pack_rt:\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            if \"pad_temp\" in pad_data.op.name:\n                s[pad_data].compute_inline()\n        else:\n            if \"pad_temp\" in pad_data.op.name:\n                pack_data = pad_data.op.input_tensors[0]\n                bind_data_copy(s[pack_data])\n                s[pad_data].compute_inline()\n            else:\n                pack_data = pad_data\n                bind_data_copy(s[pack_data])\n\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n    elif \"pad_temp\" in pad_data.op.name:\n        s[pad_data].compute_inline()\n        # create cache stage\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n\n    if autotvm.GLOBAL_SCOPE.in_tuning or filter_pack_rt:\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            bind_data_copy(s[kernel])\n        WT = s.cache_read(kernel, get_texture_storage(kernel.shape), [conv])\n        bind_data_copy(s[WT])\n\n    s[conv].set_scope(\"local\")\n    if latest_blocked == latest and output != latest:\n        s[output].compute_inline()\n\n    # tile and bind spatial axes\n    n, fc, y, x, fb = s[latest_blocked].op.axis\n\n    kernel_scope, n = s[latest_blocked].split(n, nparts=1)\n\n    bf, vf, tf = cfg[\"tile_fc\"].apply(s, latest_blocked, fc)\n    by, vy, ty = cfg[\"tile_y\"].apply(s, latest_blocked, y)\n    bx, vx, tx = cfg[\"tile_x\"].apply(s, latest_blocked, x)\n\n    bf = s[latest_blocked].fuse(n, bf)\n    s[latest_blocked].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[latest_blocked].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[latest_blocked].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[latest_blocked].bind(vf, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vy, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vx, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[latest_blocked].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[latest_blocked].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[latest_blocked].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fb)\n    s[latest_blocked].vectorize(fb)\n\n    s[conv].compute_at(s[latest_blocked], tx)\n\n    # tile reduction axes\n    n, fc, y, x, fb = s[conv].op.axis\n\n    rcc, rcb, ry, rx = s[conv].op.reduce_axis\n    rco, rci = cfg[\"tile_rcc\"].apply(s, conv, rcc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(rco, ryo, rxo, rci, ryi, rxi, rcb, n, fc, y, x, fb)\n    s[conv].vectorize(fb)\n    s[conv].unroll(rcb)\n\n    # unroll\n    s[latest_blocked].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[latest_blocked].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    if latest_blocked != latest:\n        s[latest].compute_root()\n        bind_data_copy(s[latest], 1)\n        if latest != output:\n            s[output].compute_inline()\n\n    N, OCC, OH, OW, OCB = get_const_tuple(latest_blocked.shape)\n    _, IC, KH, KW, _ = get_const_tuple(kernel.shape)\n    ICKHKW = IC * KH * KW\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * ICKHKW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_nchw_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Winograd NCHW template for Adreno backend\"\"\"\n\nimport logging\nfrom tvm import autotvm\nfrom .conv2d_winograd_common import conv2d_winograd_comp, schedule_conv2d_winograd_impl\n\n\nlogger = logging.getLogger(\"conv2d_nchw_winograd\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd.image2d\")\ndef conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    return conv2d_nchw_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=False\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd.image2d\")\ndef schedule_conv2d_nchw_winograd(cfg, outs):\n    return schedule_conv2d_winograd_impl(cfg, outs, tag=\"dummy_compute_at\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd_without_weight_transform.image2d\")\ndef conv2d_nchw_winograd_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    return conv2d_nchw_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=True\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd_without_weight_transform.image2d\")\ndef schedule_conv2d_nchw_winograd_without_weight_transform(cfg, outs):\n    return schedule_conv2d_winograd_impl(cfg, outs, tag=\"dummy_compute_at\", pre_computed=True)\n\n\ndef conv2d_nchw_winograd_comp(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed\n):\n    \"\"\"Compute declaration for winograd\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data: tvm.te.Tensor\n        4-D or 5-D Data tensor with shape NCHW or NCHW4c\n\n    kernel: tvm.te.Tensor\n        4-D or 5-D tensor with shape OIHW or OIHW4o\n\n    strides: int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding: int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    pre_computed: bool\n        Flag if weights were pre computed if true or the weights should be\n        computed in runtime\n\n    Returns\n    -------\n    output: tvm.te.Tensor\n        4-D or 5-D with shape NCHW or NCHW4c\n    \"\"\"\n    return conv2d_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed, \"NCHW\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_nhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"conv2d nhwc schedule on Qualcomm Adreno GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .utils import (\n    split_to_chunks,\n    pack_input,\n    pack_filter,\n    expand_spatial_dimensions,\n    add_pad,\n    bind_data_copy,\n    get_texture_storage,\n    get_default_conv2d_config,\n)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc.image2d\")\ndef schedule_conv2d_nhwc(cfg, outs):\n    \"\"\"Create the schedule for conv2d_nhwc\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"adreno_conv2d_latest_op\":\n            schedule_conv2d_NHWC(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc.image2d\")\ndef conv2d_nhwc(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"\n    Convolution operator in NHWC layout.\n    Algo:\n      1. Convert into blocked format if we have 4d original tensor.\n         In case of AutoTVM we override the convert by just tensors since such conversion\n         will be absent for real blocked convolution, no sense to include into tuning\n      2. Expand spatial dimensions to have width and height be dividable by factor 4\n         This leads to slightly bigger amount of compute but allow utilize GPU much better\n      3. Add paddings. This happens even if we do not need pad originaly. This is useful\n         due to work arounding of the gaps of texture annotation between Primary Functions\n         and limited support of textures in schedules. Later on this pad will be executed\n         separately and will produce texture\n      4. 5d Convolution compute with accumulating into out_dtype\n      5. Cast to the origin output data type\n      6. For case of 4d convolution: convert of output from 5d to 4d\n    \"\"\"\n\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    convert_from4d = False\n    if len(Input.shape) == 4:\n        batch, in_height, in_width, in_channels = Input.shape\n        in_channel_chunks, in_channel_block, in_channel_tail = split_to_chunks(in_channels, 4)\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            dshape = (batch, in_height, in_width, in_channel_chunks, in_channel_block)\n            Input = tvm.te.placeholder(dshape, Input.dtype, name=\"data_placeholder\")\n        else:\n            Input = pack_input(\n                Input,\n                \"NHWC\",\n                batch,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                in_height,\n                in_width,\n            )\n    else:\n        batch, in_height, in_width, in_channel_chunks, in_channel_block = Input.shape\n\n    if len(Filter.shape) == 4:\n        kernel_h, kernel_w, in_filter_channels, out_channles = Filter.shape\n        out_channel_chunks, out_channel_block, out_channel_tail = split_to_chunks(out_channles, 4)\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            kshape = (kernel_h, kernel_w, in_filter_channels, out_channel_chunks, out_channel_block)\n            Filter = tvm.te.placeholder(kshape, Filter.dtype, name=\"kernel_placeholder\")\n        else:\n            convert_from4d = True\n            Filter = pack_filter(\n                Filter,\n                \"HWIO\",\n                out_channel_chunks,\n                out_channel_block,\n                out_channel_tail,\n                in_filter_channels,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                kernel_h,\n                kernel_w,\n            )\n    else:\n        kernel_h, kernel_w, in_filter_channels, out_channel_chunks, out_channel_block = Filter.shape\n\n    out_height_orig, out_height, out_width_orig, out_width = expand_spatial_dimensions(\n        in_height, in_width, kernel_h, kernel_w, dilation_h, dilation_w, padding, stride_h, stride_w\n    )\n\n    temp = add_pad(\n        Input,\n        \"NHWC\",\n        out_height_orig,\n        out_width_orig,\n        kernel_h,\n        kernel_w,\n        dilation_h,\n        dilation_w,\n        padding,\n        stride_h,\n        stride_w,\n    )\n\n    rcc = te.reduce_axis((0, in_channel_chunks), name=\"rcc\")\n    rcb = te.reduce_axis((0, in_channel_block), name=\"rcb\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    conv = te.compute(\n        (batch, out_height, out_width, out_channel_chunks, out_channel_block),\n        lambda nn, yy, xx, fc, fb: te.sum(\n            (\n                temp[nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rcc, rcb]\n                * Filter[ry, rx, rcc * in_channel_block + rcb, fc, fb]\n            ).astype(out_dtype),\n            axis=[ry, rx, rcc, rcb],\n        ),\n        tag=\"conv2d_nhwc\",\n    )\n\n    if convert_from4d and not autotvm.GLOBAL_SCOPE.in_tuning:\n        dummy_cast = te.compute(\n            (batch, out_height_orig, out_width_orig, out_channel_chunks, out_channel_block),\n            lambda n, y, x, fc, fb: conv[n, y, x, fc, fb].astype(out_dtype),\n            tag=\"dummy_cast\",\n        )\n        return te.compute(\n            (batch, out_height_orig, out_width_orig, out_channles),\n            lambda n, y, x, c: dummy_cast[n, y, x, c // out_channel_block, c % out_channel_block],\n            tag=\"adreno_conv2d_latest_op\",\n        )\n    else:\n        return te.compute(\n            (batch, out_height_orig, out_width_orig, out_channel_chunks, out_channel_block),\n            lambda n, y, x, ffc, ffb: conv[n, y, x, ffc, ffb].astype(out_dtype),\n            tag=\"adreno_conv2d_latest_op\",\n        )\n\n\ndef schedule_conv2d_NHWC(cfg, s, output):\n    \"\"\"\n    schedule optimized for batch size = 1\n\n    Algo:\n    1. Split output axis to three parts: global work size, vthread, local worksize.\n       The limitations for tuning includes heuristics from some tuned networks to limit\n       search space and not pay much time for useles configurations.\n    2. In case of 4d convolution schedule copying of the input (and filter) into\n      5d tensors\n    4. pad should be scheduled separately to create independent opencl kernel. If pad is\n       inlined into convolution, this gives 1.5x performance drop\n    5. We are using cache_read for intermediate tensors to produce texture and guarantee\n       the best performance on the next stage.\n       The weights are managed through static texture planning mechanism and guarantied come\n       in texture memory scope.\n       Thus way we are calling cache_read only for data tensor\n    6. For 5d convolution we schedule the latest op with binding 5d axis and vectorize\n       for textures\n       For 4d tensor we are doing the same for the latest blocked stage, i.e. conversion\n       of data type\n    7. In case of 4d conv we need to schedule postops as well\n    \"\"\"\n    latest = s.outputs[0].output(0)\n    if len(latest.op.axis) == 4:\n        latest_blocked = dummy = output.op.input_tensors[0]\n        conv = dummy.op.input_tensors[0]\n    else:\n        conv = output.op.input_tensors[0]\n        latest_blocked = latest\n\n    pad_data, kernel = s[conv].op.input_tensors\n    filter_pack_rt = bool(\n        isinstance(kernel.op, tvm.te.ComputeOp) and \"filter_pack\" in kernel.op.tag\n    )\n\n    if \"pad_temp\" in pad_data.op.name:\n        input_pad_temp = pad_data.op.input_tensors[0]\n    else:\n        input_pad_temp = pad_data\n\n    input_pack_rt = bool(\n        isinstance(input_pad_temp.op, tvm.te.ComputeOp) and \"input_pack\" in input_pad_temp.op.tag\n    )\n    ##### space definition begin #####\n    n, y, x, fc, fb = s[conv].op.axis\n    ry, rx, rcc, rcb = s[conv].op.reduce_axis\n\n    if conv.shape[3] % 2 == 0:\n        min_threads_div = 2\n    else:\n        min_threads_div = 1\n\n    cfg.define_split(\n        \"tile_fc\",\n        fc,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8\n        and entity.size[2] >= min_threads_div\n        and entity.size[2] < 256,\n    )\n    cfg.define_split(\n        \"tile_y\",\n        y,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8 and entity.size[2] <= 16,\n    )\n    cfg.define_split(\n        \"tile_x\",\n        x,\n        num_outputs=3,\n        filter=lambda entity: entity.size[1] <= 8 and entity.size[2] <= 16,\n    )\n\n    cfg.define_split(\"tile_rcc\", rcc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n    cfg.multi_filter(\n        filter=lambda entity: (  # pylint: disable=chained-comparison\n            entity[\"tile_fc\"].size[1] * entity[\"tile_y\"].size[1] * entity[\"tile_x\"].size[1]\n        )\n        <= 24\n        and 32\n        <= (entity[\"tile_fc\"].size[2] * entity[\"tile_y\"].size[2] * entity[\"tile_x\"].size[2])\n        < 1024\n    )\n    if cfg.is_fallback:\n        get_default_conv2d_config(cfg, conv.shape[3], conv.shape[1], conv.shape[2])\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n    # There are several conditions that have to be handled:\n    # 1. If we are in the tuning, we always add cache read for data to main conv kernel\n    #    to get texture in tuning opencl kernel\n    # 2. If we are repacking input in runtime, we should always explicit schedule this one more\n    #    stage of data copy from 4d to 5d (referred as pack_data).\n    # 3. If we have pad (independently if we have runtime repack or not) we should inline it in the\n    #    cache_read(\"texture\")\n    if autotvm.GLOBAL_SCOPE.in_tuning or input_pack_rt:\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            if \"pad_temp\" in pad_data.op.name:\n                s[pad_data].compute_inline()\n        else:\n            if \"pad_temp\" in pad_data.op.name:\n                s[pad_data].compute_inline()\n                pack_data = pad_data.op.input_tensors[0]\n                bind_data_copy(s[pack_data])\n            else:\n                pack_data = pad_data\n                bind_data_copy(s[pack_data])\n\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n    elif \"pad_temp\" in pad_data.op.name:\n        s[pad_data].compute_inline()\n        # create cache stage\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n\n    if autotvm.GLOBAL_SCOPE.in_tuning or filter_pack_rt:\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            bind_data_copy(s[kernel])\n        WT = s.cache_read(kernel, get_texture_storage(kernel.shape), [conv])\n        bind_data_copy(s[WT])\n\n    s[conv].set_scope(\"local\")\n    if latest_blocked == latest and output != latest:\n        s[output].compute_inline()\n\n    # tile and bind spatial axes\n    n, y, x, fc, fb = s[latest_blocked].op.axis\n\n    kernel_scope, n = s[latest_blocked].split(n, nparts=1)\n\n    bf, vf, tf = cfg[\"tile_fc\"].apply(s, latest_blocked, fc)\n    by, vy, ty = cfg[\"tile_y\"].apply(s, latest_blocked, y)\n    bx, vx, tx = cfg[\"tile_x\"].apply(s, latest_blocked, x)\n\n    by = s[latest_blocked].fuse(n, by)\n    s[latest_blocked].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[latest_blocked].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[latest_blocked].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[latest_blocked].bind(vf, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vy, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vx, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[latest_blocked].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[latest_blocked].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[latest_blocked].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fb)\n    s[latest_blocked].vectorize(fb)\n\n    s[conv].compute_at(s[latest_blocked], tx)\n\n    # tile reduction axes\n    n, y, x, fc, fb = s[conv].op.axis\n\n    ry, rx, rcc, rcb = s[conv].op.reduce_axis\n    rco, rci = cfg[\"tile_rcc\"].apply(s, conv, rcc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(rco, ryo, rxo, rci, ryi, rxi, rcb, n, fc, y, x, fb)\n    s[conv].vectorize(fb)\n    s[conv].unroll(rcb)\n\n    # unroll\n    s[latest_blocked].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[latest_blocked].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    if latest_blocked != latest:\n        s[latest].compute_root()\n        bind_data_copy(s[latest], 1)\n        if latest != output:\n            s[output].compute_inline()\n\n    N, OH, OW, OCC, OCB = get_const_tuple(latest_blocked.shape)\n    KH, KW, IC, _, _ = get_const_tuple(kernel.shape)\n    ICKHKW = IC * KH * KW\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * ICKHKW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_nhwc_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Winograd NHWC template for Adreno backend\"\"\"\n\nimport logging\nfrom tvm import autotvm\nfrom .conv2d_winograd_common import conv2d_winograd_comp, schedule_conv2d_winograd_impl\n\n\nlogger = logging.getLogger(\"conv2d_nhwc_winograd\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd.image2d\")\ndef conv2d_nhwc_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    return conv2d_nhwc_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=False\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd.image2d\")\ndef schedule_conv2d_nhwc_winograd(cfg, outs):\n    return schedule_conv2d_winograd_impl(cfg, outs, tag=\"dummy_compute_at\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd_without_weight_transform.image2d\")\ndef conv2d_nhwc_winograd_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    return conv2d_nhwc_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=True\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd_without_weight_transform.image2d\")\ndef schedule_conv2d_nhwc_winograd_without_weight_transform(cfg, outs):\n    return schedule_conv2d_winograd_impl(cfg, outs, tag=\"dummy_compute_at\", pre_computed=True)\n\n\ndef conv2d_nhwc_winograd_comp(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed\n):\n    \"\"\"Compute declaration for winograd\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data: tvm.te.Tensor\n        4-D or 5-D Data tensor with shape NCHW or NCHW4c\n\n    kernel: tvm.te.Tensor\n        4-D or 5-D tensor with shape OIHW or OIHW4o\n\n    strides: int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding: int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    pre_computed: bool\n        Flag if weights were pre computed if true or the weights should be\n        computed in runtime\n\n    Returns\n    -------\n    output: tvm.te.Tensor\n        4-D or 5-D with shape NCHW or NCHW4c\n    \"\"\"\n    return conv2d_winograd_comp(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed, \"NHWC\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/conv2d_winograd_common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Common Winograd implementation for Adreno backend\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom tvm.topi import nn\nfrom tvm.topi.utils import get_const_int, get_const_tuple, traverse_inline\nfrom ..nn.winograd_util import winograd_transform_matrices\nfrom .utils import (\n    split_to_chunks,\n    pack_input,\n    pack_filter,\n    bind_data_copy,\n    get_texture_storage,\n    infer_tile_size,\n)\n\n\ndef conv2d_winograd_comp(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed, layout\n):\n    \"\"\"Compute declaration for winograd\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data: tvm.te.Tensor\n        4-D or 5-D Data tensor with shape NCHW or NCHW4c\n\n    kernel: tvm.te.Tensor\n        4-D or 5-D tensor with shape OIHW or OIHW4o\n\n    strides: int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding: int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    pre_computed: bool\n        Flag if weights were pre computed if true or the weights should be\n        computed in runtime\n\n    layout: str\n        NHWC or NCHW values are accepted\n\n    Returns\n    -------\n    output: tvm.te.Tensor\n        4-D or 5-D with shape NCHW or NCHW4c\n    \"\"\"\n    assert layout in (\"NCHW\", \"NHWC\")\n    tile_size = infer_tile_size(data, layout)\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides\n\n    convert_from4d = False\n    if len(data.shape) == 4:\n        convert_from4d = True\n        if layout == \"NCHW\":\n            N, DCI, H, W = get_const_tuple(data.shape)\n        else:\n            N, H, W, DCI = get_const_tuple(data.shape)\n        if not pre_computed:\n            if layout == \"NCHW\":\n                out_channels, CI, KH, KW = get_const_tuple(kernel.shape)\n            else:\n                KH, KW, CI, out_channels = get_const_tuple(kernel.shape)\n        else:\n            alpha, _, CI, out_channels = get_const_tuple(kernel.shape)\n            KH = KW = alpha + 1 - tile_size\n\n        in_channel_chunks, in_channel_block, in_channel_tail = split_to_chunks(CI, 4)\n        out_channel_chunks, out_channel_block, out_channel_tail = split_to_chunks(out_channels, 4)\n        if autotvm.GLOBAL_SCOPE.in_tuning is True:\n            if layout == \"NCHW\":\n                dshape = (N, in_channel_chunks, H, W, in_channel_block)\n            else:\n                dshape = (N, H, W, in_channel_chunks, in_channel_block)\n            if not pre_computed:  # kernel tensor is raw tensor, do strict check\n                if layout == \"NCHW\":\n                    kshape = (out_channel_chunks, CI, KH, KW, out_channel_block)\n                else:\n                    kshape = (KH, KW, CI, out_channel_chunks, out_channel_block)\n            else:\n                kshape = (alpha, alpha, CI, out_channel_chunks, out_channel_block)\n            data = tvm.te.placeholder(dshape, data.dtype, name=\"data_placeholder\")\n            kernel = tvm.te.placeholder(kshape, kernel.dtype, name=\"kernel_placeholder\")\n        else:\n            data = pack_input(\n                data, layout, N, in_channel_chunks, in_channel_block, in_channel_tail, H, W\n            )\n            kernel_layout = \"OIHW\" if layout == \"NCHW\" else \"HWIO\"\n            if not pre_computed:  # kernel tensor is raw tensor, do strict check\n                kernel = pack_filter(\n                    kernel,\n                    kernel_layout,\n                    out_channel_chunks,\n                    out_channel_block,\n                    out_channel_tail,\n                    CI,\n                    in_channel_chunks,\n                    in_channel_block,\n                    in_channel_tail,\n                    KH,\n                    KW,\n                )\n            else:\n                kernel = pack_filter(\n                    kernel,\n                    \"HWIO\",\n                    out_channel_chunks,\n                    out_channel_block,\n                    out_channel_tail,\n                    CI,\n                    in_channel_chunks,\n                    in_channel_block,\n                    in_channel_tail,\n                    alpha,\n                    alpha,\n                )\n    if layout == \"NCHW\":\n        N, DCI, H, W, CB = get_const_tuple(data.shape)\n    else:\n        N, H, W, DCI, CB = get_const_tuple(data.shape)\n    if not pre_computed:  # kernel tensor is raw tensor, do strict check\n        if layout == \"NCHW\":\n            CO, CI, KH, KW, COB = get_const_tuple(kernel.shape)\n        else:\n            KH, KW, CI, CO, COB = get_const_tuple(kernel.shape)\n        alpha = KW + tile_size - 1\n        assert HSTR == 1 and WSTR == 1 and KH == KW\n    else:\n        alpha, _, CI, CO, COB = get_const_tuple(kernel.shape)\n        KH = KW = alpha + 1 - tile_size\n        assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1\n\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n\n    if not isinstance(H, int) or not isinstance(W, int):\n        raise RuntimeError(\n            \"adreno winograd conv2d doesn't support dynamic input\\\n                           height or width.\"\n        )\n\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW))\n    if layout == \"NCHW\":\n        data_pad = nn.pad(data, (0, 0, pt, pl, 0), (0, 0, pb, pr, 0), name=\"data_pad\")\n    else:\n        data_pad = nn.pad(data, (0, pt, pl, 0, 0), (0, pb, pr, 0, 0), name=\"data_pad\")\n\n    r = KW\n    m = tile_size\n    A, B, G = winograd_transform_matrices(m, r, data.dtype)\n\n    H = (H + pt + pb - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n\n    P = N * nH * nW if isinstance(N, int) else nH * nW\n\n    # transform kernel\n    if not pre_computed:\n        r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n        r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n        if layout == \"NCHW\":\n            kernel_pack = te.compute(\n                (alpha, alpha, CI, CO, COB),\n                lambda eps, nu, ci, co, cob: te.sum(\n                    kernel[co][ci][r_kh][r_kw][cob] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n                ),\n                name=\"kernel_pack\",\n            )\n        else:\n            kernel_pack = te.compute(\n                (alpha, alpha, CI, CO, COB),\n                lambda eps, nu, ci, co, cob: te.sum(\n                    kernel[r_kh][r_kw][ci][co][cob] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n                ),\n                name=\"kernel_pack\",\n            )\n    else:\n        kernel_pack = kernel\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    if layout == \"NCHW\":\n        N, CI, _, _, CB = get_const_tuple(data.shape)\n    else:\n        N, _, _, CI, CB = get_const_tuple(data.shape)\n\n    # pack input tile\n    if layout == \"NCHW\":\n        input_tile = te.compute(\n            (alpha, alpha, CI, P, CB),\n            lambda eps, nu, c, p, cb: data_pad[idxdiv(p, (nH * nW))][c][\n                idxmod(idxdiv(p, nW), nH) * m + eps\n            ][idxmod(p, nW) * m + nu][cb],\n            name=\"d\",\n        )\n    else:\n        input_tile = te.compute(\n            (alpha, alpha, CI, P, CB),\n            lambda eps, nu, c, p, cb: data_pad[idxdiv(p, (nH * nW))][\n                idxmod(idxdiv(p, nW), nH) * m + eps\n            ][idxmod(p, nW) * m + nu][c][cb],\n            name=\"d\",\n        )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_a\")\n    data_pack = te.compute(\n        (P, CI, alpha, alpha, CB),\n        lambda p, ci, eps, nu, cb: te.sum(\n            input_tile[r_a][r_b][ci][p][cb] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"data_pack\",\n    )\n\n    # repack transformed data\n    data_pack_trans = te.compute(\n        (alpha, alpha, CI, P, CB),\n        lambda eps, nu, c, p, cb: data_pack[p][c][eps][nu][cb],\n        name=\"data_pack_trans\",\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    cb = te.reduce_axis((0, CB), name=\"cb\")\n    bgemm = te.compute(\n        (alpha, alpha, CO, P, COB),\n        lambda eps, nu, co, p, cob: te.sum(\n            (\n                kernel_pack[eps][nu][ci * CB + cb][co][cob] * data_pack_trans[eps][nu][ci][p][cb]\n            ).astype(out_dtype),\n            axis=[ci, cb],\n        ),\n        name=\"bgemm\",\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_a\")\n    inverse = te.compute(\n        (CO, P, m, m, COB),\n        lambda co, p, vh, vw, cob: te.sum(\n            bgemm[r_a][r_b][co][p][cob] * (A[r_a][vh] * A[r_b][vw]).astype(out_dtype),\n            axis=[r_a, r_b],\n        ),\n        name=\"inverse\",\n    )\n\n    # output\n    if layout == \"NCHW\":\n        if convert_from4d and autotvm.GLOBAL_SCOPE.in_tuning is False:\n            output = te.compute(\n                (N, out_channels, H, W),\n                lambda n, c, h, w: inverse[c // CB][n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m)][\n                    idxmod(h, m)\n                ][idxmod(w, m)][c % CB].astype(out_dtype),\n                name=\"output\",\n                tag=\"dummy_compute_at\",\n            )\n        else:\n            output = te.compute(\n                (N, CO, H, W, COB),\n                lambda n, co, h, w, cob: inverse[co][\n                    n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m)\n                ][idxmod(h, m)][idxmod(w, m)][cob].astype(out_dtype),\n                name=\"output\",\n                tag=\"dummy_compute_at\",\n            )\n    else:\n        if convert_from4d and autotvm.GLOBAL_SCOPE.in_tuning is False:\n            output = te.compute(\n                (N, H, W, out_channels),\n                lambda n, h, w, c: inverse[c // CB][n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m)][\n                    idxmod(h, m)\n                ][idxmod(w, m)][c % CB].astype(out_dtype),\n                name=\"output\",\n                tag=\"dummy_compute_at\",\n            )\n        else:\n            output = te.compute(\n                (N, H, W, CO, COB),\n                lambda n, h, w, co, cob: inverse[co][\n                    n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m)\n                ][idxmod(h, m)][idxmod(w, m)][cob].astype(out_dtype),\n                name=\"output\",\n                tag=\"dummy_compute_at\",\n            )\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * CO * COB * H * W * CI * CB * KH * KW)\n\n    return output\n\n\ndef schedule_conv2d_winograd_impl(cfg, outs, tag, pre_computed=False):\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == tag:\n            schedule_conv2d_winograd(cfg, s, op.output(0), pre_computed=pre_computed)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef schedule_conv2d_winograd(cfg, s, output, pre_computed):\n    \"\"\"Schedule winograd template\"\"\"\n    inverse = s[output].op.input_tensors[0]\n    bgemm, A = s[inverse].op.input_tensors\n    kernel_pack, data_pack_trans = s[bgemm].op.input_tensors\n    data_pack = s[data_pack_trans].op.input_tensors[0]\n    input_tile, B = s[data_pack].op.input_tensors\n    pad_data = s[input_tile].op.input_tensors[0]\n\n    # data transform\n    s[B].compute_inline()\n    s[A].compute_inline()\n\n    # probably will improve real topology execution\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # Padding to texture\n        AA = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [input_tile])\n        bind_data_copy(s[AA])\n\n    s[input_tile].compute_inline()\n\n    OL = s.cache_write(data_pack, \"local\")\n    c, p, eps, nu, cb = s[data_pack].op.axis\n    fused = s[data_pack].fuse(c, p, eps, nu)\n    bx, tx = s[data_pack].split(fused, 128)\n    s[data_pack].vectorize(cb)\n    s[data_pack].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[data_pack].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    _, _, eps, nu, cb = s[OL].op.axis\n    r_a, r_b = s[OL].op.reduce_axis\n    s[OL].unroll(eps)\n    s[OL].unroll(nu)\n    s[OL].unroll(r_a)\n    s[OL].unroll(r_b)\n    s[OL].vectorize(cb)\n    s[OL].compute_at(s[data_pack], tx)\n    s[data_pack].set_scope(get_texture_storage(data_pack.shape))\n\n    s[data_pack_trans].compute_inline()\n\n    # transform kernel\n    if not pre_computed:\n        kernel, G = s[kernel_pack].op.input_tensors\n        eps, nu, ci, co, cob = s[kernel_pack].op.axis\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # skip this part during tuning to make recrods accurate\n            # this part will be pre-computed during pre-compute optimization pass\n            s[G].pragma(s[G].op.axis[0], \"debug_skip_region\")\n            s[kernel_pack].pragma(eps, \"debug_skip_region\")\n        else:\n            s[G].compute_inline()\n            r_a, r_b = s[kernel_pack].op.reduce_axis\n            for axis in [eps, nu, r_a, r_b]:\n                s[kernel_pack].unroll(axis)\n\n            fused = s[kernel_pack].fuse(ci, co)\n            bb, tt = s[kernel_pack].split(fused, 128)\n            s[kernel_pack].reorder(bb, tt, eps, nu, r_a, r_b, cob)\n            s[kernel_pack].vectorize(cob)\n            s[kernel_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n            s[kernel_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n    else:\n        kernel = kernel_pack\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"filter_pack\" in kernel.op.tag:\n        # manage scheduling of datacopy\n        pack_data = pad_data.op.input_tensors[0]\n        bind_data_copy(s[pack_data])\n        bind_data_copy(s[kernel])\n    elif isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n    s[pad_data].compute_inline()\n\n    ##### space definition begin #####\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 4, 16])\n    b1, b2, y, x, cb = s[bgemm].op.axis\n    rcc = s[bgemm].op.reduce_axis[0]\n    alpha = get_const_int(b1.dom.extent)\n\n    cfg.define_split(\n        \"tile_y\", y, num_outputs=3, filter=lambda entry: entry.size[2] <= 64 and entry.size[1] <= 16\n    )\n\n    min_x_div = 1\n    for bn in range(4, 0, -1):\n        if bgemm.shape[3] % bn == 0:\n            min_x_div = bn\n            break\n\n    cfg.define_split(\n        \"tile_x\",\n        x,\n        num_outputs=3,\n        filter=lambda entry: entry.size[2] <= 64\n        and entry.size[1] >= min_x_div\n        and entry.size[1] <= 16,\n    )\n    cfg.define_split(\"tile_rc\", rcc, num_outputs=2)\n    cfg.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_y\"].size[2] * entity[\"tile_x\"].size[2]) < 1024\n    )\n    ##### space definition end #####\n\n    # batch gemm\n    OL = s.cache_write(bgemm, \"local\")\n    if (\n        autotvm.GLOBAL_SCOPE.in_tuning\n        or isinstance(kernel.op, tvm.te.ComputeOp)\n        and \"filter_pack\" in kernel.op.tag\n    ):\n        BB = s.cache_read(kernel_pack, get_texture_storage(kernel_pack.shape), [OL])\n        bind_data_copy(s[BB])\n\n    by = s[bgemm].fuse(b1, b2, y)\n\n    # tile and bind spatial axes\n    bgemm_scope, by = s[bgemm].split(by, nparts=1)\n    by, vy, ty = cfg[\"tile_y\"].apply(s, bgemm, by)\n    bx, vx, tx = cfg[\"tile_x\"].apply(s, bgemm, x)\n    s[bgemm].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[bgemm].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[bgemm].bind(vy, te.thread_axis(\"vthread\"))\n    s[bgemm].bind(vx, te.thread_axis(\"vthread\"))\n    s[bgemm].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[bgemm].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[bgemm].reorder(bgemm_scope, by, bx, vy, vx, ty, tx, cb)\n    s[bgemm].vectorize(cb)\n    s[bgemm].set_scope(get_texture_storage(bgemm.shape))\n\n    # tile reduction axes\n    s[OL].compute_at(s[bgemm], tx)\n    b1, b2, y, x, cb = s[OL].op.axis\n    (rcc, rcb) = s[OL].op.reduce_axis\n    b = s[OL].fuse(b1, b2)\n    s[OL].reorder(b, y, x, rcc, rcb, cb)\n    # s[OL].unroll(rcb)\n    s[OL].pragma(rcb, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[OL].pragma(rcb, \"unroll_explicit\", True)\n    s[OL].vectorize(cb)\n\n    # schedule inverse, output and fusion\n    if output.op in s.outputs:\n        OL = None\n    else:\n        OL = output\n        s[OL].set_scope(\"local\")\n        output = s.outputs[0]\n\n    if len(s[output].op.axis) == 4:\n        n, co, h, w = s[output].op.axis\n        cb = None\n    else:\n        n, co, h, w, cb = s[output].op.axis\n    inverse_scope, n = s[output].split(n, nparts=1)\n\n    fused = s[output].fuse(n, co, h, w)\n    bb, tt = s[output].split(fused, 128)\n    if cb is not None:\n        s[output].reorder(bb, tt, cb)\n        s[output].vectorize(cb)\n\n    s[output].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    if OL is not None:\n        s[OL].compute_at(s[output], tt)\n\n    co, p, vh, vw, cb = s[inverse].op.axis\n    r_a, r_b = s[inverse].op.reduce_axis\n    for axis in [vh, vw, r_a, r_b]:\n        s[inverse].unroll(axis)\n    s[inverse].vectorize(cb)\n    s[inverse].compute_at(s[output], tt)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/depthwise_conv2d_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"depthwise_conv2d_nchw(c) schedule on Qualcomm Adreno GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .utils import (\n    split_to_chunks,\n    pack_input,\n    pack_filter,\n    expand_spatial_dimensions,\n    add_pad,\n    bind_data_copy,\n    get_texture_storage,\n    get_default_conv2d_config,\n)\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchwc.image2d\")\ndef schedule_depthwise_conv2d_nchwc(cfg, outs):\n    \"\"\"Create the schedule for depthwise conv2d_nchw4c_ohwi4o\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"adreno_dw_conv2d_latest_op\":\n            schedule_depthwise_conv2d_NCHWc_KCRSk(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchwc.image2d\")\ndef depthwise_conv2d_nchwc(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"\n    Depthwise convolution operator in NCHWc layout.\n    Algo:\n      1. Convert into blocked format if we have 4d original tensor.\n         In case of AutoTVM we override the convert by just tensors since such conversion\n         will be absent for real blocked convolution, no sense to include into tuning\n      2. Expand spatial dimensions to have width and height be dividable by factor 4\n         This leads to slightly bigger amount of compute but allow utilize GPU much better\n      3. Add paddings. This happens even if we do not need pad originaly. This is useful\n         due to work arounding of the gaps of texture annotation between Primary Functions\n         and limited support of textures in schedules. Later on this pad will be executed\n         separately and will produce texture\n      4. 5d Convolution compute with accumulating into out_dtype\n      5. Cast to the origin output data type\n      6. For case of 4d convolution: convert of output from 5d to 4d\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    convert_from4d = False\n    if len(Input.shape) == 4:\n        batch, in_channels, in_height, in_width = Input.shape\n        out_channles, in_filter_channels, kernel_h, kernel_w = Filter.shape\n\n        in_channel_chunks, in_channel_block, in_channel_tail = split_to_chunks(in_channels, 4)\n        out_channel_chunks, out_channel_block, out_channel_tail = split_to_chunks(out_channles, 4)\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            dshape = (batch, in_channel_chunks, in_height, in_width, in_channel_block)\n            Input = tvm.te.placeholder(dshape, Input.dtype, name=\"data_placeholder\")\n            kshape = (out_channel_chunks, in_filter_channels, kernel_h, kernel_w, out_channel_block)\n            Filter = tvm.te.placeholder(kshape, Filter.dtype, name=\"kernel_placeholder\")\n        else:\n            convert_from4d = True\n            Input = pack_input(\n                Input,\n                \"NCHW\",\n                batch,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                in_height,\n                in_width,\n            )\n            Filter = pack_filter(\n                Filter,\n                \"OIHW\",\n                out_channel_chunks,\n                out_channel_block,\n                out_channel_tail,\n                in_filter_channels,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                kernel_h,\n                kernel_w,\n            )\n\n    else:\n        batch, in_channel_chunks, in_height, in_width, in_channel_block = Input.shape\n        out_channel_chunks, in_filter_channels, kernel_h, kernel_w, out_channel_block = Filter.shape\n\n    out_height_orig, out_height, out_width_orig, out_width = expand_spatial_dimensions(\n        in_height, in_width, kernel_h, kernel_w, dilation_h, dilation_w, padding, stride_h, stride_w\n    )\n\n    temp = add_pad(\n        Input,\n        \"NCHW\",\n        out_height_orig,\n        out_width_orig,\n        kernel_h,\n        kernel_w,\n        dilation_h,\n        dilation_w,\n        padding,\n        stride_h,\n        stride_w,\n    )\n\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    conv = te.compute(\n        (batch, out_channel_chunks, out_height, out_width, out_channel_block),\n        lambda nn, ffc, yy, xx, ffb: te.sum(\n            (\n                temp[\n                    nn,\n                    ffc // in_filter_channels,\n                    yy * stride_h + ry * dilation_h,\n                    xx * stride_w + rx * dilation_w,\n                    ffb,\n                ]\n                * Filter[ffc // in_filter_channels, ffc % in_filter_channels, ry, rx, ffb]\n            ).astype(out_dtype),\n            axis=[ry, rx],\n        ),\n        tag=\"depthwise_conv2d_nchwc\",\n    )\n\n    if convert_from4d and not autotvm.GLOBAL_SCOPE.in_tuning:\n        dummy_cast = te.compute(\n            (batch, out_channel_chunks, out_height_orig, out_width_orig, out_channel_block),\n            lambda n, fc, y, x, fb: conv[n, fc, y, x, fb].astype(out_dtype),\n            tag=\"dummy_cast\",\n        )\n        return te.compute(\n            (batch, out_channles, out_height_orig, out_width_orig),\n            lambda n, c, y, x: dummy_cast[n, c // out_channel_block, y, x, c % out_channel_block],\n            tag=\"adreno_dw_conv2d_latest_op\",\n        )\n    else:\n        return te.compute(\n            (batch, out_channel_chunks, out_height_orig, out_width_orig, out_channel_block),\n            lambda n, ffc, y, x, ffb: conv[n, ffc, y, x, ffb].astype(out_dtype),\n            tag=\"adreno_dw_conv2d_latest_op\",\n        )\n\n\ndef schedule_depthwise_conv2d_NCHWc_KCRSk(cfg, s, output):\n    \"\"\"\n    schedule optimized for batch size = 1\n\n    Algo:\n    1. Split output axis to three parts: global work size, vthread, local worksize.\n       The limitations for tuning includes heuristics from some tuned networks to limit\n       search space and not pay much time for useles configurations.\n    2. For depthwise convolution it's better to inline pad into the conv2d compute, the\n       divergence in opencl kernel will not so significant as for regular conv2d.\n    3. For 5d convolution we schedule the latest op with binding 5d axis and vectorize\n       for textures\n       For 4d tensor we are doing the same for the latest blocked stage, i.e. conversion\n       of data type\n    4. In case of 4d conv we need to schedule postops as well\n    \"\"\"\n    latest = s.outputs[0].output(0)\n    if len(latest.op.axis) == 4:\n        latest_blocked = dummy = output.op.input_tensors[0]\n        conv = dummy.op.input_tensors[0]\n    else:\n        conv = output.op.input_tensors[0]\n        latest_blocked = latest\n\n    ##### space definition begin #####\n    n, fc, y, x, fb = s[conv].op.axis\n    ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_fc\", fc, num_outputs=3)\n    cfg.define_split(\"tile_y\", y, num_outputs=3)\n    cfg.define_split(\"tile_x\", x, num_outputs=3)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n    cfg.multi_filter(\n        filter=lambda entity: (  # pylint: disable=chained-comparison\n            entity[\"tile_fc\"].size[1] * entity[\"tile_y\"].size[1] * entity[\"tile_x\"].size[1]\n        )\n        <= 32\n        and 32\n        <= (entity[\"tile_fc\"].size[2] * entity[\"tile_y\"].size[2] * entity[\"tile_x\"].size[2])\n        < 1024\n    )\n\n    if cfg.is_fallback:\n        get_default_conv2d_config(cfg, conv.shape[1], conv.shape[2], conv.shape[3])\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n    if (\n        isinstance(kernel.op, tvm.te.ComputeOp) and \"filter_pack\" in kernel.op.tag\n    ):  # len(latest.op.axis) == 4:\n        # manage scheduling of datacopy\n        pad_data, kernel = s[conv].op.input_tensors\n        if \"pad_temp\" in pad_data.op.name:\n            pack_data = pad_data.op.input_tensors[0]\n            bind_data_copy(s[pack_data])\n        else:\n            bind_data_copy(s[pad_data])\n        bind_data_copy(s[kernel])\n\n    pad_data, kernel = s[conv].op.input_tensors\n\n    if \"pad_temp\" in pad_data.op.name:\n        s[pad_data].compute_inline()\n\n    s[conv].set_scope(\"local\")\n    if latest_blocked == latest and output != latest:\n        s[output].compute_inline()\n\n    if autotvm.GLOBAL_SCOPE.in_tuning or len(latest.op.axis) == 4:\n        # create cache stage for tuning only or in case of 4d case\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n        WT = s.cache_read(kernel, get_texture_storage(kernel.shape), [conv])\n        bind_data_copy(s[WT])\n\n    # tile and bind spatial axes\n    n, fc, y, x, fb = s[latest_blocked].op.axis\n    kernel_scope, n = s[latest_blocked].split(n, nparts=1)\n\n    bf, vf, tf = cfg[\"tile_fc\"].apply(s, latest_blocked, fc)\n    by, vy, ty = cfg[\"tile_y\"].apply(s, latest_blocked, y)\n    bx, vx, tx = cfg[\"tile_x\"].apply(s, latest_blocked, x)\n\n    bf = s[latest_blocked].fuse(n, bf)\n    s[latest_blocked].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[latest_blocked].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[latest_blocked].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[latest_blocked].bind(vf, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vy, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vx, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[latest_blocked].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[latest_blocked].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[latest_blocked].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fb)\n    s[latest_blocked].vectorize(fb)\n\n    s[conv].compute_at(s[latest_blocked], tx)\n\n    # tile reduction axes\n    n, fc, y, x, fb = s[conv].op.axis\n\n    ry, rx = s[conv].op.reduce_axis\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(ryo, rxo, ryi, rxi, n, fc, y, x, fb)\n    s[conv].vectorize(fb)\n\n    # unroll\n    s[latest_blocked].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[latest_blocked].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n    if latest_blocked != latest:\n        s[latest].compute_root()\n        bind_data_copy(s[latest], 1)\n        if latest != output:\n            s[output].compute_inline()\n\n    N, OCC, OH, OW, OCB = get_const_tuple(latest_blocked.shape)\n    _, _, KH, KW, ICB = get_const_tuple(kernel.shape)\n    KHKW = KH * KW\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * KHKW * ICB)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/depthwise_conv2d_nhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"depthwise_conv2d_nhwc(c) schedule on Qualcomm Adreno GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .utils import (\n    split_to_chunks,\n    pack_input,\n    pack_filter,\n    expand_spatial_dimensions,\n    add_pad,\n    bind_data_copy,\n    get_texture_storage,\n    get_default_conv2d_config,\n)\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nhwc.image2d\")\ndef schedule_depthwise_conv2d_nhwc(cfg, outs):\n    \"\"\"Create the schedule for depthwise conv2d_nchw4c_ohwi4o\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"adreno_dw_conv2d_latest_op\":\n            schedule_depthwise_conv2d_NHWC_HWOI(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nhwc.image2d\")\ndef depthwise_conv2d_nhwc(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"\n    Depthwise convolution operator in NCHWc layout.\n    Algo:\n      1. Convert into blocked format if we have 4d original tensor.\n         In case of AutoTVM we override the convert by just tensors since such conversion\n         will be absent for real blocked convolution, no sense to include into tuning\n      2. Expand spatial dimensions to have width and height be dividable by factor 4\n         This leads to slightly bigger amount of compute but allow utilize GPU much better\n      3. Add paddings. This happens even if we do not need pad originaly. This is useful\n         due to work arounding of the gaps of texture annotation between Primary Functions\n         and limited support of textures in schedules. Later on this pad will be executed\n         separately and will produce texture\n      4. 5d Convolution compute with accumulating into out_dtype\n      5. Cast to the origin output data type\n      6. For case of 4d convolution: convert of output from 5d to 4d\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    convert_from4d = False\n    if len(Input.shape) == 4:\n        batch, in_height, in_width, in_channels = Input.shape\n        kernel_h, kernel_w, out_channles, in_filter_channels = Filter.shape\n\n        in_channel_chunks, in_channel_block, in_channel_tail = split_to_chunks(in_channels, 4)\n        out_channel_chunks, out_channel_block, out_channel_tail = split_to_chunks(out_channles, 4)\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            dshape = (batch, in_height, in_width, in_channel_chunks, in_channel_block)\n            Input = tvm.te.placeholder(dshape, Input.dtype, name=\"data_placeholder\")\n            kshape = (kernel_h, kernel_w, out_channel_block, in_filter_channels, out_channel_chunks)\n            Filter = tvm.te.placeholder(kshape, Filter.dtype, name=\"kernel_placeholder\")\n        else:\n            convert_from4d = True\n            Input = pack_input(\n                Input,\n                \"NHWC\",\n                batch,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                in_height,\n                in_width,\n            )\n            Filter = pack_filter(\n                Filter,\n                \"HWOI\",\n                out_channel_chunks,\n                out_channel_block,\n                out_channel_tail,\n                in_filter_channels,\n                in_channel_chunks,\n                in_channel_block,\n                in_channel_tail,\n                kernel_h,\n                kernel_w,\n            )\n\n    else:\n        batch, in_height, in_width, in_channel_chunks, in_channel_block = Input.shape\n        kernel_h, kernel_w, out_channel_chunks, in_filter_channels, out_channel_block = Filter.shape\n\n    out_height_orig, out_height, out_width_orig, out_width = expand_spatial_dimensions(\n        in_height, in_width, kernel_h, kernel_w, dilation_h, dilation_w, padding, stride_h, stride_w\n    )\n\n    temp = add_pad(\n        Input,\n        \"NHWC\",\n        out_height_orig,\n        out_width_orig,\n        kernel_h,\n        kernel_w,\n        dilation_h,\n        dilation_w,\n        padding,\n        stride_h,\n        stride_w,\n    )\n\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    conv = te.compute(\n        (batch, out_height, out_width, out_channel_chunks, out_channel_block),\n        lambda nn, yy, xx, ffc, ffb: te.sum(\n            (\n                temp[nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, ffc, ffb]\n                * Filter[ry, rx, ffc, 0, ffb]\n            ).astype(out_dtype),\n            axis=[ry, rx],\n        ),\n        tag=\"depthwise_conv2d_nhwc\",\n    )\n\n    if convert_from4d and not autotvm.GLOBAL_SCOPE.in_tuning:\n        dummy_cast = te.compute(\n            (batch, out_height_orig, out_width_orig, out_channel_chunks, out_channel_block),\n            lambda n, y, x, fc, fb: conv[n, y, x, fc, fb].astype(out_dtype),\n            tag=\"dummy_cast\",\n        )\n        return te.compute(\n            (batch, out_height_orig, out_width_orig, out_channles),\n            lambda n, y, x, c: dummy_cast[n, y, x, c // out_channel_block, c % out_channel_block],\n            tag=\"adreno_dw_conv2d_latest_op\",\n        )\n    else:\n        return te.compute(\n            (batch, out_height_orig, out_width_orig, out_channel_chunks, out_channel_block),\n            lambda n, y, x, ffc, ffb: conv[n, y, x, ffc, ffb].astype(out_dtype),\n            tag=\"adreno_dw_conv2d_latest_op\",\n        )\n\n\ndef schedule_depthwise_conv2d_NHWC_HWOI(cfg, s, output):\n    \"\"\"\n    schedule optimized for batch size = 1\n\n    Algo:\n    1. Split output axis to three parts: global work size, vthread, local worksize.\n       The limitations for tuning includes heuristics from some tuned networks to limit\n       search space and not pay much time for useles configurations.\n    2. In case of 4d convolution schedule copying of the input (and filter) into\n      5d tensors\n    3. For depthwise convolution it's better to inline pad into the conv2d compute, the\n       divergence in opencl kernel will not so significant as for regular conv2d.\n    4. For 5d convolution we schedule the latest op with binding 5d axis and vectorize\n       for textures\n       For 4d tensor we are doing the same for the latest blocked stage, i.e. conversion\n       of data type\n    5. In case of 4d conv we need to schedule postops as well\n    \"\"\"\n    latest = s.outputs[0].output(0)\n    if len(latest.op.axis) == 4:\n        latest_blocked = dummy = output.op.input_tensors[0]\n        conv = dummy.op.input_tensors[0]\n    else:\n        conv = output.op.input_tensors[0]\n        latest_blocked = latest\n\n    ##### space definition begin #####\n    n, y, x, fc, fb = s[conv].op.axis\n    ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_fc\", fc, num_outputs=3)\n    cfg.define_split(\"tile_y\", y, num_outputs=3)\n    cfg.define_split(\"tile_x\", x, num_outputs=3)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    cfg.multi_filter(\n        filter=lambda entity: (  # pylint: disable=chained-comparison\n            entity[\"tile_fc\"].size[1] * entity[\"tile_y\"].size[1] * entity[\"tile_x\"].size[1]\n        )\n        <= 32\n        and 32\n        <= (entity[\"tile_fc\"].size[2] * entity[\"tile_y\"].size[2] * entity[\"tile_x\"].size[2])\n        < 1024\n    )\n    if cfg.is_fallback:\n        get_default_conv2d_config(cfg, conv.shape[3], conv.shape[1], conv.shape[2])\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n    if (\n        isinstance(kernel.op, tvm.te.ComputeOp) and \"filter_pack\" in kernel.op.tag\n    ):  # len(latest.op.axis) == 4:\n        # manage scheduling of datacopy\n        pad_data, kernel = s[conv].op.input_tensors\n        if \"pad_temp\" in pad_data.op.name:\n            pack_data = pad_data.op.input_tensors[0]\n            bind_data_copy(s[pack_data])\n        else:\n            bind_data_copy(s[pad_data])\n        bind_data_copy(s[kernel])\n\n    pad_data, kernel = s[conv].op.input_tensors\n\n    if \"pad_temp\" in pad_data.op.name:\n        s[pad_data].compute_inline()\n\n    s[conv].set_scope(\"local\")\n    if latest_blocked == latest and output != latest:\n        s[output].compute_inline()\n\n    if autotvm.GLOBAL_SCOPE.in_tuning or len(latest.op.axis) == 4:\n        # create cache stage for tuning only or in case of 4d case\n        AT = s.cache_read(pad_data, get_texture_storage(pad_data.shape), [conv])\n        bind_data_copy(s[AT])\n        WT = s.cache_read(kernel, get_texture_storage(kernel.shape), [conv])\n        bind_data_copy(s[WT])\n\n    # tile and bind spatial axes\n    n, y, x, fc, fb = s[latest_blocked].op.axis\n    kernel_scope, n = s[latest_blocked].split(n, nparts=1)\n\n    bf, vf, tf = cfg[\"tile_fc\"].apply(s, latest_blocked, fc)\n    by, vy, ty = cfg[\"tile_y\"].apply(s, latest_blocked, y)\n    bx, vx, tx = cfg[\"tile_x\"].apply(s, latest_blocked, x)\n\n    by = s[latest_blocked].fuse(n, by)\n    s[latest_blocked].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[latest_blocked].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[latest_blocked].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[latest_blocked].bind(vf, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vy, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(vx, te.thread_axis(\"vthread\"))\n    s[latest_blocked].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[latest_blocked].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[latest_blocked].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[latest_blocked].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fb)\n    s[latest_blocked].vectorize(fb)\n\n    s[conv].compute_at(s[latest_blocked], tx)\n\n    # tile reduction axes\n    n, y, x, fc, fb = s[conv].op.axis\n\n    ry, rx = s[conv].op.reduce_axis\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(ryo, rxo, ryi, rxi, n, fc, y, x, fb)\n    s[conv].vectorize(fb)\n\n    # unroll\n    s[latest_blocked].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[latest_blocked].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n    if latest_blocked != latest:\n        s[latest].compute_root()\n        bind_data_copy(s[latest], 1)\n        if latest != output:\n            s[output].compute_inline()\n\n    N, OH, OW, OCC, OCB = get_const_tuple(latest_blocked.shape)\n    KH, KW, _, _, _ = get_const_tuple(kernel.shape)\n    KHKW = KH * KW\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * KHKW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable,\n\"\"\"Schedule for composition of injective operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom .utils import bind_data_copy\nfrom .. import utils\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n\n    bind_data_copy(sch[out])\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"Schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    tvm.te.schedule.AutoInlineInjective(s)\n    for out in outs:\n        if not utils.is_empty_shape(out.shape):\n            schedule_injective_from_existing(s, out)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"pooling schedules for Qualcomm Adreno GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Schedule for various pooling operators.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of pool\n        in the format of an array of tensors.\n\n    layout: str\n        Data layout.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for pool.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(PaddedInput, Pool):\n        if isinstance(PaddedInput.op, tvm.te.ComputeOp):\n            s[PaddedInput].compute_inline()\n        num_thread = tvm.target.Target.current(allow_none=False).max_num_threads\n        num_thread = int(num_thread * 2)\n        if Pool.op in s.outputs:\n            Out = Pool\n            OL = s.cache_write(Pool, \"local\")\n        else:\n            Out = outs[0].op.output(0)\n            s[Pool].set_scope(\"local\")\n        fused = s[Out].fuse(*s[Out].op.axis[:-1])\n        bx, tx = s[Out].split(fused, factor=num_thread)\n        s[Out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[Out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[Out].vectorize(s[Out].op.axis[-1])\n        if Pool.op in s.outputs:\n            s[OL].compute_at(s[Out], tx)\n            s[OL].vectorize(s[OL].op.axis[-1])\n        else:\n            s[Pool].compute_at(s[Out], tx)\n            s[Pool].vectorize(s[Pool].op.axis[-1])\n\n    scheduled_ops = []\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule pool\n        elif OP.tag.startswith(\"pool\"):\n            PaddedInput = OP.input_tensors[0]\n            Pool = OP.output(0)\n            _schedule(PaddedInput, Pool)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,too-many-locals,len-as-condition\n\"\"\"Schedule for reduce operators\"\"\"\nimport numpy\nfrom tvm import te\nfrom ..utils import get_const_tuple\nfrom .injective import schedule_injective_from_existing\nfrom .utils import get_div\nfrom ..cuda.reduction import schedule_reduce_impl\n\n\ndef _schedule_reduce_adreno(op, sch, is_idx_reduce=False):\n    if is_idx_reduce:\n        real_output = op.output(0)\n        temp_idx_input = op.input_tensors[0].op.output(0)\n        temp_val_input = op.input_tensors[0].op.output(1)\n    else:\n        real_output = op.output(0)\n    shape = get_const_tuple(real_output.shape)\n    latest4 = shape[-1] == 4\n    div4 = numpy.prod(shape) % 4 == 0\n\n    # Fuse and split the axis\n    if latest4:\n        fused_outer = sch[real_output].fuse(\n            *[sch[real_output].op.axis[i] for i in range(len(sch[real_output].op.axis) - 1)]\n        )\n    else:\n        fused_outer = sch[real_output].fuse(\n            *[sch[real_output].op.axis[i] for i in range(len(sch[real_output].op.axis))]\n        )\n\n    ftc = numpy.prod(shape)\n    a = fused_outer\n    if latest4:\n        sch[real_output].vectorize(sch[real_output].op.axis[-1])\n    elif div4 and not is_idx_reduce:\n        a, b = sch[real_output].split(fused_outer, factor=4)\n        sch[real_output].vectorize(b)\n        ftc = ftc / 4\n\n    num_thread = get_div(ftc, 128)\n\n    bx, outer_in = sch[real_output].split(a, factor=num_thread)\n\n    sch[real_output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    sch[real_output].bind(outer_in, te.thread_axis(\"threadIdx.y\"))\n    if is_idx_reduce:\n        sch[temp_idx_input].compute_at(sch[real_output], outer_in)\n        sch[temp_val_input].compute_at(sch[real_output], outer_in)\n\n\ndef schedule_reduce(outs):\n    return schedule_reduce_impl(outs, _schedule_reduce_adreno, schedule_injective_from_existing)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/adreno/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"util functions to be reused in different compute/schedule on Qualcomm Adreno GPU\"\"\"\n\nimport tvm\nimport numpy\nfrom tvm import te\nfrom tvm._ffi.registry import register_func\nfrom tvm.topi.utils import simplify\nfrom tvm.topi import nn\nfrom tvm.autotvm.task.space import SplitEntity\nfrom ..utils import get_const_tuple\n\n\ndef get_div(value, start):\n    \"\"\"Returns the maximum divider for `value` starting from `start` value\"\"\"\n    div = 1\n    for d in range(start, 0, -1):\n        if (value % d) == 0:\n            div = d\n            break\n    return div\n\n\ndef split_to_chunks(extent, block):\n    \"\"\"\n    Splits the trip count value to chunks and block, returns the remainder as well\n    the chunks and blocks covers or overlaps the origin value\n\n    If extent can be divisible by block:\n        extent = chunks * block\n    else\n        extent = (chunks - 1) * block + tail\n\n    Parameters\n    ----------\n    extent: int\n        tripcount for original compute\n\n    block: int\n        size of the block\n\n    Returns\n    ----------\n    out: tuple of the (chunks, block, tail)\n         chunks = ceildiv(extent, block)\n         tail = number of origin elements in the latest chunk\n    \"\"\"\n    tail = extent % block\n    chunks = extent // block\n    if tail == 0:\n        tail = block\n    else:\n        chunks += 1\n    return chunks, block, tail\n\n\ndef pack_input(Input, layout, batch, chunks, block, original_tail, in_height, in_width):\n    \"\"\"\n    Adds compute stages for packing of the data in runtime. Extends channel dimensions\n    to be dividable by factor 4\n\n    This function should be substituted by Schedule.transform_layout() in the future: see\n    https://github.com/apache/tvm-rfcs/blob/main/rfcs/0039-buffer-physical-layout.md\n\n    Parameters\n    ----------\n    Input: tvm.te.Tensor\n        Input tensor to be repacked in runtime\n\n    layout: string\n        Layout of origin 4d tensor\n        NCHW or NHWC are acceptable\n\n    batch: int\n        Batch size\n\n    chunks: int\n        Number of channel chunks been in the final tensor\n\n    block: int\n        size of the channel block\n\n    original_tail: int\n        Tail in the latest chunk diffing original number of channels vs blocked one\n        If original_tail != block:\n          original_channels = chunks * block - original_tail\n        else\n          original_channels = chunks * block\n\n    in_height: int\n        Height of the feature map\n\n    in_width: int\n        Width of the feature map\n    \"\"\"\n\n    pad_value = tvm.tir.const(0, Input.dtype)\n\n    def _reorder_data_nchw(*indices):\n        condition = []\n        condition.append(indices[1] == chunks - 1)\n        condition.append(indices[4] >= original_tail)\n        condition = tvm.tir.all(*condition)\n        return tvm.tir.if_then_else(\n            condition,\n            pad_value,\n            Input[indices[0], indices[1] * block + indices[4], indices[2], indices[3]],\n        )\n\n    def _reorder_data_nhwc(*indices):\n        condition = []\n        condition.append(indices[3] == chunks - 1)\n        condition.append(indices[4] >= original_tail)\n        condition = tvm.tir.all(*condition)\n        return tvm.tir.if_then_else(\n            condition,\n            pad_value,\n            Input[indices[0], indices[1], indices[2], indices[3] * block + indices[4]],\n        )\n\n    # compute:\n    if layout == \"NCHW\":\n        reordered_data = te.compute(\n            [batch, chunks, in_height, in_width, block],\n            _reorder_data_nchw,\n            name=\"input_pack\",\n            tag=\"input_pack\",\n        )\n    elif layout == \"NHWC\":\n        reordered_data = te.compute(\n            [batch, in_height, in_width, chunks, block],\n            _reorder_data_nhwc,\n            name=\"input_pack\",\n            tag=\"input_pack\",\n        )\n    else:\n        assert False, \"Adreno util function pack_input does not accept unknown layout\"\n    return reordered_data\n\n\ndef pack_filter(\n    Filter,\n    layout,\n    out_chunks,\n    out_block,\n    out_original_tail,\n    in_filter_channels,\n    in_chunks,\n    in_block,\n    in_original_tail,\n    kernel_h,\n    kernel_w,\n):\n    \"\"\"\n    Adds compute stages for packing of the filter in runtime. Extends channels dimensions\n    to be dividable by factor 4\n\n    This function should be substituted by Schedule.transform_layout() in the future: see\n    https://github.com/apache/tvm-rfcs/blob/main/rfcs/0039-buffer-physical-layout.md\n\n    Parameters\n    ----------\n    Filter: tvm.te.Tensor\n        Filter tensor to be repacked in runtime\n\n    layout: string\n        Layout of origin 4d tensor\n        NCHW or NHWC are acceptable\n\n    out_chunks: int\n        Number of chunks for filters\n\n    out_block: int\n        Size of the block for output channels\n\n    out_original_tail: int\n        Original size of the latest chunk of output filters\n\n    in_filter_channels: int\n        Number of filter channels. might be different vs input channels in the\n        data due to groups/depthwise nature\n\n    in_chunks: int\n        Number of input data channel chunks\n\n    in_block: int\n        Size of the block for input data channels\n\n    in_original_tail\n        Original size of the latest chunk for input data channels\n\n    kernel_h: int\n        Height of the conv2d kernel\n\n    kernel_w: int\n        Width of the conv2d kernel\n    \"\"\"\n    pad_value = tvm.tir.const(0, Filter.dtype)\n\n    def _reorder_weights_depthwise_oihw(*indices):\n        conditionA = []\n        conditionA.append(indices[0] == out_chunks - 1)\n        conditionA.append(indices[4] >= out_original_tail)\n        conditionAT = tvm.tir.all(*conditionA)\n\n        return tvm.tir.if_then_else(\n            conditionAT,\n            pad_value,\n            Filter[indices[0] * out_block + indices[4], indices[1], indices[2], indices[3]],\n        )\n\n    def _reorder_weights_depthwise_hwoi(*indices):\n        conditionA = []\n        conditionA.append(indices[2] == out_chunks - 1)\n        conditionA.append(indices[4] >= out_original_tail)\n        conditionAT = tvm.tir.all(*conditionA)\n\n        return tvm.tir.if_then_else(\n            conditionAT,\n            pad_value,\n            Filter[indices[0], indices[1], indices[2] * out_block + indices[4], indices[3]],\n        )\n\n    def _reorder_weights_oihw(*indices):\n        conditionA = []\n        conditionA.append(indices[0] == out_chunks - 1)\n        conditionA.append(indices[4] >= out_original_tail)\n        conditionAT = tvm.tir.all(*conditionA)\n\n        conditionO = []\n        conditionO.append(conditionAT)\n        conditionO.append(indices[1] >= in_chunks * in_block + in_original_tail)\n        conditionOT = tvm.tir.any(*conditionO)\n        return tvm.tir.if_then_else(\n            conditionOT,\n            pad_value,\n            Filter[indices[0] * out_block + indices[4], indices[1], indices[2], indices[3]],\n        )\n\n    def _reorder_weights_hwio(*indices):\n        conditionA = []\n        conditionA.append(indices[3] == out_chunks - 1)\n        conditionA.append(indices[4] >= out_original_tail)\n        conditionAT = tvm.tir.all(*conditionA)\n\n        conditionO = []\n        conditionO.append(conditionAT)\n        conditionO.append(indices[2] >= in_chunks * in_block + in_original_tail)\n        conditionOT = tvm.tir.any(*conditionO)\n        return tvm.tir.if_then_else(\n            conditionOT,\n            pad_value,\n            Filter[indices[0], indices[1], indices[2], indices[3] * out_block + indices[4]],\n        )\n\n    if in_filter_channels == 1:\n        if layout == \"OIHW\":\n            reordered_filter = te.compute(\n                [out_chunks, in_filter_channels, kernel_h, kernel_w, out_block],\n                _reorder_weights_depthwise_oihw,\n                name=\"filter_pack\",\n                tag=\"filter_pack\",\n            )\n        elif layout == \"HWOI\":\n            reordered_filter = te.compute(\n                [kernel_h, kernel_w, out_chunks, in_filter_channels, out_block],\n                _reorder_weights_depthwise_hwoi,\n                name=\"filter_pack\",\n                tag=\"filter_pack\",\n            )\n        else:\n            assert False, \"Adreno util function def pack_filter does not accept unknown layout\"\n    else:\n        if layout == \"OIHW\":\n            reordered_filter = te.compute(\n                [out_chunks, in_filter_channels, kernel_h, kernel_w, out_block],\n                _reorder_weights_oihw,\n                name=\"filter_pack\",\n                tag=\"filter_pack\",\n            )\n        elif layout == \"HWIO\":\n            reordered_filter = te.compute(\n                [kernel_h, kernel_w, in_filter_channels, out_chunks, out_block],\n                _reorder_weights_hwio,\n                name=\"filter_pack\",\n                tag=\"filter_pack\",\n            )\n        else:\n            assert False, \"Adreno util function def pack_filter does not accept unknown layout\"\n    return reordered_filter\n\n\ndef expand_spatial_dimensions(\n    in_height, in_width, kernel_h, kernel_w, dilation_h, dilation_w, padding, stride_h, stride_w\n):\n    \"\"\"\n    Expands spatial dimensions to be dividable by factor 4. This will allow us to do extrimely\n    better parallel computation on GPU. The drawback of this solution - it will be number of\n    useless computations. By fact the speed-up of parallelism significantly overcomes the slowdown\n    of extra compute and eventuially this is useful approach, at least for GPU\n\n    Parameters\n    ----------\n    in_height: int\n        Height of the feature map\n\n    in_width: int\n        Width of the feature map\n\n    kernel_h: int\n        Height of the conv2d kernel\n\n    kernel_w: int\n        Width of the conv2d kernel\n\n    dilation_h: int\n        Vertical dilation of the conv2d kernel\n\n    dilation_w: int\n        Horizontal dilation of the conv2d kernel\n\n    padding: tuple or list\n        Conv2d paddings\n\n    stride_h: int\n        Vertical stride  of the conv2d kernel\n\n    stride_w: int\n        Horizontal stride  of the conv2d kernel\n    \"\"\"\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_height_orig = out_height = simplify(\n        (in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1\n    )\n    out_width_orig = out_width = simplify(\n        (in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1\n    )\n\n    # can output shape be divded by 2 or even 4?\n    # if it cannot be divided, need to extend for further help with split\n    # theortically there should be addition padding for inputs, but it will be optimized by\n    # cache_read InferBound. We must proceed pad here exactly to produce tensor which is\n    # required for calculation of original out size, not more! In other case intermediate\n    # tensor might be allcoated with less sizes while compute will try to fill the expanded\n    # one - data discrepancy as a result\n    # And in case of textures it is not a problem if we provide texture of less size because\n    # 1. It is not important which values would be for extra calc - these calculations are\n    #    required only for better utilizatin of GPU fit to working groups\n    # 2. When we request pixel out opf bound, texture will handle this correctly. As mentioned\n    #    above, the value itself is not important\n    if out_height % 2 != 0:\n        out_height += 1\n    if out_width % 2 != 0:\n        out_width += 1\n\n    if out_height % 4 != 0:\n        out_height += 2\n    if out_width % 4 != 0:\n        out_width += 2\n    return out_height_orig, out_height, out_width_orig, out_width\n\n\ndef add_pad(\n    data,\n    layout,\n    out_height,\n    out_width,\n    kernel_h,\n    kernel_w,\n    dilation_h,\n    dilation_w,\n    padding,\n    stride_h,\n    stride_w,\n):\n    \"\"\"Computes required padding values by the parameters of conv2d and adds\n        compute for extending of original tensor\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        5d tensor, the layout of spatial dimensions are defined as separate argument\n\n    layout: string\n        Layout of origin 4d tensor\n\n    out_height: int\n        Height of the output feature map\n\n    out_width: int\n        Width of the output feature map\n\n    kernel_h: int\n        Height of the conv2d kernel\n\n    kernel_w: int\n        Width of the conv2d kernel\n\n    dilation_h: int\n        Height dilation value from conv2d attributes\n\n    dilation_w: int\n        Width dilation value from conv2d attributes\n\n    padding: list / tuple of n ints\n        Padding values from conv2d attributes\n\n    stride_h: int\n        Height stride value from conv2d attributes\n\n    stride_w: int\n        Width stride value from conv2d attributes\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        n-D, the same layout as Input.\n    \"\"\"\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    # compute graph\n    if layout == \"NCHW\":\n        y_axis = 2\n        x_axis = 3\n        if len(data.shape) == 4:\n            _, _, in_height, in_width = data.shape\n        else:\n            _, _, in_height, in_width, _ = data.shape\n    elif layout == \"NHWC\":\n        y_axis = 1\n        x_axis = 2\n        if len(data.shape) == 4:\n            _, in_height, in_width, _ = data.shape\n        else:\n            _, in_height, in_width, _, _ = data.shape\n    else:\n        assert False, \"not supported layout in adreno util add_pad\"\n    pad_before = [0, 0, 0, 0, 0]\n    pad_after = [0, 0, 0, 0, 0]\n    pad_before[y_axis] = pad_top\n    pad_before[x_axis] = pad_left\n    pad_after[y_axis] = pad_down\n    pad_after[x_axis] = pad_right\n\n    # calculation of real used input size:\n    input_latest_w = (out_width - 1) * stride_w + (kernel_w - 1) * dilation_w + 1\n    input_latest_h = (out_height - 1) * stride_h + (kernel_h - 1) * dilation_h + 1\n    if input_latest_w < in_width + pad_before[x_axis] + pad_after[x_axis]:\n        pad_after[x_axis] -= in_width + pad_before[x_axis] + pad_after[x_axis] - input_latest_w\n    if input_latest_h < in_height + pad_before[y_axis] + pad_after[y_axis]:\n        pad_after[y_axis] -= in_height + pad_before[y_axis] + pad_after[y_axis] - input_latest_h\n    if (\n        pad_before[0] == 0\n        and pad_before[1] == 0\n        and pad_before[2] == 0\n        and pad_before[3] == 0\n        and pad_after[0] == 0\n        and pad_after[1] == 0\n        and pad_after[2] == 0\n        and pad_after[3] == 0\n    ):\n        return data\n    else:\n        return nn.pad(data, pad_before, pad_after, name=\"pad_temp\")\n\n\ndef bind_data_copy(stage, axis_to_vectorize=None):\n    \"\"\"\n    Schedules the eltwise stages like copying of data or postops\n\n    Parameters\n    ----------\n    stage: tvm.te.Tensor\n\n    axis_to_vectorize:\n        Causes to split certain axis, moves inner part to the end of schedule\n        and enable vectorization by this axis\n        If parameter is not pointed, the schedule will be vectorized if the most inner\n        dim is eq to 4 (size of the vector in texture)\n    \"\"\"\n    shape = get_const_tuple(stage.op.output(0).shape)\n    if axis_to_vectorize and len(shape) == 4 and shape[axis_to_vectorize] % 4 == 0:\n        ax0, ax1, ax2, ax3 = stage.op.axis\n        if axis_to_vectorize == 1:\n            oax1, iax1 = stage.split(ax1, factor=4)\n            stage.reorder(ax0, oax1, ax2, ax3, iax1)\n            stage.vectorize(iax1)\n            fused = stage.fuse(ax0, oax1, ax2, ax3)\n        elif axis_to_vectorize == 3:\n            oax3, iax3 = stage.split(ax3, factor=4)\n            stage.reorder(ax0, ax1, ax2, oax3, iax3)\n            stage.vectorize(iax3)\n            fused = stage.fuse(ax0, ax1, ax2, oax3)\n\n        ftc = numpy.prod(shape) / 4\n        div = get_div(ftc, 128)\n        block, thread = stage.split(fused, factor=div)\n\n        stage.bind(block, te.thread_axis(\"blockIdx.z\"))\n        stage.bind(thread, te.thread_axis(\"threadIdx.z\"))\n    else:\n        if shape[-1] == 4:\n            axes = stage.op.axis\n            fused = stage.fuse(*axes[:-1])\n            ftc = numpy.prod(shape[:-1])\n            div = get_div(ftc, 64)\n            block, thread = stage.split(fused, factor=div)\n            stage.bind(block, te.thread_axis(\"blockIdx.x\"))\n            stage.bind(thread, te.thread_axis(\"threadIdx.x\"))\n            stage.vectorize(axes[-1])\n        else:\n            ftc = numpy.prod(shape)\n            vthread = get_div(ftc, 8)\n            fused = stage.fuse(*stage.op.axis)\n            ftc = ftc / vthread\n            # 1024 is a maximum work group size on the most Adreno GPU\n            num_thread = get_div(ftc, 1024 // vthread)\n            a, b = stage.split(fused, factor=num_thread)\n            a, c = stage.split(a, factor=vthread)\n            stage.bind(c, te.thread_axis(\"vthread\"))\n            stage.bind(a, te.thread_axis(\"blockIdx.x\"))\n            stage.bind(b, te.thread_axis(\"threadIdx.x\"))\n\n\ndef get_texture_storage(shape):\n    \"\"\"\n    Returns the texture layout acceptable for the shape\n\n    Parameters\n    ----------\n    shape: array\n        Shape of the tensor to be packed to texture\n    \"\"\"\n    # certain limitation of the Qualcomm devices. Subject to be determined for certain device\n    # individually, but until we have access to remote device during compilation, we have to\n    # define it uniformly for all target devices\n    # limit = 16384\n    limit = tvm.target.Target.current().attrs[\"texture_spatial_limit\"]\n\n    if shape[0] * shape[1] * shape[2] < limit and shape[3] < limit:\n        return \"global.texture\"\n    elif shape[0] * shape[1] < limit and shape[2] * shape[3] < limit:\n        return \"global.texture-nhwc\"\n    else:\n        return \"global.texture-weight\"\n\n\n@register_func(\"tvm.info.mem.global.texture\")\n@register_func(\"tvm.info.mem.global.texture-nhwc\")\n@register_func(\"tvm.info.mem.global.texture-weight\")\ndef mem_info_global_texture_variants():\n    return tvm.ir.make_node(\n        \"MemoryInfo\",\n        unit_bits=16,\n        max_num_bits=16384 * 16384 * 4 * 32,\n        max_simd_bits=4 * 32,\n        head_address=None,\n    )\n\n\ndef infer_tile_size(data, layout):\n    \"\"\"Compute the tile size for Winograd algorithm\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        Data tensor\n\n    layout: string\n        Layout of data tebsir\n        NCHW, NCHW4c, NHWC or NHWC4c are acceptable\n\n    Returns\n    -------\n    tile_size : int\n        Calculated tile size\n    \"\"\"\n    assert layout in (\"NCHW\", \"NCHW4c\", \"NHWC\", \"NHWC4c\"), \"Incompatible layout\"\n    if layout in (\"NCHW\", \"NCHW4c\"):\n        H = get_const_tuple(data.shape)[2]\n    else:\n        H = get_const_tuple(data.shape)[1]\n\n    if H % 8 == 0:\n        return 4\n    return 2\n\n\ndef get_default_conv2d_config(cfg, fc, y, x):\n    \"\"\"Defines conv2d default parameters for split axis for Adreno conv2d and depthwise conv2d\"\"\"\n    # look for vthread params:\n    vy = 1\n    for n in range(5, 0, -1):\n        if y % n == 0:\n            vy = n\n            break\n\n    vx = 1\n    for n in range(5, 0, -1):\n        if x % n == 0 and vy * n < 9:\n            vx = n\n            break\n\n    y = y // vy\n    x = x // vx\n\n    tfc = 1\n    for n in range(64, 0, -1):\n        if fc % n == 0:\n            tfc = n\n            break\n    ty = 1\n    for n in range(16, 0, -1):\n        if y % n == 0 and tfc * n <= 512:\n            ty = n\n            break\n    tx = 1\n    for n in range(16, 0, -1):\n        if x % n == 0 and tfc * ty * n <= 512:\n            tx = n\n            break\n\n    fc = fc // tfc\n    y = y // ty\n    x = x // tx\n\n    cfg[\"tile_fc\"] = SplitEntity([fc, 1, tfc])\n    cfg[\"tile_y\"] = SplitEntity([y, vy, ty])\n    cfg[\"tile_x\"] = SplitEntity([x, vx, tx])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/argwhere.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks\n\"\"\"Argwhere operator\"\"\"\nimport tvm\nfrom tvm.te import hybrid\n\n\n@hybrid.script\ndef hybrid_argwhere_1d(output_shape, condition):\n    \"\"\"Find the indices of elements of a 1-D tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        1-D tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    a = output_tensor(output_shape, \"int32\")\n    a1 = condition.shape[0]\n    valid_index = 0\n    for i1 in range(a1):\n        if condition[i1] != 0:\n            a[valid_index, 0] = i1\n            valid_index += 1\n    return a\n\n\n@hybrid.script\ndef hybrid_argwhere_2d(output_shape, condition):\n    \"\"\"Find the indices of elements of a 2-D tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        2-D tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    a = output_tensor(output_shape, \"int32\")\n    a1 = condition.shape[0]\n    a2 = condition.shape[1]\n    valid_index = 0\n    for i1 in range(a1):\n        for i2 in range(a2):\n            if condition[i1, i2] != 0:\n                a[valid_index, 0] = i1\n                a[valid_index, 1] = i2\n                valid_index += 1\n    return a\n\n\n@hybrid.script\ndef hybrid_argwhere_3d(output_shape, condition):\n    \"\"\"Find the indices of elements of a 3-D tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        3-D tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    a = output_tensor(output_shape, \"int32\")\n    a1 = condition.shape[0]\n    a2 = condition.shape[1]\n    a3 = condition.shape[2]\n    valid_index = 0\n    for i1 in range(a1):\n        for i2 in range(a2):\n            for i3 in range(a3):\n                if condition[i1, i2, i3] != 0:\n                    a[valid_index, 0] = i1\n                    a[valid_index, 1] = i2\n                    a[valid_index, 2] = i3\n                    valid_index += 1\n    return a\n\n\n@hybrid.script\ndef hybrid_argwhere_4d(output_shape, condition):\n    \"\"\"Find the indices of elements of a 4-D tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        4-D tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    a = output_tensor(output_shape, \"int32\")\n    a1 = condition.shape[0]\n    a2 = condition.shape[1]\n    a3 = condition.shape[2]\n    a4 = condition.shape[3]\n    valid_index = 0\n    for i1 in range(a1):\n        for i2 in range(a2):\n            for i3 in range(a3):\n                for i4 in range(a4):\n                    if condition[i1, i2, i3, i4] != 0:\n                        a[valid_index, 0] = i1\n                        a[valid_index, 1] = i2\n                        a[valid_index, 2] = i3\n                        a[valid_index, 3] = i4\n                        valid_index += 1\n    return a\n\n\n@hybrid.script\ndef hybrid_argwhere_5d(output_shape, condition):\n    \"\"\"Find the indices of elements of a 5-D tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        5-D tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    a = output_tensor(output_shape, \"int32\")\n    a1 = condition.shape[0]\n    a2 = condition.shape[1]\n    a3 = condition.shape[2]\n    a4 = condition.shape[3]\n    a5 = condition.shape[4]\n    valid_index = 0\n    for i1 in range(a1):\n        for i2 in range(a2):\n            for i3 in range(a3):\n                for i4 in range(a4):\n                    for i5 in range(a5):\n                        if condition[i1, i2, i3, i4, i5] != 0:\n                            a[valid_index, 0] = i1\n                            a[valid_index, 1] = i2\n                            a[valid_index, 2] = i3\n                            a[valid_index, 3] = i4\n                            a[valid_index, 4] = i5\n                            valid_index += 1\n    return a\n\n\n@tvm.target.generic_func\ndef argwhere(output_shape, condition):\n    \"\"\"Find the indices of elements of a tensor that are non-zero.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    if len(condition.shape) == 1:\n        return hybrid_argwhere_1d(output_shape.shape, condition)\n    if len(condition.shape) == 2:\n        return hybrid_argwhere_2d(output_shape.shape, condition)\n    if len(condition.shape) == 3:\n        return hybrid_argwhere_3d(output_shape.shape, condition)\n    if len(condition.shape) == 4:\n        return hybrid_argwhere_4d(output_shape.shape, condition)\n    if len(condition.shape) == 5:\n        return hybrid_argwhere_5d(output_shape.shape, condition)\n    raise ValueError(\"Does not support rank higher than 5 in argwhere\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wildcard-import\n\"\"\"Schedule for ARM CPU\"\"\"\n\nfrom .conv1d import *\nfrom .conv2d import *\nfrom .depthwise_conv2d import *\nfrom .conv2d_transpose import *\nfrom .conv2d_int8 import *\nfrom . import conv2d_alter_op\nfrom .bitserial_conv2d import *\nfrom .bitserial_dense import *\nfrom .injective import *\nfrom .group_conv2d import *\nfrom .pooling import *\nfrom .dense import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/arm_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Arm target utility functions\"\"\"\n\nfrom tvm.target import Target\n\n\ndef get_tiling_B_interleaved_t(interleave_A):\n    \"\"\"Compute the tiling information for matrix B', where B'\n    is the transposed and interleaved version of matrix B in C=A*B.\n\n    The tiling information is chosen to maximize register usage during the\n    tile computation.\n\n    Please refer to:\n    - https://discuss.tvm.apache.org/t/rfc-improve-quantized-convolution-performance-for-armv8-architectures # pylint: disable=line-too-long\n    - https://discuss.tvm.apache.org/t/rfc-accelerate-quantized-convolution-through-dot-product\n    - https://discuss.tvm.apache.org/t/rfc-improve-quantized-convolution-through-mmla-instruction\n    - Conv2DGemmWeightTransformRel in src/relay/op/nn/convolution.h\n     In order to have more information\n\n    Parameters\n    ----------\n    interleave_A: bool\n                  determines if A is expected to be interleaved\n\n    Returns\n    ----------\n    tile_rows_B: the output tile rows of B'\n    tile_cols_B: the output tile columns of B'\n    \"\"\"\n    target = Target.current(allow_none=False)\n\n    if target.features.has_matmul_i8:\n        # If smmla/ummla is available,  A must be interleaved.\n        # Each load from B' will contain 8 elements\n        # and we are loading 12 rows of B' (i.e., 12 columns of B)\n        tile_rows_B = 12\n        tile_cols_B = 8\n    elif target.features.has_dotprod:\n        # The number of tile rows of B' vary depending on the\n        # strategy:\n        # * If we are interleaving A, then we select 12 columns from B'(i.e.,\n        #   12 rows from B).\n        # * If we are not interleaving A, then we select 16 columns from B'(i.e.,\n        #   16 rows from B).\n        tile_rows_B = 12 if interleave_A else 16\n\n        # Dot product instruction groups 2 (u)int16x8 vectors in\n        # groups of 4 and compute the dot product among those groups\n        # This means that the number of columns in a tile of B' (i.e.,  the\n        # rows of the original matrix B)  need to be 4.\n        tile_cols_B = 4\n    else:\n        # If no acceleration is available, A must be interleaved. In this case\n        # we load 4 rows of B' (i.e., 4 columns of B). Each of them will contain 16 elements\n        tile_rows_B = 4\n        tile_cols_B = 16\n\n    return tile_rows_B, tile_cols_B\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/bitserial_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,invalid-name,unused-argument\n\"\"\"Bitserial conv2d schedule on arm cpu\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import relay\nfrom ..nn.pad import pad\nfrom ..nn.bitserial_conv2d import bitserial_conv2d_legalize\nfrom ..nn.bitserial_util import bitpack, binary_op_multiplier\nfrom ..nn.utils import get_pad_tuple\nfrom ..utils import get_const_int, get_const_tuple, traverse_inline\n\n\ndef _kernel_vec_spatial_pack_nhwc(kernel, kernel_bits, VC, use_bitpack=True):\n    if use_bitpack:\n        kernel_q = bitpack(kernel, kernel_bits, pack_axis=2, bit_axis=2, pack_type=\"uint8\")\n    else:\n        kernel_q = kernel\n    KH, KW, KB, CI, CO = kernel_q.shape\n    kvshape = (CO // VC, KH, KW, KB, VC, CI)\n    return te.compute(\n        kvshape,\n        lambda co, dh, dw, b, vc, ci: kernel_q[dh][dw][b][ci][co * VC + vc],\n        name=\"kernel_vec\",\n    )\n\n\n@autotvm.register_topi_compute(\"bitserial_conv2d_nhwc.arm_cpu\")\ndef bitserial_conv2d_nhwc(\n    cfg,\n    data,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    pack_dtype,\n    out_dtype,\n    unipolar,\n):\n    \"\"\"Compute convolution with pack on spatial axes.\"\"\"\n    assert data.shape[0].value == 1, \"spatial pack convolution only support batch size=1\"\n    assert pack_dtype == \"uint8\", \"only support packing into uint8 bits\"\n    assert out_dtype == \"int16\", \"only support output type of int16\"\n\n    N, H, W, CI = get_const_tuple(data.shape)\n    if len(kernel.shape) == 4:\n        KH, KW, _, CO = get_const_tuple(kernel.shape)\n        CI_packed = CI // 8\n    else:\n        KH, KW, KB, CI_packed, CO = get_const_tuple(kernel.shape)\n\n    if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2):\n        TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel)\n    else:\n        TPAD, LPAD, DPAD, RPAD = padding\n\n    if isinstance(stride, (tuple, list)):\n        HSTR, WSTR = stride\n    else:\n        HSTR, WSTR = stride, stride\n    HCAT, WCAT = KH - 1, KW - 1\n\n    PAD_H = H + (TPAD + DPAD)\n    PAD_W = W + (LPAD + RPAD)\n    OH = (PAD_H - KH) // HSTR + 1\n    OW = (PAD_W - KW) // WSTR + 1\n    oshape = (1, OH, OW, CO)\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    # Pad input channels of weights and data when it is not a multiple of 8\n    if CI_packed % 8 != 0:\n        CI_PAD = CI_packed % 8\n        CI_packed += CI_PAD\n    else:\n        CI_PAD = 0\n\n    # ==================== define configuration space ====================\n    n, oh, ow, co = cfg.axis(N), cfg.axis(OH), cfg.axis(OW), cfg.axis(CO)\n    ci, kh, kw = cfg.reduce_axis(CI_packed), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n    ib, kb = cfg.reduce_axis(activation_bits), cfg.reduce_axis(weight_bits)\n\n    co, vc = cfg.define_split(\"tile_co\", co, num_outputs=2, filter=lambda x: x.size[-1] == 8)\n    oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2, filter=lambda x: x.size[-1] >= 2)\n    ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda x: x.size[-1] >= 2)\n    ci_o, ci_i = cfg.define_split(\n        \"tile_ci\", ci, num_outputs=2, filter=lambda x: x.size[-1] == 8 or x.size[-1] == 16\n    )\n    re_axes = cfg.define_reorder(\n        \"reorder_0\",\n        [n, oh, ow, co, vh, vw, kh, kw, ci_o, kb, ib, vc, ci_i],\n        policy=\"candidate\",\n        candidate=[\n            [n, oh, ow, co, vh, vw, kh, kw, ci_o, kb, ib, vc, ci_i],\n            [n, oh, ow, co, vh, vw, kw, kh, ci_o, kb, ib, vc, ci_i],\n        ],\n    )\n    # binary ops\n    cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW * binary_op_multiplier(pack_dtype))\n    # ====================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    data_q = bitpack(data, activation_bits, pack_axis=3, bit_axis=3, pack_type=\"uint8\")\n\n    kernel_vec = _kernel_vec_spatial_pack_nhwc(kernel, weight_bits, VC, len(kernel.shape) == 4)\n    idxm = tvm.tir.indexmod\n    if idxm(kernel_vec.shape[-1], 8) != 0 and CI_PAD != 0:\n        kernel_vec = pad(kernel_vec, [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, CI_PAD])\n\n    N, H, W, IB, CI = data_q.shape\n    OCO, KH, KW, KB, VC, CI = kernel_vec.shape\n\n    dvshape = (\n        N,\n        PAD_H // (VH * HSTR),\n        PAD_W // (VW * WSTR),\n        VH * HSTR + HCAT,\n        VW * WSTR + WCAT,\n        IB,\n        CI,\n    )\n    ovshape = (1, OH // VH, OW // VW, CO // VC, VH, VW, VC)\n\n    if TPAD != 0 and RPAD != 0:\n        data_pad = pad(data_q, (0, TPAD, LPAD, 0, 0), (0, DPAD, RPAD, 0, CI_PAD), name=\"data_pad\")\n    elif CI_PAD != 0:\n        data_pad = pad(data_q, (0, 0, 0, 0, 0), (0, 0, 0, 0, CI_PAD), name=\"data_pad\")\n    else:\n        data_pad = data_q\n\n    data_vec = te.compute(\n        dvshape,\n        lambda n, h, w, vh, vw, b, ci: data_pad[n][h * VH * HSTR + vh][w * VW * WSTR + vw][b][ci],\n        name=\"data_vec\",\n    )\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    dh = te.reduce_axis((0, KH), name=\"dh\")\n    dw = te.reduce_axis((0, KW), name=\"dw\")\n    ib = te.reduce_axis((0, IB), name=\"ib\")\n    kb = te.reduce_axis((0, KB), name=\"kb\")\n\n    def _bipolar_conv(n, h, w, co, vh, vw, vc):\n        return te.sum(\n            (\n                tvm.tir.popcount(\n                    kernel_vec[co, dh, dw, kb, vc, ci].astype(\"uint16\")\n                    & data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ib, ci].astype(\"uint16\")\n                )\n                << (kb + ib).astype(\"uint16\")\n            ),\n            axis=[dh, dw, kb, ib, ci],\n        )\n\n    def _unipolar_conv(n, h, w, co, vh, vw, vc):\n        return te.sum(\n            (\n                (\n                    tvm.tir.popcount(\n                        kernel_vec[co, dh, dw, kb, vc, ci].astype(\"int16\")\n                        & data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ib, ci].astype(\"int16\")\n                    )\n                    - tvm.tir.popcount(\n                        ~kernel_vec[co, dh, dw, kb, vc, ci].astype(\"int16\")\n                        & data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ib, ci]\n                    ).astype(\"int16\")\n                )\n                << (kb + ib).astype(\"int16\")\n            ),\n            axis=[dh, dw, kb, ib, ci],\n        )\n\n    if unipolar:\n        conv_vec = te.compute(ovshape, _unipolar_conv, name=\"conv_vec\", tag=\"unipolar\")\n    else:\n        conv_vec = te.compute(ovshape, _bipolar_conv, name=\"conv_vec\", tag=\"bipolar\")\n\n    conv = te.compute(\n        oshape,\n        lambda n, h, w, co: conv_vec[\n            n, idxd(h, VH), idxd(w, VW), idxd(co, VC), idxm(h, VH), idxm(w, VW), idxm(co, VC)\n        ].astype(out_dtype),\n        name=\"conv\",\n        tag=\"spatial_bitserial_conv_nhwc\",\n    )\n\n    return conv\n\n\ndef _intrin_popcount(m, k_i, w_b, x_b, unipolar):\n    pack_dtype = \"uint8\"\n    w = te.placeholder((w_b, m, k_i), dtype=pack_dtype, name=\"w\")\n    x = te.placeholder(\n        (\n            x_b,\n            k_i,\n        ),\n        dtype=pack_dtype,\n        name=\"x\",\n    )\n    k = te.reduce_axis((0, k_i), name=\"k\")\n    bw = te.reduce_axis((0, w_b), name=\"bw\")\n    bx = te.reduce_axis((0, x_b), name=\"bx\")\n    if unipolar:\n        dtype = \"int16\"\n        z = te.compute(\n            (m,),\n            lambda i: te.sum(\n                (\n                    tvm.tir.popcount(w[bw, i, k].astype(dtype) & x[bx, k].astype(dtype))\n                    - tvm.tir.popcount(~w[bw, i, k].astype(dtype) & x[bx, k].astype(dtype))\n                )\n                << (bw + bx).astype(dtype),\n                axis=[bw, bx, k],\n            ),\n            name=\"z\",\n        )\n    else:\n        dtype = \"uint16\"\n        z = te.compute(\n            (m,),\n            lambda i: te.sum(\n                tvm.tir.popcount(w[bw, i, k].astype(dtype) & x[bx, k].astype(dtype))\n                << (bw + bx).astype(dtype),\n                axis=[bw, bx, k],\n            ),\n            name=\"z\",\n        )\n    Wb = tvm.tir.decl_buffer(\n        w.shape, w.dtype, name=\"W\", offset_factor=k_i, strides=[te.var(\"ldw\"), te.var(\"ldw\"), 1]\n    )  # stride can be inferred\n    Xb = tvm.tir.decl_buffer(\n        x.shape, x.dtype, name=\"X\", offset_factor=k_i, strides=[te.var(\"ldw\"), 1]\n    )\n    Zb = tvm.tir.decl_buffer(z.shape, z.dtype, name=\"Z\", offset_factor=1, strides=[1])\n\n    def _intrin_func(ins, outs):\n        ww, xx = ins\n        zz = outs[0]\n\n        args_2 = tvm.tir.const(2, \"uint32\")\n\n        if unipolar:\n            vpadd = \"llvm.arm.neon.vpadd.v8i8\"\n            vpadalu = \"llvm.arm.neon.vpadals.v16i8.v8i16\"\n            full_dtype = \"int8x16\"\n            half_dtype = \"int8x8\"\n            return_dtype = \"int16x8\"\n        else:\n            vpadd = \"llvm.arm.neon.vpadd.v8u8\"\n            vpadalu = \"llvm.arm.neon.vpadalu.v16u8.v8u16\"\n            full_dtype = \"uint8x16\"\n            half_dtype = \"uint8x8\"\n            return_dtype = \"uint16x8\"\n\n        def _instr(index):\n            irb = tvm.tir.ir_builder.create()\n            if index == 1:  # reduce reset\n                irb.emit(zz.vstore(0, tvm.tir.const(0, return_dtype)))\n                return irb.get()\n            # body and reduce update\n            cnts8 = [None] * 8\n            cnts4 = [None] * 4\n            cnts2 = [None] * 2\n            for bw in range(w_b):\n                for bx in range(x_b):\n                    if k_i == 16:\n                        for i in range(m):\n                            w_ = ww.vload([bw, i, 0], \"uint8x16\").astype(full_dtype)\n                            x_ = xx.vload([bx, 0], \"uint8x16\").astype(full_dtype)\n                            if unipolar:\n                                cnts = tvm.tir.popcount(w_ & x_) - tvm.tir.popcount(~w_ & x_)\n                            else:\n                                cnts = tvm.tir.popcount(w_ & x_)\n                            upper_half = tvm.tir.call_intrin(half_dtype, \"tir.vectorhigh\", cnts)\n                            lower_half = tvm.tir.call_intrin(half_dtype, \"tir.vectorlow\", cnts)\n                            cnts8[i] = upper_half + lower_half\n                        for i in range(m // 2):\n                            cnts4[i] = tvm.tir.call_llvm_pure_intrin(\n                                half_dtype, vpadd, args_2, cnts8[i * 2], cnts8[i * 2 + 1]\n                            )\n                        for i in range(m // 4):\n                            cnts2[i] = tvm.tir.call_llvm_pure_intrin(\n                                half_dtype, vpadd, args_2, cnts4[i * 2], cnts4[i * 2 + 1]\n                            )\n                        cnts = tvm.tir.call_intrin(\n                            full_dtype, \"tir.vectorcombine\", cnts2[0], cnts2[1]\n                        )\n                        shifted_cnts = cnts << tvm.tir.const(bw + bx, pack_dtype)\n                        out = tvm.tir.call_llvm_pure_intrin(\n                            return_dtype, vpadalu, args_2, zz.vload(0, return_dtype), shifted_cnts\n                        )\n                    else:  # ki == 8\n                        for i in range(m):\n                            w_ = ww.vload([bw, i, 0], \"uint8x8\").astype(half_dtype)\n                            x_ = xx.vload([bx, 0], \"uint8x8\").astype(half_dtype)\n                            if unipolar:\n                                cnts8[i] = tvm.tir.popcount(w_ & x_) - tvm.tir.popcount(~w_ & x_)\n                            else:\n                                cnts8[i] = tvm.tir.popcount(w_ & x_)\n                        for i in range(m // 2):\n                            cnts4[i] = tvm.tir.call_llvm_pure_intrin(\n                                half_dtype, vpadd, args_2, cnts8[i * 2], cnts8[i * 2 + 1]\n                            )\n                        for i in range(m // 4):\n                            cnts2[i] = tvm.tir.call_llvm_pure_intrin(\n                                half_dtype, vpadd, args_2, cnts4[i * 2], cnts4[i * 2 + 1]\n                            )\n                        cnts = tvm.tir.call_intrin(\n                            full_dtype, \"tir.vectorcombine\", cnts2[0], cnts2[1]\n                        )\n                        shifted_cnts = cnts << tvm.tir.const(bw + bx, pack_dtype)\n                        out = tvm.tir.call_llvm_pure_intrin(\n                            return_dtype, vpadalu, args_2, zz.vload(0, return_dtype), shifted_cnts\n                        )\n                    irb.emit(zz.vstore(0, out))\n            return irb.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        z.op, _intrin_func, binds={w: Wb, x: Xb, z: Zb}, default_buffer_params=buffer_params\n    )\n\n\n# ARM specific schedule that using custom microkernel\ndef _schedule_spatial_conv2d_nhwc(\n    cfg, s, data_pad, data_vec, kernel_vec, conv_out, output, last, unipolar\n):\n    _, _, _, _, _, IB, CI = data_vec.shape\n    _, KH, KW, KB, _, _ = kernel_vec.shape\n    KB = get_const_int(KB)\n    IB = get_const_int(IB)\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    ##### Schedule data padding and  packing\n    if data_pad is not None:\n        s[data_pad].compute_inline()\n\n    _, h, _, _, _, _, _ = s[data_vec].op.axis\n    cfg.define_split(\"tile_ah\", cfg.axis(h), num_outputs=2, max_factor=32)\n    oh, ih = cfg[\"tile_ah\"].apply(s, data_vec, h)\n    s[data_vec].parallel(oh)\n\n    #### Schedule kernel packing\n    co, _, _, _, _, _ = s[kernel_vec].op.axis\n    cfg.define_split(\"tile_bco\", cfg.axis(co), num_outputs=2, max_factor=32)\n    oco, ico = cfg[\"tile_bco\"].apply(s, kernel_vec, co)\n    s[kernel_vec].parallel(oco)\n\n    ##### Schedule Convolution\n    n, oh, ow, co, vh, vw, vc = s[conv_out].op.axis\n    kh, kw, kb, ib, ci = s[conv_out].op.reduce_axis\n\n    ci_o, ci_i = cfg[\"tile_ci\"].apply(s, conv_out, ci)\n    re_axes = cfg[\"reorder_0\"].apply(\n        s, conv_out, [n, oh, ow, co, vh, vw, kh, kw, ci_o, kb, ib, vc, ci_i]\n    )\n\n    # Use microkernel\n    kfactor = cfg[\"tile_ci\"].size[1]\n    if kfactor % 8 == 0:\n        pc = _intrin_popcount(VC, kfactor, KB, IB, unipolar)\n        s[conv_out].tensorize(kb, pc)\n\n    n, h, w, co = s[last].op.axis\n    co, vc = cfg[\"tile_co\"].apply(s, last, co)\n    oh, vh = cfg[\"tile_oh\"].apply(s, last, h)\n    ow, vw = cfg[\"tile_ow\"].apply(s, last, w)\n    s[last].reorder(n, oh, ow, co, vh, vw, vc)\n    s[last].vectorize(vc)\n    if last != output:\n        s[output].compute_inline()\n\n    s[conv_out].compute_at(s[last], co)\n    s[last].parallel(oh)\n    return s\n\n\n@autotvm.register_topi_schedule(\"bitserial_conv2d_nhwc.arm_cpu\")\ndef schedule_bitserial_conv2d_nhwc(cfg, outs):\n    \"\"\"Arm cpu schedule for bitserial conv2d\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"spatial_bitserial_conv_nhwc\" in op.tag:\n            output = op.output(0)\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[0]\n            data_vec = conv_out.op.input_tensors[1]\n            data_q = data_vec.op.input_tensors[0]\n            data = data_q.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data_q.op, te.tensor.ComputeOp) and \"pad\" in data_q.op.tag:\n                data_pad = data_q\n                data_q = data\n                data = data.op.input_tensors[0]\n            unipolar = \"unipolar\" in conv_out.op.tag\n            _schedule_spatial_conv2d_nhwc(\n                cfg, s, data_pad, data_vec, kernel_vec, conv_out, output, outs[0], unipolar\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@bitserial_conv2d_legalize.register(\"arm_cpu\")\ndef _bitserial_conv2d_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes Bitserial Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n\n    # Fix different kernel layouts where possible.\n    if attrs[\"data_layout\"] == \"NHWC\":\n        data, kernel = inputs\n        if len(kernel.data.shape) == 4:\n            # HWIO layout is expected for NHWC input.\n            if attrs[\"kernel_layout\"] == \"HWOI\":\n                # Handle HWOI layout. This is common in TF depthwise conv2d graph.\n                kernel = relay.transpose(kernel, axes=(0, 1, 3, 2))\n            elif attrs[\"kernel_layout\"] == \"OIHW\":\n                kernel = relay.transpose(kernel, axes=(2, 3, 1, 0))\n            ## Set new attrs for the tranposed conv.\n            new_attrs = {k: attrs[k] for k in attrs.keys()}\n            new_attrs[\"kernel_layout\"] = \"HWIO\"\n\n            conv = relay.nn.bitserial_conv2d(data, kernel, **new_attrs)\n            return conv\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/bitserial_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, invalid-name, too-many-locals, too-many-arguments\n\"\"\"Schedule for bitserial dense operator.\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.topi.utils import get_const_tuple\nfrom .. import tag\nfrom .bitserial_conv2d import _intrin_popcount\nfrom ..nn.pad import pad\nfrom ..nn.bitserial_util import bitpack, binary_op_multiplier\n\n\n@autotvm.register_topi_compute(\"bitserial_dense.arm_cpu\")\ndef bitserial_dense(cfg, data, weight, data_bits, weight_bits, pack_dtype, out_dtype, unipolar):\n    \"\"\"The default implementation of bitserial dense in topi.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    data_packed = bitpack(data, data_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    if len(weight.shape) == 2:\n        weight_packed = bitpack(weight, weight_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    else:\n        weight_packed = weight\n\n    batch, DB, in_dim = get_const_tuple(data_packed.shape)\n    out_dim, WB, in_dim = get_const_tuple(weight_packed.shape)\n\n    # Pad Inputs so that microkernel can be used\n    # out_dim and in_dim need to be multiples of 8\n    if out_dim % 8 != 0:\n        out_dim_pad = out_dim % 8\n        data_packed = pad(data_packed, [0, 0, 0], [out_dim_pad, 0, 0], name=\"PaddedInput\")\n        out_dim += out_dim_pad\n\n    ######## Search space\n\n    x, y = cfg.axis(batch), cfg.axis(out_dim)\n    db, wb, k = cfg.reduce_axis(DB), cfg.reduce_axis(WB), cfg.reduce_axis(in_dim)\n\n    ko, ki = cfg.define_split(\n        \"tile_k\", k, num_outputs=2, filter=lambda xx: xx.size[-1] == 8 or xx.size[-1] == 16\n    )\n    xo, xi = cfg.define_split(\"tile_x\", x, num_outputs=2)\n    yo, yi = cfg.define_split(\"tile_y\", y, num_outputs=2, filter=lambda xx: xx.size[-1] == 8)\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [yo, xo, ko, xi, wb, db, yi, ki],\n        policy=\"candidate\",\n        candidate=[\n            [yo, xo, ko, xi, wb, db, yi, ki],\n            [yo, xo, xi, ko, wb, db, yi, ki],\n            [yo, xo, ko, xi, wb, db, yi, ki],\n        ],\n    )\n\n    ###### Compute rule\n    VY = cfg[\"tile_y\"].size[-1]\n    VK = cfg[\"tile_k\"].size[-1]\n\n    wvshape = (out_dim // VY, in_dim // VK, WB, VY, VK)\n    oshape = (batch, out_dim)\n\n    k = te.reduce_axis((0, in_dim), name=\"k\")\n    db = te.reduce_axis((0, DB), name=\"db\")\n    wb = te.reduce_axis((0, WB), name=\"wb\")\n\n    # Tile data and weights\n    weight_vec = te.compute(\n        wvshape,\n        lambda yo, ko, wb, vy, vk: weight_packed[yo * VY + vy][wb][ko * VK + vk],\n        name=\"weight_vec\",\n    )\n    matmul_unipolar = te.compute(\n        oshape,\n        lambda x, y: te.sum(\n            (\n                tvm.tir.popcount(\n                    weight_vec[y // VY, k // VK, wb, y % VY, k % VK].astype(out_dtype)\n                    & data_packed[x, db, k].astype(out_dtype)\n                )\n                - tvm.tir.popcount(\n                    ~weight_vec[y // VY, k // VK, wb, y % VY, k % VK].astype(out_dtype)\n                    & data_packed[x, db, k].astype(out_dtype)\n                )\n            )\n            << (wb + db).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense_unipolar\",\n    )\n\n    matmul = te.compute(\n        oshape,\n        lambda x, y: te.sum(\n            tvm.tir.popcount(\n                weight_vec[y // VY, k // VK, wb, y % VY, k % VK].astype(out_dtype)\n                & data_packed[x, db, k].astype(out_dtype)\n            )\n            << (wb + db).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense\",\n    )\n\n    cfg.add_flop(batch * out_dim * in_dim * binary_op_multiplier(pack_dtype))\n\n    if unipolar:\n        return matmul_unipolar\n    return matmul\n\n\n@autotvm.register_topi_schedule(\"bitserial_dense.arm_cpu\")\ndef schedule_bitserial_dense(cfg, outs):\n    \"\"\"Schedule for binary_dense.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of bitserial dense operator.\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for bitserial_dense.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(cfg, s, data_vec, weight_vec, output, unipolar):\n\n        z, k, _, y, x = s[weight_vec].op.axis\n        s[weight_vec].parallel(z)\n        s[weight_vec].vectorize(x)\n\n        x, y = s[output].op.axis\n        wb, db, k = s[output].op.reduce_axis\n        _, DB, _ = get_const_tuple(data_vec.shape)\n        _, _, WB, _, _ = get_const_tuple(weight_vec.shape)\n\n        yo, yi = cfg[\"tile_y\"].apply(s, output, y)\n        xo, xi = cfg[\"tile_x\"].apply(s, output, x)\n        ko, ki = cfg[\"tile_k\"].apply(s, output, k)\n\n        cfg[\"reorder_0\"].apply(s, output, [yo, xo, ko, xi, wb, db, yi, ki])\n\n        fused = s[output].fuse(xo, yo)\n        s[output].parallel(fused)\n\n        nfactor = cfg[\"tile_y\"].size[-1]\n        kfactor = cfg[\"tile_k\"].size[-1]\n        if nfactor % 8 == 0:\n            pc = _intrin_popcount(nfactor, kfactor, WB, DB, unipolar)\n            s[output].tensorize(wb, pc)\n\n        return s\n\n    def traverse(op):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag) or \"elemwise\" in op.tag:\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n\n        elif op.tag == \"bitserial_dense\" or \"bitserial_dense_unipolar\":\n            output = op.output(0)\n            weight_vec = op.input_tensors[0]\n\n            data_vec = op.input_tensors[1]\n            data = data_vec.op.input_tensors[0]\n            if \"QuantizeInput\" in data.op.name:\n                data = data.op.input_tensors[0]\n            unipolar = output.op.tag == \"bitserial_dense_unipolar\"\n            _schedule(cfg, s, data_vec, weight_vec, output, unipolar)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % op.tag)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, no-else-return, unused-argument, import-outside-toplevel\n\"\"\"Conv1D schedule for ARM CPU\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom tvm import autotvm\n\nfrom .mprofile.dsp.conv1d import (\n    conv1d_nwc_dsp_compute,\n    conv1d_nwc_dsp_schedule,\n)\n\n\n@autotvm.register_topi_compute(\"conv1d_nwc_dsp.arm_cpu\")\ndef conv1d_nwc_dsp(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv1d with v7e-m DSP instructions.\"\"\"\n    return conv1d_nwc_dsp_compute(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv1d_nwc_dsp.arm_cpu\")\ndef schedule_conv1d_nwc_dsp(cfg, outs):\n    return conv1d_nwc_dsp_schedule(cfg, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, no-else-return, unused-argument, import-outside-toplevel\n\"\"\"Conv2D schedule for ARM CPU\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nimport tvm.contrib.nnpack\n\nfrom ..utils import traverse_inline, get_const_tuple\nfrom .. import nn\nfrom ..nn.utils import get_const_int, get_pad_tuple\nfrom ..nn.winograd_util import winograd_transform_matrices\nfrom .conv2d_spatial_pack import (\n    conv2d_spatial_pack_nchw,\n    conv2d_spatial_pack_nhwc,\n    schedule_conv2d_spatial_pack_nchw,\n    schedule_conv2d_spatial_pack_nhwc,\n)\nfrom .mprofile.dsp.conv2d import (\n    conv2d_nhwc_dsp_compute,\n    conv2d_nhwc_dsp_schedule,\n)\nfrom .mprofile.dsp.tensordot_conv2ds import (\n    conv2d_nhwc_ohwi_dsp_compute,\n    tensordot_conv2ds_schedule,\n)\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_spatial_pack.arm_cpu\")\ndef conv2d_nchw_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with NCHW layout\"\"\"\n    return conv2d_spatial_pack_nchw(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=2\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_spatial_pack.arm_cpu\")\ndef schedule_conv2d_nchw_spatial_pack(cfg, outs):\n    \"\"\"Create schedule for conv2d_nchw\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        # schedule conv2d\n        if \"spatial_conv2d_output\" in op.tag:\n            output = op.output(0)\n            conv = op.input_tensors[0]\n\n            data_vec = conv.op.input_tensors[0]\n            data_pad = data_vec.op.input_tensors[0]\n            s[data_pad].compute_inline()\n\n            kernel_vec = conv.op.input_tensors[1]\n            if kernel_vec.op.name == \"kernel_vec\":\n                kernel = kernel_vec.op.input_tensors[0]\n            else:\n                kernel = kernel_vec\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            schedule_conv2d_spatial_pack_nchw(cfg, s, data_vec, kernel_vec, conv, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_spatial_pack.arm_cpu\")\ndef conv2d_nhwc_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with NHWC layout\"\"\"\n    return conv2d_spatial_pack_nhwc(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_spatial_pack.arm_cpu\")\ndef schedule_conv2d_nhwc_spatial_pack(cfg, outs):\n    \"\"\"Create schedule for conv2d_nhwc\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"spatial_conv_output_NHWC\" in op.tag:\n            schedule_conv2d_spatial_pack_nhwc(cfg, s, op, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd.arm_cpu\")\ndef conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d_nchw layout using Winograd with weight transform\"\"\"\n    tile_size = 4\n    return _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd.arm_cpu\")\ndef schedule_conv2d_nchw_winograd(cfg, outs):\n    \"\"\"Create schedule for conv2d_nchw_winograd\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"winograd_conv2d_output\" in op.tag:\n            output = op.output(0)\n            _schedule_winograd(cfg, s, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size):\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n    if not isinstance(IH, int) or not isinstance(IW, int):\n        raise RuntimeError(\"ARM winograd conv2d doesn't support dynamic input height or width.\")\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    if len(kernel.shape) == 4:\n        if dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_h, dilation_w))\n        pre_computed = False\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n    else:\n        assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n        pre_computed = True\n        H_CAT, W_CAT, CO, CI, VC = get_const_tuple(kernel.shape)\n        CO *= VC\n        KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW))\n\n    assert KH == 3 and KW == 3 and HSTR == 1 and WSTR == 1\n    data_pad = nn.pad(data, (0, 0, pt, pl), (0, 0, pb, pr), name=\"data_pad\")\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    r = KW\n    m = tile_size\n    alpha = m + r - 1\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    K = CO\n    C = CI\n\n    H = (IH + pt + pb - 3) // HSTR + 1\n    W = (IW + pl + pr - 3) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n\n    # TODO(@kevinthesun): Support tuning/optimization for dynamic shape.\n    tile_p = P if isinstance(N, int) else nH * nW\n    cfg.define_split(\"tile_p\", cfg.axis(tile_p), num_outputs=2, filter=lambda x: x.size[-1] <= 16)\n    cfg.define_split(\"tile_k\", cfg.axis(K), num_outputs=2, filter=lambda x: x.size[-1] <= 16)\n    VP = cfg[\"tile_p\"].size[-1]\n    VK = cfg[\"tile_k\"].size[-1]\n\n    # pack input tile\n    input_tile = te.compute(\n        (C, idxd(P, VP), alpha, alpha, VP),\n        lambda c, b, eps, nu, bb: data_pad[\n            idxd(b * VP + bb, nH * nW),\n            c,\n            idxm(idxd(b * VP + bb, nW), nH) * m + eps,\n            idxm(b * VP + bb, nW) * m + nu,\n        ],\n        name=\"d\",\n    )\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        VC = cfg[\"tile_k\"].size[-1]\n        kvshape = (KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), CI, VC)\n        U = tvm.te.placeholder(kvshape, kernel.dtype, name=\"U\")\n    else:\n        # transform kernel\n        if pre_computed:\n            U = kernel\n        else:\n            r_kh = te.reduce_axis((0, KH), \"r_kh\")\n            r_kw = te.reduce_axis((0, KW), \"r_kw\")\n            U = te.compute(\n                (alpha, alpha, idxd(K, VK), C, VK),\n                lambda eps, nu, k, c, kk: te.sum(\n                    kernel[k * VK + kk][c][r_kh][r_kw].astype(out_dtype)\n                    * G[eps][r_kh]\n                    * G[nu][r_kw],\n                    axis=[r_kh, r_kw],\n                ),\n                name=\"U\",\n            )\n\n    # transform image\n    r_eps = te.reduce_axis((0, alpha), \"r_eps\")\n    r_nu = te.reduce_axis((0, alpha), \"r_nu\")\n    V = te.compute(\n        (alpha, alpha, idxd(P, VP), C, VP),\n        lambda eps, nu, b, c, bb: te.sum(\n            input_tile[c][b][r_eps][r_nu][bb].astype(out_dtype) * B[r_eps][eps] * B[r_nu][nu],\n            axis=[r_eps, r_nu],\n        ),\n        name=\"V\",\n    )\n\n    # batch gemm\n    c = te.reduce_axis((0, C), name=\"c\")\n    M = te.compute(\n        (alpha, alpha, K, P),\n        lambda eps, nu, k, b: te.sum(\n            U[eps][nu][idxd(k, VK)][c][idxm(k, VK)] * V[eps][nu][idxd(b, VP)][c][idxm(b, VP)],\n            axis=c,\n        ),\n        name=\"M\",\n    )\n\n    # inverse transform\n    r_eps = te.reduce_axis((0, alpha), \"r_eps\")\n    r_nu = te.reduce_axis((0, alpha), \"r_nu\")\n    Y = te.compute(\n        (K, P, m, m),\n        lambda k, b, vh, vw: te.sum(\n            M[r_eps][r_nu][k][b] * A[r_eps][vh] * A[r_nu][vw], axis=[r_eps, r_nu]\n        ),\n        name=\"Y\",\n    )\n\n    # unpack output\n    output = te.compute(\n        (N, K, H, W),\n        lambda n, k, h, w: Y[k][n * nH * nW + idxd(h, m) * nW + idxd(w, m), idxm(h, m), idxm(w, m)],\n        name=\"output\",\n        tag=\"winograd_conv2d_output\",\n    )\n\n    # we have to manually assign effective GFLOP for winograd\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * K * H * W * KH * KW * C)\n    return output\n\n\ndef _schedule_winograd(cfg, s, output, last):\n    Y = output.op.input_tensors[0]\n    M, A = Y.op.input_tensors\n    U, V = M.op.input_tensors\n    d, B = V.op.input_tensors\n    data_pad = d.op.input_tensors[0]\n\n    # padding\n    s[data_pad].compute_inline()\n\n    # pack input tiles\n    s[d].compute_inline()\n\n    # transform kernel\n    if isinstance(U.op, tvm.te.ComputeOp):\n        kernel, G = U.op.input_tensors\n        s[G].compute_inline()\n        (\n            eps,\n            nu,\n            k,\n            c,\n            kk,\n        ) = s[U].op.axis\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # kernel transformation will be pre-computed during compilation, so we skip\n            # this part to make tuning records correct\n            s[U].pragma(eps, \"debug_skip_region\")\n        else:\n            r_kh, r_kw = s[U].op.reduce_axis\n            s[U].reorder(k, c, eps, nu, r_kh, r_kw, kk)\n            for axis in [eps, nu, r_kh, r_kw]:\n                s[U].unroll(axis)\n            s[U].vectorize(kk)\n            s[U].parallel(k)\n\n        if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n            s[kernel].compute_inline()\n\n    # transform image\n    DD = s.cache_read(d, \"global\", [V])\n    s[B].compute_inline()\n    eps, nu, b, c, bb = s[V].op.axis\n    r_eps, r_nu = s[V].op.reduce_axis\n    s[V].reorder(b, c, eps, nu, r_eps, r_nu, bb)\n    for axis in [eps, nu, r_eps, r_nu]:\n        s[V].unroll(axis)\n    s[DD].compute_at(s[V], c)\n    s[V].vectorize(bb)\n    s[V].parallel(b)\n\n    # batch gemm\n    eps, nu, k, b = s[M].op.axis\n    c = s[M].op.reduce_axis[0]\n    cfg.define_split(\"tile_c\", c, num_outputs=2, filter=lambda x: x.size[-1] <= 16)\n    co, ci = cfg[\"tile_c\"].apply(s, M, c)\n    xo, xi = cfg[\"tile_p\"].apply(s, M, b)\n    s[M].reorder(eps, nu, xo, co, k, ci, xi)\n    cfg.define_annotate(\"ann_reduce\", [ci], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [k, xi], policy=\"try_unroll_vec\")\n    cfg[\"ann_reduce\"].apply(s, M, [ci], axis_lens=[cfg[\"tile_c\"].size[-1]], max_unroll=16, cfg=cfg)\n    cfg[\"ann_spatial\"].apply(s, M, [k, xi])\n\n    # inverse transform\n    s[A].compute_inline()\n    k, b, vh, vw = s[Y].op.axis\n    r_eps, r_nu = s[Y].op.reduce_axis\n    for axis in [vh, vw, r_eps, r_nu]:\n        s[Y].unroll(axis)\n\n    # output\n    n, co, h, w = s[last].op.axis\n    co, coi = cfg[\"tile_k\"].apply(s, last, co)\n    p = s[last].fuse(n, co)\n    s[M].compute_at(s[last], p)\n    s[last].parallel(p)\n\n    MM = s.cache_read(M, \"global\", [Y])\n    m = get_const_int(V.shape[0]) + 1 - 3\n    ho, wo, hi, wi = s[last].tile(h, w, m, m)\n    s[Y].compute_at(s[last], wo)\n    s[MM].compute_at(s[last], wo)\n\n    if output != last:\n        s[output].compute_inline()\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd_nnpack.arm_cpu\")\ndef conv2d_nchw_winograd_nnpack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d_nchw using nnpack Winograd implementation\"\"\"\n    dtype = data.dtype\n    if dtype == \"float32\":\n        return _conv2d_arm_cpu_winograd_nnpack(\n            cfg,\n            data,\n            kernel,\n            strides,\n            padding,\n            dilation,\n            out_dtype,\n            tvm.contrib.nnpack.ConvolutionAlgorithm.WT_8x8,\n        )\n    elif dtype == \"float16\":\n        return _conv2d_arm_cpu_winograd_nnpack(\n            cfg,\n            data,\n            kernel,\n            strides,\n            padding,\n            dilation,\n            out_dtype,\n            tvm.contrib.nnpack.ConvolutionAlgorithm.WT_8x8_FP16,\n        )\n    else:\n        raise ValueError(\"Unsupported data type {} for conv2d winograd nnpack\".format(dtype))\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd_nnpack.arm_cpu\")\ndef schedule_conv2d_nchw_winograd_nnpack(cfg, outs):\n    \"\"\"Create schedule for conv2d_nchw_winograd_nnpack\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"winograd_nnpack_conv2d_output\" in op.tag:\n            output = op.output(0)\n            _schedule_winograd_nnpack(cfg, s, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _conv2d_arm_cpu_winograd_nnpack(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, convolution_algorithm\n):\n    \"\"\"TOPI compute callback. Use winograd NNPACK template\"\"\"\n    N, CI, IH, IW = get_const_tuple(data.shape)\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    assert (dilation_h, dilation_w) == (1, 1)\n    assert len(kernel.shape) == 4\n    CO, _, KH, KW = get_const_tuple(kernel.shape)\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW))\n\n    assert (\n        KH == 3\n        and KW == 3\n        and pt == 1\n        and pb == 1\n        and pl == 1\n        and pr == 1\n        and HSTR == 1\n        and WSTR == 1\n    )\n    H = (IH + pt + pb - 3) // HSTR + 1\n    W = (IW + pl + pr - 3) // WSTR + 1\n\n    cfg.define_knob(\"winograd_nnpack_algorithm\", [convolution_algorithm])\n\n    assert N == 1\n    with tvm.te.tag_scope(\"winograd_nnpack_conv2d_weight_transform\"):\n        transformed_kernel = tvm.contrib.nnpack.convolution_inference_weight_transform(\n            kernel, algorithm=cfg[\"winograd_nnpack_algorithm\"].val\n        )\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            transformed_kernel = te.compute(transformed_kernel.shape, lambda *args: 0.0)\n\n    with tvm.te.tag_scope(\"winograd_nnpack_conv2d_output\"):\n        output = tvm.contrib.nnpack.convolution_inference_without_weight_transform(\n            data,\n            transformed_kernel,\n            bias=None,\n            padding=[pt, pb, pl, pr],\n            stride=[HSTR, WSTR],\n            algorithm=cfg[\"winograd_nnpack_algorithm\"].val,\n        )\n\n    # we have to manually assign effective GFLOP for winograd\n    cfg.add_flop(2 * N * CI * H * W * KH * KW * CO)\n    return output\n\n\ndef _schedule_winograd_nnpack(cfg, s, output, last):\n    # Could have bias.\n\n    (X, TK) = output.op.input_tensors[:2]\n\n    # transform kernel\n    assert isinstance(TK.op, (te.tensor.ComputeOp, te.tensor.ExternOp, te.tensor.PlaceholderOp))\n    if autotvm.GLOBAL_SCOPE.in_tuning and isinstance(TK.op, te.tensor.ComputeOp):\n        # kernel transformation will be pre-computed during compilation, so we skip\n        # this part to make tuning records correct\n        s[TK].pragma(s[TK].op.axis[0], \"debug_skip_region\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd_nnpack_without_weight_transform.arm_cpu\")\ndef conv2d_nchw_winograd_nnpack_without_weight_transform(\n    cfg, data, transformed_kernel, bias, strides, padding, dilation, out_dtype\n):\n    \"\"\"Compute conv2d_nchw using NNPack winograd without weight transform\"\"\"\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    assert (dilation_h, dilation_w) == (1, 1)\n    assert len(transformed_kernel.shape) == 4\n    CO, _, _, _ = get_const_tuple(transformed_kernel.shape)\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    KH, KW = 3, 3\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW))\n\n    assert (\n        KH == 3\n        and KW == 3\n        and pt == 1\n        and pb == 1\n        and pl == 1\n        and pr == 1\n        and HSTR == 1\n        and WSTR == 1\n    )\n    H = (IH + pt + pb - 3) // HSTR + 1\n    W = (IW + pl + pr - 3) // WSTR + 1\n\n    assert N == 1\n    with tvm.te.tag_scope(\"winograd_nnpack_conv2d_output\"):\n        output = tvm.contrib.nnpack.convolution_inference_without_weight_transform(\n            data=data,\n            transformed_kernel=transformed_kernel,\n            bias=bias,\n            padding=[pt, pb, pl, pr],\n            stride=[HSTR, WSTR],\n            algorithm=cfg[\"winograd_nnpack_algorithm\"].val,\n        )\n\n    # we have to manually assign effective GFLOP for winograd\n    cfg.add_flop(2 * N * CI * H * W * KH * KW * CO)\n    return output\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd_nnpack_without_weight_transform.arm_cpu\")\ndef schedule_conv2d_nchw_winograd_nnpack_without_weight_transform(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"winograd_nnpack_conv2d_output\" in op.tag:\n            output = op.output(0)\n            _schedule_winograd_nnpack(cfg, s, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_dsp.arm_cpu\")\ndef conv2d_nhwc_dsp(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d_nhwc with v7e-m DSP instructions.\"\"\"\n    return conv2d_nhwc_dsp_compute(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_dsp.arm_cpu\")\ndef schedule_conv2d_nhwc_dsp(cfg, outs):\n    \"\"\"Create schedule for conv2d_nhwc_dsp\"\"\"\n    return conv2d_nhwc_dsp_schedule(cfg, outs)\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_ohwi_dsp.arm_cpu\")\ndef conv2d_nhwc_ohwi_dsp(cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype):\n    \"\"\"Compute conv2d_nhwc_ohwi with v7e-m DSP instructions and the tensordot kernel.\"\"\"\n    return conv2d_nhwc_ohwi_dsp_compute(\n        cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_ohwi_dsp.arm_cpu\")\ndef schedule_conv2d_nhwc_ohwi_dsp(cfg, outs):\n    \"\"\"Create schedule for conv2d_nhwc_ohwi.\"\"\"\n    return tensordot_conv2ds_schedule(cfg, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D alter op and legalize functions for arm cpu\"\"\"\n\nimport logging\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\n\nfrom ..nn import conv2d_alter_layout, conv2d_legalize\nfrom ..utils import get_const_tuple\nfrom ..x86.conv2d import _get_default_config as _get_x86_default_config\nfrom ..x86.conv2d_int8 import _get_default_config_int8\nfrom .conv2d_int8 import is_int8_hw_support\nfrom .arm_utils import get_tiling_B_interleaved_t\nfrom ..generic.conv2d import conv2d_alter_int8_common\nfrom .mprofile.dsp.micro_kernel.common import num_simd_lanes_per_word\n\nlogger = logging.getLogger(\"topi\")\n\n\ndef interleave_transpose_weights(inputs, data, kernel, interleave_A):\n    \"\"\"Transform the weight matrix by reshaping, interleaving and transposing it\n\n    Parameters\n    ----------\n    inputs : tvm.relay.Expr\n        Grouped input symbols\n    data :\n        Input shape and dtype\n    kernel :\n        Input shape and dtype\n    interleave_A: indicates if we expect matrix A to be interleaved\n\n    Returns\n    ----------\n    new_kernel : tvm.te.placeholder\n                 A placeholder with the new shape\n    new_kernel_expr : tvm.relay.Expr\n                The relay expression of the weights\n    \"\"\"\n    assert (\n        data.dtype == \"int8\"\n        and kernel.dtype == \"int8\"\n        or data.dtype == \"uint8\"\n        and kernel.dtype == \"uint8\"\n    )\n\n    KH, KW, IC, OC = get_const_tuple(kernel.shape)\n    K = KH * KW * IC\n    N = OC\n\n    # Get tiling information for the interleaved transposed version of B\n    tile_rows_B, tile_cols_B = get_tiling_B_interleaved_t(interleave_A)\n\n    pad_K = 0\n    pad_N = 0\n\n    if N % tile_rows_B != 0:\n        pad_N = tile_rows_B - (N % tile_rows_B)\n    if K % tile_cols_B != 0:\n        pad_K = tile_cols_B - (K % tile_cols_B)\n\n    N_padded = N + pad_N\n    K_padded = K + pad_K\n    new_kernel_expr = relay.nn.contrib_conv2d_gemm_weight_transform(\n        inputs[1], tile_rows_B, tile_cols_B\n    )\n    new_kernel = te.placeholder(\n        (N_padded // tile_rows_B, K_padded // tile_cols_B, tile_rows_B, tile_cols_B), kernel.dtype\n    )\n    return new_kernel, new_kernel_expr\n\n\n@conv2d_alter_layout.register([\"arm_cpu\"])\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n\n    _, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n    if workload is None:\n        # The best implementation is not an AutoTVM template,\n        # we then assume it's not necessary to alter this op.\n        return None\n    cfg = dispatch_ctx.query(target, workload)\n\n    topi_tmpl = workload[0]\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    strides = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data, kernel = tinfos\n    out_dtype = out_type.dtype\n\n    # Extract data types\n    data_tensor, kernel_tensor = tinfos\n    data_dtype = data_tensor.dtype\n    kernel_dtype = kernel_tensor.dtype\n\n    idxd = tvm.tir.indexdiv\n\n    if topi_tmpl == \"depthwise_conv2d_nhwc_dsp.arm_cpu\":\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWOI\"\n\n        # We are not able to check if inputs[1] (the kernel) is a constant in the\n        # strategy function, so as a stopgap solution we use an assert here.\n        assert isinstance(\n            inputs[1], relay.Constant\n        ), \"depthwise_conv2d_nhwc_dsp.arm_cpu requires kernel be a relay Constant\"\n\n        channels = get_const_tuple(data.shape)[3]\n        KH, KW, _, _ = get_const_tuple(kernel.shape)\n        simd_lanes = num_simd_lanes_per_word(data.dtype)\n\n        HWOI_kernel_np = inputs[1].data.numpy()\n        CHWc_kernel_np = np.zeros((channels // simd_lanes, KH, KW, simd_lanes), dtype=kernel.dtype)\n        for i in range(channels // simd_lanes):\n            CHWc_kernel_np[i] = HWOI_kernel_np[:, :, simd_lanes * i : simd_lanes * (i + 1), 0]\n        reshaped_new_kernel = CHWc_kernel_np.reshape((KH, KW, channels, 1))\n\n        # Store the same config for the altered operator (workload)\n        new_data = data\n        new_kernel = te.placeholder((KH, KW, channels, 1), dtype=kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"depthwise_conv2d_nhwc_dsp.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.conv2d(\n            inputs[0],\n            relay.Constant(tvm.nd.array(reshaped_new_kernel)),\n            **new_attrs,\n        )\n\n    # Only microTVM does layout alteration for NHWC layout with real data types\n    if data_layout == \"NHWC\" and data_dtype not in [\"uint8\", \"int8\"]:\n        return None\n\n    if topi_tmpl == \"conv2d_nchw_spatial_pack.arm_cpu\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        VC = cfg[\"tile_co\"].size[-1]\n\n        new_attrs[\"kernel_layout\"] = \"OIHW%do\" % VC\n\n        new_data = data\n        new_kernel = te.placeholder((idxd(CO, VC), CI, KH, KW, VC), dtype=kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_spatial_pack.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_nhwc_spatial_pack.arm_cpu\":\n        assert (\n            data.dtype == \"int8\"\n            and kernel.dtype == \"int8\"\n            or data.dtype == \"uint8\"\n            and kernel.dtype == \"uint8\"\n        )\n\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n\n        data_expr, kernel_expr = inputs\n\n        data_int16 = relay.cast(data_expr, dtype=\"int16\")\n        kernel_int16 = relay.cast(kernel_expr, dtype=\"int16\")\n\n        new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n        new_data = te.placeholder(data.shape, \"int16\")\n        new_kernel = te.placeholder(kernel.shape, \"int16\")\n\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nhwc_spatial_pack.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.conv2d(data_int16, kernel_int16, **new_attrs)\n\n    if topi_tmpl == \"conv2d_nchw_winograd.arm_cpu\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        VC = cfg[\"tile_k\"].size[-1]\n        tile_size = 4\n\n        weight_expr = inputs[1]\n        weight_expr = relay.nn.contrib_conv2d_winograd_weight_transform(\n            weight_expr, tile_size=tile_size\n        )\n        weight_expr = relay.reshape(\n            weight_expr, newshape=(KH + tile_size - 1, KW + tile_size - 1, CO // VC, VC, CI)\n        )\n        weight_expr = relay.transpose(weight_expr, axes=[0, 1, 2, 4, 3])\n\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n\n        new_data = data\n        new_kernel = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), CI, VC), kernel.dtype\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_winograd.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight_expr, **new_attrs\n        )\n\n    if topi_tmpl == \"conv2d_nchw_winograd_nnpack.arm_cpu\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        new_attrs[\"channels\"] = CO\n\n        # pre-compute winograd_nnpack transform\n        # for winograd_nnpack_fp16, the precompute prune pass must run on device,\n        # where float16 is supported\n        weight_dtype = \"float32\"\n        weight_expr = inputs[1]\n        transformed_weight = relay.nn.contrib_conv2d_winograd_nnpack_weight_transform(\n            weight_expr,\n            convolution_algorithm=cfg[\"winograd_nnpack_algorithm\"].val,\n            out_dtype=weight_dtype,\n        )\n\n        new_data = data\n        new_kernel = te.placeholder((CO, CI, 8, 8), \"float32\")\n\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, None, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_winograd_nnpack_without_weight_transform.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], transformed_weight, **new_attrs\n        )\n\n    if topi_tmpl == \"depthwise_conv2d_nchw_spatial_pack.arm_cpu\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, M, KH, KW = get_const_tuple(kernel.shape)\n        VC = cfg[\"tile_co\"].size[-1]\n\n        new_attrs[\"kernel_layout\"] = \"OIHW%do\" % (cfg[\"tile_co\"].size[-1])\n\n        # Store the same config for the altered operator (workload)\n        new_data = data\n        new_kernel = te.placeholder((idxd(CO, VC), M, KH, KW, VC), dtype=kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"depthwise_conv2d_nchw_spatial_pack.arm_cpu\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_NCHWc.x86\":\n        # Converting NCHW to NCHWc.\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        if cfg.is_fallback:\n            _get_x86_default_config(\n                cfg,\n                data_tensor,\n                kernel_tensor,\n                strides,\n                padding,\n                dilation,\n                out_dtype,\n                False,\n                data_layout,\n            )\n        batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n        out_channel, _, kh, kw = get_const_tuple(kernel_tensor.shape)\n        ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n        # update new attrs\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        # (oc, ic, h, w) -> (OC, IC, h, w, ic, oc)\n        new_attrs[\"kernel_layout\"] = \"OIHW%di%do\" % (ic_bn, oc_bn)\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        # Store altered operator's config\n        new_data = te.placeholder(\n            (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n        )\n        new_kernel = te.placeholder(\n            (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn, oc_bn),\n            dtype=kernel_tensor.dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_kernel,\n                strides,\n                padding,\n                dilation,\n                new_attrs[\"data_layout\"],\n                new_attrs[\"out_layout\"],\n                out_dtype,\n            ],\n            topi_tmpl,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    if topi_tmpl == \"depthwise_conv2d_NCHWc.x86\":\n        # Converting NCHW to NCHWc.\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        if cfg.is_fallback:\n            _get_x86_default_config(\n                cfg, data_tensor, kernel_tensor, strides, padding, out_dtype, True, data_layout\n            )\n\n        batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n        out_channel, channel_multiplier, kh, kw = get_const_tuple(kernel_tensor.shape)\n        ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n        assert channel_multiplier == 1\n\n        # update new attrs\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        new_attrs[\"kernel_layout\"] = \"OIHW1i%do\" % oc_bn\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        # Store altered operator's config.\n        new_data = te.placeholder(\n            (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n        )\n        new_kernel = te.placeholder((out_channel // oc_bn, 1, kh, kw, 1, oc_bn), dtype=kernel_dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_kernel,\n                strides,\n                padding,\n                dilation,\n                new_attrs[\"data_layout\"],\n                new_attrs[\"out_layout\"],\n                out_dtype,\n            ],\n            topi_tmpl,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_depthwise_conv2d_nchwc(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_NCHWc_int8.arm_cpu\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n        out_channel, _, kh, kw = get_const_tuple(kernel_tensor.shape)\n\n        n_elems = 4\n\n        if cfg.is_fallback:\n            _get_default_config_int8(\n                cfg,\n                data_tensor,\n                kernel_tensor,\n                strides,\n                padding,\n                dilation,\n                out_dtype,\n                False,\n                data_layout,\n                int32_lanes=4,\n            )\n\n        ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n        if cfg.is_fallback:\n            # ic_bn needs to be divided by n_elems below\n            ic_bn = max(ic_bn, n_elems)\n\n        # update new attrs\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        new_attrs[\"kernel_layout\"] = \"OIHW{:n}i{:n}o{:n}i\".format(ic_bn // n_elems, oc_bn, n_elems)\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        # Store altered operator's config.\n        new_data = te.placeholder(\n            (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n        )\n        new_kernel = te.placeholder(\n            (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn // n_elems, oc_bn, n_elems),\n            dtype=kernel_dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_kernel,\n                strides,\n                padding,\n                dilation,\n                new_attrs[\"data_layout\"],\n                new_attrs[\"out_layout\"],\n                out_dtype,\n            ],\n            topi_tmpl,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_NHWC_quantized_interleaved.arm_cpu\":\n        # TODO(masahi): This schedule can easily result in a tensorization error\n        # if used in the fallback mode\n        if cfg.is_fallback:  # if is fallback, clear query cache and return None\n            autotvm.task.clear_fallback_cache(target, workload)\n            return None\n\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n        KH, KW, _, OC = get_const_tuple(kernel.shape)\n        new_workload_name = \"conv2d_NHWC_quantized_interleaved_without_transform.arm_cpu\"\n        new_kernel, new_kernel_expr = interleave_transpose_weights(\n            inputs, data, kernel, interleave_A=True\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [data, new_kernel, strides, padding, dilation, out_dtype, (KH, KW), OC],\n            new_workload_name,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.contrib_conv2d_gemm_without_weight_transform(\n            inputs[0], new_kernel_expr, **new_attrs\n        )\n    if topi_tmpl == \"conv2d_NHWC_quantized_native.arm_cpu\":\n        # TODO(masahi): This schedule can easily result in a tensorization error\n        # if used in the fallback mode\n        if cfg.is_fallback:  # if is fallback, clear query cache and return None\n            autotvm.task.clear_fallback_cache(target, workload)\n            return None\n\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n        KH, KW, _, OC = get_const_tuple(kernel.shape)\n        new_workload_name = \"conv2d_NHWC_quantized_native_without_transform.arm_cpu\"\n        new_kernel, new_kernel_expr = interleave_transpose_weights(\n            inputs, data, kernel, interleave_A=False\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [data, new_kernel, strides, padding, dilation, out_dtype, (KH, KW), OC],\n            new_workload_name,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_gemm_without_weight_transform(\n            inputs[0], new_kernel_expr, **new_attrs\n        )\n    return None\n\n\n@conv2d_legalize.register(\"arm_cpu\")\ndef _conv2d_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Collect the input tensors.\n    data_tensor, kernel_tensor = arg_types[0], arg_types[1]\n    data_dtype = data_tensor.dtype\n    kernel_dtype = kernel_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    data, kernel = inputs\n\n    # ARM vector instructions operate on the same dtype for data and kernel, we\n    # provide those here and conv2d_alter_int8_common will convert to the\n    # correct datatype.\n    if is_int8_hw_support(kernel_dtype, kernel_dtype):\n        # ARM intrinsics need the datatypes of data and kernel to be the same\n        return conv2d_alter_int8_common(\n            data, data_tensor, kernel, kernel_tensor, output_tensor, attrs, kernel_dtype, 8, 8\n        )\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d_gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin\n\"\"\"GEMM Convolution schedule on ARM\"\"\"\nimport tvm\nfrom tvm.target import Target\nfrom tvm import te\nfrom tvm.topi import nn\nfrom tvm.autotvm.task.space import AnnotateEntity, ReorderEntity, OtherOptionEntity\nfrom ..utils import get_const_tuple, get_const_int\nfrom ..nn.utils import get_pad_tuple\nfrom .tensor_intrin import (\n    gemm_4x4_int8_int8_int32,\n    gemm_acc_4x4_int8_int8_int32,\n    gemm_acc_nx16_int8_int8_int32,\n    gemm_acc_2x2_int8_int8_int32,\n)\n\n\ndef configure_knobs(cfg, M, K, target):\n    \"\"\"Configure auto-tuning knobs for the interleaved strategy\"\"\"\n\n    x, y = cfg.axis(M // 4), cfg.axis(K // 16)\n    cfg.define_reorder(\"reorder_gemm\", [x, y], policy=\"candidate\", candidate=[[x, y], [y, x]])\n\n    outer_loop, inner_loop = cfg.axis(4), cfg.axis(16)\n    cfg.define_annotate(\n        \"A_interleaved_unroll_vec\", [outer_loop, inner_loop], policy=\"try_unroll_vec\"\n    )\n\n    # Fallback configuration\n    if cfg.is_fallback:\n        cfg[\"reorder_gemm\"] = ReorderEntity([0, 1])\n        cfg[\"A_interleaved_unroll_vec\"] = AnnotateEntity([\"unroll\", \"vec\"])\n\n    if not target.features.has_dotprod:\n        cfg.define_knob(\"gemm_quantized_unroll\", [True, False])\n        if cfg.is_fallback:\n            cfg[\"gemm_quantized_unroll\"] = OtherOptionEntity(False)\n\n\n# Compute function\ndef compute_conv2d_gemm_without_weight_transform(\n    cfg,\n    data,\n    B_interleaved_t,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    kernel_size,\n    output_channels,\n    interleave_A,\n):\n    \"\"\"Compute conv2d by transforming the input,\n    executing GEMM and transforming the output back\"\"\"\n    batches, IH, IW, IC = get_const_tuple(data.shape)\n\n    KH, KW = get_const_tuple(kernel_size)\n    OC = get_const_int(output_channels)\n    kernel_area = KH * KW\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = get_const_tuple(dilation)\n\n    dilated_kernel_h = (KH - 1) * dilation_h + 1\n    dilated_kernel_w = (KW - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n\n    OH = (IH + pad_top + pad_down - dilated_kernel_h) // HSTR + 1\n    OW = (IW + pad_left + pad_right - dilated_kernel_w) // WSTR + 1\n    if pad_top or pad_left:\n        data_pad = nn.pad(\n            data, [0, pad_top, pad_left, 0], [0, pad_down, pad_right, 0], name=\"data_pad\"\n        )\n    else:\n        data_pad = data\n\n    # Im2col\n    M = OH * OW\n    K = IC * kernel_area\n    N = OC\n\n    A_shape = (batches, M, K)\n    if kernel_area == 1:\n        A = tvm.topi.reshape(data_pad, A_shape)\n    else:\n        A = te.compute(\n            A_shape,\n            lambda n, x, y: data_pad[\n                n,\n                HSTR * (x // OW) + dilation_h * ((y // IC) // KW),\n                WSTR * (x % OW) + dilation_w * ((y // IC) % KW),\n                y % IC,\n            ],\n            name=\"data_im2col\",\n        )\n\n    #  Pad if necessary\n    N_transformed = B_interleaved_t.shape[0]\n    tile_rows_B = B_interleaved_t.shape[2]\n    tile_cols_B = B_interleaved_t.shape[3]\n\n    # Select the tiling strategy for A.\n    # The tiling information is chosen to maximize register usage during\n    # the tile computation.\n    #\n    # Please refer to:\n    # - https://discuss.tvm.apache.org/t/rfc-improve-quantized-convolution-performance-for-armv8-architectures # pylint: disable=line-too-long\n    # - https://discuss.tvm.apache.org/t/rfc-accelerate-quantized-convolution-through-dot-product\n    # - https://discuss.tvm.apache.org/t/rfc-improve-quantized-convolution-through-mmla-instruction\n    # - Conv2DGemmWeightTransformRel in src/relay/op/nn/convolution.h\n    # In order to have more information\n    #\n    target = Target.current(allow_none=False)\n    if target.features.has_matmul_i8:\n        # If smmla/ummla is enabled, we are loading 8 rows from A. Each row\n        # will contain 8 elements\n        tile_rows_A = 8\n        tile_cols_A = 8\n    elif target.features.has_dotprod and interleave_A:\n        # If dot product has been enabled, and we are interleaving A\n        # tile size should be 8x4\n        tile_rows_A = 8\n        tile_cols_A = 4\n    else:\n        # If either there is no dot product or if we are using a native strategy\n        # tile size should be 4x16\n        tile_rows_A = 4\n        tile_cols_A = 16\n\n    pad_M = 0\n    pad_K = 0\n\n    if M % tile_rows_A != 0:\n        pad_M = tile_rows_A - (M % tile_rows_A)\n\n    if K % tile_cols_A != 0:\n        pad_K = tile_cols_A - (K % tile_cols_A)\n\n    M_padded = M + pad_M\n    K_padded = K + pad_K\n    N_padded = N_transformed * tile_rows_B\n\n    pad_before = (0, 0, 0)\n    pad_after = (0, pad_M, pad_K)\n\n    if pad_M != 0 or pad_K != 0:\n        A = nn.pad(A, pad_before=pad_before, pad_after=pad_after, name=\"A_padded\")\n\n    idxm = tvm.tir.indexmod\n    k = te.reduce_axis((0, K_padded), \"k\")\n\n    if interleave_A:\n        # Configuration space\n        configure_knobs(cfg, M_padded, K_padded, target)\n\n        # Pack the input data\n        A_interleaved = te.compute(\n            (batches, M_padded // tile_rows_A, K_padded // tile_cols_A, tile_rows_A, tile_cols_A),\n            lambda b, x, y, z, w: A[b, z + tile_rows_A * x, w + tile_cols_A * y],\n            name=\"A_interleaved\",\n        )\n        target = Target.current(allow_none=False)\n        if target.features.has_matmul_i8:\n            # Execute GEMM. In the case of mmla, we need to enforce the tiling\n            # from the compute. This is because mmla is doing a tiled computation\n            # as well. So we have a big 8x12 tile, with small 2x2 sub-tiles\n            # generated by mmla. In theory we could make the tile 2x2 and\n            # fuse and split during scheduling, but this would not work\n            # because of possible padding\n            C_interleaved = te.compute(\n                (\n                    batches,\n                    M_padded // tile_rows_A,\n                    N_transformed,\n                    tile_rows_A // 2,\n                    tile_rows_B // 2,\n                    2,\n                    2,\n                ),\n                lambda b, x, y, w, z, s, t: te.sum(\n                    A_interleaved[b, x, k // tile_cols_A, 2 * w + s, idxm(k, tile_cols_A)].astype(\n                        \"int32\"\n                    )\n                    * B_interleaved_t[y, k // tile_cols_B, 2 * z + t, idxm(k, tile_cols_B)].astype(\n                        \"int32\"\n                    ),\n                    axis=k,\n                ),\n                name=\"C_interleaved\",\n            )\n            # Unpack the result\n            C = te.compute(\n                (batches, M, N),\n                lambda b, x, y: C_interleaved[\n                    b,\n                    x // tile_rows_A,\n                    y // tile_rows_B,\n                    idxm(x, tile_rows_A) // 2,\n                    idxm(y, tile_rows_B) // 2,\n                    idxm(idxm(x, tile_rows_A), 2),\n                    idxm(idxm(y, tile_rows_B), 2),\n                ].astype(out_dtype),\n                name=\"C\",\n            )\n        else:\n            # Execute GEMM\n            C_interleaved = te.compute(\n                (batches, M_padded // tile_rows_A, N_transformed, tile_rows_A, tile_rows_B),\n                lambda b, x, y, w, z: te.sum(\n                    A_interleaved[b, x, k // tile_cols_A, w, idxm(k, tile_cols_A)].astype(\"int32\")\n                    * B_interleaved_t[y, k // tile_cols_B, z, idxm(k, tile_cols_B)].astype(\"int32\"),\n                    axis=k,\n                ),\n                name=\"C_interleaved\",\n            )\n            # Unpack the result\n            C = te.compute(\n                (batches, M, N),\n                lambda b, x, y: C_interleaved[\n                    b,\n                    x // tile_rows_A,\n                    y // tile_rows_B,\n                    idxm(x, tile_rows_A),\n                    idxm(y, tile_rows_B),\n                ].astype(out_dtype),\n                name=\"C\",\n            )\n        zero = tvm.tir.const(0)\n    else:\n        # No need to pack/unpack, execute GEMM directly\n        C = te.compute(\n            (batches, M_padded, N_padded),\n            lambda b, x, y: te.sum(\n                A[b, x, k].astype(\"int32\")\n                * B_interleaved_t[\n                    y // tile_rows_B, k // tile_cols_B, idxm(y, tile_rows_B), idxm(k, tile_cols_B)\n                ].astype(\"int32\"),\n                axis=k,\n            ),\n            name=\"C\",\n        )\n\n        # We need to ensure that infer bound pass does not remove the padding\n        # which is necessary for the tensorizations to work. So we need to\n        # add a dummy reference to the padding area of the result\n        zero = (\n            tvm.tir.const(1, C.dtype) * C[0, M_padded - 1, N_padded - 1]\n            - tvm.tir.const(1, C.dtype) * C[0, M_padded - 1, N_padded - 1]\n        )\n\n    # Reshape the result into a convolution output\n    out_shape = (batches, OH, OW, OC)\n    out = te.compute(\n        out_shape,\n        lambda b, x, y, z: (C(b, y + OW * x, z) + zero).astype(out_dtype),\n        name=\"conv2d_gemm_output\",\n    )\n    return out\n\n\ndef schedule_conv2d_gemm_interleaved(cfg, s, out, final_out):\n    \"\"\"Schedule the conv2d_gemm interleaved strategy\"\"\"\n    C = out.op.input_tensors[0]\n    C_interleaved = C.op.input_tensors[0]\n    A_interleaved = C_interleaved.op.input_tensors[0]\n\n    # Input transform\n    A_interleaved_input = A_interleaved.op.input_tensors[0]\n    if A_interleaved_input.op.name == \"A_padded\":\n        s[A_interleaved_input].compute_at(s[A_interleaved], A_interleaved.op.axis[3])\n        s[A_interleaved_input].vectorize(A_interleaved_input.op.axis[2])\n        s[A_interleaved_input].compute_inline()\n        data_im2col = A_interleaved_input.op.input_tensors[0]\n    else:\n        data_im2col = A_interleaved_input\n\n    b, m, n = data_im2col.op.axis\n    if data_im2col.op.name == \"data_im2col\":\n        n_outer, n_inner = s[data_im2col].split(n, 16)\n        s[data_im2col].unroll(n_outer)\n        s[data_im2col].vectorize(n_inner)\n        b_m_fused = s[data_im2col].fuse(b, m)\n        s[data_im2col].parallel(b_m_fused)\n    else:\n        s[data_im2col].compute_inline()\n\n    # Computation(through tensorize)\n    b, xo, yo, xi, yi = C_interleaved.op.axis[0:5]\n    outer_gemm, inner_gemm = cfg[\"reorder_gemm\"].apply(s, C_interleaved, [xo, yo])\n\n    b_outer_gemm_fused = s[C_interleaved].fuse(b, outer_gemm)\n    s[C_interleaved].parallel(b_outer_gemm_fused)\n    s[A_interleaved].compute_at(s[C_interleaved], b_outer_gemm_fused)\n    _, _, _, outer_A_interleaved, inner_A_interleaved = A_interleaved.op.axis\n    cfg[\"A_interleaved_unroll_vec\"].apply(\n        s, A_interleaved, [outer_A_interleaved, inner_A_interleaved]\n    )\n\n    in_type = A_interleaved.dtype\n    out_type = C.dtype\n\n    k = C_interleaved.op.reduce_axis[0]\n    _, M, N = C.shape\n    if in_type in [\"int8\", \"uint8\"]:\n        target = Target.current(allow_none=False)\n        if target.features.has_matmul_i8:\n            gemm_acc = gemm_acc_2x2_int8_int8_int32(in_type)\n            xi_inner, yi_inner = C_interleaved.op.axis[-2:]\n            k_outer, k_inner = s[C_interleaved].split(k, 8)\n            s[C_interleaved].reorder(\n                b_outer_gemm_fused, inner_gemm, k_outer, xi, yi, xi_inner, yi_inner, k_inner\n            )\n            s[C_interleaved].tensorize(xi_inner, gemm_acc)\n            s[C_interleaved].unroll(xi)\n            s[C_interleaved].unroll(yi)\n        elif target.features.has_dotprod:\n            gemm_acc = gemm_acc_4x4_int8_int8_int32(in_type)\n            xi_outer, yi_outer, xi_inner, yi_inner = s[C_interleaved].tile(\n                xi, yi, x_factor=8, y_factor=4\n            )\n            k_outer, k_inner = s[C_interleaved].split(k, 4)\n            xi_inner_outer, xi_inner_inner = s[C_interleaved].split(xi_inner, 4)\n            s[C_interleaved].reorder(\n                b_outer_gemm_fused,\n                inner_gemm,\n                xi_outer,\n                yi_outer,\n                k_outer,\n                xi_inner_outer,\n                xi_inner_inner,\n                yi_inner,\n                k_inner,\n            )\n            s[C_interleaved].tensorize(xi_inner_inner, gemm_acc)\n            s[C_interleaved].unroll(xi_inner_outer)\n\n        elif target.features.has_asimd:\n            s[C_interleaved].reorder(yi, xi)\n            K = A_interleaved_input.shape[2]\n            assert in_type in [\"int8\", \"uint8\"], \"Only int8 and uint8 gemm are supported\"\n            unroll = cfg[\"gemm_quantized_unroll\"].val\n            gemm = gemm_4x4_int8_int8_int32(M, N, K, unroll, in_type)\n            s[C_interleaved].tensorize(yi, gemm)\n\n    # Output transform\n    if out != final_out:\n        n, h, w, c = out.op.axis\n        _, inner = s[out].split(c, 4)\n        s[C].compute_at(s[out], inner)\n        s[out].vectorize(inner)\n    return s\n\n\ndef schedule_conv2d_gemm_native(cfg, s, out, final_out):\n    \"\"\"Schedule the conv2d_gemm hybrid strategy\"\"\"\n    C = out.op.input_tensors[0]\n    A = C.op.input_tensors[0]\n    in_type = A.dtype\n\n    # Computation\n    b, x, y = C.op.axis\n    (k,) = C.op.reduce_axis\n    k_outer, k_inner = s[C].split(k, 16)\n    x_outer, y_outer, x_inner, y_inner = s[C].tile(x, y, x_factor=4, y_factor=16)\n    s[C].reorder(b, x_outer, y_outer, k_outer, x_inner, y_inner, k_inner)\n    gemm_acc = gemm_acc_nx16_int8_int8_int32(in_type, rows=1)\n    s[C].unroll(x_inner)\n    s[C].tensorize(y_inner, gemm_acc)\n    s[C].parallel(x_outer)\n\n    # Input transform\n    if A.op.name == \"A_padded\":\n        padding_A = True\n        data_im2col = A.op.input_tensors[0]\n    else:\n        padding_A = False\n        data_im2col = A\n\n    b, m, n = data_im2col.op.axis\n    if data_im2col.op.name == \"data_im2col\":\n        n_outer, n_inner = s[data_im2col].split(n, 16)\n        s[data_im2col].unroll(n_outer)\n        s[data_im2col].vectorize(n_inner)\n        s[data_im2col].parallel(m)\n    elif padding_A:\n        s[data_im2col].compute_inline()\n        s[A].compute_at(s[C], x_inner)\n    else:\n        s[data_im2col].compute_at(s[C], x_inner)\n\n    # Output transform\n    if out != final_out:\n        n, h, w, c = out.op.axis\n        _, inner = s[out].split(c, 4)\n        s[out].vectorize(inner)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D int8 schedule on ARM\"\"\"\nfrom tvm import te, target, autotvm\nfrom ..utils import traverse_inline, get_const_tuple\nfrom ..generic import conv2d as conv2d_generic\nfrom .. import nn\nfrom ...target import codegen\nfrom ..nn.conv2d import _get_workload as _get_conv2d_workload, unpack_NCHWc_to_nchw\nfrom ..x86.conv2d_int8 import _pack_data\nfrom ..nn.utils import get_pad_tuple\nfrom .tensor_intrin import dot_int8_int8_int32_neon_82, dot_int8_int8_int32_neon\nfrom .conv2d_gemm import (\n    compute_conv2d_gemm_without_weight_transform,\n    schedule_conv2d_gemm_interleaved,\n    schedule_conv2d_gemm_native,\n)\nfrom .arm_utils import get_tiling_B_interleaved_t\n\n\ndef _get_default_config(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"\n    Get default int8 schedule config for the workload\n    \"\"\"\n    wkl = _get_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype)\n    is_kernel_1x1 = wkl.kernel_h == 1 and wkl.kernel_w == 1\n    if is_kernel_1x1:\n        conv2d_generic.fallback_schedule_cpu_1x1_int8(cfg, wkl, int32_lanes=4, num_int8_elements=4)\n    else:\n        conv2d_generic.fallback_schedule_cpu_common_int8(\n            cfg, wkl, int32_lanes=4, num_int8_elements=4\n        )\n\n\n@autotvm.register_topi_compute(\"conv2d_NCHWc_int8.arm_cpu\")\ndef conv2d_NCHWc_int8(cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype):\n    \"\"\"Compute conv2d int8 with NCHWc layout\"\"\"\n    # layout and out_layout are not used here,\n    # we keep them for debug convenience when dumping autotvm workload\n\n    if len(data.shape) == 5:  # data is in nchwc\n        n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n        in_channel = ic_chunk * ic_bn\n\n        oc_chunk, ic_chunk, kh, kw, ic_bn, oc_bn, _ = get_const_tuple(kernel.shape)\n        num_filter = oc_chunk * oc_bn\n    else:\n        # data is nchw, implicitly treat it as nchw1c\n        n, in_channel, ih, iw = get_const_tuple(data.shape)\n        num_filter, _, kh, kw = get_const_tuple(kernel.shape)\n\n    # Define autotvm tuning space\n    is_kernel_1x1 = kh == 1 and kw == 1\n    pt, pl, pb, pr = get_pad_tuple(padding, (kh, kw))\n    sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    dh, dw = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    dilated_kernel_h = (kh - 1) * dh + 1\n    dilated_kernel_w = (kw - 1) * dw + 1\n    oh = (ih - dilated_kernel_h + pt + pb) // sh + 1\n    ow = (iw - dilated_kernel_w + pl + pr) // sw + 1\n\n    # input and output should be a multiple of 8 (intrinsics are 8 lanes)\n    cfg.define_split(\n        \"tile_ic\", in_channel, num_outputs=2, filter=lambda y: y.size[-1] % min(8, in_channel) == 0\n    )\n    cfg.define_split(\n        \"tile_oc\", num_filter, num_outputs=2, filter=lambda y: y.size[-1] % min(8, num_filter) == 0\n    )\n    cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda y: y.size[-1] <= 64)\n    if is_kernel_1x1:\n        cfg.define_knob(\"tile_oh\", [1, 2] if oh > 1 else [1])\n    else:\n        cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # If no config was set, we can fallback to NCHW config.\n    if cfg.is_fallback:\n        _get_default_config(\n            cfg,\n            te.placeholder((n, in_channel, ih, iw), dtype=data.dtype),\n            te.placeholder((num_filter, in_channel, kh, kw), dtype=kernel.dtype),\n            strides,\n            padding,\n            dilation,\n            out_dtype,\n        )\n    # Pack data if raw 4-D data is provided.\n    # This can only happen when autotuning.\n    if len(data.shape) == 4:\n        data, kernel = _pack_data(cfg, data, kernel)\n\n    n_elems = int(kernel.shape[-1])\n\n    return nn.conv2d_NCHWc_int8(\n        data, kernel, strides, padding, dilation, layout, out_layout, out_dtype, n_elems=n_elems\n    )\n\n\ndef is_int8_hw_support(data_dtype, kernel_dtype):\n    \"\"\"\n    Checks to ensure that we can use int8 on arm\n    1) The datatypes are correct.\n    2) LLVM version has support for the instructions.\n    \"\"\"\n    # 1) Check datatypes\n    is_dtype_support = data_dtype == kernel_dtype and \"int8\" in data_dtype\n\n    # 2) Check LLVM support\n    llvm_version = codegen.llvm_version_major()\n    is_llvm_support = llvm_version >= 8\n\n    # 3) Check target\n    current_target = target.Target.current(allow_none=False)\n    is_target_support = bool(\n        current_target.features.has_asimd or current_target.features.has_dotprod\n    )\n\n    return is_dtype_support and is_llvm_support and is_target_support\n\n\n@autotvm.register_topi_schedule(\"conv2d_NCHWc_int8.arm_cpu\")\ndef schedule_conv2d_NCHWc_int8(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def _callback(op):\n        if \"conv2d_NCHWc_int8\" in op.tag:\n            conv_out = op.output(0)\n            kernel_vec = conv_out.op.input_tensors[1]\n            data_vec = conv_out.op.input_tensors[0]\n            data = (\n                data_vec.op.input_tensors[0]\n                if isinstance(data_vec.op, te.tensor.ComputeOp) and \"pad\" not in data_vec.op.tag\n                else data_vec\n            )\n            if isinstance(data.op, te.tensor.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            args = [s, cfg, data_vec, kernel_vec, conv_out, outs[0]]\n            # int8 conv kernel is 7-dim\n            _, _, kh, kw, _, _, n_elems = get_const_tuple(kernel_vec.shape)\n            assert n_elems == 4\n            dtype = \"uint\" if data.dtype == \"uint8\" else \"int\"\n            current_target = target.Target.current(allow_none=False)\n            if current_target.features.has_dotprod:\n                intrin = dot_int8_int8_int32_neon_82(int32_lanes=4, dtype=dtype)\n            elif current_target.features.has_asimd:\n                assert dtype == \"int\", \"uint8 not supported if dot product is not available\"\n                intrin = dot_int8_int8_int32_neon()\n            else:\n                raise RuntimeError(\n                    \"Cannot schedule schedule_NCHWc_int8 without neon or arm v8.2 neon support\"\n                )\n            # On raspberry pi 4s, we see poor performance when the fused\n            # operations are inlined into the main computation body. These\n            # fused ops dominated the runtime on small convolutions repeatedly\n            # blow the cache. Using workloads from resnet50, inceptionv3, and\n            # mobilenetv3, we empirically determine the size at which inline is\n            # not worth it to be kernel heigh * kernel width < 500. These tests\n            # were only run on raspberry pi 4, other arm cpus may have larger\n            # caches where inlining has good performance.\n            if target.Target.current().mcpu == \"cortex-a72\" and kh * kw < 500:\n                inline_fused = False\n            else:\n                inline_fused = True\n            if kh == 1 and kw == 1:\n                conv2d_generic.schedule_conv_NCHWc_cpu_1x1_int8(\n                    *args, int32_lanes=4, int8_elems=4, intrin=intrin, inline_fused=inline_fused\n                )\n            else:\n                conv2d_generic.schedule_conv_NCHWc_cpu_common_int8(\n                    *args, int32_lanes=4, int8_elems=4, intrin=intrin, inline_fused=inline_fused\n                )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef conv2d_nchw_int8(data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with NCHW layout and int8 dtype\"\"\"\n    layout = \"NCHW\"\n    # pylint: disable=no-value-for-parameter\n    packed_out = conv2d_NCHWc_int8(\n        data, kernel, strides, padding, dilation, layout, layout, out_dtype\n    )\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_conv2d_nchw_int8(outs):\n    \"\"\"Create the schedule for conv2d_nchw_int8\"\"\"\n    # pylint: disable=no-value-for-parameter\n    return schedule_conv2d_NCHWc_int8(outs)\n\n\ndef _compute_conv2d_NHWC_quantized(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, interleave_A\n):\n    N, IH, IW, IC = get_const_tuple(data.shape)\n    KH, KW, _, OC = get_const_tuple(kernel.shape)\n    tile_rows_B, tile_cols_B = get_tiling_B_interleaved_t(interleave_A)\n\n    kernel = nn.conv2d_gemm_weight_transform(kernel, tile_rows_B, tile_cols_B)\n    return compute_conv2d_gemm_without_weight_transform(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, (KH, KW), OC, interleave_A\n    )\n\n\ndef _compute_conv2d_NHWC_quantized_without_transform(\n    cfg,\n    data,\n    B,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    kernel_size=None,\n    output_channels=None,\n    interleave_A=False,\n):\n    return compute_conv2d_gemm_without_weight_transform(\n        cfg,\n        data,\n        B,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        kernel_size,\n        output_channels,\n        interleave_A,\n    )\n\n\ndef _schedule_conv2d_NHWC_quantized(cfg, outs, interleave_A):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    # Vectorize the output and then inline all the rest\n    out = outs[0]\n    n, h, w, c = out.op.axis\n    n_h_fused = s[out].fuse(n, h)\n    outer, inner = s[out].split(c, 4)\n    s[out].vectorize(inner)\n    s[out].parallel(n_h_fused)\n\n    def _callback(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        if op.name == \"conv2d_gemm_output\":\n            conv_out = op.output(0)\n            if interleave_A:\n                schedule_conv2d_gemm_interleaved(cfg, s, conv_out, out)\n            else:\n                schedule_conv2d_gemm_native(cfg, s, conv_out, out)\n            if out != conv_out:\n                s[conv_out].compute_at(s[out], inner)\n            else:\n                C = conv_out.op.input_tensors[0]\n                if interleave_A:\n                    s[C].compute_at(s[out], inner)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n# Interleaved schedules: those schedule will interleave the input data. The\n# weights are interleaved and transposed\n@autotvm.register_topi_compute(\"conv2d_NHWC_quantized_interleaved.arm_cpu\")\ndef compute_conv2d_NHWC_quantized_interleaved(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    \"\"\"Interface for interleaved compute_conv2d_NHWC_quantized_interleaved\"\"\"\n    return _compute_conv2d_NHWC_quantized(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, True\n    )\n\n\n@autotvm.register_topi_compute(\"conv2d_NHWC_quantized_interleaved_without_transform.arm_cpu\")\ndef compute_conv2d_NHWC_quantized_interleaved_without_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, kernel_size, output_channels\n):\n    \"\"\"Interface for interleaved compute_conv2d_NHWC_quantized_interleaved_without_transform\"\"\"\n    return _compute_conv2d_NHWC_quantized_without_transform(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, kernel_size, output_channels, True\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_NHWC_quantized_interleaved.arm_cpu\")\ndef schedule_conv2d_NHWC_quantized_interleaved(cfg, outs):\n    \"\"\"Interface for interleaved schedule_conv2d_NHWC_quantized_interleaved\"\"\"\n    return _schedule_conv2d_NHWC_quantized(cfg, outs, True)\n\n\n@autotvm.register_topi_schedule(\"conv2d_NHWC_quantized_interleaved_without_transform.arm_cpu\")\ndef schedule_conv2d_NHWC_quantized_interleaved_without_transform(cfg, outs):\n    \"\"\"Interface for interleaved schedule_conv2d_NHWC_quantized_interleaved\"\"\"\n    return _schedule_conv2d_NHWC_quantized(cfg, outs, True)\n\n\n# Native schedules: those schedule won't interleave A (which is left in its native form).\n# The weights are interleaved and transposed\n@autotvm.register_topi_compute(\"conv2d_NHWC_quantized_native.arm_cpu\")\ndef compute_conv2d_NHWC_quantized_native(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Interface for native compute_conv2d_NHWC_quantized\"\"\"\n    return _compute_conv2d_NHWC_quantized(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, False\n    )\n\n\n@autotvm.register_topi_compute(\"conv2d_NHWC_quantized_native_without_transform.arm_cpu\")\ndef compute_conv2d_NHWC_quantized_native_without_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, kernel_size, output_channels\n):\n    \"\"\"Interface for compute_conv2d_NHWC_quantized_native_without_transform\"\"\"\n    return _compute_conv2d_NHWC_quantized_without_transform(\n        cfg,\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        kernel_size,\n        output_channels,\n        False,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_NHWC_quantized_native.arm_cpu\")\ndef schedule_conv2d_NHWC_quantized_native(cfg, outs):\n    \"\"\"Interface for native schedule_conv2d_NHWC_quantized\"\"\"\n    return _schedule_conv2d_NHWC_quantized(cfg, outs, False)\n\n\n@autotvm.register_topi_schedule(\"conv2d_NHWC_quantized_native_without_transform.arm_cpu\")\ndef schedule_conv2d_NHWC_quantized_native_without_transform(cfg, outs):\n    \"\"\"Interface for native schedule_conv2d_NHWC_quantized\"\"\"\n    return _schedule_conv2d_NHWC_quantized(cfg, outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d_spatial_pack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,no-else-return\n\"\"\"Conv2D spatial pack implementation for ARM CPU\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom .. import nn\nfrom ..utils import get_const_tuple\nfrom ..nn.utils import get_const_int, get_pad_tuple\n\n\ndef conv2d_spatial_pack_nchw(cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile):\n    \"\"\"compute define for Conv2d Spatial Pack with NCHW layout\"\"\"\n    out_dtype = out_dtype or data.dtype\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n    if not isinstance(IH, int) or not isinstance(IW, int):\n        raise RuntimeError(\"ARM winograd conv2d doesn't support dynamic input height or width.\")\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    if len(kernel.shape) == 4:\n        pre_packed = False\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n    else:  # kernel tensor is pre packed\n        pre_packed = True\n        CO, _, KH, KW, VC = get_const_tuple(kernel.shape)\n        CO = CO * VC\n\n    dilated_kernel_h = (KH - 1) * dilation_h + 1\n    dilated_kernel_w = (KW - 1) * dilation_w + 1\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    OH = (IH + pad_top + pad_bottom - dilated_kernel_h) // HSTR + 1\n    OW = (IW + pad_left + pad_right - dilated_kernel_w) // WSTR + 1\n    data_pad = nn.pad(data, [0, 0, pad_top, pad_left], [0, 0, pad_bottom, pad_right])\n\n    # ==================== define configuration space ====================\n    # TODO(@kevinthesun): Support tuning/optimization for dynamic shape.\n    n_tuning_axis = N if isinstance(N, int) else 1\n    n, co, oh, ow = cfg.axis(n_tuning_axis), cfg.axis(CO), cfg.axis(OH), cfg.axis(OW)\n    ci, kh, kw = cfg.reduce_axis(CI), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n\n    if num_tile == 2:  # for arm cpu\n        co, vc = cfg.define_split(\"tile_co\", co, num_outputs=2)\n        oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2)\n        ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2)\n    elif num_tile == 3:  # for mali gpu\n        co, _, vc = cfg.define_split(\"tile_co\", co, num_outputs=3)\n        oh, _, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=3)\n        ow, _, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=3)\n    else:\n        raise RuntimeError(\"Invalid num_tile\")\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [n, co, oh, ow, ci, kh, kw, vh, vw, vc],\n        policy=\"candidate\",\n        candidate=[\n            [n, co, oh, ow, ci, kh, kw, vh, vw, vc],\n            [n, co, oh, ow, ci, kh, kw, vc, vh, vw],\n        ],\n    )\n\n    cfg.define_annotate(\"ann_reduce\", [kh, kw], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [vh, vw, vc], policy=\"try_unroll_vec\")\n\n    # fallback support\n    if cfg.is_fallback:\n        if num_tile == 2:  # arm cpu\n            ref_log = autotvm.tophub.load_reference_log(\n                \"arm_cpu\", \"rk3399\", \"conv2d_nchw_spatial_pack.arm_cpu\"\n            )\n            cfg.fallback_with_reference_log(ref_log)\n        elif num_tile == 3:  # mali gpu\n            ref_log = autotvm.tophub.load_reference_log(\n                \"mali\", \"rk3399\", \"conv2d_nchw_spatial_pack.mali\"\n            )\n            cfg.fallback_with_reference_log(ref_log)\n    # ====================================================================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    kvshape = (CO // VC, CI, KH, KW, VC)\n    ovshape = (N, CO // VC, OH // VH, OW // VW, VH, VW, VC)\n    oshape = (N, CO, OH, OW)\n\n    if dilation_h != 1 or dilation_w != 1:\n        # undilate input data\n        dvshape = (N, OH // VH, OW // VW, CI, KH, KW, VH, VW)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, h, w, ci, kh, kw, vh, vw: data_pad[n][ci][\n                (h * VH + vh) * HSTR + kh * dilation_h\n            ][(w * VW + vw) * WSTR + kw * dilation_w],\n            name=\"data_vec_undilated\",\n        )\n    else:\n        dvshape = (N, OH // VH, OW // VW, CI, VH * HSTR + KH - 1, VW * WSTR + KW - 1)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, h, w, ci, vh, vw: data_pad[n][ci][h * VH * HSTR + vh][w * VW * WSTR + vw],\n            name=\"data_vec\",\n        )\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # use \"kernel_autotvm\" instead of \"kernel\" to avoid naming conflict with OpenCL keyword\n        kernel_vec = tvm.te.placeholder(kvshape, kernel.dtype, name=\"kernel_autotvm\")\n    else:\n        if pre_packed:\n            kernel_vec = kernel\n        else:\n            kernel_vec = te.compute(\n                kvshape,\n                lambda co, ci, kh, kw, vc: kernel[co * VC + vc][ci][kh][kw],\n                name=\"kernel_vec\",\n            )\n\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    kh = te.reduce_axis((0, KH), name=\"kh\")\n    kw = te.reduce_axis((0, KW), name=\"kw\")\n\n    if dilation_h != 1 or dilation_w != 1:\n        conv = te.compute(\n            ovshape,\n            lambda n, co, h, w, vh, vw, vc: te.sum(\n                data_vec[n, h, w, ci, kh, kw, vh, vw].astype(out_dtype)\n                * kernel_vec[co, ci, kh, kw, vc].astype(out_dtype),\n                axis=[ci, kh, kw],\n            ),\n            name=\"conv\",\n        )\n    else:\n        conv = te.compute(\n            ovshape,\n            lambda n, co, h, w, vh, vw, vc: te.sum(\n                data_vec[n, h, w, ci, vh * HSTR + kh, vw * WSTR + kw].astype(out_dtype)\n                * kernel_vec[co, ci, kh, kw, vc].astype(out_dtype),\n                axis=[ci, kh, kw],\n            ),\n            name=\"conv\",\n        )\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    output = te.compute(\n        oshape,\n        lambda n, co, h, w: conv[\n            n,\n            idxdiv(co, VC),\n            idxdiv(h, VH),\n            idxdiv(w, VW),\n            idxmod(h, VH),\n            idxmod(w, VW),\n            idxmod(co, VC),\n        ],\n        name=\"output_unpack\",\n        tag=\"spatial_conv2d_output\",\n    )\n    return output\n\n\ndef schedule_conv2d_spatial_pack_nchw(cfg, s, data_vec, kernel_vec, conv, output, last):\n    \"\"\"schedule implementation\"\"\"\n    n, co, oh, ow, vh, vw, vc = s[conv].op.axis\n    ci, kh, kw = s[conv].op.reduce_axis\n\n    # schedule conv\n    cfg[\"reorder_0\"].apply(s, conv, [n, co, oh, ow, ci, kh, kw, vh, vw, vc])\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv,\n        [kh, kw],\n        axis_lens=[get_const_int(kh.dom.extent), get_const_int(kw.dom.extent)],\n        max_unroll=None,\n        cfg=cfg,\n    )\n    cfg[\"ann_spatial\"].apply(\n        s,\n        conv,\n        [vh, vw, vc],\n        axis_lens=[cfg[\"tile_oh\"].size[-1], cfg[\"tile_ow\"].size[-1], cfg[\"tile_co\"].size[-1]],\n        max_unroll=None,\n        cfg=cfg,\n    )\n\n    # schedule fusion\n    n, co, h, w = s[last].op.axis\n    co, vc = cfg[\"tile_co\"].apply(s, last, co)\n    oh, vh = cfg[\"tile_oh\"].apply(s, last, h)\n    ow, vw = cfg[\"tile_ow\"].apply(s, last, w)\n    s[last].reorder(n, co, oh, ow, vh, vw, vc)\n    if last != output:\n        s[output].compute_inline()\n        cfg[\"ann_spatial\"].apply(\n            s,\n            last,\n            [vh, vw, vc],\n            axis_lens=[cfg[\"tile_oh\"].size[-1], cfg[\"tile_ow\"].size[-1], cfg[\"tile_co\"].size[-1]],\n            max_unroll=16,\n            cfg=cfg,\n        )\n    s[conv].compute_at(s[last], ow)\n\n    # mark parallel\n    s[last].parallel(co)\n\n    if data_vec.op.name == \"data_vec_undilated\":\n        _, h, _, _, _, _, _, _ = s[data_vec].op.axis\n    else:\n        _, h, _, _, _, _ = s[data_vec].op.axis\n    s[data_vec].parallel(h)\n\n    if kernel_vec.op.name == \"kernel_vec\":\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            co, _, _, _, _ = s[kernel_vec].op.axis\n            s[kernel_vec].parallel(co)\n    elif kernel_vec.op.name == \"kernel_vec_conv2d_transpose\":  # for conv2d transpose\n        co, _, _, _, _ = s[kernel_vec].op.axis\n        s[kernel_vec].parallel(co)\n\n    return s\n\n\ndef conv2d_spatial_pack_nhwc(cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=2):\n    \"\"\"Spatial pack compute for Conv2d NHWC\"\"\"\n    out_dtype = out_dtype or data.dtype\n\n    N, IH, IW, IC = get_const_tuple(data.shape)\n    assert len(kernel.shape) == 4, \"AlterOpLayout not enabled for NHWC yet\"\n    KH, KW, _, OC = get_const_tuple(kernel.shape)\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    dilated_kernel_h = (KH - 1) * dilation_h + 1\n    dilated_kernel_w = (KW - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n\n    OH = (IH + pad_top + pad_down - dilated_kernel_h) // HSTR + 1\n    OW = (IW + pad_left + pad_right - dilated_kernel_w) // WSTR + 1\n    data_pad = nn.pad(data, [0, pad_top, pad_left, 0], [0, pad_down, pad_right, 0])\n\n    # ==================== define configuration space ====================\n    # If it has dynamic shape in batch, we fix the split factor to 1\n    n = cfg.axis(N) if isinstance(N, int) else cfg.axis(1)\n    oc, oh, ow = cfg.axis(OC), cfg.axis(OH), cfg.axis(OW)\n    ic, kh, kw = cfg.reduce_axis(IC), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n\n    if num_tile == 2:  # for arm cpu\n        oco, oci = cfg.define_split(\"tile_co\", oc, num_outputs=2)\n        oho, ohi = cfg.define_split(\"tile_oh\", oh, num_outputs=2)\n        owo, owi = cfg.define_split(\"tile_ow\", ow, num_outputs=2)\n    elif num_tile == 3:  # for mali gpu\n        oco, _, oci = cfg.define_split(\"tile_co\", oc, num_outputs=3)\n        oho, _, ohi = cfg.define_split(\"tile_oh\", oh, num_outputs=3)\n        owo, _, owi = cfg.define_split(\"tile_ow\", ow, num_outputs=3)\n    else:\n        raise RuntimeError(\"Invalid num_tile\")\n\n    cfg.define_reorder(\n        \"reorder_conv\",\n        [n, oho, owo, oco, kh, kw, ic, ohi, owi, oci],\n        policy=\"candidate\",\n        candidate=[\n            [n, oho, owo, oco, kh, kw, ic, ohi, owi, oci],\n            [n, oho, owo, oco, ohi, kh, kw, ic, owi, oci],\n            [n, oho, owo, oco, ohi, kh, kw, owi, ic, oci],\n            [n, oho, owo, ohi, oco, kh, kw, owi, ic, oci],\n        ],\n    )\n\n    cfg.define_annotate(\"ann_reduce\", [kh, kw], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [ohi, owi, oci], policy=\"try_unroll_vec\")\n    # ====================================================================\n\n    OCI = cfg[\"tile_co\"].size[-1]\n    OHI = cfg[\"tile_oh\"].size[-1]\n    OWI = cfg[\"tile_ow\"].size[-1]\n    OCO = OC // OCI\n    OHO = OH // OHI\n    OWO = OW // OWI\n\n    kvshape = (OCO, KH, KW, IC, OCI)\n    ovshape = (N, OHO, OWO, OCO, OHI, OWI, OCI)\n    oshape = (N, OH, OW, OC)\n\n    if dilation_h != 1 or dilation_w != 1:\n        # undilate input data\n        dvshape = (N, OHO, OWO, KH, KW, IC, OHI, OWI)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, oho, owo, kh, kw, ic, ohi, owi: data_pad[n][\n                (oho * OHI + ohi) * HSTR + kh * dilation_h\n            ][(owo * OWI + owi) * WSTR + kw * dilation_w][ic],\n            name=\"data_vec_undilated\",\n        )\n    else:\n        dvshape = (N, OHO, OWO, KH + (OHI - 1) * HSTR, KW + (OWI - 1) * WSTR, IC)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, oho, owo, ohi, owi, ic: data_pad[n][oho * OHI * HSTR + ohi][\n                owo * OWI * WSTR + owi\n            ][ic],\n            name=\"data_vec\",\n        )\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        kernel_vec = tvm.te.placeholder(kvshape, kernel.dtype, name=\"kernel\")\n    else:\n        kernel_vec = te.compute(\n            kvshape,\n            lambda oco, kh, kw, ic, oci: kernel[kh][kw][ic][oco * OCI + oci],\n            name=\"kernel_vec\",\n        )\n\n    ic = te.reduce_axis((0, IC), name=\"ic\")\n    kh = te.reduce_axis((0, KH), name=\"kh\")\n    kw = te.reduce_axis((0, KW), name=\"kw\")\n\n    if dilation_h != 1 or dilation_w != 1:\n        conv = te.compute(\n            ovshape,\n            lambda n, oho, owo, oco, ohi, owi, oci: te.sum(\n                data_vec[n, oho, owo, kh, kw, ic, ohi, owi].astype(out_dtype)\n                * kernel_vec[oco, kh, kw, ic, oci].astype(out_dtype),\n                axis=[ic, kh, kw],\n            ),\n            name=\"conv\",\n        )\n    else:\n        conv = te.compute(\n            ovshape,\n            lambda n, oho, owo, oco, ohi, owi, oci: te.sum(\n                data_vec[n, oho, owo, ohi * HSTR + kh, owi * WSTR + kw, ic].astype(out_dtype)\n                * kernel_vec[oco, kh, kw, ic, oci].astype(out_dtype),\n                axis=[ic, kh, kw],\n            ),\n            name=\"conv\",\n        )\n\n    idiv = tvm.tir.indexdiv\n    imod = tvm.tir.indexmod\n    output = te.compute(\n        oshape,\n        lambda n, oho, owo, oc: conv[n][idiv(oho, OHI)][idiv(owo, OWI)][idiv(oc, OCI)][\n            imod(oho, OHI)\n        ][imod(owo, OWI)][imod(oc, OCI)],\n        name=\"output_unpack\",\n        tag=\"spatial_conv_output_NHWC\",\n    )\n    return output\n\n\ndef schedule_conv2d_spatial_pack_nhwc(cfg, s, op, output):\n    \"\"\"Spatial Pack schedule for Conv2d NHWC\"\"\"\n    unpack = op.output(0)\n    conv = unpack.op.input_tensors[0]\n    data_vec = conv.op.input_tensors[0]\n    kernel_vec = conv.op.input_tensors[1]\n    data_pad = data_vec.op.input_tensors[0]\n    OHI = cfg[\"tile_oh\"].size[-1]\n    OWI = cfg[\"tile_ow\"].size[-1]\n    OCI = cfg[\"tile_co\"].size[-1]\n\n    # schedule unpack/output\n    if output != unpack:\n        s[unpack].compute_inline()\n    n, oh, ow, oc = s[output].op.axis\n    oco, oci = cfg[\"tile_co\"].apply(s, output, oc)\n    oho, ohi = cfg[\"tile_oh\"].apply(s, output, oh)\n    owo, owi = cfg[\"tile_ow\"].apply(s, output, ow)\n    s[output].reorder(n, oho, owo, oco, ohi, owi, oci)\n    cfg[\"ann_spatial\"].apply(\n        s, output, [ohi, owi, oci], axis_lens=[OHI, OWI, OCI], max_unroll=16, cfg=cfg\n    )\n    cfg.define_knob(\"compat\", [0, 1, 2])\n    if cfg[\"compat\"].val < 2:\n        compat_axis = [owo, oco][cfg[\"compat\"].val]  # pylint: disable=R1706\n        s[conv].compute_at(s[output], compat_axis)\n    paxis = s[output].fuse(n, oho)\n    s[output].parallel(paxis)\n\n    # schedule conv\n    n, oho, owo, oco, ohi, owi, oci = s[conv].op.axis\n    ic, kh, kw = s[conv].op.reduce_axis\n    cfg[\"reorder_conv\"].apply(s, conv, [n, oho, owo, oco, kh, kw, ohi, owi, ic, oci])\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv,\n        [kh, kw],\n        axis_lens=[get_const_int(kh.dom.extent), get_const_int(kw.dom.extent)],\n        max_unroll=16,\n        cfg=cfg,\n    )\n    cfg[\"ann_spatial\"].apply(\n        s, conv, [ohi, owi, oci], axis_lens=[OHI, OWI, OCI], max_unroll=16, cfg=cfg\n    )\n    if cfg[\"compat\"].val < 2:\n        compat_axis = [owo, oco][cfg[\"compat\"].val]  # pylint: disable=R1706\n        s[kernel_vec].compute_at(s[conv], compat_axis)\n        s[data_vec].compute_at(s[conv], compat_axis)\n\n    if not autotvm.GLOBAL_SCOPE.in_tuning:\n        # schedule kernel pack\n        oco, kh, kw, ic, oci = kernel_vec.op.axis\n        s[kernel_vec].vectorize(oci)\n        s[kernel_vec].unroll(ic)\n        if cfg[\"compat\"].val == 2:\n            s[kernel_vec].parallel(oco)\n\n    # schedule data pack\n    if data_vec.op.name == \"data_vec_undilated\":\n        n, oho, owo, kh, kw, ic, ohi, owi = s[data_vec].op.axis\n        s[data_vec].vectorize(owi)\n        s[data_vec].unroll(ohi)\n    else:\n        n, oho, owo, ohi, owi, ic = s[data_vec].op.axis\n        s[data_vec].vectorize(ic)\n        s[data_vec].unroll(owi)\n    if cfg[\"compat\"].val == 2:\n        paxis = s[data_vec].fuse(n, oho)\n        s[data_vec].parallel(paxis)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"Transposed 2D convolution operators (sometimes called Deconvolution).\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom ..nn import dilate, pad, get_pad_tuple\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .conv2d_spatial_pack import schedule_conv2d_spatial_pack_nchw\n\n\n@autotvm.register_topi_compute(\"conv2d_transpose_nchw.arm_cpu\")\ndef conv2d_transpose_nchw(cfg, Input, Filter, strides, padding, out_dtype, output_padding):\n    \"\"\"Transposed 2D convolution nchw forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [in_channel, num_filter, filter_height, filter_width]\n\n    strides : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    out_dtype: str\n        The output data type. This is used for mixed precision.\n\n    output_padding : tuple of int\n        Used to get the right output shape in gradients\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return _decl_spatial_pack(\n        cfg, Input, Filter, strides, padding, \"NCHW\", out_dtype, 2, output_padding\n    )\n\n\ndef _decl_spatial_pack(\n    cfg, data, kernel, strides, padding, layout, out_dtype, num_tile, output_padding\n):\n    assert layout == \"NCHW\", \"Only support NCHW\"\n    out_dtype = out_dtype or data.dtype\n\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n    if not isinstance(IH, int) or not isinstance(IW, int):\n        raise RuntimeError(\"ARM winograd conv2d doesn't support dynamic input height or width.\")\n\n    _, CO, KH, KW = get_const_tuple(kernel.shape)\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    opad_h, opad_w = output_padding\n    assert opad_h < HSTR and opad_w < WSTR\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (KH, KW))\n    bpad_top, bpad_bottom = KH - 1 - pad_top, KH - 1 - pad_bottom + opad_h\n    bpad_left, bpad_right = KW - 1 - pad_left, KW - 1 - pad_right + opad_w\n\n    OH = (IH - 1) * HSTR - pad_top - pad_bottom + KH + opad_h\n    OW = (IW - 1) * WSTR - pad_left - pad_right + KW + opad_w\n\n    dilated_input = dilate(data, [1, 1, HSTR, WSTR])\n    data_pad = pad(dilated_input, [0, 0, bpad_top, bpad_left], [0, 0, bpad_bottom, bpad_right])\n\n    # ==================== define configuration space ====================\n    # TODO(@kevinthesun): Support tuning/optimization for dynamic shape.\n    n_tuning_axis = N if isinstance(N, int) else 1\n    n, co, oh, ow = cfg.axis(n_tuning_axis), cfg.axis(CO), cfg.axis(OH), cfg.axis(OW)\n    ci, kh, kw = cfg.reduce_axis(CI), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n\n    if num_tile == 2:  # for arm cpu\n        co, vc = cfg.define_split(\"tile_co\", co, num_outputs=2)\n        oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2)\n        ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2)\n    elif num_tile == 3:  # for mali gpu\n        co, _, vc = cfg.define_split(\"tile_co\", co, num_outputs=3)\n        oh, _, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=3)\n        ow, _, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=3)\n    else:\n        raise RuntimeError(\"Invalid num_tile\")\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [n, co, oh, ow, ci, kh, kw, vh, vw, vc],\n        policy=\"candidate\",\n        candidate=[\n            [n, co, oh, ow, ci, kh, kw, vh, vw, vc],\n            [n, co, oh, ow, ci, kh, kw, vc, vh, vw],\n        ],\n    )\n\n    cfg.define_annotate(\"ann_reduce\", [kh, kw], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [vh, vw, vc], policy=\"try_unroll_vec\")\n    # ====================================================================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    dvshape = (N, OH // VH, OW // VW, CI, VH + KH - 1, VW + KW - 1)\n    kvshape = (CO // VC, CI, KH, KW, VC)\n    ovshape = (N, CO // VC, OH // VH, OW // VW, VH, VW, VC)\n    oshape = (N, CO, OH, OW)\n\n    data_vec = te.compute(\n        dvshape,\n        lambda n, h, w, ci, vh, vw: data_pad[n][ci][h * VH + vh][w * VW + vw],\n        name=\"data_vec\",\n    )\n\n    kernel_vec = te.compute(\n        kvshape,\n        lambda co, ci, kh, kw, vc: kernel[ci][co * VC + vc][kh][kw],\n        name=\"kernel_vec_conv2d_transpose\",\n    )\n\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    kh = te.reduce_axis((0, KH), name=\"kh\")\n    kw = te.reduce_axis((0, KW), name=\"kw\")\n\n    conv = te.compute(\n        ovshape,\n        lambda n, co, h, w, vh, vw, vc: te.sum(\n            data_vec[n, h, w, ci, vh + kh, vw + kw].astype(out_dtype)\n            * kernel_vec[co, ci, KH - 1 - kh, KW - 1 - kw, vc].astype(out_dtype),\n            axis=[ci, kh, kw],\n        ),\n        name=\"conv\",\n    )\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    output = te.compute(\n        oshape,\n        lambda n, co, h, w: conv[\n            n,\n            idxdiv(co, VC),\n            idxdiv(h, VH),\n            idxdiv(w, VW),\n            idxmod(h, VH),\n            idxmod(w, VW),\n            idxmod(co, VC),\n        ],\n        name=\"output_unpack\",\n        tag=\"spatial_conv2d_transpose_output\",\n    )\n    return output\n\n\n# register customized schedule for arm cpu.\n@autotvm.register_topi_schedule(\"conv2d_transpose_nchw.arm_cpu\")\ndef schedule_conv2d_transpose_nchw(cfg, outs):\n    \"\"\"Schedule conv2d transpose for arm cpu\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"spatial_conv2d_transpose_output\" in op.tag:\n            output = op.output(0)\n            conv = op.input_tensors[0]\n\n            data_vec = conv.op.input_tensors[0]\n            data_pad = data_vec.op.input_tensors[0]\n            dilated_input = data_pad.op.input_tensors[0]\n            s[data_pad].compute_inline()\n            s[dilated_input].compute_inline()\n\n            kernel_vec = conv.op.input_tensors[1]\n            if kernel_vec.op.name == \"kernel_vec\":\n                kernel = kernel_vec.op.input_tensors[0]\n            else:\n                kernel = kernel_vec\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            schedule_conv2d_spatial_pack_nchw(cfg, s, data_vec, kernel_vec, conv, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, no-else-return, unused-argument, import-outside-toplevel\n\"\"\"Dense schedule for ARM CPU\"\"\"\n\nfrom tvm import autotvm\nfrom .mprofile.dsp.dense import dense_dsp_schedule, dense_dsp_compute\n\n\n@autotvm.register_topi_compute(\"dense_dsp.arm_cpu\")\ndef dense_dsp(cfg, data, weight, bias, out_dtype):\n    \"\"\"Compute conv2d_nhwc with v7e-m DSP instructions.\"\"\"\n    return dense_dsp_compute(cfg, data, weight, bias=bias, out_dtype=out_dtype)\n\n\n@autotvm.register_topi_schedule(\"dense_dsp.arm_cpu\")\ndef schedule_dense_dsp(cfg, outs):\n    \"\"\"Create schedule for dense_dsp\"\"\"\n    return dense_dsp_schedule(cfg, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable\n\"\"\"Depthwise convolution schedule for ARM CPU\"\"\"\n\nimport tvm\nfrom tvm.target import Target\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom .. import nn\nfrom ..utils import traverse_inline, get_const_tuple, get_const_int\nfrom ..nn.utils import get_pad_tuple\nfrom .tensor_intrin import smlal_int16_int32\nfrom .mprofile.dsp.depthwise_conv2d import (\n    depthwise_conv2d_nhwc_dsp_compute,\n    depthwise_conv2d_nhwc_dsp_schedule,\n)\nfrom .mprofile.dsp.tensordot_conv2ds import (\n    depthwise_conv2d_nchw_oihw_dsp_compute,\n    tensordot_conv2ds_schedule,\n)\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw.arm_cpu\")\ndef depthwise_conv2d_nchw(_, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute depthwise_conv2d with NCHW layout\"\"\"\n    return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw.arm_cpu\")\ndef schedule_depthwise_conv2d_nchw(cfg, outs):\n    \"\"\"Schedule depthwise conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The configuration of this template\n    outs: Array of Tensor\n        The computation graph description of depthwise convolution2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(cfg, s, data, data_pad, kernel, output):\n        A, B, C = data, kernel, output\n        s[data_pad].compute_inline()\n\n        ##### space definition begin #####\n        n, c, h, w = s[output].op.axis\n        _, vc = cfg.define_split(\"tile_c\", c, num_outputs=2)\n        _, vh = cfg.define_split(\"tile_h\", h, num_outputs=2)\n        _, vw = cfg.define_split(\"tile_w\", w, num_outputs=2)\n        cfg.define_annotate(\"ann\", [vh, vw, vc], policy=\"try_unroll_vec\")\n\n        # fallback support\n        if cfg.is_fallback:\n            ref_log = autotvm.tophub.load_reference_log(\n                \"arm_cpu\", \"rk3399\", \"depthwise_conv2d_nchw.arm_cpu\"\n            )\n            cfg.fallback_with_reference_log(ref_log)\n        ##### space definition end #####\n\n        # park data to vector form  [n, c, h, w] -> [n, C, h, w, VC]\n        A0 = s.cache_read(data_pad, \"global\", C)\n        n, c, h, w = s[A0].op.axis\n        c, vc = cfg[\"tile_c\"].apply(s, A0, c)\n        s[A0].reorder(n, c, h, w, vc)\n        A1 = s.cache_write(A0, \"global\")\n        s[A0].compute_inline()\n\n        # park kernel to vector form  [co, ci, kh, kw] -> [CO, ci, kh, kw, VC]\n        B0 = s.cache_read(B, \"global\", C)\n        c, m, h, w = s[B0].op.axis\n        c, vc, = cfg[\n            \"tile_c\"\n        ].apply(s, B0, c)\n        s[B0].reorder(c, m, h, w, vc)\n        B1 = s.cache_write(B0, \"global\")\n        s[B0].compute_inline()\n\n        n, c, h, w = s[C].op.axis\n        c, vc, = cfg[\n            \"tile_c\"\n        ].apply(s, C, c)\n        s[C].reorder(n, c, h, w, vc)\n\n        # depthwise conv\n        C0 = s.cache_write(C, \"global\")\n        _, c, h, w, vc = s[C0].op.axis\n        dh, dw = s[C0].op.reduce_axis\n        oh, ih = cfg[\"tile_h\"].apply(s, C0, h)\n        ow, iw = cfg[\"tile_w\"].apply(s, C0, w)\n        s[C0].reorder(c, oh, ow, dh, dw, ih, iw, vc)\n        s[A1].compute_at(s[C0], oh)\n\n        # try unroll and vectorization\n        cfg[\"ann\"].apply(\n            s,\n            C0,\n            [ih, iw, vc],\n            axis_lens=[cfg[\"tile_h\"].size[-1], cfg[\"tile_w\"].size[-1], cfg[\"tile_c\"].size[-1]],\n            max_unroll=16,\n            cfg=cfg,\n        )\n\n        # fusion\n        if C.op not in s.outputs:\n            s[C].compute_inline()\n\n        # mark parallel\n        last = outs[0]\n        n, c, h, w = s[last].op.axis\n        s[last].parallel(c)\n\n        n, c, h, w, vc = s[C0].op.axis\n        s[C0].parallel(c)\n\n        c, m, h, w, vc = s[B1].op.axis\n        s[B1].parallel(c)\n\n        return s\n\n    def _callback(op):\n        if op.tag == \"depthwise_conv2d_nchw\":\n            output = op.output(0)\n            kernel = op.input_tensors[1]\n            data = op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n            _schedule(cfg, s, data, data_pad, kernel, output)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n# TODO:\n# This schedule has incorrect result on some hardware platforms (like NV Jetson TX2)\n# Let us comment it out but not remove.\n# see discussion:\n# https://discuss.tvm.apache.org/t/autotuner-incorrect-result-after-tuning-mobilenetv2-on-arm-cpu\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw_spatial_pack.arm_cpu\")\ndef depthwise_conv2d_nchw_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"TOPI compute callback for depthwise_conv2d nchw\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, multiplier, filter_height, filter_width] or\n        pre-packed 5-D with shape [num_filter_chunk, multiplier, filter_height,\n        filter_width, num_filter_block]\n\n    strides : list of two ints\n        [stride_height, stride_width]\n\n    padding : list of two ints\n        [pad_height, pad_width]\n\n    dilation : list of two ints\n        [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n\n    return _decl_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=2)\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nhwc.arm_cpu\")\ndef compute_depthwise_conv2d_nhwc(_, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"TOPI compute callback for depthwise_conv2d nhwc\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]\n\n    strides : list of two ints\n        [stride_height, stride_width]\n\n    padding : list of two ints\n        [pad_height, pad_width]\n\n    dilation : list of two ints\n        [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    out_dtype = out_dtype or data.dtype\n\n    N, IH, IW, IC = get_const_tuple(data.shape)\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    KH, KW, IC, channel_multiplier = get_const_tuple(kernel.shape)\n\n    dilated_kernel_h = (KH - 1) * dilation_h + 1\n    dilated_kernel_w = (KW - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n\n    OH = (IH + pad_top + pad_down - dilated_kernel_h) // HSTR + 1\n    OW = (IW + pad_left + pad_right - dilated_kernel_w) // WSTR + 1\n\n    if pad_top or pad_left or pad_down or pad_right:\n        data_pad = nn.pad(\n            data, [0, pad_top, pad_left, 0], [0, pad_down, pad_right, 0], name=\"data_pad\"\n        )\n    else:\n        data_pad = data\n\n    output_shape = (N, OH, OW, IC * channel_multiplier)\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    reduce_h = te.reduce_axis((0, KH), name=\"reduce_h\")\n    reduce_w = te.reduce_axis((0, KW), name=\"reduce_w\")\n\n    out = te.compute(\n        output_shape,\n        lambda n, h, w, c: te.sum(\n            data_pad[\n                n,\n                HSTR * h + dilation_h * reduce_h,\n                w * WSTR + reduce_w * dilation_w,\n                idxdiv(c, channel_multiplier),\n            ].astype(out_dtype)\n            * kernel[\n                reduce_h, reduce_w, idxdiv(c, channel_multiplier), idxmod(c, channel_multiplier)\n            ].astype(out_dtype),\n            axis=[reduce_h, reduce_w],\n        ),\n        name=\"depthwise_conv2d_nhwc_output\",\n    )\n    return out\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nhwc.arm_cpu\")\ndef schedule_depthwise_conv2d_nhwc(cfg, outs):\n    \"\"\"Create the schedule for depthwise_conv2d_nchw_spatial_pack\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    out = outs[0]\n\n    ##### space definition begin #####\n    n, h, w, c = s[out].op.axis\n    # Split the number of input/output channels\n    cfg.define_split(\"tile_c\", c, num_outputs=2)\n    # Split the height of the convolution\n    _, hi = cfg.define_split(\"tile_h\", h, num_outputs=2)\n    # Split the width of the convolution\n    _, wi = cfg.define_split(\"tile_w\", w, num_outputs=2)\n    # Additional out (e.g., requantization, bias addition, etc..)\n    # 0: locate the output on the second last axis of the main compuation\n    # 1: locate the output closest to the main computation\n    cfg.define_knob(\"locate_output\", [0, 1])\n    # Determine if we should unroll the computation of the inner tile\n    cfg.define_knob(\"unroll_tile\", [True, False])\n\n    # fallback support\n    if cfg.is_fallback:\n        cfg[\"tile_c\"] = SplitEntity([-1, 8])\n        cfg[\"tile_h\"] = SplitEntity([-1, 2])\n        cfg[\"tile_w\"] = SplitEntity([-1, 2])\n        cfg[\"locate_output\"] = OtherOptionEntity(1)\n        cfg[\"unroll_tile\"] = OtherOptionEntity(True)\n    ##### space definition end #####\n\n    def schedule_conv(conv):\n        conv_data = conv.op.input_tensors[0]\n        kernel_data = conv.op.input_tensors[1]\n        in_type = conv_data.dtype\n\n        _, _, IC, channel_multiplier = get_const_tuple(kernel_data.shape)\n\n        n, w, h, c = conv.op.axis\n        r_h, r_w = conv.op.reduce_axis\n        ho, hi = cfg[\"tile_h\"].apply(s, conv, h)\n        wo, wi = cfg[\"tile_w\"].apply(s, conv, w)\n        co, ci = cfg[\"tile_c\"].apply(s, conv, c)\n\n        split_val = cfg[\"tile_c\"].size[-1]\n        target = Target.current(allow_none=False)\n        use_tensorization = (\n            (in_type == \"int16\")\n            and (split_val == 8)\n            and (IC % split_val == 0)\n            and (channel_multiplier == 1)\n            and target.features.has_asimd\n        )\n\n        data_pad_value = -1\n        if conv_data.name == \"data_pad\":\n            assert isinstance(conv_data.op, tvm.te.ComputeOp)\n            # Define a strategy for padding computation\n            cfg.define_knob(\"data_pad_strategy\", [1, 2, 3])\n            if cfg.is_fallback:\n                # We cannot inline padding when tensorizing.\n                # So, if we can tensorize, let's compute_at the closest axis\n                cfg[\"data_pad_strategy\"] = (\n                    OtherOptionEntity(2) if use_tensorization else OtherOptionEntity(3)\n                )\n            # Compute padding on the third to last axis of the computation\n            if cfg[\"data_pad_strategy\"].val == 1:\n                s[conv_data].vectorize(list(s[conv_data].op.axis)[-1])\n                s[conv_data].compute_at(s[conv], ho)\n            # Compute padding on the second to last axis of the computation\n            if cfg[\"data_pad_strategy\"].val == 2:\n                s[conv_data].vectorize(list(s[conv_data].op.axis)[-1])\n                s[conv_data].compute_at(s[conv], wo)\n            # Inline padding during computation\n            if cfg[\"data_pad_strategy\"].val == 3:\n                s[conv_data].compute_inline()\n            data_pad_value = cfg[\"data_pad_strategy\"].val\n\n        if use_tensorization and data_pad_value != 3:\n            smlal = smlal_int16_int32()\n            s[conv].tensorize(ci, smlal)\n        else:\n            s[conv].vectorize(ci)\n\n        if cfg[\"unroll_tile\"].val:\n            s[conv].unroll(r_h)\n            s[conv].unroll(r_w)\n            s[conv].unroll(wi)\n            s[conv].unroll(hi)\n\n        s[conv].reorder(n, ho, wo, co, hi, wi, r_h, r_w, ci)\n        fused_n_ho = s[conv].fuse(n, ho)\n        return fused_n_ho\n\n    def schedule_conv_out(out):\n        n, h, w, c = out.op.axis\n        co, ci = cfg[\"tile_c\"].apply(s, out, c)\n        wo, wi = cfg[\"tile_w\"].apply(s, out, w)\n        ho, hi = cfg[\"tile_h\"].apply(s, out, h)\n        s[out].reorder(n, ho, wo, co, hi, wi, ci)\n        if cfg[\"unroll_tile\"]:\n            s[out].unroll(wi)\n            s[out].unroll(hi)\n\n        if out.dtype in [\"int8\", \"uint8\"]:\n            # In case of quantized convolution further split the channel in batches of 4 elements\n            # so that we can use arm intrinsics to run fixed_point_multiplication\n            ci_outer, ci_inner = s[out].split(ci, 4)\n            s[out].vectorize(ci_inner)\n            s[out].unroll(ci_outer)\n\n        fused_n_ho = s[out].fuse(n, ho)\n        return hi, wi, fused_n_ho\n\n    def _callback(op):\n        if op.name == \"depthwise_conv2d_nhwc_output\":\n            conv = op.output(0)\n            if conv != out:\n                hi, wi, p_axis = schedule_conv_out(out)\n                schedule_conv(conv)\n                if cfg[\"locate_output\"].val == 0:\n                    s[conv].compute_at(s[out], hi)\n                if cfg[\"locate_output\"].val == 1:\n                    s[conv].compute_at(s[out], wi)\n            else:\n                p_axis = schedule_conv(out)\n\n            s[out].parallel(p_axis)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw_spatial_pack.arm_cpu\")\ndef schedule_depthwise_conv2d_nchw_spatial_pack(cfg, outs):\n    \"\"\"Create the schedule for depthwise_conv2d_nchw_spatial_pack\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"spatial_depthwise_conv2d_nchw_output\":\n            output = op.output(0)\n            conv = op.input_tensors[0]\n            data_vec = conv.op.input_tensors[0]\n            kernel_vec = conv.op.input_tensors[1]\n            if kernel_vec.op.name == \"kernel_vec\":\n                kernel = kernel_vec.op.input_tensors[0]\n            else:\n                kernel = kernel_vec\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            _schedule_spatial_pack(cfg, s, data_vec, kernel_vec, conv, output, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _decl_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile):\n    out_dtype = out_dtype or data.dtype\n\n    N, C, IH, IW = get_const_tuple(data.shape)\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    if len(kernel.shape) == 4:\n        pre_packed = False\n        C, M, KH, KW = get_const_tuple(kernel.shape)\n    else:  # kernel tensor is pre packed\n        pre_packed = True\n        C, M, KH, KW, VC = get_const_tuple(kernel.shape)\n        C = C * VC\n\n    dilated_kernel_h = (KH - 1) * dilation_h + 1\n    dilated_kernel_w = (KW - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    OH = (IH + pad_top + pad_down - dilated_kernel_h) // HSTR + 1\n    OW = (IW + pad_left + pad_right - dilated_kernel_w) // WSTR + 1\n    # pack data\n    HPAD = pad_top + pad_down\n    WPAD = pad_left + pad_right\n    DOPAD = HPAD != 0 or WPAD != 0\n    if DOPAD:\n        data_pad = nn.pad(\n            data, (0, 0, pad_top, pad_left), (0, 0, pad_down, pad_right), name=\"data_pad\"\n        )\n    else:\n        data_pad = data\n\n    # fallback support\n    # Currently, Mali schedule doesn't use it like conv2d.\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            \"arm_cpu\", \"rk3399\", \"depthwise_conv2d_nchw_spatial_pack.arm_cpu\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n\n    # ==================== define configuration space ====================\n    n, c, oh, ow = cfg.axis(N), cfg.axis(C), cfg.axis(OH), cfg.axis(OW)\n    kh, kw = cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n\n    # Currently, Mali schedule doesn't use it like conv2d.\n    # Leave num_tile for possible future use of Mali schedule\n    if num_tile == 2:  # for arm cpu\n        co, vc = cfg.define_split(\"tile_co\", c, num_outputs=2)\n        oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2)\n        ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2)\n    else:\n        raise RuntimeError(\"Invalid num_tile\")\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [n, co, oh, ow, kh, kw, vh, vw, vc],\n        policy=\"candidate\",\n        candidate=[[n, co, oh, ow, kh, kw, vh, vw, vc], [n, co, oh, ow, kh, kw, vc, vh, vw]],\n    )\n\n    cfg.define_reorder(\n        \"reorder_1\",\n        [n, co, oh, ow, vh, vw, vc],\n        policy=\"candidate\",\n        candidate=[\n            [n, co, oh, ow, vh, vw, vc],\n            [n, co, oh, ow, vc, vh, vw],\n            [n, co, oh, ow, vh, vc, vw],\n        ],\n    )\n\n    cfg.define_annotate(\"ann_reduce\", [kh, kw], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [vh, vw, vc], policy=\"try_unroll_vec\")\n    # ====================================================================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    kvshape = (C // VC, M, KH, KW, VC)\n    ovshape = (N, C * M // VC, OH // VH, OW // VW, VH, VW, VC)\n    oshape = (N, C * M, OH, OW)\n\n    if dilation_h != 1 or dilation_w != 1:\n        # undilate input data\n        dvshape = (N, OH // VH, OW // VW, C, KH, KW, VH, VW)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, h, w, c, kh, kw, vh, vw: data_pad[n][c][\n                (h * VH + vh) * HSTR + kh * dilation_h\n            ][(w * VW + vw) * WSTR + kw * dilation_w],\n            name=\"data_vec_undilated\",\n        )\n    else:\n        dvshape = (N, OH // VH, OW // VW, C, VH * HSTR + KH - 1, VW * WSTR + KW - 1)\n        data_vec = te.compute(\n            dvshape,\n            lambda n, h, w, c, vh, vw: data_pad[n][c][h * VH * HSTR + vh][w * VW * WSTR + vw],\n            name=\"data_vec\",\n        )\n\n    if pre_packed:\n        kernel_vec = kernel\n    else:\n        kernel_vec = te.compute(\n            kvshape, lambda co, m, kh, kw, vc: kernel[co * VC + vc][m][kh][kw], name=\"kernel_vec\"\n        )\n\n    kh = te.reduce_axis((0, KH), name=\"kh\")\n    kw = te.reduce_axis((0, KW), name=\"kw\")\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    if dilation_h != 1 or dilation_w != 1:\n        conv = te.compute(\n            ovshape,\n            lambda n, co, h, w, vh, vw, vc: te.sum(\n                data_vec[n, h, w, idxdiv(co * VC + vc, M), kh, kw, vh, vw].astype(out_dtype)\n                * kernel_vec[idxdiv(co, M), idxmod(co, M), kh, kw, vc].astype(out_dtype),\n                axis=[kh, kw],\n            ),\n            name=\"depthwise_conv\",\n        )\n    else:\n        conv = te.compute(\n            ovshape,\n            lambda n, co, h, w, vh, vw, vc: te.sum(\n                data_vec[n, h, w, idxdiv((co * VC + vc), M), vh * HSTR + kh, vw * WSTR + kw].astype(\n                    out_dtype\n                )\n                * kernel_vec[idxdiv(co, M), idxmod(co, M), kh, kw, vc].astype(out_dtype),\n                axis=[kh, kw],\n            ),\n            name=\"depthwise_conv\",\n        )\n\n    output = te.compute(\n        oshape,\n        lambda n, co, h, w: conv[\n            n,\n            idxdiv(co, VC),\n            idxdiv(h, VH),\n            idxdiv(w, VW),\n            idxmod(h, VH),\n            idxmod(w, VW),\n            idxmod(co, VC),\n        ],\n        name=\"output_unpack\",\n        tag=\"spatial_depthwise_conv2d_nchw_output\",\n    )\n    return output\n\n\ndef _schedule_spatial_pack(cfg, s, data_vec, kernel_vec, conv, output, last):\n    \"\"\"schedule implementation\"\"\"\n    n, co, oh, ow, vh, vw, vc = s[conv].op.axis\n    kh, kw = s[conv].op.reduce_axis\n\n    if data_vec.op.name == \"data_vec_undilated\":\n        _, dv_oh, dv_ow, dv_c, _, _, dv_vh, dv_vw = s[data_vec].op.axis\n    else:\n        _, dv_oh, dv_ow, dv_c, dv_vh, dv_vw = s[data_vec].op.axis\n\n    data_pad = data_vec.op.input_tensors[0]\n    if data_pad.op.name == \"data_pad\":\n        assert isinstance(data_pad.op, tvm.te.ComputeOp)\n        has_padding = True\n    else:\n        assert isinstance(data_pad.op, tvm.te.PlaceholderOp)\n        has_padding = False\n\n    cfg.define_knob(\"data_pad_inline\", [0, 1, 2, 3, 4])\n\n    if cfg[\"data_pad_inline\"].val == 1 and has_padding:\n        s[data_pad].compute_inline()\n    if cfg[\"data_pad_inline\"].val == 2 and has_padding:\n        s[data_pad].vectorize(list(s[data_pad].op.axis)[-1])\n    if cfg[\"data_pad_inline\"].val == 3 and has_padding:\n        s[data_pad].vectorize(list(s[data_pad].op.axis)[-1])\n        s[data_pad].compute_at(s[data_vec], dv_oh)\n    if cfg[\"data_pad_inline\"].val == 4 and has_padding:\n        s[data_pad].vectorize(list(s[data_pad].op.axis)[-1])\n        s[data_pad].compute_at(s[data_vec], dv_ow)\n\n    cfg.define_knob(\"data_vec_inline\", [0, 1, 2, 3])\n    if cfg[\"data_vec_inline\"].val == 1:\n        s[data_vec].compute_at(s[conv], oh)\n    if cfg[\"data_vec_inline\"].val == 2:\n        s[data_vec].compute_at(s[conv], ow)\n    if cfg[\"data_vec_inline\"].val == 3:\n        s[data_vec].compute_at(s[conv], co)\n\n    # schedule conv\n    cfg[\"reorder_0\"].apply(s, conv, [n, co, oh, ow, kh, kw, vh, vw, vc])\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv,\n        [kh, kw],\n        axis_lens=[get_const_int(kh.dom.extent), get_const_int(kw.dom.extent)],\n        max_unroll=16,\n        cfg=cfg,\n    )\n    cfg[\"ann_spatial\"].apply(\n        s,\n        conv,\n        [vh, vw, vc],\n        axis_lens=[cfg[\"tile_oh\"].size[-1], cfg[\"tile_ow\"].size[-1], cfg[\"tile_co\"].size[-1]],\n        max_unroll=16,\n        cfg=cfg,\n    )\n\n    # schedule fusion\n    n, co, h, w = s[last].op.axis\n    co, vc = cfg[\"tile_co\"].apply(s, last, co)\n    oh, vh = cfg[\"tile_oh\"].apply(s, last, h)\n    ow, vw = cfg[\"tile_ow\"].apply(s, last, w)\n    cfg[\"reorder_1\"].apply(s, last, [n, co, oh, ow, vh, vw, vc])\n    if last != output:\n        s[output].compute_inline()\n        cfg[\"ann_spatial\"].apply(\n            s,\n            last,\n            [vh, vw, vc],\n            axis_lens=[cfg[\"tile_oh\"].size[-1], cfg[\"tile_ow\"].size[-1], cfg[\"tile_co\"].size[-1]],\n            max_unroll=16,\n            cfg=cfg,\n        )\n    else:\n        s[last].vectorize(vw)\n    cfg.define_knob(\"conv_inline\", [0, 1, 2, 3])\n    if cfg[\"conv_inline\"].val == 1:\n        s[conv].compute_at(s[last], ow)\n    if cfg[\"conv_inline\"].val == 2:\n        s[conv].compute_at(s[last], oh)\n    if cfg[\"conv_inline\"].val == 3:\n        s[conv].compute_at(s[last], co)\n\n    # mark parallel\n    s[last].parallel(co)\n\n    if data_vec.op.name == \"data_vec_undilated\":\n        _, h, _, _, _, _, _, _ = s[data_vec].op.axis\n    else:\n        _, h, _, _, _, _ = s[data_vec].op.axis\n    s[data_vec].parallel(h)\n\n    if kernel_vec.op.name == \"kernel_vec\":\n        co, _, _, _, _ = s[kernel_vec].op.axis\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # kernel packing will be pre-computed during compilation, so we skip\n            # this part to make tuning records correct\n            s[kernel_vec].pragma(co, \"debug_skip_region\")\n        else:\n            s[kernel_vec].parallel(co)\n\n    return s\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nhwc_dsp.arm_cpu\")\ndef depthwise_conv2d_nhwc_dsp(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d_nhwc with v7e-m DSP instructions.\"\"\"\n    return depthwise_conv2d_nhwc_dsp_compute(\n        cfg, data, kernel, strides, padding, dilation, out_dtype\n    )\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nhwc_dsp.arm_cpu\")\ndef schedule_depthwise_conv2d_nhwc_dsp(cfg, outs):\n    \"\"\"Create schedule for conv2d_nhwc_dsp\"\"\"\n    return depthwise_conv2d_nhwc_dsp_schedule(cfg, outs)\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw_oihw_dsp.arm_cpu\")\ndef depthwise_conv2d_nchw_oihw_dsp(\n    cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype\n):\n    \"\"\"Compute depthwise_conv2d_nchw_oihw with v7e-m DSP instructions and the tensordot kernel.\"\"\"\n    return depthwise_conv2d_nchw_oihw_dsp_compute(\n        cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype\n    )\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw_oihw_dsp.arm_cpu\")\ndef schedule_depthwise_conv2d_nchw_oihw_dsp(cfg, outs):\n    \"\"\"Create schedule for depthwise_conv2d_nchw_oihw.\"\"\"\n    return tensordot_conv2ds_schedule(cfg, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter,import-outside-toplevel\n\"\"\"Grouped Spatial Pack Convolution (Group Conv2D) schedule on ARM\"\"\"\n\nimport tvm\nfrom tvm import autotvm\nfrom tvm import te\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom ..utils import get_const_tuple\nfrom ..nn.pad import pad\nfrom .. import tag\n\nfrom ..nn.conv2d import _get_workload as _get_conv2d_workload\n\n\ndef group_conv2d_nchw(data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"Compute group_conv2d with NCHW layout\"\"\"\n    return group_conv2d_nchw_spatial_pack(\n        data, kernel, strides, padding, dilation, groups, out_dtype\n    )\n\n\ndef schedule_group_conv2d_nchw(outs):\n    \"\"\"Compute group_conv2d with NCHW layout\"\"\"\n    return schedule_group_conv2d_nchwc(outs)\n\n\ndef _get_default_config(\n    cfg, data, kernel, strides, padding, dilation, groups, out_dtype, layout=\"NCHW\"\n):\n    \"\"\"\n    Get default schedule config for the workload\n    \"\"\"\n    static_data_shape = []\n    for dim in get_const_tuple(data.shape):\n        if isinstance(dim, tvm.tir.Var):\n            static_data_shape.append(1)\n        else:\n            static_data_shape.append(dim)\n    data = te.placeholder(static_data_shape, dtype=data.dtype)\n\n    wkl = _get_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype, layout)\n    _fallback_schedule(cfg, wkl)\n\n\ndef _fallback_schedule(cfg, wkl):\n    simd_width = 4  # assume ARM SIMD Width is 4\n    pad_left, pad_right = wkl.padl, wkl.padr\n    stride_w = wkl.stride_w\n    out_width = (wkl.width + pad_left + pad_right - wkl.kernel_w) // stride_w + 1\n    groups = wkl.groups\n    kernels_per_group = wkl.out_filter // groups\n    kernel_depth = wkl.in_filter // groups\n\n    oc_bn = 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if kernels_per_group % bn == 0:\n            oc_bn = bn\n            break\n    if oc_bn > kernels_per_group:\n        oc_bn = kernels_per_group\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if kernel_depth % bn == 0:\n            ic_bn = bn\n            break\n    if ic_bn > kernel_depth:\n        ic_bn = kernel_depth\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\n@autotvm.register_topi_compute(\"group_conv2d_nchw.arm_cpu\")\ndef group_conv2d_nchw_spatial_pack(\n    cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"\n):\n    \"\"\"\n    Compute group conv2d with NCHW layout, using GSPC algorithm.\n    https://arxiv.org/abs/2006.09791\n    \"\"\"\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(dilation, int):\n        dilation_h, dilation_w = dilation, dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    assert isinstance(padding, int) or len(padding) == 2 or len(padding) == 4\n    if isinstance(padding, int):\n        pad_top, pad_left, pad_bottom, pad_right = padding, padding, padding, padding\n    elif len(padding) == 2:\n        hpad, wpad = padding\n        pad_top, pad_bottom = hpad, hpad\n        pad_left, pad_right = wpad, wpad\n    else:\n        pad_top, pad_left, pad_bottom, pad_right = padding\n\n    hpad = pad_top + pad_bottom\n    wpad = pad_left + pad_right\n\n    assert isinstance(strides, int) or len(strides) == 2\n    if isinstance(strides, int):\n        stride_h, stride_w = strides, strides\n    else:\n        stride_h, stride_w = strides\n\n    batch_size, in_channel, in_height, in_width = get_const_tuple(data.shape)\n    out_channel, kernel_depth, k_height, k_width = get_const_tuple(kernel.shape)\n\n    pad_height = in_height + pad_top + pad_bottom\n    pad_width = in_width + pad_left + pad_right\n\n    dilated_kernel_h = (k_height - 1) * dilation_h + 1\n    dilated_kernel_w = (k_width - 1) * dilation_w + 1\n    out_height = (in_height + pad_top + pad_bottom - dilated_kernel_h) // stride_h + 1\n    out_width = (in_width + pad_left + pad_right - dilated_kernel_w) // stride_w + 1\n\n    kernels_per_group = out_channel // groups\n\n    cfg.define_split(\"tile_ic\", in_channel, num_outputs=2)\n    cfg.define_split(\"tile_oc\", out_channel, num_outputs=2)\n    cfg.define_split(\"tile_ow\", out_width, num_outputs=2, filter=lambda y: y.size[-1] <= 64)\n    cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # If no config was set, we can fallback to default config.\n    if cfg.is_fallback:\n        _get_default_config(\n            cfg,\n            te.placeholder((batch_size, in_channel, in_height, in_width), dtype=data.dtype),\n            te.placeholder(\n                (out_channel, in_channel // groups, k_height, k_width), dtype=kernel.dtype\n            ),\n            strides,\n            padding,\n            dilation,\n            groups,\n            out_dtype,\n        )\n\n    oc_bn = cfg[\"tile_oc\"].size[-1]\n    ic_bn = cfg[\"tile_ic\"].size[-1]\n\n    # pack data\n    DOPAD = hpad != 0 or wpad != 0\n    if DOPAD:\n        data_pad = pad(\n            data, (0, 0, pad_top, pad_left), (0, 0, pad_bottom, pad_right), name=\"data_pad\"\n        )\n    else:\n        data_pad = data\n\n    shape = (groups, batch_size, kernel_depth // ic_bn, pad_height, ic_bn, pad_width)\n\n    data_vec = te.compute(\n        shape,\n        lambda g, n, C, h, c, w: data_pad[n, C * ic_bn + c + kernel_depth * g, h, w],\n        name=\"data_vec\",\n    )\n\n    # pack kernel\n    shape = (\n        groups,\n        kernels_per_group // oc_bn,\n        kernel_depth // ic_bn,\n        k_height,\n        k_width,\n        ic_bn,\n        oc_bn,\n    )\n\n    kernel_vec = te.compute(\n        shape,\n        lambda g, out_channel, in_channel, h, w, ci, co: kernel[\n            (out_channel * oc_bn + co + g * kernels_per_group), in_channel * ic_bn + ci, h, w\n        ],\n        name=\"kernel_vec\",\n    )\n\n    # convolution\n    oshape = (groups, batch_size, kernels_per_group // oc_bn, out_height, out_width, oc_bn)\n    unpack_shape = (batch_size, out_channel, out_height, out_width)\n\n    ic = te.reduce_axis((0, (kernel_depth)), name=\"ic\")\n    kh = te.reduce_axis((0, k_height), name=\"kh\")\n    kw = te.reduce_axis((0, k_width), name=\"kw\")\n\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n\n    conv = te.compute(\n        oshape,\n        lambda g, n, oc_chunk, oh, ow, oc_block: te.sum(\n            data_vec[\n                g,\n                n,\n                idxdiv(ic, ic_bn),\n                oh * stride_h + kh * dilation_h,\n                idxmod(ic, ic_bn),\n                ow * stride_w + kw * dilation_w,\n            ].astype(out_dtype)\n            * kernel_vec[\n                g, oc_chunk, idxdiv(ic, ic_bn), kh, kw, idxmod(ic, ic_bn), oc_block\n            ].astype(out_dtype),\n            axis=[ic, kh, kw],\n        ),\n        name=\"conv\",\n    )\n\n    unpack = te.compute(\n        unpack_shape,\n        lambda n, c, h, w: conv[\n            idxdiv(c, kernels_per_group),\n            n,\n            idxmod(idxdiv(c, oc_bn), (kernels_per_group // oc_bn)),\n            h,\n            w,\n            idxmod(idxmod(c, oc_bn), kernels_per_group),\n        ].astype(out_dtype),\n        name=\"output_unpack\",\n        tag=\"group_conv2d_nchw\",\n    )\n\n    return unpack\n\n\n@autotvm.register_topi_schedule(\"group_conv2d_nchw.arm_cpu\")\ndef schedule_group_conv2d_nchwc(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n\n        if \"group_conv2d_nchw\" in op.tag:\n            output = op.output(0)\n\n            if \"tile_ic\" not in cfg:\n                return\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel = kernel_vec.op.input_tensors[0]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            data_vec = conv_out.op.input_tensors[0]\n            data = data_vec.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            args = [s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, outs[0]]\n            _schedule_gspc_nchw(*args)\n\n        scheduled_ops.append(op)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef _schedule_gspc_nchw(s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, last):\n    \"\"\"Schedule GSPC\"\"\"\n    ic_bn, oc_bn, reg_n, unroll_kw = (\n        cfg[\"tile_ic\"].size[-1],\n        cfg[\"tile_oc\"].size[-1],\n        cfg[\"tile_ow\"].size[-1],\n        cfg[\"unroll_kw\"].val,\n    )\n\n    _, W = data, kernel_vec\n    A0, A1 = data_pad, data_vec\n\n    # schedule data\n    if (\n        data_pad is not None\n        and isinstance(data_pad.op, tvm.te.ComputeOp)\n        and \"pad\" in data_pad.op.tag\n    ):\n        s[A0].compute_inline()\n\n    groups, batch, ic_chunk, ih, ic_block, _ = s[A1].op.axis\n\n    parallel_axis = s[A1].fuse(batch, ic_chunk, ih)\n    s[A1].parallel(parallel_axis)\n\n    # schedule kernel pack\n    groups, oc_chunk, ic_chunk, oh, ow, ic_block, oc_block = s[W].op.axis\n    s[W].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n\n    if oc_bn > 1:\n        s[W].vectorize(oc_block)\n\n    parallel_axis = s[W].fuse(groups, oc_chunk, oh)\n    s[W].parallel(parallel_axis)\n\n    # schedule conv\n    C, O0, O = conv_out, output, last\n    CC = s.cache_write(C, \"global\")\n\n    _, _, oc_chunk, oh, ow, oc_block = s[C].op.axis\n\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n\n    s[C].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    s[C].fuse(oc_chunk, oh)\n    s[C].vectorize(oc_block)\n\n    groups, batch, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n\n    ic, kh, kw = s[CC].op.reduce_axis\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    if unroll_kw:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, ic_block, kw, ow_block, oc_block)\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, kw, ic_block, ow_block, oc_block)\n\n    parallel_axis = s[CC].fuse(groups, batch, oc_chunk, oh)\n    s[CC].parallel(parallel_axis)\n\n    s[CC].vectorize(oc_block)\n\n    s[CC].unroll(ow_block)\n\n    if O0 != O:\n        s[O0].compute_inline()\n\n    batch, oc, oh, ow = s[O].op.axis\n    ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n    oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n\n    s[O].reorder(batch, oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[O].fuse(oc_chunk, oh)\n    s[O].vectorize(oc_block)\n    s[O].parallel(parallel_axis)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"Schedule for pooling operators\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom ..utils import is_empty_shape\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n    if len(sch[out].op.axis) >= 4:\n        fused = sch[out].fuse(sch[out].op.axis[0], sch[out].op.axis[1], sch[out].op.axis[2])\n        sch[out].parallel(fused)\n    elif len(sch[out].op.axis) >= 3:\n        fused = sch[out].fuse(sch[out].op.axis[0], sch[out].op.axis[1])\n        sch[out].parallel(fused)\n    elif len(sch[out].op.axis) >= 2:\n        sch[out].parallel(sch[out].op.axis[0])\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"ARM CPU schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    x = outs[0]\n\n    if list(s[x].op.axis):\n        # do not vectorize for broadcast\n        (io, ii) = s[x].split(list(s[x].op.axis)[-1], 16 // np.dtype(x.dtype).itemsize)\n        s[x].vectorize(ii)\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    if not is_empty_shape(x.shape):\n        schedule_injective_from_existing(s, x)\n    return s\n\n\ndef schedule_concatenate(outs):\n    \"\"\"Schedule for concatenate op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of concatenate in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    x = outs[0]\n    tvm.te.schedule.AutoInlineInjective(s)\n    if len(s[x].op.axis) >= 4:\n        fused = s[x].fuse(s[x].op.axis[0], s[x].op.axis[1], s[x].op.axis[2])\n        s[x].parallel(fused)\n    elif len(s[x].op.axis) >= 3:\n        fused = s[x].fuse(s[x].op.axis[0], s[x].op.axis[1])\n        s[x].parallel(fused)\n    elif len(s[x].op.axis) >= 2:\n        s[x].parallel(s[x].op.axis[0])\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Schedules specialized for cortex-m DSP instructions.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Direct implementation of conv1d.\"\"\"\nfrom tvm import autotvm\nfrom tvm.autotvm.task import deserialize_args\nfrom tvm import te\nfrom tvm.topi.utils import simplify, traverse_inline\nfrom tvm.topi.nn.pad import pad\nfrom tvm.topi.nn.utils import get_pad_tuple1d\nfrom tvm.tir.expr import Mul\n\nfrom .micro_kernel.gemm import (\n    intrin_gemm_MxKxN,\n    gemm_MxKxN_impl,\n)\n\n\ndef conv1d_nwc_dsp(*args, **kwargs):\n    \"\"\"Defines the v7e-m DSP instructions of conv1d on NWC layout.\"\"\"\n    assert not kwargs, \"Do not support kwargs in template function call\"\n    args = deserialize_args(args)\n    data, kernel = args[:2]\n    layout = args[-2]\n    cfg = autotvm.get_config()\n    args = [cfg] + args\n    assert layout == \"NWC\"\n    conv = conv1d_nwc_dsp_compute(*args)\n    sched = conv1d_nwc_dsp_schedule(cfg, [data, kernel, conv])\n    return sched, [data, kernel, conv]\n\n\nconv1d_nwc_dsp.template_key = \"dsp\"\nconv1d_nwc_dsp.default_data_layout = \"NWC\"\nconv1d_nwc_dsp.default_kernel_layout = \"WOI\"\n\n\ndef conv1d_nwc_dsp_compute(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute function for v7e-m DSP instructions of conv1d on NWC layout.\"\"\"\n    if isinstance(strides, (tuple, list)):\n        strides = strides[0]\n    if isinstance(dilation, (tuple, list)):\n        dilation = dilation[0]\n\n    batch_size, data_width, in_channels = data.shape\n    kernel_size, out_channels, _ = kernel.shape\n\n    # Compute the output shape\n    dilated_kernel_size = (kernel_size - 1) * dilation + 1\n    pad_left, pad_right = get_pad_tuple1d(padding, (dilated_kernel_size,))\n    out_channels = simplify(out_channels)\n    out_width = simplify((data_width - dilated_kernel_size + pad_left + pad_right) // strides + 1)\n\n    # Apply padding\n    pad_before = [0, pad_left, 0]\n    pad_after = [0, pad_right, 0]\n    padded_data = pad(data, pad_before, pad_after, name=\"padded_data\")\n\n    # Compute graph\n    rc = te.reduce_axis((0, in_channels), name=\"rc\")\n    rw = te.reduce_axis((0, kernel_size), name=\"rw\")\n\n    conv = te.compute(\n        (batch_size, out_width, out_channels),\n        lambda b, w, c: te.sum(\n            padded_data[b, w * strides + rw * dilation, rc].astype(out_dtype)\n            * kernel[rw, c, rc].astype(out_dtype),\n            axis=[rw, rc],\n        ),\n        name=\"conv1d\",\n        tag=\"conv1d_nwc\",\n    )\n\n    ###########################\n    # Config Space Definition #\n    ###########################\n    n, ow, co = (\n        cfg.axis(batch_size.value),\n        cfg.axis(out_width.value),\n        cfg.axis(out_channels.value),\n    )\n    kw, ci = (\n        cfg.reduce_axis(kernel_size.value),\n        cfg.reduce_axis(in_channels.value),\n    )\n\n    owo, owi = cfg.define_split(\"tile_ow\", ow, policy=\"factors\", num_outputs=2)\n    cio, cii = cfg.define_split(\n        \"tile_ci\",\n        ci,\n        policy=\"factors\",\n        num_outputs=2,\n        # TODO: check case with in_channels.value % 4 != 0 with AutoTVM\n        filter=None if cfg.is_fallback else lambda x: x.size[-1] % 4 == 0,\n    )\n    coo, coi = cfg.define_split(\"tile_co\", co, policy=\"factors\", num_outputs=2)\n\n    cfg.define_reorder(\n        \"reorder_0_simd\",\n        [n, owo, owi, coo, coi, kw, cio, cii],\n        policy=\"candidate\",\n        candidate=[\n            [n, kw, owo, coo, cio, owi, coi, cii],\n            [n, kw, coo, owo, cio, owi, coi, cii],\n            [n, kw, owo, coo, cio, owi, coi, cii],\n            [n, kw, coo, owo, cio, owi, coi, cii],\n        ],\n    )\n\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 2, 4, 8, 16, 32])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    if cfg.is_fallback:\n        cfg.fallback_split(\"tile_ow\", [-1, out_width.value])\n        cfg.fallback_split(\"tile_ci\", [-1, in_channels.value])\n        cfg.fallback_split(\"tile_co\", [-1, out_channels.value])\n\n    return conv\n\n\ndef conv1d_nwc_dsp_schedule(cfg, outs):\n    \"\"\"Schedule function for v7e-m DSP instructions of conv1d on NWC layout.\"\"\"\n    sched = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv1d_nwc\" not in op.tag:\n            return\n\n        # extract tensors\n        output = op.output(0)\n        conv = op\n        data_vec = conv.input_tensors[0]\n\n        source_index_w = output.op.body[0].source[0].a.value.indices[1].a\n        stride_w = source_index_w.b.value if isinstance(source_index_w, Mul) else 1\n\n        # tile reduction axes\n        n, ow, co = sched[conv].op.axis\n        kw, ci = sched[conv].op.reduce_axis\n\n        M = cfg[\"tile_ow\"].size[-1]\n        K = cfg[\"tile_ci\"].size[-1]\n        N = cfg[\"tile_co\"].size[-1]\n\n        owo, owi = cfg[\"tile_ow\"].apply(sched, conv, ow)\n        cio, cii = cfg[\"tile_ci\"].apply(sched, conv, ci)\n        coo, coi = cfg[\"tile_co\"].apply(sched, conv, co)\n\n        cfg[\"reorder_0_simd\"].apply(sched, conv, [n, owo, owi, coo, coi, kw, cio, cii])\n\n        gemm, uniq_id = intrin_gemm_MxKxN(M, K, N, data_vec.dtype, output.dtype, stride_w)\n        sched[output].tensorize(owi, gemm)\n        sched[output].pragma(n, \"import_c\", gemm_MxKxN_impl(M, K, N, uniq_id))\n\n        # this is the scope to attach global config inside this kernel\n        kernel_scope = n\n\n        # tune unroll\n        sched[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        sched[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(sched, outs[-1].op, _callback)\n    return sched\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Direct implementation of conv2d.\"\"\"\n\nfrom tvm import autotvm\nfrom tvm.autotvm.task import deserialize_args\nfrom tvm import te\nfrom tvm.topi.utils import simplify, traverse_inline\nfrom tvm.topi.nn.pad import pad\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.tir.expr import Mul\n\nfrom .micro_kernel.gemm import (\n    intrin_gemm_MxKxN,\n    gemm_MxKxN_impl,\n)\n\n\ndef conv2d_nhwc_dsp(*args, **kwargs):\n    \"\"\"Defines the v7e-m DSP instructions of conv2d.\"\"\"\n    assert not kwargs, \"Do not support kwargs in template function call\"\n    args = deserialize_args(args)\n    data, kernel = args[:2]\n    layout = args[-2]\n    cfg = autotvm.get_config()\n    args = [cfg] + args\n    assert layout == \"NHWC\"\n    conv = conv2d_nhwc_dsp_compute(*args)\n    sched = conv2d_nhwc_dsp_schedule(cfg, [data, kernel, conv])\n    return sched, [data, kernel, conv]\n\n\nconv2d_nhwc_dsp.template_key = \"dsp\"\nconv2d_nhwc_dsp.default_data_layout = \"NHWC\"\nconv2d_nhwc_dsp.default_kernel_layout = \"HWOI\"\n\n\ndef conv2d_nhwc_dsp_compute(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute function for v7e-m DSP instructions of conv2d.\"\"\"\n    assert isinstance(strides, int) or len(strides) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(strides, int):\n        stride_h = stride_w = strides\n    else:\n        stride_h, stride_w = strides\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch_size, in_height, in_width, in_channels = data.shape\n    kernel_h, kernel_w, out_channels, _ = kernel.shape\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    padded_data = pad(data, pad_before, pad_after, name=\"padded_data\")\n\n    rc = te.reduce_axis((0, in_channels), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    conv = te.compute(\n        (batch_size, out_height, out_width, out_channels),\n        lambda nn, yy, xx, ff: te.sum(\n            padded_data[\n                nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rc\n            ].astype(out_dtype)\n            * kernel[ry, rx, ff, rc].astype(out_dtype),\n            axis=[ry, rx, rc],\n        ),\n        name=\"conv2d\",\n        tag=\"conv2d_nhwc\",\n    )\n\n    ###########################\n    # Config Space Definition #\n    ###########################\n    n, oh, ow, co = (\n        cfg.axis(batch_size.value),\n        cfg.axis(out_height.value),\n        cfg.axis(out_width.value),\n        cfg.axis(out_channels.value),\n    )\n    kh, kw, ci = (\n        cfg.reduce_axis(kernel_h.value),\n        cfg.reduce_axis(kernel_w.value),\n        cfg.reduce_axis(in_channels.value),\n    )\n\n    owo, owi = cfg.define_split(\"tile_ow\", ow, policy=\"factors\", num_outputs=2)\n    cio, cii = cfg.define_split(\n        \"tile_ci\",\n        ci,\n        policy=\"factors\",\n        num_outputs=2,\n        # TODO: check case with in_channels.value % 4 != 0 with AutoTVM\n        filter=None if cfg.is_fallback else lambda x: x.size[-1] % 4 == 0,\n    )\n    coo, coi = cfg.define_split(\"tile_co\", co, policy=\"factors\", num_outputs=2)\n\n    cfg.define_reorder(\n        \"reorder_0_simd\",\n        [n, oh, owo, owi, coo, coi, kh, kw, cio, cii],\n        policy=\"candidate\",\n        candidate=[\n            [n, oh, kh, kw, owo, coo, cio, owi, coi, cii],\n            [n, oh, kh, kw, coo, owo, cio, owi, coi, cii],\n            [n, kh, kw, oh, owo, coo, cio, owi, coi, cii],\n            [n, kh, kw, oh, coo, owo, cio, owi, coi, cii],\n        ],\n    )\n\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 2, 4, 8, 16, 32])\n    cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    if cfg.is_fallback:\n        cfg.fallback_split(\"tile_ow\", [-1, out_width.value])\n        cfg.fallback_split(\"tile_ci\", [-1, in_channels.value])\n        cfg.fallback_split(\"tile_co\", [-1, out_channels.value])\n\n    return conv\n\n\ndef conv2d_nhwc_dsp_schedule(cfg, outs):\n    \"\"\"Schedule function for v7e-m DSP instructions of conv2d.\"\"\"\n    sched = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc\" not in op.tag:\n            return\n\n        # extract tensors\n        output = op.output(0)\n        conv = op\n        data_vec = conv.input_tensors[0]\n        kernel = conv.input_tensors[1]  # pylint: disable=unused-variable\n        last = outs[0]  # pylint: disable=unused-variable\n\n        source_index_w = output.op.body[0].source[0].a.value.indices[2].a\n        stride_w = source_index_w.b.value if isinstance(source_index_w, Mul) else 1\n\n        # tile reduction axes\n        n, oh, ow, co = sched[conv].op.axis\n        kh, kw, ci = sched[conv].op.reduce_axis\n\n        M = cfg[\"tile_ow\"].size[-1]\n        K = cfg[\"tile_ci\"].size[-1]\n        N = cfg[\"tile_co\"].size[-1]\n\n        owo, owi = cfg[\"tile_ow\"].apply(sched, conv, ow)\n        cio, cii = cfg[\"tile_ci\"].apply(sched, conv, ci)\n        coo, coi = cfg[\"tile_co\"].apply(sched, conv, co)\n\n        cfg[\"reorder_0_simd\"].apply(sched, conv, [n, oh, owo, owi, coo, coi, kh, kw, cio, cii])\n\n        gemm, uniq_id = intrin_gemm_MxKxN(M, K, N, data_vec.dtype, output.dtype, stride_w)\n        sched[output].tensorize(owi, gemm)\n        sched[output].pragma(n, \"import_c\", gemm_MxKxN_impl(M, K, N, uniq_id))\n\n        # this is the scope to attach global config inside this kernel\n        kernel_scope = n\n\n        # tune unroll\n        sched[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        sched[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(sched, outs[-1].op, _callback)\n    return sched\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Direct implementation of dense.\"\"\"\n\nfrom tvm import te\nfrom tvm.topi.utils import traverse_inline, get_const_tuple\n\nfrom .micro_kernel.gemm import (\n    intrin_gemm_MxKxN,\n    gemm_MxKxN_impl,\n)\nfrom .... import tag\n\n\ndef dense_dsp_compute(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Defines the v7e-m DSP instructions of dense.\"\"\"\n    M, K = get_const_tuple(data.shape)\n    N, _ = get_const_tuple(weight.shape)\n\n    cfg.define_split(\"tile_x\", M, policy=\"factors\", num_outputs=2)\n    cfg.define_split(\"tile_y\", N, policy=\"factors\", num_outputs=2)\n    cfg.define_split(\"tile_k\", K, policy=\"factors\", num_outputs=2)\n\n    k = te.reduce_axis((0, K), \"k\")\n    C = te.compute(\n        (M, N),\n        lambda x, y: te.sum(\n            data[x, k].astype(out_dtype) * weight[y, k].astype(out_dtype),\n            axis=k,\n        ),\n        name=\"dense\",\n        tag=\"dense_dsp\",\n    )\n\n    if bias is not None:\n        C = te.compute((M, N), lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST)\n    return C\n\n\ndef dense_dsp_schedule(cfg, outs):\n    \"\"\"Schedule function for v7e-m DSP instructions of dense.\"\"\"\n    sched = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"dense\" not in op.tag:\n            return\n\n        output = op.output(0)\n        dense = op\n\n        data = dense.input_tensors[0]\n\n        M = cfg[\"tile_x\"].size[-1]\n        N = cfg[\"tile_y\"].size[-1]\n        K = cfg[\"tile_k\"].size[-1]\n\n        x, y = sched[dense].op.axis\n        k = sched[dense].op.reduce_axis[0]\n\n        x_o, x_i = cfg[\"tile_x\"].apply(sched, dense, x)\n        y_o, y_i = cfg[\"tile_y\"].apply(sched, dense, y)\n        k_o, k_i = cfg[\"tile_k\"].apply(sched, dense, k)\n\n        sched[dense].reorder(x_o, y_o, k_o, x_i, y_i, k_i)\n\n        gemm, uniq_id = intrin_gemm_MxKxN(M, K, N, data.dtype, output.dtype, stride_w=1)\n        sched[output].tensorize(x_i, gemm)\n        sched[output].pragma(x_o, \"import_c\", gemm_MxKxN_impl(M, K, N, uniq_id))\n\n    traverse_inline(sched, outs[-1].op, _callback)\n    return sched\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"ARM Cortex-M DSP schedule for depthwise_conv2d\"\"\"\n\nimport random\nimport string\n\nfrom tvm import te, topi\nfrom tvm.topi.utils import traverse_inline\nfrom tvm.topi.nn.pad import pad\n\nfrom .micro_kernel.multi_channel_convolve import (\n    intrin_multi_channel_convolve,\n    multi_channel_convolve_impl,\n)\nfrom .micro_kernel.common import num_simd_lanes_per_word\n\n\ndef depthwise_conv2d_nhwc_dsp_compute(_cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute function for v7e-m DSP instructions of DepthwiseConv2D. Has a lot of requirements\n    for use - if not all apply, the fallback implementation will be used instead.\"\"\"\n    assert isinstance(strides, int) or len(strides) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(strides, int):\n        stride_h = stride_w = strides\n    else:\n        stride_h, stride_w = strides\n\n    # We do not support dilation currently. It would be possible, but it would require\n    # modifying the way the kernel is packed. Gnarly.\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    assert dilation_h == dilation_w == 1\n\n    batch_size, height, width, channels = data.shape\n    kernel_h, kernel_w, _, _ = kernel.shape\n    simd_lanes = num_simd_lanes_per_word(data.dtype)\n\n    # We don't support different numbers of input and output channels.\n    assert channels == kernel.shape[2]\n    assert kernel.shape[3] == 1\n\n    # We take in int8 as our dtype, but we spit out int32. This is because we cannot\n    # round until we compute activations.\n    assert out_dtype == \"int32\"\n\n    # Padding the data requires COPYING THE ENTIRE INPUT TENSOR, which\n    # is slow and bad. We should really implement a strip mining\n    # routine to avoid this, but TVM has terrible support for that.\n\n    if padding == \"SAME\":\n        # This assumption makes the logic easier. Could be removed with work.\n        assert height % stride_h == width % stride_w == 0\n\n        output_h = height // stride_h\n        output_w = width // stride_w\n\n        # This padding behavior is consistent with other TVM depthwise_conv2d schedules. However it\n        # differs from the TensorFlow, which only pads the bottom right if stride > 1. This probably\n        # brings down accuracy slightly for models imported from TFLite.\n        pad_down = 1 if stride_h == 1 else 0\n        pad_right = 1 if stride_w == 1 else 0\n\n        padded_data = pad(\n            data,\n            [0, kernel_h // 2, kernel_w // 2, 0],\n            [0, pad_down, pad_right, 0],\n            name=\"padded_data\",\n        )\n\n    elif padding == \"VALID\":\n        assert height > kernel_h and width > kernel_w\n        output_h = (height - kernel_h) // stride_h + 1\n        output_w = (width - kernel_w) // stride_w + 1\n        padded_data = data\n\n    elif isinstance(padding, tuple):\n        if len(padding) == 2:\n            pad_up, pad_down = padding[0]\n            pad_left, pad_right = padding[1]\n        else:\n            pad_up, pad_left, pad_down, pad_right = padding\n\n        output_h = (height - kernel_h + pad_up + pad_down) // stride_h + 1\n        output_w = (width - kernel_w + pad_left + pad_right) // stride_w + 1\n        padded_data = pad(\n            data,\n            [0, pad_up, pad_left, 0],\n            [0, pad_down, pad_right, 0],\n            name=\"padded_data\",\n        )\n\n    else:\n        raise RuntimeError()\n    _, padded_h, padded_w, _ = padded_data.shape\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n    reshaped_kernel = topi.reshape(kernel, (channels // simd_lanes, kernel_h, kernel_w, simd_lanes))\n    return te.compute(\n        (batch_size, output_h, output_w, channels),\n        lambda h, i, j, k: te.sum(\n            padded_data[h, (i * stride_h) + kh_i, (j * stride_w) + kw_i, k].astype(\"int32\")\n            * reshaped_kernel[k // simd_lanes, kh_i, kw_i, k % simd_lanes].astype(\"int32\"),\n            axis=(kh_i, kw_i),\n        ),\n        name=\"depthwise_conv2d\",\n        tag=f\"depthwise_conv2d_nhwc_{padded_h}_{padded_w}_dsp\",\n    )\n\n\ndef depthwise_conv2d_nhwc_dsp_schedule(_cfg, outs):\n\n    \"\"\"Schedule function for v7e-m DSP instructions of conv2d.\"\"\"\n    schedule = te.create_schedule([x.op for x in outs])\n\n    def _callback(operator):\n        if \"depthwise_conv2d_nhwc\" not in operator.tag:\n            return\n\n        # extract tensors\n        output = operator.output(0)\n        padded_data = output.op.input_tensors[0]\n        reshaped_kernel = output.op.input_tensors[1]\n        in_dtype = padded_data.dtype\n\n        _, padded_h, padded_w, channels = padded_data.shape\n        _, kernel_h, kernel_w, _ = reshaped_kernel.shape\n        suffix = \"\".join(random.choices(string.ascii_uppercase, k=8))\n\n        b_ax, y_ax, x_ax, c_ax = schedule[output].op.axis\n        ky_ax, kx_ax = schedule[output].op.reduce_axis\n        simd_lanes = num_simd_lanes_per_word(in_dtype)\n        c_ax_o, c_ax_i = schedule[output].split(c_ax, factor=simd_lanes)\n        schedule[output].reorder(b_ax, c_ax_o, y_ax, x_ax, ky_ax, kx_ax, c_ax_i)\n\n        multi_channel_convolve = intrin_multi_channel_convolve(\n            in_dtype, padded_h, padded_w, channels, kernel_h, kernel_w, suffix\n        )\n        schedule[output].tensorize(ky_ax, multi_channel_convolve)\n        schedule[output].pragma(\n            b_ax,\n            \"import_c\",\n            multi_channel_convolve_impl(\n                in_dtype, padded_h, padded_w, channels, kernel_h, kernel_w, suffix\n            ),\n        )\n\n    traverse_inline(schedule, outs[-1].op, _callback)\n    return schedule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/avg_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Defines sum intrinsics for sum operation with v7e-m DSP instructions.\"\"\"\n\nimport random\nimport string\n\nimport tvm\nfrom tvm import te\nfrom . import common\n\n\ndef intrin_sum(shape, in_dtype, out_dtype, reset=False):\n    \"\"\"Defines a v7e-m DSP-accelerated sum operation.\"\"\"\n    UNIQ_ID_LEN = 8\n    uniq_id = \"\".join(random.choices(string.ascii_uppercase, k=UNIQ_ID_LEN))\n    func_prefix = \"sum16\"\n\n    assert in_dtype == \"int16\"\n    assert out_dtype == \"int16\"\n\n    width = shape[-1]\n    x = te.placeholder(shape, name=\"x\", dtype=in_dtype)\n    k = te.reduce_axis((0, width), name=\"rc\")\n\n    def get_slice(indices, k):\n        s = list(indices)\n        s[-1] = s[-1] + k\n        return tuple(s)\n\n    z = te.compute(\n        (1,) * len(shape), lambda *i: te.sum(x[get_slice(i, k)], axis=[k]).astype(out_dtype)\n    )\n\n    def _intrin_func(ins, outs):\n        aa = ins[0]\n        cc = outs[0]\n\n        def _body():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    cc.dtype,\n                    f\"{func_prefix}_{width}_{uniq_id}\",\n                    aa.access_ptr(\"r\"),\n                    cc.access_ptr(\"w\"),\n                    aa.elem_offset,\n                    1 if reset else 0,\n                )\n            )\n            return ib.get()\n\n        def _reduce_reset():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(cc.dtype, f\"{func_prefix}_reset_{uniq_id}\", cc.access_ptr(\"w\"))\n            )\n            return ib.get()\n\n        def _reduce_update():\n            return _body()\n\n        return _body(), _reduce_reset(), _reduce_update()\n\n    binds = {\n        t: tvm.tir.decl_buffer(\n            t.shape,\n            t.dtype,\n            t.op.name,\n            strides=[te.var(f\"{t.op.name}_s_{i}\") for i in range(0, len(t.shape))],\n            offset_factor=1,\n        )\n        for t in [x, z]\n    }\n\n    intrin_decl = te.decl_tensor_intrin(z.op, _intrin_func, binds=binds)\n    return intrin_decl, uniq_id\n\n\ndef sum_impl(N, uniq_id):\n    \"\"\"Emit C code for sum impl.\"\"\"\n    cc_code = (\n        common.common_includes\n        + f\"\"\"\n\n#ifdef __cplusplus\nextern \"C\"\n#endif // __cplusplus\n__STATIC_FORCEINLINE int32_t sum16_reset_{uniq_id}(\n    int16_t *res) {{\n  *res = (int16_t)0;\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t sum16_{N}_{uniq_id}(\n    int16_t *arr,\n    int16_t *res16,\n    long arr_offset,\n    int reset) {{\n  int n;\n  int32_t *p32;\n  int32_t res = reset ? 0 : *res16;\n\n  if ( arr_offset % 4 != 0 ) {{\n    res += *arr;\n    p32 = (int32_t *)(&arr[1]);\n    n = {N} - 1;\n  }} else {{\n    p32 = (int32_t *)arr;\n    n = {N};\n  }}\n\n  for ( int i = 0; i < n / 2; ++ i ) {{\n    res = __SMLAD(*p32, 0x00010001, res);\n    ++ p32;\n  }}\n\n  if ( n % 2 != 0 )\n    res += *(int16_t *)p32;\n\n  *res16 = res;\n\n  return 0;\n}}\n\n\"\"\"\n    )\n    return cc_code\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Defines common C code for all microkernel operations.\"\"\"\n\n\ncommon_includes = \"\"\"\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <arm_nnsupportfunctions.h>\n\n#include <tvm/runtime/crt/error_codes.h>\n\n\"\"\"\n\nMICRO_WORD_LENGTH_BITS = 32\n\n\ndef num_simd_lanes_per_word(dtype: str) -> int:\n    \"\"\"Takes a dtype, and returns how many of that dtype fit into a single microcontroller word.\n\n    >>> num_simd_lanes_per_word(\"int8\")\n    4\n    >>> num_simd_lanes_per_word(\"int16\")\n    2\n    \"\"\"\n    assert dtype.startswith(\"int\")\n    dtype_width = int(dtype[3:])\n    return MICRO_WORD_LENGTH_BITS // dtype_width\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Defines gemm intrinsics for matrix multiplication with v7e-m DSP instructions.\"\"\"\n\nimport random\nimport string\n\nimport tvm\nfrom tvm import te\nfrom . import common\n\n\n##########################\n# MxKxN MatMul Intrinsic #\n##########################\n\n# NOTE this is transposed matmul (A * B^T)\ndef intrin_gemm_MxKxN(M, K, N, in_dtype, out_dtype, stride_w=1):\n    \"\"\"Defines a v7e-m DSP-accelerated transposed matmul.\"\"\"\n    # we generate a unique ID for every intrinsic definition, to prevent name\n    # collisions in the generated source (e.g., if there are multiple operators\n    # in the same module that use the same intrinsic)\n    #\n    # TODO(weberlo, areusch): to cut down on memory usage, we should cache each intrinsic\n    # instantiation and include it only once, eliminating the need for unique\n    # IDs\n    UNIQ_ID_LEN = 8\n    uniq_id = \"\".join(random.choices(string.ascii_uppercase, k=UNIQ_ID_LEN))\n\n    if isinstance(M, tvm.tir.IntImm):\n        M = M.value\n    if isinstance(K, tvm.tir.IntImm):\n        K = K.value\n    if isinstance(N, tvm.tir.IntImm):\n        N = N.value\n    # TODO(weberlo, areusch): support more dtypes?\n    assert in_dtype in (\"int8\", \"int16\")\n    assert out_dtype == \"int32\"\n    A = te.placeholder((M * stride_w - (stride_w - 1), K), name=\"a\", dtype=in_dtype)\n    B = te.placeholder((N, K), name=\"b\", dtype=in_dtype)\n    k = te.reduce_axis((0, K), name=\"k\")\n    C = te.compute(\n        (M, N),\n        lambda i, j: te.sum(\n            A[i * stride_w, k].astype(out_dtype) * B[j, k].astype(out_dtype), axis=k\n        ),\n        name=\"c\",\n    )\n    A_buf = tvm.tir.decl_buffer(\n        A.shape, A.dtype, name=\"A\", offset_factor=1, strides=[te.var(\"A_s\"), 1]\n    )\n    B_buf = tvm.tir.decl_buffer(\n        B.shape, B.dtype, name=\"B\", offset_factor=1, strides=[te.var(\"B_s\"), 1]\n    )\n    C_buf = tvm.tir.decl_buffer(\n        C.shape, C.dtype, name=\"C\", offset_factor=1, strides=[te.var(\"C_s\"), 1]\n    )\n\n    def intrin_func(ins, outs):\n        aa, bb = ins\n        cc = outs[0]\n        gemm_func_prefix = \"gemm\" if in_dtype == \"int8\" else \"gemm16\"\n\n        def _reduce_update():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    f\"{gemm_func_prefix}_{M}x{K}x{N}_update_{uniq_id}\",\n                    aa.access_ptr(\"r\"),\n                    bb.access_ptr(\"r\"),\n                    cc.access_ptr(\"w\"),\n                    aa.strides[0] * stride_w,\n                    bb.strides[0],\n                    cc.strides[0],\n                )\n            )\n            return ib.get()\n\n        def _reduce_reset():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\", f\"gemm_{M}x{K}x{N}_reset_{uniq_id}\", cc.access_ptr(\"w\"), cc.strides[0]\n                )\n            )\n            return ib.get()\n\n        def _body():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    f\"{gemm_func_prefix}_{M}x{K}x{N}_body_{uniq_id}\",\n                    aa.access_ptr(\"r\"),\n                    bb.access_ptr(\"r\"),\n                    cc.access_ptr(\"w\"),\n                    aa.strides[0] * stride_w,\n                    bb.strides[0],\n                    cc.strides[0],\n                )\n            )\n            return ib.get()\n\n        return _body(), _reduce_reset(), _reduce_update()\n\n    intrin_decl = te.decl_tensor_intrin(C.op, intrin_func, binds={A: A_buf, B: B_buf, C: C_buf})\n    return intrin_decl, uniq_id\n\n\ndef gemm_MxKxN_impl(M, K, N, uniq_id):\n    \"\"\"Emit C code for gemm impl.\"\"\"\n    # TODO(weberlo, areusch): are there any SIMD tricks to zero out arrays quickly?\n    # aa_pad_size = M * K\n    bb_pad_size = N * K\n    # code reference: CMSIS-NN paper (https://arxiv.org/abs/1801.06601)\n    cc_code = (\n        common.common_includes\n        + f\"\"\"\n\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{N}_body_rest_{uniq_id}(\n    int K,\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int k_base = (K / 4) * 4;\n  switch ( K % 4 ) {{\n  case 1:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] = (int32_t) a_ptr[0] * (int32_t) b_ptr[0];\n      }}\n    }}\n    break;\n  case 2:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] =   (int32_t) a_ptr[0] * (int32_t) b_ptr[0]\n                               + (int32_t) a_ptr[1] * (int32_t) b_ptr[1];\n      }}\n    }}\n    break;\n  case 3:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] =   (int32_t) a_ptr[0] * (int32_t) b_ptr[0]\n                               + (int32_t) a_ptr[1] * (int32_t) b_ptr[1]\n                               + (int32_t) a_ptr[2] * (int32_t) b_ptr[2];\n      }}\n    }}\n    break;\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{K}x{N}_body_loop_{uniq_id}(\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t sum = 0;\n      for (int l = 0; l < {K}; l++) {{\n        sum += (int32_t) aa[i*A_stride + l] * (int32_t) bb[j*B_stride + l];\n      }}\n      // NOTE: this is the line where `*_body` differs from `*_update`. here\n      // we're *setting* the result, instead of accumulating, because we know\n      // the `i` and `j` itervars span their entire respective axes.\n      cc[i*C_stride + j] = sum;\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{K}x{N}_body_{uniq_id}(\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int16_t bb_pad[{bb_pad_size}];\n  int32_t retcode = 0;\n\n  if ( {M} < 2 && {N} < 2 ) {{\n    retcode = gemm_{M}x{K}x{N}_body_loop_{uniq_id}(aa, bb, cc, A_stride, B_stride, C_stride);\n    goto out;\n  }}\n\n  for (int i = 0; i < {N}; i++)\n    for (int j = 0; j < {K} / 4; j++)\n      read_and_pad(&bb[i*B_stride + j*4], (int32_t*) &bb_pad[i*{K} + j*4], (int32_t*) &bb_pad[i*{K} + j*4 + 2]);\n\n  for (int i = 0; i < {M}; i++) {{\n    int16_t aa_pad_line[{K}];\n    for (int l = 0; l < {K} / 4; l++)\n      read_and_pad(&aa[i*A_stride + l*4], (int32_t*) &aa_pad_line[l*4], (int32_t*) &aa_pad_line[l*4 + 2]);\n\n    for (int j = 0; j < {N}; j++) {{\n      int32_t *aa_ptr = (int32_t *) aa_pad_line;\n      int32_t *bb_ptr = (int32_t *) &bb_pad[j*{K}];\n      int32_t sum = 0;\n      for (int l = 0; l < 2 * ({K} / 4); l++) {{\n        sum = __SMLAD(*aa_ptr, *bb_ptr, sum);\n        ++ aa_ptr; ++ bb_ptr;\n      }}\n      // NOTE: this is the line where `*_body` differs from `*_update`. here\n      // we're *setting* the result, instead of accumulating, because we know\n      // the `i` and `j` itervars span their entire respective axes.\n      cc[i*C_stride + j] = sum;\n    }}\n  }}\n\n  if ( {K} % 4 != 0 )\n    gemm_{M}x{N}_body_rest_{uniq_id}({K}, aa, bb, cc, A_stride, B_stride, C_stride);\n\nout:\n  return retcode;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{N}_update_rest_{uniq_id}(\n    int K,\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int k_base = (K / 4) * 4;\n  switch ( K % 4 ) {{\n  case 1:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] += (int32_t) a_ptr[0] * (int32_t) b_ptr[0];\n      }}\n    }}\n    break;\n  case 2:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] +=   (int32_t) a_ptr[0] * (int32_t) b_ptr[0]\n                                + (int32_t) a_ptr[1] * (int32_t) b_ptr[1];\n      }}\n    }}\n    break;\n  case 3:\n    for (int i = 0; i < {M}; i++) {{\n      for (int j = 0; j < {N}; j++) {{\n        int8_t *a_ptr = &aa[i * A_stride + k_base];\n        int8_t *b_ptr = &bb[j * B_stride + k_base];\n        cc[i * C_stride + j] +=   (int32_t) a_ptr[0] * (int32_t) b_ptr[0]\n                                + (int32_t) a_ptr[1] * (int32_t) b_ptr[1]\n                                + (int32_t) a_ptr[2] * (int32_t) b_ptr[2];\n      }}\n    }}\n    break;\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{K}x{N}_update_loop_{uniq_id}(\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t sum = 0;\n      for (int l = 0; l < {K}; l++) {{\n        sum += (int32_t) aa[i*A_stride + l] * (int32_t) bb[j*B_stride + l];\n      }}\n      cc[i*C_stride + j] += sum;\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{K}x{N}_update_{uniq_id}(\n    int8_t *aa, int8_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int16_t bb_pad[{bb_pad_size}];\n  int32_t retcode = 0;\n\n  if ( {M} < 2 && {N} < 2 ) {{\n    retcode = gemm_{M}x{K}x{N}_update_loop_{uniq_id}(aa, bb, cc, A_stride, B_stride, C_stride);\n    goto out;\n  }}\n\n  for (int i = 0; i < {N}; i++)\n    for (int j = 0; j < {K} / 4; j++)\n      read_and_pad(&bb[i*B_stride + j*4], (int32_t*) &bb_pad[i*{K} + j*4], (int32_t*) &bb_pad[i*{K} + j*4 + 2]);\n\n  for (int i = 0; i < {M}; i++) {{\n    int16_t aa_pad_line[{K}];\n    for (int l = 0; l < {K} / 4; l++)\n      read_and_pad(&aa[i*A_stride + l*4], (int32_t*) &aa_pad_line[l*4], (int32_t*) &aa_pad_line[l*4 + 2]);\n\n    for (int j = 0; j < {N}; j++) {{\n      int32_t *aa_ptr = (int32_t *) aa_pad_line;\n      int32_t *bb_ptr = (int32_t *) &bb_pad[j*{K}];\n      int32_t sum = 0;\n      for (int l = 0; l < 2 * ({K} / 4); l++) {{\n        sum = __SMLAD(*aa_ptr, *bb_ptr, sum);\n        ++ aa_ptr; ++ bb_ptr;\n      }}\n      cc[i*C_stride + j] += sum;\n    }}\n  }}\n\n  if ( {K} % 4 != 0 )\n    gemm_{M}x{N}_update_rest_{uniq_id}({K}, aa, bb, cc, A_stride, B_stride, C_stride);\n\nout:\n  return retcode;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{N}_body_rest_{uniq_id}(\n    int K,\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int k_base = (K / 2) * 2;\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int16_t *a_ptr = &aa[i * A_stride + k_base];\n      int16_t *b_ptr = &bb[j * B_stride + k_base];\n      cc[i * C_stride + j] = (int32_t) a_ptr[0] * (int32_t) b_ptr[0];\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{K}x{N}_body_loop_{uniq_id}(\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t sum = 0;\n      for (int l = 0; l < {K}; l++) {{\n        sum += (int32_t) aa[i*A_stride + l] * (int32_t) bb[j*B_stride + l];\n      }}\n      // NOTE: this is the line where `*_body` differs from `*_update`. here\n      // we're *setting* the result, instead of accumulating, because we know\n      // the `i` and `j` itervars span their entire respective axes.\n      cc[i*C_stride + j] = sum;\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{K}x{N}_body_{uniq_id}(\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int32_t retcode = 0;\n\n  if ( {M} < 2 && {N} < 2 ) {{\n    retcode = gemm16_{M}x{K}x{N}_body_loop_{uniq_id}(aa, bb, cc, A_stride, B_stride, C_stride);\n    goto out;\n  }}\n\n  if(((uint32_t)aa & 0x3) != 0 || ((uint32_t)bb & 0x3) != 0){{\n    retcode = kTvmErrorFunctionCallInvalidArg;\n    goto out;\n  }}\n\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t *aa_ptr = (int32_t *) &aa[i*A_stride];\n      int32_t *bb_ptr = (int32_t *) &bb[j*B_stride];\n\n      int32_t sum = 0;\n      for (int l = 0; l < {K} / 2; l++) {{\n        sum = __SMLAD(*aa_ptr, *bb_ptr, sum);\n        ++ aa_ptr; ++ bb_ptr;\n      }}\n      // NOTE: this is the line where `*_body` differs from `*_update`. here\n      // we're *setting* the result, instead of accumulating, because we know\n      // the `i` and `j` itervars span their entire respective axes.\n      cc[i*C_stride + j] = sum;\n    }}\n  }}\n\n  if ( {K} % 2 != 0 )\n    gemm16_{M}x{N}_body_rest_{uniq_id}({K}, aa, bb, cc, A_stride, B_stride, C_stride);\n\nout:\n  return retcode;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{N}_update_rest_{uniq_id}(\n    int K,\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int k_base = (K / 2) * 2;\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int16_t *a_ptr = &aa[i * A_stride + k_base];\n      int16_t *b_ptr = &bb[j * B_stride + k_base];\n      cc[i * C_stride + j] += (int32_t) a_ptr[0] * (int32_t) b_ptr[0];\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{K}x{N}_update_loop_{uniq_id}(\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t sum = 0;\n      for (int l = 0; l < {K}; l++) {{\n        sum += (int32_t) aa[i*A_stride + l] * (int32_t) bb[j*B_stride + l];\n      }}\n      cc[i*C_stride + j] += sum;\n    }}\n  }}\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm16_{M}x{K}x{N}_update_{uniq_id}(\n    int16_t *aa, int16_t *bb, int32_t *cc,\n    int A_stride, int B_stride, int C_stride) {{\n  int32_t retcode = 0;\n\n  if ( {M} < 2 && {N} < 2 ) {{\n    retcode = gemm16_{M}x{K}x{N}_update_loop_{uniq_id}(aa, bb, cc, A_stride, B_stride, C_stride);\n    goto out;\n  }}\n\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      int32_t *aa_ptr = (int32_t *) &aa[i*A_stride];\n      int32_t *bb_ptr = (int32_t *) &bb[j*B_stride];\n\n      int32_t sum = 0;\n      for (int l = 0; l < {K} / 2; l++) {{\n        sum = __SMLAD(*aa_ptr, *bb_ptr, sum);\n        ++ aa_ptr; ++ bb_ptr;\n      }}\n      cc[i*C_stride + j] += sum;\n    }}\n  }}\n\n  if ( {K} % 2 != 0 )\n    gemm16_{M}x{N}_update_rest_{uniq_id}({K}, aa, bb, cc, A_stride, B_stride, C_stride);\n\nout:\n  return retcode;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t gemm_{M}x{K}x{N}_reset_{uniq_id}(int32_t *cc, int C_stride) {{\n  for (int i = 0; i < {M}; i++) {{\n    for (int j = 0; j < {N}; j++) {{\n      cc[i*C_stride + j] = 0;\n    }}\n  }}\n  return 0;\n}}\n\n\"\"\"\n    )\n    return cc_code\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/max_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Defines max intrinsics for elemwise max operation with v7e-m DSP instructions.\"\"\"\n\nimport random\nimport string\n\nimport tvm\nfrom tvm import te\nfrom . import common\n\n\ndef intrin_max(shape, in_dtype, out_dtype):\n    \"\"\"Defines a v7e-m DSP-accelerated max pool.\"\"\"\n    UNIQ_ID_LEN = 8\n    uniq_id = \"\".join(random.choices(string.ascii_uppercase, k=UNIQ_ID_LEN))\n    func_prefix = \"max8\"\n\n    assert in_dtype == \"int8\"\n    assert out_dtype == \"int8\"\n\n    x = te.placeholder(shape, name=\"x\", dtype=in_dtype)\n    k = te.reduce_axis((0, 1), name=\"rc\")\n    z = te.compute(shape, lambda *i: tvm.tir.max(x[i], axis=[k]).astype(out_dtype))\n\n    def _intrin_func(ins, outs):\n        aa = ins[0]\n        cc = outs[0]\n\n        def _body():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    cc.dtype,\n                    f\"{func_prefix}_{uniq_id}\",\n                    aa.access_ptr(\"r\"),\n                    cc.access_ptr(\"w\"),\n                    cc.strides[0],\n                )\n            )\n            return ib.get()\n\n        def _reduce_reset():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    cc.dtype, f\"{func_prefix}_reset_{uniq_id}\", cc.access_ptr(\"w\"), cc.strides[0]\n                )\n            )\n            return ib.get()\n\n        def _reduce_update():\n            return _body()\n\n        return _body(), _reduce_reset(), _reduce_update()\n\n    binds = {\n        t: tvm.tir.decl_buffer(\n            t.shape,\n            t.dtype,\n            t.op.name,\n            strides=[te.var(f\"{t.op.name}_s_{i}\") for i in range(0, len(t.shape))],\n            offset_factor=1,\n        )\n        for t in [x, z]\n    }\n\n    intrin_decl = te.decl_tensor_intrin(z.op, _intrin_func, binds=binds)\n    return intrin_decl, uniq_id\n\n\ndef max_impl(uniq_id):\n    \"\"\"Emit C code for pool impl.\"\"\"\n    cc_code = (\n        common.common_includes\n        + f\"\"\"\n\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t max8_reset_{uniq_id}(\n    int8_t *res,\n    int N) {{\n  memset(res, (int8_t)-128, N * sizeof(*res));\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t max8_loop_{uniq_id}(\n    int8_t *arg,\n    int8_t *res,\n    int N) {{\n  for ( int i = 0; i < N; ++ i )\n    if ( arg[i] > res[i] )\n      res[i] = arg[i];\n  return 0;\n}}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\n__STATIC_FORCEINLINE int32_t max8_{uniq_id}(\n    int8_t *arg,\n    int8_t *res,\n    int N) {{\n  int32_t *parg32, *pres32;\n  int una_arg = (int32_t)arg & 0x3, una_res = (int32_t)res & 0x3;\n  int32_t retcode = 0;\n\n  if ( N < 4 || ((una_arg || una_res) && una_arg != una_res) ) {{\n    retcode = max8_loop_{uniq_id}(arg, res, N);\n    goto out;\n  }}\n  if ( una_arg ) {{\n    int n = (4 - una_arg);\n    if ( n > N || (N - n) < 4 )\n      n = N;\n    retcode = max8_loop_{uniq_id}(arg, res, n);\n    N -= n;\n    if ( N == 0 )\n      goto out;\n    arg += n; res += n;\n  }}\n\n  parg32 = (int32_t *)arg;\n  pres32 = (int32_t *)res;\n\n  for ( int i = 0; i < N / 4; ++ i ) {{\n    int32_t arg32 = *parg32 ++;\n    int32_t res32 = *pres32;\n    __SSUB8(arg32, res32);\n    res32 = __SEL(arg32, res32);\n    *pres32 ++ = res32;\n  }}\n\n  if ( N & 0x3 ) {{\n    retcode = max8_loop_{uniq_id}((int8_t *)parg32, (int8_t *)pres32, N & 0x3);\n    goto out;\n  }}\n\nout:\n  return retcode;\n}}\n\n\"\"\"\n    )\n    return cc_code\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/multi_channel_convolve.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"This is a special intrinsic used for depthwise convolution using Cortex-M DSP instructions\n(v7e-m). It takes as inputs an int8 HWC data tensor and an int8 CHWc kernel. This intrinsic \"lays\"\nthe kernel on top of the data tensors starting from a given pointer, performs signed sixteen-bit\nmultiplies on each pair of values, and sums all the products in an int32 accumlator. This process is\nrepeated four times giving four int32 outputs - one per channel.\"\"\"\n\nimport textwrap\n\nfrom tvm import te, tir\nfrom .common import num_simd_lanes_per_word\n\n\ndef _get_func_name(in_dtype, tensor_w, channels, kernel_h, kernel_w, suffix):\n    \"\"\"Gets the C function name of the tensorized function.\"\"\"\n    return f\"kernel_convolve_{in_dtype}_w{tensor_w}_c{channels}_kh{kernel_h}_kw{kernel_w}_{suffix}\"\n\n\ndef intrin_multi_channel_convolve(\n    in_dtype, _tensor_h, tensor_w, channels, kernel_h, kernel_w, suffix\n):\n    \"\"\"Defines a v7e-m DSP-accelerated multi-channel convolution. Works on two\n    channels if in_dtype==int16, and four channels if in_dtype==int8.\"\"\"\n    simd_lanes = num_simd_lanes_per_word(in_dtype)\n\n    overlap_dims = (kernel_h, kernel_w, simd_lanes)\n    data_slice = te.placeholder(overlap_dims, name=\"data_slice\", dtype=in_dtype)\n    kernel_slice = te.placeholder(overlap_dims, name=\"kernel_slice\", dtype=in_dtype)\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n\n    output_slice = te.compute(\n        (simd_lanes,),\n        lambda k: te.sum(\n            data_slice[kh_i, kw_i, k].astype(\"int32\") * kernel_slice[kh_i, kw_i, k].astype(\"int32\"),\n            axis=(kh_i, kw_i),\n        ),\n        name=\"c\",\n    )\n\n    data_buf = tir.decl_buffer(\n        data_slice.shape,\n        data_slice.dtype,\n        name=\"data\",\n        offset_factor=1,\n        strides=[tensor_w * channels, channels, 1],\n    )\n    kernel_buf = tir.decl_buffer(\n        kernel_slice.shape,\n        kernel_slice.dtype,\n        name=\"kernel\",\n        offset_factor=1,\n        strides=[kernel_w * simd_lanes, simd_lanes, 1],\n    )\n    output_buf = tir.decl_buffer(\n        output_slice.shape, output_slice.dtype, name=\"output\", offset_factor=1, strides=[1]\n    )\n\n    def intrin_func(ins, outs):\n        builder = tir.ir_builder.create()\n        builder.emit(\n            tir.call_extern(\n                \"int32\",\n                _get_func_name(in_dtype, tensor_w, channels, kernel_h, kernel_w, suffix),\n                outs[0].access_ptr(\"w\"),\n                ins[0].access_ptr(\"r\"),\n                ins[1].access_ptr(\"r\"),\n            )\n        )\n        return builder.get()\n\n    return te.decl_tensor_intrin(\n        output_slice.op,\n        intrin_func,\n        binds={data_slice: data_buf, kernel_slice: kernel_buf, output_slice: output_buf},\n    )\n\n\ndef multi_channel_convolve_impl(in_dtype, *args) -> str:\n    \"\"\"Generates C code for a fast multi-channel convolution function for ARM Cortex-M. This is done\n    by calling a sub-function depending on the input data type, as since v7e-m has no quad multiply\n    accumulate instruction, the int8 and int16 cases work differently.\"\"\"\n    if in_dtype == \"int8\":\n        return _quad_int8_channel_convolve_impl(*args)\n    if in_dtype == \"int16\":\n        return _dual_int16_channel_convolve_impl(*args)\n\n    raise NotImplementedError(f\"No Cortex-M {in_dtype} depthwise_conv2d implementation exists!\")\n\n\ndef _quad_int8_channel_convolve_impl(_tensor_h, tensor_w, channels, kernel_h, kernel_w, suffix):\n    return textwrap.dedent(\n        (\n            f\"\"\"\n        #include <stdint.h>\n        #include <arm_nnsupportfunctions.h>\n\n        // __SXTB16(_ROR(X, Y)) is combined into one assembly instruction\n\n        #define TVMGEN_QUAD_INT8_CHANNEL_REARRANGE_SUM_DSP( \\\n            arranged_kernel, \\\n            tensor_c3210, \\\n            sum_c0, sum_c1, sum_c2, sum_c3) {{ \\\n          \\\n          uint32_t kernel_c3210 = *arranged_kernel++; \\\n          \\\n          uint32_t tensor_c20 = __SXTB16(tensor_c3210); \\\n          uint32_t kernel_c20 = __SXTB16(kernel_c3210); \\\n          sum_c0 = __builtin_arm_smlabb(tensor_c20, kernel_c20, sum_c0); \\\n          sum_c2 = __builtin_arm_smlatt(tensor_c20, kernel_c20, sum_c2); \\\n          \\\n          uint32_t tensor_c31 = __SXTB16(__ROR(tensor_c3210, 8)); \\\n          uint32_t kernel_c31 = __SXTB16(__ROR(kernel_c3210, 8)); \\\n          sum_c1 = __builtin_arm_smlabb(tensor_c31, kernel_c31, sum_c1); \\\n          sum_c3 = __builtin_arm_smlatt(tensor_c31, kernel_c31, sum_c3); \\\n        }}\n\n        /* We do four channels at once to get this speed boost. */\n        #ifdef __cplusplus\n        extern \"C\"\n        #endif\n        int32_t {_get_func_name(\"int8\", tensor_w, channels, kernel_h, kernel_w, suffix)}(\n            uint32_t *out,\n            uint32_t *tensor,\n            uint32_t *kernel) {{\n\n          uint32_t sum_c0 = 0;\n          uint32_t sum_c1 = 0;\n          uint32_t sum_c2 = 0;\n          uint32_t sum_c3 = 0;\n\n          #pragma GCC unroll 3\n          for (int i = 0; i < {kernel_h}; i++) {{\n            #pragma GCC unroll 3\n            for (int j = 0; j < {kernel_w}; j++) {{\n              TVMGEN_QUAD_INT8_CHANNEL_REARRANGE_SUM_DSP(\n                kernel,\n                *(tensor + j * {channels // 4} + i * {tensor_w * (channels // 4)}),\n                sum_c0, sum_c1, sum_c2, sum_c3)\n            }}\n          }}\n\n          out[0] = sum_c0;\n          out[1] = sum_c1;\n          out[2] = sum_c2;\n          out[3] = sum_c3;\n          return 0;\n        }}\n\n        #undef TVMGEN_QUAD_INT8_CHANNEL_REARRANGE_SUM_DSP\n        \"\"\"\n        )\n    )\n\n\ndef _dual_int16_channel_convolve_impl(_tensor_h, tensor_w, channels, kernel_h, kernel_w, suffix):\n    return textwrap.dedent(\n        (\n            f\"\"\"\n        #include <stdint.h>\n\n        /* We do four channels at once to get this speed boost. */\n        #ifdef __cplusplus\n        extern \"C\"\n        #endif\n        int32_t {_get_func_name(\"int16\", tensor_w, channels, kernel_h, kernel_w, suffix)}(\n            uint32_t *out,\n            uint32_t *tensor,\n            uint32_t *kernel) {{\n\n          uint32_t sum_c0 = 0;\n          uint32_t sum_c1 = 0;\n\n          #pragma GCC unroll 3\n          for (int i = 0; i < {kernel_h}; i++) {{\n            #pragma GCC unroll 3\n            for (int j = 0; j < {kernel_w}; j++) {{\n              uint32_t tensor_c10 = *(tensor + j * {channels // 2}\n                + i * {tensor_w * (channels // 2)});\n              uint32_t kernel_c10 = *kernel++;\n              sum_c0 = __builtin_arm_smlabb(tensor_c10, kernel_c10, sum_c0);\n              sum_c1 = __builtin_arm_smlatt(tensor_c10, kernel_c10, sum_c1);\n            }}\n          }}\n\n          out[0] = sum_c0;\n          out[1] = sum_c1;\n          return 0;\n        }}\n\n        #undef TVMGEN_DUAL_INT16_CHANNEL_REARRANGE_SUM\n        \"\"\"\n        )\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/micro_kernel/tensordot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Computes a \"jumpy tensordot\" operator, which can be used to tensorize many common operators\nincluding regular conv2d, depthwise conv2d, and grouped conv2d provided the data and kernel layouts\nare the optimal ones. When groups=1, the optimal data layout is NHWC and kernel layout is OHWI. When\nthis is a depthwise convolution, the optimal data layout is NCHW and kernel layout is OIHW.\"\"\"\n\nimport textwrap\n\nfrom tvm import te, tir\n\nfrom .common import num_simd_lanes_per_word\n\n\ndef _get_func_name(in_dtype, tensor_h, jump, tensor_w, suffix):\n    \"\"\"Gets the C function name of the tensordot function.\"\"\"\n    return f\"tensordot_{in_dtype}_h{tensor_h}_j{jump}_w{tensor_w}_{suffix}\"\n\n\ndef make_intrin_tensordot(slices, strides, tensordot_params):\n    \"\"\"Helper function for constructing tensordot intrinsic. We can't construct the whole thing here\n    (as multiple schedules use tensordot and each must build the intrinstic differently) but we can\n    build part here to simplify the code.\"\"\"\n\n    # in_dtype, tensor_h, jump, tensor_w, suffix = tensordot_params\n    data, kernel, output = slices\n    data_strides, kernel_strides = strides\n\n    data_buf = tir.decl_buffer(\n        data.shape, data.dtype, name=\"data\", offset_factor=1, strides=data_strides\n    )\n    kernel_buf = tir.decl_buffer(\n        kernel.shape,\n        kernel.dtype,\n        name=\"kernel\",\n        offset_factor=1,\n        strides=kernel_strides,\n    )\n    output_buf = tir.decl_buffer(\n        output.shape, output.dtype, name=\"output\", offset_factor=1, strides=[1]\n    )\n\n    def intrin_func(ins, outs):\n        builder = tir.ir_builder.create()\n        builder.emit(\n            tir.call_extern(\n                \"int32\",\n                _get_func_name(*tensordot_params),\n                outs[0].access_ptr(\"w\"),\n                ins[0].access_ptr(\"r\"),\n                ins[1].access_ptr(\"r\"),\n            )\n        )\n        return builder.get()\n\n    return te.decl_tensor_intrin(\n        output.op,\n        intrin_func,\n        binds={data: data_buf, kernel: kernel_buf, output: output_buf},\n    )\n\n\ndef tensordot_impl(in_dtype: str, tensor_h: int, jump: int, tensor_w: int, suffix: str) -> str:\n    \"\"\"Generates C code for taking the dot products of two `tensor_h` * `tensor_w` tensors. Also has\n    a `jump` argument that advances the pointer of one tensor by that many words after each row. The\n    `jump` and `tensor_w` values must be word-aligned for the input data type, as non-word-aligned\n    memory access is slow on the Cortex-M series. Depending on the input datatype, the code may\n    contain DSP instructions for Arm v7e-m. C code contains DSP instructions for Arm v7e-m. See\n    the below pseudocode for reference:\n\n    tensordot(out_ptr, dat_ptr, ker_ptr) {\n        sum = 0;\n        for (i = 0; i < tensor_h; i++) {\n            for (j = 0; j < tensor_w; j++) {\n                sum += (*dat_ptr++) * (*ker_ptr++);\n            }\n            dat_ptr += jump;\n        }\n        *out_ptr = sum;\n    }\n    \"\"\"\n\n    simd_lanes = num_simd_lanes_per_word(in_dtype)\n    assert tensor_w % simd_lanes == 0\n    assert jump % simd_lanes == 0\n\n    if in_dtype == \"int8\":\n        inner_loop = \"\"\"\n              uint32_t tensor_c20 = __SXTB16(tensor_batch);\n              uint32_t kernel_c20 = __SXTB16(kernel_batch);\n              sum = __SMLAD(tensor_c20, kernel_c20, sum);\n\n              uint32_t tensor_c31 = __SXTB16(__ROR(tensor_batch, 8));\n              uint32_t kernel_c31 = __SXTB16(__ROR(kernel_batch, 8));\n              sum = __SMLAD(tensor_c31, kernel_c31, sum);\"\"\"\n\n    elif in_dtype == \"int16\":\n        inner_loop = \"\"\"\n              sum = __SMLAD(tensor_batch, kernel_batch, sum);\"\"\"\n\n    elif in_dtype == \"int32\":\n        inner_loop = \"\"\"\n              // Compiles to a single MAC instruction\n              sum += tensor_batch * kernel_batch;\"\"\"\n\n    else:\n        raise ValueError(f\"No tensordot implementation exists for dtype '{in_dtype}'!\")\n\n    function_name = _get_func_name(in_dtype, tensor_h, jump, tensor_w, suffix)\n    return textwrap.dedent(\n        (\n            f\"\"\"\n        #include <stdint.h>\n        #include <arm_nnsupportfunctions.h>\n\n        #ifdef __cplusplus\n        extern \"C\"\n        #endif\n        __STATIC_FORCEINLINE int32_t {function_name}(\n            uint32_t *out,\n            uint32_t *tensor,\n            uint32_t *kernel) {{\n\n          uint32_t sum = 0;\n\n          #pragma GCC unroll {tensor_h}\n          for (int i = 0; i < {tensor_h}; i++) {{\n            #pragma GCC unroll {tensor_w // simd_lanes}\n            for (int j = 0; j < {tensor_w // simd_lanes}; j++) {{\n              uint32_t tensor_batch = *tensor++;\n              uint32_t kernel_batch = *kernel++;\n              {inner_loop.strip()}\n            }}\n            tensor += {jump // simd_lanes};\n          }}\n          out[0] = sum;\n          return 0;\n        }}\n        \"\"\"\n        )\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-value-for-parameter\n\"\"\"Direct implementation of pool.\"\"\"\nimport logging\n\nimport tvm\n\nfrom tvm import te\nfrom tvm.topi.utils import traverse_inline\n\nfrom .micro_kernel.max_pool import (\n    intrin_max,\n    max_impl,\n)\n\nfrom .micro_kernel.avg_pool import (\n    intrin_sum,\n    sum_impl,\n)\n\nlogger = logging.getLogger(\"topi\")\n\n\ndef schedule_maxpool_1d_nwc(s, op):\n    \"\"\"Schedule function for v7e-m DSP instructions of maxpool 1d NWC layout.\"\"\"\n    output = op.output(0)\n    data_vec = op.input_tensors[0]\n\n    channels = data_vec.shape[-1]\n    if isinstance(channels, tvm.tir.IntImm):\n        channels = channels.value\n\n    n, w, c = s[op].op.axis\n    (k,) = s[op].op.reduce_axis\n\n    s[op].reorder(n, w, k, c)\n    max_val, uniq_id = intrin_max((1, 1, channels), data_vec.dtype, output.dtype)\n    s[op].tensorize(c, max_val)\n    s[output].pragma(n, \"import_c\", max_impl(uniq_id))\n\n\ndef schedule_maxpool_2d_nhwc(s, op):\n    \"\"\"Schedule function for v7e-m DSP instructions of maxpool 2d NHWC layout.\"\"\"\n    output = op.output(0)\n    data_vec = op.input_tensors[0]\n\n    channels = data_vec.shape[-1]\n    if isinstance(channels, tvm.tir.IntImm):\n        channels = channels.value\n\n    n, h, w, c = s[op].op.axis\n    ko, ki = s[op].op.reduce_axis\n\n    s[op].reorder(n, h, w, ko, ki, c)\n    max_val, uniq_id = intrin_max((1, 1, 1, channels), data_vec.dtype, output.dtype)\n    s[op].tensorize(c, max_val)\n    s[output].pragma(n, \"import_c\", max_impl(uniq_id))\n\n\ndef schedule_avgpool_1d_ncw(s, op):\n    \"\"\"Schedule function for v7e-m DSP instructions of avgpool 1d NCW layout.\"\"\"\n    output = op.output(0)\n    data_vec = op.input_tensors[0]\n\n    n, _, _ = s[op].op.axis\n    (k,) = s[op].op.reduce_axis\n    pool_w = k.dom.extent.value\n\n    summary, uniq_id = intrin_sum((1, 1, pool_w), data_vec.dtype, output.dtype, reset=True)\n    s[op].tensorize(k, summary)\n    s[output].pragma(n, \"import_c\", sum_impl(pool_w, uniq_id))\n\n\ndef schedule_avgpool_2d_nchw(s, op):\n    \"\"\"Schedule function for v7e-m DSP instructions of avgpool 2d NCHW layout.\"\"\"\n    output = op.output(0)\n    data_vec = op.input_tensors[0]\n\n    n, _, _, _ = s[op].op.axis\n    _, ki = s[op].op.reduce_axis\n    pool_w = ki.dom.extent.value\n\n    summary, uniq_id = intrin_sum((1, 1, 1, pool_w), data_vec.dtype, output.dtype)\n    s[op].tensorize(ki, summary)\n    s[output].pragma(n, \"import_c\", sum_impl(pool_w, uniq_id))\n\n\ndef pool_dsp_schedule(outs, layout):\n    \"\"\"Schedule function for v7e-m DSP instructions of pooling.\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"pool_max\" in op.tag:\n            in_dtype = op.input_tensors[0].dtype\n            if in_dtype != \"int8\":\n                logger.warning(\"Does not have micro-kernel for %s maxpool.\", in_dtype)\n            elif layout == \"NWC\":\n                schedule_maxpool_1d_nwc(s, op)\n            elif layout == \"NHWC\":\n                schedule_maxpool_2d_nhwc(s, op)\n        elif \"pool_sum\" in op.tag:\n            in_dtype = op.input_tensors[0].dtype\n            if in_dtype != \"int16\":\n                logger.warning(\"Does not have micro-kernel for %s avgpool.\", in_dtype)\n            elif layout == \"NCW\":\n                schedule_avgpool_1d_ncw(s, op)\n            elif layout == \"NCHW\":\n                schedule_avgpool_2d_nchw(s, op)\n\n    traverse_inline(s, outs[-1].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/mprofile/dsp/tensordot_conv2ds.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Implementations of several conv2d variations, all tensorized using tensordot and optimized for\nCortex-M DSP. Currently contains a standard conv2d and depthwise conv2d implementation, but could be\nextended to add a grouped conv2d operator. Due to the way we tensorize, this schedule ONLY works\nwhen the data and kernel layouts are NCHWxc and OIHWxi respectively, where x is the number of\ninput channels divided by the number of groups.\"\"\"\n\nimport random\nimport string\nfrom typing import Callable, Tuple, Union\n\nimport tvm\nfrom tvm import te\nfrom tvm.tir import indexdiv, indexmod\nfrom tvm.topi.utils import traverse_inline\nfrom tvm.topi.nn.pad import pad\n\nfrom .micro_kernel.tensordot import (\n    make_intrin_tensordot,\n    tensordot_impl,\n)\n\n\ndef _unpack_2d_argument(argument: Union[int, Tuple]) -> Tuple:\n    if isinstance(argument, int):\n        return (argument, argument)\n    assert len(argument) == 2\n    return argument\n\n\ndef _check_no_dilation(dilation: Union[int, Tuple]) -> None:\n    \"\"\"Takes a dilation argument as an integer or tuple, and makes sure both dimensions are 1.\n    Dilation prevents us from using DSP instructions, so this schedule can't work (aside from the\n    niche case where dilation_h == stride_h and dilation_w == stride_w, which is rare enough we\n    probably don't need to support it).\"\"\"\n\n    dilation_h, dilation_w = _unpack_2d_argument(dilation)\n    assert dilation_h == dilation_w == 1\n\n\ndef _unpack_padding(padding: Tuple) -> Tuple:\n    assert isinstance(padding, tuple)\n    if len(padding) == 2:\n        (pad_up, pad_down), (pad_left, pad_right) = padding\n    else:\n        pad_up, pad_left, pad_down, pad_right = padding\n    return pad_up, pad_left, pad_down, pad_right\n\n\ndef _pad_if_needed(data: te.tensor.Tensor, layout: str, padding: Tuple) -> te.tensor.Tensor:\n    \"\"\"Performs padding on a te.tensor.Tensor object if necessary. If padding = (0, 0, 0, 0), the\n    input tensor is returned unmodified. We only care about tuples here - \"VALID\" and \"SAME\" padding\n    will be converted by the importer TFLite importer if present.\"\"\"\n\n    pad_up, pad_left, pad_down, pad_right = padding\n    if not any(padding):\n        return data\n\n    # We want to pad the \"H\" and \"W\" columns, and their position depends on the layout\n    pad_before, pad_after = [0, 0, 0, 0], [0, 0, 0, 0]\n    pad_before[layout.index(\"H\")] = pad_up\n    pad_before[layout.index(\"W\")] = pad_left\n    pad_after[layout.index(\"H\")] = pad_down\n    pad_after[layout.index(\"W\")] = pad_right\n    return pad(data, pad_before, pad_after, name=\"padded_data\")\n\n\ndef _compute_output_dim(\n    data_dim: int, kernel_dim: int, pad_before: int, pad_after: int, stride: int\n) -> int:\n    \"\"\"Computes an output dimension of a convolution, given the data dimension, kernel dimension,\n    padding, and stride along that axis. Note that when stride > 1, this division will often not\n    be perfectly even.\"\"\"\n    return (data_dim + pad_before + pad_after - kernel_dim) // stride + 1\n\n\ndef _wrap_te_compute(\n    shape: Tuple,\n    fcompute: Callable[[int, int, int, int], tvm.ir.PrimExpr],\n    desired_out_layout: str,\n    current_out_layout: str = \"NHWC\",\n    **kwargs,\n) -> te.tensor.Tensor:\n    \"\"\"Wrapper over te.compute that allows the output layout to be easily changed.\"\"\"\n    assert current_out_layout.isalpha() and desired_out_layout.isalpha()\n    assert sorted(current_out_layout) == sorted(desired_out_layout)\n    forward_order = (current_out_layout.index(c) for c in desired_out_layout)\n    reverse_order = (desired_out_layout.index(c) for c in current_out_layout)\n\n    return te.compute(\n        tuple(shape[i] for i in forward_order),\n        lambda *args: fcompute(*(args[i] for i in reverse_order)),\n        **kwargs,\n    )\n\n\ndef _get_suffix() -> str:\n    \"\"\"Returns a random eight-character string to append to C function names. Prevents accidental\n    re-definition of functions if the same operator appears twice in a Relay graph.\"\"\"\n    return \"\".join(random.choices(string.ascii_uppercase, k=8))\n\n\ndef conv2d_nhwc_ohwi_dsp_compute(\n    _cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype\n):\n    \"\"\"Standard conv2d schedule that can be tensorized using tensordot.\"\"\"\n\n    stride_h, stride_w = _unpack_2d_argument(strides)\n    pad_up, pad_left, pad_down, pad_right = _unpack_padding(padding)\n    _check_no_dilation(dilation)\n\n    batch_size, data_h, data_w, in_channels = data.shape\n    output_channels, kernel_h, kernel_w, _ = kernel.shape\n    assert kernel.shape[3] == in_channels\n\n    output_h = _compute_output_dim(data_h, kernel_h, pad_up, pad_down, stride_h)\n    output_w = _compute_output_dim(data_w, kernel_w, pad_left, pad_right, stride_w)\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n    kc_i = te.reduce_axis((0, in_channels), name=\"rc\")\n\n    padded_data = _pad_if_needed(data, \"NHWC\", (pad_up, pad_left, pad_down, pad_right))\n    return _wrap_te_compute(\n        (batch_size, output_h, output_w, output_channels),\n        lambda n, y, x, c: te.sum(\n            padded_data[n, y * stride_h + kh_i, x * stride_w + kw_i, kc_i].astype(out_dtype)\n            * kernel[c, kh_i, kw_i, kc_i].astype(out_dtype),\n            axis=(kh_i, kw_i, kc_i),\n        ),\n        out_layout,\n        name=\"conv2d\",\n        tag=\"conv2d_nhwc_ohwi_dsp\",\n    )\n\n\ndef _make_conv2d_tensorization(padded_data, kernel):\n    _, _, padded_w, in_channels = padded_data.shape\n    _, kernel_h, kernel_w, _ = kernel.shape\n    in_dtype = padded_data.dtype\n    suffix = _get_suffix()\n    assert in_dtype == kernel.dtype\n\n    data_slice = te.placeholder((kernel_h, kernel_w, in_channels), name=\"a\", dtype=in_dtype)\n    kernel_slice = te.placeholder((kernel_h, kernel_w, in_channels), name=\"b\", dtype=in_dtype)\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n    kc_i = te.reduce_axis((0, in_channels), name=\"kc_i\")\n\n    output_slice = te.compute(\n        (1,),\n        lambda k: te.sum(\n            data_slice[kh_i, kw_i, kc_i].astype(\"int32\")\n            * kernel_slice[kh_i, kw_i, kc_i].astype(\"int32\"),\n            axis=[kh_i, kw_i, kc_i],\n        ),\n        name=\"c\",\n    )\n\n    # TVM has a really strange bug where the outer reduction axis (kh_i) having length 1 causes the\n    # decl_buffer strides check to fail. height_stride is a dark magic workaround for this.\n    height_stride = in_channels * padded_w if kernel_h > 1 else in_channels\n    jump = (padded_w - kernel_w) * in_channels\n    tensordot_params = (in_dtype, kernel_h, jump, kernel_w * in_channels, suffix)\n    intrin_tensordot = make_intrin_tensordot(\n        (data_slice, kernel_slice, output_slice),\n        ([height_stride, in_channels, 1], [kernel_w * in_channels, in_channels, 1]),\n        tensordot_params,\n    )\n\n    tensordot_code = tensordot_impl(*tensordot_params)\n    return (intrin_tensordot, tensordot_code)\n\n\ndef depthwise_conv2d_nchw_oihw_dsp_compute(\n    _cfg, data, kernel, strides, padding, dilation, out_layout, out_dtype\n):\n    \"\"\"Depthwise conv2d schedule that can be tensorized using tensordot.\"\"\"\n\n    stride_h, stride_w = _unpack_2d_argument(strides)\n    pad_up, pad_left, pad_down, pad_right = _unpack_padding(padding)\n    _check_no_dilation(dilation)\n\n    batch_size, in_channels, data_h, data_w = data.shape\n    _, c_mul, kernel_h, kernel_w = kernel.shape\n    output_channels = in_channels * c_mul\n    assert kernel.shape[0] == in_channels\n\n    output_h = _compute_output_dim(data_h, kernel_h, pad_up, pad_down, stride_h)\n    output_w = _compute_output_dim(data_w, kernel_w, pad_left, pad_right, stride_w)\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n\n    padded_data = _pad_if_needed(data, \"NCHW\", (pad_up, pad_left, pad_down, pad_right))\n    return _wrap_te_compute(\n        (batch_size, output_h, output_w, output_channels),\n        lambda n, y, x, c: te.sum(\n            padded_data[\n                n,\n                indexdiv(c, c_mul),\n                y * stride_h + kh_i,\n                x * stride_w + kw_i,\n            ].astype(out_dtype)\n            * kernel[indexdiv(c, c_mul), indexmod(c, c_mul), kh_i, kw_i].astype(out_dtype),\n            axis=(kh_i, kw_i),\n        ),\n        out_layout,\n        name=\"depthwise_conv2d\",\n        tag=\"depthwise_conv2d_nchw_oihw_dsp\",\n    )\n\n\ndef _make_depthwise_conv2d_tensorization(padded_data, kernel):\n    _, _, _, padded_w = padded_data.shape\n    _, _, kernel_h, kernel_w = kernel.shape\n\n    in_dtype = padded_data.dtype\n    suffix = _get_suffix()\n    assert in_dtype == kernel.dtype\n\n    data_slice = te.placeholder((kernel_h, kernel_w), name=\"a\", dtype=in_dtype)\n    kernel_slice = te.placeholder((kernel_h, kernel_w), name=\"b\", dtype=in_dtype)\n\n    kh_i = te.reduce_axis((0, kernel_h), name=\"kh_i\")\n    kw_i = te.reduce_axis((0, kernel_w), name=\"kw_i\")\n\n    output_slice = te.compute(\n        (1,),\n        lambda k: te.sum(\n            data_slice[kh_i, kw_i].astype(\"int32\") * kernel_slice[kh_i, kw_i].astype(\"int32\"),\n            axis=[kh_i, kw_i],\n        ),\n        name=\"c\",\n    )\n\n    jump = padded_w - kernel_w\n    tensordot_params = (in_dtype, kernel_h, jump, kernel_w, suffix)\n    intrin_tensordot = make_intrin_tensordot(\n        (data_slice, kernel_slice, output_slice),\n        ([padded_w, 1], [kernel_w, 1]),\n        tensordot_params,\n    )\n\n    tensordot_code = tensordot_impl(*tensordot_params)\n    return (intrin_tensordot, tensordot_code)\n\n\ndef tensordot_conv2ds_schedule(_cfg, outs):\n    \"\"\"Schedule function using v7e-m DSP instructions for all the conv2d operators in this file. We\n    use one schedule function for them all, because they are tensorized with the same kernel.\"\"\"\n\n    schedule = te.create_schedule([x.op for x in outs])\n\n    def _callback(operator):\n        if \"conv2d\" in operator.tag:\n            output = operator.output(0)\n            padded_data = output.op.input_tensors[0]\n            kernel = output.op.input_tensors[1]\n\n            if operator.tag == \"conv2d_nhwc_ohwi_dsp\":\n                b_ax, y_ax, x_ax, co_ax = schedule[output].op.axis\n                kh_ax, kw_ax, ci_ax = schedule[output].op.reduce_axis\n                schedule[output].reorder(b_ax, y_ax, x_ax, co_ax, kh_ax, kw_ax, ci_ax)\n                intrin, code = _make_conv2d_tensorization(padded_data, kernel)\n\n            elif operator.tag == \"depthwise_conv2d_nchw_oihw_dsp\":\n                b_ax, y_ax, x_ax, co_ax = schedule[output].op.axis\n                kh_ax, kw_ax = schedule[output].op.reduce_axis\n                schedule[output].reorder(b_ax, co_ax, y_ax, x_ax, kh_ax, kw_ax)\n                intrin, code = _make_depthwise_conv2d_tensorization(padded_data, kernel)\n\n            else:\n                raise ValueError(f\"Cannot tensorize {operator.tag} with tensordot!\")\n\n            schedule[output].tensorize(kh_ax, intrin)\n            schedule[output].pragma(b_ax, \"import_c\", code)\n\n    traverse_inline(schedule, outs[-1].op, _callback)\n    return schedule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"Schedule for pooling operators\"\"\"\n\nfrom .mprofile.dsp.pool import pool_dsp_schedule\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Create schedule for avgpool/maxpool with dsp\"\"\"\n    return pool_dsp_schedule(outs, layout)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/arm_cpu/tensor_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D int8 schedule on ARM\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm.ir import register_intrin_lowering\n\n\ndef gemm_4x4_int8_int8_int32(M, N, K, unroll, in_type):\n    \"\"\"\n    Int8 4x4 matrix multiplication and accumulation using a sequence of\n    umull -> uadalp -> umull2 -> uadalp instructions. This function\n    takes two arrays of int8 data type  A[4][K] and B[4][K], and produces\n    a 4x4 matrix which is equal to A*B'.\n\n    The pseudo code is as follows.\n\n    .. code-block:: c\n\n        void gemm_4x4_int8_int8_int32(int8 A[4][K], int8 B[4][K], int32 C[4][4]){\n            for (int i = 0; i < 4; i++){\n                for (int j = 0; j < 4; j++){\n                    for (int k = 0; k < K; k++){\n                        C[i][j] += A[i][k] * B[j][k]\n                    }\n            }\n        }\n\n    Notes:\n        * The tiling strategy is picked to maximize register usage.\n\n    Parameters\n    ----------\n    M : int\n        rows of the matrix A\n    N : int\n        columns of the matrix B\n    K : int\n        columns of matrix A\n    unroll : bool\n        Unroll the loop accumulation if True\n    in_type : str, {'uint8', 'int8'}\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The ARM uint8/int8 TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n    assert in_type in [\"uint8\", \"int8\"]\n    A = te.placeholder((K // 16, te.var(\"m\"), 16), dtype=in_type, name=\"A\")\n    B = te.placeholder((K // 16, te.var(\"n\"), 16), dtype=in_type, name=\"B\")\n    dtype_vec = in_type + \"x16\"\n    idxm = tvm.tir.indexmod\n\n    k = te.reduce_axis((0, K), \"k\")\n    C = te.compute(\n        (te.var(\"m\"), te.var(\"n\")),\n        lambda x, y: te.sum(\n            A[k // 16, x, idxm(k, 16)].astype(\"int32\") * B[k // 16, y, idxm(k, 16)].astype(\"int32\"),\n            axis=k,\n        ),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        A.shape,\n        dtype=in_type,\n        name=\"a_buffer\",\n        offset_factor=1,\n        strides=[te.var(\"sa_1\"), te.var(\"sa_2\"), 1],\n    )\n\n    b_buffer = tvm.tir.decl_buffer(\n        B.shape,\n        dtype=in_type,\n        name=\"b_buffer\",\n        offset_factor=1,\n        strides=[te.var(\"sb_1\"), te.var(\"sb_2\"), 1],\n    )\n\n    c_buffer = tvm.tir.decl_buffer(\n        C.shape, dtype=\"int32\", name=\"c_buffer\", offset_factor=1, strides=[te.var(\"sc\"), 1]\n    )\n\n    # Intrinsics used in the following algorithm\n    umull_intrin = \"llvm.aarch64.neon.umull\" if in_type == \"uint8\" else \"llvm.aarch64.neon.smull\"\n    uaddlp_intrin = \"llvm.aarch64.neon.uaddlp\" if in_type == \"uint8\" else \"llvm.aarch64.neon.saddlp\"\n    addp_intrin = \"llvm.aarch64.neon.addp\"\n\n    def uadalp(a, b):\n        \"\"\"Add pair and accumulate\n\n        Parameters:\n        ----------\n        a: int16x8 vector\n        b: int16x8 vector\n\n        Returns:\n        --------\n            return a int32x4 vector\n\n        Pseudocode:\n        ----------\n            a += (b0+b1, b2+b3, b4+b5, b6+b7)\n        \"\"\"\n\n        return a + tvm.tir.call_llvm_pure_intrin(\n            \"int32x4\", uaddlp_intrin, tvm.tir.const(1, \"uint32\"), b\n        )\n\n    def umull(a, b):\n        \"\"\"Multiply long (higher part)\n\n        Parameters:\n        ----------\n        a: int8x16 vector\n        b: int8x16 vector\n\n        Returns:\n        --------\n            return a int16x8 vector\n\n        Pseudocode:\n        ----------\n            c = (a0*b0, a1*b1, a2*b2, a3*b3, a4*b4, a5*b5, a6*b6, a7*b7)\n        \"\"\"\n        a_high = tvm.tir.call_intrin(\"int8x8\", \"tir.vectorhigh\", a)\n        b_high = tvm.tir.call_intrin(\"int8x8\", \"tir.vectorhigh\", b)\n        c = tvm.tir.call_llvm_pure_intrin(\n            \"int16x8\", umull_intrin, tvm.tir.const(2, \"uint32\"), a_high, b_high\n        )\n        return c\n\n    def umull2(a, b):\n        \"\"\"Multiply long (lower part)\n\n        Parameters:\n        ----------\n        a: int8x16 vector\n        b: int8x16 vector\n\n        Returns:\n        --------\n            return a int16x8 vector\n\n        Pseudocode:\n        ----------\n            c = (a8*b8, a9*b9, a10*b10, a11*b11, a12*b12, a13*b13, a14*b14, a15*b15)\n        \"\"\"\n        a_low = tvm.tir.call_intrin(\"int8x8\", \"tir.vectorlow\", a)\n        b_low = tvm.tir.call_intrin(\"int8x8\", \"tir.vectorlow\", b)\n        c = tvm.tir.call_llvm_pure_intrin(\n            \"int16x8\", umull_intrin, tvm.tir.const(2, \"uint32\"), a_low, b_low\n        )\n        return c\n\n    def addp(a, b):\n        \"\"\"Add two vectors in pairs\n\n        Parameters:\n        ----------\n        a: int32x4 vector\n        b: int32x4 vector\n\n        Returns:\n        --------\n            return a int32x4 vector\n\n        Pseudocode:\n        ----------\n            c = (a0+a1, a2+a3, b0+b1, b0+b3)\n        \"\"\"\n        return tvm.tir.call_llvm_pure_intrin(\n            \"int32x4\", addp_intrin, tvm.tir.const(2, \"uint32\"), a, b\n        )\n\n    def accumulation_loop(M, N, ins, acc, tile_idx):\n        \"\"\"Internal tile accumulation. This function\n        takes two arrays of int8 data type  A[tile_idx][4][16] and B[tile_idx][4][16], produces\n        a 4x4 matrix which is equal to A*B' and accumulates into C[4][4]\n\n        The pseudo code is as follows.\n\n        .. code-block:: c\n\n            void gemm_4x4_int8_int8_int32(int8 A[tile_idx][4][K],\n                                          int8 B[tile_idx][4][K],\n                                          int32 C[4][4]){\n                for (int i = 0; i < 4; i++){\n                    for (int j = 0; j < 4; j++){\n                        for (int k = 0; k < 16; k++){\n                            C[i][j] += A[tile_idx][i][k] * B[tile_idx][j][k]\n                        }\n                }\n            }\n\n        Notes:\n            * The tiling strategy is picked to maximize register usage.\n\n        Parameters:\n        ----------\n        M : int\n            Number of total rows of the output matrix\n        N : int\n            Number of total columns of the output matrix\n        ins : list of tvm.tir.buffer\n            Input buffers\n        acc : tvm.tir.ir_builder.BufferVar\n            Bank of register accumulators\n        tiled_idx : int\n            Index of a sub-tile of A and B in A[tile_idx][:][:] and B[tile_idx][:][:].\n            Please note that  0 <= tile_idx <= K//16\n\n        \"\"\"\n        a0 = ins[0].vload([tile_idx, 0, 0], dtype_vec)\n        a1 = tvm.tir.const(0, \"int8x16\")\n        if M > 1:\n            a1 = ins[0].vload([tile_idx, 1, 0], dtype_vec)\n        a2 = tvm.tir.const(0, \"int8x16\")\n        if M > 2:\n            a2 = ins[0].vload([tile_idx, 2, 0], dtype_vec)\n        a3 = tvm.tir.const(0, \"int8x16\")\n        if M > 3:\n            a3 = ins[0].vload([tile_idx, 3, 0], dtype_vec)\n\n        b0 = ins[1].vload([tile_idx, 0, 0], dtype_vec)\n        b1 = tvm.tir.const(0, \"int8x16\")\n        if N > 1:\n            b1 = ins[1].vload([tile_idx, 1, 0], dtype_vec)\n        b2 = tvm.tir.const(0, \"int8x16\")\n        if N > 2:\n            b2 = ins[1].vload([tile_idx, 2, 0], dtype_vec)\n        b3 = tvm.tir.const(0, \"int8x16\")\n        if N > 3:\n            b3 = ins[1].vload([tile_idx, 3, 0], dtype_vec)\n\n        # First half\n        # Lower part of a0 * {b0,b1,b2,b3}\n        d00 = umull(a0, b0)\n        d01 = umull(a0, b1)\n        d02 = umull(a0, b2)\n        d03 = umull(a0, b3)\n\n        # Lower part of a1 * {b0,b1,b2,b3}\n        d10 = umull(a1, b0)\n        d11 = umull(a1, b1)\n        d12 = umull(a1, b2)\n        d13 = umull(a1, b3)\n\n        # Accumulate\n        acc[0] = uadalp(acc[0], d00)\n        acc[1] = uadalp(acc[1], d01)\n        acc[2] = uadalp(acc[2], d02)\n        acc[3] = uadalp(acc[3], d03)\n        acc[4] = uadalp(acc[4], d10)\n        acc[5] = uadalp(acc[5], d11)\n        acc[6] = uadalp(acc[6], d12)\n        acc[7] = uadalp(acc[7], d13)\n\n        # Higher part of a0 * {b0,b1,b2,b3}\n        d00 = umull2(a0, b0)\n        d01 = umull2(a0, b1)\n        d02 = umull2(a0, b2)\n        d03 = umull2(a0, b3)\n\n        # Higher part of a1 * {b0,b1,b2,b3}\n        d10 = umull2(a1, b0)\n        d11 = umull2(a1, b1)\n        d12 = umull2(a1, b2)\n        d13 = umull2(a1, b3)\n\n        # Accumulate again\n        acc[0] = uadalp(acc[0], d00)\n        acc[1] = uadalp(acc[1], d01)\n        acc[2] = uadalp(acc[2], d02)\n        acc[3] = uadalp(acc[3], d03)\n        acc[4] = uadalp(acc[4], d10)\n        acc[5] = uadalp(acc[5], d11)\n        acc[6] = uadalp(acc[6], d12)\n        acc[7] = uadalp(acc[7], d13)\n\n        # Second half\n        # Lower part of a2 * {b0,b1,b2,b3}\n        d00 = umull(a2, b0)\n        d01 = umull(a2, b1)\n        d02 = umull(a2, b2)\n        d03 = umull(a2, b3)\n\n        # Lower part of a3 * {b0,b1,b2,b3}\n        d10 = umull(a3, b0)\n        d11 = umull(a3, b1)\n        d12 = umull(a3, b2)\n        d13 = umull(a3, b3)\n\n        # Accumulate\n        acc[8] = uadalp(acc[8], d00)\n        acc[9] = uadalp(acc[9], d01)\n        acc[10] = uadalp(acc[10], d02)\n        acc[11] = uadalp(acc[11], d03)\n        acc[12] = uadalp(acc[12], d10)\n        acc[13] = uadalp(acc[13], d11)\n        acc[14] = uadalp(acc[14], d12)\n        acc[15] = uadalp(acc[15], d13)\n\n        # Higher part of a2 * {b0,b1,b2,b3}\n        d00 = umull2(a2, b0)\n        d01 = umull2(a2, b1)\n        d02 = umull2(a2, b2)\n        d03 = umull2(a2, b3)\n\n        # Lower part of a3 * {b0,b1,b2,b3}\n        d10 = umull2(a3, b0)\n        d11 = umull2(a3, b1)\n        d12 = umull2(a3, b2)\n        d13 = umull2(a3, b3)\n\n        # Accumulate\n        acc[8] = uadalp(acc[8], d00)\n        acc[9] = uadalp(acc[9], d01)\n        acc[10] = uadalp(acc[10], d02)\n        acc[11] = uadalp(acc[11], d03)\n        acc[12] = uadalp(acc[12], d10)\n        acc[13] = uadalp(acc[13], d11)\n        acc[14] = uadalp(acc[14], d12)\n        acc[15] = uadalp(acc[15], d13)\n\n    def _intrin_func(ins, outs):\n        def _instr():\n            ib = tvm.tir.ir_builder.create()\n            # Allocate a local buffer (possibly translates to registers)\n            acc = ib.allocate(\"int32x4\", 16, name=\"accs\", scope=\"local\")\n            m = outs[0].shape[0]\n            n = outs[0].shape[1]\n            # Initialization\n            for i in range(0, 16):\n                acc[i] = tvm.tir.const(0, \"int32x4\")\n\n            if unroll:\n                for i in range(0, int(K // 16)):\n                    accumulation_loop(M, N, ins, acc, i)\n            else:\n                with ib.for_range(0, K // 16, name=\"i\") as i:\n                    accumulation_loop(M, N, ins, acc, i)\n\n            # Final accumulations\n            # acc[4*r + c] contains the partial accumulations of element C[r][c]\n            #\n            # In particular:\n            # acc[4*r] contains the partial sums of a[r,0:K].*b[0,0:K] -> (a,b,c,d)\n            # acc[4*r+1] contains the partial sums of a[r, 0:K].*b[1,0:K] -> (e,f,g,h)\n            # acc[4*r+2] contains the partial sums of a[r, 0:K].*b[2,0:K] -> (i,j,k,l)\n            # acc[4*r+3] contains the partial sums of a[r, 0:K].*b[3,0:K] -> (m,n,o,p)\n            #\n            # Please note that 0<= r, c < 4\n\n            acc[0] = addp(acc[0], acc[1])  # (a+b, c+d, e+f, g+h)\n            acc[1] = addp(acc[2], acc[3])  # (i+j, k+l, m+n, o+p)\n            acc[0] = addp(acc[0], acc[1])  # (a+b+c+d, e+f+g+h, i+j+k+l, m+n+o+p)\n\n            acc[4] = addp(acc[4], acc[5])  # (a+b, c+d, e+f, g+h)\n            acc[5] = addp(acc[6], acc[7])  # (i+j, k+l, m+n, o+p)\n            acc[4] = addp(acc[4], acc[5])  # (a+b+c+d, e+f+g+h, i+j+k+l, m+n+o+p)\n\n            acc[8] = addp(acc[8], acc[9])  # (a+b, c+d, e+f, g+h)\n            acc[9] = addp(acc[10], acc[11])  # (i+j, k+l, m+n, o+p)\n            acc[8] = addp(acc[8], acc[9])  # (a+b+c+d, e+f+g+h, i+j+k+l, m+n+o+p)\n\n            acc[12] = addp(acc[12], acc[13])  # (a+b, c+d, e+f, g+h)\n            acc[13] = addp(acc[14], acc[15])  # (i+j, k+l, m+n, o+p)\n            acc[12] = addp(acc[12], acc[13])  # (a+b+c+d, e+f+g+h, i+j+k+l, m+n+o+p)\n\n            # Store the result\n            if N > 3:\n                out_0 = acc[0]\n                out_1 = acc[4]\n                out_2 = acc[8]\n                out_3 = acc[12]\n            elif N > 2:\n                out_0 = tvm.tir.call_intrin(\"int32x3\", \"tir.reinterpret\", acc[0])\n                out_1 = tvm.tir.call_intrin(\"int32x3\", \"tir.reinterpret\", acc[4])\n                out_2 = tvm.tir.call_intrin(\"int32x3\", \"tir.reinterpret\", acc[8])\n                out_3 = tvm.tir.call_intrin(\"int32x3\", \"tir.reinterpret\", acc[12])\n            elif N > 1:\n                out_0 = tvm.tir.call_intrin(\"int32x2\", \"tir.reinterpret\", acc[0])\n                out_1 = tvm.tir.call_intrin(\"int32x2\", \"tir.reinterpret\", acc[4])\n                out_2 = tvm.tir.call_intrin(\"int32x2\", \"tir.reinterpret\", acc[8])\n                out_3 = tvm.tir.call_intrin(\"int32x2\", \"tir.reinterpret\", acc[12])\n            else:\n                out_0 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", acc[0])\n                out_1 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", acc[4])\n                out_2 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", acc[8])\n                out_3 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", acc[12])\n\n            ib.emit(outs[0].vstore([0, 0], out_0))\n            if M > 1:\n                ib.emit(outs[0].vstore([1, 0], out_1))\n            if M > 2:\n                ib.emit(outs[0].vstore([2, 0], out_2))\n            if M > 3:\n                ib.emit(outs[0].vstore([3, 0], out_3))\n            return ib.get()\n\n        # body, reset, update\n        return _instr()\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={A: a_buffer, B: b_buffer, C: c_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef dot_int8_int8_int32_neon_82(int32_lanes, dtype=\"uint\"):\n    \"\"\"\n    Int8 dot product by every 4 elements using ARM v8.2 udot.\n    This function takes two arrays of int8 datatype -- data[4] and\n    kernel[int32_lanes][4] -- and computes a dot product of data[4] with every\n    4 elements of kernels, resulting in output[int32_lanes] of uint32 datatype.\n    The pseudo code is as follows.\n\n    .. code-block:: c\n\n        void dot_int8_int8_int32(int8 data[4], int8 kernel[16][4], int32 output[16]){\n            for (int i = 0; i < int32_lanes; i++){\n                out[i] = 0;\n                for (int k = 0; k < 4; k++){\n                    out[i] += data[k] * kernel[i][k]\n                }\n            }\n        }\n\n    Physically, the kernel array sits in a vector register and\n    the data[4] is broadcasted to another vector register. This\n    function returns a TensorIntrin that can be used to tensorize\n    a schedule.\n\n    Parameters\n    ----------\n    int32_lanes : int\n        How many int32/uint32 to produce\n    dtype : str, optional, {\"uint\", \"int\"}\n        Whether it works on unsigned int or signed int\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The ARM uint8 TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n    num_int8_elements = 4  # 4 int8 elements in int32\n\n    data = te.placeholder((num_int8_elements,), dtype=\"%s8\" % dtype, name=\"data\")\n    kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=\"%s8\" % dtype, name=\"kernel\")\n\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int32_lanes,),\n        lambda i: te.sum(\n            data[k].astype(\"%s32\" % dtype) * kernel[i, k].astype(\"%s32\" % dtype), axis=k\n        ),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=\"%s8\" % dtype, name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        kernel.shape,\n        dtype=\"%s8\" % dtype,\n        name=\"b_buffer\",\n        offset_factor=1,\n        strides=[te.var(\"s\"), 1],\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, \"%s32x%d\" % (dtype, int32_lanes))))\n                return ib.get()\n\n            dtype_a = \"%s8x%d\" % (dtype, num_int8_elements)\n            dtype_b = \"%s8x%d\" % (dtype, int32_lanes * num_int8_elements)\n            dtype_c = \"%s32x%d\" % (dtype, int32_lanes)\n\n            a_int8 = ins[0].vload([0], dtype_a)\n            re_int32 = tvm.tir.call_intrin(\"%s32\" % dtype, \"tir.reinterpret\", a_int8)\n            # broadcast a\n            vec_ai32 = re_int32.astype(dtype_c)\n\n            vec_a = tvm.tir.call_intrin(dtype_b, \"tir.reinterpret\", vec_ai32)\n            vec_b = ins[1].vload([0, 0], dtype_b)\n            vec_c = outs[0].vload([0], dtype_c)\n\n            inst = \"udot\" if dtype == \"uint\" else \"sdot\"\n            inst = \"llvm.aarch64.neon.%s.v%di32.v%di8\" % (\n                inst,\n                int32_lanes,\n                int32_lanes * num_int8_elements,\n            )\n            vdot = tvm.tir.call_llvm_pure_intrin(\n                dtype_c, inst, tvm.tir.const(3, \"uint32\"), vec_c, vec_a, vec_b\n            )\n            ib.emit(outs[0].vstore(0, vdot))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef dot_int8_int8_int32_neon():\n    \"\"\"\n    Int8 dot product using vmlal instructions\n\n    .. code-block:: c\n\n        void dot_int8_int8_int32(int8 data[4], int8 kernel[4][4], int32 output[4]){\n            for (int i = 0; i < 4; i++){\n                out[i] = 0;\n                for (int k = 0; k < 4; k++){\n                    out[i] += data[k] * kernel[i][k]\n                }\n            }\n        }\n\n    We use the smull and saddlp instructions to compute the dot product.\n    smull : int8x16 -> int8x16 -> int16x8 elementwise multiplication\n    saddlp: int16x8 -> int32x4 pairwise addition of elements\n\n    Data is broadcast across the register\n    int8 elements\n    |         data      |         data      |\n    |  0 |  1 |  2 |  3 |  4 |  5 |  6 |  7 |\n\n                      smull\n\n    int8 elements\n    |     kernel[i]     |     kernel[i+1]   |\n    |  0 |  1 |  2 |  3 |  4 |  5 |  6 |  7 |\n\n                        =\n\n    int16 elements\n    |               data * kernel[i]        |         data * kernel[i+1]            |\n    |    0    |    1    |    2    |    3    |    4    |    5    |    6    |    7    |\n\n                                          saddlp =\n\n    int32 elements\n    |    partial sum(data * kernel[i])      |  partial sum(data * kernel[i+1])      |\n    |         0         |         1         |         2         |         3         |\n\n\n    We apply the above kernel twice and use addp to compute the second set of pairwise additions\n\n    int32 elements (narrowed for so they fit on a line)\n    |    psum d*k[i]    |   psum d*k[i+1]   |           |   psum d*k[i+2]   |   psum d*k[i+3]   |\n    |    0    |    1    |    2    |    3    |   addp    |    4    |    5    |    6    |    7    |\n                                                 =\n    |sum d*ki |sum d*ki1|sum d*ki2|sum d*ki3|\n    |    0    |    1    |    2    |    3    |\n\n\n    \"\"\"\n    int32_lanes = 4  # 4 int32 lanes = 128\n    num_int8_elements = 4  # 4 int8 elements in int32\n    data = te.placeholder((num_int8_elements,), dtype=\"int8\", name=\"data\")\n    kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=\"int8\", name=\"kernel\")\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int32_lanes,),\n        lambda i: te.sum(data[k].astype(\"int32\") * kernel[i, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=\"int8\", name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        kernel.shape, dtype=\"int8\", name=\"b_buffer\", offset_factor=1, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            int_8xl = \"int8x8\"\n            int_32xl = \"int32x4\"\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, int_32xl)))\n                return ib.get()\n\n            # this broadcasts data to the vector size\n            a_int8 = ins[0].vload([0], \"int8x4\")\n            re_int32 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", a_int8)\n            vec_ai32 = re_int32.astype(\"int32x2\")\n            vec_a = tvm.tir.call_intrin(int_8xl, \"tir.reinterpret\", vec_ai32)\n\n            vec_b = ins[1].vload([0, 0], \"int8x16\")\n\n            def pairwise_add_mul(extract_half):\n                vec_b_half = tvm.tir.call_intrin(\"int8x8\", extract_half, vec_b)\n                multiply = tvm.tir.call_llvm_pure_intrin(\n                    \"int16x8\",\n                    \"llvm.aarch64.neon.smull.v8i16\",  # saturating pairwise multiplication\n                    tvm.tir.const(2, \"uint32\"),\n                    vec_a,\n                    vec_b_half,\n                )\n                pairwise_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int32x4\",\n                    \"llvm.aarch64.neon.saddlp.v4i32.v8i16\",\n                    tvm.tir.const(1, \"uint32\"),\n                    multiply,\n                )\n                return pairwise_reduction\n\n            pair_1 = pairwise_add_mul(\"tir.vectorlow\")\n            pair_2 = pairwise_add_mul(\"tir.vectorhigh\")\n            quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                \"int32x4\",\n                \"llvm.aarch64.neon.addp.v4i32\",\n                tvm.tir.const(2, \"uint32\"),\n                pair_1,\n                pair_2,\n            )\n            if index == 0:\n                ib.emit(outs[0].vstore(0, quad_reduction))\n            else:\n                ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], int_32xl)))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef select_word(vec, lane, dtype_vec):\n    \"\"\"\n    Utility function used to select a int8x4 word within a int8x16 vector\n    and replicate 4 times.\n    The pseudo-code for this operation is:\n\n    v = [x0, ..., x15]\n    vsub(lane) = v[4*lane:4*lane+3]\n    replicated_v(lane) = [vsub(lane), vsub(lane), vsub(lane), vsub(lane)]\n\n    Note that 0<=lane<4\n\n     Parameters\n    ----------\n    vec : tvm.tir.Expr\n         int8x16 vector expression\n    lane : int\n        vector lane we want to replicate\n    dtype_vec : str\n        vector data type (e.g., int8x16)\n\n    Returns\n    ----------\n    output : tvm.tir.Expr\n        replicated vector\n    \"\"\"\n    # Reinterpret vec_a as 4 int32 words\n    vec_int32 = tvm.tir.call_intrin(\"int32x4\", \"tir.reinterpret\", vec)\n    # Broadcast the lane-th word\n    vec_int32_shuffled = tvm.tir.Shuffle([vec_int32], [lane, lane, lane, lane])\n    # Convert back to uint8x16\n    vec_int8_broadcast = tvm.tir.call_intrin(dtype_vec, \"tir.reinterpret\", vec_int32_shuffled)\n    return vec_int8_broadcast\n\n\ndef gemm_acc_4x4_int8_int8_int32(dtype):\n    \"\"\"\n    Int8 4x4 matrix multiplication and accumulation using sdot/udot\n    instructions. This function takes two arrays of int8 datatype\n    -- A[4][4] and B[4][4] and produces a 4x4 matrix\n    which is equal to A*B'.\n\n    The pseudo code is as follows.\n\n    .. code-block:: c\n\n        void gemm_acc_4x4_int8_int8_int32(int8 A[4][4], int8 B[4][4], int32 C[4][4]){\n            for (int i = 0; i < 4; i++){\n                for (int j = 0; j < 4; j++){\n                    for (int k = 0; k < 4; k++){\n                        C[i][j] += A[i][k] * B[j][k]\n                    }\n            }\n        }\n\n    Notes:\n        * The tiling strategy is picked to maximize register usage.\n\n    Parameters\n    ----------\n    dtype : str, {\"uint8\", \"int8\"}\n        Whether it works on unsigned int or signed int\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Arm TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n    assert dtype in [\"uint8\", \"int8\"]\n    # This needs to be a variable number of \"rows\" since TVM\n    # \"thinks\" I only need to compute one row because of\n    # padding\n    A = te.placeholder((te.var(\"rows\"), 4), dtype, name=\"A\")\n    B = te.placeholder((4, 4), dtype, name=\"B\")\n    dtype_vec = dtype + \"x16\"\n\n    k = te.reduce_axis((0, 4), name=\"k\")\n    C = te.compute(\n        (te.var(\"rows\"), 4),\n        lambda i, j: te.sum(A[i, k].astype(\"int32\") * B[j, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    aa_buffer = tvm.tir.decl_buffer(\n        A.shape, dtype, name=\"aa_buffer\", offset_factor=1, strides=[te.var(\"sa\"), 1]\n    )\n    bb_buffer = tvm.tir.decl_buffer(\n        B.shape, dtype, name=\"bb_buffer\", offset_factor=1, strides=[te.var(\"sb\"), 1]\n    )\n    cc_buffer = tvm.tir.decl_buffer(\n        C.shape, dtype=\"int32\", name=\"cc_buffer\", offset_factor=1, strides=[te.var(\"sc\"), 1]\n    )\n\n    llvm_intrin = \"llvm.aarch64.neon.sdot\" if dtype == \"int8\" else \"llvm.aarch64.neon.udot\"\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                for i in range(0, 4):\n                    ib.emit(outs[0].vstore([i, 0], tvm.tir.const(0, \"int32x4\")))\n                return ib.get()\n            # Load all the elements of tile A.\n            # vec_a = [a, b, c, d,\n            #          e, f, g, h,\n            #          l, m, n, o,\n            #          p, q, r, s];\n            vec_a = ins[0].vload([0, 0], dtype_vec)\n\n            # Replicate 4 times the i-th row of A. For instance,\n            # vec_a[0] = [a, b, c, d,\n            #             a, b, c, d,\n            #             a, b, c, d,\n            #             a, b, c, d,];\n            vec_aa = [select_word(vec_a, i, dtype_vec) for i in range(0, 4)]\n\n            # Load all the elements of B. Remember that B\n            # is transposed:\n            # vec_b = [0, 4, 8, 12,\n            #          1, 5, 9, 13,\n            #          2, 6, 10, 14,\n            #          3, 7, 11, 15,];\n            vec_b = ins[1].vload([0, 0], dtype_vec)\n\n            # Execute the dot product\n            for i in range(0, 4):\n                vec_c = outs[0].vload([i, 0], \"int32x4\")\n                # Compute the product between the i-th row of A\n                # and all the rows of B. Remember that sdot/udot\n                # subdive the input vectors in 16 elements\n                # and then take the dot product among each group.\n                # The result is stored in a int32x4 register\n                #\n                # For instance, for i=0, we have:\n                # sdot(vec_aa[0], vec_b) = [a*0+b*4+c*8+d*12,\n                #                           a*1+b*5+c*9+d*13,\n                #                           a*2+b*6+c*10+d*14,\n                #                           a*3+b*7+c*11+d*15]\n                vdot = tvm.tir.call_llvm_intrin(\n                    \"int32x4\",\n                    llvm_intrin,\n                    tvm.tir.const(3, \"uint32\"),\n                    vec_c,\n                    vec_b,\n                    vec_aa[i],\n                )\n\n                # Store the result\n                ib.emit(outs[0].vstore([i, 0], vdot))\n\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={A: aa_buffer, B: bb_buffer, C: cc_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef gemm_acc_nx16_int8_int8_int32(dtype, rows):\n    \"\"\"\n    Int8 nx16 matrix multiplication and accumulation using sdot/udot instructions\n    This function takes two arrays of int8 datatype -- A[n][4] and\n    B[4][16] and produces a rowsx16 matrix which is equal to A*B'\n    The pseudo code is as follows.\n\n    .. code-block:: c\n\n        void mmla_nx16_int8_int8_int32(int8 A[n][16], int8 B[4][16][4], int32 output[n][16]){\n            for (int i = 0; i < n; i++){\n                for (int j = 0; j < 16; j++){\n                    for (int k = 0; k < 16; k++){\n                        out[i][j] += A[i][k] * B[k//4][j][k%4]\n                    }\n                }\n            }\n        }\n\n    Notes:\n        * The tile size of B is 16x4. Since the reduction variable k moves between 0 and 16\n          we need 4 tiles of B to compute a single row of the output. The first 4 values of\n          k will be fetched from B[0][j][k], the second batch of 4 from B[1][j][k] and so on\n        * The tiling strategy is picked to maximize register usage.\n\n    Parameters\n    ----------\n    dtype : str, {\"uint8\", \"int8\"}\n        Whether it works on unsigned int or signed int\n    rows : int\n        Number of the output rows \"n\"\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Arm TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n    assert dtype in [\"uint8\", \"int8\"]\n    A = te.placeholder((rows, 16), dtype, name=\"A\")\n    B = te.placeholder((4, 16, 4), dtype, name=\"B\")\n    dtype_vec = dtype + \"x16\"\n    idxm = tvm.tir.indexmod\n    k = te.reduce_axis((0, 16), name=\"k\")\n    C = te.compute(\n        (rows, 16),\n        lambda i, j: te.sum(\n            A[i, k].astype(\"int32\") * B[k // 4, j, idxm(k, 4)].astype(\"int32\"), axis=k\n        ),\n        name=\"C\",\n    )\n\n    aa_buffer = tvm.tir.decl_buffer(\n        A.shape, dtype, name=\"aa_buffer\", offset_factor=1, strides=[te.var(\"sa\"), 1]\n    )\n    bb_buffer = tvm.tir.decl_buffer(\n        B.shape,\n        dtype,\n        name=\"bb_buffer\",\n        offset_factor=1,\n        strides=[te.var(\"sb0\"), te.var(\"sb1\"), 1],\n    )\n    cc_buffer = tvm.tir.decl_buffer(\n        C.shape, dtype=\"int32\", name=\"cc_buffer\", offset_factor=1, strides=[te.var(\"sc\"), 1]\n    )\n\n    llvm_intrin = \"llvm.aarch64.neon.sdot\" if dtype == \"int8\" else \"llvm.aarch64.neon.udot\"\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                for i in range(0, rows):\n                    ib.emit(outs[0].vstore([i, 0], tvm.tir.const(0, \"int32x16\")))\n                return ib.get()\n            # Iterate on the number of rows of the output\n            for k in range(0, rows):\n                # Load 16 elements of A\n                # vec_a = [a, b, c, d, e, f, g, h, l, m, n, o, p, q, r, s];\n                vec_a = ins[0].vload([k, 0], dtype_vec)\n\n                # Iterate over each of the 4 rowsx4 tiles of the output\n                for j in range(0, 4):\n                    # Accumulate over each of the 4 (16x4) tiles contained in B\n                    for i in range(0, 4):\n                        # Replicate a single 4-element group of A (A[k, i:i+4])\n                        vec_aa = select_word(vec_a, i, dtype_vec)\n\n                        # Load 4 rows (each rows with 4 elements) from B (B[i:i+4, j:j+4])\n                        # vec_b = [0, 16, 32, 48,\n                        #          1, 17, 33, 49,\n                        #          2, 18, 34, 50,\n                        #          3, 19, 35, 51,];\n                        vec_b = ins[1].vload([i, 4 * j, 0], dtype_vec)\n\n                        # Accumulate in the correct part of the output\n                        vec_c = outs[0].vload([k, 4 * j], \"int32x4\")\n\n                        # Compute the dot product between the rowsx4 tile\n                        # from A and the 4x4 tile from B\n                        #\n                        # For instance, for i=0, we have:\n                        # sdot(vec_aa[0], vec_b) = [a*0+b*16+c*32+d*48,\n                        #                           a*1+b*17+c*33+d*49,\n                        #                           a*2+b*18+c*34+d*50,\n                        #                           a*3+b*19+c*35+d*51]\n                        vdot = tvm.tir.call_llvm_intrin(\n                            \"int32x4\",\n                            llvm_intrin,\n                            tvm.tir.const(3, \"uint32\"),\n                            vec_c,\n                            vec_b,\n                            vec_aa,\n                        )\n                        ib.emit(outs[0].vstore([k, 4 * j], vdot))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={A: aa_buffer, B: bb_buffer, C: cc_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef smlal_int16_int32():\n    \"\"\"\n    Intrinsic to be used in order to load two int16x8 vectors and multiply\n    them together through a pair of smlal/smlal2 instructions. The pseudo-code\n    for the algorithm is as follows:\n\n        vec_a = vload(A, \"int16x8\")\n        vec_b = vload(B, \"int16x8\")\n\n        vec_c[0:4] += vec_a[0:4]*vec_b[0:4] //  -> smlal instruction\n        vec_c[4:8] += vec_a[4:8]*vec_b[4:8] // -> smlal2 instruction\n\n    So we load a single int16x8 vector and we accumulate its lower (0:4) and\n    higher part separately.\n    \"\"\"\n    int16_lanes = 8\n    A = te.placeholder((int16_lanes,), dtype=\"int16\", name=\"A\")\n    B = te.placeholder((int16_lanes, 1), dtype=\"int16\", name=\"B\")\n    C = te.compute(\n        (int16_lanes,),\n        lambda i: A[i].astype(\"int32\") * B[i, 0].astype(\"int32\"),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        A.shape, dtype=\"int16\", name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        B.shape,\n        dtype=\"int16\",\n        name=\"b_buffer\",\n        offset_factor=1,\n        strides=[te.var(\"sb\"), 1],\n    )\n    c_buffer = tvm.tir.decl_buffer(\n        C.shape,\n        dtype=\"int32\",\n        name=\"c_buffer\",\n        offset_factor=1,\n        strides=[1],\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, \"int32x8\")))\n                return ib.get()\n\n            vec_a = ins[0].vload([0], \"int16x8\")\n            vec_b = ins[1].vload([0, 0], \"int16x8\")\n            inst = \"llvm.aarch64.neon.smull\"\n\n            # Higher part of the vector\n            vec_c_h = outs[0].vload([4], \"int32x4\")\n            vec_a_h = tvm.tir.call_intrin(\"int16x4\", \"tir.vectorhigh\", vec_a)\n            vec_b_h = tvm.tir.call_intrin(\"int16x4\", \"tir.vectorhigh\", vec_b)\n            vmull_h = tvm.tir.call_llvm_pure_intrin(\n                \"int32x4\", inst, tvm.tir.const(2, \"uint32\"), vec_a_h, vec_b_h\n            )\n            vec_out_h = vec_c_h + vmull_h\n\n            # Lower part of the vector\n            vec_c_l = outs[0].vload([0], \"int32x4\")\n            vec_a_l = tvm.tir.call_intrin(\"int16x4\", \"tir.vectorlow\", vec_a)\n            vec_b_l = tvm.tir.call_intrin(\"int16x4\", \"tir.vectorlow\", vec_b)\n            vmull_l = tvm.tir.call_llvm_pure_intrin(\n                \"int32x4\", inst, tvm.tir.const(2, \"uint32\"), vec_a_l, vec_b_l\n            )\n            vec_out_l = vec_c_l + vmull_l\n\n            # Combine higher and lower part in a single int32x8 vector to store\n            # (this will require two different store instructions, since the\n            # length of a NEON vector is fixed at 128\n            vec_out = tvm.tir.call_intrin(\"int32x8\", \"tir.vectorcombine\", vec_out_l, vec_out_h)\n            ib.emit(outs[0].vstore(0, vec_out))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={A: a_buffer, B: b_buffer, C: c_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef gemm_acc_2x2_int8_int8_int32(dtype):\n    \"\"\"\n    Int8 2x2 matrix multiplication using smmla/ummla instructions\n    This function takes two arrays of int8 datatype -- A[2][8] and\n    B[2][8] and produces a 2x2 matrix which is equal to A*B'\n    The pseudo code is as follows.\n\n    .. code-block:: c\n\n        void mmla_2x2_int8_int8_int32(int8 A[2][8], int8 B[2][8], int32 C[2][2]){\n            for (int i = 0; i < 2; i++){\n                for (int j = 0; j < 2; j++){\n                    for (int k = 0; k < 8; k++){\n                        C[i][j] += A[i][k] * B[j][k]\n                    }\n            }\n        }\n\n    Parameters\n    ----------\n    dtype : str, {\"uint8\", \"int8\"}\n        Whether it works on unsigned int or signed int\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Arm TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n    assert dtype in [\"uint8\", \"int8\"]\n    A = te.placeholder((2, 8), dtype, name=\"A\")\n    B = te.placeholder((2, 8), dtype, name=\"B\")\n    dtype_vec = dtype + \"x16\"\n\n    k = te.reduce_axis((0, 8), name=\"k\")\n    C = te.compute(\n        (2, 2),\n        lambda i, j: te.sum(A[i, k].astype(\"int32\") * B[j, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    aa_buffer = tvm.tir.decl_buffer(\n        A.shape, dtype, name=\"aa_buffer\", offset_factor=1, strides=[te.var(\"sa\"), 1]\n    )\n    bb_buffer = tvm.tir.decl_buffer(\n        B.shape, dtype, name=\"bb_buffer\", offset_factor=1, strides=[te.var(\"sb\"), 1]\n    )\n    cc_buffer = tvm.tir.decl_buffer(\n        C.shape, dtype=\"int32\", name=\"cc_buffer\", offset_factor=1, strides=[te.var(\"sc\"), 1]\n    )\n\n    llvm_intrin = \"llvm.aarch64.neon.smmla\" if dtype == \"int8\" else \"llvm.aarch64.neon.ummla\"\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore([0, 0], tvm.tir.const(0, \"int32x4\")))\n                return ib.get()\n            # Load in vec_a the two rows of A\n            # vec_a = [a, b, c, d, e, f, g, h;\n            #          i, j, k, l, m, n, o, p,]\n            vec_a = ins[0].vload([0, 0], dtype_vec)\n            # Load in vec_b the two rows of B\n            # vec_b = [0, 2, 4, 6, 8, 10, 12, 14;\n            #          1, 3, 5, 7, 9, 11, 13, 14,]\n            vec_b = ins[1].vload([0, 0], dtype_vec)\n\n            # Execute the matrix multiplication via (s/u)mmla:\n            # vec_c = [a*0 + b*2 + c*4 + d*6 +e*8 + f*10 + g*12 + h*14;\n            #          a*1 + b*3 + c*5 + d*7 +e*9 + f*11 + g*13 + h*15;\n            #          i*0 + j*2 + k*4 + l*6 +m*8 + n*10 + o*12 + p*14;\n            #          i*1 + j*3 + k*5 + l*7 +m*9 + n*11 + o*13 + p*15]\n            vec_c = outs[0].vload([0, 0], \"int32x4\")\n            vmmla = tvm.tir.call_llvm_intrin(\n                \"int32x4\",\n                llvm_intrin,\n                tvm.tir.const(3, \"uint32\"),\n                vec_c,\n                vec_a,\n                vec_b,\n            )\n            # Store the result\n            ib.emit(outs[0].vstore([0, 0], vmmla))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={A: aa_buffer, B: bb_buffer, C: cc_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef _q_multiply_shift_arm(op):\n    \"\"\"\n    Implementation of q_multiply_shift_arm through arm intrinsics\n    sqrdmulh and srshl when q == 31.\n\n    Please note that this is introducing a small round-up error for\n    some corner cases. This is because we are rounding twice instead\n    than only once. I.e.:\n\n        * original q_multiply_shift: round(x*y*2^-s)\n        * arm q_multiply_shift: round(round(x*y)*2^-s)\n    \"\"\"\n    x = op.args[0]\n    y = op.args[1]\n    q = op.args[2]\n    s = op.args[3]\n\n    # Don't use this intrinsic if we don't have a int32x4 vector\n    # or if we are not multiplying q31 numbers\n    if x.dtype != \"int32x4\" or q.value != 31:\n        return op\n\n    # Case 1, shift is negative\n    sqrdmulh = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.aarch64.neon.sqrdmulh\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n\n    fixup = (sqrdmulh & (-s)) >> 31\n    fixed_up_x = sqrdmulh + fixup\n    out_1 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.aarch64.neon.srshl\", tvm.tir.const(2, \"uint32\"), sqrdmulh, s\n    )\n\n    # Case 2, shift is positive\n    x = x * (1 << (s))\n    out_2 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.aarch64.neon.sqrdmulh\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n\n    # Select depending on the shift\n    return tvm.tir.Select(s < 0, out_1, out_2)\n\n\nregister_intrin_lowering(\n    \"tir.q_multiply_shift\", target=\"llvm.aarch64\", f=_q_multiply_shift_arm, level=99\n)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"ARM Mali GPU specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .gemm import *\nfrom .conv2d import *\nfrom .dense import *\nfrom .depthwise_conv2d import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"conv2d schedule on ARM Mali (Bifrost) GPU\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\n\nfrom .gemm import decl_winograd_gemm, schedule_gemm\nfrom .transforms import tile_and_bind, tile_and_bind3d\nfrom ..utils import traverse_inline, get_const_int, get_const_tuple\nfrom .. import nn\nfrom ..nn.winograd_util import winograd_transform_matrices\n\n# reuse some compute declarations from ARM CPU\nfrom ..arm_cpu.conv2d_spatial_pack import conv2d_spatial_pack_nchw\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_spatial_pack.bifrost\")\ndef conv2d_nchw_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"TOPI compute callback for conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width] or\n        pre-packed 5-D with shape [num_filter_chunk, in_channel, filter_height,\n        filter_width, num_filter_block]\n\n    strides : list of two ints\n        [stride_height, stride_width]\n\n    padding : list of two ints\n        [pad_height, pad_width]\n\n    dilation : list of two ints\n        [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return conv2d_spatial_pack_nchw(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=3\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_spatial_pack.bifrost\")\ndef schedule_conv2d_nchw_spatial_pack(cfg, outs):\n    \"\"\"TOPI schedule callback for conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The configuration of this template\n    outs: Array of Tensor\n        The computation graph description of convolution2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        # schedule conv2d\n        if \"spatial_conv2d_output\" in op.tag:\n            output = op.output(0)\n            conv = op.input_tensors[0]\n\n            data_vec = conv.op.input_tensors[0]\n            data_pad = data_vec.op.input_tensors[0]\n            s[data_pad].compute_inline()\n\n            kernel_vec = conv.op.input_tensors[1]\n            if kernel_vec.op.name == \"kernel_vec\":\n                kernel = kernel_vec.op.input_tensors[0]\n            else:\n                kernel = kernel_vec\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            _schedule_spatial_pack(cfg, s, output, conv, data_vec, kernel_vec)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_spatial_pack(cfg, s, output, conv, data_vec, kernel_vec):\n    \"\"\"schedule the spatial packing for conv2d\"\"\"\n    data = s[data_vec].op.input_tensors[0]\n\n    max_unroll = 16\n    vec_size = [1, 2, 4, 8, 16]\n    # get tunable parameters (they are defined in compute)\n    BC, TC, VC = cfg[\"tile_co\"].size\n    BH, TH, VH = cfg[\"tile_oh\"].size\n    BW, TW, VW = cfg[\"tile_ow\"].size\n\n    # schedule padding\n    if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n        data_pad = data\n        s[data_pad].compute_inline()\n\n    # schedule data packing\n    if isinstance(data_vec.op, te.tensor.ComputeOp) and data_vec.op.name == \"data_vec_undilated\":\n        _, h, w, ci, _, _, vh, vw = s[data_vec].op.axis\n    else:\n        _, h, w, ci, vh, vw = s[data_vec].op.axis\n    tile_and_bind3d(s, data_vec, h, w, ci, 1)\n    if vh.dom.extent.value < max_unroll:\n        s[data_vec].unroll(vh)\n    if vw.dom.extent.value < max_unroll:\n        s[data_vec].unroll(vw)\n\n    if isinstance(kernel_vec.op, tvm.te.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            max_threads = tvm.target.Target.current(allow_none=False).max_num_threads\n            co, ci, kh, kw, vc = s[kernel_vec].op.axis\n            fused = s[kernel_vec].fuse(co, ci, kh, kw, vc)\n            fused, vec = s[kernel_vec].split(fused, VC)\n            bb, tt = s[kernel_vec].split(fused, max_threads)\n            s[kernel_vec].bind(bb, te.thread_axis(\"blockIdx.x\"))\n            s[kernel_vec].bind(tt, te.thread_axis(\"threadIdx.x\"))\n            if VC in vec_size:\n                s[kernel_vec].vectorize(vec)\n\n    # schedule convolution\n    n, c, h, w, vh, vw, vc = s[conv].op.axis\n    kc, kh, kw = s[conv].op.reduce_axis\n\n    cfg[\"reorder_0\"].apply(s, conv, [n, c, h, w, kc, kh, kw, vh, vw, vc])\n    tile_and_bind3d(s, conv, c, h, w, TC, TH, TW)\n\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv,\n        [kh, kw],\n        axis_lens=[get_const_int(kernel_vec.shape[2]), get_const_int(kernel_vec.shape[3])],\n        max_unroll=max_unroll,\n    )\n\n    cfg[\"ann_spatial\"].apply(\n        s,\n        conv,\n        [vh, vw, vc],\n        axis_lens=[VH, VW, VC],\n        max_unroll=max_unroll,\n        vec_size=vec_size,\n        cfg=cfg,\n    )\n\n    # schedule output\n    if output.op not in s.outputs:  # has bias\n        s[output].compute_inline()\n        output = s.outputs[0]\n\n    _, co, oh, ow = s[output].op.axis\n    tile_and_bind3d(s, output, co, oh, ow, TC, TH, TW)\n\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd.bifrost\")\ndef conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Use Winograd as the convolution method\"\"\"\n    return _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd.bifrost\")\ndef schedule_conv2d_nchw_winograd(cfg, outs):\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"winograd_conv2d_output\" in op.tag:\n            _schedule_winograd(cfg, s, op)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _decl_winograd_kernel_transform(kernel, tile_size, G):\n    \"\"\"Declare a Winograd kernel transform\n    This exists separately to allow for precomputation\n    The precomputation will most often happen on CPU\n\n    Parameters\n    ----------\n    kernel : tvm.te.Tensor\n        The kernel to transform\n\n    tile_size : int\n        The size of the tile to use for the Winograd filter\n\n    Returns\n    -------\n    U : tvm.te.Tensor\n        Transformed kernel\n\n    \"\"\"\n    CO, CI, KH, KW = [get_const_int(x) for x in kernel.shape]\n    # Only support 32 bit floats\n    out_dtype = \"float32\"\n\n    alpha = G.shape[0]\n    K = CO\n    C = CI\n\n    def upround(x, align):\n        return (x + align - 1) // align * align\n\n    ALIGN = 16\n    K_round = upround(K, ALIGN)\n\n    # Padded Kernel [K_round, C, KH, KW]\n    # Pad the number of kernels to multiple of ALIGN\n    padded_kernel = te.compute(\n        (K_round, C, KH, KW),\n        lambda k, c, h, w: tvm.tir.if_then_else(\n            k < K, kernel[k][c][h][w], tvm.tir.const(0, out_dtype)\n        ),\n        name=\"padded_kernel\",\n    )\n\n    # U [alpha, alpha, K_round, C]\n    # Perform the kernel transform\n    r_kh = te.reduce_axis((0, KH), \"r_kh\")\n    r_kw = te.reduce_axis((0, KW), \"r_kw\")\n    U = te.compute(\n        (alpha, alpha, K_round, C),\n        lambda eps, nu, k, c: te.sum(\n            padded_kernel[k][c][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n        ),\n        name=\"U\",\n    )\n\n    return U\n\n\ndef _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size=2):\n    \"\"\"Declare a winograd convolution - only tile_size=2 is currently supported\"\"\"\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    if int(kernel.shape[2]) == 3:\n        if dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_h, dilation_w))\n        pre_computed = False\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n    else:\n        assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n        pre_computed = True\n        H_CAT, W_CAT, CO, CI = get_const_tuple(kernel.shape)\n        KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW))\n\n    assert KH == 3 and KW == 3 and HSTR == 1 and WSTR == 1\n    data_pad = nn.pad(data, (0, 0, pt, pl), (0, 0, pb, pr), name=\"data_pad\")\n\n    r = KW\n    m = tile_size\n    alpha = m + r - 1\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    K = CO\n    C = CI\n    H = (IH + pt + pb - 3) // HSTR + 1\n    W = (IW + pl + pr - 3) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n\n    def upround(x, align):\n        return (x + align - 1) // align * align\n\n    ALIGN = 16\n    P_round = upround(P, ALIGN)\n    K_round = upround(K, ALIGN)\n\n    # CONFIG\n\n    cfg.define_knob(\"data_transform_wgx\", [1, 2, 4, 8, 16, 32, 64])\n    cfg.define_knob(\"data_transform_wgy\", [1, 2, 4, 8, 16, 32, 64])\n\n    # Pack input tile\n    input_tile = te.compute((N, C, H + 2, W + 2), lambda n, c, h, w: data_pad[n][c][h][w], name=\"d\")\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        VC = cfg[\"tile_k\"].size[-1]\n        kvshape = (KH + tile_size - 1, KW + tile_size - 1, tvm.tir.indexdiv(CO, VC), CI, VC)\n        U = tvm.te.placeholder(kvshape, kernel.dtype, name=\"U\")\n    else:\n        if pre_computed:\n            U = kernel\n        else:\n            U = _decl_winograd_kernel_transform(kernel, tile_size, G)\n\n    # V [alpha * alpha, C, P_round)\n    # Perform the image transform\n    r_eps = te.reduce_axis((0, alpha), \"r_eps\")\n    r_nu = te.reduce_axis((0, alpha), \"r_nu\")\n    V = te.compute(\n        (alpha * alpha, C, P_round),\n        lambda epsnu, c, b: te.sum(\n            input_tile[b // (nH * nW)][c][b // nW % nH * m + r_eps][b % nW * m + r_nu]\n            * B[r_eps][epsnu // alpha]\n            * B[r_nu][epsnu % alpha],\n            axis=[r_eps, r_nu],\n        ),\n        name=\"V\",\n    )\n\n    # Winograd GEMM is a wrapper around batched GEMM to convert U to a 3D Tensor\n    _, M = decl_winograd_gemm(cfg, U, V)\n\n    # Y [K, P, m, m]\n    # Winograd output transform\n    r_eps = te.reduce_axis((0, alpha), \"r_eps\")\n    r_nu = te.reduce_axis((0, alpha), \"r_nu\")\n    Y = te.compute(\n        (K, P, m, m),\n        lambda k, b, vh, vw: te.sum(\n            M[r_eps * alpha + r_nu][k][b] * A[r_eps][vh] * A[r_nu][vw], axis=[r_eps, r_nu]\n        ),\n        name=\"Y\",\n    )\n\n    # Output [N, K, H, W]\n    # Unpack back to NCHW format\n    # The last term ensures alignment is not lost to bound inference\n    output = te.compute(\n        (N, K, H, W),\n        lambda n, k, h, w: Y[k][n * nH * nW + (h // m) * nW + w // m][h % m][w % m]\n        + tvm.tir.const(0, out_dtype) * M[(alpha * alpha) - 1][K_round - 1][P_round - 1],\n        name=\"output\",\n        tag=\"winograd_conv2d_output\",\n    )\n\n    return output\n\n\ndef _schedule_winograd(cfg, s, op):\n    \"\"\"Schedule Winograd convolution for Bifrost\"\"\"\n\n    # Get ops and tensors\n    output = op.output(0)\n\n    Y = op.input_tensors[0]\n    M, A = s[Y].op.input_tensors\n    U_3D, V = s[M].op.input_tensors\n    U = s[U_3D].op.input_tensors[0]\n    d, B = s[V].op.input_tensors\n    data_pad = s[d].op.input_tensors[0]\n\n    if isinstance(U.op, tvm.te.ComputeOp):\n        padded_kernel, G = s[U].op.input_tensors\n        kernel = s[padded_kernel].op.input_tensors[0]\n        s[G].compute_inline()\n        eps, _, _, _ = s[U].op.axis\n        y, _, _, _ = s[padded_kernel].op.axis\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            # Pad kernel\n            y, x, ky, kx = s[padded_kernel].op.axis\n            s[padded_kernel].unroll(ky)\n            s[padded_kernel].unroll(kx)\n            tile_and_bind(s, padded_kernel, y, x, 1, 8)\n\n            # Transform kernel\n            eps, nu, k, c = s[U].op.axis\n            s[U].reorder(k, c, eps, nu)\n            r_kh, r_kw = s[U].op.reduce_axis\n            _ = [s[U].unroll(x) for x in [eps, nu, r_kh, r_kw]]\n\n            yo, xo, yi, xi = tile_and_bind(s, U, k, c, 1, 4)\n\n        # Dilation\n        if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n            s[kernel].compute_inline()\n\n    # Pad data\n    s[data_pad].compute_inline()\n\n    # Pack data\n    n, c, h, w = s[d].op.axis\n    w, wi = s[d].split(w, 4)\n    s[d].unroll(wi)\n    b = s[d].fuse(n, c)\n    tile_and_bind3d(s, d, b, h, w, 1, 4, 2)\n\n    # Transform data\n    bIL_d = s.cache_read(d, \"local\", [V])\n\n    s[B].compute_inline()\n    epsnu, c, b = s[V].op.axis\n    r_eps, r_nu = s[V].op.reduce_axis\n    s[V].reorder(b, c, epsnu, r_nu, r_eps)\n    _ = [s[V].unroll(x) for x in [epsnu, r_eps, r_nu]]\n    yo, xo, yi, xi = tile_and_bind(\n        s, V, b, c, cfg[\"data_transform_wgy\"].val, cfg[\"data_transform_wgx\"].val\n    )\n\n    s[bIL_d].compute_at(s[V], xi)\n    n, c, h, w = s[bIL_d].op.axis\n    s[bIL_d].unroll(h)\n    s[bIL_d].vectorize(w)\n\n    # Batched GEMM\n    # Inline the 4D -> 3D tensor transform on the kernel\n    s[U_3D].compute_inline()\n    U_transform, V_transform = schedule_gemm(\n        cfg, s, U_3D, V, M, batched=True, schedule_transforms=True\n    )\n\n    # Inverse transform\n    CR_M = s.cache_read(M, \"local\", [Y])\n    CW_Y = s.cache_write(Y, \"local\")\n\n    s[A].compute_inline()\n    k, b, vh, vw = s[Y].op.axis\n    fused = s[Y].fuse(vh, vw)\n    s[Y].vectorize(fused)\n    yo, xo, yi, xi = tile_and_bind(s, Y, k, b, 1, 4)\n\n    s[CR_M].compute_at(s[Y], xi)\n    k, b, epsnu = s[CR_M].op.axis\n    s[CR_M].unroll(k)\n\n    s[CW_Y].compute_at(s[Y], xi)\n    k, b, vh, vw = s[CW_Y].op.axis\n    r_eps, r_nu = s[CW_Y].op.reduce_axis\n    _ = [s[CW_Y].unroll(x) for x in [vh, vw, r_eps, r_nu]]\n\n    # Schedule output and fusion\n    if output.op not in s.outputs:\n        s[output].compute_inline()\n        output = s.outputs[0]\n\n    _, k, h, w = s[output].op.axis\n    tile_and_bind3d(s, output, k, h, w, 1, 2, 2)\n\n\n##### REGISTER ALTER OP LAYOUT #####\n@nn.conv2d_alter_layout.register(\"bifrost\")\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n\n    _, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n    if workload is None:\n        # The best implementation is not an AutoTVM template,\n        # we then assume it's not necessary to alter this op.\n        return None\n    cfg = dispatch_ctx.query(target, workload)\n    if cfg.is_fallback:  # if is fallback, clear query cache and return None\n        autotvm.task.clear_fallback_cache(target, workload)\n        return None\n\n    topi_tmpl = workload[0]\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    strides = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data, kernel = tinfos\n    out_dtype = out_type.dtype\n\n    idxd = tvm.tir.indexdiv\n\n    if topi_tmpl == \"conv2d_nchw_spatial_pack.bifrost\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        VC = cfg[\"tile_co\"].size[-1]\n\n        new_attrs[\"kernel_layout\"] = \"OIHW%do\" % VC\n\n        new_data = data\n        new_kernel = te.placeholder((idxd(CO, VC), CI, KH, KW, VC), dtype=kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_spatial_pack.bifrost\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_nchw_winograd.bifrost\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        tile_size = 2\n\n        weight_expr = inputs[1]\n        weight_expr = relay.nn.contrib_conv2d_winograd_weight_transform(\n            weight_expr, tile_size=tile_size\n        )\n        weight_expr = relay.reshape(\n            weight_expr, newshape=(KH + tile_size - 1, KW + tile_size - 1, CO, CI)\n        )\n\n        new_attrs[\"tile_size\"] = tile_size\n\n        new_data = data\n        new_kernel = te.placeholder((KH + tile_size - 1, KW + tile_size - 1, CO, CI), kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_winograd.bifrost\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight_expr, **new_attrs\n        )\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable\n\"\"\"dense schedule on ARM Mali Biforst GPU\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline\n\n\n@autotvm.register_topi_compute(\"dense.bifrost\")\ndef dense(_, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator on Biforst\"\"\"\n    return nn.dense(data, weight, bias, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"dense.bifrost\")\ndef schedule_dense(cfg, outs):\n    \"\"\"Schedule for dense operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config entity for this template\n    outs: Array of Tensor\n        The computation graph description of dense\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for dense.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"dense\":\n            vec_size = [1, 2, 4, 8, 16]\n            max_unroll = 32\n\n            dense_out = op.output(0)\n            output = outs[0]\n\n            y, x = s[output].op.axis\n            c = s[dense_out].op.reduce_axis[0]\n\n            ##### space definition begin #####\n            cfg.define_split(\"tile_y\", y, num_outputs=3)\n            cfg.define_split(\"tile_x\", x, num_outputs=3)\n            cfg.define_split(\"c_unroll\", c, num_outputs=2, max_factor=64)\n\n            # fallback support\n            if cfg.is_fallback:\n                ref_log = autotvm.tophub.load_reference_log(\"mali\", \"rk3399\", \"dense.bifrost\")\n                cfg.fallback_with_reference_log(ref_log)\n            ##### space definition end #####\n\n            if dense_out.op in s.outputs:\n                dense_out = s.cache_write(output, \"local\")\n\n            by, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n            bx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            if cfg[\"tile_y\"].size[-1] < max_unroll:\n                s[output].unroll(yi)\n            if cfg[\"tile_x\"].size[-1] in vec_size:\n                s[output].vectorize(xi)\n            s[dense_out].compute_at(s[output], tx)\n\n            k = s[dense_out].op.reduce_axis[0]\n            y, x = s[dense_out].op.axis\n            k, k_unroll = cfg[\"c_unroll\"].apply(s, dense_out, k)\n            s[dense_out].reorder(k, k_unroll, y, x)\n            s[dense_out].unroll(k_unroll)\n            if cfg[\"tile_y\"].size[-1] < max_unroll:\n                s[dense_out].unroll(y)\n            if cfg[\"tile_x\"].size[-1] in vec_size:\n                s[dense_out].vectorize(x)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef fuse_and_bind(s, tensor, axis=None, num_thread=None):\n    \"\"\"fuse all the axis and bind to GPU threads\"\"\"\n    axis = axis or s[tensor].op.axis\n    fused = s[tensor].fuse(*axis)\n    bx, tx = s[tensor].split(fused, num_thread)\n    s[tensor].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    return bx, tx\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"depthwise_conv2d schedule on ARM Mali GPU\"\"\"\n\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\n\nfrom .. import utils\nfrom .. import tag\n\n\ndef schedule_depthwise_conv2d_nchw(outs):\n    \"\"\"Schedule for depthwise_conv2d nchw forward.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(pad_data, kernel, conv):\n        raw_data = s[pad_data].op.input_tensors[0]\n\n        if conv.op not in s.outputs:  # has bias or relu\n            output = outs[0]\n        else:  # no bias or relu\n            output = conv\n\n        def tile_and_bind3d(tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None):\n            \"\"\"tile and bind 3d\"\"\"\n            y_factor = y_factor or z_factor\n            x_factor = x_factor or y_factor\n            zo, zi = s[tensor].split(z, z_factor)\n            yo, yi = s[tensor].split(y, y_factor)\n            xo, xi = s[tensor].split(x, x_factor)\n            s[tensor].bind(zo, te.thread_axis(\"blockIdx.z\"))\n            s[tensor].bind(zi, te.thread_axis(\"threadIdx.z\"))\n            s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n            s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n            s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n            s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n            return zo, zi, yo, yi, xo, xi\n\n        # set tunable parameters\n        VH = 1\n        VW = 1\n        num_thread = 4\n        while utils.get_const_int(conv.shape[3]) % (VW * 2) == 0 and VW * 2 <= 4:\n            VW = VW * 2\n        while utils.get_const_int(conv.shape[2]) % (VH * 2) == 0 and VH * 2 <= 2:\n            VH = VH * 2\n        if raw_data.dtype == \"float16\":\n            if utils.get_const_int(conv.shape[3]) % (VW * 2) == 0:\n                VW *= 2\n                num_thread *= 2\n            else:\n                num_thread *= 2\n\n        # schedule padding\n        _, c, y, x = s[pad_data].op.axis\n        tile_and_bind3d(pad_data, c, y, x, num_thread, 1, 1)\n\n        # schedule conv\n        di, dj = s[conv].op.reduce_axis\n        s[conv].unroll(di)\n        s[conv].unroll(dj)\n\n        _, c, y, x = s[output].op.axis\n        y, x, yi, xi = s[output].tile(y, x, VH, VW)\n        s[output].unroll(yi)\n        s[output].vectorize(xi)\n\n        _, _, _, _, _, ji = tile_and_bind3d(output, c, y, x, num_thread, 1, 1)\n\n        if conv.op not in s.outputs:\n            _, c, y, x = s[conv].op.axis\n            y, x, yi, xi = s[conv].tile(y, x, VH, VW)\n            s[conv].unroll(yi)\n            s[conv].vectorize(xi)\n            s[conv].compute_at(s[output], ji)\n\n    def traverse(op):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if tensor.op.input_tensors:\n                    traverse(tensor.op)\n\n        # schedule depthwise_conv2d\n        if op.tag == \"depthwise_conv2d_nchw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            conv = op.output(0)\n            _schedule(pad_data, kernel, conv)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"GEMM schedules for Mali Bifrost\"\"\"\nfrom tvm import te\n\nfrom .transforms import tile_and_bind, tile_and_bind3d, interleave_transpose, transpose_interleave\nfrom .. import utils\n\n\ndef decl_gemm(cfg, A, B):\n    \"\"\"Declare a single GEMM computation for Mali Bifrost GPUs\n\n    Parameters\n    ----------\n    cfg : Config\n        Schedule configuration\n\n    A : tvm.te.Tensor\n        2D Tensor, shape [n, k]\n\n    B : tvm.te.Tensor\n        2D Tensor, shape [k, m]\n\n    Returns\n    -------\n    C : tvm.te.Tensor\n        2D Tensor, shape [n, m]\n    \"\"\"\n\n    cfg.define_knob(\"work_group_x\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n    cfg.define_knob(\"work_group_y\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n    cfg.define_knob(\"unroll_k_factor\", [1, 2, 4])\n    cfg.define_knob(\"A_interleave\", [1, 4, 8, 16, 24, 32, 48, 64])\n    cfg.define_knob(\"B_interleave\", [1, 4, 8, 16, 32])\n    cfg.define_knob(\"split_k_factor\", [1, 4, 16])\n\n    # Mutual k axis must be of equal extent\n    assert utils.get_const_int(A.shape[1]) == utils.get_const_int(B.shape[0])\n    n = A.shape[0]\n    m = B.shape[1]\n    k_size = utils.get_const_int(A.shape[1])\n    unroll_gemm = cfg[\"split_k_factor\"].val\n    if unroll_gemm == 1:\n        # No unrolling case must have the same set of tensors to keep scheduling consistent\n        # Create identity tensors to take the place of A_unrolled, B_unrolled and R\n        A_unrolled = te.compute((n, k_size), lambda i, j: A[i, j], name=\"A_unrolled\")\n        B_unrolled = te.compute((k_size, m), lambda i, j: B[i, j], name=\"B_unrolled\")\n\n        # Declare standard GEMM\n        k = te.reduce_axis((0, A.shape[1]), name=\"k\")\n        C = te.compute(\n            (n, m), lambda i, j: te.sum(A_unrolled[i, k] * B_unrolled[k, j], axis=k), name=\"C\"\n        )\n\n        R = te.compute((n, m), lambda i, j: C[i, j], name=\"R\")\n\n    else:\n        unrolled_k_size = k_size // unroll_gemm\n\n        # Unroll the two input matrices along the shared k axis\n        A_unrolled = te.compute(\n            (unroll_gemm, n, unrolled_k_size),\n            lambda b, i, j: A[i][unrolled_k_size * b + j],\n            name=\"A_unrolled\",\n        )\n\n        B_unrolled = te.compute(\n            (unroll_gemm, unrolled_k_size, m),\n            lambda b, i, j: B[unrolled_k_size * b + i][j],\n            name=\"B_unrolled\",\n        )\n\n        # Declare a batched GEMM\n        k = te.reduce_axis((0, unrolled_k_size), name=\"k\")\n        C = te.compute(\n            (unroll_gemm, n, m),\n            lambda b, i, j: te.sum(A_unrolled[b][i][k] * B_unrolled[b][k][j], axis=k),\n            name=\"C\",\n        )\n\n        # Then declare a reduction to reduce the sub matrices\n        k = te.reduce_axis((0, unroll_gemm), name=\"k\")\n        R = te.compute((n, m), lambda i, j: te.sum(C[k][i][j], axis=k), name=\"R\")\n\n    return R\n\n\ndef decl_batched_gemm(cfg, A, B):\n    \"\"\"Declare a batched GEMM computation for Mali Bifrost GPUs\n    Parameters\n    ----------\n    cfg : Config\n        Schedule configuration\n\n    A : tvm.te.Tensor\n        3D Tensor, shape [b, n, k]\n\n    B : tvm.te.Tensor\n        3D Tensor, shape [b, k, m]\n\n    Returns\n    -------\n    C : tvm.te.Tensor\n        3D Tensor, shape [b, n, m]\n\n    \"\"\"\n    # Mutual b and k axis must be of equal extent\n    assert utils.get_const_int(A.shape[2]) == utils.get_const_int(B.shape[1])\n    assert utils.get_const_int(A.shape[0]) == utils.get_const_int(B.shape[0])\n\n    cfg.define_knob(\"work_group_x\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n    cfg.define_knob(\"work_group_y\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n    cfg.define_knob(\"unroll_k_factor\", [1, 2, 4])\n    cfg.define_knob(\"A_interleave\", [1, 4, 8, 16, 32, 64])\n    cfg.define_knob(\"B_interleave\", [1, 4, 8, 16, 32])\n\n    n = A.shape[1]\n    m = B.shape[2]\n    k_size = utils.get_const_int(A.shape[2])\n    b_size = utils.get_const_int(A.shape[0])\n\n    # Declare a batched GEMM\n    k = te.reduce_axis((0, k_size), name=\"k\")\n    C = te.compute(\n        (b_size, n, m), lambda b, i, j: te.sum(A[b][i][k] * B[b][k][j], axis=k), name=\"C\"\n    )\n\n    return C\n\n\ndef decl_winograd_gemm(cfg, A, B):\n    \"\"\"Declare a winograd GEMM for Mali Bifrost GPUs\n    Winograd uses batched GEMM, however the input tensors are 4D\n    This wraps decl_batched_gemm to provide it with 3D tensors\n\n    Parameters\n    ----------\n    cfg : Config\n        Schedule configuration\n\n    A : tvm.te.Tensor\n        4D Tensor, shape [a, a, n, k]\n\n    B : tvm.te.Tensor\n        4D Tensor, shape [a * a, k, m]\n\n    Returns\n    -------\n\n    \"\"\"\n    alpha = utils.get_const_int(A.shape[0])\n    n = utils.get_const_int(A.shape[2])\n    k = utils.get_const_int(A.shape[3])\n\n    A_3D = te.compute(\n        (alpha * alpha, n, k), lambda b, i, j: A[b // alpha][b % alpha][i][j], name=\"A_3D\"\n    )\n\n    C = decl_batched_gemm(cfg, A_3D, B)\n    return A_3D, C\n\n\ndef schedule_gemm(cfg, s, A, B, C, batched=False, schedule_transforms=True):\n    \"\"\"Schedule GEMM, single and batched\n\n    Parameters\n    ----------\n    cfg : Config\n        Schedule configuration\n\n    s : tvm.te.schedule.Schedule\n        Operator schedule\n\n    A : tvm.te.Tensor\n        2D/3D Tensor, shape [n, k]/[b, n, k]\n\n    B : tvm.te.Tensor\n        2D/3D Tensor, shape [k, m]/[b, k, m]\n\n    C : tvm.te.Tensor\n        2D/3D Tensor, shape [n, m]/[b, n, m]\n\n    batched : bool\n        Whether the GEMM is batched\n\n    Returns\n    -------\n\n    \"\"\"\n    block_size_x = 4\n    block_size_y = 4\n    warp_size_x = 2\n    warp_size_y = 2\n\n    work_group_x = cfg[\"work_group_x\"].val\n    work_group_y = cfg[\"work_group_y\"].val\n    k_unroll = cfg[\"unroll_k_factor\"].val\n\n    if not batched:\n        y_index, x_index = (0, 1)\n    else:\n        y_index, x_index = (1, 2)\n\n    trans_inter, A_transposed_interleaved = transpose_interleave(\n        s, A, cfg[\"A_interleave\"].val, y_index, x_index, [C], batched=batched\n    )\n    inter_trans, B_interleaved_transposed = interleave_transpose(\n        s, B, cfg[\"B_interleave\"].val, y_index, x_index, [C], batched=batched\n    )\n\n    if schedule_transforms:\n        # Schedule A\n        y, x = s[trans_inter].op.axis\n        y, x, yi, xi = s[trans_inter].tile(y, x, 1, 8)\n        s[trans_inter].unroll(yi)\n        s[trans_inter].unroll(xi)\n        tile_and_bind(s, trans_inter, y, x, 1, 4)\n\n        # Schedule B\n        y, x = s[inter_trans].op.axis\n        xo, xi = s[inter_trans].split(x, 4)\n        s[inter_trans].vectorize(xi)\n        tile_and_bind(s, inter_trans, y, xo, 4, 4)\n\n    # Schedule C\n    CR_A = s.cache_read(A_transposed_interleaved, \"local\", [C])\n    CR_B = s.cache_read(B_interleaved_transposed, \"local\", [C])\n    CW_C = s.cache_write(C, \"local\")\n\n    if not batched:\n        y, x = s[C].op.axis\n    else:\n        z, y, x = s[C].op.axis\n    y, x, yt, xt = s[C].tile(y, x, block_size_y, block_size_x)\n    s[C].unroll(yt)\n    s[C].vectorize(xt)\n    # Tile the global work space to generate 'square' warps -> 2x2 for warp size of 4\n    y, x, wy, wx = s[C].tile(y, x, warp_size_y, warp_size_x)\n    x = s[C].fuse(x, wy, wx)\n    if not batched:\n        yo, xo, yi, xi = tile_and_bind(s, C, y, x, work_group_y, work_group_x)\n    else:\n        # For batched GEMM bind batch to z axis\n        zo, yo, xo, zi, yi, xi = tile_and_bind3d(s, C, z, y, x, 1, work_group_y, work_group_x)\n\n    s[CW_C].compute_at(s[C], xi)\n    if not batched:\n        y, x = s[CW_C].op.axis\n    else:\n        _, y, x = s[CW_C].op.axis\n    y, x, yt, xt = s[CW_C].tile(y, x, block_size_y, block_size_x)\n    k = s[CW_C].op.reduce_axis[0]\n    s[CW_C].reorder(k, yt, xt)\n    ko, ki = s[CW_C].split(k, k_unroll)\n    s[CW_C].unroll(ki)\n    s[CW_C].unroll(yt)\n    s[CW_C].unroll(xt)\n\n    if not batched:\n        i, j = s[CR_A].op.axis\n    else:\n        _, i, j = s[CR_A].op.axis\n    s[CR_A].reorder(j, i)\n    s[CR_A].compute_at(s[CW_C], ki)\n    s[CR_A].unroll(j)\n    s[CR_A].vectorize(i)\n\n    if not batched:\n        i, j = s[CR_B].op.axis\n    else:\n        _, i, j = s[CR_B].op.axis\n    s[CR_B].compute_at(s[CW_C], ki)\n    s[CR_B].unroll(i)\n    s[CR_B].vectorize(j)\n\n    return trans_inter, inter_trans\n\n\ndef schedule_unrollable_gemm(cfg, s, A, B, C, R):\n    \"\"\"Schedule a GEMM that can be unrolled by a constant factor\n    along its inner dimension\n\n    Parameters\n    ----------\n    cfg : Config\n        Schedule configuration\n\n    s : tvm.te.schedule.Schedule\n        Operator schedule\n\n    A : tvm.te.Tensor\n        2D/3D Tensor, shape [n, k]/[b, n, k]\n\n    B : tvm.te.Tensor\n        2D/3D Tensor, shape [k, m]/[b, k, m]\n\n    C : tvm.te.Tensor\n        2D/3D Tensor, shape [n, m]/[b, n, m]\n\n    R : tvm.te.Tensor\n        2D Tensor, shape [n, m]\n\n    \"\"\"\n    # If the GEMM is 2D, no unrolling has taken place\n    # Use non-batched GEMM schedule and inline identity matrices A, B and R\n    if len(C.op.axis) == 2:\n        s[A].compute_inline()\n        s[B].compute_inline()\n        schedule_gemm(cfg, s, A, B, C)\n        s[R].compute_inline()\n\n    # GEMM is 3D, use batched GEMM schedule, inline A and B and schedule R\n    else:\n        s[A].compute_inline()\n        s[B].compute_inline()\n        schedule_gemm(cfg, s, A, B, C, batched=True)\n\n        CR_C = s.cache_read(C, \"local\", [R])\n\n        y, x = s[R].op.axis\n        xo, xi = s[R].split(x, 4)\n        k = s[R].op.reduce_axis[0]\n        s[R].reorder(k, xi)\n        ko, ki = s[R].split(k, 4)\n        s[R].unroll(xi)\n        s[R].unroll(ki)\n        tile_and_bind(s, R, y, xo, 1, 2)\n\n        s[CR_C].compute_at(s[R], ko)\n        _, y, x = s[CR_C].op.axis\n        s[CR_C].unroll(y)\n        s[CR_C].vectorize(x)\n\n\ndef get_unrollable_gemm_ops(R):\n    \"\"\"Get all GEMM operators from the final reduction\n    This is a helper function to more easily get all the GEMM operations\n    from an operator\n\n    Parameters\n    ----------\n    R : tvm.te.Tensor\n        Reduced tensor, final stage of GEMM\n\n    Returns\n    -------\n    A_unrolled : tvm.te.Tensor\n        Matrix A unrolled along k\n\n    B_unrolled: tvm.te.Tensor\n        Matrix B unrolled along k\n\n    C : tvm.te.Tensor\n        Result of batched GEMM\n\n    R : tvm.te.Tensor\n        Reduction of C, result of unrollable GEMM\n\n    \"\"\"\n    C = R.op.input_tensors[0]\n    A_unrolled, B_unrolled = C.op.input_tensors\n    return A_unrolled, B_unrolled, C, R\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/bifrost/transforms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Utility scheduling functions for the Bifrost schedules\"\"\"\n\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\n\n\ndef fuse_and_bind(s, tensor, axis=None, num_thread=None):\n    \"\"\"Fuse all the axis and bind to GPU threads\"\"\"\n    axis = axis or s[tensor].op.axis\n    fused = s[tensor].fuse(*axis)\n    max_threads = tvm.target.Target.current(allow_none=False).max_num_threads\n    bx, tx = s[tensor].split(fused, num_thread or max_threads)\n    s[tensor].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    return bx, tx\n\n\ndef tile_and_bind(s, tensor, y, x, y_factor, x_factor=None):\n    \"\"\"Tile and bind to GPU threads\"\"\"\n    x_factor = x_factor or y_factor\n    yo, xo, yi, xi = s[tensor].tile(y, x, y_factor, x_factor)\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n    return yo, xo, yi, xi\n\n\ndef tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None):\n    \"\"\"Tile and bind 3d\"\"\"\n    y_factor = y_factor or z_factor\n    x_factor = x_factor or y_factor\n    zo, zi = s[tensor].split(z, z_factor)\n    yo, yi = s[tensor].split(y, y_factor)\n    xo, xi = s[tensor].split(x, x_factor)\n    s[tensor].bind(zo, te.thread_axis(\"blockIdx.z\"))\n    s[tensor].bind(zi, te.thread_axis(\"threadIdx.z\"))\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    return zo, yo, xo, zi, yi, xi\n\n\ndef pack_tensor(s, tensor, factor, readers):\n    \"\"\"Do transform X[n, m] -> X[n / factor, m, factor]\"\"\"\n    tmp = s.cache_read(tensor, \"global\", readers)\n    y, x = s[tmp].op.axis\n    yo, yi = s[tmp].split(y, factor)\n    s[tmp].reorder(yo, x, yi)\n    s[tmp].compute_inline()\n    return s.cache_write(tmp, \"global\"), tmp\n\n\ndef transpose(s, tensor, y_index, x_index, readers):\n    \"\"\"Do transform X[n, m] -> X[m, n]\"\"\"\n    tmp = s.cache_read(tensor, \"global\", readers)\n    y, x = s[tmp].op.axis[y_index], s[tmp].op.axis[x_index]\n    s[tmp].reorder(x, y)\n    s[tmp].compute_inline()\n    A_transpose = s.cache_write(tmp, \"global\")\n\n    CR_A = s.cache_read(tensor, \"local\", [A_transpose])\n    CW_A_transpose = s.cache_write(A_transpose, \"local\")\n\n    y, x = s[A_transpose].op.axis[y_index], s[A_transpose].op.axis[x_index]\n    yo, xo, yi, xi = s[A_transpose].tile(y, x, 4, 4)\n    s[A_transpose].unroll(yi)\n    s[A_transpose].vectorize(xi)\n    _, _, _, xi = tile_and_bind(s, A_transpose, yo, xo, 32, 2)\n\n    s[CW_A_transpose].compute_at(s[A_transpose], xi)\n    y, x = s[CW_A_transpose].op.axis[y_index], s[CW_A_transpose].op.axis[x_index]\n    s[CW_A_transpose].unroll(x)\n    s[CW_A_transpose].unroll(y)\n\n    s[CR_A].compute_at(s[A_transpose], xi)\n    y, x = s[CR_A].op.axis[y_index], s[CR_A].op.axis[x_index]\n    s[CR_A].unroll(y)\n    s[CR_A].vectorize(x)\n\n    return tmp\n\n\ndef interleave_transpose(s, tensor, width, y_index, x_index, readers, batched=False):\n    \"\"\"Interleave the tensor, then transpose it\"\"\"\n    tmp = s.cache_read(tensor, \"global\", readers)\n    y, x = s[tmp].op.axis[y_index], s[tmp].op.axis[x_index]\n    xo, xi = s[tmp].split(x, width)\n    s[tmp].reorder(xo, y, xi)\n    s[tmp].fuse(y, xi)\n    if batched:\n        z = s[tmp].op.axis[0]\n        s[tmp].fuse(z, xo)\n    s[tmp].compute_inline()\n    return s.cache_write(tmp, \"global\"), tmp\n\n\ndef transpose_interleave(s, tensor, width, y_index, x_index, readers, batched=False):\n    \"\"\"Transpose the tensor, then interleave it\"\"\"\n    tmp = s.cache_read(tensor, \"global\", readers)\n    y, x = s[tmp].op.axis[y_index], s[tmp].op.axis[x_index]\n    yo, yi = s[tmp].split(y, width)\n    s[tmp].reorder(yo, x, yi)\n    s[tmp].fuse(x, yi)\n    if batched:\n        z = s[tmp].op.axis[0]\n        s[tmp].fuse(z, yo)\n    s[tmp].compute_inline()\n    return s.cache_write(tmp, \"global\"), tmp\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/broadcast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Broadcast operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom . import cpp as _cpp\n\n\ndef broadcast_to(data, shape):\n    \"\"\"Broadcast the src to the target shape\n\n    We follows the numpy broadcasting rule.\n    See also https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data\n\n    shape : list or tuple\n        The target shape to be broadcasted.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return _cpp.broadcast_to(data, shape)\n\n\ndef add(lhs, rhs):\n    \"\"\"Addition with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.add(lhs, rhs)\n\n\ndef subtract(lhs, rhs):\n    \"\"\"Subtraction with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.subtract(lhs, rhs)\n\n\ndef multiply(lhs, rhs):\n    \"\"\"Multiplication with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.multiply(lhs, rhs)\n\n\ndef divide(lhs, rhs):\n    \"\"\"Division with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.divide(lhs, rhs)\n\n\ndef floor_divide(lhs, rhs):\n    \"\"\"Floor division with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.floor_divide(lhs, rhs)\n\n\ndef mod(lhs, rhs):\n    \"\"\"Modulus with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.mod(lhs, rhs)\n\n\ndef floor_mod(lhs, rhs):\n    \"\"\"Floor modulus with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.floor_mod(lhs, rhs)\n\n\ndef maximum(lhs, rhs):\n    \"\"\"Take element-wise maximum of two tensors with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.maximum(lhs, rhs)\n\n\ndef minimum(lhs, rhs):\n    \"\"\"Take element-wise maximum of two tensors with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.minimum(lhs, rhs)\n\n\ndef power(lhs, rhs):\n    \"\"\"Power with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.power(lhs, rhs)\n\n\ndef left_shift(lhs, rhs):\n    \"\"\"Left shift with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.left_shift(lhs, rhs)\n\n\ndef right_shift(lhs, rhs):\n    \"\"\"Right shift with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.right_shift(lhs, rhs)\n\n\ndef greater(lhs, rhs):\n    \"\"\"Compute (lhs>rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.greater(lhs, rhs)\n\n\ndef less(lhs, rhs):\n    \"\"\"Compute (lhs<rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.less(lhs, rhs)\n\n\ndef equal(lhs, rhs):\n    \"\"\"Compute (lhs==rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.equal(lhs, rhs)\n\n\ndef not_equal(lhs, rhs):\n    \"\"\"Compute (lhs!=rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.not_equal(lhs, rhs)\n\n\ndef greater_equal(lhs, rhs):\n    \"\"\"Compute (lhs>=rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.greater_equal(lhs, rhs)\n\n\ndef less_equal(lhs, rhs):\n    \"\"\"Compute (lhs<=rhs) with auto-broadcasting\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n        The left operand\n    rhs : tvm.te.Tensor or Expr\n        The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n        Returns Expr if both operands are Expr.\n        Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.less_equal(lhs, rhs)\n\n\ndef logical_and(lhs, rhs):\n    \"\"\"Compute element-wise logical and of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.logical_and(lhs, rhs)\n\n\ndef logical_or(lhs, rhs):\n    \"\"\"Compute element-wise logical or of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.logical_or(lhs, rhs)\n\n\ndef logical_xor(lhs, rhs):\n    \"\"\"Compute element-wise logical xor of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.logical_xor(lhs, rhs)\n\n\ndef bitwise_and(lhs, rhs):\n    \"\"\"Compute element-wise bitwise and of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.bitwise_and(lhs, rhs)\n\n\ndef bitwise_or(lhs, rhs):\n    \"\"\"Compute element-wise bitwise or of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.bitwise_or(lhs, rhs)\n\n\ndef bitwise_xor(lhs, rhs):\n    \"\"\"Compute element-wise bitwise xor of data.\n\n    Parameters\n    ----------\n    lhs : tvm.te.Tensor or Expr\n          The left operand\n    rhs : tvm.te.Tensor or Expr\n          The right operand\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if both operands are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.bitwise_xor(lhs, rhs)\n\n\ndef logical_not(data):\n    \"\"\"Compute element-wise logical not of data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or Expr\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if the operand are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.logical_not(data)\n\n\ndef bitwise_not(data):\n    \"\"\"Compute element-wise bitwise not of data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or Expr\n\n    Returns\n    -------\n    ret : tvm.te.Tensor or Expr\n          Returns Expr if the operand are Expr.\n          Otherwise returns Tensor.\n    \"\"\"\n    return _cpp.bitwise_not(data)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"FFI for C++ TOPI ops and schedules\"\"\"\nfrom .impl import *  # pylint: disable=wildcard-import\nfrom . import cuda\nfrom . import nn\nfrom . import vision\nfrom . import x86\nfrom . import generic\nfrom . import rocm\nfrom . import utils\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for CUDA TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.cuda\", \"tvm.topi.cpp.cuda\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/generic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for generic TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.generic\", \"tvm.topi.cpp.generic\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/impl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Load Lib for C++ TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi\", \"tvm.topi.cpp\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for NN TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.nn\", \"tvm.topi.cpp.nn\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/rocm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for Rocm TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.rocm\", \"tvm.topi.cpp.rocm\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for TOPI utility functions\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.utils\", \"tvm.topi.cpp.utils\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/vision/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"FFI for vision TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\nfrom . import yolo\n\ntvm._ffi._init_api(\"topi.vision\", \"tvm.topi.cpp.vision\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/vision/yolo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for Yolo TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.vision.yolo\", \"tvm.topi.cpp.vision.yolo\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cpp/x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"FFI for x86 TOPI ops and schedules\"\"\"\nimport tvm._ffi\n\ntvm._ffi._init_api(\"topi.x86\", \"tvm.topi.cpp.x86\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"CUDA specific declaration and schedules.\"\"\"\nfrom .conv1d import *\nfrom .conv1d_transpose_ncw import *\nfrom .conv2d import *\nfrom .conv2d_hwcn import *\nfrom .conv2d_int8 import *\nfrom .conv2d_winograd import *\nfrom .conv2d_nhwc_winograd import *\nfrom .depthwise_conv2d import *\nfrom .group_conv2d_nchw import *\nfrom . import conv2d_alter_op\nfrom .conv2d_transpose import *\nfrom .conv3d_transpose_ncdhw import *\nfrom .deformable_conv2d import *\nfrom .conv3d import *\nfrom .conv3d_winograd import *\nfrom . import conv3d_alter_op\nfrom .reduction import schedule_reduce\nfrom .softmax import *\nfrom .injective import schedule_injective, schedule_elemwise, schedule_broadcast\nfrom .dense import *\nfrom .pooling import *\nfrom .nn import schedule_lrn\nfrom .batch_matmul import *\nfrom .batch_matmul_tensorcore import *\nfrom .vision import *\nfrom .ssd import *\nfrom .nms import get_valid_counts, non_max_suppression, all_class_non_max_suppression\nfrom .rcnn import *\nfrom .scatter import *\nfrom .sort import *\nfrom .conv2d_nhwc_tensorcore import *\nfrom .conv3d_ndhwc_tensorcore import *\nfrom .dense_tensorcore import *\nfrom .conv2d_hwnc_tensorcore import *\nfrom .correlation import *\nfrom .sparse import *\nfrom . import tensorcore_alter_op\nfrom .argwhere import *\nfrom .scan import *\nfrom .sparse_reshape import *\nfrom .transform import *\nfrom .unique import *\nfrom .searchsorted import *\nfrom .stft import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/argwhere.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-arguments, invalid-name\n\"\"\"Argwhere operator\"\"\"\n\nimport logging\n\nimport tvm\nfrom tvm import te\nfrom .injective import schedule_injective_from_existing\nfrom .scan import exclusive_scan\nfrom .. import tag\nfrom ..utils import ceil_div, prod\nfrom ..transform import reshape\nfrom ..broadcast import not_equal\nfrom ..math import cast\n\n\nlogger = logging.getLogger(\"topi\")\n\nfdiv = tvm.tir.floordiv\nfmod = tvm.tir.floormod\n\n\ndef compact_nonzero_indices_ir(condition, write_indices, out, do_write_func):\n    \"\"\"Copy nonzero indices to the corresponding write locations.\n\n    Parameters\n    ----------\n    condition : Buffer\n        The input condition.\n\n    write_indices : Buffer\n        The result of exclusive scan on a boolean array, where True indicates that\n        the condition is non zero at that position.\n\n    out : Buffer\n        The output buffer to copy indices to.\n\n    do_write_func : a function\n        A callback that accepts an output buffer, a dst index to write to, and a src index.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    ib = tvm.tir.ir_builder.create()\n    size_1d = prod(condition.shape)\n\n    condition = ib.buffer_ptr(condition)\n    write_indices = ib.buffer_ptr(write_indices)\n    out = ib.buffer_ptr(out)\n\n    nthread_tx = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_bx = ceil_div(size_1d, nthread_tx)\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n    with ib.new_scope():\n        idx = bx * nthread_tx + tx\n        with ib.if_scope(idx < size_1d):\n            with ib.if_scope(condition[idx] != 0):\n                do_write_func(out, write_indices[idx], idx)\n\n    return ib.get()\n\n\ndef argwhere_common(output_shape, condition, do_write_func):\n    \"\"\"A common compute used by argwhere of various ranks.\n\n    Parameters\n    ----------\n    output_shape : list of int or tvm.tir.Any\n        Tensor with output shape info.\n\n    condition : tvm.te.Tensor\n        The input condition.\n\n    do_write_func : a function\n        A callback that accepts an output buffer, a dst index to write to, and a src index.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n\n    flags = not_equal(condition, tvm.tir.const(0))\n    flags_1d = reshape(flags, (prod(flags.shape),))\n    write_indices = exclusive_scan(cast(flags_1d, dtype=\"int32\"))\n\n    condition_buf = tvm.tir.decl_buffer(\n        condition.shape, condition.dtype, \"data_buf\", data_alignment=8\n    )\n    write_indices_buf = tvm.tir.decl_buffer(\n        write_indices.shape, write_indices.dtype, \"write_indices_buf\", data_alignment=8\n    )\n    out_buf = tvm.tir.decl_buffer(output_shape, \"int32\", \"out_buf\", data_alignment=8)\n\n    out = te.extern(\n        [output_shape],\n        [condition, write_indices],\n        lambda ins, outs: compact_nonzero_indices_ir(ins[0], ins[1], outs[0], do_write_func),\n        dtype=[\"int32\"],\n        in_buffers=[condition_buf, write_indices_buf],\n        out_buffers=[out_buf],\n        name=\"argwhere\",\n        tag=\"argwhere_gpu\",\n    )\n\n    return out\n\n\ndef argwhere_1d(output_shape, condition):\n    \"\"\"Compute for argwhere 1D\n\n    Parameters\n    ----------\n    condition : list of int or tvm.tir.Any\n        The output shape\n\n    out : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def do_write(out, write_index, idx):\n        out[write_index] = idx\n\n    return argwhere_common(output_shape, condition, do_write)\n\n\ndef argwhere_2d(output_shape, condition):\n    \"\"\"Compute for argwhere 2D\n\n    Parameters\n    ----------\n    condition : list of int or tvm.tir.Any\n        The output shape\n\n    out : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def do_write(out, write_index, idx):\n        a1 = condition.shape[1]\n        out[write_index * 2] = tvm.tir.floordiv(idx, a1)\n        out[write_index * 2 + 1] = tvm.tir.floormod(idx, a1)\n\n    return argwhere_common(output_shape, condition, do_write)\n\n\ndef argwhere_3d(output_shape, condition):\n    \"\"\"Compute for argwhere 3D\n\n    Parameters\n    ----------\n    condition : list of int or tvm.tir.Any\n        The output shape\n\n    out : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def do_write(out, write_index, idx):\n        _, a1, a2 = condition.shape\n        s1 = a1 * a2\n        out[write_index * 3] = fdiv(idx, s1)\n        out[write_index * 3 + 1] = fdiv(fmod(idx, s1), a2)\n        out[write_index * 3 + 2] = fmod(idx, a2)\n\n    return argwhere_common(output_shape, condition, do_write)\n\n\ndef argwhere_4d(output_shape, condition):\n    \"\"\"Compute for argwhere 4D\n\n    Parameters\n    ----------\n    condition : list of int or tvm.tir.Any\n        The output shape\n\n    out : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def do_write(out, write_index, idx):\n        _, a1, a2, a3 = condition.shape\n        s1 = a2 * a3\n        s2 = a1 * s1\n        out[write_index * 4] = fdiv(idx, s2)\n        out[write_index * 4 + 1] = fdiv(fmod(idx, s2), s1)\n        out[write_index * 4 + 2] = fdiv(fmod(idx, s1), a3)\n        out[write_index * 4 + 3] = fmod(idx, a3)\n\n    return argwhere_common(output_shape, condition, do_write)\n\n\ndef argwhere_5d(output_shape, condition):\n    \"\"\"Compute for argwhere 5D\n\n    Parameters\n    ----------\n    condition : list of int or tvm.tir.Any\n        The output shape\n\n    out : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def do_write(out, write_index, idx):\n        _, a1, a2, a3, a4 = condition.shape\n        s1 = a3 * a4\n        s2 = a2 * s1\n        s3 = a1 * s2\n        out[write_index * 5] = fdiv(idx, s3)\n        out[write_index * 5 + 1] = fdiv(fmod(idx, s3), s2)\n        out[write_index * 5 + 2] = fdiv(fmod(idx, s2), s1)\n        out[write_index * 5 + 3] = fdiv(fmod(idx, s1), a4)\n        out[write_index * 5 + 4] = fmod(idx, a4)\n\n    return argwhere_common(output_shape, condition, do_write)\n\n\ndef argwhere(output_shape, condition):\n    \"\"\"Find the indices of elements of a tensor that are non-zero.\n\n    Parameters\n    ----------\n    output_shape : tvm.te.Tensor\n        Tensor with output shape info.\n\n    condition : tvm.te.Tensor\n        Tensor with boolean values.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Indices of non-zero elements.\n    \"\"\"\n    if len(condition.shape) == 1:\n        return argwhere_1d(output_shape.shape, condition)\n    if len(condition.shape) == 2:\n        return argwhere_2d(output_shape.shape, condition)\n    if len(condition.shape) == 3:\n        return argwhere_3d(output_shape.shape, condition)\n    if len(condition.shape) == 4:\n        return argwhere_4d(output_shape.shape, condition)\n    if len(condition.shape) == 5:\n        return argwhere_5d(output_shape.shape, condition)\n    raise ValueError(\"Argwhere does not support rank higher than 5\")\n\n\ndef schedule_argwhere(outs):\n    \"\"\"Schedule for argwhere on cuda.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of argwhere\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for argwhere\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        if tag.is_injective(op.tag):\n            schedule_injective_from_existing(s, op.output(0))\n        for tensor in op.input_tensors:\n            if tensor.op.input_tensors and tensor.op not in scheduled_ops:\n                traverse(tensor.op)\n        scheduled_ops.append(op)\n\n    for out in outs:\n        traverse(out.op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,unused-variable,unused-argument\n\"\"\"cuda batch_matmul operators\"\"\"\nimport tvm\nfrom tvm import autotvm\nfrom tvm import te\nfrom tvm.contrib import cublas\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\nfrom .. import nn, generic\nfrom ..utils import traverse_inline, get_const_tuple, get_max_power2_factor\nfrom .tensor_intrin import dp4a\n\n\n@autotvm.register_topi_compute(\"batch_matmul.cuda\")\ndef batch_matmul(cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True):\n    \"\"\"Compute batch matrix multiplication of `tensor_a` and `tensor_b`.\n\n    Both `tensor_a` and `tensor_b` can be transposed. For legacy reason, we use NT format\n    (transpose_a=False, transpose_b=True) by default.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file.\n\n    tensor_a : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    tensor_b : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    out_shape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    return nn.batch_matmul(\n        x,\n        y,\n        oshape=out_shape,\n        out_dtype=out_dtype,\n        transpose_a=transpose_a,\n        transpose_b=transpose_b,\n    )\n\n\n@autotvm.register_topi_schedule(\"batch_matmul.cuda\")\ndef schedule_batch_matmul(cfg, outs):\n    \"\"\"Schedule for batch_matmul\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of batch_matmul\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(cfg, op):\n        C = op.output(0)\n        A, B = s[C].op.input_tensors\n        if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A:\n            s[B].compute_inline()\n        _, M, N = get_const_tuple(C.shape)\n        AA = s.cache_read(A, \"shared\", [C])\n        AL = s.cache_read(AA, \"local\", [C])\n        BB = s.cache_read(B, \"shared\", [C])\n        BL = s.cache_read(BB, \"local\", [C])\n        CC = s.cache_write(C, \"local\")\n        if op not in s.outputs:\n            s[C].compute_inline()\n            C = s.outputs[0].output(0)\n\n        b, y, x = s[C].op.axis\n        (k,) = s[CC].op.reduce_axis\n\n        cfg.define_split(\"tile_y\", y, num_outputs=3)\n        cfg.define_split(\"tile_x\", x, num_outputs=3)\n        cfg.define_split(\"tile_k\", k, num_outputs=2)\n        cfg.define_knob(\"auto_unroll_max_step\", [8, 16, 32, 64])\n        target = tvm.target.Target.current()\n        if target.kind.name in [\"nvptx\", \"rocm\"]:\n            # llvm-based backends cannot do non-explicit unrolling\n            cfg.define_knob(\"unroll_explicit\", [1])\n        else:\n            cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n        if cfg.is_fallback:\n            y_bn = get_max_power2_factor(M, 64)\n            x_bn = get_max_power2_factor(N, 64)\n            y_nthreads = min(y_bn, 8)\n            x_nthreads = min(x_bn, 8)\n            cfg[\"tile_x\"] = SplitEntity([-1, x_nthreads, x_bn // x_nthreads])\n            cfg[\"tile_y\"] = SplitEntity([-1, y_nthreads, y_bn // y_nthreads])\n            cfg[\"tile_k\"] = SplitEntity([-1, 8])\n            cfg[\"auto_unroll_max_step\"] = OtherOptionEntity(16)\n\n        by, ty, yi = cfg[\"tile_y\"].apply(s, C, y)\n        bx, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n\n        thread_x = te.thread_axis(\"threadIdx.x\")\n        thread_y = te.thread_axis(\"threadIdx.y\")\n\n        s[C].reorder(b, by, bx, ty, tx, yi, xi)\n        s[C].bind(b, te.thread_axis(\"blockIdx.z\"))\n        s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n        s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[C].bind(ty, thread_y)\n        s[C].bind(tx, thread_x)\n        s[C].pragma(yi, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        s[C].pragma(yi, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n        s[CC].compute_at(s[C], tx)\n        _, yi, xi = s[CC].op.axis\n        ko, ki = cfg[\"tile_k\"].apply(s, CC, k)\n        s[CC].reorder(ko, ki, yi, xi)\n        s[CC].pragma(ki, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        s[CC].pragma(ki, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n        s[AA].compute_at(s[CC], ko)\n        s[AL].compute_at(s[CC], ki)\n        s[BB].compute_at(s[CC], ko)\n        s[BL].compute_at(s[CC], ki)\n        _, y, k = s[AA].op.axis\n        ty, yi = s[AA].split(y, nparts=cfg[\"tile_y\"].size[1])\n        tx, ki = s[AA].split(k, nparts=cfg[\"tile_x\"].size[1])\n        s[AA].reorder(ty, tx, yi, ki)\n        s[AA].bind(ty, thread_y)\n        s[AA].bind(tx, thread_x)\n        s[AA].pragma(yi, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        s[AA].pragma(yi, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n        _, x, k = s[BB].op.axis\n        ty, xi = s[BB].split(x, nparts=cfg[\"tile_y\"].size[1])\n        tx, ki = s[BB].split(k, nparts=cfg[\"tile_x\"].size[1])\n        s[BB].bind(ty, thread_y)\n        s[BB].bind(tx, thread_x)\n        s[BB].reorder(ty, tx, xi, ki)\n        s[BB].pragma(xi, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n        s[BB].pragma(xi, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    def _callback(op):\n        if \"batch_matmul\" in op.tag:\n            _schedule(cfg, op)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"batch_matmul_cublas.cuda\")\ndef batch_matmul_cublas(\n    cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Compute batch matrix multiplication of `x` and `y`.\n\n    Both `x` and `y` can be transposed. For legacy reason, we use NT format\n    (transpose_a=False, transpose_b=True) by default.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file.\n\n    x : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    y : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    out_shape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    if transpose_a:\n        b, k, m = get_const_tuple(x.shape)\n    else:\n        b, m, k = get_const_tuple(x.shape)\n    if transpose_b:\n        b, n, k = get_const_tuple(y.shape)\n    else:\n        b, k, n = get_const_tuple(y.shape)\n    if all([isinstance(s, int) for s in [b, m, n, k]]):\n        cfg.add_flop(b * m * k * n * 2)\n    return cublas.batch_matmul(x, y, transa=transpose_a, transb=transpose_b, dtype=out_dtype)\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_cublas.cuda\")\ndef schedule_batch_matmul_cublas(_, outs):\n    \"\"\"Schedule batch_matmul operator using CUBLAS\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"batch_matmul_int8.cuda\")\ndef batch_matmul_int8(\n    cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Batch Matmul operator for int8 on CUDA.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file.\n\n    x : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    y : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    out_shape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    del out_shape\n    # TODO(jcf94): Deal with different transpose combinations\n    assert not transpose_a and transpose_b\n    if out_dtype is None:\n        out_dtype = x.dtype\n\n    x_shape = get_const_tuple(x.shape)\n    y_shape = get_const_tuple(y.shape)\n    assert len(x_shape) == 3 and len(y_shape) == 3, \"only support 3-dim batch_matmul\"\n\n    XB, M, XK = x.shape\n    YB, N, YK = y.shape\n    assert XB == YB or XB == 1 or YB == 1, \"batch dimension doesn't match\"\n    assert XK == YK, \"shapes of x and y is inconsistent\"\n\n    nB = tvm.te.max(XB, YB)\n    nK = ((XK + 3) // 4) * 4\n    reduce_k = te.reduce_axis((0, nK), name=\"k\")\n\n    # pad for _dp4a vectorize\n    pad_x = te.compute(\n        (XB, M, nK),\n        lambda b, i, j: tvm.te.if_then_else(\n            j >= XK, tvm.runtime.convert(0).astype(x.dtype), x[b, i, j]\n        ),\n    )\n    pad_y = te.compute(\n        (YB, N, nK),\n        lambda b, i, j: tvm.te.if_then_else(\n            j >= YK, tvm.runtime.convert(0).astype(y.dtype), y[b, i, j]\n        ),\n    )\n\n    out = te.compute(\n        (nB, M, N),\n        lambda b, i, j: te.sum(\n            pad_x[b if XB != 1 else 0, i, reduce_k].astype(out_dtype)\n            * pad_y[b if YB != 1 else 0, j, reduce_k].astype(out_dtype),\n            axis=[reduce_k],\n        ),\n        tag=\"batch_matmul_int8\",\n    )\n    cfg.add_flop(XB * M * N * nK * 2)\n    return out\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_int8.cuda\")\ndef schedule_batch_matmul_int8(cfg, outs):\n    \"\"\"Batch Matmul schedule for int8 on CUDA\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"batch_matmul_int8\" in op.tag:\n            _schedule_batch_matmul_int8(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_batch_matmul_int8(cfg, s, output):\n    input_x, input_y = s[output].op.input_tensors\n    if len(input_y.op.input_tensors) == 1 and input_y.op.input_tensors[0] == input_x:\n        s[input_y].compute_inline()\n\n    B, M, K = get_const_tuple(input_x.shape)\n    _, N, _ = get_const_tuple(input_y.shape)\n\n    k_factor = 4\n    assert K % k_factor == 0, \"Input dimension must divide {}\".format(k_factor)\n    if K % 16 == 0:\n        k_factor = 16\n\n    cfg.define_split(\"tile_f\", B, num_outputs=4)\n    cfg.define_split(\"tile_m\", M, num_outputs=4)\n    cfg.define_split(\"tile_n\", N, num_outputs=4)\n    cfg.define_split(\"tile_k\", K // k_factor, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 256, 512, 1024])\n\n    batch_matmul_op = s.outputs[0]\n    s[input_x].compute_inline()\n    s[input_y].compute_inline()\n\n    x_cache = s.cache_read(input_x, \"shared\", [batch_matmul_op])\n    y_cache = s.cache_read(input_y, \"shared\", [batch_matmul_op])\n    batch_matmul_cache = s.cache_write(batch_matmul_op.output(0), \"local\")\n\n    # tile reduce axis\n    ko = batch_matmul_cache.op.reduce_axis[0]\n    ko, ki = s[batch_matmul_cache].split(ko, factor=4)\n    ko, kt = cfg[\"tile_k\"].apply(s, batch_matmul_cache, ko)\n    # dp4a tensorize\n\n    target = tvm.target.Target.current(allow_none=False)\n    do_tensorize = \"+dotprod\" in target.mattr or target.supports_integer_dot_product\n\n    if do_tensorize:\n        dtypes = (input_x.dtype, input_y.dtype)\n        s[batch_matmul_cache].tensorize(ki, dp4a(\"shared\", \"shared\", \"local\", dtypes))\n\n    # tile axis\n    f, m, n = batch_matmul_op.axis\n    kernel_scope, f = s[batch_matmul_op].split(f, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, batch_matmul_op, f)\n    bm, vm, tm, mi = cfg[\"tile_m\"].apply(s, batch_matmul_op, m)\n    bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, batch_matmul_op, n)\n    s[batch_matmul_op].reorder(bf, bm, bn, vf, vm, vn, tf, tm, tn, fi, mi, ni)\n\n    # bind axis\n    s[batch_matmul_op].bind(bf, tvm.te.thread_axis(\"blockIdx.z\"))\n    s[batch_matmul_op].bind(bm, tvm.te.thread_axis(\"blockIdx.y\"))\n    s[batch_matmul_op].bind(bn, tvm.te.thread_axis(\"blockIdx.x\"))\n\n    s[batch_matmul_op].bind(vf, tvm.te.thread_axis(\"vthread\"))\n    s[batch_matmul_op].bind(vm, tvm.te.thread_axis(\"vthread\"))\n    s[batch_matmul_op].bind(vn, tvm.te.thread_axis(\"vthread\"))\n\n    s[batch_matmul_op].bind(tf, tvm.te.thread_axis(\"threadIdx.z\"))\n    s[batch_matmul_op].bind(tm, tvm.te.thread_axis(\"threadIdx.y\"))\n    s[batch_matmul_op].bind(tn, tvm.te.thread_axis(\"threadIdx.x\"))\n\n    # cache compute at\n    s[batch_matmul_cache].compute_at(s[batch_matmul_op], tn)\n    fo, mo, no = batch_matmul_cache.op.axis[:3]\n    s[batch_matmul_cache].reorder(ko, kt, fo, mo, no, ki)\n\n    # for load in [splited_x_op, splited_y_op]\n    for load in [x_cache, y_cache]:\n        s[load].compute_at(s[batch_matmul_cache], ko)\n        outer, inner = s[load].split(s[load].op.axis[-1], factor=k_factor)\n        s[load].vectorize(inner)\n\n        fused = s[load].op.axis[:-1] + [outer]\n        fused = s[load].fuse(*fused)\n\n        fused, tx = s[load].split(fused, factor=cfg[\"tile_n\"].size[2])\n        fused, ty = s[load].split(fused, factor=cfg[\"tile_m\"].size[2])\n        fused, tz = s[load].split(fused, factor=cfg[\"tile_f\"].size[2])\n\n        s[load].bind(tz, tvm.te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, tvm.te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, tvm.te.thread_axis(\"threadIdx.x\"))\n\n    # max unroll\n    s[batch_matmul_op].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[batch_matmul_op].pragma(kernel_scope, \"unroll_explicit\", False)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/batch_matmul_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,unused-variable,unused-argument\n\"\"\"cuda batch_matmul operators\"\"\"\nimport tvm\nfrom tvm import autotvm\nfrom tvm import te\nfrom ..utils import traverse_inline, get_const_tuple\nfrom .tensor_intrin import (\n    intrin_wmma_load_matrix_A,\n    intrin_wmma_load_matrix_W,\n    intrin_wmma_store_matrix,\n    intrin_wmma_gemm,\n)\n\n\n@autotvm.register_topi_compute(\"batch_matmul_tensorcore.cuda\")\ndef batch_matmul_tensorcore(\n    cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"batch matmul tensorcore operator on cuda\"\"\"\n    # TODO(jcf94): Deal with different transpose combinations\n    assert not transpose_a and transpose_b\n    # TODO(liuxin.ai): Deal with out_shape for broadcast\n    del out_shape\n    return batch_matmul_tensorcore_cuda(x, y, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_tensorcore.cuda\")\ndef schedule_batch_matmul_tensorcore(cfg, outs):\n    \"\"\"Schedule for batch_matmul operator using Tensorcore\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of batch_matmul\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(cfg, s, C):\n        A, B = s[C].op.input_tensors\n        if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A:\n            s[B].compute_inline()\n        batch, m_dim, k_dim = get_const_tuple(A.shape)\n        batch, n_dim, k_dim = get_const_tuple(B.shape)\n        data_dtype = A.dtype\n        out_dtype = C.dtype\n\n        # Explicit memory access\n        AS = s.cache_read(A, \"shared\", [C])\n        BS = s.cache_read(B, \"shared\", [C])\n        AF = s.cache_read(AS, \"wmma.matrix_a\", [C])\n        BF = s.cache_read(BS, \"wmma.matrix_b\", [C])\n        CF = s.cache_write(C, \"wmma.accumulator\")\n        CS = s.cache_read(CF, \"shared\", [C])\n\n        # fallback support\n        target = tvm.target.Target.current()\n        if cfg.is_fallback:\n            ref_log = autotvm.tophub.load_reference_log(\n                target.kind.name, target.model, \"batch_matmul_tensorcore.cuda\"\n            )\n            cfg.fallback_with_reference_log(ref_log)\n\n        # Deal with op fusion, such as bias/relu and slice after padding\n        if C.op not in s.outputs and \"injective\" in s.outputs[0].tag:\n            s[C].compute_inline()\n            C = s.outputs[0].output(0)\n\n        # create tuning space\n        cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n        cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n        cfg.define_knob(\"warp_row_tiles\", [1, 2, 4])\n        cfg.define_knob(\"warp_col_tiles\", [1, 2, 4])\n        cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n        cfg.define_knob(\"offset\", [0, 8])\n        cfg.define_knob(\"offsetCS\", [0, 8])\n        cfg.define_knob(\"vec\", [1, 2, 4, 8])\n\n        # Ensure that the default parameters are applicable when autotvm is not in use\n        if data_dtype in [\"float16\", \"uint8\", \"int8\"]:\n            if m_dim % 32 == 0 and n_dim % 8 == 0:\n                cfg.define_knob(\"wmma_m\", [32, 16, 8])\n            elif m_dim % 16 == 0 and n_dim % 16 == 0:\n                cfg.define_knob(\"wmma_m\", [16, 8, 32])\n            elif m_dim % 8 == 0 and n_dim % 32 == 0:\n                cfg.define_knob(\"wmma_m\", [8, 16, 32])\n            wmma_k = 16\n            wmma_m = cfg[\"wmma_m\"].val\n            if wmma_m == 16:\n                wmma_n = 16\n            elif wmma_m == 8:\n                wmma_n = 32\n            elif wmma_m == 32:\n                wmma_n = 8\n        elif data_dtype in [\"int4\", \"uint4\"]:\n            wmma_m = wmma_n = 8\n            wmma_k = 32\n        else:\n            raise ValueError(\"data dtype %s is not yet supported\" % data_dtype)\n\n        warp_size = 32\n        block_row_warps = cfg[\"block_row_warps\"].val\n        block_col_warps = cfg[\"block_col_warps\"].val\n        warp_row_tiles = cfg[\"warp_row_tiles\"].val\n        warp_col_tiles = cfg[\"warp_col_tiles\"].val\n        chunk = cfg[\"chunk\"].val\n        offset = cfg[\"offset\"].val\n        offsetCS = cfg[\"offsetCS\"].val\n        vec = cfg[\"vec\"].val\n\n        # Define the stride of intrin functions\n        AS_align = chunk * wmma_k + offset\n        BS_align = chunk * wmma_k + offset\n        CS_align = warp_col_tiles * block_col_warps * wmma_n + offsetCS\n        AS_stride = [AS_align, 1]\n        BS_stride = [BS_align, 1]\n        AF_stride = [wmma_k, 1]\n        BF_stride = [wmma_k, 1]\n        CF_stride = [warp_col_tiles * wmma_n, 1]\n        CS_stride = [CS_align, 1]\n\n        block_x = te.thread_axis(\"blockIdx.x\")\n        block_y = te.thread_axis(\"blockIdx.y\")\n        block_z = te.thread_axis(\"blockIdx.z\")\n        thread_x = te.thread_axis(\"threadIdx.x\")\n        thread_y = te.thread_axis(\"threadIdx.y\")\n        thread_z = te.thread_axis(\"threadIdx.z\")\n\n        # Schedule for dense computation\n        block_factor_m = wmma_m * warp_row_tiles * block_row_warps\n        block_factor_n = wmma_n * warp_col_tiles * block_col_warps\n        b, m, n = C.op.axis\n        block_i, bc = s[C].split(m, factor=block_factor_m)\n        block_j, oc = s[C].split(n, factor=block_factor_n)\n        s[C].reorder(b, block_i, block_j, bc, oc)\n        t = s[C].fuse(bc, oc)\n        t, vi = s[C].split(t, factor=vec)\n        t, tx = s[C].split(t, factor=warp_size)\n        t, ty = s[C].split(t, factor=block_row_warps)\n        t, tz = s[C].split(t, factor=block_col_warps)\n        s[C].bind(block_i, block_x)\n        s[C].bind(block_j, block_y)\n        s[C].bind(b, block_z)\n        s[C].bind(tz, thread_z)\n        s[C].bind(ty, thread_y)\n        s[C].bind(tx, thread_x)\n        s[C].vectorize(vi)\n\n        # Schedule for wmma store\n        s[CS].compute_at(s[C], block_j)\n        bs, bb, oo = CS.op.axis\n        s[CS].storage_align(bb, CS_align - 1, CS_align)\n        bb, bbi = s[CS].split(bb, factor=wmma_m)\n        oo, ooi = s[CS].split(oo, factor=wmma_n)\n        bb, bbii = s[CS].split(bb, factor=warp_row_tiles)\n        oo, ooii = s[CS].split(oo, factor=warp_col_tiles)\n        s[CS].reorder(bs, bb, oo, bbii, ooii, bbi, ooi)\n        s[CS].bind(bb, thread_z)\n        s[CS].bind(oo, thread_y)\n\n        # Schedule for wmma computation\n        s[CF].compute_at(s[CS], oo)\n        bs, warp_i, warp_j = CF.op.axis\n        warp_i, _ii = s[CF].split(warp_i, factor=wmma_m)\n        warp_j, _jj = s[CF].split(warp_j, factor=wmma_n)\n        (k,) = CF.op.reduce_axis\n        k, _k = s[CF].split(k, factor=wmma_k)\n        ko, ki = s[CF].split(k, factor=chunk)\n        s[CF].reorder(bs, ko, ki, warp_i, warp_j, _ii, _jj, _k)\n\n        # Schedule for  wmma_matrix_a load\n        s[AF].compute_at(s[CF], ki)\n        bs, b, i = AF.op.axis\n        b, b_ii = s[AF].split(b, factor=wmma_m)\n        i, i_jj = s[AF].split(i, factor=wmma_k)\n        s[AF].reorder(bs, b, i, b_ii, i_jj)\n\n        # Schedule for  wmma_matrix_b load\n        s[BF].compute_at(s[CF], ki)\n        bs, o, i = BF.op.axis\n        o, o_ii = s[BF].split(o, factor=wmma_n)\n        i, i_ii = s[BF].split(i, factor=wmma_k)\n        s[BF].reorder(bs, o, i, o_ii, i_ii)\n\n        # Schedule for A's(B's) shared memory load\n        def shared_schedule(stage, strides):\n            s[stage].compute_at(s[CF], ko)\n            bs, xo, yo = stage.op.axis\n            s[stage].storage_align(xo, strides - 1, strides)\n            t = s[stage].fuse(xo, yo)\n            t, vi = s[stage].split(t, factor=vec)\n            t, tx = s[stage].split(t, factor=warp_size)\n            t, ty = s[stage].split(t, factor=block_row_warps)\n            _, tz = s[stage].split(t, factor=block_col_warps)\n            s[stage].bind(ty, thread_y)\n            s[stage].bind(tz, thread_z)\n            s[stage].bind(tx, thread_x)\n            s[stage].vectorize(vi)\n\n        shared_schedule(AS, AS_align)\n        shared_schedule(BS, BS_align)\n\n        shape = (wmma_m, wmma_n, wmma_k)\n        AL_gemm = te.placeholder((wmma_m, wmma_k), name=\"AL_gemm\", dtype=data_dtype)\n        BL_gemm = te.placeholder((wmma_n, wmma_k), name=\"BL_gemm\", dtype=data_dtype)\n        k_gemm = te.reduce_axis((0, wmma_k), name=\"k_gemm\")\n        CL_compute = te.compute(\n            (wmma_m, wmma_n),\n            lambda ii, jj: te.sum(\n                AL_gemm[ii, k_gemm].astype(out_dtype) * BL_gemm[jj, k_gemm].astype(out_dtype),\n                axis=k_gemm,\n            ),\n            name=\"CL_compute\",\n        )\n\n        # lower the computation loops down to TensorCore hardware intrinsics\n        # by mapping the dense tensorcore to tensor intrinsics\n        s[AF].tensorize(\n            b_ii,\n            intrin_wmma_load_matrix_A(\n                AF_stride,\n                AS_stride,\n                shape,\n                \"row_major\",\n                (wmma_m, wmma_k),\n                (wmma_m, wmma_k),\n                data_dtype,\n            ),\n        )\n        s[BF].tensorize(\n            o_ii,\n            intrin_wmma_load_matrix_W(\n                BF_stride,\n                BS_stride,\n                shape,\n                \"col_major\",\n                (wmma_n, wmma_k),\n                (wmma_n, wmma_k),\n                data_dtype,\n            ),\n        )\n        s[CF].tensorize(\n            _ii,\n            intrin_wmma_gemm(AL_gemm, BL_gemm, CL_compute, AF_stride, BF_stride, CF_stride, shape),\n        )\n        s[CS].tensorize(\n            bbi,\n            intrin_wmma_store_matrix(\n                CS_stride, CF_stride, shape, out_dtype, (wmma_m, wmma_n), (wmma_m, wmma_n)\n            ),\n        )\n\n    def _callback(op):\n        if \"batch_matmul_tensorcore\" in op.tag:\n            _schedule(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef batch_matmul_tensorcore_cuda(x, y, out_dtype=None):\n    \"\"\"Computes batch matrix multiplication of `x` and `y` when `x` and `y` are\n    data in batch.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        3-D with shape [batch, M, K]\n\n    y : tvm.te.Tensor\n        3-D with shape [batch, N, K]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    assert len(x.shape) == 3 and len(y.shape) == 3, \"only support 3-dim batch_matmul\"\n    x_shape = get_const_tuple(x.shape)\n    y_shape = get_const_tuple(y.shape)\n    assert x_shape[0] == y_shape[0], \"batch dimension doesn't match\"\n    assert x_shape[2] == y_shape[2], \"shapes of x and y is inconsistent\"\n    batch, M, K = x.shape\n    N = y.shape[1]\n\n    if out_dtype is None:\n        out_dtype = x.dtype\n\n    assert x.dtype == y.dtype\n    assert x.dtype in [\"float16\", \"uint8\", \"int8\", \"uint4\", \"int4\"]\n    if x.dtype in [\"float16\", \"uint8\", \"int8\"]:\n        assert (\n            (M % 8 == 0 and K % 16 == 0 and N % 32 == 0)\n            or (M % 16 == 0 and K % 16 == 0 and N % 16 == 0)\n            or (M % 32 == 0 and K % 16 == 0 and N % 8 == 0)\n        ), \"The shape of (M, K, N) must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32)\"\n    else:\n        assert (\n            M % 8 == 0 and K % 32 == 0 and N % 8 == 0\n        ), \"The shape of (M, K, N) must be multiple of (8, 32, 8)\"\n\n    k = te.reduce_axis((0, K), name=\"k\")\n    return te.compute(\n        (batch, M, N),\n        lambda b, i, j: te.sum(x[b, i, k].astype(out_dtype) * y[b, j, k].astype(out_dtype), axis=k),\n        tag=\"batch_matmul_tensorcore\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Compute definition for conv1d with cuda backend\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline, get_const_tuple\n\n\n@autotvm.register_topi_compute(\"conv1d_ncw.cuda\")\ndef conv1d_ncw(cfg, data, kernel, strides, padding, dilation, out_dtype=\"float32\"):\n    return nn.conv1d_ncw(data, kernel, strides, padding, dilation, out_dtype)\n\n\ndef _schedule_conv1d_ncw(cfg, outs):\n    \"\"\"TOPI schedule callback of conv1d ncw for cuda gpu\n\n    Parameters\n    ----------\n    cfg : ConfigEntity\n        the config for this template.\n\n    outs : Array of Tensor\n        The computation graph description of conv1d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s : Schedule\n        The computation schedule for conv1d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv1d_ncw\" or op.tag == \"group_conv1d_ncw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, f, x = s[conv].op.axis\n            rc = s[conv].op.reduce_axis[0]\n            cfg.define_split(\"tile_n\", cfg.axis(n), num_outputs=4)\n            cfg.define_split(\"tile_f\", cfg.axis(f), num_outputs=4)\n            cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4)\n            cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=3)\n            cfg.define_knob(\"auto_unroll_max_step\", [64, 512, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            ##### space definition end #####\n\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            # create cache stage\n            s[pad_data].set_scope(\"shared\")\n            AA = pad_data\n            WW = s.cache_read(kernel, \"shared\", [OL])\n\n            # tile and bind spatial axes\n            n, f, x = s[output].op.axis\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            s[output].reorder(bn, bf, bx, vn, vf, vx, tn, tf, tx, ni, fi, xi)\n            s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(bf, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vn, te.thread_axis(\"vthread\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[OL].compute_at(s[output], tx)\n            # number of threads\n            n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_f\"].size[2]\n            n_tx = cfg[\"tile_x\"].size[2]\n\n            # tile reduction axes\n            n, f, x = s[OL].op.axis\n            rc, rx = s[OL].op.reduce_axis\n            rco, rcm, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n            s[OL].reorder(rco, rcm, rx, rci, n, f, x)\n\n            s[AA].compute_at(s[OL], rx)\n            s[WW].compute_at(s[OL], rx)\n\n            # cooperative fetching\n            for load in [AA, WW]:\n                n, f, x = s[load].op.axis\n                fused = s[load].fuse(f, x)\n                tz, fused = s[load].split(fused, nparts=n_tz)\n                tx, fused = s[load].split(fused, nparts=n_tx)\n                s[load].bind(tz, te.thread_axis(\"threadIdx.y\"))\n                s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n            N, CO, OW = get_const_tuple(output.shape)\n            _, CI, KW = get_const_tuple(kernel.shape)\n            cfg.add_flop(2 * N * OW * CO * KW * CI)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n\n\n@autotvm.register_topi_schedule(\"conv1d_ncw.cuda\")\ndef schedule_conv1d_ncw(cfg, outs):\n    return _schedule_conv1d_ncw(cfg, outs)\n\n\n@autotvm.register_topi_compute(\"group_conv1d_ncw.cuda\")\ndef group_conv1d_ncw(cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"):\n    return nn.group_conv1d_ncw(data, kernel, strides, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"group_conv1d_ncw.cuda\")\ndef schedule_group_conv1d_ncw(cfg, outs):\n    return _schedule_conv1d_ncw(cfg, outs)\n\n\n@autotvm.register_topi_compute(\"conv1d_nwc.cuda\")\ndef conv1d_nwc(cfg, data, kernel, strides, padding, dilation, out_dtype=\"float32\"):\n    return nn.conv1d_nwc(data, kernel, strides, padding, dilation, out_dtype)\n\n\ndef _schedule_conv1d_nwc(cfg, outs):\n    \"\"\"TOPI schedule callback of conv1d nwc for cuda gpu\n\n    Parameters\n    ----------\n    cfg : ConfigEntity\n        the config for this template.\n\n    outs : Array of Tensor\n        The computation graph description of conv1d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s : Schedule\n        The computation schedule for conv1d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv1d_nwc\" or op.tag == \"group_conv1d_nwc\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, x, f = s[conv].op.axis\n            rc = s[conv].op.reduce_axis[0]\n            cfg.define_split(\"tile_n\", cfg.axis(n), num_outputs=4)\n            cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4)\n            cfg.define_split(\"tile_f\", cfg.axis(f), num_outputs=4)\n            cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=3)\n            cfg.define_knob(\"auto_unroll_max_step\", [64, 512, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            ##### space definition end #####\n\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            # create cache stage\n            s[pad_data].set_scope(\"shared\")\n            AA = pad_data\n            WW = s.cache_read(kernel, \"shared\", [OL])\n\n            # tile and bind spatial axes\n            n, f, x = s[output].op.axis\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n\n            s[output].reorder(bn, bx, bf, vn, vx, vf, tn, tx, tf, ni, xi, fi)\n            s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bf, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vn, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n\n            s[output].bind(tf, te.thread_axis(\"threadIdx.x\"))\n            s[OL].compute_at(s[output], tf)\n            # number of threads\n            n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_x\"].size[2]\n            n_tx = cfg[\"tile_f\"].size[2]\n\n            # tile reduction axes\n            n, x, f = s[OL].op.axis\n            rc, rx = s[OL].op.reduce_axis\n            rco, rcm, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n            s[OL].reorder(rco, rcm, rx, rci, n, x, f)\n\n            s[AA].compute_at(s[OL], rx)\n            s[WW].compute_at(s[OL], rx)\n\n            # cooperative fetching\n            for load in [AA, WW]:\n                n, x, f = s[load].op.axis\n                fused = s[load].fuse(x, f)\n                tz, fused = s[load].split(fused, nparts=n_tz)\n                tx, fused = s[load].split(fused, nparts=n_tx)\n                s[load].bind(tz, te.thread_axis(\"threadIdx.y\"))\n                s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n            N, OW, CO = get_const_tuple(output.shape)\n            KW, CI, _ = get_const_tuple(kernel.shape)\n            cfg.add_flop(2 * N * OW * CO * KW * CI)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n\n\n@autotvm.register_topi_schedule(\"conv1d_nwc.cuda\")\ndef schedule_conv1d_nwc(cfg, outs):\n    return _schedule_conv1d_nwc(cfg, outs)\n\n\n@autotvm.register_topi_compute(\"group_conv1d_nwc.cuda\")\ndef group_conv1d_nwc(cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"):\n    return nn.group_conv1d_nwc(data, kernel, strides, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"group_conv1d_nwc.cuda\")\ndef schedule_group_conv1d_nwc(cfg, outs):\n    return _schedule_conv1d_nwc(cfg, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv1d_transpose_ncw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Conv1d transpose template for cuda backend\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom .. import nn\nfrom ..utils import get_const_tuple, traverse_inline\n\n\n@autotvm.task.register_topi_compute(\"conv1d_transpose_nchw.cuda\")\ndef conv1d_transpose_ncw(cfg, data, kernel, stride, padding, out_dtype, output_padding):\n    \"\"\"Transposed 1D convolution ncw forward operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n    Input : tvm.te.Tensor\n        3-D with shape [batch, in_channel, inp_width]\n    Filter : tvm.te.Tensor\n        3-D with shape [in_channel, num_filter, kernel_size]\n    stride : tuple of one int\n        The spatial stride along width\n    padding : int, tuple, or string\n        int: padding size\n        tuple of 2 ints: (pad_left, pad_right) for left and right padding\n        string: ['VALID', 'SAME']\n    out_dtype: str\n        The output type. This is used in mixed precision\n    output_padding : ints\n        Used to disambiguate the output shape.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n    u    3-D with shape [batch, out_channel, out_width]\n    \"\"\"\n    if isinstance(stride, (tuple, list)):\n        stride = stride[0]\n    if isinstance(output_padding, (tuple, list)):\n        output_padding = output_padding[0]\n    assert output_padding < stride\n    cfg.stride = stride\n    cfg.output_padding = output_padding\n    batch, inp_channels, inp_width = get_const_tuple(data.shape)\n    _, out_channels, kernel_size = get_const_tuple(kernel.shape)\n    pad_left, pad_right = nn.get_pad_tuple1d(padding, kernel_size)\n    out_width = (inp_width - 1) * stride + kernel_size - pad_left - pad_right + output_padding\n    pad_left = kernel_size - 1 - pad_left\n    pad_right = kernel_size - 1 - pad_right + output_padding\n    padded_width = pad_left + inp_width + pad_right\n\n    padded_data = te.compute(\n        (batch, inp_channels, padded_width),\n        lambda n, c, x: tvm.tir.if_then_else(\n            tvm.tir.all(x >= pad_left, x < pad_left + inp_width),\n            data[n, c, x - pad_left],\n            tvm.tir.const(0.0, \"float32\"),\n        ),\n        name=\"data_pad\",\n    )\n\n    padded_kernel = te.compute(\n        (inp_channels, out_channels, kernel_size + stride - 1),\n        lambda ci, co, k: tvm.tir.if_then_else(\n            tvm.tir.all(k < kernel_size),\n            kernel[ci, co, kernel_size - k - 1],\n            tvm.tir.const(0.0, \"float32\"),\n        ),\n        name=\"kernel_pad\",\n    )\n\n    ci = te.reduce_axis((0, inp_channels), name=\"ci\")\n    k = te.reduce_axis((0, tvm.tir.indexdiv(kernel_size + stride - 1, stride)), name=\"k\")\n    border = pad_left * (stride - 1)\n\n    # Skip multiplication by 0 values in the input data inserted when stride is greater then 1.\n    # During multiplication of kernel by padded data:\n    #  Kernel indices are: 0, 1 * stride, 2 * stride, ..., ceil(kernel_size / stride) plus\n    #  data offset mod stride\n    data_out = te.compute(\n        (batch, out_channels, out_width),\n        lambda b, co, w: te.sum(\n            padded_data[b, ci, tvm.tir.indexdiv(border + w + stride - 1, stride) + k].astype(\n                out_dtype\n            )\n            * padded_kernel[\n                ci, co, k * stride + tvm.tir.indexmod(stride - w - border, stride)\n            ].astype(out_dtype),\n            axis=[ci, k],\n        ),\n        tag=\"conv1d_transpose_ncw\",\n    )\n\n    return data_out\n\n\n@autotvm.task.register_topi_schedule(\"conv1d_transpose_nchw.cuda\")\ndef schedule_conv1d_transpose_ncw(cfg, outs):\n    \"\"\"TOPI Schedule callback for conv1d_transpose operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The parameters for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv1d transpose\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv1d transpose.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv1d_transpose_ncw\":\n            padded_data = op.input_tensors[0]\n            padded_kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, f, x = s[conv].op.axis\n            rc = s[conv].op.reduce_axis[0]\n            cfg.define_split(\"tile_n\", cfg.axis(n if isinstance(n, int) else 1), num_outputs=4)\n            cfg.define_split(\"tile_f\", cfg.axis(f), num_outputs=4)\n            cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4)\n            cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=3)\n            cfg.define_knob(\"auto_unroll_max_step\", [64, 512, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            ##### space definition end #####\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            s[padded_kernel].compute_inline()\n            s[padded_data].compute_inline()\n\n            # tile and bind spatial axes\n            n, f, x = s[output].op.axis\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            s[output].reorder(bn, bf, bx, vn, vf, vx, tn, tf, tx, ni, fi, xi)\n            s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(bf, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vn, te.thread_axis(\"vthread\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[OL].compute_at(s[output], tx)\n\n            # tile reduction axes\n            n, f, x = s[OL].op.axis\n            rc, rx = s[OL].op.reduce_axis\n            rco, rcm, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n            s[OL].reorder(rco, rcm, rx, rci, n, f, x)\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Compute definition for conv2d with cuda backend\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import OtherOptionEntity\nfrom tvm.contrib import cudnn\n\nfrom .. import nn, generic\nfrom ..nn.utils import get_pad_tuple\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .conv2d_direct import schedule_direct_cuda\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw.cuda\")\ndef conv2d_nchw(cfg, data, kernel, strides, padding, dilation, out_dtype=\"float32\"):\n    \"\"\"Compute conv2d with NCHW layout\"\"\"\n    return nn.conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw.cuda\")\ndef schedule_conv2d_nchw(cfg, outs):\n    \"\"\"Create the schedule for conv2d_nchw\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv2d_nchw\":\n            schedule_direct_cuda(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_cudnn.cuda\")\ndef conv2d_cudnn(\n    cfg, data, kernel, strides, padding, dilation, groups=1, layout=\"NCHW\", out_dtype=\"float32\"\n):\n    \"\"\"Compute conv2d using CuDNN library\"\"\"\n    if layout == \"NCHW\":\n        tensor_format = 0  # CUDNN_TENSOR_NCHW\n        N, _, H, W = get_const_tuple(data.shape)\n    elif layout == \"NHWC\":\n        tensor_format = 1  # CUDNN_TENSOR_NHWC\n        N, H, W, _ = get_const_tuple(data.shape)\n    else:\n        raise ValueError(\"Unsupported layout %s in cudnn\" % layout)\n    CO, CI, KH, KW = get_const_tuple(kernel.shape)\n\n    # handle dilation\n    stride_h, stride_w = (strides, strides) if isinstance(strides, int) else strides\n    dilation_h, dilation_w = (dilation, dilation) if isinstance(dilation, int) else dilation\n    KH_dilated = (KH - 1) * dilation_h + 1\n    KW_dilated = (KW - 1) * dilation_h + 1\n\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH_dilated, KW_dilated))\n    if (pt != pb) or (pl != pr):\n        raise ValueError(\"Cudnn doesn't support asymmetric padding.\")\n\n    OH = (H + pt + pb - KH) // stride_h + 1\n    OW = (W + pl + pr - KW) // stride_w + 1\n\n    if isinstance(N, int):\n        cfg.add_flop(\n            groups\n            * 2\n            * N\n            * OH\n            * OW\n            * CO\n            * CI\n            * ((KH - 1) * dilation_h + 1)\n            * ((KW - 1) * dilation_w + 1)\n        )\n\n    if data.dtype == \"int8\" or kernel.dtype == \"int8\":\n        if layout == \"NCHW\":\n            raise ValueError(\"NCHW layout do not support int8 in cudnn\")\n        dtype = \"int32\"\n    else:\n        dtype = data.dtype\n\n    cfg.define_knob(\"algo\", range(cudnn.algo_to_index(\"fwd\", \"CUDNN_CONVOLUTION_FWD_ALGO_COUNT\")))\n    if cfg.is_fallback:\n        if cudnn.exists():\n            # Let CUDNN choose the best algo, based on benchmarks run\n            # on the local machine.  In the future, this should be\n            # based on parameters stored in the Target.\n            cfg[\"algo\"] = OtherOptionEntity(-1)\n        else:\n            cfg[\"algo\"] = OtherOptionEntity(0)\n\n    return cudnn.conv_forward(\n        data,\n        kernel,\n        [pt, pl],  # cudnn padding pt, pl on both sides of input\n        [stride_h, stride_w],\n        [dilation_h, dilation_w],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        algo=cfg[\"algo\"].val,\n        conv_dtype=dtype,\n        groups=groups,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_cudnn.cuda\")\ndef schedule_conv2d_cudnn(cfg, outs):\n    \"\"\"Create the schedule for conv2d_cudnn\"\"\"\n    return generic.schedule_extern(outs)\n\n\ndef conv2d_backward_weight_cudnn(\n    dy, x, kernel_size, padding, stride, dilation, groups, layout, output_dtype\n):\n    \"\"\"Compute conv2d wgrad using CuDNN library\"\"\"\n    assert layout in [\"NCHW\", \"NHWC\"]\n\n    if dy.dtype == \"float16\":\n        # cuDNN does not seem to support other combination.\n        assert output_dtype == \"float16\", \"Only supports fp16 output for cuDNN fp16 wgrad.\"\n\n    conv_dtype = \"float32\"  # Accumulation is always fp32\n    return cudnn.conv_backward_filter(\n        dy,\n        x,\n        kernel_size,\n        padding,\n        stride,\n        dilation,\n        conv_mode=1,\n        tensor_format=0 if layout == \"NCHW\" else 1,\n        conv_dtype=conv_dtype,\n        groups=groups,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Conv2D alter op and legalize functions for cuda backend\"\"\"\n\nimport logging\n\nimport tvm\nfrom tvm import autotvm, relay, te\n\nfrom .. import nn\nfrom ..nn import conv2d_legalize\nfrom ..utils import get_const_tuple, is_target\nfrom .conv2d_winograd import _infer_tile_size\nfrom .tensorcore_alter_op import pad_to_tensorcore\n\nlogger = logging.getLogger(\"topi\")\n\n\n@nn.conv2d_alter_layout.register([\"cuda\", \"gpu\"])\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    if not is_target([\"vulkan\", \"rocm\", \"cuda\"]):\n        return None\n    dispatch_ctx = autotvm.task.DispatchContext.current\n\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    strides = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data, kernel = tinfos\n    out_dtype = out_type.dtype\n\n    impl, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n    if workload is None:\n        # The best implementation is not an AutoTVM template.\n        # It may be from the auto-scheduler\n\n        if impl.name.find(\"winograd\") != -1:\n            if dilation != (1, 1):\n                logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n                return None\n\n            if data_layout == \"NHWC\" and kernel_layout == \"HWIO\":\n                N, H, W, CI = get_const_tuple(data.shape)\n                KH, KW, _, CO = get_const_tuple(kernel.shape)\n                # Pre-compute weight transformation in winograd\n                tile_size = _infer_tile_size(tinfos[0], tinfos[1], layout=\"NHWC\")\n                # HWIO -> OIHW\n                kernel_transform = relay.transpose(inputs[1], axes=[3, 2, 0, 1])\n                # alpha, alpha, CO, CI\n                weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n                    kernel_transform, tile_size=tile_size\n                )\n                new_attrs[\"tile_size\"] = tile_size\n                new_attrs[\"channels\"] = CO\n                return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                    inputs[0], weight, **new_attrs\n                )\n            elif data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n                N, CI, H, W = get_const_tuple(data.shape)\n                CO, _, KH, KW = get_const_tuple(kernel.shape)\n                # Pre-compute weight transformation in winograd\n                tile_size = _infer_tile_size(tinfos[0], tinfos[1], layout=\"NCHW\")\n                # alpha, alpha, CO, CI\n                weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n                    inputs[1], tile_size=tile_size\n                )\n                # alpha, alpha, CI, CO\n                weight = relay.transpose(weight, axes=[0, 1, 3, 2])\n                new_attrs[\"tile_size\"] = tile_size\n                new_attrs[\"channels\"] = CO\n                return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                    inputs[0], weight, **new_attrs\n                )\n\n        return None\n\n    cfg = dispatch_ctx.query(target, workload)\n    if cfg.is_fallback:  # if is fallback, clear query cache and return None\n        autotvm.task.clear_fallback_cache(target, workload)\n        do_new_layout = False\n        if is_target([\"vulkan\", \"rocm\"]):\n            do_new_layout = \"+dotprod\" in target.mattr or target.supports_integer_dot_product\n        if not do_new_layout:\n            return None\n\n    topi_tmpl = workload[0]\n    if topi_tmpl == \"conv2d_NCHWc_int8.cuda\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        assert CO % 4 == 0, \"Number of output channels should be multiple of 4\"\n        new_layout = \"NCHW4c\"\n        new_attrs[\"channels\"] = CO\n        new_attrs[\"data_layout\"] = new_layout\n        new_attrs[\"out_layout\"] = new_layout\n        new_attrs[\"kernel_layout\"] = \"OIHW4o4i\"\n        ic_block_factor = oc_block_factor = 4\n\n        # Store the same config for the altered operator (workload)\n        new_data = te.placeholder(\n            (N, CI // ic_block_factor, H, W, ic_block_factor), dtype=data.dtype\n        )\n        new_kernel = te.placeholder(\n            (\n                CO // oc_block_factor,\n                CI // ic_block_factor,\n                KH,\n                KW,\n                oc_block_factor,\n                ic_block_factor,\n            ),\n            dtype=kernel.dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, new_layout, out_dtype],\n            \"conv2d_NCHWc_int8.cuda\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_nchw_winograd.cuda\":\n        if dilation != (1, 1):\n            logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n            return None\n\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n\n        # pre-compute weight transformation in winograd\n        tile_size = _infer_tile_size(tinfos[0], tinfos[1])\n\n        weight = relay.nn.contrib_conv2d_winograd_weight_transform(inputs[1], tile_size=tile_size)\n        weight = relay.transpose(weight, axes=[0, 1, 3, 2])\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n\n        # Store the same config for the altered operator (workload)\n        new_data = data\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO), dtype=kernel.dtype\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_weight, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_winograd_without_weight_transform.cuda\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight, **new_attrs\n        )\n\n    if topi_tmpl in (\"conv2d_nhwc_winograd_direct.cuda\", \"conv2d_nhwc_winograd_tensorcore.cuda\"):\n        if dilation != (1, 1):\n            logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n            return None\n\n        assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n        N, H, W, CI = get_const_tuple(data.shape)\n        KH, KW, _, CO = get_const_tuple(kernel.shape)\n\n        # Pre-compute weight transformation in winograd\n        tile_size = _infer_tile_size(data, kernel, layout=\"NHWC\")\n        kernel_transform = relay.transpose(inputs[1], axes=[3, 2, 0, 1])\n        weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n            kernel_transform, tile_size=tile_size\n        )\n        weight = relay.transpose(weight, axes=[0, 1, 3, 2])\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n        # Store the same config for the altered operator (workload)\n        new_data = data\n        new_weight = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, CI, CO), dtype=kernel.dtype\n        )\n        if topi_tmpl == \"conv2d_nhwc_winograd_direct.cuda\":\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                \"conv2d_nhwc_winograd_direct_without_weight_transform.cuda\",\n            )\n        elif topi_tmpl == \"conv2d_nhwc_winograd_tensorcore.cuda\":\n            new_workload = autotvm.task.args_to_workload(\n                [new_data, new_weight, strides, padding, dilation, out_dtype],\n                \"conv2d_nhwc_winograd_tensorcore_without_weight_transform.cuda\",\n            )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight, **new_attrs\n        )\n\n    if topi_tmpl == \"group_conv2d_NCHWc_int8.cuda\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n\n        new_layout = \"NCHW4c\"\n        new_attrs[\"channels\"] = CO\n        new_attrs[\"data_layout\"] = new_layout\n        new_attrs[\"out_layout\"] = new_layout\n        new_attrs[\"kernel_layout\"] = \"OIHW4o4i\"\n        ic_block_factor = oc_block_factor = 4\n\n        # Store the same config for the altered operator (workload)\n        new_data = te.placeholder(\n            (N, CI // ic_block_factor, H, W, ic_block_factor), dtype=data.dtype\n        )\n        new_kernel = te.placeholder(\n            (\n                CO // oc_block_factor,\n                CI // ic_block_factor // groups,\n                KH,\n                KW,\n                oc_block_factor,\n                ic_block_factor,\n            ),\n            dtype=kernel.dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, groups, out_dtype],\n            \"group_conv2d_NCHWc_int8.cuda\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_HWNCnc_tensorcore.cuda\":\n        assert data_layout == \"HWNC\" and kernel_layout == \"HWOI\"\n        assert float(tvm.cuda(0).compute_version) >= 7.5\n        H, W, N, CI = get_const_tuple(data.shape)\n        KH, KW, CO, _ = get_const_tuple(kernel.shape)\n\n        if (\n            kernel.dtype in [\"int4\", \"uint4\"]\n            and (CI % 32 != 0 or CO % 8 != 0)\n            or kernel.dtype in [\"int8\", \"uint8\"]\n            and (CI % 16 != 0 or CO % 32 != 0)\n        ):\n            return relay.nn.conv2d(*inputs, **new_attrs)\n\n        new_attrs[\"channels\"] = CO\n        if kernel.dtype in [\"int4\", \"uint4\"]:\n            new_attrs[\"kernel_layout\"] = \"HWOI8o32i\"\n            ic_block_factor = 32\n            oc_block_factor = 8\n        else:\n            new_attrs[\"kernel_layout\"] = \"HWOI32o16i\"\n            ic_block_factor = 16\n            oc_block_factor = 32\n\n        new_kernel = te.placeholder(\n            (\n                KH,\n                KW,\n                CO // oc_block_factor,\n                CI // ic_block_factor,\n                oc_block_factor,\n                ic_block_factor,\n            ),\n            dtype=kernel.dtype,\n        )\n\n        new_workload = autotvm.task.args_to_workload(\n            [data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_HWNCnc_tensorcore.cuda\",\n        )\n\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.conv2d(*inputs, **new_attrs)\n\n    return None\n\n\ndef _pad_conv2d_HWNC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor):\n    # Pad batch size\n    if db != 0:\n        data = relay.nn.pad(data, pad_width=((0, 0), (0, 0), (0, db), (0, 0)))\n\n    # Pad input channel\n    if di != 0:\n        data = relay.nn.pad(data, pad_width=((0, 0), (0, 0), (0, 0), (0, di)))\n        kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, 0), (0, di)))\n\n    # Pad output channel\n    if do != 0:\n        kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, do), (0, 0)))\n\n    if do != 0:\n        new_out_channel = out_channel + do\n        new_attrs[\"channels\"] = new_out_channel\n\n    out = relay.nn.conv2d(data, kernel, **new_attrs)\n\n    if db != 0 or do != 0:\n        original_out_shape = [x.value for x in output_tensor.shape]\n        out = relay.strided_slice(out, begin=[0, 0, 0, 0], end=original_out_shape)\n\n    return out\n\n\ndef _pad_conv2d_NHWC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor):\n    # Pad batch size\n    if db != 0:\n        data = relay.nn.pad(data, pad_width=((0, db), (0, 0), (0, 0), (0, 0)))\n\n    # Pad input channel\n    if di != 0:\n        data = relay.nn.pad(data, pad_width=((0, 0), (0, 0), (0, 0), (0, di)))\n        kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, di), (0, 0)))\n\n    # Pad output channel\n    if do != 0:\n        kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, 0), (0, do)))\n\n    if do != 0:\n        new_out_channel = out_channel + do\n        new_attrs[\"channels\"] = new_out_channel\n\n    out = relay.nn.conv2d(data, kernel, **new_attrs)\n\n    if db != 0 or do != 0:\n        original_out_shape = [x.value for x in output_tensor.shape]\n        out = relay.strided_slice(out, begin=[0, 0, 0, 0], end=original_out_shape)\n\n    return out\n\n\n@conv2d_legalize.register([\"cuda\", \"gpu\"])\ndef _conv2d_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    if not is_target([\"vulkan\", \"rocm\", \"cuda\"]):\n        return None\n    # Dilation not supported yet. Return None if dilation is not (1, 1)\n    dilation = attrs.get_int_tuple(\"dilation\")\n    if not (dilation[0] == 1 and dilation[1] == 1):\n        return None\n\n    # No legalization for depthwise convolutions yet.\n    groups = attrs.get_int(\"groups\")\n    if groups != 1:\n        return None\n\n    # Collect the input tensors.\n    data_tensor, kernel_tensor = arg_types[0], arg_types[1]\n    data_dtype = data_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    data, kernel = inputs\n\n    # Get the conv attrs\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    # Get data layout. Return None if not NCHW\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n\n    # Pad input and output channels to use int8 schedule.\n    if data_dtype in [\"int8\", \"uint8\"]:\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            oc_modified = False\n            in_channel = data_tensor.shape[1].value\n            out_channel = kernel_tensor.shape[0].value\n\n            # Pad input channel\n            if in_channel % 4 != 0:\n                new_in_channel = ((in_channel + 4) // 4) * 4\n                diff = new_in_channel - in_channel\n                pad_width = ((0, 0), (0, diff), (0, 0), (0, 0))\n                data = relay.nn.pad(data, pad_width=pad_width)\n                kernel = relay.nn.pad(kernel, pad_width=pad_width)\n\n            # Pad output channel\n            new_out_channel = out_channel\n            if out_channel % 4 != 0:\n                new_out_channel = ((out_channel + 4) // 4) * 4\n                diff = new_out_channel - out_channel\n                kernel = relay.nn.pad(kernel, pad_width=((0, diff), (0, 0), (0, 0), (0, 0)))\n                oc_modified = True\n\n            if oc_modified:\n                new_attrs[\"channels\"] = new_out_channel\n                out = tvm.relay.nn.conv2d(data, kernel, **new_attrs)\n                original_out_shape = [x.value for x in output_tensor.shape]\n                out = relay.strided_slice(out, begin=[0, 0, 0, 0], end=original_out_shape)\n            else:\n                out = relay.nn.conv2d(data, kernel, **new_attrs)\n            return out\n\n        if data_layout == \"NHWC\" and kernel_layout == \"HWIO\":\n            batch = data_tensor.shape[0].value\n            in_channel = data_tensor.shape[3].value\n            out_channel = kernel_tensor.shape[3].value\n\n            if (\n                (batch % 8 == 0 and in_channel % 16 == 0 and out_channel % 32 == 0)\n                or (batch % 16 == 0 and in_channel % 16 == 0 and out_channel % 16 == 0)\n                or (batch % 32 == 0 and in_channel % 16 == 0 and out_channel % 8 == 0)\n            ):\n                # no need to pad\n                return None\n\n            candidates = [(16, 16, 16), (32, 16, 8), (8, 16, 32)]\n            (db, di, do), extra_flops = pad_to_tensorcore(\n                batch, in_channel, out_channel, candidates\n            )\n\n            if extra_flops > 2:\n                logger.info(\"conv2d pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n                return None\n\n            logger.info(\"conv2d pad_to_tensorcore, extra_flops %s\", extra_flops)\n\n            return _pad_conv2d_NHWC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor)\n\n        if data_layout == \"HWNC\" and kernel_layout == \"HWOI\":\n            batch = data_tensor.shape[2].value\n            in_channel = data_tensor.shape[3].value\n            out_channel = kernel_tensor.shape[2].value\n\n            if batch % 8 == 0 and in_channel % 16 == 0 and out_channel % 32 == 0:\n                return None\n\n            candidates = [(8, 16, 32)]\n            (db, di, do), extra_flops = pad_to_tensorcore(\n                batch, in_channel, out_channel, candidates\n            )\n\n            if extra_flops > 2:\n                logger.info(\"conv2d pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n                return None\n            logger.info(\"conv2d pad_to_tensorcore, extra_flops %s\", extra_flops)\n\n            return _pad_conv2d_HWNC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor)\n\n    elif data_dtype in [\"float16\"]:\n        if data_layout == \"NHWC\" and kernel_layout == \"HWIO\":\n            if isinstance(data_tensor.shape[0], tvm.tir.expr.Any):\n                # Skip legalize when the batch size is dynamic\n                return None\n\n            batch = data_tensor.shape[0].value\n            in_channel = data_tensor.shape[3].value\n            out_channel = kernel_tensor.shape[3].value\n\n            if (\n                (batch % 8 == 0 and in_channel % 16 == 0 and out_channel % 32 == 0)\n                or (batch % 16 == 0 and in_channel % 16 == 0 and out_channel % 16 == 0)\n                or (batch % 32 == 0 and in_channel % 16 == 0 and out_channel % 8 == 0)\n            ):\n                # no need to pad\n                return None\n\n            candidates = [(16, 16, 16), (32, 16, 8), (8, 16, 32)]\n            (db, di, do), extra_flops = pad_to_tensorcore(\n                batch, in_channel, out_channel, candidates\n            )\n\n            if extra_flops > 2:\n                logger.info(\"conv2d pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n                return None\n\n            logger.info(\"conv2d pad_to_tensorcore, extra_flops %s\", extra_flops)\n\n            return _pad_conv2d_NHWC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor)\n\n    elif data_dtype in [\"int4\", \"uint4\"]:\n        if data_layout == \"NHWC\" and kernel_layout == \"HWIO\":\n            batch = data_tensor.shape[0].value\n            in_channel = data_tensor.shape[3].value\n            out_channel = kernel_tensor.shape[3].value\n\n            if (\n                (batch % 8 == 0 and in_channel % 16 == 0 and out_channel % 32 == 0)\n                or (batch % 16 == 0 and in_channel % 16 == 0 and out_channel % 16 == 0)\n                or (batch % 32 == 0 and in_channel % 16 == 0 and out_channel % 8 == 0)\n            ):\n                # no need to pad\n                return None\n\n            candidates = [(16, 16, 16), (32, 16, 8), (8, 16, 32)]\n            (db, di, do), extra_flops = pad_to_tensorcore(\n                batch, in_channel, out_channel, candidates\n            )\n\n            if extra_flops > 2:\n                logger.info(\"conv2d pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n                return None\n\n            logger.info(\"conv2d pad_to_tensorcore, extra_flops %s\", extra_flops)\n\n            return _pad_conv2d_NHWC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor)\n\n        if data_layout == \"HWNC\" and kernel_layout == \"HWOI\":\n            batch = data_tensor.shape[2].value\n            in_channel = data_tensor.shape[3].value\n            out_channel = kernel_tensor.shape[2].value\n\n            if batch % 8 == 0 and in_channel % 32 == 0 and out_channel % 8 == 0:\n                return None\n\n            candidates = [(8, 32, 8)]\n            (db, di, do), extra_flops = pad_to_tensorcore(\n                batch, in_channel, out_channel, candidates\n            )\n\n            if extra_flops > 2:\n                logger.info(\"conv2d pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n                return None\n            logger.info(\"conv2d pad_to_tensorcore, extra_flops %s\", extra_flops)\n\n            return _pad_conv2d_HWNC(db, di, do, data, kernel, out_channel, new_attrs, output_tensor)\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_direct.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"The templates for cuda conv2d operators\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple\n\n\ndef schedule_direct_cuda(cfg, s, conv):\n    \"\"\"schedule optimized for batch size = 1\"\"\"\n\n    ##### space definition begin #####\n    n, f, y, x = s[conv].op.axis\n    rc, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_f\", f, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    # fallback support\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            target.kind.name, target.model, \"conv2d_nchw.cuda\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n\n    s[pad_data].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, f, y, x = s[output].op.axis\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, f, y, x = s[OL].op.axis\n    rc, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n    s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        n, f, y, x = s[load].op.axis\n        fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    N, CO, OH, OW = get_const_tuple(output.shape)\n    _, KH, KW, CI = get_const_tuple(kernel.shape)\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_hwcn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument\n\"\"\"Schedule for conv2d_hwcn with auto fusion\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom tvm.autotvm.task.space import SplitEntity\n\nfrom .. import nn, tag\n\n\n@autotvm.register_topi_compute(\"conv2d_hwcn.cuda\")\ndef conv2d_hwcn(cfg, data, kernel, strides, padding, dilation, out_dtype=\"float32\"):\n    \"\"\"Compute conv2d with HWCN layout on CUDA\"\"\"\n    return nn.conv2d_hwcn(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_hwcn.cuda\")\ndef schedule_conv2d_hwcn(cfg, outs):\n    \"\"\"Schedule for conv2d_hwcn and any element-wise operations.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_hwcn in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d_hwcn.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    sch = te.create_schedule([x.op for x in outs])\n\n    def schedule(Apad, W, B):\n        \"\"\"Schedule conv2d_hwcn\"\"\"\n        sch[Apad].compute_inline()\n        AA = sch.cache_read(Apad, \"shared\", [B])\n        WW = sch.cache_read(W, \"shared\", [B])\n        AL = sch.cache_read(AA, \"local\", [B])\n        WL = sch.cache_read(WW, \"local\", [B])\n\n        if B.op in sch.outputs:\n            Out = B\n            BL = sch.cache_write(Out, \"local\")\n        else:\n            Out = sch.outputs[0].output(0)\n            sch[B].set_scope(\"local\")\n            BL = B\n\n        hi, wi, fi, ni = sch[Out].op.axis\n\n        # Create tuning space\n        n_thread_cand = [1, 2, 4, 8, 16, 32]\n        vthread_cand = [1, 2, 4, 8]\n\n        cfg.define_split(\n            \"tile_fi\",\n            fi,\n            num_outputs=4,\n            filter=lambda x: (x.size[1] in vthread_cand and x.size[2] in n_thread_cand),\n        )\n        cfg.define_split(\n            \"tile_ni\",\n            ni,\n            num_outputs=4,\n            filter=lambda x: (x.size[1] in vthread_cand and x.size[2] in n_thread_cand),\n        )\n\n        if cfg.is_fallback:\n            cfg[\"tile_fi\"] = SplitEntity([-1, 2, 8, 4])\n            cfg[\"tile_ni\"] = SplitEntity([-1, 2, 8, 4])\n\n        # Scheduling\n        step = 8\n\n        bz = sch[Out].fuse(hi, wi)\n        by, tyz, ty, fi = cfg[\"tile_fi\"].apply(sch, Out, fi)\n        bx, txz, tx, ni = cfg[\"tile_ni\"].apply(sch, Out, ni)\n        sch[Out].reorder(bz, by, bx, tyz, txz, ty, tx, fi, ni)\n\n        sch[Out].bind(bz, te.thread_axis(\"blockIdx.z\"))\n        sch[Out].bind(by, te.thread_axis(\"blockIdx.y\"))\n        sch[Out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        sch[Out].bind(tyz, te.thread_axis(\"vthread\"))\n        sch[Out].bind(txz, te.thread_axis(\"vthread\"))\n        sch[Out].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        sch[Out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n        # Schedule BL local write\n        sch[BL].compute_at(sch[Out], tx)\n        yi, xi, fi, ni = sch[BL].op.axis\n        ry, rx, rc = sch[BL].op.reduce_axis\n        rco, rci = sch[BL].split(rc, factor=step)\n        sch[BL].reorder(rco, ry, rx, rci, fi, ni)\n        fuse_index = sch[BL].fuse(ry, rx)\n        fuse_index = sch[BL].fuse(fuse_index, rco)\n        rx = fuse_index\n\n        sch[AA].compute_at(sch[BL], rx)\n        sch[WW].compute_at(sch[BL], rx)\n        sch[AL].compute_at(sch[BL], rci)\n        sch[WL].compute_at(sch[BL], rci)\n        # Schedule for A's shared memory load\n        yi, xi, ci, ni = sch[AA].op.axis\n        ty, ci = sch[AA].split(ci, nparts=cfg[\"tile_fi\"].size[2])\n        tx, ni = sch[AA].split(ni, nparts=cfg[\"tile_ni\"].size[2])\n        _, ni = sch[AA].split(ni, factor=4)\n        sch[AA].reorder(ty, tx, yi, xi, ci, ni)\n        sch[AA].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        sch[AA].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        sch[AA].vectorize(ni)\n        # Schedule for W's shared memory load\n        yi, xi, ci, fi = sch[WW].op.axis\n        ty, ci = sch[WW].split(ci, nparts=cfg[\"tile_fi\"].size[2])\n        tx, fi = sch[WW].split(fi, nparts=cfg[\"tile_ni\"].size[2])\n        _, fi = sch[WW].split(fi, factor=4)\n        sch[WW].reorder(ty, tx, yi, xi, ci, fi)\n        sch[WW].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        sch[WW].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        sch[WW].vectorize(fi)\n\n    scheduled_ops = []\n\n    def traverse(operator):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        if tag.is_broadcast(operator.tag):\n            if operator not in sch.outputs:\n                sch[operator].compute_inline()\n            for tensor in operator.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        elif operator.tag == \"conv2d_hwcn\":\n            Apad = operator.input_tensors[0]\n            W = operator.input_tensors[1]\n            if isinstance(W.op, tvm.te.ComputeOp) and \"dilate\" in W.op.tag:\n                sch[W].compute_inline()\n            B = operator.output(0)\n            schedule(Apad, W, B)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % operator.tag)\n\n        scheduled_ops.append(operator)\n\n    traverse(outs[0].op)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_hwnc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-function-args\n# pylint: disable=too-many-statements, unused-argument, too-many-arguments\n\"\"\"Tensorcore template for cuda backend\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.target import Target\nfrom tvm.topi.cuda.injective import schedule_injective_from_existing\nfrom ..utils import get_const_tuple, traverse_inline, simplify, tag\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple\nfrom .tensor_intrin import intrin_wmma_load_matrix_A\nfrom .tensor_intrin import intrin_wmma_load_matrix_W\nfrom .tensor_intrin import intrin_wmma_store_matrix\nfrom .tensor_intrin import intrin_wmma_gemm\n\n\ndef unpack_HWNCnc_to_hwnc(packed_out, out_dtype):\n    \"\"\"Unpack conv2d_hwnc output from layout hwncnc to hwnc\n\n     Parameters\n    -----------\n    packed_out : tvm.te.Tensor\n        The output tensor of conv2d_hwnc.\n\n    out_dtype : str\n        The output dtype.\n\n    Returns\n    -------\n    unpacked_out : tvm.te.Tensor\n        The unpacked output tensor in hwnc layout.\n    \"\"\"\n    H, W, N, O, wmma_m, wmma_n = get_const_tuple(packed_out.shape)\n\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n\n    oshape = (H, W, N * wmma_m, O * wmma_n)\n    unpacked_out = te.compute(\n        oshape,\n        lambda h, w, n, o: packed_out[\n            h, w, idxdiv(n, wmma_m), idxdiv(o, wmma_n), idxmod(n, wmma_m), idxmod(o, wmma_n)\n        ].astype(out_dtype),\n        name=\"output_unpack\",\n        tag=tag.INJECTIVE + \",unpack_hwncc\",\n    )\n    return unpacked_out\n\n\ndef conv2d_hwnc_tensorcore(data, kernel, strides, padding, dilation, in_dtype, out_dtype=\"int32\"):\n    \"\"\" \"Compute conv2d with tensorcore for HWNC layout with int8/int4\"\"\"\n    assert data.dtype in (\"int4\", \"uint4\", \"int8\", \"uint8\")\n    assert kernel.dtype in (\"int4\", \"uint4\", \"int8\", \"uint8\")\n    packed_out = hwnc_tensorcore_cuda(data, kernel, strides, padding, dilation, out_dtype)\n    return unpack_HWNCnc_to_hwnc(packed_out, out_dtype)\n\n\n@autotvm.register_topi_compute(\"conv2d_HWNCnc_tensorcore.cuda\")\ndef hwnc_tensorcore_cuda(cfg, Input, Filter, stride, padding, dilation, out_dtype=\"int32\"):\n    \"\"\"Compute declaration for tensorcore\"\"\"\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    in_dtype = Input.dtype\n\n    if in_dtype in [\"int4\", \"uint4\"]:\n        wmma_n = wmma_m = 8\n        wmma_k = 32\n    else:\n        wmma_m = 8\n        wmma_n = 32\n        wmma_k = 16\n\n    pre_computed = len(Filter.shape) == 6\n    in_height, in_width, batch, in_channels = get_const_tuple(Input.shape)\n    if pre_computed:\n        kernel_h, kernel_w, oc_chunk, _, oc_block_factor, _ = get_const_tuple(Filter.shape)\n        num_filter = oc_block_factor * oc_chunk\n    else:\n        kernel_h, kernel_w, num_filter, _ = get_const_tuple(Filter.shape)\n\n    if in_dtype in [\"int4\", \"uint4\"]:\n        assert batch % 8 == 0 and in_channels % 32 == 0 and num_filter % 8 == 0\n    else:\n        assert batch % 8 == 0 and in_channels % 16 == 0 and num_filter % 32 == 0, (\n            \"The shape of (batch, in_channels, num_filter) \"\n            \"must be multiple of (8, 16, 32) for int8, \"\n            \"and (8, 32, 8) for int4\"\n        )\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_channels = num_filter\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n\n    cfg.add_flop(\n        2 * batch * out_height * out_width * out_channels * in_channels * kernel_h * kernel_w\n    )\n\n    # Input feature map: (H, W, N, IC, n, ic)\n    data_shape = (in_height, in_width, batch // wmma_m, in_channels // wmma_k, wmma_m, wmma_k)\n\n    # Kernel: (H, W, OC, IC, oc, ic)\n    kernel_shape = (\n        kernel_h,\n        kernel_w,\n        out_channels // wmma_n,\n        in_channels // wmma_k,\n        wmma_n,\n        wmma_k,\n    )\n\n    # Reduction axes\n    kh = te.reduce_axis((0, kernel_h), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_w), name=\"kw\")\n    ic = te.reduce_axis((0, in_channels // wmma_k), name=\"ic\")\n    ii = te.reduce_axis((0, wmma_k), name=\"ii\")\n\n    if pre_computed:\n        packed_kernel = Filter\n    else:\n        packed_kernel = te.compute(\n            kernel_shape,\n            lambda kh, kw, o, i, oo, ii: Filter[kh, kw, o * wmma_n + oo, i * wmma_k + ii],\n            name=\"packed_kernel\",\n        )\n\n    packed_data = te.compute(\n        data_shape, lambda h, w, n, i, nn, ii: Input[h, w, n * wmma_m + nn, i * wmma_k + ii]\n    )\n\n    pad_before = [pad_top, pad_left, 0, 0, 0, 0]\n    pad_after = [pad_down, pad_right, 0, 0, 0, 0]\n    pad_data = pad(packed_data, pad_before, pad_after, name=\"pad_data\")\n\n    Conv = te.compute(\n        (out_height, out_width, batch // wmma_m, out_channels // wmma_n, wmma_m, wmma_n),\n        lambda h, w, n, o, nn, oo: te.sum(\n            (\n                pad_data[h * stride_h + kh, w * stride_w + kw, n, ic, nn, ii].astype(\"int32\")\n                * packed_kernel[kh, kw, o, ic, oo, ii].astype(\"int32\")\n            ),\n            axis=[ic, kh, kw, ii],\n        ),\n        name=\"Conv\",\n        tag=\"conv2d_HWNCnc_tensorcore\",\n    )\n    return Conv\n\n\ndef schedule_hwnc_tensorcore_cuda(cfg, s, Conv):\n    \"\"\"Schedule tensorcore template\"\"\"\n    pad_data, packed_kernel = s[Conv].op.input_tensors\n    ic, kh, kw, ii = s[Conv].op.reduce_axis\n    packed_data = s[pad_data].op.input_tensors[0]\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    # Designate the memory hierarchy\n    AS = s.cache_read(pad_data, \"shared\", [Conv])\n    WS = s.cache_read(packed_kernel, \"shared\", [Conv])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\n    WF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\n    ConvF = s.cache_write(Conv, \"wmma.accumulator\")\n\n    if Conv.op in s.outputs:\n        output = Conv\n        ConvS = s.cache_read(ConvF, \"shared\", [Conv])\n        OL = ConvS\n    else:\n        output = s.outputs[0].output(0)\n        s[Conv].set_scope(\"shared\")\n        OL = Conv\n\n    out_dtype = Conv.dtype\n\n    if isinstance(packed_kernel.op, te.tensor.ComputeOp) and packed_kernel.name == \"packed_kernel\":\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            s[packed_kernel].pragma(s[packed_kernel].op.axis[0], \"debug_skip_region\")\n        else:\n            with Target(\"cuda\"):\n                schedule_injective_from_existing(s, packed_kernel)\n\n    if isinstance(pad_data.op, te.tensor.ComputeOp) and \"pad\" in pad_data.op.tag:\n        s[pad_data].compute_inline()\n        data = pad_data.op.input_tensors[0]\n\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # skip this part during tuning to make recrods accurate\n            # this part will be pre-computed during NNVM's pre-compute optimization pass\n            s[pad_data].pragma(s[pad_data].op.axis[0], \"debug_skip_region\")\n    else:\n        data = pad_data\n        s[data].compute_inline()\n\n    data_dtype = data.dtype\n    kernel_dtype = packed_kernel.dtype\n\n    # Schedule for autotvm\n    cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n    cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n    cfg.define_knob(\"warp_row_tiles\", [1, 2, 4, 8, 16])\n    cfg.define_knob(\"warp_col_tiles\", [1, 2, 4, 8, 16])\n    cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n    cfg.define_knob(\"split_block_k_nums\", [1, 2, 4, 8, 16, 32])\n    cfg.define_knob(\"vector_ws\", [1, 8])\n    cfg.define_knob(\"vector_as\", [1, 8, 16])\n\n    block_row_warps = cfg[\"block_row_warps\"].val\n    block_col_warps = cfg[\"block_col_warps\"].val\n    warp_row_tiles = cfg[\"warp_row_tiles\"].val\n    warp_col_tiles = cfg[\"warp_col_tiles\"].val\n    chunk = cfg[\"chunk\"].val\n    vector_as = cfg[\"vector_as\"].val\n    vector_ws = cfg[\"vector_ws\"].val\n    split_block_k_nums = cfg[\"split_block_k_nums\"].val\n\n    s[packed_data].compute_inline()\n\n    if data_dtype in [\"int4\", \"uint4\"]:\n        wmma_m = wmma_n = 8\n        wmma_k = 32\n    else:\n        wmma_m = 8\n        wmma_n = 32\n        wmma_k = 16\n\n    warp_size = 32\n\n    # Schedule for output\n    if len(s[output].op.axis) == 4:\n        (\n            hc,\n            wc,\n            nc,\n            oc,\n        ) = output.op.axis\n        nc, nnc = s[output].split(nc, factor=wmma_m)\n        oc, ooc = s[output].split(oc, factor=wmma_n)\n    else:\n        hc, wc, nc, oc, nnc, ooc = output.op.axis\n\n    kernel_scope, hc = s[output].split(hc, nparts=1)\n\n    block_k = s[output].fuse(hc, wc)\n    block_k, split_block_k = s[output].split(block_k, factor=split_block_k_nums)\n    nc, nci = s[output].split(nc, factor=warp_row_tiles)\n    block_i, nc = s[output].split(nc, factor=block_row_warps)\n    oc, oci = s[output].split(oc, factor=warp_col_tiles)\n    block_j, oc = s[output].split(oc, factor=block_col_warps)\n    s[output].reorder(block_k, split_block_k, block_i, block_j, nc, oc, nci, oci, nnc, ooc)\n    t = s[output].fuse(nnc, ooc)\n    _, tx = s[output].split(t, factor=warp_size)\n    s[output].bind(block_k, block_z)\n    s[output].bind(block_i, block_x)\n    s[output].bind(block_j, block_y)\n    s[output].bind(tx, thread_x)\n    s[output].bind(nc, thread_y)\n    s[output].bind(oc, thread_z)\n\n    # Schedule wmma store\n    s[OL].compute_at(s[output], block_j)\n    hc, wc, nc, oc, nnc, ooc = OL.op.axis\n    oc, oci = s[OL].split(oc, factor=warp_col_tiles)\n    _, oc = s[OL].split(oc, factor=block_col_warps)\n    nc, nci = s[OL].split(nc, factor=warp_row_tiles)\n    _, nc = s[OL].split(nc, factor=block_row_warps)\n    s[OL].reorder(nc, oc, nci, oci, nnc, ooc)\n    s[OL].bind(nc, thread_y)\n    s[OL].bind(oc, thread_z)\n\n    # Schedule local computation\n    s[ConvF].compute_at(s[OL], oc)\n    _, _, n, o, nnf, oof = ConvF.op.axis\n    ko, ki = s[ConvF].split(ic, factor=chunk)\n    s[ConvF].reorder(ko, kh, ki, kw, n, o, nnf, oof, ii)\n\n    cfg.define_reorder(\"reorder_inner\", [ko, kh], policy=\"all\")\n    cfg[\"reorder_inner\"].apply(s, ConvF, [ko, kh])\n    cfg[\"reorder_inner\"].apply(s, ConvF, [ki, kw])\n\n    # Move intermediate computation into each output compute tile\n    s[AF].compute_at(s[ConvF], kw)\n    s[WF].compute_at(s[ConvF], kw)\n\n    # Schedule for A's share memory\n    s[AS].compute_at(s[ConvF], ko)\n\n    _, _, n, _, nn, ii = AS.op.axis\n    tx, xo = s[AS].split(n, nparts=block_row_warps)\n    ty, _ = s[AS].split(xo, nparts=block_col_warps)\n    t = s[AS].fuse(nn, ii)\n    to, ti = s[AS].split(t, nparts=warp_size)\n    ti, _t = s[AS].split(ti, factor=vector_as)\n    s[AS].bind(tx, thread_y)\n    s[AS].bind(ty, thread_z)\n    s[AS].bind(to, thread_x)\n    s[AS].vectorize(_t)\n\n    # Schedule for W's share memory\n    s[WS].compute_at(s[ConvF], kw)\n    kh, kw, ic, o, ii, oo = WS.op.axis\n    tx, xo = s[WS].split(o, nparts=block_row_warps)\n    ty, _ = s[WS].split(xo, nparts=block_col_warps)\n    t = s[WS].fuse(ii, oo)\n    to, ti = s[WS].split(t, nparts=warp_size)\n    ti, _t = s[WS].split(ti, factor=vector_ws)\n    s[WS].bind(tx, thread_y)\n    s[WS].bind(ty, thread_z)\n    s[WS].bind(to, thread_x)\n    s[WS].vectorize(ti)\n\n    # double buffer\n    cfg.define_knob(\"AS_double_buffer\", [0, 1])\n    cfg.define_knob(\"WS_double_buffer\", [0, 1])\n    if cfg[\"AS_double_buffer\"].val:\n        s[AS].double_buffer()\n    if cfg[\"WS_double_buffer\"].val:\n        s[WS].double_buffer()\n\n    # unroll\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", False)\n\n    shape = (wmma_m, wmma_n, wmma_k)\n\n    AS_shape = (wmma_m, wmma_k)\n    AL_shape = (wmma_m, wmma_k)\n    WS_shape = (wmma_n, wmma_k)\n    WL_shape = (wmma_n, wmma_k)\n    CL_shape = (wmma_m, wmma_n)\n    CS_shape = (wmma_m, wmma_n)\n\n    AL_gemm = te.placeholder(AL_shape, name=\"A\", dtype=data_dtype)\n    WL_gemm = te.placeholder(WL_shape, name=\"B\", dtype=kernel_dtype)\n    k_gemm = te.reduce_axis((0, wmma_k), name=\"k\")\n    CL_compute = te.compute(\n        CL_shape,\n        lambda ii, jj: te.sum(\n            (AL_gemm[ii, k_gemm].astype(\"int32\") * WL_gemm[jj, k_gemm].astype(\"int32\")), axis=k_gemm\n        ),\n        name=\"C\",\n    )\n\n    AL_strides = [wmma_k, 1]\n    AS_strides = [wmma_k, 1]\n    WL_strides = [wmma_k, 1]\n    WS_strides = [wmma_k, 1]\n    CL_strides = [wmma_n, 1]\n    CS_strides = [wmma_n, 1]\n\n    s[AF].tensorize(\n        AF.op.axis[-2],\n        intrin_wmma_load_matrix_A(\n            AL_strides, AS_strides, shape, \"row_major\", AS_shape, AL_shape, data_dtype\n        ),\n    )\n\n    s[WF].tensorize(\n        WF.op.axis[-2],\n        intrin_wmma_load_matrix_W(\n            WL_strides, WS_strides, shape, \"col_major\", WS_shape, WL_shape, kernel_dtype\n        ),\n    )\n\n    s[OL].tensorize(\n        nnc, intrin_wmma_store_matrix(CS_strides, CL_strides, shape, out_dtype, CL_shape, CS_shape)\n    )\n\n    s[ConvF].tensorize(\n        nnf,\n        intrin_wmma_gemm(AL_gemm, WL_gemm, CL_compute, AL_strides, WL_strides, CL_strides, shape),\n    )\n\n    return s\n\n\n@autotvm.register_topi_schedule(\"conv2d_HWNCnc_tensorcore.cuda\")\ndef schedule_conv2d_hwnc_tensorcore(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_HWNCnc_tensorcore\" in op.tag:\n            schedule_hwnc_tensorcore_cuda(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n# pylint: disable=no-value-for-parameter\n\"\"\"Int8 conv2d in NCHWc layout\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .injective import schedule_injective_from_existing\nfrom .tensor_intrin import dp4a\nfrom ..nn.pad import pad\nfrom ..nn.conv2d import unpack_NCHWc_to_nchw\nfrom ..nn.utils import get_pad_tuple\nfrom ..utils import get_const_tuple, traverse_inline\n\n\ndef conv2d_nchw_int8(data, kernel, strides, padding, dilation, out_dtype=\"int32\"):\n    \"\"\"Compute conv2d internally using conv2d_nchwc layout for int8 dtype\"\"\"\n    assert data.dtype in (\"int8\", \"uint8\")\n    assert kernel.dtype in (\"int8\", \"uint8\")\n    assert data.dtype == kernel.dtype\n    packed_out = conv2d_NCHWc_int8(data, kernel, strides, padding, dilation, \"NCHW\", out_dtype)\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_conv2d_nchw_int8(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    return schedule_conv2d_NCHWc_int8(outs)\n\n\n@autotvm.register_topi_compute(\"conv2d_NCHWc_int8.cuda\")\ndef conv2d_NCHWc_int8(cfg, data, kernel, stride, padding, dilation, layout, out_dtype):\n    \"\"\"Convolution operator in NCHW[x]c layout for int8.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width] or\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width] or\n        6-D with shape [num_filter_chunk, in_channel_chunk, filter_height,\n        filter_width, num_filter_block, in_channel_block]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding: int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    layout : str\n        layout of data\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block]\n    \"\"\"\n    assert layout in [\"NCHW\", \"NCHW4c\"]\n    ic_block_factor = 4\n    oc_block_factor = 4\n\n    pre_computed = len(kernel.shape) == 6\n    if not pre_computed:\n        batch, channels, height, width = get_const_tuple(data.shape)\n        assert (\n            channels % ic_block_factor == 0\n        ), \"Number of input channels should be multiple of {}\".format(ic_block_factor)\n        packed_data = te.compute(\n            (batch, channels // ic_block_factor, height, width, ic_block_factor),\n            lambda n, c, h, w, vc: data[n, c * ic_block_factor + vc, h, w],\n            name=\"packed_data\",\n        )\n\n        out_channels, in_channels, kernel_h, kernel_w = get_const_tuple(kernel.shape)\n        assert (\n            out_channels % oc_block_factor == 0\n        ), \"Number of output channels should be multiple of {}\".format(oc_block_factor)\n        packed_kernel = te.compute(\n            (\n                out_channels // oc_block_factor,\n                in_channels // ic_block_factor,\n                kernel_h,\n                kernel_w,\n                oc_block_factor,\n                ic_block_factor,\n            ),\n            lambda oc_chunk, ic_chunk, kh, kw, oc_block, ic_block: kernel[\n                oc_chunk * oc_block_factor + oc_block, ic_chunk * ic_block_factor + ic_block, kh, kw\n            ],\n            name=\"packed_kernel\",\n        )\n\n    else:\n        packed_data = data\n        packed_kernel = kernel\n\n    batch, ic_chunk, in_height, in_width, ic_block = get_const_tuple(packed_data.shape)\n    oc_chunk, ic_chunk, kernel_h, kernel_w, oc_block, ic_block = get_const_tuple(\n        packed_kernel.shape\n    )\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    # compute graph\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down, pad_right, 0]\n    pad_data = pad(packed_data, pad_before, pad_after, name=\"pad_data\")\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    out_height = (in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1\n    out_width = (in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1\n    oshape = (batch, oc_chunk, out_height, out_width, oc_block)\n\n    icc = te.reduce_axis((0, ic_chunk), name=\"ic_chunk\")\n    icb = te.reduce_axis((0, ic_block), name=\"ic_block\")\n    kh = te.reduce_axis((0, kernel_h), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_w), name=\"kw\")\n\n    packed_kernel_dtype = packed_kernel.dtype\n    packed_dtype = \"int32\" if packed_kernel_dtype == \"int8\" else \"uint32\"\n    conv = te.compute(\n        oshape,\n        lambda n, oc_chunk, oh, ow, oc_block: te.sum(\n            pad_data[\n                n, icc, oh * stride_h + kh * dilation_h, ow * stride_w + kw * dilation_w, icb\n            ].astype(packed_dtype)\n            * packed_kernel[oc_chunk, icc, kh, kw, oc_block, icb].astype(packed_dtype),\n            axis=[icc, kh, kw, icb],\n        ),\n    )\n\n    output = te.compute(\n        oshape,\n        lambda n, oc_chunk, oh, ow, oc_block: conv[n, oc_chunk, oh, ow, oc_block].astype(out_dtype),\n        tag=\"conv2d_NCHWc_int8\",\n    )\n\n    # num flop\n    num_flop = (\n        batch\n        * oc_chunk\n        * oc_block\n        * out_height\n        * out_width\n        * ic_chunk\n        * ic_block\n        * kernel_h\n        * kernel_w\n        * 2\n    )\n    cfg.add_flop(num_flop)\n\n    return output\n\n\n@autotvm.register_topi_schedule(\"conv2d_NCHWc_int8.cuda\")\ndef schedule_conv2d_NCHWc_int8(cfg, outs):\n    \"\"\"Schedule conv2d int8 NCHWc template\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv2d_NCHWc_int8\":\n            _schedule_conv2d_NCHWc_int8(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_conv2d_NCHWc_int8(cfg, s, output):\n    conv = output.op.input_tensors[0]\n    packed_data, packed_kernel = conv.op.input_tensors\n\n    if isinstance(packed_data.op, tvm.te.ComputeOp) and \"pad\" in packed_data.op.tag:\n        pad_data = packed_data\n        packed_data = pad_data.op.input_tensors[0]\n    else:\n        pad_data = packed_data\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # skip this part during tuning to make recrods accurate\n        # this part will be pre-computed during NNVM's pre-compute optimization pass\n        s[packed_data].pragma(s[packed_data].op.axis[0], \"debug_skip_region\")\n        s[packed_kernel].pragma(s[packed_kernel].op.axis[0], \"debug_skip_region\")\n    else:\n        if isinstance(packed_kernel.op, tvm.te.ComputeOp) and packed_kernel.name == \"packed_kernel\":\n            # data and kernel are not pre-computed, schedule layout transform here\n            schedule_injective_from_existing(s, packed_data)\n            schedule_injective_from_existing(s, packed_kernel)\n\n    if pad_data != packed_data:\n        s[pad_data].compute_inline()\n\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [conv])\n    WW = s.cache_read(packed_kernel, \"shared\", [conv])\n\n    s[conv].set_scope(\"local\")\n\n    # handle bias\n    if output.op not in s.outputs:\n        s[output].compute_inline()\n        output = s.outputs[0].output(0)\n\n    # tile and bind spatial axes\n    if len(s[output].op.axis) == 5:\n        n, f, y, x, c = s[output].op.axis\n    else:\n        # For task extraction of auto-tuning, the expected output is 4D.  Since auto-tuning tasks\n        # are created from scratch, therefore the real auto-tuning will still happen on 5D output.\n        n, f, y, x = s[output].op.axis\n\n    cfg.define_split(\"tile_n\", cfg.axis(n), num_outputs=4)\n    cfg.define_split(\"tile_f\", cfg.axis(f), num_outputs=4)\n    cfg.define_split(\"tile_y\", cfg.axis(y), num_outputs=4)\n    cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4)\n\n    # this is the scope to attach global config inside this kernel\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    s[output].reorder(bn, bf, by, bx, vn, vf, vy, vx, tn, tf, ty, tx, ni, fi, yi, xi)\n    s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(bf, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(s[output].fuse(by, bx), te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vn, te.thread_axis(\"vthread\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n\n    cfg.define_knob(\"fuse_yx\", [0, 1])  # fuse ty,tx or tn,tf\n    if cfg[\"fuse_yx\"].val:\n        s[output].bind(tn, te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(tf, te.thread_axis(\"threadIdx.y\"))\n        tyx = s[output].fuse(ty, tx)\n        s[output].bind(tyx, te.thread_axis(\"threadIdx.x\"))\n        s[conv].compute_at(s[output], tyx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2]\n        n_ty = cfg[\"tile_f\"].size[2]\n        n_tx = cfg[\"tile_y\"].size[2] * cfg[\"tile_x\"].size[2]\n    else:\n        s[output].bind(s[output].fuse(tn, tf), te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[conv].compute_at(s[output], tx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_f\"].size[2]\n        n_ty = cfg[\"tile_y\"].size[2]\n        n_tx = cfg[\"tile_x\"].size[2]\n\n    # tile and bind reduction axes\n    n, f, y, x, c = s[conv].op.axis\n\n    rc, ry, rx, rc_block = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=2)\n    cfg.define_split(\"tile_ry\", cfg.axis(ry), num_outputs=2)\n    cfg.define_split(\"tile_rx\", cfg.axis(rx), num_outputs=2)\n    rco, rci = cfg[\"tile_rc\"].apply(s, conv, rc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x, c, rc_block)\n\n    cfg.define_reorder(\"reorder_inner\", [rco, ryo, rxo], policy=\"all\")\n    cfg[\"reorder_inner\"].apply(s, conv, [rco, ryo, rxo])\n    cfg[\"reorder_inner\"].apply(s, conv, [rci, ryi, rxi])\n\n    _, rc_block = s[conv].split(rc_block, factor=4)\n    target = tvm.target.Target.current(allow_none=False)\n    do_tensorize = \"+dotprod\" in target.mattr or target.supports_integer_dot_product\n\n    if do_tensorize:\n        dtypes = (pad_data.dtype, packed_kernel.dtype)\n        s[conv].tensorize(rc_block, dp4a(\"shared\", \"shared\", \"local\", dtypes))\n\n    cache_loc = [rco, ryo, rxo][cfg[\"reorder_inner\"].perm[-1]]\n    s[AA].compute_at(s[conv], cache_loc)\n    s[WW].compute_at(s[conv], cache_loc)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        c = s[load].op.axis[-1]\n        c_outer, c = s[load].split(c, factor=4)\n        s[load].vectorize(c)\n        fused = s[load].op.axis[:-1] + [c_outer]\n        fused = s[load].fuse(*fused)\n\n        fused, tx = s[load].split(fused, factor=n_tx)\n        fused, ty = s[load].split(fused, factor=n_ty)\n        fused, tz = s[load].split(fused, factor=n_tz)\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # double buffer\n    cfg.define_knob(\"AA_double_buffer\", [0, 1])\n    cfg.define_knob(\"WW_double_buffer\", [0, 1])\n    if cfg[\"AA_double_buffer\"].val:\n        s[AA].double_buffer()\n    if cfg[\"WW_double_buffer\"].val:\n        s[WW].double_buffer()\n\n    # unroll\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", False)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_nhwc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-function-args\n# pylint: disable=too-many-statements, unused-argument, too-many-arguments\n\"\"\"Tensorcore template for cuda backend\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple, traverse_inline, simplify\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple\nfrom .tensor_intrin import intrin_wmma_load_matrix_A\nfrom .tensor_intrin import intrin_wmma_load_matrix_W\nfrom .tensor_intrin import intrin_wmma_store_matrix\nfrom .tensor_intrin import intrin_wmma_gemm\n\n\ndef nhwc_tensorcore_cuda(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"Compute declaration for tensorcore\"\"\"\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_height, in_width, in_channel = get_const_tuple(Input.shape)\n    kernel_h, kernel_w, _, num_filter = get_const_tuple(Filter.shape)\n    assert (\n        (batch % 16 == 0 and in_channel % 16 == 0 and num_filter % 16 == 0)\n        or (batch % 8 == 0 and in_channel % 16 == 0 and num_filter % 32 == 0)\n        or (batch % 32 == 0 and in_channel % 16 == 0 and num_filter % 8 == 0)\n    ), (\n        \"The shape of (batch, in_channel, num_filter) \"\n        \"must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32) for now\"\n    )\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = num_filter\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    PaddedInput = pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    # convert data type of input feature maps and weights\n    # TODO: add checking here, datatype casting may cause precision loss\n    TransPaddedInput = te.compute(\n        PaddedInput.shape, lambda n, h, w, c: PaddedInput[n, h, w, c].astype(\"float16\")\n    )\n    TransFilter = te.compute(Filter.shape, lambda h, w, i, o: Filter[h, w, i, o].astype(\"float16\"))\n    Output = te.compute(\n        (batch, out_height, out_width, out_channel),\n        lambda nn, yy, xx, ff: te.sum(\n            TransPaddedInput[\n                nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rc\n            ].astype(out_dtype)\n            * TransFilter[ry, rx, rc, ff].astype(out_dtype),\n            axis=[ry, rx, rc],\n        ),\n        name=\"Conv2dOutput\",\n        tag=\"conv2d_nhwc_tensorcore\",\n    )\n    return Output\n\n\ndef schedule_nhwc_tensorcore_cuda(cfg, s, Conv):\n    \"\"\"Schedule tensorcore template\"\"\"\n    kh, kw, ic = s[Conv].op.reduce_axis\n    out_dtype = Conv.dtype\n    trans_paddata, kernel = s[Conv].op.input_tensors\n    in_dtype = trans_paddata.dtype\n    batch, _, _, _ = get_const_tuple(Conv.shape)\n    _, _, _, out_channels = get_const_tuple(kernel.shape)\n    paddata = s[trans_paddata].op.input_tensors\n\n    # inline the pad and dtype transform\n    s[trans_paddata].compute_inline()\n    s[kernel].compute_inline()\n    s[paddata[0]].compute_inline()\n\n    # Designate the memory hierarchy\n    AS = s.cache_read(trans_paddata, \"shared\", [Conv])\n    WS = s.cache_read(kernel, \"shared\", [Conv])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\n    WF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\n    ConvF = s.cache_write(Conv, \"wmma.accumulator\")\n\n    if Conv.op in s.outputs:\n        output = Conv\n        ConvS = s.cache_read(ConvF, \"shared\", [Conv])\n        OL = ConvS\n    else:\n        output = s.outputs[0].output(0)\n        s[Conv].set_scope(\"shared\")\n        OL = Conv\n\n    # Schedule for autotvm\n    cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n    cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n    cfg.define_knob(\"warp_row_tiles\", [1, 2, 4])\n    cfg.define_knob(\"warp_col_tiles\", [1, 2, 4])\n    cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n    cfg.define_knob(\"offset\", [0, 8])\n    cfg.define_knob(\"vector_width\", [1, 2, 4, 8])\n\n    if batch % 16 == 0 and out_channels % 16 == 0:\n        cfg.define_knob(\"wmma_m\", [16, 8, 32])\n    elif batch % 8 == 0 and out_channels % 32 == 0:\n        cfg.define_knob(\"wmma_m\", [8, 16, 32])\n    elif batch % 32 == 0 and out_channels % 8 == 0:\n        cfg.define_knob(\"wmma_m\", [32, 16, 8])\n\n    # fallback support\n    target = tvm.target.Target.current()\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            target.kind.name, target.model, \"conv2d_nhwc_tensorcore.cuda\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n\n    block_row_warps = cfg[\"block_row_warps\"].val\n    block_col_warps = cfg[\"block_col_warps\"].val\n    warp_row_tiles = cfg[\"warp_row_tiles\"].val\n    warp_col_tiles = cfg[\"warp_col_tiles\"].val\n    chunk = cfg[\"chunk\"].val\n    offset = cfg[\"offset\"].val\n    wmma_m = cfg[\"wmma_m\"].val\n    vector_width = cfg[\"vector_width\"].val\n\n    wmma_k = 16\n    if wmma_m == 16:\n        wmma_n = 16\n    elif wmma_m == 8:\n        wmma_n = 32\n    elif wmma_m == 32:\n        wmma_n = 8\n\n    warp_size = 32\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    # Define the intrin strides\n    def get_strides(extents):\n        return [np.prod(extents[i:]).tolist() for i in range(len(extents))]\n\n    AS_align = chunk * wmma_k + offset\n    WS_align = warp_col_tiles * block_col_warps * wmma_n + offset\n    block_factor_n = wmma_m * warp_row_tiles * block_row_warps\n    block_factor_o = wmma_n * warp_col_tiles * block_col_warps\n    CS_align = block_factor_o + offset\n    AS_strides = get_strides([1, 1, AS_align, 1])\n    AL_strides = get_strides([1, 1, wmma_k, 1])\n    WS_strides = get_strides([WS_align, 1])\n    WL_strides = get_strides([wmma_n * warp_col_tiles, 1])\n    CL_strides = get_strides([1, 1, wmma_n * warp_col_tiles, 1])\n    CS_strides = get_strides([1, 1, CS_align, 1])\n\n    # Schedule for output\n    nc, hc, wc, oc = output.op.axis\n    block_k = s[output].fuse(hc, wc)\n    s[output].bind(block_k, block_z)\n    block_i, nc = s[output].split(nc, factor=block_factor_n)\n    block_j, oc = s[output].split(oc, factor=block_factor_o)\n    s[output].reorder(block_k, block_i, block_j, nc, oc)\n    t = s[output].fuse(nc, oc)\n    t, ti = s[output].split(t, factor=vector_width)\n    t, tx = s[output].split(t, factor=warp_size)\n    t, ty = s[output].split(t, factor=block_row_warps)\n    t, tz = s[output].split(t, factor=block_col_warps)\n    s[output].bind(block_i, block_x)\n    s[output].bind(block_j, block_y)\n    s[output].bind(tz, thread_z)\n    s[output].bind(ty, thread_y)\n    s[output].bind(tx, thread_x)\n    s[output].vectorize(ti)\n\n    # Schedule wmma store\n    s[OL].compute_at(s[output], block_j)\n    nc, hc, wc, oc = OL.op.axis\n    s[OL].reorder(hc, wc, nc, oc)\n    s[OL].storage_align(wc, CS_align - 1, CS_align)\n    oc, ooc = s[OL].split(oc, factor=wmma_n)\n    oc, oci = s[OL].split(oc, factor=warp_col_tiles)\n    _, oc = s[OL].split(oc, factor=block_col_warps)\n    nc, nnc = s[OL].split(nc, factor=wmma_m)\n    nc, nci = s[OL].split(nc, factor=warp_row_tiles)\n    _, nc = s[OL].split(nc, factor=block_row_warps)\n    s[OL].reorder(nc, oc, nci, oci, nnc, ooc)\n    s[OL].bind(nc, thread_y)\n    s[OL].bind(oc, thread_z)\n\n    # Schedule wmma computation\n    s[ConvF].compute_at(s[OL], oc)\n    n, h, w, o = ConvF.op.axis\n    n, nnf = s[ConvF].split(n, factor=wmma_m)\n    o, oof = s[ConvF].split(o, factor=wmma_n)\n    ic, ii = s[ConvF].split(ic, factor=wmma_k)\n    ko, ki = s[ConvF].split(ic, factor=chunk)\n    s[ConvF].reorder(kh, kw, ko, ki, n, o, nnf, oof, ii)\n\n    s[AF].compute_at(s[ConvF], ki)\n    s[WF].compute_at(s[ConvF], ki)\n\n    # Schedule wmma load\n    n, h, w, i = AF.op.axis\n    n, nn = s[AF].split(n, factor=wmma_m)\n    i, ii = s[AF].split(i, factor=wmma_k)\n    s[AF].reorder(n, i, nn, ii)\n\n    kh, kw, i, o = WF.op.axis\n    i, ii = s[WF].split(i, factor=wmma_k)\n    o, oo = s[WF].split(o, factor=wmma_n)\n    s[WF].reorder(o, i, oo)\n    s[WF].reorder(i, o, ii, oo)\n\n    s[WS].compute_at(s[ConvF], ko)\n    s[AS].compute_at(s[ConvF], ko)\n\n    # Schedule for data's share memory\n    n, h, w, i = AS.op.axis\n    s[AS].reorder(h, w, n, i)\n    s[AS].storage_align(w, AS_align - 1, AS_align)\n    t = s[AS].fuse(n, i)\n    t, ti = s[AS].split(t, factor=vector_width)\n    t, tx = s[AS].split(t, factor=warp_size)\n    t, ty = s[AS].split(t, factor=block_row_warps)\n    _, tz = s[AS].split(t, factor=block_col_warps)\n    s[AS].bind(ty, thread_y)\n    s[AS].bind(tz, thread_z)\n    s[AS].bind(tx, thread_x)\n    s[AS].vectorize(ti)\n\n    # Schedule for kernel's share memory\n    kh, kw, ic, o = WS.op.axis\n    t = s[WS].fuse(ic, o)\n    s[WS].storage_align(ic, WS_align - 1, WS_align)\n    t, ti = s[WS].split(t, factor=vector_width)\n    t, tx = s[WS].split(t, factor=warp_size)\n    t, ty = s[WS].split(t, factor=block_row_warps)\n    _, tz = s[WS].split(t, factor=block_col_warps)\n    s[WS].bind(ty, thread_y)\n    s[WS].bind(tz, thread_z)\n    s[WS].bind(tx, thread_x)\n    s[WS].vectorize(ti)\n\n    shape = (wmma_m, wmma_n, wmma_k)\n\n    # tensorize the wmma process\n    AS_shape = (wmma_m, 1, 1, wmma_k)\n    AL_shape = (wmma_m, 1, 1, wmma_k)\n    WS_shape = (wmma_k, wmma_n)\n    WL_shape = (wmma_k, wmma_n)\n    CL_shape = (wmma_m, 1, 1, wmma_n)\n    CS_shape = (wmma_m, 1, 1, wmma_n)\n\n    AL_gemm = te.placeholder(AL_shape, name=\"A\", dtype=in_dtype)\n    WL_gemm = te.placeholder(WL_shape, name=\"B\", dtype=in_dtype)\n    k_gemm = te.reduce_axis((0, wmma_k), name=\"k\")\n    CL_compute = te.compute(\n        CL_shape,\n        lambda ii, t0, t1, jj: te.sum(\n            AL_gemm[ii, t0, t1, k_gemm].astype(out_dtype) * WL_gemm[k_gemm, jj].astype(out_dtype),\n            axis=k_gemm,\n        ),\n        name=\"C\",\n    )\n\n    s[AF].tensorize(\n        nn,\n        intrin_wmma_load_matrix_A(\n            AL_strides, AS_strides, shape, \"row_major\", AS_shape, AL_shape, in_dtype\n        ),\n    )\n    s[WF].tensorize(\n        ii,\n        intrin_wmma_load_matrix_W(\n            WL_strides, WS_strides, shape, \"row_major\", WS_shape, WL_shape, in_dtype\n        ),\n    )\n    s[OL].tensorize(\n        nnc, intrin_wmma_store_matrix(CS_strides, CL_strides, shape, out_dtype, CL_shape, CS_shape)\n    )\n    s[ConvF].tensorize(\n        nnf,\n        intrin_wmma_gemm(AL_gemm, WL_gemm, CL_compute, AL_strides, WL_strides, CL_strides, shape),\n    )\n\n    N, OH, OW, CO = get_const_tuple(output.shape)\n    KH, KW, CI, _ = get_const_tuple(kernel.shape)\n    cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW)\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_tensorcore.cuda\")\ndef conv2d_nhwc_tensorcore(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with tensorcore for NCHW layout\"\"\"\n    return nhwc_tensorcore_cuda(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_tensorcore.cuda\")\ndef schedule_conv2d_nhwc_tensorcore(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc_tensorcore\" in op.tag:\n            schedule_nhwc_tensorcore_cuda(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_nhwc_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n# pylint: disable=too-many-arguments,too-many-locals\n# pylint: disable=too-many-statements\n\"\"\"Winograd template for cuda backend\"\"\"\n\nimport tvm\nfrom tvm import autotvm, te\n\nfrom .. import nn\nfrom ..nn.winograd_util import winograd_transform_matrices\nfrom ..utils import get_const_int, get_const_tuple, traverse_inline\nfrom .tensor_intrin import (\n    intrin_wmma_gemm,\n    intrin_wmma_load_matrix_A,\n    intrin_wmma_load_matrix_W,\n    intrin_wmma_store_matrix,\n)\n\n\ndef _infer_tile_size(data, kernel):\n    \"\"\"Compute the tile size\"\"\"\n    N, H, W, CI = get_const_tuple(data.shape)\n    if H % 8 == 0:\n        return 4\n    return 2\n\n\ndef schedule_bgemm_tensorcore(cfg, s, bgemm, data_pack, kernel_pack):\n    \"\"\"Schedule for bgemm tensorcore\"\"\"\n    A = data_pack\n    B = kernel_pack\n    C = bgemm\n    _, _, P, out_dim = get_const_tuple(C.shape)\n    out_dtype = C.dtype\n\n    # Explicit memory access\n    AS = s.cache_read(A, \"shared\", [C])\n    BS = s.cache_read(B, \"shared\", [C])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [C])\n    BF = s.cache_read(BS, \"wmma.matrix_b\", [C])\n    CF = s.cache_write(C, \"wmma.accumulator\")\n    CS = s.cache_read(CF, \"shared\", [C])\n\n    # Create tuning space\n    cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n    cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n    cfg.define_knob(\"warp_row_tiles\", [1, 2, 4, 8])\n    cfg.define_knob(\"warp_col_tiles\", [1, 2, 4, 8])\n    cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n    cfg.define_knob(\"offset\", [0, 1, 2, 4, 8])\n    cfg.define_knob(\"offsetCS\", [0, 1, 2, 4, 8])\n    cfg.define_knob(\"vec\", [1, 2, 4, 8])\n\n    # Ensure that the default parameters are applicable when autotvm is not in use\n    if P % 16 == 0 and out_dim % 16 == 0:\n        cfg.define_knob(\"wmma_m\", [16, 8, 32])\n    elif P % 32 == 0 and out_dim % 8 == 0:\n        cfg.define_knob(\"wmma_m\", [32, 16, 8])\n    elif P % 8 == 0 and out_dim % 32 == 0:\n        cfg.define_knob(\"wmma_m\", [8, 16, 32])\n\n    warp_size = 32\n    wmma_k = 16\n    block_row_warps = cfg[\"block_row_warps\"].val\n    block_col_warps = cfg[\"block_col_warps\"].val\n    warp_row_tiles = cfg[\"warp_row_tiles\"].val\n    warp_col_tiles = cfg[\"warp_col_tiles\"].val\n    chunk = cfg[\"chunk\"].val\n    offsetAB = cfg[\"offset\"].val\n    offsetCS = cfg[\"offsetCS\"].val\n    wmma_m = cfg[\"wmma_m\"].val\n    vec = cfg[\"vec\"].val\n\n    if wmma_m == 16:\n        wmma_n = 16\n    elif wmma_m == 8:\n        wmma_n = 32\n    elif wmma_m == 32:\n        wmma_n = 8\n\n    # Define the stride of intrin functions\n    AS_align = chunk * wmma_k + offsetAB\n    BS_align = warp_col_tiles * block_col_warps * wmma_n + offsetAB\n    CS_align = warp_col_tiles * block_col_warps * wmma_n + offsetCS\n    AS_stride = [AS_align, 1]\n    BS_stride = [BS_align, 1]\n    AF_stride = [wmma_k, 1]\n    BF_stride = [wmma_n * warp_col_tiles, 1]\n    CF_stride = [warp_col_tiles * wmma_n, 1]\n    CS_stride = [CS_align, 1]\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    # Schedule for computation\n    block_factor_b = wmma_m * warp_row_tiles * block_row_warps\n    block_factor_o = wmma_n * warp_col_tiles * block_col_warps\n    alpha_1, alpha_2, b, o = C.op.axis\n    block_k = s[C].fuse(alpha_1, alpha_2)\n    block_i, bc = s[C].split(b, factor=block_factor_b)\n    block_j, oc = s[C].split(o, factor=block_factor_o)\n    s[C].reorder(block_k, block_i, block_j, bc, oc)\n    t = s[C].fuse(bc, oc)\n    t, vi = s[C].split(t, factor=vec)\n    t, tx = s[C].split(t, factor=warp_size)\n    t, ty = s[C].split(t, factor=block_row_warps)\n    t, tz = s[C].split(t, factor=block_col_warps)\n    s[C].bind(block_k, block_z)\n    s[C].bind(block_i, block_x)\n    s[C].bind(block_j, block_y)\n    s[C].bind(tz, thread_z)\n    s[C].bind(ty, thread_y)\n    s[C].bind(tx, thread_x)\n    s[C].vectorize(vi)\n\n    # Schedule for wmma store\n    s[CS].compute_at(s[C], block_j)\n    _, _, bb, oo = CS.op.axis\n    s[CS].storage_align(bb, CS_align - 1, CS_align)\n    bb, bbi = s[CS].split(bb, factor=wmma_m)\n    oo, ooi = s[CS].split(oo, factor=wmma_n)\n    bb, bbii = s[CS].split(bb, factor=warp_row_tiles)\n    oo, ooii = s[CS].split(oo, factor=warp_col_tiles)\n    s[CS].reorder(bb, oo, bbii, ooii, bbi, ooi)\n\n    # Schedule for wmma computation\n    s[CF].compute_at(s[CS], oo)\n    _, _, warp_i, warp_j = CF.op.axis\n    warp_i, _ii = s[CF].split(warp_i, factor=wmma_m)\n    warp_j, _jj = s[CF].split(warp_j, factor=wmma_n)\n    (k,) = CF.op.reduce_axis\n    k, _k = s[CF].split(k, factor=wmma_k)\n    ko, ki = s[CF].split(k, factor=chunk)\n    s[CF].reorder(ko, ki, warp_i, warp_j, _ii, _jj, _k)\n\n    # Schedule for  wmma_matrix_a load\n    s[AF].compute_at(s[CF], ki)\n    _, _, b, i = AF.op.axis\n    b, b_ii = s[AF].split(b, factor=wmma_m)\n    i, i_jj = s[AF].split(i, factor=wmma_k)\n    s[AF].reorder(b, i, b_ii, i_jj)\n\n    # Schedule for  wmma_matrix_b load\n    s[BF].compute_at(s[CF], ki)\n    _, _, i, o = BF.op.axis\n    o, o_ii = s[BF].split(o, factor=wmma_n)\n    i, i_ii = s[BF].split(i, factor=wmma_k)\n    s[BF].reorder(i, o, i_ii, o_ii)\n\n    # Schedule for A's(B's) shared memory load\n    def shared_schedule(stage, strides):\n        s[stage].compute_at(s[CF], ko)\n        _, _, xo, yo = stage.op.axis\n        s[stage].storage_align(xo, strides - 1, strides)\n        t = s[stage].fuse(xo, yo)\n        t, vi = s[stage].split(t, factor=vec)\n        t, tx = s[stage].split(t, factor=warp_size)\n        t, ty = s[stage].split(t, factor=block_row_warps)\n        _, tz = s[stage].split(t, factor=block_col_warps)\n        s[stage].bind(ty, thread_y)\n        s[stage].bind(tz, thread_z)\n        s[stage].bind(tx, thread_x)\n        s[stage].vectorize(vi)\n\n    shared_schedule(AS, AS_align)\n    shared_schedule(BS, BS_align)\n\n    shape = (wmma_m, wmma_n, wmma_k)\n    in_dtype = \"float16\"\n    AL_gemm = te.placeholder((wmma_m, wmma_k), name=\"AL_gemm\", dtype=in_dtype)\n    BL_gemm = te.placeholder((wmma_k, wmma_n), name=\"BL_gemm\", dtype=in_dtype)\n    k_gemm = te.reduce_axis((0, wmma_k), name=\"k_gemm\")\n    CL_compute = te.compute(\n        (wmma_m, wmma_n),\n        lambda ii, jj: te.sum(\n            AL_gemm[ii, k_gemm].astype(out_dtype) * BL_gemm[k_gemm, jj].astype(out_dtype),\n            axis=k_gemm,\n        ),\n        name=\"CL_compute\",\n    )\n\n    # Lower the computation loops down to TensorCore hardware intrinsics\n    # by mapping the tensorcore to tensor intrinsics\n    s[AF].tensorize(\n        b_ii,\n        intrin_wmma_load_matrix_A(\n            AF_stride, AS_stride, shape, \"row_major\", (wmma_m, wmma_k), (wmma_m, wmma_k), \"float16\"\n        ),\n    )\n    s[BF].tensorize(\n        i_ii,\n        intrin_wmma_load_matrix_W(\n            BF_stride, BS_stride, shape, \"row_major\", (wmma_k, wmma_n), (wmma_k, wmma_n), \"float16\"\n        ),\n    )\n    s[CF].tensorize(\n        _ii, intrin_wmma_gemm(AL_gemm, BL_gemm, CL_compute, AF_stride, BF_stride, CF_stride, shape)\n    )\n    s[CS].tensorize(\n        bbi,\n        intrin_wmma_store_matrix(\n            CS_stride, CF_stride, shape, out_dtype, (wmma_m, wmma_n), (wmma_m, wmma_n)\n        ),\n    )\n\n\ndef schedule_bgemm_direct(cfg, s, bgemm, data_pack, kernel_pack):\n    \"\"\"Schedule for bgemm direct\"\"\"\n    b1, b2, y, x = s[bgemm].op.axis\n    rc = s[bgemm].op.reduce_axis[0]\n    alpha = get_const_int(b1.dom.extent)\n\n    # Create tuning space\n    cfg.define_split(\n        \"tile_b\", cfg.axis(alpha * alpha), num_outputs=4, filter=lambda x: x.size[-3:] == [1, 1, 1]\n    )\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_knob(\"offset_bgemm\", [0, 1, 2, 4, 8])\n    cfg.define_knob(\"vector_bgemm\", [1, 2, 4, 8])\n    offset_bgemm = cfg[\"offset_bgemm\"].val\n    vector_bgemm = cfg[\"vector_bgemm\"].val\n\n    C = bgemm\n    A0, B0 = kernel_pack, data_pack\n\n    # Designate the memory hierarchy\n    OL = s.cache_write(C, \"local\")\n    AA = s.cache_read(A0, \"shared\", [OL])\n    BB = s.cache_read(B0, \"shared\", [OL])\n\n    # Tile and bind spatial axes\n    b = s[bgemm].fuse(b1, b2)\n    bgemm_scope, b = s[bgemm].split(b, nparts=1)\n    bz, vz, tz, zi = cfg[\"tile_b\"].apply(s, C, b)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, C, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].bind(bz, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(vz, te.thread_axis(\"vthread\"))\n    s[C].bind(vy, te.thread_axis(\"vthread\"))\n    s[C].bind(vx, te.thread_axis(\"vthread\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].reorder(bgemm_scope, bz, by, bx, vz, vy, vx, tz, ty, tx, zi, yi, xi)\n\n    # Tile reduction axes\n    s[OL].compute_at(s[C], tx)\n    b1, b2, y, x = s[OL].op.axis\n    b = s[OL].fuse(b1, b2)\n    (rc,) = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    s[OL].reorder(rco, b, y, x, rci)\n\n    s[AA].compute_at(s[OL], rco)\n    _, _, k, n = s[AA].op.axis\n    AA_align = offset_bgemm + cfg[\"tile_x\"].size[1] * cfg[\"tile_x\"].size[2] * cfg[\"tile_x\"].size[3]\n    s[AA].storage_align(k, AA_align - 1, AA_align)\n\n    s[BB].compute_at(s[OL], rco)\n    _, _, m, k = s[BB].op.axis\n    BB_align = offset_bgemm + cfg[\"tile_rc\"].size[1]\n    s[BB].storage_align(m, BB_align - 1, BB_align)\n\n    # Schedule for A and B shared memory load\n    for load in [AA, BB]:\n        fused = s[load].fuse(*list(s[load].op.axis))\n        fused, ti = s[load].split(fused, factor=vector_bgemm)\n        fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n        fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n        fused, tz = s[load].split(fused, cfg[\"tile_b\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[load].vectorize(ti)\n\n\ndef nhwc_winograd_cuda(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, use_tensorcore, pre_computed\n):\n    \"\"\"Compute declaration for winograd\"\"\"\n    tile_size = _infer_tile_size(data, kernel)\n    N, H, W, CI = get_const_tuple(data.shape)\n\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n\n    if not isinstance(H, int) or not isinstance(W, int):\n        raise RuntimeError(\n            \"cuda winograd nhwc conv2d doesn't support dynamic \\\n                           input height or width.\"\n        )\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides\n\n    if not pre_computed:  # Kernel tensor is raw tensor, do strict check\n        if dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (dilation_h, dilation_w, 1, 1))\n        KH, KW, CI, CO = get_const_tuple(kernel.shape)\n        alpha = KW + tile_size - 1\n        assert HSTR == 1 and WSTR == 1 and KH == KW\n    else:\n        # Kernel tensor is pre-transfomred. This op is created by conv2d_alter_op.\n        # Dilation is not supported\n        alpha, _, CI, CO = get_const_tuple(kernel.shape)\n        KH = KW = alpha + 1 - tile_size\n        assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1\n\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW))\n    data_pad = nn.pad(\n        data,\n        (0, pt, pl, 0),\n        (0, pb, pr, 0),\n        name=\"data_pad\",\n        attrs={\"schedule_rule\": \"None\"},\n    )\n\n    r = KW\n    m = tile_size\n    H = (H + pt + pb - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW if isinstance(N, int) else nH * nW\n\n    # Determine whether the shape is available with tensorcore\n    shape_judge = (\n        (P % 16 == 0 and CI % 16 == 0 and CO % 16 == 0)\n        or (P % 8 == 0 and CI % 16 == 0 and CO % 32 == 0)\n        or (P % 32 == 0 and CI % 16 == 0 and CO % 8 == 0)\n    )\n\n    if shape_judge and use_tensorcore:\n        trans_type = \"float16\"\n    else:\n        trans_type = data.dtype\n\n    # Compute transform matrix\n    A, _, _ = winograd_transform_matrices(m, r, out_dtype)\n    _, B, G = winograd_transform_matrices(m, r, data.dtype)\n\n    # Transform kernel\n    if not pre_computed:\n        # Check if we are currently tuning, if so we want to avoid counting\n        # prepacking in time costs. Just use a placeholder with the packed shape instead.\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            kernel_pack = te.placeholder(\n                (alpha, alpha, CI, CO), dtype=kernel.dtype, name=\"kernel_pack\"\n            )\n        else:\n            r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n            r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n            kernel_pack = te.compute(\n                (alpha, alpha, CI, CO),\n                lambda eps, nu, ci, co: te.sum(\n                    (kernel[r_kh][r_kw][ci][co]) * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n                ),\n                name=\"kernel_pack\",\n            )\n    else:\n        kernel_pack = kernel\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    # Pack input tile\n    input_tile = te.compute(\n        (P, CI, alpha, alpha),\n        lambda p, c, eps, nu: data_pad[\n            idxdiv(p, (nH * nW)), idxmod(idxdiv(p, nW), nH) * m + eps, idxmod(p, nW) * m + nu, c\n        ],\n        name=\"d\",\n        attrs={\"schedule_rule\": \"None\"},\n    )\n\n    # Transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    data_pack = te.compute(\n        (alpha, alpha, P, CI),\n        lambda eps, nu, p, ci: te.sum(\n            input_tile[p][ci][r_a][r_b] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"data_pack\",\n    )\n\n    # Convert data type of input feature maps and weights for tensorcore\n    Transdata = te.compute(\n        data_pack.shape, lambda eps, nu, p, ci: data_pack[eps, nu, p, ci].astype(trans_type)\n    )\n    TransFilter = te.compute(\n        kernel_pack.shape, lambda eps, nu, ci, co: kernel_pack[eps, nu, ci, co].astype(trans_type)\n    )\n\n    # Do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, P, CO),\n        lambda eps, nu, p, co: te.sum(\n            (Transdata[eps][nu][p][ci]).astype(out_dtype)\n            * (TransFilter[eps][nu][ci][co]).astype(out_dtype),\n            axis=[ci],\n        ),\n        name=\"bgemm\",\n    )\n\n    # Inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    inverse = te.compute(\n        (P, CO, m, m),\n        lambda p, co, vh, vw: te.sum(\n            bgemm[r_a][r_b][p][co] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]\n        ),\n        name=\"inverse\",\n    )\n\n    # Output\n    output = te.compute(\n        (N, H, W, CO),\n        lambda n, h, w, co: inverse[\n            n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), co, idxmod(h, m), idxmod(w, m)\n        ],\n        name=\"output\",\n        tag=\"conv2d_nhwc_winograd\",\n    )\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * CO * H * W * CI * KH * KW)\n    return output\n\n\ndef data_weight_transform(s, data_trans, input_tile, thread_num_trans, offset_trans, trans_tag):\n    \"\"\"Schedule for data or kernel transform\"\"\"\n    kernel_align = thread_num_trans + offset_trans\n    indata_s = s.cache_read(input_tile, \"shared\", [data_trans])\n    data_l = s.cache_write(data_trans, \"local\")\n    # Schedule for data or kernel transform\n    eps, nu, p, c = s[data_trans].op.axis\n\n    block_x, thread_x = s[data_trans].split(c, thread_num_trans)\n    block_x = s[data_trans].fuse(p, block_x)\n    s[data_trans].reorder(block_x, thread_x, eps, nu)\n    s[data_trans].bind(thread_x, te.thread_axis(\"threadIdx.x\"))\n    s[data_trans].bind(block_x, te.thread_axis(\"blockIdx.x\"))\n\n    s[data_l].compute_at(s[data_trans], thread_x)\n    eps_l, nu_l, p_l, c_l = s[data_l].op.axis\n    r_a, r_b = s[data_l].op.reduce_axis\n    block_x_l, thread_x_l = s[data_l].split(c_l, thread_num_trans)\n    block_x_l = s[data_l].fuse(p_l, block_x_l)\n\n    s[data_l].reorder(block_x_l, thread_x_l, eps_l, nu_l, r_a, r_b)\n\n    for axis in [eps_l, nu_l, r_a, r_b]:\n        s[data_l].unroll(axis)\n\n    # Schedule for share memory load\n    s[indata_s].compute_at(s[data_l], block_x_l)\n    if trans_tag == \"data\":\n        p_is, c_is, eps_is, nu_is = s[indata_s].op.axis\n        data_align = (\n            get_const_int(eps_is.dom.extent) * get_const_int(nu_is.dom.extent) + offset_trans\n        )\n        s[indata_s].storage_align(c_is, data_align - 1, data_align)\n        block_x_is, thread_x_is = s[indata_s].split(c_is, thread_num_trans)\n        s[indata_s].bind(thread_x_is, te.thread_axis(\"threadIdx.x\"))\n    else:\n        eps_is, nu_is, ci_is, co_is = s[indata_s].op.axis\n        s[indata_s].storage_align(nu_is, kernel_align - 1, kernel_align)\n        block_x_is, thread_x_is = s[indata_s].split(co_is, thread_num_trans)\n        s[indata_s].reorder(ci_is, block_x_is, eps_is, nu_is, thread_x_is)\n        s[indata_s].bind(thread_x_is, te.thread_axis(\"threadIdx.x\"))\n\n\ndef schedule_nhwc_winograd_cuda(cfg, s, output, use_tensorcore, pre_computed):\n    \"\"\"Schedule winograd template\"\"\"\n    # Get stages\n    inverse = s[output].op.input_tensors[0]\n    bgemm, A = s[inverse].op.input_tensors\n    Transdata, TransFilter = s[bgemm].op.input_tensors\n    data_pack = s[Transdata].op.input_tensors[0]\n    kernel_pack = s[TransFilter].op.input_tensors[0]\n    s[Transdata].compute_inline()\n    s[TransFilter].compute_inline()\n\n    input_tile, B = s[data_pack].op.input_tensors\n    pad_data = s[input_tile].op.input_tensors[0]\n\n    # Define the stride of intrin functions\n    cfg.define_knob(\"thread_num_inverse\", [1, 32, 64, 128, 256])\n    cfg.define_knob(\"thread_num_data\", [1, 32, 64, 128, 256])\n    cfg.define_knob(\"thread_num_kernel\", [1, 32, 64, 128, 256])\n    cfg.define_knob(\"offset_inverse\", [0, 2, 4])\n    cfg.define_knob(\"offset_data\", [0, 1, 2, 4])\n    cfg.define_knob(\"offset_kernel\", [0, 1, 2, 4])\n    cfg.define_knob(\"inverse_in_vector\", [1, 2, 4])\n\n    thread_num_data = cfg[\"thread_num_data\"].val\n    thread_num_kernel = cfg[\"thread_num_kernel\"].val\n    thread_num_inverse = cfg[\"thread_num_inverse\"].val\n    offset_data = cfg[\"offset_data\"].val\n    offset_kernel = cfg[\"offset_kernel\"].val\n    offset_inverse = cfg[\"offset_inverse\"].val\n    inverse_in_vector = cfg[\"inverse_in_vector\"].val\n\n    # Data transform\n    s[B].compute_inline()\n    data_weight_transform(s, data_pack, input_tile, thread_num_data, offset_data, trans_tag=\"data\")\n    s[input_tile].compute_inline()\n    s[pad_data].compute_inline()\n\n    # Kernel transform\n    if not pre_computed and not autotvm.GLOBAL_SCOPE.in_tuning:\n        kernel, G = s[kernel_pack].op.input_tensors\n        s[G].compute_inline()\n        data_weight_transform(\n            s, kernel_pack, kernel, thread_num_kernel, offset_kernel, trans_tag=\"kernel\"\n        )\n    else:\n        kernel = kernel_pack\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    b1, b2, y, x = s[bgemm].op.axis\n    alpha = get_const_int(b1.dom.extent)\n    _, _, P, CI = get_const_tuple(Transdata.shape)\n    _, _, _, CO = get_const_tuple(TransFilter.shape)\n\n    # Determine whether the shape is available with tensorcore\n    shape_judge = (\n        (P % 16 == 0 and CI % 16 == 0 and CO % 16 == 0)\n        or (P % 8 == 0 and CI % 16 == 0 and CO % 32 == 0)\n        or (P % 32 == 0 and CI % 16 == 0 and CO % 8 == 0)\n    )\n\n    if shape_judge and use_tensorcore:\n        schedule_bgemm_tensorcore(cfg, s, bgemm, Transdata, TransFilter)\n    else:\n        schedule_bgemm_direct(cfg, s, bgemm, Transdata, TransFilter)\n\n    # Schedule inverse, output and fusion\n    if output.op in s.outputs:\n        OL = None\n    else:\n        OL = output\n        s[OL].set_scope(\"local\")\n        output = s.outputs[0]\n\n    s[A].compute_inline()\n    inverse_s = s.cache_read(bgemm, \"shared\", [inverse])\n\n    m = alpha - 3 + 1\n    offset_inverse_in = offset_inverse\n    vector_width_inverse_in = inverse_in_vector\n\n    # Schedule for output\n    n, h, w, co = s[output].op.axis\n    ho, wo, hi, wi = s[output].tile(h, w, m, m)\n    s[output].reorder(n, ho, wo, co, hi, wi)\n    fused = s[output].fuse(n, ho, wo)\n\n    block_x_s, thread_x_s = s[output].split(co, thread_num_inverse)\n    block_x_s = s[output].fuse(fused, block_x_s)\n    s[output].reorder(block_x_s, thread_x_s, hi, wi)\n\n    if OL is not None:\n        s[OL].compute_inline()\n\n    # Schedule for inverse\n    s[inverse].compute_at(s[output], thread_x_s)\n    p_inv, co_inv, eps_inv, nu_inv = s[inverse].op.axis\n    block_x_inv, thread_x_inv = s[inverse].split(co_inv, thread_num_inverse)\n    r_a, r_b = s[inverse].op.reduce_axis\n    for axis in [eps_inv, nu_inv, r_a, r_b]:\n        s[inverse].unroll(axis)\n\n    # Schedule for share memory load\n    s[inverse_s].compute_at(s[output], block_x_s)\n    eps_inv_s, nu_inv_s, p_inv_s, co_inv_s = s[inverse_s].op.axis\n    inverse_in_align = offset_inverse_in + thread_num_inverse\n    s[inverse_s].storage_align(p_inv_s, inverse_in_align - 1, inverse_in_align)\n    block_x_inv_s, thread_x_inv_s = s[inverse_s].split(co_inv_s, thread_num_inverse)\n    block_x_inv_s = s[inverse_s].fuse(p_inv_s, block_x_inv_s)\n    s[inverse_s].reorder(block_x_inv_s, eps_inv_s, nu_inv_s, thread_x_inv_s)\n    t = s[inverse_s].fuse(eps_inv_s, nu_inv_s, thread_x_inv_s)\n    t, ti = s[inverse_s].split(t, factor=vector_width_inverse_in)\n    t, tx = s[inverse_s].split(t, factor=thread_num_inverse)\n    s[inverse_s].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[inverse_s].vectorize(ti)\n\n    s[output].bind(thread_x_s, te.thread_axis(\"threadIdx.x\"))\n    s[output].bind(block_x_s, te.thread_axis(\"blockIdx.x\"))\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd_direct.cuda\")\ndef conv2d_nhwc_winograd_direct(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with winograd for NHWC layout\"\"\"\n    return nhwc_winograd_cuda(\n        cfg,\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        use_tensorcore=False,\n        pre_computed=False,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd_direct.cuda\")\ndef schedule_conv2d_nhwc_winograd_direct(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc_winograd\" in op.tag:\n            schedule_nhwc_winograd_cuda(\n                cfg, s, op.output(0), use_tensorcore=False, pre_computed=False\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd_tensorcore.cuda\")\ndef conv2d_nhwc_winograd_tensorcore(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with winograd for NHWC layout\"\"\"\n    return nhwc_winograd_cuda(\n        cfg,\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        use_tensorcore=True,\n        pre_computed=False,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd_tensorcore.cuda\")\ndef schedule_conv2d_nhwc_winograd_tensorcore(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc_winograd\" in op.tag:\n            schedule_nhwc_winograd_cuda(\n                cfg, s, op.output(0), use_tensorcore=True, pre_computed=False\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd_direct_without_weight_transform.cuda\")\ndef conv2d_nhwc_winograd_direct_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    \"\"\"Compute conv2d with winograd for NHWC layout\"\"\"\n    return nhwc_winograd_cuda(\n        cfg,\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        use_tensorcore=False,\n        pre_computed=True,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd_direct_without_weight_transform.cuda\")\ndef schedule_conv2d_nhwc_winograd_direct_without_weight_transform(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc_winograd\" in op.tag:\n            schedule_nhwc_winograd_cuda(\n                cfg, s, op.output(0), use_tensorcore=False, pre_computed=True\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_winograd_tensorcore_without_weight_transform.cuda\")\ndef conv2d_nhwc_winograd_tensorcore_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    \"\"\"Compute conv2d with winograd for NHWC layout\"\"\"\n    return nhwc_winograd_cuda(\n        cfg,\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        use_tensorcore=True,\n        pre_computed=True,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_winograd_tensorcore_without_weight_transform.cuda\")\ndef schedule_conv2d_nhwc_winograd_tensorcore_without_weight_transform(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nhwc_winograd\" in op.tag:\n            schedule_nhwc_winograd_cuda(\n                cfg, s, op.output(0), use_tensorcore=True, pre_computed=True\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Conv2d transpose template for cuda backend\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cudnn\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\nfrom .. import nn\nfrom ..utils import get_const_tuple, traverse_inline\n\n\n@autotvm.register_topi_compute(\"conv2d_transpose_nchw.cuda\")\ndef conv2d_transpose_nchw(cfg, data, kernel, stride, padding, out_dtype, output_padding, groups=1):\n    \"\"\"Transposed 2D convolution nchw forward operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n    Filter : tvm.te.Tensor\n        4-D with shape [in_channel, num_filter, filter_height, filter_width]\n    strides : tuple of two ints\n        The spatial stride along height and width\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n    out_dtype: str\n        The output type. This is used in mixed precision\n    output_padding : tuple of two ints\n        Used to disambiguate output shape.\n    groups : int\n        number of groups\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    batch, inp_channels, inp_height, inp_width = get_const_tuple(data.shape)\n    _, out_channels, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n    stride_height, stride_width = stride\n    outpad_height, outpad_width = output_padding\n    assert outpad_height < stride_height and outpad_width < stride_width\n    assert (\n        inp_channels % groups == 0\n    ), f\"input channels {inp_channels} must divide group size {groups}\"\n    cfg.stride = stride\n    pad_top, pad_left, pad_bottom, pad_right = nn.get_pad_tuple(\n        padding, (kernel_height, kernel_width)\n    )\n\n    out_width = (inp_width - 1) * stride_width + kernel_width - pad_left - pad_right + outpad_width\n    pad_left = kernel_width - 1 - pad_left\n    pad_right = kernel_width - 1 - pad_right + outpad_width\n    dilated_width = stride_width * (inp_width - 1) + 1\n\n    out_height = (\n        (inp_height - 1) * stride_height + kernel_height - pad_top - pad_bottom + outpad_height\n    )\n    pad_top = kernel_height - 1 - pad_top\n    pad_bottom = kernel_height - 1 - pad_bottom + outpad_height\n    dilated_height = stride_height * (inp_height - 1) + 1\n\n    # compute pad\n    data = te.compute(\n        (\n            batch,\n            inp_channels,\n            pad_top + dilated_height + pad_bottom,\n            pad_left + dilated_width + pad_right,\n        ),\n        lambda n, c, y, x: tvm.tir.if_then_else(\n            tvm.tir.all(\n                x >= pad_left,\n                x < pad_left + dilated_width,\n                tvm.tir.indexmod(x - pad_left, stride_width).equal(0),\n                y >= pad_top,\n                y < pad_top + dilated_height,\n                tvm.tir.indexmod(y - pad_top, stride_height).equal(0),\n            ),\n            data[\n                n,\n                c,\n                tvm.tir.indexdiv(y - pad_top, stride_height),\n                tvm.tir.indexdiv(x - pad_left, stride_width),\n            ],\n            tvm.tir.const(0.0, data.dtype),\n        ),\n        name=\"data_pad\",\n    )\n\n    # compute transposed conv\n    dc = te.reduce_axis((0, inp_channels // groups), name=\"dc\")\n    dh = te.reduce_axis((0, kernel_height), name=\"dh\")\n    dw = te.reduce_axis((0, kernel_width), name=\"dw\")\n    data_out = te.compute(\n        (batch, out_channels * groups, out_height, out_width),\n        lambda b, c, h, w: te.sum(\n            data[b, c // out_channels * (inp_channels // groups) + dc, h + dh, w + dw].astype(\n                out_dtype\n            )\n            * kernel[\n                c // out_channels * (inp_channels // groups) + dc,\n                c % out_channels,\n                kernel_height - 1 - dh,\n                kernel_width - 1 - dw,\n            ].astype(out_dtype),\n            axis=[dc, dh, dw],\n        ),\n        tag=\"conv2d_transpose_nchw\",\n    )\n\n    return data_out\n\n\n@autotvm.register_topi_schedule(\"conv2d_transpose_nchw.cuda\")\ndef schedule_conv2d_transpose_nchw(cfg, outs):\n    \"\"\"TOPI Schedule callback for conv2d transpose operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The parameters for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d transpose\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d transpose.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _fallback_schedule(N, F, Y, X):\n        # pylint: disable=unused-argument\n        # split N (batch dimension)\n        if N > 1:\n            cfg[\"tile_n\"] = SplitEntity([-1, 1, 1, 4])\n        else:\n            cfg[\"tile_n\"] = SplitEntity([1, 1, 1, 1])\n        # split F (output channel dimension)\n        if F > 1:\n            cfg[\"tile_f\"] = SplitEntity([-1, 1, 4, 1])\n        # split Y (height dimension)\n        y_split_factor = 1\n        for candidate in range(5, 17):\n            if Y % candidate == 0:\n                y_split_factor = candidate\n                break\n        cfg[\"tile_y\"] = SplitEntity([-1, 1, 1, y_split_factor])\n        # split X (width dimension)\n        x_split_factor = 1\n        for candidate in range(5, 17):\n            if X % candidate == 0:\n                x_split_factor = candidate\n                break\n        cfg[\"tile_x\"] = SplitEntity([-1, x_split_factor, 1, 1])\n        # split RC (input channel dimension, which is a reduction axis)\n        cfg[\"tile_rc\"] = SplitEntity([-1, 1, 16])\n        # other configurations\n        cfg[\"fuse_yx\"] = OtherOptionEntity(False)\n        cfg[\"unroll_explicit\"] = OtherOptionEntity(True)\n        cfg[\"auto_unroll_max_step\"] = OtherOptionEntity(1500)\n\n    def _callback(op):\n        if op.tag == \"conv2d_transpose_nchw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, f, y, x = s[conv].op.axis\n            rc = s[conv].op.reduce_axis[0]\n            # TODO(@kevinthesun): Support tuning/optimization for dynamic shape.\n            bs = pad_data.shape[0]\n            n_tuning_axis = n if isinstance(bs, tvm.tir.IntImm) else 1\n            cfg.define_split(\"tile_n\", cfg.axis(n_tuning_axis), num_outputs=4)\n            cfg.define_split(\"tile_f\", cfg.axis(f), num_outputs=4)\n            cfg.define_split(\"tile_y\", cfg.axis(y), num_outputs=4)\n            cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=4)\n            cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=3)\n            cfg.define_knob(\"auto_unroll_max_step\", [64, 512, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            if cfg.is_fallback:\n                N, F, Y, X = get_const_tuple(conv.shape)\n                if not isinstance(N, int):\n                    N = 1\n                _fallback_schedule(N, F, Y, X)\n\n            ##### space definition end #####\n\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            # create cache stage\n            s[pad_data].set_scope(\"shared\")\n            AA = pad_data\n            WW = s.cache_read(kernel, \"shared\", [OL])\n\n            # tile and bind spatial axes\n            n, f, y, x = s[output].op.axis\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n            by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            s[output].reorder(bn, bf, by, bx, vn, vf, vy, vx, tn, tf, ty, tx, ni, fi, yi, xi)\n            s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(bf, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(s[output].fuse(by, bx), te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vn, te.thread_axis(\"vthread\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n            s[output].bind(vy, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n\n            cfg.define_knob(\"fuse_yx\", [0, 1])  # fuse ty,tx or tn,tf\n\n            if cfg[\"fuse_yx\"].val:\n                s[output].bind(tn, te.thread_axis(\"threadIdx.z\"))\n                s[output].bind(tf, te.thread_axis(\"threadIdx.y\"))\n                tyx = s[output].fuse(ty, tx)\n                s[output].bind(s[output].fuse(ty, tx), te.thread_axis(\"threadIdx.x\"))\n                s[OL].compute_at(s[output], tyx)\n\n                # number of threads\n                n_tz = cfg[\"tile_n\"].size[2]\n                n_ty = cfg[\"tile_f\"].size[2]\n                n_tx = cfg[\"tile_y\"].size[2] * cfg[\"tile_x\"].size[2]\n            else:\n                s[output].bind(s[output].fuse(tn, tf), te.thread_axis(\"threadIdx.z\"))\n                s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n                s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n                s[OL].compute_at(s[output], tx)\n\n                # number of threads\n                n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_f\"].size[2]\n                n_ty = cfg[\"tile_y\"].size[2]\n                n_tx = cfg[\"tile_x\"].size[2]\n\n            # tile reduction axes\n            n, f, y, x = s[OL].op.axis\n            rc, ry, rx = s[OL].op.reduce_axis\n            rco, rcm, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n            s[OL].reorder(rco, rcm, ry, rx, rci, n, f, y, x)\n\n            s[AA].compute_at(s[OL], rx)\n            s[WW].compute_at(s[OL], rx)\n\n            # cooperative fetching\n            for load in [AA, WW]:\n                n, f, y, x = s[load].op.axis\n                fused = s[load].fuse(f, y, x)\n                tz, fused = s[load].split(fused, nparts=n_tz)\n                ty, fused = s[load].split(fused, nparts=n_ty)\n                tx, fused = s[load].split(fused, nparts=n_tx)\n                s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n                s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n                s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n\n\ndef conv2d_transpose_cudnn(\n    x, w, stride, padding, out_dtype, output_padding=(0, 0), layout=\"NCHW\", groups=1\n):\n    \"\"\"Compute conv2d_tranpose using cudnn dgrad kernel\"\"\"\n    tensor_format = 0 if layout == \"NCHW\" else 1\n    return cudnn.conv_backward_data(\n        x,\n        w,\n        padding,\n        stride,\n        (1, 1),\n        1,\n        tensor_format,\n        out_dtype,\n        groups=groups,\n        output_padding=output_padding,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv2d_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Winograd template for cuda backend\"\"\"\n\nimport logging\n\nimport tvm\nfrom tvm import autotvm, te\n\nfrom .. import nn\nfrom ..nn.conv2d import (\n    _conv2d_winograd_nchw_impl,\n    _conv2d_winograd_nhwc_impl,\n    conv2d_winograd_nchw,\n    conv2d_winograd_nhwc,\n)\nfrom ..nn.winograd_util import winograd_transform_matrices\nfrom ..utils import get_const_int, get_const_tuple, traverse_inline\n\nlogger = logging.getLogger(\"conv2d_winograd\")\n\n\ndef _infer_tile_size(data, kernel, layout=\"NCHW\"):\n    if layout == \"NCHW\":\n        N, CI, H, W = get_const_tuple(data.shape)\n    else:\n        assert layout == \"NHWC\"\n        N, H, W, CI = get_const_tuple(data.shape)\n\n    if H % 8 == 0:\n        return 4\n    return 2\n\n\ndef winograd_cuda(cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed):\n    \"\"\"Compute declaration for winograd\"\"\"\n    tile_size = _infer_tile_size(data, kernel)\n\n    N, CI, H, W = get_const_tuple(data.shape)\n\n    if isinstance(N, tvm.tir.Any):\n        N = tvm.te.size_var(\"n\")\n\n    if not isinstance(H, int) or not isinstance(W, int):\n        raise RuntimeError(\n            \"cuda winograd conv2d doesn't support dynamic input\\\n                           height or width.\"\n        )\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides\n\n    if not pre_computed:  # kernel tensor is raw tensor, do strict check\n        if dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_h, dilation_w))\n        CO, CI, KH, KW = get_const_tuple(kernel.shape)\n        alpha = KW + tile_size - 1\n        assert HSTR == 1 and WSTR == 1 and KH == KW\n    else:\n        # kernel tensor is pre-transfomred. this op is created by alter op layout.\n        # dilation is not supported\n        alpha, _, CI, CO = get_const_tuple(kernel.shape)\n        KH = KW = alpha + 1 - tile_size\n        assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1\n\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW))\n    data_pad = nn.pad(\n        data,\n        (0, 0, pt, pl),\n        (0, 0, pb, pr),\n        name=\"data_pad\",\n    )\n\n    r = KW\n    m = tile_size\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    H = (H + pt + pb - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n\n    P = N * nH * nW if isinstance(N, int) else nH * nW\n\n    # transform kernel\n    if not pre_computed:\n        r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n        r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n        kernel_pack = te.compute(\n            (alpha, alpha, CI, CO),\n            lambda eps, nu, ci, co: te.sum(\n                kernel[co][ci][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n            ),\n            name=\"kernel_pack\",\n        )\n    else:\n        kernel_pack = kernel\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    # pack input tile\n    input_tile = te.compute(\n        (CI, P, alpha, alpha),\n        lambda c, p, eps, nu: data_pad[idxdiv(p, (nH * nW))][c][\n            idxmod(idxdiv(p, nW), nH) * m + eps\n        ][idxmod(p, nW) * m + nu],\n        name=\"d\",\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_a\")\n    data_pack = te.compute(\n        (alpha, alpha, CI, P),\n        lambda eps, nu, ci, p: te.sum(\n            input_tile[ci][p][r_a][r_b] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"data_pack\",\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, CO, P),\n        lambda eps, nu, co, p: te.sum(\n            kernel_pack[eps][nu][ci][co] * data_pack[eps][nu][ci][p], axis=[ci]\n        ),\n        name=\"bgemm\",\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_a\")\n    inverse = te.compute(\n        (CO, P, m, m),\n        lambda co, p, vh, vw: te.sum(\n            bgemm[r_a][r_b][co][p] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]\n        ),\n        name=\"inverse\",\n    )\n\n    # output\n    output = te.compute(\n        (N, CO, H, W),\n        lambda n, co, h, w: inverse[\n            co, n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), idxmod(h, m), idxmod(w, m)\n        ],\n        name=\"output\",\n        tag=\"conv2d_nchw_winograd\",\n    )\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * CO * H * W * CI * KH * KW)\n\n    return output\n\n\ndef schedule_winograd_cuda(cfg, s, output, pre_computed):\n    \"\"\"Schedule winograd template\"\"\"\n    # get stages\n    inverse = s[output].op.input_tensors[0]\n    bgemm, A = s[inverse].op.input_tensors\n    kernel_pack, data_pack = s[bgemm].op.input_tensors\n    input_tile, B = s[data_pack].op.input_tensors\n    pad_data = s[input_tile].op.input_tensors[0]\n\n    # data transform\n    s[B].compute_inline()\n\n    data_l = s.cache_write(data_pack, \"local\")\n    eps, nu, c, p = s[data_l].op.axis\n    r_a, r_b = s[data_l].op.reduce_axis\n    for axis in [eps, nu, r_a, r_b]:\n        s[data_l].unroll(axis)\n\n    eps, nu, c, p = s[data_pack].op.axis\n    p, pi = s[data_pack].split(p, 1)\n    fused = s[data_pack].fuse(c, p)\n    bb, tt = s[data_pack].split(fused, 128)\n    s[data_pack].reorder(bb, tt, pi, eps, nu)\n    s[data_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[data_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    s[data_l].compute_at(s[data_pack], pi)\n    s[input_tile].compute_at(s[data_pack], pi)\n    s[pad_data].compute_inline()\n\n    # transform kernel\n    if not pre_computed:\n        kernel, G = s[kernel_pack].op.input_tensors\n        eps, nu, ci, co = s[kernel_pack].op.axis\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # skip this part during tuning to make recrods accurate\n            # this part will be pre-computed during pre-compute optimization pass\n            s[G].pragma(s[G].op.axis[0], \"debug_skip_region\")\n            s[kernel_pack].pragma(eps, \"debug_skip_region\")\n        else:\n            s[G].compute_inline()\n            r_a, r_b = s[kernel_pack].op.reduce_axis\n            for axis in [eps, nu, r_a, r_b]:\n                s[kernel_pack].unroll(axis)\n\n            fused = s[kernel_pack].fuse(ci, co)\n            bb, tt = s[kernel_pack].split(fused, 128)\n            s[kernel_pack].reorder(bb, tt, eps, nu, r_a, r_b)\n            s[kernel_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n            s[kernel_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n    else:\n        kernel = kernel_pack\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    ##### space definition begin #####\n    b1, b2, y, x = s[bgemm].op.axis\n    rc = s[bgemm].op.reduce_axis[0]\n    alpha = get_const_int(b1.dom.extent)\n\n    cfg.define_split(\n        \"tile_b\", cfg.axis(alpha * alpha), num_outputs=4, filter=lambda x: x.size[-3:] == [1, 1, 1]\n    )\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 128, 1500])\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n    ##### space definition end #####\n\n    # batch gemm\n    C = bgemm\n    A0, B0 = kernel_pack, data_pack\n\n    OL = s.cache_write(C, \"local\")\n    AA = s.cache_read(A0, \"shared\", [OL])\n    BB = s.cache_read(B0, \"shared\", [OL])\n\n    b = s[bgemm].fuse(b1, b2)\n\n    # tile and bind spatial axes\n    bgemm_scope, b = s[bgemm].split(b, nparts=1)\n    bz, vz, tz, zi = cfg[\"tile_b\"].apply(s, C, b)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, C, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].bind(bz, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(vz, te.thread_axis(\"vthread\"))\n    s[C].bind(vy, te.thread_axis(\"vthread\"))\n    s[C].bind(vx, te.thread_axis(\"vthread\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].reorder(bgemm_scope, bz, by, bx, vz, vy, vx, tz, ty, tx, zi, yi, xi)\n\n    # tile reduction axes\n    s[OL].compute_at(s[C], tx)\n    b1, b2, y, x = s[OL].op.axis\n    b = s[OL].fuse(b1, b2)\n    (rc,) = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    s[OL].reorder(rco, rci, b, y, x)\n\n    s[AA].compute_at(s[OL], rco)\n    s[BB].compute_at(s[OL], rco)\n\n    # cooperative fetching\n    for load in [AA, BB]:\n        fused = s[load].fuse(*list(s[load].op.axis))\n        fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n        fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n        fused, tz = s[load].split(fused, cfg[\"tile_b\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    s[C].pragma(bgemm_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[C].pragma(bgemm_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    # schedule inverse, output and fusion\n    if output.op in s.outputs:\n        OL = None\n    else:\n        OL = output\n        s[OL].set_scope(\"local\")\n        output = s.outputs[0]\n\n    m = alpha - 3 + 1\n    n, co, h, w = s[output].op.axis\n    ho, wo, hi, wi = s[output].tile(h, w, m, m)\n    inverse_scope, n = s[output].split(n, nparts=1)\n\n    fused = s[output].fuse(n, co, ho, wo)\n    bb, tt = s[output].split(fused, 128)\n\n    s[output].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    if OL is not None:\n        s[OL].compute_at(s[output], tt)\n\n    s[A].compute_inline()\n    co, p, vh, vw = s[inverse].op.axis\n    r_a, r_b = s[inverse].op.reduce_axis\n    for axis in [vh, vw, r_a, r_b]:\n        s[inverse].unroll(axis)\n    s[inverse].compute_at(s[output], tt)\n\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd.cuda\")\ndef conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    return winograd_cuda(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=False\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd.cuda\")\ndef schedule_conv2d_nchw_winograd(cfg, outs):\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nchw_winograd\" in op.tag:\n            schedule_winograd_cuda(cfg, s, op.output(0), pre_computed=False)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd_without_weight_transform.cuda\")\ndef conv2d_nchw_winograd_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, out_dtype\n):\n    return winograd_cuda(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=True\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd_without_weight_transform.cuda\")\ndef schedule_conv2d_nchw_winograd_without_weight_transform(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_nchw_winograd\" in op.tag:\n            schedule_winograd_cuda(cfg, s, op.output(0), pre_computed=True)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@conv2d_winograd_nhwc.register([\"cuda\", \"gpu\"])\ndef conv2d_winograd_nhwc_cuda(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    pre_computed=False,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd in NHWC layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n    \"\"\"\n    tile_size = _infer_tile_size(data, weight, layout=\"NHWC\")\n    return _conv2d_winograd_nhwc_impl(\n        data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed\n    )\n\n\n@conv2d_winograd_nchw.register([\"cuda\", \"gpu\"])\ndef conv2d_winograd_nchw_cuda(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    pre_computed=False,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd in NCHW layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n    \"\"\"\n    tile_size = _infer_tile_size(data, weight, layout=\"NCHW\")\n    return _conv2d_winograd_nchw_impl(\n        data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Compute definition for conv3d with cuda backend\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.contrib import cudnn\n\nfrom .. import nn, generic\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .conv3d_direct import schedule_direct_conv3d_cuda\n\n\n@autotvm.register_topi_compute(\"conv3d_ncdhw.cuda\")\ndef conv3d_ncdhw(cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"):\n    \"\"\"Conv3D operator in NCDHW layout for cuda backend.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    strides : int or a list/tuple of three ints\n        stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or a list/tuple of three ints\n        padding size, or [pad_depth, pad_height, pad_width]\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    return nn.conv3d_ncdhw(data, kernel, strides, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv3d_ncdhw.cuda\")\ndef schedule_conv3d_ncdhw(cfg, outs):\n    \"\"\"TOPI schedule callback of conv3d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv3d_ncdhw\" in op.tag:\n            schedule_direct_conv3d_cuda(cfg, s, op.output(0), \"NCDHW\", \"conv3d_ncdhw.cuda\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3d_ndhwc.cuda\")\ndef conv3d_ndhwc(cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"):\n    \"\"\"Conv3d operator in NDHWC layout for cuda backend.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_depth, in_height, in_width, in_channel]\n\n    Filter : tvm.te.Tensor\n        5-D with shape [filter_depth, filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_depth, out_height, out_width, out_channel]\n    \"\"\"\n    return nn.conv3d_ndhwc(data, kernel, strides, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv3d_ndhwc.cuda\")\ndef schedule_conv3d_ndhwc(cfg, outs):\n    \"\"\"TOPI schedule callback of conv3d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv3d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv3d_ndhwc\" in op.tag:\n            schedule_direct_conv3d_cuda(cfg, s, op.output(0), \"NDHWC\", \"conv3d_ndhwc.cuda\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3d_cudnn.cuda\")\ndef conv3d_cudnn(\n    cfg, data, kernel, strides, padding, dilation, groups, layout=\"NCDHW\", out_dtype=\"float32\"\n):\n    \"\"\"Conv3D operator for cuda backend.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    strides : int or a list/tuple of three ints\n        stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or a list/tuple of three ints\n        padding size, or [pad_depth, pad_height, pad_width]\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    layout : str\n        layout of data\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    if layout == \"NCDHW\":\n        tensor_format = 0  # CUDNN_TENSOR_NCHW\n        N, _, D, H, W = get_const_tuple(data.shape)\n    elif layout == \"NDHWC\":\n        tensor_format = 1  # CUDNN_TENSOR_NHWC\n        N, D, H, W, _ = get_const_tuple(data.shape)\n    else:\n        raise ValueError(\"Unsupported layout %s in cudnn\" % layout)\n    CO, CI, KD, KH, KW = get_const_tuple(kernel.shape)\n\n    assert groups == 1, \"conv3d_cudnn does not support groups\"\n\n    # handle dilation\n    stride_d, stride_h, stride_w = (\n        (strides, strides, strides) if isinstance(strides, int) else strides\n    )\n    pad_d, pad_h, pad_w = (padding, padding, padding) if isinstance(padding, int) else padding\n    dilation_d, dilation_h, dilation_w = (\n        (dilation, dilation, dilation) if isinstance(dilation, int) else dilation\n    )\n\n    OD = (D + 2 * pad_d - KD) // stride_d + 1\n    OH = (H + 2 * pad_h - KH) // stride_h + 1\n    OW = (W + 2 * pad_w - KW) // stride_w + 1\n\n    if isinstance(N, int):\n        cfg.add_flop(\n            2\n            * N\n            * OD\n            * OH\n            * OW\n            * CO\n            * CI\n            * ((KD - 1) * dilation_d + 1)\n            * ((KH - 1) * dilation_h + 1)\n            * ((KW - 1) * dilation_w + 1)\n        )\n\n    cfg.define_knob(\"algo\", range(cudnn.algo_to_index(\"fwd\", \"CUDNN_CONVOLUTION_FWD_ALGO_COUNT\")))\n    if cfg.is_fallback:\n        if cudnn.exists():\n            # Let CUDNN choose the best algo, based on benchmarks run\n            # on the local machine.  In the future, this should be\n            # based on parameters stored in the Target.\n            cfg[\"algo\"] = OtherOptionEntity(-1)\n        else:\n            cfg[\"algo\"] = OtherOptionEntity(0)\n\n    return cudnn.conv_forward(\n        data,\n        kernel,\n        [pad_d, pad_h, pad_w],\n        [stride_d, stride_h, stride_w],\n        [dilation_d, dilation_h, dilation_w],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        algo=cfg[\"algo\"].val,\n        conv_dtype=dtype,\n    )\n\n\n@autotvm.register_topi_schedule(\"conv3d_cudnn.cuda\")\ndef schedule_conv3d_cudnn(_, outs):\n    \"\"\"TOPI schedule callback of conv3d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d.\n    \"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Conv3D alter op and legalize functions for cuda backend\"\"\"\n\nimport logging\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import get_const_tuple\nfrom .conv3d_winograd import _infer_tile_size\n\nlogger = logging.getLogger(\"topi\")\n\n\n@nn.conv3d_alter_layout.register([\"cuda\", \"gpu\"])\ndef _alter_conv3d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n\n    _, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.conv3d\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n    if workload is None:\n        # The best implementation is not an AutoTVM template,\n        # we then assume it's not necessary to alter this op.\n        return None\n    cfg = dispatch_ctx.query(target, workload)\n    if cfg.is_fallback:  # if is fallback, clear query cache and return None\n        autotvm.task.clear_fallback_cache(target, workload)\n        return None\n\n    topi_tmpl = workload[0]\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    strides = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    groups = attrs.get_int(\"groups\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data, kernel = tinfos\n    out_dtype = out_type.dtype\n\n    if topi_tmpl == \"conv3d_ncdhw_winograd.cuda\":\n        if dilation != (1, 1, 1):\n            logger.warning(\"Does not support weight pre-transform for dilated 3D convolution.\")\n            return None\n\n        assert data_layout == \"NCDHW\" and kernel_layout == \"OIDHW\"\n        N, CI, D, H, W = get_const_tuple(data.shape)\n        CO, _, KD, KH, KW = get_const_tuple(kernel.shape)\n\n        # Pre-compute weight transformation in winograd\n        tile_size = _infer_tile_size(tinfos[0], tinfos[1])\n\n        weight = relay.nn.contrib_conv3d_winograd_weight_transform(inputs[1], tile_size=tile_size)\n        new_attrs[\"tile_size\"] = tile_size\n        new_attrs[\"channels\"] = CO\n\n        # Store the same config for the altered operators (workload)\n        new_data = data\n        # Check if depth is transformed or not\n        if 2 < KD < 8 and KD == KH:\n            new_weight = te.placeholder(\n                (KD + tile_size - 1, KH + tile_size - 1, KW + tile_size - 1, CO, CI),\n                dtype=kernel.dtype,\n            )\n        else:\n            new_weight = te.placeholder(\n                (KH + tile_size - 1, KW + tile_size - 1, KD, CO, CI), dtype=kernel.dtype\n            )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_weight, strides, padding, dilation, out_dtype],\n            \"conv3d_ncdhw_winograd_without_weight_transform.cuda\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv3d_winograd_without_weight_transform(\n            inputs[0], weight, **new_attrs\n        )\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d_direct.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"The templates for cuda conv3d operators\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple\n\n\ndef schedule_direct_conv3d_cuda(cfg, s, conv, layout, workload_name):\n    \"\"\"schedule optimized for batch size = 1\"\"\"\n\n    ##### space definition begin #####\n    if layout == \"NCDHW\":\n        n, f, d, y, x = s[conv].op.axis\n    elif layout == \"NDHWC\":\n        n, d, y, x, f = s[conv].op.axis\n    else:\n        raise ValueError(\"not support this layout {} yet\".format(layout))\n    rc, rd, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_f\", f, num_outputs=4)\n    cfg.define_split(\"tile_d\", d, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_rd\", ry, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    # fallback support\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(target.kind.name, target.model, workload_name)\n        cfg.fallback_with_reference_log(ref_log)\n    ##### space definition end #####\n\n    pad_data, kernel = s[conv].op.input_tensors\n\n    s[pad_data].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, f, d, y, x = s[output].op.axis\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    bd, vd, td, di = cfg[\"tile_d\"].apply(s, output, d)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].reorder(bf, bd, by, bx, vf, vd, vy, vx, tf, td, ty, tx, fi, di, yi, xi)\n\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(s[output].fuse(bd, by), te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vd, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(s[output].fuse(td, tf), te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, f, d, y, x = s[OL].op.axis\n    rc, rd, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    rdo, rdi = cfg[\"tile_rd\"].apply(s, OL, rd)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n    s[OL].reorder(rco, rdo, ryo, rxo, rci, rdi, ryi, rxi, n, f, d, y, x)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        n, f, d, y, x = s[load].op.axis\n        fused = s[load].fuse(n, f, d, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n        td, fused = s[load].split(fused, nparts=cfg[\"tile_d\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(s[load].fuse(td, ty), te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    N, CO, OD, OH, OW = get_const_tuple(output.shape)\n    _, KD, KH, KW, CI = get_const_tuple(kernel.shape)\n    cfg.add_flop(2 * N * OD * OH * OW * CO * CI * KD * KH * KW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d_ndhwc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-function-args\n# pylint: disable=too-many-statements, unused-argument, too-many-arguments\n\"\"\"Tensorcore template for cuda backend\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple, traverse_inline, simplify\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple3d\nfrom .tensor_intrin import intrin_wmma_load_matrix_A\nfrom .tensor_intrin import intrin_wmma_load_matrix_W\nfrom .tensor_intrin import intrin_wmma_store_matrix\nfrom .tensor_intrin import intrin_wmma_gemm\n\n\ndef ndhwc_tensorcore_cuda(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    \"\"\"Compute declaration for conv3d tensorcore function\"\"\"\n    assert isinstance(stride, int) or len(stride) == 3\n    assert isinstance(dilation, int) or len(dilation) == 3\n\n    if isinstance(stride, int):\n        stride_d = stride_h = stride_w = stride\n    else:\n        stride_d, stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_d = dilation_h = dilation_w = dilation\n    else:\n        dilation_d, dilation_h, dilation_w = dilation\n\n    batch, in_depth, in_height, in_width, in_channel = get_const_tuple(Input.shape)\n    kernel_d, kernel_h, kernel_w, _, num_filter = get_const_tuple(Filter.shape)\n    assert (\n        (batch % 16 == 0 and in_channel % 16 == 0 and num_filter % 16 == 0)\n        or (batch % 8 == 0 and in_channel % 16 == 0 and num_filter % 32 == 0)\n        or (batch % 32 == 0 and in_channel % 16 == 0 and num_filter % 8 == 0)\n    ), (\n        \"The shape of (batch, in_channel, num_filter) \"\n        \"must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32) for now\"\n    )\n\n    # compute the output shape\n    dilated_kernel_d = (kernel_d - 1) * dilation_d + 1\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_front, pad_top, pad_left, pad_back, pad_down, pad_right = get_pad_tuple3d(\n        padding, (dilated_kernel_d, dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = num_filter\n    out_depth = simplify((in_depth - dilated_kernel_d + pad_front + pad_back) // stride_d + 1)\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    pad_before = [0, pad_front, pad_top, pad_left, 0]\n    pad_after = [0, pad_back, pad_down, pad_right, 0]\n    PaddedInput = pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    rz = te.reduce_axis((0, kernel_d), name=\"rz\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    # convert data type of input feature maps and weights\n    # TODO: add checking here, datatype casting may cause precision loss\n    TransPaddedInput = te.compute(\n        PaddedInput.shape, lambda n, d, h, w, c: PaddedInput[n, d, h, w, c].astype(\"float16\")\n    )\n    TransFilter = te.compute(\n        Filter.shape, lambda d, h, w, i, o: Filter[d, h, w, i, o].astype(\"float16\")\n    )\n    Output = te.compute(\n        (batch, out_depth, out_height, out_width, out_channel),\n        lambda nn, zz, yy, xx, ff: te.sum(\n            TransPaddedInput[\n                nn,\n                zz * stride_d + rz * dilation_d,\n                yy * stride_h + ry * dilation_h,\n                xx * stride_w + rx * dilation_w,\n                rc,\n            ].astype(out_dtype)\n            * TransFilter[rz, ry, rx, rc, ff].astype(out_dtype),\n            axis=[rz, ry, rx, rc],\n        ),\n        name=\"Conv3dOutput\",\n        tag=\"conv3d_ndhwc_tensorcore\",\n    )\n    return Output\n\n\ndef schedule_ndhwc_tensorcore_cuda(cfg, s, Conv):\n    \"\"\"Schedule tensorcore template\"\"\"\n    kd, kh, kw, ic = s[Conv].op.reduce_axis\n    out_dtype = Conv.dtype\n    trans_paddata, kernel = s[Conv].op.input_tensors\n    in_dtype = trans_paddata.dtype\n    batch, _, _, _, _ = get_const_tuple(Conv.shape)\n    _, _, _, _, out_channels = get_const_tuple(kernel.shape)\n    paddata = s[trans_paddata].op.input_tensors\n\n    # inline the pad and dtype transform\n    s[trans_paddata].compute_inline()\n    s[kernel].compute_inline()\n    s[paddata[0]].compute_inline()\n\n    # Designate the memory hierarchy\n    AS = s.cache_read(trans_paddata, \"shared\", [Conv])\n    WS = s.cache_read(kernel, \"shared\", [Conv])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\n    WF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\n    ConvF = s.cache_write(Conv, \"wmma.accumulator\")\n\n    if Conv.op in s.outputs:\n        output = Conv\n        ConvS = s.cache_read(ConvF, \"shared\", [Conv])\n        OL = ConvS\n    else:\n        output = s.outputs[0].output(0)\n        s[Conv].set_scope(\"shared\")\n        OL = Conv\n\n    # Schedule for autotvm\n    cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n    cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n    cfg.define_knob(\"warp_row_tiles\", [1, 2, 4])\n    cfg.define_knob(\"warp_col_tiles\", [1, 2, 4])\n    cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n    cfg.define_knob(\"offset\", [0, 8])\n    cfg.define_knob(\"vector_width\", [1, 2, 4, 8])\n\n    if batch % 16 == 0 and out_channels % 16 == 0:\n        cfg.define_knob(\"wmma_m\", [16, 8, 32])\n    elif batch % 8 == 0 and out_channels % 32 == 0:\n        cfg.define_knob(\"wmma_m\", [8, 16, 32])\n    elif batch % 32 == 0 and out_channels % 8 == 0:\n        cfg.define_knob(\"wmma_m\", [32, 16, 8])\n\n    # fallback support\n    target = tvm.target.Target.current()\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            target.kind.name, target.model, \"conv3d_ndhwc_tensorcore.cuda\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n\n    block_row_warps = cfg[\"block_row_warps\"].val\n    block_col_warps = cfg[\"block_col_warps\"].val\n    warp_row_tiles = cfg[\"warp_row_tiles\"].val\n    warp_col_tiles = cfg[\"warp_col_tiles\"].val\n    chunk = cfg[\"chunk\"].val\n    offset = cfg[\"offset\"].val\n    wmma_m = cfg[\"wmma_m\"].val\n    vector_width = cfg[\"vector_width\"].val\n\n    wmma_k = 16\n    if wmma_m == 16:\n        wmma_n = 16\n    elif wmma_m == 8:\n        wmma_n = 32\n    elif wmma_m == 32:\n        wmma_n = 8\n\n    warp_size = 32\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    # Define the intrin strides\n    def get_strides(extents):\n        return [np.prod(extents[i:]).tolist() for i in range(len(extents))]\n\n    AS_align = chunk * wmma_k + offset\n    WS_align = warp_col_tiles * block_col_warps * wmma_n + offset\n    block_factor_n = wmma_m * warp_row_tiles * block_row_warps\n    block_factor_o = wmma_n * warp_col_tiles * block_col_warps\n    CS_align = block_factor_o + offset\n    AS_strides = get_strides([1, 1, 1, AS_align, 1])\n    AL_strides = get_strides([1, 1, 1, wmma_k, 1])\n    WS_strides = get_strides([WS_align, 1])\n    WL_strides = get_strides([wmma_n * warp_col_tiles, 1])\n    CL_strides = get_strides([1, 1, 1, wmma_n * warp_col_tiles, 1])\n    CS_strides = get_strides([1, 1, 1, CS_align, 1])\n\n    # Schedule for output\n    nc, dc, hc, wc, oc = output.op.axis\n    block_k = s[output].fuse(dc, hc, wc)\n    s[output].bind(block_k, block_z)\n    block_i, nc = s[output].split(nc, factor=block_factor_n)\n    block_j, oc = s[output].split(oc, factor=block_factor_o)\n    s[output].reorder(block_k, block_i, block_j, nc, oc)\n    t = s[output].fuse(nc, oc)\n    t, ti = s[output].split(t, factor=vector_width)\n    t, tx = s[output].split(t, factor=warp_size)\n    t, ty = s[output].split(t, factor=block_row_warps)\n    t, tz = s[output].split(t, factor=block_col_warps)\n    s[output].bind(block_i, block_x)\n    s[output].bind(block_j, block_y)\n    s[output].bind(tz, thread_z)\n    s[output].bind(ty, thread_y)\n    s[output].bind(tx, thread_x)\n    s[output].vectorize(ti)\n\n    # Schedule wmma store\n    s[OL].compute_at(s[output], block_j)\n    nc, dc, hc, wc, oc = OL.op.axis\n    s[OL].reorder(dc, hc, wc, nc, oc)\n    s[OL].storage_align(wc, CS_align - 1, CS_align)\n    oc, ooc = s[OL].split(oc, factor=wmma_n)\n    oc, oci = s[OL].split(oc, factor=warp_col_tiles)\n    _, oc = s[OL].split(oc, factor=block_col_warps)\n    nc, nnc = s[OL].split(nc, factor=wmma_m)\n    nc, nci = s[OL].split(nc, factor=warp_row_tiles)\n    _, nc = s[OL].split(nc, factor=block_row_warps)\n    s[OL].reorder(nc, oc, nci, oci, nnc, ooc)\n    s[OL].bind(nc, thread_y)\n    s[OL].bind(oc, thread_z)\n\n    # Schedule wmma computation\n    s[ConvF].compute_at(s[OL], oc)\n    n, d, h, w, o = ConvF.op.axis\n    n, nnf = s[ConvF].split(n, factor=wmma_m)\n    o, oof = s[ConvF].split(o, factor=wmma_n)\n    ic, ii = s[ConvF].split(ic, factor=wmma_k)\n    ko, ki = s[ConvF].split(ic, factor=chunk)\n    s[ConvF].reorder(kd, kh, kw, ko, ki, n, o, nnf, oof, ii)\n\n    s[AF].compute_at(s[ConvF], ki)\n    s[WF].compute_at(s[ConvF], ki)\n\n    # Schedule wmma load\n    n, d, h, w, i = AF.op.axis\n    n, nn = s[AF].split(n, factor=wmma_m)\n    i, ii = s[AF].split(i, factor=wmma_k)\n    s[AF].reorder(n, i, nn, ii)\n\n    kd, kh, kw, i, o = WF.op.axis\n    i, ii = s[WF].split(i, factor=wmma_k)\n    o, oo = s[WF].split(o, factor=wmma_n)\n    s[WF].reorder(o, i, oo)\n    s[WF].reorder(i, o, ii, oo)\n\n    s[WS].compute_at(s[ConvF], ko)\n    s[AS].compute_at(s[ConvF], ko)\n\n    # Schedule for data's share memory\n    n, d, h, w, i = AS.op.axis\n    s[AS].reorder(d, h, w, n, i)\n    s[AS].storage_align(w, AS_align - 1, AS_align)\n    t = s[AS].fuse(n, i)\n    t, ti = s[AS].split(t, factor=vector_width)\n    t, tx = s[AS].split(t, factor=warp_size)\n    t, ty = s[AS].split(t, factor=block_row_warps)\n    _, tz = s[AS].split(t, factor=block_col_warps)\n    s[AS].bind(ty, thread_y)\n    s[AS].bind(tz, thread_z)\n    s[AS].bind(tx, thread_x)\n    s[AS].vectorize(ti)\n\n    # Schedule for kernel's share memory\n    kd, kh, kw, ic, o = WS.op.axis\n    t = s[WS].fuse(ic, o)\n    s[WS].storage_align(ic, WS_align - 1, WS_align)\n    t, ti = s[WS].split(t, factor=vector_width)\n    t, tx = s[WS].split(t, factor=warp_size)\n    t, ty = s[WS].split(t, factor=block_row_warps)\n    _, tz = s[WS].split(t, factor=block_col_warps)\n    s[WS].bind(ty, thread_y)\n    s[WS].bind(tz, thread_z)\n    s[WS].bind(tx, thread_x)\n    s[WS].vectorize(ti)\n\n    shape = (wmma_m, wmma_n, wmma_k)\n\n    # tensorize the wmma process\n    AS_shape = (wmma_m, 1, 1, 1, wmma_k)\n    AL_shape = (wmma_m, 1, 1, 1, wmma_k)\n    WS_shape = (wmma_k, wmma_n)\n    WL_shape = (wmma_k, wmma_n)\n    CL_shape = (wmma_m, 1, 1, 1, wmma_n)\n    CS_shape = (wmma_m, 1, 1, 1, wmma_n)\n\n    AL_gemm = te.placeholder(AL_shape, name=\"A\", dtype=in_dtype)\n    WL_gemm = te.placeholder(WL_shape, name=\"B\", dtype=in_dtype)\n    k_gemm = te.reduce_axis((0, wmma_k), name=\"k\")\n    CL_compute = te.compute(\n        CL_shape,\n        lambda ii, t0, t1, t2, jj: te.sum(\n            AL_gemm[ii, t0, t1, t2, k_gemm].astype(out_dtype)\n            * WL_gemm[k_gemm, jj].astype(out_dtype),\n            axis=k_gemm,\n        ),\n        name=\"C\",\n    )\n\n    s[AF].tensorize(\n        nn,\n        intrin_wmma_load_matrix_A(\n            AL_strides, AS_strides, shape, \"row_major\", AS_shape, AL_shape, in_dtype\n        ),\n    )\n    s[WF].tensorize(\n        ii,\n        intrin_wmma_load_matrix_W(\n            WL_strides, WS_strides, shape, \"row_major\", WS_shape, WL_shape, in_dtype\n        ),\n    )\n    s[OL].tensorize(\n        nnc, intrin_wmma_store_matrix(CS_strides, CL_strides, shape, out_dtype, CL_shape, CS_shape)\n    )\n    s[ConvF].tensorize(\n        nnf,\n        intrin_wmma_gemm(AL_gemm, WL_gemm, CL_compute, AL_strides, WL_strides, CL_strides, shape),\n    )\n\n    N, OD, OH, OW, CO = get_const_tuple(output.shape)\n    KD, KH, KW, CI, _ = get_const_tuple(kernel.shape)\n    cfg.add_flop(2 * N * OD * OH * OW * CO * CI * KD * KH * KW)\n\n\n@autotvm.register_topi_compute(\"conv3d_ndhwc_tensorcore.cuda\")\ndef conv3d_ndhwc_tensorcore(cfg, data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"Compute conv3d with tensorcore for NDHWC layout\"\"\"\n    assert groups == 1, \"tensorcore conv3d does not support groups\"\n    return ndhwc_tensorcore_cuda(cfg, data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv3d_ndhwc_tensorcore.cuda\")\ndef schedule_conv3d_ndhwc_tensorcore(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv3d_ndhwc_tensorcore\" in op.tag:\n            schedule_ndhwc_tensorcore_cuda(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d_transpose_ncdhw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Conv3d transpose template for cuda backend\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom .. import nn\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .conv3d_direct import schedule_direct_conv3d_cuda\n\n\n@autotvm.register_topi_compute(\"conv3d_transpose_ncdhw.cuda\")\ndef conv3d_transpose_ncdhw(cfg, data, kernel, stride, padding, out_dtype, output_padding):\n    \"\"\"Transposed 3D convolution ncdhw forward operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n    Filter : tvm.te.Tensor\n        5-D with shape [in_channel, num_filter, filter_depth, filter_height, filter_width]\n    strides : int or a list/tuple of three ints\n        The spatial stride along height and width\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n    out_dtype: str\n        The output type. This is used in mixed precision\n    output_padding : tuple of three ints\n        Used to disambiguate output shape\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    batch, inp_channels, inp_depth, inp_height, inp_width = get_const_tuple(data.shape)\n    _, out_channels, kernel_depth, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n    stride_depth, stride_height, stride_width = stride\n    outpad_depth, outpad_height, outpad_width = output_padding\n    assert (\n        outpad_height < stride_height\n        and outpad_width < stride_width\n        and outpad_depth < stride_depth\n    )\n    cfg.stride = stride\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = nn.get_pad_tuple3d(\n        padding, (kernel_depth, kernel_height, kernel_width)\n    )\n\n    out_depth = (inp_depth - 1) * stride_depth + kernel_depth - pad_front - pad_back + outpad_depth\n    pad_front = kernel_depth - 1 - pad_front\n    pad_back = kernel_depth - 1 - pad_back\n    dilated_depth = stride_depth * (inp_depth - 1) + 1\n\n    out_width = (inp_width - 1) * stride_width + kernel_width - pad_left - pad_right + outpad_width\n    pad_left = kernel_width - 1 - pad_left\n    pad_right = kernel_width - 1 - pad_right\n    dilated_width = stride_width * (inp_width - 1) + 1\n\n    out_height = (\n        (inp_height - 1) * stride_height + kernel_height - pad_top - pad_bottom + outpad_height\n    )\n    pad_top = kernel_height - 1 - pad_top\n    pad_bottom = kernel_height - 1 - pad_bottom\n    dilated_height = stride_height * (inp_height - 1) + 1\n\n    # compute pad\n    data = te.compute(\n        (\n            batch,\n            inp_channels,\n            pad_front + dilated_depth + pad_back,\n            pad_top + dilated_height + pad_bottom,\n            pad_left + dilated_width + pad_right,\n        ),\n        lambda n, c, d, y, x: tvm.tir.if_then_else(\n            tvm.tir.all(\n                x >= pad_left,\n                x < pad_left + dilated_width,\n                tvm.tir.indexmod(x - pad_left, stride_width).equal(0),\n                y >= pad_top,\n                y < pad_top + dilated_height,\n                tvm.tir.indexmod(y - pad_top, stride_height).equal(0),\n                d >= pad_front,\n                d < pad_front + dilated_depth,\n                tvm.tir.indexmod(d - pad_front, stride_depth).equal(0),\n            ),\n            data[\n                n,\n                c,\n                tvm.tir.indexdiv(d - pad_front, stride_depth),\n                tvm.tir.indexdiv(y - pad_top, stride_height),\n                tvm.tir.indexdiv(x - pad_left, stride_width),\n            ],\n            tvm.tir.const(0.0, \"float32\"),\n        ),\n        name=\"data_pad\",\n    )\n\n    # compute transposed conv\n    dc = te.reduce_axis((0, inp_channels), name=\"dc\")\n    dd = te.reduce_axis((0, kernel_depth), name=\"dd\")\n    dh = te.reduce_axis((0, kernel_height), name=\"dh\")\n    dw = te.reduce_axis((0, kernel_width), name=\"dw\")\n    data_out = te.compute(\n        (batch, out_channels, out_depth, out_height, out_width),\n        lambda b, c, d, h, w: te.sum(\n            data[b, dc, d + dd, h + dh, w + dw].astype(out_dtype)\n            * kernel[\n                dc, c, kernel_depth - 1 - dd, kernel_height - 1 - dh, kernel_width - 1 - dw\n            ].astype(out_dtype),\n            axis=[dc, dd, dh, dw],\n        ),\n        tag=\"conv3d_transpose_ncdhw\",\n    )\n\n    return data_out\n\n\n@autotvm.register_topi_schedule(\"conv3d_transpose_ncdhw.cuda\")\ndef schedule_conv3d_transpose_ncdhw(cfg, outs):\n    \"\"\"TOPI Schedule callback for conv3d transpose operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The parameters for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv3d transpose\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv3d transpose.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv3d_transpose_ncdhw\":\n            schedule_direct_conv3d_cuda(\n                cfg, s, op.output(0), \"NCDHW\", \"conv3d_transpose_ncdhw.cuda\"\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/conv3d_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Winograd template for cuda backend\"\"\"\n\nimport logging\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import get_const_int, get_const_tuple, traverse_inline, simplify\nfrom ..nn.winograd_util import winograd_transform_matrices\n\nlogger = logging.getLogger(\"conv3d_winograd\")\n\n\ndef _infer_tile_size(data, kernel):\n    N, CI, D, H, W = get_const_tuple(data.shape)\n\n    if H % 8 == 0:\n        return 4\n    return 2\n\n\ndef winograd_cuda(cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed):\n    \"\"\"Compute declaration for winograd\"\"\"\n    tile_size = _infer_tile_size(data, kernel)\n\n    N, CI, D, H, W = get_const_tuple(data.shape)\n\n    if isinstance(dilation, int):\n        dilation_d = dilation_h = dilation_w = dilation\n    else:\n        dilation_d, dilation_h, dilation_w = dilation\n    DSTR, HSTR, WSTR = (strides, strides, strides) if isinstance(strides, int) else strides\n\n    if not pre_computed:  # kernel tensor is raw tensor, do strict check\n        if dilation_d != 1 or dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_d, dilation_h, dilation_w))\n        CO, CI, KD, KH, KW = get_const_tuple(kernel.shape)\n        alpha = KW + tile_size - 1\n        assert DSTR == 1 and HSTR == 1 and WSTR == 1 and KD == KH and KH == KW\n    else:\n        # kernel tensor is pre-transformed. this op is created by alter op layout.\n        # dilation is not supported\n        alpha, _, _, CO, CI = get_const_tuple(kernel.shape)\n        KD = KH = KW = alpha + 1 - tile_size\n        assert (\n            DSTR == 1\n            and HSTR == 1\n            and WSTR == 1\n            and dilation_d == 1\n            and dilation_h == 1\n            and dilation_w == 1\n        )\n\n    pf, pt, pl, pb, pd, pr = nn.get_pad_tuple3d(padding, (KD, KH, KW))\n    data_pad = nn.pad(data, (0, 0, pf, pt, pl), (0, 0, pb, pd, pr), name=\"data_pad\")\n\n    r = KW\n    m = tile_size\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    D = (D + pf + pb - KD) // DSTR + 1\n    H = (H + pt + pd - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nD, nH, nW = (D + m - 1) // m, (H + m - 1) // m, (W + m - 1) // m\n    P = N * nD * nH * nW\n\n    # transform kernel\n    if not pre_computed:\n        # Check if we are currently tuning, if so we want to avoid counting\n        # prepacking in time costs. Just use a placeholder with the packed shape instead.\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            kernel_pack = te.placeholder(\n                (alpha, alpha, alpha, CO, CI), dtype=kernel.dtype, name=\"kernel_pack\"\n            )\n        else:\n            r_kd = te.reduce_axis((0, KD), name=\"r_kd\")\n            r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n            r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n            kernel_pack = te.compute(\n                (alpha, alpha, alpha, CO, CI),\n                lambda omg, eps, nu, co, ci: te.sum(\n                    kernel[co][ci][r_kd][r_kh][r_kw] * G[omg][r_kd] * G[eps][r_kh] * G[nu][r_kw],\n                    axis=[r_kd, r_kh, r_kw],\n                ),\n                name=\"kernel_pack\",\n            )\n    else:\n        kernel_pack = kernel\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    # pack input tile\n    input_tile = te.compute(\n        (CI, P, alpha, alpha, alpha),\n        lambda c, p, omg, eps, nu: data_pad[idxdiv(p, (nD * nH * nW))][c][\n            idxmod(idxdiv(p, nH * nW), nD) * m + omg\n        ][idxmod(idxdiv(p, nW), nH) * m + eps][idxmod(p, nW) * m + nu],\n        name=\"d\",\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    r_c = te.reduce_axis((0, alpha), \"r_c\")\n    data_pack = te.compute(\n        (alpha, alpha, alpha, CI, P),\n        lambda omg, eps, nu, ci, p: te.sum(\n            input_tile[ci][p][r_a][r_b][r_c] * B[r_a][omg] * B[r_b][eps] * B[r_c][nu],\n            axis=[r_a, r_b, r_c],\n        ),\n        name=\"data_pack\",\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, alpha, CO, P),\n        lambda omg, eps, nu, co, p: te.sum(\n            kernel_pack[omg][eps][nu][co][ci] * data_pack[omg][eps][nu][ci][p], axis=[ci]\n        ),\n        name=\"bgemm\",\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    r_c = te.reduce_axis((0, alpha), \"r_c\")\n    inverse = te.compute(\n        (CO, P, m, m, m),\n        lambda co, p, vd, vh, vw: te.sum(\n            bgemm[r_a][r_b][r_c][co][p] * A[r_a][vd] * A[r_b][vh] * A[r_c][vw], axis=[r_a, r_b, r_c]\n        ),\n        name=\"inverse\",\n    )\n\n    # output\n    output = te.compute(\n        (N, CO, D, H, W),\n        lambda n, co, d, h, w: inverse[\n            co,\n            n * nD * nH * nW + idxdiv(d, m) * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m),\n            idxmod(d, m),\n            idxmod(h, m),\n            idxmod(w, m),\n        ],\n        name=\"output\",\n        tag=\"conv3d_ncdhw_winograd\",\n    )\n    cfg.add_flop(2 * N * CO * D * H * W * CI * KD * KH * KW)\n\n    return output\n\n\ndef winograd_without_depth_cuda(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed\n):\n    \"\"\"Compute declaration for winograd without transforming depth\"\"\"\n    tile_size = _infer_tile_size(data, kernel)\n\n    N, CI, D, H, W = get_const_tuple(data.shape)\n\n    if isinstance(dilation, int):\n        dilation_d = dilation_h = dilation_w = dilation\n    else:\n        dilation_d, dilation_h, dilation_w = dilation\n    DSTR, HSTR, WSTR = (strides, strides, strides) if isinstance(strides, int) else strides\n\n    if not pre_computed:  # kernel tensor is raw tensor, do strict check\n        if dilation_d != 1 or dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_d, dilation_h, dilation_w))\n        CO, CI, KD, KH, KW = get_const_tuple(kernel.shape)\n        alpha = KW + tile_size - 1\n        assert HSTR == 1 and WSTR == 1 and KH == KW\n    else:\n        # kernel tensor is pre-transfomred. this op is created by alter op layout.\n        # dilation is not supported\n        alpha, _, KD, CO, CI = get_const_tuple(kernel.shape)\n        KH = KW = alpha + 1 - tile_size\n        assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1\n\n    pf, pt, pl, pb, pd, pr = nn.get_pad_tuple3d(padding, (KD, KH, KW))\n    data_pad = nn.pad(data, (0, 0, pf, pt, pl), (0, 0, pb, pd, pr), name=\"data_pad\")\n    out_depth = simplify((D - KD + pf + pb) // DSTR + 1)\n    D += pf + pb\n\n    r = KW\n    m = tile_size\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    H = (H + pt + pd - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n\n    # transform kernel\n    if not pre_computed:\n        # During autotuning dont count kernel packing as a time cost\n        # as it will later be removed via alter_op_layout.\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            kernel_pack = te.placeholder(\n                (alpha, alpha, KD, CO, CI), dtype=kernel.dtype, name=\"kernel_pack\"\n            )\n        else:\n            r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n            r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n            kernel_pack = te.compute(\n                (alpha, alpha, KD, CO, CI),\n                lambda eps, nu, d, co, ci: te.sum(\n                    kernel[co][ci][d][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n                ),\n                name=\"kernel_pack\",\n            )\n    else:\n        kernel_pack = kernel\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    # pack input tile\n    input_tile = te.compute(\n        (CI, D, P, alpha, alpha),\n        lambda c, d, p, eps, nu: data_pad[idxdiv(p, (nH * nW))][c][d][\n            idxmod(idxdiv(p, nW), nH) * m + eps\n        ][idxmod(p, nW) * m + nu],\n        name=\"d\",\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    data_pack = te.compute(\n        (alpha, alpha, CI, D, P),\n        lambda eps, nu, ci, d, p: te.sum(\n            input_tile[ci][d][p][r_a][r_b] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"data_pack\",\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    rz = te.reduce_axis((0, KD), name=\"rz\")\n    bgemm = te.compute(\n        (alpha, alpha, CO, out_depth, P),\n        lambda eps, nu, co, d, p: te.sum(\n            kernel_pack[eps][nu][rz][co][ci] * data_pack[eps][nu][ci][d * DSTR + rz][p],\n            axis=[ci, rz],\n        ),\n        name=\"bgemm\",\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    inverse = te.compute(\n        (CO, out_depth, P, m, m),\n        lambda co, d, p, vh, vw: te.sum(\n            bgemm[r_a][r_b][co][d][p] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]\n        ),\n        name=\"inverse\",\n    )\n\n    # output\n    output = te.compute(\n        (N, CO, out_depth, H, W),\n        lambda n, co, d, h, w: inverse[\n            co, d, n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), idxmod(h, m), idxmod(w, m)\n        ],\n        name=\"output\",\n        tag=\"conv3d_ncdhw_winograd_without_depth\",\n    )\n    cfg.add_flop(2 * N * CO * D * H * W * CI * KD * KH * KW)\n\n    return output\n\n\ndef schedule_winograd_cuda(cfg, s, output, pre_computed):\n    \"\"\"Schedule winograd template\"\"\"\n    # get stages\n    inverse = s[output].op.input_tensors[0]\n    bgemm, A = s[inverse].op.input_tensors\n    kernel_pack, data_pack = s[bgemm].op.input_tensors\n    input_tile, B = s[data_pack].op.input_tensors\n    pad_data = s[input_tile].op.input_tensors[0]\n\n    # data transform\n    s[B].compute_inline()\n\n    data_l = s.cache_write(data_pack, \"local\")\n    omg, eps, nu, c, p = s[data_l].op.axis\n    r_a, r_b, r_c = s[data_l].op.reduce_axis\n    # TODO unrolling by omg, eps, nu may improve performance but\n    # in some cases causes extremely long build times due to imperfect tiling.\n    for axis in [r_a, r_b, r_c]:\n        s[data_l].unroll(axis)\n\n    omg, eps, nu, c, p = s[data_pack].op.axis\n    p, pi = s[data_pack].split(p, 1)\n    fused = s[data_pack].fuse(c, p)\n    bb, tt = s[data_pack].split(fused, 128)\n    s[data_pack].reorder(bb, tt, pi, omg, eps, nu)\n    s[data_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[data_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    s[data_l].compute_at(s[data_pack], pi)\n    s[input_tile].compute_at(s[data_pack], pi)\n    s[pad_data].compute_inline()\n\n    # transform kernel\n    if not pre_computed and not autotvm.GLOBAL_SCOPE.in_tuning:\n        kernel, G = s[kernel_pack].op.input_tensors\n        omg, eps, nu, co, ci = s[kernel_pack].op.axis\n        s[G].compute_inline()\n        r_a, r_b, r_c = s[kernel_pack].op.reduce_axis\n        # Could add additional unrolling by omg, eps, nu in the future.\n        for axis in [r_a, r_b, r_c]:\n            s[kernel_pack].unroll(axis)\n\n        fused = s[kernel_pack].fuse(co, ci)\n        bb, tt = s[kernel_pack].split(fused, 128)\n        s[kernel_pack].reorder(bb, tt, omg, eps, nu, r_a, r_b, r_c)\n        s[kernel_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n        s[kernel_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n    else:\n        kernel = kernel_pack\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    ##### space definition begin #####\n    b1, b2, b3, y, x = s[bgemm].op.axis\n    rc = s[bgemm].op.reduce_axis[0]\n    alpha = get_const_int(b1.dom.extent)\n\n    cfg.define_split(\n        \"tile_b\",\n        cfg.axis(alpha * alpha * alpha),\n        num_outputs=4,\n        filter=lambda x: x.size[-3:] == [1, 1, 1],\n    )\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 128, 1500])\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n    ##### space definition end #####\n\n    # batch gemm\n    C = bgemm\n    A0, B0 = kernel_pack, data_pack\n\n    OL = s.cache_write(C, \"local\")\n    AA = s.cache_read(A0, \"shared\", [OL])\n    BB = s.cache_read(B0, \"shared\", [OL])\n\n    b = s[bgemm].fuse(b1, b2, b3)\n\n    # tile and bind spatial axes\n    bgemm_scope, b = s[bgemm].split(b, nparts=1)\n    bz, vz, tz, zi = cfg[\"tile_b\"].apply(s, C, b)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, C, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].bind(bz, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(vz, te.thread_axis(\"vthread\"))\n    s[C].bind(vy, te.thread_axis(\"vthread\"))\n    s[C].bind(vx, te.thread_axis(\"vthread\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].reorder(bgemm_scope, bz, by, bx, vz, vy, vx, tz, ty, tx, zi, yi, xi)\n\n    # tile reduction axes\n    s[OL].compute_at(s[C], tx)\n    b1, b2, b3, y, x = s[OL].op.axis\n    b = s[OL].fuse(b1, b2, b3)\n    (rc,) = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    s[OL].reorder(rco, rci, b, y, x)\n\n    s[AA].compute_at(s[OL], rco)\n    s[BB].compute_at(s[OL], rco)\n\n    # cooperative fetching\n    for load in [AA, BB]:\n        fused = s[load].fuse(*list(s[load].op.axis))\n        fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n        fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n        fused, tz = s[load].split(fused, cfg[\"tile_b\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    s[C].pragma(bgemm_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[C].pragma(bgemm_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    # schedule inverse, output and fusion\n    if output.op in s.outputs:\n        OL = None\n    else:\n        OL = output\n        s[OL].set_scope(\"local\")\n        output = s.outputs[0]\n\n    m = alpha - 3 + 1\n    n, co, d, h, w = s[output].op.axis\n    do, di = s[output].split(d, m)\n    ho, hi = s[output].split(h, m)\n    wo, wi = s[output].split(w, m)\n    s[output].reorder(n, co, do, ho, wo, di, hi, wi)\n    inverse_scope, n = s[output].split(n, nparts=1)\n\n    fused = s[output].fuse(n, co, do, ho, wo)\n    bb, tt = s[output].split(fused, 128)\n\n    s[output].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    if OL is not None:\n        s[OL].compute_at(s[output], tt)\n\n    s[A].compute_inline()\n    co, p, vd, vh, vw = s[inverse].op.axis\n    r_a, r_b, r_c = s[inverse].op.reduce_axis\n    # Could add additional unrolling of vd, vh, vw, in the future\n    for axis in [r_a, r_b, r_c]:\n        s[inverse].unroll(axis)\n    s[inverse].compute_at(s[output], tt)\n\n    return s\n\n\ndef schedule_winograd_no_depth_cuda(cfg, s, output, pre_computed):\n    \"\"\"Schedule winograd template\"\"\"\n    # get stages\n    inverse = s[output].op.input_tensors[0]\n    bgemm, A = s[inverse].op.input_tensors\n    kernel_pack, data_pack = s[bgemm].op.input_tensors\n    input_tile, B = s[data_pack].op.input_tensors\n    pad_data = s[input_tile].op.input_tensors[0]\n\n    # data transform\n    s[B].compute_inline()\n\n    data_l = s.cache_write(data_pack, \"local\")\n    eps, nu, c, d, p = s[data_l].op.axis\n    r_a, r_b = s[data_l].op.reduce_axis\n    for axis in [eps, nu, r_a, r_b]:\n        s[data_l].unroll(axis)\n\n    eps, nu, c, d, p = s[data_pack].op.axis\n    p, pi = s[data_pack].split(p, 1)\n    fused = s[data_pack].fuse(c, d, p)\n    bb, tt = s[data_pack].split(fused, 128)\n    s[data_pack].reorder(bb, tt, pi, eps, nu)\n    s[data_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[data_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    s[data_l].compute_at(s[data_pack], pi)\n    s[input_tile].compute_at(s[data_pack], pi)\n    s[pad_data].compute_inline()\n\n    # transform kernel\n    if not pre_computed and not autotvm.GLOBAL_SCOPE.in_tuning:\n        kernel, G = s[kernel_pack].op.input_tensors\n        eps, nu, kd, co, ci = s[kernel_pack].op.axis\n        s[G].compute_inline()\n        r_a, r_b = s[kernel_pack].op.reduce_axis\n        for axis in [eps, nu, r_a, r_b]:\n            s[kernel_pack].unroll(axis)\n\n        fused = s[kernel_pack].fuse(kd, co, ci)\n        bb, tt = s[kernel_pack].split(fused, 128)\n        s[kernel_pack].reorder(bb, tt, eps, nu, r_a, r_b)\n        s[kernel_pack].bind(bb, te.thread_axis(\"blockIdx.x\"))\n        s[kernel_pack].bind(tt, te.thread_axis(\"threadIdx.x\"))\n    else:\n        kernel = kernel_pack\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    ##### space definition begin #####\n    b1, b2, z, y, x = s[bgemm].op.axis\n    # Combine channel and depth axes.\n    rc = s[bgemm].op.reduce_axis[0]\n    rz = s[bgemm].op.reduce_axis[1]\n    alpha = get_const_int(b1.dom.extent)\n\n    cfg.define_split(\n        \"tile_b\", cfg.axis(alpha * alpha), num_outputs=4, filter=lambda x: x.size[-3:] == [1, 1, 1]\n    )\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_rz\", rz, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 128, 1500])\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n    ##### space definition end #####\n\n    # batch gemm\n    C = bgemm\n    A0, B0 = kernel_pack, data_pack\n\n    OL = s.cache_write(C, \"local\")\n    AA = s.cache_read(A0, \"shared\", [OL])\n    BB = s.cache_read(B0, \"shared\", [OL])\n\n    b = s[bgemm].fuse(b1, b2)\n    # Allow two different tiling strategies as both seem\n    # to work best in different cases.\n    cfg.define_knob(\"unroll_axis\", [0, 1])\n    # tile and bind spatial axes\n    bgemm_scope, b = s[bgemm].split(b, nparts=1)\n    bz, vz, tz, zi = cfg[\"tile_b\"].apply(s, C, b)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, C, z)\n    if cfg[\"unroll_axis\"].val:\n        bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, C, y)\n    else:\n        bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].bind(bz, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(vz, te.thread_axis(\"vthread\"))\n    s[C].bind(vy, te.thread_axis(\"vthread\"))\n    s[C].bind(vx, te.thread_axis(\"vthread\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].reorder(bgemm_scope, bz, by, bx, vz, vy, vx, tz, ty, tx, zi, yi, xi)\n    if cfg[\"unroll_axis\"].val:\n        s[C].unroll(x)\n    else:\n        s[C].unroll(y)\n\n    # tile reduction axes\n    s[OL].compute_at(s[C], tx)\n    b1, b2, y1, y2, x = s[OL].op.axis\n    y = s[OL].fuse(y1, y2)\n    b = s[OL].fuse(b1, b2)\n    rc, rz = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    rzo, rzi = cfg[\"tile_rz\"].apply(s, OL, rz)\n    s[OL].reorder(rco, rzo, rci, rzi, b, y, x)\n\n    s[AA].compute_at(s[OL], rco)\n    s[BB].compute_at(s[OL], rco)\n\n    # cooperative fetching\n    for load in [AA, BB]:\n        fused = s[load].fuse(*list(s[load].op.axis))\n        fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n        fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n        fused, tz = s[load].split(fused, cfg[\"tile_b\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    s[C].pragma(bgemm_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[C].pragma(bgemm_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    # schedule inverse, output and fusion\n    if output.op in s.outputs:\n        OL = None\n    else:\n        OL = output\n        s[OL].set_scope(\"local\")\n        output = s.outputs[0]\n\n    m = alpha - 3 + 1\n    n, co, d, h, w = s[output].op.axis\n    do, di = s[output].split(d, m)\n    ho, hi = s[output].split(h, m)\n    wo, wi = s[output].split(w, m)\n    s[output].reorder(n, co, do, ho, wo, di, hi, wi)\n    inverse_scope, n = s[output].split(n, nparts=1)\n\n    fused = s[output].fuse(n, co, do, ho, wo)\n    bb, tt = s[output].split(fused, 128)\n\n    s[output].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    if OL is not None:\n        s[OL].compute_at(s[output], tt)\n\n    s[A].compute_inline()\n    co, d, p, vh, vw = s[inverse].op.axis\n    r_a, r_b = s[inverse].op.reduce_axis\n    for axis in [vh, vw, r_a, r_b]:\n        s[inverse].unroll(axis)\n    s[inverse].compute_at(s[output], tt)\n\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3d_ncdhw_winograd.cuda\")\ndef conv3d_ncdhw_winograd(cfg, data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"Conv3d NCDHW using winograd optimization\"\"\"\n    assert groups == 1, \"conv3d_ncdhw_winograd only supports a single group\"\n    CO, CI, KD, KH, KW = get_const_tuple(kernel.shape)\n    # Check if we can transform depth.\n    if 2 < KD < 8 and KD == KH:\n        return winograd_cuda(\n            cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=False\n        )\n\n    return winograd_without_depth_cuda(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=False\n    )\n\n\n@autotvm.register_topi_schedule(\"conv3d_ncdhw_winograd.cuda\")\ndef schedule_conv3d_ncdhw_winograd(cfg, outs):\n    \"\"\"Dispatch to schedule approriate for conv3d winograd algorithm used.\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv3d_ncdhw_winograd_without_depth\" in op.tag:\n            schedule_winograd_no_depth_cuda(cfg, s, op.output(0), pre_computed=False)\n        elif \"conv3d_ncdhw_winograd\" in op.tag:\n            schedule_winograd_cuda(cfg, s, op.output(0), pre_computed=False)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3d_ncdhw_winograd_without_weight_transform.cuda\")\ndef conv3d_ncdhw_winograd_without_weight_transform(\n    cfg, data, kernel, strides, padding, dilation, groups, out_dtype\n):\n    \"\"\"Conv3d NCDHW winograd without weight transform.\"\"\"\n    assert (\n        groups == 1\n    ), \"conv3d_ncdhw_winograd_without_weight_transform does not support more than one group\"\n    A, B, C, _, _ = get_const_tuple(kernel.shape)\n    # Check if we can transform depth.\n    if A == B == C:\n        return winograd_cuda(\n            cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=True\n        )\n\n    return winograd_without_depth_cuda(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, pre_computed=True\n    )\n\n\n@autotvm.register_topi_schedule(\"conv3d_ncdhw_winograd_without_weight_transform.cuda\")\ndef schedule_conv3d_ncdhw_winograd_without_weight_transform(cfg, outs):\n    \"\"\"TOPI schedule callback\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv3d_ncdhw_winograd_without_depth\" in op.tag:\n            schedule_winograd_no_depth_cuda(cfg, s, op.output(0), pre_computed=True)\n        elif \"conv3d_ncdhw_winograd\" in op.tag:\n            schedule_winograd_cuda(cfg, s, op.output(0), pre_computed=True)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/correlation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Correlation operators on CUDA\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline\n\n\n@autotvm.register_topi_compute(\"correlation_nchw.cuda\")\ndef correlation_nchw(\n    cfg, data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply\n):\n    \"\"\"Correlation operator in NCHW layout.\n\n    Parameters\n    ----------\n    data1 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    data2 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    kernel_size: int\n        Kernel size for correlation, must be an odd number\n\n    max_displacement: int\n        Max displacement of Correlation\n\n    stride1: int\n        Stride for data1\n\n    stride2: int\n        Stride for data2 within the neightborhood centered around data1\n\n    padding : int or a list/tuple of 2 or 4 ints\n        Padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    is_multiply: bocorrelation\n        operation type is either multiplication or substraction\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    # pylint: disable=unused-argument\n    return nn.correlation_nchw(\n        data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply\n    )\n\n\ndef _schedule_correlation_nchw(cfg, s, correlation):\n    \"\"\"Schedule correlation_nchw direct template\"\"\"\n    # pylint: disable=invalid-name\n    ##### space definition begin #####\n    n, f, y, x = s[correlation].op.axis\n    rc, ry, rx = s[correlation].op.reduce_axis\n    cfg.define_split(\"tile_f\", f, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    ##### space definition end #####\n\n    padded_data1, padded_data2 = s[correlation].op.input_tensors\n    s[padded_data1].compute_inline()\n    s[padded_data2].compute_inline()\n\n    # create cache stage\n    s[correlation].set_scope(\"local\")\n    AA = s.cache_read(padded_data1, \"shared\", [correlation])\n    BB = s.cache_read(padded_data2, \"shared\", [correlation])\n\n    output = s.outputs[0].output(0)\n\n    # tile and bind spatial axes\n    n, f, y, x = s[output].op.axis\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n    s[correlation].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, f, y, x = s[correlation].op.axis\n    rc, ry, rx = s[correlation].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, correlation, rc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, correlation, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, correlation, rx)\n    s[correlation].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x)\n\n    s[AA].compute_at(s[correlation], rxo)\n    s[BB].compute_at(s[correlation], rxo)\n\n    # cooperative fetching\n    for load in [AA, BB]:\n        n, f, y, x = s[load].op.axis\n        fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n\n@autotvm.register_topi_schedule(\"correlation_nchw.cuda\")\ndef schedule_correlation_nchw(cfg, outs):\n    \"\"\"schedule of correlation_nchw for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of correlation\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for correlation.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"correlation_nchw\":\n            _schedule_correlation_nchw(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/deformable_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Schedule template of deformable conv2d with cuda backend\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom .. import nn\nfrom ..utils import traverse_inline\n\n\n@autotvm.register_topi_compute(\"deformable_conv2d_nchw.cuda\")\ndef deformable_conv2d_nchw(\n    cfg, data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype\n):\n    \"\"\"Deformable Conv2d.\"\"\"\n    return nn.deformable_conv2d_nchw(\n        data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype\n    )\n\n\n@autotvm.register_topi_schedule(\"deformable_conv2d_nchw.cuda\")\ndef schedule_deformable_conv2d_nchw(cfg, outs):\n    \"\"\"TOPI schedule callback of deformable conv2d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"deformable_conv2d_nchw\":\n            _schedule_direct_cuda(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_direct_cuda(cfg, s, conv):\n    \"\"\"Schedule template of deformable conv2d\"\"\"\n    n, f, y, x = s[conv].op.axis\n    rc, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_f\", f, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    data_deform, kernel = s[conv].op.input_tensors\n\n    s[data_deform].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AA = s.cache_read(data_deform, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, f, y, x = s[output].op.axis\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, f, y, x = s[OL].op.axis\n    rc, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n    s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x)\n    cfg.define_reorder(\"reorder_inner\", [rco, ryo, rxo], \"all\")\n    cfg[\"reorder_inner\"].apply(s, OL, [rco, ryo, rxo])\n    cfg[\"reorder_inner\"].apply(s, OL, [rci, ryi, rxi])\n\n    cache_loc = [rco, ryo, rxo][cfg[\"reorder_inner\"].perm[-1]]\n    s[AA].compute_at(s[OL], cache_loc)\n    s[WW].compute_at(s[OL], cache_loc)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        fused = s[load].fuse(*s[load].op.axis)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Schedule for dense operator\"\"\"\nimport logging\nimport tvm\nfrom tvm import te\nimport tvm.autotvm as autotvm\nfrom tvm.contrib import cublas\nfrom .tensor_intrin import dp4a\nfrom .. import tag\nfrom .. import generic\nfrom ..utils import traverse_inline, get_const_tuple\n\nlogger = logging.getLogger(\"topi\")\n\n\ndef _matmul_cublas_common(\n    cfg,\n    tensor_a,\n    tensor_b,\n    bias=None,\n    out_dtype=None,\n    transpose_a=False,\n    transpose_b=False,\n):\n    assert len(tensor_a.shape) == 2 and len(tensor_b.shape) == 2, \"only support 2-dim matmul\"\n    if bias is not None:\n        assert len(bias.shape) == 1\n    if out_dtype is None:\n        out_dtype = tensor_a.dtype\n    if out_dtype not in [tensor_a.dtype, \"int32\"]:\n        assert out_dtype == tensor_a.dtype, \"Mixed precision other than int8 + int32 not supported.\"\n    batch, in_dim = get_const_tuple(tensor_a.shape)\n    out_dim, _ = get_const_tuple(tensor_b.shape)\n    matmul = cublas.matmul(tensor_a, tensor_b, transpose_a, transpose_b, dtype=out_dtype)\n    if all(isinstance(d, int) for d in [batch, in_dim, out_dim]):\n        cfg.add_flop(batch * in_dim * out_dim * 2)\n    if bias is not None:\n        matmul = te.compute(\n            (batch, out_dim), lambda i, j: matmul[i, j] + bias[j], tag=tag.BROADCAST\n        )\n    return matmul\n\n\n@autotvm.register_topi_compute(\"matmul_cublas.cuda\")\ndef matmul_cublas(\n    cfg,\n    tensor_a,\n    tensor_b,\n    bias=None,\n    out_dtype=None,\n    transpose_a=False,\n    transpose_b=False,\n):\n    \"\"\"Matmul operator on CUDA with CUBLAS\"\"\"\n    return _matmul_cublas_common(cfg, tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b)\n\n\n@autotvm.register_topi_schedule(\"matmul_cublas.cuda\")\ndef schedule_matmul_cublas(_, outs):\n    \"\"\"Schedule matmul operator using CUBLAS\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"dense_cublas.cuda\")\ndef dense_cublas(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator on CUDA with CUBLAS. This is an alias of matmul_nt operator.\"\"\"\n    return _matmul_cublas_common(cfg, data, weight, bias, out_dtype, False, True)\n\n\n@autotvm.register_topi_schedule(\"dense_cublas.cuda\")\ndef schedule_dense_cublas(_, outs):\n    \"\"\"Schedule dense operator using CUBLAS\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"dense_int8.cuda\")\ndef dense_int8(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator for int8 on CUDA\"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n\n    batch, in_dim = get_const_tuple(data.shape)\n    out_dim, _ = get_const_tuple(weight.shape)\n    k = te.reduce_axis((0, in_dim), name=\"k\")\n\n    matmul = te.compute(\n        (batch, out_dim),\n        lambda i, j: te.sum(\n            data[i, k].astype(out_dtype) * weight[j, k].astype(out_dtype), axis=[k]\n        ),\n        tag=\"dense_int8\",\n    )\n\n    cfg.add_flop(batch * in_dim * out_dim * 2)\n\n    if bias is not None:\n        matmul = te.compute(\n            (batch, out_dim),\n            lambda i, j: matmul[i, j] + bias[j].astype(out_dtype),\n            tag=tag.BROADCAST,\n        )\n        cfg.add_flop(batch * out_dim)\n\n    return matmul\n\n\n@autotvm.register_topi_schedule(\"dense_int8.cuda\")\ndef schedule_dense_int8(cfg, outs):\n    \"\"\"Dense schedule for int8 on CUDA\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"dense_int8\" in op.tag:\n            _schedule_dense_int8(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_dense_int8(cfg, s, output):\n    data, weight = s[output].op.input_tensors\n    if len(weight.op.input_tensors) == 1 and weight.op.input_tensors[0] == data:\n        s[weight].compute_inline()\n\n    batch, in_dim = get_const_tuple(data.shape)\n    out_dim, _ = get_const_tuple(weight.shape)\n\n    in_dim_factor = 4\n    assert in_dim % in_dim_factor == 0, \"Input dimension must divide {}\".format(in_dim_factor)\n    if in_dim % 16 == 0:\n        in_dim_factor = 16\n\n    # create tuning space\n    cfg.define_split(\"tile_y\", batch, num_outputs=4)\n    cfg.define_split(\"tile_x\", out_dim, num_outputs=4)\n    cfg.define_split(\"tile_k\", in_dim // in_dim_factor, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    # create cache stage\n    AA = s.cache_read(data, \"shared\", [output])\n    WW = s.cache_read(weight, \"shared\", [output])\n    CC = s.cache_write(output, \"local\")\n\n    # handle bias\n    if output.op not in s.outputs:\n        s[output].compute_inline()\n        output = s.outputs[0].output(0)\n\n    n, x = s[output].op.axis\n\n    # this is the scope to attach global config inside this kernel\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    ko = CC.op.reduce_axis[0]\n    ko, ki = s[CC].split(ko, factor=4)\n    ko, kt = cfg[\"tile_k\"].apply(s, CC, ko)\n    target = tvm.target.Target.current(allow_none=False)\n    do_tensorize = \"+dotprod\" in target.mattr or target.supports_integer_dot_product\n\n    if do_tensorize:\n        dtypes = (data.dtype, weight.dtype)\n        s[CC].tensorize(ki, dp4a(\"shared\", \"shared\", \"local\", dtypes))\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, n)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    s[output].reorder(by, bx, vy, vx, ty, tx, yi, xi)\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    n_ty = cfg[\"tile_y\"].size[2]\n    n_tx = cfg[\"tile_x\"].size[2]\n\n    s[CC].compute_at(s[output], tx)\n    yo, xo = CC.op.axis[:2]\n    s[CC].reorder(ko, kt, yo, xo, ki)\n\n    for load in [AA, WW]:\n        s[load].compute_at(s[CC], ko)\n\n        outer, inner = s[load].split(s[load].op.axis[-1], factor=in_dim_factor)\n        s[load].vectorize(inner)\n        fused = s[load].op.axis[:-1] + [outer]\n        fused = s[load].fuse(*fused)\n\n        fused, tx = s[load].split(fused, factor=n_tx)\n        fused, ty = s[load].split(fused, factor=n_ty)\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", False)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/dense_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument\n\"\"\"Compute and Schedule definition for dense tensorcore with cuda backend\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nimport tvm.autotvm as autotvm\nfrom .. import tag\nfrom ..utils import traverse_inline, get_const_tuple\nfrom .tensor_intrin import (\n    intrin_wmma_load_matrix_A,\n    intrin_wmma_load_matrix_W,\n    intrin_wmma_store_matrix,\n    intrin_wmma_gemm,\n)\n\n\n@autotvm.register_topi_compute(\"dense_tensorcore.cuda\")\ndef dense_tensorcore(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense tensorcore operator on CUDA\"\"\"\n    matmul = dense_tensorcore_cuda(data, weight, bias, out_dtype)\n    return matmul\n\n\n@autotvm.register_topi_schedule(\"dense_tensorcore.cuda\")\ndef schedule_dense_tensorcore(cfg, outs):\n    \"\"\"Schedule dense operator using Tensorcore\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"dense_tensorcore\":\n            _schedule_dense_tensorcore(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef dense_tensorcore_cuda(data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense tensorcore operator on CUDA\"\"\"\n    assert len(data.shape) == 2 and len(weight.shape) == 2, \"only support 2-dim dense\"\n    if bias is not None:\n        assert len(bias.shape) == 1\n    if out_dtype is None:\n        out_dtype = data.dtype\n    batch, in_dim = get_const_tuple(data.shape)\n    out_dim, _ = get_const_tuple(weight.shape)\n\n    assert data.dtype == weight.dtype\n    assert data.dtype in [\"float16\", \"int8\", \"uint8\", \"int4\", \"uint4\"]\n    if data.dtype in [\"float16\", \"int8\", \"uint8\"]:\n        assert (\n            (batch % 8 == 0 and in_dim % 16 == 0 and out_dim % 32 == 0)\n            or (batch % 16 == 0 and in_dim % 16 == 0 and out_dim % 16 == 0)\n            or (batch % 32 == 0 and in_dim % 16 == 0 and out_dim % 8 == 0)\n        ), (\n            \"The shape of (batch, in_dim, out_dim) \"\n            \"must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32) for now\"\n        )\n    else:\n        assert (\n            batch % 8 == 0 and in_dim % 32 == 0 and out_dim % 8 == 0\n        ), \"The shape of (batch, in_dim, out_dim) must be multiple of (8, 32, 8)\"\n\n    k = te.reduce_axis((0, in_dim), name=\"k\")\n    matmul = te.compute(\n        (batch, out_dim),\n        lambda i, j: te.sum(data[i, k].astype(out_dtype) * weight[j, k].astype(out_dtype), axis=k),\n        name=\"T_dense\",\n        tag=\"dense_tensorcore\",\n    )\n    if bias is not None:\n        matmul = te.compute(\n            (batch, out_dim),\n            lambda i, j: matmul[i, j] + bias[j].astype(out_dtype),\n            tag=tag.BROADCAST,\n        )\n    return matmul\n\n\ndef _schedule_dense_tensorcore(cfg, s, C):\n    \"\"\"Schedule dense operator using Tensorcore\"\"\"\n    A, B = s[C].op.input_tensors\n    if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A:\n        s[B].compute_inline()\n    batch, out_dim = get_const_tuple(C.shape)\n    data_dtype = A.dtype\n    out_dtype = C.dtype\n\n    # Explicit memory access\n    AS = s.cache_read(A, \"shared\", [C])\n    BS = s.cache_read(B, \"shared\", [C])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [C])\n    BF = s.cache_read(BS, \"wmma.matrix_b\", [C])\n    CF = s.cache_write(C, \"wmma.accumulator\")\n    CS = s.cache_read(CF, \"shared\", [C])\n\n    # fallback support\n    target = tvm.target.Target.current()\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            target.kind.name, target.model, \"dense_tensorcore.cuda\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n\n    # Deal with op fusion, such as bias and relu\n    if C.op not in s.outputs:\n        s[C].compute_inline()\n        C = s.outputs[0].output(0)\n\n    # create tuning space\n    cfg.define_knob(\"block_row_warps\", [1, 2, 4])\n    cfg.define_knob(\"block_col_warps\", [1, 2, 4])\n    cfg.define_knob(\"warp_row_tiles\", [1, 2, 4])\n    cfg.define_knob(\"warp_col_tiles\", [1, 2, 4])\n    cfg.define_knob(\"chunk\", [1, 2, 4, 8])\n    cfg.define_knob(\"offset\", [0, 8])\n    cfg.define_knob(\"offsetCS\", [0, 8])\n    cfg.define_knob(\"vec\", [1, 2, 4, 8])\n\n    if data_dtype in [\"float16\", \"int8\", \"uint8\"]:\n        # Ensure that the default parameters are applicable when autotvm is not in use\n        if batch % 32 == 0 and out_dim % 8 == 0:\n            cfg.define_knob(\"wmma_m\", [32, 16, 8])\n        elif batch % 16 == 0 and out_dim % 16 == 0:\n            cfg.define_knob(\"wmma_m\", [16, 8, 32])\n        elif batch % 8 == 0 and out_dim % 32 == 0:\n            cfg.define_knob(\"wmma_m\", [8, 16, 32])\n        wmma_k = 16\n        wmma_m = cfg[\"wmma_m\"].val\n        if wmma_m == 16:\n            wmma_n = 16\n        elif wmma_m == 8:\n            wmma_n = 32\n        elif wmma_m == 32:\n            wmma_n = 8\n    elif data_dtype in [\"int4\", \"uint4\"]:\n        wmma_m = wmma_n = 8\n        wmma_k = 32\n    else:\n        raise ValueError(\"data dtype %s is not yet supported\" % data_dtype)\n\n    warp_size = 32\n    block_row_warps = cfg[\"block_row_warps\"].val\n    block_col_warps = cfg[\"block_col_warps\"].val\n    warp_row_tiles = cfg[\"warp_row_tiles\"].val\n    warp_col_tiles = cfg[\"warp_col_tiles\"].val\n    chunk = cfg[\"chunk\"].val\n    offset = cfg[\"offset\"].val\n    offsetCS = cfg[\"offsetCS\"].val\n    vec = cfg[\"vec\"].val\n\n    # Define the stride of intrin functions\n    AS_align = chunk * wmma_k + offset\n    BS_align = chunk * wmma_k + offset\n    CS_align = warp_col_tiles * block_col_warps * wmma_n + offsetCS\n    AS_stride = [AS_align, 1]\n    BS_stride = [BS_align, 1]\n    AF_stride = [wmma_k, 1]\n    BF_stride = [wmma_k, 1]\n    CF_stride = [warp_col_tiles * wmma_n, 1]\n    CS_stride = [CS_align, 1]\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    # Schedule for dense computation\n    block_factor_b = wmma_m * warp_row_tiles * block_row_warps\n    block_factor_o = wmma_n * warp_col_tiles * block_col_warps\n    b, o = C.op.axis\n    block_i, bc = s[C].split(b, factor=block_factor_b)\n    block_j, oc = s[C].split(o, factor=block_factor_o)\n    s[C].reorder(block_i, block_j, bc, oc)\n    t = s[C].fuse(bc, oc)\n    t, vi = s[C].split(t, factor=vec)\n    t, tx = s[C].split(t, factor=warp_size)\n    t, ty = s[C].split(t, factor=block_row_warps)\n    t, tz = s[C].split(t, factor=block_col_warps)\n    s[C].bind(block_i, block_x)\n    s[C].bind(block_j, block_y)\n    s[C].bind(tz, thread_z)\n    s[C].bind(ty, thread_y)\n    s[C].bind(tx, thread_x)\n    s[C].vectorize(vi)\n\n    # Schedule for wmma store\n    s[CS].compute_at(s[C], block_j)\n    bb, oo = CS.op.axis\n    s[CS].storage_align(bb, CS_align - 1, CS_align)\n    bb, bbi = s[CS].split(bb, factor=wmma_m)\n    oo, ooi = s[CS].split(oo, factor=wmma_n)\n    bb, bbii = s[CS].split(bb, factor=warp_row_tiles)\n    oo, ooii = s[CS].split(oo, factor=warp_col_tiles)\n    s[CS].reorder(bb, oo, bbii, ooii, bbi, ooi)\n    s[CS].bind(bb, thread_y)\n    s[CS].bind(oo, thread_z)\n\n    # Schedule for wmma computation\n    s[CF].compute_at(s[CS], oo)\n    warp_i, warp_j = CF.op.axis\n    warp_i, _ii = s[CF].split(warp_i, factor=wmma_m)\n    warp_j, _jj = s[CF].split(warp_j, factor=wmma_n)\n    (k,) = CF.op.reduce_axis\n    k, _k = s[CF].split(k, factor=wmma_k)\n    ko, ki = s[CF].split(k, factor=chunk)\n    s[CF].reorder(ko, ki, warp_i, warp_j, _ii, _jj, _k)\n\n    # Schedule for  wmma_matrix_a load\n    s[AF].compute_at(s[CF], ki)\n    b, i = AF.op.axis\n    b, b_ii = s[AF].split(b, factor=wmma_m)\n    i, i_jj = s[AF].split(i, factor=wmma_k)\n    s[AF].reorder(b, i, b_ii, i_jj)\n\n    # Schedule for  wmma_matrix_b load\n    s[BF].compute_at(s[CF], ki)\n    o, i = BF.op.axis\n    o, o_ii = s[BF].split(o, factor=wmma_n)\n    i, i_ii = s[BF].split(i, factor=wmma_k)\n    s[BF].reorder(o, i, o_ii, i_ii)\n\n    # Schedule for A's(B's) shared memory load\n    def shared_schedule(stage, strides):\n        s[stage].compute_at(s[CF], ko)\n        xo, yo = stage.op.axis\n        s[stage].storage_align(xo, strides - 1, strides)\n        t = s[stage].fuse(xo, yo)\n        t, vi = s[stage].split(t, factor=vec)\n        t, tx = s[stage].split(t, factor=warp_size)\n        t, ty = s[stage].split(t, factor=block_row_warps)\n        _, tz = s[stage].split(t, factor=block_col_warps)\n        s[stage].bind(ty, thread_y)\n        s[stage].bind(tz, thread_z)\n        s[stage].bind(tx, thread_x)\n        s[stage].vectorize(vi)\n\n    shared_schedule(AS, AS_align)\n    shared_schedule(BS, BS_align)\n\n    shape = (wmma_m, wmma_n, wmma_k)\n    AL_gemm = te.placeholder((wmma_m, wmma_k), name=\"AL_gemm\", dtype=data_dtype)\n    BL_gemm = te.placeholder((wmma_n, wmma_k), name=\"BL_gemm\", dtype=data_dtype)\n    k_gemm = te.reduce_axis((0, wmma_k), name=\"k_gemm\")\n    CL_compute = te.compute(\n        (wmma_m, wmma_n),\n        lambda ii, jj: te.sum(\n            AL_gemm[ii, k_gemm].astype(out_dtype) * BL_gemm[jj, k_gemm].astype(out_dtype),\n            axis=k_gemm,\n        ),\n        name=\"CL_compute\",\n    )\n\n    # lower the computation loops down to TensorCore hardware intrinsics\n    # by mapping the dense tensorcore to tensor intrinsics\n    s[AF].tensorize(\n        b_ii,\n        intrin_wmma_load_matrix_A(\n            AF_stride, AS_stride, shape, \"row_major\", (wmma_m, wmma_k), (wmma_m, wmma_k), data_dtype\n        ),\n    )\n    s[BF].tensorize(\n        o_ii,\n        intrin_wmma_load_matrix_W(\n            BF_stride, BS_stride, shape, \"col_major\", (wmma_n, wmma_k), (wmma_n, wmma_k), data_dtype\n        ),\n    )\n    s[CF].tensorize(\n        _ii, intrin_wmma_gemm(AL_gemm, BL_gemm, CL_compute, AF_stride, BF_stride, CF_stride, shape)\n    )\n    s[CS].tensorize(\n        bbi,\n        intrin_wmma_store_matrix(\n            CS_stride, CF_stride, shape, out_dtype, (wmma_m, wmma_n), (wmma_m, wmma_n)\n        ),\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Schedule for depthwise_conv2d with auto fusion\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import traverse_inline\nfrom .. import tag\nfrom .. import nn\n\n# register original implementation of depthwise_conv2d_nchw since we don't need to change this part\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw.cuda\")\ndef depthwise_conv2d_nchw(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute depthwise_conv2d with NCHW layout.\"\"\"\n    return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw.cuda\")\ndef schedule_depthwise_conv2d_nchw(cfg, outs):\n    \"\"\"Schedule for depthwise_conv2d nchw forward.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"depthwise_conv2d_nchw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, f, y, x = s[conv].op.axis\n            cfg.define_split(\"tile_f\", f, num_outputs=4)\n            cfg.define_split(\"tile_y\", y, num_outputs=4)\n            cfg.define_split(\"tile_x\", x, num_outputs=4)\n            cfg.define_knob(\"auto_unroll_max_step\", [0, 256, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            # fallback support\n            if cfg.is_fallback:\n                ref_log = autotvm.tophub.load_reference_log(\n                    target.kind.name, target.model, \"depthwise_conv2d_nchw.cuda\"\n                )\n                cfg.fallback_with_reference_log(ref_log)\n                # TODO(lmzheng): A bug here, set unroll_explicit to False as workaround\n                cfg[\"unroll_explicit\"].val = 0\n            ##### space definition end #####\n\n            s[pad_data].compute_inline()\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            # create cache stage\n            AA = s.cache_read(pad_data, \"shared\", [OL])\n            WW = s.cache_read(kernel, \"shared\", [OL])\n            AL = s.cache_read(AA, \"local\", [OL])\n            WL = s.cache_read(WW, \"local\", [OL])\n\n            # tile and bind spatial axes\n            n, f, y, x = s[output].op.axis\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n            by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bf = s[output].fuse(n, bf)\n            s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n            s[output].bind(vy, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n            s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n            s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n            s[OL].compute_at(s[output], tx)\n\n            # cooperative fetching\n            s[AA].compute_at(s[output], bx)\n            s[WW].compute_at(s[output], bx)\n            s[AL].compute_at(s[output], tx)\n            s[WL].compute_at(s[output], tx)\n\n            for load in [AA, WW]:\n                fused = s[load].fuse(*list(s[load].op.axis))\n                fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n                fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n                fused, tz = s[load].split(fused, cfg[\"tile_f\"].size[2])\n                s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n                s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n                s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef schedule_depthwise_conv2d_nhwc(outs):\n    \"\"\"Schedule for depthwise_conv2d nhwc forward.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nhwc.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(temp, Filter, DepthwiseConv2d):\n        s[temp].compute_inline()\n        FS = s.cache_read(Filter, \"shared\", [DepthwiseConv2d])\n        if DepthwiseConv2d.op in s.outputs:\n            Output = DepthwiseConv2d\n            CL = s.cache_write(DepthwiseConv2d, \"local\")\n        else:\n            Output = outs[0].op.output(0)\n            s[DepthwiseConv2d].set_scope(\"local\")\n\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_x = te.thread_axis(\"threadIdx.x\")\n\n        b, h, w, c = s[Output].op.axis\n\n        # make sure the size of our parallelism is not larger than the number of threads\n        num_thread = min(\n            tvm.arith.Analyzer().simplify(temp.shape[3]).value,\n            tvm.target.Target.current().max_num_threads,\n        )\n        xoc, xic = s[Output].split(c, factor=num_thread)\n        s[Output].reorder(xoc, b, h, w, xic)\n        xo, yo, _, _ = s[Output].tile(h, w, x_factor=2, y_factor=2)\n        fused = s[Output].fuse(yo, xo)\n        fused = s[Output].fuse(fused, b)\n        fused = s[Output].fuse(fused, xoc)\n\n        s[Output].bind(fused, block_x)\n        s[Output].bind(xic, thread_x)\n\n        if DepthwiseConv2d.op in s.outputs:\n            s[CL].compute_at(s[Output], xic)\n        else:\n            s[DepthwiseConv2d].compute_at(s[Output], xic)\n\n        _, _, ci, fi = s[FS].op.axis\n        s[FS].compute_at(s[Output], fused)\n        fused = s[FS].fuse(fi, ci)\n        s[FS].bind(fused, thread_x)\n\n    scheduled_ops = []\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule depthwise_conv2d\n        if OP.tag == \"depthwise_conv2d_nhwc\":\n            PaddedInput = OP.input_tensors[0]\n            Filter = OP.input_tensors[1]\n            if isinstance(Filter.op, tvm.te.ComputeOp) and \"dilate\" in Filter.op.tag:\n                s[Filter].compute_inline()\n            DepthwiseConv2d = OP.output(0)\n            _schedule(PaddedInput, Filter, DepthwiseConv2d)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef schedule_depthwise_conv2d_backward_input_nhwc(outs):\n    \"\"\"Schedule for depthwise_conv2d nhwc backward wrt input.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        backward wrt input in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d backward\n        wrt input with layout nhwc.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(Padded_out_grad, In_grad):\n        s[Padded_out_grad].compute_inline()\n\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_x = te.thread_axis(\"threadIdx.x\")\n        _, h, w, c = In_grad.op.axis\n\n        fused_hwc = s[In_grad].fuse(h, w, c)\n        xoc, xic = s[In_grad].split(fused_hwc, factor=128)\n\n        s[In_grad].bind(xoc, block_x)\n        s[In_grad].bind(xic, thread_x)\n\n    def traverse(OP):\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if OP.tag == \"depthwise_conv2d_backward_input_nhwc\":\n            Padded_out_grad = OP.input_tensors[0]\n            Dilated_out_grad = Padded_out_grad.op.input_tensors[0]\n            s[Dilated_out_grad].compute_inline()\n            In_grad = OP.output(0)\n            _schedule(Padded_out_grad, In_grad)\n        else:\n            raise ValueError(\"Depthwise conv backward wrt input for non-NHWC is not supported.\")\n\n    traverse(outs[0].op)\n    return s\n\n\ndef schedule_depthwise_conv2d_backward_weight_nhwc(outs):\n    \"\"\"Schedule for depthwise_conv2d nhwc backward wrt weight.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        backward wrt weight in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d backward\n        wrt weight with layout nhwc.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(Weight_grad):\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_y = te.thread_axis(\"threadIdx.y\")\n        thread_x = te.thread_axis(\"threadIdx.x\")\n\n        db, dh, dw = Weight_grad.op.reduce_axis\n\n        fused_dbdhdw = s[Weight_grad].fuse(db, dh, dw)\n        _, ki = s[Weight_grad].split(fused_dbdhdw, factor=8)\n        BF = s.rfactor(Weight_grad, ki)\n\n        fused_fwcm = s[Weight_grad].fuse(*s[Weight_grad].op.axis)\n\n        xo, xi = s[Weight_grad].split(fused_fwcm, factor=32)\n\n        s[Weight_grad].bind(xi, thread_x)\n        s[Weight_grad].bind(xo, block_x)\n\n        s[Weight_grad].bind(s[Weight_grad].op.reduce_axis[0], thread_y)\n        s[BF].compute_at(s[Weight_grad], s[Weight_grad].op.reduce_axis[0])\n\n    def traverse(OP):\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if OP.tag == \"depthwise_conv2d_backward_weight_nhwc\":\n            Padded_in = OP.input_tensors[1]\n            s[Padded_in].compute_inline()\n            Weight_grad = OP.output(0)\n            _schedule(Weight_grad)\n        else:\n            raise ValueError(\"Depthwise conv backward wrt weight for non-NHWC is not supported.\")\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/group_conv2d_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n# pylint: disable=no-value-for-parameter\n\"\"\"The template for cuda group_conv2d_nchw\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .injective import schedule_injective_from_existing\nfrom .tensor_intrin import dp4a\nfrom ..nn.pad import pad\nfrom ..nn.conv2d import unpack_NCHWc_to_nchw\nfrom ..nn.utils import get_pad_tuple\nfrom ..utils import traverse_inline, get_const_tuple, get_const_int\nfrom .. import nn\n\n\ndef group_conv2d_nchw_int8(data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"):\n    \"\"\"Compute group_conv2d internally using group_conv2d_nchwc layout for int8 dtype\"\"\"\n    assert data.dtype in (\"int8\", \"uint8\")\n    assert kernel.dtype in (\"int8\", \"uint8\")\n    assert data.dtype == kernel.dtype\n    packed_out = group_conv2d_NCHWc_int8(\n        data, kernel, strides, padding, dilation, groups, out_dtype\n    )\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_group_conv2d_nchw_int8(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    return schedule_group_conv2d_NCHWc_int8(outs)\n\n\n@autotvm.register_topi_compute(\"group_conv2d_nchw.cuda\")\ndef group_conv2d_nchw(_, data, kernel, stride, padding, dilation, groups, out_dtype=\"float32\"):\n    return nn.group_conv2d_nchw(data, kernel, stride, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"group_conv2d_nchw.cuda\")\ndef schedule_group_conv2d_nchw(cfg, outs):\n    \"\"\"TOPI schedule callback of group conv2d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for group conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"group_conv2d_nchw\":\n            _schedule_group_conv2d_nchw_direct(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_group_conv2d_nchw_direct(cfg, s, conv):\n    \"\"\"Schedule group conv2d NCHW direct template\"\"\"\n    workload = conv.op.attrs[\"workload\"]\n    groups = get_const_int(workload[6])\n    num_filters = get_const_int(conv.shape[1])\n\n    ##### space definition begin #####\n    n, f, y, x = s[conv].op.axis\n    rc, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_n\", n, num_outputs=4)\n    cfg.define_split(\"tile_g\", cfg.axis(groups), num_outputs=2)\n    cfg.define_split(\"tile_f\", cfg.axis(num_filters // groups), num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rc\", rc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    target = tvm.target.Target.current()\n    if target.kind.name in [\"nvptx\", \"rocm\"]:\n        cfg.define_knob(\"unroll_explicit\", [1])\n    else:\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n    pad_data, kernel = s[conv].op.input_tensors\n\n    s[pad_data].compute_inline()\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, f, y, x = s[output].op.axis\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    g, f = s[output].split(f, nparts=groups)\n    bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n    bg, vg = cfg[\"tile_g\"].apply(s, output, g)\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    s[output].reorder(bn, bg, bf, by, bx, vn, vg, vf, vy, vx, tn, tf, ty, tx, ni, fi, yi, xi)\n    s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(s[output].fuse(bg, bf), te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(s[output].fuse(by, bx), te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vn, te.thread_axis(\"vthread\"))\n    s[output].bind(vg, te.thread_axis(\"vthread\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n\n    cfg.define_knob(\"fuse_yx\", [0, 1])  # fuse ty,tx or tn,tf\n    if cfg[\"fuse_yx\"].val:\n        s[output].bind(tn, te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(tf, te.thread_axis(\"threadIdx.y\"))\n        tyx = s[output].fuse(ty, tx)\n        s[output].bind(tyx, te.thread_axis(\"threadIdx.x\"))\n        s[OL].compute_at(s[output], tyx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2]\n        n_ty = cfg[\"tile_f\"].size[2]\n        n_tx = cfg[\"tile_y\"].size[2] * cfg[\"tile_x\"].size[2]\n    else:\n        s[output].bind(s[output].fuse(tn, tf), te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[OL].compute_at(s[output], tx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_f\"].size[2]\n        n_ty = cfg[\"tile_y\"].size[2]\n        n_tx = cfg[\"tile_x\"].size[2]\n\n    # tile reduction axes\n    n, f, y, x = s[OL].op.axis\n    rc, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rc\"].apply(s, OL, rc)\n    ryo, ryi = cfg[\"tile_rx\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_ry\"].apply(s, OL, rx)\n    s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        n, f, y, x = s[load].op.axis\n        fused = s[load].fuse(n, f, y, x)\n        fused, tx = s[load].split(fused, factor=n_tx)\n        fused, ty = s[load].split(fused, factor=n_ty)\n        fused, tz = s[load].split(fused, factor=n_tz)\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    N, CO, OH, OW = get_const_tuple(output.shape)\n    _, CI_div_groups, KH, KW = get_const_tuple(kernel.shape)\n    cfg.add_flop(2 * N * OH * OW * CO * CI_div_groups * KH * KW)\n\n\n@autotvm.register_topi_compute(\"group_conv2d_NCHWc_int8.cuda\")\ndef group_conv2d_NCHWc_int8(\n    cfg, data, kernel, stride, padding, dilation, groups, out_dtype=\"float32\"\n):\n    \"\"\"Group convolution operator for 'group_conv2d_NCHWc_int8'.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width] or\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel // groups, filter_height, filter_width] or\n        6-D with shape [num_filter_chunk, in_channel_chunk // groups, filter_height,\n        filter_width, num_filter_block, in_channel_block]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    groups : int\n        number of groups\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_height, out_width, out_channel_block]\n    \"\"\"\n    ic_block_factor = 4\n    oc_block_factor = 4\n\n    pre_computed = len(kernel.shape) == 6\n    if not pre_computed:\n        batch, channels, height, width = get_const_tuple(data.shape)\n        out_channels, in_channels, kernel_h, kernel_w = get_const_tuple(kernel.shape)\n\n        assert channels % groups == 0, \"input channels must divide group size\"\n        assert out_channels % groups == 0, \"output channels must divide group size\"\n        assert (\n            channels % ic_block_factor == 0\n        ), \"Number of input channels per group must divide {}\".format(ic_block_factor)\n        assert (\n            out_channels % oc_block_factor == 0\n        ), \"Number of output channels per group must divide {}\".format(oc_block_factor)\n\n        packed_data = te.compute(\n            (batch, channels // ic_block_factor, height, width, ic_block_factor),\n            lambda n, c, h, w, vc: data[n, c * ic_block_factor + vc, h, w],\n            name=\"packed_data\",\n        )\n        packed_kernel = te.compute(\n            (\n                out_channels // oc_block_factor,\n                in_channels // ic_block_factor,\n                kernel_h,\n                kernel_w,\n                oc_block_factor,\n                ic_block_factor,\n            ),\n            lambda oc_chunk, ic_chunk, kh, kw, oc_block, ic_block: kernel[\n                oc_chunk * oc_block_factor + oc_block, ic_chunk * ic_block_factor + ic_block, kh, kw\n            ],\n            name=\"packed_kernel\",\n        )\n    else:\n        packed_data = data\n        packed_kernel = kernel\n\n    batch, ic_chunk, in_height, in_width, _ = get_const_tuple(packed_data.shape)\n    oc_chunk, _, kernel_h, kernel_w, oc_block, ic_block = get_const_tuple(packed_kernel.shape)\n\n    # TODO(kumasento): these assertions ensure that the number of groups\n    # should be smaller or equal to the number of blocks, so that each\n    # group will have at least one block.\n    # Shall we pad the channels to avoid raising assertions?\n    assert (\n        groups <= oc_chunk\n    ), \"Number of groups {} should be less than \" \"output channel chunk size {}\".format(\n        groups, oc_chunk\n    )\n    assert (\n        groups <= ic_chunk\n    ), \"Number of groups {} should be less than \" \"input channel chunk size {}\".format(\n        groups, ic_chunk\n    )\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    # pad the input data\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down, pad_right, 0]\n    pad_data = pad(packed_data, pad_before, pad_after, name=\"pad_data\")\n\n    # compute the output shape\n    out_height = (in_height - (kernel_h - 1) * dilation_h - 1 + pad_top + pad_down) // stride_h + 1\n    out_width = (in_width - (kernel_w - 1) * dilation_w - 1 + pad_left + pad_right) // stride_w + 1\n\n    oshape = (batch, oc_chunk, out_height, out_width, oc_block)\n\n    icc = te.reduce_axis((0, ic_chunk // groups), name=\"ic_chunk\")\n    icb = te.reduce_axis((0, ic_block_factor), name=\"ic_block\")\n    kh = te.reduce_axis((0, kernel_h), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_w), name=\"kw\")\n\n    # NOTE(kumasento): explanation of this snippet -\n    # oc_chunk//groups and ic_chunk//groups give you the number of blocks,\n    # i.e., chunk, per group.\n    # occ is the ID of the output channel block, so that occ//(oc_chunk//groups)\n    # produces the ID of the group.\n    # Multiplying that result with ic_chunk//groups resulting in the ID\n    # of the beginning block of the corresponding input group.\n    # Adding the block offset (icc) will give you the exact block ID.\n    #\n    # Compared with a normal convolution, group convolution only sums\n    # input channels from the group that an output channel resides in.\n    conv = te.compute(\n        oshape,\n        lambda n, occ, oh, ow, ocb: te.sum(\n            pad_data[\n                n,\n                occ // (oc_chunk // groups) * (ic_chunk // groups) + icc,\n                oh * stride_h + kh * dilation_h,\n                ow * stride_w + kw * dilation_w,\n                icb,\n            ].astype(\"int32\")\n            * packed_kernel[occ, icc, kh, kw, ocb, icb].astype(\"int32\"),\n            axis=[icc, kh, kw, icb],\n        ),\n    )\n\n    # Type conversion\n    output = te.compute(\n        oshape, lambda *index: conv(*index).astype(out_dtype), tag=\"group_conv2d_NCHWc_int8\"\n    )\n\n    num_flop = (\n        batch\n        * oc_chunk\n        * oc_block\n        * out_height\n        * out_width\n        * ic_chunk\n        * ic_block\n        * kernel_h\n        * kernel_w\n        * 2\n        // groups\n    )\n    cfg.add_flop(num_flop)\n\n    return output\n\n\n@autotvm.register_topi_schedule(\"group_conv2d_NCHWc_int8.cuda\")\ndef schedule_group_conv2d_NCHWc_int8(cfg, outs):\n    \"\"\"TOPI schedule callback of group conv2d for cuda gpu\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for group conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"group_conv2d_NCHWc_int8\":\n            _schedule_group_conv2d_NCHWc_int8(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_group_conv2d_NCHWc_int8(cfg, s, output):\n    \"\"\"Schedule group conv2d int8 NCHWc template\"\"\"\n    workload = output.op.attrs[\"workload\"]\n    groups = get_const_int(workload[6])\n\n    conv = output.op.input_tensors[0]\n    packed_data, packed_kernel = conv.op.input_tensors\n\n    if isinstance(packed_data.op, tvm.te.ComputeOp) and \"pad\" in packed_data.op.tag:\n        pad_data = packed_data\n        packed_data = pad_data.op.input_tensors[0]\n    else:\n        pad_data = packed_data\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # skip this part during tuning to make records accurate\n        # this part will be pre-computed during NNVM's pre-compute optimization pass\n        s[packed_data].pragma(s[packed_data].op.axis[0], \"debug_skip_region\")\n        s[packed_kernel].pragma(s[packed_kernel].op.axis[0], \"debug_skip_region\")\n    else:\n        if isinstance(packed_kernel.op, tvm.te.ComputeOp) and packed_kernel.name == \"packed_kernel\":\n            # data and kernel are not pre-computed, schedule layout transform here\n            schedule_injective_from_existing(s, packed_data)\n            schedule_injective_from_existing(s, packed_kernel)\n\n    if pad_data != packed_data:\n        s[pad_data].compute_inline()\n\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [conv])\n    WW = s.cache_read(packed_kernel, \"shared\", [conv])\n\n    s[conv].set_scope(\"local\")\n\n    # handle bias\n    if output.op not in s.outputs:\n        s[output].compute_inline()\n        output = s.outputs[0].output(0)\n\n    oc_chunk = get_const_int(output.shape[1])\n    # tile and bind spatial axes\n    if len(s[output].op.axis) == 5:\n        n, f, y, x, c = s[output].op.axis\n    else:\n        # For task extraction of auto-tuning, the expected output is 4D.  Since auto-tuning tasks\n        # are created from scratch, therefore the real auto-tuning will still happen on 5D output.\n        n, f, y, x = s[output].op.axis\n\n    cfg.define_split(\"tile_n\", n, num_outputs=4)\n    cfg.define_split(\"tile_g\", cfg.axis(groups), num_outputs=2)\n    cfg.define_split(\"tile_f\", cfg.axis(oc_chunk // groups), num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n\n    # this is the scope to attach global config inside this kernel\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    g, f = s[output].split(f, nparts=groups)\n    s[output].bind(n, te.thread_axis(\"blockIdx.z\"))\n    bn, vn, tn, ni = cfg[\"tile_n\"].apply(s, output, n)\n    bg, vg = cfg[\"tile_g\"].apply(s, output, g)\n    bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    s[output].reorder(bn, bg, bf, by, bx, vn, vg, vf, vy, vx, tn, tf, ty, tx, ni, fi, yi, xi)\n    s[output].bind(bn, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(s[output].fuse(bg, bf), te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(s[output].fuse(by, bx), te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vn, te.thread_axis(\"vthread\"))\n    s[output].bind(vg, te.thread_axis(\"vthread\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    cfg.define_knob(\"fuse_yx\", [0, 1])  # fuse ty,tx or tn,tf\n    if cfg[\"fuse_yx\"].val:\n        s[output].bind(tn, te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(tf, te.thread_axis(\"threadIdx.y\"))\n        tyx = s[output].fuse(ty, tx)\n        s[output].bind(tyx, te.thread_axis(\"threadIdx.x\"))\n        s[conv].compute_at(s[output], tyx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2]\n        n_ty = cfg[\"tile_f\"].size[2]\n        n_tx = cfg[\"tile_y\"].size[2] * cfg[\"tile_x\"].size[2]\n    else:\n        s[output].bind(tn, te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(s[output].fuse(tn, tf), te.thread_axis(\"threadIdx.z\"))\n        s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[conv].compute_at(s[output], tx)\n\n        # number of threads\n        n_tz = cfg[\"tile_n\"].size[2] * cfg[\"tile_f\"].size[2]\n        n_ty = cfg[\"tile_y\"].size[2]\n        n_tx = cfg[\"tile_x\"].size[2]\n\n    # tile and bind reduction axes\n    n, f, y, x, c = s[conv].op.axis\n    rc, ry, rx, rc_block = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_rc\", cfg.axis(rc), num_outputs=2)\n    cfg.define_split(\"tile_ry\", cfg.axis(ry), num_outputs=2)\n    cfg.define_split(\"tile_rx\", cfg.axis(rx), num_outputs=2)\n    rco, rci = cfg[\"tile_rc\"].apply(s, conv, rc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, conv, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, conv, rx)\n\n    s[conv].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x, c, rc_block)\n    _, rc_block = s[conv].split(rc_block, factor=4)\n    target = tvm.target.Target.current(allow_none=False)\n    do_tensorize = \"+dotprod\" in target.mattr or target.supports_integer_dot_product\n    if do_tensorize:\n        dtypes = (pad_data.dtype, packed_kernel.dtype)\n        s[conv].tensorize(rc_block, dp4a(\"shared\", \"shared\", \"local\", dtypes))\n\n    s[AA].compute_at(s[conv], rxo)\n    s[WW].compute_at(s[conv], rxo)\n\n    # cooperative fetching\n    for load in [AA, WW]:\n        c = s[load].op.axis[-1]\n        c_outer, c = s[load].split(c, factor=4)\n        s[load].vectorize(c)\n        fused = s[load].op.axis[:-1] + [c_outer]\n        fused = s[load].fuse(*fused)\n\n        fused, tx = s[load].split(fused, factor=n_tx)\n        fused, ty = s[load].split(fused, factor=n_ty)\n        fused, tz = s[load].split(fused, factor=n_tz)\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # double buffer\n    cfg.define_knob(\"AA_double_buffer\", [0, 1])\n    cfg.define_knob(\"WW_double_buffer\", [0, 1])\n    if cfg[\"AA_double_buffer\"].val:\n        s[AA].double_buffer()\n    if cfg[\"WW_double_buffer\"].val:\n        s[WW].double_buffer()\n\n    # unroll\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n    s[output].pragma(kernel_scope, \"unroll_explicit\", False)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable,\n\"\"\"Schedule for composition of injective operator\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom .. import utils\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n\n    def find_nearest_small_factor(num, target):\n        \"\"\"Find the nearest factor of the given number that is smaller than the target.\"\"\"\n        for i in range(target, 0, -1):\n            if num % i == 0:\n                return i\n        # Unreachable because i=1 must hold.\n        return -1\n\n    fused = sch[out].fuse(*sch[out].op.axis)\n    num_thread = tvm.target.Target.current(allow_none=False).max_num_threads\n    max_block = 256\n\n    # Vectorize on fp16 data type to enable half2 for better memory bandwidth utilization.\n    vector_width = 2 if out.dtype == \"float16\" else 1\n\n    is_dynamic_output = False\n    for dim in out.shape:\n        if not isinstance(dim, tvm.tir.IntImm):\n            is_dynamic_output = True\n            break\n\n    out_len = utils.prod(out.shape)\n\n    try:\n        const_size = utils.get_const_int(out_len)\n\n        # Adjust block and thread to make sure they are dividable so that vectorize can be\n        # correctly applied.\n        if vector_width > 1 and const_size % vector_width == 0:\n            remain_total_size = const_size // vector_width\n            cand_sizes = []\n            for max_size in [num_thread, max_block]:\n                cand_sizes.append(\n                    max_size\n                    if remain_total_size % max_size == 0\n                    else find_nearest_small_factor(remain_total_size, max_size)\n                )\n                remain_total_size //= cand_sizes[-1]\n\n            # If the product of candidate dividable (block * thread) is too small,\n            # then the performance may be worse even half2 is enabled. Note that 0.7\n            # is just a heuristic ratio and may not be optimal for all workloads.\n            if np.prod(cand_sizes) / (max_block * num_thread) >= 0.7:\n                num_thread, max_block = cand_sizes\n\n        need_block_split = const_size > max_block * num_thread * vector_width\n    except ValueError:\n        need_block_split = False\n        const_size = 0\n\n    if vector_width > 1:\n        fused, v = sch[out].split(fused, vector_width)\n        sch[out].vectorize(v)\n\n    if need_block_split:\n        xo, xi = sch[out].split(fused, factor=num_thread * max_block)\n        bx, tx = sch[out].split(xi, factor=num_thread)\n        sch[out].reorder(bx, tx, xo)\n        sch[out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        sch[out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    else:\n        # Use less threads for dynamic shape ops to avoid runtime error.\n        if is_dynamic_output:\n            num_thread //= 2\n        if const_size != 0 and const_size < num_thread:\n            bx, tx = sch[out].split(fused, factor=const_size)\n        else:\n            bx, tx = sch[out].split(fused, factor=num_thread)\n        sch[out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        sch[out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"Schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    tvm.te.schedule.AutoInlineInjective(s)\n    for out in outs:\n        if not utils.is_empty_shape(out.shape):\n            schedule_injective_from_existing(s, out)\n    return s\n\n\nschedule_elemwise = schedule_injective\nschedule_broadcast = schedule_injective\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/nms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, too-many-statements, singleton-comparison\n# pylint: disable=bad-continuation, unused-argument\n\"\"\"Non-maximum suppression operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import nvcc\nfrom tvm.contrib.thrust import can_use_thrust, can_use_rocthrust\nfrom tvm.ir import register_intrin_lowering\nfrom tvm.tir import if_then_else\nfrom .sort import argsort, argsort_thrust\nfrom .scan import exclusive_scan\nfrom ..utils import ceil_div\nfrom ..math import cast\nfrom ..transform import reshape\nfrom ..vision.nms_util import (\n    calculate_overlap,\n    binary_search,\n    collect_selected_indices,\n    collect_selected_indices_and_scores,\n    run_all_class_nms,\n)\n\n\ndef cuda_atomic_add_rule(op):\n    if op.dtype == \"float32\":\n        return tvm.tir.call_pure_extern(\"float32\", \"atomicAdd\", op.args[0], op.args[1])\n    if op.dtype == \"float64\":\n        return tvm.tir.call_pure_extern(\"float64\", \"atomicAdd\", op.args[0], op.args[1])\n    if op.dtype == \"int32\":\n        return tvm.tir.call_pure_extern(\"int32\", \"atomicAdd\", op.args[0], op.args[1])\n    raise RuntimeError(\"only support int32, float32 and float64\")\n\n\ndef opencl_atomic_add_rule(op):\n    if op.dtype == \"int32\":\n        return tvm.tir.call_pure_extern(\"int32\", \"atomic_add\", op.args[0], op.args[1])\n    raise RuntimeError(\"only support int32\")\n\n\nregister_intrin_lowering(\"tir.atomic_add\", target=\"cuda\", f=cuda_atomic_add_rule, level=99)\n\nregister_intrin_lowering(\"tir.atomic_add\", target=\"opencl\", f=opencl_atomic_add_rule, level=99)\n\n\ndef atomic_add(x, y):\n    return tvm.tir.call_intrin(y.dtype, \"tir.atomic_add\", x, y)\n\n\ndef get_valid_boxes_ir(data, valid_boxes, score_threshold, id_index, score_index):\n    \"\"\"Low level IR to identify bounding boxes given a score threshold.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input data. 3-D Buffer with shape [batch_size, num_anchors, elem_length].\n\n    score_threshold : Buffer or float32\n        Lower limit of score for valid bounding boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    score_index: optional, int\n        Index of the scores/confidence of boxes.\n\n    Returns\n    -------\n    valid_boxes: Buffer\n        2D Buffer  indicating valid boxes with shape [batch_size, num_anchors].\n\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    elem_length = data.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    data = ib.buffer_ptr(data)\n\n    valid_boxes = ib.buffer_ptr(valid_boxes)\n    if isinstance(score_threshold, float):\n        score_threshold = tvm.tir.FloatImm(\"float32\", score_threshold)\n    id_index = tvm.tir.IntImm(\"int32\", id_index)\n    score_index = tvm.tir.IntImm(\"int32\", score_index)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(num_anchors, max_threads)\n        nthread_by = batch_size\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        ib.scope_attr(by, \"thread_extent\", nthread_by)\n        tid = bx * max_threads + tx\n\n        with ib.if_scope(tid < num_anchors):\n            i = by\n            j = tid\n            score = data[(i * num_anchors + j) * elem_length + score_index]\n            with ib.if_scope(\n                tvm.tir.all(\n                    score > score_threshold,\n                    tvm.tir.any(\n                        id_index < 0, data[(i * num_anchors + j) * elem_length + id_index] >= 0\n                    ),\n                )\n            ):\n                valid_boxes[i * num_anchors + j] = 1\n            with ib.else_scope():\n                valid_boxes[i * num_anchors + j] = 0\n    return ib.get()\n\n\ndef get_valid_counts_ir(data, valid_indices, valid_boxes, out, out_indices):\n    \"\"\"Low level IR to get valid count of bounding boxes\n    given a score threshold. Also prepares to move valid boxes to the\n    top of input data.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input data. 3-D Buffer with shape [batch_size, num_anchors, elem_length].\n\n    valid_indices: Buffer\n        2D Buffer of flag indicating valid data with shape [batch_size, num_anchors].\n\n    Returns\n    -------\n    out : Buffer\n        Sorted valid boxes\n\n    out_indices : Buffer\n        Incidices of valid boxes in original data\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    elem_length = data.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    data = ib.buffer_ptr(data)\n    valid_indices = ib.buffer_ptr(valid_indices)\n    valid_boxes = ib.buffer_ptr(valid_boxes)\n\n    out = ib.buffer_ptr(out)\n    out_indices = ib.buffer_ptr(out_indices)\n    one = tvm.tir.const(1, dtype=out.dtype)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = num_anchors // max_threads + 1\n    nthread_by = batch_size\n    with ib.new_scope():\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        ib.scope_attr(by, \"thread_extent\", nthread_by)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < num_anchors):\n            i = by\n            j = tid\n            with ib.for_range(0, elem_length) as k:\n                out[(i * num_anchors + j) * elem_length + k] = -one\n            out_indices[i * num_anchors + j] = -1\n    with ib.new_scope():\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        ib.scope_attr(by, \"thread_extent\", nthread_by)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < num_anchors):\n            i = by\n            j = tid\n            with ib.if_scope(valid_boxes[i, tid] > 0):\n                with ib.for_range(0, elem_length) as k:\n                    out[(i * num_anchors + valid_indices[i, tid]) * elem_length + k] = data[\n                        (i * num_anchors + j) * elem_length + k\n                    ]\n                out_indices[i * num_anchors + valid_indices[i, tid]] = j\n    return ib.get()\n\n\ndef get_valid_counts(data, score_threshold=0, id_index=0, score_index=1):\n    \"\"\"Get valid count of bounding boxes given a score threshold.\n    Also moves valid boxes to the top of input data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data. 3-D tensor with shape [batch_size, num_anchors, elem_length].\n\n    score_threshold : optional, tvm.te.Tensor or float\n        Lower limit of score for valid bounding boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    score_index: optional, int\n        Index of the scores/confidence of boxes.\n\n    Returns\n    -------\n    valid_count : tvm.te.Tensor\n        1-D tensor for valid number of boxes.\n\n    out_tensor : tvm.te.Tensor\n        Rearranged data tensor.\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    valid_boxes_buf = tvm.tir.decl_buffer(\n        (batch_size, num_anchors), \"int32\", \"valid_boxes_buf\", data_alignment=8\n    )\n    valid_boxes = te.extern(\n        [(batch_size, num_anchors)],\n        [data],\n        lambda ins, outs: get_valid_boxes_ir(\n            ins[0], outs[0], score_threshold, id_index, score_index\n        ),\n        dtype=[\"int32\"],\n        in_buffers=[data_buf],\n        out_buffers=[valid_boxes_buf],\n        name=\"get_valid_boxes\",\n        tag=\"get_valid_boxes_gpu\",\n    )\n\n    valid_indices_buf = tvm.tir.decl_buffer(\n        (batch_size, num_anchors), \"int32\", \"valid_indices_buf\", data_alignment=8\n    )\n\n    valid_indices, valid_count = exclusive_scan(valid_boxes, axis=1, return_reduction=True)\n\n    out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"out_buf\", data_alignment=8)\n    out_indices_buf = tvm.tir.decl_buffer(\n        (batch_size, num_anchors), \"int32\", \"out_buf\", data_alignment=8\n    )\n\n    out, out_indices = te.extern(\n        [data.shape, (batch_size, num_anchors)],\n        [data, valid_indices, valid_boxes],\n        lambda ins, outs: get_valid_counts_ir(ins[0], ins[1], ins[2], outs[0], outs[1]),\n        dtype=[\"int32\", data.dtype],\n        in_buffers=[data_buf, valid_indices_buf, valid_boxes_buf],\n        out_buffers=[out_buf, out_indices_buf],\n        name=\"get_valid_counts\",\n        tag=\"get_valid_counts_gpu\",\n    )\n\n    return [valid_count, out, out_indices]\n\n\ndef _nms_loop(\n    ib,\n    batch_size,\n    top_k,\n    iou_threshold,\n    max_output_size,\n    valid_count,\n    on_new_valid_box_func,\n    on_new_invalidated_box_func,\n    needs_bbox_check_func,\n    calc_overlap_func,\n    out_scores,\n    num_valid_boxes,\n):\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n\n    with ib.new_scope():\n        nthread_by = batch_size\n        nthread_tx = max_threads\n\n        # Some cuda architectures have smaller limit of 32K for cudaDevAttrMaxRegistersPerBlock\n        # vs 64K for most GPUs. Since this kernel uses many registers (around 35), the limit will\n        # be exceeded with 1024 threads.\n        target = tvm.target.Target.current(allow_none=False)\n        if target.kind.name == \"cuda\":\n            if nvcc.get_target_compute_version(target) in [\"3.2\", \"5.3\", \"6.2\"]:\n                nthread_tx = 512\n\n        by = te.thread_axis(\"blockIdx.y\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(by, \"thread_extent\", nthread_by)\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n\n        num_valid_boxes_local = ib.allocate(\n            \"int32\", (1,), name=\"num_valid_boxes_local\", scope=\"local\"\n        )\n        num_valid_boxes_local[0] = 0\n\n        def nms_inner_loop(ib, i, j, nkeep):\n            # The box j is valid, invalidate other boxes that overlap with j above iou_threshold\n            on_new_valid_box_func(ib, tx, num_valid_boxes_local[0], i, j)\n            num_valid_boxes_local[0] += 1\n\n            num_iter_per_thread = ceil_div(nkeep - (j + 1), nthread_tx)\n\n            with ib.for_range(0, num_iter_per_thread, name=\"_k\") as _k:\n                k = j + 1 + _k * nthread_tx + tx\n\n                with ib.if_scope(\n                    tvm.tir.all(\n                        k < nkeep,\n                        out_scores[i, k] > 0,  # is the box k still valid?\n                        needs_bbox_check_func(i, j, k),\n                    )\n                ):\n                    iou = calc_overlap_func(i, j, k)\n\n                    with ib.if_scope(iou >= iou_threshold):\n                        # invalidate the box k\n                        out_scores[i, k] = -1.0\n                        on_new_invalidated_box_func(i, k)\n\n                ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n\n        i = by\n\n        nkeep = if_then_else(tvm.tir.all(top_k > 0, top_k < valid_count[i]), top_k, valid_count[i])\n        max_output_size = if_then_else(max_output_size > 0, max_output_size, nkeep)\n\n        with ib.if_scope(tvm.tir.all(iou_threshold > 0, valid_count[i] > 0)):\n            # Apply nms\n            # No need to do more iteration if we have already reached max_output_size boxes\n            box_idx = ib.allocate(\"int32\", (1,), name=\"box_idx\", scope=\"local\")\n            box_idx[0] = 0\n            with ib.while_loop(\n                tvm.tir.all(box_idx[0] < nkeep, num_valid_boxes_local[0] < max_output_size)\n            ):\n                # Proceed to the inner loop if the box with id box_idx is still valid\n                with ib.if_scope(out_scores[i, box_idx[0]] > -1.0):\n                    nms_inner_loop(ib, i, box_idx[0], nkeep)\n                box_idx[0] += 1\n\n            with ib.if_scope(tx + 0 == 0):\n                num_valid_boxes[i] = num_valid_boxes_local[0]\n\n        with ib.else_scope():\n            num_valid_boxes[i] = 0\n\n    return ib.get()\n\n\ndef nms_ir(\n    data,\n    sorted_index,\n    valid_count,\n    indices,\n    out_bboxes,\n    out_scores,\n    out_class_ids,\n    out_features,\n    box_indices,\n    num_valid_boxes,\n    max_output_size,\n    iou_threshold,\n    force_suppress,\n    top_k,\n    coord_start,\n    id_index,\n    score_index,\n    return_indices,\n):\n    \"\"\"Low level IR routing for transform location in multibox_detection operator.\n\n    Parameters\n    ----------\n    data : Buffer\n        Buffer of output boxes with class and score.\n\n    sorted_index : Buffer\n        Buffer of output box indexes sorted by score.\n\n    valid_count : Buffer\n        Buffer of number of valid output boxes.\n\n    indices : Buffer\n        indices in original tensor, with shape [batch_size, num_anchors],\n        represents the index of box in original data. It could be the third\n        output out_indices of get_valid_counts. The values in the second\n        dimension are like the output of arange(num_anchors) if get_valid_counts\n        is not used before non_max_suppression.\n\n    out_bboxes : Buffer\n        Output buffer, to be filled with sorted box coordinates.\n\n    out_scores : Buffer\n        Output buffer, to be filled with sorted scores.\n\n    out_class_ids : Buffer\n        Output buffer, to be filled with sorted class ids.\n\n    box_indices : Buffer\n        A indices tensor mapping sorted indices to original indices\n        This is the first output of NMS when return_indices=True.\n\n    num_valid_boxes : Buffer\n        Record the number of boxes that have survived IOU tests.\n        This is the second output of NMS when return_indices=True.\n\n    max_output_size : int\n        Max number of output valid boxes for each instance.\n        By default all valid boxes are returned.\n\n    iou_threshold : float\n        Overlapping(IoU) threshold to suppress object with smaller score.\n\n    force_suppress : boolean\n        Whether to suppress all detections regardless of class_id.\n\n    top_k : int\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    coord_start : int\n        Start index of the consecutive 4 coordinates.\n\n    id_index : int\n        index of the class categories, -1 to disable.\n\n    score_index : optional, int\n        Index of the scores/confidence of boxes.\n\n    return_indices : boolean\n        Whether to return box indices in input data.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    box_data_length = data.shape[2]\n    num_features = out_features.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    data = ib.buffer_ptr(data)\n    sorted_index = ib.buffer_ptr(sorted_index)\n    valid_count = ib.buffer_ptr(valid_count)\n    indices = ib.buffer_ptr(indices)\n\n    # outputs\n    out_bboxes = ib.buffer_ptr(out_bboxes)\n    out_scores = ib.buffer_ptr(out_scores)\n    out_class_ids = ib.buffer_ptr(out_class_ids)\n    out_features = ib.buffer_ptr(out_features)\n    box_indices = ib.buffer_ptr(box_indices)\n    num_valid_boxes = ib.buffer_ptr(num_valid_boxes)\n\n    if isinstance(iou_threshold, float):\n        iou_threshold = tvm.tir.FloatImm(\"float32\", iou_threshold)\n    top_k = tvm.tir.IntImm(\"int32\", top_k)\n    coord_start = tvm.tir.IntImm(\"int32\", coord_start)\n    id_index = tvm.tir.IntImm(\"int32\", id_index)\n    score_index = tvm.tir.IntImm(\"int32\", score_index)\n    force_suppress = tvm.tir.IntImm(\"int32\", 1 if force_suppress else 0)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(num_anchors, max_threads)\n        nthread_by = batch_size\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(by, \"thread_extent\", nthread_by)\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        i = by\n        base_src_idx = i * num_anchors * box_data_length\n        base_bbox_idx = i * num_anchors * 4\n        base_features_idx = i * num_anchors * num_features\n\n        with ib.if_scope(tvm.tir.all(iou_threshold > 0, valid_count[i] > 0)):\n            # Reorder output\n            nkeep = if_then_else(\n                tvm.tir.all(top_k > 0, top_k < valid_count[i]), top_k, valid_count[i]\n            )\n            j = bx * max_threads + tx\n            with ib.if_scope(j < nkeep):\n                src_idx = base_src_idx + sorted_index[i * num_anchors + j] * box_data_length\n                with ib.for_range(0, 4, kind=\"unroll\") as k:\n                    out_bboxes[(base_bbox_idx + j * 4 + k)] = data[src_idx + coord_start + k]\n                with ib.for_range(0, num_features, kind=\"unroll\") as k:\n                    out_features[(base_features_idx + j * num_features + k)] = data[\n                        src_idx + coord_start + 4 + k\n                    ]\n\n                out_scores[i * num_anchors + j] = data[src_idx + score_index]\n\n                if id_index >= 0:\n                    out_class_ids[i * num_anchors + j] = data[src_idx + id_index]\n\n            with ib.else_scope():\n                # Indices > nkeep are discarded\n                # Only needed for return_indices = False case\n                if return_indices is False:\n                    with ib.if_scope(j < num_anchors):\n                        with ib.for_range(0, 4, kind=\"unroll\") as k:\n                            out_bboxes[(base_bbox_idx + j * 4 + k)] = -1.0\n                        with ib.for_range(0, num_features, kind=\"unroll\") as k:\n                            out_features[(base_features_idx + j * num_features + k)] = -1.0\n\n                        out_scores[i, j] = -1.0\n\n                        if id_index >= 0:\n                            out_class_ids[i, j] = -1.0\n\n            if return_indices:\n                with ib.if_scope(j < num_anchors):\n                    box_indices[i * num_anchors + j] = -1\n\n        with ib.else_scope():\n            # Need to copy all boxes if not using return_indices\n            bounds = valid_count[i] if return_indices else num_anchors\n            with ib.if_scope(j < bounds):\n                src_offset = base_src_idx + j * box_data_length\n\n                with ib.for_range(0, 4, kind=\"unroll\") as k:\n                    out_bboxes[base_bbox_idx + j * 4 + k] = data[src_offset + coord_start + k]\n                with ib.for_range(0, num_features, kind=\"unroll\") as k:\n                    out_features[(base_features_idx + j * num_features + k)] = data[\n                        src_offset + coord_start + 4 + k\n                    ]\n                out_scores[i * num_anchors + j] = data[src_offset + score_index]\n\n                if id_index >= 0:\n                    out_class_ids[i * num_anchors + j] = data[src_offset + id_index]\n\n                box_indices[i * num_anchors + j] = j\n\n    if isinstance(max_output_size, int):\n        max_output_size = tvm.tir.const(max_output_size)\n\n    def calc_overlap(i, j, k):\n        offset_j = j * 4\n        offset_k = k * 4\n        base_bbox_idx = i * num_anchors * 4\n        return calculate_overlap(\n            out_bboxes,\n            base_bbox_idx + offset_j,\n            base_bbox_idx + offset_k,\n        )\n\n    def on_new_valid_box(ib, tid, num_current_valid_box, i, j):\n        # When return_indices is False, no need to populate box_indices\n        if return_indices:\n            with ib.if_scope(tid + 0 == 0):\n                orig_idx = sorted_index[i * num_anchors + j]\n                box_indices[i, num_current_valid_box] = indices[i, orig_idx]\n\n    def on_new_invalidated_box(i, k):\n        if return_indices is False and id_index >= 0:\n            out_class_ids[i, k] = -1.0\n\n    def needs_bbox_check(i, j, k):\n        return tvm.tir.any(\n            force_suppress > 0,\n            id_index < 0,\n            out_class_ids[i, k] == out_class_ids[i, j],\n        )\n\n    return _nms_loop(\n        ib,\n        batch_size,\n        top_k,\n        iou_threshold,\n        max_output_size,\n        valid_count,\n        on_new_valid_box,\n        on_new_invalidated_box,\n        needs_bbox_check,\n        calc_overlap,\n        out_scores,\n        num_valid_boxes,\n    )\n\n\ndef _fetch_score_ir(data, score, axis):\n    \"\"\"\n    Fetch score from data.\n    This routine is required for dynamic shape nms.\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    elem_length = data.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    data = ib.buffer_ptr(data)\n    score = ib.buffer_ptr(score)\n    with ib.if_scope(num_anchors > 0):\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        nthread_tx = max_threads\n        nthread_bx = batch_size * num_anchors // max_threads + 1\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < batch_size * num_anchors):\n            score[tid] = data[tid * elem_length + axis]\n\n    return ib.get()\n\n\ndef _dispatch_sort(scores, ret_type=\"indices\"):\n    target = tvm.target.Target.current()\n    if target and (\n        can_use_thrust(target, \"tvm.contrib.thrust.sort\")\n        or can_use_rocthrust(target, \"tvm.contrib.thrust.sort\")\n    ):\n        return argsort_thrust(scores, axis=1, is_ascend=False, dtype=\"int32\", ret_type=ret_type)\n    return argsort(scores, axis=1, is_ascend=False, dtype=\"int32\", ret_type=ret_type)\n\n\ndef _get_sorted_indices(data, data_buf, score_index, score_shape):\n    \"\"\"Extract a 1D score tensor from the packed input and do argsort on it.\"\"\"\n    score_buf = tvm.tir.decl_buffer(score_shape, data.dtype, \"score_buf\", data_alignment=8)\n    score_tensor = te.extern(\n        [score_shape],\n        [data],\n        lambda ins, outs: _fetch_score_ir(\n            ins[0],\n            outs[0],\n            score_index,\n        ),\n        dtype=[data.dtype],\n        in_buffers=[data_buf],\n        out_buffers=[score_buf],\n        name=\"fetch_score\",\n        tag=\"fetch_score\",\n    )\n    return _dispatch_sort(score_tensor)\n\n\ndef _run_nms(\n    data,\n    data_buf,\n    sort_tensor,\n    valid_count,\n    indices,\n    max_output_size,\n    iou_threshold,\n    force_suppress,\n    top_k,\n    coord_start,\n    id_index,\n    score_index,\n    return_indices,\n):\n    \"\"\"Run NMS using sorted scores.\"\"\"\n    sort_tensor_buf = tvm.tir.decl_buffer(\n        sort_tensor.shape, sort_tensor.dtype, \"sort_tensor_buf\", data_alignment=8\n    )\n\n    valid_count_dtype = \"int32\"\n    valid_count_buf = tvm.tir.decl_buffer(\n        valid_count.shape, valid_count_dtype, \"valid_count_buf\", data_alignment=4\n    )\n    indices_buf = tvm.tir.decl_buffer(indices.shape, indices.dtype, \"indices_buf\", data_alignment=8)\n\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    # Number of extra features per box beyond coords, score, and id.\n    num_features = data.shape[2] - 6 if id_index >= 0 else data.shape[2] - 5\n\n    # output shapes\n    bbox_shape = (batch_size, num_anchors, 4)\n    score_shape = (batch_size, num_anchors)\n    class_id_shape = score_shape\n    out_features_shape = (batch_size, num_anchors, num_features)\n    box_indices_shape = score_shape\n    num_valid_boxes_shape = (batch_size, 1)\n\n    return te.extern(\n        [\n            bbox_shape,\n            score_shape,\n            class_id_shape,\n            out_features_shape,\n            box_indices_shape,\n            num_valid_boxes_shape,\n        ],\n        [data, sort_tensor, valid_count, indices],\n        lambda ins, outs: nms_ir(\n            ins[0],\n            ins[1],\n            ins[2],\n            ins[3],\n            outs[0],  # sorted bbox\n            outs[1],  # sorted scores\n            outs[2],  # sorted class ids\n            outs[3],  # sorted box feats\n            outs[4],  # box_indices\n            outs[5],  # num_valid_boxes\n            max_output_size,\n            iou_threshold,\n            force_suppress,\n            top_k,\n            coord_start,\n            id_index,\n            score_index,\n            return_indices,\n        ),\n        dtype=[data.dtype, \"float32\", \"float32\", \"float32\", \"int32\", \"int32\"],\n        in_buffers=[data_buf, sort_tensor_buf, valid_count_buf, indices_buf],\n        name=\"nms\",\n        tag=\"nms\",\n    )\n\n\ndef _concatenate_outputs(\n    out_bboxes,\n    out_scores,\n    out_class_ids,\n    out_features,\n    out_shape,\n    coord_start,\n    score_index,\n    id_index,\n):\n    \"\"\"Pack the results from NMS into a single 5D or 6D tensor.\"\"\"\n    batch_size = out_bboxes.shape[0]\n    num_anchors = out_bboxes.shape[1]\n    num_features = out_features.shape[2]\n\n    def ir(out_bboxes, out_scores, out_class_ids, out):\n        ib = tvm.tir.ir_builder.create()\n\n        out_bboxes = ib.buffer_ptr(out_bboxes)\n        out_scores = ib.buffer_ptr(out_scores)\n        out_class_ids = ib.buffer_ptr(out_class_ids)\n        out = ib.buffer_ptr(out)\n\n        with ib.if_scope(num_anchors > 0):\n            max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(num_anchors, nthread_tx)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            by = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            ib.scope_attr(by, \"thread_extent\", batch_size)\n\n            tid = bx * nthread_tx + tx\n            i = by\n\n            with ib.if_scope(tid < num_anchors):\n                with ib.for_range(0, 4, kind=\"unroll\") as j:\n                    out[i, tid, coord_start + j] = out_bboxes[i, tid, j]\n                with ib.for_range(0, num_features, kind=\"unroll\") as j:\n                    out[i, tid, coord_start + 4 + j] = out_features[i, tid, j]\n                out[i, tid, score_index] = out_scores[i, tid]\n                if id_index >= 0:\n                    out[i, tid, id_index] = out_class_ids[i, tid]\n\n        return ib.get()\n\n    return te.extern(\n        [out_shape],\n        [out_bboxes, out_scores, out_class_ids],\n        lambda ins, outs: ir(ins[0], ins[1], ins[2], outs[0]),\n        dtype=[\"float32\"],\n        name=\"nms_output_concat\",\n        tag=\"nms_output_concat\",\n    )\n\n\ndef non_max_suppression(\n    data,\n    valid_count,\n    indices,\n    max_output_size=-1,\n    iou_threshold=0.5,\n    force_suppress=False,\n    top_k=-1,\n    coord_start=2,\n    score_index=1,\n    id_index=0,\n    return_indices=True,\n    invalid_to_bottom=False,\n):\n    \"\"\"Non-maximum suppression operator for object detection.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D tensor with shape [batch_size, num_anchors, elem_length].\n        The last dimension should be in format of\n        [class_id, score, box_left, box_top, box_right, box_bottom].\n        It could be the second output out_tensor of get_valid_counts.\n\n    valid_count : tvm.te.Tensor\n        1-D tensor for valid number of boxes. It could be the output\n        valid_count of get_valid_counts.\n\n    indices : tvm.te.Tensor\n        2-D tensor with shape [batch_size, num_anchors], represents\n        the index of box in original data. It could be the third\n        output out_indices of get_valid_counts. The values in the\n        second dimension are like the output of arange(num_anchors)\n        if get_valid_counts is not used before non_max_suppression.\n\n    max_output_size : optional, tvm.te.Tensor or int\n        Max number of output valid boxes for each instance.\n        By default all valid boxes are returned.\n\n    iou_threshold : optional, tvm.te.Tensor or float\n        Non-maximum suppression threshold.\n\n    force_suppress : optional, boolean\n        Whether to suppress all detections regardless of class_id.\n\n    top_k : optional, int\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    coord_start : required, int\n        Start index of the consecutive 4 coordinates.\n\n    score_index : optional, int\n        Index of the scores/confidence of boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    return_indices : boolean\n        Whether to return box indices in input data.\n\n    invalid_to_bottom : optional, boolean\n        Whether to move all valid bounding boxes to the top.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        3-D tensor with shape [batch_size, num_anchors, elem_length].\n\n    Example\n    --------\n    .. code-block:: python\n\n        # An example to use nms\n        dshape = (1, 5, 6)\n        data = te.placeholder(dshape, name=\"data\")\n        valid_count = te.placeholder((dshape[0],), dtype=\"int32\", name=\"valid_count\")\n        iou_threshold = 0.7\n        force_suppress = True\n        top_k = -1\n        out = non_max_suppression(data=data, valid_count=valid_count, iou_threshold=iou_threshold,\n                                 force_suppress=force_supress, top_k=top_k, return_indices=False)\n        np_data = np.random.uniform(dshape)\n        np_valid_count = np.array([4])\n        s = topi.generic.schedule_nms(out)\n        f = tvm.build(s, [data, valid_count, out], \"cuda\")\n        dev = tvm.cuda(0)\n        tvm_data = tvm.nd.array(np_data, dev)\n        tvm_valid_count = tvm.nd.array(np_valid_count, dev)\n        tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), dev)\n        f(tvm_data, tvm_valid_count, tvm_out)\n    \"\"\"\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n\n    sort_tensor = _get_sorted_indices(data, data_buf, score_index, (data.shape[0], data.shape[1]))\n\n    out_bboxes, out_scores, out_class_ids, out_features, box_indices, num_valid_boxes = _run_nms(\n        data,\n        data_buf,\n        sort_tensor,\n        valid_count,\n        indices,\n        max_output_size,\n        iou_threshold,\n        force_suppress,\n        top_k,\n        coord_start,\n        id_index,\n        score_index,\n        return_indices,\n    )\n\n    if return_indices:\n        return [box_indices, num_valid_boxes]\n\n    return _concatenate_outputs(\n        out_bboxes,\n        out_scores,\n        out_class_ids,\n        out_features,\n        data.shape,\n        coord_start,\n        score_index,\n        id_index,\n    )\n\n\ndef _get_valid_box_count(scores, score_threshold):\n    batch_classes, num_boxes = scores.shape\n\n    def searchsorted_ir(scores, valid_count):\n        ib = tvm.tir.ir_builder.create()\n        scores = ib.buffer_ptr(scores)\n        valid_count = ib.buffer_ptr(valid_count)\n\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n\n        with ib.new_scope():\n            ib.scope_attr(bx, \"thread_extent\", ceil_div(batch_classes, max_threads))\n            ib.scope_attr(tx, \"thread_extent\", max_threads)\n            tid = bx * max_threads + tx\n\n            with ib.if_scope(tid < batch_classes):\n                binary_search(ib, tid, num_boxes, scores, score_threshold, valid_count)\n\n        return ib.get()\n\n    scores_buf = tvm.tir.decl_buffer(scores.shape, scores.dtype, \"scores_buf\", data_alignment=8)\n\n    return te.extern(\n        [(batch_classes,)],\n        [scores],\n        lambda ins, outs: searchsorted_ir(ins[0], outs[0]),\n        dtype=[\"int32\"],\n        in_buffers=[scores_buf],\n        name=\"searchsorted\",\n        tag=\"searchsorted\",\n    )\n\n\ndef _collect_selected_indices_ir(num_class, selected_indices, num_detections, row_offsets, out):\n    batch_classes, num_boxes = selected_indices.shape\n\n    ib = tvm.tir.ir_builder.create()\n\n    selected_indices = ib.buffer_ptr(selected_indices)\n    num_detections = ib.buffer_ptr(num_detections)\n    row_offsets = ib.buffer_ptr(row_offsets)\n    out = ib.buffer_ptr(out)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = ceil_div(num_boxes, nthread_tx)\n    nthread_by = batch_classes\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    by = te.thread_axis(\"blockIdx.y\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    ib.scope_attr(by, \"thread_extent\", nthread_by)\n\n    with ib.new_scope():\n        idx = bx * nthread_tx + tx\n        idy = cast(by, \"int64\")\n        batch_id = idy // num_class\n        class_id = idy % num_class\n        with ib.if_scope(idx < num_detections[idy]):\n            out[row_offsets[idy] + idx, 0] = batch_id\n            out[row_offsets[idy] + idx, 1] = class_id\n            out[row_offsets[idy] + idx, 2] = cast(selected_indices[idy, idx], \"int64\")\n\n    return ib.get()\n\n\ndef _collect_selected_indices_and_scores_ir(\n    selected_indices,\n    selected_scores,\n    num_detections,\n    row_offsets,\n    num_total_detections,\n    collected_indices,\n    collected_scores,\n):\n    batch_size, num_class = row_offsets.shape\n    num_boxes = selected_indices.shape[1]\n\n    ib = tvm.tir.ir_builder.create()\n\n    selected_indices = ib.buffer_ptr(selected_indices)\n    selected_scores = ib.buffer_ptr(selected_scores)\n    num_detections = ib.buffer_ptr(num_detections)\n    row_offsets = ib.buffer_ptr(row_offsets)\n    num_total_detections = ib.buffer_ptr(num_total_detections)\n    collected_indices = ib.buffer_ptr(collected_indices)\n    collected_scores = ib.buffer_ptr(collected_scores)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = ceil_div(num_boxes, nthread_tx)\n    nthread_by = batch_size * num_class\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    by = te.thread_axis(\"blockIdx.y\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    ib.scope_attr(by, \"thread_extent\", nthread_by)\n    zero = cast(0, \"int64\")\n\n    with ib.new_scope():\n        idx = bx * nthread_tx + tx\n        idy = cast(by, \"int64\")\n        batch_id = idy // num_class\n        class_id = idy % num_class\n\n        with ib.if_scope(idx < num_detections[batch_id, class_id]):\n            offset = row_offsets[batch_id, class_id] + idx\n            collected_indices[batch_id, offset, 0] = class_id\n            collected_indices[batch_id, offset, 1] = cast(selected_indices[idy, idx], \"int64\")\n            collected_scores[batch_id, offset] = selected_scores[idy, idx]\n        with ib.else_scope():\n            with ib.if_scope(idx < num_boxes):\n                offset = (\n                    num_total_detections[batch_id]\n                    + class_id * num_boxes\n                    - row_offsets[batch_id, class_id]\n                    + idx\n                    - num_detections[batch_id, class_id]\n                )\n                collected_indices[batch_id, offset, 0] = zero\n                collected_indices[batch_id, offset, 1] = zero\n                collected_scores[batch_id, offset] = 0.0\n\n    return ib.get()\n\n\ndef all_class_non_max_suppression(\n    boxes,\n    scores,\n    max_output_boxes_per_class,\n    iou_threshold,\n    score_threshold,\n    output_format=\"onnx\",\n):\n    \"\"\"Non-maximum suppression operator for object detection, corresponding to ONNX\n    NonMaxSuppression and TensorFlow combined_non_max_suppression.\n    NMS is performed for each class separately.\n\n    Parameters\n    ----------\n    boxes : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_boxes, 4)\n\n    scores: tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_classes, num_boxes)\n\n    max_output_boxes_per_class : int or tvm.te.Tensor, optional\n        The maxinum number of output selected boxes per class\n\n    iou_threshold : float or tvm.te.Tensor, optionaIl\n        IoU test threshold\n\n    score_threshold : float or tvm.te.Tensor, optional\n        Score threshold to filter out low score boxes early\n\n    output_format : str, optional\n        \"onnx\" or \"tensorflow\", see below\n\n    Returns\n    -------\n    out : list of tvm.te.Tensor\n        If `output_format` is \"onnx\", the output is two tensors. The first is `indices` of size\n        `(batch_size * num_class* num_boxes , 3)` and the second is a scalar tensor\n        `num_total_detection` of shape `(1,)` representing the total number of selected\n        boxes. The three values in `indices` encode batch, class, and box indices.\n        Rows of `indices` are ordered such that selected boxes from batch 0, class 0 come\n        first, in descending of scores, followed by boxes from batch 0, class 1 etc. Out of\n        `batch_size * num_class* num_boxes` rows of indices, only the first `num_total_detection`\n        rows are valid.\n\n        If `output_format` is \"tensorflow\", the output is three tensors, the first\n        is `indices` of size `(batch_size, num_class * num_boxes , 2)`, the second is `scores` of\n        size `(batch_size, num_class * num_boxes)`, and the third is `num_total_detection` of size\n        `(batch_size,)` representing the total number of selected boxes per batch. The two values\n        in `indices` encode class and box indices. Of num_class * num_boxes boxes in `indices` at\n        batch b, only the first `num_total_detection[b]` entries are valid. The second axis of\n        `indices` and `scores` are sorted within each class by box scores, but not across classes.\n        So the box indices and scores for the class 0 come first in a sorted order, followed by\n        the class 1 etc.\n    \"\"\"\n    batch, num_class, num_boxes = scores.shape\n\n    scores = reshape(scores, (batch * num_class, num_boxes))\n    sorted_scores, sorted_indices = _dispatch_sort(scores, ret_type=\"both\")\n    valid_count = _get_valid_box_count(sorted_scores, score_threshold)\n\n    selected_indices, selected_scores, num_detections = run_all_class_nms(\n        boxes,\n        sorted_scores,\n        sorted_indices,\n        valid_count,\n        max_output_boxes_per_class,\n        iou_threshold,\n        _nms_loop,\n        return_scores=(output_format == \"tensorflow\"),\n    )\n\n    if output_format == \"onnx\":\n        row_offsets, num_total_detections = exclusive_scan(\n            num_detections, return_reduction=True, output_dtype=\"int64\"\n        )\n        selected_indices = collect_selected_indices(\n            num_class, selected_indices, num_detections, row_offsets, _collect_selected_indices_ir\n        )\n        return [selected_indices, num_total_detections]\n\n    num_detections_per_batch = reshape(num_detections, (batch, num_class))\n    row_offsets, num_total_detections = exclusive_scan(\n        num_detections_per_batch, return_reduction=True, output_dtype=\"int64\", axis=1\n    )\n\n    selected_indices, selected_scores = collect_selected_indices_and_scores(\n        selected_indices,\n        selected_scores,\n        num_detections_per_batch,\n        row_offsets,\n        num_total_detections,\n        _collect_selected_indices_and_scores_ir,\n    )\n\n    return [selected_indices, selected_scores, num_total_detections]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"scheduler functions for cuda backend\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom ..utils import traverse_inline\n\n\ndef schedule_lrn(outs):\n    \"\"\"Schedule for LRN\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of LRN\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n\n    def _callback(op):\n        if \"sqr_sum\" in op.tag:\n            pad = op.input_tensors[0]\n            s[pad].compute_inline()\n            fused_axis = s[outs[0]].fuse(*s[outs[0]].op.axis)\n            bx, tx = s[outs[0]].split(fused_axis, factor=max_threads)\n            s[outs[0]].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[outs[0]].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[op].compute_at(s[outs[0]], tx)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Schedule for pooling operators\"\"\"\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..utils import traverse_inline\nfrom .reduction import _schedule_reduce\nfrom .injective import schedule_injective_from_existing\n\n\ndef schedule_adaptive_pool(outs, layout=\"NCHW\"):\n    \"\"\"Schedule for adaptive_pool.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of adaptive_pool\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for adaptive_pool.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule_non_global(Pool):\n        if Pool.op in s.outputs:\n            Out = Pool\n            OL = s.cache_write(Pool, \"local\")\n        else:\n            Out = outs[0].op.output(0)\n            s[Pool].set_scope(\"local\")\n\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        fused_axis = s[Out].fuse(*s[Out].op.axis)\n        bx, tx = s[Out].split(fused_axis, factor=max_threads)\n        s[Out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[Out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n        if Pool.op in s.outputs:\n            s[OL].compute_at(s[Out], tx)\n        else:\n            s[Pool].compute_at(s[Out], tx)\n\n    scheduled_ops = []\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_injective(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule global_pool\n        elif OP.tag.startswith(\"adaptive_pool\"):\n            Pool = OP.output(0)\n            oshape = Pool.shape\n            if (layout == \"NCHW\" and oshape[2] == 1 and oshape[3] == 1) or (\n                layout == \"NHWC\" and oshape[1] == 1 and oshape[2] == 1\n            ):\n                _schedule_reduce(OP, s)\n                if OP != outs[0].op:\n                    # the final division for adaptive pool or fused elemwise ops\n                    schedule_injective_from_existing(s, outs[0])\n            else:\n                _schedule_non_global(Pool)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Schedule for pool.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of pool\n        in the format of an array of tensors.\n\n    layout: str\n        Data layout.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for pool.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(PaddedInput, Pool):\n        if isinstance(PaddedInput.op, tvm.te.ComputeOp):\n            s[PaddedInput].compute_inline()\n        num_thread = tvm.target.Target.current(allow_none=False).max_num_threads\n        if Pool.op in s.outputs:\n            Out = Pool\n            OL = s.cache_write(Pool, \"local\")\n        else:\n            Out = outs[0].op.output(0)\n            s[Pool].set_scope(\"local\")\n        fused = s[Out].fuse(*s[Out].op.axis)\n        bx, tx = s[Out].split(fused, factor=num_thread)\n        s[Out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[Out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        if Pool.op in s.outputs:\n            s[OL].compute_at(s[Out], tx)\n        else:\n            s[Pool].compute_at(s[Out], tx)\n\n    scheduled_ops = []\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_injective(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule pool\n        elif OP.tag.startswith(\"pool\"):\n            PaddedInput = OP.input_tensors[0]\n            Pool = OP.output(0)\n            _schedule(PaddedInput, Pool)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef schedule_pool_grad(outs):\n    \"\"\"Schedule for pool_grad on CUDA\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of pool_grad\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for pool_grad.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule_pool_grad(op):\n        if op in s.outputs:\n            out = op\n        else:\n            out = outs[0].op.output(0)\n        fused = s[out].fuse(*s[out].op.axis)\n        num_thread = tvm.target.Target.current(allow_none=False).max_num_threads\n        bx, tx = s[out].split(fused, factor=num_thread)\n        s[out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n        if tag.COMM_REDUCE_IDX in op.input_tensors[0].op.tag:\n            max_pool_index = op.input_tensors[0]\n            s[max_pool_index].compute_at(s[out], tx)\n\n            pool_input = max_pool_index.op.input_tensors[0]\n            if isinstance(pool_input.op, tvm.te.ComputeOp):\n                # handle padding\n                s[pool_input].compute_inline()\n        if op not in s.outputs:\n            s[op].compute_at(s[out], tx)\n\n    def _callback(op):\n        if op.tag.startswith(\"pool_grad\"):\n            _schedule_pool_grad(op)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/rcnn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Faster R-CNN and Mask R-CNN operators\"\"\"\nfrom .proposal import proposal\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/rcnn/proposal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, singleton-comparison, bad-continuation\n\"\"\"Proposal operator\"\"\"\nimport math\nimport tvm\nfrom tvm import te\nfrom ...vision.rcnn import generate_anchor, reg_bbox, reg_iou\nfrom ...utils import get_const_tuple, get_const_int\n\n\ndef predict_bbox_ir(\n    cls_prob_buf,\n    bbox_pred_buf,\n    im_info_buf,\n    out_buf,\n    scales,\n    ratios,\n    feature_stride,\n    rpn_min_size,\n    iou_loss,\n):\n    \"\"\"Predict bounding boxes based on anchors, scores and deltas.\n\n    Parameters\n    ----------\n    cls_prob_buf : tvm.te.schedule.Buffer\n        4-D with shape [batch, 2 * num_anchors, height, width]\n\n    bbox_pred_buf : tvm.te.schedule.Buffer\n        4-D with shape [batch, 4 * num_anchors, height, width]\n\n    im_info_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, 3]\n\n    out_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]\n        The last dimension is in format of [w_start, h_start, w_end, h_end, score]\n\n    scales : list/tuple of float\n        Scales of anchor windows.\n\n    ratios : list/tuple of float\n        Ratios of anchor windows.\n\n    feature_stride : int\n        The size of the receptive field each unit in the convolution layer of the rpn, for example\n        the product of all stride's prior to this layer.\n\n    rpn_min_size : int\n        Minimum height or width in proposal.\n\n    iou_loss : bool\n        Usage of IoU loss.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_anchors, height, width = get_const_tuple(cls_prob_buf.shape)\n    num_anchors //= 2\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = (batch * height * width) // max_threads + 1\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    tid = bx * max_threads + tx\n    ib = tvm.tir.ir_builder.create()\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n    p_score = ib.buffer_ptr(cls_prob_buf)\n    p_delta = ib.buffer_ptr(bbox_pred_buf)\n    p_im_info = ib.buffer_ptr(im_info_buf)\n    p_out = ib.buffer_ptr(out_buf)\n\n    idxm = tvm.tir.indexmod\n    idxd = tvm.tir.indexdiv\n\n    with ib.if_scope(tid < batch * height * width):\n        w = idxm(tid, width)\n        h = idxm(idxd(tid, width), height)\n        b = idxd(idxd(tid, width), height)\n\n        for k in range(num_anchors):\n            out_index = tid * num_anchors + k\n            ratio = ratios[k // len(scales)]\n            scale = scales[k % len(scales)]\n            anchor = generate_anchor(ratio, scale, feature_stride)\n            im_height = p_im_info[b * 3]\n            im_width = p_im_info[b * 3 + 1]\n            x1 = anchor[0] + w * feature_stride\n            y1 = anchor[1] + h * feature_stride\n            x2 = anchor[2] + w * feature_stride\n            y2 = anchor[3] + h * feature_stride\n\n            delta = [\n                p_delta[((((b * num_anchors + k) * 4 + i) * height + h) * width + w)]\n                for i in range(4)\n            ]\n            regression_func = reg_iou if iou_loss else reg_bbox\n            pred_x1, pred_y1, pred_x2, pred_y2 = regression_func(x1, y1, x2, y2, *delta)\n\n            pred_x1 = tvm.te.max(tvm.te.min(pred_x1, im_width - 1.0), 0.0)\n            pred_y1 = tvm.te.max(tvm.te.min(pred_y1, im_height - 1.0), 0.0)\n            pred_x2 = tvm.te.max(tvm.te.min(pred_x2, im_width - 1.0), 0.0)\n            pred_y2 = tvm.te.max(tvm.te.min(pred_y2, im_height - 1.0), 0.0)\n\n            real_height = (im_height / feature_stride).astype(\"int32\")\n            real_width = (im_width / feature_stride).astype(\"int32\")\n\n            bbox_w = pred_x2 - pred_x1 + 1.0\n            bbox_h = pred_y2 - pred_y1 + 1.0\n            min_size = p_im_info[b * 3 + 2] * rpn_min_size\n\n            pred_score = p_score[((b * num_anchors * 2 + num_anchors + k) * height + h) * width + w]\n            pred_score = tvm.tir.Select(\n                tvm.tir.any(h >= real_height, w >= real_width), -1.0, pred_score\n            )\n            p_out[out_index * 5 + 0] = pred_x1\n            p_out[out_index * 5 + 1] = pred_y1\n            p_out[out_index * 5 + 2] = pred_x2\n            p_out[out_index * 5 + 3] = pred_y2\n            p_out[out_index * 5 + 4] = pred_score\n\n            with ib.if_scope(tvm.tir.any(bbox_w < min_size, bbox_h < min_size)):\n                p_out[out_index * 5 + 0] -= min_size / 2.0\n                p_out[out_index * 5 + 1] -= min_size / 2.0\n                p_out[out_index * 5 + 2] += min_size / 2.0\n                p_out[out_index * 5 + 3] += min_size / 2.0\n                p_out[out_index * 5 + 4] = -1.0\n\n    return ib.get()\n\n\ndef argsort_ir(data_buf, out_index_buf):\n    \"\"\"Batched odd-even transposition sort.\n\n    Parameters\n    ----------\n    data_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]\n\n    out_index_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Indices of data in sorted order.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_bbox = get_const_tuple(data_buf.shape)\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    ib = tvm.tir.ir_builder.create()\n    p_data = ib.buffer_ptr(data_buf)\n    index_out = ib.buffer_ptr(out_index_buf)\n    nthread_tx = max_threads\n    nthread_bx = (num_bbox + 1) // 2 // max_threads + 1\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"vthread\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"virtual_thread\", nthread_bx)\n    tid = bx * nthread_tx + tx\n    temp_data = ib.allocate(\"float32\", (1,), name=\"temp_data\", scope=\"local\")\n    temp_index = ib.allocate(\"int32\", (1,), name=\"temp_index\", scope=\"local\")\n\n    idxm = tvm.tir.indexmod\n\n    with ib.for_range(0, batch, kind=\"unroll\") as b:\n        start = b * num_bbox\n        for i in range(2):\n            bbox_id = tid * 2 + i\n            with ib.if_scope(bbox_id < num_bbox):\n                index_out[start + bbox_id] = bbox_id\n        with ib.for_range(0, num_bbox) as k:\n            offset = start + 2 * tid + idxm(k, 2)\n            with ib.if_scope(\n                tvm.tir.all(offset + 1 < num_bbox, p_data[offset] < p_data[offset + 1])\n            ):\n                temp_data[0] = p_data[offset]\n                p_data[offset] = p_data[offset + 1]\n                p_data[offset + 1] = temp_data[0]\n                temp_index[0] = index_out[offset]\n                index_out[offset] = index_out[offset + 1]\n                index_out[offset + 1] = temp_index[0]\n            ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n    return ib.get()\n\n\ndef nms_ir(sorted_bbox_buf, out_buf, nms_threshold):\n    \"\"\"Non-maximum suppression.\n\n    Parameters\n    ----------\n    sorted_bbox_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]. The last dimension is in format of\n        [w_start, h_start, w_end, h_end, score].\n\n    out_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Boolean mask of whether a bounding box should be removed.\n\n    nms_threshold : float\n        Non-maximum suppression threshold.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def calculate_overlap(out_tensor, box_a_idx, box_b_idx):\n        \"\"\"Calculate overlap of two boxes.\"\"\"\n        w = tvm.te.max(\n            0.0,\n            tvm.te.min(out_tensor[box_a_idx + 2], out_tensor[box_b_idx + 2])\n            - tvm.te.max(out_tensor[box_a_idx], out_tensor[box_b_idx])\n            + 1.0,\n        )\n        h = tvm.te.max(\n            0.0,\n            tvm.te.min(out_tensor[box_a_idx + 3], out_tensor[box_b_idx + 3])\n            - tvm.te.max(out_tensor[box_a_idx + 1], out_tensor[box_b_idx + 1])\n            + 1.0,\n        )\n        i = w * h\n        u = (\n            (out_tensor[box_a_idx + 2] - out_tensor[box_a_idx] + 1.0)\n            * (out_tensor[box_a_idx + 3] - out_tensor[box_a_idx + 1] + 1.0)\n            + (out_tensor[box_b_idx + 2] - out_tensor[box_b_idx] + 1.0)\n            * (out_tensor[box_b_idx + 3] - out_tensor[box_b_idx + 1] + 1.0)\n            - i\n        )\n        return i / u\n\n    batch, num_bbox = get_const_tuple(out_buf.shape)\n    max_threads = int(math.sqrt(tvm.target.Target.current(allow_none=False).max_num_threads))\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib = tvm.tir.ir_builder.create()\n    p_data = ib.buffer_ptr(sorted_bbox_buf)\n    p_out = ib.buffer_ptr(out_buf)\n    nthread_tx = max_threads\n    nthread_bx = num_bbox // max_threads + 1\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    i = bx * max_threads + tx\n    with ib.for_range(0, batch, kind=\"unroll\", name=\"n\") as b:\n        base_idx = b * num_bbox\n        with ib.if_scope(i < num_bbox):\n            p_out[base_idx + i] = False\n        with ib.for_range(0, num_bbox - 1) as l:\n            with ib.if_scope(tvm.tir.all(i < num_bbox, i > l, p_out[base_idx + l] == False)):\n                iou = calculate_overlap(p_data, (base_idx + l) * 5, (base_idx + i) * 5)\n                with ib.if_scope(iou > nms_threshold):\n                    p_out[base_idx + i] = True\n        ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n    return ib.get()\n\n\ndef prepare_output_ir(sorted_bbox_buf, remove_mask_buf, out_buf):\n    \"\"\"Copy output after applying nms to continuous memory.\n\n    Parameters\n    ----------\n    sorted_bbox_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]. The last dimension is in format of\n        [w_start, h_start, w_end, h_end, score].\n\n    remove_mask_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Boolean mask of whether a bounding box should be removed.\n\n    out_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of\n        [batch_index, w_start, h_start, w_end, h_end].\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_bbox, _ = get_const_tuple(sorted_bbox_buf.shape)\n    rpn_post_nms_top_n = get_const_int(out_buf.shape[0]) // batch\n    nthread_tx = batch\n    tx = te.thread_axis(\"threadIdx.x\")\n    ib = tvm.tir.ir_builder.create()\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    i = ib.allocate(\"int32\", (1,), \"i\", scope=\"local\")\n    i[0] = 0\n    p_sorted_bbox = ib.buffer_ptr(sorted_bbox_buf)\n    p_remove = ib.buffer_ptr(remove_mask_buf)\n    p_out = ib.buffer_ptr(out_buf)\n    b = tx\n\n    nkeep = ib.allocate(\"int32\", (1,), \"nkeep\", scope=\"local\")\n    nkeep[0] = 0  # number of bbox after nms\n\n    with ib.for_range(0, num_bbox) as j:\n        with ib.if_scope(p_remove[b * num_bbox + j] == False):\n            nkeep[0] += 1\n    with ib.if_scope(nkeep[0] > 0):\n        with ib.for_range(\n            0, te.ceil(tvm.tir.const(rpn_post_nms_top_n, \"float32\") / nkeep[0]).astype(\"int32\")\n        ):\n            with ib.for_range(0, num_bbox) as j:\n                offset_j = (b * num_bbox + j) * 5\n                offset_i = (b * rpn_post_nms_top_n + i[0]) * 5\n                with ib.if_scope(\n                    tvm.tir.all(i[0] < rpn_post_nms_top_n, p_remove[(b * num_bbox + j)] == False)\n                ):\n                    p_out[offset_i] = tvm.tir.Cast(\"float32\", b)\n                    with ib.for_range(0, 4, kind=\"unroll\") as k:\n                        p_out[offset_i + k + 1] = p_sorted_bbox[offset_j + k]\n                    i[0] = i[0] + 1\n\n    body = ib.get()\n    return body\n\n\ndef proposal(\n    cls_prob,\n    bbox_pred,\n    im_info,\n    scales,\n    ratios,\n    feature_stride,\n    threshold,\n    rpn_pre_nms_top_n,\n    rpn_post_nms_top_n,\n    rpn_min_size,\n    iou_loss,\n):\n    \"\"\"Proposal operator.\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        4-D with shape [batch, 2 * num_anchors, height, width]\n\n    bbox_pred : tvm.te.Tensor\n        4-D with shape [batch, 4 * num_anchors, height, width]\n\n    im_info : tvm.te.Tensor\n        2-D with shape [batch, 3]\n\n    scales : list/tuple of float\n        Scales of anchor windows.\n\n    ratios : list/tuple of float\n        Ratios of anchor windows.\n\n    feature_stride : int\n        The size of the receptive field each unit in the convolution layer of the rpn, for example\n        the product of all stride's prior to this layer.\n\n    threshold : float\n        Non-maximum suppression threshold.\n\n    rpn_pre_nms_top_n : int\n        Number of top scoring boxes to apply NMS. -1 to use all boxes.\n\n    rpn_post_nms_top_n : int\n        Number of top scoring boxes to keep after applying NMS to RPN proposals.\n\n    rpn_min_size : int\n        Minimum height or width in proposal.\n\n    iou_loss : bool\n        Usage of IoU loss.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        2-D tensor with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of\n        [batch_index, w_start, h_start, w_end, h_end].\n    \"\"\"\n\n    batch, _, height, width = get_const_tuple(cls_prob.shape)\n    num_anchors = len(scales) * len(ratios)\n    num_bbox = height * width * num_anchors\n    rpn_pre_nms_top_n = min(rpn_pre_nms_top_n, num_bbox) if rpn_pre_nms_top_n > 0 else num_bbox\n\n    bbox = te.extern(\n        (batch, num_bbox, 5),\n        [cls_prob, bbox_pred, im_info],\n        lambda ins, outs: predict_bbox_ir(\n            ins[0], ins[1], ins[2], outs[0], scales, ratios, feature_stride, rpn_min_size, iou_loss\n        ),\n        dtype=bbox_pred.dtype,\n    )\n    score = te.compute((batch, num_bbox), lambda b, i: bbox[b, i, 4], tag=\"bbox_score\")\n    sorted_index = te.extern(\n        [score.shape], [score], lambda ins, outs: argsort_ir(ins[0], outs[0]), dtype=\"int32\"\n    )\n    sorted_bbox = te.compute(\n        (batch, rpn_pre_nms_top_n, 5),\n        lambda b, i, j: bbox[b, sorted_index[b, i], j],\n        tag=\"sorted_bbox\",\n    )\n    nms_remove_mask = te.extern(\n        (batch, rpn_pre_nms_top_n),\n        [sorted_bbox],\n        lambda ins, outs: nms_ir(ins[0], outs[0], threshold),\n        dtype=\"bool\",\n    )\n    nms_out = te.extern(\n        (batch * rpn_post_nms_top_n, 5),\n        [sorted_bbox, nms_remove_mask],\n        lambda ins, outs: prepare_output_ir(ins[0], ins[1], outs[0]),\n        dtype=sorted_bbox.dtype,\n    )\n    return nms_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,too-many-locals,len-as-condition\n\"\"\"Schedule for reduce operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom operator import mul\nfrom functools import reduce\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom .injective import schedule_injective_from_existing\n\n\ndef _schedule_reduce(op, sch, is_idx_reduce=False):\n    if is_idx_reduce:\n        data_out = op.input_tensors[0]\n    else:\n        data_in = op.input_tensors[0]\n        data_out = op.output(0)\n\n    if not sch[data_out].op.reduce_axis:\n        return schedule_injective_from_existing(sch, op.output(0))\n\n    if len(sch[data_out].op.axis) > 0:\n        all_reduce = False\n        num_thread = 32\n        target = tvm.target.Target.current()\n        if target and (target.kind.name == \"opencl\" or target.kind.name == \"metal\"):\n            # without it, CL_INVALID_WORK_GROUP_SIZE occurred when running test_topi_reduce.py\n            # don't know why\n            num_thread = 16\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n        thread_y = te.thread_axis((0, num_thread), \"threadIdx.y\")\n    else:\n        all_reduce = True\n        num_thread = tvm.target.Target.current(allow_none=False).max_num_threads\n        thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n\n    # Fuse and refactor the reduce axis\n    fused_reduce = sch[data_out].fuse(\n        *[sch[data_out].op.reduce_axis[i] for i in range(len(sch[data_out].op.reduce_axis))]\n    )\n    ko, ki = sch[data_out].split(fused_reduce, factor=num_thread)\n    if is_idx_reduce:\n        data_out_rf, _ = sch.rfactor(data_out, ki)\n    else:\n        data_out_rf = sch.rfactor(data_out, ki)\n    tx = sch[data_out].op.reduce_axis[0]\n    sch[data_out].bind(tx, thread_x)\n    sch[data_out_rf].compute_at(sch[data_out], tx)\n    if is_idx_reduce:\n        real_output = op.output(0)\n        temp_idx_input = data_out.op.output(0)\n        temp_val_input = data_out.op.output(1)\n    else:\n        real_output = data_out\n    if not all_reduce:\n        # Fuse and split the axis\n        fused_outer = sch[real_output].fuse(\n            *[sch[real_output].op.axis[i] for i in range(len(sch[real_output].op.axis))]\n        )\n        bx, outer_in = sch[real_output].split(fused_outer, factor=num_thread)\n\n        # Bind the axes to threads and blocks\n        sch[real_output].bind(outer_in, thread_y)\n        sch[real_output].bind(bx, block_x)\n        if is_idx_reduce:\n            sch[temp_idx_input].compute_at(sch[real_output], outer_in)\n            sch[temp_val_input].compute_at(sch[real_output], outer_in)\n        sch[real_output].set_store_predicate(\n            tvm.tir.all(\n                thread_x.equal(0), block_x * num_thread + thread_y < reduce(mul, real_output.shape)\n            )\n        )\n    else:\n        if is_idx_reduce:\n            spatial_axis = sch[real_output].fuse(*(sch[real_output].op.axis))\n            sch[real_output].bind(spatial_axis, te.thread_axis(\"blockIdx.x\"))\n            sch[temp_idx_input].compute_at(sch[real_output], spatial_axis)\n            sch[temp_val_input].compute_at(sch[real_output], spatial_axis)\n        sch[real_output].set_store_predicate(thread_x.equal(0))\n    return sch\n\n\ndef _enable_auto_inline(sch):\n    def is_scheduled(stage):\n        # auto inline requires the attach type is AttachType.kGroupRoot\n        conds = [\n            len(stage.relations) == 0,\n            stage.attach_type == 1,\n            stage.all_iter_vars == stage.leaf_iter_vars,\n        ]\n        if not all(conds):\n            return True\n        return False\n\n    for s in sch.stages:\n        if not s.is_output and isinstance(s.op, tvm.te.ComputeOp):\n            if is_scheduled(s) or len(s.op.reduce_axis) != 0:\n                return False\n    return True\n\n\ndef schedule_reduce_impl(outs, schedule_reduce_stage, schedule_injective_stage):\n    \"\"\"Schedule for inject->reduce->bcast ops.\n    Traverse over the stages in the schedule and schedule separate stages depending\n    on the position of the stage. Injecteve post-ops of reduction will be scheduled using\n    injection schedule, injective pre-ops of reduction will be inlined, reduction stage\n    will be scheduled using reduction schedule\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of reduce in the format\n          of an array of tensors.\n    schedule_reduce_stage: Function responsible for scheduling the reduction\n          stage\n    schedule_injective_stage: Function responsible for scheduling the\n          standalone injection stage\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    sch = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n    enable_auto_inline = _enable_auto_inline(sch)\n\n    def traverse_before_reduce(operator):\n        \"\"\"Internal traverse function\"\"\"\n        if isinstance(operator, tvm.te.PlaceholderOp):\n            return\n        if tag.is_injective(operator.tag):\n            sch[operator].compute_inline()\n            for tensor in operator.input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % operator.tag)\n\n        scheduled_ops.append(operator)\n\n    def traverse_after_reduce(operator):\n        \"\"\"Internal traverse function\"\"\"\n        if tag.is_broadcast(operator.tag):\n            if operator not in scheduled_ops:\n                schedule_injective_stage(sch, operator.output(0))\n            for tensor in operator.input_tensors:\n                if tensor.op not in scheduled_ops:\n                    if enable_auto_inline:\n                        traverse_before_reduce(tensor.op)\n                    else:\n                        traverse_after_reduce(tensor.op)\n        elif operator.tag == \"comm_reduce\":\n            if operator not in scheduled_ops:\n                schedule_reduce_stage(operator, sch, is_idx_reduce=False)\n            for tensor in operator.input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        elif operator.tag == \"comm_reduce_idx\":\n            if operator not in scheduled_ops:\n                schedule_reduce_stage(operator, sch, is_idx_reduce=True)\n            input_tensors = operator.input_tensors[0].op.input_tensors\n            for tensor in input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        elif isinstance(operator, tvm.te.PlaceholderOp):\n            pass\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % operator.tag)\n\n        scheduled_ops.append(operator)\n\n    for out in outs:\n        traverse_after_reduce(out.op)\n    return sch\n\n\ndef schedule_reduce(outs):\n    return schedule_reduce_impl(outs, _schedule_reduce, schedule_injective_from_existing)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/scan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements\n\"Scan related operators\"\nfrom typing import Callable, Optional, Union\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib.thrust import can_use_rocthrust, can_use_thrust\n\nfrom .. import tag\nfrom ..math import cast, ceil_log2\nfrom ..transform import expand_dims, reshape, squeeze, transpose\nfrom ..utils import ceil_div, get_const_int, prod, swap\nfrom .injective import schedule_injective_from_existing\n\n\ndef _get_thrust_func_name(tvmop):\n    tvmop_to_thrust_func_name = {tvm.tir.generic.add: \"tvm.contrib.thrust.sum_scan\"}\n    assert tvmop in tvmop_to_thrust_func_name, \"{} not supported by thrust\".format(tvmop)\n    return tvmop_to_thrust_func_name[tvmop]\n\n\ndef exclusive_scan_ir(data, output, reduction=None, binop=tvm.tir.generic.add, identity_value=0):\n    \"\"\"Low level IR to do exclusive sum scan along rows of 2D input.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input N-D Buffer. Scan is done over the innermost axis.\n\n    output: Buffer\n        A buffer to store the output scan, of the same shape as data\n\n    reduction: Buffer, optional\n        (N-1)-D Buffer, to store the sum of each scan axis.\n\n    binop: function, optional\n        A binary associative op to use for scan. The function takes two TIR expressions\n        and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute\n        prefix sum.\n\n    identity_value: int or float\n        A value for the binary operation which provides the identity property. E.g. if * is\n        your operator and i is the identity_value then a * i = a for all a in the domain of\n        your operation.\n    \"\"\"\n\n    batch_size = prod(data.shape[:-1])\n    scan_axis_size = data.shape[-1]\n\n    ib = tvm.tir.ir_builder.create()\n\n    data = ib.buffer_ptr(data)\n    output = ib.buffer_ptr(output)\n\n    out_dtype = output.dtype\n\n    if reduction is not None:\n        reduction = ib.buffer_ptr(reduction)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n\n    with ib.if_scope(scan_axis_size == 0):\n        with ib.new_scope():\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(bx, \"thread_extent\", batch_size)\n            with ib.if_scope(bx < batch_size):\n                if reduction is not None:\n                    reduction[bx] = cast(identity_value, out_dtype)\n    with ib.else_scope():\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(scan_axis_size, max_threads)\n            nthread_by = batch_size\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            by = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            ib.scope_attr(by, \"thread_extent\", nthread_by)\n            tid = bx * nthread_tx + tx\n            with ib.if_scope(tid < scan_axis_size):\n                output[by * scan_axis_size + tid] = cast(data[by * scan_axis_size + tid], out_dtype)\n\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(scan_axis_size, max_threads)\n        nthread_by = batch_size\n\n        # The following algorithm performs parallel exclusive scan\n        # Up Sweep of exclusive scan\n        lim = ceil_log2(scan_axis_size)\n\n        with ib.for_range(0, cast(lim, \"int64\"), dtype=\"int64\") as l2_width:\n            width = 2 << l2_width\n\n            with ib.new_scope():\n                tx = te.thread_axis(\"threadIdx.x\")\n                bx = te.thread_axis(\"blockIdx.x\")\n                ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n                ib.scope_attr(\n                    bx,\n                    \"thread_extent\",\n                    tvm.tir.generic.cast(ceil_div(scan_axis_size, max_threads * width), \"int32\"),\n                )\n                tid = bx * nthread_tx + tx\n\n                by = te.thread_axis(\"blockIdx.y\")\n                ib.scope_attr(by, \"thread_extent\", nthread_by)\n                start = ib.allocate(\"int64\", (1,), name=\"start\", scope=\"local\")\n                middle = ib.allocate(\"int64\", (1,), name=\"middle\", scope=\"local\")\n                end = ib.allocate(\"int64\", (1,), name=\"end\", scope=\"local\")\n                start[0] = width * tid\n                with ib.if_scope(start[0] < scan_axis_size):\n                    middle[0] = start[0] + tvm.tir.indexdiv(width, 2)\n                    end[0] = tvm.te.min(start[0] + width, scan_axis_size)\n                    with ib.if_scope(middle[0] < scan_axis_size):\n                        output[by * scan_axis_size + end[0] - 1] = binop(\n                            output[by * scan_axis_size + end[0] - 1],\n                            output[by * scan_axis_size + middle[0] - 1],\n                        )\n\n        # Down Sweep of exclusive scan\n        with ib.new_scope():\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(bx, \"thread_extent\", batch_size)\n            with ib.if_scope(bx < batch_size):\n                if reduction is not None:\n                    reduction[bx] = output[(bx + 1) * scan_axis_size - 1]\n                output[(bx + 1) * scan_axis_size - 1] = cast(identity_value, out_dtype)\n\n        with ib.for_range(0, cast(lim, \"int64\"), dtype=\"int64\") as l2_width:\n            width = 2 << (lim - l2_width - 1)\n\n            with ib.new_scope():\n                tx = te.thread_axis(\"threadIdx.x\")\n                bx = te.thread_axis(\"blockIdx.x\")\n                ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n                ib.scope_attr(\n                    bx,\n                    \"thread_extent\",\n                    tvm.tir.generic.cast(ceil_div(scan_axis_size, max_threads * width), \"int32\"),\n                )\n                tid = bx * nthread_tx + tx\n\n                by = te.thread_axis(\"blockIdx.y\")\n                ib.scope_attr(by, \"thread_extent\", nthread_by)\n                start = ib.allocate(\"int64\", (1,), name=\"start\", scope=\"local\")\n                middle = ib.allocate(\"int64\", (1,), name=\"middle\", scope=\"local\")\n                end = ib.allocate(\"int64\", (1,), name=\"end\", scope=\"local\")\n                tmp = ib.allocate(out_dtype, (1,), name=\"end\", scope=\"local\")\n                start[0] = width * tid\n                with ib.if_scope(tvm.tir.all(start[0] < scan_axis_size)):\n                    middle[0] = start[0] + tvm.tir.indexdiv(width, 2)\n                    end[0] = tvm.tir.min(start[0] + width, scan_axis_size)\n                    with ib.if_scope(middle[0] < scan_axis_size):\n                        tmp[0] = output[by * scan_axis_size + middle[0] - 1]\n                        output[by * scan_axis_size + middle[0] - 1] = output[\n                            by * scan_axis_size + end[0] - 1\n                        ]\n                        output[by * scan_axis_size + end[0] - 1] = binop(\n                            output[by * scan_axis_size + end[0] - 1], tmp[0]\n                        )\n    return ib.get()\n\n\ndef get_reduction_from_exclusive_scan(data, ex_scan_output, binop=tvm.tir.generic.add):\n    \"\"\"Return the sum of the last element of data and the exclusive scan output.\n    The is the reduction of data along each row (for 2-D case).\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data of any shape\n\n    ex_scan_output : tvm.te.Tensor\n        The output of exclusive scan on data\n\n    binop: function, optional\n        A binary associative op to use for scan. The function takes two TIR expressions\n        and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute\n        prefix sum.\n\n    Returns\n    -------\n    reduction : tvm.te.Tensor\n        (N-1)-D tensor storing the reduction of each scan axis.\n    \"\"\"\n    ndim = len(data.shape)\n    if ndim == 1:\n        data = expand_dims(data, axis=0)\n        ex_scan_output = expand_dims(ex_scan_output, axis=0)\n\n    def ir(data, data_ex_scan, reduction):\n        batch_size = prod(data.shape[:-1])\n        scan_axis_size = data.shape[-1]\n\n        ib = tvm.tir.ir_builder.create()\n\n        data = ib.buffer_ptr(data)\n        data_ex_scan = ib.buffer_ptr(data_ex_scan)\n        reduction = ib.buffer_ptr(reduction)\n\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(batch_size, max_threads)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            tid = bx * max_threads + tx\n            with ib.if_scope(tid < batch_size):\n                with ib.if_scope(scan_axis_size > 0):\n                    reduction[tid] = binop(\n                        data_ex_scan[tid * scan_axis_size + scan_axis_size - 1],\n                        data[tid * scan_axis_size + scan_axis_size - 1],\n                    )\n                with ib.else_scope():\n                    reduction[tid] = cast(0, reduction.dtype)\n\n        return ib.get()\n\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"valid_indices_buf\", data_alignment=8)\n    ex_scan_output_buf = tvm.tir.decl_buffer(\n        ex_scan_output.shape, ex_scan_output.dtype, \"ex_scan_output_buf\", data_alignment=8\n    )\n\n    reduction = te.extern(\n        [data.shape[:-1]],\n        [data, ex_scan_output],\n        lambda ins, outs: ir(ins[0], ins[1], outs[0]),\n        dtype=[ex_scan_output.dtype],\n        in_buffers=[data_buf, ex_scan_output_buf],\n        name=\"ex_scan_reduction\",\n        tag=\"ex_scan_reduction_gpu\",\n    )\n\n    if ndim == 1:\n        return squeeze(reduction, 0)\n\n    return reduction\n\n\ndef scan_thrust(\n    data, output_dtype, exclusive=True, return_reduction=False, binop=tvm.tir.generic.add\n):\n    \"\"\"Do exclusive or inclusive scan on 1D or multidimensional input, using thrust.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data of any shape. The scan is done over the innermost axis.\n\n    output_dtype: string\n        The dtype of the output scan tensor.\n\n    exclusive: bool, optional\n        Whether or not do exclusive or inclusive scan.\n\n    return_reduction: bool, optional\n        Whether or not return a (N-1)-D tensor storing the reduction of each scan axis.\n        Reductions are computed as part of the upsweep pass, so there is no extra cost.\n        If False, reductions are ignored. It must be False when exclusive is False.\n\n    binop: function, optional\n        A binary associative op to use for scan. Since we need to lookup the corresponding\n        thrust function, arbitrariy callables are not supported. Currently only\n        tvm.tir.generic.add can be passed in.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        A N-D tensor of the same rank N and shape as the input data.\n\n    reduction : tvm.te.Tensor, optional\n        (N-1)-D tensor storing the reduction of each scan axis.\n        Returned if return_reduction is True.\n    \"\"\"\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    output_buf = tvm.tir.decl_buffer(data.shape, output_dtype, \"output_buf\", data_alignment=8)\n\n    output = te.extern(\n        [data.shape],\n        [data],\n        lambda ins, outs: tvm.tir.call_packed(\n            _get_thrust_func_name(binop), ins[0], outs[0], exclusive\n        ),\n        dtype=[output_dtype],\n        in_buffers=[data_buf],\n        out_buffers=[output_buf],\n        name=\"exclusive_scan_thrust\",\n        tag=\"exclusive_scan_thrust_gpu\",\n    )\n\n    if return_reduction:\n        assert exclusive, \"return_reduction should be False for inclusive scan\"\n        reduction = get_reduction_from_exclusive_scan(data, output, binop)\n        return output, reduction\n\n    return output\n\n\ndef exclusive_scan(\n    data,\n    axis=-1,\n    return_reduction=False,\n    output_dtype=None,\n    binop=tvm.tir.generic.add,\n    identity_value=0,\n):\n    \"\"\"Do exclusive scan on 1D or multidimensional input.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data of any shape.\n\n    axis: int, optional\n        The axis to do scan on. By default, scan is done on the innermost axis.\n\n    return_reduction: bool, optional\n        Whether or not return a tensor storing the reduction over each scan axis.\n        If the input rank is N, this tensor is of rank N - 1.\n        Reductions are computed as part of the upsweep pass, so there is no extra cost.\n        If False, reductions are ignored.\n\n    output_dtype: string, optional\n        The dtype of the output scan tensor. If not provided, the dtype of the input is used.\n\n    binop: function, optional\n        A binary associative op to use for scan. The function takes two TIR expressions\n        and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute\n        prefix sum.\n\n    identity_value: int or float\n        A value for the binary operation which provides the identity property. E.g. if * is\n        your operator and i is the identity_value then a * i = a for all a in the domain of\n        your operation.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        A N-D tensor of the same rank N and shape as the input data.\n\n    reduction : tvm.te.Tensor, optional\n        (N-1)-D tensor storing the reduction of each scan axis.\n        Returned if return_reduction is True.\n    \"\"\"\n\n    def do_scan(data, output_dtype):\n        target = tvm.target.Target.current()\n\n        # TODO: add support for a prod_scan\n        if (\n            target\n            and binop == tvm.tir.generic.add\n            and (\n                can_use_thrust(target, \"tvm.contrib.thrust.sum_scan\")\n                or can_use_rocthrust(target, \"tvm.contrib.thrust.sum_scan\")\n            )\n        ):\n            return scan_thrust(\n                data, output_dtype, exclusive=True, return_reduction=return_reduction, binop=binop\n            )\n\n        if ndim == 1:\n            # TIR exclusive scan accepts only 2D or higher-rank inputs.\n            data = expand_dims(data, axis=0)\n\n        data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n        output_buf = tvm.tir.decl_buffer(data.shape, output_dtype, \"output_buf\", data_alignment=8)\n\n        if return_reduction:\n            output, reduction = te.extern(\n                [data.shape, data.shape[:-1]],\n                [data],\n                lambda ins, outs: exclusive_scan_ir(\n                    ins[0], outs[0], outs[1], binop=binop, identity_value=identity_value\n                ),\n                dtype=[output_dtype, output_dtype],\n                in_buffers=[data_buf],\n                name=\"exclusive_scan\",\n                tag=\"exclusive_scan_gpu\",\n            )\n        else:\n            output = te.extern(\n                [data.shape],\n                [data],\n                lambda ins, outs: exclusive_scan_ir(\n                    ins[0], outs[0], binop=binop, identity_value=identity_value\n                ),\n                dtype=[output_dtype],\n                in_buffers=[data_buf],\n                out_buffers=[output_buf],\n                name=\"exclusive_scan\",\n                tag=\"exclusive_scan_gpu\",\n            )\n            reduction = None\n\n        if ndim == 1:\n            output = squeeze(output, 0)\n            if return_reduction:\n                reduction = squeeze(reduction, 0)\n\n        if return_reduction:\n            return output, reduction\n\n        return output\n\n    if output_dtype is None or output_dtype == \"\":\n        output_dtype = data.dtype\n\n    ndim = len(data.shape)\n    if axis < 0:\n        axis += ndim\n\n    # If scan axis is not the innermost one, swap the scan and the innermost axes\n    # Scan is always done on the innermost axis, for performance reason.\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    if return_reduction:\n        output, reduction = do_scan(data, output_dtype)\n    else:\n        output = do_scan(data, output_dtype)\n\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        output = transpose(output, axes)\n\n    if return_reduction:\n        return output, reduction\n\n    return output\n\n\ndef inclusive_scan(data, axis=-1, output_dtype=None, binop=tvm.tir.generic.add, identity_value=0):\n    \"\"\"Do inclusive scan on 1D or multidimensional input.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data of any shape.\n\n    axis: int, optional\n        The axis to do scan on. By default, scan is done on the innermost axis.\n\n    output_dtype: string, optional\n        The dtype of the output scan tensor. If not provided, the dtype of the input is used.\n\n    binop: function, optional\n        A binary associative op to use for scan. The function takes two TIR expressions\n        and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute\n        prefix sum.\n\n    identity_value: int or float\n        A value for the binary operation which provides the identity property. E.g. if * is\n        your operator and i is the identity_value then a * i = a for all a in the domain of\n        your operation.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        A N-D tensor of the same rank N as the input data.\n    \"\"\"\n    ex_scan = exclusive_scan(\n        data, axis, output_dtype=output_dtype, binop=binop, identity_value=identity_value\n    )\n\n    if output_dtype is not None and data.dtype != output_dtype and output_dtype != \"\":\n        data = cast(data, output_dtype)\n\n    return binop(data, ex_scan)\n\n\ndef schedule_scan(outs):\n    \"\"\"Schedule for scan operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of scan\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        if tag.is_injective(op.tag):\n            schedule_injective_from_existing(s, op.output(0))\n        for tensor in op.input_tensors:\n            if tensor.op.input_tensors and tensor.op not in scheduled_ops:\n                traverse(tensor.op)\n        scheduled_ops.append(op)\n\n    for out in outs:\n        traverse(out.op)\n    return s\n\n\ndef scanop(\n    data: tvm.te.Tensor,\n    binop: Callable[[\"tvm.Expr\", \"tvm.Expr\"], \"tvm.Expr\"],\n    identity_value: Union[float, int],\n    axis: Optional[int] = None,\n    dtype: Optional[str] = None,\n    exclusive: Optional[bool] = None,\n) -> tvm.te.Tensor:\n    \"\"\"Cumulative binary operator (scan) with similar axis behavior as np.cumsum and np.cumprod.\n\n    See cumprod and cumsum for an example of use.\n\n    E.g. if * is your binary operator and the input tensor is [1, 2, 3, 4] the output may be\n    [1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4]\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    binop: Callable (tvm.Expr, tvm.Expr) -> tvm.Expr\n        A binary operator which should be associative and commutative. E.g. if * is your\n        operator then a * (b * c) = (a * b) * c and a * b = b * a\n\n    identity_value: int or float\n        A value for the binary operation which provides the identity property. E.g. if * is\n        your operator and i is the identity_value then a * i = a for all a in the domain of\n        your operation.\n\n    axis : int, optional\n        Axis along which the operation is computed. The default (None) is to compute\n        the cumulative operation over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are computed.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If true will return exclusive cumulative operation in which the first element is not\n        included. In other terms, if true, the j-th output element would be\n        the cumulative operation of the first (j-1) elements. Otherwise, it would be the\n        cumulative operation of the first j elements.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    if axis is None:\n        axis = 0\n        data = reshape(data, (prod(data.shape),))\n    axis = get_const_int(axis)\n    if exclusive is not None and exclusive:\n        return exclusive_scan(\n            data, axis, output_dtype=dtype, binop=binop, identity_value=identity_value\n        )\n    return inclusive_scan(\n        data, axis, output_dtype=dtype, binop=binop, identity_value=identity_value\n    )\n\n\ndef cumsum(\n    data: tvm.te.Tensor,\n    axis: Optional[int] = None,\n    dtype: Optional[int] = None,\n    exclusive: Optional[bool] = None,\n) -> tvm.te.Tensor:\n    \"\"\"Numpy style cumsum op. Return the cumulative sum of the elements along a given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative sum is computed. The default (None) is to compute\n        the cumsum over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are summed.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If true will return exclusive sum in which the first element is not\n        included. In other terms, if true, the j-th output element would be\n        the sum of the first (j-1) elements. Otherwise, it would be the sum of\n        the first j elements.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    return scanop(\n        data=data,\n        binop=tvm.tir.generic.add,\n        identity_value=0,\n        axis=axis,\n        dtype=dtype,\n        exclusive=exclusive,\n    )\n\n\ndef cumprod(\n    data: tvm.te.Tensor,\n    axis: Optional[int] = None,\n    dtype: Optional[int] = None,\n    exclusive: Optional[bool] = None,\n):\n    \"\"\"Numpy style cumprod op. Return the cumulative product of the elements along a given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative product is computed. The default (None) is to compute\n        the cumproduct over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are multiplied.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If True, will return exclusive product in which the first element is not\n        included. In other terms, if True, the j-th output element would be\n        the product of the first (j-1) elements. Otherwise, it would be the product of\n        the first j elements.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    return scanop(\n        data=data,\n        binop=tvm.tir.generic.multiply,\n        identity_value=1,\n        axis=axis,\n        dtype=dtype,\n        exclusive=exclusive,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/scatter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, too-many-statements, singleton-comparison, unused-argument\n\"\"\"Scatter operator \"\"\"\nimport tvm\nfrom tvm import te, autotvm\nfrom ..scatter import _verify_scatter_nd_inputs\nfrom ..generic import schedule_extern\nfrom .nms import atomic_add\nfrom .sort import stable_sort_by_key_thrust\nfrom ..utils import prod, ceil_div\n\n\ndef _memcpy_ir(ib, out_ptr, data_ptr, shape):\n    fused = prod(shape)\n    with ib.new_scope():\n        num_thread = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        num_blocks = ceil_div(fused, num_thread)\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", num_blocks)\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", num_thread)\n        tid = bx * num_thread + tx\n\n        with ib.if_scope(tid < fused):\n            out_ptr[tid] = data_ptr[tid]\n\n\ndef gen_ir_1d(data, indices, updates, axis, out, update_func):\n    \"\"\"Generate scatter ir for 1d inputs\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices : tir.Tensor\n        The index locations to update.\n\n    updates : tir.Tensor\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    out : tir.Tensor\n        The output tensor.\n\n    update_func: function\n        The function to be applied to a destination and the corresponding update.\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    assert axis == 0\n    n = data.shape[0]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n\n    _memcpy_ir(ib, out_ptr, data_ptr, data.shape)\n\n    indices_ptr = ib.buffer_ptr(indices)\n    updates_ptr = ib.buffer_ptr(updates)\n\n    ni = indices.shape[0]\n\n    with ib.new_scope():\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", 1)\n        with ib.for_range(0, ni, name=\"i\") as i:\n            index = indices_ptr[i]\n            with ib.if_scope(index < 0):\n                update_func(out_ptr, index + n, updates_ptr[i])\n            with ib.else_scope():\n                update_func(out_ptr, index, updates_ptr[i])\n\n    return ib.get()\n\n\ndef gen_ir_2d(data, indices, updates, axis, out, update_func):\n    \"\"\"Generate scatter ir for 2d inputs\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices : tir.Tensor\n        The index locations to update.\n\n    updates : tir.Tensor\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    out : tir.Tensor\n        The output tensor.\n\n    update_func: function\n        The function to be applied to a destination and the corresponding update\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    n = data.shape[0]\n    c = data.shape[1]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n\n    _memcpy_ir(ib, out_ptr, data_ptr, data.shape)\n\n    indices_ptr = ib.buffer_ptr(indices)\n    updates_ptr = ib.buffer_ptr(updates)\n\n    ni = indices.shape[0]\n    ci = indices.shape[1]\n\n    if axis == 0:\n        with ib.new_scope():\n            j = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            with ib.for_range(0, ni, name=\"i\") as i:\n                idx = i * ci + j\n                index = indices_ptr[idx]\n                with ib.if_scope(index < 0):\n                    update_func(out_ptr, (index + n) * c + j, updates_ptr[idx])\n                with ib.else_scope():\n                    update_func(out_ptr, index * c + j, updates_ptr[idx])\n    else:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            with ib.for_range(0, ci, name=\"j\") as j:\n                idx = i * ci + j\n                index = indices_ptr[idx]\n                with ib.if_scope(index < 0):\n                    update_func(out_ptr, i * c + (index + c), updates_ptr[idx])\n                with ib.else_scope():\n                    update_func(out_ptr, i * c + index, updates_ptr[idx])\n    return ib.get()\n\n\ndef gen_ir_3d(data, indices, updates, axis, out, update_func):\n    \"\"\"Generate scatter ir for 3d inputs\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices : tir.Tensor\n        The index locations to update.\n\n    updates : tir.Tensor\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    out : tir.Tensor\n        The output tensor.\n\n    update_func: function\n        The function to be applied to a destination and the corresponding update\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    warp_size = tvm.target.Target.current(False).thread_warp_size\n\n    n = data.shape[0]\n    c = data.shape[1]\n    h = data.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n\n    _memcpy_ir(ib, out_ptr, data_ptr, data.shape)\n\n    indices_ptr = ib.buffer_ptr(indices)\n    updates_ptr = ib.buffer_ptr(updates)\n    ni = indices.shape[0]\n    ci = indices.shape[1]\n    hi = indices.shape[2]\n\n    if axis == 0:\n        with ib.new_scope():\n            j = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", warp_size)\n            with ib.for_range(0, ni, name=\"i\") as i:\n                with ib.for_range(0, ceil_div(hi, warp_size), name=\"k\") as k_:\n                    k = k_ * warp_size + tx\n                    with ib.if_scope(k < hi):\n                        idx = (i * ci + j) * hi + k\n                        index = indices_ptr[idx]\n                        with ib.if_scope(index < 0):\n                            update_func(out_ptr, ((index + n) * c + j) * h + k, updates_ptr[idx])\n                        with ib.else_scope():\n                            update_func(out_ptr, (index * c + j) * h + k, updates_ptr[idx])\n    elif axis == 1:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", warp_size)\n            with ib.for_range(0, ci, name=\"j\") as j:\n                with ib.for_range(0, ceil_div(hi, warp_size), name=\"k\") as k_:\n                    k = k_ * warp_size + tx\n                    with ib.if_scope(k < hi):\n                        idx = (i * ci + j) * hi + k\n                        index = indices_ptr[idx]\n                        with ib.if_scope(index < 0):\n                            update_func(out_ptr, (i * c + (index + c)) * h + k, updates_ptr[idx])\n                        with ib.else_scope():\n                            update_func(out_ptr, (i * c + index) * h + k, updates_ptr[idx])\n    else:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            j = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            with ib.for_range(0, hi, name=\"k\") as k:\n                idx = (i * ci + j) * hi + k\n                index = indices_ptr[idx]\n                with ib.if_scope(index < 0):\n                    update_func(out_ptr, (i * c + j) * h + (index + h), updates_ptr[idx])\n                with ib.else_scope():\n                    update_func(out_ptr, (i * c + j) * h + index, updates_ptr[idx])\n    return ib.get()\n\n\ndef gen_ir_4d(data, indices, updates, axis, out, update_func):\n    \"\"\"Generate scatter ir for 4d inputs\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices : tir.Tensor\n        The index locations to update.\n\n    updates : tir.Tensor\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    out : tir.Tensor\n        The output tensor.\n\n    update_func: function\n        The function to be applied to a destination and the corresponding update\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    warp_size = tvm.target.Target.current(False).thread_warp_size\n\n    n = data.shape[0]\n    c = data.shape[1]\n    h = data.shape[2]\n    w = data.shape[3]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n    _memcpy_ir(ib, out_ptr, data_ptr, data.shape)\n\n    indices_ptr = ib.buffer_ptr(indices)\n    updates_ptr = ib.buffer_ptr(updates)\n    ni = indices.shape[0]\n    ci = indices.shape[1]\n    hi = indices.shape[2]\n    wi = indices.shape[3]\n\n    if axis == 0:\n        with ib.new_scope():\n            j = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            k = te.thread_axis(\"blockIdx.z\")\n            ib.scope_attr(k, \"thread_extent\", hi)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", warp_size)\n            with ib.for_range(0, ni, name=\"i\") as i:\n                with ib.for_range(0, ceil_div(wi, warp_size), name=\"l\") as l_:\n                    l = l_ * warp_size + tx\n                    with ib.if_scope(l < wi):\n                        idx = ((i * ci + j) * hi + k) * wi + l\n                        index = indices_ptr[idx]\n                        with ib.if_scope(index < 0):\n                            update_func(\n                                out_ptr, (((index + n) * c + j) * h + k) * w + l, updates_ptr[idx]\n                            )\n                        with ib.else_scope():\n                            update_func(\n                                out_ptr, ((index * c + j) * h + k) * w + l, updates_ptr[idx]\n                            )\n    elif axis == 1:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            k = te.thread_axis(\"blockIdx.z\")\n            ib.scope_attr(k, \"thread_extent\", hi)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", warp_size)\n            with ib.for_range(0, ci, name=\"j\") as j:\n                with ib.for_range(0, ceil_div(wi, warp_size), name=\"l\") as l_:\n                    l = l_ * warp_size + tx\n                    with ib.if_scope(l < wi):\n                        idx = ((i * ci + j) * hi + k) * wi + l\n                        index = indices_ptr[idx]\n                        with ib.if_scope(index < 0):\n                            update_func(\n                                out_ptr, ((i * c + (index + c)) * h + k) * w + l, updates_ptr[idx]\n                            )\n                        with ib.else_scope():\n                            update_func(\n                                out_ptr, ((i * c + index) * h + k) * w + l, updates_ptr[idx]\n                            )\n    elif axis == 2:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            j = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", warp_size)\n            with ib.for_range(0, hi, name=\"k\") as k:\n                with ib.for_range(0, ceil_div(wi, warp_size), name=\"l\") as l_:\n                    l = l_ * warp_size + tx\n                    with ib.if_scope(l < wi):\n                        idx = ((i * ci + j) * hi + k) * wi + l\n                        index = indices_ptr[idx]\n                        with ib.if_scope(index < 0):\n                            update_func(\n                                out_ptr, ((i * c + j) * h + (index + h)) * w + l, updates_ptr[idx]\n                            )\n                        with ib.else_scope():\n                            update_func(\n                                out_ptr, ((i * c + j) * h + index) * w + l, updates_ptr[idx]\n                            )\n    else:\n        with ib.new_scope():\n            i = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(i, \"thread_extent\", ni)\n            j = te.thread_axis(\"blockIdx.y\")\n            ib.scope_attr(j, \"thread_extent\", ci)\n            k = te.thread_axis(\"blockIdx.z\")\n            ib.scope_attr(k, \"thread_extent\", hi)\n            with ib.for_range(0, wi, name=\"l\") as l:\n                idx = ((i * ci + j) * hi + k) * wi + l\n                index = indices_ptr[idx]\n                with ib.if_scope(index < 0):\n                    update_func(out_ptr, ((i * c + j) * h + k) * w + (index + w), updates_ptr[idx])\n                with ib.else_scope():\n                    update_func(out_ptr, ((i * c + j) * h + k) * w + index, updates_ptr[idx])\n    return ib.get()\n\n\n@autotvm.register_topi_compute(\"scatter.cuda\")\ndef scatter(cfg, data, indices, updates, axis=0):\n    \"\"\"Update data at positions defined by indices with values in updates\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    if axis < 0:\n        axis += len(data.shape)\n    assert axis >= 0\n    assert axis < len(data.shape)\n\n    rank = len(data.shape)\n    assert 1 <= rank <= 4, \"scatter only supports 1-4 dimensions\"\n\n    ir_funcs = {\n        1: gen_ir_1d,\n        2: gen_ir_2d,\n        3: gen_ir_3d,\n        4: gen_ir_4d,\n    }\n\n    def update_func(dst_ptr, dst_index, update):\n        dst_ptr[dst_index] = update\n\n    out_shape = data.shape\n    out_buf = tvm.tir.decl_buffer(out_shape, data.dtype, \"out_buf\")\n\n    cfg.add_flop(1)  # A dummy value to satisfy AutoTVM\n\n    out = te.extern(\n        [out_shape],\n        [data, indices, updates],\n        lambda ins, outs: ir_funcs[rank](ins[0], ins[1], ins[2], axis, outs[0], update_func),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_gpu\",\n        tag=\"scatter_gpu\",\n    )\n\n    return out\n\n\n@autotvm.register_topi_schedule(\"scatter.cuda\")\ndef schedule_scatter(_, outs):\n    return schedule_extern(outs)\n\n\ndef gen_scatter_1d_thrust(data, indices_sorted, updates_sorted, out):\n    \"\"\"Generate scatter ir for 1d inputs, using a sorting based approach.\n    By sorting indices and comparing neighboring two indices, we can tell which\n    of elements in the indices tensor can scatter its update value into the output.\n    Sorting of indices, and sorting of updates with respect to indices, can be done\n    at the same time by thrust's sort_by_key function. It is important that sorting\n    be done in a \"stable\" way via stable_sort, to guarantee deterministic output.\n    Negative indices are assumed to have been converted to corresponding positive\n    indices.\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices_sorted : tir.Tensor\n        The sorted index locations to update.\n\n    updates : tir.Tensor\n        The values to update, sorted by indices.\n\n    out : tir.Tensor\n        The output tensor.\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    n = data.shape[0]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n\n    with ib.new_scope():\n        nthread_bx = ceil_div(n, nthread_tx)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * nthread_tx + tx\n        with ib.if_scope(tid < n):\n            out_ptr[tid] = data_ptr[tid]\n\n    indices_ptr = ib.buffer_ptr(indices_sorted)\n    updates_ptr = ib.buffer_ptr(updates_sorted)\n\n    ni = indices_sorted.shape[0]\n\n    with ib.new_scope():\n        nthread_bx = ceil_div(ni, nthread_tx)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * nthread_tx + tx\n\n        with ib.if_scope(tid == ni - 1):\n            # The last element can always update.\n            index = indices_ptr[tid]\n            update = updates_ptr[tid]\n            out_ptr[index] = update\n\n        with ib.else_scope():\n            with ib.if_scope(tid < ni - 1):\n                index = indices_ptr[tid]\n                index_next = indices_ptr[tid + 1]\n\n                # If the next neighbor in the sorted list of indices has a different index,\n                # that means thread tid is the last one to have this index.\n                # This thread can update the output.\n                with ib.if_scope(index != index_next):\n                    update = updates_ptr[tid]\n                    out_ptr[index] = update\n\n    return ib.get()\n\n\n@autotvm.register_topi_compute(\"scatter_via_sort.cuda\")\ndef scatter_via_sort(cfg, data, indices, updates, axis=0):\n    \"\"\"Update data at positions defined by indices with values in updates\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    if axis < 0:\n        axis += len(data.shape)\n    assert axis == 0 and len(data.shape) == 1, \"sorting based scatter only supported for 1d input\"\n\n    cfg.add_flop(1)  # A dummy value to satisfy AutoTVM\n\n    out_shape = data.shape\n    out_buf = tvm.tir.decl_buffer(out_shape, data.dtype, \"out_buf\")\n\n    indices_sorted, updates_sorted = stable_sort_by_key_thrust(indices, updates, for_scatter=True)\n\n    out = te.extern(\n        [out_shape],\n        [data, indices_sorted, updates_sorted],\n        lambda ins, outs: gen_scatter_1d_thrust(ins[0], ins[1], ins[2], outs[0]),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_via_sort_gpu\",\n        tag=\"scatter_via_sort_gpu\",\n    )\n\n    return out\n\n\n@autotvm.register_topi_schedule(\"scatter_via_sort.cuda\")\ndef schedule_scatter_via_sort(_, outs):\n    return schedule_extern(outs)\n\n\ndef gen_scatter_add_1d_atomic(data, indices, updates, axis, out, _):\n    \"\"\"Generate scatter add ir for 1d inputs, using atomic_add instruction\n\n    Parameters\n    ----------\n    data : tir.Tensor\n        The input data to the operator.\n\n    indices : tir.Tensor\n        The index locations to update.\n\n    updates : tir.Tensor\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    out : tir.Tensor\n        The output tensor.\n\n    Returns\n    -------\n    ret : tir\n        The computational ir.\n    \"\"\"\n    assert axis == 0\n    n = data.shape[0]\n\n    ib = tvm.tir.ir_builder.create()\n\n    out_ptr = ib.buffer_ptr(out)\n    data_ptr = ib.buffer_ptr(data)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n\n    with ib.new_scope():\n        nthread_bx = ceil_div(n, nthread_tx)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * nthread_tx + tx\n        with ib.if_scope(tid < n):\n            out_ptr[tid] = data_ptr[tid]\n\n    indices_ptr = ib.buffer_ptr(indices)\n    updates_ptr = ib.buffer_ptr(updates)\n\n    ni = indices.shape[0]\n\n    atomic_add_return = ib.allocate(updates.dtype, (1,), name=\"atomic_add_return\", scope=\"local\")\n\n    with ib.new_scope():\n        nthread_bx = ceil_div(ni, nthread_tx)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * nthread_tx + tx\n\n        with ib.if_scope(tid < ni):\n            index = indices_ptr[tid]\n            with ib.if_scope(index < 0):\n                atomic_add_return[0] = atomic_add(\n                    tvm.tir.call_intrin(\"handle\", \"tir.address_of\", out_ptr[index + n]),\n                    updates_ptr[tid],\n                )\n            with ib.else_scope():\n                atomic_add_return[0] = atomic_add(\n                    tvm.tir.call_intrin(\"handle\", \"tir.address_of\", out_ptr[index]),\n                    updates_ptr[tid],\n                )\n\n    return ib.get()\n\n\ndef scatter_add(data, indices, updates, axis=0):\n    \"\"\"Update data by adding values in updates at positions defined by indices\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to be added.\n\n    axis : int\n        The axis to scatter on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    if axis < 0:\n        axis += len(data.shape)\n    assert axis >= 0\n    assert axis < len(data.shape)\n\n    rank = len(data.shape)\n    assert 1 <= rank <= 4, \"scatter_add only supports 1-4 dimensions\"\n\n    ir_funcs = {\n        1: gen_scatter_add_1d_atomic,\n        2: gen_ir_2d,\n        3: gen_ir_3d,\n        4: gen_ir_4d,\n    }\n\n    def update_func(dst_ptr, dst_index, update):\n        dst_ptr[dst_index] += update\n\n    out_shape = data.shape\n    out_buf = tvm.tir.decl_buffer(out_shape, data.dtype, \"out_buf\")\n    out = te.extern(\n        [out_shape],\n        [data, indices, updates],\n        lambda ins, outs: ir_funcs[rank](ins[0], ins[1], ins[2], axis, outs[0], update_func),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_add_gpu\",\n        tag=\"scatter_add_gpu\",\n    )\n\n    return out\n\n\ndef scatter_nd(data, indices, updates, mode):\n    \"\"\"Scatter elements from a n-dimension array.\n\n    Given updates with shape (Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1}), indices with shape\n    (M, Y_0, ..., Y_{K-1}), and output copied from data with shape (X_0, X_1, ..., X_{N-1}),\n    scatter_nd computes\n\n    .. code-block::\n\n        output[indices[0, y_0, ..., y_{K-1}],\n               ...,\n               indices[M-1, y_0, ..., y_{K-1}],\n               x_M,\n               ...,\n               x_{N-1}\n              ] = f(output[...], updates[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}])\n\n    where the update function f is determinted by the mode.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The source array.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    updates : tvm.te.Tensor\n        The updates to apply at the Indices\n\n    mode : string\n        The update mode for the algorithm, either \"update\" or \"add\"\n        If update, the update values will replace the input data\n        If add, the update values will be added to the input data\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    _verify_scatter_nd_inputs(data, indices, updates)\n\n    def gen_ir(data_ptr, indices_ptr, updates_ptr, out_ptr):\n        ib = tvm.tir.ir_builder.create()\n\n        data = ib.buffer_ptr(data_ptr)\n        indices = ib.buffer_ptr(indices_ptr)\n        updates = ib.buffer_ptr(updates_ptr)\n        out = ib.buffer_ptr(out_ptr)\n\n        atomic_add_return = ib.allocate(\n            updates.dtype, (1,), name=\"atomic_add_return\", scope=\"local\"\n        )\n\n        fused_indices_dimension = 1\n        for i in indices_ptr.shape[1:]:\n            fused_indices_dimension *= i\n\n        fused_updates_dimension = 1\n        for i in updates_ptr.shape[len(indices_ptr.shape) - 1 :]:\n            fused_updates_dimension *= i\n\n        fused_shape = 1\n        for i in data_ptr.shape:\n            fused_shape *= i\n\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        tdim = min(max_threads, fused_updates_dimension)\n\n        with ib.new_scope():\n            bdim = ceil_div(fused_shape, tdim)\n            bx = te.thread_axis(\"blockIdx.x\")\n            tx = te.thread_axis(\"threadIdx.x\")\n            ib.scope_attr(bx, \"thread_extent\", bdim)\n            ib.scope_attr(tx, \"thread_extent\", tdim)\n\n            index = bx * tdim + tx\n            with ib.if_scope(index < fused_shape):\n                out[index] = data[index]\n\n        # For better performance, we introduce blockIdx.y to implement for-loops\n        # within one thread.\n        # The code is parallel over the scattered indices, so we use atomic_add\n        # to guarantee correctness when mode==\"add\"\n\n        # For now, atomic is not supported by target \"vulkan\", \"metal\", or \"cuda\" with \"int64\"\n        # So we fallback to normal algorithm, using \"+=\" rather than atomic_add\n\n        # TODO (CaptainDuke):\n        # Since multiple threads compete for the same write index, which leads to\n        # non-determinstic output for update mode. We could add a new attribute,\n        # \"allow_non_deterministic\", which can be conditionally set to True by\n        # each frontend when non-determinsm is allowed.\n        cur_target_kind = str(tvm.target.Target.current(allow_none=False).kind)\n        with ib.new_scope():\n            if (\n                mode == \"add\"\n                and cur_target_kind not in [\"vulkan\", \"metal\"]\n                and updates.dtype in [\"int32\", \"float32\"]\n            ):\n                bdim_x = fused_indices_dimension\n                bdim_y = ceil_div(fused_updates_dimension, tdim)\n                # In case of large input sizes, fused_indices_dimension might be too large.\n                # So we use blockIdx.x because holds larger scales.\n                bx = te.thread_axis(\"blockIdx.x\")\n                by = te.thread_axis(\"blockIdx.y\")\n                tx = te.thread_axis(\"threadIdx.x\")\n                ib.scope_attr(bx, \"thread_extent\", bdim_x)\n                ib.scope_attr(by, \"thread_extent\", bdim_y)\n                ib.scope_attr(tx, \"thread_extent\", tdim)\n\n                j = by * tdim + tx\n                with ib.if_scope(j < fused_updates_dimension):\n                    offset = fused_updates_dimension\n                    index = j  # This is x_M, .. x_{N-1} part of the index into out.\n                    # Build up the indices[0, y_0, .. y_{K-1}], .. indices[M-1, y_0, .. y_{K-1}]\n                    # part of the index into out.\n                    up_index = bx * fused_updates_dimension + j\n                    for l in reversed(range(indices_ptr.shape[0].value)):\n                        # indices[bx * l * fused_indices_dimension] = indices[l, y_0, ... y_{k-1}]\n                        index += offset * indices[bx + l * fused_indices_dimension]\n                        offset *= data_ptr.shape[l]\n                    atomic_add_return[0] = atomic_add(\n                        tvm.tir.call_intrin(\"handle\", \"tir.address_of\", out[index]),\n                        updates[up_index],\n                    )\n            else:\n                bdim_x = ceil_div(fused_updates_dimension, tdim)\n                bx = te.thread_axis(\"blockIdx.x\")\n                tx = te.thread_axis(\"threadIdx.x\")\n                ib.scope_attr(bx, \"thread_extent\", bdim_x)\n                ib.scope_attr(tx, \"thread_extent\", tdim)\n                with ib.for_range(0, fused_indices_dimension) as i:\n                    j = bx * tdim + tx\n                    with ib.if_scope(j < fused_updates_dimension):\n                        offset = fused_updates_dimension\n                        index = j  # This is x_M, .. x_{N-1} part of the index into out.\n                        # Build up the\n                        # indices[0, y_0, .. y_{K-1}], ... indices[M-1, y_0, .. y_{K-1}]\n                        # part of the index into out.\n                        for l in reversed(range(indices_ptr.shape[0].value)):\n                            # indices[i * l * fused_indices_dimension] = indices[l, y_0,\n                            #                                                   ... y_{k-1}]\n                            index += offset * indices[i + l * fused_indices_dimension]\n                            offset *= data_ptr.shape[l]\n                        if mode == \"update\":\n                            out[index] = updates[i * fused_updates_dimension + j]\n                        elif mode == \"add\":\n                            out[index] += updates[i * fused_updates_dimension + j]\n                        else:\n                            raise NotImplementedError(\"scatter_nd mode not in [update, add]:\", mode)\n\n        return ib.get()\n\n    out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"out_buf\")\n    return te.extern(\n        [data.shape],\n        [data, indices, updates],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0]),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_nd_cuda\",\n        tag=\"scatter_nd_cuda\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/searchsorted.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"searchsorted operator for GPU\"\"\"\nimport tvm\nfrom tvm import te\nfrom .. import utils\nfrom ..searchsorted import binary_search\n\n\ndef searchsorted(sorted_sequence, values, right, out_dtype=\"int64\"):\n    \"\"\"Find indices where elements should be inserted to maintain order.\n       If `sorted_sequence` is N-dimensional, the innermost dimension of\n       `values` are searched in the corresponding dimension of `sorted_sequence`.\n\n    Parameters\n    ----------\n    sorted_sequence : te.Tensor\n        N-D or 1-D Tensor, containing monotonically increasing sequence\n        on the innermost dimension.\n\n    values : te.Tensor\n        N-D Tensor containing the search values. When `sorted_sequence` is 1-D,\n        the shape of `values` can be arbitrary. Otherwise, ranks of `sorted_sequence`\n        and `values` must be the same, and outer N-1 axes must have the same size.\n\n    right : bool, optional\n        Controls which index is returned if a value lands exactly on one of sorted values. If\n        False, the index of the first suitable location found is given. If true, return the\n        last such index. If there is no suitable index, return either 0 or N (where N is the\n        size of the innermost dimension).\n\n    dtype : string, optional\n        The data type of the output indices.\n\n    Returns\n    -------\n    indices : te.Tensor\n        Tensor with same shape as values, representing the indices of\n        elements of `values` if they are inserted in `sorted_sequence`.\n    \"\"\"\n\n    def ir(sorted_sequence, values, indices):\n        ib = tvm.tir.ir_builder.create()\n        sorted_sequence_shape = sorted_sequence.shape\n        values_shape = values.shape\n        num_search = utils.prod(values_shape)\n        search_range = sorted_sequence_shape[-1]\n\n        sorted_sequence = ib.buffer_ptr(sorted_sequence)\n        values = ib.buffer_ptr(values)\n        indices = ib.buffer_ptr(indices)\n\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(\n            bx, \"thread_extent\", tvm.tir.indexdiv(num_search + max_threads - 1, max_threads)\n        )\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        tid = bx * max_threads + tx\n\n        with ib.if_scope(tid < num_search):\n            if len(sorted_sequence_shape) == 1:\n                sequence_offset = 0\n            else:\n                sequence_id = tid // values_shape[-1]\n                sequence_offset = sequence_id * search_range\n\n            indices[tid] = binary_search(\n                ib,\n                sequence_offset,\n                search_range,\n                sorted_sequence,\n                values[tid],\n                right,\n                out_dtype,\n            )\n\n        return ib.get()\n\n    return te.extern(\n        values.shape,\n        [sorted_sequence, values],\n        lambda ins, outs: ir(ins[0], ins[1], outs[0]),\n        name=\"searchsorted\",\n        dtype=out_dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/softmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, trailing-whitespace\n\"\"\"Schedule for softmax operator\"\"\"\nfrom tvm.target import Target\nfrom tvm import te\nfrom tvm.contrib import cudnn\nfrom .. import generic\nfrom .injective import schedule_injective_from_existing\nfrom ..utils import get_const_int, traverse_inline\n\n\ndef _schedule_softmax(softmax_op, s, outs, tgt):\n    op_tag = softmax_op.tag\n    axis = get_const_int(softmax_op.attrs[\"axis\"])  # reduce axis\n    if op_tag == \"softmax_output\":\n        expsum = softmax_op.input_tensors[1]\n        exp = softmax_op.input_tensors[0]\n        max_elem = s[exp].op.input_tensors[1]\n        delta = None\n    elif op_tag == \"fast_softmax_output\":\n        expsum = softmax_op.input_tensors[1]\n        exp = softmax_op.input_tensors[0]\n        delta = s[exp].op.input_tensors[0]\n        max_elem = s[delta].op.input_tensors[1]\n    elif op_tag == \"log_softmax_output\":\n        exp = None\n        delta = None\n        max_elem = softmax_op.input_tensors[1]\n        expsum = softmax_op.input_tensors[2]\n    else:\n        raise ValueError(\n            \"Tag is expected to be softmax_output or log_softmax_output. \\\n                         Got {0}\".format(\n                op_tag\n            )\n        )\n\n    # The nvptx and rocm backends only supports 32-bits warp shuffle\n    # instructions.\n    #\n    # TODO(tvm-team) Fix nvptx codegen or deprecate nvptx backend.\n    def sched_warp_softmax():\n        if tgt.kind.name in [\"nvptx\", \"rocm\"]:\n            dtype = softmax_op.output(0).dtype\n            return dtype in [\"float32\", \"int32\"]\n        if tgt.kind.name != \"cuda\":\n            # this is used as the gpu schedule for other arches which\n            # may not have warp reductions\n            return False\n        return True\n\n    if len(outs[0].shape) != 2:\n        ops = [max_elem.op, expsum.op, softmax_op]\n        if delta is not None:\n            ops.append(delta.op)\n        if exp is not None:\n            ops.append(exp.op)\n        if softmax_op != outs[0].op:\n            ops.append(outs[0].op)\n\n        for op in ops:\n            s = schedule_injective_from_existing(s, op.output(0))\n\n    elif sched_warp_softmax():\n        # A warp of 32 threads performs a row reduction.\n        num_thread = tgt.thread_warp_size\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n\n        # (4) softmax\n        output = outs[0]\n        xo, xi = s[output].split(output.op.axis[axis], nparts=num_thread)\n        xio, xii = s[output].split(xi, factor=4)\n        s[output].vectorize(xii)\n        s[output].bind(xo, thread_x)\n        s[output].bind(output.op.axis[axis ^ 1], block_x)\n        s[output].reorder(output.op.axis[axis ^ 1], xo, xio, xii)\n\n        if softmax_op != outs[0].op:\n            s[softmax_op].compute_at(s[output], xio)\n            s[softmax_op].vectorize(softmax_op.axis[axis])  # vec_len == 4\n\n        # (3) expsum\n        k = expsum.op.reduce_axis[0]\n        ko, _ = s[expsum].split(k, nparts=num_thread)\n        s[expsum].bind(ko, thread_x)\n        s[expsum].compute_at(s[output], xo)\n\n        # (2) exp\n        if delta is not None:\n            s[exp].compute_inline()\n            s[delta].compute_inline()\n        elif exp is not None:\n            xo, xi = s[exp].split(exp.op.axis[axis], nparts=num_thread)\n            _, xii = s[exp].split(xi, factor=4)\n            s[exp].vectorize(xii)\n            s[exp].bind(xo, thread_x)\n            s[exp].compute_at(s[expsum], expsum.op.axis[0])\n            s[exp].compute_at(s[output], output.op.axis[axis ^ 1])\n            s[exp].set_scope(\"warp\")\n\n        # (1) max_elem\n        k = max_elem.op.reduce_axis[0]\n        ko, _ = s[max_elem].split(k, nparts=num_thread)\n        s[max_elem].bind(ko, thread_x)\n        if exp is not None and delta is None:\n            s[max_elem].compute_at(s[exp], xo)\n        else:\n            s[max_elem].bind(ko, thread_x)\n            s[max_elem].bind(max_elem.op.axis[0], block_x)\n\n    else:\n        num_thread = 64\n        block_x = te.thread_axis(\"blockIdx.x\")\n        thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n\n        if delta is not None:\n            s[exp].compute_inline()\n            s[delta].compute_inline()\n        elif exp is not None:\n            s[exp].bind(exp.op.axis[axis ^ 1], block_x)\n\n        s[max_elem].bind(max_elem.op.axis[0], block_x)\n        k = expsum.op.reduce_axis[0]\n        ko, ki = s[expsum].split(k, factor=num_thread)\n        EF = s.rfactor(expsum, ki)\n        s[expsum].bind(s[expsum].op.axis[0], block_x)\n        s[expsum].bind(s[expsum].op.reduce_axis[0], thread_x)\n        s[EF].compute_at(s[expsum], s[expsum].op.reduce_axis[0])\n        s[expsum].set_store_predicate(thread_x.var.equal(0))\n\n        output = outs[0]\n        tx, xi = s[output].split(output.op.axis[axis], nparts=num_thread)\n        s[output].bind(output.op.axis[axis ^ 1], block_x)\n        s[output].bind(tx, thread_x)\n        s[output].reorder(output.op.axis[axis ^ 1], tx, xi)\n\n        if softmax_op != outs[0].op:\n            s[softmax_op].compute_at(s[output], tx)\n\n\ndef schedule_softmax(outs):\n    \"\"\"Schedule for softmax op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of softmax in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tgt = Target.current(allow_none=False)\n\n    def _callback(op):\n        if \"softmax\" in op.tag:\n            _schedule_softmax(op, s, outs, tgt)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef softmax_cudnn(x, axis=-1):\n    \"\"\"Perform softmax on the data using cudnn\"\"\"\n    return cudnn.softmax(x, axis)\n\n\ndef schedule_softmax_cudnn(outs):\n    \"\"\"Schedule for softmax cudnn op\"\"\"\n    return generic.schedule_extern(outs)\n\n\ndef log_softmax_cudnn(x, axis=-1):\n    \"\"\"Perform log_softmax on the data using cudnn\"\"\"\n    return cudnn.log_softmax(x, axis)\n\n\ndef schedule_log_softmax_cudnn(outs):\n    \"\"\"Schedule for log_softmax cudnn op\"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/sort.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, too-many-statements, singleton-comparison, unused-argument, no-else-return\n\"\"\"Sort related operators \"\"\"\nimport tvm\nfrom tvm import te\n\nfrom .injective import schedule_injective_from_existing\nfrom ..transform import strided_slice, transpose\nfrom .. import tag\nfrom ..utils import ceil_div, swap\nfrom ..math import cast, ceil_log2\n\n\ndef _schedule_sort(outs):\n    \"\"\"Schedule for argsort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of argsort\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        if tag.is_injective(op.tag):\n            schedule_injective_from_existing(s, op.output(0))\n        for tensor in op.input_tensors:\n            if tensor.op.input_tensors and tensor.op not in scheduled_ops:\n                traverse(tensor.op)\n        scheduled_ops.append(op)\n\n    for out in outs:\n        traverse(out.op)\n    return s\n\n\ndef _get_threads(ib, nthread_tx, nthread_bx, nthread_by, nthread_bz):\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n    by = te.thread_axis(\"blockIdx.y\")\n    bz = te.thread_axis(\"blockIdx.z\")\n    ib.scope_attr(by, \"thread_extent\", nthread_by)\n    ib.scope_attr(bz, \"thread_extent\", nthread_bz)\n\n    return tx, bx, by, bz\n\n\ndef _sort_init(ib, shape, axis, keys_in, keys_out, values_out=None, value_init_func=None):\n    \"\"\"Initialize the output buffers by copying from inputs\"\"\"\n    axis_mul_before = 1\n    axis_mul_after = 1\n    if axis < 0:\n        axis = len(shape) + axis\n    for i, value in enumerate(shape, 0):\n        if i < axis:\n            axis_mul_before *= value\n        elif i > axis:\n            axis_mul_after *= value\n\n    # Set up threading\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = ceil_div(shape[axis], max_threads)\n    nthread_by = axis_mul_before\n    nthread_bz = axis_mul_after\n\n    # Copy the keys_in to initial output\n    with ib.new_scope():\n        tx, bx, by, bz = _get_threads(ib, nthread_tx, nthread_bx, nthread_by, nthread_bz)\n        tid = bx * nthread_tx + tx\n        idx = (by * shape[axis] + tid) * axis_mul_after + bz\n        with ib.if_scope(tid < shape[axis]):\n            keys_out[idx] = keys_in[idx]\n            if values_out is not None:\n                values_out[idx] = value_init_func(idx, tid)\n\n    return axis_mul_before, axis_mul_after\n\n\n## TODO(mbrookhart): These are effective optimziation hyperparametrs\n## Perhaps we can autotune?\nblock_size = 128\nthread_work = 4\n\n\ndef _odd_even_sort(\n    ib,\n    size,\n    axis_mul_before,\n    axis_mul_after,\n    is_ascend,\n    keys,\n    keys_swap,\n    values=None,\n    values_swap=None,\n):\n\n    nthread_tx = block_size // 2\n    nthread_bx = ceil_div(size, block_size)\n    nthread_by = axis_mul_before\n    nthread_bz = axis_mul_after\n    with ib.new_scope():\n        ib.scope_attr(tvm.tir.const(0), \"hand_threaded\", 0)\n        tx, bx, by, bz = _get_threads(ib, nthread_tx, nthread_bx, nthread_by, nthread_bz)\n        tid = 2 * tx\n        start = bx * block_size\n\n        ## Create shared memory as syncable thread scratch space\n        tmp_keys_swap = ib.allocate(\n            keys_swap.dtype,\n            (block_size,),\n            name=\"temp_keys_swap\",\n            scope=\"shared\",\n        )\n        if values_swap is not None:\n            tmp_values_swap = ib.allocate(\n                values_swap.dtype,\n                (block_size,),\n                name=\"temp_values_swap\",\n                scope=\"shared\",\n            )\n\n        ## Create thread local data for swapping\n        temp_keys = ib.allocate(keys_swap.dtype, (1,), name=\"temp_keys\", scope=\"local\")\n        if values_swap is not None:\n            temp_values = ib.allocate(values_swap.dtype, (1,), name=\"temp_values\", scope=\"local\")\n\n        temp_cond1 = ib.allocate(keys_swap.dtype, (1,), name=\"temp_cond1\", scope=\"local\")\n        temp_cond2 = ib.allocate(keys_swap.dtype, (1,), name=\"temp_cond2\", scope=\"local\")\n        # Copy data to scratch space\n        base_idx = by * size * axis_mul_after + bz\n        with ib.for_range(0, 2) as n:\n            with ib.if_scope((tid + n + start) < size):\n                tmp_keys_swap[tid + n] = keys[base_idx + (tid + n + start) * axis_mul_after]\n                if values_swap is not None:\n                    tmp_values_swap[tid + n] = values[base_idx + (tid + n + start) * axis_mul_after]\n\n        ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n\n        idxm = tvm.tir.indexmod\n        # OddEvenTransposeSort\n        current_sort_num = tvm.tir.min(block_size, size - start)\n        with ib.for_range(0, current_sort_num) as k:\n            n = idxm(tid + k, 2)\n            with ib.if_scope(tid + n < current_sort_num - 1):\n                temp_cond1[0] = tmp_keys_swap[tid + n]\n                temp_cond2[0] = tmp_keys_swap[tid + n + 1]\n                if is_ascend:\n                    cond = temp_cond1[0] > temp_cond2[0]\n                else:\n                    cond = temp_cond1[0] < temp_cond2[0]\n                with ib.if_scope(cond):\n                    temp_keys[0] = tmp_keys_swap[tid + n]\n                    tmp_keys_swap[tid + n] = tmp_keys_swap[tid + n + 1]\n                    tmp_keys_swap[tid + n + 1] = temp_keys[0]\n                    if values_swap is not None:\n                        temp_values[0] = tmp_values_swap[tid + n]\n                        tmp_values_swap[tid + n] = tmp_values_swap[tid + n + 1]\n                        tmp_values_swap[tid + n + 1] = temp_values[0]\n            ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n\n        ## Copy sorted data to output\n        with ib.for_range(0, 2) as n:\n            with ib.if_scope(tid + n + start < size):\n                keys[base_idx + (tid + n + start) * axis_mul_after] = tmp_keys_swap[tid + n]\n                keys_swap[base_idx + (tid + n + start) * axis_mul_after] = tmp_keys_swap[tid + n]\n                if values_swap is not None:\n                    values[base_idx + (tid + n + start) * axis_mul_after] = tmp_values_swap[tid + n]\n                    values_swap[base_idx + (tid + n + start) * axis_mul_after] = tmp_values_swap[\n                        tid + n\n                    ]\n\n\ndef _sort_common(\n    ib,\n    size,\n    axis_mul_before,\n    axis_mul_after,\n    is_ascend,\n    keys,\n    keys_swap,\n    values=None,\n    values_swap=None,\n):\n    \"\"\"Either sort only values or sort values by keys.\"\"\"\n\n    ## This function performs a multi-level mergesort\n    ## For blocks of length <= block_size, it does odd-even transpose sort\n    ##    in GPU shared memory\n    ## For intermediate block sizes (>block_size, < max_threads * thread_work)\n    ##    it uses the mergpath algorthim https://arxiv.org/abs/1406.2628\n    ##    to merge blocks in parallel\n    ## At some point, the size of the blocks to be merged is too big for max_threads\n    ##    and we switch to using a dual-level mergepath where the outer mergepath\n    ##    finds the start/end locations of the inner mergepath so that we can split\n    ##    the merge into more blocks\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_by = axis_mul_before * axis_mul_after\n    nthread_bz = 1\n    nthread_tx = max_threads\n    nthread_bx = ceil_div(size, nthread_tx)\n\n    def compare(a, b):\n        \"\"\"\n        Compare a and b in proper ascending or descending order\n        \"\"\"\n        if is_ascend:\n            out = a <= b\n        else:\n            out = b <= a\n        return out\n\n    # Sort the lower levels of the merge using odd-even sort, it's fast for small inputs\n    lower_lim = ceil_log2(block_size)\n\n    _odd_even_sort(\n        ib,\n        size,\n        axis_mul_before * axis_mul_after,\n        1,\n        is_ascend,\n        keys,\n        keys_swap,\n        values,\n        values_swap,\n    )\n\n    upper_lim = ceil_log2(size)\n\n    def get_merge_begin(source, base_idx, aCount, bCount, aStart, bStart, diag, step_count):\n        first = ib.allocate(\"int64\", (1,), name=\"first\", scope=\"local\")\n        mid = ib.allocate(\"int64\", (1,), name=\"mid\", scope=\"local\")\n        last = ib.allocate(\"int64\", (1,), name=\"last\", scope=\"local\")\n        first[0] = tvm.te.max(0, diag - bCount)\n        last[0] = tvm.te.min(diag, aCount)\n        with ib.while_loop(first[0] < last[0]):\n            mid = (first[0] + last[0]) >> 1\n            a = source[base_idx + (aStart + mid)]\n            b = source[base_idx + (bStart + diag - 1 - mid)]\n            with ib.if_scope(compare(a, b)):\n                first[0] = mid + 1\n            with ib.else_scope():\n                last[0] = mid\n        return first[0], last[0]\n\n    def serial_merge(\n        source,\n        dest,\n        source_idx,\n        dest_idx,\n        base_idx,\n        aCount,\n        bCount,\n        aStart,\n        bStart,\n        kStart,\n        diag,\n        step_count,\n        first,\n        last,\n    ):\n        i = ib.allocate(\"int64\", (1,), name=\"i\", scope=\"local\")\n        j = ib.allocate(\"int64\", (1,), name=\"j\", scope=\"local\")\n        i[0] = aStart + first\n        j[0] = bStart + diag - last\n        with ib.for_range(0, tvm.te.min(aCount + bCount - diag, step_count)) as count:\n            i_idx = base_idx + i[0]\n            j_idx = base_idx + j[0]\n            k_idx = base_idx + (kStart + diag + count)\n\n            def assign_i():\n                \"\"\"assign i value to current output\"\"\"\n                dest[k_idx] = source[i_idx]\n                if values is not None:\n                    dest_idx[k_idx] = source_idx[i_idx]\n                i[0] += 1\n\n            def assign_j():\n                \"\"\"assign j value to current output\"\"\"\n                dest[k_idx] = source[j_idx]\n                if values is not None:\n                    dest_idx[k_idx] = source_idx[j_idx]\n                j[0] += 1\n\n            ## if both of the iterators are in range\n            with ib.if_scope(tvm.tir.all(i[0] < aStart + aCount, j[0] < bStart + bCount)):\n                # compare them and insert whichever is next into the output\n                with ib.if_scope(compare(source[i_idx], source[j_idx])):\n                    assign_i()\n                with ib.else_scope():\n                    assign_j()\n            # otherwise, simply copy the remainder of the valid iterator to the output\n            with ib.else_scope():\n                with ib.if_scope(i[0] < aStart + aCount):\n                    assign_i()\n                with ib.else_scope():\n                    assign_j()\n\n    with ib.for_range(0, cast(upper_lim - lower_lim, \"int64\"), dtype=\"int64\") as l2_width:\n        width = 2 << (l2_width + lower_lim)\n        # Define and launch the cuda kernel\n        with ib.new_scope():\n            target = tvm.target.Target.current()\n            if \"vulkan\" in str(target):\n                # Vulkan can't handle dynamic nthread, so we thread slightly differently\n                # for vulkan. We don't do this generally because it causes a 15% perf\n                # regression on other platforms\n                ntx = max_threads\n                nbx = tvm.tir.generic.cast(ceil_div(width, max_threads * thread_work), \"int32\")\n                nbz = tvm.tir.generic.cast(ceil_div(size, width), \"int32\")\n                tx, bx, by, bz = _get_threads(ib, ntx, nbx, nthread_by, nbz)\n            else:\n                ntx = tvm.tir.generic.cast(tvm.te.min(max_threads, width), \"int32\")\n                nbx = tvm.tir.generic.cast(ceil_div(width, max_threads * thread_work), \"int32\")\n                nbz = tvm.tir.generic.cast(ceil_div(size, width), \"int32\")\n                tx, bx, by, bz = _get_threads(ib, ntx, nbx, nthread_by, nbz)\n\n            def mergepath(\n                source,\n                dest,\n                source_idx,\n                dest_idx,\n                aCount,\n                bCount,\n                aStart,\n                bStart,\n                kStart,\n                step_count,\n                even,\n            ):\n                # pylint: disable=arguments-out-of-order\n                def merge(source, dest, source_idx, dest_idx):\n                    diag = tx * step_count\n                    first, last = get_merge_begin(\n                        source,\n                        by * size,\n                        aCount,\n                        bCount,\n                        aStart,\n                        bStart,\n                        diag,\n                        step_count,\n                    )\n                    # iterate over the output loop\n                    serial_merge(\n                        source,\n                        dest,\n                        source_idx,\n                        dest_idx,\n                        by * size,\n                        aCount,\n                        bCount,\n                        aStart,\n                        bStart,\n                        kStart,\n                        diag,\n                        step_count,\n                        first,\n                        last,\n                    )\n\n                with ib.if_scope(even):\n                    merge(source, dest, source_idx, dest_idx)\n                with ib.else_scope():\n                    merge(dest, source, dest_idx, source_idx)\n\n            def mergesort(source, dest, source_idx, dest_idx, size, width, even):\n                # calculate the start, mid, and end points of this section\n                start = width * bz\n                middle = cast(tvm.te.min(start + tvm.tir.indexdiv(width, 2), size), \"int64\")\n                end = cast(tvm.te.min(start + width, size), \"int64\")\n                with ib.if_scope(start < size):\n                    with ib.if_scope(nbx == 1):\n                        ## merge the start->middle and middle->end arrays\n                        aCount = middle - start\n                        bCount = end - middle\n                        mergepath(\n                            source,\n                            dest,\n                            source_idx,\n                            dest_idx,\n                            aCount,\n                            bCount,\n                            start,\n                            middle,\n                            start,\n                            ceil_div(width, ntx),\n                            even,\n                        )\n                    with ib.else_scope():\n                        step_count = max_threads * thread_work\n                        diag = bx * step_count\n\n                        def do_merge(first, last):\n                            aStart = start + first\n                            bStart = middle + diag - last\n                            aCount = tvm.te.min(middle - aStart, step_count)\n                            bCount = tvm.te.min(end - bStart, step_count)\n                            mergepath(\n                                source,\n                                dest,\n                                source_idx,\n                                dest_idx,\n                                aCount,\n                                bCount,\n                                aStart,\n                                bStart,\n                                start + diag,\n                                thread_work,\n                                even,\n                            )\n\n                        with ib.if_scope(even):\n                            first, last = get_merge_begin(\n                                source,\n                                by * size,\n                                middle - start,\n                                end - middle,\n                                start,\n                                middle,\n                                diag,\n                                step_count,\n                            )\n                            do_merge(first, last)\n                        with ib.else_scope():\n                            first, last = get_merge_begin(\n                                dest,\n                                by * size,\n                                middle - start,\n                                end - middle,\n                                start,\n                                middle,\n                                diag,\n                                step_count,\n                            )\n                            do_merge(first, last)\n\n            # Call the kernel\n            mergesort(\n                keys,\n                keys_swap,\n                values,\n                values_swap,\n                size,\n                width,\n                tvm.tir.indexmod(l2_width, 2) == 0,\n            )\n    nthread_by = axis_mul_before\n    nthread_bz = axis_mul_after\n    nthread_tx = max_threads\n    nthread_bx = ceil_div(size, nthread_tx)\n    ## if the final sorted data ended up in the swap, copy it to the real output\n    with ib.if_scope(\n        tvm.tir.all(upper_lim > lower_lim, tvm.tir.indexmod(upper_lim - lower_lim, 2) == 1)\n    ):\n        with ib.new_scope():\n            tx, bx, by, bz = _get_threads(ib, nthread_tx, nthread_bx, nthread_by, nthread_bz)\n            tid = bx * nthread_tx + tx\n            idx = (by * axis_mul_after + bz) * size + tid\n            with ib.if_scope(tid < size):\n                keys[idx] = keys_swap[idx]\n                if values is not None:\n                    values[idx] = values_swap[idx]\n\n\ndef sort_ir(\n    data, values_out, values_out_swap, axis, is_ascend, indices_out=None, indices_out_swap=None\n):\n    \"\"\"Low level IR to do sorting on the GPU, same usage as tvm.contrib.sort.argsort on the CPU.\n\n    Parameters\n    ----------\n    data: Buffer\n        Buffer of input data. Data will be sorted in place.\n\n    values_out : Buffer\n        Output buffer of values of sorted tensor with same shape as data.\n\n    values_out_swap : Buffer\n        Output buffer of values with same shape as data to use as swap.\n\n    axis : Int\n        Axis long which to sort the input tensor.\n\n    is_ascend : Boolean\n        Whether to sort in ascending or descending order.\n\n    indicess_out : Buffer\n        Output buffer of indices of sorted tensor with same shape as data.\n\n    indices_out_swap : Buffer\n        Output buffer of indices with same shape as data to use as swap.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    ib = tvm.tir.ir_builder.create()\n    shape = data.shape\n\n    data = ib.buffer_ptr(data)\n    values_out = ib.buffer_ptr(values_out)\n    values_out_swap = ib.buffer_ptr(values_out_swap)\n    if indices_out is not None:\n        indices_out = ib.buffer_ptr(indices_out)\n        assert indices_out_swap is not None\n        indices_out_swap = ib.buffer_ptr(indices_out_swap)\n\n    with ib.if_scope(shape[axis] > 0):\n        axis_mul_before, axis_mul_after = _sort_init(\n            ib,\n            shape,\n            axis,\n            data,\n            values_out,\n            indices_out,\n            value_init_func=lambda _, tid: tvm.tir.generic.cast(tid, indices_out.dtype),\n        )\n\n        _sort_common(\n            ib,\n            shape[axis],\n            axis_mul_before,\n            axis_mul_after,\n            is_ascend,\n            values_out,\n            values_out_swap,\n            values=indices_out,\n            values_swap=indices_out_swap,\n        )\n\n    return ib.get()\n\n\ndef sort_by_key_ir(\n    keys_in, values_in, keys_out, values_out, keys_out_swap, values_out_swap, axis, is_ascend\n):\n    \"\"\"Low level IR to do sort by key on the GPU.\n\n    Parameters\n    ----------\n    keys_in: Buffer\n        Buffer of input keys.\n\n    values_in: Buffer\n        Buffer of input keys.\n\n    keys_out : Buffer\n        Buffer of output sorted keys.\n\n    values_out : Buffer\n        Buffer of output sorted values.\n\n    keys_out_swap : Buffer\n        Output buffer of values with same shape as keys_in to use as swap.\n\n    values_out_swap : Buffer\n        Output buffer of values with same shape as values_in to use as swap.\n\n    axis : Int\n        Axis long which to sort the input tensor.\n\n    is_ascend : Boolean\n        Whether to sort in ascending or descending order.\n\n    indicess_out : Buffer\n        Output buffer of indices of sorted tensor with same shape as keys_in.\n\n    values_out_swap : Buffer\n        Output buffer of indices with same shape as keys_in to use as swap.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    ib = tvm.tir.ir_builder.create()\n    shape = keys_in.shape\n\n    keys_in = ib.buffer_ptr(keys_in)\n    values_in = ib.buffer_ptr(values_in)\n    keys_out = ib.buffer_ptr(keys_out)\n    keys_out_swap = ib.buffer_ptr(keys_out_swap)\n    values_out = ib.buffer_ptr(values_out)\n    values_out_swap = ib.buffer_ptr(values_out_swap)\n\n    with ib.if_scope(shape[axis] > 0):\n        axis_mul_before, axis_mul_after = _sort_init(\n            ib,\n            shape,\n            axis,\n            keys_in,\n            keys_out,\n            values_out,\n            value_init_func=lambda idx, _: values_in[idx],\n        )\n\n        _sort_common(\n            ib,\n            shape[axis],\n            axis_mul_before,\n            axis_mul_after,\n            is_ascend,\n            keys_out,\n            keys_out_swap,\n            values=values_out,\n            values_swap=values_out_swap,\n        )\n    return ib.get()\n\n\ndef sort(data, axis=-1, is_ascend=1):\n    \"\"\"Performs sorting along the given axis and returns an array of\n    sorted values with the same shape as the input data.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        The input array.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The output of this function.\n    \"\"\"\n    ndim = len(data.shape)\n    axis = ndim + axis if axis < 0 else axis\n    if axis != ndim - 1:\n        # Prepare for sorting along axis -1.\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    value_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"value_buf\", data_alignment=8)\n    value_buf_swap = tvm.tir.decl_buffer(data.shape, data.dtype, \"value_buf_swap\", data_alignment=8)\n\n    out = te.extern(\n        [data.shape, data.shape],\n        [data],\n        lambda ins, outs: sort_ir(ins[0], outs[0], outs[1], -1, is_ascend),\n        out_buffers=[value_buf, value_buf_swap],\n        name=\"sort_gpu\",\n        tag=\"sort_gpu\",\n    )[0]\n\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        out = transpose(out, axes)\n\n    return out\n\n\ndef sort_thrust(data, axis=-1, is_ascend=1):\n    \"\"\"Performs sorting along the given axis and returns an array of\n    sorted values with the same shape as the input data.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        The input array.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The output of this function.\n    \"\"\"\n    dtype = \"float32\"\n\n    ndim = len(data.shape)\n    axis = ndim + axis if axis < 0 else axis\n\n    if axis != ndim - 1:\n        # Prepare for sorting along axis -1.\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    value_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"value_buf\", data_alignment=8)\n    indices_buf = tvm.tir.decl_buffer(data.shape, dtype, \"out_buf\", data_alignment=8)\n    out = te.extern(\n        [data.shape, data.shape],\n        [data],\n        ## TODO(mbrookhart): This thrust function is actually doing argsort, not sort\n        ## For performance, we should probably rename the contrib function and add\n        ## a pure sort\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.thrust.sort\", ins[0], outs[0], outs[1], is_ascend\n        ),\n        out_buffers=[value_buf, indices_buf],\n        name=\"sort_gpu\",\n        tag=\"sort_gpu\",\n    )[0]\n\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        out = transpose(out, axes)\n    return out\n\n\ndef argsort(data, axis=-1, is_ascend=1, dtype=\"float32\", ret_type=\"indices\"):\n    \"\"\"Performs sorting along the given axis and returns an array of indices\n    having same shape as an input array that index data in sorted order.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        The input array.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        DType of the output indices.\n\n    ret_type : string, optional\n        The return type [both, indices].\n        \"both\": return both sorted data and indices.\n        \"indices\": return sorted indices only.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The output of this function.\n    \"\"\"\n    ndim = len(data.shape)\n    axis = ndim + axis if axis < 0 else axis\n    if axis != ndim - 1:\n        # Prepare for sorting along axis -1.\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    value_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"value_buf\", data_alignment=8)\n    value_swap_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"value_swap_buf\", data_alignment=8)\n    indices_buf = tvm.tir.decl_buffer(data.shape, dtype, \"out_buf\", data_alignment=8)\n    indices_swap_buf = tvm.tir.decl_buffer(data.shape, dtype, \"out_swap_buf\", data_alignment=8)\n\n    outs = te.extern(\n        [data.shape, data.shape, data.shape, data.shape],\n        [data],\n        lambda ins, outs: sort_ir(\n            ins[0],\n            outs[0],\n            outs[2],\n            -1,\n            is_ascend,\n            indices_out=outs[1],\n            indices_out_swap=outs[3],\n        ),\n        out_buffers=[value_buf, indices_buf, value_swap_buf, indices_swap_buf],\n        name=\"argsort_gpu\",\n        tag=\"argsort_gpu\",\n    )\n\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        outs = [transpose(out, axes) for out in outs]\n\n    if ret_type == \"indices\":\n        return outs[1]\n\n    return outs[0], outs[1]\n\n\ndef argsort_thrust(data, axis=-1, is_ascend=1, dtype=\"float32\", ret_type=\"indices\"):\n    \"\"\"Performs sorting along the given axis and returns an array of indices\n    having same shape as an input array that index data in sorted order.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        The input array.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        DType of the output indices.\n\n    ret_type : string, optional\n        The return type [both, indices].\n        \"both\": return both sorted data and indices.\n        \"indices\": return sorted indices only.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The output of this function.\n    \"\"\"\n    return topk_thrust(data, 0, axis, ret_type, is_ascend, dtype)\n\n\ndef schedule_sort(outs):\n    \"\"\"Schedule for sort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of argsort\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _schedule_sort(outs)\n\n\ndef schedule_argsort(outs):\n    \"\"\"Schedule for argsort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of argsort\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _schedule_sort(outs)\n\n\ndef topk(data, k=1, axis=-1, ret_type=\"both\", is_ascend=False, dtype=\"int64\"):\n    \"\"\"Get the top k elements in an input tensor along the given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tensor.\n\n    k : int, optional\n        Number of top elements to select. Return all elements if k < 1.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    ret_type: str, optional\n        The return type [both, values, indices].\n        \"both\": return both top k data and indices.\n        \"values\": return top k data only.\n        \"indices\": return top k indices only.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        The data type of the indices output.\n\n    Returns\n    -------\n    out : tvm.te.Tensor or List[tvm.te.Tensor]\n        The computed result.\n    \"\"\"\n    assert ret_type in [\"both\", \"values\", \"indices\"]\n    ndim = len(data.shape)\n    axis = axis + ndim if axis < 0 else axis\n    assert 0 <= axis < ndim\n    dshape = data.shape\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    values_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"values_buf\", data_alignment=8)\n    values_swap_buf = tvm.tir.decl_buffer(\n        data.shape, data.dtype, \"values_swap_buf\", data_alignment=8\n    )\n    indices_buf = tvm.tir.decl_buffer(data.shape, dtype, \"indices_buf\", data_alignment=8)\n    indices_swap_buf = tvm.tir.decl_buffer(data.shape, dtype, \"indies_swap_buf\", data_alignment=8)\n\n    if ret_type == \"values\":\n        output = te.extern(\n            [data.shape, data.shape],\n            [data],\n            lambda ins, outs: sort_ir(ins[0], outs[0], outs[1], -1, is_ascend),\n            out_buffers=[values_buf, values_swap_buf],\n            name=\"topk_gpu\",\n            tag=\"topk_gpu\",\n        )[0]\n        if axis != ndim - 1:\n            axes = swap(list(range(ndim)), axis)\n            output = transpose(output, axes)\n    else:\n        output = te.extern(\n            [data.shape, data.shape, data.shape, data.shape],\n            [data],\n            lambda ins, outs: sort_ir(\n                ins[0],\n                outs[0],\n                outs[2],\n                -1,\n                is_ascend,\n                indices_out=outs[1],\n                indices_out_swap=outs[3],\n            ),\n            out_buffers=[values_buf, indices_buf, values_swap_buf, indices_swap_buf],\n            name=\"topk_gpu\",\n            tag=\"topk_gpu\",\n        )[0:2]\n        if axis != ndim - 1:\n            axes = swap(list(range(ndim)), axis)\n            output[0] = transpose(output[0], axes)\n            output[1] = transpose(output[1], axes)\n\n    if isinstance(k, int) and k < 1:\n        if ret_type == \"indices\":\n            return output[1]\n        return output\n    beg = [0] * ndim\n    end = []\n    strides = [1] * ndim\n    for i in range(ndim):\n        if i == axis:\n            end.append(k if isinstance(k, int) else tvm.te.size_var(\"dim\"))\n        else:\n            end.append(dshape[i])\n    if ret_type == \"both\":\n        values_out, indices_out = output\n        values_out = strided_slice(values_out, beg, end, strides)\n        indices_out = strided_slice(indices_out, beg, end, strides)\n        output = [values_out, indices_out]\n    elif ret_type == \"values\":\n        output = [strided_slice(output, beg, end, strides)]\n    else:  # ret_type == \"indices\"\n        indices_out = output[1]\n        output = [strided_slice(indices_out, beg, end, strides)]\n    return output\n\n\ndef topk_thrust(data, k=1, axis=-1, ret_type=\"both\", is_ascend=False, dtype=\"int64\"):\n    \"\"\"Get the top k elements in an input tensor along the given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tensor.\n\n    k : int, optional\n        Number of top elements to select. Return all elements if k < 1.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    ret_type: str, optional\n        The return type [both, values, indices].\n        \"both\": return both top k data and indices.\n        \"values\": return top k data only.\n        \"indices\": return top k indices only.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        The data type of the indices output.\n\n    Returns\n    -------\n    out : tvm.te.Tensor or List[tvm.te.Tensor]\n        The computed result.\n    \"\"\"\n    assert ret_type in [\"both\", \"values\", \"indices\"]\n    ndim = len(data.shape)\n    axis = ndim + axis if axis < 0 else axis\n\n    if axis != ndim - 1:\n        # Prepare for sorting along axis -1.\n        axes = swap(list(range(ndim)), axis)\n        data = transpose(data, axes)\n\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    out_bufs = [\n        tvm.tir.decl_buffer(data.shape, data.dtype, \"value_buf\", data_alignment=8),\n        tvm.tir.decl_buffer(data.shape, dtype, \"indices_buf\", data_alignment=8),\n    ]\n\n    is_ascend = 1 if is_ascend else 0\n\n    out = te.extern(\n        [data.shape, data.shape],\n        [data],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.thrust.sort\", ins[0], outs[0], outs[1], is_ascend\n        ),\n        in_buffers=[data_buf],\n        out_buffers=out_bufs,\n        name=\"topk_gpu\",\n        tag=\"topk_gpu\",\n    )\n\n    if isinstance(k, tvm.tir.IntImm):\n        k = k.value\n\n    if not isinstance(k, int) or k > 0:\n        beg = [0] * ndim\n        end = data.shape[:-1] + [k if isinstance(k, int) else tvm.te.size_var(\"dim\")]\n        strides = [1] * ndim\n        out = [strided_slice(o, beg, end, strides) for o in out]\n\n    if axis != ndim - 1:\n        axes = swap(list(range(ndim)), axis)\n        out = [transpose(o, axes) for o in out]\n\n    if ret_type == \"values\":\n        out = out[0]\n    elif ret_type == \"indices\":\n        out = out[1]\n\n    return out\n\n\ndef schedule_topk(outs):\n    \"\"\"Schedule for argsort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of argsort\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _schedule_sort(outs)\n\n\ndef sort_by_key(keys, values, axis=-1, is_ascend=1):\n    \"\"\"Sort values with respect to keys. Both keys and values will\n     be sorted and returned.\n\n    Parameters\n    ----------\n    keys: tvm.te.Tensor\n        The input keys.\n\n    values : tvm.te.Tensor,\n        The input values.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    Returns\n    -------\n    keys_sorted : tvm.te.Tensor\n        The sorted keys\n\n    values_sorted : tvm.te.Tensor\n        The values sorted with respect to the keys\n    \"\"\"\n    keys_buf = tvm.tir.decl_buffer(keys.shape, keys.dtype, \"keys_buf\", data_alignment=8)\n    values_buf = tvm.tir.decl_buffer(values.shape, values.dtype, \"values_buf\", data_alignment=8)\n\n    out_bufs = [\n        tvm.tir.decl_buffer(keys.shape, keys.dtype, \"keys_buf\", data_alignment=8),\n        tvm.tir.decl_buffer(values.shape, values.dtype, \"values_buf\", data_alignment=8),\n        tvm.tir.decl_buffer(keys.shape, keys.dtype, \"keys_swap_buf\", data_alignment=8),\n        tvm.tir.decl_buffer(values.shape, values.dtype, \"values_swap_buf\", data_alignment=8),\n    ]\n    out = te.extern(\n        [keys.shape, values.shape, keys.shape, values.shape],\n        [keys, values],\n        lambda ins, outs: sort_by_key_ir(\n            ins[0], ins[1], outs[0], outs[1], outs[2], outs[3], axis, is_ascend\n        ),\n        in_buffers=[keys_buf, values_buf],\n        out_buffers=out_bufs,\n        dtype=[keys.dtype, values.dtype],\n        name=\"sort_by_key\",\n        tag=\"sort_by_key\",\n    )\n    return out[0], out[1]\n\n\ndef stable_sort_by_key_thrust(keys, values, for_scatter=False):\n    \"\"\"Sort values with respect to keys using thrust.\n    Both keys and values will be sorted and returned.\n    Sorting is done via stable sort, so relative ordering among\n    ties are preserved.\n\n    Parameters\n    ----------\n    keys: tvm.te.Tensor\n        The 1D input keys.\n\n    values : tvm.te.Tensor,\n        The 1D input values.\n\n    for_scatter: bool, optional\n        If True, negative keys are interpreted as negative indices.\n        Before sorting, negative indices are converted to corresponding positive indices.\n        The output keys (indices) are all positive.\n        This option is introduced to optimize the scatter implementation.\n\n    Returns\n    -------\n    keys_sorted : tvm.te.Tensor\n        The sorted keys\n\n    values_sorted : tvm.te.Tensor\n        The values sorted with respect to the keys\n    \"\"\"\n    keys_buf = tvm.tir.decl_buffer(keys.shape, keys.dtype, \"keys_buf\", data_alignment=8)\n    values_buf = tvm.tir.decl_buffer(values.shape, values.dtype, \"values_buf\", data_alignment=8)\n    out_bufs = [\n        tvm.tir.decl_buffer(keys.shape, keys.dtype, \"keys_buf\", data_alignment=8),\n        tvm.tir.decl_buffer(keys.shape, values.dtype, \"values_buf\", data_alignment=8),\n    ]\n    out = te.extern(\n        [keys.shape, values.shape],\n        [keys, values],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.thrust.stable_sort_by_key\", ins[0], ins[1], outs[0], outs[1], for_scatter\n        ),\n        in_buffers=[keys_buf, values_buf],\n        out_buffers=out_bufs,\n        dtype=[keys.dtype, values.dtype],\n        name=\"stable_sort_by_key\",\n        tag=\"stable_sort_by_key\",\n    )\n    return out[0], out[1]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Sparse operators\"\"\"\nimport numpy as np\nimport scipy.sparse as sp\n\nimport tvm\nfrom tvm import relay, te\n\nfrom .. import nn\nfrom ..utils import traverse_inline, get_const_tuple, prod, get_const_int, ceil_div\nfrom .transform import schedule_transpose_from_existing\n\n\ndef sparse_dense(data, weight_data, weight_indices, weight_indptr, sparse_lhs=False):\n    \"\"\"\n    Computes sparse-dense matrix multiplication of `data` and\n    `(weight_data, weight_indices, weight_indptr).T`\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        2-D with shape [M, K], float32\n\n    weight_data : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        3-D with shape [num_blocks, bs_r, bs_c] (BSR)\n\n    weight_indices : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        1-D with shape [num_blocks] (BSR)\n\n    weight_indptr : tvm.te.Tensor\n        1-D with shape [N + 1] (CSR) or\n        1-D with shape [(N + 1) // bs_r] (BSR)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    # pylint:disable=unused-argument\n    return nn.sparse_dense(data, weight_data, weight_indices, weight_indptr, sparse_lhs)\n\n\ndef schedule_sparse_dense(outs):\n    \"\"\"Create schedule for sparse dense\"\"\"\n    # pylint:disable=invalid-name\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"sparse_dense_sp_rhs_bsrmm\" or op.tag == \"sparse_dense_sp_lhs_bsrmm\":\n            y_bsrmm = op.input_tensors[0]\n            assert (\n                y_bsrmm.op.tag == \"sparse_dense_sp_rhs_bsrmm_block\"\n                or y_bsrmm.op.tag == \"sparse_dense_sp_lhs_bsrmm_block\"\n            )\n            out = s.outputs[0].output(0)\n\n            if op not in s.outputs:\n                y_reshape = op.output(0)\n                s[y_reshape].compute_at(s[out], s[out].op.axis[1])\n\n            (_, c) = s[y_bsrmm].op.reduce_axis\n\n            (m_o, n_o) = s[out].op.axis\n            s[out].bind(m_o, te.thread_axis(\"blockIdx.x\"))\n            s[out].bind(n_o, te.thread_axis(\"blockIdx.y\"))\n            s[y_bsrmm].compute_at(s[out], n_o)\n\n            thread_x = te.thread_axis(\"threadIdx.x\")\n\n            y_bsrmm_factored = s.rfactor(y_bsrmm, c)\n            tx = s[y_bsrmm].op.reduce_axis[0]\n            s[y_bsrmm].bind(tx, thread_x)\n            s[y_bsrmm_factored].compute_at(s[y_bsrmm], tx)\n            s[y_bsrmm].set_store_predicate(thread_x.var.equal(0))\n            s[out].set_store_predicate(thread_x.var.equal(0))\n        elif op.tag == \"sparse_dense_sp_lhs_csrmm\" or op.tag == \"sparse_dense_sp_rhs_csrmm\":\n            out = op.output(0)\n            const_size = get_const_int(prod(out.shape))\n            fused = s[out].fuse(*s[out].op.axis)\n            bx, tx = s[out].split(fused, factor=const_size)\n            s[out].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[out].bind(bx, te.thread_axis(\"blockIdx.x\"))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef sparse_dense_tir(data, w_data, w_indices, w_indptr):\n    \"\"\"Compute data * w^T.\n\n    Actually computes (w * data^T) ^ T as data needs to be in column-major\n    format for performance reasons.\n\n    Good resources:\n    Yang, Carl, Ayd\u0131n Bulu\u00e7, and John D. Owens. \"Design principles for sparse\n    matrix multiplication on the GPU.\" European Conference on Parallel\n    Processing. Springer, Cham, 2018. <- This code is basically row-split from here.\n    Gale, Trevor, et al. \"Sparse GPU Kernels for Deep Learning.\" arXiv preprint\n    arXiv:2006.10901 (2020).\n\n\n    Profile with\n    `/opt/nvidia/nsight-compute/2020.1.2/ncu -k default_function_kernel1\n    --section '.*' -s 1 -c 1 venv/bin/python3 test_topi_sparse.py manual`\n    with either default_function_kernel0 for the transpose or\n    default_function_kernel1 for the multiply.\n    \"\"\"\n\n    def gen_ir(data, w_data, w_indices, w_indptr, out):\n        # pylint: disable=invalid-name, simplifiable-if-statement\n        # TODO(tkonolige): use tensorcores for block multiply\n        # TODO(tkonolige): use vectorize on loads\n        # TODO(tkonolige): separate implementation if M is small\n        # TODO(tkonolige): separate implementation for large block sizes\n        ib = tvm.tir.ir_builder.create()\n\n        if tvm.target.Target.current(allow_none=False).kind.name == \"cuda\":\n            use_warp_storage = True\n        else:\n            # TVMs warp shuffle intrinsics are slow on ROCM because they use\n            # LDS (shared memory) to do the shuffling. Instead, we could use\n            # ROCM's support for accessing neighboring threads memory, but we\n            # those intrinsics aren't accessible from TVM. For now, we just use\n            # shared memory. We also default to shared memory on platforms\n            # where we do not know how warp storage performs.\n            use_warp_storage = False\n\n        warp_size = int(tvm.target.Target.current(allow_none=False).thread_warp_size)\n        m = data.shape[1]\n        nb = w_indptr.shape[0] - 1\n        # treat csr like block size 1 bsr\n        if len(w_data.shape) == 1:\n            bs_n = 1\n            bs_k = 1\n        else:\n            bs_n = w_data.shape[1]\n            bs_k = w_data.shape[2]\n        bs_m = bs_n\n        mb = m // bs_m\n        mi = warp_size\n        assert (\n            mb >= mi\n        ), \"Number of block rows in dense matrix must be larger than warp size: {} vs {}.\".format(\n            warp_size, mb\n        )\n        mo = ceil_div(mb, mi)\n        ni = 1  # TODO(tkonolige): how do I compute the number of warps per block?\n        no = ceil_div(nb, ni)\n        rowlength_bi = warp_size\n\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", mo)\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(by, \"thread_extent\", no)\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", warp_size)\n        warp = te.thread_axis(\"threadIdx.y\")\n        ib.scope_attr(warp, \"thread_extent\", ni)\n\n        out_ptr = ib.buffer_ptr(out)\n        data_ptr = ib.buffer_ptr(data)\n        w_data_ptr = ib.buffer_ptr(w_data)\n        w_indices_ptr = ib.buffer_ptr(w_indices)\n        w_indptr_ptr = ib.buffer_ptr(w_indptr)\n\n        n_index = by * ni + warp\n        m_index = bx * mi + tx\n        row_start = w_indptr_ptr[n_index]\n\n        # Guaranteed to be evenly divisible\n        rowlength_bo = ceil_div(w_indptr_ptr[n_index + 1] - row_start, rowlength_bi)\n\n        # thread local storage for bs_m x bs_n block\n        block = ib.allocate(data.dtype, (bs_m, bs_n), name=\"block\", scope=\"local\")\n        data_cache = ib.allocate(data.dtype, (mi, bs_m, bs_k), name=\"data_cache\", scope=\"local\")\n        if use_warp_storage:\n            indices = ib.allocate(w_indices.dtype, (rowlength_bi,), name=\"indices\", scope=\"warp\")\n            w_data_cache = ib.allocate(\n                w_data.dtype, (rowlength_bi, bs_n, bs_k), name=\"w_data_cache\", scope=\"warp\"\n            )\n        else:\n            indices = ib.allocate(\n                w_indices.dtype, (ni, rowlength_bi), name=\"indices\", scope=\"shared\"\n            )\n            w_data_cache = ib.allocate(\n                w_data.dtype, (ni, rowlength_bi, bs_n, bs_k), name=\"w_data_cache\", scope=\"shared\"\n            )\n\n        # zero block\n        with ib.for_range(0, bs_m, name=\"x\", kind=\"unroll\") as x:\n            with ib.for_range(0, bs_n, name=\"y\", kind=\"unroll\") as y:\n                block[x, y] = 0.0\n        # compute into thread local storage using warp_size chunks\n        with ib.for_range(0, rowlength_bo, name=\"bb\") as bb:\n            elem_idx = bb * rowlength_bi + tx\n            # Cache indices. Guaranteed to be multiple of warp_size.\n            if use_warp_storage:\n                indices[tx] = w_indices_ptr[row_start + elem_idx]\n            else:\n                indices[warp, tx] = w_indices_ptr[row_start + elem_idx]\n            # cache dense matrix\n            # each thread has a row\n            # TODO: ideally we could vectorize this\n            with ib.for_range(0, rowlength_bi, name=\"bi\") as bi:\n                with ib.for_range(0, bs_m, name=\"x\", kind=\"unroll\") as x:\n                    with ib.for_range(0, bs_k, name=\"z\", kind=\"unroll\") as z:\n                        # This memory acces should be out of bounds when\n                        # m_index >= mb (which occurs when the dense matrix\n                        # rows % 32 != 0), but it seems to work just fine...\n                        if use_warp_storage:\n                            ind = indices[bi]\n                        else:\n                            ind = indices[warp, bi]\n                        data_cache[bi, x, z] = data_ptr[ind * bs_k + z, m_index * bs_m + x]\n            # cache w_data\n            elem_idx = bb * rowlength_bi + tx\n            with ib.for_range(0, bs_n, name=\"y\", kind=\"unroll\") as y:\n                with ib.for_range(0, bs_k, name=\"z\", kind=\"unroll\") as z:\n                    data_indices = [row_start + elem_idx] + (\n                        [y, z] if len(w_data.shape) > 1 else []\n                    )\n                    cache_indices = [tx, y, z] if use_warp_storage else [warp, tx, y, z]\n                    w_data_cache[cache_indices] = w_data_ptr[data_indices]\n            with ib.for_range(0, mi, name=\"i\") as i:\n                # thread local block matmul\n                with ib.for_range(0, bs_m, name=\"x\", kind=\"unroll\") as x:\n                    with ib.for_range(0, bs_n, name=\"y\", kind=\"unroll\") as y:\n                        with ib.for_range(0, bs_k, name=\"z\", kind=\"unroll\") as z:\n                            if use_warp_storage:\n                                w = w_data_cache[i, y, z]\n                            else:\n                                w = w_data_cache[warp, i, y, z]\n                            block[x, y] += data_cache[i, x, z] * w\n        # store results\n        with ib.for_range(0, bs_m, name=\"x\", kind=\"unroll\") as x:\n            with ib.for_range(0, bs_n, name=\"y\", kind=\"unroll\") as y:\n                with ib.if_scope(m_index < mb):\n                    with ib.if_scope(n_index < nb):\n                        # It doesn't seem like we would be getting coelesced\n                        # writes here, but it doesn't seem to matter\n                        out_ptr[m_index * bs_m + x, n_index * bs_n + y] = block[x, y]\n\n        return ib.get()\n\n    data_t = tvm.topi.transpose(data)\n    # handle csr\n    if len(w_data.shape) == 1:\n        blocksize = 1\n    else:\n        blocksize = w_data.shape[1]\n    out_shape = (data_t.shape[1], (w_indptr.shape[0] - 1) * blocksize)\n    out_buf = tvm.tir.decl_buffer(out_shape, data.dtype, \"out_buf\")\n    out = te.extern(\n        [out_shape],\n        [data_t, w_data, w_indices, w_indptr, data],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"sparse_dense_gpu\",\n        tag=\"sparse_dense_gpu\",\n    )\n    return out\n\n\ndef is_valid_for_sparse_dense_padded(data, weight_data):\n    \"\"\"\n    Check whether input is applicable for sparse_dense_padded op.\n    If not we should fall back to default scheduling.\n    \"\"\"\n    # pylint:disable=invalid-name\n    warp_size = int(tvm.target.Target.current(allow_none=False).thread_warp_size)\n    # If there are multiple alter_ops in a model, the first alteration does not\n    # run type inference for the subsequent ones. In this case, we don't have\n    # the shape information, so we run the inferencer manually.\n    try:\n        m = get_const_tuple(data.checked_type.shape)[1]\n    except ValueError:\n        data_infered = relay.transform.InferType()(tvm.IRModule.from_expr(data))[\"main\"]\n        m = get_const_tuple(data_infered.ret_type.shape)[1]\n    if len(weight_data.shape) == 1:\n        bs_m = 1\n    else:\n        bs_m = weight_data.shape[1]\n\n    mb = m // bs_m\n    if mb >= warp_size:\n        return True\n    return False\n\n\ndef sparse_dense_padded(data, weight_data, weight_indices, weight_indptr, sparse_lhs=False):\n    \"\"\"\n    Computes sparse-dense matrix multiplication of `data` and\n    `(weight_data, weight_indices, weight_indptr).T`\n\n    This variation uses a padded matrix where all row lengths are a multiple of the warp size.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        2-D with shape [M, K], float32\n\n    weight_data : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        3-D with shape [num_blocks, bs_r, bs_c] (BSR)\n\n    weight_indices : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        1-D with shape [num_blocks] (BSR)\n\n    weight_indptr : tvm.te.Tensor\n        1-D with shape [N + 1] (CSR) or\n        1-D with shape [(N + 1) // bs_r] (BSR)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    # TODO(ANSHUMAN87): Handle for sparse_lhs case too\n    assert not sparse_lhs, \"Currently only sparse weight is supported.\"\n    return sparse_dense_tir(data, weight_data, weight_indices, weight_indptr)\n\n\ndef schedule_sparse_dense_padded(outs):\n    \"\"\"Create schedule for sparse dense\"\"\"\n    # XXX: this will fail if we don't include the data_t Tensor in the schedule\n    # ops. Maybe create_schedule should do some analysis so this isn't\n    # necessary\n    data_t = outs[0].op.input_tensors[0]\n    s = te.create_schedule([outs[0].op, data_t.op])\n    schedule_transpose_from_existing(s, outs[0].op.input_tensors[0])\n    return s\n\n\ndef pad_sparse_matrix(matrix, blocksize):\n    \"\"\"Pad rows of sparse matrix matrix so that they are a multiple of blocksize.\"\"\"\n    assert isinstance(matrix, sp.bsr_matrix)\n    new_entries = np.zeros(matrix.shape[0], dtype=matrix.indptr.dtype)\n    bsr = matrix.blocksize[0]\n    for i in range(matrix.shape[0] // bsr):\n        row_length = matrix.indptr[i + 1] - matrix.indptr[i]\n        if row_length % blocksize != 0:\n            new_entries[i] = blocksize - (row_length % blocksize)\n    additional = np.sum(new_entries)\n    indices = np.zeros(matrix.indices.shape[0] + additional, dtype=matrix.indices.dtype)\n    data = np.zeros(\n        (matrix.data.shape[0] + additional, matrix.data.shape[1], matrix.data.shape[2]),\n        dtype=matrix.data.dtype,\n    )\n\n    n = matrix.shape[0] // bsr\n    indptr = np.zeros(n + 1, dtype=matrix.indptr.dtype)\n    indptr[: matrix.indptr.shape[0]] = matrix.indptr\n\n    for i in range(matrix.shape[0] // bsr):\n        indptr[i + 1] = indptr[i] + new_entries[i] + (matrix.indptr[i + 1] - matrix.indptr[i])\n        indices[indptr[i] : indptr[i + 1] - new_entries[i]] = matrix.indices[\n            matrix.indptr[i] : matrix.indptr[i + 1]\n        ]\n        data[indptr[i] : indptr[i + 1] - new_entries[i], :, :] = matrix.data[\n            matrix.indptr[i] : matrix.indptr[i + 1], :, :\n        ]\n\n    return sp.bsr_matrix((data, indices, indptr), matrix.shape)\n\n\n@nn.sparse_dense_alter_layout.register([\"cuda\", \"gpu\", \"rocm\"])\ndef _alter_sparse_dense_layout(_attrs, inputs, _tinfos, _out_type):\n    \"\"\"With cuda, we modify use alter_op_layout to swap the default\n    sparse_dense implementation for one that operates on a padded matrix. We\n    also pad the matrix.\n    \"\"\"\n    # TODO(ANSHUMAN87): Handle for sparse_lhs case too\n    if (\n        isinstance(inputs[1], relay.Constant)\n        and isinstance(inputs[2], relay.Constant)\n        and isinstance(inputs[3], relay.Constant)\n        and is_valid_for_sparse_dense_padded(inputs[0], inputs[1].data.numpy())\n    ):\n        if len(inputs[1].data.numpy().shape) == 1:\n            sparse_matrix = sp.csr_matrix(\n                (inputs[1].data.numpy(), inputs[2].data.numpy(), inputs[3].data.numpy())\n            ).tobsr()\n        else:\n            sparse_matrix = sp.bsr_matrix(\n                (inputs[1].data.numpy(), inputs[2].data.numpy(), inputs[3].data.numpy())\n            )\n        warp_size = int(tvm.target.Target.current(allow_none=False).thread_warp_size)\n        sparse_matrix = pad_sparse_matrix(sparse_matrix, warp_size)\n        return relay.nn._make.sparse_dense_padded(\n            inputs[0],\n            relay.Constant(tvm.nd.array(sparse_matrix.data)),\n            relay.Constant(tvm.nd.array(sparse_matrix.indices)),\n            relay.Constant(tvm.nd.array(sparse_matrix.indptr)),\n        )\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/sparse_reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks\n\"\"\"Sparse_Reshape operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom ...tir import decl_buffer, ir_builder, Cast\nfrom ...te import extern, div, floordiv, floormod\nfrom ..utils import ceil_div\n\n\ndef sparse_reshape(\n    sparse_indices,\n    prev_shape,\n    new_shape,\n    new_sparse_indices_shape,\n    new_shape_shape,\n):\n    \"\"\"\n    Reshape a Sparse Tensor\n    Parameters\n    ----------\n    sparse_indices : relay.Expr\n        A 2-D tensor[N, n_dim] of integers containing location of sparse values, where N is the\n        number of sparse values and n_dim is the number of dimensions of the dense_shape\n    prev_shape : relay.Expr\n        A 1-D tensor containing the previous shape of the dense tensor\n    new_shape : relay.Expr\n        A 1-D tensor containing the new shape of the dense tensor\n    Returns\n    -------\n    result: relay.Expr\n        Output tensor.\n    Examples\n    --------\n    .. code-block:: python\n\n        sparse_indices = [[0, 0, 0],\n                            [0, 0, 1],\n                            [0, 1, 0],\n                            [1, 0, 0],\n                            [1, 2, 3]]\n        prev_shape = [2, 3, 4]\n        new_shape = [9, -1]\n        new_sparse_indices, new_shape = relay.sparse_reshape(sparse_indices,\n                            prev_shape,\n                            new_shape)\n        new_sparse_indices = [[0, 0],\n                              [0, 1],\n                              [1, 2],\n                              [4, 2],\n                              [8, 1]]\n        new_shape = [9, 4]\n    \"\"\"\n\n    def gen_ir(\n        sparse_indices_ptr,\n        prev_shape_ptr,\n        new_shape_ptr,\n        new_sparse_indices_ptr,\n        out_new_shape_ptr,\n    ):\n        ib = ir_builder.create()\n\n        sparse_indices = ib.buffer_ptr(sparse_indices_ptr)\n        prev_shape = ib.buffer_ptr(prev_shape_ptr)\n\n        new_shape = ib.buffer_ptr(new_shape_ptr)\n        out_new_shape = ib.buffer_ptr(out_new_shape_ptr)\n        new_sparse_indices = ib.buffer_ptr(new_sparse_indices_ptr)\n        out_new_shape = ib.buffer_ptr(out_new_shape_ptr)\n\n        prev_shape_size = prev_shape_ptr.shape[0]\n        new_shape_size = new_shape_ptr.shape[0]\n\n        multipliers = ib.allocate(\n            new_shape_ptr.dtype, (prev_shape_size,), name=\"multipliers\", scope=\"global\"\n        )\n        dividers = ib.allocate(\n            new_shape_ptr.dtype, (new_shape_size,), name=\"dividers\", scope=\"global\"\n        )\n        flattened_indices = ib.allocate(\n            new_shape_ptr.dtype,\n            (sparse_indices_ptr.shape[0],),\n            name=\"flattened_indices\",\n            scope=\"global\",\n        )\n        total_ele = ib.allocate(new_shape_ptr.dtype, (1,), name=\"total_ele\", scope=\"global\")\n        division_total_ele = ib.allocate(\n            new_shape_ptr.dtype, (1,), name=\"division_total_ele\", scope=\"global\"\n        )\n        equal_shape = ib.allocate(\"bool\", (1,), name=\"equal_shape\", scope=\"global\")\n        max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n        with ib.new_scope():\n            # The computation in this block is very very miniscule since we are just iterating over\n            # shape tensors which are very small (< 10) and there is no need of parallelization\n            nthread_tx = 1\n            nthread_bx = 1\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n            total_ele[0] = prev_shape[0]\n\n            # Cumulative Reverse Exclusive Multiply\n            multipliers[prev_shape_size - 1] = Cast(new_shape_ptr.dtype, 1)\n            with ib.for_range(0, prev_shape_size - 1) as i_:\n                i = i_ + 1\n                multipliers[prev_shape_size - 1 - i] = (\n                    prev_shape[prev_shape_size - i] * multipliers[prev_shape_size - i]\n                )\n                total_ele[0] *= prev_shape[prev_shape_size - i]\n\n            division_total_ele[0] = Cast(new_shape_ptr.dtype, 1)\n            with ib.for_range(0, new_shape_size) as i:\n                with ib.if_scope(new_shape[i] != -1):\n                    division_total_ele[0] *= new_shape[i]\n\n            # Compute true output shape (replace negative ones)\n            with ib.for_range(0, new_shape_size) as i:\n                with ib.if_scope(new_shape[i] == -1):\n                    out_new_shape[i] = Cast(\n                        new_shape_ptr.dtype, div(total_ele[0], division_total_ele[0])\n                    )\n                with ib.else_scope():\n                    out_new_shape[i] = new_shape[i]\n\n            # Check if prev_shape and new_shape are equal\n            equal_shape[0] = True\n            with ib.if_scope(prev_shape_size == new_shape_size):\n                with ib.for_range(0, prev_shape_size) as i:\n                    with ib.if_scope(prev_shape[i] != out_new_shape[i]):\n                        equal_shape[0] = False\n            with ib.else_scope():\n                equal_shape[0] = False\n\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(sparse_indices_ptr.shape[0], max_threads)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n\n            row_number = bx * max_threads + tx\n\n            # Return same inputs if shapes are equal\n            with ib.if_scope(equal_shape[0]):\n                with ib.if_scope(row_number < sparse_indices_ptr.shape[0]):\n                    with ib.for_range(0, sparse_indices_ptr.shape[1]) as j:\n                        new_sparse_indices[row_number, j] = sparse_indices[row_number, j]\n\n            # Else compute new_sparse_indices\n            with ib.else_scope():\n                dividers[new_shape_size - 1] = Cast(new_shape_ptr.dtype, 1)\n                with ib.for_range(0, new_shape_size - 1) as i_:\n                    i = i_ + 1\n                    dividers[new_shape_size - 1 - i] = (\n                        dividers[new_shape_size - i] * out_new_shape[new_shape_size - i]\n                    )\n\n                with ib.if_scope(row_number < sparse_indices_ptr.shape[0]):\n                    flattened_indices[row_number] = Cast(new_shape_ptr.dtype, 0)\n                    with ib.for_range(0, sparse_indices_ptr.shape[1]) as j:\n                        flattened_indices[row_number] += (\n                            sparse_indices[row_number, j] * multipliers[j]\n                        )\n\n                with ib.if_scope(row_number < sparse_indices_ptr.shape[0]):\n                    current_element = ib.allocate(\n                        new_shape_ptr.dtype, (1,), name=\"current_element\", scope=\"local\"\n                    )\n                    current_element[0] = flattened_indices[row_number]\n\n                    with ib.for_range(0, new_sparse_indices_ptr.shape[1]) as j:\n                        new_sparse_indices[row_number, j] = Cast(\n                            sparse_indices_ptr.dtype, floordiv(current_element[0], dividers[j])\n                        )\n                        current_element[0] = floormod(current_element[0], dividers[j])\n\n        return ib.get()\n\n    new_sparse_indices_buf = decl_buffer(\n        new_sparse_indices_shape, sparse_indices.dtype, \"new_sparse_indices_buf\"\n    )\n    new_shape_buf = decl_buffer(new_shape_shape, prev_shape.dtype, \"new_shape_buf\")\n\n    return extern(\n        [new_sparse_indices_shape, new_shape_shape],\n        [sparse_indices, prev_shape, new_shape],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0], outs[1]),\n        out_buffers=[new_sparse_indices_buf, new_shape_buf],\n        name=\"sparse_reshape_cuda\",\n        tag=\"sparse_reshape_cuda\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/ssd/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"VISION network operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .multibox import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/ssd/multibox.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, too-many-statements, too-many-function-args\n\"\"\"SSD multibox operators\"\"\"\nimport math\nimport tvm\nfrom tvm import te\nfrom tvm.tir import if_then_else, exp\n\nfrom tvm import topi\n\nfrom ..nms import non_max_suppression\n\n\ndef multibox_prior_ir(data, out, sizes, ratios, steps, offsets):\n    \"\"\"Low level IR routing for multibox_prior operator.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input data buffer.\n\n    out : Buffer\n        Output buffer.\n\n    sizes : tuple of float\n        Tuple of sizes for anchor boxes.\n\n    ratios : tuple of float\n        Tuple of ratios for anchor boxes.\n\n    steps : Tuple of float\n        Priorbox step across y and x, -1 for auto calculation.\n\n    offsets : tuple of int\n        Priorbox center offsets, y and x respectively.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    max_threads = int(math.sqrt(tvm.target.Target.current(allow_none=False).max_num_threads))\n    tx = te.thread_axis(\"threadIdx.x\")\n    ty = te.thread_axis(\"threadIdx.y\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    by = te.thread_axis(\"blockIdx.y\")\n    ib = tvm.tir.ir_builder.create()\n    p_out = ib.buffer_ptr(out)\n    in_height = data.shape[2]\n    in_width = data.shape[3]\n    nthread_tx = max_threads\n    nthread_bx = in_height // max_threads + 1\n    nthread_ty = max_threads\n    nthread_by = in_width // max_threads + 1\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(ty, \"thread_extent\", nthread_ty)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    ib.scope_attr(by, \"thread_extent\", nthread_by)\n\n    num_sizes = len(sizes)\n    num_ratios = len(ratios)\n    size_ratio_concat = sizes + ratios\n    steps_h = steps[0] if steps[0] > 0 else 1.0 / in_height\n    steps_w = steps[1] if steps[1] > 0 else 1.0 / in_width\n    offset_h = offsets[0]\n    offset_w = offsets[1]\n\n    i = bx * max_threads + tx\n    j = by * max_threads + ty\n    with ib.if_scope((i < in_height)):\n        with ib.if_scope((j < in_width)):\n            center_h = (i + offset_h) * steps_h\n            center_w = (j + offset_w) * steps_w\n\n            for k in range(num_sizes + num_ratios - 1):\n                w = if_then_else(\n                    k < num_sizes,\n                    float(size_ratio_concat[k]) * in_height / in_width / 2.0,\n                    float(size_ratio_concat[0])\n                    * in_height\n                    / in_width\n                    * math.sqrt(size_ratio_concat[k + 1])\n                    / 2.0,\n                )\n                h = if_then_else(\n                    k < num_sizes,\n                    size_ratio_concat[k] / 2.0,\n                    size_ratio_concat[0] / math.sqrt(size_ratio_concat[k + 1]) / 2.0,\n                )\n                count = (\n                    i * in_width * (num_sizes + num_ratios - 1)\n                    + j * (num_sizes + num_ratios - 1)\n                    + k\n                ) * 4\n                p_out[count] = center_w - w\n                p_out[count + 1] = center_h - h\n                p_out[count + 2] = center_w + w\n                p_out[count + 3] = center_h + h\n\n    body = ib.get()\n    return body\n\n\ndef multibox_prior(data, sizes=(1,), ratios=(1,), steps=(-1, -1), offsets=(0.5, 0.5), clip=False):\n    \"\"\"Generate prior(anchor) boxes from data, sizes and ratios.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, c_in, h_in, w_in]]\n\n    sizes : tuple of float\n        Tuple of sizes for anchor boxes.\n\n    ratios : tuple of float\n        Tuple of ratios for anchor boxes.\n\n    steps : Tuple of float\n        Priorbox step across y and x, -1 for auto calculation.\n\n    offsets : tuple of int\n        Priorbox center offsets, y and x respectively.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        3-D tensor with shape [1, h_in * w_in * (num_sizes + num_ratios - 1), 4]\n    \"\"\"\n    num_sizes = len(sizes)\n    num_ratios = len(ratios)\n    oshape = (1, data.shape[2] * data.shape[3] * (num_sizes + num_ratios - 1), 4)\n    out = te.extern(\n        oshape,\n        [data],\n        lambda ins, outs: multibox_prior_ir(ins[0], outs[0], sizes, ratios, steps, offsets),\n        tag=\"multibox_prior\",\n    )\n    if clip:\n        out = topi.clip(out, 0, 1)\n    return out\n\n\ndef transform_loc_pre(cls_prob, valid_count, temp_valid_count, temp_cls_id, temp_score, threshold):\n    \"\"\"Low level IR routing for transform location data preparation.\n\n    Parameters\n    ----------\n    cls_prob : Buffer\n        Buffer of class probabilities.\n\n    valid_count : Buffer\n        Buffer of number of valid output boxes.\n\n    temp_valid_count : Buffer\n        Output intermediate result buffer\n\n    temp_cls_id : Buffer\n        Output intermediate result buffer\n\n    temp_score : Buffer\n        Output buffer\n\n    threshold : float\n        Threshold to be a positive prediction.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch_size = cls_prob.shape[0]\n    num_classes = cls_prob.shape[1]\n    num_anchors = cls_prob.shape[2]\n\n    ib = tvm.tir.ir_builder.create()\n\n    cls_prob = ib.buffer_ptr(cls_prob)\n    cls_id = ib.buffer_ptr(temp_cls_id)\n    valid_count = ib.buffer_ptr(valid_count)\n    temp_valid_count = ib.buffer_ptr(temp_valid_count)\n    score = ib.buffer_ptr(temp_score)\n\n    threshold = tvm.tir.FloatImm(\"float32\", threshold)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = (batch_size * num_anchors) // max_threads + 1\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    tid = bx * max_threads + tx\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    with ib.if_scope(tid < batch_size * num_anchors):\n        i = idxd(tid, num_anchors)\n        j = idxm(tid, num_anchors)\n        valid_count[i] = 0\n        score[tid] = -1.0\n        cls_id[tid] = 0\n        with ib.for_range(0, num_classes - 1) as k:\n            temp = cls_prob[i * num_classes * num_anchors + (k + 1) * num_anchors + j]\n            cls_id[tid] = if_then_else(temp > score[tid], k + 1, cls_id[tid])\n            score[tid] = tvm.te.max(temp, score[tid])\n        with ib.if_scope(tvm.tir.all(cls_id[tid] > 0, score[tid] < threshold)):\n            cls_id[tid] = 0\n        with ib.if_scope(cls_id[tid] > 0):\n            temp_valid_count[tid] = 1\n        with ib.else_scope():\n            temp_valid_count[tid] = 0\n\n        with ib.if_scope(tid < batch_size):\n            with ib.for_range(0, num_anchors) as k:\n                with ib.if_scope(k > 0):\n                    temp_valid_count[tid * num_anchors + k] += temp_valid_count[\n                        tid * num_anchors + k - 1\n                    ]\n            valid_count[i] = temp_valid_count[tid * num_anchors + num_anchors - 1]\n\n    return ib.get()\n\n\ndef transform_loc_ir(\n    loc_pred,\n    anchor,\n    temp_valid_count,\n    temp_cls_id,\n    temp_score,\n    out,\n    clip,\n    variances,\n    batch_size,\n    num_anchors,\n):\n    \"\"\"Low level IR routing for transform location in multibox_detection operator.\n\n    Parameters\n    ----------\n    loc_pred : Buffer\n        Buffer of location regression predictions.\n\n    anchor : Buffer\n        Buffer of prior anchor boxes.\n\n    temp_valid_count : Buffer\n        Intermediate result buffer.\n\n    temp_cls_id : Buffer\n        Intermediate result buffer.\n\n    temp_score : Buffer\n        Input buffer which stores intermediate results.\n\n    out : Buffer\n        Output buffer.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    variances : tuple of float\n        Variances to be decoded from box regression output.\n\n    batch_size : int\n        Batch size\n\n    num_anchors : int\n        Number of anchors\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def transform_loc(loc, loc_base_idx, anchor, anchor_base_idx, clip, vx, vy, vw, vh):\n        \"\"\"Transform prior anchor box to output box through location predictions.\"\"\"\n        al = anchor[anchor_base_idx]\n        at = anchor[anchor_base_idx + 1]\n        ar = anchor[anchor_base_idx + 2]\n        ab = anchor[anchor_base_idx + 3]\n        aw = ar - al\n        ah = ab - at\n        ax = (al + ar) / 2.0\n        ay = (at + ab) / 2.0\n        px = loc[loc_base_idx]\n        py = loc[loc_base_idx + 1]\n        pw = loc[loc_base_idx + 2]\n        ph = loc[loc_base_idx + 3]\n        ox = px * vx * aw + ax\n        oy = py * vy * ah + ay\n        ow = exp(pw * vw) * aw / 2.0\n        oh = exp(ph * vh) * ah / 2.0\n        return (\n            tvm.tir.if_then_else(clip, tvm.te.max(0.0, tvm.te.min(1.0, ox - ow)), ox - ow),\n            tvm.tir.if_then_else(clip, tvm.te.max(0.0, tvm.te.min(1.0, oy - oh)), oy - oh),\n            tvm.tir.if_then_else(clip, tvm.te.max(0.0, tvm.te.min(1.0, ox + ow)), ox + ow),\n            tvm.tir.if_then_else(clip, tvm.te.max(0.0, tvm.te.min(1.0, oy + oh)), oy + oh),\n        )\n\n    ib = tvm.tir.ir_builder.create()\n\n    loc_pred = ib.buffer_ptr(loc_pred)\n    anchor = ib.buffer_ptr(anchor)\n    temp_valid_count = ib.buffer_ptr(temp_valid_count)\n    cls_id = ib.buffer_ptr(temp_cls_id)\n    score = ib.buffer_ptr(temp_score)\n    out_loc = ib.buffer_ptr(out)\n\n    max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = (batch_size * num_anchors) // max_threads + 1\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n    ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n    tid = bx * max_threads + tx\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    with ib.if_scope(tid < batch_size * num_anchors):\n        i = idxd(tid, num_anchors)\n        j = idxm(tid, num_anchors)\n\n        with ib.if_scope(cls_id[tid] > 0):\n            with ib.if_scope(tid == 0):\n                out_base_idx = i * num_anchors * 6\n                out_loc[out_base_idx] = cls_id[tid] - 1.0\n                out_loc[out_base_idx + 1] = score[tid]\n                (\n                    out_loc[out_base_idx + 2],\n                    out_loc[out_base_idx + 3],\n                    out_loc[out_base_idx + 4],\n                    out_loc[out_base_idx + 5],\n                ) = transform_loc(\n                    loc_pred,\n                    tid * 4,\n                    anchor,\n                    j * 4,\n                    clip,\n                    variances[0],\n                    variances[1],\n                    variances[2],\n                    variances[3],\n                )\n            with ib.else_scope():\n                out_base_idx = i * num_anchors * 6 + temp_valid_count[tid - 1] * 6\n                out_loc[out_base_idx] = cls_id[tid] - 1.0\n                out_loc[out_base_idx + 1] = score[tid]\n                (\n                    out_loc[out_base_idx + 2],\n                    out_loc[out_base_idx + 3],\n                    out_loc[out_base_idx + 4],\n                    out_loc[out_base_idx + 5],\n                ) = transform_loc(\n                    loc_pred,\n                    tid * 4,\n                    anchor,\n                    j * 4,\n                    clip,\n                    variances[0],\n                    variances[1],\n                    variances[2],\n                    variances[3],\n                )\n\n    return ib.get()\n\n\ndef multibox_transform_loc(\n    cls_prob, loc_pred, anchor, clip=True, threshold=0.01, variances=(0.1, 0.1, 0.2, 0.2)\n):\n    \"\"\"Location transformation for multibox detection\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        Class probabilities.\n\n    loc_pred : tvm.te.Tensor\n        Location regression predictions.\n\n    anchor : tvm.te.Tensor\n        Prior anchor boxes.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    threshold : float\n        Threshold to be a positive prediction.\n\n    variances : tuple of float\n        Variances to be decoded from box regression output.\n\n    Returns\n    -------\n    ret : tuple of tvm.te.Tensor composed of\n\n    out : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_anchors, 6)\n\n    valid_count : tvm.te.Tensor\n        1-D tensor with shape (batch_size,), number of valid anchor boxes.\n    \"\"\"\n    batch_size = cls_prob.shape[0]\n    num_anchors = cls_prob.shape[2]\n    oshape = (batch_size, num_anchors, 6)\n    # Define data alignment for intermediate buffer\n    valid_count_dtype = \"int32\"\n    out_loc_dtype = loc_pred.dtype\n\n    valid_count_buf = tvm.tir.decl_buffer(\n        (batch_size,), valid_count_dtype, \"valid_count_buf\", data_alignment=4\n    )\n    loc_pred_buf = tvm.tir.decl_buffer(\n        loc_pred.shape, loc_pred.dtype, \"loc_pred_buf\", data_alignment=8\n    )\n    anchor_buf = tvm.tir.decl_buffer(anchor.shape, anchor.dtype, \"anchor_buf\", data_alignment=8)\n\n    temp_valid_count_buf = tvm.tir.decl_buffer(\n        (\n            batch_size,\n            num_anchors,\n        ),\n        valid_count_dtype,\n        \"temp_valid_count\",\n        data_alignment=8,\n    )\n    temp_cls_id_buf = tvm.tir.decl_buffer(\n        (\n            batch_size,\n            num_anchors,\n        ),\n        valid_count_dtype,\n        \"temp_cls_id\",\n        data_alignment=8,\n    )\n    temp_score_buf = tvm.tir.decl_buffer(\n        (\n            batch_size,\n            num_anchors,\n        ),\n        cls_prob.dtype,\n        \"temp_score\",\n        data_alignment=8,\n    )\n\n    valid_count, temp_valid_count, temp_cls_id, temp_score = te.extern(\n        [\n            (batch_size,),\n            (\n                batch_size,\n                num_anchors,\n            ),\n            (\n                batch_size,\n                num_anchors,\n            ),\n            (\n                batch_size,\n                num_anchors,\n            ),\n        ],\n        [cls_prob],\n        lambda ins, outs: transform_loc_pre(ins[0], outs[0], outs[1], outs[2], outs[3], threshold),\n        dtype=[valid_count_dtype, valid_count_dtype, valid_count_dtype, cls_prob.dtype],\n        out_buffers=[valid_count_buf, temp_valid_count_buf, temp_cls_id_buf, temp_score_buf],\n        tag=\"multibox_transform_loc_phase_one\",\n    )\n\n    out_loc = te.extern(\n        [oshape],\n        [loc_pred, anchor, temp_valid_count, temp_cls_id, temp_score],\n        lambda ins, outs: transform_loc_ir(\n            ins[0],\n            ins[1],\n            ins[2],\n            ins[3],\n            ins[4],\n            outs[0],\n            clip,\n            variances,\n            batch_size,\n            num_anchors,\n        ),\n        in_buffers=[\n            loc_pred_buf,\n            anchor_buf,\n            temp_valid_count_buf,\n            temp_cls_id_buf,\n            temp_score_buf,\n        ],\n        dtype=[out_loc_dtype],\n        tag=\"multibox_transform_loc\",\n    )\n\n    return [out_loc, valid_count]\n\n\ndef multibox_detection(\n    cls_prob,\n    loc_pred,\n    anchor,\n    clip=True,\n    threshold=0.01,\n    nms_threshold=0.5,\n    force_suppress=False,\n    variances=(0.1, 0.1, 0.2, 0.2),\n    nms_topk=-1,\n):\n    \"\"\"Convert multibox detection predictions.\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        Class probabilities.\n\n    loc_pred : tvm.te.Tensor\n        Location regression predictions.\n\n    anchor : tvm.te.Tensor\n        Prior anchor boxes.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    nms_threshold : float\n        Non-maximum suppression threshold.\n\n    force_suppress : boolean\n        Whether to suppress all detections regardless of class_id.\n\n    threshold : float\n        Threshold to be a positive prediction.\n\n    variances : tuple of float\n        Variances to be decoded from box regression output.\n\n    nms_topk : int\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_anchors, 6)\n    \"\"\"\n    inter_out = multibox_transform_loc(cls_prob, loc_pred, anchor, clip, threshold, variances)\n    out = non_max_suppression(\n        inter_out[0],\n        inter_out[1],\n        inter_out[1],\n        max_output_size=-1,\n        iou_threshold=nms_threshold,\n        force_suppress=force_suppress,\n        top_k=nms_topk,\n        return_indices=False,\n    )\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/stft.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks, unused-argument\n\"\"\"STFT operator\"\"\"\nfrom math import pi\nimport tvm\nfrom tvm import te, tir\nfrom ..utils import ceil_div\n\n\ndef _get_max_threads(batch_row):\n    max_threads = tvm.target.Target.current(allow_none=False).max_num_threads\n    return tir.min(batch_row, max_threads)\n\n\ndef stft(\n    data,\n    n_fft,\n    hop_length,\n    win_length,\n    window,\n    normalized,\n    onesided,\n    output_shape,\n):\n    \"\"\"\n    The STFT computes the Fourier transform of short overlapping windows of the input.\n    This gives frequency components of the signal as they change over time.\n    Parameters\n    ----------\n    data : relay.Expr\n        Either a 1-D tensor or a 2-D batch tensor.\n    n_fft : int\n        The size of Fourier transform\n    hop_length : int\n        The distance between neighboring sliding window frames\n    win_length : int\n        The size of window frame and STFT filter\n    window : relay.Expr\n        A 1-D tensor window frame\n    normalized : bool\n        Whether to return the normalized STFT results\n    onesided : bool\n        Whether to return onesided result or fill with conjugate symmetry\n    Returns\n    -------\n    output : relay.Expr\n        Tensor containing the STFT result\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [1, 2, 3, 4, 5, 6]\n        window = [4, 3, 2]\n        [n_fft, hop_length, win_length, normalized, onesided] = [3, 3, 3, False, True]\n        relay.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n        -> [[[15.0000,  0.0000], [34.0000,  0.0000]], [[ 4.5000,  0.8660], [ 1.0000, -1.7321]]]\n    \"\"\"\n\n    def gen_ir(\n        data_ptr,\n        n_fft,\n        hop_length,\n        win_length,\n        window_ptr,\n        normalized,\n        onesided,\n        output_ptr,\n    ):\n        ib = tir.ir_builder.create()\n        data = ib.buffer_ptr(data_ptr)\n        window = ib.buffer_ptr(window_ptr)\n        output = ib.buffer_ptr(output_ptr)\n        max_threads = _get_max_threads(output_ptr.shape[0] * output_ptr.shape[1])\n        output_size = output_ptr.shape[0] * output_ptr.shape[1] * output_ptr.shape[2]\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(output_size, max_threads)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            tid = bx * max_threads + tx\n\n            with ib.if_scope(tid < output_size):\n                matrix_size = output_ptr.shape[1] * output_ptr.shape[2]\n                batch = tir.floordiv(tid, matrix_size)\n                row = tir.floordiv(tir.indexmod(tid, matrix_size), output_ptr.shape[2])\n                col = tir.indexmod(tir.indexmod(tid, matrix_size), output_ptr.shape[2])\n                output[batch, row, col, 0] = tir.Cast(data_ptr.dtype, 0)\n                output[batch, row, col, 1] = tir.Cast(data_ptr.dtype, 0)\n                with ib.for_range(0, win_length) as wlen:\n                    output[batch, row, col, 0] += (\n                        window[wlen]\n                        * data[batch, col * hop_length + wlen]\n                        * tir.cos(2 * pi * row * wlen / win_length)\n                    )\n                    output[batch, row, col, 1] -= (\n                        window[wlen]\n                        * data[batch, col * hop_length + wlen]\n                        * tir.sin(2 * pi * row * wlen / win_length)\n                    )\n                with ib.if_scope(normalized):\n                    output[batch, row, col, 0] /= tir.sqrt(tir.const(n_fft, \"float32\"))\n                    output[batch, row, col, 1] /= tir.sqrt(tir.const(n_fft, \"float32\"))\n\n        return ib.get()\n\n    output_buf = tir.decl_buffer(output_shape, data.dtype, \"output_buf\")\n\n    return te.extern(\n        output_shape,\n        [data, window],\n        lambda ins, outs: gen_ir(\n            ins[0], n_fft, hop_length, win_length, ins[1], normalized, onesided, outs[0]\n        ),\n        dtype=[data.dtype],\n        out_buffers=[output_buf],\n        name=\"stft_cuda\",\n        tag=\"stft_cuda\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/tensor_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unnecessary-lambda, too-many-arguments\n\"\"\"Tensor intrinsics on CUDA.\"\"\"\nimport tvm\nfrom tvm import te\nfrom ..utils import is_target\n\n\ndef dp4a(x_scope=\"local\", y_scope=\"local\", z_scope=\"local\", dtypes=(\"int8\", \"int8\")):\n    \"\"\"\n    Int8 dot product reduced by every 4 elements using __dp4a\n\n    Parameters\n    ----------\n    x_scope : str, optional\n        The storage scope of buffer for lhs\n    y_scope : str, optional\n        The storage scope of buffer for rhs\n    z_scope : str, optional\n        The storage scope of buffer for result\n    dtypes:  tuple of strs, optional\n        The dtype of x and y\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The dp4a TensorIntrin that can be used in tensorizing schedule.\n    \"\"\"\n\n    n = 4  # dp4a requires operands packed by 4\n    result_dtype = \"int32\" if dtypes[1] == \"int8\" else \"uint32\"\n\n    x = te.placeholder((n,), name=\"x\", dtype=dtypes[0])\n    y = te.placeholder((n,), name=\"y\", dtype=dtypes[1])\n\n    k = te.reduce_axis((0, n), name=\"rc\")\n\n    z = te.compute(\n        (1,), lambda i: te.sum(x[k].astype(result_dtype) * y[k].astype(result_dtype), axis=[k])\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            xx, yy = ins\n            zz = outs[0]\n            zz_dtype = zz.dtype\n\n            if index == 1:\n                return zz.vstore(0, tvm.tir.const(0, zz_dtype))\n\n            ib = tvm.tir.ir_builder.create()\n\n            vec_x_dtype = \"int8x4\" if xx.dtype == \"int8\" else \"uint8x4\"\n            vec_y_dtype = \"int8x4\" if yy.dtype == \"int8\" else \"uint8x4\"\n\n            vec_x = xx.vload(0, dtype=vec_x_dtype)\n            vec_y = yy.vload(0, dtype=vec_y_dtype)\n            prev_z = 0 if index == 0 else zz.vload(0)\n\n            if is_target(\"rocm\"):\n                # TODO(masahi): Here we are assuming that we are compiling for gfx10 or later\n                # We can refine the specification for dot product on rocm if needed later.\n\n                # We can just use \"llvm.amdgcn.udot4\" for u8u8u32, but it is not tested.\n                assert (\n                    dtypes[0] == \"int8\" and dtypes[0] == \"int8\"\n                ), \"u8u8u32 dot product for rocm not supported yet\"\n\n                new_z = tvm.tir.call_llvm_pure_intrin(\n                    zz_dtype,\n                    \"llvm.amdgcn.sdot4\",\n                    tvm.tir.const(4, \"uint32\"),\n                    tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", vec_x),\n                    tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", vec_y),\n                    prev_z,\n                    True,\n                )\n            else:\n                new_z = tvm.tir.call_pure_extern(zz_dtype, \"__dp4a\", vec_x, vec_y, prev_z)\n\n            ib.emit(zz.vstore(0, new_z))\n\n            return ib.get()\n\n        return _instr(0), _instr(1), _instr(2)  # body, reset, update\n\n    default_buffer_params = {\"data_alignment\": 4, \"offset_factor\": 1}\n    scopes = {x: x_scope, y: y_scope, z: z_scope}\n    binds = {\n        t: tvm.tir.decl_buffer(\n            t.shape, t.dtype, t.op.name, scope=scopes[t], **default_buffer_params\n        )\n        for t in [x, y, z]\n    }\n\n    return te.decl_tensor_intrin(\n        z.op, _intrin_func, binds=binds, default_buffer_params=default_buffer_params\n    )\n\n\ndef intrin_wmma_load_matrix_A(strides_dst, strides_from, shape, layout, A_shape, C_shape, in_dtype):\n    \"\"\"Intrin function for loading data from shared memory to wmma.matrix_a\"\"\"\n    wmma_m, wmma_n, wmma_k = shape\n\n    A = te.placeholder(A_shape, name=\"A\", dtype=in_dtype)\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"shared\", strides=strides_from, data_alignment=32, offset_factor=8\n    )\n    C = te.compute(C_shape, lambda *i: A(*i), name=\"C\")\n    BC = tvm.tir.decl_buffer(\n        C.shape,\n        C.dtype,\n        scope=\"wmma.matrix_a\",\n        strides=strides_dst,\n        data_alignment=32,\n        offset_factor=8,\n    )\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        row = wmma_m * wmma_k\n        warp_index = BC.elem_offset // row + BC.elem_offset % row // wmma_k\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_load_matrix_sync\",\n                BC.data,\n                wmma_m,\n                wmma_n,\n                wmma_k,\n                warp_index,\n                BA.access_ptr(\"r\"),\n                strides_from[0],\n                layout,\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_load_matrix_W(strides_dst, strides_from, shape, layout, A_shape, C_shape, in_dtype):\n    \"\"\"Intrin function for loading data from shared memory to wmma.matrix_b\"\"\"\n    wmma_m, wmma_n, wmma_k = shape\n\n    A = te.placeholder(A_shape, name=\"A\", dtype=in_dtype)\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"shared\", strides=strides_from, data_alignment=32, offset_factor=8\n    )\n    C = te.compute(C_shape, lambda *i: A(*i), name=\"C\")\n    BC = tvm.tir.decl_buffer(\n        C.shape,\n        C.dtype,\n        scope=\"wmma.matrix_b\",\n        strides=strides_dst,\n        data_alignment=32,\n        offset_factor=8,\n    )\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        row = wmma_n * wmma_k\n        warp_index = BC.elem_offset // row + BC.elem_offset % row // wmma_n\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_load_matrix_sync\",\n                BC.data,\n                wmma_m,\n                wmma_n,\n                wmma_k,\n                warp_index,\n                BA.access_ptr(\"r\"),\n                strides_from[0],\n                layout,\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_store_matrix(strides_dst, strides_from, shape, out_dtype, A_shape, C_shape):\n    \"\"\"Intrin function for storing the results from wmma.accumulator to shared\"\"\"\n    wmma_m, wmma_n, wmma_k = shape\n    A = te.placeholder(A_shape, name=\"A\", dtype=out_dtype)\n    BA = tvm.tir.decl_buffer(\n        A.shape,\n        A.dtype,\n        scope=\"wmma.accumulator\",\n        strides=strides_from,\n        data_alignment=32,\n        offset_factor=8,\n    )\n    C = te.compute(C_shape, lambda *i: A(*i), name=\"C\")\n    BC = tvm.tir.decl_buffer(\n        C.shape, C.dtype, scope=\"shared\", strides=strides_dst, data_alignment=32, offset_factor=8\n    )\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        row = wmma_m * wmma_n\n        warp_index = BA.elem_offset // row + BA.elem_offset % row // wmma_n\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_store_matrix_sync\",\n                BA.data,\n                wmma_m,\n                wmma_n,\n                wmma_k,\n                warp_index,\n                BC.access_ptr(\"w\"),\n                strides_dst[0],\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_gemm(AL_gemm, WL_gemm, CL_compute, strides_A, strides_W, strides_Conv, shape):\n    \"\"\"Intrin for wmma fill_fragment and mma_sync\n\n    Parameters\n    ----------\n    AL_gemm : tvm.te.placeholder\n        wmma matrix A\n    WL_gemm : tvm.te.placeholder\n        wmma matrix B\n    CL_compute : tvm.te.compute\n        The definition of wmma gemm\n    \"\"\"\n    wmma_m, wmma_n, wmma_k = shape\n    A = AL_gemm\n    B = WL_gemm\n    C = CL_compute\n\n    BA = tvm.tir.decl_buffer(\n        A.shape,\n        A.dtype,\n        name=\"BA\",\n        scope=\"wmma.matrix_a\",\n        data_alignment=32,\n        offset_factor=8,\n        strides=strides_A,\n    )\n    BB = tvm.tir.decl_buffer(\n        B.shape,\n        B.dtype,\n        name=\"BB\",\n        scope=\"wmma.matrix_b\",\n        data_alignment=32,\n        offset_factor=8,\n        strides=strides_W,\n    )\n    BC = tvm.tir.decl_buffer(\n        C.shape,\n        C.dtype,\n        name=\"BC\",\n        scope=\"wmma.accumulator\",\n        data_alignment=32,\n        offset_factor=8,\n        strides=strides_Conv,\n    )\n\n    def intrin_func(ins, outs):\n        BA, BB = ins\n        (BC,) = outs\n\n        def warp_idnex(offset, row, col):\n            row = row * col\n            return offset // row + offset % row // col\n\n        warp_index_A = warp_idnex(BA.elem_offset, wmma_m, wmma_k)\n        warp_index_B = warp_idnex(BB.elem_offset, wmma_k, wmma_n)\n        warp_index_C = warp_idnex(BC.elem_offset, wmma_m, wmma_n)\n\n        def init():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_fill_fragment\",\n                    BC.data,\n                    wmma_m,\n                    wmma_n,\n                    wmma_k,\n                    warp_index_C,\n                    0.0,\n                )\n            )\n            return ib.get()\n\n        def update():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_mma_sync\",\n                    BC.data,\n                    warp_index_C,\n                    BA.data,\n                    warp_index_A,\n                    BB.data,\n                    warp_index_B,\n                    BC.data,\n                    warp_index_C,\n                )\n            )\n            return ib.get()\n\n        return update(), init(), update()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, B: BB, C: BC})\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/tensorcore_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"Tensorcore alter op and legalize functions for cuda backend\"\"\"\n\nimport logging\nimport math\nfrom tvm import relay, tir\n\nfrom .. import nn\n\nlogger = logging.getLogger(\"topi\")\n\n\n@nn.batch_matmul_legalize.register(\"cuda\")\ndef _batch_matmul_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes batch_matmul op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    arg_types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Collect the input tensors.\n    x_tensor, y_tensor = arg_types[0], arg_types[1]\n    dtype = x_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    x, y = inputs\n\n    B, M, K = x_tensor.shape\n    B, N, K = y_tensor.shape\n    if (\n        isinstance(B, tir.expr.Any)\n        or isinstance(M, tir.expr.Any)\n        or isinstance(K, tir.expr.Any)\n        or isinstance(N, tir.expr.Any)\n    ):\n        # Dynamic shape do not support alter op layout now\n        return None\n\n    M = M.value\n    K = K.value\n    N = N.value\n\n    # Pad input and output channels to use tensorcore schedule.\n    if dtype in [\"float16\", \"int8\", \"uint8\"]:\n        # The shape of (M, K, N) must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32)\n        if (\n            (M % 8 == 0 and K % 16 == 0 and N % 32 == 0)\n            or (M % 16 == 0 and K % 16 == 0 and N % 16 == 0)\n            or (M % 32 == 0 and K % 16 == 0 and N % 8 == 0)\n        ):\n            # no need to pad\n            return None\n        candidates = [(16, 16, 16), (32, 16, 8), (8, 16, 32)]\n    elif dtype in [\"int4\", \"uint4\"]:\n        if M % 8 == 0 and K % 32 == 0 and N % 8 == 0:\n            # no need to pad\n            return None\n\n        candidates = [(8, 32, 8)]\n    else:\n        return None\n\n    (dm, dk, dn), extra_flops = pad_to_tensorcore(M, K, N, candidates)\n\n    if extra_flops > 2:\n        logger.info(\"batch_matmul pad_to_tensorcore skipped, extra_flops %s\", extra_flops)\n        return None\n\n    logger.info(\"batch_matmul pad_to_tensorcore, extra_flops %s\", extra_flops)\n    x_ = relay.nn.pad(x, pad_width=((0, 0), (0, dm), (0, dk))) if dm or dk else x\n    y_ = relay.nn.pad(y, pad_width=((0, 0), (0, dn), (0, dk))) if dn or dk else y\n    out_ = relay.nn.batch_matmul(x_, y_, attrs.out_dtype)\n    out = (\n        relay.strided_slice(out_, begin=[0, 0, 0], end=[x.value for x in output_tensor.shape])\n        if dm or dn\n        else out_\n    )\n    return out\n\n\n@nn.dense_legalize.register(\"cuda\")\ndef _dense_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes dense op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    # Collect the input tensors.\n    x_tensor, y_tensor = arg_types[0], arg_types[1]\n    dtype = x_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    x, y = inputs\n\n    M, K = x_tensor.shape\n    N, K = y_tensor.shape\n    try:\n        M = M.value\n        K = K.value\n        N = N.value\n    except AttributeError:\n        # todo: deal with unfixed shape when compiling wdl model\n        return None\n\n    # Pad input and output channels to use tensorcore schedule.\n    if dtype in [\"float16\", \"int8\", \"uint8\"]:\n        # The shape of (M, K, N) must be multiple of (16, 16, 16) or (32, 16, 8) or (8, 16, 32)\n        if (\n            (M % 8 == 0 and K % 16 == 0 and N % 32 == 0)\n            or (M % 16 == 0 and K % 16 == 0 and N % 16 == 0)\n            or (M % 32 == 0 and K % 16 == 0 and N % 8 == 0)\n        ):\n            # no need to pad\n            return None\n\n        candidates = [(16, 16, 16), (32, 16, 8), (8, 16, 32)]\n    elif dtype in [\"int4\", \"uint4\"]:\n        if M % 8 == 0 and K % 32 == 0 and N % 8 == 0:\n            # no need to pad\n            return None\n        candidates = [(8, 32, 8)]\n    else:\n        return None\n\n    (dm, dk, dn), extra_flops_ratio = pad_to_tensorcore(M, K, N, candidates)\n    skip_pad = extra_flops_ratio > 2\n\n    if skip_pad and dtype in [\"int8\", \"uint8\"]:\n        skip_pad = False\n        # If tensorcore schedule padding fails, pad to nearest upward 4x4x4 as long as\n        # the additional flops ratio isn't double or more.\n        # Note that 4x4x4 is invalid for tensorcore scheduling, but padding upwards to 4x4x4\n        # doesn't hurt if tensorcore padding has already failed.\n        if M % 4 == 0 and K % 4 == 0 and N % 4 == 0:\n            # No need to pad\n            return None\n        (dm, dk, dn) = _pad_to(M, K, N, (4, 4, 4))\n        extra_flops_ratio = _extra_flops(M, K, N, dm, dk, dn) / (M * K * N)\n        skip_pad = extra_flops_ratio > 2\n\n    if skip_pad:\n        logger.info(\"dense pad_to_tensorcore skipped, extra_flops_ratio %s\", extra_flops_ratio)\n        return None\n\n    logger.info(\"dense pad_to_tensorcore, extra_flops_ratio %s\", extra_flops_ratio)\n\n    x_ = relay.nn.pad(x, pad_width=((0, dm), (0, dk))) if dm or dk else x\n    y_ = relay.nn.pad(y, pad_width=((0, dn), (0, dk))) if dn or dk else y\n\n    # If units is explicitly specified, it is used to compute the output shape.\n    # We need to update units after padding to prevent a type error.\n    if attrs[\"units\"] is not None:\n        new_attrs[\"units\"] = N + dn\n\n    out_ = relay.nn.dense(x_, y_, **new_attrs)\n    out = (\n        relay.strided_slice(out_, begin=[0, 0], end=[x.value for x in output_tensor.shape])\n        if dm or dn\n        else out_\n    )\n    return out\n\n\ndef pad_to_tensorcore(M, K, N, candidates):\n    \"\"\"pad shape to enable tensorcore\"\"\"\n    flops = M * K * N\n    extra_flops = math.inf\n    best_pad = (0, 0, 0)\n    for padding in candidates:\n        dm, dk, dn = _pad_to(M, K, N, padding)\n        e = _extra_flops(M, K, N, dm, dk, dn)\n        # print(dm, dk, dn, e, flops)\n        if e < extra_flops:\n            extra_flops = e\n            best_pad = (dm, dk, dn)\n    return best_pad, extra_flops / flops\n\n\ndef _extra_flops(M, K, N, dm, dk, dn):\n    return (M + dm) * (N + dn) * (K + dk) - M * N * K\n\n\ndef _pad_to(M, K, N, PADDING):\n    dm, dk, dn = 0, 0, 0\n\n    if M % PADDING[0] != 0:\n        M_ = ((M + PADDING[0]) // PADDING[0]) * PADDING[0]\n        dm = M_ - M\n    if K % PADDING[1] != 0:\n        K_ = ((K + PADDING[1]) // PADDING[1]) * PADDING[1]\n        dk = K_ - K\n    if N % PADDING[2] != 0:\n        N_ = ((N + PADDING[2]) // PADDING[2]) * PADDING[2]\n        dn = N_ - N\n\n    return dm, dk, dn\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"CUDA implementations of transforms\"\"\"\nimport tvm\nfrom ... import te\nfrom ...target import Target\nfrom ..utils import traverse_inline\n\n\ndef schedule_transpose(outs):\n    \"\"\"Schedule a unfused transpose\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    schedule_transpose_from_existing(s, outs[0])\n    return s\n\n\ndef schedule_transpose_from_existing(s, out):\n    \"\"\"Schedule for transpose on the gpu.\n\n    Roughly follows this:\n    https://developer.nvidia.com/blog/efficient-matrix-transpose-cuda-cc/, but\n    without the padding for shared memory. For better performance, we could\n    rewrite it in tir to add the padding. Also, rewriting in tir would allow\n    use to use warp shuffles instead of shared memory (see\n    https://github.com/bryancatanzaro/trove).\n    \"\"\"\n\n    def _callback(op):\n        # pylint: disable=invalid-name\n        m, n = s[op].op.axis\n        warp_size = int(Target.current(allow_none=False).thread_warp_size)\n        no, ni = s[op].split(n, factor=warp_size)\n        mo, mi = s[op].split(m, factor=warp_size)\n        s[op].reorder(mo, no, mi, ni)\n        s[op].bind(mo, te.thread_axis(\"blockIdx.x\"))\n        s[op].bind(no, te.thread_axis(\"blockIdx.y\"))\n        c = s.cache_read(op.input_tensors[0], \"shared\", op)\n        s[c].compute_at(s[op], no)\n        thread_x = te.thread_axis(\"threadIdx.x\")\n        thread_y = te.thread_axis(\"threadIdx.y\")\n        s[op].bind(ni, thread_x)\n        # This is a hack to make the scheduling language realize that this axis\n        # can be scheduled.\n        a, _ = s[c].split(s[c].op.axis[1], factor=1)\n        s[c].bind(a, thread_x)\n        # Use 4 warps per block. Slightly faster than 1 warp per block\n        ao, _ = s[op].split(mi, nparts=4)\n        s[op].bind(ao, thread_y)\n        ao, _ = s[c].split(s[c].op.axis[0], nparts=4)\n        s[c].bind(ao, thread_y)\n\n    traverse_inline(s, out.op, _callback)\n\n\ndef _invert_permutation_ir(data, out):\n    \"\"\"Low level IR to get invert_permutation.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input data. 1-D Buffer with shape [elem_num].\n\n    out : Buffer\n        1D buffer for invert permutation result with the same shape with data.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    elem_num = data.shape[0]\n\n    irb = tvm.tir.ir_builder.create()\n    data = irb.buffer_ptr(data)\n    out = irb.buffer_ptr(out)\n\n    max_threads = int(Target.current(allow_none=False).max_num_threads)\n    nthread_tx = max_threads\n    nthread_bx = elem_num // max_threads + 1\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    block_x = te.thread_axis(\"blockIdx.x\")\n    irb.scope_attr(thread_x, \"thread_extent\", nthread_tx)\n    irb.scope_attr(block_x, \"thread_extent\", nthread_bx)\n    tid = block_x * max_threads + thread_x\n\n    with irb.if_scope(tid < elem_num):\n        r_ind = data[tid]\n        out[r_ind] = tid\n    return irb.get()\n\n\ndef invert_permutation(data):\n    \"\"\"Compute definition of invert_permutation.\n    For an output tensor y and an input tensor x, this operation computes the following:\n\n       y[x[i]] = i for i in [0, 1, ..., len(x) - 1]\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        1-D tensor\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n    \"\"\"\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"out_buf\", data_alignment=8)\n\n    out = te.extern(\n        [data.shape],\n        [data],\n        lambda ins, outs: _invert_permutation_ir(ins[0], outs[0]),\n        in_buffers=[\n            data_buf,\n        ],\n        out_buffers=[\n            out_buf,\n        ],\n        name=\"invert_permutation\",\n        tag=\"invert_permutation_gpu\",\n    )\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/unique.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Unique operator\"\"\"\nimport tvm\nfrom tvm import te, tir\nfrom ...te import hybrid\nfrom .scan import cumsum\nfrom .sort import sort, argsort\nfrom ..utils import ceil_div\n\n\ndef _get_max_threads(batch_size):\n    target = tvm.target.Target.current()\n    max_threads = tvm.target.Target.current(allow_none=False).max_num_threads\n    if \"vulkan\" in str(target) and not isinstance(batch_size, tvm.tir.IntImm):\n        # SPIR-V does not support dynamic thread group size\n        return max_threads\n    return tir.min(batch_size, max_threads)\n\n\ndef _calc_adjacent_diff_ir(data, output, binop=tir.Sub):\n    \"\"\"Low level IR to calculate adjacent difference in an 1-D array.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input 1-D Buffer.\n\n    output: Buffer\n        A buffer to store adjacent difference, of the same shape as data. The adjacent difference\n        is defined as: output[0] = 0, output[i] = binop(data[i], data[i-1])\n        where i > 0 and i < len(data).\n\n    binop: function, optional\n        A binary associative op to use for calculating adjacent difference. The function takes two\n        TIR expressions and produce a new TIR expression. By default it uses tvm.tir.Sub to\n        compute the adjacent difference.\n    \"\"\"\n    ib = tir.ir_builder.create()\n    data_ptr = ib.buffer_ptr(data)\n    output_ptr = ib.buffer_ptr(output)\n    batch_size = data.shape[0]\n    max_threads = _get_max_threads(batch_size)\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(batch_size, max_threads)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < batch_size):\n            with ib.if_scope(tid == 0):\n                output_ptr[tid] = 0\n            with ib.else_scope():\n                output_ptr[tid] = tir.Cast(output.dtype, binop(data_ptr[tid], data_ptr[tid - 1]))\n    return ib.get()\n\n\ndef _calc_adjacent_diff(data, out_dtype=\"int32\", binop=tir.Sub):\n    \"\"\"Function calculate adjacent difference in an 1-D array.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input 1-D tensor.\n\n    output_dtype : str\n        The output tensor data type.\n\n    binop: function, optional\n        A binary associative op to use for calculating difference. The function takes two\n        TIR expressions and produce a new TIR expression. By default it uses tvm.tir.Sub to\n        compute the adjacent difference.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        1-D tensor storing the adjacent difference of the input tensor. The adjacent difference\n        is defined as: output[0] = 0, output[i] = binop(data[i], data[i-1])\n        where i > 0 and i < len(data).\n    \"\"\"\n    data_buf = tir.decl_buffer(data.shape, data.dtype, \"sorted_data_buf\", data_alignment=8)\n    output_buf = tir.decl_buffer(data.shape, out_dtype, \"output_buf\", data_alignment=8)\n    return te.extern(\n        [data.shape],\n        [data],\n        lambda ins, outs: _calc_adjacent_diff_ir(ins[0], outs[0], binop=binop),\n        dtype=[out_dtype],\n        in_buffers=[data_buf],\n        out_buffers=[output_buf],\n        name=\"_calc_adjacent_diff\",\n        tag=\"_calc_adjacent_diff_gpu\",\n    )\n\n\n@hybrid.script\ndef _calc_num_unique(inc_scan):\n    \"\"\"Helper function to get the number of unique elements fron inc_scan tensor\"\"\"\n    output = output_tensor((1,), \"int32\")\n    for i in bind(\"threadIdx.x\", 1):\n        output[i] = inc_scan[inc_scan.shape[0] - 1] + int32(1)\n    return output\n\n\ndef _calc_unique_ir(\n    data, argsorted_indices, inc_scan, index_converter, unique_elements, inverse_indices, counts\n):\n    \"\"\"Low level IR to calculate unique elements, inverse indices, and counts (optional) of\n    unique elements of 1-D array.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input 1-D Buffer.\n\n    argsorted_indices : Buffer\n        A buffer that stores the argsorted indices of the input data.\n\n    inc_scan : Buffer\n        A buffer that stores the inclusive scan of the binary tir.NE adjacent difference\n        of the sorted data.\n\n    index_converter (optional) : Buffer\n        An optional index converter that transforms the unique element index\n        such that new_idx = index_converter[old_idx].\n\n    unique_elements : Buffer\n        A buffer that stores the unique elements.\n\n    inverse_indices : Buffer\n        A buffer that stores the index of each input data element in the unique element array.\n\n    counts (optional) : Buffer\n        A buffer that stores the count of each unique element.\n    \"\"\"\n    ib = tir.ir_builder.create()\n    data_ptr = ib.buffer_ptr(data)\n    argsorted_indices_ptr = ib.buffer_ptr(argsorted_indices)\n    inc_scan_ptr = ib.buffer_ptr(inc_scan)\n    unique_elements_ptr = ib.buffer_ptr(unique_elements)\n    inverse_indices_ptr = ib.buffer_ptr(inverse_indices)\n\n    index_converter_ptr = None\n    if isinstance(index_converter, tir.Buffer):\n        index_converter_ptr = ib.buffer_ptr(index_converter)\n\n    if isinstance(counts, tir.Buffer):\n        counts_ptr = ib.buffer_ptr(counts)\n        # use indices_ptr as a tmp buffer to store tids with inc_scan[tid] != inc_scan[tid-1]\n        unique_seq_indices_ptr = ib.buffer_ptr(inverse_indices)\n\n    batch_size = data.shape[0]\n    max_threads = _get_max_threads(batch_size)\n\n    # if need to return counts\n    if isinstance(counts, tir.Buffer):\n        num_unique = inc_scan_ptr[inc_scan.shape[0] - 1] + 1\n        num_elements = data.shape[0]\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(batch_size, max_threads)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            tid = bx * max_threads + tx\n            with ib.if_scope(tid < batch_size):\n                with ib.if_scope(tid == 0):\n                    unique_seq_indices_ptr[num_unique - 1] = num_elements\n                with ib.else_scope():\n                    with ib.if_scope(inc_scan_ptr[tid] != inc_scan_ptr[tid - 1]):\n                        unique_seq_indices_ptr[inc_scan_ptr[tid] - 1] = tid\n        with ib.new_scope():\n            nthread_tx = max_threads\n            nthread_bx = ceil_div(batch_size, max_threads)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            tid = bx * max_threads + tx\n            with ib.if_scope(tid < num_unique):\n                unique_idx = tid if not index_converter_ptr else index_converter_ptr[tid]\n                with ib.if_scope(tid == 0):\n                    counts_ptr[unique_idx] = unique_seq_indices_ptr[tid]\n                with ib.else_scope():\n                    counts_ptr[unique_idx] = (\n                        unique_seq_indices_ptr[tid] - unique_seq_indices_ptr[tid - 1]\n                    )\n    # calculate unique elements and inverse indices\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(batch_size, max_threads)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < batch_size):\n            data_idx = argsorted_indices_ptr[tid]\n            unique_idx = (\n                inc_scan_ptr[tid]\n                if not index_converter_ptr\n                else index_converter_ptr[inc_scan_ptr[tid]]\n            )\n            inverse_indices_ptr[data_idx] = unique_idx\n            with ib.if_scope(tid == 0):\n                unique_elements_ptr[unique_idx] = data_ptr[data_idx]\n            with ib.else_scope():\n                with ib.if_scope(inc_scan_ptr[tid] != inc_scan_ptr[tid - 1]):\n                    unique_elements_ptr[unique_idx] = data_ptr[data_idx]\n    return ib.get()\n\n\ndef _calc_first_occurence_ir(argsorted_indices, inc_scan, first_occurence):\n    \"\"\"Low level IR to calculate the first occurence of each unique element in the input data.\n\n    Parameters\n    ----------\n    argsorted_indices : Buffer\n        A buffer that stores the argsorted indices of the input data.\n\n    inc_scan : Buffer\n        A buffer that stores the inclusive scan of the binary tir.NE adjacent difference\n        of the sorted data.\n\n    first_occurence : Buffer\n        A buffer that stores the first occurence of each unique element in the input data.\n    \"\"\"\n    ib = tir.ir_builder.create()\n    argsorted_indices_ptr = ib.buffer_ptr(argsorted_indices)\n    inc_scan_ptr = ib.buffer_ptr(inc_scan)\n    first_occurence_ptr = ib.buffer_ptr(first_occurence)\n    batch_size = argsorted_indices.shape[0]\n    max_threads = _get_max_threads(batch_size)\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(batch_size, max_threads)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < batch_size):\n            first_occurence_ptr[tid] = batch_size\n    with ib.new_scope():\n        nthread_tx = max_threads\n        nthread_bx = ceil_div(batch_size, max_threads)\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n        ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n        tid = bx * max_threads + tx\n        with ib.if_scope(tid < batch_size):\n            with ib.if_scope(tid == 0):\n                first_occurence_ptr[inc_scan_ptr[tid]] = argsorted_indices_ptr[tid]\n            with ib.else_scope():\n                with ib.if_scope(inc_scan_ptr[tid] != inc_scan_ptr[tid - 1]):\n                    first_occurence_ptr[inc_scan_ptr[tid]] = argsorted_indices_ptr[tid]\n    return ib.get()\n\n\ndef unique(data, is_sorted=True, return_counts=False):\n    \"\"\"\n    Find the unique elements of a 1-D tensor. Please note `output` and `counts` are all padded to\n    have the same length of `data` and element with index >= num_unique[0] has undefined value.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        A 1-D tensor of integers.\n\n    sorted : bool\n        Whether to sort the unique elements in ascending order before returning as output.\n\n    return_counts : bool\n        Whether to return the count of each unique element.\n\n    Returns\n    -------\n    unique : tvm.te.Tensor\n        A 1-D tensor containing the unique elements of the input data tensor. The same size as\n        the input data. If there are less unique elements than input data, the end of the tensor\n        is padded with zeros.\n\n    indices : tvm.te.Tensor\n        A 1-D tensor. The same size as output. For each entry in output, it contains\n        the index of its first occurence in the input data. The end of the tensor is padded\n        with the length of the input data.\n\n    inverse_indices : tvm.te.Tensor\n        A 1-D tensor. For each entry in data, it contains the index of that data element in the\n        unique array. (Note that inverse_indices is very similar to indices if output is not\n        sorted)\n\n    num_unique : tvm.te.Tensor\n        A 1-D tensor with size=1 containing the number of unique elements in the input data tensor.\n\n    counts (optional) : tvm.te.Tensor\n        A 1-D tensor containing the count of each unique element in the output.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, False)\n        output          =  [4, 5, 1, 2, 3, ?, ?, ?]\n        indices         =  [0, 1, 2, 3, 4, ?, ?, ?]\n        inverse_indices =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique      =  [5]\n\n        [output, indices, num_unique, counts] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, True)\n        output          =  [4, 5, 1, 2, 3, ?, ?, ?]\n        indices         =  [0, 1, 2, 3, 4, ?, ?, ?]\n        inverse_indices =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique      =  [5]\n        counts          =  [2, 2, 1, 1, 2, ?, ?, ?]\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], True)\n        output          =  [1, 2, 3, 4, 5, ?, ?, ?]\n        indices         =  [2, 3, 4, 0, 1, ?, ?, ?]\n        inverse_indices =  [3, 4, 0, 1, 2, 2, 3, 4]\n        num_unique      =  [5]\n    \"\"\"\n    sorted_data = sort(data)\n    argsorted_indices = argsort(data, dtype=\"int32\")\n    # adjacent difference\n    adjacent_diff = _calc_adjacent_diff(sorted_data, out_dtype=\"int32\", binop=tir.NE)\n    # inclusive scan\n    inc_scan = cumsum(adjacent_diff, dtype=\"int32\", exclusive=0)\n    # total number of unique elements\n    num_unique_elements = _calc_num_unique(inc_scan)\n    # buffers\n    data_buf = tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    argsorted_indices_buf = tir.decl_buffer(\n        data.shape, \"int32\", \"argsorted_indices_buf\", data_alignment=8\n    )\n    inc_scan_buf = tvm.tir.decl_buffer(data.shape, \"int32\", \"inc_scan_buf\", data_alignment=8)\n    unique_elements_buf = tir.decl_buffer(\n        data.shape, data.dtype, \"unique_elements_buf\", data_alignment=8\n    )\n    inverse_indices_buf = tvm.tir.decl_buffer(\n        data.shape, \"int32\", \"inverse_indices_buf\", data_alignment=8\n    )\n    # prepare outputs\n    if return_counts:\n        counts_buf = tir.decl_buffer(data.shape, \"int32\", \"counts_buf\", data_alignment=8)\n        out_data_shape = [data.shape] * 3\n        out_buffers = [unique_elements_buf, inverse_indices_buf, counts_buf]\n        out_dtypes = [data.dtype, \"int32\", \"int32\"]\n    else:\n        out_data_shape = [data.shape] * 2\n        out_buffers = [unique_elements_buf, inverse_indices_buf]\n        out_dtypes = [data.dtype, \"int32\"]\n    # prepare inputs and fcompute\n    # calculate first occurence\n    first_occurence_buf = tir.decl_buffer(\n        data.shape, \"int32\", \"first_occurence_buf\", data_alignment=8\n    )\n    first_occurence = te.extern(\n        [data.shape],\n        [argsorted_indices, inc_scan],\n        lambda ins, outs: _calc_first_occurence_ir(ins[0], ins[1], outs[0]),\n        dtype=[\"int32\"],\n        in_buffers=[argsorted_indices_buf, inc_scan_buf],\n        out_buffers=[first_occurence_buf],\n        name=\"_calc_first_occurence\",\n        tag=\"_calc_first_occurence_gpu\",\n    )\n    if is_sorted:\n        in_data = [data, argsorted_indices, inc_scan]\n        in_buffers = [data_buf, argsorted_indices_buf, inc_scan_buf]\n        if return_counts:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, None, *outs)\n        else:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, None, *outs, None)\n        indices = first_occurence\n    else:\n        # calculate index converter by sorting unique elements by their first occurence\n        argsorted_first_occurence = argsort(first_occurence, dtype=\"int32\")\n        index_converter = argsort(argsorted_first_occurence, dtype=\"int32\")\n        index_converter_buf = tir.decl_buffer(\n            data.shape, \"int32\", \"index_converter_buf\", data_alignment=8\n        )\n        in_data = [data, argsorted_indices, inc_scan, index_converter]\n        in_buffers = [data_buf, argsorted_indices_buf, inc_scan_buf, index_converter_buf]\n        if return_counts:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, *outs)\n        else:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, *outs, None)\n        indices = sort(first_occurence)\n    outs = te.extern(\n        out_data_shape,\n        in_data,\n        fcompute,\n        dtype=out_dtypes,\n        in_buffers=in_buffers,\n        out_buffers=out_buffers,\n        name=\"_calc_unique\",\n        tag=\"_calc_unique_gpu\",\n    )\n    if return_counts:\n        return [outs[0], indices, outs[1], num_unique_elements, outs[2]]\n    return [outs[0], indices, outs[1], num_unique_elements]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/cuda/vision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, no-member, import-outside-toplevel\n\"\"\"Schedule for vision operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import cpp\nfrom .. import tag\nfrom .pooling import schedule_pool\nfrom .injective import schedule_injective_from_existing\n\n\ndef _default_schedule(outs):\n    \"\"\"Default schedule for gpu.\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        if tag.is_injective(op.tag) or op.tag in [\"bbox_score\", \"sorted_bbox\"]:\n            schedule_injective_from_existing(s, op.output(0))\n        for tensor in op.input_tensors:\n            if tensor.op.input_tensors and tensor.op not in scheduled_ops:\n                traverse(tensor.op)\n        scheduled_ops.append(op)\n\n    for o in outs:\n        traverse(o.op)\n\n    return s\n\n\ndef schedule_reorg(outs):\n    \"\"\"Schedule for reorg operator.\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of reorg\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for reorg.\n    \"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    cpp_target = cpp.TEST_create_target(target.kind.name)\n    return cpp.cuda.schedule_injective(cpp_target, outs)\n\n\ndef schedule_nms(outs):\n    \"\"\"Schedule for non-maximum suppression\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of nms\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs)\n\n\ndef schedule_multibox_prior(outs):\n    \"\"\"Schedule for multibox_prior operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of multibox_prior\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for multibox_prior.\n    \"\"\"\n    return _default_schedule(outs)\n\n\ndef schedule_multibox_transform_loc(outs):\n    \"\"\"Schedule for multibox_transform_loc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of\n      multibox_transform_loc in the format\n      of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs)\n\n\ndef schedule_multibox_detection(outs):\n    \"\"\"Schedule for multibox_detection operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of multibox_detection\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for multibox_detection.\n    \"\"\"\n    return _default_schedule(outs)\n\n\ndef schedule_roi_align(outs):\n    return schedule_pool(outs, \"NCHW\")\n\n\ndef schedule_roi_pool(outs):\n    return schedule_pool(outs, \"NCHW\")\n\n\ndef schedule_proposal(outs):\n    \"\"\"Schedule for proposal operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of proposal\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs)\n\n\ndef schedule_get_valid_counts(outs):\n    \"\"\"Schedule for get_valid_counts operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of get_valid_counts\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/einsum.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,consider-using-enumerate,redefined-outer-name\n\"\"\"Einsum operator\"\"\"\nfrom . import cpp\n\n\ndef einsum(subscripts, *operand):\n    \"\"\"Evaluates the Einstein summation convention on the operands.\n\n    Parameters\n    ----------\n    subscripts : string\n        Specifies the subscripts for summation as comma separated list of subscript labels.\n        An implicit (classical Einstein summation) calculation is performed unless the\n        explicit indicator \u2018->\u2019 is included as well as subscript labels of the precise\n        output form.\n\n    a_tuple : tuple of tvm.te.Tensor\n        These are the Tensors for the operation.\n        The only difference of einsum between in tvm and numpy is it needs an extra brackets\n        for the tensors. For example, topi.einsum(\"ij, jk -> ik\", (A, B)).\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The calculation based on the Einstein summation convention.\n    \"\"\"\n\n    return cpp.einsum(subscripts, operand)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Generic declaration and schedules.\n\nThis is a recommended way of using TOPI API.\nTo use the generic schedule function, user must set\nthe current target scope using with block. See also :any:`tvm.target`\n\nExample\n-------\n.. code-block:: python\n\n  # create schedule that dispatches to topi.cuda.schedule_injective\n  with tvm.target.Target(\"cuda\"):\n    s = tvm.tir.generic.schedule_injective(outs)\n\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .nn import *\nfrom .injective import *\nfrom .extern import *\nfrom .vision import *\nfrom .sort import *\nfrom .search import *\nfrom .image import *\nfrom .math import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin\n\"\"\"Generic convolution schedules\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import relay\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\nfrom ..utils import get_const_tuple, traverse_inline\nfrom ..nn.utils import get_pad_tuple\n\n\ndef fallback_schedule_cpu_common_int8(cfg, wkl, int32_lanes, num_int8_elements):\n    \"\"\"Fallback schedule for conv2d int8 on cpu.\n    Normally the inner most pattern takes two int8/uint8 tensors\n    data[num_int8_elements] and kernel[int32_lanes, num_int8_elements],\n    produces a dot product int32/uint32 output[int32_lanes].\n\n    Parameters\n    ----------\n    int32_lanes : int\n        How many numbers of int32/uint32 will be produced using intrinsic.\n        This is related to output channel.\n    num_int8_elements : int\n        How many numbers of input int32/uint32 will be multiplied and reduced.\n        This is related to input channel.\n    \"\"\"\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    dilated_kernel_w = (wkl.kernel_w - 1) * wkl.dilation_w + 1\n    out_width = (wkl.width + pl + pr - dilated_kernel_w) // WSTR + 1\n\n    assert wkl.out_filter % int32_lanes == 0, \"wkl.out_filter=%d, int32_lanes=%d\" % (\n        wkl.out_filter,\n        int32_lanes,\n    )\n    assert wkl.in_filter % num_int8_elements == 0, \"wkl.in_filter=%d, num_int8_elements=%d\" % (\n        wkl.in_filter,\n        num_int8_elements,\n    )\n\n    oc_bn = int32_lanes if int32_lanes >= num_int8_elements else num_int8_elements\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -4):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\ndef fallback_schedule_cpu_1x1_int8(cfg, wkl, int32_lanes, num_int8_elements):\n    \"\"\"Fallback schedule for 1x1 conv2d int8 on cpu.\n    Normally the inner most pattern takes two int8/uint8 tensors\n    data[num_int8_elements] and kernel[int32_lanes, num_int8_elements],\n    produces a dot product int32/uint32 output[int32_lanes].\n\n    Parameters\n    ----------\n    int32_lanes : int\n        How many numbers of int32/uint32 will be produced using intrinsic.\n        This is related to output channel.\n    num_int8_elements : int\n        How many numbers of input int32/uint32 will be multiplied and reduced.\n        This is related to input channel.\n    \"\"\"\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    out_height = (wkl.height + pt + pb - wkl.kernel_h) // HSTR + 1\n    out_width = (wkl.width + pl + pr - wkl.kernel_w) // WSTR + 1\n\n    assert wkl.out_filter % int32_lanes == 0, \"wkl.out_filter=%d, int32_lanes=%d\" % (\n        wkl.out_filter,\n        int32_lanes,\n    )\n    assert wkl.in_filter % num_int8_elements == 0, \"wkl.in_filter=%d, num_int8_elements=%d\" % (\n        wkl.in_filter,\n        num_int8_elements,\n    )\n\n    oc_bn = int32_lanes if int32_lanes >= num_int8_elements else num_int8_elements\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -4):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    for ow_factor in range(out_width, 0, -1):\n        if out_width % ow_factor == 0:\n            for oh_factor in range(out_height, 0, -1):\n                if out_height % oh_factor == 0 and ow_factor * oh_factor < 32:\n                    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n                    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n                    cfg[\"tile_oh\"] = OtherOptionEntity(oh_factor)\n                    cfg[\"tile_ow\"] = SplitEntity([out_width // ow_factor, ow_factor])\n                    return\n    raise ValueError(\"cannot decide default schedule for workload: {}\".format(wkl))\n\n\ndef schedule_conv_NCHWc_cpu_common_int8(\n    s,\n    cfg,\n    data_vec,\n    kernel_vec,\n    conv_out,\n    last,\n    int32_lanes=16,\n    int8_elems=4,\n    intrin=None,\n    inline_fused=True,\n):\n    \"\"\"\n    Defines the schedule for INT8 for Intel and ARM machines\n    Uses the Intel/ARM intrinsics to use INT8 operations\n    More details - https://software.intel.com/en-us/articles/\n    lower-numerical-precision-deep-learning-inference-and-training\n    \"\"\"\n    if isinstance(cfg[\"tile_ow\"], int):\n        reg_n = cfg[\"tile_ow\"]\n    else:\n        reg_n = cfg[\"tile_ow\"].size[-1]\n\n    if isinstance(cfg[\"unroll_kw\"], (int, bool)):\n        unroll_kw = cfg[\"unroll_kw\"]\n    else:\n        unroll_kw = cfg[\"unroll_kw\"].val\n\n    _, _, _, _, ic_bn = get_const_tuple(data_vec.shape)\n    _, _, _, _, oc_bn = get_const_tuple(conv_out.shape)\n\n    # schedule pad\n    if isinstance(s[data_vec].op, te.tensor.ComputeOp) and \"pad\" in data_vec.op.tag:\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n        data_vec = data_vec.op.input_tensors[0]\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # only in autotuning, input data of conv2d_NCHWc will be 4-D.\n        # skip this part during tuning to make records accurate.\n        # this part will be folded during Relay fold_constant pass.\n        if isinstance(data_vec.op, te.tensor.ComputeOp):\n            s[data_vec].pragma(s[data_vec].op.axis[0], \"debug_skip_region\")\n        if isinstance(kernel_vec.op, te.tensor.ComputeOp):\n            s[kernel_vec].pragma(s[kernel_vec].op.axis[0], \"debug_skip_region\")\n    elif isinstance(kernel_vec.op, te.tensor.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        # data and kernel are not pre-computed, schedule layout transform here.\n        # this should only be used by x86 conv2d_nchw, which is for\n        # testing purpose.\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n\n        # conv2d_nchwc_int8 has 7D kernel\n        oc_chunk, ic_chunk, oh, ow, ic_block, oc_block, _ = s[kernel_vec].op.axis\n        s[kernel_vec].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n        oc_bn = cfg[\"tile_oc\"].size[-1]\n        if oc_bn > 1:\n            s[kernel_vec].vectorize(oc_block)\n        parallel_axis = s[kernel_vec].fuse(oc_chunk, oh)\n        s[kernel_vec].parallel(parallel_axis)\n\n    # schedule 5-D NCHW[x]c conv\n    C, O = conv_out, last\n    CC = s.cache_write(C, \"global\")\n\n    batch, oc_chunk, oh, ow, oc_block = s[C].op.axis\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n    s[C].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[C].fuse(batch, oc_chunk, oh)\n    s[C].vectorize(oc_block)\n    if C == O:\n        s[C].parallel(parallel_axis)\n\n    s[CC].compute_at(s[C], parallel_axis)\n    _, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n    kh, kw, ic_outer, ic_f_inner, ic_s_inner = s[CC].op.reduce_axis\n\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n\n    assert oc_bn % int32_lanes == 0, f\"oc_bn={oc_bn} % int32_lanes={int32_lanes} != 0\"\n    assert (\n        ic_bn % int8_elems == 0\n    ), f\"ic_bn={ic_bn} % int8_elems={int8_elems} != 0\"  # (u)int8 elements in (u)int32\n\n    oc_f_inner, oc_s_inner = s[CC].split(oc_block, factor=int32_lanes)\n\n    if unroll_kw:\n        s[CC].reorder(\n            oc_chunk,\n            oh,\n            ow_chunk,\n            ic_outer,\n            kh,\n            ic_f_inner,\n            kw,\n            ow_block,\n            oc_f_inner,\n            oc_s_inner,\n            ic_s_inner,\n        )\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(\n            oc_chunk,\n            oh,\n            ow_chunk,\n            ic_outer,\n            kh,\n            kw,\n            ic_f_inner,\n            ow_block,\n            oc_f_inner,\n            oc_s_inner,\n            ic_s_inner,\n        )\n\n    if intrin is not None:\n        s[CC].tensorize(oc_s_inner, intrin)\n    s[CC].unroll(ow_block)\n    s[CC].unroll(oc_f_inner)\n\n    if C != O:\n        out_ndim = len(s[O].op.axis)\n        if out_ndim == 5:\n            batch, oc_chunk, oh, ow, oc_block = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n        elif out_ndim == 4:\n            batch, oc, oh, ow = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n            oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n        else:\n            raise ValueError(\"Unsupported output ndim: %s\" % out_ndim)\n        parallel_axis = s[O].fuse(batch, oc_chunk, oh)\n        if inline_fused:\n            s[C].compute_at(s[O], ow_block)\n        else:\n            s[C].compute_at(s[O], parallel_axis)\n        s[O].vectorize(oc_block)\n        s[O].parallel(parallel_axis)\n\n    return s\n\n\ndef schedule_conv_NCHWc_cpu_1x1_int8(\n    s,\n    cfg,\n    data_vec,\n    kernel_vec,\n    conv_out,\n    last,\n    int32_lanes=16,\n    int8_elems=4,\n    intrin=None,\n    inline_fused=False,\n):\n    \"\"\"\n    Defines the 1x1 conv schedule for INT8 for Intel and ARM machines\n    Uses the Intel/ARM intrinsics to use INT8 operations\n    More details - https://software.intel.com/en-us/articles/\n    lower-numerical-precision-deep-learning-inference-and-training\n    \"\"\"\n    oh_factor, ow_factor = cfg[\"tile_oh\"].val, cfg[\"tile_ow\"].size[-1]\n    _, _, _, _, ic_bn = get_const_tuple(data_vec.shape)\n    _, _, _, _, oc_bn = get_const_tuple(conv_out.shape)\n\n    # schedule pad\n    if isinstance(s[data_vec].op, te.tensor.ComputeOp) and \"pad\" in data_vec.op.tag:\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n        data_vec = data_vec.op.input_tensors[0]\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # only in autotuning, input data of conv2d_NCHWc will be 4-D.\n        # skip this part during tuning to make records accurate.\n        # this part will be folded during Relay fold_constant pass.\n        if isinstance(data_vec.op, te.tensor.ComputeOp):\n            s[data_vec].pragma(s[data_vec].op.axis[0], \"debug_skip_region\")\n        if isinstance(kernel_vec.op, te.tensor.ComputeOp):\n            s[kernel_vec].pragma(s[kernel_vec].op.axis[0], \"debug_skip_region\")\n    elif isinstance(kernel_vec.op, te.tensor.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        # data and kernel are not pre-computed, schedule layout transform here.\n        # this should only be used by x86 conv2d_nchw, which is for\n        # testing purpose.\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n\n        # Conv2d int8 schedule has 7D kernel\n        oc_chunk, ic_chunk, oh, ow, ic_block, oc_block, _ = s[kernel_vec].op.axis\n        s[kernel_vec].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n        oc_bn = cfg[\"tile_oc\"].size[-1]\n        if oc_bn > 1:\n            s[kernel_vec].vectorize(oc_block)\n        parallel_axis = s[kernel_vec].fuse(oc_chunk, oh)\n        s[kernel_vec].parallel(parallel_axis)\n\n    C, O = conv_out, last\n    CC = s.cache_write(C, \"global\")\n\n    batch, oc_chunk, oh, ow, oc_block = s[C].op.axis\n    oh_outer, oh_inner = s[C].split(oh, factor=oh_factor)\n    ow_outer, ow_inner = s[C].split(ow, factor=ow_factor)\n    s[C].reorder(oc_chunk, oh_outer, ow_outer, oh_inner, ow_inner, oc_block)\n    s[C].vectorize(oc_block)\n\n    parallel_axis = s[C].fuse(batch, oc_chunk, oh_outer)\n    if C == O:\n        s[C].parallel(parallel_axis)\n    s[CC].compute_at(s[C], parallel_axis)  # good perf on mobilenet, but not on individuals?\n\n    _, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n    kh, kw, ic_outer, ic_f_inner, ic_s_inner = s[CC].op.reduce_axis\n\n    assert oc_bn % int32_lanes == 0\n    assert ic_bn % int8_elems == 0  # (u)int8 elements in (u)int32\n\n    oc_f_inner, oc_s_inner = s[CC].split(oc_block, factor=int32_lanes)\n\n    oh_outer, oh_inner = s[CC].split(oh, factor=oh_factor)\n    ow_outer, ow_inner = s[CC].split(ow, factor=ow_factor)\n\n    s[CC].reorder(\n        oc_chunk,\n        oh_outer,\n        ow_outer,\n        kh,\n        kw,\n        ic_outer,\n        ic_f_inner,\n        oh_inner,\n        ow_inner,\n        oc_f_inner,\n        oc_s_inner,\n        ic_s_inner,\n    )\n    s[CC].fuse(oc_chunk, oh_outer)\n\n    if intrin is not None:\n        s[CC].tensorize(oc_s_inner, intrin)\n    s[CC].unroll(ow_inner)\n    s[CC].unroll(oh_inner)\n\n    if C != O:\n        out_ndim = len(s[O].op.axis)\n        if out_ndim == 5:\n            batch, oc_chunk, oh, ow, oc_block = s[O].op.axis\n            oh_outer, oh_inner = s[O].split(oh, factor=oh_factor)\n            ow_outer, ow_inner = s[O].split(ow, factor=ow_factor)\n        elif out_ndim == 4:\n            batch, oc, oh, ow = s[O].op.axis\n            oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n            oh_outer, oh_inner = s[O].split(oh, factor=oh_factor)\n            ow_outer, ow_inner = s[O].split(ow, factor=ow_factor)\n        else:\n            raise ValueError(\"Unsupported output ndim: %s\" % out_ndim)\n\n        s[O].reorder(oc_chunk, oh_outer, ow_outer, oh_inner, ow_inner, oc_block)\n        parallel_axis = s[O].fuse(batch, oc_chunk, oh_outer)\n        if inline_fused:\n            s[C].compute_at(s[O], ow_inner)\n        else:\n            s[C].compute_at(s[O], parallel_axis)\n        s[O].vectorize(oc_block)\n        s[O].parallel(parallel_axis)\n\n    return s\n\n\ndef schedule_depthwise_conv2d_nhwc(outs):\n    \"\"\"Create schedule for depthwise conv2d in NHWC layout.\n    Parameters\n    ----------\n    outs : list[te.tensor.Tensor]\n            The output tensors.\n    Returns\n    -------\n    s : tvm.te.schedule.Schedule\n        The computation schedule for depthwise conv2d.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        if \"depthwise_conv2d_nhwc\" in op.tag:\n            out = outs[0]\n            depthwise_conv2d_out = op.output(0)\n            data_pad = depthwise_conv2d_out.op.input_tensors[0]\n            s[data_pad].compute_inline()\n            if depthwise_conv2d_out != out:\n                s[depthwise_conv2d_out].compute_at(s[out], s[out].op.axis[3])\n            s[out].fuse(*s[out].op.axis)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef conv2d_alter_int8_common(\n    data,\n    data_tensor,\n    kernel,\n    kernel_tensor,\n    output_tensor,\n    attrs,\n    data_dtype: str,\n    in_channel_vector_length: int,\n    out_channel_vector_length: int,\n):\n    \"\"\"\n    Convert TE inputs/outputs so that they are suitable for fast Int8 instructions.\n\n    Int8 instructions require input channels and output channels to be a\n    multiple of the vector length. For input channels, we pad both the inputs\n    and weights channels. For output channels, we pad the weight and\n    stride_slice the output.\n\n    Arguments\n    ---------\n    data: Expr\n        Data Expr\n    data_tensor: Tensor\n        Data tensor\n    kernel: Expr\n        Kernel Expr\n    kernel_tensor: Tensor\n        Kernel tensor\n    output_tensor: Tensor\n        Output tensor\n    attrs: Conv2dAttrs\n        Attributes of the computation\n    data_dtype: \"int8\" or \"uint8\"\n        Desired dtype of data. Data will be converted to this dtype before the main computation.\n    in_channel_vector_length: int\n        Length of vector units on target hardware. Input channels are padded to this length.\n    out_channel_vector_length: int\n        Output size of vector instruction. Output channels are padded to this length.\n\n    Returns\n    -------\n    out : Tensor\n        Conv2d computation with inputs in the correct order for tensorization.\n    \"\"\"\n    # Dilation not supported yet. Return None if dilation is not (1, 1)\n    dilation = attrs.get_int_tuple(\"dilation\")\n    if not (dilation[0] == 1 and dilation[1] == 1):\n        return None\n\n    # No legalization for depthwise convolutions yet.\n    groups = attrs.get_int(\"groups\")\n    if groups != 1:\n        return None\n\n    # Get the conv attrs\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    padding = attrs.get_int_tuple(\"padding\")\n    kh, kw = attrs.get_int_tuple(\"kernel_size\")\n    pt, pl, pb, pr = get_pad_tuple(padding, (kh, kw))\n\n    if data_tensor.dtype != data_dtype:\n        # How to convert data to uint8\n        # Original --> C = A (conv) B\n        # A and B are int8\n        #   C = (A + 128 - 128) (conv) B\n        #   C = (A' conv B) - 128 (conv) B\n        # where A' = A + 128\n        # and 128 (conv) B is basically a reduce on CRS axis for weights.\n        #\n        # How to convert data to int8\n        #   C = (A - 128 + 128) (conv) B\n        #   C = (A' conv B) + 128 (conv) B\n        # where A' = A - 128\n        if data_dtype == \"uint8\":\n            # shift data to uint8\n            before_shift = relay.add\n            after_shift = relay.subtract\n            pad_value = 128\n        else:\n            # shift data to int8\n            before_shift = relay.subtract\n            after_shift = relay.add\n            pad_value = -128\n\n        if attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWIO\":\n            adjust_shift = relay.sum(relay.cast(kernel, dtype=\"int32\"), axis=(0, 1, 2))\n            pad_width = ((0, 0), (pt, pb), (pl, pr), (0, 0))\n        elif attrs[\"data_layout\"] == \"NCHW\" and attrs[\"kernel_layout\"] == \"OIHW\":\n            pad_width = ((0, 0), (0, 0), (pt, pb), (pl, pr))\n            adjust_shift = relay.sum(relay.cast(kernel, dtype=\"int32\"), axis=(1, 2, 3))\n            adjust_shift = relay.expand_dims(adjust_shift, axis=1, num_newaxis=2)\n        else:\n            return None\n\n        data = relay.cast(data, \"int32\")\n        data = before_shift(data, relay.const(128, \"int32\"))\n        data = relay.cast(data, data_dtype)\n\n        # Do external padding as pad value has to be 128.\n        if any(padding):\n            data = relay.nn.pad(data, pad_width=pad_width, pad_value=pad_value)\n\n        new_attrs[\"padding\"] = (0, 0)\n\n        # Multiply 128 to adjust shift.\n        adjust_shift = relay.multiply(adjust_shift, relay.const(128, \"int32\"))\n\n    # Flags to remember if the expr is modified\n    ic_modified = False\n    oc_modified = False\n\n    # Find the value of input and output channel.\n    in_channel = -1\n    out_channel = -1\n    if attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWIO\":\n        in_channel = data_tensor.shape[3].value\n        out_channel = kernel_tensor.shape[3].value\n    elif attrs[\"data_layout\"] == \"NCHW\" and attrs[\"kernel_layout\"] == \"OIHW\":\n        in_channel = data_tensor.shape[1].value\n        out_channel = kernel_tensor.shape[0].value\n    else:\n        return None\n\n    if in_channel % in_channel_vector_length != 0:\n        new_in_channel = (\n            (in_channel + in_channel_vector_length) // in_channel_vector_length\n        ) * in_channel_vector_length\n        diff = new_in_channel - in_channel\n        if attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWIO\":\n            data = relay.nn.pad(data, pad_width=((0, 0), (0, 0), (0, 0), (0, diff)))\n            kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, diff), (0, 0)))\n            ic_modified = True\n        elif attrs[\"data_layout\"] == \"NCHW\" and attrs[\"kernel_layout\"] == \"OIHW\":\n            pad_width = ((0, 0), (0, diff), (0, 0), (0, 0))\n            data = relay.nn.pad(data, pad_width=pad_width)\n            kernel = relay.nn.pad(kernel, pad_width=pad_width)\n            ic_modified = True\n        else:\n            return None\n\n    new_out_channel = out_channel\n    if out_channel % out_channel_vector_length != 0:\n        new_out_channel = (\n            (out_channel + out_channel_vector_length) // out_channel_vector_length\n        ) * out_channel_vector_length\n        diff = new_out_channel - out_channel\n        if attrs[\"data_layout\"] == \"NHWC\" and attrs[\"kernel_layout\"] == \"HWIO\":\n            kernel = relay.nn.pad(kernel, pad_width=((0, 0), (0, 0), (0, 0), (0, diff)))\n            oc_modified = True\n        elif attrs[\"data_layout\"] == \"NCHW\" and attrs[\"kernel_layout\"] == \"OIHW\":\n            kernel = relay.nn.pad(kernel, pad_width=((0, diff), (0, 0), (0, 0), (0, 0)))\n            oc_modified = True\n        else:\n            return None\n\n    if oc_modified:\n        new_attrs[\"channels\"] = new_out_channel\n        out = relay.nn.conv2d(data, kernel, **new_attrs)\n        original_out_shape = [x.value for x in output_tensor.shape]\n        out = relay.strided_slice(out, begin=[0, 0, 0, 0], end=original_out_shape)\n    else:\n        out = relay.nn.conv2d(data, kernel, **new_attrs)\n\n    if data_tensor.dtype != data_dtype:\n        out = after_shift(out, adjust_shift)\n\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/default.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"The default schedule used by various operators\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef default_schedule(outs, auto_inline):\n    \"\"\"Default schedule for llvm.\"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    if target.kind.name not in (\"llvm\", \"c\"):\n        raise RuntimeError(\"schedule not registered for '%s'\" % target)\n    s = te.create_schedule([x.op for x in outs])\n    if auto_inline:\n        x = outs[0]\n        te.schedule.AutoInlineInjective(s)\n        s[x].fuse(s[x].op.axis)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/extern.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"generic declaration and schedules.\"\"\"\nimport tvm\nfrom .. import cpp\n\n\ndef schedule_extern(outs):\n    \"\"\"Schedule for an extern op followed by injective operations.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of extern plus injective ops in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    target = tvm.target.Target.current()\n    return cpp.generic.schedule_extern(target, outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Generic image operators\"\"\"\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_dilation2d_nchw(outs):\n    \"\"\"Schedule for dilation2d\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The computation graph description of dilation2d\n        in the format of an array of tensors.\n    Returns\n    -------\n    sch : Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_dilation2d_nhwc(outs):\n    \"\"\"Schedule for dilation2d\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The computation graph description of dilation2d\n        in the format of an array of tensors.\n    Returns\n    -------\n    sch : Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"generic declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n    sch[out].fuse(*sch[out].op.axis)\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"Schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    if target.kind.name != \"llvm\":\n        raise RuntimeError(\"schedule_injective not registered for '%s'\" % target)\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    x = outs[0]\n    s = te.create_schedule([x.op for x in outs])\n    te.schedule.AutoInlineInjective(s)\n    schedule_injective_from_existing(s, x)\n    return s\n\n\nschedule_elemwise = schedule_injective\nschedule_broadcast = schedule_injective\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Generic math operators\"\"\"\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_einsum(outs):\n    \"\"\"Schedule for einsum operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of einsum.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Generic nn operators\"\"\"\nfrom tvm import te\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_conv1d_ncw(outs):\n    \"\"\"Schedule for conv1d_ncw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv1d_ncw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv1d_nwc(outs):\n    \"\"\"Schedule for conv1d_nwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv1d_nwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_group_conv1d_ncw(outs):\n    \"\"\"Schedule for group_conv1d_ncw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of group_conv1d_ncw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_group_conv1d_nwc(outs):\n    \"\"\"Schedule for group_conv1d_nwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of group_conv1d_nwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_hwcn(outs):\n    \"\"\"Schedule for conv2d_hwcn\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_hwcn\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_nchw(outs):\n    \"\"\"Schedule for conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_nhwc_pack(outs):\n    \"\"\"Schedule for conv2d_nhwc_pack\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nhwc_pack\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_nhwc(outs):\n    \"\"\"Schedule for conv2d_nhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_NCHWc(outs):\n    \"\"\"Schedule for conv2d_NCHW[x]c\n\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The computation graph description of conv2d_NCHWc\n        in the format of an array of tensors.\n        The number of filter, i.e., the output channel.\n\n    Returns\n    -------\n    sch : Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_NCHWc_int8(outs):\n    \"\"\"Schedule for conv2d_NCHW[x]c_int8\n\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The computation graph description of conv2d_NCHWc_int8\n        in the format of an array of tensors.\n        The number of filter, i.e., the output channel.\n\n    Returns\n    -------\n    sch : Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_winograd_weight_transform(outs):\n    \"\"\"Schedule for weight transformation of winograd\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of this operator\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    # Typically this is computed in PreCompute pass\n    # so we make a schedule here for cpu llvm\n    s = te.create_schedule([x.op for x in outs])\n    output = outs[0]\n    _, G = s[output].op.input_tensors\n    s[G].compute_inline()\n    eps, nu, co, ci = s[output].op.axis\n    r_kh, r_kw = s[output].op.reduce_axis\n    s[output].reorder(co, ci, r_kh, r_kw, eps, nu)\n    for axis in [r_kh, r_kw, eps, nu]:\n        s[output].unroll(axis)\n    s[output].parallel(co)\n    return s\n\n\ndef schedule_conv2d_gemm_weight_transform(outs):\n    \"\"\"Schedule for weight transformation of gemm\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of this operator\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    # Typically this is computed in PreCompute pass\n    s = te.create_schedule([x.op for x in outs])\n    return s\n\n\ndef schedule_conv3d_winograd_weight_transform(outs):\n    \"\"\"Schedule for weight transformation of 3D winograd\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of this operator\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    # Typically this is computed in PreCompute pass\n    # so we make a schedule here for cpu llvm\n    s = te.create_schedule([x.op for x in outs])\n    output = outs[0]\n    _, G = s[output].op.input_tensors\n    s[G].compute_inline()\n    transform_depth = len(s[output].op.reduce_axis) == 3\n    if transform_depth:\n        omg, eps, nu, ci, co = s[output].op.axis\n        r_kd, r_kh, r_kw = s[output].op.reduce_axis\n        s[output].reorder(co, ci, omg, eps, nu, r_kd, r_kh, r_kw)\n        for axis in [r_kd, r_kh, r_kw]:\n            s[output].unroll(axis)\n    else:\n        eps, nu, d, ci, co = s[output].op.axis\n        r_kh, r_kw = s[output].op.reduce_axis\n        s[output].reorder(co, ci, d, eps, nu, r_kh, r_kw)\n        for axis in [r_kh, r_kw]:\n            s[output].unroll(axis)\n    s[output].parallel(co)\n    return s\n\n\ndef schedule_conv2d_winograd_without_weight_transform(outs):\n    \"\"\"Schedule for winograd without weight transformation\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of this operator\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_winograd_nnpack_weight_transform(outs):\n    \"\"\"Schedule for weight transformation of winograd\n     Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of this operator\n          in the format of an array of tensors.\n     Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    # Typically this is computed in PreCompute pass\n    s = te.create_schedule([x.op for x in outs])\n    return s\n\n\ndef schedule_conv3d_ncdhw(outs):\n    \"\"\"Schedule for conv3d_ncdhw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv3d_ndhwc(outs):\n    \"\"\"Schedule for conv3d_ndhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv3d_ndhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv3d_transpose_ncdhw(outs):\n    \"\"\"Schedule for conv3d_transpose_ncdhw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv3d_transpose_ncdhw\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv2d_transpose_nchw(outs):\n    \"\"\"Schedule for conv2d_transpose_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_transpose_nchw\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_conv1d_transpose_ncw(outs):\n    \"\"\"Schedule for conv1d_transpose_ncw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_transpose_ncw\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_depthwise_conv2d_nchw(outs):\n    \"\"\"Schedule for depthwise_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of depthwise_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_depthwise_conv2d_nhwc(outs):\n    \"\"\"Schedule for depthwise_conv2d_nhwc\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of depthwise_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_depthwise_conv2d_NCHWc(outs):\n    \"\"\"Schedule for depthwise_conv2d_NCHWc\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of depthwise_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_group_conv2d_nchw(outs):\n    \"\"\"Schedule for group_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of group_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_group_conv2d_transpose_nchw(outs):\n    \"\"\"Schedule for group_conv2d_transpose_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of group_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_group_conv2d_nhwc(outs):\n    \"\"\"Schedule for group_conv2d_nhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of group_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_deformable_conv2d_nchw(outs):\n    \"\"\"Schedule for deformable_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of deformable_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_deformable_conv2d_nhwc(outs):\n    \"\"\"Schedule for deformable_conv2d_nhwc.\n    We only use the default schedule here and rely on auto_scheduler.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of deformable_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_bitserial_conv2d_nchw(outs):\n    \"\"\"Schedule for bitserial_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of bitserial_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_bitserial_conv2d_nhwc(outs):\n    \"\"\"Schedule for bitserial_conv2d_nhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of bitserial_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_bitserial_dense(outs):\n    \"\"\"Schedule for bitserial_dense\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of bitserial_dense\n          in the format of an array of tensors.\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_reduce(outs):\n    \"\"\"Schedule for reduction\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of reduce\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, True)\n\n\ndef schedule_softmax(outs):\n    \"\"\"Schedule for softmax\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of softmax\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_fast_softmax(outs):\n    \"\"\"Schedule for fast_softmax\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of fast_softmax\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_matmul(outs):\n    \"\"\"Schedule for matmul\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of matmul\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_dense(outs):\n    \"\"\"Schedule for dense\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of dense\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Schedule for pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of pool\n          in the format of an array of tensors.\n\n    layout: str\n        Data layout.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_pool_grad(outs):\n    \"\"\"Schedule for pool_grad\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of pool\n          in the format of an array of tensors.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_adaptive_pool(outs):\n    \"\"\"Schedule for adaptive pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of adaptive pool\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_binarize_pack(outs):\n    \"\"\"Schedule for binarize_pack\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of binarize_pack\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_bitpack(outs):\n    \"\"\"Schedule for bitpack\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of bitpack\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_binary_dense(outs):\n    \"\"\"Schedule for binary_dense\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of binary_dense\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_lrn(outs):\n    \"\"\"Schedule for lrn\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of lrn\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_sparse_dense(outs):\n    \"\"\"Schedule for sparse_dense\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of sparse_dense\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_sparse_transpose(outs):\n    \"\"\"Schedule for sparse_transpose\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of sparse_transpose\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_sparse_conv2d(outs):\n    \"\"\"Schedule for sparse_conv2d\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of sparse_conv2d\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_batch_matmul(outs):\n    \"\"\"Schedule for batch_matmul\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of sparse_transpose\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_batch_norm(outs):\n    \"\"\"Schedule for batch_norm\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of sparse_transpose\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_correlation_nchw(outs):\n    \"\"\"Schedule for correlation_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of correlation_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_lstm(outs):\n    \"\"\"Schedule for LSTM\n\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The outputs of LSTM (hidden states and cell states).\n\n    Returns\n    -------\n    sch: Schedule\n        The default schedule for LSTM.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/search.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member\n\"\"\"Generic search operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_argwhere(outs):\n    \"\"\"Schedule for argwhere operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of argwhere.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_scatter(outs):\n    \"\"\"Schedule for scatter operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of scatter.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_scatter_add(outs):\n    \"\"\"Schedule for scatter_add operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of scatter_add.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_sparse_fill_empty_rows(outs):\n    return _default_schedule(outs, False)\n\n\ndef schedule_unique(outs):\n    \"\"\"Schedule for unique operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of unique.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/sort.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member\n\"\"\"Generic sort operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_sort(outs):\n    \"\"\"Schedule for sort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The indices that would sort an input array along\n      the given axis.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_argsort(outs):\n    \"\"\"Schedule for argsort operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The indices that would sort an input array along\n      the given axis.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_topk(outs):\n    \"\"\"Schedule for topk operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The indices that would sort an input array along\n      the given axis.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic/vision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member\n\"\"\"Generic vision operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom .. import cpp\nfrom .default import default_schedule as _default_schedule\n\n\ndef schedule_reorg(outs):\n    \"\"\"Schedule for reorg\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of reorg\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    target = tvm.target.Target.current(allow_none=False)\n    cpp_target = cpp.TEST_create_target(target.kind.name)\n    return cpp.generic.default_schedule(cpp_target, outs, False)\n\n\ndef schedule_get_valid_counts(outs):\n    \"\"\"Schedule for get_valid_counts\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of nms\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_nms(outs):\n    \"\"\"Schedule for non-maximum suppression\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of nms\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_multibox_prior(outs):\n    \"\"\"Schedule for multibox_prior\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of multibox_prior\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_multibox_transform_loc(outs):\n    \"\"\"Schedule for multibox_transform_loc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of\n      multibox_transform_loc in the format\n      of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_multibox_detection(outs):\n    \"\"\"Schedule for multibox_detection\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of multibox_detection\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_roi_align(outs):\n    \"\"\"Schedule for roi_align\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of roi_align\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_roi_pool(outs):\n    \"\"\"Schedule for roi_align\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of roi_pool\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n\n\ndef schedule_proposal(outs):\n    \"\"\"Schedule for proposal operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n      The computation graph description of proposal\n      in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n      The computation schedule for the op.\n    \"\"\"\n    return _default_schedule(outs, False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/generic_op_impl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Implementation of generic operators in the presence of Tensor\"\"\"\n# pylint: disable=invalid-name, too-many-arguments\nimport tvm\nfrom tvm import te\nfrom . import broadcast as _broadcast\nfrom . import math as _math\n\n\ndef _make_bop(broadcast_bop, orig_bop):\n    \"\"\"Make a specific overloaded binary operator of Tensor when applicable;\n    apply the original operator if it is not supposed to be overloaded.\n\n    Consider the following scenario:\n    OP :   + | - | * | /\n    R0 :   int | float | Expr | TensorSlice | Tensor (rank zero)\n    R1 :   Tensor (positive rank)\n\n    In terms of (LHS OP RHS), we apply the following overloading rules:\n    (1) We use broadcast_OP(LHS, RHS), when both LHS and RHS are R1.\n    (2) We perform element-wise operation of Tensor and scalar,\n        when one of LHS and RHS is R1 and another is R0.\n    (3) We do not overload OP (i.e. stick to orig_bop) otherwise.\n\n    Parameters\n    ----------\n    broadcast_bop : operator function\n        Operator for broadcast tensor-tensor operation, for rule (1).\n\n    orig_bop: operator function\n        Operator before overloading, for rule (3).\n\n    Returns\n    -------\n    ret : operator function\n        The overloaded operator function if applicable or orig_bop otherwise.\n    \"\"\"\n\n    name = orig_bop.__name__\n\n    def _tensor_bop_impl(lhs, rhs):\n        \"\"\"Overloaded {op} operator.\n\n        If both operands are non-zero-rank Tensors, it performs\n        tensor-tensor {op} operation, and broadcasts inputs when necessary.\n\n        If one operand is non-zero-rank Tensor, while the other operand is\n        scalar like type (e.g., numeric types, Expr, or TensorSlice),\n        it performs tensor-scalar {op} operation on an element-wise basis.\n\n        Otherwise, it performs default generic.{op} operation, as defined\n        in tvm.generic module.\n\n        Parameters\n        ----------\n        lhs : object\n            Left operand.\n        rhs : object\n            Right operand.\n\n        Returns\n        -------\n        ret : tvm.te.Tensor (if at least one operand is non-zero-rank Tensor)\n              tvm.Expr (otherwise)\n            The result of {op} operation.\n        \"\"\"\n        if not isinstance(lhs, te.tensor.Tensor) and not isinstance(rhs, te.tensor.Tensor):\n            return orig_bop(lhs, rhs)\n        return broadcast_bop(lhs, rhs)\n\n    _tensor_bop_impl.__doc__ = _tensor_bop_impl.__doc__.format(op=name)\n    return _tensor_bop_impl\n\n\ndef _bind_generic_ops():\n    \"\"\"Bind generic operators for Tensor.\"\"\"\n    # Check __op_priority__ to make sure the binding happens only once.\n    __op_priority__ = 1\n    if __op_priority__ > tvm.tir.generic.__op_priority__:\n        tvm.tir.generic.__op_priority__ = __op_priority__\n        tvm.tir.generic.add = _make_bop(_broadcast.add, tvm.tir.generic.add)\n        tvm.tir.generic.subtract = _make_bop(_broadcast.subtract, tvm.tir.generic.subtract)\n        tvm.tir.generic.multiply = _make_bop(_broadcast.multiply, tvm.tir.generic.multiply)\n        tvm.tir.generic.divide = _make_bop(_broadcast.divide, tvm.tir.generic.divide)\n        tvm.tir.generic.cast = _math.cast\n\n\n_bind_generic_ops()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/gpu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"GPU specific declaration and schedules.\"\"\"\nfrom .dense import *\nfrom .conv2d import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/gpu/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Schedule for conv2d operator\"\"\"\nfrom tvm import te, autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline\nfrom .conv2d_nhwc import schedule_conv2d_nhwc_direct\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc.gpu\")\ndef conv2d_nhwc(cfg, data, kernel, strides, padding, dilation, out_dtype=\"float32\"):\n    \"\"\"Compute conv2d with NHWC layout\"\"\"\n    return nn.conv2d_nhwc(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc.gpu\")\ndef schedule_conv2d_nhwc(cfg, outs):\n    \"\"\"Create the schedule for conv2d_nhwc\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv2d_nhwc\":\n            schedule_conv2d_nhwc_direct(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/gpu/conv2d_nhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument\n\"\"\"Direct conv2d in NHWC layout\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import get_const_tuple\n\n\ndef schedule_conv2d_nhwc_direct(cfg, s, Conv):\n    \"\"\"schedule optimized for NHWC direct conv2d\"\"\"\n    pad_data, kernel = s[Conv].op.input_tensors\n    s[pad_data].compute_inline()\n\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    if Conv.op in s.outputs:\n        output = Conv\n        OL = s.cache_write(Conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[Conv].set_scope(\"local\")\n        OL = Conv\n    # create cache stage\n    AA = s.cache_read(pad_data, \"shared\", [OL])\n    WW = s.cache_read(kernel, \"shared\", [OL])\n    AL = s.cache_read(AA, \"local\", [OL])\n    WL = s.cache_read(WW, \"local\", [OL])\n\n    # Currently Conv2d NHWC only support dynamic shpe in batch\n    dynamic_batch = isinstance(s[output].op.axis[0].dom.extent, tvm.tir.expr.Var)\n\n    # Schedule for autotvm\n    cfg.define_knob(\"tile_n\", [1] if dynamic_batch else [2, 4, 8])\n    cfg.define_knob(\"tile_c\", [2, 4, 8])\n    cfg.define_knob(\"num_thread_n\", [1] if dynamic_batch else [4, 8, 16])\n    cfg.define_knob(\"num_thread_c\", [4, 8, 16])\n    cfg.define_knob(\"vthread_n\", [1] if dynamic_batch else [1, 2])\n    cfg.define_knob(\"vthread_c\", [1, 2])\n    cfg.define_knob(\"step\", [16, 3, 32, 64])\n    cfg.define_knob(\"vectorize\", [1, 2, 4, 8])\n\n    # fallback support\n    target = tvm.target.Target.current()\n    if cfg.is_fallback:\n        ref_log = autotvm.tophub.load_reference_log(\n            target.kind.name, target.model, \"conv2d_nhwc.gpu\"\n        )\n        cfg.fallback_with_reference_log(ref_log)\n\n    tile_n = cfg[\"tile_n\"].val\n    tile_c = cfg[\"tile_c\"].val\n    num_thread_n = cfg[\"num_thread_n\"].val\n    num_thread_c = cfg[\"num_thread_c\"].val\n    vthread_n = cfg[\"vthread_n\"].val\n    vthread_c = cfg[\"vthread_c\"].val\n    step = cfg[\"step\"].val\n    vec_factor = cfg[\"vectorize\"].val\n    block_factor_c = tile_c * num_thread_c * vthread_c\n\n    offset = 8\n    A_align = step + offset\n    W_align = block_factor_c + offset\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis((0, num_thread_c), \"threadIdx.x\")\n    thread_y = te.thread_axis((0, num_thread_n), \"threadIdx.y\")\n    thread_xz = te.thread_axis((0, vthread_c), \"vthread\", name=\"vx\")\n    thread_yz = te.thread_axis((0, vthread_n), \"vthread\", name=\"vy\")\n\n    # Schedule for output\n    ni, _, wi, fi = s[output].op.axis\n    bx = wi\n    fi, vec = s[output].split(fi, factor=vec_factor)\n    s[output].vectorize(vec)\n    tx, fi = s[output].split(fi, factor=tile_c)\n    txz, tx = s[output].split(tx, factor=num_thread_c)\n    bz, txz = s[output].split(txz, factor=vthread_c)\n    ty, ni = s[output].split(ni, factor=tile_n)\n    tyz, ty = s[output].split(ty, factor=num_thread_n)\n    by, tyz = s[output].split(tyz, factor=vthread_n)\n    s[output].reorder(bx, by, bz, tyz, txz, ty, tx, ni, fi, vec)\n    s[output].bind(bz, block_z)\n    s[output].bind(by, block_y)\n    s[output].bind(bx, block_x)\n    s[output].bind(tyz, thread_yz)\n    s[output].bind(txz, thread_xz)\n    s[output].bind(ty, thread_y)\n    s[output].bind(tx, thread_x)\n    # Schedule local computation\n    s[OL].compute_at(s[output], tx)\n    ni, yi, xi, fi = s[OL].op.axis\n    ry, rx, rc = s[OL].op.reduce_axis\n    rco, rci = s[OL].split(rc, factor=step)\n    s[OL].vectorize(fi)\n    s[OL].reorder(rco, ry, rx, rci, ni, fi)\n\n    s[AA].compute_at(s[OL], rx)\n    s[WW].compute_at(s[OL], rx)\n    s[AL].compute_at(s[OL], rci)\n    s[WL].compute_at(s[OL], rci)\n    # Schedule for data's share memory\n    ni, yi, xi, ci = s[AA].op.axis\n    s[AA].reorder(yi, xi, ni, ci)\n    s[AA].storage_align(xi, A_align - 1, A_align)\n    t = s[AA].fuse(ni, ci)\n    ty, tx = s[AA].split(t, factor=num_thread_c)\n    _, ty = s[AA].split(ty, factor=num_thread_n)\n    s[AA].bind(tx, thread_x)\n    s[AA].bind(ty, thread_y)\n    # Schedule for kernel's share memory\n    _, _, ic, o = s[WW].op.axis\n    t = s[WW].fuse(ic, o)\n    s[WW].storage_align(ic, W_align - 1, W_align)\n    t, vec = s[WW].split(t, factor=vec_factor)\n    s[WW].vectorize(vec)\n    ty, tx = s[WW].split(t, factor=num_thread_c)\n    _, ty = s[WW].split(ty, factor=num_thread_n)\n    s[WW].bind(tx, thread_x)\n    s[WW].bind(ty, thread_y)\n\n    N, OH, OW, CO = get_const_tuple(output.shape)\n    KH, KW, CI, _ = get_const_tuple(kernel.shape)\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/gpu/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Schedule for dense operator\"\"\"\n\nimport logging\n\nfrom tvm import autotvm, te\nfrom tvm.autotvm.task.space import SplitEntity\n\nfrom .. import nn\nfrom ..utils import traverse_inline, get_const_tuple\n\nlogger = logging.getLogger(\"topi\")\n\n\n@autotvm.register_topi_compute(\"dense_small_batch.gpu\")\ndef dense_small_batch(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator on GPU\"\"\"\n    return nn.dense(data, weight, bias, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"dense_small_batch.gpu\")\ndef schedule_dense_small_batch(cfg, outs):\n    \"\"\"Schedule float32/64 dense with small batch size\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"dense\":\n            _schedule_dense_small_batch(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"matmul_default.gpu\")\ndef matmul_default(\n    cfg,\n    tensor_a,\n    tensor_b,\n    bias=None,\n    out_dtype=None,\n    transpose_a=False,\n    transpose_b=False,\n):\n    \"\"\"Matmul operator on GPU\"\"\"\n    return nn.matmul(tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b)\n\n\n@autotvm.register_topi_schedule(\"matmul_default.gpu\")\ndef schedule_matmul_default(cfg, outs):\n    \"\"\"Schedule matmul on GPU\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"matmul\":\n            # Temporary use this as a basic schedule for matmul\n            # TODO(jcf94): Add a more general schedule for matmul\n            _schedule_dense_small_batch(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_dense_small_batch(cfg, s, C):\n    A, weights = C.op.input_tensors\n    if len(weights.op.input_tensors) == 1 and weights.op.input_tensors[0] == A:\n        s[weights].compute_inline()\n\n    _, in_dim_weights = get_const_tuple(weights.shape)\n    _, in_dim_A = get_const_tuple(A.shape)\n\n    if isinstance(in_dim_A, int):\n        in_dim = in_dim_A\n    elif isinstance(in_dim_weights, int):\n        in_dim = in_dim_weights\n    else:\n        in_dim = None\n\n    if in_dim is not None:\n        cfg.define_split(\"tile_k\", in_dim, num_outputs=2)\n        if cfg.is_fallback:\n            cfg[\"tile_k\"] = SplitEntity([-1, 64] if in_dim > 64 else [1, 64])\n        _, kf = cfg[\"tile_k\"].apply(s, C, C.op.reduce_axis[0])\n    else:\n        tile_k = 64\n        _, kf = s[C].split(C.op.reduce_axis[0], tile_k)\n\n    CF = s.rfactor(C, kf)\n\n    if C.op in s.outputs:\n        Out = C\n    else:\n        Out = s.outputs[0].output(0)\n        s[C].compute_at(s[Out], s[Out].op.axis[1])\n    s[Out].bind(s[Out].op.axis[0], te.thread_axis(\"blockIdx.y\"))\n    s[Out].bind(s[Out].op.axis[1], te.thread_axis(\"blockIdx.x\"))\n\n    tx = s[C].op.reduce_axis[0]\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    s[C].bind(tx, thread_x)\n    s[CF].compute_at(s[C], tx)\n    s[C].set_store_predicate(thread_x.var.equal(0))\n    s[Out].set_store_predicate(thread_x.var.equal(0))\n\n\n@autotvm.register_topi_compute(\"dense_large_batch.gpu\")\ndef dense_large_batch(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator on GPU\"\"\"\n    return nn.dense(data, weight, bias, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"dense_large_batch.gpu\")\ndef schedule_dense_large_batch(cfg, outs):\n    \"\"\"Schedule float32/64 dense with large batch size\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"dense\":\n            _schedule_dense_large_batch(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_dense_large_batch(cfg, s, C):\n    \"\"\"Schedule float32/64 dense with large batch size\"\"\"\n    A, B = C.op.input_tensors\n    if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A:\n        s[B].compute_inline()\n    batch, in_dim = get_const_tuple(A.shape)\n    out_dim, _ = get_const_tuple(B.shape)\n    k = C.op.reduce_axis[0]\n\n    # create tuning space\n    try:\n        block_cand = [64, 128]\n        vthread_cand = [2**x for x in range(1, 7)]\n        n_thread_cand = [2**x for x in range(3, 7)]\n        cfg.define_split(\n            \"tile_x\",\n            batch,\n            num_outputs=4,\n            filter=lambda x: (\n                x.size[1] in vthread_cand\n                and x.size[2] in n_thread_cand\n                and (x.size[1] * x.size[2] * x.size[3]) in block_cand\n            ),\n        )\n        cfg.define_split(\n            \"tile_y\",\n            out_dim,\n            num_outputs=4,\n            filter=lambda x: (\n                x.size[1] in vthread_cand\n                and x.size[2] in n_thread_cand\n                and (x.size[1] * x.size[2] * x.size[3]) in block_cand\n            ),\n        )\n        cfg.define_split(\"tile_k\", in_dim, num_outputs=3, filter=lambda x: x.size[0] > 2)\n    except IndexError:\n        # Index error happens when no entities left after filtering, which was designed\n        # to prune tuning space for better search efficiency.\n        logger.debug(\"Tuning space was created without pruning due to unfit shapes\")\n        cfg.define_split(\"tile_x\", batch, num_outputs=4)\n        cfg.define_split(\"tile_y\", out_dim, num_outputs=4)\n        cfg.define_split(\"tile_k\", in_dim, num_outputs=3)\n\n    if cfg.is_fallback:\n        if batch > 1:\n            cfg[\"tile_x\"] = SplitEntity([-1, 2, 16, 2])\n        else:\n            cfg[\"tile_x\"] = SplitEntity([1, 1, 1, 1])\n        if out_dim > 1:\n            cfg[\"tile_y\"] = SplitEntity([-1, 2, 16, 2])\n        else:\n            cfg[\"tile_y\"] = SplitEntity([1, 1, 1, 1])\n        if in_dim > 8:\n            cfg[\"tile_k\"] = SplitEntity([-1, 8, 1])\n        else:\n            cfg[\"tile_k\"] = SplitEntity([-1, 1, 1])\n\n    # Explicit memory access\n    AA = s.cache_read(A, \"shared\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n    AL = s.cache_read(AA, \"local\", [C])\n    BL = s.cache_read(BB, \"local\", [C])\n    CC = s.cache_write(C, \"local\")\n\n    # Deal with op fusion\n    if C.op not in s.outputs:\n        s[C].compute_inline()\n        C = s.outputs[0].output(0)\n\n    # Split and reorder computation\n    bx, txz, tx, xi = cfg[\"tile_x\"].apply(s, C, C.op.axis[0])\n    by, tyz, ty, yi = cfg[\"tile_y\"].apply(s, C, C.op.axis[1])\n    s[C].reorder(by, bx, tyz, txz, ty, tx, yi, xi)\n    s[CC].compute_at(s[C], tx)\n\n    # Binding\n    s[C].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tyz, te.thread_axis(\"vthread\"))\n    s[C].bind(txz, te.thread_axis(\"vthread\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    # Split reduction\n    yo, xo = CC.op.axis\n    ko, kt, ki = cfg[\"tile_k\"].apply(s, CC, k)\n    s[CC].reorder(ko, kt, ki, yo, xo)\n    s[AA].compute_at(s[CC], ko)\n    s[BB].compute_at(s[CC], ko)\n    s[CC].unroll(kt)\n    s[AL].compute_at(s[CC], kt)\n    s[BL].compute_at(s[CC], kt)\n\n    # Schedule for A's shared memory load\n    num_thread_x = cfg[\"tile_x\"].size[2]\n    ty, _ = s[AA].split(s[AA].op.axis[0], nparts=num_thread_x)\n    _, xi = s[AA].split(s[AA].op.axis[1], factor=num_thread_x * 4)\n    tx, xi = s[AA].split(xi, nparts=num_thread_x)\n    s[AA].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[AA].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[AA].double_buffer()\n\n    # Schedule for B' shared memory load\n    num_thread_y = cfg[\"tile_y\"].size[2]\n    ty, _ = s[BB].split(s[BB].op.axis[0], nparts=num_thread_y)\n    _, xi = s[BB].split(s[BB].op.axis[1], factor=num_thread_y * 4)\n    tx, xi = s[BB].split(xi, nparts=num_thread_y)\n    s[BB].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[BB].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[BB].double_buffer()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Schedules for Hexagon. \"\"\"\n\n# pylint: disable=wildcard-import\n\nfrom .batch_matmul import *\nfrom .conv2d import *\nfrom .dense import *\nfrom .injective import *\nfrom .pad import *\nfrom .pooling import *\nfrom .reduce import *\nfrom .resize2d import *\nfrom .tensor_intrin import *\nfrom .qnn import *\nfrom .dense_alter_op import *\nfrom .conv2d_alter_op import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Schedule for composition of batch_matmul operator\"\"\"\n\nimport tvm\n\n\ndef schedule_batch_matmul(outs):\n    \"\"\"Schedule for batch_matmul op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of batch_matmul in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Schedule for conv2d\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom .. import nn\nfrom ..utils import traverse_inline\nfrom .tensor_intrin import dot_vrmpy\nfrom ..generic import conv2d as conv2d_generic\n\n\ndef schedule_conv2d_nhwc(outs):\n    \"\"\"Schedule for conv2d NHWC operator.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n\n\ndef schedule_conv2d_nchw(outs):\n    return schedule_conv2d_nhwc(outs)\n\n\ndef schedule_conv2d(outs, layout=\"NHWC\"):\n    layout_uncase = layout.casefold()\n    if layout_uncase == \"NHWC\".casefold():\n        return schedule_conv2d_nhwc(outs)\n    if layout_uncase == \"NCHW\".casefold():\n        return schedule_conv2d_nchw(outs)\n\n    raise ValueError(f\"Unexpected layout={layout}\")\n\n\ndef schedule_depthwise_conv2d_nchw(outs):\n    return schedule_conv2d_nchw(outs)\n\n\ndef schedule_depthwise_conv2d_nhwc(out):\n    return schedule_conv2d_nhwc(out)\n\n\ndef schedule_conv2d_transpose_nchw(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = schedule_conv2d_nchw(outs)\n\n    def _callback(op):\n        if \"unpack_nchwc\" in op.tag:\n            conv_out = op.input_tensors[0]\n            # retrieve data\n            data_vec = conv_out.op.input_tensors[0]\n            if isinstance(data_vec, tvm.te.ComputeOp):\n                data_pad = data_vec.op.input_tensors[0]\n                data_dilate = data_pad.op.input_tensors[0]\n                s[data_dilate].compute_inline()\n                s[data_pad].compute_inline()\n            # retrieve kernel\n            kernel_vec = conv_out.op.input_tensors[1]\n            if isinstance(kernel_vec, tvm.te.ComputeOp):\n                kernel_transform = kernel_vec.op.input_tensors[0]\n                s[kernel_transform].compute_inline()\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef conv2d_NCHWc_int8(\n    data, kernel, stride, padding, dilation, layout, out_layout, out_dtype=\"int32\"\n):\n    \"\"\"Compute definition for int8 conv2d in NCHWc layout\"\"\"\n    n_elems = int(kernel.shape[-1])\n    return nn.conv2d_NCHWc_int8(\n        data, kernel, stride, padding, dilation, layout, out_layout, out_dtype, n_elems=n_elems\n    )\n\n\ndef schedule_conv2d_NCHWc_int8(outs):\n    \"\"\"Schedule for int8 conv2d in NCHWc layout using vrmpy tensorization\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_NCHWc_int8\" in op.tag:\n            conv_out = op.output(0)\n            kernel_vec = conv_out.op.input_tensors[1]\n            data_vec = conv_out.op.input_tensors[0]\n            out_width = conv_out.shape[3]\n\n            reg_n = 1\n            for n in range(31, 0, -1):\n                if out_width % n == 0:\n                    reg_n = n\n                    break\n\n            cfg = {\"tile_ow\": reg_n, \"unroll_kw\": False}\n            args = [s, cfg, data_vec, kernel_vec, conv_out, outs[0]]\n            intrin = dot_vrmpy(data_vec.dtype, kernel_vec.dtype)\n\n            conv2d_generic.schedule_conv_NCHWc_cpu_common_int8(\n                *args,\n                int32_lanes=32,\n                int8_elems=4,\n                intrin=intrin,\n                inline_fused=True,\n            )\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2d alter op functions for Hexagon\"\"\"\n\nfrom tvm import relay\nfrom ..utils import get_const_tuple\nfrom .. import nn\nfrom ..nn import conv2d_alter_layout\nfrom ..generic.conv2d import conv2d_alter_int8_common\n\n\n@conv2d_alter_layout.register(\"hexagon\")\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    \"\"\"Convert nn.conv2d into nn.contrib_conv2d_nchwc if vrmpy is applicable.\"\"\"\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data_tensor, kernel_tensor = tinfos\n    out_channel, in_channel, _, _ = get_const_tuple(kernel_tensor.shape)\n\n    if (\n        \"int8\" in data_tensor.dtype\n        and \"int8\" in kernel_tensor.dtype\n        and out_channel % 32 == 0\n        and in_channel % 4 == 0\n        and data_layout == \"NCHW\"\n        and kernel_layout == \"OIHW\"\n    ):\n        out_channel, in_channel, _, _ = get_const_tuple(kernel_tensor.shape)\n\n        n_elems = 4\n        oc_bn = 32\n        ic_bn = min(in_channel, 32)\n\n        new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        new_attrs[\"kernel_layout\"] = \"OIHW{:n}i{:n}o{:n}i\".format(ic_bn // n_elems, oc_bn, n_elems)\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    return None\n\n\n@nn.conv2d_legalize.register(\"hexagon\")\ndef _conv2d_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalize conv2d op for vrmpy tensorization.\n\n    If the inputs are signed or unsigned int8, the input and output channels are padded to be\n    a multiple of 4 and 32 respectively.\n\n    If the input data types are (int8, int8), they are converted to (uint8, int8) and\n    the vector-by-vector variant of vrmpy is applied.\n    If the input data types are (uint8, uint8), the more efficient vector-by-scalar variant of vrmpy\n    is applied.\n\n    Unlike the nn.dense case (see dense_alter_op.py), we do not convert (uint8, int8) to\n    (uint8, uint8). That would introduce another convolution by a constant (128 or 1) filter,\n    to compensate for the dtype legalization. In the nn.dense case, such compensation factor is\n    just a sum over the K axis.\n    \"\"\"\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n\n    output_tensor = arg_types[2]\n\n    data, kernel = inputs\n\n    if data_layout != \"NCHW\" or kernel_layout != \"OIHW\":\n        return None\n\n    data_tensor, kernel_tensor = arg_types[0], arg_types[1]\n\n    if \"int8\" in data_tensor.dtype and \"int8\" in data_tensor.dtype:\n        output_tensor = arg_types[2]\n        data, kernel = inputs\n        desired_data_dtype = \"uint8\"\n        in_channel_vector_length = 4\n        out_channel_vector_length = 32\n\n        return conv2d_alter_int8_common(\n            data,\n            data_tensor,\n            kernel,\n            kernel_tensor,\n            output_tensor,\n            attrs,\n            desired_data_dtype,\n            in_channel_vector_length,\n            out_channel_vector_length,\n        )\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Schedule for dense operator\"\"\"\n\nimport tvm\nfrom tvm.topi.utils import traverse_inline\nfrom tvm import te\nfrom .. import tag\nfrom .tensor_intrin import dot_vrmpy\n\n\ndef schedule_dense(outs):\n    \"\"\"Schedule for dense op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of dense in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n\n\ndef dense_u8u8i32_vrmpy_compute(X, packed_w, bias, out_dtype):\n    \"\"\"Compute for uint8 x uint8 -> int32 dense using vrmpy\"\"\"\n    assert X.dtype == \"uint8\" and packed_w.dtype == \"uint8\" and out_dtype == \"int32\"\n    m, k = X.shape\n    n_o, _, n_i, _ = packed_w.shape\n    assert n_i == 32\n    ak = te.reduce_axis((0, k), name=\"k\")\n\n    C = te.compute(\n        (m, n_o * n_i),\n        lambda i, j: te.sum(\n            X[i, ak].astype(\"int32\")\n            * packed_w[tvm.tir.indexdiv(j, 32), tvm.tir.indexdiv(ak, 4), j % 32, ak % 4].astype(\n                \"int32\"\n            ),\n            axis=ak,\n        ),\n        tag=\"dense_u8u8i32_vrmpy\",\n        name=\"compute\",\n    )\n\n    if bias is not None:\n        C = te.compute(C.shape, lambda i, j: C[i, j] + bias[j], tag=tag.BROADCAST)\n\n    return C\n\n\ndef dense_u8u8i32_vrmpy_schedule(outs):\n    \"\"\"Schedule for vrmpy dense\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    # O: The output of the fused op\n    O = outs[0]\n\n    def _schedule_dense(s, C, O):\n        (a_k,) = C.op.reduce_axis\n        a_y = C.op.axis[-2]\n        a_yo, a_yi = s[C].split(a_y, factor=32)\n        a_xo, a_xi = s[C].split(C.op.axis[-1], factor=32)\n        a_ko, a_ki = s[C].split(a_k, factor=4)\n\n        s[C].reorder(a_yo, a_xo, a_yi, a_ko, a_xi, a_ki)\n\n        pc = dot_vrmpy(\"uint8\", \"uint8\")\n        s[C].tensorize(a_xi, pc)\n        s[C].parallel(s[C].fuse(a_yo, a_xo))\n\n        if C != O:\n            a_y = O.op.axis[-2]\n            a_yo, a_yi = s[O].split(a_y, factor=32)\n            a_xo, a_xi = s[O].split(O.op.axis[-1], factor=32)\n\n            s[O].reorder(a_yo, a_xo, a_yi, a_xi)\n            s[O].vectorize(a_xi)\n            s[C].compute_at(s[O], a_yi)\n            s[O].parallel(s[O].fuse(a_yo, a_xo))\n\n    def _callback(op):\n        if \"u8u8i32_vrmpy\" in op.tag:\n            # C: The output of GEMM\n            C = op.output(0)\n            _schedule_dense(s, C, O)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/dense_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Dense alter op functions for ARM\"\"\"\n\nimport tvm\nfrom tvm import relay\nfrom .. import nn\nfrom ..nn import dense_alter_layout\n\n\ndef check_vrmpy_applicable(x, y):\n    return (\n        \"int8\" in x.dtype and \"int8\" in y.dtype and y.shape[-2] % 32 == 0 and y.shape[-1] % 4 == 0\n    )\n\n\n@dense_alter_layout.register([\"hexagon\"])\ndef _alter_dense_layout(attrs, inputs, tinfos, out_type):\n    data_tensor, weight_tensor = tinfos\n    out_dtype = out_type.dtype\n\n    if check_vrmpy_applicable(data_tensor, weight_tensor):\n        weight_layout = \"NC32n4c\"\n        return relay.nn.contrib_dense_pack(inputs[0], inputs[1], weight_layout, None, out_dtype)\n    else:\n        return None\n\n\ndef vrmpy_legalize(x, w, arg_types, op, attrs):\n    \"\"\"\n    Legalizes int8 inputs to dense for vrmpy.\n    X'_u8 = X_s8 + 128\n    X_s8 * W_s8 = (X'_u8 - 128) * (W'_u8 - 128)\n                = X'_u8 * W'_u8 - X'_u8 * 128 - 128 * W'_u8 + 128 * 128\n    X_u8 * W_s8 = X_u8 * (W'_u8 - 128)\n                = X'_u8 * W'_u8 - X_u8 * 128\n    \"\"\"\n    if not check_vrmpy_applicable(arg_types[0], arg_types[1]):\n        return None\n\n    def cast_to_uint8(x):\n        x = relay.cast(x, \"int32\")\n        x = relay.add(x, relay.const(128, \"int32\"))\n        return relay.cast(x, \"uint8\")\n\n    if arg_types[0].dtype == \"int8\" and arg_types[1].dtype == \"int8\":\n        x = cast_to_uint8(x)\n        w = cast_to_uint8(w)\n\n        W_u8x128 = relay.const(-128, \"int32\") * relay.sum(relay.cast(w, \"int32\"), axis=[-1])\n        X_u8x128 = relay.const(-128, \"int32\") * relay.sum(relay.cast(x, \"int32\"), axis=[-1])\n        X_u8x128 = relay.expand_dims(X_u8x128, axis=1)\n\n        out = op(x, w, **attrs)\n\n        out += W_u8x128\n        out += X_u8x128\n\n        k_dim = int(arg_types[0].shape[-1])\n        return out + relay.const(128 * 128 * k_dim, \"int32\")\n\n    if arg_types[0].dtype == \"uint8\" and arg_types[1].dtype == \"int8\":\n        w = cast_to_uint8(w)\n\n        X_u8x128 = relay.expand_dims(\n            relay.const(-128, \"int32\") * relay.sum(relay.cast(x, \"int32\"), axis=[-1]), axis=1\n        )\n\n        out = op(x, w, **attrs)\n\n        return out + X_u8x128\n\n    return None\n\n\n@nn.dense_legalize.register(\"hexagon\")\ndef _dense_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalize dense op for HVX vectorization and vrmpy tensorization.\n\n    Given a workload with a matrix X of shape (M, K) and a matrix Y of (N, K),\n    we first pad the N dimension to be a multiple of the output vector length.\n\n    And if the inputs are signed or unsigned int8 and the Y matrix can be packed into the\n    NK32n4k layout, we convert both inputs to uint8 to apply the most efficient variant of vrmpy.\n    \"\"\"\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n    # Collect the input tensors.\n    x_tensor, y_tensor = arg_types[0], arg_types[1]\n    dtype = x_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    x, y = inputs\n\n    N, _ = y_tensor.shape\n\n    if dtype == \"float16\":\n        vec_len = 64\n    elif \"int8\" in dtype:\n        vec_len = 32\n    else:\n        return None\n\n    if N % vec_len != 0:\n        N_padded = ((N + vec_len) // vec_len) * vec_len\n        dn = N_padded - N\n\n        y_ = relay.nn.pad(y, pad_width=((0, dn), (0, 0)))\n\n        # If units is explicitly specified, it is used to compute the output shape.\n        # We need to update units after padding to prevent a type error.\n        if attrs[\"units\"] is not None:\n            new_attrs[\"units\"] = N + dn\n\n        arg_types = [\n            arg_types[0],\n            tvm.ir.tensor_type.TensorType([N + dn, arg_types[1].shape[1]], arg_types[1].dtype),\n        ]\n\n        vrmpy_out = vrmpy_legalize(x, y_, arg_types, relay.nn.dense, new_attrs)\n\n        if vrmpy_out is None:\n            out_ = relay.nn.dense(x, y_, **new_attrs)\n        else:\n            out_ = vrmpy_out\n\n        out = relay.strided_slice(out_, begin=[0, 0], end=[x.value for x in output_tensor.shape])\n        return out\n\n    return vrmpy_legalize(inputs[0], inputs[1], arg_types, relay.nn.dense, attrs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Schedule for injective operators\"\"\"\n\nimport tvm\n\nimport numpy as np\n\n\ndef schedule_injective(outs):\n    \"\"\"Schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of injective in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    # Fuse axes and vectorize inner elements\n    for x in outs:\n        fused = s[x].fuse(*x.op.axis)\n        outer, inner = s[x].split(fused, factor=128 // np.dtype(x.dtype).itemsize)\n        s[x].vectorize(inner)\n        s[x].parallel(outer)\n    return s\n\n\ndef schedule_softmax(outs):\n    return schedule_injective(outs)\n\n\ndef schedule_elemwise(outs):\n    return schedule_injective(outs)\n\n\ndef schedule_broadcast(outs):\n    return schedule_injective(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/pad.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Schedule for nn.pad operator\"\"\"\n\nimport tvm\n\nimport numpy as np\n\n\ndef schedule_pad(outs):\n    \"\"\"Schedule for pad op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of injective in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    # Fuse axes and vectorize only if last output tensor dimension is divisible by a factor:\n    factor = 128 // np.dtype(outs[0].dtype).itemsize\n    last_dim = outs[0].shape[-1]\n    if last_dim % factor == 0 and last_dim // factor >= 0:\n        fused = s[outs[0]].fuse(*outs[0].op.axis)\n        _, inner = s[outs[0]].split(fused, factor=factor)\n        s[outs[0]].vectorize(inner)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Schedule for pooling operators\"\"\"\n\nimport tvm\n\n\ndef schedule_pool(outs, layout=\"NHWC\"):  # pylint: disable=unused-argument\n    \"\"\"Schedule for pooling op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of injective in the format\n        of an array of tensors.\n\n    layout: str\n        The tensor layout.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n\n\ndef schedule_adaptive_pool(outs):\n    return schedule_pool(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Computes and schedules for Hexagon quantized ops \"\"\"\n\nfrom .avg_pool2d import qnn_avg_pool2d_compute, qnn_avg_pool2d_schedule\nfrom .qadd_qsub_qmul import *\nfrom .dequantize import (\n    dequantize_compute,\n    dequantize_schedule,\n)\n\nfrom .quantize import quantize_compute, tir_quantize_schedule\nfrom .nn import *\nfrom .qdepthwise_conv2d_slice import qdepthwise_conv2d_compute, qdepthwise_conv2d_schedule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/avg_pool2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals\n\n\"\"\" Compute and schedule for quantized avg_pool2d op\n\nPlease note the following assumptions made by the implementation:\n\n1) The input must be padded in advance to account for 'padding'. In addition,\n   both input and output must be padded as per the physical buffer layout.\n2) The current implementation assumes 'count_include_pad' to be 'True'. It can be\n   modified to support 'False' case but the element count for the pooling window\n   must be pre-computed and provided as an input to reduce the run-time overhead.\n3) 'padding' is ignored. It must be handled outside of the sliced op.\n4) Please note that this implementation will not work if the output includes any\n   physical layout related padding as it can result into out-of-bound access\n   for the input.\n\"\"\"\n\nfrom tvm import te\nfrom tvm import tir\nfrom ..utils import get_layout_transform_fn, get_fixed_point_value\n\n\ndef validate_out_shape(out_shape: list, in_shape: list, kernel: list, stride: list, dilation: list):\n    \"\"\"Validate output shape\"\"\"\n    _, oh, ow, _ = out_shape\n    _, ih, iw, _ = in_shape\n    kh, kw = kernel\n    sh, sw = stride\n    dh, dw = dilation\n    if ih < (oh - 1) * sh + dh * (kh - 1) + 1:\n        raise RuntimeError(\"Output height is too large\")\n    if iw < (ow - 1) * sw + dw * (kw - 1) + 1:\n        raise RuntimeError(\"Output width is too large\")\n\n\ndef saturate(x: te.Tensor, dtype: str):\n    \"\"\"Saturate value for the specified data type\"\"\"\n    return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype)))\n\n\ndef qnn_avg_pool2d_compute(\n    data: te.Tensor,\n    kernel: list,\n    stride: list,\n    dilation: list,\n    oshape: list,\n    odtype: str,\n    # quantization params:\n    input_zero_point: int,\n    input_scale: float,\n    output_zero_point: int,\n    output_scale: float,\n):\n    \"\"\"Compute for quantized avg_pool2d\"\"\"\n    kh, kw = kernel\n    rh = te.reduce_axis((0, kh), name=\"rh\")\n    rw = te.reduce_axis((0, kw), name=\"rw\")\n    ob, oh, ow, oc = oshape\n    if isinstance(ob, int):\n        validate_out_shape(oshape, data.shape, kernel, stride, dilation)\n\n    if odtype == \"uint8\":\n        temp_dtype = \"uint16\"\n    elif odtype == \"int8\":\n        temp_dtype = \"int16\"\n    else:\n        raise RuntimeError(f\"Unsupported output dtype, {odtype}'\")\n\n    sh, sw = stride\n    dh, dw = dilation\n\n    PoolArea = kh * kw\n\n    scale = input_scale / output_scale\n    scale_fixed_point, rsh = get_fixed_point_value(scale, \"int16\")\n    scale_with_area = scale_fixed_point // PoolArea\n    corr = (output_zero_point << rsh) - input_zero_point * scale_fixed_point\n\n    Sum = te.compute(\n        oshape,\n        lambda b, h, w, c: te.sum(\n            data[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(temp_dtype), axis=[rh, rw]\n        ),\n        name=\"sum\",\n    )\n\n    Avg = te.compute(\n        oshape,\n        lambda b, h, w, c: saturate(\n            ((Sum[b, h, w, c] * scale_with_area) + corr) >> rsh, odtype\n        ).astype(odtype),\n        name=\"avg\",\n    )\n    return Avg\n\n\ndef schedule_nhwc_8h8w32c(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str):\n    \"\"\"Schedule for input and output layout nhwc-8h8w32c\"\"\"\n    func = te.create_prim_func([ins, outs])\n    s = tir.Schedule(func)\n    Sum = s.get_block(\"sum\")\n    Avg = s.get_block(\"avg\")\n\n    input_transform_fn = get_layout_transform_fn(input_layout)\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Sum, (\"read\", 0), input_transform_fn)\n    s.transform_layout(Avg, (\"write\", 0), output_transform_fn)\n\n    # Schedule 'Avg'\n    # Split and reorder the axes to iterate over the output tensor chunks.\n    # Each chunk consists for 2048 bytes with 32 channels being the fastest\n    # changing axis, followed by 8 width and then 8 height.\n    # The width is split by a factor of 4 and then fused with 32 channels\n    # to provide full vector length of data for the output tensor chunks.\n    # NOTE: These schedules are a work in progress and may require\n    # adjustments in future as some of the missing features for 2-d tensors\n    # become available.\n    n, h, w, c = s.get_loops(Avg)\n    ho, hi = s.split(h, [None, 8])\n    wo, wi = s.split(w, [None, 8])\n    wio, wii = s.split(wi, [None, 4])\n    co, ci = s.split(c, [None, 32])\n    s.reorder(n, ho, wo, co, hi, wio, wii, ci)\n    wii_ci = s.fuse(wii, ci)\n    s.vectorize(wii_ci)\n\n    # Schedule 'Sum'\n    s.compute_at(Sum, wio)\n    Sum_axis = s.get_loops(Sum)\n    # Compute for 'Sum' includes reduction along height and width. The axes\n    # are being reordered so that 4 width and 32 channels become the\n    # inner-most loops which then can be fused and vectorized. However,\n    # vectorization of the 2-d tensors doesn't work when reduction is\n    # involved and requires codegen support that is yet to be added.\n    s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-4], Sum_axis[-3])\n    ci_wii = s.fuse(Sum_axis[-4], Sum_axis[-3])\n    # s.vectorize(ci_wii) # Doesn't work\n    return s\n\n\ndef schedule_n11c_2048c(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str):\n    \"\"\"Schedule for output layout: n11c-2048c, input layout: nhwc-8h8w32c\"\"\"\n    func = te.create_prim_func([ins, outs])\n    s = tir.Schedule(func)\n    Sum = s.get_block(\"sum\")\n    Avg = s.get_block(\"avg\")\n\n    input_transform_fn = get_layout_transform_fn(input_layout)\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Sum, (\"read\", 0), input_transform_fn)\n    s.transform_layout(Avg, (\"write\", 0), output_transform_fn)\n\n    # Schedule 'Avg'\n    # Split and reorder the axes to iterate over the output tensor chunks.\n    # Each chunk consists for 2048 bytes. For n11c-2048c tensor layout, each chunk\n    # only contains 2048 channels which get split by a factor of 128 to be vectorized.\n    # NOTE: These schedules are a work in progress and may require\n    # adjustments in future as some of the missing features for 2-d tensors\n    # become available.\n    n, h, w, c = s.get_loops(Avg)\n    co, ci = s.split(c, [None, 2048])\n    cio, cii = s.split(ci, [None, 128])\n    s.vectorize(cii)\n\n    # Schedule 'Sum'\n    # Compute for 'Sum' includes reduction along height and width. The axes are being\n    # reordered so that 128 channels become the inner-most loop and can be vectorized.\n    # However, vectorization of the 2-d tensors doesn't work when reduction is\n    # involved and requires codegen support that is yet to be added.\n    s.compute_at(Sum, cio)\n    Sum_axis = s.get_loops(Sum)\n    s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-3])\n    # s.vectorize(Sum_axis[-3]) # Doesn't work\n    return s\n\n\ndef qnn_avg_pool2d_schedule(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str):\n    \"\"\"Quantized avg_pool2d schedule\n\n    NOTE: This schedule assumes that both input and output tensors are in the form of\n    2d discontiguous buffer and data is already arranged as per the input and output layout\n    respectively.\n\n    \"\"\"\n    if output_layout == \"nhwc-8h8w32c-2d\":\n        return schedule_nhwc_8h8w32c(outs, ins, output_layout, input_layout)\n    if output_layout == \"n11c-2048c-2d\":\n        return schedule_n11c_2048c(outs, ins, output_layout, input_layout)\n    raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/dequantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" Hexagon qnn.dequantize slice op compute and schedule\"\"\"\n\nfrom tvm import te\nfrom tvm import tir\nfrom ..utils import get_layout_transform_fn\n\n\ndef dequantize_compute(tensor_A, scale_A, zero_point_A):\n\n    return te.compute(\n        tensor_A.shape,\n        lambda *indices: (scale_A * (tensor_A[indices] - zero_point_A)).astype(\"float32\"),\n        name=\"dequantize\",\n    )\n\n\ndef dequantize_stir_schedule_nhwc_8h8w32c(\n    _in,\n    _out,\n    in_layout,\n    out_layout,\n):\n    \"\"\"Schedule for nhwc int8/uint8 to f32 : nhwc layout\"\"\"\n    func = te.create_prim_func([_in, _out])\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"dequantize\"\n    n, h, w, c = sch.get_loops(sch.get_block(block_name))\n    ho, hi = sch.split(h, [None, 4])\n    wo, wi = sch.split(w, [None, 8])\n    wio, wii = sch.split(wi, [None, 4])\n    co, ci = sch.split(c, [None, 32])\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    sch.reorder(n, ho, wo, co, hi, wio, wii, ci)\n    wii_ci = sch.fuse(wii, ci)\n    sch.vectorize(wii_ci)\n    return sch\n\n\ndef dequantize_stir_schedule_nc(\n    _in,\n    _out,\n    in_layout,\n    out_layout,\n):\n    \"\"\"Schedule for nc int8/uint8 to f32 : nc layout\"\"\"\n    func = te.create_prim_func([_in, _out])\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"dequantize\"\n    _, c_orig = sch.get_loops(sch.get_block(block_name))\n    _, c_inner = sch.split(c_orig, [None, 512])\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    sch.vectorize(c_inner)\n    return sch\n\n\ndef dequantize_schedule(_in, _output, in_layout_str, out_layout_str):\n    \"\"\"Schedule for int8/uint8 to f32 : top level function\"\"\"\n    f32_layout_transform_func = get_layout_transform_fn(out_layout_str)\n    in_layout_transform_func = get_layout_transform_fn(in_layout_str)\n    if out_layout_str == \"nhwc-4h2w32c2w-2d\":\n        return dequantize_stir_schedule_nhwc_8h8w32c(\n            _in,\n            _output,\n            in_layout_transform_func,\n            f32_layout_transform_func,\n        )\n    if out_layout_str == \"nc-512c-2d\":\n        return dequantize_stir_schedule_nc(\n            _in,\n            _output,\n            in_layout_transform_func,\n            f32_layout_transform_func,\n        )\n    raise RuntimeError(f\"Unexpected layout '{layout}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hexagon QNN operators\"\"\"\n# pylint: disable=invalid-name\n\nimport tvm\nfrom tvm import te, topi\nfrom ...utils import get_const_tuple\nfrom ...nn.utils import get_pad_tuple\nfrom ...nn.pad import pad\nfrom ... import tag, nn\nfrom ...x86.concat import concatenate\n\n\ndef clip_cast(val, dtype):\n    # clip + cast:\n    const_min = tvm.tir.min_value(dtype)\n    const_max = tvm.tir.max_value(dtype)\n    return te.max(tvm.te.min(val, const_max), const_min).astype(dtype)\n\n\ndef get_qnn_param(param, indices, axis):\n    # Account scalar and 1D quantization parameters:\n    if len(param.shape) == 0:\n        return param\n\n    param_idx = tvm.tir.indexmod(indices[axis], topi.shape(param)[0])\n    return param[param_idx]\n\n\ndef default_schedule(outs):\n    \"\"\"Simple default schedule for QNN ops.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of dense in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n\n\ndef qnn_quantize(data, output_scale, output_zero_point, axis, out_dtype):\n    \"\"\"Compute for qnn.quantize\n\n    Q_output = clamp((round(input_tensor/output_scale) + output_zero_point),\n                     out_dtype::min,\n                     out_dtype::max)\n    \"\"\"\n\n    assert len(output_scale.shape) == 0 or len(output_scale.shape) == 1\n    assert len(output_zero_point.shape) == 0 or len(output_zero_point.shape) == 1\n\n    def _compute(*indices):\n        value = data(*indices)\n        scale = get_qnn_param(output_scale, indices, axis)\n        zp = get_qnn_param(output_zero_point, indices, axis)\n\n        val = te.add(te.round(te.div(value, scale)), zp)\n        return clip_cast(val, out_dtype)\n\n    return te.compute(data.shape, _compute, tag=tag.ELEMWISE)\n\n\ndef schedule_qnn_quantize(outs):\n    \"\"\"Schedule for qnn.quantize\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.quantize\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_dequantize(data, input_scale, input_zero_point, axis):\n    \"\"\"Compute for qnn.dequantize\n\n    fp_output = input_scale * (Q_input - input_zero_point)\n    \"\"\"\n\n    def _compute(*indices):\n        value = data(*indices)\n        scale = get_qnn_param(input_scale, indices, axis)\n        zp = get_qnn_param(input_zero_point, indices, axis)\n\n        return te.multiply(scale, te.subtract(value, zp))\n\n    return te.compute(data.shape, _compute, tag=tag.ELEMWISE)\n\n\ndef schedule_qnn_dequantize(outs):\n    \"\"\"Schedule for qnn.dequantize\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.dequantize\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_requantize(data, input_scale, input_zp, output_scale, output_zp, axis, out_dtype):\n    \"\"\"Compute for qnn.requantize\n\n    Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input))\n\n    TODO: support 'rounding' and 'compute_dtype' arguments.\n    \"\"\"\n\n    def _compute(*indices):\n        value = data(*indices)\n\n        iscale = get_qnn_param(input_scale, indices, axis)\n        oscale = get_qnn_param(output_scale, indices, axis)\n\n        sub = te.subtract(value, input_zp)\n        mul = te.div(iscale, oscale)\n        val = te.add(te.round(te.multiply(mul, sub)), output_zp)\n\n        # clip + cast:\n        const_min = tvm.tir.min_value(out_dtype)\n        const_max = tvm.tir.max_value(out_dtype)\n        return te.max(tvm.te.min(val, const_max), const_min).astype(out_dtype)\n\n    return te.compute(data.shape, _compute)\n\n\ndef schedule_qnn_requantize(outs):\n    \"\"\"Schedule for qnn.requantize\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.requantize\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_add(\n    lhs, rhs, lhs_scale, lhs_zero_point, rhs_scale, rhs_zero_point, output_scale, output_zero_point\n):\n    \"\"\"Compute for qnn.add\n\n    Q_output = zp_output + round((lhs_scale)/(scale_output) * (lhs_input - lhs_zp_input))\n                         + round((rhs_scale)/(scale_output) * (rhs_input - rhs_zp_input))\n\n    TODO: support 'axis' argument.\n    \"\"\"\n\n    assert lhs.dtype == rhs.dtype\n    dtype = lhs.dtype\n\n    def _compute(*indices):\n        lvalue = lhs(*indices)\n        rvalue = rhs(*indices)\n        q_lv = te.round(\n            te.multiply(te.div(lhs_scale, output_scale), te.subtract(lvalue, lhs_zero_point))\n        ).astype(\"int32\")\n        q_rv = te.round(\n            te.multiply(te.div(rhs_scale, output_scale), te.subtract(rvalue, rhs_zero_point))\n        ).astype(\"int32\")\n        val = te.add(te.add(q_lv, q_rv), output_zero_point)\n\n        # clip + cast:\n        const_min = tvm.tir.min_value(dtype)\n        const_max = tvm.tir.max_value(dtype)\n        return te.max(tvm.te.min(val, const_max), const_min).astype(dtype)\n\n    return te.compute(lhs.shape, _compute)\n\n\ndef schedule_qnn_add(outs):\n    \"\"\"Schedule for qnn.add\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.add\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef requantize_tensor(tensor, i_scale, i_zp, o_scale, o_zp, out_dtype):\n    \"\"\"Requantize tensor\"\"\"\n\n    def _compute(*indices):\n        value = tensor(*indices)\n        mul_value = te.round(\n            te.multiply(te.div(i_scale, o_scale), te.subtract(value, i_zp))\n        ).astype(\"int32\")\n        rq_value = te.add(mul_value, o_zp)\n\n        return clip_cast(rq_value, out_dtype)\n\n    return te.compute(tensor.shape, _compute)\n\n\ndef qnn_concatenate(data, axis, out_dtype):\n    \"\"\"Compute for qnn.concatenate\n\n    Parameters\n    ----------\n    data: Array of Tensor\n          The computation graph description of qnn.concatenate\n          in the format of an array of tensors.\n\n    axis: int\n          The axis along which the tensors are concatenated.\n\n    out_dtype: string\n          Data type of output tensor\n\n    Returns\n    -------\n    out: Tensor\n        The computation for the op.\n    \"\"\"\n\n    # Get output quantization parameters.\n    o_scale = data[-2]\n    o_zp = data[-1]\n\n    # Initially qnn.concatenate had 3 tuples: (1) tuple with input tensors, (2) tuple with input\n    # scales and (3) tuple with input zero points.\n    # Last 2 elements in data represent output scale and zero point.\n    num_of_tuples = 3\n    assert ((len(data) - 2) % num_of_tuples) == 0\n    args_num = (len(data) - 2) // num_of_tuples\n\n    args = []\n    for i in range(args_num):\n        # Get next tensor and its quantization parameters.\n        tensor = data[i]\n        i_scale = data[i + args_num]\n        i_zp = data[i + args_num * 2]\n\n        # Requantize tensors and add them to the list.\n        args.append(requantize_tensor(tensor, i_scale, i_zp, o_scale, o_zp, out_dtype))\n\n    # Call x86 implementation of concatenate.\n    return concatenate(args, axis)\n\n\ndef schedule_qnn_concatenate(outs):\n    \"\"\"Schedule for qnn.concatenate\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.add\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_conv2d(  # Conv2d inputs\n    data,\n    weight,\n    # Conv2d quantization params:\n    input_zero_point,\n    kernel_zero_point,\n    _input_scale,\n    _kernel_scale,\n    # bias\n    bias,\n    # Requantization params:\n    rq_input_scale,\n    rq_input_zero_point,\n    rq_output_scale,\n    rq_output_zero_point,\n    # Conv2d attributes:\n    strides,\n    padding,\n    dilation,\n    oshape,\n    odtype,\n):\n    \"\"\"Compute for qnn.conv2d with NCHW layout.\n\n    Output data type should be specified through the 'odtype' parameter. qnn.conv2d leverages int32\n    type to store intermediate results. If 'odtype' differs from int32, you need to specify\n    requantization parameters.\n    \"\"\"\n    in_channel = data.shape[1]  # NCHW layout\n    kernel_height = weight.shape[2]  # OIHW layout\n    kernel_width = weight.shape[3]  # OIHW layout\n\n    height_stride, width_stride = strides\n    dilation_h, dilation_w = dilation\n\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        get_const_tuple(padding), (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    # Subtract zero point from input and then do padding with 0 value\n    data = te.compute(data.shape, lambda *indices: te.subtract(data(*indices), input_zero_point))\n\n    # DOPAD\n    if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0:\n        pad_before = (0, 0, pad_top, pad_left)\n        pad_after = (0, 0, pad_down, pad_right)\n        data_pad = pad(data, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data\n\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n\n    # axis=0 in get_qnn_param means 'O' dimension in \"OIHW\" weights layout.\n    out = te.compute(\n        oshape,\n        lambda n, oc, oh, ow: te.sum(\n            data_pad[\n                n,\n                ic,\n                oh * height_stride + kh * dilation_h,\n                ow * width_stride + kw * dilation_w,\n            ].astype(\"int32\")\n            * te.subtract(\n                weight[oc, ic, kh, kw], get_qnn_param(kernel_zero_point, (oc, ic, kh, kw), axis=0)\n            ).astype(\"int32\"),\n            axis=[ic, kh, kw],\n        ),\n    )\n\n    # Add bias\n    if bias is not None:\n        assert len(out.shape) == len(bias.shape)\n        assert bias.shape[2] == 1 and bias.shape[3] == 1\n        out = te.compute(out.shape, lambda n, c, h, w: out[n, c, h, w] + bias[n, c, 0, 0])\n\n    # Requantize output of convolution\n    # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input))\n    if rq_input_scale is not None and rq_output_scale is not None:\n        # Now supported only scalar and 1D quantization parameters\n        assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1\n        assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1\n        axis = -1\n        if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1:\n            axis = 1  # Axis param should correspond to 'C' dimension.\n\n        return qnn_requantize(\n            out,\n            rq_input_scale,\n            rq_input_zero_point,\n            rq_output_scale,\n            rq_output_zero_point,\n            axis,\n            odtype,\n        )\n\n    return out\n\n\ndef schedule_qnn_conv2d(outs):\n    \"\"\"Schedule for qnn.conv2d\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.conv2d\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_depthwise_conv2d(  # Conv2d inputs\n    data,\n    weight,\n    # Conv2d quantization params:\n    input_zero_point,\n    kernel_zero_point,\n    _input_scale,\n    _kernel_scale,\n    # bias\n    bias,\n    # Requantization params:\n    rq_input_scale,\n    rq_input_zero_point,\n    rq_output_scale,\n    rq_output_zero_point,\n    # Conv2d attributes:\n    strides,\n    padding,\n    dilation,\n    oshape,\n    odtype,\n):\n    \"\"\"Compute for qnn.conv2d with NCHW layout\n\n    Output data type should be specified through the 'odtype' parameter. qdepthwise nn.conv2d\n    leverages int32 type to store intermediate results. If 'odtype' differs from int32, you need to\n    specify requantization parameters.\n    \"\"\"\n    kernel_height = weight.shape[2]  # OIHW layout\n    kernel_width = weight.shape[3]  # OIHW layout\n\n    height_stride, width_stride = strides\n    dilation_h, dilation_w = dilation\n\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        get_const_tuple(padding), (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    # Subtract zero point from input and then do padding with 0 value\n    data = te.compute(data.shape, lambda *indices: te.subtract(data(*indices), input_zero_point))\n\n    # DOPAD\n    if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0:\n        pad_before = (0, 0, pad_top, pad_left)\n        pad_after = (0, 0, pad_down, pad_right)\n        data_pad = pad(data, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data\n\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n\n    out = te.compute(\n        oshape,\n        lambda n, oc, oh, ow: te.sum(\n            data_pad[\n                n,\n                oc,\n                oh * height_stride + kh * dilation_h,\n                ow * width_stride + kw * dilation_w,\n            ].astype(\"int32\")\n            * te.subtract(weight[oc, 0, kh, kw], kernel_zero_point).astype(\"int32\"),\n            axis=[kh, kw],\n        ),\n    )\n\n    # Add bias\n    if bias is not None:\n        assert len(out.shape) == len(bias.shape)\n        assert bias.shape[2] == 1 and bias.shape[3] == 1\n        out = te.compute(out.shape, lambda n, c, h, w: out[n, c, h, w] + bias[n, c, 0, 0])\n\n    # Requantize output of convolution\n    # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input))\n    if rq_input_scale is not None and rq_output_scale is not None:\n        # Now supported only scalar and 1D quantization parameters\n        assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1\n        assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1\n        axis = -1\n        if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1:\n            axis = 1  # Axis param should correspond to 'C' dimension.\n\n        return qnn_requantize(\n            out,\n            rq_input_scale,\n            rq_input_zero_point,\n            rq_output_scale,\n            rq_output_zero_point,\n            axis,\n            odtype,\n        )\n\n    return out\n\n\ndef schedule_qnn_depthwise_conv2d(outs):\n    \"\"\"Schedule for depthwise qnn.conv2d\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.conv2d\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_dense(\n    data,\n    weight,\n    # Dense quantization params:\n    input_zero_point,\n    kernel_zero_point,\n    _input_scale,\n    _kernel_scale,\n    # bias\n    bias,\n    # Requantization params:\n    rq_input_scale,\n    rq_input_zero_point,\n    rq_output_scale,\n    rq_output_zero_point,\n    out_dtype,\n):\n    \"\"\"Compute for qnn.dense\n\n    Output data type should be specified through the 'odtype' parameter. qnn.dense leverages int32\n    type to store intermediate results. If 'odtype' differs from int32, you need to specify\n    requantization parameters.\n    \"\"\"\n    M, K = get_const_tuple(data.shape)\n    N, _ = get_const_tuple(weight.shape)\n    k = te.reduce_axis((0, K), \"k\")\n    # This implementation uses \"int32\" dense output data type.\n    # axis=0 in get_qnn_param mean 'N' dimension in \"NK\" weights layout.\n    out = te.compute(\n        (M, N),\n        lambda m, n: te.sum(\n            te.subtract(data[m, k], input_zero_point).astype(\"int32\")\n            * te.subtract(weight[n, k], get_qnn_param(kernel_zero_point, (n, k), axis=0)).astype(\n                \"int32\"\n            ),\n            axis=k,\n        ),\n    )\n\n    # Add bias\n    if bias is not None:\n        out = te.compute(out.shape, lambda n, c: out[n, c] + bias[c])\n\n    # Requantize output of dense\n    # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input))\n    if rq_input_scale is not None and rq_output_scale is not None:\n        # Now supported only scalar and 1D quantization parameters\n        assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1\n        assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1\n        axis = -1\n        if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1:\n            axis = 1  # Axis param should correspond to 'N' dimension.\n\n        return qnn_requantize(\n            out,\n            rq_input_scale,\n            rq_input_zero_point,\n            rq_output_scale,\n            rq_output_zero_point,\n            axis,\n            out_dtype,\n        )\n\n    return out\n\n\ndef schedule_qnn_dense(outs):\n    \"\"\"Schedule for qnn.dense\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.dense\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n\n\ndef qnn_batch_matmul(\n    tensor_a,\n    tensor_b,\n    # batch_matmul quantization params:\n    a_zero_point,\n    b_zero_point,\n    _a_scale,\n    _b_scale,\n    # Attributes\n    transpose_a,\n    transpose_b,\n    out_dtype,\n):\n    \"\"\"Compute for qnn.batch_matmul\"\"\"\n\n    # Preprocess tensor_a: subtract zp\n    a_sub_zp = te.compute(\n        tensor_a.shape, lambda *indices: te.subtract(tensor_a(*indices), a_zero_point)\n    )\n    # Preprocess tensor_b: subtract zp\n    b_sub_zp = te.compute(\n        tensor_b.shape, lambda *indices: te.subtract(tensor_b(*indices), b_zero_point)\n    )\n\n    return nn.batch_matmul(a_sub_zp, b_sub_zp, None, out_dtype, transpose_a, transpose_b)\n\n\ndef schedule_qnn_batch_matmul(outs):\n    \"\"\"Schedule for qnn.batch_matmul\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of qnn.batch_matmul\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return default_schedule(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/qadd_qsub_qmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n# pylint: disable=invalid-name\r\n\r\n\"\"\"Compute and schedule for quantized add, multiply, subtract op\r\n\r\nPlease note the following assumptions made by the implementation:\r\n\r\n1) The inputs will be multiple of crouton layout except for the axis that needs broadcasting.\"\"\"\r\n\r\nfrom tvm import te\r\nfrom tvm import tir\r\nfrom ..utils import get_layout_transform_fn, get_fixed_point_value\r\n\r\n\r\ndef broadcast_axis(tensor_A, tensor_B):\r\n    \"\"\"Find out the indices that will have broadcasting\"\"\"\r\n    A_broadcast = []\r\n    B_broadcast = []\r\n\r\n    for i in range(len(tensor_A.shape)):\r\n        if tensor_A.shape[i] == tensor_B.shape[i]:\r\n            A_broadcast.append(1)\r\n            B_broadcast.append(1)\r\n        elif tensor_A.shape[i] == 1:\r\n            A_broadcast.append(0)\r\n            B_broadcast.append(1)\r\n        elif tensor_B.shape[i] == 1:\r\n            A_broadcast.append(1)\r\n            B_broadcast.append(0)\r\n    return A_broadcast, B_broadcast\r\n\r\n\r\ndef saturate(x: te.Tensor, dtype: str):\r\n    \"\"\"Saturate value for the specified data type\"\"\"\r\n    return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype)))\r\n\r\n\r\ndef get_int_scale(\r\n    scale_A: float,\r\n    scale_B: float,\r\n    scale_M: float,\r\n    zero_point_A: int,\r\n    zero_point_B: int,\r\n    zero_point_M: int,\r\n    op: str,\r\n):\r\n    \"\"\"\r\n    Get fixed-point number and exp_scale_factor from topi.hexagon.utils.get_fixed_point_value.\r\n    Also, depending on the op, this function uses exp_scale_factor(log2 of the scale factor)\r\n    to adjust the output's zero_point.\r\n    \"\"\"\r\n\r\n    C_recip = 1 / scale_M\r\n\r\n    if op == \"qmul\":\r\n        scale = scale_A * scale_B * C_recip\r\n        scale_fixed_point, rsh = get_fixed_point_value(scale, \"int16\")\r\n\r\n        # We need to adjust output's zero point value since the compute for the op is multiplied\r\n        # by a scaling factor.\r\n        # The scaling factor is 2^x where x is the exp_scale_factor which is assigned to rsh here.\r\n        # Since zero_point_M is multipled by 2^rsh while converting floating-point scale value\r\n        # into fixed-point number, we left shift it by rsh in our compute to reflect that.\r\n\r\n        corr = zero_point_M << rsh\r\n\r\n        return scale_fixed_point, rsh, corr\r\n\r\n    a_scale_f = scale_A * C_recip\r\n    b_scale_f = scale_B * C_recip\r\n    scale_fixed_point_a, rsh_a = get_fixed_point_value(a_scale_f, \"int16\")\r\n    scale_fixed_point_b, rsh_b = get_fixed_point_value(b_scale_f, \"int16\")\r\n\r\n    # Here we have two exp_scale_factors rsh_a and rsh_b.\r\n    # To avoid complexity, we want to use a common exp_scale_factor and\r\n    # we want to use the lowest of the two.\r\n\r\n    # Since, either of scale_fixed_point_a or scale_fixed_point_b has already been multiplied\r\n    # by 2^max(rsh_a, rsh_b) in topi.hexagon.utils.get_fixed_point_value,\r\n    # we want to undo that by right shifting that scale_fixed_point value\r\n    # by the difference of rsh_a and rsh_b.\r\n\r\n    # This results into having a common exp_scale_factor for both scale_fixed_point_a\r\n    # and scale_fixed_point_b.\r\n\r\n    # We also set rsh here which is used to adjust the zero_point_M and compute the corr value,\r\n    # computation of which comes from the original equation of the op's compute.\r\n\r\n    if rsh_a > rsh_b:\r\n        scale_fixed_point_a = scale_fixed_point_a >> (rsh_a - rsh_b)\r\n        rsh = rsh_b\r\n    else:\r\n        scale_fixed_point_b = scale_fixed_point_b >> (rsh_b - rsh_a)\r\n        rsh = rsh_a\r\n\r\n    if op == \"qadd\":\r\n        corr = (zero_point_M << rsh) - (\r\n            zero_point_A * scale_fixed_point_a + zero_point_B * scale_fixed_point_b\r\n        )\r\n    else:\r\n        corr = (zero_point_M << rsh) - (\r\n            zero_point_A * scale_fixed_point_a - zero_point_B * scale_fixed_point_b\r\n        )\r\n\r\n    return scale_fixed_point_a, scale_fixed_point_b, rsh, corr\r\n\r\n\r\ndef qadd_broadcast_compute(\r\n    tensor_A: te.Tensor,\r\n    tensor_B: te.Tensor,\r\n    output_shape: list,\r\n    zero_point_A: int,\r\n    scale_A: float,\r\n    zero_point_B: int,\r\n    scale_B: float,\r\n    zero_point_M: int,\r\n    scale_M: float,\r\n    dtype: str,\r\n):\r\n    \"\"\"Compute quantized add with broadcasting\"\"\"\r\n    A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B)\r\n    n_a, h_a, w_a, c_a = A_broadcast\r\n    n_b, h_b, w_b, c_b = B_broadcast\r\n\r\n    scale_a, scale_b, rsh, corr = get_int_scale(\r\n        scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, \"qadd\"\r\n    )\r\n\r\n    return te.compute(\r\n        output_shape,\r\n        lambda n, h, w, c: saturate(\r\n            (\r\n                (\r\n                    (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] * scale_a)\r\n                    + (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] * scale_b)\r\n                    + corr\r\n                )\r\n                >> rsh\r\n            ),\r\n            dtype,\r\n        ).astype(dtype),\r\n    )\r\n\r\n\r\ndef qsubtract_broadcast_compute(\r\n    tensor_A: te.Tensor,\r\n    tensor_B: te.Tensor,\r\n    output_shape: list,\r\n    zero_point_A: int,\r\n    scale_A: float,\r\n    zero_point_B: int,\r\n    scale_B: float,\r\n    zero_point_M: int,\r\n    scale_M: float,\r\n    dtype: str,\r\n):\r\n    \"\"\"Compute quantized subtract with broadcasting\"\"\"\r\n    A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B)\r\n    n_a, h_a, w_a, c_a = A_broadcast\r\n    n_b, h_b, w_b, c_b = B_broadcast\r\n\r\n    scale_a, scale_b, rsh, corr = get_int_scale(\r\n        scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, \"qsub\"\r\n    )\r\n\r\n    return te.compute(\r\n        output_shape,\r\n        lambda n, h, w, c: saturate(\r\n            (\r\n                (\r\n                    (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] * scale_a)\r\n                    - (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] * scale_b)\r\n                    + corr\r\n                )\r\n                >> rsh\r\n            ),\r\n            dtype,\r\n        ).astype(dtype),\r\n    )\r\n\r\n\r\ndef qmultiply_broadcast_compute(\r\n    tensor_A: te.Tensor,\r\n    tensor_B: te.Tensor,\r\n    output_shape: list,\r\n    zero_point_A: int,\r\n    scale_A: float,\r\n    zero_point_B: int,\r\n    scale_B: float,\r\n    zero_point_M: int,\r\n    scale_M: float,\r\n    dtype: str,\r\n):\r\n    \"\"\"Compute quantized multiply with broadcasting\"\"\"\r\n    A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B)\r\n    n_a, h_a, w_a, c_a = A_broadcast\r\n    n_b, h_b, w_b, c_b = B_broadcast\r\n\r\n    scale_int, rsh, corr = get_int_scale(\r\n        scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, \"qmul\"\r\n    )\r\n\r\n    return te.compute(\r\n        output_shape,\r\n        lambda n, h, w, c: saturate(\r\n            (\r\n                (\r\n                    scale_int\r\n                    * (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] - zero_point_A)\r\n                    * (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] - zero_point_B)\r\n                    + corr\r\n                )\r\n                >> rsh\r\n            ),\r\n            dtype,\r\n        ).astype(dtype),\r\n    )\r\n\r\n\r\ndef tir_schedule_quant(\r\n    out_M: te.Tensor,\r\n    tensor_A: te.Tensor,\r\n    tensor_B: te.Tensor,\r\n    output_layout: str,\r\n    tensor_A_layout: str,\r\n    tensor_B_layout: str,\r\n):\r\n    \"\"\"Schedule for output layout nhwc-8h8w32c-2d\"\"\"\r\n    func = te.create_prim_func([tensor_A, tensor_B, out_M])\r\n\r\n    s = tir.Schedule(func)\r\n\r\n    block = s.get_block(\"compute\")\r\n\r\n    if tensor_A_layout == \"nhwc-8h8w32c-2d\":\r\n        tensor_A_transformed_layout = get_layout_transform_fn(tensor_A_layout)\r\n        s.transform_layout(block, buffer=tensor_A.name, index_map=tensor_A_transformed_layout)\r\n\r\n    if tensor_B_layout == \"nhwc-8h8w32c-2d\":\r\n        tensor_B_transformed_layout = get_layout_transform_fn(tensor_B_layout)\r\n        s.transform_layout(block, buffer=tensor_B.name, index_map=tensor_B_transformed_layout)\r\n\r\n    output_transformed_layout = get_layout_transform_fn(output_layout)\r\n    s.transform_layout(block, buffer=out_M.name, index_map=output_transformed_layout)\r\n\r\n    n, h, w, c = s.get_loops(block)\r\n\r\n    h_o, h_i = s.split(h, [None, 8])\r\n    w_o, w_i = s.split(w, [None, 8])\r\n    c_o, c_i = s.split(c, [None, 32])\r\n    wio, wii = s.split(w_i, [None, 4])\r\n\r\n    s.reorder(n, h_o, w_o, c_o, h_i, wio, wii, c_i)\r\n\r\n    return s\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/qdepthwise_conv2d_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals\n\"\"\"\nPlease note the following assumptions made by the implementation:\n1) The input must be padded in advance to account for 'padding'. In addition,\n   both input and output must be padded as per the physical buffer layout.\n2) 'padding' is ignored. It must be handled outside of the sliced op.\n3) The weights are expected to be as per physical layout\n\nThe initial compute for quantized depthwise conv2d is as follows\nwhere cm = channel_multiplier; assumed to be 1,\nzp_a = Activation_zero_point,\nzp_w = Weight_zero_point,\nQa = Quantized Activation,\nQw = Quantized Weights.\n\n     a) Qc(n, oh, ow, oc) = (Sigma(r, s) (Qw(r, s, oc%cm, oc/cm) - zp_w)\n                                      * (Qa(n, oh + r, ow + s, oc/cm) - zp_a))\n                                      * scale_value\n        where scale_value = (activation_scale * weight_scale) / output_scale\n\n        This can be written as\n\n     b) Qc(n, oh, ow, oc) = (t1 - t2 - t3 + t4) * scale_value\n\n        where t1 = Sigma(r, s) Qw(r, s, oc%cm, oc/cm) * Qa(n, oh + r, ow + s, oc/cm)\n              t2 = Sigma(r, s) zp_w * Qa(n, oh + r, ow + s, oc/cm)\n              t3 = Sigma(r, s) zp_a * Qw(r, s, oc%cm, oc/cm)\n              t4 = Sigma(r, s) zp_a * zp_w\n\n     c) Qc(n, oh, ow, oc) = saturate(((t1 - t2 - t3 + t4) * fixed_scale_value)) >> rsh)\n\n        where fixed_scale_value, rsh are fixed point values for scale_value.\n\n\nCompute and schedule for quantized depthwise conv2d slice op\"\"\"\n\nimport typing\nimport tvm\nfrom tvm import te\nfrom ..utils import get_layout_transform_fn, get_fixed_point_value, saturate\n\n\ndef qdepthwise_conv2d_compute(\n    activations: te.Tensor,\n    weights: te.Tensor,\n    out_shape: typing.Tuple,\n    stride: typing.Tuple,\n    dilation: typing.Tuple,\n    dtype: str,\n    # quantization params:\n    activation_zero_point,\n    activation_scale,\n    weight_zero_point,\n    weight_scale,\n    output_zero_point,\n    output_scale,\n):\n    \"\"\"Compute for quantized depthwise conv2d\"\"\"\n    filt_shape = weights.shape\n    ob, oh, ow, oc = out_shape\n\n    if dtype == \"uint8\":\n        temp_dtype = \"int32\"\n        big_dtype = \"int64\"\n    elif dtype == \"int8\":\n        temp_dtype = \"int32\"\n        big_dtype = \"int64\"\n    else:\n        raise RuntimeError(f\"Unsupported output dtype, {odtype}'\")\n\n    reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name=\"reduce_height\")\n    reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name=\"reduce_width\")\n    stride_height, stride_width = stride\n    dilation_height, dilation_width = dilation\n\n    scale_value = (activation_scale * weight_scale) / output_scale\n    fixed_scale_value, rsh = get_fixed_point_value(scale_value, \"int16\")\n\n    t1 = tvm.te.compute(\n        out_shape,\n        lambda n, h, w, c: tvm.te.sum(\n            (\n                (\n                    activations[\n                        n,\n                        h * stride_height + reduce_height * dilation_height,\n                        w * stride_width + reduce_width * dilation_width,\n                        c,\n                    ].astype(temp_dtype)\n                )\n                * (weights[reduce_height, reduce_width, 0, c].astype(temp_dtype))\n            ).astype(temp_dtype),\n            axis=[reduce_height, reduce_width],\n        ),\n        name=\"t1\",\n    )\n\n    t2 = tvm.te.compute(\n        out_shape,\n        lambda n, h, w, c: tvm.te.sum(\n            (\n                (\n                    activations[\n                        n,\n                        h * stride_height + reduce_height * dilation_height,\n                        w * stride_width + reduce_width * dilation_width,\n                        c,\n                    ].astype(temp_dtype)\n                )\n                * weight_zero_point\n            ).astype(temp_dtype),\n            axis=[reduce_height, reduce_width],\n        ),\n        name=\"t2\",\n    )\n\n    t3 = tvm.te.compute(\n        (oc,),\n        lambda c: tvm.te.sum(\n            (\n                ((weights[reduce_height, reduce_width, 0, c].astype(temp_dtype)))\n                * activation_zero_point\n            ).astype(temp_dtype),\n            axis=[reduce_height, reduce_width],\n        ),\n        name=\"t3\",\n    )\n\n    t4 = activation_zero_point * weight_zero_point * reduce_height * reduce_width\n\n    output = tvm.te.compute(\n        out_shape,\n        lambda n, h, w, c: saturate(\n            (\n                (\n                    (\n                        ((t1[n, h, w, c]).astype(big_dtype) - t2[n, h, w, c] - t3[c] + t4)\n                        * fixed_scale_value\n                    )\n                    >> rsh\n                )\n                + (output_zero_point).astype(big_dtype)\n            ),\n            dtype,\n        ).astype(dtype),\n        name=\"output\",\n    )\n\n    return output\n\n\ndef qdepthwise_conv2d_schedule(\n    outs: te.Tensor,\n    ins: typing.List[te.Tensor],\n    transform_activation_layout: str,\n    transform_weights: str,\n):\n    \"\"\"\n    Schedule for quantized depthwise conv2d for input layout nhwc-8h8w32c\n    assert len(ins) == 2, \"This schedule expects only 2 inputs - Activations and Weights\n    \"\"\"\n    source_expr = ins + [outs]\n    prim_func = tvm.te.create_prim_func(source_expr)\n    sch = tvm.tir.Schedule(prim_func)\n\n    compute = sch.get_block(\"output\")\n    compute1 = sch.get_block(\"t1\")\n\n    transform_layout_fn = get_layout_transform_fn(transform_activation_layout)\n    transform_layout_weights = get_layout_transform_fn(transform_weights)\n\n    # Apply layout_transform for activation\n    sch.transform_layout(compute1, ins[0].name, transform_layout_fn)\n\n    # Apply layout_transform for weights\n    sch.transform_layout(compute1, ins[1].name, transform_layout_weights)\n\n    # Apply layout_transform for output\n    sch.transform_layout(compute, outs.name, transform_layout_fn)\n\n    # This returns the original 6d loop\n    batch, height, width, channel, reduce_height, reduce_width = sch.get_loops(compute1)\n    h_outer, h_inner = sch.split(height, [None, 8])\n    w_outer, w_inner = sch.split(width, [None, 8])\n    c_outer, c_inner = sch.split(channel, [None, 32])\n    sch.reorder(\n        batch,\n        h_outer,\n        w_outer,\n        c_outer,\n        h_inner,\n        reduce_height,\n        reduce_width,\n        w_inner,\n        c_inner,\n    )\n\n    sch.decompose_reduction(compute1, reduce_height)\n    # wi_ci = sch.fuse(w_inner,c_inner)\n    # sch.vectorize(wi_ci)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/qnn/quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n# pylint: disable=invalid-name\r\n\"\"\"Compute and schedule for hexagon quantize\r\nPlease note the following assumptions made by the implementation:\r\n1) The input and output data will be multiple of crouton layout\r\n2) And the supported layout is NHWC\r\n3) The input layout will be nhwc-4h2w32c2w-2d and\r\n   output layout will be nhwc-8h8w32c-2d\"\"\"\r\n\r\n\r\nfrom tvm import te\r\nfrom tvm import tir\r\nfrom ..utils import get_layout_transform_fn, saturate\r\n\r\n\r\ndef quantize_compute(tensor_A: te.Tensor, scale: float, zero_point: int, dtype: str):\r\n    \"\"\"Compute for quantize\"\"\"\r\n    scale_recip = 1 / scale\r\n\r\n    return te.compute(\r\n        tensor_A.shape,\r\n        lambda n, h, w, c: saturate(\r\n            ((tensor_A[n, h, w, c] * scale_recip).astype(\"int32\") + zero_point),\r\n            dtype,\r\n        ).astype(dtype),\r\n        name=\"quantize\",\r\n    )\r\n\r\n\r\ndef tir_quantize_schedule(\r\n    out_M: te.Tensor,\r\n    tensor_A: te.Tensor,\r\n    input_layout: str,\r\n    output_layout: str,\r\n):\r\n    \"\"\"Schedule for output layout nhwc-8h8w32c-2d\"\"\"\r\n    func = te.create_prim_func([tensor_A, out_M])\r\n\r\n    s = tir.Schedule(func)\r\n\r\n    block = s.get_block(\"quantize\")\r\n\r\n    input_transformed_layout = get_layout_transform_fn(input_layout)\r\n    s.transform_layout(block, buffer=tensor_A.name, index_map=input_transformed_layout)\r\n\r\n    output_transformed_layout = get_layout_transform_fn(output_layout)\r\n    s.transform_layout(block, buffer=out_M.name, index_map=output_transformed_layout)\r\n\r\n    # Fixed chunk size is 2048 byte\r\n    # For uint8 the layout for fixed chunk is 8x8x32\r\n    # where each element is 1 bytes\r\n    # Split and reorder is done to iterate over the fixed chunk\r\n    # Channel is split by a factor of 32\r\n    # Width is split by a factor of 8\r\n    # Height is split by a factor of 8\r\n    n, h, w, c = s.get_loops(block)\r\n\r\n    h_o, h_i = s.split(h, [None, 8])\r\n    w_o, w_i = s.split(w, [None, 8])\r\n    c_o, c_i = s.split(c, [None, 32])\r\n    wio, wii = s.split(w_i, [None, 4])\r\n\r\n    s.reorder(n, h_o, w_o, c_o, h_i, wio, wii, c_i)\r\n\r\n    return s\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Schedule for composition of reduction operator\"\"\"\n\nimport tvm\n\n\ndef schedule_reduce(outs):\n    \"\"\"Schedule for reduction op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of reduction in the format\n        of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs\n    s = tvm.te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/resize2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n# pylint: disable=invalid-name\r\n\r\n\"\"\"Compute and schedule for resize2d\r\nPlease note the following assumptions made by the implementation:\r\n1) The input and output data will be multiple of crouton layout\r\n2) And the supported layout is NHWC\"\"\"\r\n\r\nfrom tvm import te\r\nfrom tvm import tir\r\nfrom tvm import topi\r\nfrom .utils import get_layout_transform_fn\r\n\r\n\r\ndef resize2d_compute(\r\n    data,\r\n    roi,\r\n    size,\r\n    layout,\r\n    method=\"linear\",\r\n    coordinate_transformation_mode=\"half_pixel\",\r\n    rounding_method=\"\",\r\n    bicubic_alpha=-0.5,\r\n    bicubic_exclude=0,\r\n    extrapolation_value=0.0,\r\n    out_dtype=None,\r\n    output_shape=None,\r\n):\r\n    \"\"\"Call resize2d op from topi.image\"\"\"\r\n    return topi.image.resize2d(\r\n        data,\r\n        roi,\r\n        size,\r\n        layout,\r\n        method,\r\n        coordinate_transformation_mode,\r\n        rounding_method,\r\n        bicubic_alpha,\r\n        bicubic_exclude,\r\n        extrapolation_value,\r\n        out_dtype,\r\n        output_shape,\r\n    )\r\n\r\n\r\ndef tir_resize2d_schedule(\r\n    out_m,\r\n    input_a,\r\n    input_layout: str,\r\n    output_layout: str,\r\n):\r\n    \"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d and nhwc-8h8w32c-2d\"\"\"\r\n    func = te.create_prim_func([input_a, out_m])\r\n\r\n    s = tir.Schedule(func)\r\n\r\n    block = s.get_block(\"resize\")\r\n\r\n    if input_layout in (\r\n        \"nhwc-8h2w32c2w-2d\",\r\n        \"nhwc-8h8w32c-2d\",\r\n    ):\r\n        input_transformed_layout = get_layout_transform_fn(input_layout)\r\n        s.transform_layout(block, buffer=(\"read\", 0), index_map=input_transformed_layout)\r\n\r\n    output_transformed_layout = get_layout_transform_fn(output_layout)\r\n    s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout)\r\n\r\n    if output_layout == \"nhwc-8h2w32c2w-2d\":\r\n        # Fixed chunk size is 2048 byte\r\n        # For fp16 the layout for fixed chunk is 8x4x32\r\n        # where each element is 2 bytes\r\n        # Split and reorder is done to iterate over the fixed chunk\r\n        # Channel is split by a factor of 32\r\n        # Width is split by a factor of 4\r\n        # Height is split by a factor of 8\r\n        n, h, w, c = s.get_loops(block)\r\n\r\n        ho, hi = s.split(h, [None, 8])\r\n        wo, wi = s.split(w, [None, 4])\r\n        co, ci = s.split(c, [None, 32])\r\n\r\n        s.reorder(n, ho, wo, co, hi, wi, ci)\r\n\r\n    elif output_layout == \"nhwc-8h8w32c-2d\":\r\n        # Fixed chunk size is 2048 byte\r\n        # For uint8 the layout for fixed chunk is 8x8x32\r\n        # where each element is 1 bytes\r\n        # Split and reorder is done to iterate over the fixed chunk\r\n        # Channel is split by a factor of 32\r\n        # Width is split by a factor of 8\r\n        # Height is split by a factor of 8\r\n        n, h, w, c = s.get_loops(block)\r\n\r\n        ho, hi = s.split(h, [None, 8])\r\n        wo, wi = s.split(w, [None, 8])\r\n        co, ci = s.split(c, [None, 32])\r\n\r\n        s.reorder(n, ho, wo, co, hi, wi, ci)\r\n\r\n    return s\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Computes and Schedules for Hexagon slice ops. \"\"\"\n\nfrom .avg_pool2d import avg_pool2d_compute, avg_pool2d_schedule\nfrom .max_pool2d import max_pool2d_compute, max_pool2d_STIR_schedule\nfrom .add_subtract_multiply import *\nfrom .argmax import argmax_compute, argmax_schedule\nfrom .batch_flatten import batch_flatten_compute, batch_flatten_stir_schedule\nfrom .softmax_slice import *\nfrom .clip import *\nfrom .cast import (\n    cast_f16_f32_compute,\n    cast_f16_f32_schedule,\n    cast_f32_f16_compute,\n    cast_f32_f16_schedule,\n)\nfrom .conv2d import *\nfrom .reshape import reshape_compute, reshape_stir_schedule\nfrom .relu import relu_compute, relu_stir_schedule\nfrom .tanh import tanh_te_compute, tanhf16_schedule\nfrom .dwconv2d import *\nfrom .depth_to_space import d2s_compute, d2s_schedule\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/add_subtract_multiply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n# pylint: disable=invalid-name\r\n\r\n\"\"\"Compute and schedule for add, multiply, subtract slice op\r\n\r\nPlease note the following assumptions made by the implementation:\r\n\r\n1) The inputs will be multiple of crouton layout except for the axis that needs broadcasting.\"\"\"\r\n\r\nfrom tvm import te\r\nfrom tvm import tir\r\nfrom tvm import topi\r\nfrom ..utils import get_layout_transform_fn\r\n\r\n\r\ndef add_broadcast_compute(input_a, input_b):\r\n    \"\"\"Call the add op from topi\"\"\"\r\n    return topi.add(input_a, input_b)\r\n\r\n\r\ndef subtract_broadcast_compute(input_a, input_b):\r\n    \"\"\"Call the subtract op from topi\"\"\"\r\n    return topi.subtract(input_a, input_b)\r\n\r\n\r\ndef multiply_broadcast_compute(input_a, input_b):\r\n    \"\"\"Call the multiply op from topi\"\"\"\r\n    return topi.multiply(input_a, input_b)\r\n\r\n\r\ndef tir_broadcast_schedule(\r\n    out_m,\r\n    input_a,\r\n    input_b,\r\n    output_layout: str,\r\n    input_a_layout: str,\r\n    input_b_layout: str,\r\n    op_name: str,\r\n):\r\n    \"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\"\r\n    func = te.create_prim_func([input_a, input_b, out_m])\r\n\r\n    s = tir.Schedule(func)\r\n\r\n    block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"}\r\n\r\n    block = s.get_block(block_dict[op_name])\r\n\r\n    if input_a_layout == \"nhwc-8h2w32c2w-2d\":\r\n        input_a_transformed_layout = get_layout_transform_fn(input_a_layout)\r\n        s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout)\r\n\r\n    if input_b_layout == \"nhwc-8h2w32c2w-2d\":\r\n        input_b_transformed_layout = get_layout_transform_fn(input_b_layout)\r\n        s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout)\r\n\r\n    output_transformed_layout = get_layout_transform_fn(output_layout)\r\n    s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout)\r\n\r\n    n, h, w, c = s.get_loops(block)\r\n\r\n    h_o, h_i = s.split(h, [None, 8])\r\n    w_o, w_i = s.split(w, [None, 4])\r\n    c_o, c_i = s.split(c, [None, 32])\r\n    wio, wii = s.split(w_i, [None, 2])\r\n\r\n    s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii)\r\n\r\n    fused = s.fuse(c_i, wii)\r\n    s.vectorize(fused)\r\n\r\n    return s\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/argmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Hexagon slice argmax compute and schedule\"\"\"\n\nfrom tvm import tir\nfrom tvm import topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef argmax_compute(in_tensor, axis):\n    out_tensor = topi.argmax(in_tensor, axis)\n    return out_tensor\n\n\ndef argmax_stir_schedule_nhwc(func, in_layout, out_layout):\n    \"\"\"Schedule for nhwc argmax\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    sch.transform_layout(\"A_red_temp\", \"A\", in_layout)\n    sch.transform_layout(\"A_red\", \"A_red\", out_layout)\n    return sch\n\n\ndef argmax_schedule(argmax_func, in_layout_str, out_layout_str):\n    \"\"\"Schedule for argmax: top level function\"\"\"\n    if (in_layout_str == \"nhwc-8h2w32c2w-2d\") and (out_layout_str == \"nhw-32h16w-2d\"):\n        fp16_layout_transform = get_layout_transform_fn(in_layout_str)\n        int32_layout_transform = get_layout_transform_fn(out_layout_str)\n        tir_s = argmax_stir_schedule_nhwc(\n            argmax_func, fp16_layout_transform, int32_layout_transform\n        )\n        return tir_s\n    if (in_layout_str == \"nhwc-8h8w32c-2d\") and (out_layout_str == \"nhw-32h16w-2d\"):\n        int8_layout_transform = get_layout_transform_fn(in_layout_str)\n        int32_layout_transform = get_layout_transform_fn(out_layout_str)\n        tir_s = argmax_stir_schedule_nhwc(\n            argmax_func, int8_layout_transform, int32_layout_transform\n        )\n        return tir_s\n    raise RuntimeError(f\"Unexpected input_layout, output_layout '{in_layout_str, out_layout_str}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/avg_pool2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals\n\n\"\"\" Compute and schedule for avg_pool2d slice op\n\nPlease note the following assumptions made by the implementation:\n\n1) The input must be padded in advance to account for 'padding'. In addition,\n   both input and output must be padded as per the physical buffer layout.\n2) The current implementation assumes 'count_include_pad' to be 'True'. It can be\n   modified to support 'False' case but the element count for the pooling window\n   must be pre-computed and provided as an input to reduce the run-time overhead.\n3) 'padding' is ignored. It must be handled outside of the sliced op.\n4) Please note that this implementation will not work if the output includes any\n   physical layout related padding as it can result into out-of-bound access\n   for the input.\n\"\"\"\n\nfrom tvm import te\nfrom tvm import tir\nfrom ..utils import get_layout_transform_fn\n\n\ndef validate_out_shape(out_shape, in_shape, kernel, stride, dilation):\n    \"\"\"Validate output shape\"\"\"\n    _, oh, ow, _ = out_shape\n    _, ih, iw, _ = in_shape\n    kh, kw = kernel\n    sh, sw = stride\n    dh, dw = dilation\n    if ih < (oh - 1) * sh + dh * (kh - 1) + 1:\n        raise RuntimeError(\"Output height is too large\")\n    if iw < (ow - 1) * sw + dw * (kw - 1) + 1:\n        raise RuntimeError(\"Output width is too large\")\n\n\ndef avg_pool2d_compute(A, kernel, stride, dilation, oshape, odtype=\"float16\"):\n    \"\"\"avg_pool2d compute\"\"\"\n    if odtype != \"float16\":\n        RuntimeError(f\"Unsupported output dtype '{odtype}'\")\n    kh, kw = kernel\n    rh = te.reduce_axis((0, kh), name=\"rh\")\n    rw = te.reduce_axis((0, kw), name=\"rw\")\n    ob, oh, ow, oc = oshape\n    if isinstance(ob, int):\n        validate_out_shape(oshape, A.shape, kernel, stride, dilation)\n\n    sh, sw = stride\n    dh, dw = dilation\n    InvArea = float(1) / (kh * kw)\n\n    Sum = te.compute(\n        oshape,\n        lambda b, h, w, c: te.sum(\n            A[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(\"float32\"), axis=[rh, rw]\n        ),\n        name=\"sum\",\n    )\n    Avg = te.compute(\n        oshape, lambda b, h, w, c: (Sum[b, h, w, c] * InvArea).astype(A.dtype), name=\"avg\"\n    )\n    return Avg\n\n\ndef schedule_nhwc_8h2w32c2w(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"Schedule for input and output layout nhwc-8h2w32c2w\"\"\"\n    func = te.create_prim_func([ins, outs])\n    s = tir.Schedule(func)\n    Sum = s.get_block(\"sum\")\n    Avg = s.get_block(\"avg\")\n\n    input_transform_fn = get_layout_transform_fn(input_layout)\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Sum, (\"read\", 0), input_transform_fn)\n    s.transform_layout(Avg, (\"write\", 0), output_transform_fn)\n\n    # Schedule 'Avg'\n    n, h, w, c = s.get_loops(Avg)\n    ho, hi = s.split(h, [None, 8])\n    wo, wi = s.split(w, [None, 4])\n    wio, wii = s.split(wi, [None, 2])\n    co, ci = s.split(c, [None, 32])\n    s.reorder(n, ho, wo, co, hi, wio, ci, wii)\n    ci_wii = s.fuse(ci, wii)\n    s.vectorize(ci_wii)\n\n    # Schedule 'Sum'\n    s.compute_at(Sum, wio)\n    Sum_axis = s.get_loops(Sum)\n    s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-4], Sum_axis[-3])\n    ci_wii = s.fuse(Sum_axis[-4], Sum_axis[-3])\n    # s.vectorize(ci_wii) # Doesn't work\n    return s\n\n\ndef schedule_n11c_1024c(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"Schedule for output layout: n11c-1024c, input layout: nhwc-8h2w32c2w\"\"\"\n    func = te.create_prim_func([ins, outs])\n    s = tir.Schedule(func)\n    Sum = s.get_block(\"sum\")\n    Avg = s.get_block(\"avg\")\n\n    input_transform_fn = get_layout_transform_fn(input_layout)\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Sum, (\"read\", 0), input_transform_fn)\n    s.transform_layout(Avg, (\"write\", 0), output_transform_fn)\n\n    # Schedule 'Avg'\n    n, h, w, c = s.get_loops(Avg)\n    co, ci = s.split(c, [None, 1024])\n    cio, cii = s.split(ci, [None, 64])\n    s.vectorize(cii)\n\n    # Schedule 'Sum'\n    s.compute_at(Sum, cio)\n    Sum_axis = s.get_loops(Sum)\n    s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-3])\n    # s.vectorize(Sum_axis[-3]) # Doesn't work\n    return s\n\n\ndef avg_pool2d_schedule(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"avg_pool2d schedule\"\"\"\n    if output_layout == \"nhwc-8h2w32c2w-2d\":\n        return schedule_nhwc_8h2w32c2w(outs, ins, output_layout, input_layout)\n    if output_layout == \"n11c-1024c-2d\":\n        return schedule_n11c_1024c(outs, ins, output_layout, input_layout)\n    raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/batch_flatten.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Hexagon slice batch flatten compute and schedule\"\"\"\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef batch_flatten_compute(inp: te.Tensor) -> te.Tensor:\n    \"\"\"Compute for slice batch flatten op for hexagon.\n    This op makes the following assumptions:\n    1. This op is written for a sliced batch flatten operation.\n    2. The input is assumed to be in NHWC layout.\n\n    Parameters\n    ----------\n    Input : te.Tensor\n        Input activations padded for inner dimension size\n    Returns\n    -------\n    Output : te.Tensor\n        Output of applying batch flatten operation on input\n    \"\"\"\n    return topi.nn.flatten(inp)\n\n\ndef batch_flatten_stir_schedule(\n    out: te.Tensor,\n    inp: te.Tensor,\n    out_layout: str,\n    in_layout: str,\n) -> tir.Schedule:\n    \"\"\"STIR schedule definition for the compute of batch flatten compute.\n    Parameters\n    ----------\n    outputs : te.Tensor\n        The output tensor as returned by a call to batch_flatten_compute\n    input : te.Tensor\n        Input tensor to batch_flatten\n    out_layout: typing.Callable\n        The transformation function definition for the expected output layout\n    in_layout: typing.Callable\n        The transformation function definition for the input layout\n    Returns\n    -------\n    sch : tvm.tir.Schedule\n        The STIR schedule for slice batch flatten compute\n    \"\"\"\n\n    batch_flatten_func = te.create_prim_func([inp, out])\n    sch = tir.Schedule(batch_flatten_func, debug_mask=\"all\")\n    compute = sch.get_block(\"compute\")\n\n    sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout))\n    sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout))\n    i, j = sch.get_loops(compute)\n    jout, channel = sch.split(j, [None, inp.shape[3]])\n    height, width = sch.split(jout, [inp.shape[1], inp.shape[2]])\n    channelo, channeli = sch.split(channel, [None, 1024])\n    channelio, channelii = sch.split(channeli, [None, 64])\n    sch.reorder(i, height, width, channelo, channelio, channelii)\n    sch.vectorize(channelii)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/cast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Hexagon slice cast op compute and schedule\"\"\"\n\nfrom tvm import te\nfrom tvm import tir\nfrom ..utils import get_layout_transform_fn\n\n\ndef get_layout_transform_for_f32(f32_layout_string):\n    \"\"\"\n    Given f32 layout string, return transform_layout function and\n    channel/height split factor to be used for scheduling\n    \"\"\"\n    layout_transform_fn = get_layout_transform_fn(f32_layout_string)\n    if f32_layout_string == \"nhwc-8h2w32c2w-2d\":\n        return [layout_transform_fn, 8]\n    if f32_layout_string == \"nhwc-4h2w32c2w-2d\":\n        return [layout_transform_fn, 4]\n    if f32_layout_string == \"nc-1024c-2d\":\n        return [layout_transform_fn, 1024]\n    if f32_layout_string == \"nc-512c-2d\":\n        return [layout_transform_fn, 512]\n    raise RuntimeError(f\"Unexpected f32_layout '{f32_layout_string}'\")\n\n\ndef cast_f16_f32_compute(in_tensor):\n    out_tensor = te.compute(\n        in_tensor.shape, lambda *indices: in_tensor[indices].astype(\"float32\"), name=\"CastF16F32\"\n    )\n    return out_tensor\n\n\ndef cast_f16_f32_stir_schedule_nhwc(func, in_layout, out_layout, h_split_factor):\n    \"\"\"Schedule for nhwc f16 to f32 cast: nhwc layout\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"CastF16F32\"\n    n_orig, h_orig, w_orig, c_orig = sch.get_loops(sch.get_block(block_name))\n    h_outer, h_inner = sch.split(h_orig, [None, h_split_factor])\n    w_outer, w_inner = sch.split(w_orig, [None, 4])\n    c_outer, c_inner = sch.split(c_orig, [None, 32])\n    w_inner_o, w_inner_i = sch.split(w_inner, [None, 2])\n    sch.reorder(n_orig, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i)\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    fused = sch.fuse(c_inner, w_inner_i)\n    sch.vectorize(fused)\n    return sch\n\n\ndef cast_f16_f32_stir_schedule_nc(func, in_layout, out_layout, c_split_factor):\n    \"\"\"Schedule for nc f16 to f32 cast: nc layout\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"CastF16F32\"\n    _, c_orig = sch.get_loops(sch.get_block(block_name))\n    _, c_inner = sch.split(c_orig, [None, c_split_factor])\n    _, c_inner_inner = sch.split(c_inner, [None, 64])\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    sch.vectorize(c_inner_inner)\n    return sch\n\n\ndef cast_f16_f32_schedule(cast_func, in_layout_str, out_layout_str):\n    \"\"\"Schedule for f16 to f32 cast: top level function\"\"\"\n    f32_layout_transform_func, split_factor = get_layout_transform_for_f32(out_layout_str)\n    f16_layout_transform_func = get_layout_transform_fn(in_layout_str)\n    if in_layout_str == \"nhwc-8h2w32c2w-2d\":\n        return cast_f16_f32_stir_schedule_nhwc(\n            cast_func,\n            f16_layout_transform_func,\n            f32_layout_transform_func,\n            split_factor,\n        )\n    if in_layout_str == \"nc-1024c-2d\":\n        return cast_f16_f32_stir_schedule_nc(\n            cast_func, f16_layout_transform_func, f32_layout_transform_func, split_factor\n        )\n    raise RuntimeError(f\"Unexpected input_layout, output_layout '{input_layout, output_layout}'\")\n\n\ndef cast_f32_f16_compute(in_tensor):\n    out_tensor = te.compute(\n        in_tensor.shape, lambda *indices: in_tensor[indices].astype(\"float16\"), name=\"CastF32F16\"\n    )\n    return out_tensor\n\n\ndef cast_f32_f16_stir_schedule_nhwc(func, in_layout, out_layout, h_split_factor):\n    \"\"\"Schedule for nhwc f32 to f16 cast: nhwc layout\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"CastF32F16\"\n    n_orig, h_orig, w_orig, c_orig = sch.get_loops(sch.get_block(block_name))\n    h_outer, h_inner = sch.split(h_orig, [None, h_split_factor])\n    w_outer, w_inner = sch.split(w_orig, [None, 4])\n    c_outer, c_inner = sch.split(c_orig, [None, 32])\n    w_inner_o, w_inner_i = sch.split(w_inner, [None, 2])\n    sch.reorder(n_orig, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i)\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    fused = sch.fuse(c_inner, w_inner_i)\n    sch.vectorize(fused)\n    return sch\n\n\ndef cast_f32_f16_stir_schedule_nc(func, in_layout, out_layout, c_split_factor):\n    \"\"\"Schedule for nc f32 to f16 cast: nc layout\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"CastF32F16\"\n    _, c_orig = sch.get_loops(sch.get_block(block_name))\n    _, c_inner = sch.split(c_orig, [None, c_split_factor])\n    _, c_inner_inner = sch.split(c_inner, [None, 64])\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    sch.vectorize(c_inner_inner)\n    return sch\n\n\ndef cast_f32_f16_schedule(cast_func, in_layout_str, out_layout_str):\n    \"\"\"Schedule for f32 to f16 cast: top level function\"\"\"\n    f32_layout_transform_func, split_factor = get_layout_transform_for_f32(in_layout_str)\n    f16_layout_transform_func = get_layout_transform_fn(out_layout_str)\n    if out_layout_str == \"nhwc-8h2w32c2w-2d\":\n        return cast_f32_f16_stir_schedule_nhwc(\n            cast_func, f32_layout_transform_func, f16_layout_transform_func, split_factor\n        )\n    if out_layout_str == \"nc-1024c-2d\":\n        return cast_f32_f16_stir_schedule_nc(\n            cast_func, f32_layout_transform_func, f16_layout_transform_func, split_factor\n        )\n    raise RuntimeError(f\"Unexpected input_layout, output_layout '{in_layout_str, out_layout_str}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/clip.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name\n\n\"\"\"\nClip the elements in `A` between `A_min` and `A_max`.\n\"\"\"\n\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef clip_compute(A, A_min, A_max):\n    \"\"\"\n    Use topi clip implementation\n    \"\"\"\n    return topi.clip(A, A_min, A_max)\n\n\ndef clip_schedule(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"\n    Hexagon clip schedule\n    \"\"\"\n    A = ins\n    M = outs\n\n    func = te.create_prim_func([A, M])\n\n    s = tir.Schedule(func)\n\n    block = s.get_block(\"compute\")\n\n    input_transformed_layout = get_layout_transform_fn(input_layout)\n    s.transform_layout(block, buffer=(\"read\", 0), index_map=input_transformed_layout)\n\n    output_transformed_layout = get_layout_transform_fn(output_layout)\n    s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout)\n\n    n, h, w, c = s.get_loops(block)\n\n    ho, hi = s.split(h, [None, 8])\n    wo, wi = s.split(w, [None, 4])\n    co, ci = s.split(c, [None, 32])\n    wio, wii = s.split(wi, [None, 2])\n\n    s.reorder(n, ho, wo, co, hi, wio, ci, wii)\n\n    fused = s.fuse(ci, wii)\n    s.vectorize(fused)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long\n\n\"\"\"Hexagon slice conv2d compute and schedule\"\"\"\nimport typing\n\nimport tvm\nfrom tvm import te\n\nfrom ..utils import get_layout_transform_fn\n\n\ndef conv2d_compute(\n    activations: te.Tensor,\n    weights: te.Tensor,\n    out_shape: typing.Tuple,\n    stride: typing.Tuple,\n    dilation: typing.Tuple,\n    dtype: str,\n    output_name: str,\n    weights_width_reversed: bool = True,\n) -> te.Tensor:\n    \"\"\"Compute for slice conv2d op for hexagon.\n\n    This op makes the following assumptions:\n    1. This op is written for a sliced convolution with 2d physical buffers\n    2. The input activations is assumed to be in NHWC layout and filter is in HWIO layout\n    3. Grouped convolutions are not supported. and there will be a separate compute definition for depthwise convolution\n    4. In order to get grouped convolutions, it is assumed that the op will be sliced according to the groups and multiple calls to this compute would be placed.\n\n\n    Parameters\n    ----------\n    activations : te.Tensor\n        Input activations padded for inner dimension size\n    weights : te.Tensor\n        Weights without dilation\n    out_shape : typing.Tuple\n        The logical output shape without considering input padding\n    stride : typing.Tuple\n        stride\n    dilation : typing.Tuple\n        dilation\n    dtype : str\n        dtype\n    output_name : str\n        The name to be given to output. This would become the block name for the corresponding STIR compute\n    weights_width_reversed : bool\n        The width axis of weights are expected in reverse order if weights_width_reversed is True\n\n    Returns\n    -------\n    output : te.Tensor\n        Output of applying 2D convolution of Weights on Input\n    \"\"\"\n\n    filt_shape = weights.shape\n\n    reduce_channel = tvm.te.reduce_axis((0, filt_shape[2]), name=\"reduce_channel\")\n    reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name=\"reduce_height\")\n    reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name=\"reduce_width\")\n    stride_height, stride_width = stride\n    dilation_height, dilation_width = dilation\n\n    if weights_width_reversed:\n        weights_width_var = filt_shape[1] - reduce_width - 1\n    else:\n        weights_width_var = reduce_width\n\n    output = tvm.te.compute(\n        out_shape,\n        lambda n, h, w, c: tvm.te.sum(\n            (\n                activations[\n                    n,\n                    h * stride_height + reduce_height * dilation_height,\n                    w * stride_width + reduce_width * dilation_width,\n                    reduce_channel,\n                ]\n                * weights[reduce_height, weights_width_var, reduce_channel, c]\n            ).astype(dtype),\n            axis=[reduce_channel, reduce_height, reduce_width],\n        ),\n        name=output_name,\n    )\n    return output\n\n\ndef conv2d_te_schedule(\n    out: te.Tensor,\n    ins: typing.List[te.Tensor],\n    transform_activation_layout: str,\n    transform_weights_layout: str,\n    transform_output_layout: str,\n) -> te.Schedule:\n    \"\"\"TE Schedule for the sliced conv2d op\n\n    This schedule makes the following assumptions:\n    1. There is only one output tensor\n    2. The activations and weights have specific layouts defined by the last 2 arguments\n    3. All transformation functions are expected to be a bijection for now\n\n    Parameters\n    ----------\n    out : te.Tensor\n        The output tensor returned by a call to conv2d_compute\n    ins : typing.List[te.Tensor]\n        The list of 2 Tensors which would be the input activations and weights\n    transform_activation_layout : str\n        The expected activations layout\n    transform_weights_layout : str\n        String representing the weights layout as defined in get_layout_transform_fn\n    transform_output_layout: str\n        String representing the output layout as defined in get_layout_transform_fn\n\n    Returns\n    -------\n    sch : te.Schedule\n        The TE schedule for slice conv2d\n    \"\"\"\n    activations, weights = ins\n    output = out\n    sch = tvm.te.create_schedule(output.op)\n    reduce_channel, reduce_height, reduce_width = sch[output].op.reduce_axis\n    sch[activations].transform_layout(get_layout_transform_fn(transform_activation_layout))\n    sch[weights].transform_layout(get_layout_transform_fn(transform_weights_layout))\n    transformed_axis = sch[output].transform_layout(\n        get_layout_transform_fn(transform_output_layout)\n    )\n    fused_out_axis = sch[output].fuse(transformed_axis[-1], transformed_axis[-2])\n    sch[output].reorder(\n        *[*transformed_axis[:-2], reduce_height, reduce_width, reduce_channel, fused_out_axis]\n    )\n    # The below code doesn't work yet as vectorization across 2D boundary is not yet supported\n    # s[output].vectorize(fused_out_axis)\n    return sch\n\n\ndef conv2d_schedule(\n    outs: te.Tensor,\n    ins: typing.List[te.Tensor],\n    transform_activation_layout: str,\n    transform_weights_layout: str,\n    transform_output_layout: str,\n    output_name: str,\n) -> tvm.tir.Schedule:\n    \"\"\"STIR schedule definition for the compute defined above by conv2d_compute.\n\n    - Auto-generated prim_func before applying schedule primitives for reference\n    - The below TVMScript code is for conv2d with padded input dimensions and a stride of 1x1\n\n    # from tvm.script import tir as T\n    @T.prim_func\n    def func(InputTensor: T.Buffer[(1, 24, 12, 32), \"float16\"], Weights: T.Buffer[(3, 3, 32, 32), \"float16\"], compute: T.Buffer[(1, 16, 8, 32), \"float16\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 16, 8, 32, 32, 3, 3):\n            with T.block(\"compute\"):\n                n, h, w, c, rc, rh, rw = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(InputTensor[n, h + rh, w + rw, rc], Weights[rh, rw, rc, c])\n                T.writes(compute[n, h, w, c])\n                with T.init():\n                    compute[n, h, w, c] = T.float16(0)\n                compute[n, h, w, c] = compute[n, h, w, c] + InputTensor[n, h + rh, w + rw, rc] * Weights[rh, rw, rc, c]\n\n    Parameters\n    ----------\n    outs : te.Tensor\n        The output Tensor as returned by a call to conv2d_compute\n    ins : typing.List[te.Tensor]\n        This is a list of 2 tensors - Input activations and Weights\n    transform_activation_layout : str\n        String representing the activations layout as defined in get_layout_transform_fn\n    transform_weights_layout : str\n        String representing the weights layout as defined in get_layout_transform_fn\n    transform_output_layout: str\n        String representing the output layout as defined in get_layout_transform_fn\n    output_name : str\n        The name that was given to the output compute and which can be used to get the block name\n\n    Returns\n    -------\n    sch : tvm.tir.Schedule\n        The STIR schedule for slice conv2d compute\n    \"\"\"\n\n    assert len(ins) == 2, \"This schedule expects only 2 inputs - Activations and Weights\"\n    source_expr = ins + [outs]\n    prim_func = tvm.te.create_prim_func(source_expr)\n    sch = tvm.tir.Schedule(prim_func)\n\n    compute = sch.get_block(output_name)\n    # Apply layout_transform for activation\n    sch.transform_layout(compute, ins[0].name, get_layout_transform_fn(transform_activation_layout))\n\n    # Apply layout_transform for weights\n    sch.transform_layout(compute, ins[1].name, get_layout_transform_fn(transform_weights_layout))\n\n    # Apply layout_transform for output\n    sch.transform_layout(compute, outs.name, get_layout_transform_fn(transform_output_layout))\n\n    batch, height, width, channel, reduce_channel, reduce_height, reduce_width = sch.get_loops(\n        compute\n    )  # This still returns the original 7d loop\n    h_outer, h_inner = sch.split(height, [None, 8])\n    w_outer, w_inner = sch.split(width, [None, 4])\n    w_inner_outer, w_inner_inner = sch.split(w_inner, [2, 2])\n    c_outer, c_inner = sch.split(channel, [None, 32])\n    sch.reorder(\n        batch,\n        h_outer,\n        w_outer,\n        c_outer,\n        h_inner,\n        w_inner_outer,\n        reduce_height,\n        reduce_width,\n        reduce_channel,\n        c_inner,\n        w_inner_inner,\n    )\n    sch.decompose_reduction(compute, reduce_height)\n    # ci_wii = s.fuse(ci, wii)\n    # s.vectorize(ci_wii)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Compute and schedule for depth to space slice op\n\"\"\"\n\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef d2s_compute(inp, block_size, layout, mode):\n    \"\"\"depth_to_space compute\"\"\"\n    return topi.nn.depth_to_space(inp, block_size=block_size, layout=layout, mode=mode)\n\n\ndef d2s_schedule(inp, out, input_layout, output_layout):\n    \"\"\"Schedule for depth to space: top level function\"\"\"\n    if (input_layout != output_layout) or (\n        output_layout not in (\"nhwc-8h2w32c2w-2d\", \"nhwc-8h8w32c-2d\")\n    ):\n        raise RuntimeError(\n            f\"Unexpected input_layout, output_layout '{input_layout, output_layout}'\"\n        )\n    d2s_func = te.create_prim_func([inp, out])\n    sch = tir.Schedule(d2s_func, debug_mask=\"all\")\n    compute = sch.get_block(\"depth_to_space\")\n    sch.transform_layout(compute, inp.name, get_layout_transform_fn(input_layout))\n    sch.transform_layout(compute, out.name, get_layout_transform_fn(output_layout))\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/dwconv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long\n\n\"\"\"Hexagon slice dwconv2d compute and schedule\"\"\"\nimport typing\n\nimport tvm\nfrom tvm import te\nfrom ..utils import get_layout_transform_fn\n\n\ndef dwconv2d_compute(\n    activations: te.Tensor,\n    weights: te.Tensor,\n    out_shape: typing.Tuple,\n    stride: typing.Tuple,\n    dilation: typing.Tuple,\n    dtype: str,\n) -> te.Tensor:\n    \"\"\"Compute for slice dwconv2d op for hexagon.\n    This op makes the following assumptions:\n    1. This op is written for a sliced dw convolution with 2d physical buffers\n    2. The input activations is assumed to be in NHWC layout and filter is in HWIO layout\n    Parameters\n    ----------\n    activations : te.Tensor\n        Input activations padded for inner dimension size\n    weights : te.Tensor\n        Weights without dilation\n    out_shape : typing.Tuple\n        The logical output shape without considering input padding\n    stride : typing.Tuple\n        stride\n    dilation : typing.Tuple\n        dilation\n    dtype : str\n        dtype\n    Returns\n    -------\n    output : te.Tensor\n        Output of applying 2D depthwise convolution of Weights on Input\n    \"\"\"\n\n    filt_shape = weights.shape\n\n    reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name=\"reduce_height\")\n    reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name=\"reduce_width\")\n    stride_height, stride_width = stride\n    dilation_height, dilation_width = dilation\n    output = tvm.te.compute(\n        out_shape,\n        lambda n, h, w, c: tvm.te.sum(\n            (\n                activations[\n                    n,\n                    h * stride_height + reduce_height * dilation_height,\n                    w * stride_width + reduce_width * dilation_width,\n                    c,\n                ]\n                * weights[reduce_height, reduce_width, 0, c]\n            ).astype(dtype),\n            axis=[reduce_height, reduce_width],\n        ),\n        name=\"Output\",\n    )\n    return output\n\n\ndef dwconv2d_schedule(\n    outs: te.Tensor,\n    ins: typing.List[te.Tensor],\n    transform_activation_layout: str,\n    transform_weights: str,\n) -> tvm.tir.Schedule:\n    \"\"\"STIR schedule definition for the compute defined above by dwconv2d_compute.\n        - Auto-generated prim_func before applying schedule primitives for reference\n        - The below TVMScript code is for dwconv2d with padded input dimensions and a stride of 1x1\n    # from tvm.script import tir as T\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(InputTensor: T.Buffer[(1, 16, 8, 32), \"float16\"], Weights: T.Buffer[(3, 3, 1, 32), \"float16\"], Output: T.Buffer[(1, 8, 4, 32), \"float16\"]) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            for i0, i1, i2, i3, i4, i5 in T.grid(1, 8, 4, 32, 3, 3):\n                with T.block(\"Output\"):\n                    n, h, w, c, reduce_height, reduce_width = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                    T.reads(InputTensor[n, h + reduce_height, w + reduce_width, c], Weights[reduce_height, reduce_width, 0, c])\n                    T.writes(Output[n, h, w, c])\n                    with T.init():\n                        Output[n, h, w, c] = T.float16(0)\n                    Output[n, h, w, c] = Output[n, h, w, c] + InputTensor[n, h + reduce_height, w + reduce_width, c] * Weights[reduce_height, reduce_width, 0, c]\n        Parameters\n        ----------\n        outs : te.Tensor\n            The output Tensor as returned by a call to dwconv2d_compute\n        ins : typing.List[te.Tensor]\n            This is a list of 2 tensors - Input activations and Weights\n        transform_activation_layout : str\n            The transformation string representing the expected activations layout\n        transform_weights : typing.Callable\n            The transformation function definition for the expected weights layout\n        Returns\n        -------\n        sch : tvm.tir.Schedule\n            The STIR schedule for slice dwconv2d compute\n    \"\"\"\n    assert len(ins) == 2, \"This schedule expects only 2 inputs - Activations and Weights\"\n    source_expr = ins + [outs]\n    prim_func = tvm.te.create_prim_func(source_expr)\n    sch = tvm.tir.Schedule(prim_func)\n    compute = sch.get_block(\"Output\")\n    transform_layout_fn = get_layout_transform_fn(transform_activation_layout)\n    transform_layout_weights = get_layout_transform_fn(transform_weights)\n    # Apply layout_transform for activation\n    sch.transform_layout(compute, ins[0].name, transform_layout_fn)\n\n    # Apply layout_transform for weights\n    sch.transform_layout(compute, ins[1].name, transform_layout_weights)\n\n    # Apply layout_transform for output\n    sch.transform_layout(compute, outs.name, transform_layout_fn)\n\n    batch, height, width, channel, reduce_height, reduce_width = sch.get_loops(\n        compute\n    )  # This still returns the original 6d loop\n    h_outer, h_inner = sch.split(height, [None, 8])\n    w_outer, w_inner = sch.split(width, [None, 4])\n    w_inner_outer, w_inner_inner = sch.split(w_inner, [2, 2])\n    c_outer, c_inner = sch.split(channel, [None, 32])\n    sch.reorder(\n        batch,\n        h_outer,\n        w_outer,\n        c_outer,\n        h_inner,\n        w_inner_outer,\n        reduce_height,\n        reduce_width,\n        c_inner,\n        w_inner_inner,\n    )\n    sch.decompose_reduction(compute, reduce_height)\n    # ci_wii = sch.fuse(c_inner, w_inner_inner)\n    # sch.vectorize(ci_wii)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/max_pool2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals\n\n\"\"\" Compute and schedule for max_pool2d slice op\n\nPlease note the following assumptions made by the implementation:\n\n1) The input must be padded in advance to account for 'padding'. In addition,\n   both input and output must be padded as per the physical buffer layout.\n\n2) The current implementation assumes 'count_include_pad' to be 'True'. It can be\n   modified to support 'False' case but the element count for the pooling window\n   must be pre-computed and provided as an input to reduce the run-time overhead.\n\n3) 'padding' is ignored. It must be handled outside of the sliced op.\n\n4) This implementation will not work if the output includes any physical layout\n   related padding, as it can result into out-of-bound access for the input.\n\"\"\"\n\nfrom tvm import te\nfrom tvm import tir\nfrom ..utils import get_layout_transform_fn\n\n\ndef validate_out_shape(out_shape, in_shape, kernel, stride, dilation):\n    \"\"\"Validate output shape\"\"\"\n    _, oh, ow, _ = out_shape\n    _, ih, iw, _ = in_shape\n    kh, kw = kernel\n    sh, sw = stride\n    dh, dw = dilation\n    if ih < (oh - 1) * sh + dh * (kh - 1) + 1:\n        raise RuntimeError(\"Output height is too large\")\n    if iw < (ow - 1) * sw + dw * (kw - 1) + 1:\n        raise RuntimeError(\"Output width is too large\")\n\n\ndef max_pool2d_compute(A, out_shape, kernel, stride, dilation):\n    \"\"\"max_pool2d compute\"\"\"\n    kh, kw = kernel\n    rh = te.reduce_axis((0, kh), name=\"rh\")\n    rw = te.reduce_axis((0, kw), name=\"rw\")\n    ob, oh, ow, oc = out_shape\n    if isinstance(ob, int):\n        validate_out_shape(out_shape, A.shape, kernel, stride, dilation)\n\n    sh, sw = stride\n    dh, dw = dilation\n\n    Max = te.compute(\n        out_shape,\n        lambda b, h, w, c: te.max(\n            A[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(A.dtype), axis=[rh, rw]\n        ),\n        name=\"max\",\n    )\n    return Max\n\n\ndef STIR_schedule_nhwc_8h2w32c2w_nhwc_8h8w32c(\n    outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str\n):\n    \"\"\"Schedule for input and output layout nhwc-8h2w32c2w and nhwc-8h8w32c\"\"\"\n    func = te.create_prim_func([ins, outs])\n    s = tir.Schedule(func)\n\n    # NOTE!!! This scheduling logic is a work in progress.\n    # It is not known to ultimately result in near-optimal Hexagon performance.\n    # The schedule below strives to implement these heuristics:\n    #\n    # (1) For mathematical operations on tensor values, prefer HVX SIMD operations\n    #     over per-element scalar operations.\n    #\n    # (2) Minimize the number of memory transfers used to operate on tensor values:\n    #     host-memory <--> Hexagon DDR <--> VTCM <--> HVX registers\n    #\n    # As a consequence of (1) + (2), prefer TIR schedules that load each value\n    # into an HVX SIMD tensor exactly once.\n\n    Max = s.get_block(\"max\")\n\n    if input_layout in (\n        \"nhwc-8h2w32c2w-2d\",\n        \"nhwc-8h8w32c-2d\",\n    ):\n        input_transform_fn = get_layout_transform_fn(input_layout)\n        s.transform_layout(Max, (\"read\", 0), input_transform_fn)\n\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Max, (\"write\", 0), output_transform_fn)\n\n    # pylint: disable=line-too-long\n    #\n    # Restructure the loop nestings to have this overall structure:\n    # (loop over different 128-byte output-tensor chunks) : n, ho, wo, co   }- the first level of a two-level tensor layout\n    #    (loop within one 128-byte output-tensor chunk) : hi, wio, ci, wii  }- the second level of a two-level tensor layout\n    #        (loop over reduction axes) : rh, rw                            }- loop over multiple elements of the input tensor\n    #\n    # Note: This schedule is a work in progress.  We *expect* that it's\n    # crucially important for the loops to have this relative ordering:\n    #    n ... ho ... wo ... co ... hi ... wio ... ci ... wii\n    # because it lets us visit each of the 128-byte output chunks precisely once.\n\n    (\n        n,\n        h,\n        w,\n        c,\n        rh,\n        rw,\n    ) = s.get_loops(Max)\n\n    # Restructure the loops from NHWC to nhwc_8h2w32c2w or nhwc_8h8w32c, with loops for 'max's reduction\n    # axes at the very end.\n    # nhwc_8h2w32c2w layout is for float16 and nhwc-8h8w32c-2d layout is for uint8/int8\n    if output_layout == \"nhwc-8h2w32c2w-2d\":\n        ho, hi = s.split(h, [None, 8])\n        wo, wi = s.split(w, [None, 4])\n        wio, wii = s.split(wi, [None, 2])\n        co, ci = s.split(c, [None, 32])\n        s.reorder(n, ho, wo, co, hi, wio, ci, wii, rh, rw)\n    elif output_layout == \"nhwc-8h8w32c-2d\":\n        ho, hi = s.split(h, [None, 8])\n        wo, wi = s.split(w, [None, 8])\n        co, ci = s.split(c, [None, 32])\n\n        s.reorder(n, ho, wo, co, hi, wi, ci, rh, rw)\n\n    # TODO: Enable vectorization.\n    # Hexagon v69's HVX units support SIMD operations on 64-element float16 vectors.\n    #\n    # TVM's 'vectorize' schedule primitive is the idiomatic way to encourage lower layers of the\n    # compiler to generate this kind of SIMD object code.\n    #\n    # Several requirements must be met to use 'vectorize':\n    #\n    # 1) It can only be applied to a schedule's innermost loop variable.\n    #\n    # 2) Any block-iterator(s) bound to that innermost loop variable must be\n    #    *data-parallel* block iterators.\n    #\n    # 3) Ideally, the innermost loop variable will iterate only over the output\n    #    tensor's fastest-changing indices and nothing else.  But in our case,\n    #    our two innermost loops correspond to the the max operator's reduction axes.\n    #\n    # Finding a good way to satisfy all of these requirements at the same time is\n    # left for future work.\n\n    # ci_wii = s.fuse(ci, wii)\n    # s.vectorize(ci_wii_rh_rw)\n\n    return s\n\n\ndef STIR_schedule_n11c(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"Schedule for output layout: n11c-1024c, n11c-2048c-2d;\"\"\"\n\n    # NOTE: This function is a variation of the STIR_schedule_maxpool2d\n    # functions.  Most of that function's code comments apply to this function\n    # as well, but are ommited for brevity.\n\n    # NOTE: the \"n11c-1024c\" output layout is shorthand for this axis mapping:\n    # [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024]\n    func = te.create_prim_func([ins, outs])\n\n    s = tir.Schedule(func)\n    Max = s.get_block(\"max\")\n\n    input_transform_fn = get_layout_transform_fn(input_layout)\n    output_transform_fn = get_layout_transform_fn(output_layout)\n    s.transform_layout(Max, (\"read\", 0), input_transform_fn)\n    s.transform_layout(Max, (\"write\", 0), output_transform_fn)\n\n    (\n        n,\n        h,\n        w,\n        c,\n        rh,\n        rw,\n    ) = s.get_loops(Max)\n    if output_layout == \"n11c-1024c-2d\":\n        co, ci = s.split(c, [None, 1024])\n    else:\n        co, ci = s.split(c, [None, 2048])\n    # s.vectorize(ci)\n\n    return s\n\n\ndef max_pool2d_STIR_schedule(outs, ins, output_layout: str, input_layout: str):\n    \"\"\"STIR based schedule\"\"\"\n    if output_layout == \"nhwc-8h2w32c2w-2d\" or \"nhwc-8h8w32c-2d\":\n        return STIR_schedule_nhwc_8h2w32c2w_nhwc_8h8w32c(outs, ins, output_layout, input_layout)\n    if output_layout == \"n11c-1024c-2d\" or \"n11c-2048c-2d\":\n        return STIR_schedule_n11c(outs, ins, output_layout, input_layout)\n    raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/relu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Hexagon slice relu op\"\"\"\n\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef relu_compute(Input):\n    \"\"\"Relu topi compute\"\"\"\n    return topi.nn.relu(Input)\n\n\ndef relu_te_sched(Output, Input, layout):\n    \"\"\"\n    Schedule assumes the layout function to be bijective\n    \"\"\"\n    s = te.create_schedule(Output.op)\n    s[Input].transform_layout(layout)\n    out_axes = s[Output].transform_layout(layout)\n    fused = s[Output].fuse(out_axes[6], out_axes[7])\n    s[Output].vectorize(fused)\n    return s\n\n\ndef relu_stir_schedule(Input, Output, input_layout, output_layout):\n    \"\"\"\n    Schedule assumes the layout function to be bijective\n    \"\"\"\n    if (input_layout != output_layout) or (output_layout != \"nhwc-8h2w32c2w-2d\"):\n        raise RuntimeError(\n            f\"Unexpected input_layout, output_layout '{input_layout, output_layout}'\"\n        )\n    relu_func = te.create_prim_func([Input, Output])\n    sch = tir.Schedule(relu_func, debug_mask=\"all\")\n    block = sch.get_block(\"compute\")\n    sch.transform_layout(block, Input.name, get_layout_transform_fn(input_layout))\n    sch.transform_layout(block, Output.name, get_layout_transform_fn(output_layout))\n\n    n, h, w, c = sch.get_loops(block)\n    h_o, h_i = sch.split(h, [None, 8])\n    w_o, w_i = sch.split(w, [None, 4])\n    c_o, c_i = sch.split(c, [None, 32])\n    wio, wii = sch.split(w_i, [None, 2])\n\n    sch.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii)\n\n    fused = sch.fuse(c_i, wii)\n    sch.vectorize(fused)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Hexagon slice reshape compute and schedule\"\"\"\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef reshape_compute(inp: te.Tensor, new_shape: tuple) -> te.Tensor:\n    \"\"\"Compute for slice reshape op for hexagon.\n    This op makes the following assumptions:\n    1. This op is written for a sliced reshape operation.\n    2. The input is assumed to be in NHWC layout.\n\n    Parameters\n    ----------\n    Input : te.Tensor\n        Input tensor\n    New Shape: tuple\n        Output shape\n    Returns\n    -------\n    Output : te.Tensor\n        Output of applying reshape operation on input\n    \"\"\"\n    return topi.transform.reshape(inp, new_shape)\n\n\ndef stir_sched_nhwc_2d_op(\n    out: te.Tensor,\n    inp: te.Tensor,\n    out_layout: str,\n    in_layout: str,\n    c_split: int,\n) -> tir.Schedule:\n    \"\"\"Schedule for output layout: nc-1024-2d, nc-2048-2d\"\"\"\n    reshape_func = te.create_prim_func([inp, out])\n    sch = tir.Schedule(reshape_func, debug_mask=\"all\")\n    compute = sch.get_block(\"T_reshape\")\n\n    sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout))\n    sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout))\n    i, j = sch.get_loops(compute)\n    jout, channel = sch.split(j, [None, inp.shape[3]])\n    height, width = sch.split(jout, [inp.shape[1], inp.shape[2]])\n    channelo, channeli = sch.split(channel, [None, 1024])\n    channelio, channelii = sch.split(channeli, [None, c_split])\n    sch.reorder(i, height, width, channelo, channelio, channelii)\n    sch.vectorize(channelii)\n    return sch\n\n\ndef stir_schedule_nhwc_8h2w32c2w(\n    out: te.Tensor,\n    inp: te.Tensor,\n    out_layout: str,\n    in_layout: str,\n) -> tir.Schedule:\n    \"\"\"Schedule for input and output layout nhwc-8h2w32c2w\"\"\"\n    reshape_func = te.create_prim_func([inp, out])\n    sch = tir.Schedule(reshape_func, debug_mask=\"all\")\n    compute = sch.get_block(\"T_reshape\")\n\n    sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout))\n    sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout))\n    return sch\n\n\ndef reshape_stir_schedule(\n    out: te.Tensor,\n    inp: te.Tensor,\n    output_layout: str,\n    input_layout: str,\n) -> tir.Schedule:\n    \"\"\"STIR schedule definition for the compute of reshape compute.\n    Parameters\n    ----------\n    outputs : te.Tensor\n        The output tensor as returned by a call to reshape_compute\n    input : te.Tensor\n        Input tensor to reshape\n    out_layout: str\n        The transformation function definition for the expected output layout\n    in_layout: str\n        The transformation function definition for the input layout\n    Returns\n    -------\n    sch : tvm.tir.Schedule\n        The STIR schedule for slice reshape compute\n    \"\"\"\n    if output_layout in [\"nhwc-8h2w32c2w-2d\", \"nhwc-8h8w32c-2d\"]:\n        return stir_schedule_nhwc_8h2w32c2w(out, inp, output_layout, input_layout)\n    if output_layout == \"nc-1024-2d\":\n        return stir_sched_nhwc_2d_op(out, inp, output_layout, input_layout, 64)\n    if output_layout == \"nc-2048-2d\":\n        return stir_sched_nhwc_2d_op(out, inp, output_layout, input_layout, 128)\n    raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/softmax_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hexagon slice softmax compute and schedule\"\"\"\n\nimport typing\n\nfrom tvm import te, tir, topi\nfrom ..utils import get_layout_transform_fn\n\n\ndef softmax_compute(in_tensor):\n    \"\"\"\n    Compute for slice softmax op for hexagon.\n    This op makes the following assumptions:\n    1. This op is written for a sliced softmax operation.\n    2. The input is assumed to be in NC layout.\n    \"\"\"\n    return topi.nn.softmax(in_tensor, axis=1)\n\n\ndef softmax_stir_schedule(\n    out: te.Tensor, inp: te.Tensor, out_layout: typing.Callable, in_layout: typing.Callable\n):\n    \"\"\"\n    STIR schedule definition for the compute of softmax\n    \"\"\"\n\n    in_layout = get_layout_transform_fn(in_layout)\n    out_layout = get_layout_transform_fn(out_layout)\n\n    func = te.create_prim_func([inp, out])\n    sch = tir.Schedule(func, debug_mask=\"all\")\n\n    max_tensor = sch.get_block(\"T_softmax_maxelem\")\n    exp_tensor = sch.get_block(\"T_softmax_exp\")\n    sum_tensor = sch.get_block(\"T_softmax_expsum\")\n    out_tensor = sch.get_block(\"T_softmax_norm\")\n\n    sch.transform_layout(max_tensor, inp.name, in_layout)\n    sch.transform_layout(out_tensor, out.name, out_layout)\n\n    _, c_inner = sch.get_loops(max_tensor)\n    _, c_inner_i = sch.split(c_inner, [None, 64])\n    rf_max = sch.rfactor(c_inner_i, 0)\n    _, _, max_inner = sch.get_loops(rf_max)\n    sch.vectorize(max_inner)\n\n    _, loopi = sch.get_loops(exp_tensor)\n    _, loopi_i = sch.split(loopi, [None, 512])\n    sch.vectorize(loopi_i)\n\n    _, c_sum_inner = sch.get_loops(sum_tensor)\n    _, c_sum_inner_i = sch.split(c_sum_inner, [None, 64])\n    rf_sum = sch.rfactor(c_sum_inner_i, 0)\n    _, _, sum_inner = sch.get_loops(rf_sum)\n    sch.vectorize(sum_inner)\n\n    _, c_out_inner = sch.get_loops(out_tensor)\n    _, c_out_inner_i = sch.split(c_out_inner, [None, 512])\n    sch.vectorize(c_out_inner_i)\n\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/slice_ops/tanh.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" Hexagon tanh slice op compute and schedule \"\"\"\nimport tvm\nfrom tvm import te, tir\nfrom ..utils import get_layout_transform_fn\n\n\ndef tanh_te_compute(in_tensor):\n    out_tensor = te.compute(\n        in_tensor.shape, lambda n, h, w, c: tvm.tir.tanh(in_tensor[n, h, w, c]), name=\"tanhf16\"\n    )\n    return out_tensor\n\n\ndef tanhf16_stir_sched_nhwc(func, in_layout, out_layout, h_split_factor=8):\n    \"\"\"Schedule for nhwc fp16 to nchw fp16 layout\"\"\"\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block_name = \"tanhf16\"\n    n, h, w, c = sch.get_loops(sch.get_block(block_name))\n    h_outer, h_inner = sch.split(h, [None, h_split_factor])\n    w_outer, w_inner = sch.split(w, [None, 4])\n    c_outer, c_inner = sch.split(c, [None, 32])\n    w_inner_o, w_inner_i = sch.split(w_inner, [None, 2])\n    sch.reorder(n, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i)\n    sch.transform_layout(block_name, \"A\", in_layout)\n    sch.transform_layout(block_name, block_name, out_layout)\n    fused = sch.fuse(c_inner, w_inner_i)\n    sch.vectorize(fused)\n    return sch\n\n\ndef tanhf16_schedule(tanh_func, in_layout_str, out_layout_str):\n    in_layout_transform_func = get_layout_transform_fn(in_layout_str)\n    out_layout_transform_func = get_layout_transform_fn(out_layout_str)\n    return tanhf16_stir_sched_nhwc(\n        tanh_func,\n        in_layout_transform_func,\n        out_layout_transform_func,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/tensor_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Optimized implementation of q_multiply_shift based on LLVM intrinsics\"\"\"\n\nimport tvm\nfrom tvm.ir import register_intrin_lowering\nfrom tvm import te\n\n\ndef _q_multiply_shift_hexagon(op):\n    \"\"\"\n    Implementation of q_multiply_shift through hexagon intrinsics vmpyewuh and vmpyowh when q == 31.\n    \"\"\"\n    x = op.args[0]\n    y = op.args[1]\n    fractional_bits = op.args[2]\n    shift = op.args[3]\n\n    # Don't use this intrinsic if we don't have a int32x32 vector\n    # or if we are not multiplying q31 numbers\n    if x.dtype != \"int32x32\" or fractional_bits.value != 31:\n        return op\n\n    # Case 1, shift is negative\n    mul_e_1 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyewuh.128B\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n    mul_o_1 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyowh.sacc.128B\", tvm.tir.const(3, \"uint32\"), mul_e_1, x, y\n    )\n    fixup = 1 << (-shift - 1)\n    round_mul = mul_o_1 + fixup\n    out_negative_shift = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vaslwv.128B\", tvm.tir.const(2, \"uint32\"), round_mul, shift\n    )\n\n    # Case 2, shift is positive\n    x = x * (1 << (shift))\n    mul_e_2 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyewuh.128B\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n    mul_o_2 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyowh.rnd.sacc.128B\", tvm.tir.const(3, \"uint32\"), mul_e_2, x, y\n    )\n\n    # Select depending on the shift\n    return tvm.tir.Select(shift < 0, out_negative_shift, mul_o_2)\n\n\nregister_intrin_lowering(\n    \"tir.q_multiply_shift\", target=\"hexagon\", f=_q_multiply_shift_hexagon, level=99\n)\n\n\ndef _q_multiply_shift_per_axis_hexagon(op):\n    \"\"\"\n    Implementation of q_multiply_shift_per_axis through hexagon intrinsics vmpyewuh and vmpyowh when\n    q == 31.\n    \"\"\"\n    x = op.args[0]\n    y = op.args[1]\n    left_shift = op.args[2]\n    right_shift = op.args[3]\n    fractional_bits = op.args[4]\n    is_lshift_required = op.args[5]\n    is_rshift_required = op.args[6]\n\n    # Don't use this intrinsic if we don't have a int32x32 vector\n    # or if we are not multiplying q31 numbers\n    if x.dtype != \"int32x32\" or fractional_bits.value != 31:\n        return op\n\n    # Don't use this intrinsic when we need do both: left and right shifts.\n    # For now it is not clear how to implement this case through vector HVX instructions without\n    # accuracy drop.\n    if is_rshift_required.value and is_lshift_required.value:\n        return op\n\n    # Case 1: do the left shift\n    shifted_x = x << left_shift\n    mul_e_1 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyewuh.128B\", tvm.tir.const(2, \"uint32\"), shifted_x, y\n    )\n    left_shift_out = tvm.tir.call_llvm_intrin(\n        op.dtype,\n        \"llvm.hexagon.V6.vmpyowh.rnd.sacc.128B\",\n        tvm.tir.const(3, \"uint32\"),\n        mul_e_1,\n        shifted_x,\n        y,\n    )\n\n    # Case 2: do the right shift\n    mul_e_2 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyewuh.128B\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n    mul_o_2 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyowh.sacc.128B\", tvm.tir.const(3, \"uint32\"), mul_e_2, x, y\n    )\n    fixup = 1 << (right_shift - 1)\n    round_mul = mul_o_2 + fixup\n    right_shift_out = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vasrwv.128B\", tvm.tir.const(2, \"uint32\"), round_mul, right_shift\n    )\n\n    # Case 3: do neither right nor left shift\n    mul_e_3 = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyewuh.128B\", tvm.tir.const(2, \"uint32\"), x, y\n    )\n    no_shift_out = tvm.tir.call_llvm_intrin(\n        op.dtype, \"llvm.hexagon.V6.vmpyowh.rnd.sacc.128B\", tvm.tir.const(3, \"uint32\"), mul_e_3, x, y\n    )\n\n    return tvm.tir.Select(\n        tvm.tir.Not(tvm.tir.Or(is_lshift_required, is_rshift_required)),\n        no_shift_out,\n        tvm.tir.Select(is_lshift_required, left_shift_out, right_shift_out),\n    )\n\n\nregister_intrin_lowering(\n    \"tir.q_multiply_shift_per_axis\",\n    target=\"hexagon\",\n    f=_q_multiply_shift_per_axis_hexagon,\n    level=99,\n)\n\n\ndef dot_vrmpy(x_ty, y_ty):\n    \"\"\"Generates vrmpy instruciton for tensorization.\"\"\"\n    int32_lanes = 32\n    num_int8_elements = 4  # 4 int8 elements in int32\n    data = te.placeholder((num_int8_elements,), dtype=x_ty, name=\"data\")\n    kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=y_ty, name=\"kernel\")\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int32_lanes,),\n        lambda i: te.sum(data[k].astype(\"int32\") * kernel[i, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=x_ty, name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        kernel.shape, dtype=y_ty, name=\"b_buffer\", offset_factor=1, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, \"int32x32\")))\n                return ib.get()\n\n            vec_zero = tvm.tir.const(0, \"int32x32\")\n\n            if x_ty == \"uint8\" and y_ty == \"uint8\":\n                a_uint8 = ins[0].vload([0], \"uint8x4\")\n                re_int32 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", a_uint8)\n                vec_b = ins[1].vload([0, 0], \"uint8x128\")\n\n                vrmpy_inst_name = \"llvm.hexagon.V6.vrmpyub.acc.128B\"\n\n                vec_bi32 = tvm.tir.call_intrin(\"int32x32\", \"tir.reinterpret\", vec_b)\n\n                quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int32x32\",\n                    vrmpy_inst_name,\n                    tvm.tir.const(3, \"uint32\"),\n                    vec_zero,\n                    vec_bi32,\n                    re_int32,\n                )\n            elif x_ty == \"uint8\" and y_ty == \"int8\":\n                a_uint8 = ins[0].vload([0], \"uint8x4\")\n                re_int32 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", a_uint8)\n                vec_b = ins[1].vload([0, 0], \"int8x128\")\n\n                vrmpy_inst_name = \"llvm.hexagon.V6.vrmpybusv.acc.128B\"\n\n                vec_bi32 = tvm.tir.call_intrin(\"int32x32\", \"tir.reinterpret\", vec_b)\n\n                quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int32x32\",\n                    vrmpy_inst_name,\n                    tvm.tir.const(3, \"uint32\"),\n                    vec_zero,\n                    re_int32.astype(\"int32x32\"),\n                    vec_bi32,\n                )\n            else:\n                raise ValueError(f\"Only (u8, u8) or (u8, i8) dtype pairs are supported by vrmpy.\")\n\n            if index == 0:\n                ib.emit(outs[0].vstore(0, quad_reduction))\n            else:\n                ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], \"int32x32\")))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hexagon/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name\n\n\n\"\"\"Common hexagon specific utilities\"\"\"\nimport math\nimport struct\nfrom typing import Tuple\nfrom tvm import te\n\n\ndef n11c_1024c_2d(n, h, w, c):\n    \"\"\"Return index map for n11c_1024 2d layout\"\"\"\n    return [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024]\n\n\ndef n11c_1024c_1d(n, h, w, c):\n    \"\"\"Return index map for n11c_1024 1d layout\"\"\"\n    return [n, h, w, c // 1024, c % 1024]\n\n\ndef nhwc_8h2w32c2w_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_8h2w32c2w 2d layout\"\"\"\n    return [n, h // 8, w // 4, c // 32, te.AXIS_SEPARATOR, h % 8, (w % 4) // 2, c % 32, w % 2]\n\n\ndef nhwc_8h2w32c2w_1d(n, h, w, c):\n    \"\"\"Return index map for nhwc_8h2w32c2w 1d layout\"\"\"\n    return [n, h // 8, w // 4, c // 32, h % 8, (w % 4) // 2, c % 32, w % 2]\n\n\ndef nhw_32h16w_2d(n, h, w):\n    \"\"\"Return index map for nhw_32h16w 2d layout\"\"\"\n    return [n, h // 32, w // 16, te.AXIS_SEPARATOR, h % 32, w % 16]\n\n\ndef nhwc_4h4w32c_1d(n, h, w, c):\n    \"\"\"Return index map for nhwc_4h4232c 1d layout\"\"\"\n    return [n, h // 4, w // 4, c // 32, h % 4, w % 4, c % 32]\n\n\ndef nhwc_4h4w32c_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_4h4w32c 2d layout\"\"\"\n    return [n, h // 4, w // 4, c // 32, te.AXIS_SEPARATOR, h % 4, w % 4, c % 32]\n\n\ndef nc_512c_1d(n, c):\n    \"\"\"Return index map for nc_512c 1d layout\"\"\"\n    return [n, c // 512, c % 512]\n\n\ndef nc_512c_2d(n, c):\n    \"\"\"Return index map for nc_512c 2d layout\"\"\"\n    return [n, c // 512, te.AXIS_SEPARATOR, c % 512]\n\n\ndef nc_1024c_2d(n, c):\n    \"\"\"Return index map for nc_1024c 2d layout\"\"\"\n    return [n, c // 1024, te.AXIS_SEPARATOR, c % 1024]\n\n\ndef nhwc_4h2w32c2w_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_4h2w32c2w 2d layout\"\"\"\n    return [n, h // 4, w // 4, c // 32, te.AXIS_SEPARATOR, h % 4, (w % 4) // 2, c % 32, w % 2]\n\n\ndef nhwc_1024c_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_1024 2d layout\"\"\"\n    return [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024]\n\n\ndef nc_1024_2d(n, c):\n    \"\"\"Return index map for nc_1024 2d layout\"\"\"\n    return [n, c // 1024, te.AXIS_SEPARATOR, c % 1024]\n\n\ndef nhwc_2048c_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_2048 2d layout\"\"\"\n    return [n, h, w, c // 2048, te.AXIS_SEPARATOR, c % 2048]\n\n\ndef nc_2048_2d(n, c):\n    \"\"\"Return index map for nc_2048 2d layout\"\"\"\n    return [n, c // 2048, te.AXIS_SEPARATOR, c % 2048]\n\n\ndef nc_2048c_2d(n, c):\n    \"\"\"Return index map for nc_2048 2d layout\"\"\"\n    return [n, c // 2048, te.AXIS_SEPARATOR, c % 2048]\n\n\ndef nhwc_8h8w32c_2d(n, h, w, c):\n    \"\"\"Return index map for nhwc_8h8w32c 2d layout\"\"\"\n    return [n, h // 8, w // 8, c // 32, te.AXIS_SEPARATOR, h % 8, w % 8, c % 32]\n\n\ndef n11c_2048c_2d(n, h, w, c):\n    \"\"\"Return index map for n11c_2048c 2d layout\"\"\"\n    return [n, h, w, c // 2048, te.AXIS_SEPARATOR, c % 2048]\n\n\ndef iohw_16i32o2i_1d(height, width, in_channel, out_channel):\n    return [\n        in_channel // 32,\n        out_channel // 32,\n        height,\n        width,\n        (in_channel % 32) // 2,\n        out_channel % 32,\n        in_channel % 2,\n    ]\n\n\ndef ohwi32o_1d(height, width, in_channel, out_channel):\n    return [out_channel // 32, height, width, in_channel, out_channel % 32]\n\n\ndef get_layout_transform_fn(layout):\n    \"\"\"Return index map function as per the layout string\"\"\"\n    if layout == \"nhwc-8h2w32c2w-2d\":\n        return nhwc_8h2w32c2w_2d\n    if layout == \"nhwc-8h2w32c2w-1d\":\n        return nhwc_8h2w32c2w_1d\n    if layout == \"n11c-1024c-2d\":\n        return n11c_1024c_2d\n    if layout == \"n11c-1024c-1d\":\n        return n11c_1024c_1d\n    if layout == \"nhwc-1024c-2d\":\n        return nhwc_1024c_2d\n    if layout == \"nc-1024-2d\":\n        return nc_1024_2d\n    if layout == \"nhw-32h16w-2d\":\n        return nhw_32h16w_2d\n    if layout == \"nhwc-4h4w32c-2d\":\n        return nhwc_4h4w32c_2d\n    if layout == \"nhwc-4h4w32c-1d\":\n        return nhwc_4h4w32c_1d\n    if layout == \"nc-512c-2d\":\n        return nc_512c_2d\n    if layout == \"nc-512c-1d\":\n        return nc_512c_1d\n    if layout == \"nhwc-4h2w32c2w-2d\":\n        return nhwc_4h2w32c2w_2d\n    if layout == \"nc-1024c-2d\":\n        return nc_1024c_2d\n    if layout == \"iohw-16i32o2i-1d\":\n        return iohw_16i32o2i_1d\n    if layout == \"nhwc-2048c-2d\":\n        return nhwc_2048c_2d\n    if layout == \"nc-2048-2d\":\n        return nc_2048_2d\n    if layout == \"nc-2048c-2d\":\n        return nc_2048c_2d\n    if layout == \"nhwc-8h8w32c-2d\":\n        return nhwc_8h8w32c_2d\n    if layout == \"n11c-2048c-2d\":\n        return n11c_2048c_2d\n    if layout == \"ohwi32o-1d\":\n        return ohwi32o_1d\n    raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n\ndef get_fixed_point_value(flp: float, dtype: str = \"int16\") -> Tuple[int, int]:\n    \"\"\"\n    Return fixed-point value and the corresponding log2 of the scale factor used to compute\n    this value.\n\n    Parameters\n    ----------\n    flp : float\n        Floating-point value to be converted\n    dtype : str\n        Type of the resulting fixed-point value. By default, it's set to \"int16\"\n\n    Returns\n    -------\n    fixed_point_value : int\n        Fixed-point value for the given floating-point value\n    exp_scale_factor : int\n        log2 of the scale factor\n\n    Convert floating-point value into fixed-point number. This is done by\n    multiplying the value by a scaling factor and then rounding it to the nearest\n    integer value.\n\n    As per IEEE-754 standard, a floating-point value can be represented as follows\n    [see: https://en.wikipedia.org/wiki/IEEE_754-1985]:\n        (-1)^S * M * 2^(E-Bias)\n\n    Here,\n    * S is the signed bit (0 or 1).\n    * M is the mantissa. It's composed of an implicit 1 for the normalized floating-point\n      values or 0 for the denormalized values, and the fraction part. This ensures that\n      mantissa is always within [0, 2) range. Please note that this function doesn't\n      handle denormalized values.\n    * E is the exponent.\n\n    In single precision, 23 bits are used to represent the fraction part of\n    the mantissa (and therefore, '23' shows up in one of the computations below) and\n    8 bits are used for the exponent. Since exponent field needs to reperesent both\n    positive and negative values, a bias (127 for single precision) is added to the actual\n    value. Therefore, to compute the actual exponent, 127 must be subtracted from the stored\n    value.\n\n    As mentioned above, to find the corresponding fixed-point number, we multiply the\n    value with a scaling factor and then round it to the nearest integer. The scaling factor\n    is chosen to be a power for 2 and it's the largest value that can be safely multiplied\n    to the floating-point value, without causing the resulting value to overflow the range\n    of the integer type used to represent the fixed-point value.\n\n    So, if we assume the scaling factor to be 2^x, the resulting fixed-point value will be:\n        round((-1)^S * (M) * 2^(E-Bias) * 2^x)\n\n    This can be simplified to:\n        round((-1)^S * M * 2^(E-Bias+x)\n\n    Now, if 'int16' is used for fixed-point value, then it has to be >= -(2 * 2^14)\n    and <= (2 * 2^14) - 1. Since M (Mantissa) is always < 2, in order for the fixed-point value\n    to be within this range, 2^(E - Bias + x) must be <= 2^14 - 1.\n    And, if we ignore -1, (E - Bias + x) should be <= 14. Note: if mantissa gets too close to 2,\n    this will cause the resulting value to go out of range and require it to be saturated.\n    In the following implementation, we perform range check and adjust the scale to avoid\n    saturation.\n    For most cases, 2^x, where x = 14 - (E - Bias) or 14 - (E - 127) for single precision, is the\n    best scaling factor for 'int16' type that can be used to convert the floating-point value to\n    fixed-point with the least amount of precision loss.\n\n\n    Here is a more rigorous explanation of the above, for non-negative scale values, which are of\n    interest. M < 2, so M * 2^(E-Bias+x) < 2 ^ (E-Bias+x+1)   [Note: LHS is a fraction, RHS int]\n    => round(M * 2^(E-Bias+x)) <= 2 ^ (E-Bias+x+1)  [Note the \"<=\", not \"<\"]\n    We want x s.t. round(M * 2^(E-Bias+x)) <= 2^15 - 1\n    We know round(M * 2^(E-Bias+x)) <= 2^(E-Bias+x+1)\n    It will be sufficient to choose x s.t. 2^(E-Bias+x+1) <= 2^15 - 1\n    That is, max x. s.t. 2^(E-Bias+x+1) < 2^15\n    E-Bias+x+1 < 15\n    E-Bias+x+1 <= 14\n    Max x will make E-Bias+x+1 = 14\n    x = 13 - E + Bias\n\n    Additonal notes on various floating-point values:\n    ------------------------------------------------\n    1) Denormalized values: causes assertion failure. The problem with the denormalized values\n        is that they require a very large scale factor (>= 2^127) to be converted to a fixed-point\n        value. As the denormalzied values get smaller, the scale factor becomes too large to be\n        represented as a IEEE-754 floating point value (as being done in the computaton below)\n        and therefore, the denormalized values aren't being handled here.\n    2) NaN and INF: assertion failure\n    \"\"\"\n\n    def within_range(val, dtype):\n        if dtype == \"int16\":\n            return -32768 <= val <= 32767\n        raise RuntimeError(f\"Unsupported dtype, {dtype}'\")\n\n    # Make sure that 'flp' isn't NaN or infinity\n    if math.isnan(flp) or math.isinf(flp):\n        raise RuntimeError(\"NaN or INF can not be represented as fixed-point\")\n\n    flp_f = struct.pack(\"f\", flp)\n    flp_i = struct.unpack(\"I\", flp_f)\n    exp_stored_value = (flp_i[0] >> 23) & 0xFF\n\n    if exp_stored_value == 0:\n        raise RuntimeError(\n            \"Denormalized values are not considered for float -> fixed-point conversion!\"\n        )\n\n    exp_value = ((flp_i[0] >> 23) & 0xFF) - 127\n    if dtype == \"int16\":\n        max_bits = 14\n    else:\n        raise RuntimeError(f\"Unsupported dtype, {dtype}'\")\n\n    exp_scale_factor = max_bits - exp_value  # log2 of the scale_factor\n\n    if exp_scale_factor > 127:\n        raise RuntimeError(\"Value too small for fixed-point conversion!\")\n\n    # Scaling factor = 2^exp_scale_factor\n    # Since exp_scale_factor can be -ve or +ve, scaling factor is calculated by first\n    # representing the value in the binary format as per IEEE floating-point standand and then\n    # reinterpreting it as a float using struct.pack and struct.unpack functions.\n    # struct.pack returns a bytes object packed as integer and struct.unpack\n    # unpacks this bytes object into float.\n    scale = ((exp_scale_factor + 127) & 0xFF) << 23\n    scale_i = struct.pack(\"I\", scale)\n    scale_f = struct.unpack(\"f\", scale_i)\n    fixed_point_value = int(round(flp * scale_f[0]))\n\n    if not within_range(fixed_point_value, dtype):\n        # Adjust scale factor to avoid overflow.\n        exp_scale_factor -= 1\n        scale = ((exp_scale_factor + 127) & 0xFF) << 23\n        scale_i = struct.pack(\"I\", scale)\n        scale_f = struct.unpack(\"f\", scale_i)\n        fixed_point_value = int(round(flp * scale_f[0]))\n\n    return fixed_point_value, exp_scale_factor\n\n\ndef saturate(x: te.Tensor, dtype: str):\n    \"\"\"Saturate value for the specified data type\"\"\"\n    return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype)))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hls/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"HLS specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .injective import schedule_injective, schedule_elemwise, schedule_broadcast\nfrom .nn import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hls/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable,\n\"\"\"Schedule for composition of injective operator\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n    fused = sch[out].fuse(*sch[out].op.axis)\n    px, x = sch[out].split(fused, nparts=1)\n    sch[out].bind(px, te.thread_axis(\"pipeline\"))\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"Schedule for injective op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n    for out in outs:\n        schedule_injective_from_existing(s, out)\n    return s\n\n\nschedule_elemwise = schedule_injective\nschedule_broadcast = schedule_injective\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/hls/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"HLS nn operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\ndef _schedule_conv2d(outs):\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_injective(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n        # schedule conv2d\n        elif OP.tag.find(\"conv2d\") >= 0:\n            Conv2d = OP.output(0)\n            if not Conv2d.op in s.outputs:\n                Out = outs[0].op.output(0)\n                s[Conv2d].compute_at(s[Out], s[Out].op.axis[1])\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n\n    px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1)\n    s[outs[0]].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n\n\ndef schedule_conv2d_nchw(outs):\n    \"\"\"Schedule for conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_conv2d_nhwc(outs):\n    \"\"\"Schedule for conv2d_nhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_conv2d_NCHWc(outs):\n    \"\"\"Schedule for conv2d_NCHW[x]c\n\n    Parameters\n    ----------\n    outs : Array of Tensor\n        The computation graph description of conv2d_NCHWc\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    sch : Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_conv2d_transpose_nchw(outs):\n    \"\"\"Schedule for conv2d_transpose_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_transpose_nchw\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_depthwise_conv2d_nchw(outs):\n    \"\"\"Schedule for depthwise_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of depthwise_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_depthwise_conv2d_nhwc(outs):\n    \"\"\"Schedule for depthwise_conv2d_nhwc\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of depthwise_conv2d_nhwc\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_bitserial_conv2d_nchw(outs):\n    \"\"\"Schedule for bitserial_conv2d_nchw\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of bitserial_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_bitserial_conv2d_nhwc(outs):\n    \"\"\"Schedule for bitserial_conv2d_nhwc\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of bitserial_conv2d_nchw\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    return _schedule_conv2d(outs)\n\n\ndef schedule_reduce(outs):\n    \"\"\"Schedule for reduction\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of reduce\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n        elif OP.tag in [\"comm_reduce\", \"comm_reduce_idx\"]:\n            if OP.tag == \"comm_reduce\":\n                Reduce = OP.output(0)\n            else:\n                Reduce = OP.input_tensors[0]\n            if not Reduce.op in s.outputs:\n                Out = outs[0].op.output(0)\n                s[Reduce].compute_at(s[Out], s[Out].op.axis[0])\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n\n    fused = s[outs[0]].fuse()\n    px, x = s[outs[0]].split(fused, nparts=1)\n    s[outs[0]].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n\n\ndef schedule_softmax(outs):\n    \"\"\"Schedule for softmax\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of softmax\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    softmax = outs[0]\n\n    op_tag = softmax.op.tag\n    if op_tag == \"softmax_output\":\n        expsum = softmax.op.input_tensors[1]\n        exp = softmax.op.input_tensors[0]\n        max_elem = s[exp].op.input_tensors[1]\n    elif op_tag == \"log_softmax_output\":\n        exp = None\n        max_elem = softmax.op.input_tensors[1]\n        expsum = softmax.op.input_tensors[2]\n    else:\n        raise ValueError(\n            \"Tag is expected to be softmax_output or log_softmax_output. \\\n                         Got {0}\".format(\n                op_tag\n            )\n        )\n\n    if exp is not None:\n        s[exp].compute_at(s[softmax], s[softmax].op.axis[1])\n\n    s[expsum].compute_at(s[softmax], s[softmax].op.axis[1])\n    s[max_elem].compute_at(s[softmax], s[softmax].op.axis[1])\n\n    px, x = s[softmax].split(softmax.op.axis[0], nparts=1)\n    s[softmax].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n\n\ndef schedule_dense(outs):\n    \"\"\"Schedule for dense\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of dense\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n        # schedule dense\n        elif OP.tag == \"dense\":\n            Dense = OP.output(0)\n            if not Dense.op in s.outputs:\n                Out = outs[0].op.output(0)\n                s[Dense].compute_at(s[Out], s[Out].op.axis[1])\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n\n    px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1)\n    s[outs[0]].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Schedule for pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of pool\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n        # schedule pool\n        elif OP.tag.startswith(\"pool\"):\n            Pool = OP.output(0)\n            if not Pool.op in s.outputs:\n                Out = outs[0].op.output(0)\n                s[Pool].compute_at(s[Out], s[Out].op.axis[1])\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n\n    px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1)\n    s[outs[0]].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n\n\ndef schedule_adaptive_pool(outs):\n    \"\"\"Schedule for adaptive_pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of adaptive_pool\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    tvm.te.schedule.AutoInlineInjective(s)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n        # schedule global_pool\n        elif OP.tag.startswith(\"adaptive_pool\"):\n            Pool = OP.output(0)\n            if not Pool.op in s.outputs:\n                Out = outs[0].op.output(0)\n                s[Pool].compute_at(s[Out], s[Out].op.axis[1])\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n\n    px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1)\n    s[outs[0]].bind(px, te.thread_axis(\"pipeline\"))\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/image/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"IMAGE network operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .resize import *\nfrom .dilation2d import *\nfrom .grid_sample import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/image/dilation2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin\n\"\"\"Dilation2D operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom tvm import te\nfrom tvm.topi.utils import simplify\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple\n\n\ndef dilation2d_nchw(input, filter, stride, padding, dilations, out_dtype=None):\n    \"\"\"Morphological dilation operator in NCHW layout.\n\n    Parameters\n    ----------\n    input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    filter : tvm.te.Tensor\n        3-D with shape [ in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str\n        Padding size\n\n    dilations: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype : Optional[str]\n        Specifies the output data type.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, in_channel, out_height, out_width]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilations, int) or len(dilations) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilations, int):\n        dilation_h = dilation_w = dilations\n    else:\n        dilation_h, dilation_w = dilations\n\n    batch, in_channel, in_height, in_width = input.shape\n    channel, kernel_h, kernel_w = filter.shape\n    assert (\n        in_channel.value == channel.value\n    ), \"For Dilation2D input and filter channels should be same.\"\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    # compute graph\n    pad_before = [0, 0, pad_top, pad_left]\n    pad_after = [0, 0, pad_down, pad_right]\n    temp = pad(input, pad_before, pad_after, name=\"pad_temp\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    return te.compute(\n        (batch, in_channel, out_height, out_width),\n        lambda nn, ff, yy, xx: te.max(\n            temp[nn, ff, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w].astype(\n                out_dtype\n            )\n            + filter[ff, ry, rx].astype(out_dtype),\n            axis=[ry, rx],\n        ),\n        tag=\"dilation2d_nchw\",\n    )\n\n\ndef dilation2d_nhwc(input, filter, stride, padding, dilations, out_dtype=None):\n    \"\"\"Morphological 2d dilation NHWC layout.\n\n    Parameters\n    ----------\n    input : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    filter : tvm.te.Tensor\n        3-D with shape [filter_height, filter_width, in_channel]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int\n        Padding size\n\n    dilations: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype : Optional[str]\n        Specifies the output data type.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, in_channel]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilations, int) or len(dilations) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilations, int):\n        dilation_h = dilation_w = dilations\n    else:\n        dilation_h, dilation_w = dilations\n\n    batch, in_height, in_width, in_channel = input.shape\n    kernel_h, kernel_w, channel = filter.shape\n    assert (\n        in_channel.value == channel.value\n    ), \"For Dilation2D input and filter channels should be same.\"\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    padded_input = pad(input, pad_before, pad_after, name=\"padded_input\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    return te.compute(\n        (batch, out_height, out_width, in_channel),\n        lambda nn, yy, xx, ff: te.max(\n            padded_input[\n                nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, ff\n            ].astype(out_dtype)\n            + filter[ry, rx, ff].astype(out_dtype),\n            axis=[ry, rx],\n        ),\n        tag=\"dilation2d_nhcw\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/image/grid_sample.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"affine_grid and grid_sample operator\"\"\"\nfrom tvm import te, tir\n\n\ndef affine_grid(data, target_shape):\n    \"\"\"affine_grid operator that generates 2D sampling grid.\n\n    This operation is described in https://arxiv.org/pdf/1506.02025.pdf. It generates a uniform\n    sampling grid within the target shape and normalizes it to [-1, 1]. The provided affine\n    transformation is then applied on the sampling grid.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        3-D with shape [batch, 2, 3]. The affine matrix.\n\n    target_shape: list/tuple of two int\n        Specifies the output shape (H, W).\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        4-D with shape [batch, 2, target_height, target_width]\n    \"\"\"\n    assert target_shape is not None\n    assert len(target_shape) == 2\n    assert (\n        target_shape[0] > 1 and target_shape[1] > 1\n    ), \"target height/width should be greater than 1\"\n\n    dtype = data.dtype\n    y_step = tir.const((2.0 - 1e-7) / (target_shape[0] - 1), dtype=dtype)\n    x_step = tir.const((2.0 - 1e-7) / (target_shape[1] - 1), dtype=dtype)\n    start = tir.const(-1.0, dtype=dtype)\n\n    def _compute(n, dim, i, j):\n        y = start + i * y_step\n        x = start + j * x_step\n        return data[n, dim, 0] * x + data[n, dim, 1] * y + data[n, dim, 2]\n\n    oshape = (data.shape[0], len(target_shape), *target_shape)\n    return te.compute(oshape, _compute, tag=\"affine_grid\")\n\n\ndef _grid_sample_2d(\n    data, grid, method=\"bilinear\", layout=\"NCHW\", padding_mode=\"zeros\", align_corners=True\n):\n    \"\"\"Applies bilinear/nearest/bicubic sampling to input feature map.\n\n    Given :math:`data` and :math:`grid` assuming NCHW layout, then the output is computed by\n\n    .. math::\n\n        x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\\\\n        y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\\\\n        output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src})\n\n    :math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and\n    :math:`G()` denotes the interpolation method.\n\n    The out-boundary points will be padded with zeros if padding_mode is \"zeros\", or\n    border pixel value if padding_mode is \"border\", or\n    inner pixel value if padding_mode is \"reflection\".\n\n    The left-top corner (-1, -1) and right-bottom corner (1, 1) in grid will be map to\n    (0, 0) and (h - 1, w - 1) of data if align_corners is \"True\", or\n    (-0.5, -0.5) and (h - 0.5, w - 0.5) of data if align_corners is \"False\".\n\n    The shape of the output will be (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]).\n\n    The operator assumes that :math:`grid` has been normalized to [-1, 1].\n\n    grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    grid : tvm.Tensor\n        4-D with shape [batch, 2, out_height, out_width]\n\n    method : str\n        The interpolation method \"nearest\", \"bilinear\", \"bicubic\" are supported.\n\n    layout : str\n        The layout of input data and the output.\n\n    padding_mode : str\n        The padding mode for outside grid values, \"zeros\", \"border\", \"reflection\" are supported.\n\n    align_corners: bool\n        Geometrically, we consider the pixels of the input as squares rather than points.\n        If set to \"True\", the extrema (\"-1\" and \"1\") are considered as referring\n        to the center points of the input corner pixels. If set to \"False\", they\n        are instead considered as referring to the corner points of the input corner\n        pixels, making the sampling more resolution agnostic.\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        4-D with shape [batch, in_channel, out_height, out_width]\n    \"\"\"\n\n    assert method in (\"bilinear\", \"nearest\", \"bicubic\"), f\"{method} is not supported\"\n    assert padding_mode in (\"zeros\", \"border\", \"reflection\"), f\"{padding_mode} is not supported\"\n    assert layout == \"NCHW\", f\"{layout} is not supported\"\n\n    batch, in_channel, in_height, in_width = data.shape\n    out_height, out_width = grid.shape[2:]\n\n    def _get_pixel_value(n, c, h, w):\n        return te.if_then_else(\n            te.all(h >= 0, w >= 0, h < in_height, w < in_width),\n            data[n, c, h, w],\n            tir.const(0.0, dtype=data.dtype),\n        )\n\n    def _unnormalize(h, w):\n        if align_corners:\n            y = (h + 1) * (in_height - 1) / 2\n            x = (w + 1) * (in_width - 1) / 2\n        else:\n            y = -0.5 + (h + 1) * in_height / 2\n            x = -0.5 + (w + 1) * in_width / 2\n        return (y, x)\n\n    def _clip_coordinates(x, size):\n        return te.min(te.max(x, 0), size - 1)\n\n    def _compute_source_index(n, h, w):\n        y = grid[n, 1, h, w]\n        x = grid[n, 0, h, w]\n        y, x = _unnormalize(y, x)\n\n        if padding_mode == \"reflection\":\n            y = _reflect_coordinates(y, in_height)\n            x = _reflect_coordinates(x, in_width)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n        elif padding_mode == \"border\":\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n\n        return (y, x)\n\n    def _reflect_coordinates(x, size):\n        def __refelection(x, size, corner_start):\n            def __reflect(index, size, corner_start):\n                index_align_corner = te.abs(corner_start - index)\n                size_times = te.truncdiv(index_align_corner.astype(\"int32\"), size).astype(\"int32\")\n                t = tir.Mod(size_times, 2)\n                extra = index_align_corner - size_times * size\n                return tir.if_then_else(\n                    tir.EQ(t, 0), extra + corner_start, size - extra + corner_start\n                )\n\n            return tir.if_then_else(\n                tir.all(x >= corner_start, x <= size + corner_start),\n                x,\n                __reflect(x, size, corner_start),\n            )\n\n        if align_corners:\n            new_x = __refelection(x, size - 1, 0)\n        else:\n            new_x = __refelection(x, size, -0.5)\n        return new_x\n\n    def _bilinear_sample(n, c, h, w):\n        y, x = _compute_source_index(n, h, w)\n        y0 = te.floor(y).astype(\"int32\")\n        x0 = te.floor(x).astype(\"int32\")\n        y1 = y0 + tir.const(1, \"int32\")\n        x1 = x0 + tir.const(1, \"int32\")\n\n        return (\n            _get_pixel_value(n, c, y0, x0) * (1.0 - (y - y0)) * (1.0 - (x - x0))\n            + _get_pixel_value(n, c, y0, x1) * (1.0 - (y - y0)) * (x - x0)\n            + _get_pixel_value(n, c, y1, x0) * (y - y0) * (1.0 - (x - x0))\n            + _get_pixel_value(n, c, y1, x1) * (y - y0) * (x - x0)\n        )\n\n    def _nearest_sample(n, c, h, w):\n        y, x = _compute_source_index(n, h, w)\n        y_new = te.nearbyint(y).astype(\"int32\")\n        x_new = te.nearbyint(x).astype(\"int32\")\n\n        return _get_pixel_value(n, c, y_new, x_new)\n\n    def _bicubic_sample(n, c, h, w):\n        A = -0.75  # -0.75 is used in pytorch, it maybe different in other frameworks\n\n        def cubic_weight_1(fraction):\n            return ((A + 2) * fraction - (A + 3)) * fraction * fraction + 1\n\n        def cubic_weight_2(fraction):\n            return ((A * fraction - 5 * A) * fraction + 8 * A) * fraction - 4 * A\n\n        def cubic_interp_1d(pixel_0, pixel_1, pixel_2, pixel_3, fraction):\n            weights = [0] * 4\n            weights[0] = cubic_weight_2(fraction + 1)\n            weights[1] = cubic_weight_1(fraction)\n            weights[2] = cubic_weight_1(1 - fraction)\n            weights[3] = cubic_weight_2(2 - fraction)\n            return (\n                pixel_0 * weights[0]\n                + pixel_1 * weights[1]\n                + pixel_2 * weights[2]\n                + pixel_3 * weights[3]\n            )\n\n        y = grid[n, 1, h, w]\n        x = grid[n, 0, h, w]\n        y, x = _unnormalize(y, x)\n        y_floor = te.floor(y).astype(\"int32\")\n        x_floor = te.floor(x).astype(\"int32\")\n        y_fraction = y - y_floor\n        x_fraction = x - x_floor\n\n        coefficients = [0] * 4\n\n        for i in range(4):\n            y_ = y_floor - 1 + i\n            x_0 = x_floor - 1\n            x_1 = x_floor + 0\n            x_2 = x_floor + 1\n            x_3 = x_floor + 2\n\n            if padding_mode == \"border\":\n                y_ = _clip_coordinates(y_, in_height).astype(\"int32\")\n                x_0 = _clip_coordinates(x_0, in_width).astype(\"int32\")\n                x_1 = _clip_coordinates(x_1, in_width).astype(\"int32\")\n                x_2 = _clip_coordinates(x_2, in_width).astype(\"int32\")\n                x_3 = _clip_coordinates(x_3, in_width).astype(\"int32\")\n\n            elif padding_mode == \"reflection\":\n                y_ = _reflect_coordinates(y_, in_height)\n                x_0 = _reflect_coordinates(x_0, in_width)\n                x_1 = _reflect_coordinates(x_1, in_width)\n                x_2 = _reflect_coordinates(x_2, in_width)\n                x_3 = _reflect_coordinates(x_3, in_width)\n\n                y_ = _clip_coordinates(y_, in_height).astype(\"int32\")\n                x_0 = _clip_coordinates(x_0, in_width).astype(\"int32\")\n                x_1 = _clip_coordinates(x_1, in_width).astype(\"int32\")\n                x_2 = _clip_coordinates(x_2, in_width).astype(\"int32\")\n                x_3 = _clip_coordinates(x_3, in_width).astype(\"int32\")\n\n            coefficients[i] = cubic_interp_1d(\n                _get_pixel_value(n, c, y_, x_0),\n                _get_pixel_value(n, c, y_, x_1),\n                _get_pixel_value(n, c, y_, x_2),\n                _get_pixel_value(n, c, y_, x_3),\n                x_fraction,\n            )\n\n        return cubic_interp_1d(\n            coefficients[0], coefficients[1], coefficients[2], coefficients[3], y_fraction\n        )\n\n    if method == \"bilinear\":\n        interpolation = _bilinear_sample\n    elif method == \"nearest\":\n        interpolation = _nearest_sample\n    else:  # method == \"bicubic\"\n        interpolation = _bicubic_sample\n\n    return te.compute((batch, in_channel, out_height, out_width), interpolation, tag=\"grid_sample\")\n\n\ndef _grid_sample_3d(\n    data, grid, method=\"bilinear\", layout=\"NCDHW\", padding_mode=\"zeros\", align_corners=True\n):\n    \"\"\"Applies bilinear/nearest sampling to input feature map.\n\n    Given :math:`data` and :math:`grid` assuming NCDHW layout, then the output is computed by\n\n    .. math::\n\n        x_{src} = grid[batch, 0, z_{dst}, y_{dst}, x_{dst}] \\\\\n        y_{src} = grid[batch, 1, z_{dst}, y_{dst}, x_{dst}] \\\\\n        z_{src} = grid[batch, 2, z_{dst}, y_{dst}, x_{dst}] \\\\\n        output[batch, channel, z_{src}, y_{dst}, x_{dst}]\n        = G(data[batch, channel, z_{src}, y_{src}, x_{src})\n\n    :math:`x_{dst}`, :math:`y_{dst}`, :math:`z_{dst}` enumerate all spatial locations\n    in :math:`output`, and :math:`G()` denotes the interpolation method.\n\n    The out-boundary points will be padded with zeros if padding_mode is \"zeros\", or\n    border pixel value if padding_mode is \"border\", or\n    inner pixel value if padding_mode is \"reflection\".\n\n    The left-top corner (-1, -1, -1) and right-bottom corner (1, 1, 1) in grid will be map to\n    (0, 0, 0) and (d - 1, h - 1, w - 1) of data if align_corners is \"True\", or\n    (-0.5, -0.5, -0.5) and (d - 0.5, h - 0.5, w - 0.5) of data if align_corners is \"False\".\n\n    The shape of the output will be\n    (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3], grid.shape[4]).\n\n    The operator assumes that :math:`grid` has been normalized to [-1, 1].\n\n    grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    grid : tvm.Tensor\n        5-D with shape [batch, 3, out_depth, out_height, out_width]\n\n    method : str\n        The interpolation method \"nearest\", \"bilinear\"(\"trilinear\") are supported.\n\n    layout : str\n        The layout of input data and the output.\n\n    padding_mode : str\n        The padding mode for outside grid values, \"zeros\", \"border\", \"reflection\" are supported.\n\n    align_corners: bool\n        Geometrically, we consider the pixels of the input as squares rather than points.\n        If set to \"True\", the extrema (\"-1\" and \"1\") are considered as referring\n        to the center points of the input corner pixels. If set to \"False\", they\n        are instead considered as referring to the corner points of the input corner\n        pixels, making the sampling more resolution agnostic.\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        5-D with shape [batch, in_channel, out_depth, out_height, out_width]\n    \"\"\"\n\n    assert method in (\"bilinear\", \"nearest\"), f\"{method} is not supported\"\n    assert padding_mode in (\"zeros\", \"border\", \"reflection\"), f\"{padding_mode} is not supported\"\n    assert layout == \"NCDHW\", f\"{layout} is not supported\"\n\n    batch, in_channel, in_depth, in_height, in_width = data.shape\n    out_depth, out_height, out_width = grid.shape[2:]\n\n    def _get_pixel_value(n, c, d, h, w):\n        return te.if_then_else(\n            te.all(d >= 0, h >= 0, w >= 0, d < in_depth, h < in_height, w < in_width),\n            data[n, c, d, h, w],\n            tir.const(0.0, dtype=data.dtype),\n        )\n\n    def _compute_source_index(n, d, h, w):\n        z = grid[n, 2, d, h, w]\n        y = grid[n, 1, d, h, w]\n        x = grid[n, 0, d, h, w]\n\n        if align_corners:\n            z = (z + 1) * (in_depth - 1) / 2\n            y = (y + 1) * (in_height - 1) / 2\n            x = (x + 1) * (in_width - 1) / 2\n        else:\n            z = -0.5 + (z + 1) * in_depth / 2\n            y = -0.5 + (y + 1) * in_height / 2\n            x = -0.5 + (x + 1) * in_width / 2\n\n        if padding_mode == \"reflection\":\n            z = _reflect_coordinates(z, in_depth)\n            y = _reflect_coordinates(y, in_height)\n            x = _reflect_coordinates(x, in_width)\n            z = _clip_coordinates(z, in_depth)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n        elif padding_mode == \"border\":\n            z = _clip_coordinates(z, in_depth)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n\n        return (z, y, x)\n\n    def _clip_coordinates(x, size):\n        return te.min(te.max(x, 0), size - 1)\n\n    def _reflect_coordinates(x, size):\n        def __refelection(x, size, corner_start):\n            def __reflect(index, size, corner_start):\n                index_align_corner = te.abs(corner_start - index)\n                size_times = te.truncdiv(index_align_corner.astype(\"int32\"), size).astype(\"int32\")\n                t = tir.Mod(size_times, 2)\n                extra = index_align_corner - size_times * size\n                return tir.if_then_else(\n                    tir.EQ(t, 0), extra + corner_start, size - extra + corner_start\n                )\n\n            return tir.if_then_else(\n                tir.all(x >= corner_start, x <= size + corner_start),\n                x,\n                __reflect(x, size, corner_start),\n            )\n\n        if align_corners:\n            return __refelection(x, size - 1, 0)\n        return __refelection(x, size, -0.5)\n\n    def _trilinear_sample(n, c, d, h, w):\n        z, y, x = _compute_source_index(n, d, h, w)\n        z0 = te.floor(z).astype(\"int32\")\n        y0 = te.floor(y).astype(\"int32\")\n        x0 = te.floor(x).astype(\"int32\")\n        z1 = z0 + tir.const(1, \"int32\")\n        y1 = y0 + tir.const(1, \"int32\")\n        x1 = x0 + tir.const(1, \"int32\")\n\n        return (\n            _get_pixel_value(n, c, z0, y0, x0) * (1 - (x - x0)) * (1 - (y - y0)) * (1 - (z - z0))\n            + _get_pixel_value(n, c, z0, y0, x1) * (x - x0) * (1 - (y - y0)) * (1 - (z - z0))\n            + _get_pixel_value(n, c, z1, y1, x0) * (1 - (x - x0)) * (y - y0) * (z - z0)\n            + _get_pixel_value(n, c, z1, y1, x1) * (x - x0) * (y - y0) * (z - z0)\n            + _get_pixel_value(n, c, z0, y1, x0) * (1 - (x - x0)) * (y - y0) * (1 - (z - z0))\n            + _get_pixel_value(n, c, z1, y0, x1) * (x - x0) * (1 - (y - y0)) * (z - z0)\n            + _get_pixel_value(n, c, z1, y0, x0) * (1 - (x - x0)) * (1 - (y - y0)) * (z - z0)\n            + _get_pixel_value(n, c, z0, y1, x1) * (x - x0) * (y - y0) * (1 - (z - z0))\n        )\n\n    def _nearest_sample(n, c, d, h, w):\n        z, y, x = _compute_source_index(n, d, h, w)\n        z_new = te.nearbyint(z).astype(\"int32\")\n        y_new = te.nearbyint(y).astype(\"int32\")\n        x_new = te.nearbyint(x).astype(\"int32\")\n        return _get_pixel_value(n, c, z_new, y_new, x_new)\n\n    if method == \"bilinear\":\n        interpolation = _trilinear_sample\n    else:  # method == \"nearest\"\n        interpolation = _nearest_sample\n\n    return te.compute(\n        (batch, in_channel, out_depth, out_height, out_width), interpolation, tag=\"grid_sample\"\n    )\n\n\ndef grid_sample(\n    data, grid, method=\"bilinear\", layout=\"NCHW\", padding_mode=\"zeros\", align_corners=True\n):\n    \"\"\"Applies grid sampling to input feature map.\n\n    Given :math:`data` and :math:`grid`, then for 4-D the output is computed by\n\n    .. math::\n\n        x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\\\\n        y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\\\\n        output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src}])\n\n    :math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and\n    :math:`G()` denotes the interpolation function.\n\n    The out-boundary points will be padded with zeros if padding_mode is \"zeros\", or\n    border pixel value if padding_mode is \"border\", or\n    inner pixel value if padding_mode is \"reflection\".\n\n    The left-top corner (-1, -1) and right-bottom corner (1, 1) in grid will be map to\n    (0, 0) and (h - 1, w - 1) of data if align_corners is \"True\", or\n    (-0.5, -0.5) and (h - 0.5, w - 0.5) of data if align_corners is \"False\".\n\n    The shape of the output will be\n    4-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]), or\n    5-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3], grid.shape[4]).\n\n    The operator assumes that :math:`grid` has been normalized to [-1, 1].\n\n    grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample.\n\n    Parameters\n    ----------\n    data : tvm.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width], or\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    grid : tvm.Tensor\n        4-D with shape [batch, 2, out_height, out_width], or\n        5-D with shape [batch, 3, out_depth, out_height, out_width]\n\n    method : str\n        The interpolation method, 4-D \"nearest\", \"bilinear\", \"bicubic\" and\n        5-D \"nearest\", \"bilinear\"(\"trilinear\") are supported.\n\n    layout : str\n        The layout of input data and the output.\n\n    padding_mode : str\n        The padding mode for outside grid values, \"zeros\", \"border\", \"reflection\" are supported.\n\n    align_corners: bool\n        Geometrically, we consider the pixels of the input as squares rather than points.\n        If set to \"True\", the extrema (\"-1\" and \"1\") are considered as referring\n        to the center points of the input corner pixels. If set to \"False\", they\n        are instead considered as referring to the corner points of the input corner\n        pixels, making the sampling more resolution agnostic.\n\n    Returns\n    -------\n    Output : tvm.Tensor\n        4-D with shape [batch, in_channel, out_height, out_width], or\n        5-D with shape [batch, in_channel, out_depth, out_height, out_width]\n    \"\"\"\n\n    if len(layout) == 4:\n        compute = _grid_sample_2d\n    elif len(layout) == 5:\n        compute = _grid_sample_3d\n    else:\n        msg = f\"layout {layout} is not supported\"\n        raise ValueError(msg)\n\n    return compute(data, grid, method, layout, padding_mode, align_corners)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/image/resize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator input resize compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom tvm.topi.utils import nchw_pack_layout, nchw_xc_layout\nfrom .. import tag\n\n\ndef can_convert_multiply_to_intdiv(origin_size, scaled_size):\n    \"\"\"Check whether can convert multiplication to division\"\"\"\n    # Only support IntImm type\n    if not isinstance(scaled_size, tvm.tir.expr.IntImm):\n        return False\n\n    div = scaled_size / origin_size.astype(\"float\")\n    if div.value % 1 != 0:\n        return False\n    epsilon = 1e-5\n    check = 1 / (epsilon * origin_size + epsilon)\n    if div > check:\n        return False\n    return True\n\n\ndef get_1d_indices(indices, layout=\"NCW\"):\n    \"\"\"Get 1d indices\"\"\"\n    (cc, inum, ic) = (0, 0, 0)\n    if layout == \"NWC\":\n        n, x, c = indices\n        cc = None\n    elif layout == \"NCW\":\n        n, c, x = indices\n        cc = None\n    elif ncw_pack_layout(layout):\n        n, c, x, inum, ic = indices\n    else:\n        # else must be NCHWxc\n        assert ncw_xc_layout(layout)\n        n, c, x, cc = indices\n\n    return n, c, x, cc, inum, ic\n\n\ndef get_2d_indices(indices, layout=\"NCHW\"):\n    \"\"\"Get 2d indices\"\"\"\n    (cc, inum, ic) = (0, 0, 0)\n    if layout == \"NHWC\":\n        n, y, x, c = indices\n        cc = None\n    elif layout == \"NCHW\":\n        n, c, y, x = indices\n        cc = None\n    elif nchw_pack_layout(layout):\n        n, c, y, x, inum, ic = indices\n    else:\n        # else must be NCHWxc\n        assert nchw_xc_layout(layout)\n        n, c, y, x, cc = indices\n\n    return n, c, y, x, cc, inum, ic\n\n\ndef get_3d_indices(indices, layout=\"NCDHW\"):\n    \"\"\"Get 3d indices\"\"\"\n    if layout == \"NDHWC\":\n        n, z, y, x, c = indices\n        cc = None\n    elif layout == \"NCDHW\":\n        n, c, z, y, x = indices\n        cc = None\n    else:\n        n, c, z, y, x, cc = indices\n\n    return n, c, z, y, x, cc\n\n\ndef get_1d_pixel(data, layout, image_width, n, c, x, cc, ib, ic):\n    \"\"\"Get 1d pixel\"\"\"\n    x = tvm.te.max(tvm.te.min(x, image_width - 1), 0)\n    if layout == \"NWC\":\n        return data(n, x, c).astype(\"float\")\n    if layout == \"NCW\":\n        return data(n, c, x).astype(\"float\")\n    if ncw_pack_layout(layout):\n        return data(n, c, x, ib, ic).astype(\"float\")\n\n    # else must be NCHWxc\n    assert ncw_xc_layout(layout)\n    return data(n, c, x, cc).astype(\"float\")\n\n\ndef get_2d_pixel(data, layout, image_height, image_width, n, c, y, x, cc, ib, ic):\n    \"\"\"Get 2d pixel\"\"\"\n    y = tvm.te.max(tvm.te.min(y, image_height - 1), 0)\n    x = tvm.te.max(tvm.te.min(x, image_width - 1), 0)\n    if layout == \"NHWC\":\n        return data(n, y, x, c).astype(\"float\")\n    if layout == \"NCHW\":\n        return data(n, c, y, x).astype(\"float\")\n    if nchw_pack_layout(layout):\n        return data(n, c, y, x, ib, ic).astype(\"float\")\n\n    # else must be NCHWxc\n    assert nchw_xc_layout(layout)\n    return data(n, c, y, x, cc).astype(\"float\")\n\n\ndef get_3d_pixel(data, layout, image_depth, image_height, image_width, n, c, z, y, x, cc):\n    \"\"\"Get 3d pixel\"\"\"\n    z = tvm.te.max(tvm.te.min(z, image_depth - 1), 0)\n    y = tvm.te.max(tvm.te.min(y, image_height - 1), 0)\n    x = tvm.te.max(tvm.te.min(x, image_width - 1), 0)\n    if layout == \"NDHWC\":\n        return data(n, z, y, x, c).astype(\"float\")\n    if layout == \"NCDHW\":\n        return data(n, c, z, y, x).astype(\"float\")\n    # else must be NCDHWxc\n    return data(n, c, z, y, x, cc).astype(\"float\")\n\n\ndef get_inx(\n    x,\n    image_width,\n    target_width,\n    coordinate_transformation_mode,\n    start_x=0,\n    end_x=-1,\n    use_int_div=False,\n):\n    \"\"\"Infer input x from output x with various coordinate transformation methods\"\"\"\n    scale_x = te.div(image_width.astype(\"float\"), target_width.astype(\"float\"))\n    if coordinate_transformation_mode == \"half_pixel\":\n        in_x = (x + 0.5) * scale_x - 0.5\n    elif coordinate_transformation_mode == \"align_corners\":\n        in_x = (image_width - 1).astype(\"float\") / (target_width - 1) * x\n    elif coordinate_transformation_mode == \"asymmetric\":\n        if use_int_div:\n            in_x = te.div(x, te.div(target_width, image_width))\n        else:\n            in_x = scale_x * x\n    elif coordinate_transformation_mode == \"pytorch_half_pixel\":\n        in_x = te.if_then_else(target_width > 1, (x + 0.5) * scale_x - 0.5, 0.0)\n    elif coordinate_transformation_mode == \"tf_half_pixel_for_nn\":\n        in_x = (x + 0.5) * scale_x\n    elif coordinate_transformation_mode == \"tf_crop_and_resize\":\n        in_x = te.if_then_else(\n            target_width > 1,\n            start_x * (image_width - 1)\n            + x * (end_x - start_x) * (image_width - 1).astype(\"float\") / (target_width - 1),\n            0.5 * (start_x + end_x) * (image_width - 1),\n        )\n    else:\n        raise ValueError(\n            \"Unsupported coordinate_transformation_mode: {}\".format(coordinate_transformation_mode)\n        )\n    return in_x\n\n\ndef get_closest_index(in_x, rounding_method, boxes, use_int_div=False):\n    \"\"\"get the closest index to a value based on a certain rounding method\"\"\"\n    if use_int_div:\n        closest_x_index = in_x.astype(\"int32\")\n        return closest_x_index\n\n    if rounding_method == \"round\" or boxes is not None:\n        closest_x_index = te.round(in_x).astype(\"int32\")\n    elif rounding_method == \"round_prefer_floor\":\n        closest_x_index = te.ceil(in_x - 0.5).astype(\"int32\")\n    elif rounding_method == \"round_prefer_ceil\":\n        closest_x_index = te.floor(in_x + 0.5).astype(\"int32\")\n    elif rounding_method == \"floor\":\n        # Add epsilon to floor to prevent gpu rounding errors.\n        epsilon = 1e-5\n        closest_x_index = te.floor(in_x + epsilon).astype(\"int32\")\n    elif rounding_method == \"ceil\":\n        # Subract epsilon from ceil to prevent gpu rounding errors.\n        epsilon = 1e-5\n        closest_x_index = te.ceil(in_x - epsilon).astype(\"int32\")\n    else:\n        raise ValueError(\"Uknown rounding method: {}\".format(rounding_method))\n    return closest_x_index\n\n\ndef _lerp(A, B, t):\n    \"\"\"Perform Linear interpolation in 1D\"\"\"\n    return A * (1.0 - t) + B * t\n\n\ndef _cubic_spline_weights(t, alpha):\n    \"\"\"create cubic spline weights in 1D\"\"\"\n    t2 = t * t\n    t3 = t * t * t\n    w1 = alpha * (t3 - 2 * t2 + t)\n    w2 = (alpha + 2) * t3 - (3 + alpha) * t2 + 1\n    w3 = -(alpha + 2) * t3 + (3 + 2 * alpha) * t2 - alpha * t\n    w4 = -alpha * t3 + alpha * t2\n    return [w1, w2, w3, w4]\n\n\ndef _cubic_kernel(inputs, w):\n    \"\"\"perform cubic interpolation in 1D\"\"\"\n    return sum([a_i * w_i for a_i, w_i in zip(inputs, w)])\n\n\ndef _resize_1d(\n    indices,\n    data,\n    roi,\n    image_width,\n    target_width,\n    boxes=None,\n    box_indices=None,\n    method=None,\n    extrapolation_value=0.0,\n    layout=\"NCW\",\n    coordinate_transformation_mode=\"align_corners\",\n    rounding_method=\"\",\n    alpha=-0.5,\n    exclude_outside=0,\n    out_dtype=None,\n):\n\n    \"\"\"Perform resize operation on the data with selected method and options.\n\n    Parameters\n    ----------\n    indices : tuple\n        The indices of input data\n\n    data : tvm.te.Tensor\n        inputs is a 3-D tensor with shape\n        [batch, channel, in_width]\n        or  [batch, in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 2, and format [start_w, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    image_width : integer\n        Input image width\n\n    target_width : integer\n        The target resized image width\n\n    boxes : tvm.te.Tensor, optional\n        A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies\n        the coordinates of a box.\n\n    box_indices : tvm.te.Tensor, optional\n        A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that\n        the i-th box refers to.\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    layout: string, optional\n        \"NCW\", \"NWC\", or \"NCWc\".\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    alpha: float, optional\n        Bicubic spline coefficient\n\n    exclude_outside: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    Returns\n    -------\n    output : out_dtype\n        The computed result with type out_dtype\n    \"\"\"\n\n    def _cast_output(value, data_dtype=\"float32\", out_dtype=None):\n        if out_dtype:\n            dtype = out_dtype\n        else:\n            dtype = data_dtype\n        return value.astype(dtype)\n\n    n, c, x, cc, inum, ic = get_1d_indices(indices, layout)\n    box_idx = box_indices(n) if box_indices is not None else n\n    if boxes is not None:\n        # TODO(mbrookhart): Find an example of this\n        raise NotImplementedError(\"resize1d with image boxes not yet implemented\")\n    in_x = get_inx(\n        x,\n        image_width,\n        target_width,\n        coordinate_transformation_mode,\n        roi[0],\n        roi[1],\n    )\n\n    if method == \"nearest_neighbor\":\n        if rounding_method == \"\":\n            if coordinate_transformation_mode == \"align_corners\":\n                rounding_method = \"round\"\n            else:\n                rounding_method = \"floor\"\n\n        closest_x_index = get_closest_index(in_x, rounding_method, boxes)\n\n        value = get_1d_pixel(\n            data,\n            layout,\n            image_width,\n            box_idx,\n            c,\n            closest_x_index,\n            cc,\n            inum,\n            ic,\n        )\n    elif method == \"linear\":\n        x_int = te.floor(in_x).astype(\"int32\")\n\n        x_lerp = in_x - x_int\n\n        p = [0 for i in range(2)]\n        for i in range(2):\n            p[i] = get_1d_pixel(\n                data,\n                layout,\n                image_width,\n                box_idx,\n                c,\n                x_int + i,\n                cc,\n                inum,\n                ic,\n            )\n\n        value = _lerp(*p, x_lerp)\n\n    elif method == \"cubic\":\n        xint = te.floor(in_x).astype(\"int32\")\n        xfract = in_x - te.floor(in_x)\n\n        # Get the surrounding values\n        p = [0 for i in range(4)]\n        for i in range(4):\n            p[i] = get_1d_pixel(\n                data,\n                layout,\n                image_width,\n                box_idx,\n                c,\n                xint + i - 1,\n                cc,\n                inum,\n                ic,\n            )\n\n        wx = _cubic_spline_weights(xfract, alpha)\n        if exclude_outside:\n            for i in range(4):\n                wx[i] = te.if_then_else(\n                    te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i]\n                )\n            sum_wx = sum(wx)\n            wx = [w / sum_wx for w in wx]\n        value = _cubic_kernel(p, wx)\n\n    else:\n        raise ValueError(\"Unknown resize method:\", method)\n\n    if coordinate_transformation_mode == \"tf_crop_and_resize\":\n        # use extrapolation_value if in_x is out of boundary\n        value = tvm.tir.if_then_else(\n            in_x < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, value),\n        )\n    return _cast_output(value, data.dtype, out_dtype=out_dtype)\n\n\ndef resize1d(\n    data,\n    roi,\n    size,\n    layout=\"NCW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    bicubic_alpha=-0.5,\n    bicubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n    output_shape=None,\n):\n    \"\"\"Perform resize operation on the data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        inputs is a 3-D tensor with shape\n        [batch, channel in_width]\n        or  [batch in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 2, and format [start_w, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    size: Tuple\n        Output resolution scale to\n\n    layout: string, optional\n        \"NCW\", \"NWC\", or \"NCWc\".\n\n    coordinate_transformation_mode: string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        Refer to the ONNX Resize operator specification for details.\n        Available options are \"half_pixel\", \"align_corners\" and \"asymmetric\".\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method:\n        Method for rounding coordinate locations\n\n    bicubic_alpha: float, optional\n        Bicubic spline coefficient\n\n    bicubic_exclude: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    output_shape: tvm.tir.container.Array, optional\n        Shape to return. If left None will be inferred\n        (If shape is determined dynamically, pass out_dtype.shape as output_shape)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, chananel, in_width*scale]\n        or [batch, in_width*scale, channel]\n        or 5-D with shape [batch, channel-major, in_width*scale, channel-minor]\n    \"\"\"\n    method = method.lower()\n    if layout == \"NWC\":\n        in_n, in_w, in_c = data.shape\n        if output_shape is None:\n            output_shape = [in_n, size[0], in_c]\n    elif layout == \"NCW\":\n        in_n, in_c, in_w = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0]]\n    elif ncw_pack_layout(layout):  # for NCWinic\n        in_n, in_c, in_w, in_inum, in_ic = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0], in_inum, in_ic]\n    elif ncw_xc_layout(layout):  # for NCWxc\n        in_n, in_c, in_w, in_cc = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0], in_cc]\n    else:\n        raise ValueError(\"%s layout is not supported.\" % layout)\n\n    if isinstance(size, tuple):\n        size = list(size)\n\n    for i in range(1):\n        if isinstance(size[i], int):\n            size[i] = tvm.tir.IntImm(\"int32\", size[i])\n\n    def compute_func(*indices):\n        return _resize_1d(\n            indices,\n            data,\n            roi,\n            in_w,\n            size[0],\n            method=method,\n            layout=layout,\n            coordinate_transformation_mode=coordinate_transformation_mode,\n            rounding_method=rounding_method,\n            alpha=bicubic_alpha,\n            exclude_outside=bicubic_exclude,\n            extrapolation_value=extrapolation_value,\n            out_dtype=out_dtype,\n        )\n\n    return te.compute(output_shape, compute_func, name=\"resize\", tag=tag.INJECTIVE)\n\n\ndef _resize_2d(\n    indices,\n    data,\n    roi,\n    image_height,\n    image_width,\n    target_height,\n    target_width,\n    boxes=None,\n    box_indices=None,\n    method=None,\n    extrapolation_value=0.0,\n    layout=\"NCHW\",\n    coordinate_transformation_mode=\"align_corners\",\n    rounding_method=\"\",\n    alpha=-0.5,\n    exclude_outside=0,\n    out_dtype=None,\n):\n\n    \"\"\"Perform resize operation on the data with selected method and options.\n\n    Parameters\n    ----------\n    indices : tuple\n        The indices of input data\n\n    data : tvm.te.Tensor\n        inputs is a 4-D tensor with shape\n        [batch, channel, in_height, in_width]\n        or  [batch, in_height, in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 4, and format [start_h, start_w, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    image_height : integer\n        Input image height\n\n    image_width : integer\n        Input image width\n\n    target_height : integer\n        The target resized image height\n\n    target_width : integer\n        The target resized image width\n\n    boxes : tvm.te.Tensor, optional\n        A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies\n        the coordinates of a box.\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    box_indices : tvm.te.Tensor, optional\n        A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that\n        the i-th box refers to.\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    layout: string, optional\n        \"NCHW\", \"NHWC\", or \"NCHWc\".\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    alpha: float, optional\n        Bicubic spline coefficient\n\n    exclude_outside: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    Returns\n    -------\n    output : out_dtype\n        The computed result with type out_dtype\n    \"\"\"\n\n    def _cast_output(value, data_dtype=\"float32\", out_dtype=None):\n        if out_dtype:\n            dtype = out_dtype\n        else:\n            dtype = data_dtype\n        return value.astype(dtype)\n\n    height_use_int_div = False\n    width_use_int_div = False\n    if method == \"nearest_neighbor\" and coordinate_transformation_mode == \"asymmetric\":\n        height_use_int_div = can_convert_multiply_to_intdiv(image_height, target_height)\n        width_use_int_div = can_convert_multiply_to_intdiv(image_width, target_width)\n\n    n, c, y, x, cc, inum, ic = get_2d_indices(indices, layout)\n    box_idx = box_indices(n) if box_indices is not None else n\n    if boxes is not None:\n        y1, x1 = boxes(n, 0), boxes(n, 1)\n        y2, x2 = boxes(n, 2), boxes(n, 3)\n\n        in_h = (image_height - 1) * (y2 - y1)\n        in_w = (image_width - 1) * (x2 - x1)\n        h_scale = in_h.astype(\"float\") / (target_height - 1)\n        w_scale = in_w.astype(\"float\") / (target_width - 1)\n\n        in_y = y1 * (image_height - 1) + h_scale * y\n        in_x = x1 * (image_width - 1) + w_scale * x\n    else:\n        in_x = get_inx(\n            x,\n            image_width,\n            target_width,\n            coordinate_transformation_mode,\n            roi[1],\n            roi[3],\n            width_use_int_div,\n        )\n        in_y = get_inx(\n            y,\n            image_height,\n            target_height,\n            coordinate_transformation_mode,\n            roi[0],\n            roi[2],\n            height_use_int_div,\n        )\n\n    if method == \"nearest_neighbor\":\n        if rounding_method == \"\":\n            if coordinate_transformation_mode == \"align_corners\":\n                rounding_method = \"round\"\n            else:\n                rounding_method = \"floor\"\n\n        closest_x_index = get_closest_index(in_x, rounding_method, boxes, width_use_int_div)\n        closest_y_index = get_closest_index(in_y, rounding_method, boxes, height_use_int_div)\n\n        value = get_2d_pixel(\n            data,\n            layout,\n            image_height,\n            image_width,\n            box_idx,\n            c,\n            closest_y_index,\n            closest_x_index,\n            cc,\n            inum,\n            ic,\n        )\n    elif method == \"linear\":\n        y_int = te.floor(in_y).astype(\"int32\")\n        x_int = te.floor(in_x).astype(\"int32\")\n\n        y_lerp = in_y - y_int\n        x_lerp = in_x - x_int\n\n        p = [[0 for i in range(2)] for j in range(2)]\n        for j in range(2):\n            for i in range(2):\n                p[j][i] = get_2d_pixel(\n                    data,\n                    layout,\n                    image_height,\n                    image_width,\n                    box_idx,\n                    c,\n                    y_int + j,\n                    x_int + i,\n                    cc,\n                    inum,\n                    ic,\n                )\n\n        top = _lerp(*p[0], x_lerp)\n        bottom = _lerp(*p[1], x_lerp)\n        value = _lerp(top, bottom, y_lerp)\n\n    elif method == \"cubic\":\n        xint = te.floor(in_x).astype(\"int32\")\n        xfract = in_x - te.floor(in_x)\n\n        yint = te.floor(in_y).astype(\"int32\")\n        yfract = in_y - te.floor(in_y)\n\n        # Get the surrounding values\n        p = [[0 for i in range(4)] for j in range(4)]\n        for j in range(4):\n            for i in range(4):\n                p[j][i] = get_2d_pixel(\n                    data,\n                    layout,\n                    image_height,\n                    image_width,\n                    box_idx,\n                    c,\n                    yint + j - 1,\n                    xint + i - 1,\n                    cc,\n                    inum,\n                    ic,\n                )\n\n        wx = _cubic_spline_weights(xfract, alpha)\n        wy = _cubic_spline_weights(yfract, alpha)\n        if exclude_outside:\n            for i in range(4):\n                wx[i] = te.if_then_else(\n                    te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i]\n                )\n                wy[i] = te.if_then_else(\n                    te.any(yint - 1 + i < 0, yint + i > image_height), 0.0, wy[i]\n                )\n            sum_wx = sum(wx)\n            sum_wy = sum(wy)\n            wx = [w / sum_wx for w in wx]\n            wy = [w / sum_wy for w in wy]\n        col0 = _cubic_kernel(p[0], wx)\n        col1 = _cubic_kernel(p[1], wx)\n        col2 = _cubic_kernel(p[2], wx)\n        col3 = _cubic_kernel(p[3], wx)\n        value = _cubic_kernel([col0, col1, col2, col3], wy)\n\n    else:\n        raise ValueError(\"Unknown resize method:\", method)\n\n    if coordinate_transformation_mode == \"tf_crop_and_resize\":\n        out = tvm.tir.if_then_else(\n            in_y < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_y > image_height - 1, extrapolation_value, value),\n        )\n        # use extrapolation_value if in_x is out of boundary\n        value = tvm.tir.if_then_else(\n            in_x < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, out),\n        )\n    return _cast_output(value, data.dtype, out_dtype=out_dtype)\n\n\ndef resize2d(\n    data,\n    roi,\n    size,\n    layout=\"NCHW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    bicubic_alpha=-0.5,\n    bicubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n    output_shape=None,\n):\n    \"\"\"Perform resize operation on the data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        inputs is a 4-D tensor with shape\n        [batch, channel, in_height, in_width]\n        or  [batch, in_height, in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 4, and format [start_h, start_w, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    size: Tuple\n        Output resolution scale to\n\n    layout: string, optional\n        \"NCHW\", \"NHWC\", or \"NCHWc\".\n\n    coordinate_transformation_mode: string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        Refer to the ONNX Resize operator specification for details.\n        Available options are \"half_pixel\", \"align_corners\" and \"asymmetric\".\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method:\n        Method for rounding coordinate locations\n\n    bicubic_alpha: float, optional\n        Bicubic spline coefficient\n\n    bicubic_exclude: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    output_shape: tvm.tir.container.Array, optional\n        Shape to return. If left None will be inferred\n        (If shape is determined dynamically, pass out_dtype.shape as output_shape)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, channel, in_height*scale, in_width*scale]\n        or [batch, in_height*scale, in_width*scale, channel]\n        or 5-D with shape [batch, channel-major, in_height*scale, in_width*scale, channel-minor]\n    \"\"\"\n    method = method.lower()\n    if layout == \"NHWC\":\n        in_n, in_h, in_w, in_c = data.shape\n        if output_shape is None:\n            output_shape = [in_n, size[0], size[1], in_c]\n    elif layout == \"NCHW\":\n        in_n, in_c, in_h, in_w = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0], size[1]]\n    elif nchw_pack_layout(layout):  # for NCHWinic\n        in_n, in_c, in_h, in_w, in_inum, in_ic = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0], size[1], in_inum, in_ic]\n    elif nchw_xc_layout(layout):  # for NCHWxc\n        in_n, in_c, in_h, in_w, in_cc = data.shape\n        if output_shape is None:\n            output_shape = [in_n, in_c, size[0], size[1], in_cc]\n    else:\n        raise ValueError(\"%s layout is not supported.\" % layout)\n\n    if isinstance(size, tuple):\n        size = list(size)\n\n    for i in range(2):\n        if isinstance(size[i], int):\n            size[i] = tvm.tir.IntImm(\"int32\", size[i])\n\n    def compute_func(*indices):\n        return _resize_2d(\n            indices,\n            data,\n            roi,\n            in_h,\n            in_w,\n            size[0],\n            size[1],\n            method=method,\n            layout=layout,\n            coordinate_transformation_mode=coordinate_transformation_mode,\n            rounding_method=rounding_method,\n            alpha=bicubic_alpha,\n            exclude_outside=bicubic_exclude,\n            extrapolation_value=extrapolation_value,\n            out_dtype=out_dtype,\n        )\n\n    return te.compute(output_shape, compute_func, name=\"resize\", tag=tag.INJECTIVE)\n\n\ndef crop_and_resize(\n    data,\n    boxes,\n    box_indices,\n    crop_size,\n    layout=\"NCHW\",\n    method=\"bilinear\",\n    extrapolation_value=None,\n    out_dtype=None,\n):\n    \"\"\"Perform crop and resize operation on the data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        inputs is a 4-D tensor with shape\n        [batch, channel, in_height, in_width]\n        or  [batch, in_height, in_width, channel]\n\n    boxes : tvm.te.Tensor\n        A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies\n        the coordinates of a box.\n\n    box_indices : tvm.te.Tensor\n        A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that\n        the i-th box refers to.\n\n    crop_size : Tuple\n        The target size of each box.\n\n    layout : string, optional\n        \"NCHW\", \"NHWC\"\n\n    method : {\"bilinear\", \"nearest_neighbor\"}\n        Method to be used for resizing.\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    out_dtype : string, optional\n        Type to return. If left None will be same as input type.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [num_boxes, channel, crop_height, crop_width]\n        or [num_boxes, crop_height, crop_width, channel]\n    \"\"\"\n    method = method.lower()\n    target_h = crop_size[0]\n    target_w = crop_size[1]\n    if layout == \"NHWC\":\n        output_shape = [box_indices.shape[0], crop_size[0], crop_size[1], data.shape[3]]\n        image_h = data.shape[1].astype(\"int32\")\n        image_w = data.shape[2].astype(\"int32\")\n    elif layout == \"NCHW\":\n        output_shape = [box_indices.shape[0], data.shape[1], crop_size[0], crop_size[1]]\n        image_h = data.shape[2].astype(\"int32\")\n        image_w = data.shape[3].astype(\"int32\")\n    elif layout.startswith(\"NCHW\"):  # for NCHWxc\n        output_shape = [\n            box_indices.shape[0],\n            data.shape[1],\n            crop_size[0],\n            crop_size[1],\n            data.shape[4],\n        ]\n        image_h = data.shape[2].astype(\"int32\")\n        image_w = data.shape[3].astype(\"int32\")\n    else:\n        raise ValueError(\"%s layout is not supported.\" % layout)\n    if method == \"bilinear\":\n        method = \"linear\"\n\n    def compute_func(*indices):\n        return _resize_2d(\n            indices,\n            data,\n            [0.0] * 4,\n            image_h,\n            image_w,\n            target_h,\n            target_w,\n            boxes,\n            box_indices,\n            method=method,\n            extrapolation_value=extrapolation_value,\n            layout=layout,\n            coordinate_transformation_mode=\"tf_crop_and_resize\",\n            out_dtype=out_dtype,\n        )\n\n    return te.compute(output_shape, compute_func, name=\"crop_and_resize\", tag=tag.INJECTIVE)\n\n\ndef _resize_3d(\n    indices,\n    data,\n    roi,\n    image_depth,\n    image_height,\n    image_width,\n    target_depth,\n    target_height,\n    target_width,\n    boxes=None,\n    box_indices=None,\n    method=None,\n    extrapolation_value=0.0,\n    layout=\"NCHW\",\n    coordinate_transformation_mode=\"align_corners\",\n    rounding_method=\"\",\n    alpha=-0.5,\n    exclude_outside=0,\n    out_dtype=None,\n):\n\n    \"\"\"Perform resize operation on the data with selected method and options.\n\n    Parameters\n    ----------\n    indices : tuple\n        The indices of input data\n\n    data : tvm.te.Tensor\n        inputs is a 4-D tensor with shape\n        [batch, channel, in_height, in_width]\n        or  [batch, in_height, in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 6, and format [start_d, start_h, start_w, end_d, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    image_depth : integer\n        Input image depth\n\n    image_height : integer\n        Input image height\n\n    image_width : integer\n        Input image width\n\n    target_depth : integer\n        The target resized image depth\n\n    target_height : integer\n        The target resized image height\n\n    target_width : integer\n        The target resized image width\n\n    boxes : tvm.te.Tensor, optional\n        A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies\n        the coordinates of a box.\n\n    box_indices : tvm.te.Tensor, optional\n        A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that\n        the i-th box refers to.\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    layout: string, optional\n        \"NCHW\", \"NHWC\", or \"NCHWc\".\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method: string, optional\n        indicates how to find the \"nearest\" pixel in nearest_neighbor method\n        [round, floor, ceil]\n\n    alpha: float, optional\n        Bicubic spline coefficient\n\n    exclude_oiutside: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    Returns\n    -------\n    output : out_dtype\n        The computed result with type out_dtype\n    \"\"\"\n\n    def _cast_output(value, data_dtype=\"float32\", out_dtype=None):\n        if out_dtype:\n            dtype = out_dtype\n        else:\n            dtype = data_dtype\n        return value.astype(dtype)\n\n    n, c, z, y, x, cc = get_3d_indices(indices, layout)\n    box_idx = box_indices(n) if box_indices is not None else n\n    if boxes is not None:\n        # TODO(mbrookhart): Find an example of this\n        raise NotImplementedError(\"resize1d with image boxes not yet implemented\")\n    in_z = get_inx(z, image_depth, target_depth, coordinate_transformation_mode, roi[2], roi[5])\n    in_y = get_inx(y, image_height, target_height, coordinate_transformation_mode, roi[1], roi[4])\n    in_x = get_inx(x, image_width, target_width, coordinate_transformation_mode, roi[0], roi[3])\n\n    if method == \"nearest_neighbor\":\n        if rounding_method == \"\":\n            if coordinate_transformation_mode == \"align_corners\":\n                rounding_method = \"round\"\n            else:\n                rounding_method = \"floor\"\n\n        closest_z_index = get_closest_index(in_z, rounding_method, boxes)\n        closest_y_index = get_closest_index(in_y, rounding_method, boxes)\n        closest_x_index = get_closest_index(in_x, rounding_method, boxes)\n\n        value = get_3d_pixel(\n            data,\n            layout,\n            image_depth,\n            image_height,\n            image_width,\n            box_idx,\n            c,\n            closest_z_index,\n            closest_y_index,\n            closest_x_index,\n            cc,\n        )\n    elif method == \"linear\":\n        z_int = te.floor(in_z).astype(\"int32\")\n        y_int = te.floor(in_y).astype(\"int32\")\n        x_int = te.floor(in_x).astype(\"int32\")\n\n        z_lerp = in_z - z_int\n        y_lerp = in_y - y_int\n        x_lerp = in_x - x_int\n\n        p = [[[0 for i in range(2)] for j in range(2)] for k in range(2)]\n        for k in range(2):\n            for j in range(2):\n                for i in range(2):\n                    p[k][j][i] = get_3d_pixel(\n                        data,\n                        layout,\n                        image_depth,\n                        image_height,\n                        image_width,\n                        box_idx,\n                        c,\n                        z_int + k,\n                        y_int + j,\n                        x_int + i,\n                        cc,\n                    )\n        l = [[0 for i in range(2)] for j in range(2)]\n        for j in range(2):\n            for i in range(2):\n                l[j][i] = _lerp(*p[j][i], x_lerp)\n\n        top = _lerp(*l[0], y_lerp)\n        bottom = _lerp(*l[1], y_lerp)\n        value = _lerp(top, bottom, z_lerp)\n\n    elif method == \"cubic\":\n        zint = te.floor(in_z).astype(\"int32\")\n        zfract = in_z - te.floor(in_z)\n\n        yint = te.floor(in_y).astype(\"int32\")\n        yfract = in_y - te.floor(in_y)\n\n        xint = te.floor(in_x).astype(\"int32\")\n        xfract = in_x - te.floor(in_x)\n\n        # Get the surrounding values\n        p = [[[0 for i in range(4)] for j in range(4)] for k in range(4)]\n        for k in range(4):\n            for j in range(4):\n                for i in range(4):\n                    p[k][j][i] = get_3d_pixel(\n                        data,\n                        layout,\n                        image_depth,\n                        image_height,\n                        image_width,\n                        box_idx,\n                        c,\n                        zint + k - 1,\n                        yint + j - 1,\n                        xint + i - 1,\n                        cc,\n                    )\n\n            wz = _cubic_spline_weights(zfract, alpha)\n            wy = _cubic_spline_weights(yfract, alpha)\n            wx = _cubic_spline_weights(xfract, alpha)\n            if exclude_outside:\n                for i in range(4):\n                    wz[i] = te.if_then_else(\n                        te.any(xint - 1 + i < 0, xint + i > image_height), 0.0, wx[i]\n                    )\n                    wy[i] = te.if_then_else(\n                        te.any(yint - 1 + i < 0, yint + i > image_height), 0.0, wy[i]\n                    )\n                    wx[i] = te.if_then_else(\n                        te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i]\n                    )\n                sum_wz = sum(wz)\n                sum_wy = sum(wy)\n                sum_wx = sum(wx)\n                wz = [w / sum_wz for w in wz]\n                wy = [w / sum_wy for w in wy]\n                wx = [w / sum_wx for w in wx]\n\n            l = [[0 for i in range(4)] for j in range(4)]\n            for j in range(4):\n                for i in range(4):\n                    l[j][i] = _cubic_kernel(p[j][i], wx)\n            col0 = _cubic_kernel(l[0], wy)\n            col1 = _cubic_kernel(l[1], wy)\n            col2 = _cubic_kernel(l[2], wy)\n            col3 = _cubic_kernel(l[3], wy)\n            value = _cubic_kernel([col0, col1, col2, col3], wz)\n\n    else:\n        raise ValueError(\"Unknown resize method:\", method)\n\n    if coordinate_transformation_mode == \"tf_crop_and_resize\":\n        out = tvm.tir.if_then_else(\n            in_z < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_z > image_depth - 1, extrapolation_value, value),\n        )\n        out = tvm.tir.if_then_else(\n            in_y < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_y > image_height - 1, extrapolation_value, value),\n        )\n        # use extrapolation_value if in_x is out of boundary\n        value = tvm.tir.if_then_else(\n            in_x < 0,\n            extrapolation_value,\n            tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, out),\n        )\n    return _cast_output(value, data.dtype, out_dtype=out_dtype)\n\n\ndef resize3d(\n    data,\n    roi,\n    size,\n    layout=\"NCDHW\",\n    method=\"linear\",\n    coordinate_transformation_mode=\"half_pixel\",\n    rounding_method=\"\",\n    bicubic_alpha=-0.5,\n    bicubic_exclude=0,\n    extrapolation_value=0.0,\n    out_dtype=None,\n    output_shape=None,\n):\n    \"\"\"Perform resize operation on the data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        inputs is a 5-D tensor with shape\n        [batch, channel, in_depth, in_height, in_width]\n        or  [batch, in_depth, in_height, in_width, channel]\n\n    roi: Tuple of Float or Expr\n        The region of interest for cropping the input image. Expected to be of\n        size 6, and format [start_d, start_h, start_w, end_d, end_h, end_w].\n        Only used if coordinate_transformation_mode is tf_crop_and_resize.\n\n    size: Tuple\n        Output resolution scale to\n\n    layout: string, optional\n        \"NCDHW\", \"NDHWC\", or \"NCDHWc\".\n\n    method: string, optional\n        method of interpolation (\"nearest\", \"linear\", \"bicubic\")\n\n    coordinate_transformation_mode : string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        [half_pixel, align_corners, asymmetric, pytorch_half_pixel,\n        tf_half_pixel_for_nn, and tf_crop_and_resize].\n\n    rounding_method:\n        Method for rounding coordinate locations\n\n    bicubic_alpha: float, optional\n        Bicubic spline coefficient\n\n    bicubic_exclude: bool, optional:\n        Exclude values outside the image fdor bicubic interpolation\n\n    extrapolation_value: float, optional\n        Value used for extrapolation, when applicable.\n\n    out_dtype: string, optional\n        Type to return. If left None will be same as input type.\n\n    output_shape: tvm.tir.container.Array, optional\n        Shape to return. If left None will be inferred\n        (If shape is determined dynamically, pass out_dtype.shape as output_shape)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, channel, in_depth*scale, in_height*scale, in_width*scale]\n        or [batch, in_depth*scale, in_height*scale, in_width*scale, channel]\n        or 5-D with shape\n        [batch, channel-major, in_depth*scale, in_height*scale, in_width*scale, channel-minor]\n    \"\"\"\n\n    method = method.lower()\n    if layout == \"NDHWC\":\n        in_n, in_d, in_h, in_w, in_c = data.shape\n        output_shape = [in_n, size[0], size[1], size[2], in_c]\n    elif layout == \"NCDHW\":\n        in_n, in_c, in_d, in_h, in_w = data.shape\n        output_shape = [in_n, in_c, size[0], size[1], size[2]]\n    # Otherwise layout must be NCHWxc\n    else:\n        in_n, in_c, in_d, in_h, in_w, in_cc = data.shape\n        output_shape = [in_n, in_c, size[0], size[1], size[2], in_cc]\n\n    if isinstance(size, tuple):\n        size = list(size)\n\n    for i in range(3):\n        if isinstance(size[i], int):\n            size[i] = tvm.tir.IntImm(\"int32\", size[i])\n\n    def compute_func(*indices):\n        return _resize_3d(\n            indices,\n            data,\n            roi,\n            in_d,\n            in_h,\n            in_w,\n            size[0],\n            size[1],\n            size[2],\n            method=method,\n            layout=layout,\n            coordinate_transformation_mode=coordinate_transformation_mode,\n            rounding_method=rounding_method,\n            alpha=bicubic_alpha,\n            exclude_outside=bicubic_exclude,\n            extrapolation_value=extrapolation_value,\n            out_dtype=out_dtype,\n        )\n\n    return te.compute(output_shape, compute_func, name=\"resize\", tag=tag.INJECTIVE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/intel_graphics/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"Intel Gen9 GPU specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .conv2d import *\nfrom . import conv2d_alter_op\nfrom .depthwise_conv2d import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/intel_graphics/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return, too-many-arguments, too-many-locals, too-many-statements, no-member, too-many-branches, too-many-boolean-expressions\n\"\"\"conv2d schedule on Intel Graphics\"\"\"\n\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom .. import nn\nfrom .. import utils\nfrom ..utils import simplify, get_const_tuple, traverse_inline\n\n\ndef _get_default_config(cfg, data, kernel, strides, padding, out_dtype, is_depthwise=False):\n    if is_depthwise:\n        raise RuntimeError(\"Depthwise not supported for intel graphics.\")\n\n    batch_size, in_channel, height, width = get_const_tuple(data.shape)\n    out_channel, _, hkernel, _ = get_const_tuple(kernel.shape)\n    HSTR, _ = strides\n\n    ic_bn = 1\n    oc_bn, oc_bn_upper = 16, 16\n    for i in range(oc_bn_upper, 0, -1):\n        if out_channel % i == 0:\n            oc_bn = i\n            break\n\n    if HSTR == 2:\n        if out_channel + hkernel == 515:\n            block_oh = 4\n            block_ow = 4\n        else:\n            block_oh = 4\n            block_ow = 5\n    elif hkernel == 3:\n        if out_channel == 512:\n            block_oh = 2\n            block_ow = 7\n        else:\n            block_oh = 2\n            block_ow = 14\n    else:\n        block_oh = 1\n        block_ow = 16\n    cfg[\"tile_ic\"] = SplitEntity([in_channel // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([out_channel // oc_bn, oc_bn])\n    cfg[\"block_oh\"] = OtherOptionEntity(block_oh)\n    cfg[\"block_ow\"] = OtherOptionEntity(block_ow)\n\n\ndef _create_schedule_template(cfg, dshape, kshape, strides, padding, dilation):\n    \"\"\"Create schedule configuration from input arguments\"\"\"\n    n, ic, h, w = dshape\n    oc, _, kh, kw = kshape\n\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (kh, kw))\n    sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    oh = (h - kh + pt + pb) // sh + 1\n    ow = (w - kw + pl + pr) // sw + 1\n    ic_bn_upper = 32\n    oc_bn_upper = 64\n    oc_bn_lower = min(oc, 8)\n    ic_bn_candidates, oc_bn_candidates = [], []\n    for i in range(1, ic + 1):\n        if ic % i == 0 and i <= ic_bn_upper:\n            ic_bn_candidates.append(i)\n    if not ic_bn_candidates:\n        ic_bn_candidates.append(1)\n        ic_bn_candidates.append(ic)\n\n    for i in range(1, oc + 1):\n        if oc % i == 0 and oc_bn_lower <= i <= oc_bn_upper:\n            oc_bn_candidates.append(i)\n    if not oc_bn_candidates:\n        oc_bn_candidates.append(1)\n        oc_bn_candidates.append(oc)\n\n    blk_candidates_low_limits = 5\n    blk_oh_list, blk_ow_list = [], []\n    for i, j in zip(range(oh, 0, -1), range(ow, 0, -1)):\n        if i <= 16 and oh % i == 0:\n            blk_oh_list.append(i)\n        if j <= 16 and ow % j == 0:\n            blk_ow_list.append(j)\n\n    if len(blk_oh_list) < blk_candidates_low_limits:\n        for i in range(2, oh):\n            if i not in blk_oh_list:\n                blk_oh_list.append(i)\n                if len(blk_oh_list) >= 5:\n                    break\n\n    if len(blk_ow_list) < blk_candidates_low_limits:\n        for i in range(min(ow - 1, 16), 1, -1):\n            if i not in blk_ow_list:\n                blk_ow_list.append(i)\n                if len(blk_ow_list) >= 5:\n                    break\n\n    # Create schedule config\n    cfg.define_knob(\"tile_ic\", ic_bn_candidates)\n    cfg.define_knob(\"tile_oc\", oc_bn_candidates)\n    cfg.define_knob(\"block_oh\", blk_oh_list)\n    cfg.define_knob(\"block_ow\", blk_ow_list)\n\n\n##### SCHEDULE UTILITIES #####\ndef tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None):\n    \"\"\"tile and bind 3d\"\"\"\n    y_factor = y_factor or z_factor\n    x_factor = x_factor or y_factor\n    zo, zi = s[tensor].split(z, z_factor)\n    yo, yi = s[tensor].split(y, y_factor)\n    xo, xi = s[tensor].split(x, x_factor)\n    s[tensor].reorder(zo, yo, xo, zi, yi, xi)\n\n    thread_z = te.thread_axis((0, z_factor), \"threadIdx.z\")\n    thread_y = te.thread_axis((0, y_factor), \"threadIdx.y\")\n    thread_x = te.thread_axis((0, x_factor), \"threadIdx.x\")\n    s[tensor].bind(zo, te.thread_axis(\"blockIdx.z\"))\n    s[tensor].bind(zi, thread_z)\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, thread_y)\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, thread_x)\n    return xi, thread_z, thread_y, thread_x\n\n\ndef _pack_data(data, kernel, ic_bn, oc_bn):\n    n, _, ih, iw = get_const_tuple(data.shape)\n    oc, ic, kh, kw = get_const_tuple(kernel.shape)\n\n    ic_chunk = ic // ic_bn\n    oc_chunk = oc // oc_bn\n\n    data = te.compute(\n        (n, ic_chunk, ih, iw, ic_bn),\n        lambda bs, c, h, w, vc: data[bs, c * ic_bn + vc, h, w],\n        name=\"data_vec\",\n    )\n\n    kernel = te.compute(\n        (oc_chunk, ic_chunk, kh, kw, ic_bn, oc_bn),\n        lambda occ, icc, k_h, k_w, icb, ocb: kernel[occ * oc_bn + ocb, icc * ic_bn + icb, k_h, k_w],\n        name=\"kernel_vec\",\n    )\n\n    return data, kernel\n\n\n@autotvm.register_topi_compute(\"conv2d_NCHWc.intel_graphics\")\ndef conv2d_NCHWc(\n    cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype=\"float32\"\n):\n    \"\"\"Conv2D operator for Intel Graphics backend.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        5-D with shape [num_filter, in_channel, filter_height, filter_width, nnum_filter_vec]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n\n    layout : str\n        layout of data\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    if len(data.shape) == 5:\n        batch, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n        oc_chunk, _, kernel_height, kernel_width, _, oc_bn = get_const_tuple(kernel.shape)\n        in_channel = ic_chunk * ic_bn\n        num_filter = oc_chunk * oc_bn\n    else:\n        batch, in_channel, ih, iw = get_const_tuple(data.shape)\n        num_filter, _, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n\n    dh, dw = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (kernel_height, kernel_width)\n    )\n    assert (dh, dw) == (1, 1), \"Does not support dilation\"\n    if isinstance(strides, (tuple, list)):\n        stride_h, stride_w = strides\n    else:\n        stride_h, stride_w = strides, strides\n\n    data_shape = (batch, in_channel, ih, iw)\n    kernel_shape = (num_filter, in_channel, kernel_height, kernel_width)\n    _create_schedule_template(cfg, data_shape, kernel_shape, strides, padding, dilation)\n\n    if cfg.is_fallback:\n        _get_default_config(\n            cfg,\n            te.placeholder((batch, in_channel, ih, iw), dtype=data.dtype),\n            te.placeholder(\n                (num_filter, in_channel, kernel_height, kernel_width), dtype=kernel.dtype\n            ),\n            strides,\n            padding,\n            out_dtype,\n        )\n\n    ic_bn = cfg[\"tile_ic\"].val if hasattr(cfg[\"tile_ic\"], \"val\") else cfg[\"tile_ic\"].size[-1]\n    oc_bn = cfg[\"tile_oc\"].val if hasattr(cfg[\"tile_oc\"], \"val\") else cfg[\"tile_oc\"].size[-1]\n\n    # Pack data if raw 4-D data is provided.\n    if len(data.shape) == 4:\n        data, kernel = _pack_data(data, kernel, ic_bn, oc_bn)\n\n    out_channel = num_filter\n    out_height = simplify((ih - kernel_height + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((iw - kernel_width + pad_left + pad_right) // stride_w + 1)\n    oshape = (batch, out_channel // oc_bn, out_height, out_width, oc_bn)\n\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_height), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_width), name=\"rx\")\n\n    block_h = cfg[\"block_oh\"].val\n    block_w = cfg[\"block_ow\"].val\n\n    c_h = out_height\n    c_w = out_width\n\n    if out_height % block_h != 0:\n        c_h = (out_height // block_h + 1) * block_h\n\n    if out_width % block_w != 0:\n        c_w = (out_width // block_w + 1) * block_w\n\n    cshape = (batch, out_channel // oc_bn, c_h, c_w, oc_bn)\n\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down + c_h - out_height, pad_right + c_w - out_width, 0]\n    DOPAD = (\n        pad_top != 0\n        or pad_left != 0\n        or pad_down + c_h - out_height != 0\n        or pad_right + c_w - out_width != 0\n    )\n    DOUNPACK = c_h - out_height != 0 or c_w - out_width != 0\n    if DOPAD:\n        temp = nn.pad(data, pad_before, pad_after, name=\"pad_temp\")\n    else:\n        temp = data\n\n    conv = te.compute(\n        cshape,\n        lambda nn, ff, yy, xx, ff_v: te.sum(\n            temp[nn, rc // ic_bn, yy * stride_h + ry, xx * stride_w + rx, rc % ic_bn].astype(\n                out_dtype\n            )\n            * kernel[ff, rc // ic_bn, ry, rx, rc % ic_bn, ff_v].astype(out_dtype),\n            axis=[rc, ry, rx],\n        ),\n        tag=\"conv2d_NCHWc\",\n        name=\"conv2d_NCHWc\",\n    )\n\n    if DOUNPACK:\n        output = te.compute(\n            oshape,\n            lambda nn, ff, yy, xx, ff_v: conv[nn][ff][yy][xx][ff_v],\n            name=\"output_unpack\",\n            tag=\"conv2d_NCHWc_unpack\",\n        )\n    else:\n        output = conv\n\n    return output\n\n\n@autotvm.register_topi_schedule(\"conv2d_NCHWc.intel_graphics\")\ndef schedule_conv2d_NCHWc(cfg, outs):\n    \"\"\"Schedule for conv2d_nchw for Intel Graphics\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_nchw\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d_nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"inline all one-to-one-mapping operators except the last stage (output)\"\"\"\n        if \"conv2d_NCHWc\" in op.tag:\n            _schedule_cl_spatialpack_NCHWc(cfg, s, op)\n\n    traverse_inline(s, outs[0].op, _callback)\n\n    return s\n\n\ndef _schedule_cl_spatialpack_NCHWc(cfg, s, op):\n    output = op.output(0)\n    if op.name == \"conv2d_NCHWc\":\n        temp = op.input_tensors[0]\n        kernel = op.input_tensors[1]\n        temp_W = s.cache_read(temp, \"warp\", [output])\n        conv_L = s.cache_write(output, \"local\")\n        if output.op in s.outputs:\n            conv = output\n        else:\n            s[output].compute_inline()\n            conv = s.outputs[0]\n        SCHEDULE_OUTPUT = False\n    else:  # conv2d_NCHWc_unpack\n        conv = op.input_tensors[0]\n        temp = s[conv].op.input_tensors[0]\n        kernel = s[conv].op.input_tensors[1]\n        temp_W = s.cache_read(temp, \"warp\", [conv])\n        conv_L = s.cache_write(conv, \"local\")\n        SCHEDULE_OUTPUT = True\n    kernel_L = s.cache_read(kernel, \"local\", [conv_L])\n\n    if temp.name == \"pad_temp\":\n        data = temp.op.input_tensors[0]\n        # TODO(@Laurawly): Do we need to schedule pad op here?\n    else:\n        data = temp\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        # only in autotuning, input data of conv2d_NCHWc will be 4-D.\n        # skip this part during tuning to make records accurate.\n        # this part will be folded during Relay fold_constant pass.\n        s[data].pragma(s[data].op.axis[0], \"debug_skip_region\")\n        s[kernel].pragma(s[kernel].op.axis[0], \"debug_skip_region\")\n    elif isinstance(kernel.op, tvm.te.ComputeOp) and kernel.name == \"kernel_vec\":\n        # data and kernel are not pre-computed, schedule layout transform here.\n        # TODO(@Laurawly): Add schedule for data and kernel pack\n        pass\n\n    OUTPUT_BLOCK_HEIGHT = cfg[\"block_oh\"].val\n    OUTPUT_BLOCK_WIDTH = cfg[\"block_ow\"].val\n\n    # schedule conv\n    z_factor = 1\n    y_factor = 1\n    x_factor = 16\n    thread_z = te.thread_axis((0, z_factor), \"threadIdx.z\")\n    thread_y = te.thread_axis((0, y_factor), \"threadIdx.y\")\n    thread_x = te.thread_axis((0, x_factor), \"threadIdx.x\")\n    _, co, oh, ow, vc = s[conv].op.axis\n    ooh, ioh = s[conv].split(oh, factor=OUTPUT_BLOCK_HEIGHT)\n    oow, iow = s[conv].split(ow, factor=OUTPUT_BLOCK_WIDTH)\n    s[conv].reorder(_, co, ooh, oow, vc, ioh, iow)\n    coo, coi = s[conv].split(co, nparts=1)\n    ooho, oohi = s[conv].split(ooh, factor=z_factor)\n    oowo, oowi = s[conv].split(oow, factor=y_factor)\n    vco, vci = s[conv].split(vc, factor=x_factor)\n    s[conv].reorder(_, coo, vco, ooho, oowo, coi, oohi, oowi, vci, ioh, iow)\n    s[conv].bind(oohi, thread_z)\n    s[conv].bind(oowi, thread_y)\n    s[conv].bind(vci, thread_x)\n    s[conv].bind(ooho, te.thread_axis(\"blockIdx.z\"))\n    s[conv].bind(oowo, te.thread_axis(\"blockIdx.y\"))\n    s[conv].bind(coi, te.thread_axis(\"blockIdx.x\"))\n\n    # schedule conv_L\n    s[conv_L].compute_at(s[conv], vci)\n    i, oc, h, w, vc = s[conv_L].op.axis\n    rc, ry, rx = s[conv_L].op.reduce_axis\n    s[conv_L].reorder(i, oc, rc, ry, rx, vc, h, w)\n    s[temp_W].compute_at(s[conv_L], rc)\n    if kernel.shape[3].value != 7:\n        s[conv_L].unroll(ry)\n        s[conv_L].unroll(rx)\n\n    # schedule temp\n    if temp.op.name == \"pad_temp\":\n        _, ci, h, w, vci = s[temp].op.axis\n        tile_and_bind3d(s, temp, ci, h, w, 1, 16, 16)\n\n    # schedule temp_W\n    _, ci, h, w, vci = s[temp_W].op.axis\n    zo, zi = s[temp_W].split(vci, 1)\n    yo, yi = s[temp_W].split(h, 1)\n    xo, xi = s[temp_W].split(w, 16)\n    s[temp_W].reorder(zo, yo, xo, zi, yi, xi)\n    s[temp_W].bind(zi, thread_z)\n    s[temp_W].bind(yi, thread_y)\n    s[temp_W].bind(xi, thread_x)\n    s[temp_W].storage_align(s[temp_W].op.axis[2], 16, 0)\n\n    # schedule kernel_L\n    if OUTPUT_BLOCK_HEIGHT == 2 and OUTPUT_BLOCK_WIDTH == 14:\n        s[kernel_L].compute_at(s[conv_L], ry)\n    else:\n        s[kernel_L].compute_at(s[conv_L], rx)\n\n    # schedule output\n    if SCHEDULE_OUTPUT:\n        if output.op in s.outputs:\n            out = output\n        else:\n            s[output].compute_inline()\n            out = s.outputs[0]\n\n        _, co, h, w, vc = s[out].op.axis\n        tile_and_bind3d(s, out, w, h, vc, 4, 8, 8)\n\n\ndef conv2d_nchw(data, kernel, stride, padding, dilation, out_dtype=\"float32\"):\n    \"\"\"Conv2D operator for Intel Graphics backend.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    assert data.shape[0].value == 1, \"only support batch size=1 convolution on intel gpu\"\n    assert data.dtype == kernel.dtype, \"Do not support inputs with different data types now.\"\n\n    return _decl_cl_spatialpack(data, kernel, stride, padding, out_dtype)\n\n\ndef schedule_conv2d_nchw(outs):\n    \"\"\"Schedule for conv2d_nchw for Intel Graphics\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv2d_nchw\n        in the format of an array of tensors.\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d_nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"inline all one-to-one-mapping operators except the last stage (output)\"\"\"\n        if \"conv2d\" in op.tag:\n            _schedule_cl_spatialpack(s, op)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _decl_cl_spatialpack(data, kernel, stride, padding, out_dtype=\"float16\"):\n    batch, in_channel, in_height, in_width = [utils.get_const_int(x) for x in data.shape]\n    num_filter, channel, kernel_h, kernel_w = [utils.get_const_int(x) for x in kernel.shape]\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(padding, (kernel_h, kernel_w))\n\n    if isinstance(stride, (tuple, list)):\n        stride_h, stride_w = stride\n    else:\n        stride_h, stride_w = stride, stride\n\n    out_channel = num_filter\n    out_height = simplify((in_height - kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - kernel_w + pad_left + pad_right) // stride_w + 1)\n    oshape = (batch, out_channel, out_height, out_width)\n\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    if stride_h == 2:\n        if num_filter + kernel_h == 515:\n            block_h = 4\n            block_w = 4\n        else:\n            block_h = 4\n            block_w = 5\n    elif kernel_h == 3:\n        if num_filter == 512:\n            block_h = 2\n            block_w = 7\n        else:\n            block_h = 2\n            block_w = 14\n    elif kernel_h == 7 and padding == 3 and stride == 1:\n        block_h = 3\n        block_w = 4\n    else:\n        block_h = 1\n        block_w = 16\n    attrs = {\"block_h\": block_h, \"block_w\": block_w}\n    c_h = out_height\n    c_w = out_width\n\n    if out_height % block_h != 0:\n        c_h = (out_height // block_h + 1) * block_h\n\n    if out_width % block_w != 0:\n        c_w = (out_width // block_w + 1) * block_w\n\n    pad_before = [0, 0, pad_top, pad_left]\n    pad_after = [0, 0, pad_down + c_h - block_h, pad_right + c_w - block_w]\n    temp = nn.pad(data, pad_before, pad_after, name=\"pad_temp\")\n\n    nv = 16\n    if num_filter % nv != 0:\n        num_filter = (num_filter // nv + 1) * nv\n        out_channel = num_filter\n\n    cshape = (batch, out_channel // nv, c_h, c_w, nv)\n    kvshape = (num_filter // nv, channel, kernel_h, kernel_w, nv)\n\n    kernel_vec = te.compute(\n        kvshape, lambda co, ci, kh, kw, vc: kernel[co * nv + vc][ci][kh][kw], name=\"kernel_vec\"\n    )\n\n    conv = te.compute(\n        cshape,\n        lambda nn, ff, yy, xx, vc: te.sum(\n            temp[nn, rc, yy * stride_h + ry, xx * stride_w + rx].astype(out_dtype)\n            * kernel_vec[ff, rc, ry, rx, vc].astype(out_dtype),\n            axis=[rc, ry, rx],\n        ),\n        name=\"conv\",\n        attrs=attrs,\n    )\n\n    output = te.compute(\n        oshape,\n        lambda nn, ff, yy, xx: conv[nn][ff // nv][yy][xx][ff % nv],\n        name=\"output_unpack\",\n        tag=\"conv2d\",\n    )\n\n    return output\n\n\ndef _schedule_cl_spatialpack(s, op):\n    output = op.output(0)\n    _, _, out_height, out_width = [utils.get_const_int(x) for x in output.shape]\n\n    conv = op.input_tensors[0]\n    temp = s[conv].op.input_tensors[0]\n    kernel_vec = s[conv].op.input_tensors[1]\n    kernel = s[kernel_vec].op.input_tensors[0]\n    temp_W = s.cache_read(temp, \"shared\", [conv])\n    conv_L = s.cache_write(conv, \"local\")\n\n    kernel_L = s.cache_read(kernel_vec, \"local\", [conv_L])\n    _, in_channel, temp_h, temp_w = [utils.get_const_int(x) for x in temp.shape]\n\n    attrs = s[conv].op.attrs\n    OUTPUT_BLOCK_HEIGHT = attrs[\"block_h\"]\n    OUTPUT_BLOCK_WIDTH = attrs[\"block_w\"]\n\n    # schedule conv\n    z_factor = 1\n    y_factor = 1\n    x_factor = 16\n    thread_z = te.thread_axis((0, z_factor), \"threadIdx.z\")\n    thread_y = te.thread_axis((0, y_factor), \"threadIdx.y\")\n    thread_x = te.thread_axis((0, x_factor), \"threadIdx.x\")\n    _, co, oh, ow, vc = s[conv].op.axis\n    ooh, ioh = s[conv].split(oh, factor=OUTPUT_BLOCK_HEIGHT)\n    oow, iow = s[conv].split(ow, factor=OUTPUT_BLOCK_WIDTH)\n    s[conv].reorder(_, co, ooh, oow, vc, ioh, iow)\n    coo, coi = s[conv].split(co, nparts=1)\n    ooho, oohi = s[conv].split(ooh, factor=z_factor)\n    oowo, oowi = s[conv].split(oow, factor=y_factor)\n    vco, vci = s[conv].split(vc, factor=x_factor)\n    s[conv].reorder(_, coo, vco, ooho, oowo, coi, oohi, oowi, vci, ioh, iow)\n    s[conv].bind(oohi, thread_z)\n    s[conv].bind(oowi, thread_y)\n    s[conv].bind(vci, thread_x)\n    s[conv].bind(ooho, te.thread_axis(\"blockIdx.z\"))\n    s[conv].bind(oowo, te.thread_axis(\"blockIdx.y\"))\n    s[conv].bind(coi, te.thread_axis(\"blockIdx.x\"))\n\n    # schedule conv_L\n    s[conv_L].compute_at(s[conv], vci)\n    i, oc, h, w, vc = s[conv_L].op.axis\n    rc, ry, rx = s[conv_L].op.reduce_axis\n    s[conv_L].reorder(i, oc, rc, ry, rx, vc, h, w)\n    s[temp_W].compute_at(s[conv_L], rc)\n    if kernel.shape[3].value != 7:\n        s[conv_L].unroll(ry)\n        s[conv_L].unroll(rx)\n\n    # schedule temp\n    _, ci, h, w = s[temp].op.axis\n    tile_and_bind3d(s, temp, ci, h, w, 1, 16, 16)\n\n    # schedule temp_W\n    _, ci, h, w = s[temp_W].op.axis\n    zo, zi = s[temp_W].split(ci, 1)\n    yo, yi = s[temp_W].split(h, 1)\n    xo, xi = s[temp_W].split(w, 16)\n    s[temp_W].reorder(zo, yo, xo, zi, yi, xi)\n    s[temp_W].bind(zi, thread_z)\n    s[temp_W].bind(yi, thread_y)\n    s[temp_W].bind(xi, thread_x)\n    s[temp_W].storage_align(s[temp_W].op.axis[2], 16, 0)\n\n    s[kernel_vec].compute_inline()\n\n    # schedule kernel_L\n    if OUTPUT_BLOCK_HEIGHT == 2 and OUTPUT_BLOCK_WIDTH == 14:\n        s[kernel_L].compute_at(s[conv_L], ry)\n    else:\n        s[kernel_L].compute_at(s[conv_L], rx)\n\n    # schedule output\n    if output.op in s.outputs:\n        out = output\n    else:\n        s[output].compute_inline()\n        out = s.outputs[0]\n\n    _, co, h, w = s[out].op.axis\n    tile_and_bind3d(s, out, w, h, co, 4, 8, 8)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/intel_graphics/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D alter op and legalize functions for x86\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\n\nfrom ..utils import get_const_tuple\nfrom ..nn import conv2d_alter_layout, conv2d_infer_layout\nfrom .conv2d import _get_default_config\n\n\n@conv2d_alter_layout.register([\"intel_graphics\"])\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n    if isinstance(dispatch_ctx, autotvm.task.ApplyGraphBest):\n        cfg = dispatch_ctx.query(target, None)\n        workload = cfg.workload\n    else:\n        _, outs = relay.backend.te_compiler.select_implementation(\n            relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n        )\n        workload = autotvm.task.get_workload(outs)\n        if workload is None:\n            # The best implementation is not an AutoTVM template,\n            # we then assume it's not necessary to alter this op.\n            return None\n        cfg = dispatch_ctx.query(target, workload)\n\n    topi_tmpl = workload[0]\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    padding = attrs.get_int_tuple(\"padding\")\n    strides = attrs.get_int_tuple(\"strides\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data_tensor, kernel_tensor = tinfos\n    data_dtype = data_tensor.dtype\n    kernel_dtype = kernel_tensor.dtype\n    out_dtype = out_type.dtype\n\n    if topi_tmpl == \"conv2d_NCHWc.intel_graphics\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        if cfg.is_fallback:\n            _get_default_config(cfg, data_tensor, kernel_tensor, strides, padding, out_dtype, False)\n        batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n        out_channel, _, kh, kw = get_const_tuple(kernel_tensor.shape)\n        ic_bn = cfg[\"tile_ic\"].val if hasattr(cfg[\"tile_ic\"], \"val\") else cfg[\"tile_ic\"].size[-1]\n        oc_bn = cfg[\"tile_oc\"].val if hasattr(cfg[\"tile_oc\"], \"val\") else cfg[\"tile_oc\"].size[-1]\n\n        # update new attrs\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        # (oc, ic, h, w) -> (OC, IC, h, w, ic, oc)\n        new_attrs[\"kernel_layout\"] = \"OIHW%di%do\" % (ic_bn, oc_bn)\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        # Store altered operator's config\n        new_data = te.placeholder(\n            (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n        )\n        new_kernel = te.placeholder(\n            (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn, oc_bn), dtype=kernel_dtype\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_kernel,\n                strides,\n                padding,\n                dilation,\n                new_attrs[\"data_layout\"],\n                new_attrs[\"out_layout\"],\n                out_dtype,\n            ],\n            \"conv2d_NCHWc.intel_graphics\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    return None\n\n\n@conv2d_infer_layout.register(\"intel_graphics\")\ndef _conv2d_infer_layout(workload, cfg):\n    _, data, kernel, strides, padding, dilation, layout, dtype = workload\n    batch_size, in_channel, in_height, in_width = data[1]\n    out_channel, _, k_height, k_width = kernel[1]\n    out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1\n    out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1\n    tile_ic, tile_oc = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    in_shape = (batch_size, in_channel // tile_ic, in_height, in_width, tile_ic)\n    in_layout = \"NCHW%dc\" % tile_ic\n    out_shape = (batch_size, out_channel // tile_oc, out_height, out_width, tile_oc)\n    out_layout = \"NCHW%dc\" % tile_oc\n    return ((in_shape, in_layout),), ((out_shape, out_layout),)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/intel_graphics/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Schedule for depthwise_conv2d with auto fusion\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..utils import traverse_inline\nfrom .. import nn\nfrom ..nn.depthwise_conv2d import depthwise_conv2d_infer_layout\n\n# register original implementation of depthwise_conv2d_nchw since we don't need to change this part\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw.intel_graphics\")\ndef depthwise_conv2d_nchw(_, data, kernel, strides, padding, dilation, out_dtype):\n    return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw.intel_graphics\")\ndef schedule_depthwise_conv2d_nchw(cfg, outs):\n    \"\"\"Schedule for depthwise_conv2d nchw forward.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of depthwise_conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"depthwise_conv2d_nchw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n\n            ##### space definition begin #####\n            n, f, y, x = s[conv].op.axis\n            cfg.define_split(\"tile_f\", f, num_outputs=4)\n            cfg.define_split(\"tile_y\", y, num_outputs=4)\n            cfg.define_split(\"tile_x\", x, num_outputs=4)\n            cfg.define_knob(\"auto_unroll_max_step\", [0, 256, 1500])\n\n            target = tvm.target.Target.current()\n            if target.kind.name in [\"nvptx\", \"rocm\"]:\n                cfg.define_knob(\"unroll_explicit\", [1])\n            else:\n                cfg.define_knob(\"unroll_explicit\", [0, 1])\n\n            # fallback support\n            if cfg.is_fallback:\n                ref_log = autotvm.tophub.load_reference_log(\n                    target.kind.name, target.model, \"depthwise_conv2d_nchw.intel_graphics\"\n                )\n                cfg.fallback_with_reference_log(ref_log)\n                cfg[\"unroll_explicit\"].val = 0\n            ##### space definition end #####\n\n            s[pad_data].compute_inline()\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            if conv.op in s.outputs:\n                output = conv\n                OL = s.cache_write(conv, \"local\")\n            else:\n                output = s.outputs[0].output(0)\n                s[conv].set_scope(\"local\")\n                OL = conv\n\n            # create cache stage\n            AA = s.cache_read(pad_data, \"shared\", [OL])\n            WW = s.cache_read(kernel, \"shared\", [OL])\n            AL = s.cache_read(AA, \"local\", [OL])\n            WL = s.cache_read(WW, \"local\", [OL])\n\n            # tile and bind spatial axes\n            n, f, y, x = s[output].op.axis\n            bf, vf, tf, fi = cfg[\"tile_f\"].apply(s, output, f)\n            by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n            bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            kernel_scope, n = s[output].split(n, nparts=1)\n            bf = s[output].fuse(n, bf)\n            s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n            s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(vf, te.thread_axis(\"vthread\"))\n            s[output].bind(vy, te.thread_axis(\"vthread\"))\n            s[output].bind(vx, te.thread_axis(\"vthread\"))\n            s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n            s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n            s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi)\n            s[OL].compute_at(s[output], tx)\n\n            # cooperative fetching\n            s[AA].compute_at(s[output], bx)\n            s[WW].compute_at(s[output], bx)\n            s[AL].compute_at(s[output], tx)\n            s[WL].compute_at(s[output], tx)\n\n            for load in [AA, WW]:\n                fused = s[load].fuse(*list(s[load].op.axis))\n                fused, tx = s[load].split(fused, cfg[\"tile_x\"].size[2])\n                fused, ty = s[load].split(fused, cfg[\"tile_y\"].size[2])\n                fused, tz = s[load].split(fused, cfg[\"tile_f\"].size[2])\n                s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n                s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n                s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n            s[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@depthwise_conv2d_infer_layout.register(\"intel_graphics\")\ndef _depthwise_conv2d_infer_layout(workload, _):\n    \"\"\"Infer input/output shapes and layouts from a workload and cfg.\n\n    Parameters\n    ----------\n    workload : tuple\n        conv2d workload\n\n    cfg : tuple\n        tvm.autotvm config\n\n    Returns\n    -------\n    Output : [tuple of tuple and str, tuple of tuple and str]\n        Input shapes and layouts, and output shapes and layouts\n    \"\"\"\n    _, data, kernel, strides, padding, _, _ = workload\n    batch_size, in_channel, in_height, in_width = data[1]\n    filter_channel, channel_multiplier, k_height, k_width = kernel[1]\n    out_channel = filter_channel * channel_multiplier\n    out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1\n    out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1\n    in_shape = (batch_size, in_channel, in_height, in_width)\n    out_shape = (batch_size, out_channel, out_height, out_width)\n    in_layout = out_layout = \"NCHW\"\n    return ((in_shape, in_layout),), ((out_shape, out_layout),)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/mali/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"ARM Mali GPU specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .conv2d import *\nfrom .depthwise_conv2d import *\nfrom .dense import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/mali/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return\n\"\"\"conv2d schedule on ARM Mali GPU\"\"\"\nimport logging\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import get_factors\n\nfrom ..utils import traverse_inline, get_const_int, get_const_tuple\nfrom .. import nn\nfrom ..nn.winograd_util import winograd_transform_matrices\nfrom ..nn.conv2d import conv2d_winograd_nhwc, _conv2d_winograd_nhwc_impl\n\n# reuse some compute declarations from ARM CPU\nfrom ..arm_cpu.conv2d_spatial_pack import conv2d_spatial_pack_nchw\nfrom ..arm_cpu.conv2d_spatial_pack import conv2d_spatial_pack_nhwc\n\nlogger = logging.getLogger(\"topi\")\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_spatial_pack.mali\")\ndef conv2d_nchw_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"TOPI compute callback for conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width] or\n        pre-packed 5-D with shape [num_filter_chunk, in_channel, filter_height,\n        filter_width, num_filter_block]\n\n    strides : list of two ints\n        [stride_height, stride_width]\n\n    padding : list of two ints\n        [pad_height, pad_width]\n\n    dilation : list of two ints\n        [dilation_height, dilation_width]\n\n    out_dtype: str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return conv2d_spatial_pack_nchw(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=3\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_spatial_pack.mali\")\ndef schedule_conv2d_nchw_spatial_pack(cfg, outs):\n    \"\"\"TOPI schedule callback for conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The configuration of this template\n    outs: Array of Tensor\n        The computation graph description of convolution2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        # schedule conv2d\n        if \"spatial_conv2d_output\" in op.tag:\n            _schedule_spatial_pack(cfg, s, op, layout=\"NCHW\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_spatial_pack.mali\")\ndef conv2d_nhwc_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with NHWC layout\"\"\"\n    return conv2d_spatial_pack_nhwc(\n        cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=3\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_spatial_pack.mali\")\ndef schedule_conv2d_nhwc_spatial_pack(cfg, outs):\n    \"\"\"Create schedule for conv2d_nhwc\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        # schedule conv2d\n        if \"spatial_conv_output_NHWC\" in op.tag:\n            _schedule_spatial_pack(cfg, s, op, layout=\"NHWC\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_spatial_pack(cfg, s, op, layout):\n    \"\"\"schedule the spatial packing for conv2d\"\"\"\n\n    assert layout in (\"NCHW\", \"NHWC\")\n\n    output = op.output(0)\n    conv = op.input_tensors[0]\n    data_vec = conv.op.input_tensors[0]\n    data_pad = data_vec.op.input_tensors[0]\n    s[data_pad].compute_inline()\n    kernel_vec = conv.op.input_tensors[1]\n    if kernel_vec.op.name == \"kernel_vec\":\n        kernel = kernel_vec.op.input_tensors[0]\n    else:\n        kernel = kernel_vec\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n    data = s[data_vec].op.input_tensors[0]\n\n    max_unroll = 16\n    vec_size = [1, 2, 4, 8, 16]\n    # get tunable parameters (they are defined in compute)\n    _, TC, VC = cfg[\"tile_co\"].size\n    _, TH, VH = cfg[\"tile_oh\"].size\n    _, TW, VW = cfg[\"tile_ow\"].size\n\n    # schedule padding\n    if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n        data_pad = data\n        s[data_pad].compute_inline()\n\n    # schedule data packing\n    if layout == \"NCHW\":\n        if isinstance(data_vec.op, tvm.te.ComputeOp) and data_vec.op.name == \"data_vec_undilated\":\n            _, h, w, ci, _, _, vh, vw = s[data_vec].op.axis\n        else:\n            _, h, w, ci, vh, vw = s[data_vec].op.axis\n        z, y, x, unroll1, unroll2 = h, w, ci, vh, vw\n    else:\n        if isinstance(data_vec.op, tvm.te.ComputeOp) and data_vec.op.name == \"data_vec_undilated\":\n            _, oho, owo, _, _, ic, ohi, owi = s[data_vec].op.axis\n        else:\n            _, oho, owo, ohi, owi, ic = s[data_vec].op.axis\n        z, y, x, unroll1, unroll2 = oho, owo, ohi, ic, owi\n    tile_and_bind3d(s, data_vec, z, y, x, 1)\n    if unroll1.dom.extent.value < max_unroll:\n        s[data_vec].unroll(unroll1)\n    if unroll2.dom.extent.value < max_unroll:\n        s[data_vec].unroll(unroll2)\n\n    if isinstance(kernel_vec.op, tvm.te.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            max_threads = tvm.target.Target.current(allow_none=False).max_num_threads\n            ax1, ax2, ax3, ax4, ax5 = s[kernel_vec].op.axis\n            fused = s[kernel_vec].fuse(ax1, ax2, ax3, ax4, ax5)\n            fused, vec = s[kernel_vec].split(fused, VC)\n            bb, tt = s[kernel_vec].split(fused, max_threads)\n            s[kernel_vec].bind(bb, te.thread_axis(\"blockIdx.x\"))\n            s[kernel_vec].bind(tt, te.thread_axis(\"threadIdx.x\"))\n            if VC in vec_size:\n                s[kernel_vec].vectorize(vec)\n\n    # schedule convolution\n    ic, kh, kw = s[conv].op.reduce_axis\n    if layout == \"NCHW\":\n        kh_dim, kw_dim = kernel_vec.shape[2], kernel_vec.shape[3]\n    else:\n        kh_dim, kw_dim = kernel_vec.shape[0], kernel_vec.shape[1]\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv,\n        [kh, kw],\n        axis_lens=[get_const_int(kh_dim), get_const_int(kw_dim)],\n        max_unroll=max_unroll,\n    )\n\n    if layout == \"NCHW\":\n        n, c, h, w, vh, vw, vc = s[conv].op.axis\n        cfg[\"reorder_0\"].apply(s, conv, [n, c, h, w, ic, kh, kw, vh, vw, vc])\n        tile_and_bind3d(s, conv, c, h, w, TC, TH, TW)\n        unroll_vec_axes = [vh, vw, vc]\n        axis_lens = [VH, VW, VC]\n    else:\n        n, oho, owo, oco, ohi, owi, oci = s[conv].op.axis\n        cfg[\"reorder_conv\"].apply(s, conv, [n, oho, owo, oco, kh, kw, ic, ohi, owi, oci])\n        tile_and_bind3d(s, conv, oho, owo, oco, TH, TW, TC)\n        unroll_vec_axes = [ohi, owi, oci]\n        axis_lens = [VH, VW, VC]\n\n    cfg[\"ann_spatial\"].apply(\n        s,\n        conv,\n        unroll_vec_axes,\n        axis_lens,\n        max_unroll=max_unroll,\n        vec_size=vec_size,\n        cfg=cfg,\n    )\n\n    # schedule output\n    if output.op not in s.outputs:  # has bias\n        s[output].compute_inline()\n        output = s.outputs[0]\n    if layout == \"NCHW\":\n        _, co, oh, ow = s[output].op.axis\n        tile_and_bind3d(s, output, co, oh, ow, TC, TH, TW)\n    else:\n        _, oh, ow, co = s[output].op.axis\n        tile_and_bind3d(s, output, oh, ow, co, TH, TW, TC)\n\n    return s\n\n\n##### WINOGRAD TEMPLATE #####\ndef _pick_tile_size(data, kernel, layout=\"NCHW\"):\n    if layout == \"NCHW\":\n        N, CI, H, W = get_const_tuple(data.shape)\n    else:\n        assert layout == \"NHWC\"\n        N, H, W, CI = get_const_tuple(data.shape)\n\n    if H % 4 == 0:\n        return 4\n    else:\n        return 2\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_winograd.mali\")\ndef conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    tile_size = _pick_tile_size(data, kernel)\n    return _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size)\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_winograd.mali\")\ndef schedule_conv2d_nchw_winograd(cfg, outs):\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"winograd_conv2d_output\" in op.tag:\n            _schedule_winograd(cfg, s, op)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size):\n    N, CI, IH, IW = get_const_tuple(data.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    if len(kernel.shape) == 4:\n        if dilation_h != 1 or dilation_w != 1:\n            kernel = nn.dilate(kernel, (1, 1, dilation_h, dilation_w))\n        pre_computed = False\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n    else:\n        assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n        pre_computed = True\n        H_CAT, W_CAT, CO, CI, VC = get_const_tuple(kernel.shape)\n        CO *= VC\n        KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1\n    HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW))\n\n    assert KH == 3 and KW == 3 and HSTR == 1 and WSTR == 1\n    data_pad = nn.pad(data, (0, 0, pt, pl), (0, 0, pb, pr), name=\"data_pad\")\n\n    r = KW\n    m = tile_size\n    alpha = m + r - 1\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    H = (IH + pt + pb - 3) // HSTR + 1\n    W = (IW + pl + pr - 3) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n\n    ##### space definition begin #####\n    tile_bna_candidates = [1, 2, 4, 8, 16]\n    factors = get_factors(CO)\n    cfg.define_knob(\"tile_bna\", [x for x in tile_bna_candidates if x in factors])\n    cfg.define_knob(\"tile_bnb\", [1, 2, 4, 8, 16])\n    cfg.define_split(\"tile_t1\", CI, num_outputs=2, max_factor=128)\n    cfg.define_split(\"tile_t2\", CO, num_outputs=2, max_factor=128)\n    cfg.define_split(\"c_unroll\", CI, num_outputs=2, max_factor=8)\n    cfg.define_knob(\"yt\", [1, 2, 4, 8, 16, 32])\n    ##### space definition end #####\n\n    if cfg.is_fallback:\n        cfg[\"tile_bnb\"].val = 4\n        cfg[\"tile_bna\"].val = 4\n        while CO % cfg[\"tile_bna\"].val != 0:\n            cfg[\"tile_bna\"].val //= 2\n        cfg[\"yt\"].val = 8\n        cfg.fallback_split(\"tile_t1\", [-1, 128])\n        cfg.fallback_split(\"tile_t2\", [-1, 128])\n        cfg.fallback_split(\"c_unroll\", [-1, 8])\n\n    bna = cfg[\"tile_bna\"].val\n    bnb = cfg[\"tile_bnb\"].val\n\n    P_round = (P + bnb - 1) // bnb * bnb\n    assert CO % bna == 0 and P_round % bnb == 0\n\n    # pack input tile\n    input_tile = te.compute(\n        (CI, P_round // bnb, alpha, alpha, bnb),\n        lambda ci, b, eps, nu, bb: tvm.tir.if_then_else(\n            b * bnb + bb < P,\n            data_pad[(b * bnb + bb) // (nH * nW)][ci][(b * bnb + bb) // nW % nH * m + eps][\n                (b * bnb + bb) % nW * m + nu\n            ],\n            tvm.tir.const(0, data_pad.dtype),\n        ),\n        name=\"d\",\n    )\n\n    if autotvm.GLOBAL_SCOPE.in_tuning:\n        kvshape = (alpha, alpha, CO // bna, CI, bna)\n        U = tvm.te.placeholder(kvshape, kernel.dtype, name=\"U\")\n    else:\n        # transform kernel\n        if pre_computed:\n            U = kernel\n        else:\n            r_kh = te.reduce_axis((0, KH), \"r_kh\")\n            r_kw = te.reduce_axis((0, KW), \"r_kw\")\n            U = te.compute(\n                (alpha, alpha, CO // bna, CI, bna),\n                lambda eps, nu, co, ci, vco: te.sum(\n                    kernel[co * bna + vco][ci][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw],\n                    axis=[r_kh, r_kw],\n                ),\n                name=\"U\",\n            )\n\n    # transform image\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    V = te.compute(\n        (alpha, alpha, P_round // bnb, CI, bnb),\n        lambda eps, nu, p, ci, vp: te.sum(\n            input_tile[ci][p][r_a][r_b][vp] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b]\n        ),\n        name=\"V\",\n    )\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    # batch gemm\n    ci = te.reduce_axis((0, CI), name=\"c\")\n    M = te.compute(\n        (alpha, alpha, CO, P_round),\n        lambda eps, nu, co, p: te.sum(\n            U[eps][nu][idxdiv(co, bna)][ci][idxmod(co, bna)]\n            * V[eps][nu][idxdiv(p, bnb)][ci][idxmod(p, bnb)],\n            axis=ci,\n        ),\n        name=\"M\",\n    )\n\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    Y = te.compute(\n        (CO, P, m, m),\n        lambda co, p, vh, vw: te.sum(M[r_a][r_b][co][p] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]),\n        name=\"Y\",\n    )\n\n    # unpack output\n    output = te.compute(\n        (N, CO, H, W),\n        lambda n, co, h, w: Y[\n            co, n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), idxmod(h, m), idxmod(w, m)\n        ]\n        # The following hack term is used to make the padding in batch gemm (\"M\")\n        # effective, otherwise the padding will be eliminated by bound inference.\n        # Use `tvm.tir.Mul` instead of `*` to avoid issues in const folding.\n        + tvm.tir.Mul(tvm.tir.const(0, out_dtype), M[alpha - 1][alpha - 1][CO - 1][P_round - 1]),\n        name=\"output\",\n        tag=\"winograd_conv2d_output\",\n    )\n\n    # we have to manually assign effective GFLOP for winograd\n    cfg.add_flop(2 * N * CO * H * W * KH * KW * CI)\n    return output\n\n\ndef _schedule_winograd(cfg, s, op):\n    \"\"\"schedule winograd fast convolution F(2x2, 3x3) for conv2d\"\"\"\n    # get ops and tensors\n    output = op.output(0)\n\n    Y = op.input_tensors[0]\n    M, A = s[Y].op.input_tensors\n    U, V = s[M].op.input_tensors\n    d, B = s[V].op.input_tensors\n    data_pad = s[d].op.input_tensors[0]\n\n    # padding\n    s[data_pad].compute_inline()\n\n    # transform kernel\n    if isinstance(U.op, tvm.te.ComputeOp):\n        kernel, G = s[U].op.input_tensors\n        s[G].compute_inline()\n        (\n            eps,\n            nu,\n            co,\n            ci,\n            vco,\n        ) = s[U].op.axis\n        if not autotvm.GLOBAL_SCOPE.in_tuning:\n            r_kh, r_kw = s[U].op.reduce_axis\n            s[U].reorder(co, ci, eps, nu, r_kh, r_kw, vco)\n            _ = [s[U].unroll(x) for x in [eps, nu, r_kh, r_kw]]\n            s[U].vectorize(vco)\n            tile_and_bind(s, U, co, ci, 1, 256)\n\n        # dilation\n        if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n            s[kernel].compute_inline()\n\n    # transform image\n    s[B].compute_inline()\n    VL = s.cache_write(V, \"local\")\n\n    eps, nu, p, ci, vp = s[V].op.axis\n    s[V].reorder(p, ci, eps, nu, vp)\n    for axis in [eps, nu]:\n        s[V].unroll(axis)\n    s[V].vectorize(vp)\n    fused = s[V].fuse(p, ci)\n\n    bb, tt = cfg[\"tile_t1\"].apply(s, V, fused)\n    s[V].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[V].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    eps, nu, p, ci, vp = s[VL].op.axis\n    r_a, r_b = s[VL].op.reduce_axis\n    for axis in [eps, nu, r_a, r_b]:\n        s[VL].unroll(axis)\n    s[VL].vectorize(vp)\n    s[d].compute_at(s[V], tt)\n    s[VL].compute_at(s[V], tt)\n\n    # batch gemm\n    bna = cfg[\"tile_bna\"].val\n    bnb = cfg[\"tile_bnb\"].val\n\n    eps, nu, k, b = s[M].op.axis\n    alpha = eps.dom.extent\n    c = s[M].op.reduce_axis[0]\n    yo, xo, yi, xi = s[M].tile(k, b, bna, bnb)\n    c, c_unroll = cfg[\"c_unroll\"].apply(s, M, c)\n    s[M].reorder(yo, xo, c, c_unroll, yi, xi)\n    s[M].unroll(c_unroll)\n    s[M].unroll(yi)\n    s[M].vectorize(xi)\n    z = s[M].fuse(eps, nu)\n    tile_and_bind3d(s, M, z, yo, xo, 1, cfg[\"yt\"].val, 1)\n\n    # inverse transform\n    s[A].compute_inline()\n    k, b, vh, vw = s[Y].op.axis\n    r_a, r_b = s[Y].op.reduce_axis\n    for axis in [vh, vw, r_a, r_b]:\n        s[Y].unroll(axis)\n\n    # schedule output and fusion\n    if output.op not in s.outputs:\n        s[output].compute_inline()\n        output = s.outputs[0]\n\n    n, co, h, w = s[output].op.axis\n    m = alpha - 3 + 1\n    h, w, hi, wi = s[output].tile(h, w, m, m)\n    s[output].unroll(hi)\n    s[output].unroll(wi)\n    fused = s[output].fuse(n, co, h, w)\n    bb, tt = cfg[\"tile_t2\"].apply(s, output, fused)\n    s[output].bind(bb, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tt, te.thread_axis(\"threadIdx.x\"))\n\n    s[Y].compute_at(s[output], tt)\n\n\n##### REGISTER ALTER OP LAYOUT #####\n@nn.conv2d_alter_layout.register([\"mali\"])\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    strides = attrs.get_int_tuple(\"strides\")\n    padding = attrs.get_int_tuple(\"padding\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data, kernel = tinfos\n    out_dtype = out_type.dtype\n\n    impl, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n    if workload is None:\n        # The best implementation is not an AutoTVM template.\n        # It may be from the auto-scheduler\n        if impl.name.find(\"winograd\") != -1:\n            if dilation != (1, 1):\n                logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n                return None\n\n            assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n            N, H, W, CI = get_const_tuple(data.shape)\n            KH, KW, _, CO = get_const_tuple(kernel.shape)\n\n            # Pre-compute weight transformation in winograd\n            tile_size = _pick_tile_size(tinfos[0], tinfos[1], layout=\"NHWC\")\n\n            # HWIO -> OIHW\n            kernel_transform = relay.transpose(inputs[1], axes=[3, 2, 0, 1])\n            # alpha, alpha, CO, CI\n            weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n                kernel_transform, tile_size=tile_size\n            )\n            new_attrs[\"tile_size\"] = tile_size\n            new_attrs[\"channels\"] = CO\n            return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                inputs[0], weight, **new_attrs\n            )\n\n        return None\n    cfg = dispatch_ctx.query(target, workload)\n    if cfg.is_fallback:  # if is fallback, clear query cache and return None\n        autotvm.task.clear_fallback_cache(target, workload)\n        return None\n\n    topi_tmpl = workload[0]\n    idxd = tvm.tir.indexdiv\n\n    if topi_tmpl == \"conv2d_nchw_spatial_pack.mali\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        VC = cfg[\"tile_co\"].size[-1]\n\n        new_attrs[\"kernel_layout\"] = \"OIHW%do\" % VC\n\n        new_data = data\n        new_kernel = te.placeholder((idxd(CO, VC), CI, KH, KW, VC), dtype=kernel.dtype)\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_spatial_pack.mali\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.conv2d(*inputs, **new_attrs)\n    elif topi_tmpl == \"conv2d_nchw_winograd.mali\":\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        N, CI, H, W = get_const_tuple(data.shape)\n        CO, _, KH, KW = get_const_tuple(kernel.shape)\n        tile_size = _pick_tile_size(data, kernel)\n        VC = cfg[\"tile_bna\"].val\n\n        weight_expr = inputs[1]\n        weight_expr = relay.nn.contrib_conv2d_winograd_weight_transform(\n            weight_expr, tile_size=tile_size\n        )\n        weight_expr = relay.reshape(\n            weight_expr, newshape=(KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), VC, CI)\n        )\n        weight_expr = relay.transpose(weight_expr, axes=[0, 1, 2, 4, 3])\n\n        new_attrs[\"tile_size\"] = tile_size\n\n        new_data = data\n        new_kernel = te.placeholder(\n            (KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), CI, VC), kernel.dtype\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [new_data, new_kernel, strides, padding, dilation, out_dtype],\n            \"conv2d_nchw_winograd.mali\",\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n            inputs[0], weight_expr, **new_attrs\n        )\n    else:\n        return None\n\n\n@conv2d_winograd_nhwc.register([\"mali\"])\ndef conv2d_winograd_nhwc_mali(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    pre_computed=False,\n    auto_scheduler_rewritten_layout=\"\",\n):\n    \"\"\"Conv2D Winograd in NHWC layout.\n    This is a clean version to be used by the auto-scheduler for mali.\n    \"\"\"\n    tile_size = _pick_tile_size(data, weight, layout=\"NHWC\")\n    return _conv2d_winograd_nhwc_impl(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        tile_size,\n        pre_computed,\n        auto_scheduler_rewritten_layout,\n    )\n\n\n##### SCHECULE UTILITIES #####\ndef tile_and_bind(s, tensor, y, x, y_factor, x_factor=None):\n    \"\"\"tile and bind to GPU threads\"\"\"\n    x_factor = x_factor or y_factor\n    yo, xo, yi, xi = s[tensor].tile(y, x, y_factor, x_factor)\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n    return yo, xo, yi, xi\n\n\ndef tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None):\n    \"\"\"tile and bind 3d\"\"\"\n    y_factor = y_factor or z_factor\n    x_factor = x_factor or y_factor\n    zo, zi = s[tensor].split(z, z_factor)\n    yo, yi = s[tensor].split(y, y_factor)\n    xo, xi = s[tensor].split(x, x_factor)\n    s[tensor].bind(zo, te.thread_axis(\"blockIdx.z\"))\n    s[tensor].bind(zi, te.thread_axis(\"threadIdx.z\"))\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[tensor].reorder(zo, yo, xo, zi, yi, xi)\n    return zo, yo, xo, zi, yi, xi\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/mali/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable\n\"\"\"dense schedule on ARM Mali GPU\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline\n\n\n@autotvm.register_topi_compute(\"dense.mali\")\ndef dense(_, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator on Mali\"\"\"\n    return nn.dense(data, weight, bias, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"dense.mali\")\ndef schedule_dense(cfg, outs):\n    \"\"\"Schedule for dense operator.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config entity for this template\n    outs: Array of Tensor\n        The computation graph description of dense\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for dense.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"dense\":\n            vec_size = [1, 2, 4, 8, 16]\n            max_unroll = 32\n\n            dense_out = op.output(0)\n            output = outs[0]\n\n            y, x = s[output].op.axis\n            c = s[dense_out].op.reduce_axis[0]\n\n            ##### space definition begin #####\n            cfg.define_split(\"tile_y\", y, num_outputs=3)\n            cfg.define_split(\"tile_x\", x, num_outputs=3)\n            cfg.define_split(\"c_unroll\", c, num_outputs=2, max_factor=64)\n\n            # fallback support\n            if cfg.is_fallback:\n                ref_log = autotvm.tophub.load_reference_log(\"mali\", \"rk3399\", \"dense.mali\")\n                cfg.fallback_with_reference_log(ref_log)\n            ##### space definition end #####\n\n            if dense_out.op in s.outputs:\n                dense_out = s.cache_write(output, \"local\")\n\n            by, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n            bx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n            s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n            s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n            s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n            s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n            if cfg[\"tile_y\"].size[-1] < max_unroll:\n                s[output].unroll(yi)\n            if cfg[\"tile_x\"].size[-1] in vec_size:\n                s[output].vectorize(xi)\n            s[dense_out].compute_at(s[output], tx)\n\n            k = s[dense_out].op.reduce_axis[0]\n            y, x = s[dense_out].op.axis\n            k, k_unroll = cfg[\"c_unroll\"].apply(s, dense_out, k)\n            s[dense_out].reorder(k, k_unroll, y, x)\n            s[dense_out].unroll(k_unroll)\n            if cfg[\"tile_y\"].size[-1] < max_unroll:\n                s[dense_out].unroll(y)\n            if cfg[\"tile_x\"].size[-1] in vec_size:\n                s[dense_out].vectorize(x)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef fuse_and_bind(s, tensor, axis=None, num_thread=None):\n    \"\"\"fuse all the axis and bind to GPU threads\"\"\"\n    # TODO(@comaniac): figure out where this function is used.\n    axis = axis or s[tensor].op.axis\n    fused = s[tensor].fuse(*axis)\n    bx, tx = s[tensor].split(fused, num_thread)\n    s[tensor].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    return bx, tx\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/mali/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"depthwise_conv2d schedule on ARM Mali GPU\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\n\nfrom .. import nn\nfrom ..utils import traverse_inline\n\n# register original implementation of depthwise_conv2d_nchw since we don't need to change this part\n@autotvm.register_topi_compute(\"depthwise_conv2d_nchw.mali\")\ndef depthwise_conv2d_nchw(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype)\n\n\n# register customized schedule for Mali.\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nchw.mali\")\ndef schedule_depthwise_conv2d_nchw(cfg, outs):\n    \"\"\"Schedule depthwise conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The configuration of this template\n    outs: Array of Tensor\n        The computation graph description of depthwise convolution2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"traverse to find op to schedule\"\"\"\n        # schedule depthwise_conv2d\n        if op.tag == \"depthwise_conv2d_nchw\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n            _schedule(cfg, s, pad_data, kernel, conv, \"NCHW\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n# register original implementation of depthwise_conv2d_nhwc since we don't need to change this part\n@autotvm.register_topi_compute(\"depthwise_conv2d_nhwc.mali\")\ndef depthwise_conv2d_nhwc(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    return nn.depthwise_conv2d_nhwc(data, kernel, strides, padding, dilation, out_dtype)\n\n\n# register customized schedule for Mali.\n@autotvm.register_topi_schedule(\"depthwise_conv2d_nhwc.mali\")\ndef schedule_depthwise_conv2d_nhwc(cfg, outs):\n    \"\"\"Schedule depthwise conv2d\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The configuration of this template\n    outs: Array of Tensor\n        The computation graph description of depthwise convolution2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for depthwise_conv2d nchw.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"traverse to find op to schedule\"\"\"\n        # schedule depthwise_conv2d\n        if op.tag == \"depthwise_conv2d_nhwc\":\n            pad_data = op.input_tensors[0]\n            kernel = op.input_tensors[1]\n            conv = op.output(0)\n            _schedule(cfg, s, pad_data, kernel, conv, \"NHWC\")\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule(cfg, s, pad_data, kernel, conv, layout):\n    \"\"\"schedule depthwise_conv2d\"\"\"\n    assert layout in (\"NCHW\", \"NHWC\")\n\n    max_unroll = 16\n    vec_size = [1, 2, 4, 8, 16]\n\n    ##### space definition begin #####\n    if layout == \"NCHW\":\n        n, c, h, w = s[conv].op.axis\n    else:\n        n, h, w, c = s[conv].op.axis\n\n    bc, tc, ci = cfg.define_split(\"tile_c\", c, num_outputs=3)\n    bh, th, hi = cfg.define_split(\"tile_y\", h, num_outputs=3)\n    bw, tw, wi = cfg.define_split(\"tile_x\", w, num_outputs=3)\n    cfg.define_annotate(\"ann_spatial\", [ci, hi, wi], policy=\"try_unroll_vec\")\n\n    # fallback support\n    if cfg.is_fallback:\n        if layout == \"NCHW\":\n            ref_log = autotvm.tophub.load_reference_log(\n                \"mali\", \"rk3399\", \"depthwise_conv2d_nchw.mali\"\n            )\n            cfg.fallback_with_reference_log(ref_log)\n        else:\n            cfg.fallback_split(\"tile_c\", [-1, 4, 2])\n            cfg.fallback_split(\"tile_y\", [-1, 4, 2])\n            cfg.fallback_split(\"tile_x\", [-1, 4, 2])\n    ###### space definition end ######\n\n    # schedule padding\n    if layout == \"NCHW\":\n        n, c, h, w = s[pad_data].op.axis\n        z, y, x = c, h, w\n        z_factor, y_factor, x_factor = cfg[\"tile_c\"].size[1], 1, 1\n    else:\n        n, h, w, c = s[pad_data].op.axis\n        z, y, x = h, w, c\n        z_factor, y_factor, x_factor = 1, 1, cfg[\"tile_c\"].size[1]\n    tile_and_bind3d(s, pad_data, z, y, x, z_factor, y_factor, x_factor)\n\n    # schedule dilation\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n\n    # schedule conv\n    if conv.op not in s.outputs:\n        s[conv].set_scope(\"local\")\n        OL = conv\n        output = s.outputs[0].output(0)\n    else:\n        OL = s.cache_write(conv, \"local\")\n        output = conv\n\n    if layout == \"NCHW\":\n        n, c, h, w = s[output].op.axis\n    else:\n        n, h, w, c = s[output].op.axis\n\n    bc, tc, ci = cfg[\"tile_c\"].apply(s, output, c)\n    bh, th, hi = cfg[\"tile_y\"].apply(s, output, h)\n    bw, tw, wi = cfg[\"tile_x\"].apply(s, output, w)\n\n    if layout == \"NCHW\":\n        bz, tz, by, ty, bx, tx = bc, tc, bh, th, bw, tw\n    else:\n        bz, tz, by, ty, bx, tx = bh, th, bw, tw, bc, tc\n\n    bz = s[output].fuse(n, bz)\n    s[output].bind(bz, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    di, dj = s[OL].op.reduce_axis\n    s[OL].unroll(di)\n    s[OL].unroll(dj)\n\n    s[OL].compute_at(s[output], tx)\n\n    if layout == \"NCHW\":\n        n, ci, hi, wi = s[OL].op.axis\n    else:\n        n, hi, wi, ci = s[OL].op.axis\n\n    cfg[\"ann_spatial\"].apply(\n        s,\n        OL,\n        [ci, hi, wi],\n        axis_lens=[cfg[\"tile_c\"].size[2], cfg[\"tile_y\"].size[2], cfg[\"tile_x\"].size[2]],\n        max_unroll=max_unroll,\n        vec_size=vec_size,\n        cfg=cfg,\n    )\n\n\ndef tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None):\n    \"\"\"tile and bind 3d\"\"\"\n    y_factor = y_factor or z_factor\n    x_factor = x_factor or y_factor\n    zo, zi = s[tensor].split(z, z_factor)\n    yo, yi = s[tensor].split(y, y_factor)\n    xo, xi = s[tensor].split(x, x_factor)\n    s[tensor].bind(zo, te.thread_axis(\"blockIdx.z\"))\n    s[tensor].bind(zi, te.thread_axis(\"threadIdx.z\"))\n    s[tensor].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[tensor].bind(yi, te.thread_axis(\"threadIdx.y\"))\n    s[tensor].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[tensor].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    return zo, zi, yo, yi, xo, xi\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Elementwise operators\"\"\"\n# pylint: disable=redefined-builtin,unused-argument\nimport tvm\nfrom tvm import te\nfrom . import tag\nfrom . import cpp\nfrom .utils import get_const_tuple\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef identity(x):\n    \"\"\"Take identity of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    # pylint: disable=unnecessary-lambda\n    return te.compute(x.shape, lambda *i: x(*i))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef negative(x):\n    \"\"\"Take negation of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    # pylint: disable=unnecessary-lambda\n    return te.compute(x.shape, lambda *i: -x(*i))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef exp(x):\n    \"\"\"Take exponential of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.exp(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef erf(x):\n    \"\"\"Take gauss error function of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.erf(x(*i)))\n\n\n@tvm.target.generic_func\ndef erf_legalize(attrs, inputs, types):\n    \"\"\"Legalizes ERF op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr.\n    \"\"\"\n    # Note changed by default.\n    return None\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef tanh(x):\n    \"\"\"Take hyperbolic tanh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.tanh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef tan(x):\n    \"\"\"Take tan of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.tan(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef cos(x):\n    \"\"\"Take cos of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.cos(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef cosh(x):\n    \"\"\"Take cosh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.cosh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef sin(x):\n    \"\"\"Take sin of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.sin(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef sinh(x):\n    \"\"\"Take sinh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.sinh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef acos(x):\n    \"\"\"Take arc cos of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.acos(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef acosh(x):\n    \"\"\"Take arc cosh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.acosh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef asin(x):\n    \"\"\"Take arc sin of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.asin(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef asinh(x):\n    \"\"\"Take arc sinh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.asinh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef atan(x):\n    \"\"\"Take atan of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.atan(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef atanh(x):\n    \"\"\"Take atanh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.atanh(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef floor(x):\n    \"\"\"Take floor of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.floor(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef ceil(x):\n    \"\"\"Take ceil of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.ceil(x(*i)))\n\n\ndef sign(x):\n    \"\"\"Returns -1, 0, 1 based on sign of x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.sign(x)\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef trunc(x):\n    \"\"\"Take truncated value of the input of x, element-wise.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.trunc(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef abs(x):\n    \"\"\"Take absolute value of the input of x, element-wise.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.abs(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef isnan(x):\n    \"\"\"Check if value of x is NaN, element-wise.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.isnan(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef isfinite(x):\n    \"\"\"Check if value of x is finite, element-wise.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.isfinite(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef isinf(x):\n    \"\"\"Check if value of x is infinite, element-wise.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.isinf(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef round(x):\n    \"\"\"Round elements of x to nearest integer.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.round(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef log(x):\n    \"\"\"Take logarithm of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.log(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef log2(x):\n    \"\"\"Take logarithm to the base 2 of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.log2(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef log10(x):\n    \"\"\"Take logarithm to the base 10 of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.log10(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef sqrt(x):\n    \"\"\"Take square root of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.sqrt(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef rsqrt(x):\n    \"\"\"Take inverse square root of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.rsqrt(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef sigmoid(x):\n    \"\"\"Take sigmoid tanh of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: te.sigmoid(x(*i)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef left_shift(x, n):\n    \"\"\"Take n bits left shift of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n    n : int\n        Number of bits.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: x(*i) << n)\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef right_shift(x, n):\n    \"\"\"Take n bits right shift of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n    n : int\n        Number of bits.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: x(*i) >> n)\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef clip(x, a_min, a_max):\n    \"\"\"Clip (limit) the values in an array. Given an interval, values\n    outside the interval are clipped to the interval edges.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n    a_min : int or float\n        Minimum value.\n    a_max : int or float\n        Maximum value.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n\n    def _compute(*indices):\n        value = x(*indices)\n        const_min = tvm.tir.const(a_min, value.dtype)\n        const_max = tvm.tir.const(a_max, value.dtype)\n        return tvm.te.max(tvm.te.min(value, const_max), const_min)\n\n    return te.compute(x.shape, _compute)\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef fixed_point_multiply(x, multiplier, shift):\n    \"\"\"Fixed point multiplication between data and a fixed point\n    constant expressed as multiplier * 2^(-shift), where multiplier\n    is a Q-number with 31 fractional bits\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor or Expr\n        Input argument.\n    multiplier : int\n        Multiplier of a fixed floating point number described as multiplier*2^(-shift).\n    shift : int\n        Shift of a fixed floating point number described as multiplier*2^(-shift).\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n\n    def _compute(*indices):\n        value = x(*indices)\n        return tvm.tir.q_multiply_shift(\n            value,\n            tvm.tir.const(multiplier, \"int32\"),\n            tvm.tir.const(31, \"int32\"),\n            tvm.tir.const(shift, \"int32\"),\n        )\n\n    return te.compute(x.shape, _compute)\n\n\n@tvm.te.tag_scope(tag=tag.BROADCAST)\ndef fixed_point_multiply_per_axis(\n    x: te.Tensor,\n    y: te.Tensor,\n    lshift: te.Tensor,\n    rshift: te.Tensor,\n    is_lshift_required: int,\n    is_rshift_required: int,\n    axes,\n):\n    \"\"\"Fixed point multiplication between data and a fixed point constant expressed as\n    multiplier * 2^(-shift), where multiplier is a Q-number with 31 fractional bits\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n    y : tvm.te.Tensor\n        Multiplier of a fixed floating point number described as multiplier*2^(-shift).\n    lshift : tvm.te.Tensor\n        Left shifts of a fixed floating point number described as multiplier*2^(-shift).\n    rshift : tvm.te.Tensor\n        Right shifts of a fixed floating point number described as multiplier*2^(-shift).\n    is_lshift_required : int\n        Whether we need to do left shift or not.\n    is_rshift_required : int\n        Whether we need to do right shift or not.\n\n    Returns\n    -------\n    z : tvm.te.Tensor\n        The result.\n    \"\"\"\n\n    def _compute(*indices):\n        elements = []\n        for element in get_const_tuple(axes):\n            elements += [indices[element]]\n        param_indices = tuple(elements)\n\n        value = x(*indices)\n        m = y(*param_indices)\n        l_shift = lshift(*param_indices)\n        r_shift = rshift(*param_indices)\n        return tvm.tir.q_multiply_shift_per_axis(\n            value,\n            m,\n            l_shift,\n            r_shift,\n            tvm.tir.const(31, \"int32\"),\n            tvm.tir.const(is_lshift_required, \"bool\"),\n            tvm.tir.const(is_rshift_required, \"bool\"),\n        )\n\n    return te.compute(x.shape, _compute)\n\n\ndef cast(x, dtype, span=None):\n    \"\"\"Cast input to specified data type.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor or Expr\n        Input argument.\n\n    dtype : str\n        Data type.\n\n    span : Optional[Span]\n        The location of the cast in the source.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    if isinstance(x, te.tensor.Tensor):\n        return te.compute(x.shape, lambda *i: x(*i).astype(dtype), tag=tag.ELEMWISE)\n    # pylint: disable=import-outside-toplevel\n    from tvm.tir import _ffi_api\n\n    return _ffi_api._cast(dtype, x, span)\n\n\ndef reinterpret(x, dtype):\n    \"\"\"Reinterpret input to specified data type.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    dtype : str\n        Data type.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.reinterpret(x, dtype)\n\n\ndef fast_exp(x):\n    \"\"\"Take exponential of input x using fast_exp implementation\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.fast_exp(x, x.dtype, tag.ELEMWISE)\n\n\ndef fast_tanh(x):\n    \"\"\"Take hyperbolic tangent of input x using fast_tanh implementation\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.fast_tanh(x, x.dtype, tag.ELEMWISE)\n\n\ndef fast_erf(x):\n    \"\"\"Take gauss error function of input x using fast_erf implementation.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.fast_erf(x, x.dtype, tag.ELEMWISE)\n\n\ndef ceil_log2(x):\n    \"\"\"Compute integer ceil log2 with a special code path for vulkan\n    SPIR-V does not support log2 on fp64. Instead, we compute integer ceil_log2 via clz\n    intrinsic when the target is vulkan.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    if not isinstance(x, tvm.tir.PrimExpr):\n        x = tvm.tir.const(x)\n\n    if \"float\" in x.dtype:\n        return tvm.tir.ceil(tvm.tir.log2(x))\n\n    if \"vulkan\" in tvm.target.Target.current().kind.name:\n        clz = tvm.tir.clz(x)\n        bits = int(x.dtype[-2:])\n        res = tvm.tir.if_then_else(x & (x - 1) == 0, bits - clz - 1, bits - clz)\n\n        if res.dtype != x.dtype:\n            return cast(res, x.dtype)\n\n        return res\n\n    return cast(tvm.tir.ceil(tvm.tir.log2(cast(x, \"float64\"))), x.dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Neural network operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .conv1d import *\nfrom .conv2d import *\nfrom .conv3d import *\nfrom .correlation import *\nfrom .deformable_conv2d import *\nfrom .depthwise_conv2d import *\nfrom .elemwise import *\nfrom .dilate import *\nfrom .flatten import *\nfrom .dense import *\nfrom .mapping import *\nfrom .pooling import *\nfrom .softmax import *\nfrom .conv3d_transpose import *\nfrom .conv2d_transpose import *\nfrom .conv1d_transpose import *\nfrom .bnn import *\nfrom .qnn import *\nfrom .upsampling import *\nfrom .layer_norm import layer_norm\nfrom .local_response_norm import *\nfrom .bitserial_conv2d import *\nfrom .bitserial_dense import *\nfrom .batch_matmul import *\nfrom .batch_norm import *\nfrom .sparse import *\nfrom .pad import *\nfrom .fifo_buffer import *\nfrom .depth_to_space import *\nfrom .space_to_depth import *\nfrom .space_to_batch_nd import *\nfrom .batch_to_space_nd import *\nfrom .loss import *\nfrom .lstm import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Batch matrix multiplication\"\"\"\n# pylint: disable=invalid-name\nimport logging\n\nimport tvm\nfrom tvm import auto_scheduler, te\n\nfrom ..utils import get_const_tuple\n\nlogger = logging.getLogger(\"topi\")\n\n\ndef batch_matmul(\n    tensor_a,\n    tensor_b,\n    oshape=None,\n    out_dtype=None,\n    transpose_a=False,\n    transpose_b=True,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Compute batch matrix multiplication of `tensor_a` and `tensor_b`.\n\n    Both `tensor_a` and `tensor_b` can be transposed. For legacy reason, we use NT format\n    (transpose_a=False, transpose_b=True) by default.\n\n    Parameters\n    ----------\n    tensor_a : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    tensor_b : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    oshape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    auto_scheduler_rewritten_layout: Optional[str] = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the tensor\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    assert len(tensor_a.shape) == 3, \"tensor_a only support 3-dim\"\n    if transpose_a:\n        XB, XK, XI = get_const_tuple(tensor_a.shape)\n    else:\n        XB, XI, XK = get_const_tuple(tensor_a.shape)\n    if auto_scheduler_rewritten_layout:\n        # Infer shape for the rewritten layout\n        YB, YK, YJ = auto_scheduler.get_shape_from_rewritten_layout(\n            auto_scheduler_rewritten_layout, [\"b\", \"k\", \"j\"]\n        )\n        auto_scheduler.remove_index_check(tensor_b)\n    elif meta_schedule_original_shape:\n        auto_scheduler.rewrite_tensor_shape(tensor_b, meta_schedule_original_shape)\n        if transpose_b:\n            YB, YJ, YK = get_const_tuple(tensor_b.shape)\n        else:\n            YB, YK, YJ = get_const_tuple(tensor_b.shape)\n    else:\n        assert len(tensor_b.shape) == 3, \"tensor_b only support 3-dim\"\n        if transpose_b:\n            YB, YJ, YK = get_const_tuple(tensor_b.shape)\n        else:\n            YB, YK, YJ = get_const_tuple(tensor_b.shape)\n\n    assert XK == YK or isinstance(YK, tvm.tir.expr.Var), \"shapes of x and y are inconsistent\"\n    k = te.reduce_axis((0, XK), name=\"k\")\n    if oshape is None:\n        assert XB == YB or XB == 1 or YB == 1, \"batch dimension doesn't match\"\n        batch = (\n            tvm.tir.expr.SizeVar(\"batch\", \"int32\")\n            if isinstance(XB, tvm.tir.expr.Var) or isinstance(YB, tvm.tir.expr.Var)\n            else te.max(XB, YB)\n        )\n        oshape = (batch, XI, YJ)\n    if out_dtype is None:\n        out_dtype = tensor_a.dtype\n        if tensor_a.dtype != tensor_b.dtype:\n            logger.warning(\n                \"tensor_a has different data type with tensor_b: %s, %s\",\n                tensor_a.dtype,\n                tensor_b.dtype,\n            )\n\n    if (transpose_a, transpose_b) == (True, True):\n        compute_lambda = lambda b, i, j: te.sum(\n            tensor_a[b if XB != 1 else 0, k, i].astype(out_dtype)\n            * tensor_b[b if YB != 1 else 0, j, k].astype(out_dtype),\n            axis=k,\n        )\n        compute_name = \"T_batch_matmul_TT\"\n    elif (transpose_a, transpose_b) == (True, False):\n        compute_lambda = lambda b, i, j: te.sum(\n            tensor_a[b if XB != 1 else 0, k, i].astype(out_dtype)\n            * tensor_b[b if YB != 1 else 0, k, j].astype(out_dtype),\n            axis=k,\n        )\n        compute_name = \"T_batch_matmul_TN\"\n    elif (transpose_a, transpose_b) == (False, True):\n        compute_lambda = lambda b, i, j: te.sum(\n            tensor_a[b if XB != 1 else 0, i, k].astype(out_dtype)\n            * tensor_b[b if YB != 1 else 0, j, k].astype(out_dtype),\n            axis=k,\n        )\n        compute_name = \"T_batch_matmul_NT\"\n    else:  # (transpose_a, transpose_b) == (False, False):\n        compute_lambda = lambda b, i, j: te.sum(\n            tensor_a[b if XB != 1 else 0, i, k].astype(out_dtype)\n            * tensor_b[b if YB != 1 else 0, k, j].astype(out_dtype),\n            axis=k,\n        )\n        compute_name = \"T_batch_matmul_NN\"\n\n    output = te.compute(\n        oshape,\n        compute_lambda,\n        name=compute_name,\n        tag=\"batch_matmul\",\n        attrs={\"layout_free_placeholders\": [tensor_b]},\n    )\n    if auto_scheduler_rewritten_layout:\n        output = auto_scheduler.rewrite_compute_body(output, auto_scheduler_rewritten_layout)\n\n    return output\n\n\n@tvm.target.generic_func\ndef batch_matmul_legalize(attrs, inputs, types):\n    \"\"\"Legalizes batch_matmul op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current batch_matmul\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # not to change by default\n    # pylint: disable=unused-argument\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/batch_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Batch normalization.\"\"\"\nimport typing\n\nfrom tvm import te\nfrom tvm import topi\n\n\ndef batch_norm(\n    data: te.Tensor,\n    gamma: te.Tensor,\n    beta: te.Tensor,\n    moving_mean: te.Tensor,\n    moving_var: te.Tensor,\n    axis: typing.Optional[int] = None,\n    epsilon: typing.Optional[float] = None,\n    center: typing.Optional[bool] = None,\n    scale: typing.Optional[bool] = None,\n) -> typing.List[te.Tensor]:\n    \"\"\"Batch normalization layer (Ioffe and Szegedy, 2014).\n\n    Normalizes the input at each batch, i.e. applies a transformation\n    that maintains the mean activation close to 0 and the activation\n    standard deviation close to 1.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input to be batch-normalized.\n\n    gamma : tvm.te.Tensor\n        Scale factor to be applied to the normalized tensor.\n\n    beta : tvm.te.Tensor\n        Offset to be applied to the normalized tensor.\n\n    moving_mean : tvm.te.Tensor\n        Running mean of input.\n\n    moving_var : tvm.te.Tensor\n        Running variance of input.\n\n    axis : int, optional, default=1\n        Specify along which shape axis the normalization should occur.\n\n    epsilon : float, optional, default=1e-5\n        Small float added to variance to avoid dividing by zero.\n\n    center : bool, optional, default=True\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : bool, optional, defualt=True\n        If True, scale normalized tensor by gamma. If False, gamma\n        is ignored.\n\n    Returns\n    -------\n    output : list of tvm.te.Tensor\n        Normalized data with same shape as input\n\n    moving_mean : tvm.te.Tensor\n        Running mean of input.\n\n    moving_var : tvm.te.Tensor\n        Running variance of input.\n    \"\"\"\n    if axis is None:\n        axis = 1\n\n    if epsilon is None:\n        epsilon = 1e-5\n\n    if center is None:\n        center = True\n\n    if scale is None:\n        scale = True\n\n    shape = [1] * len(data.shape)\n    shape[axis] = data.shape[axis]\n\n    moving_mean_rs = topi.reshape(moving_mean, shape)\n    moving_var_rs = topi.reshape(moving_var, shape)\n\n    out = (data - moving_mean_rs) / topi.math.sqrt(moving_var_rs + epsilon)\n\n    if scale:\n        out = out * topi.reshape(gamma, shape)\n    if center:\n        out = out + topi.reshape(beta, shape)\n\n    # Moving mean and var aren't updated during test. To avoid\n    # placeholder reuse, we multiply by 1 and return them.\n    return [out, moving_mean * 1, moving_var * 1]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/batch_to_space_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator batch_to_space_nd compute.\"\"\"\nfrom __future__ import absolute_import\nfrom . import cpp\n\n\ndef batch_to_space_nd(data, block_shape, crop_begin_list, crop_end_list):\n    \"\"\"Perform space to batch transformation on the data\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D Tensor with shape [batch, spatial_shape, remaining_shapes],\n        where spatial_shape has M dimensions.\n\n    block_size : list of ints\n        list of size [M] where M is number of spatial dims, specifies block\n        size for each spatial dimension.\n\n    crop_begin_list : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        begin crop size for each spatial dimension.\n\n    crop_end_list : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        end crop size for each spatial dimension.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n    \"\"\"\n\n    return cpp.nn.batch_to_space_nd(data, block_shape, crop_begin_list, crop_end_list)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/bitserial_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n# pylint: disable=unused-argument, redefined-builtin\n\"\"\"Bitserial Conv2D operators\"\"\"\nimport tvm\nfrom tvm import te\nfrom .pad import pad\nfrom .utils import get_pad_tuple\nfrom .bitserial_util import bitpack\nfrom ..utils import get_const_tuple\n\n\ndef bitserial_conv2d_nchw(\n    data,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    \"\"\"Bitserial Conv2D operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of two or four ints\n        padding size, [pad_height, pad_width], [pad_top, pad_left, pad_down, pad_right]\n\n    activation_bits: int\n        number of bits used for activations/input elements\n\n    weight_bits: int\n        number of bits used for weight elements\n\n    out_dtype: str\n        return type of convolution\n\n    pack_dtype: str\n        bit packing type\n\n    unipolar: bool\n        if binarization style is in unipolar 1/0 format, instead of bipolar -1/+1 format\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    assert isinstance(stride, int) or len(stride) == 2\n    Input_q = bitpack(data, activation_bits, pack_axis=1, bit_axis=2, pack_type=pack_dtype)\n    if len(kernel.shape) == 4:\n        Filter_q = bitpack(kernel, weight_bits, pack_axis=1, bit_axis=4, pack_type=pack_dtype)\n    else:\n        Filter_q = kernel\n    batch, in_channel, activation_bits, in_height, in_width = Input_q.shape\n    num_filter, _, kernel_h, kernel_w, weight_bits = Filter_q.shape\n\n    if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2):\n        TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel)\n    else:\n        TPAD, LPAD, DPAD, RPAD = padding\n    pad_before = [0, 0, 0, TPAD, LPAD]\n    pad_after = [0, 0, 0, DPAD, RPAD]\n\n    PadInput_q = pad(Input_q, pad_before, pad_after, name=\"pad_temp\")\n    # compute the output shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + TPAD + DPAD) // stride_h + 1\n    out_width = (in_width - kernel_w + LPAD + RPAD) // stride_w + 1\n\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    b1 = te.reduce_axis((0, activation_bits), name=\"b1\")\n    b2 = te.reduce_axis((0, weight_bits), name=\"b2\")\n\n    if unipolar:\n\n        def _conv(nn, ff, yy, xx):\n            b1b2 = (b1 + b2).astype(out_dtype)\n            return te.sum(\n                (\n                    (\n                        tvm.tir.popcount(\n                            PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx]\n                            & Filter_q[ff, rc, ry, rx, b2]\n                        )\n                        - tvm.tir.popcount(\n                            PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx]\n                            & ~Filter_q[ff, rc, ry, rx, b2]\n                        )\n                    )\n                    << (b1b2)\n                ).astype(out_dtype),\n                axis=[rc, ry, rx, b2, b1],\n            ).astype(out_dtype)\n\n    else:\n\n        def _conv(nn, ff, yy, xx):\n            b1b2 = (b1 + b2).astype(out_dtype)\n            return te.sum(\n                (\n                    tvm.tir.popcount(\n                        PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx]\n                        & Filter_q[ff, rc, ry, rx, b2]\n                    )\n                    << (b1b2)\n                ).astype(out_dtype),\n                axis=[rc, ry, rx, b2, b1],\n            ).astype(out_dtype)\n\n    return te.compute(\n        (batch, out_channel, out_height, out_width),\n        _conv,\n        name=\"Conv2dOutput\",\n        tag=\"bitserial_conv2d_nchw\",\n    )\n\n\ndef bitserial_conv2d_nhwc(\n    data,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    \"\"\"Bitserial Conv2D operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of two or four ints\n        padding size, [pad_height, pad_width], [pad_top, pad_left, pad_down, pad_right]\n\n    activation_bits: int\n        number of bits used for activations/input elements\n\n    weight_bits: int\n        number of bits used for weight elements\n\n    out_dtype: str\n        return type of convolution\n\n    pack_dtype: str\n        bit packing type\n\n    unipolar: bool\n        if binarization style is in unipolar 1/0 format, instead of bipolar -1/+1 format\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    assert isinstance(stride, int) or len(stride) == 2\n    Input_q = bitpack(data, activation_bits, pack_axis=3, bit_axis=4, pack_type=pack_dtype)\n    if len(kernel.shape) == 4:\n        Filter_q = bitpack(kernel, weight_bits, pack_axis=2, bit_axis=4, pack_type=pack_dtype)\n        kernel_h, kernel_w, _, num_filter, _ = get_const_tuple(Filter_q.shape)\n    else:\n        Filter_q = kernel\n        kernel_h, kernel_w, _, _, num_filter = get_const_tuple(Filter_q.shape)\n    batch, in_height, in_width, in_channel_q, _ = get_const_tuple(Input_q.shape)\n\n    if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2):\n        TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel)\n    else:\n        TPAD, LPAD, DPAD, RPAD = padding\n    pad_before = [0, TPAD, LPAD, 0, 0]\n    pad_after = [0, DPAD, RPAD, 0, 0]\n\n    # compute the output shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + TPAD + DPAD) // stride_h + 1\n    out_width = (in_width - kernel_w + LPAD + RPAD) // stride_w + 1\n    PadInput_q = pad(Input_q, pad_before, pad_after, name=\"PaddedInput\")\n\n    rc = te.reduce_axis((0, in_channel_q), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    b1 = te.reduce_axis((0, activation_bits), name=\"b1\")\n    b2 = te.reduce_axis((0, weight_bits), name=\"b2\")\n\n    if unipolar:\n\n        def _conv(nn, yy, xx, ff):\n            b1b2 = (b1 + b2).astype(out_dtype)\n            return te.sum(\n                (\n                    (\n                        tvm.tir.popcount(\n                            PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1]\n                            & Filter_q[ry, rx, rc, ff, b2]\n                        )\n                        - tvm.tir.popcount(\n                            PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1]\n                            & ~Filter_q[ry, rx, rc, ff, b2]\n                        )\n                    )\n                    << b1b2\n                ).astype(out_dtype),\n                axis=[rc, ry, rx, b2, b1],\n            )\n\n    else:\n\n        def _conv(nn, yy, xx, ff):\n            b1b2 = (b1 + b2).astype(out_dtype)\n            return te.sum(\n                (\n                    tvm.tir.popcount(\n                        PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1]\n                        & Filter_q[ry, rx, rc, ff, b2]\n                    )\n                    << b1b2\n                ).astype(out_dtype),\n                axis=[rc, ry, rx, b2, b1],\n            )\n\n    conv = te.compute(\n        (batch, out_height, out_width, out_channel),\n        _conv,\n        name=\"Conv2dOutput\",\n        tag=\"bitserial_conv2d_nhwc\",\n    )\n\n    return conv\n\n\n@tvm.target.generic_func\ndef bitserial_conv2d_legalize(attrs, inputs, types):\n    \"\"\"Legalizes Bitserial Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # not to change by default\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/bitserial_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Bitserial Dense operator.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom tvm.topi.utils import get_const_tuple\nfrom .bitserial_util import bitpack\n\n\ndef bitserial_dense(\n    data, weight, data_bits, weight_bits, pack_dtype=\"uint32\", out_dtype=\"int16\", unipolar=True\n):\n    \"\"\"The default implementation of bitserial dense in topi.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim] or\n        3-D with shape [out_dim, weight_bits, in_dim]\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    data_packed = bitpack(data, data_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    if len(weight.shape) == 2:\n        weight_packed = bitpack(weight, weight_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    else:\n        weight_packed = weight\n    Y, DB, K = get_const_tuple(data_packed.shape)\n    X, WB, _ = get_const_tuple(weight_packed.shape)\n\n    oshape = (Y, X)\n    k = te.reduce_axis((0, K), name=\"k\")\n    db = te.reduce_axis((0, DB), name=\"db\")\n    wb = te.reduce_axis((0, WB), name=\"wb\")\n\n    matmul_unipolar = te.compute(\n        oshape,\n        lambda i, j: te.sum(\n            (\n                tvm.tir.popcount(weight_packed[j, wb, k] & data_packed[i, db, k])\n                - tvm.tir.popcount(~weight_packed[j, wb, k] & data_packed[i, db, k])\n            ).astype(out_dtype)\n            << (db + wb).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense_unipolar\",\n    )\n\n    matmul = te.compute(\n        oshape,\n        lambda i, j: te.sum(\n            tvm.tir.popcount(weight_packed[j, wb, k] & data_packed[i, db, k]).astype(out_dtype)\n            << (db + wb).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense\",\n    )\n\n    if unipolar:\n        return matmul_unipolar\n    return matmul\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/bitserial_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Utility functions for bitserial operators\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm.topi.transform import concatenate\nfrom ..utils import get_const_int\n\n\ndef bitpack(data, bits, pack_axis, bit_axis, pack_type, name=\"QuantizeInput\"):\n    \"\"\"Packs data into format necessary for bitserial computation\n\n    Parameters\n    ----------\n    pack_axis : int\n       index of the axis to pack in data\n    bit_axis : int\n       index of axis to place bit axis in resulting packed data\n    \"\"\"\n    ishape = data.shape\n    n = len(ishape)\n    if pack_type == \"uint8\":\n        data_width = 8\n    elif pack_type == \"uint16\":\n        data_width = 16\n    elif pack_type == \"uint32\":\n        data_width = 32\n    elif pack_type == \"uint64\":\n        data_width = 64\n\n    # Data must be in multiples of the data_width\n    assert get_const_int(ishape[pack_axis]) % data_width == 0, \"Not a multiple of word size\"\n\n    shape_vec = list(ishape)\n    shape_vec[pack_axis] = shape_vec[pack_axis] // data_width\n    shape_vec.insert(bit_axis, 1)\n    bitserial_oshape = tuple(shape_vec)\n    masks = np.array([0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80])\n\n    # pack axis shifts if bit axis comes before\n    if bit_axis <= pack_axis:\n        pack_axis += 1\n\n    def _bitpack(*indices):\n        packed_data = [tvm.tir.const(0, pack_type)] * bits\n        for k in range(data_width):\n            # Translate indices for packed data back to original\n            idx = [0] * n\n            j = 0\n            for i in range(n + 1):\n                if i == bit_axis:\n                    continue\n                if i == pack_axis:\n                    idx[j] = indices[i] * data_width + k\n                else:\n                    idx[j] = indices[i]\n                j += 1\n\n            element = data(*idx)\n            for b in range(bits):\n                extracted_bit = ((element & tvm.tir.const(masks[b], \"int32\")) >> b).astype(\n                    pack_type\n                )\n                packed_data[b] = packed_data[b] | extracted_bit\n                if k < data_width - 1:\n                    packed_data[b] = packed_data[b] << 1\n\n            if k == data_width - 1:\n                return tuple(packed_data)\n        return tuple(packed_data)\n\n    output_tuple = te.compute(bitserial_oshape, _bitpack, name=name, tag=\"bitpack\")\n\n    if bits > 1:\n        return concatenate(output_tuple, axis=bit_axis)\n    return output_tuple\n\n\ndef binary_op_multiplier(pack_dtype):\n    \"\"\" \"Returns number of bits packed into\n    pack_dtype: string\n        pack type for the operator (must be a uint)\"\"\"\n    return int(pack_dtype[4:])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/bnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Binary Neural Network (BNN) Operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..utils import simplify, get_const_int\n\n\ndef binarize_pack(data, axis=None, name=\"PackedInput\"):\n    \"\"\"Binarization and bit-packing along a certain axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D input, can be any layout.\n\n    axis : None or int\n        The axis along which to do binarization and bit-packing,\n        default is the last axis.\n\n    name : str, optional\n        The name prefix operators generate.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D, the same layout as input, dtype is uint32.\n    \"\"\"\n    ishape = data.shape\n    if axis is None:\n        axis = len(ishape) - 1\n    assert get_const_int(ishape[axis]) % 32 == 0\n    n = len(ishape)\n    oshape = tuple(simplify(ishape[i] // 32) if i == axis else ishape[i] for i in range(n))\n\n    def _binarize_pack(*indices):\n        start_idx = [indices[i] * 32 if i == axis else indices[i] for i in range(n)]\n        packed = tvm.tir.const(0, \"uint32\")\n        for j in range(32):\n            idx = [start_idx[i] + j if i == axis else start_idx[i] for i in range(n)]\n            sign = (data(*idx) >= 0).astype(\"uint32\")\n            packed = packed | sign\n            if j == 31:\n                return packed\n            packed = packed << 1\n        raise RuntimeError(\"not resach\")\n\n    return te.compute(oshape, _binarize_pack, name=name, tag=\"binarize_pack\")\n\n\ndef binary_dense(data, weight):\n    \"\"\"Binary matrix multiplication using xor and bit-count.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim], dtype is uint32.\n\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim], dtype is uint32.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim], dtype is float32.\n    \"\"\"\n    assert (\n        data.dtype == \"uint32\" and weight.dtype == \"uint32\"\n    ), \"dtype of data and weight should be uint32\"\n    assert len(data.shape) == 2 and len(weight.shape) == 2, \"only support 2-dim binary dense\"\n    batch, in_dim = data.shape\n    out_dim, _ = weight.shape\n    k = te.reduce_axis((0, in_dim), name=\"k\")\n    matmul = te.compute(\n        (batch, out_dim),\n        lambda i, j: te.sum(tvm.tir.popcount(data[i, k] ^ weight[j, k]), axis=k),\n        tag=\"binary_dense\",\n    )\n\n    return te.compute(\n        (batch, out_dim), lambda i, j: 32 * in_dim - 2.0 * matmul(i, j), tag=tag.ELEMWISE\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"1D convolution operators.\"\"\"\nfrom .conv2d import conv\n\n\ndef conv1d(\n    data,\n    kernel,\n    strides=1,\n    padding=\"VALID\",\n    dilation=1,\n    data_layout=\"NCW\",\n    kernel_layout=\"\",\n    out_dtype=None,\n):\n    \"\"\"1D convolution forward operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D input shape [batch, in_channel, in_width] for data_layout == 'NCW'\n        and [batch, in_width, in_channel] for data_layout == 'NWC'\n\n    kernel : tvm.te.Tensor\n        3-D kernel with shape [num_filter, in_channel, filter_size] for kernel_layout == 'OIW'\n        and [filter_size, in_channel, num_filter] for kernel_layout == 'WIO'\n\n    strides : int or tuple\n        The spatial stride along width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation : int or tuple\n        Dilation rate if convolution should be dilated.\n\n    data_layout : str\n        How input data is laid out, must be one of ['NCW', 'NWC']\n\n    kernel_layout: Optiona[str]\n        The layout of the kernel. If unspecified, use default layout. \"OIW\" if data_layout == \"NCW\",\n        \"WIO\" if data_layout == \"NWC\".\n\n    out_dtype : str\n        The output data type. If None then output is same type as input.\n    \"\"\"\n    return conv(data, kernel, strides, padding, dilation, 1, data_layout, kernel_layout, out_dtype)\n\n\ndef conv1d_nwc(data, kernel, strides=1, padding=\"VALID\", dilation=1, out_dtype=None):\n    \"\"\"1D convolution in NWC layout. See :py:func:`conv` for details on parameters\"\"\"\n    return conv(data, kernel, strides, padding, dilation, 1, \"NWC\", \"WIO\", out_dtype=out_dtype)\n\n\ndef conv1d_ncw(data, kernel, strides=1, padding=\"VALID\", dilation=1, out_dtype=None):\n    \"\"\"1D convolution in NCW layout. See :py:func:`conv` for details on parameters\"\"\"\n    return conv(data, kernel, strides, padding, dilation, 1, \"NCW\", \"OIW\", out_dtype=out_dtype)\n\n\ndef group_conv1d_nwc(\n    data, kernel, strides=1, padding=\"VALID\", dilation=1, groups=1, out_dtype=None\n):\n    \"\"\"1D convolution forward operator for NWC layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D with shape [batch, in_width, in_channel]\n\n    kernel : tvm.te.Tensor\n        3-D with shape [filter_size, in_channel, num_filter]\n\n    strides : int or tuple\n        The spatial stride along width\n\n    padding : int, tuple, or str\n        Padding size can be an integer for equal padding,\n        a tuple of (left, right) or a string in ['VALID', 'SAME'].\n\n    dilation : int or tuple\n        Dilation rate if convolution should be dilated.\n\n    groups : int\n        Number of groups\n\n    out_dtype : str\n        The output data type. If None then output is same type as input.\n    \"\"\"\n    return conv(data, kernel, strides, padding, dilation, groups, \"NWC\", \"WIO\", out_dtype=out_dtype)\n\n\ndef group_conv1d_ncw(\n    data, kernel, strides=1, padding=\"VALID\", dilation=1, groups=1, out_dtype=None\n):\n    \"\"\"1D convolution forward operator for NCW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D with shape [batch, in_channel, in_width]\n\n    kernel : tvm.te.Tensor\n        3-D with shape [num_filter, in_channel, filter_size]\n\n    strides : int or tuple\n        The spatial stride along width\n\n    padding : int, tuple, or str\n        Padding size can be an integer for equal padding,\n        a tuple of (left, right) or a string in ['VALID', 'SAME'].\n\n    dilation : int or tuple\n        Dilation rate if convolution should be dilated.\n\n    groups : int\n        Number of groups\n\n    out_dtype : str\n        The output data type. If None then output is same type as input.\n    \"\"\"\n    return conv(data, kernel, strides, padding, dilation, groups, \"NCW\", \"OIW\", out_dtype=out_dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv1d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Transposed 1D convolution operators (sometimes called Deconvolution).\"\"\"\nfrom tvm import te\nfrom .dilate import dilate\nfrom .pad import pad\nfrom ..utils import simplify\nfrom .utils import get_pad_tuple1d\n\n\ndef conv1d_transpose_ncw(data, kernel, stride, padding, out_dtype, output_padding):\n    \"\"\"Transposed 1D convolution ncw forward operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D with shape [batch, in_channel, in_width]\n\n    kernel : tvm.te.Tensor\n        3-D with shape [in_channel, num_filter, filter_width]\n\n    stride : ints\n        The spatial stride along width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    out_dtype : str\n        The output data type. This is used for mixed precision.\n\n    output_padding : ints\n        Used to recover the actual output shape in case there are more\n        than one possible shape.  Must be smaller than stride.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, out_channel, out_width]\n\n    \"\"\"\n\n    # dilate and pad\n    if isinstance(stride, (tuple, list)):\n        stride = stride[0]\n    if isinstance(output_padding, (tuple, list)):\n        output_padding = output_padding[0]\n    batch, channels_in, data_width = data.shape\n    _, channels_out, kernel_width = kernel.shape\n    assert output_padding < stride\n    channels_out = simplify(channels_out)\n    data = dilate(data, [1, 1, stride], name=\"data_dilate\")\n    pad_left, pad_right = get_pad_tuple1d(padding, (kernel_width,))\n    pad_left = kernel_width - 1 - pad_left\n    pad_right = kernel_width - 1 - pad_right + output_padding\n    data = pad(data, [0, 0, pad_left], [0, 0, pad_right], name=\"data_pad\")\n\n    # transpose kernel, switch kernel layout to IOW\n    kernel = te.compute(\n        (channels_out, channels_in, kernel_width),\n        lambda o, i, w: kernel[i][o][kernel_width - 1 - w],\n        name=\"kernel\",\n    )\n\n    # convolution\n    _, _, data_width = data.shape\n    out_w = simplify(data_width - kernel_width + 1)\n    dc = te.reduce_axis((0, channels_in), name=\"dc\")\n    dw = te.reduce_axis((0, kernel_width), name=\"dw\")\n    output = te.compute(\n        (batch, channels_out, out_w),\n        lambda b, c, w: te.sum(\n            data[b, dc, w + dw].astype(out_dtype) * kernel[c, dc, dw].astype(out_dtype),\n            axis=[dc, dw],\n        ),\n        tag=\"conv1d_transpose_ncw\",\n    )\n\n    return output\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin\n\"\"\"Conv2D operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport re\nfrom collections import namedtuple\nfrom typing import Optional, Sequence, Union\n\nimport numpy as np\nimport tvm\nfrom tvm import auto_scheduler, te\n\nfrom ..utils import get_const_int, get_const_tuple, simplify, tag\nfrom .pad import pad\nfrom .utils import get_pad_tuple, get_pad_tuple_generic\nfrom .winograd_util import winograd_transform_matrices\n\n# workload description of conv2d\nWorkload = namedtuple(\n    \"Workload\",\n    [\n        \"in_dtype\",\n        \"out_dtype\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"groups\",\n        \"out_filter\",\n        \"kernel_h\",\n        \"kernel_w\",\n        \"padt\",\n        \"padl\",\n        \"padb\",\n        \"padr\",\n        \"dilation_h\",\n        \"dilation_w\",\n        \"stride_h\",\n        \"stride_w\",\n    ],\n)\n\n\ndef conv2d(\n    input, filter, strides, padding, dilation, data_layout=\"NCHW\", kernel_layout=\"\", out_dtype=None\n):\n    \"\"\"Conv2D operator.\n\n    Parameters\n    ----------\n    input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width] in data_layout\n\n    filter : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width] in kernel_layout\n\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    data_layout : str\n        layout of data\n\n    kernel_layout : Optional[str]\n        layout of kernel. If unspecified, use default layout inferred from data_layout. \"OIHW\" if\n        data_layout == \"NCHW\", \"HWIO\" if data_layout == \"NHWC\".\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    # search platform specific declaration first\n    # default declaration\n    return conv(input, filter, strides, padding, dilation, 1, data_layout, kernel_layout, out_dtype)\n\n\n@tvm.target.generic_func\ndef conv2d_legalize(attrs, inputs, types):\n    \"\"\"Legalizes Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # not to change by default\n    return None\n\n\n@tvm.target.generic_func\ndef conv2d_alter_layout(attrs, inputs, tinfos, out_type):\n    \"\"\"Change Conv2D layout.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : tvm.relay.Expr\n        Grouped input symbols\n    tinfos : list\n        Input shape and dtype\n    out_type: type\n        The output type\n\n    Note\n    ----\n    Unlike other TOPI functions, this function operates on both graph level and operator level.\n    \"\"\"\n    # not to change by default\n    return None\n\n\n@tvm.target.generic_func\ndef conv2d_infer_layout(workload, cfg):\n    \"\"\"Infer input/output shapes and layouts from a workload and cfg.\n\n    Parameters\n    ----------\n    workload : tuple\n        conv2d workload\n\n    cfg : tuple\n        tvm.autotvm config\n\n    Returns\n    -------\n    Output : [tuple of tuple and str, tuple of tuple and str]\n        Input shapes and layouts, and output shapes and layouts\n    \"\"\"\n    raise ValueError(\"missing register for topi.nn.conv2d_infer_layout\")\n\n\ndef _get_workload(data, kernel, stride, padding, dilation, out_dtype, data_layout=\"NCHW\"):\n    \"\"\"Get the workload structure.\"\"\"\n    if data_layout == \"NCHW\":\n        _, CI, IH, IW = get_const_tuple(data.shape)\n    elif data_layout == \"NHWC\":\n        _, IH, IW, CI = get_const_tuple(data.shape)\n    elif data_layout == \"HWCN\":\n        IH, IW, CI, _ = get_const_tuple(data.shape)\n    else:\n        raise ValueError(\"not support this layout {} yet\".format(data_layout))\n\n    if data_layout == \"NCHW\":\n        CO, CIG, KH, KW = get_const_tuple(kernel.shape)\n    else:\n        KH, KW, CIG, CO = get_const_tuple(kernel.shape)\n\n    dilation_h, dilation_w = (\n        dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    )\n    pt, pl, pb, pr = get_pad_tuple(\n        padding,\n        (get_const_int((KH - 1) * dilation_h + 1), get_const_int((KW - 1) * dilation_w + 1)),\n    )\n    GRPS = CI // CIG\n    if isinstance(stride, (tuple, list)):\n        HSTR, WSTR = stride\n    else:\n        HSTR, WSTR = stride, stride\n    assert (data.dtype == kernel.dtype) or (\n        data.dtype == \"uint8\" and kernel.dtype == \"int8\"\n    ), \"Do not support inputs with different data types now. ' \\\n        '{} vs. {}\".format(\n        data.dtype, kernel.dtype\n    )\n    return Workload(\n        data.dtype,\n        out_dtype,\n        IH,\n        IW,\n        CI,\n        GRPS,\n        CO,\n        KH,\n        KW,\n        pt,\n        pl,\n        pb,\n        pr,\n        dilation_h,\n        dilation_w,\n        HSTR,\n        WSTR,\n    )\n\n\ndef conv2d_nchw(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return conv(Input, Filter, stride, padding, dilation, 1, \"NCHW\", \"OIHW\", out_dtype=out_dtype)\n\n\ndef conv2d_hwcn(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Convolution operator in HWCN layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [in_height, in_width, in_channel, batch]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [out_height, out_width, out_channel, batch]\n    \"\"\"\n    return conv(Input, Filter, stride, padding, dilation, 1, \"HWCN\", \"HWIO\", out_dtype=out_dtype)\n\n\ndef conv2d_nhwc(\n    Input,\n    Filter,\n    stride,\n    padding,\n    dilation,\n    out_dtype=\"float32\",\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str = \"float32\",\n        The type of output tensor\n\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    return conv(\n        Input,\n        Filter,\n        stride,\n        padding,\n        dilation,\n        1,\n        \"NHWC\",\n        \"HWIO\",\n        out_dtype,\n        auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape,\n        auto_scheduler_should_rewrite_layout=True,\n    )\n\n\ndef conv2d_NCHWc(data, kernel, stride, padding, dilation, layout, out_layout, out_dtype=\"float32\"):\n    \"\"\"Conv2D operator for nChw[x]c layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    kernel : tvm.te.Tensor\n        6-D with shape\n        [num_filter_chunk, in_channel_chunk, filter_height, filter_width,\n        in_channel_block, num_filter_block]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    layout : str\n        Input data layout\n\n    out_layout : str\n        Output data layout\n\n    out_dtype : str\n        output data type\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block]\n    \"\"\"\n\n    # layout and out_layout are not used here,\n    # we keep them for debug convenience when dumping autotvm workload\n    HSTR, WSTR = stride if isinstance(stride, (tuple, list)) else (stride, stride)\n    dilation_h, dilation_w = (\n        dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    )\n\n    n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n    in_channel = ic_chunk * ic_bn\n    target = tvm.target.Target.current(allow_none=False)\n    oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn = get_const_tuple(kernel.shape)\n    num_filter = oc_chunk * oc_bn\n    groups = ic_chunk // ic_chunk_group\n\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HPAD = pad_top + pad_down\n    WPAD = pad_left + pad_right\n\n    # output shape\n    out_height = (ih + HPAD - dilated_kernel_h) // HSTR + 1\n    out_width = (iw + WPAD - dilated_kernel_w) // WSTR + 1\n    oshape = (n, oc_chunk, out_height, out_width, oc_bn)\n    pad_before = (0, 0, pad_top, pad_left, 0)\n    pad_after = (0, 0, pad_down, pad_right, 0)\n\n    # DOPAD\n    DOPAD = HPAD != 0 or WPAD != 0\n    if DOPAD:\n        data_pad = pad(data, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data\n\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    return te.compute(\n        oshape,\n        lambda n, oc_chunk, oh, ow, oc_block: te.sum(\n            data_pad[\n                n,\n                idxdiv(ic, ic_bn),\n                oh * HSTR + kh * dilation_h,\n                ow * WSTR + kw * dilation_w,\n                idxmod(ic, ic_bn),\n            ].astype(out_dtype)\n            * kernel[oc_chunk, idxdiv(ic, ic_bn), kh, kw, idxmod(ic, ic_bn), oc_block].astype(\n                out_dtype\n            ),\n            axis=[ic, kh, kw],\n        ),\n        name=\"conv2d_NCHWc\",\n        tag=\"conv2d_NCHWc\",\n    )\n\n\ndef conv2d_NCHWc_int8(\n    data, kernel, stride, padding, dilation, layout, out_layout, out_dtype=\"int32\", n_elems=4\n):\n    \"\"\"Conv2D operator for nChw[x]c layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    kernel : tvm.te.Tensor\n        7-D with shape\n        [num_filter_chunk, in_channel_chunk, filter_height, filter_width, in_channel_block/4,\n        num_filter_block, 4]\n\n    stride : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    layout : str\n        Input data layout\n\n    out_layout : str\n        Output data layout\n\n    out_dtype : str\n        output data type\n\n    n_elems : int\n        numer of int8 elements accumulated\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block]\n    \"\"\"\n\n    # layout and out_layout are not used here,\n    # we keep them for debug convenience when dumping autotvm workload\n    HSTR, WSTR = stride if isinstance(stride, (tuple, list)) else (stride, stride)\n    dilation_h, dilation_w = (\n        dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    )\n\n    n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n    in_channel = ic_chunk * ic_bn\n    oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn, _ = get_const_tuple(\n        kernel.shape\n    )\n    groups = ic_chunk // ic_chunk_group\n\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HPAD = pad_top + pad_down\n    WPAD = pad_left + pad_right\n\n    # output shape\n    out_height = (ih + HPAD - dilated_kernel_h) // HSTR + 1\n    out_width = (iw + WPAD - dilated_kernel_w) // WSTR + 1\n    oshape = (n, oc_chunk, out_height, out_width, oc_bn)\n    pad_before = (0, 0, pad_top, pad_left, 0)\n    pad_after = (0, 0, pad_down, pad_right, 0)\n\n    # DOPAD\n    DOPAD = HPAD != 0 or WPAD != 0\n    if DOPAD:\n        data_pad = pad(data, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data\n\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n\n    if groups == 1:\n        ic_outer = te.reduce_axis((0, in_channel // ic_bn), name=\"ic_outer\")\n        ic_f_inner = te.reduce_axis((0, ic_bn // n_elems), name=\"ic_f_inner\")\n        ic_s_inner = te.reduce_axis((0, n_elems), name=\"ic_s_inner\")\n        return te.compute(\n            oshape,\n            lambda n, oc_chunk, oh, ow, oc_block: te.sum(\n                data_pad[\n                    n,\n                    ic_outer,\n                    oh * HSTR + kh * dilation_h,\n                    ow * WSTR + kw * dilation_w,\n                    ic_f_inner * n_elems + ic_s_inner,\n                ].astype(out_dtype)\n                * kernel[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype(\n                    out_dtype\n                ),\n                axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner],\n            ),\n            name=\"conv2d_NCHWc_int8\",\n            tag=\"conv2d_NCHWc_int8\",\n            attrs={\"schedule_rule\": \"conv2d_NCHWc_int8\"},\n        )\n    # for int8 group conv support\n    ic_chunk = in_channel // ic_bn\n    ic_outer = te.reduce_axis((0, ic_chunk // groups), name=\"ic_outer\")\n    ic_f_inner = te.reduce_axis((0, ic_bn // n_elems), name=\"ic_f_inner\")\n    ic_s_inner = te.reduce_axis((0, n_elems), name=\"ic_s_inner\")\n    oshape = (n, oc_chunk, out_height, out_width, oc_bn)\n    return te.compute(\n        oshape,\n        lambda n, occ, oh, ow, oc_block: te.sum(\n            data_pad[\n                n,\n                (occ * oc_bn // (oc_chunk * oc_bn // groups)) * (ic_chunk // groups) + ic_outer,\n                oh * HSTR + kh,\n                ow * WSTR + kw,\n                ic_f_inner * n_elems + ic_s_inner,\n            ].astype(out_dtype)\n            * kernel[occ, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype(out_dtype),\n            axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner],\n        ),\n        name=\"conv2d_NCHWc_int8\",\n        tag=\"conv2d_NCHWc_int8\",\n        attrs={\"schedule_rule\": \"conv2d_NCHWc_int8\"},\n    )\n\n\ndef conv2d_gemm_weight_transform(kernel, tile_rows, tile_cols):\n    \"\"\"Weight transformation for winograd\n\n    Parameters\n    ----------\n    kernel: Tensor\n        The raw kernel tensor with layout \"NHWC\".\n    tile_rows: int\n        Tile rows of the weight transformation for ConvGemm.\n    tile_cols: int\n        Tile columns of the weight transformation for ConvGemm.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [CI*KH*KW,CO]\n    \"\"\"\n    KH, KW, IC, OC = get_const_tuple(kernel.shape)\n    K = KH * KW * IC\n    N = OC\n\n    kernel_flat = te.compute(\n        (K, N), lambda x, y: kernel[(x // IC) // KW, (x // IC) % KW, x % IC, y], \"weight_flatten\"\n    )\n\n    pad_K = 0\n    pad_N = 0\n\n    if N % tile_rows != 0:\n        pad_N = tile_rows - (N % tile_rows)\n\n    if K % tile_cols != 0:\n        pad_K = tile_cols - (K % tile_cols)\n\n    N_padded = N + pad_N\n    K_padded = K + pad_K\n\n    if pad_K != 0 or pad_N != 0:\n        kernel_flat = pad(\n            kernel_flat, pad_before=(0, 0), pad_after=(pad_K, pad_N), name=\"weight_padding\"\n        )\n\n    return te.compute(\n        (N_padded // tile_rows, K_padded // tile_cols, tile_rows, tile_cols),\n        lambda x, y, z, w: kernel_flat[w + tile_cols * y, z + tile_rows * x],\n        name=\"weight_block_reshape\",\n    )\n\n\ndef conv2d_winograd_weight_transform(kernel, tile_size):\n    \"\"\"Weight transformation for winograd\n\n    Parameters\n    ----------\n    kernel: Tensor\n        The raw kernel tensor with layout \"NCHW\".\n    tile_size: int\n        Tile size of winograd transform. e.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [alpha, alpha, CO, CI]\n    \"\"\"\n    shape = get_const_tuple(kernel.shape)\n    assert shape[2] == shape[3], \"Only support NxN kernel\"\n\n    K = shape[3]\n    r = tile_size + K - 1\n    shape = (r, r) + shape[:2]\n\n    _, _, G = winograd_transform_matrices(tile_size, K, kernel.dtype)\n\n    r_kh = te.reduce_axis((0, K), name=\"r_kh\")\n    r_kw = te.reduce_axis((0, K), name=\"r_kw\")\n    return te.compute(\n        shape,\n        lambda eps, nu, co, ci: te.sum(\n            kernel[co][ci][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n        ),\n        name=\"transform_weight\",\n    )\n\n\ndef conv2d_winograd_nnpack_weight_transform(kernel, convolution_algorithm, out_dtype):\n    \"\"\"Weight transformation for winograd\n\n    Parameters\n    ----------\n    kernel: Tensor\n        The raw kernel tensor with layout \"NCHW\". Only 3x3 kernel is supported for now.\n    convolution_algorithm: int\n        The convolution algorithm for Winograd NNPACK.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [alpha, alpha, CO, CI]\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    from tvm.contrib import nnpack\n\n    return nnpack.convolution_inference_weight_transform(\n        kernel, algorithm=convolution_algorithm, dtype=out_dtype\n    )\n\n\ndef group_conv2d_nchw(Input, Filter, stride, padding, dilation, groups, out_dtype=None):\n    \"\"\"Group convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel // groups, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    groups : int\n        number of groups\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return conv(\n        Input, Filter, stride, padding, dilation, groups, \"NCHW\", \"OIHW\", out_dtype=out_dtype\n    )\n\n\ndef conv(\n    inp: te.Tensor,\n    filt: te.Tensor,\n    stride: Union[int, Sequence[int]],\n    padding: Union[int, Sequence[int]],\n    dilation: Union[int, Sequence[int]],\n    groups: int,\n    data_layout: str,\n    kernel_layout: str = \"\",\n    out_dtype: Union[str, None] = None,\n    auto_scheduler_rewritten_layout: Optional[str] = None,\n    meta_schedule_original_shape=None,\n    auto_scheduler_should_rewrite_layout: bool = False,\n):\n    \"\"\"Convolution operator in NCHW or NHWC layout.\n\n    Supports 1D, 2D, 3D, ... and grouping.\n\n    Parameters\n    ----------\n    inp : tvm.te.Tensor\n        N-D with shape [batch, in_channel, in_height, in_width, ...] in `data_layout`\n\n    filt : tvm.te.Tensor\n        N-D with shape [num_filter, in_channel // groups, filter_height, filter_width, ...] in\n        `kernel_layout`\n\n    stride : int or a list/tuple of dim ints\n        (where dim=2 for NCHW, dim=1 for NCH, etc.)\n        Stride size, or [stride_height, stride_width, ...]\n\n    padding : int or a list/tuple of dim or 2*dim ints\n        (where dim=2 for NCHW, dim=1 for NCH, etc.)\n        padding size, or\n        [pad_height, pad_width, ...] for dim ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2*dim ints\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    groups : int\n        number of groups\n\n    data_layout : str\n        Layout of the input. N indicates batch dimension, C indicates\n        channels, any other character indicates HW (or H or HWD for 1D and 3D).\n\n    kernel_layout: Optional[str]\n        Layout of the filter. I indicates input channels, O indicates output channels,\n        any other character indicates HW dimension of the filter (or H or HWD for 1D and 3D).\n        If kernel_layout is empty, use data_layout to infer the default kernel_layout. Default\n        kernel_layout is OIHW for NCHW data layout, HWIO for NHWC data layout.\n\n    out_dtype : str\n        Elements are converted to this type before elementwise multiplication\n        and summation.\n\n    auto_scheduler_rewritten_layout: str\n        Layout from autoscheduler's layout rewritting.\n\n    meta_schedule_original_shape : Optional[List[PrimExpr]]\n        The original shape of the input tensor.\n\n    auto_scheduler_should_rewrite_layout : bool\n        Should auto scheduler be allowed to rewrite the layout of the filter\n        tensor. Defaults to false. This can cause errors if used with grouped\n        convs.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        N-D with shape [batch, out_channel, out_height, out_width, ...] in `data_layout`\n    \"\"\"\n    dim = len(inp.shape) - 2\n    if out_dtype is None:\n        out_dtype = inp.dtype\n    assert isinstance(stride, int) or len(stride) == dim\n    assert isinstance(dilation, int) or len(dilation) == dim\n    if isinstance(stride, int):\n        strides = [stride for _ in range(dim)]\n    else:\n        strides = stride\n\n    if isinstance(dilation, int):\n        dilations = [dilation for _ in range(dim)]\n    else:\n        dilations = list(dilation)\n\n    # transform from data_layout to NCHW\n    data_permutation_to = [data_layout.find(\"N\"), data_layout.find(\"C\")] + [\n        x.span()[0] for x in re.finditer(\"[^NC]\", data_layout)\n    ]\n    # transform from NCHW to data_layout\n    data_permutation_from = np.argsort(data_permutation_to)\n    # transform from CHW to data_layout\n    data_permutation_from_reductions = data_permutation_from[1:].copy()\n    data_permutation_from_reductions[\n        data_permutation_from_reductions > data_permutation_from[0]\n    ] -= 1\n\n    if kernel_layout == \"\":\n        # kernel permutation, if C appears before HW then num_filter is first, otherwise it is last\n        # tkonolige: I don't really understand kernel ordering for NHWC, it seems\n        # like num_filters should match the N dimension\n        if data_layout.find(\"C\") < re.search(\"[^NC]\", data_layout).span()[0]:\n            kernel_permutation_to = [0, 1] + list(range(2, dim + 2))\n        else:\n            kernel_permutation_to = [dim + 1, dim] + list(range(dim))\n    else:\n        # transform from kernel_layout to OIHW\n        kernel_permutation_to = [kernel_layout.find(\"O\"), kernel_layout.find(\"I\")] + [\n            x.span()[0] for x in re.finditer(\"[^OI]\", kernel_layout)\n        ]\n    # transform from OIHW to kernel_layout\n    kernel_permutation_from = np.argsort(kernel_permutation_to)\n\n    if meta_schedule_original_shape:\n        auto_scheduler.rewrite_tensor_shape(filt, meta_schedule_original_shape)\n    batch, in_channel, *dimensions = np.array(get_const_tuple(inp.shape))[\n        data_permutation_to\n    ].tolist()\n    num_filter, _, *kernel_dimensions = np.array(get_const_tuple(filt.shape))[\n        kernel_permutation_to\n    ].tolist()\n\n    # Autoscheduler may have messed with the input layout, so we extract the\n    # dimensions that it gives us\n    if auto_scheduler_rewritten_layout:\n        num_filter, _, *kernel_dimensions = auto_scheduler.get_shape_from_rewritten_layout(\n            auto_scheduler_rewritten_layout,\n            [\"ff\", \"rc\"] + [f\"r{i}\" for i in [\"y\", \"x\", \"z\"][: len(kernel_dimensions)]],\n        )\n        auto_scheduler.remove_index_check(filt)\n\n    assert in_channel % groups == 0, \"input channels must divide group size\"\n    assert num_filter % groups == 0, \"output channels must divide group size\"\n\n    dilated_kernel_dimensions = [(k - 1) * dil + 1 for k, dil in zip(kernel_dimensions, dilations)]\n    pad_begin, pad_end = get_pad_tuple_generic(padding, dilated_kernel_dimensions)\n    # compute the output shape\n    out_channel = num_filter\n    out_dimensions = [\n        simplify(d - (k - 1) * dil - 1 + pb + pe) // stride + 1\n        for d, k, dil, pb, pe, stride in zip(\n            dimensions, kernel_dimensions, dilations, pad_begin, pad_end, strides\n        )\n    ]\n    # compute graph\n    pad_before = list(np.array([0, 0] + pad_begin)[data_permutation_from])\n    pad_after = list(np.array([0, 0] + pad_end)[data_permutation_from])\n    temp = pad(inp, pad_before, pad_after, name=\"pad_temp\")\n    rc = te.reduce_axis((0, in_channel // groups), name=\"rc\")\n    rs = [te.reduce_axis((0, k), name=f\"r{i}\") for i, k in zip([\"y\", \"x\", \"z\"], kernel_dimensions)]\n\n    def compute(*args):\n        nn, ff, *dim_indices = list(np.array(args)[data_permutation_to])\n\n        if groups == 1:\n            simplified_channel_index = rc\n        else:\n            simplified_channel_index = ff // (num_filter // groups) * (in_channel // groups) + rc\n\n        return te.sum(\n            temp.__getitem__(\n                tuple(\n                    np.array(\n                        [nn, simplified_channel_index]\n                        + [\n                            di * stride + r * dil\n                            for di, stride, r, dil in zip(dim_indices, strides, rs, dilations)\n                        ]\n                    )[data_permutation_from]\n                )\n            ).astype(out_dtype)\n            * filt.__getitem__(tuple(np.array([ff, rc] + rs)[kernel_permutation_from])).astype(\n                out_dtype\n            ),\n            # Schedules depend on reduction axes being in the same order as the\n            # layout, so we reorder here.\n            axis=np.array([rc, *rs])[data_permutation_from_reductions].tolist(),\n        )\n\n    out = te.compute(\n        list(np.array([batch, out_channel] + out_dimensions)[data_permutation_from]),\n        compute,\n        # tag is expected to be lowercase\n        tag=f\"{'group_' if groups > 1 else ''}conv{dim}d_{data_layout.lower()}\",\n        name=f\"{'group_' if groups > 1 else ''}conv{dim}d_{data_layout.lower()}\",\n        attrs={\"layout_free_placeholders\": [filt]} if auto_scheduler_should_rewrite_layout else {},\n        varargs_names=list(np.array([\"nn\", \"ff\", \"yy\", \"xx\", \"zz\"])[data_permutation_from]),\n    )\n    # if we used autoscheduler's changed layout we need to rewrite the ordering\n    # of the output dimensions\n    if auto_scheduler_rewritten_layout:\n        out = auto_scheduler.rewrite_compute_body(out, auto_scheduler_rewritten_layout)\n    return out\n\n\ndef group_conv2d_nhwc(Input, Filter, stride, padding, dilation, groups, out_dtype=None):\n    \"\"\"Group convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel, ...]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel // groups, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    groups : int\n        number of groups\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    return conv(\n        Input, Filter, stride, padding, dilation, groups, \"NHWC\", \"HWIO\", out_dtype=out_dtype\n    )\n\n\ndef unpack_NCHWc_to_nchw(packed_out, out_dtype):\n    \"\"\"Unpack conv2d_NCHWc output from layout NCHWc to NCHW\n\n    Parameters\n    ----------\n    packed_out : tvm.te.Tensor\n        The output tensor of conv2d_NCHWc.\n\n    out_dtype : str\n        The output dtype.\n\n    Returns\n    -------\n    unpacked_out : tvm.te.Tensor\n        The unpacked output tensor in NCHW layout.\n    \"\"\"\n    n, oc_chunk, oh, ow, oc_bn = get_const_tuple(packed_out.shape)\n\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n\n    oshape = (n, oc_chunk * oc_bn, oh, ow)\n    unpacked_out = te.compute(\n        oshape,\n        lambda n, c, h, w: packed_out[n, idxdiv(c, oc_bn), h, w, idxmod(c, oc_bn)].astype(\n            out_dtype\n        ),\n        name=\"output_unpack\",\n        tag=tag.INJECTIVE + \",unpack_nchwc\",\n    )\n    return unpacked_out\n\n\n@tvm.target.generic_func\ndef conv2d_winograd_nhwc(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    pre_computed=False,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd in NHWC layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n    weight : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n    out_dtype : str, optional\n        Specifies the output data type.\n    pre_computed: bool\n        Whether the kernel is precomputed\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    tile_size = 4\n    return _conv2d_winograd_nhwc_impl(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        tile_size,\n        pre_computed=pre_computed,\n        write_cache_level=2,\n        auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape=meta_schedule_original_shape,\n    )\n\n\n@tvm.target.generic_func\ndef conv2d_winograd_nchw(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    pre_computed=False,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd in NCHW layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n    weight : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n    out_dtype : str, optional\n        Specifies the output data type.\n    pre_computed: bool\n        Whether the kernel is precomputed\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    tile_size = 4\n    return _conv2d_winograd_nchw_impl(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        tile_size,\n        pre_computed,\n        auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape,\n    )\n\n\ndef _conv2d_winograd_nhwc_impl(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    tile_size,\n    pre_computed=False,\n    write_cache_level=None,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd implementation in NHWC layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n    weight : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n    out_dtype : str, optional\n        Specifies the output data type.\n    tile_size : int\n        The size of the tile to use for the Winograd filter\n    pre_computed: bool = False\n        Whether the kernel is precomputed\n    write_cache_level: Optional[int] = None\n        The cache level to write to in multi-level tiling rule in MetaSchedule.\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    N, H, W, CI = get_const_tuple(data.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    if meta_schedule_original_shape:\n        auto_scheduler.rewrite_tensor_shape(weight, meta_schedule_original_shape)\n\n    assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n    if not pre_computed:\n        KH, KW, CI, CO = get_const_tuple(weight.shape)\n    else:\n        if auto_scheduler_rewritten_layout:\n            H_CAT, W_CAT, CO, CI = get_const_tuple(\n                auto_scheduler.get_shape_from_rewritten_layout(\n                    auto_scheduler_rewritten_layout, [\"eps\", \"nu\", \"co\", \"ci\"]\n                )\n            )\n            auto_scheduler.remove_index_check(weight)\n        else:\n            H_CAT, W_CAT, CO, CI = get_const_tuple(weight.shape)\n\n        KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1\n\n    pad_t, pad_l, pad_b, pad_r = get_pad_tuple(padding, (KH, KW))\n    HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides\n    assert HSTR == 1 and WSTR == 1 and KH == 3 and KW == 3\n\n    r = KW\n    m = tile_size\n    alpha = m + r - 1\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    H = (H + pad_t + pad_b - KH) // HSTR + 1\n    W = (W + pad_l + pad_r - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n    P = N * nH * nW\n\n    pad_extra = (nW - 1) * m + alpha - (H + pad_t + pad_b)\n    data_pad = pad(\n        data,\n        (0, pad_t, pad_l, 0),\n        (0, pad_b + pad_extra, pad_r + pad_extra, 0),\n        name=\"data_pad\",\n        attrs={\"schedule_rule\": \"None\"},\n    )\n\n    if not pre_computed:\n        r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n        r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n        kernel_pack = te.compute(\n            (alpha, alpha, CO, CI),\n            lambda eps, nu, co, ci: te.sum(\n                weight[r_kh, r_kw, ci, co] * G[eps, r_kh] * G[nu, r_kw],\n                axis=[r_kh, r_kw],\n            ),\n            name=\"kernel_pack\",\n        )\n        bgemm_attrs = {}\n    else:\n        kernel_pack = weight\n        bgemm_attrs = {\"layout_free_placeholders\": [kernel_pack]}\n    if write_cache_level is not None:\n        if not isinstance(write_cache_level, int):\n            bgemm_attrs[\"meta_schedule.write_cache_level\"] = write_cache_level\n        else:\n            bgemm_attrs[\"meta_schedule.write_cache_level\"] = [write_cache_level]\n\n    # pack data tile\n    input_tile = te.compute(\n        (alpha, alpha, P, CI),\n        lambda eps, nu, p, ci: data_pad[\n            p // (nH * nW),\n            ((p // nW) % nH) * m + eps,\n            (p % nW) * m + nu,\n            ci,\n        ],\n        name=\"input_tile\",\n        attrs={\"schedule_rule\": \"None\"},\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    data_pack = te.compute(\n        (alpha, alpha, P, CI),\n        lambda eps, nu, p, ci: te.sum(\n            input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu],\n            axis=[r_a, r_b],\n        ),\n        name=\"data_pack\",\n        attrs={\n            \"auto_scheduler_simplify_const_tensor_indices\": [\"eps\", \"nu\", \"r_a\", \"r_b\"],\n            \"schedule_rule\": \"conv2d_nhwc_winograd_data_pack\",\n        },\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, P, CO),\n        lambda eps, nu, p, co: te.sum(\n            data_pack[eps, nu, p, ci] * kernel_pack[eps, nu, co, ci],\n            axis=[ci],\n        ),\n        name=\"bgemm\",\n        attrs=bgemm_attrs,\n    )\n\n    if auto_scheduler_rewritten_layout:\n        bgemm = auto_scheduler.rewrite_compute_body(bgemm, auto_scheduler_rewritten_layout)\n\n    # inverse transform\n\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    inverse = te.compute(\n        (m, m, P, CO),\n        lambda vh, vw, p, co: te.sum(\n            bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw],\n            axis=[r_a, r_b],\n        ),\n        name=\"inverse\",\n        attrs={\n            \"auto_scheduler_simplify_const_tensor_indices\": [\"vh\", \"vw\", \"r_a\", \"r_b\"],\n            \"schedule_rule\": \"conv2d_nhwc_winograd_inverse\",\n        },\n    )\n\n    # output\n    output = te.compute(\n        (N, H, W, CO),\n        lambda n, h, w, co: inverse[\n            h % m,\n            w % m,\n            n * nH * nW + (h // m) * nW + (w // m),\n            co,\n        ],\n        name=\"conv2d_winograd\",\n    )\n\n    return output\n\n\ndef _conv2d_winograd_nchw_impl(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    tile_size,\n    pre_computed=False,\n    write_cache_level=None,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"\n    write_cache_level: Optional[int] = None\n        The cache level to write to in multi-level tiling rule in MetaSchedule.\n    \"\"\"\n    del auto_scheduler_rewritten_layout\n\n    N, CI, H, W = get_const_tuple(data.shape)\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n    if meta_schedule_original_shape:\n        auto_scheduler.rewrite_tensor_shape(weight, meta_schedule_original_shape)\n\n    assert (dilation_h, dilation_w) == (1, 1), \"Does not support dilation\"\n    HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides\n\n    if not pre_computed:  # kernel tensor is raw tensor, do strict check\n        CO, CI, KH, KW = get_const_tuple(weight.shape)\n        alpha = KW + tile_size - 1\n        assert HSTR == 1 and WSTR == 1 and KH == KW\n    else:\n        alpha, _, CI, CO = get_const_tuple(weight.shape)\n        KH = KW = alpha + 1 - tile_size\n        assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1\n\n    pad_t, pad_l, pad_b, pad_r = get_pad_tuple(padding, (KH, KW))\n    assert HSTR == 1 and WSTR == 1 and KH == 3 and KW == 3\n\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW))\n    data_pad = pad(\n        data,\n        (0, 0, pt, pl),\n        (0, 0, pb, pr),\n        name=\"data_pad\",\n    )\n\n    r = KW\n    m = tile_size\n    A, B, G = winograd_transform_matrices(m, r, out_dtype)\n\n    H = (H + pt + pb - KH) // HSTR + 1\n    W = (W + pl + pr - KW) // WSTR + 1\n    nH, nW = (H + m - 1) // m, (W + m - 1) // m\n\n    P = N * nH * nW if isinstance(N, int) else nH * nW\n\n    # transform kernel\n    if not pre_computed:\n        r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n        r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n        kernel_pack = te.compute(\n            (alpha, alpha, CI, CO),\n            lambda eps, nu, ci, co: te.sum(\n                weight[co, ci, r_kh, r_kw] * G[eps, r_kh] * G[nu, r_kw],\n                axis=[r_kh, r_kw],\n            ),\n            name=\"kernel_pack\",\n        )\n        bgemm_attrs = {}\n    else:\n        kernel_pack = weight\n        bgemm_attrs = {\"layout_free_placeholders\": [kernel_pack]}\n    if write_cache_level is not None:\n        if not isinstance(write_cache_level, int):\n            bgemm_attrs[\"meta_schedule.write_cache_level\"] = write_cache_level\n        else:\n            bgemm_attrs[\"meta_schedule.write_cache_level\"] = [write_cache_level]\n\n    # pack data tile\n    input_tile = te.compute(\n        (CI, P, alpha, alpha),\n        lambda ci, p, eps, nu: data_pad[\n            p // (nH * nW),\n            ci,\n            ((p // nW) % nH) * m + eps,\n            (p % nW) * m + nu,\n        ],\n        name=\"input_tile\",\n        attrs={\"schedule_rule\": \"None\"},\n    )\n\n    # transform data\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    data_pack = te.compute(\n        (alpha, alpha, CI, P),\n        lambda eps, nu, ci, p: te.sum(\n            input_tile[ci, p, r_a, r_b] * B[r_a, eps] * B[r_b, nu],\n            axis=[r_a, r_b],\n        ),\n        name=\"data_pack\",\n        attrs={\n            \"schedule_rule\": \"conv2d_nchw_winograd_data_pack\",\n        },\n    )\n\n    # do batch gemm\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    bgemm = te.compute(\n        (alpha, alpha, CO, P),\n        lambda eps, nu, co, p: te.sum(\n            data_pack[eps, nu, ci, p] * kernel_pack[eps, nu, ci, co],\n            axis=[ci],\n        ),\n        name=\"bgemm\",\n        attrs=bgemm_attrs,\n    )\n\n    # inverse transform\n    r_a = te.reduce_axis((0, alpha), \"r_a\")\n    r_b = te.reduce_axis((0, alpha), \"r_b\")\n    inverse = te.compute(\n        (CO, P, m, m),\n        lambda co, p, vh, vw: te.sum(\n            bgemm[r_a, r_b, co, p] * A[r_a, vh] * A[r_b, vw],\n            axis=[r_a, r_b],\n        ),\n        name=\"inverse\",\n        attrs={\n            \"schedule_rule\": \"conv2d_nchw_winograd_inverse\",\n        },\n    )\n\n    # output\n    output = te.compute(\n        (N, CO, H, W),\n        lambda n, co, h, w: inverse[\n            co,\n            n * nH * nW + (h // m) * nW + (w // m),\n            h % m,\n            w % m,\n        ],\n        name=\"conv2d_winograd\",\n    )\n\n    return output\n\n\ndef conv2d_winograd_nhwc_without_weight_transform(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd without layout transform in NHWC layout.\n    This is a clean version to be used by the auto-scheduler for both CPU and GPU.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n    weight : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n    out_dtype : str, optional\n        Specifies the output data type.\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n\n    return conv2d_winograd_nhwc(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        pre_computed=True,\n        auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape=meta_schedule_original_shape,\n    )\n\n\ndef conv2d_winograd_nchw_without_weight_transform(\n    data,\n    weight,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"Conv2D Winograd without layout transform in NCHW layout.\n    This is a clean version to be used by meta-schedule for both CPU and GPU.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n    weight : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n    out_dtype : str, optional\n        Specifies the output data type.\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    return conv2d_winograd_nchw(\n        data,\n        weight,\n        strides,\n        padding,\n        dilation,\n        out_dtype,\n        pre_computed=True,\n        auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape=meta_schedule_original_shape,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Transposed 2D convolution operators (sometimes called Deconvolution).\"\"\"\nimport collections\n\nimport tvm\nfrom tvm import relay, te\n\nfrom ..utils import simplify\nfrom .dilate import dilate\nfrom .pad import pad\nfrom .utils import get_pad_tuple\n\n\ndef _ntuple(n):\n    def parse(x):\n        if isinstance(x, collections.abc.Iterable):\n            assert len(x) == n, f\"Input can only have {n} elements, but got {len(x)} instead: {x}.\"\n            return x\n        return tuple(repeat(x, n))\n\n    return parse\n\n\n_single = _ntuple(1)\n_pair = _ntuple(2)\n_triple = _ntuple(3)\n_quadruple = _ntuple(4)\n\n\ndef conv2d_transpose_nchw(Input, Filter, strides, padding, out_dtype, output_padding):\n    \"\"\"Transposed 2D convolution nchw forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [in_channel, num_filter, filter_height, filter_width]\n\n    strides : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    out_dtype : str\n        The output data type. This is used for mixed precision.\n\n    output_padding : tuple of ints\n        Used to get the right output shape for gradients\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return declaration_conv2d_transpose_impl(\n        Input, Filter, strides, padding, out_dtype, output_padding=output_padding\n    )\n\n\ndef conv2d_transpose_nchw_preprocess(data, kernel, strides, padding, out_dtype, output_padding):\n    \"\"\"Preprocess data and kernel to make the compute pattern\n    of conv2d_transpose the same as conv2d\"\"\"\n    batch, in_c, in_h, in_w = data.shape\n    _, out_c, filter_h, filter_w = kernel.shape\n    stride_h, stride_w = strides\n    opad_h, opad_w = output_padding\n    assert opad_h < stride_h and opad_w < stride_w\n    # dilate data\n    data_dilate = dilate(data, [1, 1, stride_h, stride_w], name=\"data_dilate\")\n    # pad data\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w))\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom + opad_h\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad_w\n    data_pad = pad(\n        data_dilate, [0, 0, bpad_top, bpad_left], [0, 0, bpad_bottom, bpad_right], name=\"data_pad\"\n    )\n    # transform kernel layout from IOHW to OIHW, and rotate kernel by 180 degrees\n    kernel_transform = te.compute(\n        (out_c, in_c, filter_h, filter_w),\n        lambda o, i, h, w: kernel[i][o][filter_h - 1 - h][filter_w - 1 - w],\n        name=\"kernel_transform\",\n    )\n    return data_pad, kernel_transform\n\n\ndef declaration_conv2d_transpose_impl(data, kernel, strides, padding, out_dtype, output_padding):\n    \"\"\"Implementation of conv2d transpose\"\"\"\n    data_pad, kernel_transform = conv2d_transpose_nchw_preprocess(\n        data, kernel, strides, padding, out_dtype, output_padding\n    )\n    batch, in_c, in_h, in_w = data_pad.shape\n    out_c, _, filter_h, filter_w = kernel_transform.shape\n\n    # convolution stage\n    out_c = simplify(out_c)\n\n    out_h = simplify(in_h - filter_h + 1)\n    out_w = simplify(in_w - filter_w + 1)\n    dc = te.reduce_axis((0, in_c), name=\"dc\")\n    dh = te.reduce_axis((0, filter_h), name=\"dh\")\n    dw = te.reduce_axis((0, filter_w), name=\"dw\")\n\n    Output = te.compute(\n        (batch, out_c, out_h, out_w),\n        lambda b, c, h, w: te.sum(\n            data_pad[b, dc, h + dh, w + dw].astype(out_dtype)\n            * kernel_transform[c, dc, dh, dw].astype(out_dtype),\n            axis=[dc, dh, dw],\n        ),\n        tag=\"conv2d_transpose_nchw\",\n    )\n\n    return Output\n\n\ndef group_conv2d_transpose_nchw(data, kernel, stride, padding, out_dtype, output_padding, groups):\n    \"\"\"Group convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel : tvm.te.Tensor\n        4-D with shape [in_channel, out_channel // groups, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    out_dtype : str\n        The output data type. This is used for mixed precision.\n\n    output_padding : tuple of ints\n        Used to get the right output shape for gradients\n\n    groups : int\n        number of groups\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    if groups == 1:\n        return conv2d_transpose_nchw(data, kernel, stride, padding, out_dtype, output_padding)\n\n    # some pre-processing and prelimnary checks\n    if out_dtype is None:\n        out_dtype = data.dtype\n\n    batch, in_channels, in_h, in_w = data.shape\n    _, out_c, filter_h, filter_w = kernel.shape\n    assert (\n        in_channels % groups == 0\n    ), f\"input channels {in_channels} must divide group size {groups}\"\n    # assert out_c % groups == 0, f\"output channels {in_c} must divide group size {groups}\"\n\n    strides = _pair(stride)\n    # padding = _pair(padding)\n    # output_padding = _pair(output_padding)\n    # dilation = _pair(dilation)\n\n    stride_h, stride_w = strides\n    opad_h, opad_w = output_padding\n    assert (\n        opad_h < stride_h and opad_w < stride_w\n    ), f\"[{output_padding}] opad_h:{opad_h} < stride_h:{stride_h} \\\n        and opad_w:{opad_w} < stride_w:{stride_w} does not satisfy.\"\n    # dilate data\n    data_dilate = dilate(data, [1, 1, stride_h, stride_w], name=\"data_dilate\")\n    # pad data\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w))\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom + opad_h\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad_w\n    data_pad = pad(\n        data_dilate, [0, 0, bpad_top, bpad_left], [0, 0, bpad_bottom, bpad_right], name=\"data_pad\"\n    )\n    # transform kernel layout from IOHW to OIHW, and rotate kernel by 180 degrees\n    kernel_transform = te.compute(\n        (out_c, in_channels, filter_h, filter_w),\n        lambda i, o, h, w: kernel[o][i][filter_h - 1 - h][filter_w - 1 - w],\n        name=\"kernel_transform\",\n    )\n\n    batch, in_channels, in_h, in_w = data_pad.shape\n    out_c, _, filter_h, filter_w = kernel_transform.shape\n\n    # convolution stage\n    out_channels = simplify(out_c * groups)\n\n    out_h = simplify(in_h - filter_h + 1)\n    out_w = simplify(in_w - filter_w + 1)\n    dc = te.reduce_axis((0, in_channels // groups), name=\"dc\")\n    dh = te.reduce_axis((0, filter_h), name=\"dh\")\n    dw = te.reduce_axis((0, filter_w), name=\"dw\")\n\n    # data: batch, in_channels, out_h, out_w\n    # weight: out_channels // G, in_channels, out_h, out_w\n    return te.compute(\n        (batch, out_channels, out_h, out_w),\n        lambda b, c, h, w: te.sum(\n            data_pad[\n                b, c // (out_channels // groups) * (in_channels // groups) + dc, h + dh, w + dw\n            ].astype(out_dtype)\n            * kernel_transform[\n                c % (out_channels // groups),\n                c // (out_channels // groups) * (in_channels // groups) + dc,\n                dh,\n                dw,\n            ].astype(out_dtype),\n            axis=[dc, dh, dw],\n        ),\n        tag=\"group_conv2d_transpose_nchw\",\n    )\n\n\ndef layout_transform(tensor: \"relay.Expr\", current_layout: str, desired_layout: str):\n    \"\"\"Transform a tensor with the current layout to the desired layout.\n\n    E.g. layout_transform(t, \"NCHW\", \"CNHW\") --> relay.transpose(t, [1, 0, 2, 3])\n\n    Parameters\n    ----------\n    tensor: relay.Expr\n        The Tensor to transpose\n\n    current_layout: str\n        The current layout e.g. NCHW or OIHW\n\n    desired_layout: str\n        The desired layout, must be compatible with current_layout\n\n    Returns\n    -------\n    The layout_transformed tensor.\n    \"\"\"\n    if sorted(current_layout) != sorted(desired_layout):\n        raise ValueError(f\"Incompatible layouts: {current_layout} vs {desired_layout}\")\n\n    if current_layout == desired_layout:\n        return tensor\n\n    current_layout_map = {c: i for i, c in enumerate(current_layout)}\n    desired_layout_map = {c: i for i, c in enumerate(desired_layout)}\n\n    axes = [None] * len(current_layout)\n    for c, i in desired_layout_map.items():\n        axes[i] = current_layout_map[c]\n    return relay.transpose(tensor, axes=axes)\n\n\n@tvm.target.generic_func\ndef conv2d_transpose_legalize(attrs, inputs, types):\n    \"\"\"Legalizes Transposed 2D convolution op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current Transposed 2D convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    data, kernel = inputs\n    kernel_layout = attrs[\"kernel_layout\"]\n\n    target = tvm.target.Target.current(allow_none=True)\n    if target and \"cudnn\" in target.libs:\n        # cuDNN backend can directly operate on NHWC layout.\n        return None\n\n    if attrs[\"data_layout\"] == \"NHWC\":\n        kernel = layout_transform(kernel, kernel_layout, \"IOHW\")\n\n        # Set new attrs for conv2d_transpose.\n        new_attrs = {k: attrs[k] for k in attrs.keys()}\n        new_attrs[\"data_layout\"] = \"NCHW\"\n        # layout of kernel should be IOHW, but kernel_layout will be swapped - OIHW\n        new_attrs[\"kernel_layout\"] = \"IOHW\"\n\n        # Convert data to NCHW.\n        data = relay.transpose(data, axes=(0, 3, 1, 2))\n        deconv = relay.nn.conv2d_transpose(data, kernel, **new_attrs)\n        # Convert back to original NHWC layout.\n        out = relay.transpose(deconv, axes=(0, 2, 3, 1))\n        return out\n\n    if attrs[\"data_layout\"] == \"NCHW\":\n        kernel = layout_transform(kernel, kernel_layout, \"IOHW\")\n        new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n        # layout of kernel should be IOHW, but kernel_layout will be swapped - OIHW\n        new_attrs[\"kernel_layout\"] = \"IOHW\"\n        return relay.nn.conv2d_transpose(data, kernel, **new_attrs)\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv3d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin, no-else-return\n\"\"\"Conv3D operators\"\"\"\nimport tvm\nfrom tvm import te\n\nfrom ..utils import get_const_tuple\nfrom .conv2d import conv\nfrom .winograd_util import winograd_transform_matrices\n\n\ndef conv3d_ncdhw(Input, Filter, stride, padding, dilation, groups, out_dtype=None):\n    \"\"\"Conv3D operator in NCDHW layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [strid_depth, stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    return conv(Input, Filter, stride, padding, dilation, groups, \"NCDHW\", \"OIDHW\", out_dtype)\n\n\ndef conv3d_ndhwc(\n    Input,\n    Filter,\n    stride,\n    padding,\n    dilation,\n    groups,\n    out_dtype=\"float32\",\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_origin_shape=None,\n):\n    \"\"\"Convolution operator in NDHWC layout.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_depth, in_height, in_width, in_channel]\n\n    Filter : tvm.te.Tensor\n        5-D with shape [filter_depth, filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups.\n\n    out_dtype: str = \"float32\",\n        The type of output tensor\n\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n\n    meta_schedule_origin_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_depth, out_height, out_width, out_channel]\n    \"\"\"\n    return conv(\n        Input,\n        Filter,\n        stride,\n        padding,\n        dilation,\n        groups,\n        \"NDHWC\",\n        \"DHWIO\",\n        out_dtype,\n        auto_scheduler_rewritten_layout,\n        meta_schedule_origin_shape,\n    )\n\n\ndef conv3d_winograd_weight_transform(kernel, tile_size):\n    \"\"\"Weight transformation for 3D winograd\n\n    Parameters\n    ----------\n    kernel: Tensor\n        The raw kernel tensor with layout \"NCDHW\".\n    tile_size: int\n        Tile size of winograd transform. e.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [alpha, alpha, alpha, CO, CI]\n    \"\"\"\n    CO, CI, KD, KH, KW = get_const_tuple(kernel.shape)\n\n    depth_transform = 2 < KD < 8 and KD == KH\n\n    if depth_transform:\n        assert KD == KH == KW, \"Only support NxNxN kernel\"\n    else:\n        assert KH == KW, \"Only supports DxNxN kernel\"\n\n    r = tile_size + KH - 1\n\n    r_kh = te.reduce_axis((0, KH), name=\"r_kh\")\n    r_kw = te.reduce_axis((0, KW), name=\"r_kw\")\n    _, _, G = winograd_transform_matrices(tile_size, KH, kernel.dtype)\n    if depth_transform:\n        shape = (r, r, r, CO, CI)\n        r_kd = te.reduce_axis((0, KD), name=\"r_kd\")\n        return te.compute(\n            shape,\n            lambda omg, eps, nu, co, ci: te.sum(\n                kernel[co][ci][r_kd][r_kh][r_kw] * G[omg][r_kd] * G[eps][r_kh] * G[nu][r_kw],\n                axis=[r_kd, r_kh, r_kw],\n            ),\n            name=\"transform_weight\",\n        )\n    else:\n        shape = (r, r, KD, CO, CI)\n        return te.compute(\n            shape,\n            lambda eps, nu, d, co, ci: te.sum(\n                kernel[co][ci][d][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw]\n            ),\n            name=\"transform_weight\",\n        )\n\n\n@tvm.target.generic_func\ndef conv3d_alter_layout(attrs, inputs, tinfos, out_type):\n    \"\"\"Change Conv3D layout.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : tvm.relay.Expr\n        Grouped input symbols\n    tinfos : list\n        Input shape and dtype\n    out_type: type\n        The output type\n\n    Note\n    ----\n    Unlike other TOPI functions, this function operates on both graph level and operator level.\n    \"\"\"\n    # not to change by default\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/conv3d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Transposed 3D convolution operators (sometimes called Deconvolution).\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom .dilate import dilate\nfrom .pad import pad\nfrom .utils import get_pad_tuple3d\nfrom ..utils import simplify\n\n\ndef conv3d_transpose_ncdhw(Input, Filter, strides, padding, out_dtype, output_padding):\n    \"\"\"Transposed 3D convolution ncdhw forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        5-D with shape [in_channel, num_filter, filter_depth, filter_height, filter_width]\n\n    strides : int or a list/tuple of three ints\n        The spatial stride along depth,height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    out_dtype : str\n        The output data type. This is used for mixed precision.\n\n    output_padding : tuple of ints\n        Used to get the right output shape for gradients\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    return declaration_conv3d_transpose_impl(\n        Input, Filter, strides, padding, out_dtype, output_padding\n    )\n\n\ndef conv3d_transpose_ncdhw_preprocess(data, kernel, strides, padding, out_dtype, output_padding):\n    \"\"\"Preprocess data and kernel to make the compute pattern\n    of conv3d_transpose the same as conv3d\"\"\"\n    batch, in_c, in_d, in_h, in_w = data.shape\n    _, out_c, filter_d, filter_h, filter_w = kernel.shape\n    stride_d, stride_h, stride_w = strides\n    opad_d, opad_h, opad_w = output_padding\n    assert opad_d < stride_d and opad_h < stride_h and opad_w < stride_w\n    # dilate data\n    data_dilate = dilate(data, [1, 1, stride_d, stride_h, stride_w], name=\"data_dilate\")\n    # pad data\n    fpad_front, fpad_top, fpad_left, fpad_back, fpad_bottom, fpad_right = get_pad_tuple3d(\n        padding, (filter_d, filter_h, filter_w)\n    )\n    bpad_front = filter_d - 1 - fpad_front\n    bpad_back = filter_d - 1 - fpad_back + opad_d\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom + opad_h\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad_w\n    data_pad = pad(\n        data_dilate,\n        [0, 0, bpad_front, bpad_top, bpad_left],\n        [0, 0, bpad_back, bpad_bottom, bpad_right],\n        name=\"data_pad\",\n    )\n    # transform kernel layout from IODHW to OIDHW, and rotate kernel by 180 degrees\n    kernel_transform = te.compute(\n        (out_c, in_c, filter_d, filter_h, filter_w),\n        lambda o, i, d, h, w: kernel[i][o][filter_d - 1 - d][filter_h - 1 - h][filter_w - 1 - w],\n        name=\"kernel_transform\",\n    )\n    return data_pad, kernel_transform\n\n\ndef declaration_conv3d_transpose_impl(data, kernel, strides, padding, out_dtype, output_padding):\n    \"\"\"Implementation of conv3d transpose\"\"\"\n    data_pad, kernel_transform = conv3d_transpose_ncdhw_preprocess(\n        data, kernel, strides, padding, out_dtype, output_padding\n    )\n    batch, in_c, in_d, in_h, in_w = data_pad.shape\n    out_c, _, filter_d, filter_h, filter_w = kernel_transform.shape\n    stride_d, stride_h, stride_w = strides\n\n    # convolution stage\n    out_c = simplify(out_c)\n    out_d = simplify(in_d - filter_d + 1)\n    out_h = simplify(in_h - filter_h + 1)\n    out_w = simplify(in_w - filter_w + 1)\n    dc = te.reduce_axis((0, in_c), name=\"dc\")\n    dd = te.reduce_axis((0, filter_d), name=\"dd\")\n    dh = te.reduce_axis((0, filter_h), name=\"dh\")\n    dw = te.reduce_axis((0, filter_w), name=\"dw\")\n\n    Output = te.compute(\n        (batch, out_c, out_d, out_h, out_w),\n        lambda b, c, d, h, w: te.sum(\n            data_pad[b, dc, d + dd, h + dh, w + dw].astype(out_dtype)\n            * kernel_transform[c, dc, dd, dh, dw].astype(out_dtype),\n            axis=[dc, dd, dh, dw],\n        ),\n        tag=\"conv3d_transpose_ncdhw\",\n    )\n\n    return Output\n\n\n@tvm.target.generic_func\ndef conv3d_transpose_legalize(attrs, inputs, types):\n    \"\"\"Legalizes Transposed 3D convolution op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current Transposed 3D convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    if attrs[\"data_layout\"] == \"NDHWC\":\n        data, kernel = inputs\n        kernel_layout = attrs[\"kernel_layout\"]\n        # Convert Kernel layout to IODHW\n        # kernel_layout is different from input kernel layout - IO is swapped\n        if kernel_layout == \"DHWIO\":\n            # input kernel layout is swapped to DHWOI\n            # output kernel layout will be IODHW\n            kernel = relay.transpose(kernel, axes=(4, 3, 0, 1, 2))\n        elif kernel_layout == \"DHWOI\":\n            # input kernel layout is swapped to DHWIO\n            # output kernel layout will be IODHW\n            kernel = relay.transpose(kernel, axes=(3, 4, 0, 1, 2))\n        elif kernel_layout == \"IODHW\":\n            # input kernel layout is swapped to OIDHW\n            # output kernel layout will be IODHW\n            kernel = relay.transpose(kernel, axes=(1, 0, 2, 3, 4))\n        elif kernel_layout == \"OIDHW\":\n            # input kernel layout is swapped to IODHW\n            # output kernel layout will be IODHW\n            pass\n        else:\n            # Skip legalize. Let relay.nn.conv2d_transpose to handle the case\n            return None\n\n        # Set new attrs for conv3d_transpose.\n        new_attrs = {k: attrs[k] for k in attrs.keys()}\n        new_attrs[\"data_layout\"] = \"NCDHW\"\n        # layout of kernel should be IODHW, but kernel_layout should be swapped - OIDHW\n        new_attrs[\"kernel_layout\"] = \"OIDHW\"\n\n        # Convert data to NCDHW.\n        data = relay.transpose(data, axes=(0, 4, 1, 2, 3))\n        deconv = relay.nn.conv3d_transpose(data, kernel, **new_attrs)\n        # Convert back to original NDHWC layout.\n        out = relay.transpose(deconv, axes=(0, 2, 3, 4, 1))\n        return out\n\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/correlation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Correlation operators\"\"\"\nfrom tvm import te\n\nfrom .pad import pad\nfrom ..utils import get_const_tuple\n\n\ndef correlation_nchw(\n    data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply\n):\n    \"\"\"Correlation operator in NCHW layout.\n\n    Parameters\n    ----------\n    data1 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    data2 : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    kernel_size: int\n        Kernel size for correlation, must be an odd number\n\n    max_displacement: int\n        Max displacement of Correlation\n\n    stride1: int\n        Stride for data1\n\n    stride2: int\n        Stride for data2 within the neightborhood centered around data1\n\n    padding : int or a list/tuple of 2 or 4 ints\n        Padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    is_multiply: bool\n        operation type is either multiplication or substraction\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    # pylint: disable=unnecessary-lambda, invalid-name\n    data_shape = get_const_tuple(data1.shape)\n    assert get_const_tuple(data2.shape) == data_shape, \"data1 and data2 should have the same shape\"\n    assert kernel_size > 0 and kernel_size % 2, \"kernel_size should be non-negative odd number\"\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 2:\n            pad_before_h = pad_after_h = padding[0]\n            pad_before_w = pad_after_w = padding[1]\n        elif len(padding) == 4:\n            pad_before_h, pad_before_w, pad_after_h, pad_after_w = padding\n        else:\n            raise ValueError(\"invalid padding\")\n    elif isinstance(padding, int):\n        pad_before_h = pad_after_h = pad_before_w = pad_after_w = padding\n    else:\n        raise ValueError(\"invalid padding\")\n    pad_before = [0, 0, pad_before_h, pad_before_w]\n    pad_after = [0, 0, pad_after_h, pad_after_w]\n    padded_data1 = pad(data1, pad_before, pad_after)\n    padded_data2 = pad(data2, pad_before, pad_after)\n\n    batch, channel, height, width = data_shape\n\n    kernel_radius = (kernel_size - 1) // 2\n    border_size = max_displacement + kernel_radius\n    displacement_radius = max_displacement // stride2\n    displacement_size = 2 * displacement_radius + 1\n\n    padded_width = width + pad_before_w + pad_after_w\n    padded_height = height + pad_before_h + pad_after_h\n    out_channel = displacement_size * displacement_size\n    out_height = (padded_height - 2 * border_size + stride1 - 1) // stride1\n    out_width = (padded_width - 2 * border_size + stride1 - 1) // stride1\n\n    rc = te.reduce_axis((0, channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_size), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_size), name=\"rx\")\n\n    if is_multiply:\n        corr_func = lambda x, y: x * y\n    else:\n        corr_func = lambda x, y: te.abs(x - y)\n\n    def _compute_correlation(n, q, i, j):\n        # location in data1\n        y1 = i * stride1 + max_displacement\n        x1 = j * stride1 + max_displacement\n        # location in data2\n        y2 = y1 + (te.indexdiv(q, displacement_size) - displacement_radius) * stride2\n        x2 = x1 + (te.indexmod(q, displacement_size) - displacement_radius) * stride2\n        return te.sum(\n            corr_func(padded_data1[n, rc, y1 + ry, x1 + rx], padded_data2[n, rc, y2 + ry, x2 + rx]),\n            axis=[rc, ry, rx],\n        )\n\n    correlation = te.compute(\n        (batch, out_channel, out_height, out_width),\n        lambda n, q, i, j: _compute_correlation(n, q, i, j),\n        tag=\"correlation_nchw\",\n    )\n    return correlation / (kernel_size * kernel_size * channel)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/deformable_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Deformable Conv2D operators\"\"\"\nimport tvm\nfrom tvm import te\n\nfrom .utils import get_pad_tuple\nfrom ..utils import get_const_tuple\nfrom ..cpp.utils import bilinear_sample_nchw, bilinear_sample_nhwc\n\n\ndef deformable_conv2d_nchw(\n    data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype\n):\n    \"\"\"Deformable conv2D operator in NCHW layout.\n\n    The deformable convolution operation is described in https://arxiv.org/abs/1703.06211\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    offset : tvm.te.Tensor\n        4-D with shape [batch, deformable_groups * filter_height * filter_width * 2,\n        out_height, out_width].\n\n    kernel : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    deformable_groups : int\n        number of deformable groups\n\n    groups : int\n        number of groups\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n\n    if isinstance(strides, int):\n        stride_h = stride_w = strides\n    else:\n        stride_h, stride_w = strides\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_channel, in_height, in_width = get_const_tuple(data.shape)\n    out_channel, channel, kernel_h, kernel_w = get_const_tuple(kernel.shape)\n    _, _, out_height, out_width = get_const_tuple(offset.shape)\n    assert in_channel % deformable_groups == 0, \"Input cahnnels must divide deformable group size\"\n    assert groups == 1, \"deformable_conv2d_nchw does not support groups > 1\"\n\n    ic_per_dgroup = channel // deformable_groups\n\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, _, _ = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w))\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    zero = tvm.tir.const(0.0, data.dtype)\n\n    def _bilinear(n, c, h, w):\n        outside = tvm.tir.any(h < 0, w < 0, h >= in_height, w >= in_width)\n        val = bilinear_sample_nchw(data, (n, c, h, w), in_height - 1, in_width - 1)\n        return tvm.tir.if_then_else(outside, zero, val)\n\n    data_deform = te.compute(\n        (batch, in_channel, kernel_h, kernel_w, out_height, out_width),\n        lambda n, c, kh, kw, y, x: _bilinear(\n            n,\n            c,\n            y * stride_h\n            - pad_top\n            + kh * dilation_h\n            + offset[\n                n, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2, y, x\n            ],\n            x * stride_w\n            - pad_left\n            + kw * dilation_w\n            + offset[\n                n,\n                c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2 + 1,\n                y,\n                x,\n            ],\n        ),\n        tag=\"data_deform\",\n    )\n    return te.compute(\n        (batch, out_channel, out_height, out_width),\n        lambda n, f, y, x: te.sum(\n            data_deform[n, rc, ry, rx, y, x].astype(out_dtype)\n            * kernel[f, rc, ry, rx].astype(out_dtype),\n            axis=[rc, ry, rx],\n        ),\n        tag=\"deformable_conv2d_nchw\",\n    )\n\n\ndef deformable_conv2d_nhwc(\n    data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype\n):\n    \"\"\"Deformable conv2D operator in NHWC layout.\n\n    The deformable convolution operation is described in https://arxiv.org/abs/1703.06211\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    offset : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width,\n                        deformable_groups * filter_height * filter_width * 2].\n\n    kernel : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of two ints\n        padding size, or [pad_height, pad_width]\n\n    dilation : int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    deformable_groups : int\n        number of deformable groups\n\n    groups : int\n        number of groups\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n\n    if isinstance(strides, int):\n        stride_h = stride_w = strides\n    else:\n        stride_h, stride_w = strides\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_height, in_width, in_channel = get_const_tuple(data.shape)\n    kernel_h, kernel_w, channel, out_channel = get_const_tuple(kernel.shape)\n    _, out_height, out_width, _ = get_const_tuple(offset.shape)\n    assert in_channel % deformable_groups == 0, \"Input cahnnels must divide deformable group size\"\n    assert groups == 1, \"deformable_conv2d_nchw does not support groups > 1\"\n\n    ic_per_dgroup = channel // deformable_groups\n\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, _, _ = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w))\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    zero = tvm.tir.const(0.0, data.dtype)\n\n    def _bilinear(n, h, w, c):\n        outside = tvm.tir.any(h < 0, w < 0, h >= in_height, w >= in_width)\n        val = bilinear_sample_nhwc(data, (n, h, w, c), in_height - 1, in_width - 1)\n        return tvm.tir.if_then_else(outside, zero, val)\n\n    data_deform = te.compute(\n        (batch, kernel_h, kernel_w, in_channel, out_height, out_width),\n        lambda n, kh, kw, c, y, x: _bilinear(\n            n,\n            y * stride_h\n            - pad_top\n            + kh * dilation_h\n            + offset[\n                n, y, x, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2\n            ],\n            x * stride_w\n            - pad_left\n            + kw * dilation_w\n            + offset[\n                n,\n                y,\n                x,\n                c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2 + 1,\n            ],\n            c,\n        ),\n        tag=\"data_deform\",\n    )\n    return te.compute(\n        (batch, out_height, out_width, out_channel),\n        lambda n, y, x, f: te.sum(\n            data_deform[n, ry, rx, rc, y, x].astype(out_dtype)\n            * kernel[ry, rx, rc, f].astype(out_dtype),\n            axis=[ry, rx, rc],\n        ),\n        tag=\"deformable_conv2d_nhwc\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"TVM operator fully connected compute.\"\"\"\nimport tvm\nfrom tvm import auto_scheduler, te\n\nfrom .. import tag\n\n\ndef matmul(\n    tensor_a,\n    tensor_b,\n    bias=None,\n    out_dtype=None,\n    transpose_a=False,\n    transpose_b=False,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"The default implementation of matmul in topi.\n\n    Parameters\n    ----------\n    tensor_a : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n\n    tensor_b : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim]\n\n    bias : Optional[tvm.te.Tensor]\n        1-D with shape [out_dim]\n\n    out_dtype : Optional[str]\n        The output type. This is used for mixed precision.\n\n    transpose_a : Optional[bool] = False\n        Whether the tensor_a is in transposed format.\n\n    transpose_b : Optional[bool] = False\n        Whether the tensor_b is in transposed format.\n\n    auto_scheduler_rewritten_layout: Optional[str] = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    # TODO(jcf94): Add multi-dim support for tensor_a\n    assert len(tensor_a.shape) == 2, \"only support 2-dim matmul\"\n    if bias is not None:\n        assert len(bias.shape) == 1\n    if out_dtype is None:\n        out_dtype = tensor_a.dtype\n    if transpose_a:\n        in_dim, batch = tensor_a.shape\n    else:\n        batch, in_dim = tensor_a.shape\n\n    if auto_scheduler_rewritten_layout:\n        # Infer shape for the rewritten layout\n        out_dim, red_dim = auto_scheduler.get_shape_from_rewritten_layout(\n            auto_scheduler_rewritten_layout, [\"j\", \"k\"]\n        )\n        auto_scheduler.remove_index_check(tensor_b)\n    elif meta_schedule_original_shape:\n        auto_scheduler.rewrite_tensor_shape(tensor_b, meta_schedule_original_shape)\n        if transpose_b:\n            out_dim, red_dim = tensor_b.shape\n        else:\n            red_dim, out_dim = tensor_b.shape\n    elif transpose_b:\n        out_dim, red_dim = tensor_b.shape\n    else:\n        red_dim, out_dim = tensor_b.shape\n\n    # cmp should be done by values\n    assert int(in_dim) == int(\n        red_dim\n    ), \"Inner dimensions of dense do not match. {in_dim} vs {red_dim}.\"\n\n    k = te.reduce_axis((0, in_dim), name=\"k\")\n    if (transpose_a, transpose_b) == (True, True):\n        compute_lambda = lambda i, j: te.sum(\n            tensor_a[k, i].astype(out_dtype) * tensor_b[j, k].astype(out_dtype), axis=k\n        )\n        compute_name = \"T_matmul_TT\"\n        compute_tag = \"matmul\"\n    elif (transpose_a, transpose_b) == (True, False):\n        compute_lambda = lambda i, j: te.sum(\n            tensor_a[k, i].astype(out_dtype) * tensor_b[k, j].astype(out_dtype), axis=k\n        )\n        compute_name = \"T_matmul_TN\"\n        compute_tag = \"matmul\"\n    elif (transpose_a, transpose_b) == (False, True):\n        compute_lambda = lambda i, j: te.sum(\n            tensor_a[i, k].astype(out_dtype) * tensor_b[j, k].astype(out_dtype), axis=k\n        )\n        compute_name = \"T_matmul_NT\"\n        # TODO(jcf94): Remove `dense` when `matmul` is finally ready\n        compute_tag = \"dense\"\n    else:  # (transpose_a, transpose_b) == (False, False):\n        compute_lambda = lambda i, j: te.sum(\n            tensor_a[i, k].astype(out_dtype) * tensor_b[k, j].astype(out_dtype), axis=k\n        )\n        compute_name = \"T_matmul_NN\"\n        compute_tag = \"matmul\"\n\n    mat = te.compute(\n        (batch, out_dim),\n        compute_lambda,\n        name=compute_name,\n        tag=compute_tag,\n        attrs={\"layout_free_placeholders\": [tensor_b]},\n    )\n\n    if bias is not None:\n        mat = te.compute(\n            (batch, out_dim),\n            lambda i, j: mat[i, j] + bias[j].astype(out_dtype),\n            tag=tag.BROADCAST,\n        )\n\n    if auto_scheduler_rewritten_layout:\n        mat = auto_scheduler.rewrite_compute_body(mat, auto_scheduler_rewritten_layout)\n\n    return mat\n\n\n@tvm.target.generic_func\ndef matmul_legalize(attrs, inputs, types):\n    \"\"\"Legalizes matmul op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current matmul\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # not to change by default\n    # pylint: disable=unused-argument\n    return None\n\n\ndef dense(\n    data,\n    weight,\n    bias=None,\n    out_dtype=None,\n    auto_scheduler_rewritten_layout=\"\",\n    meta_schedule_original_shape=None,\n):\n    \"\"\"The default implementation of dense in topi.\n    This is an alias of matmul_nt operator for data tensor in non-transposed format and weight\n    tensor in transposed format.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim]\n\n    bias : Optional[tvm.te.Tensor]\n        1-D with shape [out_dim]\n\n    out_dtype : Optional[str]\n        The output type. This is used for mixed precision.\n\n    auto_scheduler_rewritten_layout: str = \"\"\n        The layout after auto-scheduler's layout rewrite pass.\n\n    meta_schedule_original_shape: Optional[List[PrimExpr]] = None\n        The original shape of the input tensor.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    return matmul(\n        data,\n        weight,\n        bias,\n        out_dtype,\n        False,\n        True,\n        auto_scheduler_rewritten_layout,\n        meta_schedule_original_shape,\n    )\n\n\n@tvm.target.generic_func\ndef dense_legalize(attrs, inputs, types):\n    \"\"\"Legalizes dense op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current dense\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # not to change by default\n    # pylint: disable=unused-argument\n    return None\n\n\ndef dense_pack(data, weight, bias=None, out_dtype=None):\n    \"\"\"The default implementation of dense_pack in topi.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim]\n\n    bias : Optional[tvm.te.Tensor]\n        1-D with shape [out_dim]\n\n    out_dtype : Optional[str]\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n    M, K = get_const_tuple(data.shape)  # batch, in_dim\n    N, _, packw_bn = get_const_tuple(weight.shape)  # out_dim\n    N = N * packw_bn\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    k = te.reduce_axis((0, K), name=\"k\")\n    C = te.compute(\n        (M, N),\n        lambda y, x: te.sum(\n            data[y, k].astype(out_dtype)\n            * weight[idxdiv(x, packw_bn), k, idxmod(x, packw_bn)].astype(out_dtype),\n            axis=k,\n        ),\n        name=\"T_dense_pack\",\n        tag=\"dense_pack\",\n    )\n    if bias is not None:\n        C = te.compute((M, N), lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST)\n    return C\n\n\n@tvm.target.generic_func\ndef dense_alter_layout(attrs, inputs, tinfos, out_type):\n    \"\"\"Change dense layout.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : tvm.relay.Expr\n        Grouped input symbols\n    tinfos : list\n        Input shape and dtype\n    out_type: type\n        The output type\n\n    Note\n    ----\n    Unlike other TOPI functions, this function operates on both graph level and operator level.\n    \"\"\"\n    # not to change by default\n    return None\n\n\n@tvm.target.generic_func\ndef batch_matmul_legalize(attrs, inputs, types):\n    \"\"\"Legalizes batch_matmul op.\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current batch_matmul\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator depth_to_space compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\ndef depth_to_space(data, block_size, layout=\"NCHW\", mode=\"DCR\"):\n    \"\"\"Perform depth to space transformation on the data\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D tensor in either NCHW or NHWC layout.\n\n    block_size : int\n        Size of blocks to compose from channel dimension.\n\n    layout : string\n        Either NCHW or NHWC, indicating data layout.\n\n    mode : string\n        Either DCR or CDR, indicates how channels should be accessed.\n        In DCR, channels are interwoven in the Tensorflow style while\n        in CDR channels are accessed sequentially as in Pytorch.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        Output of shape [N, C / block_size**2, H * block_size, W * block_size]\n    \"\"\"\n    if layout == \"NCHW\":\n        in_n, in_c, in_h, in_w = data.shape\n        channel_factor = tvm.tir.truncdiv(in_c, (block_size * block_size))\n        output_shape = [in_n, channel_factor, in_h * block_size, in_w * block_size]\n    elif layout == \"NHWC\":\n        in_n, in_h, in_w, in_c = data.shape\n        channel_factor = tvm.tir.truncdiv(in_c, (block_size * block_size))\n        output_shape = [in_n, in_h * block_size, in_w * block_size, channel_factor]\n    else:\n        raise ValueError(\"Only NCHW and NHWC layouts are currently supported.\")\n\n    def _get_indices(*indices):\n        if layout == \"NCHW\":\n            n, c, y, x = indices\n        elif layout == \"NHWC\":\n            n, y, x, c = indices\n        return n, c, y, x\n\n    def _get_pixel(n, c, y, x):\n        block_x = tvm.tir.truncdiv(x, block_size)\n        block_y = tvm.tir.truncdiv(y, block_size)\n        idx_x = tvm.tir.truncmod(x, block_size)\n        idx_y = tvm.tir.truncmod(y, block_size)\n        if mode == \"DCR\":\n            channel_idx = channel_factor * ((block_size * idx_y) + idx_x) + c\n        else:\n            channel_idx = (c * block_size * block_size) + ((block_size * idx_y) + idx_x)\n\n        if layout == \"NCHW\":\n            output = data(n, channel_idx, block_y, block_x)\n        else:\n            output = data(n, block_y, block_x, channel_idx)\n        return output\n\n    def _compute(*indices):\n        n, c, y, x = _get_indices(*indices)\n        return _get_pixel(n, c, y, x)\n\n    return te.compute(output_shape, _compute, name=\"depth_to_space\", tag=tag.INJECTIVE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals, unused-argument\n\"\"\"Depthwise convolution operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom collections import namedtuple\nimport tvm\nfrom tvm import te\n\nfrom .dilate import dilate\nfrom .pad import pad\nfrom .utils import get_pad_tuple\nfrom ..utils import simplify, get_const_tuple\n\n# workload description of depthwise-conv2d\nWorkload = namedtuple(\n    \"Workload\",\n    [\n        \"in_dtype\",\n        \"out_dtype\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"kernel_h\",\n        \"kernel_w\",\n        \"padt\",\n        \"padl\",\n        \"padb\",\n        \"padr\",\n        \"dilation_h\",\n        \"dilation_w\",\n        \"stride_h\",\n        \"stride_w\",\n    ],\n)\n\n\ndef _get_workload(data, kernel, stride, padding, dilation, out_dtype, data_layout=\"NCHW\"):\n    \"\"\"Get the workload structure for a depthwise conv2d.\n\n    Input data and filter should use NCHW layout.\n    \"\"\"\n    if data_layout == \"NCHW\":\n        _, in_channel, height, width = get_const_tuple(data.shape)\n        filter_channel, channel_multiplier, kh, kw = get_const_tuple(kernel.shape)\n    elif data_layout == \"NHWC\":\n        _, height, width, in_channel = get_const_tuple(data.shape)\n        kh, kw, filter_channel, channel_multiplier = get_const_tuple(kernel.shape)\n    elif data_layout == \"NCHWc\":\n        _, in_channel_chunk, height, width, in_channel_block = get_const_tuple(data.shape)\n        in_channel = in_channel_chunk * in_channel_block\n        (\n            filter_channel_chunk,\n            cm_chunk,\n            kh,\n            kw,\n            cm_block,\n            filter_channel_block,\n        ) = get_const_tuple(kernel.shape)\n        filter_channel = filter_channel_chunk * filter_channel_block\n        channel_multiplier = cm_chunk * cm_block\n\n        assert (\n            in_channel_block == filter_channel_block\n        ), \"Incorrect dimensions, data has block size {}, but filter has block size {}\".format(\n            in_channel_block, filter_channel_block\n        )\n\n    else:\n        raise ValueError(\"Data layout {} not supported\".format(data_layout))\n\n    assert (\n        in_channel == filter_channel\n    ), \"Incorrect dimensions, data has {} channels but filter expects {} channels\".format(\n        in_channel, filter_channel\n    )\n\n    out_channel = filter_channel * channel_multiplier\n    dilation_h, dilation_w = (\n        dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    )\n    if isinstance(stride, (tuple, list)):\n        HSTR, WSTR = stride\n    else:\n        HSTR, WSTR = stride, stride\n    assert (data.dtype == kernel.dtype) or (\n        data.dtype == \"uint8\" and kernel.dtype == \"int8\"\n    ), \"Do not support inputs with different data types now. ' \\\n        '{} vs. {}\".format(\n        data.dtype, kernel.dtype\n    )\n    dilated_kernel_h = (kh - 1) * dilation_h + 1\n    dilated_kernel_w = (kw - 1) * dilation_w + 1\n    pt, pl, pb, pr = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w))\n    return Workload(\n        data.dtype,\n        out_dtype,\n        height,\n        width,\n        in_channel,\n        out_channel,\n        kh,\n        kw,\n        pt,\n        pl,\n        pb,\n        pr,\n        dilation_h,\n        dilation_w,\n        HSTR,\n        WSTR,\n    )\n\n\ndef depthwise_conv2d_nchw(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Depthwise convolution nchw forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [in_channel, channel_multiplier, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        The spatial stride, or (stride_height, stride_width).\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str, optional\n        Output data type\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    out_dtype = Input.dtype if out_dtype is None else out_dtype\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_channel, in_height, in_width = Input.shape\n    # shape of dilated kernel\n    filter_channel, channel_multiplier, filter_height, filter_width = Filter.shape\n\n    dilated_kernel_h = (filter_height - 1) * dilation_h + 1\n    dilated_kernel_w = (filter_width - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = simplify(in_channel * channel_multiplier)\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n\n    # padding stage\n    pad_before = [0, 0, pad_top, pad_left]\n    pad_after = [0, 0, pad_down, pad_right]\n    PaddedInput = pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    # depthconv stage\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    di = te.reduce_axis((0, filter_height), name=\"di\")\n    dj = te.reduce_axis((0, filter_width), name=\"dj\")\n    Output = te.compute(\n        (batch, out_channel, out_height, out_width),\n        lambda b, c, i, j: te.sum(\n            (\n                PaddedInput[\n                    b,\n                    idxdiv(c, channel_multiplier),\n                    i * stride_h + di * dilation_h,\n                    j * stride_w + dj * dilation_w,\n                ].astype(out_dtype)\n                * Filter[\n                    idxdiv(c, channel_multiplier), idxmod(c, channel_multiplier), di, dj\n                ].astype(out_dtype)\n            ),\n            axis=[di, dj],\n        ),\n        name=\"DepthwiseConv2d\",\n        tag=\"depthwise_conv2d_nchw\",\n    )\n    return Output\n\n\ndef depthwise_conv2d_nhwc(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Depthwise convolution nhwc forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    Filter : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]\n\n    stride : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of two ints\n        dilation size, or [dilation_height, dilation_width]\n\n    out_dtype: str, optional\n        Output data type\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    out_dtype = Input.dtype if out_dtype is None else out_dtype\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_height, in_width, in_channel = Input.shape\n    # shape of dilated kernel\n    filter_height, filter_width, filter_channel, channel_multiplier = Filter.shape\n\n    dilated_kernel_h = (filter_height - 1) * dilation_h + 1\n    dilated_kernel_w = (filter_width - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = simplify(in_channel * channel_multiplier)\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n\n    # padding stage\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    PaddedInput = pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    # depthconv stage\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    di = te.reduce_axis((0, filter_height), name=\"di\")\n    dj = te.reduce_axis((0, filter_width), name=\"dj\")\n    Output = te.compute(\n        (batch, out_height, out_width, out_channel),\n        lambda b, i, j, c: te.sum(\n            (\n                PaddedInput[\n                    b,\n                    i * stride_h + di * dilation_h,\n                    j * stride_w + dj * dilation_w,\n                    idxdiv(c, channel_multiplier),\n                ].astype(out_dtype)\n                * Filter[\n                    di, dj, idxdiv(c, channel_multiplier), idxmod(c, channel_multiplier)\n                ].astype(out_dtype)\n            ),\n            axis=[di, dj],\n        ),\n        name=\"DepthwiseConv2d\",\n        tag=\"depthwise_conv2d_nhwc\",\n    )\n    return Output\n\n\ndef depthwise_conv2d_backward_input_nhwc(Filter, Out_grad, oshape, ishape, stride, padding):\n    \"\"\"Depthwise convolution nhwc backward wrt input operator.\n\n    Parameters\n    ----------\n    Filter : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]\n\n    Out_grad : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n\n    stride : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n    \"\"\"\n    batch, in_h, in_w, in_c = ishape\n    _, out_h, out_w, out_c = oshape\n    filter_h, filter_w, _, channel_multiplier = Filter.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    dilated_out_grad = dilate(Out_grad, [1, stride_h, stride_w, 1], name=\"dilated_out_grad\")\n\n    # padding params in forward propagation\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w))\n    # padding params in backward propagation\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = (filter_h - 1 - fpad_bottom) + (stride_h - 1)\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = (filter_w - 1 - fpad_right) + (stride_w - 1)\n\n    padded_out_grad = pad(\n        dilated_out_grad,\n        [0, bpad_top, bpad_left, 0],\n        [0, bpad_bottom, bpad_right, 0],\n        name=\"padded_out_grad\",\n    )\n\n    dh = te.reduce_axis((0, filter_h), name=\"dh\")\n    dw = te.reduce_axis((0, filter_w), name=\"dw\")\n    dc = te.reduce_axis((0, channel_multiplier), name=\"dc\")\n\n    In_grad = te.compute(\n        (batch, in_h, in_w, in_c),\n        lambda b, h, w, c: te.sum(\n            padded_out_grad[b, h + dh, w + dw, c * channel_multiplier + dc]\n            * Filter[filter_h - 1 - dh, filter_w - 1 - dw, c, dc],\n            axis=[dh, dw, dc],\n        ),\n        tag=\"depthwise_conv2d_backward_input_nhwc\",\n    )\n\n    return In_grad\n\n\ndef depthwise_conv2d_backward_weight_nhwc(Input, Out_grad, oshape, fshape, stride, padding):\n    \"\"\"Depthwise convolution nhwc backward wrt weight operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    Out_grad : tvm.te.Tensor\n        4-D with shape [batch, out_height, out_width, out_channel]\n\n    stride : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]\n    \"\"\"\n    batch, out_h, out_w, out_c = oshape\n    filter_h, filter_w, _, channel_multiplier = fshape\n    in_c = Input.shape[3].value\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (filter_h, filter_w))\n\n    padded_in = pad(\n        Input, [0, pad_top, pad_left, 0], [0, pad_bottom, pad_right, 0], name=\"padded_in\"\n    )\n\n    dh = te.reduce_axis((0, Out_grad.shape[1].value), name=\"dh\")\n    dw = te.reduce_axis((0, Out_grad.shape[2].value), name=\"dw\")\n    db = te.reduce_axis((0, batch), name=\"db\")\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    Weight_grad = te.compute(\n        (filter_h, filter_w, in_c, channel_multiplier),\n        lambda fh, fw, c, m: te.sum(\n            Out_grad[db, dh, dw, c * channel_multiplier + idxmod(m, channel_multiplier)]\n            * padded_in[db, fh + dh * stride_h, fw + dw * stride_w, c],\n            axis=[db, dh, dw],\n        ),\n        tag=\"depthwise_conv2d_backward_weight_nhwc\",\n    )\n\n    return Weight_grad\n\n\ndef depthwise_conv2d_NCHWc(\n    Input, Filter, stride, padding, dilation, layout, out_layout, out_dtype=None\n):\n    \"\"\"Depthwise convolution NCHW[x]c forward operator.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    Filter : tvm.te.Tensor\n        6-D with shape [out_channel_chunk, 1, filter_height, filter_width, 1, out_channel_block]\n        In NCHWc depthwise convolution,\n        we group kernel's in_channel and channel_multiplier together then do the tiling.\n\n    stride : tuple of two ints\n        The spatial stride along height and width\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    dilation: int or a list/tuple of two ints\n         dilation size, or [dilation_height, dilation_width]\n\n    layout : str\n        Input data layout\n\n    out_layout : str\n        Output data layout\n\n    out_dtype: str, optional\n        Output data type\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block]\n    \"\"\"\n    raise ValueError(\"missing register for topi.nn.depthwise_conv2d_NCHWc\")\n\n\n@tvm.target.generic_func\ndef depthwise_conv2d_infer_layout(workload, cfg):\n    \"\"\"Infer input/output shapes and layouts from a workload and cfg.\n\n    Parameters\n    ----------\n    workload : tuple\n        conv2d workload\n\n    cfg : tuple\n        tvm.autotvm config\n\n    Returns\n    -------\n    Output : [tuple of tuple and str, tuple of tuple and str]\n        Input shapes and layouts, and output shapes and layouts\n    \"\"\"\n    raise ValueError(\"missing register for topi.nn.depthwise_conv2d_infer_layout\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/dilate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Dilation operators\"\"\"\nimport tvm\nfrom tvm import te\nfrom .. import utils\nfrom .. import tag\n\n\n@te.tag_scope(tag=tag.INJECTIVE + \",dilate\")\ndef dilate(data, strides, dilation_value=0.0, name=\"DilatedInput\"):\n    \"\"\"Dilate data with given dilation value (0 by default).\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D, can be any layout.\n\n    strides : list / tuple of n ints\n        Dilation stride on each dimension, 1 means no dilation.\n\n    dilation_value : int/float, optional\n        Value used to dilate the input.\n\n    name : str, optional\n        The name prefix operators generated\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        n-D, the same layout as data.\n    \"\"\"\n    n = len(data.shape)\n    if len(strides) != n:\n        raise ValueError(\"data dimension and strides size dismatch : %d vs %d\" % (n, len(strides)))\n    ana = tvm.arith.Analyzer()\n    out_shape = tuple(ana.simplify((data.shape[i] - 1) * strides[i] + 1) for i in range(n))\n\n    def _dilate(*indices):\n        not_zero = []\n        index_tuple = []\n        idxdiv = tvm.tir.indexdiv\n        idxmod = tvm.tir.indexmod\n        for i in range(n):\n            if not utils.equal_const_int(strides[i], 1):\n                index_tuple.append(idxdiv(indices[i], strides[i]))\n                not_zero.append(idxmod(indices[i], strides[i]).equal(0))\n            else:\n                index_tuple.append(indices[i])\n        if not_zero:\n            not_zero = tvm.tir.all(*not_zero)\n            return tvm.tir.if_then_else(\n                not_zero, data(*index_tuple), tvm.tir.const(dilation_value, data.dtype)\n            )\n        return data(*index_tuple)\n\n    return te.compute(out_shape, _dilate, name=name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/elemwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Elementwise operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..utils import get_const_int\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef relu(x):\n    \"\"\"Take relu of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return te.compute(x.shape, lambda *i: tvm.te.max(x(*i), tvm.tir.const(0, x.dtype)))\n\n\n@tvm.te.tag_scope(tag=tag.ELEMWISE)\ndef leaky_relu(x, alpha):\n    \"\"\"Take leaky relu of input x.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    alpha : float\n        The slope for the small gradient when x < 0\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n\n    def _compute(*indices):\n        value = x(*indices)\n        calpha = tvm.tir.const(alpha, value.dtype)\n        return tvm.tir.Select(value > 0, value, value * calpha)\n\n    return te.compute(x.shape, _compute)\n\n\n@tvm.te.tag_scope(tag=tag.BROADCAST)\ndef prelu(x, slope, axis=1):\n    \"\"\"PReLU.\n    It accepts two arguments: an input ``x`` and a weight array ``W``\n    and computes the output as :math:`PReLU(x) y = x > 0 ? x : W * x`,\n    where :math:`*` is an elementwise multiplication for each sample in the\n    batch.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n\n    slope : tvm.te.Tensor\n        Channelised slope tensor for prelu\n\n    axis : int\n        The axis where the channel data needs to be applied\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n\n    Links\n    -----\n    [http://arxiv.org/pdf/1502.01852v1.pdf]\n    \"\"\"\n\n    assert len(slope.shape) == 1\n    assert axis < len(x.shape)\n    assert get_const_int(slope.shape[0]) == get_const_int(x.shape[axis])\n\n    def _compute_channelwise(*indices):\n        xval = x(*indices)\n        return tvm.tir.Select(xval > 0, xval, xval * slope(indices[axis]))\n\n    return te.compute(x.shape, _compute_channelwise)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/fifo_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"FIFO buffer op\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..transform import concatenate, strided_slice\n\n\n@tvm.te.tag_scope(tag=tag.INJECTIVE + \",fifo_buffer\")\ndef fifo_buffer(data, buffer, axis):\n    \"\"\"\n    FIFO buffer to enable computation reuse in CNNs with sliding indow input\n\n    Compute equivalent of\n\n    .. code-block:: python\n\n        concat(buffer, data, axis=axis)\n        .slice_axis(axis=axis,\n                    begin=data.shape[axis],\n                    end=data.shape[axis]+buffer.shape[axis])\n\n    Useful for\n\n    * Encoding explicit re-use of computation in convolution ops operated on a sliding window input\n    * Implementing a FIFO queue to cache intermediate results, e.g. as in Fast WaveNet.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data\n    buffer : tvm.te.Tensor\n        Previous value of the FIFO buffer\n    axis : int\n        Specify which axis should be used for buffering\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        Updated value for the buffer\n    \"\"\"\n    assert len(data.shape) == len(buffer.shape), (\n        \"buffer and data must have same number of dimensions, \"\n        + \"buffer.shape = {}, data.shape = {}\".format(buffer.shape, data.shape)\n    )\n    assert len(buffer.shape) >= 1, \"Zero-dimension tensor not supported\"\n    assert 0 <= axis < len(buffer.shape), \"buffer axis out of range\"\n    for i in range(len(data.shape)):\n        if i == axis:\n            assert int(str(data.shape[i])) <= int(str(buffer.shape[i]))\n        else:\n            assert int(str(data.shape[i])) == int(str(buffer.shape[i]))\n\n    buflen = buffer.shape[axis]\n    data_size = data.shape[axis]\n\n    # Explicitly write out formula up to 4D, and then use concat+slice combo for 5D and higher\n    if len(buffer.shape) == 1:\n        return te.compute(\n            buffer.shape,\n            lambda i: tvm.tir.if_then_else(\n                i < buflen - data_size, buffer[i + data_size], data[i - buflen + data_size]\n            ),\n            name=\"new_buffer\",\n        )\n    if len(buffer.shape) == 2:\n        if axis == 0:\n            return te.compute(\n                buffer.shape,\n                lambda i, j: tvm.tir.if_then_else(\n                    i < buflen - data_size,\n                    buffer[i + data_size, j],\n                    data[i - buflen + data_size, j],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 1:\n            return te.compute(\n                buffer.shape,\n                lambda i, j: tvm.tir.if_then_else(\n                    j < buflen - data_size,\n                    buffer[i, j + data_size],\n                    data[i, j - buflen + data_size],\n                ),\n                name=\"new_buffer\",\n            )\n        assert False, \"Invalid value for axis; it should be at most {}\".format(len(buffer.shape))\n    elif len(buffer.shape) == 3:\n        if axis == 0:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k: tvm.tir.if_then_else(\n                    i < buflen - data_size,\n                    buffer[i + data_size, j, k],\n                    data[i - buflen + data_size, j, k],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 1:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k: tvm.tir.if_then_else(\n                    j < buflen - data_size,\n                    buffer[i, j + data_size, k],\n                    data[i, j - buflen + data_size, k],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 2:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k: tvm.tir.if_then_else(\n                    k < buflen - data_size,\n                    buffer[i, j, k + data_size],\n                    data[i, j, k - buflen + data_size],\n                ),\n                name=\"new_buffer\",\n            )\n        assert False, \"Invalid value for axis; it should be at most {}\".format(len(buffer.shape))\n    elif len(buffer.shape) == 4:\n        if axis == 0:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k, l: tvm.tir.if_then_else(\n                    i < buflen - data_size,\n                    buffer[i + data_size, j, k, l],\n                    data[i - buflen + data_size, j, k, l],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 1:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k, l: tvm.tir.if_then_else(\n                    j < buflen - data_size,\n                    buffer[i, j + data_size, k, l],\n                    data[i, j - buflen + data_size, k, l],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 2:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k, l: tvm.tir.if_then_else(\n                    k < buflen - data_size,\n                    buffer[i, j, k + data_size, l],\n                    data[i, j, k - buflen + data_size, l],\n                ),\n                name=\"new_buffer\",\n            )\n        if axis == 3:\n            return te.compute(\n                buffer.shape,\n                lambda i, j, k, l: tvm.tir.if_then_else(\n                    l < buflen - data_size,\n                    buffer[i, j, k, l + data_size],\n                    data[i, j, k, l - buflen + data_size],\n                ),\n                name=\"new_buffer\",\n            )\n        assert False, \"Invalid value for axis; it should be at most {}\".format(len(buffer.shape))\n    else:\n        # Implement FIFO buffer as combination of concat and slice\n        begin = [0] * len(buffer.shape)\n        begin[axis] = data.shape[axis]\n        end = list(buffer.shape[:])\n        end[axis] += data.shape[axis]\n        return strided_slice(concatenate((buffer, data), axis=axis), begin=begin, end=end)\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/flatten.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator flatten compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\n@tvm.te.tag_scope(tag=tag.INJECTIVE)\ndef flatten(data):\n    \"\"\"Flattens the input array into a 2-D array by collapsing the higher dimensions.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input array.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D array with collapsed higher dimensions.\n    \"\"\"\n    ishape = data.shape\n    dim = 1\n    for i in range(1, len(ishape)):\n        dim = dim * ishape[i]\n    oshape = [ishape[0], dim]\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    def unwrap(idx, shape):\n        index = []\n        for s in reversed(shape):\n            index.append(idxmod(idx, s))\n            idx = idxdiv(idx, s)\n        return list(reversed(index))\n\n    return te.compute(oshape, lambda i, j: data(i, *unwrap(j, ishape[1:])))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/layer_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Layer normalization operator.\"\"\"\nfrom .. import cpp\n\n\ndef layer_norm(data, gamma, beta, axis, epsilon=1e-5):\n    \"\"\"Layer normalization operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D with shape (d_0, d_1, ..., d_{N-1})\n\n    gamma: tvm.te.Tensor\n        K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k\n\n    beta: tvm.te.Tensor\n        Optional, K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k\n\n    axis : list of int\n        Axis over the normalization applied\n\n    epsilon : float\n        The epsilon value to avoid division by zero.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        N-D with shape (d_0, d_1, ..., d_{N-1})\n    \"\"\"\n    return cpp.nn.layer_norm(data, gamma, beta, axis, epsilon)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/local_response_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator for local response norm compute.\"\"\"\nfrom __future__ import absolute_import\nfrom .. import cpp\n\n\ndef lrn(data, size, axis=1, alpha=0.0001, beta=0.75, bias=2):\n    \"\"\"Perform the across channels local response normalisation\n    on the input data.\n\n    sum_sqr_up^i{x, y} = (bias+((alpha/size)* \\\n                                {sum_{j=max(0, i-size/2)}^{min(N-1,i+size/2)} \\\n                                     (data^j{x,y})^2}))^beta\n    output^i{x, y} = data^i{x, y}/sum_sqr_up^i{x, y}\n    N is the number for input channels\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    size : int\n        normalisation window size\n\n    axis : int\n        input data layout channel axis\n        default value is 1 for NCHW format\n\n    bias : float\n        offset to avoid dividing by 0\n\n    alpha : float\n        to be divided\n\n    beta : float\n        exponent\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D output with same shape\n    \"\"\"\n    return cpp.nn.lrn(data, size, axis, alpha, beta, bias)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/loss.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-argument\n\"\"\"Loss functions definitions.\"\"\"\nfrom __future__ import absolute_import\nfrom . import cpp\n\n\ndef nll_loss(predictions, targets, weights, reduction, ignore_index):\n    \"\"\"Negative log likelihood loss on the input data.\n\n    output{n, i_1, i_2, ..., i_k} = -p * w\n      where t = target{n, i_1, i_2, ..., i_k}\n            p = predictions{n, t, i_1, i_2, i_k}\n            w = weights{n, i_1, i_2, ..., i_k} if t != ignore_index else 0\n\n    result = reduction(output)\n\n    Parameters\n    ----------\n    predictions : tvm.te.Tensor\n        (k+2)-D with shape (N, C, d_1, d_2, ..., d_k),\n        where C is the number of target classes\n\n    targets : tvm.te.Tensor\n        (k+1)-D with shape (N, d_1, d_2, ..., d_k)\n        The target value of the input.\n\n    weights : tvm.te.Tensor\n        1-D with shape (C,)\n        The weight of each target value.\n\n    reduction : string\n        The reduction method to apply to output.\n        Can be \"mean\", \"sum\" or \"none\".\n\n    ignore_index : int\n        The target value to ignore.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        a scalar if the reduction type is \"mean\" or \"sum\",\n        otherwise the same shape as `target`.\n    \"\"\"\n    return cpp.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"General LSTM implementation using TE scan.\"\"\"\nfrom tvm import te, tir\nfrom tvm.topi import tag\n\n\ndef lstm(\n    Xs,\n    Wi,\n    Wh,\n    Bi=None,\n    Bh=None,\n    h_init=None,\n    c_init=None,\n    proj=None,\n    p_i=None,\n    p_f=None,\n    p_o=None,\n    f_act=tir.sigmoid,\n    g_act=tir.tanh,\n    h_act=tir.tanh,\n    reverse=False,\n    weight_layout: str = \"IFGO\",\n):\n    \"\"\"General LSTM implemented using TE scan.\n\n    Parameters\n    ----------\n    Xs : te.Tensor\n        Input sequence with shape `(seq_len, batch_size, in_dim)`\n    Wi : te.Tensor\n        Input weight matrix with shape `(4 * hidden_dim, in_dim)`. The weights are packed according\n        to `weight_layout`.\n    Wh : te.Tensor\n        Hidden weight matrix with shape `(4 * hidden_dim, hidden_dim or proj_dim)`. Packed as `Wh`.\n    Bi : te.Tensor, optional\n        Input bias with shape `(4 * hidden_dim,)`, by default None. Packed as `Wh`.\n    Bh : te.Tensor, optional\n        Hidden bias with shape as `Bi`, by default None. Packed as `Wh`.\n    h_init : te.Tensor, optional\n        Initial hidden state with shape `(batch_size, hidden_dim or proj_dim)`, zero if None\n    c_init : te.Tensor, optional\n        Initial cell state with same shape as `h_init`, zero if None\n    proj : te.Tensor, optional\n        Projection matrix with shape `(proj_dim, hidden_dim)`, by default None\n    p_i, p_f, p_o : te.Tensor, optional\n        Peephole LSTM matrices with shape `(batch_size, hidden_dim)`, by default None\n    f_act, g_act, h_act : F, optional\n        Gate activation functions\n    reverse : bool, optional\n        Whether to process `Xs` in reverse, by default False\n    weight_layout : str, optional\n        The packed weight layout for gates, by default \"IFGO\". Note: I = input, F = forget,\n        G = cell, O = output.\n\n    Returns\n    -------\n    result : te.Tensor, te.Tensor\n        Tuple of hidden states (with shape `(seq_len, batch_size, hidden_dim or proj_dim)`), and\n        cell states (with shape `(seq_len, batch_size, hidden_dim)`).\n    \"\"\"\n    assert len(weight_layout) == 4 and sorted(weight_layout) == sorted(\n        \"IFGO\"\n    ), f'given weight layout \"{weight_layout}\" is not a permutation of \"IFGO\"'\n\n    i_gate_idx = weight_layout.find(\"I\")\n    f_gate_idx = weight_layout.find(\"F\")\n    g_gate_idx = weight_layout.find(\"G\")\n    o_gate_idx = weight_layout.find(\"O\")\n\n    seq_len, batch_size, in_dim = Xs.shape\n    assert (\n        Wi.shape[0] % 4 == 0\n    ), f\"dim 0 of input weight should be 4 * hidden_dim, but {Wi.shape[0]} is not divisible by 4\"\n    hidden_dim = Wi.shape[0] // 4\n    proj_dim = hidden_dim\n    if proj is not None:\n        proj_dim = proj.shape[0]\n\n    # te.scan uses up 1 element for the initial value\n    scan_len = seq_len + 1\n\n    # precompute input-hidden matmul outside the scan\n    ki = te.reduce_axis((0, in_dim), name=\"ki2h\")\n    Xi2h = te.compute(\n        (seq_len * batch_size, 4 * hidden_dim),\n        lambda tb, ij: te.sum(Xs[(tb // batch_size), tb % batch_size, ki] * Wi[ij, ki], axis=ki),\n        name=\"Xi2h\",\n    )\n    if Bi is not None:\n        Xi2h = te.compute(\n            Xi2h.shape, lambda tb, ij: Xi2h[tb, ij] + Bi[ij], name=\"Xi2h_bias\", tag=tag.INJECTIVE\n        )\n\n    h_state = te.placeholder((scan_len, batch_size, proj_dim), name=\"h_state\")\n    c_state = te.placeholder((scan_len, batch_size, hidden_dim), name=\"c_state\")\n    h_init = te.compute(\n        (1, batch_size, proj_dim),\n        lambda _, b, i: h_init[b, i] if h_init is not None else 0.0,\n        name=\"h_init\",\n    )\n    c_init = te.compute(\n        (1, batch_size, hidden_dim),\n        lambda _, b, i: c_init[b, i] if c_init is not None else 0.0,\n        name=\"c_init\",\n    )\n\n    # begin scan computations, first the (batched) hidden-hidden dense\n    kh = te.reduce_axis((0, proj_dim), name=\"kh2h\")\n    s_h2h = te.compute(\n        (scan_len, batch_size, 4, hidden_dim),\n        lambda t, b, i, j: te.sum(h_state[t - 1, b, kh] * Wh[i * hidden_dim + j, kh], axis=kh),\n        name=\"s_h2h\",\n    )\n    if Bh is not None:\n        s_h2h = te.compute(\n            s_h2h.shape,\n            lambda t, b, i, j: s_h2h[t, b, i, j] + Bh[i * hidden_dim + j],\n            name=\"s_h2h_bias\",\n            tag=tag.INJECTIVE,\n        )\n\n    # helper to reverse time if scanning backwards\n    get_x_t = lambda t: seq_len - t if reverse else t - 1\n\n    gates = te.compute(\n        (scan_len, batch_size, 4, hidden_dim),\n        lambda t, b, i, j: Xi2h[get_x_t(t) * batch_size + b, i * hidden_dim + j]\n        + s_h2h[t, b, i, j],\n        name=\"gates\",\n        tag=tag.INJECTIVE,\n    )\n\n    # helper to correctly read each gate dense from the batched output\n    read_gate = lambda t, b, j, idx: gates[t, b, idx, j]\n\n    gate_shape = (scan_len, batch_size, hidden_dim)\n\n    # compute the activated gates (and do some extra stuff if peephole weights are present)\n    if p_i is not None and p_f is not None:\n        i_gate = te.compute(\n            gate_shape,\n            lambda t, b, j: f_act(\n                read_gate(t, b, j, i_gate_idx) + p_i[b, j] * c_state[t - 1, b, j]\n            ),\n            name=\"i_gate_p\",\n            tag=tag.INJECTIVE,\n        )\n        f_gate = te.compute(\n            gate_shape,\n            lambda t, b, j: f_act(\n                read_gate(t, b, j, f_gate_idx) + p_f[b, j] * c_state[t - 1, b, j]\n            ),\n            name=\"f_gate_p\",\n            tag=tag.INJECTIVE,\n        )\n    else:\n        i_gate = te.compute(\n            gate_shape,\n            lambda *i: f_act(read_gate(*i, i_gate_idx)),\n            name=\"i_gate\",\n            tag=tag.INJECTIVE,\n        )\n        f_gate = te.compute(\n            gate_shape,\n            lambda *i: f_act(read_gate(*i, f_gate_idx)),\n            name=\"f_gate\",\n            tag=tag.INJECTIVE,\n        )\n\n    g_gate = te.compute(\n        gate_shape, lambda *i: g_act(read_gate(*i, g_gate_idx)), name=\"g_gate\", tag=tag.INJECTIVE\n    )\n\n    next_c = te.compute(\n        gate_shape,\n        lambda t, b, j: f_gate[t, b, j] * c_state[t - 1, b, j] + i_gate[t, b, j] * g_gate[t, b, j],\n        name=\"next_c\",\n    )\n\n    if p_o is not None:\n        o_gate = te.compute(\n            gate_shape,\n            lambda t, b, j: f_act(read_gate(t, b, j, o_gate_idx) + p_o[b, j] * next_c[t, b, j]),\n            name=\"o_gate_p\",\n            tag=tag.INJECTIVE,\n        )\n    else:\n        o_gate = te.compute(\n            gate_shape,\n            lambda *i: f_act(read_gate(*i, o_gate_idx)),\n            name=\"o_gate\",\n            tag=tag.INJECTIVE,\n        )\n\n    next_h = te.compute(gate_shape, lambda *i: o_gate(*i) * h_act(next_c(*i)), name=\"next_h\")\n\n    # project hidden state back to proj_dim if projection matrix is present\n    if proj is not None:\n        kr = te.reduce_axis((0, hidden_dim), name=\"kh2p\")\n        next_h = te.compute(\n            (scan_len, batch_size, proj_dim),\n            lambda t, b, j: te.sum(next_h[t, b, kr] * proj[j, kr], axis=kr),\n            name=\"next_h_proj\",\n        )\n\n    scan_h, scan_c = te.scan(\n        [h_init, c_init], [next_h, next_c], [h_state, c_state], name=\"lstm_scan\"\n    )\n\n    # drop the initial values, TODO(@altanh): is there a better way?\n    scan_h = te.compute(\n        (seq_len, batch_size, proj_dim), lambda t, b, j: scan_h[t + 1, b, j], name=\"hidden_states\"\n    )\n    scan_c = te.compute(\n        (seq_len, batch_size, hidden_dim), lambda t, b, j: scan_c[t + 1, b, j], name=\"cell_states\"\n    )\n\n    return scan_h, scan_c\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/mapping.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long\n\"\"\"Operators of one-to-one-mapping on the first input\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\n@tvm.te.tag_scope(tag=tag.BROADCAST)\ndef scale_shift_nchw(Input, Scale, Shift):\n    \"\"\"Batch normalization operator in inference.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D input tensor, NCHW layout [batch, channel, height, width]\n\n    Scale : tvm.te.Tensor\n        Scale tensor, 1-D of size channel number\n\n    Shift : tvm.te.Tensor\n        Shift tensor, 1-D of size channel number\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        Output tensor, layout is NCHW\n    \"\"\"\n    return te.compute(\n        Input.shape, lambda b, c, i, j: Input[b, c, i, j] * Scale[c] + Shift[c], name=\"ScaleShift\"\n    )\n\n\n@tvm.te.tag_scope(tag=tag.BROADCAST)\ndef scale_shift_nhwc(Input, Scale, Shift):\n    \"\"\"Batch normalization operator in inference.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D input tensor, NHWC layout [batch, height, width, channel]\n\n    Scale : tvm.te.Tensor\n        Scale tensor, 1-D of size channel number\n\n    Shift : tvm.te.Tensor\n        Shift tensor, 1-D of size channel number\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        Output tensor, layout is NHWC\n    \"\"\"\n    return te.compute(\n        Input.shape, lambda b, i, j, c: Input[b, i, j, c] * Scale[c] + Shift[c], name=\"ScaleShift\"\n    )\n\n\n@tvm.te.tag_scope(tag=tag.BROADCAST)\ndef scale_shift_nchwc(Input, Scale, Shift):\n    \"\"\"Batch normalization operator in inference.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        5-D input tensor, NCHWc layout [batch, channel_chunk, height, width, channel_block]\n\n    Scale : tvm.te.Tensor\n        Scale tensor, 2-D of size [channel_chunk, channel_block]\n\n    Shift : tvm.te.Tensor\n        Shift tensor, 2-D of size [channel_chunk, channel_block]\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        Output tensor, layout is NHWC\n    \"\"\"\n    return te.compute(\n        Input.shape,\n        lambda b, cc, i, j, cb: Input[b, cc, i, j, cb] * Scale[cc, cb] + Shift[cc, cb],\n        name=\"ScaleShift\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/pad.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pad the data by constant value \"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\n\nfrom .. import tag\nfrom ..utils import equal_const_int\n\n\n@tvm.te.tag_scope(tag=tag.INJECTIVE + \",pad\")\ndef pad(data, pad_before, pad_after=None, pad_value=0.0, name=\"PadInput\", attrs=None):\n    \"\"\"Pad Input with zeros.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D input, can be any layout.\n\n    pad_before : list / tuple of n ints\n        Pad width on each dimension to pad the before the axis begin.\n\n    pad_after : list / tuple of n ints, optional\n        Pad width each dimension to pad the after the axis end.\n\n    pad_value : float, optional\n        The value to be padded.\n\n    name : str, optional\n        The name prefix operators generated\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        n-D, the same layout as Input.\n    \"\"\"\n    n = len(data.shape)\n    pad_after = pad_after if pad_after else pad_before\n    if len(pad_before) != n:\n        raise ValueError(\n            \"Input dimension and pad_before dismatch : %d vs %d\" % (n, len(pad_before))\n        )\n    if len(pad_after) != n:\n        raise ValueError(\"Input dimension and pad_after dismatch : %d vs %d\" % (n, len(pad_before)))\n    ana = tvm.arith.Analyzer()\n    dshape = []\n    for dim in data.shape:\n        if isinstance(dim, tvm.tir.Any):\n            dshape.append(tvm.te.size_var(\"dim\"))\n        else:\n            dshape.append(dim)\n    out_shape = tuple(ana.simplify(dshape[i] + pad_before[i] + pad_after[i]) for i in range(n))\n    pad_value = (\n        pad_value\n        if isinstance(pad_value, tvm.tir.PrimExpr)\n        else tvm.tir.const(pad_value, data.dtype)\n    )\n\n    def _pad(*indices):\n        not_zero = []\n        index_tuple = []\n        for i in range(n):\n            if equal_const_int(pad_before[i], 0) and equal_const_int(pad_after[i], 0):\n                index_tuple.append(indices[i])\n            else:\n                index_tuple.append(indices[i] - pad_before[i])\n                not_zero.append(indices[i] >= pad_before[i])\n                not_zero.append(indices[i] < data.shape[i] + pad_before[i])\n        if not_zero:\n            not_zero = tvm.tir.all(*not_zero)\n            return tvm.tir.if_then_else(not_zero, data(*index_tuple), pad_value)\n        return data(*index_tuple)\n\n    return te.compute(out_shape, _pad, name=name, attrs=attrs)\n\n\n@tvm.te.tag_scope(tag=tag.INJECTIVE + \",pad\")\ndef mirror_pad(data, pad_before, pad_after=None, mode=\"SYMMETRIC\", name=\"MirrorPadInput\"):\n    \"\"\"Pad Input with mirroring either symmetric or reflected.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D input, can be any layout.\n\n    pad_before : list / tuple of n ints\n        Pad width on each dimension to pad the before the axis begin.\n\n    pad_after : list / tuple of n ints, optional\n        Pad width each dimension to pad the after the axis end.\n\n    mode: str, optional\n        Type of mirror padding to apply. Must be SYMMETRIC or REFLECT\n\n    name : str, optional\n        The name prefix operators generated\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        n-D, the same layout as Input.\n    \"\"\"\n    n = len(data.shape)\n    pad_after = pad_after if pad_after else pad_before\n    if len(pad_before) != n:\n        raise ValueError(\n            \"Input dimension and pad_before dismatch : %d vs %d\" % (n, len(pad_before))\n        )\n    if len(pad_after) != n:\n        raise ValueError(\"Input dimension and pad_after dismatch : %d vs %d\" % (n, len(pad_before)))\n    ana = tvm.arith.Analyzer()\n    out_shape = tuple(ana.simplify(data.shape[i] + pad_before[i] + pad_after[i]) for i in range(n))\n    assert mode in (\"SYMMETRIC\", \"REFLECT\")\n    mode = int(mode == \"SYMMETRIC\")\n\n    def _pad(*indices):\n        index_tuple = []\n        above = []\n        below = []\n        for i in range(n):\n            if equal_const_int(pad_before[i], 0) and equal_const_int(pad_after[i], 0):\n                index_tuple.append(indices[i])\n                above.append(False)\n                below.append(False)\n            else:\n                index_tuple.append(indices[i] - pad_before[i])\n                above.append(indices[i] >= data.shape[i] + pad_before[i])\n                below.append(indices[i] < pad_before[i])\n        mapped_tuple = []\n        for i, axis in enumerate(index_tuple):\n            mapped_axis = tvm.tir.if_then_else(below[i], -axis - mode, axis)\n            mapped_axis = tvm.tir.if_then_else(\n                above[i], (2 * (data.shape[i] - 1)) - axis + mode, mapped_axis\n            )\n            mapped_tuple.append(mapped_axis)\n        return data(*mapped_tuple)\n\n    return te.compute(out_shape, _pad, name=name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator pooling compute.\"\"\"\nfrom __future__ import absolute_import\n\nfrom .. import cpp\n\nPOOL_TYPE_CODE = {\"avg\": 0, \"max\": 1}\n\n\ndef global_pool(data, pool_type, layout=\"NCHW\"):\n    \"\"\"Perform global pooling on height and width dimension of data.\n       It decides the height and width dimension according to the layout string,\n       in which 'W' and 'H' means width and height respectively.\n       Width and height dimension cannot be split.\n       For example, NCHW, NCHW16c, etc. are valid for pool,\n       while NCHW16w, NCHW16h are not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    layout : str\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCHW16c can describe a 5-D tensor of\n        [batch_size, channel, height, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in same layout with height and width dimension size of 1.\n        e.g., for NCHW, the output shape will be [batch, channel, 1, 1]\n    \"\"\"\n    return cpp.nn.global_pool(data, POOL_TYPE_CODE[pool_type], layout)\n\n\ndef pool_grad(\n    grads,\n    data,\n    kernel,\n    stride,\n    padding,\n    pool_type,\n    ceil_mode=False,\n    layout=\"NCHW\",\n    count_include_pad=True,\n):\n    \"\"\"Gradient of pooling on height and width dimension of data.\n       It decides the height and width dimension according to the layout string,\n       in which 'W' and 'H' means width and height respectively.\n       Width and height dimension cannot be split.\n       For example, NCHW, NCHW16c, etc. are valid for pool,\n       while NCHW16w, NCHW16h are not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    grads : tvm.te.Tensor\n        n-D with shape of layout\n\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    kernel : list/tuple of two ints\n        Kernel size, [kernel_height, kernel_width]\n\n    stride : list/tuple of two ints\n        Stride size, [stride_height, stride_width]\n\n    padding : list/tuple of four ints\n        Pad size, [pad_top, pad_left, pad_bottom, pad_right]]\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    ceil_mode : bool\n        Whether to use ceil when calculating output size.\n\n    layout: string\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCHW16c can describe a 5-D tensor of\n        [batch_size, channel, height, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    count_include_pad: bool\n        Whether include padding in the calculation when pool_type is 'avg'\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in the same layout\n    \"\"\"\n    return cpp.nn.pool_grad(\n        grads,\n        data,\n        kernel,\n        stride,\n        padding,\n        POOL_TYPE_CODE[pool_type],\n        ceil_mode,\n        layout,\n        count_include_pad,\n    )\n\n\ndef adaptive_pool(data, output_size, pool_type, layout=\"NCHW\"):\n    \"\"\"Perform pooling on height and width dimension of data.\n       The pooling kernel and stride sizes are automatically chosen for desired\n       output sizes.\n       It decides the height and width dimension according to the layout string,\n       in which 'W' and 'H' means width and height respectively.\n       Width and height dimension cannot be split.\n       For example, NCHW, NCHW16c, etc. are valid for pool,\n       while NCHW16w, NCHW16h are not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    output_size : tuple of int\n        output height and width.\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    layout: string\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCHW16c can describe a 5-D tensor of\n        [batch_size, channel, height, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in the same layout\n    \"\"\"\n    return cpp.nn.adaptive_pool(data, output_size, POOL_TYPE_CODE[pool_type], layout)\n\n\ndef adaptive_pool3d(data, output_size, pool_type, layout=\"NCDHW\"):\n    \"\"\"Perform pooling on three dimensional data.\n    See the two dimensional version above for details.\n    \"\"\"\n    return cpp.nn.adaptive_pool3d(data, output_size, POOL_TYPE_CODE[pool_type], layout)\n\n\ndef pool1d(\n    data,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode=False,\n    layout=\"NCW\",\n    count_include_pad=True,\n):\n    \"\"\"Perform pooling on width dimension of data.\n       Width axis is determined according to the layout string.\n       in which 'w' means width.\n       Width dimension cannot be split.\n       For example, NCW, NCW16c, etc. are valid for pool,\n       while NCW16w is not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    kernel : list/tuple of one int or int\n        Kernel size, [kernel_width]\n\n    stride : list/tuple of one int or int\n        Stride size, [stride_width]\n\n    dilation: list/tuple of two ints\n        Dilation size, [dilation_height, dilation_width]\n\n    padding : list/tuple of two ints\n        Pad size, [pad_left, pad_right]\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    ceil_mode : bool\n        Whether to use ceil when calculating output size.\n\n    layout: string\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCW16c can describe a 4-D tensor of\n        [batch_size, channel, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    count_include_pad: bool\n        Whether include padding in the calculation when pool_type is 'avg'\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in the same layout\n    \"\"\"\n    if isinstance(kernel, int):\n        kernel = [\n            kernel,\n        ]\n    if isinstance(stride, int):\n        stride = [\n            stride,\n        ]\n    return cpp.nn.pool1d(\n        data,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        POOL_TYPE_CODE[pool_type],\n        ceil_mode,\n        layout,\n        count_include_pad,\n    )\n\n\ndef pool2d(\n    data,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode=False,\n    layout=\"NCHW\",\n    count_include_pad=True,\n):\n    \"\"\"Perform pooling on height and width dimension of data.\n       It decides the height and width dimension according to the layout string,\n       in which 'W' and 'H' means width and height respectively.\n       Width and height dimension cannot be split.\n       For example, NCHW, NCHW16c, etc. are valid for pool,\n       while NCHW16w, NCHW16h are not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    kernel : list/tuple of two ints\n        Kernel size, [kernel_height, kernel_width]\n\n    stride : list/tuple of two ints\n        Stride size, [stride_height, stride_width]\n\n    dilation: list/tuple of two ints\n        Dilation size, [dilation_height, dilation_width]\n\n    padding : list/tuple of four ints\n        Pad size, [pad_top, pad_left, pad_bottom, pad_right]]\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    ceil_mode : bool\n        Whether to use ceil when calculating output size.\n\n    layout: string\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCHW16c can describe a 5-D tensor of\n        [batch_size, channel, height, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    count_include_pad: bool\n        Whether include padding in the calculation when pool_type is 'avg'\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in the same layout\n    \"\"\"\n    return cpp.nn.pool2d(\n        data,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        POOL_TYPE_CODE[pool_type],\n        ceil_mode,\n        layout,\n        count_include_pad,\n    )\n\n\ndef pool3d(\n    data,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode=False,\n    layout=\"NCDHW\",\n    count_include_pad=True,\n):\n    \"\"\"Perform pooling on depth, height and width dimension of data.\n       It decides the depth, height and width dimension according to the layout string,\n       in which 'D', 'W' and 'H' means depth, width and height respectively.\n       Depth, width and height dimension cannot be split.\n       For example, NCDHW, NCDHW16c, etc. are valid for pool,\n       while NCDHW16d, NCDHW16w, NCDHW16h are not.\n       See parameter `layout` for more information of the layout string convention.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        n-D with shape of layout\n\n    kernel : list/tuple of three ints\n        Kernel size, [kernel_depth, kernel_height, kernel_width]\n\n    stride : list/tuple of three ints\n        Stride size, [stride_depth, stride_height, stride_width]\n\n    dilation: list/tuple of two ints\n        Dilation size, [dilation_height, dilation_width]\n\n    padding : list/tuple of six ints\n        Pad size, [pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right]\n\n    pool_type : str\n        Pool type, 'max' or 'avg'\n\n    ceil_mode : bool\n        Whether to use ceil when calculating output size.\n\n    layout: string\n        Layout of the input data.\n        The layout is supposed to be composed of upper cases, lower cases and numbers,\n        where upper case indicates a dimension and\n        the corresponding lower case with factor size indicates the split dimension.\n        For example, NCDHW16c can describe a 6-D tensor of\n        [batch_size, channel, depth, height, width, channel_block],\n        in which channel_block=16 is a split of dimension channel.\n\n    count_include_pad: bool\n        Whether include padding in the calculation when pool_type is 'avg'\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        n-D in the same layout\n    \"\"\"\n    return cpp.nn.pool3d(\n        data,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        POOL_TYPE_CODE[pool_type],\n        ceil_mode,\n        layout,\n        count_include_pad,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/qnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Quantized Neural Network (QNN) Operators\"\"\"\nimport tvm\nfrom tvm import te, tir, topi\n\nSQNN_DISABLE = 0\nSQNN_INT8 = 1\nSQNN_UINT8 = 2\nSQNN_INT32 = 3\n\nSQNN_DTYPE_TO_CODE = {\n    \"disable\": SQNN_DISABLE,\n    \"int8\": SQNN_INT8,\n    \"uint8\": SQNN_UINT8,\n    \"int32\": SQNN_INT32,\n}\n\nSQNN_CODE_TO_DTYPE = {v: k for k, v in SQNN_DTYPE_TO_CODE.items()}\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef simulated_quantize(data, out_dtype, output_scale=None, output_zero_point=None, axis=-1):\n    \"\"\"Simulated QNN quantize operator that mimics QNN outputs without changing datatype.\n    The benefit of this operator over true QNN quantize is that this operator allows dynamic\n    datatype selection and can operate on both per-channel and scalar scales and zero points while\n    QNN quantize requires both of these to be fixed at compile time.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        An N-D input tensor to the operator.\n\n    out_dtype: tvm.te.Tensor\n        A scalar variable that indicates which datatype to simulate quantization with. Use\n        SQNN_DTYPE_TO_CODE to convert a dtype string into the corresponding variable\n        value.\n\n    output_scale: tvm.te.Tensor, optional\n        A scalar tensor representing the scale to use when quantizing to integer datatypes.\n        When it contains more than a single value, N must match the number of channels in data.\n\n    output_zero_point: tvm.te.Tensor, optional\n        A 1-D tensor representing the zero point to use when quantizing to integer datatypes.\n        When it contains more than a single value, N must match the number of channels in data.\n\n    axis: int, optional\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    \"\"\"\n    # When disabled, just pass through the input values.\n    def _compute_pass_through(value, *indices):\n        return value[indices]\n\n    # Simulate quantization for arbitrary integer datatypes. The computation for all datatypes is:\n    # Q_output = clip((round(input_tensor/output_scale) + output_zero_point),\n    #                 out_dtype::min,\n    #                 out_dtype::max)\n    def _compute_intn(dtype, value, *indices):\n        assert output_scale is not None and output_zero_point is not None\n        const_min = tvm.tir.min_value(dtype)\n        const_max = tvm.tir.max_value(dtype)\n        # Use indexmod to handle both scalar and per-channel QNN parameters.\n        scale_idx = tir.indexmod(indices[axis], topi.shape(output_scale)[0])\n        zp_idx = tir.indexmod(indices[axis], topi.shape(output_zero_point)[0])\n        return te.max(\n            te.min(\n                te.round(value[indices] / output_scale[scale_idx]) + output_zero_point[zp_idx],\n                const_max,\n            ),\n            const_min,\n        )\n\n    # Use an if chain to dynamically return the proper quantization based on the input datatype.\n    # This allows the op to compile once but apply different quantization approaches\n    # using a variable datatype input.\n    def _dispatch_sim_quantize(value):\n        pass_through_value = te.compute(\n            data.shape, lambda *indices: _compute_pass_through(value, *indices)\n        )\n        int8_value = te.compute(\n            data.shape,\n            lambda *indices: tir.if_then_else(\n                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"int8\"]),\n                _compute_intn(\"int8\", value, *indices),\n                pass_through_value[indices],\n            ),\n        )\n        uint8_value = te.compute(\n            data.shape,\n            lambda *indices: tir.if_then_else(\n                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"uint8\"]),\n                _compute_intn(\"uint8\", value, *indices),\n                int8_value[indices],\n            ),\n        )\n        int32_value = te.compute(\n            data.shape,\n            lambda *indices: tir.if_then_else(\n                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"int32\"]),\n                _compute_intn(\"int32\", value, *indices),\n                uint8_value[indices],\n            ),\n        )\n\n        return int32_value\n\n    return te.compute(data.shape, lambda *indices: _dispatch_sim_quantize(data)[indices])\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef simulated_dequantize(data, in_dtype, input_scale=None, input_zero_point=None, axis=-1):\n    \"\"\"Simulated QNN dequantize operator that mimics QNN outputs without changing datatype.\n    The benefit of this operator over true QNN dequantize is that this operator allows dynamic\n    datatype selection and can operate on both per-channel and scalar scales and zero points while\n    QNN dequantize requires both of these to be fixed at compile time.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        An N-D input tensor to the operator.\n\n    in_dtype: tvm.te.Tensor\n        A scalar variable that indicates which datatype to simulate dequantization with. Use\n        SQNN_DTYPE_TO_CODE to convert a dtype string into the corresponding variable\n        value.\n\n    input_scale: tvm.te.Tensor, optional\n        A scalar tensor representing the scale to use when dequantizing from integer datatypes.\n        When it contains more than a single value, N must match the number of channels in data.\n\n    input_zero_point: tvm.te.Tensor, optional\n        A 1-D tensor representing the zero point to use when dequantizing from integer datatypes.\n        When it contains more than a single value, N must match the number of channels in data.\n\n    axis: int, optional\n        The channel axis for quantization. Default value is -1 which corresponds to the last axis.\n\n    \"\"\"\n    # When disabled simply return the input tensor.\n    def _compute_pass_through(value, *indices):\n        return value[indices]\n\n    # Simulate dequantization for arbitrary integer datatypes. The computation for all datatypes is:\n    # DQ_output = (input - zero_point) * scale\n    def _compute_intn(value, *indices):\n        assert input_scale is not None and input_zero_point is not None\n        # Use indexmod to handle both scalar and per-channel QNN parameters.\n        scale_idx = tir.indexmod(indices[axis], topi.shape(input_scale)[0])\n        zp_idx = tir.indexmod(indices[axis], topi.shape(input_zero_point)[0])\n        return (value[indices] - input_zero_point[zp_idx]) * input_scale[scale_idx]\n\n    # Use an if chain to dynamically return the proper dequantization based on the input datatype.\n    # This allows the op to compile once but apply different quantization approaches\n    # using a variable datatype input.\n    def _dispatch_sim_dequantize(value):\n        pass_through_value = te.compute(\n            data.shape, lambda *indices: _compute_pass_through(value, *indices)\n        )\n        intn_condition = tvm.te.any(\n            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"int8\"]),\n            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"uint8\"]),\n            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"int32\"]),\n        )\n        intn_value = te.compute(\n            data.shape,\n            lambda *indices: tir.if_then_else(\n                intn_condition,\n                _compute_intn(value, *indices),\n                pass_through_value[indices],\n            ),\n        )\n\n        return intn_value\n\n    return te.compute(data.shape, lambda *indices: _dispatch_sim_dequantize(data)[indices])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/softmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator for softmax and log_softmax compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te, topi\n\n\n@tvm.te.tag_scope(tag=\"softmax_output\")\ndef softmax(x, axis=-1):\n    \"\"\"Perform softmax activation on the data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        can be any dimension\n\n    axis : int\n        channel axis\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        output shape is the same as input\n    \"\"\"\n    return softmax_common(x, axis, False)\n\n\n@tvm.te.tag_scope(tag=\"fast_softmax_output\")\ndef fast_softmax(x, axis=-1):\n    \"\"\"Perform softmax activation on the data.\n    Use approximation to compute exponent for faster speed.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        can be any dimension\n\n    axis : int\n        channel axis\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        output shape is the same as input\n    \"\"\"\n    return softmax_common(x, axis, True)\n\n\ndef softmax_common(x, axis, use_fast_exp):\n    \"\"\"The common part of softmax and fast_softmax\"\"\"\n    shape = x.shape\n    if axis < 0:\n        axis = len(shape) + axis\n    if axis >= len(shape):\n        ValueError(\"axis parameter should be less than input dim\")\n\n    k1 = te.reduce_axis((0, shape[axis]), name=\"k\")\n    k2 = te.reduce_axis((0, shape[axis]), name=\"k\")\n\n    def insert_reduce_index(indices, reduce_index):\n        return indices[:axis] + (reduce_index,) + indices[axis:]\n\n    def get_non_reduce_indices(indices):\n        return tuple([var for (i, var) in enumerate(indices) if i != axis])\n\n    def _compute_max(*indices):\n        eval_range = insert_reduce_index(indices, k1)\n        return tvm.te.max(x[eval_range], axis=k1)\n\n    def _compute_delta(max_elem, *indices):\n        non_reduce_indices = get_non_reduce_indices(indices)\n        return x[indices] - max_elem[non_reduce_indices]\n\n    def _compute_exp(max_elem, *indices):\n        non_reduce_indices = get_non_reduce_indices(indices)\n        return te.exp(x[indices] - max_elem[non_reduce_indices])\n\n    def _compute_expsum(exp, *indices):\n        eval_range = insert_reduce_index(indices, k2)\n        return te.sum(exp[eval_range], axis=k2)\n\n    def _normalize(exp, expsum, *indices):\n        non_reduce_indices = get_non_reduce_indices(indices)\n        return exp[indices] / expsum[non_reduce_indices]\n\n    reduced_shape = tuple([dim for (i, dim) in enumerate(shape) if i != axis])\n    max_elem = te.compute(reduced_shape, _compute_max, name=\"T_softmax_maxelem\")\n\n    if use_fast_exp:\n        delta = te.compute(\n            shape, lambda *indices: _compute_delta(max_elem, *indices), name=\"T_softmax_delta\"\n        )\n        exp = topi.math.fast_exp(delta)\n    else:\n        exp = te.compute(\n            shape, lambda *indices: _compute_exp(max_elem, *indices), name=\"T_softmax_exp\"\n        )\n    expsum = te.compute(\n        reduced_shape, lambda *indices: _compute_expsum(exp, *indices), name=\"T_softmax_expsum\"\n    )\n    return te.compute(\n        shape,\n        lambda *indices: _normalize(exp, expsum, *indices),\n        name=\"T_softmax_norm\",\n        attrs={\"axis\": axis},\n    )\n\n\n@tvm.te.tag_scope(tag=\"log_softmax_output\")\ndef log_softmax(x, axis=-1):\n    \"\"\"Perform log softmax activation on the data\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D input data\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        N-D output with same shape\n    \"\"\"\n    shape = x.shape\n    if axis < 0:\n        axis = len(shape) + axis\n    if axis >= len(shape):\n        ValueError(\"axis parameter should be less than input dim\")\n\n    k1 = te.reduce_axis((0, shape[axis]), name=\"k\")\n    k2 = te.reduce_axis((0, shape[axis]), name=\"k\")\n\n    def insert_reduce_index(indices, reduce_index):\n        return indices[:axis] + (reduce_index,) + indices[axis:]\n\n    def get_non_reduce_indices(indices):\n        return tuple([var for (i, var) in enumerate(indices) if i != axis])\n\n    def _compute_max(*indices):\n        eval_range = insert_reduce_index(indices, k1)\n        return tvm.te.max(x[eval_range], axis=k1)\n\n    def _compute_expsum(max_elem, *indices):\n        eval_range = insert_reduce_index(indices, k2)\n        return te.sum(te.exp(x[eval_range] - max_elem[indices]), axis=k2)\n\n    def _normalize(max_elem, expsum, *indices):\n        non_reduce_indices = get_non_reduce_indices(indices)\n        return x[indices] - max_elem[non_reduce_indices] - te.log(expsum[non_reduce_indices])\n\n    reduced_shape = tuple([dim for (i, dim) in enumerate(shape) if i != axis])\n    max_elem = te.compute(reduced_shape, _compute_max, name=\"T_softmax_maxelem\")\n    expsum = te.compute(reduced_shape, lambda *indices: _compute_expsum(max_elem, *indices))\n    return te.compute(\n        shape,\n        lambda *indices: _normalize(max_elem, expsum, *indices),\n        attrs={\"axis\": axis},\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/space_to_batch_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator space_to_batch_nd compute.\"\"\"\nfrom __future__ import absolute_import\nfrom . import cpp\n\n\ndef space_to_batch_nd(data, block_shape, pad_before, pad_after, pad_value=0.0):\n    \"\"\"Perform batch to space transformation on the data\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D Tensor with shape [batch, spatial_shape, remaining_shapes],\n        where spatial_shape has M dimensions.\n\n    block_shape : list of ints\n        list of size [M] where M is number of spatial dims, specifies block\n        size for each spatial dimension.\n\n    pad_before : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        zero-padding size before each spatial dimension.\n\n    pad_after : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        zero-padding size after each spatial dimension.\n\n    pad_value : float, optional\n        The value used for padding.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n    \"\"\"\n\n    return cpp.nn.space_to_batch_nd(data, block_shape, pad_before, pad_after, pad_value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/space_to_depth.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"TVM operator space_to_depth compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\n\n\ndef space_to_depth(data, block_size, layout=\"NCHW\"):\n    \"\"\"Perform space to depth transformation on the data\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D tensor in either NCHW or NHWC layout.\n\n    block_size : int\n        Size of blocks to decompose into channel dimension.\n\n    layout : string\n        Either NCHW or NHWC, indicating data layout.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        Output of shape [N, C * block_size**2, H / block_size, W / block_size]\n    \"\"\"\n\n    if layout == \"NCHW\":\n        in_n, in_c, in_h, in_w = data.shape\n        output_shape = [\n            in_n,\n            in_c * block_size * block_size,\n            tvm.tir.truncdiv(in_h, block_size),\n            tvm.tir.truncdiv(in_w, block_size),\n        ]\n    elif layout == \"NHWC\":\n        in_n, in_h, in_w, in_c = data.shape\n        output_shape = [\n            in_n,\n            tvm.tir.truncdiv(in_h, block_size),\n            tvm.tir.truncdiv(in_w, block_size),\n            in_c * block_size * block_size,\n        ]\n    else:\n        raise ValueError(\"Only NCHW and NHWC layouts are currently supported.\")\n\n    def _get_indices(*indices):\n        if layout == \"NCHW\":\n            n, c, y, x = indices\n        elif layout == \"NHWC\":\n            n, y, x, c = indices\n        return n, c, y, x\n\n    def _get_pixel(n, c, y, x):\n        block_offset = tvm.tir.truncdiv(c, in_c)\n        channel_idx = tvm.tir.truncmod(c, in_c)\n        x_idx = tvm.tir.truncmod(block_offset, block_size)\n        y_idx = tvm.tir.truncdiv(block_offset, block_size)\n\n        if layout == \"NCHW\":\n            output = data(n, channel_idx, y_idx + (y * block_size), x_idx + (x * block_size))\n        else:\n            output = data(n, y_idx + (y * block_size), x_idx + (x * block_size), channel_idx)\n        return output\n\n    def _compute(*indices):\n        n, c, y, x = _get_indices(*indices)\n        return _get_pixel(n, c, y, x)\n\n    return te.compute(output_shape, _compute, name=\"space_to_depth\", tag=tag.INJECTIVE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Sparse operators\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te, auto_scheduler\n\nfrom ..utils import get_const_tuple\n\n\ndef sparse_dense_sp_rhs(data, weight_data, weight_indices, weight_indptr):\n    \"\"\"\n    Computes sparse-dense matrix multiplication of `data` and\n    `(weight_data, weight_indices, weight_indptr).T`\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [M, K]\n\n    weight_data : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        3-D with shape [num_blocks, bs_r, bs_c] (BSR)\n\n    weight_indices : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        1-D with shape [num_blocks] (BSR)\n\n    weight_indptr : tvm.te.Tensor\n        1-D with shape [N + 1] (CSR) or\n        1-D with shape [(N + 1) // bs_r] (BSR)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    assert len(weight_data.shape) in (1, 3)\n    if len(weight_data.shape) == 1:\n        func = _sparse_dense_sp_rhs_csrmm\n    if len(weight_data.shape) == 3:\n        func = _sparse_dense_sp_rhs_bsrmm\n    return func(data, weight_data, weight_indices, weight_indptr)\n\n\ndef sparse_dense_sp_lhs(data_data, data_indices, data_indptr, weight):\n    \"\"\"\n    Computes sparse-dense matrix multiplication of\n    `(data_data, data_indices, data_indptr)` and `weight.T`\n\n    Parameters\n    ----------\n    data_data:\n        1-D with shape [nnz] (CSR) or\n        3-D with shape [num_blocks, bs_r, bs_c] (BSR)\n\n    data_indices:\n        1-D with shape [nnz] (CSR) or\n        1-D with shape [num_blocks] (BSR)\n\n    data_indptr:\n        1-D with shape [M + 1] (CSR) or\n        1-D with shape [(M + 1) // bs_r] (BSR)\n\n    weight:\n        2-D with shape [N, K]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    assert len(data_data.shape) in (1, 3)\n    if len(data_data.shape) == 1:\n        func = _sparse_dense_sp_lhs_csrmm\n    if len(data_data.shape) == 3:\n        func = _sparse_dense_sp_lhs_bsrmm\n    return func(data_data, data_indices, data_indptr, weight)\n\n\n# pylint: disable=no-else-return,inconsistent-return-statements\ndef sparse_dense(dense_data, sparse_data, sparse_indices, sparse_indptr, sparse_lhs=False):\n    \"\"\"\n    Computes sparse-dense matrix multiplication of `data` and\n    `(weight_data, weight_indices, weight_indptr).T`, if sparse_lhs=False\n    or\n    Computes sparse-dense matrix multiplication of\n    `(data_data, data_indices, data_indptr)` and `weight.T`, if sparse_lhs=True\n\n    Parameters\n    ----------\n    dense_data : tvm.te.Tensor\n        2-D with shape [M, K]\n\n    sparse_data : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        3-D with shape [num_blocks, bs_r, bs_c] (BSR)\n\n    sparse_indices : tvm.te.Tensor\n        1-D with shape [nnz] (CSR) or\n        1-D with shape [num_blocks] (BSR)\n\n    sparse_indptr : tvm.te.Tensor\n        1-D with shape [N + 1] (CSR) or\n        1-D with shape [(N + 1) // bs_r] (BSR)\n\n    sparse_lhs : bool, optional\n        Indicates whether lhs or rhs matrix is sparse. Default value is False.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    if sparse_lhs:\n        return sparse_dense_sp_lhs(sparse_data, sparse_indices, sparse_indptr, dense_data)\n    else:\n        return sparse_dense_sp_rhs(dense_data, sparse_data, sparse_indices, sparse_indptr)\n\n\ndef _sparse_dense_sp_lhs_csrmm(data_data, data_indices, data_indptr, weight):\n    oshape = (get_const_tuple(data_indptr.shape)[0] - 1, get_const_tuple(weight.shape)[0])\n\n    def f(row, i):\n        row_start = data_indptr[row]\n        row_end = data_indptr[row + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        elem = row_start + elem_idx\n        a_val = data_data[elem]\n        weight_val = weight[i, data_indices[elem]]\n        return te.sum(a_val * weight_val, axis=elem_idx)\n\n    return te.compute(oshape, f, tag=\"sparse_dense_sp_lhs_csrmm\")\n\n\ndef _sparse_dense_sp_rhs_csrmm(data, weight_data, weight_indices, weight_indptr):\n    oshape = (get_const_tuple(data.shape)[0], get_const_tuple(weight_indptr.shape)[0] - 1)\n\n    def f(i, row):\n        row_start = weight_indptr[row]\n        row_end = weight_indptr[row + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        elem = row_start + elem_idx\n        a_val = weight_data[elem]\n        weight_val = data[i, weight_indices[elem]]\n        return te.sum(a_val * weight_val, axis=elem_idx)\n\n    return te.compute(oshape, f, tag=\"sparse_dense_sp_rhs_csrmm\")\n\n\ndef _sparse_dense_sp_lhs_bsrmm(data_data, data_indices, data_indptr, weight):\n    (m, _) = get_const_tuple(weight.shape)\n    (_, bs_r, bs_c) = get_const_tuple(data_data.shape)\n    (num_blocks_plus_1,) = get_const_tuple(data_indptr.shape)\n    num_blocks = num_blocks_plus_1 - 1\n\n    def _compute_block(nb_j, j, i):\n        row_start = data_indptr[nb_j]\n        row_end = data_indptr[nb_j + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        block_offset = row_start + elem_idx\n        c = te.reduce_axis((0, bs_c), name=\"c\")\n        block_j = data_indices[block_offset]\n        block_ij_val = data_data[block_offset][j][c]\n        x_val = weight[i, bs_c * block_j + c]\n        return te.sum(block_ij_val * x_val, axis=[elem_idx, c])\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    bsrmm_block = te.compute(\n        (num_blocks, bs_r, m), _compute_block, tag=\"sparse_dense_sp_lhs_bsrmm_block\"\n    )\n    return te.compute(\n        (num_blocks * bs_r, m),\n        lambda m, n: bsrmm_block[idxd(m, bs_r), idxm(m, bs_r), n],\n        tag=\"sparse_dense_sp_lhs_bsrmm\",\n    )\n\n\ndef _sparse_dense_sp_rhs_bsrmm(data, weight_data, weight_indices, weight_indptr):\n    (m, k) = get_const_tuple(data.shape)\n    (_, bs_r, bs_c) = get_const_tuple(weight_data.shape)\n    (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape)\n    num_blocks = num_blocks_plus_1 - 1\n\n    def _compute_block(i, nb_j, j):\n        row_start = weight_indptr[nb_j]\n        row_end = weight_indptr[nb_j + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        block_offset = row_start + elem_idx\n        c = te.reduce_axis((0, bs_c), name=\"c\")\n        block_j = weight_indices[block_offset]\n        block_ij_val = weight_data[block_offset][j][c]\n        x_val = data[i, bs_c * block_j + c]\n        return te.sum(block_ij_val * x_val, axis=[elem_idx, c])\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    bsrmm_block = te.compute(\n        (m, num_blocks, bs_r),\n        _compute_block,\n        tag=\"sparse_dense_sp_rhs_bsrmm_block\",\n        attrs={\"FLOP\": 2 * m * num_blocks * bs_r * k},\n    )\n    return te.compute(\n        (m, num_blocks * bs_r),\n        lambda m, n: bsrmm_block[m, idxd(n, bs_r), idxm(n, bs_r)],\n        tag=\"sparse_dense_sp_rhs_bsrmm\",\n    )\n\n\ndef sparse_transpose(sparse_data, sparse_indices, sparse_indptr):\n    \"\"\"\n    Transpose a square sparse matrix,\n    `A` is an n-by-n sparse matrix in the CSR format.\n    ** Currently only support Square Matrices **\n\n    Parameters\n    ----------\n    sparse_data : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    sparse_indices : tvm.te.Tensor\n        1-D with shape [nonzeros], dtype of 'int32'\n\n    sparse_indptr : tvm.te.Tensor\n        1-D with shape [n+1], dtype of 'int32'\n\n    Returns\n    -------\n    out_data : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    out_indices : tvm.te.Tensor\n        1-D with shape [nonzeros], dtype of 'int32'\n\n    out_indptr : tvm.te.Tensor\n        1-D with shape [n+1], dtype of 'int32'\n    \"\"\"\n    assert len(sparse_data.shape) == 1, \"error in data dimension\"\n    assert len(sparse_indices.shape) == 1, \"error in indices dimension\"\n    assert len(sparse_indptr.shape) == 1, \"error in indptr dimension\"\n\n    nnz = get_const_tuple(sparse_data.shape)[0]\n    n = get_const_tuple(sparse_indptr.shape)[0] - 1\n    output_shape = [(nnz,), (nnz,), (n + 1,)]\n\n    # TODO: Add BSR transpose support\n\n    output_data, output_indices, output_indptr = te.extern(\n        shape=output_shape,\n        inputs=[sparse_data, sparse_indices, sparse_indptr],\n        fcompute=lambda ins, outs: _csr_transpose_ir(\n            ins[0], ins[1], ins[2], outs[0], outs[1], outs[2]\n        ),\n        tag=\"sparse_transpose_csr\",\n        dtype=[sparse_data.dtype, \"int32\", \"int32\"],\n        name=\"out\",\n    )\n\n    return [output_data, output_indices, output_indptr]\n\n\ndef _csr_transpose_ir(data, indices, indptr, out_data, out_indices, out_indptr):\n    \"\"\"define ir for csr_transpose\"\"\"\n    irb = tvm.tir.ir_builder.create()\n\n    data_ptr = irb.buffer_ptr(data)\n    indices_ptr = irb.buffer_ptr(indices)\n    indptr_ptr = irb.buffer_ptr(indptr)\n\n    out_data_ptr = irb.buffer_ptr(out_data)\n    out_indices_ptr = irb.buffer_ptr(out_indices)\n    out_indptr_ptr = irb.buffer_ptr(out_indptr)\n\n    n = get_const_tuple(indptr.shape)[0] - 1\n    nnz = get_const_tuple(data.shape)[0]\n\n    with irb.for_range(0, n, kind=\"parallel\", name=\"col\") as col:\n        out_indptr_ptr[col] = 0\n\n    with irb.for_range(0, nnz, kind=\"serial\", name=\"nz_idx\") as nz_idx:\n        out_indptr_ptr[indices_ptr[nz_idx]] += 1\n\n    cumsum = irb.allocate(\"int32\", (1,), name=\"cumsum\", scope=\"local\")\n    temp = irb.allocate(\"int32\", (1,), name=\"temp\", scope=\"local\")\n    cumsum[0] = 0\n    with irb.for_range(0, n, kind=\"serial\", name=\"col\") as col:\n        temp[0] = out_indptr_ptr[col]\n        out_indptr_ptr[col] = cumsum[0]\n        cumsum[0] += temp[0]\n\n    out_indptr_ptr[n] = nnz\n\n    with irb.for_range(0, n, kind=\"serial\", name=\"row\") as row:\n        offset = indptr_ptr[row]\n        diff = indptr_ptr[row + 1] - indptr_ptr[row]\n        with irb.for_range(0, diff, kind=\"serial\", name=\"idx\") as idx:\n            real_idx = offset + idx\n            col = indices_ptr[real_idx]\n            dest = out_indptr_ptr[col]\n\n            out_indices_ptr[dest] = row\n            out_data_ptr[dest] = data_ptr[real_idx]\n            out_indptr_ptr[col] += 1\n\n    last = irb.allocate(\"int32\", (1,), name=\"last\", scope=\"local\")\n    temp2 = irb.allocate(\"int32\", (1,), name=\"temp2\", scope=\"local\")\n    last[0] = 0\n    with irb.for_range(0, n, kind=\"serial\", name=\"col\") as col:\n        temp2[0] = out_indptr_ptr[col]\n        out_indptr_ptr[col] = last[0]\n        last[0] = temp2[0]\n\n    return irb.get()\n\n\n@tvm.target.generic_func\ndef sparse_dense_alter_layout(_attrs, _inputs, _tinfos, _out_type):\n    \"\"\"Change Sparse Dense layout.\n\n    This is used for modifying the inputs weights so they are more amenable for\n    the target.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : tvm.relay.Expr\n        Grouped input symbols\n    tinfos : list\n        Input shape and dtype\n    out_type: type\n        The output type\n\n    Note\n    ----\n    Unlike other TOPI functions, this function operates on both graph level and operator level.\n    \"\"\"\n    return None\n\n\n@auto_scheduler.register_task_input_check_func\ndef try_get_sparse_input(args):\n    \"\"\"Analyze the input data from the given args.\n\n    Parameters\n    ----------\n    args : List[Tensor]\n        Input/output Tensor of a TVM subgraph.\n\n    Returns\n    -------\n    Dict[Tensor, str] :\n        Map from the input Tensor to its buffer name.\n\n    Notes\n    -----\n    The buffer name is specially designed, and these buffer should be provided in\n    `SearchTask(..., task_inputs={...})`.\n    \"\"\"\n    sparse_prefix = sparse_data = sparse_indices = sparse_indptr = None\n\n    def _process_inputs(input_tensors, m, n, prefix_init):\n        nonlocal sparse_prefix\n        nonlocal sparse_data\n        nonlocal sparse_indices\n        nonlocal sparse_indptr\n\n        assert len(input_tensors) == 4\n        unsure_tensors = list(input_tensors)\n        # Get the Dense data\n        dense_data = None\n        for tensor in unsure_tensors:\n            if len(tensor.shape) == 2:\n                assert dense_data is None\n                dense_data = tensor\n                assert m == dense_data.shape[0]\n                k = dense_data.shape[1]\n        unsure_tensors.remove(dense_data)\n\n        # Get the Sparse data\n        sparse_data = None\n        for tensor in unsure_tensors:\n            if len(tensor.shape) == 3:\n                assert sparse_data is None\n                sparse_data = tensor\n                block_size, bs_r, bs_c = sparse_data.shape\n        unsure_tensors.remove(sparse_data)\n\n        # Get the Sparse indptr & indices\n        sparse_indices = None\n        for tensor in unsure_tensors:\n            assert len(tensor.shape) == 1\n            if tensor.shape[0] == block_size:\n                assert sparse_indices is None\n                sparse_indices = tensor\n        unsure_tensors.remove(sparse_indices)\n        assert len(unsure_tensors) == 1\n        sparse_indptr = unsure_tensors[0]\n\n        # Generate the sparse_prefix\n        density = 1.0\n        for i in sparse_data.shape:\n            density *= i\n        density /= k * n\n        density = density.value\n        sparse_prefix = \"%s_%d_%d_%d_%d_%d_%d_\" % (\n            prefix_init,\n            n,\n            k,\n            bs_r,\n            bs_c,\n            sparse_indices.shape[0],\n            sparse_indptr.shape[0],\n        )\n\n    visited = set()\n\n    def _traverse(t):\n        # We cannot directly add tensors to the set, because the comparison of\n        # two tensors with ndim=0 is ambiguous.\n        assert t.handle is not None\n        if t.handle.value in visited:\n            return\n\n        if isinstance(t.op, te.ComputeOp):\n            # TODO(jcf94): Currently only support to one sparse op, add more support here\n            if t.op.tag == \"sparse_dense_sp_rhs_bsrmm\":\n                m, n = t.shape\n                assert len(t.op.input_tensors) == 1\n                block_tensor = t.op.input_tensors[0]\n                _process_inputs(block_tensor.op.input_tensors, m, n, \"sparse_dense_bsr\")\n            if sparse_prefix is not None:\n                # Early stop if we find a sparse_prefix\n                # Notice: If any workload has more than one sparse input, this may get problem\n                return\n            for x in t.op.input_tensors:\n                _traverse(x)\n        visited.add(t.handle.value)\n\n    try:\n        for arg in args:\n            _traverse(arg)\n    # pylint: disable=broad-except\n    except Exception:\n        return {}\n\n    if sparse_data is None or sparse_indices is None or sparse_indptr is None:\n        return {}\n\n    sparse_input_map = {}\n    sparse_input_map[sparse_data] = sparse_prefix + \"W_data\"\n    sparse_input_map[sparse_indices] = sparse_prefix + \"W_indices\"\n    sparse_input_map[sparse_indptr] = sparse_prefix + \"W_indptr\"\n\n    return sparse_input_map\n\n\ndef _sparse_conv2d_bsr_compute_nhwc(data, weight_data, weight_indices, weight_indptr):\n    (m, h, w, k) = get_const_tuple(data.shape)  # pylint: disable=C0103\n    if len(weight_data.shape) == 2:\n        _, bs_r = get_const_tuple(weight_data.shape)\n    elif len(weight_data.shape) == 3:\n        _, bs_r, bs_c = get_const_tuple(weight_data.shape)\n    (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape)\n    num_blocks = num_blocks_plus_1 - 1\n\n    def _compute_block(i, h, w, nb_j, j):  # pylint: disable=C0103\n        row_start = weight_indptr[nb_j]\n        row_end = weight_indptr[nb_j + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        block_offset = row_start + elem_idx\n        block_j = weight_indices[block_offset]\n        if len(weight_data.shape) == 3:\n            c = te.reduce_axis((0, bs_c), name=\"c\")\n            block_ij_val = weight_data[block_offset][j][c]\n            x_val = data[i, h, w, bs_c * block_j + c]\n            return te.sum(block_ij_val * x_val, axis=[elem_idx, c])\n        else:\n            block_ij_val = weight_data[block_offset][j]\n            x_val = data[i, h, w, block_j]\n            return te.sum(block_ij_val * x_val, axis=[elem_idx])\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    bsrmm_block = te.compute(\n        (m, h, w, num_blocks, bs_r),\n        _compute_block,\n        tag=\"sparse_conv2d_sp_bsrmm_block\",\n        attrs={\"FLOP\": 2 * m * num_blocks * bs_r * k * h * w},\n    )\n    return te.compute(\n        (m, h, w, num_blocks * bs_r),\n        lambda m, h, w, n: bsrmm_block[m, h, w, idxd(n, bs_r), idxm(n, bs_r)],\n        tag=\"sparse_conv2d_sp_bsrmm\",\n        name=\"sparse_conv2d\",\n        attrs={\"layout\": \"NHWC\"},\n    )\n\n\ndef _sparse_conv2d_bsr_compute_nchw(data, weight_data, weight_indices, weight_indptr):\n    (m, k, h, w) = get_const_tuple(data.shape)  # pylint: disable=C0103\n    if len(weight_data.shape) == 2:\n        _, bs_r = get_const_tuple(weight_data.shape)\n    elif len(weight_data.shape) == 3:\n        _, bs_r, bs_c = get_const_tuple(weight_data.shape)\n    (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape)\n    num_blocks = num_blocks_plus_1 - 1\n\n    def _compute_block(i, nb_j, j, h, w):  # pylint: disable=C0103\n        row_start = weight_indptr[nb_j]\n        row_end = weight_indptr[nb_j + 1]\n        row_elems = row_end - row_start\n        elem_idx = te.reduce_axis((0, row_elems), name=\"elem_idx\")\n        block_offset = row_start + elem_idx\n        block_j = weight_indices[block_offset]\n        if len(weight_data.shape) == 3:\n            c = te.reduce_axis((0, bs_c), name=\"c\")\n            block_ij_val = weight_data[block_offset][j][c]\n            x_val = data[i, bs_c * block_j + c, h, w]\n            return te.sum(block_ij_val * x_val, axis=[elem_idx, c])\n        else:\n            block_ij_val = weight_data[block_offset][j]\n            x_val = data[i, block_j, h, w]\n            return te.sum(block_ij_val * x_val, axis=[elem_idx])\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    bsrmm_block = te.compute(\n        (m, num_blocks, bs_r, h, w),\n        _compute_block,\n        tag=\"sparse_conv2d_sp_bsrmm_block\",\n        attrs={\"FLOP\": 2 * m * num_blocks * bs_r * k * h * w},\n    )\n    return te.compute(\n        (m, num_blocks * bs_r, h, w),\n        lambda m, n, h, w: bsrmm_block[m, idxd(n, bs_r), idxm(n, bs_r), h, w],\n        tag=\"sparse_conv2d_sp_bsrmm\",\n        name=\"sparse_conv2d\",\n        attrs={\"layout\": \"NCHW\"},\n    )\n\n\ndef sparse_conv2d(\n    dense_data, sparse_data, sparse_indices, sparse_indptr, layout=\"NHWC\", kernel_size=1\n):\n    \"\"\"\n    Computes sparse-conv2d(1*1) of ``data`` and\n    ``(weight_data, weight_indices, weight_indptr)``\n\n    Parameters\n    ----------\n    dense_data : tvm.te.Tensor\n        4-D with shape ``[M, H, W, K]`` (layout=NHWC)\n\n        4-D with shape ``[M, K, H, W]`` (layout=NCHW)\n\n    sparse_data : tvm.te.Tensor\n        2-D with shape ``[num_blocks, bs_r]`` (BSR)\n\n        3-D with shape ``[num_blocks, bs_r, bs_c]`` (BSR)\n\n    sparse_indices : tvm.te.Tensor\n        1-D with shape ``[num_blocks]`` (BSR)\n\n    sparse_indptr : tvm.te.Tensor\n        1-D with shape ``[(N + 1) // bs_r]`` (BSR)\n\n    layout : str\n        layout of data\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [M, H, W, N] (layout=NHWC)\n        4-D with shape [M, N, H ,W] (layout=NCHW)\n    \"\"\"\n    if kernel_size == 1:\n        if layout == \"NHWC\":\n            return _sparse_conv2d_bsr_compute_nhwc(\n                dense_data, sparse_data, sparse_indices, sparse_indptr\n            )\n        elif layout == \"NCHW\":\n            return _sparse_conv2d_bsr_compute_nchw(\n                dense_data, sparse_data, sparse_indices, sparse_indptr\n            )\n    else:\n        raise ValueError(\"Unsupport Layout %s\" % layout)\n\n\n@auto_scheduler.register_task_input_check_func\ndef try_get_conv2d_sparse_input(args):\n    \"\"\"Analyze the input data from the given args.\n\n    Parameters\n    ----------\n    args : List[Tensor]\n        Input/output Tensor of a TVM subgraph.\n\n    Returns\n    -------\n    Dict[Tensor, str] :\n        Map from the input Tensor to its buffer name.\n\n    Notes\n    -----\n    The buffer name is specially designed, and these buffer should be provided in\n    `SearchTask(..., task_inputs={...})`.\n    \"\"\"\n    sparse_prefix = sparse_data = sparse_indices = sparse_indptr = None\n\n    def _process_inputs(input_tensors, m, h, w, n, prefix_init, layout):  # pylint: disable=C0103\n        nonlocal sparse_prefix\n        nonlocal sparse_data\n        nonlocal sparse_indices\n        nonlocal sparse_indptr\n\n        assert len(input_tensors) == 4\n        unsure_tensors = list(input_tensors)\n        # Get the Dense data\n        dense_data = None\n        for tensor in unsure_tensors:\n            if len(tensor.shape) == 4:\n                assert dense_data is None\n                dense_data = tensor\n                if layout == \"NHWC\":\n                    assert m == dense_data.shape[0]\n                    assert h == dense_data.shape[1]\n                    assert w == dense_data.shape[2]\n                    k = dense_data.shape[3]\n                elif layout == \"NCHW\":\n                    assert m == dense_data.shape[0]\n                    assert h == dense_data.shape[2]\n                    assert w == dense_data.shape[3]\n                    k = dense_data.shape[1]\n        unsure_tensors.remove(dense_data)\n        # Get the Sparse data\n        sparse_data = None\n        for tensor in unsure_tensors:\n            if len(tensor.shape) == 3:\n                assert sparse_data is None\n                sparse_data = tensor\n                block_size, bs_r, bs_c = sparse_data.shape\n            if len(tensor.shape) == 2:\n                assert sparse_data is None\n                sparse_data = tensor\n                block_size, bs_r = sparse_data.shape\n                bs_c = 1\n        unsure_tensors.remove(sparse_data)\n        # Get the Sparse indptr & indices\n        sparse_indices = None\n        for tensor in unsure_tensors:\n            assert len(tensor.shape) == 1\n            if tensor.shape[0] == block_size:\n                assert sparse_indices is None\n                sparse_indices = tensor\n        unsure_tensors.remove(sparse_indices)\n        assert len(unsure_tensors) == 1\n        sparse_indptr = unsure_tensors[0]\n        # Generate the sparse_prefix\n        density = 1.0\n        for i in sparse_data.shape:\n            density *= i\n        density /= k * n\n        density = density.value\n        sparse_prefix = \"%s_%d_%d_%d_%d_%d_%d_\" % (\n            prefix_init,\n            n,\n            k,\n            bs_r,\n            bs_c,\n            sparse_indices.shape[0],\n            sparse_indptr.shape[0],\n        )\n\n    visited = set()\n\n    def _traverse(t):\n        # We cannot directly add tensors to the set, because the comparison of\n        # two tensors with ndim=0 is ambiguous.\n        assert t.handle is not None\n        if t.handle.value in visited:\n            return\n\n        if isinstance(t.op, te.ComputeOp):\n            if t.op.tag == \"sparse_conv2d_sp_bsrmm\":\n                m, h, w, n = t.shape  # pylint: disable=C0103\n                assert len(t.op.input_tensors) == 1\n                block_tensor = t.op.input_tensors[0]\n                _process_inputs(\n                    block_tensor.op.input_tensors,\n                    m,\n                    h,\n                    w,\n                    n,\n                    \"sparse_conv2d_bsr\",\n                    t.op.attrs[\"layout\"],\n                )\n            if sparse_prefix is not None:\n                # Early stop if we find a sparse_prefix\n                # Notice: If any workload has more than one sparse input, this may get problem\n                return\n            for x in t.op.input_tensors:\n                _traverse(x)\n        visited.add(t.handle.value)\n\n    try:\n        for arg in args:\n            _traverse(arg)\n    # pylint: disable=broad-except\n    except Exception:\n        return {}\n\n    if sparse_data is None or sparse_indices is None or sparse_indptr is None:\n        return {}\n\n    sparse_input_map = {}\n    sparse_input_map[sparse_data] = sparse_prefix + \"W_data\"\n    sparse_input_map[sparse_indices] = sparse_prefix + \"W_indices\"\n    sparse_input_map[sparse_indptr] = sparse_prefix + \"W_indptr\"\n\n    return sparse_input_map\n\n\ndef sparse_add(dense_data, sparse_data, sparse_indices, sparse_indptr):\n    \"\"\"\n    Computes sparse-dense addition\n\n    Parameters\n    ----------\n    dense_data : tvm.te.Tensor\n        2-D with shape [M, N]\n\n    sparse_data : tvm.te.Tensor\n        1-D with shape [nnz] (CSR)\n\n    sparse_indices : tvm.te.Tensor\n        1-D with shape [nnz] (CSR)\n\n    sparse_indptr : tvm.te.Tensor\n        1-D with shape [M + 1] (CSR)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [M, N]\n    \"\"\"\n    # TODO(ANSHUMAN87): support BSR format too\n    assert len(sparse_data.shape) == 1, \"only CSR format is supported\"\n    return _sparse_add_csr(dense_data, sparse_data, sparse_indices, sparse_indptr)\n\n\ndef _sparse_add_csr(dense_data_inp, sparse_data_inp, sparse_indices_inp, sparse_indptr_inp):\n    oshape = get_const_tuple(dense_data_inp.shape)\n\n    def _csr_add_ir(dense_data, sparse_data, sparse_indices, sparse_indptr, out_data):\n        irb = tvm.tir.ir_builder.create()\n        dense_data_ptr = irb.buffer_ptr(dense_data)\n        sparse_data_ptr = irb.buffer_ptr(sparse_data)\n        sparse_indices_ptr = irb.buffer_ptr(sparse_indices)\n        sparse_indptr_ptr = irb.buffer_ptr(sparse_indptr)\n\n        out_data_ptr = irb.buffer_ptr(out_data)\n\n        with irb.for_range(0, oshape[0], kind=\"vectorize\", name=\"row\") as row:\n            with irb.for_range(0, oshape[1], kind=\"parallel\", name=\"col\") as col:\n                out_data_ptr[row, col] = dense_data_ptr[row, col]\n\n        with irb.for_range(0, oshape[0], kind=\"parallel\", name=\"row\") as row:\n            offset = sparse_indptr_ptr[row]\n            diff = sparse_indptr_ptr[row + 1] - sparse_indptr_ptr[row]\n            with irb.for_range(0, diff, kind=\"serial\", name=\"idx\") as idx:\n                real_idx = offset + idx\n                col = sparse_indices_ptr[real_idx]\n                out_data_ptr[row, col] = sparse_data_ptr[real_idx] + out_data_ptr[row, col]\n\n        return irb.get()\n\n    return te.extern(\n        shape=oshape,\n        inputs=[dense_data_inp, sparse_data_inp, sparse_indices_inp, sparse_indptr_inp],\n        fcompute=lambda ins, outs: _csr_add_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        tag=\"sparse_add_csr\",\n        dtype=[\n            dense_data_inp.dtype,\n            sparse_data_inp.dtype,\n            sparse_indices_inp.dtype,\n            sparse_indptr_inp.dtype,\n        ],\n        name=\"sparse_add_csr_output\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/upsampling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator upsampling compute.\"\"\"\nfrom tvm import topi\nfrom tvm import te\nfrom ..utils import simplify\n\n\ndef upsampling(\n    data,\n    scale_h,\n    scale_w,\n    layout=\"NCHW\",\n    method=\"nearest_neighbor\",\n    align_corners=False,\n    output_shape=None,\n):\n    \"\"\"Perform upsampling on the data.\n       Nearest neighbor and bilinear upsampling are supported.\n\n    Parameters\n    ----------\n    inputs : tvm.te.Tensor\n        inputs is a 4-D tensor with shape\n        [batch, channel, in_height, in_width]\n        or  [batch, in_height, in_width, channel]\n\n    scale_h : float\n        Scaling factor for height\n\n    scale_w : float\n        Scaling factor for width\n\n    layout : string, optional\n        either \"NCHW\" or \"NHWC\"\n\n    method : {\"bilinear\", \"nearest_neighbor\", \"bicubic\"}\n        Method to be used for upsampling.\n\n    output_shape: tvm.tir.container.Array, optional\n        Shape to return. If left None will be inferred\n        (If shape is determined dynamically, pass out_dtype.shape as output_shape)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, channel, in_height*scale_h, in_width*scale_w]\n        or [batch, in_height*scale, in_width*scale, channel]\n    \"\"\"\n    base_layout = layout[0:4]\n    if base_layout == \"NCHW\":\n        if not output_shape:  # static case\n            scaled_h = data.shape[2] * scale_h\n            scaled_w = data.shape[3] * scale_w\n            reshape_size = (\n                simplify(topi.cast(te.round(scaled_h), data.shape[2].dtype)),\n                simplify(topi.cast(te.round(scaled_w), data.shape[3].dtype)),\n            )\n        else:  # dynamic case -- we don't need to scale; already done in shape func\n            reshape_size = (\n                simplify(topi.cast(te.round(output_shape[2]), output_shape[2].dtype)),\n                simplify(topi.cast(te.round(output_shape[3]), output_shape[3].dtype)),\n            )\n    elif layout == \"NHWC\":\n        if not output_shape:  # static case\n            scaled_h = data.shape[1] * scale_h\n            scaled_w = data.shape[2] * scale_w\n            reshape_size = (\n                simplify(topi.cast(te.round(scaled_h), data.shape[1].dtype)),\n                simplify(topi.cast(te.round(scaled_w), data.shape[2].dtype)),\n            )\n        else:  # dynamic case\n            reshape_size = (\n                simplify(topi.cast(te.round(output_shape[1]), output_shape[1].dtype)),\n                simplify(topi.cast(te.round(output_shape[2]), output_shape[2].dtype)),\n            )\n\n    else:\n        raise ValueError(\"not support this layout {} yet\".format(layout))\n    coord_trans = \"align_corners\" if align_corners else \"asymmetric\"\n    if method[0:2] == \"bi\":\n        method = method[2:]\n    return topi.image.resize2d(\n        data,\n        [0.0] * 4,\n        reshape_size,\n        layout=layout,\n        method=method,\n        coordinate_transformation_mode=coord_trans,\n        output_shape=output_shape,\n    )\n\n\ndef upsampling3d(\n    data,\n    scale_d,\n    scale_h,\n    scale_w,\n    layout=\"NCDHW\",\n    method=\"nearest_neighbor\",\n    coordinate_transformation_mode=\"half_pixel\",\n    output_shape=None,\n):\n    \"\"\"Perform upsampling on the data.\n       Nearest neighbor and bilinear upsampling are supported.\n\n    Parameters\n    ----------\n    inputs : tvm.te.Tensor\n        inputs is a 5-D tensor with shape\n        [batch, channel, in_depth, in_height, in_width]\n        or  [batch, in_depth, in_height, in_width, channel]\n\n    scale_d : float\n        Scaling factor for depth\n\n    scale_h : float\n        Scaling factor for height\n\n    scale_w : float\n        Scaling factor for width\n\n    layout : string, optional\n        either \"NCDHW\" or \"NDHWC\"\n\n    method : {\"trilinear\", \"nearest_neighbor\"}\n        Method to be used for upsampling.\n\n    coordinate_transformation_mode: string, optional\n        Describes how to transform the coordinate in the resized tensor\n        to the coordinate in the original tensor.\n        Refer to the ONNX Resize operator specification for details.\n        Available options are \"half_pixel\", \"align_corners\" and \"asymmetric\".\n\n    output_shape: tvm.tir.container.Array, optional\n        Shape to return. If left None will be inferred\n        (If shape is determined dynamically, pass out_dtype.shape as output_shape)\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, channel, in_depth*scale, in_height*scale, in_width*scale]\n        or [batch, in_depth*scale, in_height*scale, in_width*scale, channel]\n    \"\"\"\n    base_layout = layout[0:5]\n    if base_layout == \"NCDHW\":\n        if not output_shape:  # static case\n            scaled_d = data.shape[2] * scale_d\n            scaled_h = data.shape[3] * scale_h\n            scaled_w = data.shape[4] * scale_w\n            resize_shape = (\n                simplify(topi.cast(te.round(scaled_d), data.shape[2].dtype)),\n                simplify(topi.cast(te.round(scaled_h), data.shape[3].dtype)),\n                simplify(topi.cast(te.round(scaled_w), data.shape[4].dtype)),\n            )\n        else:  # dynamic case -- don't need to scale; already done in shape func\n            resize_shape = (\n                simplify(topi.cast(te.round(output_shape[2]), data.shape[2].dtype)),\n                simplify(topi.cast(te.round(output_shape[3]), data.shape[3].dtype)),\n                simplify(topi.cast(te.round(output_shape[4]), data.shape[4].dtype)),\n            )\n    elif layout == \"NDHWC\":\n        if not output_shape:  # static case\n            scaled_d = data.shape[1] * scale_d\n            scaled_h = data.shape[2] * scale_h\n            scaled_w = data.shape[3] * scale_w\n            resize_shape = (\n                simplify(topi.cast(te.round(scaled_d), data.shape[1].dtype)),\n                simplify(topi.cast(te.round(scaled_h), data.shape[2].dtype)),\n                simplify(topi.cast(te.round(scaled_w), data.shape[3].dtype)),\n            )\n        else:  # dynamic case\n            resize_shape = (\n                simplify(topi.cast(te.round(output_shape[1]), data.shape[1].dtype)),\n                simplify(topi.cast(te.round(output_shape[2]), data.shape[2].dtype)),\n                simplify(topi.cast(te.round(output_shape[3]), data.shape[3].dtype)),\n            )\n    else:\n        raise ValueError(\"not support this layout {} yet\".format(layout))\n    if method[0:3] == \"tri\":\n        method = method[3:]\n    return topi.image.resize3d(\n        data,\n        [0.0] * 6,\n        resize_shape,\n        layout=layout,\n        method=method,\n        coordinate_transformation_mode=coordinate_transformation_mode,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"NN operator common utilities\"\"\"\nfrom __future__ import absolute_import\n\nimport tvm\nfrom ..utils import get_const_int\n\n\ndef infer_pad(data, data_pad):\n    \"\"\"Infer the padding from stages in reverse.\n\n    Parameters\n    ----------\n    data : Tensor\n        data stage.\n\n    data_pad : Tensor\n        pad stage.\n\n    Returns\n    -------\n    hpad : int\n        padding size on height\n    wpad : int\n        padding size on width\n    \"\"\"\n    if data_pad is None:\n        return 0, 0\n    _, _, IH, IW = data.shape\n    _, _, TH, TW = data_pad.shape\n    hpad = (TH - IH) // 2\n    wpad = (TW - IW) // 2\n    return get_const_int(hpad), get_const_int(wpad)\n\n\ndef infer_pad3d(data, data_pad, layout):\n    \"\"\"Infer the padding from stages in reverse.\n\n    Parameters\n    ----------\n    data : Tensor\n        data stage.\n\n    data_pad : Tensor\n        pad stage.\n\n    Returns\n    -------\n    dpad : int\n        padding depth\n    hpad : int\n        padding height\n    wpad : int\n        padding width\n    \"\"\"\n    if data_pad is None:\n        return 0, 0, 0\n\n    if layout == \"NDHWC\":\n        _, ID, IH, IW, _ = data.shape\n        _, TD, TH, TW, _ = data_pad.shape\n    elif layout == \"NCDHW\":\n        _, _, ID, IH, IW = data.shape\n        _, _, TD, TH, TW = data_pad.shape\n    else:\n        raise ValueError(\"Layout {} is not supported\".format(layout))\n    dpad = TD - ID\n    hpad = TH - IH\n    wpad = TW - IW\n    return get_const_int(dpad), get_const_int(hpad), get_const_int(wpad)\n\n\ndef infer_stride(data, kernel, out):\n    \"\"\"Infer the stride from stages in reverse.\n\n    Parameters\n    ----------\n    data : Tensor\n        data stage.\n\n    kernel : Tensor\n        kernel stage.\n\n    out : Tensor\n        output stage.\n\n    Returns\n    -------\n    hstride : int\n        stride size on height\n    wstride : int\n        stride size on width\n    \"\"\"\n    _, _, IH, IW = data.shape\n    _, _, KH, KW = kernel.shape\n    _, _, OH, OW = out.shape\n    hstride = (IH - KH) // tvm.te.max(OH - 1, 1) + tvm.tir.Select(OH == 1, 1, 0)\n    wstride = (IW - KW) // tvm.te.max(OW - 1, 1) + tvm.tir.Select(OW == 1, 1, 0)\n    return get_const_int(hstride), get_const_int(wstride)\n\n\ndef get_pad_tuple(padding, kernel):\n    \"\"\"Common code to get the pad option\n\n    Parameters\n    ----------\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    kernel : tuple of int\n        Conv kernel size\n\n    Returns\n    -------\n    pad_top : int\n        Padding size on top\n\n    pad_left : int\n        Padding size on left\n\n    pad_down : int\n        Padding size on down.\n\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 2:\n            pad_h = padding[0] * 2\n            pad_w = padding[1] * 2\n        elif len(padding) == 4:\n            return padding[0], padding[1], padding[2], padding[3]\n        else:\n            raise ValueError(\"Size of padding can only be 2 or 4\")\n    elif isinstance(padding, int):\n        pad_h = pad_w = padding * 2\n    elif padding == \"VALID\":\n        pad_h = 0\n        pad_w = 0\n    elif padding == \"SAME\":\n        pad_h = kernel[0] - 1\n        pad_w = kernel[1] - 1\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_top = (pad_h + 1) // 2\n    pad_left = (pad_w + 1) // 2\n    return pad_top, pad_left, pad_h - pad_top, pad_w - pad_left\n\n\ndef get_pad_tuple_generic(padding, kernel):\n    \"\"\"Common code to get the pad option\n\n    Parameters\n    ----------\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    kernel : tuple of int\n        Conv kernel size\n\n    Returns\n    -------\n    pad_top : int\n        Padding size on top\n\n    pad_down : int\n        Padding size on down.\n\n    pad_left : int\n        Padding size on left\n\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == len(kernel):\n            pad_dimensions = [p * 2 for p in padding]\n        elif len(padding) == len(kernel) * 2:\n            return [padding[i] for i in range(len(kernel))], [\n                padding[len(kernel) + i] for i in range(len(kernel))\n            ]\n        else:\n            raise ValueError(\"Size of padding can only be len(kernel) or len(kernel) * 2\")\n    elif isinstance(padding, int):\n        pad_dimensions = [padding * 2 for _ in range(len(kernel))]\n    elif padding == \"VALID\":\n        pad_dimensions = [0 for _ in range(len(kernel))]\n    elif padding == \"SAME\":\n        pad_dimensions = [k - 1 for k in kernel]\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_begin = [(p + 1) // 2 for p in pad_dimensions]\n    return [pad_begin, [pd - pb for pb, pd in zip(pad_begin, pad_dimensions)]]\n\n\ndef get_pad_tuple3d(padding, kernel):\n    \"\"\"Common code to get the pad option\n\n    Parameters\n    ----------\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    kernel : tuple of int\n        Conv kernel size\n\n    Returns\n    -------\n    pad_front : int\n        Padding size on front.\n\n    pad_top : int\n        Padding size on top\n\n    pad_left : int\n        Padding size on left\n\n    pad_back : int\n        Padding size on back.\n\n    pad_down : int\n        Padding size on down.\n\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 3:\n            pad_d = padding[0] * 2\n            pad_h = padding[1] * 2\n            pad_w = padding[2] * 2\n        elif len(padding) == 6:\n            return padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]\n        else:\n            raise ValueError(\"Size of padding can only be 3 or 6\")\n    elif isinstance(padding, int):\n        pad_d = pad_w = pad_h = padding * 2\n    elif padding == \"VALID\":\n        pad_h = 0\n        pad_w = 0\n        pad_d = 0\n    elif padding == \"SAME\":\n        pad_d = kernel[0] - 1\n        pad_h = kernel[1] - 1\n        pad_w = kernel[2] - 1\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_top = (pad_h + 1) // 2\n    pad_left = (pad_w + 1) // 2\n    pad_front = (pad_d + 1) // 2\n    return pad_front, pad_top, pad_left, pad_d - pad_front, pad_h - pad_top, pad_w - pad_left\n\n\ndef get_pad_tuple1d(padding, kernel):\n    \"\"\"Common code to get the pad option\n\n    Parameters\n    ----------\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    kernel : tuple of int\n        Conv kernel size\n\n    Returns\n    -------\n    pad_left : int\n        Padding size on left\n\n    pad_right : int\n        Padding size on right.\n    \"\"\"\n    # compute the padding size\n    if isinstance(padding, (tuple, list)):\n        if len(padding) == 1:\n            pad_w = padding[0] * 2\n        elif len(padding) == 2:\n            return padding[0], padding[1]\n        else:\n            raise ValueError(\"Size of padding can only be 2 or 4\")\n    elif isinstance(padding, int):\n        pad_w = padding * 2\n    elif padding == \"VALID\":\n        pad_w = 0\n    elif padding == \"SAME\":\n        pad_w = kernel[0] - 1\n    else:\n        raise ValueError(\"Unknown padding option %s\" % padding)\n    pad_left = (pad_w + 1) // 2\n    return pad_left, pad_w - pad_left\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/nn/winograd_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\"\"\" Utility functions for implementing Winograd convolutions\n    [*] Fast Algorithms for Convolutional Neural Networks\n        Andrew Lavin, Scott Gray\n        https://arxiv.org/abs/1509.09308\n        https://github.com/andravin/wincnn\n\"\"\"\n\nfrom operator import mul\nfrom functools import reduce\nimport numpy as np\nfrom tvm.contrib.pickle_memoize import memoize\nfrom ..utils import const_matrix\n\n\n# pylint: disable=invalid-name\ndef _cook_toom_convolution(a, n, r):\n    \"\"\"Compute Cook-Toom convolution A,B,G matrices\"\"\"\n\n    def _F_m(a, n):\n        f = lambda j, i: reduce(mul, ((a[i] - a[k] if k != i else 1) for k in range(0, n - 1)), 1)\n        F = np.fromfunction(np.vectorize(f), (1, n - 1), dtype=int)\n        F = np.diagflat(F)\n        F = np.append(F, np.zeros((n - 1, 1), dtype=int), axis=1)\n        f = lambda i, j: (1 if j == (n - 1) else 0)\n        z = np.fromfunction(np.vectorize(f), (1, n), dtype=int)\n\n        return np.append(F, z, axis=0)\n\n    def _A_m(a, m, n):\n        f = lambda i, j: a[i] ** j\n        A = np.fromfunction(np.vectorize(f), (m - 1, n), dtype=int)\n        f = lambda i, j: (1 if j == (n - 1) else 0)\n        z = np.fromfunction(np.vectorize(f), (1, n), dtype=int)\n\n        return np.append(A, z, axis=0)\n\n    def _B_m(a, n):\n        f = lambda j, i: reduce(mul, ((a[i] - a[k] if k != i else 1) for k in range(0, n - 1)), 1)\n        Ff = np.fromfunction(np.vectorize(f), (1, n - 1), dtype=int)\n        f = (\n            lambda i, nth: (\n                reduce(mul, [(np.poly1d([1, -a[k]]) if k != i else 1) for k in range(0, n - 1)], 1)\n            ).coef[n - 1 - nth - 1]\n            / Ff[0, i]\n        )\n        F = np.fromfunction(np.vectorize(f), (n - 1, n - 1), dtype=int)\n        f = lambda i, j: -a[i] ** (n - 1)\n        t = np.fromfunction(np.vectorize(f), (n - 1, 1), dtype=int)\n        T = np.append(np.eye(n - 1), t, axis=1)\n\n        return np.append(F.T.dot(T), np.array([np.eye(n)[n - 1]]), axis=0)\n\n    alpha = n + r - 1\n\n    f = _F_m(a, alpha)\n\n    if f[0, 0] < 0:\n        f[0, :] *= -1\n\n    A = _A_m(a, alpha, n)\n\n    G = _A_m(a, alpha, r).T\n    G = G.dot(np.linalg.inv(f)).T\n\n    B = _B_m(a, alpha)\n    B = B.dot(f.T)\n\n    return (A, B, G)\n\n\ndef _interpolation_points(degree):\n    \"\"\"Propose filter points\"\"\"\n\n    assert 2 < degree < 18\n\n    # Default interpolation lookup table\n    #\n    # [1] Error Analysis and Improving the Accuracy of Winograd Convolution for Deep Neural Networks\n    #     Barbara Barabasz, Andrew Anderson, Kirk M. Soodhalter, David Gregg\n    #     https://arxiv.org/abs/1803.10986\n    #\n\n    # pylint: disable=bad-whitespace,line-too-long\n    in_pts = [\n        #   {invalid}\n        [],\n        # 01 {E=4.63E-08 on conv2d  [1]}\n        [],\n        # 02 {E=7.65E-08 on F( 2,3) [1]}\n        [0, -1, 1],\n        # 03 {E=2.35E-07 on F( 3,3) [1]}\n        [0, -1, 1, 1 / 2],\n        # 04 {E=3.29E-07 on F( 4,3) [1]}\n        [0, -1, 1, 1 / 2, -2],\n        # 05 {E=6.81E-07 on F( 5,3) [1]}\n        [0, -1, 1, 1 / 2, -2, -1 / 2],\n        # 06 {E=8.79E-07 on F( 6,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2],\n        # 07 {E=3.71E-06 on F( 7,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4],\n        # 08 {E=7.35E-06 on F( 8,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4],\n        # 09 {E=2.20E-05 on F( 9,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 3 / 4, -4 / 3],\n        # 10 {E=3.22E-05 on F(10,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 3 / 4, -4 / 3],\n        # 11 {E=1.09E-04 on F(11,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 3 / 4, -4 / 3, 1 / 4],\n        # 12 {E=1.99E-04 on F(12,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4],\n        # 13 {E=5.54E-04 on F(13,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, 3 / 4, -4 / 3],\n        # 14 {E=8.80E-04 on F(14,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4, 3 / 4, -4 / 3],\n        # 15 {E=1.07E-02 on F(15,3) [1]}\n        [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4, 2 / 3, -3 / 2, 3 / 2],\n        # 16 {E=1.93E-02 on F(16,3) [1]}\n        [\n            0,\n            -1,\n            1,\n            1 / 2,\n            -1 / 2,\n            2,\n            -2,\n            -1 / 4,\n            4,\n            1 / 4,\n            -3 / 4,\n            4 / 3,\n            -4,\n            2 / 3,\n            -3 / 2,\n            -2 / 3,\n            3 / 2,\n        ],\n    ]  # pylint: enable=bad-whitespace,line-too-long\n\n    return np.array(in_pts[degree - 1], dtype=np.float64)\n\n\n@memoize(\"topi.nn.winograd_matrices\", save_at_exit=False)\ndef winograd_transform_matrices(tile_size, kernel_size, out_dtype):\n    \"\"\"Compute the A, B, and G transform matrices for `tile_size` as a `tvm.Expr`.\"\"\"\n    if not 1 < tile_size < 9:\n        raise ValueError(\"Unsupported tile size for Winograd: {}\".format(tile_size))\n    if not 2 < kernel_size < 8:\n        raise ValueError(\"Unsupported kernel size for Winograd: {}\".format(kernel_size))\n\n    degree = tile_size + kernel_size - 2\n\n    intp_pts = _interpolation_points(degree)\n    A_data, B_data, G_data = _cook_toom_convolution(intp_pts, tile_size, kernel_size)\n\n    return (\n        const_matrix(A_data.astype(out_dtype), \"A\"),\n        const_matrix(B_data.astype(out_dtype), \"B\"),\n        const_matrix(G_data.astype(out_dtype), \"G\"),\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/random/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Pseudorandom generator kernels and operators.\"\"\"\nfrom __future__ import absolute_import\n\nfrom .kernel import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/random/kernel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Pseudorandom number kernels.\"\"\"\nimport math\nimport numpy as np\n\nimport tvm\nimport tvm.topi\n\nfrom ... import tir\nfrom ...tir import ir_builder\n\n\n# Threefry PRNG with splitting based on\n# - J. K. Salmon, M. A. Moraes, R. O. Dror and D. E. Shaw, \"Parallel random numbers: As easy as 1,\n#   2, 3,\" SC '11: Proceedings of 2011 International Conference for High Performance Computing,\n#   Networking, Storage and Analysis, Seattle, WA, 2011, pp. 1-12, doi: 10.1145/2063384.2063405.\n# - Claessen, K. ; Palka, M. (2013) \"Splittable Pseudorandom Number Generators using Cryptographic\n#   Hashing\". Proceedings of Haskell Symposium 2013 pp. 47-58.  MLA\n# - Ferguson, Niels, et al. \"The Skein hash function family.\" Submission to NIST (round 3) 7.7.5\n#   (2010): 3.\n\n\n# Threefry is a counter based PRNG: given a unique input, it generates a unique random number. As\n# there is no state to maintain, we can apply it to a sequence of numbers (0..N) to generate a\n# sequence of random numbers in parallel. In order to make the PRNG splittable (that is we can\n# generate a sequence of random numbers in one place, and another sequence in another), we add a\n# path and key in addition to the counter. The path allows us to encode a sequence of splits (a 0 in\n# the path indicates the left result of a split, a 1 indicates the right). To avoid continuously\n# growing the path, we can compress an existing path into the key portion of the generator by\n# hashing the current key, path, and counter to create the new key (this same technique is used if\n# we run out of room for the counter). They key is initialized with a unique initial state.\n#\n# Random numbers are generated by applying the Threefry hash to the current key, path, and counter.\n\n# This module use encoding e4 from the appendix of \"Splittable Pseudorandom Number Generators using\n# Cryptographic Hashing\" (confusingly, the definition in the paper uses e3 to define the encoding\n# function). This encoding uses a 10 element uint64 tensor where each byte means the following:\n\n# .. code-block:\n\n#     gen:\n#     words: 0 1 2 3 | 4 5  | 6 7     | 8 9\n#     usage: key     | path | counter | position of next step in path encoded in binary\n#                                       ex: 0b00010 -> next path entry goes one from the right\n\n# Right now, counter only uses the rightmost word.\n\n# Threefry rotation constants from the Skein paper (\"The Skein Hash Function Family\"\n# https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf)\n_ROTATIONS = {\n    4: [[14, 16], [52, 57], [23, 40], [5, 37], [25, 33], [46, 12], [58, 22], [32, 32]],\n    8: [\n        [46, 36, 19, 37],\n        [33, 27, 14, 42],\n        [17, 49, 36, 39],\n        [44, 9, 54, 56],\n        [39, 30, 34, 24],\n        [13, 50, 10, 17],\n        [25, 29, 39, 43],\n        [8, 35, 56, 22],\n    ],\n    16: [\n        [24, 13, 8, 47, 8, 17, 22, 37],\n        [38, 19, 10, 55, 49, 18, 23, 52],\n        [33, 4, 51, 13, 34, 41, 59, 17],\n        [5, 20, 48, 41, 47, 28, 16, 25],\n        [41, 9, 37, 31, 12, 47, 44, 30],\n        [16, 34, 56, 51, 4, 53, 42, 41],\n        [31, 44, 47, 46, 19, 42, 44, 25],\n        [9, 48, 35, 52, 23, 31, 37, 20],\n    ],\n}\n\n# Threefry permutation constants from the Skein paper (\"The Skein Hash Function Family\"\n# https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf)\n_PERMUTATIONS = {\n    4: [0, 3, 2, 1],\n    8: [2, 1, 4, 7, 6, 5, 0, 3],\n    16: [0, 9, 2, 13, 6, 11, 4, 15, 10, 7, 12, 3, 14, 5, 8, 1],\n}\n\n\ndef _threefry(\n    irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape\n):\n    \"\"\"IRBuilder code for running Threefry\n\n    Parameters\n    ----------\n    irb: IRBuilder\n        IRBuilder that this code will be generated for.\n\n    key_buf: BufferVar\n        Buffer to read the key from.\n\n    key_offset: number\n        Threefry will write to :code:`key_buf[key_offset:key_offset+4]`\n\n    counter_buf: BufferVar\n        Buffer to read the counter from.\n\n    counter_offset: number\n        Threefry will write to :code:`counter_buf[counter_offset:counter_offset+4]`\n\n    out_buf: BufferVar\n        Buffer to read the counter from.\n\n    out_offset: number\n        Threefry will write to :code:`out_buf[out_offset:out_offset+4*product(out_shape)]`\n\n    out_shape: number\n        Determines the number of output states to generate. :code:`state[i]` will correspond to\n        counter+i.\n    \"\"\"\n    nrounds = 20\n    nwords = 4\n    iwidth = 64\n    assert nrounds % 4 == 0\n    assert nwords in [4, 8, 16]\n\n    # The paper has constants for 32 bit threefry, but we keep the implementation simple by only\n    # using 64-bit words.\n    assert key_buf.dtype == \"uint64\", \"threefry only supports 64-bit keys\"\n    assert key_buf.dtype == counter_buf.dtype, \"threefry key and counter must be the same dtype\"\n\n    def mix(a, b, rotation):\n        x = a + b  # wrapping\n        y = x ^ ((b << rotation) | (b >> (iwidth - rotation)))\n        return [x, y]\n\n    # temporary buffer for holding the results of _PERMUTATIONS\n    tmp = irb.allocate(out_buf.dtype, out_shape * nwords, name=\"tmp\", scope=\"global\")\n    tmp_offset = 0\n\n    # Initialize entire key. It is composed of the original key with one\n    # element appended. The appended element is the xor of all key words plus a\n    # constant.\n    full_key = irb.allocate(\"uint64\", nwords + 1, name=\"full_key\", scope=\"global\")\n    for i in range(nwords):\n        full_key[i] = key_buf[key_offset + i]\n    # initial key constant, full_key[nwords] is equivalent to k_{N_W} in the Skein paper.\n    full_key[nwords] = tvm.tir.const(0x1BD11BDAA9FC1A22, dtype=\"uint64\")\n    for i in range(nwords):\n        full_key[nwords] ^= key_buf[key_offset + i]\n\n    with irb.for_range(0, out_shape, dtype=\"uint64\", name=\"i\") as i:\n        for j in range(nwords):\n            out_buf[out_offset + i * nwords + j] = counter_buf[counter_offset + j] + i\n\n    def key_schedule(s, i):\n        # Threefry uses no tweak, so the key schedule is simple\n        if i == nwords - 1:\n            return full_key[(s + i) % (nwords + 1)] + tvm.tir.const(s, dtype=\"uint64\")\n        return full_key[(s + i) % (nwords + 1)]\n\n    with irb.for_range(0, out_shape, name=\"l\") as l:  # pylint: disable=invalid-name\n        for i in range(nrounds // 4):\n            for j in range(nwords):\n                out_buf[out_offset + l * nwords + j] += key_schedule(i, j)  # wrapping\n            for k in range(4):\n                for j in range(nwords // 2):\n                    (\n                        out_buf[out_offset + l * nwords + j * 2 + 0],\n                        out_buf[out_offset + l * nwords + j * 2 + 1],\n                    ) = mix(\n                        out_buf[out_offset + l * nwords + j * 2 + 0],\n                        out_buf[out_offset + l * nwords + j * 2 + 1],\n                        _ROTATIONS[nwords][(i * 4 + k) % 8][j],\n                    )\n                for j in range(nwords):\n                    tmp[tmp_offset + l * nwords + j] = out_buf[\n                        out_offset + l * nwords + _PERMUTATIONS[nwords][j]\n                    ]\n                # number of rounds is even, so out always contains the result\n                (out_buf, tmp) = (tmp, out_buf)\n                (out_offset, tmp_offset) = (tmp_offset, out_offset)\n\n\ndef threefry_generate(gen, out_shape):\n    \"\"\"Generate a series of random values\n\n    Notes\n    -----\n    This function uses the counter portion of the generator state to generate a series of random\n    numbers in parallel. Random number `i` is generated by applying Threefry to the current\n    generator state with the counter portion incremented by `i`. This means that each random number\n    is generated independently from each other random number, so we can compute them in parallel.\n\n    If there is not enough room left in the counter to generate the desired shape of random values,\n    then a new generator is created by applying Threefry to the current key, path, and counter.\n    This new generator will have a reset counter.\n\n    Warning\n    -------\n    Threeyfry requires that unsigned integer arithmetic wraps on overflow. Currently TVM has no\n    guarantee of this, so threefry contains an internal assert to check wrapping behavior. This\n    assert may or may not run depending on your platform, so it is recommended you run\n    :py:func:`threefry_test_wrapping` to verify wrapping behavior.\n\n    Parameters\n    ----------\n    gen : Tensor[10, uint64]\n        Generator state. Can be create with :py:func:`tvm.relay.random.threefry_key`. This should\n        not be reused in another function, otherwise random numbers will be repeated.\n\n    out_shape : Sequence[int]\n        Output shape of the random numbers.\n\n    Returns\n    -------\n    new_gen : Tensor[10, uint64]\n        The new generator state to be used in subsequent calls.\n\n    rand : Tensor[out_shape, uint64]\n        Tensor of random numbers with shape `out_shape`.\n    \"\"\"\n    out_len = tir.const(1)\n    for s in out_shape:\n        out_len *= s\n    assert (\n        out_len.value <= 2**64 - 1\n    ), f\"Can only generate up to 2^64 random numbers, but {out_len} were requested.\"\n\n    def gen_ir(gen_ptr, out_gen_ptr, out_array_ptr):\n        irb = ir_builder.create()\n        gen = irb.buffer_ptr(gen_ptr)\n        out_gen = irb.buffer_ptr(out_gen_ptr)\n        out_array = irb.buffer_ptr(out_array_ptr)\n\n        # Check that unsigned arithmetic wraps, as it is required to implement threefry correctly.\n        irb.emit(\n            tvm.tir.AssertStmt(\n                tvm.tir.const(0xFFFFFFFFFFFFFFFF, \"uint64\") + tvm.tir.const(1, \"uint64\")\n                == tvm.tir.const(0, \"uint64\"),\n                tvm.tir.StringImm(\n                    \"Unsigned integer arithmetic is not wrapping, but threefry requires wrapping.\"\n                ),\n                tvm.tir.Evaluate(0),\n            )\n        )\n\n        # Create a temporary array to hold the generator state we will use to create the random\n        # numbers. We cannot use gen because we may need to update the key + path if there is not\n        # enough room in the counter.\n        tmp = irb.allocate(gen.dtype, 10, name=\"tmp\", scope=\"global\")\n\n        # TODO(tkonolige): for now we only use the last word of the counter for counting. It is too\n        # much work to figure out how to do 128 bit addition.\n\n        # Max value for counter should be 2**64-2 because we need to reserve a special value to\n        # indicate the counter is used up.\n        with irb.if_scope(gen[7] < tir.const(2**64 - 1, dtype=gen.dtype) - out_len):\n            for i in range(10):\n                tmp[i] = gen[i]\n        with irb.else_scope():\n            # no room left in the counter, we have to change the path or key\n            with irb.if_scope(gen[8] == 0 and gen[9] == 0):\n                # out of room in the path, have to generate new key\n\n                # The paper says the counter that we will be hashing should be a special value of\n                # all ones. We need to allocate some space for it because we cannot overwrite gen.\n                tmp_counter = irb.allocate(gen.dtype, 2, name=\"tmp_counter\", scope=\"global\")\n                tmp_counter[0] = tir.const(0xFFFFFFFFFFFFFFFF, dtype=gen.dtype)\n                tmp_counter[1] = tir.const(0xFFFFFFFFFFFFFFFF, dtype=gen.dtype)\n                _threefry(irb, gen, 0, tmp_counter, 0, tmp, 0, 1)\n                tmp[4] = tir.const(0, dtype=gen.dtype)  # zero path, i.e. no path\n                tmp[5] = tir.const(0, dtype=gen.dtype)\n                tmp[6] = tir.const(0, dtype=gen.dtype)  # zero counter\n                tmp[7] = tir.const(0, dtype=gen.dtype)\n                tmp[8] = tir.const(1 << 63, dtype=gen.dtype)  # one in the leftmost position\n                tmp[9] = tir.const(0, dtype=gen.dtype)\n            with irb.else_scope():\n                tmp[0] = gen[0]\n                tmp[1] = gen[1]\n                tmp[2] = gen[2]\n                tmp[3] = gen[3]\n                tmp[4] = gen[4] | gen[8]  # add a 1 to the path\n                tmp[5] = gen[5] | gen[9]\n                tmp[6] = tir.const(0, dtype=gen.dtype)  # zero counter\n                tmp[7] = tir.const(0, dtype=gen.dtype)\n                _shift_right(irb, gen[8], gen[9], tmp, 8, tmp, 9)\n\n        # Compute random values\n        if out_len.value >= 4:\n            _threefry(irb, tmp, 0, tmp, 4, out_array, 0, out_len // 4)\n        if out_len.value % 4 != 0:\n            remaining = irb.allocate(gen.dtype, 4, name=\"remaining\", scope=\"global\")\n            tmp[7] = tmp[7] + tir.Cast(gen.dtype, out_len // 4 * 4)  # increment counter\n            _threefry(irb, tmp, 0, tmp, 4, remaining, 0, 1)\n            with irb.for_range(0, out_len % 4, dtype=\"uint64\", name=\"i\") as i:\n                out_array[out_len // 4 * 4 + i] = remaining[i]\n\n        # Update generator state\n        out_gen[0] = tmp[0]  # key stays the same\n        out_gen[1] = tmp[1]\n        out_gen[2] = tmp[2]\n        out_gen[3] = tmp[3]\n        out_gen[4] = tmp[4]  # path stays the same\n        out_gen[5] = tmp[5]\n        out_gen[6] = tir.const(0, dtype=gen.dtype)  # unused, leave it as 0\n        if out_len.value % 4 != 0:\n            # increment counter for the remaining\n            # as we will generate 4 random numbers for the remaining, increase 4 here.\n            # the main increment was done before the second _threefry.\n            out_gen[7] = tmp[7] + tir.Cast(gen.dtype, 4)\n        else:\n            out_gen[7] = tmp[7] + tir.Cast(gen.dtype, out_len)  # increment counter\n        out_gen[8] = tmp[8]  # path unchanged, so no update here\n        out_gen[9] = tmp[9]\n\n        return irb.get()\n\n    out_gen = tvm.tir.decl_buffer((10,), name=\"out_gen\", dtype=\"uint64\")\n    out_array = tvm.tir.decl_buffer(out_shape, name=\"out_array\", dtype=\"uint64\")\n    return tvm.te.extern(\n        [out_gen.shape, out_array.shape],\n        [gen],\n        lambda ins, outs: gen_ir(ins[0], outs[0], outs[1]),\n        out_buffers=[out_gen, out_array],\n        name=\"threefry_generate\",\n        tag=\"threefry_generate\",\n    )\n\n\ndef _shift_right(irb, a, b, out_a, a_off, out_b, b_off):\n    \"\"\"Binary shift a 128bit number composed of two 64 bit words right by one.\"\"\"\n    with irb.if_scope(a == 1):\n        out_a[a_off] = tir.const(0, dtype=a.dtype)\n        out_b[b_off] = tir.const(0x8000000000000000, dtype=a.dtype)\n    with irb.else_scope():\n        with irb.if_scope(a == 0):\n            out_a[a_off] = tir.const(0, dtype=a.dtype)\n            out_b[b_off] = b >> 1\n        with irb.else_scope():\n            out_a[a_off] = a >> 1\n            out_b[b_off] = tir.const(0, dtype=a.dtype)\n\n\ndef threefry_split(gen):\n    \"\"\"Split a single generator state into two new ones\n\n    Notes\n    -----\n    The new generator is created by appending a one (for the right output) or a zero (for the left\n    output) to the end of the path portion of the generator If there is no longer and room in the\n    path, then we create a new key portion of the generator by applying Threefry to the old state,\n    path, and counter. i.e. :code:`new_key = threefry(old_key, [old_path, old_counter])`. This\n    resets the path portion of the new generator.\n\n    Parameters\n    ----------\n    gen : Tensor[10, uint64]\n        Generator state. Can be create with :py:func:`tvm.relay.random.threefry_key`. This should\n        not be reused in another function, otherwise random numbers will be repeated.\n\n    Returns\n    -------\n    out_gen_left : Tensor[10, uint64]\n        New generator state that is distinct from `out_gen_right`.\n\n    out_gen_right : Tensor[10, uint64]\n        New generator state that is distinct from `out_gen_left`.\n    \"\"\"\n\n    def gen_ir(gen_ptr, out_left_ptr, out_right_ptr):\n        irb = ir_builder.create()\n        gen = irb.buffer_ptr(gen_ptr)\n        out_left = irb.buffer_ptr(out_left_ptr)\n        out_right = irb.buffer_ptr(out_right_ptr)\n\n        with irb.if_scope(gen[8] == 0 and gen[9] == 0):\n            # Generate new key because we have run out of room to extend the path\n            _threefry(irb, gen, 0, gen, 4, out_left, 0, 1)\n            out_left[4] = tir.const(0, dtype=gen.dtype)\n            out_left[5] = tir.const(0, dtype=gen.dtype)\n            out_left[6] = tir.const(0, dtype=gen.dtype)  # counter gets zeroed\n            out_left[7] = tir.const(0, dtype=gen.dtype)  # counter gets zeroed\n            out_left[8] = tir.const(\n                1 << 62, dtype=gen.dtype\n            )  # one in the second from the leftmost position\n            out_left[9] = tir.const(0, dtype=gen.dtype)\n\n            out_right[0] = out_left[0]\n            out_right[1] = out_left[1]\n            out_right[2] = out_left[2]\n            out_right[3] = out_left[3]\n            out_right[4] = tir.const(1 << 63, dtype=gen.dtype)  # one in the leftmost position\n            out_right[5] = tir.const(0, dtype=gen.dtype)\n            out_right[6] = tir.const(0, dtype=gen.dtype)\n            out_right[7] = tir.const(0, dtype=gen.dtype)\n            out_right[8] = tir.const(\n                1 << 62, dtype=gen.dtype\n            )  # one in the second from the leftmost position\n            out_right[9] = tir.const(0, dtype=gen.dtype)\n        with irb.else_scope():\n            out_left[0] = gen[0]\n            out_left[1] = gen[1]\n            out_left[2] = gen[2]\n            out_left[3] = gen[3]\n            out_left[4] = gen[4]  # adding a zero here, but its already zero padded\n            out_left[5] = gen[5]\n            out_left[6] = gen[6]\n            out_left[7] = gen[7]\n            # move path position over one bit\n            _shift_right(irb, gen[8], gen[9], out_left, 8, out_left, 9)\n\n            out_right[0] = gen[0]\n            out_right[1] = gen[1]\n            out_right[2] = gen[2]\n            out_right[3] = gen[3]\n            out_right[4] = gen[4] | gen[8]  # add a one to the path\n            out_right[5] = gen[5] | gen[9]\n            out_right[6] = gen[6]\n            out_right[7] = gen[7]\n            _shift_right(irb, gen[8], gen[9], out_right, 8, out_right, 9)\n\n        return irb.get()\n\n    out_left = tvm.tir.decl_buffer((10,), name=\"out_left\", dtype=\"uint64\")\n    out_right = tvm.tir.decl_buffer((10,), name=\"out_right\", dtype=\"uint64\")\n    return tvm.te.extern(\n        [out_left.shape, out_right.shape],\n        [gen],\n        lambda ins, outs: gen_ir(ins[0], outs[0], outs[1]),\n        out_buffers=[out_left, out_right],\n        name=\"threefry_split\",\n        tag=\"threefry_split\",\n    )\n\n\ndef threefry_test_wrapping(target, device):\n    \"\"\"Test that unsigned arithmetic wraps on overflow.\n\n    Parameters\n    ----------\n    target : tvm.target.Target\n        Target to run against\n    device : tvm.runtime.Device\n        Context to run the test on\n\n    Returns\n    -------\n    is_wrapping : bool\n        Whether or not unsigned integer arithmetic is wrapping for this target, context pair. True\n        indicates that threefry will work on this platform.\n    \"\"\"\n    if isinstance(target, str):\n        target = tvm.target.Target(target)\n\n    def gen_ir(out_ptr):\n        irb = ir_builder.create()\n        out = irb.buffer_ptr(out_ptr)\n        if \"gpu\" in target.keys:\n            thread_x = tvm.te.thread_axis(\"threadIdx.x\")\n            irb.scope_attr(thread_x, \"thread_extent\", 1)\n        out[0] = tvm.tir.const(0xFFFFFFFFFFFFFFFF, \"uint64\") + tvm.tir.const(1, \"uint64\")\n        return irb.get()\n\n    out = tvm.tir.decl_buffer((1,), dtype=\"uint64\")\n    f = tvm.te.extern(\n        [out.shape], [], lambda ins, outs: gen_ir(outs[0]), dtype=\"uint64\", out_buffers=[out]\n    )\n    s = tvm.te.create_schedule([f.op])\n    out_ary = tvm.nd.array(np.ones((1,), \"uint64\"), device)\n    tvm.build(s, [f], target=target)(out_ary)\n    return out_ary.numpy()[0] == 0\n\n\ndef uniform(gen, low, high, out_shape, out_dtype):\n    \"\"\"Draw samples from a uniform distribution.\n\n    Samples are uniformly distributed over the half-open interval [low, high)\n    (includes low, but excludes high). In other words, any value within the\n    given interval is equally likely to be drawn by uniform.\n\n    Parameters\n    ----------\n    gen : ThreefryKey\n        Generator state. Can be create with :py:func:`tvm.relay.threefry_key`. This should not be\n        reused in another function, otherwise random numbers will be repeated.\n\n    low : Tensor[(), out_dtype]\n        Lower boundary of the output interval. All values generated will be\n        greater than or equal to low.\n\n    high : Tensor[(), out_dtype]\n        Upper boundary of the output interval. All values generated will be\n        less than high.\n\n    out_shape : Sequence[int]\n        Output shape of the random numbers.\n\n    out_dtype : str\n        The output dtype.\n\n    Returns\n    -------\n    new_gen : ThreefryKey\n        New generator state that is distinct from `gen`.\n\n    out : Tensor[out_shape, out_dtype]\n        Tensor of random numbers with shape `out_shape` and type `out_dtype`.\n    \"\"\"\n    new_gen, random_bits = threefry_generate(gen, out_shape)\n    assert out_dtype in (\"float32\", \"float64\"), (\n        \"Only support float32 or float64 for now, got %s\" % out_dtype\n    )\n    if out_dtype == \"float32\":\n        random_dtype = \"uint32\"\n        nbits = 32\n        nfraction = 23\n    elif out_dtype == \"float64\":\n        random_dtype = \"uint64\"\n        nbits = 64\n        nfraction = 52\n    nexp = nbits - nfraction - 1\n    random_bits = random_bits.astype(random_dtype)\n\n    fraction = tvm.topi.right_shift(\n        random_bits, tvm.tir.const(nbits - nfraction, dtype=random_dtype)\n    )\n    exponent = tvm.topi.left_shift(\n        tvm.topi.full(out_shape, random_dtype, (1 << (nexp - 1)) - 1),\n        tvm.tir.const(nfraction, dtype=random_dtype),\n    )\n    mantissa = tvm.topi.bitwise_or(fraction, exponent).astype(random_dtype)\n    standard_uniform_values = tvm.topi.reinterpret(mantissa, out_dtype) - tvm.tir.const(\n        1, dtype=out_dtype\n    )\n    uniform_values = tvm.topi.add(tvm.topi.multiply(standard_uniform_values, high - low), low)\n\n    return new_gen, uniform_values\n\n\ndef normal(gen, mean, scale, out_shape, out_dtype):\n    \"\"\"Draw samples from a normal distribution.\n    The algorithm is based on Box-Muller transform\n\n    Parameters\n    ----------\n    gen : ThreefryKey\n        Generator state. Can be create with :py:func:`tvm.relay.threefry_key`. This should not be\n        reused in another function, otherwise random numbers will be repeated.\n\n    mean : Tensor[(), out_dtype]\n        The mean of the normal distribution.\n\n    scale : Tensor[(), out_dtype]\n        The standard deviation of the normal distribution.\n\n    out_shape : Sequence[int]\n        Output shape of the random numbers.\n\n    out_dtype : str\n        The output dtype.\n\n    Returns\n    -------\n    new_gen : ThreefryKey\n        New generator state that is distinct from `gen`.\n\n    out : Tensor[out_shape, out_dtype]\n        Tensor of random numbers with shape `out_shape` and type `out_dtype`.\n    \"\"\"\n    out_shape = list(out_shape)\n    # Box-Muller transform need two pieces of original uniform data\n    out_shape.insert(0, 2)\n    new_gen, uniform_values = uniform(\n        gen,\n        tvm.tir.const(0.0, out_dtype),\n        tvm.tir.const(1.0, out_dtype),\n        out_shape,\n        out_dtype,\n    )\n    two_pi = tvm.tir.const(2.0 * math.pi, out_dtype)\n    uniform_values_1 = tvm.topi.strided_slice(uniform_values, [0], [1], strides=[1], axes=[0])\n    uniform_values_1 = tvm.topi.squeeze(uniform_values_1, axis=0)\n    uniform_values_2 = tvm.topi.strided_slice(uniform_values, [1], [2], strides=[1], axes=[0])\n    uniform_values_2 = tvm.topi.squeeze(uniform_values_2, axis=0)\n    uniform_values_1 = tvm.topi.subtract(tvm.tir.const(1.0, out_dtype), uniform_values_1)\n    sqrt_values = tvm.topi.sqrt(\n        tvm.topi.multiply(tvm.tir.const(-2.0, out_dtype), tvm.topi.log(uniform_values_1))\n    )\n    sin_values = tvm.topi.sin(tvm.topi.multiply(two_pi, uniform_values_2))\n    random_values = tvm.topi.add(\n        tvm.topi.multiply(tvm.topi.multiply(sqrt_values, sin_values), scale), mean\n    )\n\n    return new_gen, random_values\n\n\ndef multinomial(gen, probs, num_samples):\n    \"\"\"Draw samples from a multinomial distribution defined by the input tensor.\n\n    Parameters\n    ----------\n    gen : ThreefryKey\n        Generator state. Can be created with :py:func:`tvm.relay.threefry_key`. This should not be\n        reused in another function, otherwise random numbers will be repeated.\n\n    probs: Tensor[(input_rows, indices), float]\n        A tensor containing the probabilities to sample from. Each value represents the\n        probability of choosing its corresponding index. If a tensor is provided, the last dimension\n        is treated independently. Negative values in this tensor will be clipped to zero to\n        represent they have no chance of being selected.\n\n    num_samples: int\n        Number of samples to draw from each row.\n\n    Returns\n    -------\n    new_gen : ThreefryKey\n        New generator state that is distinct from `gen`.\n\n    out : Tensor[(input_rows, num_samples), int64]\n        Tensor of sampled indices with shape `input_rows x num_samples` and type `out_dtype`.\n    \"\"\"\n    # Convert to float for consistent behavior.\n    probs = tvm.topi.cast(probs, \"float32\")\n    # Clip negative values to 0.\n    probs = tvm.topi.maximum(probs, 0)\n    # Normalize input probabilities.\n    probs = tvm.topi.divide(probs, tvm.topi.expand_dims(tvm.topi.sum(probs, axis=-1), -1))\n    # Convert probability to cumulative sum.\n    cumulative_probs = tvm.topi.cumsum(probs, axis=-1)\n    # Sample a set of uniform values.\n    new_gen, uniform_values = uniform(\n        gen,\n        tvm.tir.const(0.0, \"float32\"),\n        tvm.tir.const(1.0, \"float32\"),\n        [*probs.shape[:-1], num_samples],\n        \"float32\",\n    )\n    # Find index corresponding to sampled values.\n    closest_prob = tvm.topi.subtract(\n        tvm.topi.expand_dims(cumulative_probs, axis=-1),\n        tvm.topi.expand_dims(uniform_values, axis=-2),\n    )\n    zeros = tvm.topi.full_like(closest_prob, 0)\n    ones = tvm.topi.full_like(closest_prob, 1)\n    # Find the smallest positive index for each sample.\n    cond = tvm.topi.greater(closest_prob, zeros)\n    closest_non_neg = tvm.topi.where(cond, closest_prob, ones)\n    sampled_indices = tvm.topi.argmin(closest_non_neg, axis=-2)\n    return new_gen, sampled_indices\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=redefined-builtin,consider-using-enumerate,no-member\n\"\"\"Reduce operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom . import cpp\n\n\ndef _get_real_axis(ndim, axis):\n    if axis is None:\n        real_axis = list(range(ndim))\n    else:\n        if isinstance(axis, int):\n            axis = [axis]\n        else:\n            assert isinstance(axis, (list, tuple))\n        real_axis = []\n        for ele in axis:\n            if ele < 0:\n                ele += ndim\n            if ele >= ndim:\n                raise ValueError(\n                    \"{} exceeds the maximum dimension {}. Received axis={}\".format(ele, ndim, axis)\n                )\n            real_axis.append(ele)\n        real_axis.sort()\n        real_axis = list(set(real_axis))  # Remove the duplicates\n    return real_axis\n\n\ndef sum(data, axis=None, keepdims=False):\n    \"\"\"Sum of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a sum is performed.\n        The default, axis=None, will sum all of the elements of the input array.\n        If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.sum(data, axis, keepdims)\n\n\ndef all(data, axis=None, keepdims=False):\n    \"\"\"Logical AND of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm boolean tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a logical AND is performed.\n        The default, axis=None, will perform logical AND over all elements of the input array.\n        If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.all(data, axis, keepdims)\n\n\ndef any(data, axis=None, keepdims=False):\n    \"\"\"Logical OR of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm boolean tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a logical OR is performed.\n        The default, axis=None, will perform logical OR over all elements of the input array.\n        If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.any(data, axis, keepdims)\n\n\ndef max(data, axis=None, keepdims=False):\n    \"\"\"Maximum of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which the max operation is performed.\n        The default, axis=None, will find the max element from all of the elements of the input\n        array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.max(data, axis, keepdims)\n\n\ndef min(data, axis=None, keepdims=False):\n    \"\"\"Minimum of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a minimum operation is performed.\n        The default, axis=None, will find the minimum element from all of the elements of the\n        input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.min(data, axis, keepdims)\n\n\ndef argmax(data, axis=None, keepdims=False, select_last_index=False):\n    \"\"\"Returns the indices of the maximum values along an axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a argmax operation is performed.\n        The default, axis=None, will find the indices of the maximum element of the elements of\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    select_last_index: bool\n        Whether to select the last index if the maximum element appears multiple times, else\n        select the first index.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.argmax(data, axis, keepdims, select_last_index)\n\n\ndef argmin(data, axis=None, keepdims=False, select_last_index=False):\n    \"\"\"Returns the indices of the minimum values along an axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a argmin operation is performed.\n        The default, axis=None, will find the indices of minimum element all of the elements of\n        the input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    select_last_index: bool\n        Whether to select the last index if the minimum element appears multiple times, else\n        select the first index.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.argmin(data, axis, keepdims, select_last_index)\n\n\ndef prod(data, axis=None, keepdims=False):\n    \"\"\"Product of array elements over a given axis or a list of axes\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tvm tensor\n\n    axis : None or int or tuple of int\n        Axis or axes along which a prod operation is performed.\n        The default, axis=None, will get the prod element over all of the elements of the\n        input array. If axis is negative it counts from the last to the first axis.\n\n    keepdims : bool\n        If this is set to True, the axes which are reduced are left in the result as dimensions\n        with size one.\n        With this option, the result will broadcast correctly against the input array.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.prod(data, axis, keepdims)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/rocm/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"rocm specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .batch_matmul import *\nfrom .conv2d import *\nfrom .dense import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/rocm/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Schedule for batch_matmul operator\"\"\"\nfrom tvm import autotvm\nfrom tvm.contrib import rocblas\nfrom .. import generic\nfrom ..utils import get_const_tuple\n\n\n@autotvm.register_topi_compute(\"batch_matmul_rocblas.rocm\")\ndef batch_matmul_rocblas(\n    cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Computes matrix multiplication of `x` and `y` via rocblas when\n    `x` and `y` are batched matrices.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file\n    x : tvm.te.Tensor\n        3-D with shape [batch, M, K]\n    y : tvm.te.Tensor\n        3-D with shape [batch, N, K]\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    del out_dtype\n    batch, M, K = get_const_tuple(x.shape)\n    _, N, _ = get_const_tuple(y.shape)\n    if out_shape is not None:\n        assert out_shape[0] == batch, \"Input and output batch sizes must match\"\n        assert out_shape[1] == M and out_shape[2] == N, \"Invalid output shape\"\n    result = rocblas.batch_matmul(x, y, transpose_a, transpose_b)\n    cfg.add_flop(batch * M * N * K * 2)\n    return result\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_rocblas.rocm\")\ndef schedule_batch_matmul_rocblas(_, outs):\n    \"\"\"Schedule for batch_matmul operator with rocm cblas\"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/rocm/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\"\"\"Compute definition for conv2d with rocm backend\"\"\"\nfrom tvm import autotvm\nfrom tvm.contrib import miopen\n\nfrom .. import generic\nfrom ..utils import get_const_tuple\nfrom ..nn.utils import get_pad_tuple\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_miopen.rocm\")\ndef conv2d_nchw_miopen(\n    cfg, data, kernel, strides, padding, dilation, layout=\"NCHW\", out_dtype=\"float32\"\n):\n    \"\"\"Conv2D operator for rocm backend.\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    filter : tvm.te.Tensor\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    strides : int or a list/tuple of two ints\n        stride size, or [stride_height, stride_width]\n\n    padding : int or a list/tuple of 2 or 4 ints\n        padding size, or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 4 ints\n\n    layout : str\n        layout of data\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n\n    CO, CI, KH, KW = get_const_tuple(kernel.shape)\n    N, _, H, W = get_const_tuple(data.shape)\n\n    assert layout == \"NCHW\"\n\n    # handle dilation\n    stride_h, stride_w = (strides, strides) if isinstance(strides, int) else strides\n    pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW))\n    pad_h, pad_w = pt + pb, pl + pr\n    dilation_h, dilation_w = (dilation, dilation) if isinstance(dilation, int) else dilation\n    assert (pt == pb) and (pl == pr)\n    OH = (H + 2 * pad_h - KH) // stride_h + 1\n    OW = (W + 2 * pad_w - KW) // stride_w + 1\n    cfg.add_flop(\n        2 * N * OH * OW * CO * CI * ((KH - 1) * dilation_h + 1) * ((KW - 1) * dilation_w + 1)\n    )\n\n    return miopen.conv2d_forward(\n        data, kernel, stride_h, stride_w, pt, pl, dilation_h, dilation_w, conv_mode=0, data_type=1\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_miopen.rocm\")\ndef schedule_conv2d_nchw_miopen(cfg, outs):\n    \"\"\"TOPI schedule callback of conv2d for rocm\n\n    Parameters\n    ----------\n    cfg: ConfigEntity\n        The config for this template\n\n    outs: Array of Tensor\n        The computation graph description of conv2d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv2d.\n    \"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/rocm/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Schedule for dense operator\"\"\"\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.contrib import rocblas\nfrom .. import generic\nfrom .. import tag\n\n\n@autotvm.register_topi_compute(\"dense_rocblas.rocm\")\ndef dense_rocblas(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense operator for rocm backend with cblas.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim]\n\n    bias : tvm.te.Tensor, optional\n        1-D with shape [out_dim]\n\n    out_dtype : str\n        The output type. This is used for mixed precision.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n    assert out_dtype == data.dtype, \"Mixed precision not supported.\"\n    matmul = rocblas.matmul(data, weight, False, True)\n    batch, in_dim = data.shape\n    out_dim, _ = weight.shape\n    cfg.add_flop(batch * in_dim * out_dim * 2)\n    if bias is not None:\n        matmul = te.compute(\n            (batch, out_dim), lambda i, j: matmul[i, j] + bias[j], tag=tag.BROADCAST\n        )\n    return matmul\n\n\n@autotvm.register_topi_schedule(\"dense_rocblas.rocm\")\ndef schedule_dense_rocblas(_, outs):\n    \"\"\"Schedule for dense operator with rocm cblas\"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/scan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Scan (cumulative binary) operators\"\"\"\nfrom typing import Callable, Optional\n\nimport tvm\n\nfrom ..te import extern\nfrom ..tir import decl_buffer, generic, ir_builder\nfrom .math import cast\nfrom . import utils\n\n\ndef scanop(\n    data: tvm.te.Tensor,\n    binop: Callable[[\"tvm.Expr\", \"tvm.Expr\"], \"tvm.Expr\"],\n    identity_value: \"tvm.Expr\",\n    op_name: str,\n    axis: Optional[int] = None,\n    dtype: Optional[str] = None,\n    exclusive: Optional[bool] = None,\n) -> tvm.te.Tensor:\n    \"\"\"Cumulative binary operator (scan) with similar axis behavior as np.cumsum and np.cumprod.\n\n    See cumprod and cumsum for an example of use.\n\n    E.g. if * is your binary operator and the input tensor is [1, 2, 3, 4] the output may be\n    [1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4]\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    binop: Callable (tvm.Expr, tvm.Expr) -> tvm.Expr\n        A binary operator which should be associative and commutative. E.g. if * is your\n        operator then a * (b * c) = (a * b) * c and a * b = b * a\n\n    identity_value: tvm.Expr\n        A value for the binary operation which provides the identity property. E.g. if * is\n        your operator and i is the identity_value then a * i = a for all a in the domain of\n        your operation.\n\n    axis : int, optional\n        Axis along which the operation is computed. The default (None) is to compute\n        the cumulative operation over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are computed.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If True will return exclusive cumulative operation in which the first element is not\n        included. In other terms, if True, the j-th output element would be\n        the cumulative operation of the first (j-1) elements. Otherwise, it would be the\n        cumulative operation of the first j elements. The cumulative operation of zero elements\n        is assumed to be the identity_value.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    if dtype is None or dtype == \"\":\n        dtype = data.dtype\n\n    if exclusive is None:\n        exclusive = False\n\n    def maybe_cast(x):\n        if dtype != data.dtype:\n            return cast(x, dtype)\n        return x\n\n    axis_mul_before = 1\n    axis_mul_after = 1\n\n    if axis is None:\n        axis = 0\n        cumsum_axis_len = utils.prod(data.shape)\n        shape = (cumsum_axis_len,)\n    else:\n        if not isinstance(axis, int):\n            axis = utils.get_const_int(axis)\n\n        shape = data.shape\n        cumsum_axis_len = shape[axis]\n\n        if axis < 0:\n            axis = len(shape) + axis\n\n        for i, value in enumerate(shape, 0):\n            if i < axis:\n                axis_mul_before *= value\n            elif i > axis:\n                axis_mul_after *= value\n\n    def gen_ir(data_buf, out_buf):\n        ib = ir_builder.create()\n        data_buf = ib.buffer_ptr(data_buf)\n        out_buf = ib.buffer_ptr(out_buf)\n\n        with ib.for_range(0, axis_mul_before * axis_mul_after, \"fused\", kind=\"parallel\") as fused:\n            i = fused // axis_mul_after\n            j = fused % axis_mul_after\n            base_idx = i * cumsum_axis_len * axis_mul_after + j\n            if exclusive:\n                out_buf[base_idx] = cast(identity_value, dtype)\n            else:\n                out_buf[base_idx] = maybe_cast(data_buf[base_idx])\n            with ib.for_range(0, cumsum_axis_len - 1, \"_k\") as _k:\n                k = _k + 1\n                cur_idx = base_idx + k * axis_mul_after\n                prev_idx = base_idx + (k - 1) * axis_mul_after\n                if exclusive:\n                    out_buf[cur_idx] = binop(out_buf[prev_idx], maybe_cast(data_buf[prev_idx]))\n                else:\n                    out_buf[cur_idx] = binop(out_buf[prev_idx], maybe_cast(data_buf[cur_idx]))\n\n        return ib.get()\n\n    out_buf = decl_buffer(shape, dtype, \"out_buf\")\n\n    return extern(\n        [shape],\n        [data],\n        lambda ins, outs: gen_ir(ins[0], outs[0]),\n        dtype=dtype,\n        out_buffers=[out_buf],\n        name=op_name,\n        tag=op_name,\n    )\n\n\ndef cumsum(\n    data: tvm.te.Tensor,\n    axis: Optional[int] = None,\n    dtype: Optional[int] = None,\n    exclusive: Optional[bool] = None,\n) -> tvm.te.Tensor:\n    \"\"\"Numpy style cumsum op. Return the cumulative sum of the elements along a given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative sum is computed. The default (None) is to compute\n        the cumsum over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are summed.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If True, will return exclusive sum in which the first element is not\n        included. In other terms, if True, the j-th output element would be\n        the sum of the first (j-1) elements. Otherwise, it would be the sum of\n        the first j elements.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    return scanop(\n        data=data,\n        binop=generic.add,\n        identity_value=0,\n        op_name=\"cumsum_generic\",\n        axis=axis,\n        dtype=dtype,\n        exclusive=exclusive,\n    )\n\n\ndef cumprod(\n    data: tvm.te.Tensor,\n    axis: Optional[int] = None,\n    dtype: Optional[int] = None,\n    exclusive: Optional[bool] = None,\n) -> tvm.te.Tensor:\n    \"\"\"Numpy style cumprod op. Return the cumulative product of the elements along a given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    axis : int, optional\n        Axis along which the cumulative product is computed. The default (None) is to compute\n        the cumproduct over the flattened array.\n\n    dtype : string, optional\n        Type of the returned array and of the accumulator in which the elements are multiplied.\n        If dtype is not specified, it defaults to the dtype of data.\n\n    exclusive : bool, optional\n        If True, will return exclusive product in which the first element is not\n        included. In other terms, if True, the j-th output element would be\n        the product of the first (j-1) elements. Otherwise, it would be the product of\n        the first j elements.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The result has the same size as data, and the same shape as data if axis is not None.\n        If axis is None, the result is a 1-d array.\n    \"\"\"\n    return scanop(\n        data=data,\n        binop=generic.multiply,\n        identity_value=1,\n        op_name=\"cumprod_generic\",\n        axis=axis,\n        dtype=dtype,\n        exclusive=exclusive,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/scatter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks\n\"\"\"Scatter operator\"\"\"\nfrom ..tir import decl_buffer, ir_builder, AssertStmt, StringImm, Evaluate, expr\nfrom ..te import extern, hybrid\n\n\n@hybrid.script\ndef _scatter_1d(data, indices, updates):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        out[i] = data[i]\n    for i in range(indices.shape[0]):\n        out[indices[i] if indices[i] >= 0 else indices[i] + data.shape[0]] = updates[i]\n    return out\n\n\n@hybrid.script\ndef _scatter_2d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            out[i, j] = data[i, j]\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                out[\n                    indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis], j\n                ] = updates[i, j]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                out[\n                    i, indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis]\n                ] = updates[i, j]\n\n    return out\n\n\n@hybrid.script\ndef _scatter_3d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            for k in range(data.shape[2]):\n                out[i, j, k] = data[i, j, k]\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                        j,\n                        k,\n                    ] = updates[i, j, k]\n    elif axis == 1:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        i,\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                        k,\n                    ] = updates[i, j, k]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        i,\n                        j,\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                    ] = updates[i, j, k]\n\n    return out\n\n\n@hybrid.script\ndef _scatter_4d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            for k in range(data.shape[2]):\n                for l in range(data.shape[3]):\n                    out[i, j, k, l] = data[i, j, k, l]\n\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            j,\n                            k,\n                            l,\n                        ] = updates[i, j, k, l]\n    elif axis == 1:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            k,\n                            l,\n                        ] = updates[i, j, k, l]\n    elif axis == 2:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            j,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            l,\n                        ] = updates[i, j, k, l]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            j,\n                            k,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                        ] = updates[i, j, k, l]\n\n    return out\n\n\ndef scatter(data, indices, updates, axis=0):\n    \"\"\"Update data at positions defined by indices with values in updates\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    axis : int\n        The axis to scatter on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    if axis < 0:\n        axis += len(data.shape)\n    assert axis >= 0\n    assert axis < len(data.shape)\n\n    if len(data.shape) == 1:\n        return _scatter_1d(data, indices, updates)\n    if len(data.shape) == 2:\n        return _scatter_2d(data, indices, updates, axis)\n    if len(data.shape) == 3:\n        return _scatter_3d(data, indices, updates, axis)\n    if len(data.shape) == 4:\n        return _scatter_4d(data, indices, updates, axis)\n    raise ValueError(\"scatter only support for 1-4 dimensions\")\n\n\ndef _verify_scatter_nd_inputs(data, indices, updates):\n    mdim = int(indices.shape[0])\n    assert mdim <= len(data.shape), (\n        f\"The first dimension of the indices ({mdim}) must be less than or equal to \"\n        f\"the length of the shape of the output ({len(data.shape)}).\"\n    )\n    for i in range(len(indices.shape) - 1):\n        if isinstance(indices.shape[i + 1], expr.Var) or isinstance(updates.shape[i], expr.Var):\n            continue\n        assert indices.shape[i + 1] == updates.shape[i], (\n            f\"Dimension of indices[{i+1}] ({indices.shape[i+1]}) must equal dimension of \"\n            f\"updates[{i}] ({updates.shape[i]}).\"\n        )\n    for i in range(mdim, len(data.shape)):\n        data_ind = i - mdim + len(indices.shape) - 1\n        if isinstance(updates.shape[data_ind], expr.Var) or isinstance(data.shape[i], expr.Var):\n            continue\n        assert updates.shape[data_ind] == data.shape[i], (\n            f\"Dimension of updates[{data_ind}] ({updates.shape[data_ind]}) must equal dimension \"\n            f\"of out_shape[{i}] ({data.shape[i]}).\"\n        )\n\n    assert (\n        \"int\" in indices.dtype\n    ), f\"Indices must be a tensor of integers, but its elements are {indices.dtype}.\"\n\n\ndef scatter_nd(data, indices, updates, mode):\n    \"\"\"Scatter elements from a n-dimension array.\n\n    Given updates with shape (Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1}), indices with shape\n    (M, Y_0, ..., Y_{K-1}), and output copied from data with shape (X_0, X_1, ..., X_{N-1}),\n    scatter_nd computes\n\n    .. code-block::\n\n        output[indices[0, y_0, ..., y_{K-1}],\n               ...,\n               indices[M-1, y_0, ..., y_{K-1}],\n               x_M,\n               ...,\n               x_{N-1}\n              ] = f(output[...], updates[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}])\n\n    where the update function f is determinted by the mode.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The source array.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    updates : tvm.te.Tensor\n        The updates to apply at the Indices\n\n    mode : string\n        The update mode for the algorithm, either \"update\" or \"add\"\n        If update, the update values will replace the input data\n        If add, the update values will be added to the input data\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    _verify_scatter_nd_inputs(data, indices, updates)\n\n    def gen_ir(data_ptr, indices_ptr, updates_ptr, out_ptr):\n        ib = ir_builder.create()\n\n        data = ib.buffer_ptr(data_ptr)\n        indices = ib.buffer_ptr(indices_ptr)\n        updates = ib.buffer_ptr(updates_ptr)\n        out = ib.buffer_ptr(out_ptr)\n\n        fused_shape = 1\n        for i in data.shape:\n            fused_shape *= i\n        with ib.for_range(0, fused_shape) as i:\n            out[i] = data[i]\n\n        # We combine all the indices dimensions but the first one into a single\n        # dimension so we can iterate it in single loop instead of an arbitrary\n        # number of loops. We do the same thing for all the data dimensions.\n        fused_indices_dimension = 1\n        for i in indices_ptr.shape[1:]:\n            fused_indices_dimension *= i\n\n        fused_data_dimension = 1\n        for i in data_ptr.shape[len(indices_ptr.shape) - 1 :]:\n            fused_data_dimension *= i\n\n        with ib.for_range(0, fused_indices_dimension, name=\"i\") as i:\n            with ib.for_range(0, fused_data_dimension, name=\"j\") as j:\n                offset = fused_data_dimension\n                index = j  # This is x_M, .. x_{N-1} part of the index into out.\n                # Build up the indices[0, y_0, .. y_{K-1}], .. indices[M-1, y_0, .. y_{K-1}] part\n                # of the index into out.\n                for l in reversed(range(indices_ptr.shape[0].value)):\n                    # indices[i * l * fused_indices_dimension] = indices[l, y_0, ... y_{k-1}]\n                    index += offset * indices[i + l * fused_indices_dimension]\n                    ib.emit(\n                        AssertStmt(\n                            indices[i + l * fused_indices_dimension] < shape[l],\n                            StringImm(\"index out of bounds\"),\n                            Evaluate(0),\n                        )\n                    )\n                    offset *= shape[l]\n                if mode == \"add\":\n                    out[index] += updates[i * fused_data_dimension + j]\n                elif mode == \"update\":\n                    out[index] = updates[i * fused_data_dimension + j]\n                else:\n                    raise NotImplementedError(\"scatter_nd mode not in [update, add]:\", mode)\n\n        return ib.get()\n\n    out_buf = decl_buffer(shape, data.dtype, \"out_buf\")\n    return extern(\n        [shape],\n        [data, indices, updates],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0]),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_nd_generic\",\n        tag=\"scatter_nd_generic\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/scatter_add.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks\n\"\"\"Scatter Add operator\"\"\"\nfrom tvm.te import hybrid\n\n\n@hybrid.script\ndef _scatter_add_1d(data, indices, updates):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        out[i] = data[i]\n    for i in range(indices.shape[0]):\n        out[indices[i] if indices[i] >= 0 else indices[i] + data.shape[0]] += updates[i]\n    return out\n\n\n@hybrid.script\ndef _scatter_add_2d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            out[i, j] = data[i, j]\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                out[\n                    indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis], j\n                ] += updates[i, j]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                out[\n                    i, indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis]\n                ] += updates[i, j]\n\n    return out\n\n\n@hybrid.script\ndef _scatter_add_3d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            for k in range(data.shape[2]):\n                out[i, j, k] = data[i, j, k]\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                        j,\n                        k,\n                    ] += updates[i, j, k]\n    elif axis == 1:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        i,\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                        k,\n                    ] += updates[i, j, k]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    out[\n                        i,\n                        j,\n                        indices[i, j, k]\n                        if indices[i, j, k] >= 0\n                        else indices[i, j, k] + data.shape[axis],\n                    ] += updates[i, j, k]\n\n    return out\n\n\n@hybrid.script\ndef _scatter_add_4d(data, indices, updates, axis):\n    out = output_tensor(data.shape, data.dtype)\n    for i in range(data.shape[0]):\n        for j in range(data.shape[1]):\n            for k in range(data.shape[2]):\n                for l in range(data.shape[3]):\n                    out[i, j, k, l] = data[i, j, k, l]\n\n    if axis == 0:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            j,\n                            k,\n                            l,\n                        ] += updates[i, j, k, l]\n    elif axis == 1:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            k,\n                            l,\n                        ] += updates[i, j, k, l]\n    elif axis == 2:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            j,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                            l,\n                        ] += updates[i, j, k, l]\n    else:\n        for i in range(indices.shape[0]):\n            for j in range(indices.shape[1]):\n                for k in range(indices.shape[2]):\n                    for l in range(indices.shape[3]):\n                        out[\n                            i,\n                            j,\n                            k,\n                            indices[i, j, k, l]\n                            if indices[i, j, k, l] >= 0\n                            else indices[i, j, k, l] + data.shape[axis],\n                        ] += updates[i, j, k, l]\n\n    return out\n\n\ndef scatter_add(data, indices, updates, axis=0):\n    \"\"\"Update data by adding values in updates at positions defined by indices\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    indices : relay.Expr\n        The index locations to update.\n\n    updates : relay.Expr\n        The values to update.\n\n    axis : int\n        The axis to scatter_add on\n\n    Returns\n    -------\n    ret : relay.Expr\n        The computed result.\n    \"\"\"\n    if axis < 0:\n        axis += len(data.shape)\n    assert axis >= 0\n    assert axis < len(data.shape)\n\n    if len(data.shape) == 1:\n        return _scatter_add_1d(data, indices, updates)\n    if len(data.shape) == 2:\n        return _scatter_add_2d(data, indices, updates, axis)\n    if len(data.shape) == 3:\n        return _scatter_add_3d(data, indices, updates, axis)\n    if len(data.shape) == 4:\n        return _scatter_add_4d(data, indices, updates, axis)\n    raise ValueError(\"scatter_add only support for 1-4 dimensions\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/searchsorted.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"searchsorted operator\"\"\"\nfrom . import utils\nfrom . import te\nfrom ..tir import ir_builder\nfrom .math import cast\n\n\ndef binary_search(ib, sequence_offset, search_range, sorted_sequence, value, right, out_dtype):\n    \"\"\"Common IR generator for binary search used by CPU and GPU backends.\n\n    `sorted_sequence` is a N-D Buffer whose innermost dimension we want to search for `value`,\n    and `search_range` is the size of the innermost dimension. `sequence_offset` is\n    a 1-D linearlized offset specifying which of innermost sequences to search.\n\n    So the search for `value` is performed over\n    `sorted_sequence[sequence_offset:(sequence_offset + search_range)]`.\n    Note that we index N-D Buffer by 1-D linearlized indices.\n\n    \"\"\"\n    lo = ib.allocate(out_dtype, (1,), name=\"lo\", scope=\"local\")\n    hi = ib.allocate(out_dtype, (1,), name=\"hi\", scope=\"local\")\n\n    lo[0] = cast(0, out_dtype)\n    hi[0] = cast(search_range, out_dtype)\n\n    # Reference: pytorch/aten/src/ATen/native/cuda/Bucketization.cu\n    def condition(current_val, target_val):\n        if right:\n            return current_val <= target_val\n        return current_val < target_val\n\n    with ib.while_loop(lo[0] < hi[0]):\n        mid = lo[0] + (hi[0] - lo[0] >> 1)\n        with ib.if_scope(condition(sorted_sequence[sequence_offset + mid], value)):\n            lo[0] = mid + 1\n        with ib.else_scope():\n            hi[0] = mid\n\n    return lo[0]\n\n\ndef searchsorted(sorted_sequence, values, right=False, out_dtype=\"int64\"):\n    \"\"\"Find indices where elements should be inserted to maintain order.\n       If `sorted_sequence` is N-dimensional, the innermost dimension of\n       `values` are searched in the corresponding dimension of `sorted_sequence`.\n\n    Parameters\n    ----------\n    sorted_sequence : te.Tensor\n        N-D or 1-D Tensor, containing monotonically increasing sequence\n        on the innermost dimension.\n\n    values : te.Tensor\n        N-D Tensor containing the search values. When `sorted_sequence` is 1-D,\n        the shape of `values` can be arbitrary. Otherwise, ranks of `sorted_sequence`\n        and `values` must be the same, and outer N-1 axes must have the same size.\n\n    right : bool, optional\n        Controls which index is returned if a value lands exactly on one of sorted values. If\n        False, the index of the first suitable location found is given. If true, return the\n        last such index. If there is no suitable index, return either 0 or N (where N is the\n        size of the innermost dimension).\n\n    dtype : string, optional\n        The data type of the output indices.\n\n    Returns\n    -------\n    indices : te.Tensor\n        Tensor with same shape as values, representing the indices of\n        elements of `values` if they are inserted in `sorted_sequence`.\n    \"\"\"\n\n    def ir(sorted_sequence, values, indices):\n        ib = ir_builder.create()\n        sorted_sequence_shape = sorted_sequence.shape\n        values_shape = values.shape\n        num_search = utils.prod(values_shape)\n        search_range = sorted_sequence_shape[-1]\n\n        sorted_sequence = ib.buffer_ptr(sorted_sequence)\n        values = ib.buffer_ptr(values)\n        indices = ib.buffer_ptr(indices)\n\n        with ib.for_range(0, num_search, name=\"i\", kind=\"parallel\") as i:\n            if len(sorted_sequence_shape) == 1:\n                sequence_offset = 0\n            else:\n                sequence_id = i // values_shape[-1]\n                sequence_offset = sequence_id * search_range\n\n            indices[i] = binary_search(\n                ib,\n                sequence_offset,\n                search_range,\n                sorted_sequence,\n                values[i],\n                right,\n                out_dtype,\n            )\n\n        return ib.get()\n\n    return te.extern(\n        values.shape,\n        [sorted_sequence, values],\n        lambda ins, outs: ir(ins[0], ins[1], outs[0]),\n        name=\"searchsorted\",\n        dtype=out_dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sort.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-arguments\n\"\"\"Argsort operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom .utils import get_const_tuple\n\n\ndef sort(data, axis=-1, is_ascend=1):\n    \"\"\"Performs sorting along the given axis and returns an array\n    in sorted order.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tensor.\n\n    axis : int, optional\n        Axis along which to sort the input tensor.\n        By default the flattened array is used.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        DType of the output indices.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Sorted index tensor.\n\n    \"\"\"\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"out_buf\", data_alignment=8)\n    out = te.extern(\n        data.shape,\n        [data],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.sort.sort\", ins[0], outs[0], axis, is_ascend\n        ),\n        dtype=data.dtype,\n        in_buffers=[data_buf],\n        out_buffers=out_buf,\n        name=\"sort_cpu\",\n        tag=\"sort_cpu\",\n    )\n    return out\n\n\ndef argsort(data, valid_count=None, axis=-1, is_ascend=1, dtype=\"float32\"):\n    \"\"\"Performs sorting along the given axis and returns an array\n    of indices having the same shape as an input array that index\n    data in sorted order.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tensor.\n\n    valid_count : tvm.te.Tensor, optional\n        1-D tensor for valid number of boxes.\n\n    axis : int, optional\n        Axis along which to sort the input tensor.\n        By default the flattened array is used.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        DType of the output indices.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        Sorted index tensor.\n\n    Example\n    --------\n    .. code-block:: python\n\n        # An example to use argsort\n        dshape = (1, 5, 6)\n        data = te.placeholder(dshape, name=\"data\")\n        axis = 0\n        is_ascend = False\n        out = argsort(data, axis=axis, is_ascend=is_ascend)\n        np_data = np.random.uniform(dshape)\n        s = topi.generic.schedule_argsort(out)\n        f = tvm.build(s, [data, out], \"llvm\")\n        dev = tvm.cpu()\n        tvm_data = tvm.nd.array(np_data, dev)\n        tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), dev)\n        f(tvm_data, tvm_out)\n    \"\"\"\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    if valid_count is not None:\n        valid_count_buf = tvm.tir.decl_buffer(\n            valid_count.shape, valid_count.dtype, \"valid_count_buf\", data_alignment=4\n        )\n        out_buf = tvm.tir.decl_buffer(data.shape, \"int32\", \"out_buf\", data_alignment=8)\n        out = te.extern(\n            data.shape,\n            [data, valid_count],\n            lambda ins, outs: tvm.tir.call_packed(\n                \"tvm.contrib.sort.argsort_nms\", ins[0], ins[1], outs[0], axis, is_ascend\n            ),\n            dtype=\"int32\",\n            in_buffers=[data_buf, valid_count_buf],\n            out_buffers=out_buf,\n            name=\"argsort_nms_cpu\",\n            tag=\"argsort_nms_cpu\",\n        )\n    else:\n        out_buf = tvm.tir.decl_buffer(data.shape, dtype, \"out_buf\", data_alignment=8)\n        out = te.extern(\n            data.shape,\n            [data],\n            lambda ins, outs: tvm.tir.call_packed(\n                \"tvm.contrib.sort.argsort\", ins[0], outs[0], axis, is_ascend\n            ),\n            dtype=dtype,\n            in_buffers=[data_buf],\n            out_buffers=out_buf,\n            name=\"argsort_cpu\",\n            tag=\"argsort_cpu\",\n        )\n    return out\n\n\ndef topk(data, k=1, axis=-1, ret_type=\"both\", is_ascend=False, dtype=\"int64\"):\n    \"\"\"Get the top k elements in an input tensor along the given axis.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input tensor.\n\n    k : int or tvm.te.Tensor, optional\n        Number of top elements to select. Return all elements if k < 1.\n\n    axis : int, optional\n        Axis long which to sort the input tensor.\n\n    ret_type: str, optional\n        The return type [both, values, indices].\n        \"both\": return both top k data and indices.\n        \"values\": return top k data only.\n        \"indices\": return top k indices only.\n\n    is_ascend : boolean, optional\n        Whether to sort in ascending or descending order.\n\n    dtype : string, optional\n        The data type of the indices output.\n\n    Returns\n    -------\n    out : tvm.te.Tensor or List[tvm.te.Tensor]\n        The computed result.\n    \"\"\"\n    assert ret_type in [\"both\", \"values\", \"indices\"]\n    data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"data_buf\", data_alignment=8)\n    out_shape = list(get_const_tuple(data.shape))\n    kvar = tvm.te.size_var(\"k\")\n    if not isinstance(k, int):\n        out_shape[axis] = kvar\n    elif k >= 1:\n        out_shape[axis] = k\n    out_bufs = []\n    if ret_type in [\"both\", \"values\"]:\n        out_bufs.append(tvm.tir.decl_buffer(out_shape, data.dtype, \"value_buf\", data_alignment=8))\n    if ret_type in [\"both\", \"indices\"]:\n        out_bufs.append(tvm.tir.decl_buffer(out_shape, dtype, \"indices_buf\", data_alignment=8))\n    out_shapes = [out_shape] * len(out_bufs)\n\n    kv = kvar if not isinstance(k, int) else k\n    out = te.extern(\n        out_shapes,\n        [data],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.sort.topk\", ins[0], *outs, kv, axis, ret_type, is_ascend\n        ),\n        in_buffers=[data_buf],\n        out_buffers=out_bufs,\n        name=\"topk_cpu\",\n        tag=\"topk_cpu\",\n    )\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Sparse operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .csrmv import csrmv\nfrom .csrmm import csrmm\nfrom .dense import dense\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse/csrmm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator compute SpMM in CSR format.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..utils import simplify\nfrom ...tir.generic import cast\n\n\ndef csrmm_default(data, indices, indptr, weight, bias=None):\n    # pylint: disable=invalid-name\n    \"\"\"The default implementation of csrmm in topi.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    indices : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    indptr : tvm.te.Tensor\n        1-D with shape [m+1]\n\n    weight : tvm.te.Tensor\n        2-D with shape [k, n]\n\n    bias : tvm.te.Tensor, optional\n        1-D with shape [m]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [m, n]\n    \"\"\"\n    assert (\n        len(data.shape) == 1\n        and len(indices.shape) == 1\n        and len(indptr.shape) == 1\n        and len(weight.shape) == 2\n    ), \"only support 2-dim csrmm\"\n    assert isinstance(\n        weight, te.tensor.Tensor\n    ), \"weight matrix is assumed to be tvm.te.Tensor, but weight is `%s`\" % (type(weight))\n    assert (\n        data.dtype == weight.dtype\n    ), \"Data and weight must have the same dtype, but they have %s and %s\" % (\n        data.dtype,\n        weight.dtype,\n    )\n    if bias is not None:\n        assert len(bias.shape) == 1\n    M = simplify(indptr.shape[0] - 1)\n    _, N = weight.shape\n\n    def csrmm_default_ir(data, indices, indptr, weight, out):\n        \"\"\"define ir for csrmm\"\"\"\n        irb = tvm.tir.ir_builder.create()\n        data_ptr = irb.buffer_ptr(data)\n        indices_ptr = irb.buffer_ptr(indices)\n        indptr_ptr = irb.buffer_ptr(indptr)\n        weight_ptr = irb.buffer_ptr(weight)\n        out_ptr = irb.buffer_ptr(out)\n        M = simplify(indptr.shape[0] - 1)\n        _, N = weight.shape\n        with irb.for_range(0, N, kind=\"vectorize\", name=\"n\") as n:\n            with irb.for_range(0, M, kind=\"parallel\", name=\"row\") as row:\n                dot = irb.allocate(data.dtype, (1,), name=\"dot\", scope=\"local\")\n                out_ptr[row * N + n] = cast(0, data.dtype)\n                dot[0] = cast(0, data.dtype)\n                row_start = indptr_ptr[row]\n                row_end = indptr_ptr[row + 1]\n                row_elems = row_end - row_start\n                with irb.for_range(0, row_elems, name=\"idx\") as idx:\n                    elem = row_start + idx\n                    dot[0] += data_ptr[elem] * weight_ptr[indices_ptr[elem] * N + n]\n                out_ptr[row * N + n] += dot[0]\n        return irb.get()\n\n    oshape = (M, N)\n    matmul = te.extern(\n        oshape,\n        [data, indices, indptr, weight],\n        lambda ins, outs: csrmm_default_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        tag=\"csrmm\",\n        dtype=data.dtype,\n        name=\"out\",\n    )\n    if bias is not None:\n        matmul = te.compute(oshape, lambda i, j: matmul[i, j] + bias[i], tag=tag.BROADCAST)\n    return matmul\n\n\ndef csrmm(a, b, c=None):\n    \"\"\"The `csrmm` routine performs a matrix-matrix operation defined as :math:`C := A*B + C`,\n    where `B` and `C` are dense matrices, `A` is an m-by-k sparse matrix in the CSR format.\n\n    Parameters\n    ----------\n    a : tvm.contrib.sparse.CSRNDArray\n        2-D sparse matrix with shape [m, k]\n\n    b : tvm.te.Tensor\n        2-D dense matrix with shape [k, n]\n\n    c : tvm.te.Tensor, optional\n        1-D dense vector with shape [n]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [m, n]\n    \"\"\"\n    return csrmm_default(a.data, a.indices, a.indptr, b, c)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse/csrmv.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator compute SpMV in CSR format.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ...tir.generic import cast\n\n\ndef csrmv_default(data, indices, indptr, weight, bias=None):\n    \"\"\"The default implementation of csrmv in topi.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    indices : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    indptr : tvm.te.Tensor\n        1-D with shape [m+1]\n\n    weight : tvm.te.Tensor\n        2-D with shape [k, 1]\n\n    bias : tvm.te.Tensor, optional\n        1-D with shape [1]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [m, 1]\n    \"\"\"\n    assert len(data.shape) == 1 and len(weight.shape) == 2, \"only support 2-dim csrmv\"\n    assert isinstance(\n        weight, te.tensor.Tensor\n    ), \"weight matrix is assumed to be tvm.te.Tensor, but weight is `%s`\" % (type(weight))\n    assert (\n        data.dtype == weight.dtype\n    ), \"Data and weight must have the same dtype, but they have %s and %s\" % (\n        data.dtype,\n        weight.dtype,\n    )\n    if bias is not None:\n        assert len(bias.shape) == 1\n    batch = indptr.shape[0] - 1\n\n    def csrmv_default_ir(data, indices, indptr, weight, out):\n        \"\"\"define ir for csrmv\"\"\"\n        irb = tvm.tir.ir_builder.create()\n        data_ptr = irb.buffer_ptr(data)\n        indices_ptr = irb.buffer_ptr(indices)\n        indptr_ptr = irb.buffer_ptr(indptr)\n        weight_ptr = irb.buffer_ptr(weight)\n        out_ptr = irb.buffer_ptr(out)\n        num_rows = indptr.shape[0] - 1\n        with irb.for_range(0, num_rows, kind=\"parallel\", name=\"row\") as row:\n            dot = irb.allocate(data.dtype, (1,), name=\"dot\", scope=\"local\")\n            out_ptr[row] = cast(0, data.dtype)\n            dot[0] = cast(0, data.dtype)\n            row_start = indptr_ptr[row]\n            row_end = indptr_ptr[row + 1]\n            row_elems = row_end - row_start\n            with irb.for_range(0, row_elems, name=\"elemidx\") as elemidx:\n                elem = row_start + elemidx\n                dot[0] += data_ptr[elem] * weight_ptr[indices_ptr[elem]]\n            out_ptr[row] += dot[0]\n        return irb.get()\n\n    oshape = (batch, 1)\n    matmul = te.extern(\n        oshape,\n        [data, indices, indptr, weight],\n        lambda ins, outs: csrmv_default_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        tag=\"csrmv\",\n        dtype=data.dtype,\n        name=\"csrmv\",\n    )\n    if bias is not None:\n        matmul = te.compute((batch, 1), lambda i, j: matmul[i, 0] + bias[i], tag=tag.BROADCAST)\n    return matmul\n\n\ndef csrmv(a, x, y=None):\n    \"\"\"The `csrmv` routine performs a matrix-vector operation defined as :math:`y := A*x + y`,\n    where `x` and `y` are vectors, `A` is an m-by-k sparse matrix in the CSR format.\n\n    Parameters\n    ----------\n    a : tvm.contrib.sparse.CSRNDArray\n        2-D sparse matrix with shape [m, k]\n\n    x : tvm.te.Tensor\n        2-D dense matrix with shape [k, 1]\n\n    y : tvm.te.Tensor, optional\n        1-D dense vector with shape [1]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D dense matrix with shape [m, 1]\n    \"\"\"\n    return csrmv_default(a.data, a.indices, a.indptr, x, y)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"TVM operator compute Dense in CSR format.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom tvm import te\nfrom .. import tag\nfrom ..utils import simplify\n\n\ndef dense_si(data, indices, indptr, weight, bias=None):\n    # pylint: disable=invalid-name\n    \"\"\"The implementation of dense in topi, assuming sparse input.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        1-D with shape [num_nonzeros]\n\n    indices : tvm.te.Tensor\n        1-D with shape [num_nonzeros]\n\n    indptr : tvm.te.Tensor\n        1-D with shape [m+1]\n\n    weight : tvm.te.Tensor\n        2-D with shape [k, n]\n\n    bias : tvm.te.Tensor, optional\n        1-D with shape [m]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [m, n]\n    \"\"\"\n    assert (\n        len(data.shape) == 1\n        and len(indices.shape) == 1\n        and len(indptr.shape) == 1\n        and len(weight.shape) == 2\n    ), \"only support 2-dim dense\"\n    assert isinstance(\n        weight, te.tensor.Tensor\n    ), \"weight matrix is assumed to be tvm.te.Tensor, but weight is `%s`\" % (type(weight))\n    if bias is not None:\n        assert len(bias.shape) == 1\n    dtype = data.dtype\n    M = simplify(indptr.shape[0] - 1)\n    N, _ = weight.shape\n\n    def dense_default_ir(data, indices, indptr, weight, out):\n        \"\"\"Define IR for Dense\"\"\"\n        dtype = data.dtype\n        irb = tvm.tir.ir_builder.create()\n        data_ptr = irb.buffer_ptr(data)\n        indices_ptr = irb.buffer_ptr(indices)\n        indptr_ptr = irb.buffer_ptr(indptr)\n        weight_ptr = irb.buffer_ptr(weight)\n        out_ptr = irb.buffer_ptr(out)\n        M = simplify(indptr.shape[0] - 1)\n        N, K = weight.shape\n        with irb.for_range(0, N, kind=\"vectorize\", name=\"n\") as n:\n            with irb.for_range(0, M, kind=\"parallel\", name=\"m\") as m:\n                dot = irb.allocate(dtype, (1,), name=\"dot\", scope=\"local\")\n                out_ptr[m * N + n] = tvm.tir.const(0, dtype)\n                dot[0] = tvm.tir.const(0, dtype)\n                row_start = indptr_ptr[m]\n                row_elems = indptr_ptr[m + 1] - row_start\n                with irb.for_range(0, row_elems, name=\"k\") as k:\n                    elem = row_start + k\n                    dot[0] += data_ptr[elem] * weight_ptr[indices_ptr[elem] + n * K]\n                out_ptr[m * N + n] += dot[0]\n        return irb.get()\n\n    oshape = (M, N)\n    matmul = te.extern(\n        oshape,\n        [data, indices, indptr, weight],\n        lambda ins, outs: dense_default_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        tag=\"dense\",\n        dtype=dtype,\n        name=\"out\",\n    )\n    if bias is not None:\n        matmul = te.compute(oshape, lambda i, j: matmul[i, j] + bias[j], tag=tag.BROADCAST)\n    return matmul\n\n\ndef dense_sw(data, w_data, w_indices, w_indptr, bias=None):\n    # pylint: disable=invalid-name\n    \"\"\"The implementation of dense in topi, assuming sparse weight.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [m, k]\n\n    w_data : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    w_indices : tvm.te.Tensor\n        1-D with shape [nonzeros]\n\n    w_indptr : tvm.te.Tensor\n        1-D with shape [n+1]\n\n    bias : tvm.te.Tensor, optional\n        1-D with shape [n]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [m, n]\n    \"\"\"\n    assert (\n        len(w_data.shape) == 1\n        and len(w_indices.shape) == 1\n        and len(w_indptr.shape) == 1\n        and len(data.shape) == 2\n    ), \"only support 2-dim dense\"\n    assert isinstance(\n        data, te.tensor.Tensor\n    ), \"data matrix is assumed to be tvm.te.Tensor, but weight is `%s`\" % (type(data))\n    if bias is not None:\n        assert len(bias.shape) == 1\n    dtype = data.dtype\n    M, _ = data.shape\n    N = simplify(w_indptr.shape[0] - 1)\n\n    def dense_default_ir(data, w_data, w_indices, w_indptr, out):\n        \"\"\"Define IR for Dense\"\"\"\n        dtype = data.dtype\n        irb = tvm.tir.ir_builder.create()\n        data_ptr = irb.buffer_ptr(data)\n        w_data_ptr = irb.buffer_ptr(w_data)\n        w_indices_ptr = irb.buffer_ptr(w_indices)\n        w_indptr_ptr = irb.buffer_ptr(w_indptr)\n        out_ptr = irb.buffer_ptr(out)\n        M, K = data.shape\n        N = simplify(w_indptr.shape[0] - 1)\n        with irb.for_range(0, M, kind=\"vectorize\", name=\"m\") as m:\n            with irb.for_range(0, N, kind=\"parallel\", name=\"n\") as n:\n                dot = irb.allocate(dtype, (1,), name=\"dot\", scope=\"local\")\n                out_ptr[m * N + n] = tvm.tir.const(0, dtype)\n                dot[0] = tvm.tir.const(0, dtype)\n                row_start = w_indptr_ptr[n]\n                row_elems = w_indptr_ptr[n + 1] - row_start\n                with irb.for_range(0, row_elems, name=\"k\") as k:\n                    elem = row_start + k\n                    dot[0] += w_data_ptr[elem] * data_ptr[w_indices_ptr[elem] + m * K]\n                out_ptr[m * N + n] += dot[0]\n        return irb.get()\n\n    oshape = (M, N)\n    matmul = te.extern(\n        oshape,\n        [data, w_data, w_indices, w_indptr],\n        lambda ins, outs: dense_default_ir(ins[0], ins[1], ins[2], ins[3], outs[0]),\n        tag=\"dense\",\n        dtype=dtype,\n        name=\"out\",\n    )\n    if bias is not None:\n        matmul = te.compute(oshape, lambda i, j: matmul[i, j] + bias[j], tag=tag.BROADCAST)\n    return matmul\n\n\ndef dense(data, weight, bias=None):\n    \"\"\"Applies a linear transformation: :math:`Y = XW^T + b`.\n    Either data or weight should be tvm.contrib.sparse.CSRNDArray.\n\n    Parameters\n    ----------\n    data : tvm.contrib.sparse.CSRNDArray or te.tensor.Tensor\n        2-D with shape [batch, in_dim]\n\n    weight : te.tensor.Tensor or tvm.contrib.sparse.CSRNDArray\n        2-D with shape [out_dim, in_dim]\n\n    bias : te.tensor.Tensor, optional\n        1-D with shape [out_dim]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    ret = None\n    if isinstance(data, tvm.contrib.sparse.CSRPlaceholderOp) and isinstance(\n        weight, te.tensor.Tensor\n    ):\n        ret = dense_si(data.data, data.indices, data.indptr, weight, bias)\n    elif isinstance(data, te.tensor.Tensor) and isinstance(\n        weight, tvm.contrib.sparse.CSRPlaceholderOp\n    ):\n        ret = dense_sw(data, weight.data, weight.indices, weight.indptr, bias)\n    else:\n        raise NotImplementedError(\n            \"implementation for %s as data and %s as weights, \"\n            \"is not supported yet.\"\n            % (\n                type(data),\n                type(weight),\n            )\n        )\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Some utils for Sparse operation.\"\"\"\nimport tvm\nfrom tvm import relay, auto_scheduler\nfrom tvm.relay import data_dep_optimization as ddo\nfrom tvm.auto_scheduler import _ffi_api\n\n\ndef random_bsr_matrix(m, n, bs_r, bs_c, density, dtype):\n    \"\"\"Generate a random sparse matrix in bsr format.\n\n    Returns\n    -------\n    scipy.sparse.bsr_matrix\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    import numpy as np\n    import itertools\n    import scipy.sparse as sp\n\n    y = np.zeros((m, n), dtype=dtype)\n    assert m % bs_r == 0\n    assert n % bs_c == 0\n    nnz = int(density * m * n)\n    num_blocks = int(nnz / (bs_r * bs_c)) + 1\n    candidate_blocks = np.asarray(list(itertools.product(range(0, m, bs_r), range(0, n, bs_c))))\n    assert candidate_blocks.shape[0] == m // bs_r * n // bs_c\n    chosen_blocks = candidate_blocks[\n        np.random.choice(candidate_blocks.shape[0], size=num_blocks, replace=False)\n    ]\n    # pylint: disable=invalid-name\n    for (r, c) in chosen_blocks:\n        y[r : r + bs_r, c : c + bs_c] = np.random.randn(bs_r, bs_c)\n    s = sp.bsr_matrix(y, blocksize=(bs_r, bs_c))\n    assert s.data.shape == (num_blocks, bs_r, bs_c)\n    assert s.indices.shape == (num_blocks,)\n    assert s.indptr.shape == (m // bs_r + 1,)\n    return s\n\n\ndef random_sparse_dense_params(func, params, bs_r, bs_c, density):\n    \"\"\"Replace the dense parameters with random sparse parameters. Mainly used for testing.\n\n    Parameters\n    ----------\n    func : tvm.relay.Expr\n        Expr will be optimized to sparse operation.\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the Expr.\n    bs_r : int\n        The row of BSR matrix block.\n    bs_c : int\n        The column of BSR matrix block.\n    density : float\n        The density of the random sparse parameters.\n\n    Returns\n    -------\n    Dict[Srting, tvm.nd.array]\n        The generated random parameters.\n    \"\"\"\n\n    def deepcopy(param_dic):\n        ret = {}\n        for k, v in param_dic.items():\n            ret[k] = tvm.nd.array(v.numpy())\n        return ret\n\n    new_params = deepcopy(params)\n    dense_weight_names = relay.analysis.sparse_dense._search_dense_op_weight(func)\n    for item in dense_weight_names:\n        name = str(item)\n        shape = new_params[name].shape\n        if shape[0] % bs_r == 0 and shape[1] % bs_c == 0:\n            new_w = random_bsr_matrix(shape[0], shape[1], bs_r, bs_c, density, \"float32\").todense()\n            new_params[name] = tvm.nd.array(new_w)\n    return new_params\n\n\ndef random_sparse_conv2d_params(func, params, bs_r, bs_c, density, layout):\n    \"\"\"Replace the dense parameters with random sparse parameters. Mainly used for testing.\n\n    Parameters\n    ----------\n    func : tvm.relay.Expr\n        Expr will be optimized to sparse operation.\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the Expr.\n    bs_r : int\n        The row of BSR matrix block.\n    bs_c : int\n        The column of BSR matrix block.\n    density : float\n        The density of the random sparse parameters.\n    layout : str\n        layout of network\n\n    Returns\n    -------\n    Dict[Srting, tvm.nd.array]\n        The generated random parameters.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    import numpy as np\n\n    def deepcopy(param_dic):\n        ret = {}\n        for k, v in param_dic.items():\n            ret[k] = tvm.nd.array(v.numpy())\n        return ret\n\n    new_params = deepcopy(params)\n    conv2d_weight_names = relay.analysis.sparse_conv2d._search_conv2d_op_weight(func)\n    for item in conv2d_weight_names:\n        name = str(item)\n        shape = new_params[name].shape\n        if not ((shape[0] == 1 and shape[1] == 1) or (shape[2] == 1 and shape[3] == 1)):\n            continue\n        if layout == \"NCHW\" and shape[0] % bs_r == 0 and shape[1] % bs_c == 0:\n            new_w = random_bsr_matrix(shape[0], shape[1], bs_r, bs_c, density, \"float32\").todense()\n            new_params[name] = tvm.nd.array(np.array(new_w).reshape(shape))\n        elif layout == \"NHWC\" and shape[3] % bs_r == 0 and shape[2] % bs_c == 0:\n            new_w = random_bsr_matrix(shape[3], shape[2], bs_r, bs_c, density, \"float32\").todense()\n            new_params[name] = tvm.nd.array(np.array(new_w).reshape(shape))\n    return new_params\n\n\ndef convert_model_dense_to_sparse(\n    mod, params, random_params=False, bs_r=1, bs_c=1, sparsity=0.85, layout=\"NHWC\"\n):\n    \"\"\"Convert a dense model to sparse model.\n\n    Parameters\n    ----------\n    mod : tvm.Module\n        The dense model.\n    params : Dict[Srting, tvm.nd.array]\n        Parameters of the dense model.\n    random_params : Bool = False\n        True to replace the parameters of the dense model with some random sparse tensors.\n        This is mainly used for testing.\n    bs_r : int\n        The row of BSR matrix block.\n    bs_c : int\n        The column of BSR matrix block.\n    sparsity : float\n        The sparsity of the random sparse parameters.\n    layout : str\n        layout of network\n\n    Returns\n    -------\n    tvm.Module\n        The updated sparse model.\n    Dict[Srting, tvm.nd.array]\n        The updated parameters.\n    \"\"\"\n\n    mod, params = ddo.simplify_fc_transpose.convert(mod[\"main\"], params)\n    if random_params:\n        # Manually replace the parameters of dense to sparse tensors\n        params = random_sparse_dense_params(mod, params, bs_r=bs_r, bs_c=bs_c, density=1 - sparsity)\n        # Manually replace the parameters of conv2d to sparse tensors\n        params = random_sparse_conv2d_params(\n            mod, params, bs_r=bs_r, bs_c=bs_c, density=1 - sparsity, layout=layout\n        )\n    # convert dense matmul to sparse matmul\n    mod, params = ddo.bsr_dense.convert(mod, params, (bs_r, bs_c), sparsity_threshold=0.8)\n    # convert dense conv2d to sparse conv2d\n    mod, params = ddo.bsr_conv2d.convert(\n        mod, params, (bs_r, bs_c), sparsity_threshold=0.8, layout=layout\n    )\n\n    return tvm.IRModule.from_expr(mod), params\n\n\ndef sparse_sketch_rules():\n    \"\"\"Return the sketch rules for sparse op\"\"\"\n    sparse_sketch_rule_list = [\n        auto_scheduler.PreloadCustomSketchRule(\n            sparse_conv2d_meet_condition_func, sparse_conv2d_apply_func, \"SparseConv2D\"\n        ),\n        auto_scheduler.PreloadCustomSketchRule(\n            sparse_dense_meet_condition_func, sparse_dense_apply_func, \"SparseDense\"\n        ),\n        # Add more sketch rules for sparse\n    ]\n    return sparse_sketch_rule_list\n\n\ndef sparse_conv2d_meet_condition_func(search_policy, state, stage_id):\n    state = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if state.stages[stage_id].op.tag in [\n        \"sparse_conv2d_sp_bsrmm\",\n        \"sparse_conv2d_sp_bsrmm_block\",\n    ]:\n        return auto_scheduler.PreloadCustomSketchRule.APPLY_AND_SKIP_REST\n    return auto_scheduler.PreloadCustomSketchRule.PASS\n\n\ndef sparse_conv2d_apply_func(search_policy, state, stage_id):\n    \"\"\"Describe how to generate the initial sketch for sparse conv2d\"\"\"\n    ret = []\n    s_0 = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if s_0.stages[stage_id].op.tag == \"sparse_conv2d_sp_bsrmm_block\":\n        return [s_0.state_object, stage_id - 1]\n\n    sparse_conv2d = s_0.stages[stage_id].op\n    sparse_conv2d_block = s_0.stages[stage_id - 1].op\n    assert sparse_conv2d.tag == \"sparse_conv2d_sp_bsrmm\"\n    assert sparse_conv2d_block.tag == \"sparse_conv2d_sp_bsrmm_block\"\n    layout = sparse_conv2d.attrs[\"layout\"]\n\n    # Set the default consumer of compute block\n    consumer = sparse_conv2d\n\n    # If sparse conv2d has a single elementwise consumer\n    # We can compute inline the sparse_conv2d output stage\n    consumers = _ffi_api.SearchPolicyUtilsGetConsumers(\n        search_policy.search_task, s_0.state_object, stage_id\n    )\n    if len(consumers) == 1:\n        consumer_id = int(consumers.items()[0][0])\n        if _ffi_api.SearchPolicyUtilsIsElementwiseMatch(\n            search_policy.search_task, s_0.state_object, stage_id, consumer_id\n        ):\n            consumer = s_0.stages[consumer_id].op\n            s_0.compute_inline(sparse_conv2d)\n\n    c = None\n    if layout == \"NHWC\":\n        if len(s_0[sparse_conv2d_block].iters) == 6:\n            # bs_c = 1\n            i, h, w, nb_j, j, row_offset = s_0[  # pylint: disable=invalid-name\n                sparse_conv2d_block\n            ].iters\n        else:\n            i, h, w, nb_j, j, row_offset, c = s_0[  # pylint: disable=invalid-name\n                sparse_conv2d_block\n            ].iters\n        m, x, y, n = s_0[consumer].iters\n    elif layout == \"NCHW\":\n        if len(s_0[sparse_conv2d_block].iters) == 6:\n            # bs_c = 1\n            i, nb_j, j, h, w, row_offset = s_0[  # pylint: disable=invalid-name\n                sparse_conv2d_block\n            ].iters\n        else:\n            i, nb_j, j, h, w, row_offset, c = s_0[  # pylint: disable=invalid-name\n                sparse_conv2d_block\n            ].iters\n        m, n, x, y = s_0[consumer].iters\n\n    i_0, i_1, i_2 = s_0.split(sparse_conv2d_block, i, [None, None])\n    m_0, m_1 = s_0.follow_split(consumer, m, len(s_0.transform_steps) - 1, 1)\n    h_0, h_1, h_2 = s_0.split(sparse_conv2d_block, h, [None, None])\n    x_0, x_1 = s_0.follow_split(consumer, x, len(s_0.transform_steps) - 1, 1)\n    w_0, w_1, w_2 = s_0.split(sparse_conv2d_block, w, [None, None])  # pylint: disable=invalid-name\n    y_0, y_1 = s_0.follow_split(consumer, y, len(s_0.transform_steps) - 1, 1)\n    j_0, j_1 = s_0.split(sparse_conv2d_block, nb_j, [None])\n    n_0, n_1 = s_0.follow_split(consumer, n, len(s_0.transform_steps) - 1, 1)\n    if layout == \"NHWC\":\n        if c is None:\n            s_0.reorder(\n                sparse_conv2d_block,\n                [i_0, h_0, w_0, j_0, i_1, h_1, w_1, j_1, row_offset, i_2, h_2, w_2, j],\n            )\n        else:\n            s_0.reorder(\n                sparse_conv2d_block,\n                [i_0, h_0, w_0, j_0, i_1, h_1, w_1, j_1, row_offset, i_2, h_2, w_2, j, c],\n            )\n        s_0.reorder(consumer, [m_0, x_0, y_0, n_0, m_1, x_1, y_1, n_1])\n    elif layout == \"NCHW\":\n        if c is None:\n            s_0.reorder(\n                sparse_conv2d_block,\n                [i_0, j_0, h_0, w_0, i_1, j_1, h_1, w_1, row_offset, i_2, j, h_2, w_2],\n            )\n        else:\n            s_0.reorder(\n                sparse_conv2d_block,\n                [i_0, j_0, h_0, w_0, i_1, j_1, h_1, w_1, row_offset, i_2, j, c, h_2, w_2],\n            )\n        s_0.reorder(consumer, [m_0, n_0, x_0, y_0, m_1, n_1, x_1, y_1])\n    s_0.compute_at(sparse_conv2d_block, consumer, n_0)\n\n    ret.append([s_0.state_object, stage_id - 2])\n\n    return ret\n\n\ndef sparse_dense_meet_condition_func(search_policy, state, stage_id):\n    state = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if state.stages[stage_id].op.tag in [\n        \"sparse_dense_sp_rhs_bsrmm\",\n        \"sparse_dense_sp_rhs_bsrmm_block\",\n    ]:\n        return auto_scheduler.PreloadCustomSketchRule.APPLY_AND_SKIP_REST\n    return auto_scheduler.PreloadCustomSketchRule.PASS\n\n\ndef sparse_dense_apply_func(search_policy, state, stage_id):\n    \"\"\"Describe how to generate the initial sketch for sparse dense\"\"\"\n    ret = []\n    s_0 = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n    if s_0.stages[stage_id].op.tag == \"sparse_dense_sp_rhs_bsrmm_block\":\n        return [s_0.state_object, stage_id - 1]\n\n    sparse_dense = s_0.stages[stage_id].op\n    sparse_dense_block = s_0.stages[stage_id - 1].op\n    assert sparse_dense.tag == \"sparse_dense_sp_rhs_bsrmm\"\n    assert sparse_dense_block.tag == \"sparse_dense_sp_rhs_bsrmm_block\"\n\n    # Set the default consumer of compute block\n    consumer = sparse_dense\n\n    # If sparse dense has a single elementwise consumer\n    # We can compute inline the sparse_dense output stage\n    consumers = _ffi_api.SearchPolicyUtilsGetConsumers(\n        search_policy.search_task, s_0.state_object, stage_id\n    )\n    if len(consumers) == 1:\n        consumer_id = int(consumers.items()[0][0])\n        if _ffi_api.SearchPolicyUtilsIsElementwiseMatch(\n            search_policy.search_task, s_0.state_object, stage_id, consumer_id\n        ):\n            consumer = s_0.stages[consumer_id].op\n            s_0.compute_inline(sparse_dense)\n\n    i, nb_j, j, row_offset, c = s_0[sparse_dense_block].iters\n    m, n = s_0[consumer].iters\n    i_0, i_1, i_2 = s_0.split(sparse_dense_block, i, [None, None])\n    m_0, m_1 = s_0.follow_split(consumer, m, len(s_0.transform_steps) - 1, 1)\n    j_0, j_1 = s_0.split(sparse_dense_block, nb_j, [None])\n    n_0, n_1 = s_0.follow_split(consumer, n, len(s_0.transform_steps) - 1, 1)\n    s_0.reorder(sparse_dense_block, [i_0, j_0, i_1, j_1, row_offset, i_2, j, c])\n    s_0.reorder(consumer, [m_0, n_0, m_1, n_1])\n    s_0.compute_at(sparse_dense_block, consumer, n_0)\n\n    ret.append([s_0.state_object, stage_id - 2])\n\n    return ret\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse_fill_empty_rows.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHnew_sparse_indices WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=no-else-return, too-many-locals, too-many-arguments, too-many-branches\n# pylint: disable=undefined-variable, invalid-name\n\"\"\"SparseFillEmptyRows operator\"\"\"\nfrom ..te import hybrid\n\n\n@hybrid.script\ndef _sparse_fill_empty_rows(\n    sparse_indices,\n    sparse_values,\n    dense_shape,\n    default_value,\n    new_sparse_indices_shape,\n    new_sparse_values_shape,\n    empty_row_indicator_shape,\n):\n    default_value_ = int64(default_value[0])\n    new_sparse_indices = output_tensor(new_sparse_indices_shape, \"int64\")\n    new_sparse_values = output_tensor(new_sparse_values_shape, \"int64\")\n    empty_row_indicator = output_tensor(empty_row_indicator_shape, \"int64\")\n    new_sparse_indices_row_id = 0\n\n    if int64(sparse_indices.shape[0]) == int64(0):  # Handle Empty Case\n        #  Fill all rows with default values\n        for i in range(0, new_sparse_indices_shape[0]):\n            new_sparse_indices[i, 0] = int64(i)\n            new_sparse_values[i] = default_value_\n            empty_row_indicator[i] = int64(1)\n            for k in range(1, int64(new_sparse_indices_shape[1])):\n                new_sparse_indices[i, k] = int64(0)\n\n        return (new_sparse_indices, new_sparse_values, empty_row_indicator)\n\n    else:\n        # Iterate through sparse_indices and add rows if/when required\n        for i in range(0, int64(sparse_indices.shape[0])):\n            if i == 0:\n                prev_row_id = int64(0)\n            else:\n                prev_row_id = int64(sparse_indices[i - 1, 0] + 1)\n            row_id = int64(sparse_indices[i, 0])\n\n            # Since input is in row-major order, add rows between prev_row_id and row_id\n            for j in range(prev_row_id, row_id):\n                new_sparse_indices[new_sparse_indices_row_id, 0] = int64(j)\n                for k in range(1, int64(new_sparse_indices_shape[1])):\n                    new_sparse_indices[new_sparse_indices_row_id, k] = int64(0)\n                empty_row_indicator[prev_row_id] = int64(1)\n                new_sparse_values[new_sparse_indices_row_id] = default_value_\n                new_sparse_indices_row_id += 1\n\n            # Add current element to output\n            new_sparse_indices[new_sparse_indices_row_id, 0] = row_id\n            for k in range(1, int64(new_sparse_indices_shape[1])):\n                new_sparse_indices[new_sparse_indices_row_id, k] = int64(sparse_indices[i, k])\n            new_sparse_values[new_sparse_indices_row_id] = int64(sparse_values[i])\n            empty_row_indicator[row_id] = int64(0)\n            new_sparse_indices_row_id += 1\n\n        # Add rows with default value if last row id of sparse_indices is not dense_shape[0] - 1\n        for i in range(\n            int64(sparse_indices[sparse_indices.shape[0] - 1, 0] + 1), int64(dense_shape[0])\n        ):\n\n            new_sparse_indices[new_sparse_indices_row_id, 0] = int64(i)\n            for k in range(1, int64(new_sparse_indices_shape[1])):\n                new_sparse_indices[new_sparse_indices_row_id, k] = int64(0)\n            empty_row_indicator[i] = int64(1)\n            new_sparse_values[new_sparse_indices_row_id] = default_value_\n            new_sparse_indices_row_id += 1\n\n        return (new_sparse_indices, new_sparse_values, empty_row_indicator)\n\n\ndef sparse_fill_empty_rows(\n    sparse_indices,\n    sparse_values,\n    dense_shape,\n    default_value,\n    new_sparse_indices_shape,\n    new_sparse_values_shape,\n    empty_row_indicator_shape,\n):\n    return _sparse_fill_empty_rows(\n        sparse_indices,\n        sparse_values,\n        dense_shape,\n        default_value,\n        new_sparse_indices_shape,\n        new_sparse_values_shape,\n        empty_row_indicator_shape,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/sparse_reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks\n\"\"\"Sparse_Reshape operator\"\"\"\nfrom ..tir import decl_buffer, ir_builder, Cast\nfrom ..te import extern, div, floordiv, floormod\n\n\ndef sparse_reshape(\n    sparse_indices,\n    prev_shape,\n    new_shape,\n    new_sparse_indices_shape,\n    new_shape_shape,\n):\n    \"\"\"\n    Reshape a Sparse Tensor\n\n    Parameters\n    ----------\n    sparse_indices : relay.Expr\n        A 2-D tensor[N, n_dim] of integers containing location of sparse values, where N is the\n        number of sparse values and n_dim is the number of dimensions of the dense_shape\n\n    prev_shape : relay.Expr\n        A 1-D tensor containing the previous shape of the dense tensor\n\n    new_shape : relay.Expr\n        A 1-D tensor containing the new shape of the dense tensor\n\n    Returns\n    -------\n    result: relay.Expr\n        Output tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        sparse_indices = [[0, 0, 0],\n                            [0, 0, 1],\n                            [0, 1, 0],\n                            [1, 0, 0],\n                            [1, 2, 3]]\n        prev_shape = [2, 3, 4]\n        new_shape = [9, -1]\n        new_sparse_indices, new_shape = relay.sparse_reshape(\n            sparse_indices, prev_shape, new_shape)\n        new_sparse_indices = [[0, 0],\n                              [0, 1],\n                              [1, 2],\n                              [4, 2],\n                              [8, 1]]\n        new_shape = [9, 4]\n    \"\"\"\n\n    def gen_ir(\n        sparse_indices_ptr,\n        prev_shape_ptr,\n        new_shape_ptr,\n        new_sparse_indices_ptr,\n        out_new_shape_ptr,\n    ):\n        ib = ir_builder.create()\n\n        sparse_indices = ib.buffer_ptr(sparse_indices_ptr)\n        prev_shape = ib.buffer_ptr(prev_shape_ptr)\n\n        new_shape = ib.buffer_ptr(new_shape_ptr)\n        out_new_shape = ib.buffer_ptr(out_new_shape_ptr)\n        new_sparse_indices = ib.buffer_ptr(new_sparse_indices_ptr)\n        out_new_shape = ib.buffer_ptr(out_new_shape_ptr)\n\n        prev_shape_size = prev_shape_ptr.shape[0]\n        new_shape_size = new_shape_ptr.shape[0]\n\n        multipliers = ib.allocate(\n            new_shape_ptr.dtype, (prev_shape_size,), name=\"multipliers\", scope=\"local\"\n        )\n        dividers = ib.allocate(\n            new_shape_ptr.dtype, (new_shape_size,), name=\"dividers\", scope=\"local\"\n        )\n        flattened_indices = ib.allocate(\n            new_shape_ptr.dtype,\n            (sparse_indices_ptr.shape[0],),\n            name=\"flattened_indices\",\n            scope=\"local\",\n        )\n\n        total_ele = ib.allocate(new_shape_ptr.dtype, (1,), name=\"total_ele\", scope=\"local\")\n        total_ele[0] = prev_shape[0]\n\n        # Cumulative Reverse Exclusive Multiply\n        multipliers[prev_shape_size - 1] = Cast(new_shape_ptr.dtype, 1)\n        with ib.for_range(0, prev_shape_size - 1) as i_:\n            i = i_ + 1\n            multipliers[prev_shape_size - 1 - i] = (\n                prev_shape[prev_shape_size - i] * multipliers[prev_shape_size - i]\n            )\n            total_ele[0] *= prev_shape[prev_shape_size - i]\n\n        division_total_ele = ib.allocate(\n            new_shape_ptr.dtype, (1,), name=\"division_total_ele\", scope=\"local\"\n        )\n        division_total_ele[0] = Cast(new_shape_ptr.dtype, 1)\n        with ib.for_range(0, new_shape_size) as i:\n            with ib.if_scope(new_shape[i] != -1):\n                division_total_ele[0] *= new_shape[i]\n\n        # Compute true output shape (replace negative ones)\n        with ib.for_range(0, new_shape_size) as i:\n            with ib.if_scope(new_shape[i] == -1):\n                out_new_shape[i] = Cast(\n                    new_shape_ptr.dtype, div(total_ele[0], division_total_ele[0])\n                )\n            with ib.else_scope():\n                out_new_shape[i] = new_shape[i]\n\n        equal_shape = ib.allocate(\"bool\", (1,), name=\"equal_shape\", scope=\"local\")\n\n        # Check if prev_shape and new_shape are equal\n        equal_shape[0] = True\n        with ib.if_scope(prev_shape_size == new_shape_size):\n            with ib.for_range(0, prev_shape_size) as i:\n                with ib.if_scope(prev_shape[i] != out_new_shape[i]):\n                    equal_shape[0] = False\n        with ib.else_scope():\n            equal_shape[0] = False\n\n        # Return same inputs if shapes are equal\n        with ib.if_scope(equal_shape[0]):\n            with ib.for_range(0, sparse_indices_ptr.shape[0], kind=\"parallel\") as i:\n                with ib.for_range(0, sparse_indices_ptr.shape[1]) as j:\n                    new_sparse_indices[i, j] = sparse_indices[i, j]\n\n        # Else compute new_sparse_indices\n        with ib.else_scope():\n            dividers[new_shape_size - 1] = Cast(new_shape_ptr.dtype, 1)\n            with ib.for_range(0, new_shape_size - 1) as i_:\n                i = i_ + 1\n                dividers[new_shape_size - 1 - i] = (\n                    dividers[new_shape_size - i] * out_new_shape[new_shape_size - i]\n                )\n\n            with ib.for_range(0, sparse_indices_ptr.shape[0], kind=\"parallel\") as i:\n                flattened_indices[i] = Cast(new_shape_ptr.dtype, 0)\n                with ib.for_range(0, sparse_indices_ptr.shape[1]) as j:\n                    flattened_indices[i] += sparse_indices[i, j] * multipliers[j]\n\n            with ib.for_range(0, new_sparse_indices_ptr.shape[0], kind=\"parallel\") as i:\n                current_element = ib.allocate(\n                    new_shape_ptr.dtype, (1,), name=\"current_element\", scope=\"local\"\n                )\n                current_element[0] = flattened_indices[i]\n\n                with ib.for_range(0, new_sparse_indices_ptr.shape[1]) as j:\n                    new_sparse_indices[i, j] = Cast(\n                        sparse_indices_ptr.dtype, floordiv(current_element[0], dividers[j])\n                    )\n                    current_element[0] = floormod(current_element[0], dividers[j])\n\n        return ib.get()\n\n    new_sparse_indices_buf = decl_buffer(\n        new_sparse_indices_shape, sparse_indices.dtype, \"new_sparse_indices_buf\"\n    )\n    new_shape_buf = decl_buffer(new_shape_shape, prev_shape.dtype, \"new_shape_buf\")\n\n    return extern(\n        [new_sparse_indices_shape, new_shape_shape],\n        [sparse_indices, prev_shape, new_shape],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0], outs[1]),\n        out_buffers=[new_sparse_indices_buf, new_shape_buf],\n        name=\"sparse_reshape_cpu\",\n        tag=\"sparse_reshape_cpu\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/stft.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks, unused-argument\n\"\"\"STFT operator\"\"\"\nfrom math import pi\nfrom tvm import te, tir\n\n\ndef stft(\n    data,\n    n_fft,\n    hop_length,\n    win_length,\n    window,\n    normalized,\n    onesided,\n    output_shape,\n):\n    \"\"\"\n    The STFT computes the Fourier transform of short overlapping windows of the input.\n    This gives frequency components of the signal as they change over time.\n    Parameters\n    ----------\n    data : relay.Expr\n        Either a 1-D tensor or a 2-D batch tensor.\n    n_fft : int\n        The size of Fourier transform\n    hop_length : int\n        The distance between neighboring sliding window frames\n    win_length : int\n        The size of window frame and STFT filter\n    window : relay.Expr\n        A 1-D tensor window frame\n    normalized : bool\n        Whether to return the normalized STFT results\n    onesided : bool\n        Whether to return onesided result or fill with conjugate symmetry\n    Returns\n    -------\n    output : relay.Expr\n        Tensor containing the STFT result\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [1, 2, 3, 4, 5, 6]\n        window = [4, 3, 2]\n        [n_fft, hop_length, win_length, normalized, onesided] = [3, 3, 3, False, True]\n        relay.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n        -> [[[15.0000,  0.0000], [34.0000,  0.0000]], [[ 4.5000,  0.8660], [ 1.0000, -1.7321]]]\n    \"\"\"\n\n    def gen_ir(\n        data_ptr,\n        n_fft,\n        hop_length,\n        win_length,\n        window_ptr,\n        normalized,\n        onesided,\n        output_ptr,\n        loop_kind,\n    ):\n        ib = tir.ir_builder.create()\n        data = ib.buffer_ptr(data_ptr)\n        window = ib.buffer_ptr(window_ptr)\n        output = ib.buffer_ptr(output_ptr)\n        # https://librosa.org/doc/0.7.2/_modules/librosa/core/spectrum.html#stft\n        with ib.for_range(\n            0, output_ptr.shape[0] * output_ptr.shape[1], kind=\"parallel\"\n        ) as batch_row:\n            with ib.for_range(0, output_ptr.shape[2], kind=loop_kind) as col:\n                batch = ib.allocate(\"int32\", (1), name=\"batch\", scope=\"local\")\n                row = ib.allocate(\"int32\", (1), name=\"row\", scope=\"local\")\n                batch = tir.floordiv(batch_row, output_ptr.shape[1])\n                row = tir.floormod(batch_row, output_ptr.shape[1])\n                output[batch, row, col, 0] = tir.Cast(data_ptr.dtype, 0)\n                output[batch, row, col, 1] = tir.Cast(data_ptr.dtype, 0)\n                with ib.for_range(0, win_length) as wlen:\n                    output[batch, row, col, 0] += (\n                        window[wlen]\n                        * data[batch, col * hop_length + wlen]\n                        * tir.cos(2 * pi * row * wlen / win_length)\n                    )\n                    output[batch, row, col, 1] -= (\n                        window[wlen]\n                        * data[batch, col * hop_length + wlen]\n                        * tir.sin(2 * pi * row * wlen / win_length)\n                    )\n                with ib.if_scope(normalized):\n                    output[batch, row, col, 0] /= tir.sqrt(tir.const(n_fft, \"float32\"))\n                    output[batch, row, col, 1] /= tir.sqrt(tir.const(n_fft, \"float32\"))\n\n        return ib.get()\n\n    output_buf = tir.decl_buffer(output_shape, data.dtype, \"output_buf\")\n    loop_kind = \"vectorize\"\n    if isinstance(output_shape[2], tir.expr.SizeVar):  # any_dim\n        loop_kind = \"serial\"\n\n    return te.extern(\n        output_shape,\n        [data, window],\n        lambda ins, outs: gen_ir(\n            ins[0], n_fft, hop_length, win_length, ins[1], normalized, onesided, outs[0], loop_kind\n        ),\n        dtype=[data.dtype],\n        out_buffers=[output_buf],\n        name=\"stft_cpu\",\n        tag=\"stft_cpu\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/tag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Namespace of all tag system in tvm\n\nEach operator can be tagged by a tag, which indicate its type.\n\nGeneric categories\n\n- tag.ELEMWISE=\"elemwise\":\n   Elementwise operator, for example :code:`out[i, j] = input[i, j]`\n- tag.BROADCAST=\"broadcast\":\n    Broadcasting operator, can always map output axis to the input in order.\n    for example :code:`out[i, ax1, j, ax2] = input[i, j]`.\n    Note that the axis need to be in order so transpose is not a bcast operator.\n    If an input of broadcast operator has same shape as output,\n    we can ensure that it is elementwise relation.\n- tag.INJECTIVE=\"injective\":\n    Injective operator, can always injectively map output axis to a single input axis.\n    All injective operator can still be safely fused similar to ewise to reduction.\n\n- tag.COMM_REDUCE=\"comm_reduce\":\n    Communicative reduction operator\n- If an op does not belong to these generic categories, it should have a special tag.\n\nNote\n----\nWhen we add a new topi operator, the op need to be tagged as generic as possible.\nWe can also compose tags like \"injective,pad\" to give generic and specific information.\nWhen we use composed tags, we must always put generic tag in the first location.\n\"\"\"\n\nELEMWISE = \"elemwise\"\nBROADCAST = \"broadcast\"\nINJECTIVE = \"injective\"\nCOMM_REDUCE = \"comm_reduce\"\nCOMM_REDUCE_IDX = \"comm_reduce_idx\"\n\n\ndef is_broadcast(tag):\n    \"\"\"Check if a tag is bcast\n\n    Parameters\n    ----------\n    tag : str\n        The input tag\n\n    Returns\n    -------\n    ret : bool\n        Whether a tag is broadcast\n    \"\"\"\n    if tag in (ELEMWISE, BROADCAST):\n        return True\n    return tag.startswith(ELEMWISE) or tag.startswith(BROADCAST)\n\n\ndef is_injective(tag):\n    \"\"\"Check if a tag is injective\n\n    Parameters\n    ----------\n    tag : str\n        The input tag\n\n    Returns\n    -------\n    ret : bool\n        Whether a tag is injective\n    \"\"\"\n    if tag in (ELEMWISE, BROADCAST, INJECTIVE):\n        return True\n    return tag.startswith(ELEMWISE) or tag.startswith(BROADCAST) or tag.startswith(INJECTIVE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,consider-using-enumerate,unused-argument,len-as-condition\n\"\"\"Elementwise operators\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom . import cpp\n\n\ndef elemwise_sum(xs):\n    \"\"\"Perform element-wise sum on inputs\n\n    Parameters\n    ----------\n    xs : list of tvm.te.Tensor\n        Input arguments.\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.elemwise_sum(xs)\n\n\ndef full(shape, dtype, fill_value):\n    \"\"\"Fill tensor with fill_value\n\n    Parameters\n    ----------\n    shape : tuple\n        Input tensor shape.\n    dtype : str\n        Data type\n    fill_value : float\n        Value to be filled\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.full(shape, dtype, fill_value)\n\n\ndef full_like(x, fill_value):\n    \"\"\"Construct a tensor with same shape as input tensor,\n       then fill tensor with fill_value.\n\n    Parameters\n    ----------\n    x : tvm.te.Tensor\n        Input argument.\n    fill_value : float\n        Value to be filled\n\n    Returns\n    -------\n    y : tvm.te.Tensor\n        The result.\n    \"\"\"\n    return cpp.full_like(x, fill_value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"TOPI Testing Util functions.\n\nUsed to verify the correctness of operators in TOPI .\n\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .conv1d_ncw_python import conv1d_ncw_python, group_conv1d_ncw_python\nfrom .conv2d_hwcn_python import conv2d_hwcn_python\nfrom .conv2d_nchw_python import conv2d_nchw_python\nfrom .conv2d_nhwc_python import conv2d_nhwc_python\nfrom .conv3d_ncdhw_python import conv3d_ncdhw_python\nfrom .conv3d_ndhwc_python import conv3d_ndhwc_python\nfrom .conv3d_transpose_ncdhw_python import conv3d_transpose_ncdhw_python\nfrom .conv2d_transpose_python import conv2d_transpose_nchw_python, conv2d_transpose_nhwc_python\nfrom .conv1d_transpose_ncw_python import conv1d_transpose_ncw_python\nfrom .correlation_nchw_python import correlation_nchw_python\nfrom .deformable_conv2d_python import deformable_conv2d_nchw_python, deformable_conv2d_nhwc_python\nfrom .depthwise_conv2d_python import (\n    depthwise_conv2d_python_nchw,\n    depthwise_conv2d_python_nhwc,\n    depthwise_conv2d_python_nchwc,\n)\nfrom .dilate_python import dilate_python\nfrom .softmax_python import softmax_python, log_softmax_python\nfrom .resize_python import resize1d_python, resize2d_python, resize3d_python\nfrom .reorg_python import reorg_python\nfrom .roi_align_python import roi_align_nchw_python, roi_align_nhwc_python\nfrom .roi_pool_python import roi_pool_nchw_python\nfrom .layer_norm_python import layer_norm_python\nfrom .lrn_python import lrn_python\nfrom .l2_normalize_python import l2_normalize_python\nfrom .gather_python import gather_python\nfrom .gather_nd_python import gather_nd_python\nfrom .strided_slice_python import strided_slice_python, strided_set_python\nfrom .batch_matmul import batch_matmul\nfrom .batch_norm import batch_norm\nfrom .slice_axis_python import slice_axis_python\nfrom .sequence_mask_python import sequence_mask\nfrom .poolnd_python import poolnd_python\nfrom .pool_grad_python import pool_grad_nchw\nfrom .one_hot import one_hot\nfrom .depth_to_space import depth_to_space_python\nfrom .space_to_depth import space_to_depth_python\nfrom .crop_and_resize_python import crop_and_resize_python\nfrom .common import (\n    compare_numpy_tvm,\n    get_injective_schedule,\n    get_reduce_schedule,\n    get_broadcast_schedule,\n    get_elemwise_schedule,\n    get_conv2d_nchw_implement,\n    dispatch,\n)\nfrom .adaptive_pool_python import adaptive_pool\nfrom .grid_sample_python import affine_grid_python, grid_sample_python\nfrom .matrix_set_diag import matrix_set_diag\nfrom .space_to_batch_nd import space_to_batch_nd_python\nfrom .batch_to_space_nd import batch_to_space_nd_python\nfrom .nll_loss import nll_loss\nfrom .dense import dense\nfrom .searchsorted import searchsorted_ref\nfrom .conv2d_backcward_weight_python import conv2d_backward_weight_python\nfrom .lstm_python import lstm_python\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/adaptive_pool_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, unused-variable\n\"\"\"adaptive pool in python\"\"\"\nimport numpy as np\n\n\ndef _start_index(index, odim, idim):\n    return int(np.floor(index * idim / odim))\n\n\ndef _end_index(index, odim, idim):\n    return int(np.ceil((index + 1) * idim / odim))\n\n\ndef _pool1d(in_size, out_size, np_data, np_op):\n    out = np.zeros(out_size).astype(np_data.dtype)\n    ow = out_size[0]\n    for l in range(ow):\n        l_start = _start_index(l, ow, in_size[0])\n        l_end = _end_index(l, ow, in_size[0])\n        l_sl = slice(l_start, l_end)\n        out[l] = np_op(np_data[l_sl])\n    return out\n\n\ndef _pool2d(in_size, out_size, np_data, np_op):\n    out = np.zeros(out_size).astype(np_data.dtype)\n    oh, ow = out_size\n    for k in range(oh):\n        k_start = _start_index(k, oh, in_size[0])\n        k_end = _end_index(k, oh, in_size[0])\n        k_sl = slice(k_start, k_end)\n        for l in range(ow):\n            l_start = _start_index(l, ow, in_size[1])\n            l_end = _end_index(l, ow, in_size[1])\n            l_sl = slice(l_start, l_end)\n            out[k, l] = np_op(np_data[k_sl, l_sl])\n    return out\n\n\ndef _pool3d(in_size, out_size, np_data, np_op):\n    out = np.zeros(out_size).astype(np_data.dtype)\n    od, oh, ow = out_size\n    for m in range(od):\n        m_start = _start_index(m, od, in_size[0])\n        m_end = _end_index(m, od, in_size[0])\n        m_sl = slice(m_start, m_end)\n        for k in range(oh):\n            k_start = _start_index(k, oh, in_size[1])\n            k_end = _end_index(k, oh, in_size[1])\n            k_sl = slice(k_start, k_end)\n            for l in range(ow):\n                l_start = _start_index(l, ow, in_size[2])\n                l_end = _end_index(l, ow, in_size[2])\n                l_sl = slice(l_start, l_end)\n                out[m, k, l] = np_op(np_data[m_sl, k_sl, l_sl])\n    return out\n\n\ndef adaptive_pool_channel_first(np_data, out_size, pool_op, np_op):\n    \"\"\"The reference function for adaptive pool, channel first layout\"\"\"\n    ishape = np_data.shape\n    n, c = ishape[:2]\n    oshape = (n, c) + out_size\n    np_out = np.zeros(oshape).astype(np_data.dtype)\n\n    for i in range(n):\n        for j in range(c):\n            np_out[i, j] = pool_op(ishape[2:], out_size, np_data[i, j], np_op)\n\n    return np_out\n\n\ndef adaptive_pool_channel_last(np_data, out_size, pool_op, np_op):\n    \"\"\"The reference function for adaptive pool, channel last layout\"\"\"\n    ishape = np_data.shape\n    n, c = ishape[0], ishape[-1]\n    oshape = (n,) + out_size + (c,)\n    np_out = np.zeros(oshape).astype(np_data.dtype)\n\n    for i in range(n):\n        for j in range(c):\n            if len(out_size) == 1:\n                np_out[i, :, j] = pool_op(ishape[1:-1], out_size, np_data[i, :, j], np_op)\n            elif len(out_size) == 2:\n                np_out[i, :, :, j] = pool_op(ishape[1:-1], out_size, np_data[i, :, :, j], np_op)\n            else:\n                np_out[i, :, :, :, j] = pool_op(\n                    ishape[1:-1], out_size, np_data[i, :, :, :, j], np_op\n                )\n\n    return np_out\n\n\ndef adaptive_pool(np_data, out_size, pool_type, layout):\n    \"\"\"The reference function for adaptive pool, for 2d and 3d\"\"\"\n    if isinstance(out_size, int):\n        out_size = (out_size,)\n    if len(out_size) == 1:\n        pool_op = _pool1d\n    elif len(out_size) == 2:\n        pool_op = _pool2d\n    else:\n        assert len(out_size) == 3\n        pool_op = _pool3d\n\n    np_op = np.mean if pool_type == \"avg\" else np.max\n\n    if layout in [\"NCW\", \"NCHW\", \"NCDHW\"]:\n        return adaptive_pool_channel_first(np_data, out_size, pool_op, np_op)\n\n    assert layout in [\"NWC\", \"NHWC\", \"NDHWC\"]\n    return adaptive_pool_channel_last(np_data, out_size, pool_op, np_op)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Batch matmul in python\"\"\"\nimport numpy as np\n\n\ndef batch_matmul(x, y, out_dtype=None, trans_x=False, trans_y=True):\n    \"\"\"batch_matmul operator implemented in numpy.\n\n    Parameters\n    ----------\n    x : numpy.ndarray\n        3-D with shape [batch, M, K]\n\n    y : numpy.ndarray\n        3-D with shape [batch, N, K]\n\n    out_dtype: string, optional\n        Specify the dtype of output\n\n    Returns\n    -------\n    out : numpy.ndarray\n        3-D with shape [batch, M, N]\n    \"\"\"\n    if trans_x:\n        XB, _, M = x.shape\n    else:\n        XB, M, _ = x.shape\n    if trans_y:\n        YB, N, _ = y.shape\n    else:\n        YB, _, N = y.shape\n    batch = max(XB, YB)\n    dtype = x.dtype if out_dtype is None else out_dtype\n    out = np.zeros((batch, M, N)).astype(dtype)\n    for i in range(batch):\n        xx = x[i if XB != 1 else 0].astype(dtype)\n        yy = y[i if YB != 1 else 0].astype(dtype)\n        out[i] = np.dot(\n            xx.T if trans_x else xx,\n            yy.T if trans_y else yy,\n        )\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/batch_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Batch Normalization implemented in Numpy.\"\"\"\nimport numpy as np\n\n\ndef batch_norm(\n    x: np.ndarray,\n    gamma: np.ndarray,\n    beta: np.ndarray,\n    moving_mean: np.ndarray,\n    moving_var: np.ndarray,\n    axis: int,\n    epsilon: float,\n    center: bool,\n    scale: bool,\n):\n    \"\"\"Batch Normalization operator implemented in Numpy.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        Input to be batch-normalized.\n\n    gamma : np.ndarray\n        Scale factor to be applied to the normalized tensor.\n\n    beta : np.ndarray\n        Offset to be applied to the normalized tensor.\n\n    moving_mean : np.ndarray\n        Running mean of input.\n\n    moving_var : np.ndarray\n        Running variance of input.\n\n    axis : int\n        Specify along which shape axis the normalization should occur.\n\n    epsilon : float\n        Small float added to variance to avoid dividing by zero.\n\n    center : bool\n        If True, add offset of beta to normalized tensor, If False,\n        beta is ignored.\n\n    scale : bool\n        If True, scale normalized tensor by gamma. If False, gamma\n        is ignored.\n\n    Returns\n    -------\n    output : np.ndarray\n        Normalized data with same shape as input\n\n    moving_mean : np.ndarray\n        Running mean of input.\n\n    moving_var : np.ndarray\n        Running variance of input.\n    \"\"\"\n    shape = [1] * len(x.shape)\n    shape[axis] = x.shape[axis]\n\n    moving_mean_rs = moving_mean.reshape(shape)\n    moving_var_rs = moving_var.reshape(shape)\n\n    out = (x - moving_mean_rs) / np.sqrt(moving_var_rs + epsilon)\n\n    if scale:\n        out = out * gamma.reshape(shape)\n    if center:\n        out = out + beta.reshape(shape)\n\n    return [out, moving_mean, moving_var]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/batch_to_space_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Batch to space ND in python\"\"\"\nimport numpy as np\nfrom . import strided_slice_python\n\n\ndef batch_to_space_nd_python(data, block_shape, crop_begin_list, crop_end_list):\n    \"\"\"Batch to Space operator in python for NHWC layout.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        N-D with shape [batch, spatial_shape, remaining_shapes],\n        where spatial_shape has M dimensions.\n\n    block_shape : list of ints\n        1-D array of size [M] where M is number of spatial dims, specifies block\n        size for each spatial dimension.\n\n    crop_begin_list : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        begin crop size for each spatial dimension.\n\n    crop_end_list : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        end crop size for each spatial dimension.\n\n    Returns\n    -------\n    b2s_out : np.ndarray\n        N-D with shape\n        [batch / prod(block_shape),\n        in_shape[1] * block_shape[0] - crop_begin_list[0] - crop_end_list[0], ...,\n        in_shape[M] * block_shape[M-1] - crop_begin_list[M-1] - crop_end_list[M-1],\n        remaining_shape]\n    \"\"\"\n    in_shape = data.shape\n    N = len(in_shape)\n    M = len(block_shape)\n    block_shape_prod = np.prod(block_shape)\n    in_batch = data.shape[0]\n    axis = []\n    r_p_shape = []\n\n    r_shape = [block_shape[i] for i in range(0, M)]\n    axis.append(len(r_shape))\n    r_shape.append(in_batch // block_shape_prod)\n\n    for i in range(1, N):\n        axis.append(len(r_shape))\n        if len(axis) < (M + N):\n            axis.append(len(r_shape) - (M + 1))\n        r_shape.append(in_shape[i])\n\n    r_p_shape.append(int((in_batch / block_shape_prod)))\n    for i in range(1, M + 1):\n        r_p_shape.append(in_shape[i] * block_shape[i - 1])\n    for i in range(M + 1, N):\n        r_p_shape.append(in_shape[i])\n\n    b2s_out = np.reshape(data, newshape=r_shape)\n    b2s_out = np.transpose(b2s_out, axes=axis)\n    b2s_out = np.reshape(b2s_out, newshape=r_p_shape)\n\n    # Crop the start and end of dimensions of b2s_out\n    begin_idx = []\n    end_idx = []\n    strides = []\n\n    for i, _ in enumerate(r_p_shape):\n        strides.append(1)\n        if 0 < i <= M:\n            # begin and end index for spatial dimensions\n            begin_idx.append(crop_begin_list[i - 1])\n            end_idx.append(r_p_shape[i] - crop_end_list[i - 1])\n        else:\n            begin_idx.append(0)\n            end_idx.append(r_p_shape[i])\n\n    b2s_out = strided_slice_python(b2s_out, begin_idx, end_idx, strides)\n    return b2s_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Common utility for topi test\"\"\"\n\nimport numpy as np\nimport scipy.signal\n\nimport tvm\nfrom tvm import topi\nfrom tvm.testing import assert_allclose\n\n_injective_schedule = {\n    \"generic\": topi.generic.schedule_injective,\n    \"cpu\": topi.x86.schedule_injective,\n    \"arm_cpu\": topi.arm_cpu.schedule_injective,\n    \"gpu\": topi.cuda.schedule_injective,\n    \"hls\": topi.hls.schedule_injective,\n}\n\n_reduce_schedule = {\n    \"generic\": topi.generic.schedule_reduce,\n    \"cpu\": topi.x86.schedule_reduce,\n    \"gpu\": topi.cuda.schedule_reduce,\n    \"hls\": topi.cuda.schedule_reduce,\n}\n\n\ndef dispatch(target, dispatch_map):\n    if isinstance(target, str):\n        target = tvm.target.Target(target)\n    assert isinstance(target, tvm.target.Target)\n    for key in target.keys:\n        if key in dispatch_map:\n            return dispatch_map[key]\n    return dispatch_map[\"generic\"]\n\n\ndef get_injective_schedule(target):\n    return dispatch(target, _injective_schedule)\n\n\ndef get_reduce_schedule(target):\n    return dispatch(target, _reduce_schedule)\n\n\nget_broadcast_schedule = get_injective_schedule\nget_elemwise_schedule = get_injective_schedule\n\n_conv2d_nchw_implement = {\n    \"generic\": (topi.nn.conv2d_nchw, topi.generic.schedule_conv2d_nchw),\n    \"cpu\": (topi.x86.conv2d_nchw, topi.x86.schedule_conv2d_nchw),\n    \"arm_cpu\": (\n        topi.arm_cpu.conv2d_nchw_spatial_pack,\n        topi.arm_cpu.schedule_conv2d_nchw_spatial_pack,\n    ),\n    \"gpu\": (topi.cuda.conv2d_nchw, topi.cuda.schedule_conv2d_nchw),\n    \"mali\": (topi.mali.conv2d_nchw_spatial_pack, topi.mali.schedule_conv2d_nchw_spatial_pack),\n    \"bifrost\": (\n        topi.bifrost.conv2d_nchw_spatial_pack,\n        topi.bifrost.schedule_conv2d_nchw_spatial_pack,\n    ),\n    \"intel_graphics\": (topi.intel_graphics.conv2d_nchw, topi.intel_graphics.schedule_conv2d_nchw),\n    \"hls\": (topi.nn.conv2d_nchw, topi.hls.schedule_conv2d_nchw),\n}\n\n\ndef get_conv2d_nchw_implement(target):\n    return dispatch(target, _conv2d_nchw_implement)\n\n\ndef compare_numpy_tvm(inputs, output, target, device, compute, schedule):\n    \"\"\"Compare a numpy inputs and output of a function to the results of the TVM version.\n\n    Parameters\n    ----------\n    inputs : Sequence[numpy.nd.array]\n        List of input numpy arrays to pass to the function.\n    output : numpy.nd.array\n        Verified correct function output.\n    target : tvm.target.Target\n        Target to run on.\n    device : tvm.runtime.Device\n        Context to run on.\n    compute : callable\n        Topi compute function to test against.\n    schedule : callable\n        Topi scheduling function to test against.\n    \"\"\"\n    te_inputs = [tvm.te.placeholder(shape=i.shape, dtype=str(i.dtype)) for i in inputs]\n    te_out = tvm.nd.array(np.zeros(output.shape).astype(output.dtype), device=device)\n    with tvm.target.Target(target):\n        out = compute(*te_inputs)\n        s = schedule([out])\n        func = tvm.build(s, te_inputs + [out])\n        arys = [tvm.nd.array(x, device=device) for x in inputs]\n        func(*(arys + [te_out]))\n        assert_allclose(te_out.numpy(), output, atol=1e-4, rtol=1e-4)\n\n\ndef _convolve2d(data, weights):\n    \"\"\"2d convolution operator in HW layout.\n\n    This is intended to be used as a replacement for\n    scipy.signals.convolve2d, with wider support for different dtypes.\n    scipy.signal.convolve2d does not support all TVM-supported\n    dtypes (e.g. float16).  Where possible, this function uses\n    scipy.signal.convolve2d to take advantage of compiled scipy\n    routines, falling back to an explicit loop only where needed.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        2-D with shape [in_height, in_width]\n\n    weights : numpy.ndarray\n        2-D with shape [filter_height, filter_width].\n\n    Returns\n    -------\n    b_np : np.ndarray\n        2-D with shape [out_height, out_width]\n\n        Return value and layout conventions are matched to\n        ``scipy.signal.convolve2d(data, weights, mode=\"valid\")``\n    \"\"\"\n\n    try:\n        return scipy.signal.convolve2d(data, weights, mode=\"valid\")\n    except ValueError:\n        pass\n\n    weights = np.rot90(weights, k=2)\n\n    assert len(data.shape) == len(weights.shape) == 2\n\n    dtype = data.dtype\n    kernel_h, kernel_w = weights.shape\n\n    output_shape = [a_dim - w_dim + 1 for a_dim, w_dim in zip(data.shape, weights.shape)]\n    output = np.zeros(output_shape, dtype=dtype)\n\n    for y in range(output_shape[0]):\n        for x in range(output_shape[1]):\n            output[y][x] = np.sum(data[y : y + kernel_h, x : x + kernel_w] * weights)\n\n    return output\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv1d_ncw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable, invalid-name\n\"\"\"1D convolution in python\"\"\"\nimport numpy as np\nfrom tvm.topi.nn.utils import get_pad_tuple1d\n\n\ndef dilate_np(x, dilation):\n    \"\"\"1D dilation using numpy\n\n    Parameters\n    ----------\n    x : numpy.ndarray\n        Array to dilate with shape [batch, in_channel, in_width]\n\n    dilation : int\n        dilation rate of output\n\n    Returns\n    -------\n    out : numpy.ndarray\n        Dilated output with shape [batch, in_channel, (in_width - 1) * dilation + 1]\n    \"\"\"\n    irange = range(len(x) - 1)\n    for d in range(dilation - 1):\n        indices = [(d + 1) * (i + 1) for i in irange]\n        x = np.insert(x, indices, 0)\n    return x\n\n\ndef group_conv1d_ncw_python(a_np, w_np, stride, padding, dilation, groups):\n    \"Grouped version of `conv1d_ncw_python`, see that for documentation\"\n    a_slices = np.array_split(a_np, groups, axis=1)\n    w_slices = np.array_split(w_np, groups, axis=0)\n    b_slices = [\n        conv1d_ncw_python(a_slice, w_slice, stride, padding, dilation)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    return np.concatenate(b_slices, axis=1)\n\n\ndef conv1d_ncw_python(a_np, w_np, stride, padding, dilation):\n    \"\"\"1D convolution operator in NCW layout\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        3-D with shape [batch, in_channel, in_width]\n\n    w_np : numpy.ndarray\n        3-D with shape [num_filter, in_channel, filter_width]\n\n    stride : int\n        Stride size\n\n    padding : int, tuple, or str\n        Single int for padding size or tuple of (left, right) padding\n        or a string in ['VALID', 'SAME']\n\n    dilation : int\n        Dilation rate of the kernel\n\n    groups : int\n        Number of groups in the convolution\n\n    Returns\n    -------\n    b_np : numpy.ndarray\n        3-D with shape [batch, out_channel, out_width]\n    \"\"\"\n    batch, in_c, in_w = a_np.shape\n    out_c, _, filter_w = w_np.shape\n    if isinstance(stride, (tuple, list)):\n        stride = stride[0]\n    if isinstance(dilation, (tuple, list)):\n        dilation = dilation[0]\n\n    dilated_filter_w = (filter_w - 1) * dilation + 1\n    pad_left, pad_right = get_pad_tuple1d(padding, (dilated_filter_w,))\n    out_w = ((in_w - dilated_filter_w + pad_left + pad_right) // stride) + 1\n\n    padded_a_np = np.zeros((batch, in_c, in_w + pad_left + pad_right))\n    padded_a_np[:, :, pad_left : (in_w + pad_left)] = a_np\n\n    b_np = np.zeros((batch, out_c, out_w))\n    for n in range(batch):\n        for f in range(out_c):\n            for c in range(in_c):\n                out = np.convolve(\n                    padded_a_np[n, c], np.flip(dilate_np(w_np[f, c], dilation)), mode=\"valid\"\n                )\n                b_np[n, f] += out[::stride]\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv1d_transpose_ncw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable\n\"\"\"Transposed 1D convolution in python\"\"\"\nimport numpy as np\nimport scipy\nimport tvm.topi.testing\nfrom tvm.topi.nn.utils import get_pad_tuple1d\n\n\ndef conv1d_transpose_ncw_python(a_np, w_np, stride, padding, output_padding):\n    \"\"\"Transposed 1D convolution operator in NCW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        3-D with shape [batch, in_channel, in_width]\n\n    w_np : numpy.ndarray\n        3-D with shape [in_channel, num_filter, filter_width]\n\n    stride : int or a list/tuple of one int\n        Stride size, or [stride_width]\n\n    padding : int, tuple, or str\n        Single int for padding size, or\n        tuple of 2 ints for left and right padding, or\n        ['VALID', 'SAME']\n\n    output_padding : tuple\n        Used to recover the actual output shape in case more than one\n        is possible\n\n    Returns\n    -------\n    b_np : np.ndarray\n        3-D with shape [batch, out_channel, out_width]\n\n    \"\"\"\n    batch, in_c, in_w = a_np.shape\n    _, out_c, filter_w = w_np.shape\n    opad = output_padding[0]\n    if isinstance(stride, int):\n        stride_w = stride\n    else:\n        stride_w = stride[0]\n    assert opad < stride_w\n    fpad_left, fpad_right = get_pad_tuple1d(padding, filter_w)\n    # dilate stage\n    dilated_a_np = tvm.topi.testing.dilate_python(a_np, [1, 1, stride_w])\n    # padding stage\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad\n    padded_a_np = np.zeros((batch, in_c, dilated_a_np.shape[2] + bpad_left + bpad_right))\n    padded_a_np[:, :, bpad_left : dilated_a_np.shape[2] + bpad_left] = dilated_a_np\n    # convolution stage\n    out_w = (in_w - 1) * stride_w - fpad_left - fpad_right + filter_w + opad\n    b_np = np.zeros((batch, out_c, out_w))\n    for n in range(batch):\n        for f in range(out_c):\n            for c in range(in_c):\n                out = scipy.signal.convolve(padded_a_np[n, c], w_np[c, f], mode=\"valid\")\n                b_np[n, f] += out\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv2d_backcward_weight_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-nested-blocks\n\"\"\"Gradient of conv2d with respect to weight in python\"\"\"\nimport numpy as np\n\n\n# Reference: cutlass/tools/util/include/cutlass/util/reference/host/convolution.h\ndef conv2d_backward_weight_nchw_python(\n    dy_np, x_np, kernel_size, stride, padding, groups=1, channels=None\n):\n    \"\"\"Gradient of the conv2d op with respect to weight, in NCHW layout.\n\n    Parameters\n    ----------\n    dy_np : numpy.ndarray\n        4-D with shape [batch, in_channel, out_height, out_width]\n\n    x_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel_size : tuple of two ints\n        Height and width of the weight\n\n    stride : tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : tuple of two ints\n        Spatial padding, or [pad_h, pad_w]\n\n    Returns\n    -------\n    dw_np : np.ndarray\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    \"\"\"\n    N, C, H, W = x_np.shape\n    _, K, P, Q = dy_np.shape\n    R, S = kernel_size\n    pad_h, pad_w = padding\n    stride_h, stride_w = stride\n    is_depth_wise = C == K and C == groups\n\n    if is_depth_wise:\n        assert channels == groups, \"Only channel_mult == 1 supported for now.\"\n        dw = np.zeros((K, 1, R, S)).astype(dy_np.dtype)\n    else:\n        assert groups == 1, \"General grouped conv2d not supported for now.\"\n        dw = np.zeros((K, C, R, S)).astype(dy_np.dtype)\n\n    for k in range(K):\n        for r in range(R):\n            for s in range(S):\n                for c in range(dw.shape[1]):\n                    acc = 0\n                    for n in range(N):\n                        for p in range(P):\n                            for q in range(Q):\n                                if not is_depth_wise:\n                                    in_c = c\n                                else:\n                                    in_c = k\n\n                                coord = (\n                                    n,\n                                    in_c,\n                                    p * stride_h - pad_h + r,\n                                    q * stride_w - pad_w + s,\n                                )\n\n                                if (\n                                    coord[2] < H\n                                    and coord[2] >= 0\n                                    and coord[3] < W\n                                    and coord[3] >= 0\n                                ):\n                                    acc += dy_np[n, k, p, q] * x_np[coord]\n\n                    dw[k, c, r, s] = acc\n\n    return dw\n\n\ndef conv2d_backward_weight_python(\n    dy_np, x_np, kernel_size, stride, padding, layout=\"NCHW\", groups=1, channels=None\n):\n    \"\"\"Gradient of the conv2d op with respect to weight, in NCHW or NHWC layout.\n\n    Parameters\n    ----------\n    dy_np : numpy.ndarray\n        4-D with shape [batch, in_channel, out_height, out_width] for NCHW layout\n\n    x_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width] for NCHW layout\n\n    kernel_size : tuple of two ints\n        Height and width of the weight\n\n    stride : tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : tuple of two ints\n        Spatial padding, or [pad_h, pad_w]\n\n    layout: string\n        Layout of dy_np and x_np\n\n    groups: int\n        Number of groups for grouped convolution.\n\n    channels : int\n        Number of output channels of this convolution.\n\n    Returns\n    -------\n    dw_np : np.ndarray\n        Tensor of shape [num_filter, in_channel, filter_height, filter_width] for NCHW layout,\n        [num_filter, filter_height, filter_width, in_channel] for NHWC layout.\n    \"\"\"\n    if layout == \"NCHW\":\n        return conv2d_backward_weight_nchw_python(\n            dy_np, x_np, kernel_size, stride, padding, groups, channels\n        )\n\n    dw_np_oihw = conv2d_backward_weight_nchw_python(\n        np.transpose(dy_np, [0, 3, 1, 2]),\n        np.transpose(x_np, [0, 3, 1, 2]),\n        kernel_size,\n        stride,\n        padding,\n        groups,\n        channels,\n    )\n    return np.transpose(dw_np_oihw, [0, 2, 3, 1])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv2d_hwcn_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Convolution in python\"\"\"\nimport numpy as np\nimport scipy.signal\nfrom tvm.topi.nn.utils import get_pad_tuple\n\n\ndef conv2d_hwcn_python(a_np, w_np, stride, padding):\n    \"\"\"Convolution operator in HWCN layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [in_height, in_width, in_channel, batch]\n\n    w_np : numpy.ndarray\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [out_height, out_width, out_channel, batch]\n    \"\"\"\n    in_height, in_width, in_channel, batch = a_np.shape\n    kernel_h, kernel_w, _, num_filter = w_np.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n    # compute the output shape\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    # change the layout from HWCN to NCHW\n    at = a_np.transpose((3, 2, 0, 1))\n    wt = w_np.transpose((3, 2, 0, 1))\n    bt = np.zeros((batch, out_channel, out_height, out_width))\n    # computation\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_h > 0 or pad_w > 0:\n                    apad = np.zeros((in_height + pad_h, in_width + pad_w))\n                    apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = at[n, c]\n                else:\n                    apad = at[n, c]\n                out = scipy.signal.convolve2d(apad, np.rot90(np.rot90(wt[f, c])), mode=\"valid\")\n                bt[n, f] += out[::stride_h, ::stride_w]\n    return bt.transpose((2, 3, 1, 0))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv2d_nchw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals, too-many-branches\n\"\"\"Convolution in python\"\"\"\nimport numpy as np\nimport scipy\n\nfrom tvm.topi.nn.utils import get_pad_tuple\n\n\ndef _conv2d_nchw_python(a_np, w_np, stride, padding):\n    \"\"\"Convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    w_np : numpy.ndarray\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    batch, in_channel, in_height, in_width = a_np.shape\n    num_filter, _, kernel_h, kernel_w = w_np.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n    # compute the output shape\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    b_np = np.zeros((batch, out_channel, out_height, out_width), dtype=a_np.dtype)\n    # computation\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_h > 0 or pad_w > 0:\n                    apad = np.zeros((in_height + pad_h, in_width + pad_w), dtype=a_np.dtype)\n                    apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = a_np[n, c]\n                else:\n                    apad = a_np[n, c]\n\n                out = _conv2d_hw(apad, w_np[f, c])\n                b_np[n, f] += out[::stride_h, ::stride_w]\n    return b_np\n\n\ndef _conv2d_hw(apad, w_np_fc):\n    \"\"\"2d convolution operator in HW layout.\n\n    This is intended to be used as a subroutine from\n    _conv2d_nchw_python.  Using scipy.signal.convolve2d directly does\n    not work for all dtypes (e.g. float16).  Where possible, this\n    function uses scipy.signal.convolve2d to take advantage of\n    compiled scipy routines, falling back to an explicit loop only\n    where needed\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        2-D with shape [in_height, in_width]\n\n    w_np : numpy.ndarray\n        2-D with shape [filter_height, filter_width].\n\n    Returns\n    -------\n    b_np : np.ndarray\n        2-D with shape [out_height, out_width]\n    \"\"\"\n\n    try:\n        return scipy.signal.convolve2d(apad, np.rot90(np.rot90(w_np_fc)), mode=\"valid\")\n    except ValueError:\n        pass\n\n    assert len(apad.shape) == len(w_np_fc.shape) == 2\n\n    dtype = apad.dtype\n    in_height, in_width = apad.shape\n    kernel_h, kernel_w = w_np_fc.shape\n\n    output_shape = [a_dim - w_dim + 1 for a_dim, w_dim in zip(apad.shape, w_np_fc.shape)]\n    output = np.zeros(output_shape, dtype=apad.dtype)\n\n    for y in range(output_shape[0]):\n        for x in range(output_shape[1]):\n            output[y][x] = np.sum(apad[y : y + kernel_h, x : x + kernel_w] * w_np_fc)\n\n    return output\n\n\ndef conv2d_nchw_python(a_np, w_np, stride, padding, groups=1):\n    \"\"\"Convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    w_np : numpy.ndarray\n        4-D with shape [num_filter, in_channel // groups, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    a_slices = np.array_split(a_np, groups, axis=1)\n    w_slices = np.array_split(w_np, groups, axis=0)\n    b_slices = [\n        _conv2d_nchw_python(a_slice, w_slice, stride, padding)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    b_np = np.concatenate(b_slices, axis=1)\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv2d_nhwc_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Convolution in python\"\"\"\nimport numpy as np\nimport scipy.signal\nfrom tvm.topi.nn.utils import get_pad_tuple\n\n\ndef _conv2d_nhwc_python(a_np, w_np, stride, padding):\n    \"\"\"Convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    w_np : numpy.ndarray\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of two ints\n        Padding size, or ['VALID', 'SAME'], or [pad_height, pad_width]\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    batch, in_height, in_width, in_channel = a_np.shape\n    kernel_h, kernel_w, _, num_filter = w_np.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n\n    # compute the output shape\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    # change the layout from NHWC to NCHW\n    at = a_np.transpose((0, 3, 1, 2))\n    wt = w_np.transpose((3, 2, 0, 1))\n    bt = np.zeros((batch, out_channel, out_height, out_width))\n    # computation\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_h > 0 or pad_w > 0:\n                    apad = np.zeros((in_height + pad_h, in_width + pad_w))\n                    apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = at[n, c]\n                else:\n                    apad = at[n, c]\n                out = scipy.signal.convolve2d(apad, np.rot90(np.rot90(wt[f, c])), mode=\"valid\")\n                bt[n, f] += out[::stride_h, ::stride_w]\n    return bt.transpose((0, 2, 3, 1))\n\n\ndef conv2d_nhwc_python(a_np, w_np, stride, padding, groups=1):\n    \"\"\"Convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    w_np : numpy.ndarray\n        4-D with shape [filter_height, filter_width, in_channel // groups, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n\n    a_slices = np.array_split(a_np, groups, axis=3)\n    w_slices = np.array_split(w_np, groups, axis=3)\n    b_slices = [\n        _conv2d_nhwc_python(a_slice, w_slice, stride, padding)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    b_np = np.concatenate(b_slices, axis=3)\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv2d_transpose_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-variable\n\"\"\"Transposed convolution in python\"\"\"\nimport numpy as np\nimport scipy\nimport tvm.topi.testing\nfrom tvm.topi.nn.utils import get_pad_tuple\n\n\ndef _conv2d_transpose_nchw_python(a_np, w_np, stride, padding, output_padding):\n    \"\"\"Transposed convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    w_np : numpy.ndarray\n        4-D with shape [in_channel, num_filter, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    output_padding : int or a list/tuple of two ints\n        Use to disambiguate the output shape.\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    batch, in_c, in_h, in_w = a_np.shape\n    _, out_c, filter_h, filter_w = w_np.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n    if isinstance(output_padding, int):\n        opad_h = opad_w = output_padding\n    else:\n        opad_h, opad_w = output_padding\n    assert opad_h < stride_h and opad_w < stride_w\n    # dilate stage\n    dilated_a_np = tvm.topi.testing.dilate_python(a_np, [1, 1, stride_h, stride_w])\n    # padding stage\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w))\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom + opad_h\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad_w\n    padded_a_np = np.zeros(\n        (\n            batch,\n            in_c,\n            dilated_a_np.shape[2] + bpad_top + bpad_bottom,\n            dilated_a_np.shape[3] + bpad_left + bpad_right,\n        )\n    ).astype(a_np.dtype)\n    padded_a_np[\n        :,\n        :,\n        bpad_top : dilated_a_np.shape[2] + bpad_top,\n        bpad_left : dilated_a_np.shape[3] + bpad_left,\n    ] = dilated_a_np\n    # convolution stage\n    out_h = (in_h - 1) * stride_h - fpad_top - fpad_bottom + filter_h + opad_h\n    out_w = (in_w - 1) * stride_w - fpad_left - fpad_right + filter_w + opad_w\n    b_np = np.zeros((batch, out_c, out_h, out_w)).astype(a_np.dtype)\n    for n in range(batch):\n        for f in range(out_c):\n            for c in range(in_c):\n                out = scipy.signal.convolve2d(padded_a_np[n, c], w_np[c, f], mode=\"valid\")\n                b_np[n, f] += out\n    return b_np\n\n\ndef conv2d_transpose_nhwc_python(\n    a_nhwc, weight, weight_format, stride, padding, output_padding=(0, 0)\n):\n    \"\"\"Transposed convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    a_nhwc : numpy.ndarray\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    weight : numpy.ndarray\n        4-D in formats HWIO, HWOI, OIHW or IOHW\n\n    weight_format : str\n        ['HWIO', 'HWOI', 'OIHW', 'IOHW']\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    assert a_nhwc.ndim == 4, \"a_nhwc number of dimensions should be 4\"\n    assert weight.ndim == 4, \"weight number of dimensions should be 4\"\n\n    a_nchw = np.transpose(a_nhwc, (0, 3, 1, 2))\n\n    # conv2d_transpose_nchw_python needs kernel layout to be IOHW\n    if weight_format == \"HWIO\":\n        w_iohw = np.transpose(weight, (2, 3, 0, 1))\n    elif weight_format == \"HWOI\":\n        w_iohw = np.transpose(weight, (3, 2, 0, 1))\n    elif weight_format == \"OIHW\":\n        w_iohw = np.transpose(weight, (1, 0, 2, 3))\n    elif weight_format == \"IOHW\":\n        w_iohw = weight\n    else:\n        raise ValueError(\"Valid weight_formats are HWIO, HWOI, OIHW or IOHW\")\n\n    res_nchw = conv2d_transpose_nchw_python(\n        a_nchw, w_iohw, stride, padding, output_padding=output_padding\n    )\n    res_nhwc = np.transpose(res_nchw, (0, 2, 3, 1))\n    return res_nhwc\n\n\ndef conv2d_transpose_nchw_python(a_np, w_np, stride, padding, output_padding, groups=1):\n    \"\"\"Convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    w_np : numpy.ndarray\n        4-D with shape [in_channel, num_filter // groups, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str\n        Padding size, or ['VALID', 'SAME']\n\n    output_padding : int or a list/tuple of two ints\n        Use to disambiguate the output shape.\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    a_slices = np.array_split(a_np, groups, axis=1)\n    w_slices = np.array_split(w_np, groups, axis=0)\n    b_slices = [\n        _conv2d_transpose_nchw_python(a_slice, w_slice, stride, padding, output_padding)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    b_np = np.concatenate(b_slices, axis=1)\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv3d_ncdhw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals, too-many-branches\n\"\"\"Convolution 3D in python\"\"\"\nimport numpy as np\nimport scipy.signal\nfrom tvm.topi.nn.utils import get_pad_tuple3d\n\n\ndef _conv3d_ncdhw_python(a_np, w_np, stride, padding):\n    batch, in_channel, in_depth, in_height, in_width = a_np.shape\n    num_filter, _, kernel_d, kernel_h, kernel_w = w_np.shape\n    if isinstance(stride, int):\n        stride_d = stride_h = stride_w = stride\n    else:\n        stride_d, stride_h, stride_w = stride\n\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(\n        padding, (kernel_d, kernel_h, kernel_w)\n    )\n    pad_d = pad_front + pad_back\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n\n    # compute the output shape\n    out_channel = num_filter\n    out_depth = (in_depth - kernel_d + pad_d) // stride_d + 1\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    b_np = np.zeros((batch, out_channel, out_depth, out_height, out_width))\n    # computation\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_d > 0 or pad_h > 0 or pad_w > 0:\n                    apad = np.zeros((in_depth + pad_d, in_height + pad_h, in_width + pad_w))\n                    apad[\n                        pad_front : pad_front + in_depth,\n                        pad_top : pad_top + in_height,\n                        pad_left : pad_left + in_width,\n                    ] = a_np[n, c]\n                else:\n                    apad = a_np[n, c]\n                out = scipy.signal.convolve(apad, np.flip(w_np[f, c]), mode=\"valid\")\n                b_np[n, f] += out[::stride_d, ::stride_h, ::stride_w]\n    return b_np\n\n\ndef conv3d_ncdhw_python(a_np, w_np, stride, padding, groups=1):\n    \"\"\"Convolution operator in NCDHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    w_np : numpy.ndarray\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str or a list/tuple of three ints\n        Padding size, or ['VALID', 'SAME'], or [pad_depth, pad_height, pad_width]\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    a_slices = np.array_split(a_np, groups, axis=1)\n    w_slices = np.array_split(w_np, groups, axis=0)\n    b_slices = [\n        _conv3d_ncdhw_python(a_slice, w_slice, stride, padding)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    b_np = np.concatenate(b_slices, axis=1)\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv3d_ndhwc_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Convolution 3D in python\"\"\"\nimport numpy as np\nimport scipy.signal\nfrom tvm.topi.nn.utils import get_pad_tuple3d\n\n\ndef _conv3d_ndhwc_python(a_np, w_np, stride, padding):\n    \"\"\"Convolution 3D operator in NDHWC layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    w_np : numpy.ndarray\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str or a list/tuple of three ints\n        Padding size, or ['VALID', 'SAME'], or [pad_depth, pad_height, pad_width]\n\n    Returns\n    -------\n    b_np : np.ndarray\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    batch, in_depth, in_height, in_width, in_channel = a_np.shape\n    kernel_d, kernel_h, kernel_w, _, num_filter = w_np.shape\n    if isinstance(stride, int):\n        stride_d = stride_h = stride_w = stride\n    else:\n        stride_d, stride_h, stride_w = stride\n\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(\n        padding, (kernel_d, kernel_h, kernel_w)\n    )\n    pad_d = pad_front + pad_back\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n    # compute the output shape\n    out_channel = num_filter\n    out_depth = (in_depth - kernel_d + pad_d) // stride_d + 1\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    # change the layout from NHWC to NCHW\n    at = a_np.transpose((0, 4, 1, 2, 3))\n    wt = w_np.transpose((4, 3, 0, 1, 2))\n    bt = np.zeros((batch, out_channel, out_depth, out_height, out_width), dtype=a_np.dtype)\n    # computation\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_d > 0 or pad_h > 0 or pad_w > 0:\n                    apad = np.zeros(\n                        (in_depth + pad_d, in_height + pad_h, in_width + pad_w), dtype=a_np.dtype\n                    )\n                    apad[\n                        pad_front : pad_front + in_depth,\n                        pad_top : pad_top + in_height,\n                        pad_left : pad_left + in_width,\n                    ] = at[n, c]\n                else:\n                    apad = at[n, c]\n                out = scipy.signal.convolve(apad, np.flip(wt[f, c]), mode=\"valid\")\n                bt[n, f] += out[::stride_d, ::stride_h, ::stride_w]\n    return bt.transpose((0, 2, 3, 4, 1))\n\n\ndef conv3d_ndhwc_python(a_np, w_np, stride, padding, groups=1):\n    \"\"\"Convolution 3D operator in NDHWC layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    w_np : numpy.ndarray\n        5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]\n\n    stride : int or a list/tuple of three ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str or a list/tuple of three ints\n        Padding size, or ['VALID', 'SAME'], or [pad_depth, pad_height, pad_width]\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    a_slices = np.array_split(a_np, groups, axis=4)\n    w_slices = np.array_split(w_np, groups, axis=4)\n    b_slices = [\n        _conv3d_ndhwc_python(a_slice, w_slice, stride, padding)\n        for a_slice, w_slice in zip(a_slices, w_slices)\n    ]\n    b_np = np.concatenate(b_slices, axis=4)\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/conv3d_transpose_ncdhw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals, too-many-branches\n\"\"\"Convolution 3D transpose in python\"\"\"\nimport numpy as np\nimport tvm.topi.testing\nfrom tvm.topi.nn.utils import get_pad_tuple3d\n\n\ndef conv3d_transpose_ncdhw_python(a_np, w_np, stride, padding, output_padding):\n    \"\"\"Transposed 3d convolution operator in NCDHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        5-D with shape [batch, in_channel, in_depth, in_height, in_width]\n\n    w_np : numpy.ndarray\n        5-D with shape [in_channel, num_filter, filter_depth, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or str\n        Padding size\n\n    output_padding : int or list/tuple of three ints\n        Used to disambiguate output shape.\n\n    Returns\n    -------\n    b_np : np.ndarray\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width]\n    \"\"\"\n    batch, in_c, in_d, in_h, in_w = a_np.shape\n    _, out_c, filter_d, filter_h, filter_w = w_np.shape\n    if isinstance(stride, int):\n        stride_d = stride_h = stride_w = stride\n    else:\n        stride_d, stride_h, stride_w = stride\n    if isinstance(output_padding, int):\n        opad_d = opad_h = opad_w = output_padding\n    else:\n        opad_d, opad_h, opad_w = output_padding\n    assert opad_d < stride_d and opad_h < stride_h and opad_w < stride_w\n\n    # dilate stage\n    dilated_a_np = tvm.topi.testing.dilate_python(a_np, [1, 1, stride_d, stride_h, stride_w])\n\n    # padding stage\n    fpad_front, fpad_top, fpad_left, fpad_back, fpad_bottom, fpad_right = get_pad_tuple3d(\n        padding, (filter_d, filter_h, filter_w)\n    )\n\n    bpad_front = filter_d - 1 - fpad_front\n    bpad_back = filter_d - 1 - fpad_back + opad_d\n    bpad_top = filter_h - 1 - fpad_top\n    bpad_bottom = filter_h - 1 - fpad_bottom + opad_h\n    bpad_left = filter_w - 1 - fpad_left\n    bpad_right = filter_w - 1 - fpad_right + opad_w\n\n    padded_a_np = np.zeros(\n        (\n            batch,\n            in_c,\n            dilated_a_np.shape[2] + bpad_front + bpad_back,\n            dilated_a_np.shape[3] + bpad_top + bpad_bottom,\n            dilated_a_np.shape[4] + bpad_left + bpad_right,\n        )\n    )\n\n    padded_a_np[\n        :,\n        :,\n        bpad_front : dilated_a_np.shape[2] + bpad_front,\n        bpad_top : dilated_a_np.shape[3] + bpad_top,\n        bpad_left : dilated_a_np.shape[4] + bpad_left,\n    ] = dilated_a_np\n\n    # convolution stage\n    out_d = (in_d - 1) * stride_d - bpad_front - bpad_back + filter_d\n    out_h = (in_h - 1) * stride_h - fpad_top - fpad_bottom + filter_h\n    out_w = (in_w - 1) * stride_w - fpad_left - fpad_right + filter_w\n\n    w_np = np.flip(w_np, axis=[2, 3, 4]).transpose((1, 0, 2, 3, 4))\n    b_np = tvm.topi.testing.conv3d_ncdhw_python(\n        padded_a_np, w_np, stride=(1, 1, 1), padding=(0, 0, 0)\n    )\n\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/correlation_nchw_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Convolution 3D in python\"\"\"\nimport numpy as np\n\n\ndef correlation_nchw_python(\n    data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply\n):\n    \"\"\"Correlationn operator in NCHW layout.\n\n    Parameters\n    ----------\n    data1_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    data2_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    kernel_size: int\n        Kernel size for correlation, must be an odd number\n\n    max_displacement: int\n        Max displacement of Correlation\n\n    stride1: int\n        Stride for data1\n\n    stride2: int\n        Stride for data2 within the neightborhood centered around data1\n\n    padding: int\n        Padding for correlation\n\n    is_multiply: bool\n        operation type is either multiplication or substraction\n\n    Returns\n    -------\n    c_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    # compute output's dimension\n    pad_data_height = data1.shape[2] + 2 * padding\n    pad_data_width = data1.shape[3] + 2 * padding\n    kernel_radius = (kernel_size - 1) // 2\n    border_size = max_displacement + kernel_radius\n    out_width = (pad_data_width - border_size * 2) // stride1\n    out_height = (pad_data_height - border_size * 2) // stride1\n    neighborhood_grid_radius = max_displacement // stride2\n    neighborhood_grid_width = neighborhood_grid_radius * 2 + 1\n    out_channel = neighborhood_grid_width * neighborhood_grid_width\n\n    out = np.zeros((data1.shape[0], out_channel, out_height, out_width))\n    pad_data1 = np.zeros((data1.shape[0], data1.shape[1], pad_data_height, pad_data_width))\n    pad_data2 = np.zeros((data1.shape[0], data1.shape[1], pad_data_height, pad_data_width))\n\n    pad_data1[:, :, padding : padding + data1.shape[2], padding : padding + data1.shape[3]] = data1[\n        :, :, :, :\n    ]\n    pad_data2[:, :, padding : padding + data2.shape[2], padding : padding + data2.shape[3]] = data2[\n        :, :, :, :\n    ]\n\n    if is_multiply:\n        corr_func = lambda x, y: x * y\n    else:\n        corr_func = lambda x, y: abs(x - y)\n\n    # pylint: disable=too-many-nested-blocks\n    for i in range(out_height):\n        for j in range(out_width):\n            for nbatch in range(data1.shape[0]):\n                # x1,y1 is the location in data1 , i,j is the location in output\n                x1 = j * stride1 + max_displacement\n                y1 = i * stride1 + max_displacement\n\n                for q in range(out_channel):\n                    # location in data2\n                    x2 = x1 + (q % neighborhood_grid_width - neighborhood_grid_radius) * stride2\n                    y2 = y1 + (q // neighborhood_grid_width - neighborhood_grid_radius) * stride2\n\n                    for h in range(kernel_size):\n                        for w in range(kernel_size):\n                            for channel in range(data1.shape[1]):\n                                out[nbatch, q, i, j] += corr_func(\n                                    pad_data1[nbatch, channel, y1 + h, x1 + w],\n                                    pad_data2[nbatch, channel, y2 + h, x2 + w],\n                                )\n\n    out /= float(kernel_size**2 * data1.shape[1])\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/crop_and_resize_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals, too-many-nested-blocks\n\"\"\"crop and resize in python\"\"\"\nimport math\nimport numpy as np\n\n\ndef crop_and_resize_python(\n    image, boxes, box_indices, crop_size, layout, method=\"bilinear\", extrapolation_value=0\n):\n    \"\"\"Crop and resize using python\"\"\"\n    (target_h, target_w) = crop_size\n\n    if layout == \"NHWC\":\n        batch = boxes.shape[0]\n        image_height, image_width, channel = image.shape[1], image.shape[2], image.shape[3]\n        scaled_image = np.ones((batch, target_h, target_w, channel))\n    else:\n        batch = boxes.shape[0]\n        channel, image_height, image_width = image.shape[1], image.shape[2], image.shape[3]\n        scaled_image = np.ones((batch, channel, target_h, target_w))\n\n    for n, box in enumerate(boxes):\n        b_in = box_indices[n]\n        y1, x1 = boxes[n][0], boxes[n][1]\n        y2, x2 = boxes[n][2], boxes[n][3]\n\n        in_h = (image_height - 1) * (y2 - y1)\n        in_w = (image_width - 1) * (x2 - x1)\n        h_scale = np.float32(in_h) / np.float32(target_h - 1)\n        w_scale = np.float32(in_w) / np.float32(target_w - 1)\n\n        for y in range(target_h):\n\n            in_y = y1 * (image_height - 1) + h_scale * y\n\n            if in_y < 0 or in_y > image_height - 1:\n                for x in range(target_w):\n                    for d in range(channel):\n                        if layout == \"NHWC\":\n                            scaled_image[n][y][x][d] = extrapolation_value\n                        else:\n                            scaled_image[n][d][y][x] = extrapolation_value\n                continue\n\n            if method == \"bilinear\":\n                top_y_index = math.floor(in_y)\n                bottom_y_index = math.ceil(in_y)\n                y_lerp = in_y - top_y_index\n\n                for x in range(target_w):\n                    in_x = x1 * (image_width - 1) + x * w_scale\n                    if in_x < 0 or in_x > image_width - 1:\n                        for d in range(channel):\n                            if layout == \"NHWC\":\n                                scaled_image[n][y][x][d] = extrapolation_value\n                            else:\n                                scaled_image[n][d][y][x] = extrapolation_value\n                        continue\n\n                    left_x_index = math.floor(in_x)\n                    right_x_index = math.ceil(in_x)\n                    x_lerp = in_x - left_x_index\n\n                    for d in range(channel):\n                        if layout == \"NHWC\":\n                            top_left = image[b_in][top_y_index][left_x_index][d]\n                            top_right = image[b_in][top_y_index][right_x_index][d]\n                            bottom_left = image[b_in][bottom_y_index][left_x_index][d]\n                            bottom_right = image[b_in][bottom_y_index][right_x_index][d]\n                            top = top_left + (top_right - top_left) * x_lerp\n                            bottom = bottom_left + (bottom_right - bottom_left) * x_lerp\n                            scaled_image[n][y][x][d] = top + (bottom - top) * y_lerp\n                        else:\n                            top_left = image[b_in][d][top_y_index][left_x_index]\n                            top_right = image[b_in][d][top_y_index][right_x_index]\n                            bottom_left = image[b_in][d][bottom_y_index][left_x_index]\n                            bottom_right = image[b_in][d][bottom_y_index][right_x_index]\n                            top = top_left + (top_right - top_left) * x_lerp\n                            bottom = bottom_left + (bottom_right - bottom_left) * x_lerp\n                            scaled_image[n][d][y][x] = top + (bottom - top) * y_lerp\n\n            elif method == \"nearest_neighbor\":\n                for x in range(target_w):\n                    in_x = x1 * (image_width - 1) + x * w_scale\n                    if in_x < 0 or in_x > image_width - 1:\n                        for d in range(channel):\n                            if layout == \"NHWC\":\n                                scaled_image[n][y][x][d] = extrapolation_value\n                            else:\n                                scaled_image[n][d][y][x] = extrapolation_value\n                        continue\n                    closest_x_index = np.round(in_x).astype(\"int32\")\n                    closest_y_index = np.round(in_y).astype(\"int32\")\n                    for d in range(channel):\n                        if layout == \"NHWC\":\n                            scaled_image[n][y][x][d] = image[b_in][closest_y_index][\n                                closest_x_index\n                            ][d]\n                        else:\n                            scaled_image[n][d][y][x] = image[b_in][d][closest_y_index][\n                                closest_x_index\n                            ]\n\n    return scaled_image\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/deformable_conv2d_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Deformable convolution in python\"\"\"\nimport itertools\nimport math\nimport numpy as np\nfrom tvm.topi.nn.utils import get_pad_tuple\n\n\ndef deformable_conv2d_nchw_python(\n    a_np, offset_np, w_np, stride, padding, dilation, deformable_groups, groups\n):\n    \"\"\"Deformable convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    offset_np : numpy.ndarray\n        4-D with shape [batch, deformable_groups * filter_height * filter_width * 2,\n                        out_height, out_width]\n\n    w_np : numpy.ndarray\n        4-D with shape [num_filter, in_channel, filter_height, filter_width]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    dilation : int or a list/tuple of two ints\n        Dilation size, or [dilate_height, dilate_width]\n\n    deformable_groups : int\n        Number of deformable groups\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    batch, in_channel, in_height, in_width = a_np.shape\n    out_channel, _, kernel_h, kernel_w = w_np.shape\n    out_height, out_width = offset_np.shape[-2:]\n    dtype = a_np.dtype\n    ic_per_dgroup = in_channel // deformable_groups\n    assert groups == 1, \"deformable_conv2d_nchw_python does not support groups > 1\"\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, _, _ = get_pad_tuple(padding, (kernel_h, kernel_w))\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    def _bilinear(n, c, h, w):\n        y_low = int(math.floor(h))\n        x_low = int(math.floor(w))\n        y_high = y_low + 1\n        x_high = x_low + 1\n\n        wy_h = h - y_low\n        wx_h = w - x_low\n        wy_l = 1 - wy_h\n        wx_l = 1 - wx_h\n\n        val = 0\n        for wx, xp in zip((wx_l, wx_h), (x_low, x_high)):\n            for wy, yp in zip((wy_l, wy_h), (y_low, y_high)):\n                if 0 <= yp < in_height and 0 <= xp < in_width:\n                    val += wx * wy * a_np[n, c, yp, xp]\n        return val\n\n    a_deform = np.zeros((batch, in_channel, out_height, out_width, kernel_h, kernel_w), dtype=dtype)\n    for n, h, w in itertools.product(range(batch), range(out_height), range(out_width)):\n        offset = offset_np[n, :, h, w].reshape(deformable_groups, kernel_h, kernel_w, 2)\n        in_h = h * stride_h - pad_top\n        in_w = w * stride_w - pad_left\n\n        index_h_base, index_w_base = np.meshgrid(\n            np.arange(in_h, in_h + kernel_h * dilation_h, dilation_h, dtype=offset_np.dtype),\n            np.arange(in_w, in_w + kernel_w * dilation_w, dilation_w, dtype=offset_np.dtype),\n            indexing=\"ij\",\n        )\n\n        for c, kh, kw in itertools.product(range(in_channel), range(kernel_h), range(kernel_w)):\n            dg = c // ic_per_dgroup\n            index_h = index_h_base + offset[dg, ..., 0]\n            index_w = index_w_base + offset[dg, ..., 1]\n\n            y, x = index_h[kh, kw], index_w[kh, kw]\n            if y < 0 or y >= in_height or x < 0 or x >= in_width:\n                continue\n            a_deform[n, c, h, w, kh, kw] = _bilinear(n, c, y, x)\n\n    b_np = np.zeros((batch, out_channel, out_height, out_width), dtype=dtype)\n    for n, c, f, h, w in itertools.product(\n        range(batch), range(in_channel), range(out_channel), range(out_height), range(out_width)\n    ):\n        b_np[n, f, h, w] += np.tensordot(a_deform[n, c, h, w], w_np[f, c])\n\n    return b_np\n\n\ndef deformable_conv2d_nhwc_python(\n    a_np, offset_np, w_np, stride, padding, dilation, deformable_groups, groups\n):\n    \"\"\"Deformable convolution operator in NHWC layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    offset_np : numpy.ndarray\n        4-D with shape [batch, out_height, out_width,\n                        deformable_groups * filter_height * filter_width * 2]\n\n    w_np : numpy.ndarray\n        4-D with shape [filter_height, filter_width, in_channel, num_filter]\n\n    stride : int or a list/tuple of two ints\n        Stride size, or [stride_height, stride_width]\n\n    padding : int or str or a list/tuple of 2 or 4 ints\n        Padding size, or ['VALID', 'SAME'], or\n        [pad_height, pad_width] for 2 ints, or\n        [pad_top, pad_left, pad_bottom, pad_right] for 2 ints\n\n    dilation : int or a list/tuple of two ints\n        Dilation size, or [dilate_height, dilate_width]\n\n    deformable_groups : int\n        Number of deformable groups\n\n    groups : int\n        Number of groups\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    a_np = np.transpose(a_np, [0, 3, 1, 2])  # NHWC -> NCHW\n    offset_np = np.transpose(offset_np, [0, 3, 1, 2])  # NHWC -> NCHW\n    w_np = np.transpose(w_np, [3, 2, 0, 1])  # HWIO -> OIHW\n    b_np = deformable_conv2d_nchw_python(\n        a_np, offset_np, w_np, stride, padding, dilation, deformable_groups, groups\n    )\n    b_np = np.transpose(b_np, [0, 2, 3, 1])  # NCHW -> NHWC\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Dense in python\"\"\"\nimport numpy as np\n\n\ndef dense(x, y, bias, use_bias=False, use_relu=False, out_dtype=None):\n    \"\"\"dense operator implemented in numpy.\n\n    Parameters\n    ----------\n    x : numpy.ndarray\n        2-D with shape [M, K]\n\n    y : numpy.ndarray\n        2-D with shape [N, K]\n\n    bias: numpy.ndarray\n        1-D with shape [M,]\n\n    out_dtype: string, optional\n        Specify the dtype of output\n\n    Returns\n    -------\n    out : numpy.ndarray\n        2-D with shape [M, N]\n    \"\"\"\n    dtype = x.dtype if out_dtype is None else out_dtype\n    if use_bias:\n        out = np.dot(x.astype(dtype), y.T.astype(dtype)) + bias\n    else:\n        out = np.dot(x.astype(dtype), y.T.astype(dtype))\n\n    if use_relu:\n        out = np.maximum(out, 0)\n\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Depth to space in python\"\"\"\nimport numpy as np\n\n\ndef depth_to_space_python(data, block_size, mode=\"DCR\"):\n    \"\"\"Depth to Space operator in python for NCHW layout.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    block_size : int\n        Size of blocks to convert channel pixels into.\n\n    Returns\n    -------\n    d2s_out : np.ndarray\n        4-D with shape [batch, in_channel / (block_size * block_size),\n                        out_height * block_size, out_width * block_size]\n    \"\"\"\n    in_n, in_c, in_h, in_w = data.shape\n    new_h = int(in_h * block_size)\n    new_w = int(in_h * block_size)\n    new_c = int(in_c / (block_size * block_size))\n\n    if mode == \"DCR\":\n        expanded = np.reshape(data, newshape=[in_n, block_size, block_size, new_c, in_h, in_w])\n        transposed = np.transpose(expanded, axes=[0, 3, 4, 1, 5, 2])\n    else:\n        expanded = np.reshape(data, newshape=(in_n, new_c, block_size, block_size, in_h, in_w))\n        transposed = np.transpose(expanded, axes=(0, 1, 4, 2, 5, 3))\n    newshape = [in_n, new_c, new_h, new_w]\n    d2s_out = np.reshape(transposed, newshape=newshape)\n    return d2s_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/depthwise_conv2d_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, line-too-long\n\"\"\"Depthwise convolution in python\"\"\"\nimport numpy as np\n\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom .common import _convolve2d\n\n\ndef depthwise_conv2d_python_nchw(input_np, filter_np, stride, padding):\n    \"\"\"Depthwise convolution operator in NCHW layout.\n\n    Parameters\n    ----------\n    input_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    filter_np : numpy.ndarray\n        4-D with shape [in_channel, channel_multiplier, filter_height, filter_width]\n\n    stride : list / tuple of 2 ints\n        [stride_height, stride_width]\n\n    padding : str\n        'VALID' or 'SAME'\n\n    Returns\n    -------\n    output_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    batch, in_channel, in_height, in_width = input_np.shape\n    _, channel_multiplier, filter_height, filter_width = filter_np.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (filter_height, filter_width))\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n\n    out_channel = in_channel * channel_multiplier\n    out_height = (in_height - filter_height + pad_h) // stride_h + 1\n    out_width = (in_width - filter_width + pad_w) // stride_w + 1\n    output_np = np.zeros((batch, out_channel, out_height, out_width))\n\n    for i in range(batch):\n        for j in range(out_channel):\n            apad = input_np[i, j // channel_multiplier, :, :]\n            if pad_h or pad_w:\n                apad = np.pad(apad, [(pad_top, pad_bottom), (pad_left, pad_right)])\n\n            conv = _convolve2d(\n                apad,\n                np.rot90(filter_np[j // channel_multiplier, j % channel_multiplier, :, :], k=2),\n            )\n            output_np[i, j, :, :] = conv[\n                ::stride_h,\n                ::stride_w,\n            ]\n\n    return output_np\n\n\ndef depthwise_conv2d_python_nchwc(input_np, filter_np, stride, padding):\n    \"\"\"Depthwise convolution operator in NCHWc layout.\n\n    Parameters\n    ----------\n    input_np : numpy.ndarray\n        5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block]\n\n    filter_np : numpy.ndarray\n        6-D with shape [out_channel_chunk, channel_multiplier_chunk,\n                        filter_height, filter_width,\n                        channel_multiplier_block, out_channel_block]\n\n    stride : list / tuple of 2 ints\n        [stride_height, stride_width]\n\n    padding : str\n        'VALID' or 'SAME'\n\n    Returns\n    -------\n    output_np : np.ndarray\n        5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block]\n    \"\"\"\n    # Transform to NCHW\n    batch_size, in_channel_chunk, in_height, in_width, in_channel_block = input_np.shape\n    input_nchw = input_np.transpose(0, 1, 4, 2, 3).reshape(\n        (batch_size, in_channel_chunk * in_channel_block, in_height, in_width)\n    )\n\n    (\n        out_channel_chunk,\n        channel_multiplier_chunk,\n        filter_height,\n        filter_width,\n        channel_multiplier_block,\n        out_channel_block,\n    ) = filter_np.shape\n    filter_nchw = filter_np.transpose(0, 5, 1, 4, 2, 3).reshape(\n        (\n            out_channel_chunk * out_channel_block,\n            channel_multiplier_chunk * channel_multiplier_block,\n            filter_height,\n            filter_width,\n        )\n    )\n\n    # Perform conv2d\n    output_np = depthwise_conv2d_python_nchw(input_nchw, filter_nchw, stride, padding)\n\n    # Transform back to NCHWc\n\n    # pylint: disable=unpacking-non-sequence\n    batch_size, out_channel, out_height, out_width = output_np.shape\n    return output_np.reshape(\n        (batch_size, out_channel_chunk, out_channel_block, out_height, out_width)\n    ).transpose(0, 1, 3, 4, 2)\n\n\ndef depthwise_conv2d_python_nhwc(input_np, filter_np, stride, padding):\n    \"\"\"Depthwise convolution operator in nhwc layout.\n\n    Parameters\n    ----------\n    input_np : numpy.ndarray\n        4-D with shape [batch, in_height, in_width, in_channel]\n\n    filter_np : numpy.ndarray\n        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]\n\n    stride : list / tuple of 2 ints\n        [stride_height, stride_width]\n\n    padding : str\n        'VALID' or 'SAME'\n\n    Returns\n    -------\n    output_np : np.ndarray\n        4-D with shape [batch, out_height, out_width, out_channel]\n    \"\"\"\n    input_nchw = input_np.transpose(0, 3, 1, 2)\n    filter_nchw = filter_np.transpose(2, 3, 0, 1)\n    output_nchw = depthwise_conv2d_python_nchw(input_nchw, filter_nchw, stride, padding)\n    return output_nchw.transpose(0, 2, 3, 1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/dilate_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Dilate operation in python\"\"\"\nimport numpy as np\n\n\ndef dilate_python(input_np, strides, dilation_value=0.0, out_dtype=None):\n    \"\"\"Dilate operation.\n\n    Parameters\n    ----------\n    input_np : numpy.ndarray\n        n-D, can be any layout.\n\n    strides : list / tuple of n ints\n        Dilation stride on each dimension, 1 means no dilation.\n\n    dilation_value : int/float, optional\n        Value used to dilate the input.\n\n    out_dtype : Option[str]\n        The datatype of the dilated array.  If unspecified, will use\n        the same dtype as the input array.\n\n    Returns\n    -------\n    output_np : numpy.ndarray\n        n-D, the same layout as Input.\n\n    \"\"\"\n    assert len(input_np.shape) == len(\n        strides\n    ), \"Input dimension and strides size dismatch : %d vs %d\" % (\n        len(input_np.shape),\n        len(strides),\n    )\n\n    if out_dtype is None:\n        out_dtype = input_np.dtype\n\n    output_size = [\n        (input_dim - 1) * stride + 1 for input_dim, stride in zip(input_np.shape, strides)\n    ]\n    non_zero_elements = np.ix_(\n        *[range(0, output_dim, stride) for output_dim, stride in zip(output_size, strides)]\n    )\n\n    output_np = np.full(shape=output_size, fill_value=dilation_value, dtype=out_dtype)\n    output_np[non_zero_elements] = input_np\n\n    return output_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/gather_nd_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"gather_nd in python\"\"\"\nimport numpy as np\n\n\ndef gather_nd_python(a_np, indices_np):\n    \"\"\"Python version of GatherND operator\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        Numpy array\n\n    indices_np : numpy.ndarray\n        Numpy array\n\n    Returns\n    -------\n    b_np : numpy.ndarray\n        Numpy array\n    \"\"\"\n    a_shape = a_np.shape\n    indices_np = indices_np.astype(\"int32\")\n    indices_shape = indices_np.shape\n    assert len(indices_shape) > 1\n    assert indices_shape[0] <= len(a_shape)\n    b_shape = list(indices_shape[1:])\n    for i in range(indices_shape[0], len(a_shape)):\n        b_shape.append(a_shape[i])\n    b_np = np.zeros(b_shape)\n    for idx in np.ndindex(*indices_shape[1:]):\n        a_idx = []\n        for i in range(indices_shape[0]):\n            indices_pos = tuple([i] + list(idx))\n            a_idx.append(indices_np[indices_pos])\n        b_np[idx] = a_np[tuple(a_idx)]\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/gather_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"gather in python\"\"\"\nimport numpy as np\n\n\ndef gather_python(data, axis, indices):\n    \"\"\"Python version of Gather operator\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        Numpy array\n\n    axis: int\n        integer\n\n    indices : numpy.ndarray\n        Numpy array\n\n    Returns\n    -------\n    b_np : numpy.ndarray\n        Numpy array\n    \"\"\"\n    shape_indices = indices.shape\n    out = np.zeros(shape_indices, dtype=data.dtype)\n    for index in np.ndindex(*shape_indices):\n        new_index = list(index)\n        new_index[axis] = indices[index]\n        out[index] = data[tuple(new_index)]\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/grid_sample_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"affine_grid and grid_sample operators in python\"\"\"\nimport math\nimport numpy as np\n\n\ndef affine_grid_python(data, target_shape):\n    yv, xv = np.meshgrid(np.arange(target_shape[0]), np.arange(target_shape[1]))\n    yv = yv.T * 2 / (target_shape[0] - 1) - 1\n    xv = xv.T * 2 / (target_shape[1] - 1) - 1\n    ones = np.ones_like(xv)\n    grid = np.stack([xv, yv, ones]).reshape(3, -1)\n    return data.reshape(-1, 3).dot(grid).reshape(data.shape[0], 2, *target_shape)\n\n\ndef grid_sample_2d(\n    data: np.ndarray,\n    grid: np.ndarray,\n    method=\"bilinear\",\n    layout=\"NCHW\",\n    padding_mode=\"zeros\",\n    align_corners=True,\n):\n    r\"\"\"grid_sample_2d for NCHW layout\"\"\"\n\n    assert method in (\"bilinear\", \"nearest\", \"bicubic\"), f\"{method} is not supported\"\n    assert layout == \"NCHW\"\n    assert padding_mode in (\"zeros\", \"border\", \"reflection\"), f\"{padding_mode} is not supported\"\n    assert len(data.shape) == len(grid.shape) == 4\n\n    batch, channel = data.shape[:2]\n    in_height, in_width = data.shape[2:]\n    out_height, out_width = grid.shape[2:]\n    out_shape = [batch, channel, out_height, out_width]\n    out = np.zeros(out_shape)\n\n    def _get_pixel(b, c, h, w):\n        if 0 <= h <= in_height - 1 and 0 <= w <= in_width - 1:\n            return data[b, c, h, w]\n        return 0\n\n    def _unnormalize(h, w):\n        if align_corners:\n            new_h = (h + 1) * (in_height - 1) / 2\n            new_w = (w + 1) * (in_width - 1) / 2\n        else:\n            new_h = -0.5 + (h + 1) * in_height / 2\n            new_w = -0.5 + (w + 1) * in_width / 2\n        return (new_h, new_w)\n\n    def _clip_coordinates(x, size):\n        return min(max(x, 0), size - 1)\n\n    def _reflect_coordinates(i, size):\n        def __refelection(i, size, corner_start):\n            def __reflect(index, size, corner_start):\n                index_align_corner = abs(corner_start - index)\n                size_times = index_align_corner // size\n                even = size_times % 2 == 0\n                extra = index_align_corner - size_times * size\n                return extra + corner_start if even else size - extra + corner_start\n\n            if corner_start <= i <= size + corner_start:\n                new_i = i\n            else:\n                new_i = __reflect(i, size, corner_start)\n            return new_i\n\n        if align_corners:\n            x = __refelection(i, size - 1, 0)\n        else:\n            x = __refelection(i, size, -0.5)\n        return x\n\n    def _compute_source_index(b, h, w):\n        y = grid[b, 1, h, w]\n        x = grid[b, 0, h, w]\n        y, x = _unnormalize(y, x)\n\n        if padding_mode == \"reflection\":\n            y = _reflect_coordinates(y, in_height)\n            x = _reflect_coordinates(x, in_width)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n        elif padding_mode == \"border\":\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n\n        return (y, x)\n\n    def _nearest_sample():\n        for _b in range(batch):\n            for _c in range(channel):\n                for _h in range(out_height):\n                    for _w in range(out_width):\n                        y, x = _compute_source_index(_b, _h, _w)\n                        # python round is not used here,\n                        # beacause it is done toward the even choice\n                        new_y = int(y + 0.5) if y > 0 else int(y - 0.5)\n                        new_x = int(x + 0.5) if x > 0 else int(x - 0.5)\n                        out[_b, _c, _h, _w] = _get_pixel(_b, _c, new_y, new_x)\n\n    def _bilinear_sample():\n        for _b in range(batch):\n            for _c in range(channel):\n                for _h in range(out_height):\n                    for _w in range(out_width):\n                        y, x = _compute_source_index(_b, _h, _w)\n                        y0 = int(math.floor(y))\n                        x0 = int(math.floor(x))\n                        y1 = y0 + 1\n                        x1 = x0 + 1\n\n                        out[_b, _c, _h, _w] = (\n                            _get_pixel(_b, _c, y0, x0) * (1.0 - (y - y0)) * (1.0 - (x - x0))\n                            + _get_pixel(_b, _c, y0, x1) * (1.0 - (y - y0)) * (x - x0)\n                            + _get_pixel(_b, _c, y1, x0) * (y - y0) * (1.0 - (x - x0))\n                            + _get_pixel(_b, _c, y1, x1) * (y - y0) * (x - x0)\n                        )\n\n    def _bicubic_sample():\n        A = -0.75\n\n        def cubic_weight_1(x_fraction):\n            return ((A + 2) * x_fraction - (A + 3)) * x_fraction * x_fraction + 1\n\n        def cubic_weight_2(x_fraction):\n            return ((A * x_fraction - 5 * A) * x_fraction + 8 * A) * x_fraction - 4 * A\n\n        def cubic_interp_1d(pixel_0, pixel_1, pixel_2, pixel_3, x_fraction):\n            weights = [0] * 4\n            weights[0] = cubic_weight_2(x_fraction + 1)\n            weights[1] = cubic_weight_1(x_fraction)\n            weights[2] = cubic_weight_1(1 - x_fraction)\n            weights[3] = cubic_weight_2(2 - x_fraction)\n\n            return (\n                pixel_0 * weights[0]\n                + pixel_1 * weights[1]\n                + pixel_2 * weights[2]\n                + pixel_3 * weights[3]\n            )\n\n        def coefficients_along_x(x_floor, y_floor, x_fraction):\n            coefficients = [0] * 4\n\n            for i in range(4):\n                y_ = y_floor - 1 + i\n                x_0 = x_floor - 1\n                x_1 = x_floor + 0\n                x_2 = x_floor + 1\n                x_3 = x_floor + 2\n\n                if padding_mode == \"border\":\n                    y_ = _clip_coordinates(y_, in_height)\n                    x_0 = _clip_coordinates(x_0, in_width)\n                    x_1 = _clip_coordinates(x_1, in_width)\n                    x_2 = _clip_coordinates(x_2, in_width)\n                    x_3 = _clip_coordinates(x_3, in_width)\n\n                elif padding_mode == \"reflection\":\n                    y_ = _reflect_coordinates(y_, in_height)\n                    x_0 = _reflect_coordinates(x_0, in_width)\n                    x_1 = _reflect_coordinates(x_1, in_width)\n                    x_2 = _reflect_coordinates(x_2, in_width)\n                    x_3 = _reflect_coordinates(x_3, in_width)\n\n                    y_ = int(_clip_coordinates(y_, in_height))\n                    x_0 = int(_clip_coordinates(x_0, in_width))\n                    x_1 = int(_clip_coordinates(x_1, in_width))\n                    x_2 = int(_clip_coordinates(x_2, in_width))\n                    x_3 = int(_clip_coordinates(x_3, in_width))\n\n                coefficients[i] = cubic_interp_1d(\n                    _get_pixel(_b, _c, y_, x_0),\n                    _get_pixel(_b, _c, y_, x_1),\n                    _get_pixel(_b, _c, y_, x_2),\n                    _get_pixel(_b, _c, y_, x_3),\n                    x_fraction,\n                )\n            return coefficients\n\n        for _b in range(batch):\n            for _c in range(channel):\n                for _h in range(out_height):\n                    for _w in range(out_width):\n                        y = grid[_b, 1, _h, _w]\n                        x = grid[_b, 0, _h, _w]\n                        y, x = _unnormalize(y, x)\n                        y_floor = int(math.floor(y))\n                        x_floor = int(math.floor(x))\n                        y_fraction = y - y_floor\n                        x_fraction = x - x_floor\n\n                        coefficients = coefficients_along_x(x_floor, y_floor, x_fraction)\n\n                        out[_b, _c, _h, _w] = cubic_interp_1d(\n                            coefficients[0],\n                            coefficients[1],\n                            coefficients[2],\n                            coefficients[3],\n                            y_fraction,\n                        )\n\n    if method == \"bilinear\":\n        _bilinear_sample()\n    elif method == \"nearest\":\n        _nearest_sample()\n    else:  # mode == \"bicubic\":\n        _bicubic_sample()\n\n    return out\n\n\ndef grid_sample_3d(\n    data: np.ndarray,\n    grid: np.ndarray,\n    method=\"bilinear\",\n    layout=\"NCDHW\",\n    padding_mode=\"zeros\",\n    align_corners=True,\n):\n    r\"\"\"grid_sample_3d for NCDHW layout\"\"\"\n\n    assert method in (\"bilinear\", \"nearest\"), f\"{method} is not supported\"\n    assert layout == \"NCDHW\"\n    assert padding_mode in (\"zeros\", \"border\", \"reflection\"), f\"{padding_mode} is not supported\"\n    assert len(data.shape) == len(grid.shape) == 5\n\n    batch, channel = data.shape[:2]\n    in_depth, in_height, in_width = data.shape[2:]\n    out_depth, out_height, out_width = grid.shape[2:]\n    out_shape = [batch, channel, out_depth, out_height, out_width]\n    out = np.zeros(out_shape)\n\n    def _get_pixel(b, c, d, h, w):\n        if 0 <= d <= in_depth - 1 and 0 <= h <= in_height - 1 and 0 <= w <= in_width - 1:\n            return data[b, c, d, h, w]\n        return 0\n\n    def _unnormalize(d, h, w):\n        if align_corners:\n            new_d = (d + 1) * (in_depth - 1) / 2\n            new_h = (h + 1) * (in_height - 1) / 2\n            new_w = (w + 1) * (in_width - 1) / 2\n        else:\n            new_d = -0.5 + (d + 1) * in_depth / 2\n            new_h = -0.5 + (h + 1) * in_height / 2\n            new_w = -0.5 + (w + 1) * in_width / 2\n        return (new_d, new_h, new_w)\n\n    def _clip_coordinates(x, size):\n        return min(max(x, 0), size - 1)\n\n    def _reflect_coordinates(i, size):\n        def __refelection(i, size, corner_start):\n            def __reflect(index, size, corner_start):\n                index_align_corner = abs(corner_start - index)\n                size_times = index_align_corner // size\n                even = size_times % 2 == 0\n                extra = index_align_corner - size_times * size\n                return extra + corner_start if even else size - extra + corner_start\n\n            if corner_start <= i <= size + corner_start:\n                new_i = i\n            else:\n                new_i = __reflect(i, size, corner_start)\n            return new_i\n\n        if align_corners:\n            x = __refelection(i, size - 1, 0)\n        else:\n            x = __refelection(i, size, -0.5)\n        return x\n\n    def _compute_source_index(b, d, h, w):\n        z = grid[b, 2, d, h, w]\n        y = grid[b, 1, d, h, w]\n        x = grid[b, 0, d, h, w]\n        z, y, x = _unnormalize(z, y, x)\n\n        if padding_mode == \"reflection\":\n            z = _reflect_coordinates(z, in_depth)\n            y = _reflect_coordinates(y, in_height)\n            x = _reflect_coordinates(x, in_width)\n            z = _clip_coordinates(z, in_depth)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n        elif padding_mode == \"border\":\n            z = _clip_coordinates(z, in_depth)\n            y = _clip_coordinates(y, in_height)\n            x = _clip_coordinates(x, in_width)\n        return (z, y, x)\n\n    def _nearest_sample():\n        for _b in range(batch):\n            for _c in range(channel):\n                for _d in range(out_depth):\n                    for _h in range(out_height):\n                        for _w in range(out_width):\n                            z, y, x = _compute_source_index(_b, _d, _h, _w)\n                            # python round is not used here,\n                            # beacause it is done toward the even choice\n                            new_z = int(z + 0.5) if z > 0 else int(z - 0.5)\n                            new_y = int(y + 0.5) if y > 0 else int(y - 0.5)\n                            new_x = int(x + 0.5) if x > 0 else int(x - 0.5)\n                            out[_b, _c, _d, _h, _w] = _get_pixel(_b, _c, new_z, new_y, new_x)\n\n    def _triilinear_sample():\n        for _b in range(batch):\n            for _c in range(channel):\n                for _d in range(out_depth):\n                    for _h in range(out_height):\n                        for _w in range(out_width):\n                            z, y, x = _compute_source_index(_b, _d, _h, _w)\n                            z0 = int(math.floor(z))\n                            y0 = int(math.floor(y))\n                            x0 = int(math.floor(x))\n                            z1 = z0 + 1\n                            y1 = y0 + 1\n                            x1 = x0 + 1\n\n                            out[_b, _c, _d, _h, _w] = (\n                                _get_pixel(_b, _c, z0, y0, x0)\n                                * (1 - (x - x0))\n                                * (1 - (y - y0))\n                                * (1 - (z - z0))\n                                + _get_pixel(_b, _c, z0, y0, x1)\n                                * (x - x0)\n                                * (1 - (y - y0))\n                                * (1 - (z - z0))\n                                + _get_pixel(_b, _c, z1, y1, x0)\n                                * (1 - (x - x0))\n                                * (y - y0)\n                                * (z - z0)\n                                + _get_pixel(_b, _c, z1, y1, x1) * (x - x0) * (y - y0) * (z - z0)\n                                + _get_pixel(_b, _c, z0, y1, x0)\n                                * (1 - (x - x0))\n                                * (y - y0)\n                                * (1 - (z - z0))\n                                + _get_pixel(_b, _c, z1, y0, x1)\n                                * (x - x0)\n                                * (1 - (y - y0))\n                                * (z - z0)\n                                + _get_pixel(_b, _c, z1, y0, x0)\n                                * (1 - (x - x0))\n                                * (1 - (y - y0))\n                                * (z - z0)\n                                + _get_pixel(_b, _c, z0, y1, x1)\n                                * (x - x0)\n                                * (y - y0)\n                                * (1 - (z - z0))\n                            )\n\n    if method == \"bilinear\":\n        _triilinear_sample()\n    else:  # method == \"nearest\":\n        _nearest_sample()\n\n    return out\n\n\ndef grid_sample_python(\n    data: np.ndarray,\n    grid: np.ndarray,\n    method=\"bilinear\",\n    layout=\"NCHW\",\n    padding_mode=\"zeros\",\n    align_corners=True,\n):\n    r\"\"\"grid_sample_3d for NCDHW layout or grid_sample_2d for NCHW layout\"\"\"\n\n    if len(data.shape) == 4:\n        grid_sample = grid_sample_2d\n    elif len(data.shape) == 5:\n        grid_sample = grid_sample_3d\n    else:\n        raise ValueError(\"invalid shape\")\n\n    return grid_sample(data, grid, method, layout, padding_mode, align_corners)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/l2_normalize_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"L2 normalize in python\"\"\"\nimport numpy as np\n\n\ndef l2_normalize_python(a_np, eps, axis=None):\n    \"\"\"L2 normalize operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    eps : float\n        epsilon constant value\n    axis : list of int\n        axis over the normalization applied\n\n    Returns\n    -------\n    l2_normalize_out : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    dot_value = np.power(a_np, 2.0)\n    sqr_sum = np.sum(dot_value, axis, keepdims=True)\n    sqrt_sum = np.sqrt(np.maximum(np.broadcast_to(sqr_sum, a_np.shape), eps))\n    l2_normalize_out = np.divide(a_np, sqrt_sum)\n    return l2_normalize_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/layer_norm_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Layer normalization in python\"\"\"\nimport numpy as np\n\n\ndef layer_norm_python(data, gamma, beta, axis, epsilon=1e-5):\n    \"\"\"Layer normalization operator in Python.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        N-D with shape (d_0, d_1, ..., d_{N-1})\n\n    gamma: numpy.ndarray\n        K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k\n\n    beta: numpy.ndarray\n        Optional, K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k\n\n    axis : int or tuple of ints\n        Axis over the normalization applied\n\n    epsilon : float\n        The epsilon value to avoid division by zero.\n\n    Returns\n    -------\n    result : np.ndarray\n        N-D with shape (d_0, d_1, ..., d_{N-1})\n    \"\"\"\n    mean = np.mean(data, axis, keepdims=True)\n    var = np.var(data, axis, keepdims=True)\n    result = (data - mean) / np.sqrt(var + epsilon)\n    result *= gamma\n    if beta is not None:\n        result += beta\n    return result\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/lrn_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"LRN in python\"\"\"\nfrom itertools import product\nimport numpy as np\n\n\ndef lrn_python(a_np, size, axis, bias, alpha, beta):\n    \"\"\"Local response normalization operator in NCHW layout.\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    size : int\n        normalization window size\n\n    axis : int\n        input data layout channel axis\n\n    bias : float\n        offset to avoid dividing by 0. constant value\n\n    alpha : float\n        constant value\n\n    beta : float\n        exponent constant value\n\n    Returns\n    -------\n    lrn_out : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    radius = size // 2\n    sqr_sum = np.zeros(shape=a_np.shape).astype(a_np.dtype)\n    for i, j, k, l in product(*[range(_axis) for _axis in a_np.shape]):\n        axis_size = a_np.shape[axis]\n        if axis == 1:\n            # NCHW layout\n            sum_start = j - radius if j - radius >= 0 else 0\n            sum_end = j + radius + 1 if j + radius + 1 < axis_size else axis_size\n            sqr_sum[i, j, k, l] = sum(\n                a_np[i, sum_start:sum_end, k, l] * a_np[i, sum_start:sum_end, k, l]\n            )\n        elif axis == 3:\n            # NHWC layout\n            sum_start = l - radius if l - radius >= 0 else 0\n            sum_end = l + radius + 1 if l + radius + 1 < axis_size else axis_size\n            sqr_sum[i, j, k, l] = sum(\n                a_np[i, j, k, sum_start:sum_end] * a_np[i, j, k, sum_start:sum_end]\n            )\n\n    sqr_sum_up = np.power((bias + (alpha * sqr_sum / size)), beta)\n    lrn_out = np.divide(a_np, sqr_sum_up)\n    return lrn_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/lstm_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"LSTM reference implementation using numpy.\"\"\"\nimport numpy as np\n\n\ndef lstm_python(\n    Xs: np.array,\n    Wi: np.array,\n    Wh: np.array,\n    Bi: np.array = None,\n    Bh: np.array = None,\n    h_init: np.array = None,\n    c_init: np.array = None,\n    proj: np.array = None,\n    p_i: np.array = None,\n    p_f: np.array = None,\n    p_o: np.array = None,\n    f_act: str = \"sigmoid\",\n    g_act: str = \"tanh\",\n    h_act: str = \"tanh\",\n    reverse: bool = False,\n    weight_layout: str = \"IFGO\",\n):\n    \"\"\"LSTM reference implementation using numpy\n\n    Parameters\n    ----------\n    Xs : np.array\n        (seq_length, batch_size, in_dim)\n    Wi : np.array\n        (4 * hidden_dim, in_dim)\n    Wh : np.array\n        (4 * hidden_dim, out_dim) where out_dim = proj_dim if proj_dim > 0, else hidden_dim\n    Bi : np.array, optional\n        (4 * hidden_dim,), by default None\n    Bh : np.array, optional\n        (4 * hidden_dim,), by default None\n    h_init : np.array, optional\n        (batch_size, out_dim), by default None\n    c_init : np.array, optional\n        (batch_size, hidden_dim), by default None\n    proj : np.array, optional\n        (proj_dim, hidden_dim), by default None\n    p_i, p_f, p_o: np.array, optional\n        (batch_size, hidden_dim), by default None\n    f_act, g_act, h_act: str, optional\n        activations, by default \"sigmoid\", \"tanh\", \"tanh\"\n    reverse : bool, optional\n        process Xs in reverse, by default False\n    weight_layout : str, optional\n        Packed layout for weights and biases, by default \"IFGO\"\n    \"\"\"\n    i_gate_idx = weight_layout.find(\"I\")\n    f_gate_idx = weight_layout.find(\"F\")\n    g_gate_idx = weight_layout.find(\"G\")\n    o_gate_idx = weight_layout.find(\"O\")\n\n    str2act = {\"sigmoid\": lambda x: 1 / (1 + np.exp(-x)), \"tanh\": np.tanh}\n\n    f_act = str2act[f_act]\n    g_act = str2act[g_act]\n    h_act = str2act[h_act]\n\n    S, B, F = Xs.shape\n    H = Wi.shape[0] // 4\n    O = Wh.shape[1]\n\n    # make life a bit easier\n    Wi = np.reshape(Wi, (4, H, F))\n    Wh = np.reshape(Wh, (4, H, O))\n    if Bi is not None:\n        Bi = np.reshape(Bi, (4, H))\n    if Bh is not None:\n        Bh = np.reshape(Bh, (4, H))\n\n    h0 = h_init if h_init is not None else np.zeros((B, O), \"float32\")\n    c0 = c_init if c_init is not None else np.zeros((B, H), \"float32\")\n\n    hs = [h0]\n    cs = [c0]\n\n    for t in range(S):\n        x = Xs[S - t - 1 if reverse else t]\n        xh = [np.matmul(x, Wi[g].T) for g in range(4)]\n        if Bi is not None:\n            xh = [xh[g] + Bi[g] for g in range(4)]\n\n        hh = [np.matmul(hs[t], Wh[g].T) for g in range(4)]\n        if Bh is not None:\n            hh = [hh[g] + Bh[g] for g in range(4)]\n\n        sums = [xh[g] + hh[g] for g in range(4)]\n\n        if p_i is not None and p_f is not None:\n            i_gate = f_act(sums[i_gate_idx] + p_i * cs[t])\n            f_gate = f_act(sums[f_gate_idx] + p_f * cs[t])\n        else:\n            i_gate = f_act(sums[i_gate_idx])\n            f_gate = f_act(sums[f_gate_idx])\n\n        g_gate = g_act(sums[g_gate_idx])\n\n        next_c = f_gate * cs[t] + i_gate * g_gate\n\n        if p_o is not None:\n            o_gate = f_act(sums[o_gate_idx] + p_o * next_c)\n        else:\n            o_gate = f_act(sums[o_gate_idx])\n\n        next_h = o_gate * h_act(next_c)\n\n        if proj is not None:\n            next_h = np.matmul(next_h, proj.T)\n\n        hs.append(next_h)\n        cs.append(next_c)\n\n    return np.stack(hs[1:], axis=0), np.stack(cs[1:], axis=0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/matrix_set_diag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"MatrixSetDiag in Python\"\"\"\nimport numpy as np\n\n\ndef matrix_set_diag(input_np, diagonal, k=0, align=\"RIGHT_LEFT\"):\n    \"\"\"matrix_set_diag operator implemented in numpy.\n\n    Returns a numpy array with the diagonals of input array\n    replaced with the provided diagonal values.\n\n    Parameters\n    ----------\n    input_np : numpy.ndarray\n        Input Array.\n        Shape = [D1, D2, D3, ... , Dn-1 , Dn]\n\n    diagonal : numpy.ndarray\n        Values to be filled in the diagonal.\n\n    k : int or tuple of int\n        Diagonal Offsets.\n\n    align : string\n        Some diagonals are shorter than max_diag_len and need to be padded.\n        Possible Vales:\n        [\"RIGHT_LEFT\" (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", \"RIGHT_RIGHT\"]\n\n    Returns\n    -------\n    result : numpy.ndarray\n        New Array with given diagonal values.\n        Shape = [D1, D2, D3, ... , Dn-1 , Dn]\n    \"\"\"\n    out = np.array(input_np, copy=True)\n\n    cols = input_np.shape[-1]\n    rows = input_np.shape[-2]\n\n    onlyOneDiagonal = True\n    if isinstance(k, (tuple, list)):\n        if len(k) < 2 or k[0] == k[1]:\n            k = k[0]\n        else:\n            onlyOneDiagonal = False\n\n    if onlyOneDiagonal:\n        for i in range(diagonal.shape[-1]):\n            if k >= 0:\n                out[..., i, i + k] = diagonal[..., i]\n            else:\n                out[..., i - k, i] = diagonal[..., i]\n    else:\n        for ki in range(k[0], k[1] + 1):\n            diag_len = min(cols - max(ki, 0), rows + min(ki, 0))\n            offset = 0\n            if ki >= 0:\n                if align[:5] == \"RIGHT\":\n                    offset = diagonal.shape[-1] - diag_len\n            else:\n                if align[-5:] == \"RIGHT\":\n                    offset = diagonal.shape[-1] - diag_len\n            for i in range(diag_len):\n                if ki >= 0:\n                    out[..., i, i + ki] = diagonal[..., k[1] - ki, i + offset]\n                else:\n                    out[..., i - ki, i] = diagonal[..., k[1] - ki, i + offset]\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/nll_loss.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"NLLLoss in python\"\"\"\nimport numpy as np\n\n\ndef nll_loss(predictions, targets, weights, reduction=\"mean\", ignore_index=-100):\n    \"\"\"nll_loss operator implemented in numpy.\n\n    output{n, i_1, i_2, ..., i_k} = -p * w\n      where t = target{n, i_1, i_2, ..., i_k}\n            p = predictions{n, t, i_1, i_2, i_k}\n            w = weights{n, i_1, i_2, ..., i_k} if t != ignore_index else 0\n\n    result = reduction(output)\n\n    Parameters\n    ----------\n    predictions : numpy.ndarray\n        (k+2)-D with shape (N, C, d_1, d_2, ..., d_k),\n        where C is the number of target classes\n\n    targets : numpy.ndarray\n        (k+1)-D with shape (N, d_1, d_2, ..., d_k)\n        The target value of the input.\n\n    weights : numpy.ndarray\n        1-D with shape (C,)\n        The weight of each target value.\n\n    reduction : string\n        The reduction method to apply to output.\n        Can be \"mean\", \"sum\" or \"none\".\n\n    ignore_index : int\n        The target value to ignore.\n\n    Returns\n    -------\n    output : numpy.ndarray\n        a scalar if the reduction type is \"mean\" or \"sum\",\n        otherwise the same shape as `target`.\n    \"\"\"\n    res = np.zeros(targets.shape)\n    weight_sum = 0.0\n    for index in np.ndindex(targets.shape):\n        class_id = targets[index]\n        if class_id != ignore_index:\n            index_list = list(index)\n            pred_index = tuple(index_list[:1] + [class_id] + index_list[1:])\n            res[index] = -predictions[pred_index] * weights[class_id]\n            weight_sum += weights[class_id]\n    if reduction == \"mean\":\n        return np.sum(res) / weight_sum\n    if reduction == \"sum\":\n        return np.sum(res)\n    return res\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/one_hot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"OneHot in python\"\"\"\nimport numpy as np\n\n\ndef one_hot(indices, on_value, off_value, depth, axis, dtype):\n    \"\"\"one_hot operator implemented in numpy.\n\n    Returns a one-hot tensor where the locations repsented by indices take value on_value,\n    other locations take value off_value.\n    Final dimension is <indices outer dimensions> x depth x <indices inner dimensions>.\n\n    Parameters\n    ----------\n    indices : numpy.ndarray\n        Locations to set to on_value.\n\n    on_value : int/float\n        Value to fill at indices.\n\n    off_value : int/float\n        Value to fill at all other positions besides indices.\n\n    depth : int\n        Depth of the one-hot dimension.\n\n    axis : int\n        Axis to fill.\n\n    dtype : str\n        Data type of the output tensor.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The one-hot tensor.\n    \"\"\"\n    oshape = []\n    true_axis = len(indices.shape) if axis == -1 else axis\n    ndim = len(indices.shape) + 1\n    indices_index = 0\n    for i in range(0, ndim):\n        if i == true_axis:\n            oshape.append(depth)\n        else:\n            oshape.append(indices.shape[indices_index])\n            indices_index += 1\n\n    out = np.empty(oshape)\n    output_indices = list(np.ndindex(out.shape))\n    for output_index in output_indices:\n        indices_indices = []\n        for i, out_idx in enumerate(output_index):\n            if i == true_axis:\n                continue\n            indices_indices.append(out_idx)\n\n        index = output_index[true_axis]\n        if indices[tuple(indices_indices)] == index:\n            out[output_index] = on_value\n        else:\n            out[output_index] = off_value\n\n    return out.astype(dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/pool_grad_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, unused-variable\n\"\"\"Gradient of pooling in python\"\"\"\nimport numpy as np\n\n\ndef pool_grad_nchw(\n    a_np, out_grad_np, pool_size, strides, padding, pool_type, ceil_mode, count_include_pad=True\n):\n    \"\"\"pool_grad for NCHW layout in python\"\"\"\n    dtype = a_np.dtype\n    n, ic, ih, iw = a_np.shape\n    kh, kw = pool_size\n    sh, sw = strides\n    pt, pl, pb, pr = padding\n\n    pad_np = np.zeros(shape=(n, ic, ih + pt + pb, iw + pl + pr)).astype(dtype)\n    no_zero = (range(n), range(ic), (range(pt, ih + pt)), (range(pl, iw + pl)))\n    pad_np[np.ix_(*no_zero)] = a_np\n    _, _, oh, ow = out_grad_np.shape\n    pool_grad_np = np.zeros(shape=a_np.shape)\n    pad_pool_grad_np = np.zeros(shape=pad_np.shape)\n\n    if pool_type == \"avg\":\n        for i in range(oh):\n            for j in range(ow):\n                if count_include_pad:\n                    shape = pad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw].shape\n                    # this can be different from kh*kw if input size cannot divide stride\n                    pad_count = shape[2] * shape[3]\n                else:\n                    pad_count = np.sum(\n                        pad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw] > 0, axis=(2, 3)\n                    )\n                    # take the first element, as they are the same across batch and channel\n                    pad_count = pad_count.ravel()[0]\n                pad_pool_grad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw] += out_grad_np[\n                    :, :, i, j\n                ].reshape(n, ic, 1, 1) / np.maximum(pad_count, 1)\n    elif pool_type == \"max\":\n        for i in range(oh):\n            for j in range(ow):\n                a_patch = pad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw]\n                a_patch = np.reshape(a_patch, (n, ic, -1))\n                max_indices = np.argmax(a_patch, axis=2)\n                c_idx, n_idx = np.meshgrid(range(ic), range(n), sparse=True)\n                h_idx, w_idx = np.unravel_index(max_indices, (kh, kw))\n                pad_pool_grad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw][\n                    n_idx, c_idx, h_idx, w_idx\n                ] += out_grad_np[n_idx, c_idx, i, j]\n    for i in range(pool_grad_np.shape[2]):\n        for j in range(pool_grad_np.shape[3]):\n            pool_grad_np[:, :, i, j] = pad_pool_grad_np[:, :, i + pt, j + pl]\n\n    return pool_grad_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/poolnd_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, unused-variable\n\"\"\"Ground truth max and average pooling operators in python.\"\"\"\nimport itertools\nimport math\nfrom typing import List, Tuple, Optional\n\nimport numpy as np\nimport tvm\n\n\ndef _get_supported_layout(dims: int):\n    \"\"\"\n    Returns layout that is supported by poolnd_python based on number of\n    dimensions of input tensor\n    \"\"\"\n    assert dims in [3, 4, 5], f\"{dims}-dimensional tensor is not supported\"\n    if dims == 3:\n        return \"NCW\"\n    if dims == 4:\n        return \"NCHW\"\n    # dims == 5\n    return \"NCDHW\"\n\n\ndef _convert_to_layout(\n    input_tensor: np.ndarray,\n    layout: str,\n) -> np.ndarray:\n    \"\"\"\n    Converts back to original layout after the algorithm is finished\n    \"\"\"\n    supported_layout = _get_supported_layout(input_tensor.ndim)\n    if layout is not None and supported_layout != layout:\n        # Generate transpose list\n        transpose_list = []\n        for d in layout:\n            transpose_list.append(supported_layout.index(d))\n        return input_tensor.transpose(transpose_list)\n    return input_tensor\n\n\ndef _convert_from_layout(\n    input_tensor: np.ndarray,\n    layout: str,\n) -> np.ndarray:\n    \"\"\"\n    Converts tensor to one of suppored layouts\n    \"\"\"\n    supported_layout = _get_supported_layout(input_tensor.ndim)\n    if layout is not None and supported_layout != layout:\n        # Generate transpose list\n        transpose_list = []\n        for d in supported_layout:\n            transpose_list.append(layout.index(d))\n        return input_tensor.transpose(transpose_list)\n    return input_tensor\n\n\ndef get_slice(\n    spatial_dimensions: int,\n    pad_np: np.array,\n    dim_coord: Tuple[int],\n    kernel: Tuple[int],\n    strides: Tuple[int],\n    dilation: Tuple[int],\n) -> List[slice]:\n    \"\"\"\n    Programmatically create a slice object of the right dimensions for pad_np.\n\n    We assume pad_np's first two dimensions are not spatial and are not touched by the pad.\n\n    pad_np[slice] should give the elements of the data that a pool operation will use for the\n    step given in dim_coord.\n    \"\"\"\n    slices = [slice(None)] * spatial_dimensions\n\n    for nd in range(spatial_dimensions):\n        slices[nd] = slice(\n            dim_coord[nd] * strides[nd],\n            dim_coord[nd] * strides[nd] + (kernel[nd] - 1) * dilation[nd] + 1,\n            dilation[nd],\n        )\n\n    # Add back batch and channel dimensions\n    slices = [slice(None), slice(None)] + slices\n\n    return slices\n\n\ndef pad_tensor(\n    np_arr: np.array,\n    pad_value: float,\n    padding_before: List[int],\n    padding_after: List[int],\n    dtype: str,\n) -> np.array:\n    \"\"\"Pad the spatial dimensions of the given array.\"\"\"\n    orig_shape = list(np_arr.shape)\n    padded_shape = list(np_arr.shape)\n    n = len(orig_shape)\n    for dim in range(2, n):\n        i = dim - 2\n        padded_shape[dim] += padding_after[i] + padding_before[i]\n\n    pad_np = (np.zeros(shape=padded_shape) + pad_value).astype(dtype)\n    ranges_it = [range(padded_shape[0]), range(padded_shape[1])]\n    for dim in range(2, n):\n        i = dim - 2\n        ranges_it.append(range(padding_before[i], padding_before[i] + orig_shape[dim]))\n    pad_np[np.ix_(*ranges_it)] = np_arr\n    return pad_np\n\n\ndef poolnd_python(\n    np_data: np.array,\n    kernel: Tuple[int],\n    strides: Tuple[int],\n    dilation: Tuple[int],\n    padding_before: Tuple[int],\n    padding_after: Tuple[int],\n    pool_type: str,\n    count_include_pad: bool = True,\n    ceil_mode: bool = False,\n    dtype: str = \"float32\",\n    layout: Optional[str] = None,\n) -> np.array:\n    \"\"\"Ground truth pooling operator impelmented in numpy.\"\"\"\n\n    np_data = _convert_from_layout(np_data, layout)\n\n    out_shape = [np_data.shape[0], np_data.shape[1]]\n    for dim in range(2, len(np_data.shape)):\n        i = dim - 2\n        val = (\n            float(\n                np_data.shape[dim]\n                - (kernel[i] - 1) * dilation[i]\n                - 1\n                + padding_before[i]\n                + padding_after[i]\n            )\n            / strides[i]\n        )\n\n        if ceil_mode:\n            out_shape.append(int(math.ceil(val) + 1))\n        else:\n            out_shape.append(int(math.floor(val) + 1))\n    out_shape = tuple(out_shape)\n\n    # Create a padded array, and a boolean mask showing which values are padded values\n    pad_value = 0\n    if pool_type == \"max\" and not count_include_pad:\n        pad_value = tvm.te.min_value(dtype).value\n    pad_data = pad_tensor(np_data, pad_value, padding_before, padding_after, dtype)\n    pad_map = pad_tensor(np.ones_like(np_data), 0, padding_before, padding_after, \"bool\")\n\n    # Create iterator which gives all indices for output array\n    dim_iterators = []\n    for spatial_dimension in range(2, len(np_data.shape)):\n        dim_iterators.append(range(out_shape[spatial_dimension]))\n    coord_iterator = itertools.product(*dim_iterators)\n\n    ret_np = np.zeros(shape=out_shape).astype(dtype)\n    for coordinate in coord_iterator:\n        # Get index into the values that any pool operation will use for given coordinate\n        np_index = get_slice(\n            spatial_dimensions=len(out_shape) - 2,\n            pad_np=pad_data,\n            dim_coord=coordinate,\n            kernel=kernel,\n            strides=strides,\n            dilation=dilation,\n        )\n\n        output_slice = [slice(None), slice(None)] + list(coordinate)\n        reduction_axis = tuple(range(2, len(np_data.shape)))\n        if pool_type == \"avg\":\n            count_non_padded = (\n                pad_data[np_index].size if count_include_pad else np.sum(pad_map[np_index])\n            )\n            # We summed over the non spatial dimensions too so divide by them\n            count_non_padded /= out_shape[0] * out_shape[1]\n            if count_non_padded == 0:\n                ret_np[output_slice] = 0\n            else:\n                ret_np[output_slice] = (\n                    np.sum(pad_data[np_index], axis=reduction_axis) / count_non_padded\n                )\n        elif pool_type == \"max\":\n            count_non_padded = np.sum(pad_map[np_index])\n            # All padded values, default to 0\n            ret_np[output_slice] = np.max(pad_data[np_index], axis=reduction_axis)\n        else:\n            raise ValueError(\"Pool type {} is not supported\".format(pool_type))\n\n    return _convert_to_layout(ret_np, layout)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/reorg_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Reorg in python\"\"\"\nimport numpy as np\n\n\ndef reorg_python(a_np, stride):\n    \"\"\"Reorg operator\n\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    stride : int\n        Stride size\n\n    Returns\n    -------\n    b_np : np.ndarray\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n\n    batch, in_channel, in_height, in_width = a_np.shape\n    a_np = np.reshape(a_np, batch * in_channel * in_height * in_width)\n    out_c = int(in_channel / (stride * stride))\n    out_channel = in_channel * stride * stride\n    out_height = int(in_height / stride)\n    out_width = int(in_width / stride)\n    b_np = np.zeros(batch * out_channel * out_height * out_width)\n    cnt = 0\n    for b in range(batch):\n        for k in range(in_channel):\n            for j in range(in_height):\n                for i in range(in_width):\n                    c2 = k % out_c\n                    offset = int(k / out_c)\n                    w2 = int(i * stride + offset % stride)\n                    h2 = int(j * stride + offset / stride)\n                    out_index = int(\n                        w2 + in_width * stride * (h2 + in_height * stride * (c2 + out_c * b))\n                    )\n                    b_np[cnt] = a_np[int(out_index)]\n                    cnt = cnt + 1\n    b_np = np.reshape(b_np, (batch, out_channel, out_height, out_width))\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/resize_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Upsampling in python\"\"\"\nimport math\nimport numpy as np\nfrom tvm.topi.utils import nchw_pack_layout\n\n\ndef get_inx(x, image_width, target_width, coordinate_transformation_mode):\n    \"\"\"Infer input x from output x with various coordinate transformation methods\"\"\"\n    scale = image_width / target_width\n    if coordinate_transformation_mode == \"half_pixel\":\n        in_x = (x + 0.5) * scale - 0.5\n    elif coordinate_transformation_mode == \"align_corners\":\n        in_x = (image_width - 1) / (target_width - 1) * x if target_width > 1 else 0\n    elif coordinate_transformation_mode == \"asymmetric\":\n        in_x = scale * x\n    else:\n        raise ValueError(\n            \"Unsupported coordinate_transformation_mode: {}\".format(coordinate_transformation_mode)\n        )\n    return in_x\n\n\ndef get_index(x, image_width, target_width, coordinate_transformation_mode):\n    \"\"\"get and round the nearest index for nearest_neighbor\"\"\"\n    in_x = get_inx(x, image_width, target_width, coordinate_transformation_mode)\n    if coordinate_transformation_mode == \"align_corners\":\n        # round prefer ceil\n        out = int(math.floor(in_x + 0.5))\n    else:\n        out = int(math.floor(in_x))\n    out = max(min(out, image_width - 1), 0)\n    return out\n\n\ndef resize3d_nearest(arr, scale, coordinate_transformation_mode):\n    \"\"\"Populate the array by scale factor\"\"\"\n    d, h, w = arr.shape\n    out_d, out_h, out_w = [int(round(i * s)) for i, s in zip(arr.shape, scale)]\n    out = np.empty((out_d, out_h, out_w))\n    for z in range(out_d):\n        for y in range(out_h):\n            for x in range(out_w):\n                in_z = get_index(z, d, out_d, coordinate_transformation_mode)\n                in_y = get_index(y, h, out_h, coordinate_transformation_mode)\n                in_x = get_index(x, w, out_w, coordinate_transformation_mode)\n                out[z, y, x] = arr[in_z, in_y, in_x]\n    return out\n\n\ndef resize3d_linear(data_in, scale, coordinate_transformation_mode):\n    \"\"\"Trilinear 3d scaling using python\"\"\"\n    dtype = data_in.dtype\n    d, h, w = data_in.shape\n    new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]\n    data_out = np.ones((new_d, new_h, new_w))\n\n    indexes = np.mgrid[0:2, 0:2, 0:2]\n\n    def _get_patch(zint, yint, xint):\n        # Get the surrounding values\n        indices = indexes.copy()\n        indices[0] = np.maximum(np.minimum(indexes[0] + zint, d - 1), 0)\n        indices[1] = np.maximum(np.minimum(indexes[1] + yint, h - 1), 0)\n        indices[2] = np.maximum(np.minimum(indexes[2] + xint, w - 1), 0)\n        p = data_in[indices[0], indices[1], indices[2]]\n        return p\n\n    for m in range(new_d):\n        for j in range(new_h):\n            for k in range(new_w):\n                in_z = get_inx(m, d, new_d, coordinate_transformation_mode)\n                in_y = get_inx(j, h, new_h, coordinate_transformation_mode)\n                in_x = get_inx(k, w, new_w, coordinate_transformation_mode)\n                zint = math.floor(in_z)\n                zfract = in_z - math.floor(in_z)\n\n                yint = math.floor(in_y)\n                yfract = in_y - math.floor(in_y)\n\n                xint = math.floor(in_x)\n                xfract = in_x - math.floor(in_x)\n\n                wz = np.array([1.0 - zfract, zfract], dtype=dtype)\n                wy = np.array([1.0 - yfract, yfract], dtype=dtype)\n                wx = np.array([1.0 - xfract, xfract], dtype=dtype)\n\n                p = _get_patch(zint, yint, xint)\n                l = np.sum(p * wx, axis=-1)\n                col = np.sum(l * wy, axis=-1)\n                data_out[m, j, k] = np.sum(col * wz)\n\n    return data_out\n\n\ndef resize3d_cubic(data_in, scale, coordinate_transformation_mode):\n    \"\"\"Tricubic 3d scaling using python\"\"\"\n    dtype = data_in.dtype\n    d, h, w = data_in.shape\n    new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]\n    data_out = np.ones((new_d, new_h, new_w))\n\n    def _cubic_spline_weights(t, alpha=-0.5):\n        \"\"\"create cubic spline weights in 1D\"\"\"\n        t2 = t * t\n        t3 = t * t * t\n        w1 = alpha * (t3 - 2 * t2 + t)\n        w2 = (alpha + 2) * t3 - (3 + alpha) * t2 + 1\n        w3 = -(alpha + 2) * t3 + (3 + 2 * alpha) * t2 - alpha * t\n        w4 = -alpha * t3 + alpha * t2\n        return np.array([w1, w2, w3, w4])\n\n    indexes = np.mgrid[-1:3, -1:3, -1:3]\n\n    def _get_patch(zint, yint, xint):\n        # Get the surrounding values\n        indices = indexes.copy()\n        indices[0] = np.maximum(np.minimum(indexes[0] + zint, d - 1), 0)\n        indices[1] = np.maximum(np.minimum(indexes[1] + yint, h - 1), 0)\n        indices[2] = np.maximum(np.minimum(indexes[2] + xint, w - 1), 0)\n        p = data_in[indices[0], indices[1], indices[2]]\n        return p\n\n    for m in range(new_d):\n        for j in range(new_h):\n            for k in range(new_w):\n                in_z = get_inx(m, d, new_d, coordinate_transformation_mode)\n                in_y = get_inx(j, h, new_h, coordinate_transformation_mode)\n                in_x = get_inx(k, w, new_w, coordinate_transformation_mode)\n                zint = math.floor(in_z)\n                zfract = in_z - math.floor(in_z)\n\n                yint = math.floor(in_y)\n                yfract = in_y - math.floor(in_y)\n\n                xint = math.floor(in_x)\n                xfract = in_x - math.floor(in_x)\n\n                wz = _cubic_spline_weights(zfract)\n                wy = _cubic_spline_weights(yfract)\n                wx = _cubic_spline_weights(xfract)\n\n                p = _get_patch(zint, yint, xint)\n\n                l = np.sum(p * wx, axis=-1)\n                col = np.sum(l * wy, axis=-1)\n                data_out[m, j, k] = np.sum(col * wz)\n\n    return data_out\n\n\ndef resize3d_ncdhw(\n    data, scale, method=\"nearest_neighbor\", coordinate_transformation_mode=\"align_corners\"\n):\n    \"\"\"reference kernel for 3D image resizing\"\"\"\n    ishape = data.shape\n\n    oshape = (\n        ishape[0],\n        ishape[1],\n        int(round(ishape[2] * scale[0])),\n        int(round(ishape[3] * scale[1])),\n        int(round(ishape[4] * scale[2])),\n    )\n\n    output_np = np.zeros(oshape, dtype=data.dtype)\n\n    for b in range(oshape[0]):\n        for c in range(oshape[1]):\n            if method == \"nearest_neighbor\":\n                output_np[b, c, :, :, :] = resize3d_nearest(\n                    data[b, c, :, :, :], scale, coordinate_transformation_mode\n                )\n            elif method == \"linear\":\n                output_np[b, c, :, :, :] = resize3d_linear(\n                    data[b, c, :, :, :], scale, coordinate_transformation_mode\n                )\n            elif method == \"cubic\":\n                output_np[b, c, :, :, :] = resize3d_cubic(\n                    data[b, c, :, :, :], scale, coordinate_transformation_mode\n                )\n            else:\n                raise ValueError(\"Unknown resize method\", method)\n\n    return output_np\n\n\ndef resize1d_python(\n    data,\n    scale,\n    layout=\"NCW\",\n    method=\"nearest_neighbor\",\n    coordinate_transformation_mode=\"align_corners\",\n):\n    \"\"\"Python version of 3D scaling using nearest neighbour\"\"\"\n\n    if layout == \"NWC\":\n        data = data.transpose([0, 2, 1])\n\n    data = np.expand_dims(data, axis=[2, 3])\n    output_np = resize3d_ncdhw(data, (1, 1) + scale, method, coordinate_transformation_mode)\n    output_np = np.squeeze(output_np, axis=2)\n    output_np = np.squeeze(output_np, axis=2)\n\n    if layout == \"NWC\":\n        output_np = output_np.transpose([0, 2, 1])\n\n    return output_np\n\n\ndef resize2d_python(\n    data,\n    scale,\n    layout=\"NCHW\",\n    method=\"nearest_neighbor\",\n    coordinate_transformation_mode=\"align_corners\",\n):\n    \"\"\"Python version of scaling using nearest neighbour\"\"\"\n\n    if layout == \"NHWC\":\n        data = data.transpose([0, 3, 1, 2])\n    elif nchw_pack_layout(layout):\n        ishape = data.shape\n        transposed = data.transpose([0, 4, 1, 5, 2, 3])\n        tshape = transposed.shape\n        data = transposed.reshape(\n            tshape[0] * tshape[1], tshape[2] * tshape[3], tshape[4], tshape[5]\n        )\n\n    data = np.expand_dims(data, axis=2)\n    output_np = resize3d_ncdhw(data, (1,) + scale, method, coordinate_transformation_mode)\n    output_np = np.squeeze(output_np, axis=2)\n\n    if layout == \"NHWC\":\n        output_np = output_np.transpose([0, 2, 3, 1])\n    elif nchw_pack_layout(layout):\n        output_np = output_np.reshape(tshape[0:4] + output_np.shape[2:])\n        output_np = output_np.transpose([0, 2, 4, 5, 1, 3])\n\n    return output_np\n\n\ndef resize3d_python(\n    data,\n    scale,\n    layout=\"NCDHW\",\n    method=\"nearest_neighbor\",\n    coordinate_transformation_mode=\"align_corners\",\n):\n    \"\"\"Python version of 3D scaling using nearest neighbour\"\"\"\n\n    if layout == \"NDHWC\":\n        data = data.transpose([0, 4, 1, 2, 3])\n\n    output_np = resize3d_ncdhw(data, scale, method, coordinate_transformation_mode)\n\n    if layout == \"NDHWC\":\n        output_np = output_np.transpose([0, 2, 3, 4, 1])\n\n    return output_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/roi_align_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-nested-blocks\n\"Roi align in python\"\nimport math\nimport numpy as np\n\n\ndef _bilinear(a_np, n, c, y, x, height, width, layout):\n    if y < -1 or y > height or x < -1 or x > width:\n        return 0\n\n    y = min(max(y, 0), height - 1)\n    x = min(max(x, 0), width - 1)\n\n    y_low = int(math.floor(y))\n    x_low = int(math.floor(x))\n    y_high = y_low + 1\n    x_high = x_low + 1\n\n    wy_h = y - y_low\n    wx_h = x - x_low\n    wy_l = 1 - wy_h\n    wx_l = 1 - wx_h\n\n    val = 0\n    for wx, xp in zip((wx_l, wx_h), (x_low, x_high)):\n        for wy, yp in zip((wy_l, wy_h), (y_low, y_high)):\n            if 0 <= yp < height and 0 <= xp < width:\n                if layout == \"NCHW\":\n                    val += wx * wy * a_np[n, c, yp, xp]\n                else:\n                    val += wx * wy * a_np[n, yp, xp, c]\n    return val\n\n\ndef roi_align_common(\n    a_np,\n    b_np,\n    rois_np,\n    channel,\n    pooled_size_h,\n    pooled_size_w,\n    spatial_scale,\n    sample_ratio,\n    avg_mode,\n    max_mode,\n    height,\n    width,\n    layout,\n):\n    \"\"\"Common code used by roi align NCHW and NHWC\"\"\"\n    num_roi = rois_np.shape[0]\n\n    for i in range(num_roi):\n        roi = rois_np[i]\n        batch_index = int(roi[0])\n        roi_start_w, roi_start_h, roi_end_w, roi_end_h = roi[1:] * spatial_scale\n        roi_h = max(roi_end_h - roi_start_h, 1.0)\n        roi_w = max(roi_end_w - roi_start_w, 1.0)\n\n        bin_h = roi_h / pooled_size_h\n        bin_w = roi_w / pooled_size_w\n\n        if sample_ratio > 0:\n            roi_bin_grid_h = roi_bin_grid_w = int(sample_ratio)\n        else:\n            roi_bin_grid_h = int(math.ceil(roi_h / pooled_size_h))\n            roi_bin_grid_w = int(math.ceil(roi_w / pooled_size_w))\n\n        count = roi_bin_grid_h * roi_bin_grid_w\n\n        for c in range(channel):\n            for ph in range(pooled_size_h):\n                for pw in range(pooled_size_w):\n                    if avg_mode:\n                        total = 0.0\n                    if max_mode:\n                        total = float(\"-inf\")\n                    for iy in range(roi_bin_grid_h):\n                        for ix in range(roi_bin_grid_w):\n                            y = roi_start_h + ph * bin_h + (iy + 0.5) * bin_h / roi_bin_grid_h\n                            x = roi_start_w + pw * bin_w + (ix + 0.5) * bin_w / roi_bin_grid_w\n                            if avg_mode:\n                                total += (\n                                    _bilinear(a_np, batch_index, c, y, x, height, width, layout)\n                                    / count\n                                )\n                            if max_mode:\n                                total = max(\n                                    total,\n                                    _bilinear(a_np, batch_index, c, y, x, height, width, layout),\n                                )\n\n                    if layout == \"NCHW\":\n                        b_np[i, c, ph, pw] = total\n                    else:\n                        b_np[i, ph, pw, c] = total\n    return b_np\n\n\ndef roi_align_nchw_python(a_np, rois_np, pooled_size, spatial_scale, sample_ratio, mode=b\"avg\"):\n    \"\"\"Roi align NCHW in python\"\"\"\n    avg_mode = mode in (b\"avg\", \"avg\", 0)\n    max_mode = mode in (b\"max\", \"max\", 1)\n    assert avg_mode or max_mode, \"Mode must be average or max. Please pass a valid mode.\"\n    _, channel, height, width = a_np.shape\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    b_np = np.zeros((rois_np.shape[0], channel, pooled_size_h, pooled_size_w), dtype=a_np.dtype)\n\n    return roi_align_common(\n        a_np,\n        b_np,\n        rois_np,\n        channel,\n        pooled_size_h,\n        pooled_size_w,\n        spatial_scale,\n        sample_ratio,\n        avg_mode,\n        max_mode,\n        height,\n        width,\n        \"NCHW\",\n    )\n\n\ndef roi_align_nhwc_python(a_np, rois_np, pooled_size, spatial_scale, sample_ratio, mode=b\"avg\"):\n    \"\"\"Roi align NHWC in python\"\"\"\n    avg_mode = mode in (b\"avg\", \"avg\", 0)\n    max_mode = mode in (b\"max\", \"max\", 1)\n    assert avg_mode or max_mode, \"Mode must be average or max. Please pass a valid mode.\"\n    _, height, width, channel = a_np.shape\n    num_roi = rois_np.shape[0]\n\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    b_np = np.zeros((num_roi, pooled_size_h, pooled_size_w, channel), dtype=a_np.dtype)\n\n    return roi_align_common(\n        a_np,\n        b_np,\n        rois_np,\n        channel,\n        pooled_size_h,\n        pooled_size_w,\n        spatial_scale,\n        sample_ratio,\n        avg_mode,\n        max_mode,\n        height,\n        width,\n        \"NHWC\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/roi_pool_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-nested-blocks\n\"Roi pool in python\"\nimport math\nimport numpy as np\n\n\ndef roi_pool_nchw_python(a_np, rois_np, pooled_size, spatial_scale):\n    \"\"\"Roi pool in python\"\"\"\n    _, channel, height, width = a_np.shape\n    num_roi = rois_np.shape[0]\n    b_np = np.zeros((num_roi, channel, pooled_size, pooled_size), dtype=a_np.dtype)\n\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    for i in range(num_roi):\n        roi = rois_np[i]\n        batch_index = int(roi[0])\n        roi_start_w = int(round(roi[1] * spatial_scale))\n        roi_start_h = int(round(roi[2] * spatial_scale))\n        roi_end_w = int(round(roi[3] * spatial_scale))\n        roi_end_h = int(round(roi[4] * spatial_scale))\n        roi_h = max(roi_end_h - roi_start_h + 1, 1)\n        roi_w = max(roi_end_w - roi_start_w + 1, 1)\n\n        bin_h = float(roi_h) / pooled_size_h\n        bin_w = float(roi_w) / pooled_size_w\n\n        for ph in range(pooled_size_h):\n            for pw in range(pooled_size_w):\n                hstart = int(math.floor(ph * bin_h))\n                wstart = int(math.floor(pw * bin_w))\n                hend = int(math.ceil((ph + 1) * bin_h))\n                wend = int(math.ceil((pw + 1) * bin_w))\n                hstart = min(max(hstart + roi_start_h, 0), height)\n                hend = min(max(hend + roi_start_h, 0), height)\n                wstart = min(max(wstart + roi_start_w, 0), width)\n                wend = min(max(wend + roi_start_w, 0), width)\n                is_empty = (hend <= hstart) or (wend <= wstart)\n\n                for c in range(channel):\n                    if is_empty:\n                        b_np[i, c, ph, pw] = 0.0\n                    else:\n                        b_np[i, c, ph, pw] = np.max(a_np[batch_index, c, hstart:hend, wstart:wend])\n    return b_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/searchsorted.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"The reference implementation of searchsorted in Numpy.\"\"\"\nimport numpy as np\n\n\ndef searchsorted_ref(sorted_sequence, values, right, out_dtype):\n    \"\"\"Run Numpy searchsorted on 1-D or N-D sorted_sequence.\"\"\"\n    side = \"right\" if right else \"left\"\n    if len(sorted_sequence.shape) == 1 and len(values.shape) > 1:\n        sorted_sequence_2d = np.tile(sorted_sequence, (np.prod(values.shape[:-1]), 1))\n    else:\n        sorted_sequence_2d = np.reshape(sorted_sequence, (-1, sorted_sequence.shape[-1]))\n\n    values_2d = np.reshape(values, (-1, values.shape[-1]))\n    indices = np.zeros(values_2d.shape, dtype=out_dtype)\n\n    for i in range(indices.shape[0]):\n        indices[i] = np.searchsorted(sorted_sequence_2d[i], values_2d[i], side=side)\n\n    return np.reshape(indices, values.shape)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/sequence_mask_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Sequence mask in python\"\"\"\nimport numpy as np\n\n\ndef sequence_mask(data, valid_length, mask_value, axis):\n    \"\"\"batch_matmul operator implemented in numpy.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        N-D with shape [batch_size, MAX_LENGTH, ...] or [MAX_LENGTH, batch_size, ...]\n\n    valid_length : numpy.ndarray\n        1-D with shape [batch_size,]\n\n    mask_value : float\n        Masking value\n\n    axis : int\n        The axis of the length dimension\n\n    Returns\n    -------\n    out : numpy.ndarray\n        N-D with shape same as data\n    \"\"\"\n    in_shape = data.shape\n    max_length = data.shape[axis]\n    val_len_expand_shape = [1 for _ in range(len(in_shape))]\n    val_len_expand_shape[1 - axis] = in_shape[1 - axis]\n    seq_len_expand_shape = [1 for _ in range(len(in_shape))]\n    seq_len_expand_shape[axis] = in_shape[axis]\n    mask = np.broadcast_to(\n        np.arange(max_length).reshape(seq_len_expand_shape), in_shape\n    ) >= valid_length.reshape(val_len_expand_shape)\n    out = data * (1 - mask) + mask_value * mask\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/slice_axis_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Slice axis in python\"\"\"\n\n\ndef slice_axis_python(data, axis, begin, end=None):\n    \"\"\"Slice input array along specific axis.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        The source array to be sliced.\n\n    axis : int\n        Axis to be sliced.\n\n    begin: int\n        The index to begin with in the slicing.\n\n    end: int, optional\n        The index indicating end of the slice.\n\n    Returns\n    -------\n    ret : numpy.ndarray\n        The computed result.\n    \"\"\"\n    dshape = data.shape\n    if axis < 0:\n        axis += len(dshape)\n    if begin < 0:\n        begin += dshape[axis]\n    if end <= 0:\n        end += dshape[axis]\n    slc = [slice(None)] * len(dshape)\n    slc[axis] = slice(begin, end)\n    return data[tuple(slc)]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/softmax_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, trailing-whitespace\n\"\"\"Softmax and log_softmax operation in python\"\"\"\nimport numpy as np\n\n\ndef softmax_python(a_np, axis=1):\n    \"\"\"Softmax operator.\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        N-D input data\n\n    Returns\n    -------\n    output_np : numpy.ndarray\n        N-D output with same shape\n    \"\"\"\n    max_elem = np.amax(a_np, axis=axis, keepdims=True)\n    e = np.exp(a_np - max_elem)\n    expsum = np.sum(e, axis=axis, keepdims=True)\n    out_np = e / expsum\n    return out_np\n\n\ndef log_softmax_python(a_np, axis=1):\n    \"\"\"Log_softmax operator.\n    Parameters\n    ----------\n    a_np : numpy.ndarray\n        N-D input data\n\n    Returns\n    -------\n    output_np : numpy.ndarray\n        N-D output with same shape\n    \"\"\"\n    max_elem = np.amax(a_np, axis=axis, keepdims=True)\n    e = np.exp(a_np - max_elem)\n    expsum = np.sum(e, axis=axis, keepdims=True)\n    out_np = a_np - max_elem - np.log(expsum)\n    return out_np\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/space_to_batch_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Space to batch ND in python\"\"\"\nimport numpy as np\n\n\ndef space_to_batch_nd_python(data, block_shape, pad_before, pad_after, pad_value=0):\n    \"\"\"Space to Batch operator in python for NHWC layout.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        N-D with shape [batch, spatial_shape, remaining_shapes],\n        where spatial_shape has M dimensions.\n\n    block_shape : list of ints\n        1-D array of size [M] where M is number of spatial dims, specifies block\n        size for each spatial dimension.\n\n    pad_before : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        zero-padding size before each spatial dimension.\n\n    pad_after : list of ints\n        list of shape [M] where M is number of spatial dims, specifies\n        zero-padding size after each spatial dimension.\n\n    pad_value : float, optional\n        the value used for padding. Defaults to 0.\n\n    Returns\n    -------\n    s2b_out : np.ndarray\n        N-D with shape [batch * prod(block_shape),\n                        padded_data[1] / block_shape[0], ..., padded_data[M] / block_shape[M-1],\n                        remaining_shape]\n    \"\"\"\n    M = len(block_shape)\n    in_batch = data.shape[0]\n    block_shape_prod = np.prod(block_shape)\n\n    # Apply padding to input data\n    input_shape = data.shape\n    # Add the paddings for batch and remaining dims\n    paddings = map(list, zip(pad_before, pad_after))\n    paddings = [[0, 0]] + list(paddings) + [[0, 0]] * (data.ndim - 1 - M)\n    padded_data = np.pad(data, paddings, mode=\"constant\", constant_values=pad_value)\n    padded_shape = padded_data.shape\n\n    # Get the reshape shape and transpose axes\n    r_shape = []\n    trans_axis = []\n    r_shape.append(in_batch)\n    for i in range(1, M + 1):\n        r_shape.append((int(padded_shape[i] // block_shape[i - 1])))\n        r_shape.append(block_shape[i - 1])\n        trans_axis.append(len(r_shape) - 1)\n\n    axis_len = len(trans_axis)\n    trans_axis.append(0)\n    for i in range(axis_len):\n        trans_axis.append(trans_axis[i] - 1)\n\n    out_shape = []\n    out_shape.append(int((in_batch * block_shape_prod)))\n    for i in range(1, M + 1):\n        out_shape.append(int(padded_shape[i] // block_shape[i - 1]))\n\n    for i in range(M + 1, len(input_shape)):\n        r_shape.append(input_shape[i])\n        trans_axis.append(len(r_shape) - 1)\n        out_shape.append(input_shape[i])\n\n    s2b_out = np.reshape(padded_data, newshape=r_shape)\n    s2b_out = np.transpose(s2b_out, axes=trans_axis)\n    s2b_out = np.reshape(s2b_out, newshape=out_shape)\n\n    return s2b_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/space_to_depth.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals\n\"\"\"Space to depth in python\"\"\"\nimport numpy as np\n\n\ndef space_to_depth_python(data, block_size):\n    \"\"\"Space to Depth operator in python for NCHW layout.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    block_size : int\n        Size of spatial blocks to decompose into channels.\n\n    Returns\n    -------\n    d2s_out : np.ndarray\n        4-D with shape [batch, in_channel * (block_size * block_size),\n                        out_height / block_size, out_width / block_size]\n    \"\"\"\n    in_n, in_c, in_h, in_w = data.shape\n    new_h = int(in_h / block_size)\n    new_w = int(in_h / block_size)\n    new_c = int(in_c * (block_size * block_size))\n\n    expanded = np.reshape(data, newshape=[in_n, in_c, new_h, block_size, new_w, block_size])\n    transposed = np.transpose(expanded, axes=[0, 3, 5, 1, 2, 4])\n    newshape = [in_n, new_c, new_h, new_w]\n    d2s_out = np.reshape(transposed, newshape=newshape)\n    return d2s_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/testing/strided_slice_python.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"strided_slice/set in python\"\"\"\n\n\ndef strided_slice_python(data, begin, end, strides, slice_mode=\"end\", axes=None):\n    \"\"\"Python version of strided slice operator.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        Input data\n\n    begin : list\n        Beginning of the slices.\n\n    end : list\n        End of the slices.\n\n    strides : list\n        The stride of each slice.\n\n    slice_mode : str, optional\n        The slice mode [end, size].\n        end: The default slice mode, ending indices for the slice.\n        size: The input strides will be ignored, input end in this mode indicates\n              the sizeof a slice starting at the location specified by begin. If end[i] is -1,\n              all remaining elements in that dimension are included in the slice.\n\n    axes : list, optional\n        Axes along which slicing is applied\n\n    Returns\n    -------\n    result : numpy.ndarray\n        The sliced result.\n    \"\"\"\n    strides = [] if strides is None else strides\n    if axes is not None:\n        rank = len(data.shape)\n        new_begin = [0] * rank\n        new_end = [data.shape[i] for i in range(rank)]\n        new_strides = [1] * rank\n\n        for i, axis in enumerate(axes):\n            new_begin[axis] = begin[i]\n            new_end[axis] = end[i]\n            if len(strides) > i:\n                new_strides[axis] = strides[i]\n\n        begin = new_begin\n        end = new_end\n        strides = new_strides\n\n    slices = []\n    for i in range(len(data.shape)):\n        new_stride = None\n        if slice_mode == \"end\" and i < len(strides):\n            new_stride = strides[i]\n\n        new_begin = begin[i] if i < len(begin) else None\n        if i >= len(end):\n            new_end = None\n        elif slice_mode == \"size\":\n            if end[i] < 0:\n                new_end = None\n            else:\n                new_end = new_begin + end[i]\n        else:\n            new_end = end[i]\n\n        slices.append(slice(new_begin, new_end, new_stride))\n\n    return data[tuple(slices)]\n\n\ndef strided_set_python(data, v, begin, end, strides):\n    \"\"\"Python version of strided slice operator.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        Input data\n\n    v : numpy.ndarray\n        Value data\n\n    begin : list\n        Beginning of the slices.\n\n    end : list\n        End of the slices.\n\n    strides : list\n        The stride of each slice.\n\n    Returns\n    -------\n    result : numpy.ndarray\n        The updated result.\n    \"\"\"\n    strides = [] if strides is None else strides\n    slices = []\n    res = data.copy()\n    for i in range(len(data.shape)):\n        slices.append(\n            slice(\n                begin[i] if i < len(begin) else None,\n                end[i] if i < len(end) else None,\n                strides[i] if i < len(strides) else None,\n            )\n        )\n    res[tuple(slices)] = v\n    return res\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,consider-using-enumerate,redefined-outer-name\n\"\"\"Injective transformation operators\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.te import hybrid\nfrom . import cpp\nfrom . import tag\nfrom .utils import within_index, make_idx, const_vector\n\n\ndef expand_dims(a, axis, num_newaxis=1):\n    \"\"\"Expand the shape of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be expanded.\n\n    num_newaxis: int, optional\n        Number of newaxis to be inserted on axis\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.expand_dims(a, axis, num_newaxis)\n\n\ndef expand_like(a, shape_like, axis):\n    \"\"\"Expand an input array with the shape of second array.\n    This operation can always be composed of unsqueezing and\n    expanding dims on those unsqueezed axes.\n\n    Examples\n    --------\n    .. code-block::\n\n        input = [ 12.  19.  27.]\n        input.shape = (3,)\n\n        new_shape_array = [[[1,2],[2,3],[1,3]],\n                        [[1,4],[4,3],[5,2]],\n                        [[7,1],[7,2],[7,3]]]\n        new_shape_array.shape = (3, 3, 2)\n\n        expand_like(input, [1,2], new_shape_array) =\n                        [[[12,12],[12,12],[12,12]],\n                        [[19,19],[19,19],[19,19]],\n                        [[27,27],[27,27],[27,27]]]\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be expanded.\n    shape_like : tvm.te.Tensor\n        The tensor to with target shape.\n    axis: list of int\n        axis to be expanded on\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    odim = len(axis) + len(a.shape)\n    if odim != len(shape_like.shape):\n        if len(a.shape) == 1 and len(axis) == len(shape_like.shape):\n            # A special case: `a` is a scalar represented as a 1-dim tensor\n            return te.compute(shape_like.shape, lambda *idxs: a(0))\n        raise ValueError(\n            \"shape inconsistent when expand_like ({}, {}, {})\".format(\n                len(axis), len(a.shape), len(shape_like.shape)\n            )\n        )\n\n    real_axis = topi.reduction._get_real_axis(len(shape_like.shape), axis)\n    real_axis = sorted(real_axis)\n\n    def _compute(*idxs):\n        indices = []\n        axis_index = 0\n        for i in range(0, len(idxs)):\n            if i not in real_axis:\n                indices.append(idxs[i])\n                axis_index += 1\n        return a(*indices)\n\n    return te.compute(shape_like.shape, _compute)\n\n\ndef transpose(a, axes=None):\n    \"\"\"Permute the dimensions of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be expanded.\n\n    axes: tuple of ints, optional\n        By default, reverse the dimensions.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.transpose(a, axes)\n\n\ndef flip(a, axis=0):\n    \"\"\"Flip/reverse elements of an array in a particular axis.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be expanded.\n\n    axis : int, optional\n        The axis along which the tensors will be reveresed.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.flip(a, axis)\n\n\ndef reverse_sequence(a, seq_lengths, seq_axis=1, batch_axis=0):\n    \"\"\"Reverse the tensor for variable length slices.\n    Input is first sliced along batch axis and then elements are reversed along seq axis.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n       The tensor to be reversed.\n\n    seq_lengths : tvm.te.Tensor\n       A 1D Tensor with length a.dims[batch_axis]\n       Must be one of the following types: int32, int64\n       if seq_lengths[i] > a.dims[seq_axis], it is rounded to a.dims[seq_axis]\n       if seq_lengths[i] < 1, it is rounded to 1\n\n    seq_axis : int, optional\n       The axis along which the elements will be reversed. Default is 1.\n\n    batch_axis : int, optional\n       The axis along which the tensor will be sliced. Default is 0.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n       The computed result of same shape and type as of input.\n\n    \"\"\"\n    return cpp.reverse_sequence(a, seq_lengths, seq_axis, batch_axis)\n\n\ndef strided_slice(a, begin, end, strides=None, axes=None, slice_mode=\"end\"):\n    \"\"\"Slice of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be sliced.\n\n    begin : list of int\n        The indices to begin with in the slicing.\n\n    end : list of int\n        Indices indicating end of the slice.\n\n    strides : list of int, optional\n        Specifies the stride values, it can be negative\n        in that case, the input tensor will be reversed\n        in that particular axis.\n\n    axes : list of int, optional\n        Axes along which slicing is applied. When it is specified, begin, end\n        strides, and axes need to a list of integers of the same length.\n\n    slice_mode : str, optional\n        The slice mode [end, size].\n        end - The ending indices for the slice [default].\n        size - The input strides will be ignored, input end in this mode indicates\n        the sizeof a slice starting at the location specified by begin. If end[i]\n        is -1, all remaining elements in that dimension are included in the slice.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    if (\n        isinstance(begin, tvm.te.Tensor)\n        or isinstance(end, tvm.te.Tensor)\n        or isinstance(strides, tvm.te.Tensor)\n    ):\n        assert axes is None, \"axes argument is not supported by dynamic strided slice yet.\"\n        if not isinstance(begin, tvm.te.Tensor):\n            begin = const_vector(begin)\n        if not isinstance(end, tvm.te.Tensor):\n            end = const_vector(end)\n        if strides is None:\n            strides = [1] * begin.shape[0].value\n        if not isinstance(strides, tvm.te.Tensor):\n            strides = const_vector(strides)\n        return cpp.dynamic_strided_slice(a, begin, end, strides)\n    if strides is None:\n        strides = []\n    if axes is None:\n        axes = []\n    return cpp.strided_slice(a, begin, end, strides, axes, slice_mode)\n\n\n@tvm.te.tag_scope(tag=tag.INJECTIVE + \",strided_set\")\ndef strided_set(a, v, begin, end, strides=None):\n    \"\"\"Set slice of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be sliced.\n\n    v : tvm.te.Tensor\n        The values to set\n\n    begin: tvm.te.Tensor\n        The indices to begin with in the slicing.\n\n    end: tvm.te.Tensor\n        Indices indicating end of the slice.\n\n    strides: tvm.te.Tensor, optional\n        Specifies the stride values, it can be negative\n        in that case, the input tensor will be reversed\n        in that particular axis.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    n = len(a.shape)\n\n    if len(begin.shape) != 1:\n        raise ValueError(\"begin should be a vector\")\n    if not begin.dtype == \"int32\":\n        raise TypeError(\"begin should be int32\")\n    if len(end.shape) != 1:\n        raise ValueError(\"end should be a vector\")\n    if not end.dtype == \"int32\":\n        raise TypeError(\"end should be int32\")\n    if strides is not None:\n        if len(strides.shape) != 1:\n            raise ValueError(\"strides should be a vector\")\n        if not strides.dtype == \"int32\":\n            raise TypeError(\"strides should be int32\")\n\n    def _max(a, b):\n        return tvm.tir.Select(a > b, a, b)\n\n    if strides is None:\n        strides = [tvm.tir.const(1, \"int32\")] * n\n    else:\n        strides = [\n            tvm.tir.if_then_else(strides.shape[0] > i, strides[i], tvm.tir.const(1, \"int32\"))\n            for i in range(n)\n        ]\n\n    begin = [\n        tvm.tir.if_then_else(\n            begin.shape[0] > i,\n            begin[i],\n            tvm.tir.Select(strides[i] > 0, tvm.tir.const(0, \"int32\"), a.shape[i]),\n        )\n        for i in range(n)\n    ]\n    end = [\n        tvm.tir.if_then_else(\n            end.shape[0] > i,\n            end[i],\n            tvm.tir.Select(strides[i] > 0, a.shape[i] + 1, -(a.shape[i] + 1)),\n        )\n        for i in range(n)\n    ]\n\n    # Convert negative indexes\n    for i in range(n):\n        begin[i] = tvm.tir.if_then_else(begin[i] < 0, begin[i] + a.shape[i], begin[i])\n        end[i] = tvm.tir.if_then_else(end[i] < 0, end[i] + a.shape[i], end[i])\n\n    def _select(*indices):\n        from_val = []\n        index_tuple = []\n        for i in range(n):\n            from_val.append(within_index(begin[i], end[i], strides[i], indices[i]))\n            index_tuple.append(make_idx(begin[i], end[i], strides[i], a.shape[i], indices[i]))\n        return tvm.tir.if_then_else(tvm.tir.all(*from_val), v(*index_tuple), a(*indices))\n\n    return te.compute(a.shape, _select, name=\"strided_set\")\n\n\ndef reshape(a, newshape):\n    \"\"\"Reshape the array\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be reshaped\n    newshape : tuple of ints\n        The new shape\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.reshape(a, newshape)\n\n\ndef squeeze(a, axis=None):\n    \"\"\"Remove single-dimensional entries from the shape of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n\n    axis : None or int or tuple of ints, optional\n        Selects a subset of the single-dimensional entries in the shape.\n        If an axis is selected with shape entry greater than one, an error is raised.\n\n    Returns\n    -------\n    squeezed : tvm.te.Tensor\n    \"\"\"\n    return cpp.squeeze(a, axis)\n\n\ndef concatenate(a_tuple, axis=0):\n    \"\"\"Join a sequence of arrays along an existing axis.\n\n    Parameters\n    ----------\n    a_tuple : tuple of tvm.te.Tensor\n        The arrays to concatenate\n\n    axis : int, optional\n        The axis along which the arrays will be joined. Default is 0.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.concatenate(a_tuple, axis)\n\n\ndef stack(a, axis):\n    \"\"\"Repeats the whole array multiple times.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be stacked.\n\n    axis : int, optional\n        The axis in the result array along which the input arrays are stacked.\n\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.stack(a, axis)\n\n\ndef split(ary, indices_or_sections, axis=0):\n    \"\"\"Split an array into multiple sub-arrays.\n\n    Parameters\n    ----------\n    ary : tvm.te.Tensor\n\n    indices_or_sections : int or 1-D array\n\n    axis : int\n\n    Returns\n    -------\n    ret : tuple of tvm.te.Tensor\n    \"\"\"\n    return cpp.split(ary, indices_or_sections, axis)\n\n\ndef take(a, indices, axis=None, batch_dims=0, mode=\"clip\"):\n    \"\"\"Take elements from an array along an axis.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The source array.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    axis : int, optional\n        The axis over which to select values. By default,\n        the flattened input array is used.\n\n    batch_dims : int\n        The number of batch dimensions. By default is 0.\n\n    mode : str, optional\n        Specifies how out-of-bound indices will behave.\n        clip - clip to the range (default)\n        wrap - wrap around the indices\n        fast - no clip or wrap around (user must make sure indices are in-bound)\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    if axis is None:\n        return cpp.take(a, indices, int(batch_dims), mode)\n    return cpp.take(a, indices, int(batch_dims), int(axis), mode)\n\n\n@tvm.target.generic_func\ndef take_legalize(attrs, inputs, types):\n    \"\"\"Legalizes dyn.topk op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current op\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    if tvm.relay.ty.is_dynamic(types[0]):\n        return tvm.relay.take(tvm.relay.annotation.stop_fusion(inputs[0]), inputs[1], **attrs)\n    return None\n\n\ndef gather(data, axis, indices):\n    \"\"\"Gather values along given axis from given indices.\n\n    E.g. for a 3D tensor, output is computed as:\n\n    .. code-block:: python\n\n        out[i][j][k] = data[indices[i][j][k]][j][k]  # if axis == 0\n        out[i][j][k] = data[i][indices[i][j][k]][k]  # if axis == 1\n        out[i][j][k] = data[i][j][indices[i][j][k]]  # if axis == 2\n\n    ``indices`` must have same shape as ``data``, except at dimension ``axis``\n    which must just be not null. Output will have same shape as ``indices``.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The input data to the operator.\n\n    axis: int\n        The axis along which to index.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.gather(data, axis, indices)\n\n\ndef gather_nd(a, indices):\n    \"\"\"Gather elements from a n-dimension array..\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The source array.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.gather_nd(a, indices)\n\n\ndef matmul(a, b, transp_a=False, transp_b=False):\n    \"\"\"\n    Creates an operation that calculates a matrix multiplication (row-major notation):\n    A(i, k) * B(k, j)\n    if trans_a == trans_b, the usual transposed combinations, otherwise\n\n    Parameters\n    ----------\n    a : The matrix A\n    b : The matrix B\n    trans_a : Is A's layout transposed?\n    trans_b : Is B's layout transposed?\n\n    Returns\n    -------\n    A Tensor whose op member is the matmul operation\n    \"\"\"\n    return cpp.matmul(a, b, transp_a, transp_b)\n\n\ndef tensordot(a, b, axes):\n    \"\"\"A generalization of matrix multiplication to tensor.\n\n    Parameters\n    ----------\n    a : The tensor A\n    b : The tensor B\n    axes : The number of dimensions to reduce over\n\n    Returns\n    -------\n    A Tensor computing the result\n    \"\"\"\n    if isinstance(axes, int):\n        return cpp.tensordot(a, b, axes)\n    if isinstance(axes[0], int):\n        return cpp.tensordot(a, b, (axes[0],), (axes[1],))\n    return cpp.tensordot(a, b, axes[0], axes[1])\n\n\ndef arange(start, stop=None, step=1, dtype=\"float32\"):\n    \"\"\"Creates a tensor with evenly spaced values within a given interval.\n\n    Parameters\n    ----------\n    start : tvm.Expr, optional\n        Start of interval. The interval includes this value. The default start\n        value is 0.\n\n    stop : tvm.Expr\n        Stop of interval. The interval does not include this value.\n\n    step : tvm.Expr, optional\n        Spacing between values. The default step size is 1.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The resulting tensor.\n    \"\"\"\n    if stop is None:\n        stop = start\n        start = 0\n    return cpp.arange(start, stop, step, dtype)\n\n\ndef meshgrid(a_tuple, indexing):\n    \"\"\"Create coordinate matrices from coordinate vectors.\n\n    Parameters\n    ----------\n    a_tuple : tuple of tvm.te.Tensor\n        The coordinate vectors or scalars.\n\n    indexing : str\n        Indexing mode, either \"ij\" or \"xy\".\n\n    Returns\n    -------\n    result : tuple of tvm.te.Tensor\n        The resulting grids for each axis.\n    \"\"\"\n    return cpp.meshgrid(a_tuple, indexing)\n\n\ndef repeat(a, repeats, axis):\n    \"\"\"Repeats elements of an array.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be repeated.\n\n    repeats: int, required\n        Number of repetitions for each element\n\n    axis: int, optional\n        The axis along which to repeat values\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.repeat(a, repeats, axis)\n\n\ndef tile(a, reps):\n    \"\"\"Repeats the whole array multiple times.\n\n    Parameters\n    ----------\n    a : tvm.te.Tensor\n        The tensor to be tiled.\n\n    reps: tuple of ints, required\n        The number of times for repeating the tensor\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    return cpp.tile(a, reps)\n\n\ndef layout_transform(array, src_layout, dst_layout):\n    \"\"\"Transform the layout according to src_layout and dst_layout\n\n    Parameters\n    ----------\n    array : tvm.te.Tensor\n        The source array.\n\n    src_layout : str\n        the source layout.\n\n    dst_layout : str\n        the destination layout.\n    \"\"\"\n    return cpp.layout_transform(array, src_layout, dst_layout)\n\n\ndef shape(array, dtype=\"int32\"):\n    \"\"\"Get the shape of input array\n\n    Parameters\n    ----------\n    array : tvm.te.Tensor\n        The source tensor.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The resulting tensor.\n    \"\"\"\n    return cpp.shape(array, dtype)\n\n\ndef sequence_mask(data, valid_length, mask_value=0, axis=0):\n    \"\"\"Sets all elements outside the expected length of the sequence to a constant value.\n\n    This function takes an n-dimensional input array of the form [MAX_LENGTH, batch_size, ...] or\n    [batch_size, MAX_LENGTH, ...] and returns an array of the same shape.\n\n    `axis` means the axis of the length dimension and can only be 0 or 1. If `axis` is 0,\n    the data must have shape [MAX_LENGTH, batch_size, ...]. Otherwise (axis=1), the data must have\n    shape [batch_size, MAX_LENGTH, ...].\n\n    `valid_length` gives the length of each sequence. `valid_length` should be\n    a 1D int array with positive ints and has dimension [batch_size,].\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        N-D with shape [MAX_LENGTH, batch_size, ...] or [batch_size, MAX_LENGTH, ...]\n        depending on the value of `axis`.\n\n    valid_length : tvm.te.Tensor\n        1-D with shape [batch_size,]\n\n    mask_value : float, optional\n        The masking value, default 0\n\n    axis : int, optional\n        axis of the length dimension, must be 0 or 1, default 0\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        N-D with shape [MAX_LENGTH, batch_size, ...] or [batch_size, MAX_LENGTH, ...]\n        depending on the value of `axis`.\n    \"\"\"\n\n    assert len(data.shape) >= 2, \"only support data.ndim >= 2, received data.shape = {}\".format(\n        data.shape\n    )\n    assert axis in (0, 1), \"only support axis = 0, 1, received axis = {}\".format(axis)\n    return cpp.sequence_mask(data, valid_length, mask_value, axis)\n\n\ndef ndarray_size(array, dtype=\"int32\"):\n    \"\"\"Get the number of elements of input array\n\n    Parameters\n    ----------\n    array : tvm.te.Tensor\n        The source tensor.\n\n    dtype : str, optional\n        The target data type.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        The resulting tensor.\n    \"\"\"\n    return cpp.ndarray_size(array, dtype)\n\n\ndef where(condition, x, y):\n    \"\"\"Get the elements, either from x or y, depending on the condition.\n\n    Parameters\n    ----------\n    condition : tvm.te.Tensor\n        The condition array.\n\n    x : tvm.te.Tensor\n        First array to be selected.\n\n    y : tvm.te.Tensor\n        Second array to be selected.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        A Tensor selected from x or y depending on condition.\n    \"\"\"\n    return cpp.where(condition, x, y)\n\n\ndef one_hot(indices, on_value, off_value, depth, axis, dtype):\n    \"\"\"\n    Returns a one-hot tensor where the locations repsented by indices take value on_value,\n    other locations take value off_value.\n    Final dimension is <indices outer dimensions> x depth x <indices inner dimensions>.\n\n    Parameters\n    ----------\n    indices : tvm.te.Tensor\n        Locations to set to on_value.\n\n    on_value : tvm.te.Tensor\n        Value to fill at indices.\n\n    off_value : tvm.te.Tensor\n        Value to fill at all other positions besides indices.\n\n    depth : int\n        Depth of the one-hot dimension.\n\n    axis : int\n        Axis to fill.\n\n    dtype : relay.DataType\n        Data type of the output tensor.\n\n    Returns\n    -------\n    ret : relay.Expr\n        The one-hot tensor.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        indices = [0, 1, 2]\n\n        relay.one_hot(indices, 3) =\n            [[1, 0, 0],\n             [0, 1, 0],\n             [0, 0, 1]]\n    \"\"\"\n    return cpp.one_hot(indices, on_value, off_value, depth, axis, dtype)\n\n\ndef unravel_index(indices, shape):\n    \"\"\"Convert a flat index or array of flat indices into a tuple of coordinate arrays.\n\n    Example::\n    -   unravel_index([22, 41, 37], [7, 6]) = [[3, 6, 6], [4, 5, 1]]\n\n    Parameters\n    ----------\n    indices : relay.Expr\n        An integer array containing indices.\n\n    shape : relay.Expr\n        The shape of the array.\n\n    Returns\n    -------\n    result : relay.Expr\n        The tuple of coordinate arrays.\n    \"\"\"\n\n    return cpp.unravel_index(indices, shape)\n\n\ndef sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0):\n    \"\"\"Converts a sparse representation into a dense tensor.\n\n    Example::\n    -   sparse_to_dense([[0, 0], [1, 1]], [2, 2], [3, 3], 0) = [[3, 0], [0, 3]]\n\n    Parameters\n    ----------\n    sparse_indices : tvm.te.Tensor\n        A 0-D, 1-D, or 2-D tensor of integers containing location of sparse values.\n\n    output_shape : A list of integers\n        Shape of the dense output tensor.\n\n    sparse_values : tvm.te.Tensor\n        A 0-D or 1-D tensor containing the sparse values for the sparse indices.\n\n    default_value : tvm.te.Tensor\n        A 0-D tensor containing the default value for the remaining locations.\n        Defaults to 0.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        Dense tensor of shape output_shape. Has the same type as sparse_values.\n    \"\"\"\n\n    return cpp.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value)\n\n\ndef matrix_set_diag(data, diagonal, k=0, align=\"RIGHT_LEFT\"):\n    \"\"\"\n    Returns a tensor with the diagonals of input tensor replaced with the provided diagonal values.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        Input Tensor.\n\n    diagonal : relay.Expr\n        Values to be filled in the diagonal.\n\n    k : int or tuple of int, optional\n        Diagonal Offset(s). The diagonal or range of diagonals to set. (0 by default)\n        Positive value means superdiagonal, 0 refers to the main diagonal, and\n        negative value means subdiagonals. k can be a single integer (for a single diagonal)\n        or a pair of integers specifying the low and high ends of a matrix band.\n        k[0] must not be larger than k[1].\n\n    align : string, optional\n        Some diagonals are shorter than max_diag_len and need to be padded.\n        align is a string specifying how superdiagonals and subdiagonals should be aligned,\n        respectively. There are four possible alignments: \"RIGHT_LEFT\" (default), \"LEFT_RIGHT\",\n        \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals to the right\n        (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing\n        format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n    Returns\n    -------\n    result : relay.Expr\n        New tensor with given diagonal values.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [[[7, 7, 7, 7],\n                 [7, 7, 7, 7],\n                 [7, 7, 7, 7]],\n                [[7, 7, 7, 7],\n                 [7, 7, 7, 7],\n                 [7, 7, 7, 7]]]\n\n        diagonal = [[1, 2, 3],\n                    [4, 5, 6]]\n\n        topi.matrix_set_diag(input, diagonal) =\n            [[[1, 7, 7, 7],\n              [7, 2, 7, 7],\n              [7, 7, 3, 7]],\n             [[4, 7, 7, 7],\n              [7, 5, 7, 7],\n              [7, 7, 6, 7]]]\n    \"\"\"\n    if isinstance(k, (tuple, list)):\n        k_one = k[0]\n        if len(k) >= 2:\n            k_two = k[1]\n        else:\n            k_two = k[0]\n    else:\n        k_one = k\n        k_two = k\n\n    super_diag_right_align = align[:5] == \"RIGHT\"\n    sub_diag_right_align = align[-5:] == \"RIGHT\"\n\n    return cpp.matrix_set_diag(\n        data, diagonal, k_one, k_two, super_diag_right_align, sub_diag_right_align\n    )\n\n\ndef adv_index(data, indices):\n    \"\"\"Numpy style indexing with tensors.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data.\n\n    indices : A list of tvm.te.Tensor\n        Tensor index.\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        Output tensor\n    \"\"\"\n    return cpp.adv_index(data, indices)\n\n\n@hybrid.script\ndef invert_permutation(data):\n    \"\"\"Computes the inverse permutation of data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data\n\n    Returns\n    -------\n    result : tvm.te.Tensor\n        Output tensor\n\n    Examples\n    --------\n    .. code-block:: python\n\n        data = [3, 4, 0, 2, 1]\n        topi.invert_permutation(data) = [2, 4, 3, 0, 1]\n    \"\"\"\n    result = output_tensor(data.shape, data.dtype)\n    nums = data.shape[0]\n    for ind in range(nums):\n        r_ind = data[ind]\n        result[r_ind] = ind\n    return result\n\n\ndef sliding_window(data, axis, window_shape, strides):\n    \"\"\"Slide a window over the data tensor.\n\n    Parameters\n    ----------\n    data : relay.Expr\n        The input data to the operator.\n\n    axis : int\n        What axis the window begins sliding over. Window will be slid over\n        this axis and all following axes. The axis value determines the window\n        shape (and thus, the number of strides): window shape and strides must\n        both be of length `data.ndim-axis`.\n\n    window_shape : List[int]\n        The window shape to form over the input. Window shape must be of length\n        `data.ndim-axis`.\n\n    strides : List[int]\n        How to stride the window along each dimension. Strides must be of length\n        `data.ndim-axis`.\n\n    Returns\n    -------\n    result : relay.Expr\n        The resulting tensor.\n    \"\"\"\n    return cpp.sliding_window(data, axis, window_shape, strides)\n\n\ndef trilu(data, k, upper):\n    \"\"\"\n    Given a 2-D matrix or batches of 2-D matrices, returns the\n    upper or lower triangular part of the tensor.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor\n        The tensor that trilu will be applied to. Must be either\n        a 2D matrix or a tensor of batches of 2D matrices.\n\n    k: tvm.te.Tensor\n        The number of diagonals above or below the main diagonal\n        to exclude or include.\n\n    upper: bool\n        If True, only upper triangular values of input are kept,\n        if False, the lower triangular values are kept.\n\n\n    Returns\n    -------\n    ret : relay.Expr\n        The new tensor with appropriate diagonals set to zero.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        x = [[0, 1, 2],\n             [3, 4, 5],\n             [6, 7, 8]]\n\n        relay.trilu(x, True, 0) =\n            [[0, 1, 2],\n             [0, 4, 5],\n             [0, 0, 8]]\n    \"\"\"\n    # Make sure datatype is consistent.\n    if k.dtype != \"int32\":\n        k = tvm.tir.Cast(\"int32\", k)\n\n    # Check either above or below diagonal depending on upper.\n    check_op = tvm.tir.GE\n    if upper:\n        check_op = tvm.tir.LE\n\n    def _apply_trilu(*indices):\n        row_index = indices[-2]\n        col_index = indices[-1]\n        # promote row & col indices\n        if row_index.dtype != col_index.dtype:\n            target_type = (col_index + row_index).dtype\n            if row_index.dtype != target_type:\n                row_index = tvm.tir.Cast(target_type, row_index)\n            else:\n                col_index = tvm.tir.Cast(target_type, col_index)\n        other_indices = indices[:-2]\n        check_position = check_op(row_index, col_index - k)\n        value = data(*other_indices, row_index, col_index)\n        return tvm.tir.Select(check_position, value, tvm.tir.const(0, data.dtype))\n\n    return te.compute(data.shape, _apply_trilu, name=\"trilu\", tag=topi.tag.ELEMWISE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/unique.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Unique operator\"\"\"\nfrom tvm import te, tir\nfrom ..te import hybrid\nfrom .scan import cumsum\nfrom .sort import sort, argsort\n\n\ndef _calc_adjacent_diff_ir(data, output, binop=tir.Sub):\n    \"\"\"Low level IR to calculate adjacent difference in an 1-D array.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input 1-D Buffer.\n\n    output: Buffer\n        A buffer to store adjacent difference, of the same shape as data. The adjacent difference\n        is defined as: output[0] = 0, output[i] = binop(data[i], data[i-1])\n        where i > 0 and i < len(data).\n\n    binop: function, optional\n        A binary associative op to use for calculating adjacent difference. The function takes two\n        TIR expressions and produce a new TIR expression. By default it uses tvm.tir.Sub to\n        compute the adjacent difference.\n    \"\"\"\n    ib = tir.ir_builder.create()\n    data_ptr = ib.buffer_ptr(data)\n    output_ptr = ib.buffer_ptr(output)\n    with ib.for_range(0, data.shape[0], kind=\"parallel\") as i:\n        with ib.if_scope(i == 0):\n            output_ptr[0] = 0\n        with ib.else_scope():\n            output_ptr[i] = tir.Cast(output.dtype, binop(data_ptr[i], data_ptr[i - 1]))\n    return ib.get()\n\n\ndef _calc_adjacent_diff(data, out_dtype=\"int32\", binop=tir.Sub):\n    \"\"\"Function calculate adjacent difference in an 1-D array.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input 1-D tensor.\n\n    output_dtype : str\n        The output tensor data type.\n\n    binop: function, optional\n        A binary associative op to use for calculating difference. The function takes two\n        TIR expressions and produce a new TIR expression. By default it uses tvm.tir.Sub to\n        compute the adjacent difference.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        1-D tensor storing the adjacent difference of the input tensor. The adjacent difference\n        is defined as: output[0] = 0, output[i] = binop(data[i], data[i-1])\n        where i > 0 and i < len(data).\n    \"\"\"\n    return te.extern(\n        [data.shape],\n        [data],\n        lambda ins, outs: _calc_adjacent_diff_ir(ins[0], outs[0], binop=binop),\n        dtype=[out_dtype],\n        name=\"_calc_adjacent_diff\",\n        tag=\"_calc_adjacent_diff_cpu\",\n    )\n\n\n@hybrid.script\ndef _calc_num_unique(inc_scan):\n    \"\"\"Helper function to get the number of unique elements fron inc_scan tensor\"\"\"\n    output = output_tensor((1,), \"int32\")\n    output[0] = inc_scan[inc_scan.shape[0] - 1] + int32(1)\n    return output\n\n\ndef _calc_unique_ir(\n    data, argsorted_indices, inc_scan, index_converter, unique_elements, inverse_indices, counts\n):\n    \"\"\"Low level IR to calculate unique elements, inverse indices, and counts (optional) of\n    unique elements of 1-D array.\n\n    Parameters\n    ----------\n    data : Buffer\n        Input 1-D Buffer.\n\n    argsorted_indices : Buffer\n        A buffer that stores the argsorted indices of the input data.\n\n    inc_scan : Buffer\n        A buffer that stores the inclusive scan of the binary tir.NE adjacent difference\n        of the sorted data.\n\n    index_converter (optional) : Buffer\n        An optional index converter that transforms the unique element index\n        such that new_idx = index_converter[old_idx].\n\n    unique_elements : Buffer\n        A buffer that stores the unique elements.\n\n    inverse_indices : Buffer\n        A buffer that stores the index of each input data element in the unique element array.\n\n    counts (optional) : Buffer\n        A buffer that stores the count of each unique element.\n    \"\"\"\n    ib = tir.ir_builder.create()\n    data_ptr = ib.buffer_ptr(data)\n    argsorted_indices_ptr = ib.buffer_ptr(argsorted_indices)\n    inc_scan_ptr = ib.buffer_ptr(inc_scan)\n    unique_elements_ptr = ib.buffer_ptr(unique_elements)\n    inverse_indices_ptr = ib.buffer_ptr(inverse_indices)\n\n    index_converter_ptr = None\n    if isinstance(index_converter, tir.Buffer):\n        index_converter_ptr = ib.buffer_ptr(index_converter)\n\n    if isinstance(counts, tir.Buffer):\n        counts_ptr = ib.buffer_ptr(counts)\n        # use indices_ptr as a tmp buffer to store tids with inc_scan[tid] != inc_scan[tid-1]\n        unique_seq_indices_ptr = ib.buffer_ptr(inverse_indices)\n\n    data_length = data.shape[0]\n\n    # if need to return counts\n    if isinstance(counts, tir.Buffer):\n        num_unique = inc_scan_ptr[inc_scan.shape[0] - 1] + 1\n        num_elements = data.shape[0]\n        unique_seq_indices_ptr[num_unique - 1] = num_elements\n        with ib.new_scope():\n            with ib.for_range(0, data_length, kind=\"parallel\") as i:\n                with ib.if_scope(i > 0):\n                    with ib.if_scope(inc_scan_ptr[i] != inc_scan_ptr[i - 1]):\n                        unique_seq_indices_ptr[inc_scan_ptr[i] - 1] = i\n        with ib.new_scope():\n            with ib.for_range(0, num_unique, kind=\"parallel\") as i:\n                unique_idx = i if not index_converter_ptr else index_converter_ptr[i]\n                with ib.if_scope(i == 0):\n                    counts_ptr[unique_idx] = unique_seq_indices_ptr[i]\n                with ib.else_scope():\n                    counts_ptr[unique_idx] = (\n                        unique_seq_indices_ptr[i] - unique_seq_indices_ptr[i - 1]\n                    )\n    # calculate unique elements and inverse indices\n    with ib.new_scope():\n        with ib.for_range(0, data_length, kind=\"parallel\") as i:\n            data_idx = argsorted_indices_ptr[i]\n            unique_idx = (\n                inc_scan_ptr[i] if not index_converter_ptr else index_converter_ptr[inc_scan_ptr[i]]\n            )\n            inverse_indices_ptr[data_idx] = unique_idx\n            with ib.if_scope(i == 0):\n                unique_elements_ptr[unique_idx] = data_ptr[data_idx]\n            with ib.else_scope():\n                with ib.if_scope(inc_scan_ptr[i] != inc_scan_ptr[i - 1]):\n                    unique_elements_ptr[unique_idx] = data_ptr[data_idx]\n    return ib.get()\n\n\n@hybrid.script\ndef _calc_first_occurence(argsorted_indices, inc_scan):\n    \"\"\"Hybrid script to calculate the first occurence of each unique element in the input data.\n\n    Parameters\n    ----------\n    argsorted_indices : tvm.te.Tensor\n        A tensor that stores the argsorted indices of the input data.\n\n    inc_scan : tvm.te.Tensor\n        A tensor that stores the inclusive scan of the binary tir.NE adjacent difference\n        of the sorted data.\n\n    first_occurence : tvm.te.Tensor\n        A tensor that stores the first occurence of each unique element in the input data.\n    \"\"\"\n    first_occurence = output_tensor(argsorted_indices.shape, \"int32\")\n    for i in parallel(argsorted_indices.shape[0]):\n        first_occurence[i] = argsorted_indices.shape[0]\n    for i in parallel(argsorted_indices.shape[0]):\n        if i == 0 or inc_scan[i] != inc_scan[i - 1]:\n            first_occurence[inc_scan[i]] = argsorted_indices[i]\n    return first_occurence\n\n\ndef unique(data, is_sorted=True, return_counts=False):\n    \"\"\"\n    Find the unique elements of a 1-D tensor. Please note `output` and `counts` are all padded to\n    have the same length of `data` and element with index >= num_unique[0] has undefined value.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        A 1-D tensor of integers.\n\n    sorted : bool\n        Whether to sort the unique elements in ascending order before returning as output.\n\n    return_counts : bool\n        Whether to return the count of each unique element.\n\n    Returns\n    -------\n    unique : tvm.te.Tensor\n        A 1-D tensor containing the unique elements of the input data tensor. The same size as\n        the input data. If there are less unique elements than input data, the end of the tensor\n        is padded with zeros.\n\n    indices : tvm.te.Tensor\n        A 1-D tensor. The same size as output. For each entry in output, it contains\n        the index of its first occurence in the input data. The end of the tensor is padded\n        with the length of the input data.\n\n    inverse_indices : tvm.te.Tensor\n        A 1-D tensor. For each entry in data, it contains the index of that data element in\n        the unique array. (Note that inverse_indices is very similar to indices if output is not\n        sorted.)\n\n    num_unique : tvm.te.Tensor\n        A 1-D tensor with size=1 containing the number of unique elements in the input data tensor.\n\n    counts (optional) : tvm.te.Tensor\n        A 1-D tensor containing the count of each unique element in the output.\n\n    Examples\n    --------\n    .. code-block:: python\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, False)\n        output          =  [4, 5, 1, 2, 3, _, _, _]\n        indices         =  [0, 1, 2, 3, 4, _, _, _]\n        inverse_indices =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique      =  [5]\n\n        [output, indices, num_unique, counts] = unique([4, 5, 1, 2, 3, 3, 4, 5], False, True)\n        output          =  [4, 5, 1, 2, 3, _, _, _]\n        indices         =  [0, 1, 2, 3, 4, _, _, _]\n        inverse_indices =  [0, 1, 2, 3, 4, 4, 0, 1]\n        num_unique      =  [5]\n        counts          =  [2, 2, 1, 1, 2, _, _, _]\n\n        [output, indices, num_unique] = unique([4, 5, 1, 2, 3, 3, 4, 5], True)\n        output          =  [1, 2, 3, 4, 5, _, _, _]\n        indices         =  [2, 3, 4, 0, 1, _, _, _]\n        inverse_indices =  [3, 4, 0, 1, 2, 2, 3, 4]\n        num_unique      =  [5]\n    \"\"\"\n    sorted_data = sort(data)\n    argsorted_indices = argsort(data, dtype=\"int32\")\n    # adjacent difference\n    adjacent_diff = _calc_adjacent_diff(sorted_data, \"int32\", tir.NE)\n    # inclusive scan\n    inc_scan = cumsum(adjacent_diff, dtype=\"int32\", exclusive=0)\n    # total number of unique elements\n    num_unique_elements = _calc_num_unique(inc_scan)\n    # prepare outputs\n    if return_counts:\n        out_data_shape = [data.shape] * 3\n        out_dtypes = [data.dtype, \"int32\", \"int32\"]\n    else:\n        out_data_shape = [data.shape] * 2\n        out_dtypes = [data.dtype, \"int32\"]\n    # prepare inputs and fcompute\n\n    first_occurence = _calc_first_occurence(argsorted_indices, inc_scan)\n    if is_sorted:\n        in_data = [data, argsorted_indices, inc_scan]\n        if return_counts:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, None, *outs)\n        else:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, None, *outs, None)\n\n        indices = first_occurence\n    else:\n        # calculate index converter by sorting unique elements by their first occurence\n        argsorted_first_occurence = argsort(first_occurence, dtype=\"int32\")\n        index_converter = argsort(argsorted_first_occurence, dtype=\"int32\")\n        in_data = [data, argsorted_indices, inc_scan, index_converter]\n        if return_counts:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, *outs)\n        else:\n            fcompute = lambda ins, outs: _calc_unique_ir(*ins, *outs, None)\n        # First occurence is in order of sorted unique output, if we sort the first_occurence array\n        # we get the correct result\n        indices = sort(first_occurence)\n\n    outs = te.extern(\n        out_data_shape,\n        in_data,\n        fcompute,\n        dtype=out_dtypes,\n        name=\"_calc_unique\",\n        tag=\"_calc_unique_cpu\",\n    )\n    if return_counts:\n        return [outs[0], indices, outs[1], num_unique_elements, outs[2]]\n    return [outs[0], indices, outs[1], num_unique_elements]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Common topi utilities\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom numbers import Integral\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm.tir import bijective_layout, layout\n\nfrom . import cpp, tag\n\n\nclass InvalidShapeError(ValueError):\n    \"\"\"Invalid shape for a topi function. i.e. call winograd template for non-3x3 kernel)\"\"\"\n\n\ndef ncw_pack_layout(layout_info):\n    \"\"\"Check whether the layout type is NCWinic\"\"\"\n    return layout_info[:3] == \"NCW\" and \"c\" in layout_info and \"n\" in layout_info\n\n\ndef ncw_xc_layout(layout_info):\n    \"\"\"Check whether the layout type is NCWxc\"\"\"\n    return layout_info[:3] == \"NCW\" and \"c\" in layout_info and layout_info[3:-1].isnumeric()\n\n\ndef nchw_pack_layout(layout_info):\n    \"\"\"Check whether the layout type is NCHWinic\"\"\"\n    return layout_info[:4] == \"NCHW\" and \"c\" in layout_info and \"n\" in layout_info\n\n\ndef nchw_xc_layout(layout_info):\n    \"\"\"Check whether the layout type is NCHWxc\"\"\"\n    return layout_info[:4] == \"NCHW\" and \"c\" in layout_info and layout_info[4:-1].isnumeric()\n\n\ndef traverse_inline(s, final_op, callback):\n    \"\"\"Traverse computation graph and do auto inline\n\n    Parameters\n    ----------\n    s: schedule\n        The schedule\n    final_op: Operation\n        The final output operator.\n    callback: callable\n        The callback function on each op\n    \"\"\"\n    visited = set()\n\n    def _traverse(op):\n        if op in visited:\n            return\n        visited.add(op)\n        if tag.is_injective(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    _traverse(tensor.op)\n        callback(op)\n\n    _traverse(final_op)\n\n\ndef prod(x):\n    \"\"\"Get the product of every items in the tuple.\n\n    Parameters\n    ----------\n    x: tuple\n        Input tuple\n\n    Returns\n    -------\n    value : Expr\n        The result value\n    \"\"\"\n    if not x:\n        return tvm.tir.const(1, \"int32\")\n    res = x[0]\n    for i in range(1, len(x)):\n        res = res * x[i]\n    return res\n\n\ndef get_const_int(expr):\n    \"\"\"Verifies expr is integer and get the constant value.\n\n    Parameters\n    ----------\n    expr : tvm.Expr or int\n        The input expression.\n\n    Returns\n    -------\n    out_value : int\n        The output.\n    \"\"\"\n    if isinstance(expr, Integral):\n        return expr\n    if not isinstance(expr, tvm.tir.IntImm):\n        ana = tvm.arith.Analyzer()\n        expr = ana.simplify(expr)\n    if not isinstance(expr, tvm.tir.IntImm):\n        raise ValueError(\"Expect value to be constant int\")\n    return int(expr.value)\n\n\ndef get_const_float(expr):\n    \"\"\"Verifies expr is a floating point and get the constant value.\n\n    Parameters\n    ----------\n    expr : tvm.Expr or float\n        The input expression.\n\n    Returns\n    -------\n    out_value : float\n        The output.\n    \"\"\"\n    if isinstance(expr, float):\n        return float(expr)\n    if not isinstance(expr, tvm.tir.FloatImm):\n        ana = tvm.arith.Analyzer()\n        expr = ana.simplify(expr)\n    if not isinstance(expr, tvm.tir.FloatImm):\n        raise ValueError(\"Expect value to be constant float\")\n    return float(expr.value)\n\n\ndef equal_const_int(expr, value):\n    \"\"\"Returns if expr equals value.\n\n    Parameters\n    ----------\n    expr : tvm.Expr\n        The input expression.\n\n    Returns\n    -------\n    equal : bool\n        Whether they equals.\n    \"\"\"\n    if isinstance(expr, Integral):\n        return expr == value\n    if not isinstance(expr, tvm.tir.IntImm):\n        ana = tvm.arith.Analyzer()\n        expr = ana.simplify(expr)\n    if not isinstance(expr, tvm.tir.IntImm):\n        return False\n    return expr.value == value\n\n\ndef get_const_tuple(in_tuple):\n    \"\"\"Verifies input tuple is IntImm or Var, returns tuple of int or Var.\n\n    Parameters\n    ----------\n    in_tuple : tuple of Expr\n        The input.\n\n    Returns\n    -------\n    out_tuple : tuple of int\n        The output.\n    \"\"\"\n    ret = []\n    ana = None\n    for elem in in_tuple:\n        if isinstance(elem, (tvm.tir.Var, tvm.tir.expr.Any)):\n            ret.append(elem)\n        elif not isinstance(elem, (tvm.tir.IntImm, int)):\n            ana = tvm.arith.Analyzer() if ana is None else ana\n            elem = ana.simplify(elem)\n            if not isinstance(elem, tvm.tir.IntImm):\n                ret.append(elem)\n            else:\n                ret.append(get_const_int(elem))\n        else:\n            ret.append(get_const_int(elem))\n    return tuple(ret)\n\n\ndef const_vector(vector, name=\"const_vector\"):\n    \"\"\"convert a const numpy 1-dimensional vector to tvm tensor\n\n    Parameters\n    ----------\n    vector: numpy.ndarray\n        Const input array\n    name: str, optional\n        The name of output op\n\n    Returns\n    -------\n    tensor: Tensor\n        The created tensor\n    \"\"\"\n    if not isinstance(vector, np.ndarray):\n        vector = np.array(vector)\n    row = vector.shape[0]\n    dtype = str(vector.dtype)\n    idxm = tvm.tir.indexmod\n\n    def select_array(i):\n        now = tvm.tir.const(0.0, dtype)\n        for ii in range(row):\n            now = tvm.tir.Select(\n                tvm.tir.all(idxm(i, row) == ii),\n                tvm.tir.const(vector[ii], dtype),\n                now,\n            )\n        return now\n\n    return te.compute(vector.shape, select_array, name=name)\n\n\ndef get_float_tuple(in_tuple):\n    \"\"\"Verifies input tuple is FloatImm, returns tuple of float.\n\n    Parameters\n    ----------\n    in_tuple : tuple of Expr\n        The input.\n\n    Returns\n    -------\n    out_tuple : tuple of float\n        The output.\n    \"\"\"\n    return tuple(get_const_float(elem) for elem in in_tuple)\n\n\ndef simplify(expr):\n    \"\"\"Simplify the expression if it is Expr, directly return if it is int.\n\n    Parameters\n    ----------\n    expr : Expr or int\n        The input.\n\n    Returns\n    -------\n    out : Expr or int\n        The simplified output\n    \"\"\"\n    return tvm.arith.Analyzer().simplify(expr) if isinstance(expr, tvm.tir.PrimExpr) else expr\n\n\ndef ravel_index(indices, shape):\n    \"\"\"Flatten the index tuple to 1D\n\n    Parameters\n    ----------\n    indices : tuple of int or tvm.tir.IntImm\n        The input coordinates\n\n    shape : tuple of int\n        Shape of the tensor.\n\n    Returns\n    -------\n    idx : int or Expr\n        The index after flattening\n    \"\"\"\n    idx = None\n    for i, (shape_val, ind) in enumerate(zip(shape, indices)):\n        if i != 0:\n            idx = idx * shape_val + ind\n        else:\n            idx = ind\n    return idx\n\n\ndef unravel_index(idx, shape):\n    \"\"\"Convert the flattened ind to the coordinate array\n\n    Parameters\n    ----------\n    idx : int or tvm.tir.IntImm\n        The 1D index\n\n    shape : tuple of int\n        Shape of the tensor\n\n    Returns\n    -------\n    indices : tuple of int or tvm.tir.IntImm\n        Corresponding coordinate of the 1D index\n    \"\"\"\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n    indices = []\n    for i, dim in enumerate(reversed(shape)):\n        if dim == 0:\n            indices.append(0)\n        elif i == len(shape) - 1:\n            # Assuming the index is in-bounds, the last coordinate is\n            # already less than dim, and doesn't need the be remainder\n            # mod dim.\n            indices.append(idx)\n        else:\n            indices.append(idxm(idx, dim))\n            idx = idxd(idx, dim)\n    indices = indices[::-1]\n    return indices\n\n\ndef const_matrix(matrix, name=\"const_matrix\", attrs=None):\n    \"\"\"convert a const numpy 2-dimensional matrix to tvm tensor\n\n    Parameters\n    ----------\n    matrix: numpy.ndarray\n        Const input array\n    name: str, optional\n        The name of output op\n\n    Returns\n    -------\n    tensor: Tensor\n        The created tensor\n    \"\"\"\n    row, col = matrix.shape\n    dtype = str(matrix.dtype)\n    idxm = tvm.tir.indexmod\n\n    def select_array(i, j):\n        now = tvm.tir.const(0.0, dtype)\n        for ii in range(row):\n            for jj in range(col):\n                now = tvm.tir.Select(\n                    tvm.tir.all(idxm(i, row) == ii, idxm(j, col) == jj),\n                    tvm.tir.const(matrix[ii][jj], dtype),\n                    now,\n                )\n        return now\n\n    if attrs is None:\n        attrs = {\n            \"const_matrix\": True,\n            \"schedule_rule\": \"None\",\n        }\n\n    return te.compute(\n        matrix.shape,\n        select_array,\n        name=name,\n        attrs=attrs,\n    )\n\n\ndef get_max_power2_factor(n, max_value=None):\n    \"\"\"Get max factor of n in power of 2. If max_value is specificed, max factor\n    value will be no more max_value,\n\n    Parameter\n    ---------\n    n : int\n        The input value\n\n    max_value : int, optional\n        The max value for the factor\n\n    Returns\n    -------\n    factor : int\n        The max factor in power of 2.\n    \"\"\"\n    x = 1\n    while n % 2 == 0:\n        if max_value is not None and max_value < x * 2:\n            break\n        x *= 2\n        n /= 2\n    return x\n\n\ndef get_shape(src_shape, src_layout, dst_layout):\n    \"\"\"Given a source shape, a source layout and a destination layout, infer\n    the destination shape.\n\n    Parameter\n    ---------\n    src_shape : tuple of int or IntImm\n        Source shape\n\n    src_layout : str or Layout\n        Source layout\n\n    dst_layout : str or Layout\n        Destination layout\n\n    Returns\n    -------\n    dst_shape : tuple of int\n        Destination shape\n    \"\"\"\n    if src_layout == dst_layout:\n        return get_const_tuple(src_shape)\n\n    if isinstance(src_layout, str):\n        src_layout = layout(src_layout)\n    if isinstance(dst_layout, str):\n        dst_layout = layout(dst_layout)\n\n    assert len(src_layout) == len(dst_layout), \"Incompatible layout %s vs %s\" % (\n        src_layout,\n        dst_layout,\n    )\n\n    layout_mapping = bijective_layout(src_layout, dst_layout)\n    dst_indices = layout_mapping.forward_index(tvm.runtime.convert(list(range(len(src_layout)))))\n\n    return get_const_tuple(tuple([src_shape[i.value] for i in dst_indices]))\n\n\ndef within_index(b, e, s, i):\n    \"\"\"Return a boolean value that indicates if i is within the given index.\n\n    Parameters\n    ----------\n    b : Expr\n      beginning of the index\n\n    e : Expr\n      end of the index\n\n    s : Expr\n      strides of index\n\n    i : Expr\n      array position\n\n    Returns\n    -------\n    selected: Expr\n        bool expression that is True is the array position would be selected\n        by the index and False otherwise\n    \"\"\"\n    bc = tvm.tir.Select(s < 0, i <= e, i < b)\n    ec = tvm.tir.Select(s < 0, i > b, i >= e)\n    ss = te.if_then_else(s < 0, ((i - e) + (e % te.abs(s)) + 1) % te.abs(s), (i - b) % s)\n    return tvm.tir.Select(tvm.tir.Or(bc, ec), tvm.tir.const(False), ss.equal(0))\n\n\ndef make_idx(b, e, s, z, i):\n    \"\"\"Return the array position in the selection that corresponds to an\n    array position in the full array.\n\n    The returned value is only meaningful if within_index() returns True\n    for the same set of parameters.\n\n    Parameters\n    ----------\n    b : Expr\n      beginning of the index\n\n    e : Expr\n      end of the index\n\n    s : Expr\n      strides of index\n\n    z : Expr\n      size of the indexed dimension\n\n    i : Expr\n      array position\n\n    Returns\n    -------\n    position: Expr\n        int expression that corresponds to an array position in the selection.\n    \"\"\"\n    bc = tvm.tir.Select(s < 0, i <= e, i < b)\n    ec = tvm.tir.Select(s < 0, i > b, i >= e)\n\n    # Clamp to array size\n    b = tvm.tir.Select(z < b, z - 1, b)\n\n    ss = tvm.tir.if_then_else(s < 0, (b - i) // te.abs(s), (i - b) // s)\n    return tvm.tir.if_then_else(tvm.tir.Or(bc, ec), 88, ss)\n\n\ndef is_empty_shape(shape):\n    \"\"\"Check whether an input shape has dimesion with size 0.\n\n    Parameter\n    ---------\n    shape : list of Expr\n      Input shape\n\n    Returns\n    -------\n    is_empty: bool\n      Whether input shape is empty or has dimesion with size 0.\n    \"\"\"\n    return cpp.utils.is_empty_shape(shape)\n\n\ndef ceil_div(a, b):\n    \"\"\"Return ceil division of a by b\"\"\"\n    return tvm.tir.indexdiv(a + (b - 1), b)\n\n\ndef swap(arr, axis):\n    \"\"\"swap arr[axis] and arr[-1]\"\"\"\n    return arr[:axis] + [arr[-1]] + arr[axis + 1 : -1] + [arr[axis]]\n\n\ndef is_target(names):\n    \"\"\"Return True if the name of the current target is one of provided names\"\"\"\n    names = [names] if isinstance(names, str) else names\n    target = tvm.target.Target.current(allow_none=False)\n    return any(name in target.keys for name in names)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"VISION network operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom . import ssd\nfrom .reorg import *\nfrom .nms import *\nfrom .rcnn import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/nms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-error, invalid-name, no-member, too-many-locals, too-many-arguments, undefined-variable, too-many-nested-blocks, too-many-branches, too-many-statements, too-many-function-args\n\"\"\"Non-maximum suppression operator\"\"\"\nimport tvm\nfrom tvm import te\n\nfrom tvm.te import hybrid\nfrom tvm.tir import if_then_else\n\nfrom ..sort import argsort\nfrom ..math import cast\nfrom ..transform import reshape, gather\nfrom .. import reduction\nfrom ..scan import cumsum\nfrom .nms_util import (\n    binary_search,\n    collect_selected_indices,\n    collect_selected_indices_and_scores,\n    run_all_class_nms,\n)\n\n\n@hybrid.script\ndef hybrid_rearrange_box_out(data, one, batch_size, num_anchors):\n    \"\"\"Hybrid routine to rearrange nms output to\n    move all valid entries to top.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or numpy NDArray\n        NMS output. 3-D tensor with shape\n        [batch_size, num_anchors, 6].\n\n    one: tvm.tir.const\n        Constant one with the same dtype as data.\n\n    batch_size: tvm.tir.IntImm or tvm.tir.Var\n        Batch size. We need to pass it in since hybrid script doesn't support\n        binding variable to symbolic dim.\n\n    num_anchors: tvm.tir.IntImm or tvm.tir.Var\n        Number of anchors.\n\n    Returns\n    -------\n    output : tvm.te.Tensor or numpy NDArray\n        Transformed NMS output. 3-D tensor with shape\n        [batch_size, num_anchors, 6].\n    \"\"\"\n    elem_length = data.shape[2]\n    output = output_tensor((batch_size, num_anchors, elem_length), data.dtype)\n    valid_indices = allocate((batch_size,), \"int32\")\n\n    for i in parallel(batch_size):\n        valid_indices[i] = 0\n        for j in range(num_anchors):\n            if data[i, j, 0] >= 0:\n                for k in range(elem_length):\n                    output[i, valid_indices[i], k] = data[i, j, k]\n                valid_indices[i] += 1\n            if j >= valid_indices[i]:\n                for k in range(elem_length):\n                    output[i, j, k] = -one\n    return output\n\n\n@hybrid.script\ndef hybrid_rearrange_indices_out(data, one, batch_size, num_anchors):\n    \"\"\"Hybrid routine to rearrange nms output to\n    move all valid entries to top.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or numpy NDArray\n        NMS output. 3-D tensor with shape\n        [batch_size, num_anchors, 6] or\n        [batch_size, num_anchors, 5], or 2-D\n        tensor with shape [batch_size, num_anchors].\n\n    one: tvm.tir.const\n        Constant one with the same dtype as data.\n\n    batch_size: tvm.tir.IntImm or tvm.tir.Var\n        Batch size. We need to pass it in since hybrid script doesn't support\n        binding variable to symbolic dim.\n\n    num_anchors: tvm.tir.IntImm or tvm.tir.Var\n        Number of anchors.\n\n    Returns\n    -------\n    output : tvm.te.Tensor or numpy NDArray\n        2-D tensor with shape [batch_size, num_anchors].\n\n    valid_box_count : tvm.te.Tensor or numpy NDArray\n        Tensor with shape [batch_size, 1], indicates\n        the valid number of boxes.\n    \"\"\"\n    valid_box_count = output_tensor((batch_size, 1), \"int32\")\n    output = output_tensor((batch_size, num_anchors), data.dtype)\n    valid_indices = allocate((batch_size,), \"int32\")\n\n    for i in parallel(batch_size):\n        valid_indices[i] = 0\n        for j in range(num_anchors):\n            if data[i, j] >= 0:\n                output[i, valid_indices[i]] = data[i, j]\n                valid_indices[i] += 1\n            if data[i, j] > num_anchors or data[i, j] < -num_anchors:\n                output[i, valid_indices[i]] = 0\n                valid_indices[i] += 1\n            if j >= valid_indices[i]:\n                output[i, j] = -one\n        valid_box_count[i, 0] = valid_indices[i]\n\n    return output, valid_box_count\n\n\n@hybrid.script\ndef hybrid_get_valid_counts(\n    data, score_threshold, id_index, score_index, one, batch_size, num_anchors\n):\n    \"\"\"Hybrid routine to get valid count of bounding boxes\n    given a score threshold. Also moves valid boxes to the\n    top of input data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or numpy NDArray\n        Input data. 3-D tensor with shape [batch_size, num_anchors, 6]\n        or [batch_size, num_anchors, 5].\n\n    score_threshold : tvm.te.Tensor\n        Lower limit of score for valid bounding boxes.\n\n    id_index : tvm.tir.const\n        index of the class categories, -1 to disable.\n\n    score_index: tvm.tir.const\n        Index of the scores/confidence of boxes.\n\n    one: tvm.tir.const\n        Constant one with the same dtype as data.\n\n    batch_size: tvm.tir.IntImm or tvm.tir.Var\n        Batch size. We need to pass it in since hybrid script doesn't support\n        binding variable to symbolic dim.\n\n    num_anchors: tvm.tir.IntImm or tvm.tir.Var\n        Number of anchors.\n\n    Returns\n    -------\n    valid_count : tvm.te.Tensor or numpy NDArray\n        1-D tensor for valid number of boxes.\n\n    out_tensor : tvm.te.Tensor or numpy NDArray\n        Rearranged data tensor.\n\n    out_indices: tvm.te.Tensor or numpy NDArray\n        Related index in input data.\n    \"\"\"\n    box_data_length = data.shape[2]\n    valid_count = output_tensor((batch_size,), \"int32\")\n    out_tensor = output_tensor((batch_size, num_anchors, box_data_length), data.dtype)\n    out_indices = output_tensor((batch_size, num_anchors), \"int32\")\n    for i in parallel(batch_size):\n        valid_count[i] = 0\n        for j in range(num_anchors):\n            score = data[i, j, score_index]\n            if score > score_threshold and (id_index < 0 or data[i, j, id_index] >= 0):\n                for k in range(box_data_length):\n                    out_tensor[i, valid_count[i], k] = data[i, j, k]\n                out_indices[i, valid_count[i]] = j\n                valid_count[i] += 1\n            if j >= valid_count[i]:\n                for k in range(box_data_length):\n                    out_tensor[i, j, k] = -one\n                out_indices[i, j] = -1\n    return valid_count, out_tensor, out_indices\n\n\ndef get_valid_counts(data, score_threshold=0, id_index=0, score_index=1):\n    \"\"\"Get valid count of bounding boxes given a score threshold.\n    Also moves valid boxes to the top of input data.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        Input data. 3-D tensor with shape [batch_size, num_anchors, 6]\n        or [batch_size, num_anchors, 5].\n\n    score_threshold : optional, float\n        Lower limit of score for valid bounding boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    score_index: optional, int\n        Index of the scores/confidence of boxes.\n\n    Returns\n    -------\n    valid_count : tvm.te.Tensor\n        1-D tensor for valid number of boxes.\n\n    out_tensor : tvm.te.Tensor\n        Rearranged data tensor.\n\n    out_indices: tvm.te.Tensor or numpy NDArray\n        Related index in input data.\n    \"\"\"\n    if isinstance(score_threshold, (float, int)):\n        score_threshold = tvm.tir.const(score_threshold, dtype=data.dtype)\n    id_index_const = tvm.tir.const(id_index, \"int32\")\n    score_index_const = tvm.tir.const(score_index, \"int32\")\n    return hybrid_get_valid_counts(\n        data,\n        score_threshold,\n        id_index_const,\n        score_index_const,\n        tvm.tir.const(1, data.dtype),\n        data.shape[0],\n        data.shape[1],\n    )\n\n\n@hybrid.script\ndef hybrid_nms(\n    data,\n    sorted_index,\n    valid_count,\n    indices,\n    batch_size,\n    num_anchors,\n    max_output_size,\n    iou_threshold,\n    force_suppress,\n    top_k,\n    coord_start,\n    score_index,\n    id_index,\n    return_indices,\n    zero,\n    one,\n):\n    \"\"\"Hybrid routing for non-maximum suppression.\n\n    Parameters\n    ----------\n    data: tvm.te.Tensor or numpy NDArray\n        Bounding boxes with class and score. 3-D tensor with shape\n        [batch_size, num_anchors, 6]. It could be the second output\n        out_tensor of get_valid_counts.\n\n    sorted_index : tvm.te.Tensor or numpy NDArray\n        Bounding box indexes sorted by score, with shape\n        [batch_size, num_anchors].\n\n    valid_count : tvm.te.Tensor or numpy NDArray\n        1-D tensor for valid number of boxes. It could be the output\n        valid_count of get_valid_counts.\n\n    indices : tvm.te.Tensor or numpy.NDArray\n        indices in original tensor, with shape [batch_size, num_anchors],\n        represents the index of box in original data. It could be the third\n        output out_indices of get_valid_counts. The values in the second\n        dimension are like the output of arange(num_anchors) if get_valid_counts\n        is not used before non_max_suppression.\n\n    batch_size: tvm.tir.IntImm or tvm.tir.Var\n        Batch size. We need to pass it in since hybrid script doesn't support\n        binding variable to symbolic dim.\n\n    num_anchors: tvm.tir.IntImm or tvm.tir.Var\n        The number of anchors.\n\n    max_output_size : tvm.te.Tensor\n        Max number of output valid boxes for each instance.\n        Return all valid boxes if max_output_size < 0.\n\n    iou_threshold : tvm.te.Tensor\n        Overlapping(IoU) threshold to suppress object with smaller score.\n\n    force_suppress : tvm.tir.const\n        Whether to suppress all detections regardless of class_id.\n\n    top_k : tvm.tir.const\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    coord_start : tvm.tir.const\n        Start index of the consecutive 4 coordinates.\n\n    score_index: tvm.tir.const\n        Index of the scores/confidence of boxes.\n\n    id_index : tvm.tir.const\n        index of the class categories, -1 to disable.\n\n    return_indices : tvm.tir.const\n        Whether to return box indices in input data.\n\n    zero: tvm.tir.const\n        Constant zero with the same dtype as data.\n\n    one: tvm.tir.const\n        Constant one with the same dtype as data.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D tensor with shape [batch_size, num_anchors, 6]\n        or [batch_size, num_anchors, 5].\n\n    box_indices: tvm.te.Tensor\n        2-D tensor with shape [batch_size, num_anchors].\n    \"\"\"\n\n    box_data_length = data.shape[2]\n\n    # box_indices is the expected indices of boxes\n    box_indices = output_tensor((batch_size, num_anchors), sorted_index.dtype)\n    output = output_tensor(\n        (\n            batch_size,\n            num_anchors,\n            box_data_length,\n        ),\n        data.dtype,\n    )\n\n    for i in range(batch_size):\n        if iou_threshold > 0:\n            if valid_count[i] > 0:\n                # Reorder output\n                nkeep = valid_count[i]\n                if 0 < top_k < nkeep:\n                    nkeep = top_k\n                for j in parallel(nkeep):\n                    for k in range(box_data_length):\n                        output[i, j, k] = data[i, sorted_index[i, j], k]\n                    box_indices[i, j] = sorted_index[i, j]\n                if 0 < top_k < valid_count[i]:\n                    for j in parallel(valid_count[i] - nkeep):\n                        for k in range(box_data_length):\n                            output[i, j + nkeep, k] = -one\n                        box_indices[i, j + nkeep] = -1\n\n            # Apply nms\n            box_start_idx = coord_start\n            batch_idx = i\n            num_valid_boxes = 0\n\n            for j in range(valid_count[i]):\n                if num_valid_boxes == max_output_size:\n                    for k in range(box_data_length):\n                        output[i, j, k] = -one\n                    box_indices[i, j] = -1\n\n                elif output[i, j, score_index] > 0:\n                    box_a_idx = j\n                    is_valid_box = 1\n\n                    # a_l: left, a_t: top, a_r: right, a_b: bottom\n                    a_l = min(\n                        output[batch_idx, box_a_idx, box_start_idx],\n                        output[batch_idx, box_a_idx, box_start_idx + 2],\n                    )\n                    a_t = min(\n                        output[batch_idx, box_a_idx, box_start_idx + 1],\n                        output[batch_idx, box_a_idx, box_start_idx + 3],\n                    )\n                    a_r = max(\n                        output[batch_idx, box_a_idx, box_start_idx],\n                        output[batch_idx, box_a_idx, box_start_idx + 2],\n                    )\n                    a_b = max(\n                        output[batch_idx, box_a_idx, box_start_idx + 1],\n                        output[batch_idx, box_a_idx, box_start_idx + 3],\n                    )\n\n                    # check if current box j is valid by calculating iou with\n                    # all existing valid boxes\n                    for k in range(j):\n                        check_iou = 0\n                        if (\n                            is_valid_box == 1\n                            and k < j\n                            and output[i, k, score_index] > 0\n                            and (id_index < 0 or output[i, k, id_index] >= 0)\n                        ):\n                            if force_suppress:\n                                check_iou = 1\n                            elif id_index < 0 or output[i, j, id_index] == output[i, k, id_index]:\n                                check_iou = 1\n\n                        if check_iou > 0:\n                            box_b_idx = k\n\n                            # b_l: left, b_t: top, b_r: right, b_b: bottom\n                            b_l = min(\n                                output[batch_idx, box_b_idx, box_start_idx],\n                                output[batch_idx, box_b_idx, box_start_idx + 2],\n                            )\n                            b_t = min(\n                                output[batch_idx, box_b_idx, box_start_idx + 1],\n                                output[batch_idx, box_b_idx, box_start_idx + 3],\n                            )\n                            b_r = max(\n                                output[batch_idx, box_b_idx, box_start_idx],\n                                output[batch_idx, box_b_idx, box_start_idx + 2],\n                            )\n                            b_b = max(\n                                output[batch_idx, box_b_idx, box_start_idx + 1],\n                                output[batch_idx, box_b_idx, box_start_idx + 3],\n                            )\n\n                            # Overlapping width and height\n                            w = max(zero, min(a_r, b_r) - max(a_l, b_l))\n                            h = max(zero, min(a_b, b_b) - max(a_t, b_t))\n\n                            # Overlapping area\n                            area = h * w\n\n                            # total area of the figure formed by box a and box b\n                            # except for overlapping area\n                            u = (a_r - a_l) * (a_b - a_t) + (b_r - b_l) * (b_b - b_t) - area\n\n                            # get the iou\n                            iou = zero if u <= zero else area / u\n\n                            if iou >= iou_threshold:\n                                is_valid_box = 0\n\n                    if is_valid_box == 0:\n                        for k in range(box_data_length):\n                            output[i, j, k] = -one\n                        box_indices[i, j] = -1\n                    else:\n                        num_valid_boxes += 1\n\n        else:\n            for j in parallel(valid_count[i]):\n                for k in range(box_data_length):\n                    output[i, j, k] = data[i, j, k]\n                box_indices[i, j] = j\n\n        # Set invalid entry to be -1\n        for j in parallel(num_anchors - valid_count[i]):\n            for k in range(box_data_length):\n                output[i, j + valid_count[i], k] = -one\n            box_indices[i, j + valid_count[i]] = -1\n\n        if return_indices:\n            for j in range(valid_count[i]):\n                idx = box_indices[i, j]\n                if box_indices[i, j] >= 0:\n                    box_indices[i, j] = indices[i, idx]\n\n    return output, box_indices\n\n\n@tvm.target.generic_func\ndef non_max_suppression(\n    data,\n    valid_count,\n    indices,\n    max_output_size=-1,\n    iou_threshold=0.5,\n    force_suppress=False,\n    top_k=-1,\n    coord_start=2,\n    score_index=1,\n    id_index=0,\n    return_indices=True,\n    invalid_to_bottom=False,\n):\n    \"\"\"Non-maximum suppression operator for object detection.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        3-D tensor with shape [batch_size, num_anchors, 6] or [batch_size, num_anchors, 5].\n\n    valid_count : tvm.te.Tensor\n        1-D tensor for valid number of boxes.\n\n    indices : tvm.te.Tensor\n        2-D tensor with shape [batch_size, num_anchors].\n\n    max_output_size : optional, int or tvm.te.Tensor\n        Max number of output valid boxes for each instance.\n        Return all valid boxes if the value of max_output_size is less than 0.\n\n    iou_threshold : optional, float or tvm.te.Tensor\n        Non-maximum suppression threshold.\n\n    force_suppress : optional, boolean\n        Whether to suppress all detections regardless of class_id.\n\n    top_k : optional, int\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    coord_start : required, int\n        Start index of the consecutive 4 coordinates.\n\n    score_index: optional, int\n        Index of the scores/confidence of boxes.\n\n    id_index : optional, int\n        index of the class categories, -1 to disable.\n\n    return_indices : optional, boolean\n        Whether to return box indices in input data.\n\n    invalid_to_bottom : optional, boolean\n        Whether to move all valid bounding boxes to the top.\n\n    Returns\n    -------\n    out : tvm.te.Tensor or tuple of tvm.te.Tensor\n        3-D tensor with shape [batch_size, num_anchors, 6]\n        or [batch_size, num_anchors, 5]. Out is a tuple of tvm.te.Tensor\n        if return_indices is True, the Tensor in the tuple is 2-D tensor\n        with shape [batch_size, num_anchors] and shape\n        [batch_size, num_valid_anchors] respectively.\n\n    Example\n    --------\n    .. code-block:: python\n\n        # An example to use non_max_suppression\n        dshape = (1, 5, 6)\n        data = te.placeholder(dshape, name=\"data\")\n        valid_count = te.placeholder((dshape[0],), dtype=\"int32\", name=\"valid_count\")\n        iou_threshold = 0.7\n        force_suppress = True\n        top_k = -1\n        out = non_max_suppression(data, valid_count, indices, iou_threshold=iou_threshold,\n                                  force_suppress=force_suppress, top_k=top_k)\n        np_data = np.random.uniform(dshape)\n        np_valid_count = np.array([4])\n        s = topi.generic.schedule_nms(out)\n        f = tvm.build(s, [data, valid_count, out], \"llvm\")\n        dev = tvm.cpu()\n        tvm_data = tvm.nd.array(np_data, dev)\n        tvm_valid_count = tvm.nd.array(np_valid_count, dev)\n        tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), dev)\n        f(tvm_data, tvm_valid_count, tvm_out)\n    \"\"\"\n    batch_size = data.shape[0]\n    num_anchors = data.shape[1]\n    if isinstance(max_output_size, int):\n        max_output_size = tvm.tir.const(max_output_size, dtype=\"int32\")\n    if isinstance(iou_threshold, float):\n        iou_threshold = tvm.tir.const(iou_threshold, dtype=data.dtype)\n    score_axis = score_index\n    score_shape = (batch_size, num_anchors)\n    score_tensor = te.compute(score_shape, lambda i, j: data[i, j, score_axis])\n    sort_tensor = argsort(score_tensor, valid_count=valid_count, axis=1, is_ascend=False)\n\n    out, box_indices = hybrid_nms(\n        data,\n        sort_tensor,\n        valid_count,\n        indices,\n        batch_size,\n        num_anchors,\n        max_output_size,\n        iou_threshold,\n        tvm.tir.const(force_suppress, dtype=\"bool\"),\n        tvm.tir.const(top_k, dtype=\"int32\"),\n        tvm.tir.const(coord_start, dtype=\"int32\"),\n        tvm.tir.const(score_index, dtype=\"int32\"),\n        tvm.tir.const(id_index, dtype=\"int32\"),\n        tvm.tir.const(return_indices, dtype=\"bool\"),\n        zero=tvm.tir.const(0, dtype=data.dtype),\n        one=tvm.tir.const(1, dtype=data.dtype),\n    )\n\n    if return_indices:\n        return hybrid_rearrange_indices_out(\n            box_indices,\n            one=tvm.tir.const(1, dtype=\"int32\"),\n            batch_size=batch_size,\n            num_anchors=num_anchors,\n        )\n\n    if invalid_to_bottom:\n        out = hybrid_rearrange_box_out(\n            out,\n            one=tvm.tir.const(1, dtype=data.dtype),\n            batch_size=batch_size,\n            num_anchors=num_anchors,\n        )\n    return out\n\n\ndef _nms_loop(\n    ib,\n    batch_size,\n    top_k,\n    iou_threshold,\n    max_output_size,\n    valid_count,\n    on_new_valid_box_func,\n    on_new_invalidated_box_func,\n    needs_bbox_check_func,\n    calc_overlap_func,\n    out_scores,\n    num_valid_boxes,\n):\n    def nms_inner_loop(ib, i, j, nkeep, num_valid_boxes_local):\n        # The box j is valid, invalidate other boxes that overlap with j above iou_threshold\n        on_new_valid_box_func(ib, 0, num_valid_boxes_local[0], i, j)\n        num_valid_boxes_local[0] += 1\n\n        num_boxes_to_check = nkeep - (j + 1)\n\n        with ib.for_range(0, num_boxes_to_check, name=\"_k\", kind=\"parallel\") as _k:\n            k = j + 1 + _k\n\n            with ib.if_scope(\n                tvm.tir.all(\n                    k < nkeep,\n                    out_scores[i, k] > 0,  # is the box k still valid?\n                    needs_bbox_check_func(i, j, k),\n                )\n            ):\n                iou = calc_overlap_func(i, j, k)\n\n                with ib.if_scope(iou >= iou_threshold):\n                    # invalidate the box k\n                    out_scores[i, k] = -1.0\n                    on_new_invalidated_box_func(i, k)\n\n    with ib.for_range(0, batch_size, name=\"i\") as i:\n        nkeep = if_then_else(tvm.tir.all(top_k > 0, top_k < valid_count[i]), top_k, valid_count[i])\n        max_output_size = if_then_else(max_output_size > 0, max_output_size, nkeep)\n\n        with ib.if_scope(tvm.tir.all(iou_threshold > 0, valid_count[i] > 0)):\n            num_valid_boxes_local = ib.allocate(\n                \"int32\", (1,), name=\"num_valid_boxes_local\", scope=\"local\"\n            )\n            box_idx = ib.allocate(\"int32\", (1,), name=\"box_idx\", scope=\"local\")\n            num_valid_boxes_local[0] = 0\n            box_idx[0] = 0\n\n            # Apply nms\n            # No need to do more iteration if we have already reached max_output_size boxes\n            with ib.while_loop(\n                tvm.tir.all(box_idx[0] < nkeep, num_valid_boxes_local[0] < max_output_size)\n            ):\n                # Proceed to the inner loop if the box with id box_idx is still valid\n                with ib.if_scope(out_scores[i, box_idx[0]] > -1.0):\n                    nms_inner_loop(ib, i, box_idx[0], nkeep, num_valid_boxes_local)\n                box_idx[0] += 1\n\n            num_valid_boxes[i] = num_valid_boxes_local[0]\n\n        with ib.else_scope():\n            num_valid_boxes[i] = 0\n\n    return ib.get()\n\n\ndef _get_valid_box_count(scores, score_threshold):\n    batch_classes, num_boxes = scores.shape\n\n    def searchsorted_ir(scores, valid_count):\n        ib = tvm.tir.ir_builder.create()\n        scores = ib.buffer_ptr(scores)\n        valid_count = ib.buffer_ptr(valid_count)\n\n        with ib.for_range(0, batch_classes, name=\"i\", kind=\"parallel\") as i:\n            binary_search(ib, i, num_boxes, scores, score_threshold, valid_count)\n\n        return ib.get()\n\n    scores_buf = tvm.tir.decl_buffer(scores.shape, scores.dtype, \"scores_buf\", data_alignment=8)\n\n    return te.extern(\n        [(batch_classes,)],\n        [scores],\n        lambda ins, outs: searchsorted_ir(ins[0], outs[0]),\n        dtype=[\"int32\"],\n        in_buffers=[scores_buf],\n        name=\"searchsorted\",\n        tag=\"searchsorted\",\n    )\n\n\ndef _collect_selected_indices_ir(num_class, selected_indices, num_detections, row_offsets, out):\n    batch_classes, _ = selected_indices.shape\n\n    ib = tvm.tir.ir_builder.create()\n\n    selected_indices = ib.buffer_ptr(selected_indices)\n    num_detections = ib.buffer_ptr(num_detections)\n    row_offsets = ib.buffer_ptr(row_offsets)\n    out = ib.buffer_ptr(out)\n\n    with ib.for_range(0, batch_classes, name=\"i\", kind=\"parallel\") as i:\n        i = cast(i, \"int64\")\n        batch_id = i // num_class\n        class_id = i % num_class\n\n        with ib.for_range(0, num_detections[i], name=\"j\") as j:\n            out[row_offsets[i] + j, 0] = batch_id\n            out[row_offsets[i] + j, 1] = class_id\n            out[row_offsets[i] + j, 2] = cast(selected_indices[i, j], \"int64\")\n\n    return ib.get()\n\n\ndef _collect_selected_indices_and_scores_ir(\n    selected_indices,\n    selected_scores,\n    num_detections,\n    row_offsets,\n    num_total_detections,\n    collected_indices,\n    collected_scores,\n):\n    batch_size, num_class = row_offsets.shape\n    num_boxes = selected_indices.shape[1]\n\n    ib = tvm.tir.ir_builder.create()\n\n    selected_indices = ib.buffer_ptr(selected_indices)\n    selected_scores = ib.buffer_ptr(selected_scores)\n    num_detections = ib.buffer_ptr(num_detections)\n    row_offsets = ib.buffer_ptr(row_offsets)\n    num_total_detections = ib.buffer_ptr(num_total_detections)\n    collected_indices = ib.buffer_ptr(collected_indices)\n    collected_scores = ib.buffer_ptr(collected_scores)\n    zero = cast(0, \"int64\")\n\n    with ib.for_range(0, batch_size * num_class, name=\"i\", kind=\"parallel\") as i:\n        i = cast(i, \"int64\")\n        batch_id = i // num_class\n        class_id = i % num_class\n\n        with ib.for_range(0, num_boxes, name=\"j\") as j:\n            with ib.if_scope(j < num_detections[batch_id, class_id]):\n                offset = row_offsets[batch_id, class_id] + j\n                collected_indices[batch_id, offset, 0] = class_id\n                collected_indices[batch_id, offset, 1] = cast(selected_indices[i, j], \"int64\")\n                collected_scores[batch_id, offset] = selected_scores[i, j]\n            with ib.else_scope():\n                offset = (\n                    num_total_detections[batch_id]\n                    + class_id * num_boxes\n                    - row_offsets[batch_id, class_id]\n                    + j\n                    - num_detections[batch_id, class_id]\n                )\n                collected_indices[batch_id, offset, 0] = zero\n                collected_indices[batch_id, offset, 1] = zero\n                collected_scores[batch_id, offset] = 0.0\n\n    return ib.get()\n\n\ndef all_class_non_max_suppression(\n    boxes,\n    scores,\n    max_output_boxes_per_class,\n    iou_threshold,\n    score_threshold,\n    output_format=\"onnx\",\n):\n    \"\"\"Non-maximum suppression operator for object detection, corresponding to ONNX\n    NonMaxSuppression and TensorFlow combined_non_max_suppression.\n    NMS is performed for each class separately.\n\n    Parameters\n    ----------\n    boxes : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_boxes, 4)\n\n    scores: tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_classes, num_boxes)\n\n    max_output_boxes_per_class : int or tvm.te.Tensor, optional\n        The maxinum number of output selected boxes per class\n\n    iou_threshold : float or tvm.te.Tensor, optionaIl\n        IoU test threshold\n\n    score_threshold : float or tvm.te.Tensor, optional\n        Score threshold to filter out low score boxes early\n\n    output_format : str, optional\n        \"onnx\" or \"tensorflow\", see below.\n\n    Returns\n    -------\n    out : list of tvm.te.Tensor\n        If `output_format` is \"onnx\", the output is two tensors. The first is `indices` of size\n        `(batch_size * num_class* num_boxes , 3)` and the second is a scalar tensor\n        `num_total_detection` of shape `(1,)` representing the total number of selected\n        boxes. The three values in `indices` encode batch, class, and box indices.\n        Rows of `indices` are ordered such that selected boxes from batch 0, class 0 come\n        first, in descending of scores, followed by boxes from batch 0, class 1 etc. Out of\n        `batch_size * num_class* num_boxes` rows of indices, only the first `num_total_detection`\n        rows are valid.\n\n        If `output_format` is \"tensorflow\", the output is three tensors, the first\n        is `indices` of size `(batch_size, num_class * num_boxes , 2)`, the second is `scores` of\n        size `(batch_size, num_class * num_boxes)`, and the third is `num_total_detection` of size\n        `(batch_size,)` representing the total number of selected boxes per batch. The two values\n        in `indices` encode class and box indices. Of num_class * num_boxes boxes in `indices` at\n        batch b, only the first `num_total_detection[b]` entries are valid. The second axis of\n        `indices` and `scores` are sorted within each class by box scores, but not across classes.\n        So the box indices and scores for the class 0 come first in a sorted order, followed by\n        the class 1 etc.\n    \"\"\"\n    batch, num_class, num_boxes = scores.shape\n    scores = reshape(scores, (batch * num_class, num_boxes))\n\n    sorted_indices = argsort(scores, axis=1, is_ascend=False, dtype=\"int32\")\n    sorted_scores = gather(scores, 1, sorted_indices)\n\n    valid_count = _get_valid_box_count(sorted_scores, score_threshold)\n\n    selected_indices, selected_scores, num_detections = run_all_class_nms(\n        boxes,\n        sorted_scores,\n        sorted_indices,\n        valid_count,\n        max_output_boxes_per_class,\n        iou_threshold,\n        _nms_loop,\n        return_scores=(output_format == \"tensorflow\"),\n    )\n\n    if output_format == \"onnx\":\n        row_offsets = cumsum(num_detections, exclusive=True, dtype=\"int64\")\n        num_total_detections = reduction.sum(cast(num_detections, \"int64\"), axis=1)\n\n        selected_indices = collect_selected_indices(\n            num_class, selected_indices, num_detections, row_offsets, _collect_selected_indices_ir\n        )\n        return [selected_indices, num_total_detections]\n\n    num_detections_per_batch = reshape(num_detections, (batch, num_class))\n    row_offsets = cumsum(num_detections_per_batch, exclusive=True, dtype=\"int64\", axis=1)\n    num_total_detections = reduction.sum(cast(num_detections_per_batch, \"int64\"), axis=1)\n\n    selected_indices, selected_scores = collect_selected_indices_and_scores(\n        selected_indices,\n        selected_scores,\n        num_detections_per_batch,\n        row_offsets,\n        num_total_detections,\n        _collect_selected_indices_and_scores_ir,\n    )\n\n    return [selected_indices, selected_scores, num_total_detections]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/nms_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Common utilities used in Non-maximum suppression operators\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef _get_boundaries(output, box_idx):\n    l = tvm.te.min(\n        output[box_idx],\n        output[box_idx + 2],\n    )\n    t = tvm.te.min(\n        output[box_idx + 1],\n        output[box_idx + 3],\n    )\n    r = tvm.te.max(\n        output[box_idx],\n        output[box_idx + 2],\n    )\n    b = tvm.te.max(\n        output[box_idx + 1],\n        output[box_idx + 3],\n    )\n    return l, t, r, b\n\n\ndef calculate_overlap(out_tensor, box_a_idx, box_b_idx):\n    \"\"\"Calculate overlap of two boxes.\"\"\"\n    a_l, a_t, a_r, a_b = _get_boundaries(out_tensor, box_a_idx)\n    b_l, b_t, b_r, b_b = _get_boundaries(out_tensor, box_b_idx)\n\n    # Overlapping width and height\n    w = tvm.te.max(0.0, tvm.te.min(a_r, b_r) - tvm.te.max(a_l, b_l))\n    h = tvm.te.max(0.0, tvm.te.min(a_b, b_b) - tvm.te.max(a_t, b_t))\n\n    # Overlapping area\n    area = h * w\n\n    # total area of the figure formed by box a and box b\n    # except for overlapping area\n    u = (a_r - a_l) * (a_b - a_t) + (b_r - b_l) * (b_b - b_t) - area\n    return tvm.tir.Select(u <= 0.0, 0.0, area / u)\n\n\ndef binary_search(ib, y, num_boxes, scores, score_threshold, out):\n    \"\"\"Binary search for score_threshold on scores sorted in descending order\"\"\"\n    lo = ib.allocate(\"int32\", (1,), name=\"lo\", scope=\"local\")\n    hi = ib.allocate(\"int32\", (1,), name=\"hi\", scope=\"local\")\n\n    lo[0] = 0\n    hi[0] = num_boxes\n\n    with ib.while_loop(lo[0] < hi[0]):\n        mid = (hi[0] + lo[0]) >> 1\n        with ib.if_scope(scores[y, mid] > score_threshold):\n            lo[0] = mid + 1\n        with ib.else_scope():\n            hi[0] = mid\n\n    out[y] = lo[0]\n\n\ndef collect_selected_indices(num_class, selected_indices, num_detections, row_offsets, ir):\n    \"\"\"Collect selected indices from the core NMS loop into one linear output\n\n    Parameters\n    ----------\n    num_class : int\n\n    selected_indices: tvm.te.Tensor\n        2-D tensor with shape (batch_size * num_classes, num_boxes), representing the indices\n        of selected boxes by the core NMS loop.\n\n    num_detections tvm.te.Tensor\n        1-D tensor with shape (batch_size * num_classes,), representing\n        the number of boxes selected by the core NMS loop, per batch and class\n\n    row_offsets tvm.te.Tensor\n        1-D tensor with shape (batch_size * num_classes,), this should be the exclusive scan\n        of num_detections\n\n    ir : function\n        A function to generate IR for CPU or GPU, see its usage in vision/nms.py and cuda/nms.py\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        The output is indices of size (batch_size * num_class* num_boxes , 3).\n        Rows of indices are ordered such that selected boxes from batch 0, class 0 come\n        first, in descending of scores, followed by boxes from batch 0, class 1 etc.\n    \"\"\"\n    batch_class, num_boxes = selected_indices.shape\n    return te.extern(\n        [(batch_class * num_boxes, 3)],\n        [selected_indices, num_detections, row_offsets],\n        lambda ins, outs: ir(num_class, ins[0], ins[1], ins[2], outs[0]),\n        dtype=[\"int64\"],\n        name=\"collect_indices\",\n        tag=\"collect_indices\",\n    )\n\n\ndef collect_selected_indices_and_scores(\n    selected_indices, selected_scores, num_detections, row_offsets, num_total_detections, ir\n):\n    \"\"\"Collect selected indices and scores from the core NMS loop into one linear output\n\n    Parameters\n    ----------\n    num_class : int\n\n    selected_indices: tvm.te.Tensor\n        2-D tensor with shape (batch_size * num_classes, num_boxes), representing the indices\n        of selected boxes by the core NMS loop.\n\n    selected_indices: tvm.te.Tensor\n        2-D tensor with shape (batch_size * num_classes, num_boxes), representing the scores\n        of selected boxes by the core NMS loop.\n\n    num_detections tvm.te.Tensor\n        2-D tensor with shape (batch_size, num_classes), representing\n        the number of boxes selected by the core NMS loop, per batch and class\n\n    row_offsets tvm.te.Tensor\n        2-D tensor with shape (batch_size, num_classes), this should be the exclusive scan\n        of num_detections along axis 1\n\n    ir : function\n        A function to generate IR for CPU or GPU, see its usage in vision/nms.py and cuda/nms.py\n\n    Returns\n    -------\n    out : [tvm.te.Tensor, tvm.te.Tensor]\n        The output is two tensors. The first is indices of size\n        (batch_size, num_class* num_boxes, 2), and the second is scores of size\n        (batch_size, num_class* num_boxes).\n    \"\"\"\n    batch_size, num_class = row_offsets.shape\n    num_boxes = selected_indices.shape[1]\n    return te.extern(\n        [(batch_size, num_class * num_boxes, 2), (batch_size, num_class * num_boxes)],\n        [selected_indices, selected_scores, num_detections, row_offsets, num_total_detections],\n        lambda ins, outs: ir(ins[0], ins[1], ins[2], ins[3], ins[4], outs[0], outs[1]),\n        dtype=[\"int64\", \"float32\"],\n        name=\"collect_indices_and_scores\",\n        tag=\"collect_indices_and_scores\",\n    )\n\n\ndef _all_class_nms_ir(\n    boxes,\n    sorted_scores,\n    sorted_indices,\n    valid_count,\n    batch_class,\n    num_class,\n    num_anchors,\n    iou_threshold,\n    max_output_size_per_class,\n    box_indices,\n    selected_scores,\n    num_valid_boxes,\n    nms_loop,\n):\n    ib = tvm.tir.ir_builder.create()\n    boxes = ib.buffer_ptr(boxes)\n    sorted_scores = ib.buffer_ptr(sorted_scores)\n    sorted_indices = ib.buffer_ptr(sorted_indices)\n    valid_count = ib.buffer_ptr(valid_count)\n    box_indices = ib.buffer_ptr(box_indices)\n    num_valid_boxes = ib.buffer_ptr(num_valid_boxes)\n\n    if selected_scores is not None:\n        selected_scores = ib.buffer_ptr(selected_scores)\n\n    if isinstance(iou_threshold, float):\n        iou_threshold = tvm.tir.FloatImm(\"float32\", iou_threshold)\n\n    if isinstance(max_output_size_per_class, int):\n        max_output_size_per_class = tvm.tir.const(max_output_size_per_class)\n\n    def calc_overlap(i, j, k):\n        offset_j = sorted_indices[i, j] * 4\n        offset_k = sorted_indices[i, k] * 4\n        batch_id = i // num_class\n        base_bbox_idx = batch_id * num_anchors * 4\n        return calculate_overlap(\n            boxes,\n            base_bbox_idx + offset_j,\n            base_bbox_idx + offset_k,\n        )\n\n    def on_new_valid_box(ib, tid, num_current_valid_box, i, j):\n        with ib.if_scope(tid + 0 == 0):\n            box_indices[i, num_current_valid_box] = sorted_indices[i, j]\n\n            if selected_scores is not None:\n                selected_scores[i, num_current_valid_box] = sorted_scores[i, j]\n\n    def on_new_invalidated_box(*_):\n        pass\n\n    def needs_bbox_check(*_):\n        return tvm.tir.const(True)\n\n    return nms_loop(\n        ib,\n        batch_class,\n        tvm.tir.IntImm(\"int32\", -1),  # top_k\n        iou_threshold,\n        max_output_size_per_class,\n        valid_count,\n        on_new_valid_box,\n        on_new_invalidated_box,\n        needs_bbox_check,\n        calc_overlap,\n        sorted_scores,\n        num_valid_boxes,\n    )\n\n\ndef run_all_class_nms(\n    boxes,\n    sorted_scores,\n    sorted_indices,\n    valid_count,\n    max_output_size_per_class,\n    iou_threshold,\n    nms_loop,\n    return_scores=False,\n):\n    \"\"\"The core all class NMS routine\n\n    Parameters\n    ----------\n    boxes : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_boxes, 4)\n\n    sorted_scores: tvm.te.Tensor\n        2-D tensor with shape (batch_size * num_classes, num_boxes)\n        One of the outputs from argsort\n\n    sorted_indices: tvm.te.Tensor\n        2-D tensor with shape (batch_size * num_classes, num_boxes)\n        The other output from argsort\n\n    valid_count: tvm.te.Tensor\n        1-D tensor with shape (batch_size * num_classes,), representing\n        the number of boxes whose score is above score_threshold, per batch and class\n\n    max_output_boxes_per_class : int or tvm.te.Tensor, optional\n        The maxinum number of output selected boxes per class\n\n    iou_threshold : float or tvm.te.Tensor, optionaIl\n        IoU test threshold\n\n    nms_loop : function\n        A core NMS loop, see its usage in vision/nms.py and cuda/nms.py\n\n    return_scores : bool, optional\n        Whether or not to return selected scores, needed by the tensorflow output format.\n\n    Returns\n    -------\n    out : a list of tvm.te.Tensor\n        The output is three tensors, the first and second are indices and scores of size\n        (batch_size * num_class, num_boxes), and the third is a tensor\n        num_selected_boxes of shape (batch_size * num_class,) representing the total number of\n        selected boxes per batch and class. If return_scores is False, the second output is\n        None.\n    \"\"\"\n    batch, num_boxes, _ = boxes.shape\n    batch_class = sorted_scores.shape[0]\n    num_class = batch_class // batch\n\n    if return_scores is False:\n        selected_indices, num_detections = te.extern(\n            [(batch_class, num_boxes), (1, batch_class)],\n            [boxes, sorted_scores, sorted_indices, valid_count],\n            lambda ins, outs: _all_class_nms_ir(\n                ins[0],  # boxes\n                ins[1],  # sorted_scores\n                ins[2],  # sorted_indices\n                ins[3],  # valid_count\n                batch_class,\n                num_class,\n                num_boxes,\n                iou_threshold,\n                max_output_size_per_class,\n                outs[0],  # box_indices\n                None,  # scores\n                outs[1],  # num_selected_boxes\n                nms_loop,\n            ),\n            dtype=[\"int32\", \"int32\"],\n            name=\"all_class_nms\",\n            tag=\"all_class_nms\",\n        )\n        return selected_indices, None, num_detections\n\n    return te.extern(\n        [(batch_class, num_boxes), (batch_class, num_boxes), (1, batch_class)],\n        [boxes, sorted_scores, sorted_indices, valid_count],\n        lambda ins, outs: _all_class_nms_ir(\n            ins[0],  # boxes\n            ins[1],  # sorted_scores\n            ins[2],  # sorted_indices\n            ins[3],  # valid_count\n            batch_class,\n            num_class,\n            num_boxes,\n            iou_threshold,\n            max_output_size_per_class,\n            outs[0],  # box_indices\n            outs[1],  # selected scores\n            outs[2],  # num_selected_boxes\n            nms_loop,\n        ),\n        dtype=[\"int32\", \"float32\", \"int32\"],\n        name=\"all_class_nms\",\n        tag=\"all_class_nms\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/rcnn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"Faster R-CNN and Mask R-CNN operators\"\"\"\nfrom .roi_align import *\nfrom .roi_pool import *\nfrom .proposal import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/rcnn/proposal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, singleton-comparison, bad-continuation\n\"\"\"Proposal operator\"\"\"\nimport math\nimport tvm\nfrom tvm import te\nfrom ...utils import get_const_tuple, get_const_int\nfrom ...sort import argsort\n\n\ndef generate_anchor(ratio, scale, base_size):\n    \"\"\"Generate anchor\"\"\"\n    w = h = float(base_size)\n    x_ctr = 0.5 * (w - 1.0)\n    y_ctr = 0.5 * (h - 1.0)\n    size = w * h\n    size_ratios = math.floor(size / ratio)\n    new_w = math.floor(math.sqrt(size_ratios) + 0.5) * scale\n    new_h = math.floor((new_w / scale * ratio) + 0.5) * scale\n    return (\n        x_ctr - 0.5 * (new_w - 1.0),\n        y_ctr - 0.5 * (new_h - 1.0),\n        x_ctr + 0.5 * (new_w - 1.0),\n        y_ctr + 0.5 * (new_h - 1.0),\n    )\n\n\ndef reg_bbox(x1, y1, x2, y2, dx, dy, dw, dh):\n    \"\"\"Bounding box regression function\"\"\"\n    bbox_w = x2 - x1 + 1.0\n    bbox_h = y2 - y1 + 1.0\n    ctr_x = x1 + 0.5 * (bbox_w - 1.0)\n    ctr_y = y1 + 0.5 * (bbox_h - 1.0)\n\n    pred_ctr_x = dx * bbox_w + ctr_x\n    pred_ctr_y = dy * bbox_h + ctr_y\n    pred_w = te.exp(dw) * bbox_w\n    pred_h = te.exp(dh) * bbox_h\n\n    pred_x1 = pred_ctr_x - 0.5 * (pred_w - 1.0)\n    pred_y1 = pred_ctr_y - 0.5 * (pred_h - 1.0)\n    pred_x2 = pred_ctr_x + 0.5 * (pred_w - 1.0)\n    pred_y2 = pred_ctr_y + 0.5 * (pred_h - 1.0)\n    return pred_x1, pred_y1, pred_x2, pred_y2\n\n\ndef reg_iou(x1, y1, x2, y2, dx1, dy1, dx2, dy2):\n    \"\"\"Bounding box regression function\"\"\"\n    pred_x1 = x1 + dx1\n    pred_y1 = y1 + dy1\n    pred_x2 = x2 + dx2\n    pred_y2 = y2 + dy2\n    return pred_x1, pred_y1, pred_x2, pred_y2\n\n\ndef predict_bbox_ir(\n    cls_prob_buf,\n    bbox_pred_buf,\n    im_info_buf,\n    out_buf,\n    scales,\n    ratios,\n    feature_stride,\n    rpn_min_size,\n    iou_loss,\n):\n    \"\"\"Predict bounding boxes based on anchors, scores and deltas.\n\n    Parameters\n    ----------\n    cls_prob_buf : tvm.te.schedule.Buffer\n        4-D with shape [batch, 2 * num_anchors, height, width]\n\n    bbox_pred_buf : tvm.te.schedule.Buffer\n        4-D with shape [batch, 4 * num_anchors, height, width]\n\n    im_info_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, 3]\n\n    out_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]\n        The last dimension is in format of [w_start, h_start, w_end, h_end, score]\n\n    scales : list/tuple of float\n        Scales of anchor windows.\n\n    ratios : list/tuple of float\n        Ratios of anchor windows.\n\n    feature_stride : int\n        The size of the receptive field each unit in the convolution layer of the rpn, for example\n        the product of all stride's prior to this layer.\n\n    rpn_min_size : int\n        Minimum height or width in proposal.\n\n    iou_loss : bool\n        Usage of IoU loss.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_anchors, height, width = get_const_tuple(cls_prob_buf.shape)\n    num_anchors //= 2\n    ib = tvm.tir.ir_builder.create()\n\n    p_score = ib.buffer_ptr(cls_prob_buf)\n    p_delta = ib.buffer_ptr(bbox_pred_buf)\n    p_im_info = ib.buffer_ptr(im_info_buf)\n    p_out = ib.buffer_ptr(out_buf)\n\n    idxm = tvm.tir.indexmod\n    idxd = tvm.tir.indexdiv\n\n    with ib.for_range(0, batch * height * width) as tid:\n        w = idxm(tid, width)\n        h = idxm(idxd(tid, width), height)\n        b = idxd(idxd(tid, width), height)\n\n        for k in range(num_anchors):\n            out_index = tid * num_anchors + k\n            ratio = ratios[k // len(scales)]\n            scale = scales[k % len(scales)]\n            anchor = generate_anchor(ratio, scale, feature_stride)\n            im_height = p_im_info[b * 3]\n            im_width = p_im_info[b * 3 + 1]\n            x1 = anchor[0] + w * feature_stride\n            y1 = anchor[1] + h * feature_stride\n            x2 = anchor[2] + w * feature_stride\n            y2 = anchor[3] + h * feature_stride\n\n            delta = [\n                p_delta[((((b * num_anchors + k) * 4 + i) * height + h) * width + w)]\n                for i in range(4)\n            ]\n            regression_func = reg_iou if iou_loss else reg_bbox\n            pred_x1, pred_y1, pred_x2, pred_y2 = regression_func(x1, y1, x2, y2, *delta)\n\n            pred_x1 = tvm.te.max(tvm.te.min(pred_x1, im_width - 1.0), 0.0)\n            pred_y1 = tvm.te.max(tvm.te.min(pred_y1, im_height - 1.0), 0.0)\n            pred_x2 = tvm.te.max(tvm.te.min(pred_x2, im_width - 1.0), 0.0)\n            pred_y2 = tvm.te.max(tvm.te.min(pred_y2, im_height - 1.0), 0.0)\n\n            real_height = (im_height / feature_stride).astype(\"int32\")\n            real_width = (im_width / feature_stride).astype(\"int32\")\n\n            bbox_w = pred_x2 - pred_x1 + 1.0\n            bbox_h = pred_y2 - pred_y1 + 1.0\n            min_size = p_im_info[b * 3 + 2] * rpn_min_size\n\n            pred_score = p_score[((b * num_anchors * 2 + num_anchors + k) * height + h) * width + w]\n            pred_score = tvm.tir.Select(\n                tvm.tir.any(h >= real_height, w >= real_width), -1.0, pred_score\n            )\n            p_out[out_index * 5 + 0] = pred_x1\n            p_out[out_index * 5 + 1] = pred_y1\n            p_out[out_index * 5 + 2] = pred_x2\n            p_out[out_index * 5 + 3] = pred_y2\n            p_out[out_index * 5 + 4] = pred_score\n\n            with ib.if_scope(tvm.tir.any(bbox_w < min_size, bbox_h < min_size)):\n                p_out[out_index * 5 + 0] -= min_size / 2.0\n                p_out[out_index * 5 + 1] -= min_size / 2.0\n                p_out[out_index * 5 + 2] += min_size / 2.0\n                p_out[out_index * 5 + 3] += min_size / 2.0\n                p_out[out_index * 5 + 4] = -1.0\n\n    return ib.get()\n\n\ndef argsort_ir(data_buf, out_index_buf):\n    \"\"\"Batched odd-even transposition sort.\n\n    Parameters\n    ----------\n    data_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]\n\n    out_index_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Indices of data in sorted order.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_bbox = get_const_tuple(data_buf.shape)\n    ib = tvm.tir.ir_builder.create()\n    p_data = ib.buffer_ptr(data_buf)\n    index_out = ib.buffer_ptr(out_index_buf)\n    temp_data = ib.allocate(\"float32\", (1,), name=\"temp_data\", scope=\"local\")\n    temp_index = ib.allocate(\"int32\", (1,), name=\"temp_index\", scope=\"local\")\n    idxm = tvm.tir.indexmod\n    with ib.for_range(0, batch, kind=\"unroll\") as b:\n        start = b * num_bbox\n        for i in range(2):\n            with ib.for_range(0, (num_bbox + 1) // 2) as tid:\n                bbox_id = tid * 2 + i\n                with ib.if_scope(bbox_id < num_bbox):\n                    index_out[start + bbox_id] = bbox_id\n        with ib.for_range(0, num_bbox) as k:\n            with ib.for_range(0, (num_bbox + 1) // 2) as tid:\n                offset = start + 2 * tid + idxm(k, 2)\n                with ib.if_scope(\n                    tvm.tir.all(offset + 1 < num_bbox, p_data[offset] < p_data[offset + 1])\n                ):\n                    temp_data[0] = p_data[offset]\n                    p_data[offset] = p_data[offset + 1]\n                    p_data[offset + 1] = temp_data[0]\n                    temp_index[0] = index_out[offset]\n                    index_out[offset] = index_out[offset + 1]\n                    index_out[offset + 1] = temp_index[0]\n    return ib.get()\n\n\ndef nms_ir(sorted_bbox_buf, out_buf, nms_threshold):\n    \"\"\"Non-maximum suppression.\n\n    Parameters\n    ----------\n    sorted_bbox_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]. The last dimension is in format of\n        [w_start, h_start, w_end, h_end, score].\n\n    out_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Boolean mask of whether a bounding box should be removed.\n\n    nms_threshold : float\n        Non-maximum suppression threshold.\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n\n    def calculate_overlap(out_tensor, box_a_idx, box_b_idx):\n        \"\"\"Calculate overlap of two boxes.\"\"\"\n        w = tvm.te.max(\n            0.0,\n            tvm.te.min(out_tensor[box_a_idx + 2], out_tensor[box_b_idx + 2])\n            - tvm.te.max(out_tensor[box_a_idx], out_tensor[box_b_idx])\n            + 1.0,\n        )\n        h = tvm.te.max(\n            0.0,\n            tvm.te.min(out_tensor[box_a_idx + 3], out_tensor[box_b_idx + 3])\n            - tvm.te.max(out_tensor[box_a_idx + 1], out_tensor[box_b_idx + 1])\n            + 1.0,\n        )\n        i = w * h\n        u = (\n            (out_tensor[box_a_idx + 2] - out_tensor[box_a_idx] + 1.0)\n            * (out_tensor[box_a_idx + 3] - out_tensor[box_a_idx + 1] + 1.0)\n            + (out_tensor[box_b_idx + 2] - out_tensor[box_b_idx] + 1.0)\n            * (out_tensor[box_b_idx + 3] - out_tensor[box_b_idx + 1] + 1.0)\n            - i\n        )\n        return i / u\n\n    batch, num_bbox = get_const_tuple(out_buf.shape)\n    ib = tvm.tir.ir_builder.create()\n    p_data = ib.buffer_ptr(sorted_bbox_buf)\n    p_out = ib.buffer_ptr(out_buf)\n    with ib.for_range(0, batch, kind=\"unroll\", name=\"n\") as b:\n        base_idx = b * num_bbox\n        for i in range(num_bbox):\n            p_out[base_idx + i] = False\n        with ib.for_range(0, num_bbox - 1) as l:\n            with ib.for_range(0, num_bbox) as i:\n                with ib.if_scope(tvm.tir.all(i < num_bbox, i > l, p_out[base_idx + l] == False)):\n                    iou = calculate_overlap(p_data, (base_idx + l) * 5, (base_idx + i) * 5)\n                    with ib.if_scope(iou > nms_threshold):\n                        p_out[base_idx + i] = True\n    return ib.get()\n\n\ndef prepare_output_ir(sorted_bbox_buf, remove_mask_buf, out_buf):\n    \"\"\"Copy output after applying nms to continuous memory.\n\n    Parameters\n    ----------\n    sorted_bbox_buf : tvm.te.schedule.Buffer\n        3-D with shape [batch, num_bbox, 5]. The last dimension is in format of\n        [w_start, h_start, w_end, h_end, score].\n\n    remove_mask_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch, num_bbox]. Boolean mask of whether a bounding box should be removed.\n\n    out_buf : tvm.te.schedule.Buffer\n        2-D with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of\n        [batch_index, w_start, h_start, w_end, h_end].\n\n    Returns\n    -------\n    stmt : Stmt\n        The result IR statement.\n    \"\"\"\n    batch, num_bbox, _ = get_const_tuple(sorted_bbox_buf.shape)\n    rpn_post_nms_top_n = get_const_int(out_buf.shape[0]) // batch\n    ib = tvm.tir.ir_builder.create()\n    i = ib.allocate(\"int32\", (batch,), \"i\", scope=\"local\")\n    p_sorted_bbox = ib.buffer_ptr(sorted_bbox_buf)\n    p_remove = ib.buffer_ptr(remove_mask_buf)\n    p_out = ib.buffer_ptr(out_buf)\n\n    nkeep = ib.allocate(\"int32\", (batch,), \"nkeep\", scope=\"local\")\n\n    with ib.for_range(0, batch) as b:\n        nkeep[b] = 0\n        i[b] = 0\n\n    with ib.for_range(0, num_bbox) as j:\n        with ib.for_range(0, batch) as b:\n            with ib.if_scope(p_remove[b * num_bbox + j] == False):\n                nkeep[b] += 1\n    with ib.for_range(0, batch) as b:\n        with ib.if_scope(nkeep[b] > 0):\n            with ib.for_range(\n                0, te.ceil(tvm.tir.const(rpn_post_nms_top_n, \"float32\") / nkeep[b]).astype(\"int32\")\n            ):\n                with ib.for_range(0, num_bbox) as j:\n                    offset_j = (b * num_bbox + j) * 5\n                    offset_i = (b * rpn_post_nms_top_n + i[b]) * 5\n                    with ib.if_scope(\n                        tvm.tir.all(\n                            i[b] < rpn_post_nms_top_n, p_remove[(b * num_bbox + j)] == False\n                        )\n                    ):\n                        p_out[offset_i] = tvm.tir.Cast(\"float32\", b)\n                        with ib.for_range(0, 4, kind=\"unroll\") as k:\n                            p_out[offset_i + k + 1] = p_sorted_bbox[offset_j + k]\n                        i[b] = i[b] + 1\n\n    body = ib.get()\n    return body\n\n\ndef proposal(\n    cls_prob,\n    bbox_pred,\n    im_info,\n    scales,\n    ratios,\n    feature_stride,\n    threshold,\n    rpn_pre_nms_top_n,\n    rpn_post_nms_top_n,\n    rpn_min_size,\n    iou_loss,\n):\n    \"\"\"Proposal operator.\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        4-D with shape [batch, 2 * num_anchors, height, width]\n\n    bbox_pred : tvm.te.Tensor\n        4-D with shape [batch, 4 * num_anchors, height, width]\n\n    im_info : tvm.te.Tensor\n        2-D with shape [batch, 3]\n\n    scales : list/tuple of float\n        Scales of anchor windows.\n\n    ratios : list/tuple of float\n        Ratios of anchor windows.\n\n    feature_stride : int\n        The size of the receptive field each unit in the convolution layer of the rpn, for example\n        the product of all stride's prior to this layer.\n\n    threshold : float\n        Non-maximum suppression threshold.\n\n    rpn_pre_nms_top_n : int\n        Number of top scoring boxes to apply NMS. -1 to use all boxes.\n\n    rpn_post_nms_top_n : int\n        Number of top scoring boxes to keep after applying NMS to RPN proposals.\n\n    rpn_min_size : int\n        Minimum height or width in proposal.\n\n    iou_loss : bool\n        Usage of IoU loss.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        2-D tensor with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of\n        [batch_index, w_start, h_start, w_end, h_end].\n    \"\"\"\n    # pylint: disable=unused-argument\n    batch, _, height, width = get_const_tuple(cls_prob.shape)\n    num_anchors = len(scales) * len(ratios)\n    num_bbox = height * width * num_anchors\n    rpn_pre_nms_top_n = min(rpn_pre_nms_top_n, num_bbox) if rpn_pre_nms_top_n > 0 else num_bbox\n\n    bbox = te.extern(\n        (batch, num_bbox, 5),\n        [cls_prob, bbox_pred, im_info],\n        lambda ins, outs: predict_bbox_ir(\n            ins[0], ins[1], ins[2], outs[0], scales, ratios, feature_stride, rpn_min_size, iou_loss\n        ),\n        dtype=bbox_pred.dtype,\n    )\n    score = te.compute((batch, num_bbox), lambda b, i: bbox[b, i, 4], tag=\"bbox_score\")\n    valid_count_shape = (1,)\n    valid_count = te.compute(valid_count_shape, lambda i: num_bbox)\n    sorted_index = argsort(score, valid_count=valid_count, axis=1, is_ascend=False)\n    sorted_bbox = te.compute(\n        (batch, rpn_pre_nms_top_n, 5),\n        lambda b, i, j: bbox[b, sorted_index[b, i], j],\n        tag=\"sorted_bbox\",\n    )\n    nms_remove_mask = te.extern(\n        (batch, rpn_pre_nms_top_n),\n        [sorted_bbox],\n        lambda ins, outs: nms_ir(ins[0], outs[0], threshold),\n        dtype=\"bool\",\n    )\n    nms_out = te.extern(\n        (batch * rpn_post_nms_top_n, 5),\n        [sorted_bbox, nms_remove_mask],\n        lambda ins, outs: prepare_output_ir(ins[0], ins[1], outs[0]),\n        dtype=sorted_bbox.dtype,\n    )\n    return nms_out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/rcnn/roi_align.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Roi align operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom ...utils import get_const_tuple\nfrom ...cpp.utils import bilinear_sample_nchw, bilinear_sample_nhwc\n\n\ndef _sample_common(\n    i,\n    c,\n    ph,\n    pw,\n    rois,\n    pooled_size_h,\n    pooled_size_w,\n    spatial_scale,\n    sample_ratio,\n    dtype,\n    avg_mode,\n    bilinear_func,\n):\n    roi = rois[i]\n    batch_index = roi[0].astype(\"int32\")\n    roi_start_w, roi_start_h, roi_end_w, roi_end_h = roi[1], roi[2], roi[3], roi[4]\n    roi_start_h *= spatial_scale\n    roi_end_h *= spatial_scale\n    roi_start_w *= spatial_scale\n    roi_end_w *= spatial_scale\n\n    # force malformed ROIs to be 1x1\n    roi_h = tvm.te.max(roi_end_h - roi_start_h, tvm.tir.const(1.0, dtype))\n    roi_w = tvm.te.max(roi_end_w - roi_start_w, tvm.tir.const(1.0, dtype))\n\n    bin_h = roi_h / pooled_size_h\n    bin_w = roi_w / pooled_size_w\n\n    if sample_ratio > 0:\n        roi_bin_grid_h = roi_bin_grid_w = tvm.tir.const(sample_ratio, \"int32\")\n    else:\n        roi_bin_grid_h = te.ceil(roi_h / pooled_size_h).astype(\"int32\")\n        roi_bin_grid_w = te.ceil(roi_w / pooled_size_w).astype(\"int32\")\n\n    count = roi_bin_grid_h * roi_bin_grid_w\n    rh = te.reduce_axis((0, roi_bin_grid_h), name=\"rh\")\n    rw = te.reduce_axis((0, roi_bin_grid_w), name=\"rw\")\n    roi_start_h += ph * bin_h\n    roi_start_w += pw * bin_w\n\n    if avg_mode:\n        return te.sum(\n            bilinear_func(\n                batch_index,\n                c,\n                roi_start_h + (rh + 0.5) * bin_h / roi_bin_grid_h,\n                roi_start_w + (rw + 0.5) * bin_w / roi_bin_grid_w,\n            )\n            / count,\n            axis=[rh, rw],\n        )\n    # max mode\n    return te.max(\n        bilinear_func(\n            batch_index,\n            c,\n            roi_start_h + (rh + 0.5) * bin_h / roi_bin_grid_h,\n            roi_start_w + (rw + 0.5) * bin_w / roi_bin_grid_w,\n        ),\n        axis=[rh, rw],\n    )\n\n\ndef roi_align_nchw(data, rois, pooled_size, spatial_scale, mode, sample_ratio=-1):\n    \"\"\"ROI align operator in NCHW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    rois : tvm.te.Tensor\n        2-D with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : int or list/tuple of two ints\n        output size, or [out_height, out_width]\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    mode : int or str\n        There are two modes, average and max. For the average mode, you can pass b'avg' or 0, and\n        for the max mode, you can pass b'max' or 1.\n\n    sample_ratio : int\n        Optional sampling ratio of ROI align, using adaptive size by default.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    avg_mode = mode in (b\"avg\", 0)\n    max_mode = mode in (b\"max\", 1)\n    assert avg_mode or max_mode, \"Mode must be avg or max. Please pass in a valid mode.\"\n    dtype = rois.dtype\n    _, channel, height, width = get_const_tuple(data.shape)\n    num_roi, _ = get_const_tuple(rois.shape)\n\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    def _bilinear(i, c, y, x):\n        outside = tvm.tir.any(y < -1.0, x < -1.0, y > height, x > width)\n        y = tvm.te.min(tvm.te.max(y, 0.0), height - 1)\n        x = tvm.te.min(tvm.te.max(x, 0.0), width - 1)\n        val = bilinear_sample_nchw(data, (i, c, y, x), height - 1, width - 1)\n        return tvm.tir.if_then_else(outside, 0.0, val)\n\n    def _sample(i, c, ph, pw):\n        return _sample_common(\n            i,\n            c,\n            ph,\n            pw,\n            rois,\n            pooled_size_h,\n            pooled_size_w,\n            spatial_scale,\n            sample_ratio,\n            dtype,\n            avg_mode,\n            _bilinear,\n        )\n\n    return te.compute(\n        (num_roi, channel, pooled_size_h, pooled_size_w), _sample, tag=\"pool,roi_align_nchw\"\n    )\n\n\ndef roi_align_nhwc(data, rois, pooled_size, spatial_scale, mode, sample_ratio=-1):\n    \"\"\"ROI align operator in NHWC layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, height, width, channel]\n\n    rois : tvm.te.Tensor\n        2-D with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : int or list/tuple of two ints\n        output size, or [out_height, out_width]\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    mode : int or str\n        There are two modes, average and max. For the average mode, you can pass b'avg' or 0, and\n        for the max mode, you can pass b'max' or 1.\n\n    sample_ratio : int\n        Optional sampling ratio of ROI align, using adaptive size by default.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [num_roi, pooled_size, pooled_size, channel]\n    \"\"\"\n    avg_mode = mode in (b\"avg\", 0)\n    max_mode = mode in (b\"max\", 1)\n    assert avg_mode or max_mode, \"Mode must be avg or max. Please pass in a valid mode.\"\n    dtype = rois.dtype\n    _, height, width, channel = get_const_tuple(data.shape)\n    num_roi, _ = get_const_tuple(rois.shape)\n\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    def _bilinear(i, c, y, x):\n        outside = tvm.tir.any(y < -1.0, x < -1.0, y > height, x > width)\n        y = tvm.te.min(tvm.te.max(y, 0.0), height - 1)\n        x = tvm.te.min(tvm.te.max(x, 0.0), width - 1)\n        val = bilinear_sample_nhwc(data, (i, y, x, c), height - 1, width - 1)\n        return tvm.tir.if_then_else(outside, 0.0, val)\n\n    def _sample(i, ph, pw, c):\n        return _sample_common(\n            i,\n            c,\n            ph,\n            pw,\n            rois,\n            pooled_size_h,\n            pooled_size_w,\n            spatial_scale,\n            sample_ratio,\n            dtype,\n            avg_mode,\n            _bilinear,\n        )\n\n    return te.compute(\n        (num_roi, pooled_size_h, pooled_size_w, channel), _sample, tag=\"pool,roi_align_nchw\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/rcnn/roi_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"ROI pool operator\"\"\"\nimport tvm\nfrom tvm import te\nfrom ...utils import get_const_tuple\n\n\ndef roi_pool_nchw(data, rois, pooled_size, spatial_scale):\n    \"\"\"ROI pool operator in NCHW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    rois : tvm.te.Tensor\n        2-D with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : int or list/tuple of two ints\n        output size, or [out_height, out_width]\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    dtype = rois.dtype\n    _, channel, height, width = get_const_tuple(data.shape)\n    num_roi, _ = get_const_tuple(rois.shape)\n\n    if isinstance(pooled_size, int):\n        pooled_size_h = pooled_size_w = pooled_size\n    else:\n        pooled_size_h, pooled_size_w = pooled_size\n\n    def _pool(i, c, ph, pw):\n        roi = rois[i]\n        batch_index = roi[0].astype(\"int32\")\n        roi_start_w, roi_start_h, roi_end_w, roi_end_h = roi[1], roi[2], roi[3], roi[4]\n\n        roi_start_h = te.round(roi_start_h * spatial_scale).astype(\"int32\")\n        roi_start_w = te.round(roi_start_w * spatial_scale).astype(\"int32\")\n        roi_end_h = te.round(roi_end_h * spatial_scale).astype(\"int32\")\n        roi_end_w = te.round(roi_end_w * spatial_scale).astype(\"int32\")\n\n        # force malformed ROIs to be 1x1\n        roi_h = tvm.te.max(roi_end_h - roi_start_h + 1, tvm.tir.const(1, \"int32\"))\n        roi_w = tvm.te.max(roi_end_w - roi_start_w + 1, tvm.tir.const(1, \"int32\"))\n\n        bin_h = roi_h.astype(dtype) / pooled_size_h\n        bin_w = roi_w.astype(dtype) / pooled_size_w\n\n        # use epsilon to prevent floating point precision loss in floor/ceil\n        epsilon = tvm.tir.const(0.00001, dtype)\n        hstart = te.floor(ph * bin_h + epsilon).astype(\"int32\")\n        wstart = te.floor(pw * bin_w + epsilon).astype(\"int32\")\n        hend = te.ceil((ph + 1) * bin_h - epsilon).astype(\"int32\")\n        wend = te.ceil((pw + 1) * bin_w - epsilon).astype(\"int32\")\n        hstart = tvm.te.min(tvm.te.max(hstart + roi_start_h, 0), height)\n        wstart = tvm.te.min(tvm.te.max(wstart + roi_start_w, 0), width)\n        hend = tvm.te.min(tvm.te.max(hend + roi_start_h, 0), height)\n        wend = tvm.te.min(tvm.te.max(wend + roi_start_w, 0), width)\n\n        non_empty = tvm.tir.all(hstart < hend, wstart < wend)\n        min_value = lambda dtype: tvm.tir.if_then_else(\n            non_empty, tvm.te.min_value(dtype), tvm.tir.const(0.0, dtype)\n        )\n        # pylint: disable=unnecessary-lambda\n        _max = te.comm_reducer(lambda x, y: tvm.te.max(x, y), min_value, name=\"max\")\n        rh = te.reduce_axis((0, hend - hstart), \"rh\")\n        rw = te.reduce_axis((0, wend - wstart), \"rw\")\n        return _max(data[batch_index, c, hstart + rh, wstart + rw], axis=[rh, rw])\n\n    return te.compute((num_roi, channel, pooled_size_h, pooled_size_w), _pool, tag=\"pool,roi_pool\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/reorg.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nREORG Operator\n====================\nReorg operator, used in darknet.\n\"\"\"\nfrom __future__ import absolute_import as _abs\nfrom .. import cpp\n\n\ndef reorg(data, stride):\n    \"\"\"Reorg forward operators.\n\n    Parameters\n    ----------\n    Input : tvm.te.Tensor\n        4-D with shape [batch, in_channel, in_height, in_width]\n\n    stride : int\n        Stride value for reorganization\n\n    Returns\n    -------\n    Output : tvm.te.Tensor\n        4-D with shape [batch, out_channel, out_height, out_width]\n    \"\"\"\n    return cpp.vision.reorg(data, stride)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/ssd/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=wildcard-import\n\"\"\"VISION network operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .multibox import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/vision/ssd/multibox.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, undefined-variable\n\"\"\"SSD multibox operators\"\"\"\nimport tvm\n\nfrom tvm.te import hybrid\nfrom tvm.tir import exp, sqrt\n\nfrom tvm import topi\n\nfrom ..nms import non_max_suppression\n\n\n@hybrid.script\ndef hybrid_multibox_prior(data, sizes, ratios, steps, offsets):\n    \"\"\"Hybrid routing for multibox_prior operator.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or numpy NDArray\n        4-D tensor with shape [batch, channel, height, width]]\n\n    sizes : tvm ConsExpr\n        Sizes for anchor boxes.\n\n    ratios : tvm ConsExpr\n        Ratios for anchor boxes.\n\n    steps : tvm ConsExpr\n        Priorbox step across y and x, -1 for auto calculation.\n\n    offsets : tvm ConsExpr\n        Priorbox center offsets, y and x respectively.\n\n    Returns\n    -------\n    output : tvm.te.Tensor or numpy NDArray\n        3-D tensor with shape [1, h_in * w_in * (num_sizes + num_ratios - 1), 4]\n    \"\"\"\n    in_height = data.shape[2]\n    in_width = data.shape[3]\n    num_sizes = len(sizes)\n    num_ratios = len(ratios)\n    num_boxes = in_height * in_width * (num_sizes + num_ratios - 1)\n    output = output_tensor((1, num_boxes, 4), \"float32\")\n    steps_h = steps[0] * 1.0 if steps[0] > 0 else 1.0 / in_height\n    steps_w = steps[1] * 1.0 if steps[1] > 0 else 1.0 / in_width\n    offset_h = offsets[0]\n    offset_w = offsets[1]\n\n    # Need to define var out of const_range + if\n    w = 0.0\n    h = 0.0\n\n    for i in parallel(in_height):\n        center_h = (i + offset_h) * steps_h\n        for j in range(in_width):\n            center_w = (j + offset_w) * steps_w\n            for k in const_range(num_sizes + num_ratios - 1):\n                if k < num_sizes:\n                    w = float32(sizes[k] * in_height) / in_width / 2.0\n                    h = sizes[k] / 2.0\n                else:\n                    w = (\n                        float32(sizes[0] * in_height)\n                        / in_width\n                        * sqrt(ratios[k - num_sizes + 1] * 1.0)\n                        / 2.0\n                    )\n                    h = sizes[0] / sqrt(ratios[k - num_sizes + 1] * 1.0) / 2.0\n                count = (\n                    i * in_width * (num_sizes + num_ratios - 1)\n                    + j * (num_sizes + num_ratios - 1)\n                    + k\n                )\n                output[0, count, 0] = center_w - w\n                output[0, count, 1] = center_h - h\n                output[0, count, 2] = center_w + w\n                output[0, count, 3] = center_h + h\n\n    return output\n\n\ndef multibox_prior(data, sizes=(1,), ratios=(1,), steps=(-1, -1), offsets=(0.5, 0.5), clip=False):\n    \"\"\"Generate prior(anchor) boxes from data, sizes and ratios.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, c_in, h_in, w_in]]\n\n    sizes : tuple of float\n        Tuple of sizes for anchor boxes.\n\n    ratios : tuple of float\n        Tuple of ratios for anchor boxes.\n\n    steps : Tuple of float\n        Priorbox step across y and x, -1 for auto calculation.\n\n    offsets : tuple of int\n        Priorbox center offsets, y and x respectively.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        3-D tensor with shape [1, h_in * w_in * (num_sizes + num_ratios - 1), 4]\n    \"\"\"\n    out = hybrid_multibox_prior(\n        data,\n        tvm.runtime.convert(sizes),\n        tvm.runtime.convert(ratios),\n        tvm.runtime.convert(steps),\n        tvm.runtime.convert(offsets),\n    )\n    if clip:\n        out = topi.clip(out, 0, 1)\n    return out\n\n\n@hybrid.script\ndef _hybridy_transform_loc(box, pred_loc, variance, clip):\n    \"\"\"Transform prior anchor box to output box through location predictions.\"\"\"\n    al = box[0]\n    at = box[1]\n    ar = box[2]\n    ab = box[3]\n\n    px = pred_loc[0]\n    py = pred_loc[1]\n    pw = pred_loc[2]\n    ph = pred_loc[3]\n\n    vx = variance[0]\n    vy = variance[1]\n    vw = variance[2]\n    vh = variance[3]\n\n    output = output_tensor((4,), pred_loc.dtype)\n\n    aw = ar - al\n    ah = ab - at\n    ax = (al + ar) / 2.0\n    ay = (at + ab) / 2.0\n    ox = px * vx * aw + ax\n    oy = py * vy * ah + ay\n    ow = exp(pw * vw) * aw / 2.0\n    oh = exp(ph * vh) * ah / 2.0\n    output[0] = max(0.0, min(1.0, ox - ow)) if clip else ox - ow\n    output[1] = max(0.0, min(1.0, oy - oh)) if clip else oy - oh\n    output[2] = max(0.0, min(1.0, ox + ow)) if clip else ox + ow\n    output[3] = max(0.0, min(1.0, oy + oh)) if clip else oy + oh\n    return output\n\n\n@hybrid.script\ndef hybrid_multibox_transform_loc(cls_prob, loc_pred, anchor, clip, threshold, variances):\n    \"\"\"Hybrid routing for transform location in multibox_detection operator.\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor or numpy NDArray\n        3-D tensor of class probabilities.\n\n    loc_pred : tvm.te.Tensor or numpy NDArray\n        2-D tensor of location regression predictions.\n\n    anchor : tvm.te.Tensor or numpy NDArray\n        3-D tensor of prior anchor boxes.\n\n    clip : tvm.tir.const\n        Whether to clip out-of-boundary boxes.\n\n    threshold : tvm.tir.const\n        Threshold to be a positive prediction.\n\n    variances : tvm.nd.NDArray\n        Variances to be decoded from box regression output.\n\n    Returns\n    -------\n    out_loc : tvm.te.Tensor or numpy NDArray\n        3-D tensor of transformed location.\n\n    valid_count : tvm.te.Tensor or numpy NDArray\n        1_d tensor of valid counts for boxes.\n    \"\"\"\n    batch_size = cls_prob.shape[0]\n    num_classes = cls_prob.shape[1]\n    num_anchors = cls_prob.shape[2]\n    box_coord = allocate((4,), loc_pred.dtype)\n    pred_coord = allocate((4,), loc_pred.dtype)\n    out_loc = output_tensor((batch_size, num_anchors, 6), loc_pred.dtype)\n    valid_count = output_tensor((batch_size,), \"int32\")\n\n    for i in parallel(batch_size):\n        valid_count[i] = 0\n        for j in range(num_anchors):\n            # Find the predicted class id and probability\n            score = -1.0\n            cls_id = 0\n            for k in range(num_classes):\n                if k > 0:\n                    temp = cls_prob[i, k, j]\n                    cls_id = k if temp > score else cls_id\n                    score = max(temp, score)\n            if cls_id > 0 and score < threshold:\n                cls_id = 0\n            # [id, prob, xmin, ymin, xmax, ymax]\n            # Remove background, restore original id\n            if cls_id > 0:\n                out_loc[i, valid_count[i], 0] = cls_id - 1.0\n                out_loc[i, valid_count[i], 1] = score\n                for l in range(4):\n                    box_coord[l] = anchor[0, j, l]\n                    pred_coord[l] = loc_pred[i, j * 4 + l]\n                out_coord = _hybridy_transform_loc(box_coord, pred_coord, variances, clip)\n                out_loc[i, valid_count[i], 2] = out_coord[0]\n                out_loc[i, valid_count[i], 3] = out_coord[1]\n                out_loc[i, valid_count[i], 4] = out_coord[2]\n                out_loc[i, valid_count[i], 5] = out_coord[3]\n                valid_count[i] += 1\n\n    return out_loc, valid_count\n\n\ndef multibox_transform_loc(\n    cls_prob, loc_pred, anchor, clip=True, threshold=0.01, variances=(0.1, 0.1, 0.2, 0.2)\n):\n    \"\"\"Location transformation for multibox detection\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        Class probabilities.\n\n    loc_pred : tvm.te.Tensor\n        Location regression predictions.\n\n    anchor : tvm.te.Tensor\n        Prior anchor boxes.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    threshold : float\n        Threshold to be a positive prediction.\n\n    variances : tuple of float\n        Variances to be decoded from box regression output.\n\n    Returns\n    -------\n    ret : tuple of tvm.te.Tensor\n    \"\"\"\n    return hybrid_multibox_transform_loc(\n        cls_prob,\n        loc_pred,\n        anchor,\n        tvm.tir.const(clip, \"bool\"),\n        tvm.tir.const(threshold, \"float32\"),\n        tvm.runtime.convert(variances),\n    )\n\n\ndef multibox_detection(\n    cls_prob,\n    loc_pred,\n    anchor,\n    clip=True,\n    threshold=0.01,\n    nms_threshold=0.5,\n    force_suppress=False,\n    variances=(0.1, 0.1, 0.2, 0.2),\n    nms_topk=-1,\n):\n    \"\"\"Convert multibox detection predictions.\n\n    Parameters\n    ----------\n    cls_prob : tvm.te.Tensor\n        Class probabilities.\n\n    loc_pred : tvm.te.Tensor\n        Location regression predictions.\n\n    anchor : tvm.te.Tensor\n        Prior anchor boxes.\n\n    clip : boolean\n        Whether to clip out-of-boundary boxes.\n\n    nms_threshold : float\n        Non-maximum suppression threshold.\n\n    force_suppress : boolean\n        Whether to suppress all detections regardless of class_id.\n\n    threshold : float\n        Threshold to be a positive prediction.\n\n    variances : tuple of float\n        Variances to be decoded from box regression output.\n\n    nms_topk : int\n        Keep maximum top k detections before nms, -1 for no limit.\n\n    Returns\n    -------\n    out : tvm.te.Tensor\n        3-D tensor with shape (batch_size, num_anchors, 6)\n    \"\"\"\n    inter_out = multibox_transform_loc(cls_prob, loc_pred, anchor, clip, threshold, variances)\n    out = non_max_suppression(\n        inter_out[0],\n        inter_out[1],\n        inter_out[1],\n        max_output_size=-1,\n        iou_threshold=nms_threshold,\n        force_suppress=force_suppress,\n        top_k=nms_topk,\n        return_indices=False,\n    )\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=redefined-builtin, wildcard-import\n\"\"\"x86 specific declaration and schedules.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nfrom .conv1d import *\nfrom .conv2d import *\nfrom .conv3d import *\nfrom .binarize_pack import schedule_binarize_pack\nfrom .binary_dense import schedule_binary_dense\nfrom .nn import *\nfrom .conv2d_int8 import *\nfrom .injective import *\nfrom .reduction import *\nfrom .pooling import schedule_pool, schedule_adaptive_pool\nfrom .bitserial_conv2d import *\nfrom .bitserial_dense import *\nfrom .depthwise_conv2d import *\nfrom .dense import *\nfrom .batch_matmul import *\nfrom .roi_align import roi_align_nchw\nfrom .conv2d_transpose import *\nfrom .conv3d_transpose import *\nfrom .sparse import *\nfrom .conv2d_alter_op import *\nfrom .dense_alter_op import *\nfrom .scatter import *\nfrom .group_conv2d import *\nfrom .math_alter_op import *\nfrom .concat import *\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,unused-variable\n\"\"\"x86 batch_matmul operators\"\"\"\nimport tvm\nfrom tvm import autotvm, te\nfrom tvm.autotvm.task.space import SplitEntity\nfrom tvm.contrib import cblas, mkl\n\nfrom .. import generic, nn\nfrom ..transform import layout_transform\nfrom ..utils import get_const_tuple, get_max_power2_factor, traverse_inline\nfrom .dense import dense_vnni_schedule\nfrom .injective import schedule_injective_from_existing\n\n\n@autotvm.register_topi_compute(\"batch_matmul_vnni.x86\")\ndef batch_matmul_vnni_compute(cfg, x, y, *_):\n    \"\"\"Compute for uint8 x int8 -> int32 batch_matmul\"\"\"\n    batch, m, k = x.shape\n    packed_y_layout = \"BNK16n4k\"\n    packed_y = layout_transform(y, \"BNK\", packed_y_layout)\n    _, n_o, _, n_i, _ = packed_y.shape\n    ak = te.reduce_axis((0, k), name=\"k\")\n\n    z = te.compute(\n        (batch, m, n_o * n_i),\n        lambda b, i, j: te.sum(\n            x[b, i, ak].astype(\"int32\")\n            * packed_y[b, tvm.tir.indexdiv(j, 16), tvm.tir.indexdiv(ak, 4), j % 16, ak % 4].astype(\n                \"int32\"\n            ),\n            axis=ak,\n        ),\n        tag=\"batch_matmul_vnni\",\n        attrs={\"schedule_rule\": \"batch_matmul_vnni\"},\n    )\n\n    _, a_y, _ = z.op.axis\n    cfg.define_split(\"tile_y\", a_y, num_outputs=2)\n    cfg.define_knob(\"layout_trans_compute_root\", [0, 1])\n\n    return z\n\n\ndef batch_matmul_vnni_schedule(cfg, s, C, O, layout_trans):\n    \"\"\"Schedule batch_matmul compute using VNNI vpdpbusd instruction\"\"\"\n    # C: The output of batched GEMM\n    # O: The output of the fused op\n\n    # Schedule the GEMM part\n    s, fused_inner = dense_vnni_schedule(cfg, s, C, O, do_parallel=False)\n    # Parallelize over batch\n    fused = s[O].fuse(O.op.axis[0], fused_inner)\n    s[O].parallel(fused)\n\n    if cfg[\"layout_trans_compute_root\"].val:\n        s[layout_trans].compute_root()\n        schedule_injective_from_existing(s, layout_trans)\n    else:\n        s[layout_trans].compute_at(s[O], fused)\n        _, _, _, ni, ki = s[layout_trans].op.axis\n        s[layout_trans].vectorize(ki)\n        s[layout_trans].unroll(ni)\n\n    return s\n\n\n@autotvm.register_topi_compute(\"batch_matmul.x86\")\ndef batch_matmul(\n    cfg, tensor_a, tensor_b, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Compute batch matrix multiplication of `tensor_a` and `tensor_b`.\n\n    Both `tensor_a` and `tensor_b` can be transposed. For legacy reason, we use NT format\n    (transpose_a=False, transpose_b=True) by default.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file.\n\n    tensor_a : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    tensor_b : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    out_shape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    out_dtype : Optional[str]\n        Specifies the output data type for mixed precision batch matmul.\n\n    transpose_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    transpose_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    if cfg.is_fallback:\n        if transpose_a:\n            _, K, M = get_const_tuple(tensor_a.shape)\n        else:\n            _, M, K = get_const_tuple(tensor_a.shape)\n        if transpose_b:\n            _, N, _ = get_const_tuple(tensor_b.shape)\n        else:\n            _, _, N = get_const_tuple(tensor_b.shape)\n        _default_batch_matmul_config(cfg, M, N, K)\n    return nn.batch_matmul(\n        tensor_a,\n        tensor_b,\n        out_shape,\n        out_dtype,\n        transpose_a,\n        transpose_b,\n    )\n\n\n@autotvm.register_topi_schedule(\"batch_matmul.x86\")\ndef schedule_batch_matmul(cfg, outs):\n    \"\"\"Schedule for batch_matmul\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        AutoTVM tuning space config file.\n    outs : Array of Tensor\n        The computation graph description of batch_matmul\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"batch_matmul\" in op.tag:\n            C = op.output(0)\n            A, B = op.input_tensors\n            if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A:\n                s[B].compute_inline()\n            _, M, K = get_const_tuple(A.shape)\n            _, _, N = get_const_tuple(C.shape)\n\n            if op not in s.outputs:\n                s[C].compute_inline()\n                O = outs[0]\n            else:\n                O = C\n\n            CC = s.cache_write(C, \"global\")\n\n            # create tuning space\n            cfg.define_split(\"tile_y\", M, num_outputs=2)\n            cfg.define_split(\"tile_x\", N, num_outputs=2)\n            cfg.define_split(\"tile_k\", K, num_outputs=2)\n\n            b, y, x = s[O].op.axis\n            yo, yi = cfg[\"tile_y\"].apply(s, O, y)\n            xo, xi = cfg[\"tile_x\"].apply(s, O, x)\n            s[O].reorder(b, yo, xo, yi, xi)\n            bxyo = s[O].fuse(b, yo, xo)\n            s[O].parallel(bxyo)\n\n            s[CC].compute_at(s[O], bxyo)\n            (k,) = s[CC].op.reduce_axis\n            ko, ki = cfg[\"tile_k\"].apply(s, CC, k)\n\n            Crf = s.rfactor(CC, ki)\n            s[Crf].compute_at(s[CC], s[CC].op.axis[0])\n            _, _, y, x = s[Crf].op.axis\n            s[Crf].fuse(y, x)\n            s[Crf].vectorize(s[Crf].op.axis[0])\n            s[O].pragma(bxyo, \"auto_unroll_max_step\", 16)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_vnni.x86\")\ndef schedule_batch_matmul_vnni(cfg, outs):\n    \"\"\"Schedule for batch_matmul_vnni\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"batch_matmul_vnni\" in op.tag:\n            layout_trans = op.input_tensors[1]\n            batch_matmul_vnni_schedule(cfg, s, op.output(0), outs[0], layout_trans)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _default_batch_matmul_config(cfg, M, N, K):\n    cfg[\"tile_k\"] = SplitEntity([K // 16, 16])\n    x_bn = get_max_power2_factor(N, 8)\n    cfg[\"tile_x\"] = SplitEntity([N // x_bn, x_bn])\n    y_bn = get_max_power2_factor(M, 8)\n    cfg[\"tile_y\"] = SplitEntity([M // y_bn, y_bn])\n\n\ndef batch_matmul_blas_common(cfg, tensor_a, tensor_b, out_shape, trans_a, trans_b, lib):\n    \"\"\"Computes batch matrix multiplication of `tensor_a` and `tensor_b` when `tensor_a` and\n    `tensor_b` are data in batch, using one of BLAS libraries. Supports broadcasting in batch\n    dimension.\n\n    Parameters\n    ----------\n    cfg : ConfigSpace\n        Autotvm tuning space config file\n\n    tensor_a : tvm.te.Tensor\n        3-D with shape [batch, M, K] or [batch, K, M].\n\n    tensor_b : tvm.te.Tensor\n        3-D with shape [batch, K, N] or [batch, N, K].\n\n    out_shape : List[Optional]\n        Explicit intended output shape of the computation. Can be useful in cases\n        with dynamic input shapes.\n\n    trans_a : Optional[bool] = False\n        Whether the first tensor is in transposed format.\n\n    trans_b : Optional[bool] = True\n        Whether the second tensor is in transposed format.\n\n    lib : A contrib module which implements batch_matmul function\n        cblas and mkl are supported\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        3-D with shape [batch, M, N]\n    \"\"\"\n    assert len(tensor_a.shape) == 3 and len(tensor_b.shape) == 3, \"only support 3-dim batch_matmul\"\n    if trans_a:\n        XB, XK, M = get_const_tuple(tensor_a.shape)\n    else:\n        XB, M, XK = get_const_tuple(tensor_a.shape)\n    if trans_b:\n        YB, N, YK = get_const_tuple(tensor_b.shape)\n    else:\n        YB, YK, N = get_const_tuple(tensor_a.shape)\n    assert (XB == YB) or (YB == 1) or (XB == 1), \"batch dimension doesn't match\"\n    assert XK == YK, \"shapes of x and y is inconsistent\"\n    if out_shape is not None:\n        assert out_shape[0] in (XB, YB), \"got invalid output shape\"\n        assert out_shape[1] == M, \"got invalid output shape\"\n        assert out_shape[2] == N, \"got invalid output shape\"\n    cfg.add_flop(XB * M * N * XK * 2)\n    return lib.batch_matmul(tensor_a, tensor_b, trans_a, trans_b)\n\n\n@autotvm.register_topi_compute(\"batch_matmul_cblas.x86\")\ndef batch_matmul_cblas(\n    cfg, tensor_a, tensor_b, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Compute batch_matmul using cblas\"\"\"\n    del out_dtype  # Unused argument\n    return batch_matmul_blas_common(\n        cfg, tensor_a, tensor_b, out_shape, transpose_a, transpose_b, cblas\n    )\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_cblas.x86\")\ndef schedule_batch_matmul_cblas(_, outs):\n    \"\"\"Create schedule for batch_matmul_cblas\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"batch_matmul_mkl.x86\")\ndef batch_matmul_mkl(\n    cfg, tensor_a, tensor_b, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True\n):\n    \"\"\"Compute batch_matmul using mkl\"\"\"\n    del out_dtype  # Unused argument\n    return batch_matmul_blas_common(\n        cfg, tensor_a, tensor_b, out_shape, transpose_a, transpose_b, mkl\n    )\n\n\n@autotvm.register_topi_schedule(\"batch_matmul_mkl.x86\")\ndef schedule_batch_matmul_mkl(_, outs):\n    \"\"\"Create schedule for batch_matmul_mul\"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/binarize_pack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Schedule for binarization and bit-packing.\"\"\"\nfrom tvm import te\n\n\ndef schedule_binarize_pack(outs):\n    \"\"\"Schedule for binarize_pack.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of binarize_pack\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for binarize_pack.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(Out):\n        s[Out].parallel(Out.op.axis[0])\n\n    def traverse(OP):\n        # schedule binarize_pack\n        if OP.tag == \"binarize_pack\":\n            Out = OP.output(0)\n            _schedule(Out)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/binary_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument\n\"\"\"Schedule for binary dense operator.\"\"\"\nfrom tvm import te\nfrom .. import tag\n\n\ndef schedule_binary_dense(outs):\n    \"\"\"Schedule for binary_dense.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of binary_dense\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for binary_dense.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def _schedule(A, B, C):\n        s[C].split(s[C].op.reduce_axis[0], factor=8)\n        s[C].parallel(s[C].op.axis[0])\n        if C.op in s.outputs:\n            Out = C\n        else:\n            Out = outs[0].op.output(0)\n        xo, xi = s[Out].split(Out.op.axis[1], factor=8)\n        s[Out].vectorize(xi)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule binary_dense\n        elif OP.tag == \"binary_dense\":\n            output = OP.output(0)\n            data = OP.input_tensors[0]\n            weight = OP.input_tensors[1]\n            _schedule(data, weight, output)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/bitserial_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,invalid-name\n\"\"\"Bitserial conv2d schedule on x86\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom .. import tag\nfrom ..utils import get_const_int, get_const_tuple\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple\nfrom ..nn.bitserial_util import bitpack, binary_op_multiplier\n\n\n@autotvm.register_topi_compute(\"bitserial_conv2d_nchw.x86\")\ndef bitserial_conv2d_nchw(\n    cfg,\n    data,\n    kernel,\n    stride,\n    padding,\n    in_bits,\n    weight_bits,\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    \"\"\"Compute convolution with pack on spatial axes.\"\"\"\n    assert data.shape[0].value == 1, \"spatial pack convolution only support batch size=1\"\n    data_q = bitpack(data, in_bits, pack_axis=1, bit_axis=0, pack_type=pack_dtype)\n    # Check if kernel is already bitpacked\n    if len(kernel.shape) == 4:\n        kernel_q = bitpack(kernel, weight_bits, pack_axis=1, bit_axis=0, pack_type=pack_dtype)\n        KB, CO, _, KH, KW = get_const_tuple(kernel_q.shape)\n    else:\n        kernel_vec = kernel\n        OCO, _, KH, KW, KB, VC = get_const_tuple(kernel_vec.shape)\n        CO = OCO * VC\n\n    IB, N, CI, H, W = get_const_tuple(data_q.shape)\n    KB, CO, _, KH, KW = get_const_tuple(kernel_q.shape)\n\n    if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2):\n        TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel)\n    else:\n        TPAD, LPAD, DPAD, RPAD = padding\n    pad_before = [0, 0, 0, TPAD, LPAD]\n    pad_after = [0, 0, 0, DPAD, RPAD]\n\n    if isinstance(stride, (tuple, list)):\n        HSTR, WSTR = stride\n    else:\n        HSTR, WSTR = stride, stride\n    HCAT, WCAT = KH - 1, KW - 1\n\n    TH = H + TPAD + DPAD\n    TW = W + LPAD + RPAD\n    OH = (H + TPAD + DPAD - KH) // HSTR + 1\n    OW = (W + LPAD + RPAD - KW) // WSTR + 1\n\n    # ==================== define configuration space ====================\n    n, co, oh, ow = cfg.axis(N), cfg.axis(CO), cfg.axis(OH), cfg.axis(OW)\n    ci, kh, kw = cfg.reduce_axis(CI), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n    ib, kb = cfg.reduce_axis(in_bits), cfg.reduce_axis(weight_bits)\n\n    co, vc = cfg.define_split(\"tile_co\", co, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    cfg.define_annotate(\"ann_reduce\", [ib, kb, kh, kw], policy=\"try_unroll\")\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [n, co, oh, ow, vc, vh, vw, kh, kw, kb, ib, ci],\n        policy=\"interval_all\",\n        interval=(6, 11),\n    )\n    # binary ops\n    cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW * binary_op_multiplier(pack_dtype))\n    # ====================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    dvshape = (1, TH // (VH * HSTR), TW // (VW * WSTR), CI, VH * HSTR + HCAT, VW * WSTR + WCAT, IB)\n    kvshape = (CO // VC, CI, KH, KW, KB, VC)\n    ovshape = (1, CO // VC, OH // VH, OW // VW, VH, VW, VC)\n    oshape = (1, CO, OH, OW)\n\n    if TPAD != 0 and RPAD != 0:\n        data_pad = pad(data_q, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data_q\n\n    data_vec = te.compute(\n        dvshape,\n        lambda n, h, w, ci, vh, vw, b: data_pad[b][n][ci][h * VH * HSTR + vh][w * VW * WSTR + vw],\n        name=\"data_vec\",\n    )\n\n    if len(kernel.shape) == 4:\n        kernel_vec = te.compute(\n            kvshape,\n            lambda co, ci, dh, dw, b, vc: kernel_q[b][co * VC + vc][ci][dh][dw],\n            name=\"kernel_vec\",\n        )\n\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    dh = te.reduce_axis((0, KH), name=\"dh\")\n    dw = te.reduce_axis((0, KW), name=\"dw\")\n    b1 = te.reduce_axis((0, IB), name=\"ib\")\n    b2 = te.reduce_axis((0, KB), name=\"kb\")\n\n    def _conv(n, co, h, w, vh, vw, vc):\n        b1b2 = (b1 + b2).astype(out_dtype)\n        if unipolar:\n            return te.sum(\n                (\n                    tvm.tir.popcount(\n                        data_vec[n, h, w, ci, vh * HSTR + dh, vw * WSTR + dw, b1].astype(out_dtype)\n                        & kernel_vec[co, ci, dh, dw, b2, vc].astype(out_dtype)\n                    )\n                    - tvm.tir.popcount(\n                        data_vec[n, h, w, ci, vh * HSTR + dh, vw * WSTR + dw, b1].astype(out_dtype)\n                        & ~kernel_vec[co, ci, dh, dw, b2, vc]\n                    ).astype(out_dtype)\n                )\n                << b1b2,\n                axis=[ci, dh, dw, b1, b2],\n            )\n\n        return te.sum(\n            (\n                tvm.tir.popcount(\n                    data_vec[n, h, w, ci, vh * HSTR + dh, vw * WSTR + dw, b1]\n                    & kernel_vec[co, ci, dh, dw, b2, vc]\n                )\n            ).astype(out_dtype)\n            << b1b2,\n            axis=[ci, dh, dw, b1, b2],\n        )\n\n    conv = te.compute(ovshape, _conv, name=\"conv_out\")\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    return te.compute(\n        oshape,\n        lambda n, co, h, w: conv[\n            n, idxd(co, VC), idxd(h, VH), idxd(w, VW), idxm(h, VH), idxm(w, VW), idxm(co, VC)\n        ],\n        name=\"conv_vec\",\n        tag=\"spatial_bitserial_conv_nchw\",\n    )\n\n\n@autotvm.register_topi_compute(\"bitserial_conv2d_nhwc.x86\")\ndef bitserial_conv2d_nhwc(\n    cfg,\n    data,\n    kernel,\n    stride,\n    padding,\n    in_bits,\n    weight_bits,\n    pack_dtype=\"uint32\",\n    out_dtype=\"int16\",\n    unipolar=True,\n):\n    \"\"\"Compute convolution with pack on spatial axes.\"\"\"\n    assert data.shape[0].value == 1, \"spatial pack convolution only support batch size=1\"\n    data_q = bitpack(data, in_bits, pack_axis=3, bit_axis=4, pack_type=pack_dtype)\n    pack_kernel = len(kernel.shape) == 4\n\n    if pack_kernel:\n        kernel_q = bitpack(kernel, weight_bits, pack_axis=2, bit_axis=4, pack_type=pack_dtype)\n    else:\n        kernel_q = kernel\n\n    KH, KW, _, CO, KB = get_const_tuple(kernel_q.shape)\n    N, H, W, CI, IB = get_const_tuple(data_q.shape)\n\n    if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2):\n        TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel)\n    else:\n        TPAD, LPAD, DPAD, RPAD = padding\n    pad_before = [0, TPAD, LPAD, 0, 0]\n    pad_after = [0, DPAD, RPAD, 0, 0]\n\n    if isinstance(stride, (tuple, list)):\n        HSTR, WSTR = stride\n    else:\n        HSTR, WSTR = stride, stride\n    HCAT, WCAT = KH - 1, KW - 1\n\n    PAD_H = H + (TPAD + DPAD)\n    PAD_W = W + (LPAD + RPAD)\n    OH = (PAD_H - KH) // HSTR + 1\n    OW = (PAD_W - KW) // WSTR + 1\n    oshape = (1, OH, OW, CO)\n\n    # ==================== define configuration space ====================\n    n, oh, ow, co = cfg.axis(N), cfg.axis(OH), cfg.axis(OW), cfg.axis(CO)\n    ci, kh, kw = cfg.reduce_axis(CI), cfg.reduce_axis(KH), cfg.reduce_axis(KW)\n    ib, kb = cfg.reduce_axis(in_bits), cfg.reduce_axis(weight_bits)\n\n    co, vc = cfg.define_split(\"tile_co\", co, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    oh, vh = cfg.define_split(\"tile_oh\", oh, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    ow, vw = cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda x: max(x.size[1:]) <= 16)\n    cfg.define_annotate(\"ann_reduce\", [ib, kb, kh, kw], policy=\"try_unroll\")\n    cfg.define_reorder(\n        \"reorder_0\",\n        [n, oh, ow, co, vh, vw, kh, kw, kb, ib, vc, ci],\n        policy=\"interval_all\",\n        interval=(3, 7),\n    )\n    # binary ops\n    cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW * binary_op_multiplier(pack_dtype))\n    # ====================\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    dvshape = (\n        1,\n        PAD_H // (VH * HSTR),\n        PAD_W // (VW * WSTR),\n        VH * HSTR + HCAT,\n        VW * WSTR + WCAT,\n        CI,\n        IB,\n    )\n    kvshape = (CO, KH, KW, CI, VC, KB)\n    ovshape = (1, OH, OW, CO, VH, VW, VC)\n    oshape = (1, OH, OW, CO)\n\n    if DPAD != 0 and RPAD != 0:\n        data_pad = pad(data_q, pad_before, pad_after, name=\"data_pad\")\n    else:\n        data_pad = data_q\n\n    data_vec = te.compute(\n        dvshape,\n        lambda n, h, w, vh, vw, ci, b: data_pad[n][h * VH * HSTR + vh][w * VW * WSTR + vw][ci][b],\n        name=\"data_vec\",\n    )\n\n    kernel_vec = te.compute(\n        kvshape,\n        lambda co, dh, dw, ci, vc, b: kernel_q[dh][dw][ci][co * VC + vc][b],\n        name=\"kernel_vec\",\n    )\n\n    ci = te.reduce_axis((0, CI), name=\"ci\")\n    dh = te.reduce_axis((0, KH), name=\"dh\")\n    dw = te.reduce_axis((0, KW), name=\"dw\")\n    b1 = te.reduce_axis((0, IB), name=\"ib\")\n    b2 = te.reduce_axis((0, KB), name=\"kb\")\n\n    def _conv(n, h, w, co, vh, vw, vc):\n        b1b2 = (b1 + b2).astype(out_dtype)\n        if unipolar:\n            return te.sum(\n                (\n                    (\n                        tvm.tir.popcount(\n                            data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ci, b1]\n                            & kernel_vec[co, dh, dw, ci, vc, b2]\n                        ).astype(out_dtype)\n                        - tvm.tir.popcount(\n                            data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ci, b1]\n                            & ~kernel_vec[co, dh, dw, ci, vc, b2]\n                        ).astype(out_dtype)\n                    )\n                    << b1b2\n                ),\n                axis=[dh, dw, ci, b1, b2],\n            )\n\n        return te.sum(\n            tvm.tir.popcount(\n                data_vec[n, h, w, vh * HSTR + dh, vw * WSTR + dw, ci, b1]\n                & kernel_vec[co, dh, dw, ci, vc, b2]\n            ).astype(out_dtype)\n            << b1b2,\n            axis=[dh, dw, ci, b1, b2],\n        )\n\n    conv = te.compute(ovshape, _conv, name=\"conv\")\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n    return te.compute(\n        oshape,\n        lambda n, h, w, co: conv[\n            n, idxd(h, VH), idxd(w, VW), idxd(co, VC), idxm(h, VH), idxm(w, VW), idxm(co, VC)\n        ],\n        name=\"output_unpack\",\n        tag=\"spatial_bitserial_conv_nhwc\",\n    )\n\n\n@autotvm.register_topi_schedule(\"bitserial_conv2d_nchw.x86\")\ndef schedule_bitserial_conv2d_nchw(cfg, outs):\n    return _schedule_bitserial_conv2d(cfg, outs)\n\n\n@autotvm.register_topi_schedule(\"bitserial_conv2d_nhwc.x86\")\ndef schedule_bitserial_conv2d_nhwc(cfg, outs):\n    return _schedule_bitserial_conv2d(cfg, outs)\n\n\ndef _schedule_bitserial_conv2d(cfg, outs):\n    \"\"\"CPU schedule for bitserial convolutions NCHW and NHWC\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        output = op.output(0)\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag) or \"elemwise\" in op.tag:\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if tensor.op.input_tensors and (tensor.op not in scheduled_ops):\n                    if isinstance(tensor.op, tvm.te.ComputeOp):\n                        traverse(tensor.op)\n\n        elif \"spatial_bitserial_conv_nchw\" in op.tag or \"spatial_bitserial_conv_nhwc\" in op.tag:\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel_q = kernel_vec.op.input_tensors[0]\n            data_vec = conv_out.op.input_tensors[0]\n            data_q = data_vec.op.input_tensors[0]\n            data = data_q.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data_q.op, tvm.te.ComputeOp) and \"pad\" in data_q.op.tag:\n                data_pad = data_q\n                data_q = data\n                data = data_q.op.input_tensors[0]\n\n            if \"QuantizeInput\" in data.op.name:\n                # Need to go up 1 further, from the combine in bitpack\n                data = data.op.input_tensors[0]\n\n            if \"spatial_bitserial_conv_nchw\" in op.tag:\n                _schedule_bitserial_conv2d_nchw(\n                    cfg,\n                    s,\n                    data_q,\n                    data_pad,\n                    data_vec,\n                    kernel_q,\n                    kernel_vec,\n                    conv_out,\n                    output,\n                    outs[0],\n                )\n            elif \"spatial_bitserial_conv_nhwc\" in op.tag:\n                _schedule_bitserial_conv2d_nhwc(\n                    cfg,\n                    s,\n                    data_q,\n                    data_pad,\n                    data_vec,\n                    kernel_q,\n                    kernel_vec,\n                    conv_out,\n                    output,\n                    outs[0],\n                )\n        scheduled_ops.append(op)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef _schedule_bitserial_conv2d_nchw(\n    cfg, s, data_q, data_pad, data_vec, kernel_q, kernel_vec, conv_out, output, last\n):\n    IB, _, CI, IH, IW = data_q.shape\n    KB, CO, _, KH, KW = kernel_q.shape\n    _, _, OH, OW = output.shape\n\n    # Infer padding and stride\n    if data_pad is None:\n        padding = (0, 0)\n        TH, TW = IH, IW\n    else:\n        _, _, _, TH, TW = data_pad.shape\n        hpad = get_const_int((TH - IH) // 2)\n        wpad = get_const_int((TW - IW) // 2)\n        padding = (hpad, wpad)\n\n    hstride = get_const_int((TH - KH) // (OH - 1))\n    wstride = get_const_int((TW - KW) // (OW - 1))\n    stride = (hstride, wstride)\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    ##### Schedule Data padding, and bitpacking\n    if data_pad is not None:\n        s[data_pad].compute_inline()\n\n    _, _, h, _, _, _, _ = s[data_vec].op.axis\n    cfg.define_split(\"tile_ah\", cfg.axis(h), num_outputs=2, max_factor=32)\n    oh, ih = cfg[\"tile_ah\"].apply(s, data_vec, h)\n    if cfg[\"tile_ah\"].size[1] == 1:\n        oaxis = oh\n        paxis = oh\n    else:\n        oaxis = oh\n        paxis = ih\n\n    s[data_vec].parallel(paxis)\n    s[data_vec].pragma(oaxis, \"parallel_launch_point\")\n    s[data_vec].pragma(paxis, \"parallel_stride_pattern\")\n    s[data_vec].pragma(oaxis, \"parallel_barrier_when_finish\")\n\n    ##### Schedule Kenerl bitpacking\n    co, _, _, _, _, _ = s[kernel_vec].op.axis\n    cfg.define_split(\"tile_bco\", cfg.axis(co), num_outputs=2, max_factor=32)\n    oco, ico = cfg[\"tile_bco\"].apply(s, kernel_vec, co)\n    if cfg[\"tile_bco\"].size[1] == 1:\n        oaxis = oco\n        paxis = oco\n    else:\n        oaxis = oco\n        paxis = ico\n\n    s[kernel_vec].parallel(paxis)\n    s[kernel_vec].pragma(oaxis, \"parallel_launch_point\")\n    s[kernel_vec].pragma(paxis, \"parallel_stride_pattern\")\n    s[kernel_vec].pragma(oaxis, \"parallel_barrier_when_finish\")\n\n    ##### Schedule Convolution\n    n, co, oh, ow, vh, vw, vc = s[conv_out].op.axis\n    ci, dh, dw, ib, kb = s[conv_out].op.reduce_axis\n\n    # s[conv_out].reorder(n, oh, ow, co, vh, vw, dh, dw, ci, vc, b1, b2)\n    cfg[\"reorder_0\"].apply(s, conv_out, [n, co, oh, ow, vc, vh, vw, dh, dw, kb, ib, ci])\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv_out,\n        [kb, ib, dh, dw],\n        axis_lens=[\n            get_const_int(kb.dom.extent),\n            get_const_int(ib.dom.extent),\n            get_const_int(dh.dom.extent),\n            get_const_int(dw.dom.extent),\n        ],\n        max_unroll=16,\n        cfg=cfg,\n    )\n\n    s[conv_out].vectorize(vc)\n\n    # # Schedule output\n    n, co, h, w = s[last].op.axis\n    co, vc = s[last].split(co, VC)\n    oh, ow, vh, vw = s[last].tile(h, w, VH, VW)\n    s[last].reorder(n, co, oh, ow, vh, vw, vc)\n    if last != output:\n        s[output].compute_inline()\n    s[conv_out].compute_at(s[last], ow)\n\n    oco, ico = cfg[\"tile_oh\"].apply(s, last, co)\n    if cfg[\"tile_oh\"].size[1] == 1:\n        oaxis = oco\n        paxis = oco\n    else:\n        oco, ico = s[last].split(co, bc)\n        oaxis = oco\n        paxis = ico\n\n    s[last].parallel(oco)\n    return s\n\n\ndef _schedule_bitserial_conv2d_nhwc(\n    cfg, s, data_q, data_pad, data_vec, kernel_q, kernel_vec, conv_out, output, last\n):\n    # no stride and padding info here\n    _, IH, IW, CI, IB = data_q.shape\n    KH, KW, _, CO, KB = kernel_q.shape\n    _, OH, OW, _ = output.shape\n\n    VC = cfg[\"tile_co\"].size[-1]\n    VH = cfg[\"tile_oh\"].size[-1]\n    VW = cfg[\"tile_ow\"].size[-1]\n\n    ##### Schedule data padding and packing\n    if data_pad is not None:\n        s[data_pad].compute_inline()\n\n    _, h, _, _, _, _, _ = s[data_vec].op.axis\n    cfg.define_split(\"tile_ah\", cfg.axis(h), num_outputs=2, max_factor=32)\n    oh, ih = cfg[\"tile_ah\"].apply(s, data_vec, h)\n    s[data_vec].parallel(oh)\n\n    ##### Schedule kernel packing\n    co, _, _, _, _, _ = s[kernel_vec].op.axis\n    cfg.define_split(\"tile_bco\", cfg.axis(co), num_outputs=2, max_factor=32)\n    oco, ico = cfg[\"tile_bco\"].apply(s, kernel_vec, co)\n    s[kernel_vec].parallel(oco)\n\n    ##### Schedule Convolution\n    n, oh, ow, co, vh, vw, vc = s[conv_out].op.axis\n    dh, dw, ci, b1, b2 = s[conv_out].op.reduce_axis\n\n    # s[conv_out].reorder(n, oh, ow, co, vh, vw, dh, dw, ci, vc, b1, b2)\n    cfg[\"reorder_0\"].apply(s, conv_out, [n, oh, ow, co, vh, vw, dh, dw, ci, vc, b1, b2])\n    cfg[\"ann_reduce\"].apply(\n        s,\n        conv_out,\n        [b1, b2, dh, dw],\n        axis_lens=[\n            get_const_int(b1.dom.extent),\n            get_const_int(b2.dom.extent),\n            get_const_int(dh.dom.extent),\n            get_const_int(dw.dom.extent),\n        ],\n        max_unroll=16,\n        cfg=cfg,\n    )\n\n    s[conv_out].unroll(b1)\n    s[conv_out].unroll(b2)\n    s[conv_out].vectorize(vc)\n\n    # # Schedule output\n    n, h, w, co = s[last].op.axis\n    co, vc = s[last].split(co, VC)\n    oh, ow, vh, vw = s[last].tile(h, w, VH, VW)\n    s[last].reorder(n, oh, ow, co, vh, vw, vc)\n    s[last].vectorize(vc)\n    if last != output:\n        s[output].compute_inline()\n    s[conv_out].compute_at(s[last], ow)\n\n    oho, iho = cfg[\"tile_oh\"].apply(s, last, oh)  # reuse parameter\n    s[last].parallel(oho)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/bitserial_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Schedule for bitserial dense operator.\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.topi.utils import get_const_int, get_const_tuple\nfrom .. import tag\nfrom ..nn.bitserial_util import bitpack, binary_op_multiplier\n\n\n@autotvm.register_topi_compute(\"bitserial_dense.x86\")\ndef bitserial_dense(\n    cfg, data, weight, data_bits, weight_bits, pack_dtype=\"uint32\", out_dtype=\"int16\", unipolar=True\n):\n    \"\"\"Bitserial dense implementation. TODO: Why are these separate\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        2-D with shape [batch, in_dim]\n    weight : tvm.te.Tensor\n        2-D with shape [out_dim, in_dim] or\n        3-D with shape [out_dim, weight_bits, in_dim]\n    Returns\n    -------\n    output : tvm.te.Tensor\n        2-D with shape [batch, out_dim]\n    \"\"\"\n    data_packed = bitpack(data, data_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    if len(weight.shape) == 2:\n        weight_packed = bitpack(weight, weight_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype)\n    else:\n        weight_packed = weight\n    Y, DB, K = get_const_tuple(data_packed.shape)\n    X, WB, _ = get_const_tuple(weight_packed.shape)\n    ######## Search space\n    x, y = cfg.axis(X), cfg.axis(Y)\n    db, wb, k = cfg.reduce_axis(DB), cfg.reduce_axis(WB), cfg.reduce_axis(K)\n    ko, ki = cfg.define_split(\"tile_k\", k, num_outputs=2)\n    yo, yi = cfg.define_split(\"tile_y\", y, num_outputs=2)\n    xo, xi = cfg.define_split(\"tile_x\", x, num_outputs=2)\n\n    cfg.define_reorder(\n        \"reorder_0\",\n        [yo, xo, ko, yi, wb, db, ki, xi],\n        policy=\"candidate\",\n        candidate=[[yo, xo, ko, yi, wb, db, ki, xi], [yo, xo, yi, ko, wb, db, ki, xi]],\n    )\n\n    cfg.define_annotate(\"ann_reduce\", [db, wb], policy=\"try_unroll\")\n    cfg.define_annotate(\"ann_spatial\", [yi, xi], policy=\"try_unroll_vec\")\n\n    ###### Compute rule\n    VX = cfg[\"tile_x\"].size[-1]\n\n    wvshape = (X // VX, WB, VX, K)\n    oshape = (Y, X)\n\n    k = te.reduce_axis((0, K), name=\"k\")\n    db = te.reduce_axis((0, DB), name=\"db\")\n    wb = te.reduce_axis((0, WB), name=\"wb\")\n\n    # Tile data and weights\n    weight_vec = te.compute(\n        wvshape, lambda xo, wb, vx, k: weight_packed[xo * VX + vx][wb][k], name=\"weight_vec\"\n    )\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    matmul_unipolar = te.compute(\n        oshape,\n        lambda i, j: te.sum(\n            (\n                tvm.tir.popcount(\n                    weight_vec[idxdiv(j, VX), wb, idxmod(j, VX), k] & data_packed[i, db, k]\n                )\n                - tvm.tir.popcount(\n                    ~weight_vec[idxdiv(j, VX), wb, idxmod(j, VX), k] & data_packed[i, db, k]\n                )\n            ).astype(out_dtype)\n            << (db + wb).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense_unipolar\",\n    )\n\n    matmul = te.compute(\n        oshape,\n        lambda i, j: te.sum(\n            tvm.tir.popcount(\n                weight_vec[idxdiv(j, VX), wb, idxmod(j, VX), k] & data_packed[i, db, k]\n            ).astype(out_dtype)\n            << (db + wb).astype(out_dtype),\n            axis=[wb, db, k],\n        ),\n        tag=\"bitserial_dense\",\n    )\n\n    # binary ops\n    cfg.add_flop(2 * Y * X * K * binary_op_multiplier(pack_dtype))\n\n    if unipolar:\n        return matmul_unipolar\n    return matmul\n\n\n@autotvm.register_topi_schedule(\"bitserial_dense.x86\")\ndef schedule_bitserial_dense(cfg, outs):\n    \"\"\"Schedule for bitserial_dense.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of bitserial dense operator.\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for bitserial_dense.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _schedule(cfg, s, data_vec, weight_vec, output):\n        s[data_vec].parallel(s[data_vec].op.axis[0])\n        s[weight_vec].parallel(s[weight_vec].op.axis[0])\n\n        y, x = s[output].op.axis\n        wb, db, k = s[output].op.reduce_axis\n\n        yo, yi = cfg[\"tile_y\"].apply(s, output, y)\n        xo, xi = cfg[\"tile_x\"].apply(s, output, x)\n        ko, ki = cfg[\"tile_k\"].apply(s, output, k)\n\n        cfg[\"reorder_0\"].apply(s, output, [yo, xo, ko, yi, wb, db, ki, xi])\n        cfg[\"ann_reduce\"].apply(\n            s,\n            output,\n            [db, wb],\n            axis_lens=[get_const_int(db.dom.extent), get_const_int(wb.dom.extent)],\n            max_unroll=8,\n            cfg=cfg,\n        )\n        cfg[\"ann_spatial\"].apply(\n            s,\n            output,\n            [yi, xi],\n            axis_lens=[cfg[\"tile_y\"].size[-1], cfg[\"tile_x\"].size[-1]],\n            max_unroll=8,\n            cfg=cfg,\n        )\n        s[output].vectorize(xi)\n        s[output].parallel(yo)\n        return s\n\n    def traverse(op):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag) or \"elemwise\" in op.tag:\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp):\n                    traverse(tensor.op)\n\n        elif op.tag == \"bitserial_dense\" or \"bitserial_dense_unipolar\":\n            output = op.output(0)\n            weight_vec = op.input_tensors[0]\n\n            data_vec = op.input_tensors[1]\n            data = data_vec.op.input_tensors[0]\n            if \"QuantizeInput\" in data.op.name:\n                data = data.op.input_tensors[0]\n            _schedule(cfg, s, data_vec, weight_vec, output)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % op.tag)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/concat.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"concatenate related operators\"\nfrom typing import Optional\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom ..utils import get_const_int\n\n\ndef concatenate(data: tvm.te.Tensor, axis: Optional[int] = 0):\n    \"\"\"Join a sequence of arrays along an existing axis.\n    Optimized for CPU execution.\n\n    Parameters\n    ----------\n    data : tuple of tvm.te.Tensor\n        The arrays to concatenate\n\n    axis : int, optional\n        The axis along which the arrays will be joined. Default is 0.\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n\n    in_outers = [int(np.prod(i.shape[axis:])) for i in data]\n    in_outers_cumsum = [0, *np.cumsum(in_outers, dtype=\"int64\")[0:-1]]\n\n    def gen_ir_1d(data_bufs, out_buf):\n        \"\"\"Custom concatenation execution.\"\"\"\n        i_b = tvm.tir.ir_builder.create()\n        data_bufs1 = [i_b.buffer_ptr(data_buf) for data_buf in data_bufs]\n        out_buf = i_b.buffer_ptr(out_buf)\n\n        for i in range(len(data)):\n            with i_b.for_range(0, in_outers[i], name=\"j\") as j:\n                out_buf[in_outers_cumsum[i] + j] = data_bufs1[i][j]\n        return i_b.get()\n\n    def gen_ir(data_bufs, out_buf, inner, outer):\n        \"\"\"Common case of concatenation execution.\"\"\"\n        i_b = tvm.tir.ir_builder.create()\n        data_bufs1 = [i_b.buffer_ptr(data_buf) for data_buf in data_bufs]\n        out_buf = i_b.buffer_ptr(out_buf)\n        if inner > 1:\n            with i_b.for_range(0, inner, name=\"inn\", kind=\"parallel\") as inn:\n                pos = inn * outer\n                for i in range(len(data)):\n                    offset = inn * in_outers[i]\n                    with i_b.for_range(0, in_outers[i], name=\"j\") as j:\n                        out_buf[pos + in_outers_cumsum[i] + j] = data_bufs1[i][offset + j]\n        else:\n            for i in range(len(data)):\n                with i_b.for_range(0, in_outers[i], name=\"j\", kind=\"parallel\") as j:\n                    out_buf[in_outers_cumsum[i] + j] = data_bufs1[i][j]\n        return i_b.get()\n\n    if axis < 0:\n        axis += len(data[0].shape)\n    concat_axis_sizes = [int(t.shape[axis]) for t in data]\n    join_size = int(np.sum(concat_axis_sizes))\n\n    dtype = data[0].dtype\n    out_shape = data[0].shape[:axis] + [join_size] + data[0].shape[axis + 1 :]\n    right_val = np.prod(out_shape[axis:])\n    left_val = np.prod(out_shape[:axis])\n\n    if (\n        len(data[0].shape) == 1\n        or (left_val == 1 and axis == len(data[0].shape) - 1)\n        or (left_val == 1 and right_val == 1)\n    ):\n        # badly parallelized case\n        return te.extern(\n            [out_shape],\n            list(data),\n            lambda ins, outs: gen_ir_1d(ins, outs[0]),\n            dtype=dtype,\n            name=\"concatenate_ext\",\n        )\n\n    inner = get_const_int(int(left_val))\n    outer = get_const_int(int(right_val))\n    return te.extern(\n        [out_shape],\n        list(data),\n        lambda ins, outs: gen_ir(ins, outs[0], inner, outer),\n        dtype=dtype,\n        name=\"concatenate_ext\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,invalid-name\n\"\"\"Conv1D schedule on for Intel CPU\"\"\"\nfrom tvm import te\nfrom .. import tag\n\n\ndef schedule_conv1d_ncw(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    output_op = outs[0].op\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            else:  # inject custom schedule\n                if len(op.axis) == 3:  # schedule bias + bn + relu\n                    n, c, w = op.axis\n                    fused = s[op].fuse(n, c)\n                    s[op].parallel(fused)\n                    s[op].vectorize(w)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n\n        if \"conv1d_ncw\" in op.tag:\n            conv = op.output(0)\n            kernel = op.input_tensors[1]\n            if isinstance(kernel.op, te.tensor.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            data = op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, te.tensor.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            n_pad, c_pad, w_pad = data_pad.op.axis\n            pad_fused = s[data_pad].fuse(n_pad, c_pad)\n            s[data_pad].parallel(pad_fused)\n            C = conv\n            n, c, w = C.op.axis\n            rc, rw = C.op.reduce_axis\n            n_out, c_out, w_out = output_op.axis\n            s[C].vectorize(w)\n            if op != output_op:  # fuse bias + bn + relu into conv\n                s[C].compute_at(s[output_op], w_out)\n            else:\n                fused = s[C].fuse(n, c)\n                s[C].parallel(fused)\n\n        scheduled_ops.append(op)\n\n    traverse(output_op)\n    return s\n\n\ndef schedule_conv1d_nwc(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    output_op = outs[0].op\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            else:  # inject custom schedule\n                if len(op.axis) == 3:  # schedule bias + bn + relu\n                    n, w, c = op.axis\n                    fused = s[op].fuse(n, w)\n                    s[op].parallel(fused)\n                    s[op].vectorize(c)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n\n        if \"conv1d_nwc\" in op.tag:\n            conv = op.output(0)\n            kernel = op.input_tensors[1]\n            if isinstance(kernel.op, te.tensor.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            data = op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, te.tensor.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            n_pad, w_pad, c_pad = data_pad.op.axis\n            pad_fused = s[data_pad].fuse(n_pad, w_pad)\n            s[data_pad].parallel(pad_fused)\n            C = conv\n            n, w, c = C.op.axis\n            rc, rw = C.op.reduce_axis\n            n_out, w_out, c_out = output_op.axis\n            s[C].vectorize(c)\n            if op != output_op:  # fuse bias + bn + relu into conv\n                s[C].compute_at(s[output_op], c_out)\n            else:\n                fused = s[C].fuse(n, w)\n                s[C].parallel(fused)\n\n        scheduled_ops.append(op)\n\n    traverse(output_op)\n    return s\n\n\ndef schedule_group_conv1d_ncw(outs):\n    return schedule_conv1d_ncw(outs)\n\n\ndef schedule_group_conv1d_nwc(outs):\n    return schedule_conv1d_nwc(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter,import-outside-toplevel\n\"\"\"Conv2D schedule on x86\"\"\"\n\nimport logging\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.contrib import dnnl\nfrom .. import nn\nfrom ..generic import schedule_extern\nfrom ..nn.conv2d import conv2d_infer_layout, _get_workload as _get_conv2d_workload\nfrom ..nn.conv2d import unpack_NCHWc_to_nchw\nfrom ..nn.depthwise_conv2d import _get_workload as _get_depthwise_conv2d_workload\nfrom ..nn.utils import get_pad_tuple\nfrom ..utils import get_const_tuple, traverse_inline\nfrom . import conv2d_avx_1x1, conv2d_avx_common\n\nlogger = logging.getLogger(\"topi\")\n\n\ndef _get_default_config(\n    cfg, data, kernel, strides, padding, dilation, out_dtype, is_depthwise=False, layout=\"NCHW\"\n):\n    \"\"\"\n    Get default schedule config for the workload\n    \"\"\"\n    static_data_shape = []\n    for dim in get_const_tuple(data.shape):\n        if isinstance(dim, tvm.tir.Var):\n            static_data_shape.append(1)\n        else:\n            static_data_shape.append(dim)\n    data = te.placeholder(static_data_shape, dtype=data.dtype)\n    if is_depthwise:\n        wkl = _get_depthwise_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype)\n        from .depthwise_conv2d import _fallback_schedule\n\n        _fallback_schedule(cfg, wkl)\n    else:\n        wkl = _get_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype, layout)\n        is_kernel_1x1 = wkl.kernel_h == 1 and wkl.kernel_w == 1\n        if is_kernel_1x1:\n            conv2d_avx_1x1._fallback_schedule(cfg, wkl)\n        else:\n            conv2d_avx_common._fallback_schedule(cfg, wkl)\n\n\n@conv2d_infer_layout.register(\"cpu\")\ndef _conv2d_infer_layout(workload, cfg):\n    _, data, kernel, strides, padding, dilation, layout, _, dtype = workload\n    batch_size, in_channel, in_height, in_width = data[1]\n    out_channel, _, k_height, k_width = kernel[1]\n    idxdiv = tvm.tir.indexdiv\n\n    pt, pl, pb, pr = get_pad_tuple(padding, (k_height, k_width))\n    hdilation, wdilation = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    dilated_kernel_h = (k_height - 1) * hdilation + 1\n    dilated_kernel_w = (k_width - 1) * wdilation + 1\n    out_height = idxdiv(in_height + pt + pb - dilated_kernel_h, strides[0]) + 1\n    out_width = idxdiv(in_width + pl + pr - dilated_kernel_w, strides[1]) + 1\n    tile_ic, tile_oc = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    in_shape = (batch_size, idxdiv(in_channel, tile_ic), in_height, in_width, tile_ic)\n    in_layout = \"NCHW%dc\" % tile_ic\n    out_shape = (batch_size, idxdiv(out_channel, tile_oc), out_height, out_width, tile_oc)\n    out_layout = \"NCHW%dc\" % tile_oc\n    return ((in_shape, in_layout),), ((out_shape, out_layout),)\n\n\ndef schedule_conv2d_nhwc(outs):\n    \"\"\"Create schedule for conv2d_nhwc\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    output_op = outs[0].op\n\n    def _callback(op):\n        if \"conv2d_nhwc\" in op.tag:\n            conv = op.output(0)\n            kernel = op.input_tensors[1]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n\n            data = op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            n_pad, h_pad, w_pad, c_pad = data_pad.op.axis\n            pad_fused = s[data_pad].fuse(n_pad, h_pad)\n            s[data_pad].parallel(pad_fused)\n            C = conv\n            n, h, w, c = C.op.axis\n            s[C].vectorize(c)\n\n            O = output_op.output(0)\n            if len(O.op.axis) == 4:  # schedule bias + bn + relu\n                n, h, w, c = O.op.axis\n                fused = s[O].fuse(n, h, w)\n                s[O].parallel(fused)\n                channels = int(O.shape[-1])\n                if channels % 64 == 0:\n                    c, ci = s[O].split(c, 64)\n                    s[O].vectorize(ci)\n                if C != O:\n                    s[C].compute_at(s[O], c)\n\n    traverse_inline(s, output_op, _callback)\n    return s\n\n\ndef conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype):\n    layout = \"NCHW\"\n    packed_out = conv2d_NCHWc(data, kernel, strides, padding, dilation, layout, layout, out_dtype)\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_conv2d_nchw(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    return schedule_conv2d_NCHWc(outs)\n\n\ndef _pack_data(cfg, data, kernel):\n    n, _, ih, iw = get_const_tuple(data.shape)\n    oc, ic, kh, kw = get_const_tuple(kernel.shape)\n    ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n    ic_chunk = ic // ic_bn\n    oc_chunk = oc // oc_bn\n\n    # Handle dynamic shape to pass tuning dispatch.\n    if isinstance(n, tvm.tir.Any):\n        n = tvm.te.size_var(\"n\")\n    if isinstance(ih, tvm.tir.Any):\n        ih = tvm.te.size_var(\"ih\")\n    if isinstance(iw, tvm.tir.Any):\n        iw = tvm.te.size_var(\"iw\")\n    if isinstance(ic, tvm.tir.Any):\n        raise RuntimeError(\"Dynamic input channel is not supported for conv2d.\")\n\n    data = te.compute(\n        (n, ic_chunk, ih, iw, ic_bn),\n        lambda bs, c, h, w, vc: data[bs, c * ic_bn + vc, h, w],\n        name=\"data_vec\",\n    )\n\n    kernel = te.compute(\n        (oc_chunk, ic_chunk, kh, kw, ic_bn, oc_bn),\n        lambda occ, icc, k_h, k_w, icb, ocb: kernel[occ * oc_bn + ocb, icc * ic_bn + icb, k_h, k_w],\n        name=\"kernel_vec\",\n    )\n\n    return data, kernel\n\n\n@autotvm.register_topi_compute(\"conv2d_NCHWc.x86\")\ndef conv2d_NCHWc(cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype):\n    \"\"\"Compute conv2d with NCHWc layout.\"\"\"\n    # layout and out_layout are not used here,\n    # we keep them for debug convenience when dumping autotvm workload\n    if len(data.shape) == 5:\n        n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n        oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn = get_const_tuple(\n            kernel.shape\n        )\n        in_channel = ic_chunk * ic_bn\n        num_filter = oc_chunk * oc_bn\n    else:\n        n, in_channel, ih, iw = get_const_tuple(data.shape)\n        num_filter, _, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n\n    # Define autotvm tuning space\n    is_kernel_1x1 = kernel_height == 1 and kernel_width == 1\n    pt, pl, pb, pr = get_pad_tuple(padding, (kernel_height, kernel_width))\n    sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    oh = (ih - kernel_height + pt + pb) // sh + 1\n    ow = (iw - kernel_width + pl + pr) // sw + 1\n\n    cfg.define_split(\"tile_ic\", in_channel, num_outputs=2)\n    cfg.define_split(\"tile_oc\", num_filter, num_outputs=2)\n    cfg.define_split(\n        \"tile_ow\", ow, num_outputs=2, filter=lambda y: y.size[-1] <= 64, policy=\"verbose\"\n    )\n    if is_kernel_1x1:\n        cfg.define_knob(\"tile_oh\", [1, 2] if oh > 1 else [1])\n    else:\n        cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # If no config was set, we can fallback to default config.\n    if cfg.is_fallback:\n        _get_default_config(\n            cfg,\n            te.placeholder((n, in_channel, ih, iw), dtype=data.dtype),\n            te.placeholder(\n                (num_filter, in_channel, kernel_height, kernel_width), dtype=kernel.dtype\n            ),\n            strides,\n            padding,\n            dilation,\n            out_dtype,\n        )\n\n    # Pack data if raw 4-D data is provided.\n    # This can only happen when autotuning.\n    if len(data.shape) == 4:\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # Directly use modified data layout placeholder.\n            dshape = (n, in_channel // cfg[\"tile_ic\"].size[-1], ih, iw, cfg[\"tile_ic\"].size[-1])\n            data = tvm.te.placeholder(dshape, data.dtype, name=\"data\")\n            kshape = (\n                num_filter // cfg[\"tile_oc\"].size[-1],\n                in_channel // cfg[\"tile_ic\"].size[-1],\n                kernel_height,\n                kernel_width,\n                cfg[\"tile_ic\"].size[-1],\n                cfg[\"tile_oc\"].size[-1],\n            )\n            kernel = tvm.te.placeholder(kshape, kernel.dtype, name=\"kernel\")\n        else:\n            data, kernel = _pack_data(cfg, data, kernel)\n\n    return nn.conv2d_NCHWc(data, kernel, strides, padding, dilation, layout, out_layout, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv2d_NCHWc.x86\")\ndef schedule_conv2d_NCHWc(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"conv2d_NCHWc\" in op.tag:\n            conv_out = op.output(0)\n            kernel_vec = conv_out.op.input_tensors[1]\n            data_vec = conv_out.op.input_tensors[0]\n\n            args = [s, cfg, data_vec, kernel_vec, conv_out, outs[0]]\n            (\n                _,\n                _,\n                kh,\n                kw,\n                _,\n                _,\n            ) = get_const_tuple(kernel_vec.shape)\n            if kh == 1 and kw == 1:\n                conv2d_avx_1x1._schedule_conv_NCHWc(*args)\n            else:\n                conv2d_avx_common._schedule_conv_NCHWc(*args)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv2d_nchw_dnnl.x86\")\ndef conv2d_nchw_dnnl(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d in NCHW format using dnnl.\"\"\"\n    groups = 1\n    _out = dnnl.dnnl_conv2d(data, kernel, strides, padding, dilation, groups, False, out_dtype)\n    return _out\n\n\n@autotvm.register_topi_schedule(\"conv2d_nchw_dnnl.x86\")\ndef schedule_conv2d_nchw_dnnl(_, outs):\n    \"\"\"Create schedule for conv2d_nchw_dnnl\"\"\"\n    return schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"conv2d_nhwc_dnnl.x86\")\ndef conv2d_nhwc_dnnl(cfg, data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d in NHWC format using dnnl.\"\"\"\n    groups = 1\n    _out = dnnl.dnnl_conv2d(data, kernel, strides, padding, dilation, groups, True, out_dtype)\n    return _out\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_dnnl.x86\")\ndef schedule_conv2d_nhwc_dnnl(_, outs):\n    \"\"\"Create schedule for conv2d_nhwc_dnnl\"\"\"\n    return schedule_extern(outs)\n\n\n# FIXME - https://github.com/apache/tvm/issues/4122\n# _declaration_conv_nhwc_pack expects kernel layout to be HWOI. However, the tests use HWIO\n# layout. Commenting until we have clarity about the nhwc_pack implementation from the author.\n# elif layout == 'NHWC' and kh == 1 and kw == 1 and kernel.dtype == \"int8\":\n#     if cfg.is_fallback:\n#         _get_default_config(cfg, data, kernel, strides, padding, out_dtype, False, layout)\n#     # specialize for INT8 1X1 conv on X86\n#     return conv2d_avx_1x1._declaration_conv_nhwc_pack(cfg, data, kernel, strides,\n#                                                       padding, dilation, out_dtype)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D alter op and legalize functions for x86\"\"\"\n\nimport logging\n\nimport re\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom .conv2d import _get_default_config\nfrom .conv2d_int8 import is_int8_hw_support, _get_default_config_int8\nfrom ..utils import get_const_tuple\nfrom ..nn import conv2d_legalize, conv2d_alter_layout\nfrom ..generic.conv2d import conv2d_alter_int8_common\n\nlogger = logging.getLogger(\"topi\")\n\n_NCHWc_matcher = re.compile(\"^NCHW[0-9]+c$\")\n_OIHWio_matcher = re.compile(\"^OIHW[0-9]+i[0-9]+o$\")\n\n\n@conv2d_alter_layout.register(\"cpu\")\ndef _alter_conv2d_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n    new_attrs = {k: attrs[k] for k in attrs.keys()}\n\n    # Parse the attributes.\n    padding = attrs.get_int_tuple(\"padding\")\n    strides = attrs.get_int_tuple(\"strides\")\n    dilation = attrs.get_int_tuple(\"dilation\")\n    data_layout = attrs[\"data_layout\"]\n    kernel_layout = attrs[\"kernel_layout\"]\n    data_tensor, kernel_tensor = tinfos\n    data_dtype = data_tensor.dtype\n    kernel_dtype = kernel_tensor.dtype\n    out_dtype = out_type.dtype\n\n    if isinstance(dispatch_ctx, autotvm.task.ApplyGraphBest):\n        cfg = dispatch_ctx.query(target, None)\n        workload = cfg.workload\n    else:\n        impl, outs = relay.backend.te_compiler.select_implementation(\n            relay.op.get(\"nn.conv2d\"), attrs, tinfos, out_type, target\n        )\n        workload = autotvm.task.get_workload(outs)\n        if workload is None:\n            # The best implementation is not an AutoTVM template.\n            # It may be from the auto-scheduler\n            if impl.name.find(\"winograd\") != -1:\n                if dilation != (1, 1):\n                    logger.warning(\"Does not support weight pre-transform for dilated convolution.\")\n                    return None\n\n                assert data_layout == \"NHWC\" and kernel_layout == \"HWIO\"\n                N, H, W, CI = get_const_tuple(data_tensor.shape)\n                KH, KW, _, CO = get_const_tuple(kernel_tensor.shape)\n\n                # Pre-compute weight transformation in winograd\n                tile_size = 4\n                # HWIO -> OIHW\n                kernel_transform = relay.transpose(inputs[1], axes=[3, 2, 0, 1])\n                # alpha, alpha, CO, CI\n                weight = relay.nn.contrib_conv2d_winograd_weight_transform(\n                    kernel_transform, tile_size=tile_size\n                )\n                new_attrs[\"tile_size\"] = tile_size\n                new_attrs[\"channels\"] = CO\n                return relay.nn.contrib_conv2d_winograd_without_weight_transform(\n                    inputs[0], weight, **new_attrs\n                )\n            return None\n\n        cfg = dispatch_ctx.query(target, workload)\n\n    topi_tmpl = workload[0]\n\n    if topi_tmpl == \"conv2d_NCHWc.x86\":\n        # we only convert conv2d_NCHW to conv2d_NCHWc for x86\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            if cfg.is_fallback:\n                _get_default_config(\n                    cfg,\n                    data_tensor,\n                    kernel_tensor,\n                    strides,\n                    padding,\n                    dilation,\n                    out_dtype,\n                    False,\n                    data_layout,\n                )\n            batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n            out_channel, _, kh, kw = get_const_tuple(kernel_tensor.shape)\n            ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n            # update new attrs\n            new_attrs[\"channels\"] = out_channel\n            new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n            # (oc, ic, h, w) -> (OC, IC, h, w, ic, oc)\n            new_attrs[\"kernel_layout\"] = \"OIHW%di%do\" % (ic_bn, oc_bn)\n            new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n            # Store altered operator's config\n            new_data = te.placeholder(\n                (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n            )\n            new_kernel = te.placeholder(\n                (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn, oc_bn),\n                dtype=kernel_tensor.dtype,\n            )\n            new_workload = autotvm.task.args_to_workload(\n                [\n                    new_data,\n                    new_kernel,\n                    strides,\n                    padding,\n                    dilation,\n                    new_attrs[\"data_layout\"],\n                    new_attrs[\"out_layout\"],\n                    out_dtype,\n                ],\n                topi_tmpl,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n        else:\n            assert _NCHWc_matcher.match(data_layout)\n            assert _OIHWio_matcher.match(kernel_layout)\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    if topi_tmpl == \"conv2d_NCHWc_int8.x86\":\n        # TODO(@icemelon9, @anijain2305): Need to support data layout NHWC with kernel layout HWIO\n        assert data_layout == \"NCHW\" and kernel_layout == \"OIHW\"\n        if cfg.is_fallback:\n            _get_default_config_int8(\n                cfg,\n                data_tensor,\n                kernel_tensor,\n                strides,\n                padding,\n                dilation,\n                out_dtype,\n                False,\n                data_layout,\n                int32_lanes=16,\n            )\n\n        batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n        out_channel, channel_multiplier, kh, kw = get_const_tuple(kernel_tensor.shape)\n        ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n        # update new attrs\n        n_elems = 4\n        new_attrs[\"channels\"] = out_channel\n        new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n        new_attrs[\"kernel_layout\"] = \"OIHW{:n}i{:n}o{:n}i\".format(ic_bn // n_elems, oc_bn, n_elems)\n        new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n        # Store altered operator's config.\n        new_data = te.placeholder(\n            (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n        )\n        new_kernel = te.placeholder(\n            (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn // n_elems, oc_bn, n_elems),\n            dtype=kernel_dtype,\n        )\n        new_workload = autotvm.task.args_to_workload(\n            [\n                new_data,\n                new_kernel,\n                strides,\n                padding,\n                dilation,\n                new_attrs[\"data_layout\"],\n                new_attrs[\"out_layout\"],\n                out_dtype,\n            ],\n            topi_tmpl,\n        )\n        dispatch_ctx.update(target, new_workload, cfg)\n\n        return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs)\n\n    if topi_tmpl == \"depthwise_conv2d_NCHWc.x86\":\n        if data_layout == \"NCHW\" and kernel_layout == \"OIHW\":\n            if cfg.is_fallback:\n                _get_default_config(\n                    cfg,\n                    data_tensor,\n                    kernel_tensor,\n                    strides,\n                    padding,\n                    dilation,\n                    out_dtype,\n                    True,\n                    data_layout,\n                )\n\n            batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape)\n            out_channel, channel_multiplier, kh, kw = get_const_tuple(kernel_tensor.shape)\n            ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n            assert channel_multiplier == 1\n\n            # update new attrs\n            new_attrs[\"channels\"] = out_channel\n            new_attrs[\"data_layout\"] = \"NCHW%dc\" % ic_bn\n            new_attrs[\"kernel_layout\"] = \"OIHW1i%do\" % oc_bn\n            new_attrs[\"out_layout\"] = \"NCHW%dc\" % oc_bn\n\n            # Store altered operator's config.\n            new_data = te.placeholder(\n                (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype\n            )\n            new_kernel = te.placeholder(\n                (out_channel // oc_bn, 1, kh, kw, 1, oc_bn), dtype=kernel_dtype\n            )\n            new_workload = autotvm.task.args_to_workload(\n                [\n                    new_data,\n                    new_kernel,\n                    strides,\n                    padding,\n                    dilation,\n                    new_attrs[\"data_layout\"],\n                    new_attrs[\"out_layout\"],\n                    out_dtype,\n                ],\n                topi_tmpl,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n        else:\n            assert _NCHWc_matcher.match(data_layout)\n            assert _OIHWio_matcher.match(kernel_layout)\n        return relay.nn.contrib_depthwise_conv2d_nchwc(*inputs, **new_attrs)\n\n    return None\n\n\n@conv2d_legalize.register(\"cpu\")\ndef _conv2d_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes Conv2D op.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Collect the input tensors.\n    data_tensor, kernel_tensor = arg_types[0], arg_types[1]\n    data_dtype = data_tensor.dtype\n    kernel_dtype = kernel_tensor.dtype\n\n    # Collect the output tensor.\n    output_tensor = arg_types[2]\n\n    # Collect the input exprs.\n    data, kernel = inputs\n\n    # Intel vector intructions require data and kernel to have different dtypes.\n    if data_tensor.dtype == \"int8\" and kernel_tensor.dtype == \"int8\":\n        data_dtype = \"uint8\"\n    if is_int8_hw_support(data_dtype, kernel_dtype):\n        return conv2d_alter_int8_common(\n            data, data_tensor, kernel, kernel_tensor, output_tensor, attrs, data_dtype, 4, 16\n        )\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d_avx_1x1.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,invalid-name\n\"\"\"1x1 Conv2D schedule on for Intel CPU\"\"\"\nfrom __future__ import absolute_import as _abs\nimport tvm\nfrom tvm import te\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom ..nn.pad import pad\nfrom ..nn.utils import get_pad_tuple\nfrom ..generic import conv2d as conv2d_generic\nfrom ..utils import get_const_tuple, simplify\nfrom .tensor_intrin import dot_16x1x16_uint8_int8_int32\nfrom .utils import get_simd_32bit_lanes\n\n\ndef _fallback_schedule(cfg, wkl):\n    simd_width = get_simd_32bit_lanes()\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    dilated_kernel_h = (wkl.kernel_h - 1) * wkl.dilation_h + 1\n    dilated_kernel_w = (wkl.kernel_w - 1) * wkl.dilation_w + 1\n\n    out_height = (wkl.height + pt + pb - dilated_kernel_h) // HSTR + 1\n    out_width = (wkl.width + pl + pr - dilated_kernel_w) // WSTR + 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if wkl.out_filter % bn == 0:\n            oc_bn = bn\n            break\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    for ow_factor in range(out_width, 0, -1):\n        if out_width % ow_factor == 0:\n            for oh_factor in range(out_height, 0, -1):\n                if out_height % oh_factor == 0 and ow_factor * oh_factor < 32:\n                    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n                    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n                    cfg[\"tile_oh\"] = OtherOptionEntity(oh_factor)\n                    cfg[\"tile_ow\"] = SplitEntity([out_width // ow_factor, ow_factor])\n                    return\n    raise ValueError(\"cannot decide default schedule for workload: {}\".format(wkl))\n\n\ndef _schedule_conv_NCHWc(s, cfg, data_vec, kernel_vec, conv_out, last):\n    # fetch schedule\n    oh_factor, ow_factor = cfg[\"tile_oh\"].val, cfg[\"tile_ow\"].size[-1]\n    _, _, _, _, ic_bn = get_const_tuple(data_vec.shape)\n\n    # schedule pad\n    if isinstance(s[data_vec].op, tvm.te.ComputeOp) and \"pad\" in data_vec.op.tag:\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        s[data_vec].vectorize(ic_block)\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n        data_vec = data_vec.op.input_tensors[0]\n\n    oc_bn = cfg[\"tile_oc\"].size[-1]\n    if isinstance(kernel_vec.op, tvm.te.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        # data and kernel are not pre-computed, schedule layout transform here.\n        # this should only be used by x86 conv2d_nchw, which is for\n        # testing purpose.\n        batch, ic_chunk, ih, ic_block, iw = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n\n        oc_chunk, ic_chunk, oh, ow, ic_block, oc_block = s[kernel_vec].op.axis\n        s[kernel_vec].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n        if oc_bn > 1:\n            s[kernel_vec].vectorize(oc_block)\n        parallel_axis = s[kernel_vec].fuse(oc_chunk, oh)\n        s[kernel_vec].parallel(parallel_axis)\n\n    C, O = conv_out, last\n    CC = s.cache_write(C, \"global\")\n\n    batch, oc_chunk, oh, ow, oc_block = s[C].op.axis\n    oh_outer, oh_inner = s[C].split(oh, factor=oh_factor)\n    ow_outer, ow_inner = s[C].split(ow, factor=ow_factor)\n    s[C].reorder(oc_chunk, oh_outer, ow_outer, oh_inner, ow_inner, oc_block)\n    s[C].vectorize(oc_block)\n\n    parallel_axis = s[C].fuse(batch, oc_chunk, oh_outer)\n    s[CC].compute_at(s[C], parallel_axis)\n    if C == O:\n        s[C].parallel(parallel_axis)\n\n    _, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n    ic, _, _ = s[CC].op.reduce_axis\n\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    oh_outer, oh_inner = s[CC].split(oh, factor=oh_factor)\n    ow_outer, ow_inner = s[CC].split(ow, factor=ow_factor)\n\n    s[CC].reorder(oc_chunk, oh_outer, ow_outer, ic_chunk, ic_block, oh_inner, ow_inner, oc_block)\n    s[CC].fuse(oc_chunk, oh_outer)\n    s[CC].vectorize(oc_block)\n\n    s[CC].unroll(ow_inner)\n    s[CC].unroll(oh_inner)\n\n    if C != O:\n        out_ndim = len(s[O].op.axis)\n        if out_ndim == 5:\n            batch, oc_chunk, oh, ow, oc_block = s[O].op.axis\n            oh_outer, oh_inner = s[O].split(oh, factor=oh_factor)\n            ow_outer, ow_inner = s[O].split(ow, factor=ow_factor)\n            s[O].reorder(oc_chunk, oh_outer, ow_outer, oh_inner, ow_inner, oc_block)\n\n            parallel_axis = s[O].fuse(batch, oc_chunk, oh_outer)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        elif out_ndim == 4:\n            batch, oc, oh, ow = s[O].op.axis\n            oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n            oh_outer, oh_inner = s[O].split(oh, factor=oh_factor)\n            ow_outer, ow_inner = s[O].split(ow, factor=ow_factor)\n            s[O].reorder(oc_chunk, oh_outer, ow_outer, oh_inner, ow_inner, oc_block)\n            parallel_axis = s[O].fuse(batch, oc_chunk, oh_outer)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        else:\n            raise ValueError(\"Unsupported output ndim: %s\" % out_ndim)\n\n    return s\n\n\ndef _schedule_conv_NCHWc_int8(s, cfg, data_vec, kernel_vec, conv_out, last):\n    return conv2d_generic.schedule_conv_NCHWc_cpu_1x1_int8(\n        s,\n        cfg,\n        data_vec,\n        kernel_vec,\n        conv_out,\n        last,\n        int32_lanes=get_simd_32bit_lanes(),\n        intrin=dot_16x1x16_uint8_int8_int32(),\n    )\n\n\ndef _declaration_conv_nhwc_pack(cfg, Input, Filter, stride, padding, dilation, out_dtype):\n    # more assertion for the shapes\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_height, in_width, in_channel = Input.shape\n    kernel_h, kernel_w, num_filter, channel = Filter.shape\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel = num_filter\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    pad_before = [0, pad_top, pad_left, 0]\n    pad_after = [0, pad_down, pad_right, 0]\n    PaddedInput = pad(Input, pad_before, pad_after, name=\"PaddedInput\")\n    # todo: padding filter to accommodate the intrinsic\n\n    # packing the Filter to let memory access be consecutive for AVX512 intrinsic\n    # Done in pre-compute stage\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    packw_shape = (kernel_h, kernel_w, idxd(num_filter, 16), 16 * idxd(channel, 4), 4)\n    PackW = te.compute(\n        packw_shape,\n        lambda a, b, c, d, e: Filter[a, b, c * 16 + idxm(d, 16), idxd(d, 16) * 4 + e],\n        name=\"packed_filter\",\n    )\n\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n    Output = te.compute(\n        (batch, out_height, out_width, out_channel),\n        lambda nn, yy, xx, ff: te.sum(\n            PaddedInput[\n                nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rc\n            ].astype(out_dtype)\n            * PackW[ry, rx, idxd(ff, 16), idxd(rc, 4) * 16 + idxm(ff, 16), idxm(rc, 4)].astype(\n                out_dtype\n            ),\n            axis=[ry, rx, rc],\n        ),\n        name=\"Conv2d_1x1_Output_int8\",\n        tag=\"conv2d_nhwc_pack_int8\",\n    )\n    return Output\n\n\ndef _schedule_conv_nhwc_pack_int8(s, cfg, data, conv_out, last):\n    \"\"\"\n    Defines the schedule for the int8 nhwc layout. For 1x1 conv, it\n    is a matrix-multiply operation by using nhwc layout. We will do\n    packing of weight to make the address access be friendly to int8\n    intrinsic\n    \"\"\"\n    # FIXME - https://github.com/apache/tvm/issues/3598\n    # pylint: disable=unreachable\n    return s\n\n    int32_lanes = 16\n\n    # assertion to fail the unhandled case\n    _, _, _, ic_num = get_const_tuple(data.shape)\n    _, _, _, oc_num = get_const_tuple(conv_out.shape)\n    assert ic_num % 4 == 0\n    assert oc_num % 16 == 0\n\n    ic_factor, oc_factor = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    # schedule data\n    A = data\n    if isinstance(s[A].op, tvm.te.ComputeOp):\n        batch, ih, iw, ic = s[A].op.axis\n        d_ic_chunk, d_ic_block = s[A].split(ic, factor=4)\n        s[A].vectorize(d_ic_block)\n\n    C, O = conv_out, last\n\n    batch, oh, ow, oc = s[C].op.axis\n    kh, kw, ic = s[C].op.reduce_axis\n    # match the x86 intrinsic\n    ic_outer, ic_inner = s[C].split(ic, factor=4)\n    oc_outer, oc_inner = s[C].split(oc, factor=int32_lanes)\n\n    ic_f_outer, ic_s_outer = s[C].split(ic_outer, factor=ic_factor)\n    s[C].reorder(oc_outer, oh, ow, ic_f_outer, ic_s_outer, kh, kw, oc_inner, ic_inner)\n\n    pc = dot_16x1x16_uint8_int8_int32()\n    s[C].tensorize(oc_inner, pc)\n\n    if C != O:\n        batch, last_oh, last_ow, last_oc = s[O].op.axis\n        oc_chunk, oc_block = s[O].split(ochannel, 16)\n        # not saw perf improvement to split oh/ow here\n        s[O].vectorize(oc_block)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d_avx_common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,invalid-name\n\"\"\"Conv2D schedule on for Intel CPU\"\"\"\nimport tvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom ..generic import conv2d as conv2d_generic\nfrom ..utils import get_const_tuple\nfrom .tensor_intrin import dot_16x1x16_uint8_int8_int32\nfrom .utils import get_simd_32bit_lanes\n\n\ndef _fallback_schedule(cfg, wkl):\n    simd_width = get_simd_32bit_lanes()\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    dilated_kernel_w = (wkl.kernel_w - 1) * wkl.dilation_w + 1\n\n    out_width = (wkl.width + pl + pr - dilated_kernel_w) // WSTR + 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if wkl.out_filter % bn == 0:\n            oc_bn = bn\n            break\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\ndef _fallback_schedule_int8(cfg, wkl):\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    out_width = (wkl.width + pl + pr - wkl.kernel_w) // WSTR + 1\n\n    oc_bn = 16\n    assert wkl.out_filter % oc_bn == 0\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -4):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n    assert wkl.in_filter % 4 == 0\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\ndef _schedule_conv_NCHWc(s, cfg, data_vec, kernel_vec, conv_out, last):\n    # fetch schedule\n    reg_n, unroll_kw = cfg[\"tile_ow\"].size[-1], cfg[\"unroll_kw\"].val\n    _, _, _, _, ic_bn = get_const_tuple(data_vec.shape)\n\n    # schedule pad\n    if isinstance(s[data_vec].op, tvm.te.ComputeOp) and \"pad\" in data_vec.op.tag:\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        s[data_vec].vectorize(ic_block)\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n        data_vec = data_vec.op.input_tensors[0]\n\n    oc_bn = cfg[\"tile_oc\"].size[-1]\n    if isinstance(kernel_vec.op, tvm.te.ComputeOp) and kernel_vec.name == \"kernel_vec\":\n        # data and kernel are not pre-computed, schedule layout transform here.\n        # this should only be used by x86 conv2d_nchw, which is for\n        # testing purpose.\n        batch, ic_chunk, ih, ic_block, iw = s[data_vec].op.axis\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n\n        oc_chunk, ic_chunk, oh, ow, ic_block, oc_block = s[kernel_vec].op.axis\n        s[kernel_vec].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n        if oc_bn > 1:\n            s[kernel_vec].vectorize(oc_block)\n        parallel_axis = s[kernel_vec].fuse(oc_chunk, oh)\n        s[kernel_vec].parallel(parallel_axis)\n\n    # schedule 5-D NCHW[x]c conv\n    C, O = conv_out, last\n    CC = s.cache_write(C, \"global\")\n\n    batch, oc_chunk, oh, ow, oc_block = s[C].op.axis\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n    s[C].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[C].fuse(batch, oc_chunk, oh)\n    s[C].vectorize(oc_block)\n    if C == O:\n        s[C].parallel(parallel_axis)\n\n    s[CC].compute_at(s[C], ow_chunk)\n    _, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n    ic, kh, kw = s[CC].op.reduce_axis\n\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    if unroll_kw:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, ic_block, kw, ow_block, oc_block)\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, kw, ic_block, ow_block, oc_block)\n\n    s[CC].vectorize(oc_block)\n    s[CC].unroll(ow_block)\n\n    if C != O:\n        out_ndim = len(s[O].op.axis)\n        if out_ndim == 5:\n            batch, oc_chunk, oh, ow, oc_block = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n            parallel_axis = s[O].fuse(batch, oc_chunk, oh)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        elif out_ndim == 4:\n            batch, oc, oh, ow = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n            oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n            parallel_axis = s[O].fuse(batch, oc_chunk, oh)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        else:\n            raise ValueError(\"Unsupported output ndim: %s\" % out_ndim)\n\n    return s\n\n\ndef _schedule_conv_NCHWc_int8(s, cfg, data_vec, kernel_vec, conv_out, last):\n    return conv2d_generic.schedule_conv_NCHWc_cpu_common_int8(\n        s,\n        cfg,\n        data_vec,\n        kernel_vec,\n        conv_out,\n        last,\n        int32_lanes=get_simd_32bit_lanes(),\n        intrin=dot_16x1x16_uint8_int8_int32(),\n        inline_fused=True,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter,import-outside-toplevel\n\"\"\"Conv2D int8 schedule on x86\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom ..nn.conv2d import _get_workload as _get_conv2d_workload\nfrom .. import tag\nfrom ..generic import conv2d as conv2d_generic\nfrom ..nn.utils import get_pad_tuple\nfrom ..nn.conv2d import unpack_NCHWc_to_nchw\nfrom ..nn.depthwise_conv2d import _get_workload as _get_depthwise_conv2d_workload\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .. import nn\nfrom . import conv2d_avx_1x1, conv2d_avx_common\nfrom .utils import target_has_sse42\n\n\ndef _get_default_config_int8(\n    cfg,\n    data,\n    kernel,\n    strides,\n    padding,\n    dilation,\n    out_dtype,\n    is_depthwise=False,\n    layout=\"NCHW\",\n    int32_lanes=4,\n):\n    \"\"\"\n    Get default schedule config for the workload\n    \"\"\"\n    if is_depthwise:\n        # Fallback to FP32 default config until a VNNI schedule is defined.\n        wkl = _get_depthwise_conv2d_workload(data, kernel, strides, padding, out_dtype)\n        from .depthwise_conv2d import _fallback_schedule\n\n        _fallback_schedule(cfg, wkl)\n    else:\n        wkl = _get_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype, layout)\n        is_kernel_1x1 = wkl.kernel_h == 1 and wkl.kernel_w == 1\n        if is_kernel_1x1:\n            conv2d_generic.fallback_schedule_cpu_1x1_int8(\n                cfg, wkl, int32_lanes=int32_lanes, num_int8_elements=4\n            )\n        else:\n            conv2d_generic.fallback_schedule_cpu_common_int8(\n                cfg, wkl, int32_lanes=int32_lanes, num_int8_elements=4\n            )\n\n\ndef is_int8_hw_support(data_dtype, kernel_dtype):\n    \"\"\"\n    Checks to ensure that we can use Intel DLBoost instructions\n    1) The datatypes are correct.\n    2) LLVM version has support for the instructions.\n    3) Target is skylake and above.\n    \"\"\"\n    # 1) Check datatypes\n    is_dtype_support = data_dtype == \"uint8\" and kernel_dtype == \"int8\"\n\n    # 2) Check LLVM support\n    llvm_version = tvm.target.codegen.llvm_version_major()\n    is_llvm_support = llvm_version >= 8\n\n    # 3) Check target\n    mcpu = tvm.target.Target.current().mcpu\n    is_target_support = target_has_sse42(mcpu)\n\n    return is_dtype_support and is_llvm_support and is_target_support\n\n\ndef conv2d_nchw_int8(data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute conv2d with NCHW layout and int8 dtype\"\"\"\n    layout = \"NCHW\"\n    packed_out = conv2d_NCHWc_int8(\n        data, kernel, strides, padding, dilation, layout, layout, out_dtype\n    )\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_conv2d_nchw_int8(outs):\n    \"\"\"Create the schedule for conv2d_nchw_int8\"\"\"\n    return schedule_conv2d_NCHWc_int8(outs)\n\n\ndef _pack_data(cfg, data, kernel):\n    n_elems = 4\n    n, _, ih, iw = get_const_tuple(data.shape)\n    oc, ic, kh, kw = get_const_tuple(kernel.shape)\n    ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n    ic_chunk = ic // ic_bn\n    oc_chunk = oc // oc_bn\n\n    data = te.compute(\n        (n, ic_chunk, ih, iw, ic_bn),\n        lambda bs, c, h, w, vc: data[bs, c * ic_bn + vc, h, w],\n        name=\"data_vec\",\n    )\n\n    kernel = te.compute(\n        (oc_chunk, ic_chunk, kh, kw, ic_bn // n_elems, oc_bn, n_elems),\n        lambda occ, icc, k_h, k_w, icbc, ocb, icbb: kernel[\n            occ * oc_bn + ocb, icc * ic_bn + icbc * n_elems + icbb, k_h, k_w\n        ],\n        name=\"kernel_vec\",\n    )\n\n    return data, kernel\n\n\n@autotvm.register_topi_compute(\"conv2d_NCHWc_int8.x86\")\ndef conv2d_NCHWc_int8(cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype):\n    \"\"\"Compute conv2d with NCHWc layout and int8 dtype\"\"\"\n    if len(data.shape) == 5:\n        n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape)\n        in_channel = ic_chunk * ic_bn\n        oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn, _ = get_const_tuple(\n            kernel.shape\n        )\n        num_filter = oc_chunk * oc_bn\n    else:\n        n, in_channel, ih, iw = get_const_tuple(data.shape)\n        num_filter, _, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n\n    # Define autotvm tuning space\n    is_kernel_1x1 = kernel_height == 1 and kernel_width == 1\n    pt, pl, pb, pr = get_pad_tuple(padding, (kernel_height, kernel_width))\n    sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    dh, dw = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n    dilated_kernel_h = (kernel_height - 1) * dh + 1\n    dilated_kernel_w = (kernel_width - 1) * dw + 1\n    oh = (ih - dilated_kernel_h + pt + pb) // sh + 1\n    ow = (iw - dilated_kernel_w + pl + pr) // sw + 1\n\n    cfg.define_split(\"tile_ic\", in_channel, num_outputs=2, filter=lambda y: y.size[-1] % 4 == 0)\n    cfg.define_split(\"tile_oc\", num_filter, num_outputs=2, filter=lambda y: y.size[-1] % 16 == 0)\n    cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda y: y.size[-1] <= 64)\n    if is_kernel_1x1:\n        cfg.define_knob(\"tile_oh\", [1, 2] if oh > 1 else [1])\n    else:\n        cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # If no config was set, we can fallback to default config.\n    if cfg.is_fallback:\n        _get_default_config_int8(\n            cfg,\n            te.placeholder((n, in_channel, ih, iw), dtype=data.dtype),\n            te.placeholder(\n                (num_filter, in_channel, kernel_height, kernel_width), dtype=kernel.dtype\n            ),\n            strides,\n            padding,\n            dilation,\n            out_dtype,\n            int32_lanes=16,\n        )\n\n    # Pack data if raw 4-D data is provided.\n    # This can only happen when autotuning.\n    if len(data.shape) == 4:\n        data, kernel = _pack_data(cfg, data, kernel)\n\n    return nn.conv2d_NCHWc_int8(\n        data, kernel, strides, padding, dilation, layout, out_layout, out_dtype\n    )\n\n\n@autotvm.register_topi_schedule(\"conv2d_NCHWc_int8.x86\")\ndef schedule_conv2d_NCHWc_int8(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        if \"conv2d_NCHWc_int8\" in op.tag:\n            conv_out = op.output(0)\n            kernel_vec = conv_out.op.input_tensors[1]\n            data_vec = conv_out.op.input_tensors[0]\n\n            args = [s, cfg, data_vec, kernel_vec, conv_out, outs[0]]\n            # int8 conv kernel is 7-dim\n            _, _, kh, kw, _, _, _ = get_const_tuple(kernel_vec.shape)\n            if kh == 1 and kw == 1:\n                conv2d_avx_1x1._schedule_conv_NCHWc_int8(*args)\n            else:\n                conv2d_avx_common._schedule_conv_NCHWc_int8(*args)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_schedule(\"conv2d_nhwc_pack_int8.x86\")\ndef schedule_conv2d_nhwc_pack_int8(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    output_op = outs[0].op\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            else:  # inject custom schedule\n                if len(op.axis) == 4:  # schedule bias + bn + relu\n                    n, h, w, c = op.axis\n                    fused = s[op].fuse(n, h, w)\n                    s[op].parallel(fused)\n                    s[op].vectorize(c)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n\n        if \"conv2d_nhwc_pack_int8\" in op.tag:\n            conv_out = op.output(0)\n            kernel = conv_out.op.input_tensors[1]\n            data_vec = conv_out.op.input_tensors[0]\n            data = (\n                data_vec.op.input_tensors[0]\n                if isinstance(data_vec.op, te.tensor.ComputeOp) and \"pad\" not in data_vec.op.tag\n                else data_vec\n            )\n            if isinstance(data.op, te.tensor.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            args = [s, cfg, data_vec, conv_out, outs[0]]\n            if data.dtype == \"uint8\":\n                kh, kw, _, _, _ = get_const_tuple(kernel.shape)\n                if kh == 1 and kw == 1:\n                    conv2d_avx_1x1._schedule_conv_nhwc_pack_int8(*args)\n                else:\n                    raise ValueError(\"Only support 1x1 kernel with \" \"schedule_conv2d_nhwc_pack.\")\n            else:\n                raise ValueError(\n                    \"Not support this data type {} with \"\n                    \"schedule_conv2d_nhwc_pack. Only support int8\".format(data.dtype)\n                )\n\n        scheduled_ops.append(op)\n\n    traverse(output_op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Conv2D Transpose schedule on x86\"\"\"\nfrom tvm import te\nfrom ..utils import traverse_inline\nfrom .. import nn\nfrom .conv2d import conv2d_nchw, schedule_conv2d_nchw\n\n\ndef conv2d_transpose_nchw(data, kernel, strides, padding, out_dtype, output_padding):\n    data_pad, kernel_transform = nn.conv2d_transpose_nchw_preprocess(\n        data, kernel, strides, padding, out_dtype, output_padding\n    )\n    # reuse conv2d_nchw implementation\n    return conv2d_nchw(\n        data_pad,\n        kernel_transform,\n        strides=(1, 1),\n        padding=(0, 0),\n        dilation=(1, 1),\n        out_dtype=out_dtype,\n    )\n\n\ndef schedule_conv2d_transpose_nchw(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = schedule_conv2d_nchw(outs)\n\n    def _callback(op):\n        if \"unpack_nchwc\" in op.tag:\n            conv_out = op.input_tensors[0]\n            # retrieve data\n            data_vec = conv_out.op.input_tensors[0]\n            if isinstance(data_vec, te.ComputeOp):\n                data_pad = data_vec.op.input_tensors[0]\n                data_dilate = data_pad.op.input_tensors[0]\n                s[data_dilate].compute_inline()\n                s[data_pad].compute_inline()\n            # retrieve kernel\n            kernel_vec = conv_out.op.input_tensors[1]\n            if isinstance(kernel_vec, te.ComputeOp):\n                kernel_transform = kernel_vec.op.input_tensors[0]\n                s[kernel_transform].compute_inline()\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv3d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, too-many-locals\n# pylint: disable=unused-argument, redefined-builtin, no-else-return\n\"\"\"Conv3D operators\"\"\"\nfrom collections import namedtuple\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\nfrom ..utils import traverse_inline\nfrom ..nn.utils import get_pad_tuple3d, infer_pad3d\nfrom ..nn.pad import pad\nfrom ..utils import get_const_tuple, simplify, get_const_int\nfrom .utils import get_simd_32bit_lanes\n\nWorkload3D = namedtuple(\n    \"Workload\",\n    [\n        \"in_dtype\",\n        \"out_dtype\",\n        \"depth\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"groups\",\n        \"out_filter\",\n        \"dkernel\",\n        \"hkernel\",\n        \"wkernel\",\n        \"dpad\",\n        \"hpad\",\n        \"wpad\",\n        \"dstride\",\n        \"hstride\",\n        \"wstride\",\n    ],\n)\n\n\n@autotvm.register_topi_compute(\"conv3d_ndhwc.x86\")\ndef conv3d_ndhwc(cfg, data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"3D convolution forward operator.\n\n    Parameters\n    ----------\n    input : tvm.te.Tensor\n        5-D input data with shapes:\n        [batch, in_depth, in_height, in_width, in_channel] for NDHWC layout\n\n    filter : tvm.te.Tensor\n        5-D filter with shape [kernel_depth, kernel_height, kernel_width, in_channels, out_channels]\n\n    strides : int or a list/tuple of three ints\n        stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or a list/tuple of three ints\n        padding size, or [pad_depth, pad_height, pad_width]\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_depth, out_height, out_width, out_channel] for NDHWC layout\n    \"\"\"\n    layout = \"NDHWC\"\n    out_dtype = data.dtype if out_dtype is None else out_dtype\n    strides = strides if isinstance(strides, (tuple, list)) else (strides, strides, strides)\n    dilation = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation, dilation)\n\n    _create_tuning_space(cfg, data, kernel, strides, padding, dilation, groups, layout)\n    if cfg.is_fallback:\n        _get_default_config(cfg, data, kernel, strides, padding, groups, out_dtype, layout)\n    return _conv3d_ndhwc(cfg, data, kernel, strides, padding, dilation, groups, out_dtype)\n\n\n@autotvm.register_topi_compute(\"conv3d_ncdhw.x86\")\ndef conv3d_ncdhw(cfg, data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"3D convolution forward operator.\n\n    Parameters\n    ----------\n    input : tvm.te.Tensor\n        5-D input data with shapes:\n        [batch, in_channel, in_depth, in_height, in_width] for NCDHW layout\n\n    filter : tvm.te.Tensor\n        5-D filter with shape [out_channels, in_channels, kernel_depth, kernel_height, kernel_width]\n\n    strides : int or a list/tuple of three ints\n        stride size, or [stride_depth, stride_height, stride_width]\n\n    padding : int or a list/tuple of three ints\n        padding size, or [pad_depth, pad_height, pad_width]\n\n    dilation: int or a list/tuple of three ints\n        dilation size, or [dilation_depth, dilation_height, dilation_width]\n\n    groups: int\n        Number of groups\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        5-D with shape [batch, out_channel, out_depth, out_height, out_width] for NCDHW layout\n    \"\"\"\n    # assert groups == 1, \"conv3d_ncdhw.x86 does not support groups\"\n    layout = \"NCDHW\"\n    out_dtype = data.dtype if out_dtype is None else out_dtype\n    strides = strides if isinstance(strides, (tuple, list)) else (strides, strides, strides)\n    dilation = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation, dilation)\n\n    _create_tuning_space(cfg, data, kernel, strides, padding, dilation, groups, layout)\n    if cfg.is_fallback:\n        _get_default_config(cfg, data, kernel, strides, padding, groups, out_dtype, layout)\n    return _conv3d_ncdhw(cfg, data, kernel, strides, padding, dilation, layout, groups, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"conv3d_ndhwc.x86\")\ndef schedule_conv3d_ndhwc(cfg, outs):\n    \"\"\"TOPI schedule callback for conv3d\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv3d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv3d.\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _traverse(op):\n        if \"conv3d_ndhwc\" in op.tag:\n            output = op.output(0)\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel = kernel_vec.op.input_tensors[0]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            data_vec = conv_out.op.input_tensors[0]\n            data = data_vec.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            kd, kh, kw, i, o = get_const_tuple(kernel.shape)\n            args = [s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, outs[0]]\n            _schedule_conv3d_ndhwc(*args)\n\n    traverse_inline(s, outs[0].op, _traverse)\n    return s\n\n\n@autotvm.register_topi_schedule(\"conv3d_ncdhw.x86\")\ndef schedule_conv3d_ncdhw(cfg, outs):\n    \"\"\"TOPI schedule callback for conv3d\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n        The computation graph description of conv3d\n        in the format of an array of tensors.\n\n    Returns\n    -------\n    s: Schedule\n        The computation schedule for conv3d.\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _traverse(op):\n        if \"conv3d_ncdhw\" in op.tag:\n            output = op.output(0)\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel = kernel_vec.op.input_tensors[0]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            data_vec = conv_out.op.input_tensors[0]\n            data = data_vec.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            kd, kh, kw, i, o = get_const_tuple(kernel.shape)\n            args = [s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, outs[0]]\n            _schedule_conv3d_ncdhw(*args)\n\n    traverse_inline(s, outs[0].op, _traverse)\n    return s\n\n\ndef _conv3d_ndhwc(cfg, data, kernel, strides, padding, dilation, groups, out_dtype):\n    out_dtype = data.dtype if out_dtype is None else out_dtype\n\n    assert isinstance(dilation, int) or len(dilation) == 3\n    if isinstance(dilation, int):\n        dilation_d, dilation_h, dilation_w = (dilation, dilation, dilation)\n    else:\n        dilation_d, dilation_h, dilation_w = dilation\n\n    DSTR, HSTR, WSTR = strides\n    batch_size, in_depth, in_height, in_width, in_channel = get_const_tuple(data.shape)\n    kernel_depth, kernel_height, kernel_width, _, num_filter = get_const_tuple(kernel.shape)\n\n    assert in_channel % groups == 0, \"input channels must be a multiple of group size\"\n    assert num_filter % groups == 0, \"number of filters must be a multiple of group size\"\n\n    dilated_kernel_d = (kernel_depth - 1) * dilation_d + 1\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_front, pad_top, pad_left, pad_back, pad_down, pad_right = get_pad_tuple3d(\n        padding, (dilated_kernel_d, dilated_kernel_h, dilated_kernel_w)\n    )\n\n    pad_d = pad_front + pad_back\n    pad_h = pad_top + pad_down\n    pad_w = pad_left + pad_right\n\n    pad_depth = in_depth + pad_d\n    pad_height = in_height + pad_h\n    pad_width = in_width + pad_w\n\n    out_depth = simplify((in_depth + pad_d - dilated_kernel_d) // DSTR + 1)\n    out_height = simplify((in_height + pad_h - dilated_kernel_h) // HSTR + 1)\n    out_width = simplify((in_width + pad_w - dilated_kernel_w) // WSTR + 1)\n\n    # pack data\n    DOPAD = pad_d != 0 or pad_h != 0 or pad_w != 0\n    if DOPAD:\n        data_pad = pad(\n            data,\n            (0, pad_front, pad_top, pad_left, 0),\n            (0, pad_back, pad_down, pad_right, 0),\n            name=\"data_pad\",\n        )\n    else:\n        data_pad = data\n\n    # fetch schedule\n    ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    assert groups == 1 or ic_bn <= groups\n    assert groups == 1 or oc_bn <= groups\n    shape = (batch_size, in_channel // ic_bn, pad_depth, pad_height, ic_bn, pad_width)\n    data_vec = te.compute(\n        shape, lambda n, C, d, h, c, w: data_pad[n, d, h, w, C * ic_bn + c], name=\"data_vec\"\n    )\n\n    ci_tile = in_channel // groups // ic_bn\n    if ci_tile == 0 or ci_tile * ic_bn * groups < in_channel:\n        ci_tile += 1\n\n    # pack kernel\n    shape = (\n        num_filter // oc_bn,\n        ci_tile,\n        kernel_depth,\n        kernel_height,\n        kernel_width,\n        ic_bn,\n        oc_bn,\n    )\n    kernel_vec = te.compute(\n        shape,\n        lambda CO, CI, d, h, w, ci, co: kernel[d, h, w, CI * ic_bn + ci, CO * oc_bn + co],\n        name=\"kernel_vec\",\n    )\n\n    # convolution\n    oshape = (batch_size, num_filter // oc_bn, out_depth, out_height, out_width, oc_bn)\n    unpack_shape = (batch_size, out_depth, out_height, out_width, num_filter)\n\n    ic = te.reduce_axis((0, in_channel // groups), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n    kd = te.reduce_axis((0, kernel_depth), name=\"kd\")\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n\n    conv = te.compute(\n        oshape,\n        lambda n, oc_chunk, od, oh, ow, oc_block: te.sum(\n            data_vec[\n                n,\n                idxdiv(\n                    (oc_chunk * oc_bn + oc_block) // (num_filter // groups) * (in_channel // groups)\n                    + ic,\n                    ic_bn,\n                ),\n                od * DSTR + kd * dilation_d,\n                oh * HSTR + kh * dilation_h,\n                idxmod(\n                    (oc_chunk * oc_bn + oc_block) // (num_filter // groups) * (in_channel // groups)\n                    + ic,\n                    ic_bn,\n                ),\n                ow * WSTR + kw * dilation_w,\n            ].astype(out_dtype)\n            * kernel_vec[\n                oc_chunk, idxdiv(ic, ic_bn), kd, kh, kw, idxmod(ic, ic_bn), oc_block\n            ].astype(out_dtype),\n            axis=[kd, kh, kw, ic],\n        ),\n        name=\"conv\",\n    )\n    conv_unpacked = te.compute(\n        unpack_shape,\n        lambda n, d, h, w, c: conv[n, idxdiv(c, oc_bn), d, h, w, idxmod(c, oc_bn)].astype(\n            out_dtype\n        ),\n        name=\"output_unpack\",\n        tag=\"conv3d_ndhwc\",\n    )\n    return conv_unpacked\n\n\ndef _conv3d_ncdhw(cfg, data, kernel, strides, padding, dilation, layout, groups, out_dtype):\n    out_dtype = data.dtype if out_dtype is None else out_dtype\n\n    assert isinstance(dilation, int) or len(dilation) == 3\n    if isinstance(dilation, int):\n        dilation_d, dilation_h, dilation_w = (dilation, dilation, dilation)\n    else:\n        dilation_d, dilation_h, dilation_w = dilation\n\n    DSTR, HSTR, WSTR = strides\n    batch_size, in_channel, in_depth, in_height, in_width = get_const_tuple(data.shape)\n    num_filter, _, kernel_depth, kernel_height, kernel_width = get_const_tuple(kernel.shape)\n\n    dilated_kernel_d = (kernel_depth - 1) * dilation_d + 1\n    dilated_kernel_h = (kernel_height - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_width - 1) * dilation_w + 1\n\n    pad_front, pad_top, pad_left, pad_back, pad_down, pad_right = get_pad_tuple3d(\n        padding, (dilated_kernel_d, dilated_kernel_h, dilated_kernel_w)\n    )\n\n    pad_d = pad_front + pad_back\n    pad_h = pad_top + pad_down\n    pad_w = pad_left + pad_right\n\n    pad_depth = in_depth + pad_d\n    pad_height = in_height + pad_h\n    pad_width = in_width + pad_w\n\n    out_depth = simplify((in_depth + pad_d - dilated_kernel_d) // DSTR + 1)\n    out_height = simplify((in_height + pad_h - dilated_kernel_h) // HSTR + 1)\n    out_width = simplify((in_width + pad_w - dilated_kernel_w) // WSTR + 1)\n\n    # pack data\n    DOPAD = pad_d != 0 or pad_h != 0 or pad_w != 0\n    if DOPAD:\n        data_pad = pad(\n            data,\n            (0, 0, pad_front, pad_top, pad_left),\n            (0, 0, pad_back, pad_down, pad_right),\n            name=\"data_pad\",\n        )\n    else:\n        data_pad = data\n\n    # fetch schedule\n    ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n    shape = (batch_size, in_channel // ic_bn, pad_depth, pad_height, ic_bn, pad_width)\n    data_vec = te.compute(\n        shape, lambda n, C, d, h, c, w: data_pad[n, C * ic_bn + c, d, h, w], name=\"data_vec\"\n    )\n\n    ci_tile = in_channel // groups // ic_bn\n    if ci_tile == 0 or ci_tile * ic_bn * groups < in_channel:\n        ci_tile += 1\n\n    # pack kernel\n    shape = (\n        num_filter // oc_bn,\n        ci_tile,\n        kernel_depth,\n        kernel_height,\n        kernel_width,\n        ic_bn,\n        oc_bn,\n    )\n    kernel_vec = te.compute(\n        shape,\n        lambda CO, CI, d, h, w, ci, co: kernel[CO * oc_bn + co, CI * ic_bn + ci, d, h, w],\n        name=\"kernel_vec\",\n    )\n\n    # convolution\n    oshape = (batch_size, num_filter // oc_bn, out_depth, out_height, out_width, oc_bn)\n    unpack_shape = (batch_size, num_filter, out_depth, out_height, out_width)\n\n    ic = te.reduce_axis((0, in_channel // groups), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n    kd = te.reduce_axis((0, kernel_depth), name=\"kd\")\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n\n    conv = te.compute(\n        oshape,\n        lambda n, oc_chunk, od, oh, ow, oc_block: te.sum(\n            data_vec[\n                n,\n                idxdiv(\n                    (oc_chunk * oc_bn + oc_block) // (num_filter // groups) * (in_channel // groups)\n                    + ic,\n                    ic_bn,\n                ),\n                od * DSTR + kd * dilation_d,\n                oh * HSTR + kh * dilation_h,\n                idxmod(\n                    (oc_chunk * oc_bn + oc_block) // (num_filter // groups) * (in_channel // groups)\n                    + ic,\n                    ic_bn,\n                ),\n                ow * WSTR + kw * dilation_w,\n            ].astype(out_dtype)\n            * kernel_vec[\n                oc_chunk, idxdiv(ic, ic_bn), kd, kh, kw, idxmod(ic, ic_bn), oc_block\n            ].astype(out_dtype),\n            axis=[ic, kd, kh, kw],\n        ),\n        name=\"conv\",\n    )\n    conv_unpacked = te.compute(\n        unpack_shape,\n        lambda n, c, d, h, w: conv[n, idxdiv(c, oc_bn), d, h, w, idxmod(c, oc_bn)].astype(\n            out_dtype\n        ),\n        name=\"output_unpack\",\n        tag=\"conv3d_ncdhw\",\n    )\n    return conv_unpacked\n\n\ndef _create_tuning_space(cfg, data, kernel, strides, padding, dilation, groups, layout):\n    \"\"\"Create schedule configuration from input arguments\"\"\"\n    dshape = get_const_tuple(data.shape)\n    kshape = get_const_tuple(kernel.shape)\n    if layout == \"NDHWC\":\n        n, d, h, w, ic = dshape\n        kd, kh, kw, _, oc = kshape\n    elif layout == \"NCDHW\":\n        n, ic, d, h, w = dshape\n        oc, _, kd, kh, kw = kshape\n    else:\n        raise ValueError(\"Not support this layout {} with \" \"schedule template.\".format(layout))\n\n    # pad_front, pad_top, pad_left, pad_back, pad_down(bottom), pad_right\n    pf, pt, pl, pb, pd, pr = get_pad_tuple3d(padding, (kd, kh, kw))\n    sd, sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides, strides)\n    od = (d - kd + pf + pb) // sd + 1\n    oh = (h - kh + pt + pd) // sh + 1\n    ow = (w - kw + pl + pr) // sw + 1\n\n    # Create schedule config\n    cfg.define_split(\"tile_ic\", ic, num_outputs=2)\n    cfg.define_split(\"tile_oc\", oc, num_outputs=2)\n    cfg.define_split(\"tile_ow\", ow, num_outputs=2, filter=lambda y: y.size[-1] <= 8)\n    cfg.define_knob(\"unroll_kw\", [True, False])\n\n\ndef _get_default_config(cfg, data, kernel, strides, padding, groups, out_dtype, layout):\n    \"\"\"\n    Get default schedule config for the workload\n    \"\"\"\n    if layout not in [\"NDHWC\", \"NCDHW\"]:\n        raise ValueError(\"Layout {} is not supported\".format(layout))\n\n    static_data_shape = []\n    for dim in get_const_tuple(data.shape):\n        if isinstance(dim, tvm.tir.Var):\n            static_data_shape.append(1)\n        else:\n            static_data_shape.append(dim)\n    data = te.placeholder(static_data_shape, dtype=data.dtype)\n    wkl = _get_conv3d_workload(data, kernel, strides, padding, groups, out_dtype, layout)\n    _fallback_schedule(cfg, wkl)\n\n\ndef _get_conv3d_workload(data, kernel, stride, padding, groups, out_dtype, data_layout=\"NCHW\"):\n    \"\"\"Get the workload structure.\"\"\"\n    if data_layout == \"NCDHW\":\n        _, CI, ID, IH, IW = get_const_tuple(data.shape)\n        CO, CIG, KD, KH, KW = get_const_tuple(kernel.shape)\n    elif data_layout == \"NDHWC\":\n        _, ID, IH, IW, CI = get_const_tuple(data.shape)\n        KD, KH, KW, CIG, CO = get_const_tuple(kernel.shape)\n    else:\n        raise ValueError(\"not support this layout {} yet\".format(data_layout))\n\n    pad_front, pad_top, pad_left, pad_back, pad_down, pad_right = get_pad_tuple3d(\n        padding, (get_const_int(KD), get_const_int(KH), get_const_int(KW))\n    )\n    DPAD = pad_front + pad_back\n    HPAD = pad_top + pad_down\n    WPAD = pad_left + pad_right\n    if isinstance(stride, (tuple, list)):\n        DSTR, HSTR, WSTR = stride\n    else:\n        DSTR, HSTR, WSTR = stride, stride, stride\n    assert (data.dtype == kernel.dtype) or (\n        data.dtype == \"uint8\" and kernel.dtype == \"int8\"\n    ), \"Do not support inputs with different data types now. ' \\\n        '{} vs. {}\".format(\n        data.dtype, kernel.dtype\n    )\n    return Workload3D(\n        data.dtype,\n        out_dtype,\n        ID,\n        IH,\n        IW,\n        CI,\n        groups,\n        CO,\n        KD,\n        KH,\n        KW,\n        DPAD,\n        HPAD,\n        WPAD,\n        DSTR,\n        HSTR,\n        WSTR,\n    )\n\n\ndef _fallback_schedule(cfg, wkl):\n    simd_width = get_simd_32bit_lanes()\n    DPAD, HPAD, WPAD = wkl.dpad, wkl.hpad, wkl.wpad\n    DSTR, HSTR, WSTR = wkl.dstride, wkl.hstride, wkl.wstride\n    out_width = (wkl.width + 2 * WPAD - wkl.wkernel) // WSTR + 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if wkl.out_filter % bn == 0:\n            oc_bn = bn\n            break\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    reg_n = 1\n    for n in range(7, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\ndef _schedule_conv3d_ndhwc(s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, last):\n    # fetch schedule\n    ic_bn, oc_bn, reg_n, unroll_kw = (\n        cfg[\"tile_ic\"].size[-1],\n        cfg[\"tile_oc\"].size[-1],\n        cfg[\"tile_ow\"].size[-1],\n        cfg[\"unroll_kw\"].val,\n    )\n\n    # get padding size\n    padding = infer_pad3d(data, data_pad, \"NDHWC\")\n    DPAD, HPAD, WPAD = padding\n    DOPAD = DPAD != 0 or HPAD != 0 or WPAD != 0\n\n    A, W = data, kernel_vec\n    A0, A1 = data_pad, data_vec\n\n    # schedule data\n    if DOPAD:\n        s[A0].compute_inline()\n    batch, ic_chunk, idd, ih, ic_block, iw = s[A1].op.axis\n    parallel_axis = s[A1].fuse(batch, ic_chunk, idd, ih)\n    s[A1].parallel(parallel_axis)\n\n    # schedule kernel pack\n    oc_chunk, ic_chunk, od, oh, ow, ic_block, oc_block = s[W].op.axis\n    s[W].reorder(oc_chunk, od, oh, ic_chunk, ow, ic_block, oc_block)\n    if oc_bn > 1:\n        s[W].vectorize(oc_block)\n    parallel_axis = s[W].fuse(oc_chunk, od, oh)\n    s[W].parallel(parallel_axis)\n\n    # schedule conv\n    C, O0, O = conv_out, output, last\n    CC = s.cache_write(C, \"global\")\n\n    _, oc_chunk, od, oh, ow, oc_block = s[C].op.axis\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n    s[C].reorder(oc_chunk, od, oh, ow_chunk, ow_block, oc_block)\n    s[C].fuse(oc_chunk, od, oh)\n    s[C].vectorize(oc_block)\n\n    s[CC].compute_at(s[C], ow_chunk)\n    _, oc_chunk, od, oh, ow, oc_block = s[CC].op.axis\n    kd, kh, kw, ic = s[CC].op.reduce_axis\n\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    if unroll_kw:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kd, kh, ic_block, kw, ow_block, oc_block)\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kd, kh, kw, ic_block, ow_block, oc_block)\n\n    s[CC].fuse(oc_chunk, od, oh)\n    s[CC].vectorize(oc_block)\n    s[CC].unroll(ow_block)\n\n    if O0 != O:\n        s[O0].compute_inline()\n\n    # unpacking\n    batch, od, oh, ow, oc = s[O].op.axis\n    ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n    oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n    s[O].reorder(oc_chunk, od, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[O].fuse(batch, oc_chunk, od, oh)\n    s[C].compute_at(s[O], parallel_axis)\n    s[O].vectorize(oc_block)\n    s[O].parallel(parallel_axis)\n    return s\n\n\ndef _schedule_conv3d_ncdhw(s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, last):\n    # fetch schedule\n    ic_bn, oc_bn, reg_n, unroll_kw = (\n        cfg[\"tile_ic\"].size[-1],\n        cfg[\"tile_oc\"].size[-1],\n        cfg[\"tile_ow\"].size[-1],\n        cfg[\"unroll_kw\"].val,\n    )\n\n    # get padding size\n    padding = infer_pad3d(data, data_pad, \"NCDHW\")\n    DPAD, HPAD, WPAD = padding\n    DOPAD = DPAD != 0 or HPAD != 0 or WPAD != 0\n\n    A, W = data, kernel_vec\n    A0, A1 = data_pad, data_vec\n\n    # schedule data\n    if DOPAD:\n        s[A0].compute_inline()\n    batch, ic_chunk, idd, ih, ic_block, iw = s[A1].op.axis\n    parallel_axis = s[A1].fuse(batch, ic_chunk, idd, ih)\n    s[A1].parallel(parallel_axis)\n\n    # schedule kernel pack\n    oc_chunk, ic_chunk, od, oh, ow, ic_block, oc_block = s[W].op.axis\n    s[W].reorder(oc_chunk, od, oh, ic_chunk, ow, ic_block, oc_block)\n    if oc_bn > 1:\n        s[W].vectorize(oc_block)\n    parallel_axis = s[W].fuse(oc_chunk, od, oh)\n    s[W].parallel(parallel_axis)\n\n    # schedule conv\n    C, O0, O = conv_out, output, last\n    CC = s.cache_write(C, \"global\")\n\n    _, oc_chunk, od, oh, ow, oc_block = s[C].op.axis\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n    s[C].reorder(oc_chunk, od, oh, ow_chunk, ow_block, oc_block)\n    s[C].fuse(oc_chunk, od, oh)\n    s[C].vectorize(oc_block)\n\n    s[CC].compute_at(s[C], ow_chunk)\n    _, oc_chunk, od, oh, ow, oc_block = s[CC].op.axis\n    ic, kd, kh, kw = s[CC].op.reduce_axis\n\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    if unroll_kw:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kd, kh, ic_block, kw, ow_block, oc_block)\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kd, kh, kw, ic_block, ow_block, oc_block)\n\n    s[CC].fuse(oc_chunk, od, oh)\n    s[CC].vectorize(oc_block)\n    s[CC].unroll(ow_block)\n\n    if O0 != O:\n        s[O0].compute_inline()\n\n    # unpacking\n    batch, oc, od, oh, ow = s[O].op.axis\n    ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n    oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n    s[O].reorder(oc_chunk, od, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[O].fuse(batch, oc_chunk, od, oh)\n    s[C].compute_at(s[O], parallel_axis)\n    s[O].vectorize(oc_block)\n    s[O].parallel(parallel_axis)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/conv3d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter\n\n\"\"\"Conv3D Transpose schedule on x86\"\"\"\nfrom tvm import te\nfrom ..utils import traverse_inline\nfrom .. import nn\nfrom .conv3d import conv3d_ncdhw, schedule_conv3d_ncdhw\n\n\ndef conv3d_transpose_ncdhw(data, kernel, strides, padding, out_dtype, output_padding):\n    data_pad, kernel_transform = nn.conv3d_transpose_ncdhw_preprocess(\n        data, kernel, strides, padding, out_dtype, output_padding\n    )\n\n    # reuse conv3d_ncdhw implementation\n    return conv3d_ncdhw(data_pad, kernel_transform, (1, 1, 1), (0, 0, 0), (1, 1, 1), 1, out_dtype)\n\n\ndef schedule_conv3d_transpose_ncdhw(outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = schedule_conv3d_ncdhw(outs)\n\n    def _callback(op):\n        if \"unpack_ncdhwc\" in op.tag:\n            conv_out = op.input_tensors[0]\n            # retrieve data\n            data_vec = conv_out.op.input_tensors[0]\n            data_pad = data_vec.op.input_tensors[0]\n            data_dilate = data_pad.op.input_tensors[0]\n            s[data_dilate].compute_inline()\n            s[data_pad].compute_inline()\n            # retrieve kernel\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel_transform = kernel_vec.op.input_tensors[0]\n            s[kernel_transform].compute_inline()\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,unused-variable\n# pylint: disable=no-value-for-parameter\n\"\"\"x86 dense operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import autotvm, te\nfrom tvm.autotvm.task.space import SplitEntity\nfrom tvm.contrib import cblas, dnnl, mkl\n\nfrom .. import generic, tag\nfrom ..utils import get_const_tuple, traverse_inline\nfrom .tensor_intrin import dot_16x1x16_uint8_int8_int32_cascadelake\nfrom .utils import get_simd_32bit_lanes\n\n\ndef _schedule_dense_pack_template(cfg, s, C, O):\n    A, packedB = s[C].op.input_tensors\n\n    CC = s.cache_write(C, \"global\")\n    y, x = s[C].op.axis\n    (k,) = s[CC].op.reduce_axis\n\n    yt, yo, yi = cfg[\"tile_y\"].apply(s, C, y)\n    xt, xo, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].reorder(xt, yt, yo, xo, yi, xi)\n    xyt = s[C].fuse(xt, yt)\n    if C == O:\n        s[C].parallel(xyt)\n    xyo = s[C].fuse(yo, xo)\n    s[C].unroll(yi)\n    s[C].vectorize(xi)\n\n    s[CC].compute_at(s[C], xyo)\n    y, x = s[CC].op.axis\n    ko, ki = cfg[\"tile_k\"].apply(s, CC, k)\n    s[CC].reorder(ko, ki, y, x)\n    s[CC].vectorize(x)\n\n    tile_inner = cfg[\"tile_inner\"].size[-1]\n    if tile_inner > 1:\n        yo, yi = s[CC].split(y, tile_inner)\n        s[CC].reorder(ko, yo, ki, yi, x)\n        s[CC].unroll(yo)\n        s[CC].unroll(ki)\n        s[CC].unroll(yi)\n    else:\n        s[CC].unroll(ki)\n        s[CC].unroll(y)\n\n    if C != O:\n        y, x = s[O].op.axis\n        yt, yo, yi = cfg[\"tile_y\"].apply(s, O, y)\n        xt, xo, xi = cfg[\"tile_x\"].apply(s, O, x)\n        s[O].reorder(xt, yt, yo, xo, yi, xi)\n        xyt = s[O].fuse(xt, yt)\n        s[C].compute_at(s[O], xyt)\n        s[O].vectorize(xi)\n        s[O].parallel(xyt)\n    return s\n\n\ndef _schedule_dense_nopack_template(cfg, s, C):\n    y, x = s[C].op.axis\n    (kk,) = s[C].op.reduce_axis\n    yo, yi = cfg[\"tile_y\"].apply(s, C, y)\n    xo, xi = cfg[\"tile_x\"].apply(s, C, x)\n    s[C].reorder(yo, xo, yi, xi)\n    xyo = s[C].fuse(yo, xo)\n    s[C].parallel(xyo)\n    s[C].unroll(kk)\n\n    (CC,) = s[C].op.input_tensors\n    s[CC].compute_at(s[C], xyo)\n    z, y, x = s[CC].op.axis\n    (k,) = s[CC].op.reduce_axis\n    yz = s[CC].fuse(z, y)\n    s[CC].reorder(k, yz, x)\n    s[CC].unroll(yz)\n    s[CC].vectorize(x)\n    return s\n\n\ndef _default_dense_pack_config(cfg, M, N, K):\n    # Generate default schedule for dynamic shape.\n    if isinstance(M, (tvm.tir.Var, tvm.tir.Any)):\n        M = 16\n    if isinstance(N, (tvm.tir.Var, tvm.tir.Any)):\n        N = 16\n    if isinstance(K, (tvm.tir.Var, tvm.tir.Any)):\n        K = 16\n\n    vec_width = get_simd_32bit_lanes()\n    tilex_ii = 1\n    for bn in range(vec_width * 2, 0, -1):\n        if N % bn == 0:\n            tilex_ii = bn\n            break\n    NN = N // tilex_ii\n    tilex_oi = 1\n    while NN // tilex_oi > 4:\n        if (NN // tilex_oi) % 2 == 1:\n            break\n        tilex_oi *= 2\n\n    tiley_ii = 8\n    while M % tiley_ii != 0:\n        tiley_ii //= 2\n    MM = M // tiley_ii\n    tiley_oi = 1\n    while MM // tiley_oi > 4:\n        if (MM // tiley_oi) % 2 == 1:\n            break\n        tiley_oi *= 2\n\n    cfg[\"tile_y\"] = SplitEntity([MM // tiley_oi, tiley_oi, tiley_ii])\n    cfg[\"tile_x\"] = SplitEntity([NN // tilex_oi, tilex_oi, tilex_ii])\n    cfg[\"tile_k\"] = SplitEntity([K, 1])\n    cfg[\"tile_inner\"] = SplitEntity([M // tiley_ii, tiley_ii])\n\n\ndef _default_dense_nopack_config(cfg, M, N, K):\n    # Generate default schedule for dynamic shape.\n    if isinstance(M, (tvm.tir.Var, tvm.tir.Any)):\n        M = 16\n    if isinstance(N, (tvm.tir.Var, tvm.tir.Any)):\n        N = 16\n    if isinstance(K, (tvm.tir.Var, tvm.tir.Any)):\n        K = 16\n\n    vec_width = get_simd_32bit_lanes()\n    tilek_bn = 1\n    for bn in range(vec_width * 2, 0, -1):\n        if K % bn == 0:\n            tilek_bn = bn\n            break\n    cfg[\"tile_k\"] = SplitEntity([K // tilek_bn, tilek_bn])\n    cfg[\"tile_x\"] = SplitEntity([N, 1])\n    cfg[\"tile_y\"] = SplitEntity([1, M])\n\n\n@autotvm.register_topi_compute(\"dense_nopack.x86\")\ndef dense_nopack(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute dense without packing\"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n    M, K = get_const_tuple(data.shape)\n    N, _ = get_const_tuple(weight.shape)\n    # create tuning space\n    cfg.define_split(\n        \"tile_y\", 32 if isinstance(M, (tvm.tir.Var, tvm.tir.Any)) else M, num_outputs=2\n    )\n    cfg.define_split(\n        \"tile_x\", 32 if isinstance(N, (tvm.tir.Var, tvm.tir.Any)) else N, num_outputs=2\n    )\n    cfg.define_split(\n        \"tile_k\", 32 if isinstance(K, (tvm.tir.Var, tvm.tir.Any)) else K, num_outputs=2\n    )\n    if cfg.is_fallback:\n        _default_dense_nopack_config(cfg, M, N, K)\n\n    vec = cfg[\"tile_k\"].size[-1]\n    k = te.reduce_axis((0, K // vec), \"k\")\n    CC = te.compute(\n        (M, N, vec),\n        lambda z, y, x: te.sum(\n            data[z, k * vec + x].astype(out_dtype) * weight[y, k * vec + x].astype(out_dtype),\n            axis=k,\n        ),\n    )\n\n    kk = te.reduce_axis((0, vec), \"kk\")\n    C = te.compute((M, N), lambda y, x: te.sum(CC[y, x, kk], axis=kk), tag=\"dense_nopack\")\n    if bias is not None:\n        C = te.compute((M, N), lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST)\n    return C\n\n\n@autotvm.register_topi_schedule(\"dense_nopack.x86\")\ndef schedule_dense_nopack(cfg, outs):\n    \"\"\"Create the schedule for dense_nopack\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"dense_nopack\" in op.tag:\n            _schedule_dense_nopack_template(cfg, s, op.output(0))\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"dense_pack.x86\")\ndef dense_pack(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute dense with transformed weight.\"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n    M, K = get_const_tuple(data.shape)  # batch, in_dim\n    if len(weight.shape) == 3:\n        N, _, packw_bn = get_const_tuple(weight.shape)  # out_dim\n        N = N * packw_bn\n    else:\n        N, _ = get_const_tuple(weight.shape)  # out_dim\n    # create tuning space\n    cfg.define_split(\n        \"tile_y\", 32 if isinstance(M, (tvm.tir.Var, tvm.tir.Any)) else M, num_outputs=3\n    )\n    cfg.define_split(\n        \"tile_x\", 32 if isinstance(N, (tvm.tir.Var, tvm.tir.Any)) else N, num_outputs=3\n    )\n    cfg.define_split(\n        \"tile_k\", 32 if isinstance(K, (tvm.tir.Var, tvm.tir.Any)) else K, num_outputs=2\n    )\n    cfg.define_split(\n        \"tile_inner\",\n        32 if isinstance(M, (tvm.tir.Var, tvm.tir.Any)) else M,\n        num_outputs=2,\n        filter=lambda y: y.size[-1] <= 16,\n    )\n    if cfg.is_fallback:\n        _default_dense_pack_config(cfg, M, N, K)\n\n    if len(weight.shape) == 2:\n        packw_bn = cfg[\"tile_x\"].size[-1]\n        packw_shape = (N // packw_bn, K, packw_bn)\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # Directly use modified data layout placeholder.\n            packw = tvm.te.placeholder(packw_shape, weight.dtype, name=\"packed_weight\")\n        else:\n            packw = te.compute(\n                packw_shape, lambda z, y, x: weight[z * packw_bn + x, y], name=\"packed_weight\"\n            )\n    else:\n        packw = weight\n\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n    k = te.reduce_axis((0, K), name=\"k\")\n    C = te.compute(\n        (M, N),\n        lambda y, x: te.sum(\n            data[y, k].astype(out_dtype)\n            * packw[idxdiv(x, packw_bn), k, idxmod(x, packw_bn)].astype(out_dtype),\n            axis=k,\n        ),\n        tag=\"dense_pack\",\n    )\n    if bias is not None:\n        C = te.compute((M, N), lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST)\n    return C\n\n\n@autotvm.register_topi_schedule(\"dense_pack.x86\")\ndef schedule_dense_pack(cfg, outs):\n    \"\"\"Create the schedule for dense_pack\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"dense_pack\" in op.tag:\n            _schedule_dense_pack_template(cfg, s, op.output(0), outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef dense_vnni_compute(cfg, X, packed_w, bias=None):\n    \"\"\"Compute for uint8 x int8 -> int32 dense\"\"\"\n    m, k = X.shape\n    n_o, _, n_i, _ = packed_w.shape\n    ak = te.reduce_axis((0, k), name=\"k\")\n\n    C = te.compute(\n        (m, n_o * n_i),\n        lambda i, j: te.sum(\n            X[i, ak].astype(\"int32\")\n            * packed_w[tvm.tir.indexdiv(j, 16), tvm.tir.indexdiv(ak, 4), j % 16, ak % 4].astype(\n                \"int32\"\n            ),\n            axis=ak,\n        ),\n        tag=\"dense_vnni\",\n        attrs={\"schedule_rule\": \"dense_vnni\"},\n    )\n\n    if bias is not None:\n        C = te.compute(C.shape, lambda i, j: C[i, j] + bias[j], tag=tag.BROADCAST)\n\n    a_y, _ = C.op.axis\n    cfg.define_split(\"tile_y\", a_y, num_outputs=2)\n\n    return C\n\n\ndef dense_vnni_schedule(cfg, s, C, O, do_parallel=True):\n    \"\"\"Schedule dense compute using VNNI vpdpbusd instruction\"\"\"\n    # C: The output of GEMM\n    # O: The output of the fused op\n    def split_y(out):\n        default_y_split_factor = 32\n        a_y = out.op.axis[-2]\n\n        if cfg.is_fallback:\n            return s[out].split(a_y, factor=default_y_split_factor)\n\n        return cfg[\"tile_y\"].apply(s, out, a_y)\n\n    (a_k,) = C.op.reduce_axis\n\n    a_yo, a_yi = split_y(C)\n    a_xo, a_xi = s[C].split(C.op.axis[-1], factor=16)\n    a_ko, a_ki = s[C].split(a_k, factor=4)\n\n    s[C].reorder(a_yo, a_xo, a_yi, a_ko, a_xi, a_ki)\n\n    pc = dot_16x1x16_uint8_int8_int32_cascadelake()\n    s[C].tensorize(a_xi, pc)\n\n    if C == O:\n        fused = s[O].fuse(a_yo, a_xo)\n    else:\n        a_yo, a_yi = split_y(O)\n        a_xo, a_xi = s[O].split(O.op.axis[-1], factor=16)\n\n        s[O].reorder(a_yo, a_xo, a_yi, a_xi)\n        s[O].vectorize(a_xi)\n        s[C].compute_at(s[O], a_yi)\n\n        fused = s[O].fuse(a_yo, a_xo)\n\n    if do_parallel:\n        s[O].parallel(fused)\n\n    return s, fused\n\n\n@autotvm.register_topi_compute(\"dense_vnni.x86\")\ndef dense_vnni(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute for uint8 x int8 -> int32 dense\"\"\"\n    if out_dtype is None:\n        out_dtype = data.dtype\n    assert len(weight.shape) == 4\n    assert data.dtype == \"uint8\" and weight.dtype == \"int8\"\n    _, _, n_inner, k_inner = get_const_tuple(weight.shape)  # out_dim\n    assert n_inner == 16 and k_inner == 4\n    return dense_vnni_compute(cfg, data, weight, bias)\n\n\n@autotvm.register_topi_schedule(\"dense_vnni.x86\")\ndef schedule_dense_vnni(cfg, outs):\n    \"\"\"Create a schedule for dense_vnni\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"dense_vnni\" in op.tag:\n            dense_vnni_schedule(cfg, s, op.output(0), outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef matmul_blas_common(cfg, tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b, lib):\n    \"\"\"Compute matmul/dense using a BLAS library\"\"\"\n    M, K = get_const_tuple(tensor_a.shape)\n    N, _ = get_const_tuple(tensor_b.shape)\n    if isinstance(M, int) and isinstance(K, int) and isinstance(N, int):\n        cfg.add_flop(M * K * N * 2)\n    if tensor_a.dtype == \"uint8\" and tensor_b.dtype == \"int8\" and out_dtype == \"int32\":\n        if not hasattr(lib, \"matmul_u8s8s32\"):\n            raise NotImplementedError(\n                f\"Matmul/Dense with {lib.__name__} for {tensor_a.dtype} is not supported \"\n                \"(matmulu8s8s32 not imlemented)\"\n            )\n        C = lib.matmul_u8s8s32(tensor_a, tensor_b, transpose_a, transpose_b, dtype=out_dtype)\n    elif tensor_a.dtype == \"float32\" or tensor_a.dtype == \"float64\":\n        C = lib.matmul(tensor_a, tensor_b, transpose_a, transpose_b)\n    else:\n        raise NotImplementedError(\n            f\"Matmul/Dense with {lib.__name__} for {tensor_a.dtype} is not supported\"\n        )\n\n    if bias is not None:\n        C = te.compute(C.shape, lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST)\n    return C\n\n\n@autotvm.register_topi_compute(\"dense_cblas.x86\")\ndef dense_cblas(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute dense using cblas. This is an alias of matmul_nt operator.\"\"\"\n    return matmul_blas_common(cfg, data, weight, bias, out_dtype, False, True, cblas)\n\n\n@autotvm.register_topi_schedule(\"dense_cblas.x86\")\ndef schedule_dense_cblas(_, outs):\n    \"\"\"Create schedule for dense_cblas. This is an alias of matmul_nt operator.\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"dense_mkl.x86\")\ndef dense_mkl(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute dense using mkl. This is an alias of matmul_nt operator.\"\"\"\n    return matmul_blas_common(cfg, data, weight, bias, out_dtype, False, True, mkl)\n\n\n@autotvm.register_topi_schedule(\"dense_mkl.x86\")\ndef schedule_dense_mkl(_, outs):\n    \"\"\"Create schedule for dense_mkl. This is an alias of matmul_nt operator.\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"dense_dnnl.x86\")\ndef dense_dnnl(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Compute dense using dnnl. This is an alias of matmul_nt operator.\"\"\"\n    return matmul_blas_common(cfg, data, weight, bias, out_dtype, False, True, dnnl)\n\n\n@autotvm.register_topi_schedule(\"dense_dnnl.x86\")\ndef schedule_dense_dnnl(_, outs):\n    \"\"\"Create schedule for dense_dnnl. This is an alias of matmul_nt operator.\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"matmul_cblas.x86\")\ndef matmul_cblas(\n    cfg, tensor_a, tensor_b, bias=None, out_dtype=None, transpose_a=False, transpose_b=False\n):\n    \"\"\"Compute matmul using cblas.\"\"\"\n    return matmul_blas_common(\n        cfg, tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b, cblas\n    )\n\n\n@autotvm.register_topi_schedule(\"matmul_cblas.x86\")\ndef schedule_matmul_cblas(_, outs):\n    \"\"\"Create schedule for matmul_cblas.\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"matmul_mkl.x86\")\ndef matmul_mkl(\n    cfg, tensor_a, tensor_b, bias=None, out_dtype=None, transpose_a=False, transpose_b=False\n):\n    \"\"\"Compute matmul using mkl.\"\"\"\n    return matmul_blas_common(\n        cfg, tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b, mkl\n    )\n\n\n@autotvm.register_topi_schedule(\"matmul_mkl.x86\")\ndef schedule_matmul_mkl(_, outs):\n    \"\"\"Create schedule for matmul_mkl.\"\"\"\n    return generic.schedule_extern(outs)\n\n\n@autotvm.register_topi_compute(\"matmul_dnnl.x86\")\ndef matmul_dnnl(\n    cfg, tensor_a, tensor_b, bias=None, out_dtype=None, transpose_a=False, transpose_b=False\n):\n    \"\"\"Compute matmul using dnnl.\"\"\"\n    return matmul_blas_common(\n        cfg, tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b, dnnl\n    )\n\n\n@autotvm.register_topi_schedule(\"matmul_dnnl.x86\")\ndef schedule_matmul_dnnl(_, outs):\n    \"\"\"Create schedule for matmul_dnnl.\"\"\"\n    return generic.schedule_extern(outs)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/dense_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Dense alter op functions for x86\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom .dense import _default_dense_pack_config\nfrom ..utils import get_const_tuple\nfrom ..nn import dense_alter_layout\nfrom .utils import target_has_vnni\nfrom .. import nn\n\n\ndef check_vnni_applicable(x, y):\n    mcpu = tvm.target.Target.current().mcpu\n    return (\n        target_has_vnni(mcpu)\n        and \"int8\" in x.dtype\n        and \"int8\" in y.dtype\n        and y.shape[-2] % 16 == 0\n        and y.shape[-1] % 4 == 0\n    )\n\n\n@dense_alter_layout.register([\"cpu\", \"arm_cpu\"])\ndef _alter_dense_layout(attrs, inputs, tinfos, out_type):\n    target = tvm.target.Target.current(allow_none=False)\n    dispatch_ctx = autotvm.task.DispatchContext.current\n    data_tensor, weight_tensor = tinfos\n    out_dtype = out_type.dtype\n    M, K = get_const_tuple(data_tensor.shape)\n    N, _ = get_const_tuple(weight_tensor.shape)\n\n    if check_vnni_applicable(data_tensor, weight_tensor) and data_tensor.dtype == \"uint8\":\n        weight_layout = \"NC16n4c\"\n        return relay.nn.contrib_dense_pack(inputs[0], inputs[1], weight_layout, None, out_dtype)\n\n    _, outs = relay.backend.te_compiler.select_implementation(\n        relay.op.get(\"nn.dense\"), attrs, tinfos, out_type, target\n    )\n    workload = autotvm.task.get_workload(outs)\n\n    if workload:\n        cfg = dispatch_ctx.query(target, workload)\n        topi_impl = workload[0]\n        if topi_impl == \"dense_pack.x86\":\n            if cfg.is_fallback:\n                _default_dense_pack_config(cfg, M, N, K)\n            packw_bn = cfg[\"tile_x\"].size[-1]\n            weight_layout = \"NC%dn\" % packw_bn\n            new_weight = te.placeholder(\n                (N // packw_bn, K, packw_bn),\n                dtype=weight_tensor.dtype,\n            )\n            # Relay dense doesn't have bias.\n            new_workload = autotvm.task.args_to_workload(\n                [\n                    data_tensor,\n                    new_weight,\n                    None,\n                    out_dtype,\n                ],\n                topi_impl,\n            )\n            dispatch_ctx.update(target, new_workload, cfg)\n            return relay.nn.contrib_dense_pack(inputs[0], inputs[1], weight_layout, None, out_dtype)\n\n    return None\n\n\ndef vnni_legalize(inputs, arg_types, op, attrs, need_expand=False):\n    \"\"\"Legalizes s8, s8 -> s32 GEMM op for VNNI.\"\"\"\n    if check_vnni_applicable(arg_types[0], arg_types[1]) and arg_types[0].dtype == \"int8\":\n        x, y = inputs\n        x = relay.cast(x, \"int32\")\n        x = relay.add(x, relay.const(128, \"int32\"))\n        x = relay.cast(x, \"uint8\")\n\n        adjust_shift = relay.const(128, \"int32\") * relay.sum(relay.cast(y, \"int32\"), axis=[-1])\n\n        if need_expand:\n            adjust_shift = relay.expand_dims(adjust_shift, axis=1)\n\n        out = op(x, y, **attrs)\n\n        return relay.subtract(out, adjust_shift)\n\n    return None\n\n\n@nn.dense_legalize.register(\"cpu\")\ndef _dense_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes s8, s8 -> s32 dense for VNNI.\"\"\"\n    return vnni_legalize(inputs, arg_types, relay.nn.dense, attrs)\n\n\n@nn.batch_matmul_legalize.register(\"cpu\")\ndef _batch_matmul_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes s8, s8 -> s32 batch_matmul for VNNI.\"\"\"\n    if attrs[\"transpose_a\"] or not attrs[\"transpose_b\"]:\n        return None\n    return vnni_legalize(inputs, arg_types, relay.nn.batch_matmul, attrs, need_expand=True)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter\n\"\"\"Depthwise Conv2D schedule on x86\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\nfrom ..nn.pad import pad\nfrom ..utils import get_const_tuple\nfrom ..nn.utils import get_pad_tuple\nfrom ..nn.depthwise_conv2d import _get_workload, depthwise_conv2d_infer_layout\nfrom ..nn.conv2d import unpack_NCHWc_to_nchw\nfrom ..utils import traverse_inline\nfrom .utils import get_simd_32bit_lanes\n\n\ndef _fallback_schedule(cfg, wkl):\n    \"\"\"\n    Get default schedule for the workload\n    Parameters\n    ----------\n    cfg : tvm.autotvm.task.space.FallbackConfigEntity\n        Fallback config to be updated\n    wkl : topi.nn.depthwise_conv2d.Workload\n        Convolution workload\n    \"\"\"\n    simd_width = get_simd_32bit_lanes()\n\n    pt, pl, pb, pr = wkl.padt, wkl.padl, wkl.padb, wkl.padr\n    HSTR, WSTR = wkl.stride_h, wkl.stride_w\n    dilated_kernel_w = (wkl.kernel_w - 1) * wkl.dilation_w + 1\n\n    out_width = (wkl.width - dilated_kernel_w + pl + pr) // WSTR + 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if wkl.out_filter % bn == 0:\n            oc_bn = bn\n            break\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if wkl.in_filter % bn == 0:\n            ic_bn = bn\n            break\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\ndef depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype):\n    \"\"\"Compute depthwise conv2d with NCHW layout.\"\"\"\n    layout = \"NCHW\"\n    packed_out = depthwise_conv2d_NCHWc(\n        data, kernel, strides, padding, dilation, layout, layout, out_dtype\n    )\n    return unpack_NCHWc_to_nchw(packed_out, out_dtype)\n\n\ndef schedule_depthwise_conv2d_nchw(outs):\n    \"\"\"Create schedule for depthwise_conv2d_nchw.\"\"\"\n    return schedule_depthwise_conv2d_NCHWc(outs)\n\n\ndef _pack_data(cfg, data, kernel):\n    n, ic, ih, iw = get_const_tuple(data.shape)\n    filters, cm, kh, kw = get_const_tuple(kernel.shape)\n    oc = filters * cm\n    ic_bn, oc_bn = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n\n    ic_chunk = ic // ic_bn\n    oc_chunk = oc // oc_bn\n\n    data = te.compute(\n        (n, ic_chunk, ih, iw, ic_bn),\n        lambda bs, c, h, w, vc: data[bs, c * ic_bn + vc, h, w],\n        name=\"data_vec\",\n    )\n\n    kernel = te.compute(\n        (oc_chunk, 1, kh, kw, 1, oc_bn),\n        lambda occ, icc, k_h, k_w, icb, ocb: kernel[\n            (occ * oc_bn + ocb) // cm, (occ * oc_bn + ocb) % cm, k_h, k_w\n        ],\n        name=\"kernel_vec\",\n    )\n\n    return data, kernel\n\n\n@autotvm.register_topi_compute(\"depthwise_conv2d_NCHWc.x86\")\ndef depthwise_conv2d_NCHWc(\n    cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype=None\n):\n    \"\"\"Compute depthwise conv2d with NCHWc layout\"\"\"\n    out_dtype = data.dtype if out_dtype is None else out_dtype\n\n    if len(data.shape) == 5:\n        batch, in_channel_chunk, in_height, in_width, in_channel_block = get_const_tuple(data.shape)\n        (\n            out_channel_chunk,\n            cm_chunk,\n            filter_height,\n            filter_width,\n            cm_block,\n            out_channel_block,\n        ) = get_const_tuple(kernel.shape)\n        in_channel = in_channel_chunk * in_channel_block\n        out_channel = out_channel_chunk * out_channel_block\n        channel_multiplier = cm_chunk * cm_block\n        assert channel_multiplier * in_channel == out_channel\n    else:\n        batch, in_channel, in_height, in_width = get_const_tuple(data.shape)\n        out_channel, channel_multiplier, filter_height, filter_width = get_const_tuple(kernel.shape)\n    assert channel_multiplier == 1\n\n    strides = strides if isinstance(strides, (tuple, list)) else (strides, strides)\n    HSTR, WSTR = strides\n\n    dh, dw = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation)\n\n    dilated_kernel_h = (filter_height - 1) * dh + 1\n    dilated_kernel_w = (filter_width - 1) * dw + 1\n    pad_top, pad_left, pad_down, pad_right = get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    HPAD = pad_top + pad_down\n    WPAD = pad_left + pad_right\n\n    out_height = (in_height + HPAD - dilated_kernel_h) // HSTR + 1\n    out_width = (in_width + WPAD - dilated_kernel_w) // WSTR + 1\n\n    cfg.define_split(\"tile_ic\", in_channel, num_outputs=2)\n    cfg.define_split(\"tile_oc\", out_channel, num_outputs=2)\n    cfg.define_split(\"tile_ow\", out_width, num_outputs=2, filter=lambda y: y.size[-1] <= 64)\n    cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # get workload and related schedule config\n    wkl = _get_workload(\n        te.placeholder((batch, in_channel, in_height, in_width), dtype=data.dtype),\n        te.placeholder(\n            (out_channel, channel_multiplier, filter_height, filter_width), dtype=kernel.dtype\n        ),\n        strides,\n        (pad_top, pad_down),\n        dilation,\n        out_dtype,\n    )\n    if cfg.is_fallback:\n        _fallback_schedule(cfg, wkl)\n\n    # Pack data if raw 4-D data is provided.\n    # This can only happen when autotuning.\n    if len(data.shape) == 4:\n        if autotvm.GLOBAL_SCOPE.in_tuning:\n            # Directly use modified data layout placeholder.\n            in_channel_block = cfg[\"tile_ic\"].size[-1]\n            in_channel_chunk = in_channel // in_channel_block\n            out_channel_block = cfg[\"tile_oc\"].size[-1]\n            out_channel_chunk = out_channel // out_channel_block\n            dshape = (batch, in_channel_chunk, in_height, in_width, in_channel_block)\n            data = tvm.te.placeholder(dshape, data.dtype, name=\"data\")\n            kshape = (out_channel_chunk, 1, filter_height, filter_width, 1, out_channel_block)\n            kernel = tvm.te.placeholder(kshape, kernel.dtype, name=\"kernel\")\n        else:\n            data, kernel = _pack_data(cfg, data, kernel)\n            _, _, _, _, in_channel_block = get_const_tuple(data.shape)\n            out_channel_chunk, _, _, _, _, out_channel_block = get_const_tuple(kernel.shape)\n\n    # padding stage\n    DOPAD = pad_top != 0 or pad_left != 0 or pad_down != 0 or pad_right != 0\n    if DOPAD:\n        pad_before = [0, 0, pad_top, pad_left, 0]\n        pad_after = [0, 0, pad_down, pad_right, 0]\n        data_pad = pad(data, pad_before, pad_after, name=\"PaddedInput\")\n    else:\n        data_pad = data\n\n    # depthconv stage\n    idxdiv = tvm.tir.indexdiv\n    idxmod = tvm.tir.indexmod\n\n    kh = te.reduce_axis((0, filter_height), name=\"kh\")\n    kw = te.reduce_axis((0, filter_width), name=\"kw\")\n    Output = te.compute(\n        (batch, out_channel_chunk, out_height, out_width, out_channel_block),\n        lambda b, oco, oh, ow, oci: te.sum(\n            (\n                data_pad[\n                    b,\n                    idxdiv(\n                        idxdiv(oco * out_channel_block + oci, channel_multiplier), in_channel_block\n                    ),\n                    oh * HSTR + kh * dh,\n                    ow * WSTR + kw * dw,\n                    idxmod(\n                        idxdiv(oco * out_channel_block + oci, channel_multiplier), in_channel_block\n                    ),\n                ].astype(out_dtype)\n                * kernel[oco, 0, kh, kw, 0, oci].astype(out_dtype)\n            ),\n            axis=[kh, kw],\n        ),\n        name=\"DepthwiseConv2d\",\n        tag=\"depthwise_conv2d_NCHWc\",\n    )\n    return Output\n\n\n@autotvm.register_topi_schedule(\"depthwise_conv2d_NCHWc.x86\")\ndef schedule_depthwise_conv2d_NCHWc(cfg, outs):\n    \"\"\"CPU schedule for depthwise conv2d in NCHW[x]c layout\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        if \"depthwise_conv2d_NCHWc\" in op.tag:\n            conv_out = op.output(0)\n            data = conv_out.op.input_tensors[0]\n            kernel = conv_out.op.input_tensors[1]\n            _schedule_depthwise_conv2d_NCHWc_impl(s, cfg, data, kernel, conv_out, outs[0])\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef _schedule_depthwise_conv2d_NCHWc_impl(s, cfg, data_vec, kernel_vec, conv_out, output):\n    tile_ow, oc_bn = cfg[\"tile_ow\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    unroll_kw = cfg[\"unroll_kw\"].val\n\n    # schedule pad\n    if isinstance(s[data_vec].op, tvm.te.ComputeOp) and \"pad\" in data_vec.op.tag:\n        batch, ic_chunk, ih, iw, ic_block = s[data_vec].op.axis\n        s[data_vec].vectorize(ic_block)\n        parallel_axis = s[data_vec].fuse(batch, ic_chunk, ih)\n        s[data_vec].parallel(parallel_axis)\n\n    C, O = conv_out, output\n    CC = s.cache_write(C, \"global\")\n\n    _, ic_chunk, oh, ow, ic_block = s[C].op.axis\n    ow_chunk, ow_block = s[C].split(ow, factor=tile_ow)\n    s[C].reorder(ic_chunk, oh, ow_chunk, ow_block, ic_block)\n    s[C].vectorize(ic_block)\n    parallel_axis = s[C].fuse(ic_chunk, oh)\n    s[C].parallel(parallel_axis)\n    s[CC].compute_at(s[C], ow_chunk)\n\n    # the ow axis in the cached block CC is the ow_block in C\n    _, ic_chunk, oh, ow, ic_block = s[CC].op.axis\n    kh, kw = s[CC].op.reduce_axis\n    s[CC].reorder(ic_chunk, oh, kh, kw, ow, ic_block)\n    if unroll_kw:\n        s[CC].unroll(kw)\n    s[CC].vectorize(ic_block)\n    s[CC].unroll(ow)\n\n    if C != O:\n        out_ndim = len(s[O].op.axis)\n        if out_ndim == 5:\n            batch, oc_chunk, oh, ow, oc_block = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=tile_ow)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n            parallel_axis = s[O].fuse(oc_chunk, oh)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        elif out_ndim == 4:\n            batch, oc, oh, ow = s[O].op.axis\n            ow_chunk, ow_block = s[O].split(ow, factor=tile_ow)\n            oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n            s[O].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n            parallel_axis = s[O].fuse(oc_chunk, oh)\n            s[C].compute_at(s[O], parallel_axis)\n            s[O].vectorize(oc_block)\n            s[O].parallel(parallel_axis)\n        else:\n            raise ValueError(\"Unsupported output ndim: %s\" % out_ndim)\n\n    return s\n\n\n@depthwise_conv2d_infer_layout.register(\"cpu\")\ndef _depthwise_conv2d_infer_layout(workload, cfg):\n    _, data, kernel, strides, padding, dilation, _, _, dtype = workload\n    batch_size, in_channel, in_height, in_width = data[1]\n    filter_channel, channel_multiplier, k_height, k_width = kernel[1]\n    out_channel = filter_channel * channel_multiplier\n    out_height = (in_height + padding[0] + padding[2] - k_height) // strides[0] + 1\n    out_width = (in_width + padding[1] + padding[3] - k_width) // strides[1] + 1\n    tile_ic, tile_oc = cfg[\"tile_ic\"].size[-1], cfg[\"tile_oc\"].size[-1]\n    in_shape = (batch_size, in_channel // tile_ic, in_height, in_width, tile_ic)\n    in_layout = \"NCHW%dc\" % tile_ic\n    out_shape = (batch_size, out_channel // tile_oc, out_height, out_width, tile_oc)\n    out_layout = \"NCHW%dc\" % tile_oc\n    return ((in_shape, in_layout),), ((out_shape, out_layout),)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n# pylint: disable=no-value-for-parameter,import-outside-toplevel\n\"\"\"Grouped Spatial Pack Convolution (Group Conv2D) schedule on x86\"\"\"\n\nimport tvm\nfrom tvm import autotvm\nfrom tvm import te\nfrom tvm.autotvm.task.space import SplitEntity, OtherOptionEntity\n\nfrom .utils import get_simd_32bit_lanes\nfrom ..utils import get_const_tuple\nfrom ..nn.pad import pad\nfrom .. import tag\n\nfrom ..nn.conv2d import _get_workload as _get_conv2d_workload\n\n\ndef group_conv2d_nchw(data, kernel, strides, padding, dilation, groups, out_dtype):\n    \"\"\"Compute group_conv2d with NCHW layout\"\"\"\n    return group_conv2d_nchw_spatial_pack(\n        data, kernel, strides, padding, dilation, groups, out_dtype\n    )\n\n\ndef schedule_group_conv2d_nchw(outs):\n    \"\"\"Compute group_conv2d with NCHW layout\"\"\"\n    return schedule_group_conv2d_nchwc(outs)\n\n\ndef _get_default_config(\n    cfg, data, kernel, strides, padding, dilation, groups, out_dtype, layout=\"NCHW\"\n):\n    \"\"\"\n    Get default schedule config for the workload\n    \"\"\"\n    static_data_shape = []\n    for dim in get_const_tuple(data.shape):\n        if isinstance(dim, tvm.tir.Var):\n            static_data_shape.append(1)\n        else:\n            static_data_shape.append(dim)\n    data = te.placeholder(static_data_shape, dtype=data.dtype)\n\n    wkl = _get_conv2d_workload(data, kernel, strides, padding, dilation, out_dtype, layout)\n    _fallback_schedule(cfg, wkl)\n\n\ndef _fallback_schedule(cfg, wkl):\n    simd_width = get_simd_32bit_lanes()\n    pad_left, pad_right = wkl.padl, wkl.padr\n    stride_w = wkl.stride_w\n    out_width = (wkl.width + pad_left + pad_right - wkl.kernel_w) // stride_w + 1\n    groups = wkl.groups\n    kernels_per_group = wkl.out_filter // groups\n    kernel_depth = wkl.in_filter // groups\n\n    oc_bn = 1\n\n    oc_bn = 1\n    for bn in range(simd_width, 0, -1):\n        if kernels_per_group % bn == 0:\n            oc_bn = bn\n            break\n    if oc_bn > kernels_per_group:\n        oc_bn = kernels_per_group\n\n    ic_bn = 1\n    for bn in range(oc_bn, 0, -1):\n        if kernel_depth % bn == 0:\n            ic_bn = bn\n            break\n    if ic_bn > kernel_depth:\n        ic_bn = kernel_depth\n\n    reg_n = 1\n    for n in range(31, 0, -1):\n        if out_width % n == 0:\n            reg_n = n\n            break\n\n    cfg[\"tile_ic\"] = SplitEntity([wkl.in_filter // ic_bn, ic_bn])\n    cfg[\"tile_oc\"] = SplitEntity([wkl.out_filter // oc_bn, oc_bn])\n    cfg[\"tile_ow\"] = SplitEntity([out_width // reg_n, reg_n])\n    cfg[\"unroll_kw\"] = OtherOptionEntity(False)\n\n\n@autotvm.register_topi_compute(\"group_conv2d_nchw.x86\")\ndef group_conv2d_nchw_spatial_pack(\n    cfg, data, kernel, strides, padding, dilation, groups, out_dtype=\"float32\"\n):\n    \"\"\"\n    Compute group conv2d with NCHW layout, using GSPC algorithm.\n    https://arxiv.org/abs/2006.09791\n    \"\"\"\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(dilation, int):\n        dilation_h, dilation_w = dilation, dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    assert isinstance(padding, int) or len(padding) == 2 or len(padding) == 4\n    if isinstance(padding, int):\n        pad_top, pad_left, pad_bottom, pad_right = padding, padding, padding, padding\n    elif len(padding) == 2:\n        hpad, wpad = padding\n        pad_top, pad_bottom = hpad, hpad\n        pad_left, pad_right = wpad, wpad\n    else:\n        pad_top, pad_left, pad_bottom, pad_right = padding\n\n    hpad = pad_top + pad_bottom\n    wpad = pad_left + pad_right\n\n    assert isinstance(strides, int) or len(strides) == 2\n    if isinstance(strides, int):\n        stride_h, stride_w = strides, strides\n    else:\n        stride_h, stride_w = strides\n\n    batch_size, in_channel, in_height, in_width = get_const_tuple(data.shape)\n    out_channel, kernel_depth, k_height, k_width = get_const_tuple(kernel.shape)\n\n    pad_height = in_height + pad_top + pad_bottom\n    pad_width = in_width + pad_left + pad_right\n\n    dilated_kernel_h = (k_height - 1) * dilation_h + 1\n    dilated_kernel_w = (k_width - 1) * dilation_w + 1\n    out_height = (in_height + pad_top + pad_bottom - dilated_kernel_h) // stride_h + 1\n    out_width = (in_width + pad_left + pad_right - dilated_kernel_w) // stride_w + 1\n\n    kernels_per_group = out_channel // groups\n\n    cfg.define_split(\"tile_ic\", in_channel, num_outputs=2)\n    cfg.define_split(\"tile_oc\", out_channel, num_outputs=2)\n    cfg.define_split(\"tile_ow\", out_width, num_outputs=2, filter=lambda y: y.size[-1] <= 64)\n    cfg.define_knob(\"unroll_kw\", [True, False])\n\n    # If no config was set, we can fallback to default config.\n    if cfg.is_fallback:\n        _get_default_config(\n            cfg,\n            te.placeholder((batch_size, in_channel, in_height, in_width), dtype=data.dtype),\n            te.placeholder(\n                (out_channel, in_channel // groups, k_height, k_width), dtype=kernel.dtype\n            ),\n            strides,\n            padding,\n            dilation,\n            groups,\n            out_dtype,\n        )\n\n    oc_bn = cfg[\"tile_oc\"].size[-1]\n    ic_bn = cfg[\"tile_ic\"].size[-1]\n\n    # pack data\n    DOPAD = hpad != 0 or wpad != 0\n    if DOPAD:\n        data_pad = pad(\n            data, (0, 0, pad_top, pad_left), (0, 0, pad_bottom, pad_right), name=\"data_pad\"\n        )\n    else:\n        data_pad = data\n\n    shape = (groups, batch_size, kernel_depth // ic_bn, pad_height, ic_bn, pad_width)\n\n    data_vec = te.compute(\n        shape,\n        lambda g, n, C, h, c, w: data_pad[n, C * ic_bn + c + kernel_depth * g, h, w],\n        name=\"data_vec\",\n    )\n\n    # pack kernel\n    shape = (\n        groups,\n        kernels_per_group // oc_bn,\n        kernel_depth // ic_bn,\n        k_height,\n        k_width,\n        ic_bn,\n        oc_bn,\n    )\n\n    kernel_vec = te.compute(\n        shape,\n        lambda g, out_channel, in_channel, h, w, ci, co: kernel[\n            (out_channel * oc_bn + co + g * kernels_per_group), in_channel * ic_bn + ci, h, w\n        ],\n        name=\"kernel_vec\",\n    )\n\n    # convolution\n    oshape = (groups, batch_size, kernels_per_group // oc_bn, out_height, out_width, oc_bn)\n    unpack_shape = (batch_size, out_channel, out_height, out_width)\n\n    ic = te.reduce_axis((0, (kernel_depth)), name=\"ic\")\n    kh = te.reduce_axis((0, k_height), name=\"kh\")\n    kw = te.reduce_axis((0, k_width), name=\"kw\")\n\n    idxmod = tvm.tir.indexmod\n    idxdiv = tvm.tir.indexdiv\n    conv = te.compute(\n        oshape,\n        lambda g, n, oc_chunk, oh, ow, oc_block: te.sum(\n            data_vec[\n                g,\n                n,\n                idxdiv(ic, ic_bn),\n                oh * stride_h + kh * dilation_h,\n                idxmod(ic, ic_bn),\n                ow * stride_w + kw * dilation_w,\n            ].astype(out_dtype)\n            * kernel_vec[\n                g, oc_chunk, idxdiv(ic, ic_bn), kh, kw, idxmod(ic, ic_bn), oc_block\n            ].astype(out_dtype),\n            axis=[ic, kh, kw],\n        ),\n        name=\"conv\",\n    )\n\n    unpack = te.compute(\n        unpack_shape,\n        lambda n, c, h, w: conv[\n            idxdiv(c, kernels_per_group),\n            n,\n            idxmod(idxdiv(c, oc_bn), (kernels_per_group // oc_bn)),\n            h,\n            w,\n            idxmod(idxmod(c, oc_bn), kernels_per_group),\n        ].astype(out_dtype),\n        name=\"output_unpack\",\n        tag=\"group_conv2d_nchw\",\n    )\n\n    return unpack\n\n\n@autotvm.register_topi_schedule(\"group_conv2d_nchw.x86\")\ndef schedule_group_conv2d_nchwc(cfg, outs):\n    \"\"\"Create schedule for tensors\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        \"\"\"Traverse operators from computation graph\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_broadcast(op.tag):\n            if op not in s.outputs:\n                s[op].compute_inline()\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n\n        if \"group_conv2d_nchw\" in op.tag:\n            output = op.output(0)\n\n            if \"tile_ic\" not in cfg:\n                return\n            conv_out = op.input_tensors[0]\n            kernel_vec = conv_out.op.input_tensors[1]\n            kernel = kernel_vec.op.input_tensors[0]\n            if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n                s[kernel].compute_inline()\n            data_vec = conv_out.op.input_tensors[0]\n            data = data_vec.op.input_tensors[0]\n            data_pad = None\n            if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n                data_pad = data\n                data = data_pad.op.input_tensors[0]\n\n            args = [s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, outs[0]]\n            _schedule_gspc_nchw(*args)\n\n        scheduled_ops.append(op)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef _schedule_gspc_nchw(s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, last):\n    \"\"\"Schedule GSPC\"\"\"\n    ic_bn, oc_bn, reg_n, unroll_kw = (\n        cfg[\"tile_ic\"].size[-1],\n        cfg[\"tile_oc\"].size[-1],\n        cfg[\"tile_ow\"].size[-1],\n        cfg[\"unroll_kw\"].val,\n    )\n\n    _, W = data, kernel_vec\n    A0, A1 = data_pad, data_vec\n\n    # schedule data\n    if (\n        data_pad is not None\n        and isinstance(data_pad.op, tvm.te.ComputeOp)\n        and \"pad\" in data_pad.op.tag\n    ):\n        s[A0].compute_inline()\n\n    groups, batch, ic_chunk, ih, ic_block, _ = s[A1].op.axis\n\n    parallel_axis = s[A1].fuse(batch, ic_chunk, ih)\n    s[A1].parallel(parallel_axis)\n\n    # schedule kernel pack\n    groups, oc_chunk, ic_chunk, oh, ow, ic_block, oc_block = s[W].op.axis\n    s[W].reorder(oc_chunk, oh, ic_chunk, ow, ic_block, oc_block)\n\n    if oc_bn > 1:\n        s[W].vectorize(oc_block)\n\n    parallel_axis = s[W].fuse(groups, oc_chunk, oh)\n    s[W].parallel(parallel_axis)\n\n    # schedule conv\n    C, O0, O = conv_out, output, last\n    CC = s.cache_write(C, \"global\")\n\n    _, _, oc_chunk, oh, ow, oc_block = s[C].op.axis\n\n    ow_chunk, ow_block = s[C].split(ow, factor=reg_n)\n\n    s[C].reorder(oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    s[C].fuse(oc_chunk, oh)\n    s[C].vectorize(oc_block)\n\n    groups, batch, oc_chunk, oh, ow, oc_block = s[CC].op.axis\n\n    ic, kh, kw = s[CC].op.reduce_axis\n    ow_chunk, ow_block = s[CC].split(ow, factor=reg_n)\n    ic_chunk, ic_block = s[CC].split(ic, factor=ic_bn)\n\n    if unroll_kw:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, ic_block, kw, ow_block, oc_block)\n        s[CC].unroll(kw)\n    else:\n        s[CC].reorder(oc_chunk, oh, ow_chunk, ic_chunk, kh, kw, ic_block, ow_block, oc_block)\n\n    parallel_axis = s[CC].fuse(groups, batch, oc_chunk, oh)\n\n    s[CC].parallel(parallel_axis)\n\n    s[CC].vectorize(oc_block)\n\n    s[CC].unroll(ow_block)\n\n    if O0 != O:\n        s[O0].compute_inline()\n\n    batch, oc, oh, ow = s[O].op.axis\n    ow_chunk, ow_block = s[O].split(ow, factor=reg_n)\n    oc_chunk, oc_block = s[O].split(oc, factor=oc_bn)\n\n    s[O].reorder(batch, oc_chunk, oh, ow_chunk, ow_block, oc_block)\n    parallel_axis = s[O].fuse(oc_chunk, oh)\n    s[O].vectorize(oc_block)\n    s[O].parallel(parallel_axis)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/injective.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"x86 declaration and schedules.\"\"\"\nfrom tvm import te\nfrom tvm.topi import tag\nfrom tvm.tir import IntImm\nfrom tvm.topi.generic.injective import (\n    schedule_injective_from_existing as schedule_injective_for_concat,\n)\nfrom ..utils import is_empty_shape\n\n\ndef schedule_injective_from_existing(sch, out):\n    \"\"\"Schedule for injective op from existing schedule.\n    Parameters\n    ----------\n    sch: Schedule\n         The schedule to update.\n    out: Tensor\n         The tensor representing the injective op.\n    Returns\n    -------\n    sch: Schedule\n         The updated schedule.\n    \"\"\"\n    if len(sch[out].op.axis) >= 5:\n        fused = sch[out].fuse(sch[out].op.axis[0], sch[out].op.axis[1], sch[out].op.axis[2])\n        sch[out].parallel(fused)\n    elif len(sch[out].op.axis) >= 3:\n        fused = sch[out].fuse(sch[out].op.axis[0], sch[out].op.axis[1])\n        sch[out].parallel(fused)\n    elif len(sch[out].op.axis) >= 1:\n        sch[out].parallel(sch[out].op.axis[0])\n\n    # Vectorize the inner most for loop. Tiling first to get a const extent\n    if len(sch[out].op.axis) >= 1:\n        l = sch[out].op.axis[-1]\n        lo, li = sch[out].split(l, factor=16)\n        sch[out].vectorize(li)\n\n        # for 1D loop, the above split will break the parallel axis\n        # Need to make the outer loop parallel again\n        if len(sch[out].op.axis) == 1:\n            sch[out].parallel(lo)\n\n    return sch\n\n\ndef schedule_injective(outs):\n    \"\"\"X86 schedule for injective op.\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    te.schedule.AutoInlineInjective(s)\n    for x in outs:\n        if not is_empty_shape(x.shape):\n            schedule_injective_from_existing(s, x)\n    return s\n\n\ndef schedule_concatenate(outs):\n    \"\"\"X86 schedule for concatenate op.\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n\n    def vectorize(sch, tensor, vectorize_limit):\n        \"\"\"Internal vectorization function for concatenate.\"\"\"\n        inner_axis = s[tensor].op.axis[len(s[tensor].op.axis) - 1]\n        # Check that the tensor shape is static. Otherwise skip vectorization.\n        if isinstance(tensor.shape[len(tensor.shape) - 1], IntImm):\n            inner_length = tensor.shape[len(tensor.shape) - 1].value\n            if inner_length <= vectorize_limit:\n                sch[tensor].vectorize(inner_axis)\n            else:\n                split_factor = 1\n                for i in range(vectorize_limit, 1, -1):\n                    if inner_length % i == 0:\n                        split_factor = i\n                        break\n                if split_factor > 1:\n                    _, inner_i = sch[tensor].split(inner_axis, split_factor)\n                    sch[tensor].vectorize(inner_i)\n\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    x = outs[0]\n    s = te.create_schedule([x.op for x in outs])\n    te.schedule.AutoInlineInjective(s)\n    if len(s[x].op.axis) >= 5:\n        fused = s[x].fuse(s[x].op.axis[0], s[x].op.axis[1], s[x].op.axis[2])\n        vectorize(s, x, 64)\n        s[x].parallel(fused)\n    elif len(s[x].op.axis) >= 3:\n        fused = s[x].fuse(s[x].op.axis[0], s[x].op.axis[1])\n        s[x].parallel(fused)\n    else:\n        s[x].parallel(s[x].op.axis[0])\n    return s\n\n\ndef schedule_concatenate_cpu(outs):\n    \"\"\"X86 schedule for concatenate op.\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description in the format\n          of an array of tensors.\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(op):\n        if tag.is_injective(op.tag):\n            schedule_injective_for_concat(s, op.output(0))\n\n        for tensor in op.input_tensors:\n            if tensor.op.input_tensors and tensor.op not in scheduled_ops:\n                traverse(tensor.op)\n        scheduled_ops.append(op)\n\n    for out in outs:\n        traverse(out.op)\n\n    return s\n\n\nschedule_elemwise = schedule_injective\nschedule_broadcast = schedule_injective\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/math_alter_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument,no-member\n\"\"\"Legalization transforms for math operations on x86\"\"\"\n\nimport logging\n\nfrom tvm import relay\nfrom ..math import erf_legalize\n\nlogger = logging.getLogger(\"topi\")\n\n\n@erf_legalize.register(\"cpu\")\ndef _erf_legalize(attrs, inputs, arg_types):\n    \"\"\"Legalizes ERF op if needed.\n\n    Parameters\n    ----------\n    attrs : tvm.ir.Attrs\n        Attributes of current convolution\n    inputs : list of tvm.relay.Expr\n        The args of the Relay expr to be legalized\n    types : list of types\n        List of input and output types\n\n    Returns\n    -------\n    result : tvm.relay.Expr\n        The legalized expr\n    \"\"\"\n    # Extract types and expressions.\n    data = inputs[0]\n    data_tensor = arg_types[0]\n    # Check if the input type is supported.\n    data_dtype = data_tensor.dtype\n    # If input is not fp32, we must cast to it.\n    if data_dtype != \"float32\":\n        data = relay.cast(data, \"float32\")\n        output = relay.erf(data)\n        return relay.cast(output, data_dtype)\n\n    # Otherwise do nothing.\n    return None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/nn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,unused-variable\n\"\"\"x86 nn operators\"\"\"\nfrom tvm import te\nfrom ..utils import traverse_inline\nfrom .injective import schedule_injective_from_existing\n\n\ndef _schedule_softmax(softmax_op, s, outs):\n    op_tag = softmax_op.tag\n    if op_tag == \"softmax_output\":\n        exp = softmax_op.input_tensors[0]\n        expsum = softmax_op.input_tensors[1]\n        max_elem = s[exp].op.input_tensors[1]\n        delta = None\n        axis = int(softmax_op.attrs[\"axis\"])\n    elif op_tag == \"fast_softmax_output\":\n        exp = softmax_op.input_tensors[0]\n        expsum = softmax_op.input_tensors[1]\n        delta = s[exp].op.input_tensors[0]\n        max_elem = s[delta].op.input_tensors[1]\n        axis = int(softmax_op.attrs[\"axis\"])\n    elif op_tag == \"log_softmax_output\":\n        exp = None\n        delta = None\n        max_elem = softmax_op.input_tensors[1]\n        expsum = softmax_op.input_tensors[2]\n        axis = int(softmax_op.attrs[\"axis\"])\n    else:\n        raise ValueError(\n            \"Tag is expected to be softmax_output or log_softmax_output. \\\n                         Got {0}\".format(\n                op_tag\n            )\n        )\n\n    output = outs[0]\n\n    def _schedule(output_op, softmax_op):\n        # only parallelize outer dimensions up to axis\n        outer_axes = [output_op.axis[i] for i in range(0, axis)]\n        fused_outer_axes = s[output_op].fuse(*outer_axes)\n        s[output_op].parallel(fused_outer_axes)\n\n        if softmax_op != output_op:\n            # fuse softmax output with following elemwise ops.\n            s[softmax_op].compute_at(s[output_op], fused_outer_axes)\n\n        # move computations with the same outer dimensions under the same root\n        s[max_elem].compute_at(s[output_op], fused_outer_axes)\n        s[expsum].compute_at(s[output_op], fused_outer_axes)\n\n        if delta is not None:\n            s[exp].compute_inline()\n            s[delta].compute_inline()\n        if exp is not None:\n            s[exp].compute_at(s[output_op], fused_outer_axes)\n\n    if list(output.shape) == list(softmax_op.output(0).shape):\n        _schedule(output.op, softmax_op)\n    else:\n        # This case can happen, for example, if the 4D input to softmax\n        # is in the NCHW layout while the fused elemwise op takes the NCHWc layout.\n        # Since we parallelize over outer axes up to the \"axis\" parameter of softmax,\n        # softmax and the fused op need to be in the same layout if we want to\n        # fuse them under the same parallel loop.\n        # This case can be removed if softmax supported AlterLayout.\n        schedule_injective_from_existing(s, output)\n        _schedule(softmax_op, softmax_op)\n\n\ndef schedule_softmax(outs):\n    \"\"\"Schedule for softmax\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of softmax\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if \"softmax\" in op.tag:\n            _schedule_softmax(op, s, outs)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\ndef schedule_batch_norm(outs):\n    \"\"\"Schedule for batch_norm\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of batch_norm\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    s = te.create_schedule([x.op for x in outs])\n    # only parallelize outer dimensions up to axis\n    output_op = outs[0].op\n    axis = output_op.axis\n    outer_axes = [output_op.axis[i] for i in range(0, len(axis) - 1)]\n    fused_outer_axes = s[output_op].fuse(*outer_axes)\n    s[output_op].parallel(fused_outer_axes)\n    # when scale or center is enabled\n    if \"divide\" not in output_op.name:\n        div = output_op.input_tensors[0]\n        substract = s[div].op.input_tensors[0]\n        s[div].compute_inline()\n        s[substract].compute_inline()\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable\n\"\"\"Schedule for pooling operators\"\"\"\nfrom tvm import te\nfrom .. import tag\n\n\ndef _parallel_sch(sch, oshape, do_vectorize=False):\n    def vectorize(fused_axis, num_parallel_axis, vectorize_limit=64):\n        \"\"\"Internal vectorization utility function.\"\"\"\n        reorder_axis = [fused_axis]\n        for i in range(num_parallel_axis, len(sch.op.axis) - 1):\n            reorder_axis.append(sch.op.axis[i])\n        k = sch.op.reduce_axis\n        fuse_k = sch.fuse(*k)\n        c = sch.op.axis[len(sch.op.axis) - 1]\n        reorder_axis += [fuse_k, c]\n        sch.reorder(*reorder_axis)\n        inner_length = oshape[len(oshape) - 1].value\n        if inner_length <= vectorize_limit:\n            sch.vectorize(c)\n        else:\n            split_factor = 1\n            for i in range(vectorize_limit, 1, -1):\n                if inner_length % i == 0:\n                    split_factor = i\n                    break\n            if split_factor > 1:\n                _, c_i = sch.split(c, split_factor)\n                sch.vectorize(c_i)\n\n    if len(sch.op.axis) >= 5:\n        fused = sch.fuse(sch.op.axis[0], sch.op.axis[1], sch.op.axis[2])\n        if do_vectorize:\n            vectorize(fused, 3)\n\n    elif len(sch.op.axis) >= 3:\n        fused = sch.fuse(sch.op.axis[0], sch.op.axis[1])\n        if do_vectorize:\n            vectorize(fused, 2)\n    else:\n        sch.parallel(sch.op.axis[0])\n        return\n    sch.parallel(fused)\n\n\ndef schedule_pool(outs, layout):\n    \"\"\"Schedule for pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of pool\n          in the format of an array of tensors.\n\n    layout: str\n        Data layout.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def _schedule(PaddedInput, Pool):\n        if isinstance(PaddedInput.op, te.tensor.ComputeOp):\n            s[PaddedInput].compute_inline()\n        do_vectorize = layout[-1] not in \"DHWdhw\"\n        _parallel_sch(s[Pool], outs[0].shape, do_vectorize)\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_injective(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule pool\n        elif OP.tag.startswith(\"pool\"):\n            # Average pool accumulation and division happens in different for loops (#3607).\n            # To ensure good parallel support, apply multi-threading on the second loop.\n            if OP != outs[0].op:\n                output = outs[0]\n                output_fused = s[output].fuse(output.op.axis[0], output.op.axis[1])\n                s[output].parallel(output_fused)\n\n            PaddedInput = OP.input_tensors[0]\n            Pool = OP.output(0)\n            _schedule(PaddedInput, Pool)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n\n\ndef schedule_adaptive_pool(outs):\n    \"\"\"Schedule for adaptive pool\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of adaptive pool\n          in the format of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse(OP):\n        \"\"\"Internal traverse function\"\"\"\n        # inline all one-to-one-mapping operators except the last stage (output)\n        if tag.is_injective(OP.tag):\n            if OP not in s.outputs:\n                s[OP].compute_inline()\n            for tensor in OP.input_tensors:\n                if isinstance(tensor.op, te.tensor.ComputeOp) and tensor.op not in scheduled_ops:\n                    traverse(tensor.op)\n        # schedule pool\n        elif OP.tag.startswith(\"adaptive_pool\"):\n            if OP != outs[0].op:\n                output = outs[0]\n                output_fused = s[output].fuse(output.op.axis[0], output.op.axis[1])\n                s[output].parallel(output_fused)\n\n            Pool = OP.output(0)\n            _parallel_sch(s[Pool], outs[0].shape)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % OP.tag)\n\n        scheduled_ops.append(OP)\n\n    traverse(outs[0].op)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"x86 declaration and schedules.\"\"\"\nimport tvm\nfrom tvm import te\nfrom .injective import schedule_injective_from_existing\nfrom .. import tag\nfrom ..utils import get_const_tuple\n\n\ndef _schedule_reduce(sch, op, is_idx_reduce=False):\n    if is_idx_reduce:\n        real_out = op.output(0)\n        fused = sch[real_out].fuse(*sch[real_out].op.axis)\n        out = op.input_tensors[0]\n    else:\n        out = op.output(0)\n\n    const_shape = True\n    out_shape = get_const_tuple(out.shape)\n    for d in out_shape:\n        if not isinstance(d, int):\n            const_shape = False\n            break\n\n    if const_shape:\n        naxes = len(sch[out].op.axis)\n        parallelism = 1\n        fuse_axes = []\n        # We choose a heuristic number 128 to limit the maximum parallelism\n        while len(fuse_axes) < naxes and parallelism < 128:\n            ivar = sch[out].op.axis[len(fuse_axes)]\n            parallelism *= int(ivar.dom.extent)\n            fuse_axes.append(ivar)\n        fused = sch[out].fuse(*fuse_axes)\n        sch[out].parallel(fused)\n    else:\n        if len(sch[out].op.axis) >= 5:\n            # avoid too many parallelism\n            fused = sch[out].fuse(sch[out].op.axis[0], sch[out].op.axis[1], sch[out].op.axis[2])\n            sch[out].parallel(fused)\n        else:\n            fused = sch[out].fuse(*sch[out].op.axis)\n            sch[out].parallel(fused)\n\n\ndef schedule_reduce(outs):\n    \"\"\"X86 schedule for reduction op.\n\n    Parameters\n    ----------\n    outs: Array of Tensor\n          The computation graph description of injective in the format\n          of an array of tensors.\n\n    Returns\n    -------\n    sch: Schedule\n        The computation schedule for the op.\n    \"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    sch = te.create_schedule([x.op for x in outs])\n    scheduled_ops = []\n\n    def traverse_before_reduce(operator):\n        \"\"\"Internal traverse function\"\"\"\n        if isinstance(operator, tvm.te.PlaceholderOp):\n            return\n        if tag.is_injective(operator.tag):\n            sch[operator].compute_inline()\n            for tensor in operator.input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        else:\n            raise RuntimeError(\"Unsupported operator: %s\" % operator.tag)\n\n        scheduled_ops.append(operator)\n\n    def traverse_after_reduce(operator):\n        \"\"\"Internal traverse function\"\"\"\n        if tag.is_broadcast(operator.tag):\n            if operator not in scheduled_ops:\n                schedule_injective_from_existing(sch, operator)\n            for tensor in operator.input_tensors:\n                traverse_after_reduce(tensor.op)\n        elif operator.tag == \"comm_reduce\":\n            _schedule_reduce(sch, operator, is_idx_reduce=False)\n            for tensor in operator.input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        elif operator.tag == \"comm_reduce_idx\":\n            _schedule_reduce(sch, operator, is_idx_reduce=True)\n            input_tensors = operator.input_tensors[0].op.input_tensors\n            for tensor in input_tensors:\n                if tensor.op not in scheduled_ops:\n                    traverse_before_reduce(tensor.op)\n        elif isinstance(operator, tvm.te.PlaceholderOp):\n            pass\n        else:\n            raise RuntimeError(\"Unsupported operator: %s (tag: %s)\" % (operator, operator.tag))\n\n        scheduled_ops.append(operator)\n\n    traverse_after_reduce(outs[0].op)\n    return sch\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/roi_align.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments, undefined-variable, too-many-nested-blocks, too-many-branches, too-many-statements\n\"\"\"Non-maximum suppression operator for intel cpu\"\"\"\nimport math\n\nimport tvm\nfrom tvm.te import hybrid\nfrom ..tensor import full\nfrom ..utils import get_const_tuple\n\n\n@hybrid.script\ndef roi_align_nchw_ir(\n    data, rois, num_rois, w_pc, pos_pc, pooled_size, spatial_scale, sample_ratio, mode\n):\n    \"\"\"Hybrid routing fo ROI align operator in NCHW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor or numpy NDArray\n        4-D with shape [batch, channel, height, width]\n\n    rois : tvm.te.Tensor or numpy NDArray\n        2-D with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    num_rois : tvm.tir.IntImm or tvm.tir.Var\n        Number of roi. We need to pass it in since hybrid script doesn't support\n        binding variable to symbolic dim.\n\n    w_pc : tvm.te.Tensor or numpy NDArray\n        3-D weight pre-calculation buffer\n\n    pos_pc : tvm.te.Tensor or numpy NDArray\n        3-D position pre-calculation buffer\n\n    pooled_size : tvm ConsExpr\n        [out_height, out_width]\n\n    spatial_scale : tvm.tir.const\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    sample_ratio : tvm.tir.const\n        Sampling ratio of ROI align, using adaptive size by default.\n\n    mode : tvm.tir.const\n        Mode of RoiAlign. A value of 0 corrensponds to b'avg', while a value of 1 corresponds to\n        b'max'.\n\n    Returns\n    -------\n    output : tvm.te.Tensor or numpy NDArray\n        4-D with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    channels = data.shape[1]\n    height = data.shape[2]\n    width = data.shape[3]\n    pooled_size_h = pooled_size[0]\n    pooled_size_w = pooled_size[1]\n    output = output_tensor((num_rois, channels, pooled_size_h, pooled_size_w), data.dtype)\n\n    for n in parallel(num_rois):\n        roi_batch_index = int32(rois[n, 0])\n        roi_start_w = rois[n, 1] * spatial_scale\n        roi_start_h = rois[n, 2] * spatial_scale\n        roi_end_w = rois[n, 3] * spatial_scale\n        roi_end_h = rois[n, 4] * spatial_scale\n\n        roi_h = max(roi_end_h - roi_start_h, 1.0)\n        roi_w = max(roi_end_w - roi_start_w, 1.0)\n\n        bin_h = roi_h / pooled_size_h\n        bin_w = roi_w / pooled_size_w\n\n        roi_bin_grid_h = sample_ratio\n        roi_bin_grid_w = roi_bin_grid_h\n        rounded_bin_h = int32(bin_h) * 1.0\n        rounded_bin_w = int32(bin_w) * 1.0\n        if sample_ratio <= 0:\n            # Cannot use ceil function since hybrid script\n            # doesn't support Call as indexing\n            roi_bin_grid_h = int32(bin_h)\n            roi_bin_grid_w = int32(bin_w)\n            if rounded_bin_h < bin_h:\n                roi_bin_grid_h += 1\n            if rounded_bin_w < bin_w:\n                roi_bin_grid_w += 1\n\n        count = roi_bin_grid_h * roi_bin_grid_w\n\n        # Pre-calculate indices and weights shared by all channels.\n        # This is the key point of optimization.\n        pre_calc_index = 0\n        iy_upper = roi_bin_grid_h\n        ix_upper = roi_bin_grid_w\n        for ph in range(pooled_size_h):\n            for pw in range(pooled_size_w):\n                for iy in range(iy_upper):\n                    yy = roi_start_h + ph * bin_h + (iy + 0.5) * bin_h / roi_bin_grid_h\n                    for ix in range(ix_upper):\n                        xx = roi_start_w + pw * bin_w + (ix + 0.5) * bin_w / roi_bin_grid_w\n                        x = xx\n                        y = yy\n                        if y < -1.0 or y > height or x < -1.0 or x > width:\n                            for i in range(4):\n                                w_pc[n, pre_calc_index, i] = 0.0\n                                pos_pc[n, pre_calc_index, i] = 0\n                        else:\n                            if y < 0.0:\n                                y = 0.0\n                            if x < 0.0:\n                                x = 0.0\n\n                            y_low = int32(y)\n                            x_low = int32(x)\n                            x_high = x_low + 1\n                            y_high = y_low + 1\n\n                            if y_low >= height - 1:\n                                y_high = height - 1\n                                y_low = y_high\n                                y = float32(y_low)\n\n                            if x_low >= width - 1:\n                                x_high = width - 1\n                                x_low = x_high\n                                x = float32(x_low)\n\n                            ly = y - y_low\n                            lx = x - x_low\n                            hy = 1.0 - ly\n                            hx = 1.0 - lx\n                            w1 = hy * hx\n                            w2 = hy * lx\n                            w3 = ly * hx\n                            w4 = ly * lx\n\n                            pos_pc[n, pre_calc_index, 0] = x_low\n                            pos_pc[n, pre_calc_index, 1] = x_high\n                            pos_pc[n, pre_calc_index, 2] = y_low\n                            pos_pc[n, pre_calc_index, 3] = y_high\n                            w_pc[n, pre_calc_index, 0] = w1\n                            w_pc[n, pre_calc_index, 1] = w2\n                            w_pc[n, pre_calc_index, 2] = w3\n                            w_pc[n, pre_calc_index, 3] = w4\n\n                        pre_calc_index += 1\n\n        for c in range(channels):\n            pre_calc_index = 0\n            for ph in range(pooled_size_h):\n                for pw in range(pooled_size_w):\n                    output_val = 0.0  # Avg mode\n                    if mode == 1:  # Max mode\n                        output_val = ninf(\"float32\")\n                    for iy in range(roi_bin_grid_h):\n                        for ix in range(roi_bin_grid_w):\n                            bilinear_val = (\n                                w_pc[n, pre_calc_index, 0]\n                                * data[\n                                    roi_batch_index,\n                                    c,\n                                    pos_pc[n, pre_calc_index, 2],\n                                    pos_pc[n, pre_calc_index, 0],\n                                ]\n                                + w_pc[n, pre_calc_index, 1]\n                                * data[\n                                    roi_batch_index,\n                                    c,\n                                    pos_pc[n, pre_calc_index, 2],\n                                    pos_pc[n, pre_calc_index, 1],\n                                ]\n                                + w_pc[n, pre_calc_index, 2]\n                                * data[\n                                    roi_batch_index,\n                                    c,\n                                    pos_pc[n, pre_calc_index, 3],\n                                    pos_pc[n, pre_calc_index, 0],\n                                ]\n                                + w_pc[n, pre_calc_index, 3]\n                                * data[\n                                    roi_batch_index,\n                                    c,\n                                    pos_pc[n, pre_calc_index, 3],\n                                    pos_pc[n, pre_calc_index, 1],\n                                ]\n                            )\n                            pre_calc_index += 1\n                            if mode == 0:  # Avg mode\n                                output_val += bilinear_val / count\n                            if mode == 1:  # Max mode\n                                output_val = max(output_val, bilinear_val)\n                        output[n, c, ph, pw] = output_val\n    return output\n\n\ndef roi_align_nchw(data, rois, pooled_size, spatial_scale, mode, sample_ratio=-1):\n    \"\"\"ROI align operator in NCHW layout.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        4-D with shape [batch, channel, height, width]\n\n    rois : tvm.te.Tensor\n        2-D with shape [num_roi, 5]. The last dimension should be in format of\n        [batch_index, w_start, h_start, w_end, h_end]\n\n    pooled_size : int or list/tuple of two ints\n        output size, or [out_height, out_width]\n\n    spatial_scale : float\n        Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal\n        of total stride in convolutional layers, which should be in range (0.0, 1.0]\n\n    mode : str\n        Mode of RoiAlign. Should be b'max' or b'avg'.\n\n    sample_ratio : int\n        Optional sampling ratio of ROI align, using adaptive size by default.\n\n    Returns\n    -------\n    output : tvm.te.Tensor\n        4-D with shape [num_roi, channel, pooled_size, pooled_size]\n    \"\"\"\n    if not isinstance(pooled_size, (tuple, list)):\n        pooled_size = (pooled_size, pooled_size)\n\n    # Pre-allocate intermediate buffer\n    if sample_ratio > 0:\n        max_roi_bin_grid_w = max_roi_bin_grid_h = sample_ratio\n    else:\n        _, _, height, width = get_const_tuple(data.shape)\n        max_roi_bin_grid_h = math.ceil(height / pooled_size[0])\n        max_roi_bin_grid_w = math.ceil(width / pooled_size[1])\n    num_rois = rois.shape[0]\n    max_pc_shape = (\n        rois.shape[0],\n        max_roi_bin_grid_h * max_roi_bin_grid_w * pooled_size[0] * pooled_size[1],\n        4,\n    )\n    w_pc_buffer = full(max_pc_shape, data.dtype, 0)\n    pos_pc_buffer = full(max_pc_shape, \"int32\", 0)\n\n    pooled_size = tvm.runtime.convert(pooled_size)\n    spatial_scale = tvm.tir.const(spatial_scale, \"float32\")\n    sample_ratio = tvm.tir.const(sample_ratio, \"int32\")\n    if mode in (b\"avg\", 0):\n        mode = tvm.tir.const(0, dtype=\"float32\")\n    elif mode in (b\"max\", 1):\n        mode = tvm.tir.const(1, dtype=\"float32\")\n    else:\n        raise ValueError(mode, \"Value %s passed in for mode not supported\", mode)\n\n    return roi_align_nchw_ir(\n        data,\n        rois,\n        num_rois,\n        w_pc_buffer,\n        pos_pc_buffer,\n        pooled_size,\n        spatial_scale,\n        sample_ratio,\n        mode,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/scatter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Scatter operators for x86\"\"\"\nimport tvm\nfrom tvm import te\nfrom ..scatter import _verify_scatter_nd_inputs\n\n\ndef scatter_nd(data, indices, updates, mode):\n    \"\"\"Scatter elements from a n-dimension array.\n\n    Given updates with shape (Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1}), indices with shape\n    (M, Y_0, ..., Y_{K-1}), and output copied from data with shape (X_0, X_1, ..., X_{N-1}),\n    scatter_nd computes\n\n    .. code-block::\n\n        output[indices[0, y_0, ..., y_{K-1}],\n               ...,\n               indices[M-1, y_0, ..., y_{K-1}],\n               x_M,\n               ...,\n               x_{N-1}\n              ] = f(output[...], updates[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}])\n\n    where the update function f is determinted by the mode.\n\n    Parameters\n    ----------\n    data : tvm.te.Tensor\n        The source array.\n\n    indices : tvm.te.Tensor\n        The indices of the values to extract.\n\n    updates : tvm.te.Tensor\n        The updates to apply at the Indices\n\n    mode : string\n        The update mode for the algorithm, either \"update\" or \"add\"\n        If update, the update values will replace the input data\n        If add, the update values will be added to the input data\n\n    Returns\n    -------\n    ret : tvm.te.Tensor\n    \"\"\"\n    _verify_scatter_nd_inputs(data, indices, updates)\n\n    def gen_ir(data_ptr, indices_ptr, updates_ptr, out_ptr):\n        # pylint: disable=invalid-name\n        ib = tvm.tir.ir_builder.create()\n\n        data = ib.buffer_ptr(data_ptr)\n        indices = ib.buffer_ptr(indices_ptr)\n        updates = ib.buffer_ptr(updates_ptr)\n        out = ib.buffer_ptr(out_ptr)\n\n        # We combine all the indices dimensions but the first one into a single\n        # dimension so we can iterate it in single loop instead of an arbitrary\n        # number of loops. We do the same thing for all the update dimensions.\n        fused_indices_dimension = 1\n        for i in indices_ptr.shape[1:]:\n            fused_indices_dimension *= i\n\n        fused_updates_dimension = 1\n        for i in updates_ptr.shape[len(indices_ptr.shape) - 1 :]:\n            fused_updates_dimension *= i\n\n        fused_shape = 1\n        for i in data_ptr.shape:\n            fused_shape *= i\n\n        with ib.for_range(0, fused_shape) as i:\n            out[i] = data[i]\n\n        with ib.for_range(0, fused_indices_dimension) as i:\n            with ib.for_range(0, fused_updates_dimension, kind=\"parallel\") as j:\n                offset = fused_updates_dimension\n                index = j  # This is x_M, .. x_{N-1} part of the index into out.\n                # Build up the indices[0, y_0, .. y_{K-1}], .. indices[M-1, y_0, .. y_{K-1}] part\n                # of the index into out.\n                for l in reversed(range(indices_ptr.shape[0].value)):\n                    # indices[i * l * fused_indices_dimension] = indices[l, y_0, ... y_{k-1}]\n                    index += offset * indices[i + l * fused_indices_dimension]\n                    offset *= data_ptr.shape[l]\n                if mode == \"update\":\n                    out[index] = updates[i * fused_updates_dimension + j]\n                elif mode == \"add\":\n                    out[index] += updates[i * fused_updates_dimension + j]\n                else:\n                    raise NotImplementedError(\"scatter_nd mode not in [update, add]:\", mode)\n\n        return ib.get()\n\n    out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, \"out_buf\")\n    return te.extern(\n        [data.shape],\n        [data, indices, updates],\n        lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0]),\n        dtype=data.dtype,\n        out_buffers=[out_buf],\n        name=\"scatter_nd_x86\",\n        tag=\"scatter_nd_x86\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"sparse_dense schedule on x86\"\"\"\nfrom functools import partial, reduce\nfrom tvm import te, tir, autotvm\n\nfrom ..transform import reshape\nfrom ..utils import traverse_inline, get_const_int\nfrom .utils import get_simd_32bit_lanes\n\n\ndef schedule_sparse_dense(outs):\n    \"\"\"Create schedule for sparse dense\"\"\"\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        simd_width = get_simd_32bit_lanes()\n        if op.tag == \"sparse_dense_sp_lhs_csrmm\" or op.tag == \"sparse_dense_sp_lhs_csrmm\":\n            (y_o, y_i) = s[op].split(s[op].op.axis[1], 2)\n            fused = s[op].fuse(s[op].op.axis[0], y_o)\n            s[op].parallel(fused)\n            s[op].vectorize(y_i)\n        elif op.tag == \"sparse_dense_sp_rhs_bsrmm\" or op.tag == \"sparse_dense_sp_rhs_bsrmm\":\n            y_bsrmm = op.input_tensors[0]\n            assert (\n                y_bsrmm.op.tag == \"sparse_dense_sp_rhs_bsrmm_block\"\n                or y_bsrmm.op.tag == \"sparse_dense_sp_lhs_bsrmm_block\"\n            )\n            y_reshape = op\n            (m, num_blocks, b_r) = s[y_bsrmm].op.axis\n            bs_r = get_const_int(b_r.dom.extent)\n            (elem_idx, c) = s[y_bsrmm].op.reduce_axis\n            s[y_bsrmm].reorder(num_blocks, m, elem_idx, b_r, c)\n            s[y_bsrmm].vectorize(b_r)\n            (m_o, n_o) = s[y_reshape].op.axis\n            (noo, noi) = s[y_reshape].split(n_o, bs_r)\n            s[y_bsrmm].compute_at(s[y_reshape], noi)\n            s[y_reshape].vectorize(noi)\n            if op != s[outs[0]].op:\n                (y_o, y_i) = s[outs[0].op].split(s[outs[0].op].op.axis[1], 2 * simd_width)\n                s[y_reshape].compute_at(s[outs[0]], y_o)\n                s[outs[0].op].parallel(y_o)\n                s[outs[0].op].vectorize(y_i)\n            else:\n                m_o_noo = s[y_reshape].fuse(m_o, noo)\n                s[y_reshape].parallel(m_o_noo)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3x3_spNHWC.x86\")\ndef spconv2d_3x3_nhwc(cfg, data, wdat, wind, wptr, layout=\"NHWC\"):\n    \"\"\"Sparse Conv2d 3x3 compute (NHWC).\"\"\"\n    assert layout == \"NHWC\"\n    nsamples, imh, imw, chanin = [i.value for i in data.shape]\n    nelems, bsrr, bsrc = [i.value for i in wdat.shape]\n    chanout = (wptr.shape[0].value - 1) * bsrr\n\n    imglen, chanlen = nsamples * imh * imw, 9 * chanin\n    cfg.define_split(\"tile_y\", imglen, num_outputs=3)\n    cfg.define_split(\"tile_x\", chanout // bsrr, num_outputs=2)\n    cfg.add_flop(imglen * (nelems * bsrc * bsrr * 2 - chanout))\n    if cfg.is_fallback:\n        cfg[\"tile_y\"] = autotvm.task.space.SplitEntity([-1, 160, 8])\n        cfg[\"tile_x\"] = autotvm.task.space.SplitEntity([-1, 4])\n\n    idxsplit = lambda x, y: reduce(lambda a, b: a[:-1] + [a[-1] % b, a[-1] // b], y, [x])\n\n    @partial(te.compute, (imglen, chanlen), name=\"Im2Col\")\n    def im2col(row, col):\n        j_w, j_h, j_n = idxsplit(row, [imw, imh])\n        j_c, k_w, k_h = idxsplit(col, [chanin, 3])\n        i_h, i_w = j_h + k_h - 1, j_w + k_w - 1\n        return tir.if_then_else(\n            tir.all(i_h >= 0, i_h < imh, i_w >= 0, i_w < imw), data[j_n, i_h, i_w, j_c], 0\n        )\n\n    @partial(te.compute, (imglen, chanout // bsrr, bsrr, bsrc), name=\"CC\")\n    def matmul(drow, wrow, brow, bcol):\n        row_start, row_end = wptr[wrow], wptr[wrow + 1]\n        elem_idx = te.reduce_axis((0, row_end - row_start), name=\"elem_idx\")\n        elem = row_start + elem_idx\n        return te.sum(\n            im2col[drow, wind[elem] * bsrc + bcol] * wdat[elem, brow, bcol], axis=elem_idx\n        )\n\n    sum_bsrc = te.reduce_axis((0, bsrc), name=\"k\")\n    ret = te.compute(\n        (imglen, chanout),\n        lambda y, x: te.sum(matmul[y, x // bsrr, x % bsrr, sum_bsrc], axis=sum_bsrc),\n        name=\"C\",\n        tag=\"conv3x3_spNHWC\",\n    )\n    return reshape(ret, (nsamples, imh, imw, chanout))\n\n\n@autotvm.register_topi_schedule(\"conv3x3_spNHWC.x86\")\ndef schedule_spconv2d_3x3_nhwc(cfg, outs):\n    \"\"\"Sparse Conv2d 3x3 schedule (NHWC).\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv3x3_spNHWC\":\n            (matmul,) = op.input_tensors\n            # wptr, wind, im2col, wdat\n            _, _, im2col, _ = matmul.op.input_tensors\n            (data,) = im2col.op.input_tensors\n            bsrr = matmul.shape[-2].value\n            chanin = data.shape[-1].value\n\n            mm_y, mm_x = s[op].op.axis\n            y_t, y_o, y_i = cfg[\"tile_y\"].apply(s, op, mm_y)\n            x_o, x_i = s[op].split(mm_x, factor=bsrr)\n            x_t, x_o = cfg[\"tile_x\"].apply(s, op, x_o)\n            (sum_ax,) = s[op].op.reduce_axis\n            s[op].reorder(y_t, x_t, y_o, x_o, y_i, x_i, sum_ax)\n            s[op].unroll(sum_ax)\n            s[op].vectorize(x_i)\n            s[op].unroll(y_i)\n\n            s[matmul].compute_at(s[op], x_o)\n            y_i, x_i, bsrr, bsrc = s[matmul].op.axis\n            (sum_ax,) = s[matmul].op.reduce_axis\n            s[matmul].reorder(x_i, sum_ax, y_i, bsrr, bsrc)\n            s[matmul].unroll(bsrc)\n            s[matmul].vectorize(bsrr)\n            s[matmul].unroll(y_i)\n\n            s[im2col].compute_at(s[op], y_o)\n            y_i, sum_ax = s[im2col].op.axis\n            _, k_i = s[im2col].split(sum_ax, factor=chanin)\n            s[im2col].vectorize(k_i)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n\n\n@autotvm.register_topi_compute(\"conv3x3_spNCHW.x86\")\ndef spconv2d_3x3_nchw(cfg, data, wdat, wind, wptr, layout=\"NCHW\"):\n    \"\"\"Sparse Conv2d 3x3 compute (NCHW).\"\"\"\n    nsamples, chanin, imgh, imgw = [i.value for i in data.shape]\n    nelems, veclen, bsrc = [i.value for i in wdat.shape]\n    chanout = (wptr.shape[0].value - 1) * veclen\n    assert bsrc == 1 and layout == \"NCHW\"\n\n    cfg.add_flop(nsamples * imgh * imgw * (nelems * veclen * bsrc * 2 - chanout))\n    cfg.define_split(\"tile_hw\", imgh * imgw, num_outputs=3)\n    cfg.define_split(\"tile_ckk\", chanin * 9, num_outputs=3)\n\n    @partial(te.compute, (nsamples, chanin * 3 * 3, imgh * imgw), name=\"im2col\")\n    def im2col(nsamples, ckk, imglen):\n        j_h, j_w = imglen // imgw, imglen % imgw\n        i_c, k_h, k_w = ckk // 9, ckk // 3 % 3, ckk % 3\n        i_h, i_w = j_h + k_h - 1, j_w + k_w - 1\n        return tir.if_then_else(\n            tir.all(i_h >= 0, i_h < imgh, i_w >= 0, i_w < imgw), data[nsamples, i_c, i_h, i_w], 0\n        )\n\n    @partial(\n        te.compute,\n        (nsamples, chanout // veclen, veclen, bsrc, imgh * imgw),\n        name=\"CC\",\n        tag=\"conv3x3_spNCHW\",\n    )\n    def matmul(nsamples, f_o, f_i, bsrk, imglen):\n        row_start, row_end = wptr[f_o], wptr[f_o + 1]\n        elem_idx = te.reduce_axis((0, row_end - row_start), name=\"elem_idx\")\n        elem = row_start + elem_idx\n        return te.sum(\n            im2col[nsamples, wind[elem] * bsrc + bsrk, imglen] * wdat[elem, f_i, bsrk],\n            axis=elem_idx,\n        )\n\n    return reshape(matmul, [nsamples, chanout, imgh, imgw])\n\n\n@autotvm.register_topi_schedule(\"conv3x3_spNCHW.x86\")\ndef schedule_spconv2d_3x3_nchw(cfg, outs):\n    \"\"\"Sparse Conv2d 3x3 schedule (NCHW).\"\"\"\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    s = te.create_schedule([x.op for x in outs])\n\n    def _callback(op):\n        if op.tag == \"conv3x3_spNCHW\":\n            # wptr, wind, im2col, wdat\n            _, _, im2col, _ = op.input_tensors\n\n            n_samples, f_o, f_i, b_c, imglen = s[op].op.axis\n            (sum_ax,) = s[op].op.reduce_axis\n            hw1, hw2, hw3 = cfg[\"tile_hw\"].apply(s, op, imglen)\n            s[op].reorder(n_samples, hw1, f_o, hw2, sum_ax, f_i, b_c, hw3)\n            s[op].unroll(f_i)\n            s[op].unroll(b_c)\n            s[op].vectorize(hw3)\n\n            s[im2col].compute_at(s[op], hw1)\n            n_samples, ckk, imglen = s[im2col].op.axis\n            ckk1, ckk2, ckk3 = cfg[\"tile_ckk\"].apply(s, im2col, ckk)\n            hw2, hw3 = s[im2col].split(imglen, factor=cfg[\"tile_hw\"].size[-1])\n            s[im2col].reorder(n_samples, ckk1, ckk2, hw2, ckk3, hw3)\n            s[im2col].unroll(ckk3)\n            s[im2col].vectorize(hw3)\n\n    traverse_inline(s, outs[0].op, _callback)\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/tensor_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Core kernel of dot product of 4 Int8 operations\"\"\"\n# pylint: disable=invalid-name\nimport tvm\nfrom tvm import te\nimport tvm.target.codegen\nfrom .utils import target_has_sse42, target_has_vnni, get_simd_32bit_lanes\n\n\ndef dot_16x1x16_uint8_int8_int32():\n    \"\"\"Dispatch the most optimized intrin depending on the target\"\"\"\n    mcpu = tvm.target.Target.current().mcpu\n\n    assert target_has_sse42(mcpu), \"An old Intel machine that does not have fast Int8 support.\"\n    if target_has_vnni(mcpu):\n        # VNNI capable platform\n        return dot_16x1x16_uint8_int8_int32_cascadelake()\n    # vpmaddubsw/vpmaddwd fallback\n    return dot_16x1x16_uint8_int8_int32_skylake()\n\n\ndef dot_16x1x16_uint8_int8_int32_skylake():\n    \"\"\"\n    Int8 dot product by every 4 elements using AVX512 Skylake instructions.\n    This function takes two arrays of uint8 and int8 datatype -- data[4] and\n    kernel[16][4] -- and computes a dot product of data[4] with every\n    4 elements of kernels, resulting in output[16] of int32 datatype.\n    The pseudo code is as follows.\n    .. code-block:: c\n        void dot_16x1x16_uint8_int8_int32(uint8 data[4], int8 kernel[16][4],\n                int32 output[16]){\n            for (int i = 0; i < 16; i++){\n                output[i] = 0;\n                for (int k = 0; k < 4; k++){\n                    output[i] += data[k] * kernel[i][k]\n                }\n            }\n        }\n\n    Physically, the kernel array sits in an AVX512 vector register and\n    the data[4] is broadcasted to another AVX512 vector register. This\n    function returns a TensorIntrin that can be used to tensorize\n    a schedule.\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Skylake int8 TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n\n    int32_lanes = get_simd_32bit_lanes()\n    num_int8_elements = 4  # 4 int8 elements in int32\n    data = te.placeholder((num_int8_elements,), dtype=\"uint8\", name=\"data\")\n    kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=\"int8\", name=\"kernel\")\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int32_lanes,),\n        lambda i: te.sum(data[k].astype(\"int32\") * kernel[i, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=\"uint8\", name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        kernel.shape, dtype=\"int8\", name=\"b_buffer\", offset_factor=1, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            # int_lx32 - output datatype after pmaddubs - 16 bits to number of lanes\n            # int_8xl - input datatype to pmaddubs - 8 bits to number of lanes\n            # int_32xl - output datatype after pmaddw - 32 bits per number of lanes\n\n            if int32_lanes == 4:\n                int_lx32 = \"int16x8\"\n                int_8xl = \"int8x16\"\n                int_32xl = \"int32x4\"\n                pmaddubs = \"llvm.x86.ssse3.pmadd.ub.sw.128\"\n                pmaddw = \"llvm.x86.sse2.pmadd.wd\"\n            elif int32_lanes == 8:\n                int_lx32 = \"int16x16\"\n                int_8xl = \"int8x32\"\n                int_32xl = \"int32x8\"\n                pmaddubs = \"llvm.x86.avx2.pmadd.ub.sw\"\n                pmaddw = \"llvm.x86.avx2.pmadd.wd\"\n            elif int32_lanes == 16:\n                int_lx32 = \"int16x32\"\n                int_8xl = \"int8x64\"\n                int_32xl = \"int32x16\"\n                pmaddubs = \"llvm.x86.avx512.pmaddubs.w.512\"\n                pmaddw = \"llvm.x86.avx512.pmaddw.d.512\"\n\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, int_32xl)))\n                return ib.get()\n\n            a_int8 = ins[0].vload([0], \"uint8x4\")\n            re_int32 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", a_int8)\n            vec_ai32 = re_int32.astype(int_32xl)\n            vec_a = tvm.tir.call_intrin(int_8xl, \"tir.reinterpret\", vec_ai32)\n            vec_b = ins[1].vload([0, 0], int_8xl)\n            vec_one = tvm.tir.const(1, int_lx32)\n            pair_reduction = tvm.tir.call_llvm_pure_intrin(\n                int_lx32,\n                pmaddubs,\n                tvm.tir.const(0, \"uint32\"),\n                vec_a,\n                vec_b,\n            )\n            quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                int_32xl,\n                pmaddw,\n                tvm.tir.const(0, \"uint32\"),\n                pair_reduction,\n                vec_one,\n            )\n            if index == 0:\n                ib.emit(outs[0].vstore(0, quad_reduction))\n            else:\n                ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], int_32xl)))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef dot_16x1x16_uint8_int8_int16():\n    \"\"\"\n    Int8 dot product by every 2 elements using AVX512 Skylake instructions.\n    This function takes two arrays of uint8 and int8 datatype -- data[2] and\n    kernel[4][32][2] -- and computes a dot product of data[2] with every\n    2 elements of kernels, resulting in output[4][32] of int16 datatype.\n    The pseudo code is as follows.\n    .. code-block:: c\n        void dot_16x1x16_uint8_int8_int16(uint8 data[2], int8 kernel[32*4][2],\n                int16 output[32*4]){\n            for (int i = 0; i< 4; i++){\n                for (int j = 0; j < 32; j++){\n                    output[i][i] = 0;\n                    for (int k = 0; k < 2; k++){\n                        output[i][j][k] += data[k] * kernel[i][j][k]\n                    }\n                }\n            }\n        }\n\n    Physically, the kernel array sits in four AVX512 vector registers and\n    the data[2] is broadcasted to another AVX512 vector register. This\n    function returns a TensorIntrin that can be used to tensorize\n    a schedule.\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Skylake int8 TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n\n    int16_lanes = 4 * 32  # 4*32 int32 lanes in 4 AVX512 vector registers\n    num_int8_elements = 2  # 2 int8 elements in int16\n    data = te.placeholder((num_int8_elements,), dtype=\"uint8\", name=\"data\")\n    kernel = te.placeholder((int16_lanes, num_int8_elements), dtype=\"int8\", name=\"kernel\")\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int16_lanes,),\n        lambda i: te.sum(data[k].astype(\"int16\") * kernel[i, k].astype(\"int16\"), axis=k),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=\"uint8\", name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(kernel.shape, dtype=\"int8\", name=\"b_buffer\", offset_factor=1)\n    # strides=[te.var('ldw'), 1, 1])\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                for i in range(4):\n                    ib.emit(outs[0].vstore([i * 32], tvm.tir.const(0, \"int16x32\")))\n                return ib.get()\n\n            a_int8 = ins[0].vload([0], \"uint8x2\")\n            re_int16 = tvm.tir.call_intrin(\"int16\", \"tir.reinterpret\", a_int8)\n            vec_ai16 = re_int16.astype(\"int16x32\")\n            vec_a = tvm.tir.call_intrin(\"int8x64\", \"tir.reinterpret\", vec_ai16)\n\n            for i in range(4):\n                vec_b = ins[1].vload([i * 32, 0], \"int8x64\")\n                pair_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int16x32\",\n                    \"llvm.x86.avx512.pmaddubs.w.512\",\n                    tvm.tir.const(0, \"uint32\"),\n                    vec_a,\n                    vec_b,\n                )\n                if index == 0:\n                    ib.emit(outs[0].vstore([i * 32], pair_reduction))\n                else:\n                    ib.emit(\n                        outs[0].vstore(\n                            [i * 32], pair_reduction + outs[0].vload([i * 32], \"int16x32\")\n                        )\n                    )\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n\n\ndef dot_16x1x16_uint8_int8_int32_cascadelake():\n    \"\"\"\n    Int8 dot product by every 4 elements using AVX512VNNI Cascade Lake instructions.\n    This function takes two arrays of uint8 and int8 datatype -- data[4] and\n    kernel[16][4] -- and computes a dot product of data[4] with every\n    4 elements of kernels, resulting in output[16] of int32 datatype.\n    The pseudo code is as follows.\n    .. code-block:: c\n        void dot_16x1x16_uint8_int8_int32_cascadelake(uint8 data[4], int8 kernel[16][4],\n                int32 output[16]){\n            for (int i = 0; i < 16; i++){\n                output[i] = 0;\n                for (int k = 0; k < 4; k++){\n                    output[i] += data[k] * kernel[i][k]\n                }\n            }\n        }\n\n    Physically, the kernel array sits in an AVX512 vector register and\n    the data[4] is broadcasted to another AVX512 vector register. This\n    function returns a TensorIntrin that can be used to tensorize\n    a schedule.\n\n    Returns\n    -------\n    intrin : TensorIntrin\n        The Cascade Lake int8 TensorIntrin that can be used in tensorizing schedule\n    \"\"\"\n\n    int32_lanes = 16  # 16 int32 lanes in AVX512\n    num_int8_elements = 4  # 4 int8 elements in int32\n    data = te.placeholder((num_int8_elements,), dtype=\"uint8\", name=\"data\")\n    kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=\"int8\", name=\"kernel\")\n    k = te.reduce_axis((0, num_int8_elements), name=\"k\")\n    C = te.compute(\n        (int32_lanes,),\n        lambda i: te.sum(data[k].astype(\"int32\") * kernel[i, k].astype(\"int32\"), axis=k),\n        name=\"C\",\n    )\n\n    a_buffer = tvm.tir.decl_buffer(\n        data.shape, dtype=\"uint8\", name=\"a_buffer\", offset_factor=1, strides=[1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        kernel.shape, dtype=\"int8\", name=\"b_buffer\", offset_factor=1, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def _intrin_func(ins, outs):\n        def _instr(index):\n            ib = tvm.tir.ir_builder.create()\n            if index == 1:\n                ib.emit(outs[0].vstore(0, tvm.tir.const(0, \"int32x16\")))\n                return ib.get()\n\n            a_int8 = ins[0].vload([0], \"uint8x4\")\n            re_int32 = tvm.tir.call_intrin(\"int32\", \"tir.reinterpret\", a_int8)\n            vec_ai32 = re_int32.astype(\"int32x16\")\n            vec_b = ins[1].vload([0, 0], \"int8x64\")\n\n            vnni_inst_name = \"llvm.x86.avx512.vpdpbusd.512\"\n            llvm_id = tvm.target.codegen.llvm_lookup_intrinsic_id(vnni_inst_name)\n\n            if llvm_id != 0:  # VNNI is available for current LLVM version\n                vec_bi32 = tvm.tir.call_intrin(\"int32x16\", \"tir.reinterpret\", vec_b)\n                vec_c = outs[0].vload([0], \"int32x16\")\n                quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int32x16\",\n                    \"llvm.x86.avx512.vpdpbusd.512\",\n                    tvm.tir.const(0, \"uint32\"),\n                    vec_c,\n                    vec_ai32,\n                    vec_bi32,\n                )\n                ib.emit(outs[0].vstore(0, quad_reduction))\n            else:  # Fall back to the normal AVX512\n                vec_a = tvm.tir.call_intrin(\"int8x64\", \"tir.reinterpret\", vec_ai32)\n                vec_one = tvm.tir.const(1, \"int16x32\")\n                pair_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int16x32\",\n                    \"llvm.x86.avx512.pmaddubs.w.512\",\n                    tvm.tir.const(0, \"uint32\"),\n                    vec_a,\n                    vec_b,\n                )\n                quad_reduction = tvm.tir.call_llvm_pure_intrin(\n                    \"int32x16\",\n                    \"llvm.x86.avx512.pmaddw.d.512\",\n                    tvm.tir.const(0, \"uint32\"),\n                    pair_reduction,\n                    vec_one,\n                )\n                if index == 0:\n                    ib.emit(outs[0].vstore(0, quad_reduction))\n                else:\n                    ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], \"int32x16\")))\n            return ib.get()\n\n        # body, reset, update\n        return _instr(0), _instr(1), _instr(2)\n\n    buffer_params = {\"offset_factor\": 1}\n    return te.decl_tensor_intrin(\n        C.op,\n        _intrin_func,\n        binds={data: a_buffer, kernel: b_buffer},\n        default_buffer_params=buffer_params,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/topi/x86/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common x86 related utilities\"\"\"\nimport tvm\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_sse41\")\ndef target_has_sse41(target):\n    return (\n        target_has_sse42(target)\n        or target_has_avx(target)\n        or target_has_avx2(target)\n        or target_has_avx512(target)\n        or target_has_vnni(target)\n        or target\n        in {\n            \"btver2\",\n            \"penryn\",\n        }\n    )\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_sse42\")\ndef target_has_sse42(target):\n    return (\n        target_has_avx(target)\n        or target_has_avx2(target)\n        or target_has_avx512(target)\n        or target_has_vnni(target)\n        or target\n        in {\n            \"silvermont\",\n            \"slm\",\n            \"goldmont\",\n            \"goldmont-plus\",\n            \"tremont\",\n            \"nehalem\",\n            \"corei7\",\n            \"westmere\",\n            \"bdver1\",\n            \"bdver2\",\n            \"bdver3\",\n            \"x86-64-v2\",\n        }\n    )\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_avx\")\ndef target_has_avx(target):\n    return (\n        target_has_avx2(target)\n        or target_has_avx512(target)\n        or target_has_vnni(target)\n        or target in {\"sandybridge\", \"corei7-avx\", \"ivybridge\", \"core-avx-i\"}\n    )\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_avx2\")\ndef target_has_avx2(target):\n    return (\n        target_has_avx512(target)\n        or target_has_vnni(target)\n        or target\n        in {\n            \"haswell\",\n            \"core-avx2\",\n            \"broadwell\",\n            \"skylake\",\n            \"bdver4\",\n            \"znver1\",\n            \"znver2\",\n            \"znver3\",\n            \"x86-64-v3\",\n        }\n    )\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_avx512\")\ndef target_has_avx512(target):\n    return target in {\n        \"skylake-avx512\",\n        \"skx\",\n        \"knl\",\n        \"knm\",\n        \"x86-64-v4\",\n        \"cannonlake\",\n        # explicit enumeration of VNNI capable due to collision with alderlake\n        \"cascadelake\",\n        \"icelake-client\",\n        \"icelake-server\",\n        \"rocketlake\",\n        \"tigerlake\",\n        \"cooperlake\",\n        \"sapphirerapids\",\n    }\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.target_has_vnni\")\ndef target_has_vnni(target):\n    return target in {\n        \"cascadelake\",\n        \"icelake-client\",\n        \"icelake-server\",\n        \"rocketlake\",\n        \"tigerlake\",\n        \"cooperlake\",\n        \"sapphirerapids\",\n        \"alderlake\",\n    }\n\n\n@tvm._ffi.register_func(\"tvm.topi.x86.utils.get_simd_32bit_lanes\")\ndef get_simd_32bit_lanes():\n    mcpu = tvm.target.Target.current().mcpu\n    fp32_vec_len = 4\n    if target_has_avx512(mcpu):\n        fp32_vec_len = 16\n    elif target_has_avx2(mcpu):\n        fp32_vec_len = 8\n    return fp32_vec_len\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/utils/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities operating at a graph/model or other \"high\" level\"\"\"\n\nfrom .roofline import roofline_analysis\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/utils/roofline/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for computing an approximate roofline model\"\"\"\nfrom typing import Dict, Optional, Union\n\nimport numpy as np\n\nfrom ... import IRModule, auto_scheduler, build, get_global_func, nd, relay, tir, topi, transform\nfrom ...contrib import utils\nfrom ...ir.expr import GlobalVar\nfrom ...ir.instrument import pass_instrument\nfrom ...rpc.base import RPC_SESS_MASK\nfrom ...rpc.client import RPCSession\nfrom ...runtime import Device, num_threads, profiler_vm, profiling\nfrom ...script import tir as T\nfrom ...target import Target\nfrom . import cuda, registry, x86\n\n\ndef _create_args(mod: IRModule, dev: Device, func_name: str = \"main\", remote=None):\n    if dev.device_type >= RPC_SESS_MASK:\n        random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n    else:\n        random_fill = get_global_func(\"tvm.contrib.random.random_fill\")\n    assert random_fill, \"Please make sure USE_RANDOM is ON in config.cmake\"\n    args = []\n    for arg in mod[func_name].params:\n        ary = nd.empty(\n            [x.value for x in arg.type_annotation.shape],\n            arg.type_annotation.dtype,\n            device=dev,\n        )\n        random_fill(ary)\n        args.append(ary)\n    return args\n\n\n@pass_instrument\nclass SaveLoweredTIR:\n    \"\"\"Save TIR functions from right before final lowering. Right now this\n    means right before tir.MakePackedAPI.\"\"\"\n\n    def __init__(self):\n        self.functions = {}\n\n    def run_before_pass(self, mod, info):\n        if info.name == \"tir.MakePackedAPI\":\n            for v, func in mod.functions.items():\n                if isinstance(func, tir.PrimFunc):\n                    self.functions[v] = func\n\n\ndef roofline_from_existing(\n    report: profiling.Report,\n    tir_functions: Dict[GlobalVar, tir.PrimFunc],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession] = None,\n) -> profiling.Report:\n    \"\"\"Add roofline and other estimated statistics to an existing profiling report.\n\n    :py:func:`roofline_analysis` should always be used instead of this function\n    unless you need a custom compilation pipeline.\n\n    Calculating roofline statistics requires features extracted the TIR\n    functions in addition to per-operator runtime information (`report`) of the\n    same TIR features. The features and TIR functions are not included with the\n    compiled library used to generate the per-operator runtime. It is essential\n    that the per-operator information comes from the exact same compilation\n    pipeline as the TIR functions.\n\n\n    Example\n    -------\n\n    ..code: : python\n\n        import tvm\n        import tvm.relay\n\n        mod, params = tvm.relay.testing.mlp.get_workload()\n\n        # it is recommended to use SaveLoweredTIR to get out the tir primfuncs\n        save_tir = tvm.utils.roofline.SaveLoweredTIR()\n        with tvm.transform.PassContext(opt_level=3, pass_instrument=[save_tir]):\n            lib = relay.vm.compile(mod, params=params, target=target)\n\n        vmexec = profiler_vm.VirtualMachineProfiler(lib, dev)\n        report = vmexec.profile(*inputs)\n\n        roofline_report = roofline_from_existing(report, save_tir.functions, target, dev)\n\n\n    Parameters\n    ----------\n    report : Report\n        Existing profiling report from :py:method:`VirtualMachineProfiler.profile`.\n    tir_functions : Dict[GlobalVar, PrimFunc]\n        TIR primfuncs from the module run to generate `report`. It is nessesary\n        that these functions come before the `tir.MakePackedAPI` pass and are\n        compatible with auto_scheduler featurization.\n        :py:class:`SaveLoweredTIR` is the recommended way to collect these\n        functions.\n    target : Target\n        TVM target that `report` was generated with.\n    dev : Device\n        Device that `report` was generated with.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n    profiling.Report\n        New profiling report that includes all information from `report`\n        along with additional roofline metrics. See\n        :py:func:`roofline_analysis` for more information on which metrics\n        are included.\n    \"\"\"\n\n    all_features = {\n        prim.attrs[\"hash\"]: (name, prim, auto_scheduler.feature.named_features_from_primfunc(prim))\n        for name, prim in tir_functions.items()\n        if isinstance(prim, tir.PrimFunc) and \"hash\" in prim.attrs.keys()\n    }\n\n    new_calls = []\n    for call in report.calls:\n        if \"Hash\" in call.keys() and call[\"Hash\"] in all_features:\n            _, prim, features = all_features[call[\"Hash\"]]\n\n            with target:\n                flops, peak_flops, flops_name = registry.estimate_peak_flops(\n                    prim, features, target, dev, remote\n                )\n                loaded_bytes, peak_bandwidth, bandwidth_name = registry.estimate_peak_bandwidth(\n                    prim, features, target, dev, remote\n                )\n            ridge_point = peak_flops / peak_bandwidth\n\n            runtime = call[\"Duration (us)\"].microseconds * 1e-6\n            arith_inten = flops / loaded_bytes\n            call = dict(call)\n            call[\"Loaded Bytes\"] = profiling.Count(int(loaded_bytes))\n            call[\"Estimated FLOPs\"] = profiling.Count(int(flops))\n            call[\"Arithmetic Intensity\"] = profiling.Ratio(arith_inten)\n            call[\"FLOP/s\"] = profiling.Ratio(flops / runtime)\n            call[\"Bandwidth\"] = profiling.Ratio(loaded_bytes / runtime)\n            compute_bound = arith_inten > ridge_point\n            call[\"Bound\"] = \"compute\" if compute_bound else \"memory\"\n            per_mem_bound = (loaded_bytes / runtime) / peak_bandwidth * 100\n            per_compute_bound = (flops / runtime) / peak_flops * 100.0\n            # We use ratio here because the percentages should be averaged instead of summed.\n            call[\"Percent of Theoretical Optimal\"] = profiling.Ratio(\n                per_compute_bound if compute_bound else per_mem_bound\n            )\n            new_calls.append(call)\n        else:\n            new_calls.append(call)\n    new_configuration = dict(report.configuration.items())\n    new_configuration[f\"Estimated Peak FLOP/s ({flops_name})\"] = profiling.Ratio(peak_flops)\n    new_configuration[\n        f\"Estimated Peak Bandwidth ({bandwidth_name}, byte/second)\"\n    ] = profiling.Ratio(peak_bandwidth)\n    return profiling.Report(new_calls, report.device_metrics, new_configuration)\n\n\ndef roofline_analysis(\n    mod: IRModule,\n    params: Dict[str, nd.NDArray],\n    target: Union[str, Target],\n    dev: Device,\n    remote: Optional[RPCSession] = None,\n) -> profiling.Report:\n    \"\"\"\n    Create a profiling report that contains roofline and other estimated\n    statistics from running a module on the VM.\n\n    The roofline model measures how close a operator gets to best possible\n    memory bandwidth or FLOP/s depending on whether it is memory or compute\n    bound. This computation uses the runtime of the operator along with two\n    numbers extracted from the TIR code: bytes of memory touched and number of\n    floating point operations.\n\n    These statistics are calculated by analyzing the lowered TIR of each\n    operator, so they are estimates of the true values. The statistics are:\n      - Bound: Is the operator memory or compute bound. This is computed by\n        assuming that the operator could perfectly cache all loads -- each byte\n        of memory is only loaded once.\n      - Percent of Theoretical Optimal: What percent of theoretical optimal for\n        the bound. i.e. percent of peak memory bandwidth if memory bound,\n        percent of peak FLOP/s if compute bound.\n      - Loaded Bytes: estimation of the number of bytes loaded from main memory.\n      - Estimated Flops: estimated number of floating point operations.\n      - Arithmetic Intensity: ratio of FLOPs per byte of data.\n      - FLOP/s: floating point operations per second.\n      - Bandwidth: Number of bytes loaded per second.\n\n    Parameters\n    ----------\n    mod : IRModule\n      Uncompiled input module\n\n    params : Dict[str, nd.NDArray]\n\n    target : Union[str, Target]\n      Target to run on.\n\n    dev : Device\n      Device to run on.\n\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n\n    report : profiling.Report\n      Profiling report which includes the estimated statistics.\n    \"\"\"\n    if isinstance(target, str):\n        target = Target(target)\n\n    save_tir = SaveLoweredTIR()\n    # copy existing context but add our instrument\n    pass_ctx = transform.PassContext.current()\n    with transform.PassContext(\n        opt_level=pass_ctx.opt_level,\n        required_pass=pass_ctx.required_pass,\n        disabled_pass=pass_ctx.disabled_pass,\n        instruments=list(pass_ctx.instruments) + [save_tir],\n        config=pass_ctx.config,\n    ):\n        lib = relay.vm.compile(mod, params=params, target=target)\n    # upload to remote if running over rpc\n    if dev.device_type >= RPC_SESS_MASK:\n        if remote is None:\n            raise RuntimeError(\"A RPCSession must be provided when using a remote device.\")\n        temp = utils.tempdir()\n        path = temp.relpath(\"roofline_lib.tar\")\n        lib.mod.export_library(path)\n        remote.upload(path)\n        lib = remote.load_module(\"roofline_lib.tar\")\n    vmexec = profiler_vm.VirtualMachineProfiler(lib, dev)\n\n    args = _create_args(mod, dev, remote=remote)\n    report = vmexec.profile(*args)\n\n    return roofline_from_existing(report, save_tir.functions, target, dev, remote=remote)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/utils/roofline/cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Estimation of peak flops and memory bandwidth for cuda devices\"\"\"\nimport functools\nimport re\nfrom typing import Dict, Optional, Tuple\n\nimport numpy as np\n\nfrom ... import build, nd, transform\nfrom ...contrib import nvcc, utils\nfrom ...rpc.base import RPC_SESS_MASK\nfrom ...rpc.client import RPCSession\nfrom ...runtime import Device\nfrom ...script import tir as T\nfrom ...target import Target\nfrom ...tir import PrimFunc\nfrom . import registry\n\n\n@functools.lru_cache(maxsize=None)\ndef estimate_peak_flops_tensorcore(\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n    mat_dtype: str = \"float16\",\n    acc_dtype: str = \"float32\",\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate the peak FLOP/s of a cuda device with tensorcores.\n\n    This estimate should only be used to compare with operators that can use\n    dense tensorcore mma instructions.\n\n    References\n    ----------\n    Wei Sun, Ang Li, Tong Geng, Sander Stuijk, Henk Corporaal: \"Dissecting\n    Tensor Cores via Microbenchmarks: Latency, Throughput and Numerical\n    Behaviors\", 2022; http://arxiv.org/abs/2206.02874\n    https://www.nvidia.com/content/PDF/nvidia-ampere-ga-102-gpu-architecture-whitepaper-v2.1.pdf\n\n    Parameters\n    ----------\n    target : Target\n        Target to run on. This should be as specific to the actual hardware as\n        possible.\n    dev : Device\n        Device to run on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n    mat_dtype : str\n        Dtype of matrices passed to mma instructions.\n    acc_dtype : str\n        Dtype of accumulator to use with mma instructions. Should be compatible\n        with `mat_dtype`.\n\n    Returns\n    -------\n    peak_flops : float\n        Approximate sustained FLOP/s of this target/device combo assuming\n        mma instructions. Addition and multiplications are each counted as\n        separate FLOPs.\n    \"\"\"\n\n    @T.prim_func\n    def peak_flops_tensorcore_tir(\n        inp: T.Buffer((16, 16), mat_dtype),\n        out: T.Buffer((16, 16), acc_dtype),\n        n: T.int32,\n        sms: T.int32,\n    ):\n        # pylint: disable=invalid-name, missing-function-docstring\n        A = T.alloc_buffer((16, 16), dtype=mat_dtype, scope=\"wmma.matrix_a\")\n        B = T.alloc_buffer((16, 16), dtype=mat_dtype, scope=\"wmma.matrix_b\")\n        C = T.alloc_buffer((16, 16), dtype=acc_dtype, scope=\"wmma.accumulator\")\n        for _ in T.thread_binding(sms, thread=\"blockIdx.x\"):\n            for _ in T.thread_binding(\n                8, thread=\"threadIdx.y\"\n            ):  # need 8 warps to get enough in-SM parallelism\n                for _ in T.thread_binding(32, thread=\"threadIdx.x\"):\n                    T.evaluate(\n                        T.tvm_load_matrix_sync(\n                            A.data,\n                            16,\n                            16,\n                            16,\n                            0,\n                            T.tvm_access_ptr(\n                                T.type_annotation(dtype=mat_dtype),\n                                inp.data,\n                                0,\n                                16,\n                                1,\n                                dtype=\"handle\",\n                            ),\n                            16,\n                            \"row_major\",\n                            dtype=\"handle\",\n                        )\n                    )\n                    T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, 0, dtype=\"handle\"))\n                    T.evaluate(T.tvm_fill_fragment(C.data, 16, 16, 16, 0, 0, dtype=\"handle\"))\n                    for _ in range(n):\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                C.data, 0, A.data, 0, B.data, 0, C.data, 0, dtype=\"handle\"\n                            )\n                        )\n                    T.evaluate(\n                        T.tvm_store_matrix_sync(\n                            C.data,\n                            16,\n                            16,\n                            16,\n                            0,\n                            T.tvm_access_ptr(\n                                T.type_annotation(dtype=acc_dtype),\n                                out.data,\n                                0,\n                                16,\n                                2,\n                                dtype=\"handle\",\n                            ),\n                            16,\n                            \"row_major\",\n                            dtype=\"handle\",\n                        )\n                    )\n\n    n = 100000\n    sms = dev.multi_processor_count\n    specialized = peak_flops_tensorcore_tir.specialize(\n        {peak_flops_tensorcore_tir.params[2]: n, peak_flops_tensorcore_tir.params[3]: sms}\n    )\n    with transform.PassContext(opt_level=3):\n        f = build(specialized, target=target)\n\n    # upload to remote if running over rpc\n    if dev.device_type >= RPC_SESS_MASK:\n        if remote is None:\n            raise RuntimeError(\"A RPCSession must be provided when using a remote device.\")\n        temp = utils.tempdir()\n        path = temp.relpath(\"peak_fma_flops.tar\")\n        f.export_library(path)\n        remote.upload(path)\n        f = remote.load_module(\"peak_fma_flops.tar\")\n\n    x = nd.empty((16, 16), dtype=mat_dtype, device=dev)\n    y = nd.empty((16, 16), dtype=acc_dtype, device=dev)\n    times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(x, y)\n    # each mma operation computes 16 x 16 x 16 FLOPs\n    return n * 16 * 16 * 16 * 2 * sms * 8 / times.min\n\n\n@registry.estimate_peak_flops.register(\"cuda\")\ndef estimate_peak_flops(\n    func: PrimFunc,  # pylint: disable=unused-argument\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate the peak FLOP/s of a cuda device.\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak flops for. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    target : Target\n        Target to run on. This should be as specific to the actual hardware as\n        possible.\n    dev : Device\n        Device to run on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n    flops : float\n        Estimated number of flops used by `func`.\n    peak_flops : float\n        Approximate sustained FLOP/s of this target/device combo. Addition and\n        multiplications are each counted as separate FLOPs.\n    name : str\n        Dtype/intrinsic used by `func` to achieve peak flops.\n    \"\"\"\n    assert nvcc.have_tensorcore(\n        dev.compute_version\n    ), \"CUDA roofline only works with devices that have tensorcores\"\n    flops = np.sum(\n        features[\"float_addsub\"]\n        + features[\"float_mul\"]\n        + features[\"float_mad\"] * 2\n        + features[\"float_divmod\"]\n    )\n    peak_flops = estimate_peak_flops_tensorcore(target, dev, remote)\n    return flops, peak_flops, \"float16 tensorcore\"\n\n\n@T.prim_func\ndef peak_bandwidth_tir(a: T.handle, b: T.handle, blocks: T.int32, warp_size: T.int32) -> None:\n    # pylint: disable=invalid-name, missing-function-docstring\n    N = T.var(\"int32\")\n    A = T.match_buffer(a, [blocks, N, 4, warp_size], \"float32\")\n    B = T.match_buffer(b, [blocks, 4, warp_size], \"float32\")\n    for i in T.thread_binding(blocks, \"blockIdx.x\"):\n        for k in T.serial(N):\n            for l in T.unroll(4):\n                # vectorized load is necessary to hit peak bandwidth\n                for j in T.thread_binding(warp_size, \"threadIdx.x\"):\n                    # += is necessary to introduce a data dependency for all\n                    # elements of A, preventing the backend from removing the\n                    # `k` loop and setting `k` to the loop extent.\n                    B[i, l, j] += A[i, k, l, j]\n\n\n@functools.lru_cache(maxsize=None)\ndef estimate_peak_bandwidth_global_mem(\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession] = None,\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate peak bandwidth of global memory. See estimate_peak_bandwidth\"\"\"\n    warp_size = dev.warp_size\n    # These sizes seem large enough to give the card time to hit a fixpoint on memory bandwidth\n    blocks = 1024\n    size = 1024\n\n    specialized = peak_bandwidth_tir.specialize(\n        {peak_bandwidth_tir.params[2]: blocks, peak_bandwidth_tir.params[3]: warp_size}\n    )\n    with transform.PassContext(opt_level=3):\n        f = build(specialized, target=target)\n\n    # upload to remote if running over rpc\n    if dev.device_type >= RPC_SESS_MASK:\n        if remote is None:\n            raise RuntimeError(\"A RPCSession must be provided when using a remote device.\")\n        temp = utils.tempdir()\n        path = temp.relpath(\"peak_bandwidth.tar\")\n        f.export_library(path)\n        remote.upload(path)\n        f = remote.load_module(\"peak_bandwidth.tar\")\n\n    a = nd.empty((blocks, size, 4, warp_size), dtype=\"float32\", device=dev)\n    b = nd.empty((blocks, 4, warp_size), dtype=\"float32\", device=dev)\n    times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(a, b)\n    return a.numpy().size * 4 / times.min  # 4 bytes per float32\n\n\n@registry.estimate_peak_bandwidth.register(\"cuda\")\ndef estimate_peak_bandwidth(\n    func: PrimFunc,  # pylint: disable=unused-argument\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession] = None,\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate peak memory bandwidth of a target/device combo.\n\n    Peak bandwidth is estimated by running a small experiment on the underlying\n    hardware. The peak bandwidth measurement assumes that vector instructions\n    are being used to load the data.\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak bandwidth for. Used to check if a specific\n        kind of memory could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind of\n        memory could be used with this function.\n    target : Target\n        Target to use for measurement. This target should be as specific to the\n        underlying hardware as possible.\n    dev : Device\n        Device to measure peak bandwidth on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n    loaded_bytes : float\n        Estimated bytes loaded by `func`.\n    peak_bandwidth : float\n        Peak memory bandwidth in bytes/seconds.\n    name : str\n        Name of the memory being used.\n    \"\"\"\n    # autoscheduler features do not take into account that 1.\n    # global and shared memory have very different performance\n    # characteristics -- both are included in the same bytes\n    # touched count 2. multiple threads accessing the same byte\n    # of memory does not use the same amount of bandwidth as\n    # multiple threads accessing different bytes of memory. We\n    # use unique bytes accessed here to avoid these two issues,\n    # but this does bias results towards being more compute\n    # bound.\n    loaded_bytes = sum(\n        [\n            np.sum(x)\n            for (k, x) in features.items()\n            if re.match(r\"^B[0-9]+\\.unique_bytes$\", k) is not None\n        ]\n    )\n    peak_bandwidth = estimate_peak_bandwidth_global_mem(target, dev, remote)\n    return loaded_bytes, peak_bandwidth, \"global\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/utils/roofline/registry.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Definition of generic functions for estimating peak flops and bandwidth\"\"\"\nfrom typing import Dict, Optional, Tuple\n\nimport numpy as np\n\nfrom ...rpc.client import RPCSession\nfrom ...runtime import Device\nfrom ...target import Target, generic_func\nfrom ...tir import PrimFunc\n\n\n@generic_func\ndef estimate_peak_bandwidth(\n    func: PrimFunc,\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession] = None,\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate peak memory bandwidth of a target/device combo.\n\n    Peak bandwidth is estimated by running a small experiment on the underlying\n    hardware. The peak bandwidth measurement assumes that vector instructions\n    are being used to load the data.\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak bandwidth for. Used to check if a specific\n        kind of memory could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind of\n        memory could be used with this function.\n    target : Target\n        Target to use for measurement. This target should be as specific to the\n        underlying hardware as possible.\n    dev : Device\n        Device to measure peak bandwidth on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n    loaded_bytes : float\n        Estimated bytes loaded by `func`.\n    peak_bandwidth : float\n        Peak memory bandwidth in bytes/seconds.\n    name : str\n        Name of the memory being used.\n    \"\"\"\n    raise NotImplementedError()\n\n\n@generic_func\ndef estimate_peak_flops(\n    func: PrimFunc,\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n) -> Tuple[float, float, str]:\n    \"\"\"\n    Estimate the maximum number of FLOP/s this target/device combo is capable\n    of reaching by running a test program. This is a generic function that\n    should be overridden for each target.\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak flops for. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    target : Target\n        Target to run on. This should be as specific to the actual hardware as\n        possible to make sure that LLVM generates the best vector code.\n    dev : Device\n        Device to run on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n\n    Returns\n    -------\n    flops : float\n        Estimated number of flops used by `func`.\n    peak_flops : float\n        Approximate sustained FLOP/s of this target/device combo assuming\n        vectorized FMA instructions. Each FMA operation counts as two FLOPs.\n    name : str\n        Dtype/intrinsic used by `func` to achieve peak flops.\n    \"\"\"\n    raise NotImplementedError()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "python/tvm/utils/roofline/x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Estimate peak flops and bandwidth for x86 devices\"\"\"\nimport functools\nimport re\nfrom typing import Dict, Optional, Tuple\n\nimport numpy as np\n\nfrom ... import build, get_global_func, nd, topi, transform\nfrom ...contrib import utils\nfrom ...rpc.base import RPC_SESS_MASK\nfrom ...rpc.client import RPCSession\nfrom ...runtime import DataType, Device, num_threads\nfrom ...script import tir as T\nfrom ...target import Target\nfrom ...tir import PrimFunc\nfrom . import registry\n\n\ndef _detect_vec_width_registers(\n    target: Target, vec_width: Optional[int], num_vector_registers: Optional[int]\n):\n    \"\"\"Get the vector width and number of vector registers for a target.\n\n    Parameters\n    ----------\n    target : Target\n        Target to detect vector width and registers for.\n    vec_width : Optional[int]\n        If None, try and detect vector width from target. Otherwise provided input is used.\n    num_vector_registers : Optional[int]\n        If None, try and number of vector registers from target. Otherwise provided input is used.\n\n    Returns\n    -------\n    vec_width: int\n        Width of a vector register on `target` in bytes.\n    num_vector_registers: int\n        Number of vector registers on `target`.\n    \"\"\"\n    if vec_width is None:\n        # Only implemented for x86 so far...\n        if (\n            str(target.kind) == \"llvm\"\n            and target.device_name == \"\"\n            and len(target.keys) == 1\n            and target.keys[0] == \"cpu\"\n        ):\n            with target:\n                vec_width = topi.x86.utils.get_simd_32bit_lanes() * 4  # in number of bytes\n        else:\n            raise RuntimeError(f\"Cannot determine vector width for target {target}\")\n    if num_vector_registers is None:\n        if target.device_name == \"\":  # indicates x86\n            num_vector_registers = 16  # Assuming for all platforms, probably wrong on older ones\n        else:\n            raise RuntimeError(f\"Cannot determine number of vector registers for target {target}\")\n    return vec_width, num_vector_registers\n\n\n@functools.lru_cache(maxsize=None)\ndef estimate_peak_fma_vector_flops(\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n    dtype: DataType,\n    vec_width: Optional[int] = None,\n    num_vector_registers: Optional[int] = None,\n):\n    \"\"\"Estimate peak flops assuming vector fma instructions and no explicit\n    intrinsics. See estimate_peak_fma_flops.\n    \"\"\"\n\n    @T.prim_func\n    def peakflops_fma_tir(\n        a: T.handle,\n        vec_width: T.int32,\n        iters: T.int32,\n        num_vector_registers: T.int32,\n        threads: T.int32,\n    ) -> None:\n        # pylint: disable=invalid-name, missing-function-docstring\n        A = T.match_buffer(a, [threads, num_vector_registers, vec_width], dtype)\n        for t in T.parallel(threads):\n            for _j in range(iters):\n                for l in T.unroll(num_vector_registers):\n                    # We want to use as few registers as possible, so we perform\n                    # all operations on the same element\n                    for k in T.vectorized(vec_width):\n                        A[t, l, k] = A[t, l, k] * A[t, l, k] + A[t, l, k]\n\n    vec_width, num_vector_registers = _detect_vec_width_registers(\n        target, vec_width, num_vector_registers\n    )\n    vec_width //= DataType(dtype).bits // 8\n    iters = 1000000\n    nthreads = num_threads()\n    specialized = peakflops_fma_tir.specialize(\n        {\n            peakflops_fma_tir.params[1]: vec_width,\n            peakflops_fma_tir.params[2]: iters,\n            peakflops_fma_tir.params[3]: num_vector_registers,\n            peakflops_fma_tir.params[4]: nthreads,\n        }\n    )\n    with transform.PassContext(opt_level=3):\n        f = build(specialized, target=target)\n\n    # upload to remote if running over rpc\n    if dev.device_type >= RPC_SESS_MASK:\n        if remote is None:\n            raise RuntimeError(\"A RPCSession must be provided when using a remote device.\")\n        temp = utils.tempdir()\n        path = temp.relpath(\"peak_fma_flops.tar\")\n        f.export_library(path)\n        remote.upload(path)\n        f = remote.load_module(\"peak_fma_flops.tar\")\n        random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n    else:\n        random_fill = get_global_func(\"tvm.contrib.random.random_fill\")\n    assert random_fill, \"Please make sure USE_RANDOM is ON in config.cmake\"\n\n    a = nd.empty((nthreads, num_vector_registers, vec_width), dtype=dtype, device=dev)\n    random_fill(a)\n    times = f.time_evaluator(f.entry_name, dev, repeat=100, number=1)(a)\n    flops = 2 * vec_width * num_vector_registers * nthreads * iters  # fma is two flops\n    return flops / times.min\n\n\n@registry.estimate_peak_flops.register(\"cpu\")\ndef estimate_peak_fma_flops(\n    func: PrimFunc,\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n    vec_width: Optional[int] = None,\n    num_vector_registers: Optional[int] = None,\n) -> Tuple[float, float, str]:\n    \"\"\"\n    Estimate the maximum number of FLOP/s this target/device combo is capable\n    of reaching by running a test program. This assumes vectorized FMA\n    (fused-multiply-add) instructions.\n\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak flops for. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind\n        intrinsic or dtype could be used with this function.\n    target : Target\n        Target to run on. This should be as specific to the actual hardware as\n        possible to make sure that LLVM generates the best vector code.\n    dev : Device\n        Device to run on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n    vec_width : Optional[int]\n        Vector width of SIMD units on the underlying hardware. Will try to\n        infer if no value is provided.\n    num_vector_registers : Optional[int]\n        Number of vector registers on the underlying hardware. Will try to\n        infer if no value is provided.\n\n    Returns\n    -------\n    flops : float\n        Estimated number of flops used by `func`.\n    peak_flops : float\n        Approximate sustained FLOP/s of this target/device combo assuming\n        vectorized FMA instructions. Each FMA operation counts as two FLOPs.\n    name : str\n        Dtype/intrinsic used by `func` to achieve peak flops.\n    \"\"\"\n    # assume that the first argument's dtype is the one we want\n    dtype = list(func.buffer_map.values())[0].dtype\n    if \"int\" in dtype:\n        flops = np.sum(\n            features[\"int_addsub\"]\n            + features[\"int_mul\"]\n            + features[\"int_mad\"] * 2\n            + features[\"int_divmod\"]\n        )\n    else:\n        flops = np.sum(\n            features[\"float_addsub\"]\n            + features[\"float_mul\"]\n            + features[\"float_mad\"] * 2\n            + features[\"float_divmod\"]\n        )\n    peak_flops = estimate_peak_fma_vector_flops(\n        target, dev, remote, dtype, vec_width, num_vector_registers\n    )\n    return flops, peak_flops, f\"{dtype} FMA\"\n\n\n@T.prim_func\ndef peak_bandwidth_tir(a: T.handle, b: T.handle, threads: T.int32, vec_width: T.int32) -> None:\n    # pylint: disable=invalid-name, missing-function-docstring\n    N = T.var(\"int32\")\n    A = T.match_buffer(a, [threads, N, 4, vec_width], \"float32\")\n    B = T.match_buffer(b, [threads, 4, vec_width], \"float32\")\n    # Parallelism is necessary to hit all cores/nodes\n    for i in T.parallel(threads):\n        for k in T.serial(N):\n            for l in T.unroll(4):\n                # vectorized load is necessary to hit peak bandwidth\n                for j in T.vectorized(vec_width):\n                    # += is necessary to introduce a data dependency for all\n                    # elements of A, preventing the backend from removing the\n                    # `k` loop and setting `k` to the loop extent.\n                    B[i, l, j] += A[i, k, l, j]\n\n\n@functools.lru_cache(maxsize=None)\ndef estimate_peak_bandwidth_dram(\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n    vec_width: Optional[int] = None,\n) -> float:\n    \"\"\"Estimate peak bandwidth for DRAM. See estimate_peak_bandwidth.\"\"\"\n    vec_width, _ = _detect_vec_width_registers(target, vec_width, 1)\n    specialized = peak_bandwidth_tir.specialize(\n        {\n            peak_bandwidth_tir.params[3]: vec_width,\n        }\n    )\n    with transform.PassContext(opt_level=3):\n        f = build(specialized, target=target)\n\n    # upload to remote if running over rpc\n    if dev.device_type >= RPC_SESS_MASK:\n        if remote is None:\n            raise RuntimeError(\"A RPCSession must be provided when using a remote device.\")\n        temp = utils.tempdir()\n        path = temp.relpath(\"peak_bandwidth.tar\")\n        f.export_library(path)\n        remote.upload(path)\n        f = remote.load_module(\"peak_bandwidth.tar\")\n        random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n    else:\n        random_fill = get_global_func(\"tvm.contrib.random.random_fill\")\n    assert random_fill, \"Please make sure USE_RANDOM is ON in config.cmake\"\n\n    threads = num_threads()\n    # Data size needs to be larger than last level of cache. We don't have a\n    # way of getting cache sizes, so this number should give us a large enough\n    # size.\n    size = 10**8 // (4 * threads * vec_width)\n    a = nd.empty((threads, size, 4, vec_width), dtype=\"float32\", device=dev)\n    random_fill(a)\n    b = nd.empty((threads, 4, vec_width), dtype=\"float32\", device=dev)\n    random_fill(b)\n    times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(a, b, threads)\n    return a.numpy().size * 4 / times.min  # 4 bytes per float32\n\n\n@registry.estimate_peak_bandwidth.register(\"cpu\")\ndef estimate_peak_bandwidth(\n    func: PrimFunc,  # pylint: disable=unused-argument\n    features: Dict[str, np.ndarray],\n    target: Target,\n    dev: Device,\n    remote: Optional[RPCSession],\n    vec_width: Optional[int] = None,\n) -> Tuple[float, float, str]:\n    \"\"\"Estimate peak memory bandwidth of a target/device combo.\n\n    Peak bandwidth is estimated by running a small experiment on the underlying\n    hardware. The peak bandwidth measurement assumes that vector instructions\n    are being used to load the data.\n\n    Parameters\n    ----------\n    func : PrimFunc\n        Function to estimate peak bandwidth for. Used to check if a specific\n        kind of memory could be used with this function.\n    features : Dict[str, np.ndarry]\n        Features extracted from `func`. Used to check if a specific kind of\n        memory could be used with this function.\n    target : Target\n        Target to use for measurement. This target should be as specific to the\n        underlying hardware as possible.\n    dev : Device\n        Device to measure peak bandwidth on.\n    remote : Optional[RPCSession]\n      Remote session used to upload artifacts for runtime evaluation. Must be\n      the same session used to create `dev`.\n    vec_width : Optional[int]\n        Vector unit width, determined from target if not supplied.\n\n    Returns\n    -------\n    loaded_bytes : float\n        Estimated bytes loaded by `func`.\n    peak_bandwidth : float\n        Peak memory bandwidth in bytes/seconds.\n    name : str\n        Name of the memory being used.\n    \"\"\"\n    # Ideally we'd be able to use this code to measure peak bandwidth of the\n    # different cache levels. If we could just generate load commands, then we\n    # could use those in a tight loop. Instead we need some code that is\n    # limited on the cache bandwidth. With the L1 cache we need an operation\n    # that has a very low arithmetic intensity and we haven't come up with one\n    # yet.\n    peak_bandwidth = estimate_peak_bandwidth_dram(target, dev, remote, vec_width)\n    loaded_bytes = sum(\n        [np.sum(x) for (k, x) in features.items() if re.match(r\"^B[0-9]+\\.bytes$\", k) is not None]\n    )\n    return loaded_bytes, peak_bandwidth, \"DRAM\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/compiler-ext/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse env_logger;\nuse tvm::export;\n\nfn diagnostics() -> Result<(), tvm::Error> {\n    tvm::ir::diagnostics::codespan::init()\n}\n\nexport!(diagnostics);\n\n#[no_mangle]\nextern \"C\" fn compiler_ext_initialize() -> i32 {\n    let _ = env_logger::try_init();\n    tvm_export(\"rust_ext\").expect(\"failed to initialize the Rust compiler extensions.\");\n    log::debug!(\"Loaded the Rust compiler extension.\");\n    return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/allocator.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::alloc::{self, Layout, LayoutError};\n\nconst DEFAULT_ALIGN_BYTES: usize = 4;\n\n#[derive(PartialEq, Eq)]\npub struct Allocation {\n    layout: Layout,\n    ptr: *mut u8,\n}\n\nimpl Allocation {\n    /// Allocates a chunk of memory of `size` bytes with optional alignment.\n    pub fn new(size: usize, align: Option<usize>) -> Result<Self, LayoutError> {\n        let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES);\n        let layout = Layout::from_size_align(size, alignment)?;\n        let ptr = unsafe { alloc::alloc(layout) };\n        if ptr.is_null() {\n            alloc::handle_alloc_error(layout);\n        }\n        Ok(Self { ptr, layout })\n    }\n\n    pub fn as_mut_ptr(&self) -> *mut u8 {\n        self.ptr\n    }\n\n    /// Returns the size of the Allocation in bytes.\n    pub fn size(&self) -> usize {\n        self.layout.size()\n    }\n\n    /// Returns the byte alignment of the Allocation.\n    pub fn align(&self) -> usize {\n        self.layout.align()\n    }\n\n    /// Returns a view of the Allocation.\n    pub fn as_slice(&self) -> &[u8] {\n        unsafe { std::slice::from_raw_parts(self.as_mut_ptr(), self.size()) }\n    }\n\n    /// Returns a mutable view of the Allocation.\n    pub fn as_mut_slice(&mut self) -> &mut [u8] {\n        unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.size()) }\n    }\n}\n\nimpl Drop for Allocation {\n    fn drop(&mut self) {\n        unsafe {\n            alloc::dealloc(self.ptr, self.layout);\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/array.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{convert::TryFrom, mem, os::raw::c_void, ptr, slice};\n\nuse ndarray;\nuse tvm_sys::{ffi::DLTensor, DataType, Device};\n\nuse crate::allocator::Allocation;\nuse crate::errors::ArrayError;\nuse std::alloc::LayoutError;\n\n/// A `Storage` is a container which holds `Tensor` data.\n#[derive(PartialEq)]\npub enum Storage<'a> {\n    /// A `Storage` which owns its contained bytes.\n    Owned(Allocation),\n\n    /// A view of an existing `Storage`.\n    View(&'a mut [u8], usize), // ptr, align\n}\n\nimpl<'a> Storage<'a> {\n    pub fn new(size: usize, align: Option<usize>) -> Result<Storage<'static>, LayoutError> {\n        Ok(Storage::Owned(Allocation::new(size, align)?))\n    }\n\n    pub fn as_mut_ptr(&self) -> *mut u8 {\n        match self {\n            Storage::Owned(alloc) => alloc.as_mut_ptr(),\n            Storage::View(slice, _) => slice.as_ptr() as *mut u8,\n        }\n    }\n\n    pub fn size(&self) -> usize {\n        match self {\n            Storage::Owned(alloc) => alloc.size(),\n            Storage::View(slice, _) => slice.len(),\n        }\n    }\n\n    pub fn align(&self) -> usize {\n        match self {\n            Storage::Owned(alloc) => alloc.align(),\n            Storage::View(_, align) => *align,\n        }\n    }\n\n    pub fn as_ptr(&self) -> *const u8 {\n        self.as_mut_ptr() as *const _\n    }\n\n    /// Returns a `Storage::View` which points to an owned `Storage::Owned`.\n    pub fn view(&self) -> Storage<'a> {\n        match self {\n            Storage::Owned(alloc) => Storage::View(\n                unsafe { slice::from_raw_parts_mut(alloc.as_mut_ptr(), self.size()) },\n                self.align(),\n            ),\n            Storage::View(slice, _) => Storage::View(\n                unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), slice.len()) },\n                self.align(),\n            ),\n        }\n    }\n\n    pub fn is_owned(&self) -> bool {\n        match self {\n            Storage::Owned(_) => true,\n            _ => false,\n        }\n    }\n\n    /// Returns an owned version of this storage via cloning.\n    pub fn to_owned(&self) -> Storage<'static> {\n        let s = Storage::new(self.size(), Some(self.align())).unwrap();\n        unsafe {\n            s.as_mut_ptr()\n                .copy_from_nonoverlapping(self.as_ptr(), self.size());\n        }\n        s\n    }\n\n    /// Returns a view of the stored data.\n    pub fn as_slice(&self) -> &[u8] {\n        match self {\n            Storage::Owned(alloc) => alloc.as_slice(),\n            Storage::View(slice, _) => &*slice,\n        }\n    }\n\n    /// Returns a mutable view of the stored data.\n    pub fn as_mut_slice(&mut self) -> &mut [u8] {\n        match self {\n            Storage::Owned(alloc) => alloc.as_mut_slice(),\n            Storage::View(slice, _) => slice,\n        }\n    }\n}\n\nimpl<'d, 's, T> From<&'d [T]> for Storage<'s> {\n    fn from(data: &'d [T]) -> Self {\n        let data = unsafe {\n            slice::from_raw_parts_mut(\n                data.as_ptr() as *const u8 as *mut u8,\n                data.len() * mem::size_of::<T>() as usize,\n            )\n        };\n        Storage::View(data, mem::align_of::<T>())\n    }\n}\n\n/// A n-dimensional array type which can be converted to/from `tvm::DLTensor` and `ndarray::Array`.\n/// `Tensor` is primarily a holder of data which can be operated on via TVM (via `DLTensor`) or\n/// converted to `ndarray::Array` for non-TVM processing.\n///\n/// # Examples\n///\n/// ```\n/// extern crate ndarray;\n/// use std::convert::TryInto;\n/// use tvm_graph_rt::{call_packed, DLTensor, ArgValue, RetValue, Tensor};\n///\n/// let mut a_nd: ndarray::Array1<f32> = ndarray::Array::from_vec(vec![1f32, 2., 3., 4.]);\n/// let mut a: Tensor = a_nd.into();\n/// let mut a_dl: DLTensor = (&mut a).into();\n///\n/// let tvm_fn = |args: &[ArgValue]| -> Result<RetValue, ()> { Ok(RetValue::default()) };\n/// call_packed!(tvm_fn, &mut a_dl);\n///\n/// // Array -> Tensor is mostly useful when post-processing TVM graph outputs.\n/// let mut a_nd: ndarray::ArrayD<f32> = a.try_into().unwrap();\n/// ```\n#[derive(PartialEq)]\npub struct Tensor<'a> {\n    /// The bytes which contain the data this `Tensor` represents.\n    pub(crate) data: Storage<'a>,\n    pub(crate) device: Device,\n    pub(crate) dtype: DataType,\n    pub(crate) shape: Vec<i64>,\n    // ^ not usize because `typedef int64_t tvm_index_t` in c_runtime_api.h\n    /// The `Tensor` strides. Can be `None` if the `Tensor` is contiguous.\n    pub(crate) strides: Option<Vec<usize>>,\n    pub(crate) byte_offset: isize,\n    /// The number of elements in the `Tensor`.\n    pub(crate) size: usize,\n}\n\nunsafe impl<'a> Send for Tensor<'a> {}\n\nimpl<'a> Tensor<'a> {\n    pub fn shape(&self) -> Vec<i64> {\n        self.shape.clone()\n    }\n\n    pub fn data(&self) -> &Storage {\n        &self.data\n    }\n\n    pub fn data_mut(&mut self) -> &'a mut Storage {\n        &mut self.data\n    }\n\n    /// Returns the data of this `Tensor` as a `Vec`.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the `Tensor` is not contiguous or does not contain elements of type `T`.\n    pub fn to_vec<T: 'static + std::fmt::Debug + Clone>(&self) -> Vec<T> {\n        assert!(self.is_contiguous());\n        assert!(self.dtype.is_type::<T>());\n        unsafe { slice::from_raw_parts(self.data.as_ptr() as *const T, self.size).to_vec() }\n    }\n\n    /// Returns `true` iff this `Tensor` is represented by a contiguous region of memory.\n    pub fn is_contiguous(&self) -> bool {\n        match self.strides {\n            None => true,\n            Some(ref strides) => {\n                // check that stride for each dimension is the\n                // product of all trailing dimensons' shapes\n                self.shape\n                    .iter()\n                    .zip(strides)\n                    .rfold(\n                        (true, 1),\n                        |(is_contig, expected_stride), (shape, stride)| {\n                            (\n                                is_contig && *stride == expected_stride,\n                                expected_stride * (*shape as usize),\n                            )\n                        },\n                    )\n                    .0\n            }\n        }\n    }\n\n    /// Returns a clone of this `Tensor`.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the `Tensor` is not contiguous or does not contain elements of type `T`.\n    pub fn copy(&mut self, other: &Tensor) {\n        assert!(\n            self.dtype == other.dtype && self.size == other.size,\n            \"Tensor shape/dtype mismatch.\"\n        );\n        assert!(\n      self.is_contiguous() && other.is_contiguous(),\n      \"copy currently requires contiguous tensors\\n`self.strides = {:?}` `other.strides = {:?}`\",\n      self.strides,\n      other.strides\n    );\n        unsafe {\n            self.data\n                .as_mut_ptr()\n                .offset(self.byte_offset as isize)\n                .copy_from_nonoverlapping(\n                    other.data.as_mut_ptr().offset(other.byte_offset),\n                    other.size * other.dtype.itemsize(),\n                );\n        }\n    }\n\n    /// Returns an owned version of this `Tensor` via cloning.\n    pub fn to_owned(&self) -> Tensor<'static> {\n        let t = Tensor {\n            data: self.data.to_owned(),\n            device: self.device,\n            dtype: self.dtype,\n            size: self.size,\n            shape: self.shape.clone(),\n            strides: None,\n            byte_offset: 0,\n        };\n        unsafe { mem::transmute::<Tensor<'a>, Tensor<'static>>(t) }\n    }\n\n    fn from_array_storage<'s, T, D: ndarray::Dimension>(\n        arr: &ndarray::Array<T, D>,\n        storage: Storage<'s>,\n        dtype_fn: fn(u8, u16) -> DataType,\n    ) -> Tensor<'s> {\n        let type_width = mem::size_of::<T>() as u8;\n\n        Tensor {\n            data: storage,\n            device: Device::default(),\n            dtype: dtype_fn(8 * type_width, 1),\n            size: arr.len(),\n            shape: arr.shape().iter().map(|&v| v as i64).collect(),\n            strides: Some(arr.strides().iter().map(|&v| v as usize).collect()),\n            byte_offset: 0,\n        }\n    }\n\n    pub fn as_dltensor(&self, flatten: bool) -> DLTensor {\n        assert!(!flatten || self.is_contiguous());\n        DLTensor {\n            data: unsafe { self.data.as_mut_ptr().offset(self.byte_offset) } as *mut c_void,\n            device: self.device.into(),\n            ndim: if flatten { 1 } else { self.shape.len() } as i32,\n            dtype: self.dtype.into(),\n            shape: if flatten {\n                &self.size as *const _ as *mut i64\n            } else {\n                self.shape.as_ptr()\n            } as *mut i64,\n            strides: if flatten || self.is_contiguous() {\n                ptr::null_mut()\n            } else {\n                self.strides.as_ref().unwrap().as_ptr()\n            } as *mut i64,\n            byte_offset: 0,\n            ..Default::default()\n        }\n    }\n}\n\n/// Conversions to `ndarray::Array` from `Tensor`, if the types match.\nmacro_rules! impl_ndarray_try_from_tensor {\n    ($type:ty, $dtype:expr) => {\n        impl<'t> TryFrom<Tensor<'t>> for ndarray::ArrayD<$type> {\n            type Error = ArrayError;\n            fn try_from(tensor: Tensor) -> Result<ndarray::ArrayD<$type>, Self::Error> {\n                if tensor.dtype != $dtype {\n                    return Err(ArrayError::IncompatibleDataType(tensor.dtype));\n                }\n                Ok(ndarray::Array::from_shape_vec(\n                    tensor\n                        .shape\n                        .iter()\n                        .map(|s| *s as usize)\n                        .collect::<Vec<usize>>(),\n                    tensor.to_vec::<$type>(),\n                )\n                .map_err(|_| ArrayError::ShapeError(tensor.shape.clone()))?)\n            }\n        }\n    };\n}\n\nmacro_rules! make_dtype_const {\n    ($name: ident, $cnst:expr) => {\n        pub const $name: DataType = $cnst;\n    };\n}\n\nmake_dtype_const!(DTYPE_INT32, DataType::int(32, 1));\nmake_dtype_const!(DTYPE_UINT32, DataType::uint(32, 1));\nmake_dtype_const!(DTYPE_FLOAT32, DataType::float(32, 1));\nmake_dtype_const!(DTYPE_FLOAT64, DataType::float(64, 1));\nimpl_ndarray_try_from_tensor!(i32, DTYPE_INT32);\nimpl_ndarray_try_from_tensor!(u32, DTYPE_UINT32);\nimpl_ndarray_try_from_tensor!(f32, DTYPE_FLOAT32);\nimpl_ndarray_try_from_tensor!(f64, DTYPE_FLOAT64);\n\nimpl<'a, 't> From<&'a Tensor<'t>> for DLTensor {\n    fn from(tensor: &'a Tensor<'t>) -> Self {\n        Tensor::as_dltensor(tensor, false /* flatten */)\n    }\n}\n\nimpl<'a, 't> From<&'a mut Tensor<'t>> for DLTensor {\n    fn from(tensor: &'a mut Tensor<'t>) -> Self {\n        Tensor::as_dltensor(tensor, false /* flatten */)\n    }\n}\n\nimpl<'a> From<DLTensor> for Tensor<'a> {\n    fn from(dlt: DLTensor) -> Self {\n        unsafe {\n            let dtype = DataType::from(dlt.dtype);\n            let shape = slice::from_raw_parts(dlt.shape, dlt.ndim as usize).to_vec();\n            let size = shape.iter().map(|v| *v as usize).product::<usize>() as usize;\n            let storage = Storage::from(slice::from_raw_parts(\n                dlt.data as *const u8,\n                dtype.itemsize() * size,\n            ));\n            Self {\n                data: storage,\n                device: Device::default(),\n                dtype,\n                size,\n                shape,\n                strides: if dlt.strides.is_null() {\n                    None\n                } else {\n                    Some(slice::from_raw_parts_mut(dlt.strides as *mut usize, size).to_vec())\n                },\n                byte_offset: dlt.byte_offset as isize,\n            }\n        }\n    }\n}\n\n/// `From` conversions to `Tensor` for owned or borrowed `ndarray::Array`.\n///\n/// # Panics\n///\n/// Panics if the ndarray is not contiguous.\nmacro_rules! impl_tensor_from_ndarray {\n    ($type:ty, $dtype_fn:expr) => {\n        impl<D: ndarray::Dimension> From<ndarray::Array<$type, D>> for Tensor<'static> {\n            fn from(arr: ndarray::Array<$type, D>) -> Self {\n                let storage = Storage::from(arr.as_slice().expect(\"NDArray must be contiguous\"));\n                Tensor::from_array_storage(&arr, storage.to_owned(), $dtype_fn)\n            }\n        }\n        impl<'a, D: ndarray::Dimension> From<&'a ndarray::Array<$type, D>> for Tensor<'a> {\n            fn from(arr: &'a ndarray::Array<$type, D>) -> Self {\n                let storage = Storage::from(arr.as_slice().expect(\"NDArray must be contiguous\"));\n                Tensor::from_array_storage(arr, storage, $dtype_fn)\n            }\n        }\n    };\n}\n\nimpl_tensor_from_ndarray!(f32, DataType::float);\nimpl_tensor_from_ndarray!(f64, DataType::float);\nimpl_tensor_from_ndarray!(i32, DataType::int);\nimpl_tensor_from_ndarray!(i64, DataType::int);\nimpl_tensor_from_ndarray!(u32, DataType::uint);\nimpl_tensor_from_ndarray!(u64, DataType::uint);\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/errors.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse thiserror::Error;\nuse tvm_sys::DataType;\n\n#[derive(Debug, Error)]\npub enum GraphFormatError {\n    #[error(\"Failed to parse graph with error: {0}\")]\n    Parse(#[source] serde_json::Error),\n    #[error(\"Failed to parse graph parameters with error: {0:?}\")]\n    Params(#[source] Option<nom::Err<(Vec<u8>, nom::error::ErrorKind)>>),\n    #[error(\"{0} is missing attribute: {1}\")]\n    MissingAttr(String, String),\n    #[error(\"Failed to parse graph attribute '{0}' with error: {1}\")]\n    InvalidAttr(String, #[source] std::num::ParseIntError),\n    #[error(\"Missing field: {0}\")]\n    MissingField(&'static str),\n    #[error(\"Invalid DLType: {0}\")]\n    InvalidDLType(String),\n    #[error(\"Unsupported Op: {0}\")]\n    UnsupportedOp(String),\n}\n\n#[derive(Debug, Error)]\n#[error(\"Function {0} not found\")]\npub struct FunctionNotFound(pub String);\n\n#[derive(Debug, Error)]\n#[error(\"Pointer {0:?} invalid when freeing\")]\npub struct InvalidPointer(pub *mut u8);\n\n#[derive(Debug, Error)]\npub enum ArrayError {\n    #[error(\"Cannot convert Tensor with dtype {0} to ndarray\")]\n    IncompatibleDataType(DataType),\n    #[error(\"Shape error when casting ndarray to TVM Array with shape {0:?}\")]\n    ShapeError(Vec<i64>),\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/graph.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    cmp, collections::HashMap, convert::TryFrom, error::Error, iter::FromIterator, mem, str,\n};\n\nuse itertools::izip;\nuse nom::{\n    character::complete::{alpha1, digit1},\n    complete, count, do_parse, length_count, map, named,\n    number::complete::{le_i32, le_i64, le_u16, le_u32, le_u64, le_u8},\n    opt, tag, take, tuple, Err as NomErr,\n};\nuse serde::{Deserialize, Serialize};\nuse serde_json;\n\nuse tvm_sys::ffi::{DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDataTypeCode_kDLUInt};\n\nuse tvm_sys::{ffi::DLTensor, ArgValue, DataType, Device, DeviceType};\n\nuse crate::{errors::*, Module, Storage, Tensor};\n\n// @see `kTVMNDArrayMagic` in `ndarray.h`\nconst _NDARRAY_MAGIC: u64 = 0xDD5E_40F0_96B4_A13F;\n// @see `kTVMNDArrayListMagic` in `graph_executor.h`\nconst _NDARRAY_LIST_MAGIC: u64 = 0xF7E5_8D4F_0504_9CB7;\n\n/// A TVM computation graph.\n///\n/// # Examples\n///\n/// ```no_run\n/// use tvm_graph_rt::Graph;\n/// use std::convert::TryFrom;\n/// let graph_json = std::fs::read_to_string(\"graph.json\").unwrap();\n/// let graph = Graph::try_from(&graph_json).unwrap();\n/// ```\n#[derive(Serialize, Deserialize, Debug)]\npub struct Graph {\n    pub nodes: Vec<Node>,\n    pub arg_nodes: Vec<usize>,\n    pub heads: Vec<Entry>,\n    pub node_row_ptr: Option<Vec<usize>>,\n    pub attrs: Option<HashMap<String, serde_json::Value>>,\n}\n\n#[derive(Serialize, Deserialize, Debug)]\npub struct Entry {\n    pub id: usize,\n    pub index: usize,\n    pub version: usize,\n}\n\nimpl Graph {\n    fn entry_index(&self, entry: &Entry) -> Result<usize, GraphFormatError> {\n        self.node_row_ptr\n            .as_ref()\n            .map(|nrp| nrp[entry.id] + entry.index)\n            .ok_or_else(|| GraphFormatError::MissingField(\"node_row_ptr\"))\n    }\n\n    /// Attempt to deserialize a JSON attribute to a type `T`.\n    fn get_attr<T: serde::de::DeserializeOwned>(&self, attr: &str) -> Result<T, GraphFormatError> {\n        Ok(serde_json::from_value::<T>(\n            self.attrs\n                .as_ref()\n                .ok_or(GraphFormatError::MissingField(\"attrs\"))?\n                .get(attr)\n                .ok_or_else(|| {\n                    GraphFormatError::MissingAttr(\"graph\".to_string(), attr.to_string())\n                })?\n                .to_owned(),\n        )\n        .map_err(|err| GraphFormatError::Parse(err.into()))?)\n    }\n}\n\n#[derive(Serialize, Deserialize, Debug)]\npub struct Node {\n    pub op: String,\n    pub name: String,\n    pub inputs: Vec<Entry>,\n    pub attrs: Option<HashMap<String, String>>,\n    pub control_deps: Option<Vec<Entry>>,\n}\n\nstruct NodeAttrs {\n    func_name: String,\n    num_outputs: usize,\n    flatten_data: bool,\n}\n\nmacro_rules! get_node_attr {\n    ($node:expr, $attrs:ident, $attr:literal) => {\n        $attrs\n            .get($attr)\n            .ok_or_else(|| GraphFormatError::MissingAttr($node.to_owned(), $attr.to_owned()))\n    };\n}\n\nimpl Node {\n    fn parse_attrs(&self) -> Result<NodeAttrs, GraphFormatError> {\n        let attrs = self\n            .attrs\n            .as_ref()\n            .ok_or_else(|| GraphFormatError::MissingAttr(self.name.clone(), \"attrs\".to_owned()))?;\n\n        let func_name = get_node_attr!(self.name, attrs, \"func_name\")?.to_owned();\n\n        let num_outputs = get_node_attr!(self.name, attrs, \"num_outputs\")?\n            .parse::<usize>()\n            .map_err(|error| GraphFormatError::InvalidAttr(\"num_outputs\".to_string(), error))?;\n\n        let flatten_data = get_node_attr!(self.name, attrs, \"flatten_data\")?\n            .parse::<u8>()\n            .map(|val| val == 1)\n            .map_err(|error| GraphFormatError::InvalidAttr(\"flatten_data\".to_string(), error))?;\n\n        Ok(NodeAttrs {\n            func_name,\n            num_outputs,\n            flatten_data,\n        })\n    }\n}\n\nimpl<'a> TryFrom<&'a String> for Graph {\n    type Error = GraphFormatError;\n    fn try_from(graph_json: &String) -> Result<Self, GraphFormatError> {\n        serde_json::from_str(graph_json).map_err(|error| GraphFormatError::Parse(error))\n    }\n}\n\nimpl<'a> TryFrom<&'a str> for Graph {\n    type Error = GraphFormatError;\n    fn try_from(graph_json: &'a str) -> Result<Self, Self::Error> {\n        serde_json::from_str(graph_json).map_err(|error| GraphFormatError::Parse(error))\n    }\n}\n\n/// A executor for a TVM computation graph.\n///\n/// # Examples\n///\n/// ```no_compile\n/// use ndarray::Array;\n///\n/// let syslib = SystemLibModule::default(); // a provider of TVM functions\n///\n/// let mut params_bytes = Vec::new();\n/// fs::File::open(\"graph.params\").unwrap().read_to_end(&mut params_bytes).unwrap();\n/// let params = tvm::runtime::load_param_dict(&params_bytes).unwrap();\n///\n/// let graph = Graph::try_from(&fs::read_to_string(\"graph.json\").unwrap()).unwrap();\n///\n/// let mut exec = GraphExecutor::new(graph, &syslib).unwrap();\n/// exec.load_params(params);\n///\n/// let x = Array::from_vec(vec![1f32, 2., 3., 4.]);\n/// exec.set_input(\"data\", x.into());\n/// exec.run();\n/// let output = exec.get_output(0).unwrap();\n///\n/// println!(\"{:#?}\", Array::try_from(output).unwrap());\n/// ```\npub struct GraphExecutor<'m, 't> {\n    graph: Graph,\n    op_execs: Vec<Box<dyn Fn() + 'm>>,\n    tensors: Vec<Tensor<'t>>,\n}\n\nunsafe impl<'m, 't> Send for GraphExecutor<'m, 't> {}\n\nimpl<'m, 't> GraphExecutor<'m, 't> {\n    pub fn new<M: 'm + Module>(graph: Graph, lib: &'m M) -> Result<Self, Box<dyn Error>> {\n        let tensors = Self::setup_storages(&graph)?;\n        Ok(GraphExecutor {\n            op_execs: Self::setup_op_execs(&graph, lib, &tensors)?,\n            tensors,\n            graph,\n        })\n    }\n\n    /// Runs the computation graph.\n    pub fn run(&mut self) {\n        self.op_execs.iter().for_each(|op_exec| {\n            op_exec();\n        });\n    }\n\n    /// Allocates `Storages` for each `storage_id` and returns `Tensor`s to hold each output.\n    fn setup_storages<'a>(graph: &'a Graph) -> Result<Vec<Tensor<'t>>, Box<dyn Error>> {\n        let storage_ids = graph.get_attr::<(String, Vec<usize>)>(\"storage_id\")?.1;\n        let shapes = graph.get_attr::<(String, Vec<Vec<i64>>)>(\"shape\")?.1;\n        let dtypes = graph\n            .get_attr::<(String, Vec<String>)>(\"dltype\")?\n            .1\n            .iter()\n            .map(|dltype| {\n                if let Ok((_, dtype)) = tvm_str_to_type(dltype) {\n                    Ok(dtype)\n                } else {\n                    Err(GraphFormatError::InvalidDLType(dltype.to_string()))\n                }\n            })\n            .collect::<Result<Vec<DataType>, GraphFormatError>>()?;\n\n        let align = dtypes.iter().map(|dtype| dtype.bits() as usize).max();\n        let mut storage_num_bytes = vec![0usize; *storage_ids.iter().max().unwrap_or(&1) + 1];\n        for (i, &storage_id) in storage_ids.iter().enumerate() {\n            let dtype_size = (dtypes[i].bits() * dtypes[i].lanes()) >> 3;\n            let nbytes = dtype_size * shapes[i].iter().product::<i64>() as usize;\n            storage_num_bytes[storage_id] = cmp::max(nbytes, storage_num_bytes[storage_id]);\n        }\n\n        let mut storages: Vec<Storage> = storage_num_bytes\n            .into_iter()\n            .map(|nbytes| Storage::new(nbytes, align))\n            .collect::<Result<Vec<Storage>, std::alloc::LayoutError>>()?;\n\n        let tensors = izip!(storage_ids, shapes, dtypes)\n            .map(|(storage_id, shape, dtype)| {\n                let storage = storages[storage_id].view();\n                Tensor {\n                    data: mem::replace(&mut storages[storage_id], storage),\n                    device: Device::default(),\n                    dtype,\n                    size: shape.iter().product::<i64>() as usize,\n                    shape,\n                    strides: None,\n                    byte_offset: 0,\n                }\n            })\n            .collect();\n\n        Ok(tensors)\n    }\n\n    /// Creates closures which represent the computation performed by this graph.\n    fn setup_op_execs<M: 'm + Module>(\n        graph: &Graph,\n        lib: &'m M,\n        tensors: &[Tensor<'t>],\n    ) -> Result<Vec<Box<dyn Fn() + 'm>>, Box<dyn Error + 'static>> {\n        if !graph.node_row_ptr.is_some() {\n            return Err(GraphFormatError::MissingField(\"node_row_ptr\").into());\n        }\n        let node_row_ptr = graph.node_row_ptr.as_ref().unwrap();\n\n        let mut op_execs = Vec::new();\n        for (i, node) in graph.nodes.iter().enumerate() {\n            if node.op == \"null\" {\n                continue;\n            }\n            if node.op != \"tvm_op\" {\n                return Err(GraphFormatError::UnsupportedOp(node.op.to_owned()).into());\n            }\n            if !node.attrs.is_some() {\n                return Err(GraphFormatError::MissingAttr(node.op.clone(), \"\".to_string()).into());\n            }\n\n            let attrs: NodeAttrs = node.parse_attrs()?.into();\n\n            if attrs.func_name == \"__nop\" {\n                continue;\n            }\n\n            let func = lib\n                .get_function(&attrs.func_name)\n                .ok_or_else(|| FunctionNotFound(attrs.func_name.clone()))?;\n            let arg_indices = node\n                .inputs\n                .iter()\n                .map(|entry| graph.entry_index(entry))\n                .chain((0..attrs.num_outputs).map(|oi| Ok(node_row_ptr[i] + oi)));\n\n            let dl_tensors: Vec<DLTensor> = arg_indices\n                .map(|idx| {\n                    let tensor = &tensors[idx?];\n                    Ok(if attrs.flatten_data {\n                        Tensor::as_dltensor(tensor, true /* flatten */)\n                    } else {\n                        DLTensor::from(tensor)\n                    })\n                })\n                .collect::<Result<Vec<DLTensor>, GraphFormatError>>()?\n                .into();\n            let op: Box<dyn Fn()> = Box::new(move || {\n                let args: Vec<ArgValue> = dl_tensors\n                    .iter()\n                    .map(|t| t.into())\n                    .collect::<Vec<ArgValue>>();\n                let err_str = format!(\"Function {} failed to execute\", attrs.func_name);\n                func(&args).expect(&err_str);\n            });\n            op_execs.push(op);\n        }\n        Ok(op_execs)\n    }\n\n    pub fn load_params(&mut self, params: HashMap<String, Tensor>) {\n        params.into_iter().for_each(|(name, param)| {\n            self.set_input(name, param);\n        })\n    }\n\n    #[allow(clippy::if_same_then_else)]\n    pub fn set_input<S: AsRef<str>>(&mut self, name: S, value: Tensor) {\n        if let Some(idx) = self.get_input_index(name.as_ref()) {\n            // TODO: consider `new_with_params` to avoid ever allocating\n            let ptr = self.tensors[idx].data.as_ptr();\n            let mut to_replace = self.tensors.iter_mut().filter(|t| t.data.as_ptr() == ptr);\n            let owner = to_replace.nth(0).unwrap();\n            if value.data.is_owned() {\n                // FIXME: for no-copy, need setup_op_execs to not capture tensor ptr\n                // mem::replace(&mut (*owner), value);\n                // to_replace.for_each(|t| {\n                //   panic!(\"replacing\");\n                //   t.data = owner.data.view();\n                // });\n                owner.copy(&value);\n            } else {\n                owner.copy(&value);\n            }\n        } else {\n            println!(\"Unexpected input `{}`\", name.as_ref());\n        }\n    }\n\n    /// Returns the graph input with name `name`, if it exists.\n    pub fn get_input<S: AsRef<str>>(&mut self, name: S) -> Option<&Tensor> {\n        self.get_input_index(name.as_ref())\n            .map(move |idx| &self.tensors[idx])\n    }\n\n    /// Returns the graph output with index `index`, if it exists.\n    pub fn get_output(&self, idx: usize) -> Option<&Tensor> {\n        let graph = &self.graph;\n        graph.heads.get(idx).and_then(|entry| {\n            graph\n                .entry_index(entry)\n                .map(|idx| self.tensors.get(idx))\n                .unwrap_or(None)\n        })\n    }\n\n    /// Returns the index for graph input with name `name`, if it exists.\n    pub fn get_input_index<S: AsRef<str>>(&self, name: S) -> Option<usize> {\n        let graph = &self.graph;\n        (0..graph.nodes.len())\n            .skip_while(|&i| graph.nodes[i].name != name.as_ref())\n            .nth(0)\n            .and_then(|i| {\n                if graph.arg_nodes.iter().any(|&id| id == i) {\n                    graph.node_row_ptr.as_ref().map(|nrp| nrp[i])\n                } else {\n                    None\n                }\n            })\n    }\n}\n\n// Converts a string to TVM DLDataTypeCode. @see `String2DLDataType` in packed_func.h\nnamed! {\n  tvm_str_to_type<&str, DataType>,\n  do_parse!(\n    type_name: alpha1 >>\n    bits:      digit1 >>\n    lanes:     opt!(complete!(tuple!(tag!(\"x\"), digit1))) >>\n    (\n        DataType::new(\n            match type_name {\n                \"int\" => DLDataTypeCode_kDLInt,\n                \"uint\" => DLDataTypeCode_kDLUInt,\n                \"float\" => DLDataTypeCode_kDLFloat,\n                _ => DLDataTypeCode_kDLFloat,\n            } as u8,\n            bits.parse::<u8>().unwrap() as u8,\n            lanes\n                .map(|(_, lanes)| lanes.parse::<u16>().unwrap() as u16)\n                .unwrap_or(1),\n        )\n    )\n  )\n}\n\n// Converts a bytes to String.\nnamed! {\n    name<String>,\n    do_parse!(\n        len_l: le_u32 >>\n        len_h: le_u32 >>\n        data: take!(len_l) >>\n        (\n            if len_h == 0 {\n                String::from_utf8(data.to_vec()).unwrap()\n            } else {\n                panic!(\"Too long string\")\n            }\n        )\n    )\n}\n\n// Parses a Device\nnamed! {\n  tvm_device<&[u8], Device>,\n  do_parse!(\n    device_type: le_u32 >>\n    device_id:   le_i32 >>\n    (\n        Device {\n            device_type: DeviceType::from(device_type),\n            device_id: device_id as usize,\n        }\n    )\n  )\n}\n\n// Parses a DataType\nnamed! {\n  data_type<&[u8], DataType>,\n  do_parse!(\n    code:  le_u8  >>\n    bits:  le_u8  >>\n    lanes: le_u16 >>\n    (DataType::new(code, bits, lanes)))\n}\n\n// Parses a Tensor from a TVM array file.\nnamed! {\n    tensor<Tensor>,\n    do_parse!(\n                take!(8)      >>\n                le_u64        >>\n        device: tvm_device    >>\n        ndim:   le_u32        >>\n        dtype:  data_type     >>\n        shape:  count!(map!(le_i64, |sz| sz as i64), ndim as usize) >>\n        length: le_i64        >>\n        data:   take!(length) >>\n        (\n            Tensor {\n                data: Storage::from(data),\n                device: device,\n                dtype: dtype,\n                size: shape.iter().product::<i64>() as usize,\n                shape: shape,\n                strides: None,\n                byte_offset: 0,\n            }\n        )\n    )\n}\n\n// Parses a graph params dict from a params binary file.\nnamed! {\n    parse_param_dict<HashMap<String, Tensor>>,\n    do_parse!(\n                 take!(8)                      >>\n                 le_u64                        >>\n        names:   length_count!(le_u64, name)   >>\n        tensors: length_count!(le_u64, tensor) >>\n        (\n            HashMap::from_iter(names.into_iter().zip(tensors.into_iter()))\n        )\n    )\n}\n\n/// Loads a param dict saved using `runtime.save_param_dict`.\npub fn load_param_dict(bytes: &[u8]) -> Result<HashMap<String, Tensor>, GraphFormatError> {\n    match parse_param_dict(bytes) {\n        Ok((remaining_bytes, param_dict)) => {\n            if remaining_bytes.is_empty() {\n                Ok(param_dict)\n            } else {\n                Err(GraphFormatError::Params(None))\n            }\n        }\n        Err(error) => Err(match error {\n            NomErr::Incomplete(error) => GraphFormatError::Params(Some(NomErr::Incomplete(error))),\n            NomErr::Error((remainder, error_kind)) => {\n                GraphFormatError::Params(Some(NomErr::Error((remainder.into(), error_kind))))\n            }\n            NomErr::Failure((remainder, error_kind)) => {\n                GraphFormatError::Params(Some(NomErr::Failure((remainder.into(), error_kind))))\n            }\n        }),\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_str_to_type() {\n        assert_eq!(\n            tvm_str_to_type(\"float24\").unwrap().1,\n            DataType::float(24, 1)\n        );\n        assert_eq!(\n            tvm_str_to_type(\"uint111x44\").unwrap().1,\n            DataType::uint(111, 44)\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! This crate is an implementation of the TVM runtime for modules compiled with `--system-lib`.\n//! It's mainly useful for compiling to WebAssembly and SGX,\n//! but also native if you prefer Rust to C++.\n//!\n//! For TVM graphs, the entrypoint to this crate is `runtime::GraphExecutor`.\n//! Single-function modules are used via the `packed_func!` macro after obtaining\n//! the function from `runtime::SystemLibModule`\n//!\n//! The main entrypoints to this crate are `GraphExecutor`\n//! For examples of use, please refer to the multi-file tests in the `tests` directory.\n\nextern crate tvm_macros;\nextern crate tvm_sys;\n\n// Re-export the import_module macro.\npub use tvm_macros::import_module;\n\n// Re-export the called pack macro, eventually remove as its not a very good\n// abstraction.\npub use tvm_sys::call_packed;\n\nuse lazy_static::lazy_static;\n\nmod allocator;\nmod array;\npub mod errors;\nmod graph;\nmod module;\nmod threading;\nmod workspace;\n\npub use tvm_sys::{\n    errors::*,\n    ffi::{self, DLTensor},\n    packed_func::{self, *},\n    ArgValue, RetValue,\n};\n\npub use self::{array::*, errors::*, graph::*, module::*, threading::*, workspace::*};\n\nlazy_static! {\n    static ref LAST_ERROR: std::sync::RwLock<Option<&'static std::ffi::CStr>> =\n        std::sync::RwLock::new(None);\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn TVMAPISetLastError(cmsg: *const i8) {\n    *LAST_ERROR.write().unwrap() = Some(std::ffi::CStr::from_ptr(cmsg));\n}\n\n#[no_mangle]\npub extern \"C\" fn TVMGetLastError() -> *const std::os::raw::c_char {\n    match *LAST_ERROR.read().unwrap() {\n        Some(err) => err.as_ptr(),\n        None => std::ptr::null(),\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/module/dso.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    cell::RefCell,\n    collections::HashMap,\n    ffi::CStr,\n    os::raw::{c_char, c_int, c_void},\n    pin::Pin,\n};\n\nuse tvm_sys::{ffi::BackendPackedCFunc, packed_func::PackedFunc};\n\nuse crate::{\n    threading::{TVMBackendParallelBarrier, TVMBackendParallelLaunch},\n    workspace::{TVMBackendAllocWorkspace, TVMBackendFreeWorkspace},\n    TVMAPISetLastError,\n};\n\nuse super::Module;\n\nconst TVM_MAIN: &[u8] = b\"__tvm_main__\";\nconst TVM_MODULE_CTX: &[u8] = b\"__tvm_module_ctx\";\n\n/// A module backed by a Dynamic Shared Object (dylib).\npub struct DsoModule<'a> {\n    lib: libloading::Library,\n    packed_funcs: RefCell<HashMap<String, &'a (dyn PackedFunc)>>,\n    _pin: std::marker::PhantomPinned,\n}\n\nmacro_rules! init_context_func {\n    ($lib:ident, $( ($fn:ident, $sig:ty) ),+ $(,)?) => {\n        unsafe {\n            $(\n                let fn_ptr = $lib.get::<*mut $sig>(concat!(\"__\", stringify!($fn)).as_bytes());\n                if let Ok(fn_ptr) = fn_ptr {\n                    **fn_ptr = $fn;\n                }\n            )+\n        }\n    };\n}\n\nimpl<'a> DsoModule<'a> {\n    pub fn new<P: AsRef<std::ffi::OsStr>>(filename: P) -> Result<Pin<Box<Self>>, std::io::Error> {\n        let lib = libloading::Library::new(filename)?;\n\n        init_context_func!(\n            lib,\n            (TVMAPISetLastError, unsafe extern \"C\" fn(*const i8)),\n            (\n                TVMBackendAllocWorkspace,\n                unsafe extern \"C\" fn(c_int, c_int, u64, c_int, c_int) -> *mut c_void\n            ),\n            (\n                TVMBackendFreeWorkspace,\n                unsafe extern \"C\" fn(c_int, c_int, *mut c_void) -> c_int\n            ),\n            (\n                TVMBackendParallelLaunch,\n                unsafe extern \"C\" fn(\n                    crate::threading::FTVMParallelLambda,\n                    *const c_void,\n                    usize,\n                ) -> c_int\n            ),\n            (\n                TVMBackendParallelBarrier,\n                unsafe extern \"C\" fn(usize, *const tvm_sys::ffi::TVMParallelGroupEnv)\n            ),\n        );\n\n        // Pin the module in memory so that `ctx` pointer (below) is stable.\n        let dso_mod = Box::pin(Self {\n            lib,\n            packed_funcs: RefCell::new(HashMap::new()),\n            _pin: std::marker::PhantomPinned,\n        });\n\n        unsafe {\n            if let Ok(ctx) = dso_mod.lib.get::<*mut *const c_void>(TVM_MODULE_CTX) {\n                **ctx = &dso_mod as *const _ as *const c_void;\n            }\n        }\n\n        Ok(dso_mod)\n    }\n}\n\nimpl<'a> Module for DsoModule<'a> {\n    fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)> {\n        let name = name.as_ref();\n        let func = match unsafe {\n            self.lib\n                .get::<BackendPackedCFunc>(if name.as_bytes() == TVM_MAIN {\n                    // If __tvm_main__ is present, it contains the name of the\n                    // actual main function.\n                    match self\n                        .lib\n                        .get::<*const c_char>(TVM_MAIN)\n                        .map(|p| CStr::from_ptr(*p))\n                    {\n                        Ok(m) => m.to_bytes(),\n                        _ => return None,\n                    }\n                } else {\n                    name.as_bytes()\n                })\n        } {\n            Ok(func) => unsafe { func.into_raw() },\n            Err(_) => return None,\n        };\n\n        self.packed_funcs.borrow_mut().insert(\n            name.to_string(),\n            &*Box::leak(super::wrap_backend_packed_func(name.to_string(), *func)),\n        );\n\n        self.packed_funcs.borrow().get(name).copied()\n    }\n}\n\nimpl<'a> Drop for DsoModule<'a> {\n    fn drop(&mut self) {\n        self.packed_funcs\n            .replace(HashMap::new())\n            .into_iter()\n            .map(|(_name, f)| unsafe { Box::from_raw(f as *const _ as *mut (dyn PackedFunc)) })\n            .for_each(std::mem::drop);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/module/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#[cfg(not(any(target_arch = \"wasm32\", target_env = \"sgx\")))]\nmod dso;\nmod syslib;\n\nuse tvm_sys::{\n    ffi::BackendPackedCFunc,\n    packed_func::{ArgValue, PackedFunc, RetValue, TVMValue},\n};\n\n#[cfg(not(any(target_arch = \"wasm32\", target_env = \"sgx\")))]\npub use dso::DsoModule;\npub use syslib::SystemLibModule;\n\npub trait Module {\n    fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)>;\n}\n\n// @see `WrapPackedFunc` in `llvm_module.cc`.\nfn wrap_backend_packed_func(func_name: String, func: BackendPackedCFunc) -> Box<dyn PackedFunc> {\n    Box::new(move |args: &[ArgValue]| {\n        let (values, type_codes): (Vec<TVMValue>, Vec<i32>) = args\n            .iter()\n            .map(|arg| {\n                let (val, code) = arg.to_tvm_value();\n                (val, code as i32)\n            })\n            .unzip();\n        let ret: RetValue = RetValue::default();\n        let (mut ret_val, mut ret_type_code) = ret.to_tvm_value();\n        let exit_code = func(\n            values.as_ptr(),\n            type_codes.as_ptr(),\n            values.len() as i32,\n            &mut ret_val,\n            &mut ret_type_code,\n            std::ptr::null_mut(),\n        );\n        if exit_code == 0 {\n            Ok(RetValue::from_tvm_value(ret_val, ret_type_code))\n        } else {\n            Err(tvm_sys::errors::FuncCallError::get_with_context(\n                func_name.clone(),\n            ))\n        }\n    })\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/module/syslib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    collections::HashMap, convert::AsRef, ffi::CStr, os::raw::c_char, string::String, sync::RwLock,\n};\n\nuse lazy_static::lazy_static;\n\nuse tvm_sys::{ffi::BackendPackedCFunc, packed_func::PackedFunc};\n\nuse super::Module;\n\npub struct SystemLibModule;\n\n#[cfg(target_env = \"sgx\")]\nextern \"C\" {\n    fn __tvm_module_startup();\n}\n\nlazy_static! {\n    static ref SYSTEM_LIB_FUNCTIONS: RwLock<HashMap<String, &'static (dyn PackedFunc)>> =\n        RwLock::new(HashMap::new());\n}\n\nimpl Module for SystemLibModule {\n    fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)> {\n        SYSTEM_LIB_FUNCTIONS\n            .read()\n            .unwrap()\n            .get(name.as_ref())\n            .copied()\n    }\n}\n\nimpl Default for SystemLibModule {\n    fn default() -> Self {\n        #[cfg(target_env = \"sgx\")]\n        unsafe {\n            __tvm_module_startup();\n        }\n        SystemLibModule {}\n    }\n}\n\n#[no_mangle]\npub extern \"C\" fn TVMBackendRegisterSystemLibSymbol(\n    cname: *const c_char,\n    func: BackendPackedCFunc,\n) -> i32 {\n    let name = unsafe { CStr::from_ptr(cname).to_str().unwrap() };\n    SYSTEM_LIB_FUNCTIONS.write().unwrap().insert(\n        name.to_string(),\n        &*Box::leak(super::wrap_backend_packed_func(name.to_string(), func)),\n    );\n    0\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/threading.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    os::raw::{c_int, c_void},\n    sync::{\n        atomic::{AtomicUsize, Ordering},\n        Arc, Barrier,\n    },\n    thread::{self, JoinHandle},\n};\n\n#[cfg(not(target_arch = \"wasm32\"))]\nuse std::env;\n\nuse crossbeam_channel::{bounded, Receiver, Sender};\nuse tvm_sys::ffi::TVMParallelGroupEnv;\n\npub(crate) type FTVMParallelLambda =\n    extern \"C\" fn(task_id: usize, penv: *const TVMParallelGroupEnv, cdata: *const c_void) -> i32;\n\n/// Holds a parallel job request made by a TVM library function.\nstruct Job {\n    cb: FTVMParallelLambda,\n    cdata: *const c_void,\n    req_num_tasks: usize,\n    pending: Arc<AtomicUsize>,\n}\n\nimpl Job {\n    /// Splits this job into a number of `Task`s which can be scheduled.\n    fn tasks(&self, num_workers: usize) -> Vec<Task> {\n        let num_tasks = if self.req_num_tasks == 0 {\n            num_workers\n        } else {\n            self.req_num_tasks.min(num_workers)\n        };\n        self.pending.store(num_tasks, Ordering::SeqCst);\n\n        let barrier = Arc::new(Barrier::new(num_tasks));\n\n        (0..num_tasks)\n            .map(move |i| Task {\n                id: i,\n                flambda: self.cb,\n                penv: TVMParallelGroupEnv {\n                    sync_handle: &Arc::clone(&barrier) as *const _ as *mut c_void,\n                    num_task: num_tasks as i32,\n                },\n                cdata: self.cdata,\n                pending: Arc::clone(&self.pending),\n            })\n            .collect()\n    }\n\n    /// Waits for all tasks in this `Job` to be completed.\n    fn wait(&self) {\n        while self.pending.load(Ordering::Acquire) > 0 {\n            thread::yield_now();\n        }\n    }\n}\n\n/// A chunk of work requested by a TVM function.\nstruct Task {\n    id: usize,\n    flambda: FTVMParallelLambda,\n    penv: TVMParallelGroupEnv,\n    cdata: *const c_void,\n    pending: Arc<AtomicUsize>,\n}\nunsafe impl Send for Task {}\nunsafe impl Sync for Task {}\n\nimpl Task {\n    fn run(self) -> i32 {\n        let status = (self.flambda)(self.id, &self.penv as *const _, self.cdata);\n        self.pending.fetch_sub(1, Ordering::AcqRel);\n        status\n    }\n}\n\n#[derive(Default)]\nstruct Threads {\n    #[allow(unused)]\n    handles: Vec<JoinHandle<()>>,\n    queues: Vec<Sender<Task>>,\n}\n\nimpl<'a> Threads {\n    fn launch<F: Sync + Send + FnOnce(Receiver<Task>) + 'static + Copy>(\n        num_threads: usize,\n        cb: F,\n    ) -> Self {\n        let (handles, queues) = (0..num_threads)\n            .map(|_| {\n                let (p, c) = bounded(2);\n                let handle = thread::spawn(move || cb(c.into()));\n                (handle, p)\n            })\n            .unzip();\n        Threads { handles, queues }\n    }\n}\n\nstruct ThreadPool {\n    num_workers: usize,\n    #[allow(unused)]\n    threads: Threads,\n}\n\nthread_local!(static THREAD_POOL: ThreadPool = ThreadPool::new());\n\nimpl ThreadPool {\n    fn new() -> Self {\n        let num_workers = max_concurrency();\n        ThreadPool {\n            num_workers,\n            threads: Threads::launch(num_workers, ThreadPool::run_worker),\n        }\n    }\n\n    fn launch(&self, job: Job) {\n        let mut tasks = job.tasks(self.num_workers + 1);\n\n        for (i, task) in tasks.split_off(1).into_iter().enumerate() {\n            self.threads.queues[i].send(task).expect(\"should send\");\n        }\n\n        tasks.pop().unwrap().run();\n        job.wait();\n    }\n\n    fn run_worker(queue: Receiver<Task>) {\n        loop {\n            let task = match queue.recv() {\n                Ok(v) => v,\n                Err(_) => break,\n            };\n            let result = task.run();\n            if result == <i32>::min_value() {\n                break;\n            } else if result != 0 {\n                panic!(\"Error running task.\");\n            }\n        }\n    }\n}\n\n#[cfg(not(target_arch = \"wasm32\"))]\nfn max_concurrency() -> usize {\n    if let Ok(threads_str) = env::var(\"TVM_NUM_THREADS\").or_else(|_| env::var(\"OMP_NUM_THREADS\")) {\n        if let Ok(threads) = usize::from_str_radix(&threads_str, 10) {\n            return threads;\n        }\n    }\n    num_cpus::get()\n}\n\n#[cfg(target_arch = \"wasm32\")]\nfn max_concurrency() -> usize {\n    0 // wasm doesn't support threads yet\n}\n\n#[no_mangle]\npub extern \"C\" fn TVMBackendParallelLaunch(\n    cb: FTVMParallelLambda,\n    cdata: *const c_void,\n    num_task: usize,\n) -> c_int {\n    if max_concurrency() < 2 {\n        let penv = TVMParallelGroupEnv {\n            sync_handle: std::ptr::null_mut(),\n            num_task: 1,\n        };\n        cb(0, &penv as *const _, cdata);\n    } else {\n        THREAD_POOL.with(|pool| {\n            pool.launch(Job {\n                cb,\n                cdata,\n                req_num_tasks: num_task,\n                pending: Arc::new(AtomicUsize::new(0)),\n            });\n        });\n    }\n    0\n}\n\n// @see issue 988 for information on why this function is used.\n#[no_mangle]\npub unsafe extern \"C\" fn TVMBackendParallelBarrier(\n    _task_id: usize,\n    penv: *const TVMParallelGroupEnv,\n) {\n    let barrier: &Arc<Barrier> = &*((*penv).sync_handle as *const Arc<Barrier>);\n    barrier.wait();\n}\n\n#[cfg(test)]\nmod tests {\n    use std::{thread, time::Duration};\n\n    use super::*;\n\n    #[test]\n    fn test_max_concurrency() {\n        env::set_var(\"TVM_NUM_THREADS\", \"42\");\n        env::set_var(\"OMP_NUM_THREADS\", \"24\");\n        assert_eq!(max_concurrency(), 42);\n        env::remove_var(\"TVM_NUM_THREADS\");\n        assert_eq!(max_concurrency(), 24);\n    }\n\n    extern \"C\" fn _flambda(\n        task_id: usize,\n        penv: *const TVMParallelGroupEnv,\n        cdata: *const c_void,\n    ) -> i32 {\n        if cdata.is_null() {\n            return 0;\n        }\n        unsafe {\n            let &(ref counter, ref task_ids_sum) = &*(cdata as *const (AtomicUsize, AtomicUsize));\n            thread::sleep(Duration::from_millis(50 * task_id as u64));\n            counter.fetch_add(1, Ordering::SeqCst);\n            task_ids_sum.fetch_add(task_id, Ordering::SeqCst);\n            assert_eq!((*penv).num_task, 3);\n        }\n        0\n    }\n\n    // #[test]\n    // fn test_parallel_launch() {\n    //     TVMBackendParallelLaunch(flambda, ptr::null(), 6);\n    //     let counter = AtomicUsize::new(0);\n    //     let task_ids_sum = AtomicUsize::new(0);\n    //     let cdata = (counter, task_ids_sum);\n    //     let num_tasks = 3;\n    //     TVMBackendParallelLaunch(flambda, &cdata as *const _ as *const c_void, num_tasks);\n    //     assert_eq!(cdata.0.load(Ordering::SeqCst), num_tasks);\n    //     assert_eq!(\n    //         cdata.1.load(Ordering::SeqCst),\n    //         (0..num_tasks).sum::<usize>()\n    //     );\n    // }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/src/workspace.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    cell::RefCell,\n    error::Error,\n    os::raw::{c_int, c_void},\n    ptr,\n};\n\nuse crate::allocator::Allocation;\nuse crate::errors::InvalidPointer;\nuse std::alloc::LayoutError;\n\nconst WS_ALIGN: usize = 64; // taken from `kTempAllocaAlignment` in `device_api.h`\n\npub fn remove_item<T: PartialEq>(vec: &mut Vec<T>, item: &T) -> Option<T> {\n    let pos = vec.iter().position(|x| *x == *item)?;\n    Some(vec.remove(pos))\n}\n\nstruct WorkspacePool {\n    workspaces: Vec<Allocation>,\n    free: Vec<usize>,\n    in_use: Vec<usize>,\n}\n\nimpl WorkspacePool {\n    fn new() -> Self {\n        WorkspacePool {\n            workspaces: Vec::new(),\n            free: Vec::new(),\n            in_use: Vec::new(),\n        }\n    }\n\n    fn alloc_new(&mut self, size: usize) -> Result<*mut u8, LayoutError> {\n        self.workspaces.push(Allocation::new(size, Some(WS_ALIGN))?);\n        self.in_use.push(self.workspaces.len() - 1);\n        Ok(self.workspaces[self.workspaces.len() - 1].as_mut_ptr())\n    }\n\n    fn alloc(&mut self, size: usize) -> Result<*mut u8, LayoutError> {\n        if self.free.is_empty() {\n            return self.alloc_new(size);\n        }\n        let idx = self\n            .free\n            .iter()\n            .fold(None, |cur_ws_idx: Option<usize>, &idx| {\n                let ws_size = self.workspaces[idx].size();\n                if ws_size < size {\n                    return cur_ws_idx;\n                }\n                cur_ws_idx.or(Some(idx)).and_then(|cur_idx| {\n                    let cur_size = self.workspaces[cur_idx].size();\n                    Some(if ws_size <= cur_size { idx } else { cur_idx })\n                })\n            });\n        match idx {\n            Some(idx) => {\n                remove_item(&mut self.free, &idx).unwrap();\n                self.in_use.push(idx);\n                Ok(self.workspaces[idx].as_mut_ptr())\n            }\n            None => self.alloc_new(size),\n        }\n    }\n\n    fn free(&mut self, ptr: *mut u8) -> Result<(), Box<dyn Error>> {\n        let mut ws_idx = None;\n        for i in 0..self.in_use.len() {\n            let idx = self.in_use[i];\n            if self.workspaces[idx].as_mut_ptr() == ptr {\n                self.in_use.remove(i);\n                ws_idx = Some(idx);\n                break;\n            }\n        }\n        let ws_idx = ws_idx.ok_or_else(|| InvalidPointer(ptr))?;\n        self.free.push(ws_idx);\n        Ok(())\n    }\n}\n\nthread_local!(static WORKSPACE_POOL: RefCell<WorkspacePool> = RefCell::new(WorkspacePool::new()));\n\nconst WORKSPACE_PAGE_SIZE: usize = 4 << 10;\n\n#[no_mangle]\npub extern \"C\" fn TVMBackendAllocWorkspace(\n    _device_type: c_int,\n    _device_id: c_int,\n    size: u64,\n    _dtype_code_hint: c_int,\n    _dtype_bits_hint: c_int,\n) -> *mut c_void {\n    let nbytes = if size == 0 {\n        WORKSPACE_PAGE_SIZE\n    } else {\n        size as usize\n    };\n    WORKSPACE_POOL.with(|pool_cell| {\n        pool_cell\n            .borrow_mut()\n            .alloc(nbytes as usize)\n            .unwrap_or(ptr::null_mut()) as *mut c_void\n    })\n}\n\n#[no_mangle]\npub extern \"C\" fn TVMBackendFreeWorkspace(\n    _device_type: c_int,\n    _device_id: c_int,\n    ptr: *mut c_void,\n) -> c_int {\n    WORKSPACE_POOL.with(|pool_cell| {\n        (match pool_cell.borrow_mut().free(ptr as *mut u8) {\n            Ok(()) => 0,\n            Err(_) => -1,\n        }) as c_int\n    })\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/build_model.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Builds a simple graph for testing.\"\"\"\n\nfrom os import path as osp\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay, runtime\nfrom tvm.relay import testing\n\nCWD = osp.dirname(osp.abspath(osp.expanduser(__file__)))\n\n\ndef _get_model(dshape):\n    data = relay.var(\"data\", shape=dshape)\n    fc = relay.nn.dense(data, relay.var(\"dense_weight\"), units=dshape[-1] * 2)\n    fc = relay.nn.bias_add(fc, relay.var(\"dense_bias\"))\n    left, right = relay.split(fc, indices_or_sections=2, axis=1)\n    one = relay.const(1, dtype=\"float32\")\n    return relay.Tuple([(left + one), (right - one), fc])\n\n\ndef main():\n    dshape = (32, 16)\n    net = _get_model(dshape)\n    mod, params = testing.create_workload(net)\n    graph, lib, params = relay.build(mod, \"llvm\", params=params)\n\n    with open(osp.join(CWD, \"graph.json\"), \"w\") as f_resnet:\n        f_resnet.write(graph)\n    with open(osp.join(CWD, \"graph.params\"), \"wb\") as f_params:\n        f_params.write(runtime.save_param_dict(params))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_graph_serde.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{convert::TryFrom, fs, io::Read};\n\nuse tvm_graph_rt::Graph;\n\nmacro_rules! mf_dir {\n    ($p:literal) => {\n        concat!(env!(\"CARGO_MANIFEST_DIR\"), $p)\n    };\n}\n\nstatic PARAMS_FIXTURE_PATH: &str = mf_dir!(\"/tests/graph.params\");\n\n#[test]\nfn test_load_graph() {\n    let output = std::process::Command::new(mf_dir!(\"/tests/build_model.py\"))\n        .env(\n            \"PYTHONPATH\",\n            concat!(mf_dir!(\"/../../python\"), \":\", mf_dir!(\"/../../nnvm/python\")),\n        )\n        .output()\n        .expect(\"Failed to build test model\");\n    assert!(\n        std::path::Path::new(PARAMS_FIXTURE_PATH).exists(),\n        \"Could not build test graph fixture: STDOUT:\\n\\n{}\\nSTDERR: {}\\n\\n\",\n        String::from_utf8(output.stdout).unwrap(),\n        String::from_utf8(output.stderr).unwrap()\n    );\n    let mut params_bytes = Vec::new();\n    fs::File::open(PARAMS_FIXTURE_PATH)\n        .unwrap()\n        .read_to_end(&mut params_bytes)\n        .unwrap();\n    let _params = tvm_graph_rt::load_param_dict(&params_bytes);\n\n    let graph = Graph::try_from(\n        &fs::read_to_string(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/tests/graph.json\")).unwrap(),\n    )\n    .unwrap();\n\n    assert_eq!(graph.nodes[3].op, \"tvm_op\");\n    assert_eq!(\n        graph.nodes[3]\n            .attrs\n            .as_ref()\n            .unwrap()\n            .get(\"func_name\")\n            .unwrap(),\n        \"tvmgen_default_fused_nn_dense_nn_bias_add\"\n    );\n    assert_eq!(graph.nodes[3].inputs[0].index, 0);\n    assert_eq!(graph.nodes[4].inputs[0].index, 0);\n    assert_eq!(graph.heads.len(), 3);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_nn/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nextern crate ar;\n\nuse std::{env, fs::File, path::Path, process::Command};\n\nuse anyhow::{Context, Result};\nuse ar::Builder;\n\nfn main() -> Result<()> {\n    let out_dir = env::var(\"OUT_DIR\")?;\n    let out_dir = Path::new(&out_dir).join(\"test_nn\");\n\n    std::fs::create_dir_all(&out_dir)?;\n\n    let manifest_dir = env::var(\"CARGO_MANIFEST_DIR\")?;\n    let manifest_dir = Path::new(&manifest_dir);\n\n    let generator = manifest_dir.join(\"src\").join(\"build_test_graph.py\");\n\n    let graph_path = out_dir.join(\"graph.o\");\n\n    let output = Command::new(&generator)\n        .arg(&out_dir)\n        .output()\n        .with_context(|| format!(\"Failed to execute: {:?}\", generator))?;\n\n    assert!(\n        graph_path.exists(),\n        \"Could not build graph lib: {}\",\n        String::from_utf8(output.stderr)\n            .unwrap()\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    let lib_file = out_dir.join(\"libtestnn.a\");\n    let file = File::create(&lib_file).context(\"failed to create library file\")?;\n    let mut builder = Builder::new(file);\n    builder.append_path(graph_path)?;\n\n    let status = Command::new(\"ranlib\").arg(&lib_file).status()?;\n\n    assert!(status.success());\n\n    println!(\"cargo:rustc-link-lib=static=testnn\");\n    println!(\"cargo:rustc-link-search=native={}\", out_dir.display());\n    println!(\"cargo:rerun-if-changed={}\", generator.display());\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_nn/src/build_test_graph.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Builds a simple graph for testing.\"\"\"\n\nfrom os import path as osp\nimport sys\n\nfrom tvm import runtime as tvm_runtime\nfrom tvm import relay\nfrom tvm.relay import testing\n\n\ndef _get_model(dshape):\n    data = relay.var(\"data\", shape=dshape)\n    fc = relay.nn.dense(data, relay.var(\"dense_weight\"), units=dshape[-1] * 2)\n    fc = relay.nn.bias_add(fc, relay.var(\"dense_bias\"))\n    left, right = relay.split(fc, indices_or_sections=2, axis=1)\n    one = relay.const(1, dtype=\"float32\")\n    return relay.Tuple([(left + one), (right - one), fc])\n\n\ndef main():\n    dshape = (4, 8)\n    net = _get_model(dshape)\n    mod, params = testing.create_workload(net)\n    runtime = relay.backend.Runtime(\"cpp\", {\"system-lib\": True})\n    graph, lib, params = relay.build(mod, \"llvm\", runtime=runtime, params=params)\n\n    out_dir = sys.argv[1]\n    lib.save(osp.join(sys.argv[1], \"graph.o\"))\n    with open(osp.join(out_dir, \"graph.json\"), \"w\") as f_resnet:\n        f_resnet.write(graph)\n\n    with open(osp.join(out_dir, \"graph.params\"), \"wb\") as f_params:\n        f_params.write(tvm_runtime.save_param_dict(params))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_nn/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{collections::HashMap, convert::TryFrom, fs, io::Read};\n\nuse ndarray::{s, Array};\nuse tvm_graph_rt::{Graph, GraphExecutor, SystemLibModule, Tensor};\n\nconst BATCH_SIZE: usize = 4;\nconst IN_DIM: usize = 8;\n\nmacro_rules! check_sum {\n    ($e:expr, $a:ident, $b:ident) => {\n        let a = Array::try_from($e.get_input(stringify!($a)).unwrap().to_owned()).unwrap();\n        check_sum!(a, $b);\n    };\n    ($e:expr, $a:expr, $b:ident) => {\n        let a = Array::try_from($e.get_output($a).unwrap().to_owned()).unwrap();\n        check_sum!(a, $b);\n    };\n    ($a:ident, $b:ident) => {\n        let a_sum: f32 = $a.scalar_sum();\n        let b_sum: f32 = $b.scalar_sum();\n        assert!((a_sum - b_sum).abs() < 1e-2, \"{} != {}\", a_sum, b_sum);\n    };\n}\n\nfn main() {\n    let syslib = SystemLibModule::default();\n\n    let mut params_bytes = Vec::new();\n    fs::File::open(concat!(env!(\"OUT_DIR\"), \"/test_nn/graph.params\"))\n        .unwrap()\n        .read_to_end(&mut params_bytes)\n        .unwrap();\n    let params = tvm_graph_rt::load_param_dict(&params_bytes)\n        .unwrap()\n        .into_iter()\n        .map(|(k, v)| (k, v.to_owned()))\n        .collect::<HashMap<String, Tensor<'static>>>();\n\n    let graph = Graph::try_from(\n        &fs::read_to_string(concat!(env!(\"OUT_DIR\"), \"/test_nn/graph.json\")).unwrap(),\n    )\n    .unwrap();\n    let mut exec = GraphExecutor::new(graph, &syslib).unwrap();\n\n    let x = Array::from_shape_vec(\n        (BATCH_SIZE, IN_DIM),\n        (0..BATCH_SIZE * IN_DIM)\n            .map(|x| x as f32)\n            .collect::<Vec<f32>>(),\n    )\n    .unwrap();\n\n    let p0 = params.get(\"p0\").unwrap().to_owned();\n    let p1 = params.get(\"p1\").unwrap().to_owned();\n    println!(\"p0: {:?}\", p0.shape());\n    println!(\"p1: {:?}\", p1.shape());\n    let w = Array::try_from(p0)\n        .unwrap()\n        .into_shape((BATCH_SIZE * 4, IN_DIM))\n        .unwrap();\n    let b = Array::try_from(p1).unwrap();\n    let dense = x.dot(&w.t()) + &b;\n    let left = dense.slice(s![.., 0..IN_DIM]);\n    let right = dense.slice(s![.., IN_DIM..]);\n    let expected_o0 = &left + 1f32;\n    let expected_o1 = &right - 1f32;\n\n    exec.load_params(params);\n    exec.set_input(\"data\", (&x).into());\n\n    check_sum!(exec, data, x);\n    check_sum!(exec, p0, w);\n    check_sum!(exec, p1, b);\n\n    exec.run();\n\n    check_sum!(exec, 0, expected_o0);\n    check_sum!(exec, 1, expected_o1);\n    check_sum!(exec, 2, dense);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_basic/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nextern crate ar;\n\nuse std::{path::PathBuf, process::Command};\n\nuse std::fs::File;\n\nuse anyhow::Result;\nuse ar::Builder;\n\nfn main() -> Result<()> {\n    let mut out_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n    out_dir.push(\"lib\");\n\n    if !out_dir.is_dir() {\n        std::fs::create_dir(&out_dir)?;\n    }\n\n    let obj_file = out_dir.join(\"test.o\");\n    let lib_file = out_dir.join(\"libtest_basic.a\");\n\n    let output = Command::new(concat!(\n        env!(\"CARGO_MANIFEST_DIR\"),\n        \"/src/build_test_lib.py\"\n    ))\n    .arg(&out_dir)\n    .output()?;\n\n    assert!(\n        obj_file.exists(),\n        \"Could not build tvm lib: {}\",\n        String::from_utf8(output.stderr)?\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    let mut builder = Builder::new(File::create(&lib_file)?);\n    builder.append_path(&obj_file)?;\n\n    drop(builder);\n\n    let status = Command::new(\"ranlib\").arg(&lib_file).status()?;\n\n    assert!(status.success());\n\n    println!(\"cargo:rustc-link-lib=static=test_basic\");\n    println!(\"cargo:rustc-link-search=native={}\", out_dir.display());\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_basic/src/build_test_lib.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Prepares a simple TVM library for testing.\"\"\"\n\nfrom os import path as osp\nimport sys\n\nimport tvm\nfrom tvm.relay.backend import Runtime\nfrom tvm import te\n\n\ndef main():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n    s[C].parallel(s[C].op.axis[0])\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    print(tvm.lower(s, [A, B, C], simple_mode=True))\n    tvm.build(s, [A, B, C], \"llvm\", runtime=runtime).save(osp.join(sys.argv[1], \"test.o\"))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_basic/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse ndarray::Array;\nuse tvm_graph_rt::{DLTensor, Module as _, SystemLibModule};\n\nmod tvm_mod {\n    tvm_graph_rt::import_module!(\"lib/test.o\");\n}\n\nfn main() {\n    // try static\n    let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);\n    let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);\n    let mut c = Array::from_vec(vec![0f32; 4]);\n    let e = Array::from_vec(vec![2f32, 2., 4., 4.]);\n    let mut a_dl: DLTensor = (&mut a).into();\n    let mut b_dl: DLTensor = (&mut b).into();\n    let mut c_dl: DLTensor = (&mut c).into();\n    let args = vec![(&mut a_dl).into(), (&mut b_dl).into(), (&mut c_dl).into()];\n    tvm_mod::default_function(&args[..]).unwrap();\n    assert!(c.all_close(&e, 1e-8f32));\n\n    // try runtime\n    let syslib = SystemLibModule::default();\n    let add = syslib\n        .get_function(\"default_function\")\n        .expect(\"main function not found\");\n    add(&args[..]).unwrap();\n    assert!(c.all_close(&e, 1e-8f32));\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_dso/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{env, path::Path, process::Command};\n\nuse anyhow::{Context, Result};\n\nfn main() -> Result<()> {\n    let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n    let exe = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/build_test_lib.py\");\n\n    let output = Command::new(exe)\n        .arg(&out_dir)\n        .output()\n        .with_context(|| anyhow::anyhow!(\"Failed to execute: {} {}\", exe, &out_dir))?;\n\n    assert!(\n        Path::new(&format!(\"{}/test.so\", out_dir)).exists(),\n        \"Could not build tvm lib: {}\",\n        String::from_utf8(output.stderr)\n            .unwrap()\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_dso/src/build_test_lib.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Prepares a simple TVM library for testing.\"\"\"\n\nfrom os import path as osp\nimport sys\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cc\n\n\ndef main():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n    s[C].parallel(s[C].op.axis[0])\n    print(tvm.lower(s, [A, B, C], simple_mode=True))\n    obj_file = osp.join(sys.argv[1], \"test.o\")\n    tvm.build(s, [A, B, C], \"llvm\").save(obj_file)\n    cc.create_shared(osp.join(sys.argv[1], \"test.so\"), [obj_file])\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_tvm_dso/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse ndarray::Array;\nuse tvm_graph_rt::{DLTensor, DsoModule, Module};\n\nfn main() {\n    tvm_graph_rt::TVMGetLastError();\n    let module = DsoModule::new(concat!(env!(\"OUT_DIR\"), \"/test.so\")).unwrap();\n    let add = module\n        .get_function(\"__tvm_main__\")\n        .expect(\"main function not found\");\n    let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);\n    let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);\n    let mut c = Array::from_vec(vec![0f32; 4]);\n    let e = Array::from_vec(vec![2f32, 2., 4., 4.]);\n    let mut a_dl: DLTensor = (&mut a).into();\n    let mut b_dl: DLTensor = (&mut b).into();\n    let mut c_dl: DLTensor = (&mut c).into();\n    let args = vec![(&mut a_dl).into(), (&mut b_dl).into(), (&mut c_dl).into()];\n    add(&args[..]).unwrap();\n    assert!(c.all_close(&e, 1e-8f32));\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_wasm32/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{path::PathBuf, process::Command};\n\nuse anyhow::{Context, Result};\n\nfn main() -> Result<()> {\n    let mut out_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n    out_dir.push(\"lib\");\n\n    if !out_dir.is_dir() {\n        std::fs::create_dir(&out_dir).context(\"failed to create directory for WASM outputs\")?;\n    }\n\n    let obj_file = out_dir.join(\"test.o\");\n    let lib_file = out_dir.join(\"libtest_wasm32.a\");\n\n    let output = Command::new(concat!(\n        env!(\"CARGO_MANIFEST_DIR\"),\n        \"/src/build_test_lib.py\"\n    ))\n    .arg(&out_dir)\n    .output()\n    .context(\"failed to execute Python script for generating TVM library\")?;\n\n    assert!(\n        obj_file.exists(),\n        \"Could not build tvm lib: {}\",\n        String::from_utf8(output.stderr)\n            .unwrap()\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    let ar = option_env!(\"LLVM_AR\").unwrap_or(\"llvm-ar-8\");\n\n    let output = Command::new(ar)\n        .arg(\"rcs\")\n        .arg(&lib_file)\n        .arg(&obj_file)\n        .output()\n        .context(\"failed to run LLVM_AR command\")?;\n\n    assert!(\n        lib_file.exists(),\n        \"Could not create archive: {}\",\n        String::from_utf8(output.stderr)\n            .unwrap()\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    println!(\"cargo:rustc-link-lib=static=test_wasm32\");\n    println!(\"cargo:rustc-link-search=native={}\", out_dir.display());\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_wasm32/src/build_test_lib.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Prepares a simple TVM library for testing.\"\"\"\n\nfrom os import path as osp\nimport sys\n\nimport tvm\nfrom tvm import te\nfrom tvm.relay.backend import Runtime\n\n\ndef main():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n    s[C].parallel(s[C].op.axis[0])\n    print(tvm.lower(s, [A, B, C], simple_mode=True))\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    tvm.build(s, [A, B, C], \"llvm -mtriple=wasm32-unknown-unknown\", runtime=runtime).save(\n        osp.join(sys.argv[1], \"test.o\")\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-graph-rt/tests/test_wasm32/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nextern \"C\" {\n    static __tvm_module_ctx: i32;\n}\n\n#[no_mangle]\nunsafe fn __get_tvm_module_ctx() -> i32 {\n    // Refer a symbol in the libtest_wasm32.a to make sure that the link of the\n    // library is not optimized out.\n    __tvm_module_ctx\n}\n\nextern crate ndarray;\n#[macro_use]\nextern crate tvm_graph_rt;\n\nuse ndarray::Array;\nuse tvm_graph_rt::{DLTensor, Module as _, SystemLibModule};\n\nfn main() {\n    // try static\n    let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);\n    let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);\n    let mut c = Array::from_vec(vec![0f32; 4]);\n    let e = Array::from_vec(vec![2f32, 2., 4., 4.]);\n    let mut a_dl: DLTensor = (&mut a).into();\n    let mut b_dl: DLTensor = (&mut b).into();\n    let mut c_dl: DLTensor = (&mut c).into();\n\n    let syslib = SystemLibModule::default();\n    let add = syslib\n        .get_function(\"default_function\")\n        .expect(\"main function not found\");\n    call_packed!(add, &mut a_dl, &mut b_dl, &mut c_dl).unwrap();\n    assert!(c.all_close(&e, 1e-8f32));\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-macros/src/external.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\nuse proc_macro2::Span;\nuse proc_macro_error::abort;\nuse quote::quote;\nuse syn::parse::{Parse, ParseStream, Result};\n\nuse syn::{\n    token::Semi, Attribute, FnArg, Generics, Ident, Lit, Meta, NestedMeta, Pat, ReturnType,\n    Signature, Type, Visibility,\n};\n\nstruct ExternalItem {\n    attrs: Vec<Attribute>,\n    visibility: Visibility,\n    sig: Signature,\n}\n\nimpl Parse for ExternalItem {\n    fn parse(input: ParseStream) -> Result<Self> {\n        let item = ExternalItem {\n            attrs: input.call(Attribute::parse_outer)?,\n            visibility: input.parse()?,\n            sig: input.parse()?,\n        };\n        let _semi: Semi = input.parse()?;\n        Ok(item)\n    }\n}\n\nstruct External {\n    visibility: Visibility,\n    tvm_name: String,\n    ident: Ident,\n    generics: Generics,\n    inputs: Vec<FnArg>,\n    ret_type: ReturnType,\n}\n\nimpl Parse for External {\n    fn parse(input: ParseStream) -> Result<Self> {\n        let method: ExternalItem = input.parse()?;\n        let visibility = method.visibility;\n        assert_eq!(method.attrs.len(), 1);\n        let sig = method.sig;\n        let tvm_name = method.attrs[0].parse_meta()?;\n        let tvm_name = match tvm_name {\n            Meta::List(meta_list) => {\n                let name = meta_list.path.get_ident().expect(\"name\");\n                assert_eq!(name.to_string(), \"name\".to_string());\n                match meta_list.nested.first() {\n                    Some(NestedMeta::Lit(Lit::Str(lit))) => lit.value(),\n                    _ => panic!(),\n                }\n            }\n            _ => panic!(),\n        };\n\n        let ident = sig.ident;\n        let generics = sig.generics;\n        let inputs = sig\n            .inputs\n            .iter()\n            .cloned()\n            .map(|param| param.clone())\n            .collect();\n        let ret_type = sig.output;\n\n        Ok(External {\n            visibility,\n            tvm_name,\n            ident,\n            generics,\n            inputs,\n            ret_type,\n        })\n    }\n}\n\nstruct ExternalInput {\n    externs: Vec<External>,\n}\n\nimpl Parse for ExternalInput {\n    fn parse(input: ParseStream) -> Result<Self> {\n        let mut externs: Vec<External> = Vec::new();\n\n        loop {\n            if input.is_empty() {\n                break;\n            }\n            externs.push(input.parse()?);\n        }\n\n        Ok(ExternalInput { externs })\n    }\n}\n\npub fn macro_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n    let ext_input = syn::parse_macro_input!(input as ExternalInput);\n\n    let tvm_rt_crate = crate::util::get_tvm_rt_crate();\n\n    let result_type = quote! { #tvm_rt_crate::function::Result };\n\n    let mut items = Vec::new();\n\n    for external in &ext_input.externs {\n        let visibility = &external.visibility;\n        let name = &external.ident;\n        let global_name = format!(\"global_{}\", external.ident);\n        let global_name = Ident::new(&global_name, Span::call_site());\n        let ext_name = &external.tvm_name;\n\n        let ty_params: Vec<syn::TypeParam> = external\n            .generics\n            .params\n            .iter()\n            .map(|ty_param| match ty_param {\n                syn::GenericParam::Type(param) => param.clone(),\n                _ => abort! { ty_param,\n                    \"Only supports type parameters.\"\n                },\n            })\n            .collect();\n\n        let args = &external.inputs;\n\n        let (args, tys): (Vec<Ident>, Vec<Type>) = args\n            .iter()\n            .map(|arg| match arg {\n                FnArg::Typed(pat_type) => match &*pat_type.pat {\n                    Pat::Ident(pat_ident) => {\n                        let ident: Ident = pat_ident.ident.clone();\n                        let ty: Type = *pat_type.ty.clone();\n                        (ident, ty)\n                    }\n                    _ => abort! { pat_type,\n                        \"Only supports type parameters.\"\n                    },\n                },\n                pat => abort! {\n                    pat, \"invalid pattern type for function\";\n\n                    note = \"{:?} is not allowed here\", pat;\n                },\n            })\n            .unzip();\n\n        let ret_type = match &external.ret_type {\n            ReturnType::Type(_, rtype) => *rtype.clone(),\n            ReturnType::Default => syn::parse_str::<Type>(\"()\").unwrap(),\n        };\n\n        let global = quote! {\n            #[allow(non_upper_case_globals)]\n            static #global_name: ::once_cell::sync::Lazy<#tvm_rt_crate::Function> =\n            ::once_cell::sync::Lazy::new(|| {\n                #tvm_rt_crate::Function::get(#ext_name)\n                .expect(concat!(\"unable to load external function\", stringify!(#ext_name), \"from TVM registry.\"))\n            });\n        };\n\n        items.push(global);\n\n        let wrapper = quote! {\n            #visibility fn #name<#(#ty_params),*>(#(#args : #tys),*) -> #result_type<#ret_type> {\n                let func_ref: #tvm_rt_crate::Function = #global_name.clone();\n                let func_ref: Box<dyn Fn(#(#tys),*) -> #result_type<#ret_type>> = func_ref.into();\n                let res: #ret_type = func_ref(#(#args),*)?;\n                Ok(res)\n            }\n        };\n\n        items.push(wrapper);\n    }\n\n    proc_macro::TokenStream::from(quote! {\n        #(#items\n        )*\n    })\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-macros/src/import_module.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\nuse quote::quote;\nuse std::{fs::File, io::Read};\nuse syn::parse::{Parse, ParseStream, Result};\nuse syn::LitStr;\n\nuse std::path::PathBuf;\n\nstruct ImportModule {\n    importing_file: LitStr,\n}\n\nimpl Parse for ImportModule {\n    fn parse(input: ParseStream) -> Result<Self> {\n        let importing_file: LitStr = input.parse()?;\n        Ok(ImportModule { importing_file })\n    }\n}\n\npub fn macro_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n    let import_module_args = syn::parse_macro_input!(input as ImportModule);\n\n    let manifest =\n        std::env::var(\"CARGO_MANIFEST_DIR\").expect(\"variable should always be set by Cargo.\");\n\n    let mut path = PathBuf::new();\n    path.push(manifest);\n    path = path.join(import_module_args.importing_file.value());\n\n    let mut fd = File::open(&path)\n        .unwrap_or_else(|_| panic!(\"Unable to find TVM object file at `{}`\", path.display()));\n    let mut buffer = Vec::new();\n    fd.read_to_end(&mut buffer).unwrap();\n\n    let fn_names = match goblin::Object::parse(&buffer).unwrap() {\n        goblin::Object::Elf(elf) => elf\n            .syms\n            .iter()\n            .filter_map(|s| {\n                if s.st_type() == 0 || goblin::elf::sym::type_to_str(s.st_type()) == \"FILE\" {\n                    return None;\n                }\n                match elf.strtab.get(s.st_name) {\n                    Some(Ok(name)) if name != \"\" => {\n                        Some(syn::Ident::new(name, proc_macro2::Span::call_site()))\n                    }\n                    _ => None,\n                }\n            })\n            .collect::<Vec<_>>(),\n        goblin::Object::Mach(goblin::mach::Mach::Binary(obj)) => {\n            obj.symbols()\n                .filter_map(|s| match s {\n                    Ok((name, ref nlist))\n                        if nlist.is_global()\n                            && nlist.n_sect != 0\n                            && !name.ends_with(\"tvm_module_ctx\") =>\n                    {\n                        Some(syn::Ident::new(\n                            if name.starts_with('_') {\n                                // Mach objects prepend a _ to globals.\n                                &name[1..]\n                            } else {\n                                &name\n                            },\n                            proc_macro2::Span::call_site(),\n                        ))\n                    }\n                    _ => None,\n                })\n                .collect::<Vec<_>>()\n        }\n        _ => panic!(\"Unsupported object format.\"),\n    };\n\n    let extern_fns = quote! {\n        mod ext {\n            extern \"C\" {\n                #(\n                    pub(super) fn #fn_names(\n                        args: *const tvm_graph_rt::ffi::TVMValue,\n                        type_codes: *const std::os::raw::c_int,\n                        num_args: std::os::raw::c_int\n                    ) -> std::os::raw::c_int;\n                )*\n            }\n        }\n    };\n\n    let fns = quote! {\n        use tvm_graph_rt::{ffi::TVMValue, ArgValue, RetValue, FuncCallError};\n        #extern_fns\n\n        #(\n            pub fn #fn_names(args: &[ArgValue]) -> Result<RetValue, FuncCallError> {\n                let (values, type_codes): (Vec<TVMValue>, Vec<i32>) = args\n                   .into_iter()\n                   .map(|arg| {\n                       let (val, code) = arg.to_tvm_value();\n                       (val, code as i32)\n                   })\n                   .unzip();\n                let exit_code = unsafe {\n                    ext::#fn_names(values.as_ptr(), type_codes.as_ptr(), values.len() as i32)\n                };\n                if exit_code == 0 {\n                    Ok(RetValue::default())\n                } else {\n                    Err(FuncCallError::get_with_context(stringify!(#fn_names).to_string()))\n                }\n            }\n        )*\n    };\n\n    proc_macro::TokenStream::from(fns)\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-macros/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse proc_macro::TokenStream;\nuse proc_macro_error::proc_macro_error;\n\nmod external;\nmod import_module;\nmod object;\nmod util;\n\n#[proc_macro]\npub fn import_module(input: TokenStream) -> TokenStream {\n    import_module::macro_impl(input)\n}\n\n#[proc_macro_error]\n#[proc_macro_derive(Object, attributes(base, ref_name, type_key, no_derive))]\npub fn macro_impl(input: TokenStream) -> TokenStream {\n    // let input = proc_macro2::TokenStream::from(input);\n    TokenStream::from(object::macro_impl(input))\n}\n\n#[proc_macro_error]\n#[proc_macro]\npub fn external(input: TokenStream) -> TokenStream {\n    external::macro_impl(input)\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-macros/src/object.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse proc_macro::TokenStream;\nuse proc_macro2::Span;\nuse quote::quote;\nuse syn::DeriveInput;\nuse syn::Ident;\n\nuse crate::util::*;\n\npub fn macro_impl(input: proc_macro::TokenStream) -> TokenStream {\n    let tvm_rt_crate = get_tvm_rt_crate();\n    let result = quote! { #tvm_rt_crate::function::Result };\n    let error = quote! { #tvm_rt_crate::errors::Error };\n    let derive_input = syn::parse_macro_input!(input as DeriveInput);\n    let payload_id = derive_input.ident.clone();\n\n    let type_key = get_attr(&derive_input, \"type_key\")\n        .map(attr_to_str)\n        .expect(\"Failed to get type_key\");\n\n    let derive = get_attr(&derive_input, \"no_derive\")\n        .map(|_| false)\n        .unwrap_or(true);\n\n    let ref_id = get_attr(&derive_input, \"ref_name\")\n        .map(|a| Ident::new(attr_to_str(a).value().as_str(), Span::call_site()))\n        .unwrap_or_else(|| {\n            let id = payload_id.to_string();\n            let suffixes = [\"Node\", \"Obj\"];\n            if let Some(suf) = suffixes\n                .iter()\n                .find(|&suf| id.len() > suf.len() && id.ends_with(suf))\n            {\n                Ident::new(&id[..id.len() - suf.len()], payload_id.span())\n            } else {\n                panic!(\n                    \"Either 'ref_name' must be given, or the struct name must end one of {:?}\",\n                    suffixes\n                )\n            }\n        });\n\n    let base_tokens = match &derive_input.data {\n        syn::Data::Struct(s) => s.fields.iter().next().and_then(|f| {\n            let (base_id, base_ty) = (f.ident.clone()?, f.ty.clone());\n            if base_id == \"base\" {\n                // The transitive case of subtyping\n                Some(quote! {\n                    impl<O> AsRef<O> for #payload_id\n                        where #base_ty: AsRef<O>\n                    {\n                        fn as_ref(&self) -> &O {\n                            self.#base_id.as_ref()\n                        }\n                    }\n                })\n            } else {\n                None\n            }\n        }),\n        _ => panic!(\"derive only works for structs\"),\n    };\n\n    let ref_derives = if derive {\n        quote! { #[derive(Debug, Clone)]}\n    } else {\n        quote! { #[derive(Clone)] }\n    };\n\n    let mut expanded = quote! {\n        unsafe impl #tvm_rt_crate::object::IsObject for #payload_id {\n            const TYPE_KEY: &'static str = #type_key;\n        }\n\n        // a silly AsRef impl is necessary for subtyping to work\n        impl AsRef<#payload_id> for #payload_id {\n            fn as_ref(&self) -> &Self {\n                self\n            }\n        }\n\n        #ref_derives\n        pub struct #ref_id(Option<#tvm_rt_crate::object::ObjectPtr<#payload_id>>);\n\n        impl #tvm_rt_crate::object::IsObjectRef for #ref_id {\n            type Object = #payload_id;\n\n            fn as_ptr(&self) -> Option<&#tvm_rt_crate::object::ObjectPtr<Self::Object>> {\n                self.0.as_ref()\n            }\n\n            fn into_ptr(self) -> Option<#tvm_rt_crate::object::ObjectPtr<Self::Object>> {\n                self.0\n            }\n\n            fn from_ptr(object_ptr: Option<#tvm_rt_crate::object::ObjectPtr<Self::Object>>) -> Self {\n                #ref_id(object_ptr)\n            }\n        }\n\n        impl std::ops::Deref for #ref_id {\n            type Target = #payload_id;\n\n            fn deref(&self) -> &Self::Target {\n                self.0.as_ref().unwrap()\n            }\n        }\n\n        impl std::convert::From<#payload_id> for #ref_id {\n            fn from(payload: #payload_id) -> Self {\n                let ptr = #tvm_rt_crate::object::ObjectPtr::new(payload);\n                #tvm_rt_crate::object::IsObjectRef::from_ptr(Some(ptr))\n            }\n        }\n\n        impl std::convert::From<#tvm_rt_crate::object::ObjectPtr<#payload_id>> for #ref_id {\n            fn from(ptr: #tvm_rt_crate::object::ObjectPtr<#payload_id>) -> Self {\n                #tvm_rt_crate::object::IsObjectRef::from_ptr(Some(ptr))\n            }\n        }\n\n        impl std::convert::TryFrom<#tvm_rt_crate::RetValue> for #ref_id {\n            type Error = #error;\n\n            fn try_from(ret_val: #tvm_rt_crate::RetValue) -> #result<#ref_id> {\n                use std::convert::TryInto;\n                let ptr: #tvm_rt_crate::object::ObjectPtr<#payload_id> = ret_val.try_into()?;\n                Ok(ptr.into())\n            }\n        }\n\n        impl<'a> From<&'a #ref_id> for #tvm_rt_crate::ArgValue<'a> {\n            fn from(object_ref: &'a #ref_id) -> #tvm_rt_crate::ArgValue<'a> {\n                use std::ffi::c_void;\n                let object_ptr = &object_ref.0;\n                match object_ptr {\n                    None => {\n                        #tvm_rt_crate::ArgValue::\n                            ObjectHandle(std::ptr::null::<c_void>() as *mut c_void)\n                    }\n                    Some(value) => value.into()\n                }\n            }\n        }\n\n        impl<'a> std::convert::TryFrom<#tvm_rt_crate::ArgValue<'a>> for #ref_id {\n            type Error = #error;\n\n            fn try_from(arg_value: #tvm_rt_crate::ArgValue<'a>) -> #result<#ref_id> {\n                use std::convert::TryInto;\n                let optr = arg_value.try_into()?;\n                Ok(#ref_id(Some(optr)))\n            }\n        }\n\n\n        impl From<#ref_id> for #tvm_rt_crate::RetValue {\n            fn from(object_ref: #ref_id) -> #tvm_rt_crate::RetValue {\n                use std::ffi::c_void;\n                let object_ptr = &object_ref.0;\n                match object_ptr {\n                    None => {\n                        #tvm_rt_crate::RetValue::ObjectHandle(std::ptr::null::<c_void>() as *mut c_void)\n                    }\n                    Some(value) => value.clone().into()\n                }\n            }\n        }\n    };\n\n    expanded.extend(base_tokens);\n\n    if derive {\n        let derives = quote! {\n            impl std::hash::Hash for #ref_id {\n                fn hash<H: std::hash::Hasher>(&self, state: &mut H) {\n                    self.0.hash(state)\n                }\n            }\n\n            impl std::cmp::PartialEq for #ref_id {\n                fn eq(&self, other: &Self) -> bool {\n                    self.0 == other.0\n                }\n            }\n\n            impl std::cmp::Eq for #ref_id {}\n        };\n\n        expanded.extend(derives);\n    }\n\n    TokenStream::from(expanded)\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-macros/src/util.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse proc_macro2::TokenStream;\nuse quote::quote;\nuse std::env;\n\npub fn get_tvm_rt_crate() -> TokenStream {\n    if env::var(\"CARGO_PKG_NAME\").unwrap() == \"tvm-rt\" {\n        quote!(crate)\n    } else {\n        quote!(tvm_rt)\n    }\n}\n\npub(crate) fn get_attr<'a>(\n    derive_input: &'a syn::DeriveInput,\n    name: &str,\n) -> Option<&'a syn::Attribute> {\n    derive_input.attrs.iter().find(|a| a.path.is_ident(name))\n}\n\npub(crate) fn attr_to_str(attr: &syn::Attribute) -> syn::LitStr {\n    match attr.parse_meta() {\n        Ok(syn::Meta::NameValue(syn::MetaNameValue {\n            lit: syn::Lit::Str(s),\n            ..\n        })) => s,\n        Ok(m) => panic!(\"Expected a string literal, got {:?}\", m),\n        Err(e) => panic!(\"{}\", e),\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/array.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::{TryFrom, TryInto};\nuse std::iter::{FromIterator, IntoIterator, Iterator};\nuse std::marker::PhantomData;\n\nuse crate::errors::Error;\nuse crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};\nuse crate::{\n    external,\n    function::{Function, Result},\n    ArgValue, RetValue,\n};\n\n#[repr(C)]\n#[derive(Clone)]\npub struct Array<T: IsObjectRef> {\n    object: ObjectRef,\n    _data: PhantomData<T>,\n}\n\n// TODO(@jroesch): convert to use generics instead of casting inside\n// the implementation.\nexternal! {\n    #[name(\"runtime.ArrayGetItem\")]\n    fn array_get_item(array: ObjectRef, index: isize) -> ObjectRef;\n    #[name(\"runtime.ArraySize\")]\n    fn array_size(array: ObjectRef) -> i64;\n}\n\nimpl<T: IsObjectRef + 'static> IsObjectRef for Array<T> {\n    type Object = Object;\n    fn as_ptr(&self) -> Option<&ObjectPtr<Self::Object>> {\n        self.object.as_ptr()\n    }\n\n    fn into_ptr(self) -> Option<ObjectPtr<Self::Object>> {\n        self.object.into_ptr()\n    }\n\n    fn from_ptr(object_ptr: Option<ObjectPtr<Self::Object>>) -> Self {\n        let object_ref = match object_ptr {\n            Some(o) => o.into(),\n            _ => panic!(),\n        };\n\n        Array {\n            object: object_ref,\n            _data: PhantomData,\n        }\n    }\n}\n\nimpl<T: IsObjectRef> Array<T> {\n    pub fn from_vec(data: Vec<T>) -> Result<Array<T>> {\n        let iter = data.iter().map(T::into_arg_value).collect();\n\n        let func = Function::get(\"runtime.Array\").expect(\n            \"runtime.Array function is not registered, this is most likely a build or linking error\",\n        );\n\n        // let array_data = func.invoke(iter)?;\n        // let array_data: ObjectRef = func.invoke(iter)?.try_into()?;\n        let array_data: ObjectPtr<Object> = func.invoke(iter)?.try_into()?;\n\n        debug_assert!(\n            array_data.count() >= 1,\n            \"array reference count is {}\",\n            array_data.count()\n        );\n\n        Ok(Array {\n            object: array_data.into(),\n            _data: PhantomData,\n        })\n    }\n\n    pub fn get(&self, index: isize) -> Result<T>\n    where\n        T: TryFrom<RetValue, Error = Error>,\n    {\n        let oref: ObjectRef = array_get_item(self.object.clone(), index)?;\n        oref.downcast()\n    }\n\n    pub fn len(&self) -> i64 {\n        array_size(self.object.clone()).expect(\"size should never fail\")\n    }\n}\n\nimpl<T: IsObjectRef> std::fmt::Debug for Array<T> {\n    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {\n        let as_vec: Vec<T> = self.clone().into_iter().collect();\n        write!(formatter, \"{:?}\", as_vec)\n    }\n}\n\npub struct IntoIter<T: IsObjectRef> {\n    array: Array<T>,\n    pos: isize,\n    size: isize,\n}\n\nimpl<T: IsObjectRef> Iterator for IntoIter<T> {\n    type Item = T;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        if self.pos < self.size {\n            let item =\n                self.array.get(self.pos)\n                    .expect(\"Can not index as in-bounds position after bounds checking.\\nNote: this error can only be do to an uncaught issue with API bindings.\");\n            self.pos += 1;\n            Some(item)\n        } else {\n            None\n        }\n    }\n}\n\nimpl<T: IsObjectRef> IntoIterator for Array<T> {\n    type Item = T;\n    type IntoIter = IntoIter<T>;\n\n    fn into_iter(self) -> Self::IntoIter {\n        let size = self.len() as isize;\n        IntoIter {\n            array: self,\n            pos: 0,\n            size: size,\n        }\n    }\n}\n\nimpl<T: IsObjectRef> FromIterator<T> for Array<T> {\n    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {\n        Array::from_vec(iter.into_iter().collect()).unwrap()\n    }\n}\n\nimpl<'a, T: IsObjectRef> From<&'a Array<T>> for ArgValue<'a> {\n    fn from(array: &'a Array<T>) -> ArgValue<'a> {\n        (&array.object).into()\n    }\n}\n\nimpl<T: IsObjectRef> From<Array<T>> for RetValue {\n    fn from(array: Array<T>) -> RetValue {\n        array.object.into()\n    }\n}\n\nimpl<'a, T: IsObjectRef> TryFrom<ArgValue<'a>> for Array<T> {\n    type Error = Error;\n\n    fn try_from(array: ArgValue<'a>) -> Result<Array<T>> {\n        let object_ref: ObjectRef = array.try_into()?;\n        // TODO: type check\n        Ok(Array {\n            object: object_ref,\n            _data: PhantomData,\n        })\n    }\n}\n\nimpl<'a, T: IsObjectRef> TryFrom<RetValue> for Array<T> {\n    type Error = Error;\n\n    fn try_from(array: RetValue) -> Result<Array<T>> {\n        let object_ref = array.try_into()?;\n        Ok(Array {\n            object: object_ref,\n            _data: PhantomData,\n        })\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::Array;\n    use crate::function::Result;\n    use crate::object::{IsObjectRef, ObjectRef};\n    use crate::string::String;\n\n    #[test]\n    fn create_array_and_get() -> Result<()> {\n        let vec: Vec<String> = vec![\"foo\".into(), \"bar\".into(), \"baz\".into()];\n        let array = Array::from_vec(vec)?;\n        assert_eq!(array.get(0)?.to_string(), \"foo\");\n        assert_eq!(array.get(1)?.to_string(), \"bar\");\n        assert_eq!(array.get(2)?.to_string(), \"baz\");\n        Ok(())\n    }\n\n    #[test]\n    fn downcast() -> Result<()> {\n        let vec: Vec<String> = vec![\"foo\".into(), \"bar\".into(), \"baz\".into()];\n        let array: ObjectRef = ObjectRef::from_ptr(Array::from_vec(vec)?.into_ptr());\n        let array: Array<ObjectRef> = array.downcast::<Array<ObjectRef>>().unwrap();\n        assert_eq!(array.get(1)?.downcast::<String>().unwrap(), \"bar\");\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/device.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::os::raw::c_void;\nuse std::ptr;\n\nuse crate::errors::Error;\n\nuse tvm_sys::ffi;\n\npub use tvm_sys::device::*;\n\ntrait DeviceExt {\n    /// Checks whether the device exists or not.\n    fn exist(&self) -> bool;\n    fn sync(&self) -> Result<(), Error>;\n    fn max_threads_per_block(&self) -> isize;\n    fn warp_size(&self) -> isize;\n    fn max_shared_memory_per_block(&self) -> isize;\n    fn compute_version(&self) -> isize;\n    fn device_name(&self) -> isize;\n    fn max_clock_rate(&self) -> isize;\n    fn multi_processor_count(&self) -> isize;\n    fn max_thread_dimensions(&self) -> isize;\n}\n\nmacro_rules! impl_device_attrs {\n    ($(($attr_name:ident, $attr_kind:expr));+) => {\n        $(\n                fn $attr_name(&self) -> isize {\n                    get_device_attr(self.device_type as i32, self.device_id as i32, 0)\n                        .expect(\"should not fail\") as isize\n                }\n\n        )+\n    };\n}\n\ncrate::external! {\n    #[name(\"runtime.GetDeviceAttr\")]\n    fn get_device_attr(device_type: i32, device_id: i32, device_kind: i32) -> i32;\n}\n\nimpl DeviceExt for Device {\n    fn exist(&self) -> bool {\n        let exists = get_device_attr(self.device_type as i32, self.device_id as i32, 0)\n            .expect(\"should not fail\");\n\n        exists != 0\n    }\n\n    /// Synchronize the device stream.\n    fn sync(&self) -> Result<(), Error> {\n        check_call!(ffi::TVMSynchronize(\n            self.device_type as i32,\n            self.device_id as i32,\n            ptr::null_mut() as *mut c_void\n        ));\n        Ok(())\n    }\n\n    impl_device_attrs!((max_threads_per_block, 1);\n        (warp_size, 2);\n        (max_shared_memory_per_block, 3);\n        (compute_version, 4);\n        (device_name, 5);\n        (max_clock_rate, 6);\n        (multi_processor_count, 7);\n        (max_thread_dimensions, 8));\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn sync() {\n        let dev = Device::cpu(0);\n        assert!(dev.sync().is_ok())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/errors.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::DataType;\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\n#[error(\"Function was not set in `function::Builder`\")]\npub struct FunctionNotFoundError;\n\n#[derive(Debug, Error)]\n#[error(\"Expected type `{expected}` but found `{actual}`\")]\npub struct TypeMismatchError {\n    pub expected: String,\n    pub actual: String,\n}\n\n#[derive(Debug, Error)]\npub enum NDArrayError {\n    #[error(\"Cannot convert from an empty array.\")]\n    EmptyArray,\n    #[error(\"Invalid datatype when attempting to convert ndarray.\")]\n    InvalidDatatype(#[from] tvm_sys::datatype::ParseDataTypeError),\n    #[error(\"a shape error occurred in the Rust ndarray library\")]\n    ShapeError(#[from] ndarray::ShapeError),\n    #[error(\"Expected type `{expected}` but found `{actual}`\")]\n    DataTypeMismatch {\n        expected: DataType,\n        actual: DataType,\n    },\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"{0}\")]\n    Downcast(#[from] tvm_sys::errors::ValueDowncastError),\n    #[error(\"raw pointer passed across boundary was null\")]\n    Null,\n    #[error(\"failed to load module due to invalid path {0}\")]\n    ModuleLoadPath(String),\n    #[error(\"failed to convert String into CString due to embedded nul character\")]\n    ToCString(#[from] std::ffi::NulError),\n    #[error(\"failed to convert CString into String\")]\n    FromCString(#[from] std::ffi::IntoStringError),\n    #[error(\"Handle `{0}` is null.\")]\n    NullHandle(String),\n    #[error(\"{0}\")]\n    NDArray(#[from] NDArrayError),\n    #[error(\"{0}\")]\n    CallFailed(String),\n    #[error(\"this case will never occur\")]\n    Infallible(#[from] std::convert::Infallible),\n    #[error(\"a panic occurred while executing a Rust packed function\")]\n    Panic,\n    #[error(\n        \"one or more error diagnostics were emitted, please check diagnostic render for output.\"\n    )]\n    DiagnosticError(String),\n    #[error(\"{0}\")]\n    Raw(String),\n}\n\nimpl Error {\n    pub fn from_raw_tvm(raw: &str) -> Error {\n        let err_header = raw.find(\":\").unwrap_or(0);\n        let (err_ty, err_content) = raw.split_at(err_header);\n        match err_ty {\n            \"DiagnosticError\" => Error::DiagnosticError((&err_content[1..]).into()),\n            _ => Error::Raw(raw.into()),\n        }\n    }\n}\n\nimpl Error {\n    pub fn downcast(actual_type: String, expected_type: &'static str) -> Error {\n        Self::Downcast(tvm_sys::errors::ValueDowncastError {\n            actual_type,\n            expected_type,\n        })\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/function.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! This module provides an idiomatic Rust API for creating and working with TVM functions.\n//!\n//! For calling an already registered TVM function use [`function::Builder`]\n//! To register a TVM packed function from Rust side either\n//! use [`function::register`] or the macro [`register_global_func`].\n//!\n//! See the tests and examples repository for more examples.\n\nuse std::convert::{TryFrom, TryInto};\nuse std::sync::Arc;\nuse std::{\n    ffi::CString,\n    os::raw::{c_char, c_int},\n    ptr, str,\n};\n\nuse crate::errors::Error;\n\npub use super::to_function::{RawArgs, ToFunction, Typed};\nuse crate::object::AsArgValue;\npub use tvm_sys::{ffi, ArgValue, RetValue};\n\npub type Result<T> = std::result::Result<T, Error>;\n\n#[derive(Debug, Hash)]\nstruct FunctionPtr {\n    handle: ffi::TVMFunctionHandle,\n}\n\n// NB(@jroesch): I think this is ok, need to double check,\n// if not we should mutex the pointer or move to Rc.\nunsafe impl Send for FunctionPtr {}\nunsafe impl Sync for FunctionPtr {}\n\nimpl FunctionPtr {\n    fn from_raw(handle: ffi::TVMFunctionHandle) -> Self {\n        FunctionPtr { handle }\n    }\n}\n\nimpl Drop for FunctionPtr {\n    fn drop(&mut self) {\n        check_call!(ffi::TVMFuncFree(self.handle));\n    }\n}\n\n/// An owned thread-safe version of `tvm::PackedFunc` for consumption in Rust.\n#[derive(Debug, Hash)]\npub struct Function {\n    inner: Arc<FunctionPtr>,\n}\n\nimpl Function {\n    pub(crate) fn from_raw(handle: ffi::TVMFunctionHandle) -> Self {\n        Function {\n            inner: Arc::new(FunctionPtr::from_raw(handle)),\n        }\n    }\n\n    pub unsafe fn null() -> Self {\n        Function::from_raw(std::ptr::null_mut())\n    }\n\n    /// For a given function, it returns a function by name.\n    pub fn get<S: AsRef<str>>(name: S) -> Option<Function> {\n        let name = CString::new(name.as_ref()).unwrap();\n        let mut handle = ptr::null_mut() as ffi::TVMFunctionHandle;\n\n        check_call!(ffi::TVMFuncGetGlobal(\n            name.as_ptr() as *const c_char,\n            &mut handle as *mut _\n        ));\n\n        if handle.is_null() {\n            None\n        } else {\n            Some(Function::from_raw(handle))\n        }\n    }\n\n    pub fn get_boxed<F, S>(name: S) -> Option<Box<F>>\n    where\n        S: AsRef<str>,\n        F: ?Sized,\n        Self: Into<Box<F>>,\n    {\n        Self::get(name).map(|f| f.into())\n    }\n\n    /// Returns the underlying TVM function handle.\n    pub fn handle(&self) -> ffi::TVMFunctionHandle {\n        self.inner.handle\n    }\n\n    /// Calls the function that created from `Builder`.\n    pub fn invoke<'a>(&self, arg_buf: Vec<ArgValue<'a>>) -> Result<RetValue> {\n        let num_args = arg_buf.len();\n        let (mut values, mut type_codes): (Vec<ffi::TVMValue>, Vec<ffi::TVMArgTypeCode>) =\n            arg_buf.into_iter().map(|arg| arg.to_tvm_value()).unzip();\n\n        let mut ret_val = ffi::TVMValue { v_int64: 0 };\n        let mut ret_type_code = 0i32;\n\n        let ret_code = unsafe {\n            ffi::TVMFuncCall(\n                self.handle(),\n                values.as_mut_ptr() as *mut ffi::TVMValue,\n                type_codes.as_mut_ptr() as *mut c_int,\n                num_args as c_int,\n                &mut ret_val as *mut _,\n                &mut ret_type_code as *mut _,\n            )\n        };\n\n        if ret_code != 0 {\n            let raw_error = crate::get_last_error();\n            let error = match Error::from_raw_tvm(raw_error) {\n                Error::Raw(string) => Error::CallFailed(string),\n                e => e,\n            };\n            return Err(error);\n        }\n\n        let rv = RetValue::from_tvm_value(ret_val, ret_type_code as u32);\n\n        Ok(rv)\n    }\n}\n\nmacro_rules! impl_to_fn {\n    () => { impl_to_fn!(@impl); };\n    ($t:ident, $($ts:ident,)*) => { impl_to_fn!(@impl $t, $($ts,)*); impl_to_fn!($($ts,)*); };\n    (@impl $($t:ident,)*) => {\n        impl<Err, Out, $($t,)*> From<Function> for Box<dyn Fn($($t,)*) -> Result<Out>>\n        where\n            Error: From<Err>,\n            Out: TryFrom<RetValue, Error = Err>,\n            $($t: for<'a> AsArgValue<'a>),*\n        {\n            fn from(func: Function) -> Self {\n                #[allow(non_snake_case)]\n                Box::new(move |$($t : $t),*| {\n                    let args = vec![ $((&$t).as_arg_value()),* ];\n                    Ok(func.invoke(args)?.try_into()?)\n                })\n            }\n        }\n    };\n}\n\nimpl_to_fn!(T1, T2, T3, T4, T5, T6,);\n\nimpl Clone for Function {\n    fn clone(&self) -> Function {\n        Function {\n            inner: self.inner.clone(),\n        }\n    }\n}\n\nimpl From<Function> for RetValue {\n    fn from(func: Function) -> RetValue {\n        RetValue::FuncHandle(func.handle())\n    }\n}\n\nimpl TryFrom<RetValue> for Function {\n    type Error = Error;\n\n    fn try_from(ret_value: RetValue) -> Result<Function> {\n        match ret_value {\n            RetValue::FuncHandle(handle) => Ok(Function::from_raw(handle)),\n            _ => Err(Error::downcast(\n                format!(\"{:?}\", ret_value),\n                \"FunctionHandle\",\n            )),\n        }\n    }\n}\n\nimpl<'a> From<&'a Function> for ArgValue<'a> {\n    fn from(func: &'a Function) -> ArgValue<'a> {\n        if func.handle().is_null() {\n            ArgValue::Null\n        } else {\n            ArgValue::FuncHandle(func.handle())\n        }\n    }\n}\n\nimpl<'a> TryFrom<ArgValue<'a>> for Function {\n    type Error = Error;\n\n    fn try_from(arg_value: ArgValue<'a>) -> Result<Function> {\n        match arg_value {\n            ArgValue::FuncHandle(handle) => Ok(Function::from_raw(handle)),\n            _ => Err(Error::downcast(\n                format!(\"{:?}\", arg_value),\n                \"FunctionHandle\",\n            )),\n        }\n    }\n}\n\nimpl<'a> TryFrom<&ArgValue<'a>> for Function {\n    type Error = Error;\n\n    fn try_from(arg_value: &ArgValue<'a>) -> Result<Function> {\n        match arg_value {\n            ArgValue::FuncHandle(handle) => Ok(Function::from_raw(*handle)),\n            _ => Err(Error::downcast(\n                format!(\"{:?}\", arg_value),\n                \"FunctionHandle\",\n            )),\n        }\n    }\n}\n\n/// Registers a Rust function with an arbitrary type signature in\n/// the TVM registry.\n///\n///\n/// A function is convertible if and only if its arguments and return types are convertible\n/// to and from TVM values respectively.\n///\n/// Use [`register_override`] if control of overriding existing global TVM function\n/// is required, this function will panic if a function is already registered.\n///\n/// ## Example\n///\n/// ```\n/// # use tvm_rt::{ArgValue, RetValue};\n/// # use tvm_rt::function::{Function, Result, register};\n///\n/// fn sum(x: i64, y: i64, z: i64) -> i64 {\n///     x + y + z\n/// }\n///\n/// register(sum, \"mysum\".to_owned()).unwrap();\n/// let func = Function::get(\"mysum\").unwrap();\n/// let boxed_fn: Box<dyn Fn(i64, i64, i64) -> Result<i64>> = func.into();\n/// let ret = boxed_fn(10, 20, 30).unwrap();\n/// assert_eq!(ret, 60);\n/// ```\npub fn register<F, I, O, S: Into<String>>(f: F, name: S) -> Result<()>\nwhere\n    F: ToFunction<I, O>,\n    F: Typed<I, O>,\n{\n    register_override(f, name, false)\n}\n\n/// Register a function with explicit control over whether to override an existing registration or not.\n///\n/// See `register` for more details on how to use the registration API.\npub fn register_override<F, I, O, S: Into<String>>(f: F, name: S, override_: bool) -> Result<()>\nwhere\n    F: ToFunction<I, O>,\n    F: Typed<I, O>,\n{\n    let func = f.to_function();\n    let name = name.into();\n    // Not sure about this code\n    let handle = func.handle();\n    let name = CString::new(name)?;\n    check_call!(ffi::TVMFuncRegisterGlobal(\n        name.into_raw(),\n        handle,\n        override_ as c_int\n    ));\n\n    Ok(())\n}\n\npub fn register_untyped<S: Into<String>>(\n    f: for<'a> fn(Vec<ArgValue<'a>>) -> Result<RetValue>,\n    name: S,\n    override_: bool,\n) -> Result<()> {\n    //TODO(@jroesch): can we unify the untpyed and typed registration functions.\n    let func = ToFunction::<RawArgs, RetValue>::to_function(f);\n    let name = name.into();\n    // Not sure about this code\n    let handle = func.handle();\n    let name = CString::new(name)?;\n    check_call!(ffi::TVMFuncRegisterGlobal(\n        name.into_raw(),\n        handle,\n        override_ as c_int\n    ));\n    Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use crate::function::Function;\n\n    static CANARY: &str = \"runtime.ModuleLoadFromFile\";\n\n    #[test]\n    fn get_fn() {\n        assert!(Function::get(CANARY).is_some());\n        assert!(Function::get(\"does not exists!\").is_none());\n    }\n\n    #[test]\n    fn register_and_call_closure0() {\n        use crate::function;\n        use function::Result;\n\n        fn constfn() -> i64 {\n            return 10;\n        }\n\n        function::register_override(constfn, \"constfn\".to_owned(), true).unwrap();\n\n        let func = Function::get_boxed::<dyn Fn() -> Result<i32>, _>(\"constfn\").unwrap();\n        let ret = func().unwrap();\n        assert_eq!(ret, 10);\n    }\n\n    #[test]\n    fn register_and_call_closure1() {\n        use crate::function::{self};\n\n        fn ident(x: i64) -> i64 {\n            return x;\n        }\n\n        function::register_override(ident, \"ident\".to_owned(), true).unwrap();\n        let func = Function::get_boxed::<dyn Fn(i32) -> Result<i32>, _>(\"ident\").unwrap();\n        assert_eq!(func(60).unwrap(), 60);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/graph_rt.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryInto;\n\nuse crate::Function;\nuse crate::{function::Result, ByteArray, Device, Module, NDArray};\n\n/// An instance of the C++ graph executor.\n///\n/// An efficient and light weight runtime for static deep learning models.\npub struct GraphRt {\n    /// The backing graph executor module which exposes a set of packed functions\n    /// which can be invoked by a client.\n    ///\n    /// In the graph executor module, it exposes create, load_params, set_input, get_output, and run.\n    module: Module,\n}\n\nimpl GraphRt {\n    /// Create a graph executor directly from a runtime module.\n    pub fn from_module(module: Module, dev: Device) -> Result<GraphRt> {\n        let default: Box<dyn Fn(Device) -> Result<Module>> =\n            module.get_function(\"default\", false)?.into();\n\n        Ok(Self {\n            module: default(dev)?,\n        })\n    }\n\n    /// Create a graph executor from the deprecated graph, lib, dev triple.\n    pub fn create_from_parts(graph: &str, lib: Module, dev: Device) -> Result<Self> {\n        let runtime_create_fn = Function::get(\"tvm.graph_executor.create\").unwrap();\n\n        let runtime_create_fn_ret = runtime_create_fn.invoke(vec![\n            graph.into(),\n            (&lib).into(),\n            (&dev.device_type).into(),\n            // NOTE you must pass the device id in as i32 because that's what TVM expects\n            (dev.device_id as i32).into(),\n        ]);\n\n        let graph_executor_module: Module = runtime_create_fn_ret?.try_into()?;\n        Ok(Self {\n            module: graph_executor_module,\n        })\n    }\n\n    /// Load the parameters of the model into the runtime.\n    pub fn load_params<P>(&mut self, params: P) -> Result<()>\n    where\n        P: Into<ByteArray>,\n    {\n        let load_param_fn = self.module.get_function(\"load_params\", false)?;\n\n        let params: ByteArray = params.into();\n\n        load_param_fn.invoke(vec![(&params).into()])?;\n\n        Ok(())\n    }\n\n    /// Set the input with name `name` with the value of `input`.\n    pub fn set_input(&mut self, name: &str, input: NDArray) -> Result<()> {\n        let ref set_input_fn = self.module.get_function(\"set_input\", false)?;\n\n        set_input_fn.invoke(vec![name.into(), (&input).into()])?;\n        Ok(())\n    }\n\n    /// Run the graph module, once setting parameters and inputs.\n    pub fn run(&mut self) -> Result<()> {\n        let ref run_fn = self.module.get_function(\"run\", false)?;\n\n        // execute the run function. Note that it has no argument\n        run_fn.invoke(vec![])?;\n        Ok(())\n    }\n\n    /// Extract the ith output from the graph executor and returns it.\n    pub fn get_output(&mut self, i: i64) -> Result<NDArray> {\n        let get_output_fn = self.module.get_function(\"get_output\", false)?;\n        get_output_fn.invoke(vec![i.into()])?.try_into()\n    }\n\n    /// Extract the ith output from the graph executor and write the results into output.\n    pub fn get_output_into(&mut self, i: i64, output: NDArray) -> Result<()> {\n        let get_output_fn = self.module.get_function(\"get_output\", false)?;\n        get_output_fn.invoke(vec![i.into(), (&output).into()])?;\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! [TVM](https://github.com/apache/tvm) is a compiler stack for deep learning systems.\n//!\n//! This crate provides an idiomatic Rust API for TVM runtime.\n//!\n//! The TVM runtime API contains the data structures used by higher-level TVM executors.\n//! Specifically it exposes the basic types such as NDArray, as well as the more general object system.\n//! The TVM object system enables cross-language interoperability including that of closures for all\n//! supported languages including C++, and Python.\n\n// Macro to check the return call to TVM runtime shared library.\n\n#[macro_export]\nmacro_rules! tvm_call {\n    ($e:expr) => {{\n        if unsafe { $e } != 0 {\n            Err($crate::get_last_error().into())\n        } else {\n            Ok(())\n        }\n    }};\n}\n\n#[macro_export]\nmacro_rules! check_call {\n    ($e:expr) => {{\n        if unsafe { $e } != 0 {\n            panic!(\"{}\", $crate::get_last_error());\n        }\n    }};\n}\n\n// Define all sumodules.\npub mod array;\npub mod device;\npub mod errors;\npub mod function;\npub mod graph_rt;\npub mod map;\npub mod module;\npub mod ndarray;\npub mod object;\npub mod string;\nmod to_function;\n\npub use object::*;\npub use string::*;\n\nuse std::{\n    ffi::{CStr, CString},\n    str,\n};\n\npub use crate::{\n    device::{Device, DeviceType},\n    errors::*,\n    function::Function,\n    module::Module,\n    ndarray::NDArray,\n};\n\npub use function::{ArgValue, RetValue};\npub use tvm_sys::byte_array::ByteArray;\npub use tvm_sys::datatype::DataType;\nuse tvm_sys::ffi;\n\npub use tvm_macros::external;\n\n/// Gets the last error message.\npub fn get_last_error() -> &'static str {\n    unsafe {\n        match CStr::from_ptr(ffi::TVMGetLastError()).to_str() {\n            Ok(s) => s,\n            Err(_) => \"Invalid UTF-8 message\",\n        }\n    }\n}\n\npub(crate) fn set_last_error<E: std::error::Error>(err: &E) {\n    let c_string = CString::new(err.to_string()).unwrap();\n    unsafe {\n        ffi::TVMAPISetLastError(c_string.as_ptr());\n    }\n}\n\n/// Outputs the current TVM version.\npub fn version() -> &'static str {\n    match str::from_utf8(ffi::TVM_VERSION) {\n        Ok(s) => s,\n        Err(_) => \"Invalid UTF-8 string\",\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use crate::{ByteArray, DataType, Device};\n    use std::{convert::TryInto, str::FromStr};\n\n    #[test]\n    fn print_version() {\n        println!(\"TVM version: {}\", version());\n    }\n\n    #[test]\n    fn set_error() {\n        let err = errors::NDArrayError::EmptyArray;\n        set_last_error(&err);\n        assert_eq!(\n            get_last_error().trim(),\n            errors::NDArrayError::EmptyArray.to_string()\n        );\n    }\n\n    // todo(@jroesch): #8800 Follow up with ByteArray RetValue ownership.\n    // #[test]\n    // fn bytearray() {\n    //     let w = vec![1u8, 2, 3, 4, 5];\n    //     let v = ByteArray::from(w.as_slice());\n    //     let tvm: ByteArray = RetValue::from(v).try_into().unwrap();\n    //     assert_eq!(\n    //         tvm.data(),\n    //         w.iter().copied().collect::<Vec<u8>>().as_slice()\n    //     );\n    // }\n\n    #[test]\n    fn ty() {\n        let t = DataType::from_str(\"int32\").unwrap();\n        let tvm: DataType = RetValue::from(t).try_into().unwrap();\n        assert_eq!(tvm, t);\n    }\n\n    #[test]\n    fn device() {\n        let c = Device::from_str(\"cuda\").unwrap();\n        let tvm: Device = RetValue::from(c).try_into().unwrap();\n        assert_eq!(tvm, c);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/map.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::collections::HashMap;\nuse std::convert::{TryFrom, TryInto};\nuse std::iter::FromIterator;\nuse std::marker::PhantomData;\n\nuse crate::object::debug_print;\n\nuse crate::array::Array;\nuse crate::errors::Error;\nuse crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};\nuse crate::ArgValue;\nuse crate::{\n    external,\n    function::{Function, Result},\n    RetValue,\n};\n\n#[repr(C)]\n#[derive(Clone)]\npub struct Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    object: ObjectRef,\n    _data: PhantomData<(K, V)>,\n}\n\n// TODO(@jroesch): convert to use generics instead of casting inside\n// the implementation.\nexternal! {\n   #[name(\"runtime.MapSize\")]\n   fn map_size(map: ObjectRef) -> i64;\n   #[name(\"runtime.MapGetItem\")]\n   fn map_get_item(map_object: ObjectRef, key: ObjectRef) -> ObjectRef;\n   #[name(\"runtime.MapCount\")]\n   fn map_count(map: ObjectRef, key: ObjectRef) -> ObjectRef;\n   #[name(\"runtime.MapItems\")]\n   fn map_items(map: ObjectRef) -> Array<ObjectRef>;\n}\n\nimpl<'a, K: 'a, V: 'a> FromIterator<(&'a K, &'a V)> for Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    fn from_iter<T: IntoIterator<Item = (&'a K, &'a V)>>(iter: T) -> Self {\n        let iter = iter.into_iter();\n        let (lower_bound, upper_bound) = iter.size_hint();\n        let mut buffer: Vec<ArgValue> = Vec::with_capacity(upper_bound.unwrap_or(lower_bound) * 2);\n        for (k, v) in iter {\n            buffer.push(k.into_arg_value());\n            buffer.push(v.into_arg_value());\n        }\n        Self::from_data(buffer).expect(\"failed to convert from data\")\n    }\n}\n\nimpl<K, V> Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    pub fn from_data(data: Vec<ArgValue>) -> Result<Map<K, V>> {\n        let func = Function::get(\"runtime.Map\").expect(\n            \"runtime.Map function is not registered, this is most likely a build or linking error\",\n        );\n\n        let map_data: ObjectPtr<Object> = func.invoke(data)?.try_into()?;\n\n        debug_assert!(\n            map_data.count() >= 1,\n            \"map_data count is {}\",\n            map_data.count()\n        );\n\n        Ok(Map {\n            object: map_data.into(),\n            _data: PhantomData,\n        })\n    }\n\n    pub fn get(&self, key: &K) -> Result<V>\n    where\n        V: TryFrom<RetValue, Error = Error>,\n    {\n        let key = key.clone();\n        let oref: ObjectRef = map_get_item(self.object.clone(), key.upcast())?;\n        oref.downcast()\n    }\n\n    pub fn empty() -> Self {\n        Self::from_iter(vec![].into_iter())\n    }\n\n    //(@jroesch): I don't think this is a correct implementation.\n    pub fn null() -> Self {\n        Map {\n            object: ObjectRef::null(),\n            _data: PhantomData,\n        }\n    }\n}\n\npub struct IntoIter<K, V> {\n    // NB: due to FFI this isn't as lazy as one might like\n    key_and_values: Array<ObjectRef>,\n    next_key: i64,\n    _data: PhantomData<(K, V)>,\n}\n\nimpl<K, V> Iterator for IntoIter<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    type Item = (K, V);\n\n    #[inline]\n    fn next(&mut self) -> Option<(K, V)> {\n        if self.next_key < self.key_and_values.len() {\n            let key = self\n                .key_and_values\n                .get(self.next_key as isize)\n                .expect(\"this should always succeed\");\n            let value = self\n                .key_and_values\n                .get((self.next_key as isize) + 1)\n                .expect(\"this should always succeed\");\n            self.next_key += 2;\n            Some((key.downcast().unwrap(), value.downcast().unwrap()))\n        } else {\n            None\n        }\n    }\n\n    #[inline]\n    fn size_hint(&self) -> (usize, Option<usize>) {\n        ((self.key_and_values.len() / 2) as usize, None)\n    }\n}\n\nimpl<K, V> IntoIterator for Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    type Item = (K, V);\n    type IntoIter = IntoIter<K, V>;\n\n    fn into_iter(self) -> IntoIter<K, V> {\n        let items = map_items(self.object).expect(\"unable to get map items\");\n        IntoIter {\n            key_and_values: items,\n            next_key: 0,\n            _data: PhantomData,\n        }\n    }\n}\n\nuse std::fmt;\n\nimpl<K, V> fmt::Debug for Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {\n        let ctr = debug_print(self.object.clone()).unwrap();\n        fmt.write_fmt(format_args!(\"{:?}\", ctr))\n    }\n}\n\nimpl<K, V, S> From<Map<K, V>> for HashMap<K, V, S>\nwhere\n    K: Eq + std::hash::Hash,\n    K: IsObjectRef,\n    V: IsObjectRef,\n    S: std::hash::BuildHasher + std::default::Default,\n{\n    fn from(map: Map<K, V>) -> HashMap<K, V, S> {\n        HashMap::from_iter(map.into_iter())\n    }\n}\n\nimpl<'a, K, V> From<&'a Map<K, V>> for ArgValue<'a>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    fn from(map: &'a Map<K, V>) -> ArgValue<'a> {\n        (&map.object).into()\n    }\n}\n\nimpl<K, V> From<Map<K, V>> for RetValue\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    fn from(map: Map<K, V>) -> RetValue {\n        map.object.into()\n    }\n}\n\nimpl<'a, K, V> TryFrom<ArgValue<'a>> for Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    type Error = Error;\n\n    fn try_from(array: ArgValue<'a>) -> Result<Map<K, V>> {\n        let object_ref: ObjectRef = array.try_into()?;\n        // TODO: type check\n        Ok(Map {\n            object: object_ref,\n            _data: PhantomData,\n        })\n    }\n}\n\nimpl<K, V> TryFrom<RetValue> for Map<K, V>\nwhere\n    K: IsObjectRef,\n    V: IsObjectRef,\n{\n    type Error = Error;\n\n    fn try_from(array: RetValue) -> Result<Map<K, V>> {\n        let object_ref = array.try_into()?;\n        // TODO: type check\n        Ok(Map {\n            object: object_ref,\n            _data: PhantomData,\n        })\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use std::collections::HashMap;\n\n    use super::*;\n    use crate::string::String as TString;\n\n    #[test]\n    fn test_from_into_hash_map() {\n        let mut std_map: HashMap<TString, TString> = HashMap::new();\n        std_map.insert(\"key1\".into(), \"value1\".into());\n        std_map.insert(\"key2\".into(), \"value2\".into());\n        let tvm_map = Map::from_iter(std_map.iter());\n        let back_map = tvm_map.into();\n        assert_eq!(std_map, back_map);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/module.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! Provides the [`Module`] type and methods for working with runtime TVM modules.\n\nuse std::{\n    ffi::CString,\n    os::raw::{c_char, c_int},\n    path::Path,\n    ptr,\n};\n\nuse crate::object::Object;\nuse tvm_macros::Object;\nuse tvm_sys::ffi;\n\nuse crate::errors::Error;\nuse crate::String as TString;\nuse crate::{errors, function::Function};\n\n/// Wrapper around TVM module handle which contains an entry function.\n/// The entry function can be applied to an imported module through [`entry_func`].\n///\n/// [`entry_func`]:struct.Module.html#method.entry_func\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Module\"]\n#[type_key = \"runtime.Module\"]\npub struct ModuleNode {\n    base: Object,\n}\n\ncrate::external! {\n    #[name(\"runtime.RuntimeEnabled\")]\n    fn runtime_enabled(target: CString) -> i32;\n\n    #[name(\"runtime.ModuleLoadFromFile\")]\n    fn load_from_file(file_name: CString, format: CString) -> Module;\n\n    #[name(\"runtime.ModuleSaveToFile\")]\n    fn save_to_file(module: Module, name: TString, fmt: TString);\n\n    // TODO(@jroesch): we need to refactor this\n    #[name(\"tvm.relay.module_export_library\")]\n    fn export_library(module: Module, file_name: TString);\n}\n\nimpl Module {\n    pub fn default_fn(&mut self) -> Result<Function, Error> {\n        self.get_function(\"default\", true)\n    }\n\n    /// Gets a function by name from a registered module.\n    pub fn get_function(&self, name: &str, query_import: bool) -> Result<Function, Error> {\n        let name = CString::new(name)?;\n        let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;\n\n        check_call!(ffi::TVMModGetFunction(\n            self.handle(),\n            name.as_ptr() as *const c_char,\n            query_import as c_int,\n            &mut fhandle as *mut _\n        ));\n\n        if fhandle.is_null() {\n            return Err(errors::Error::NullHandle(name.into_string()?.to_string()));\n        }\n\n        Ok(Function::from_raw(fhandle))\n    }\n\n    /// Imports a dependent module such as `.ptx` for cuda gpu.\n    pub fn import_module(&self, dependent_module: Module) {\n        check_call!(ffi::TVMModImport(self.handle(), dependent_module.handle()))\n    }\n\n    /// Loads a module shared library from path.\n    pub fn load<P: AsRef<Path>>(path: &P) -> Result<Module, Error> {\n        let ext = CString::new(\n            path.as_ref()\n                .extension()\n                .unwrap_or_else(|| std::ffi::OsStr::new(\"\"))\n                .to_str()\n                .ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,\n        )?;\n\n        let cpath = CString::new(\n            path.as_ref()\n                .to_str()\n                .ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,\n        )?;\n\n        let module = load_from_file(cpath, ext)?;\n        Ok(module)\n    }\n\n    pub fn save_to_file(&self, name: String, fmt: String) -> Result<(), Error> {\n        save_to_file(self.clone(), name.into(), fmt.into())\n    }\n\n    pub fn export_library(&self, name: String) -> Result<(), Error> {\n        export_library(self.clone(), name.into())\n    }\n\n    /// Checks if a target device is enabled for a module.\n    pub fn enabled(&self, target: &str) -> bool {\n        let target = CString::new(target).unwrap();\n        let enabled = runtime_enabled(target).unwrap();\n        enabled != 0\n    }\n\n    /// Returns the underlying module handle.\n    pub unsafe fn handle(&self) -> ffi::TVMModuleHandle {\n        self.0.clone().unwrap().into_raw() as *mut _\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/ndarray.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! This module implements the [`NDArray`] type for working with *TVM tensors* or\n//! coverting from a Rust's ndarray to TVM `NDArray`.\n//!\n//! One can create an empty NDArray given the shape, device and dtype using [`empty`].\n//! To create an NDArray from a mutable buffer in cpu use [`copy_from_buffer`].\n//! To copy an NDArray to different device use [`copy_to_device`].\n//!\n//! Given a [`Rust's dynamic ndarray`], one can convert it to TVM NDArray as follows:\n//!\n//! # Example\n//!\n//! ```\n//! # use tvm_rt::{NDArray, DataType, Device};\n//! # use ndarray::{Array, ArrayD};\n//! # use std::str::FromStr;\n//! use std::convert::TryFrom;\n//!\n//! let a = Array::from_shape_vec((2, 2), vec![1f32, 2., 3., 4.])\n//!     .unwrap()\n//!     .into_dyn(); // Rust's ndarray\n//! let nd = NDArray::from_rust_ndarray(&a, Device::cpu(0), DataType::from_str(\"float32\").unwrap()).unwrap();\n//! assert_eq!(nd.shape(), &[2, 2]);\n//! let rnd: ArrayD<f32> = ArrayD::try_from(&nd).unwrap();\n//! assert!(rnd.all_close(&a, 1e-8f32));\n//! ```\n//!\n//! [`Rust's dynamic ndarray`]:https://docs.rs/ndarray/0.12.1/ndarray/\n//! [`copy_from_buffer`]:struct.NDArray.html#method.copy_from_buffer\n//! [`copy_to_device`]:struct.NDArray.html#method.copy_to_device\n\nuse std::ffi::c_void;\nuse std::{borrow::Cow, convert::TryInto};\nuse std::{convert::TryFrom, mem, os::raw::c_int, ptr, slice, str::FromStr};\n\nuse mem::size_of;\nuse tvm_macros::Object;\nuse tvm_sys::ffi::DLTensor;\nuse tvm_sys::{ffi, ByteArray, DataType, Device};\n\nuse ndarray::{Array, ArrayD};\nuse num_traits::Num;\n\nuse crate::errors::NDArrayError;\n\nuse crate::object::{Object, ObjectPtr, ObjectRef};\n\n/// See the [`module-level documentation`](../ndarray/index.html) for more details.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"NDArray\"]\n#[type_key = \"runtime.NDArray\"]\npub struct NDArrayContainer {\n    base: Object,\n    // Container Base\n    dl_tensor: DLTensor,\n    manager_ctx: *mut c_void,\n    shape: ObjectRef,\n}\n\nimpl NDArrayContainer {\n    pub(crate) fn from_raw(handle: ffi::TVMArrayHandle) -> Option<ObjectPtr<Self>> {\n        let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;\n        let base_ptr = unsafe { (handle as *mut i8).offset(-base_offset) };\n        let object_ptr = ObjectPtr::from_raw(base_ptr.cast());\n        object_ptr.map(|ptr| {\n            ptr.downcast::<NDArrayContainer>()\n                .expect(\"we know this is an NDArray container\")\n        })\n    }\n\n    pub fn leak<'a>(object_ptr: ObjectPtr<NDArrayContainer>) -> &'a mut NDArrayContainer\n    where\n        NDArrayContainer: 'a,\n    {\n        let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;\n        unsafe {\n            &mut *std::mem::ManuallyDrop::new(object_ptr)\n                .ptr\n                .as_ptr()\n                .cast::<u8>()\n                .offset(base_offset)\n                .cast::<NDArrayContainer>()\n        }\n    }\n\n    pub fn as_mut_ptr<'a>(object_ptr: &ObjectPtr<NDArrayContainer>) -> *mut NDArrayContainer\n    where\n        NDArrayContainer: 'a,\n    {\n        let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;\n        unsafe {\n            object_ptr\n                .ptr\n                .as_ptr()\n                .cast::<u8>()\n                .offset(base_offset)\n                .cast::<NDArrayContainer>()\n        }\n    }\n}\n\nfn cow_usize<'a>(slice: &[i64]) -> Cow<'a, [usize]> {\n    if std::mem::size_of::<usize>() == 64 {\n        debug_assert!(slice.iter().all(|&x| x >= 0));\n        let shape: &[usize] = unsafe { std::mem::transmute(slice) };\n        Cow::Borrowed(shape)\n    } else {\n        let shape: Vec<usize> = slice\n            .iter()\n            .map(|&x| usize::try_from(x).unwrap_or_else(|_| panic!(\"Cannot fit into usize: {}\", x)))\n            .collect();\n        Cow::Owned(shape)\n    }\n}\n\nimpl NDArray {\n    pub(crate) fn _from_raw(handle: ffi::TVMArrayHandle) -> Self {\n        let ptr = NDArrayContainer::from_raw(handle);\n        NDArray(ptr)\n    }\n\n    // I think these should be marked as unsafe functions? projecting a reference is bad news.\n    pub fn as_dltensor(&self) -> &DLTensor {\n        &self.dl_tensor\n    }\n\n    pub(crate) fn as_raw_dltensor(&self) -> *mut DLTensor {\n        unsafe { std::mem::transmute(self.as_dltensor()) }\n    }\n\n    pub fn is_view(&self) -> bool {\n        false\n    }\n\n    /// Returns the shape of the NDArray.\n    pub fn shape(&self) -> &[i64] {\n        let arr = self.as_dltensor();\n        if arr.shape.is_null() || arr.data.is_null() {\n            &[]\n        } else {\n            unsafe { slice::from_raw_parts(arr.shape, self.ndim()) }\n        }\n    }\n\n    /// Returns the shape of the NDArray as a &[usize]\n    ///\n    /// On 64-bit platforms, this is zero-cost and uses the shape from the DLTensor.\n    /// On other platforms, this copies into a buffer.\n    pub fn shape_usize(&self) -> Cow<[usize]> {\n        cow_usize(self.shape())\n    }\n\n    /// Returns the strides of the underlying NDArray.\n    pub fn strides(&self) -> Option<&[i64]> {\n        let arr = self.as_dltensor();\n        if arr.strides.is_null() {\n            None\n        } else {\n            Some(unsafe { slice::from_raw_parts(arr.strides, self.ndim()) })\n        }\n    }\n\n    /// Returns the strides of the NDArray as a &[usize]\n    ///\n    /// On 64-bit platforms, this is zero-cost and uses the strides from the DLTensor.\n    /// On other platforms, this copies into a buffer.\n    pub fn strides_usize(&self) -> Option<Cow<[usize]>> {\n        self.strides().map(cow_usize)\n    }\n\n    /// Returns true if the tensor is empty\n    pub fn is_empty(&self) -> bool {\n        self.as_dltensor().data.is_null()\n    }\n\n    /// Returns the total number of entries of the NDArray.\n    pub fn len(&self) -> usize {\n        let len: i64 = self.shape().iter().product();\n        usize::try_from(len).unwrap_or_else(|_| panic!(\"bad len: {}\", len))\n    }\n\n    /// Returns the total bytes taken up by the data.\n    /// This is equal to `nd.len() * nd.dtype().itemsize()`\n    pub fn size(&self) -> usize {\n        self.len() * self.dtype().itemsize()\n    }\n\n    /// Returns the device which the NDArray was defined.\n    pub fn device(&self) -> Device {\n        self.as_dltensor().device.into()\n    }\n\n    /// Returns the type of the entries of the NDArray.\n    pub fn dtype(&self) -> DataType {\n        self.as_dltensor().dtype.into()\n    }\n\n    /// Returns the number of dimensions of the NDArray.\n    pub fn ndim(&self) -> usize {\n        self.as_dltensor()\n            .ndim\n            .try_into()\n            .expect(\"number of dimensions must always be positive\")\n    }\n\n    /// Shows whether the underlying ndarray is contiguous in memory or not.\n    pub fn is_contiguous(&self) -> bool {\n        match self.strides() {\n            None => true,\n            Some(strides) => {\n                // NDArrayError::MissingShape in case shape is not determined\n                self.shape()\n                    .iter()\n                    .zip(strides)\n                    .rfold(\n                        (true, 1),\n                        |(is_contig, expected_stride), (shape, stride)| {\n                            (\n                                is_contig && *stride == expected_stride,\n                                expected_stride * shape,\n                            )\n                        },\n                    )\n                    .0\n            }\n        }\n    }\n\n    pub fn byte_offset(&self) -> isize {\n        self.as_dltensor().byte_offset as isize\n    }\n\n    /// Flattens the NDArray to a `Vec` of the same type in cpu.\n    ///\n    /// ## Example\n    ///\n    /// ```\n    /// # use tvm_rt::{Device, DataType, NDArray};\n    /// # use std::str::FromStr;\n    /// let mut shape = [4];\n    /// let mut data = vec![1i32, 2, 3, 4];\n    /// let dev = Device::cpu(0);\n    /// let mut ndarray = NDArray::empty(&mut shape, dev, DataType::from_str(\"int32\").unwrap());\n    /// ndarray.copy_from_buffer(&mut data);\n    /// assert_eq!(ndarray.shape(), shape);\n    /// assert_eq!(ndarray.to_vec::<i32>().unwrap(), data);\n    /// ```\n    pub fn to_vec<T>(&self) -> Result<Vec<T>, NDArrayError> {\n        let n = self.size() / size_of::<T>();\n        let mut vec: Vec<T> = Vec::with_capacity(n);\n\n        let ptr = vec.as_mut_ptr();\n        let slice = unsafe { slice::from_raw_parts_mut(ptr, n) };\n        self.copy_to_buffer(slice);\n\n        unsafe { vec.set_len(n) };\n        Ok(vec)\n    }\n\n    /// Converts the NDArray to [`ByteArray`].\n    pub fn to_bytearray(&self) -> Result<ByteArray, NDArrayError> {\n        let v = self.to_vec::<u8>()?;\n        Ok(ByteArray::from(v))\n    }\n\n    /// Creates an NDArray from a mutable buffer of types i32, u32 or f32 in cpu.\n    ///\n    /// ## Example\n    ///\n    /// ```\n    /// # use tvm_rt::{Device, DataType, NDArray};\n    /// # use std::str::FromStr;\n    /// let shape = &mut [2];\n    /// let mut data = vec![1f32, 2.0];\n    /// let dev = Device::cpu(0);\n    /// let mut ndarray = NDArray::empty(shape, dev, DataType::from_str(\"int32\").unwrap());\n    /// ndarray.copy_from_buffer(&mut data);\n    /// ```\n    ///\n    /// *Note*: if something goes wrong during the copy, it will panic\n    /// from TVM side. See `TVMArrayCopyFromBytes` in `include/tvm/runtime/c_runtime_api.h`.\n    pub fn copy_from_buffer<T: Num32>(&mut self, data: &[T]) {\n        check_call!(ffi::TVMArrayCopyFromBytes(\n            self.as_raw_dltensor(),\n            data.as_ptr() as *mut _,\n            (data.len() * mem::size_of::<T>()) as _,\n        ));\n    }\n\n    pub fn copy_to_buffer<T>(&self, data: &mut [T]) {\n        assert_eq!(self.size(), data.len() * size_of::<T>());\n        check_call!(ffi::TVMArrayCopyToBytes(\n            self.as_raw_dltensor(),\n            data.as_ptr() as *mut _,\n            self.size() as _,\n        ));\n    }\n\n    pub fn fill_from_iter<T, I>(&mut self, iter: I)\n    where\n        T: Num32,\n        I: ExactSizeIterator<Item = T>,\n    {\n        assert!(self.is_contiguous());\n        assert_eq!(self.size(), size_of::<T>() * iter.len());\n        let mut ptr: *mut T = self.as_dltensor().data.cast();\n        iter.for_each(|x| unsafe {\n            ptr.write(x);\n            ptr = ptr.add(1);\n        })\n    }\n\n    /// Copies the NDArray to another target NDArray.\n    pub fn copy_to_ndarray(&self, target: NDArray) -> Result<NDArray, NDArrayError> {\n        if self.dtype() != target.dtype() {\n            return Err(NDArrayError::DataTypeMismatch {\n                expected: self.dtype(),\n                actual: target.dtype(),\n            });\n        }\n\n        check_call!(ffi::TVMArrayCopyFromTo(\n            self.as_raw_dltensor(),\n            target.as_raw_dltensor(),\n            ptr::null_mut() as ffi::TVMStreamHandle\n        ));\n\n        Ok(target)\n    }\n\n    /// Copies the NDArray to a target device.\n    pub fn copy_to_device(&self, target: &Device) -> Result<NDArray, NDArrayError> {\n        let tmp = NDArray::empty(self.shape(), *target, self.dtype());\n        let copy = self.copy_to_ndarray(tmp)?;\n        Ok(copy)\n    }\n\n    /// Converts a Rust's ndarray to TVM NDArray.\n    pub fn from_rust_ndarray<T: Num32 + Copy>(\n        input_nd: &ArrayD<T>,\n        dev: Device,\n        dtype: DataType,\n    ) -> Result<Self, NDArrayError> {\n        let shape: Vec<i64> = input_nd.shape().iter().map(|&x| x as i64).collect();\n        let mut nd = NDArray::empty(&shape, dev, dtype);\n        nd.fill_from_iter(input_nd.iter().copied());\n        Ok(nd)\n    }\n\n    /// Allocates and creates an empty NDArray given the shape, device and dtype.\n    pub fn empty(shape: &[i64], dev: Device, dtype: DataType) -> NDArray {\n        let mut handle = ptr::null_mut() as ffi::TVMArrayHandle;\n        let dtype: tvm_sys::ffi::DLDataType = dtype.into();\n        check_call!(ffi::TVMArrayAlloc(\n            shape.as_ptr(),\n            shape.len() as c_int,\n            i32::from(dtype.code) as c_int,\n            i32::from(dtype.bits) as c_int,\n            i32::from(dtype.lanes) as c_int,\n            dev.device_type as c_int,\n            dev.device_id as c_int,\n            &mut handle as *mut _,\n        ));\n        let ptr = NDArrayContainer::from_raw(handle)\n            .map(|o| o.downcast().expect(\"this should never fail\"));\n        NDArray(ptr)\n    }\n\n    pub fn zeroed(self) -> NDArray {\n        unsafe {\n            let dltensor = self.as_raw_dltensor();\n            let bytes_ptr: *mut u8 = std::mem::transmute((*dltensor).data);\n            println!(\"size {}\", self.size());\n            std::ptr::write_bytes(bytes_ptr, 0, self.size());\n            self\n        }\n    }\n}\n\nmacro_rules! impl_from_ndarray_rustndarray {\n    ($type:ty, $type_name:tt) => {\n        impl<'a> TryFrom<&'a NDArray> for ArrayD<$type> {\n            type Error = NDArrayError;\n\n            fn try_from(nd: &NDArray) -> Result<ArrayD<$type>, Self::Error> {\n                assert_eq!(nd.dtype(), DataType::from_str($type_name)?, \"Type mismatch\");\n                Ok(Array::from_shape_vec(\n                    &*nd.shape_usize(),\n                    nd.to_vec::<$type>()?,\n                )?)\n            }\n        }\n\n        impl<'a> TryFrom<&'a mut NDArray> for ArrayD<$type> {\n            type Error = NDArrayError;\n\n            fn try_from(nd: &mut NDArray) -> Result<ArrayD<$type>, Self::Error> {\n                assert_eq!(nd.dtype(), DataType::from_str($type_name)?, \"Type mismatch\");\n                Ok(Array::from_shape_vec(\n                    &*nd.shape_usize(),\n                    nd.to_vec::<$type>()?,\n                )?)\n            }\n        }\n    };\n}\n\nimpl_from_ndarray_rustndarray!(i32, \"int\");\nimpl_from_ndarray_rustndarray!(u32, \"uint\");\nimpl_from_ndarray_rustndarray!(f32, \"float\");\n\nmod sealed {\n    /// Private trait to prevent other traits from being implemeneted in downstream crates.\n    pub trait Sealed {}\n}\n\n/// A trait for the supported 32-bits numerical types in frontend.\npub trait Num32: Num + sealed::Sealed {\n    const BITS: u8 = 32;\n}\n\nmacro_rules! impl_num32 {\n    ($($type:ty),+) => {\n        $(\n            impl sealed::Sealed for $type {}\n            impl Num32 for $type {}\n        )+\n    };\n}\n\nimpl_num32!(i32, u32, f32);\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn basics() {\n        let shape = &[1, 2, 3];\n        let dev = Device::cpu(0);\n        println!(\"before empty\");\n        let ndarray = NDArray::empty(shape, dev, DataType::from_str(\"int32\").unwrap());\n        println!(\"after empty\");\n        assert_eq!(ndarray.shape(), shape);\n        assert_eq!(ndarray.len(), shape.iter().product::<i64>() as usize);\n        assert_eq!(ndarray.ndim(), 3);\n        assert!(ndarray.strides().is_none());\n        assert_eq!(ndarray.byte_offset(), 0);\n    }\n\n    #[test]\n    fn copy() {\n        let shape = &[4];\n        let data = vec![1i32, 2, 3, 4];\n        let dev = Device::cpu(0);\n        let mut ndarray = NDArray::empty(shape, dev, DataType::int(32, 1)).zeroed();\n        assert_eq!(ndarray.to_vec::<i32>().unwrap(), vec![0, 0, 0, 0]);\n        ndarray.copy_from_buffer(&data);\n        assert_eq!(ndarray.shape(), shape);\n        assert_eq!(ndarray.to_vec::<i32>().unwrap(), data);\n        assert_eq!(ndarray.ndim(), 1);\n        assert!(ndarray.is_contiguous());\n        assert_eq!(ndarray.byte_offset(), 0);\n        let shape = vec![4];\n        let e = NDArray::empty(&shape, Device::cpu(0), DataType::from_str(\"int32\").unwrap());\n        let nd = ndarray.copy_to_ndarray(e);\n        assert!(nd.is_ok());\n        assert_eq!(nd.unwrap().to_vec::<i32>().unwrap(), data);\n    }\n\n    /// This occasionally panics on macOS: https://github.com/rust-lang/rust/issues/71397\n    #[test]\n    #[should_panic(expected = \"called `Result::unwrap()` on an `Err`\")]\n    fn copy_wrong_dtype() {\n        let shape = vec![4];\n        let mut data = vec![1f32, 2., 3., 4.];\n        let dev = Device::cpu(0);\n        let mut nd_float = NDArray::empty(&shape, dev, DataType::from_str(\"float32\").unwrap());\n        nd_float.copy_from_buffer(&mut data);\n        let empty_int = NDArray::empty(&shape, dev, DataType::from_str(\"int32\").unwrap());\n        nd_float.copy_to_ndarray(empty_int).unwrap();\n    }\n\n    #[test]\n    fn rust_ndarray() {\n        let a = Array::from_shape_vec((2, 2), vec![1f32, 2., 3., 4.])\n            .unwrap()\n            .into_dyn();\n        let nd =\n            NDArray::from_rust_ndarray(&a, Device::cpu(0), DataType::from_str(\"float32\").unwrap())\n                .unwrap();\n        assert_eq!(nd.shape(), &[2, 2]);\n        let rnd: ArrayD<f32> = ArrayD::try_from(&nd).unwrap();\n        assert!(rnd.all_close(&a, 1e-8f32));\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/object/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryFrom;\nuse std::ffi::CString;\n\nuse crate::errors::Error;\nuse crate::external;\n\nuse tvm_sys::{ArgValue, RetValue};\n\nmod object_ptr;\n\npub use object_ptr::{IsObject, Object, ObjectPtr, ObjectRef};\n\npub trait AsArgValue<'a> {\n    fn as_arg_value(&'a self) -> ArgValue<'a>;\n}\n\nimpl<'a, T: 'static> AsArgValue<'a> for T\nwhere\n    &'a T: Into<ArgValue<'a>>,\n{\n    fn as_arg_value(&'a self) -> ArgValue<'a> {\n        self.into()\n    }\n}\n\n// TODO we would prefer to blanket impl From/TryFrom ArgValue/RetValue, but we\n// can't because of coherence rules. Instead, we generate them in the macro, and\n// add what we can (including Into instead of From) as subtraits.\n// We also add named conversions for clarity\npub trait IsObjectRef:\n    Sized\n    + Clone\n    + Into<RetValue>\n    + for<'a> AsArgValue<'a>\n    + TryFrom<RetValue, Error = Error>\n    + for<'a> TryFrom<ArgValue<'a>, Error = Error>\n    + std::fmt::Debug\n{\n    type Object: IsObject;\n    fn as_ptr(&self) -> Option<&ObjectPtr<Self::Object>>;\n    fn into_ptr(self) -> Option<ObjectPtr<Self::Object>>;\n    fn from_ptr(object_ptr: Option<ObjectPtr<Self::Object>>) -> Self;\n\n    fn null() -> Self {\n        Self::from_ptr(None)\n    }\n\n    fn into_arg_value<'a>(&'a self) -> ArgValue<'a> {\n        self.as_arg_value()\n    }\n\n    fn from_arg_value<'a>(arg_value: ArgValue<'a>) -> Result<Self, Error> {\n        Self::try_from(arg_value)\n    }\n\n    fn into_ret_value<'a>(self) -> RetValue {\n        self.into()\n    }\n\n    fn from_ret_value<'a>(ret_value: RetValue) -> Result<Self, Error> {\n        Self::try_from(ret_value)\n    }\n\n    fn upcast<U>(self) -> U\n    where\n        U: IsObjectRef,\n        Self::Object: AsRef<U::Object>,\n    {\n        let ptr = self.into_ptr().map(ObjectPtr::upcast);\n        U::from_ptr(ptr)\n    }\n\n    fn downcast<U>(self) -> Result<U, Error>\n    where\n        U: IsObjectRef,\n        U::Object: AsRef<Self::Object>,\n    {\n        let ptr = self.into_ptr().map(ObjectPtr::downcast);\n        let ptr = ptr.transpose()?;\n        Ok(U::from_ptr(ptr))\n    }\n}\n\nexternal! {\n    #[name(\"ir.DebugPrint\")]\n    pub fn debug_print(object: ObjectRef) -> CString;\n    #[name(\"node.StructuralHash\")]\n    fn structural_hash(object: ObjectRef, map_free_vars: bool) -> i64;\n    #[name(\"node.StructuralEqual\")]\n    fn structural_equal(lhs: ObjectRef, rhs: ObjectRef, assert_mode: bool, map_free_vars: bool) -> bool;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/object/object_ptr.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryFrom;\nuse std::ffi::CString;\nuse std::fmt;\nuse std::os::raw::c_char;\nuse std::ptr::NonNull;\nuse std::sync::atomic::AtomicI32;\n\nuse tvm_macros::Object;\nuse tvm_sys::ffi::{\n    self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeIndex2Key, TVMObjectTypeKey2Index,\n};\nuse tvm_sys::{ArgValue, RetValue};\n\nuse crate::errors::Error;\n\ntype Deleter = unsafe extern \"C\" fn(object: *mut Object) -> ();\n\n/// A TVM intrusive smart pointer header, in TVM all FFI compatible types\n/// start with an Object as their first field. The base object tracks\n/// a type_index which is an index into the runtime type information\n/// table, an atomic reference count, and a customized deleter which\n/// will be invoked when the reference count is zero.\n///\n#[derive(Debug, Object)]\n#[ref_name = \"ObjectRef\"]\n#[type_key = \"runtime.Object\"]\n#[repr(C)]\npub struct Object {\n    /// The index into TVM's runtime type information table.\n    pub(self) type_index: u32,\n    // TODO(@jroesch): pretty sure Rust and C++ atomics are the same, but not sure.\n    // NB: in general we should not touch this in Rust.\n    /// The reference count of the smart pointer.\n    pub(self) ref_count: AtomicI32,\n    /// The deleter function which is used to deallocate the underlying data\n    /// when the reference count is zero. This field must always be set for\n    /// all objects.\n    ///\n    /// The common use case is ensuring that the allocator which allocated the\n    /// data is also the one that deletes it.\n    pub(self) fdeleter: Deleter,\n}\n\n/// The default deleter for objects allocated in Rust, we use a bit of\n/// trait magic here to get a monomorphized deleter for each object\n/// \"subtype\".\n///\n/// This function just converts the pointer to the correct type\n/// and reconstructs a Box which then is dropped to deallocate\n/// the underlying allocation.\nunsafe extern \"C\" fn delete<T: IsObject>(object: *mut Object) {\n    let typed_object: *mut T = object as *mut T;\n    let boxed: Box<T> = Box::from_raw(typed_object);\n    drop(boxed);\n}\n\nfn derived_from(child_type_index: u32, parent_type_index: u32) -> bool {\n    let mut is_derived = 0;\n    crate::check_call!(ffi::TVMObjectDerivedFrom(\n        child_type_index,\n        parent_type_index,\n        &mut is_derived\n    ));\n\n    if is_derived == 0 {\n        false\n    } else {\n        true\n    }\n}\n\nimpl Object {\n    fn new(type_index: u32, deleter: Deleter) -> Object {\n        Object {\n            type_index,\n            // NB(@jroesch): I believe it is sound to use Rust atomics\n            // in conjunction with C++ atomics given the memory model\n            // is nearly identical.\n            //\n            // Of course these are famous last words which I may later\n            // regret.\n            ref_count: AtomicI32::new(0),\n            fdeleter: deleter,\n        }\n    }\n\n    fn get_type_key(&self) -> String {\n        let mut cstring: *mut c_char = std::ptr::null_mut();\n        unsafe {\n            if TVMObjectTypeIndex2Key(self.type_index, &mut cstring as *mut _) != 0 {\n                panic!(\"{}\", crate::get_last_error());\n            }\n            return CString::from_raw(cstring)\n                .into_string()\n                .expect(\"type keys should be valid utf-8\");\n        }\n    }\n\n    fn get_type_index<T: IsObject>() -> u32 {\n        let type_key = T::TYPE_KEY;\n        let cstring = CString::new(type_key).expect(\"type key must not contain null characters\");\n\n        // TODO(@jroesch): look into TVMObjectTypeKey2Index.\n        if type_key == \"runtime.Object\" {\n            return 0;\n        } else {\n            let mut index = 0;\n            unsafe {\n                if TVMObjectTypeKey2Index(cstring.as_ptr(), &mut index) != 0 {\n                    panic!(\"{}\", crate::get_last_error())\n                }\n            }\n            return index;\n        }\n    }\n\n    pub fn count(&self) -> i32 {\n        // need to do atomic read in C++\n        // ABI compatible atomics is funky/hard.\n        self.ref_count.load(std::sync::atomic::Ordering::Relaxed)\n    }\n\n    /// Allocates a base object value for an object subtype of type T.\n    /// By using associated constants and generics we can provide a\n    /// type indexed abstraction over allocating objects with the\n    /// correct index and deleter.\n    pub fn base<T: IsObject>() -> Object {\n        let index = Object::get_type_index::<T>();\n        Object::new(index, delete::<T>)\n    }\n\n    /// Increases the object's reference count by one.\n    pub(self) fn inc_ref(&self) {\n        let raw_ptr = self as *const Object as *mut Object as *mut std::ffi::c_void;\n        unsafe {\n            assert_eq!(TVMObjectRetain(raw_ptr), 0);\n        }\n    }\n\n    /// Decreases the object's reference count by one.\n    pub(self) fn dec_ref(&self) {\n        let raw_ptr = self as *const Object as *mut Object as *mut std::ffi::c_void;\n        unsafe {\n            assert_eq!(TVMObjectFree(raw_ptr), 0);\n        }\n    }\n}\n\n/// An unsafe trait which should be implemented for an object\n/// subtype.\n///\n/// The trait contains the type key needed to compute the type\n/// index, a method for accessing the base object given the\n/// subtype, and a typed delete method which is specialized\n/// to the subtype.\npub unsafe trait IsObject: AsRef<Object> + std::fmt::Debug {\n    const TYPE_KEY: &'static str;\n}\n\n/// A smart pointer for types which implement IsObject.\n/// This type directly corresponds to TVM's C++ type ObjectPtr<T>.\n///\n/// See object.h for more details.\n#[repr(C)]\npub struct ObjectPtr<T: IsObject> {\n    pub ptr: NonNull<T>,\n}\n\nimpl ObjectPtr<Object> {\n    pub fn from_raw(object_ptr: *mut Object) -> Option<ObjectPtr<Object>> {\n        let non_null = NonNull::new(object_ptr);\n        non_null.map(|ptr| {\n            debug_assert!(unsafe { ptr.as_ref().count() } >= 0);\n            ObjectPtr { ptr }\n        })\n    }\n}\n\nimpl<T: IsObject> Clone for ObjectPtr<T> {\n    fn clone(&self) -> Self {\n        unsafe { self.ptr.as_ref().as_ref().inc_ref() }\n        ObjectPtr { ptr: self.ptr }\n    }\n}\n\nimpl<T: IsObject> Drop for ObjectPtr<T> {\n    fn drop(&mut self) {\n        unsafe { self.ptr.as_ref().as_ref().dec_ref() }\n    }\n}\n\nimpl<T: IsObject> ObjectPtr<T> {\n    pub fn leak<'a>(object_ptr: ObjectPtr<T>) -> &'a mut T\n    where\n        T: 'a,\n    {\n        unsafe { &mut *std::mem::ManuallyDrop::new(object_ptr).ptr.as_ptr() }\n    }\n\n    pub fn new(object: T) -> ObjectPtr<T> {\n        object.as_ref().inc_ref();\n        let object_ptr = Box::new(object);\n        let object_ptr = Box::leak(object_ptr);\n        let ptr = NonNull::from(object_ptr);\n        ObjectPtr { ptr }\n    }\n\n    pub fn count(&self) -> i32 {\n        // need to do atomic read in C++\n        // ABI compatible atomics is funky/hard.\n        self.as_ref()\n            .ref_count\n            .load(std::sync::atomic::Ordering::Relaxed)\n    }\n\n    /// This method avoid running the destructor on self once it's dropped, so we don't accidentally release the memory\n    unsafe fn cast<U: IsObject>(self) -> ObjectPtr<U> {\n        let ptr = self.ptr.cast();\n        std::mem::forget(self);\n        ObjectPtr { ptr }\n    }\n\n    pub fn upcast<U>(self) -> ObjectPtr<U>\n    where\n        U: IsObject,\n        T: AsRef<U>,\n    {\n        unsafe { self.cast() }\n    }\n\n    pub fn downcast<U>(self) -> Result<ObjectPtr<U>, Error>\n    where\n        U: IsObject + AsRef<T>,\n    {\n        let child_index = Object::get_type_index::<U>();\n        let object_index = self.as_ref().type_index;\n\n        let is_derived = if child_index == object_index {\n            true\n        } else {\n            // TODO(@jroesch): write tests\n            derived_from(object_index, child_index)\n        };\n\n        if is_derived {\n            Ok(unsafe { self.cast() })\n        } else {\n            let type_key = self.as_ref().get_type_key();\n            Err(Error::downcast(type_key.into(), U::TYPE_KEY))\n        }\n    }\n\n    pub unsafe fn into_raw(self) -> *mut T {\n        self.ptr.as_ptr()\n    }\n\n    pub unsafe fn as_ptr(&self) -> *mut T {\n        self.ptr.as_ptr()\n    }\n}\n\nimpl<T: IsObject> std::ops::Deref for ObjectPtr<T> {\n    type Target = T;\n\n    fn deref(&self) -> &Self::Target {\n        unsafe { self.ptr.as_ref() }\n    }\n}\n\nimpl<T: IsObject> fmt::Debug for ObjectPtr<T> {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        use std::ops::Deref;\n        write!(f, \"{:?}\", self.deref())\n    }\n}\n\nimpl<'a, T: IsObject> From<ObjectPtr<T>> for RetValue {\n    fn from(object_ptr: ObjectPtr<T>) -> RetValue {\n        let raw_object_ptr = ObjectPtr::leak(object_ptr) as *mut T as *mut std::ffi::c_void;\n        assert!(!raw_object_ptr.is_null());\n        RetValue::ObjectHandle(raw_object_ptr)\n    }\n}\n\nimpl<'a, T: IsObject> TryFrom<RetValue> for ObjectPtr<T> {\n    type Error = Error;\n\n    fn try_from(ret_value: RetValue) -> Result<ObjectPtr<T>, Self::Error> {\n        use crate::ffi::DLTensor;\n        use crate::ndarray::NDArrayContainer;\n\n        match ret_value {\n            RetValue::ObjectHandle(handle) | RetValue::ModuleHandle(handle) => {\n                let optr = ObjectPtr::from_raw(handle as *mut Object).ok_or(Error::Null)?;\n                debug_assert!(optr.count() >= 1);\n                optr.downcast()\n            }\n            RetValue::NDArrayHandle(handle) => {\n                let optr: ObjectPtr<NDArrayContainer> =\n                    NDArrayContainer::from_raw(handle as *mut DLTensor).ok_or(Error::Null)?;\n                debug_assert!(optr.count() >= 1);\n                optr.upcast::<Object>().downcast()\n            }\n            _ => Err(Error::downcast(format!(\"{:?}\", ret_value), T::TYPE_KEY)),\n        }\n    }\n}\n\nimpl<'a, T: IsObject> From<&'a ObjectPtr<T>> for ArgValue<'a> {\n    fn from(object_ptr: &'a ObjectPtr<T>) -> ArgValue<'a> {\n        debug_assert!(object_ptr.count() >= 1);\n        let object_ptr = object_ptr.clone().upcast::<Object>();\n        match T::TYPE_KEY {\n            \"runtime.NDArray\" => {\n                use crate::ndarray::NDArrayContainer;\n                let dcast_ptr = object_ptr.downcast().unwrap();\n                let raw_ptr = NDArrayContainer::as_mut_ptr(&dcast_ptr) as *mut std::ffi::c_void;\n                assert!(!raw_ptr.is_null());\n                ArgValue::NDArrayHandle(raw_ptr)\n            }\n            \"runtime.Module\" => {\n                let raw_ptr = unsafe { object_ptr.as_ptr() } as *mut std::ffi::c_void;\n                assert!(!raw_ptr.is_null());\n                ArgValue::ModuleHandle(raw_ptr)\n            }\n            _ => {\n                let raw_ptr = unsafe { object_ptr.as_ptr() } as *mut std::ffi::c_void;\n                assert!(!raw_ptr.is_null());\n                ArgValue::ObjectHandle(raw_ptr)\n            }\n        }\n    }\n}\n\nimpl<'a, T: IsObject> TryFrom<ArgValue<'a>> for ObjectPtr<T> {\n    type Error = Error;\n\n    fn try_from(arg_value: ArgValue<'a>) -> Result<ObjectPtr<T>, Self::Error> {\n        use crate::ffi::DLTensor;\n        use crate::ndarray::NDArrayContainer;\n\n        match arg_value {\n            ArgValue::ObjectHandle(handle) | ArgValue::ModuleHandle(handle) => {\n                let optr = ObjectPtr::from_raw(handle as *mut Object).ok_or(Error::Null)?;\n                optr.inc_ref();\n                // We are building an owned, ref-counted view into the underlying ArgValue, in order to be safe we must\n                // bump the reference count by one.\n                assert!(optr.count() >= 1);\n                optr.downcast()\n            }\n            ArgValue::NDArrayHandle(handle) => {\n                let optr =\n                    NDArrayContainer::from_raw(handle as *mut DLTensor).ok_or(Error::Null)?;\n                // We are building an owned, ref-counted view into the underlying ArgValue, in order to be safe we must\n                // bump the reference count by one.\n                assert!(optr.count() >= 1);\n                // TODO(@jroesch): figure out if there is a more optimal way to do this\n                let object = optr.upcast::<Object>();\n                object.inc_ref();\n                object.downcast()\n            }\n            _ => Err(Error::downcast(format!(\"{:?}\", arg_value), \"ObjectHandle\")),\n        }\n    }\n}\n\nimpl<T: IsObject> std::hash::Hash for ObjectPtr<T> {\n    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {\n        state.write_i64(\n            super::structural_hash(ObjectRef(Some(self.clone().upcast())), false).unwrap(),\n        )\n    }\n}\n\nimpl<T: IsObject> PartialEq for ObjectPtr<T> {\n    fn eq(&self, other: &Self) -> bool {\n        let lhs = ObjectRef(Some(self.clone().upcast()));\n        let rhs = ObjectRef(Some(other.clone().upcast()));\n        super::structural_equal(lhs, rhs, false, false).unwrap()\n    }\n}\n\nimpl<T: IsObject> Eq for ObjectPtr<T> {}\n\n#[cfg(test)]\nmod tests {\n    use super::{Object, ObjectPtr};\n    use anyhow::{ensure, Result};\n    use std::convert::TryInto;\n    use tvm_sys::{ArgValue, RetValue};\n\n    #[test]\n    fn test_new_object() -> anyhow::Result<()> {\n        let object = Object::base::<Object>();\n        let ptr = ObjectPtr::new(object);\n        assert_eq!(ptr.count(), 1);\n        Ok(())\n    }\n\n    #[test]\n    fn test_leak() -> anyhow::Result<()> {\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        assert_eq!(ptr.count(), 1);\n        let object = ObjectPtr::leak(ptr);\n        assert_eq!(object.count(), 1);\n        Ok(())\n    }\n\n    #[test]\n    fn test_clone() -> anyhow::Result<()> {\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        assert_eq!(ptr.count(), 1);\n        let ptr2 = ptr.clone();\n        assert_eq!(ptr2.count(), 2);\n        drop(ptr);\n        assert_eq!(ptr2.count(), 1);\n        Ok(())\n    }\n\n    #[test]\n    fn roundtrip_retvalue() -> Result<()> {\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        assert_eq!(ptr.count(), 1);\n        let ret_value: RetValue = ptr.clone().into();\n        let ptr2: ObjectPtr<Object> = ret_value.try_into()?;\n        assert_eq!(ptr.count(), ptr2.count());\n        assert_eq!(ptr.count(), 2);\n        ensure!(\n            ptr.type_index == ptr2.type_index,\n            \"type indices do not match\"\n        );\n        ensure!(\n            ptr.fdeleter == ptr2.fdeleter,\n            \"objects have different deleters\"\n        );\n        // After dropping the second pointer we should only see only refcount.\n        drop(ptr2);\n        assert_eq!(ptr.count(), 1);\n        Ok(())\n    }\n\n    #[test]\n    fn roundtrip_argvalue() -> Result<()> {\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        assert_eq!(ptr.count(), 1);\n        let ptr_clone = ptr.clone();\n        assert_eq!(ptr.count(), 2);\n        let arg_value: ArgValue = (&ptr_clone).into();\n        assert_eq!(ptr.count(), 2);\n        let ptr2: ObjectPtr<Object> = arg_value.try_into()?;\n        assert_eq!(ptr2.count(), 3);\n        assert_eq!(ptr.count(), ptr2.count());\n        drop(ptr_clone);\n        assert_eq!(ptr.count(), 2);\n        ensure!(\n            ptr.type_index == ptr2.type_index,\n            \"type indices do not match\"\n        );\n        ensure!(\n            ptr.fdeleter == ptr2.fdeleter,\n            \"objects have different deleters\"\n        );\n        // After dropping the second pointer we should only see only refcount.\n        drop(ptr2);\n        assert_eq!(ptr.count(), 1);\n        Ok(())\n    }\n\n    fn test_fn_raw<'a>(\n        mut args: crate::to_function::ArgList<'a>,\n    ) -> crate::function::Result<RetValue> {\n        let v: ArgValue = args.remove(0);\n        let v2: ArgValue = args.remove(0);\n        // assert_eq!(o.count(), 2);\n        let o: ObjectPtr<Object> = v.try_into().unwrap();\n        assert_eq!(o.count(), 2);\n        let o2: ObjectPtr<Object> = v2.try_into().unwrap();\n        assert_eq!(o2.count(), 3);\n        drop(o2);\n        assert_eq!(o.count(), 2);\n        Ok(o.into())\n    }\n\n    #[test]\n    fn test_ref_count_raw_fn() {\n        use super::*;\n        use crate::function::{register_untyped, Function};\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        // Call the function without the wrapping for TVM.\n        assert_eq!(ptr.count(), 1);\n        let same = test_fn_raw(vec![(&ptr).into(), (&ptr).into()]).unwrap();\n        let output: ObjectPtr<Object> = same.try_into().unwrap();\n        assert_eq!(output.count(), 2);\n        drop(output);\n        assert_eq!(ptr.count(), 1);\n\n        register_untyped(test_fn_raw, \"test_fn_raw\", true).unwrap();\n        let raw_func = Function::get(\"test_fn_raw\").unwrap();\n        let output = raw_func.invoke(vec![(&ptr).into(), (&ptr).into()]).unwrap();\n        let output: ObjectPtr<Object> = output.try_into().unwrap();\n        assert_eq!(output.count(), 2);\n        drop(output);\n        assert_eq!(ptr.count(), 1);\n    }\n\n    fn test_fn_typed(o: ObjectPtr<Object>, o2: ObjectPtr<Object>) -> ObjectPtr<Object> {\n        assert_eq!(o.count(), 3);\n        assert_eq!(o2.count(), 3);\n        drop(o2);\n        assert_eq!(o.count(), 2);\n        return o;\n    }\n\n    #[test]\n    fn test_ref_count_typed() {\n        use super::*;\n        use crate::function::{register, Function};\n        let ptr = ObjectPtr::new(Object::base::<Object>());\n        // Call the function without the wrapping for TVM.\n        assert_eq!(ptr.count(), 1);\n        let output = test_fn_typed(ptr.clone(), ptr.clone());\n        assert_eq!(output.count(), 2);\n        drop(output);\n        assert_eq!(ptr.count(), 1);\n\n        register(test_fn_typed, \"test_fn_typed\").unwrap();\n        let typed_func = Function::get(\"test_fn_typed\").unwrap();\n        let output = typed_func\n            .invoke(vec![(&ptr).into(), (&ptr).into()])\n            .unwrap();\n        let output: ObjectPtr<Object> = output.try_into().unwrap();\n        assert_eq!(output.count(), 2);\n        drop(output);\n        assert_eq!(ptr.count(), 1);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/string.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::cmp::{Ordering, PartialEq};\nuse std::hash::{Hash, Hasher};\n\nuse super::Object;\n\nuse tvm_macros::Object;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"String\"]\n#[type_key = \"runtime.String\"]\n#[no_derive]\npub struct StringObj {\n    base: Object,\n    data: *const u8,\n    size: u64,\n}\n\nimpl From<std::string::String> for String {\n    fn from(s: std::string::String) -> Self {\n        let size = s.len() as u64;\n        let data = Box::into_raw(s.into_boxed_str()).cast();\n        let base = Object::base::<StringObj>();\n        StringObj { base, data, size }.into()\n    }\n}\n\nimpl From<&'static str> for String {\n    fn from(s: &'static str) -> Self {\n        let size = s.len() as u64;\n        let data = s.as_bytes().as_ptr();\n        let base = Object::base::<StringObj>();\n        StringObj { base, data, size }.into()\n    }\n}\n\nimpl AsRef<[u8]> for String {\n    fn as_ref(&self) -> &[u8] {\n        self.as_bytes()\n    }\n}\n\nimpl std::fmt::Display for String {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        self.to_string_lossy().fmt(f)\n    }\n}\n\nimpl String {\n    pub fn is_empty(&self) -> bool {\n        self.len() == 0\n    }\n\n    pub fn len(&self) -> usize {\n        self.size as usize\n    }\n\n    pub fn as_bytes(&self) -> &[u8] {\n        unsafe { std::slice::from_raw_parts(self.data, self.len()) }\n    }\n\n    pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {\n        std::str::from_utf8(self.as_bytes())\n    }\n\n    pub fn to_string_lossy(&self) -> std::borrow::Cow<str> {\n        std::string::String::from_utf8_lossy(self.as_bytes())\n    }\n}\n\nimpl<T: AsRef<[u8]>> PartialEq<T> for String {\n    fn eq(&self, other: &T) -> bool {\n        self.as_bytes() == other.as_ref()\n    }\n}\n\nimpl<T: AsRef<[u8]>> PartialOrd<T> for String {\n    fn partial_cmp(&self, other: &T) -> Option<Ordering> {\n        self.as_bytes().partial_cmp(other.as_ref())\n    }\n}\n\nimpl Eq for String {}\n\nimpl Ord for String {\n    fn cmp(&self, other: &Self) -> Ordering {\n        self.as_bytes().cmp(other.as_bytes())\n    }\n}\n\nimpl Hash for String {\n    fn hash<H: Hasher>(&self, state: &mut H) {\n        self.as_bytes().hash(state);\n    }\n}\n\nimpl std::fmt::Debug for String {\n    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        formatter.write_fmt(format_args!(\"{:?}\", self.to_string_lossy()))\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::String;\n    use crate::object::debug_print;\n    use crate::IsObjectRef;\n    use anyhow::{ensure, Result};\n\n    #[test]\n    fn test_string_debug() -> Result<()> {\n        let s = String::from(\"foo\");\n        let object_ref = s.upcast();\n        println!(\"about to call\");\n        let string = debug_print(object_ref)?;\n        println!(\"after call\");\n        ensure!(\n            string.into_string().expect(\"is cstring\").contains(\"foo\"),\n            \"string content is invalid\"\n        );\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-rt/src/to_function.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! This module provides an idiomatic Rust API for creating and working with TVM functions.\n//!\n//! For calling an already registered TVM function use [`function::Builder`]\n//! To register a TVM packed function from Rust side either\n//! use [`function::register`] or the macro [`register_global_func`].\n//!\n//! See the tests and examples repository for more examples.\n\nuse std::convert::{TryFrom, TryInto};\nuse std::{\n    os::raw::{c_int, c_void},\n    ptr, slice,\n};\n\nuse super::{function::Result, Function};\nuse crate::errors::Error;\n\npub use tvm_sys::{ffi, ArgValue, RetValue};\n\n/// A trait representing whether the function arguments\n/// and return type can be assigned to a TVM packed function.\n///\n/// By splitting the conversion to function into two traits\n/// we are able to improve error reporting, by splitting the\n/// conversion of inputs and outputs to this trait.\n///\n/// And the implementation of it to `ToFunction`.\n\npub type ArgList<'a> = Vec<ArgValue<'a>>;\n\npub enum Args<'a, I> {\n    Typed(I),\n    Raw(ArgList<'a>),\n}\n\npub trait Typed<I, O> {\n    fn args<'arg>(i: Vec<ArgValue<'arg>>) -> Result<Args<'arg, I>>;\n    fn ret(o: O) -> Result<RetValue>;\n}\n\npub trait ToFunction<I, O>: Sized {\n    type Handle;\n\n    fn into_raw(self) -> *mut Self::Handle;\n\n    fn call<'a>(handle: *mut Self::Handle, args: Vec<ArgValue<'a>>) -> Result<RetValue>\n    where\n        Self: Typed<I, O>;\n\n    fn drop(handle: *mut Self::Handle);\n\n    fn to_function(self) -> Function\n    where\n        Self: Typed<I, O>,\n    {\n        let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;\n        let resource_handle = self.into_raw();\n\n        check_call!(ffi::TVMFuncCreateFromCFunc(\n            Some(Self::tvm_callback),\n            resource_handle as *mut _,\n            Some(Self::tvm_finalizer),\n            &mut fhandle as *mut ffi::TVMFunctionHandle,\n        ));\n\n        Function::from_raw(fhandle)\n    }\n\n    /// The callback function which is wrapped converted by TVM\n    /// into a packed function stored in fhandle.\n    unsafe extern \"C\" fn tvm_callback(\n        args: *mut ffi::TVMValue,\n        type_codes: *mut c_int,\n        num_args: c_int,\n        ret: ffi::TVMRetValueHandle,\n        resource_handle: *mut c_void,\n    ) -> c_int\n    where\n        Self: Typed<I, O>,\n    {\n        #![allow(unused_assignments, unused_unsafe)]\n        let result = std::panic::catch_unwind(|| {\n            // turning off the incorrect linter complaints\n            let len = num_args as usize;\n            let args_list = slice::from_raw_parts_mut(args, len);\n            let type_codes_list = slice::from_raw_parts_mut(type_codes, len);\n            let mut local_args: Vec<ArgValue> = Vec::new();\n            let mut value = ffi::TVMValue { v_int64: 0 };\n            let mut tcode = 0;\n            let resource_handle = resource_handle as *mut Self::Handle;\n            for i in 0..len {\n                value = args_list[i];\n                tcode = type_codes_list[i];\n                // TODO(@jroesch): I believe it is sound to disable this specialized move rule.\n                //\n                // This is used in C++ to deal with moving an RValue or reference to a return value\n                // directly so you can skip copying.\n                //\n                // I believe this is not needed as the move directly occurs into the Rust function.\n\n                // if tcode == ffi::TVMArgTypeCode_kTVMObjectHandle as c_int\n                //     || tcode == ffi::TVMArgTypeCode_kTVMObjectRValueRefArg as c_int\n                //     || tcode == ffi::TVMArgTypeCode_kTVMPackedFuncHandle as c_int\n                //     || tcode == ffi::TVMArgTypeCode_kTVMModuleHandle as c_int\n                //     || tcode == ffi::TVMArgTypeCode_kTVMNDArrayHandle as c_int\n                // {\n                //     check_call!(ffi::TVMCbArgToReturn(\n                //         &mut value as *mut _,\n                //         &mut tcode as *mut _\n                //     ));\n                // }\n                let arg_value = ArgValue::from_tvm_value(value, tcode as u32);\n                local_args.push(arg_value);\n            }\n\n            let rv = match Self::call(resource_handle, local_args) {\n                Ok(v) => v,\n                Err(msg) => {\n                    return Err(msg);\n                }\n            };\n\n            // TODO(@jroesch): clean up the handling of the is dec_ref\n            match rv.clone().try_into() as Result<crate::object::ObjectPtr<crate::object::Object>> {\n                Err(_) => {}\n                Ok(v) => drop(v),\n            };\n\n            let (mut ret_val, ret_tcode) = rv.to_tvm_value();\n            let mut ret_type_code = ret_tcode as c_int;\n\n            check_call!(ffi::TVMCFuncSetReturn(\n                ret,\n                &mut ret_val as *mut _,\n                &mut ret_type_code as *mut _,\n                1 as c_int\n            ));\n\n            Ok(())\n        });\n\n        // Here we handle either a panic or true error to isolate\n        // the unwinding as it will cause issues if we allow Rust\n        // to unwind over C++ boundary without care.\n        match result {\n            Err(_) => {\n                // TODO(@jroesch): figure out how to improve error here.\n                crate::set_last_error(&Error::Panic);\n                return -1;\n            }\n            Ok(inner_res) => match inner_res {\n                Err(err) => {\n                    crate::set_last_error(&err);\n                    return -1;\n                }\n                Ok(()) => return 0,\n            },\n        }\n    }\n\n    /// The finalizer which is invoked when the packed function's\n    /// reference count is zero.\n    unsafe extern \"C\" fn tvm_finalizer(fhandle: *mut c_void) {\n        let handle = std::mem::transmute(fhandle);\n        Self::drop(handle)\n    }\n}\n\npub struct RawArgs;\n\nimpl Typed<RawArgs, RetValue> for for<'a> fn(Vec<ArgValue<'a>>) -> Result<RetValue> {\n    fn args<'arg>(args: Vec<ArgValue<'arg>>) -> Result<Args<'arg, RawArgs>> {\n        Ok(Args::Raw(args))\n    }\n\n    fn ret(o: RetValue) -> Result<RetValue> {\n        Ok(o)\n    }\n}\n\nimpl ToFunction<RawArgs, RetValue> for for<'arg> fn(Vec<ArgValue<'arg>>) -> Result<RetValue> {\n    type Handle = for<'arg> fn(Vec<ArgValue<'arg>>) -> Result<RetValue>;\n\n    fn into_raw(self) -> *mut Self::Handle {\n        let ptr: Box<Self::Handle> = Box::new(self);\n        Box::into_raw(ptr)\n    }\n\n    fn call<'arg>(handle: *mut Self::Handle, args: Vec<ArgValue<'arg>>) -> Result<RetValue> {\n        unsafe {\n            let func = *handle;\n            func(args)\n        }\n    }\n\n    fn drop(_: *mut Self::Handle) {}\n}\n\n/// A helper trait which correctly captures the complex conversion and lifetime semantics needed\n/// to coerce an ordinary Rust value into `ArgValue`.\npub trait TryFromArgValue<F>: TryFrom<F> {\n    fn from_arg_value(f: F) -> std::result::Result<Self, Error>;\n}\n\nimpl<'a, T> TryFromArgValue<ArgValue<'a>> for T\nwhere\n    Self: TryFrom<ArgValue<'a>>,\n    Error: From<<Self as TryFrom<ArgValue<'a>>>::Error>,\n{\n    fn from_arg_value(f: ArgValue<'a>) -> std::result::Result<T, Error> {\n        Ok(TryFrom::try_from(f)?)\n    }\n}\n\nmacro_rules! impl_typed_and_to_function {\n    ($len:literal; $($t:ident),*) => {\n        impl<Fun, Out, $($t),*> Typed<($($t,)*), Out> for Fun\n        where\n            Fun: Fn($($t),*) -> Out,\n            Out: TryInto<RetValue>,\n            Error: From<Out::Error>,\n            $( for<'a> $t: TryFromArgValue<ArgValue<'a>>, )*\n        {\n            #[allow(non_snake_case, unused_variables, unused_mut)]\n            fn args<'arg>(args: Vec<ArgValue<'arg>>) -> Result<Args<'arg, ($($t,)*)>> {\n                if args.len() != $len {\n                    return Err(Error::CallFailed(format!(\"{} expected {} arguments, got {}.\\n\",\n                                                         std::any::type_name::<Self>(),\n                                                         $len, args.len())))\n                }\n                let mut args = args.into_iter();\n                $(let $t = TryFromArgValue::from_arg_value(args.next().unwrap())?;)*\n                Ok(Args::Typed(($($t,)*)))\n            }\n\n            fn ret(out: Out) -> Result<RetValue> {\n                out.try_into().map_err(|e| e.into())\n            }\n        }\n\n\n        impl<Fun, $($t,)* Out> ToFunction<($($t,)*), Out> for Fun\n        where\n            Fun: Fn($($t,)*) -> Out + 'static\n        {\n            type Handle = Box<dyn Fn($($t,)*) -> Out + 'static>;\n\n            fn into_raw(self) -> *mut Self::Handle {\n                let ptr: Box<Self::Handle> = Box::new(Box::new(self));\n                Box::into_raw(ptr)\n            }\n\n            #[allow(non_snake_case)]\n            fn call<'a>(handle: *mut Self::Handle, args: Vec<ArgValue<'a>>) -> Result<RetValue>\n            where\n                Fun: Typed<($($t,)*), Out>\n            {\n                let ($($t,)*) = match Fun::args(args)? {\n                    Args::Raw(_) => panic!(\"impossible case\"),\n                    Args::Typed(typed) => typed,\n                };\n\n                let fn_ptr = unsafe { &*handle };\n                let out = fn_ptr($($t),*);\n                Fun::ret(out)\n            }\n\n            fn drop(ptr: *mut Self::Handle) {\n                let bx = unsafe { Box::from_raw(ptr) };\n                std::mem::drop(bx)\n            }\n        }\n    }\n}\n\nimpl_typed_and_to_function!(0;);\nimpl_typed_and_to_function!(1; A);\nimpl_typed_and_to_function!(2; A, B);\nimpl_typed_and_to_function!(3; A, B, C);\nimpl_typed_and_to_function!(4; A, B, C, D);\nimpl_typed_and_to_function!(5; A, B, C, D, E);\nimpl_typed_and_to_function!(6; A, B, C, D, E, F);\nimpl_typed_and_to_function!(7; A, B, C, D, E, F, G);\nimpl_typed_and_to_function!(8; A, B, C, D, E, F, G, H);\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    fn call<'a, F, I, O>(f: F, args: Vec<ArgValue<'a>>) -> Result<RetValue>\n    where\n        F: ToFunction<I, O>,\n        F: Typed<I, O>,\n    {\n        F::call(f.into_raw(), args)\n    }\n\n    #[test]\n    fn test_to_function0() {\n        fn zero() -> i32 {\n            10\n        }\n        let _ = zero.to_function();\n        let good = call(zero, vec![]).unwrap();\n        assert_eq!(i32::try_from(good).unwrap(), 10);\n        let bad = call(zero, vec![1.into()]).unwrap_err();\n        assert!(matches!(bad, Error::CallFailed(..)));\n    }\n\n    #[test]\n    fn test_to_function2() {\n        fn two_arg(i: i32, j: i32) -> i32 {\n            i + j\n        }\n        let good = call(two_arg, vec![3.into(), 4.into()]).unwrap();\n        assert_eq!(i32::try_from(good).unwrap(), 7);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nextern crate bindgen;\n\nuse std::{\n    path::{Path, PathBuf},\n    str::FromStr,\n};\n\nuse anyhow::{Context, Result};\nuse tvm_build::{BuildConfig, CMakeSetting};\n\n/// The necessary information for detecting a TVM installation.\nstruct TVMInstall {\n    source_path: PathBuf,\n    build_path: PathBuf,\n}\n\n/// Find the TVM install using the provided path.\nfn find_using_tvm_path<P: AsRef<Path>>(tvm_path: P) -> Result<TVMInstall> {\n    Ok(TVMInstall {\n        source_path: tvm_path.as_ref().into(),\n        build_path: tvm_path.as_ref().into(),\n    })\n}\n\n#[allow(unused)]\nfn if_unset<K: AsRef<std::ffi::OsStr>, V: AsRef<std::ffi::OsStr>>(k: K, v: V) -> Result<()> {\n    match std::env::var(k.as_ref()) {\n        Ok(other) if other != \"\" => {\n            println!(\n                \"cargo:warning=Using existing environment variable setting {:?}={:?}\",\n                k.as_ref(),\n                v.as_ref()\n            );\n        }\n        _ => std::env::set_var(k, v),\n    }\n\n    Ok(())\n}\n\n/// Find a TVM installation using TVM build by either first installing or detecting.\nfn find_using_tvm_build() -> Result<TVMInstall> {\n    let mut build_config = BuildConfig::default();\n    build_config.repository = Some(\"https://github.com/apache/tvm\".to_string());\n    build_config.branch = Some(option_env!(\"TVM_BRANCH\").unwrap_or(\"main\").into());\n\n    if cfg!(feature = \"use-cuda\") {\n        build_config.settings.use_cuda = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-opencl\") {\n        build_config.settings.use_opencl = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-vulkan\") {\n        build_config.settings.use_vulkan = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-rocm\") {\n        build_config.settings.use_rocm = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-metal\") {\n        build_config.settings.use_metal = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-hexagon-device\") {\n        build_config.settings.use_hexagon_device = Some(true);\n    }\n    if cfg!(feature = \"use-rpc\") {\n        build_config.settings.use_rpc = Some(true);\n    }\n    if cfg!(feature = \"use-threads\") {\n        build_config.settings.use_threads = Some(true);\n    }\n    if cfg!(feature = \"use-llvm\") {\n        build_config.settings.use_llvm = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-stackvm-runtime\") {\n        build_config.settings.use_stackvm_runtime = Some(true);\n    }\n    if cfg!(feature = \"use-graph-runtime\") {\n        build_config.settings.use_graph_runtime = Some(true);\n    }\n    if cfg!(feature = \"use-graph-runtime-debug\") {\n        build_config.settings.use_graph_runtime_debug = Some(true);\n    }\n    if cfg!(feature = \"use-openmp\") {\n        build_config.settings.use_openmp = Some(true);\n    }\n    if cfg!(feature = \"use-relay-debug\") {\n        build_config.settings.use_relay_debug = Some(true);\n    }\n    if cfg!(feature = \"use-rtti\") {\n        build_config.settings.use_rtti = Some(true);\n    }\n    if cfg!(feature = \"use-mscv-mt\") {\n        build_config.settings.use_mscv_mt = Some(true);\n    }\n    if cfg!(feature = \"use-micro\") {\n        build_config.settings.use_micro = Some(true);\n    }\n    if cfg!(feature = \"use-install-dev\") {\n        build_config.settings.use_install_dev = Some(true);\n    }\n    if cfg!(feature = \"hide_private-symbols\") {\n        build_config.settings.hide_private_symbols = Some(true);\n    }\n    if cfg!(feature = \"use-fallback-stl-map\") {\n        build_config.settings.use_fallback_stl_map = Some(true);\n    }\n    if cfg!(feature = \"use-ethosn\") {\n        build_config.settings.use_ethosn = Some(true);\n    }\n    if cfg!(feature = \"use-index_default-i64\") {\n        build_config.settings.use_index_default_i64 = Some(true);\n    }\n    if cfg!(feature = \"use-tf-tvmdsoop\") {\n        build_config.settings.use_tf_tvmdsoop = Some(true);\n    }\n    if cfg!(feature = \"use-byodt-posit\") {\n        build_config.settings.use_byodt_posit = Some(true);\n    }\n    if cfg!(feature = \"use-mkl\") {\n        build_config.settings.use_mkl = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-mkldnn\") {\n        build_config.settings.use_mkldnn = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-dnnl-codegen\") {\n        build_config.settings.use_dnnl_codegen = Some(true);\n    }\n    if cfg!(feature = \"use-cudnn\") {\n        build_config.settings.use_cudnn = Some(true);\n    }\n    if cfg!(feature = \"use-cublas\") {\n        build_config.settings.use_cublas = Some(true);\n    }\n    if cfg!(feature = \"use-thrust\") {\n        build_config.settings.use_thrust = Some(true);\n    }\n    if cfg!(feature = \"use-miopen\") {\n        build_config.settings.use_miopen = Some(true);\n    }\n    if cfg!(feature = \"use-rocblas\") {\n        build_config.settings.use_rocblas = Some(true);\n    }\n    if cfg!(feature = \"use-sort\") {\n        build_config.settings.use_sort = Some(true);\n    }\n    if cfg!(feature = \"use-nnpack\") {\n        build_config.settings.use_nnpack = Some(true);\n    }\n    if cfg!(feature = \"use-random\") {\n        build_config.settings.use_random = Some(true);\n    }\n    if cfg!(feature = \"use-micro-standalone-runtime\") {\n        build_config.settings.use_micro_standalone_runtime = Some(true);\n    }\n    if cfg!(feature = \"use-cpp-rpc\") {\n        build_config.settings.use_cpp_rpc = Some(true);\n    }\n    if cfg!(feature = \"use-tflite\") {\n        build_config.settings.use_tflite = Some(true);\n    }\n    if cfg!(feature = \"use-coreml\") {\n        build_config.settings.use_coreml = Some(true);\n    }\n    if cfg!(feature = \"use-target-onnx\") {\n        build_config.settings.use_target_onnx = Some(true);\n    }\n    if cfg!(feature = \"use-arm-compute-lib\") {\n        build_config.settings.use_arm_compute_lib = Some(true);\n    }\n    if cfg!(feature = \"use-arm-compute-lib-graph-runtime\") {\n        build_config.settings.use_arm_compute_lib_graph_runtime = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-tensorrt-codegen\") {\n        build_config.settings.use_tensorrt_codegen = Some(true);\n    }\n    if cfg!(feature = \"use-tensorrt-runtime\") {\n        build_config.settings.use_tensorrt_runtime = CMakeSetting::from_str(\"on\").ok();\n    }\n    if cfg!(feature = \"use-vitis-ai\") {\n        build_config.settings.use_vitis_ai = Some(true);\n    }\n    if cfg!(any(\n        feature = \"static-linking\",\n        feature = \"build-static-runtime\"\n    )) {\n        build_config.settings.build_static_runtime = Some(true);\n    }\n\n    let build_result = tvm_build::build(build_config)?;\n    let source_path = build_result.revision.source_path();\n    let build_path = build_result.revision.build_path();\n    Ok(TVMInstall {\n        source_path,\n        build_path,\n    })\n}\n\nfn main() -> Result<()> {\n    let TVMInstall {\n        source_path,\n        build_path,\n    } = match option_env!(\"TVM_HOME\") {\n        Some(tvm_path) if tvm_path != \"\" => find_using_tvm_path(tvm_path),\n        _ => find_using_tvm_build(),\n    }?;\n\n    // If the TVM_HOME environment variable changed, the LLVM_CONFIG_PATH environment variable\n    // changed or the source headers have changed we need to rebuild the Rust bindings.\n    println!(\"cargo:rerun-if-env-changed=TVM_HOME\");\n    println!(\"cargo:rerun-if-env-changed=LLVM_CONFIG_PATH\");\n    println!(\"cargo:rerun-if-changed={}/include\", source_path.display());\n\n    let library_name = if cfg!(feature = \"runtime-only\") {\n        \"tvm_runtime\"\n    } else {\n        \"tvm\"\n    };\n\n    match &std::env::var(\"CARGO_CFG_TARGET_ARCH\")\n        .expect(\"CARGO_CFG_TARGET_ARCH must be set by CARGO\")[..]\n    {\n        \"wasm32\" => {}\n        _ => {\n            if cfg!(feature = \"static-linking\") {\n                println!(\"cargo:rustc-link-lib=static={}\", library_name);\n                // TODO(@jroesch): move this to tvm-build as library_path?\n                println!(\n                    \"cargo:rustc-link-search=native={}/build\",\n                    build_path.display()\n                );\n            }\n\n            if cfg!(feature = \"dynamic-linking\") {\n                println!(\"cargo:rustc-link-lib=dylib={}\", library_name);\n                println!(\n                    \"cargo:rustc-link-search=native={}/build\",\n                    build_path.display()\n                );\n            }\n        }\n    };\n\n    let runtime_api = source_path.join(\"include/tvm/runtime/c_runtime_api.h\");\n    let backend_api = source_path.join(\"include/tvm/runtime/c_backend_api.h\");\n    let source_path = source_path.display().to_string();\n    let dlpack_include = format!(\"-I{}/3rdparty/dlpack/include/\", source_path);\n    let tvm_include = format!(\"-I{}/include/\", source_path);\n\n    let out_file = PathBuf::from(std::env::var(\"OUT_DIR\")?).join(\"c_runtime_api.rs\");\n\n    // @see rust-bindgen#550 for `blacklist_type`\n    bindgen::Builder::default()\n        .header(runtime_api.display().to_string())\n        .header(backend_api.display().to_string())\n        .clang_arg(dlpack_include)\n        .clang_arg(tvm_include)\n        .blacklist_type(\"max_align_t\")\n        .layout_tests(false)\n        .derive_partialeq(true)\n        .derive_eq(true)\n        .derive_default(true)\n        .generate()\n        .map_err(|()| {\n            anyhow::anyhow!(\"bindgen failed to generate the Rust bindings for the C API\")\n        })?\n        .write_to_file(out_file)\n        .context(\"failed to write the generated Rust binding to disk\")?;\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/array.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    mem,\n    os::raw::{c_int, c_void},\n};\n\nuse crate::ffi::{\n    DLDataType, DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDataTypeCode_kDLUInt, DLDevice,\n    DLDeviceType_kDLCPU, DLTensor,\n};\n\n/// `From` conversions to `DLTensor` for `ndarray::Array`.\n/// Takes a reference to the `ndarray` since `DLTensor` is not owned.\nmacro_rules! impl_dltensor_from_ndarray {\n    ($type:ty, $typecode:expr) => {\n        impl<'a, D: ndarray::Dimension> From<&'a mut ndarray::Array<$type, D>> for DLTensor {\n            fn from(arr: &'a mut ndarray::Array<$type, D>) -> Self {\n                DLTensor {\n                    data: arr.as_mut_ptr() as *mut c_void,\n                    device: DLDevice {\n                        device_type: DLDeviceType_kDLCPU,\n                        device_id: 0,\n                    },\n                    ndim: arr.ndim() as c_int,\n                    dtype: DLDataType {\n                        code: $typecode as u8,\n                        bits: 8 * mem::size_of::<$type>() as u8,\n                        lanes: 1,\n                    },\n                    shape: arr.shape().as_ptr() as *const i64 as *mut i64,\n                    strides: arr.strides().as_ptr() as *const i64 as *mut i64,\n                    byte_offset: 0,\n                    ..Default::default()\n                }\n            }\n        }\n    };\n}\n\nimpl_dltensor_from_ndarray!(f32, DLDataTypeCode_kDLFloat);\nimpl_dltensor_from_ndarray!(f64, DLDataTypeCode_kDLFloat);\nimpl_dltensor_from_ndarray!(i32, DLDataTypeCode_kDLInt);\nimpl_dltensor_from_ndarray!(i64, DLDataTypeCode_kDLInt);\nimpl_dltensor_from_ndarray!(u32, DLDataTypeCode_kDLUInt);\nimpl_dltensor_from_ndarray!(u64, DLDataTypeCode_kDLUInt);\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/byte_array.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\nuse std::convert::TryFrom;\n\nuse crate::errors::ValueDowncastError;\nuse crate::ffi::{TVMByteArray, TVMByteArrayFree};\nuse crate::{ArgValue, RetValue};\n\n/// A newtype wrapping a raw TVM byte-array.\n///\n/// ## Example\n///\n/// ```\n/// let v = b\"hello\";\n/// let barr = tvm_sys::ByteArray::from(&v);\n/// assert_eq!(barr.len(), v.len());\n/// assert_eq!(barr.data(), &[104u8, 101, 108, 108, 111]);\n/// ```\npub enum ByteArray {\n    Rust(TVMByteArray),\n    External(TVMByteArray),\n}\n\nimpl Drop for ByteArray {\n    fn drop(&mut self) {\n        match self {\n            ByteArray::Rust(bytes) => {\n                let ptr = bytes.data;\n                let len = bytes.size as _;\n                let cap = bytes.size as _;\n                let data: Vec<u8> = unsafe { Vec::from_raw_parts(ptr as _, len, cap) };\n                drop(data);\n            }\n            ByteArray::External(byte_array) => unsafe {\n                if TVMByteArrayFree(byte_array as _) != 0 {\n                    panic!(\"error\");\n                }\n            },\n        }\n    }\n}\n\nimpl ByteArray {\n    /// Gets the underlying byte-array\n    pub fn data(&self) -> &[u8] {\n        match self {\n            ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => unsafe {\n                std::slice::from_raw_parts(byte_array.data as *const u8, byte_array.size as _)\n            },\n        }\n    }\n\n    /// Gets the length of the underlying byte-array\n    pub fn len(&self) -> usize {\n        match self {\n            ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => byte_array.size as _,\n        }\n    }\n\n    /// Converts the underlying byte-array to `Vec<u8>`\n    pub fn to_vec(&self) -> Vec<u8> {\n        self.data().to_vec()\n    }\n\n    pub fn is_empty(&self) -> bool {\n        self.len() == 0\n    }\n}\n\nimpl<T: Into<Vec<u8>>> From<T> for ByteArray {\n    fn from(arg: T) -> Self {\n        let mut incoming_bytes: Vec<u8> = arg.into();\n        let mut bytes = Vec::with_capacity(incoming_bytes.len());\n        bytes.append(&mut incoming_bytes);\n\n        let mut bytes = std::mem::ManuallyDrop::new(bytes);\n        let ptr = bytes.as_mut_ptr();\n        assert_eq!(bytes.len(), bytes.capacity());\n        ByteArray::Rust(TVMByteArray {\n            data: ptr as _,\n            size: bytes.len() as _,\n        })\n    }\n}\n\nimpl<'a> From<&'a ByteArray> for ArgValue<'a> {\n    fn from(val: &'a ByteArray) -> ArgValue<'a> {\n        match val {\n            ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => {\n                ArgValue::Bytes(byte_array)\n            }\n        }\n    }\n}\n\n// todo(@jroesch): #8800 Follow up with ByteArray RetValue ownership.\n// impl From<ByteArray> for RetValue {\n//     fn from(val: ByteArray) -> RetValue {\n//         match val {\n//             ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => {\n//                 // TODO(@jroesch): This requires a little more work, going to land narratives\n//                 RetValue::Bytes(byte_array)\n//             }\n//         }\n//     }\n// }\n\nimpl TryFrom<RetValue> for ByteArray {\n    type Error = ValueDowncastError;\n    fn try_from(val: RetValue) -> Result<ByteArray, Self::Error> {\n        match val {\n            RetValue::Bytes(array) => Ok(ByteArray::External(array)),\n            _ => Err(ValueDowncastError {\n                expected_type: \"ByteArray\",\n                actual_type: format!(\"{:?}\", val),\n            }),\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn convert() {\n        let v = vec![1u8, 2, 3];\n        let barr = ByteArray::from(v.to_vec());\n        assert_eq!(barr.len(), v.len());\n        assert_eq!(barr.to_vec(), vec![1u8, 2, 3]);\n        let v = b\"hello\";\n        let barr = ByteArray::from(v.to_vec());\n        assert_eq!(barr.len(), v.len());\n        assert_eq!(barr.data(), &[104u8, 101, 108, 108, 111]);\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/datatype.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::any::TypeId;\nuse std::convert::TryFrom;\nuse std::str::FromStr;\n\nuse crate::ffi::DLDataType;\nuse crate::packed_func::RetValue;\n\nuse thiserror::Error;\n\nconst DL_INT_CODE: u8 = 0;\nconst DL_UINT_CODE: u8 = 1;\nconst DL_FLOAT_CODE: u8 = 2;\nconst DL_HANDLE: u8 = 3;\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]\n#[repr(C)]\npub struct DataType {\n    code: u8,\n    bits: u8,\n    lanes: u16,\n}\n\nimpl DataType {\n    pub const fn new(code: u8, bits: u8, lanes: u16) -> DataType {\n        DataType { code, bits, lanes }\n    }\n\n    /// Returns the number of bytes occupied by an element of this `DataType`.\n    pub fn itemsize(&self) -> usize {\n        (self.bits as usize * self.lanes as usize) >> 3\n    }\n\n    /// Returns whether this `DataType` represents primitive type `T`.\n    pub fn is_type<T: 'static>(&self) -> bool {\n        if self.lanes != 1 {\n            return false;\n        }\n        let typ = TypeId::of::<T>();\n        (typ == TypeId::of::<i32>() && self.code == DL_INT_CODE && self.bits == 32)\n            || (typ == TypeId::of::<i64>() && self.code == DL_INT_CODE && self.bits == 64)\n            || (typ == TypeId::of::<u32>() && self.code == DL_UINT_CODE && self.bits == 32)\n            || (typ == TypeId::of::<u64>() && self.code == DL_UINT_CODE && self.bits == 64)\n            || (typ == TypeId::of::<f32>() && self.code == DL_FLOAT_CODE && self.bits == 32)\n            || (typ == TypeId::of::<f64>() && self.code == DL_FLOAT_CODE && self.bits == 64)\n    }\n\n    pub fn code(&self) -> usize {\n        self.code as usize\n    }\n\n    pub fn bits(&self) -> usize {\n        self.bits as usize\n    }\n\n    pub fn lanes(&self) -> usize {\n        self.lanes as usize\n    }\n\n    pub const fn int(bits: u8, lanes: u16) -> DataType {\n        DataType::new(DL_INT_CODE, bits, lanes)\n    }\n\n    pub const fn float(bits: u8, lanes: u16) -> DataType {\n        DataType::new(DL_FLOAT_CODE, bits, lanes)\n    }\n\n    pub const fn float32() -> DataType {\n        Self::float(32, 1)\n    }\n\n    pub const fn uint(bits: u8, lanes: u16) -> DataType {\n        DataType::new(DL_UINT_CODE, bits, lanes)\n    }\n}\n\nimpl<'a> From<&'a DataType> for DLDataType {\n    fn from(dtype: &'a DataType) -> Self {\n        Self {\n            code: dtype.code as u8,\n            bits: dtype.bits as u8,\n            lanes: dtype.lanes as u16,\n        }\n    }\n}\n\nimpl From<DLDataType> for DataType {\n    fn from(dtype: DLDataType) -> Self {\n        Self {\n            code: dtype.code,\n            bits: dtype.bits,\n            lanes: dtype.lanes,\n        }\n    }\n}\n\nimpl From<DataType> for DLDataType {\n    fn from(dtype: DataType) -> Self {\n        Self {\n            code: dtype.code,\n            bits: dtype.bits,\n            lanes: dtype.lanes,\n        }\n    }\n}\n\n#[derive(Debug, Error)]\npub enum ParseDataTypeError {\n    #[error(\"invalid number: {0}\")]\n    InvalidNumber(std::num::ParseIntError),\n    #[error(\"missing data type specifier (e.g., int32, float64)\")]\n    MissingDataType,\n    #[error(\"unknown type: {0}\")]\n    UnknownType(String),\n}\n\n/// Implements TVMType conversion from `&str` of general format `{dtype}{bits}x{lanes}`\n/// such as \"int32\", \"float32\" or with lane \"float32x1\".\nimpl FromStr for DataType {\n    type Err = ParseDataTypeError;\n\n    fn from_str(type_str: &str) -> Result<Self, Self::Err> {\n        use ParseDataTypeError::*;\n\n        if type_str == \"bool\" {\n            return Ok(DataType::new(1, 1, 1));\n        }\n\n        let mut type_lanes = type_str.split('x');\n        let typ = type_lanes.next().ok_or(MissingDataType)?;\n        let lanes = type_lanes\n            .next()\n            .map(|l| <u16>::from_str_radix(l, 10))\n            .unwrap_or(Ok(1))\n            .map_err(InvalidNumber)?;\n        let (type_name, bits) = match typ.find(char::is_numeric) {\n            Some(idx) => {\n                let (name, bits_str) = typ.split_at(idx);\n                (\n                    name,\n                    u8::from_str_radix(bits_str, 10).map_err(InvalidNumber)?,\n                )\n            }\n            None => (typ, 32),\n        };\n\n        let type_code = match type_name {\n            \"int\" => DL_INT_CODE,\n            \"uint\" => DL_UINT_CODE,\n            \"float\" => DL_FLOAT_CODE,\n            \"handle\" => DL_HANDLE,\n            _ => return Err(UnknownType(type_name.to_string())),\n        };\n\n        Ok(DataType::new(type_code, bits, lanes))\n    }\n}\n\nimpl std::fmt::Display for DataType {\n    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n        if self.bits == 1 && self.lanes == 1 {\n            return write!(f, \"bool\");\n        }\n        let mut type_str = match self.code {\n            DL_INT_CODE => \"int\",\n            DL_UINT_CODE => \"uint\",\n            DL_FLOAT_CODE => \"float\",\n            DL_HANDLE => \"handle\",\n            _ => \"unknown\",\n        }\n        .to_string();\n\n        type_str += &self.bits.to_string();\n        if self.lanes > 1 {\n            type_str += &format!(\"x{}\", self.lanes);\n        }\n        f.write_str(&type_str)\n    }\n}\n\nimpl From<DataType> for RetValue {\n    fn from(dt: DataType) -> RetValue {\n        RetValue::DataType((&dt).into())\n    }\n}\n\nimpl TryFrom<RetValue> for DataType {\n    type Error = anyhow::Error;\n    fn try_from(ret_value: RetValue) -> anyhow::Result<DataType> {\n        match ret_value {\n            RetValue::DataType(dt) => Ok(dt.into()),\n            // TODO(@jroesch): improve\n            _ => Err(anyhow::anyhow!(\"unable to convert datatype from ...\")),\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/device.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! Provides [`Device`] and related device queries.\n//!\n//! Create a new device for device type and device id.\n//!\n//! # Example\n//!\n//! ```\n//! # use tvm_sys::{DeviceType, Device};\n//! let cpu = DeviceType::from(\"cpu\");\n//! let dev = Device::new(cpu , 0);\n//! let cpu0 = Device::cpu(0);\n//! assert_eq!(dev, cpu0);\n//! ```\n//!\n//! Or from a supported device name.\n//!\n//! ```\n//! use tvm_sys::Device;\n//! let cpu0 = Device::from(\"cpu\");\n//! println!(\"{}\", cpu0);\n//! ```\n\nuse std::convert::TryFrom;\nuse std::fmt::{self, Display, Formatter};\nuse std::str::FromStr;\n\nuse crate::ffi::{self, *};\nuse crate::packed_func::{ArgValue, RetValue};\n\nuse anyhow::Result;\nuse enumn::N;\nuse thiserror::Error;\n\n/// Device type represents the set of devices supported by\n/// [TVM](https://github.com/apache/tvm).\n///\n/// ## Example\n///\n/// ```\n/// use tvm_sys::DeviceType;\n/// let cpu = DeviceType::from(\"cpu\");\n/// println!(\"device is: {}\", cpu);\n///```\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, N)]\n#[repr(i64)]\npub enum DeviceType {\n    CPU = 1,\n    CUDA = 2,\n    CUDAHost = 3,\n    OpenCL = 4,\n    Vulkan = 7,\n    Metal = 8,\n    VPI = 9,\n    ROCM = 10,\n    ExtDev = 12,\n}\n\nimpl Default for DeviceType {\n    /// default device is cpu.\n    fn default() -> Self {\n        DeviceType::CPU\n    }\n}\n\nimpl From<DeviceType> for ffi::DLDeviceType {\n    fn from(device_type: DeviceType) -> Self {\n        device_type as Self\n    }\n}\n\nimpl From<ffi::DLDeviceType> for DeviceType {\n    fn from(device_type: ffi::DLDeviceType) -> Self {\n        Self::n(device_type as _).expect(\"invalid enumeration value for ffi::DLDeviceType\")\n    }\n}\n\nimpl Display for DeviceType {\n    fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n        write!(\n            f,\n            \"{}\",\n            match self {\n                DeviceType::CPU => \"cpu\",\n                DeviceType::CUDA => \"cuda\",\n                DeviceType::CUDAHost => \"cuda_host\",\n                DeviceType::OpenCL => \"opencl\",\n                DeviceType::Vulkan => \"vulkan\",\n                DeviceType::Metal => \"metal\",\n                DeviceType::VPI => \"vpi\",\n                DeviceType::ROCM => \"rocm\",\n                DeviceType::ExtDev => \"ext_device\",\n                // DeviceType(_) => \"rpc\",\n            }\n        )\n    }\n}\n\nimpl<'a> From<&'a str> for DeviceType {\n    fn from(type_str: &'a str) -> Self {\n        match type_str {\n            \"cpu\" => DeviceType::CPU,\n            \"llvm\" => DeviceType::CPU,\n            \"stackvm\" => DeviceType::CPU,\n            \"cuda\" => DeviceType::CUDA,\n            \"nvptx\" => DeviceType::CUDA,\n            \"cl\" => DeviceType::OpenCL,\n            \"opencl\" => DeviceType::OpenCL,\n            \"metal\" => DeviceType::Metal,\n            \"vpi\" => DeviceType::VPI,\n            \"rocm\" => DeviceType::ROCM,\n            _ => panic!(\"{:?} not supported!\", type_str),\n        }\n    }\n}\n\nimpl<'a> From<&DeviceType> for ArgValue<'a> {\n    fn from(dev: &DeviceType) -> Self {\n        Self::Int(*dev as _)\n    }\n}\n\n#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]\npub struct Device {\n    pub device_type: DeviceType,\n    pub device_id: usize,\n}\n\nimpl Device {\n    pub fn new(device_type: DeviceType, device_id: usize) -> Device {\n        Device {\n            device_type,\n            device_id,\n        }\n    }\n}\n\nimpl<'a> From<&'a Device> for DLDevice {\n    fn from(dev: &'a Device) -> Self {\n        Self {\n            device_type: dev.device_type.into(),\n            device_id: dev.device_id as i32,\n        }\n    }\n}\n\nimpl Default for Device {\n    fn default() -> Self {\n        Self {\n            device_type: DLDeviceType_kDLCPU.into(),\n            device_id: 0,\n        }\n    }\n}\n\n#[derive(Debug, Error)]\n#[error(\"unsupported device: {0}\")]\npub struct UnsupportedDeviceError(String);\n\nmacro_rules! impl_tvm_device {\n    ( $( $dev_type:ident : [ $( $dev_name:ident ),+ ] ),+ ) => {\n        /// Creates a Device from a string (e.g., \"cpu\", \"cuda\", \"ext_dev\")\n        impl FromStr for Device {\n            type Err = UnsupportedDeviceError;\n            fn from_str(type_str: &str) -> Result<Self, Self::Err> {\n                Ok(Self {\n                    device_type: match type_str {\n                         $( $(  stringify!($dev_name)  )|+ => $dev_type.into()),+,\n                        _ => return Err(UnsupportedDeviceError(type_str.to_string())),\n                    },\n                    device_id: 0,\n                })\n            }\n        }\n\n        impl Device {\n            $(\n                $(\n                    pub fn $dev_name(device_id: usize) -> Self {\n                        Self {\n                            device_type: $dev_type.into(),\n                            device_id: device_id,\n                        }\n                    }\n                )+\n            )+\n        }\n    };\n}\n\nimpl_tvm_device!(\n    DLDeviceType_kDLCPU: [cpu, llvm, stackvm],\n    DLDeviceType_kDLCUDA: [cuda, nvptx],\n    DLDeviceType_kDLOpenCL: [cl],\n    DLDeviceType_kDLMetal: [metal],\n    DLDeviceType_kDLVPI: [vpi],\n    DLDeviceType_kDLROCM: [rocm],\n    DLDeviceType_kDLExtDev: [ext_dev]\n);\n\nimpl<'a> From<&'a str> for Device {\n    fn from(target: &str) -> Self {\n        Device::new(DeviceType::from(target), 0)\n    }\n}\n\nimpl From<ffi::DLDevice> for Device {\n    fn from(dev: ffi::DLDevice) -> Self {\n        Device {\n            device_type: DeviceType::from(dev.device_type),\n            device_id: dev.device_id as usize,\n        }\n    }\n}\n\nimpl From<Device> for ffi::DLDevice {\n    fn from(dev: Device) -> Self {\n        ffi::DLDevice {\n            device_type: dev.device_type.into(),\n            device_id: dev.device_id as i32,\n        }\n    }\n}\n\nimpl Display for Device {\n    fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n        write!(f, \"{}({})\", self.device_type, self.device_id)\n    }\n}\n\nimpl<'a> From<&'a Device> for ArgValue<'a> {\n    fn from(dev: &'a Device) -> Self {\n        DLDevice::from(dev).into()\n    }\n}\n\nimpl<'a> From<Device> for ArgValue<'a> {\n    fn from(dev: Device) -> Self {\n        DLDevice::from(dev).into()\n    }\n}\n\nimpl From<Device> for RetValue {\n    fn from(ret_value: Device) -> RetValue {\n        RetValue::Device(ret_value.into())\n    }\n}\n\nimpl TryFrom<RetValue> for Device {\n    type Error = anyhow::Error;\n    fn try_from(ret_value: RetValue) -> anyhow::Result<Device> {\n        match ret_value {\n            RetValue::Device(dt) => Ok(dt.into()),\n            // TODO(@jroesch): improve\n            _ => Err(anyhow::anyhow!(\"unable to convert datatype from ...\")),\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn device() {\n        let dev = Device::cpu(0);\n        println!(\"device: {}\", dev);\n        let default_dev = Device::new(DeviceType::CPU, 0);\n        assert_eq!(dev.clone(), default_dev);\n        assert_ne!(dev, Device::cuda(0));\n\n        let str_dev = Device::new(DeviceType::CUDA, 0);\n        assert_eq!(str_dev.clone(), str_dev);\n        assert_ne!(str_dev, Device::new(DeviceType::CPU, 0));\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/errors.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse thiserror::Error;\n\n#[derive(Error, Debug)]\n#[error(\"invalid header (expected {expected_type:?}, found {actual_type:?})\")]\npub struct ValueDowncastError {\n    pub actual_type: String,\n    pub expected_type: &'static str,\n}\n\n#[derive(Error, Debug)]\n#[error(\"Function call `{context:?}` returned error: {message:?}\")]\npub struct FuncCallError {\n    context: String,\n    message: String,\n}\n\nimpl FuncCallError {\n    pub fn get_with_context(context: String) -> Self {\n        Self {\n            context,\n            message: unsafe { std::ffi::CStr::from_ptr(crate::ffi::TVMGetLastError()) }\n                .to_str()\n                .expect(\"failed while attempting to retrieve the TVM error message\")\n                .to_owned(),\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! This crate contains the minimal interface over TVM's\n//! C runtime API.\n//!\n//! These common bindings are useful to both runtimes\n//! written in Rust, as well as higher level API bindings.\n//!\n//! See the `tvm-rt` or `tvm` crates for full bindings to\n//! the TVM API.\n\n/// The low-level C runtime FFI API for TVM.\npub mod ffi {\n    #![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused)]\n\n    use std::os::raw::{c_char, c_int, c_void};\n\n    include!(concat!(env!(\"OUT_DIR\"), \"/c_runtime_api.rs\"));\n\n    pub type BackendPackedCFunc = extern \"C\" fn(\n        args: *const TVMValue,\n        type_codes: *const c_int,\n        num_args: c_int,\n        out_ret_value: *mut TVMValue,\n        out_ret_tcode: *mut u32,\n        resource_handle: *mut c_void,\n    ) -> c_int;\n}\n\npub mod array;\npub mod byte_array;\npub mod datatype;\npub mod device;\npub mod errors;\n#[macro_use]\npub mod packed_func;\npub mod value;\n\npub use byte_array::ByteArray;\npub use datatype::DataType;\npub use device::{Device, DeviceType};\npub use errors::*;\npub use packed_func::{ArgValue, RetValue};\n\nimpl<T, E> std::convert::TryFrom<Result<T, E>> for RetValue\nwhere\n    RetValue: std::convert::TryFrom<T>,\n    E: From<<RetValue as std::convert::TryFrom<T>>::Error>,\n{\n    type Error = E;\n\n    fn try_from(val: Result<T, E>) -> Result<RetValue, Self::Error> {\n        val.and_then(|t| RetValue::try_from(t).map_err(|e| e.into()))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/packed_func.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    convert::TryFrom,\n    ffi::{CStr, CString},\n    os::raw::{c_char, c_void},\n};\n\nuse crate::{errors::ValueDowncastError, ffi::*};\n\npub use crate::ffi::TVMValue;\n\npub trait PackedFunc:\n    Fn(&[ArgValue]) -> Result<RetValue, crate::errors::FuncCallError> + Send + Sync\n{\n}\n\nimpl<T> PackedFunc for T where\n    T: Fn(&[ArgValue]) -> Result<RetValue, crate::errors::FuncCallError> + Send + Sync\n{\n}\n\n/// Calls a packed function and returns a `RetValue`.\n///\n/// # Example\n///\n/// `call_packed!(my_tvm_func, &mut arg1, &mut arg2)`\n#[macro_export]\nmacro_rules! call_packed {\n    ($fn:expr, $($args:expr),+) => {\n        $fn(&[$($args.into(),)+])\n    };\n    ($fn:expr) => {\n        $fn(&Vec::new())\n    };\n}\n\n/// Constructs a derivative of a TVMPodValue.\nmacro_rules! TVMPODValue {\n    {\n        $(#[$m:meta])+\n        $name:ident $(<$a:lifetime>)? {\n            $($extra_variant:ident ( $variant_type:ty ) ),+ $(,)?\n        },\n        match $value:ident {\n            $($tvm_type:ident => { $from_tvm_type:expr })+\n        },\n        match &self {\n            $($self_type:ident ( $val:ident ) => { $from_self_type:expr })+\n        }\n        $(,)?\n    } => {\n        $(#[$m])+\n        #[derive(Clone, Debug)]\n        pub enum $name $(<$a>)? {\n            Int(i64),\n            UInt(i64),\n            Float(f64),\n            Null,\n            DataType(DLDataType),\n            String(*mut c_char),\n            Device(DLDevice),\n            Handle(*mut c_void),\n            ArrayHandle(TVMArrayHandle),\n            ObjectHandle(*mut c_void),\n            ModuleHandle(TVMModuleHandle),\n            FuncHandle(TVMFunctionHandle),\n            NDArrayHandle(*mut c_void),\n            $($extra_variant($variant_type)),+\n        }\n\n        impl $(<$a>)? $name $(<$a>)? {\n            pub fn from_tvm_value($value: TVMValue, type_code: u32) -> Self {\n                use $name::*;\n                #[allow(non_upper_case_globals)]\n                unsafe {\n                    match type_code as _ {\n                        DLDataTypeCode_kDLInt => Int($value.v_int64),\n                        DLDataTypeCode_kDLUInt => UInt($value.v_int64),\n                        DLDataTypeCode_kDLFloat => Float($value.v_float64),\n                        TVMArgTypeCode_kTVMNullptr => Null,\n                        TVMArgTypeCode_kTVMDataType => DataType($value.v_type),\n                        TVMArgTypeCode_kDLDevice => Device($value.v_device),\n                        TVMArgTypeCode_kTVMOpaqueHandle => Handle($value.v_handle),\n                        TVMArgTypeCode_kTVMDLTensorHandle => ArrayHandle($value.v_handle as TVMArrayHandle),\n                        TVMArgTypeCode_kTVMObjectHandle => ObjectHandle($value.v_handle),\n                        TVMArgTypeCode_kTVMObjectRValueRefArg => ObjectHandle(*($value.v_handle as *mut *mut c_void)),\n                        TVMArgTypeCode_kTVMModuleHandle => ModuleHandle($value.v_handle),\n                        TVMArgTypeCode_kTVMPackedFuncHandle => FuncHandle($value.v_handle),\n                        TVMArgTypeCode_kTVMNDArrayHandle => NDArrayHandle($value.v_handle),\n                        $( $tvm_type => { $from_tvm_type } ),+\n                        _ => unimplemented!(\"{}\", type_code),\n                    }\n                }\n            }\n\n            pub fn to_tvm_value(&self) -> (TVMValue, TVMArgTypeCode) {\n                use $name::*;\n                match self {\n                    Int(val) => (TVMValue { v_int64: *val }, DLDataTypeCode_kDLInt),\n                    UInt(val) => (TVMValue { v_int64: *val as i64 }, DLDataTypeCode_kDLUInt),\n                    Float(val) => (TVMValue { v_float64: *val }, DLDataTypeCode_kDLFloat),\n                    Null => (TVMValue{ v_int64: 0 },TVMArgTypeCode_kTVMNullptr),\n                    DataType(val) => (TVMValue { v_type: *val }, TVMArgTypeCode_kTVMDataType),\n                    Device(val) => (TVMValue { v_device: val.clone() }, TVMArgTypeCode_kDLDevice),\n                    String(val) => {\n                        (\n                            TVMValue { v_handle: *val as *mut c_void },\n                            TVMArgTypeCode_kTVMStr,\n                        )\n                    }\n                    Handle(val) => (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMOpaqueHandle),\n                    ArrayHandle(val) => {\n                        (\n                            TVMValue { v_handle: *val as *const _ as *mut c_void },\n                            TVMArgTypeCode_kTVMNDArrayHandle,\n                        )\n                    },\n                    ObjectHandle(val) => (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMObjectHandle),\n                    ModuleHandle(val) =>\n                        (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMModuleHandle),\n                    FuncHandle(val) => (\n                        TVMValue { v_handle: *val },\n                        TVMArgTypeCode_kTVMPackedFuncHandle\n                    ),\n                    NDArrayHandle(val) =>\n                        (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMNDArrayHandle),\n                    $( $self_type($val) => { $from_self_type } ),+\n                }\n            }\n        }\n    }\n}\n\nTVMPODValue! {\n    /// A borrowed TVMPODValue. Can be constructed using `into()` but the preferred way\n    /// to obtain a `ArgValue` is automatically via `call_packed!`.\n    ArgValue<'a> {\n        Bytes(&'a TVMByteArray),\n        Str(&'a CStr),\n    },\n    match value {\n        TVMArgTypeCode_kTVMBytes => { Bytes(&*(value.v_handle as *const TVMByteArray)) }\n        TVMArgTypeCode_kTVMStr => { Str(CStr::from_ptr(value.v_handle as *const i8)) }\n    },\n    match &self {\n        Bytes(val) => {\n            (TVMValue { v_handle: *val as *const _ as *mut c_void }, TVMArgTypeCode_kTVMBytes)\n        }\n        Str(val) => { (TVMValue { v_handle: val.as_ptr() as *mut c_void }, TVMArgTypeCode_kTVMStr) }\n    }\n}\n\nTVMPODValue! {\n    /// An owned TVMPODValue. Can be converted from a variety of primitive and object types.\n    /// Can be downcasted using `try_from` if it contains the desired type.\n    ///\n    /// # Example\n    ///\n    /// ```\n    /// use std::convert::{TryFrom, TryInto};\n    /// use tvm_sys::RetValue;\n    ///\n    /// let a = 42u32;\n    /// let b: u32 = tvm_sys::RetValue::from(a).try_into().unwrap();\n    ///\n    /// let s = \"hello, world!\";\n    /// let t: RetValue = s.to_string().into();\n    /// assert_eq!(String::try_from(t).unwrap(), s);\n    /// ```\n    RetValue {\n        Bytes(TVMByteArray),\n        Str(&'static CStr),\n    },\n    match value {\n        TVMArgTypeCode_kTVMBytes => { Bytes(*(value.v_handle as *const TVMByteArray)) }\n        TVMArgTypeCode_kTVMStr => { Str(CStr::from_ptr(value.v_handle as *mut i8)) }\n    },\n    match &self {\n        Bytes(val) =>\n            { (TVMValue { v_handle: val as *const _ as *mut c_void }, TVMArgTypeCode_kTVMBytes ) }\n        Str(val) =>\n            { (TVMValue { v_str: val.as_ptr() }, TVMArgTypeCode_kTVMStr ) }\n    }\n}\n\n#[macro_export]\nmacro_rules! try_downcast {\n    ($val:ident -> $into:ty, $( |$pat:pat| { $converter:expr } ),+ ) => {\n        match $val {\n            $( $pat => { Ok($converter) } )+\n            _ => Err($crate::errors::ValueDowncastError {\n                actual_type: format!(\"{:?}\", $val),\n                expected_type: stringify!($into),\n            }),\n        }\n    };\n}\n\n/// Creates a conversion to a `ArgValue` for a primitive type and DLDataTypeCode.\nmacro_rules! impl_pod_value {\n    ($variant:ident, $inner_ty:ty, [ $( $type:ty ),+ ] ) => {\n        $(\n            impl<'a> From<$type> for ArgValue<'a> {\n                fn from(val: $type) -> Self {\n                    Self::$variant(val as $inner_ty)\n                }\n            }\n\n            impl<'a> From<&'a $type> for ArgValue<'a> {\n                fn from(val: &'a $type) -> Self {\n                    Self::$variant(*val as $inner_ty)\n                }\n            }\n\n            impl<'a> TryFrom<ArgValue<'a>> for $type {\n                type Error = $crate::errors::ValueDowncastError;\n                fn try_from(val: ArgValue<'a>) -> Result<Self, Self::Error> {\n                    try_downcast!(val -> $type, |ArgValue::$variant(val)| { val as $type })\n                }\n            }\n\n            impl<'a, 'v> TryFrom<&'a ArgValue<'v>> for $type {\n                type Error = $crate::errors::ValueDowncastError;\n                fn try_from(val: &'a ArgValue<'v>) -> Result<Self, Self::Error> {\n                    try_downcast!(val -> $type, |ArgValue::$variant(val)| { *val as $type })\n                }\n            }\n\n            impl From<$type> for RetValue {\n                fn from(val: $type) -> Self {\n                    Self::$variant(val as $inner_ty)\n                }\n            }\n\n            impl TryFrom<RetValue> for $type {\n              type Error = $crate::errors::ValueDowncastError;\n                fn try_from(val: RetValue) -> Result<Self, Self::Error> {\n                    try_downcast!(val -> $type, |RetValue::$variant(val)| { val as $type })\n                }\n            }\n        )+\n    };\n}\n\nimpl_pod_value!(Int, i64, [i8, i16, i32, i64, isize]);\nimpl_pod_value!(UInt, i64, [u8, u16, u32, u64, usize]);\nimpl_pod_value!(Float, f64, [f32, f64]);\nimpl_pod_value!(DataType, DLDataType, [DLDataType]);\nimpl_pod_value!(Device, DLDevice, [DLDevice]);\n\nimpl<'a> From<&'a str> for ArgValue<'a> {\n    fn from(s: &'a str) -> Self {\n        Self::String(CString::new(s).unwrap().into_raw())\n    }\n}\n\nimpl<'a> From<String> for ArgValue<'a> {\n    fn from(s: String) -> Self {\n        Self::String(CString::new(s).unwrap().into_raw())\n    }\n}\n\nimpl<'a> From<&'a CStr> for ArgValue<'a> {\n    fn from(s: &'a CStr) -> Self {\n        Self::Str(s)\n    }\n}\n\nimpl<'a> From<&'a CString> for ArgValue<'a> {\n    fn from(s: &'a CString) -> Self {\n        Self::String(s.as_ptr() as _)\n    }\n}\n\nimpl<'a> From<&'a TVMByteArray> for ArgValue<'a> {\n    fn from(s: &'a TVMByteArray) -> Self {\n        Self::Bytes(s)\n    }\n}\n\nimpl<'a> TryFrom<ArgValue<'a>> for &'a str {\n    type Error = ValueDowncastError;\n    fn try_from(val: ArgValue<'a>) -> Result<Self, Self::Error> {\n        try_downcast!(val -> &str, |ArgValue::Str(s)| { s.to_str().unwrap() })\n    }\n}\n\nimpl<'a, 'v> TryFrom<&'a ArgValue<'v>> for &'v str {\n    type Error = ValueDowncastError;\n    fn try_from(val: &'a ArgValue<'v>) -> Result<Self, Self::Error> {\n        try_downcast!(val -> &str, |ArgValue::Str(s)| { s.to_str().unwrap() })\n    }\n}\n\n/// Converts an unspecialized handle to a ArgValue.\nimpl<'a, T> From<*const T> for ArgValue<'a> {\n    fn from(ptr: *const T) -> Self {\n        Self::Handle(ptr as *mut c_void)\n    }\n}\n\n/// Converts an unspecialized mutable handle to a ArgValue.\nimpl<'a, T> From<*mut T> for ArgValue<'a> {\n    fn from(ptr: *mut T) -> Self {\n        Self::Handle(ptr as *mut c_void)\n    }\n}\n\nimpl<'a> From<&'a mut DLTensor> for ArgValue<'a> {\n    fn from(arr: &'a mut DLTensor) -> Self {\n        Self::ArrayHandle(arr as *mut DLTensor)\n    }\n}\n\nimpl<'a> From<&'a DLTensor> for ArgValue<'a> {\n    fn from(arr: &'a DLTensor) -> Self {\n        Self::ArrayHandle(arr as *const _ as *mut DLTensor)\n    }\n}\n\nimpl TryFrom<RetValue> for String {\n    type Error = ValueDowncastError;\n    fn try_from(val: RetValue) -> Result<String, Self::Error> {\n        try_downcast!(\n            val -> String,\n            |RetValue::String(s)| { unsafe { CString::from_raw(s).into_string().unwrap() }},\n            |RetValue::Str(s)| { s.to_str().unwrap().to_string() }\n        )\n    }\n}\n\nimpl From<String> for RetValue {\n    fn from(s: String) -> Self {\n        Self::String(std::ffi::CString::new(s).unwrap().into_raw())\n    }\n}\n\nimpl From<TVMByteArray> for RetValue {\n    fn from(arr: TVMByteArray) -> Self {\n        Self::Bytes(arr)\n    }\n}\n\nimpl TryFrom<RetValue> for TVMByteArray {\n    type Error = ValueDowncastError;\n    fn try_from(val: RetValue) -> Result<Self, Self::Error> {\n        try_downcast!(val -> TVMByteArray, |RetValue::Bytes(val)| { val })\n    }\n}\n\nimpl Default for RetValue {\n    fn default() -> Self {\n        Self::Int(0)\n    }\n}\n\nimpl TryFrom<RetValue> for std::ffi::CString {\n    type Error = ValueDowncastError;\n    fn try_from(val: RetValue) -> Result<CString, Self::Error> {\n        try_downcast!(val -> std::ffi::CString,\n            |RetValue::Str(val)| { val.into() })\n    }\n}\n\n// Implementations for bool.\n\nimpl<'a> From<&bool> for ArgValue<'a> {\n    fn from(s: &bool) -> Self {\n        (*s as i64).into()\n    }\n}\n\nimpl From<bool> for RetValue {\n    fn from(s: bool) -> Self {\n        (s as i64).into()\n    }\n}\n\nimpl TryFrom<RetValue> for bool {\n    type Error = ValueDowncastError;\n\n    fn try_from(val: RetValue) -> Result<bool, Self::Error> {\n        try_downcast!(val -> bool,\n            |RetValue::Int(val)| { !(val == 0) })\n    }\n}\n\nimpl<'a> TryFrom<ArgValue<'a>> for bool {\n    type Error = ValueDowncastError;\n\n    fn try_from(val: ArgValue<'a>) -> Result<bool, Self::Error> {\n        try_downcast!(val -> bool, |ArgValue::Int(val)| { !(val == 0) })\n    }\n}\n\nimpl From<()> for RetValue {\n    fn from(_: ()) -> Self {\n        RetValue::Null\n    }\n}\n\nimpl TryFrom<RetValue> for () {\n    type Error = ValueDowncastError;\n\n    fn try_from(val: RetValue) -> Result<(), Self::Error> {\n        try_downcast!(val -> bool,\n            |RetValue::Null| { () })\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm-sys/src/value.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::str::FromStr;\n\nuse crate::ffi::*;\n\nuse thiserror::Error;\n\nmacro_rules! impl_pod_tvm_value {\n    ($field:ident, $field_ty:ty, $( $ty:ty ),+) => {\n        $(\n            impl From<$ty> for TVMValue {\n                fn from(val: $ty) -> Self {\n                    TVMValue { $field: val as $field_ty }\n                }\n            }\n\n            impl From<TVMValue> for $ty {\n                fn from(val: TVMValue) -> Self {\n                    unsafe { val.$field as $ty }\n                }\n            }\n        )+\n    };\n    ($field:ident, $ty:ty) => {\n        impl_pod_tvm_value!($field, $ty, $ty);\n    }\n}\n\nimpl_pod_tvm_value!(v_int64, i64, i8, u8, i16, u16, i32, u32, i64, u64, isize, usize);\nimpl_pod_tvm_value!(v_float64, f64, f32, f64);\nimpl_pod_tvm_value!(v_type, DLDataType);\nimpl_pod_tvm_value!(v_device, DLDevice);\n\n#[derive(Debug, Error)]\n#[error(\"unsupported device: {0}\")]\npub struct UnsupportedDeviceError(String);\n\nmacro_rules! impl_tvm_device {\n    ( $( $dev_type:ident : [ $( $dev_name:ident ),+ ] ),+ ) => {\n        /// Creates a DLDevice from a string (e.g., \"cpu\", \"cuda\", \"ext_dev\")\n        impl FromStr for DLDevice {\n            type Err = UnsupportedDeviceError;\n            fn from_str(type_str: &str) -> Result<Self, Self::Err> {\n                Ok(Self {\n                    device_type: match type_str {\n                         $( $(  stringify!($dev_name)  )|+ => $dev_type ),+,\n                        _ => return Err(UnsupportedDeviceError(type_str.to_string())),\n                    },\n                    device_id: 0,\n                })\n            }\n        }\n\n        impl DLDevice {\n            $(\n                $(\n                    pub fn $dev_name(device_id: usize) -> Self {\n                        Self {\n                            device_type: $dev_type,\n                            device_id: device_id as i32,\n                        }\n                    }\n                )+\n            )+\n        }\n    };\n}\n\nimpl_tvm_device!(\n    DLDeviceType_kDLCPU: [cpu, llvm, stackvm],\n    DLDeviceType_kDLCUDA: [cuda, nvptx],\n    DLDeviceType_kDLOpenCL: [cl],\n    DLDeviceType_kDLMetal: [metal],\n    DLDeviceType_kDLVPI: [vpi],\n    DLDeviceType_kDLROCM: [rocm],\n    DLDeviceType_kDLExtDev: [ext_dev]\n);\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/examples/resnet/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse anyhow::{Context, Result};\nuse std::{io::Write, path::Path, process::Command};\n\nfn main() -> Result<()> {\n    let out_dir = std::env::var(\"CARGO_MANIFEST_DIR\")?;\n    let python_script = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/build_resnet.py\");\n    let synset_txt = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/synset.txt\");\n\n    println!(\"cargo:rerun-if-changed={}\", python_script);\n    println!(\"cargo:rerun-if-changed={}\", synset_txt);\n\n    let output = Command::new(\"python3\")\n        .arg(python_script)\n        .arg(&format!(\"--build-dir={}\", out_dir))\n        .output()\n        .with_context(|| anyhow::anyhow!(\"failed to run python3\"))?;\n\n    if !output.status.success() {\n        std::io::stdout()\n            .write_all(&output.stderr)\n            .context(\"Failed to write error\")?;\n        panic!(\"Failed to execute build script\");\n    }\n\n    assert!(\n        Path::new(&format!(\"{}/deploy_lib.o\", out_dir)).exists(),\n        \"Could not prepare demo: {}\",\n        String::from_utf8(output.stderr)\n            .unwrap()\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n    println!(\"cargo:rustc-link-search=native={}\", out_dir);\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/examples/resnet/src/build_resnet.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport csv\nimport logging\nfrom os import path as osp\nimport sys\nimport shutil\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay, runtime\nfrom tvm.relay import testing\nfrom tvm.contrib import graph_executor, cc\nfrom PIL import Image\nfrom tvm.contrib.download import download_testdata\nfrom mxnet.gluon.model_zoo.vision import get_model\n\nlogging.basicConfig(\n    level=logging.INFO, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n)\nlogger = logging.getLogger(__name__)\n\nparser = argparse.ArgumentParser(description=\"Resnet build example\")\naa = parser.add_argument\naa(\"--build-dir\", type=str, required=True, help=\"directory to put the build artifacts\")\naa(\"--batch-size\", type=int, default=1, help=\"input image batch size\")\naa(\n    \"--opt-level\",\n    type=int,\n    default=3,\n    help=\"level of optimization. 0 is unoptimized and 3 is the highest level\",\n)\naa(\"--target\", type=str, default=\"llvm\", help=\"target for compilation\")\naa(\"--image-shape\", type=str, default=\"3,224,224\", help=\"input image dimensions\")\naa(\"--image-name\", type=str, default=\"cat.png\", help=\"name of input image to download\")\nargs = parser.parse_args()\n\nbuild_dir = args.build_dir\nbatch_size = args.batch_size\nopt_level = args.opt_level\ntarget = tvm.target.create(args.target)\nimage_shape = tuple(map(int, args.image_shape.split(\",\")))\ndata_shape = (batch_size,) + image_shape\n\n\ndef build(target_dir):\n    \"\"\"Compiles resnet18 with TVM\"\"\"\n    # Download the pretrained model in MxNet's format.\n    block = get_model(\"resnet18_v1\", pretrained=True)\n\n    shape_dict = {\"data\": (1, 3, 224, 224)}\n    mod, params = relay.frontend.from_mxnet(block, shape_dict)\n    # Add softmax to do classification in last layer.\n    func = mod[\"main\"]\n    func = relay.Function(\n        func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs\n    )\n\n    target = \"llvm\"\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(func, target, params=params)\n\n    # save the model artifacts\n    deploy_lib = osp.join(target_dir, \"deploy_lib.o\")\n    lib.save(deploy_lib)\n    cc.create_shared(osp.join(target_dir, \"deploy_lib.so\"), [osp.join(target_dir, \"deploy_lib.o\")])\n\n    with open(osp.join(target_dir, \"deploy_graph.json\"), \"w\") as fo:\n        fo.write(graph)\n\n    with open(osp.join(target_dir, \"deploy_param.params\"), \"wb\") as fo:\n        fo.write(runtime.save_param_dict(params))\n\n\ndef download_img_labels():\n    \"\"\"Download an image and imagenet1k class labels for test\"\"\"\n    from mxnet.gluon.utils import download\n\n    synset_url = \"\".join(\n        [\n            \"https://gist.githubusercontent.com/zhreshold/\",\n            \"4d0b62f3d01426887599d4f7ede23ee5/raw/\",\n            \"596b27d23537e5a1b5751d2b0481ef172f58b539/\",\n            \"imagenet1000_clsid_to_human.txt\",\n        ]\n    )\n    synset_name = \"synset.txt\"\n    synset_path = download_testdata(synset_url, synset_name + \".raw\", module=\"data\", overwrite=True)\n\n    with open(synset_path) as fin:\n        data = fin.read()\n        synset = eval(data)\n\n    with open(synset_name, \"w\") as f:\n        for key in synset:\n            f.write(synset[key])\n            f.write(\"\\n\")\n\n    print(synset_path)\n    print(synset_name)\n\n    return synset\n\n\ndef transform_image(image):\n    image = np.array(image) - np.array([123.0, 117.0, 104.0])\n    image /= np.array([58.395, 57.12, 57.375])\n    image = image.transpose((2, 0, 1))\n    image = image[np.newaxis, :]\n    return image\n\n\ndef get_cat_image():\n    img_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\n    img_path = download_testdata(img_url, \"cat.png\", module=\"data\")\n    shutil.copyfile(img_path, \"cat.png\")\n    img = Image.open(img_path).resize((224, 224))\n    return transform_image(img)\n\n\ndef test_build(build_dir):\n    \"\"\"Sanity check with the cat image we download.\"\"\"\n    graph = open(osp.join(build_dir, \"deploy_graph.json\")).read()\n    lib = tvm.runtime.load_module(osp.join(build_dir, \"deploy_lib.so\"))\n    params = bytearray(open(osp.join(build_dir, \"deploy_param.params\"), \"rb\").read())\n    input_data = get_cat_image()\n    dev = tvm.cpu()\n    module = graph_executor.create(graph, lib, dev)\n    module.load_params(params)\n    module.run(data=input_data)\n    out = module.get_output(0).numpy()\n    top1 = np.argmax(out[0])\n    synset = download_img_labels()\n    print(\"TVM prediction top-1:\", top1, synset[top1])\n\n\nif __name__ == \"__main__\":\n    logger.info(\"Compiling the model to graph executor.\")\n    build(build_dir)\n    logger.info(\"Testing the model's predication on test data.\")\n    test_build(build_dir)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/examples/resnet/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::{\n    fs::{self, File},\n    io::{BufRead, BufReader},\n    path::Path,\n};\n\nuse ::ndarray::{Array, ArrayD, Axis};\nuse image::{FilterType, GenericImageView};\n\nuse anyhow::Context as _;\nuse tvm_rt::graph_rt::GraphRt;\nuse tvm_rt::*;\n\nfn main() -> anyhow::Result<()> {\n    let dev = Device::cpu(0);\n    println!(\"{}\", concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/cat.png\"));\n\n    let img = image::open(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/cat.png\"))\n        .context(\"Failed to open cat.png\")?;\n\n    println!(\"original image dimensions: {:?}\", img.dimensions());\n    // for bigger size images, one needs to first resize to 256x256\n    // with `img.resize_exact` method and then `image.crop` to 224x224\n    let img = img.resize(224, 224, FilterType::Nearest).to_rgb();\n    println!(\"resized image dimensions: {:?}\", img.dimensions());\n    let mut pixels: Vec<f32> = vec![];\n    for pixel in img.pixels() {\n        let tmp = pixel.data;\n        // normalize the RGB channels using mean, std of imagenet1k\n        let tmp = [\n            (tmp[0] as f32 - 123.0) / 58.395, // R\n            (tmp[1] as f32 - 117.0) / 57.12,  // G\n            (tmp[2] as f32 - 104.0) / 57.375, // B\n        ];\n        for e in &tmp {\n            pixels.push(*e);\n        }\n    }\n\n    let arr = Array::from_shape_vec((224, 224, 3), pixels)?;\n    let arr: ArrayD<f32> = arr.permuted_axes([2, 0, 1]).into_dyn();\n    // make arr shape as [1, 3, 224, 224] acceptable to resnet\n    let arr = arr.insert_axis(Axis(0));\n    // create input tensor from rust's ndarray\n    let input = NDArray::from_rust_ndarray(&arr, Device::cpu(0), DataType::float(32, 1))?;\n    println!(\n        \"input shape is {:?}, len: {}, size: {}\",\n        input.shape(),\n        input.len(),\n        input.size(),\n    );\n\n    let graph = fs::read_to_string(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/deploy_graph.json\"))\n        .context(\"Failed to open graph\")?;\n\n    // load the built module\n    let lib = Module::load(&Path::new(concat!(\n        env!(\"CARGO_MANIFEST_DIR\"),\n        \"/deploy_lib.so\"\n    )))?;\n\n    // parse parameters and convert to TVMByteArray\n    let params: Vec<u8> = fs::read(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/deploy_param.params\"))?;\n    println!(\"param bytes: {}\", params.len());\n\n    // If you want an easy way to test a memory leak simply replace the program below with:\n    // let mut output: Vec<f32>;\n\n    // loop {\n    //     let mut graph_rt = GraphRt::create_from_parts(&graph, lib.clone(), dev)?;\n    //     graph_rt.load_params(params.clone())?;\n    //     graph_rt.set_input(\"data\", input.clone())?;\n    //     graph_rt.run()?;\n\n    //     // prepare to get the output\n    //     let output_shape = &[1, 1000];\n    //     let output_nd = NDArray::empty(output_shape, Device::cpu(0), DataType::float(32, 1));\n    //     graph_rt.get_output_into(0, output_nd.clone())?;\n\n    //     // flatten the output as Vec<f32>\n    //     output = output_nd.to_vec::<f32>()?;\n    // }\n\n    let mut graph_rt = GraphRt::create_from_parts(&graph, lib, dev)?;\n    graph_rt.load_params(params)?;\n    graph_rt.set_input(\"data\", input)?;\n    graph_rt.run()?;\n\n    // prepare to get the output\n    let output_shape = &[1, 1000];\n    let output_nd = NDArray::empty(output_shape, Device::cpu(0), DataType::float(32, 1));\n    graph_rt.get_output_into(0, output_nd.clone())?;\n\n    // flatten the output as Vec<f32>\n    let output: Vec<f32> = output_nd.to_vec::<f32>()?;\n\n    // find the maximum entry in the output and its index\n    let (argmax, max_prob) = output\n        .iter()\n        .copied()\n        .enumerate()\n        .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())\n        .unwrap();\n\n    // create a hash map of (class id, class name)\n    let file = File::open(\"synset.txt\").context(\"failed to open synset\")?;\n    let synset: Vec<std::string::String> = BufReader::new(file)\n        .lines()\n        .into_iter()\n        .map(|x| x.expect(\"readline failed\"))\n        .collect();\n\n    let label = &synset[argmax];\n    println!(\n        \"input image belongs to the class `{}` with probability {}\",\n        label, max_prob\n    );\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/bin/tyck.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::path::PathBuf;\n\nuse anyhow::Result;\nuse structopt::StructOpt;\n\nuse tvm::ir::diagnostics::codespan;\nuse tvm::ir::{self, IRModule};\nuse tvm::runtime::Error;\n\n#[derive(Debug, StructOpt)]\n#[structopt(name = \"tyck\", about = \"Parse and type check a Relay program.\")]\nstruct Opt {\n    /// Input file\n    #[structopt(parse(from_os_str))]\n    input: PathBuf,\n}\n\nfn main() -> Result<()> {\n    codespan::init().expect(\"Failed to initialize Rust based diagnostics.\");\n    let opt = Opt::from_args();\n    let _module = match IRModule::parse_file(opt.input) {\n        Err(ir::module::Error::TVM(Error::DiagnosticError(_))) => return Ok(()),\n        Err(e) => {\n            return Err(e.into());\n        }\n        Ok(module) => module,\n    };\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/compiler/graph_rt.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryInto;\nuse std::io::Read;\nuse std::path::Path;\n\nuse once_cell::sync::Lazy;\nuse thiserror::Error;\n\nuse crate::ir::IRModule;\nuse crate::python;\nuse crate::runtime::{map::Map, Function, Module as RtModule, NDArray, String};\n\n#[derive(Error, Debug)]\npub enum Error {\n    #[error(\"{0}\")]\n    IO(#[from] std::io::Error),\n    #[error(\"{0}\")]\n    TVM(#[from] crate::errors::Error),\n}\n\nstatic TVM_BUILD: Lazy<Function> = Lazy::new(|| {\n    python::import(\"tvm\").unwrap();\n    python::import(\"tvm.relay\").unwrap();\n    Function::get(\"tvm.relay.build\").unwrap()\n});\n\nfn _compile_module(\n    module: IRModule,\n    target: String,\n    target_host: String,\n    params: Map<String, NDArray>,\n    module_name: String,\n) -> Result<RtModule, Error> {\n    // The RAW API is Fn(IRModule, String, String, Map<String, NDArray>, String);\n    let module = TVM_BUILD.invoke(vec![\n        (&module).into(),\n        (&target).into(),\n        (&target_host).into(),\n        (&params).into(),\n        (&module_name).into(),\n    ])?;\n    let module: RtModule = module.try_into().unwrap();\n    Ok(module)\n}\n\n#[derive(Debug)]\npub struct CompilerConfig {\n    target: Option<String>,\n    target_host: Option<String>,\n    params: Map<String, NDArray>,\n    module_name: Option<String>,\n}\n\nimpl Default for CompilerConfig {\n    fn default() -> Self {\n        CompilerConfig {\n            target: None,\n            target_host: None,\n            params: Map::empty(),\n            module_name: None,\n        }\n    }\n}\n\n/// Compile a module from a configuration and IRModule.\n///\n/// # Arguments\n///\n/// * `config` - The configuration for the compiler.\n/// * `module` - The IRModule to compile.\npub fn compile_module(config: CompilerConfig, module: IRModule) -> Result<RtModule, Error> {\n    let target = config.target.unwrap_or(\"llvm\".into());\n    _compile_module(\n        module,\n        target,\n        \"llvm\".into(),\n        Map::<String, NDArray>::empty(),\n        \"default\".into(),\n    )\n}\n\n/// Compile an IRModule on disk and output a runtime module to disk.\n///\n/// # Arguments\n/// * `config` - The configuration for the compiler.\n/// * `ir_mod_path` - The path the serialized IRModule.\n//\n/// * `output_rt_mod_path` - The path to the output runtime module.\npub fn compile_from_disk<P1, P2>(\n    config: CompilerConfig,\n    ir_mod_path: P1,\n    output_rt_mod_path: P2,\n) -> Result<(), Error>\nwhere\n    P1: AsRef<Path>,\n    P2: AsRef<Path>,\n{\n    let mut input_file = std::fs::File::open(ir_mod_path.as_ref())?;\n    let mut input_module_text = std::string::String::new();\n    input_file.read_to_string(&mut input_module_text)?;\n    let input_module = IRModule::parse(\"name\", input_module_text)?;\n    let rt_module = compile_module(config, input_module)?;\n    let output_path_str = output_rt_mod_path.as_ref().display().to_string();\n    rt_module.export_library(output_path_str)?;\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/compiler/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npub mod graph_rt;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/arith.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::runtime::{Object, ObjectPtr};\n\nuse tvm_macros::Object;\n\nmacro_rules! define_node {\n    ($name:ident, $ref:expr, $typekey:expr; $node:ident { $($id:ident : $t:ty),*}) => {\n        #[repr(C)]\n        #[derive(Object, Debug)]\n        #[ref_name = $ref]\n        #[type_key = $typekey]\n        pub struct $node {\n            base: Object,\n            $(pub $id : $t),*\n        }\n\n        impl $name {\n            pub fn new($($id : $t,)*) -> $name {\n                let base = Object::base::<$node>();\n                let node = $node { base, $($id),* };\n                $name(Some(ObjectPtr::new(node)))\n            }\n        }\n    }\n}\n\ndefine_node!(ConstIntBound, \"ConstIntBound\", \"arith.ConstIntBound\";\n             ConstIntBoundNode { min_value: i64, max_value: i64 });\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/attrs.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::runtime::Object;\nuse tvm_macros::Object;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Attrs\"]\n#[type_key = \"Attrs\"]\npub struct BaseAttrsNode {\n    pub base: Object,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/diagnostics/codespan.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! A TVM diagnostics renderer which uses the Rust `codespan` library\n//! to produce error messages.\n//!\n//! This is an example of using the exposed API surface of TVM to\n//! customize the compiler behavior.\nuse std::collections::HashMap;\nuse std::sync::{Arc, Mutex};\n\nuse codespan_reporting::diagnostic::{Diagnostic as CDiagnostic, Label, Severity};\nuse codespan_reporting::files::SimpleFiles;\nuse codespan_reporting::term::termcolor::{ColorChoice, StandardStream};\nuse codespan_reporting::term::{self};\n\nuse super::*;\nuse crate::ir::source_map::*;\n\n/// A representation of a TVM Span as a range of bytes in a file.\nstruct ByteRange<FileId> {\n    /// The file in which the range occurs.\n    #[allow(dead_code)]\n    file_id: FileId,\n    /// The range start.\n    start_pos: usize,\n    /// The range end.\n    end_pos: usize,\n}\n\n/// A mapping from Span to ByteRange for a single file.\nenum FileSpanToByteRange {\n    AsciiSource(Vec<usize>),\n    #[allow(dead_code)]\n    Utf8 {\n        /// Map character regions which are larger then 1-byte to length.\n        lengths: HashMap<isize, isize>,\n        /// The source of the program.\n        source: String,\n    },\n}\n\nimpl FileSpanToByteRange {\n    /// Construct a span to byte range mapping from the program source.\n    fn new(source: String) -> FileSpanToByteRange {\n        if source.is_ascii() {\n            let line_lengths = source.lines().map(|line| line.len()).collect();\n            FileSpanToByteRange::AsciiSource(line_lengths)\n        } else {\n            panic!()\n        }\n    }\n\n    /// Lookup the corresponding ByteRange for a given Span.\n    fn lookup(&self, span: &Span) -> ByteRange<String> {\n        use FileSpanToByteRange::*;\n\n        let source_name: String = span.source_name.name.as_str().unwrap().into();\n\n        match self {\n            AsciiSource(ref line_lengths) => {\n                let start_pos = (&line_lengths[0..(span.line - 1) as usize])\n                    .into_iter()\n                    .sum::<usize>()\n                    + (span.column) as usize;\n                let end_pos = (&line_lengths[0..(span.end_line - 1) as usize])\n                    .into_iter()\n                    .sum::<usize>()\n                    + (span.end_column) as usize;\n                ByteRange {\n                    file_id: source_name,\n                    start_pos,\n                    end_pos,\n                }\n            }\n            _ => panic!(),\n        }\n    }\n}\n\n/// A mapping for all files in a source map to byte ranges.\nstruct SpanToByteRange {\n    map: HashMap<String, FileSpanToByteRange>,\n}\n\nimpl SpanToByteRange {\n    fn new() -> SpanToByteRange {\n        SpanToByteRange {\n            map: HashMap::new(),\n        }\n    }\n\n    /// Add a source file to the span mapping.\n    pub fn add_source(&mut self, source: Source) {\n        let source_name: String = source.source_name.name.as_str().expect(\"foo\").into();\n\n        if self.map.contains_key(&source_name) {\n            panic!()\n        } else {\n            let source = source.source.as_str().expect(\"fpp\").into();\n            self.map\n                .insert(source_name, FileSpanToByteRange::new(source));\n        }\n    }\n\n    /// Lookup a span to byte range mapping.\n    ///\n    /// First resolves the Span to a file, and then maps the span to a byte range in the file.\n    pub fn lookup(&self, span: &Span) -> ByteRange<String> {\n        let source_name: String = span.source_name.name.as_str().expect(\"foo\").into();\n\n        match self.map.get(&source_name) {\n            Some(file_span_to_bytes) => file_span_to_bytes.lookup(span),\n            None => panic!(),\n        }\n    }\n}\n\n/// The state of the `codespan` based diagnostics.\nstruct DiagnosticState {\n    files: SimpleFiles<String, String>,\n    span_map: SpanToByteRange,\n    // todo unify wih source name\n    source_to_id: HashMap<String, usize>,\n}\n\nimpl DiagnosticState {\n    fn new() -> DiagnosticState {\n        DiagnosticState {\n            files: SimpleFiles::new(),\n            span_map: SpanToByteRange::new(),\n            source_to_id: HashMap::new(),\n        }\n    }\n\n    fn add_source(&mut self, source: Source) {\n        let source_str: String = source.source.as_str().unwrap().into();\n        let source_name: String = source.source_name.name.as_str().unwrap().into();\n        self.span_map.add_source(source);\n        let file_id = self.files.add(source_name.clone(), source_str);\n        self.source_to_id.insert(source_name, file_id);\n    }\n\n    fn to_diagnostic(&self, diag: super::Diagnostic) -> CDiagnostic<usize> {\n        let severity = match diag.level {\n            DiagnosticLevel::Error => Severity::Error,\n            DiagnosticLevel::Warning => Severity::Warning,\n            DiagnosticLevel::Note => Severity::Note,\n            DiagnosticLevel::Help => Severity::Help,\n            DiagnosticLevel::Bug => Severity::Bug,\n        };\n\n        let source_name: String = diag.span.source_name.name.as_str().unwrap().into();\n        let file_id = *self.source_to_id.get(&source_name).unwrap();\n\n        let message: String = diag.message.as_str().unwrap().into();\n\n        let byte_range = self.span_map.lookup(&diag.span);\n\n        let diagnostic = CDiagnostic::new(severity)\n            .with_message(message)\n            .with_code(\"EXXX\")\n            .with_labels(vec![Label::primary(\n                file_id,\n                byte_range.start_pos..byte_range.end_pos,\n            )]);\n\n        diagnostic\n    }\n}\n\nfn renderer(state: &mut DiagnosticState, diag_ctx: DiagnosticContext) {\n    let source_map = diag_ctx.module.source_map.clone();\n    let writer = StandardStream::stderr(ColorChoice::Always);\n    let config = codespan_reporting::term::Config::default();\n    for diagnostic in diag_ctx.diagnostics.clone() {\n        match source_map.source_map.get(&diagnostic.span.source_name) {\n            Err(err) => panic!(\"{}\", err),\n            Ok(source) => {\n                state.add_source(source);\n                let diagnostic = state.to_diagnostic(diagnostic);\n                term::emit(&mut writer.lock(), &config, &state.files, &diagnostic).unwrap();\n            }\n        }\n    }\n}\n\n/// Initialize the `codespan` based diagnostics.\n///\n/// Calling this function will globally override the TVM diagnostics renderer.\npub fn init() -> Result<()> {\n    let diag_state = Arc::new(Mutex::new(DiagnosticState::new()));\n    let render_fn = move |diag_ctx: DiagnosticContext| {\n        let mut guard = diag_state.lock().unwrap();\n        renderer(&mut *guard, diag_ctx);\n    };\n\n    override_renderer(Some(render_fn))?;\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/diagnostics/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse super::module::IRModule;\nuse super::span::*;\nuse crate::runtime::function::Result;\nuse crate::runtime::object::{Object, ObjectPtr};\nuse crate::runtime::{\n    array::Array,\n    function::{self, Function, ToFunction},\n    string::String as TString,\n};\n/// The diagnostic interface to TVM, used for reporting and rendering\n/// diagnostic information by the compiler. This module exposes\n/// three key abstractions: a Diagnostic, the DiagnosticContext,\n/// and the DiagnosticRenderer.\nuse tvm_macros::{external, Object};\n\npub mod codespan;\n\nexternal! {\n    #[name(\"runtime.ArrayGetItem\")]\n    fn get_renderer() -> DiagnosticRenderer;\n\n    #[name(\"diagnostics.DiagnosticRenderer\")]\n    fn diagnostic_renderer(func: Function) -> DiagnosticRenderer;\n\n    #[name(\"diagnostics.Emit\")]\n    fn emit(ctx: DiagnosticContext, diagnostic: Diagnostic) -> ();\n\n    #[name(\"diagnostics.DiagnosticContextDefault\")]\n    fn diagnostic_context_default(module: IRModule) -> DiagnosticContext;\n\n    #[name(\"diagnostics.DiagnosticContextRender\")]\n    fn diagnostic_context_render(ctx: DiagnosticContext) -> ();\n\n    #[name(\"diagnostics.DiagnosticRendererRender\")]\n    fn diagnositc_renderer_render(renderer: DiagnosticRenderer, ctx: DiagnosticContext) -> ();\n\n    #[name(\"diagnostics.ClearRenderer\")]\n    fn clear_renderer() -> ();\n}\n\n/// The diagnostic level, controls the printing of the message.\n#[repr(C)]\n#[derive(PartialEq, Eq, Debug)]\npub enum DiagnosticLevel {\n    Bug = 10,\n    Error = 20,\n    Warning = 30,\n    Note = 40,\n    Help = 50,\n}\n\n/// A compiler diagnostic.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Diagnostic\"]\n#[type_key = \"Diagnostic\"]\npub struct DiagnosticNode {\n    pub base: Object,\n    /// The level.\n    pub level: DiagnosticLevel,\n    /// The span at which to report an error.\n    pub span: Span,\n    /// The diagnostic message.\n    pub message: TString,\n}\n\nimpl Diagnostic {\n    pub fn new(level: DiagnosticLevel, span: Span, message: TString) -> Diagnostic {\n        let node = DiagnosticNode {\n            base: Object::base::<DiagnosticNode>(),\n            level,\n            span,\n            message,\n        };\n        ObjectPtr::new(node).into()\n    }\n\n    pub fn bug(span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder::new(DiagnosticLevel::Bug, span)\n    }\n\n    pub fn error(span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder::new(DiagnosticLevel::Error, span)\n    }\n\n    pub fn warning(span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder::new(DiagnosticLevel::Warning, span)\n    }\n\n    pub fn note(span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder::new(DiagnosticLevel::Note, span)\n    }\n\n    pub fn help(span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder::new(DiagnosticLevel::Help, span)\n    }\n}\n\n/// A wrapper around std::stringstream to build a diagnostic.\npub struct DiagnosticBuilder {\n    /// The level.\n    pub level: DiagnosticLevel,\n\n    /// The span of the diagnostic.\n    pub span: Span,\n\n    /// The in progress message.\n    pub message: String,\n}\n\nimpl DiagnosticBuilder {\n    pub fn new(level: DiagnosticLevel, span: Span) -> DiagnosticBuilder {\n        DiagnosticBuilder {\n            level,\n            span,\n            message: \"\".into(),\n        }\n    }\n}\n\n/// Display diagnostics in a given display format.\n///\n/// A diagnostic renderer is responsible for converting the\n/// raw diagnostics into consumable output.\n///\n/// For example the terminal renderer will render a sequence\n/// of compiler diagnostics to std::out and std::err in\n/// a human readable form.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"DiagnosticRenderer\"]\n#[type_key = \"DiagnosticRenderer\"]\n/// A diagnostic renderer, which given a diagnostic context produces a \"rendered\"\n/// form of the diagnostics for either human or computer consumption.\npub struct DiagnosticRendererNode {\n    /// The base type.\n    pub base: Object,\n    // TODO(@jroesch): we can't easily exposed packed functions due to\n    // memory layout\n    // missing field here\n}\n\nimpl DiagnosticRenderer {\n    /// Render the provided context.\n    pub fn render(&self, ctx: DiagnosticContext) -> Result<()> {\n        diagnositc_renderer_render(self.clone(), ctx)\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"DiagnosticContext\"]\n#[type_key = \"DiagnosticContext\"]\n/// A diagnostic context for recording errors against a source file.\npub struct DiagnosticContextNode {\n    // The base type.\n    pub base: Object,\n\n    /// The Module to report against.\n    pub module: IRModule,\n\n    /// The set of diagnostics to report.\n    pub diagnostics: Array<Diagnostic>,\n\n    /// The renderer set for the context.\n    pub renderer: DiagnosticRenderer,\n}\n\n/// A diagnostic context which records active errors\n/// and contains a renderer.\nimpl DiagnosticContext {\n    pub fn new<F>(module: IRModule, render_func: F) -> DiagnosticContext\n    where\n        F: Fn(DiagnosticContext) -> () + 'static,\n    {\n        let renderer = diagnostic_renderer(render_func.to_function()).unwrap();\n        let node = DiagnosticContextNode {\n            base: Object::base::<DiagnosticContextNode>(),\n            module,\n            diagnostics: Array::from_vec(vec![]).unwrap(),\n            renderer,\n        };\n        DiagnosticContext(Some(ObjectPtr::new(node)))\n    }\n\n    pub fn default(module: IRModule) -> DiagnosticContext {\n        diagnostic_context_default(module).unwrap()\n    }\n\n    /// Emit a diagnostic.\n    pub fn emit(&mut self, diagnostic: Diagnostic) -> Result<()> {\n        emit(self.clone(), diagnostic)\n    }\n\n    /// Render the errors and raise a DiagnosticError exception.\n    pub fn render(&mut self) -> Result<()> {\n        diagnostic_context_render(self.clone())\n    }\n\n    /// Emit a diagnostic and then immediately attempt to render all errors.\n    pub fn emit_fatal(&mut self, diagnostic: Diagnostic) -> Result<()> {\n        self.emit(diagnostic)?;\n        self.render()?;\n        Ok(())\n    }\n}\n\n/// Override the global diagnostics renderer.\n// render_func: Option[Callable[[DiagnosticContext], None]]\n//     If the render_func is None it will remove the current custom renderer\n//     and return to default behavior.\nfn override_renderer<F>(opt_func: Option<F>) -> Result<()>\nwhere\n    F: Fn(DiagnosticContext) -> () + 'static,\n{\n    match opt_func {\n        None => clear_renderer(),\n        Some(func) => {\n            let func = func.to_function();\n            let render_factory = move || diagnostic_renderer(func.clone()).unwrap();\n\n            function::register_override(render_factory, \"diagnostics.OverrideRenderer\", true)?;\n\n            Ok(())\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/expr.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse tvm_macros::Object;\n\nuse crate::runtime::String as TString;\nuse crate::runtime::{self, external, IsObject, IsObjectRef, Object, ObjectPtr, ObjectRef};\nuse crate::DataType;\n\nuse super::relay;\nuse super::span::Span;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BaseExpr\"]\n#[type_key = \"Expr\"]\npub struct BaseExprNode {\n    pub base: Object,\n    pub span: Span,\n}\n\nimpl BaseExprNode {\n    pub fn base<T: IsObject>(span: Span) -> BaseExprNode {\n        BaseExprNode {\n            base: Object::base::<T>(),\n            span,\n        }\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PrimExpr\"]\n#[type_key = \"PrimExpr\"]\npub struct PrimExprNode {\n    pub base: BaseExprNode,\n    pub datatype: DataType,\n}\n\nimpl PrimExprNode {\n    pub fn base<T: IsObject>(datatype: DataType, span: Span) -> PrimExprNode {\n        PrimExprNode {\n            base: BaseExprNode::base::<T>(span),\n            datatype,\n        }\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"GlobalVar\"]\n#[type_key = \"GlobalVar\"]\npub struct GlobalVarNode {\n    pub base: relay::ExprNode,\n    pub name_hint: TString,\n}\n\nimpl GlobalVar {\n    pub fn new(name_hint: String, span: Span) -> GlobalVar {\n        let node = GlobalVarNode {\n            base: relay::ExprNode::base::<GlobalVarNode>(span),\n            name_hint: name_hint.into(),\n        };\n        GlobalVar(Some(ObjectPtr::new(node)))\n    }\n}\n\n// TODO(@jroesch): update to match TVM\n// Move IntImm\n// Define FloatImm\n// Define Bool\n// Define tvm::Integer?\n// Define RangeNode\n\n// TODO: figure out how to type the last argument runtime::TypedPackedFunc<String(ObjectRef)> annotate)\nexternal! {\n    #[name(\"ir.AsText\")]\n    fn _as_text(object: ObjectRef, show_meta_data: i32, annotate: runtime::Function) -> TString;\n}\n\npub fn as_text<T: IsObjectRef>(object: T) -> String {\n    let no_func = unsafe { runtime::Function::null() };\n    _as_text(object.upcast(), 0, no_func)\n        .unwrap()\n        .as_str()\n        .unwrap()\n        .into()\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/function.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse tvm_macros::Object;\n\nuse super::span::Span;\n\nuse crate::ir::relay::ExprNode;\nuse crate::runtime::{IsObject, IsObjectRef, ObjectRef};\n\n// TODO(@jroesch): define DictAttrs\npub type DictAttrs = ObjectRef;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BaseFunc\"]\n#[type_key = \"BaseFunc\"]\npub struct BaseFuncNode {\n    pub base: ExprNode,\n    pub attrs: DictAttrs,\n}\n\nimpl BaseFuncNode {\n    pub fn base<T: IsObject>() -> BaseFuncNode {\n        BaseFuncNode {\n            base: ExprNode::base::<T>(Span::null()),\n            attrs: <ObjectRef as IsObjectRef>::null(),\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npub mod arith;\npub mod attrs;\npub mod diagnostics;\npub mod expr;\npub mod function;\npub mod module;\npub mod op;\npub mod relay;\npub mod source_map;\npub mod span;\npub mod tir;\npub mod ty;\n\npub use expr::*;\npub use module::IRModule;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/module.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::collections::HashMap;\nuse std::iter::FromIterator;\nuse std::path::Path;\n\nuse thiserror::Error;\nuse tvm_macros::Object;\n\nuse crate::runtime::array::Array;\nuse crate::runtime::function::Result;\nuse crate::runtime::map::Map;\nuse crate::runtime::string::String as TVMString;\nuse crate::runtime::{external, IsObjectRef, Object};\n\nuse super::expr::GlobalVar;\nuse super::function::BaseFunc;\nuse super::source_map::SourceMap;\nuse super::{relay, ty::GlobalTypeVar, ty::TypeData};\n\n#[derive(Error, Debug)]\npub enum Error {\n    #[error(\"{0}\")]\n    IO(#[from] std::io::Error),\n    #[error(\"{0}\")]\n    TVM(#[from] crate::runtime::Error),\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"IRModule\"]\n#[type_key = \"IRModule\"]\npub struct IRModuleNode {\n    pub base: Object,\n    pub functions: Map<GlobalVar, BaseFunc>,\n    pub type_definitions: Map<GlobalTypeVar, TypeData>,\n    pub source_map: SourceMap,\n    // TODO(@jroesch): this is missing some fields\n}\n\nexternal! {\n    // Parser functions\n    #[name(\"parser.ParseModule\")]\n    fn parse_module(file_name: TVMString, source: TVMString) -> IRModule;\n    #[name(\"parser.ParseExpr\")]\n    fn parse_expression(file_name: TVMString, source: TVMString) -> IRModule;\n    #[name(\"ir.IRModule\")]\n    fn module_new(funcs: Map<GlobalVar, BaseFunc>, types: Map<GlobalTypeVar, TypeData>) -> IRModule;\n    // Module methods\n    #[name(\"ir.Module_Add\")]\n    fn module_add(module: IRModule, type_name: GlobalVar, expr: BaseFunc, update: bool) -> IRModule;\n    #[name(\"ir.Module_AddDef\")]\n    fn module_add_def(module: IRModule, type_name: GlobalTypeVar, type_data: TypeData, update: bool) -> ();\n    #[name(\"ir.Module_GetGlobalVar\")]\n    fn module_get_global_var(module: IRModule, name: TVMString) -> GlobalVar;\n    #[name(\"ir.Module_GetGlobalVars\")]\n    fn module_get_global_vars(module: IRModule) -> Array<GlobalVar>;\n    #[name(\"ir.Module_Lookup\")]\n    fn module_lookup(module: IRModule, var: GlobalVar) -> BaseFunc;\n    #[name(\"ir.Module_Lookup_str\")]\n    fn module_lookup_str(module: IRModule, name: TVMString) -> BaseFunc;\n    #[name(\"ir.Module_GetGlobalTypeVars\")]\n    fn module_get_global_type_vars(module: IRModule) -> Array<GlobalTypeVar>;\n    #[name(\"ir.Module_ContainGlobalVar\")]\n    fn module_contains_global_var(module: IRModule, name: TVMString) -> bool;\n    #[name(\"ir.Module_ContainGlobalTypeVar\")]\n    fn module_contains_global_type_var(module: IRModule, name: TVMString) -> bool;\n    #[name(\"ir.Module_LookupDef\")]\n    fn module_lookup_def(module: IRModule, global: GlobalTypeVar) -> TypeData;\n    #[name(\"ir.Module_LookupDef_str\")]\n    fn module_lookup_def_str(module: IRModule, global: TVMString) -> TypeData;\n    #[name(\"ir.Module_LookupTag\")]\n    fn module_lookup_tag(module: IRModule, tag: i32) -> relay::Constructor;\n    #[name(\"ir.Module_FromExpr\")]\n    fn module_from_expr(expr: relay::Expr, funcs: Map<GlobalVar, BaseFunc>, types: Map<GlobalTypeVar, TypeData>) -> IRModule;\n    #[name(\"ir.Module_Import\")]\n    fn module_import(module: IRModule, path: TVMString);\n    #[name(\"ir.Module_ImportFromStd\")]\n    fn module_import_from_std(module: IRModule, path: TVMString);\n}\n\n// Note: we don't expose update here as update is going to be removed.\n\nimpl IRModule {\n    pub fn new<'a, F, T>(funcs: F, types: T) -> Result<IRModule>\n    where\n        F: IntoIterator<Item = (&'a GlobalVar, &'a BaseFunc)>,\n        T: IntoIterator<Item = (&'a GlobalTypeVar, &'a TypeData)>,\n    {\n        module_new(Map::from_iter(funcs), Map::from_iter(types))\n    }\n\n    pub fn empty() -> Result<IRModule> {\n        let funcs = HashMap::<GlobalVar, BaseFunc>::new();\n        let types = HashMap::<GlobalTypeVar, TypeData>::new();\n        IRModule::new(funcs.iter(), types.iter())\n    }\n\n    pub fn parse<N, S>(file_name: N, source: S) -> Result<IRModule>\n    where\n        N: Into<TVMString>,\n        S: Into<TVMString>,\n    {\n        parse_module(file_name.into(), source.into())\n    }\n\n    pub fn parse_file<P: 'static + AsRef<Path>>(\n        file_path: P,\n    ) -> std::result::Result<IRModule, Error> {\n        let file_path = file_path.as_ref();\n        let file_path_as_str = file_path.to_str().unwrap().to_string();\n        let source = std::fs::read_to_string(file_path)?;\n        let module = IRModule::parse(file_path_as_str, source)?;\n        Ok(module)\n    }\n\n    pub fn add<F>(&mut self, var: GlobalVar, func: F) -> Result<IRModule>\n    // todo(@jroesch): can we do better here? why doesn't BaseFunc::Object work?\n    where\n        F: IsObjectRef,\n        F::Object: AsRef<<BaseFunc as IsObjectRef>::Object>,\n    {\n        module_add(self.clone(), var, func.upcast(), true)\n    }\n\n    pub fn add_def(\n        &mut self,\n        type_name: GlobalTypeVar,\n        type_data: TypeData,\n        update: bool,\n    ) -> Result<()> {\n        module_add_def(self.clone(), type_name, type_data, update)\n    }\n\n    pub fn get_global_var<S>(&self, name: S) -> Result<GlobalVar>\n    where\n        S: Into<TVMString>,\n    {\n        module_get_global_var(self.clone(), name.into())\n    }\n\n    pub fn get_global_vars(&self) -> Result<Array<GlobalVar>> {\n        module_get_global_vars(self.clone())\n    }\n\n    pub fn lookup(&self, var: GlobalVar) -> Result<BaseFunc> {\n        module_lookup(self.clone(), var)\n    }\n\n    pub fn lookup_str<S>(&self, name: S) -> Result<BaseFunc>\n    where\n        S: Into<TVMString>,\n    {\n        module_lookup_str(self.clone(), name.into())\n    }\n\n    pub fn get_global_type_vars(&self) -> Result<Array<GlobalTypeVar>> {\n        module_get_global_type_vars(self.clone())\n    }\n\n    pub fn contains_global_var<S: Into<TVMString>>(&self, name: S) -> Result<bool> {\n        module_contains_global_var(self.clone(), name.into())\n    }\n\n    pub fn contains_global_type_var<S: Into<TVMString>>(&self, name: S) -> Result<bool> {\n        module_contains_global_type_var(self.clone(), name.into())\n    }\n\n    pub fn lookup_def(&self, global: GlobalTypeVar) -> Result<TypeData> {\n        module_lookup_def(self.clone(), global)\n    }\n\n    pub fn lookup_def_str<S>(&self, global: S) -> Result<TypeData>\n    where\n        S: Into<TVMString>,\n    {\n        module_lookup_def_str(self.clone(), global.into())\n    }\n\n    pub fn lookup_tag(&self, tag: i32) -> Result<relay::Constructor> {\n        module_lookup_tag(self.clone(), tag)\n    }\n\n    pub fn from_expr<E>(expr: E) -> Result<IRModule>\n    where\n        E: IsObjectRef,\n        E::Object: AsRef<<relay::Expr as IsObjectRef>::Object>,\n    {\n        Self::from_expr_with_items(expr, HashMap::new(), HashMap::new())\n    }\n\n    pub fn from_expr_with_items<'a, E, F, T>(expr: E, funcs: F, types: T) -> Result<IRModule>\n    where\n        F: IntoIterator<Item = (&'a GlobalVar, &'a BaseFunc)>,\n        T: IntoIterator<Item = (&'a GlobalTypeVar, &'a TypeData)>,\n        E: IsObjectRef,\n        E::Object: AsRef<<relay::Expr as IsObjectRef>::Object>,\n    {\n        module_from_expr(expr.upcast(), Map::from_iter(funcs), Map::from_iter(types))\n    }\n\n    pub fn import<S: Into<TVMString>>(&mut self, path: S) -> Result<()> {\n        module_import(self.clone(), path.into())\n    }\n\n    pub fn import_from_std<S: Into<TVMString>>(&mut self, path: S) -> Result<()> {\n        module_import_from_std(self.clone(), path.into())\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::relay::*;\n    use super::*;\n    use crate::ir::span::Span;\n    use crate::ir::ty::{GlobalTypeVar, TypeData, TypeKind};\n    use tvm_rt::IsObjectRef;\n\n    fn add_dummy_functions(names: Vec<&str>) -> Result<IRModule> {\n        let mut module = IRModule::empty()?;\n        let x = Var::static_tensor(\"x\".into(), vec![1, 1], DataType::float32());\n        let params = vec![x.clone()];\n        let func = relay::Function::simple(params, x);\n\n        for name in names {\n            let gv = GlobalVar::new(name.into(), Span::null());\n            module = module.add(gv, func.clone())?;\n        }\n\n        Ok(module)\n    }\n\n    fn add_dummy_types(names: Vec<&str>) -> Result<IRModule> {\n        let mut module = IRModule::empty()?;\n\n        for name in names {\n            let name: String = name.into();\n            let name = GlobalTypeVar::new(name, TypeKind::Type, Span::null());\n            let type_data = TypeData::new(name.clone(), vec![], vec![], Span::null());\n            module.add_def(name, type_data, true)?;\n        }\n\n        Ok(module)\n    }\n\n    #[test]\n    fn test_module_add() -> anyhow::Result<()> {\n        let mut module = IRModule::empty()?;\n        let x = Var::static_tensor(\"x\".into(), vec![1, 1], DataType::float32());\n        let params = vec![x.clone()];\n        let func = relay::Function::simple(params, x);\n        let module = module.add(GlobalVar::new(\"foo\".into(), Span::null()), func)?;\n        let lfunc = module.lookup_str(\"foo\")?;\n        let lfunc = lfunc.downcast::<relay::Function>()?;\n        assert_eq!(lfunc.params.len(), 1);\n        Ok(())\n    }\n\n    #[test]\n    fn test_module_add_def() -> Result<()> {\n        let mut module = IRModule::empty()?;\n        let name = GlobalTypeVar::new(\"my_type\", TypeKind::Type, Span::null());\n        let type_data = TypeData::new(name.clone(), vec![], vec![], Span::null());\n        module.add_def(name.clone(), type_data, true)?;\n        let _by_gtv = module.lookup_def(name)?;\n        let _by_gv = module.lookup_def_str(\"my_type\")?;\n        Ok(())\n    }\n\n    #[test]\n    fn test_get_global_var() -> Result<()> {\n        let mut module = IRModule::empty()?;\n        let x = Var::static_tensor(\"x\".into(), vec![1, 1], DataType::float32());\n        let params = vec![x.clone()];\n        let func = relay::Function::simple(params, x);\n        let gv_foo = GlobalVar::new(\"foo\".into(), Span::null());\n        let module = module.add(gv_foo.clone(), func)?;\n        let gv = module.get_global_var(\"foo\")?;\n        assert_eq!(gv_foo, gv);\n        Ok(())\n    }\n\n    #[test]\n    fn test_get_global_vars() -> Result<()> {\n        let names = vec![\"foo\", \"bar\", \"baz\"];\n        let module = add_dummy_functions(names.clone())?;\n        let gvars: Vec<String> = module\n            .get_global_vars()?\n            .into_iter()\n            .map(|gv| gv.name_hint.as_str().unwrap().to_string())\n            .collect();\n\n        for name in names {\n            assert!(gvars.contains(&name.to_string()));\n        }\n\n        Ok(())\n    }\n\n    #[test]\n    fn test_get_global_type_vars() -> Result<()> {\n        let names = vec![\"foo\", \"bar\", \"baz\"];\n        let module = add_dummy_types(names.clone())?;\n        let gvars: Vec<String> = module\n            .get_global_type_vars()?\n            .into_iter()\n            .map(|gv| gv.name_hint.as_str().unwrap().to_string())\n            .collect();\n\n        for name in names {\n            assert!(gvars.contains(&name.to_string()));\n        }\n\n        Ok(())\n    }\n\n    #[test]\n    fn test_contains_global_var() -> Result<()> {\n        let module = add_dummy_functions(vec![\"foo\"])?;\n        assert!(module.contains_global_var(\"foo\")?);\n        Ok(())\n    }\n\n    #[test]\n    fn test_contains_global_type_var() -> Result<()> {\n        let module = add_dummy_types(vec![\"foo\"])?;\n        assert!(module.contains_global_type_var(\"foo\")?);\n        Ok(())\n    }\n\n    // TODO(@jroesch): not really sure about this API at all.\n    // pub fn lookup_tag(&self, tag: i32) -> Result<relay::Constructor> {\n    //     module_lookup_tag(self.clone(), tag)\n    // }\n\n    #[test]\n    fn test_from_expr() -> Result<()> {\n        let x = Var::static_tensor(\"x\".into(), vec![1, 1], DataType::float32());\n        let params = vec![x.clone()];\n        let func = relay::Function::simple(params, x);\n        let module = IRModule::from_expr(func.clone())?;\n        let main_fn = module.lookup_str(\"main\")?;\n        let main_fn = main_fn.downcast::<relay::Function>()?;\n        assert_eq!(main_fn, func);\n        Ok(())\n    }\n\n    #[test]\n    fn test_import() -> Result<()> {\n        let mut std_path: String = env!(\"CARGO_MANIFEST_DIR\").into();\n        std_path += \"/../../python/tvm/relay/std/prelude.rly\";\n\n        let mut mod1 = IRModule::empty()?;\n        mod1.import(std_path.clone())?;\n        mod1.lookup_str(\"map\")?;\n\n        // TODO(@jroesch): this requires another patch of mine to enable.\n\n        // if cfg!(feature = \"python\") {\n        //     crate::python::load().unwrap();\n        //     let mut mod2 = IRModule::empty()?;\n        //     mod2.import_from_std(\"prelude.rly\")?;\n        //     mod2.lookup_str(\"map\")?;\n        // }\n\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/op.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::ir::relay::ExprNode;\nuse crate::runtime::array::Array;\nuse crate::runtime::ObjectRef;\nuse crate::runtime::String as TString;\nuse tvm_macros::Object;\n\ntype FuncType = ObjectRef;\ntype AttrFieldInfo = ObjectRef;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Op\"]\n#[type_key = \"Op\"]\npub struct OpNode {\n    pub base: ExprNode,\n    pub name: TString,\n    pub op_type: FuncType,\n    pub description: TString,\n    pub arguments: Array<AttrFieldInfo>,\n    pub attrs_type_key: TString,\n    pub attrs_type_index: u32,\n    pub num_inputs: i32,\n    pub support_level: i32,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/relay/attrs/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npub mod nn;\npub mod reduce;\npub mod transform;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/relay/attrs/nn.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::ir::attrs::BaseAttrsNode;\nuse crate::ir::PrimExpr;\nuse crate::runtime::array::Array;\nuse crate::runtime::DataType;\nuse crate::runtime::String as TString;\nuse tvm_macros::Object;\n\ntype IndexExpr = PrimExpr;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PadAttrs\"]\n#[type_key = \"relay.attrs.PadAttrs\"]\npub struct PadAttrsNode {\n    pub base: BaseAttrsNode,\n    pub pad_width: Array<Array<IndexExpr>>,\n    pub pad_mode: TString,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Conv1DAttrs\"]\n#[type_key = \"relay.attrs.Conv1DAttrs\"]\npub struct Conv1DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    // TODO(@gussmith23) groups is \"int\", what should it be here?\n    pub groups: i32,\n    pub channels: IndexExpr,\n    pub kernel_size: Array<IndexExpr>,\n    pub data_layout: TString,\n    pub kernel_layout: TString,\n    pub out_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Conv2DAttrs\"]\n#[type_key = \"relay.attrs.Conv2DAttrs\"]\npub struct Conv2DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    // TODO(@gussmith23) groups is \"int\", what should it be here?\n    pub groups: i32,\n    pub channels: IndexExpr,\n    pub kernel_size: Array<IndexExpr>,\n    pub data_layout: TString,\n    pub kernel_layout: TString,\n    pub out_layout: TString,\n    pub auto_scheduler_rewritten_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Conv3DAttrs\"]\n#[type_key = \"relay.attrs.Conv3DAttrs\"]\npub struct Conv3DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    pub groups: i32,\n    pub channels: IndexExpr,\n    pub kernel_size: Array<IndexExpr>,\n    pub data_layout: TString,\n    pub kernel_layout: TString,\n    pub out_layout: TString,\n    pub auto_scheduler_rewritten_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Conv3DTransposeAttrs\"]\n#[type_key = \"relay.attrs.Conv3DTransposeAttrs\"]\npub struct Conv3DTransposeAttrsNode {\n    pub base: BaseAttrsNode,\n    pub channels: IndexExpr,\n    pub kernel_size: Array<IndexExpr>,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub output_padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    pub groups: i32,\n    pub data_layout: TString,\n    pub kernel_layout: TString,\n    pub out_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BiasAddAttrs\"]\n#[type_key = \"relay.attrs.BiasAddAttrs\"]\npub struct BiasAddAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"MatmulAttrs\"]\n#[type_key = \"relay.attrs.MatmulAttrs\"]\npub struct MatmulAttrsNode {\n    pub base: BaseAttrsNode,\n    pub units: IndexExpr,\n    pub out_dtype: DataType,\n    pub transpose_a: bool,\n    pub transpose_b: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"DenseAttrs\"]\n#[type_key = \"relay.attrs.DenseAttrs\"]\npub struct DenseAttrsNode {\n    pub base: BaseAttrsNode,\n    pub units: IndexExpr,\n    pub auto_scheduler_rewritten_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"GlobalPool2DAttrs\"]\n#[type_key = \"relay.attrs.GlobalPool2DAttrs\"]\npub struct GlobalPool2DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub layout: TString,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"MaxPool2DAttrs\"]\n#[type_key = \"relay.attrs.MaxPool2DAttrs\"]\npub struct MaxPool2DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub pool_size: Array<IndexExpr>,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    pub layout: TString,\n    pub ceil_mode: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"SoftmaxAttrs\"]\n#[type_key = \"relay.attrs.SoftmaxAttrs\"]\npub struct SoftmaxAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BatchNormAttrs\"]\n#[type_key = \"relay.attrs.BatchNormAttrs\"]\npub struct BatchNormAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n    pub epsilon: f64,\n    pub center: bool,\n    pub scale: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"LeakyReluAttrs\"]\n#[type_key = \"relay.attrs.LeakyReluAttrs\"]\npub struct LeakyReluAttrsNode {\n    pub base: BaseAttrsNode,\n    pub alpha: f64,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"AvgPool2DAttrs\"]\n#[type_key = \"relay.attrs.AvgPool2DAttrs\"]\npub struct AvgPool2DAttrsNode {\n    pub base: BaseAttrsNode,\n    pub pool_size: Array<IndexExpr>,\n    pub strides: Array<IndexExpr>,\n    pub padding: Array<IndexExpr>,\n    pub dilation: Array<IndexExpr>,\n    pub layout: TString,\n    pub ceil_mode: bool,\n    pub count_include_pad: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"UpSamplingAttrs\"]\n#[type_key = \"relay.attrs.UpSamplingAttrs\"]\npub struct UpSamplingAttrsNode {\n    pub base: BaseAttrsNode,\n    pub scale_h: f64,\n    pub scale_w: f64,\n    pub layout: TString,\n    pub method: TString,\n    pub align_corners: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"DropoutAttrs\"]\n#[type_key = \"relay.attrs.DropoutAttrs\"]\npub struct DropoutAttrsNode {\n    pub base: BaseAttrsNode,\n    pub rate: f64,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BatchMatmulAttrs\"]\n#[type_key = \"relay.attrs.BatchMatmulAttrs\"]\npub struct BatchMatmulAttrsNode {\n    pub base: BaseAttrsNode,\n    pub auto_scheduler_rewritten_layout: TString,\n    pub out_dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"LayerNormAttrs\"]\n#[type_key = \"relay.attrs.LayerNormAttrs\"]\npub struct LayerNormAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n    pub epsilon: f64,\n    pub center: bool,\n    pub scale: bool,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/relay/attrs/reduce.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::ir::attrs::BaseAttrsNode;\nuse crate::ir::PrimExpr;\nuse crate::runtime::array::Array;\nuse tvm_macros::Object;\n\ntype IndexExpr = PrimExpr;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"ReduceAttrs\"]\n#[type_key = \"relay.attrs.ReduceAttrs\"]\npub struct ReduceAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: Array<IndexExpr>,\n    pub keepdims: bool,\n    pub exclude: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"VarianceAttrs\"]\n#[type_key = \"relay.attrs.ReduceAttrs\"]\npub struct VarianceAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: Array<IndexExpr>,\n    pub keepdims: bool,\n    pub exclude: bool,\n    pub unbiased: bool,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/relay/attrs/transform.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::ir::attrs::BaseAttrsNode;\nuse crate::ir::relay::TString;\nuse crate::ir::tir::IntImm;\nuse crate::ir::PrimExpr;\nuse crate::runtime::array::Array;\nuse crate::runtime::ObjectRef;\nuse tvm_macros::Object;\nuse tvm_rt::DataType;\n\ntype IndexExpr = PrimExpr;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"ClipAttrs\"]\n#[type_key = \"relay.attrs.ClipAttrs\"]\npub struct ClipAttrsNode {\n    pub base: BaseAttrsNode,\n    pub a_min: f64,\n    pub a_max: f64,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"CastAttrs\"]\n#[type_key = \"relay.attrs.CastAttrs\"]\npub struct CastAttrsNode {\n    pub base: BaseAttrsNode,\n    pub dtype: DataType,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"ExpandDimsAttrs\"]\n#[type_key = \"relay.attrs.ExpandDimsAttrs\"]\npub struct ExpandDimsAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n    pub num_newaxis: i32,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"ConcatenateAttrs\"]\n#[type_key = \"relay.attrs.ConcatenateAttrs\"]\npub struct ConcatenateAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: i32,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"ReshapeAttrs\"]\n#[type_key = \"relay.attrs.ReshapeAttrs\"]\npub struct ReshapeAttrsNode {\n    pub base: BaseAttrsNode,\n    pub newshape: Array<IndexExpr>,\n    pub reverse: bool,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"SplitAttrs\"]\n#[type_key = \"relay.attrs.SplitAttrs\"]\npub struct SplitAttrsNode {\n    pub base: BaseAttrsNode,\n    pub indices_or_sections: ObjectRef,\n    pub axis: i32,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TransposeAttrs\"]\n#[type_key = \"relay.attrs.TransposeAttrs\"]\npub struct TransposeAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axes: Array<IndexExpr>,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"SqueezeAttrs\"]\n#[type_key = \"relay.attrs.SqueezeAttrs\"]\npub struct SqueezeAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: Array<IntImm>,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TakeAttrs\"]\n#[type_key = \"relay.attrs.TakeAttrs\"]\npub struct TakeAttrsNode {\n    pub base: BaseAttrsNode,\n    pub batch_dims: IntImm,\n    pub axis: IntImm,\n    pub mode: TString,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"StackAttrs\"]\n#[type_key = \"relay.attrs.StackAttrs\"]\npub struct StackAttrsNode {\n    pub base: BaseAttrsNode,\n    pub axis: IntImm,\n}\n\n// TODO(@gussmith23) How to support Optional type? This \"just works\" when values\n// are provided for begin/end/strides, but I'm not sure what happens if None is\n// passed from the C++ side.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"StridedSliceAttrs\"]\n#[type_key = \"relay.attrs.StridedSliceAttrs\"]\npub struct StridedSliceAttrsNode {\n    pub base: BaseAttrsNode,\n    pub begin: Array<IntImm>,\n    pub end: Array<IntImm>,\n    pub strides: Array<IntImm>,\n    pub slice_mode: TString,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/relay/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\nuse crate::runtime::array::Array;\nuse crate::runtime::{self, object::*, IsObjectRef, String as TString};\n\nuse super::attrs::Attrs;\nuse super::expr::BaseExprNode;\nuse super::function::BaseFuncNode;\nuse super::span::Span;\nuse super::ty::Type;\n\nuse tvm_macros::Object;\nuse tvm_rt::NDArray;\n\npub use super::expr::{GlobalVar, GlobalVarNode};\npub use crate::runtime::DataType;\n\npub mod attrs;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Expr\"]\n#[type_key = \"RelayExpr\"]\npub struct ExprNode {\n    pub base: BaseExprNode,\n    pub checked_type: Type,\n    pub virtual_device: ObjectRef,\n}\n\nimpl ExprNode {\n    pub fn base<T: IsObject>(span: Span) -> ExprNode {\n        ExprNode {\n            base: BaseExprNode::base::<T>(span.clone()),\n            checked_type: Type::null(),\n            virtual_device: ObjectRef::null(),\n        }\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Id\"]\n#[type_key = \"relay.Id\"]\npub struct IdNode {\n    pub base: Object,\n    pub name_hint: TString,\n}\n\nimpl Id {\n    fn new(name_hint: TString) -> Id {\n        let node = IdNode {\n            base: Object::base::<IdNode>(),\n            name_hint: name_hint,\n        };\n        Id(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Constant\"]\n#[type_key = \"relay.Constant\"]\npub struct ConstantNode {\n    pub base: ExprNode,\n    pub data: NDArray,\n}\n\nimpl Constant {\n    pub fn new(data: NDArray, span: Span) -> Constant {\n        let node = ConstantNode {\n            base: ExprNode::base::<ConstantNode>(span),\n            data: data,\n        };\n        Constant(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Tuple\"]\n#[type_key = \"relay.Tuple\"]\npub struct TupleNode {\n    pub base: ExprNode,\n    pub fields: Array<Expr>,\n}\n\nimpl Tuple {\n    pub fn new(fields: Array<Expr>, span: Span) -> Tuple {\n        let node = TupleNode {\n            base: ExprNode::base::<TupleNode>(span),\n            fields,\n        };\n        Tuple(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Var\"]\n#[type_key = \"relay.Var\"]\npub struct VarNode {\n    pub base: ExprNode,\n    pub vid: Id,\n    pub type_annotation: Type,\n}\n\nimpl Var {\n    pub fn new(name_hint: String, type_annotation: Type, span: Span) -> Var {\n        let node = VarNode {\n            base: ExprNode::base::<VarNode>(span),\n            vid: Id::new(name_hint.into()),\n            type_annotation: type_annotation,\n        };\n        Var(Some(ObjectPtr::new(node)))\n    }\n\n    pub fn name_hint(&self) -> &TString {\n        &self.vid.0.as_ref().unwrap().name_hint\n    }\n\n    pub fn static_tensor(name_hint: String, sh: Vec<i32>, dtype: DataType) -> Var {\n        let sh = Array::from_vec(sh.into_iter().map(Into::into).collect()).unwrap();\n        Self::new(\n            name_hint,\n            super::ty::TensorType::new(sh, dtype, Span::null()).upcast(),\n            Span::null(),\n        )\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Call\"]\n#[type_key = \"relay.Call\"]\npub struct CallNode {\n    pub base: ExprNode,\n    deleter: ObjectRef,\n    pub op: Expr,\n    pub args: Array<Expr>,\n    pub attrs: Attrs,\n    pub type_args: Array<Type>,\n}\n\nimpl Call {\n    pub fn new(\n        op: Expr,\n        args: Array<Expr>,\n        attrs: Attrs,\n        type_args: Array<Type>,\n        span: Span,\n    ) -> Call {\n        let node = CallNode {\n            base: ExprNode::base::<CallNode>(span),\n            deleter: todo!(\"Don't know how to construct this\"),\n            op: op,\n            args: args,\n            attrs: attrs,\n            type_args: type_args,\n        };\n        Call(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Let\"]\n#[type_key = \"relay.Let\"]\npub struct LetNode {\n    pub base: ExprNode,\n    pub var: Var,\n    pub value: Expr,\n    pub body: Expr,\n}\n\nimpl Let {\n    pub fn new(var: Var, value: Expr, body: Expr, span: Span) -> Let {\n        let node = LetNode {\n            base: ExprNode::base::<LetNode>(span),\n            var,\n            value,\n            body,\n        };\n        Let(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"If\"]\n#[type_key = \"relay.If\"]\npub struct IfNode {\n    pub base: ExprNode,\n    pub cond: Expr,\n    pub true_branch: Expr,\n    pub false_branch: Expr,\n}\n\nimpl If {\n    pub fn new(cond: Expr, true_branch: Expr, false_branch: Expr, span: Span) -> If {\n        let node = IfNode {\n            base: ExprNode::base::<IfNode>(span),\n            cond,\n            true_branch,\n            false_branch,\n        };\n        If(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TupleGetItem\"]\n#[type_key = \"relay.TupleGetItem\"]\npub struct TupleGetItemNode {\n    pub base: ExprNode,\n    pub tuple: Expr,\n    pub index: i32,\n}\n\nimpl TupleGetItem {\n    pub fn new(tuple: Expr, index: i32, span: Span) -> TupleGetItem {\n        let node = TupleGetItemNode {\n            base: ExprNode::base::<TupleGetItemNode>(span),\n            tuple,\n            index,\n        };\n        TupleGetItem(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"RefCreate\"]\n#[type_key = \"relay.RefCreate\"]\npub struct RefCreateNode {\n    pub base: ExprNode,\n    pub value: Expr,\n}\n\nimpl RefCreate {\n    pub fn new(value: Expr, span: Span) -> RefCreate {\n        let node = RefCreateNode {\n            base: ExprNode::base::<RefCreateNode>(span),\n            value,\n        };\n        RefCreate(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"RefRead\"]\n#[type_key = \"relay.RefRead\"]\npub struct RefReadNode {\n    pub base: ExprNode,\n    pub ref_value: Expr,\n}\n\nimpl RefRead {\n    pub fn new(ref_value: Expr, span: Span) -> RefRead {\n        let node = RefReadNode {\n            base: ExprNode::base::<RefReadNode>(span),\n            ref_value,\n        };\n        RefRead(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"RefWrite\"]\n#[type_key = \"relay.RefWrite\"]\npub struct RefWriteNode {\n    pub base: ExprNode,\n    pub ref_value: Expr,\n    pub value: Expr,\n}\n\nimpl RefWrite {\n    pub fn new(ref_value: Expr, value: Expr, span: Span) -> RefWrite {\n        let node = RefWriteNode {\n            base: ExprNode::base::<RefWriteNode>(span),\n            ref_value,\n            value,\n        };\n        RefWrite(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Constructor\"]\n#[type_key = \"relay.Constructor\"]\npub struct ConstructorNode {\n    pub base: ExprNode,\n    pub name_hint: String,\n    pub inputs: Array<Type>,\n    pub tag: i32,\n}\n\nimpl Constructor {\n    pub fn new(name_hint: String, inputs: Array<Type>, tag: i32, span: Span) -> Constructor {\n        let node = ConstructorNode {\n            base: ExprNode::base::<ConstructorNode>(span),\n            name_hint,\n            inputs,\n            tag,\n        };\n        Constructor(Some(ObjectPtr::new(node)))\n    }\n}\n\n// TODO(@jroesch): define the type data\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Pattern\"]\n#[type_key = \"relay.Pattern\"]\npub struct PatternNode {\n    pub base: Object,\n    pub span: Span,\n}\n\nimpl PatternNode {\n    pub fn base<T: IsObject>(span: Span) -> PatternNode {\n        PatternNode {\n            base: Object::base::<T>(),\n            span: span,\n        }\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PatternWildcard\"]\n#[type_key = \"relay.PatternWildcard\"]\npub struct PatternWildcardNode {\n    pub base: PatternNode,\n}\n\nimpl PatternWildcard {\n    pub fn new(span: Span) -> PatternWildcard {\n        let node = PatternWildcardNode {\n            base: PatternNode::base::<PatternWildcardNode>(span),\n        };\n        PatternWildcard(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PatternVar\"]\n#[type_key = \"relay.PatternVar\"]\npub struct PatternVarNode {\n    pub base: PatternNode,\n    pub var: Var,\n}\n\nimpl PatternVar {\n    pub fn new(var: Var, span: Span) -> PatternVar {\n        let node = PatternVarNode {\n            base: PatternNode::base::<PatternVarNode>(span),\n            var: var,\n        };\n        PatternVar(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PatternConstructor\"]\n#[type_key = \"relay.PatternConstructor\"]\npub struct PatternConstructorNode {\n    pub base: PatternNode,\n    pub constructor: Constructor,\n    pub patterns: Array<Pattern>,\n}\n\nimpl PatternConstructor {\n    pub fn new(\n        constructor: Constructor,\n        patterns: Array<Pattern>,\n        span: Span,\n    ) -> PatternConstructor {\n        let node = PatternConstructorNode {\n            base: PatternNode::base::<PatternConstructorNode>(span),\n            constructor,\n            patterns,\n        };\n        PatternConstructor(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PatternTuple\"]\n#[type_key = \"relay.PatternTuple\"]\npub struct PatternTupleNode {\n    pub base: PatternNode,\n    pub patterns: Array<Pattern>,\n}\n\nimpl PatternTuple {\n    pub fn new(patterns: Array<Pattern>, span: Span) -> PatternTuple {\n        let node = PatternTupleNode {\n            base: PatternNode::base::<PatternTupleNode>(span),\n            patterns,\n        };\n        PatternTuple(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Clause\"]\n#[type_key = \"relay.Clause\"]\npub struct ClauseNode {\n    pub base: Object,\n    pub lhs: Pattern,\n    pub rhs: Expr,\n}\n\nimpl Clause {\n    pub fn new(lhs: Pattern, rhs: Expr, _span: Span) -> Clause {\n        let node = ClauseNode {\n            base: Object::base::<ClauseNode>(),\n            lhs,\n            rhs,\n        };\n        Clause(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Match\"]\n#[type_key = \"relay.Match\"]\npub struct MatchNode {\n    pub base: ExprNode,\n    pub data: Expr,\n    pub clauses: Array<Clause>,\n    pub complete: bool,\n}\n\nimpl Match {\n    pub fn new(data: Expr, clauses: Array<Clause>, complete: bool, span: Span) -> Match {\n        let node = MatchNode {\n            base: ExprNode::base::<MatchNode>(span),\n            data,\n            clauses,\n            complete,\n        };\n        Match(Some(ObjectPtr::new(node)))\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Function\"]\n#[type_key = \"relay.Function\"]\npub struct FunctionNode {\n    pub base: BaseFuncNode,\n    pub params: Array<Var>,\n    pub body: Expr,\n    pub ret_type: Type,\n    pub type_params: Array<Type>,\n}\n\nimpl Function {\n    pub fn new(\n        params: Array<Var>,\n        body: Expr,\n        ret_type: Type,\n        type_params: Array<Type>,\n    ) -> Function {\n        let node = FunctionNode {\n            base: BaseFuncNode::base::<FunctionNode>(),\n            params: params,\n            body: body,\n            ret_type: ret_type,\n            type_params: type_params,\n        };\n        Function(Some(ObjectPtr::new(node)))\n    }\n\n    pub fn simple<E>(params: Vec<Var>, body: E) -> Function\n    where\n        E: IsObjectRef,\n        E::Object: AsRef<<Expr as IsObjectRef>::Object>,\n    {\n        let params = Array::from_vec(params).unwrap();\n        Self::new(\n            params,\n            body.upcast(),\n            Type::null(),\n            Array::from_vec(vec![]).unwrap(),\n        )\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use crate::ir::as_text;\n    use crate::runtime::String as TString;\n    use anyhow::Result;\n\n    #[test]\n    fn test_id() -> Result<()> {\n        let string = TString::from(\"foo\");\n        let id = Id::new(string);\n        let text = as_text(id.clone());\n        assert!(text.contains(\"relay.Id\"));\n        Ok(())\n    }\n\n    #[test]\n    fn test_global() -> Result<()> {\n        let gv = GlobalVar::new(\"main\".to_string(), Span::null());\n        let text = as_text(gv.clone());\n        assert!(text.contains(\"@main\"));\n        Ok(())\n    }\n\n    #[test]\n    fn test_var() -> Result<()> {\n        let var = Var::new(\"local\".to_string(), Type::null(), Span::null());\n        let text = as_text(var.clone());\n        assert!(text.contains(\"%local\"));\n        Ok(())\n    }\n\n    #[test]\n    fn test_parse_constant() -> Result<()> {\n        let module = crate::ir::module::IRModule::parse(\n            \"\",\n            r#\"\n#[version = \"0.0.5\"]\ndef @main() -> float32 {\n  0.01639530062675476f\n}\n\"#,\n        )\n        .unwrap();\n        let main = module\n            .lookup(module.get_global_var(\"main\").unwrap())\n            .unwrap();\n        let func = main.downcast::<crate::ir::relay::Function>().unwrap();\n        let constant = func\n            .body\n            .clone()\n            .downcast::<crate::ir::relay::Constant>()\n            .unwrap();\n        let tuple_type = constant\n            .clone()\n            .upcast::<Expr>()\n            .checked_type\n            .clone()\n            .downcast::<crate::ir::ty::TensorType>()\n            .unwrap();\n        // Test type\n        assert_eq!(tuple_type.shape.len(), 0,);\n        assert_eq!(tuple_type.dtype, \"float32\".parse().unwrap(),);\n        // Check that actual data matches up with type\n        assert_eq!(constant.data.dtype(), \"float32\".parse().unwrap(),);\n        assert_eq!(constant.data.len(), 1);\n        assert_eq!(constant.data.size(), 4);\n        assert_eq!(constant.data.shape(), &[]);\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/source_map.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either exprss or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::runtime::map::Map;\nuse crate::runtime::object::Object;\nuse crate::runtime::string::String as TString;\n\nuse super::span::SourceName;\n\nuse tvm_macros::Object;\n\n/// A program source in any language.\n///\n/// Could represent the source from an ML framework or a source of an IRModule.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[type_key = \"Source\"]\n#[ref_name = \"Source\"]\npub struct SourceNode {\n    pub base: Object,\n    /// The source name.\n    pub source_name: SourceName,\n\n    /// The raw source.\n    pub source: TString,\n    // TODO(@jroesch): Non-ABI compat field\n    // A mapping of line breaks into the raw source.\n    // std::vector<std::pair<int, int>> line_map;\n}\n\n/// A mapping from a unique source name to source fragments.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[type_key = \"SourceMap\"]\n#[ref_name = \"SourceMap\"]\npub struct SourceMapNode {\n    /// The base object.\n    pub base: Object,\n    /// The source mapping.\n    pub source_map: Map<SourceName, Source>,\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/span.rs",
        "content": "/*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements.  See the NOTICE file\n* distributed with this work for additional information\n* regarding copyright ownership.  The ASF licenses this file\n* to you under the Apache License, Version 2.0 (the\n* \"License\"); you may not use this file except in compliance\n* with the License.  You may obtain a copy of the License at\n*\n*   http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing,\n* software distributed under the License is distributed on an\n* \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n* KIND, either express or implied.  See the License for the\n\n* specific language governing permissions and limitations\n* under the License.\n*/\n\nuse crate::runtime::{Object, ObjectPtr, String as TString};\nuse tvm_macros::Object;\n\n/// A source file name, contained in a Span.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[type_key = \"SourceName\"]\n#[ref_name = \"SourceName\"]\npub struct SourceNameNode {\n    pub base: Object,\n    pub name: TString,\n}\n\n/// Span information for diagnostic purposes.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[type_key = \"Span\"]\n#[ref_name = \"Span\"]\npub struct SpanNode {\n    pub base: Object,\n    /// The source name.\n    pub source_name: SourceName,\n    /// The line number.\n    pub line: i32,\n    /// The column offset.\n    pub column: i32,\n    /// The end line number.\n    pub end_line: i32,\n    /// The end column number.\n    pub end_column: i32,\n}\n\nimpl Span {\n    pub fn new(\n        source_name: SourceName,\n        line: i32,\n        end_line: i32,\n        column: i32,\n        end_column: i32,\n    ) -> Span {\n        let span_node = SpanNode {\n            base: Object::base::<SpanNode>(),\n            source_name,\n            line,\n            end_line,\n            column,\n            end_column,\n        };\n        Span(Some(ObjectPtr::new(span_node)))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/tir.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse super::{PrimExpr, PrimExprNode};\n\nuse crate::ir::span::Span;\nuse crate::runtime::{IsObjectRef, String as TVMString};\nuse crate::DataType;\n\nuse tvm_macros::Object;\n\nmacro_rules! define_node {\n    ($name:ident, $ref:expr, $typekey:expr; $node:ident { $($id:ident : $t:ty),*}) => {\n        #[repr(C)]\n        #[derive(Object, Debug)]\n        #[ref_name = $ref]\n        #[type_key = $typekey]\n        pub struct $node {\n            base: PrimExprNode,\n            $(pub $id : $t),*\n        }\n\n        impl $name {\n            pub fn new(datatype: DataType, $($id : $t,)*) -> $name {\n                let base = PrimExprNode::base::<$node>(datatype, Span::null());\n                let node = $node { base, $($id),* };\n                node.into()\n            }\n        }\n    }\n}\n\n// TODO(@jroesch): should move up to expr.rs to mirror TVM.\ndefine_node!(IntImm, \"IntImm\", \"IntImm\";\n             IntImmNode { value: i64 });\n\nimpl From<i32> for IntImm {\n    fn from(i: i32) -> IntImm {\n        IntImm::new(DataType::int(32, 1), i as i64)\n    }\n}\n\nimpl From<i32> for PrimExpr {\n    fn from(i: i32) -> PrimExpr {\n        IntImm::from(i).upcast()\n    }\n}\n\ndefine_node!(Var, \"Var\", \"tir.Var\";\n             VarNode { name_hint: TVMString });\n\ndefine_node!(Add, \"Add\", \"tir.Add\"; AddNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Sub, \"Sub\", \"tir.Sub\"; SubNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Mul, \"Mul\", \"tir.Mul\"; MulNode { a: PrimExpr, b: PrimExpr });\n\ndefine_node!(Div, \"Div\", \"tir.Div\"; DivNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Mod, \"Mod\", \"tir.Mod\"; ModNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(FloorDiv, \"FloorDiv\", \"tir.FloorDiv\"; FloorDivNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(FloorMod, \"FloorMod\", \"tir.FloorMod\"; FloorModNode { a: PrimExpr, b: PrimExpr });\n\ndefine_node!(Min, \"Min\", \"tir.Min\"; MinNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Max, \"Max\", \"tir.Max\"; MaxNode { a: PrimExpr, b: PrimExpr });\n\n// the new datatype is in the base expr\ndefine_node!(Cast, \"Cast\", \"tir.Cast\"; CastNode { value: PrimExpr });\n\n// renamed base to start to avoid name clash\ndefine_node!(Ramp, \"Ramp\", \"tir.Ramp\"; RampNode { start: PrimExpr, stride: PrimExpr, lanes: i32 });\n\ndefine_node!(Select, \"Select\", \"tir.Select\";\n             SelectNode { condition: PrimExpr, true_value: PrimExpr, false_value: PrimExpr });\n\ndefine_node!(Eq, \"Eq\", \"tir.EQ\"; EqNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Ne, \"Ne\", \"tir.NE\"; NeNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Lt, \"Lt\", \"tir.LT\"; LtNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Le, \"Le\", \"tir.LE\"; LeNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Gt, \"Gt\", \"tir.GT\"; GtNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Ge, \"Ge\", \"tir.GE\"; GeNode { a: PrimExpr, b: PrimExpr });\n\ndefine_node!(And, \"And\", \"tir.And\"; AndNode { a: PrimExpr, b: PrimExpr });\ndefine_node!(Or,  \"Or\",  \"tir.Or\";  OrNode  { a: PrimExpr, b: PrimExpr });\ndefine_node!(Not, \"Not\", \"tir.Not\"; NotNode { value: PrimExpr });\n\ndefine_node!(Let, \"Let\", \"tir.Let\"; LetNode { var: Var, value: PrimExpr, body: PrimExpr });\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/ir/ty.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse tvm_macros::Object;\nuse tvm_rt::{array::Array, DataType};\n\nuse crate::ir::relay::Constructor;\nuse crate::ir::span::Span;\nuse crate::ir::PrimExpr;\nuse crate::runtime::{string::String as TString, IsObject, IsObjectRef, Object, ObjectPtr};\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"Type\"]\n#[type_key = \"Type\"]\npub struct TypeNode {\n    pub base: Object,\n    pub span: Span,\n}\n\nimpl TypeNode {\n    fn base<T: IsObject>(span: Span) -> Self {\n        TypeNode {\n            base: Object::base::<T>(),\n            span,\n        }\n    }\n}\n\n/*\n * \\brief Primitive data types used in the low-level IR.\n *\n * PrimType represents POD-values and handles that are\n * not automatically managed by the runtime.\n *\n * \\sa PrimType\n */\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PrimType\"]\n#[type_key = \"PrimType\"]\npub struct PrimTypeNode {\n    pub base: TypeNode,\n    /// The corresponding dtype field.\n    pub dtype: DataType,\n}\n\n/*\n *!\n * \\brief Low-level raw pointer type.\n *\n *  PointerType represents type hints in the TIR to be\n *  passed to the final code generator.\n *\n *  PointerType should not occur in the high-level analysis.\n *\n * \\sa PointerType\n */\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PointerType\"]\n#[type_key = \"PointerType\"]\npub struct PointerTypeNode {\n    pub base: TypeNode,\n    /// The type of the element which the pointer points to.\n    pub element_type: Type,\n}\n\n/// Possible kinds of type variables.\n#[derive(PartialEq, Eq, Debug)]\npub enum TypeKind {\n    Type = 0,\n    /// Template variable in shape expression.\n    ShapeVar = 1,\n    Constraint = 4,\n    AdtHandle = 5,\n    TypeData = 6,\n}\n\n/// Type parameter in functions.\n///\n/// A type variable can be viewed as template parameter in c++ template function.\n///\n/// For example, in the following pesudo code,\n/// the TypeVar of f is TypeVar(\"n\", kind=kShapeVar).\n/// This function can take in a Tensor with shape=(3, 3) and\n/// returns a Tensor with shape=(9,)\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TypeVar\"]\n#[type_key = \"TypeVar\"]\npub struct TypeVarNode {\n    pub base: TypeNode,\n    pub name_hint: TString,\n    pub kind: TypeKind,\n}\n\n/// A global type variable that is used for defining new types or type aliases.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"GlobalTypeVar\"]\n#[type_key = \"GlobalTypeVar\"]\npub struct GlobalTypeVarNode {\n    pub base: TypeNode,\n    pub name_hint: TString,\n    pub kind: TypeKind,\n}\n\nimpl GlobalTypeVar {\n    pub fn new<S>(name_hint: S, kind: TypeKind, span: Span) -> GlobalTypeVar\n    where\n        S: Into<TString>,\n    {\n        let node = GlobalTypeVarNode {\n            base: TypeNode::base::<GlobalTypeVarNode>(span),\n            name_hint: name_hint.into(),\n            kind: kind,\n        };\n        ObjectPtr::new(node).into()\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TupleType\"]\n#[type_key = \"TupleType\"]\npub struct TupleTypeNode {\n    pub base: TypeNode,\n    pub fields: Array<Type>,\n}\n\nimpl TupleType {\n    // todo add coercion\n    pub fn new(fields: Vec<Type>, span: Span) -> Self {\n        let node = TupleTypeNode {\n            base: TypeNode::base::<TupleTypeNode>(span),\n            fields: Array::from_vec(fields).unwrap(),\n        };\n        ObjectPtr::new(node).into()\n    }\n\n    pub fn empty() -> TupleType {\n        TupleType::new(vec![], Span::null())\n    }\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TypeConstraint\"]\n#[type_key = \"TypeConstraint\"]\npub struct TypeConstraintNode {\n    pub base: TypeNode,\n}\n\n/// The representation of a polymorphic function type.\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"FuncType\"]\n#[type_key = \"FuncType\"]\npub struct FuncTypeNode {\n    pub base: TypeNode,\n    /// The type of arguments.\n    pub arg_types: Array<Type>,\n    /// The return type of the function.\n    pub ret_type: Type,\n    /// ...\n    pub type_params: Array<TypeVar>,\n    /// Type constraints that must hold when\n    /// calling this function.\n    pub type_constraints: Array<TypeConstraint>,\n}\n\n/*\n * \\brief Intermediate values that is used to indicate incomplete type\n *         during type inference.\n *\n * If we view the type relations as \"computational graph of types\",\n * then IncompleteType represents intermediate values of the graph,\n * TypeVar represents the input to the graph.\n */\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"IncompleteType\"]\n#[type_key = \"IncompleteType\"]\npub struct IncompleteTypeNode {\n    pub base: TypeNode,\n    pub kind: TypeKind,\n}\n\n/*\n * \\brief Reference Type High-level Relay IR.\n *\n * \\sa RelayRefType.\n */\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"RefType\"]\n#[type_key = \"relay.RefType\"]\npub struct RelayRefTypeNode {\n    pub base: TypeNode,\n    pub value: Type,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"BaseTensorType\"]\n#[type_key = \"relay.BaseTensorType\"]\npub struct BaseTensorTypeNode {\n    pub base: TypeNode,\n}\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TensorType\"]\n#[type_key = \"relay.TensorType\"]\npub struct TensorTypeNode {\n    pub base: TypeNode,\n    pub shape: Array<PrimExpr>,\n    pub dtype: DataType,\n}\n\nimpl TensorType {\n    pub fn new(shape: Array<PrimExpr>, dtype: DataType, span: Span) -> TensorType {\n        let node = TensorTypeNode {\n            base: TypeNode::base::<TensorTypeNode>(span),\n            shape,\n            dtype,\n        };\n        ObjectPtr::new(node).into()\n    }\n\n    pub fn static_sh(shape: Vec<i32>, dtype: DataType, span: Span) -> TensorType {\n        let sh = Array::from_vec(shape.into_iter().map(Into::into).collect()).unwrap();\n        Self::new(sh, dtype, span)\n    }\n}\n\n// TODO(@jroesch): implement these in future.\n//\n// using TypeCall = tvm::TypeCall;\n// using TypeCallNode = tvm::TypeCallNode;\n// using TypeRelation = tvm::TypeRelation;\n// using TypeRelationNode = tvm::TypeRelationNode;\n// using TypeRelationFn = tvm::TypeRelationFn;\n// using TypeReporter = tvm::TypeReporter;\n// using TypeReporterNode = tvm::TypeReporterNode;\n\n/* TypeData container node.\n\\brief Stores all data for an Algebraic Data Type (ADT).\n\nIn particular, it stores the handle (global type var) for an ADT\nand the constructors used to build it and is kept in the module. Note\nthat type parameters are also indicated in the type data: this means that\nfor any instance of an ADT, the type parameters must be indicated. That is,\nan ADT definition is treated as a type-level function, so an ADT handle\nmust be wrapped in a TypeCall node that instantiates the type-level arguments.\nThe kind checker enforces this. */\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"TypeData\"]\n#[type_key = \"relay.TypeData\"]\npub struct TypeDataNode {\n    /// The header is simply the name of the ADT.\n    /// We adopt nominal typing for ADT definitions;\n    /// that is, differently-named ADT definitions with same constructors\n    /// have different types.\n    pub base: TypeNode,\n    pub type_name: GlobalTypeVar,\n    /// The type variables (to allow for polymorphism).\n    pub type_vars: Array<TypeVar>,\n    /// The constructors.\n    pub constructors: Array<Constructor>,\n}\n\nimpl TypeData {\n    pub fn new<TypeVars, Ctors>(\n        type_name: GlobalTypeVar,\n        type_vars: TypeVars,\n        constructors: Ctors,\n        span: Span,\n    ) -> TypeData\n    where\n        TypeVars: IntoIterator<Item = TypeVar>,\n        Ctors: IntoIterator<Item = Constructor>,\n    {\n        use std::iter::FromIterator;\n        let type_data = TypeDataNode {\n            base: TypeNode::base::<TypeDataNode>(span),\n            type_name,\n            type_vars: Array::from_iter(type_vars),\n            constructors: Array::from_iter(constructors),\n        };\n        TypeData(Some(ObjectPtr::new(type_data)))\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/lib.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n//! [TVM](https://github.com/apache/tvm) is a compiler stack for deep learning systems.\n//!\n//! This crate provides an idiomatic Rust API for TVM runtime frontend.\n//!\n//! One particular use case is that given optimized deep learning model artifacts,\n//! (compiled with TVM) which include a shared library\n//! `lib.so`, `graph.json` and a byte-array `param.params`, one can load them\n//! in Rust idiomatically to create a TVM Graph Executor and\n//! run the model for some inputs and get the\n//! desired predictions *all in Rust*.\n//!\n//! Checkout the `examples` repository for more details.\n\npub use crate::{errors::*, function::Function, module::Module, ndarray::NDArray};\n\npub use tvm_rt::{DataType, Device, DeviceType};\n\npub use tvm_rt::device;\npub use tvm_rt::errors;\npub use tvm_rt::function;\npub use tvm_rt::module;\npub use tvm_rt::ndarray;\n\n#[cfg(feature = \"python\")]\npub mod compiler;\npub mod ir;\n#[cfg(feature = \"python\")]\npub mod python;\npub mod runtime;\npub mod transform;\n\npub use runtime::version;\n\n#[macro_export]\nmacro_rules! export {\n    ($($fn_name:expr),*) => {\n        pub fn tvm_export(ns: &str) -> Result<(), tvm::Error> {\n            $(\n                let name = String::from(ns) + ::std::stringify!($fn_name);\n                tvm::runtime::function::register_override($fn_name, name, true)?;\n            )*\n            Ok(())\n        }\n    }\n}\n\n#[macro_export]\nmacro_rules! export_mod {\n    ($ns:expr, $($mod_name:expr),*) => {\n        pub fn tvm_mod_export() -> Result<(), tvm::Error> {\n            $(\n                $mod_name::tvm_export($ns)?;\n            )*\n            Ok(())\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/python.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse pyo3::prelude::*;\n\n/// Load the Python interpreter into the address space.\n///\n/// This enables the ability for Rust code to call TVM\n/// functionality defined in Python.\n///\n/// For example registered TVM functions can now be\n/// obtained via `Function::get`.\npub fn load() -> Result<String, ()> {\n    let gil = Python::acquire_gil();\n    let py = gil.python();\n    // let main_mod = initialize();\n    //let main_mod = main_mod.as_ref(py);\n    load_python_tvm_(py).map_err(|e| {\n        // We can't display Python exceptions via std::fmt::Display,\n        // so print the error here manually.\n        e.print_and_set_sys_last_vars(py);\n    })\n}\n\npub fn import(mod_to_import: &str) -> PyResult<()> {\n    let gil = Python::acquire_gil();\n    let py = gil.python();\n    import_python(py, mod_to_import)?;\n    Ok(())\n}\n\nfn import_python<'p, 'b: 'p>(py: Python<'p>, to_import: &'b str) -> PyResult<&'p PyModule> {\n    let imported_mod = py.import(to_import)?;\n    Ok(imported_mod)\n}\n\nfn load_python_tvm_(py: Python) -> PyResult<String> {\n    let imported_mod = import_python(py, \"tvm\")?;\n    let version: String = imported_mod.get(\"__version__\")?.extract()?;\n    Ok(version)\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use anyhow::Result;\n\n    #[ignore]\n    #[test]\n    fn test_run() -> Result<()> {\n        load().unwrap();\n        Ok(())\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/runtime/mod.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npub use tvm_rt::*;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/src/transform.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse crate::ir::relay::Function;\nuse crate::runtime::array::Array;\nuse crate::runtime::{\n    external,\n    function::{self, Result, ToFunction},\n    String as TString,\n};\nuse crate::runtime::{Object, ObjectPtr, ObjectRef};\n\nuse tvm_macros::Object;\n\npub type Pass = ObjectRef;\npub type IRModule = ObjectRef;\npub type PassContext = ObjectRef;\n\n#[repr(C)]\n#[derive(Object, Debug)]\n#[ref_name = \"PassInfo\"]\n#[type_key = \"transform.PassInfo\"]\npub struct PassInfoNode {\n    pub base: Object,\n    pub opt_level: i32,\n    pub name: TString,\n    pub required: Array<TString>,\n}\n\nimpl PassInfo {\n    pub fn new(opt_level: i32, name: String, required: Vec<String>) -> Result<PassInfo> {\n        let required = required.into_iter().map(|name| name.into()).collect();\n\n        let required = Array::from_vec(required)?;\n\n        let node = PassInfoNode {\n            base: Object::base::<PassInfoNode>(),\n            opt_level,\n            name: name.into(),\n            required,\n        };\n\n        Ok(PassInfo(Some(ObjectPtr::new(node))))\n    }\n}\n\nexternal! {\n    #[name(\"relay._transform.MakeFunctionPass\")]\n    fn create_func_pass(func: function::Function, pass_info: PassInfo) -> Pass;\n}\n\npub fn function_pass<F: Fn(Function, IRModule, PassContext) -> Function + 'static>(\n    pass_fn: F,\n    pass_info: PassInfo,\n) -> Result<Pass> {\n    let func = pass_fn.to_function();\n    create_func_pass(func, pass_info)\n}\n\n/// A macro for generating the correct TVM symbols for plugin loading.\n///\n/// The expression passed to the macro will be run when TVM loads the\n/// shared library.\n///\n/// This is useful for calling register to register packed functions\n/// to consume via TVM's packed function APIs.\n#[macro_export]\nmacro_rules! initialize {\n    ($body:expr) => {\n        #[no_mangle]\n        pub unsafe extern \"C\" fn initialize(\n            args: *mut tvm_sys::ffi::TVMValue,\n            type_codes: *mut c_int,\n            num_args: c_int,\n            ret: tvm_sys::ffi::TVMRetValueHandle,\n        ) -> c_int {\n            $body\n            return 0;\n        }\n    };\n}\n\n#[macro_export]\nmacro_rules! export_pass {\n    ($name:literal,$func:expr) => {\n        #[no_mangle]\n        pub unsafe extern \"C\" fn initialize(\n            args: *mut tvm_sys::ffi::TVMValue,\n            type_codes: *mut c_int,\n            num_args: c_int,\n            ret: tvm_sys::ffi::TVMRetValueHandle,\n        ) -> c_int {\n            register($func, $name).unwrap();\n            return 0;\n        }\n    };\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/basics/build.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse anyhow::{Context, Result};\n\nfn main() -> Result<()> {\n    let out_dir = std::env::var(\"OUT_DIR\").unwrap();\n    let tvm_mk_add = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/tvm_add.py\");\n\n    let output = std::process::Command::new(tvm_mk_add)\n        .args(&[\n            if cfg!(feature = \"cpu\") {\n                \"llvm\"\n            } else {\n                \"cuda\"\n            },\n            &std::env::var(\"OUT_DIR\").unwrap(),\n        ])\n        .output()\n        .with_context(|| anyhow::anyhow!(tvm_mk_add))?;\n\n    assert!(\n        std::path::Path::new(&format!(\"{}/test_add.so\", out_dir)).exists(),\n        \"Could not build tvm lib: {}\",\n        String::from_utf8(output.stderr)\n            .context(\"utf-8 conversion failed\")?\n            .trim()\n            .split(\"\\n\")\n            .last()\n            .unwrap_or(\"\")\n    );\n\n    println!(\"cargo:rustc-link-search=native={}\", out_dir);\n\n    Ok(())\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/basics/src/main.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::str::FromStr;\n\nuse tvm::*;\n\nfn main() {\n    let shape = &mut [2];\n    let mut data = vec![3f32, 4.0];\n\n    let (dev, dev_name) = if cfg!(feature = \"cpu\") {\n        (Device::cpu(0), \"cpu\")\n    } else {\n        (Device::cuda(0), \"cuda\")\n    };\n\n    let dtype = DataType::from_str(\"float32\").unwrap();\n    let mut arr = NDArray::empty(shape, dev, dtype);\n    arr.copy_from_buffer(data.as_mut_slice());\n    let ret = NDArray::empty(shape, dev, dtype);\n    let fadd = Module::load(&concat!(env!(\"OUT_DIR\"), \"/test_add.so\")).unwrap();\n    if !fadd.enabled(dev_name) {\n        return;\n    }\n\n    if cfg!(feature = \"cuda\") {\n        fadd.import_module(Module::load(&concat!(env!(\"OUT_DIR\"), \"/test_add.ptx\")).unwrap());\n    }\n\n    // todo(@jroesch): fix the entry_name\n    fadd.get_function(\"__tvm_main__\", false)\n        .expect(\"module must have entry point\")\n        .invoke(vec![(&arr).into(), (&arr).into(), (&ret).into()])\n        .unwrap();\n\n    assert_eq!(ret.to_vec::<f32>().unwrap(), vec![6f32, 8.0]);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/basics/src/tvm_add.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os.path as osp\nimport sys\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cc\n\n\ndef main(target, out_dir):\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n\n    if target == \"cuda\":\n        bx, tx = s[C].split(C.op.axis[0], factor=64)\n        s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    fadd = tvm.build(s, [A, B, C], tvm.target.Target(target, host=\"llvm\"), name=\"myadd\")\n    fadd.save(osp.join(out_dir, \"test_add.o\"))\n    if target == \"cuda\":\n        fadd.imported_modules[0].save(osp.join(out_dir, \"test_add.ptx\"))\n    cc.create_shared(osp.join(out_dir, \"test_add.so\"), [osp.join(out_dir, \"test_add.o\")])\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1], sys.argv[2])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/callback/src/bin/array.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#![allow(unused_imports)]\n\nextern crate ndarray as rust_ndarray;\n\nuse rust_ndarray::ArrayD;\nuse std::{\n    convert::{TryFrom, TryInto},\n    str::FromStr,\n};\n\nuse tvm::{\n    errors::Error,\n    function::register_untyped,\n    runtime::{ArgValue, RetValue},\n    *,\n};\n\nfn main() {\n    fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {\n        let mut ret = 0.0;\n        for arg in args {\n            let arg: NDArray = arg.try_into()?;\n            let rnd: ArrayD<f32> = ArrayD::try_from(&arg)?;\n            ret += rnd.scalar_sum();\n        }\n        Ok(RetValue::from(ret))\n    }\n\n    let shape = &[2];\n    let data = vec![3.0, 4.0];\n    let mut arr = NDArray::empty(shape, Device::cpu(0), DataType::float(32, 1));\n    arr.copy_from_buffer(data.as_slice());\n\n    register_untyped(sum, \"sum\", true).unwrap();\n    let func = Function::get(\"sum\").expect(\"function registered\");\n\n    let ret: f32 = func\n        .invoke(vec![(&arr).into()])\n        .unwrap()\n        .try_into()\n        .expect(\"call should succeed\");\n\n    assert_eq!(ret, 7.0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/callback/src/bin/error.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::panic;\n\nuse tvm::{\n    errors::Error,\n    runtime::{ArgValue, RetValue},\n    *,\n};\n\nfn main() {\n    fn error<'a>(_args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {\n        Err(errors::NDArrayError::DataTypeMismatch {\n            expected: DataType::int(64, 1),\n            actual: DataType::float(64, 1),\n        }\n        .into())\n    }\n\n    function::register_untyped(error, \"error\", true).unwrap();\n\n    let func = Function::get(\"error\");\n    assert!(func.is_some());\n    match func.unwrap().invoke(vec![10.into(), 20.into()]) {\n        Err(_) => {}\n        Ok(_) => panic!(\"expected error\"),\n    }\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/callback/src/bin/float.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#![allow(unused_imports)]\n\nuse std::convert::TryInto;\nuse tvm::{\n    errors::Error,\n    runtime::{ArgValue, RetValue},\n    *,\n};\n\nfn main() {\n    fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {\n        let mut ret = 0.0;\n        for arg in args.into_iter() {\n            let val: f64 = arg.try_into()?;\n            ret += val;\n        }\n        Ok(RetValue::from(ret))\n    }\n\n    function::register_untyped(sum, \"sum\", true).expect(\"registration should succeed\");\n\n    let func = Function::get(\"sum\").expect(\"sum was just registered.\");\n\n    let ret: f64 = func\n        .invoke(vec![10.0f64.into(), 20.0.into(), 30.0.into()])\n        .unwrap()\n        .try_into()\n        .unwrap();\n\n    assert_eq!(ret, 60f64);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/callback/src/bin/int.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryInto;\nuse tvm::{\n    errors::Error,\n    runtime::{ArgValue, RetValue},\n    *,\n};\n\nfn main() {\n    fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {\n        let mut ret = 0i64;\n        for arg in args.iter() {\n            let val: i64 = arg.try_into()?;\n            ret += val;\n        }\n        Ok(RetValue::from(ret))\n    }\n\n    tvm::function::register_untyped(sum, \"mysum\".to_owned(), false).unwrap();\n    let func = Function::get(\"mysum\").unwrap();\n    let ret: i64 = func\n        .invoke(vec![10.into(), 20.into(), 30.into()])\n        .unwrap()\n        .try_into()\n        .unwrap();\n    assert_eq!(ret, 60);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "rust/tvm/tests/callback/src/bin/string.rs",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nuse std::convert::TryInto;\nuse tvm::{\n    errors::Error,\n    runtime::{ArgValue, RetValue},\n    *,\n};\n\n// FIXME\nfn main() {\n    fn concat_str<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {\n        let mut ret = \"\".to_string();\n        for arg in args.iter() {\n            let val: &str = arg.try_into()?;\n            ret += val;\n        }\n        Ok(RetValue::from(ret))\n    }\n\n    let a = std::ffi::CString::new(\"a\").unwrap();\n    let b = std::ffi::CString::new(\"b\").unwrap();\n    let c = std::ffi::CString::new(\"c\").unwrap();\n\n    tvm::function::register_untyped(concat_str, \"concat_str\".to_owned(), false).unwrap();\n\n    let func = Function::get(\"concat_str\").expect(\"just registered a function\");\n\n    let args = vec![\n        a.as_c_str().into(),\n        b.as_c_str().into(),\n        c.as_c_str().into(),\n    ];\n\n    let ret: String = func\n        .invoke(args)\n        .expect(\"function call should succeed\")\n        .try_into()\n        .unwrap();\n\n    assert_eq!(ret, \"abc\".to_owned());\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/conjunctive_normal_form.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file conjunctive_normal_form.h\n *\n * \\brief Centralized location for simplifying into specific forms\n */\n\n#ifndef TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_\n#define TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_\n\n#include <tvm/tir/expr.h>\n\nnamespace tvm {\nnamespace arith {\n\nclass Analyzer;\n\n/*! \\brief Convert boolean expression to AND of ORs and simplify\n *\n * \\param expr The PrimExpr to be simplified\n *\n * \\param analyzer The analyzer with which to simplify\n *\n * \\return The simplified expression\n */\nPrimExpr SimplifyAsAndOfOrs(const PrimExpr& expr, Analyzer* analyzer);\n\n}  // namespace arith\n}  // namespace tvm\n\n#endif  // TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/const_fold.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file const_fold.h\n * \\brief Centralized location for constant folding.\n */\n#ifndef TVM_ARITH_CONST_FOLD_H_\n#define TVM_ARITH_CONST_FOLD_H_\n\n#include <tvm/runtime/container/optional.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include \"int_operator.h\"\n\nnamespace tvm {\nnamespace arith {\n\n/*!\n * \\brief Try to run binary compute with constant folding.\n *\n * \\param a The left operand.\n * \\param b The right operand.\n * \\tparam Op The operator type.\n *\n * \\note a and b Must already matched data types with each other.\n * \\return NullOpt if constant fold fails, otherwise return folded result.\n */\ntemplate <typename Op>\ninline Optional<PrimExpr> TryConstFold(PrimExpr a, PrimExpr b);\n\n/*!\n * \\brief Try to run unary compute with constant folding.\n *\n * \\param a The left operand.\n * \\tparam Op The operator type.\n *\n * \\note a and b Must already matched data types with each other.\n * \\return NullOpt if constant fold fails, otherwise return folded result.\n */\ntemplate <typename Op>\ninline Optional<PrimExpr> TryConstFold(PrimExpr a);\n\n/*!\n * \\brief Check whether type is used to represent index.\n *\n * Index types are frequently used in shape computation\n * and need to be aggressively constant-folded.\n *\n * \\param type The type to represent index.\n * \\return the checked result.\n */\ninline bool IsIndexType(const DataType& type) {\n  return type.is_int() && type.lanes() == 1 && (type.bits() == 32 || type.bits() == 64);\n}\n\n/*! \\brief Helper to get const folding result repr in int64. */\ninline int64_t GetFoldResultInt64Repr(int64_t x, const DataType& dtype) {\n  if (dtype.bits() < 64) {\n    x &= (1LL << dtype.bits()) - 1;\n  }\n  if (dtype.is_int()) {\n    // get sign extended value of integer with specified bits\n    int64_t m = 1LL << (dtype.bits() - 1);\n    x = (x ^ m) - m;\n  }\n  return x;\n}\n\n/*! \\brief Helper to get fp32 const folding result repr in double. */\ninline double GetFoldResultDoubleRepr(float x) {\n  double res = static_cast<double>(x);\n  if (std::isinf(res) || std::isnan(res)) {\n    return res;\n  }\n  // certain platform (eg, on gcc7-i386) do the folding arithmetic\n  // on float and write back to double is optimized to double\n  // precision arithmetic, this is legal and we check the output\n  // range thus to ensure consistency when the float result is inf.\n  if (res < std::numeric_limits<float>::lowest()) {\n    LOG(WARNING) << \"underlying float value overflow\";\n    return -std::numeric_limits<double>::infinity();\n  } else if (res > std::numeric_limits<float>::max()) {\n    LOG(WARNING) << \"underlying float value overflow\";\n    return std::numeric_limits<double>::infinity();\n  }\n  return res;\n}\n\n#define TVM_ARITH_CONST_PROPAGATION(BODY)        \\\n  using tir::FloatImmNode;                       \\\n  const IntImmNode* pa = a.as<IntImmNode>();     \\\n  const IntImmNode* pb = b.as<IntImmNode>();     \\\n  const FloatImmNode* fa = a.as<FloatImmNode>(); \\\n  const FloatImmNode* fb = b.as<FloatImmNode>(); \\\n  BODY;\n\n#define TVM_INDEX_CONST_PROPAGATION(BODY)                 \\\n  const IntImmNode* pa = a.as<IntImmNode>();              \\\n  const IntImmNode* pb = b.as<IntImmNode>();              \\\n  const DataType& ta = a.dtype();                         \\\n  const DataType& tb = b.dtype();                         \\\n  if (arith::IsIndexType(ta) && arith::IsIndexType(tb)) { \\\n    BODY;                                                 \\\n  }\n\n// specialization of constant folders.\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Add>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      int64_t res = pa->value + pb->value;\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa && pa->value == 0) return b;\n    if (pb && pb->value == 0) return a;\n    if (fa && fb) {\n      if (rtype.bits() == 32) {\n        return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) +\n                                                       static_cast<float>(fb->value)));\n      } else if (rtype.bits() == 64) {\n        return FloatImm(rtype, fa->value + fb->value);\n      } else {\n        return NullOpt;\n      }\n    }\n    if (fa && fa->value == 0) return b;\n    if (fb && fb->value == 0) return a;\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Sub>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    ICHECK(!((pa && pa->dtype.is_uint() && pa->value == 0U) &&\n             (pb && pb->dtype.is_uint() && pb->value > 0U)))\n        << \"Checked failed. Minuend 's value is 0U and it's dtype is uint \"\n        << \"while Subtrahend's dtype is uint; which will cause a negative uint\";\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      int64_t res = pa->value - pb->value;\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pb && pb->value == 0) return a;\n    if (fa && fb) {\n      if (rtype.bits() == 32) {\n        return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) -\n                                                       static_cast<float>(fb->value)));\n      } else if (rtype.bits() == 64) {\n        return FloatImm(rtype, fa->value - fb->value);\n      } else {\n        return NullOpt;\n      }\n    }\n    if (fb && fb->value == 0) return a;\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Mul>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      int64_t res = pa->value * pb->value;\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa) {\n      if (pa->value == 1) return b;\n      if (pa->value == 0) return a;\n    }\n    if (pb) {\n      if (pb->value == 1) return a;\n      if (pb->value == 0) return b;\n    }\n    if (fa && fb) {\n      if (rtype.bits() == 32) {\n        return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) *\n                                                       static_cast<float>(fb->value)));\n      } else if (rtype.bits() == 64) {\n        return FloatImm(rtype, fa->value * fb->value);\n      } else {\n        return NullOpt;\n      }\n    }\n    if (fa) {\n      if (fa->value == 1) return b;\n      if (fa->value == 0) return a;\n    }\n    if (fb) {\n      if (fb->value == 1) return a;\n      if (fb->value == 0) return b;\n    }\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Div>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      // due to division and mod can have different modes\n      // NOTE: this will assumes truc div.\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n      int64_t res = pa->value / pb->value;\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa) {\n      if (pa->value == 0) return a;\n    }\n    if (pb) {\n      if (pb->value == 1) return a;\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n    }\n    if (fa && fb) {\n      ICHECK_NE(fb->value, 0) << \"Divide by zero\";\n      if (rtype.bits() == 32) {\n        return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) /\n                                                       static_cast<float>(fb->value)));\n      } else if (rtype.bits() == 64) {\n        return FloatImm(rtype, fa->value / fb->value);\n      } else {\n        return NullOpt;\n      }\n    }\n    if (fa && fa->value == 0) return a;\n    if (fb) {\n      if (fb->value == 1) return a;\n      ICHECK_NE(fb->value, 0) << \"Divide by zero\";\n    }\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Mod>(PrimExpr a, PrimExpr b) {\n  TVM_INDEX_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n      int64_t res = pa->value % pb->value;\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa) {\n      if (pa->value == 0) return a;\n    }\n    if (pb) {\n      if (pb->value == 1) return tir::make_zero(rtype);\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n    }\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::FloorDiv>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n      int64_t res = arith::floordiv(pa->value, pb->value);\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa) {\n      if (pa->value == 0) return a;\n    }\n    if (pb) {\n      if (pb->value == 1) return a;\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n    }\n    if (fa && fb && fb->value != 0) {\n      if (rtype.bits() == 32) {\n        return FloatImm(rtype, GetFoldResultDoubleRepr(std::floor(static_cast<float>(fa->value) /\n                                                                  static_cast<float>(fb->value))));\n      } else if (rtype.bits() == 64) {\n        return FloatImm(rtype, std::floor(fa->value / fb->value));\n      } else {\n        return NullOpt;\n      }\n    }\n    if (fa && fa->value == 0) return a;\n    if (fb) {\n      if (fb->value == 1) return a;\n      ICHECK_NE(fb->value, 0) << \"Divide by zero\";\n    }\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::FloorMod>(PrimExpr a, PrimExpr b) {\n  TVM_INDEX_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) {\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n      int64_t res = arith::floormod(pa->value, pb->value);\n      return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));\n    }\n    if (pa) {\n      if (pa->value == 0) return a;\n    }\n    if (pb) {\n      if (pb->value == 1) return tir::make_zero(rtype);\n      ICHECK_NE(pb->value, 0) << \"Divide by zero\";\n    }\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Min>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) return IntImm(rtype, std::min(pa->value, pb->value));\n    if (fa && fb) return FloatImm(rtype, std::min(fa->value, fb->value));\n  });\n  if (a.same_as(b)) return a;\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Max>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    const DataType& rtype = a.dtype();\n    if (pa && pb) return IntImm(rtype, std::max(pa->value, pb->value));\n    if (fa && fb) return FloatImm(rtype, std::max(fa->value, fb->value));\n  });\n  if (a.same_as(b)) return a;\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::GT>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value > pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value > fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::GE>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value >= pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value >= fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::LT>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value < pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value < fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::LE>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value <= pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value <= fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::EQ>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value == pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value == fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::NE>(PrimExpr a, PrimExpr b) {\n  TVM_ARITH_CONST_PROPAGATION({\n    if (pa && pb) return IntImm(DataType::UInt(1), pa->value != pb->value);\n    if (fa && fb) return IntImm(DataType::UInt(1), fa->value != fb->value);\n  });\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::And>(PrimExpr a, PrimExpr b) {\n  const IntImmNode* pa = a.as<IntImmNode>();\n  const IntImmNode* pb = b.as<IntImmNode>();\n  if (pa && pa->value) return b;\n  if (pa && !pa->value) return a;\n  if (pb && pb->value) return a;\n  if (pb && !pb->value) return b;\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Or>(PrimExpr a, PrimExpr b) {\n  const IntImmNode* pa = a.as<IntImmNode>();\n  const IntImmNode* pb = b.as<IntImmNode>();\n  if (pa && pa->value) return a;\n  if (pa && !pa->value) return b;\n  if (pb && pb->value) return b;\n  if (pb && !pb->value) return a;\n  return NullOpt;\n}\n\ntemplate <>\ninline Optional<PrimExpr> TryConstFold<tir::Not>(PrimExpr a) {\n  const IntImmNode* pa = a.as<IntImmNode>();\n  if (pa) {\n    return IntImm(DataType::UInt(1), !(pa->value));\n  }\n  return NullOpt;\n}\n\n/*! \\brief Helper namespace for symbolic value limits */\nstruct SymbolicLimits {\n  /*! \\brief positive infinity */\n  static PrimExpr pos_inf_;\n  /*! \\brief negative infinity */\n  static PrimExpr neg_inf_;\n};\n\n/*!\n * \\brief Opaque expression representing positive infinity.\n *\n *  It can can only be used as parameter of by min/max\n *  for integer analysis and cannot be used in normal expressions.\n *\n * \\return positive infinity.\n */\ninline PrimExpr pos_inf() { return SymbolicLimits::pos_inf_; }\n\n/*!\n * \\brief Check if value is positive infinity.\n * \\param value The value to be checked.\n *\n * \\return The check result.\n */\ninline bool is_pos_inf(const PrimExpr& value) { return value.same_as(SymbolicLimits::pos_inf_); }\n\n/*!\n * \\brief Opaque expression representing negative infinity.\n *\n *  It can can only be used as parameter of by min/max\n *  for integer analysis and cannot be used in normal expressions.\n *\n * \\return negative infinity.\n */\ninline PrimExpr neg_inf() { return SymbolicLimits::neg_inf_; }\n\n/*!\n * \\brief Check if value is negative infinity.\n * \\param value The value to be checked.\n *\n * \\return The check result.\n */\ninline bool is_neg_inf(const PrimExpr& value) { return value.same_as(SymbolicLimits::neg_inf_); }\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_CONST_FOLD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/constraint_extract.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file contraint_extract.h\n *\n * \\brief Centralized location for extraction of constraints from a boolean expression.\n */\n\n#ifndef TVM_ARITH_CONSTRAINT_EXTRACT_H_\n#define TVM_ARITH_CONSTRAINT_EXTRACT_H_\n\n#include <tvm/tir/expr.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace arith {\n\n/* \\brief Returns constraints that are true if the expression is true.\n *\n * Utility to break up a boolean expression into independent\n * constraints.\n *\n * Example: `i==5 && j==3` => `[i==5 && j==3, i==5, j==3]`\n * Example: `i==5 || j==3` => `[i==5 || j==3]`\n * Example: `!(i>5 || j==3)` => `[!(i==5 || j==3), i<=5, j!=3]`\n *\n * Intended for use in bounds analysis or simplification within a\n * conditional, or identifying independent conditionals that may be\n * hoisted.\n *\n * \\param expr The expression to be analyzers\n *\n * \\returns A vector of independent constraints\n */\nstd::vector<PrimExpr> ExtractConstraints(const PrimExpr& expr);\n\n}  // namespace arith\n}  // namespace tvm\n\n#endif  // TVM_ARITH_CONSTRAINT_EXTRACT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/int_operator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file int_operator.h\n * \\brief Additional useful operators for integer.\n */\n#ifndef TVM_ARITH_INT_OPERATOR_H_\n#define TVM_ARITH_INT_OPERATOR_H_\n\n#include <limits>\n#include <utility>\n\nnamespace tvm {\nnamespace arith {\n\n/*!\n * \\brief Check if an integer op with operand x, y will overflow.\n * \\param x The left operand.\n * \\param y The left operand.\n * \\param min_value The minimum value of the domain.\n * \\param max_value The maximum value of the domain.\n * \\return Whether overflow can happen.\n * \\tparam Op The integer operator.\n */\ntemplate <typename Op>\ninline bool WillOverflow(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {\n  return false;\n}\n\ntemplate <>\ninline bool WillOverflow<tir::AddNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {\n  if ((y > 0) && (x > max_value - y)) return true;\n  if ((y < 0) && (x < min_value - y)) return true;\n  return false;\n}\n\ntemplate <>\ninline bool WillOverflow<tir::SubNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {\n  if ((y > 0) && (x < min_value + y)) return true;\n  if ((y < 0) && (x > max_value + y)) return true;\n  return false;\n}\n\ntemplate <>\ninline bool WillOverflow<tir::MulNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {\n  if (y == 0) return false;\n  if (y > 0) {\n    if (x < min_value / y) return true;\n    if (x > max_value / y) return true;\n  } else {\n    if (y == -1 && x == std::numeric_limits<int64_t>::min()) return true;\n    if (x > min_value / y) return true;\n    if (x < max_value / y) return true;\n  }\n  return false;\n}\n\ntemplate <>\ninline bool WillOverflow<tir::ModNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {\n  return y == 0;\n}\n\n/*!\n * \\brief Perform trunc division of two integers.\n * \\param x The left operand.\n * \\param y The right operand.\n * \\return the result.\n */\ninline int64_t truncdiv(int64_t x, int64_t y) { return x / y; }\n\n/*!\n * \\brief Compute the truncdiv remainder of two integers.\n * \\param x The left operand.\n * \\param y The right operand.\n * \\return the result.\n */\ninline int64_t truncmod(int64_t x, int64_t y) { return x % y; }\n\n/*!\n * \\brief Perform floor division of two integers.\n * \\param x The left operand.\n * \\param y The right operand.\n * \\return the result.\n */\ninline int64_t floordiv(int64_t x, int64_t y) {\n  int64_t rdiv = x / y;\n  int64_t rmod = x % y;\n  bool is_floor_div = (y >= 0 && rmod >= 0) || (y < 0 && rmod <= 0);\n  return is_floor_div ? rdiv : (rdiv - 1);\n}\n\n/*!\n * \\brief Compute the floordiv remainder of two integers.\n * \\param x The left operand.\n * \\param y The right operand.\n * \\return the result.\n */\ninline int64_t floormod(int64_t x, int64_t y) {\n  int64_t rmod = x % y;\n  bool is_floor_div = (y >= 0 && rmod >= 0) || (y < 0 && rmod <= 0);\n  return is_floor_div ? rmod : rmod + y;\n}\n\n/*!\n * \\brief Use Extended Euclidean algorithm to solve ax + by = gcd(a, b)\n * \\param a The first coefficient.\n * \\param b The second coefficient.\n * \\param x The solution of x.\n * \\param y The solution of y.\n * \\return The GCD of a and b.\n */\ninline int64_t ExtendedEuclidean(int64_t a, int64_t b, int64_t* x, int64_t* y) {\n  // Extended Euclidean algorithm\n  // if a < 0, the problem can be convert into\n  // |a|* (-x) + b * y = gcd(|a|, b)\n  //\n  // initial condition:\n  // a * 0 + b * 1 = b\n  // a * 1 + b * 0 = a\n  int64_t s = 0, old_s = 1;\n  int64_t r = b, old_r = a >= 0 ? a : -a;\n  // Iteration (r2 < r1):\n  // a * x1 + b * y1 = r1\n  // a * x2 + b * y2 = r2\n  // The above two eqs can derive the following eq (q = r1 / r2)\n  // a * (x1 - x2 * q) + b * (y1 - y2 * q) = r1 - r2 * q = r3\n  // Because r3 < r2, the iteration can eventually terminate\n  while (r != 0) {\n    int64_t q = old_r / r;\n    int64_t tmp = old_r;\n    old_r = r;\n    r = tmp - q * r;\n    tmp = old_s;\n    old_s = s;\n    s = tmp - q * s;\n  }\n\n  *x = a >= 0 ? old_s : -old_s;\n  if (b != 0) {\n    *y = (old_r - (*x) * a) / b;\n  } else {\n    *y = 1;\n  }\n\n  return old_r;\n}\n\n/*!\n * \\brief Take GCD of a and b.\n * \\param a The first operand.\n * \\param b The second operand.\n * \\return The result.\n */\ninline int64_t ZeroAwareGCD(int64_t a, int64_t b) {\n  if (a < 0) a = -a;\n  if (b < 0) b = -b;\n  if (a < b) std::swap(a, b);\n  if (b == 0) return a;\n  // perform GCD (greatest common divisor)\n  // ax + by = gcd(a, b) z if a != 0, b != 0\n  while (a % b != 0) {\n    a = a % b;\n    std::swap(a, b);\n  }\n  return b;\n}\n\n/*!\n * \\brief Calculate the least common multiple for two values.\n * \\param a an integer number\n * \\param b an integer number\n * \\return the least common multiple.\n */\ninline int64_t LeastCommonMultiple(int64_t a, int64_t b) {\n  int64_t x, y;\n  return (a * b) / ExtendedEuclidean(a, b, &x, &y);\n}\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_INT_OPERATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/interval_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file int_set.h\n * \\brief Internal data structure for integer set.\n */\n#ifndef TVM_ARITH_INTERVAL_SET_H_\n#define TVM_ARITH_INTERVAL_SET_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/tir/op.h>\n\n#include <limits>\n\n#include \"const_fold.h\"\n\nnamespace tvm {\nnamespace arith {\n\n// Acknowledgement: IntervalSet design originates from Halide.\n/*!\n * \\brief Symbolic interval set.\n *\n * \\note We intentionally keep the internal of IntSet private,\n         as we might change it later.\n */\nclass IntervalSetNode : public IntSetNode {\n public:\n  /*! \\brief Minimum value in the interval. */\n  PrimExpr min_value;\n  /*! \\brief Maximum value in the interval. */\n  PrimExpr max_value;\n\n  // visitor overload.\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"min_value\", &min_value);\n    v->Visit(\"max_value\", &max_value);\n  }\n\n  /*! \\return Whether the interval has upper bound. */\n  bool HasUpperBound() const { return !is_pos_inf(max_value) && !IsEmpty(); }\n  /*! \\return Whether the interval has lower bound. */\n  bool HasLowerBound() const { return !is_neg_inf(min_value) && !IsEmpty(); }\n  /*! \\return Whether the interval is a single point. */\n  bool IsSinglePoint() const {\n    if (min_value.same_as(max_value)) {\n      return true;\n    }\n    Analyzer analyzer;\n    return analyzer.CanProveEqual(min_value, max_value);\n  }\n  /*! \\return whether interval represent nothing */\n  bool IsEmpty() const {\n    // during computations, either extreme could occur.\n    return is_pos_inf(min_value) || is_neg_inf(max_value);\n  }\n  /*! \\return whether interval represent everything */\n  bool IsEverything() const { return is_neg_inf(min_value) && is_pos_inf(max_value); }\n\n  static constexpr const char* _type_key = \"arith.IntervalSet\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(IntervalSetNode, IntSetNode);\n};\n\n/*!\n * \\brief Interval set used for symbolic integer analysis.\n * \\sa IntervalSetNode\n */\nclass IntervalSet : public IntSet {\n public:\n  /*!\n   * \\brief Make a new instance of interval set.\n   * \\param min_value The minimum value in the interval.\n   * \\param max_value The maximum value in the interval.\n   * \\return The created set.\n   */\n  TVM_DLL IntervalSet(PrimExpr min_value, PrimExpr max_value);\n\n  /*!\n   * \\brief Create an IntervalSet that represents a single point.\n   * \\param value The value to be represented.\n   * \\return The result set.\n   */\n  static IntervalSet SinglePoint(PrimExpr value) { return IntervalSet(value, value); }\n  /*!\n   * \\brief Create an IntervalSet that represents everything.\n   * \\param value The value to be represented.\n   * \\return The result set.\n   */\n  static IntervalSet Everything() { return IntervalSet(neg_inf(), pos_inf()); }\n  /*!\n   * \\brief Create an empty eet.\n   * \\return The result set.\n   */\n  static IntervalSet Empty() { return IntervalSet(pos_inf(), neg_inf()); }\n\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(IntervalSetNode);\n  TVM_DEFINE_OBJECT_REF_METHODS(IntervalSet, IntSet, IntervalSetNode);\n};\n\n/*!\n * \\brief Create union of two IntervalSets.\n * \\param analyzer The analyzer for simplification analysis.\n * \\param a The first set.\n * \\param b The second set.\n * \\return The result set.\n */\nTVM_DLL IntervalSet Union(Analyzer* analyzer, IntervalSet a, IntervalSet b);\n\n/*!\n * \\brief Create insersection of two IntervalSets.\n * \\param analzyer The analyzer for simplification analysis.\n * \\param a The first set.\n * \\param b The second set.\n * \\return The result set.\n */\nTVM_DLL IntervalSet Intersect(Analyzer* analzyer, IntervalSet a, IntervalSet b);\n\n}  // namespace arith\n}  // namespace tvm\n\n#endif  // TVM_ARITH_INTERVAL_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/ir_mutator_with_analyzer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arithmetic/ir_mutator_with_analyzer.h\n * \\brief IR mutator base-class with an analyzer context.\n */\n#ifndef TVM_ARITH_IR_MUTATOR_WITH_ANALYZER_H_\n#define TVM_ARITH_IR_MUTATOR_WITH_ANALYZER_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace arith {\n\n/*!\n * \\brief IRMutator with an analyzer context.\n *\n * This class can sub-classed by ir mutators that need an analyzer.\n * It will populates scope-related info such as bounds of loop-variables and constraints\n * for the analyzer, so that the child class can do accurate context-dependent analysis.\n *\n * \\sa src/arithmetic/ir_mutator_with_analyzer.cc\n */\nclass IRMutatorWithAnalyzer : public tir::StmtExprMutator {\n public:\n  explicit IRMutatorWithAnalyzer(Analyzer* analyzer) : analyzer_(analyzer) {}\n\n  using StmtExprMutator::VisitExpr_;\n  using StmtExprMutator::VisitStmt_;\n\n  // override functions that need to populate the context information.\n  tir::Stmt VisitStmt_(const tir::ForNode* op) override;\n  tir::Stmt VisitStmt_(const tir::BlockNode* op) override;\n  tir::Stmt VisitStmt_(const tir::LetStmtNode* op) override;\n  tir::Stmt VisitStmt_(const tir::IfThenElseNode* op) override;\n  tir::Stmt VisitStmt_(const tir::AttrStmtNode* op) override;\n  tir::Stmt VisitStmt_(const tir::AssertStmtNode* op) override;\n  PrimExpr VisitExpr_(const tir::LetNode* op) override;\n  PrimExpr VisitExpr_(const tir::SelectNode* op) override;\n  PrimExpr VisitExpr_(const tir::CallNode* op) override;\n  PrimExpr VisitExpr_(const tir::ReduceNode* op) override;\n\n protected:\n  /*! \\brief internal analyzer field. */\n  Analyzer* analyzer_;\n};\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_IR_MUTATOR_WITH_ANALYZER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/ir_visitor_with_analyzer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arithmetic/ir_visitor_with_analyzer.h\n * \\brief IR visitor class with an analyzer context.\n */\n\n#ifndef TVM_ARITH_IR_VISITOR_WITH_ANALYZER_H_\n#define TVM_ARITH_IR_VISITOR_WITH_ANALYZER_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt_functor.h>\n\nnamespace tvm {\nnamespace arith {\n\nclass IRVisitorWithAnalyzer : public tir::StmtExprVisitor {\n public:\n  PrimExpr Simplify(const PrimExpr& expr) { return analyzer_.Simplify(expr); }\n\n  using StmtExprVisitor::VisitExpr_;\n  using StmtExprVisitor::VisitStmt_;\n\n  void VisitStmt_(const tir::ForNode* op);\n  void VisitStmt_(const tir::BlockNode* op);\n  void VisitStmt_(const tir::LetStmtNode* op);\n  void VisitStmt_(const tir::IfThenElseNode* op);\n  void VisitStmt_(const tir::AttrStmtNode* op);\n  void VisitStmt_(const tir::AssertStmtNode* op);\n  void VisitExpr_(const tir::CallNode* op);\n  void VisitExpr_(const tir::LetNode* op);\n  void VisitExpr_(const tir::ReduceNode* op);\n\n  // IRVisitorWithAnalyzer deliberately does not handle Select nodes,\n  // because both sides of a Select node are visited regardless of the\n  // condition.\n\n protected:\n  /*! \\brief internal analyzer field. */\n  arith::Analyzer analyzer_;\n\n private:\n  PrimExpr ExtractRealCondition(PrimExpr condition) const;\n};\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_IR_VISITOR_WITH_ANALYZER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/narrow_predicate_expression.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file narrow_predicate_expression.h\n * \\brief Utility for extracting and interacting with buffer touch points\n */\n\n#include <tvm/ir/expr.h>\n#include <tvm/tir/var.h>\n\n#ifndef TVM_ARITH_NARROW_PREDICATE_EXPRESSION_H_\n#define TVM_ARITH_NARROW_PREDICATE_EXPRESSION_H_\n\nnamespace tvm {\nnamespace arith {\n\n/* \\brief Narrow a true expression to remove free parameters\n *\n * This function provides two guarantees:\n *\n * 1. If the resulting expression evaluates to True, then the original\n * expression also evaluates to True.\n *\n * 2. The resulting expression does not contain any of the free\n * parameters.\n *\n * 3. The resulting expression does not contain any BufferLoad\n *\n * \\param expr The expression to be examined.\n *\n * \\param ranges The variables to be removed from the expression\n *\n * \\returns An expression that, if true, implies that the original\n * expression is also true.\n */\nPrimExpr NarrowPredicateExpression(PrimExpr expr, Map<tir::Var, Range> free_parameters);\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_NARROW_PREDICATE_EXPRESSION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/pattern_match.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/arithmetic/pattern_match.h\n *\n * \\brief Internal tool for expression-template based pattern matching.\n *\n * It helps to simplify pattern matching and rewrites.\n * All the patterns are generated via expression template during compile time,\n * so the result code should be as efficient as manually written pattern match code.\n *\n * The code below shows how to use the pattern matcher.\n *\n * \\code\n *\n *  // max(x + z, y + z) => max(x, y) + z\n *  arith::PVar<Expr> x, y, z;\n *\n *  // The following code tries to match the declared pattern.\n *  // Match will fill the result of match into PVar if successful.\n *  // Note that z occurs twice in the pattern,\n *  // an equality check is performed to ensure each occurance of z\n *  // is equivalent to each other.\n *  if (max(x + z, y + z).Match(expr)) {\n *    // Eval evaluates a pattern with the current matched value.\n *    // The filled value is valid until the next call to Match.\n *    return (max(x, y) + z).Eval();\n *  }\n *\n *  tvm::tir::Var tx, ty;\n *  arith::PVar<IntImm> c;\n *  arith::PVar<Var> v;\n *  // We can match integer and Var, both of which are\n *  // special case container of Expr\n *  ICHECK((v * c).Match(tx * 3));\n *  ICHECK_EQ(c.Eval()->value, 3);\n *  // cannot match c to ty\n *  ICHECK(!(v * c).Match(tx * ty));\n *\n * \\endcode\n *\n * \\note The pattern matcher is not threadsafe,\n *       do not use the same PVar in multiple threads.\n *\n *       Please be aware that the filled value in a PVar\n *       can be overriden in the next call to Match.\n */\n#ifndef TVM_ARITH_PATTERN_MATCH_H_\n#define TVM_ARITH_PATTERN_MATCH_H_\n\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n\n#include <cmath>\n#include <tuple>\n\n#include \"const_fold.h\"\n\nnamespace tvm {\nnamespace arith {\n/*!\n * \\brief Base class of all the patterns.\n *\n * There are two major member functions supported by each pattern.\n * - Match: checks if value matches the pattern.\n * - Eval: construct a new value based on matched values in PVar.\n *\n * We use curiously recurring template pattern to construct\n * expression templates.\n *\n * \\tparam Derived The type of the derived class.\n */\ntemplate <typename Derived>\nclass Pattern {\n public:\n  /*!\n   * \\brief Nested storage type in the expression.\n   *\n   *  Depending on the Derived class,\n   *  Nested can be Derived (nest by value) or\n   *  const Derived& (nest by reference).\n   *\n   *  The trick of Nested typedef originates from Eigen.\n   *\n   * \\note We use nest by value for intermediate expressions,\n   *       and nest by reference for PVars.\n   */\n  using Nested = Derived;\n  /*!\n   * \\brief Check if value matches the current pattern.\n   *\n   * This call also populates the PVars with matched value.\n   * The values in PVars are valid until the next call to Match.\n   *\n   * \\return whether value matches the pattern.\n   */\n  template <typename NodeType>\n  bool Match(const NodeType& value) const {\n    derived().InitMatch_();\n    return derived().Match_(value);\n  }\n  /*! \\return Derived instance of current class. */\n  const Derived& derived() const { return *static_cast<const Derived*>(this); }\n};\n\n/*!\n * \\brief Default deep equality checker\n * \\tparam T the comparison point.\n */\ntemplate <typename T>\nclass PEqualChecker {\n public:\n  bool operator()(const T& lhs, const T& rhs) const { return lhs == rhs; }\n};\n\ntemplate <>\nclass PEqualChecker<PrimExpr> {\n public:\n  bool operator()(const PrimExpr& lhs, const PrimExpr& rhs) const {\n    if (lhs.same_as(rhs)) return true;\n    return tir::ExprDeepEqual()(lhs, rhs);\n  }\n};\n\ntemplate <>\nclass PEqualChecker<IntImm> {\n public:\n  bool operator()(const IntImm& lhs, const IntImm& rhs) const { return lhs->value == rhs->value; }\n};\n\ntemplate <>\nclass PEqualChecker<FloatImm> {\n public:\n  bool operator()(const FloatImm& lhs, const FloatImm& rhs) const {\n    return std::fabs(lhs->value - rhs->value) < 1e-20;\n  }\n};\n\ntemplate <>\nclass PEqualChecker<tir::Var> {\n public:\n  bool operator()(const tir::Var& lhs, const tir::Var& rhs) const { return lhs.same_as(rhs); }\n};\n\n/*!\n * \\brief Pattern variable container.\n *\n * PVar is used as a \"hole\" in the pattern that can be matched.\n *\n * \\tparam T the type of the hole.\n *\n * \\note PVar is not thread safe.\n *       Do not use the same PVar in multiple threads.\n */\ntemplate <typename T>\nclass PVar : public Pattern<PVar<T>> {\n public:\n  // Store PVars by reference in the expression.\n  using Nested = const PVar<T>&;\n\n  void InitMatch_() const { filled_ = false; }\n\n  bool Match_(const T& value) const {\n    if (!filled_) {\n      value_ = value;\n      filled_ = true;\n      return true;\n    } else {\n      return PEqualChecker<T>()(value_, value);\n    }\n  }\n\n  template <typename NodeRefType,\n            typename = typename std::enable_if<std::is_base_of<NodeRefType, T>::value>::type>\n  bool Match_(const NodeRefType& value) const {\n    if (const auto* ptr = value.template as<typename T::ContainerType>()) {\n      return Match_(GetRef<T>(ptr));\n    } else {\n      return false;\n    }\n  }\n\n  T Eval() const {\n    ICHECK(filled_);\n    return value_;\n  }\n\n  T EvalOr(const T& default_value) const { return filled_ ? value_ : default_value; }\n\n protected:\n  /*! \\brief The matched value */\n  mutable T value_;\n  /*! \\brief whether the variable has been filled */\n  mutable bool filled_{false};\n};\n\n/*!\n * \\brief Wrapper for pattern variable container with extra match logic.\n *\n * \\tparam Derived the type of derived class.\n * \\tparam T the type of the hole.\n */\ntemplate <typename Derived, typename T>\nclass PVarWithCheck : public arith::Pattern<PVarWithCheck<Derived, T>> {\n public:\n  // Store by reference in the expression.\n  using Nested = const PVarWithCheck<Derived, T>&;\n\n  void InitMatch_() const { pvar_.InitMatch_(); }\n\n  bool Match_(const T& value) const {\n    if (!static_cast<const Derived*>(this)->Match_(value)) return false;\n    return pvar_.Match_(value);\n  }\n\n  template <typename NodeRefType,\n            typename = typename std::enable_if<std::is_base_of<NodeRefType, T>::value>::type>\n  bool Match_(const NodeRefType& value) const {\n    if (const auto* ptr = value.template as<typename T::ContainerType>()) {\n      return Match_(GetRef<T>(ptr));\n    } else {\n      return false;\n    }\n  }\n\n  T Eval() const { return pvar_.Eval(); }\n\n protected:\n  arith::PVar<T> pvar_;\n};\n\n/*!\n * \\brief Pattern variable container with expr type check.\n *\n * \\tparam T the type of the hole.\n * \\tparam DType the Pattern type of dtype.\n */\ntemplate <typename T, typename DType,\n          typename = std::enable_if<std::is_base_of<T, PrimExpr>::value>>\nclass PVarWithDataType : public PVarWithCheck<PVarWithDataType<T, DType>, T> {\n public:\n  explicit PVarWithDataType(const DType& dtype) : dtype_(dtype) {}\n\n  bool Match_(const T& value) const { return dtype_.Match_(value->dtype); }\n\n protected:\n  typename DType::Nested dtype_;\n};\n\n/*!\n * \\brief Pattern variable container for data type with lanes.\n */\nclass PVecDataType : public PVarWithCheck<PVecDataType, DataType> {\n public:\n  /*! \\brief construct vector dtype placeholder with element type check */\n  explicit PVecDataType(const DataType& elem_dtype) : elem_dtype_(elem_dtype) {}\n\n  bool Match_(const DataType& dtype) const { return dtype.code() == elem_dtype_.code(); }\n\n protected:\n  DataType elem_dtype_;\n};\n\n/*!\n * \\brief Constant Pattern variable container.\n *\n * \\tparam T the type of the hole.\n */\ntemplate <typename T>\nclass PConst : public Pattern<PConst<T>> {\n public:\n  PConst(T value)  // NOLINT(*)\n      : value_(value) {}\n\n  void InitMatch_() const {}\n\n  bool Match_(const T& value) const { return PEqualChecker<T>()(value_, value); }\n\n  T Eval() const { return value_; }\n\n private:\n  const T value_;\n};\n\n/*!\n * \\brief Pattern binary expression.\n * \\tparam OpType The AST noderef type.\n * \\tparam TA The pattern type of the first operand.\n * \\tparam TB The pattern type of the second operand.\n */\ntemplate <typename OpType, typename TA, typename TB>\nclass PBinaryExpr : public Pattern<PBinaryExpr<OpType, TA, TB>> {\n public:\n  PBinaryExpr(const TA& a, const TB& b) : a_(a), b_(b) {}\n\n  void InitMatch_() const {\n    a_.InitMatch_();\n    b_.InitMatch_();\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    using NodeType = typename OpType::ContainerType;\n    if (const NodeType* ptr = node.as<NodeType>()) {\n      if (!a_.Match_(ptr->a)) return false;\n      if (!b_.Match_(ptr->b)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const {\n    PrimExpr lhs = a_.Eval();\n    PrimExpr rhs = b_.Eval();\n    if (auto ret = TryConstFold<OpType>(lhs, rhs)) return ret.value();\n    return OpType(lhs, rhs);\n  }\n\n private:\n  typename TA::Nested a_;\n  typename TB::Nested b_;\n};\n\ntemplate <typename TA>\nclass PConstWithTypeLike : public Pattern<PConstWithTypeLike<TA>> {\n public:\n  PConstWithTypeLike(const TA& ref, int64_t value) : ref_(ref), value_(value) {}\n\n  void InitMatch_() const {}\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::IntImmNode* ptr = node.as<tir::IntImmNode>()) {\n      return ptr->value == value_;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const { return tir::make_const(ref_.Eval().dtype(), value_); }\n\n private:\n  typename TA::Nested ref_;\n  int64_t value_;\n};\n\n#define TVM_PATTERN_BINARY_OP_EX(FuncName, NodeName, CheckStep)                               \\\n  template <typename TA, typename TB>                                                         \\\n  inline PBinaryExpr<NodeName, TA, TB> FuncName(const Pattern<TA>& a, const Pattern<TB>& b) { \\\n    CheckStep;                                                                                \\\n    return PBinaryExpr<NodeName, TA, TB>(a.derived(), b.derived());                           \\\n  }                                                                                           \\\n  template <typename TA>                                                                      \\\n  inline PBinaryExpr<NodeName, TA, PConstWithTypeLike<TA>> FuncName(const Pattern<TA>& a,     \\\n                                                                    int64_t b) {              \\\n    CheckStep;                                                                                \\\n    return FuncName(a, PConstWithTypeLike<TA>(a.derived(), b));                               \\\n  }                                                                                           \\\n  template <typename TA>                                                                      \\\n  inline PBinaryExpr<NodeName, PConstWithTypeLike<TA>, TA> FuncName(int64_t b,                \\\n                                                                    const Pattern<TA>& a) {   \\\n    CheckStep;                                                                                \\\n    return FuncName(PConstWithTypeLike<TA>(a.derived(), b), a);                               \\\n  }\n\n#define TVM_PATTERN_BINARY_OP(FuncName, NodeName) TVM_PATTERN_BINARY_OP_EX(FuncName, NodeName, )\n\n// raise ambiguity error for operator overload of / and %\nTVM_PATTERN_BINARY_OP_EX(operator/, tir::Div, DivAmbiguityError(a));\nTVM_PATTERN_BINARY_OP_EX(operator%, tir::Mod, DivAmbiguityError(a));\n\n// arithmetic expressions\nTVM_PATTERN_BINARY_OP(operator+, tir::Add);\nTVM_PATTERN_BINARY_OP(operator-, tir::Sub);\nTVM_PATTERN_BINARY_OP(operator*, tir::Mul);\nTVM_PATTERN_BINARY_OP(min, tir::Min);\nTVM_PATTERN_BINARY_OP(max, tir::Max);\nTVM_PATTERN_BINARY_OP(div, tir::Div);\nTVM_PATTERN_BINARY_OP(truncdiv, tir::Div);\nTVM_PATTERN_BINARY_OP(truncmod, tir::Mod);\nTVM_PATTERN_BINARY_OP(floordiv, tir::FloorDiv);\nTVM_PATTERN_BINARY_OP(floormod, tir::FloorMod);\n\n// logical expressions\nTVM_PATTERN_BINARY_OP(operator>, tir::GT);\nTVM_PATTERN_BINARY_OP(operator>=, tir::GE);\nTVM_PATTERN_BINARY_OP(operator<, tir::LT);\nTVM_PATTERN_BINARY_OP(operator<=, tir::LE);\nTVM_PATTERN_BINARY_OP(operator==, tir::EQ);\nTVM_PATTERN_BINARY_OP(operator!=, tir::NE);\nTVM_PATTERN_BINARY_OP(operator&&, tir::And);\nTVM_PATTERN_BINARY_OP(operator||, tir::Or);\n\n/*!\n * \\brief Pattern not expression.\n * \\tparam TA The pattern type of the true operand.\n */\ntemplate <typename TA>\nclass PNotExpr : public Pattern<PNotExpr<TA>> {\n public:\n  explicit PNotExpr(const TA& value) : value_(value) {}\n\n  void InitMatch_() const { value_.InitMatch_(); }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::NotNode* ptr = node.as<tir::NotNode>()) {\n      if (!value_.Match_(ptr->a)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const { return tir::Not(value_.Eval()); }\n\n private:\n  typename TA::Nested value_;\n};\n\ntemplate <typename TA>\ninline PNotExpr<TA> operator!(const Pattern<TA>& value) {\n  return PNotExpr<TA>(value.derived());\n}\n\n// select\n/*!\n * \\brief Pattern select expression.\n * \\tparam TCond The pattern type of the condition.\n * \\tparam TA The pattern type of the true operand.\n * \\tparam TB The pattern type of the false operand.\n */\ntemplate <typename TCond, typename TA, typename TB>\nclass PSelectExpr : public Pattern<PSelectExpr<TCond, TA, TB>> {\n public:\n  PSelectExpr(const TCond& condition, const TA& true_value, const TB& false_value)\n      : condition_(condition), true_value_(true_value), false_value_(false_value) {}\n\n  void InitMatch_() const {\n    condition_.InitMatch_();\n    true_value_.InitMatch_();\n    false_value_.InitMatch_();\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::SelectNode* ptr = node.as<tir::SelectNode>()) {\n      if (!condition_.Match_(ptr->condition)) return false;\n      if (!true_value_.Match_(ptr->true_value)) return false;\n      if (!false_value_.Match_(ptr->false_value)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const {\n    return tir::Select(condition_.Eval(), true_value_.Eval(), false_value_.Eval());\n  }\n\n private:\n  typename TCond::Nested condition_;\n  typename TA::Nested true_value_;\n  typename TB::Nested false_value_;\n};\n\n/*!\n * \\brief Construct a select pattern.\n *\n * \\param condition The condition expression.\n * \\param true_value The value when condition is true.\n * \\param true_value The value when condition is false.\n *\n * \\return The result pattern.\n *\n * \\tparam TCond The pattern type of the condition.\n * \\tparam TA The pattern type of the true operand.\n * \\tparam TB The pattern type of the false operand.\n */\ntemplate <typename TCond, typename TA, typename TB>\ninline PSelectExpr<TCond, TA, TB> select(const Pattern<TCond>& condition,\n                                         const Pattern<TA>& true_value,\n                                         const Pattern<TB>& false_value) {\n  return PSelectExpr<TCond, TA, TB>(condition.derived(), true_value.derived(),\n                                    false_value.derived());\n}\n\n/*!\n * \\brief Pattern cast expression.\n * \\tparam DType The Pattern type of dtype.\n * \\tparam TA The pattern type of the first operand.\n */\ntemplate <typename DType, typename TA>\nclass PCastExpr : public Pattern<PCastExpr<DType, TA>> {\n public:\n  PCastExpr(const DType& dtype, const TA& value) : dtype_(dtype), value_(value) {}\n\n  void InitMatch_() const {\n    dtype_.InitMatch_();\n    value_.InitMatch_();\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::CastNode* ptr = node.as<tir::CastNode>()) {\n      if (!dtype_.Match_(ptr->dtype)) return false;\n      if (!value_.Match_(ptr->value)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const { return tir::Cast(dtype_.Eval(), value_.Eval()); }\n\n private:\n  typename DType::Nested dtype_;\n  typename TA::Nested value_;\n};\n\n/*!\n * \\brief Construct a cast pattern.\n *\n * \\param dtype The target data type, can be PVar<DataType> or PConst<DataType>.\n * \\param value The input type.\n *\n * \\return The result pattern.\n *\n * \\tparam DType The pattern type of type.\n * \\tparam TA The pattern type of value.\n */\ntemplate <typename DType, typename TA>\ninline PCastExpr<DType, TA> cast(const Pattern<DType>& dtype, const Pattern<TA>& value) {\n  return PCastExpr<DType, TA>(dtype.derived(), value.derived());\n}\n\n/*!\n * \\brief Pattern ramp expression.\n * \\tparam TBase The pattern type of the base.\n * \\tparam TStride The pattern type of the stride.\n * \\tparam TLanes The pattern type of the lanes.\n */\ntemplate <typename TBase, typename TStride, typename TLanes>\nclass PRampExpr : public Pattern<PRampExpr<TBase, TStride, TLanes>> {\n public:\n  PRampExpr(const TBase& base, const TStride& stride, const TLanes& lanes)\n      : base_(base), stride_(stride), lanes_(lanes) {}\n\n  void InitMatch_() const {\n    base_.InitMatch_();\n    stride_.InitMatch_();\n    lanes_.InitMatch_();\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::RampNode* ptr = node.as<tir::RampNode>()) {\n      if (!base_.Match_(ptr->base)) return false;\n      if (!stride_.Match_(ptr->stride)) return false;\n      if (!lanes_.Match_(ptr->lanes)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const { return tir::Ramp(base_.Eval(), stride_.Eval(), lanes_.Eval()); }\n\n private:\n  typename TBase::Nested base_;\n  typename TStride::Nested stride_;\n  typename TLanes::Nested lanes_;\n};\n\n/*!\n * \\brief Construct a ramp pattern.\n *\n * \\param base The base pattern.\n * \\param stride The stride pattern.\n * \\param lanes The lanes pattern.\n *\n * \\return The result pattern.\n *\n * \\tparam TBase The pattern type of the base.\n * \\tparam TStride The pattern type of the stride.\n * \\tparam TLanes The pattern type of the lanes.\n */\ntemplate <typename TBase, typename TStride, typename TLanes>\ninline PRampExpr<TBase, TStride, TLanes> ramp(const Pattern<TBase>& base,\n                                              const Pattern<TStride>& stride,\n                                              const Pattern<TLanes>& lanes) {\n  return PRampExpr<TBase, TStride, TLanes>(base.derived(), stride.derived(), lanes.derived());\n}\n\ntemplate <typename TBase>\ninline PRampExpr<TBase, PConstWithTypeLike<TBase>, PConst<int>> ramp(const Pattern<TBase>& base,\n                                                                     int stride, int lanes) {\n  return PRampExpr<TBase, PConstWithTypeLike<TBase>, PConst<int>>(\n      base.derived(), PConstWithTypeLike<TBase>(base.derived(), stride), PConst<int>(lanes));\n}\n\n/*!\n * \\brief Pattern broadcast expression.\n * \\tparam TA The pattern type of the value.\n * \\tparam TLanes The pattern type of the lanes.\n */\ntemplate <typename TA, typename TLanes>\nclass PBroadcastExpr : public Pattern<PBroadcastExpr<TA, TLanes>> {\n public:\n  PBroadcastExpr(const TA& value, const TLanes& lanes) : value_(value), lanes_(lanes) {}\n\n  void InitMatch_() const {\n    value_.InitMatch_();\n    lanes_.InitMatch_();\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::BroadcastNode* ptr = node.as<tir::BroadcastNode>()) {\n      if (!value_.Match_(ptr->value)) return false;\n      if (!lanes_.Match_(ptr->lanes)) return false;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const { return tir::Broadcast(value_.Eval(), lanes_.Eval()); }\n\n private:\n  typename TA::Nested value_;\n  typename TLanes::Nested lanes_;\n};\n\n/*!\n * \\brief Construct a broadcast pattern.\n *\n * \\param value The value pattern.\n * \\param lanes The lanes pattern.\n *\n * \\return The result pattern.\n *\n * \\tparam TA The pattern type of the value.\n * \\tparam TLanes The pattern type of the lanes.\n */\ntemplate <typename TA, typename TLanes>\ninline PBroadcastExpr<TA, TLanes> broadcast(const Pattern<TA>& value,\n                                            const Pattern<TLanes>& lanes) {\n  return PBroadcastExpr<TA, TLanes>(value.derived(), lanes.derived());\n}\n\n// internal namespace\nnamespace detail {\n// implementation details for  CallExpr\ntemplate <bool stop, std::size_t I, typename F>\nstruct tuple_for_each_dispatcher {\n  template <typename TTuple>\n  static void run(F& f, const TTuple& tuple) {  // NOLINT(*)\n    f(I, std::get<I>(tuple));\n    tuple_for_each_dispatcher<(I + 1) == std::tuple_size<TTuple>::value, (I + 1), F>::run(f, tuple);\n  }\n};\n\ntemplate <std::size_t I, typename F>\nstruct tuple_for_each_dispatcher<true, I, F> {\n  template <typename TTuple>\n  static void run(F& f, const TTuple& tuple) {}  // NOLINT(*)\n};\n\ntemplate <typename F, typename TTuple>\ninline void tuple_for_each(F& f, const TTuple& tuple) {  // NOLINT(*)\n  tuple_for_each_dispatcher<std::tuple_size<TTuple>::value == 0, 0, F>::run(f, tuple);\n}\n\nstruct PCallExprInitMatchFunctor {\n  template <typename T>\n  void operator()(size_t i, const T& pattern) const {\n    pattern.InitMatch_();\n  }\n};\n\nstruct PCallExprMatchFunctor {\n  const tir::CallNode* call_;\n  bool matched_{true};\n\n  explicit PCallExprMatchFunctor(const tir::CallNode* call) : call_(call) {}\n\n  template <typename T>\n  void operator()(size_t i, const T& pattern) {\n    matched_ = matched_ && pattern.Match_(call_->args[i]);\n  }\n};\n\nstruct PCallExprEvalArgsFunctor {\n  Array<PrimExpr> args_;\n\n  template <typename T>\n  void operator()(size_t i, const T& pattern) {\n    args_.push_back(pattern.Eval());\n  }\n};\n}  // namespace detail\n\n/*!\n * \\brief Pattern CallExpr expression.\n * \\tparam Op The operator functor class.\n * \\tparam TArgs The arguments.\n * \\note Op functor contains the name of the function and\n *          the implementation of Eval.\n */\ntemplate <typename Op, typename... TArgs>\nclass PCallExpr : public Pattern<PCallExpr<Op, TArgs...>> {\n public:\n  explicit PCallExpr(const TArgs&... args) : args_(args...) {}\n\n  void InitMatch_() const {\n    detail::PCallExprInitMatchFunctor finit;\n    detail::tuple_for_each(finit, args_);\n  }\n\n  bool Match_(const ObjectRef& node) const {\n    if (const tir::CallNode* ptr = node.as<tir::CallNode>()) {\n      if (ptr->args.size() != sizeof...(TArgs)) return false;\n      if (!ptr->op.same_as(Op::GetOp())) return false;\n      detail::PCallExprMatchFunctor fmatch(ptr);\n      detail::tuple_for_each(fmatch, args_);\n      return fmatch.matched_;\n    } else {\n      return false;\n    }\n  }\n\n  PrimExpr Eval() const {\n    detail::PCallExprEvalArgsFunctor feval_args;\n    detail::tuple_for_each(feval_args, args_);\n    return Op::Eval(feval_args.args_);\n  }\n\n private:\n  std::tuple<typename TArgs::Nested...> args_;\n};\n\n// arithemetic intrinsics\n#define TVM_PATTERN_BINARY_INTRIN(FuncName, OpName, IntrinOpName)                         \\\n  struct OpName {                                                                         \\\n    static PrimExpr Eval(Array<PrimExpr> args) {                                          \\\n      return tir::Call(args[0].dtype(), GetOp(), args);                                   \\\n    }                                                                                     \\\n    static const Op& GetOp() { return tir::builtin::IntrinOpName(); }                     \\\n  };                                                                                      \\\n  template <typename TA, typename TB>                                                     \\\n  inline PCallExpr<OpName, TA, TB> FuncName(const Pattern<TA>& a, const Pattern<TB>& b) { \\\n    return PCallExpr<OpName, TA, TB>(a.derived(), b.derived());                           \\\n  }\n\nTVM_PATTERN_BINARY_INTRIN(operator<<, PLeftShiftOp, shift_left);\nTVM_PATTERN_BINARY_INTRIN(operator>>, PRightShiftOp, shift_right);\nTVM_PATTERN_BINARY_INTRIN(operator&, PBitwiseAndOp, bitwise_and);\nTVM_PATTERN_BINARY_INTRIN(operator|, PBitwiseOrOp, bitwise_or);\nTVM_PATTERN_BINARY_INTRIN(operator^, PBitwiseXorOp, bitwise_xor);\n\n// unary intrinsics\n#define TVM_PATTERN_UNARY_INTRIN(FuncName, OpName, IntrinOpName)      \\\n  struct OpName {                                                     \\\n    static PrimExpr Eval(Array<PrimExpr> args) {                      \\\n      return tir::Call(args[0].dtype(), GetOp(), args);               \\\n    }                                                                 \\\n    static const Op& GetOp() { return tir::builtin::IntrinOpName(); } \\\n  };                                                                  \\\n  template <typename TA>                                              \\\n  inline PCallExpr<OpName, TA> FuncName(const Pattern<TA>& a) {       \\\n    return PCallExpr<OpName, TA>(a.derived());                        \\\n  }\n\nTVM_PATTERN_UNARY_INTRIN(operator~, PBitwiseNotOp, bitwise_not);\n\n// if_then_else\nstruct PIfThenElseOp {\n  static PrimExpr Eval(Array<PrimExpr> args) { return tir::Call(args[1].dtype(), GetOp(), args); }\n  static const Op& GetOp() { return tir::builtin::if_then_else(); }\n};\n\n/*!\n * \\brief Construct a if_then_else pattern.\n *\n * \\param cond The condition expression.\n * \\param true_value The value when condition is true.\n * \\param true_value The value when condition is false.\n *\n * \\return The result pattern.\n *\n * \\tparam TCond The pattern type of the condition.\n * \\tparam TA The pattern type of the true operand.\n * \\tparam TB The pattern type of the false operand.\n */\ntemplate <typename TCond, typename TA, typename TB>\ninline PCallExpr<PIfThenElseOp, TCond, TA, TB> if_then_else(const Pattern<TCond>& cond,\n                                                            const Pattern<TA>& true_value,\n                                                            const Pattern<TB>& false_value) {\n  return PCallExpr<PIfThenElseOp, TCond, TA, TB>(cond.derived(), true_value.derived(),\n                                                 false_value.derived());\n}\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_PATTERN_MATCH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/arith/rewrite_simplify.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rewrite_simplify.h\n * \\brief Rewrite-rule based simplification.\n */\n#ifndef TVM_ARITH_REWRITE_SIMPLIFY_H_\n#define TVM_ARITH_REWRITE_SIMPLIFY_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/tir/op.h>\n\n#include <unordered_map>\n#include <vector>\n\n#include \"const_fold.h\"\n#include \"ir_mutator_with_analyzer.h\"\n#include \"pattern_match.h\"\n\nnamespace tvm {\nnamespace arith {\n\nusing namespace tir;\n\n/*!\n * \\brief Rewrite-based simplifier.\n *\n * This class can be inheritated for other simplifiers.\n */\nclass RewriteSimplifier::Impl : public IRMutatorWithAnalyzer {\n public:\n  using IRMutatorWithAnalyzer::VisitExpr_;\n\n  explicit Impl(Analyzer* parent) : IRMutatorWithAnalyzer(parent) {}\n\n  void Update(const Var& var, const PrimExpr& info, bool override_info);\n  PrimExpr VisitExpr_(const AddNode* op) override;\n  PrimExpr VisitExpr_(const SubNode* op) override;\n  PrimExpr VisitExpr_(const MulNode* op) override;\n  PrimExpr VisitExpr_(const DivNode* op) override;\n  PrimExpr VisitExpr_(const ModNode* op) override;\n  PrimExpr VisitExpr_(const FloorDivNode* op) override;\n  PrimExpr VisitExpr_(const FloorModNode* op) override;\n  PrimExpr VisitExpr_(const MinNode* op) override;\n  PrimExpr VisitExpr_(const MaxNode* op) override;\n  PrimExpr VisitExpr_(const EQNode* op) override;\n  PrimExpr VisitExpr_(const NENode* op) override;\n  PrimExpr VisitExpr_(const LTNode* op) override;\n  PrimExpr VisitExpr_(const LENode* op) override;\n  PrimExpr VisitExpr_(const GTNode* op) override;\n  PrimExpr VisitExpr_(const GENode* op) override;\n  PrimExpr VisitExpr_(const AndNode* op) override;\n  PrimExpr VisitExpr_(const OrNode* op) override;\n  PrimExpr VisitExpr_(const NotNode* op) override;\n  PrimExpr VisitExpr_(const SelectNode* op) override;\n  PrimExpr VisitExpr_(const CallNode* op) override;\n  PrimExpr VisitExpr_(const VarNode* op) override;\n  PrimExpr VisitExpr_(const CastNode* op) override;\n  PrimExpr VisitExpr_(const LetNode* op) override;\n\n  std::function<void()> EnterConstraint(const PrimExpr& constraint);\n\n  /*! \\brief Enable an optional extension or extensions\n   *\n   * \\param flags A bitwise OR of all optional extensions that should\n   * be enabled.\n   */\n  void SetEnabledExtensions(Extension flags);\n\n  /*! \\brief Return the currently enabled extensions */\n  Extension GetEnabledExtensions() const;\n\n protected:\n  // counter to record recursive rewrite depth.\n  int recur_depth_{0};\n  // internal variable map\n  std::unordered_map<Var, PrimExpr, ObjectPtrHash, ObjectPtrEqual> var_map_;\n\n  std::vector<PrimExpr> literal_constraints_;\n\n  // Optionally enabled extensions\n  Extension enabled_extensions_{kNone};\n\n  /*! Whether the simplifier is current\n   */\n  bool recursively_visiting_boolean_{false};\n\n  // maximum number of recursion allowed during a single pass.\n  static const constexpr int kMaxRecurDepth = 5;\n\n  /*!\n   * \\brief try to compare x against val.\n   * \\param x The expression to be evaluated.\n   * \\param val The constant value.\n   * \\return comparison result.\n   */\n  CompareResult TryCompare(const PrimExpr& x, int64_t val);\n\n  /*! Try to compare x against y\n   *\n   * \\param x The lhs of the comparison\n   * \\param y The rhs of the comparison\n   * \\return comparison result.\n   */\n  CompareResult TryCompare(const PrimExpr& x, const PrimExpr& y);\n\n  /*!\n   * \\brief Internal function to check whether or not to inline let.\n   * \\param op The let expr.\n   * \\return The inline decision.\n   */\n  bool CanInlineLet(const LetNode* op);\n\n  /*! \\brief Internal function to apply constraints\n   *\n   * Tests whether the expression is known to be true or false based\n   * on existing constraints.  If the expression or its negation\n   * matches a constraint, return the boolean it should be replaced\n   * with.  Otherwise, return false.\n   */\n  Optional<PrimExpr> TryMatchLiteralConstraint(const PrimExpr& expr) const;\n\n  /*! \\brief Rewrite rules for Less Than comparisons\n   *\n   * These are separate from the VisitExpr_(const LTNode*) method, as\n   * they may required from rewrites of LT or LE.\n   */\n  PrimExpr ApplyRewriteRules(LT node);\n\n  /*! \\brief Rewrite rules for Equal comparisons\n   *\n   * These are separate from the VisitExpr_(const EQNode*) method, as\n   * they may required from rewrites of LE or NE.\n   */\n  PrimExpr ApplyRewriteRules(EQ node);\n\n  /*! \\brief Rewrite rules for Equal comparisons\n   *\n   * These are separate from the VisitExpr_(const EQNode*) method, as\n   * they may required from rewrites of LT, LE, or NE.\n   */\n  PrimExpr ApplyRewriteRules(Not node);\n\n private:\n  CompareResult TryCompareUsingKnownInequalities(const PrimExpr& x, const PrimExpr& y);\n  CompareResult TryCompareUsingConstIntBounds(const PrimExpr& x, const PrimExpr y);\n\n  // Whether x >= val\n  bool CanProveGreaterEqual(const PrimExpr& x, int64_t val) {\n    return analyzer_->CanProveGreaterEqual(x, val);\n  }\n  // Whether x < val\n  bool CanProveLess(const PrimExpr& x, int64_t val) { return analyzer_->CanProveLess(x, val); }\n  // Whether x == val\n  bool CanProveEqual(const PrimExpr& x, int64_t val) {\n    // TODO(tqchen) refer back to super-analyzer.\n    return TryCompare(x, val) == CompareResult::kEQ;\n  }\n\n  // Recursive rewrite x\n  // we limit maximum depth of recursive rewrite allowed to\n  // avoid infinite loop\n  PrimExpr RecursiveRewrite(const PrimExpr& x) {\n    if (recur_depth_ >= kMaxRecurDepth) return x;\n    ++recur_depth_;\n    PrimExpr res = this->VisitExpr(x);\n    --recur_depth_;\n    return res;\n  }\n\n  template <typename TA>\n  PConstWithTypeLike<TA> ZeroWithTypeLike(const Pattern<TA>& pattern) {\n    return PConstWithTypeLike<TA>(pattern.derived(), 0);\n  }\n\n  template <typename TA>\n  PConstWithTypeLike<TA> OneWithTypeLike(const Pattern<TA>& pattern) {\n    return PConstWithTypeLike<TA>(pattern.derived(), 1);\n  }\n};\n\n}  // namespace arith\n}  // namespace tvm\n#endif  // TVM_ARITH_REWRITE_SIMPLIFY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/auto_scheduler/search_policy/empty_policy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/search_policy/empty_policy.h\n * \\brief A simple example of the search policy which always returns the initial naive schedule\n * (state).\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_POLICY_EMPTY_POLICY_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_POLICY_EMPTY_POLICY_H_\n\n#include <tvm/auto_scheduler/loop_state.h>\n#include <tvm/auto_scheduler/measure.h>\n#include <tvm/auto_scheduler/search_policy.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*!\n * \\brief A simple example of the search policy which always returns the initial naive schedule\n * (state).\n * The key implementation for this structure is `Search()`, check `empty_policy.cc` for more\n * details.\n */\nclass EmptyPolicyNode : public SearchPolicyNode {\n public:\n  State Search(int num_measure_trials, int early_stopping, int num_measures_per_round,\n               ProgramMeasurer measurer) final;\n\n  std::pair<Array<MeasureInput>, Array<MeasureResult>> ContinueSearchOneRound(\n      int num_measure, ProgramMeasurer measurer) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.EmptyPolicy\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(EmptyPolicyNode, SearchPolicyNode);\n\n private:\n  /*!\n   * \\brief Use a sub function to generate several candidate states in each search round.\n   * \\returns The generated states\n   */\n  Array<State> SearchOneRound();\n};\n\n/*!\n * \\brief Managed reference to EmptyPolicyNode.\n * \\sa EmptyPolicyNode\n */\nclass EmptyPolicy : public SearchPolicy {\n public:\n  explicit EmptyPolicy(SearchTask task, Optional<Array<SearchCallback>> init_search_callbacks);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(EmptyPolicy, SearchPolicy, EmptyPolicyNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_POLICY_EMPTY_POLICY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/auto_scheduler/search_policy/sketch_policy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/search_policy/sketch_policy.h\n * \\brief This search policy constructs a search space according to the compute declaration.\n * It then randomly samples programs from the search space and uses evolutionary search with a\n * learned cost model to fine tune the sampled programs.\n * The final optimized programs are sent to actual hardware for measurement.\n * The above process is repeated until the auto-scheduler runs out of time budget.\n *\n * Reference:\n * L. Zheng, C. Jia, M. Sun, Z. Wu, C. Yu, et al. \"Ansor : Generating High-Performance Tensor\n * Programs for Deep Learning.\" (OSDI 2020).\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_H_\n\n#include <tvm/auto_scheduler/cost_model.h>\n#include <tvm/auto_scheduler/search_policy.h>\n\n#include <memory>\n#include <set>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"sketch_policy_rules.h\"\n#include \"utils.h\"\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*! \\brief String keys used in parameter map of SketchPolicy. */\nstruct SketchParamKey {\n  /*! \\brief Always allocate this percentage of measurements to random sampled states. */\n  static constexpr const char* eps_greedy = \"eps_greedy\";\n  /*! \\brief Retry several times if SearchOneRound gets no valid state. */\n  static constexpr const char* empty_retry_count = \"retry_search_one_round_on_empty\";\n\n  struct SampleInitPopulation {\n    /*! \\brief The minimal size of valid population in the initial sampling. */\n    static constexpr const char* min_population = \"sample_init_min_population\";\n    /*! \\brief The maximum percentage of measured states in the initial sampling. */\n    static constexpr const char* use_measured_ratio = \"sample_init_use_measured_ratio\";\n  };\n\n  struct EvolutionarySearch {\n    /*! \\brief The population size of evolutionary search. */\n    static constexpr const char* population = \"evolutionary_search_population\";\n    /*! \\brief The number of iterations performed by generic algorithm.*/\n    static constexpr const char* num_iters = \"evolutionary_search_num_iters\";\n    /*! \\brief The mutation probability.*/\n    static constexpr const char* mutation_prob = \"evolutionary_search_mutation_prob\";\n  };\n\n  struct MultiLevelTiling {\n    /*! \\brief The structure of multi-level tiling for CPU. */\n    static constexpr const char* cpu_structure = \"cpu_multi_level_tiling_structure\";\n    /*! \\brief The structure of multi-level tiling for GPU. */\n    static constexpr const char* gpu_structure = \"gpu_multi_level_tiling_structure\";\n  };\n\n  /*! \\brief The max inner most split factor. */\n  static constexpr const char* max_innermost_split_factor = \"max_innermost_split_factor\";\n  /*! \\brief The max vectorize size. */\n  static constexpr const char* max_vectorize_size = \"max_vectorize_size\";\n  /*! \\brief Whether disable compute location changing. */\n  static constexpr const char* disable_change_compute_location = \"disable_change_compute_location\";\n};\n\nclass SketchPolicy;\n\n/*!\n * \\brief The search policy that searches in a hierarchical search space defined by sketches.\n * The policy randomly samples programs from the space defined by sketches\n * and use evolutionary search to  fine-tune them.\n */\nclass SketchPolicyNode : public SearchPolicyNode {\n public:\n  /*! \\brief The cost model to estimate the complete schedules. */\n  CostModel program_cost_model;\n  /*! \\brief The parameters map for this search policy. */\n  Map<String, ObjectRef> params;\n  /*! \\brief The rules to generate sketches. */\n  std::vector<SketchGenerationRule*> sketch_rules;\n  /*! \\brief The rules to generate initial population. */\n  std::vector<PopulationGenerationRule*> init_rules;\n  /*! \\brief The rules to mutate states in the evolutionary search. */\n  std::vector<std::shared_ptr<PopulationMutationRule>> mutation_rules;\n  /*! \\brief Random generator. */\n  std::mt19937 rand_gen;\n  /*! \\brief Memorize split space for Split. */\n  SplitFactorizationMemo split_memo;\n\n  State Search(int num_measure_trials, int early_stopping, int num_measures_per_round,\n               ProgramMeasurer measurer) final;\n\n  std::pair<Array<MeasureInput>, Array<MeasureResult>> ContinueSearchOneRound(\n      int num_measure, ProgramMeasurer measurer) final;\n\n  /*!\n   * \\brief Generate sketches.\n   * \\return The generated sketches(states).\n   */\n  Array<State> GenerateSketches();\n\n  /*!\n   * \\brief Sample the init population.\n   * \\param sketches The initial sketches for the sampled population\n   * \\return The generated states (the initial population).\n   */\n  Array<State> SampleInitPopulation(const Array<State>& sketches);\n\n  /*!\n   * \\brief Perform evolutionary search.\n   * \\param init_populations The states generated from init population.\n   * \\param out_size The number of expected output states.\n   * \\return The generated states after evolutionary search.\n   */\n  Array<State> EvolutionarySearch(const Array<State>& init_populations, int out_size);\n\n  static constexpr const char* _type_key = \"auto_scheduler.SketchPolicy\";\n\n  TVM_DECLARE_FINAL_OBJECT_INFO(SketchPolicyNode, SearchPolicyNode);\n\n private:\n  /*!\n   * \\brief Run one round of the search pipeline.\n   * \\param num_random_states Number of states that are picked randomly, this is used for\n   * eps-greedy policy.\n   * \\param random_states The picked random states, used as one of the output of this function.\n   * \\return The best several states generated in this search round.\n   */\n  Array<State> SearchOneRound(int num_random_states, Array<State>* random_states = nullptr);\n\n  /*!\n   * \\brief Pick states from best states and random states with eps-greedy policy.\n   * \\param best_states States picked by cost model.\n   * \\param random_states States picked randomly.\n   * \\param remaining_n_trials The remaining number of states need to be generated.\n   * \\return The generated states to be measured, wrapped in MeasureInput.\n   */\n  Array<MeasureInput> PickStatesWithEpsGreedy(const Array<State>& best_states,\n                                              const Array<State>& random_states,\n                                              int remaining_n_trials);\n\n  /*! \\brief The number of states to measure per iteration. */\n  int num_measure_per_iter_;\n\n  /*! \\brief The cached sketches */\n  Array<State> sketch_cache_;\n\n  /*! \\brief The minimul output population of SampleInitPopulation */\n  int sample_init_min_pop_;\n\n  friend class SketchPolicy;\n};\n\n/*!\n * \\brief Managed reference to SketchPolicyNode.\n * \\sa SketchPolicyNode\n */\nclass SketchPolicy : public SearchPolicy {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param task  The SearchTask for the computation declaration.\n   * \\param program_cost_model The cost model for complete programs.\n   * \\param params The parameters map for this search process.\n   * \\param seed The random seed of this search process.\n   * \\param verbose Verbose level. 0 for silent, 1 to output information during schedule\n   * search.\n   * \\param init_search_callbacks SearchCallback to be called before schedule search.\n   */\n  SketchPolicy(SearchTask task, CostModel program_cost_model, Map<String, ObjectRef> params,\n               int seed, int verbose, Optional<Array<SearchCallback>> init_search_callbacks);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(SketchPolicy, SearchPolicy, SketchPolicyNode);\n};\n\n/*! \\brief Pre-search callback function to load custom rules for sketch generation */\nclass PreloadCustomSketchRuleNode : public SearchCallbackNode {\n public:\n  /*! \\brief The condition check function of this rule. */\n  PackedFunc meet_condition_func;\n  /*! \\brief The apply function of this rule. */\n  PackedFunc apply_func;\n  /*! \\brief The name of this rule. */\n  String rule_name;\n\n  void Callback(SearchPolicyNode* policy) final;\n\n  static constexpr const char* _type_key = \"auto_scheduler.PreloadCustomSketchRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PreloadCustomSketchRuleNode, SearchCallbackNode);\n};\n\n/*!\n * \\brief Managed reference to PreloadCustomSketchRuleNode.\n * \\sa PreloadCustomSketchRuleNode\n */\nclass PreloadCustomSketchRule : public SearchCallback {\n public:\n  /*!\n   * \\brief The constructor.\n   * \\param meet_condition_func The condition check function of this rule.\n   * \\param apply_func The apply function of this rule.\n   * \\param rule_name The name of this rule.\n   */\n  PreloadCustomSketchRule(PackedFunc meet_condition_func, PackedFunc apply_func, String rule_name);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(PreloadCustomSketchRule, SearchCallback,\n                                        PreloadCustomSketchRuleNode);\n};\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/auto_scheduler/search_policy/sketch_policy_rules.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/search_policy/sketch_policy_rules.h\n * \\brief Rules for generating the sketches, sampling the initial population, and mutating the\n * population in SketchPolicy.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_RULES_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_RULES_H_\n\n#include <tvm/auto_scheduler/loop_state.h>\n#include <tvm/auto_scheduler/search_task.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"utils.h\"\n\nnamespace tvm {\nnamespace auto_scheduler {\n\nclass SketchPolicyNode;\n\n/********** Sketch Generation Rule **********/\n\n/*! \\brief The base class for derivation rules used in the sketch generation. */\nclass SketchGenerationRule {\n public:\n  /*! \\brief Result enumeration of the condition function. */\n  enum class ConditionKind : int {\n    /*! \\brief Skip this rule and continue to try the next rules. */\n    kSkip = 0,\n    /*! \\brief Apply this rule and continue to try the next rules. */\n    kApply = 1,\n    /*! \\brief Apply this rule and skip the rest rules. */\n    kApplyAndSkipRest = 2\n  };\n\n  /*!\n   * \\brief Condition check function of this rule.\n   * \\param policy The SketchPolicyNode of this rule, some information may be used during\n   * the condition checking.\n   * \\param state The original state to be checked.\n   * \\param stage_id The index of the stage to process this condition check.\n   * \\return The condition check result of this rule.\n   */\n  virtual ConditionKind MeetCondition(const SketchPolicyNode& policy, const State& state,\n                                      int stage_id) const = 0;\n\n  /*!\n   * \\brief Apply function of this rule.\n   * \\param policy The SketchPolicyNode of this rule, some information may be used during\n   * the rule applying.\n   * \\param state The original state to apply this rule.\n   * \\param stage_id The index of the next stage to apply this rule.\n   * \\return The state after applying this rule, and index of the next stage.\n   */\n  virtual std::vector<std::pair<State, int>> Apply(const SketchPolicyNode& policy,\n                                                   const State& state, int stage_id) const = 0;\n\n  /*!\n   * \\brief Get the name of this rule.\n   * \\return A string of the rule name.\n   */\n  virtual std::string GetRuleName() const = 0;\n};\n\n#define DEFINE_SKETCH_GENERATION_RULE(rule_name)                                                 \\\n  class rule_name : public SketchGenerationRule {                                                \\\n   public:                                                                                       \\\n    ConditionKind MeetCondition(const SketchPolicyNode& policy, const State& state,              \\\n                                int stage_id) const final;                                       \\\n    std::vector<std::pair<State, int>> Apply(const SketchPolicyNode& policy, const State& state, \\\n                                             int stage_id) const final;                          \\\n    std::string GetRuleName() const final { return #rule_name; }                                 \\\n  };\n\n/*! \\brief The rule that simply skips the current stage. It returns an unchanged state and move to\n * the next stage. */\nDEFINE_SKETCH_GENERATION_RULE(RuleSkipStage);\n\n/*! \\brief The rule that inlines simple elementwise ops.\n * \\note This rule only inlines the strictly inlineable stages. Stages marked as not strictly\n * inlineable will have a chance to try different compute at location in InitPopulation later.\n */\nDEFINE_SKETCH_GENERATION_RULE(RuleAlwaysInline);\n\n/*! \\brief The rule that performs multi-level tiling. */\nDEFINE_SKETCH_GENERATION_RULE(RuleMultiLevelTiling);\n\n/*! \\brief The rule that performs multi-level tiling and fuses later consumers. */\nDEFINE_SKETCH_GENERATION_RULE(RuleMultiLevelTilingWithFusion);\n\n/*! \\brief The rule that adds a cache read stage. Mainly used for GPU cooperative fetching,\n * Currently only support 1 to 1 match cache read. */\nDEFINE_SKETCH_GENERATION_RULE(RuleAddCacheRead);\n\n/*! \\brief The rule that adds a cache write stage. */\nDEFINE_SKETCH_GENERATION_RULE(RuleAddCacheWrite);\n\n/*! \\brief The rule that adds rfactor stage. */\nDEFINE_SKETCH_GENERATION_RULE(RuleAddRfactor);\n\n/*! \\brief The rule that deals with compute ops that perform \"fake reduction\" with const tensors.\n * This kind of op comes from winograd transformation. */\nDEFINE_SKETCH_GENERATION_RULE(RuleSimplifyComputeWithConstTensor);\n\n/*! \\brief The rule that use cross thread reduction for GPU. */\nDEFINE_SKETCH_GENERATION_RULE(RuleCrossThreadReduction);\n\n/*! \\brief Handle special cases in Winograd transformation for GPU. We need to change the compute\n * location of the producers of compute ops that perform \"fake reduction\" with const tensors. */\nDEFINE_SKETCH_GENERATION_RULE(RuleSpecialComputeLocationGPU);\n\n/*! \\brief The rule that allows users to generate custom sketches. */\nclass RuleCustomSketch : public SketchGenerationRule {\n public:\n  RuleCustomSketch(PackedFunc meet_condition_func, PackedFunc apply_func,\n                   String rule_name = \"CustomSketchRule\")\n      : meet_condition_func_(std::move(meet_condition_func)),\n        apply_func_(std::move(apply_func)),\n        rule_name_(std::move(rule_name)) {}\n\n  ConditionKind MeetCondition(const SketchPolicyNode& policy, const State& state,\n                              int stage_id) const final;\n\n  std::vector<std::pair<State, int>> Apply(const SketchPolicyNode& policy, const State& state,\n                                           int stage_id) const final;\n\n  std::string GetRuleName() const final { return rule_name_; }\n\n private:\n  PackedFunc meet_condition_func_;\n  PackedFunc apply_func_;\n  String rule_name_;\n};\n\n/********** Init Population **********/\n\n/*! \\brief The base class for rules used to annotate the sketches to get the initial population. */\nclass PopulationGenerationRule {\n public:\n  /*! \\brief Result enumeration of the apply function. */\n  enum class ResultKind : int { kValid = 0, kInvalid = 1 };\n\n  /*!\n   * \\brief Apply function of this rule.\n   * \\param policy The SketchPolicyNode of this rule, some member may get changed during the\n   * rule applying. (e.g. random number generator)\n   * \\param state The state to apply this rule, update inplace.\n   * \\return The result of this rule, indicate if there's any valid state generated.\n   */\n  virtual ResultKind Apply(SketchPolicyNode* policy, State* state,\n                           std::mt19937* rand_gen) const = 0;\n\n  /*! \\brief The deconstructor */\n  virtual ~PopulationGenerationRule() = default;\n};\n\n// A helper to define population initialization rules\n#define DEFINE_INIT_POPULATION_RULE(rule_name)                                                    \\\n  class rule_name : public PopulationGenerationRule {                                             \\\n   public:                                                                                        \\\n    ResultKind Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const final; \\\n  };\n\n/*! \\brief The rule that fills the incomplete SplitSteps. */\nDEFINE_INIT_POPULATION_RULE(InitFillTileSize);\n\n/*! \\brief The rule that randomly changes the computation location for some stages that do not\n * need tiling and are not strictly inlineable(e.g. data padding). */\nDEFINE_INIT_POPULATION_RULE(InitChangeComputeLocation);\n\n/*! \\brief The rule that annotates parallel for CPU. */\nDEFINE_INIT_POPULATION_RULE(InitParallel);\n\n/*! \\brief The rule that annotates unroll. */\nDEFINE_INIT_POPULATION_RULE(InitUnroll);\n\n/*! \\brief The rule that annotates vectorization. */\nDEFINE_INIT_POPULATION_RULE(InitVectorization);\n\n/*! \\brief The rule that annotates thread binding for GPU. */\nDEFINE_INIT_POPULATION_RULE(InitThreadBind);\n\n/********** Mutation **********/\n\n/*! \\brief The base class for mutation rules used in the evolutionary search. */\nclass PopulationMutationRule : public PopulationGenerationRule {\n public:\n  /* \\brief The constructor\n   * \\param selection_weight the probabiliy of applying this rule is\n   *        proportional to this weight\n   */\n  explicit PopulationMutationRule(double selection_weight) : weight(selection_weight) {}\n\n  /* \\brief The weight of this rule */\n  double weight;\n};\n\n// A helper to define mutation rules used in the evolutionary search\n#define DEFINE_MUTATE_POPULATION_RULE(rule_name)                                                  \\\n  class rule_name : public PopulationMutationRule {                                               \\\n   public:                                                                                        \\\n    explicit rule_name(double weight) : PopulationMutationRule(weight) {}                         \\\n    ResultKind Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const final; \\\n  };\n\n/*! \\brief The rule that mutates tile size by randomly dividing a tile size by a factor\n    and multipling it to another tile size. */\nDEFINE_MUTATE_POPULATION_RULE(MutateTileSize);\n\n/*! \\brief The rule that mutates the number of fused outer iterators annotated by parallel. */\nDEFINE_MUTATE_POPULATION_RULE(MutateParallel);\n\n/*! \\brief The rule that randomly changes the computation location for some stages that do not\n * need tiling and are not strictly inlineable(e.g. data padding). */\nDEFINE_MUTATE_POPULATION_RULE(MutateComputeLocation);\n\n/*! \\brief The rule that mutates the value of a randomly selected auto unroll pragma step. */\nDEFINE_MUTATE_POPULATION_RULE(MutateAutoUnroll);\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_POLICY_SKETCH_POLICY_RULES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/auto_scheduler/search_policy/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/search_policy/utils.h\n * \\brief Common utilities for search policies.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_SEARCH_POLICY_UTILS_H_\n#define TVM_AUTO_SCHEDULER_SEARCH_POLICY_UTILS_H_\n\n#include <dmlc/common.h>\n#include <tvm/auto_scheduler/loop_state.h>\n#include <tvm/auto_scheduler/search_policy.h>\n#include <tvm/ir/expr.h>\n#include <tvm/te/operation.h>\n\n#include <algorithm>\n#include <condition_variable>\n#include <set>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../utils.h\"\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/*! \\brief Return whether the search task is targeting a CPU. */\ninline bool IsCPUTask(const SearchTask& task) {\n  return (task)->target->GetTargetDeviceType() == kDLCPU;\n}\n\n/*! \\brief Return whether the search task is targeting a GPU. */\ninline bool IsGPUTask(const SearchTask& task) {\n  int device_type = (task)->target->GetTargetDeviceType();\n  return device_type == kDLCUDA || device_type == kDLOpenCL || device_type == kDLVulkan ||\n         device_type == kDLMetal || device_type == kDLROCM || device_type == kOpenGL;\n}\n\n/*! \\brief Return whether the search task is targeting a CUDA GPU. */\ninline bool IsCUDATask(const SearchTask& task) {\n  return (task)->target->GetTargetDeviceType() == kDLCUDA;\n}\n\n/*! \\brief Return whether the search task is targeting a OpenCL GPU. */\ninline bool IsOpenCLTask(const SearchTask& task) {\n  return (task)->target->GetTargetDeviceType() == kDLOpenCL;\n}\n\n/*! \\brief Argsort. Order: largest to smallest */\ntemplate <typename T>\ninline std::vector<int> Argsort(const std::vector<T>& scores) {\n  std::vector<int> index;\n  index.reserve(scores.size());\n  for (size_t i = 0; i < scores.size(); ++i) {\n    index.push_back(i);\n  }\n  auto cmp = [&scores](int l, int r) { return scores[l] > scores[r]; };\n  std::sort(index.begin(), index.end(), cmp);\n  return index;\n}\n\n/*! \\brief Convert operation to stage id. */\ninline int OperationToStage(const te::Operation& op, const State& state) {\n  for (size_t i = 0; i < state->stages.size(); ++i) {\n    if (op == state->stages[i]->op) {\n      return i;\n    }\n  }\n  LOG(FATAL) << \"Cannot find op: \" << op;\n  return -1;\n}\n\n/********** Get Parameters **********/\n\n/*! \\brief Get an integer from a tvm str Map. */\ninline int GetIntParam(const Map<String, ObjectRef>& attr_dict, const std::string& key) {\n  ICHECK_GT(attr_dict.count(key), 0) << \"Cannot find key: \\\"\" << key << \"\\\" in \" << attr_dict;\n  auto pint = attr_dict[key].as<IntImmNode>();\n  ICHECK(pint != nullptr);\n  return pint->value;\n}\n\n/*! \\brief Get a double from a tvm str Map. */\ninline double GetDoubleParam(const Map<String, ObjectRef>& attr_dict, const std::string& key) {\n  ICHECK_GT(attr_dict.count(key), 0) << \"Cannot find key: \\\"\" << key << \"\\\" in \" << attr_dict;\n  auto pdouble = attr_dict[key].as<FloatImmNode>();\n  ICHECK(pdouble != nullptr);\n  return pdouble->value;\n}\n\n/*! \\brief Get a string from a tvm str Map. */\ninline std::string GetStringParam(const Map<String, ObjectRef>& attr_dict, const std::string& key) {\n  ICHECK_GT(attr_dict.count(key), 0) << \"Cannot find key: \\\"\" << key << \"\\\" in \" << attr_dict;\n  const auto& target = attr_dict[key];\n  if (auto pstr = target.as<StringImmNode>()) {\n    return pstr->value;\n  }\n  auto pstr = target.as<StringObj>();\n  ICHECK(pstr != nullptr);\n  return pstr->data;\n}\n\n/*! \\brief Get a iterator name set from a tvm str Map. */\ninline std::set<std::string> GetIterNameSetParam(const Map<String, ObjectRef>& attr_dict,\n                                                 const std::string& key) {\n  std::set<std::string> ret;\n  ICHECK_GT(attr_dict.count(key), 0) << \"Cannot find key: \\\"\" << key << \"\\\" in \" << attr_dict;\n  auto names = attr_dict[key].as<ArrayNode>();\n  ICHECK(names != nullptr);\n  for (const auto& name : *names) {\n    ret.insert(name.as<StringObj>()->data);\n  }\n  return ret;\n}\n\n/********** Checks with ComputeDAG **********/\n\n/*! \\brief Return whether an op is strictly-inlineable. */\ninline bool IsStrictlyInlineable(const SearchTask& task, const State& state, int stage_id) {\n  if (state->current_compute_dag) {\n    return state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.IsStrictlyInlineable(\n        state->stages[stage_id]->op);\n  } else {\n    return task->compute_dag->access_analyzer.IsStrictlyInlineable(state->stages[stage_id]->op);\n  }\n}\n\n/*! \\brief Return whether an op is an output op. */\ninline bool IsOutputOp(const SearchTask& task, const State& state, int stage_id) {\n  if (state->current_compute_dag) {\n    return state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.IsOutput(\n        state->stages[stage_id]->op);\n  } else {\n    return task->compute_dag->access_analyzer.IsOutput(state->stages[stage_id]->op);\n  }\n}\n\n/*! \\brief Return whether an op needs multi level tiling. */\ninline bool NeedsMultilevelTiling(const SearchTask& task, const State& state, int stage_id) {\n  if (state->current_compute_dag) {\n    return state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.NeedsMultiLevelTiling(\n        state->stages[stage_id]->op);\n  } else {\n    return task->compute_dag->access_analyzer.NeedsMultiLevelTiling(state->stages[stage_id]->op);\n  }\n}\n\n/*! \\brief Get all consumers for a stage. This function propagates the relation for inlined ops. */\ninline std::set<int> GetConsumers(const SearchTask& task, const State& state, int stage_id) {\n  std::unordered_set<te::Operation, ObjectHash, ObjectEqual> consumers;\n  std::set<int> ret;\n\n  if (state->current_compute_dag) {\n    consumers = state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.GetConsumers(\n        state, state->stages[stage_id]->op);\n  } else {\n    consumers = task->compute_dag->access_analyzer.GetConsumers(state, state->stages[stage_id]->op);\n  }\n\n  for (const auto& op : consumers) {\n    ret.insert(OperationToStage(op, state));\n  }\n  return ret;\n}\n\n/*! \\brief Check if a stage has single consumer or all of its consumers share a common root, return\n * the target consumer root or -1. */\ninline int GetSingleConsumerId(const SearchTask& task, const State& state, int stage_id) {\n  const std::set<int>& consumers = GetConsumers(task, state, stage_id);\n  if (consumers.empty()) {\n    return -1;\n  }\n\n  if (consumers.size() == 1) {\n    return *consumers.begin();\n  } else {\n    // Check all consumers share a common root\n    int common_root_id = -1;\n    bool mismatch = false;\n    for (const auto& consumer_stage_id : consumers) {\n      int root_id = -1;\n      if (state->stages[consumer_stage_id]->compute_at == ComputeAtKind::kRoot) {\n        root_id = consumer_stage_id;\n      } else if (state->stages[consumer_stage_id]->compute_at == ComputeAtKind::kIter) {\n        root_id = state->attach_map->stage_to_attach_iter.at(consumer_stage_id).first;\n      } else {\n        LOG(FATAL) << \"Invalid case\";\n      }\n\n      if (common_root_id == -1) {\n        common_root_id = root_id;\n      } else {\n        if (common_root_id != root_id) {\n          mismatch = true;\n          break;\n        }\n      }\n    }\n\n    return mismatch ? -1 : common_root_id;\n  }\n}\n\n/*! \\brief Get all producers for a stage. This function propagates the relation for inlined ops. */\ninline std::set<int> GetProducers(const SearchTask& task, const State& state, int stage_id) {\n  std::unordered_set<te::Operation, ObjectHash, ObjectEqual> producers;\n  std::set<int> ret;\n\n  if (state->current_compute_dag) {\n    producers = state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.GetProducers(\n        state, state->stages[stage_id]->op);\n  } else {\n    producers = task->compute_dag->access_analyzer.GetProducers(state, state->stages[stage_id]->op);\n  }\n\n  for (const auto& op : producers) {\n    ret.insert(OperationToStage(op, state));\n  }\n  return ret;\n}\n\n/*! \\brief Get all producers for a stage. This function DOES NOT propagates the relation for\n * inlined ops. */\ninline std::set<int> GetDirectProducers(const SearchTask& task, const State& state, int stage_id) {\n  std::unordered_set<te::Operation, ObjectHash, ObjectEqual> producers;\n  std::set<int> ret;\n\n  if (state->current_compute_dag) {\n    producers = state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.GetDirectProducers(\n        state->stages[stage_id]->op);\n  } else {\n    producers = task->compute_dag->access_analyzer.GetDirectProducers(state->stages[stage_id]->op);\n  }\n\n  for (const auto& op : producers) {\n    ret.insert(OperationToStage(op, state));\n  }\n  return ret;\n}\n\n/*! \\brief Get the number of common outer iterators. This function propagates the relation for\n * chains with multiple ops. */\ninline int GetNumCommonOuterIterator(const SearchTask& task, const State& state, int stage_id,\n                                     int target_stage_id) {\n  if (state->current_compute_dag) {\n    return state->current_compute_dag.as<ComputeDAGNode>()\n        ->access_analyzer.GetNumCommonOuterIterator(state->stages[stage_id]->op,\n                                                    state->stages[target_stage_id]->op);\n  } else {\n    return task->compute_dag->access_analyzer.GetNumCommonOuterIterator(\n        state->stages[stage_id]->op, state->stages[target_stage_id]->op);\n  }\n}\n\n/*! \\brief Return whether two ops are elementwise-matched. */\ninline bool ElementwiseMatch(const SearchTask& task, const State& state, int stage_id,\n                             int target_stage_id) {\n  const auto& op = state->stages[stage_id]->op;\n  const auto& target_op = state->stages[target_stage_id]->op;\n  if (state->current_compute_dag) {\n    return state->current_compute_dag.as<ComputeDAGNode>()->access_analyzer.ElementWiseMatch(\n        op, target_op);\n  } else {\n    return task->compute_dag->access_analyzer.ElementWiseMatch(op, target_op);\n  }\n}\n\n/********** Get informations from Stage/Iterator **********/\n\n/*! \\brief Return the extent of an iterator. */\ninline int64_t GetExtent(const Iterator& it) {\n  if (it->range.defined()) {\n    if (auto pint = it->range->extent.as<IntImmNode>()) {\n      return pint->value;\n    }\n  }\n  return -1;\n}\n\n/*! \\brief Compute the product of lengths of all space iters and all reduce iters, respectively. */\ninline std::pair<int64_t, int64_t> GetCumulativeSpaceAndReductionLength(const Stage& stage) {\n  int64_t cum_space_len = 1, cum_reduce_len = 1;\n  for (const auto& iter : stage->iters) {\n    if (iter->iter_kind == IteratorKind::kSpatial) {\n      cum_space_len *= GetExtent(iter);\n    } else if (iter->iter_kind == IteratorKind::kReduction) {\n      cum_reduce_len *= GetExtent(iter);\n    }\n  }\n  return std::make_pair(cum_space_len, cum_reduce_len);\n}\n\n/*! \\brief Return whether this stage needs rfactor. */\ninline bool NeedsRfactor(const SearchTask& task, const State& state, int stage_id) {\n  const auto& op = state->stages[stage_id]->op;\n  if (op->IsInstance<te::ComputeOpNode>()) {\n    // Compute the product of lengths of all space iters and all reduce iters\n    int cum_space_len, cum_reduce_len;\n    std::tie(cum_space_len, cum_reduce_len) =\n        GetCumulativeSpaceAndReductionLength(state->stages[stage_id]);\n\n    if (NeedsMultilevelTiling(task, state, stage_id)) {\n      // Do not use rfactor if we have enough parallelism on space iters\n      if (cum_space_len > cum_reduce_len || cum_space_len > task->hardware_params->num_cores * 16) {\n        return false;\n      } else {\n        return true;\n      }\n    } else if (cum_reduce_len > 1) {\n      // Always try rfactor for reduction ops\n      return cum_reduce_len > task->hardware_params->num_cores;\n    }\n  }\n\n  return false;\n}\n\n/*! \\brief Return whether the stage has reduce iterators. */\ninline bool HasReduceIter(const Stage& stage) {\n  for (const auto& iter : stage->iters) {\n    if (iter->iter_kind != IteratorKind::kSpatial) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the stage has specific annotated iterators. */\ninline bool HasAnnotatedIter(const Stage& stage, IteratorAnnotation type) {\n  for (const auto& iter : stage->iters) {\n    if (iter->annotation == type) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the stage has only one consumer and they are elementwise-matched. */\ninline bool HasSingleElementwiseMatchedConsumer(const SearchTask& task, const State& state,\n                                                int stage_id, int* target_stage_id = nullptr) {\n  // Temporal object to be used if the input pointer is nullptr\n  int temp_target_stage_id;\n  if (target_stage_id == nullptr) {\n    target_stage_id = &temp_target_stage_id;\n  }\n  const std::set<int>& consumers = GetConsumers(task, state, stage_id);\n  if (consumers.size() == 1) {\n    *target_stage_id = *consumers.begin();\n    if (ElementwiseMatch(task, state, stage_id, *target_stage_id) &&\n        (!(HasReduceIter(state->stages[stage_id]) &&\n           HasReduceIter(state->stages[*target_stage_id]))) &&\n        (!StrEndsWith(state->stages[*target_stage_id]->op->name, \".shared\"))) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the step changes the number of stages */\ninline bool IsStageNumberChangingStep(const Step& step) {\n  return step->IsInstance<CacheWriteStepNode>() || step->IsInstance<CacheReadStepNode>() ||\n         step->IsInstance<RfactorStepNode>();\n}\n\n/*! \\brief Return whether the state does cache_read for stage_id. */\ninline bool HasCacheReadStage(const State& s, int stage_id) {\n  for (int i = static_cast<int>(s->transform_steps.size()) - 1; i >= 0; --i) {\n    if (auto ps = s->transform_steps[i].as<CacheReadStepNode>()) {\n      if (stage_id == ps->stage_id) {\n        return true;\n      }\n    }\n\n    if (IsStageNumberChangingStep(s->transform_steps[i])) {\n      if (stage_id > s->transform_steps[i]->stage_id) {\n        stage_id--;\n      }\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the state does cache_write for stage_id. */\ninline bool HasCacheWriteStage(const State& s, int stage_id) {\n  for (int i = static_cast<int>(s->transform_steps.size()) - 1; i >= 0; --i) {\n    if (auto ps = s->transform_steps[i].as<CacheWriteStepNode>()) {\n      if (stage_id == ps->stage_id) {\n        return true;\n      }\n    }\n\n    if (IsStageNumberChangingStep(s->transform_steps[i])) {\n      if (stage_id > s->transform_steps[i]->stage_id) {\n        stage_id--;\n      }\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the state does rfactor for stage_id. */\ninline bool HasRfactorStage(const State& s, int stage_id) {\n  for (int i = static_cast<int>(s->transform_steps.size()) - 1; i >= 0; --i) {\n    if (auto ps = s->transform_steps[i].as<RfactorStepNode>()) {\n      if (stage_id == ps->stage_id) {\n        return true;\n      }\n    }\n\n    if (IsStageNumberChangingStep(s->transform_steps[i])) {\n      if (stage_id > s->transform_steps[i]->stage_id) {\n        stage_id--;\n      }\n    }\n  }\n  return false;\n}\n\n/*! \\brief Return whether the stage does cross thread reduction. */\ninline bool HasCrossThreadReduction(const State& state, int stage_id) {\n  std::function<bool(const Stage&)> check_stage = [](const Stage& in_stage) {\n    for (const auto& iter : in_stage->iters) {\n      if (iter->annotation == IteratorAnnotation::kThreadX &&\n          iter->iter_kind == IteratorKind::kReduction) {\n        return true;\n      }\n    }\n    return false;\n  };\n\n  // Check the stage itself\n  if (check_stage(state->stages[stage_id])) {\n    return true;\n  }\n\n  // Check the attached stages\n  for (size_t iter_id = 0; iter_id < state->stages[stage_id]->iters.size(); iter_id++) {\n    const auto& res =\n        state->attach_map->iter_to_attached_stages.find(std::make_pair(stage_id, iter_id));\n    if (res != state->attach_map->iter_to_attached_stages.end()) {\n      for (int attached_stage_id : res->second) {\n        if (check_stage(state->stages[attached_stage_id])) {\n          return true;\n        }\n      }\n    }\n  }\n\n  return false;\n}\n\n/*! \\brief Return whether the stage has been tiled already. */\ninline bool IsTiled(const Stage& stage) {\n  auto op = stage->op.as<te::ComputeOpNode>();\n  ICHECK(op != nullptr);\n  return stage->iters.size() != op->axis.size() + op->reduce_axis.size();\n}\n\n/*! \\brief Extract primitive iterators from a nested fused or splitted iterator's name. */\ninline void ExtractOriginalIterators(const std::string& name, std::set<std::string>* rets) {\n  size_t last_pos = 0;\n  for (size_t i = 0; i < name.size(); ++i) {\n    if (name[i] == '@' || name[i] == '.') {  // '@' for fuse and '.' for split\n      if (!isdigit(name[last_pos]) && name[last_pos] != '@' && name[last_pos] != '.') {\n        rets->insert(name.substr(last_pos, i - last_pos));\n      }\n      last_pos = i + 1;\n    }\n  }\n\n  if (last_pos < name.size() && !isdigit(name[last_pos]) && name[last_pos] != '@' &&\n      name[last_pos] != '.') {\n    rets->insert(name.substr(last_pos, name.size() - last_pos));\n  }\n}\n\n/*! \\brief Get the last reduce iterator in the outermost reduce tile. */\ninline Iterator GetLastReduceIteratorInOutermostReduceTile(const Stage& stage) {\n  auto pop = stage->op.as<te::ComputeOpNode>();\n  ICHECK(pop != nullptr);\n  std::set<std::string> original_names;\n\n  const std::set<std::string>& no_split_at_inner_name_set =\n      stage->op->attrs.count(SearchPolicyKey::no_split_at_inner)\n          ? GetIterNameSetParam(stage->op->attrs, SearchPolicyKey::no_split_at_inner)\n          : std::set<std::string>();\n  size_t reduce_axis_size = 0;\n  for (const auto axis : pop->reduce_axis) {\n    if (!no_split_at_inner_name_set.count(axis->var->name_hint)) {\n      reduce_axis_size++;\n    }\n  }\n  if (reduce_axis_size) {\n    for (const auto& iter : stage->iters) {\n      if (iter->iter_kind == IteratorKind::kReduction) {\n        ExtractOriginalIterators(iter->name, &original_names);\n        if (original_names.size() == reduce_axis_size) {\n          return iter;\n        }\n      }\n    }\n  } else {\n    // Return the first reduce iterator\n    for (const auto& iter : stage->iters) {\n      if (iter->iter_kind == IteratorKind::kReduction) {\n        return iter;\n      }\n    }\n  }\n\n  LOG(FATAL) << \"Cannot find the iterator.\";\n  return stage->iters[0];\n}\n\n/*! \\brief Get the target stage id of a history step in the new state.\n * We need this because the stage_id in the history may be stale due to later steps */\ninline int GetTargetStageIDInState(const State& s, int step_id) {\n  int stage_inc = 0;\n\n  for (size_t i = step_id + 1; i < s->transform_steps.size(); ++i) {\n    if (IsStageNumberChangingStep(s->transform_steps[i])) {\n      if (s->transform_steps[i]->stage_id <= s->transform_steps[step_id]->stage_id + stage_inc)\n        stage_inc++;\n    }\n  }\n  return s->transform_steps[step_id]->stage_id + stage_inc;\n}\n\n/*! \\brief Get all split steps for one stage. */\ninline void GetSplitStepIds(const State& s, int stage_id, std::vector<int>* split_step_ids) {\n  for (int i = static_cast<int>(s->transform_steps.size()) - 1; i >= 0; --i) {\n    if (auto ps = s->transform_steps[i].as<SplitStepNode>()) {\n      if (stage_id == ps->stage_id) {\n        split_step_ids->push_back(i);\n      }\n    }\n\n    if (IsStageNumberChangingStep(s->transform_steps[i])) {\n      if (stage_id > s->transform_steps[i]->stage_id) {\n        stage_id--;\n      }\n    }\n  }\n}\n\n/*! \\brief Fuse all reduction iterators. */\ninline State FuseAllReductionIterators(const State& state, int stage_id, Iterator* fused_iter,\n                                       Array<Iterator>* space_iters,\n                                       Array<Iterator>* reduce_iters) {\n  space_iters->clear();\n  reduce_iters->clear();\n\n  for (const auto& iter : state->stages[stage_id]->iters) {\n    if (iter->iter_kind == IteratorKind::kSpatial) {\n      space_iters->push_back(iter);\n    } else if (iter->iter_kind == IteratorKind::kReduction) {\n      reduce_iters->push_back(iter);\n    }\n  }\n\n  ICHECK(!reduce_iters->empty());\n  State tmp_s = state;\n  if (reduce_iters->size() > 1) {\n    *fused_iter = tmp_s.fuse(stage_id, *reduce_iters);\n  } else {\n    *fused_iter = (*reduce_iters)[0];\n  }\n  return tmp_s;\n}\n\n/*! \\brief Fuse all outer level space iterators. */\ninline State FuseAllOuterSpaceIterators(const State& state, int stage_id, Iterator* fused_iter) {\n  std::vector<Iterator> to_fuse;\n  for (size_t iter_id = 0; iter_id < state->stages[stage_id]->iters.size(); ++iter_id) {\n    const auto& it = state->stages[stage_id]->iters[iter_id];\n    // Stop at reduce iterator or annotated iterator\n    if (it->iter_kind == IteratorKind::kReduction || it->annotation != IteratorAnnotation::kNone) {\n      break;\n    }\n    // Stop at compute_at attach point\n    if (state->attach_map->iter_to_attached_stages.count(std::make_pair(stage_id, iter_id - 1))) {\n      break;\n    }\n    to_fuse.push_back(it);\n  }\n\n  State tmp_s = state;\n  if (to_fuse.size() == 1) {\n    *fused_iter = to_fuse[0];\n  } else {\n    *fused_iter = tmp_s.fuse(stage_id, to_fuse);\n  }\n  return tmp_s;\n}\n\n/*! \\brief Random sample states. */\ninline Array<State> RandomSampleStates(const Array<State>& in_states, std::mt19937* random_gen,\n                                       size_t out_size) {\n  Array<State> out_states;\n  for (size_t i = 0; i < out_size; i++) {\n    out_states.push_back(in_states[(*random_gen)() % in_states.size()]);\n  }\n  return out_states;\n}\n\n/*! \\brief Compute prefix-sum probabiilty based on the given weights */\ninline void ComputePrefixSumProb(const std::vector<float>& weights,\n                                 std::vector<double>* prefix_sum_probs) {\n  // Compute selection probabilities.\n  float sum = 0.0;\n  prefix_sum_probs->resize(weights.size());\n  for (size_t i = 0; i < weights.size(); ++i) {\n    sum += std::max(weights[i], 0.0f);\n    (*prefix_sum_probs)[i] = sum;\n  }\n  for (size_t i = 0; i < weights.size(); ++i) {\n    (*prefix_sum_probs)[i] /= sum;\n  }\n}\n\n/*! \\brief Random choose an index according to a prefix sum probability. */\ninline int RandomChoose(const std::vector<double>& prefix_sum_probs, std::mt19937* random_gen) {\n  std::uniform_real_distribution<> dis(0.0, 1.0);\n  double x = dis(*random_gen);\n\n  ICHECK(!prefix_sum_probs.empty());\n\n  return std::lower_bound(prefix_sum_probs.begin(), prefix_sum_probs.end(), x) -\n         prefix_sum_probs.begin();\n}\n\n/*! \\brief Print a title */\ninline void PrintTitle(const std::string& title, int verbose) {\n  StdCout(verbose) << Chars('-', 70) << \"\\n\"\n                   << Chars('-', 30) << \"  [ \" << title << \" ]\\n\"\n                   << Chars('-', 70) << std::endl;\n}\n\n/*!\n * \\brief Enumerate all possible factorization schemes for splitting an axes.\n * \\note This class will memorize the results for reuse.\n */\nclass SplitFactorizationMemo {\n public:\n  using QueryKey = std::tuple<int, int, int>;\n\n  const Array<Array<Integer>>& GetFactorizationSchemes(int extent, int n_lengths,\n                                                       int max_innermost_factor);\n  const std::vector<int>& GetFactors(int n);\n\n private:\n  void DfsEnumerate(int now, int remaining_length, int max_innermost_factor);\n\n  std::unordered_map<QueryKey, Array<Array<Integer>>> memory_;\n\n  int n_lengths_;\n  Array<Integer> tmp_stack_;\n  Array<Array<Integer>>* results_;\n  std::unordered_map<int, std::vector<int>> factor_memory_;\n};\n\n/*! \\brief Get the indexes of SplitStep that processes on spatial iterator. */\nArray<Integer> GetSpatialSplitStepIds(const State& s, int stage_id);\n\n/*! \\brief Get the possible compute locations for a stage. */\nstd::vector<std::pair<int, int>> GetComputeLocationCandidates(const SearchTask& task,\n                                                              const State& state, int stage_id);\n\n// Apply multi-level tiling structure according to a string format,\n// where \"S\" stands a space level, \"R\" stands for a reduction level.\n// For example, if the format is \"SSRSRS\", then we will\n// use tiling structure:  space_L0, space_L1, reduce_L0, space_L2, reduce_L1, space_L3\n// For example, if apply \"SSRSRS\" to matrix multiplication,\n// we have space iterators i and j, reduce iterator k.\n// Then the tiling structure is : i0, j0, i1, j1, k0, i2, j2, k1, i3, j3\nState DoMultiLevelTiling(const State& state, int stage_id, const std::string& format,\n                         std::vector<int>* spatial_split_step_ids = nullptr);\n\n// Apply tiling structure: space, space, space, ..., with tile sizes from other SplitStep\nState FollowTiling(const State& state, int stage_id, const std::vector<int>& split_step_ids,\n                   int n_split);\n\n// Prune invalid states and return the results in-place.\nvoid PruneInvalidState(const SearchTask& task, Array<State>* states);\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_SEARCH_POLICY_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/auto_scheduler/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler/utils.h\n * \\brief Common utilities.\n */\n\n#ifndef TVM_AUTO_SCHEDULER_UTILS_H_\n#define TVM_AUTO_SCHEDULER_UTILS_H_\n\n#include <dmlc/common.h>\n#include <tvm/tir/expr.h>\n\n#include <algorithm>\n#include <deque>\n#include <exception>\n#include <future>\n#include <iomanip>\n#include <numeric>\n#include <random>\n#include <string>\n#include <thread>\n#include <tuple>\n#include <utility>\n#include <vector>\n\nnamespace std {\n\n/*! \\brief Hash function for std::pair */\ntemplate <typename T1, typename T2>\nstruct hash<std::pair<T1, T2>> {\n  std::size_t operator()(const std::pair<T1, T2>& k) const {\n    return ::dmlc::HashCombine(std::hash<T1>()(k.first), std::hash<T2>()(k.second));\n  }\n};\n\n/*! \\brief Hash function for std::tuple */\ntemplate <typename T1, typename T2, typename T3>\nstruct hash<std::tuple<T1, T2, T3>> {\n  std::size_t operator()(const std::tuple<T1, T2, T3>& k) const {\n    return ::dmlc::HashCombine(\n        ::dmlc::HashCombine(std::hash<T1>()(std::get<0>(k)), std::hash<T2>()(std::get<1>(k))),\n        std::hash<T3>()(std::get<2>(k)));\n  }\n};\n\n}  // namespace std\n\nnamespace tvm {\nnamespace auto_scheduler {\n\n/********** Utilities for Array, std::vector, std::string **********/\n/*! \\brief Get the first appearance index of elements in an Array */\ntemplate <typename T>\ninline void GetIndices(const Array<T>& array, const Array<T>& to_locate, Array<Integer>* indices) {\n  for (const auto& v : to_locate) {\n    auto it = std::find(array.begin(), array.end(), v);\n    if (it != array.end()) {\n      indices->push_back(it - array.begin());\n    } else {\n      LOG(FATAL) << \"Cannot find the item\";\n    }\n  }\n}\n\n/*! \\brief Get the first appearance index of an element in an Array */\ntemplate <typename T>\ninline int GetIndex(const Array<T>& array, const T& to_locate) {\n  for (size_t i = 0; i < array.size(); ++i) {\n    if (array[i] == to_locate) {\n      return i;\n    }\n  }\n  LOG(FATAL) << \"Cannot find the item\";\n  return -1;\n}\n\n/*! \\brief Delete the item in a std::vector if it exists. */\ntemplate <typename T>\ninline void FindAndDeleteItem(std::vector<T>* array, const T& to_delete) {\n  auto iter = std::find(array->begin(), array->end(), to_delete);\n  if (iter != array->end()) {\n    array->erase(iter);\n  }\n}\n\n/*! \\brief Compute the product of all elements in a vector */\ninline int64_t ElementProduct(const std::vector<int>& array) {\n  int64_t ret = 1;\n  for (auto x : array) {\n    ret *= x;\n  }\n  return ret;\n}\n\n/*! \\brief Move elements from multiple vectors to one vector */\ntemplate <typename T>\nstd::vector<T>& ConcatenateMove(std::vector<T>* out, std::vector<T>* in) {\n  out->insert(out->end(), std::make_move_iterator(in->begin()), std::make_move_iterator(in->end()));\n  return *out;\n}\n\n/*! \\brief Move elements from multiple vectors to one vector */\ntemplate <typename T, typename... Args>\nstd::vector<T>& ConcatenateMove(std::vector<T>* out, std::vector<T>* first, Args... args) {\n  ConcatenateMove(out, first);\n  ConcatenateMove(out, args...);\n  return *out;\n}\n\n/*! \\brief Get a random permutation of integers [0, n-1] */\ntemplate <typename G>\nvoid RandomPermutation(int n, std::vector<int>* out, G* gen) {\n  out->assign(n, 0);\n  std::iota(out->begin(), out->end(), 0);\n  std::shuffle(out->begin(), out->end(), *gen);\n}\n\n/*! \\brief Replace a sub-string to another sub-string in a string */\ninline void StrReplace(std::string* base, const std::string& from, const std::string& to) {\n  auto pos = base->find(from);\n  while (pos != std::string::npos) {\n    base->replace(pos, from.size(), to);\n    pos = base->find(from, pos + to.size());\n  }\n}\n\n/*! \\brief Return whether two int arrays are elementwise-equal */\ninline bool IntArrayEqual(const Array<PrimExpr>& arr1, const Array<PrimExpr>& arr2) {\n  if (arr1.size() != arr2.size()) {\n    return false;\n  }\n\n  for (size_t i = 0; i < arr1.size(); ++i) {\n    auto int1 = arr1[i].as<IntImmNode>();\n    auto int2 = arr2[i].as<IntImmNode>();\n    ICHECK(int1 != nullptr);\n    ICHECK(int2 != nullptr);\n    if (int1->value != int2->value) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/********** Utilities for TVM Containers / ByteArray **********/\n/*! \\brief Compute mean of a FloatImm array */\ninline double FloatArrayMean(const Array<PrimExpr>& float_array) {\n  double sum = 0;\n  if (float_array.empty()) {\n    return 0.0;\n  }\n\n  for (const auto& x : float_array) {\n    auto floatimm = x.as<tir::FloatImmNode>();\n    ICHECK(floatimm != nullptr);\n    sum += floatimm->value;\n  }\n  return sum / float_array.size();\n}\n\n/*! \\brief Return whether a string starts with another substring */\ninline bool StrStartsWith(const String& a, const String& b) {\n  if (b.size() > a.size()) return false;\n  return std::equal(a.c_str(), a.c_str() + b.size(), b.c_str());\n}\n\n/*! \\brief Return whether a string ends with another substring */\ninline bool StrEndsWith(const String& a, const String& b) {\n  if (b.size() > a.size()) return false;\n  return std::equal(a.c_str() + a.size() - b.size(), a.c_str() + a.size(), b.c_str());\n}\n\n/********** Other Utilities **********/\n/*! \\brief Get an int value from an Expr */\ninline int64_t GetIntImm(const PrimExpr& expr) {\n  auto pint = expr.as<IntImmNode>();\n  if (pint == nullptr) {\n    return 1;\n  }\n  return pint->value;\n}\n\n/*! \\brief Compute the product of the lengths of axes */\ninline int64_t AxisLengthProd(const Array<tir::IterVar>& axes) {\n  int64_t ret = 1.0;\n  for (const auto& x : axes) {\n    if (const IntImmNode* imm = x->dom->extent.as<IntImmNode>()) {\n      ret *= imm->value;\n    } else {\n      return -1.0;\n    }\n  }\n  return ret;\n}\n\n/*!\n * \\brief Clean the name of an iterator or an op to make it valid in python code.\n * \\param str The original name.\n * \\param prefix The name prefix to differentiate the same name (e.g., the same iterator names).\n * \\return The cleaned name.\n */\ninline std::string CleanName(const std::string& str, const std::string& prefix = \"\") {\n  std::string ret = str;\n  StrReplace(&ret, \".\", \"_\");\n  StrReplace(&ret, \"@\", \"_\");\n  StrReplace(&ret, \"outer\", \"o\");\n  StrReplace(&ret, \"inner\", \"i\");\n  if (prefix != \"\") {\n    return prefix + \"_\" + ret;\n  }\n  return ret;\n}\n\n/*! \\brief An empty output stream */\nclass NullStream : public std::ostream {\n public:\n  NullStream() : std::ostream(nullptr) {}\n  NullStream(const NullStream&) : std::ostream(nullptr) {}\n  static NullStream& Global();\n};\n\ntemplate <class T>\nNullStream& operator<<(NullStream& os, const T& value) {\n  return os;\n}\n\n/*! \\brief Get std cout with verbose control */\ninline std::ostream& StdCout(int verbose, int setting = 1) {\n  return verbose >= setting ? std::cout : NullStream::Global();\n}\n\n/*! \\brief Print multiple chars */\ninline std::string Chars(const char& str, int times) {\n  std::stringstream ret;\n  for (int i = 0; i < times; ++i) {\n    ret << str;\n  }\n  return ret.str();\n}\n\n/*! \\brief Print the time elapsed */\ninline void PrintTimeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> t_begin,\n                             const std::string& info, int verbose) {\n  double duration = std::chrono::duration_cast<std::chrono::duration<double>>(\n                        std::chrono::high_resolution_clock::now() - t_begin)\n                        .count();\n  StdCout(verbose) << \"Time elapsed for \" << info << \": \" << std::fixed << std::setprecision(2)\n                   << duration << \" s\" << std::endl;\n}\n\n/*!\n * \\brief Parse shape and axis names from layout string\n */\ninline void ParseKernelLayout(const String& layout, Array<PrimExpr>* shape,\n                              std::vector<std::string>* axes) {\n  int32_t factor = 0;\n  std::string axis = \"\";\n  for (char c : std::string(layout)) {\n    if (c >= 'A' && c <= 'z') {\n      axis += c;\n      if (factor != 0) {\n        shape->push_back(factor);\n        factor = 0;\n      }\n    } else if (c >= '0' && c <= '9') {\n      factor = factor * 10 + c - '0';\n      if (!axis.empty()) {\n        axes->push_back(axis);\n        axis = \"\";\n      }\n    } else {\n      LOG(FATAL) << \"Invalid layout \" << layout;\n    }\n  }\n  if (!axis.empty()) {\n    axes->push_back(axis);\n  }\n}\n\n/*! \\brief Get the base name before '_' of an axis */\ninline std::string AxisBaseName(const std::string& str) { return str.substr(0, str.rfind(\"_\")); }\n\n}  // namespace auto_scheduler\n}  // namespace tvm\n\n#endif  // TVM_AUTO_SCHEDULER_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/autotvm/feature_visitor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file feature_visitor.h\n * \\brief Base class for feature extractor.\n *        These features are used for machine learning cost model\n */\n\n#ifndef TVM_AUTOTVM_FEATURE_VISITOR_H_\n#define TVM_AUTOTVM_FEATURE_VISITOR_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace autotvm {\n\nusing namespace tvm::tir;\n\n/*!\n * \\brief Type of for loop, used as one-hot encoding in features\n */\nenum AnnotationType {\n  kBlockX,\n  kBlockY,\n  kBlockZ,\n  kThreadX,\n  kThreadY,\n  kThreadZ,\n  kUnrolled,\n  kVectorized,\n  kParallel,\n  kSerial,\n  kVirtualThread,\n  kNum,\n};\n\n/*!\n * \\brief A base class for feature extractor, used for processing\n * for loop and memory access in the IR\n */\nclass FeatureVisitor : public StmtExprVisitor {\n public:\n  // for loop\n  void VisitStmt_(const ForNode* op) final;\n  void VisitStmt_(const AttrStmtNode* op) final;\n\n  // memory access\n  void VisitExpr_(const BufferLoadNode* op) final;\n  void VisitStmt_(const BufferStoreNode* op) final;\n\n  using StmtExprVisitor::VisitExpr_;\n  using StmtExprVisitor::VisitStmt_;\n\n protected:\n  /*!\n   * \\brief Enter a for loop node\n   * \\param var The expression to be printed.\n   * \\param length The output stream\n   * \\param ann_type The type for the for loop\n   * \\return skip Whether skip this node\n   */\n  virtual bool EnterItervar_(tir::Var var, int64_t length, AnnotationType ann_type) = 0;\n  /*! \\brief Exit a for loop subtree */\n  virtual void ExitItervar_() = 0;\n  /*!\n   * \\brief Enter a memory access node\n   * \\param buffer_var The buffer to access.\n   * \\param index Index expression\n   */\n  virtual void EnterMem_(tir::Var buffer_var, tvm::PrimExpr index) = 0;\n  /*! \\brief Exit a memory access node */\n  virtual void ExitMem_() = 0;\n};\n\n}  // namespace autotvm\n}  // namespace tvm\n\n#endif  // TVM_AUTOTVM_FEATURE_VISITOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/autotvm/touch_extractor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file touch_extractor.h\n * \\brief Extract feature of touch pattern of axes in lowered IR\n */\n\n#ifndef TVM_AUTOTVM_TOUCH_EXTRACTOR_H_\n#define TVM_AUTOTVM_TOUCH_EXTRACTOR_H_\n\n#include <tvm/runtime/registry.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/expr_functor.h>\n\n#include <deque>\n#include <map>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"feature_visitor.h\"\n\nnamespace tvm {\nnamespace autotvm {\n\nusing TouchedBuffer = std::string;\n\n// touch pattern buf[(stride * var) % mod) + other]\nstruct TouchPattern {\n  int64_t stride{0};\n  int64_t mod{-1};  // -1 for +inf\n\n  int64_t count{1};\n  int64_t reuse{1};\n  int64_t thread_count{0};  // count when move thread axis into innermost\n  int64_t thread_reuse{0};  // reuse ratio move thread axis into innermost\n};\n\n// all the feature of an iter var\nstruct ItervarFeature {\n  ItervarFeature(Var var, int64_t extent, int nest, AnnotationType ann_type, int64_t topdown,\n                 int counter)\n      : length(extent), nest_level(nest), ann(ann_type), topdown_product(topdown), order(counter) {}\n  ItervarFeature() {}\n\n  // Axis Attributes\n  int64_t length;\n  int nest_level;\n  AnnotationType ann;        // one-hot axis type\n  int64_t topdown_product;   // accumulative product of axis length, in top-down order\n  int64_t bottomup_product;  // accumulative product of axis length, in bottom-up order\n  // bottomup_product = reuse * count for any touched buffer\n\n  int order;  // used for soring axis\n\n  // Arithmetic feature\n  int add_ct{0};\n  int mul_ct{0};\n  int div_ct{0};\n\n  // Memory Touch Feature\n  std::unordered_map<TouchedBuffer, TouchPattern> touch_feature;\n};\n\n// extract iter vars and their touch pattern from ir\nclass TouchExtractor : public FeatureVisitor {\n public:\n  void Analyze(const Stmt& stmt) { operator()(stmt); }\n\n  // arithmetic stats\n  void VisitExpr_(const AddNode* op) final {\n    if (op->dtype.is_float() || op->dtype.is_bfloat16()) {\n      itervar_map[itervar_stack_.back()].add_ct++;\n    }\n    FeatureVisitor::VisitExpr_(op);\n  }\n\n  void VisitExpr_(const SubNode* op) final {\n    if (op->dtype.is_float() || op->dtype.is_bfloat16()) {\n      itervar_map[itervar_stack_.back()].add_ct++;\n    }\n    FeatureVisitor::VisitExpr_(op);\n  }\n\n  void VisitExpr_(const MulNode* op) final {\n    if (op->dtype.is_float() || op->dtype.is_bfloat16()) {\n      itervar_map[itervar_stack_.back()].mul_ct++;\n    }\n    FeatureVisitor::VisitExpr_(op);\n  }\n\n  void VisitExpr_(const DivNode* op) final {\n    if (op->dtype.is_float() || op->dtype.is_bfloat16()) {\n      itervar_map[itervar_stack_.back()].div_ct++;\n    }\n    FeatureVisitor::VisitExpr_(op);\n  }\n\n  void VisitExpr_(const ModNode* op) final {\n    if (op->dtype.is_float() || op->dtype.is_bfloat16()) {\n      itervar_map[itervar_stack_.back()].div_ct++;\n    }\n    FeatureVisitor::VisitExpr_(op);\n  }\n\n  std::unordered_map<Var, ItervarFeature, tvm::ObjectPtrHash, tvm::ObjectPtrEqual> itervar_map;\n\n private:\n  bool EnterItervar_(Var var, int64_t length, AnnotationType ann_type);\n  void ExitItervar_();\n  void EnterMem_(Var buffer_var, PrimExpr index);\n  void ExitMem_();\n\n  int64_t topdown_product_{1};\n  std::map<std::string, size_t> buffer_counter_;\n  size_t itervar_counter_{0};\n  std::deque<Var> itervar_stack_;  // use deque instead of stack for indexing\n  std::deque<size_t> skip_stack_size_;\n\n  using FeatureVisitor::VisitExpr_;\n};\n\n}  // namespace autotvm\n}  // namespace tvm\n\n#endif  // TVM_AUTOTVM_TOUCH_EXTRACTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/block_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/block_config.h\n * \\brief BlockConfig object for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_BLOCK_CONFIG_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_BLOCK_CONFIG_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass BlockConfig;\n\n/*! \\brief Node to represent a BlockConfig */\nclass BlockConfigNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Get the shape of input block.\n   * \\return The input shape of the block config.\n   */\n  inline std::vector<int> GetInputBlockShape() const { return input_shape_; }\n\n  /*!\n   * \\brief Get the shape of output block.\n   * \\return The output shape of the block config.\n   */\n  inline std::vector<int> GetOutputBlockShape() const { return output_shape_; }\n\n  /*!\n   * \\brief Get the number of cycles required to output this block\n   * \\return The output cycles\n   */\n  inline int GetOutputCycles() const { return output_cycles_; }\n\n  /*!\n   * \\brief Get the number of cycles required to compute this block\n   * \\return The compute cycles\n   */\n  inline int GetComputeCycles() const { return compute_cycles_; }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.BlockConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BlockConfigNode, Object);\n\n protected:\n  friend class BlockConfig;\n\n  /*! \\brief The shape of the input block */\n  std::vector<int> input_shape_;\n  /*! \\brief The shape of the output block */\n  std::vector<int> output_shape_;\n  /*! \\brief Cycles required to compute this block */\n  int compute_cycles_;\n  /*! \\brief Cycles required to output this block */\n  int output_cycles_;\n};\n\n/*!\n * \\brief An object that contains a an output block shape as well as the output and compute cycles\n * required to compute this block\n */\nclass BlockConfig : public ObjectRef {\n public:\n  BlockConfig(const std::vector<int>& input_shape, const std::vector<int>& output_shape,\n              int compute_cycles, int output_cycles);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(BlockConfig, ObjectRef, BlockConfigNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_BLOCK_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/cascader_options.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/cascader_options.h\n * \\brief Class to store configuration options for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_CASCADER_OPTIONS_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_CASCADER_OPTIONS_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include \"tensor_config.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\n/*! \\brief Node to represent CascaderOptions */\nclass CascaderOptionsNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\brief The MemoryRegion to place cascading buffer into. */\n  MemoryRegion cascade_region;\n  /*! \\brief The maximum number of Proposals to generate. */\n  int max_proposals;\n  /*! \\brief How many striping factors to try per axis. */\n  int stripe_factors;\n  /*! \\brief The maximum number of Parts in a Plan. */\n  int max_plan_size;\n  /*! \\brief The maximum number of open Plans saved for a Part Group */\n  int max_open_plans;\n  /*! \\brief The maximum number of closed Plans saved for a Part Group */\n  int max_closed_plans;\n  /*! \\brief The maximum size of Tensor that will always be copied into the cascade region. */\n  int always_copy_size;\n  /*! \\brief Flag to disable pareto culling for plans to allow non pareto-optimal plans */\n  bool disable_pareto_plans;\n  /*! \\brief Flag to disable pareto culling for proposals to allow non pareto-optimal proposals */\n  bool disable_pareto_proposals;\n  /*! \\brief Whether to consider multi-dimensional striping */\n  bool enable_multi_dimensional_striping;\n  /*! \\brief Flag to disable culling for block configs to allow non-dominant blocks */\n  bool disable_block_culling;\n  /*! \\brief A boolean option to enable striping. */\n  bool enable_striping;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.CascaderOptions\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CascaderOptionsNode, Object)\n};\n\n/*! \\brief A class to hold configuration options for the cascader. */\nclass CascaderOptions : public ObjectRef {\n public:\n  CascaderOptions(const MemoryRegion& cascade_region, int max_proposals, int stripe_factors,\n                  int max_plan_size, int max_open_plans, int max_closed_plans, int always_copy_size,\n                  bool disable_pareto_plans, bool disable_pareto_proposals,\n                  bool enable_multi_dimensional_striping, bool disable_block_culling,\n                  bool multi_dimensional_striping);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CascaderOptions, ObjectRef, CascaderOptionsNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_CASCADER_OPTIONS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/common.h\n * \\brief Common functions used in the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_COMMON_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_COMMON_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n\n#include <functional>\n#include <numeric>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\n/*!\n * \\brief Make a tvm::Array<Integer> from an int vector.\n * \\param vec The int vector.\n * \\return The Integer Array.\n * \\note Array<Integer>(std::vector<int>) doesn't work as this implicit\n * type conversion fails. This is why this helper is required.\n */\ninline Array<Integer> make_array(const std::vector<int>& vec) {\n  Array<Integer> arr;\n  arr.resize(vec.size());\n  for (unsigned int i = 0; i < vec.size(); ++i) {\n    arr.Set(i, Integer(vec[i]));\n  }\n  return arr;\n}\n\n/*!\n * \\brief Make a tvm::Array<Integer> from a size_t vector.\n * \\param vec The size_t vector.\n * \\return The Integer Array.\n * \\note Array<Integer>(std::vector<size_t>) doesn't work as this implicit\n * type conversion fails. This is why this helper is required.\n */\ninline Array<Integer> make_array(const std::vector<size_t>& vec) {\n  Array<Integer> arr;\n  arr.resize(vec.size());\n  for (unsigned int i = 0; i < vec.size(); ++i) {\n    arr.Set(i, Integer(vec[i]));\n  }\n  return arr;\n}\n\n/*!\n * \\brief Make a tvm::Array<IntImm> from an int64_t vector.\n * \\param vec The int64_t vector.\n * \\return The IntImm Array.\n * \\note Array<IntImm>(std::vector<int64_t>) doesn't work as this implicit\n * type conversion fails. This is why this helper is required.\n */\ninline Array<IntImm> make_array(const std::vector<int64_t>& vec) {\n  Array<IntImm> arr;\n  arr.resize(vec.size());\n  for (unsigned int i = 0; i < vec.size(); ++i) {\n    arr.Set(i, IntImm(DataType::Int(64), vec[i]));\n  }\n  return arr;\n}\n\n/*!\n * \\brief Make a tvm::Array<FloatImm> from an float vector.\n * \\param vec The float vector.\n * \\return The FloatImm Array.\n */\ninline Array<FloatImm> make_array(const std::vector<float>& vec) {\n  Array<FloatImm> arr;\n  arr.resize(vec.size());\n  for (unsigned int i = 0; i < vec.size(); ++i) {\n    arr.Set(i, FloatImm(DataType::Float(32), static_cast<double>(vec[i])));\n  }\n  return arr;\n}\n\n/*!\n * \\brief Calculate the ceil of an Integer division\n * \\param dividend The dividend of the division\n * \\param divisor The divisor of the division\n * \\return The quotient\n */\ninline int round_up_divide(int dividend, int divisor) {\n  return dividend / divisor + (dividend % divisor != 0);\n}\n\n/*!\n * \\brief Make a vector from a tvm::Array.\n * \\param arr The Array.\n * \\return The vector.\n */\ntemplate <typename T, typename tvm_T>\ninline std::vector<T> make_vector(const Array<tvm_T>& arr) {\n  std::vector<T> vec(arr.size());\n  for (unsigned int i = 0; i < arr.size(); ++i) {\n    vec[i] = arr[i]->value;\n  }\n  return vec;\n}\n\n/*!\n * \\brief Create a combined hash.\n * \\param seed The current hash value.\n * \\param v The value to combine into the hash.\n * \\return The combined hash.\n */\ntemplate <class T>\ninline void hash_combine(std::size_t* seed, T const& v) {\n  *seed ^= std::hash<T>()(v) + 0x9e3779b9 + (*seed << 6) + (*seed >> 2);\n}\n\n/*!\n * \\brief Hash a vector.\n * \\param vec The vector to hash.\n * \\return The hash.\n */\ntemplate <class T>\ninline std::size_t hash_vector(const std::vector<T>& vec) {\n  std::size_t seed = vec.size();\n  for (const auto& elem : vec) {\n    hash_combine(&seed, elem);\n  }\n  return seed;\n}\n\ntemplate <class T>\ninline T mul_reduce(const std::vector<T>& vec) {\n  return std::accumulate(vec.begin(), vec.end(), 1, std::multiplies<T>());\n}\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/graph.h\n * \\brief Graph objects (Tensor and Part) for the Ethos-U cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_GRAPH_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_GRAPH_H_\n\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/object.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/tensor.h>\n\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"block_config.h\"\n#include \"propagator.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass Tensor;\nclass Part;\nclass StripeConfig;\n\n/*!\n * \\brief The buffering mode to use when realizing a tensor.\n * RECOMPUTE - The 'default' behaviour of TVM. Overlapping stripes will be recomputed.\n * ROLLING - Apply both the sliding window and storage folding optimizations to the tensor\n * realization.\n */\nenum BufferMode { RECOMPUTE, ROLLING };\n\n/*! \\brief A struct to hold a Tensor Expression subgraph */\nstruct TESubgraph {\n  /*! \\brief The input te::Tensors to the subgraph */\n  std::vector<te::Tensor> input_tensors;\n  /*! \\brief The output te::Tensor of the subgraph */\n  te::Tensor output_tensor;\n};\n\n/*! \\brief Node to hold performance information for a Part */\nclass PerformanceInfoNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\brief The cycles to compute a block */\n  int64_t compute_cycles;\n  /*! \\brief The number of bytes read per input tensor */\n  std::vector<int64_t> read_bytes;\n  /*! \\brief The number of bytes written to the output tensor */\n  int64_t write_bytes;\n  /*! \\brief The block config used for this performance point */\n  BlockConfig block_config;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.PerformanceInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PerformanceInfoNode, Object);\n};\n\n/*!\n * \\brief A class to hold the performance information for a Part.\n * \\note The performance information for a Part is composed of 3 factors: the compute cycles,\n * the number of bytes read from each input tensor and the number of bytes written to the output\n * tensor. Bytes read/written is reported in favour of read/write bandwidth cycles so the\n * calculation of the performance information can be re-used with different memory homing.\n */\nclass PerformanceInfo : public ObjectRef {\n public:\n  PerformanceInfo(int64_t compute_cycles, std::vector<int64_t> read_bytes, int64_t write_bytes,\n                  BlockConfig block_config) {\n    auto n = make_object<PerformanceInfoNode>();\n    n->compute_cycles = compute_cycles;\n    n->read_bytes = std::move(read_bytes);\n    n->write_bytes = write_bytes;\n    n->block_config = block_config;\n    data_ = std::move(n);\n  }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PerformanceInfo, ObjectRef, PerformanceInfoNode);\n};\n\n/*! \\brief Node to represent a Tensor */\nclass TensorNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The shape of the tensor */\n  std::vector<int> GetShape() const { return shape_; }\n  /*! \\return The data type of the tensor */\n  DataType GetDataType() const { return dtype_; }\n  /*! \\return Whether the tensor stores a constant value */\n  bool IsConstant() const { return is_constant_; }\n  /*! \\return The compression ratio of the tensor */\n  float GetCompressionRatio() const { return compression_ratio_; }\n  /*! \\return The producers of the tensor */\n  const std::vector<Part> GetProducers() const { return producers_; }\n  /*! \\return The consumers of the tensor */\n  const std::vector<Part> GetConsumers() const { return consumers_; }\n  /*! \\return The size of the tensor in bytes */\n  int GetSize() const { return size_ * compression_ratio_; }\n\n  /*! \\brief Add a producer of the tensor */\n  inline void AddProducer(const Part& part) { producers_.push_back(part); }\n  /*! \\brief Add a consumer of the tensor */\n  inline void AddConsumer(const Part& part) { consumers_.push_back(part); }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.Tensor\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorNode, Object);\n\n protected:\n  friend class Tensor;\n\n  /*! \\brief The shape of the tensor */\n  std::vector<int> shape_;\n  /*! \\brief The data type of the tensor */\n  DataType dtype_;\n  /*! \\brief Whether the tensor stores a constant value */\n  bool is_constant_;\n  /*! \\brief The compression ratio of the tensor */\n  float compression_ratio_;\n  /*! \\brief The producers of the tensor */\n  std::vector<Part> producers_;\n  /*! \\brief The consumers of the tensor */\n  std::vector<Part> consumers_;\n  /*! \\brief The size of the tensor in bytes */\n  int size_;\n};\n\n/*!\n * \\brief A class to describe a Tensor in a Cascader graph.\n * \\note Cascader graphs consist of two object types: Tensors and Parts. This class\n * defines the Tensors which represent the tensors that are consumed and produced\n * as part of the graph. They are augmented with information about their 'kind'\n * (input/output/constant/intermediate), their default memory home (which memory they\n * are expected to be allocated in) and a compression ratio where applicable (weights\n * for instance are compressed).\n */\nclass Tensor : public ObjectRef {\n public:\n  Tensor(const std::vector<int>& shape, DataType dtype, bool is_constant, float compression_ratio);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Tensor, ObjectRef, TensorNode);\n};\n\n/*! \\brief Node to represent a Part */\nclass PartNode : public Object {\n public:\n  virtual void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The TE subgraph represented by the Part */\n  const TESubgraph GetSubgraph() const { return subgraph_; }\n  /*! \\return The output->input propagators */\n  const std::vector<Propagator> GetPropagators() const { return propagators_; }\n  /*! \\return Whether the Part is inline */\n  bool IsInline() const { return in_line_; }\n  /*! \\return The input tensors */\n  const std::vector<Tensor> GetInputTensors() const { return input_tensors_; }\n  /*! \\return The output tensor */\n  const Tensor GetOutputTensor() const { return output_tensor_; }\n\n  /*! \\brief Add a producer of the tensor */\n  void SetInput(uint64_t input_index, const Tensor& input_tensor);\n  /*! \\brief Add a consumer of the tensor */\n  void SetOutput(const Tensor& output_tensor) { output_tensor_ = output_tensor; }\n  /*!\n   * \\brief Calculate the input stripe configs for a given output stripe config using the\n   * Propagators. \\param output_stripe_config The output stripe config to propagate. \\return The\n   * calculated input stripe configs.\n   */\n  std::vector<StripeConfig> CalculateInputStripeConfigs(const StripeConfig& output_stripe_config);\n  /*!\n   * \\brief Get the preferred alignment in each axis for a stripe of the Part.\n   * \\note This is used to bias the selection of StripeConfigs towards those that are integer\n   * multiples of a tensor intrinsic used to compute the Part.\n   */\n  virtual const std::vector<int> GetStripeAlignHint() const;\n  /*!\n   * \\brief Get the performance information for a given output stripe config.\n   * \\param output_stripe_config The output stripe config to compute the performance for.\n   * \\param is_rolling Whether the output config should be computed as a rolling buffer.\n   * \\return The performance information containing the compute cycles and read/write bytes.\n   */\n  virtual const PerformanceInfo GetPerformanceInfo(const StripeConfig& output_stripe_config,\n                                                   BufferMode buffer_mode) = 0;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.Part\";\n  TVM_DECLARE_BASE_OBJECT_INFO(PartNode, Object);\n\n protected:\n  friend class Part;\n\n  /*! \\brief The Tensor Expression subgraph represented by the Part */\n  TESubgraph subgraph_;\n  /*! \\brief The output->input propagators */\n  std::vector<Propagator> propagators_;\n  /*! \\brief Whether the Part is computed in-line */\n  bool in_line_;\n  /*! \\brief The input tensors */\n  std::vector<Tensor> input_tensors_;\n  /*! \\brief The output tensor */\n  Tensor output_tensor_;\n};\n\n/*!\n * \\brief A class to describe a Part in a Cascader graph.\n * \\note Cascader graphs consist of two object types: Tensors and Parts. This class\n * defines the Parts which represent the operations which produce and consume Tensors.\n *\n * A Part can represent one or more Tensor Expression compute operations but the subgraph\n * it represents must have only a single output. Multiple TE compute operations should be\n * represented under a single Part if the intermediate tensors between them won't be\n * realized. This is a common pattern in Ethos-U where a sequence of TE compute operations\n * are used to represent a single hardware primitive operation.\n *\n * Parts contain a Propagator per input which describes how a given output stripe config\n * should be transformed into an input stripe config for each input. This is essential\n * to analyse both the performance of Parts (determining the data that will be read) and\n * in cascading Parts together (determining compatible stripe config choices).\n *\n * A Part can be marked as 'in_line', in which case it is assumed that it doesn't need to\n * allocate space for its output tensor.\n *\n * This is only a base class and concrete Parts must be derived from it, implementing a\n * function to model the performance of the Part as well as to determine its compute\n * quantum.\n */\nclass Part : public ObjectRef {\n public:\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Part, ObjectRef, PartNode);\n};\n\n/*! \\brief Node to represent a CascaderGraph */\nclass CascaderGraphNode : public Object {\n public:\n  CascaderGraphNode() {}\n  CascaderGraphNode(std::vector<Tensor> input_tensors, std::vector<Tensor> output_tensors);\n\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The input Tensors of the CascaderGraph */\n  std::vector<Tensor> GetInputTensors() const { return input_tensors_; }\n  /*! \\return The output Tensors of the CascaderGraph */\n  std::vector<Tensor> GetOutputTensors() const { return output_tensors_; }\n  /*! \\return The order of the Parts in the CascaderGraph */\n  std::vector<Part> GetPartOrder() const { return part_order_; }\n  /*!\n   * \\brief Get the ID of a Part in the CascaderGraph.\n   * \\param part The Part to get the ID of.\n   * \\return The ID of the Part in the CascaderGraph.\n   * \\note Each Part is given a unique ID within the CascaderGraph.\n   */\n  int GetPartID(const Part& part) const;\n  /*!\n   * \\brief Get the ID of a Tensor in the CascaderGraph.\n   * \\param tensor The Tensor to get the ID of.\n   * \\return The ID of the Tensor in the CascaderGraph.\n   * \\note Each Tensor is given a unique ID within the CascaderGraph.\n   */\n  int GetTensorID(const Tensor& tensor) const;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.CascaderGraph\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CascaderGraphNode, Object);\n\n protected:\n  /*!\n   * \\brief Initialize the CascaderGraph by defining a topological ordering.\n   * \\note This will traverse the Parts and Tensors using a depth-first\n   * visiting pattern and use the traversal order to initialize both the\n   * 'order' vectors and the ID maps. The order vectors define the ordering\n   * that the cascader expects the CascaderGraph to be executed in, but reversed.\n   * The ID maps assign a unique integer ID to each Part and Tensor corresponding\n   * to their position in their respective order vector.\n   */\n  void Init_();\n\n  /*! \\brief The input Tensors of the CascaderGraph */\n  std::vector<Tensor> input_tensors_;\n  /*! \\brief The output Tensors of the CascaderGraph */\n  std::vector<Tensor> output_tensors_;\n  /*! \\brief The order of the Tensors in the CascaderGraph */\n  std::vector<Tensor> tensor_order_;\n  /*! \\brief The order of the Parts in the CascaderGraph */\n  std::vector<Part> part_order_;\n  /*! \\brief A map between Parts in the CascaderGraph and their IDs */\n  std::unordered_map<Part, int, ObjectPtrHash, ObjectPtrEqual> part_id_map_;\n  /*! \\brief A map between Tensors in the CascaderGraph and their IDs */\n  std::unordered_map<Tensor, int, ObjectPtrHash, ObjectPtrEqual> tensor_id_map_;\n};\n\n/*!\n * \\brief A class to describe a graph of Parts and Tensors used by the cascader.\n * \\note This class describes a graph consisting of two object types: Tensors and Parts.\n * It defines a topological ordering on the graph such that each Part and Tensor has a\n * position in the ordering. This ordering is used by the Plan and Proposal generation\n * algorithms. It is also the ordering the Parts are expected to be executed in.\n *\n * In addition to defining an ordering, the Parts and Tensors are also all given unique\n * IDs which they can be referred to by.\n */\nclass CascaderGraph : public ObjectRef {\n public:\n  CascaderGraph(std::vector<Tensor> input_tensors, std::vector<Tensor> output_tensors);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CascaderGraph, ObjectRef, CascaderGraphNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/pareto.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/pareto.h\n * \\brief Pareto optimisation functions for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PARETO_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PARETO_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n\n#include <algorithm>\n#include <array>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass Plan;\nclass MemoryRegion;\nclass Proposal;\n\n/*!\n * \\brief Determine the Pareto optimal points.\n * \\param costs The points as a vector of N-dimensional costs.\n * \\return A vector that is true where a point is Pareto optimal and false otherwise.\n */\ntemplate <int N>\nstd::vector<bool> GetParetoFrontier(const std::vector<std::array<float, N>>& costs);\n\n/*!\n * \\brief Evenly sample items from a vector to reduce its size.\n * \\param vec The vector to thin.\n * \\param max_size The maximum size of the thinned vector.\n * \\return The thinned vector.\n */\ntemplate <class T>\nstd::vector<T> ThinVector(const std::vector<T>& vec, size_t max_size);\n\n/*!\n * \\brief Cull plans which are not Pareto optimal then thin them down.\n * \\param plans The plans to apply the Pareto culling to.\n * \\param max_plans The maximum number of plans after the culling.\n * \\param disable_pareto_metric Whether to only select from Pareto frontier or not.\n * \\return The culled plans.\n * \\note Plan Pareto-optimality is determined based upon a Plan's memory_usage\n * and cycles.\n */\nstd::vector<Plan> ParetoCullPlans(std::vector<Plan> plans, size_t max_plans,\n                                  bool disable_pareto_metric);\n\nstd::vector<Proposal> ParetoCullProposals(std::vector<Proposal> proposals, size_t max_proposals,\n                                          bool disable_pareto_metric);\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PARETO_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/parts/ethosu.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/parts/ethosu.h\n * \\brief Arm(R) Ethos(TM)-U NPU Part object\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PARTS_ETHOSU_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PARTS_ETHOSU_H_\n\n#include <tvm/runtime/object.h>\n\n#include <vector>\n\n#include \"../block_config.h\"\n#include \"../graph.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\n/*! \\brief Node to represent an EthosuPart */\nclass EthosuPartNode : public PartNode {\n public:\n  /*!\n   * \\brief Get the optimal BlockConfig to use given a StripeConfig\n   * \\param output_stripe_config The output StripeConfig.\n   */\n  const BlockConfig GetBlockConfig(const StripeConfig& output_stripe_config);\n  /*!\n   * \\brief Get the preferred alignment in each axis for a stripe of the Part.\n   * \\note This is used to bias the selection of StripeConfigs towards those that are integer\n   * multiples of a tensor intrinsic used to compute the Part.\n   */\n  const std::vector<int> GetStripeAlignHint() const final { return output_quantum_; }\n  /*!\n   * \\brief Get the performance information for a given output stripe config.\n   * \\param output_stripe_config The output stripe config to compute the performance for.\n   * \\param buffer_mode The mode of buffering, rolling or recompute.\n   * \\return The performance information containing the compute cycles and read/write bytes.\n   */\n  const PerformanceInfo GetPerformanceInfo(const StripeConfig& output_stripe_config,\n                                           BufferMode buffer_mode) final;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.EthosuPart\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(EthosuPartNode, PartNode);\n\n protected:\n  friend class EthosuPart;\n\n  /*!\n   * \\brief Get the size of input required (per input tensor) to compute a stripe given a\n   * block_shape\n   * \\param block_shape The shape of the block(s) the stripe is split into\n   * \\param stripe_shape The shape of the full stripe to compute.\n   * \\return The bytes required per input tensor.\n   */\n  const std::vector<int64_t> GetBytesRead(const std::vector<int>& block_shape,\n                                          const std::vector<int>& full_shape);\n\n  /*!\n   * \\brief Get cost heuristic of using a given block config with the associated stripe config\n   * \\param block_config The block config that is being checked for the cost\n   * \\param output_stripe_config The striping configuration associated with the operator\n   * \\return A cost heuristic representative of the choice\n   */\n  float CalculateCost(const BlockConfig& block_config, const StripeConfig& output_stripe_config);\n\n  /*! \\brief List of block configs that are valid for this part */\n  std::vector<BlockConfig> valid_block_configs_;\n  /*! \\brief The output volume that is atomically computed */\n  std::vector<int> output_quantum_;\n  /*! \\brief Index for output height dimension */\n  int height_idx_;\n  /*! \\brief Index for output width dimension */\n  int width_idx_;\n  /*! \\brief Index of weight tensor, -1 if the Part has no weights */\n  int weight_tensor_idx_;\n  /*! \\brief Number of sub-kernels the kernel has been split into */\n  int subkernels_;\n};\n\n/*!\n * \\brief A class to describe a Part to be executed on an Arm(R) Ethos(TM)-U NPU.\n * \\note EthosuParts must be provided with an output quantum and the cycles taken to\n * compute an output quantum which depend on the operator the NPU is computing.\n */\nclass EthosuPart : public Part {\n public:\n  EthosuPart(const TESubgraph& subgraph, const std::vector<Propagator> propagators,\n             const std::vector<int>& output_quantum, int subkernels,\n             const std::vector<BlockConfig>& valid_block_configs, int weight_tensor_idx);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(EthosuPart, Part, EthosuPartNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PARTS_ETHOSU_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/parts/inline.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/parts/inline.h\n * \\brief Inline Part object\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PARTS_INLINE_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PARTS_INLINE_H_\n\n#include <tvm/runtime/object.h>\n\n#include <vector>\n\n#include \"../graph.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\n/*! \\brief Node to represent an inlined Part */\nclass InlinePartNode : public PartNode {\n public:\n  /*!\n   * \\brief Get the performance information for a given output stripe config.\n   * \\param output_stripe_config The output stripe config to compute the performance for.\n   * \\param is_rolling Whether the output config should be computed as a rolling buffer.\n   * \\return The performance information containing the compute cycles and read/write bytes.\n   */\n  const PerformanceInfo GetPerformanceInfo(const StripeConfig& output_stripe_config,\n                                           BufferMode buffer_mode) final;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.InlinePart\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(InlinePartNode, PartNode);\n\n protected:\n  friend class InlinePart;\n};\n\n/*!\n * \\brief A class to describe a inlined Part in a Cascader graph.\n * \\note Inlined Parts have a few special properties. First by IsInline being true,\n * the Cascader will not allocate any space for the outputs of the Part. This is because\n * they will be directly consumed as they are produced by the following Part. Second, they\n * are assumed to be 'free' and require no cycles to execute. Lastly, as they are 'free'\n * the compute quantum is arbitrary, but by convention it is a single tensor element.\n *\n * Examples of inline Parts include strided_slice, reshape and concatenate - all of which\n * get absorbed into the DMA functionality of Ethos-U compute primitives.\n */\nclass InlinePart : public Part {\n public:\n  InlinePart(const TESubgraph& subgraph, const std::vector<Propagator> propagators);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(InlinePart, Part, InlinePartNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PARTS_INLINE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/plan.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/plan.h\n * \\brief Plan object for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PLAN_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PLAN_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"graph.h\"\n#include \"tensor_config.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\n/*! \\brief Node to represent a Plan */\nclass PlanNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The TensorConfigs specified by the Plan */\n  const std::vector<TensorConfig>& GetTensorConfigs() const { return tensor_configs_; }\n  /*! \\return The TensorConfigs which are 'open' meaning they are a Plan input/output but have\n   * INTERIOR state */\n  const std::vector<TensorConfig>& GetOpenConfigs() const { return open_configs_; }\n  /*! \\return The TensorConfig of the Plan's output tensor */\n  const TensorConfig GetOutputConfig() const { return output_config_; }\n  /*! \\return The Parts which are covered by the Plan */\n  const std::vector<Part>& GetPartGroup() const { return part_group_; }\n  /*! \\return The memory region in which to store interior Plan buffers */\n  MemoryRegion const GetInteriorRegion() const { return interior_region_; }\n  /*!\n   * \\return The interior memory used by the Plan in bytes.\n   * \\note The interior memory usage is defined as being the memory required in the interior region\n   * to execute the Plan excluding input and output buffers.\n   */\n  int GetMemoryUsage() const { return memory_usage_; }\n  /*! \\return The cycles taken to execute the Plan */\n  int GetCycles() const { return cycles_; }\n  /*! \\return Whether the Plan is 'closed' meaning it has no 'open' TensorConfigs */\n  bool IsClosed() const { return open_configs_.size() == 0; }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.Plan\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PlanNode, Object);\n\n protected:\n  friend class Plan;\n\n  /*! \\brief The TensorConfigs specified by the Plan */\n  std::vector<TensorConfig> tensor_configs_;\n  /*! \\brief The TensorConfigs which are 'open' meaning they are a Plan input/output but have\n   * INTERIOR state */\n  std::vector<TensorConfig> open_configs_;\n  /*! \\brief The TensorConfig of the Plan's output tensor */\n  TensorConfig output_config_;\n  /*! \\brief The Parts which are covered by the Plan */\n  std::vector<Part> part_group_;\n  /*! \\brief The memory region in which to store interior Plan buffers */\n  MemoryRegion interior_region_;\n  /*! \\brief The interior memory used by the Plan in bytes */\n  int memory_usage_;\n  /*! \\brief The cycles taken to execute the Plan */\n  int cycles_;\n};\n\n/*!\n * \\brief A class which describes how to schedule a subgraph of Parts together.\n * \\note A Plan takes the form of a subgraph of connected Parts (recorded in part_group) with\n * TensorConfigs for all of the required Tensors (recorded in tensor_configs). This information can\n * be used to produce a Tensor Expression schedule with inter-operator scheduling. A Plan is\n * necessarily single-output such that all non-output Parts are 'computed_at'ed the scope of the\n * output Part. This is what achieves the technique referred to as 'cascading'. A Plan also has an\n * interior memory region which specifies the region of memory into which all the Plans intermediate\n * buffers should be allocated.\n *\n * Additionally, a Plan contains some other information used during the Plan generation and\n * selection algorithms. Both the memory and cycles required to run the Plan are accounted for so\n * that Plans can be ranked and Pareto-culled on these metrics. Furthermore, the TensorConfigs which\n * are 'open' is recorded indicating that these are valid points to merge with another Plan. A Plan\n * can only be turned into a schedule if it has no 'open' TensorConfigs - at which point the Plan is\n * said to be 'closed'.\n */\nclass Plan : public ObjectRef {\n public:\n  Plan(const std::vector<TensorConfig>& tensor_configs,\n       const std::vector<TensorConfig>& open_configs, const TensorConfig& output_config,\n       const std::vector<Part>& part_group, const MemoryRegion& interior_region, int memory_usage,\n       int cycles);\n  /*!\n   * \\brief Merge two Plans which share an 'open' TensorConfig.\n   * \\param other The Plan to merge with.\n   * \\return The merged Plan.\n   * \\note The current Plan is referred to as the 'upper Plan' and the other Plan as the 'lower\n   * Plan'. The 'open' output config of the upper Plan must be an 'open' input config of the lower\n   * Plan. The Tensor referenced by these configs is the Tensor on which the two Plans will be\n   * merged. The merge process does the following:\n   *\n   * The tensor config maps will be merged with TensorConfigs from the upper Plan taking priority.\n   * The open configs will be merged with the TensorConfigs that are being merged having been\n   * removed. The output config will be that of the lower Plan. The part groups will be merged. The\n   * interior region is necessarily the same for both the upper and lower Plan. The cycles and\n   * memory usage will be summed.\n   */\n  Plan Merge(const Plan& other) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Plan, ObjectRef, PlanNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n// Hash functions TensorConfig and Part sets\nnamespace std {\n\nusing TensorConfigSet = std::vector<::tvm::contrib::ethosu::cascader::TensorConfig>;\nusing PartSet = std::vector<::tvm::contrib::ethosu::cascader::Part>;\n\ntemplate <>\nstruct hash<TensorConfigSet> {\n  std::size_t operator()(const TensorConfigSet& tensor_config_set) const {\n    size_t seed = 0;\n    for (const auto& tensor_config : tensor_config_set) {\n      seed ^= hash<::tvm::contrib::ethosu::cascader::TensorConfig>()(tensor_config);\n    }\n    return seed;\n  }\n};\n\ntemplate <>\nstruct equal_to<TensorConfigSet> {\n  bool operator()(const TensorConfigSet& lhs, const TensorConfigSet& rhs) const {\n    std::unordered_set<::tvm::contrib::ethosu::cascader::TensorConfig> lh_set(lhs.begin(),\n                                                                              lhs.end());\n    std::unordered_set<::tvm::contrib::ethosu::cascader::TensorConfig> rh_set(rhs.begin(),\n                                                                              rhs.end());\n    return lh_set == rh_set;\n  }\n};\n\ntemplate <>\nstruct hash<PartSet> {\n  std::size_t operator()(const PartSet& part_set) const {\n    size_t seed = 0;\n    for (const auto& part : part_set) {\n      seed ^= tvm::runtime::ObjectHash()(part);\n    }\n    return seed;\n  }\n};\n\ntemplate <>\nstruct equal_to<PartSet> {\n  bool operator()(const PartSet& lhs, const PartSet& rhs) const { return lhs == rhs; }\n};\n\n}  // namespace std\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PLAN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/plan_generator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/plan_generator.h\n * \\brief Algorithm to generate possible Plans in the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PLAN_GENERATOR_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PLAN_GENERATOR_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass CascaderGraph;\nclass MemoryRegion;\nclass Part;\nclass Tensor;\nclass StripeConfig;\nclass Plan;\nclass CascaderOptions;\n\nusing HomeMap =\n    std::unordered_map<Tensor, std::vector<MemoryRegion>, ObjectPtrHash, ObjectPtrEqual>;\n\n/*!\n * \\brief Generate possible output StripeConfigs that could be applied to a Part's output.\n * \\param part The Part to generate StripeConfigs for.\n * \\param stripe_factors How many striping factors to try per axis.\n * \\param enable_striping Whether striping is enabled\n * \\param multi_dimensional Whether to stripe in more than one dimension.\n * \\return The generated StripeConfigs for the Part's output.\n */\nstd::vector<StripeConfig> GenerateOutputStripeConfigs(const Part& part, int stripe_factors,\n                                                      bool enable_striping, bool multi_dimensional);\n\n/*!\n * \\brief Generate single-Part Plans for a Part for a given list of output StripeConfigs.\n * \\param part The Part to generate Plans for.\n * \\param output_stripe_configs The output StripeConfigs to generate Plans with.\n * \\param home_map The Tensor homing map defining valid memory homes for Tensors.\n * \\param options The configuration options with which to run the generator.\n * \\return The generated Plans covering the Part.\n * \\note For each of the output StripeConfigs provided, this algorithm will produce a number\n * of Plans corresponding to different choices of Tensor homing/copying, buffer modes\n * and INTERIOR/BOUNDARY states. For each of these variants, the Part's performance will\n * be queried and the memory usage will be calculated.\n */\nstd::vector<Plan> GenerateSinglePlans(const Part& part,\n                                      const std::vector<StripeConfig>& output_stripe_configs,\n                                      const HomeMap& home_map, const CascaderOptions& options);\n\n/*!\n * \\brief Generate pareto optimal Plans for a Graph.\n * \\param graph The Graph to generate Plans for.\n * \\param home_map The Tensor homing map defining valid memory homes for Tensors.\n * \\param options The configuration options with which to run the generator.\n * \\return A map between Part groups and a list of pareto optimal Plans which cover that group.\n * \\note This algorithm does the following:\n *\n * Iterate Part-by-Part in a reversed topological ordering (starting at the output Parts and\n * working towards the input Parts).\n *\n * For each Part:\n *  1. Determine the possible StripeConfigs we might want to use to stripe the Part using\n *     GenerateOutputStripeConfigs.\n *  2. Additionally, collect all the StripeConfigs of open Plans that could connect to this\n *     Part (i.e. the Plan has an open TensorConfig for the Part's output Tensor).\n *  3. Use these two lists of StripeConfigs to produce single Part Plans with GenerateSinglePlans.\n *  4. For the generated Plans that have an open output TensorConfig, try and merge these into\n *     existing Plans which share an open input TensorConfig.\n *  5. All Plans are then indexed by both the Part group they cover and their open TensorConfigs.\n *  6. Plans which cover the same Part group and share the same open TensorConfigs are culled\n *     using ParetoCullPlans.\n *\n * Once every Part has been visited, return the Plans with no open TensorConfigs indexed by Part\n * group.\n */\nstd::unordered_map<std::vector<Part>, std::vector<Plan>> GenerateGraphPlans(\n    const CascaderGraph& graph, const HomeMap& home_map, const CascaderOptions& options);\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PLAN_GENERATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/propagator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/propagator.h\n * \\brief Propagator class for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PROPAGATOR_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PROPAGATOR_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass Propagator;\nclass StripeConfig;\n\n/*! \\brief Node to represent a Propagator */\nclass PropagatorNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The transform matrix to apply to the StripeConfigs */\n  const std::vector<std::vector<float>> GetTransform() const { return transform_; }\n  /*! \\return The offset vector to apply to the StripeConfigs */\n  const std::vector<int> GetOffset() const { return offset_; }\n  /*! \\return The number of input dimensions */\n  size_t GetInputDims() const { return offset_.size(); }\n  /*! \\return The number of output dimensions */\n  size_t GetOutputDims() const { return transform_[0].size() - 1; }\n  /*!\n   * \\brief Propagate a StripeConfig through the transform and offset matrices.\n   * \\param stripe_config The StripeConfig to propagate.\n   * \\return The transformed StripeConfig.\n   * \\note The propagation proceeds as follows:\n   *\n   * Both the stripe shape and extent have 1 appended to them (so they pick up\n   * constant factors from the affine transform) and are then multiplied by the\n   * transform matrix. The result is then ceil-rounded and has the trailing 1\n   * stripped to give the new shape and extent.\n   *\n   * The strides has 0 appended to it (so it doesn't pick up constant factors)\n   * and is then multiplied by the transform matrix. The trailing 0 is stripped.\n   *\n   * For the remaining three values we introduce the concept of the 'binarized'\n   * transform matrix. This is the transform matrix but with every non-zero element\n   * set to 1. It represents how axes get re-ordered as part of the propagation.\n   *\n   * [2,   0,   0, 1]            [1, 0, 0, 1]\n   * [0,   0, 0.4, 2]  binarize  [0, 0, 1, 1]\n   * [0, 1.5,   0, 0]   ---->    [0, 1, 0, 0]\n   * [0,   0,   0, 1]            [0, 0, 0, 1]\n   *\n   * The order has 0 appended to it and is multiplied by the 'binarized' transform\n   * matrix. The trailing 0 is then stripped.\n   *\n   * The stripes has 0 appended to it and multiplied by the 'binarized' transform\n   * matrix. The trailing 0 is then stripped and any remaining 0 elements that\n   * were introduced by the transform are set instead to 1.\n   *\n   * The stripe offset is multiplied by the 'binarized' transform matrix and is\n   * then summed with the propagator offset.\n   */\n  StripeConfig propagate(const StripeConfig& stripe_config) const;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.Propagator\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PropagatorNode, Object);\n\n protected:\n  friend class Propagator;\n\n  /*! \\brief The transform matrix to apply to the StripeConfigs */\n  std::vector<std::vector<float>> transform_;\n  /*! \\brief The offset vector to apply to the StripeConfigs */\n  std::vector<int> offset_;\n};\n\n/*!\n * \\brief A class to transform StripeConfigs according to the data dependencies\n between Part outputs and inputs. The dependency is represented as an affine\n transformation matrix + an offset vector. Using this, an output StripeConfig\n can be propagated through a Part to arrive at the input StripeConfigs.\n * \\note The transform matrix should be a 2D affine transform matrix.\n * As an example, consider a (1, 1, 2, 32) output stripe for an NHWC pooling\n * operation with a 3x3 pool size:\n *\n * [1, 0, 0, 0, 0]     [ 1]     [ 1]\n * [0, 1, 0, 0, 2]     [ 1]     [ 3]\n * [0, 0, 1, 0, 2]  x  [ 2]  =  [ 4]\n * [0, 0, 0, 1, 0]     [32]     [32]\n * [0, 0, 0, 0, 1]     [ 1]     [ 1]\n *\n * Using the appropriate affine matrix we see that the required input data to\n * produce that output stripe is a (1, 3, 4, 32) stripe. These matrices should\n * be derived for the Parts to relate input and output data dependencies.\n *\n * The offset is a 1D vector representing the first tensor element to read.\n * Often this is just the 0 element, but for an operator such as pad it may be\n * negative. For instance, a symmetric padding by 1 of a 2D tensor would require\n * the offset vector [-1, -1]. Additionally, positive offsets may be required\n * for operators like strided_slice where only part of a tensor is read from.\n */\nclass Propagator : public ObjectRef {\n public:\n  Propagator(const std::vector<std::vector<float>>& transform, const std::vector<int>& offset);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Propagator, ObjectRef, PropagatorNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PROPAGATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/proposal.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/proposal.h\n * \\brief Proposal object for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"graph.h\"\n#include \"plan.h\"\n#include \"tensor_config.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nusing MemoryUsageMap = std::unordered_map<MemoryRegion, int, ObjectPtrHash, ObjectPtrEqual>;\nusing TensorConfigMap = std::unordered_map<Tensor, TensorConfig, ObjectPtrHash, ObjectPtrEqual>;\n\n/*! \\brief Node to represent a Proposal */\nclass ProposalNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The CascaderGraph to which the Proposal applies */\n  const CascaderGraph GetGraph() const { return graph_; }\n  /*! \\return The Parts which are covered by the Proposal */\n  const std::vector<Part> GetPartGroup() const { return part_group_; }\n  /*! \\return The Plans used in the Proposal */\n  const std::vector<Plan> GetPlans() const { return plans_; }\n  /*! \\return The TensorConfigs indexed by Tensor in the Proposal which aren't produced by a Plan */\n  const TensorConfigMap GetInputTensorConfigs() const { return input_tensor_configs_; }\n  /*! \\return The MemoryRegion where cascading buffers should be homed */\n  const MemoryRegion GetCascadeRegion() const { return cascade_region_; }\n  /*! \\return The memory required to execute the Proposal in the cascading MemoryRegion */\n  const int GetMemoryUsage() const { return memory_usage_; }\n  /*! \\return The estimated cycles taken to execute the Proposal */\n  int GetCycles() const { return cycles_; }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.Proposal\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ProposalNode, Object);\n\n protected:\n  friend class Proposal;\n\n  /*! \\brief The CascaderGraph to which the Proposal applies */\n  CascaderGraph graph_;\n  /*! \\brief The Parts which are covered by the Proposal */\n  std::vector<Part> part_group_;\n  /*! \\brief The Plans used in the Proposal */\n  std::vector<Plan> plans_;\n  /*! \\brief The TensorConfigs indexed by Tensor in the Proposal which aren't produced by a Plan */\n  TensorConfigMap input_tensor_configs_;\n  /*! \\brief The MemoryRegion where cascading buffers should be homed */\n  MemoryRegion cascade_region_;\n  /*! \\brief The memory required to execute the Proposal in the cascading MemoryRegion */\n  int memory_usage_;\n  /*! \\brief The estimated cycles taken to execute the Proposal */\n  int cycles_;\n};\n\n/*!\n * \\brief A class which describes how to schedule a CascaderGraph as a series of disjoint Plans.\n */\nclass Proposal : public ObjectRef {\n public:\n  Proposal(const CascaderGraph& graph, const std::vector<Part>& part_group,\n           const std::vector<Plan>& plans, const TensorConfigMap& input_tensor_configs,\n           const MemoryRegion& cascade_region, int memory_usage, int cycles);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(Proposal, ObjectRef, ProposalNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/proposal_generator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/proposal_generator.h\n * \\brief Algorithm to generate possible Proposals in the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_GENERATOR_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_GENERATOR_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass CascaderGraph;\nclass MemoryRegion;\nclass Tensor;\nclass Proposal;\nclass CascaderOptions;\n\nusing HomeMap =\n    std::unordered_map<Tensor, std::vector<MemoryRegion>, ObjectPtrHash, ObjectPtrEqual>;\n\n/*!\n * \\brief Generate Pareto optimal Proposals for a CascaderGraph.\n * \\param graph The CascaderGraph to generate Proposals for.\n * \\param home_map The Tensor homing map defining valid memory homes for Tensors.\n * \\param options The configuration options with which to run the generator.\n * \\return A vector of Pareto optimal Proposals.\n * \\note This algorithm takes a top-down dynamic programming approach to determining how\n * to optimally combine Plans into Proposals. It does the following:\n *\n * First, run GenerateGraphPlans to generate the Pareto optimal Plans that cover all the\n * Part groups in the CascaderGraph.\n *\n * Solve the problem recursively, generating optimal Proposals for increasingly small\n * portions of the overall graph.\n *\n * Take the first Part in the graph:\n *   1. Find all the Plans for which the Part is both in the Plan's Part group and has the\n *      highest Part ID of any Part in the Part group (i.e. it's the 'first' Part in the\n *      group).\n *   For each Plan:\n *     2. Get the Part group covered by the Plan and subtract it from the 'total Part group'\n *        covering all the Parts. This forms a 'residual Part group'.\n *     3. Recursively, determine the optimal Proposals for the 'residual Part group' (the graph\n *        minus the Parts included in the Plan). Memoize the results.\n *     For each residual Proposal:\n *       4. Create a new Proposal by adding the current Plan to the residual Proposal.\n *   5. Pareto cull all the newly created Proposals (which all share the same Part group).\n * 6. Return the Proposals which cover all the Parts in the CascaderGraph.\n *\n */\nstd::vector<Proposal> GenerateProposals(const CascaderGraph& graph, const HomeMap& home_map,\n                                        const CascaderOptions& options);\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_PROPOSAL_GENERATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/stripe_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/stripe_config.h\n * \\brief StripeConfig object for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_STRIPE_CONFIG_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_STRIPE_CONFIG_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <map>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass StripeConfig;\nclass PropagatorNode;\n\n/*! \\brief Node to represent a StripeConfig */\nclass StripeConfigNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Get the shape of the stripe config.\n   * \\return The shape of the stripe config.\n   * \\note The shape refers to the size of the stripes in each dimension.\n   */\n  inline std::vector<int> GetShape() const { return shape_; }\n  /*!\n   * \\brief Get the extent of the stripe config.\n   * \\return The extent of the stripe config.\n   * \\note The extent refers to the extent over which a StripeConfig operates.\n   * Specifically, it is the extent in each axis between the lowest value read\n   * by a stripe and the highest value read by a stripe.\n   */\n  inline std::vector<int> GetExtent() const { return extent_; }\n  /*!\n   * \\brief Get the strides of the stripe config.\n   * \\return The strides of the stripe config.\n   * \\note The strides refer to the stride between stripes in each axis.\n   * The strides are represented as a float rather than an int to account for\n   * cases of 'fractional striding'. The stride should therefore be interpreted\n   * as the average striding in each axis.\n   *\n   * The starting offset of the i-th stripe in axis 'ax' is given by:\n   *\n   * stripe_offset_i[ax] = offset[ax] + floor(strides[ax]*i)\n   *\n   * As a concrete example, consider a 2x2 upscaling operation. If an output\n   * stripe config with a stride of (3, 3) is chosen, then when this is\n   * propagated to the input it will be reduced by a factor of two to become\n   * (1.5, 1.5).\n   *\n   * This means the first stripe in axis 0 should begin at (floor(1.5*0), 0) = (0, 0),\n   * the second at (floor(1.5*1), 0) = (1, 0), and the third at (floor(1.5*2), 0) =\n   * (3, 0). This results in irregular striding where 'strides' is the average\n   * striding value.\n   */\n  inline std::vector<float> GetStrides() const { return strides_; }\n  /*!\n   * \\brief Get the order of the stripe config.\n   * \\return The order of the stripe config.\n   * \\note The order refers to order in which the axes are iterated over.\n   * The first (outermost) axis is labelled as 1 with the rest increasing\n   * according to the axis' position. Any axis labelled with 0 isn't iterated over.\n   * For example, [1, 3, 2] would mean axis 0 is the outermost iteration axis,\n   * then axis 2, then finally axis 1.\n   */\n  inline std::vector<int> GetOrder() const { return order_; }\n  /*!\n   * \\brief Get the stripes of the stripe config.\n   * \\return The stripes of the stripe config.\n   * \\note The stripes refer to the number of stripes in each axis.\n   * There must be at least one stripe in any given axis.\n   */\n  inline std::vector<int> GetStripes() const { return stripes_; }\n  /*!\n   * \\brief Get the offset of the stripe config.\n   * \\return The offset of the stripe config.\n   * \\note The offset refers to the offset of the first stripe\n   * from the first element of the tensor. For example, in a slice operation\n   * which only returns the second (4, 8) half of a (8, 8) tensor, the offset\n   * would need to be [4, 0].\n   */\n  inline std::vector<int> GetOffset() const { return offset_; }\n  /*! \\return The hash of the StripeConfigNode */\n  size_t GetHash() const { return hash_; }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.StripeConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StripeConfigNode, Object);\n\n protected:\n  friend class StripeConfig;\n  friend class PropagatorNode;\n\n  /*! \\brief Compute the hash of the StripeConfigNode */\n  void ComputeHash_();\n\n  /*! \\brief The shape of the stripes */\n  std::vector<int> shape_;\n  /*! \\brief The extent of region to stripe over */\n  std::vector<int> extent_;\n  /*! \\brief The strides of the stripes */\n  std::vector<float> strides_;\n  /*! \\brief The order of the striping axes */\n  std::vector<int> order_;\n  /*! \\brief The number of stripes in each axis */\n  std::vector<int> stripes_;\n  /*! \\brief The offset of the first stripe */\n  std::vector<int> offset_;\n  /*! \\brief The hash of the StripeConfigNode */\n  std::size_t hash_{0};\n};\n\n/*!\n * \\brief An object to describe how a tensor should be computed as a series\n of n-dimensional tiles, or 'stripes'.\n * \\note The StripeConfig is a verbose way of specifying how to tile a tensor.\n * We can imagine taking a 2D tensor of size (12, 12) and wanting to compute\n * it in tiles of (4, 4). The tile is referred to as a stripe here to generalize\n * this to n-dimensional tiles.\n *\n * The size of that stripe in each axis is the 'shape'. The strides is how far\n * you should move between stripes, so also (4, 4) for a simple non-overlappping\n * tiling. However, we explore some overlapping scheduling options so shape != strides\n * in general. Note that the striding may be fractional, for instance (1.5, 1.5).\n * This means the first stripe should begin at (floor(1.5*0), 0) = (0, 0), the second\n * at (floor(1.5*1), 0) = (1, 0), and the third at (floor(1.5*2), 0) = (3, 0). This results\n * in slightly irregular striding where 'strides' should be interpreted as the average\n * striding value.\n *\n * The 'extent' is simply (12, 12), the region over which we're conducting our tiling.\n *\n * The 'order' tells us which axis to iterate over first and which second and the\n * 'stripes' tells us how many stripes we need to compute in each of those axes.\n *\n * Finally, the 'offset' tells us where to start the first stripe. In this simple\n * case the offset is just (0, 0), but in something like a slice operation we\n * may want to start part way through a tensor.\n */\nclass StripeConfig : public ObjectRef {\n public:\n  StripeConfig(const std::vector<int>& shape, const std::vector<int>& extent,\n               const std::vector<float>& strides, const std::vector<int>& order,\n               const std::vector<int>& stripes, const std::vector<int>& offset);\n  /*!\n   * \\brief Check if two StripeConfigs are equals to each other.\n   * \\param other StripeConfig to be checked.\n   * \\return Whether the two StripeConfigs equal each other.\n   */\n  bool operator==(const StripeConfig& other) const;\n\n  TVM_DEFINE_OBJECT_REF_METHODS(StripeConfig, ObjectRef, StripeConfigNode);\n};\n\n/*!\n * \\brief Count the number of stripes of each shape that are executed for a given\n StripeConfig.\n * \\param stripe_config The StripeConfig to count the stripes for.\n * \\param enable_sliding_window Whether to assume the sliding window optimization.\n * \\return A map between stripe shapes and the number of stripes of that shape that need\n * executing.\n * \\note If the StripeConfig were to split an (8, 8) tensor into (4, 4) stripes with\n * (4, 4) striding, then this function will return {(4, 4): 4} indicating that 4 (4, 4)\n * stripes will be executed. If instead an (8, 8) were striped using (5, 5) stripes\n * with (5, 5) striding, this function would return:\n *\n * {\n *   (5, 5): 1,\n *   (3, 5): 1,\n *   (5, 3): 1,\n *   (3, 3): 1,\n * }\n *\n * This is because some of the stripes will exceed the extent of the tensor and so only part\n * of them will need executing. Therefore, CountStripes will return the exact number of each\n * shape of stripe that is executed, accounting for edge and overlap behaviour which is not\n * explicit in the StripeConfig alone.\n */\nstd::map<std::vector<int>, int> CountStripes(const StripeConfig& stripe_config,\n                                             bool enable_sliding_window);\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n// Hash and equal function for StripeConfig\nnamespace std {\n\n/*! \\brief The equal_to function for tvm::contrib::ethosu::cascader::StripeConfig */\ntemplate <>\nstruct equal_to<::tvm::contrib::ethosu::cascader::StripeConfig> {\n  bool operator()(const ::tvm::contrib::ethosu::cascader::StripeConfig& lhs,\n                  const ::tvm::contrib::ethosu::cascader::StripeConfig& rhs) const {\n    return lhs == rhs;\n  }\n};\n\n/*! \\brief The hash function for tvm::contrib::ethosu::cascader::StripeConfig */\ntemplate <>\nstruct hash<::tvm::contrib::ethosu::cascader::StripeConfig> {\n  std::size_t operator()(\n      const ::tvm::contrib::ethosu::cascader::StripeConfig& stripe_config) const {\n    return stripe_config->GetHash();\n  }\n};\n\n}  // namespace std\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_STRIPE_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/ethosu/cascader/tensor_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/contrib/ethosu/cascader/tensor_config.h\n * \\brief TensorConfig object for the NPU cascader\n */\n#ifndef TVM_CONTRIB_ETHOSU_CASCADER_TENSOR_CONFIG_H_\n#define TVM_CONTRIB_ETHOSU_CASCADER_TENSOR_CONFIG_H_\n\n#include <tvm/node/reflection.h>\n#include <tvm/runtime/object.h>\n\n#include <functional>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"graph.h\"\n#include \"stripe_config.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace ethosu {\nnamespace cascader {\n\nclass MemoryRegionNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\brief The name of the region */\n  std::string name;\n  /*! \\brief The size of the region */\n  int size;\n  /*! \\brief The read bandwidth of the region in bytes per cycle */\n  int read_bandwidth;\n  /*! \\brief The write bandwidth of the region in bytes per cycle */\n  int write_bandwidth;\n  /*! \\brief The read bandwidth of the region in bytes per cycle */\n  int read_latency;\n  /*! \\brief The write bandwidth of the region in bytes per cycle */\n  int write_latency;\n  /*! \\brief Length of memory burst */\n  int burst_length;\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.MemoryRegion\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MemoryRegionNode, Object)\n};\n\nclass MemoryRegion : public ObjectRef {\n public:\n  MemoryRegion(std::string name, int size, int read_bandwidth, int write_bandwidth,\n               int read_latency, int write_latency, int burst_length) {\n    auto n = make_object<MemoryRegionNode>();\n    n->name = name;\n    n->size = size;\n    n->read_bandwidth = read_bandwidth;\n    n->write_bandwidth = write_bandwidth;\n    n->read_latency = read_latency;\n    n->write_latency = write_latency;\n    n->burst_length = burst_length;\n    data_ = std::move(n);\n  }\n\n  TVM_DEFINE_OBJECT_REF_METHODS(MemoryRegion, ObjectRef, MemoryRegionNode);\n};\n\n/*! \\brief The 'state' of a TensorConfig as used in the Plan generation algorithm.\n * BOUNDARY - Should describe a Plan input/output Tensor.\n * INTERIOR - Should describe an intermediate Tensor in a 'closed' Plan.\n */\nenum TensorConfigState { BOUNDARY, INTERIOR };\n\n/*! \\brief Node to represent a TensorConfig */\nclass TensorConfigNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  /*! \\return The Tensor the config applies to */\n  const Tensor GetTensor() const { return tensor_; }\n  /*! \\return The region where the tensor is allocated */\n  MemoryRegion GetHomeRegion() const { return home_region_; }\n  /*!\n   * \\return The state of the TensorConfig.\n   * \\note The TensorConfigState is only used as part of the Plan generation algorithm. For a Plan\n   * to be 'closed' (and therefore not subject to any further merging), all the TensorConfigs that\n   * describe Plan input or output Tensors must be in the 'BOUNDARY' state with the rest being\n   * 'INTERIOR'. If any of the input or output tensors are described by an 'INTERIOR' TensorConfig,\n   * then the Plan is 'open' and should be merged with other 'open' Plans until the result becomes\n   * 'closed'.\n   */\n  TensorConfigState GetState() const { return state_; }\n  /*!\n   * \\return The mode in which the buffer should be realized\n   * \\note There are multiple buffering strategies by which a tensor may be realized (computed).\n   * These affect the amount of recomputation necessary as well as the size of buffer required to\n   * store the tensor. See 'BufferMode' for a description of the allowable buffering modes.\n   */\n  BufferMode GetBufferMode() const { return buffer_mode_; }\n  /*!\n   * \\return Whether to copy the tensor.\n   * \\note While a tensor will originally reside in its home region, the TensorConfig may optionally\n   * specify that the tensor should be copied (according to the StripeConfigs) into another\n   * MemoryRegion. As an example for where this may be used, if a weights tensor initially resides\n   * in slow Flash memory then necessarily the home region will be Flash. However, if the weights\n   * values are used multiple times by a Part, it may be more performant to choose to copy the\n   * weights into a faster memory like SRAM.\n   */\n  bool DoCopy() const { return copy_tensor_; }\n  /*! \\return The region to copy the tensor to */\n  MemoryRegion GetCopyRegion() const {\n    if (!copy_tensor_) {\n      return home_region_;\n    }\n    return copy_region_;\n  }\n  /*!\n   * \\return The StripeConfigs with which to compute the tensor.\n   * \\note The StripeConfigs determine the order in which the elements of the tensor should be\n   * computed, including potentially computing them multiple times (recompute). Multiple\n   * StripeConfigs are used over just a single StripeConfig for the case where the tensor is\n   * consumed by two different Parts executing themselves with different StripeConfigs. In this\n   * case, there is a StripeConfig per consumer of the tensor.\n   */\n  const std::vector<StripeConfig> GetStripeConfigs() const { return stripe_configs_; }\n  /*!\n   * \\return The size of the buffer needed for the TensorConfig.\n   * \\note The size of buffer necessary to store a tensor being produced using the TensorConfig is\n   * not necessarily just the size of the tensor. In Plans, a tensor may be being produced and\n   * consumed in 'stripes' which are smaller than the full tensor. Therefore, the buffer necessary\n   * to store the tensor may only need to be as large as the stripe. The precise size of the buffer\n   * will depend both on the BufferMode and StripeConfigs (as well as, of course, the Tensor).\n   */\n  int GetBufferSize() const;\n  /*! \\return The hash of the TensorConfigNode */\n  size_t GetHash() const { return hash_; }\n\n  static constexpr const char* _type_key = \"contrib.ethosu.cascader.TensorConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorConfigNode, Object);\n\n protected:\n  friend class TensorConfig;\n\n  /*! \\brief Compute the hash of the TensorConfigNode */\n  void ComputeHash_();\n\n  /*! \\return The size of the recompute buffer needed*/\n  int GetRecomputeBufferSize_() const;\n  /*! \\return The size of the rolling buffer needed*/\n  int GetRollingBufferSize_() const;\n\n  /*! \\brief The Tensor the config applies to */\n  Tensor tensor_;\n  /*! \\brief The region where the tensor is allocated */\n  MemoryRegion home_region_;\n  /*! \\return The state of the TensorConfig */\n  TensorConfigState state_;\n  /*! \\brief The mode in which the buffer should be realized */\n  BufferMode buffer_mode_;\n  /*! \\return The StripeConfigs with which to compute the tensor */\n  std::vector<StripeConfig> stripe_configs_;\n  /*! \\brief Whether to copy the tensor */\n  bool copy_tensor_;\n  /*! \\brief The region to copy the tensor to */\n  MemoryRegion copy_region_;\n  /*! \\brief The hash of the TensorConfigNode */\n  size_t hash_{0};\n};\n\n/*!\n * \\brief A class which describes how to realize a Tensor.\n * \\note The TensorConfig describes both how a Tensor is scheduled (the order in which it's\n * produced/consumed) and how its allocated in memory (which region it should reside in and whether\n * it should be copied). For further detail on how TensorConfig stores this information, consult the\n * documentation of TensorConfigNode.\n */\nclass TensorConfig : public ObjectRef {\n public:\n  TensorConfig(const Tensor& tensor, const MemoryRegion& home_region, TensorConfigState state,\n               BufferMode buffer_mode, const std::vector<StripeConfig>& stripe_configs,\n               bool copy_tensor, const MemoryRegion& copy_region);\n  /*!\n   * \\brief Check if two TensorConfigs are equal to each other.\n   * \\param other TensorConfig to be checked.\n   * \\return Whether the two TensorConfigs equal each other.\n   */\n  bool operator==(const TensorConfig& other) const;\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(TensorConfig, ObjectRef, TensorConfigNode);\n};\n\n}  // namespace cascader\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace tvm\n\n// Hash and equal function for TensorConfig\nnamespace std {\n\n/*! \\brief The equal_to function for tvm::contrib::ethosu::cascader::TensorConfig */\ntemplate <>\nstruct equal_to<::tvm::contrib::ethosu::cascader::TensorConfig> {\n  bool operator()(const ::tvm::contrib::ethosu::cascader::TensorConfig& lhs,\n                  const ::tvm::contrib::ethosu::cascader::TensorConfig& rhs) const {\n    return lhs == rhs;\n  }\n};\n\n/*! \\brief The hash function for tvm::contrib::ethosu::cascader::TensorConfig */\ntemplate <>\nstruct hash<::tvm::contrib::ethosu::cascader::TensorConfig> {\n  std::size_t operator()(\n      const ::tvm::contrib::ethosu::cascader::TensorConfig& tensor_config) const {\n    return tensor_config->GetHash();\n  }\n};\n\n}  // namespace std\n\n#endif  // TVM_CONTRIB_ETHOSU_CASCADER_TENSOR_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/hybrid/codegen_hybrid.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_hybrid.h\n * \\brief Common utilities to generated C style code.\n */\n#ifndef TVM_CONTRIB_HYBRID_CODEGEN_HYBRID_H_\n#define TVM_CONTRIB_HYBRID_CODEGEN_HYBRID_H_\n\n#include <tvm/ir/name_supply.h>\n#include <tvm/target/codegen.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <map>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\n\nusing namespace te;\nusing namespace tir;\n/*!\n * \\brief A base class to generate Hybrid Script.\n *\n * **NOTE** CodeGenHybrid does not aim at generating Python scripts consumed by Python2/3.\n * For runtime support, please refer the decorator in ``tvm/python/hybrid/api.py``.\n */\nclass CodeGenHybrid : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,\n                      public StmtFunctor<void(const Stmt&)> {\n public:\n  /*!\n   * \\brief Dump the given function body to hybrid script.\n   * \\param stmt The function body to be dumped to hybrid script.\n   * \\param inputs Input tensors of this schedule.\n   * \\param outputs Output tensors of this schedule.\n   * \\param name The name of the function.\n   */\n  void DumpStmt(const Stmt& stmt, const Array<ObjectRef>& inputs, const Array<Tensor>& outputs,\n                const std::string& name = \"hybrid_func\");\n  /*!\n   * \\brief Finalize the compilation and return the code.\n   * \\return The code.\n   */\n  std::string Finish();\n  /*! \\brief Reserve keywords in avoid of name conflict. */\n  void ReserveKeywords();\n  /*!\n   * \\brief Print the Stmt n to CodeGenHybrid->stream\n   * \\param n The statement to be printed.\n   */\n  void PrintStmt(const Stmt& n) { this->VisitStmt(n); }\n  /*!\n   * \\brief Print the expression n(or its ssa id if in ssa mode) into os\n   * \\param n The expression to be printed.\n   * \\param os The output stream\n   */\n  void PrintExpr(const PrimExpr& n, std::ostream& os) { this->VisitExpr(n, os); }\n  /*!\n   * \\brief Same as PrintExpr, but simply returns result string\n   * \\param n The expression to be printed.\n   */\n  std::string PrintExpr(const PrimExpr& n) {\n    std::ostringstream os;\n    PrintExpr(n, os);\n    return os.str();\n  }\n  // expression\n  void VisitExpr_(const VarNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const LoadNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const BufferLoadNode* op, std::ostream& os) override;    // NOLINT(*)\n  void VisitExpr_(const LetNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const CallNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const ProducerLoadNode* op, std::ostream& os) override;  // NOLINT(*)\n  void VisitExpr_(const AddNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const SubNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const MulNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const DivNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const ModNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const FloorDivNode* op, std::ostream& os) override;      // NOLINT(*)\n  void VisitExpr_(const FloorModNode* op, std::ostream& os) override;      // NOLINT(*)\n  void VisitExpr_(const MinNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const MaxNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const EQNode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const NENode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const LTNode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const LENode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const GTNode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const GENode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const AndNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const OrNode* op, std::ostream& os) override;            // NOLINT(*)\n  void VisitExpr_(const CastNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const NotNode* op, std::ostream& os) override;           // NOLINT(*)\n  void VisitExpr_(const SelectNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const RampNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) override;     // NOLINT(*)\n  void VisitExpr_(const IntImmNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const FloatImmNode* op, std::ostream& os) override;      // NOLINT(*)\n  void VisitExpr_(const StringImmNode* op, std::ostream& os) override;     // NOLINT(*)\n  // statment\n  void VisitStmt_(const LetStmtNode* op) override;\n  void VisitStmt_(const StoreNode* op) override;\n  void VisitStmt_(const BufferStoreNode* op) override;\n  void VisitStmt_(const ProducerStoreNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const AllocateNode* op) override;\n  void VisitStmt_(const ProducerRealizeNode* op) override;\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const EvaluateNode* op) override;\n  void VisitStmt_(const SeqStmtNode* op) override;\n  /*!\n   * \\brief Print Type represetnation of type t.\n   * \\param t The type representation.\n   * \\param os The stream to print the ctype into\n   */\n  virtual void PrintType(DataType t, std::ostream& os);  // NOLINT(*)\n\n private:\n  /*! \\brief The current indent of the code dump. */\n  int indent_{0};\n  /*! \\brief The tab size of code indent. */\n  const int tab_{4};\n  /*! \\brief Print the current indent spaces. */\n  inline void PrintIndent();\n  /*! \\brief NameSupply for allocated ids.  */\n  NameSupply ids_allocated = NameSupply(\"\");\n  /*!\n   * \\brief Keys are either (tensors, value_index) or (variables, 0).\n   *        Values are the corresponding IDs.*/\n  std::map<std::pair<const Object*, int>, std::string> id_map_;\n  /*! \\brief Variables (keys) binded to the threads (values). */\n  std::map<const VarNode*, std::string> binds_;\n  /*! \\brief The output code string builder. */\n  std::stringstream stream;\n  /*!\n   * \\brief Get or allocate the ID for the given variable.\n   * \\param v The given variable.\n   */\n  std::string GetVarID(const VarNode* v);\n  /*!\n   * \\brief Get or allocate the ID for the given tensor.\n   * \\param tensor The tensor to allocate a name.\n   */\n  std::string GetTensorID(const Tensor& tensor);\n};\n\n}  // namespace contrib\n}  // namespace tvm\n#endif  // TVM_CONTRIB_HYBRID_CODEGEN_HYBRID_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/torch/base64.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file base64.h\n * \\brief Util functions for converting plain bytes back to plain bytes\n */\n\n#ifndef TVM_CONTRIB_TORCH_BASE64_H_\n#define TVM_CONTRIB_TORCH_BASE64_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <cctype>\n#include <cstdio>\n#include <string>\n\n#include \"../../support/base64.h\"\n\nnamespace tvm {\nnamespace support {\n\nsize_t b64strlen(const std::string b64str) {\n  ICHECK(b64str.size() % 4 == 0) << \"invalid base64 encoding\";\n  size_t length = b64str.size() / 4 * 3;\n  if (b64str[b64str.size() - 2] == '=') {\n    length -= 2;\n  } else if (b64str[b64str.size() - 1] == '=') {\n    length -= 1;\n  }\n  return length;\n}\n\nvoid b64decode(const std::string b64str, u_char* ret) {\n  size_t index = 0;\n  const auto length = b64str.size();\n  for (size_t i = 0; i < length; i += 4) {\n    int8_t ch0 = base64::DecodeTable[(int32_t)b64str[i]];\n    int8_t ch1 = base64::DecodeTable[(int32_t)b64str[i + 1]];\n    int8_t ch2 = base64::DecodeTable[(int32_t)b64str[i + 2]];\n    int8_t ch3 = base64::DecodeTable[(int32_t)b64str[i + 3]];\n    u_char st1 = (ch0 << 2) + (ch1 >> 4);\n    ret[index++] = st1;\n    if (b64str[i + 2] != '=') {\n      u_char st2 = ((ch1 & 0b1111) << 4) + (ch2 >> 2);\n      ret[index++] = st2;\n      if (b64str[i + 3] != '=') {\n        u_char st3 = ((ch2 & 0b11) << 6) + ch3;\n        ret[index++] = st3;\n      }\n    }\n  }\n  ICHECK(b64strlen(b64str) == index) << \"base64 decoding fails\";\n}\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_CONTRIB_TORCH_BASE64_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/torch/tvm_module_wrapper/runtime_bridge.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file runtime_bridge.h\n * \\brief Util functions for pytorch tvm interaction.\n */\n#ifndef TVM_CONTRIB_TORCH_TVM_MODULE_WRAPPER_RUNTIME_BRIDGE_H_\n#define TVM_CONTRIB_TORCH_TVM_MODULE_WRAPPER_RUNTIME_BRIDGE_H_\n\nextern \"C\" {\n\n/*\n * DLPack data structure extend with `is_bool` flag.\n * DLPack haven't support boolean tensor\n * (https://github.com/pytorch/pytorch/blob/4618371da56c887195e2e1d16dad2b9686302800/aten/src/ATen/DLConvertor.cpp#L42),\n * thus a boolean tensor will be regarded as a UInt8 tensor\n * (https://github.com/apache/tvm/blob/de124862714e747764aa8b7f41a90bcb25f3c6a8/python/tvm/_ffi/runtime_ctypes.py#L91).\n */\nstruct DLPackTensorExt {\n  DLManagedTensor* dl_managed_tensor;\n  bool is_bool;\n};\n\n/*\n * A wrapper pointing to TVM runtime module.\n */\nstruct TVMContribTorchRuntimeModule;\n\n/*\n * Obtain a saved runtime module passed by TVM FFI.\n * @return A TVM runtime module wrapper.\n */\nTVMContribTorchRuntimeModule* tvm_contrib_torch_get_last_saved_runtime_module();\n\n/*\n * Delete TVMContribTorchRuntimeModule pointer.\n */\nvoid tvm_contrib_torch_free_runtime_module(TVMContribTorchRuntimeModule* module_ptr);\n\n/*\n * Obtain ExecutorFactory runtime module from ExecutorFactory class.\n * @param graph_executor_factory ExecutorFactory class\n * @param input_example For obtaining device information\n * @return ExecutorFactory TVM runtime module wrapper\n */\nTVMContribTorchRuntimeModule* tvm_contrib_torch_create_graph_runtime_module(\n    TVMContribTorchRuntimeModule* graph_executor_factory, DLManagedTensor* input_example);\n\n/*\n * Forward method for OperatorModuleWrapper.\n * @param runtime_module TVM runtime module wrapper\n * @param inputs Array pointer of the input tensors\n * @param input_size The number of input tensors\n */\nvoid tvm_contrib_torch_operator_module_forward(TVMContribTorchRuntimeModule* runtime_module,\n                                               DLPackTensorExt* inputs, size_t input_size);\n\n/*\n * Forward method for GraphExecutorFactoryWrapper.\n * @param graph_executor_factory TVM runtime module wrapper\n * @param inputs Array pointer of the input tensors\n * @param input_size The number of input tensors\n * @param outputs The resulting output tensors pointer\n * @return The number of output tensors\n */\nsize_t tvm_contrib_torch_graph_executor_module_forward(\n    TVMContribTorchRuntimeModule* graph_executor_factory, DLPackTensorExt* inputs,\n    size_t input_size, DLPackTensorExt** outputs);\n\n/*\n * Encode TVM runtime module.\n * @param runtime_module TVM runtime module wrapper\n * @return The encoding stream (char array)\n */\nchar* tvm_contrib_torch_encode(TVMContribTorchRuntimeModule* runtime_module);\n\n/*\n * Decode TVM runtime module.\n * @param state The encoding stream (char array) of TVM runtime module\n * @return TVM runtime module wrapper\n */\nTVMContribTorchRuntimeModule* tvm_contrib_torch_decode(const char* state);\n\n/*\n * Delete DLPackTensorExt pointer.\n */\nvoid tvm_contrib_torch_free_dlpack_tensor_ext_array(DLPackTensorExt*);\n\n/*\n * Delete char array pointer.\n */\nvoid tvm_contrib_torch_free_encoding(char* encoding);\n\n/*\n * Checking if a DLPackTensorExt is boolean or cannot be copied in zero cost.\n */\nbool tvm_contrib_torch_tensor_ability_of_zero_copy(DLPackTensorExt*);\n}\n\n#endif  // TVM_CONTRIB_TORCH_TVM_MODULE_WRAPPER_RUNTIME_BRIDGE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/contrib/torch/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file utils.h\n * \\brief Util functions for pytorch tvm interaction.\n */\n\n#ifndef TVM_CONTRIB_TORCH_UTILS_H_\n#define TVM_CONTRIB_TORCH_UTILS_H_\n\n#include <dlpack/dlpack.h>\n#include <torch/script.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/device_api.h>\n#ifdef PT_TVMDSOOP_ENABLE_GPU\n#include <cuda_runtime.h>\n#endif\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace contrib {\nnamespace pytorch {\n\ninline bool GetTvmDtype(const caffe2::TypeMeta& dtype, DLDataType* res) noexcept {\n  if (dtype == torch::kFloat16) {\n    *res = {kDLFloat, 16, 1};\n  } else if (dtype == torch::kFloat32) {\n    *res = {kDLFloat, 32, 1};\n  } else if (dtype == torch::kFloat64) {\n    *res = {kDLFloat, 64, 1};\n  } else if (dtype == torch::kInt8) {\n    *res = {kDLInt, 8, 1};\n  } else if (dtype == torch::kInt16) {\n    *res = {kDLInt, 16, 1};\n  } else if (dtype == torch::kInt32) {\n    *res = {kDLInt, 32, 1};\n  } else if (dtype == torch::kInt64) {\n    *res = {kDLInt, 64, 1};\n  } else if (dtype == torch::kUInt8) {\n    *res = {kDLUInt, 8, 1};\n  } else if (dtype == torch::kBool) {\n    *res = {kDLInt, 1, 1};\n  } else {\n    return false;\n  }\n  return true;\n}\n\ninline bool GetTvmDtype(const caffe2::TypeMeta& dtype, tvm::runtime::DataType* res) noexcept {\n  DLDataType dlpack_dtype;\n\n  if (!GetTvmDtype(dtype, &dlpack_dtype)) {\n    return false;\n  }\n  *res = tvm::runtime::DataType(dlpack_dtype);\n  return true;\n}\n\ninline bool GetTorchDtype(const DLDataType& dtype, c10::ScalarType* res) noexcept {\n  if (dtype.lanes != 1) {\n    // only scalar type\n    return false;\n  }\n  if (dtype.code == kDLFloat) {\n    if (dtype.bits == 16) {\n      *res = torch::kFloat16;\n    } else if (dtype.bits == 32) {\n      *res = torch::kFloat32;\n    } else if (dtype.bits == 64) {\n      *res = torch::kFloat64;\n    } else {\n      return false;\n    }\n  } else if (dtype.code == kDLInt) {\n    if (dtype.bits == 16) {\n      *res = torch::kInt16;\n    } else if (dtype.bits == 32) {\n      *res = torch::kInt32;\n    } else if (dtype.bits == 64) {\n      *res = torch::kInt64;\n    } else if (dtype.bits == 1) {\n      *res = torch::kBool;\n    } else {\n      return false;\n    }\n  } else if (dtype.code == kDLUInt) {\n    if (dtype.bits == 8) {\n      *res = torch::kUInt8;\n    } else if (dtype.bits == 1) {\n      *res = torch::kBool;\n    } else {\n      return false;\n    }\n  } else {\n    return false;\n  }\n  return true;\n}\n\ninline bool GetTorchDtype(const tvm::runtime::DataType& dtype, c10::ScalarType* res) noexcept {\n  using tvm::runtime::DataType;\n  if (dtype == DataType::Float(16)) {\n    *res = torch::kFloat16;\n  } else if (dtype == DataType::Float(32)) {\n    *res = torch::kFloat32;\n  } else if (dtype == DataType::Float(64)) {\n    *res = torch::kFloat64;\n  } else if (dtype == DataType::Int(32)) {\n    *res = torch::kInt32;\n  } else if (dtype == DataType::Int(64)) {\n    *res = torch::kInt64;\n  } else if (dtype == DataType::Int(1)) {\n    *res = torch::kBool;\n  } else if (dtype == DataType::Int(8)) {\n    *res = torch::kInt8;\n  } else if (dtype == DataType::Int(16)) {\n    *res = torch::kInt16;\n  } else if (dtype == DataType::UInt(8)) {\n    *res = torch::kUInt8;\n  } else if (dtype == DataType::Bool()) {\n    *res = torch::kBool;\n  } else {\n    return false;\n  }\n  return true;\n}\n\n// Buffer information used for actual computation.\n// Each buffer is associated with one PyTorch tensor\n// whose underlying buffer is record into \"origin_buf\".\n// For input tensor, we copy data from origin_buf to buf\n// and for output tensor, copy data from buf to origin_buf\nclass TensorAsBuf {\n public:\n  explicit TensorAsBuf(const at::Tensor& tensor)\n      : pt_device_type_(tensor.device().type()),\n        device_id_(tensor.device().index()),\n        origin_shape_(tensor.sizes().begin(), tensor.sizes().end()) {\n    CHECK(pt_device_type_ == torch::kCUDA || pt_device_type_ == torch::kCPU);\n    device_type_ = (pt_device_type_ == torch::kCUDA ? kDLCUDA : kDLCPU);\n\n    char* buf = static_cast<char*>(tensor.data_ptr());\n    this->origin_buf_ = buf;\n    this->size_ = tensor.nbytes();\n\n    // const int alignment = 64;\n    const int alignment = tvm::runtime::kAllocAlignment;\n    char* aligned = reinterpret_cast<char*>(((uint64_t)buf + alignment - 1) & (~(alignment - 1)));\n    if (buf == aligned) {\n      this->tensor_ = tensor;\n      this->buf_ = buf;\n      this->offset_ = 0;\n    } else {\n      const auto options =\n          torch::TensorOptions().dtype(tensor.dtype()).device(pt_device_type_, device_id_);\n      this->inline_tensor_ =\n          torch::empty({static_cast<int64_t>(tensor.nbytes() + alignment)}, options);\n      this->tensor_ = this->inline_tensor_;\n\n      buf = static_cast<char*>(this->tensor_.data_ptr());\n      char* buf_aligned = reinterpret_cast<char*>(((uint64_t)buf + alignment) & (~(alignment - 1)));\n      this->buf_ = buf;\n      this->offset_ = buf_aligned - buf;\n    }\n  }\n\n  void CopyToOrigin() {\n    if (buf_ == origin_buf_) {\n      return;\n    }\n    if (device_type_ == kDLCPU) {\n      memcpy(origin_buf_, buf_ + offset_, size_);\n#ifdef PT_TVMDSOOP_ENABLE_GPU\n    } else if (device_type_ == kDLCUDA) {\n      cudaMemcpy(origin_buf_, buf_ + offset_, size_, cudaMemcpyDeviceToDevice);\n#endif\n    } else {\n      LOG(FATAL) << \"Only support CPU and CUDA now. Device \" << device_type_\n                 << \" is not implemented currently\";\n    }\n  }\n\n  void CopyFromOrigin() {\n    if (buf_ == origin_buf_) {\n      return;\n    }\n    if (device_type_ == kDLCPU) {\n      memcpy(buf_ + offset_, origin_buf_, size_);\n#ifdef PT_TVMDSOOP_ENABLE_GPU\n    } else if (device_type_ == kDLCUDA) {\n      cudaMemcpy(buf_ + offset_, origin_buf_, size_, cudaMemcpyDeviceToDevice);\n#endif\n    } else {\n      LOG(FATAL) << \"Only support CPU and CUDA now. Device \" << device_type_\n                 << \" is not implemented currently\";\n    }\n  }\n\n  // Create DLPack tensor from PyTorch tensor\n  void MakeDLTensor(DLTensor* out) {\n    const DLDevice dl_ctx{DLDeviceType(device_type_), device_id_};\n    DLDataType dlpack_type;\n    const auto& tensor = this->tensor_;\n    CHECK(GetTvmDtype(tensor.dtype(), &dlpack_type));\n\n    out->device = dl_ctx;\n    out->ndim = origin_shape_.size();\n    out->shape = origin_shape_.data();\n    out->strides = nullptr;\n    out->byte_offset = 0;\n    out->dtype = dlpack_type;\n    out->data = buf_ + offset_;\n  }\n\n  std::string DebugString() {\n    std::stringstream ss;\n    ss << \"dl device: \" << device_type_ << \"\\npt device: \" << static_cast<int>(pt_device_type_)\n       << \"\\ndevice_id: \" << device_id_ << \"\\nsize: \" << size_ << \"\\noffset: \" << offset_\n       << \"\\nshape:\";\n    for (auto dim : origin_shape_) {\n      ss << ' ' << dim;\n    }\n    ss << std::endl;\n    return ss.str();\n  }\n\n private:\n  DLDeviceType device_type_;\n  c10::DeviceType pt_device_type_;\n  int device_id_;\n\n  at::Tensor inline_tensor_;\n  at::Tensor tensor_;\n  size_t size_;\n  size_t offset_;\n\n  std::vector<int64_t> origin_shape_;\n\n  char* origin_buf_;\n  char* buf_;\n};\n}  // namespace pytorch\n}  // namespace contrib\n}  // namespace tvm\n#endif  // TVM_CONTRIB_TORCH_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/driver/internal_driver_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/driver/driver_api.h\n * \\brief Internal compiler driver APIs to drive the compilation.\n *\n * This module provides functionality that may be called internally\n * within TVM, but is not part of the public-facing API.\n */\n#ifndef TVM_DRIVER_INTERNAL_DRIVER_API_H_\n#define TVM_DRIVER_INTERNAL_DRIVER_API_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\n\n/*!\n * \\brief Build a device and host module for a specific target from a map\n * contains target to IRModule. This function is used\n * for heterogeneous build.\n * \\param input The map contains target to an IRModule.\n * \\param target_host The target for building host code. To use the default,\n *        pass Target().\n * \\return The built module that contains code for different processors.\n */\nruntime::Module TIRToRuntime(const Map<Target, IRModule>& input, const Target& target_host);\n\n}  // namespace tvm\n\n#endif  // TVM_DRIVER_INTERNAL_DRIVER_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/ir/attr_functor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file attr_functor.h\n * \\brief A way to define arbitrary function signature\n *        with dispatch on common attributes.\n *\n * Common attributes include:\n *  - int, float, str constants\n *  - array of attributes\n *  - map of attributes\n */\n#ifndef TVM_IR_ATTR_FUNCTOR_H_\n#define TVM_IR_ATTR_FUNCTOR_H_\n\n#include <tvm/node/functor.h>\n#include <tvm/tir/expr.h>\n\n#include <utility>\n\nnamespace tvm {\n\ntemplate <typename FType>\nclass AttrFunctor;\n\n#define ATTR_FUNCTOR_DEFAULT \\\n  { return VisitAttrDefault_(op, std::forward<Args>(args)...); }\n\n#define ATTR_FUNCTOR_DISPATCH(OP)                                                          \\\n  vtable.template set_dispatch<OP>([](const ObjectRef& n, TSelf* self, Args... args) {     \\\n    return self->VisitAttr_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \\\n  });\n\n// A functor for common attribute information.\ntemplate <typename R, typename... Args>\nclass AttrFunctor<R(const ObjectRef& n, Args...)> {\n private:\n  using TSelf = AttrFunctor<R(const ObjectRef& n, Args...)>;\n  using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;\n\n public:\n  /*! \\brief the result type of this functor */\n  using result_type = R;\n  /*! \\brief virtual destructor */\n  virtual ~AttrFunctor() {}\n  /*!\n   * \\brief The functor call.\n   * \\param n The expression node.\n   * \\param args Additional arguments.\n   * \\return The result of the call\n   */\n  virtual R VisitAttr(const ObjectRef& n, Args... args) {\n    static FType vtable = InitVTable();\n    if (vtable.can_dispatch(n)) {\n      return vtable(n, this, std::forward<Args>(args)...);\n    } else {\n      return VisitAttrDefault_(n.get(), std::forward<Args>(args)...);\n    }\n  }\n  virtual R VisitAttrDefault_(const Object* node, Args... args) = 0;\n  virtual R VisitAttr_(const ArrayNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::IntImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::FloatImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::StringImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  // deep comparison of symbolic integer expressions.\n  virtual R VisitAttr_(const tir::VarNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::SizeVarNode* op, Args... args) {\n    return VisitAttr_(static_cast<const tir::VarNode*>(op), std::forward<Args>(args)...);\n  }\n  virtual R VisitAttr_(const tir::AddNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::SubNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::MulNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::DivNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::ModNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::FloorDivNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::FloorModNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::MinNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::MaxNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::GENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::GTNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::LTNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::LENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::EQNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::NENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::AndNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::OrNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::NotNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::CastNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::CallNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n  virtual R VisitAttr_(const tir::SelectNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;\n\n private:\n  // initialize the vtable.\n  static FType InitVTable() {\n    using namespace tir;\n    FType vtable;\n    // Set dispatch\n    ATTR_FUNCTOR_DISPATCH(ArrayNode);\n    ATTR_FUNCTOR_DISPATCH(IntImmNode);\n    ATTR_FUNCTOR_DISPATCH(FloatImmNode);\n    ATTR_FUNCTOR_DISPATCH(StringImmNode);\n    ATTR_FUNCTOR_DISPATCH(VarNode);\n    ATTR_FUNCTOR_DISPATCH(SizeVarNode);\n    ATTR_FUNCTOR_DISPATCH(AddNode);\n    ATTR_FUNCTOR_DISPATCH(SubNode);\n    ATTR_FUNCTOR_DISPATCH(MulNode);\n    ATTR_FUNCTOR_DISPATCH(DivNode);\n    ATTR_FUNCTOR_DISPATCH(ModNode);\n    ATTR_FUNCTOR_DISPATCH(FloorDivNode);\n    ATTR_FUNCTOR_DISPATCH(FloorModNode);\n    ATTR_FUNCTOR_DISPATCH(MinNode);\n    ATTR_FUNCTOR_DISPATCH(MaxNode);\n    ATTR_FUNCTOR_DISPATCH(GENode);\n    ATTR_FUNCTOR_DISPATCH(GTNode);\n    ATTR_FUNCTOR_DISPATCH(LENode);\n    ATTR_FUNCTOR_DISPATCH(LTNode);\n    ATTR_FUNCTOR_DISPATCH(EQNode);\n    ATTR_FUNCTOR_DISPATCH(NENode);\n    ATTR_FUNCTOR_DISPATCH(AndNode);\n    ATTR_FUNCTOR_DISPATCH(OrNode);\n    ATTR_FUNCTOR_DISPATCH(NotNode);\n    ATTR_FUNCTOR_DISPATCH(CastNode);\n    ATTR_FUNCTOR_DISPATCH(CallNode);\n    ATTR_FUNCTOR_DISPATCH(SelectNode);\n    return vtable;\n  }\n};\n\n}  // namespace tvm\n#endif  // TVM_IR_ATTR_FUNCTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/meta_schedule/module_equality.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_MODULE_EQUALITY_H_\n#define TVM_META_SCHEDULE_MODULE_EQUALITY_H_\n\n#include <tvm/ir/module.h>\n\n#include <memory>\n#include <string>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*! \\brief Method to compute hash and determine equality of modules  */\nclass ModuleEquality {\n public:\n  virtual ~ModuleEquality() = default;\n\n  virtual size_t Hash(IRModule mod) const = 0;\n  virtual bool Equal(IRModule lhs, IRModule rhs) const = 0;\n\n  /*!\n   * \\brief Create a ModuleEquality instance\n   * \\param mod_eq_name A string to specify the module equality testing and hashing method.\n   *  It must be one of the followings:\n   *    - \"structural\": Use StructuralEqual/Hash\n   *    - \"ignore-ndarray\": Same as \"structural\", but ignore ndarray raw data during\n   *                        equality testing and hashing.\n   *    - \"anchor-block\": Apply equality testing and hashing on the anchor block extracted from a\n   *                      given module. The \"ignore-ndarray\" varint is used for the extracted blocks\n   *                      or in case no anchor block is found.\n   *                      For the definition of the anchor block, see tvm/tir/analysis.h.\n   * \\return An owning pointer to the created instance\n   */\n  static std::unique_ptr<ModuleEquality> Create(const std::string& mod_eq_name);\n};\n\n/*! \\brief Functor to compute hash a module using the provided method. */\nclass ModuleHash {\n public:\n  explicit ModuleHash(const ModuleEquality& mod_eq) : mod_eq_(mod_eq) {}\n  size_t operator()(const IRModule& mod) const { return mod_eq_.Hash(mod); }\n\n private:\n  const ModuleEquality& mod_eq_;\n};\n\n/*! \\brief Functor to determine equality of modules using the provided method. */\nclass ModuleEqual {\n public:\n  explicit ModuleEqual(const ModuleEquality& mod_eq) : mod_eq_(mod_eq) {}\n  bool operator()(const IRModule& lhs, const IRModule& rhs) const {\n    return mod_eq_.Equal(lhs, rhs);\n  }\n\n private:\n  const ModuleEquality& mod_eq_;\n};\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_MODULE_EQUALITY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/meta_schedule/schedule_rule/multi_level_tiling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_SCHEDULE_RULE_MULTI_LEVEL_TILING_H_\n#define TVM_META_SCHEDULE_SCHEDULE_RULE_MULTI_LEVEL_TILING_H_\n\n#include <tvm/meta_schedule/schedule_rule.h>\n#include <tvm/tir/schedule/schedule.h>\n\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../../support/array.h\"\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*!\n * \\brief Configuration of data reuse type:\n * 0) kNoReuse: no reuse is allowed, then no cache_read/write is performed.\n * 1) kMayReuse: reuse is allowed, but no reuse is explored.\n * 2) kMustReuse: reuse is allowed and no reuse is not explored.\n */\nenum class ReuseType : int32_t {\n  kNoReuse = 0,\n  kMayReuse = 1,\n  kMustReuse = 2,\n};\n\n/*!\n * \\brief Converts a string to ReuseType.\n * \\param str The string to be converted.\n * \\return The converted ReuseType.\n */\ninline ReuseType Str2ReuseType(const String& str) {\n  if (str == \"no\") {\n    return ReuseType::kNoReuse;\n  } else if (str == \"may\") {\n    return ReuseType::kMayReuse;\n  } else if (str == \"must\") {\n    return ReuseType::kMustReuse;\n  } else {\n    LOG(FATAL) << \"ValueError: Unknown ReuseType: \" << str;\n    throw;\n  }\n}\n\n/*! \\brief Configuration of data reuse patterns */\nstruct ReuseConfig {\n  /*! \\brief Type of data reuse: no-reuse, may-reuse or must-reuse */\n  ReuseType req;\n  /*! \\brief Which levels are caching stage inserted at */\n  std::vector<int> levels;\n  /*! \\brief The storage scope */\n  String scope;\n\n  /*! \\brief Default constructor: no data reuse */\n  ReuseConfig() : req(ReuseType::kNoReuse) {}\n\n  /*! \\brief Construct from a configuration dictionary */\n  explicit ReuseConfig(const Map<String, ObjectRef>& config)\n      : req(Str2ReuseType(Downcast<String>(config.at(\"req\")))),\n        levels(support::AsVector<Integer, int>(Downcast<Array<Integer>>(config.at(\"levels\")))),\n        scope(Downcast<String>(config.at(\"scope\"))) {\n    ICHECK_EQ(config.size(), 3);\n  }\n};\n\n// Forware declaration\nclass State;\n\n/*! \\brief The state of auto scheduling for the multi-level tiling rule */\nclass StateNode : public Object {\n public:\n  /*! \\brief The schedule to date */\n  tir::Schedule sch;\n  /*! \\brief The block to be tiled */\n  tir::BlockRV block_rv;\n  /*! \\brief The loop tiles */\n  Array<Array<tir::LoopRV>> tiles;\n  /*! \\brief The mapping from buffer index to read cache block. */\n  std::unordered_map<int, tir::BlockRV> read_reuse;\n  /*! \\brief The mapping from buffer index to write cache block. */\n  std::unordered_map<int, tir::BlockRV> write_reuse;\n\n  /*!\n   * \\brief Create a copy of the state. The underlying schedule is copied. Schedule rules that\n   * produce multiple states should use this method to create new states.\n   */\n  virtual State Copy() const;\n\n  static constexpr const char* _type_key = \"meta_schedule.State\";\n  TVM_DECLARE_BASE_OBJECT_INFO(StateNode, Object);\n};\n\n/*! \\brief Managed reference to StateNode */\nclass State : public ObjectRef {\n public:\n  /*! \\brief Default constructor */\n  explicit State(tir::Schedule sch, tir::BlockRV block_rv, Array<Array<tir::LoopRV>> tiles = {});\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(State, ObjectRef, StateNode);\n};\n\n/*!\n * \\brief Helper to apply a sub-rule to a list of auto scheduling states\n * \\tparam FLambda The type of the sub-rule functor\n * \\param states The list of states to be applied\n * \\return The list of states after applying the sub-rule\n */\ntemplate <class FLambda>\nstd::vector<State> SubRule(std::vector<State> states, FLambda sub_rule) {\n  std::vector<State> results;\n  for (auto&& state : states) {\n    std::vector<State> next = sub_rule(std::move(state));\n    results.insert(results.end(),                          //\n                   std::make_move_iterator(next.begin()),  //\n                   std::make_move_iterator(next.end()));\n  }\n  return results;\n}\n\n/*!\n * \\brief The mega rule: multi-level tiling with data reuse\n */\nclass MultiLevelTilingNode : public ScheduleRuleNode {\n public:\n  virtual ~MultiLevelTilingNode() = default;\n\n  // SubRule 1. add write cache\n  std::vector<State> AddWriteReuse(State state) const;\n  // SubRule 2. tile the loop nest\n  std::vector<State> TileLoopNest(State state) const;\n  // SubRule 3. add read cache\n  std::vector<State> AddReadReuse(State state) const;\n\n  // Do nothing; Inherited from ScheduleRuleNode\n  void InitializeWithTuneContext(const TuneContext& context) final;\n\n  // Entry of the mega rule; Inherited from ScheduleRuleNode\n  Array<tir::Schedule> Apply(const tir::Schedule& sch, const tir::BlockRV& block_rv) override;\n\n  // Inherited from ScheduleRuleNode\n  ScheduleRule Clone() const override;\n\n protected:\n  virtual std::vector<State> ApplySubRules(std::vector<State> states);\n\n  virtual Array<tir::LoopRV> SplitLoop(const tir::Schedule& sch, tir::BlockRV block,\n                                       tir::LoopRV loop, int n_tiles) const;\n\n  // Annotate a block to use cooperative fetching\n  void AnnotateCooperativeFetching(tir::Schedule* sch, const tir::BlockRV& block) const;\n\n public:\n  /*!\n   * \\brief The tiling structure. Recommended:\n   * - 'SSRSRS' on CPU\n   * - 'SSSRRSRS' on GPU\n   */\n  String structure;\n  /*! \\brief For each level of tiles, which thread axis it is bound to */\n  Array<String> tile_binds;\n  /*! \\brief The maximum size of the innermost factor */\n  int max_innermost_factor;\n  /*! \\brief The length of vector lane in vectorized cooperative fetching */\n  std::vector<int> vector_load_lens;\n  /*! \\brief Data reuse configuration for reading */\n  ReuseConfig reuse_read_;\n  /*! \\brief Data reuse configuration for writing */\n  ReuseConfig reuse_write_;\n  /*! \\brief The indices of spatial tiles in `structure` */\n  std::vector<int> s_indices_;\n  /*! \\brief The indices of reduction tiles in `structure` */\n  std::vector<int> r_indices_;\n  /*! \\brief The size of the thread warp */\n  int thread_warp_size_;\n  /*! \\brief The maximum number of threads to be used size of a thread warp */\n  int max_threads_per_block_;\n  /*! \\brief The logging function */\n  PackedFunc logger;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"structure\", &structure);\n    v->Visit(\"tile_binds\", &tile_binds);\n    v->Visit(\"max_innermost_factor\", &max_innermost_factor);\n    // `vector_load_lens` is not visited\n    // `reuse_read_` is not visited\n    // `reuse_write_` is not visited\n    // `s_indices_` is not visited\n    // `r_indices_` is not visited\n    // `thread_warp_size_` is not visited\n    // `max_threads_per_block` is not visited\n  }\n\n  static constexpr const char* _type_key = \"meta_schedule.MultiLevelTiling\";\n  TVM_DECLARE_BASE_OBJECT_INFO(MultiLevelTilingNode, ScheduleRuleNode);\n};\n\ntemplate <typename NodeType>\nObjectPtr<NodeType> MultiLevelTilingInitCommon(String structure, Optional<Array<String>> tile_binds,\n                                               Optional<Integer> max_innermost_factor,\n                                               Optional<Array<Integer>> vector_load_lens,\n                                               Optional<Map<String, ObjectRef>> reuse_read,\n                                               Optional<Map<String, ObjectRef>> reuse_write) {\n  ObjectPtr<NodeType> n = make_object<NodeType>();\n  n->structure = structure;\n  n->tile_binds = tile_binds.value_or({});\n  n->max_innermost_factor = max_innermost_factor.value_or(Integer(-1))->value;\n  n->vector_load_lens = vector_load_lens.defined()\n                            ? support::AsVector<Integer, int>(vector_load_lens.value())\n                            : std::vector<int>();\n  n->reuse_read_ = reuse_read.defined() ? ReuseConfig(reuse_read.value()) : ReuseConfig();\n  n->reuse_write_ = reuse_write.defined() ? ReuseConfig(reuse_write.value()) : ReuseConfig();\n  for (int i = 0, len = structure.size(); i < len; ++i) {\n    char c = structure.data()[i];\n    if (c == 'S') {\n      n->s_indices_.push_back(i);\n    } else if (c == 'R') {\n      n->r_indices_.push_back(i);\n    } else {\n      LOG(FATAL) << \"ValueError: Invalid tiling structure: \" << structure;\n    }\n  }\n  n->thread_warp_size_ = -1;\n  n->max_threads_per_block_ = -1;\n  return n;\n}\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_SCHEDULE_RULE_MULTI_LEVEL_TILING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/meta_schedule/trace_apply.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_TRACE_APPLY_H_\n#define TVM_META_SCHEDULE_TRACE_APPLY_H_\n\n#include <tvm/meta_schedule/schedule_rule.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/trace.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*!\n * \\brief Apply the trace from a TIR module whose anchor block is the same but fused elemewise\n * op blocks differ. This function can be used for transferring a trace tuned on a conv2d -> add\n * subgraph to other subgraphs having the same conv2d workload, for example. We call such trace\n * an \"anchor trace\". Those blocks that are not scheduled by the given anchor trace will be either\n * inlined or parallelized.\n * \\param sch The schedule to apply the anchor trace.\n * \\param anchor_trace The trace tuned on other subgraph with the same anchor-block workload.\n * \\param target The target information needed for inlining and parallelization.\n */\nvoid ScheduleUsingAnchorTrace(tir::Schedule sch, const tir::Trace& anchor_trace,\n                              const tvm::Target& target);\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_TRACE_APPLY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/meta_schedule/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_META_SCHEDULE_UTILS_H_\n#define TVM_META_SCHEDULE_UTILS_H_\n\n#include <dmlc/memory_io.h>\n#include <tvm/arith/analyzer.h>\n#include <tvm/meta_schedule/arg_info.h>\n#include <tvm/meta_schedule/builder.h>\n#include <tvm/meta_schedule/cost_model.h>\n#include <tvm/meta_schedule/database.h>\n#include <tvm/meta_schedule/extracted_task.h>\n#include <tvm/meta_schedule/feature_extractor.h>\n#include <tvm/meta_schedule/measure_callback.h>\n#include <tvm/meta_schedule/profiler.h>\n#include <tvm/meta_schedule/runner.h>\n#include <tvm/meta_schedule/schedule_rule.h>\n#include <tvm/meta_schedule/search_strategy.h>\n#include <tvm/meta_schedule/space_generator.h>\n#include <tvm/meta_schedule/task_scheduler.h>\n#include <tvm/meta_schedule/tune_context.h>\n#include <tvm/node/node.h>\n#include <tvm/node/serialization.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/support/parallel_for.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/transform.h>\n\n#include <algorithm>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../printer/text_printer.h\"\n#include \"../support/array.h\"\n#include \"../support/base64.h\"\n#include \"../support/nd_int_set.h\"\n#include \"../support/table_printer.h\"\n#include \"../support/utils.h\"\n#include \"../tir/schedule/primitive.h\"\n#include \"../tir/schedule/utils.h\"\n\n#define TVM_PY_LOG(logging_level, logger)                                \\\n  ::tvm::meta_schedule::PyLogMessage(__FILE__, __LINE__, logger,         \\\n                                     PyLogMessage::Level::logging_level) \\\n      .stream()\n#define TVM_PY_LOG_CLEAR_SCREEN(logging_func) clear_logging(__FILE__, __LINE__, logging_func)\n\nnamespace tvm {\nnamespace meta_schedule {\n\n/*!\n * \\brief Class to accumulate an log message on the python side. Do not use directly, instead use\n * TVM_PY_LOG(DEBUG), TVM_PY_LOG(INFO), TVM_PY_LOG(WARNING), TVM_PY_ERROR(ERROR).\n * \\sa TVM_PY_LOG\n * \\sa TVM_PY_LOG_CLEAR_SCREEN\n */\nclass PyLogMessage {\n public:\n  enum class Level : int32_t {\n    CLEAR = -10,\n    DEBUG = 10,\n    INFO = 20,\n    WARNING = 30,\n    ERROR = 40,\n    // FATAL not included\n  };\n\n  explicit PyLogMessage(const char* filename, int lineno, PackedFunc logger, Level logging_level)\n      : filename_(filename), lineno_(lineno), logger_(logger), logging_level_(logging_level) {}\n\n  TVM_NO_INLINE ~PyLogMessage() {\n    ICHECK(logging_level_ != Level::CLEAR)\n        << \"Cannot use CLEAR as logging level in TVM_PY_LOG, please use TVM_PY_LOG_CLEAR_SCREEN.\";\n    if (this->logger_ != nullptr) {\n      logger_(static_cast<int>(logging_level_), std::string(filename_), lineno_, stream_.str());\n    } else {\n      if (logging_level_ == Level::INFO) {\n        runtime::detail::LogMessage(filename_, lineno_, TVM_LOG_LEVEL_INFO).stream()\n            << stream_.str();\n      } else if (logging_level_ == Level::WARNING) {\n        runtime::detail::LogMessage(filename_, lineno_, TVM_LOG_LEVEL_WARNING).stream()\n            << stream_.str();\n      } else if (logging_level_ == Level::ERROR) {\n        runtime::detail::LogMessage(filename_, lineno_, TVM_LOG_LEVEL_ERROR).stream()\n            << stream_.str();\n      } else if (logging_level_ == Level::DEBUG) {\n        runtime::detail::LogMessage(filename_, lineno_, TVM_LOG_LEVEL_DEBUG).stream()\n            << stream_.str();\n      } else {\n        runtime::detail::LogFatal(filename_, lineno_).stream() << stream_.str();\n      }\n    }\n  }\n  std::ostringstream& stream() { return stream_; }\n\n private:\n  const char* filename_;\n  int lineno_;\n  std::ostringstream stream_;\n  PackedFunc logger_;\n  Level logging_level_;\n};\n\n/*!\n * \\brief Whether the tuning is running on ipython kernel.\n * \\return A boolean indicating whether ipython kernel is used.\n */\ninline bool using_ipython() {\n  bool flag = false;\n  const auto* f_using_ipython = runtime::Registry::Get(\"meta_schedule.using_ipython\");\n  if (f_using_ipython) {\n    flag = (*f_using_ipython)();\n  }\n  return flag;\n}\n\n/*!\n * \\brief Print out the performance table interactively in jupyter notebook.\n * \\param str The serialized performance table.\n */\ninline void print_interactive_table(const String& data) {\n  const auto* f_print_interactive_table =\n      runtime::Registry::Get(\"meta_schedule.print_interactive_table\");\n  ICHECK(f_print_interactive_table->defined())\n      << \"Cannot find print_interactive_table function in registry.\";\n  (*f_print_interactive_table)(data);\n}\n\n/*!\n * \\brief A helper function to clear logging output for ipython kernel and console.\n * \\param file The file name.\n * \\param lineno The line number.\n * \\param logging_func The logging function.\n */\ninline void clear_logging(const char* file, int lineno, PackedFunc logging_func) {\n  if (logging_func.defined() && using_ipython()) {\n    logging_func(static_cast<int>(PyLogMessage::Level::CLEAR), file, lineno, \"\");\n  } else {\n    // this would clear all logging output in the console\n    runtime::detail::LogMessage(file, lineno, TVM_LOG_LEVEL_INFO).stream()\n        << \"\\033c\\033[3J\\033[2J\\033[0m\\033[H\";\n  }\n}\n\n/*! \\brief The type of the random state */\nusing TRandState = support::LinearCongruentialEngine::TRandState;\n\n/*!\n * \\brief Get the base64 encoded result of a string.\n * \\param str The string to encode.\n * \\return The base64 encoded string.\n */\ninline std::string Base64Encode(std::string str) {\n  std::string result;\n  dmlc::MemoryStringStream m_stream(&result);\n  support::Base64OutStream b64stream(&m_stream);\n  static_cast<dmlc::Stream*>(&b64stream)->Write(str);\n  b64stream.Finish();\n  return result;\n}\n\n/*!\n * \\brief Get the base64 decoded result of a string.\n * \\param str The string to decode.\n * \\return The base64 decoded string.\n */\ninline std::string Base64Decode(std::string str) {\n  std::string result;\n  dmlc::MemoryStringStream m_stream(&str);\n  support::Base64InStream b64stream(&m_stream);\n  b64stream.InitPosition();\n  static_cast<dmlc::Stream*>(&b64stream)->Read(&result);\n  return result;\n}\n\n/*!\n * \\brief Parses a json string into a json object.\n * \\param json_str The json string.\n * \\return The json object\n */\nObjectRef JSONLoads(std::string json_str);\n\n/*!\n * \\brief Dumps a json object into a json string.\n * \\param json_obj The json object.\n * \\return The json string\n */\nstd::string JSONDumps(ObjectRef json_obj);\n\n/*!\n * \\brief Converts a structural hash code to string\n * \\param hash_code The hash code\n * \\return The string representation of the hash code\n */\ninline String SHash2Str(Workload::THashCode hash_code) { return std::to_string(hash_code); }\n\n/*!\n * \\brief Converts an TVM object to the hex string representation of its structural hash.\n * \\param obj The TVM object.\n * \\return The hex string representation of the hash code.\n */\ninline String SHash2Hex(const ObjectRef& obj) {\n  std::ostringstream os;\n  size_t hash_code = 0;\n  if (obj.defined()) {\n    hash_code = StructuralHash()(obj);\n  }\n  os << \"0x\" << std::setw(16) << std::setfill('0') << std::hex << hash_code;\n  return os.str();\n}\n\n/*!\n * \\brief Fork a random state into another, i.e. PRNG splitting.\n * The given random state is also mutated.\n * \\param rand_state The random state to be forked\n * \\return The forked random state\n */\ninline support::LinearCongruentialEngine::TRandState ForkSeed(\n    support::LinearCongruentialEngine::TRandState* rand_state) {\n  return support::LinearCongruentialEngine(rand_state).ForkSeed();\n}\n\n/*!\n * \\brief Fork a random state into another ones, i.e. PRNG splitting.\n *  The given random state is also mutated.\n * \\param rand_state The random state to be forked\n * \\param n The number of forks\n * \\return The forked random states\n */\ninline std::vector<support::LinearCongruentialEngine::TRandState> ForkSeed(\n    support::LinearCongruentialEngine::TRandState* rand_state, int n) {\n  std::vector<support::LinearCongruentialEngine::TRandState> results;\n  results.reserve(n);\n  for (int i = 0; i < n; ++i) {\n    results.push_back(support::LinearCongruentialEngine(rand_state).ForkSeed());\n  }\n  return results;\n}\n\n/*!\n * \\brief Get deep copy of an IRModule.\n * \\param mod The IRModule to make a deep copy.\n * \\return The deep copy of the IRModule.\n */\ninline IRModule DeepCopyIRModule(IRModule mod) {\n  return Downcast<IRModule>(LoadJSON(SaveJSON(mod)));\n}\n\n/*!\n * \\brief Concatenate strings\n * \\param strs The strings to concatenate\n * \\param delim The delimiter\n * \\return The concatenated string\n */\ninline std::string Concat(const Array<String>& strs, const std::string& delim) {\n  if (strs.empty()) {\n    return \"\";\n  }\n  std::ostringstream os;\n  os << strs[0];\n  for (int i = 1, n = strs.size(); i < n; ++i) {\n    os << delim << strs[i];\n  }\n  return os.str();\n}\n\n/*!\n * \\brief Get the BlockRV from a block StmtSRef\n * \\param sch The schedule\n * \\param block_sref The block StmtSRef\n * \\param global_var_name The global variable name\n * \\return The BlockRV\n */\ninline tir::BlockRV GetRVFromSRef(const tir::Schedule& sch, const tir::StmtSRef& block_sref,\n                                  const String& global_var_name) {\n  const tir::BlockNode* block = TVM_SREF_TO_BLOCK(block_sref);\n  return sch->GetBlock(block->name_hint, global_var_name);\n}\n\n/*!\n * \\brief A helper data structure that replays a trace and collects failure counts\n * for each postprocessor\n */\nstruct ThreadedTraceApply {\n  /*! \\brief Constructor */\n  explicit ThreadedTraceApply(const Array<Postproc>& postprocs)\n      : n_(postprocs.size()), items_(new Item[n_]) {\n    for (int i = 0; i < n_; ++i) {\n      items_[i].postproc = postprocs[i];\n      items_[i].fail_counter = 0;\n    }\n  }\n\n  /*! \\brief Destructor */\n  ~ThreadedTraceApply() { delete[] items_; }\n\n  /*!\n   * \\brief Apply the trace and postprocessors to an IRModule\n   * \\param mod The IRModule to be applied\n   * \\param trace The trace to apply to the IRModule\n   * \\param rand_state The random seed\n   * \\return The schedule created, or NullOpt if any postprocessor fails\n   */\n  Optional<tir::Schedule> Apply(const IRModule& mod, const tir::Trace& trace,\n                                TRandState* rand_state) {\n    tir::Schedule sch =\n        tir::Schedule::Traced(mod,\n                              /*rand_state=*/ForkSeed(rand_state),\n                              /*debug_mode=*/0,\n                              /*error_render_level=*/tir::ScheduleErrorRenderLevel::kNone);\n\n    trace->ApplyToSchedule(sch, /*remove_postproc=*/true);\n    sch->EnterPostproc();\n\n    for (int i = 0; i < n_; ++i) {\n      Item& item = items_[i];\n      if (!item.postproc->Apply(sch)) {\n        item.fail_counter++;\n        return NullOpt;\n      }\n    }\n    return sch;\n  }\n\n  /*! \\brief Returns a string summarizing the failures on each postprocessor */\n  std::string SummarizeFailures() const {\n    std::ostringstream os;\n    for (int i = 0; i < n_; ++i) {\n      const Item& item = items_[i];\n      os << \"Postproc #\" << i << \" [\" << item.postproc  //\n         << \"]: \" << item.fail_counter.load() << \" failure(s)\";\n      if (i != n_ - 1) {\n        os << \"\\n\";\n      }\n    }\n    return os.str();\n  }\n\n private:\n  /*! \\brief A helper data structure that stores the fail count for each postprocessor. */\n  struct Item {\n    /*! \\brief The postprocessor. */\n    Postproc postproc{nullptr};\n    /*! \\brief The thread-safe postprocessor failure counter. */\n    std::atomic<int> fail_counter{0};\n  };\n\n  /*! \\brief The number of total postprocessors. */\n  int n_;\n  /*! \\brief The pointer to the list of postprocessor items. */\n  Item* items_;\n};\n\n/*!\n * \\brief Get the number of cores in CPU\n * \\param target The target\n * \\return The number of cores.\n */\ninline int GetTargetNumCores(const Target& target) {\n  int num_cores = target->GetAttr<Integer>(\"num-cores\").value_or(-1).IntValue();\n  if (num_cores == -1) {\n    static const auto* f_cpu_count = runtime::Registry::Get(\"meta_schedule.cpu_count\");\n    ICHECK(f_cpu_count)\n        << \"ValueError: Cannot find the packed function \\\"meta_schedule._cpu_count\\\"\";\n    num_cores = (*f_cpu_count)(false);\n    LOG(FATAL)\n        << \"Target does not have attribute \\\"num-cores\\\", physical core number must be \"\n           \"defined! For example, on the local machine, the target must be \\\"llvm -num-cores \"\n        << num_cores << \"\\\"\";\n  }\n  return num_cores;\n}\n\n/*!\n * \\brief Get the median of the running time from RunnerResult in millisecond\n * \\param results The results from RunnerResult\n * \\return The median of the running time in millisecond\n */\ninline double GetRunMsMedian(const RunnerResult& runner_result) {\n  Array<FloatImm> run_secs = runner_result->run_secs.value();\n  ICHECK(!run_secs.empty());\n  std::vector<double> v;\n  v.reserve(run_secs.size());\n  std::transform(run_secs.begin(), run_secs.end(), std::back_inserter(v),\n                 [](const FloatImm& f) -> double { return f->value; });\n  std::sort(v.begin(), v.end());\n  int n = v.size();\n  if (n % 2 == 0) {\n    return (v[n / 2 - 1] + v[n / 2]) * 0.5 * 1000.0;\n  } else {\n    return v[n / 2] * 1000.0;\n  }\n}\n\n/*!\n * \\brief Convert the given object to an array of floating point numbers\n * \\param obj The object to be converted\n * \\return The array of floating point numbers\n */\ninline Array<FloatImm> AsFloatArray(const ObjectRef& obj) {\n  const ArrayNode* arr = obj.as<ArrayNode>();\n  ICHECK(arr) << \"TypeError: Expect an array, but gets: \" << obj->GetTypeKey();\n  Array<FloatImm> results;\n  results.reserve(arr->size());\n  for (const ObjectRef& elem : *arr) {\n    if (const auto* int_imm = elem.as<IntImmNode>()) {\n      results.push_back(FloatImm(DataType::Float(32), int_imm->value));\n    } else if (const auto* float_imm = elem.as<FloatImmNode>()) {\n      results.push_back(FloatImm(DataType::Float(32), float_imm->value));\n    } else {\n      LOG(FATAL) << \"TypeError: Expect an array of float or int, but gets: \" << elem->GetTypeKey();\n    }\n  }\n  return results;\n}\n\n/*!\n * \\brief Convert the given object to an array of integers\n * \\param obj The object to be converted\n * \\return The array of integers\n */\ninline Array<Integer> AsIntArray(const ObjectRef& obj) {\n  const ArrayNode* arr = obj.as<ArrayNode>();\n  ICHECK(arr) << \"TypeError: Expect an array, but gets: \" << obj->GetTypeKey();\n  Array<Integer> results;\n  results.reserve(arr->size());\n  for (const ObjectRef& elem : *arr) {\n    if (const auto* int_imm = elem.as<IntImmNode>()) {\n      results.push_back(Integer(int_imm->value));\n    } else {\n      LOG(FATAL) << \"TypeError: Expect an array of integers, but gets: \" << elem->GetTypeKey();\n    }\n  }\n  return results;\n}\n\n/*! \\brief The struct defining comparison function of sorting by mean run seconds. */\nstruct SortTuningRecordByMeanRunSecs {\n  static const constexpr double kMaxMeanTime = 1e10;\n\n  static double Mean(const Array<FloatImm>& a) {\n    if (a.empty()) {\n      return kMaxMeanTime;\n    }\n    double sum = 0.0;\n    for (const FloatImm& i : a) {\n      sum += i->value;\n    }\n    return sum / a.size();\n  }\n\n  bool operator()(const TuningRecord& a, const TuningRecord& b) const {\n    double a_time = Mean(a->run_secs.value_or({}));\n    double b_time = Mean(b->run_secs.value_or({}));\n    return a_time < b_time;\n  }\n};\n\n/*!\n * \\brief The helper function to clone schedule rules, postprocessors, and mutators.\n * \\param src The source space generator.\n * \\param dst The destination space generator.\n */\ninline void CloneRules(const SpaceGeneratorNode* src, SpaceGeneratorNode* dst) {\n  if (src->sch_rules.defined()) {\n    Array<ScheduleRule> original = src->sch_rules.value();\n    Array<ScheduleRule> sch_rules;\n    sch_rules.reserve(original.size());\n    for (const ScheduleRule& sch_rule : original) {\n      sch_rules.push_back(sch_rule->Clone());\n    }\n    dst->sch_rules = std::move(sch_rules);\n  }\n  if (src->postprocs.defined()) {\n    Array<Postproc> original = src->postprocs.value();\n    Array<Postproc> postprocs;\n    postprocs.reserve(original.size());\n    for (const Postproc& postproc : original) {\n      postprocs.push_back(postproc->Clone());\n    }\n    dst->postprocs = std::move(postprocs);\n  }\n  if (src->mutator_probs.defined()) {\n    Map<Mutator, FloatImm> original = src->mutator_probs.value();\n    Map<Mutator, FloatImm> mutator_probs;\n    for (const auto& kv : original) {\n      mutator_probs.Set(kv.first->Clone(), kv.second);\n    }\n    dst->mutator_probs = std::move(mutator_probs);\n  }\n}\n\n/*! \\brief Returns true if the given target is one of the supported gpu targets. */\ninline bool IsGPUTarget(const std::string& target_name) {\n  static const std::unordered_set<std::string> gpu_targets{\"cuda\", \"rocm\", \"vulkan\", \"metal\"};\n  return gpu_targets.count(target_name);\n}\n\n/*!\n * \\brief Create an AutoInline schedule rule for the given target.\n * \\param target_name The name of the target (\"llvm\", \"cuda\", etc.)\n * \\return The AutoInline schedule rule for the given target.\n */\ninline ScheduleRule GetDefaultAutoInline(const std::string& target_name) {\n  Array<ScheduleRule> rules{nullptr};\n  if (target_name == \"llvm\") {\n    rules = ScheduleRule::DefaultLLVM();\n  } else if (target_name == \"hexagon\") {\n    rules = ScheduleRule::DefaultHexagon();\n  } else if (IsGPUTarget(target_name)) {\n    rules = ScheduleRule::DefaultCUDA();\n  } else {\n    LOG(FATAL) << \"ValueError: Unsupported target: \" << target_name;\n  }\n  for (const ScheduleRule& rule : rules) {\n    if (rule->GetTypeKey() == \"meta_schedule.AutoInline\") {\n      return rule;\n    }\n  }\n  LOG(FATAL) << \"ValueError: AutoInline rule is not found in the default rules for target: \"\n             << target_name;\n  throw;\n}\n\n/*!\n * \\brief Summarize the run time of the given FloatImm array.\n * \\param arr The array of FloatImm.\n * \\return The summary of the values in the given array.\n */\ninline double Sum(const Array<FloatImm>& arr) {\n  double sum = 0;\n  for (const FloatImm& f : arr) {\n    sum += f->value;\n  }\n  return sum;\n}\n\n}  // namespace meta_schedule\n}  // namespace tvm\n\n#endif  // TVM_META_SCHEDULE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/node/attr_registry.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/node/attr_registry.h\n * \\brief Common global registry for objects that also have additional attrs.\n */\n#ifndef TVM_NODE_ATTR_REGISTRY_H_\n#define TVM_NODE_ATTR_REGISTRY_H_\n\n#include <tvm/node/attr_registry_map.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <mutex>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\n\n/*!\n * \\brief Implementation of registry with attributes.\n *\n * \\tparam EntryType The type of the registry entry.\n * \\tparam KeyType The actual key that is used to lookup the attributes.\n *                 each entry has a corresponding key by default.\n */\ntemplate <typename EntryType, typename KeyType>\nclass AttrRegistry {\n public:\n  using TSelf = AttrRegistry<EntryType, KeyType>;\n  /*!\n   * \\brief Get an entry from the registry.\n   * \\param name The name of the item.\n   * \\return The corresponding entry.\n   */\n  const EntryType* Get(const String& name) const {\n    auto it = entry_map_.find(name);\n    if (it != entry_map_.end()) return it->second;\n    return nullptr;\n  }\n\n  /*!\n   * \\brief Get an entry or register a new one.\n   * \\param name The name of the item.\n   * \\return The corresponding entry.\n   */\n  EntryType& RegisterOrGet(const String& name) {\n    auto it = entry_map_.find(name);\n    if (it != entry_map_.end()) return *it->second;\n    uint32_t registry_index = static_cast<uint32_t>(entries_.size());\n    auto entry = std::unique_ptr<EntryType>(new EntryType(registry_index));\n    auto* eptr = entry.get();\n    eptr->name = name;\n    entry_map_[name] = eptr;\n    entries_.emplace_back(std::move(entry));\n    return *eptr;\n  }\n\n  /*!\n   * \\brief List all the entry names in the registry.\n   * \\return The entry names.\n   */\n  Array<String> ListAllNames() const {\n    Array<String> names;\n    for (const auto& kv : entry_map_) {\n      names.push_back(kv.first);\n    }\n    return names;\n  }\n\n  /*!\n   * \\brief Update the attribute stable.\n   * \\param attr_name The name of the attribute.\n   * \\param key The key to the attribute table.\n   * \\param value The value to be set.\n   * \\param plevel The support level.\n   */\n  void UpdateAttr(const String& attr_name, const KeyType& key, runtime::TVMRetValue value,\n                  int plevel) {\n    using runtime::TVMRetValue;\n    std::lock_guard<std::mutex> lock(mutex_);\n    auto& op_map = attrs_[attr_name];\n    if (op_map == nullptr) {\n      op_map.reset(new AttrRegistryMapContainerMap<KeyType>());\n      op_map->attr_name_ = attr_name;\n    }\n\n    uint32_t index = key->AttrRegistryIndex();\n    if (op_map->data_.size() <= index) {\n      op_map->data_.resize(index + 1, std::make_pair(TVMRetValue(), 0));\n    }\n    std::pair<TVMRetValue, int>& p = op_map->data_[index];\n    ICHECK(p.second != plevel) << \"Attribute \" << attr_name << \" of \" << key->AttrRegistryName()\n                               << \" is already registered with same plevel=\" << plevel;\n    ICHECK(value.type_code() != kTVMNullptr) << \"Registered packed_func is Null for \" << attr_name\n                                             << \" of operator \" << key->AttrRegistryName();\n    if (p.second < plevel && value.type_code() != kTVMNullptr) {\n      op_map->data_[index] = std::make_pair(value, plevel);\n    }\n  }\n\n  /*!\n   * \\brief Reset an attribute table entry.\n   * \\param attr_name The name of the attribute.\n   * \\param key The key to the attribute table.\n   */\n  void ResetAttr(const String& attr_name, const KeyType& key) {\n    std::lock_guard<std::mutex> lock(mutex_);\n    auto& op_map = attrs_[attr_name];\n    if (op_map == nullptr) {\n      return;\n    }\n    uint32_t index = key->AttrRegistryIndex();\n    if (op_map->data_.size() > index) {\n      op_map->data_[index] = std::make_pair(TVMRetValue(), 0);\n    }\n  }\n\n  /*!\n   * \\brief Get an internal attribute map.\n   * \\param attr_name The name of the attribute.\n   * \\return The result attribute map.\n   */\n  const AttrRegistryMapContainerMap<KeyType>& GetAttrMap(const String& attr_name) {\n    std::lock_guard<std::mutex> lock(mutex_);\n    auto it = attrs_.find(attr_name);\n    if (it == attrs_.end()) {\n      LOG(FATAL) << \"Attribute \\'\" << attr_name << \"\\' is not registered\";\n    }\n    return *it->second.get();\n  }\n\n  /*!\n   * \\brief Check of attribute has been registered.\n   * \\param attr_name The name of the attribute.\n   * \\return The check result.\n   */\n  bool HasAttrMap(const String& attr_name) {\n    std::lock_guard<std::mutex> lock(mutex_);\n    return attrs_.count(attr_name);\n  }\n\n  /*!\n   * \\return a global singleton of the registry.\n   */\n  static TSelf* Global() {\n    static TSelf* inst = new TSelf();\n    return inst;\n  }\n\n private:\n  // mutex to avoid registration from multiple threads.\n  std::mutex mutex_;\n  // entries in the registry\n  std::vector<std::unique_ptr<EntryType>> entries_;\n  // map from name to entries.\n  std::unordered_map<String, EntryType*> entry_map_;\n  // storage of additional attribute table.\n  std::unordered_map<String, std::unique_ptr<AttrRegistryMapContainerMap<KeyType>>> attrs_;\n};\n\n}  // namespace tvm\n#endif  // TVM_NODE_ATTR_REGISTRY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/node/ndarray_hash_equal.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_NODE_NDARRAY_HASH_EQUAL_H_\n#define TVM_NODE_NDARRAY_HASH_EQUAL_H_\n\n#include <tvm/runtime/ndarray.h>\n\nnamespace tvm {\n\nclass SEqualReducer;\nclass SHashReducer;\n\n/*!\n * \\brief Test two NDArrays for equality.\n * \\param lhs The left operand.\n * \\param rhs The right operand.\n * \\param equal A Reducer class to reduce the structural equality result of two objects.\n * See tvm/node/structural_equal.h.\n * \\param compare_data Whether or not to consider ndarray raw data in the equality testing.\n * \\return The equality testing result.\n */\nbool NDArrayEqual(const runtime::NDArray::Container* lhs, const runtime::NDArray::Container* rhs,\n                  SEqualReducer equal, bool compare_data);\n\n/*!\n * \\brief Hash NDArray.\n * \\param arr The NDArray to compute the hash for.\n * \\param hash_reduce A Reducer class to reduce the structural hash value.\n * See tvm/node/structural_hash.h.\n * \\param hash_data Whether or not to hash ndarray raw data.\n */\nvoid NDArrayHash(const runtime::NDArray::Container* arr, SHashReducer* hash_reduce, bool hash_data);\n\n}  // namespace tvm\n\n#endif  //  TVM_NODE_NDARRAY_HASH_EQUAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/parser/meta_ref.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file meta_ref.h\n * \\brief A reference into the metadata section of the Relay text format.\n */\n\n#ifndef TVM_PARSER_META_REF_H_\n#define TVM_PARSER_META_REF_H_\n\n#include <tvm/ir/attrs.h>\n#include <tvm/parser/parser.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace parser {\n\nusing namespace relay;\n\n/*!\n * \\brief Options for allocating storage.\n */\nstruct MetaRefAttrs : public tvm::AttrsNode<MetaRefAttrs> {\n  tvm::String node_type_key;\n  uint64_t node_index;\n\n  TVM_DECLARE_ATTRS(MetaRefAttrs, \"relay.attrs.MetaRefAttrs\") {\n    TVM_ATTR_FIELD(node_type_key)\n        .describe(\"The type_key representing the type of the node referenced.\");\n    TVM_ATTR_FIELD(node_index).describe(\"The index into the type specific node array.\");\n  }\n};\n\n/*! \\brief A reference to a \"meta-expression\".\n *\n * In the text format we allow referencing metadata which\n * uses a compact serialization that proceeds the main\n * program body.\n *\n * We can reference this table using an expression of\n * the form `meta[Type][index]`.\n *\n * We must later resolve these references to actual in-memory\n * AST nodes but this requires first parsing the full program\n * then expanding these temporary AST nodes into their corresponding\n * nodes.\n *\n * For example the nth large constant will be pretty-printed as meta[relay.Constant][n]\n * with its compact binary serialization residing in the metadata section at the end\n * of the program.\n *\n * \\param type_key The type key of the object in the meta section.\n * \\param node_index The index into that subfield.\n * \\returns The meta table reference.\n */\nExpr MetaRef(std::string type_key, uint64_t node_index);\n\nrelay::Function ExpandMetaRefs(const MetaTable& meta_table, const relay::Function& func);\nIRModule ExpandMetaRefs(const MetaTable& meta_table, const IRModule& mod);\n\n}  // namespace parser\n}  // namespace tvm\n\n#endif  // TVM_PARSER_META_REF_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/parser/op_table.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file token.h\n * \\brief A operator table for parsing.\n *\n * Provides symbolic token sequences to map to TVM operators, with a given associativity and arity.\n */\n\n#ifndef TVM_PARSER_OP_TABLE_H_\n#define TVM_PARSER_OP_TABLE_H_\n\n#include <tvm/ir/op.h>\n#include <tvm/runtime/object.h>\n\n#include <fstream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"./tokenizer.h\"\n\nnamespace tvm {\nnamespace parser {\n\nstruct Rule {\n  std::vector<TokenType> tokens;\n  int precedence;\n  int arity;\n  tvm::Op op;\n  bool left_assoc;\n\n  Rule() : tokens(), precedence(0), arity(0), op(tvm::Op()), left_assoc(false) {}\n\n  Rule(std::vector<TokenType> tokens, tvm::Op op, int precedence, int arity = 2,\n       bool left_assoc = false)\n      : tokens(tokens), precedence(precedence), arity(arity), op(op), left_assoc(left_assoc) {}\n\n  Rule(const Rule& rule) {\n    this->tokens = rule.tokens;\n    this->op = rule.op;\n    this->precedence = rule.precedence;\n    this->arity = rule.arity;\n    this->left_assoc = rule.left_assoc;\n  }\n};\n\nstruct OperatorTable {\n  std::vector<Rule> rules;\n  std::unordered_map<std::string, Rule> this_is_a_hack;\n\n  explicit OperatorTable(std::vector<Rule> rules) : rules(rules), this_is_a_hack() {\n    for (auto rule : rules) {\n      std::stringstream key;\n      for (auto token : rule.tokens) {\n        key << ToString(token);\n      }\n      this->this_is_a_hack.insert({key.str(), rule});\n    }\n  }\n};\n\nOperatorTable DefaultOpTable() {\n  return OperatorTable(\n      {Rule({TokenType::kStar}, Op::Get(\"multiply\"), 12, 2, true),\n       Rule({TokenType::kDivision}, Op::Get(\"divide\"), 12, 2, true),\n       Rule({TokenType::kPlus}, Op::Get(\"add\"), 10, 2, true),\n       Rule({TokenType::kMinus}, Op::Get(\"subtract\"), 10, 2, true),\n       Rule({TokenType::kLAngle}, Op::Get(\"less\"), 8, 2, true),\n       Rule({TokenType::kLAngle, TokenType::kEqual}, Op::Get(\"less_equal\"), 8, 2, true),\n       Rule({TokenType::kRAngle}, Op::Get(\"greater\"), 8, 2, true),\n       Rule({TokenType::kRAngle, TokenType::kEqual}, Op::Get(\"greater_equal\"), 8, 2, true),\n       Rule({TokenType::kEqual, TokenType::kEqual}, Op::Get(\"equal\"), 7, 2, true),\n       Rule({TokenType::kBang, TokenType::kEqual}, Op::Get(\"not_equal\"), 7, 2, true)});\n}\n\n}  // namespace parser\n}  // namespace tvm\n#endif  // TVM_PARSER_OP_TABLE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/parser/span_check.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file span_check.h\n * \\brief Check that the Relay IR has correctly attached span information.\n */\n\n#ifndef TVM_PARSER_SPAN_CHECK_H_\n#define TVM_PARSER_SPAN_CHECK_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/ir/type_functor.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/object.h>\n\n#include <fstream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace parser {\n\nusing namespace tvm::relay;\nusing tvm::transform::Pass;\n\nstruct SpanChecker : ExprVisitor {\n  Expr expression;\n  DiagnosticContext diag_ctx;\n  std::vector<Span> span_stack;\n\n  explicit SpanChecker(DiagnosticContext diag_ctx) : diag_ctx(diag_ctx) {}\n\n  void VisitExpr(const Expr& expr) override;\n  void VisitExpr_(const VarNode* op) override;\n  void VisitExpr_(const GlobalVarNode* op) override;\n  void VisitExpr_(const ConstantNode* op) override;\n  void VisitExpr_(const TupleNode* op) override;\n  void VisitExpr_(const FunctionNode* op) override;\n  void VisitExpr_(const CallNode* op) override;\n  void VisitExpr_(const LetNode* op) override;\n  void VisitExpr_(const IfNode* op) override;\n  void VisitExpr_(const OpNode* op) override;\n  void VisitExpr_(const TupleGetItemNode* op) override;\n  void VisitExpr_(const RefCreateNode* op) override;\n  void VisitExpr_(const RefReadNode* op) override;\n  void VisitExpr_(const RefWriteNode* op) override;\n  void VisitExpr_(const ConstructorNode* op) override;\n  void VisitExpr_(const MatchNode* op) override;\n  void VisitType(const Type& t) override;\n  void VisitClause(const Clause& c) override;\n  void VisitPattern(const Pattern& c) override;\n  void VisitSpan(const Span& span) override;\n};\n\nPass SpanCheck();\n\n}  // namespace parser\n}  // namespace tvm\n#endif  // TVM_PARSER_SPAN_CHECK_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/parser/token.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file token.h\n * \\brief The definition of tokens for the TVM parser.\n */\n\n#ifndef TVM_PARSER_TOKEN_H_\n#define TVM_PARSER_TOKEN_H_\n\n#include <tvm/ir/span.h>\n#include <tvm/runtime/object.h>\n\n#include <fstream>\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace parser {\n\nusing namespace runtime;\n\nenum class TokenType {\n  kCommentStart,\n  kCommentEnd,\n  kLineComment,\n  kComment,\n  kWhitespace,\n  kNewline,\n  kStringLiteral,\n  kIdentifier,\n  kLocal,\n  kGlobal,\n  kOp,\n  kGraph,\n  kOpenParen,\n  kCloseParen,\n  kAtSymbol,\n  kPercent,\n  kComma,\n  kPeriod,\n  kEqual,\n  kSemicolon,\n  kColon,\n  kInteger,\n  kFloat,\n  kDivision,\n  kBoolean,\n  kPlus,\n  kStar,\n  kMinus,\n  kRAngle,\n  kLAngle,\n  kRCurly,\n  kLCurly,\n  kRSquare,\n  kLSquare,\n  kBang,\n  kAt,\n  kQuestion,\n  kIf,\n  kElse,\n  kUnderscore,\n  kLet,\n  kFn,\n  kDefn,\n  kTypeDef,\n  kExtern,\n  kMatch,\n  kPartialMatch,\n  kMetadata,\n  kMetaReference,\n  kFreeVar,\n  kRef,\n  kRefRead,\n  kRefWrite,\n  kVersion,\n  kUnknown,\n  kEndOfFile,\n  kNull,\n};\n\nstd::string ToString(const TokenType& token_type) {\n  switch (token_type) {\n    case TokenType::kCommentStart:\n      return \"CommentStart\";\n    case TokenType::kCommentEnd:\n      return \"CommentEnd\";\n    case TokenType::kLineComment:\n      return \"LineComment\";\n    case TokenType::kComment:\n      return \"Comment\";\n    case TokenType::kWhitespace:\n      return \"WhiteSpace\";\n    case TokenType::kNewline:\n      return \"Newline\";\n    case TokenType::kStringLiteral:\n      return \"StringLiteral\";\n    case TokenType::kIdentifier:\n      return \"Identifier\";\n    case TokenType::kLocal:\n      return \"Local\";\n    case TokenType::kGlobal:\n      return \"Global\";\n    case TokenType::kGraph:\n      return \"Graph\";\n    case TokenType::kOp:\n      return \"Op\";\n    case TokenType::kOpenParen:\n      return \"OpenParen\";\n    case TokenType::kCloseParen:\n      return \"CloseParen\";\n    case TokenType::kAtSymbol:\n      return \"AtSymbol\";\n    case TokenType::kPercent:\n      return \"Percent\";\n    case TokenType::kComma:\n      return \"Comma\";\n    case TokenType::kColon:\n      return \"Colon\";\n    case TokenType::kSemicolon:\n      return \"Semicolon\";\n    case TokenType::kPeriod:\n      return \"Period\";\n    case TokenType::kEqual:\n      return \"Equal\";\n    case TokenType::kInteger:\n      return \"Integer\";\n    case TokenType::kFloat:\n      return \"Float\";\n    case TokenType::kPlus:\n      return \"Plus\";\n    case TokenType::kStar:\n      return \"Star\";\n    case TokenType::kMinus:\n      return \"Minus\";\n    case TokenType::kDivision:\n      return \"Division\";\n    case TokenType::kRAngle:\n      return \"RAngle\";\n    case TokenType::kLAngle:\n      return \"LAngle\";\n    case TokenType::kRCurly:\n      return \"RCurly\";\n    case TokenType::kLCurly:\n      return \"LCurly\";\n    case TokenType::kRSquare:\n      return \"RSquare\";\n    case TokenType::kLSquare:\n      return \"LSquare\";\n    case TokenType::kBang:\n      return \"Bang\";\n    case TokenType::kUnderscore:\n      return \"Underscore\";\n    case TokenType::kAt:\n      return \"At\";\n    case TokenType::kLet:\n      return \"Let\";\n    case TokenType::kIf:\n      return \"If\";\n    case TokenType::kElse:\n      return \"Else\";\n    case TokenType::kFn:\n      return \"Fn\";\n    case TokenType::kDefn:\n      return \"Defn\";\n    case TokenType::kTypeDef:\n      return \"TypeDef\";\n    case TokenType::kExtern:\n      return \"Extern\";\n    case TokenType::kMatch:\n      return \"Match\";\n    case TokenType::kPartialMatch:\n      return \"PartialMatch\";\n    case TokenType::kQuestion:\n      return \"Question\";\n    case TokenType::kBoolean:\n      return \"Boolean\";\n    case TokenType::kMetadata:\n      return \"Metadata\";\n    case TokenType::kMetaReference:\n      return \"MetaReference\";\n    case TokenType::kFreeVar:\n      return \"FreeVar\";\n    case TokenType::kVersion:\n      return \"Version\";\n    case TokenType::kRef:\n      return \"Ref\";\n    case TokenType::kRefRead:\n      return \"RefRead\";\n    case TokenType::kRefWrite:\n      return \"RefWrite\";\n    case TokenType::kUnknown:\n      return \"Unknown\";\n    case TokenType::kEndOfFile:\n      return \"EndOfFile\";\n    case TokenType::kNull:\n      return \"Null\";\n    // Older compilers warn even though the above code is exhaustive.\n    default:\n      LOG(FATAL) << \"unreachable code\";\n      return \"\";\n  }\n}\n\nstd::string Pretty(const TokenType& token_type) {\n  switch (token_type) {\n    case TokenType::kCommentStart:\n      return \"`/*`\";\n    case TokenType::kCommentEnd:\n      return \"`*/`\";\n    case TokenType::kLineComment:\n      return \"`//`\";\n    case TokenType::kComment:\n      return \"comment\";\n    case TokenType::kWhitespace:\n      return \"whitespace\";\n    case TokenType::kNewline:\n      return \"newline\";\n    case TokenType::kStringLiteral:\n      return \"string literal\";\n    case TokenType::kIdentifier:\n      return \"identifier\";\n    case TokenType::kLocal:\n      return \"local variable\";\n    case TokenType::kGlobal:\n      return \"global variable\";\n    case TokenType::kGraph:\n      return \"graph variable\";\n    case TokenType::kOp:\n      return \"operator\";\n    case TokenType::kOpenParen:\n      return \"`(`\";\n    case TokenType::kCloseParen:\n      return \"`)`\";\n    case TokenType::kAtSymbol:\n      return \"`@`\";\n    case TokenType::kPercent:\n      return \"`%`\";\n    case TokenType::kComma:\n      return \"`,`\";\n    case TokenType::kColon:\n      return \"`:`\";\n    case TokenType::kSemicolon:\n      return \"`;`\";\n    case TokenType::kPeriod:\n      return \"`.`\";\n    case TokenType::kEqual:\n      return \"`=`\";\n    case TokenType::kInteger:\n      return \"integer\";\n    case TokenType::kFloat:\n      return \"float\";\n    case TokenType::kPlus:\n      return \"`+`\";\n    case TokenType::kStar:\n      return \"`*`\";\n    case TokenType::kMinus:\n      return \"`-`\";\n    case TokenType::kDivision:\n      return \"`/`\";\n    case TokenType::kRAngle:\n      return \"`<`\";\n    case TokenType::kLAngle:\n      return \"`>`\";\n    case TokenType::kRCurly:\n      return \"`}`\";\n    case TokenType::kLCurly:\n      return \"`{`\";\n    case TokenType::kRSquare:\n      return \"`]`\";\n    case TokenType::kLSquare:\n      return \"`[`\";\n    case TokenType::kBang:\n      return \"`!`\";\n    case TokenType::kUnderscore:\n      return \"`_`\";\n    case TokenType::kAt:\n      return \"`@`\";\n    case TokenType::kLet:\n      return \"`let`\";\n    case TokenType::kIf:\n      return \"`if`\";\n    case TokenType::kElse:\n      return \"`else`\";\n    case TokenType::kFn:\n      return \"`fn`\";\n    case TokenType::kDefn:\n      return \"`def`\";\n    case TokenType::kTypeDef:\n      return \"`type`\";\n    case TokenType::kExtern:\n      return \"`extern`\";\n    case TokenType::kBoolean:\n      return \"boolean\";\n    case TokenType::kMetadata:\n      return \"metadata section\";\n    case TokenType::kMetaReference:\n      return \"`meta`\";\n    case TokenType::kFreeVar:\n      return \"`free_var`\";\n    case TokenType::kMatch:\n      return \"`match`\";\n    case TokenType::kPartialMatch:\n      return \"`match?`\";\n    case TokenType::kQuestion:\n      return \"`?`\";\n    case TokenType::kRef:\n      return \"`ref`\";\n    case TokenType::kRefRead:\n      return \"`ref_read`\";\n    case TokenType::kRefWrite:\n      return \"`ref_write`\";\n    case TokenType::kUnknown:\n      return \"unknown\";\n    case TokenType::kEndOfFile:\n      return \"end of file\";\n    case TokenType::kNull:\n      return \"null\";\n    case TokenType::kVersion:\n      return \"version attribute\";\n    // Older compilers warn even though the above code is exhaustive.\n    default:\n      LOG(FATAL) << \"unreachable code\";\n      return \"\";\n  }\n}\n\nclass Token;\n\nclass TokenNode : public Object {\n public:\n  Span span;\n  TokenType token_type;\n  mutable runtime::ObjectRef data;\n\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"parser.Token\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TokenNode, Object);\n};\n\nTVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)\n    .set_dispatch<TokenNode>([](const ObjectRef& ref, ReprPrinter* p) {\n      auto* node = static_cast<const TokenNode*>(ref.get());\n      p->stream << \"Token(span=\" << node->span << \", token_type=\" << ToString(node->token_type)\n                << \", data=\" << node->data << \")\";\n    });\n\nTVM_REGISTER_NODE_TYPE(TokenNode);\n\nclass Token : public ObjectRef {\n public:\n  TVM_DLL explicit Token(Span span, TokenType token_type, ObjectRef data = ObjectRef());\n\n  static Token Null();\n  int64_t ToNumber() const;\n  std::string ToString() const;\n  Map<String, Array<ObjectRef>> ToMetadata() const;\n  TVM_DEFINE_OBJECT_REF_METHODS(Token, ObjectRef, TokenNode);\n};\n\nToken::Token(Span span, TokenType token_type, ObjectRef data) {\n  ObjectPtr<TokenNode> n = make_object<TokenNode>();\n  n->span = span;\n  n->token_type = token_type;\n  n->data = data;\n  data_ = std::move(n);\n}\n\nToken Token::Null() { return Token(Span(SourceName(), 0, 0, 0, 0), TokenType::kNull); }\n\nint64_t Token::ToNumber() const {\n  return Downcast<tvm::Integer>(this->operator->()->data).IntValue();\n}\n\nstd::string Token::ToString() const { return Downcast<tvm::String>(this->operator->()->data); }\n\nMap<String, Array<ObjectRef>> Token::ToMetadata() const {\n  ObjectRef data = this->operator->()->data;\n  if (data.defined()) {\n    return Downcast<Map<String, Array<ObjectRef>>>(data);\n  } else {\n    return Map<String, Array<ObjectRef>>({});\n  }\n}\n\n}  // namespace parser\n}  // namespace tvm\n#endif  // TVM_PARSER_TOKEN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/parser/tokenizer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file parser.h\n * \\brief A parser for TVM IR.\n */\n#ifndef TVM_PARSER_TOKENIZER_H_\n#define TVM_PARSER_TOKENIZER_H_\n\n#include <tvm/node/serialization.h>\n#include <tvm/runtime/object.h>\n\n#include <fstream>\n#include <limits>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../support/scalars.h\"\n#include \"./meta_ref.h\"\n#include \"./token.h\"\n\nnamespace tvm {\nnamespace parser {\n\nusing namespace runtime;\n\n// trim from start (in place)\nstatic inline void ltrim(std::string& s) {  // NOLINT(*)\n  s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));\n}\n\n// trim from end (in place)\nstatic inline void rtrim(std::string& s) {  // NOLINT(*)\n  s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(),\n          s.end());\n}\n\nbool IsDigit(char c) { return '0' <= c && c <= '9'; }\n\nbool IsWhitespace(char c) { return ' ' == c || c == '\\t' || c == '\\n'; }\n\nbool IsNumeric(char c) {\n  return (IsDigit(c) || c == '.' || c == 'e' || c == '-' || c == '+' || c == 'E') &&\n         !IsWhitespace(c);\n}\n\nbool IsIdentLetter(char c) {\n  return '_' == c || c == '/' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');\n}\n\nbool IsIdent(char c) { return IsIdentLetter(c) || IsDigit(c); }\n\nstatic std::unordered_map<std::string, TokenType> KEYWORD_TABLE = {\n    {\"let\", TokenType::kLet},          {\"fn\", TokenType::kFn},\n    {\"def\", TokenType::kDefn},         {\"if\", TokenType::kIf},\n    {\"else\", TokenType::kElse},        {\"type\", TokenType::kTypeDef},\n    {\"match\", TokenType::kMatch},      {\"extern\", TokenType::kExtern},\n    {\"free_var\", TokenType::kFreeVar}, {\"ref\", TokenType::kRef},\n    {\"ref_read\", TokenType::kRefRead}, {\"ref_write\", TokenType::kRefWrite}};\n\nstruct Tokenizer {\n  DiagnosticContext diag_ctx;\n  const SourceName& source_name;\n\n  size_t pos;\n  int col;\n  int line;\n  char next_char;\n  String source;\n  std::vector<Token> tokens;\n\n  char Next() {\n    char c = this->source.at(this->pos);\n    if (c == '\\n') {\n      this->line += 1;\n      this->col = 1;\n    } else {\n      this->col += 1;\n    }\n    pos += 1;\n    return c;\n  }\n\n  bool More() { return this->pos < this->source.size(); }\n\n  char Peek() {\n    ICHECK(pos < this->source.size());\n    return this->source.at(this->pos);\n  }\n\n  Token NewToken(TokenType token_type, ObjectRef data = ObjectRef(), int lines = 0, int cols = 1) {\n    auto span =\n        Span(this->source_name, this->line, this->line + lines, this->col, this->col + cols);\n    return Token(span, token_type, data);\n  }\n\n  Span SpanFrom(int line, int column) {\n    int end_line = this->line;\n    int end_column = this->col;\n    return Span(this->source_name, line, end_line, column, end_column);\n  }\n\n  enum CommentParserState {\n    Proceed,\n    Forward,\n    Backward,\n  };\n\n  void MatchComment(std::string* buffer) {\n    // We only invoke this after we have matched the first start\n    // token assume, we are proceeding the parse forward with\n    // nesting = 1.\n    //\n    // When we are done we should be at nesting zero and be\n    // in the stop state.\n    CommentParserState state = CommentParserState::Proceed;\n    int nesting = 1;\n\n    while (More()) {\n      switch (state) {\n        case CommentParserState::Proceed: {\n          if (Peek() == '/') {\n            state = CommentParserState::Forward;\n          } else if (Peek() == '*') {\n            state = CommentParserState::Backward;\n          }\n          buffer->operator+=(Next());\n          continue;\n        }\n        case CommentParserState::Forward: {\n          if (Peek() == '*') {\n            nesting += 1;\n            buffer->operator+=(Next());\n          }\n          state = CommentParserState::Proceed;\n          continue;\n        }\n        case CommentParserState::Backward: {\n          if (Peek() == '/') {\n            nesting -= 1;\n            if (nesting == 0) {\n              Next();\n              buffer->pop_back();\n              return;\n            }\n          }\n\n          buffer->operator+=(Next());\n          state = CommentParserState::Proceed;\n          continue;\n        }\n      }\n    }\n  }\n\n  Token ParseNumber(bool is_pos, bool is_float, std::string number) {\n    ICHECK(number.size() > 0) << \"an empty string is an invalid number\";\n\n    Token token = NewToken(is_float ? TokenType::kFloat : TokenType::kInteger);\n    size_t suffix_pos = number.rfind(is_float ? 'f' : 'i');\n    if (suffix_pos == std::string::npos) {\n      suffix_pos = number.size();\n    }\n    std::string literal_text = number.substr(0, suffix_pos);\n    std::string suffix;\n    if (suffix_pos < number.size()) {\n      suffix = number.substr(suffix_pos + 1, number.size() - suffix_pos);\n    }\n    int width = 32;\n\n    if (suffix.size()) {\n      try {\n        width = std::stoi(suffix);\n      } catch (const std::invalid_argument& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid numeric suffix `\" << suffix << \"`\");\n      } catch (const std::out_of_range& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid numeric suffix `\" << suffix << \"`\");\n      }\n    }\n\n    if (is_float) {\n      double value = 0.0;\n      size_t index = 0;\n      try {\n        value = stod(literal_text, &index);\n      } catch (const std::invalid_argument& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid floating point number `\" << literal_text << \"`\");\n      } catch (const std::out_of_range& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid floating point number `\" << literal_text << \"`\");\n      }\n      if (index < literal_text.size()) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid floating point number `\" << literal_text << \"`\");\n      }\n      value = is_pos ? value : -value;\n      token->data = support::ValueToFloatImm(value, width);\n      if (!token->data.defined()) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"floating point number `\" << literal_text\n                            << \"` unrepresentable in width \" << width);\n        token->data = support::ValueToFloatImm(0.0, width);\n      }\n    } else {\n      int64_t value = 0;\n      size_t index = 0;\n      try {\n        value = std::stoll(literal_text, &index);\n      } catch (const std::invalid_argument& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid integer number `\" << literal_text << \"`\");\n      } catch (const std::out_of_range& err) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid integer number `\" << literal_text << \"`\");\n      }\n      if (index < literal_text.size()) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"invalid integer number `\" << literal_text << \"`\");\n      }\n      value = is_pos ? value : -value;\n      token->data = support::ValueToIntImm(value, width);\n      if (!token->data.defined() && suffix.empty()) {\n        // Without any i suffix the legacy behavior was to default to int64 if out of range\n        // for int32.\n        width = 64;\n        token->data = support::ValueToIntImm(value, width);\n      }\n      if (!token->data.defined()) {\n        this->diag_ctx.Emit(Diagnostic::Error(token->span)\n                            << \"integer number `\" << literal_text << \"` unrepresentable in width \"\n                            << width);\n        token->data = support::ValueToIntImm(0, width);\n      }\n    }\n\n    return token;\n  }\n\n  Token ParseNumber(bool is_pos) {\n    std::stringstream ss;\n    while (More() && IsNumeric(Peek())) {\n      ss << Next();\n    }\n\n    bool is_float = false;\n    if (More() && (Peek() == 'f' || Peek() == 'i')) {\n      is_float = Peek() == 'f';\n      // Capture trailing width suffix\n      ss << Next();\n      while (More() && IsNumeric(Peek())) {\n        ss << Next();\n      }\n    }\n    return ParseNumber(is_pos, is_float, ss.str());\n  }\n\n  bool MatchString(const std::string& string) {\n    int start = this->pos;\n\n    for (auto c : string) {\n      if (Peek() != c) {\n        this->pos = start;\n        return false;\n      } else {\n        Next();\n      }\n    }\n\n    return true;\n  }\n\n  Token TokenizeMetaRef() {\n    int line = this->line;\n    int column = this->col;\n\n    std::stringstream type_key;\n    while (More() && Peek() != ']') {\n      type_key << Next();\n    }\n    ICHECK_EQ(Peek(), ']');\n    Next();\n\n    ICHECK_EQ(Peek(), '[');\n    Next();\n    std::stringstream str_index;\n    while (More() && Peek() != ']') {\n      str_index << Next();\n    }\n    ICHECK_EQ(Peek(), ']');\n    Next();\n    // todo: add error handling around bad indices\n    auto index = ParseNumber(true, false, str_index.str()).ToNumber();\n    auto span = SpanFrom(line, column);\n    return Token(span, TokenType::kMetaReference, MetaRef(type_key.str(), index));\n  }\n\n  Token TokenizeAttr() {\n    int line = this->line;\n    int column = this->col;\n    Next();\n    if (Peek() == '[') {\n      Next();\n      std::stringstream raw_attribute;\n\n      while (More() && Peek() != ']') {\n        raw_attribute << Next();\n      }\n\n      ICHECK_EQ(Next(), ']');\n\n      auto attribute = raw_attribute.str();\n      // Clean up the white-space on both sides.\n      ltrim(attribute);\n      rtrim(attribute);\n\n      // Metadata can only appear at the bottom of a file and goes to EOF.\n      if (attribute == \"metadata\") {\n        std::stringstream metadata;\n        while (More()) {\n          metadata << Next();\n        }\n        ObjectRef metadata_map = tvm::LoadJSON(metadata.str());\n        auto span = SpanFrom(line, column);\n        return Token(span, TokenType::kMetadata, metadata_map);\n      }\n      if (attribute.rfind(\"version\", 0) == 0) {\n        std::string version = attribute.substr(attribute.find(\"=\") + 1);\n        ltrim(version);\n        rtrim(version);\n        auto span = SpanFrom(line, column);\n        return Token(span, TokenType::kVersion, tvm::String(version));\n      } else {\n        // TOOD(@jroesch): maybe make this a warning an continue parsing?\n        auto span = SpanFrom(line, column);\n        this->diag_ctx.EmitFatal(Diagnostic::Error(span) << \"unsupported attribute \" << attribute);\n        return Token();\n      }\n    } else {\n      auto span = SpanFrom(line, column);\n      this->diag_ctx\n          .EmitFatal(Diagnostic::Error(span)\n                     << \"`#` denotes the start of an attribute can only be followed by `[`\"\n                     << \" found `\" << Peek() << \"`\");\n      return Token();\n    }\n  }\n\n  inline Token TokenizeOnce() {\n    int line = this->line;\n    int col = this->col;\n    auto next = Peek();\n    VLOG(9) << \"tvm::parser::TokenizeOnce: next=\" << next;\n    if (next == '\\n') {\n      auto token = NewToken(TokenType::kNewline);\n      Next();\n      return token;\n    } else if (next == '\\r') {\n      Next();\n      if (More() && Peek() == '\\n') {\n        auto token = NewToken(TokenType::kNewline);\n        return token;\n      } else {\n        auto span = SpanFrom(line, col);\n        this->diag_ctx.EmitFatal(\n            Diagnostic::Error(span)\n            << \"\\\\r carriage returns must be followed by a \\\\n in the TVM text format\");\n        return Token();\n      }\n    } else if (next == '\"') {\n      // TODO(@jroesch): Properly tokenize escape sequences in strings.\n      // see https://github.com/apache/tvm/issues/6153.\n      Next();\n      std::stringstream string_content;\n      while (More() && Peek() != '\"') {\n        string_content << Next();\n      }\n      Next();\n      return NewToken(TokenType::kStringLiteral, tvm::String(string_content.str()));\n    } else if (IsWhitespace(next)) {\n      auto token = NewToken(TokenType::kWhitespace);\n      Next();\n      return token;\n    } else if (next == '-') {\n      int negs = 0;\n      while (More() && Peek() == '-') {\n        Next();\n        negs++;\n      }\n      bool is_neg = negs % 2 == 1;\n      if (More() && IsDigit(Peek())) {\n        return ParseNumber(!is_neg);\n      } else if (More() && MatchString(\"inff\")) {\n        return ParseNumber(!is_neg, true, \"inff\");\n      } else {\n        // If there isn't a number right after either,\n        // this is really slow for lexing, should replace\n        // with multi-token return or something.\n        pos = pos - (negs - 1);\n        return NewToken(TokenType::kMinus);\n      }\n    } else if (IsDigit(next)) {\n      return ParseNumber(true);\n    } else if (MatchString(\"inff\")) {\n      return ParseNumber(true, true, \"inff\");\n    } else if (next == '.') {\n      auto token = NewToken(TokenType::kPeriod);\n      Next();\n      return token;\n    } else if (next == ',') {\n      auto token = NewToken(TokenType::kComma);\n      Next();\n      return token;\n    } else if (next == '=') {\n      auto token = NewToken(TokenType::kEqual);\n      Next();\n      return token;\n    } else if (next == ';') {\n      auto token = NewToken(TokenType::kSemicolon);\n      Next();\n      return token;\n    } else if (next == ':') {\n      auto token = NewToken(TokenType::kColon);\n      Next();\n      return token;\n    } else if (next == '(') {\n      auto token = NewToken(TokenType::kOpenParen);\n      Next();\n      return token;\n    } else if (next == ')') {\n      auto token = NewToken(TokenType::kCloseParen);\n      Next();\n      return token;\n    } else if (next == '+') {\n      auto token = NewToken(TokenType::kPlus);\n      Next();\n      return token;\n    } else if (next == '*') {\n      auto token = NewToken(TokenType::kStar);\n      Next();\n      return token;\n    } else if (next == '<') {\n      auto token = NewToken(TokenType::kLAngle);\n      Next();\n      return token;\n    } else if (next == '>') {\n      auto token = NewToken(TokenType::kRAngle);\n      Next();\n      return token;\n    } else if (next == '{') {\n      auto token = NewToken(TokenType::kLCurly);\n      Next();\n      return token;\n    } else if (next == '}') {\n      auto token = NewToken(TokenType::kRCurly);\n      Next();\n      return token;\n    } else if (next == '[') {\n      auto token = NewToken(TokenType::kLSquare);\n      Next();\n      return token;\n    } else if (next == ']') {\n      auto token = NewToken(TokenType::kRSquare);\n      Next();\n      return token;\n    } else if (next == '!') {\n      auto token = NewToken(TokenType::kBang);\n      Next();\n      return token;\n    } else if (next == '@') {\n      auto token = NewToken(TokenType::kAt);\n      Next();\n      return token;\n    } else if (next == '?') {\n      auto token = NewToken(TokenType::kQuestion);\n      Next();\n      return token;\n    } else if (MatchString(\"meta[\")) {\n      return TokenizeMetaRef();\n    } else if (next == '#') {\n      return TokenizeAttr();\n    } else if (next == '%') {\n      auto token = NewToken(TokenType::kPercent);\n      Next();\n\n      std::stringstream number;\n      while (More() && IsDigit(Peek())) {\n        number << Next();\n      }\n\n      auto number_str = number.str();\n      if (number_str.size()) {\n        auto num_tok = ParseNumber(true, false, number_str);\n        auto span = SpanFrom(token->span->line, token->span->column);\n        token = Token(span, TokenType::kGraph, num_tok->data);\n      }\n\n      return token;\n    } else if (next == '/') {\n      Next();\n      if (Peek() == '/') {\n        auto token = NewToken(TokenType::kLineComment);\n        // Consume the /\n        Next();\n        std::stringstream comment;\n        while (More() && Peek() != '\\n') {\n          comment << Next();\n        }\n        token->data = tvm::String(comment.str());\n        return token;\n      } else if (Peek() == '*') {\n        // Eat the first /* pair before entering the state machine.\n        Next();\n        std::string comment;\n        MatchComment(&comment);\n        auto token = NewToken(TokenType::kComment, tvm::String(comment));\n        return token;\n      } else {\n        return NewToken(TokenType::kDivision);\n      }\n    } else if (IsIdentLetter(next)) {\n      std::stringstream ss;\n      // Due the below code we need to patch\n      // the line/col info to the start of\n      // token.\n      int line = this->line;\n      int col = this->col;\n\n      while (More() && IsIdent(Peek())) {\n        ss << Next();\n      }\n\n      std::string keyword = ss.str();\n      auto it = KEYWORD_TABLE.find(keyword);\n\n      TokenType token_type;\n      if (it != KEYWORD_TABLE.end()) {\n        token_type = it->second;\n\n        if (token_type == TokenType::kMatch) {\n          if (More() && Peek() == '?') {\n            Next();\n            token_type = TokenType::kPartialMatch;\n          }\n        }\n      } else {\n        token_type = TokenType::kIdentifier;\n      }\n\n      auto span = SpanFrom(line, col);\n      return Token(span, token_type, tvm::String(ss.str()));\n    } else {\n      std::stringstream ss;\n      while (More() && !IsWhitespace(Peek())) {\n        ss << Next();\n      }\n      auto token = NewToken(TokenType::kUnknown);\n      token->data = tvm::String(ss.str());\n      return token;\n    }\n  }\n\n  void Tokenize() {\n    VLOG(9) << \"tvm::parser::Tokenize\";\n    while (this->More()) {\n      auto token = TokenizeOnce();\n      ICHECK(token.defined());\n      this->tokens.push_back(token);\n    }\n    this->tokens.push_back(NewToken(TokenType::kEndOfFile));\n  }\n\n  explicit Tokenizer(const DiagnosticContext& ctx, const Source& source)\n      : diag_ctx(ctx),\n        source_name(source->source_name),\n        pos(0),\n        col(1),\n        line(1),\n        source(source->source),\n        tokens() {}\n};\n\nstd::vector<Token> Condense(const std::vector<Token>& tokens, Token* table) {\n  std::vector<Token> out;\n  bool found_metadata = false;\n\n  for (size_t i = 0; i < tokens.size(); i++) {\n    auto current = tokens.at(i);\n    switch (current->token_type) {\n      case TokenType::kMetadata: {\n        if (!found_metadata) {\n          found_metadata = true;\n          *table = current;\n        } else {\n          LOG(FATAL) << \"duplicate metadata section\";\n        }\n        continue;\n      }\n      case TokenType::kPercent: {\n        auto next = tokens.at(i + 1);\n        if (next->token_type == TokenType::kIdentifier) {\n          // Match this token.\n          i += 1;\n          // TODO(@jroesch): merge spans\n          auto tok = Token(current->span, TokenType::kLocal, next->data);\n          ICHECK(tok.defined());\n          out.push_back(tok);\n        } else if (next->token_type == TokenType::kInteger) {\n          i += 1;\n          auto tok = Token(current->span, TokenType::kGraph, next->data);\n          ICHECK(tok.defined());\n          out.push_back(tok);\n        } else {\n          ICHECK(current.defined());\n          out.push_back(current);\n        }\n        continue;\n      }\n      case TokenType::kAt: {\n        auto next = tokens.at(i + 1);\n        if (next->token_type == TokenType::kIdentifier) {\n          // Match this token.\n          i += 1;\n          // TODO(@jroesch): merge spans\n          auto tok = Token(current->span, TokenType::kGlobal, next->data);\n          ICHECK(tok.defined());\n          out.push_back(tok);\n        } else {\n          ICHECK(current.defined());\n          out.push_back(current);\n        }\n        continue;\n      }\n      case TokenType::kIdentifier: {\n        std::string str = Downcast<tvm::String>(current->data);\n        Token tok;\n        // TODO(@jroesch): merge spans\n        if (str == \"True\") {\n          auto data = tvm::Integer(1);\n          tok = Token(current->span, TokenType::kBoolean, data);\n        } else if (str == \"False\") {\n          auto data = tvm::Integer(0);\n          tok = Token(current->span, TokenType::kBoolean, data);\n        } else if (str == \"_\") {\n          tok = Token(current->span, TokenType::kUnderscore);\n        } else {\n          tok = current;\n        }\n        out.push_back(tok);\n        continue;\n      }\n      default: {\n        out.push_back(current);\n        continue;\n      }\n    }\n  }\n\n  return out;\n}\n\nstd::pair<std::vector<Token>, Token> Tokenize(const DiagnosticContext& ctx, const Source& source) {\n  auto tokenizer = Tokenizer(ctx, source);\n  tokenizer.Tokenize();\n  Token meta_table(Span(), TokenType::kUnknown, ObjectRef());\n  auto tokens = Condense(tokenizer.tokens, &meta_table);\n  for (auto token : tokens) {\n    ICHECK(token.defined());\n  }\n  return {tokens, meta_table};\n}\n\n}  // namespace parser\n}  // namespace tvm\n\n#endif  // TVM_PARSER_TOKENIZER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/printer/doc.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/printer/doc.h\n * \\brief Doc ADT used for pretty printing.\n *\n *  Reference: Philip Wadler. A Prettier Printer. Journal of Functional Programming'98\n */\n#ifndef TVM_PRINTER_DOC_H_\n#define TVM_PRINTER_DOC_H_\n\n#include <tvm/node/node.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n#include <type_traits>\n#include <vector>\n\nnamespace tvm {\n\n/*!\n * \\brief Doc atom node for the ADT.\n * \\sa DocAtom\n */\nclass DocAtomNode : public Object {\n public:\n  static constexpr const char* _type_key = \"printer.DocAtom\";\n  TVM_DECLARE_BASE_OBJECT_INFO(DocAtomNode, Object);\n};\n\n/*!\n * \\brief Managed reference to DocAtomNode.\n * \\sa DocAtomNode.\n */\nclass DocAtom : public ObjectRef {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(DocAtom, ObjectRef, DocAtomNode);\n};\n\n/*!\n * \\brief Stream-like interface for Doc DSL.\n *\n * The Doc DSL de-couples the layout decision from the printing decision.\n *\n * The layout(code formating) decisions include:\n * - Change indentation.\n * - Break single line into multiple ones(subjected to future improvements).\n */\nclass Doc {\n public:\n  /*! \\brief default constructor */\n  Doc() {}\n  /*!\n   * \\brief Append right to the end of the current doc stream.\n   * \\param right The doc to be appended.\n   * \\return reference to self.\n   */\n  Doc& operator<<(const Doc& right);\n  /*!\n   * \\brief Append right to the end of the current doc stream.\n   * \\param right The doc to be appended.\n   * \\return reference to self.\n   * \\note pass by value to allow copy elison optimization.\n   */\n  Doc& operator<<(std::string right);\n  /*!\n   * \\brief Append right to the end of the current doc stream.\n   * \\param right The doc to be appended.\n   * \\return reference to self.\n   */\n  Doc& operator<<(const DocAtom& right);\n  /*!\n   * \\brief Convert value to string via std::ostreamstream\n   *        the append to the current doc stream.\n   * \\param right The doc to be appended.\n   * \\tparam T the type of the value.\n   * \\return reference to self.\n   */\n  template <typename T, typename = typename std::enable_if<!std::is_class<T>::value>::type>\n  Doc& operator<<(const T& value) {\n    std::ostringstream os;\n    os << value;\n    return *this << os.str();\n  }\n  /*!\n   * \\brief Convert the doc stream into string.\n   * \\return The string representation.\n   */\n  std::string str();\n  /*!\n   * \\brief Create a doc that represents text content.\n   * \\return The created doc.\n   */\n  static Doc Text(std::string value);\n  /*!\n   * \\brief Create a doc that represents raw text(can have new lines)\n   * \\return The created doc.\n   */\n  static Doc RawText(std::string value);\n  /*!\n   * \\brief Create a doc that represents a new line.\n   * \\return The created doc.\n   */\n  static Doc NewLine(int indent = 0);\n  /*!\n   * \\brief Create a new doc that adds indentation to everyline of the doc.\n   * \\param indent The indent to be added.\n   * \\param doc The doc to be indented.\n   * \\return The created doc.\n   * \\note pass by value to allow copy elison optimization.\n   */\n  static Doc Indent(int indent, Doc doc);\n  /*!\n   * \\brief Create a Doc that represents a string literal.\n   * \\param value The content of the string literal.\n   * \\param quote The quote in the literal.\n   * \\return The created doc.\n   */\n  static Doc StrLiteral(const std::string& value, std::string quote = \"\\\"\");\n  /*!\n   * \\brief Create a Doc that represents a boolean literal in python syntax.\n   * \\param value The bool value.\n   * \\return The created doc.\n   */\n  static Doc PyBoolLiteral(bool value);\n  /*!\n   * \\brief Enclose body by brace and add indent.\n   * \\param body The body\n   * \\param open The open brace.\n   * \\param close The close brace.\n   * \\param indent amount of indentation.\n   * \\return The created doc.\n   */\n  static Doc Brace(std::string open, const Doc& body, std::string close, int indent = 2);\n  /*!\n   * \\brief Create a doc by concatenating  together with separator.\n   * \\param vec The docs to be concatenated.\n   * \\param sep The seperator.\n   * \\return The created doc.\n   */\n  static Doc Concat(const std::vector<Doc>& vec, const Doc& sep = Text(\", \"));\n\n private:\n  /*! \\brief Internal doc stream. */\n  std::vector<DocAtom> stream_;\n};\n\n}  // namespace tvm\n#endif  // TVM_PRINTER_DOC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/printer/meta_data.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/printer/meta_data.h\n * \\brief Meta data context for printers.\n */\n#ifndef TVM_PRINTER_META_DATA_H_\n#define TVM_PRINTER_META_DATA_H_\n\n#include <tvm/node/serialization.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"doc.h\"\n\nnamespace tvm {\n/*!\n * \\brief Meta data context for Printers\n *\n * This is an important part to enable bi-directional serializability.\n * We use tvm's Node system to build the current IR.\n * It can be hard to design a text format for all the possible nodes\n * as the set of nodes can grow when we do more extensions.\n *\n * Instead of trying to design readable text format for every node,\n * we support a meta data section in the text format.\n * We allow the text format to refer to a node in the meta data section.\n *\n * The meta data section is a json serialized string of an Map<string, Array<NodeRef>>.\n * Each element in the meta data section can be referenced by the text format.\n * Each meta data node is printed in the following format.\n *\n * meta[type-key-of-node>][<index-in-meta-section>]\n *\n * Specifically, consider the following IR(constructed by python).\n *\n * \\code\n *\n * n = tvm.var(\"n\")\n * x = tvm.relay.var(\"x\", shape=(n, 1))\n * f = tvm.relay.Function([x], x)\n * print(f.astext())\n *\n * \\endcode\n *\n * The corresponding text format is shown in the following code block.\n *\n * \\code\n *\n * fn (%x: Tensor[(meta[Variable][0],), float32]) {\n *   %x\n * }\n * # Meta data section is a json-serialized string\n * # of the following array.\n * # [tvm.var(\"n\")]\n *\n * \\endcode\n *\n * Note that we store tvm.var(\"n\") in the meta data section.\n * Since it is stored in the index-0 in the meta data section,\n * we print it as meta[Variable][0].\n *\n * The text parser can recover this object by loading from the corresponding\n * location in the meta data section.\n *\n * This is a design trade-off.\n * It allows us to embedded any meta data in the text format,\n * while still being able to tweak the text part of the printed IR easily.\n */\nclass TextMetaDataContext {\n public:\n  /*!\n   * \\brief Get text representation of meta node.\n   * \\param node The node to be converted to meta node.\n   * \\return A string representation of the meta node.\n   */\n  Doc GetMetaNode(const ObjectRef& node) {\n    auto it = meta_repr_.find(node);\n    if (it != meta_repr_.end()) {\n      return it->second;\n    }\n    std::string type_key = node->GetTypeKey();\n    ICHECK(!type_key.empty());\n    Array<ObjectRef>& mvector = meta_data_[type_key];\n    int64_t index = static_cast<int64_t>(mvector.size());\n    mvector.push_back(node);\n    Doc doc;\n    doc << \"meta[\" << type_key << \"][\" << index << \"]\";\n    meta_repr_[node] = doc;\n    return meta_repr_[node];\n  }\n\n  /*!\n   * \\brief Test whether a node has been put in meta\n   * \\param node The query node\n   * \\return whether the node has been put in meta\n   */\n  bool InMeta(const ObjectRef& node) { return meta_repr_.find(node) != meta_repr_.end(); }\n\n  /*!\n   * \\brief Print a key value pair\n   */\n  Doc PrintKeyValue(const std::string& str, const Doc& v) const {\n    return Doc() << \"\\\"\" << str << \"\\\": \" << v;\n  }\n\n  /*!\n   * \\brief Get the metadata section in json format.\n   * \\return the meta data string.\n   */\n  Doc GetMetaSection() const {\n    if (meta_data_.size() == 0) return Doc();\n    return Doc::RawText(SaveJSON(Map<String, ObjectRef>(meta_data_.begin(), meta_data_.end())));\n  }\n\n  /*! \\return whether the meta data context is empty. */\n  bool empty() const { return meta_data_.empty(); }\n\n private:\n  /*! \\brief additional metadata stored in TVM json format */\n  std::unordered_map<String, Array<ObjectRef>> meta_data_;\n  /*! \\brief map from meta data into its string representation */\n  std::unordered_map<ObjectRef, Doc, ObjectPtrHash, ObjectPtrEqual> meta_repr_;\n};\n}  // namespace tvm\n#endif  // TVM_PRINTER_META_DATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/printer/text_printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file text_printer.h\n * \\brief Printer to print out the unified IR text format\n *        that can be parsed by a parser.\n */\n\n#ifndef TVM_PRINTER_TEXT_PRINTER_H_\n#define TVM_PRINTER_TEXT_PRINTER_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/ir/type_functor.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/pattern_functor.h>\n#include <tvm/tir/expr_functor.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op.h>\n#include <tvm/tir/stmt_functor.h>\n#include <tvm/tir/var.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../ir/attr_functor.h\"\n#include \"../relay/analysis/dependency_graph.h\"\n#include \"doc.h\"\n#include \"meta_data.h\"\n#include \"text_printer.h\"\n\nnamespace tvm {\nclass TextPrinter;\n}  // namespace tvm\n\nnamespace tvm {\nnamespace relay {\n\nclass RelayTextPrinter : public ExprFunctor<Doc(const Expr&)>,\n                         public PatternFunctor<Doc(const Pattern&)>,\n                         public TypeFunctor<Doc(const Type&)>,\n                         public AttrFunctor<Doc(const ObjectRef&)> {\n public:\n  explicit RelayTextPrinter(bool show_meta_data, TextMetaDataContext* meta,\n                            runtime::TypedPackedFunc<std::string(ObjectRef)> annotate)\n      : show_meta_data_(show_meta_data), annotate_(annotate), meta_(meta) {}\n  Doc VisitExpr(const Expr& expr) override;\n  virtual Doc VisitLeaf(const Expr& expr);\n  virtual bool CheckVisited(const Expr& expr);\n\n  /*!\n   * \\brief Print additional info about expr in comment.\n   * \\param expr The expression.\n   */\n  Doc PrintOptionalInfo(const Expr& expr);\n  // indent a new body\n  Doc PrintBody(const ObjectRef& node, int indent = 2);\n  // create a new scope by creating a new printer object. This allows temp var\n  // numbers to be reused and prevents hoisted vars from escaping too far\n  Doc PrintScope(const ObjectRef& node);\n  Doc PrintFinal(const ObjectRef& node);\n\n  /*!\n   * \\brief Returns \\p attrs printed using the generic attribute visitor, as a sequence\n   * of key=value entries, if any.\n   */\n  void AppendGenericAttrs(std::vector<Doc>* docs, const Attrs& attrs, bool include_type_key);\n\n  /*!\n   * \\brief Returns \\p attrs printed as a sequence of key=value entries, if any.\n   * This is used for call attributes.\n   */\n  std::vector<Doc> PrintCallAttrs(const Attrs& attrs, const Expr& op);\n\n  /*!\n   * \\brief Returns \\p dict_attrs printed as a sequence of key=value entries, if any.\n   * This is used for function definition attributes.\n   */\n  std::vector<Doc> PrintDictAttrs(const DictAttrs& dict_attrs);\n  std::vector<Doc> PrintDictAttrs(const Map<String, ObjectRef>& dict_attrs);\n\n  /*!\n   * \\brief Returns \\p value printed as the rhs of an attribute key=value entry. If \\p force_meta\n   * is true then value is printed in meta[...] for irrespective of the show_meta_data_ flag.\n   */\n  Doc PrintAttributeValue(const ObjectRef& value, bool force_meta = false);\n\n  /*!\n   * \\brief Returns \\p attrs printed as a self-contained value, ie wrapped in braces.\n   */\n  Doc PrintAttrsAsAttributeValue(const Attrs& attrs);\n\n  /*!\n   * \\brief Returns \\p map printed as a self-contained value, ie wrapped in braces.\n   */\n  Doc PrintMapAsAttributeValue(const Map<ObjectRef, ObjectRef>& map);\n\n  Doc PrintSpan(const Span& span);\n\n  Doc Print(const ObjectRef& node, bool meta = false, bool try_inline = false);\n\n  Doc TempVar(int n);\n  Doc AllocTemp();\n  /*!\n   * \\brief get a unique name with the corresponding prefix\n   * \\param prefix The prefix of the name\n   * \\return The returned name.\n   */\n  Doc GetUniqueName(const std::string& prefix);\n  Doc Print(Kind k);\n  /*!\n   * \\brief Allocate name to a type variable.\n   * \\param var The input type variable.\n   * \\return The corresponding name.\n   */\n  Doc AllocTypeVar(const TypeVar& var);\n  /*!\n   * \\brief Allocate name to a variable.\n   * \\param var The input variable.\n   * \\return The corresponding name.\n   */\n  Doc AllocVar(const Var& var);\n  bool IsUnique(const Expr& expr);\n  bool AlwaysInline(const Expr& expr);\n\n  Doc PrintFunc(const Doc& prefix, const relay::Function& fn);\n  Doc PrintFunc(const Doc& prefix, const BaseFunc& base_func);\n  Doc PrintMod(const IRModule& mod);\n\n  //------------------------------------\n  // Overload of Expr printing functions\n  //------------------------------------\n  Doc PrintExpr(const Expr& expr, bool meta, bool try_inline, bool optional_info = true);\n  // Should only be triggered when op is a free variable being visited for the\n  // first time.\n  Doc VisitExpr_(const VarNode* op) final;\n  Doc VisitExpr_(const ConstantNode* op) final;\n  Doc VisitExpr_(const TupleNode* op) final;\n  Doc VisitExpr_(const TupleGetItemNode* op) final;\n  Doc VisitExpr_(const IfNode* op) final;\n  Doc VisitExpr_(const LetNode* op) final;\n  Doc VisitExpr_(const FunctionNode* op) final;\n  Doc VisitExpr_(const GlobalVarNode* op) final;\n  Doc VisitExpr_(const OpNode* op) final;\n  Doc VisitExpr_(const CallNode* op) final;\n  Doc VisitExpr_(const RefCreateNode* op) final;\n  Doc VisitExpr_(const RefReadNode* op) final;\n  Doc VisitExpr_(const RefWriteNode* op) final;\n  Doc VisitExpr_(const MatchNode* op) final;\n  Doc PrintPattern(const Pattern& pattern, bool meta);\n  Doc VisitPattern_(const PatternConstructorNode* p) final;\n  Doc VisitPattern_(const PatternTupleNode* pt) final;\n  Doc VisitPattern_(const PatternWildcardNode* pw) final;\n  Doc VisitPattern_(const PatternVarNode* pv) final;\n  Doc VisitExpr_(const ConstructorNode* n) final;\n  //------------------------------------\n  // Overload of Type printing functions\n  //------------------------------------\n  Doc PrintType(const Type& type, bool meta);\n  Doc VisitTypeDefault_(const Object* node) final;\n  Doc VisitType_(const TypeVarNode* node) final;\n  Doc VisitType_(const GlobalTypeVarNode* node) final;\n  Doc VisitType_(const TypeCallNode* node) final;\n  Doc PrintDType(DataType dtype);\n  Doc VisitType_(const TensorTypeNode* node) final;\n  Doc VisitType_(const TupleTypeNode* node) final;\n  Doc VisitType_(const FuncTypeNode* node) final;\n  Doc VisitType_(const RelayRefTypeNode* node) final;\n  Doc VisitType_(const TypeDataNode* node) final;\n  //------------------------------------\n  // Overload of Attr printing functions\n  //------------------------------------\n  Doc VisitAttrDefault_(const Object* op) final;\n  Doc VisitAttr_(const ArrayNode* op) final;\n  Doc VisitAttr_(const tir::IntImmNode* op) final;\n  Doc VisitAttr_(const tir::FloatImmNode* op) final;\n  Doc VisitAttr_(const tir::StringImmNode* op) final;\n\n private:\n  /*! \\brief Whether to print meta data. */\n  bool show_meta_data_;\n  /*! \\brief additional comment function */\n  runtime::TypedPackedFunc<std::string(ObjectRef)> annotate_;\n  /*! \\brief Stack of docs to implement scoped GNFing. */\n  std::vector<Doc> doc_stack_{};\n  /*! \\brief Set for introduced vars */\n  std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> var_memo_;\n  /*! \\brief Set for exprs have been printed optional information */\n  std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> opt_info_memo_;\n  /*! \\brief Map for result and memo_ diffs for visited expression */\n  std::unordered_map<Expr, Doc, ObjectPtrHash, ObjectPtrEqual> result_memo_;\n  /*! \\brief Map from Expr to Doc */\n  std::unordered_map<Expr, Doc, ObjectPtrHash, ObjectPtrEqual> memo_;\n  /*! \\brief Map from Type to Doc */\n  std::unordered_map<Type, Doc, ObjectPtrHash, ObjectPtrEqual> memo_type_;\n  /*! \\brief Map from Type to Doc */\n  std::unordered_map<Pattern, Doc, ObjectPtrHash, ObjectPtrEqual> memo_pattern_;\n  /*! \\brief name allocation map */\n  std::unordered_map<std::string, int> name_alloc_map_;\n  /*! \\brief meta data context */\n  TextMetaDataContext* meta_;\n  /*! \\brief counter of temporary variable */\n  size_t temp_var_counter_{0};\n  /*! \\brief whether the printer is currently in an ADT definition */\n  bool in_adt_def_;\n  /*! \\brief arena for dependency graph */\n  support::Arena arena_;\n  /*! \\brief dependency graph of the expr */\n  DependencyGraph dg_;\n  class AttrPrinter;\n  friend class AttrPrinter;\n  friend class tvm::TextPrinter;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n *  \\brief Meta node collector\n *  If we decide to put some node into meta, then all the sub-nodes inside\n *  it need to be put in meta as well, since when parsing we need to know\n *  whether two refs are the same\n */\nclass MetaCollector : public StmtExprVisitor {\n public:\n  explicit MetaCollector(TextMetaDataContext* meta) : meta_(meta) {}\n\n  void Collect(const ObjectRef& n) {\n    // these nodes can be print directly(StringLiteral or use identifier to identify)\n    if (!n.defined() || n.as<StringImmNode>() || n.as<StringObj>() || n.as<SizeVarNode>() ||\n        n.as<VarNode>() || n.as<BufferNode>() || n.as<IterVarNode>()) {\n      return;\n    }\n    if (n->IsInstance<StmtNode>()) {\n      VisitStmt(Downcast<Stmt>(n));\n    } else if (n->IsInstance<PrimExprNode>()) {\n      VisitExpr(Downcast<PrimExpr>(n));\n    }\n  }\n\n  void VisitStmt(const Stmt& n) override {\n    meta_->GetMetaNode(n);\n    StmtVisitor::VisitStmt(n);\n  }\n\n  void VisitExpr(const PrimExpr& n) override {\n    meta_->GetMetaNode(n);\n    ExprVisitor::VisitExpr(n);\n  }\n\n private:\n  TextMetaDataContext* meta_;\n};\n\nclass TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,\n                       public ExprFunctor<Doc(const PrimExpr&)>,\n                       public TypeFunctor<Doc(const Type&)> {\n public:\n  explicit TIRTextPrinter(bool show_meta, TextMetaDataContext* meta)\n      : show_meta_(show_meta), meta_(meta), meta_collector_(meta) {}\n\n  /*! \\brief Print the node */\n  Doc Print(const ObjectRef& node);\n\n  /*! \\brief Place into `s` the name used in the preceding Print call for `v`.\n   * \\param v Var instance to check. Must point to a VarNode visited by Print.\n   * \\param s String to receive the name.\n   * \\return true when a name re-mapping was found.\n   */\n  bool GetVarName(::tvm::tir::Var v, std::string* s);\n\n private:\n  /*! \\brief whether show meta data */\n  bool show_meta_;\n  /*! \\brief meta data context */\n  TextMetaDataContext* meta_;\n  /*! \\brief meta collector */\n  MetaCollector meta_collector_;\n  /*! \\brief Map from Var to Doc */\n  std::unordered_map<Var, Doc, ObjectPtrHash, ObjectPtrEqual> memo_var_;\n  /*! \\brief Map from Buffer to Doc */\n  std::unordered_map<Buffer, Doc, ObjectPtrHash, ObjectPtrEqual> memo_buf_;\n  /*! \\brief Map from Buffer to Doc */\n  std::unordered_map<DataProducer, Doc, ObjectPtrHash, ObjectPtrEqual> memo_producer_;\n  /*! \\brief name allocation map */\n  std::unordered_map<std::string, int> name_alloc_map_;\n\n  friend class tvm::TextPrinter;\n\n  Doc VisitExpr_(const IntImmNode* op) override;\n  Doc VisitExpr_(const FloatImmNode* op) override;\n  Doc VisitExpr_(const StringImmNode* op) override;\n  Doc VisitExpr_(const CastNode* op) override;\n  Doc VisitExpr_(const VarNode* op) override;\n  Doc VisitExpr_(const AddNode* op) override;\n  Doc VisitExpr_(const SubNode* op) override;\n  Doc VisitExpr_(const MulNode* op) override;\n  Doc VisitExpr_(const DivNode* op) override;\n  Doc VisitExpr_(const ModNode* op) override;\n  Doc VisitExpr_(const FloorDivNode* op) override;\n  Doc VisitExpr_(const FloorModNode* op) override;\n  Doc VisitExpr_(const MinNode* op) override;\n  Doc VisitExpr_(const MaxNode* op) override;\n  Doc VisitExpr_(const EQNode* op) override;\n  Doc VisitExpr_(const NENode* op) override;\n  Doc VisitExpr_(const LTNode* op) override;\n  Doc VisitExpr_(const LENode* op) override;\n  Doc VisitExpr_(const GTNode* op) override;\n  Doc VisitExpr_(const GENode* op) override;\n  Doc VisitExpr_(const AndNode* op) override;\n  Doc VisitExpr_(const OrNode* op) override;\n  Doc VisitExpr_(const NotNode* op) override;\n  Doc VisitExpr_(const SelectNode* op) override;\n  Doc VisitExpr_(const BufferLoadNode* op) override;\n  Doc VisitExpr_(const ProducerLoadNode* op) override;\n  Doc VisitExpr_(const LoadNode* op) override;\n  Doc VisitExpr_(const RampNode* op) override;\n  Doc VisitExpr_(const BroadcastNode* op) override;\n  Doc VisitExpr_(const LetNode* op) override;\n  Doc VisitExpr_(const CallNode* op) override;\n  Doc VisitExpr_(const ShuffleNode* op) override;\n  Doc VisitExpr_(const ReduceNode* op) override;\n  Doc VisitExprDefault_(const Object* op) override;\n\n  Doc VisitStmt_(const LetStmtNode* op) override;\n  Doc VisitStmt_(const AttrStmtNode* op) override;\n  Doc VisitStmt_(const AssertStmtNode* op) override;\n  Doc VisitStmt_(const StoreNode* op) override;\n  Doc VisitStmt_(const BufferStoreNode* op) override;\n  Doc VisitStmt_(const ProducerStoreNode* op) override;\n  Doc VisitStmt_(const BufferRealizeNode* op) override;\n  Doc VisitStmt_(const ProducerRealizeNode* op) override;\n  Doc VisitStmt_(const AllocateNode* op) override;\n  Doc VisitStmt_(const AllocateConstNode* op) override;\n  Doc VisitStmt_(const DeclBufferNode* op) override;\n  Doc VisitStmt_(const IfThenElseNode* op) override;\n  Doc VisitStmt_(const SeqStmtNode* op) override;\n  Doc VisitStmt_(const EvaluateNode* op) override;\n  Doc VisitStmt_(const ForNode* op) override;\n  Doc VisitStmt_(const WhileNode* op) override;\n  Doc VisitStmt_(const PrefetchNode* op) override;\n  Doc VisitStmt_(const BlockRealizeNode* op) override;\n  Doc VisitStmtDefault_(const Object* op) override;\n\n  Doc VisitType_(const PrimTypeNode* node) override;\n  Doc VisitType_(const PointerTypeNode* node) override;\n  Doc VisitType_(const TupleTypeNode* node) override;\n\n  Doc PrintIRModule(const IRModule& module);\n  Doc PrintPrimFunc(const PrimFunc& primFunc);\n  Doc PrintArray(const ArrayNode* op);\n  Doc PrintIterVar(const IterVarNode* op);\n  Doc PrintRange(const RangeNode* op);\n  Doc PrintBuffer(const BufferNode* op);\n  Doc PrintProducer(const DataProducerNode* op);\n  Doc BufferNode2Doc(const BufferNode* op, Doc doc);\n  Doc DataProducerNode2Doc(const DataProducerNode* op, Doc doc);\n  Doc PrintString(const StringObj* op) { return Doc::StrLiteral(op->data); }\n  Doc PrintBufferRegion(const BufferRegionNode* op);\n\n  /*!\n   * \\brief special method to print out data type\n   * \\param dtype The data type\n   */\n  static Doc PrintDType(DataType dtype);\n  /*!\n   * \\brief special method to print out const scalar\n   * \\param dtype The data type\n   * \\param data The pointer to hold the data.\n   */\n  template <typename T>\n  static Doc PrintConstScalar(DataType dtype, const T& data);\n  Doc GetUniqueName(std::string prefix);\n  Doc AllocVar(const Var& var);\n  Doc AllocConst(const AllocateConst& var);\n  Doc AllocBuf(const Buffer& buffer);\n  Doc AllocProducer(const DataProducer& buffer);\n  /*!\n   * \\brief special method to render vectors of docs with a separator\n   * \\param vec vector of docs\n   * \\param sep separator\n   */\n  static Doc PrintSep(const std::vector<Doc>& vec, const Doc& sep);\n  Doc PrintBody(const Stmt& body, bool indent = true);\n};\n\nString AsTVMScript(const ObjectRef& mod, const String& tir_prefix = \"T\", bool show_meta = false);\n\nString AsTVMScriptWithDiagnostic(const ObjectRef& mod, const String& tir_prefix, bool show_meta,\n                                 runtime::TypedPackedFunc<std::string(Stmt)> annotate);\n\n}  // namespace tir\n}  // namespace tvm\n\nnamespace tvm {\n\nclass TextPrinter {\n public:\n  explicit TextPrinter(bool show_meta_data,\n                       const runtime::TypedPackedFunc<std::string(ObjectRef)>& annotate,\n                       bool show_warning = true)\n      : show_meta_data_(show_meta_data),\n        show_warning_(show_warning),\n        annotate_(annotate),\n        relay_text_printer_(show_meta_data, &meta_, annotate),\n        tir_text_printer_(show_meta_data, &meta_) {}\n\n  /*! \\brief whether show meta data */\n  bool show_meta_data_;\n\n  /*! \\brief whether show the meta data warning message */\n  bool show_warning_;\n\n  /*! \\brief meta data context */\n  TextMetaDataContext meta_;\n  /*! \\brief additional comment function */\n  runtime::TypedPackedFunc<std::string(ObjectRef)> annotate_;\n  /*! \\brief Relay Text Printer */\n  relay::RelayTextPrinter relay_text_printer_;\n  /*! \\brief TIR Text Printer */\n  tir::TIRTextPrinter tir_text_printer_;\n\n  bool GetVarName(::tvm::tir::Var v, std::string* s) { return tir_text_printer_.GetVarName(v, s); }\n\n  Doc PrintFinal(const ObjectRef& node) {\n    Doc doc;\n    if (node.defined() && node->IsInstance<IRModuleNode>()) {\n      doc << PrintMod(Downcast<IRModule>(node));\n    } else if (node.defined() &&\n               (node->IsInstance<tir::PrimFuncNode>() || node->IsInstance<PrimExprNode>() ||\n                node->IsInstance<tir::StmtNode>())) {\n      doc << tir_text_printer_.Print(node);\n    } else {\n      doc << relay_text_printer_.PrintFinal(node);\n    }\n    if (!meta_.empty()) {\n      doc << Doc::NewLine();\n      if (show_meta_data_) {\n        doc << \"#[metadata]\" << Doc::NewLine() << meta_.GetMetaSection();\n      } else if (show_warning_) {\n        doc << \"/* For debugging purposes the metadata section has been omitted.\" << Doc::NewLine()\n            << \" * If you would like to see the full metadata section you can set the \"\n            << Doc::NewLine() << \" * option to `True` when invoking `astext`. \" << Doc::NewLine()\n            << \" */\";\n      }\n    }\n    return doc;\n  }\n\n  Doc PrintMod(const IRModule& mod);\n};\n}  // namespace tvm\n\n#endif  // TVM_PRINTER_TEXT_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/analysis/annotated_region_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/transforms/annotated_region_set.h\n * \\brief Define data structures to extract and manipulate regions from\n * a relay function. Regions are denoted by region_begin and region_end\n * annotations that exist on all the input and output edges of the region.\n */\n\n#ifndef TVM_RELAY_ANALYSIS_ANNOTATED_REGION_SET_H_\n#define TVM_RELAY_ANALYSIS_ANNOTATED_REGION_SET_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/annotation.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/transform.h>\n\n#include <list>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\nclass AnnotatedRegion;\nclass AnnotatedRegionSet;\n\nclass AnnotatedRegionNode : public Object {\n public:\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"id\", &id_);\n    v->Visit(\"target\", &target_);\n    Array<Expr> nodes_array(nodes_.begin(), nodes_.end());\n    v->Visit(\"nodes\", &nodes_array);\n    Array<Expr> args_array(ins_.begin(), ins_.end());\n    v->Visit(\"args\", &args_array);\n    Array<Expr> rets_array(outs_.begin(), outs_.end());\n    v->Visit(\"rets\", &rets_array);\n  }\n\n  /*! \\brief Get the region ID. */\n  int GetID() const { return id_; }\n\n  /*! \\brief Get the region name. */\n  std::string GetName() const { return func_name_; }\n\n  /*! \\brief Get the region target. */\n  std::string GetTarget() const { return target_; }\n\n  /*! \\brief Get the region's inputs. */\n  std::list<Expr> GetInputs() const { return ins_; }\n\n  /*! \\brief Get the region's outputs. */\n  std::list<Expr> GetOutputs() const { return outs_; }\n\n  /*! \\brief Get the region's nodes. */\n  std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> GetNodes() const { return nodes_; }\n\n  static constexpr const char* _type_key = \"relay.AnnotatedRegion\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AnnotatedRegionNode, Object);\n\n protected:\n  /*! \\brief The region ID. */\n  int id_{-1};\n  /*! \\brief The func name. */\n  std::string func_name_ = \"default\";\n  /*! \\brief The target for this region. */\n  std::string target_ = \"default\";\n  /*! \\brief The inputs to this region. */\n  std::list<Expr> ins_;\n  /*! \\brief The outputs of this region */\n  std::list<Expr> outs_;\n  /*! \\brief Nodes in this region. */\n  std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> nodes_;\n\n  friend class AnnotatedRegionSet;\n  friend class AnnotatedRegionSetNode;\n};\n\n/*!\n * \\brief An object to hold the properties of a region as used by the\n * AnnotatedRegionSet class. This should be considered read-only.\n */\nclass AnnotatedRegion : public ObjectRef {\n public:\n  AnnotatedRegion() {\n    auto n = make_object<AnnotatedRegionNode>();\n    data_ = std::move(n);\n  }\n\n  /*!\n   * \\brief Construct from an object pointer.\n   * \\param n The object pointer.\n   */\n  explicit AnnotatedRegion(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*! \\return Mutable pointers to the node. */\n  AnnotatedRegionNode* operator->() const {\n    auto* ptr = get_mutable();\n    ICHECK(ptr != nullptr);\n    return static_cast<AnnotatedRegionNode*>(ptr);\n  }\n};\n\nclass AnnotatedRegionSetNode : public Object {\n  using UnorderedRegionSet = std::unordered_set<AnnotatedRegion, ObjectPtrHash, ObjectPtrEqual>;\n  // Create iterator alias for a RegionSet object.\n  using iterator = UnorderedRegionSet::iterator;\n  using const_iterator = UnorderedRegionSet::const_iterator;\n\n public:\n  /*! \\brief Default constructor. */\n  AnnotatedRegionSetNode() = default;\n\n  /*! \\return The begin iterator */\n  iterator begin() { return regions_.begin(); }\n  /*! \\return The end iterator */\n  iterator end() { return regions_.end(); }\n  /*! \\return The const begin iterator */\n  const_iterator begin() const { return regions_.begin(); }\n  /*! \\return The const end iterator */\n  const_iterator end() const { return regions_.end(); }\n\n  /*!\n   * \\brief Get the region that an expression belongs to.\n   *\n   * \\param expr Which expr to get the region for.\n   *\n   * \\return A pointer to the region, nullptr if the expression\n   * doesn't belong to a region.\n   */\n  AnnotatedRegion GetRegion(const Expr& expr) const;\n\n  /*!\n   * \\brief Merge src region into dest region.\n   *\n   * \\param src The region to merge - will be erased.\n   * \\param dest The region into which src will be merged.\n   */\n  void MergeRegions(AnnotatedRegion src, AnnotatedRegion dest);\n\n  void VisitAttrs(AttrVisitor* v) {\n    Array<AnnotatedRegion> regions_array(regions_.begin(), regions_.end());\n    v->Visit(\"regions\", &regions_array);\n  }\n\n  static constexpr const char* _type_key = \"relay.AnnotatedRegionSet\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AnnotatedRegionSetNode, Object);\n\n private:\n  /*!\n   * \\brief Add an expression to a region.\n   *\n   * \\param dest The region to add the expression to.\n   * \\param expr The expression.\n   */\n  void AddToRegion(AnnotatedRegion dest, const Expr& expr);\n\n  /*!\n   * \\brief Make a new region for a target.\n   *\n   * \\return The new region.\n   */\n  AnnotatedRegion MakeRegion(const std::string& func_name, const std::string& target);\n\n  std::unordered_set<AnnotatedRegion, ObjectPtrHash, ObjectPtrEqual> regions_;\n  /*! \\brief The next region ID to assign. */\n  int region_id_{0};\n\n  friend class AnnotatedRegionSet;\n};\n\n/*!\n * \\brief A class to hold a set of regions produced from a relay expression\n * that contains 'region_begin' and 'region_end' style annotations. The\n * regions should be disjoint. The class provides both a method to construct\n * the region set of a given relay expression as well as additional methods\n * to update and query regions.\n */\nclass AnnotatedRegionSet : public ObjectRef {\n  using UnorderedRegionSet = std::unordered_set<AnnotatedRegion, ObjectPtrHash, ObjectPtrEqual>;\n  // Create iterator alias for a RegionSet object.\n  using iterator = UnorderedRegionSet::iterator;\n  using const_iterator = UnorderedRegionSet::const_iterator;\n\n public:\n  AnnotatedRegionSet() {\n    auto n = make_object<AnnotatedRegionSetNode>();\n    data_ = std::move(n);\n  }\n\n  /*!\n   * \\brief Construct from an object pointer.\n   *\n   * \\param n The object pointer.\n   */\n  explicit AnnotatedRegionSet(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*! \\return The begin iterator. */\n  iterator begin() {\n    auto* n = operator->();\n    ICHECK(n);\n    return n->begin();\n  }\n  /*! \\return The end iterator. */\n  iterator end() {\n    auto* n = operator->();\n    ICHECK(n);\n    return n->end();\n  }\n  /*! \\return The begin iterator. */\n  const_iterator begin() const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return n->begin();\n  }\n  /*! \\return The end iterator. */\n  const_iterator end() const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return n->end();\n  }\n\n  /*! \\return mutable pointers to the node. */\n  AnnotatedRegionSetNode* operator->() const {\n    auto* ptr = get_mutable();\n    ICHECK(ptr != nullptr);\n    return static_cast<AnnotatedRegionSetNode*>(ptr);\n  }\n\n  /*! \\return The region an expression belongs to. */\n  AnnotatedRegion operator[](const Expr& expr) {\n    const auto* n = operator->();\n    ICHECK(n);\n    return n->GetRegion(expr);\n  }\n\n  /*! \\brief Create a RegionSet from a relay expression.\n   *\n   * \\param expr The relay expr from which to construct the set.\n   * \\param begin Region begin annotation operator.\n   * \\param end Region end annotation operator.\n   * \\param func_name function name\n   *\n   * \\return The created RegionSet for the expression.\n   */\n  static AnnotatedRegionSet Create(const Expr& expr, const Op& begin, const Op& end,\n                                   const std::string& func_name = \"default\");\n\n private:\n  /*! \\brief Helper class to construct a RegionSet from an expr.*/\n  class Creator;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_ANALYSIS_ANNOTATED_REGION_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/analysis/call_graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/analysis/call_graph.h\n * \\brief Define data structures for the call graph of a IRModule. It borrows\n * the idea how LLVM constructs CallGraph.\n *\n * https://llvm.org/doxygen/CallGraph_8h_source.html\n */\n\n#ifndef TVM_RELAY_ANALYSIS_CALL_GRAPH_H_\n#define TVM_RELAY_ANALYSIS_CALL_GRAPH_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/runtime/object.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\nclass CallGraphEntry;\nclass CallGraph;\n\nclass CallGraphNode : public Object {\n  using CallGraphMap =\n      std::unordered_map<GlobalVar, std::unique_ptr<CallGraphEntry>, ObjectPtrHash, ObjectPtrEqual>;\n  // Create iterator alias for a CallGraphNode object.\n  using iterator = CallGraphMap::iterator;\n  using const_iterator = CallGraphMap::const_iterator;\n\n public:\n  /*! \\brief The IR module for creating a CallGraphNode. */\n  IRModule module;\n\n  /*! \\brief Default constructor. */\n  CallGraphNode() {}\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"module\", &module); }\n\n  /*!\n   * \\brief Print the call graph.\n   *\n   * \\param os The stream for printing.\n   */\n  void Print(std::ostream& os) const;\n\n  /*! \\return The begin iterator. */\n  iterator begin() { return call_graph_.begin(); }\n  /*! \\return The end iterator. */\n  iterator end() { return call_graph_.end(); }\n  /*! \\return The begin iterator. */\n  const_iterator begin() const { return call_graph_.begin(); }\n  /*! \\return The end iterator. */\n  const_iterator end() const { return call_graph_.end(); }\n\n  /*!\n   * \\brief Get an element from the CallGraphNode using a GlobalVar.\n   *\n   * \\param gv The GlobalVar used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  const CallGraphEntry* operator[](const GlobalVar& gv) const;\n  /*!\n   * \\brief Get an element from the CallGraphNode using a GlobalVar.\n   *\n   * \\param gv The GlobalVar used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  CallGraphEntry* operator[](const GlobalVar& gv);\n  /*!\n   * \\brief Get an element from the CallGraphNode using the global function name.\n   *\n   * \\param gvar_name The global function name used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  const CallGraphEntry* operator[](const std::string& gvar_name) const {\n    return (*this)[module->GetGlobalVar(gvar_name)];\n  }\n  /*!\n   * \\brief Get an element from the CallGraphNode using the global function name.\n   *\n   * \\param gvar_name The global function name used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  CallGraphEntry* operator[](const std::string& gvar_name) {\n    return (*this)[module->GetGlobalVar(gvar_name)];\n  }\n\n  /*!\n   * \\brief Get the global function corresponding to the variable.\n   *\n   * \\param var The global variable.\n   *\n   * \\return The found global function.\n   */\n  BaseFunc GetGlobalFunction(const GlobalVar& var) const;\n\n  /*!\n   * \\brief Get the entries/root nodes of CallGraphNode.\n   *\n   *  Entry functions are never referenced by other functions.\n   *  Note these functions can be recursive as well.\n   *\n   * \\return The list of CallGraphEntry that represent entry nodes.\n   */\n  std::vector<CallGraphEntry*> GetEntryGlobals() const;\n\n  /*!\n   * \\brief Remove a GlobalVar in a given CallGraphEntry from the current\n   *        IR module.\n   *\n   * \\param cg_node The CallGraphEntry that contains a global function to be\n   *        removed.\n   * \\param update_call_graph Indicate if we will update the CallGraph as well\n   *        since updating is costly. We are only able to remove a leaf function\n   *        when update_call_graph is disabled because the edges pointing to\n   *        functions being removed are not updated.\n   *\n   * \\return The GlobalVar removed from the current module.\n   */\n  GlobalVar RemoveGlobalVarFromModule(CallGraphEntry* cg_node, bool update_call_graph = false);\n\n  /*!\n   * \\brief Lookup a GlobalVar for the CallGraphNode. It creates an entry for\n   *        the GlobalVar if it doesn't exist.\n   *\n   * \\param gv The GlobalVar for query.\n   *\n   * \\return The queried entry.\n   */\n  CallGraphEntry* LookupGlobalVar(const GlobalVar& gv);\n\n  /*!\n   * \\brief Get the entries from the CallGraphNode in the topological order.\n   *\n   *  This is useful for various module-level optimizations/analysis. For example,\n   *  inlining requires the correct order of the functions being processed, i.e.\n   *  callee should be always handled before callers.\n   *\n   * \\return The list of collected entries that are sorted in the topological order.\n   */\n  std::vector<CallGraphEntry*> TopologicalOrder() const;\n\n  static constexpr const char* _type_key = \"relay.CallGraph\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CallGraphNode, Object);\n\n private:\n  /*!\n   * \\brief Create a CallGraphEntry for a global function and add it to the\n   *        CallGraphNode.\n   *\n   * \\param gv The global var.\n   * \\param func The global function corresponding to `gv`.\n   */\n  void AddToCallGraph(const GlobalVar& gv, const Function& func);\n\n  /*! \\brief A record contains GlobalVar to CallGraphEntry mapping. */\n  CallGraphMap call_graph_;\n\n  friend CallGraph;\n};\n\n/*!\n * \\brief The class that represents the call graph of a Relay IR module. It also\n * provides a variety of utility functions for users to query, view, and update\n * a call graph.\n */\nclass CallGraph : public ObjectRef {\n  using CallGraphMap =\n      std::unordered_map<GlobalVar, std::unique_ptr<CallGraphEntry>, ObjectPtrHash, ObjectPtrEqual>;\n  // Create iterator alias for a CallGraph object.\n  using iterator = CallGraphMap::iterator;\n  using const_iterator = CallGraphMap::const_iterator;\n\n public:\n  /*!\n   * \\brief Construct a CallGraph from a IR module.\n   *\n   * \\param module The IR module\n   */\n  explicit CallGraph(IRModule module);\n\n  /*!\n   * \\brief Construct from an object pointer.\n   * \\param n The object pointer.\n   */\n  explicit CallGraph(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*! \\return The begin iterator. */\n  iterator begin() {\n    auto* n = operator->();\n    ICHECK(n);\n    return n->begin();\n  }\n  /*! \\return The end iterator. */\n  iterator end() {\n    auto* n = operator->();\n    ICHECK(n);\n    return n->end();\n  }\n  /*! \\return The begin iterator. */\n  const_iterator begin() const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return n->begin();\n  }\n  /*! \\return The end iterator. */\n  const_iterator end() const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return n->end();\n  }\n\n  /*!\n   * \\brief Get an element from the CallGraph using a GlobalVar.\n   *\n   * \\param gv The GlobalVar used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  const CallGraphEntry* operator[](const GlobalVar& gv) const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return (*n)[gv];\n  }\n  /*!\n   * \\brief Get an element from the CallGraph using a GlobalVar.\n   *\n   * \\param gv The GlobalVar used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  CallGraphEntry* operator[](const GlobalVar& gv) {\n    auto* n = operator->();\n    ICHECK(n);\n    return (*n)[gv];\n  }\n  /*!\n   * \\brief Get an element from the CallGraph using the global function name.\n   *\n   * \\param gvar_name The global function name used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  const CallGraphEntry* operator[](const std::string& gvar_name) const {\n    const auto* n = operator->();\n    ICHECK(n);\n    return (*n)[gvar_name];\n  }\n  /*!\n   * \\brief Get an element from the CallGraph using the global function name.\n   *\n   * \\param gvar_name The global function name used for indexing.\n   *\n   * \\return The fetched element.\n   */\n  CallGraphEntry* operator[](const std::string& gvar_name) {\n    auto* n = operator->();\n    ICHECK(n);\n    return (*n)[gvar_name];\n  }\n\n  /*! \\return mutable pointers to the node. */\n  CallGraphNode* operator->() const {\n    auto* ptr = get_mutable();\n    ICHECK(ptr != nullptr);\n    return static_cast<CallGraphNode*>(ptr);\n  }\n\n private:\n  /*! \\brief Overload the << operator to print a call graph. */\n  friend std::ostream& operator<<(std::ostream& os, const CallGraph&);\n};\n\n/*!\n * \\brief A node in the call graph. It maintains the edges from a caller to\n * all callees.\n */\nclass CallGraphEntry {\n public:\n  using CallGraphEntryPair = std::pair<GlobalVar, CallGraphEntry*>;\n  using CallGraphEntryVector = std::vector<CallGraphEntryPair>;\n  using CallGraphEntrySet = std::unordered_set<const CallGraphEntry*>;\n  // Create iterator alias for a CallGraphEntry object.\n  using iterator = std::vector<CallGraphEntryPair>::iterator;\n  using const_iterator = std::vector<CallGraphEntryPair>::const_iterator;\n\n  /*!\n   * \\brief Construct from a GlobalVar.\n   *\n   * \\param gv The GlobalVar to create a CallGraphEntry.\n   */\n  explicit CallGraphEntry(const GlobalVar& gv) : global_(gv) {}\n  /*!\n   * \\brief Delete copy constructor.\n   */\n  CallGraphEntry(const CallGraphEntry&) = delete;\n  /*! \\brief Delete assignment. */\n  CallGraphEntry& operator=(const CallGraphEntry&) = delete;\n\n  /*! \\return The begin iterator */\n  iterator begin() { return called_globals_.begin(); }\n  /*! \\return The end iterator */\n  iterator end() { return called_globals_.end(); }\n  /*! \\return The const begin iterator */\n  const_iterator begin() const { return called_globals_.begin(); }\n  /*! \\return The const end iterator */\n  const_iterator end() const { return called_globals_.end(); }\n\n  /*!\n   * \\brief Return if the list of called nodes is empty.\n   *\n   * \\return true if the list is empty. Otherwise, false.\n   */\n  bool empty() const { return called_globals_.empty(); }\n\n  /*!\n   * \\brief Return the size of the list that represents the nodes are called by\n   * the current node.\n   *\n   * \\return The number of called nodes.\n   */\n  uint32_t size() const { return static_cast<uint32_t>(called_globals_.size()); }\n\n  /*!\n   * \\brief Fetch the i-th CallGraphEntry from the list of nodes that are called\n   * by the current function.\n   *\n   * \\param i The index.\n   *\n   * \\return The fetched CallGraphEntry.\n   */\n  CallGraphEntry* operator[](size_t i) const {\n    ICHECK_LT(i, called_globals_.size()) << \"Invalid Index\";\n    return called_globals_[i].second;\n  }\n\n  /*!\n   * \\brief Print the call graph that is stemmed from the current CallGraphEntry.\n   *\n   * \\param os The stream for printing.\n   */\n  void Print(std::ostream& os) const;\n\n  /*!\n   * \\brief Return the number of times the global function is referenced.\n   *\n   * \\return The count.\n   */\n  uint32_t GetRefCount() const { return ref_cnt_; }\n\n  /*!\n   * \\brief Return the GlobalVar stored in the current CallGraphEntry.\n   *\n   * \\return The GlobalVar.\n   */\n  GlobalVar GetGlobalVar() const { return global_; }\n\n  /*!\n   * \\brief Return the name hint of the GlobalVar stored in the CallGraphEntry.\n   *\n   * \\return The name hint of the global function.\n   */\n  std::string GetNameHint() const { return global_->name_hint; }\n\n  /*!\n   * \\brief Return if the global function corresponding to the current\n   * CallGraphEntry is a recursive function.\n   *\n   * \\return true if it is recursive. Otherwise, false.\n   */\n  bool IsRecursive() const { return is_recursive_; }\n\n  /*!\n   * \\brief Return if the global function corresponding to the current\n   * CallGraphEntry is both a recursive function and an entry function. This type\n   * of function only has one reference which is called by itself.\n   *\n   * \\return true if it is both a recursive function and an entry. Otherwise, false.\n   */\n  bool IsRecursiveEntry() const { return GetRefCount() == 1 && IsRecursive(); }\n\n  /*!\n   * \\brief Return the topological order of the CallGraphEntry.\n   *\n   * \\param visited A set of CallGraphEntry objects that have been visited.\n   *\n   * \\return The list of CallGraphEntry that is represented in topological order.\n   */\n  std::vector<CallGraphEntry*> TopologicalOrder(\n      CallGraphEntrySet* visited = new CallGraphEntrySet()) const;\n\n  /*!\n   * \\brief Remove all edges from the current CallGraphEntry to any global\n   * function it calls.\n   */\n  void CleanCallGraphEntries();\n\n  /*!\n   * \\brief Add a node to the list of nodes that are being called by the current\n   * global function.\n   *\n   * \\param cg_node The CallGraphEntry that will be added to the call list.\n   */\n  void AddCalledGlobal(CallGraphEntry* cg_node);\n\n  /*!\n   * \\brief Remove a call edge to the global function from the current\n   * function.\n   *\n   * \\param callee The function that is being called.\n   */\n  void RemoveCallTo(const GlobalVar& callee);\n\n  /*!\n   * \\brief Remove all the edges that represent that calls to the global function\n   * stored in a given CallGraphEntry.\n   *\n   * \\param callee The function that is being called.\n   */\n  void RemoveAllCallTo(CallGraphEntry* callee);\n\n private:\n  /*! \\brief Decrement the reference counter by 1. */\n  void DecRef() {\n    ICHECK_GT(ref_cnt_, 0);\n    --ref_cnt_;\n  }\n  /*! \\brief Increment the reference counter by 1. */\n  void IncRef() { ++ref_cnt_; }\n\n  /*!\n   * \\brief Mark if the global function stored in the CallGraphEntry is\n   * recursive function.\n   */\n  bool is_recursive_{false};\n  /*! \\brief Count the number of times the global function is referenced. */\n  uint32_t ref_cnt_{0};\n  /*! \\brief The GlobalVar stored in the current CallGraphEntry. */\n  GlobalVar global_;\n  /*! \\brief The list of entries called by the current CallGraphEntry. */\n  CallGraphEntryVector called_globals_;\n\n  friend class CallGraph;\n  /*! \\brief Overload the << operator to print a call graph node. */\n  friend std::ostream& operator<<(std::ostream& os, const CallGraphEntry&);\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ANALYSIS_CALL_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/analysis/dependency_graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/analysis/dependency_graph.h\n * \\brief create a dependency graph.\n */\n#ifndef TVM_RELAY_ANALYSIS_DEPENDENCY_GRAPH_H_\n#define TVM_RELAY_ANALYSIS_DEPENDENCY_GRAPH_H_\n\n#include <tvm/relay/expr.h>\n\n#include <unordered_map>\n#include <vector>\n\n#include \"../../support/arena.h\"\n#include \"../transforms/let_list.h\"\n\nnamespace tvm {\nnamespace relay {\n\nusing support::LinkedList;\nusing support::LinkNode;\n\n/* DependencyGraph track input and output of an Expr.\n * Additionally, dummy scope is created to model scope.\n * It allow us to traverse the graph in reverse order.\n */\nclass DependencyGraph {\n public:\n  /*! \\brief A node in the graph. */\n  struct Node {\n    // Determine scope boundaries. Used for calculating scopes, not for\n    // constructing dependency graph.\n    bool new_scope = false;\n    // incoming edges\n    LinkedList<Node*> children;\n    // outgoing edges\n    LinkedList<Node*> parents;\n  };\n\n  /*! \\brief Maps a Relay Expr to its node in the dependency graph. */\n  std::unordered_map<Expr, Node*, ObjectPtrHash, ObjectPtrEqual> expr_node;\n\n  /*! \\brief The dependency graph in post DFS order. */\n  std::vector<Node*> post_dfs_order;\n\n  /*!\n   * \\brief Create a dependency graph.\n   * \\param arena The arena used for data allocation.\n   * \\param body The body of the expression to create a graph.\n   */\n  static DependencyGraph Create(support::Arena* arena, const Expr& body);\n\n private:\n  class Creator;\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ANALYSIS_DEPENDENCY_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/analysis/type_solver.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file type_solver.h\n * \\brief Solver logic for type inference.\n */\n#ifndef TVM_RELAY_ANALYSIS_TYPE_SOLVER_H_\n#define TVM_RELAY_ANALYSIS_TYPE_SOLVER_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../support/arena.h\"\n\nnamespace tvm {\nnamespace relay {\n\nusing support::LinkedList;\nusing support::LinkNode;\n\n/*!\n * \\brief Interface of type solver used in type inference.\n *\n * TypeSolver works on a list of constraints among incomplete types.\n * The user will populate the constraints by AddConstraint and Assign.\n * Then we can call Solve to trying to resolve the unknown.\n *\n * This can be viewed as \"type program(computational graph)\" of types, where\n * the type constraint are operators of the graph and the incomplete\n * types are intermediate value of the graph.\n * If all the input types are concretely known, we should be able to\n * just run a forward pass on the \"type program\" to get all the types.\n *\n * The list of constraints representation means we are storing it as a bipartite\n * graph instead of a DAG. This is because some constraints might go both direction.\n * TypeSolver could take advantage of bidirectional constraints to deduce input\n * value given output ones. Never-the-less, we should keep in mind that\n * there is a \"forward direction\" that the TypeSolver should take advantage of.\n */\nclass TypeSolver {\n public:\n  TypeSolver(const GlobalVar& current_func, DiagnosticContext diag_ctx);\n  ~TypeSolver();\n  /*!\n   * \\brief Add a type constraint to the solver.\n   * \\param constraint The constraint to be added.\n   * \\param location The location at which the constraint was incurred.\n   */\n  void AddConstraint(const TypeConstraint& constraint, const Span& span);\n  /*!\n   * \\brief Resolve type to the solution type in the solver.\n   * \\param type The type to be resolved.\n   * \\return The resolved type.\n   */\n  Type Resolve(const Type& type);\n  /*!\n   * \\brief Start to solve the types using the current known information.\n   * \\return Whether all the incomplete types has been fully resolved.\n   */\n  bool Solve();\n  /*!\n   * \\brief Unify lhs and rhs.\n   * \\param lhs The left operand.\n   * \\param rhs The right operand\n   * \\param location The location at which the unification problem arose.\n   */\n  Type Unify(const Type& lhs, const Type& rhs, const Span& span, bool assign_lhs = true,\n             bool assign_rhs = true);\n  /*!\n   * \\brief Report a diagnostic.\n   * \\param diag The diagnostic to report.\n   */\n  void Emit(const Diagnostic& diag) { diag_ctx_.Emit(diag); }\n\n private:\n  class OccursChecker;\n  class Unifier;\n  class Resolver;\n  class Propagator;\n  class Merger;\n  class Reporter;\n  struct TypeNode;\n  struct RelationNode;\n  // Internally the solver maintains a bipartite graph of Relation and Types.\n  // All the object in the structure is managed by a arena allocator\n  // which releases the memory upon distruction of the type solver.\n  /*!\n   * \\brief type node struct\n   *  TypeNode implements a union-find data structure(via parent)\n   *  that can unifies the same types to the name resolved_type.\n   *\n   *  It also contains collection of links to related Relations,\n   *  which is stored in rel_set.\n   */\n  struct TypeNode {\n    /*! \\brief The final resolved type */\n    Type resolved_type;\n    /*! \\brief type node in the union find algorithm */\n    TypeNode* parent{nullptr};\n    /*! \\brief set of relations that is related to this type node */\n    std::unordered_set<RelationNode*> rel_set;\n\n    /*!\n     * \\brief Find the root type node, perform path compression\n     * \\return The root type node.\n     */\n    TypeNode* FindRoot() {\n      // fast path\n      if (this->parent == nullptr) return this;\n      // slow path with path compression.\n      TypeNode* root = this;\n      while (root->parent != nullptr) {\n        root = root->parent;\n      }\n      for (TypeNode* p = this; p != root;) {\n        TypeNode* parent = p->parent;\n        p->parent = root;\n        p = parent;\n      }\n      return root;\n    }\n  };\n\n  /*! \\brief relation node */\n  struct RelationNode {\n    /*! \\brief Whether the relation is in the queue to be solved */\n    bool inqueue{false};\n    /*! \\brief Whether the relation is resolved */\n    bool resolved{false};\n    /*! \\brief The corresponding type relation */\n    TypeRelation rel;\n    /*! \\brief list types to this relation */\n    LinkedList<TypeNode*> type_list;\n    /*! \\brief The location this type relation originated from. */\n    Span span;\n  };\n\n  /*! \\brief A simple union find between shapes. */\n  tvm::Map<IndexExpr, IndexExpr> shape_uf_;\n  /*! \\brief List of all allocated type nodes */\n  std::vector<TypeNode*> type_nodes_;\n  /*! \\brief List of all allocated relation nodes */\n  std::vector<RelationNode*> rel_nodes_;\n  /*! \\brief Number of resolved relations */\n  size_t num_resolved_rels_{0};\n  /*! \\brief map from types to type nodes. */\n  std::unordered_map<Type, TypeNode*, ObjectPtrHash, ObjectPtrEqual> tmap_;\n  /*! \\brief Internal queue to update the relation */\n  std::queue<RelationNode*> update_queue_;\n  /*! \\brief allocator of all the internal node obhect*/\n  support::Arena arena_;\n  /*! \\brief Reporter that reports back to self */\n  TypeReporter reporter_;\n  /*! \\brief The global representing the current function. */\n  GlobalVar current_func_;\n  /*! \\brief The diagnostic context. */\n  DiagnosticContext diag_ctx_;\n  /*! \\brief The module. */\n  IRModule module_;\n\n  /*!\n   * \\brief GetTypeNode that is corresponds to t.\n   * if it do not exist, create a new one.\n   * \\return The type node.\n   */\n  TypeNode* GetTypeNode(const Type& t) {\n    auto it = tmap_.find(t);\n    if (it != tmap_.end()) {\n      return it->second->FindRoot();\n    } else {\n      TypeNode* n = arena_.make<TypeNode>();\n      type_nodes_.push_back(n);\n      n->resolved_type = t;\n      tmap_[t] = n;\n      return n;\n    }\n  }\n  /*!\n   * \\brief Add relation node rel to the update queue\n   * \\param rel The relation node\n   */\n  void AddToQueue(RelationNode* rel) {\n    if (rel->inqueue) return;\n    ICHECK(!rel->resolved);\n    rel->inqueue = true;\n    update_queue_.push(rel);\n  }\n\n  /*!\n   * \\brief Merge rhs type node to lhs\n   * \\param src The source operand\n   * \\param dst The dst operand.\n   */\n  void MergeFromTo(TypeNode* src, TypeNode* dst);\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_ANALYSIS_TYPE_SOLVER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/aot/aot_lower_main.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RELAY_BACKEND_AOT_AOT_LOWER_MAIN_H_\n#define TVM_RELAY_BACKEND_AOT_AOT_LOWER_MAIN_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/target/compilation_config.h>\n\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n\n#include \"../utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace backend {\nnamespace aot {\n\nusing StorageMap =\n    std::unordered_map<Expr, StorageInfo, runtime::ObjectPtrHash, runtime::ObjectPtrEqual>;\n\n/*! \\brief Exposed for testing, part of the implementation of AOTLowerMain */\nstd::tuple<StorageMap, std::vector<int>> CreateStorage(const Function& func);\n\n/*! \\brief Lower the Relay main function into TIR for use with the AOT executor.\n *\n * This pass expects that all operators have already been lowered to TIR and\n * so only Calls to 'call_lowered' are present in main.\n *\n * \\param mod_name The name of the module.\n * \\param config The compilation config.\n * \\param call_type The call type to use when calling functions.\n */\ntransform::Pass AOTLowerMain(String mod_name, tvm::CompilationConfig config, CallType call_type);\n\n}  // namespace aot\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_AOT_AOT_LOWER_MAIN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/aot/create_executor_metadata.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RELAY_BACKEND_AOT_CREATE_EXECUTOR_METADATA_H_\n#define TVM_RELAY_BACKEND_AOT_CREATE_EXECUTOR_METADATA_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/relay/executor.h>\n#include <tvm/runtime/container/string.h>\n\n#include \"../utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace backend {\nnamespace aot {\n\n/*! \\brief Create ExecutorCodegenMetadata needed for AOT execution.\n * \\param mod The module.\n * \\param mod_name The module name.\n * \\param executor The executor configuration.\n * \\param workspace_byte_alignment The alignment of the workspace pool.\n * \\param constant_byte_alignment The alignment of the constant pool.\n * \\return The ExecutorCodegenMetadata.\n */\nExecutorCodegenMetadata CreateExecutorMetadata(const IRModule& mod, String mod_name,\n                                               Executor executor, Integer workspace_byte_alignment,\n                                               Integer constant_byte_alignment);\n\n}  // namespace aot\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_AOT_CREATE_EXECUTOR_METADATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/aot/create_function_metadata.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RELAY_BACKEND_AOT_CREATE_FUNCTION_METADATA_H_\n#define TVM_RELAY_BACKEND_AOT_CREATE_FUNCTION_METADATA_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n\n#include \"../utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace backend {\nnamespace aot {\n\n/*! \\brief Create FunctionInfo metadata for all the PrimFuncs in a module lowered\n *  for AOT execution.\n * \\param mod The module.\n * \\param workspace_byte_alignment The alignment of the workspace pool.\n * \\param constant_byte_alignment The alignment of the constant pool.\n * \\return A map between function names and FunctionInfos.\n */\nMap<String, FunctionInfo> CreateFunctionMetadata(const IRModule& mod,\n                                                 Integer workspace_byte_alignment,\n                                                 Integer constant_byte_alignment);\n\n}  // namespace aot\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_AOT_CREATE_FUNCTION_METADATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/cmsisnn/buffer_size.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/cmsisnn/buffer_size.h\n * \\brief CMSIS-NN Buffer Size calculation functions\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CMSISNN_BUFFER_SIZE_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CMSISNN_BUFFER_SIZE_H_\n\n#include <tvm/ir/transform.h>\n\n#include \"compiler_attrs.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace cmsisnn {\n\n#define CH_IN_BLOCK_MVE (124)\n\n/*!\n * \\brief Calculates the appropriate buffer size for CMSIS-NN Convolutions\n * See:\n * https://github.com/ARM-software/CMSIS_5/blob/8c60448c0e1e50e426180b26db9bc31ddf774361/CMSIS/NN/Source/ConvolutionFunctions/arm_convolve_wrapper_s8.c#L108-L127\n *\n * \\param is_int16 - type of conv2d\n * \\param target - CMSIS-NN Target\n * \\param padding_w - Width padding\n * \\param padding_h - Height padding\n * \\param input_n - Input batch size\n * \\param input_h - Input height\n * \\param input_c - Input channels\n * \\param output_h - Output height\n * \\param output_w - Output width\n * \\param stride_w - Stride width\n * \\param stride_h - Stride height\n * \\param filter_w - Filter width\n * \\param filter_h - Filter height\n *\n * \\return Size of buffer to allocate for convolution\n */\nint Conv2dBufferSize(bool is_int16, Target target, int32_t padding_w, int32_t padding_h,\n                     int32_t input_n, int32_t input_h, int32_t input_c, int32_t output_h,\n                     int32_t output_w, int32_t stride_w, int32_t stride_h, int32_t dilation_w,\n                     int32_t dilation_h, int32_t filter_w, int32_t filter_h);\n\nint Conv2dBufferSizeInt8(Target target, int32_t padding_w, int32_t padding_h, int32_t input_n,\n                         int32_t input_h, int32_t input_c, int32_t output_h, int32_t output_w,\n                         int32_t stride_w, int32_t stride_h, int32_t dilation_w, int32_t dilation_h,\n                         int32_t filter_w, int32_t filter_h);\n\nint Conv2dBufferSizeInt16(Target target, int32_t padding_w, int32_t padding_h, int32_t input_n,\n                          int32_t input_h, int32_t input_c, int32_t output_h, int32_t output_w,\n                          int32_t stride_w, int32_t stride_h, int32_t dilation_w,\n                          int32_t dilation_h, int32_t filter_w, int32_t filter_h);\n\n/*!\n * \\brief Calculates the appropriate buffer size for CMSIS-NN Depthwise Convolutions\n * See:\n * https://github.com/ARM-software/CMSIS_5/blob/325443e52637b6c7eedbd160d238a6c462e89c9f/CMSIS/NN/Source/ConvolutionFunctions/arm_depthwise_conv_wrapper_s8.c#L115-L129\n *\n * \\param is_int16 - type of conv2d\n * \\param target - CMSIS-NN Target\n * \\param input_n - Input batch size\n * \\param input_c - Input channels\n * \\param output_c - Output channels\n * \\param filter_w - Filter width\n * \\param filter_h - Filter height\n * \\param dilation_w - Dilation width\n * \\param dilation_h - Dilation height\n * \\param depth_multiplier - Depth Multiplier for Depthwise Convolution\n *\n * \\return Size of buffer to allocate for depthwise convolution\n */\nint DepthwiseConv2dBufferSize(bool is_int16, Target target, int32_t input_n, int32_t input_c,\n                              int32_t output_c, int32_t filter_w, int32_t filter_h,\n                              int32_t dilation_w, int32_t dilation_h, int32_t depth_multiplier);\n\nint DepthwiseConv2dBufferSizeInt8(Target target, int32_t input_n, int32_t input_c, int32_t output_c,\n                                  int32_t filter_w, int32_t filter_h, int32_t dilation_w,\n                                  int32_t dilation_h, int32_t depth_multiplier);\n\nint DepthwiseConv2dBufferSizeInt16(Target target, int32_t input_n, int32_t input_c,\n                                   int32_t output_c, int32_t filter_w, int32_t filter_h,\n                                   int32_t dilation_w, int32_t dilation_h,\n                                   int32_t depth_multiplier);\n\n/*!\n * \\brief Calculates the appropriate buffer size for CMSIS-NN Average Pooling\n * See:\n * https://github.com/ARM-software/CMSIS_5/blob/bff28575f0c96a4ee9008947fea2b018a69b4900/CMSIS/NN/Source/PoolingFunctions/arm_avgpool_s8.c#L388-L398\n *\n * \\param target - CMSIS-NN Target\n * \\param input_c - Input channels\n *\n * \\return Size of buffer to allocate for average pooling\n */\nint AvgPoolBufferSize(Target target, int32_t input_c);\n\n}  // namespace cmsisnn\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CMSISNN_BUFFER_SIZE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/cmsisnn/compiler_attrs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/cmsisnn/compiler_attrs.h\n * \\brief CMSIS-NN Compiler Attribute functionality\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CMSISNN_COMPILER_ATTRS_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CMSISNN_COMPILER_ATTRS_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace cmsisnn {\n\n/*! \\brief Attributes to store the compiler options for CMSIS-NN. */\nstruct CMSISNNCompilerConfigNode : public tvm::AttrsNode<CMSISNNCompilerConfigNode> {\n  String mcpu;\n  String mattr;\n\n  TVM_DECLARE_ATTRS(CMSISNNCompilerConfigNode, \"ext.attrs.CMSISNNCompilerConfigNode\") {\n    TVM_ATTR_FIELD(mcpu)\n        .describe(\n            \"The CPU to configure CMSIS-NN for (i.e. cortex-m55, cortex-m4), can also include \"\n            \"attributes (i.e. cortex-m55+nomve)\")\n        .set_default(\"\");\n    TVM_ATTR_FIELD(mattr)\n        .describe(\"The attributes to configure CMSIS-NN (i.e. +nodsp, +nomve)\")\n        .set_default(\"\");\n  }\n};\n\nclass CMSISNNCompilerConfig : public Attrs {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(CMSISNNCompilerConfig, Attrs,\n                                            CMSISNNCompilerConfigNode);\n};\n\n/*! \\brief Convert External Code Generator options to TVM Target. */\nTarget CreateTarget(const tvm::transform::PassContext& ctx);\n\n}  // namespace cmsisnn\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CMSISNN_COMPILER_ATTRS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/cmsisnn/convolutions.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/cmsisnn/convolutions.h\n * \\brief CMSIS-NN utility functions for Convolutions\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CMSISNN_CONVOLUTIONS_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CMSISNN_CONVOLUTIONS_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/transform.h>\n#include <tvm/runtime/ndarray.h>\n\n#include \"../../../op/make_op.h\"\n#include \"../../../qnn/utils.h\"\n#include \"../../../transforms/pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace cmsisnn {\n/*!\n * \\brief Checks if Relay Conv2D was originally CMSIS-NN compliant Depthwise Convolution\n * See:\n * https://github.com/apache/tvm/blob/6ed3ab3e33f8eafa4acaf53b7a671831de7587e9/python/tvm/relay/frontend/tflite.py#L2107\n *\n *\n * \\return true if a Conv2D is a Depthwise Convolution based on Conv2D's inputs' shapes and\n * attributes\n */\n\nbool IsCMSISNNDepthwise(const Conv2DAttrs* conv2d_attrs, const Array<PrimExpr>& input_shape,\n                        const Array<PrimExpr>& kernel_shape);\n\n}  // namespace cmsisnn\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CMSISNN_CONVOLUTIONS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/codegen_c/codegen_c.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/codegen_c/codegen_c.h\n * \\brief The base class for external codegen tools.\n */\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CODEGEN_C_CODEGEN_C_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CODEGEN_C_CODEGEN_C_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/relay/op.h>\n\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\n\nstruct Output {\n  std::string name;\n  std::string dtype;\n  int size;\n  bool need_copy;\n};\n\nstruct GenerateBodyOutput {\n  std::string decl;\n  std::vector<std::string> buffers;\n  std::vector<Output> outputs;\n};\n\nclass CSourceModuleCodegenBase {\n public:\n  CSourceModuleCodegenBase() = default;\n  virtual ~CSourceModuleCodegenBase() = default;\n\n  /*!\n   * \\brief Create a runtime module for the external library. For example, it\n   * could be a CSourceModule that can be directly compiled and linked together\n   * with a DSOModule, or a json style module that emitts a json artifact that\n   * is able to be executed by a customized json runtime.\n   *\n   * \\param ref The ext_func Relay expression/module to be executed using extern ops.\n   *\n   * \\return A runtime module.\n   */\n  virtual runtime::Module CreateCSourceModule(const ObjectRef& ref) = 0;\n};\n\n// The base class to generate the declaration functions in C.\nclass CodegenCBase {\n public:\n  virtual ~CodegenCBase() {}\n\n protected:\n  /*! \\brief Print indents using spaces. */\n  void PrintIndents() {\n    for (int i = 0; i < indent_; i++) {\n      code_stream_ << ' ';\n    }\n  }\n\n  /*!\n   * \\brief Enter a new scope.\n   */\n  void EnterScope() { indent_ += 2; }\n\n  /*!\n   * \\brief Exit a scope.\n   */\n  void ExitScope() {\n    ICHECK_GE(indent_, 2U) << \"Wrong ident found.\";\n    indent_ -= 2;\n  }\n\n  /*!\n   * \\brief Creates a runtime function header\n   */\n  void PrintRuntimeFunctionHeader(std::string func_name) {\n    code_stream_ << \"#ifdef __cplusplus\\n\";\n    code_stream_ << \"extern \\\"C\\\" {\\n\";\n    code_stream_ << \"#endif\\n\";\n    code_stream_ << \"TVM_DLL int32_t \";\n    code_stream_ << func_name << \"(\";\n    code_stream_ << \"TVMValue* args, \";\n    code_stream_ << \"int* type_code, \";\n    code_stream_ << \"int num_args, \";\n    code_stream_ << \"TVMValue* out_value, \";\n    code_stream_ << \"int* out_type_code) {\\n\";\n  }\n\n  /*!\n   * \\brief Adds a line to convert TVMValue args to DLTensors\n   */\n  void PrintArgToData(int idx) {\n    PrintIndents();\n    code_stream_ << \"DLTensor* arg\" << idx << \" = \";\n    code_stream_ << \"(DLTensor*)(((TVMValue*)args)[\" << idx << \"].v_handle);\\n\";\n  }\n\n  /*!\n   * \\brief Adds a line to convert TVMValue rets to DLTensors\n   */\n  void PrintRetToData(int idx) {\n    PrintIndents();\n    code_stream_ << \"DLTensor* ret\" << idx << \" = \";\n    code_stream_ << \"(DLTensor*)(((TVMValue*)args)[\" << idx << \"].v_handle);\\n\";\n  }\n\n  /*!\n   * \\brief Gerenate C code for the external function.\n   *\n   * \\param func_name The name of the external function.\n   * \\param args arguments to the external function.\n   *\n   * \\code\n   *\n   * Array<NDArray> foo_consts;\n   *\n   * // An example code for the generated C function.\n   * int foo_wrapper_(DLTensor* arg0,\n   *                              DLTensor* arg1,\n   *                              DLTensor* out) {\n   *   foo_((float*)(arg0->data),\n   *        (float*)(arg1->data),\n   *        (float*)(out->data));\n   *   return 0;\n   * }\n   *\n   * TVM_DLL_EXPORT_TYPED_FUNC(foo, foo_wrapper_);\n   *\n   * int foo_init_wrapper_(Array<NDArray> arr) {\n   *   foo_consts = arr;\n   *   return 0;\n   * }\n   *\n   * TVM_DLL_EXPORT_TYPED_FUNC(__init_foo, foo_init_wrapper_);\n   *\n   * \\endcode\n   */\n  void GenerateBackendCFunc(const std::string& func_name, const Array<Var>& args,\n                            const std::string& const_arr_name, const std::vector<Output>& outs,\n                            bool pass_dl_tensor = false) {\n    // Print signature\n    code_stream_ << \"\\n\";\n\n    code_stream_ << \"int \" << func_name << \"_wrapper_(\";\n    for (size_t i = 0; i < args.size(); i++) {\n      code_stream_ << \"DLTensor* arg\" << i << \",\\n\";\n      code_stream_ << \"\\t\";\n    }\n    for (size_t i = 0; i < outs.size() - 1; i++) {\n      code_stream_ << \"DLTensor* out\" << i << \",\\n\";\n      code_stream_ << \"\\t\";\n    }\n    code_stream_ << \"DLTensor* out\" << outs.size() - 1 << \") {\\n\";\n\n    EnterScope();\n\n    // Generate the internal call.\n    PrintIndents();\n    code_stream_ << func_name << \"_(\";\n    for (size_t i = 0; i < args.size(); i++) {\n      if (pass_dl_tensor) {\n        code_stream_ << \"arg\" << i << \",\\n\";\n      } else {\n        const auto& dtype_str = GetDtypeString(args[i]);\n        code_stream_ << \"(\" << dtype_str << \"*)(arg\" << i << \"->data),\\n\";\n      }\n      PrintIndents();\n    }\n    for (size_t i = 0; i < outs.size() - 1; i++) {\n      if (pass_dl_tensor) {\n        code_stream_ << \"out\" << i << \",\\n\";\n      } else {\n        code_stream_ << \"(\" << outs[i].dtype << \"*)(out\" << i << \"->data),\\n\";\n      }\n      PrintIndents();\n    }\n    if (pass_dl_tensor) {\n      code_stream_ << \"out\" << outs.size() - 1 << \");\\n\";\n    } else {\n      code_stream_ << \"(\" << outs.back().dtype << \"*)(out\" << outs.size() - 1 << \"->data));\\n\";\n    }\n    PrintIndents();\n    code_stream_ << \"return 0;\\n\";\n    ExitScope();\n    code_stream_ << \"}\\n\\n\";\n\n    // Create the external function\n    PrintRuntimeFunctionHeader(func_name);\n    EnterScope();\n    for (size_t i = 0; i < args.size(); i++) {\n      PrintArgToData(i);\n    }\n    for (size_t i = 0; i < outs.size(); i++) {\n      PrintRetToData(args.size() + i);\n    }\n    PrintIndents();\n    code_stream_ << func_name << \"_wrapper_(\";\n    for (size_t i = 0; i < args.size(); i++) {\n      code_stream_ << \"arg\" << i << \",\";\n    }\n    for (size_t i = 0; i < outs.size() - 1; i++) {\n      code_stream_ << \"ret\" << args.size() + i << \",\";\n    }\n    code_stream_ << \"ret\" << args.size() + outs.size() - 1 << \");\\n\";\n    PrintIndents();\n    code_stream_ << \"return 0;\\n\";\n    ExitScope();\n    code_stream_ << \"}\\n\";\n    code_stream_ << \"#ifdef __cplusplus\\n\";\n    code_stream_ << \"}\\n\";\n    code_stream_ << \"#endif\\n\";\n\n    if (!const_arr_name.empty()) {\n      // If there are constants, insert the __init_ and the wrapper\n      // This segment would be generated in C++ because of the usage\n      // of tvm::runtime::Array. This is not ideal, but this to demonstrate\n      // constant copying process used packed imports in other external\n      // codegen. Moreover, in microTVM we dont expect this part to be generated.\n      code_stream_ << \"#ifdef __cplusplus\\n\";\n      code_stream_ << \"int \" << func_name\n                   << \"_init_wrapper_(tvm::runtime::Array<tvm::runtime::NDArray> arr) {\\n\";\n      EnterScope();\n      PrintIndents();\n      code_stream_ << func_name << \"_consts = arr;\\n\";\n      code_stream_ << \"return 0;\\n\";\n      ExitScope();\n      code_stream_ << \"}\\n\\n\";\n      code_stream_ << \"TVM_DLL_EXPORT_TYPED_FUNC(__init_\" << func_name << \", \" << func_name\n                   << \"_init_wrapper_);\\n\\n\";\n      code_stream_ << \"#endif\\n\";\n    }\n  }\n\n  /*!\n   * \\brief Emit the code for external runtime.\n   *\n   * \\param out The outputs.\n   *\n   * \\return The code string.\n   */\n  virtual std::string JIT(const std::vector<Output>& out) = 0;\n\n  /*!\n   * \\brief A common interface that is used by various external runtime to\n   * generate the wrapper to invoke external kernels.\n   *\n   * \\param ext_func_id The unique id of an external function. It will be used\n   * during runtime to pick the correct external function.\n   * \\param args The arguments used by the external function.\n   * \\param buf_decl The declaration of temporary buffers that used to store the\n   * intermeidate of each external kernel.\n   * \\param body The statements of the external function.\n   * \\param out The name and id pairs for output.\n   *\n   * \\return The emitted code string.\n   */\n  std::string JitImpl(const std::string& ext_func_id, const Array<Var>& args,\n                      const std::vector<std::string>& buf_decl,\n                      const std::vector<std::string>& body, const std::string& const_arr_name,\n                      const std::vector<Output>& outs) {\n    // Create a declaration for global ndarrays that contain constant data.\n    if (!const_arr_name.empty()) {\n      code_stream_ << \"#ifdef __cplusplus\\n\";\n      code_stream_ << const_arr_name << \"\\n\\n\";\n      code_stream_ << \"#endif\\n\";\n    }\n    // Create the signature. For example, it could be:\n    // void dnnl_0_(float* in0, float* in1, float* out0, float* out1) {}\n    code_stream_ << \"void \" << ext_func_id << \"_(\";\n\n    for (const auto& arg : args) {\n      const auto& dtype_str = GetDtypeString(arg);\n      code_stream_ << dtype_str << \"* \" << arg->name_hint() << \", \";\n    }\n    for (size_t i = 0; i < outs.size() - 1; ++i) {\n      code_stream_ << outs[i].dtype << \"* out\" << i << \", \";\n    }\n    code_stream_ << outs.back().dtype << \"* out\" << outs.size() - 1 << \") {\\n\";\n    this->EnterScope();\n\n    // Function body\n    for (auto decl : buf_decl) {\n      this->PrintIndents();\n      code_stream_ << decl << \"\\n\";\n    }\n    code_stream_ << \"\\n\";\n    for (auto stmt : body) {\n      this->PrintIndents();\n      code_stream_ << stmt << \"\\n\";\n    }\n\n    // Copy output\n    for (size_t i = 0; i < outs.size(); ++i) {\n      if (!outs[i].need_copy) {\n        continue;\n      }\n      this->PrintIndents();\n      code_stream_ << \"memcpy(out\" << i << \", \" << outs[i].name << \", 4 * \" << outs[i].size\n                   << \");\\n\";\n    }\n\n    // Free buffers\n    for (size_t i = 0; i < buf_decl.size(); i++) {\n      this->PrintIndents();\n      code_stream_ << \"free(buf_\" << i << \");\\n\";\n    }\n\n    this->ExitScope();\n    code_stream_ << \"}\\n\";\n\n    // Create the wrapper to call the ext_func\n    this->GenerateBackendCFunc(ext_func_id, args, const_arr_name, outs);\n    return code_stream_.str();\n  }\n\n  /*!\n   * \\brief Returns dtype string\n   *\n   * \\param var Var to get the dtype of\n   *\n   * \\return The dtype string.\n   */\n  std::string GetDtypeString(const Var& var) {\n    auto ttype = var->checked_type().as<TensorTypeNode>();\n    ICHECK(ttype) << \"Expect TensorTypeNode\";\n    return GetDtypeString(ttype);\n  }\n\n  /*!\n   * \\brief Returns dtype string\n   *\n   * \\param ttype TensorTypeNode* to get the dtype of\n   *\n   * \\return The dtype string.\n   */\n  std::string GetDtypeString(const TensorTypeNode* ttype) {\n    std::string dtype;\n    if (runtime::TypeMatch(ttype->dtype, kDLFloat, 32)) {\n      dtype = \"float\";\n    } else if (runtime::TypeMatch(ttype->dtype, kDLFloat, 16)) {\n      dtype = \"half\";\n    } else if (runtime::TypeMatch(ttype->dtype, kDLBfloat, 16)) {\n      dtype = \"bfloat\";\n    } else if (runtime::TypeMatch(ttype->dtype, kDLInt, 32)) {\n      dtype = \"int\";\n    } else if (runtime::TypeMatch(ttype->dtype, kDLInt, 64)) {\n      dtype = \"int64_t\";\n    } else {\n      LOG(FATAL) << \"Unsupported dtype \" << ttype->dtype;\n    }\n\n    return dtype;\n  }\n\n  /*!\n   * \\brief Creates a checker to check if the NDArray pool is initialized\n   *\n   * \\param symobl The Symbol of the current function\n   *\n   * \\return The created checker\n   */\n  std::string CreateInitChecker(const std::string& symbol) const {\n    std::ostringstream oss;\n    oss << \"ICHECK(!\" << symbol\n        << \"_consts.empty()) << \\\"C source module hasn't been initialized.\\\";\\n\";\n    return oss.str();\n  }\n\n  /*!\n   * \\brief Generates the global ndarray pool declaration\n   *\n   * \\param symobl The Symbol of the current function\n   *\n   * \\return The created declaration\n   */\n  std::string CreateNDArrayPool(const std::string& symbol) const {\n    return \"tvm::runtime::Array<tvm::runtime::NDArray> \" + symbol + \"_consts;\";\n  }\n\n  /*!\n   * \\brief Generates the reference to the data of a constant ndarray\n   *\n   * \\param symobl The Symbol of the current function\n   * \\param symobl const_id The index of the constant\n   *\n   * \\return The created reference\n   */\n  std::string CreateDataReference(const std::string& symbol, size_t const_id) const {\n    return \"(float*)(\" + symbol + \"_consts[\" + std::to_string(const_id) + \"]->data)\";\n  }\n\n  /*!\n   * \\brief Returns the variable name for a constant variable\n   *\n   * \\param symobl The Symbol of the current function\n   * \\param symobl const_id The index of the constant\n   *\n   * \\return The created variable name\n   */\n  std::string CreateConstVar(const std::string& symbol, size_t const_id) const {\n    return symbol + \"_const_\" + std::to_string(const_id);\n  }\n\n  /*! \\brief The external function source code stream. */\n  std::ostringstream code_stream_;\n\n private:\n  /*! \\brief Indent of the source code. */\n  int indent_{0};\n};\n\n/*!\n * \\brief A pass to translate all \"Primitive\" Relay functions with \"Compiler=ccompiler\" to\n * a \\p CSourceModule.\n */\ntransform::Pass CCompilerPass();\n\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CODEGEN_C_CODEGEN_C_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/codegen_json/codegen_json.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/contrib/codegen_json.h\n * \\brief Utilities for json codegen and runtime\n */\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CODEGEN_JSON_CODEGEN_JSON_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CODEGEN_JSON_CODEGEN_JSON_H_\n\n#include <dmlc/any.h>\n#include <dmlc/json.h>\n#include <tvm/node/reflection.h>\n#include <tvm/tir/op.h>\n\n#include <cstdint>\n#include <limits>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../../../../runtime/contrib/json/json_node.h\"\n#include \"../../../../runtime/contrib/json/json_runtime.h\"\n#include \"../../utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace backend {\nnamespace contrib {\n\nusing namespace tvm::runtime::json;\n\nusing ShapeVector = std::vector<std::vector<int64_t>>;\nusing TypeVector = std::vector<std::string>;\nusing JSONGraphObjectPtr = std::shared_ptr<JSONGraphNode>;\n\n/*!\n * \\brief Helper class to extract all attributes of a certain op and save them\n * into text format.\n */\nclass OpAttrExtractor : public AttrVisitor {\n public:\n  explicit OpAttrExtractor(JSONGraphObjectPtr node) : node_(node) {}\n\n  template <typename T = double, typename = std::enable_if_t<std::is_floating_point<T>::value>>\n  std::string Fp2String(const T value) {\n    std::ostringstream out;\n    out.precision(std::numeric_limits<T>::max_digits10);\n    out << value;\n    return out.str();\n  }\n\n  void SetNodeAttr(const char* key, const std::vector<std::string>& value) {\n    std::vector<dmlc::any> attr;\n    attr.emplace_back(value);\n    node_->SetAttr(key, attr);\n  }\n\n  void Visit(const char* key, double* value) final { SetNodeAttr(key, {Fp2String(*value)}); }\n\n  void Visit(const char* key, int64_t* value) final { SetNodeAttr(key, {std::to_string(*value)}); }\n\n  void Visit(const char* key, uint64_t* value) final { SetNodeAttr(key, {std::to_string(*value)}); }\n\n  void Visit(const char* key, int* value) final { SetNodeAttr(key, {std::to_string(*value)}); }\n\n  void Visit(const char* key, bool* value) final { SetNodeAttr(key, {std::to_string(*value)}); }\n\n  void Visit(const char* key, std::string* value) final { SetNodeAttr(key, {*value}); }\n\n  void Visit(const char* key, DataType* value) final {\n    if (!value->is_void()) {\n      SetNodeAttr(key, {runtime::DLDataType2String(*value)});\n    } else {\n      SetNodeAttr(key, {\"\"});\n    }\n  }\n\n  void Visit(const char* key, runtime::ObjectRef* value) final {\n    if (const auto* an = (*value).as<ArrayNode>()) {\n      std::vector<std::string> attr;\n      for (size_t i = 0; i < an->size(); ++i) {\n        if (const auto* im = (*an)[i].as<IntImmNode>()) {\n          attr.push_back(std::to_string(im->value));\n        } else if (const auto* fm = (*an)[i].as<FloatImmNode>()) {\n          attr.push_back(Fp2String(fm->value));\n        } else if (const auto* str = (*an)[i].as<StringObj>()) {\n          String s = GetRef<String>(str);\n          attr.push_back(s);\n        } else {\n          LOG(FATAL) << \"Not supported type: \" << (*an)[i]->GetTypeKey();\n        }\n      }\n      SetNodeAttr(key, attr);\n    } else if (!(*value).defined()) {  // Skip NullValue\n      SetNodeAttr(key, std::vector<std::string>{\"\"});\n    } else if (const auto* im = (*value).as<IntImmNode>()) {\n      SetNodeAttr(key, std::vector<std::string>{std::to_string(im->value)});\n    } else if (const auto* fm = (*value).as<FloatImmNode>()) {\n      SetNodeAttr(key, std::vector<std::string>{Fp2String(fm->value)});\n    } else if (const auto* str = (*value).as<StringObj>()) {\n      String s = GetRef<String>(str);\n      SetNodeAttr(key, std::vector<std::string>{s});\n    } else {\n      LOG(FATAL) << \"Not yet supported type: \" << (*value)->GetTypeKey() << \": \" << *value;\n    }\n  }\n\n  void Visit(const char* key, runtime::NDArray* value) final {\n    LOG(FATAL) << \"NDArray is not allowed in op attribute\";\n  }\n\n  void Visit(const char* key, void** value) final {\n    LOG(FATAL) << \"void pointer is not allowed in op attribute\";\n  }\n\n  void Extract(Object* node) {\n    if (node) {\n      reflection_->VisitAttrs(node, this);\n    }\n  }\n\n private:\n  JSONGraphObjectPtr node_;\n  ReflectionVTable* reflection_ = ReflectionVTable::Global();\n};\n\n/*! \\brief Serialize a Relay expression to JSON. */\nclass JSONSerializer : public MemoizedExprTranslator<std::vector<JSONGraphNodeEntry>> {\n public:\n  /*!\n   * \\brief Constructor\n   *\n   * \\param symbol The symbol that represents the graph being converted.\n   * \\param expr The Relay expression to be converted to the JSON form.\n   */\n  JSONSerializer(std::string symbol, Expr expr)\n      : symbol_(std::move(symbol)), func_(std::move(expr)) {}\n\n  void serialize() {\n    relay::Function func = Downcast<relay::Function>(func_);\n    // First we convert all the parameters into input nodes.\n    for (const auto& param : func->params) {\n      auto node_ptr = std::make_shared<JSONGraphNode>(param->name_hint(), \"input\" /* op_type_ */);\n      memo_[param] = AddNode(node_ptr, param);\n    }\n    heads_ = VisitExpr(func->body);\n  }\n\n  /*!\n   * \\brief Returns the accumulated map from constant names to the NDArray they must be bound to\n   * at runtime. Also referred to a 'params' elsewhere in the code.\n   */\n  const std::unordered_map<std::string, runtime::NDArray>& const_name_to_constant() const {\n    return const_name_to_constant_;\n  }\n\n  /*!\n   * \\brief Return the constant names in order they were encountered during translation.\n   */\n  const Array<String>& const_names() const { return const_names_; }\n\n  /*!\\brief Return the generated json. */\n  std::string GetJSON() {\n    std::ostringstream os;\n    dmlc::JSONWriter writer(&os);\n    Save(&writer);\n    return os.str();\n  }\n\n protected:\n  /*!\n   * \\brief Add a node to graph.\n   *\n   * \\param node A graph node. It is a shared pointer. Some attributes of it\n   *        will be added, i.e. shape and type. These attributes are attached to\n   *        the JSON graph in the end.\n   * \\param expr The relay expression.\n   * \\return A list of graph entry nodes. It the relay expr is a tuple type, we\n   *         will flatten it.\n   */\n  std::vector<JSONGraphNodeEntry> AddNode(JSONGraphObjectPtr node, const Expr& expr) {\n    auto checked_type = expr->checked_type();\n    auto node_id = nodes_.size();\n    nodes_.push_back(node);\n    std::vector<JSONGraphNodeEntry> ret;\n    ShapeVector shape;\n    TypeVector dtype;\n    // Flatten tuple node.\n    if (const auto* tuple_type = checked_type.as<TupleTypeNode>()) {\n      for (size_t i = 0; i < tuple_type->fields.size(); ++i) {\n        const auto* tensor_type = tuple_type->fields[i].as<TensorTypeNode>();\n        ICHECK(tensor_type) << \"Expect TensorType, but received: .\"\n                            << tuple_type->fields[i]->GetTypeKey();\n        ret.push_back(JSONGraphNodeEntry(node_id, i));\n        shape.emplace_back(GetIntShape(tensor_type->shape));\n        dtype.emplace_back(DType2String(tensor_type->dtype));\n      }\n      node->SetNumOutput(tuple_type->fields.size());\n    } else {\n      const auto* tensor_type = checked_type.as<TensorTypeNode>();\n      ICHECK(tensor_type) << \"Expect TensorType, but received: \" << checked_type->GetTypeKey();\n      shape.emplace_back(GetIntShape(tensor_type->shape));\n      dtype.emplace_back(DType2String(tensor_type->dtype));\n      ret.push_back(JSONGraphNodeEntry(node_id, 0));\n    }\n    std::vector<dmlc::any> shape_attrs;\n    shape_attrs.emplace_back(shape);\n    node->SetAttr(\"shape\", shape_attrs);\n\n    std::vector<dmlc::any> type_attrs;\n    type_attrs.emplace_back(dtype);\n    node->SetAttr(\"dtype\", type_attrs);\n    return ret;\n  }\n\n  void SetCallNodeAttribute(JSONGraphObjectPtr node, const CallNode* cn) {\n    if (cn->op.as<OpNode>()) {\n      OpAttrExtractor extractor(node);\n      const Object* call_attr = cn->attrs.get();\n      extractor.Extract(const_cast<Object*>(call_attr));\n    } else if (const auto* fn = cn->op.as<FunctionNode>()) {\n      auto pattern = fn->GetAttr<String>(attr::kPartitionedFromPattern);\n      ICHECK(pattern.defined());\n      std::vector<std::string> values;\n      values.push_back(pattern.value());\n      std::vector<dmlc::any> attr;\n      attr.emplace_back(values);\n      node->SetAttr(\"PartitionedFromPattern\", attr);\n    }\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExprDefault_(const Object* op) {\n    LOG(FATAL) << \"JSON runtime currently doesn't support \" << op->GetTypeKey();\n    return {};\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const VarNode* vn) {\n    ICHECK(memo_.count(GetRef<Expr>(vn)));\n    return memo_[GetRef<Expr>(vn)];\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const ConstantNode* constant_node) {\n    std::string name = symbol_ + \"_const_\" + std::to_string(const_names_.size());\n    VLOG(1) << \"Will require parameter '\" << name\n            << \"' to be supplied by the ConstLoaderModule at runtime\";\n    ICHECK_EQ(const_name_to_constant_.count(name), 0);\n    const_name_to_constant_.emplace(name, constant_node->data);\n    const_names_.push_back(name);\n    auto node = std::make_shared<JSONGraphNode>(name, /*op_type=*/\"const\");\n    return AddNode(node, GetRef<Expr>(constant_node));\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const TupleNode* tn) {\n    std::vector<JSONGraphNodeEntry> fields;\n    for (const auto& field : tn->fields) {\n      auto ref = VisitExpr(field);\n      fields.insert(fields.end(), ref.begin(), ref.end());\n    }\n    return fields;\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const CallNode* cn) {\n    Expr expr = GetRef<Expr>(cn);\n    std::string name;\n    if (const auto* op_node = cn->op.as<OpNode>()) {\n      name = op_node->name;\n    } else if (const auto* fn = cn->op.as<FunctionNode>()) {\n      auto comp = fn->GetAttr<String>(attr::kComposite);\n      ICHECK(comp.defined()) << \"JSON runtime only supports composite functions.\";\n      name = comp.value();\n    } else {\n      LOG(FATAL) << \"JSON runtime does not support calls to \" << cn->op->GetTypeKey();\n    }\n\n    std::vector<JSONGraphNodeEntry> inputs;\n    for (const auto& arg : cn->args) {\n      auto res = VisitExpr(arg);\n      inputs.insert(inputs.end(), res.begin(), res.end());\n    }\n    auto node = std::make_shared<JSONGraphNode>(name,     /* name_ */\n                                                \"kernel\", /* op_type_ */\n                                                inputs, 1 /* num_outputs_ */);\n    SetCallNodeAttribute(node, cn);\n    return AddNode(node, GetRef<Expr>(cn));\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const LetNode* ln) {\n    ICHECK_EQ(memo_.count(ln->var), 0);\n    memo_[ln->var] = VisitExpr(ln->value);\n    return VisitExpr(ln->body);\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const TupleGetItemNode* gtn) {\n    auto vtuple = VisitExpr(gtn->tuple);\n    return {vtuple[gtn->index]};\n  }\n\n  std::vector<JSONGraphNodeEntry> VisitExpr_(const FunctionNode* fn) {\n    ICHECK(fn->GetAttr<String>(attr::kComposite).defined())\n        << \"JSON runtime only supports composite functions\";\n    // FunctionNode should be handled by the caller.\n    return {};\n  }\n\n  /*!\n   * \\brief Save to JSON graph\n   *\n   * \\param writer A json writer\n   */\n  void Save(dmlc::JSONWriter* writer) {\n    std::vector<size_t> arg_nodes;\n    for (size_t i = 0; i < nodes_.size(); ++i) {\n      auto node = nodes_[i];\n      if (node->IsLeaf()) {\n        arg_nodes.push_back(i);\n      }\n    }\n    size_t num_entry = 0;\n    std::vector<size_t> node_row_ptr{0};\n    for (auto node : nodes_) {\n      num_entry += node->GetNumOutput();\n      node_row_ptr.push_back(num_entry);\n    }\n    writer->BeginObject();\n    writer->WriteObjectKeyValue(\"nodes\", nodes_);\n    writer->WriteObjectKeyValue(\"arg_nodes\", arg_nodes);\n    writer->WriteObjectKeyValue(\"heads\", heads_);\n    writer->WriteObjectKeyValue(\"node_row_ptr\", node_row_ptr);\n    writer->EndObject();\n  }\n\n private:\n  /*! \\brief The symbol that represents the json graph. */\n  std::string symbol_;\n  /*! \\brief The function to be serialized. */\n  const Expr func_;\n  /*! \\brief JSON graph nodes. */\n  std::vector<JSONGraphObjectPtr> nodes_;\n  /*! \\brief Output of the JSON graph. */\n  std::vector<JSONGraphNodeEntry> heads_;\n  /*!\n   * \\brief A map from constant names to NDArrays for each Constant encountered during\n   * translation to JSON. The JSON will record only the constant name. The actual NDArray must\n   * be made available at runtime from a ConstLoaderModule.\n   */\n  std::unordered_map<std::string, runtime::NDArray> const_name_to_constant_;\n  /*!\n   * \\brief The domain of the above map, but in order the constants were encountered during\n   * translation.\n   */\n  Array<String> const_names_;\n};\n\n}  // namespace contrib\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CODEGEN_JSON_CODEGEN_JSON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/constant_transforms.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/constant_transforms.h\n * \\brief Transforms applied to constant operations during codegen for BYOC backends.\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CONSTANT_TRANSFORMS_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CONSTANT_TRANSFORMS_H_\n\n#include <tvm/relay/expr.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\n\n/*!\n *\\brief Transpose weights from `source_layout` to `target_layout`\n *\n * \\param data The constant expression to transpose.\n * \\param source_layout The current layout of the constant e.g. \"OHWI\".\n * \\param target_layout The target layout of the constant e.g. \"HWIO\".\n */\nConstant TransposeWeights(const Constant& data, const std::string& source_layout,\n                          const std::string& target_layout);\n\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CONSTANT_TRANSFORMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/cutlass/codegen.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/cutlass/codegen.h\n * \\brief The 'custom' compilation pass for CUTLASS (invoked by the RelayToTIRTargetHook pass).\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_CUTLASS_CODEGEN_H_\n#define TVM_RELAY_BACKEND_CONTRIB_CUTLASS_CODEGEN_H_\n\n#include <tvm/ir/transform.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace cutlass {\n\n/*!\n * \\brief Returns the pass which replaces all calls to \"Primitive\" functions with \"Compiler\"\n * attribute of \"cutlass\" with an call to an extern, and binds a \\p runtime::StaticLibrary\n * to the IRModule's \"external_mods\" attribute containing compiled implementations of\n * those functions using the CUTLASS C++ template library.\n */\ntransform::Pass CompileForCutlass();\n\n}  // namespace cutlass\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_CUTLASS_CODEGEN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/dnnl/comp_op_matcher.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/dnnl/comp_op_matcher.h\n * \\brief Implement matcher based function to parse complex composite nodes.\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_DNNL_COMP_OP_MATCHER_H_\n#define TVM_RELAY_BACKEND_CONTRIB_DNNL_COMP_OP_MATCHER_H_\n\n#include <tvm/relay/function.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../../ir/dataflow_matcher_impl.h\"\n\n/*!\n * \\brief Converter value to dmlc attr acceptable format\n *\n * \\tparam T type of value (auto deduction)\n * \\param val value to convert\n * \\return resulting dmlc object\n */\ntemplate <typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(std::vector<std::string>{std::to_string(val)});\n  return dmlc::any{attr};\n}\n\ntemplate <typename T, std::enable_if_t<std::is_same<T, std::string>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(std::vector<std::string>{val});\n  return dmlc::any{attr};\n}\n\ntemplate <typename T,\n          std::enable_if_t<std::is_same<T, std::vector<std::string>>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(val);\n  return dmlc::any{attr};\n}\n\n/*! \\brief Constructor of const scalar expression with defined type */\ntvm::relay::Expr constant(float val) {\n  auto value = tvm::runtime::NDArray::Empty({}, tvm::DataType::Float(32), {kDLCPU, 0});\n  value.CopyFromBytes(&val, sizeof(val));\n  auto res = tvm::relay::Constant(value);\n  tvm::relay::transform::InferTypeLocal(res);\n  return res;\n}\n\n/*!\n * \\brief Simple helper to accumulate composite function arguments and corresponding attributes\n * with indexes of them.\n */\nclass ArgPacker {\n public:\n  ArgPacker(std::unordered_map<std::string, dmlc::any>* attrs, std::vector<tvm::relay::Expr>* args)\n      : attrs_(attrs), args_(args) {}\n\n  int Put(const tvm::relay::Expr& arg, std::string tag_name = \"\") {\n    if (!arg.defined()) return -1;\n    int idx = args_->size();\n    args_->push_back(arg);\n    if (!tag_name.empty()) {\n      attrs_->operator[](tag_name) = dmlc_attr(idx);\n    }\n    return idx;\n  }\n\n private:\n  std::unordered_map<std::string, dmlc::any>* attrs_;\n  std::vector<tvm::relay::Expr>* args_;\n};\n\nconst tvm::relay::CallNode* ParseQnnConvComp(const tvm::relay::FunctionNode& comp_fn,\n                                             std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                             std::vector<tvm::relay::Expr>* args) {\n  using namespace tvm::relay;\n\n  // Pattern\n  auto src = IsWildcard();\n  auto wgh = IsWildcard();\n  auto sum_src = IsWildcard();\n  auto bias = IsConstant();\n\n  auto o_scl = IsConstant();\n  auto act_scl = IsConstant();\n  auto sum_scl = IsConstant();\n  auto dst_zp = IsConstant();\n\n  DFPattern cnv;\n  DFPattern pat;\n\n  cnv = IsOp(\"qnn.conv2d\")({src, wgh, IsConstant(), IsConstant(), IsConstant(), IsConstant()});\n  pat = IsOp(\"cast\")({cnv});\n  pat = IsOp(\"add\")({pat, bias}) || pat;\n  pat = IsOp(\"multiply\")({pat, o_scl});\n  pat = IsOp(\"clip\")({pat});\n  pat = IsOp(\"multiply\")({pat, act_scl}) || pat;\n  pat = IsOp(\"add\")({pat, sum_scl * IsOp(\"cast\")({sum_src})}) || pat;\n  pat = IsOp(\"add\")({pat, dst_zp}) || pat;\n  pat = IsOp(\"cast\")({pat});\n\n  // Check pattern match\n  auto indexed_body = CreateIndexedGraph(comp_fn.body);\n  DFPatternMatcher matcher(indexed_body.get());\n  auto res = matcher.Match(pat, comp_fn.body);\n  ICHECK(res) << \"Mismatch of DNNL partitioner and codegen logic\";\n\n  // Handle arguments in deterministic order\n  auto map = matcher.GetMemo();\n  auto find = [&map](const DFPattern& pat) -> tvm::relay::Expr {\n    if (map.count(pat)) return map.at(pat)[0];\n    return {};\n  };\n\n  ArgPacker arg_holder(ext_attrs, args);\n  arg_holder.Put(find(src));\n  arg_holder.Put(find(wgh));\n  arg_holder.Put(find(bias), \"bias_idx\");\n  arg_holder.Put(find(sum_src), \"sum_idx\");\n  arg_holder.Put(find(o_scl), \"o_scl_idx\");\n  arg_holder.Put(find(act_scl), \"act_scl_idx\");\n  arg_holder.Put(find(sum_scl), \"sum_scl_idx\");\n  arg_holder.Put(find(dst_zp), \"dst_zp_idx\");\n\n  // Activation. Default clip to simulate relu via uint8 cast\n  std::vector<std::string> clip_attr{\"clip\"};\n  auto act_scl_val = map.count(act_scl) ? find(act_scl) : constant(1.0);\n  clip_attr.push_back(std::to_string(arg_holder.Put(act_scl_val)));      // act_scale\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(0.0))));    // alpha\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(255.0))));  // beta\n  (*ext_attrs)[\"activation\"] = dmlc_attr(clip_attr);\n\n  return map.at(cnv)[0].as<CallNode>();\n}\n\nconst tvm::relay::CallNode* ParseQnnDenseComp(const tvm::relay::FunctionNode& comp_fn,\n                                              std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                              std::vector<tvm::relay::Expr>* args) {\n  using namespace tvm::relay;\n\n  // Pattern\n  auto src = IsWildcard();\n  auto wgh = IsWildcard();\n  auto sum_src = IsWildcard();\n  auto bias = IsConstant();\n\n  auto o_scl = IsConstant();\n  auto act_scl = IsConstant();\n  auto sum_scl = IsConstant();\n  auto dst_zp = IsConstant();\n\n  DFPattern dns, act, pat;\n\n  dns = IsOp(\"qnn.dense\")({src, wgh, IsConstant(), IsConstant(), IsConstant(), IsConstant()});\n  pat = IsOp(\"cast\")({dns});\n  pat = IsOp(\"add\")({pat, bias}) || pat;\n  pat = IsOp(\"multiply\")({pat, o_scl});\n  pat = IsOp(\"clip\")({pat});\n  pat = IsOp(\"multiply\")({pat, act_scl}) || pat;\n  pat = IsOp(\"add\")({pat, sum_scl * IsOp(\"cast\")({sum_src})}) || pat;\n  pat = IsOp(\"add\")({pat, dst_zp}) || pat;\n  pat = IsOp(\"cast\")({pat});\n\n  // Check pattern match\n  auto indexed_body = CreateIndexedGraph(comp_fn.body);\n  DFPatternMatcher matcher(indexed_body.get());\n  auto res = matcher.Match(pat, comp_fn.body);\n  ICHECK(res) << \"Mismatch of DNNL partitioner and codegen logic\";\n\n  // Handle arguments in deterministic order\n  auto memo = matcher.GetMemo();\n  auto find = [&memo](const DFPattern& pat) -> tvm::relay::Expr {\n    if (memo.count(pat)) return memo.at(pat)[0];\n    return {};\n  };\n\n  ArgPacker arg_holder(ext_attrs, args);\n  arg_holder.Put(find(src));\n  arg_holder.Put(find(wgh));\n  arg_holder.Put(find(bias), \"bias_idx\");\n  arg_holder.Put(find(sum_src), \"sum_idx\");\n  arg_holder.Put(find(o_scl), \"o_scl_idx\");\n  arg_holder.Put(find(act_scl), \"act_scl_idx\");\n  arg_holder.Put(find(sum_scl), \"sum_scl_idx\");\n  arg_holder.Put(find(dst_zp), \"dst_zp_idx\");\n\n  // Activation. Default clip to simulate relu via uint8 cast\n  std::vector<std::string> clip_attr{\"clip\"};\n  auto act_scl_val = memo.count(act_scl) ? find(act_scl) : constant(1.0);\n  clip_attr.push_back(std::to_string(arg_holder.Put(act_scl_val)));      // act_scale\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(0.0))));    // alpha\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(255.0))));  // beta\n  (*ext_attrs)[\"activation\"] = dmlc_attr(clip_attr);\n\n  return memo.at(dns)[0].as<CallNode>();\n}\n\n/*!\n * Parse composite function and return real args, additional attributes and root call node\n * @param comp_fn composite function to parse\n * @param ext_attrs attr collection with additional attributes\n * @param args real arguments of node\n * @return root call node\n */\nconst tvm::relay::CallNode* ParseComposite(const tvm::relay::FunctionNode& comp_fn,\n                                           std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                           std::vector<tvm::relay::Expr>* args) {\n  auto comp = comp_fn.GetAttr<tvm::String>(tvm::relay::attr::kComposite);\n  ICHECK(comp.defined()) << \"DNNL JSON runtime only supports composite functions.\";\n  auto name = comp.value();\n\n  const tvm::relay::CallNode* res = nullptr;\n  if (name == \"dnnl.qnn.conv2d\")\n    res = ParseQnnConvComp(comp_fn, ext_attrs, args);\n  else if (name == \"dnnl.qnn.dense\")\n    res = ParseQnnDenseComp(comp_fn, ext_attrs, args);\n  return res;\n}\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_DNNL_COMP_OP_MATCHER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/ethosn/codegen_ethosn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/ethosn/codegen_ethosn.h\n * \\brief The Relay -> Arm(R) Ethos(TM)-N command stream compiler.\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_ETHOSN_CODEGEN_ETHOSN_H_\n#define TVM_RELAY_BACKEND_CONTRIB_ETHOSN_CODEGEN_ETHOSN_H_\n\n#include <dmlc/memory_io.h>\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/transform.h>\n#include <tvm/relay/type.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/registry.h>\n\n#include <algorithm>\n#include <fstream>\n#include <map>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../../../../runtime/contrib/ethosn/ethosn_runtime.h\"\n#include \"../codegen_c/codegen_c.h\"\n#include \"ethosn_api.h\"\n#include \"ethosn_support_library/Support.hpp\"\n#include \"ethosn_support_library/SupportQueries.hpp\"\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace ethosn {\n\nnamespace sl = ::ethosn::support_library;\n\n/*!\n * \\brief A struct to hold an uncompiled support library network alongside\n * the desired order of input and output operation ids.\n */\nstruct NetworkWithIDs {\n  struct hash_pair {\n    template <class T_0, class T_1>\n    size_t operator()(const std::pair<T_0, T_1>& p) const {\n      return std::hash<T_0>{}(p.first) ^ std::hash<T_1>{}(p.second);\n    }\n  };\n  std::shared_ptr<sl::Network> network;\n  std::unordered_map<uint32_t, unsigned int> input_ids;\n  std::unordered_map<std::pair<uint32_t, uint32_t>, unsigned int, hash_pair> output_ids;\n};\n\n/*!\n * \\brief A base class for error handling using ErrorReporter.\n */\nclass ErrorReportingPass {\n public:\n  ErrorReportingPass(const IRModule& mod, const GlobalVar& var) : mod_(mod), var_(var) {}\n\n  /*!\n   * \\brief Report fatal errors for an expression.\n   * \\param expr The expression to report errors at.\n   * \\param err The errors to report.\n   */\n  void ReportFatalError(const ObjectRef& expr, const EthosnError& err) {\n    for (const auto& msg : err.msgs) {\n      error_reporter_.ReportAt(this->var_, expr, ErrorBuilder() << msg);\n    }\n    error_reporter_.RenderErrors(this->mod_);\n  }\n\n protected:\n  /*! \\brief An ErrorReporter object to render the errors.*/\n  ErrorReporter error_reporter_;\n  /*! \\brief The module to report errors for. */\n  IRModule mod_;\n  /*! \\brief The GlobalVar to report errors for. */\n  GlobalVar var_;\n};\n\n/*!\n * \\brief A custom pass to infer the support library tensor information\n * for a Relay expression.\n *\n * Support Library requires that tensors are explicitly declared with\n * information on their size, data type, format (eg. NHWC) and quantisation\n * parameters. In Relay, size and data type are already determined when the\n * type_infer pass is run. However, format and quantisation parameters are\n * properties of the operators that consume the tensors.\n *\n * This pass works by having each node initialise the information of its\n * parents, essentially propagating the inferred information all the way up\n * to the inputs of the expression.\n *\n * Because the children initialise the information of the parents, it is\n * necessary to traverse the graph in such a way so as to ensure all the\n * children of a node are visited before the parent is. As Relay does not\n * keep a reference to child nodes, this pass goes in preorder but will\n * skip visiting a parent if all the children haven't yet been visited (see\n * VisitInferred for the logic that implements this).\n *\n * Inference only works for supported callnodes, for tuplenodes, tuplegetitem\n * nodes and free var nodes. Other nodes should not be off-loaded to Ethos-N.\n */\nclass InferTensorsVisitor : private ErrorReportingPass, private ExprVisitor {\n public:\n  InferTensorsVisitor(const IRModule& mod, const GlobalVar& var) : ErrorReportingPass(mod, var) {}\n\n  /*!\n   * \\brief Infer the support library tensor information for all the nodes\n   * in an expression.\n   * \\param expr The expression for which to infer tensor information.\n   * \\return A map of expressions to tensor information.\n   * \\note This algorithm does not traverse into functions, so call it on\n   * the body of the function you're interested in.\n   */\n  std::map<Expr, std::vector<sl::TensorInfo>> Infer(const Expr& expr);\n\n private:\n  // Infer a callnode if it's a supported operator/composite function\n  void InferCall(const CallNode* cn);\n  void VisitInferred(const Expr& expr);\n\n  void VisitExpr_(const CallNode* cn) final;\n  void VisitExpr_(const TupleNode* tn) final;\n  void VisitExpr_(const TupleGetItemNode* tg) final;\n  // Don't traverse into functions, the Ethos-N codegen isn't meant to support them.\n  void VisitExpr_(const FunctionNode* fn) final {}\n\n  /*! \\brief A look-up table from Expr to tensor infos. */\n  std::map<Expr, std::vector<sl::TensorInfo>> tensor_table_;\n};\n\nstd::map<Expr, std::vector<sl::TensorInfo>> InferTensors(const IRModule& mod, const GlobalVar& var,\n                                                         const Expr& expr) {\n  return InferTensorsVisitor(mod, var).Infer(expr);\n}\n\n/*!\n * \\brief A pass to generate a support library network from a Relay function.\n *\n * This pass constructs an equivalent support library network from a Relay\n * function in two visits. One to infer the tensor information of all the nodes\n * and another in postorder to add the nodes as support library operands.\n * (Supported) Callnodes, tuplenodes, tuplegetitemnodes and (free)\n * varnodes are handled by this pass.\n *\n * As part of the pass, nodes in the function body are associated with both\n * type information in the 'tensor_table', and support library operands in the\n * 'operand_table'. Both of these are maps of vectors as a Relay node can have\n * tuple type and accordingly be associated with multiple tensors. For nodes\n * which are not tuple type, vectors of size 1 are used.\n */\nclass ConstructNetworkVisitor : public MixedModeVisitor, private ErrorReportingPass {\n public:\n  explicit ConstructNetworkVisitor(const IRModule& mod, const GlobalVar& var)\n      : ErrorReportingPass(mod, var) {}\n\n  /*!\n   * \\brief Construct a support library network from a given Relay function. The\n   * function should contain only nodes supported by Ethos-N.\n   * \\param func The Relay function for which to construct a support library network.\n   * \\return A support library network that performs the same operation as the Relay\n   * function.\n   */\n  NetworkWithIDs Construct(const Function& func);\n\n private:\n  // Translate from a callnode to the appropriate 'Make' method\n  sl::TensorsAndId HandleCall(const CallNode*);\n\n  void VisitExpr_(const CallNode* cn) final;\n  void VisitExpr_(const TupleNode* op) final;\n  void VisitExpr_(const TupleGetItemNode* tg) final;\n  void VisitLeaf(const Expr& expr) final;\n\n  // Make a support library operand from a Call\n  EthosnError MakeConvolutionLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeFullyConnectedLayer(const Call&, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeMaxPool2DLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeAvgPool2DLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeReshapeLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeAdditionLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeSigmoidLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeMeanLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeTanhLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeConv2DTransposeLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeConcatenateLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeSplitLayer(const Call& call, sl::TensorsAndId* outs);\n  EthosnError MakeDepthToSpaceLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeReluLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeLeakyReLULayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeRequantizeLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeReinterpretQuantizeLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n  EthosnError MakeResizeLayer(const Call& call, sl::TensorAndId<sl::Operand>* out);\n\n  /*! \\brief A look-up table from Expr to layers. */\n  std::map<Expr, std::vector<std::shared_ptr<sl::Operand>>> operand_table_;\n  /*! \\brief A look-up table from Expr to SL operation IDs. */\n  std::map<Expr, std::vector<std::pair<uint32_t, uint32_t>>> id_table_;\n  /*! \\brief A look-up table from Expr to tensor infos. */\n  std::map<Expr, std::vector<sl::TensorInfo>> tensor_table_;\n  /*! \\brief The support library network to compile. */\n  std::shared_ptr<sl::Network> network_;\n};\n\nNetworkWithIDs ConstructNetwork(const IRModule& mod, const GlobalVar& var, const Function& func) {\n  return ConstructNetworkVisitor(mod, var).Construct(func);\n}\n\n/*! \\brief Attributes to store the compiler options for Ethos-N */\nstruct EthosnCompilerConfigNode : public tvm::AttrsNode<EthosnCompilerConfigNode> {\n  String variant;\n  String sram_size;\n  String tops;\n  String ple_ratio;\n  bool strategy0;\n  bool strategy1;\n  bool strategy3;\n  bool strategy4;\n  bool strategy6;\n  bool strategy7;\n  bool dump_ram;\n  bool initial_sram_dump;\n  bool block_config_16x16;\n  bool block_config_32x8;\n  bool block_config_8x32;\n  bool block_config_8x8;\n  bool enable_intermediate_compression;\n  bool disable_winograd;\n  String debug_dir;\n  bool inline_non_compute_intensive_partitions;\n\n  TVM_DECLARE_ATTRS(EthosnCompilerConfigNode, \"ext.attrs.EthosnCompilerConfigNode\") {\n    TVM_ATTR_FIELD(variant).describe(\"See Ethos-N documentation.\").set_default(\"n78\");\n    TVM_ATTR_FIELD(sram_size)\n        .describe(\"Optionally override the default sram size. See Ethos(TM)-N documentation.\")\n        .set_default(\"0\");\n    TVM_ATTR_FIELD(tops)\n        .describe(\"Valid values 1, 2, 4 and 8. See Ethos(TM)-N documentation.\")\n        .set_default(\"1\");\n    TVM_ATTR_FIELD(ple_ratio)\n        .describe(\"Valid values 2 and 4. See Ethos(TM)-N documentation.\")\n        .set_default(\"2\");\n    TVM_ATTR_FIELD(strategy0).set_default(true);\n    TVM_ATTR_FIELD(strategy1).set_default(true);\n    TVM_ATTR_FIELD(strategy3).set_default(true);\n    TVM_ATTR_FIELD(strategy4).set_default(true);\n    TVM_ATTR_FIELD(strategy6).set_default(true);\n    TVM_ATTR_FIELD(strategy7).set_default(true);\n    TVM_ATTR_FIELD(dump_ram).set_default(false);\n    TVM_ATTR_FIELD(initial_sram_dump).set_default(false);\n    TVM_ATTR_FIELD(block_config_16x16).set_default(true);\n    TVM_ATTR_FIELD(block_config_32x8).set_default(true);\n    TVM_ATTR_FIELD(block_config_8x32).set_default(true);\n    TVM_ATTR_FIELD(block_config_8x8).set_default(true);\n    TVM_ATTR_FIELD(enable_intermediate_compression).set_default(true);\n    TVM_ATTR_FIELD(disable_winograd).set_default(false);\n    TVM_ATTR_FIELD(debug_dir).set_default(\".\");\n    TVM_ATTR_FIELD(inline_non_compute_intensive_partitions)\n        .describe(\n            \"A heuristic to improve performance. Inlines functions partitioned for Arm(R) \"\n            \"Ethos(TM)-N that are deemed 'non-compute-intensive'. The inlined functions will \"\n            \"continue through TVM's standard compilation flow.\")\n        .set_default(true);\n  }\n};\n\nclass EthosnCompilerConfig : public Attrs {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(EthosnCompilerConfig, Attrs, EthosnCompilerConfigNode);\n};\n\nTVM_REGISTER_NODE_TYPE(EthosnCompilerConfigNode);\nTVM_REGISTER_PASS_CONFIG_OPTION(\"relay.ext.ethos-n.options\", EthosnCompilerConfig);\n\nEthosnCompilerConfig GetCompilerAttrs() {\n  auto ctx = transform::PassContext::Current();\n  Optional<EthosnCompilerConfig> cfg =\n      ctx->GetConfig<EthosnCompilerConfig>(\"relay.ext.ethos-n.options\");\n  if (!cfg.defined()) {\n    return AttrsWithDefaultValues<EthosnCompilerConfig>();\n  }\n  return cfg.value();\n}\nTVM_REGISTER_GLOBAL(\"relay.ext.ethos-n.get_compiler_attrs\").set_body_typed(GetCompilerAttrs);\n\n/*! \\brief The compiler for Ethos-N functions */\nclass EthosnCompiler {\n public:\n  /*!\n   * \\brief Create an Ethos-N runtime module from a Relay Ethos-N function\n   * \\param ref An ObjectRef pointing to a Relay Ethos-N function\n   * \\return runtime_module An Ethos-N runtime module\n   */\n  static runtime::Module CreateRuntimeModule(const ObjectRef& ref);\n\n  /*!\n   * \\brief Initialise the is-supported functionality of the Ethos-N support library\n   * with the target variant.\n   * \\return Error object\n   */\n  static EthosnError SupportedSetup();\n\n  /*!\n   * \\brief Return the is-supported API of the Support Library\n   * \\return A reference to the API.\n   */\n  static std::unique_ptr<sl::SupportQueries>& GetSupported() {\n    ICHECK(m_Queries != nullptr);\n    return m_Queries;\n  }\n\n private:\n  /*!\n   * \\brief Compile a single Relay Ethos-N function into an ordered compiled network.\n   * Compilation options will be taken from the PassContext.\n   * \\param mod The module the function is stored in (for error reporting purposes)\n   * \\param gvar The global var corresponding to the function\n   * \\param func The function to be compiled\n   * \\return ordered_compiled_network A compiled network with additional information\n   * to handle difference in input/output ordering between the TVM runtime and the\n   * Ethos-N compiled network.\n   */\n  static runtime::ethosn::OrderedCompiledNetwork CompileEthosnFunc(const IRModule& mod,\n                                                                   const GlobalVar& gvar,\n                                                                   const Function& func);\n\n  /*!\n   * \\brief Get the Support Library compilation options from the PassContext\n   * \\return options The compilation options\n   */\n  static sl::CompilationOptions CreateOptions();\n\n  /*!\n   * \\brief Determine the order in which inputs should be provided/outputs should be\n   * read from a compiled network. This is required because when you compile a network\n   * for Ethos-N, you don't have control over the order in which the inputs/outputs\n   * are given. You can, however, query what order the compiler decided to give them in.\n   * We therefore keep track of our desired order and the actual order and create a\n   * small translation table between the two for use in the runtime.\n   * \\param network A network additionally with the desired input/output order\n   * \\param compiled_network The compiled network with an as yet undetermined input/output order\n   * \\return input_output_order The order in which to permute the inputs/outputs given\n   * by the TVM runtime such that they map correctly to the compiled network.\n   */\n  static std::pair<std::vector<uint32_t>, std::vector<uint32_t>> GetInputOutputOrder(\n      NetworkWithIDs network, const std::unique_ptr<sl::CompiledNetwork>& compiled_network);\n\n  /*!\n   * \\brief Determine the input and output sizes of a compiled network.\n   *\n   * These need to be queried from the compiled network as the compiler can choose\n   * to add additional padding on the input/output in certain cases.\n   *\n   * \\param compiled_network The network compiled by the NPU compiler.\n   * \\return Pair of vectors of buffer sizes for both the inputs and outputs of the\n   * network.\n   */\n  static std::pair<std::vector<uint32_t>, std::vector<uint32_t>> GetIOSizes(\n      const std::unique_ptr<sl::CompiledNetwork>& compiled_network);\n\n  /*!\n   * \\brief Query interface used to determine if the Ethos-N hardware supports an operation\n   * with the supplied parameters.\n   */\n  static std::unique_ptr<sl::SupportQueries> m_Queries;\n};\n\nruntime::Module CompileEthosn(const ObjectRef& ref) {\n  return EthosnCompiler::CreateRuntimeModule(ref);\n}\n\nTVM_REGISTER_GLOBAL(\"relay.ext.ethos-n\").set_body_typed(CompileEthosn);\n\nTVM_REGISTER_GLOBAL(\"relay.ext.ethos-n.constant_updater\")\n    .set_body_typed([](Expr expr, std::string symbol) { return Map<String, runtime::NDArray>(); });\n\n}  // namespace ethosn\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_ETHOSN_CODEGEN_ETHOSN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/ethosn/ethosn_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file src/relay/backend/contrib/ethosn/ethosn_api.h\n * \\brief The Relay -> Arm(R) Ethos(TM)-N command stream compiler.\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_ETHOSN_ETHOSN_API_H_\n#define TVM_RELAY_BACKEND_CONTRIB_ETHOSN_ETHOSN_API_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/transform.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/op.h>\n\n#include <algorithm>\n#include <limits>\n#include <map>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"ethosn_support_library/Support.hpp\"\n#include \"ethosn_support_library/SupportQueries.hpp\"\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace ethosn {\n\nnamespace sl = ::ethosn::support_library;\n\nstruct ConvolutionParams {\n  sl::ConvolutionInfo conv_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo weights_info;\n  sl::TensorInfo bias_info;\n  sl::TensorInfo output_info;\n  void* raw_weights = nullptr;\n  void* raw_bias = nullptr;\n  bool is_depthwise = false;\n};\n\nstruct FullyConnectedParams {\n  sl::FullyConnectedInfo fc_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo weights_info;\n  sl::TensorInfo bias_info;\n  sl::TensorInfo output_info;\n  runtime::NDArray raw_weights;\n  runtime::NDArray raw_bias;\n};\n\nstruct MaxPool2DParams {\n  sl::PoolingInfo pool_info = sl::PoolingInfo(0, 0, 0, 0, sl::Padding(), sl::PoolingType::MAX);\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct AvgPool2DParams {\n  sl::PoolingInfo pool_info = sl::PoolingInfo(0, 0, 0, 0, sl::Padding(), sl::PoolingType::AVG);\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct ReshapeParams {\n  sl::TensorShape new_shape{};\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct AdditionParams {\n  sl::QuantizationInfo output_quantization_info;\n  sl::TensorInfo lhs_info;\n  sl::TensorInfo rhs_info;\n  sl::TensorInfo output_info;\n};\n\nstruct SigmoidParams {\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct MeanParams {\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct TanhParams {\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct LeakyReLUParams {\n  sl::LeakyReluInfo leaky_relu_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct QnnConv2dTransposeParams {\n  sl::ConvolutionInfo conv_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo weights_info;\n  sl::TensorInfo bias_info;\n  sl::TensorInfo output_info;\n  runtime::NDArray raw_weights;\n  runtime::NDArray raw_bias;\n};\n\nstruct ConcatenateParams {\n  sl::QuantizationInfo qInfo;\n  sl::ConcatenationInfo concat_info = sl::ConcatenationInfo(1, qInfo);\n  std::vector<sl::TensorInfo> input_infos;\n  sl::TensorInfo output_info;\n};\n\nstruct SplitParams {\n  sl::SplitInfo split_info = sl::SplitInfo(0, {});\n  sl::TensorInfo input_info;\n  std::vector<sl::TensorInfo> output_infos;\n};\n\nstruct DepthToSpaceParams {\n  sl::DepthToSpaceInfo depth_info = sl::DepthToSpaceInfo(0);\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct ReluParams {\n  sl::ReluInfo relu_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct RequantizeParams {\n  sl::RequantizeInfo requantize_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct ReinterpretQuantizationParams {\n  sl::ReinterpretQuantizationInfo reinterpret_quantize_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\nstruct ResizeParams {\n  sl::ResizeInfo resize_info;\n  sl::TensorInfo input_info;\n  sl::TensorInfo output_info;\n};\n\n/*!\n * \\brief A wrapper around std::stringstream to build an EthosnError.\n */\nclass ErrStrm {\n public:\n  template <typename T>\n  ErrStrm& operator<<(const T& val) {  // NOLINT(*)\n    stream_ << val;\n    return *this;\n  }\n\n private:\n  std::stringstream stream_;\n  friend class EthosnError;\n};\n\n/*!\n * \\brief Custom error class for storing error messages produced\n * during compilation for Ethos-N.\n */\nclass EthosnError {\n public:\n  /*! \\brief Default constructor */\n  EthosnError() {}\n  /*!\n   * \\brief Construct error from an Array of Strings\n   * \\param msgs The messages\n   */\n  explicit EthosnError(const Array<String>& msgs) : msgs(msgs) {}\n  /*!\n   * \\brief Construct error from a String\n   * \\param msg The message\n   */\n  explicit EthosnError(const String& msg) {\n    if (msg.size()) msgs.push_back(msg);\n  }\n  /*!\n   * \\brief Construct error from an ErrStrm\n   * \\param err The ErrStrm\n   */\n  explicit EthosnError(const ErrStrm& err) : EthosnError(err.stream_.str()) {}\n\n  /*! \\return Whether there are any error messages */\n  explicit operator bool() const { return !msgs.empty(); }\n\n  /*! \\brief Add together two errors to give a single error with all the msgs */\n  EthosnError& operator+=(const EthosnError& other) {\n    msgs.insert(msgs.end(), other.msgs.begin(), other.msgs.end());\n    return *this;\n  }\n\n  /*! \\brief The error messages */\n  Array<String> msgs;\n};\n\n/*!\n * \\brief Functions to interact with Support Library's API including the\n * translation of Relay ops/composite functions into Support Library\n * equivalents.\n */\nclass EthosnAPI {\n public:\n  /*! \\brief Create a default input tensor */\n  static sl::TensorInfo DefaultInputTensor(const Expr& expr);\n\n  /*! \\brief Extract the Support Library convolution params from an ethos-n.qnn_conv2d func */\n  static EthosnError QnnConv2d(const Expr& expr, ConvolutionParams* params);\n  /*! \\brief Extract the Support Library dense params from an ethos-n.qnn_fc func */\n  static EthosnError QnnFullyConnected(const Expr& expr, FullyConnectedParams* params);\n  /*! \\brief Extract the Support Library max_pool2d params from a Relay max_pool2d call */\n  static EthosnError MaxPool2D(const Expr& expr, MaxPool2DParams* params);\n  /*! \\brief Extract the Support Library avg_pool params from a Relay ethos-n.qnn_avg_pool2d func */\n  static EthosnError AvgPool2D(const Expr& expr, AvgPool2DParams* params);\n  /*! \\brief Extract the Support Library reshape params from a Relay reshape call */\n  static EthosnError Reshape(const Expr& expr, ReshapeParams* params);\n  /*! \\brief Extract the Support Library addition params from a Relay qnn.addition call */\n  static EthosnError Addition(const Expr& expr, AdditionParams* params);\n  /*! \\brief Extract the Support Library sigmoid params from a Relay an ethos-n.qnn_sigmoid func */\n  static EthosnError Sigmoid(const Expr& expr, SigmoidParams* params);\n  /*! \\brief Extract the Support Library mean params from a mean func */\n  static EthosnError Mean(const Expr& expr, MeanParams* params);\n  /*! \\brief Extract the Support Library tanh params from a Relay an ethos-n tanh func */\n  static EthosnError Tanh(const Expr& expr, TanhParams* params);\n  /*! \\brief Extract the Support Library leaky relu params from an ethos-n leaky relu Relu call. */\n  static EthosnError LeakyReLU(const Expr& expr, LeakyReLUParams* params);\n  /*! \\brief Extract the Support Library transpose params from a Relay\n   * ethos-n.qnn_conv2d_transpose func */\n  static EthosnError QnnConv2dTranspose(const Expr& expr, QnnConv2dTransposeParams* params);\n  /*! \\brief Extract the Support Library concatenate params from a Relay qnn.concatenate call */\n  static EthosnError Concatenate(const Expr& expr, ConcatenateParams* params);\n  /*! \\brief Extract the Support Library split params from a Relay split call */\n  static EthosnError Split(const Expr& expr, SplitParams* params);\n  /*! \\brief Extract the Support Library depth_to_space params from a Relay depth_to_space call */\n  static EthosnError DepthToSpace(const Expr& expr, DepthToSpaceParams* params);\n  /*! \\brief Extract the Support Library relu params from a Relay relu call */\n  static EthosnError Relu(const Expr& expr, ReluParams* params);\n  /*! \\brief Extract the Support Library requantize params from a Relay qnn.requantize call */\n  static EthosnError Requantize(const Expr& expr, RequantizeParams* params);\n\n  /*!\n   * \\brief Extact the Support Library reinterpret quantization params from a Relay qnn.requantize\n   * call.\n   *\n   * \\note This is used for the conversion from add and mul to a reinterpret quantization operator.\n   * This is effectively an identity operation, as not the same as 'requantize'.\n   */\n  static EthosnError ReinterpretQuantize(const Expr& expr, ReinterpretQuantizationParams* params);\n\n  /*! \\brief Extract the Support Library resize params from a Relay resize call */\n  static EthosnError Resize(const Expr& expr, ResizeParams* params);\n\n private:\n  /*! \\brief Convert a TVM IndexExpr array to a SL tensor shape */\n  static EthosnError Tvm2Npu(const Array<IndexExpr>& shape, sl::TensorShape* npu_shape);\n  /*! \\brief Convert a TVM data type to a SL data type */\n  static EthosnError Tvm2Npu(const tvm::DataType& dtype, sl::DataType* data_type);\n  /*! \\brief Convert TVM 1D padding to SL padding */\n  static EthosnError Tvm2Npu(const Array<IndexExpr>& padding, sl::Padding* npu_padding);\n  /*! \\brief Convert TVM 1D striding to SL striding */\n  static EthosnError Tvm2Npu(const Array<IndexExpr>& strides, sl::Stride* npu_stride);\n  /*! \\brief Convert TVM data format to SL data format */\n  static EthosnError Tvm2Npu(const std::string& dformat, sl::DataFormat* data_format);\n  /*! \\brief Convert TVM size array for pooling size to x and y values */\n  static EthosnError Tvm2Npu(const Array<IndexExpr>& size, uint32_t* x, uint32_t* y);\n  /*! \\brief Convert TVM quantization info to SL quantization info */\n  static EthosnError Tvm2Npu(const int32_t zero_point, const float scale,\n                             sl::QuantizationInfo* npu_qinfo);\n  static EthosnError Tvm2Npu(const int32_t zero_point, const std::valarray<float> scales,\n                             const unsigned int axis, sl::QuantizationInfo* npu_qinfo);\n  /*! \\brief Convert TVM 2D padding to SL padding */\n  static EthosnError Tvm2Npu(const Array<Array<Integer>>& padding, sl::Padding* npu_padding);\n  /*! \\brief Convert a TVM Integer array to a SL tensor shape */\n  static EthosnError Tvm2Npu(const Array<Integer>& shape, sl::TensorShape* npu_shape);\n  /*! \\brief Convert a TVM Type to SL tensor info. */\n  static EthosnError Tvm2Npu(const tvm::Type& type, sl::TensorInfo* npu_tinfo);\n\n  /*! \\brief Convert a TVM pooling call to SL pooling information */\n  static EthosnError Pool2d(const Call& input, const Call& output, Array<IndexExpr> size,\n                            Array<IndexExpr> strides, Array<IndexExpr> padding,\n                            sl::PoolingType pooling_type, sl::PoolingInfo* pool_info,\n                            sl::TensorInfo* input_info, sl::TensorInfo* output_info,\n                            std::string layout);\n\n  // Convert an array of IntImmNodes into ValueT\n  // IndexT type of Array indexing variable\n  // ValueT type of resulting value\n  template <typename IndexT, typename ValueT, size_t N>\n  static EthosnError AsArray(const Array<IndexT>& arr, std::array<ValueT, N>* v);\n\n  // Get a T from a constant represented by a NDArray.\n  template <typename T>\n  static EthosnError AsConstant(const Expr& expr, T* out);\n  static EthosnError AsConstant(const Expr& expr, std::valarray<float>* out);\n};\n\n}  // namespace ethosn\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_ETHOSN_ETHOSN_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/ethosu/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/contrib/ethosu/utils.h\n * \\brief Utilities for microNPU codegen\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_ETHOSU_UTILS_H_\n#define TVM_RELAY_BACKEND_CONTRIB_ETHOSU_UTILS_H_\n\n#include <tvm/ir/expr.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/stmt.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace ethosu {\n\n/*!\n * \\brief Base addresses are input pointers to\n * the driver that get accessed by the command stream\n * using offsets to read/write data.\n */\nstruct BaseAddressNode : public Object {\n  /*! \\brief The identifier, usually it the param name of the PrimFunc that gets lowered */\n  String name;\n  /*! \\brief The index in the params array of the PrimFunc. This is needed to keep aligned\n   * between the PrimFunc arguments ordering and argument ordering of generated code */\n  Integer primfunc_param_idx;\n  /*! \\brief The region used by the command stream. This needs to match with base address\n   * index passed into the driver */\n  Integer region;\n  /*! \\brief The size of the buffer accessible by this base address */\n  Integer size;\n  /*! \\brief This is a runtime allocation that needs to be done in the function */\n  Bool is_runtime_allocation{Bool(false)};\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"name\", &name);\n    v->Visit(\"primfunc_param_idx\", &primfunc_param_idx);\n    v->Visit(\"region\", &region);\n    v->Visit(\"size\", &size);\n    v->Visit(\"is_runtime_allocation\", &is_runtime_allocation);\n  }\n\n  bool SEqualReduce(const BaseAddressNode* other, SEqualReducer equal) const {\n    return equal(name, other->name) && equal(primfunc_param_idx, other->primfunc_param_idx) &&\n           equal(region, other->region) && equal(size, other->size) &&\n           equal(is_runtime_allocation, other->is_runtime_allocation);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(name);\n    hash_reduce(primfunc_param_idx);\n    hash_reduce(region);\n    hash_reduce(size);\n    hash_reduce(is_runtime_allocation);\n  }\n\n  static constexpr const char* _type_key = \"relay.ext.ethos-u.BaseAddress\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(BaseAddressNode, Object);\n};\n\nclass BaseAddress : public ObjectRef {\n public:\n  TVM_DLL BaseAddress(String name, Integer primfunc_param_idx, Integer region, Integer size,\n                      Bool is_runtime_allocation = Bool(false));\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(BaseAddress, ObjectRef, BaseAddressNode);\n};\n\n/*!\n * \\brief Captures all the binary artifactes required to create\n * the C-source runtime module\n */\nstruct CompilationArtifactNode : public Object {\n  /*! \\brief The function name for this artifact belongs to */\n  String function_name;\n  /*! \\brief The binary command stream (CS) in hex format */\n  String command_stream;\n  /*! \\brief The encoded biases and weights in hex format */\n  String encoded_constants;\n  /*! \\brief The information regarding the base addresses */\n  Array<BaseAddress> base_addresses;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"function_name\", &function_name);\n    v->Visit(\"command_stream\", &command_stream);\n    v->Visit(\"encoded_constants\", &encoded_constants);\n    v->Visit(\"base_addresses\", &base_addresses);\n  }\n\n  bool SEqualReduce(const CompilationArtifactNode* other, SEqualReducer equal) const {\n    return equal(function_name, other->function_name) &&\n           equal(command_stream, other->command_stream) &&\n           equal(encoded_constants, other->encoded_constants) &&\n           equal(base_addresses, other->base_addresses);\n  }\n\n  void SHashReduce(SHashReducer hash_reduce) const {\n    hash_reduce(function_name);\n    hash_reduce(command_stream);\n    hash_reduce(encoded_constants);\n    hash_reduce(base_addresses);\n  }\n\n  static constexpr const char* _type_key = \"relay.ext.ethos-u.CompilationArtifact\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CompilationArtifactNode, Object);\n};\n\nclass CompilationArtifact : public ObjectRef {\n public:\n  TVM_DLL CompilationArtifact(String function_name, String command_stream, String encoded_constants,\n                              Array<BaseAddress> base_addresses);\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(CompilationArtifact, ObjectRef, CompilationArtifactNode);\n};\n\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_ETHOSU_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/tachikoma/comp_op_matcher.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/tachikoma/comp_op_matcher.h\n * \\brief Implement matcher based function to parse complex composite nodes.\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_TACHIKOMA_COMP_OP_MATCHER_H_\n#define TVM_RELAY_BACKEND_CONTRIB_TACHIKOMA_COMP_OP_MATCHER_H_\n\n#include <tvm/relay/function.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../../ir/dataflow_matcher_impl.h\"\n\n/*!\n * \\brief Converter value to dmlc attr acceptable format\n *\n * \\tparam T type of value (auto deduction)\n * \\param val value to convert\n * \\return resulting dmlc object\n */\ntemplate <typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(std::vector<std::string>{std::to_string(val)});\n  return dmlc::any{attr};\n}\n\ntemplate <typename T, std::enable_if_t<std::is_same<T, std::string>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(std::vector<std::string>{val});\n  return dmlc::any{attr};\n}\n\ntemplate <typename T,\n          std::enable_if_t<std::is_same<T, std::vector<std::string>>::value, bool> = true>\ndmlc::any dmlc_attr(const T& val) {\n  std::vector<dmlc::any> attr;\n  attr.emplace_back(val);\n  return dmlc::any{attr};\n}\n\n/*! \\brief Constructor of const scalar expression with defined type */\ntvm::relay::Expr constant(float val) {\n  auto value = tvm::runtime::NDArray::Empty({}, tvm::DataType::Float(32), {kDLCPU, 0});\n  value.CopyFromBytes(&val, sizeof(val));\n  auto res = tvm::relay::Constant(value);\n  tvm::relay::transform::InferTypeLocal(res);\n  return res;\n}\n\n/*!\n * \\brief Simple helper to accumulate composite function arguments and corresponding attributes\n * with indexes of them.\n */\nclass ArgPacker {\n public:\n  ArgPacker(std::unordered_map<std::string, dmlc::any>* attrs, std::vector<tvm::relay::Expr>* args)\n      : attrs_(attrs), args_(args) {}\n\n  int Put(const tvm::relay::Expr& arg, std::string tag_name = \"\") {\n    if (!arg.defined()) return -1;\n    int idx = args_->size();\n    args_->push_back(arg);\n    if (!tag_name.empty()) {\n      attrs_->operator[](tag_name) = dmlc_attr(idx);\n    }\n    return idx;\n  }\n\n private:\n  std::unordered_map<std::string, dmlc::any>* attrs_;\n  std::vector<tvm::relay::Expr>* args_;\n};\n\nconst tvm::relay::CallNode* ParseQnnConvComp(const tvm::relay::FunctionNode& comp_fn,\n                                             std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                             std::vector<tvm::relay::Expr>* args) {\n  using namespace tvm::relay;\n\n  // Pattern\n  auto src = IsWildcard();\n  auto wgh = IsWildcard();\n  auto sum_src = IsWildcard();\n  auto bias = IsConstant();\n\n  auto o_scl = IsConstant();\n  auto act_scl = IsConstant();\n  auto sum_scl = IsConstant();\n  auto dst_zp = IsConstant();\n\n  DFPattern cnv;\n  DFPattern pat;\n\n  cnv = IsOp(\"qnn.conv2d\")({src, wgh, IsConstant(), IsConstant(), IsConstant(), IsConstant()});\n  pat = IsOp(\"cast\")({cnv});\n  pat = IsOp(\"add\")({pat, bias}) || pat;\n  pat = IsOp(\"multiply\")({pat, o_scl});\n  pat = IsOp(\"clip\")({pat});\n  pat = IsOp(\"multiply\")({pat, act_scl}) || pat;\n  pat = IsOp(\"add\")({pat, sum_scl * IsOp(\"cast\")({sum_src})}) || pat;\n  pat = IsOp(\"add\")({pat, dst_zp}) || pat;\n  pat = IsOp(\"cast\")({pat});\n\n  // Check pattern match\n  auto indexed_body = CreateIndexedGraph(comp_fn.body);\n  DFPatternMatcher matcher(indexed_body.get());\n  auto res = matcher.Match(pat, comp_fn.body);\n  ICHECK(res) << \"Mismatch of Tachikoma partitioner and codegen logic\";\n\n  // Handle arguments in deterministic order\n  auto map = matcher.GetMemo();\n  auto find = [&map](const DFPattern& pat) -> tvm::relay::Expr {\n    if (map.count(pat)) return map.at(pat)[0];\n    return {};\n  };\n\n  ArgPacker arg_holder(ext_attrs, args);\n  arg_holder.Put(find(src));\n  arg_holder.Put(find(wgh));\n  arg_holder.Put(find(bias), \"bias_idx\");\n  arg_holder.Put(find(sum_src), \"sum_idx\");\n  arg_holder.Put(find(o_scl), \"o_scl_idx\");\n  arg_holder.Put(find(act_scl), \"act_scl_idx\");\n  arg_holder.Put(find(sum_scl), \"sum_scl_idx\");\n  arg_holder.Put(find(dst_zp), \"dst_zp_idx\");\n\n  // Activation. Default clip to simulate relu via uint8 cast\n  std::vector<std::string> clip_attr{\"clip\"};\n  auto act_scl_val = map.count(act_scl) ? find(act_scl) : constant(1.0);\n  clip_attr.push_back(std::to_string(arg_holder.Put(act_scl_val)));      // act_scale\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(0.0))));    // alpha\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(255.0))));  // beta\n  (*ext_attrs)[\"activation\"] = dmlc_attr(clip_attr);\n\n  return map.at(cnv)[0].as<CallNode>();\n}\n\nconst tvm::relay::CallNode* ParseQnnDenseComp(const tvm::relay::FunctionNode& comp_fn,\n                                              std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                              std::vector<tvm::relay::Expr>* args) {\n  using namespace tvm::relay;\n\n  // Pattern\n  auto src = IsWildcard();\n  auto wgh = IsWildcard();\n  auto sum_src = IsWildcard();\n  auto bias = IsConstant();\n\n  auto o_scl = IsConstant();\n  auto act_scl = IsConstant();\n  auto sum_scl = IsConstant();\n  auto dst_zp = IsConstant();\n\n  DFPattern dns, act, pat;\n\n  dns = IsOp(\"qnn.dense\")({src, wgh, IsConstant(), IsConstant(), IsConstant(), IsConstant()});\n  pat = IsOp(\"cast\")({dns});\n  pat = IsOp(\"add\")({pat, bias}) || pat;\n  pat = IsOp(\"multiply\")({pat, o_scl});\n  pat = IsOp(\"clip\")({pat});\n  pat = IsOp(\"multiply\")({pat, act_scl}) || pat;\n  pat = IsOp(\"add\")({pat, sum_scl * IsOp(\"cast\")({sum_src})}) || pat;\n  pat = IsOp(\"add\")({pat, dst_zp}) || pat;\n  pat = IsOp(\"cast\")({pat});\n\n  // Check pattern match\n  auto indexed_body = CreateIndexedGraph(comp_fn.body);\n  DFPatternMatcher matcher(indexed_body.get());\n  auto res = matcher.Match(pat, comp_fn.body);\n  ICHECK(res) << \"Mismatch of Tachikoma partitioner and codegen logic\";\n\n  // Handle arguments in deterministic order\n  auto memo = matcher.GetMemo();\n  auto find = [&memo](const DFPattern& pat) -> tvm::relay::Expr {\n    if (memo.count(pat)) return memo.at(pat)[0];\n    return {};\n  };\n\n  ArgPacker arg_holder(ext_attrs, args);\n  arg_holder.Put(find(src));\n  arg_holder.Put(find(wgh));\n  arg_holder.Put(find(bias), \"bias_idx\");\n  arg_holder.Put(find(sum_src), \"sum_idx\");\n  arg_holder.Put(find(o_scl), \"o_scl_idx\");\n  arg_holder.Put(find(act_scl), \"act_scl_idx\");\n  arg_holder.Put(find(sum_scl), \"sum_scl_idx\");\n  arg_holder.Put(find(dst_zp), \"dst_zp_idx\");\n\n  // Activation. Default clip to simulate relu via uint8 cast\n  std::vector<std::string> clip_attr{\"clip\"};\n  auto act_scl_val = memo.count(act_scl) ? find(act_scl) : constant(1.0);\n  clip_attr.push_back(std::to_string(arg_holder.Put(act_scl_val)));      // act_scale\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(0.0))));    // alpha\n  clip_attr.push_back(std::to_string(arg_holder.Put(constant(255.0))));  // beta\n  (*ext_attrs)[\"activation\"] = dmlc_attr(clip_attr);\n\n  return memo.at(dns)[0].as<CallNode>();\n}\n\n/*!\n * Parse composite function and return real args, additional attributes and root call node\n * @param comp_fn composite function to parse\n * @param ext_attrs attr collection with additional attributes\n * @param args real arguments of node\n * @return root call node\n */\nconst tvm::relay::CallNode* ParseComposite(const tvm::relay::FunctionNode& comp_fn,\n                                           std::unordered_map<std::string, dmlc::any>* ext_attrs,\n                                           std::vector<tvm::relay::Expr>* args) {\n  auto comp = comp_fn.GetAttr<tvm::String>(tvm::relay::attr::kComposite);\n  ICHECK(comp.defined()) << \"Tachikoma JSON runtime only supports composite functions.\";\n  auto name = comp.value();\n\n  const tvm::relay::CallNode* res = nullptr;\n  if (name == \"tachikoma.qnn.conv2d\")\n    res = ParseQnnConvComp(comp_fn, ext_attrs, args);\n  else if (name == \"tachikoma.qnn.dense\")\n    res = ParseQnnDenseComp(comp_fn, ext_attrs, args);\n  return res;\n}\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_TACHIKOMA_COMP_OP_MATCHER_H_"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/contrib/tensorrt/codegen.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/contrib/tensorrt/codegen.h\n * \\brief The 'custom' compilation pass for TensorRT (invoked by the RelayToTIRTargetHook pass).\n */\n\n#ifndef TVM_RELAY_BACKEND_CONTRIB_TENSORRT_CODEGEN_H_\n#define TVM_RELAY_BACKEND_CONTRIB_TENSORRT_CODEGEN_H_\n\n#include <tvm/ir/transform.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace contrib {\nnamespace tensorrt {\n\n/*!\n * \\brief Returns the pass which replaces all calls to \"Primitive\" functions with a \"Compiler\"\n * attribute of \"tensorrt\" with calls to an extern which is implemented by a \\p TensorRTRuntime\n * runtime module added to the IRModule's \"external_mods\" attribute.\n */\ntransform::Pass CompileForTensorRT();\n\n}  // namespace tensorrt\n}  // namespace contrib\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_CONTRIB_TENSORRT_CODEGEN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/liveness_analysis.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/liveness_analysis.h\n * \\brief  Analysis that collects the live variables before and after each node.\n * NOTE: the input IR should be in ANF.\n */\n\n#ifndef TVM_RELAY_BACKEND_LIVENESS_ANALYSIS_H_\n#define TVM_RELAY_BACKEND_LIVENESS_ANALYSIS_H_\n\n#include <tvm/relay/transform.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../support/arena.h\"\n#include \"../op/memory/device_copy.h\"\n#include \"../transforms/device_aware_visitors.h\"\n#include \"../transforms/let_list.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\nusing support::Arena;\nusing VarSet = std::unordered_set<Var, ObjectPtrHash, ObjectPtrEqual>;\n\n// TODO(@altanh, @mbs, @mbrookhart): we should do a survey of all \"*-flow graphs\" in the codebase\n//                                   to see what can be deduplicated.\n\n// TODO(@altanh): support Relay Refs once/if they are supported by the VM.\n\n/*!\n * \\brief A representation of an input expression (typically a Function) as a directed graph of\n * basic blocks, with edges between basic blocks corresponding to control flow branching.\n */\nclass ControlFlowGraph {\n public:\n  struct Node;\n  struct BasicBlock;\n\n  using NodePtr = Node*;\n  using BasicBlockPtr = BasicBlock*;\n\n  /*!\n   * \\brief A chunk of IR that does not have any control flow branching. At this stage in the IR,\n   * basic blocks correspond to:\n   *   (1) a sequence of nested Let expressions, where each node in the block corresponds to a\n   *       binding and the last node is either the (non-Let) body or a binding that branches\n   *       (e.g. \"let %x = if (%c) { true_block } else { false_block }\").\n   *   (2) an atomic expression representing the target expression of a control flow branch, e.g.\n   *       %v and %u in \"let %x = if (%c) { %v } else { %u }\".\n   */\n  struct BasicBlock {\n    // The nodes of the basic block.\n    std::vector<NodePtr> nodes;\n    // The predecessor basic blocks.\n    std::vector<BasicBlockPtr> pred;\n    // The successor basic blocks.\n    std::vector<BasicBlockPtr> succ;\n\n    static BasicBlockPtr Make(support::Arena* arena) { return arena->make<BasicBlock>(); }\n  };\n\n  /*!\n   * \\brief Roughly corresponds to a \"statement\" in the IR, such as an individual binding in a\n   * basic block or the \"return value\" of a block. Each node maps to a single corresponding expr in\n   * the IR, but the converse is not true (e.g. in the case of variables).\n   */\n  struct Node {\n    /*! \\brief The basic block this node belongs to. */\n    BasicBlockPtr parent;\n    /*! \\brief The index into the parent basic block where this node is. */\n    size_t index;\n    /*! \\brief The expr this node corresponds to. */\n    Expr expr;\n\n    /*! \\brief Returns whether or not this node is the first one in the parent basic block. */\n    bool IsFirst() const { return index == 0; }\n\n    /*! \\brief Returns whether or not this node is the last one in the parent basic block. */\n    bool IsLast() const { return index == parent->nodes.size() - 1; }\n\n    /*! \\brief Returns the predecessor nodes of this node. */\n    std::vector<NodePtr> GetPred() const {\n      std::vector<NodePtr> pred;\n      if (IsFirst()) {\n        for (const BasicBlockPtr& pred_block : parent->pred) {\n          pred.push_back(pred_block->nodes.back());\n        }\n      } else {\n        pred.push_back(parent->nodes[index - 1]);\n      }\n      return pred;\n    }\n\n    /*! \\brief Returns the successor nodes of this node. */\n    std::vector<NodePtr> GetSucc() const {\n      std::vector<NodePtr> succ;\n      if (IsLast()) {\n        for (const BasicBlockPtr& succ_block : parent->succ) {\n          succ.push_back(succ_block->nodes.front());\n        }\n      } else {\n        succ.push_back(parent->nodes[index + 1]);\n      }\n      return succ;\n    }\n\n    /*! \\brief Creates a node with the given expr and appends it to the parent basic block. */\n    static NodePtr Make(Arena* arena, BasicBlockPtr parent, Expr expr) {\n      NodePtr n = arena->make<Node>();\n      n->parent = parent;\n      n->expr = expr;\n      n->index = parent->nodes.size();\n      parent->nodes.push_back(n);\n      return n;\n    }\n  };\n\n  /*! \\brief The basic block where control flow begins. */\n  BasicBlockPtr entry;\n\n  /*!\n   * \\brief Mapping from Let expressions to their corresponding nodes. Note that Let expressions\n   * are never shared in ANF (unlike vars), so this is an injection.\n   */\n  std::unordered_map<Expr, NodePtr, ObjectPtrHash, ObjectPtrEqual> let_map;\n\n  /*! \\brief The nodes of the CFG in reverse post order. */\n  std::vector<NodePtr> reverse_post_order;\n\n  /*! \\brief Creates and returns the CFG of the given expression. */\n  static ControlFlowGraph Create(Arena* arena, const Expr& body);\n\n private:\n  class Creator;\n};\n\n/*! \\brief Helper class for building CFGs. */\nclass ControlFlowGraph::Creator : private ExprFunctor<void(const Expr&, BasicBlockPtr)> {\n public:\n  Creator() {}\n\n  ControlFlowGraph Create(Arena* arena, const Expr& body);\n\n private:\n  /*! \\brief The arena allocator. */\n  Arena* arena_;\n\n  /*! \\brief The CFG being built. */\n  ControlFlowGraph cfg_;\n  /*!\n   * \\brief Whether or not we are in a function. CFGs do not support nested functions so this is\n   * used to error out in such a case.\n   */\n  bool in_func_ = false;\n\n  /*!\n   * \\brief Link \\p to as a successor block to \\p from.\n   */\n  void Succ(BasicBlockPtr from, BasicBlockPtr to);\n\n#define DEFAULT_CFG(OP)                                       \\\n  void VisitExpr_(const OP* op, BasicBlockPtr parent) final { \\\n    NodePtr n = Node::Make(arena_, parent, GetRef<Expr>(op)); \\\n    cfg_.reverse_post_order.push_back(n);                     \\\n  }\n\n  void VisitExpr_(const FunctionNode* f, BasicBlockPtr parent) final;\n  void VisitExpr_(const LetNode* let_node, BasicBlockPtr parent) final;\n  void VisitExpr_(const IfNode* if_node, BasicBlockPtr parent);\n  void VisitExpr_(const MatchNode* match_node, BasicBlockPtr parent);\n\n  DEFAULT_CFG(VarNode);\n  DEFAULT_CFG(GlobalVarNode);\n  DEFAULT_CFG(ConstantNode);\n  DEFAULT_CFG(CallNode);\n  DEFAULT_CFG(OpNode);\n  DEFAULT_CFG(TupleNode);\n  DEFAULT_CFG(TupleGetItemNode);\n};\n\n/*!\n * \\brief Helper class for collecting the variables used/read by an expression. NOTE: for If exprs,\n * only the condition is included (not the branches). Similarly, for Match exprs only the value\n * being deconstructed is included.\n */\nclass VarUseCollector : public ExprFunctor<VarSet(const Expr& e)> {\n public:\n  VarSet VisitExpr_(const VarNode* var_node);\n  VarSet VisitExpr_(const CallNode* call_node);\n  VarSet VisitExpr_(const TupleNode* tuple_node);\n  VarSet VisitExpr_(const TupleGetItemNode* get_node);\n  VarSet VisitExpr_(const IfNode* if_node);\n  VarSet VisitExpr_(const MatchNode* match_node);\n\n  VarSet VisitExpr_(const ConstructorNode* cons_node) { return {}; }\n  VarSet VisitExpr_(const GlobalVarNode* gvar_node) { return {}; }\n  VarSet VisitExpr_(const ConstantNode* const_node) { return {}; }\n  VarSet VisitExpr_(const OpNode* op_node) { return {}; }\n  VarSet VisitExpr_(const FunctionNode* func_node) { return {}; }\n};\n\n/*!\n * \\brief Analysis that collects the variables used and defined at each node.\n */\nstruct UseDefAnalysis {\n  using CFG = ControlFlowGraph;\n\n  /*! \\brief Mapping of node -> variables used/read by node. */\n  std::unordered_map<CFG::NodePtr, VarSet> use;\n\n  /*! \\brief Mapping of node -> variable defined/written by node. */\n  std::unordered_map<CFG::NodePtr, Var> def;\n\n  VarUseCollector use_collector;\n\n  static UseDefAnalysis Analyze(const CFG& cfg);\n};\n\n/*! \\brief Returns whether \\p a and \\p b are the same set of vars. */\nbool SetEqual(const VarSet& a, const VarSet& b);\n\n/*!\n * \\brief Analysis that collects the live variables before and after each node.\n */\nstruct LivenessAnalysis {\n  using CFG = ControlFlowGraph;\n\n  /*! \\brief Mapping of node -> set of variables live before node. */\n  std::unordered_map<CFG::NodePtr, VarSet> live_in;\n\n  /*! \\brief Mapping of node -> set of variables live after node. */\n  std::unordered_map<CFG::NodePtr, VarSet> live_out;\n\n  /*!\n   * \\brief Analyze the input \\p cfg (using info from \\p use_def).\n   *\n   * \\param cfg The input control flow graph.\n   * \\param use_def Use-def analysis of \\p cfg.\n   * \\return LivenessAnalysis\n   */\n  static LivenessAnalysis Analyze(const ControlFlowGraph& cfg, const UseDefAnalysis& use_def);\n};\n\n}  // namespace transform\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_LIVENESS_ANALYSIS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/name_transforms.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/name_transforms.h\n * \\brief Transformations which are applied on names to generate appropriately named compiler\n * artifacts\n *\n * Example:\n * ToCFunctionStyle(PrefixName(CombineNames({\"Device\", \"target\", \"Invoke\"})))\n * // TVMDeviceTargetInvoke\n *\n * ToCFunctionStyle(PrefixGeneratedName(CombineNames({\"model\", \"Run\"})))\n * // TVMGenModelRun\n *\n * ToCVariableStyle(PrefixName(CombineNames({\"Device\", \"target\", \"t\"})))\n * // tvm_device_target_t\n *\n * ToCVariableStyle(PrefixGeneratedName(CombineNames({\"model\", \"Devices\"})))\n * // tvmgen_model_devices\n *\n * ToCConstantStyle(PrefixGeneratedName(CombineNames({\"model\", \"Devices\"})))\n * // TVMGEN_MODEL_DEVICES\n *\n */\n\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/runtime/logging.h>\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n\n#ifndef TVM_RELAY_BACKEND_NAME_TRANSFORMS_H_\n#define TVM_RELAY_BACKEND_NAME_TRANSFORMS_H_\n\nnamespace tvm {\nnamespace relay {\nnamespace backend {\n\n/*!\n * \\brief Transform a name to the C variable style assuming it is\n * appropriately constructed using the prefixing functions\n * \\param original_name Original name\n * \\return Transformed function in the C function style\n */\nstd::string ToCFunctionStyle(const std::string& original_name);\n\n/*!\n * \\brief Transform a name to the C variable style assuming it is\n * appropriately constructed using the prefixing functions\n * \\param name Original name\n * \\return Transformed function in the C variable style\n */\nstd::string ToCVariableStyle(const std::string& original_name);\n\n/*!\n * \\brief Transform a name to the C constant style assuming it is\n * appropriately constructed using the prefixing functions\n * \\param name Original name\n * \\return Transformed function in the C constant style\n */\nstd::string ToCConstantStyle(const std::string& original_name);\n\n/*!\n * \\brief Combine names together for use as a generated name\n * \\param names Vector of strings to combine\n * \\return Combined together names\n */\nstd::string CombineNames(const Array<String>& names);\n\n/*!\n * \\brief Apply TVM-specific prefix to a name\n * \\param names Vector of names to combine to form a combined name\n * \\return Name with prefix applied or prefix-only if no name passed\n */\ninline std::string PrefixName(const Array<String>& names) { return \"TVM_\" + CombineNames(names); }\n\n/*!\n * \\brief Apply generated TVM-specific prefix to a name\n * \\param names Vector of names to combine to form a combined name\n * \\return Name with prefix applied or prefix-only if no name passed\n */\ninline std::string PrefixGeneratedName(const Array<String>& names) {\n  return \"TVMGen_\" + CombineNames(names);\n}\n\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_NAME_TRANSFORMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/param_dict.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file param_dict.h\n * \\brief Definitions for serializing and deserializing parameter dictionaries.\n */\n#ifndef TVM_RELAY_BACKEND_PARAM_DICT_H_\n#define TVM_RELAY_BACKEND_PARAM_DICT_H_\n\n#include <tvm/node/node.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_PARAM_DICT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/te_compiler.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/te_compiler.h\n * \\brief Internal compilation layer which lowers Relay \"primitive functions\" to TIR PrimFns.\n *\n *\n * This represents the new design of the Relay compilation flow and will replace the interface\n * contained in compile_engine.h as we migrate towards a standard pass based lowering of\n * Relay functions.\n *\n * This files provides an internal API which lowers Relay programs to components which\n * can be combined with TVM produced kernels to compile an entire program.\n *\n * The result of lowering contains a combination of `runtime::Module`s produced by external\n * compilers and a set of lowered PrimFns which can be code generated for targets.\n */\n#ifndef TVM_RELAY_BACKEND_TE_COMPILER_H_\n#define TVM_RELAY_BACKEND_TE_COMPILER_H_\n\n#include <tvm/node/structural_equal.h>\n#include <tvm/node/structural_hash.h>\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/memory.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op_strategy.h>\n#include <tvm/relay/transform.h>\n#include <tvm/runtime/module.h>\n#include <tvm/topi/elemwise.h>\n\n#include <functional>\n#include <string>\n#include <unordered_map>\n\n#include \"../transforms/infer_layout_utils.h\"\n#include \"../transforms/pass_utils.h\"\n#include \"./te_compiler_cache.h\"\n#include \"./utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace tec {\n\nusing ProcessFn = std::function<void(BaseFunc)>;\n\n/*!\n * \\brief A compiler which lowers primitive Relay functions to tensor expressions\n * and schedules them into TIR functions.\n */\nclass TECompilerNode : public Object {\n public:\n  /*! \\brief destructor */\n  virtual ~TECompilerNode() {}\n  /*!\n   * \\brief Get lowered result.\n   * \\param key The key to the cached function.\n   * \\return The result.\n   */\n  virtual CachedFunc Lower(const CCacheKey& key) = 0;\n\n  /*!\n   * \\brief Get lowered result.\n   * \\param key The key to the cached function.\n   * \\return The result.\n   */\n  virtual CachedFunc Lower(const CCacheKey& key, const String mod_name) = 0;\n\n  /* Return all functions which have been lowered by the compiler in an IRModule, annotated with\n   * their target. */\n  virtual IRModule GetLoweredFunctions() = 0;\n\n  /*!\n   * \\brief Just in time compile to get a PackedFunc.\n   * \\param key The key to the cached function.\n   * \\return The result.\n   */\n  virtual PackedFunc JIT(const CCacheKey& key) = 0;\n  /*!\n   * \\brief Lower the shape function.\n   * \\param key The key to the cached function.\n   * \\return The result.\n   */\n  virtual CachedFunc LowerShapeFunc(const CCacheKey& key) = 0;\n  /*!\n   * \\brief Lower the external function using external codegen tools.\n   * \\return The runtime modules for each needed external codegen tool.\n   */\n  virtual tvm::Array<tvm::runtime::Module> LowerExternalFunctions() = 0;\n\n  /*!\n   * \\brief Update \\p module to remove functions marked with the \"Compiler\" attribute and replace\n   * them with their 'external' representation using the \"ExternalSymbol\" attribute.\n   *\n   * TODO(mbs): This is a stepping stone while we migrate to a more official representation\n   * of 'external functions' in the IRModule and allow lowering to incrementally updatethe\n   * module stead of forcing everything via the cache.\n   *\n   */\n  virtual void AddExterns(IRModule module) = 0;\n\n  /*!\n   * \\brief Get C Device API context mapping\n   * \\return Map of GlobalVar to associated C Device API context name (either Target or kCompiler\n   * annotated)\n   */\n  virtual Map<GlobalVar, String> GetDeviceContexts() = 0;\n  virtual void SetDeviceContexts(const Map<GlobalVar, String>& device_contexts) = 0;\n\n  virtual Map<String, Integer> GetOpWeights() const = 0;\n\n  /*! \\brief clear the cache. */\n  virtual void Clear() = 0;\n\n  void VisitAttrs(AttrVisitor*) {}\n\n  static constexpr const char* _type_key = \"relay.TECompiler\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TECompilerNode, Object);\n};\n\n/*! \\brief cache entry used in compile engine */\nclass TECompiler : public ObjectRef {\n public:\n  explicit TECompiler(Optional<IRModule> opt_mod = {}, Optional<String> mod_name = {});\n  explicit TECompiler(ObjectPtr<Object> n) : ObjectRef(n) {}\n  TECompilerNode* operator->() { return static_cast<TECompilerNode*>(get_mutable()); }\n  using ContainerType = TECompilerNode;\n  TVM_DLL static TECompiler& Global();\n};\n\n/*!\n * \\brief A function to create the function metadata for an input function (ie calculate buffer\n * input/output sizes)\n * \\param func The function to calculate function metadata for\n * \\param function_metadata The map that stores all the function metadatas\n * \\param workspace_byte_alignment Byte alignment for allocations\n */\nvoid UpdateFunctionMetadata(BaseFunc relay_func,\n                            Map<String, backend::FunctionInfo>& function_metadata,  // NOLINT(*)\n                            Integer workspace_byte_alignment = 16);\n\n/*!\n * \\brief Update the \"main\" control function's metadata\n *\n * \\param mod The module\n * \\param config All the available targets.\n * \\return function_infos Function info for each function in the module\n */\nbackend::FunctionInfo UpdateMainWorkspaceSize(const IRModule& mod, const CompilationConfig& config,\n                                              Map<Expr, backend::StorageInfo> storage_info_map);\n\n/*! \\brief Returns all the global \\p PrimFunc functions in \\p mod, but separated into an \\p IRModule\n * per \\p Target.\n *\n * \\param mod The IRModule to extract the per target module from\n * \\return The map from Target to IRModule\n */\nMap<Target, IRModule> GetPerTargetModules(IRModule mod);\n\ninline void DefaultProcessFn(BaseFunc) {}\n\n/*!\n * \\brief Pass to lower an IRModule's primitive functions to TIR.\n *\n * This is the \"back half\" of the Relay compiler which lowers \"primitive functions\"\n * to TE expressions, schedules them, and emits PrimFuncs.\n *\n * \\param module_name The name of this module, used as a prefix for generated globals.\n * \\param config All available targets.\n * \\param process_fn Callback allowing one-level up code generators to process\n * each function that we lower (default is no-op).\n * \\returns The pass which lowers primitive functions to TIR\n */\ntransform::Pass LowerTE(String module_name, CompilationConfig config,\n                        ProcessFn process_fn = DefaultProcessFn);\n\n}  // namespace tec\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_TE_COMPILER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/te_compiler_cache.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/tec_compiler_cache.h\n * \\brief Utilities for compiling tensor expressions inside of the Relay compiler.\n */\n#ifndef TVM_RELAY_BACKEND_TE_COMPILER_CACHE_H_\n#define TVM_RELAY_BACKEND_TE_COMPILER_CACHE_H_\n\n#include <tvm/ir/name_supply.h>\n#include <tvm/node/structural_equal.h>\n#include <tvm/node/structural_hash.h>\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/memory.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op_strategy.h>\n#include <tvm/relay/transform.h>\n#include <tvm/runtime/module.h>\n#include <tvm/topi/elemwise.h>\n\n#include <functional>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n\n#include \"../transforms/infer_layout_utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace tec {\n\n/*! \\brief Indicate whether the data or shape or both of a parameter is used in the shape func. */\nenum ShapeFuncParamState {\n  kNoNeed = 0,\n  kNeedInputData = 1,\n  kNeedInputShape = 2,\n  kNeedBoth = 3,\n};\n\nstruct LoweredOutputNode : public Object {\n  /*! \\brief The outputs to the function */\n  tvm::Array<te::Tensor> outputs;\n  /*! \\brief The implementation used to compute the output */\n  OpImplementation implementation;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"outputs\", &outputs);\n    v->Visit(\"implementation\", &implementation);\n  }\n  static constexpr const char* _type_key = \"relay.LoweredOutput\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LoweredOutputNode, Object);\n};\n\nclass LoweredOutput : public ObjectRef {\n public:\n  TVM_DLL LoweredOutput(tvm::Array<te::Tensor> outputs, OpImplementation impl);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(LoweredOutput, ObjectRef, LoweredOutputNode);\n};\n\nclass CCacheKey;\n/*! \\brief Compile cache key */\nclass CCacheKeyNode : public Object {\n public:\n  /*! \\brief The source function to be lowered. */\n  Function source_func;\n  /*! \\brief The hardware target.*/\n  Target target;\n  /*! \\brief The virtual device constrains.*/\n  VirtualDevice virtual_device;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"source_func\", &source_func);\n    v->Visit(\"target\", &target);\n    v->Visit(\"virtual_device\", &virtual_device);\n  }\n  /*! \\return The hash value of CCacheKey. */\n  inline size_t Hash() const;\n  /*!\n   * \\brief check content equality\n   * \\param other The other value.\n   * \\return The result of equality check.\n   */\n  inline bool Equal(const CCacheKeyNode* other) const;\n\n  static constexpr const char* _type_key = \"relay.CCacheKey\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CCacheKeyNode, tvm::Object);\n\n private:\n  /*!\n   * \\brief internal cached hash value.\n   */\n  mutable size_t hash_{0};\n};\n\n/*! \\brief cache entry used in compile engine */\nclass CCacheKey : public ObjectRef {\n public:\n  CCacheKey() {}\n  explicit CCacheKey(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  /*!\n   * \\brief The constructor\n   * \\param source_func The source function.\n   * \\param target The target device.\n   */\n  TVM_DLL CCacheKey(Function source_func, Target target,\n                    VirtualDevice virtual_device = VirtualDevice::FullyUnconstrained());\n\n  const CCacheKeyNode* operator->() const { return static_cast<const CCacheKeyNode*>(get()); }\n  // comparator\n  inline bool operator==(const CCacheKey& other) const {\n    ICHECK(defined() && other.defined());\n    return (*this)->Equal(other.operator->());\n  }\n  using ContainerType = CCacheKeyNode;\n};\n\n/*! \\brief Node container to represent a cached function. */\nstruct CachedFuncNode : public Object {\n  /*! \\brief compiled target */\n  tvm::Target target;\n  /*! \\brief Primitive Function Name */\n  GlobalVar prim_fn_var;\n  /*! \\brief The inputs to the function */\n  tvm::Array<te::Tensor> inputs;\n  /*! \\brief The outputs to the function */\n  tvm::Array<te::Tensor> outputs;\n  /*! \\brief The schedule to the function */\n  te::Schedule schedule;\n  /*! \\brief The TIR function if lowering in the meta schedule path */\n  Optional<tir::PrimFunc> prim_func;\n  /*! \\brief Parameter usage states in the shape function. */\n  tvm::Array<Integer> shape_func_param_states;\n  /*! \\brief The lowered functions to support the function. */\n  IRModule funcs = IRModule(Map<GlobalVar, BaseFunc>({}));\n  std::unordered_map<const ConstantNode*, te::Tensor> constant_tensors;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"target\", &target);\n    v->Visit(\"prim_fn_var\", &prim_fn_var);\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"outputs\", &outputs);\n    v->Visit(\"schedule\", &schedule);\n    v->Visit(\"prim_func\", &prim_func);\n    v->Visit(\"funcs\", &funcs);\n    v->Visit(\"shape_func_param_states\", &shape_func_param_states);\n  }\n\n  static constexpr const char* _type_key = \"relay.CachedFunc\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CachedFuncNode, Object);\n};\n\nclass CachedFunc : public ObjectRef {\n public:\n  CachedFunc(tvm::Target target, GlobalVar prim_fn_name, tvm::Array<te::Tensor> inputs,\n             tvm::Array<te::Tensor> outputs, te::Schedule schedule, tir::PrimFunc prim_func,\n             tvm::Array<Integer> shape_func_param_states,\n             IRModule funcs = IRModule(Map<GlobalVar, BaseFunc>({})),\n             std::unordered_map<const ConstantNode*, te::Tensor> constant_tensors = {});\n\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(CachedFunc, ObjectRef, CachedFuncNode);\n};\n\n/*! \\brief Node container for compile cache. */\nclass CCacheValueNode : public Object {\n public:\n  /*! \\brief The corresponding function */\n  CachedFunc cached_func;\n  /*! \\brief Result of Packed function generated by JIT */\n  PackedFunc packed_func;\n  /*! \\brief usage statistics */\n  int use_count{0};\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"cached_func\", &cached_func);\n    v->Visit(\"use_count\", &use_count);\n  }\n  static constexpr const char* _type_key = \"relay.CCacheValue\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CCacheValueNode, tvm::Object);\n};\n\n/*! \\brief cache entry used in compile engine */\nclass CCacheValue : public ObjectRef {\n public:\n  CCacheValue() {}\n  explicit CCacheValue(ObjectPtr<Object> n) : ObjectRef(n) {}\n  CCacheValueNode* operator->() { return static_cast<CCacheValueNode*>(get_mutable()); }\n  const CCacheValueNode* operator->() const { return static_cast<const CCacheValueNode*>(get()); }\n  using ContainerType = CCacheValueNode;\n};\n\nArray<IndexExpr> GetShape(const Array<IndexExpr>& shape);\n\n/*!\n * \\brief Lowers Relay primitive Function to TE Compute\n * \\param source_func The primitive function to be lowered.\n * \\param target The target we want to create schedule for.\n * \\param return_inputs If true, prepend input tensors to the output array of tensors.\n * \\return Tuple of the lowered TE compute, constant raw data, and fused function name.\n */\nstd::tuple<Array<te::Tensor>, Array<runtime::NDArray>, std::string> LowerTECompute(\n    const Function& source_func, Target target, bool return_inputs = true);\n\n/*!\n * \\brief Create schedule for target.\n * \\param source_func The primitive function to be lowered.\n * \\param target The target we want to create schedule for.\n * \\return Pair of schedule and cache.\n *  The funcs field in cache is not yet populated.\n */\nCachedFunc PrimFuncFor(const Function& source_func, const Target& target,\n                       GlobalVarSupply global_var_supply);\n\nCachedFunc ShapeFuncFor(const Function& prim_func, const Target& target,\n                        GlobalVarSupply global_var_supply);\n\n// implementations\ninline size_t CCacheKeyNode::Hash() const {\n  if (hash_ != 0) return hash_;\n  // do structral hash, avoid 0.\n  hash_ = tvm::StructuralHash()(this->source_func);\n  hash_ = dmlc::HashCombine(hash_, std::hash<std::string>()(target->str()));\n  if (hash_ == 0) hash_ = 1;\n  return hash_;\n}\n\ninline bool CCacheKeyNode::Equal(const CCacheKeyNode* other) const {\n  if (Hash() != other->Hash()) return false;\n  return this->target->str() == other->target->str() &&\n         this->virtual_device == other->virtual_device &&\n         tvm::StructuralEqual()(this->source_func, other->source_func);\n}\n\n}  // namespace tec\n}  // namespace relay\n}  // namespace tvm\n\nnamespace std {\n// overload hash\ntemplate <>\nstruct hash<::tvm::relay::tec::CCacheKey> {\n  size_t operator()(const ::tvm::relay::tec::CCacheKey& key) const {\n    ICHECK(key.defined());\n    return key->Hash();\n  }\n};\n}  // namespace std\n\n#endif  // TVM_RELAY_BACKEND_TE_COMPILER_CACHE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/token_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/token_allocator.h\n * \\brief Token allocation classes for backend\n */\n#ifndef TVM_RELAY_BACKEND_TOKEN_ALLOCATOR_H_\n#define TVM_RELAY_BACKEND_TOKEN_ALLOCATOR_H_\n\n#include <tvm/relay/type.h>\n#include <tvm/target/virtual_device.h>\n\n#include <map>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../runtime/texture.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*! A representation of a block of memory required at runtime on some device. */\nstruct StorageToken {\n  /*! \\brief Reference counter */\n  int ref_counter{0};\n  /*! \\brief number of bytes */\n  size_t max_bytes{0};\n  /*! \\brief The corresponding tensor type. */\n  TensorType ttype{nullptr};\n  /*! \\brief VirtualDevice on which the memory will reside. */\n  VirtualDevice virtual_device = VirtualDevice::FullyUnconstrained();\n  /*! \\brief The storage id */\n  int64_t storage_id{-1};\n\n  bool is_valid() const { return !virtual_device->IsFullyUnconstrained(); }\n\n  bool is_compatible(const StorageToken& that) const {\n    return virtual_device == that.virtual_device;\n  }\n\n  std::string ToString() const {\n    std::ostringstream os;\n    os << \"{storage_id: \" << storage_id << \", max_bytes: \" << max_bytes\n       << \", ttype: \" << PrettyPrint(ttype) << \", virtual_device: \" << virtual_device << \"}\";\n    return os.str();\n  }\n};\n\n/**\n * @brief Memory manager for flattened 1d memory (buffers)\n */\nclass TokenAllocator1D {\n public:\n  /*!\n   * \\brief ceil(size/word_size) to get number of words.\n   * \\param size The original size.\n   * \\param word_size The element size.\n   */\n  static size_t DivRoundUp(size_t size, size_t word_size) {\n    return (size + word_size - 1) / word_size;\n  }\n\n  /*!\n   * \\brief Get the memory requirement.\n   * \\param prototype The prototype token.\n   * \\return The required memory size.\n   *\n   * TODO(mbs): Gf GetMemorySizeBytes in aot_executor_codegen.cc,\n   * CalculateRelayExprSizeBytes in utils.cc\n   */\n  size_t GetMemorySize(StorageToken* prototype);\n  /*!\n   * \\brief Request a storage token for a given prototype.\n   * \\param prototype. The prototype storage token.\n   * \\return The result token.\n   */\n  StorageToken* Request(StorageToken* prototype);\n  /*!\n   * \\brief Alloacte a storage token by consuming prototype\n   * \\param prototype The prototype token.\n   * \\param size The size of memory being requested.\n   */\n  StorageToken* Alloc(StorageToken* prototype, int64_t storage_id);\n  /*!\n   * \\brief Check if we can release token.\n   * \\param tok The token to be released.\n   */\n  void CheckForRelease(StorageToken* tok);\n\n private:\n  // scale used for rough match\n  const size_t match_range_{16};\n  // free list of storage entry\n  std::multimap<size_t, StorageToken*> free_;\n  // all the storage resources available\n  std::vector<StorageToken*> data_;\n};\n\n/**\n * @brief Memory manager for 2d memory (textures)\n */\nclass TokenAllocator2D {\n public:\n  /*!\n   * \\brief Request a storage token for a given prototype.\n   * \\param prototype. The prototype storage token.\n   * \\return The result token.\n   */\n  StorageToken* Request(StorageToken* prototype);\n  /*!\n   * \\brief Alloacte a storage token by consuming prototype\n   * \\param prototype The prototype token.\n   * \\param size The size of memory being requested.\n   */\n  StorageToken* Alloc(StorageToken* prototype, int64_t storage_id);\n  /*!\n   * \\brief Check if we can release token.\n   * \\param tok The token to be released.\n   */\n  void CheckForRelease(StorageToken* tok);\n  /*!\n   * \\brief Get the texture 2d size requirement\n   * \\param prototype The prototype token.\n   * \\return The required texture 2d memory size in (width, height, channel).\n   */\n  runtime::Texture2DShape<int64_t> GetSize2D(StorageToken* prototype);\n\n protected:\n  struct MemBlock {\n    StorageToken* token_;\n    int64_t x_;\n    int64_t y_;\n  };\n\n  std::unordered_map<int64_t, MemBlock> blocks_;\n  std::unordered_set<int64_t> free_list_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_TOKEN_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/backend/utils.h\n * \\brief Utils function for backend\n */\n#ifndef TVM_RELAY_BACKEND_UTILS_H_\n#define TVM_RELAY_BACKEND_UTILS_H_\n\n#include <dmlc/json.h>\n#include <tvm/driver/driver_api.h>\n#include <tvm/relay/executor.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/transform.h>\n#include <tvm/relay/type.h>\n#include <tvm/target/codegen.h>\n#include <tvm/target/virtual_device.h>\n#include <tvm/te/operation.h>\n#include <tvm/tir/usmp/utils.h>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <typeinfo>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../../runtime/meta_data.h\"\n#include \"../../target/metadata.h\"\n#include \"tvm/runtime/ndarray.h\"\n\nnamespace tvm {\nnamespace relay {\n\nnamespace tec {\nclass TECompiler;\n}\n\nnamespace backend {\nusing Pass = tvm::transform::Pass;\n\n/*! \\brief Describes the type of kernel call emitted. */\nenum CallType {\n  /*!\n   * \\brief Emit PackedFunc calls bound just-in-time using TVMBackend* functions.\n   *\n   * When this type is selected, assumes all operators must be called via TVMFuncCall. Given the\n   * implementation of TVMFuncCall in the C++ runtime, this in practice implies that those\n   * functions are of type TVMBackendPackedCFunc.\n   *\n   * The following code is emitted at call sites to call a function named `func`:\n   * void* func_ptr = TVMBackendGetFuncFromEnv(\"func\");\n   * TVMFuncCall(func_ptr, values, tcodes, num_args, ret_values, ret_tcodes)\n   *\n   * The arguments given to the tir::Call node are encoded into `values`, `tcodes`, and `num_args`\n   * by LowerTVMBuiltin TIR transform.\n   *\n   * If `resource_handle` is passed to `func`, it is determined by TVMFuncCall (often,\n   * `resource_handle` is registered with the C++ runtime to provide a `this` equivalent when\n   * `func` is implemented in C).\n   *\n   * Compatible with both C++ and C runtimes, implemented with the C runtime only.\n   */\n  kPacked,  // Emit tir.call_packed and wrap all arguments in DLTensor.\n\n  /*!\n   * \\brief Directly call a TVMBackendPackedCFunc named according to the tir::Call.\n   *\n   * When this type is selected, assumes all operators are implemented in functions of type\n   * `TVMBackendPackedCFunc` and should be called directly. That is, presumes at the time of\n   * downstream compilation that there is a symbol named after the 0th arg to tir::Call of\n   * type `TVMBackendPackedCFunc`. This situation should occur when target_host == target.\n   *\n   * The following code is emitted at call sites to call a function named `func`:\n   * func(values, tcodes, num_args, ret_values, ret_tcodes, resource_handle)\n   *\n   * The arguments given to the tir::Call node are encoded into `values`, `tcodes`, and `num_args`\n   * by LowerTVMBuiltin TIR transform.\n   *\n   * `resource_handle` is encoded as the final argument to the tir::Call node. In practice, it is\n   * always the device context parameter when not null. At present, the implementation does not\n   * support forwarding device context parameters to CPacked.\n   *\n   * Compatible with the C runtime and C++ runtime (so long as target_host == target). Implemented\n   * in the same scenarios.\n   */\n  kCPacked,  // Emit tir.call_cpacked and wrap all arguments in DLTensor.\n\n  /*! \\brief Directly call a function accepting the `data` arrays as args.\n   *\n   * When this type is selected, assumes all operaotrs are implemented in C functions whose\n   * arguments are 1-to-1 with those in the tir::Call. DLTensor arguments are encoded as just the\n   * `data` parameters (i.e. no DLTensor object is passed along).\n   *\n   * The following code is emitted at call sites to a function named `func`:\n   * func(void* arg0, void* arg1, ..., void* argN) // no resource_handle\n   * -or-\n   * func(void* arg0, void* arg1, ..., void* argN, void* resource_handle) // with resource_handle\n   *\n   * `resource_handle` is encoded as the final argument to the tir::Call node. In practice, it is\n   * always the device context parameter when not null.\n   *\n   * Compatible with the C runtime and C++ runtime (so long as target_host == target). Implemented\n   * with the C runtime only.\n   */\n  kUnpacked,  // Emit tir.call_extern passing only the `data` part of DLTensors.\n};\n\n/*!\n * \\brief Structure that can be optionally used by the executor codegen\n */\nclass ExecutorCodegenMetadataNode : public Object {\n public:\n  /*! \\brief input information for the main function */\n  Array<tir::Var> inputs;\n  /*! \\brief input tensor type information */\n  Array<TensorType> input_tensor_types;\n  /*! \\brief output information for the main function */\n  Array<String> outputs;\n  /*! \\brief output tensor type information */\n  Array<TensorType> output_tensor_types;\n  /*! \\brief pool information for the main function */\n  Array<tir::Var> pools;\n  /*! \\brief device contexts information for the main function */\n  Array<String> devices;\n  /*! \\brief the executor to be used to run the model */\n  String executor = runtime::kTvmExecutorGraph;\n  /*! \\brief The external API (packed or c) in use */\n  String interface_api;\n  /*! \\brief The internal API (packed or unpacked) in use */\n  bool unpacked_api;\n  /*! \\brief Alginment of the workspace in bytes */\n  Integer workspace_alignment;\n  /*! \\brief Alginment of the constants in bytes */\n  Integer constant_alignment;\n  /*! \\brief the input var names that correspond to pool_inputs */\n  Optional<Map<tir::Var, tir::usmp::AllocatedPoolInfo>> pool_inputs;\n  /*! \\brief the I/O tensor to PoolAllocations if any*/\n  Map<String, tir::usmp::PoolAllocation> io_pool_allocations;\n\n  String mod_name = \"\";\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"inputs\", &inputs);\n    v->Visit(\"input_tensor_types\", &input_tensor_types);\n    v->Visit(\"outputs\", &outputs);\n    v->Visit(\"output_tensor_types\", &output_tensor_types);\n    v->Visit(\"pools\", &pools);\n    v->Visit(\"devices\", &devices);\n    v->Visit(\"executor\", &executor);\n    v->Visit(\"interface_api\", &interface_api);\n    v->Visit(\"unpacked_api\", &unpacked_api);\n    v->Visit(\"workspace_alignment\", &workspace_alignment);\n    v->Visit(\"constant_alignment\", &constant_alignment);\n    v->Visit(\"pool_inputs\", &pool_inputs);\n    v->Visit(\"io_pool_allocations\", &io_pool_allocations);\n    v->Visit(\"mod_name\", &mod_name);\n  }\n\n  static constexpr const char* _type_key = \"MetadataObj\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ExecutorCodegenMetadataNode, Object);\n};\n\n/*!\n * \\brief Managed reference to ExecutorCodegenMetadataNode.\n */\nclass ExecutorCodegenMetadata : public ObjectRef {\n public:\n  TVM_DLL ExecutorCodegenMetadata(Array<tir::Var> inputs, Array<TensorType> input_tensor_types,\n                                  Array<String> outputs, Array<TensorType> output_tensor_types,\n                                  Array<tir::Var> pools, Array<String> devices, String executor,\n                                  String mod_name, String interface_api = \"packed\",\n                                  bool unpacked_api = false, Integer workspace_alignment = 16,\n                                  Integer constant_alignment = 16,\n                                  Map<tir::Var, tir::usmp::AllocatedPoolInfo> pool_inputs =\n                                      Map<tir::Var, tir::usmp::AllocatedPoolInfo>(),\n                                  Map<String, tir::usmp::PoolAllocation> io_pool_allocations = {});\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(ExecutorCodegenMetadata, ObjectRef,\n                                        ExecutorCodegenMetadataNode);\n};\n\n/*!\n * \\brief The static storage information for each Tensor in the result of a Relay expression\n * (as per relay::FlattenTupleType).\n */\nclass StorageInfoNode : public Object {\n public:\n  // TODO(mbs): Switch from struct-of-array to array-of-struct repr throughout.\n  /*! \\brief The set of storage ids where the expression is stored. */\n  std::vector<int64_t> storage_ids;\n  /* \\brief The virtual devices these expressions are stored within. */\n  std::vector<VirtualDevice> virtual_devices;\n  /* \\brief The sizes of each storage element, in bytes. */\n  std::vector<int64_t> storage_sizes_in_bytes;\n\n  // TODO(@jroesch): expose the fields\n  void VisitAttrs(AttrVisitor* v) {}\n\n  static constexpr const char* _type_key = \"relay.StorageInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StorageInfoNode, Object);\n};\n\n/*! \\brief The storage information for a single expression. */\nclass StorageInfo : public ObjectRef {\n public:\n  StorageInfo(std::vector<int64_t> storage_ids, std::vector<VirtualDevice> virtual_devices,\n              std::vector<int64_t> storage_sizes_in_bytes);\n  TVM_DEFINE_OBJECT_REF_METHODS(StorageInfo, ObjectRef, StorageInfoNode);\n};\n\n/*!\n * \\brief The result of static memory planning.\n */\nclass StaticMemoryPlanNode : public Object {\n public:\n  Map<Expr, StorageInfo> expr_to_storage_info;\n\n  void VisitAttrs(AttrVisitor* v) { v->Visit(\"expr_to_storage_info\", &expr_to_storage_info); }\n\n  static constexpr const char* _type_key = \"relay.StaticMemoryPlan\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(StaticMemoryPlanNode, Object);\n};\n\n/*! \\brief The result of running static memory planning. */\nclass StaticMemoryPlan : public ObjectRef {\n public:\n  explicit StaticMemoryPlan(Map<Expr, StorageInfo> expr_to_storage_info);\n  TVM_DEFINE_OBJECT_REF_METHODS(StaticMemoryPlan, ObjectRef, StaticMemoryPlanNode);\n};\n\nstruct FunctionInfoNode : public Object {\n  Map<Target, Integer> workspace_sizes;\n  Map<Target, Integer> io_sizes;\n  Map<Target, Integer> constant_sizes;\n  Map<Target, tir::PrimFunc> tir_primfuncs;\n  Map<Target, Function> relay_primfuncs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"workspace_sizes\", &workspace_sizes);\n    v->Visit(\"io_sizes\", &io_sizes);\n    v->Visit(\"constant_sizes\", &constant_sizes);\n    v->Visit(\"tir_primfuncs\", &tir_primfuncs);\n    v->Visit(\"relay_primfuncs\", &relay_primfuncs);\n  }\n\n  static constexpr const char* _type_key = \"relay.backend.FunctionInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(FunctionInfoNode, Object);\n};\n\nclass FunctionInfo : public ObjectRef {\n public:\n  FunctionInfo(Map<Target, Integer> workspace_sizes, Map<Target, Integer> io_sizes,\n               Map<Target, Integer> constant_sizes, Map<Target, tir::PrimFunc> tir_primfuncs,\n               Map<Target, Function> relay_primfuncs);\n\n  TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(FunctionInfo, ObjectRef, FunctionInfoNode);\n};\n\n/*!\n * \\brief Calculate the bytes of memory needed to hold a tensor of a given shape and data type.\n * \\param shape The shape of the tensor\n * \\param dtype The data type of the tensor\n */\nsize_t GetMemorySizeBytes(const Array<PrimExpr>& shape, const DataType& dtype);\n\n/*!\n * \\brief Calculate the storage required to store the type of relay.Expr\n *\n * \\param func The relay expr for which the storage is calculated\n */\nint64_t CalculateRelayExprSizeBytes(const Type& expr_type);\n\n/*!\n *  \\brief Executor generator artifacts. Those artifacts  are subsequently\n *  used by the relay build process.\n */\nstruct LoweredOutput {\n  std::string graph_json;\n  Map<Target, IRModule> lowered_funcs;\n  Array<tvm::runtime::Module> external_mods;\n  Map<String, FunctionInfo> function_metadata;\n  /*!\n   * \\brief Map from constant names (allocated by the codegen as constants are encountered)\n   * to the constant's value.\n   */\n  std::unordered_map<std::string, tvm::runtime::NDArray> params;\n  ExecutorCodegenMetadata metadata;\n};\n\n/*!\n * \\brief This class is needed to avoid a GCC 5 bug that prevents maps containing enums from being\n compiled. If i386 GCC version is increased, we can remove it.\n */\nstruct EnumClassHash {\n  template <typename T>\n  std::size_t operator()(T t) const {\n    return static_cast<std::size_t>(t);\n  }\n};\n\n/*!\n * \\brief A helper to expand the params by adding the ones used in a given expression.\n */\nstruct ConstantUpdater : public ExprVisitor {\n public:\n  ConstantUpdater(const std::string& symbol,\n                  std::unordered_map<std::string, runtime::NDArray>* params)\n      : symbol_(symbol), params_(params) {}\n\n  void VisitExpr_(const ConstantNode* cn) final {\n    std::string name = symbol_ + \"_const_\" + std::to_string(const_idx_++);\n    VLOG(1) << \"binding '\" << name << \"' to constant of type \" << PrettyPrint(cn->checked_type());\n    (*params_)[name] = cn->data;\n  }\n\n private:\n  int const_idx_{0};\n  std::string symbol_;\n  std::unordered_map<std::string, runtime::NDArray>* params_;\n};\n\n/*!\n * \\brief A function to update the params with constants found in an external function.\n * \\param func The function from which to get the constant params.\n * \\param params The params to update with the constants.\n */\ninline void UpdateConstants(BaseFunc func,\n                            std::unordered_map<std::string, runtime::NDArray>* params) {\n  VLOG_CONTEXT << \"UpdateConstants\";\n  VLOG(1) << \"updating constants for:\" << std::endl << PrettyPrint(func);\n  auto codegen = func->GetAttr<String>(attr::kCompiler);\n  ICHECK(codegen.defined()) << \"No external codegen is set\";\n  std::string codegen_name = codegen.value();\n  const auto name_node = func->GetAttr<String>(tvm::attr::kGlobalSymbol);\n  std::string symbol = std::string(name_node.value());\n  std::string const_update_name = \"relay.ext.\" + codegen_name + \".constant_updater\";\n  // Get the constant updater for the external codegen\n  auto pf = tvm::runtime::Registry::Get(const_update_name);\n  // If the backend hasn't registered a constant updater, use a default one\n  if (pf == nullptr) {\n    ConstantUpdater const_visit(symbol, params);\n    const_visit(func);\n  } else {\n    Map<String, tvm::runtime::NDArray> constants = (*pf)(func, symbol);\n    for (const auto& it : constants) {\n      std::string const_name(it.first);\n      // Constant names should begin this the compiler name (to avoid conflicts)\n      ICHECK(const_name.find(codegen_name) == 0)\n          << \"External constant names must start with compiler name\";\n      (*params)[const_name] = it.second;\n    }\n  }\n  for (const auto& pair : *params) {\n    VLOG(1) << \"Constants: \" << pair.first << \" = \" << PrettyPrint(pair.second);\n  }\n}\n\n/*!\n * \\brief A simple wrapper around ExprFunctor for a single argument case.\n *  The result of visit is memoized.\n */\ntemplate <typename OutputType>\nclass MemoizedExprTranslator : public ::tvm::relay::ExprFunctor<OutputType(const Expr&)> {\n  using BaseFunctor = ::tvm::relay::ExprFunctor<OutputType(const Expr&)>;\n\n public:\n  /*! \\brief virtual destructor */\n  virtual ~MemoizedExprTranslator() {}\n\n  /*!\n   * \\brief The memoized call.\n   * \\param n The expression node.\n   * \\return The result of the call\n   */\n  virtual OutputType VisitExpr(const Expr& n) {\n    ICHECK(n.defined());\n    auto it = memo_.find(n);\n    if (it != memo_.end()) {\n      return it->second;\n    }\n    auto res = BaseFunctor::VisitExpr(n);\n    memo_[n] = res;\n    return res;\n  }\n\n protected:\n  /*! \\brief Internal map used for memoization. */\n  std::unordered_map<Expr, OutputType, ObjectPtrHash, ObjectPtrEqual> memo_;\n};\n\n/*!\n * \\brief Get the Packed Func\n *\n * \\param func_name\n * \\return const PackedFunc*\n */\ninline const PackedFunc* GetPackedFunc(const std::string& func_name) {\n  return tvm::runtime::Registry::Get(func_name);\n}\n\n/*!\n * \\brief Get a typed packed function.\n *\n * \\param func_name\n * \\return const PackedFunc*\n */\ntemplate <typename R, typename... Args>\ninline const runtime::TypedPackedFunc<R(Args...)> GetTypedPackedFunc(const std::string& func_name) {\n  auto* pf = GetPackedFunc(func_name);\n  ICHECK(pf != nullptr) << \"can not find packed function\";\n  return runtime::TypedPackedFunc<R(Args...)>(*pf);\n}\n\n/*!\n * \\brief Extract shape from an IndexExpr array to std::vector<int64_t>\n *\n * \\param shape The shape in Array\n * \\return The converted shape in std::vector<int64_t>\n */\ninline std::vector<int64_t> GetIntShape(const Array<IndexExpr>& shape) {\n  std::vector<int64_t> ret;\n  for (const auto& dim : shape) {\n    const int64_t* pval = tir::as_const_int(dim);\n    ret.push_back(pval ? *pval : -1);\n  }\n  return ret;\n}\n\n/*!\n * \\brief Convert type to string\n *\n * \\param typ\n * \\return std::string string format of type\n */\ninline std::string DType2String(const tvm::DataType dtype) {\n  std::ostringstream os;\n  if (dtype.is_float()) {\n    os << \"float\";\n  } else if (dtype.is_int()) {\n    os << \"int\";\n  } else if (dtype.is_uint()) {\n    os << \"uint\";\n  } else if (dtype.is_bfloat16()) {\n    os << \"bfloat\";\n  } else if ((*GetPackedFunc(\"runtime._datatype_get_type_registered\"))(dtype.code())) {\n    os << \"custom[\"\n       << (*GetPackedFunc(\"runtime._datatype_get_type_name\"))(dtype.code()).operator std::string()\n       << \"]\";\n  } else {\n    LOG(FATAL) << \"Unknown type with code \" << static_cast<unsigned>(dtype.code());\n  }\n  os << dtype.bits();\n  return os.str();\n}\n\n/*!\n * \\brief Bind params to function by using name\n * \\param func Relay function\n * \\param params params dict\n * \\return relay::Function\n */\nrelay::Function BindParamsByName(relay::Function func,\n                                 const std::unordered_map<std::string, runtime::NDArray>& params);\n\n/*!\n * \\brief Bind params to the main function in Relay module, using BindParamsByName\n * \\param mod Relay module\n * \\param params params dict\n */\nvoid BindParamsInModule(IRModule mod,\n                        const std::unordered_map<std::string, runtime::NDArray>& params);\n\nvoid BindParamsInModule(IRModule mod, Map<String, runtime::NDArray> params);\n\n/*!\n * \\brief Extract the shape from a Relay tensor type.\n * \\param type The provided type.\n * \\return The extracted shape in a list.\n */\ninline std::vector<int> GetShape(const Type& type) {\n  const auto* ttype = type.as<TensorTypeNode>();\n  ICHECK(ttype) << \"Expect TensorTypeNode\";\n  std::vector<int> shape;\n  for (size_t i = 0; i < ttype->shape.size(); ++i) {\n    auto* val = ttype->shape[i].as<IntImmNode>();\n    ICHECK(val);\n    shape.push_back(val->value);\n  }\n  return shape;\n}\n\n/*!\n * \\brief Check if a call has the provided name.\n * \\param call A Relay call node.\n * \\param op_name The name of the expected call.\n * \\return true if the call's name is equivalent to the given name. Otherwise,\n * false.\n */\ninline bool IsOp(const CallNode* call, const std::string& op_name) {\n  const auto* op_node = call->op.as<OpNode>();\n  ICHECK(op_node) << \"Expects a single op.\";\n  Op op = GetRef<Op>(op_node);\n  return op == Op::Get(op_name);\n}\n\n/*!\n * \\brief Retrieve the \"root\" op nested inside a fused call, such as conv2d in relu(add(conv2d))\n * \\param call A Relay call node. Typically nn.relu when called the first time.\n * \\param depth The number of calls before the root op, counting from current_call.\n * \\param expected_op_names The names of ops in this fused call. Example: {\"nn.conv2d\", \"add\",\n * \"nn.relu\"}\n * \\return A CallNode corresponding to the root op, whose name is expected_op_names[0]\n */\ninline const CallNode* GetRootCall(const CallNode* current_call, int depth,\n                                   const std::vector<std::string>& expected_op_names) {\n  ICHECK(current_call && depth >= 0 && static_cast<size_t>(depth) < expected_op_names.size() &&\n         IsOp(current_call, expected_op_names[depth]));\n\n  if (depth == 0) {\n    return current_call;\n  }\n\n  ICHECK_GT(current_call->args.size(), 0);\n  size_t valid_node_idx = 0;\n  while (valid_node_idx < current_call->args.size() &&\n         current_call->args[valid_node_idx].as<VarNode>()) {\n    valid_node_idx++;\n  }\n  while (valid_node_idx < current_call->args.size() &&\n         !(IsOp(current_call->args[valid_node_idx].as<CallNode>(), expected_op_names[depth - 1]))) {\n    valid_node_idx++;\n  }\n  const auto* next_call = current_call->args[valid_node_idx].as<CallNode>();\n  return GetRootCall(next_call, depth - 1, expected_op_names);\n}\n\n/*!\n * \\brief Retrieve the \"root\" op nested inside a fused call, such as conv2d in relu(add(conv2d))\n * Unlike the previous definition, it does not verify operator names of intermediate nodes. Instead,\n * it recursively visit child nodes until it finds a call node with the given op_name.\n * \\param call A Relay call node.\n * \\param op_name The name of an op to look for, such as \"\"nn.conv2d\".\n * \\return A CallNode corresponding to the root op with the given op_name\n */\ninline const CallNode* GetRootCall(const CallNode* current_call, const std::string& op_name) {\n  if (current_call == nullptr) return nullptr;\n  if (IsOp(current_call, op_name)) return current_call;\n\n  ICHECK_GT(current_call->args.size(), 0);\n\n  const auto* next_call = current_call->args[0].as<CallNode>();\n  return GetRootCall(next_call, op_name);\n}\n\n/*!\n * \\brief Retrieve the expected \"root\" op nested inside a fused call, such as conv2d in\n *        relu(add(conv2d))\n * \\param call A Relay call node. Typically nn.relu when called the first time.\n * \\param max_depth The maximum number of calls before the root op, counting from current_call.\n * \\param op_name The name of expected \"root\" op in this fused call.\n * \\return A CallNode corresponding to the root op\n */\ninline const CallNode* GetRootCall(const CallNode* current_call, int max_depth,\n                                   const std::string& op_name) {\n  ICHECK(current_call && max_depth >= 0);\n\n  if (max_depth == 0) {\n    ICHECK(current_call && IsOp(current_call, op_name));\n    return current_call;\n  }\n  if (IsOp(current_call, op_name)) {\n    return current_call;\n  }\n\n  ICHECK_GT(current_call->args.size(), 0);\n\n  size_t valid_node_idx = 0;\n  while (valid_node_idx < current_call->args.size() &&\n         current_call->args[valid_node_idx].as<VarNode>()) {\n    valid_node_idx++;\n  }\n\n  const auto* next_call = current_call->args[valid_node_idx].as<CallNode>();\n  return GetRootCall(next_call, max_depth - 1, op_name);\n}\n\n/*!\n * \\brief Get the external symbol of the Relay function name.\n *\n * \\param func The provided function.\n * \\return An external symbol.\n */\ninline std::string GetExtSymbol(const Function& func) {\n  const auto name_node = func->GetAttr<String>(tvm::attr::kGlobalSymbol);\n  ICHECK(name_node.defined()) << \"Fail to retrieve external symbol.\";\n  return std::string(name_node.value());\n}\n\n/*!\n * \\brief Return whether the auto scheduler is enabled in the pass context.\n */\ninline bool IsAutoSchedulerEnabled() {\n  return transform::PassContext::Current()\n      ->GetConfig<Bool>(\"relay.backend.use_auto_scheduler\", Bool(false))\n      .value();\n}\n\n/*!\n * \\brief Return whether the meta schedule is enabled in the pass context.\n */\ninline bool IsMetaScheduleEnabled() {\n  return transform::PassContext::Current()\n      ->GetConfig<Bool>(\"relay.backend.use_meta_schedule\", Bool(false))\n      .value();\n}\n\n/*! \\brief Consider MetaSchedule's dispatch option. */\ninline int UseMetaScheduleDispatch() {\n  return transform::PassContext::Current()\n      ->GetConfig<Integer>(\"relay.backend.use_meta_schedule_dispatch\", Integer(0))\n      .value()\n      ->value;\n}\n/*!\n * \\brief Method in TECompiler to convert TE compute to scheduleable TIR\n * \\param args The arguments of the TE compute\n * \\param constants The constants used in AllocateConst\n * \\return NullOpt if conversion fails; Otherwise the converted TIR\n * \\note This method could be further used as a task filtering mechanism in task extraction\n */\nusing FTECompilerTIRConverter = runtime::TypedPackedFunc<  //\n    Optional<tir::PrimFunc>(                               //\n        const Array<te::Tensor>& args,                     //\n        const Array<runtime::NDArray>& constants)>;\n\n/*! \\brief Return a task filter for AutoTIR according to `relay.backend.tir_converter` */\ninline FTECompilerTIRConverter GetTIRConverter() {\n  String name = transform::PassContext::Current()\n                    ->GetConfig<String>(\"relay.backend.tir_converter\", \"default\")\n                    .value();\n  const PackedFunc* f = runtime::Registry::Get(\"relay.backend.tir_converter.\" + name);\n  ICHECK(f != nullptr) << \"IndexError: Cannot find TIR converter: \" << name;\n  return FTECompilerTIRConverter(*f);\n}\n\n/*! \\brief Converts a PrimFunc to IRModule. */\ninline IRModule PrimFuncToIRModule(tir::PrimFunc f) {\n  f = WithAttrs(f, Map<String, ObjectRef>{\n                       {tvm::attr::kGlobalSymbol, String(\"main\")},\n                       {tvm::tir::attr::kNoAlias, Bool(1)},\n                   });\n  return IRModule({{GlobalVar(\"main\"), f}});\n}\n\n/*!\n * \\brief Get the sequence of Relay optimization passes based on backend type.\n * The prefix of the Relay passes almost overlaps between the vm and graph backend, with some slight\n * difference. This function unifies the shared optimization pass prefix between vm and graph\n * runtime, and returns the pass prefix given the backend type.\n *\n * \\param is_homogeneous True if all primitives are to be executed on the same device and target.\n * \\param is_vm True if passes are to be used for the vm executor.\n * \\return An array of passes.\n */\nArray<Pass> GetPassPrefix(bool is_homogeneous, bool is_vm);\n\n/*! \\brief Target hash function */\nstruct TargetStrHash {\n  /*!\n   * \\brief Calculate the hash code of a Target based on the string value of the Target KIND.\n   Note that this hash should NOT be used in new usecases, equality of targets based on their\n   value is not well-defined.\n   This will be removed when maps from Targets to IRModules are removed from the codebase.\n   * \\param target The Target to hash\n   * \\return String hash of the target\n   */\n  size_t operator()(const Target& target) const {\n    std::string s(target->kind->name);\n    return String::HashBytes(s.c_str(), s.size());\n  }\n};\n\n/*! \\brief Target equality function based on the string value of Target\nNote that this equality function should NOT be used in new usecases, equality of targets based on\ntheir value is not well-defined. This will be removed when maps from Targets to IRModules are\nremoved from the codebase.*/\nstruct TargetStrEqual {\n  /*!\n   * \\brief Check if the two Targets are equal\n   * \\param target One Target\n   * \\param other_target The other Target\n   * \\return String equality of the targets\n   */\n  const bool operator()(const Target& target, const Target& other_target) const {\n    TargetStrHash target_hash = TargetStrHash();\n    return target_hash(target) == target_hash(other_target);\n  }\n};\n\n/*!\n * \\brief Convert a Map<Target, IRModule> to std::unordered_map<Target, IRmodule, TargetStrHash,\n * TargetStrEqual> Target equality is currently based on pointer equality, which is a problem since\n * we have a lot of Map<Target, IRModule> in the codebase. This function converts the map to a\n * version that is keyed based on string value of the Target instead. Note that once we remove\n * Map<Target, IRModule>, this function will be removed.\n * \\param input_map The map to convert\n * \\return The converted map\n */\nstd::unordered_map<Target, IRModule, TargetStrHash, TargetStrEqual>\nTargetModuleMapToTargetStrModuleMap(Map<Target, IRModule> input_map);\n\n/*!\n * \\brief Convert a std::unordered_map<Target, IRmodule, TargetStrHash, TargetStrEqual> to\n * Map<Target, IRModule> This function is a helper that undoes TargetModuleMapToTargetStr. Note that\n * once we remove Map<Target, IRModule>, this function will be removed.\n * \\param input_map The map to convert\n * \\return The converted map\n */\nMap<Target, IRModule> TargetStrModuleMapToTargetModuleMap(\n    std::unordered_map<Target, IRModule, TargetStrHash, TargetStrEqual> input_map);\n\n/*!\n * \\brief Call \"weight update callback\" to communicate op weights seen during Relay module\n * lowering back to the auto scheduler.\n * Op weights refer to the number of times each distinct op/workload appears in a given module.\n * It is called \"use_count\" in TECompiler.\n * \\param IRModule after lowering by LowerTEPass.\n */\nvoid UpdateAutoSchedulerOpWeights(const IRModule& module);\n\n/*!\n * \\brief Extract shape from expr to vector<int64_t>\n *\n * \\param shape\n * \\return std::vector<int64_t>\n */\nstd::vector<int64_t> ShapeToJSON(tvm::Array<IndexExpr> shape);\n\n}  // namespace backend\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/backend/vm/compiler.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/backend/vm/compiler.h\n * \\brief A compiler from relay::Module to the VM byte code.\n */\n\n#ifndef TVM_RELAY_BACKEND_VM_COMPILER_H_\n#define TVM_RELAY_BACKEND_VM_COMPILER_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/interpreter.h>\n#include <tvm/relay/transform.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/vm/vm.h>\n#include <tvm/tir/function.h>\n\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../../../runtime/vm/naive_allocator.h\"\n#include \"../../../runtime/vm/profiler/vm.h\"\n#include \"../../transforms/pass_utils.h\"\n#include \"../te_compiler.h\"\n#include \"../te_compiler_cache.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace vm {\n\nusing namespace tvm::runtime;\nusing namespace tvm::runtime::vm;\nusing namespace relay::transform;\n\ntemplate <typename T, typename U>\nusing NodeMap = std::unordered_map<T, U, ObjectPtrHash, ObjectPtrEqual>;\nusing TagMap = NodeMap<tvm::relay::Constructor, Index>;\nusing TagNameMap = std::unordered_map<size_t, tvm::relay::Constructor>;\nusing GlobalMap = NodeMap<GlobalVar, Index>;\nusing ConstMap = NodeMap<Constant, Index>;\nusing ConstTensorShapeMap = NodeMap<TensorType, std::pair<Index, NDArray>>;\n\nstruct VMCompilerContext {\n  // The module context for the compilation\n  IRModule module;\n  // Error reporter\n  ErrorReporter err_reporter;\n  // Map from a unique integer to ADT constructor tag\n  TagNameMap tag_index_map;\n  // Map from ADT constructor tag to a unique integer\n  TagMap tag_map;\n  // Map from global var to a unique integer\n  GlobalMap global_map;\n  // List of constants\n  std::vector<NDArray> constants;\n  // Device indexes  for constants\n  std::vector<Index> const_device_indexes;\n  // Map from names of primitive functions already allocated to their primitive function index.\n  std::unordered_map<std::string, Index> primitive_map;\n  // The virtual devices corresponding to each device index.\n  std::vector<VirtualDevice> virtual_devices_;\n};\n\nclass VMCompiler : public runtime::ModuleNode {\n public:\n  VMCompiler() = default;\n  virtual ~VMCompiler() = default;\n\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  const char* type_key() const final { return \"VMCompiler\"; }\n\n  /*!\n   * \\brief Set the parameters\n   *\n   * \\param name name of parameter\n   * \\param data_in input DLTensor\n   */\n  void SetParam(const std::string& name, runtime::NDArray data_in);\n\n  /*!\n   * \\brief Lower the functions in a Module.\n   *\n   * ----------------------------------------------------------------------------------\n   * | This is the main entry point for the VM compilation flow.                      |\n   * |  - Preceded by \\p SetParam for the global params.                              |\n   * |  - Followed by \\p Codegen() to finalize the executable.                        |\n   * |  - Then the result runtime::Module can be constructed by GetExecutable.        |\n   * ----------------------------------------------------------------------------------\n   *\n   * \\param mod Relay Module\n   * \\param raw_targets List of available targets for running kernels. Any host target should\n   * be conveyed by the 'host' target field.\n   */\n  void Lower(IRModule mod, const Array<Target>& raw_targets);\n\n  /*\n   * \\brief Perform a series of optimizations on the input IR module. Can be used instead\n   * of Lower if wish to stop and observe optimized IRModule. Otherwise not needed on\n   * regular compilation flow.\n   *\n   * \\param mod The input IRModule.\n   * \\param raw_targets List of available target for running kernels.\n   *\n   * \\return The optimized IRModule.\n   */\n  IRModule OptimizeModule(IRModule mod, const Array<Target>& raw_targets);\n\n  /*! \\brief Generate the machine code for lowered functions. */\n  void Codegen();\n\n  /*! \\brief Returns the runtime::Module containing the compiled VM code. */\n  runtime::Module GetExecutable() const;\n\n protected:\n  /*! \\brief Builds the executor and compilation config to match \\p raw_targets. */\n  void Setup(const Array<Target>& raw_targets);\n\n  /*! \\brief Internal implementation of \\p Lower. */\n  void LowerImpl(IRModule mod);\n\n  /*! \\brief Internal implementation of \\p OptimizeModule. */\n  IRModule OptimizeModuleImpl(IRModule mod);\n\n  /*! \\brief Returns the passes which layout memory. */\n  transform::Sequential MemoryOpt(const CompilationConfig& config);\n\n  /*! \\brief Returns the passes which fuse then lower Relay primitive operators. */\n  transform::Sequential FuseAndLowerOperators(const CompilationConfig& config);\n\n  /*!\n   * \\brief Populate the global function names in a map where the value is used\n   *        as the index by the VMFunctions. Returns the number of functions.\n   */\n  size_t PopulateGlobalMap();\n\n protected:\n  /*! \\brief Targets and scopes needed for compilation. */\n  CompilationConfig config_;\n  /*! \\brief Global shared meta data */\n  VMCompilerContext context_;\n  /*! \\brief Compiled executable. */\n  ObjectPtr<Executable> exec_;\n  /*! \\brief parameters */\n  std::unordered_map<std::string, runtime::NDArray> params_;\n};\n\n}  // namespace vm\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_BACKEND_VM_COMPILER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/candidate_function_cache.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/candidate_function_cache.h\n * \\brief A cache of the unique global symbol name and cost for partitioned functions.\n */\n\n#ifndef TVM_RELAY_COLLAGE_CANDIDATE_FUNCTION_CACHE_H_\n#define TVM_RELAY_COLLAGE_CANDIDATE_FUNCTION_CACHE_H_\n\n#include <tvm/relay/function.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include \"../transforms/compiler_function_utils.h\"\n#include \"./cost.h\"\n#include \"./name_supply.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief A cache of the unique global symbol and cost for functions extracted to represent\n * partitions. If two functions are structurally equal (which includes equality of their \"Compiler\"\n * attributes) then they will share the same global symbol and estimated cost. We rely on the\n * function's attributes to distinguish partitions which are structurally the same graph but\n * intended for different targets.\n */\nclass CandidateFunctionCache : public transform::GlobalSymbolCache {\n public:\n  explicit CandidateFunctionCache(std::shared_ptr<NameSupply> name_supply)\n      : name_supply_(std::move(name_supply)) {}\n\n  struct Entry {\n    GlobalVar global_symbol;\n    Cost cost = Cost::Unknown();  // Filled in when have estimated cost.\n\n    explicit Entry(GlobalVar global_symbol) : global_symbol(std::move(global_symbol)) {}\n  };\n\n  /*!\n   * \\brief Returns the unique entry for \\p function. If no such entry already exists, create it\n   * and assign it a unique global symbol name.\n   */\n  Entry& GetEntry(const std::string& label, const Function& function);\n\n  GlobalVar GetGlobalSymbol(const Function& function) final;\n\n private:\n  std::shared_ptr<NameSupply> name_supply_;\n  std::unordered_map<Function, Entry, StructuralHash, StructuralEqual> cache_;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_CANDIDATE_FUNCTION_CACHE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/candidate_partition.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/candidate_partition.cc\n * \\brief A potential partition in the Collage search.\n */\n\n#ifndef TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_H_\n#define TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_H_\n\n#include <tvm/runtime/container/string.h>\n#include <tvm/target/compilation_config.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"./candidate_function_cache.h\"\n#include \"./cost.h\"\n#include \"./cost_estimator.h\"\n#include \"./name_supply.h\"\n#include \"./sub_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\nclass PartitionSpec;\n\n/*!\n * \\brief A candidate partition w.r.t. the overall Relay model.\n *\n * We represent the partition as a sub-graph. This means not only can we represent the scope\n * of Relay sub-expressions intended for a particular partition (or kernel), but we can also\n * represent various conventions for encoding how the operators within the partition should be\n * tagged for downstream processing.\n */\nclass CandidatePartitionNode : public Object {\n public:\n  CandidatePartitionNode() = default;\n\n  /*!\n   * \\brief Combination of all the partition rule names which produced this candidate.\n   * For debugging and explainability.\n   */\n  String rule_name_;\n\n  /*!\n   * \\brief The sub-graph of the overall expression matched by the partition rule.\n   */\n  SubGraph sub_graph_;\n\n  /*!\n   * \\brief The partition specification which produced this candidate.\n   */\n  ObjectRef /* actually PartitionSpec */ spec_;\n\n  /*!\n   * \\brief The (cached) cost of the partition.\n   *\n   * Initially Cost::Unknown, calculated and cached by EstimateCost.\n   */\n  mutable Cost cost_ = Cost::Unknown();\n\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Returns the partition specification which produced this candidate.\n   */\n  PartitionSpec partition_spec() const;\n\n  /*!\n   * \\brief Returns the name of the partition specification which produced this candidate.\n   */\n  std::string partition_spec_name() const;\n\n  /*!\n   * \\brief Returns the target of the partition specification which produced this candidate.\n   */\n  Target target() const;\n\n  /*!\n   * \\brief Return the estimated cost of the candidate partition, using \\p cost_estimator and\n   * \\p cache.\n   */\n  Cost EstimatedCost(const DataflowGraph& dataflow_graph, const CostEstimator& cost_estimator,\n                     const std::shared_ptr<CandidateFunctionCache>& cache) const;\n\n  /*!\n   * \\brief Returns a brief description of candidate suitable for debugging output.\n   */\n  std::string ToSummary(const DataflowGraph& dataflow_graph) const;\n\n  std::string ToString() const;\n\n  static constexpr const char* _type_key = \"relay.collage.CandidatePartition\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CandidatePartitionNode, Object);\n};\n\nclass CandidatePartition : public ObjectRef {\n public:\n  CandidatePartition(String rule_name, SubGraph sub_graph,\n                     ObjectRef /* actually PartitionSpec */ spec, Cost cost = Cost::Unknown());\n\n  bool operator<(const CandidatePartition& that) const;\n\n  /*!\n   * \\brief Returns true if this and \\p that candidate are disjoint, have the same (or no) target,\n   * and touch. This does not imply the \\p DisjointUnion of this and that will be valid. For\n   * example, the result may be too deep or have too many outputs.\n   */\n  bool AreTouching(const DataflowGraph& dataflow_graph, const CandidatePartition& that) const;\n\n  /*!\n   * \\brief Returns the disjoint union of this and \\p that.\n   */\n  CandidatePartition DisjointUnion(const DataflowGraph& dataflow_graph,\n                                   const CandidatePartition& that) const;\n\n  /*!\n   * \\brief Returns the disjoint union of all \\p candidates.\n   */\n  static CandidatePartition DisjointUnion(const DataflowGraph& dataflow_graph,\n                                          std::vector<CandidatePartition> candidates);\n\n  /*!\n   * \\brief Returns the root expression of \\p dataflow_graph rewritten to apply all the partitions\n   * implied by \\p candidates. The candidates can be in any order but must be disjoint.\n   */\n  static Expr ParallelRewrite(const DataflowGraph& dataflow_graph,\n                              const std::vector<CandidatePartition>& candidates);\n\n  /*!\n   * Eagerly merge all touching candidates for the same target. The candidates must be disjoint\n   * and have their Targets filled in. This is typically called on the optimal list of candidate\n   * partitions found by the Collage search in order to remove unnecessary partition boundaries.\n   * Ideally the search would never produce such candidates however to keep the search space\n   * manageable Collage may only consider candidate partitions up to a particular depth.\n   */\n  static std::vector<CandidatePartition> MaxCoalesce(const DataflowGraph& dataflow_graph,\n                                                     std::vector<CandidatePartition> candidates);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CandidatePartition, ObjectRef, CandidatePartitionNode);\n  TVM_DEFINE_OBJECT_REF_COW_METHOD(CandidatePartitionNode);\n};\n\nCandidatePartition WithRuleName(CandidatePartition candidate, String rule_name);\nCandidatePartition WithTarget(CandidatePartition candidate, Target target);\nCandidatePartition WithSubGraph(CandidatePartition candidate, SubGraph sub_graph);\n\nstruct CandidatePartitionHash {\n  size_t operator()(const CandidatePartition& candidate) const {\n    return candidate->sub_graph_->hash();\n  }\n};\n\nstruct CandidatePartitionEquals {\n  bool operator()(const CandidatePartition& left, const CandidatePartition& right) const {\n    return *left->sub_graph_.get() == *right->sub_graph_.get();\n  }\n};\n\nstruct CandidatePartitionCompare {\n  bool operator()(const CandidatePartition& left, const CandidatePartition& right) const {\n    return *left->sub_graph_.get() < *right->sub_graph_.get();\n  }\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/candidate_partition_index.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/collage/candidate_partition_index.h\n * \\brief Index for finding relevant candidate partitions for a particular search state.\n */\n#ifndef TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_INDEX_H_\n#define TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_INDEX_H_\n\n#include <tvm/relay/expr.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"./partition_spec.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Collects and indexes all the candidate partitions for the overall expression. This index\n * is used during partitioning search to find the next valid candidate partition to explore from the\n * current search state. We do not yet attempt to estimate the cost of each candidate partition, and\n * when we do so during the search we may discover it to be infeasible.\n */\nclass CandidatePartitionIndex {\n public:\n  CandidatePartitionIndex(const std::unordered_map<const ExprNode*, VirtualDevice>* virtual_devices,\n                          DataflowGraph* dataflow_graph);\n\n  /*! \\brief Constructs the index. */\n  void Index(const Array<PartitionSpec>& partition_specs);\n\n  /*! \\brief Returns all the candidates which may begin at \\p index. */\n  const std::vector<CandidatePartition>& candidates_at(PostDfsIndex index) const {\n    ICHECK_LT(index, dataflow_graph_->size());\n    return first_inside_index_to_candidates_[index];\n  }\n\n  /*! \\brief Estimates the casts of all candidates in the index. Each candidate caches its cost. */\n  void EstimateAllCosts(const CostEstimator cost_estimator,\n                        const std::shared_ptr<CandidateFunctionCache>& cache);\n\n  size_t size() const { return size_; }\n\n  std::string ToSummary() const;\n\n private:\n  /*!\n   * \\brief Returns true if \\p candidate's desired target is compatible with any existing target\n   * constraints on the candidate's sub-expressions.\n   */\n  bool IsCompatibleWithVirtualDevice(const CandidatePartition& candidate);\n\n  /*! \\brief Returns all valid candidates found from \\p partition_specs. */\n  std::vector<CandidatePartition> Collect(const Array<PartitionSpec>& partition_specs);\n\n  /*!\n   * \\brief The \\p VirtualDevice for every sub-expression in the overall expression. Needed to\n   * ensure candidates do not contradict the target/device placement already determined by\n   * device planning.\n   */\n  const std::unordered_map<const ExprNode*, VirtualDevice>* virtual_devices_;\n\n  /*! \\brief Dataflow graph for overall expression. */\n  DataflowGraph* dataflow_graph_;\n\n  /*!\n   * \\brief Maps post-dfs indexes to the all the candidates which have that as their first inside\n   * index, and which should be considered in the Collage search.\n   */\n  std::vector<std::vector<CandidatePartition>> first_inside_index_to_candidates_;\n\n  /*! \\brief Number of entries in above. */\n  size_t size_ = 0;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_CANDIDATE_PARTITION_INDEX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/candidate_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/candidate_set.h\n * \\brief Collects a set of candidate partitions.\n */\n\n#ifndef TVM_RELAY_COLLAGE_CANDIDATE_SET_H_\n#define TVM_RELAY_COLLAGE_CANDIDATE_SET_H_\n\n#include <algorithm>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"./candidate_partition.h\"\n#include \"./dataflow_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Holds a vector of current candidates and the additions/removals to apply to them.\n */\nstruct CandidateSet {\n  CandidateSet() = default;\n\n  explicit CandidateSet(std::vector<CandidatePartition> candidates_to_add);\n\n  /*!\n   * \\brief Schedule \\p new_candidate for addition before the next round (unless it is not valid).\n   */\n  void Add(const DataflowGraph& dataflow_graph, const CandidatePartition& new_candidate);\n\n  /*! \\brief Schedule \\p old_candidate for removal before the next round. */\n  void Remove(const CandidatePartition& old_candidate);\n\n  /*!\n   * \\brief Update \\p current_candidates and \\p first_new_index. Return false if no\n   * new candidates were added, in which case we have reached a fixed point.\n   */\n  bool PrepareForNextRound();\n\n  size_t size() const { return current_candidates_.size(); }\n\n  CandidatePartition operator[](size_t i) const {\n    ICHECK_LT(i, current_candidates_.size());\n    return current_candidates_[i];\n  }\n  CandidatePartition at(size_t i) const { return (*this)[i]; }\n\n  size_t first_new_index() const { return first_new_index_; }\n\n  void sort() { std::sort(current_candidates_.begin(), current_candidates_.end()); }\n\n  std::vector<CandidatePartition> MovedCurrentCandidates() {\n    return std::move(current_candidates_);\n  }\n\n private:\n  /*!\n   * \\brief Index of first candidate in current_candidates added in last round. This can be used to\n   * avoid considering candidates or candidate combinations which have already been considered in an\n   * earlier round.\n   */\n  size_t first_new_index_ = 0;\n  /*! \\brief Candidates gathered in previous rounds. */\n  std::vector<CandidatePartition> current_candidates_;\n  /*! \\brief New candidates gathered in the current round. */\n  std::vector<CandidatePartition> candidates_to_add_;\n  /*! \\brief Existing candidates to remove before starting the next round. */\n  std::vector<CandidatePartition> candidates_to_remove_;\n  /*! \\brief Which candidates have been seen so far and should not be added again. */\n  std::unordered_set<CandidatePartition, CandidatePartitionHash, CandidatePartitionEquals> seen_;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_CANDIDATE_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/collage_partitioner.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/collage/collage_partitioner.h\n * \\brief Search for an optimal partitioning of a Relay model.\n *\n * See:\n *   Collage: Automated Integration of Deep Learning Backends\n *   Byungsoo Jeon, Sunghyun Park, Peiyuan Liao, Sheng Xu, Tianqi Chen, Zhihao Jia\n *   https://arxiv.org/pdf/2111.00655.pdf\n */\n#ifndef TVM_RELAY_COLLAGE_COLLAGE_PARTITIONER_H_\n#define TVM_RELAY_COLLAGE_COLLAGE_PARTITIONER_H_\n\n#include <tvm/relay/transform.h>\n\n#include \"./cost_estimator.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Explores the space of all possible (sub-graph, target) pairs which cover the\n * model, and applies the globally optimal choice (assuming partition costs are additive).\n */\ntransform::Pass CollagePartition(CompilationConfig config, CostEstimator cost_estimator);\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_COLLAGE_PARTITIONER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/combiner_rule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/combiner_rule.h\n * \\brief Helpers for the \\p CombinePartitionRule\n */\n\n#ifndef TVM_RELAY_COLLAGE_COMBINER_RULE_H_\n#define TVM_RELAY_COLLAGE_COMBINER_RULE_H_\n\n#include <tvm/relay/dataflow_pattern.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n\n#include \"./candidate_partition.h\"\n#include \"./candidate_set.h\"\n#include \"./sub_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Base class for all 'simple' combiner rules.\n *\n * Given \\p upstream and \\p downstream candidates which touch, a simple combiner rule returns\n * true if their union should also be considered a candidate.\n */\nclass SimpleCombinerRuleNode : public Object {\n public:\n  String rule_name_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  virtual bool Fires(const DataflowGraph& dataflow_graph, const CandidatePartition& upstream,\n                     const CandidatePartition& downstream) const;\n\n  virtual std::string ToString() const;\n\n  static constexpr const char* _type_key = \"relay.collage.SimpleCombinerRule\";\n  static constexpr const uint32_t _type_child_slots = 1;\n  TVM_DECLARE_BASE_OBJECT_INFO(SimpleCombinerRuleNode, Object);\n};\n\nclass SimpleCombinerRule : public ObjectRef {\n public:\n  explicit SimpleCombinerRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SimpleCombinerRule, ObjectRef, SimpleCombinerRuleNode);\n};\n\n/*!\n * \\brief A simple combiner rule which fires if the \\p upstream and \\p downstream candidates have\n * the given \\p upstream_kind and \\p downstream_kind (or less) respectively.\n */\nclass ByKindSimpleCombinerRuleNode : public SimpleCombinerRuleNode {\n public:\n  OpPatternKind upstream_kind_;\n  OpPatternKind downstream_kind_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  bool Fires(const DataflowGraph& dataflow_graph, const CandidatePartition& upstream,\n             const CandidatePartition& downstream) const override;\n  std::string ToString() const override;\n\n  static constexpr const char* _type_key = \"relay.collage.ByKindSimpleCombinerRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ByKindSimpleCombinerRuleNode, SimpleCombinerRuleNode);\n};\n\nclass ByKindSimpleCombinerRule : public SimpleCombinerRule {\n public:\n  ByKindSimpleCombinerRule(OpPatternKind upstream_kind, OpPatternKind downstream_kind);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ByKindSimpleCombinerRule, SimpleCombinerRule,\n                                ByKindSimpleCombinerRuleNode);\n};\n\n/*! \\brief Context required by CombineRuleNode::AppendAllResultsContext. */\nstruct AppendAllResultsContext {\n  AppendAllResultsContext(const DataflowGraph* dataflow_graph, size_t max_depth,\n                          CandidateSet* candidate_set)\n      : dataflow_graph(dataflow_graph), max_depth(max_depth), candidate_set(candidate_set) {}\n\n  const DataflowGraph* dataflow_graph;\n  size_t max_depth;\n  CandidateSet* candidate_set;\n};\n\n/*!\n * \\brief Base class for all 'combiner' rules.\n *\n * Given the current candidate set, a combiner rule looks for opportunities to form larger\n * candidates, optionally removing existing candidates in the process.\n */\nclass CombinerRuleNode : public Object {\n public:\n  String rule_name_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  virtual void AppendAllResults(AppendAllResultsContext* ctxt) const;\n  virtual std::string ToString() const;\n\n  static constexpr const char* _type_key = \"relay.collage.CombinerRule\";\n  static constexpr const uint32_t _type_child_slots = 4;\n  TVM_DECLARE_BASE_OBJECT_INFO(CombinerRuleNode, Object);\n};\n\nclass CombinerRule : public ObjectRef {\n public:\n  explicit CombinerRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CombinerRule, ObjectRef, CombinerRuleNode);\n};\n\n/*!\n * \\brief A combiner rule which runs one or more simple combiner rules over the current\n * touching candidates.\n */\nclass AllSimpleCombinerRuleNode : public CombinerRuleNode {\n public:\n  Array<SimpleCombinerRule> simple_rules_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  void AppendAllResults(AppendAllResultsContext* ctxt) const override;\n  std::string ToString() const override;\n\n  static constexpr const char* _type_key = \"relay.collage.AllSimpleCombinerRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AllSimpleCombinerRuleNode, CombinerRuleNode);\n};\n\nclass AllSimpleCombinerRule : public CombinerRule {\n public:\n  AllSimpleCombinerRule(String rule_name, Array<SimpleCombinerRule> simple_rules);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(AllSimpleCombinerRule, CombinerRule, AllSimpleCombinerRuleNode);\n};\n\n/*!\n * \\brief A combiner rule which combines injective sub-groups which appear inside tuples which are\n * themselves inputs to injective sub-groups.\n */\nclass TupleArgCombinerRuleNode : public CombinerRuleNode {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  void AppendAllResults(AppendAllResultsContext* ctxt) const override;\n  std::string ToString() const override;\n\n  static constexpr const char* _type_key = \"relay.collage.TupleArgCombinerRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleArgCombinerRuleNode, CombinerRuleNode);\n};\n\nclass TupleArgCombinerRule : public CombinerRule {\n public:\n  explicit TupleArgCombinerRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleArgCombinerRule, CombinerRule, TupleArgCombinerRuleNode);\n};\n\n/*!\n * \\brief A combiner rule which combines tuple projection if it's an output of an injective\n * group.\n */\nclass TupleProjCombinerRuleNode : public CombinerRuleNode {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  void AppendAllResults(AppendAllResultsContext* ctxt) const override;\n  std::string ToString() const override;\n\n  static constexpr const char* _type_key = \"relay.collage.TupleProjCombinerRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TupleProjCombinerRuleNode, CombinerRuleNode);\n};\n\nclass TupleProjCombinerRule : public CombinerRule {\n public:\n  explicit TupleProjCombinerRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(TupleProjCombinerRule, CombinerRule, TupleProjCombinerRuleNode);\n};\n\n/*!\n * \\brief A combiner rule which combines constants in argument positions to existing candidates.\n * Note that scalars are always inlined, so this rule only combines tensor constant arguments.\n */\nclass ConstantCombinerRuleNode : public CombinerRuleNode {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  void AppendAllResults(AppendAllResultsContext* ctxt) const override;\n  std::string ToString() const override;\n\n  static constexpr const char* _type_key = \"relay.collage.ConstantCombinerRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(ConstantCombinerRuleNode, CombinerRuleNode);\n};\n\nclass ConstantCombinerRule : public CombinerRule {\n public:\n  explicit ConstantCombinerRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(ConstantCombinerRule, CombinerRule, ConstantCombinerRuleNode);\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_COMBINER_RULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/cost.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/cost.h\n * \\brief Represents the estimated cost of a candidate partition.\n */\n#ifndef TVM_RELAY_COLLAGE_COST_H_\n#define TVM_RELAY_COLLAGE_COST_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <cmath>\n#include <limits>\n#include <string>\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief The assumed cost for a candidate partition. Generally average execution time in seconds.\n * However other cost functions are possible, for example to introduce a penalty for high memory\n * use, etc.\n */\nclass Cost {\n public:\n  Cost() = delete;\n\n  static Cost Zero() { return Cost(0.0); }\n\n  /*!\n   * \\brief Returns the distinguished 'invalid' cost signaling a candidate partition is not\n   * supported by the intended target, for example because the sub-graph has an unsupported operator\n   * or the intermediate memory required exceeds some system limit.\n   */\n  static Cost Invalid() { return Cost(std::numeric_limits<double>::infinity()); }\n\n  bool is_invalid() const { return std::isinf(value_) && value_ > 0.0; }\n\n  /*!\n   * \\brief Returns the distinguished 'unknown' cost, signaling fixed priorities should be used to\n   * choose the best partitions. This can be used to disable tuning and fallback to fixed rules,\n   * much as TVM will use an un-tuned kernel if no tuning records are available.\n   */\n  static Cost Unknown() { return Cost(std::numeric_limits<double>::quiet_NaN()); }\n\n  bool is_unknown() const { return std::isnan(value_); }\n\n  /*! \\brief Returns cost with given finite, non-negative value. */\n  static Cost Value(double value) {\n    ICHECK(!std::isnan(value) && !std::isinf(value) && value >= 0.0);\n    return Cost(value);\n  }\n\n  bool is_value() const { return !std::isnan(value_) && !std::isinf(value_); }\n\n  double value() const {\n    ICHECK(is_value());\n    return value_;\n  }\n\n  /*! \\brief Return true if the less-than relation is defined for this and that. */\n  bool are_comparable(Cost that) const { return !std::isnan(value_) && !std::isnan(that.value_); }\n\n  /*! \\brief Returns sum of this and that. */\n  Cost operator+(Cost that) const { return Cost(value_ + that.value_); }\n\n  /*! \\brief Returns difference of this and that. */\n  Cost operator-(Cost that) const { return Cost(value_ - that.value_); }\n\n  /*! \\brief Returns true if this is cheaper than that, assuming they are comparable. */\n  bool operator<(Cost that) const { return value_ < that.value_; }\n\n  std::string ToString() const;\n\n private:\n  explicit Cost(double value) : value_(value) {}\n\n  /*!\n   * \\brief Non-negative value or:\n   *   - +inf if candidate partition is not feasible.\n   *   - NaN if candidate partition has an unknown cost (priority may be used to break ties).\n   */\n  double value_ = 0.0;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_COST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/cost_estimator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/cost_estimator.cc\n * \\brief Interface for measuring candidate partition cost.\n */\n\n#ifndef TVM_RELAY_COLLAGE_COST_ESTIMATOR_H_\n#define TVM_RELAY_COLLAGE_COST_ESTIMATOR_H_\n\n#include <tvm/relay/function.h>\n\n#include \"./cost.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief An (abstract) estimator for the cost of executing \"main\" in an \\p IRModule representing\n * a candidate partition, using the given target for lowering and codegen.\n *\n * Generally the implementation will compile to a \\p runtime::Module (possibly on a target-specific\n * worker if cross-compilation is not available), repeatedly invoke \"main\" with random data until\n * measure variance is acceptable (on a target-specific worker), and return the summarized costs.\n *\n * If using a TVM native \\p Target, it is possible compilation will itself invoke TVM tuning.\n *\n * TODO(mbs): Actually, currently not abstract so can get some local measurements.\n */\nclass CostEstimatorNode : public Object {\n public:\n  /*!\n   * \\brief Returns the estimated cost (possibly after many many minutes of training time) of\n   * running \"main\" in \\p mod using \\p target, which represents a possible partitioning of\n   * some overall Relay expression.\n   */\n  virtual Cost Estimate(const IRModule& mod, const Target& target) const;\n\n  static constexpr const char* _type_key = \"relay.collage.CostEstimator\";\n  TVM_DECLARE_BASE_OBJECT_INFO(CostEstimatorNode, Object);\n};\n\nclass CostEstimator : public ObjectRef {\n public:\n  CostEstimator();\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(CostEstimator, ObjectRef, CostEstimatorNode);\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_COST_ESTIMATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/dataflow_graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/dataflow_graph.h\n * \\brief A representation of the dataflow for an overall Relay expression.\n */\n#ifndef TVM_RELAY_COLLAGE_DATAFLOW_GRAPH_H_\n#define TVM_RELAY_COLLAGE_DATAFLOW_GRAPH_H_\n\n#include <tvm/relay/expr.h>\n\n#include <memory>\n#include <vector>\n\n#include \"../ir/indexed_graph.h\"\n#include \"./index_set.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Represents the dataflow of an overall Relay expression.\n */\nclass DataflowGraph {\n public:\n  using Node = IndexedGraph<Expr>::Node;\n\n  explicit DataflowGraph(Expr expr);\n\n  size_t size() const { return indexed_graph_->size(); }\n  const Node* index_to_node(PostDfsIndex index) const {\n    return indexed_graph_->index_to_node(index);\n  }\n  const Node* item_to_node(const Expr& expr) const { return indexed_graph_->item_to_node(expr); }\n  const Node* item_to_node(const ExprNode* expr_node) const {\n    return indexed_graph_->item_to_node(expr_node);\n  }\n  const Expr& expr() const { return expr_; }\n  const IndexedGraph<Expr>& indexed_graph() const { return *indexed_graph_; }\n\n  const IndexSet& downstream_of(PostDfsIndex index) const {\n    ICHECK_LT(index, indexed_graph_->size());\n    return downstream_map_[index];\n  }\n\n private:\n  /*! \\brief The overall expression. */\n  Expr expr_;\n  /*! \\brief The indexed graph which captures the main dataflow. */\n  std::unique_ptr<IndexedGraph<Expr>> indexed_graph_;\n  /*! \\brief Map from a node's PostDfsIndex to the set of its downstream dataflow node indexes. */\n  std::vector<IndexSet> downstream_map_;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_DATAFLOW_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/gather_partition_specs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/gather_partition_specs.h\n * \\brief Gather the relevant \\p PartitionSpecs from the available \\p Targets.\n */\n#ifndef TVM_RELAY_COLLAGE_GATHER_PARTITION_SPECS_H_\n#define TVM_RELAY_COLLAGE_GATHER_PARTITION_SPECS_H_\n\n#include <tvm/target/compilation_config.h>\n\n#include \"./partition_spec.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief The 'styles' of BYOC integrations. Used to influence how their corresponding\n * partition rule is constructed.\n */\nenum BYOCStyle {\n  /*!\n   * \\brief The BYOC patterns pick out 'ideal' candidates directly, either because:\n   *  - the BYOC toolchain does not perform any fusion so each matched sub-expression maps 1:1 to a\n   *    BYOC-provided operator, or\n   *  - the BYOC toolchain does perform fusion, however the patterns have been written to pick out\n   *    fusable sub-graphs.\n   */\n  kNoFusionBYOCStyle,\n\n  /*!\n   * \\brief The BYOC patterns pick out supported operators, but the BYOC backend may perform\n   * fusion over those operators in much the same way TVM does.\n   */\n  kTVMFusionBYOCStyle,\n\n  /*!\n   * \\brief The BYOC patterns pick out supported operators, but the BYOC backend may perform\n   * arbitrary fusion over those operators.\n   */\n  kArbitraryFusionBYOCStyle,\n};\n\n/*!\n * \\brief Returns all the partition specifications gathered from the \\p Targets in \\p config.\n */\nArray<PartitionSpec> GatherPartitionSpecs(const CompilationConfig& config);\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_GATHER_PARTITION_SPECS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/index_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/index_set.h\n * \\brief Efficient representation of a set of post-dfs indexes.\n */\n\n#ifndef TVM_RELAY_COLLAGE_INDEX_SET_H_\n#define TVM_RELAY_COLLAGE_INDEX_SET_H_\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../ir/dataflow_matcher_impl.h\"\n#include \"../ir/indexed_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\nusing IndexSubst = std::unordered_map<size_t, size_t>;\n\nclass IndexSet {\n public:\n  IndexSet() = default;\n  explicit IndexSet(size_t size) : bitvec_(size, false) {}\n  IndexSet(size_t size, const std::vector<size_t>& indexes);\n\n  IndexSet operator&(const IndexSet& that) const;\n  IndexSet operator|(const IndexSet& that) const;\n  IndexSet operator-(const IndexSet& that) const;\n  bool AreDisjoint(const IndexSet& that) const;\n  bool IsSubset(const IndexSet& that) const;\n  bool Intersects(const IndexSet& that) const;\n\n  bool operator[](size_t index) const {\n    ICHECK_LT(index, bitvec_.size());\n    return bitvec_[index];\n  }\n\n  IndexSet& Add(size_t index) {\n    ICHECK_LT(index, bitvec_.size());\n    bitvec_[index] = true;\n    return *this;\n  }\n\n  IndexSet Subst(size_t new_size, const IndexSubst& subst) const;\n\n  size_t end_index() const { return bitvec_.size(); }\n  size_t PopCount() const;\n  bool IsZero() const;\n  size_t FirstInsideIndex() const;\n  size_t LastInsideIndex() const;\n  size_t NextIndex(size_t index) const;\n  size_t FirstOutsideIndex() const;\n  bool operator==(const IndexSet& that) const;\n  bool operator!=(const IndexSet& that) const;\n  bool operator<(const IndexSet& that) const;\n  size_t hash() const;\n  std::string ToString() const;\n\n  struct IndexSetIterator {\n    const IndexSet* set;\n    size_t i;\n\n    size_t operator*() const {\n      ICHECK_LT(i, set->end_index());\n      return i;\n    }\n\n    const IndexSetIterator& operator++() {\n      ICHECK_LT(i, set->end_index());\n      i = set->NextIndex(i);\n      return *this;\n    }\n\n    bool operator==(const IndexSetIterator& that) const {\n      ICHECK(set == that.set);\n      return i == that.i;\n    }\n\n    bool operator!=(const IndexSetIterator& that) const {\n      ICHECK(set == that.set);\n      return i != that.i;\n    }\n  };\n\n  IndexSetIterator begin() const { return IndexSetIterator{this, FirstInsideIndex()}; }\n  IndexSetIterator end() const { return IndexSetIterator{this, end_index()}; }\n\n private:\n  explicit IndexSet(std::vector<bool> bitvec) : bitvec_(std::move(bitvec)) {}\n\n  std::vector<bool> bitvec_;\n};\n\nstruct IndexSetEqual {\n  bool operator()(const IndexSet& left, const IndexSet& right) const { return left == right; }\n};\n\nstruct IndexSetHash {\n  size_t operator()(const IndexSet& set) const { return set.hash(); }\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_INDEX_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/mock_cost_estimator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/mock_cost_estimator.cc\n * \\brief A mock CostEstimator to support unit tests.\n */\n\n#ifndef TVM_RELAY_COLLAGE_MOCK_COST_ESTIMATOR_H_\n#define TVM_RELAY_COLLAGE_MOCK_COST_ESTIMATOR_H_\n\n#include <tvm/relay/function.h>\n\n#include \"./cost.h\"\n#include \"./cost_estimator.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n// Clang (15.0.3, at least) validly complains about `@main`, but it invalidly\n// complains even about `\\c @main`.\n#if __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation-unknown-command\"\n#endif\n\n/*!\n * \\brief A mock cost estimator which can determine the cost of a candidate based on both\n * the candidate's target and the number of operator calls inside it.\n *\n * The help unit tests the estimator also ICHECK fails if:\n *  - the module has inlined \"Compiler\" functions\n *  - @main has non-tensor arguments (eg a tuple)\n *  - more than the given number of candidate modules are measured\n *\n * To support unit testing only.\n */\nclass MockCostEstimatorNode : public CostEstimatorNode {\n public:\n  Cost Estimate(const IRModule& mod, const Target& target) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.MockCostEstimator\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(MockCostEstimatorNode, CostEstimatorNode);\n\n protected:\n  /*!\n   * \\brief Map from target kind name to assumed baseline cost (in integer seconds) for all\n   * operator calls.\n   */\n  Map<String, Integer> target_costs_;\n\n  /*!\n   * \\brief If non-zero, the maximum number of distinct modules which may be estimated.\n   */\n  Integer max_estimates_;\n\n  /*! \\brief Number of calls to Estimate. */\n  mutable size_t num_estimates_ = 0;\n\n  friend class MockCostEstimator;\n};\n#if __clang__\n#pragma clang diagnostic pop\n#endif\n\nclass MockCostEstimator : public CostEstimator {\n public:\n  explicit MockCostEstimator(Map<String, Integer> target_costs, Integer max_estimates = 0);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(MockCostEstimator, CostEstimator, MockCostEstimatorNode);\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_MOCK_COST_ESTIMATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/name_supply.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/name_supply.h\n * \\brief A source of fresh variable names.\n */\n\n#ifndef TVM_RELAY_COLLAGE_NAME_SUPPLY_H_\n#define TVM_RELAY_COLLAGE_NAME_SUPPLY_H_\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*! \\brief A supply of fresh names. */\nclass NameSupply {\n public:\n  explicit NameSupply(std::string prefix) : prefix_(std::move(prefix)) {}\n\n  NameSupply MakeSubNameSupply();\n\n  void Reserve(const std::string& existing) { next_free_index_.emplace(existing, 1); }\n\n  std::string Fresh(const std::initializer_list<std::string>& hints);\n\n private:\n  /*! \\brief Prefix for all names. May be empty. */\n  std::string prefix_;\n  /*! \\brief Next unused index for variables with given basename. */\n  std::unordered_map<std::string, int> next_free_index_;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_NAME_SUPPLY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/partition_rule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/partition_rule.h\n * \\brief Compositional partitioning rules.\n */\n\n#ifndef TVM_RELAY_COLLAGE_PARTITION_RULE_H_\n#define TVM_RELAY_COLLAGE_PARTITION_RULE_H_\n\n#include <tvm/relay/dataflow_pattern.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n#include <vector>\n\n#include \"../../printer/doc.h\"\n#include \"./candidate_partition.h\"\n#include \"./combiner_rule.h\"\n#include \"./sub_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Type of function to check if a matched sub-expression should be accepted by a rule. This\n * can be used to, eg, reject operators of unsupported shape or dtype, or otherwise implement rules\n * which are difficult to express in the dataflow pattern language directly.\n */\nusing TPatternPredicate = TypedPackedFunc<bool(const Expr& matched_sub_expr)>;\n\n/*!\n * \\brief The default pattern predicate. Always returns true.\n */\nbool DefaultPatternPredicate(const Expr& matched_sub_expr);\n\n/*!\n * \\brief Base class of all partition rules.\n *\n * A \\p PartitionRule describes how to find a set of \\p CandidatePartitions for a \\p DataflowGraph.\n * The candidates are allowed to overlap, and ultimately it is the job of the Collage searcher to\n * find a selection of candidates which covers the whole Relay expression without overlap. Partition\n * rules are paired with their \\p Target and other 'top level' configuration in a \\p PartitionSpec.\n *\n * We provide a set of 'base' partition rules which produce candidates from the dataflow graph\n * directly. We also provide a set of 'combinator' partition rules which can produce new candidates\n * from the results of an arbitrary sub-rule or sub-rules. By mixing these base and combinator\n * rules we can express a wide variety of partition strategies and encoding conventions.\n *\n * There may be many thousands of candidates in flight during the Collage search. We take care to\n * defer constructing or rewriting Relay expressions until absolutely necessary. We only pay for\n * extracting a function to represent a candidate when we need to measure it's cost. And we only\n * pay for rewriting the overall Relay expression to commit to a partitioning when the Collage\n * search has completed.\n *\n * The base rules implemented so far:\n *  - \\p DFPatternPartitionRule: Given a \\p DFPattern and expression predicate, produces a candidate\n *    for every sub-graph matched by the pattern and predicate. Unlike the \\p PatternRewriter,\n *    candidates are free to overlap. Used to bring BYOC patterns into the Collage framework.\n *  - \\p OpCallByKindPartitionRule: Uses the \"TOpPattern\" attribute provided for every Relay\n *    operator to produce a candidate for every call to a 'fusable Relay operator'. Used to\n *    look ahead to how TVM will fuse sub-graphs.\n *\n * The combinator rules implemented so far:\n *  - \\p CompositePartitionRule: Indicates all candidates matched by the sub-rule should be wrapped\n *    by a \"Composite\" function. The \"Composite\" name is taken from the rule name. Used to indicate\n *    Relay operators (or groups of Relay operators) should be mapped to target-specific operators,\n *    both for BYOC and TVM external library integrations.\n *  - \\p PrimitivePartitionRule: Indicates all candidates matched by the sub-rule should be wrapped\n *    by a \"Primitive\" function, possibly with an additional \"Compiler\" attribute. Used to\n *    delineate a partition (or kernel).\n *  - \\p UnionPartitionRule: Simply unions all the candidates from all sub-rules together. Used to\n *    combine individual \\p DFPatternPartitionRules.\n *  - \\p CombinePartitionRule: Given a sub-rule and a list of 'combiner' rules, finds\n *    all possible ways of combining the sub-rule's candidates to yield even larger candidates.\n *    Note that the sub-rule's candidates may also be directly included in the results. The\n *    'combiner' rules allow combining by \\p OpPatternKinds, combining the arguments to tuples\n *    which themselves are arguments to Relay operator calls, and so on. This rule is intended to\n *    mimic the existing TVM \\p FuseOps pass, though:\n *    i) all candidates are found rather than just the largest, ii) the starting set of candidates\n *    can be provided by any other rule, and iii) we rely on \\p SubGraph validity checking to weed\n *    out infeasible candidates.\n *  - \\p OnlyValidPartitionRule: Given a \\p SubGraphConfig, ignores candidates with 'invalid'\n *    sub-graphs. Used to limit the maximum candidate depth, the number of independent outputs,\n *    and whether intermediate 'taps' are allowed.\n *  - \\p HostPartitionRule: Produces candidates for all Relay expressions which could be\n *    'left behind' for execution by the host (eg on the VM). This rule lets us simplify the\n *    overall Collage search algorithm.\n *\n * (Though not yet implemented, we'd like to allow a combinator rule which will union candidate\n * based on their 'anchor' operators. This can be used to implement 'vertical' and 'horizontal'\n * partition on more primitive candidates. Note that the \\p SubGraph machinery supports\n * multiple-input and -output sub-graphs and their validation, so horizontal partition is easy\n * implement.)\n *\n * Here are some typical ways to combine \\p PartitionRules for different partition/fusion\n * strategies:\n *\n *  - Classic pattern-based BYOC with \\p MergeComposite/AnnotateTarget/PartitionGraph passes:\n *    \\code\n *    PrimitivePartitionRule\n *      OnlyValidPartitionRule\n *        CombinePartitionRule (with join-anything combiner rule)\n *          UnionPartitionRule\n *            CompositePartitionRule(label1)\n *              DFPatternPartitionRule(pattern1)\n *                        :\n *            CompositePartitionRule(labeln)\n *              DFPatternPartitionRule(patternn)\n *    \\endcode\n *\n *  - \"Consider this library implementation for these sub-expressions\", using \\p DFPatterns to\n *    pick out which Relay operators are supported:\n *    \\code\n *    OnlyValidPartitionRule\n *      CombinePartitionRule (with default TVM combiner rules)\n *        UnionPartitionRule\n *          OpCallByKindPartitionRule\n *          CompositePartitionRule(lable1)\n *            DFPatternPartitionRule(pattern1)\n *                       :\n *          CompositePartitionRule(lablen)\n *            DFPatternPartitionRule(patternn)\n *    \\endcode\n *\n *  - Classic TVM \\p FuseOps\n *    \\code\n *    PrimitivePartitionRule\n *      OnlyValidPartitionRule\n *        CombinePartitionRule (with default TVM combiner rules)\n *          OpCallByKindPartitionRule\n *    \\endcode\n *\n *  - \"Just fuse what I tell you to fuse\", using \\p DFPatterns to directly select candidates:\n *    \\code\n *    PrimitivePartitionRule\n *      OnlyValidPartitionRule\n *        UnionPartitionRule\n *          DFPatternPartitionRule(pattern1)\n *                       :\n *          DFPatternPartitionRule(patternn)\n *    \\endcode\n */\nclass PartitionRuleNode : public Object {\n public:\n  /*!\n   * \\brief A unique (over all rules for the same target) name for the rule. Rule names are\n   * combined and captured with \\p PartitionCandidate rule names for debuggability and\n   * explainability. Some rules will copy the rule name into function attributes.\n   *\n   */\n  String rule_name_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Returns all the possible candidate partitions according to this rule for the overall\n   * expression corresponding to \\p dataflow_graph. The candidates will generally have unknown\n   * target and cost: the target will be filled in by the \\p PartitionSpec, while the cost will\n   * be filled in lazily.\n   */\n  virtual std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                        const PartitionSpec& spec) const;\n\n  std::string ToString() const;\n  Doc ToDoc() const;\n\n protected:\n  virtual void AppendBodyItems(std::vector<Doc>* body_items) const;\n\n public:\n  static constexpr const char* _type_key = \"relay.collage.PartitionRule\";\n  static constexpr const uint32_t _type_child_slots = 10;\n  TVM_DECLARE_BASE_OBJECT_INFO(PartitionRuleNode, Object);\n};\n\nclass PartitionRule : public ObjectRef {\n public:\n  explicit PartitionRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PartitionRule, ObjectRef, PartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which fires on all sub-expressions matching a dataflow-pattern and pattern\n * predicate. It is valid for matching candidates to overlap.\n */\nclass DFPatternPartitionRuleNode : public PartitionRuleNode {\n public:\n  /*!\n   * \\brief Relay pattern.\n   */\n  DFPattern pattern_;\n\n  /*!\n   * \\brief Predicate on matched sub-expression to decide if partition rule should fire.\n   */\n  TPatternPredicate predicate_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.DFPatternPartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(DFPatternPartitionRuleNode, PartitionRuleNode);\n};\n\nclass DFPatternPartitionRule : public PartitionRule {\n public:\n  DFPatternPartitionRule(String rule_name, DFPattern pattern,\n                         TPatternPredicate predicate = DefaultPatternPredicate);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(DFPatternPartitionRule, PartitionRule, DFPatternPartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which wraps candidates within a function with the \"Composite\" attribute\n * bound to the given rule name.\n *\n * This is the standard way by which operators or operator groups are tagged as being supported\n * by a particular externally provided function. It is up to the BYOC lowering function to\n * recognize the \"Composite\" name and emit the appropriate code or call.\n */\nclass CompositePartitionRuleNode : public PartitionRuleNode {\n public:\n  /*! \\brief The sub-partition rule. */\n  PartitionRule sub_rule_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.CompositePartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CompositePartitionRuleNode, PartitionRuleNode);\n};\n\nclass CompositePartitionRule : public PartitionRule {\n public:\n  CompositePartitionRule(String rule_name, PartitionRule sub_rule);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CompositePartitionRule, PartitionRule, CompositePartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which wraps candidates within a function with the \"Primitive\" attribute\n * bound to 1. If the partition spec target(s) have the \"compiler\" attribute then that name is\n * also added to the function as a \"Compiler\" attribute.\n *\n * This is the standard way by which sub-graphs are marked as being in a 'partition' who's\n * compilation will be managed by an external BYOC toolchain. It can also be used to mark\n * sub-graphs for lowering to a single kernel by the built-in TVM lowering machinery.\n */\nclass PrimitivePartitionRuleNode : public PartitionRuleNode {\n public:\n  /*! \\brief The sub-partition rule. */\n  PartitionRule sub_rule_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.PrimitivePartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PrimitivePartitionRuleNode, PartitionRuleNode);\n};\n\nclass PrimitivePartitionRule : public PartitionRule {\n public:\n  PrimitivePartitionRule(String rule_name, PartitionRule sub_rule);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PrimitivePartitionRule, PartitionRule, PrimitivePartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which simply unions all matches from all sub-partition rules.\n *\n * This can be used to combine the results of a set of, eg, DFPatternPartitionRules.\n */\nclass UnionPartitionRuleNode : public PartitionRuleNode {\n public:\n  Array<PartitionRule> sub_rules_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.UnionPartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(UnionPartitionRuleNode, PartitionRuleNode);\n};\n\nclass UnionPartitionRule : public PartitionRule {\n public:\n  UnionPartitionRule(String rule_name, Array<PartitionRule> sub_rules);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(UnionPartitionRule, PartitionRule, UnionPartitionRuleNode)\n};\n\n/*\n *! \\brief Partition rule which places calls to Relay operators with a \"TOpPattern\" attribute of\n * \\p kOutEWiseFusable or less in their own singleton sub-graph. No other Relay sub-expressions\n * (such as tuples or tuple projection) are selected, and it is up to outer partition rules to\n * account for them.\n */\nclass OpCallByKindPartitionRuleNode : public PartitionRuleNode {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n  static constexpr const char* _type_key = \"relay.collage.OpCallByKindPartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpCallByKindPartitionRuleNode, PartitionRuleNode);\n};\n\nclass OpCallByKindPartitionRule : public PartitionRule {\n public:\n  explicit OpCallByKindPartitionRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(OpCallByKindPartitionRule, PartitionRule,\n                                OpCallByKindPartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which combines sub-graphs to exploit optimizations commonly available in\n * backends (including the TVM lowering backend). Those optimization rules are in turn described by\n * one or more primitive \\p CombinerRules.\n *\n * For TVM these primitive combiner rules are guided by the \\p OpPatternKind associated with every\n * sub-graph. That in turn is the maximum of the kind of each expression node in the sub-graph,\n * using the rules:\n *  - Constants are \\p kElemwise.\n *  - A call to a Relay operator has the kind of its callee.\n *  - Tuple construction and projection are injective provided all tuple fields are of tensor type.\n *  - All other sub-expressions are opaque.\n *\n * The available \\p OpPatternKinds (and our abbreviations for them) are:\n *  - E: kElemWise, eg nn.relu\n *  - B: kBroadcast, eg add\n *  - I: kInjective, eg concatenate\n *  - R: kCommReduce, eg sum\n *  - A: kOutEWiseFusable, eg nn.conv2d (often called 'anchor nodes', hence the A abbreviation)\n *  - O: kOpaque, everything else\n * (The kTuple kind is not used by this machinery.)\n *\n * Kinds are ordered as above from least- to most-constraining w.r.t. possible partition\n * opportunities. When we write a kind abbreviation below we intend it to mean that kind *or less*.\n * And when when write 'kl -> kr' we mean it to match a sub-expression of kind kr or less who's\n * dataflow inputs are all of kind kl or less.\n *\n * We can then mimic the classic \\p FuseOps TVM Pass with the following more primitive combiner\n * rules:\n *  - Sub-groups cannot have taps. In the classic \\p FuseOps pass taps are avoided by construction\n *    by always considering all node->dominator paths. Here we naively allow taps on all candidates,\n *    but reject them using SubGraph::IsValid with a SubGraphConfig with allow_taps = false.\n *  - Combine A -> B\n *  - Combine B -> R\n *  - Combine I -> I\n *  - Combine I -> tuple -> I. That is, if an I sub-graph has a tuple as input, and at least one\n *    tuple field can be provided by an I sub-graph exit, then both the tuple and all such fields\n *    may be joined.\n gt*\n * Note that \\p FuseOps only considers the largest possible sub-graphs. However this partition rule\n * considers all possibilities so as to 'make room' for other targets supplying other\n * overlapping candidates.\n *\n * See combiner_rule.h for the more primitive combiner rules which implement the above.\n */\nclass CombinePartitionRuleNode : public PartitionRuleNode {\n public:\n  /*! \\brief The sub-rule supplying the initial set of candidates. */\n  PartitionRule sub_rule_;\n  /*! \\brief The more primitive rules to use to combine the candidates found by the above rule. */\n  Array<CombinerRule> combiner_rules_;\n  /*! \\brief Maximum max_depth for candidates. */\n  size_t max_depth_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n public:\n  static constexpr const char* _type_key = \"relay.collage.CombinePartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(CombinePartitionRuleNode, PartitionRuleNode);\n};\n\nclass CombinePartitionRule : public PartitionRule {\n public:\n  CombinePartitionRule(String rule_name, PartitionRule sub_rule, Array<CombinerRule> combiner_rules,\n                       size_t max_depth_);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(CombinePartitionRule, PartitionRule, CombinePartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rules which keeps only candidates from the sub-rule whose sub-groups are valid\n * w.r.t. the given \\p SubGraphConfig.\n */\nclass OnlyValidPartitionRuleNode : public PartitionRuleNode {\n public:\n  PartitionRule sub_rule_;\n  SubGraphConfig config_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n public:\n  static constexpr const char* _type_key = \"relay.collage.OnlyValidPartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(OnlyValidPartitionRuleNode, PartitionRuleNode);\n};\n\nclass OnlyValidPartitionRule : public PartitionRule {\n public:\n  OnlyValidPartitionRule(String rule_name, PartitionRule sub_rule, const SubGraphConfig& config);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(OnlyValidPartitionRule, PartitionRule, OnlyValidPartitionRuleNode);\n};\n\n/*!\n * \\brief Partition rule which selects nodes which can be 'left behind' to be executed by the host\n * (eg on the VM). This includes most of the 'interstitial' Relay constructs, such a let bindings,\n * operators on references, calls to non-operator functions, and so on. It can also include the\n * construction of and projection from tuples which may not be supported within a partition.\n */\nclass HostPartitionRuleNode : public PartitionRuleNode {\n public:\n  void VisitAttrs(AttrVisitor* v);\n\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph,\n                                                const PartitionSpec& spec) const override;\n\n  void AppendBodyItems(std::vector<Doc>* body_items) const override;\n\n public:\n  static constexpr const char* _type_key = \"relay.collage.HostPartitionRule\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(HostPartitionRuleNode, PartitionRuleNode);\n};\n\nclass HostPartitionRule : public PartitionRule {\n public:\n  explicit HostPartitionRule(String rule_name);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(HostPartitionRule, PartitionRule, HostPartitionRuleNode);\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_PARTITION_RULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/partition_spec.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/partition_spec.h\n * \\brief Combine a \\p PartitionRule with a \\p Target.\n */\n\n#ifndef TVM_RELAY_COLLAGE_PARTITION_SPEC_H_\n#define TVM_RELAY_COLLAGE_PARTITION_SPEC_H_\n\n#include <tvm/relay/function.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/target/target.h>\n\n#include <string>\n#include <vector>\n\n#include \"./partition_rule.h\"\n#include \"./sub_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Type of functions for checking the validity of partitions before they proceed to lowering\n * and codegen. The argument is the function extracted from the overall expression to represent\n * the partition. The result is a non-empty error message string if the candidate should be\n * rejected.\n */\nusing TValidateSubGraphFunc = TypedPackedFunc<String(const Function& function)>;\n\n/*!\n * \\brief The default validation function. Always returns the empty string, ie no error.\n */\nString DefaultValidateSubGraphFunc(const Function& function);\n\n/*!\n * \\brief Pairs a \\p PartitionRule with one or more \\p Targets it can be used for.\n */\nclass PartitionSpecNode : public Object {\n public:\n  /*!\n   * \\brief Specification name to distinguish this spec from all others. Typically the BYOC\n   * 'compiler' name, \"tvm\", or \"host\".\n   */\n  String spec_name_;\n\n  /*!\n   * \\brief The target all candidate partitions should be compiled for.\n   *\n   * It's tempting to support multiple targets here since. Eg the partitioning rules for\n   * TVM are the same irrespective of whether the target is \"cuda\" or \"llvm\", so it would make\n   * sense to build the candidate partitions first without committing to any target, then 'stamp'\n   * them for each target as the final step.\n   *\n   * However, we want to make sure any predicate in \\p DFPatternPartitionRuleNode instances\n   * can have access to the current target instance. Eg the predicate may need to consult\n   * build-time configuration to decide what operators, shapes etc are actually supported.\n   * That implies the specific target is known when the candidate partitions are being constructed.\n   *\n   * So for now we'll just force each spec to have exactly one target.\n   */\n  Target target_;\n\n  /*!\n   * \\brief The partition rule to use to gather candidates.\n   */\n  PartitionRule rule_;\n\n  /*!\n   * \\brief The validation function to apply to each candidate's the extracted function before\n   * proceeding to lowering/codegen.\n   */\n  TValidateSubGraphFunc validate_sub_graph_func_ = DefaultValidateSubGraphFunc;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  /*!\n   * \\brief Returns all the candidate partitions found by this specification. The candidates\n   * will be for a specific target, but will not yet have an extracted function or cost.\n   */\n  std::vector<CandidatePartition> AllCandidates(const DataflowGraph& dataflow_graph) const;\n\n  std::string ToString() const;\n\n  static constexpr const char* _type_key = \"relay.collage.PartitionSpec\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(PartitionSpecNode, Object);\n};\n\nclass PartitionSpec : public ObjectRef {\n public:\n  PartitionSpec(String spec_name, Target target, PartitionRule rule,\n                TValidateSubGraphFunc validate_sub_graph_func = DefaultValidateSubGraphFunc);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(PartitionSpec, ObjectRef, PartitionSpecNode);\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_PARTITION_SPEC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/priority_queue.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/priority_queue.h\n * \\brief An updatable priority queue.\n */\n\n#ifndef TVM_RELAY_COLLAGE_PRIORITY_QUEUE_H_\n#define TVM_RELAY_COLLAGE_PRIORITY_QUEUE_H_\n\n#include <set>\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*! \\brief Priority queue of search states, ordered by increasing cost. */\ntemplate <typename T, typename CmpTPtr, typename EqTPtr>\nclass PriorityQueue {\n public:\n  PriorityQueue() = default;\n\n  /*! \\brief Pushes \\p item onto the queue. */\n  void Push(T* item) { set_.emplace(item); }\n\n  /*! \\brief Pops the item with the least cost off the queue. */\n  T* Pop() {\n    ICHECK(!set_.empty());\n    T* item = *set_.begin();\n    set_.erase(set_.begin());\n    return item;\n  }\n\n  /*! \\brief Updates the queue to account for \\p item's best cost being lowered. */\n  void Update(T* item) {\n    auto itr = std::find_if(set_.begin(), set_.end(),\n                            [item](const T* that) { return EqTPtr()(that, item); });\n    ICHECK(itr != set_.end());\n    set_.erase(itr);\n    set_.emplace(item);\n  }\n\n  bool empty() const { return set_.empty(); }\n  size_t size() const { return set_.size(); }\n\n private:\n  // TODO(mbs): Actually use a pri-queue datastructure!\n  std::set<T*, CmpTPtr> set_;\n};\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_PRIORITY_QUEUE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/prune_candidates.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/prune_candidates.h\n * \\brief Try to remove candidates which will never contribute to an optimal partitioning.\n */\n\n#ifndef TVM_RELAY_COLLAGE_PRUNE_CANDIDATES_H_\n#define TVM_RELAY_COLLAGE_PRUNE_CANDIDATES_H_\n\n#include <vector>\n\n#include \"./candidate_partition.h\"\n#include \"./dataflow_graph.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Returns \\p initial_candidates with all unnecessary candidates pruned.\n *\n * We prune according to the following two heuristics:\n * 1. Given partitions (A, target) and (B, target) then\n *    cost(A union B, target) < cost(A, target) + cost(B, target).\n *    That is, there's no use estimating the cost of small partitions when a larger partition\n *    containing them is also available. More precisely, call a partition 'maximal' if it is\n *    not contained by any other partition for the same target. Then we want to prefer maximal\n *    candidates when searching.\n * 2. Given maximal partitions (A union B, target) and (A union B, target') where\n *    target != target', then min(cost(A union B, target), cost(A union B, target')) <\n *    min(cost(A, target) + cost(B, target'), cost(A, target') + cost(B, target)).\n *    That is, there's no use estimating cross-combinations of partitions which are not maximal.\n *\n * However, we can't prune a non-maximal candidate if it will make some other maximal candidate\n * unreachable during the Collage search. We achieve this by iterating until fixed point:\n *  - Find maximal candidates of current set of candidates.\n *  - Add those maximal candidates to the output 'pruned' set.\n *  - If any two candidates in the 'pruned' set intersect without being equal, remove those from\n *    the current set of candidates and go around again. That will force more candidates to\n *    be considered 'maximal'.\n * That over-approximates the true necessary candidates but is at least simple.\n *\n * CAUTION: This is pretty experimental. The above heuristics won't always be safe, and I don't\n * have a proof the pruned candidate set won't lead to 'No candidate was found covering\n * sub-expression...' errors in Partitioner::Partition().\n */\nstd::vector<CandidatePartition> PruneCandidates(\n    const DataflowGraph& dataflow_graph, const std::vector<CandidatePartition>& initial_candidates);\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_PRUNE_CANDIDATES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/sub_graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/sub_graph.h\n * \\brief Represents a sub-graph of an overall Relay expression.\n */\n\n#ifndef TVM_RELAY_COLLAGE_SUB_GRAPH_H_\n#define TVM_RELAY_COLLAGE_SUB_GRAPH_H_\n\n#include <tvm/ir/transform.h>\n#include <tvm/relay/op_attr_types.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../ir/dataflow_matcher_impl.h\"\n#include \"../ir/indexed_graph.h\"\n#include \"./dataflow_graph.h\"\n#include \"./index_set.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*! \\brief Returns operator pattern kind as single-letter string. */\nstd::string KindToString(OpPatternKind kind);\n\n/*!\n * \\brief Returns a kind and label for the single \\p sub_expr, ignoring its nested sub expressions.\n */\nstd::pair<OpPatternKind, std::string> SubExprKindAndLabel(const Expr& sub_expr);\n\n/*!\n * \\brief Returns a kind and label for all the nodes in \\p inside.\n */\nstd::pair<OpPatternKind, std::string> SubGraphKindAndLabel(const DataflowGraph& dataflow_graph,\n                                                           const IndexSet& inside);\n\n/*!\n * \\brief Returns the index set representing all the sub-expression matched by \\p matcher.\n */\nIndexSet MatcherToIndexSet(const DFPatternMatcher& matcher);\n\n/*!\n * \\brief Configuration controlling which sub-graphs are considered valid.\n */\nstruct SubGraphConfig {\n  /*! \\brief Maximum number of exit nodes in the sub-graph, or zero if no limit. */\n  size_t max_exits = 0;\n  /*!\n   * \\brief Whether a node inside the sub-graph may flow to nodes both inside and outside\n   * the sub-graph (which we call a 'tap'). Note that it is still possible to have multiple outputs\n   * even with this flag false.\n   */\n  bool allow_taps = false;\n  /*!\n   * \\brief Maximum allowed sub-graph depth, or zero if no-limit.\n   */\n  size_t max_depth = 0;\n\n  std::string ToString() const;\n};\n\nclass SubGraph;\nusing FunctionAttrsMap = Map<String, ObjectRef>;\n\n/*!\n * \\brief A nested sub-graph is a sub-graph which is to be nested inside a function as part of some\n * enclosing sub-graph.\n *\n * Extraction yields a function with input nodes replaced by parameters and exit nodes in the\n * function result. Rewriting replaces the sub-graph with a call to that function, and all\n * outputs with (projections from) the call result.\n *\n * (Note that it's tempting to move attrs_ into \\p SubGraphNode and thus avoid this class.\n * However we found the implementation was easier to understand in this form since it makes\n * the result of \\p Extract unambiguous.)\n */\nclass NestedSubGraphNode : public Object {\n public:\n  /*! \\brief The nested sub-graph. */\n  ObjectRef /* actually SubGraph */ sub_graph_obj_;\n  /*! \\brief Attributes (possibly empty) to attach to the extracted function. */\n  FunctionAttrsMap attrs_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  SubGraph sub_graph() const;\n\n  bool operator==(const NestedSubGraphNode& that) const;\n  bool operator!=(const NestedSubGraphNode& that) const { return !(*this == that); }\n  bool operator<(const NestedSubGraphNode& that) const;\n  size_t hash() const;\n\n  std::string ToString() const;\n\n  /*!\n   * \\brief Returns the function representing this nested sub-graph within the overall expression\n   * represented by \\p dataflow_graph:\n   *  - All sub-graph inputs become parameters.\n   *  - All sub-graph outputs become function results (either directly or as a field in a tuple).\n   *  - The function has attrs_ for attributes (which may be empty).\n   *  - The function body accounts for any rewrites implied by the nested sub-graph.\n   */\n  Function Extract(const DataflowGraph& dataflow_graph) const;\n\n  /*!\n   * \\brief Returns \\p expr rewritten to encode the partitioning implied by this nested sub-graph.\n   *\n   * It is valid for \\p expr to not be the same as \\p dataflow_graph.expr(), however all nodes\n   * inside this nested sub-graph must correspond to nodes shared between \\p dataflow_graph.expr()\n   * and \\p expr. See \\p SubGraph::ParallelRewrite below.\n   */\n  Expr Rewrite(const DataflowGraph& dataflow_graph, const Expr& expr) const;\n\n  static constexpr const char* _type_key = \"relay.collage.NestedSubGraph\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(NestedSubGraphNode, Object);\n};\n\nclass NestedSubGraph : public ObjectRef {\n public:\n  NestedSubGraph(SubGraph sub_graph, FunctionAttrsMap attrs);\n\n  /*!\n   * \\brief Returns copy of this nested sub-graph with all indexes substituted according to\n   * \\p subst, whose range is w.r.t. \\p new_dataflow_graph.\n   */\n  NestedSubGraph Subst(const DataflowGraph& new_dataflow_graph,\n                       const std::unordered_map<PostDfsIndex, PostDfsIndex>& subst) const;\n\n  /*!\n   * \\brief Returns true if this can be safely unioned.\n   */\n  bool TriviallyUnionable(const NestedSubGraph& that) const;\n\n  /*!\n   * \\brief Returns the disjoint union of this and \\p that nested sub-graphs, which must agree on\n   * their attributes.\n   */\n  NestedSubGraph DisjointUnion(const DataflowGraph& dataflow_graph,\n                               const NestedSubGraph& that) const;\n\n  /*!\n   * \\brief Returns \\p expr rewritten according to all the given nested sub-graphs. The\n   * nested sub-graphs can be given in any order, but must be disjoint.\n   *\n   * It is valid for \\p expr to not be the same as \\p dataflow_graph.expr(), however all nodes\n   * inside the nested sub-graphs must correspond to nodes shared between \\p dataflow_graph.expr()\n   * and \\p expr. See \\p SubGraph::ParallelRewrite below.\n   */\n  static Expr ParallelRewrite(const DataflowGraph& dataflow_graph, const Expr& expr,\n                              std::vector<NestedSubGraph> nested_sub_graphs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(NestedSubGraph, ObjectRef, NestedSubGraphNode);\n};\n\nusing NestedSubGraphs = Array<NestedSubGraph>;\n\n/*!\n * \\brief A compact representation of a sub-graph within an (implied) overall Relay expression.\n *\n * Sub-graphs can be used to represent partitions/kernels/composite functions without having to\n * pay the cost of constructing or rewriting any expressions. We also allow 'extracting' a\n * function to use for measuring a partition/kernel's latency independently from 'rewriting'\n * the overall Relay expression since only a tiny subset of candidate partitions will end up being\n * needed after Collage has completed its search.\n *\n * We expect O(thousands) of sub-graphs to be in flight while processing a given model, so we are\n * mindful of space overhead.\n *\n * A sub-graph classifies every dataflow node of the overall expression as either 'inside' or\n * 'outside' the sub-graph. Obviously not all such divisions make sense, for example it is not\n * valid for an inside node to feed into another inside node via outside nodes. We provide the\n * \\p IsValid method to check for validity, and \\p SubGraphConfig to control which validity rules\n * apply (such as maximum depth).\n *\n * We generally work with the \\p DataflowGraph representation of the overall Relay expression\n * rather than the expression itself. We use the post-dfs visit index to uniquely refer to\n * expression nodes.\n *\n * As well as 'inside' and 'outside' we have four other flavors of dataflow nodes, all uniquely\n * determined from the 'inside' nodes:\n *  - 'entry' nodes are those inside with at least one dataflow input outside.\n *  - 'exit' nodes are  those inside with at least one dataflow output outside, or which\n *    are considered 'external' in the underlying dataflow graph (eg because they represent\n *    the result of the overall function).\n *  - 'input' nodes are those outside with at least one dataflow output inside.\n *  - 'output' nodes are those outside with at least one dataflow input inside.\n * Index sets for these are cached with the sub-graph for performance.\n *\n * It is valid to have multiple entry nodes (we can bind a parameter for each). It may be valid to\n * have multiple exit nodes (we can build a tuple of all such). It may be valid to have exit nodes\n * which also contribute to other inside nodes (ie represent a 'tap' on an intermediate result).\n *\n * Sub-graphs are closed under:\n *  - Disjoint union.\n *  - Wrapping by a function with given attributes (see \\p NestedSubGraph above). This can be used\n *    to encode \"Composite\" functions, or to represent a candidate kernel within a \"Primitive\"\n *    function. (By combining 'wrapping' with 'union' we can encode, eg, 'this sub-graph should\n *    be placed inside a primitive function which itself may have calls to composite functions).\n *  - Substitution, which allows a sub-graph w.r.t. one dataflow graph to be transformed to\n *    match some other (typically smaller) dataflow graph.\n *\n * See the subclasses of \\p PartitionRule for how sub-graphs are built and combined during Collage\n * search.\n *\n * To support some of the \\p OpPatternKind-based fusion rule processing we give sub-graphs\n * a kind, which is generally the maximum of the kinds of all the operator calls appearing\n * inside it. We also given sub-graphs a (not necessarily unique) label to help debugging\n * and guide the selection of global symbol names.\n */\nclass SubGraphNode : public Object {\n public:\n  /*!\n   * \\brief Which sub-expressions are inside the sub-graph (using their post-dfs indexes w.r.t.\n   * the implied DataflowGraph).\n   */\n  IndexSet inside_;\n\n  /*!\n   * \\brief Index of first and last inside nodes.\n   *\n   * Cached for performance, uniquely determined by inside_.\n   */\n  PostDfsIndex first_inside_index_ = 0;\n  PostDfsIndex last_inside_index_ = 0;\n\n  /*!\n   * \\brief Which sub-expressions are entry/exit/input/output for this sub-graph.\n   *\n   * Cached for performance, uniquely determined by inside_.\n   */\n  IndexSet entry_;\n  IndexSet exit_;\n  IndexSet input_;\n  IndexSet output_;\n\n  /*!\n   * \\brief Maximum depth of any dataflow path from an entry to an output sub-expression.\n   *\n   * Cached for performance, uniquely determined by inside_.\n   */\n  size_t depth_ = 0;\n\n  /*!\n   * \\brief The \\p OpPatternKind summarizing the input/output behavior of the sub-graph.\n   *\n   * A sub-graph consisting of a single Relay expression node is given kind:\n   *  - For Call to a Relay operator, the \"TOpPattern\" attribute of that operator (provided the\n   *    call does not involve data-dependent dynamic shapes).\n   *  - For Call to Relay Function, the \"TOpPattern\" attribute of the function (provided it has\n   *    that attribute)\n   *  - For Constants, \\p kElemWise.\n   *  - For Tuple and tuple projections, \\p kInjective (provided all tuple fields are of tensor\n   *    type)\n   *  - All other nodes \\p kOpaque.\n   * Sub-graphs with more than one node have the maximum of the kind of each node.\n   *\n   * Cached for performance, uniquely determined by inside_.\n   */\n  OpPatternKind kind_ = kOpaque;\n\n  /*!\n   * \\brief A label for the sub-graph. Not guaranteed to be unique, but is a human-readable summary\n   * of the sub-graph which can help with debugging and guide the selection of global symbol names.\n   */\n  String label_;\n\n  /*!\n   * \\brief Nested sub-graphs of this sub-graph which must be represented by functions. These must\n   * be disjoint, but it's ok for this sub-graph to have nodes not inside any nested sub-graph.\n   */\n  NestedSubGraphs nested_sub_graphs_;\n\n  void VisitAttrs(AttrVisitor* v);\n\n  // TODO(mbs): 'Anchor nodes' and rules for unioning them.\n  // In FuseOps it's just the unique kEWiseFusable node, if any.\n  // I'd like to allow writing vertical fusion rules, eg if two candidates are directly\n  // connected and have nn.conv2d anchors allow their join.\n  // I'd also like to allow horizontal fusion rules, eg if two candidates are not directly\n  // connected but could be joined without producing invalid (eg cyclic) and have nn.conv2d anchors\n  // then do so. Come back to this.\n\n  /*! \\brief Number of nodes in overall dataflow graph. */\n  size_t overall_size() const { return inside_.end_index(); }\n\n  bool IsEmpty() const { return inside_.IsZero(); }\n\n  /*! \\brief Number of nodes in sub-graph. */\n  size_t Size() const { return inside_.PopCount(); }\n\n  /*!\n   * \\brief Returns the dataflow nodes downstream of all exit nodes.\n   */\n  IndexSet Downstream(const DataflowGraph& dataflow_graph) const;\n\n  /*!\n   * \\brief Returns true if this sub-graph is valid. Ie:\n   *  - no output of the sub-graph can flow to any input of the sub-graph (otherwise we'd end up\n   *    with a dataflow cycle when we partition).\n   *  - all inputs and outputs of the sub-graph are in the same scope, ie not separated by\n   *    control flow (otherwise there'd be no consistent program point at which to eval the\n   *    partitioned function).\n   *  - no more than config.max_outputs outputs are required.\n   *  - if config.allow_taps is false, no inside node has outputs to nodes both inside and\n   *    outside the sub-graph.\n   */\n  bool IsValid(const DataflowGraph& dataflow_graph, const SubGraphConfig& config) const;\n\n  /*!\n   * \\brief Returns this sub-graph extracted as a stand-alone function. The function will have\n   * no attributes, and is suitable for building and profiling by the \\p CostEstimator.\n   */\n  Function ExtractAsFunction(const DataflowGraph& dataflow_graph) const;\n\n  /*!\n   * \\brief Returns \\p expr rewritten to encode the partitioning implied by this sub-graph.\n   *\n   * It is valid for \\p expr to not be the same as \\p dataflow_graph.expr(), however all nodes\n   * inside this sub-graph must correspond to nodes shared between \\p dataflow_graph.expr() and\n   * \\p expr. See \\p SubGraph::ParallelRewrite below.\n   */\n  Expr Rewrite(const DataflowGraph& dataflow_graph, const Expr& expr) const;\n\n  std::string ToString() const;\n\n  bool operator==(const SubGraphNode& that) const;\n  bool operator!=(const SubGraphNode& that) const { return !(*this == that); }\n  bool operator<(const SubGraphNode& that) const;\n  size_t hash() const;\n\n private:\n  /*! \\brief Initialize the entry/exit/input/output sets given the inside and \\p dataflow_graph. */\n  void Init(const DataflowGraph& dataflow_graph);\n\n  /*! \\brief Calculates and returns the maximum path depth. */\n  size_t Depth(const DataflowGraph& dataflow_graph) const;\n\n  /*! \\brief Returns true if any (input/output) of node is (outside/inside) the sub-graph. */\n  bool AnyInputOutside(const DataflowGraph::Node* node) const;\n  bool AnyInputInside(const DataflowGraph::Node* node) const;\n  bool AnyOutputOutside(const DataflowGraph::Node* node) const;\n  bool AnyOutputInside(const DataflowGraph::Node* node) const;\n\n public:\n  static constexpr const char* _type_key = \"relay.collage.SubGraph\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(SubGraphNode, Object);\n\n  friend class SubGraph;\n};\n\nclass SubGraph : public ObjectRef {\n public:\n  /*! \\brief Primitive constructor. The following constructors are generally more convenient. */\n  SubGraph(const DataflowGraph& dataflow_graph, IndexSet inside, OpPatternKind kind = kOpaque,\n           String label = {}, std::vector<NestedSubGraph> nested_sub_graphs = {});\n\n  /*! \\brief Constructs the empty sub-graph for \\p dataflow_graph. */\n  explicit SubGraph(const DataflowGraph& dataflow_graph);\n\n  /*! \\brief Returns true if this and that are disjoint. */\n  bool AreDisjoint(const SubGraph& that) const;\n\n  /*!\n   * \\brief Returns true if:\n   *  - \\p this and \\p that are disjoint, and\n   *  - an output node of \\p this coincides with an entry node of \\p that, and\n   *  - \\p this and \\p that are not obviously invalid after \\p DisjointUnion\n   *    (eg because such a sub-graph would produce a cycle).\n   * Note however that the \\p DisjointUnion may not necessarily be valid even with the above\n   * checks.\n   */\n  bool AreTouching(const DataflowGraph& dataflow_graph, const SubGraph& that) const;\n\n  /*!\n   * \\brief Returns true if:\n   *  - all the outputs of \\p this are entries for \\p that, and\n   *  - all the inputs of \\p that are exits for \\p this.\n   */\n  bool AreSelfContained(const SubGraph& that) const;\n\n  /*!\n   * \\brief Returns disjoint union of this and \\p that sub-graphs. The result may not be valid.\n   */\n  SubGraph DisjointUnion(const DataflowGraph& dataflow_graph, const SubGraph& that) const;\n\n  /*!\n   * \\brief Returns copy of this sub-graph with all nodes placed inside a nested sub-graph with\n   * given attributes.\n   */\n  SubGraph WithAttrs(const DataflowGraph& dataflow_graph, FunctionAttrsMap attrs) const;\n\n  /*!\n   * \\brief Returns copy of this sub-graph with all indexes substituted according to \\p subst,\n   * whose range is w.r.t. \\p new_dataflow_graph.\n   */\n  SubGraph Subst(const DataflowGraph& new_dataflow_graph,\n                 const std::unordered_map<PostDfsIndex, PostDfsIndex>& subst) const;\n\n  /*!\n   * \\brief Returns the root expression of \\p dataflow_graph rewritten according to all the\n   * given sub-graphs. The sub-graphs can be given in any order, but must be disjoint.\n   */\n  static Expr ParallelRewrite(const DataflowGraph& dataflow_graph,\n                              std::vector<SubGraph> sub_graphs);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(SubGraph, ObjectRef, SubGraphNode);\n};\n\nstruct SubGraphEqual {\n  bool operator()(const SubGraph& left, const SubGraph& right) const {\n    return *left.get() == *right.get();\n  }\n};\n\nstruct SubGraphHash {\n  size_t operator()(const SubGraph& sub_graph) const { return sub_graph->hash(); }\n};\n\n/*!\n * \\brief Pass to partition every global function according to the post-dfs indexes\n * given in an array. Visible for testing from Python only, would never make sense to use\n * as a generic pass!\n */\ntvm::transform::Pass PartitionOnIndexesForTesting(Array<Integer> indexes);\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_SUB_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/collage/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/collage/utils.h\n * \\brief Misc helpers.\n */\n\n#ifndef TVM_RELAY_COLLAGE_UTILS_H_\n#define TVM_RELAY_COLLAGE_UTILS_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/runtime/container/string.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\nnamespace collage {\n\n/*!\n * \\brief Distinguished partition spec names.\n */\nconstexpr const char* kTVMSpecNamePrefix = \"tvm_\";\nconstexpr const char* kHostSpecName = \"host\";\n\n/*!\n * \\brief Returns the partition spec name to use for \\p target. For external codegen targets the\n * spec name is just the target kind name. For TVM native targets the spec name is of the form\n * \"tvm_<kind_name>\".\n */\nString GetSpecName(const Target& target);\n\n/*! \\brief Returns \\p \"<left>+<right>\". */\nString UnionLabels(String left, String right);\n\n/*! \\brief Returns \\p \"<outer>.<inner>\". */\nString NestLabels(String outer, String inner);\n\n/*! \\brief Returns abbreviation for \\p kind. */\nstd::string KindToString(OpPatternKind kind);\n\n/*! \\brief Returns maximum of \\p left and \\p right. */\nOpPatternKind CombineKinds(OpPatternKind left, OpPatternKind right);\n\n/*!\n * \\brief Returns true if \\p expr can be safely inlined in body of function extracted\n * from sub-graph, even if \\p expr was not technically matched by the pattern which produced\n * the sub-graph.\n */\nbool CanInline(const Expr& expr);\n\n/*!\n * \\brief Returns true if \\p op_node can be directly handled by the VM.\n */\nbool IsSpecialOp(const OpNode* op_node);\n\n/*!\n * \\brief Return true if the Relay expression node given by \\p expr cannot be evaluated by\n * the VM and must end up in a kernel.\n */\nbool MustBeLowered(const Expr& expr);\n\n}  // namespace collage\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_COLLAGE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/ir/dataflow_matcher_impl.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/tvm/relay/dataflow_matcher_impl.h\n * \\brief The auxiliary data structure for dataflow matcher.\n */\n#ifndef TVM_RELAY_IR_DATAFLOW_MATCHER_IMPL_H_\n#define TVM_RELAY_IR_DATAFLOW_MATCHER_IMPL_H_\n\n#include <tvm/relay/dataflow_matcher.h>\n#include <tvm/relay/dataflow_pattern.h>\n#include <tvm/relay/dataflow_pattern_functor.h>\n#include <tvm/relay/expr_functor.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"indexed_graph.h\"\n\nnamespace tvm {\nnamespace relay {\n\nclass DFPatternMatcher : public DFPatternFunctor<bool(const DFPattern&, const Expr&)> {\n public:\n  explicit DFPatternMatcher(const IndexedGraph<Expr>* expr_graph) : expr_graph_(expr_graph) {}\n  bool Match(const DFPattern& pattern, const Expr& expr);\n  Map<DFPattern, Array<Expr>> GetMemo() { return Map<DFPattern, Array<Expr>>(memo_); }\n\n  const IndexedGraph<Expr>::Node* expr_to_node(const Expr& expr) const {\n    return expr_graph_->item_to_node(expr);\n  }\n  const IndexedGraph<Expr>::Node* index_to_node(size_t index) const {\n    return expr_graph_->index_to_node(index);\n  }\n  size_t size() const { return expr_graph_->size(); }\n  const std::unordered_map<DFPattern, Array<Expr>, ObjectPtrHash, ObjectPtrEqual>& memo() const {\n    return memo_;\n  }\n  const IndexedGraph<Expr>& expr_graph() const { return *expr_graph_; }\n\n protected:\n  bool VisitDFPattern(const DFPattern& pattern, const Expr& expr) override;\n  bool VisitDFPattern_(const AltPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const AttrPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const CallPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const ConstantPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const DataTypePatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const DominatorPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const ExprPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const FunctionPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const IfPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const LetPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const ShapePatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const TupleGetItemPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const TuplePatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const TypePatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const VarPatternNode* op, const Expr& expr) override;\n  bool VisitDFPattern_(const WildcardPatternNode* op, const Expr& expr) override;\n\n  void ClearMap(size_t watermark);\n  bool MatchesPath(const DominatorPatternNode* op, const Expr& expr);\n  bool DominatesParent(const DominatorPatternNode* op, const Expr& expr);\n\n  const IndexedGraph<Expr>* expr_graph_;\n  std::unordered_map<DFPattern, Array<Expr>, ObjectPtrHash, ObjectPtrEqual> memo_;\n  std::vector<DFPattern> matched_nodes_;\n  bool memoize_ = true;\n};\n\n/*!\n * \\brief PatternGrouper does pre-rewriting pattern matching and analysis\n *\n * This class creates a number of groups of matched expressions, ensures they don't overlap, and\n * returns them to the caller for post-analysis rewriting.\n *\n * This is primarily needed to support the post-dominator analysis required for dominator pattern\n * matching.\n */\nclass PatternGrouper {\n public:\n  /*! \\brief Internal Group class for storing analysis */\n  struct Group {\n    Expr root_node;\n    int gid;\n    Map<DFPattern, Array<Expr>> matched_nodes;\n    std::string name;\n    Function function;\n    Array<Expr> args;\n  };\n\n  /*! \\brief Return the group assignments of expressions */\n  inline const std::unordered_map<Expr, int, ObjectPtrHash, ObjectPtrEqual>& GetGIDAssignments() {\n    return gid_assignments_;\n  }\n  /*! \\brief Group expressions that match the pattern */\n  const std::unordered_map<int, Group>& GroupMatches(const DFPattern& pattern, const Expr& pre);\n\n protected:\n  /*! \\brief Iteratively traverse the Expression in pre-order to find subgraphs\n   *\n   * If we traverse the graph in post-order, we can run into situtations where a small subgraph will\n   * match the pattern. Due to options like AltPattern, a larger subgraph with more nodes later in\n   * the graph may also match the pattern. With post-order traversal, we mark the smaller subgraph\n   * as matched and fail to catch the larger subgraph. This problem is fixed by using pre-order\n   * traversal.\n   */\n  void VisitExprs();\n\n  /*! \\brief Create a group based on a matched expression */\n  void CreateGroup(const Expr& expr);\n\n  /*! \\brief EmbedConst implements rules for embedding constants into partitioned functions or\n   * lifting them into the function arguments.\n   *\n   * The rules depend on what pattern the ConstantNode matched.\n   *\n   * The basic rules are:\n   *  If the constant matches ExprPattern(relay.const(*)) or a ConstantPattern(), embed the constant\n   * in the partitioned function. If the constant matched an AltPattern, recursively check the\n   * matched side of the pattern. For any other matching pattern (i.e, wildcard, VarPattern, etc),\n   * lift the constant into the arguments of the partitioned function.\n   */\n  bool EmbedConst(const Expr& expr, const DFPattern pattern);\n  // Internal State\n  DFPattern pattern_;\n  std::unordered_map<int, Group> groups_;\n  std::unordered_map<Expr, int, ObjectPtrHash, ObjectPtrEqual> gid_assignments_;\n  DFPatternMatcher* matcher_ = nullptr;\n  std::unique_ptr<IndexedGraph<DFPattern>> pattern_graph_;\n  int gid_ = 0;\n  int graph_number_ = 0;\n};\n\n/*!\n * \\brief PatternRewriter rewrites the expression by finding matches and allowing user callback\n * function to rewrite those matches\n *\n * The class uses PatternGrouper to support the dominator pattern.\n */\nclass PatternRewriter : protected MixedModeMutator {\n public:\n  explicit PatternRewriter(IRModule mod) : mod_(mod) {}\n  /*! \\brief Rewrite can take a number of callbacks and will repeatedly rewrite the graph with the\n   * callbacks until it stops changing */\n  virtual Expr Rewrite(const Array<DFPatternCallback>& callbacks, const Expr& pre);\n\n protected:\n  virtual Expr DispatchVisitExpr(const Expr& pre);\n\n  IRModule mod_;\n  DFPatternCallback callback_;\n  std::unordered_map<int, PatternGrouper::Group> groups_;\n  std::unordered_map<Expr, int, ObjectPtrHash, ObjectPtrEqual> gid_assignments_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_IR_DATAFLOW_MATCHER_IMPL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/ir/indexed_graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/ir/indexed_graph.h\n * \\brief A graph representation of the dataflow in a Relay expression or Relay (dataflow)\n * pattern. Each 'indexed graph' node is 1:1 with an expression/pattern 'node', hence the\n * term 'IndexedGraph'. Dataflow is captured in a generic representation which is convenient\n * for analysis, particularly pattern matching and partitioning.\n *\n * TODO(mbs): Copied from fuse_ops.cc, consider refactoring to share implementation.\n */\n#ifndef TVM_RELAY_IR_INDEXED_GRAPH_H_\n#define TVM_RELAY_IR_INDEXED_GRAPH_H_\n\n#include <tvm/relay/dataflow_pattern.h>\n\n#include <memory>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief The index of a node in the post-dfs traversal of overall expression. */\nusing PostDfsIndex = size_t;\n\n/*!\n * \\brief Returns a brief summary of the 'reference' expression or pattern. Only used by\n * IndexedGraph::ToString() for debugging.\n */\nstd::string RefToSummary(const Expr& expr);\nstd::string RefToSummary(const DFPattern& pattern);\n\n/*!\n * \\brief Represents the implied dataflow of an expression or (dataflow) pattern as a DAG who's\n * nodes are 1:1 with those in the underlying expression/pattern.\n *\n * Each indexed graph node captures:\n *  - Dataflow inputs.\n *  - Dataflow outputs (or a flag indicating the node is an implied output).\n *  - Dominator parent (ie closest node at which all outputs of the current node re-combine).\n *  - Dominator children (inverse of above).\n *  - Basic block (ie node representing the body of a function, arm of an if, etc).\n *\n * This class is templated so we can analyze both DFPatterns and Exprs with the same infrastructure.\n *\n * IndexedGraph should be instantiated through the CreateIndexedGraph utilities below.\n */\ntemplate <typename T>\nclass IndexedGraph {\n public:\n  using TNode = typename T::ContainerType;\n\n  /*! \\brief A Node in the graph. */\n  struct Node {\n    /*! \\brief Node Constructor\n     *  \\param ref The expression or dataflow pattern node this indexed graph node is augmenting.\n     *  \\param index The index of this node in the topological order\n     */\n    Node(const TNode* ref, PostDfsIndex index) : node_ref_(ref), index_(index) {}\n\n    /*! \\brief The underlying expression or pattern node. */\n    const TNode* node_ref_;\n\n    T ref() const {\n      ICHECK(node_ref_ != nullptr);\n      return GetRef<T>(node_ref_);\n    }\n\n    /*!\n     * \\brief The index of this node in post-dfs order. If left.index_ > right.index_ then\n     * left does not flow into right. If left.index_ = right.index_ then left and right are\n     * the same node.\n     */\n    const PostDfsIndex index_;\n\n    /*! \\brief If true this node has implicit outputs, for example as the result of a function. */\n    bool is_external_ = false;\n    /*! \\brief Immediate dataflow inputs to this node. */\n    std::vector<Node*> inputs_;\n    /*! \\brief Immediate dataflow outputs of this node -- may be empty if is_external_ is true. */\n    std::vector<Node*> outputs_;\n\n    /*!\n     * \\brief The node representing the 'basic block' containing this node:\n     *  - Function bodies start a new basic block for their bodies.\n     *  - The true and false branches of an if start their own blocks.\n     *  - The arms of a match each have their own blocks.\n     */\n    Node* basic_block_ = nullptr;\n\n    /*! \\brief The depth of this node in the dominator tree */\n    size_t depth_ = 0;\n    /*!\n     * \\brief The dominator parent of this node. This is the node N with least index such that\n     * all possible dataflows from this node pass through N.\n     */\n    Node* dominator_parent_ = nullptr;\n    /*! \\brief The nodes this node dominates. */\n    std::vector<Node*> dominator_children_;\n\n    /*!\n     * Add to \\p nodes all the nodes which are strictly downstream of \\p this, ie can be\n     * reached by following output paths.\n     */\n    void AccumulateDownstreamNodes(std::unordered_set<const Node*>* nodes) const {\n      std::stack<const Node*> stack;\n      stack.push(this);\n      while (!stack.empty()) {\n        const Node* current = stack.top();\n        stack.pop();\n        for (auto node : current->outputs_) {\n          if (nodes->count(node) == 0) {\n            stack.push(node);\n            nodes->insert(node);\n          }\n        }\n      }\n    }\n\n    /*!\n     * \\brief Returns true if \\p this is a dominator of \\p other. Ie all dataflow paths from \\p\n     * other pass through \\p this.\n     */\n    bool Dominates(const Node* other) const {\n      std::stack<const Node*> stack;\n      std::unordered_set<const Node*> visited;\n      stack.push(this);\n      while (!stack.empty()) {\n        const Node* current = stack.top();\n        stack.pop();\n        for (auto node : current->dominator_children_) {\n          if (visited.count(node) == 0) {\n            if (other == node) {\n              return true;\n            } else {\n              stack.push(node);\n            }\n            visited.insert(node);\n          }\n        }\n      }\n      return false;\n    }\n  };\n\n  PostDfsIndex size() const { return topological_order_.size(); }\n\n  Node* item_to_node(const T& item) { return item_to_node(item.get()); }\n  const Node* item_to_node(const T& item) const { return item_to_node(item.get()); }\n\n  Node* item_to_node(const TNode* item) {\n    auto itr = node_map_.find(item);\n    ICHECK(itr != node_map_.end()) << PrettyPrint(GetRef<T>(item));\n    return itr->second;\n  }\n\n  const Node* item_to_node(const TNode* item) const {\n    auto itr = node_map_.find(item);\n    ICHECK(itr != node_map_.end()) << PrettyPrint(GetRef<T>(item));\n    return itr->second;\n  }\n\n  Node* index_to_node(PostDfsIndex index) {\n    ICHECK_LT(index, topological_order_.size()) << index;\n    return topological_order_[index].get();\n  }\n\n  const Node* index_to_node(PostDfsIndex index) const {\n    ICHECK_LT(index, topological_order_.size()) << index;\n    return topological_order_[index].get();\n  }\n\n  /*!\n   * \\brief (For debugging only) Returns description of indexed graph with hints as to the\n   * sub-expressions or sub-patterns corresponding to each indexed graph node.\n   */\n  std::string ToString() const {\n    std::ostringstream os;\n    os << \"IndexedGraph(size = \" << topological_order_.size() << \") {\" << std::endl;\n    for (PostDfsIndex index = 0; index < topological_order_.size(); ++index) {\n      const Node* node = topological_order_[index].get();\n      ICHECK_EQ(index, node->index_);\n      os << \"  \" << index << \" (\" << RefToSummary(node->ref()) << \"): inputs=[\";\n      for (const auto* sub_node : node->inputs_) {\n        os << sub_node->index_ << \",\";\n      }\n      os << \"], outputs=[\";\n      for (const auto* sub_node : node->outputs_) {\n        os << sub_node->index_ << \",\";\n      }\n      os << \"]\";\n      if (node->is_external_) {\n        os << \", external\";\n      }\n      if (node->basic_block_) {\n        os << \", basic_block=\" << node->basic_block_->index_;\n      }\n      if (node->depth_ > 0) {\n        os << \", depth=\" << node->depth_;\n      }\n      if (node->dominator_parent_) {\n        os << \", dom_parent=\" << node->dominator_parent_->index_;\n      }\n      os << \", dom_children=[\";\n      for (const auto* sub_node : node->dominator_children_) {\n        os << sub_node->index_ << \",\";\n      }\n      os << \"]\" << std::endl;\n    }\n    os << \"}\";\n    return os.str();\n  }\n\n  /*!\n   * Check-fails if the graph is ill-formed. For debugging only.\n   */\n  void CheckValid() const {\n    ICHECK_GT(topological_order_.size(), 0);\n    for (PostDfsIndex index = 0; index < topological_order_.size(); ++index) {\n      const Node* node = topological_order_[index].get();\n      // We have a node.\n      ICHECK(node);\n      // Bijections with post-dfs indexes and expressions/patterns are correct.\n      ICHECK_EQ(node->index_, index);\n      ICHECK(node->node_ref_);\n      auto itr = node_map_.find(node->node_ref_);\n      ICHECK(itr != node_map_.end());\n      ICHECK_EQ(itr->second, node) << \"at index \" << index << \" in:\" << std::endl << ToString();\n      // Inputs come before.\n      for (size_t i = 0; i < node->inputs_.size(); ++i) {\n        const Node* input = node->inputs_[i];\n        ICHECK(input);\n        ICHECK_LT(input->index_, index);\n        ICHECK(std::find(input->outputs_.begin(), input->outputs_.end(), node) !=\n               input->outputs_.end());\n      }\n      // Outputs come after.\n      for (size_t i = 0; i < node->outputs_.size(); ++i) {\n        const Node* output = node->outputs_[i];\n        ICHECK(output);\n        ICHECK_GT(output->index_, index);\n        ICHECK(std::find(output->inputs_.begin(), output->inputs_.end(), node) !=\n               output->inputs_.end());\n      }\n      ICHECK_GT(node->depth_, 0);\n      // Dominator children come before.\n      for (size_t i = 0; i < node->dominator_children_.size(); ++i) {\n        const Node* child = node->dominator_children_[i];\n        ICHECK(child);\n        ICHECK_LT(child->index_, index);\n      }\n      if (node->dominator_parent_) {\n        // Dominator comes after.\n        ICHECK_GT(node->dominator_parent_->index_, index);\n      }\n    }\n  }\n\n private:\n  /*! \\brief Construct the domination tree inside IndexedGraph */\n  void PostDom() {\n    for (PostDfsIndex i = topological_order_.size(); i != 0; --i) {\n      PostDfsIndex index = i - 1;\n      auto* current = topological_order_[index].get();\n      if (current->is_external_) {\n        current->depth_ = 1;\n        current->dominator_parent_ = nullptr;\n      } else {\n        auto parent = LeastCommonAncestor(current->outputs_);\n        current->depth_ = parent ? parent->depth_ + 1 : 1;\n        current->dominator_parent_ = parent;\n        if (parent) {\n          parent->dominator_children_.push_back(current);\n        }\n      }\n    }\n  }\n\n  /*! \\brief Find the least common ancestor of all outputs of a node */\n  Node* LeastCommonAncestor(const std::vector<Node*>& outputs) {\n    if (outputs.size() == 0) {\n      return nullptr;\n    }\n    auto parent = outputs.at(0);\n    for (size_t i = 1; i < outputs.size(); ++i) {\n      parent = LeastCommonAncestor(parent, outputs.at(i));\n    }\n    return parent;\n  }\n\n  /*! \\brief Find the least common ancestor of two nodes */\n  Node* LeastCommonAncestor(Node* lhs, Node* rhs) {\n    if (lhs == nullptr || rhs == nullptr) {\n      return nullptr;\n    }\n    PostDfsIndex lhs_index = lhs->index_;\n    PostDfsIndex rhs_index = rhs->index_;\n    while (lhs != rhs) {\n      ICHECK(lhs && rhs) << \"LCA(\" << lhs_index << \", \" << rhs_index << \") on graph:\" << std::endl\n                         << ToString();\n      if (lhs->depth_ < rhs->depth_) {\n        rhs = rhs->dominator_parent_;\n      } else if (lhs->depth_ > rhs->depth_) {\n        lhs = lhs->dominator_parent_;\n      } else {\n        rhs = rhs->dominator_parent_;\n        lhs = lhs->dominator_parent_;\n      }\n    }\n    return lhs;\n  }\n\n  /*!\n   * \\brief Appends a node corresponding to \\p ref, and maintains the sub-expression/sub-pattern to\n   * node bijection. The insertion index will be the node's PostDfsIndex. All other node properties\n   * are accumulated in-place.\n   */\n  void AddNode(const T& ref) {\n    PostDfsIndex index = topological_order_.size();\n    auto node = std::make_unique<Node>(ref.get(), index);\n    node_map_[ref.get()] = node.get();\n    topological_order_.emplace_back(std::move(node));\n  }\n\n  /*!\n   * \\brief Map from underlying sub-expression or sub-pattern nodes to their indexed graph nodes.\n   */\n  std::unordered_map<const TNode*, Node*> node_map_;\n  /*! \\brief All nodes in increasing post-dfs index order. This vector owns all the nodes. */\n  std::vector<std::unique_ptr<Node>> topological_order_;\n\n  friend std::unique_ptr<IndexedGraph<Expr>> CreateIndexedGraph(const Expr& expr);\n  friend std::unique_ptr<IndexedGraph<DFPattern>> CreateIndexedGraph(const DFPattern& pattern);\n};\n\n/*! \\brief Returns an Indexed Graph for \\p expr, which much outlive the result. */\nstd::unique_ptr<IndexedGraph<Expr>> CreateIndexedGraph(const Expr& expr);\n\n/*!\n * \\brief Returns an Indexed Graph for \\p pattern, which must outlive the result.\n * The dataflow for a pattern mimics the dataflow for the expression which would match\n * that pattern.\n */\nstd::unique_ptr<IndexedGraph<DFPattern>> CreateIndexedGraph(const DFPattern& pattern);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_IR_INDEXED_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/annotation/annotation.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/op/annotation/annotation.h\n * \\brief Helpers for working with various 'annotation' attributes.\n */\n#ifndef TVM_RELAY_OP_ANNOTATION_ANNOTATION_H_\n#define TVM_RELAY_OP_ANNOTATION_ANNOTATION_H_\n\n#include <tvm/relay/attrs/annotation.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/runtime/ndarray.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Wraps \\p data in a \"stop_fusion\" annotation. */\nExpr StopFusion(Expr data);\n\n/*! \\brief Wraps \\p data in a \"cast_hint\" annotation for \\p dtype. */\nExpr CastHint(Expr data, DataType dtype);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_ANNOTATION_ANNOTATION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/call/call.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/call/call.h\n * \\brief Operators for calling lowered functions.\n */\n#ifndef TVM_RELAY_OP_CALL_CALL_H_\n#define TVM_RELAY_OP_CALL_CALL_H_\n\n#include <tvm/relay/attrs/call.h>\n#include <tvm/relay/expr.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Returns the Relay call_lowered op. Use this helper to avoid extraneous calls to\n * Registry::Get.\n */\nconst Op& CallLoweredOp();\n\n/*!\n * \\brief Helper to construct a Relay call with the \"call_lowered\" op.\n *\n * The callee must:\n *  - Be a global bound to a PrimFunc or an externally defined functions.\n *  - Accept only tensor arguments and return tensor results.\n *  - Arguments and results correspond to the flattened form (see FlattenTupleType) of the\n *    Relay Function type.\n *  - Return results by output pointer, ie use DPS.\n * The arguments remain in Relay form (ie not flattened).\n * The result remains in Relay form (ie returned from the call and not flattened).\n *\n * \\param lowered_func Lowered function to call with call_lowered.\n * \\param args Arguments to be passed to the function.\n * \\param call_lowered_attrs Function attributes.\n * \\param span TVM span for propagating debugging info.\n * \\return\n */\nCall CallLowered(GlobalVar lowered_func, Array<Expr> args, CallLoweredAttrs call_lowered_attrs,\n                 Span span);\n\n/*!\n * \\brief Lowered function and the arguments to call it with.\n */\nstruct CallLoweredProps {\n  /*! \\brief Global variable pointing to the lowered function. */\n  GlobalVar lowered_func;\n  /*! \\brief Array of the arguments to call lowered_func with. */\n  Array<Expr> arguments;\n  /*! \\brief Attributes from the call_lowered op. */\n  CallLoweredAttrs attrs;\n};\n\n/*!\n * \\brief Helper to extract the lowered function and its arguments from a Call(\"call_lowered\", ...).\n * Returns the null/empty \\p CallLoweredProps if \\p call_node is not in that form.\n */\nCallLoweredProps GetCallLoweredProps(const CallNode* call_node);\n\n/*!\n * \\brief Returns \\p call_node in 'standard' Relay form. Ie if \\p call_node is a call_lowered\n * then returns it in un-lowered form, otherwise returns \\p call_node directly.\n *\n * Useful for passes which can act uniformly on calls irrespective of their form.\n */\nCall GetAnyCall(const CallNode* call_node);\n\n/*!\n * \\brief Returns true if lowered call described by \\p props is to a reshape primitive.\n */\nbool IsReshapeOnly(const CallLoweredProps& props);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_CALL_CALL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/contrib/ethosu/common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/contrib/ethosu/common.h\n * \\brief Functions for all Arm(R) Ethos(TM)-U NPU operators to use.\n */\n\n#ifndef TVM_RELAY_OP_CONTRIB_ETHOSU_COMMON_H_\n#define TVM_RELAY_OP_CONTRIB_ETHOSU_COMMON_H_\n\n#include <tvm/relay/expr.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace op {\nnamespace contrib {\nnamespace ethosu {\n\n/*! \\brief Infer the output tensor shape for binary elementwise operators.\n * \\param ifm_shape The shape of Input Feature Map.\n * \\param ifm_layout The layout of the IFM (NHWC or NHCWB16).\n * \\param ofm_layout The layout of the OFM (NHWC or NHCWB16).\n * \\param ofm_channels The number of Output Feature Map channels.\n * \\return The shape of the output tensor.\n */\nArray<IndexExpr> EthosuInferElementwiseOutputShape(Array<IndexExpr> ifm_shape, String ifm_layout,\n                                                   String ofm_layout, IndexExpr ofm_channels);\n\n/*! \\brief Infer the output tensor shape for convolution and pooling operators.\n * \\param ifm_shape The shape of Input Feature Map.\n * \\param ifm_layout The layout of the IFM (NHWC or NHCWB16).\n * \\param ofm_layout The layout of the OFM (NHWC or NHCWB16).\n * \\param kernel_shape Kernel shape in format (height, width).\n * \\param ofm_channels The number of Output Feature Map channels.\n * \\param dilation The 2-dimensional dilation as (dilation_height, dilation_width).\n * \\param strides The 2 dimensional strides as (stride_height, stride_width).\n * \\param padding The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\n * \\return The shape of the output tensor.\n */\nArray<IndexExpr> EthosuInferKernelOutput(Array<IndexExpr> ifm_shape, String ifm_layout,\n                                         String ofm_layout, Array<IndexExpr> kernel_shape,\n                                         IndexExpr ofm_channels, Array<IndexExpr> dilation,\n                                         Array<IndexExpr> strides, Array<IndexExpr> padding);\n\n/*! \\brief Infer the Output Feature Map shape for operations that use upscaling.\n * \\param ifm_shape The shape of the Input Feature Map.\n * \\param ifm_layout The layout of the Input Feature Map.\n */\nArray<IndexExpr> EthosuInferUpscaledInput(Array<IndexExpr> ifm_shape, String ifm_layout);\n\n/*! \\brief Get data type from string representation.\n * \\param dtype Data type in lower case format followed by number of bits e.g. \"int8\".\n */\nDataType DataTypeFromString(const String& dtype);\n\n/*! \\brief Check the data type for a given input matches one given in allowed_data_types. Raise a\n * type inference error if not.\n * \\param reporter The infer type reporter.\n * \\param data_type The data type to check.\n * \\param allowed_data_types An initializer list of allowed data types.\n * \\param operator_name The name of the operator to report.\n * \\param tensor_name The name of the tensor to report e.g. \"ifm\", \"ofm\".\n * \\param operator_type The type of the operator to report e.g. \"ADD\" for binary_elementwise.\n */\nvoid CheckDataType(const TypeReporter& reporter, const DataType& data_type,\n                   const std::initializer_list<DataType>& allowed_data_types,\n                   const String& operator_name, const String& tensor_name,\n                   const String& operator_type = \"\");\n\n/*! \\brief Check the upscale method matches one given in allowed_upscale_methods. Raise a type\n * inference error if not.\n * \\param reporter The infer type reporter.\n * \\param upscale_method The upscale method string to check.\n * \\param allowed_upscale_methods An initializer list of allowed upscale methods.\n * \\param operator_name The name of the operator to report.\n * \\param operator_type The type of the operator to report e.g. \"ADD\" for binary_elementwise.\n */\nvoid CheckUpscaleMethod(const TypeReporter& reporter, const String& upscale_method,\n                        const std::initializer_list<String>& allowed_upscale_methods,\n                        const String& operator_name, const String& operator_type = \"\");\n\n/*! \\brief Check the data type matches that of the second data type provided. Raise a type inference\n * error if not.\n * \\param reporter The infer type reporter.\n * \\param data_type The data type to check.\n * \\param data_type2 The second data type to check.\n * \\param operator_name The name of the operator to report.\n * \\param tensor_name The name of the tensor to report e.g. \"ifm\", \"ofm\".\n * \\param tensor_name2 The name of the second tensor to report e.g. \"ifm2\".\n * \\param operator_type The type of the operator to report e.g. \"ADD\" for binary_elementwise.\n */\nvoid CheckDataTypeMatch(const TypeReporter& reporter, const DataType& data_type,\n                        const DataType& data_type2, const String& operator_name,\n                        const String& tensor_name, const String& tensor_name2,\n                        const String& operator_type = \"\");\n\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace op\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_CONTRIB_ETHOSU_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/contrib/ethosu/op_attrs.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/contrib/ethosu/op_attrs.h\n * \\brief Attributes for the Arm(R) Ethos(TM)-U NPU operators.\n */\n\n#ifndef TVM_RELAY_OP_CONTRIB_ETHOSU_OP_ATTRS_H_\n#define TVM_RELAY_OP_CONTRIB_ETHOSU_OP_ATTRS_H_\n\n#include <tvm/relay/op.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace op {\nnamespace contrib {\nnamespace ethosu {\n\n/*! \\brief Attributes used by the Ethos(TM)-U NPU binary elementwise operators */\nstruct EthosuBinaryElementwiseAttrs : public tvm::AttrsNode<EthosuBinaryElementwiseAttrs> {\n  String operator_type;\n  double ifm_scale;\n  int ifm_zero_point;\n  double ifm2_scale;\n  int ifm2_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  IndexExpr ifm_channels;\n  IndexExpr ifm2_channels;\n  bool reversed_operands;\n  String activation;\n  int clip_min;\n  int clip_max;\n  String rounding_mode;\n  String ifm_layout;\n  String ifm2_layout;\n  String ofm_layout;\n  String ofm_dtype;\n\n  TVM_DECLARE_ATTRS(EthosuBinaryElementwiseAttrs, \"relay.attrs.EthosuBinaryElementwiseAttrs\") {\n    TVM_ATTR_FIELD(operator_type)\n        .describe(\n            \"The type of the binary elementwise operator.\"\n            \"'ADD'\"\n            \"'SUB'\"\n            \"'MUL'\"\n            \"'MIN'\"\n            \"'MAX'\"\n            \"'SHR'\"\n            \"'SHL'\");\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm2_scale)\n        .describe(\"The quantization scale for the Input Feature Map tensor 2.\");\n    TVM_ATTR_FIELD(ifm2_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor 2.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_channels).describe(\"The number of the Input Feature Map channels.\");\n    TVM_ATTR_FIELD(ifm2_channels).describe(\"The number of the Input Feature Map 2 channels.\");\n    TVM_ATTR_FIELD(reversed_operands)\n        .describe(\"True if IFM2 is the first operand and IFM is the second operand.\")\n        .set_default(false);\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"The activation function to use. \"\n            \"'NONE' - no activation function. \"\n            \"'CLIP' - clip the output between clip_min and clip_max. \"\n            \"'TANH' - tanh activation function. \"\n            \"'SIGMOID' - sigmoid activation function. \"\n            \"'LUT' - use a look-up table to perform the activation function.\"\n            \"Available activations for activation type:\"\n            \"{int8, uint8}: 'NONE', 'CLIP', 'TANH', 'SIGMOID', 'LUT'\"\n            \"{int32}: 'NONE'\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(clip_min)\n        .describe(\"The minimum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(clip_max)\n        .describe(\"The maximum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(rounding_mode)\n        .describe(\n            \"The rounding mode to apply to the Output Feature Map tensor. \"\n            \"'TFL' - Tensorflow Lite rounding scheme. \"\n            \"'TRUNCATE' - Truncate towards zero.\"\n            \"'NATURAL' - Round to nearest value, with x.5 rounded up towards +infinity.\")\n        .set_default(\"TFL\");\n    TVM_ATTR_FIELD(ifm_layout)\n        .describe(\"The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n    TVM_ATTR_FIELD(ifm2_layout)\n        .describe(\"The layout of the Input Feature Map tensor 2. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n    TVM_ATTR_FIELD(ofm_layout)\n        .describe(\"The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n    TVM_ATTR_FIELD(ofm_dtype).describe(\n        \"The Output Feature Map tensor type.\"\n        \"MUL, ADD, SUB {IFM}->{OFM}:\"\n        \"  {uint8, int8 int32} -> {uint8, int8, int32}, any pairing\"\n        \"MAX, MIN:\"\n        \"  IFM and OFM must be of the same type, one of:\"\n        \"  {int8, uint8}\"\n        \"SHR {IFM}->{OFM}:\"\n        \"  {int32}->{int8, uint8, int32}, any pairing\"\n        \"SHL:\"\n        \"  {int32}->{int32} only\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuBinaryElementwiseAttrs);\n\n/*! \\brief Attributes used by the Ethos(TM)-U NPU convolution operator */\nstruct EthosuConv2DAttrs : public tvm::AttrsNode<EthosuConv2DAttrs> {\n  double ifm_scale;\n  int ifm_zero_point;\n  int weight_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  Array<IndexExpr> kernel_shape;\n  IndexExpr ofm_channels;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  String activation;\n  int clip_min;\n  int clip_max;\n  String rounding_mode;\n  String upscale;\n  String ifm_layout;\n  String ofm_layout;\n\n  TVM_DECLARE_ATTRS(EthosuConv2DAttrs, \"relay.attrs.EthosuConv2DAttrs\") {\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(weight_zero_point)\n        .describe(\"The quantization zero point for the weight tensor.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(kernel_shape)\n        .describe(\"The 2 dimensional kernel shape as (kernel_height, kernel_width).\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(ofm_channels)\n        .describe(\"The number of the Output Feature Map channels.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"The 2 dimensional strides as (stride_height, stride_width).\");\n    TVM_ATTR_FIELD(padding)\n        .set_default(Array<IndexExpr>({0, 0, 0, 0}))\n        .describe(\"The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\");\n    TVM_ATTR_FIELD(dilation)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"The 2 dimensional dilation as (dilation_height, dilation_width).\");\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"The activation function to use. \"\n            \"'NONE' - no activation function. \"\n            \"'CLIP' - clip the output between clip_min and clip_max. \"\n            \"'TANH' - tanh activation function. \"\n            \"'SIGMOID' - sigmoid activation function. \"\n            \"'LUT' - use a look-up table to perform the activation function.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(clip_min)\n        .describe(\"The minimum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(clip_max)\n        .describe(\"The maximum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(rounding_mode)\n        .describe(\n            \"The rounding mode to apply to the Output Feature Map tensor. \"\n            \"'TFL' - Tensorflow Lite rounding scheme. \"\n            \"'TRUNCATE' - Truncate towards zero.\"\n            \"'NATURAL' - Round to nearest value, with x.5 rounded up towards +infinity.\")\n        .set_default(\"TFL\");\n    TVM_ATTR_FIELD(upscale)\n        .describe(\n            \"The 2x2 upscaling mode to apply to the Input Feature Map tensor. \"\n            \"'NONE' - no upscaling. \"\n            \"'NEAREST' - upscale using nearest neighbour. \"\n            \"'ZEROS' - upscale using zeros.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(ifm_layout)\n        .set_default(\"NHWC\")\n        .describe(\"The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\");\n    TVM_ATTR_FIELD(ofm_layout)\n        .set_default(\"NHWC\")\n        .describe(\"The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuConv2DAttrs);\n\n/*! \\brief Attributes used by the Ethos(TM)-U NPU depthwise operator */\nstruct EthosuDepthwiseConv2DAttrs : public tvm::AttrsNode<EthosuDepthwiseConv2DAttrs> {\n  double ifm_scale;\n  int ifm_zero_point;\n  int weight_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  Array<IndexExpr> kernel_shape;\n  IndexExpr ofm_channels;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  Array<IndexExpr> dilation;\n  String activation;\n  int clip_min;\n  int clip_max;\n  String rounding_mode;\n  String upscale;\n  String ifm_layout;\n  String ofm_layout;\n  String ofm_dtype;\n\n  TVM_DECLARE_ATTRS(EthosuDepthwiseConv2DAttrs, \"relay.attrs.EthosuDepthwiseConv2DAttrs\") {\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(weight_zero_point)\n        .describe(\"The quantization zero point for the weight tensor.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(kernel_shape)\n        .describe(\"The 2 dimensional kernel shape as (kernel_height, kernel_width).\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(ofm_channels)\n        .describe(\"The number of OFM channels.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(strides)\n        .describe(\"The 2 dimensional strides as (stride_height, stride_width).\")\n        .set_default(Array<IndexExpr>({1, 1}));\n    TVM_ATTR_FIELD(padding)\n        .describe(\"The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right)\")\n        .set_default(Array<IndexExpr>({0, 0, 0, 0}));\n    TVM_ATTR_FIELD(dilation)\n        .describe(\"The 2 dimensional dilation as (dilation_height, dilation_width).\")\n        .set_default(Array<IndexExpr>({1, 1}));\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"Description: The activation function to use.\"\n            \"'NONE' - no activation function.\"\n            \"'CLIP' - clip the output between clip_min and clip_max.\"\n            \"'TANH - tanh activation function.\"\n            \"'SIGMOID' - sigmoid activation function.\"\n            \"'LUT' - use a look-up table to perform the activation function.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(clip_min)\n        .describe(\"The minimum clipping value if activation = CLIP.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(clip_max)\n        .describe(\"The maximum clipping value if activation = CLIP.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(rounding_mode)\n        .describe(\n            \"The rounding mode to apply to the Output Feature Map tensor. \"\n            \"'TFL' - Tensorflow Lite rounding scheme. \"\n            \"'TRUNCATE' - Truncate towards zero.\"\n            \"'NATURAL' - Round to nearest value, with x.5 rounded up towards +infinity.\")\n        .set_default(\"TFL\");\n    TVM_ATTR_FIELD(upscale)\n        .describe(\n            \"The 2x2 upscaling mode to apply to the Input Feature Map tensor. \"\n            \"'NONE' - no upscaling. \"\n            \"'NEAREST' - upscale using nearest neighbour. \"\n            \"'ZEROS' - upscale using zeros.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(ifm_layout)\n        .set_default(\"NHWC\")\n        .describe(\"The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\");\n    TVM_ATTR_FIELD(ofm_layout)\n        .set_default(\"NHWC\")\n        .describe(\"The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\");\n    TVM_ATTR_FIELD(ofm_dtype)\n        .describe(\"The Output Feature Map tensor data type. Can be 'int8', 'uint8' or 'int16'.\")\n        .set_default(\"int8\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuDepthwiseConv2DAttrs);\n\n/*! \\brief Attributes used by the NPU identity operator */\nstruct EthosuIdentityAttrs : public tvm::AttrsNode<EthosuIdentityAttrs> {\n  double ifm_scale;\n  int ifm_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  String activation;\n\n  TVM_DECLARE_ATTRS(EthosuIdentityAttrs, \"relay.attrs.EthosuIdentityAttrs\") {\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"The activation function to use. \"\n            \"'NONE' - no activation function. \"\n            \"'TANH' - tanh activation function. \"\n            \"'SIGMOID' - sigmoid activation function. \"\n            \"'LUT' - use a look-up table to perform the activation function.\")\n        .set_default(\"NONE\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuIdentityAttrs);\n\n/*! \\brief Attributes used by the Ethos(TM)-U NPU pooling operator */\nstruct EthosuPoolingAttrs : public tvm::AttrsNode<EthosuPoolingAttrs> {\n  String pooling_type;\n  double ifm_scale;\n  int ifm_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  Array<IndexExpr> pool_shape;\n  IndexExpr ofm_channels;\n  Array<IndexExpr> strides;\n  Array<IndexExpr> padding;\n  String activation;\n  int clip_min;\n  int clip_max;\n  String rounding_mode;\n  String upscale;\n  String ifm_layout;\n  String ofm_layout;\n\n  TVM_DECLARE_ATTRS(EthosuPoolingAttrs, \"relay.attrs.EthosuPoolingAttrs\") {\n    TVM_ATTR_FIELD(pooling_type)\n        .describe(\"The type of the pooling. 'AVG' - average pool, 'MAX' - max pool.\");\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(pool_shape)\n        .describe(\"The 2 dimensional pool shape as (pool_shape_height, pool_shape_width).\")\n        .set_default(NullValue<Array<IndexExpr>>());\n    TVM_ATTR_FIELD(ofm_channels)\n        .describe(\" The number of the Output Feature Map channels.\")\n        .set_default(NullValue<IndexExpr>());\n    TVM_ATTR_FIELD(strides)\n        .set_default(Array<IndexExpr>({1, 1}))\n        .describe(\"The 2 dimensional strides as (stride_height, stride_width).\");\n    TVM_ATTR_FIELD(padding)\n        .describe(\"The 4 dimensional padding as (pad_top, pad_left, pad_bottom, pad_right).\")\n        .set_default(Array<IndexExpr>({0, 0, 0, 0}));\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"The activation function to use. \"\n            \"'NONE' - no activation function. \"\n            \"'CLIP' - clip the output between clip_min and clip_max. \"\n            \"'TANH' - tanh activation function. \"\n            \"'SIGMOID' - sigmoid activation function. \"\n            \"'LUT' - use a look-up table to perform the activation function.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(clip_min)\n        .describe(\"The minimum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(clip_max)\n        .describe(\"The maximum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(rounding_mode)\n        .describe(\n            \"The rounding mode to apply to the Output Feature Map tensor. \"\n            \"'TFL' - Tensorflow Lite rounding scheme. \"\n            \"'TRUNCATE' - Truncate towards zero.\"\n            \"'NATURAL' - Round to nearest value, with x.5 rounded up towards +infinity.\")\n        .set_default(\"TFL\");\n    TVM_ATTR_FIELD(upscale)\n        .describe(\n            \"The 2x2 upscaling mode to apply to the Input Feature Map tensor. \"\n            \"'NONE' - no upscaling. \"\n            \"'NEAREST' - upscale using nearest neighbour. \"\n            \"'ZEROS' - upscale using zeros.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(ifm_layout)\n        .describe(\"The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n    TVM_ATTR_FIELD(ofm_layout)\n        .describe(\"The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuPoolingAttrs);\n\n/*! \\brief Attributes used by the NPU unary elementwise operator */\nstruct EthosuUnaryElementwiseAttrs : public tvm::AttrsNode<EthosuUnaryElementwiseAttrs> {\n  String operator_type;\n  double ifm_scale;\n  int ifm_zero_point;\n  double ofm_scale;\n  int ofm_zero_point;\n  IndexExpr ofm_channels;\n  String activation;\n  int clip_min;\n  int clip_max;\n  String rounding_mode;\n  String ifm_layout;\n  String ofm_layout;\n\n  TVM_DECLARE_ATTRS(EthosuUnaryElementwiseAttrs, \"relay.attrs.EthosuUnaryElementwiseAttrs\") {\n    TVM_ATTR_FIELD(operator_type)\n        .describe(\n            \"The type of the unary elementwise operator.\"\n            \"'ABS'\"\n            \"'CLZ'\");\n    TVM_ATTR_FIELD(ifm_scale).describe(\"The quantization scale for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ifm_zero_point)\n        .describe(\"The quantization zero point for the Input Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_scale).describe(\"The quantization scale for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_zero_point)\n        .describe(\"The quantization zero point for the Output Feature Map tensor.\");\n    TVM_ATTR_FIELD(ofm_channels).describe(\"The number of OFM channels.\");\n    TVM_ATTR_FIELD(activation)\n        .describe(\n            \"The activation function to use. \"\n            \"'NONE' - no activation function. \"\n            \"'CLIP' - clip the output between clip_min and clip_max. \"\n            \"'TANH' - tanh activation function. \"\n            \"'SIGMOID' - sigmoid activation function. \"\n            \"'LUT' - use a look-up table to perform the activation function.\")\n        .set_default(\"NONE\");\n    TVM_ATTR_FIELD(clip_min)\n        .describe(\"The minimum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(clip_max)\n        .describe(\"The maximum clipping value if activation = 'CLIP'.\")\n        .set_default(0);\n    TVM_ATTR_FIELD(rounding_mode)\n        .describe(\n            \"The rounding mode to apply to the Output Feature Map tensor. \"\n            \"'TFL' - Tensorflow Lite rounding scheme. \"\n            \"'TRUNCATE' - Truncate towards zero.\"\n            \"'NATURAL' - Round to nearest value, with x.5 rounded up towards +infinity.\")\n        .set_default(\"TFL\");\n    TVM_ATTR_FIELD(ifm_layout)\n        .describe(\"The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n    TVM_ATTR_FIELD(ofm_layout)\n        .describe(\"The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.\")\n        .set_default(\"NHWC\");\n  }\n};\n\nTVM_REGISTER_NODE_TYPE(EthosuUnaryElementwiseAttrs);\n\n}  // namespace ethosu\n}  // namespace contrib\n}  // namespace op\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_CONTRIB_ETHOSU_OP_ATTRS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/dyn/nn/upsampling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file src/relay/op/dyn/nn/upsampling.h\n * \\brief implementation of the InferCorrectLayout pass for dynamic upsampling\n */\n\n#ifndef TVM_RELAY_OP_DYN_NN_UPSAMPLING_H_\n#define TVM_RELAY_OP_DYN_NN_UPSAMPLING_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/tir/data_layout.h>\n\n#include \"../../op_common.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace dyn {\n\ntemplate <typename T>\nInferCorrectLayoutOutput UpsamplingInferCorrectLayout(const Attrs& attrs,\n                                                      const Array<Layout>& new_in_layouts,\n                                                      const Array<Layout>& old_in_layouts,\n                                                      const Array<tvm::relay::Type>& old_in_types) {\n  const auto* attrs_ptr = attrs.as<T>();\n  ICHECK(attrs_ptr);\n  ObjectPtr<T> params = make_object<T>(*attrs_ptr);\n\n  if (new_in_layouts.defined()) {\n    ICHECK_GT(new_in_layouts.size(), 0);\n\n    Layout raw_layout(params->layout);\n    Layout input = new_in_layouts[0];\n    if (input.IndexOf(LayoutAxis::Get('W')) == raw_layout.IndexOf(LayoutAxis::Get('W')) &&\n        input.IndexOf(LayoutAxis::Get('H')) == raw_layout.IndexOf(LayoutAxis::Get('H')) &&\n        !input.Contains(LayoutAxis::Get('w')) && !input.Contains(LayoutAxis::Get('h')) &&\n        (input.IndexOf(LayoutAxis::Get('D')) == -1 ||\n         (input.IndexOf(LayoutAxis::Get('D')) == raw_layout.IndexOf(LayoutAxis::Get('D')) &&\n          !input.Contains(LayoutAxis::Get('d'))))) {\n      params->layout = input.name();  // modify self to follow the input layout\n    }\n  }\n\n  Layout inferred_layout(params->layout);\n  Layout param_layout(\"NCHW\");\n  return InferCorrectLayoutOutput({inferred_layout, param_layout, param_layout}, {inferred_layout},\n                                  Attrs(params));\n}\n\n}  // namespace dyn\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_DYN_NN_UPSAMPLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/dyn/tensor/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/tensor/transform.h\n * \\brief Transform op attributes that can be shared among Relay and its dialects.\n */\n#ifndef TVM_RELAY_OP_DYN_TENSOR_TRANSFORM_H_\n#define TVM_RELAY_OP_DYN_TENSOR_TRANSFORM_H_\n\nnamespace tvm {\nnamespace relay {\nnamespace dyn {}  // namespace dyn\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_DYN_TENSOR_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/make_op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file tvm/relay/op/make_op.h\n * \\brief Header of internal operator functions\n * to assist in creating ops in C++\n */\n#ifndef TVM_RELAY_OP_MAKE_OP_H_\n#define TVM_RELAY_OP_MAKE_OP_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n#include <tvm/tir/index_map.h>\n\n// Include Templated Make Functions\n#include \"nn/convolution_make.h\"\n#include \"nn/pooling.h\"\n\nnamespace tvm {\nnamespace relay {\n\nExpr MakeBroadCastTo(Expr data, Array<Integer> shape);\n\nExpr MakeCast(Expr data, DataType dtype);\n\nExpr MakeClip(Expr a, double a_min, double a_max);\n\nExpr MakeConcatenate(Expr data, int axis);\n\nExpr MakeMatmul(Expr tensor_a, Expr tensor_b, IndexExpr units, DataType out_dtype, bool transpose_a,\n                bool transpose_b);\n\nExpr MakeDense(Expr data, Expr weight, IndexExpr units, DataType out_dtype);\n\nExpr MakeBatchMatmul(Expr lhs, Expr rhs, DataType out_dtype, bool transpose_a, bool transpose_b);\n\nExpr MakeExpandDims(Expr data, int axis, int num_newaxis);\n\nExpr MakeFixedPointMultiplyPerAxis(Expr x, Expr m, Expr lshift, Expr rshift,\n                                   bool is_lshift_required, bool is_rshift_required,\n                                   Array<Integer> axis);\n\nExpr MakeFull(Expr fill_value, Array<Integer> shape, DataType dtype);\n\nExpr MakeLayoutTransform(Expr data, String src_layout, String dst_layout);\n\nExpr MakeMetaScheduleLayoutTransform(Expr data, tir::IndexMap index_map);\n\nExpr MakeAutoSchedulerLayoutTransform(Expr data, String src_layout, String dst_layout);\n\nExpr MakeOnes(Array<Integer> shape, DataType dtype);\n\nExpr MakePad(Expr data, Array<Array<Integer>> pad_width, Expr pad_value, String pad_mode);\n\nExpr MakeReduce(Expr data, Array<Integer> axis, bool keepdims, bool exclude, String op_name);\n\nExpr MakeRepeat(Expr data, int repeats, int axis);\n\nExpr MakeReshape(Expr data, Array<Integer> newshape, bool allowzero = false);\n\nExpr MakeReshapeLike(Expr lhs, Expr rhs, int lhs_begin, Integer lhs_end, int rhs_begin,\n                     Integer rhs_end);\n\nExpr MakeSplit(Expr data, ObjectRef indices_or_sections, int axis);\n\nExpr MakeSqueeze(Expr data, Array<Integer> axis);\n\nExpr MakeStack(Expr data, int axis);\n\nExpr MakeTranspose(Expr data, Array<Integer> axes);\n\nExpr MakeStridedSlice(Expr data, Array<Integer> begin, Array<Integer> end, Array<Integer> strides,\n                      String slice_mode,\n                      Optional<Array<Integer>> axes = NullValue<Array<Integer>>());\n\nExpr MakeTile(Expr data, Array<Integer> reps);\n\nExpr MakeTopK(Expr data, int k, int axis, String ret_type, bool is_ascend, DataType dtype);\n\nExpr MakeUpSampling(Expr data, double scale_h, double scale_w, String layout, String method,\n                    bool align_corners);\n\nExpr MakeUpSampling3D(Expr data, double scale_d, double scale_h, double scale_w, String layout,\n                      String method, String coordinate_transformation_mode);\n\nExpr MakeVariance(Expr data, Expr mean, Array<Integer> axis, bool keepdims, bool exclude,\n                  bool unbiased);\n\nExpr MakeZeros(Array<Integer> shape, DataType dtype);\n\nExpr MakeOneHot(Expr indices, Expr on_value, Expr off_value, int depth, int axis, DataType dtype);\n\nExpr MakeResize2D(Expr data, Array<IndexExpr> size, Array<FloatImm> roi, String layout,\n                  String method, String coordinate_transformation_mode, String rounding_method,\n                  double cubic_alpha, int cubic_exclude, double extrapolation_value,\n                  DataType out_dtype);\n\nExpr MakeSparseToDense(Expr indices, Array<Integer> output_shape, Expr values, Expr default_value);\n\nExpr MakeArange(Expr start, Expr stop, Expr step, DataType dtype);\n\nExpr MakeShapeOf(Expr data, DataType dtype);\n\nExpr MakeTake(Expr data, Expr indices, Integer batch_dims, Integer axis, String mode);\n\nExpr MakeBiasAdd(Expr data, Expr bias, int axis);\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_MAKE_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/memory/device_copy.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/op/memory/device_copy.h\n * \\brief Helpers for working with \"device_copy\" attributes.\n */\n\n#ifndef TVM_RELAY_OP_MEMORY_DEVICE_COPY_H_\n#define TVM_RELAY_OP_MEMORY_DEVICE_COPY_H_\n\n#include <tvm/relay/attrs/device_copy.h>\n#include <tvm/relay/expr.h>\n\n#include <utility>\n\n#include \"../call/call.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Returns the \"device_copy\" operator. */\nconst Op& DeviceCopyOp();\n\n/*!\n * \\brief Wraps \\p expr in a \"device_copy\" CallNode indicating it should be evaluated and\n * stored at \\p src_virtual_device but then copied to \\p dst_virtual_device.\n */\nExpr DeviceCopy(Expr expr, VirtualDevice src_virtual_device, VirtualDevice dst_virtual_device);\n\n/*!\n * \\brief Wraps \\p expr in a \"device_copy\" CallNode indicating it should be evaluated and\n * stored at \\p src_virtual_device but then copied to \\p dst_virtual_device.However, return \\p expr\n * directly if \\p src_virtual_device and \\p dst_virtual_device are (structurally) the same.\n */\nExpr MaybeDeviceCopy(Expr expr, VirtualDevice src_virtual_device, VirtualDevice dst_virtual_device);\n\n/*! \\brief Result of \\p GetDeviceCopyProps. */\nstruct DeviceCopyProps {\n  Expr body;  // = null\n  VirtualDevice src_virtual_device = VirtualDevice::FullyUnconstrained();\n  VirtualDevice dst_virtual_device = VirtualDevice::FullyUnconstrained();\n\n  DeviceCopyProps() = default;\n\n  DeviceCopyProps(Expr body, VirtualDevice src_virtual_device, VirtualDevice dst_virtual_device)\n      : body(std::move(body)),\n        src_virtual_device(std::move(src_virtual_device)),\n        dst_virtual_device(std::move(dst_virtual_device)) {}\n};\n\n/*!\n * \\brief Returns the body expression, source, and destination \\p VirtualDevices for \\p call_node\n * if it is a \"device_copy\" CallNode. Otherwise returns the null expression and unconstrained\n * virtual device.\n */\nDeviceCopyProps GetDeviceCopyProps(const CallNode* call_node);\n\n/*!\n * \\brief Returns the body expression, source, and destination \\p VirtualDevices for \\p expr if it\n * is a \"device_copy\" Call. Otherwise returns the null expression and unconstrained virtual device.\n */\nDeviceCopyProps GetDeviceCopyProps(const Expr& expr);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_MEMORY_DEVICE_COPY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/memory/memory.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/memory/memory.h\n * \\brief Operators for memory related operations in Relay.\n */\n\n#ifndef TVM_RELAY_OP_MEMORY_MEMORY_H_\n#define TVM_RELAY_OP_MEMORY_MEMORY_H_\n\n#include <tvm/target/virtual_device.h>\n\n#include <vector>\n\n#include \"tvm/relay/expr.h\"\n\nnamespace tvm {\nnamespace relay {\n\nExpr AllocStorage(Expr size, Expr alignment, VirtualDevice virtual_device, DataType dtype_hint);\n/*! \\brief Returns the \"memory.alloc_tensor\" operator. */\nconst Op& MemoryAllocTensorOp();\nExpr AllocTensor(Expr storage, Expr offset, tvm::relay::Expr shape, DataType dtype,\n                 Array<IndexExpr> assert_shape);\nExpr ToTupleType(const Type& ty, const std::vector<Expr>& exprs);\nstd::vector<Expr> FromTupleType(const Type& type, const Expr& expr);\nstd::vector<TensorType> FlattenTupleType(const Type& type);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_MEMORY_MEMORY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/memory/on_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file relay/op/memory/on_device.h\n * \\brief Helpers for working with the \"on_device\" 'annotation' call.\n */\n#ifndef TVM_RELAY_OP_MEMORY_ON_DEVICE_H_\n#define TVM_RELAY_OP_MEMORY_ON_DEVICE_H_\n\n#include <tvm/relay/attrs/on_device.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n#include <tvm/runtime/ndarray.h>\n\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief Returns the \"on_device\" operator. */\nconst Op& OnDeviceOp();\n\n/*!\n * \\brief Wraps \\p body in an \"on_device\" CallNode for \\p virtual_device.\n *\n * See \\p OnDeviceAttrs for an overview.\n */\nCall OnDevice(Expr body, VirtualDevice virtual_device, bool constrain_result = false,\n              bool constrain_body = true);\n\n/*! \\brief Result of \\p GetOnDeviceProps. */\nstruct OnDeviceProps {\n  Expr body;  // = null\n  VirtualDevice virtual_device = VirtualDevice::FullyUnconstrained();\n  bool constrain_result = false;\n  bool constrain_body = false;\n\n  OnDeviceProps() = default;\n\n  OnDeviceProps(Expr body, VirtualDevice virtual_device, bool constrain_result, bool constrain_body)\n      : body(std::move(body)),\n        virtual_device(std::move(virtual_device)),\n        constrain_result(constrain_result),\n        constrain_body(constrain_body) {}\n\n  bool is_fixed() const { return constrain_result && constrain_body; }\n  bool is_normal() const { return !constrain_result && constrain_body; }\n};\n\n/*!\n * \\brief Wraps \\p body in an \"on_device\" CallNode, taking all fields other than \\p body from \\p\n * props.\n */\ninline Call OnDeviceWithProps(Expr body, const OnDeviceProps& props) {\n  return OnDevice(std::move(body), props.virtual_device, props.constrain_result,\n                  props.constrain_body);\n}\n\n/*!\n * \\brief Wraps \\p body in an \"on_device\" CallNode, but don't constrain the body or result to\n * any particular virtual device. This allows a \"device_copy\" to be inserted by PlanDevices\n * where required, while at the same time not introducing unnecessary freedom in the device\n * choices.\n */\ninline Call OnDeviceCopyOk(Expr body) {\n  return OnDevice(std::move(body), VirtualDevice::FullyUnconstrained(),\n                  /*constrain_result=*/false, /*constrain_body=*/false);\n}\n\n/*!\n * \\brief Wraps \\p expr in an \"on_device\" CallNode for \\p virtual_device and \\p constraint if the\n * \\p VirtualDevice for \\p expr cannot otherwise be recovered by the lexical scoping convention.\n * This means we will NOT wrap if:\n *  - \\p virtual_device is full unconstrained, which signals there are no device annotations\n *    already in play.\n *  - \\p expr is an operator or primitive function literal. These are device polymorphic.\n *  - \\p expr is a non-primitive function literal. The device is captured by the\n *    \"result_virtual_device\" attribute on the function itself.\n *  - \\p expr is a global var. The device is on the function attributes the global is bound to.\n *  - \\p expr is a local var. The device is tracked by the device aware visitors for us.\n *  - \\p expr is a constructor. These are device polymorphic.\n * Nested on_device calls will never be constructed, they are instead merged on-the-fly.\n */\nExpr MaybeOnDevice(Expr body, VirtualDevice virtual_device, bool constrain_result = false,\n                   bool constrain_body = true);\n\n/*! \\brief As for MaybeOnDevice, but with both body and result constrained. */\ninline Expr MaybeOnDeviceFixed(Expr body, VirtualDevice virtual_device) {\n  return MaybeOnDevice(std::move(body), std::move(virtual_device), /*constrain_result=*/true,\n                       /*constrain_body=*/true);\n}\n\n/*! \\brief As for MaybeOnDevice, but with fields other than body taken from \\p props. */\ninline Expr MaybeOnDeviceWithProps(Expr body, const OnDeviceProps& props) {\n  return MaybeOnDevice(std::move(body), props.virtual_device, props.constrain_result,\n                       props.constrain_body);\n}\n\n/*!\n * \\brief Returns the body expression, \\p VirtualDevice, and constraint field for \\p call_node if it\n * is an \"on_device\" CallNode. Otherwise returns the null expression, the unconstrained\n * \\p VirtualDevice, and \\p kBody.\n */\nOnDeviceProps GetOnDeviceProps(const CallNode* call_node);\n\n/*!\n * \\brief Returns the body expression, \\p VirtualDevice, and constraint field for \\p expr if it is\n * an \"on_device\" CallNode. Otherwise returns the null expression, the unconstrained \\p\n * VirtualDevice, and \\p kBody.\n */\nOnDeviceProps GetOnDeviceProps(const Expr& expr);\n\n/*!\n * \\brief Returns the body of \\p expr if it is an \"on_device\" annotation, otherwise returns\n * \\p expr directly.\n */\ninline Expr IgnoreOnDevice(const Expr& expr) {\n  OnDeviceProps props = GetOnDeviceProps(expr);\n  return props.body.defined() ? props.body : expr;\n}\n\n/*!\n * \\brief Returns \\p expr as \\p NodeType, or null if it is not of that type. Looks through\n * any \"on_device\" annotations.\n */\ntemplate <typename NodeType>\nconst NodeType* AsIgnoringOnDevice(const Expr& expr) {\n  const auto* node = expr.as<NodeType>();\n  if (node != nullptr) {\n    return node;\n  }\n  OnDeviceProps props = GetOnDeviceProps(expr);\n  if (!props.body.defined()) {\n    return nullptr;\n  }\n  return props.body.as<NodeType>();\n}\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_MEMORY_ON_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/nn/convolution.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/nn/convolution.h\n * \\brief Properties def of convlution operator for sharing.\n */\n#ifndef TVM_RELAY_OP_NN_CONVOLUTION_H_\n#define TVM_RELAY_OP_NN_CONVOLUTION_H_\n\n#include <tvm/auto_scheduler/compute_dag.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/tir/analysis.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"../op_common.h\"\n\nnamespace tvm {\nnamespace relay {\n\nbool Conv2DRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n               const TypeReporter& reporter);\n\nbool Conv2DTransposeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                        const TypeReporter& reporter);\n\ntemplate <typename AttrType>\nbool Conv2DWinogradRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                       const TypeReporter& reporter) {\n  ICHECK_EQ(types.size(), 3);\n  const auto* data = types[0].as<TensorTypeNode>();\n  if (data == nullptr) return false;\n  static const Layout kNCHW(\"NCHW\");\n  static const Layout kOIHW(\"OIHW\");\n\n  const AttrType* param = attrs.as<AttrType>();\n  ICHECK(param != nullptr);\n  const Layout in_layout(param->data_layout);\n  const Layout kernel_layout(param->kernel_layout);\n\n  const auto trans_in_layout = tir::BijectiveLayout(in_layout, kNCHW);\n  ICHECK(trans_in_layout.defined())\n      << \"Conv only support input layouts that are convertible from NCHW.\"\n      << \" But got \" << in_layout;\n\n  const auto trans_kernel_layout = tir::BijectiveLayout(kernel_layout, kOIHW);\n  ICHECK(trans_kernel_layout.defined())\n      << \"Conv only support kernel layouts that are convertible from OIHW.\"\n      << \" But got \" << kernel_layout;\n\n  Layout out_layout(param->out_layout == \"\" ? param->data_layout : param->out_layout);\n  const auto trans_out_layout = tir::BijectiveLayout(out_layout, kNCHW);\n  ICHECK(trans_out_layout.defined())\n      << \"Conv only support output layouts that are convertible from NCHW.\"\n      << \" But got \" << out_layout;\n\n  Array<IndexExpr> dshape_nchw = trans_in_layout.ForwardShape(data->shape);\n\n  IndexExpr channels, dilated_ksize_y, dilated_ksize_x;\n\n  ICHECK(param->kernel_size.defined() && param->channels.defined())\n      << \"The kernel size and channels of a Conv must be set or inferred by previous pass\";\n\n  ICHECK_EQ(param->kernel_size.size(), 2);\n  ICHECK_EQ(param->dilation.size(), 2);\n\n  channels = param->channels;\n  dilated_ksize_y = 1 + (param->kernel_size[0] - 1) * param->dilation[0];\n  dilated_ksize_x = 1 + (param->kernel_size[1] - 1) * param->dilation[1];\n\n  // NOTE: Do not check weight shape here!\n  // Different backend requires different layout to compute\n  // the batch gemm stage in winograd efficiently, but we want to\n  // make this op work for all backends.\n  // So we accept all weight shapes, and assume the TOPI developers\n  // can handle this correctly in alter_op_layout.\n\n  // dilation\n  Array<IndexExpr> oshape({dshape_nchw[0], channels, 0, 0});\n\n  IndexExpr pad_h, pad_w;\n  GetPaddingHeightWidth(param->padding, &pad_h, &pad_w);\n  if (!dshape_nchw[2].as<tir::AnyNode>()) {\n    oshape.Set(2, (dshape_nchw[2] + pad_h - dilated_ksize_y) / param->strides[0] + 1);\n  } else {\n    oshape.Set(2, dshape_nchw[2]);\n  }\n  if (!dshape_nchw[3].as<tir::AnyNode>()) {\n    oshape.Set(3, (dshape_nchw[3] + pad_w - dilated_ksize_x) / param->strides[1] + 1);\n  } else {\n    oshape.Set(3, dshape_nchw[3]);\n  }\n\n  DataType out_dtype = param->out_dtype;\n  if (out_dtype.bits() == 0) {\n    out_dtype = data->dtype;\n  }\n  oshape = trans_out_layout.BackwardShape(oshape);\n  // assign output type\n  reporter->Assign(types[2], TensorType(oshape, out_dtype));\n  return true;\n}\n\ntemplate <typename T>\nInferCorrectLayoutOutput ConvInferCorrectLayout(const Attrs& attrs,\n                                                const Array<Layout>& new_in_layouts,\n                                                const Array<Layout>& old_in_layouts,\n                                                const Array<tvm::relay::Type>& old_in_types) {\n  const T* params = attrs.as<T>();\n  // We always make other operators to fit the layouts of convolution layers\n  // So this inference ignores all inputs\n  return InferCorrectLayoutOutput(\n      {params->data_layout, params->kernel_layout},\n      {params->out_layout == \"\" ? params->data_layout : params->out_layout}, attrs);\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_NN_CONVOLUTION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/nn/convolution_make.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/nn/convolution_make.h\n * \\brief utilities for creating convolution ops\n */\n#ifndef TVM_RELAY_OP_NN_CONVOLUTION_MAKE_H_\n#define TVM_RELAY_OP_NN_CONVOLUTION_MAKE_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/op.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\ntemplate <typename T>\ninline Expr MakeConv(Expr data, Expr weight, Array<IndexExpr> strides, Array<IndexExpr> padding,\n                     Array<IndexExpr> dilation, int groups, IndexExpr channels,\n                     Array<IndexExpr> kernel_size, std::string data_layout,\n                     std::string kernel_layout, std::string out_layout, DataType out_dtype,\n                     std::string op_name) {\n  auto attrs = make_object<T>();\n  attrs->strides = std::move(strides);\n  attrs->padding = std::move(padding);\n  attrs->dilation = std::move(dilation);\n  attrs->groups = groups;\n  attrs->channels = std::move(channels);\n  attrs->kernel_size = std::move(kernel_size);\n  attrs->data_layout = std::move(data_layout);\n  attrs->kernel_layout = std::move(kernel_layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->out_dtype = std::move(out_dtype);\n  const Op& op = Op::Get(op_name);\n  return Call(op, {data, weight}, Attrs(attrs), {});\n}\n\ntemplate <typename T>\ninline Expr MakeConvWinograd(Expr data, Expr weight, int tile_size, Array<IndexExpr> strides,\n                             Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups,\n                             IndexExpr channels, Array<IndexExpr> kernel_size,\n                             std::string data_layout, std::string kernel_layout,\n                             std::string out_layout, DataType out_dtype, std::string op_name) {\n  auto attrs = make_object<T>();\n  attrs->tile_size = tile_size;\n  attrs->strides = std::move(strides);\n  attrs->padding = std::move(padding);\n  attrs->dilation = std::move(dilation);\n  attrs->groups = groups;\n  attrs->channels = std::move(channels);\n  attrs->kernel_size = std::move(kernel_size);\n  attrs->data_layout = std::move(data_layout);\n  attrs->kernel_layout = std::move(kernel_layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->out_dtype = std::move(out_dtype);\n  const Op& op = Op::Get(op_name);\n  return Call(op, {data, weight}, Attrs(attrs), {});\n}\n\ntemplate <typename T>\ninline Expr MakeConvGemm(Expr data, Expr weight, Array<IndexExpr> strides, Array<IndexExpr> padding,\n                         Array<IndexExpr> dilation, int groups, IndexExpr channels,\n                         Array<IndexExpr> kernel_size, std::string data_layout,\n                         std::string kernel_layout, std::string out_layout, DataType out_dtype,\n                         std::string op_name) {\n  auto attrs = make_object<T>();\n  attrs->strides = std::move(strides);\n  attrs->padding = std::move(padding);\n  attrs->dilation = std::move(dilation);\n  attrs->groups = groups;\n  attrs->channels = std::move(channels);\n  attrs->kernel_size = std::move(kernel_size);\n  attrs->data_layout = std::move(data_layout);\n  attrs->kernel_layout = std::move(kernel_layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->out_dtype = std::move(out_dtype);\n  const Op& op = Op::Get(op_name);\n  return Call(op, {data, weight}, Attrs(attrs), {});\n}\n\ntemplate <typename T>\ninline Expr MakeConvTranspose(Expr data, Expr weight, Array<IndexExpr> strides,\n                              Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups,\n                              IndexExpr channels, Array<IndexExpr> kernel_size,\n                              std::string data_layout, std::string kernel_layout,\n                              std::string out_layout, Array<IndexExpr> output_padding,\n                              DataType out_dtype, std::string op_name) {\n  auto attrs = make_object<T>();\n  attrs->strides = std::move(strides);\n  attrs->padding = std::move(padding);\n  attrs->dilation = std::move(dilation);\n  attrs->groups = groups;\n  attrs->channels = std::move(channels);\n  attrs->kernel_size = std::move(kernel_size);\n  attrs->data_layout = std::move(data_layout);\n  attrs->kernel_layout = std::move(kernel_layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->output_padding = std::move(output_padding);\n  attrs->out_dtype = std::move(out_dtype);\n  const Op& op = Op::Get(op_name);\n  return Call(op, {data, weight}, Attrs(attrs), {});\n}\n\ntemplate <typename T>\ninline Expr MakeDeformableConv(Expr data, Expr offset, Expr weight, Array<IndexExpr> strides,\n                               Array<IndexExpr> padding, Array<IndexExpr> dilation,\n                               int deformable_groups, int groups, int channels,\n                               Array<IndexExpr> kernel_size, std::string data_layout,\n                               std::string kernel_layout, std::string out_layout,\n                               DataType out_dtype, std::string op_name) {\n  auto attrs = make_object<T>();\n  attrs->strides = strides;\n  attrs->padding = padding;\n  attrs->dilation = dilation;\n  attrs->deformable_groups = deformable_groups;\n  attrs->groups = groups;\n  attrs->channels = channels;\n  attrs->kernel_size = kernel_size;\n  attrs->data_layout = data_layout;\n  attrs->kernel_layout = kernel_layout;\n  attrs->out_layout = out_layout;\n  attrs->out_dtype = out_dtype;\n  const Op& op = Op::Get(op_name);\n  return Call(op, {data, offset, weight}, Attrs{attrs}, {});\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_NN_CONVOLUTION_MAKE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/nn/nn.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/nn/nn.h\n * \\brief Properties def of nn operators for sharing.\n */\n#ifndef TVM_RELAY_OP_NN_NN_H_\n#define TVM_RELAY_OP_NN_NN_H_\n\n#include <tvm/auto_scheduler/compute_dag.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/ir/expr.h>\n#include <tvm/relay/type.h>\n\n#include <algorithm>\n#include <utility>\n#include <vector>\n\n#include \"../op_common.h\"\n\nnamespace tvm {\nnamespace relay {\n\ntemplate <typename AttrType>\nbool MatmulRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n               const TypeReporter& reporter) {\n  ICHECK_EQ(types.size(), 3);\n  const auto* tensor_a = types[0].as<TensorTypeNode>();\n  const auto* tensor_b = types[1].as<TensorTypeNode>();\n  if (tensor_a == nullptr) return false;\n  ICHECK(static_cast<int>(tensor_a->shape.size()) != 0);\n\n  const AttrType* param = attrs.as<AttrType>();\n  ICHECK(param != nullptr);\n  TensorType meta_schedule_tensor_b{nullptr};\n  if (param->meta_schedule_original_shape.size() > 0) {\n    meta_schedule_tensor_b = TensorType(param->meta_schedule_original_shape,\n                                        tensor_b == nullptr ? tensor_a->dtype : tensor_b->dtype);\n    tensor_b = meta_schedule_tensor_b.get();\n  }\n  // Default set to dense layout\n  bool transpose_a = false;\n  bool transpose_b = true;\n  const auto& mattrs = attrs.as<MatmulAttrs>();\n  if (mattrs != nullptr) {\n    transpose_a = mattrs->transpose_a;\n    transpose_b = mattrs->transpose_b;\n  }\n\n  const Array<tvm::PrimExpr>& dshape = tensor_a->shape;\n  Array<tvm::PrimExpr> oshape = dshape;\n  tvm::PrimExpr reduce = dshape[dshape.size() - 1];\n  if (transpose_a) {\n    reduce = dshape[dshape.size() - 2];\n    oshape.Set((oshape.size() - 2), dshape[oshape.size() - 1]);\n  }\n  auto tensor_b_dtype = (tensor_b == nullptr ? tensor_a->dtype : tensor_b->dtype);\n  if (param->units.defined()) {\n    // validate the tensor_b shape is proper if defined\n    // Assign tensor_b type\n    const Array<IndexExpr>& wshape = transpose_b ? Array<IndexExpr>({param->units, reduce})\n                                                 : Array<IndexExpr>({reduce, param->units});\n    // It is possible for tensor_b to be nullptr in which case we will use\n    // data dtype as the tensor_b dtype. However if tensor_b dtype is explicitly\n    // present we will use that.\n    if (param->auto_scheduler_rewritten_layout.size() != 0) {\n      // If the layout is rewritten by auto-scheduler or meta-schedule,\n      // we just forcefully apply the layout provided by auto-scheduler and\n      // skip the normal inference logic.\n      {}  // do nothing\n    } else if (param->meta_schedule_original_shape.size() == 0) {\n      // Normal case: assign result to reporter\n      reporter->Assign(types[1], TensorType(wshape, tensor_b_dtype));\n    }\n    oshape.Set((oshape.size() - 1), param->units);\n  } else {\n    if (tensor_b == nullptr) return false;\n    const Array<tvm::PrimExpr>& wshape = tensor_b->shape;\n    // When tensor_b's layout has been rewritten, figure it out based on the\n    // total number of elements and input dimensions.\n    if (param->auto_scheduler_rewritten_layout.size() != 0) {\n      PrimExpr tensor_b_elements = 1;\n      for (size_t i = 0; i < wshape.size(); i++) {\n        tensor_b_elements = tensor_b_elements * wshape[i];\n      }\n      oshape.Set(oshape.size() - 1, tensor_b_elements / dshape[dshape.size() - 1]);\n      // Otherwise just pull it out of the tensor_b shape directly.\n    } else {\n      if (param->auto_scheduler_rewritten_layout.size() == 0 &&\n          param->meta_schedule_original_shape.size() == 0) {\n        // ensure inner dimension matches between data and weight. If one inner\n        // dimension is dynamic then it is inferred to match the other inner\n        // dimension.\n        std::vector<PrimExpr> A_shape(tensor_a->shape.begin(), tensor_a->shape.end());\n        std::vector<PrimExpr> B_shape(tensor_b->shape.begin(), tensor_b->shape.end());\n        auto sa = A_shape.size();\n        auto sb = B_shape.size();\n        if (transpose_a && transpose_b) {\n          auto tmp = A_shape[sa - 2];\n          A_shape[sa - 2] = B_shape[sb - 1];\n          B_shape[sb - 1] = tmp;\n        } else if (transpose_a) {\n          auto tmp = A_shape[sa - 2];\n          A_shape[sa - 2] = B_shape[sb - 2];\n          B_shape[sb - 2] = tmp;\n        } else if (transpose_b) {\n          auto tmp = A_shape[sa - 1];\n          A_shape[sa - 1] = B_shape[sb - 1];\n          B_shape[sb - 1] = tmp;\n        } else {\n          auto tmp = A_shape[sa - 1];\n          A_shape[sa - 1] = B_shape[sb - 2];\n          B_shape[sb - 2] = tmp;\n        }\n        reporter->Assign(types[0], TensorType(A_shape, tensor_a->dtype));\n        reporter->Assign(types[1], TensorType(B_shape, tensor_b_dtype));\n      }\n      oshape.Set(oshape.size() - 1, transpose_b ? wshape[0] : wshape[1]);\n    }\n  }\n\n  DataType out_dtype = param->out_dtype;\n  if (out_dtype.bits() == 0) {\n    out_dtype = tensor_a->dtype;\n  }\n  // assign output type\n  reporter->Assign(types[2], TensorType(oshape, out_dtype));\n  return true;\n}\n\ntemplate <typename AttrType>\nbool BatchMatmulRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                    const TypeReporter& reporter) {\n  ICHECK_EQ(types.size(), 3);\n  const auto* x = types[0].as<TensorTypeNode>();\n  const auto* y = types[1].as<TensorTypeNode>();\n  if (x == nullptr || y == nullptr) return false;\n\n  const AttrType* param = attrs.as<AttrType>();\n  DataType out_dtype = param->out_dtype;\n  if (out_dtype.bits() == 0) {\n    out_dtype = x->dtype;\n    if (x->dtype.bits() == 0) {\n      out_dtype = y->dtype;\n    }\n  }\n  TensorType meta_schedule_y{nullptr};\n  if (param->meta_schedule_original_shape.size() != 0) {\n    meta_schedule_y = TensorType(param->meta_schedule_original_shape, out_dtype);\n    y = meta_schedule_y.get();\n  }\n  ICHECK(param != nullptr);\n  bool transpose_a = param->transpose_a;\n  bool transpose_b = param->transpose_b;\n  Array<PrimExpr> y_shape{nullptr};\n  if (param->auto_scheduler_rewritten_layout.size() != 0) {\n    y_shape = auto_scheduler::GetShapeFromRewrittenLayout(\n        param->auto_scheduler_rewritten_layout,\n        transpose_b ? tvm::runtime::Array<tvm::runtime::String>({\"b\", \"j\", \"k\"})\n                    : tvm::runtime::Array<tvm::runtime::String>({\"b\", \"k\", \"j\"}));\n  } else if (param->meta_schedule_original_shape.size() != 0) {\n    y_shape = param->meta_schedule_original_shape;\n  } else {\n    y_shape = y->shape;\n  }\n  ICHECK(x->shape.size() == 3 && y_shape.size() == 3);\n  const PrimExpr& xb = x->shape[0];\n  const PrimExpr& xi = x->shape[transpose_a ? 2 : 1];\n  const PrimExpr& xk = x->shape[transpose_a ? 1 : 2];\n  const PrimExpr& yb = y_shape[0];\n  const PrimExpr& yk = y_shape[transpose_b ? 2 : 1];\n  const PrimExpr& yj = y_shape[transpose_b ? 1 : 2];\n\n  bool is_dyn = false;\n  for (size_t i = 0; i < 3; ++i) {\n    if (x->shape[i].as<tir::AnyNode>() != nullptr || y_shape[i].as<tir::AnyNode>() != nullptr) {\n      is_dyn = true;\n      break;\n    }\n  }\n  if (!is_dyn) {\n    ICHECK(reporter->AssertEQ(xb, yb) || reporter->AssertEQ(xb, 1) || reporter->AssertEQ(yb, 1))\n        << \"BatchDot: batch dimensions don't match, \"\n        << \" x shape=\" << x->shape << \", y shape=\" << y_shape;\n    ICHECK(reporter->AssertEQ(xk, yk)) << \"BatchDot: shapes of x and y is inconsistent, \"\n                                       << \" x shape=\" << x->shape << \", y shape=\" << y_shape;\n  }\n\n  // assign output type\n  const auto& out_b =\n      xb->IsInstance<tir::AnyNode>() || yb->IsInstance<tir::AnyNode>() ? tir::Any() : max(xb, yb);\n  reporter->Assign(types[2], TensorType(Array<tvm::PrimExpr>({out_b, xi, yj}), out_dtype));\n  return true;\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_NN_NN_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/nn/pooling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/nn/convolution.h\n * \\brief Properties def of convlution operator for sharing.\n */\n#ifndef TVM_RELAY_OP_NN_POOLING_H_\n#define TVM_RELAY_OP_NN_POOLING_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/op.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace relay {\n\ntemplate <typename T>\ninline Expr MakeMaxPool(Expr data, Array<IndexExpr> pool_size, Array<IndexExpr> strides,\n                        Array<IndexExpr> dilation, Array<IndexExpr> padding, String layout,\n                        String out_layout, bool ceil_mode, String op_name) {\n  auto attrs = make_object<T>();\n  attrs->pool_size = std::move(pool_size);\n  attrs->strides = std::move(strides);\n  attrs->dilation = std::move(dilation);\n  attrs->padding = std::move(padding);\n  attrs->layout = std::move(layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->ceil_mode = ceil_mode;\n  static const Op& op = Op::Get(op_name);\n  return Call(op, {data}, Attrs(attrs), {});\n}\n\ntemplate <typename T>\ninline Expr MakeAvgPool(Expr data, Array<IndexExpr> pool_size, Array<IndexExpr> strides,\n                        Array<IndexExpr> dilation, Array<IndexExpr> padding, String layout,\n                        String out_layout, bool ceil_mode, bool count_include_pad, String op_name) {\n  auto attrs = make_object<T>();\n  attrs->pool_size = std::move(pool_size);\n  attrs->strides = std::move(strides);\n  attrs->dilation = std::move(dilation);\n  attrs->padding = std::move(padding);\n  attrs->layout = std::move(layout);\n  attrs->out_layout = std::move(out_layout);\n  attrs->ceil_mode = ceil_mode;\n  attrs->count_include_pad = count_include_pad;\n  static const Op& op = Op::Get(op_name);\n  return Call(op, {data}, Attrs(attrs), {});\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_NN_POOLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/nn/upsampling.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file src/relay/op/nn/upsampling.h\n * \\brief implementation of the InferCorrectLayout pass for upsampling\n */\n\n#ifndef TVM_RELAY_OP_NN_UPSAMPLING_H_\n#define TVM_RELAY_OP_NN_UPSAMPLING_H_\n\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/tir/data_layout.h>\n\n#include \"../op_common.h\"\n\nnamespace tvm {\nnamespace relay {\n\ntemplate <typename T>\nInferCorrectLayoutOutput UpsamplingInferCorrectLayout(const Attrs& attrs,\n                                                      const Array<Layout>& new_in_layouts,\n                                                      const Array<Layout>& old_in_layouts,\n                                                      const Array<tvm::relay::Type>& old_in_types) {\n  const auto* attrs_ptr = attrs.as<T>();\n  ICHECK(attrs_ptr);\n  ObjectPtr<T> params = make_object<T>(*attrs_ptr);\n\n  if (new_in_layouts.defined()) {\n    ICHECK_EQ(new_in_layouts.size(), 1);\n\n    Layout raw_layout(params->layout);\n    Layout input = new_in_layouts[0];\n    if (input.IndexOf(LayoutAxis::Get('W')) == raw_layout.IndexOf(LayoutAxis::Get('W')) &&\n        input.IndexOf(LayoutAxis::Get('H')) == raw_layout.IndexOf(LayoutAxis::Get('H')) &&\n        !input.Contains(LayoutAxis::Get('w')) && !input.Contains(LayoutAxis::Get('h')) &&\n        (input.IndexOf(LayoutAxis::Get('D')) == -1 ||\n         (input.IndexOf(LayoutAxis::Get('D')) == raw_layout.IndexOf(LayoutAxis::Get('D')) &&\n          !input.Contains(LayoutAxis::Get('d'))))) {\n      params->layout = input.name();  // modify self to follow the input layout\n    }\n  }\n\n  return InferCorrectLayoutOutput({params->layout}, {params->layout}, Attrs(params));\n}\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_NN_UPSAMPLING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/op_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file op_common.h\n * \\brief A set of utilities and common functionality\n * for relay ops.\n */\n#ifndef TVM_RELAY_OP_OP_COMMON_H_\n#define TVM_RELAY_OP_OP_COMMON_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n#include <tvm/relay/op_attr_types.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../transforms/infer_layout_utils.h\"\n#include \"type_relations.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*! Quick helper macro\n * - Expose a positional make function to construct the node.\n * - Register op to the registry.\n *\n * We make the decision to always only expose positional argument.\n * We will do rewrapping in the frontend to support language\n * sugars such as keyword arguments and default value.\n\n * \\param OpName the name of registry.\n */\n#define RELAY_REGISTER_UNARY_OP(OpName)                                        \\\n  TVM_REGISTER_GLOBAL(\"relay.op._make.\" OpName).set_body_typed([](Expr data) { \\\n    static const Op& op = Op::Get(OpName);                                     \\\n    return Call(op, {data}, Attrs(), {});                                      \\\n  });                                                                          \\\n  RELAY_REGISTER_OP(OpName)                                                    \\\n      .set_num_inputs(1)                                                       \\\n      .add_argument(\"data\", \"Tensor\", \"The input tensor.\")                     \\\n      .add_type_rel(\"Identity\", IdentityRel)                                   \\\n      .set_attr<TOpPattern>(\"TOpPattern\", kElemWise)                           \\\n      .set_attr<TOpIsStateful>(\"TOpIsStateful\", false)                         \\\n      .set_attr<FInferCorrectLayout>(\"FInferCorrectLayout\", ElemwiseArbitraryLayout)\n\n/*! Quick helper macro\n * - Expose a positional make function to construct the node.\n * - Register op to the registry.\n *\n * We make the decision to always only expose positional argument.\n * We will do rewrapping in the frontend to support language\n * sugars such as keyword arguments and default value.\n *\n * \\param OpName the name of registry.\n */\n#define RELAY_REGISTER_BINARY_OP(OpName)                                                \\\n  TVM_REGISTER_GLOBAL(\"relay.op._make.\" OpName).set_body_typed([](Expr lhs, Expr rhs) { \\\n    static const Op& op = Op::Get(OpName);                                              \\\n    return Call(op, {lhs, rhs}, Attrs(), {});                                           \\\n  });                                                                                   \\\n  RELAY_REGISTER_OP(OpName)                                                             \\\n      .set_num_inputs(2)                                                                \\\n      .add_argument(\"lhs\", \"Tensor\", \"The left hand side tensor.\")                      \\\n      .add_argument(\"rhs\", \"Tensor\", \"The right hand side tensor.\")                     \\\n      .add_type_rel(\"Broadcast\", BroadcastRel)                                          \\\n      .set_attr<TOpPattern>(\"TOpPattern\", kBroadcast)                                   \\\n      .set_attr<TOpIsStateful>(\"TOpIsStateful\", false)                                  \\\n      .set_attr<FInferCorrectLayout>(\"FInferCorrectLayout\", BinaryBroadcastLayout)\n\n// Comparisons\n#define RELAY_REGISTER_CMP_OP(OpName)                                                   \\\n  TVM_REGISTER_GLOBAL(\"relay.op._make.\" OpName).set_body_typed([](Expr lhs, Expr rhs) { \\\n    static const Op& op = Op::Get(OpName);                                              \\\n    return Call(op, {lhs, rhs}, Attrs(), {});                                           \\\n  });                                                                                   \\\n  RELAY_REGISTER_OP(OpName)                                                             \\\n      .set_num_inputs(2)                                                                \\\n      .add_argument(\"lhs\", \"Tensor\", \"The left hand side tensor.\")                      \\\n      .add_argument(\"rhs\", \"Tensor\", \"The right hand side tensor.\")                     \\\n      .add_type_rel(\"BroadcastComp\", BroadcastCompRel)                                  \\\n      .set_attr<TOpPattern>(\"TOpPattern\", kBroadcast)                                   \\\n      .set_attr<TOpIsStateful>(\"TOpIsStateful\", false)                                  \\\n      .set_attr<FInferCorrectLayout>(\"FInferCorrectLayout\", BinaryBroadcastLayout)\n\n/*! \\brief A helper class for matching and rewriting operators. */\ntemplate <typename R>\nclass OpMatch {\n public:\n  using MatchFunc =\n      std::function<R(const Array<Expr>& args, const Attrs& attrs, const Array<Type>& type_args)>;\n\n  /*! \\brief Match an operator with the given name.\n   *  \\param op_name The name of the operator to match.\n   *  \\param func The function to execute when it matches.\n   *  \\return A self-reference for builder style API.\n   */\n  inline OpMatch& Match(const std::string& op_name, MatchFunc func) {\n    auto op = Op::Get(op_name);\n    match_map_.insert({op, func});\n    return *this;\n  }\n\n  /*! \\brief Rewrite a call operation based on the operator and the registered\n   *  match functions.\n   * \\param call The call to rewrite.\n   * \\return The result of rewriting.\n   */\n  inline R operator()(const Call& call) {\n    auto it = match_map_.find(Downcast<Op>(call->op));\n    if (it != match_map_.end()) {\n      return it->second(call->args, call->attrs, call->type_args);\n    } else {\n      if (default_ != nullptr) {\n        return default_(call->args, call->attrs, call->type_args);\n      } else {\n        LOG(FATAL) << \"unexpected operation \" << call->op;\n      }\n    }\n  }\n\n private:\n  /*! \\brief The match function map. */\n  std::unordered_map<Op, MatchFunc, ObjectPtrHash, ObjectPtrEqual> match_map_;\n  /*! \\brief An optional default case. */\n  MatchFunc default_;\n};\n\n/*! \\brief A utility function to get padding width from a 1 or 2 ints tuple. */\ninline void GetPaddingWidth(const Array<IndexExpr>& padding, IndexExpr* pad_w) {\n  if (padding.size() == 1) {\n    *pad_w = padding[0] * 2;\n  } else if (padding.size() == 2) {\n    *pad_w = padding[0] + padding[1];\n  } else {\n    ICHECK_EQ(padding.size(), 4) << \" Expected padding size of 1 or 2, found \" << padding.size();\n  }\n}\n\n/*! \\brief A utility function to get padding height and width from a 1, 2, 4 ints tuple. */\ninline void GetPaddingHeightWidth(const Array<IndexExpr>& padding, IndexExpr* pad_h,\n                                  IndexExpr* pad_w) {\n  if (padding.size() == 1) {\n    *pad_h = padding[0] * 2;\n    *pad_w = padding[0] * 2;\n  } else if (padding.size() == 2) {\n    *pad_h = padding[0] * 2;\n    *pad_w = padding[1] * 2;\n  } else if (padding.size() == 4) {\n    *pad_h = padding[0] + padding[2];\n    *pad_w = padding[1] + padding[3];\n  } else {\n    ICHECK_EQ(padding.size(), 4) << \" Padding size should be 1, 2 or 4, but got \" << padding.size();\n  }\n}\n\n/*! \\brief A utility function to get padding depth, height and width from a 1, 3, 6 ints tuple. */\ninline void GetPaddingDepthHeightWidth(const Array<IndexExpr>& padding, IndexExpr* pad_d,\n                                       IndexExpr* pad_h, IndexExpr* pad_w) {\n  if (padding.size() == 1) {\n    *pad_d = padding[0] * 2;\n    *pad_h = padding[0] * 2;\n    *pad_w = padding[0] * 2;\n  } else if (padding.size() == 3) {\n    *pad_d = padding[0] * 2;\n    *pad_h = padding[1] * 2;\n    *pad_w = padding[2] * 2;\n  } else if (padding.size() == 6) {\n    *pad_d = padding[0] + padding[3];\n    *pad_h = padding[1] + padding[4];\n    *pad_w = padding[2] + padding[5];\n  } else {\n    ICHECK_EQ(padding.size(), 6) << \" Padding size should be 1, 3 or 6, but got \" << padding.size();\n  }\n}\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_OP_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/tensor/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/tensor/transform.h\n * \\brief Transform op attributes that can be shared among Relay and its dialects.\n */\n#ifndef TVM_RELAY_OP_TENSOR_TRANSFORM_H_\n#define TVM_RELAY_OP_TENSOR_TRANSFORM_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/op_attr_types.h>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../../transforms/infer_layout_utils.h\"\n#include \"../make_op.h\"\n\nnamespace tvm {\nnamespace relay {\n\ntemplate <typename AttrType>\nbool ConcatenateRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                    const TypeReporter& reporter) {\n  // types: [data, result]\n  ICHECK_EQ(types.size(), 2) << \"the arity of concatenate is 2, not \" << types.size();\n  /* If we receive a tuple we can continue, if we receive\n   * anything but an incomplete type we should signal an\n   * error.\n   */\n  const auto* tensor_tuple = types[0].as<TupleTypeNode>();\n  if (tensor_tuple == nullptr) {\n    reporter->GetDiagCtx().EmitFatal(\n        Diagnostic::Error(reporter->GetSpan())\n        << \"concatenate requires a tuple of tensors as the first argument, found \"\n        << PrettyPrint(types[0]));\n    return false;\n  } else if (types[0].as<IncompleteTypeNode>() != nullptr) {\n    return false;\n  }\n\n  const auto* param = attrs.as<AttrType>();\n  if (param == nullptr) {\n    reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan())\n                                     << \"the call attributes are not defined\");\n    return false;\n  }\n\n  if (tensor_tuple->fields[0].as<IncompleteTypeNode>()) {\n    return false;\n  }\n  const auto& first = Downcast<TensorType>(tensor_tuple->fields[0]);\n  // Sanity check: ndim and dtype.\n  const int ndim = static_cast<int>(first->shape.size());\n  const DataType dtype = first->dtype;\n\n  // Sanity check: axis\n  int axis = param->axis;\n  if (!(-ndim <= axis && axis < ndim)) {\n    throw CompileError(ErrorBuilder() << \"concatenate only accepts `axis` in [-ndim, ndim)\"\n                                      << \", but got axis = \" << axis << \", and ndim = \" << ndim);\n  }\n  axis = axis < 0 ? ndim + axis : axis;\n\n  for (const Type& ele : tensor_tuple->fields) {\n    if (ele.as<IncompleteTypeNode>()) {\n      return false;\n    }\n\n    const auto& e = Downcast<TensorType>(ele);\n\n    int e_ndim = static_cast<int>(e->shape.size());\n    const DataType& e_dtype = e->dtype;\n    if (e_ndim != ndim) {\n      throw Error(\"relay.concatenate requires all tensors have the same ndim\");\n    }\n    if (e_dtype != dtype) {\n      throw Error(\"relay.concatenate requires all tensors have the same dtype\");\n    }\n  }\n\n  // Calculate shape\n  std::vector<IndexExpr> oshape(ndim);\n  const size_t data_length = tensor_tuple->fields.size();\n\n  // Accumulate the concat axis output dim or decide if this is dynamic concat\n  bool is_dynamic_concat = false;\n  std::vector<TensorType> input_tensors;\n  IndexExpr concat_output_dim = first->shape[axis];\n  for (size_t i = 0; i < data_length; ++i) {\n    const auto& e = Downcast<TensorType>(tensor_tuple->fields[i]);\n    input_tensors.push_back(e);\n    if (e->shape[axis].as<AnyNode>()) {\n      is_dynamic_concat = true;\n      concat_output_dim = Any();\n    } else if (i > 0 && !is_dynamic_concat) {\n      // accumulate axis dimension\n      concat_output_dim += e->shape[axis];\n    }\n  }\n\n  oshape[axis] = concat_output_dim;\n\n  for (int i = 0; i < ndim; ++i) {\n    if (i == axis) {\n      // The concat axis is already handled above.\n      // The rest of the body sets the output shape for non-concat axes\n      continue;\n    }\n    std::vector<IndexExpr> non_any;\n    for (size_t j = 0; j < data_length; ++j) {\n      const auto& e = input_tensors[j];\n      if (!e->shape[i].as<AnyNode>()) {\n        non_any.push_back(e->shape[i]);\n      }\n    }\n    size_t non_any_size = non_any.size();\n    for (size_t k = 1; k < non_any_size; k++) {\n      if (reporter->AssertEQ(non_any[0], non_any[k])) continue;\n      throw Error(\n          \"relay.concatenate requires all tensors have the same shape \"\n          \"on non-concatenating axes\");\n    }\n\n    if (non_any_size == data_length) {\n      // All static case\n      oshape[i] = non_any[0];\n    } else if (non_any_size > 0 && is_dynamic_concat) {\n      // For non-concat axes, we want to enforce static shape constraint.\n      // However, if the concat axis is static, the output shape would become static while\n      // the input could be partially static/dynamic. To prevent runtime segfaults due to the lack\n      // of runtime input shape checking for such cases, static shape constraint is only enforced\n      // when the output concat axis is dynamic.\n      //\n      // Examples (both concat on the first axis):\n      // * [(?, 3), (?, ?)] -> (?, 3)\n      // * [(1, 3), (1, ?)] -> (2, ?)\n      oshape[i] = non_any[0];\n    } else {\n      oshape[i] = Any();\n    }\n  }\n\n  auto rtype = TensorType(oshape, dtype);\n  reporter->Assign(types[1], rtype);\n  return true;\n}\n\nstatic inline InferCorrectLayoutOutput ConcatenateLayout(\n    const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types) {\n  const auto* attrs_ptr = attrs.as<ConcatenateAttrs>();\n  ICHECK(attrs_ptr);\n  ObjectPtr<ConcatenateAttrs> param = make_object<ConcatenateAttrs>(*attrs_ptr);\n\n  Array<Array<IndexExpr>> old_in_shapes;\n  ICHECK_EQ(old_in_types.size(), 1);\n  for (auto old_in_tuple_t : old_in_types) {\n    ICHECK(old_in_tuple_t.as<TupleTypeNode>());\n    for (auto old_in_t : old_in_tuple_t.as<TupleTypeNode>()->fields) {\n      old_in_shapes.push_back(old_in_t.as<TensorTypeNode>()->shape);\n    }\n  }\n\n  size_t axis =\n      param->axis < 0 ? param->axis + old_in_shapes[0].size() : static_cast<size_t>(param->axis);\n\n  Layout ret;\n  bool is_new_layout_selected = false;\n  if (new_in_layouts.defined()) {  // this function is called after some operators are alternated.\n    // If all the new input layouts are same, the new in layout gets selected.  For axis, the new\n    // axis in the new layout is identified. The param->axis is then modified on the fly to conform\n    // to the new input layout.\n    const auto& concate_dim = old_in_layouts[0][axis];\n    bool all_input_layouts_same = true;\n    for (auto new_layout : new_in_layouts) {\n      if (!new_layout.Equals(new_in_layouts[0])) {\n        all_input_layouts_same = false;\n      }\n    }\n    if (all_input_layouts_same) {\n      auto new_index = new_in_layouts[0].IndexOf(concate_dim);\n      ret = new_in_layouts[0];\n      param->axis = new_index;\n      is_new_layout_selected = true;\n    }\n  }\n\n  if (!is_new_layout_selected) {\n    // this function is called on the original correct relay ir\n    for (size_t i = 0; i < old_in_layouts.size(); ++i) {\n      if (old_in_layouts[i].defined()) {\n        ret = old_in_layouts[i];\n        break;\n      }\n    }\n\n    if (ret.ndim() <= axis || !ret[axis].IsPrimal()) {\n      return InferCorrectLayoutOutput({Layout::Undef()}, {Layout::Undef()}, attrs);\n    }\n  }\n\n  return InferCorrectLayoutOutput(Array<Layout>(old_in_layouts.size(), ret), {ret}, Attrs(param));\n}\n\n/*!\n * \\brief Infer output shape for reshape.\n *\n * \\param data_shape The input data shape.\n * \\param attrs The attributes.\n * \\param reverse Whether to reverse the indices.\n * \\return Output shape.\n */\nArray<IndexExpr> InferNewShape(const Array<IndexExpr>& data_shape, const Attrs& attrs,\n                               bool reverse);\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_OP_TENSOR_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/type_relations.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/op/type_relations.h\n * \\brief A set of utilities and common functionality\n * for type relations.\n */\n#ifndef TVM_RELAY_OP_TYPE_RELATIONS_H_\n#define TVM_RELAY_OP_TYPE_RELATIONS_H_\n\n#include <tvm/ir/error.h>\n#include <tvm/relay/type.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n/*!\n * \\brief The identity type relation, all the types are equal.\n *\n * \\param types The input and output types to the relation.\n * \\param num_inputs The number of input arguments.\n * \\param attrs The attributes\n * \\param reporter The reporter.\n * \\return true whether relation has been resolved.\n */\nbool IdentityRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                 const TypeReporter& reporter);\n\n/*!\n * \\brief The broadcast type relation, implements the broadcasting\n * rule over the two input types producing the broadcasted type.\n *\n * \\param types The input and output types to the relation.\n * \\param num_inputs The number of input arguments.\n * \\param attrs The attributes\n * \\param reporter The reporter.\n * \\return true whether relation has been resolved.\n */\nbool BroadcastRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                  const TypeReporter& reporter);\n\n/*!\n * \\brief Determine the broadcasted shape from two input shapes\n * \\param t1 One of two Tensortype whose shapes are broadcasted\n * \\param t2 One of two Tensortype whose shapes are broadcasted\n * \\param output_dtype dtype of the output TensorType\n * \\return A TensorType whose shape is broadcasted from two input TensorType.\n */\nTensorType ConcreteBroadcast(const TensorType& t1, const TensorType& t2, DataType output_dtype);\n\n/*!\n * \\brief The broadcast type relation, implements the broadcasting\n *  rule over the two input types producing the broadcasted type.\n *\n * This differs from BroadcastRel in the return dtype,\n * it instead returns bool(uint8), for use in comparsion operators\n * such as equal, not_equal, lt, and so on.\n *\n * \\param types The input and output types to the relation.\n * \\param num_inputs The number of input arguments.\n * \\param attrs The attributes\n * \\param reporter The reporter.\n * \\return true whether relation has been resolved.\n */\nbool BroadcastCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                      const TypeReporter& reporter);\n\nbool IdentityCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                     const TypeReporter& reporter);\n\nArray<IndexExpr> RankShape(const Array<IndexExpr>& shape);\n\n/*!\n * \\brief The shape of type relation.\n *\n * \\param types The input and output types to the relation.\n * \\param num_inputs The number of input arguments.\n * \\param attrs The attributes\n * \\param reporter The reporter.\n * \\return true whether relation has been resolved.\n */\nbool ShapeOfRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                const TypeReporter& reporter);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_TYPE_RELATIONS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/op/vm/vm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/op/vm/vm.h\n * \\brief Dialect operators for Relay VM.\n */\n#ifndef TVM_RELAY_OP_VM_VM_H_\n#define TVM_RELAY_OP_VM_VM_H_\n\n#include <tvm/relay/expr.h>\n\nnamespace tvm {\nnamespace relay {\n\nExpr InvokeTVMOp(Expr func, Expr inputs, Expr outputs, DictAttrs attrs);\nExpr ShapeOf(Expr expr);\nExpr ReshapeTensor(Expr data, Expr shape, Array<PrimExpr> newshape);\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_OP_VM_VM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/qnn/op/op_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/qnn/op/op_common.h\n * \\brief A set of utilities and common functionality for QNN ops.\n */\n#ifndef TVM_RELAY_QNN_OP_OP_COMMON_H_\n#define TVM_RELAY_QNN_OP_OP_COMMON_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/relay/qnn/attrs.h>\n#include <tvm/relay/qnn/transform.h>\n\n#include <vector>\n\n#include \"../../op/type_relations.h\"\n#include \"../../transforms/infer_layout_utils.h\"\n#include \"../utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace qnn {\n\nTVM_REGISTER_NODE_TYPE(BroadcastAttrs);\n\n/*\n * Number of inputs for the Qnn binary operators.\n * Refer the QNN_REGISTER_BINARY_OP macro to see\n * what the operators are.\n */\nstatic constexpr int kNumQnnBinaryOpInputs = 8;\n\n/*\n * Number of expected arg types.\n */\nstatic constexpr int kNumQnnBinaryOpArgTypes = 9;\n\n/*\n * \\brief Simple struct to organize the inputs to the Qnn\n * binary operators. The main reason to have a struct\n * is to be able to perform the common checks needed at a\n * central location.\n */\nstruct QnnBinaryOpArguments {\n  Expr lhs;\n  Expr rhs;\n  Expr lhs_scale;\n  Expr lhs_zero_point;\n  Expr rhs_scale;\n  Expr rhs_zero_point;\n  Expr output_scale;\n  Expr output_zero_point;\n\n  explicit QnnBinaryOpArguments(const Array<Expr>& new_args) {\n    ICHECK_EQ(new_args.size(), kNumQnnBinaryOpInputs);\n    int idx = 0;\n    lhs = new_args[idx++];\n    rhs = new_args[idx++];\n    lhs_scale = new_args[idx++];\n    lhs_zero_point = new_args[idx++];\n    rhs_scale = new_args[idx++];\n    rhs_zero_point = new_args[idx++];\n    output_scale = new_args[idx++];\n    output_zero_point = new_args[idx++];\n    ICHECK_EQ(idx, kNumQnnBinaryOpInputs);\n  }\n};\n\n/*\n * Number of inputs for the Qnn unary operators.\n */\nstatic constexpr int kNumQnnUnaryOpInputs = 5;\n\n/*\n * Number of expected arg types.\n */\nstatic constexpr int kNumQnnUnaryOpArgTypes = 6;\n\n/*\n * \\brief Simple struct to organize the inputs to the Qnn\n * unary operators. The main reason to have a struct\n * is to be able to perform the common checks needed at a\n * central location.\n */\nstruct QnnUnaryOpArguments {\n  Expr x;\n  Expr scale;\n  Expr zero_point;\n  Expr output_scale;\n  Expr output_zero_point;\n\n  explicit QnnUnaryOpArguments(const Array<Expr>& new_args) {\n    ICHECK_EQ(new_args.size(), kNumQnnUnaryOpInputs);\n    int idx = 0;\n    x = new_args[idx++];\n    scale = new_args[idx++];\n    zero_point = new_args[idx++];\n    output_scale = new_args[idx++];\n    output_zero_point = new_args[idx++];\n    ICHECK_EQ(idx, kNumQnnUnaryOpInputs);\n  }\n};\n\n/*\n * \\brief Simple structure to hold the input tensor's dtype\n * and shape. This structure allows a common point to do\n * all the validation checks for Qnn unary operators.\n */\nstruct QnnUnaryOpTensorType {\n  DataType dtype;\n  Array<PrimExpr> shape;\n\n  explicit QnnUnaryOpTensorType(const Array<tvm::relay::Type>& arg_types, const int32_t arg_idx) {\n    ICHECK_EQ(arg_types.size(), kNumQnnUnaryOpArgTypes);\n    auto tensor_type = arg_types[arg_idx].as<TensorTypeNode>();\n    ICHECK(tensor_type != nullptr);\n    dtype = tensor_type->dtype;\n    shape = tensor_type->shape;\n  }\n};\n\n/*\n * \\brief Simple structure to hold the input tensor's dtype\n * and shape. This structure allows a common point to do\n * all the validation checks for Qnn binary operators.\n */\nstruct QnnBinaryOpTensorType {\n  DataType dtype;\n  Array<PrimExpr> shape;\n\n  explicit QnnBinaryOpTensorType(const Array<tvm::relay::Type>& arg_types, const int32_t arg_idx) {\n    ICHECK_EQ(arg_types.size(), kNumQnnBinaryOpArgTypes);\n    auto tensor_type = arg_types[arg_idx].as<TensorTypeNode>();\n    ICHECK(tensor_type != nullptr);\n    dtype = tensor_type->dtype;\n    shape = tensor_type->shape;\n  }\n};\n\n/*\n * \\brief Converts the expression from expression's dtype\n * to target dtype. This is mainly used for converting\n * computations done in Int32 to lower precision Int8 or\n * UInt8.\n * \\param expr The expression to whose dtype needs conversion.\n * \\param target_dtype The dtype of the target expression\n * \\return New expression with target dtype and possibly lower\n * precision.\n */\ninline Expr ConvertDtype(const Expr& expr, const DataType& target_dtype) {\n  auto q_min = GetQmin(target_dtype);\n  auto q_max = GetQmax(target_dtype);\n  auto output = Clip(expr, q_min, q_max);\n  return Cast(output, target_dtype);\n}\n\n/*\n * \\brief Requantizes the given expression if expression's\n * scale and zero point both do not match target scale and\n * zero point. This is mainly needed for requantizing the\n * input tensors with output tensor's scale and zero point\n * to ease the computation of final quantized tensor.\n * \\param expr The expression on which the check needs to be performed.\n * \\param expr_scale The scale of the expression.\n * \\param expr_zero_point The zero point of the expression.\n * \\param target_scale The scale of the output tensor.\n * \\param target_zero_point The zero point of the output tensor.\n * \\param expr_shape The shape of the input expression.\n * \\return New expression that is requantized to target scale and zero\n * point if the expression scale and zero points are different otherwise\n * it simply casts the given expression to Int32 as no requantization is\n * needed in this case.\n */\ninline Expr RequantizeOrUpcast(const Expr& expr, const Expr& expr_scale,\n                               const Expr& expr_zero_point, const Expr& target_scale,\n                               const Expr& target_zero_point, const Array<PrimExpr>& expr_shape,\n                               const int& axis = -1,\n                               const DataType& target_dtype = DataType::Int(32)) {\n  auto result = expr;\n  if (!IsEqualScalar(expr_scale, target_scale) ||\n      !IsEqualScalar(expr_zero_point, target_zero_point)) {\n    result = Requantize(expr, expr_shape, expr_scale, expr_zero_point, target_scale,\n                        target_zero_point, target_dtype, axis);\n  } else {\n    result = Cast(result, target_dtype);\n  }\n  return result;\n}\n\n/*! \\brief Infer layout for QNN binary broadcast operators */\ninline InferCorrectLayoutOutput QnnBinaryBroadcastLayout(\n    const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types) {\n  // Use Relay Binary Broadcast Infer correct layout.\n  auto layouts = BinaryBroadcastLayout(attrs, new_in_layouts, old_in_layouts, old_in_types);\n\n  // Fill the layouts of remaining input tensors - scales and zero points. The layouts of these\n  // tensors can be treated as C.\n  Layout channel_layout = Layout(\"C\");\n  Array<Layout> input_layouts = {layouts->input_layouts[0],\n                                 layouts->input_layouts[1],\n                                 channel_layout,\n                                 channel_layout,\n                                 channel_layout,\n                                 channel_layout,\n                                 channel_layout,\n                                 channel_layout};\n  Array<Layout> output_layouts = layouts->output_layouts;\n  return InferCorrectLayoutOutput(input_layouts, output_layouts, attrs);\n}\n\nstatic inline bool QnnBroadcastRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,\n                                   const TypeReporter& reporter) {\n  // Expected Types: lhs, rhs, lhs_scale, lhs_zero_point, rhs_scale, rhs_zero_point, output_scale,\n  // output_zero_point, out_type\n  ICHECK_EQ(types.size(), kNumQnnBinaryOpArgTypes);\n\n  // Check the lhs and rhs types\n  for (size_t i = 0; i < 2; ++i) {\n    if (types[i].as<IncompleteTypeNode>()) {\n      return false;\n    }\n  }\n  // Check the scale and zero point types\n  for (size_t i = 2; i < 8; ++i) {\n    if (types[i].as<IncompleteTypeNode>()) {\n      return false;\n    }\n  }\n\n  const auto* lhs_data = types[0].as<TensorTypeNode>();\n  const auto* rhs_data = types[1].as<TensorTypeNode>();\n\n  if (lhs_data == nullptr || rhs_data == nullptr) {\n    return false;\n  }\n\n  const BroadcastAttrs* broadcast_attrs = attrs.as<BroadcastAttrs>();\n  ICHECK(broadcast_attrs);\n\n  auto lhs_rank = static_cast<int>(lhs_data->shape.size());\n  auto rhs_rank = static_cast<int>(rhs_data->shape.size());\n\n  auto get_channel_axis = [](int rank, int axis_from_attr) {\n    if (rank <= 1) return 0;\n    if (axis_from_attr < 0) return rank + axis_from_attr;\n    return axis_from_attr;\n  };\n\n  const int lhs_axis = get_channel_axis(lhs_rank, broadcast_attrs->lhs_axis);\n  const int rhs_axis = get_channel_axis(rhs_rank, broadcast_attrs->rhs_axis);\n\n  // If zero point and scale are scalar then axis doesn't matter.\n  bool lhs_scale_is_scalar = (types[2].as<TensorTypeNode>())->shape.size() == 0;\n  bool lhs_zp_is_scalar = (types[3].as<TensorTypeNode>())->shape.size() == 0;\n  bool rhs_scale_is_scalar = (types[4].as<TensorTypeNode>())->shape.size() == 0;\n  bool rhs_zp_is_scalar = (types[5].as<TensorTypeNode>())->shape.size() == 0;\n\n  if (!(lhs_scale_is_scalar && lhs_zp_is_scalar)) {\n    ICHECK_LT(lhs_axis, lhs_rank > 0 ? lhs_rank : 1)\n        << \"lhs_axis \" << broadcast_attrs->lhs_axis << \" is out of range\";\n    ICHECK_GE(lhs_axis, 0) << \"lhs_axis \" << broadcast_attrs->lhs_axis << \" is out of range\";\n  }\n\n  if (!(rhs_scale_is_scalar && rhs_zp_is_scalar)) {\n    ICHECK_LT(rhs_axis, rhs_rank > 0 ? rhs_rank : 1)\n        << \"rhs_axis \" << broadcast_attrs->rhs_axis << \" is out of range\";\n    ICHECK_GE(rhs_axis, 0) << \"rhs_axis \" << broadcast_attrs->rhs_axis << \" is out of range\";\n  }\n\n  PrimExpr lhs_axis_shape;\n  if (lhs_rank > 0) {\n    lhs_axis_shape = lhs_data->shape[lhs_axis];\n  } else {\n    lhs_axis_shape = Integer(1);\n  }\n\n  PrimExpr rhs_axis_shape;\n  if (rhs_rank > 0) {\n    rhs_axis_shape = rhs_data->shape[rhs_axis];\n  } else {\n    rhs_axis_shape = Integer(1);\n  }\n\n  // Check and assign types for scale and zero points.\n  AssignType(types[2], DataType::Float(32), lhs_axis_shape, reporter);  // lhs_scale\n  AssignType(types[3], DataType::Int(32), lhs_axis_shape, reporter);    // lhs_zero_point\n  AssignType(types[4], DataType::Float(32), rhs_axis_shape, reporter);  // rhs_scale\n  AssignType(types[5], DataType::Int(32), rhs_axis_shape, reporter);    // rhs_zero_point\n\n  ICHECK(IsScalarType(types[6], DataType::Float(32)));  // output_scale\n  ICHECK(IsScalarType(types[7], DataType::Int(32)));    // output_zero_point\n\n  // Collect the input tensor and output tensor devoid of scale and zero points to reuse Relay\n  // BroadcastRel infer type function.\n  Array<Type> tensor_types = {types[0], types[1], types[8]};\n  return BroadcastRel(tensor_types, 3, attrs, reporter);\n}\n\n/*! Quick helper macro\n * - Expose a positional make function to construct the node.\n * - Register op to the registry.\n *\n * We make the decision to always only expose positional argument.\n * We will do rewrapping in the frontend to support language\n * sugars such as keyword arguments and default value.\n *\n * \\param OpName the name of registry.\n */\n#define QNN_REGISTER_BINARY_OP(OpName)                                                             \\\n  TVM_REGISTER_GLOBAL(\"relay.qnn.op._make.\" OpName)                                                \\\n      .set_body_typed([](Expr lhs, Expr rhs, Expr lhs_scale, Expr lhs_zero_point, Expr rhs_scale,  \\\n                         Expr rhs_zero_point, Expr output_scale, Expr output_zero_point,           \\\n                         int lhs_axis, int rhs_axis) {                                             \\\n        static const Op& op = Op::Get(\"qnn.\" OpName);                                              \\\n        auto attrs = make_object<BroadcastAttrs>();                                                \\\n        attrs->lhs_axis = lhs_axis;                                                                \\\n        attrs->rhs_axis = rhs_axis;                                                                \\\n        return Call(op,                                                                            \\\n                    {lhs, rhs, lhs_scale, lhs_zero_point, rhs_scale, rhs_zero_point, output_scale, \\\n                     output_zero_point},                                                           \\\n                    Attrs(attrs), {});                                                             \\\n      });                                                                                          \\\n  RELAY_REGISTER_OP(\"qnn.\" OpName)                                                                 \\\n      .set_attrs_type<BroadcastAttrs>()                                                            \\\n      .set_num_inputs(kNumQnnBinaryOpInputs)                                                       \\\n      .add_argument(\"lhs\", \"Tensor\", \"The left hand side quantized tensor.\")                       \\\n      .add_argument(\"rhs\", \"Tensor\", \"The right hand side quantized tensor.\")                      \\\n      .add_argument(\"lhs_scale\", \"Tensor\", \"The scale of the lhs tensor.\")                         \\\n      .add_argument(\"lhs_zero_point\", \"Tensor\", \"The zero_point of the lhs tensor.\")               \\\n      .add_argument(\"rhs_scale\", \"Tensor\", \"The scale of the rhs tensor.\")                         \\\n      .add_argument(\"rhs_zero_point\", \"Tensor\", \"The zero_point of the rhs tensor.\")               \\\n      .add_argument(\"output_scale\", \"Tensor\", \"The scale of the output tensor.\")                   \\\n      .add_argument(\"output_zero_point\", \"Tensor\", \"The zero_point of the output tensor.\")         \\\n      .add_argument(\"lhs_axis\", \"Tensor\", \"The channel quantization of the lhs tensor.\")           \\\n      .add_argument(\"rhs_axis\", \"Tensor\", \"The channel quantization of the rhs tensor.\")           \\\n      .add_type_rel(\"QnnBroadcast\", QnnBroadcastRel)                                               \\\n      .set_attr<TNonComputational>(\"TNonComputational\", true)                                      \\\n      .set_attr<FInferCorrectLayout>(\"FInferCorrectLayout\", QnnBinaryBroadcastLayout)\n\nstatic inline bool QnnElementwiseUnaryFuncRel(const Array<Type>& types, int num_inputs,\n                                              const Attrs& attrs, const TypeReporter& reporter) {\n  // Expected Types: data, scale, zero_point, output_scale, output_zero_point\n  ICHECK_EQ(types.size(), 6);\n  const auto* x = types[0].as<TensorTypeNode>();\n  if (x == nullptr) return false;\n  ICHECK(x->dtype == DataType::Int(8) || x->dtype == DataType::UInt(8))\n      << \"Expected quantized type(int8, uint8) for input but was \" << x->dtype;\n\n  // Check the types of scale and zero points.\n  for (size_t i = 1; i < 5; ++i) {\n    if (types[i].as<IncompleteTypeNode>()) {\n      return false;\n    }\n  }\n  ICHECK(IsScalarType(types[1], DataType::Float(32)));  // scale\n  ICHECK(IsScalarType(types[2], DataType::Int(32)));    // zero_point\n  ICHECK(IsScalarType(types[3], DataType::Float(32)));  // output_scale\n  ICHECK(IsScalarType(types[4], DataType::Int(32)));    // output_zero_point\n\n  // Assign types for scale and zero points.\n  reporter->Assign(types[1], TensorType({}, DataType::Float(32)));  // scale\n  reporter->Assign(types[2], TensorType({}, DataType::Int(32)));    // zero_point\n  reporter->Assign(types[3], TensorType({}, DataType::Float(32)));  // output_scale\n  reporter->Assign(types[4], TensorType({}, DataType::Int(32)));    // output_zero_point\n\n  // Collect the input tensor and output tensor devoid of scale and zero points to reuse Relay\n  // IdentityRel infer type function.\n  Array<Type> tensor_types = {types[0], types[5]};\n  return IdentityRel(tensor_types, 2, attrs, reporter);\n}\n\nstatic inline Expr LegalizeExpr(const Expr& expr) {\n  // Canonicalizations should not contain qnn ops, so use this\n  // to lower expressions automatically after using things like qnn.dequantize\n  // in the lowering process.\n  auto mod = IRModule::FromExpr(expr);\n  mod = transform::Legalize()(mod);\n  if (expr.as<FunctionNode>()) {\n    return mod->Lookup(\"main\");\n  } else {\n    return mod->Lookup(\"main\").as<FunctionNode>()->body;\n  }\n}\n\n/*! Quick helper macro\n * - Expose a positional make function to construct the node.\n * - Register op to the registry.\n *\n * For Unary Operators which also take in QParams.\n *\n * \\param OpName the name of registry.\n */\n#define QNN_CREATE_UNARY_ELEMENTWISE_OP(OpName)                                                 \\\n  TVM_REGISTER_GLOBAL(\"relay.qnn.op._make.\" OpName)                                             \\\n      .set_body_typed(                                                                          \\\n          [](Expr x, Expr scale, Expr zero_point, Expr output_scale, Expr output_zero_point) {  \\\n            return Call(Op::Get(\"qnn.\" OpName),                                                 \\\n                        {x, scale, zero_point, output_scale, output_zero_point}, Attrs(), {});  \\\n          });                                                                                   \\\n                                                                                                \\\n  RELAY_REGISTER_OP(\"qnn.\" OpName)                                                              \\\n      .describe(\"Elementwise \" OpName \" for quantized tensors.\")                                \\\n      .set_num_inputs(5)                                                                        \\\n      .add_argument(\"data\", \"Quantized Tensor\", \"The input data.\")                              \\\n      .add_argument(\"scale\", \"Tensor\", \"The quantization scale of the input tensor.\")           \\\n      .add_argument(\"zero_point\", \"Tensor\", \"The quantization zero_point of the input tensor.\") \\\n      .add_argument(\"output_scale\", \"Tensor\", \"The quantization scale of the output tensor.\")   \\\n      .add_argument(\"output_zero_point\", \"Tensor\",                                              \\\n                    \"The quantization zero_point of the output tensor.\")                        \\\n      .set_support_level(11)                                                                    \\\n      .add_type_rel(\"qnn.\" OpName, QnnElementwiseUnaryFuncRel)                                  \\\n      .set_attr<TNonComputational>(\"TNonComputational\", true)\n\n/*! Quick helper macro\n * Create a default canonicalization for a QNN operator, which dequantizes the operator\n * runs the calculation using the provided Call func, and then requantizes.\n *\n * FloatingPointFunc is usually a handle from \"src/relay/transforms/pattern_utils.h\"\n *\n * \\param FloatingPointFunc the floating point function with function signature `Expr Erf(Expr e)`\n */\n#define QNN_UNARY_OP_DEFAULT_CANONICALIZATION(FloatingPointFunc)                                  \\\n  [](const Attrs& attrs, const Array<Expr>& new_args, const Array<tvm::relay::Type>& arg_types) { \\\n    QnnUnaryOpArguments args(new_args);                                                           \\\n    QnnUnaryOpTensorType input_type(arg_types, 0);                                                \\\n    Expr dequantized_arg = MakeDequantize(args.x, args.scale, args.zero_point, -1);               \\\n    Expr output = FloatingPointFunc(dequantized_arg);                                             \\\n    Expr result =                                                                                 \\\n        MakeQuantize(output, args.output_scale, args.output_zero_point, -1, input_type.dtype);    \\\n    return LegalizeExpr(result);                                                                  \\\n  }\n}  // namespace qnn\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_QNN_OP_OP_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/qnn/op/requantize_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/qnn/op/requantize_config.h\n * \\brief QNN requantize config.\n */\n\n#ifndef TVM_RELAY_QNN_OP_REQUANTIZE_CONFIG_H_\n#define TVM_RELAY_QNN_OP_REQUANTIZE_CONFIG_H_\n\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/relay/qnn/attrs.h>\n\n#include <string>\n\n#include \"../../op/op_common.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace qnn {\n\nclass RequantizeConfig;\n/*!\n * \\brief Container for build configuration options\n */\nclass RequantizeConfigNode : public Object {\n  std::string rounding;\n  std::string compute_dtype;\n\n public:\n  explicit RequantizeConfigNode(bool is_default = false) : is_default(is_default) {}\n\n  std::string get_rounding() const {\n    if (!rounding.empty()) return rounding;\n    return \"UPWARD\";\n  }\n\n  std::string get_compute_dtype() const {\n    if (!compute_dtype.empty()) return compute_dtype;\n\n    // For the x86 architecture, the float32 computation is expected to give significant speedup,\n    // with little loss in the accuracy of the requantize operation.\n    auto target = Target::Current(true);\n    auto target_has_sse41 = tvm::runtime::Registry::Get(\"tvm.topi.x86.utils.target_has_sse41\");\n    ICHECK(target_has_sse41) << \"Function tvm.topi.x86.utils.target_has_sse41 not found\";\n    if (target.defined() && target->kind->name == \"llvm\" &&\n        (target->GetAttr<String>(\"mcpu\") &&\n         (*target_has_sse41)(target->GetAttr<String>(\"mcpu\").value()))) {\n      return \"float32\";\n    }\n\n    return \"int64\";\n  }\n\n  const bool is_default = false;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"rounding\", &rounding);\n    v->Visit(\"compute_dtype\", &compute_dtype);\n  }\n\n  static constexpr const char* _type_key = \"relay.qnn.op.RequantizeConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(RequantizeConfigNode, Object);\n};\n\n/*!\n * \\brief Container for build configuration options\n */\nclass RequantizeConfig : public ObjectRef {\n public:\n  RequantizeConfig() {}\n  explicit RequantizeConfig(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  const RequantizeConfigNode* operator->() const {\n    return static_cast<const RequantizeConfigNode*>(get());\n  }\n\n  RequantizeConfigNode* operator->() { return static_cast<RequantizeConfigNode*>(get_mutable()); }\n\n  /*!\n   * \\brief Push a new BuildConfig context onto the thread local stack.\n   * \\param build_config The configuration to set as the current context.\n   */\n  static void EnterRequantizeConfigScope(const RequantizeConfig& requantize_config);\n\n  /*!\n   * \\brief Pop a build config off the thread local context stack, restoring the previous\n   * configuration as the current context.\n   */\n  static void ExitRequantizeConfigScope();\n\n  /*!\n   * \\brief Get the current BuildConfig context from thread local storage, or a default\n   * configuration if a BuildConfig scope has not been entered.\n   * \\return The configuration that is the current context.\n   */\n  static RequantizeConfig& Current();\n\n  using ContainerType = RequantizeConfigNode;\n};\n\n}  // namespace qnn\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_QNN_OP_REQUANTIZE_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/qnn/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/qnn/utils.h\n * \\brief Utility methods needs for quantized ops that can be shared\n */\n\n#ifndef TVM_RELAY_QNN_UTILS_H_\n#define TVM_RELAY_QNN_UTILS_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/qnn/attrs.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <limits>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"./op/requantize_config.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace qnn {\n\nstatic inline Array<IndexExpr> get_shape(const Type& type) {\n  auto input_tt = type.as<TensorTypeNode>();\n  ICHECK(input_tt != nullptr) << \"Type information missing.\"\n                              << \" Please run infer_type pass.\";\n  return input_tt->shape;\n}\n\nstatic inline int32_t GetQmin(const DataType& dtype) {\n  ICHECK_LE(dtype.bits(), 32) << \"QNN ops support int32 or lower precision\";\n  if (dtype.is_int() || dtype.is_uint()) {\n    auto min_value_expr = tvm::min_value(dtype);\n    auto* min_value = tir::as_const_int(min_value_expr);\n    ICHECK(min_value != nullptr);\n    return static_cast<int32_t>(min_value[0]);\n  } else {\n    LOG(FATAL) << \"Type not supported \" << dtype;\n    return -1;  // To hide the warning\n  }\n}\n\nstatic inline int32_t GetQmax(const DataType& dtype) {\n  ICHECK_LE(dtype.bits(), 32) << \"QNN ops support int32 or lower precision\";\n  if (dtype.is_int() || dtype.is_uint()) {\n    auto max_value_expr = tvm::max_value(dtype);\n    auto* max_value = tir::as_const_int(max_value_expr);\n    ICHECK(max_value != nullptr);\n    return static_cast<int32_t>(max_value[0]);\n  } else {\n    LOG(FATAL) << \"Type not supported \" << dtype;\n    return -1;  // To hide the warning\n  }\n}\n\n/*\n * \\brief Convert FP32 representation into fixed point representation.\n * \\param double_multplier The input FP32 number.\n * \\return The pair of multiplier and shift for fixed point representation.\n * \\note Converts a floating point number so that it can be represented by\n *       integers. The representation is\n *             float_number = (significand) * 2^(exponent)\n *\n *       The significand is a number between 0.5 and 1. This is represented by\n *       an integer number. For example, if it is int32, then the decimal point\n *       exists between bit 31 and 30 from LSB (or between first and second bit\n *       from the left).\n *\n *       Some examples are\n *           0.25 = (0.5) * 2^(-1)\n *           0.125 = (0.5) * 2^(-2)\n *\n *       Credit to TFLite reference implementation.\n */\nstd::pair<int32_t, int32_t> GetFixedPointMultiplierShift(double double_multiplier);\n\nExpr RequantizeLower(const Expr& input_tensor, const Expr& input_scale,\n                     const Expr& input_zero_point, const Expr& output_scale,\n                     const Expr& output_zero_point, const RequantizeAttrs* param,\n                     const Array<IndexExpr>& input_shape, const DataType& out_dtype);\n\nstd::string SelectRequntizeParameter(const std::string& arg_value, const std::string& cfg_value,\n                                     const bool is_cfg_default, const std::string& name);\n\nstatic inline Expr Requantize(const Expr& data, const Array<IndexExpr>& input_shape,\n                              const Expr& input_scale, const Expr& input_zero_point,\n                              const Expr& output_scale, const Expr& output_zero_point,\n                              const DataType& out_dtype, const int& axis = -1,\n                              const std::string& rounding = \"None\",\n                              const std::string& compute_dtype = \"None\") {\n  auto attrs = make_object<RequantizeAttrs>();\n  attrs->axis = axis;\n  attrs->out_dtype = std::move(out_dtype);\n  const RequantizeConfig& cfg = RequantizeConfig::Current();\n  attrs->rounding =\n      SelectRequntizeParameter(rounding, cfg->get_rounding(), cfg->is_default, \"rounding\");\n  attrs->compute_dtype = SelectRequntizeParameter(compute_dtype, cfg->get_compute_dtype(),\n                                                  cfg->is_default, \"compute_dtype\");\n  return RequantizeLower(data, input_scale, input_zero_point, output_scale, output_zero_point,\n                         attrs.operator->(), input_shape, attrs->out_dtype);\n}\n\nExpr MakeRequantize(Expr data, Expr input_scale, Expr input_zero_point, Expr output_scale,\n                    Expr output_zero_point, int axis, String rounding, String compute_dtype,\n                    DataType out_dtype);\n\nExpr DequantizeLower(const Expr& input_tensor, const Expr& input_scale,\n                     const Expr& input_zero_point, const Array<tvm::relay::Type>& types,\n                     const DequantizeAttrs* attrs);\n\nstatic inline Expr Dequantize(const Expr& data, const Expr& input_scale,\n                              const Expr& input_zero_point, const Array<tvm::relay::Type>& types,\n                              const int& axis = -1) {\n  auto attrs = make_object<DequantizeAttrs>();\n  attrs->axis = std::move(axis);\n\n  return DequantizeLower(data, input_scale, input_zero_point, types, attrs.operator->());\n}\nExpr MakeDequantize(Expr data, Expr input_scale, Expr input_zero_point, int axis);\n\nExpr QuantizeLower(const Expr& input_tensor, const Expr& output_scale,\n                   const Expr& output_zero_point, const Array<tvm::relay::Type>& types,\n                   const QuantizeAttrs* attrs);\n\nstatic inline Expr Quantize(const Expr& data, const Expr& output_scale,\n                            const Expr& output_zero_point, const DataType& out_dtype,\n                            const Array<tvm::relay::Type>& types, const int& axis = -1) {\n  auto attrs = make_object<QuantizeAttrs>();\n  attrs->axis = std::move(axis);\n  attrs->out_dtype = std::move(out_dtype);\n\n  return QuantizeLower(data, output_scale, output_zero_point, types, attrs.operator->());\n}\nExpr MakeQuantize(Expr data, Expr output_scale, Expr output_zero_point, int axis,\n                  DataType out_dtype);\n\nstatic inline int64_t get_const_int(const tvm::PrimExpr& x) {\n  auto* value_ptr = tir::as_const_int(x);\n  ICHECK(value_ptr) << \"Expr is not a constant int\";\n  return value_ptr[0];\n}\n\n/*\n * \\brief Fixed point multiplication between integer tensor with floating point\n * scalar. This implementation rounds  to the nearest value when it is midway\n * between two representable values.\n * \\param tensor The quantized input tensor of dtype int64.\n * \\param multiplier The scalar multiplier.\n * \\param input_shape Shape of the input tensor.\n * \\return The sequence of Relay ops for fixed point multiplication with TONEARES rounding.\n\n * \\note Original compuation is scale_fp32 * quantized_tensor.  To convert into\n *       integer computation, the multiplication with fp32 scalar can be\n *       replaced by multiplication with an int value and then right shifting\n *       the result. This approximates the floating point computation with a\n *       fixed point computation.\n *\n *       Computation of fixed point multiplication is consist of following\n steps:\n *       1) Multiply the fixed point multiplier with quantized tensor.\n *       2) Round the result.\n *       3) Right shift the result\n */\nExpr FixedPointMultiplyToNearest(Expr tensor, double multiplier,\n                                 const Array<IndexExpr>& input_shape);\n\n/*\n * \\brief Fixed point multiplication between integer tensor with floating point\n scalar where the input tensor is per-axis/per-channel quantized..\n * \\param tensor The quantized input tensor of dtype int64.\n * \\param multiplier The scalar multiplier.\n * \\param input_shape Shape of the input tensor.\n * \\param channel_axis The channel_axis along which the input tensor is quantized. Default value is\n -1 which corresponds to the last channel_axis.\n * \\param rounding \"UPWARD\" or \"TONEAREST\". The rounding direction when the value\n is midway between\" \"two representable values.\n * \\return The sequence of Relay ops for fixed point multiplication.\n\n * \\note Original compuation is scale_fp32 * quantized_tensor.  To convert into\n *       integer computation, the multiplication with fp32 vector can be\n *       replaced by multiplication with an int vector and then right shifting\n *       the result. This approximates the floating point computation with a\n *       fixed point computation.\n *\n *       Computation of fixed point multiplication is consist of following\n steps:\n *       1) Multiply the fixed point multiplier with quantized tensor.\n *       2) Round the result.\n *       3) Right shift the result\n */\nExpr FixedPointMultiplyPerChannel(Expr tensor, std::vector<double> multiplier,\n                                  const Array<IndexExpr>& input_shape, int channel_axis,\n                                  const std::string& rounding);\n\n/*\n * Wrapper for 'FixedPointMultiplyPerChannel' with rounding parameter == \"TONEAREST\".\n */\nExpr FixedPointMultiplyPerChannelToNearest(Expr tensor, std::vector<double> multiplier,\n                                           const Array<IndexExpr>& input_shape, int channel_axis);\n\n/*\n * \\brief Creates FixedPointMultiply operation where the input tensor is\n per-axis/per-channel quantized..\n * \\param tensor The quantized input tensor.\n * \\param multipliers List of scalar multipliers.\n * \\param channel_axis The channel_axis along which the input tensor is quantized.\n * \\return The Relay op.\n */\nExpr FixedPointMultiplyPerChannel(Expr tensor, const std::vector<double>& multipliers, int axis);\n\n/*\n * \\brief Checks whether an expr type is scalar of a given data type.\n * \\param expr_type The type of expr to be checked.\n * \\param dtype The expected dtype.\n * \\return True if the type is a scalar of given dtype\n */\nstatic inline bool IsScalarType(const Type& expr_type, const DataType& dtype) {\n  const auto* tensor_type = expr_type.as<TensorTypeNode>();\n  ICHECK(tensor_type) << \"Only tensor type can be checked for scalar values. But got\"\n                      << AsText(expr_type, false);\n  ICHECK_EQ(tensor_type->shape.size(), 0);\n  ICHECK(tensor_type->dtype == dtype) << \"Expected \" << dtype << \" but got \" << tensor_type->dtype;\n  return true;\n}\n\n/*\n * \\brief Checks whether an expr type is scalar.\n * \\param expr_type The type of expr to be checked.\n * \\return True if the type is a scalar\n */\nstatic inline bool IsScalarType(const Type& expr_type) {\n  const auto* tensor_type = expr_type.as<TensorTypeNode>();\n  CHECK(tensor_type) << \"Only tensor type can be checked for scalar values. But got\"\n                     << AsText(expr_type, false);\n  return tensor_type->shape.size() == 0;\n}\n\n/*\n * \\brief Checks and assigns types to scale and zero points.\n * \\param expr_type The type of expr to be checked.\n * \\param dtype The expected dtype.\n * \\param shape The shape at C dim of original tensor.\n * \\param reporter The type reported of original InferType call.\n */\nstatic inline void AssignType(const Type& expr_type, const DataType& dtype, const IndexExpr& shape,\n                              const TypeReporter& reporter) {\n  // Scale/Zero_points can be either const scalar or a vector with C axis num elems.\n  const auto* tensor_type = expr_type.as<TensorTypeNode>();\n  ICHECK(tensor_type) << \"Can assign type to Tensor type only. But got \"\n                      << AsText(expr_type, false);\n  const auto tensor_dtype = tensor_type->dtype;\n  ICHECK(tensor_dtype == dtype) << \"Expected type is \" << dtype << \" but received \" << tensor_dtype;\n  if (tensor_type->shape.size() != 0) {\n    reporter->Assign(expr_type, TensorType({shape}, tensor_type->dtype));\n  }\n}\n\nstatic inline std::vector<float> GetFloatVectorFromConstant(const Expr& expr) {\n  const auto* n = expr.as<ConstantNode>();\n  std::vector<float> vals;\n  ICHECK(n) << \"Expr must be a constant expr - \" << AsText(expr, false);\n  int64_t num_elems = 1;\n  auto shape = n->data.Shape();\n  for (size_t i = 0; i < shape.size(); i++) {\n    num_elems *= shape[i];\n  }\n  for (int64_t i = 0; i < num_elems; i++) {\n    vals.push_back(static_cast<float*>(n->data->data)[i]);\n  }\n  return vals;\n}\n\nExpr MakeQnnConv2D(Expr data, Expr weight, Expr input_zero_point, Expr kernel_zero_point,\n                   Expr input_scale, Expr kernel_scale, Array<IndexExpr> strides,\n                   Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups,\n                   IndexExpr channels, Array<IndexExpr> kernel_size, String data_layout,\n                   String kernel_layout, String out_layout, DataType out_dtype);\n\n}  // namespace qnn\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_QNN_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/quantize/quantize.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/relay/quantize.h\n * \\brief Header of definitions for quantization\n */\n#ifndef TVM_RELAY_QUANTIZE_QUANTIZE_H_\n#define TVM_RELAY_QUANTIZE_QUANTIZE_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n\n#include <string>\n\n#include \"../transforms/pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace quantize {\n\n/*! \\brief Kind of annotate field */\nenum QAnnotateKind : int { kQIdentity = 0, kQInput = 1, kQWeight = 2, kQActivation = 3 };\n\n/*! \\brief Attribute for simulated quantize operator */\nstruct SimulatedQuantizeAttrs : public tvm::AttrsNode<SimulatedQuantizeAttrs> {\n  int kind;\n  bool sign;\n  std::string rounding;\n\n  TVM_DECLARE_ATTRS(SimulatedQuantizeAttrs, \"relay.attrs.SimulatedQuantizeAttrs\") {\n    TVM_ATTR_FIELD(kind).describe(\"kind of field, hint for nbit/dtype configuration.\");\n    TVM_ATTR_FIELD(sign).set_default(true).describe(\"whether to use signed data type.\");\n    TVM_ATTR_FIELD(rounding).set_default(\"round\").describe(\n        \"rounding mode. Can be 'floor', 'ceil', 'round'\");\n  }\n};\n\nclass QConfig;\n/*!\n * \\brief Container for build configuration options\n */\nclass QConfigNode : public Object {\n public:\n  int nbit_input = 8;\n  int nbit_weight = 8;\n  int nbit_activation = 32;\n  DataType dtype_input = DataType::Int(8);\n  DataType dtype_weight = DataType::Int(8);\n  DataType dtype_activation = DataType::Int(32);\n  std::string calibrate_mode = \"global_scale\";\n  double global_scale = 8.0;\n  std::string weight_scale = \"power2\";\n  bool skip_dense_layer = true;\n  Array<Expr> skip_conv_layers = Array<Expr>(ObjectPtr<Object>(nullptr));\n  bool do_simulation = false;\n  bool round_for_shift = true;\n  Array<Expr> debug_enabled_ops = Array<Expr>(ObjectPtr<Object>(nullptr));\n  std::string rounding = \"UPWARD\";\n  int calibrate_chunk_by = -1;\n  std::string partition_conversions = \"disabled\";\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"nbit_input\", &nbit_input);\n    v->Visit(\"nbit_weight\", &nbit_weight);\n    v->Visit(\"nbit_activation\", &nbit_activation);\n    v->Visit(\"dtype_input\", &dtype_input);\n    v->Visit(\"dtype_weight\", &dtype_weight);\n    v->Visit(\"dtype_activation\", &dtype_activation);\n    v->Visit(\"calibrate_mode\", &calibrate_mode);\n    v->Visit(\"global_scale\", &global_scale);\n    v->Visit(\"weight_scale\", &weight_scale);\n    v->Visit(\"skip_dense_layer\", &skip_dense_layer);\n    v->Visit(\"skip_conv_layers\", &skip_conv_layers);\n    v->Visit(\"do_simulation\", &do_simulation);\n    v->Visit(\"round_for_shift\", &round_for_shift);\n    v->Visit(\"debug_enabled_ops\", &debug_enabled_ops);\n    v->Visit(\"rounding\", &rounding);\n    v->Visit(\"calibrate_chunk_by\", &calibrate_chunk_by);\n    v->Visit(\"partition_conversions\", &partition_conversions);\n  }\n\n  static constexpr const char* _type_key = \"relay.quantize.QConfig\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(QConfigNode, Object);\n};\n\n/*!\n * \\brief Container for build configuration options\n */\nclass QConfig : public ObjectRef {\n public:\n  QConfig() {}\n  explicit QConfig(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  const QConfigNode* operator->() const { return static_cast<const QConfigNode*>(get()); }\n\n  QConfigNode* operator->() { return static_cast<QConfigNode*>(get_mutable()); }\n\n  /*!\n   * \\brief Push a new BuildConfig context onto the thread local stack.\n   * \\param build_config The configuration to set as the current context.\n   */\n  static void EnterQConfigScope(const QConfig& qconfig);\n\n  /*!\n   * \\brief Pop a build config off the thread local context stack, restoring the previous\n   * configuration as the current context.\n   */\n  static void ExitQConfigScope();\n\n  /*!\n   * \\brief Get the current BuildConfig context from thread local storage, or a default\n   * configuration if a BuildConfig scope has not been entered.\n   * \\return The configuration that is the current context.\n   */\n  static QConfig& Current();\n\n  using ContainerType = QConfigNode;\n};\n\n/*!\n * \\brief RAII container to provide a scoped BuildConfig context. Pushes a configuration onto the\n * context stack when constructed, and pops it when destructed.\n */\nstruct QConfigContext {\n  /*!\n   * \\brief Enter a new BuildConfig context. The given BuildConfig becomes the new current\n   * context. When the BuildConfigContext is destructed, the previous context is restored.\n   * \\param build_config The BuildConfig to set as the new current context.\n   */\n  explicit QConfigContext(const QConfig& qconfig) { QConfig::EnterQConfigScope(qconfig); }\n\n  /*! \\brief Destructor. Pops the context off the thread local stack. */\n  ~QConfigContext() { QConfig::ExitQConfigScope(); }\n};\n\n}  // namespace quantize\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_QUANTIZE_QUANTIZE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/quantize/realize.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file realize.h\n *\n * \\brief Header of definitions for op realizations\n *\n */\n#ifndef TVM_RELAY_QUANTIZE_REALIZE_H_\n#define TVM_RELAY_QUANTIZE_REALIZE_H_\n\n#include <tvm/relay/transform.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace quantize {\n\nclass QRealizeExprNode : public TempExprNode {\n public:\n  Expr data;\n  static constexpr const char* _type_key = \"relay.quantize.QRealizeExpr\";\n  TVM_DECLARE_BASE_OBJECT_INFO(QRealizeExprNode, TempExprNode);\n};\n\nclass QRealizeExpr : public TempExpr {\n public:\n  TVM_DEFINE_OBJECT_REF_METHODS(QRealizeExpr, TempExpr, QRealizeExprNode);\n};\n\nclass QRealizeIntExprNode : public QRealizeExprNode {\n public:\n  Expr dom_scale;\n  DataType dtype;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"data\", &data);\n    v->Visit(\"dom_scale\", &dom_scale);\n    v->Visit(\"dtype\", &dtype);\n  }\n\n  Expr Realize() const final;\n\n  static constexpr const char* _type_key = \"relay.quantize.QRealizeIntExpr\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(QRealizeIntExprNode, QRealizeExprNode);\n};\n\nclass QRealizeIntExpr : public QRealizeExpr {\n public:\n  TVM_DLL QRealizeIntExpr(Expr data, Expr dom_scale, DataType dtype);\n\n  TVM_DEFINE_OBJECT_REF_METHODS(QRealizeIntExpr, QRealizeExpr, QRealizeIntExprNode);\n};\n\n}  // namespace quantize\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_QUANTIZE_REALIZE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/auto_scheduler_layout_rewrite.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file auto_scheduler_layout_rewrite.h\n * \\brief Rewrite the layout of \"layout free\" tensors (e.g., the weight tensors in\n * conv2d and dense layers) according to the tile structure generated by the auto-scheduler.\n */\n\n#ifndef TVM_RELAY_TRANSFORMS_AUTO_SCHEDULER_LAYOUT_REWRITE_H_\n#define TVM_RELAY_TRANSFORMS_AUTO_SCHEDULER_LAYOUT_REWRITE_H_\n\n#include <tvm/relay/expr_functor.h>\n\n#include <deque>\n#include <string>\n\nnamespace tvm {\nnamespace relay {\n\nclass AutoSchedulerLayoutRewriter : public ExprMutator {\n public:\n  Expr VisitExpr_(const CallNode* n) final;\n\n  // Two global variables for receiving layout information from python\n  static std::deque<std::string> global_ori_layouts_queue;\n  static std::deque<std::string> global_new_layouts_queue;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_AUTO_SCHEDULER_LAYOUT_REWRITE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/combine_parallel_op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file combine_parallel_op.h\n * \\brief Abstract class to combine parallel ops and their successive element-wise ops.\n */\n#ifndef TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_H_\n#define TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_H_\n\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/relay/transform.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"./expr_subst.h\"\n#include \"pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\n\nusing Branch = std::vector<const CallNode*>;\nusing Group = std::vector<Branch>;\nusing FIsSupportedOp = std::function<bool(const CallNode* n)>;\nusing FAreCompatibleOps = std::function<bool(const CallNode* a, const CallNode* b)>;\nusing ExprSubstMap = std::unordered_map<Expr, Expr, ObjectPtrHash, ObjectPtrEqual>;\n\n/*\n * Class to find parallel branches starting with op that are\n * grouped if they are able to be combined. They are eligible to\n * be combined if they have the same input data.\n * Op can be followed by zero or more elemwise or broadcast ops,\n * which are included in the group.\n * Intermediate nodes have exactly one successor. It is possible that branches meet at a point,\n * which should be handled in ParallelOpCombiner.\n *\n *        data\n *       /    \\\n *     op      op\n *     |        |\n * elem-wise elem-wise\n *     |        |\n */\nclass BranchGroupFinder : private ExprVisitor {\n public:\n  /*\n   * \\brief Constructor\n   * \\param op The op that indicates the start of each group\n   * \\param fis_supported_op function that returns true if op\n   *                         is supported for combining\n   * \\param fare_compatible_ops function that returns true if\n   *                            two ops are compatible for combining\n   */\n  BranchGroupFinder(const Op& op, FIsSupportedOp fis_supported_op,\n                    FAreCompatibleOps fare_compatible_ops);\n\n  /*\n   * \\brief Finds all groups that can be combined.\n   * \\param expr Relay expression that represents function\n   *             to look at for groups to be combined\n   * \\return Vector of groups which can be combined.\n   */\n  std::vector<Group> Find(const Expr& expr);\n\n private:\n  /* \\brief Cache the op for finding parallel branches */\n  const Op& cached_op_;\n\n  /* \\brief function to return true if op is eligible to be combined,\n   *         false otherwise\n   */\n  FIsSupportedOp fis_supported_op_;\n\n  /* \\brief function to return true if two parallel ops are eligible\n   *         to be combined, false otherwise\n   */\n  FAreCompatibleOps fare_compatible_ops_;\n\n  /* \\brief ops that are on the first (logically, leftmost) branch\n   *         of parallel ops and are eligible to be combined\n   */\n  std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> op_roots_;\n\n  /* \\brief map of Expr to CallNodes that follow it  */\n  std::unordered_map<Expr, std::vector<const CallNode*>, ObjectPtrHash, ObjectPtrEqual>\n      children_map_;\n\n  /*\n   * \\brief Creates new branch from op and its children that have\n   *        elementwise or broadcast patterns\n   * \\return New branch\n   */\n  Branch CreateBranch(const CallNode* op);\n\n  /*\n   * \\brief Expression visitor function\n   */\n  void VisitExpr_(const CallNode* n) final;\n};\n\n/*\n * Abstract class to find and combine parallel ops and the elementwise ops that follow.\n */\nclass ParallelOpCombiner {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~ParallelOpCombiner() {}\n  /*\n   * \\brief Constructor.\n   * \\param op_name name of op to combine\n   * \\param min_num_branches min number of parallel branches beginning with op\n   *                         to start combining\n   */\n  explicit ParallelOpCombiner(const std::string& op_name, uint64_t min_num_branches);\n\n  /*\n   * \\brief Combines ops and following elementwise or broadcast ops\n   * \\param expr function to modify\n   * \\return new function with combined ops\n   */\n  Expr Combine(const Expr& expr);\n\n protected:\n  /*\n   * \\brief Checks if node is supported to be combined\n   * \\param n node in question\n   * \\return True if the op represented by n is supported to be the root of a branch\n   *         to be combined. False otherwise.\n   */\n  virtual bool IsSupportedOp(const CallNode* n) = 0;\n\n  /*\n   * \\brief Checks if two ops can be combined\n   * \\param a node a\n   * \\param b node b\n   * \\return True if a and b can be combined. False otherwise.\n   */\n  virtual bool CanOpsBeCombined(const CallNode* a, const CallNode* b) = 0;\n\n  /*\n   * \\brief Makes combined op from parallel ops in branches. This usually involves\n   *        concatenating or stacking inputs, then creating a new call.\n   * \\param branches branches that are to be combined\n   * \\return new call with branches combined.\n   */\n  virtual Call MakeCombinedOp(const Group& branches) = 0;\n\n  /*\n   * \\brief Checks if argument of op following combined ops are able to be combined\n   * \\param a node a\n   * \\param b node b\n   * \\param index index of argument in question\n   * \\return True if argument of a and b and index can be combined\n   */\n  virtual bool IsArgCompatible(const CallNode* a, const CallNode* b, size_t index) = 0;\n\n  /*\n   * \\brief Create combined call from ops that follow the initial combined op at the depth-th level.\n   *        This usually involves concatenating or stacking inputs, then creating a new call.\n   *        Only called if IsArgCompatbile returns true for each arg.\n   * \\param data combined op\n   * \\param branches branches of parallel ops to be combined\n   * \\param depth depth at which to combine ops\n   * \\param parent_index index of arg that corresponds to original input that was shared among\n   *                     all combined ops\n   * \\return new combined call\n   */\n  virtual Call MakeCombinedCallFromFollowingOps(const Expr& data, const Group& branches,\n                                                size_t depth, size_t parent_index) = 0;\n\n  /*\n   * \\brief Updates map of expr to substitute with combined expr. This usually involves\n   *        slicing or splitting data.\n   * \\param data combined op\n   * \\param branches branches of parallel ops to be combined\n   * \\param depth depth at which to substitute\n   * \\param subst_map map of Expr to replace with Expr to replace it with\n   */\n  virtual void UpdateGroupOutput(const Expr& data, const Group& branches, size_t depth,\n                                 ExprSubstMap* subst_map) = 0;\n\n private:\n  /* \\brief Cache the op to be combined */\n  const Op& cached_op_;\n\n  /* \\brief minimum number of parallel branches to combine */\n  uint64_t min_num_branches_;\n\n  /* \\brief map of Expr to Expr to substitute it with after running pass */\n  ExprSubstMap subst_map_;\n\n  /*\n   * \\brief Combine parallel branches and updates subst_map_ with Exprs\n   *        to be substituted\n   * \\param branches branches to be combined\n   */\n  void CombineBranches(const Group& branches);\n\n  /*\n   * \\brief Combine parallel branches and updates subst_map_ with Exprs\n   *        to be substituted\n   * \\param branches parallel branches to potentially be combined\n   * \\param depth depth at which to look at op\n   * \\param parent_index index of arg that corresponds to original input that was shared among\n   *                     all combined ops\n   * \\return true if parallel ops at depth can be combined, false otherwise\n   */\n  bool CheckLevel(const Group& branches, size_t depth, size_t parent_index);\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/combine_parallel_op_batch.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file combine_parallel_op_batch.h\n * \\brief Combine parallel ops into a single batch op.\n */\n#ifndef TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_BATCH_H_\n#define TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_BATCH_H_\n\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/relay/transform.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"./combine_parallel_op.h\"\n#include \"./expr_subst.h\"\n#include \"pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*\n * Class to find and combine parallel ops and following element-wise\n * and broadcast ops into a single batch op. Ops can be combined\n * if they have the same input data. Batch op is formed by\n * stacking inputs. Final results are retrieved by splitting output.\n * For example:\n *\n *               data\n *         /              \\\n *    dense (2,2)         dense (2,2)\n *        |                 |\n *   elemwise/bcast (2,2)  elemwise/bcast (2,2)\n *\n *   Would become:\n *\n *            data\n *             |\n *     batch_matmul+elemwise/bcast (2,2,2)\n */\nclass ParallelOpBatchCombiner : public ParallelOpCombiner {\n public:\n  /*\n   * \\brief Constructor.\n   * \\param op_name name of op to combine\n   * \\param batch_op_name name of op that combined branches will be joined into\n   * \\param min_num_branches min number of parallel branches beginning with op\n   *                         to start combining\n   */\n  ParallelOpBatchCombiner(const std::string& op_name, const std::string& batch_op_name,\n                          uint64_t min_num_branches);\n\n protected:\n  /*\n   * \\brief Checks if node is supported to be combined\n   * \\param n node in question\n   * \\return True by default\n   */\n  virtual bool IsSupportedOp(const CallNode* n);\n\n  /*\n   * \\brief Checks if two ops can be combined\n   * \\param a node a\n   * \\param b node b\n   * \\return True if shapes and dtypes of all args of a and b are the same\n   */\n  virtual bool CanOpsBeCombined(const CallNode* a, const CallNode* b);\n\n  /*\n   * \\brief Makes combined op from parallel ops in branches. This usually involves\n   *        concatenating or stacking inputs, then creating a new call.\n   * \\param branches branches that are to be combined\n   * \\return new call with branches combined as batch op by stacking args\n   */\n  virtual Call MakeCombinedOp(const Group& branches);\n\n  /*\n   * \\brief Checks if argument of op following combined ops are able to be combined\n   * \\param a node a\n   * \\param b node b\n   * \\param index index of argument in question\n   * \\return True if shapes and dtypes of args[index] a and b are the same\n   */\n  bool IsArgCompatible(const CallNode* a, const CallNode* b, size_t index) final;\n\n  /*\n   * \\brief Create combined call from ops that follow the initial combined op at the depth-th level.\n   *        This usually involves concatenating or stacking inputs, then creating a new call.\n   *        Only called if IsArgCompatbile returns true for each arg.\n   * \\param data combined op\n   * \\param branches branches of parallel ops to be combined\n   * \\param depth depth at which to combine ops\n   * \\param parent_index index of arg that corresponds to original input that was shared among\n   *                     all combined ops\n   * \\return new combined call as batch op by stacking args\n   */\n  Call MakeCombinedCallFromFollowingOps(const Expr& data, const Group& branches, size_t depth,\n                                        size_t parent_index) final;\n\n  /*\n   * \\brief Updates map of expr to substitute with combined expr. This usually involves\n   *        slicing or splitting data.\n   * \\param data combined op\n   * \\param branches branches of parallel ops to be combined\n   * \\param depth depth at which to substitute\n   * \\param subst_map map of Expr to replace with Expr to replace it with\n   */\n  void UpdateGroupOutput(const Expr& data, const Group& branches, size_t depth,\n                         ExprSubstMap* subst_map) final;\n\n private:\n  /* \\brief name of op to replace combined ops with. for example,\n   *         for combining parallel dense, this will will be set to\n   *         nn.batch_matmul\n   */\n  std::string batch_op_name_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_COMBINE_PARALLEL_OP_BATCH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/compiler_function_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/transforms/compiler_function_utils.h\n * \\brief Helper passes for working with functions with the \"Compiler\" attribute.\n *\n * Those wishing to use the \"RelayToTIR\" custom pass machinery to do IRModule-at-a-time external\n * codegen may find the following helpers useful:\n *\n *  - The \\p OutlineCompilerFunctionsWithExistingGlobalSymbols pass will lift inline functions with\n *    a matching \"Compiler\" attribute to be global functions, using the \"global_symbol\" attribute\n *    already assigned. Can be used before custom lowering.\n *\n *    Note that ideally \"Compiler\" attributed functions would be made global functions as early as\n *    possible and would stay that way. However, the GraphExecutorCodegen and AOTExecutorCodegen\n *    assume the entire model can be represented by a single 'main' function, and the Inline pass\n *    is run to respect that assumption. So this pass is mostly just to undo that Pass after modules\n *    have passed through the 'codegen' keyhole.\n *\n *    See also OutlineCompilerFunctionsMutator in src/relay/backend/contrib/ethosu/codegen.cc.\n *\n *  - (The \\p OutlineCompilerFunctions pass is a more general version of the above which can use\n *    a custom cache to both allocate \"global_symbol\" names and ensure two structurally equal\n *    functions are assigned the same name, and thus lowered only once. This is used by Collage\n *    when preparing the optimally partitioned IRModule).\n *\n *  - The \\p MarkCompilerFunctionsAsExtern pass will update the attributes of global functions\n *    with a matching \"Compiler\" attribute to have just the \"Extern\" attribute. That will signal\n *    the function has been dealt with. However calls to such functions will be left unchanged.\n *    Can be used after lowering to cleanup the IRModule.\n *\n *  - The \\p InlineCompilerFunctions pass can selectively inline global functions with a matching\n *    \"Compiler\" attribute who's name appears in the given set. Obviously it's more sensible to\n *    not create that function in the first place, however some external codegen have rules to\n *    accept or reject partitionings based on the overall partitioned function body. This pass\n *    can be used do the legwork, and will take care to not only inline the outer \"Compiler\"\n *    annotated funcition, but also any \"Composite\" annotated functions in its body.\n */\n\n#ifndef TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_\n#define TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n\n#include \"tvm/ir/transform.h\"\n#include \"tvm/relay/function.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\n/*!\n * \\brief Abstract class representing a cache of unique global vars keyed by functions. This can\n * be used to ensure structurally equal functions are assigned the same global var object, and\n * thus lowered at most once.\n */\nclass GlobalSymbolCache {\n public:\n  virtual ~GlobalSymbolCache();\n  virtual GlobalVar GetGlobalSymbol(const Function& function) = 0;\n};\n\n/*!\n * \\brief A \\p GlobalSymbolCache that requires every \"Compiler\" attributed function to already\n * have a \"global_symbol\" attribute.\n */\nclass ExistingGlobalSymbolCache : public GlobalSymbolCache {\n public:\n  ExistingGlobalSymbolCache() = default;\n\n  GlobalVar GetGlobalSymbol(const Function& function) final;\n\n private:\n  /*! \\brief Maps already seen global symbol names to their corresponding GlobalVar objects. */\n  std::unordered_map<std::string, GlobalVar> global_vars_;\n};\n\n/*!\n * \\brief A pass to outline all let-bound and literal functions in direct call positions which have\n * a \"Compiler\" attribute. The given \\p GlobalSymbolCache is used to determine a unique global\n * symbol for each function, which is also assigned to the \"global_symbol\" attribute of the new\n * global function.\n *\n * At most one function with the same global symbol is outlined.\n *\n * If \\p compiler_filter is non-empty only functions with that as their attribute value are\n * outlined.\n */\ntvm::transform::Pass OutlineCompilerFunctions(std::shared_ptr<GlobalSymbolCache> cache,\n                                              std::string compiler_filter = \"\");\n\n/*!\n * \\brief A pass to outline all let-bound and literal functions in direct call positions which have\n * a \"Compiler\" attribute. The functions are bound to unique global vars according to their\n * existing \"global_symbol\" attribute. At most one function with the same global symbol is outlined.\n *\n * If \\p compiler_filter is non-empty only functions with that as their attribute value are\n * outlined.\n *\n * This pass may be useful for external codegen using the \"RelayToTIR\" custom pass mechanism\n * to prepare the IRModule before custom lowering.\n */\ntvm::transform::Pass OutlineCompilerFunctionsWithExistingGlobalSymbols(\n    std::string compiler_filter = \"\");\n\n/*!\n * \\brief A pass to mark all global functions which have a \"Compiler\" attribute matching\n * compiler_filter as 'extern' by replacing all attributes with a single \"Extern\" attribute.\n * Calls to such functions are not changed.\n *\n * If \\p compiler_filter is non-empty only functions with that as their attribute value are\n * outlined.\n *\n * This pass may be useful for external codegen using the \"RelayToTIR\" custom pass mechanism to\n * cleanup the IRModule after custom lowering.\n */\ntvm::transform::Pass MarkCompilerFunctionsAsExtern(std::string compiler_filter = \"\");\n\n/*!\n * \\brief A pass to inline all global \"Compiler\" functions which are bound to a global var\n * in \\p global_vars. Both the global function and any calls to \"Composite\" functions it its body\n * are inlined.\n *\n * This pass may be useful for external codegen which needs to undo partitioning based on\n * properties of the entire partition.\n */\ntvm::transform::Pass InlineCompilerFunctionsBoundTo(Array<GlobalVar> global_vars);\n\n}  // namespace transform\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/device_aware_visitors.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/transforms/device_aware_visitors.h\n * \\brief Visitors which track the device for the current Relay expression and Relay Vars.\n */\n\n#ifndef TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_\n#define TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_\n\n#include <dlpack/dlpack.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/function.h>\n\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../op/annotation/annotation.h\"\n#include \"../op/memory/on_device.h\"\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\n/*!\n * \\brief Helper class for expression transformers which need to keep track of the \\p VirtualDevice\n * holding the results of expressions. This is recovered from function attributes and \"on_device\"\n * CallNodes added by the PlanDevices pass.\n *\n * \\sa \\p DeviceAwareExpr{Functor,Visitor,Mutator}.\n */\nclass LexicalOnDeviceMixin {\n protected:\n  explicit LexicalOnDeviceMixin(const Optional<IRModule>& maybe_mod);\n\n  /*!\n   * \\brief Returns the \\p VirtualDevice on which the result of \\p expr should/will be stored,\n   * assuming {Push,Pop}{VirtualDevice,BoundVar} have been correctly called. May return the\n   * unconstrained \\p VirtualDevice if the device planning pass has not been run.\n   */\n  VirtualDevice GetVirtualDevice(const Expr& expr) const;\n\n  /*! \\brief Indicate a function body is being entered. */\n  void EnterFunctionBody();\n\n  /*! \\brief Indicate a function body has been processed. */\n  void ExitFunctionBody();\n\n  /*! \\brief Push an \\p VirtualDevice onto the lexical VirtualDevice stack. Ignore if unconstrained.\n   */\n  void PushVirtualDevice(const VirtualDevice& virtual_device);\n\n  /*! \\brief Pop an \\p VirtualDevice from the lexical VirtualDevice stack. Ignore if stack is empty.\n   */\n  void PopVirtualDevice();\n\n  /*! \\brief Remember that \\p var will be stored at \\p virtual_device. Ignore if unconstrained.\n   *\n   * CAUTION: Despite the name we don't support re-entering the same function body.\n   */\n  void PushBoundVar(Var var, const VirtualDevice& virtual_device);\n\n  /*! \\brief Remove the binding for \\p var to its \\p VirtualDevice. Ignore if var is not bound. */\n  void PopBoundVar(const Var& var);\n\n  /*!\n   * \\brief Returns the number of function definitions wrapping the currently visited expression.\n   */\n  int function_nesting() const { return function_nesting_; }\n\n private:\n  /*!\n   * \\brief The number of function bodies entered. Since many transforms need to distinguish global\n   * functions from local functions this supports the mixin's \\p is_global() helper method.\n   */\n  int function_nesting_ = 0;\n\n  /*!\n   * \\brief The stack of lexically enclosing \"on_device\" \\p VirtualDevices, from outermost to\n   * innermost. When visiting an expression other than a variable we can assume the expression's\n   * result is to be stored on \\p expr_virtual_devices.back().\n   */\n  std::vector<VirtualDevice> expr_virtual_devices_;\n\n  /*!\n   * \\brief A map from in-scope local variables to their \\p VirtualDevices. We may assume the\n   * variable is only ever bound to a value stored on this \\p VirtualDevice at runtime.\n   *\n   * Note: We're playing it safe and keying by object refs here just in case the Relay expression\n   * being rewritten has no module or other global to keep it alive.\n   */\n  std::unordered_map<Var, VirtualDevice, runtime::ObjectPtrHash, runtime::ObjectPtrEqual>\n      var_virtual_devices_;\n\n  /*!\n   * \\brief A map from global variables to their \\p VirtualDevices, ie the \"result_virtual_device\"\n   * of the function they are bound to in the module we are working on. We calculate and store this\n   * explicitly so that we don't need to hold on to any module, which is often in the process of\n   * being rewritten.\n   */\n  std::unordered_map<GlobalVar, VirtualDevice, runtime::ObjectPtrHash, runtime::ObjectPtrEqual>\n      global_var_virtual_devices_;\n};\n\ntemplate <typename FType>\nclass DeviceAwareExprFunctor;\n\n/*!\n * \\brief ExprFunctor which tracks \\p VirtualDevices. We only support 'visitor' style implementation\n * with no additional arguments, thus this is equivalent to \\p DeviceAwareExprVisitor without\n * any memoization.\n */\ntemplate <>\nclass DeviceAwareExprFunctor<void(const Expr& n)> : public ExprFunctor<void(const Expr& n)>,\n                                                    public LexicalOnDeviceMixin {\n private:\n  using TSuper = ExprFunctor<void(const Expr& n)>;\n\n public:\n  explicit DeviceAwareExprFunctor(const Optional<IRModule>& maybe_mod)\n      : LexicalOnDeviceMixin(maybe_mod) {}\n\n  void VisitExpr_(const FunctionNode* function_node) {\n    if (function_node->HasNonzeroAttr(attr::kPrimitive)) {\n      // No tracking inside primitive functions.\n      return DeviceAwareVisitExpr_(function_node);\n    } else {\n      // Function parameters come into scope.\n      for (auto param : function_node->params) {\n        PushBoundVar(param, param->virtual_device());\n      }\n      // Entering scope of function body.\n      VirtualDevice virtual_device = function_node->virtual_device();\n      VLOG(2) << \"entering \" << virtual_device << \" for function:\" << std::endl\n              << PrettyPrint(GetRef<Function>(function_node));\n      PushVirtualDevice(virtual_device);\n      EnterFunctionBody();\n\n      DeviceAwareVisitExpr_(function_node);\n\n      // Leaving scope of function body.\n      ExitFunctionBody();\n      PopVirtualDevice();\n      VLOG(2) << \"leaving \" << virtual_device << \" for function:\" << std::endl\n              << PrettyPrint(GetRef<Function>(function_node));\n      // Function parameters go out of scope.\n      for (size_t i = 0; i < function_node->params.size(); ++i) {\n        PopBoundVar(function_node->params[i]);\n      }\n    }\n  }\n\n  void VisitExpr_(const LetNode* let_node) {\n    PreVisitLetBlock_(let_node);\n    std::vector<const LetNode*> bindings;\n    Expr expr = GetRef<Expr>(let_node);\n    while (const auto* inner_let_node = expr.as<LetNode>()) {\n      // Let-bound var (in pre visited version) goes into scope.\n      // (We'll just assume this is a letrec.)\n      VirtualDevice virtual_device = GetVirtualDevice(inner_let_node->value);\n      VLOG(2) << \"var '\" << inner_let_node->var->name_hint() << \"' has virtual device \"\n              << virtual_device;\n      PushBoundVar(inner_let_node->var, virtual_device);\n      PreVisitLetBinding_(inner_let_node->var, inner_let_node->value);\n      bindings.emplace_back(inner_let_node);\n      expr = inner_let_node->body;\n    }\n\n    VisitExpr(expr);\n\n    for (auto itr = bindings.rbegin(); itr != bindings.rend(); ++itr) {\n      // Let-bound var goes out of scope.\n      const LetNode* visited_let_node = *itr;\n      PopBoundVar(visited_let_node->var);\n      PostVisitLet_(visited_let_node);\n    }\n    PostVisitLetBlock_(let_node);\n  }\n\n  void VisitExpr_(const CallNode* call_node) {\n    OnDeviceProps props = GetOnDeviceProps(call_node);\n    if (props.body.defined() && props.is_fixed()) {\n      // Entering lexical scope of \"on_device\" call.\n      VLOG(2) << \"entering \" << props.virtual_device << \" for on_device:\" << std::endl\n              << PrettyPrint(GetRef<Call>(call_node));\n      PushVirtualDevice(props.virtual_device);\n      VisitExpr(props.body);\n      // Leaving lexical scope of \"on_device\" call.\n      PopVirtualDevice();\n      VLOG(2) << \"leaving \" << props.virtual_device << \" for on_device:\" << std::endl\n              << PrettyPrint(GetRef<Call>(call_node));\n    } else {\n      DeviceAwareVisitExpr_(call_node);\n    }\n  }\n\n  /*!\n   * \\brief These are as for VisitExpr_. \\p VirtualDevices for expressions and function parameters\n   * will be tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For\n   * functions the function_nesting count will already include that of \\p function_node.\n   */\n\n  virtual void DeviceAwareVisitExpr_(const FunctionNode* function_node) {\n    return TSuper::VisitExpr_(function_node);\n  }\n\n  virtual void DeviceAwareVisitExpr_(const CallNode* call_node) {\n    return TSuper::VisitExpr_(call_node);\n  }\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions before any let bindings or final\n   * body has been visited. Default implementation is a no-op.\n   */\n  virtual void PreVisitLetBlock_(const LetNode* let_node) { /* no-op */\n  }\n\n  /*!\n   * \\brief Visit a let-bound expression before the let body has been visited. Devices for the\n   * let-bound variable will be tracked automatically. Default implementation just visits var and\n   * value.\n   */\n  virtual void PreVisitLetBinding_(const Var& var, const Expr& value) {\n    VisitExpr(var);\n    VisitExpr(value);\n  }\n\n  /*!\n   * \\brief Visit a let expression after the let-bound value and body have been visited.\n   * Default implementation is a no-op.\n   */\n  virtual void PostVisitLet_(const LetNode* let_node) { /* no-op */\n  }\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions after it has been visited.\n   * Default implementation is a no-op.\n   */\n  virtual void PostVisitLetBlock_(const LetNode* let_node) {}\n};\n\n/*! \\brief ExprVisitor which tracks \\p VirtualDevices. */\nclass DeviceAwareExprVisitor : public ExprVisitor, public LexicalOnDeviceMixin {\n public:\n  explicit DeviceAwareExprVisitor(const Optional<IRModule>& maybe_mod)\n      : LexicalOnDeviceMixin(maybe_mod) {}\n\n  using ExprVisitor::VisitExpr_;\n\n  void VisitExpr_(const FunctionNode* function_node) final;\n  void VisitExpr_(const LetNode* let_node) final;\n  void VisitExpr_(const CallNode* call_node) final;\n\n  /*!\n   * \\brief These are as for VisitExpr_. \\p VirtualDevices for expressions and function parameters\n   * will be tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For\n   * functions the function_nesting count will already include that of \\p function_node.\n   */\n  virtual void DeviceAwareVisitExpr_(const FunctionNode* function_node);\n  virtual void DeviceAwareVisitExpr_(const CallNode* call_node);\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions before any let bindings or final\n   * body has been visited. Default implementation is a no-op.\n   */\n  virtual void PreVisitLetBlock_(const LetNode* let_node);\n\n  /*!\n   * \\brief Visit a let-bound expression before the let body has been visited. \\p VirtualDevices for\n   * the let-bound variable will be tracked automatically. Default implementation just visits var\n   * and value.\n   */\n  virtual void PreVisitLetBinding_(const Var& var, const Expr& value);\n\n  /*!\n   * \\brief Visit a let expression after the let-bound value and body have been visited.\n   * Default implementation is a no-op.\n   */\n  virtual void PostVisitLet_(const LetNode* let_node);\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions after it has been visited.\n   * Default implementation is a no-op.\n   */\n  virtual void PostVisitLetBlock_(const LetNode* let_node);\n};\n\n/*! \\brief ExprMutator which tracks \\p VirtualDevices. */\nclass DeviceAwareExprMutator : public ExprMutator, public LexicalOnDeviceMixin {\n public:\n  explicit DeviceAwareExprMutator(const Optional<IRModule>& maybe_mod)\n      : LexicalOnDeviceMixin(maybe_mod) {}\n\n  Expr VisitExpr_(const FunctionNode* function_node) final;\n  Expr VisitExpr_(const LetNode* let_node) final;\n  Expr VisitExpr_(const CallNode* call_node) final;\n\n  /*!\n   * \\brief These are as for VisitExpr_. \\p VirtualDevices for expressions and function parameters\n   * will be tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For\n   * functions the function_nesting count will already include that of \\p function_node.\n   */\n  virtual Expr DeviceAwareVisitExpr_(const FunctionNode* function_node);\n  virtual Expr DeviceAwareVisitExpr_(const CallNode* call_node);\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions before any let bindings or final\n   * body has been visited. Default implementation is a no-op.\n   */\n  virtual void PreVisitLetBlock_(const LetNode* let_node);\n\n  /*!\n   * \\brief Visit a let-bound expression before the let body has been visited. \\p VirtualDevices for\n   * the let-bound variable will be tracked automatically. Default implementation just visits var\n   * and value.\n   */\n  virtual std::pair<Var, Expr> PreVisitLetBinding_(const Var& var, const Expr& value);\n\n  /*!\n   * \\brief Visit a let expression after the let-bound value and body have been visited.\n   * Default implementation just returns a reference to the post-visited node.\n   */\n  virtual Expr PostVisitLet_(const LetNode* pre_let_node, const LetNode* post_let_node);\n\n  /*!\n   * \\brief Visit the first let in a chain of let expressions after it has been visited.\n   * Default implementation returns reference to let node.\n   */\n  virtual Expr PostVisitLetBlock_(const LetNode* pre_let_node, const LetNode* post_let_node);\n};\n\n/*!\n * \\brief Returs a map from Relay expression node to its virtual device using the annotations\n * and \\p virtual_device fields of \\p expr. The map's lifetime must not exceed that of\n * \\p expr itself.\n */\nstd::unordered_map<const ExprNode*, VirtualDevice> RecoverVirtualDeviceMap(const IRModule& mod,\n                                                                           const Expr& expr);\n\n}  // namespace transform\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/device_domains.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/analysis/device_domains.h\n * \\brief Unification domain for the device planner.\n */\n\n#ifndef TVM_RELAY_TRANSFORMS_DEVICE_DOMAINS_H_\n#define TVM_RELAY_TRANSFORMS_DEVICE_DOMAINS_H_\n\n#include <dlpack/dlpack.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/type.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/target/compilation_config.h>\n#include <tvm/target/virtual_device.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\nclass DeviceDomain;\nusing DeviceDomainPtr = std::shared_ptr<DeviceDomain>;\nclass DeviceDomains;\n\n/*!\n * \\brief Represents the domain over which we collect equality constraints.\n *\n * \\code\n *   D ::= ?x?                  -- first order, free\n *       | <virtual_device>     -- first order, bound to specific virtual device\n *       | fn(D1, ..., Dn):Dr   -- higher order\n * \\endcode\n *\n * We require a function value to be on the same device as its result. To support that we need\n * a notion of the 'result domain' of a domain:\n * \\code\n *   result_domain(?x?)                = ?x?\n *   result_domain(<virtual_device>)   = <virtual_device>\n *   result_domain(fn(D1, ..., Dn):Dr) = result_domain(Dr)\n * \\endcode\n *\n * TODO(mbs): We currently don't allow sub-VirtualDevice constraints. Eg for a function we can\n * express that the argument and result VirtualDevices must be exactly equal, but we cannot express\n * that though the devices and targets for arguments and results must be equal, it is ok for\n * memory scopes to differ. At the moment we can get away with this since we run PlanDevices\n * twice: once with all memory scopes unconstrained, then again with just memory scopes as\n * the new property to flow. However we're on thin ice here and better would be to allow\n * constraints on VirtualDevices to be exploded into their device/target component and their\n * memory scope component. Should we fold layout constraints into VirtualDevices then they would\n * probably be grouped with memory scopes.\n */\nclass DeviceDomain {\n public:\n  /*!\n   * \\brief Constructs a first-order domain for \\p virtual_device, which may be\n   * fully free (ie virtual_device is unconstrained), partially  free (ie virtual_device has at\n   * least on of its target, device id or memory scopes known), or fully fixed (ie virtual_device\n   * has its target, device id and memory scopes set).\n   *\n   * CAUTION: Use DeviceDomains::MakeFirstOrderDomain instead of this ctor.\n   */\n  explicit DeviceDomain(VirtualDevice virtual_device)\n      : virtual_device_(std::move(virtual_device)) {}\n\n  /*!\n   * \\brief Constructs a higher-order domain, where \\p args_and_result contain the\n   * function argument and result domains in order.\n   *\n   * CAUTION: Use DeviceDomains::MakeHigherOrderDomain instead of this ctor.\n   */\n  explicit DeviceDomain(std::vector<DeviceDomainPtr> args_and_result)\n      : virtual_device_(VirtualDevice::FullyUnconstrained()),\n        args_and_result_(std::move(args_and_result)) {}\n\n  bool is_higher_order() const { return !args_and_result_.empty(); }\n\n  VirtualDevice first_order_virtual_device() const {\n    ICHECK(args_and_result_.empty()) << \"expecting domain to be first-order\";\n    return virtual_device_;\n  }\n\n  size_t function_arity() const {\n    ICHECK(!args_and_result_.empty()) << \"expecting domain to be higher-order\";\n    return args_and_result_.size() - 1UL;\n  }\n\n  DeviceDomainPtr function_param(size_t i) const {\n    ICHECK(!args_and_result_.empty()) << \"expecting domain to be higher-order\";\n    ICHECK_LT(i + 1, args_and_result_.size()) << \"parameter index is out of range\";\n    return args_and_result_[i];\n  }\n\n  DeviceDomainPtr function_result() const {\n    ICHECK(!args_and_result_.empty());\n    return args_and_result_.back();\n  }\n\n private:\n  /*!\n   * \\brief If this is a function domain then always fully unconstrained. Otherwise will be\n   * fully unconstrained (the domain is still completely free), partially constrained\n   * (for example, the \\p target and \\p device_type are constrained but the \\p virtual_device_id and\n   * \\p memory_scope are still unconstrained), or fully constrained (everything is known).\n   */\n  const VirtualDevice virtual_device_;\n\n  /*!\n   * \\brief If this is a function domain then the sub-domains for each of the function's\n   * arguments, and the domain for its result. Otherwise empty.\n   */\n  const std::vector<DeviceDomainPtr> args_and_result_;\n\n  friend class DeviceDomains;\n};\n\n/*!\n * \\brief Tracks the device domains for a set of expressions w.r.t. an equivalence relation\n * built up by calls to \\p UnifyOrNull.\n */\nclass DeviceDomains {\n public:\n  explicit DeviceDomains(CompilationConfig config);\n\n  const CompilationConfig& config() const { return config_; }\n\n  /*!\n   * \\brief Returns the domain representing \\p virtual_device. If \\p virtual_device is fully\n   * constrained then the domain will be unique that \\p virtual_device.\n   */\n  DeviceDomainPtr MakeFirstOrderDomain(const VirtualDevice& virtual_device);\n\n  /*!\n   * \\brief Returns a higher-order domain with \\p args_and_results.\n   */\n  DeviceDomainPtr MakeHigherOrderDomain(std::vector<DeviceDomainPtr> arg_and_results) {\n    return std::make_shared<DeviceDomain>(std::move(arg_and_results));\n  }\n\n  /*!\n   * \\brief Returns a domain appropriate for \\p type who's result domain is bound to \\p\n   * virtual_device. If \\p type is a function then all parameter domains will be completely free. It\n   * is valid for \\p virtual_device to be fully unconstrained.\n   */\n  DeviceDomainPtr MakeDomain(const Type& type, const VirtualDevice& virtual_device);\n\n  /*!\n   * \\brief Returns a domain with the given result appropriate \\p non_canonical_virtual_device,\n   * which cannot be fully unconstrained. We first canonicalize the virtual device to unsure it has\n   * a target and is unique.\n   */\n  DeviceDomainPtr ForVirtualDevice(const Type& type,\n                                   const VirtualDevice& non_canonical_virtual_device);\n\n  /*! \\brief Returns a free domain appropriate for \\p type. */\n  DeviceDomainPtr Free(const Type& type) {\n    return MakeDomain(type, VirtualDevice::FullyUnconstrained());\n  }\n\n  /*! \\brief Returns the domain representing the equivalence class containing \\p domain. */\n  DeviceDomainPtr Lookup(DeviceDomainPtr domain);\n\n  /*!\n   * \\brief Returns the most constrained domain which agrees with both \\p lhs and \\p rhs. Returns\n   * null if no such domain exists, ie some first-order component of \\p lhs is constrained\n   * differently than the corresponding component of \\p rhs.\n   */\n  DeviceDomainPtr JoinOrNull(const DeviceDomainPtr& lhs, const DeviceDomainPtr& rhs);\n\n  /*!\n   * \\brief Unifies \\p lhs and \\p rhs, returning the most-bound of the two. Returns null if\n   * \\p lhs and \\p rhs are not unifiable, in which case the constraint system may be left in\n   * a partially modified state.\n   */\n  // TODO(mbs): I don't think we need an occurs check since the program is well-typed, but\n  // given we have refs to functions I'm prepared to be surprised.\n  DeviceDomainPtr UnifyOrNull(DeviceDomainPtr lhs, DeviceDomainPtr rhs);\n\n  /*\n   * \\brief Force all domains in \\p higher_order_domain to unify with \\p first_order_domain.\n   * This can be used to handle functions within tuples, references and ADTs since we don't\n   * attempt to track anything beyond 'the device' for expressions of those first-order types.\n   *\n   * Returns false if any unification fails.\n   */\n  bool CollapseOrFalse(const DeviceDomainPtr& first_order_domain,\n                       const DeviceDomainPtr& higher_order_domain);\n\n  /*!\n   * \\brief Unifies \\p lhs_first_order and \\p rhs_maybe_higher_order. If \\p rhs_maybe_higher_order\n   * is indeed higher-order, require all of its arguments and result to unify with\n   * \\p lhs_first_order. Otherwise same as \\p Unify. Returns false if unification is not possible.\n   *\n   * In an expression such as:\n   * \\code\n   * (fn(...) {...}, ...).0\n   * \\endcode\n   * we need to force all the devices of the inner function to be the same as the device for the\n   * overall tuple since the device domain does not understand tuples. Similarly for references\n   * and ADTs.\n   */\n  bool UnifyCollapsedOrFalse(const DeviceDomainPtr& lhs_first_order,\n                             const DeviceDomainPtr& rhs_maybe_higher_order);\n\n  /*! \\brief Returns true if a domain is known for \\p expr. */\n  bool contains(const Expr& expr) const { return expr_to_domain_.count(expr.get()); }\n\n  /*! \\brief Returns the domain representing \\p expr. */\n  DeviceDomainPtr DomainFor(const Expr& expr);\n\n  /*!\n   * \\brief Returns the domain representing the callee (ie 'op') in \\p call expression. If the\n   * callee is a primitive or special operation we handle it specially. Otherwise defers to \\p\n   * DomainFor(call->op).\n   *\n   * This special handling is needed:\n   * - To handle the \"on_device\" and \"device_copy\" ops which constrain devices to the given\n   * devices.\n   * - To handle some special ops which constrain devices to the CPU.\n   * - To allow the same primitive to be called on different devices at different call sites.\n   * Since each call to the op can have a different domain we index the ops by the call expression\n   * rather than the op itself.\n   */\n  DeviceDomainPtr DomainForCallee(const Call& call);\n\n  /*!\n   * \\brief Unifies the domains for expressions \\p lhs and \\p rhs.\n   *\n   * Aborts if unification fails.\n   */\n  void UnifyExprExact(const Expr& lhs, const Expr& rhs);\n\n  /*!\n   * \\brief Attempts to unify the domains for expressions \\p lhs and \\p rhs, however if they\n   * cannot be unified then returns with no change to the unification system.\n   */\n  void OptionalUnifyExprExact(const Expr& lhs, const Expr& rhs);\n\n  /*!\n   * \\brief Unifies the domain for \\p expr with \\p expected_domain.\n   *\n   * Aborts if unification fails.\n   */\n  void UnifyExprExact(const Expr& expr, const DeviceDomainPtr& expected_domain);\n\n  /*!\n   * \\brief Unifies the domain for \\p expr with \\p expected_domain.\n   * If \\p expected_domain is higher-order but \\p expr is first-order, require all arguments\n   * and the result of \\p expected_domain to have the same domain as for \\p expr.\n   *\n   * Aborts if unification fails.\n   */\n  void UnifyExprCollapsed(const Expr& expr_first_order,\n                          const DeviceDomainPtr& expected_domain_maybe_higher_order);\n\n  /*! \\brief Returns true if \\p domain is fully constrainted. */\n  bool IsFullyConstrained(DeviceDomainPtr domain);\n\n  /*! \\brief Force all \\p VirtualDevices in \\p domain to default to \\p default_virtual_device. */\n  void SetDefault(DeviceDomainPtr domain, const VirtualDevice& default_virtual_device);\n\n  /*!\n   * \\brief If \\p domain is higher-order default it's result domain to \\p default_virtual_device.\n   * Then force all remaining \\p VirtualDevices to the result domain (freshly defaulted or\n   * original). If \\p domain is first-order same as \\p SetDefault.\n   */\n  void SetResultDefaultThenParams(const DeviceDomainPtr& domain_maybe_higher_order,\n                                  const VirtualDevice& default_virtual_device);\n\n  /*!\n   * \\brief Returns the result domain for \\p domain (see defn in DeviceDomain comment).\n   */\n  DeviceDomainPtr ResultDomain(DeviceDomainPtr domain);\n\n  /*!\n   * \\brief Returns the result \\p VirtualDevice (possibly unconstrained) for \\p domain\n   * (see defn in DeviceDomain comment).\n   */\n  VirtualDevice ResultVirtualDevice(const DeviceDomainPtr& domain) {\n    return ResultDomain(domain)->first_order_virtual_device();\n  }\n\n  /*! \\brief Returns one-line description of \\p domain for debugging. */\n  std::string ToString(DeviceDomainPtr domain);\n\n  /*! \\brief Returns description of entire system of constraints for debugging */\n  std::string ToString();\n\n private:\n  /*! \\brief Intrinsics we need to handle specially. */\n  const Op& alloc_storage_op = Op::Get(\"memory.alloc_storage\");\n  const Op& alloc_tensor_op = Op::Get(\"memory.alloc_tensor\");\n  const Op& shape_of_op = Op::Get(\"vm.shape_of\");\n  const Op& invoke_tvm_op = Op::Get(\"vm.invoke_tvm_op\");\n  const Op& reshape_tensor_op = Op::Get(\"vm.reshape_tensor\");\n\n  CompilationConfig config_;\n\n  /*!\n   * \\brief The domain for first-order expressions of non-tensor type, such as shapes and\n   * buffer dimensions. Generally this will be a CPU.\n   */\n  DeviceDomainPtr host_domain_;\n\n  /*! \\brief Maps expressions to their domains as determined during analysis. */\n  std::unordered_map<const ExprNode*, DeviceDomainPtr> expr_to_domain_;\n\n  /*!\n   * \\brief Maps call expressions to the domains for their callee where the callee is a primitive.\n   */\n  std::unordered_map<const CallNode*, DeviceDomainPtr> call_to_callee_domain_;\n\n  /*! \\brief Maps device domains to their equivalent domains as determined during unification. */\n  std::unordered_map<DeviceDomainPtr, DeviceDomainPtr> domain_to_equiv_;\n\n  /*!\n   * \\brief Maps fully constrained \\p VirtualDevices to their corresponding domains. By sharing\n   * those domains we can ensure:\n   *\n   * \\code\n   * domain0 != domain1 && domain0 fully constrained && domain1 fully constrained\n   *   ==> domain0 and domain1 are incompatible\n   * \\endcode\n   */\n  std::unordered_map<VirtualDevice, DeviceDomainPtr, runtime::ObjectPtrHash,\n                     runtime::ObjectPtrEqual>\n      fully_constrained_virtual_device_to_domain_;\n};\n\n}  // namespace transform\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_DEVICE_DOMAINS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/expr_subst.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file expr_subst.h\n * \\brief Utility functions for substituting expressions.\n */\n#ifndef TVM_RELAY_TRANSFORMS_EXPR_SUBST_H_\n#define TVM_RELAY_TRANSFORMS_EXPR_SUBST_H_\n#include <tvm/relay/expr.h>\n\n#include <unordered_map>\n\nnamespace tvm {\nnamespace relay {\n\nExpr ExprSubst(const Expr& expr,\n               std::unordered_map<Expr, Expr, ObjectPtrHash, ObjectPtrEqual> subst_map);\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_EXPR_SUBST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/fake_quantization_to_integer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/transforms/fake_quantization_to_integer.h\n * \\brief Extract subgraph of a fake quantized region.\n */\n#ifndef TVM_RELAY_TRANSFORMS_FAKE_QUANTIZATION_TO_INTEGER_H_\n#define TVM_RELAY_TRANSFORMS_FAKE_QUANTIZATION_TO_INTEGER_H_\n\n#include <tvm/ir/affine_type.h>\n#include <tvm/relay/expr_functor.h>\n\n#include <unordered_set>\n\nnamespace tvm {\nnamespace relay {\n\nclass SubgraphExtractor : public ExprVisitor {\n public:\n  const std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual> GetSubgraph(const Expr& expr);\n  const Map<Expr, AffineType> GetAffineTypes();\n  void VisitExpr(const Expr& expr) override;\n\n protected:\n  void VisitExpr_(const CallNode* call_node) override;\n\n private:\n  const Op quantize_op_ = Op::Get(\"qnn.quantize\");\n  const Op dequantize_op_ = Op::Get(\"qnn.dequantize\");\n  bool is_fake_quantized_ = true;\n  Map<Expr, AffineType> affine_types_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_FAKE_QUANTIZATION_TO_INTEGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/fold_constant.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file fold_constant.h\n * \\brief Utility functions for folding constants in expressions.\n */\n#ifndef TVM_RELAY_TRANSFORMS_FOLD_CONSTANT_H_\n#define TVM_RELAY_TRANSFORMS_FOLD_CONSTANT_H_\n\n#include <tvm/relay/expr.h>\n\nnamespace tvm {\nnamespace relay {\nnamespace transform {\n\n/*!\n * \\brief Apply constant folding on an expression.\n *\n * \\param expr The expression to fold.\n * \\param fold_qnn Whether to fold constants for QNN operations.\n * \\returns The new folded expression.\n */\nExpr FoldConstantExpr(const Expr& expr, bool fold_qnn = true);\n\n/*!\n * \\brief Returns \\p expr with any constants expressions evaluated and let-bound constants\n * inlined. Returns \\p expr unchanged if no change.\n *\n * CAUTION: The importers rely on this function returning \\p expr unchanged to preserve sharing\n * from their p.o.v. Furthermore, this function can be called before conversion to ANF so\n * we must avoid all recursion.\n */\nExpr FoldConstantExpr(const Expr& expr, const IRModule& mod, bool fold_qnn);\n\n}  // namespace transform\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_FOLD_CONSTANT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/gradient.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file gradient.h\n * \\brief Utility functions for Automatic Differentiation in Relay.\n */\n#ifndef TVM_RELAY_TRANSFORMS_GRADIENT_H_\n#define TVM_RELAY_TRANSFORMS_GRADIENT_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/function.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\ninline Type GradRetType(const Function& f) {\n  // if type annotations are provided, we will construct a ret type;\n  // otherwise, leave it to be inferred\n  if (!f->ret_type.defined()) {\n    return Type();\n  }\n  std::vector<Type> vt;\n  for (const auto& p : f->params) {\n    if (!p->type_annotation.defined()) {\n      return Type();\n    }\n    vt.push_back(p->type_annotation);\n  }\n\n  return TupleType({f->ret_type, TupleType(vt)});\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_GRADIENT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/infer_layout_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file infer_layout_utils.h\n * \\brief Utility functions to alter the layouts of operators or replace primitive operators with\n          other expressions. This pass can be used for computing convolution in\n          custom layouts or other general weight pre-transformation.\n */\n\n#ifndef TVM_RELAY_TRANSFORMS_INFER_LAYOUT_UTILS_H_\n#define TVM_RELAY_TRANSFORMS_INFER_LAYOUT_UTILS_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/tir/data_layout.h>\n\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include \"pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Returns a new layout where the subordinate factors are adjusted based on the tensor\n *        shape.\n * \\param old_layout The old layout before any transformation.\n * \\param old_shape The shape of the original tensor.\n * \\return The adjusted Layout.\n */\nLayout AdjustSubordinateFactors(const Layout& src_layout, const Layout& old_layout,\n                                const Array<tvm::PrimExpr>& old_shape);\n\nbool Isomorphic(const Layout& lhs, const Layout& rhs);\n\n/*!\n * \\brief Try transforming `old` in as the smae way as how`ref_old` is transformed to `ref_new`.\n * `old` and `ref_old` are expected to describe two broadcastable tensors. Layout with fewer rank\n * will be expanded. For example,\n * if old = 'NW', ref_old = 'NC', ref_new = 'NC1c', then the result is 'NW1w';\n * if old = 'W', ref_old = 'NC', ref_new = 'NC1c', then the result is 'NW1w'.\n * When `old` and `ref_old` are isomorphic (same structure, only differ in naming), the transform\n * is guaranteed to succeed, in which case the function is simply renaming the axes of `ref_new`\n * to conform to `old`'s naming.\n * \\param old The layout to be transformed.\n * \\param ref_old The reference layout before transform.\n * \\param ref_new The reference layout after transform.\n * \\return The transformed layout.\n */\nLayout TryTransformLike(const Layout& old, const Layout& ref_old, const Layout& ref_new);\n\n/*\n * \\brief An output structure to hold results from FInferCorrectLayout calls.\n * \\tparam input_layouts Inferred input layouts.\n * \\tparam output_layouts Inferred output layouts.\n * \\tparam new_attrs Updated attributes consistent with inferred layouts.\n */\nclass InferCorrectLayoutOutputNode : public Object {\n public:\n  Array<Layout> input_layouts;\n  Array<Layout> output_layouts;\n  Attrs new_attrs;\n\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    v->Visit(\"input_layouts\", &input_layouts);\n    v->Visit(\"output_layouts\", &output_layouts);\n    v->Visit(\"new_attrs\", &new_attrs);\n  }\n\n  TVM_DECLARE_BASE_OBJECT_INFO(InferCorrectLayoutOutputNode, Object);\n\n  static constexpr const char* _type_key = \"relay._transform.InferCorrectLayoutOutput\";\n};\n\nclass InferCorrectLayoutOutput : public ObjectRef {\n public:\n  InferCorrectLayoutOutput(Array<Layout> input_layouts, Array<Layout> output_layouts,\n                           Attrs new_attrs) {\n    auto n = make_object<InferCorrectLayoutOutputNode>();\n    n->input_layouts = std::move(input_layouts);\n    n->output_layouts = std::move(output_layouts);\n    n->new_attrs = std::move(new_attrs);\n    data_ = n;\n  }\n  TVM_DEFINE_OBJECT_REF_METHODS(InferCorrectLayoutOutput, ObjectRef, InferCorrectLayoutOutputNode);\n};\n\n/*!\n * \\brief Infer & correct function of node layout. See \\p Layout for layout convention\n * \\param attrs The attribute of the node.\n * \\param new_in_layouts The layouts of input arguments after alter_op_layout.\n *                       This can be undefined, which means we call this function before alternating\n *                       any operators.\n * \\param old_in_layouts The layouts of input arguments before alter_op_layout.\n * \\param old_in_types The types of old input arguments.\n * \\return infer_layout_output Inferred layouts and updated attributes stored in\n *                             InferCorrectLayoutOutput above.\n */\nusing FInferCorrectLayout = runtime::TypedPackedFunc<InferCorrectLayoutOutput(\n    const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types)>;\n\ninline InferCorrectLayoutOutput ElemwiseArbitraryLayout(\n    const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types) {\n  Layout ret;\n\n  if (new_in_layouts.defined()) {\n    ICHECK_GE(new_in_layouts.size(), 1);\n    ret = new_in_layouts[0];\n  } else {\n    for (size_t i = 0; i < old_in_layouts.size(); ++i) {\n      if (old_in_layouts[i].defined()) {\n        ret = old_in_layouts[i];\n        break;\n      }\n    }\n  }\n\n  return InferCorrectLayoutOutput(Array<Layout>(old_in_layouts.size(), ret), {ret}, attrs);\n}\n\nstd::pair<Array<Layout>, Array<Layout>> BinaryBroadcastLayoutHelper(\n    const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types);\n\n/*! \\brief Infer layout for binary broadcast operators */\ninline InferCorrectLayoutOutput BinaryBroadcastLayout(const Attrs& attrs,\n                                                      const Array<Layout>& new_in_layouts,\n                                                      const Array<Layout>& old_in_layouts,\n                                                      const Array<tvm::relay::Type>& old_in_types) {\n  auto inferred_layout =\n      BinaryBroadcastLayoutHelper(attrs, new_in_layouts, old_in_layouts, old_in_types);\n  return InferCorrectLayoutOutput(inferred_layout.first, inferred_layout.second, attrs);\n}\n\n}  //  namespace relay\n}  //  namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_INFER_LAYOUT_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/let_list.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file let_list.h\n * \\brief LetList record let binding and insert let expression implicitly.\n *  using it, one can treat AST as value instead of expression,\n *  and pass them around freely without fear of AST explosion (or effect duplication).\n *  for example, if one write 'b = a + a; c = b + b; d = c + c', the AST will contain 8 'a'.\n *  if one instead write 'b = ll.Push(a + a); c = ll.Push(b + b); d = ll.Get(c + c);',\n *  the AST will contain 2 'a', as b and c are now variables.\n */\n#ifndef TVM_RELAY_TRANSFORMS_LET_LIST_H_\n#define TVM_RELAY_TRANSFORMS_LET_LIST_H_\n\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/expr.h>\n\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"tvm/relay/type.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief LetList allow you to transform expression into variables, so you can copy them around.\n *  one can insert into the LetList by calling Push, and wrap an expression with bindings with Get.\n *  additionally, there is the 'With' function, which automatically call Get.\n */\nclass LetList {\n public:\n  ~LetList() {\n    if (lets_.size() > 0 && !used_) {\n      LOG(WARNING) << \"letlist not used\";\n    }\n  }\n  /*!\n   * \\brief insert a binding.\n   *\n   * \\param pv the var of the binding.\n   *\n   * \\param expr the value of the binding.\n   *\n   * \\return a Var that hold the inserted expr.\n   */\n  Var Push(Var pv, Expr expr) {\n    ICHECK(!used_);\n    ICHECK(WellFormed(expr)) << \"expression:\" << std::endl << PrettyPrint(expr);\n    lets_.emplace_back(std::make_pair(pv, expr));\n    return pv;\n  }\n\n  /*!\n   * \\brief insert a binding.\n   *\n   * \\param expr the value of the binding.\n   *\n   * \\param ty the type of the binding.\n   *\n   * \\return a Var that hold the inserted expr.\n   */\n  Var Push(Expr expr, Type ty) { return Push(Var::GenSym(ty), expr); }\n\n  /*!\n   * \\brief insert a binding.\n   *\n   *  \\param expr the value of the binding.\n   *\n   *  \\return a Var that hold the inserted expr.\n   */\n  Var Push(Expr expr) { return Push(expr, Type()); }\n\n  /*!\n   * \\brief wrap an expr around the LetList.\n   *\n   *  \\param body the Expression to be wrapped around.\n   *\n   *  \\return the wrapped expr.\n   */\n  Expr Get(const Expr& body) {\n    ICHECK(!used_);\n    Expr ret = body;\n    for (auto rit = lets_.rbegin(); rit != lets_.rend(); ++rit) {\n      ret = Let(std::get<0>(*rit), std::get<1>(*rit), ret);\n    }\n    used_ = true;\n    return ret;\n  }\n\n  /*! \\brief get the number of let bindings in the let list.\n   *\n   *  \\return the let list size.\n   */\n  size_t size() const { return lets_.size(); }\n\n  /*! \\brief generate an LetList and wrap the result automatically.\n   *\n   *  \\param f a function that generate the unwrapped Expr.\n   *\n   *  \\code\n   *  // Example code that generate `16 * a` using 4 plus instead of 15 plus.\n   *  Expr mult_sixteen(const Var& a) {\n   *    Op plus = Op::Get(\"plus\");\n   *    // Automatically call Get with LetList::With\n   *    return LetList::With([&](LetList* ll) {\n   *      // Turn a call to plus into a variable to avoid duplication of code\n   *      Var b = ll->Push(Call(plus, {a, a}));\n   *      Var c = ll->Push(Call(plus, {b, b}));\n   *      Var d = ll->Push(Callplus, {c, c}));\n   *      return Call(plus, {d, d});\n   *    });\n   *  }\n   *  \\endcode\n   *\n   *  \\return the wrapped Expr.\n   */\n  template <typename F>\n  static Expr With(F&& f) {\n    LetList ll;\n    return ll.Get(f(&ll));\n  }\n\n  static Expr LetBind(const Expr& e, const std::function<Expr(const Var&)>& f) {\n    return With([&](LetList* ll) { return f(ll->Push(e)); });\n  }\n\n private:\n  std::vector<std::pair<Var, Expr>> lets_;\n  bool used_ = false;\n};\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_LET_LIST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/meta_schedule_layout_rewrite.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RELAY_TRANSFORMS_META_SCHEDULE_LAYOUT_REWRITE_H_\n#define TVM_RELAY_TRANSFORMS_META_SCHEDULE_LAYOUT_REWRITE_H_\n\n#include <tvm/relay/expr_functor.h>\n#include <tvm/tir/index_map.h>\n\nnamespace tvm {\nnamespace relay {\n\nclass MetaScheduleLayoutRewriter : public ExprMutator {\n public:\n  Expr VisitExpr_(const CallNode* n) final;\n\n  static void LayoutQueuePush(const tir::IndexMap& index_map);\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_META_SCHEDULE_LAYOUT_REWRITE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/pass_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file tvm/relay/_transforms/pass_utils.h\n * \\brief Utilities for writing passes\n */\n#ifndef TVM_RELAY_TRANSFORMS_PASS_UTILS_H_\n#define TVM_RELAY_TRANSFORMS_PASS_UTILS_H_\n\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/expr_functor.h>\n#include <tvm/relay/op.h>\n\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n\n#include \"../analysis/dependency_graph.h\"\n#include \"../op/annotation/annotation.h\"\n#include \"../op/memory/on_device.h\"\n#include \"./let_list.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Check if expr is positive constant.\n * \\param expr The expression to be checked.\n * \\return Whether all elements of expr is positive constant.\n */\nbool IsAllPositiveConstant(const Expr& expr);\n\n/*!\n * \\brief Substitute var with subst.\n * \\param type The type to be substituted.\n * \\param tvar The type variable to be substituted.\n * \\param subst The target of substitution.\n * \\return The substituted result.\n */\nType TypeSubst(const Type& type, const TypeVar& tvar, const Type& subst);\n\n/*!\n * \\brief Substitute var with subst.\n * \\param expr The expr to be substituted.\n * \\param tvar The type variable to be substituted.\n * \\param subst The target of substitution.\n * \\return The substituted result.\n */\nExpr TypeSubst(const Expr& expr, const TypeVar& tvar, const Type& subst);\n\n/*!\n * \\brief Substitute type vars in type.\n * \\param type The type to be substituted.\n * \\param subst_map The map of substitution.\n * \\return The substituted result.\n */\nType TypeSubst(const Type& type, const tvm::Map<TypeVar, Type>& subst_map);\n\n/*!\n * \\brief Substitute type vars in type.\n * \\param expr The expr to be substituted.\n * \\param subst_map The map of substitution.\n * \\return The substituted result.\n */\nExpr TypeSubst(const Expr& expr, const tvm::Map<TypeVar, Type>& subst_map);\n\n/*!\n * \\brief Check if type is dynamic.\n * \\param ty The type to be checked.\n * \\return Whether the type is dynamic.\n */\nbool IsDynamic(const Type& ty);\n\n/*!\n * \\brief Check if call is data dependent.\n * \\param call The call to be checked.\n * \\return Whether the call is data dependent.\n */\nbool IsDataDependent(const CallNode* call);\n\n/*!\n * \\brief Make arbitrary transformation preserve the out most function.\n * \\param func The transformation.\n * \\param e The expression\n * \\return the transformed expression. If e is a function the return is also a function.\n */\ninline Expr TransformF(const std::function<Expr(const Expr&)>& func, const Expr& e) {\n  if (const FunctionNode* f = e.as<FunctionNode>()) {\n    return WithFields(GetRef<Function>(f), f->params, func(f->body));\n  } else {\n    return func(e);\n  }\n}\n\n/*!\n * \\brief Decide whether the expression atomic or not?\n * \\param e the expression\n * \\return\n *   is it atomic?\n *   if so, the compute cost of the expression is bounded so it can be copy without graph mode.\n */\ninline bool IsAtomic(const Expr& expr) {\n  Expr true_expr = IgnoreOnDevice(expr);\n  return true_expr.as<VarNode>() || true_expr.as<OpNode>() || true_expr.as<ConstructorNode>() ||\n         true_expr.as<GlobalVarNode>() ||\n         true_expr.as<ConstantNode>();  // Constant is always by reference.\n}\n\n/*!\n * \\brief Cache the compiler_begin annotation op to reduce registry lookup overhead\n * \\param void\n * \\return compiler_begin op\n */\ninline const Op& CompilerBeginOp() {\n  static auto op = Op::Get(\"annotation.compiler_begin\");\n  return op;\n}\n\n/*!\n * \\brief Cache the compiler_end annotation op to reduce registry lookup overhead\n * \\param void\n * \\return compiler_end op\n */\ninline const Op& CompilerEndOp() {\n  static auto op = Op::Get(\"annotation.compiler_end\");\n  return op;\n}\n\ntemplate <typename ConditionObjectPtr>\nstruct TreeNode {\n  typedef std::shared_ptr<TreeNode<ConditionObjectPtr>> pointer;\n  virtual ~TreeNode() {}\n};\n\ntemplate <typename ConditionObjectPtr>\nstruct TreeLeafNode : TreeNode<ConditionObjectPtr> {\n  using TreeObjectPtr = typename TreeNode<ConditionObjectPtr>::pointer;\n\n  Expr body;\n\n  explicit TreeLeafNode(Expr body) : body(body) {}\n\n  static TreeObjectPtr Make(Expr body) { return std::make_shared<TreeLeafNode>(body); }\n\n  ~TreeLeafNode() {}\n};\n\ntemplate <typename ConditionObjectPtr>\nstruct TreeLeafFatalNode : TreeNode<ConditionObjectPtr> {\n  using TreeObjectPtr = typename TreeNode<ConditionObjectPtr>::pointer;\n\n  TreeLeafFatalNode() = default;\n\n  static TreeObjectPtr Make() { return std::make_shared<TreeLeafFatalNode>(); }\n\n  ~TreeLeafFatalNode() {}\n};\n\ntemplate <typename ConditionObjectPtr>\nstruct TreeBranchNode : TreeNode<ConditionObjectPtr> {\n  using TreeObjectPtr = typename TreeNode<ConditionObjectPtr>::pointer;\n\n  ConditionObjectPtr cond;\n  TreeObjectPtr then_branch;\n  TreeObjectPtr else_branch;\n\n  TreeBranchNode(ConditionObjectPtr cond, TreeObjectPtr then_branch, TreeObjectPtr else_branch)\n      : cond(cond), then_branch(then_branch), else_branch(else_branch) {}\n\n  static TreeObjectPtr Make(ConditionObjectPtr cond, TreeObjectPtr then_branch,\n                            TreeObjectPtr else_branch) {\n    return std::make_shared<TreeBranchNode>(cond, then_branch, else_branch);\n  }\n\n  ~TreeBranchNode() {}\n};\n\nstruct ScopeNode;\nusing Scope = std::shared_ptr<ScopeNode>;\nusing NodeScopeMap = std::unordered_map<DependencyGraph::Node*, Scope>;\nusing ExprSet = std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual>;\n\n/* Invariant: when parent is null level is 0\n * Invariant: when parent is not null level is 1 + parent->level\n */\nstruct ScopeNode {\n  // the level of the scope\n  size_t level;\n  // the parent scope\n  Scope parent;\n  // the corresponding let list which holds all let bindings in the scope\n  std::shared_ptr<LetList> let_list = std::make_shared<LetList>();\n  explicit ScopeNode(const Scope& parent) : level(1 + parent->level), parent(parent) {}\n  ScopeNode() : level(0) {}\n};\n\n/*! \\brief Calculate the scope of nodes in the dependency graph by least common ancestor.\n *\n *  \\param dg the input dependency graph\n *  \\param expr_scope the output node -> scope mapping for all nodes.\n *  \\param lifted_exprs the output set of expressions whose scope is lifted due to dependency\n */\nstd::pair<NodeScopeMap, ExprSet> CalcScope(const DependencyGraph& dg);\n\n/*! \\brief find the least common ancestor of lhs scope and rhs scope.\n */\nScope LCA(Scope lhs, Scope rhs);\n\n// For basic block normal form.\nExpr ToBasicBlockNormalFormAux(const Expr& e);\n\n// ToANormalForm for expressions and as a Pass are declared in transform.h\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_PASS_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/pattern_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file tvm/relay/transforms/pattern_utils.h\n * \\brief Header of internal operator functions\n *  These can be used for writing passes.\n */\n#ifndef TVM_RELAY_TRANSFORMS_PATTERN_UTILS_H_\n#define TVM_RELAY_TRANSFORMS_PATTERN_UTILS_H_\n\n#include <builtin_fp16.h>\n#include <tvm/node/structural_equal.h>\n#include <tvm/relay/analysis.h>\n#include <tvm/relay/attrs/nn.h>\n#include <tvm/relay/attrs/reduce.h>\n#include <tvm/relay/attrs/transform.h>\n#include <tvm/relay/expr.h>\n#include <tvm/relay/op.h>\n#include <tvm/relay/op_attr_types.h>\n#include <tvm/runtime/registry.h>\n#include <tvm/tir/data_layout.h>\n\n#include <limits>\n#include <optional>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"../backend/utils.h\"\n#include \"../op/make_op.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Dispatch DataType to the C++ data type\n *  during runtime.\n */\n#define TVM_DTYPE_DISPATCH(type, DType, ...)                                          \\\n  if (type == DataType::Float(64)) {                                                  \\\n    typedef double DType;                                                             \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Float(32)) {                                           \\\n    typedef float DType;                                                              \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Float(16)) {                                           \\\n    typedef uint16_t DType;                                                           \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::BFloat(16)) {                                          \\\n    typedef uint16_t DType;                                                           \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Int(64)) {                                             \\\n    typedef int64_t DType;                                                            \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Int(32)) {                                             \\\n    typedef int32_t DType;                                                            \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Int(16)) {                                             \\\n    typedef int16_t DType;                                                            \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Int(8)) {                                              \\\n    typedef int8_t DType;                                                             \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::UInt(64)) {                                            \\\n    typedef uint64_t DType;                                                           \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::UInt(32)) {                                            \\\n    typedef uint32_t DType;                                                           \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::UInt(16)) {                                            \\\n    typedef uint16_t DType;                                                           \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::UInt(8)) {                                             \\\n    typedef uint8_t DType;                                                            \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if (type == DataType::Bool()) {                                              \\\n    typedef bool DType;                                                               \\\n    { __VA_ARGS__ }                                                                   \\\n  } else if ((*tvm::runtime::Registry::Get(\"runtime._datatype_get_type_registered\"))( \\\n                 static_cast<uint8_t>(type.code()))) {                                \\\n    typedef double DType;                                                             \\\n    { __VA_ARGS__ }                                                                   \\\n  } else {                                                                            \\\n    LOG(FATAL) << \"unknown data type \" << type;                                       \\\n  }\n\n/*!\n * \\brief Try to do the type inference over expr:\n *\n * Do the infer_type over each node in expr\n *\n * \\param expr The IR expression\n * \\return infered expr if succeed.\n */\ninline Expr InferType(const Expr& expr) {\n  auto mod = IRModule::FromExpr(expr);\n  mod = transform::InferType()(mod);\n  if (expr.as<FunctionNode>()) {\n    return mod->Lookup(\"main\");\n  } else {\n    return mod->Lookup(\"main\").as<FunctionNode>()->body;\n  }\n}\n\n/*!\n * \\brief Try to match lhs and rhs via broadcasting rule, such that:\n *\n * rhs matches the dimension of lhs specified by lhs_axes\n * rhs's value equals 1 on rest of dimensions.\n *\n * \\param tlhs The type of left operand (data)\n * \\param trhs The type right operand (bias)\n * \\param lhs_axes The axes on lhs to match.\n * \\param rhs_value A squeezed version of rhs which only contains matched dimension.\n * \\return Whether match is successful.\n */\ninline bool MatchBroadcastToLeftAxes(const TensorTypeNode* tlhs, const TensorTypeNode* trhs,\n                                     const Array<Integer>& lhs_axes, Expr* rhs_value = nullptr) {\n  if (tlhs->shape.size() < trhs->shape.size()) return false;\n  StructuralEqual equal;\n  size_t base = tlhs->shape.size() - trhs->shape.size();\n  size_t j = 0;\n\n  // handle case trhs is simple constant\n  if (trhs->shape.size() == 0 && rhs_value != nullptr && lhs_axes.size() > 0) {\n    *rhs_value = MakeExpandDims(*rhs_value, 0, lhs_axes.size());\n    for (size_t i = 0; i < lhs_axes.size(); i++) {\n      int repeat_value =\n          tlhs->shape[static_cast<size_t>(lhs_axes[j]->value)].as<IntImmNode>()->value;\n      *rhs_value = MakeRepeat(*rhs_value, repeat_value, i);\n    }\n    return true;\n  }\n\n  ObjectPtr<SqueezeAttrs> squeeze_attrs;\n  if (rhs_value != nullptr) {\n    squeeze_attrs = make_object<SqueezeAttrs>();\n  }\n\n  for (size_t i = 0; i < tlhs->shape.size(); ++i) {\n    if (j < lhs_axes.size() && i == static_cast<size_t>(lhs_axes[j]->value)) {\n      if (i < base || !equal(tlhs->shape[i], trhs->shape[i - base])) {\n        return false;\n      }\n      ++j;\n    } else if (i >= base) {\n      if (!tir::is_const_int(trhs->shape[i - base], 1)) {\n        return false;\n      }\n      if (rhs_value != nullptr) {\n        squeeze_attrs->axis.push_back(static_cast<int>(i - base));\n      }\n    }\n  }\n  if (rhs_value != nullptr && squeeze_attrs->axis.size() != 0) {\n    static const Op& squeeze_op = Op::Get(\"squeeze\");\n    *rhs_value = Call(squeeze_op, {rhs_value[0]}, Attrs(squeeze_attrs), {});\n  }\n  return true;\n}\n\n/*!\n * \\brief Expand 1D Tensor to match axis.\n *\n * The result bias can be used to add or multiply to\n * the target Tensor on the specified axis via broadcasting rule.\n *\n * \\param bias The bias.\n * \\param target_ndim Target dimension.\n * \\param axes The axis on the output we want to match on.\n */\ninline Expr ExpandBiasToMatchAxis(Expr bias, int target_ndim, const Array<Integer>& axes) {\n  static const Op& expand_dims = Op::Get(\"expand_dims\");\n  for (size_t i = axes.size(); i != 0; --i) {\n    if (i == axes.size()) {\n      int64_t num_pad_axis = target_ndim - axes[i - 1]->value - 1;\n      if (num_pad_axis > 0) {\n        auto attrs = make_object<ExpandDimsAttrs>();\n        attrs->axis = i;\n        attrs->num_newaxis = static_cast<int>(num_pad_axis);\n        bias = Call(expand_dims, {bias}, Attrs(attrs), {});\n      }\n    } else {\n      int64_t diff = axes[i]->value - axes[i - 1]->value;\n      ICHECK_GE(diff, 0L);\n      if (diff > 0) {\n        auto attrs = make_object<ExpandDimsAttrs>();\n        attrs->axis = i;\n        attrs->num_newaxis = static_cast<int>(diff);\n        bias = Call(expand_dims, {bias}, Attrs(attrs), {});\n      }\n    }\n  }\n  return bias;\n}\n\n/*!\n * \\brief Check if the call is depthwise conv3d.\n *\n * \\param call The conv call.\n * \\param param The conv attributes.\n * \\return Whether it is depthwise_conv3d.\n */\ntemplate <typename ATTRS>\ninline bool IsDepthwiseConv(const Call& call, ATTRS param, const Layout& kernel_layout) {\n  static const Layout kOIXX =\n      backend::IsOp(call.as<CallNode>(), \"nn.conv2d\") ? Layout(\"OIHW\") : Layout(\"OIDHW\");\n  const auto bilayout = tir::BijectiveLayout(kernel_layout, kOIXX);\n  auto wshape = bilayout.ForwardShape(call->args[1]->type_as<TensorTypeNode>()->shape);\n  return tir::is_const_int(wshape[0], param->groups) && tir::is_const_int(wshape[1], 1);\n}\n\n/*!\n * \\brief Get super-dimension of output channels of conv2d\n * \\param call The conv2d call.\n * \\return Super-dimension size of output channels of conv2d.\n */\ninline int64_t GetConv2DSuperChannelsDim(const CallNode* call) {\n  auto param = call->attrs.as<Conv2DAttrs>();\n  auto tweight = call->args[1]->type_as<TensorTypeNode>();\n  auto index = param->kernel_layout.operator std::string().find('O');\n  ICHECK_NE(index, std::string::npos);\n  auto channels = tir::as_const_int(tweight->shape[index]);\n  return *channels;\n}\n\n/*!\n * \\brief Is single value tensor (scalar).\n * \\param expr The expr.\n * \\return True if single value tensor.\n */\ninline bool IsScalar(const Expr& expr) {\n  if (auto tensor_type = expr->checked_type().as<TensorTypeNode>()) {\n    for (auto dim_index_expr : tensor_type->shape) {\n      if (auto dim_index = dim_index_expr.as<IntImmNode>()) {\n        if (dim_index->value != 1) {\n          return false;\n        }\n      } else {\n        return false;\n      }\n    }\n  } else {\n    return false;\n  }\n  return true;\n}\n\n/*!\n * \\brief Check if expr is a const scalar.\n * \\param expr The expr.\n * \\return True if const scalar.\n */\ninline bool IsConstScalar(const Expr& expr) {\n  const auto* const_expr = expr.as<ConstantNode>();\n  if (const_expr) {\n    return const_expr->is_scalar();\n  }\n  return false;\n}\n\n/*!\n * \\brief Create a Constant with a scalar\n *\n * \\param dtype The data type.\n * \\param value The value of the scalar.\n * \\return A Constant.\n */\ntemplate <typename T>\ninline Constant MakeConstantScalar(DataType dtype, T value) {\n  runtime::NDArray arr = runtime::NDArray::Empty({}, dtype, {kDLCPU, 0});\n  TVM_DTYPE_DISPATCH(dtype, DType, {\n    if (dtype == DataType::Float(16)) {\n      // convert to float16\n      // storage is uint16_t\n      *static_cast<DType*>(arr->data) =\n          __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 10>(static_cast<float>(value));\n    } else if (dtype == DataType::BFloat(16)) {\n      // convert to bfloat16\n      // storage is uint16_t\n      *static_cast<DType*>(arr->data) =\n          __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 7>(static_cast<float>(value));\n    } else {\n      *static_cast<DType*>(arr->data) = value;\n    }\n  })\n  return Constant(arr);\n}\n\n/*!\n * \\brief Create a Constant with a tensor.\n *\n * \\param dtype The data type.\n * \\param value The vector of the tensor values.\n * \\return A Constant.\n */\ntemplate <typename T>\nstatic inline Constant MakeConstantTensor(DataType dtype, std::vector<int64_t> shape,\n                                          std::vector<T> value) {\n  runtime::NDArray arr = runtime::NDArray::Empty(shape, dtype, {kDLCPU, 0});\n  TVM_DTYPE_DISPATCH(dtype, DType, {\n    for (size_t i = 0; i < value.size(); i++) {\n      if (dtype == DataType::Float(16)) {\n        // convert to float16\n        // storage is uint16_t\n        // Similar handling as that in MakeConstantScalar\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 10>(\n                static_cast<float>(value[i]));\n      } else if (dtype == DataType::BFloat(16)) {\n        // convert to bfloat16\n        // storage is uint16_t\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 7>(\n                static_cast<float>(value[i]));\n      } else {\n        *(static_cast<DType*>(arr->data) + i) = value[i];\n      }\n    }\n  })\n  return Constant(arr);\n}\n\n/*!\n * \\brief Create a Constant with a tensor.\n *\n * \\param dtype The data type.\n * \\param value The array of the tensor values.\n * \\return A Constant.\n */\ntemplate <typename T>\nstatic inline Constant MakeConstantTensor(DataType dtype, std::vector<int64_t> shape,\n                                          Array<T> value) {\n  runtime::NDArray arr = runtime::NDArray::Empty(shape, dtype, {kDLCPU, 0});\n  TVM_DTYPE_DISPATCH(dtype, DType, {\n    for (size_t i = 0; i < value.size(); i++) {\n      if (dtype == DataType::Float(16)) {\n        // convert to float16\n        // storage is uint16_t\n        // Similar handling as that in MakeConstantScalar\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 10>(\n                static_cast<float>(value[i]));\n      } else if (dtype == DataType::BFloat(16)) {\n        // convert to bfloat16\n        // storage is uint16_t\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 7>(\n                static_cast<float>(value[i]));\n      } else {\n        *(static_cast<DType*>(arr->data) + i) = value[i];\n      }\n    }\n  })\n  return Constant(arr);\n}\n\n/*!\n * \\brief Create a Constant tensor of zeros.\n *\n * \\param dtype The data type.\n * \\param shape The shape of the output constant tensor.\n * \\return A Constant.\n */\nstatic inline Constant MakeConstantZeros(DataType dtype, std::vector<int64_t> shape) {\n  runtime::NDArray arr = runtime::NDArray::Empty(shape, dtype, {kDLCPU, 0});\n  int64_t data_size = 1;\n  for (int64_t dim : shape) {\n    data_size *= dim;\n  }\n  TVM_DTYPE_DISPATCH(dtype, DType, {\n    for (int64_t i = 0; i < data_size; i++) {\n      if (dtype == DataType::Float(16)) {\n        // convert to float16\n        // storage is uint16_t\n        // Similar handling as that in MakeConstantScalar\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 10>(static_cast<float>(0));\n      } else if (dtype == DataType::BFloat(16)) {\n        // convert to bfloat16\n        // storage is uint16_t\n        *(static_cast<DType*>(arr->data) + i) =\n            __truncXfYf2__<float, uint32_t, 23, uint16_t, uint16_t, 7>(static_cast<float>(0));\n      } else {\n        *(static_cast<DType*>(arr->data) + i) = 0;\n      }\n    }\n  })\n  return Constant(arr);\n}\n\n/*!\n * \\brief Check whether a shape is static and create corresponding Constant.\n Eventually this will be removed and replaced with CheckConstantShapeArrayInteger\n *\n * \\param shape The Array of the shape values.\n * \\return A Constant.\n */\nstatic inline Constant CheckConstantShape(const Array<IndexExpr>& shape) {\n  auto shape_array =\n      runtime::NDArray::Empty({int64_t(shape.size())}, DataType::Int(64), {kDLCPU, 0});\n  auto* shape_data = static_cast<int64_t*>(shape_array->data);\n  for (size_t i = 0; i < shape.size(); ++i) {\n    const auto& dim_val = shape[i].as<IntImmNode>();\n    ICHECK(dim_val) << \"Do not support symbolic shape for \"\n                       \"Array format. Pass shape as Expr instead.\";\n    shape_data[i] = dim_val->value;\n  }\n  return Constant(shape_array);\n}\n\n/*!\n * \\brief Check whether a shape is static and create corresponding Array<Integer>. Will replace\n * CheckConstantShape after dynamic refactorization is complete\n *\n * \\param shape The Array of the shape values.\n * \\return A Constant.\n */\nstatic inline Array<Integer> CheckConstantShapeArrayInteger(const Array<IndexExpr>& shape) {\n  Array<Integer> constShape;\n\n  for (size_t i = 0; i < shape.size(); ++i) {\n    const auto& dim_val = shape[i].as<IntImmNode>();\n    ICHECK(dim_val) << \"Do not support symbolic shape for \"\n                       \"Array format. Pass shape as Expr instead.\";\n\n    constShape.push_back(dim_val->value);\n  }\n  return constShape;\n}\n\n/*!\n * \\brief Check if two expressions are equal scalars.\n * \\param a The expression to be checked.\n * \\param b The expression to be checked\n * \\return Whether two expressions are equal scalars.\n */\ninline bool IsEqualScalar(const Expr& a, const Expr& b) {\n  const auto* constant_a = a.as<ConstantNode>();\n  const auto* constant_b = b.as<ConstantNode>();\n  if (!constant_a || !constant_b || !constant_a->is_scalar() || !constant_b->is_scalar()) {\n    return false;\n  }\n  return tvm::StructuralEqual()(a, b);\n}\n\n/*!\n * \\brief Convert an element of a NDArray with type int or float to scalar.\n * \\param array Input NDArray\n * \\param i element index\n * \\return Converted scalar value, or None if conversion failed\n */\nstatic inline std::optional<long double> TryToScalar(const runtime::NDArray& array, size_t i = 0) {\n  if (array->dtype.code == kDLInt) {\n    if (array->dtype.bits == 8) {\n      return std::optional<long double>(reinterpret_cast<int8_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 16) {\n      return std::optional<long double>(reinterpret_cast<int16_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 32) {\n      return std::optional<long double>(reinterpret_cast<int32_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 64) {\n      return std::optional<long double>(reinterpret_cast<int64_t*>(array->data)[i]);\n    }\n  } else if (array->dtype.code == kDLUInt) {\n    if (array->dtype.bits == 1) {  // bool\n      return std::optional<long double>(reinterpret_cast<uint8_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 8) {\n      return std::optional<long double>(reinterpret_cast<uint8_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 16) {\n      return std::optional<long double>(reinterpret_cast<uint16_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 32) {\n      return std::optional<long double>(reinterpret_cast<uint32_t*>(array->data)[i]);\n    } else if (array->dtype.bits == 64) {\n      return std::optional<long double>(reinterpret_cast<uint64_t*>(array->data)[i]);\n    }\n  } else if (array->dtype.code == kDLFloat) {\n    if (array->dtype.bits == 16) {\n      return std::optional<long double>(\n          __extendXfYf2__<uint16_t, uint16_t, 10, float, uint32_t, 23>(\n              reinterpret_cast<uint16_t*>(array->data)[i]));\n    }\n    if (array->dtype.bits == 32) {\n      return std::optional<long double>(reinterpret_cast<float*>(array->data)[i]);\n    } else if (array->dtype.bits == 64) {\n      return std::optional<long double>(reinterpret_cast<double*>(array->data)[i]);\n    }\n  } else if (array->dtype.code == kDLBfloat) {\n    if (array->dtype.bits == 16) {\n      return std::optional<long double>(__extendXfYf2__<uint16_t, uint16_t, 7, float, uint32_t, 23>(\n          reinterpret_cast<uint16_t*>(array->data)[i]));\n    }\n  }\n  return std::nullopt;\n}\n\n/*!\n * \\brief Convert an element of a NDArray with type int or float to scalar.\n * \\param array Input NDArray\n * \\param i element index\n * \\return Converted scalar value\n */\nstatic inline long double ToScalar(const runtime::NDArray& array, size_t i = 0) {\n  auto try_value = TryToScalar(array, i);\n  ICHECK(try_value) << \"Unknown data type: \" << tvm::runtime::DLDataType2String(array->dtype);\n  return try_value.value();\n}\n\n/*!\n * \\brief Convert a NDArray with type int or float to Array<Integer>.\n * \\param array Input NDArray\n * \\return Converted Array.\n */\nstatic inline Array<Integer> ToVector(const runtime::NDArray& array) {\n  size_t ndim = array.Shape().size();\n  ICHECK_EQ(ndim, 1) << \"This function should only be used for 1D NDArrays\";\n  size_t len = array.Shape().front();\n  Array<Integer> out;\n  for (size_t i = 0; i < len; ++i) {\n    long double elem_val = ToScalar(array, i);\n    out.push_back(Integer(IntImm(DataType::Int(32), static_cast<int64_t>(elem_val))));\n  }\n  return out;\n}\n\n/*!\n * \\brief Convert a NDArray with type int or float to Array<FloatImm>.\n * \\param array Input NDArray\n * \\return Converted Array.\n */\nstatic inline Array<FloatImm> ToFloatVector(const runtime::NDArray& array) {\n  size_t ndim = array.Shape().size();\n  ICHECK_EQ(ndim, 1) << \"This function should only be used for 1D NDArrays\";\n  size_t len = array.Shape().front();\n  Array<FloatImm> out;\n  for (size_t i = 0; i < len; ++i) {\n    long double elem_val = ToScalar(array, i);\n    out.push_back(FloatImm(DataType::Float(32), static_cast<float>(elem_val)));\n  }\n  return out;\n}\n\n/*!\n * \\brief Convert a NDArray with type int or float to Array<Array<Integer>>.\n * \\param array Input NDArray\n * \\return Converted Array.\n */\nstatic inline Array<Array<Integer>> ToMatrix(const runtime::NDArray& array) {\n  size_t ndim = array.Shape().size();\n  ICHECK_EQ(ndim, 2) << \"This function should only used for 2D NDArrays\";\n  size_t dim1 = array.Shape().at(0);\n  size_t dim2 = array.Shape().at(1);\n\n  Array<Array<Integer>> out;\n\n  for (size_t i = 0; i < dim1; ++i) {\n    Array<Integer> inner_out;\n    for (size_t j = 0; j < dim2; ++j) {\n      double elem_val = ToScalar(array, i * dim2 + j);\n      inner_out.push_back(Integer(static_cast<int>(elem_val)));\n    }\n    out.push_back(inner_out);\n  }\n  return out;\n}\n\ninline Expr GetField(Expr t, size_t i) { return TupleGetItem(t, i); }\n\ninline Expr Pair(Expr l, Expr r) { return Tuple({l, r}); }\n\ninline Expr Exp(Expr e) {\n  static const Op& op = Op::Get(\"exp\");\n  return Call(op, {e});\n}\n\ninline Expr Erf(Expr e) {\n  static const Op& op = Op::Get(\"erf\");\n  return Call(op, {e});\n}\n\ninline Expr FastExp(Expr e) {\n  static const Op& op = Op::Get(\"fast_exp\");\n  return Call(op, {e});\n}\n\ninline Expr FastErf(Expr e) {\n  static const Op& op = Op::Get(\"fast_erf\");\n  return Call(op, {e});\n}\n\ninline Expr FastTanh(Expr e) {\n  static const Op& op = Op::Get(\"fast_tanh\");\n  return Call(op, {e});\n}\n\ninline Expr FastSoftmax(Expr e, tvm::Attrs attr) {\n  static const Op& op = Op::Get(\"nn.fast_softmax\");\n  return Call(op, {e}, attr);\n}\n\ninline Expr Log(Expr e) {\n  static const Op& op = Op::Get(\"log\");\n  return Call(op, {e});\n}\n\ninline Expr Tanh(Expr e) {\n  static const Op& op = Op::Get(\"tanh\");\n  return Call(op, {e});\n}\n\ninline Expr Abs(Expr e) {\n  static const Op& op = Op::Get(\"abs\");\n  return Call(op, {e});\n}\n/*!\n * \\brief Get an immediate scalar from a Constant expr.\n *\n * \\param expr The Constant expr.\n * \\return A scalar with type T.\n */\ntemplate <typename T>\nT GetScalarFromConstant(Expr expr) {\n  const auto* n = expr.as<ConstantNode>();\n  ICHECK(n) << \"Expr must be a constant expr - \" << AsText(expr, false);\n  ICHECK(n->is_scalar());\n  return static_cast<T*>(n->data->data)[0];\n}\n\ninline Expr Cast(Expr x, DataType dtype) { return MakeCast(x, dtype); }\n\ninline Expr Negative(Expr x) {\n  static const Op& op = Op::Get(\"negative\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Sqrt(Expr x) {\n  static const Op& op = Op::Get(\"sqrt\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Sigmoid(Expr x) {\n  static const Op& op = Op::Get(\"sigmoid\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Rsqrt(Expr x) {\n  static const Op& op = Op::Get(\"rsqrt\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Relu(Expr x) {\n  static const Op& op = Op::Get(\"nn.relu\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Round(Expr x) {\n  static const Op& op = Op::Get(\"round\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Floor(Expr x) {\n  static const Op& op = Op::Get(\"floor\");\n  return Call(op, {x}, Attrs(), {});\n}\n\ninline Expr Clip(Expr x, double a_min, double a_max) { return MakeClip(x, a_min, a_max); }\n\ninline Expr FixedPointMultiply(Expr x, int32_t multiplier, int32_t shift) {\n  static const Op& op = Op::Get(\"fixed_point_multiply\");\n  auto attrs = make_object<FixedPointMultiplyAttrs>();\n  attrs->multiplier = multiplier;\n  attrs->shift = shift;\n  return Call(op, {x}, Attrs(attrs), {});\n}\n\ninline Expr FixedPointMultiplyPerAxis(Expr x, Expr m, Expr lshift, Expr rshift,\n                                      bool is_lshift_required, bool is_rshift_required,\n                                      Array<Integer> axes) {\n  return MakeFixedPointMultiplyPerAxis(x, m, lshift, rshift, is_lshift_required, is_rshift_required,\n                                       axes);\n}\n\ninline Expr Add(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"add\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr Subtract(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"subtract\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr Multiply(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"multiply\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr Divide(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"divide\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr Maximum(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"maximum\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr ZerosLike(Expr e) {\n  static const Op& op = Op::Get(\"zeros_like\");\n  return Call(op, {e});\n}\n\ninline Expr Zeros(Array<IndexExpr> shape, DataType dtype) {\n  return MakeZeros(CheckConstantShapeArrayInteger(shape), dtype);\n}\n\ninline Expr OnesLike(Expr e) {\n  static const Op& op = Op::Get(\"ones_like\");\n  return Call(op, {e});\n}\n\ninline Expr Ones(Array<IndexExpr> shape, DataType dtype) {\n  return MakeOnes(CheckConstantShapeArrayInteger(shape), dtype);\n}\n\ninline Expr CollapseSumLike(Expr e) {\n  static const Op& op = Op::Get(\"collapse_sum_like\");\n  return Call(op, {e});\n}\n\ninline Expr Power(Expr lhs, Expr rhs) {\n  static const Op& op = Op::Get(\"power\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\ninline Expr RightShift(Expr x, Expr nbit) {\n  static const Op& op = Op::Get(\"right_shift\");\n  return Call(op, {x, nbit}, Attrs(), {});\n}\n\ninline Expr LeftShift(Expr x, Expr nbit) {\n  static const Op& op = Op::Get(\"left_shift\");\n  return Call(op, {x, nbit}, Attrs(), {});\n}\n\ninline Expr ReshapeLike(Expr lhs, Expr rhs, int lhs_begin, Integer lhs_end, int rhs_begin,\n                        Integer rhs_end) {\n  return MakeReshapeLike(lhs, rhs, lhs_begin, lhs_end, rhs_begin, rhs_end);\n}\n\ninline Expr Copy(Expr data) {\n  static const Op& op = Op::Get(\"copy\");\n  return Call(op, {data}, Attrs(), {});\n}\n\ninline Expr Mean(Expr data, Array<Integer> axis, bool keepdims, bool exclude) {\n  return MakeReduce(data, axis, keepdims, exclude, \"mean\");\n}\n\ninline Expr Variance(Expr data, Expr mean, Array<Integer> axis, bool keepdims, bool exclude,\n                     bool unbiased = false) {\n  return MakeVariance(data, mean, axis, keepdims, exclude, unbiased);\n}\n\nstatic inline Expr Where(const Expr& condition, const Expr& x, const Expr& y) {\n  static const Op& op = Op::Get(\"where\");\n  return Call(op, {condition, x, y});\n}\n\nstatic inline Expr LogicalOr(const Expr& lhs, const Expr& rhs) {\n  static const Op& op = Op::Get(\"logical_or\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\nstatic inline Expr GreaterEqual(const Expr& lhs, const Expr& rhs) {\n  static const Op& op = Op::Get(\"greater_equal\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\nstatic inline Expr Equal(const Expr& lhs, const Expr& rhs) {\n  static const Op& op = Op::Get(\"equal\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\nstatic inline Expr Less(const Expr& lhs, const Expr& rhs) {\n  static const Op& op = Op::Get(\"less\");\n  return Call(op, {lhs, rhs}, Attrs(), {});\n}\n\nstatic inline Expr IsFinite(const Expr x) {\n  static const Op& op = Op::Get(\"isfinite\");\n  return Call(op, {x}, Attrs(), {});\n}\n\nstatic inline Expr Full(Expr fill_value, Array<IndexExpr> shape, DataType dtype) {\n  return MakeFull(fill_value, CheckConstantShapeArrayInteger(shape), dtype);\n}\n\nstatic inline Expr Conv2D(Expr data, Expr weight, Array<IndexExpr> strides,\n                          Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups,\n                          IndexExpr channels, Array<IndexExpr> kernel_size, std::string data_layout,\n                          std::string kernel_layout, std::string out_layout, DataType out_dtype) {\n  return MakeConv<Conv2DAttrs>(data, weight, strides, padding, dilation, groups, channels,\n                               kernel_size, data_layout, kernel_layout, out_layout, out_dtype,\n                               \"nn.conv2d\");\n}\n\nstatic inline Expr Dense(Expr data, Expr weight, IndexExpr units, DataType out_dtype) {\n  return MakeDense(data, weight, units, out_dtype);\n}\n\nstatic inline Expr Sum(Expr data, Array<Integer> axis, bool keepdims, bool exclude) {\n  return MakeReduce(data, axis, keepdims, exclude, \"sum\");\n}\n\nstatic inline Expr Prod(Expr data, Array<Integer> axis, bool keepdims, bool exclude) {\n  return MakeReduce(data, axis, keepdims, exclude, \"prod\");\n}\n\nstatic inline Expr Reshape(Expr data, Array<Integer> newshape) {\n  return MakeReshape(data, newshape);\n}\n\nstatic inline Expr AvgPool2D(Expr data, Array<IndexExpr> pool_size, Array<IndexExpr> strides,\n                             Array<IndexExpr> dilation, Array<IndexExpr> padding,\n                             std::string layout, std::string out_layout, bool ceil_mode,\n                             bool count_include_pad) {\n  return MakeAvgPool<AvgPool2DAttrs>(data, pool_size, strides, dilation, padding, layout,\n                                     out_layout, ceil_mode, count_include_pad, \"nn.avg_pool2d\");\n}\n\nstatic inline Expr Pad(Expr data, Array<Array<IndexExpr>> pad_width, Expr pad_value,\n                       std::string pad_mode) {\n  Array<Array<Integer>> pad_width_int;\n  for (size_t i = 0; i < pad_width.size(); ++i) {\n    pad_width_int.push_back(CheckConstantShapeArrayInteger(pad_width[i]));\n  }\n  return MakePad(data, pad_width_int, pad_value, pad_mode);\n}\n\nstatic inline Expr Tile(Expr data, Array<Integer> reps) { return MakeTile(data, reps); }\n\nstatic inline Expr BroadCastTo(Expr data, Array<IndexExpr> shape) {\n  return MakeBroadCastTo(data, CheckConstantShapeArrayInteger(shape));\n}\n\ninline Expr Hardswish(Expr x) {\n  auto three = MakeConstantScalar(DataType::Float(32), 3.0);\n  auto six = MakeConstantScalar(DataType::Float(32), 6.0);\n  auto x2 = Add(x, three);\n  x2 = Clip(x2, 0.0, 6.0);\n  x2 = Multiply(x, x2);\n  x2 = Divide(x2, six);\n  return x2;\n}\n\n}  // namespace relay\n}  // namespace tvm\n#endif  // TVM_RELAY_TRANSFORMS_PATTERN_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/simplify_expr.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/relay/transforms/simplify_expr.h\n * \\brief Utility data structures for simplifying Relay expressions.\n */\n#ifndef TVM_RELAY_TRANSFORMS_SIMPLIFY_EXPR_H_\n#define TVM_RELAY_TRANSFORMS_SIMPLIFY_EXPR_H_\n\n#include <tvm/relay/dataflow_matcher.h>\n#include <tvm/relay/expr.h>\n\n#include <memory>\n#include <vector>\n\nnamespace tvm {\nnamespace relay {\n\n/*! \\brief A wrapper class defining a rewrite matching a specific pattern. */\nclass DFPatternRewrite {\n public:\n  /*! \\brief Returns the rewritten expression. */\n  virtual Expr Callback(const Expr& pre, const Expr& post,\n                        const Map<DFPattern, Array<Expr>>& node_map) const = 0;\n\n  virtual ~DFPatternRewrite() = default;\n\n  /*! \\brief Returns the pattern to be used for matching and rewriting. */\n  inline DFPattern Pattern() const { return pattern_; }\n\n  inline bool RequireType() const { return require_type_; }\n\n  inline DFPatternCallback MakeCallback() const {\n    auto func = [this](TVMArgs args, TVMRetValue* rv) {\n      Expr pre = args[0];\n      Expr post = args[1];\n      Map<DFPattern, Array<Expr>> node_map = args[2];\n      *rv = this->Callback(pre, post, node_map);\n    };\n    return DFPatternCallback(pattern_, PackedFunc(func), require_type_);\n  }\n\n protected:\n  /*! \\brief The pattern for matching and rewriting. */\n  DFPattern pattern_;\n  /*! \\brief Whether or not the rewrite requires types to be inferred. */\n  bool require_type_ = true;\n};\n\n/*! \\brief Helper class for composing rewrites and getting callbacks. */\nclass DFPatternRewriteComposer {\n public:\n  template <typename T, typename... Args>\n  inline void AddRewrite(Args... args) {\n    rewrites_.push_back(std::make_shared<T, Args&...>(args...));\n  }\n\n  inline Array<DFPatternCallback> MakeCallbacks() const {\n    Array<DFPatternCallback> callbacks;\n    for (const auto& rewrite : rewrites_) {\n      callbacks.push_back(rewrite->MakeCallback());\n    }\n    return callbacks;\n  }\n\n private:\n  /*! \\brief the rewrites to be composed. */\n  std::vector<std::shared_ptr<DFPatternRewrite>> rewrites_;\n};\n\n}  // namespace relay\n}  // namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_SIMPLIFY_EXPR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/relay/transforms/transform_layout.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file transform_layout.h\n * \\brief Common infrastructure for transforming the layouts. This is used for AlterOpLayout and\n *        ConvertLayout pass. */\n\n#ifndef TVM_RELAY_TRANSFORMS_TRANSFORM_LAYOUT_H_\n#define TVM_RELAY_TRANSFORMS_TRANSFORM_LAYOUT_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/tir/data_layout.h>\n\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"infer_layout_utils.h\"\n#include \"pattern_utils.h\"\n\nnamespace tvm {\nnamespace relay {\n\n/*!\n * \\brief Memorizes layout transformations to reuse.\n */\nclass TransformMemorizerNode : public Object {\n public:\n  /*! \\brief The key for the memorizer map is (Expr, src_layout, dst_layout). */\n  using TransformKey = std::tuple<const Object*, std::string, std::string>;\n\n  struct key_hash : public std::function<std::size_t(TransformKey)> {\n    std::size_t operator()(const TransformKey& k) const {\n      return dmlc::HashCombine<std::string>(\n          dmlc::HashCombine<std::string>(std::hash<const Object*>()(std::get<0>(k)),\n                                         std::get<1>(k)),\n          (std::get<2>(k)));\n    }\n  };\n\n  /*!\n   * \\brief Defines the call transformation for derived passes. The new layouts are defined by\n   * used for different targets using a packed func.\n   * \\param ref_call The original call.\n   * \\param new_attrs Updated attributes consistent with new layouts.\n   * \\param new_args The traversed/recursed args to the call.\n   * \\return The new Call after calling the packed func.\n   */\n  virtual Call CallWithNewLayouts(const Call& ref_call, Attrs new_attrs,\n                                  const std::vector<Expr>& new_args) = 0;\n\n  virtual Call CallWithNewLayouts(const Call& ref_call, const std::vector<Expr>& new_args) {\n    return CallWithNewLayouts(ref_call, ref_call->attrs, new_args);\n  }\n\n  /*! \\brief The memorizer map. */\n  std::unordered_map<TransformKey, Expr, key_hash> memo;\n\n  static constexpr const char* _type_key = \"relay.alter_op_layout.TransformMemorizerNode\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TransformMemorizerNode, Object);\n};\n\n/*!\n * \\brief Container that transforms the layouts and memorizes them.\n */\nclass TransformMemorizer : public ObjectRef {\n public:\n  TransformMemorizer() = default;\n  explicit TransformMemorizer(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  TransformMemorizerNode* operator->() {\n    return static_cast<TransformMemorizerNode*>(get_mutable());\n  }\n\n  /*\n   * \\brief Memorizes and transforms the layout.\n   * \\param expr The initial expr.\n   * \\param src_layout The source layout.\n   * \\param dst_layout The dest layout.\n   * \\return The new expr with the dst layout.\n   */\n  Expr Transform(Expr raw, const Layout& src_layout, const Layout& dst_layout) {\n    if (src_layout.Equals(dst_layout)) {\n      return raw;\n    }\n\n    std::tuple<const Object*, std::string, std::string> key =\n        std::make_tuple<>(raw.get(), src_layout.name(), dst_layout.name());\n    auto& memo = operator->()->memo;\n\n    auto iter = memo.find(key);\n    if (iter != memo.end()) {\n      return iter->second;\n    } else {\n      Expr transform = TransformHelper(raw, src_layout, dst_layout);\n      memo[key] = transform;\n      return transform;\n    }\n  }\n\n  /*\n   * \\brief Helper to transform the layouts.\n   * \\param expr The initial expr.\n   * \\param src_layout The source layout.\n   * \\param dst_layout The dest layout.\n   * \\return The new expr with the dst layout.\n   * \\note It performs following 2 operations\n   *       1) If src_layout ndim is smaller then dst_layout, expand_dim is inserted to match the dim\n   *          size. For example, src_layout = C, dst_layout = NCHW16c. The src is expanded to NHWC.\n   *       2) Call layout transform with new src layout.\n   */\n  Expr TransformHelper(Expr raw, Layout src_layout, Layout dst_layout) {\n    if (src_layout.Equals(dst_layout)) {\n      return raw;\n    }\n\n    // 1) Check if the shape lengths are different. If yes, expand dims.\n    Expr input_expr = raw;\n    Layout new_src_layout = src_layout;\n    if (src_layout.ndim_primal() < dst_layout.ndim_primal()) {\n      // If scalar, then no need of layout transformation as scalar can be broadcasted easily even\n      // if the other operand has a transformed layout.\n      if (input_expr->checked_type_.defined() && IsScalar(input_expr)) {\n        return raw;\n      }\n      int num_new_axis = dst_layout.ndim_primal() - src_layout.ndim_primal();\n      new_src_layout = src_layout.ExpandPrimal(dst_layout);\n      input_expr = MakeExpandDims(input_expr, 0, num_new_axis);\n      if (new_src_layout.Equals(dst_layout)) {\n        return input_expr;\n      }\n    }\n\n    // 2) Insert layout transform on the transformed src.\n    ICHECK(new_src_layout.defined() && dst_layout.defined())\n        << \"Cannot insert layout transform because there are undefined layouts\";\n    ICHECK(tir::BijectiveLayout(new_src_layout, dst_layout).defined())\n        << \"Cannot insert layout transform because there are inconvertible layouts: \"\n        << new_src_layout << \" v.s. \" << dst_layout;\n    return MakeLayoutTransform(input_expr, new_src_layout.name(), dst_layout.name());\n  }\n\n  using ContainerType = TransformMemorizerNode;\n};\n\n/*\n * \\brief TempExprNode during layout transform. Instance of this expr will be Realized to normal\n *        expr ultimately.\n * \\tparam TransformMemorizerT The derived TransformMemorizer type.\n */\ntemplate <class TransformMemorizerT>\nclass LayoutAlternatedExprNode : public TempExprNode {\n public:\n  Expr value;\n  Layout old_layout;\n  Layout new_layout;\n  TransformMemorizerT memorizer;\n\n  Expr Realize() const final {\n    // NOTE: use a copy to discard the \"const\" qualifier\n    TransformMemorizerT tmp_memorizer = memorizer;\n    // fallback to old layout\n    return tmp_memorizer.Transform(value, new_layout, old_layout);\n  }\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"value\", &value);\n    v->Visit(\"old_layout\", &old_layout);\n    v->Visit(\"new_layout\", &new_layout);\n  }\n\n  static constexpr const char* _type_key = \"relay.alter_op_layout.LayoutAlternatedExprNode\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(LayoutAlternatedExprNode, TempExprNode);\n};\n\n/*!\n * \\brief Container for the layout alternated expr.\n * \\tparam TransformMemorizerT The derived TransformMemorizer type.\n */\ntemplate <class TransformMemorizerT>\nclass LayoutAlternatedExpr : public ObjectRef {\n public:\n  LayoutAlternatedExpr() {}\n  explicit LayoutAlternatedExpr(ObjectPtr<Object> n) : ObjectRef(n) {}\n\n  LayoutAlternatedExprNode<TransformMemorizerT>* operator->() {\n    return static_cast<LayoutAlternatedExprNode<TransformMemorizerT>*>(get_mutable());\n  }\n\n  using ContainerType = LayoutAlternatedExprNode<TransformMemorizerT>;\n};\n\n/*!\n * Call registered FInferCorrectLayout of an op.\n * Parameters are the same as the parameters for FInferCorrectLayout\n * Returns inferred_input_layout, inferred_output_layout, updated attributes, and a flag\n * indicating whether or not layout conversion is successful.\n */\nstatic inline std::tuple<InferCorrectLayoutOutput, bool> InferCorrectLayouts(\n    const Call& call, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts,\n    const Array<tvm::relay::Type>& old_in_types) {\n  static auto finfer_layout = Op::GetAttrMap<FInferCorrectLayout>(\"FInferCorrectLayout\");\n  auto null_res = std::make_tuple(\n      InferCorrectLayoutOutput(Array<Layout>(nullptr), Array<Layout>(nullptr), Attrs(nullptr)),\n      false);\n  if (!call->op.as<OpNode>()) {\n    return null_res;\n  }\n\n  Op op = Downcast<Op>(call->op);\n  if (finfer_layout.count(op)) {\n    auto out = finfer_layout[op](call->attrs, new_in_layouts, old_in_layouts, old_in_types);\n    for (auto inferred_layouts : {out->input_layouts, out->output_layouts}) {\n      for (auto layout : inferred_layouts) {\n        if (!layout.defined()) {  // inference fails\n          return null_res;\n        }\n      }\n    }\n    return std::make_tuple(out, true);\n  } else {\n    return null_res;\n  }\n}\n\n/*\n * \\brief Used with ForwardRewrite to transform the expr. The input args are same as\n *        FForwardRewrite.\n * \\param ref_call The reference old call type to be rewritten.\n *                 We can make use of the op and type information.\n * \\param new_args The new arguments (some of them could be TempExpr).\n * \\param ctx  Optional context information about ref_call.\n * \\tparam TransformMemorizerT The derived TransformMemorizer type.\n * \\return The rewriten result call, can also return nullptr,\n *         which indicate the rewriter should use the default fallback\n *         rule that realizes all its input and compose the call.\n *\n * \\note The ctx can be used to provide extra information during transformation. The ctx is\n *       templated to reuse across AlterOpLayout and ConvertLayout pass. The steps are\n *       - Extract the original layouts.\n *       - Use ctx transformation to get a Call with new layouts - CallWithNewLayouts.\n *       - Extract the new layouts from the returned Call.\n *       - Transform the original call to reuse the new layouts using TransformMemorizer.\n */\ntemplate <class TransformMemorizerT>\nExpr LayoutRewriter(const Call& ref_call, const Array<Expr>& new_args, const ObjectRef& ctx) {\n  std::vector<LayoutAlternatedExpr<TransformMemorizerT>> inputs;\n  std::vector<Expr> normal_new_args;\n\n  // NOTE: discard the \"const\" qualifier\n  // TransformMemorizer memorizer = Downcast<TransformMemorizer>(ctx);\n  // TransformMemorizerT* ctx_transformer =\n  // static_cast<TransformMemorizerT*>(memorizer.operator->());\n  TransformMemorizerT memorizer = Downcast<TransformMemorizerT>(ctx);\n\n  // fill incomplete state and flatten tuple\n  auto push_back_one_arg = [&inputs, memorizer](Expr arg) {\n    // We always expect LayoutAlternatedExpr<TransformMemorizerT>.\n    // This is used to convert the normal Expr to LayoutAlternatedExpr<TransformMemorizerT>.\n    if (const LayoutAlternatedExprNode<TransformMemorizerT>* inp =\n            arg.as<LayoutAlternatedExprNode<TransformMemorizerT>>()) {\n      inputs.push_back(GetRef<LayoutAlternatedExpr<TransformMemorizerT>>(inp));\n      return inp->value;\n    } else {\n      auto inode = make_object<LayoutAlternatedExprNode<TransformMemorizerT>>();\n      inode->value = arg;\n      inode->memorizer = memorizer;\n      inputs.push_back(LayoutAlternatedExpr<TransformMemorizerT>(inode));\n      return arg;\n    }\n  };\n\n  for (auto new_arg : new_args) {\n    // NOTE: do not support nested tuple\n    if (new_arg->IsInstance<TupleNode>()) {\n      Tuple tuple_new_arg = Downcast<Tuple>(new_arg);\n      Array<Expr> fields;\n      fields.reserve(tuple_new_arg->fields.size());\n      for (auto x : tuple_new_arg->fields) {\n        Expr tmp = push_back_one_arg(x);\n        fields.push_back(tmp);\n      }\n      normal_new_args.push_back(WithFields(tuple_new_arg, fields));\n    } else {\n      Expr tmp = push_back_one_arg(new_arg);\n      normal_new_args.push_back(tmp);\n    }\n  }\n\n  // If there is no FInferCorrectLayout for the type, then we just assume the layout is correct.\n  static auto finfer_layout = Op::GetAttrMap<FInferCorrectLayout>(\"FInferCorrectLayout\");\n  if (Op::HasAttrMap(\"FTVMAlterOpLayout\")) {\n    static auto falter_layout = Op::GetAttrMap<FTVMAlterOpLayout>(\"FTVMAlterOpLayout\");\n    if (ref_call->op.as<OpNode>()) {\n      Op op = Downcast<Op>(ref_call->op);\n      if (falter_layout.count(op) && !finfer_layout.count(op)) {\n        return memorizer->CallWithNewLayouts(ref_call, normal_new_args);\n      }\n    }\n  }\n\n  // old_prd, new_prd = state[inputs]\n  // different ops can view a tensor with different layouts, e.g. conv_1->transpose(H, W)->conv_2\n  // transpose view its output having NCWH layout, but conv_2 still views it as NCHW to operate\n  // old_prd, new_prd: the input layouts from the perspective of the producer (transpose)\n  // old_cur, new_cur: the input layouts from the perspective of the current node (conv_2)\n  // old_prd->new_prd tells how producer changed the layout\n  // old_cur->new_cur tells what change the current node wants to see\n  // No layout transforms are needed when they mean the same (NCHW->NCHW4c == NCWH->NCWH4c)\n\n  // The workflow:\n  // 1. Run InferCorrectLayouts(NULL, old_prd) to get old_cur\n  // 2. Run InferCorrectLayouts(new_prd, old_prd) to get new_cur and rewrite the current op\n\n  Array<Layout> old_prd, old_cur, old_out, new_prd, new_out, new_cur;\n  for (auto inp : inputs) {\n    old_prd.push_back(inp->old_layout);\n    new_prd.push_back(inp->new_layout);\n  }\n\n  // Collect input types to pass on to Infer Correct Layout.\n  tvm::Array<tvm::relay::Type> types;\n  for (auto arg : ref_call->args) {\n    types.push_back(arg->checked_type());\n  }\n\n  bool success = false;\n  InferCorrectLayoutOutput infer_out;\n  std::tie(infer_out, success) =\n      InferCorrectLayouts(ref_call, Array<Layout>(nullptr), old_prd, types);\n  old_cur = infer_out->input_layouts;\n  old_out = infer_out->output_layouts;\n  if (!success) {\n    return Expr(nullptr);\n  }\n  ICHECK_EQ(old_cur.size(), new_prd.size());\n\n  // for backward compatibility of InferCorrectLayouts\n  Array<Layout> new_prd_inferred = new_prd;\n  // if new_prd_inferred == 'undef':  new_prd_inferred = old_cur\n  for (size_t i = 0; i < new_prd_inferred.size(); ++i) {\n    if (!new_prd_inferred[i].defined()) {\n      new_prd_inferred.Set(i, old_cur[i]);\n    }\n  }\n  Array<Layout> old_prd_inferred = old_prd;\n  // if old_prd_inferred == 'undef':  old_prd_inferred = old_cur\n  for (size_t i = 0; i < old_prd_inferred.size(); ++i) {\n    if (!old_prd_inferred[i].defined()) {\n      old_prd_inferred.Set(i, old_cur[i]);\n    }\n  }\n\n  // new_op = alter(op)\n  Call new_call = memorizer->CallWithNewLayouts(ref_call, infer_out->new_attrs, normal_new_args);\n\n  // new_cur, new_out = op.infer(new_prd)\n  if (new_call->op->IsInstance<OpNode>()) {\n    success = false;\n    std::tie(infer_out, success) =\n        InferCorrectLayouts(new_call, new_prd_inferred, old_prd_inferred, types);\n    new_cur = infer_out->input_layouts;\n    new_out = infer_out->output_layouts;\n    if (!success) {\n      return Expr(nullptr);\n    }\n  } else {\n    return Expr(nullptr);\n  }\n\n  ICHECK_EQ(new_out.size(), old_out.size())\n      << \"The number of output nodes should keep the same during alter_op_layout\";\n  ICHECK_EQ(new_prd.size(), new_cur.size())\n      << \"The number of input nodes should keep the same during alter_op_layout\";\n\n  auto transform_layout = [&memorizer](Expr arg_item, const Layout& old_prd, const Layout& old_cur,\n                                       const Layout& new_prd, const Layout& new_cur) {\n    if (old_cur.Equals(old_prd)) {  // the two transforms can be fused to one\n      arg_item = memorizer.Transform(arg_item, new_prd, new_cur);\n    } else {\n      if (old_prd.defined()) arg_item = memorizer.Transform(arg_item, new_prd, old_prd);\n      arg_item = memorizer.Transform(arg_item, old_cur, new_cur);\n    }\n    return arg_item;\n  };\n\n  DLOG(INFO) << \"Transforming layout for `\" << ref_call->op << \"`\";\n  DLOG(INFO) << \" old_prd=\" << old_prd;\n  DLOG(INFO) << \" new_prd=\" << new_prd;\n  DLOG(INFO) << \" old_cur=\" << old_cur;\n  DLOG(INFO) << \" new_cur=\" << new_cur;\n\n  // if (new_prd != new_cur): insert transform (new_prd -> new_cur)\n  Array<Expr> transformed_args;\n  size_t pt = 0;\n  for (auto arg : new_call->args) {\n    if (arg->IsInstance<TupleNode>()) {  // unflatten tuple\n      Tuple tuple_arg = Downcast<Tuple>(arg);\n      Array<Expr> transformed_tuple_arg;\n      transformed_tuple_arg.reserve(tuple_arg->fields.size());\n      for (auto arg_item : tuple_arg->fields) {\n        transformed_tuple_arg.push_back(\n            transform_layout(arg_item, old_prd[pt], old_cur[pt], new_prd[pt], new_cur[pt]));\n        pt++;\n      }\n      transformed_args.push_back(WithFields(tuple_arg, transformed_tuple_arg));\n    } else {\n      transformed_args.push_back(\n          transform_layout(arg, old_prd[pt], old_cur[pt], new_prd[pt], new_cur[pt]));\n      pt++;\n    }\n  }\n  ICHECK_EQ(pt, inputs.size());\n\n  // state[node] = (old_out, new_out)\n  // (handle tuple output)\n  if (ref_call->checked_type()->IsInstance<TupleTypeNode>()) {\n    Expr tuple_output = Call(new_call->op, transformed_args, infer_out->new_attrs);\n    Array<Expr> fields;\n    for (size_t i = 0; i < new_out.size(); ++i) {\n      auto rnode = make_object<LayoutAlternatedExprNode<TransformMemorizerT>>();\n      rnode->value = TupleGetItem(tuple_output, i);\n      rnode->old_layout = old_out[i];\n      rnode->new_layout = new_out[i];\n      rnode->memorizer = memorizer;\n      fields.push_back(Expr(rnode));\n    }\n    return Tuple(fields);\n  } else {\n    auto rnode = make_object<LayoutAlternatedExprNode<TransformMemorizerT>>();\n    ICHECK_EQ(new_out.size(), 1);\n    rnode->value = Call(new_call->op, transformed_args, infer_out->new_attrs, {}, ref_call->span);\n    rnode->old_layout = old_out[0];\n    rnode->new_layout = new_out[0];\n    rnode->memorizer = memorizer;\n    return Expr(rnode);\n  }\n}\n\n}  //  namespace relay\n}  //  namespace tvm\n\n#endif  // TVM_RELAY_TRANSFORMS_TRANSFORM_LAYOUT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/aot_executor/aot_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Defines an implementation of Module-based Model Runtime Interface that works with\n *        Ahead-of-Time compilation.\n * \\file aot_executor.h\n */\n#ifndef TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_H_\n#define TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_H_\n\n#include <tvm/runtime/metadata.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\nclass TVM_DLL AotExecutor : public ModuleNode {\n public:\n  /*!\n   * \\brief Implements member function lookup for this Module for the frontend.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) override;\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const final { return \"AotExecutor\"; }\n\n  void Run();\n\n  /*!\n   * \\brief Initialize the AOT executor with metadata, runtime::Module, and device.\n   * \\param module The module containing the compiled functions for the host\n   *  processor.\n   * \\param devs A 1-element vector. The Device which AOT compute will run on. Currently, only\n   *  Device(kDLCPU, 0) is supported.\n   */\n  AotExecutor(tvm::runtime::Module module, const std::vector<Device>& devs);\n\n  /*!\n   * \\brief Get the input index given the name of input.\n   * \\param name The name of the input.\n   * \\return The index of input.\n   */\n  int GetInputIndex(const std::string& name);\n\n  /*!\n   * \\brief Get the output index given the name of output.\n   * \\param name The name of the output.\n   * \\return The index of output.\n   */\n  int GetOutputIndex(const std::string& name);\n\n  /*!\n   * \\brief set index-th input to the graph.\n   * \\param index The input index.\n   * \\param data_in The input data.\n   */\n  void SetInput(int index, DLTensor* data_in);\n  /*!\n   * \\brief set index-th input to the graph without copying the data\n   * \\param index The input index.\n   * \\param data_ref The input data that is referred.\n   */\n  void SetInputZeroCopy(int index, DLTensor* data_ref);\n  /*!\n   * \\brief set index-th output to the graph without copying the data.\n   * \\param index The output index.\n   * \\param data_ref The output data that is referred.\n   */\n  void SetOutputZeroCopy(int index, DLTensor* data_ref);\n  /*!\n   * \\brief Get the number of outputs\n   *\n   * \\return The number of outputs from graph.\n   */\n  int NumOutputs() const;\n  /*!\n   * \\brief Get the number of inputs\n   *\n   * \\return The number of inputs to the graph.\n   */\n  int NumInputs() const;\n  /*!\n   * \\brief Return NDArray for given input index.\n   * \\param index The input index.\n   *\n   * \\return NDArray corresponding to given input node index.\n   */\n  NDArray GetInput(int index) const;\n  /*!\n   * \\brief Return NDArray for given output index.\n   * \\param index The output index.\n   *\n   * \\return NDArray corresponding to given output node index.\n   */\n  NDArray GetOutput(int index) const;\n  /*!\n   * \\brief Copy index-th output to data_out.\n   * \\param index The output index.\n   * \\param data_out the output data.\n   */\n  void CopyOutputTo(int index, DLTensor* data_out);\n\n private:\n  /*! \\brief Metadata provided to the runtime from the compiler. */\n  metadata::Metadata metadata_;\n\n  /*! \\brief Runtime module which contains the AOT top-level function. */\n  Module module_;\n\n  /*! \\brief The devices which should be used to execute the computations. */\n  std::vector<Device> devices_;\n\n  /*! \\brief Holds one NDArray per function argument in the same order. */\n  std::vector<NDArray> args_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/aot_executor/aot_executor_factory.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/aot_executor/aot_executor_factory.h\n * \\brief Aot executor factory creating aot executor.\n */\n\n#ifndef TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_FACTORY_H_\n#define TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_FACTORY_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"./aot_executor.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass TVM_DLL AotExecutorFactory : public runtime::ModuleNode {\n public:\n  /*!\n   * \\brief Construct the AotExecutorFactory.\n   * \\param params The params of aot.\n   * \\param module_name The module name of aot.\n   */\n  AotExecutorFactory(const std::unordered_map<std::string, tvm::runtime::NDArray>& params,\n                     const std::string& module_name);\n\n  /*!\n   * \\brief Get member function to front-end\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const final { return \"AotExecutorFactory\"; }\n\n  /*!\n   * \\brief Save the module to binary stream.\n   * \\param stream The binary stream to save to.\n   */\n  void SaveToBinary(dmlc::Stream* stream) override;\n\n  /*!\n   * \\brief Create a specific executor module\n   * \\param devs The device of the host and devices where the model will be\n   *  executed.\n   * \\return created executor module\n   */\n  Module ExecutorCreate(const std::vector<Device>& devs);\n\n  /*!\n   * \\brief Set params.\n   * \\param aot_executor The aot executor we want to set the params into.\n   * \\param params The aot params value we want to set.\n   */\n  void SetParams(AotExecutor* aot_executor,\n                 const std::unordered_map<std::string, tvm::runtime::NDArray>& params) const {\n    std::unordered_map<std::string, tvm::runtime::NDArray> value = params;\n    // upload big arrays first to avoid memory issue in rpc mode\n    std::vector<std::string> keys;\n    for (const auto& p : value) {\n      keys.emplace_back(p.first);\n    }\n    std::sort(std::begin(keys), std::end(keys),\n              [&](const std::string& lhs, const std::string& rhs) -> bool {\n                auto lhs_size = GetDataSize(*value[lhs].operator->());\n                auto rhs_size = GetDataSize(*value[rhs].operator->());\n                return lhs_size > rhs_size;\n              });\n    for (const auto& key : keys) {\n      int in_idx = aot_executor->GetInputIndex(key);\n      if (in_idx >= 0) {\n        aot_executor->SetInput(in_idx, const_cast<DLTensor*>(value[key].operator->()));\n      }\n    }\n  }\n\n protected:\n  /*! \\brief The params. */\n  std::unordered_map<std::string, tvm::runtime::NDArray> params_;\n  /*! \\brief module name */\n  std::string module_name_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_AOT_EXECUTOR_AOT_EXECUTOR_FACTORY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/const_loader_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file const_loader_module.h\n * \\brief Defines an interface to use the ConstLoaderModule.\n */\n\n#ifndef TVM_RUNTIME_CONST_LOADER_MODULE_H_\n#define TVM_RUNTIME_CONST_LOADER_MODULE_H_\n\n#include <tvm/runtime/ndarray.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Create a ConstLoader module object.\n *\n * \\param const_var_ndarray Maps consts var name to NDArray containing data for the var.\n * \\param const_vars_by_symbol Maps the name of a module init function to a list of names of\n * const vars whose data will be passed to that init function.\n *\n * \\return The created ConstLoaderModule.\n */\nModule ConstLoaderModuleCreate(\n    const std::unordered_map<std::string, NDArray>& const_var_ndarray,\n    const std::unordered_map<std::string, std::vector<std::string>>& const_vars_by_symbol);\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONST_LOADER_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/arm_compute_lib/acl_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/arm_compute_lib/acl_allocator.h\n * \\brief ACL Allocator implementation that requests memory from TVM.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_ALLOCATOR_H_\n#define TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_ALLOCATOR_H_\n\n#include <arm_compute/runtime/IAllocator.h>\n#include <arm_compute/runtime/IMemoryRegion.h>\n#include <arm_compute/runtime/MemoryRegion.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/registry.h>\n\n#include <memory>\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*!\n * \\brief Override ACL memory allocator and replace with TVM workspace based allocation.\n */\nclass ACLAllocator : public arm_compute::IAllocator {\n public:\n  ACLAllocator() = default;\n\n  /*!\n   * \\brief Allocate bytes to ACL runtime.\n   *\n   * Specific implementation requests memory from TVM using their device api.\n   *\n   * \\param size Size to allocate.\n   * \\param alignment Alignment that the returned pointer should comply with.\n   * \\return A pointer to the allocated memory.\n   */\n  void* allocate(size_t size, size_t alignment) override;\n\n  /*!\n   * \\brief Free memory from ACL runtime.\n   *\n   * \\param ptr Pointer to workspace to free.\n   */\n  void free(void* ptr) override;\n\n  /*!\n   * \\brief Create self-managed memory region.\n   *\n   * \\param size Size of the memory region.\n   * \\param alignment Alignment of the memory region.\n   * \\return The memory region object.\n   */\n  std::unique_ptr<arm_compute::IMemoryRegion> make_region(size_t size, size_t alignment) override;\n\n private:\n  /*! \\brief Always allocate data in the context of the current CPU. */\n  const Device device_{kDLCPU, 0};\n  /*! \\brief Device API which allows requests for memory from TVM. */\n  runtime::DeviceAPI* device_api_ = runtime::DeviceAPI::Get(device_);\n};\n\n/*!\n * \\brief Memory region that can request TVM memory for ACL to use.\n */\nclass ACLMemoryRegion : public arm_compute::IMemoryRegion {\n public:\n  ACLMemoryRegion(size_t size, size_t alignment);\n  ACLMemoryRegion(void* ptr, size_t size);\n\n  ~ACLMemoryRegion() override;\n\n  /*! \\brief Prevent instances of this class from being copied (As this class contains\n   * pointers). */\n  ACLMemoryRegion(const ACLMemoryRegion&) = delete;\n  /*! \\brief Default move constructor. */\n  ACLMemoryRegion(ACLMemoryRegion&&) = default;\n  /*! \\brief Prevent instances of this class from being copied (As this class\n   * contains pointers) */\n  ACLMemoryRegion& operator=(const ACLMemoryRegion&) = delete;\n  /*! Default move assignment operator. */\n  ACLMemoryRegion& operator=(ACLMemoryRegion&&) = default;\n\n  void* buffer() override { return this->ptr_; }\n\n  const void* buffer() const override { return this->ptr_; }\n\n  /*!\n   * \\brief Extract a sub-region from the memory.\n   *\n   * \\warning Ownership is maintained by the parent memory,\n   *          while a wrapped raw memory region is returned by this function.\n   *          Thus parent memory should not be released before this.\n   *\n   * \\param offset Offset to the region.\n   * \\param size Size of the region.\n   * \\return A wrapped memory sub-region with no ownership of the\n   * underlying memory.\n   */\n  std::unique_ptr<arm_compute::IMemoryRegion> extract_subregion(size_t offset,\n                                                                size_t size) override;\n\n private:\n  /*! \\brief Points to a region of memory allocated by TVM. */\n  void* ptr_;\n  /*! \\brief A subregion doesn't manage TVM memory so we don't need to free it. */\n  bool is_subregion_ = false;\n  /*! \\brief Always allocate data in the context of the current CPU. */\n  const Device device_{kDLCPU, 0};\n  /*! \\brief Device API which allows requests for memory from TVM. */\n  runtime::DeviceAPI* device_api_ = runtime::DeviceAPI::Get(device_);\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/arm_compute_lib/acl_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/arm_compute_lib/acl_utils.h\n * \\brief Utils and common functions for the interface.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_UTILS_H_\n\n#include <arm_compute/core/Types.h>\n#include <arm_compute/runtime/MemoryManagerOnDemand.h>\n#include <arm_compute/runtime/Tensor.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"../json/json_node.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing JSONGraphNode = tvm::runtime::json::JSONGraphNode;\n\n/*!\n * \\brief Check if there are any errors from acl and forward them to TVM.\n *\n * Status values:\n * - 0 => OK\n * - 1 => RUNTIME_ERROR\n * - 2 => UNSUPPORTED_EXTENSION_USE\n *\n * \\param status status of called function.\n */\nvoid CheckACLError(const arm_compute::Status& status);\n\n/*!\n * \\brief Make an acl tensor from JSON tensor representation.\n *\n * \\param tensor_rep A JSON tensor representation.\n * \\param data (optional) Initialize the tensor with memory.\n * \\param scale (optional) The quantization scale.\n * \\param offset (optional) The quantization offset.\n * \\return arm_compute::Tensor.\n */\narm_compute::Tensor MakeACLTensor(const JSONGraphNode& tensor_rep, void* data = nullptr,\n                                  const DLTensor* scale = nullptr, const DLTensor* offset = nullptr,\n                                  bool apply_dim_correction = true, bool increase_dim_unit = true,\n                                  uint32_t entry_index = 0);\n\n/*!\n * \\brief Make an acl tensor info object from JSON tensor\n * representation.\n *\n * \\param shape The shape of the tensor to create.\n * \\param dtype The data type of the tensor to create.\n * \\param scale (optional) The quantization scale.\n * \\param offset (optional) The quantization offset.\n * \\return arm_compute::TensorInfo.\n */\narm_compute::TensorInfo MakeACLTensorInfo(const std::vector<int64_t>& shape,\n                                          const DLDataType& dtype, const DLTensor* scale = nullptr,\n                                          const DLTensor* offset = nullptr,\n                                          bool apply_dim_correction = true,\n                                          bool increase_dim_unit = true);\n\n/*!\n * \\brief Create a memory manager for use with a layer that\n * requires working memory.\n *\n * \\return reference counted memory manager.\n */\nstd::shared_ptr<arm_compute::MemoryManagerOnDemand> MakeACLMemoryManager();\n\n/*!\n * \\brief Convert TVM padding and stride format to acl PadStrideInfo.\n *\n * \\param pad The pad vector.\n * \\param stride The stride vector.\n * \\param ceil_mode Dimensions rounding.\n * \\return arm_compute::PadStrideInfo\n */\narm_compute::PadStrideInfo MakeACLPadStride(const std::vector<std::string>& pad,\n                                            const std::vector<std::string>& stride,\n                                            bool ceil_mode = false);\n\n/*!\n * \\brief Convert DLDataType to arm_compute::DataType.\n *\n * \\param data_type The data type to convert.\n * \\return arm_compute::DataType.\n */\narm_compute::DataType MakeACLDataType(const DLDataType& data_type);\n\n/*!\n * \\brief Convert string to arm_compute::ActivationLayerInfo\n *\n * \\param activation_type A string representing activation function.\n * Currently supports the following options: \"relu\".\n * \\return arm_compute::ActivationLayerInfo.\n */\narm_compute::ActivationLayerInfo MakeACLActivationInfo(const std::string& activation_type);\n\n/*!\n * \\brief Get a vector from DLTensor data.\n * \\note Performs a copy of data.\n *\n * \\tparam T The type of the vector.\n * \\param tensor The tensor to convert.\n * \\return Vector of type T.\n */\ntemplate <typename T>\nstd::vector<T> GetVectorFromDLTensor(const DLTensor* tensor);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_ARM_COMPUTE_LIB_ACL_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/bnns/bnns_wrp.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/**\n * \\file\n * \\brief C++ wrappers and helpers to handle BNNS objects\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_BNNS_BNNS_WRP_H_\n#define TVM_RUNTIME_CONTRIB_BNNS_BNNS_WRP_H_\n\n#include <Accelerate/Accelerate.h>\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\nnamespace BNNS {\n\nusing Dim = size_t;\nusing Shape = std::vector<Dim>;\nusing Dtype = BNNSDataType;\nusing HDL = void*;\n\nvoid* default_alloc(size_t size) { return malloc(size); }\n\nvoid default_free(void* ptr) { free(ptr); }\n\n/**\n * Main abstraction for tensor representation\n *\n * Contains buffer handler and common attributes like shape and dtype.\n */\nclass Tensor {\n public:\n  Tensor() = delete;\n  Tensor(Tensor&) = delete;\n\n  Tensor(Shape shape, Dtype dtype, void* hdl) {\n    auto rank = shape.size();\n    ICHECK(rank < BNNS_MAX_TENSOR_DIMENSION);\n\n    desc_ = {BNNSNDArrayFlags(0),\n             getPlainLayout(rank),\n             {},       // shape\n             {},       // strides\n             hdl,      // data handler\n             dtype,    // data type\n             nullptr,  // table_data (clustering case), is not used\n             dtype,\n             1.f,\n             0.f};\n    std::copy(shape.rbegin(), shape.rend(), std::begin(desc_.size));\n\n    desc_.data = hdl;\n    is_external_data = true;\n  }\n\n  ~Tensor() {\n    if (desc_.data && !is_external_data) {\n      default_free(desc_.data);\n      desc_.data = nullptr;\n    }\n  }\n\n  void allocate_memory() {\n    if (desc_.data && !is_external_data) {\n      default_free(desc_.data);\n    }\n    const size_t buff_size = getSize(desc_) * getElementSize(desc_);\n    desc_.data = default_alloc(buff_size);\n    ICHECK(desc_.data);\n    is_external_data = false;\n  }\n\n  void* get_data_hdl() const { return desc_.data; }\n\n  void set_data_hdl(void* hdl) {\n    if (desc_.data && !is_external_data) {\n      default_free(desc_.data);\n      desc_.data = nullptr;\n    }\n\n    desc_.data = hdl;\n    is_external_data = true;\n  }\n\n  const BNNSNDArrayDescriptor& get_desc() const { return desc_; }\n\n  static BNNSDataLayout getPlainLayout(size_t rank) {\n    ICHECK(rank <= BNNS_MAX_TENSOR_DIMENSION);\n    return static_cast<BNNSDataLayout>((rank << 16) | 0x8001);\n  }\n\n  static size_t getRank(BNNSDataLayout layout) { return (layout & 0xF0000) >> 16; }\n\n  static size_t getRank(BNNSNDArrayDescriptor desc) { return getRank(desc.layout); }\n\n  static size_t getSize(BNNSNDArrayDescriptor desc) {\n    auto rank = getRank(desc);\n    return std::accumulate(desc.size, desc.size + rank, 1, std::multiplies<int>());\n  }\n\n  /** return size of element in bytes */\n  static size_t getElementSize(Dtype dtype) { return (dtype & 0xFFFF) / 8; }\n\n  /** return size of element in bytes */\n  static size_t getElementSize(const BNNSNDArrayDescriptor& desc) {\n    return getElementSize(desc.data_type);\n  }\n\n private:\n  bool is_external_data = false;\n  BNNSNDArrayDescriptor desc_;\n};\n\nusing TensorPtr = std::shared_ptr<Tensor>;\n\n/**\n * Tensor View object which represent how provided BNNS::Tensor will be considered\n *\n * The single BNNS::Tensor can be treated in different form depend on particular primitive\n * expectation. More other some primitive supports only external form of batching. So we have\n * some abstraction to describe how primitive will handle provided tensor.\n *\n * Batched View\n *   View with extracted dimension as external batch value\n *   example: Tensor [2, 3, 224, 224] -> View [3, 224, 224] with ext batch 2\n *\n * Party View\n *   The collection of view on the same tensor, can be the same view or with some stride\n *   example: Tensor [6, 5, 3, 3] -> 3 x View [2, 5, 3, 3] with stride 45\n */\nclass TView {\n public:\n  /** Make view on provided tensor as is */\n  static TView as_is(const TensorPtr& origin) {\n    TView res;\n    res.origin_ = origin;\n    res.view_desc_ = origin->get_desc();\n    return res;\n  }\n\n  /** Extract outer dimension to separate batch field. TView will became batched view */\n  TView extract_outer_dim() const {\n    auto rank = Tensor::getRank(view_desc_);\n    TView res = *this;\n    res.batch_size_ = view_desc_.size[rank - 1];\n    res.batch_stride_ =\n        std::accumulate(view_desc_.size, view_desc_.size + rank - 1, 1, std::multiplies<>());\n    res.view_desc_.size[rank - 1] = 0;\n    res.view_desc_.layout = Tensor::getPlainLayout(rank - 1);\n    return res;\n  }\n\n  /** Squeeze all dims equal 1 */\n  TView squeeze(size_t min_rank = 1) const {\n    auto rank = Tensor::getRank(view_desc_);\n    size_t squeezed_shape[BNNS_MAX_TENSOR_DIMENSION] = {};\n    size_t squeezed_rank = 0;\n    for (int i = 0; i < rank; i++)\n      if (view_desc_.size[i] != 1) squeezed_shape[squeezed_rank++] = view_desc_.size[i];\n\n    if (min_rank > squeezed_rank) {\n      std::fill(squeezed_shape + squeezed_rank, squeezed_shape + min_rank, 1);\n      squeezed_rank = min_rank;\n    }\n\n    TView res = *this;\n    std::copy(squeezed_shape, squeezed_shape + squeezed_rank, res.view_desc_.size);\n    std::fill(res.view_desc_.size + squeezed_rank, res.view_desc_.size + rank, 0);\n    res.view_desc_.layout = Tensor::getPlainLayout(squeezed_rank);\n    return res;\n  }\n\n  /** Expand the shape of an array */\n  TView expand_dims(std::vector<size_t> axes) const {\n    auto rank = Tensor::getRank(view_desc_);\n    TView res = *this;\n    size_t unsqueezed_shape[BNNS_MAX_TENSOR_DIMENSION] = {};\n    size_t unsqueezed_rank = axes.size() + rank;\n    ICHECK_LE(unsqueezed_rank, BNNS_MAX_TENSOR_DIMENSION);\n    for (const auto& axis : axes) {\n      ICHECK_LT(axis, unsqueezed_rank);\n      unsqueezed_shape[axis] = 1;\n    }\n    for (int i = 0, orig_idx = 0; i < unsqueezed_rank; ++i) {\n      if (unsqueezed_shape[i] == 1) continue;\n      unsqueezed_shape[i] = view_desc_.size[orig_idx++];\n    }\n    std::copy(unsqueezed_shape, unsqueezed_shape + unsqueezed_rank, res.view_desc_.size);\n    res.view_desc_.layout = Tensor::getPlainLayout(unsqueezed_rank);\n    return res;\n  }\n\n  /** Unsqueeze tensor to a new rank */\n  TView unsqueeze(size_t new_rank) const {\n    ICHECK_LE(new_rank, BNNS_MAX_TENSOR_DIMENSION);\n    auto rank = Tensor::getRank(view_desc_);\n    ICHECK_GT(new_rank, rank);\n    std::vector<size_t> axes(new_rank - rank);\n    std::iota(axes.begin(), axes.end(), rank);\n    return expand_dims(axes);\n  }\n\n  /** Construct new TView with specified layout if it applicable */\n  TView with_layout(BNNSDataLayout layout) const {\n    ICHECK_EQ(Tensor::getRank(view_desc_), Tensor::getRank(layout));\n\n    TView res = *this;\n    res.view_desc_.layout = layout;\n    return res;\n  }\n\n  /** Construct party TView by splitting original TView into num parts */\n  TView party_split_n(size_t num) const {\n    ICHECK_EQ(party_size_, 1);\n\n    TView res = *this;\n    size_t rank = Tensor::getRank(view_desc_);\n    size_t size = Tensor::getSize(view_desc_);\n    res.party_size_ = num;\n    res.party_stride_ = size / num;\n\n    if (res.batch_size_ != 1) {\n      res.batch_size_ /= num;\n    } else {\n      res.view_desc_.size[rank - 1] /= num;\n      res.batch_stride_ /= num;\n    }\n    return res;\n  }\n\n  /** Construct party TView by duplicating original TView num times */\n  TView party_duplicate_n(size_t num) const {\n    ICHECK_EQ(party_size_, 1);\n\n    TView res = *this;\n    res.party_size_ = num;\n    res.party_stride_ = 0;\n\n    return res;\n  }\n\n  /** Return data buffer handler */\n  HDL get_data_hdl() const { return view_desc_.data; }\n\n  /** Return external batch dimension value */\n  size_t get_batch_size() const { return batch_size_; }\n\n  /** Return external batch dimension stride */\n  size_t get_stride() const { return batch_stride_; }\n\n  /** Return party element by index */\n  TView operator[](size_t i) const {\n    ICHECK_LT(i, party_size_);\n\n    TView res = *this;\n    res.party_size_ = 1;\n    if (origin_) {\n      auto hdl = reinterpret_cast<uint8_t*>(origin_->get_data_hdl());\n      hdl += i * party_stride_ * Tensor::getElementSize(view_desc_.data_type);\n      res.view_desc_.data = hdl;\n    }\n    return res;\n  }\n\n  /** Check if view is empty and doesn't relay to any tensor */\n  operator bool() const { return origin_ != nullptr; }\n\n  /** Get BNNS descriptor for particular View. Batch and Party attributed are ignored. */\n  const BNNSNDArrayDescriptor& get_bnns_view() const { return view_desc_; }\n\n private:\n  /** Original tensor object to view on */\n  TensorPtr origin_;\n\n  /** Batched view parameters */\n  BNNSNDArrayDescriptor view_desc_ = {};\n  size_t batch_size_ = 1;\n  size_t batch_stride_ = 0;\n\n  /** Party representation parameters */\n  size_t party_size_ = 1;\n  size_t party_stride_ = 0;\n};\n\n/**\n * Wrapper on top of BNNSFilter and src/dst TensorView.\n *\n * Support decomposed representation of filter and can execute sub primitives in parallel.\n */\nclass Primitive {\n public:\n  Primitive(const std::vector<BNNSFilter> fs, const TView& src, const TView& dst)\n      : filters(fs), src_view(src), dst_view(dst) {}\n\n  virtual ~Primitive() {\n    for (auto& filter : filters)\n      if (filter) {\n        BNNSFilterDestroy(filter);\n        filter = nullptr;\n      }\n  }\n\n  /** Execute primitive with using specified src/dst */\n  void execute() {\n    auto res = TVMBackendParallelLaunch(run_task, this, filters.size());\n    ICHECK_EQ(res, 0) << \"BNNS runtime. Primitive was not executed properly\";\n  }\n\n private:\n  virtual int execute_impl(int part_idx) {\n    const auto filter = this->filters[part_idx];\n    const auto src_view = this->src_view[part_idx];\n    const auto dst_view = this->dst_view[part_idx];\n\n    size_t mb = src_view.get_batch_size();\n\n    // NB! BNNS limitations\n    //   * Do not use simple BNNSFilterApply. There is a bug inside BNNS,\n    //     BNNSFilterApply doesn't work for grouped convolution.\n    //   * Group convolution doesn't support arbitrary stride for Batch dim.\n    //     The tensor should be dense.\n    return BNNSFilterApplyBatch(filter, mb, src_view.get_data_hdl(), src_view.get_stride(),\n                                dst_view.get_data_hdl(), dst_view.get_stride());\n  }\n\n  static int run_task(int task_id, TVMParallelGroupEnv* penv, void* cdata) {\n    auto prim = reinterpret_cast<Primitive*>(cdata);\n    return prim->execute_impl(task_id);\n  }\n\n protected:\n  /** BNNS kernels/filters collect which will execute primitive */\n  std::vector<BNNSFilter> filters = {};\n  const TView src_view;\n  const TView dst_view;\n};\n\n/**\n * Wrapper on top of BNNS::Primitive\n *\n * This primitive should be used for executing primitive with two inputs.\n */\nclass TwoInputPrimitive : public Primitive {\n public:\n  TwoInputPrimitive(const std::vector<BNNSFilter> fs, const TView& src, const TView& src2,\n                    const TView& dst)\n      : Primitive(fs, src, dst), src2_view(src2) {}\n\n private:\n  int execute_impl(int task_id) override {\n    const auto filter = this->filters[task_id];\n    const auto src_view = this->src_view[task_id];\n    const auto src2_view = this->src2_view[task_id];\n    const auto dst_view = this->dst_view[task_id];\n\n    size_t mb = src_view.get_batch_size();\n\n    return BNNSFilterApplyTwoInputBatch(filter, mb, src_view.get_data_hdl(), src_view.get_stride(),\n                                        src2_view.get_data_hdl(), src2_view.get_stride(),\n                                        dst_view.get_data_hdl(), dst_view.get_stride());\n  }\n\n protected:\n  const TView src2_view;\n};\n\n/**\n * Wrapper on top of BNNS::Primitive\n *\n * This primitive should be used for executing normalization filter\n */\nclass NormPrimitive : public Primitive {\n public:\n  using Primitive::Primitive;\n\n private:\n  int execute_impl(int task_id) override {\n    const auto filter = this->filters[task_id];\n    const auto src_view = this->src_view[task_id];\n    const auto dst_view = this->dst_view[task_id];\n\n    size_t mb = src_view.get_batch_size();\n    return BNNSNormalizationFilterApplyBatch(filter, mb, src_view.get_data_hdl(),\n                                             src_view.get_stride(), dst_view.get_data_hdl(),\n                                             dst_view.get_stride(), false);\n  }\n};\n\n/**\n * Wrapper on top of BNNS::Primitive\n *\n * This primitive should be used for executing pooling filter\n */\nclass PoolingPrimitive : public Primitive {\n public:\n  using Primitive::Primitive;\n\n private:\n  int execute_impl(int task_id) override {\n    const auto filter = this->filters[task_id];\n    const auto src_view = this->src_view[task_id];\n    const auto dst_view = this->dst_view[task_id];\n\n    size_t mb = src_view.get_batch_size();\n    return BNNSPoolingFilterApplyBatch(filter, mb, src_view.get_data_hdl(), src_view.get_stride(),\n                                       dst_view.get_data_hdl(), dst_view.get_stride(), nullptr, 0);\n  }\n};\n\n/**\n * Function which split primitive into sub primitives to parallel execution\n *\n * @param num requested num of sub primitives\n * @param orig_conv_param original convolution descriptor\n * @param src_view source tensor view\n * @param wgh_view weight tensor view\n * @param b_view bias tensor view\n * @param dst_view destination tensor view\n * @param num number of part to split into\n * @return collection of Convolution descriptors plus corresponding src/dst tensors view\n */\nstatic std::tuple<std::vector<BNNSLayerParametersConvolution>, TView, TView> split_to_n(\n    size_t num, const BNNSLayerParametersConvolution& orig_conv_param, const TView& src_view,\n    const TView& wgh_view, const TView& b_view, const TView& dst_view) {\n  size_t batch = src_view.get_batch_size();\n  size_t oc = dst_view.get_bnns_view().size[2];\n  size_t groups = orig_conv_param.groups;\n\n  BNNS::TView src_view_new;\n  BNNS::TView wgh_view_new;\n  BNNS::TView b_view_new;\n  BNNS::TView dst_view_new;\n\n  // TODO(apeskov): Add split by batch dim. Meanwhile we just disable it...\n  if (batch > 1 || oc % num != 0 || (groups > 1 && groups % num != 0)) {\n    return {{orig_conv_param}, src_view, dst_view};\n  }\n\n  // if groups > 1 split only by groups\n  // otherwise split inside one convolution by output channels\n  if (groups > 1) {\n    src_view_new = src_view.party_split_n(num);\n    groups = groups / num;\n  } else {\n    src_view_new = src_view.party_duplicate_n(num);\n  }\n\n  wgh_view_new = wgh_view.party_split_n(num);\n  b_view_new = b_view.party_split_n(num);\n  dst_view_new = dst_view.party_split_n(num);\n\n  std::vector<BNNSLayerParametersConvolution> res(num);\n  for (size_t i = 0; i < num; i++) {\n    auto& cur = res[i];\n    cur = orig_conv_param;\n\n    cur.i_desc = src_view_new[i].get_bnns_view();\n    cur.o_desc = dst_view_new[i].get_bnns_view();\n    cur.w_desc = wgh_view_new[i].get_bnns_view();\n    cur.bias = b_view_new[i].get_bnns_view();\n    cur.groups = groups;\n  }\n  return {res, src_view_new, dst_view_new};\n}\n\n}  // namespace BNNS\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_BNNS_BNNS_WRP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/cblas/gemm_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/contrib/gemm.h\n * \\brief Shared implementation of gemm\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_CBLAS_GEMM_COMMON_H_\n#define TVM_RUNTIME_CONTRIB_CBLAS_GEMM_COMMON_H_\n\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/registry.h>\n\n#include <algorithm>\n#include <string>\n\nnamespace tvm {\nnamespace contrib {\n\nusing namespace runtime;\ninline int ColumnStride(DLTensor* tensor) {\n  // If the tensor itself is transposed then it will have strides\n  // backward from what we expect.  Regardless, the max of the strides\n  // (the other stride is 1) is the column stride.\n  if (tensor->strides) {\n    return std::max(tensor->strides[0], tensor->strides[1]);\n  } else {\n    return tensor->shape[1];\n  }\n}\n\ninline int ElementStride(DLTensor* tensor) {\n  if (tensor->strides) {\n    return std::min(tensor->strides[0], tensor->strides[1]);\n  } else {\n    return 1;\n  }\n}\n\n// Reversed strides indicates an in-place transpose operation.\ninline bool IsInPlaceTransposed(DLTensor* tensor) {\n  return tensor->strides && (tensor->strides[1] > tensor->strides[0]);\n}\n\ninline int RowCount(DLTensor* tensor, bool trans) { return tensor->shape[trans ? 1 : 0]; }\n\ninline int ColumnCount(DLTensor* tensor, bool trans) { return tensor->shape[trans ? 0 : 1]; }\n\n// Call a column major blas.  Note that data is stored in tvm as row\n// major, so this we switch the arguments.\ntemplate <typename TGemmOp>\ninline void CallGemm(TVMArgs args, TVMRetValue* ret, TGemmOp op) {\n  DLTensor* A = args[0];\n  DLTensor* B = args[1];\n  DLTensor* C = args[2];\n  bool transa = args[3];\n  bool transb = args[4];\n  int bit_depth = sizeof(typename TGemmOp::TDatatype) * 8;\n  ICHECK_EQ(A->ndim, 2);\n  ICHECK_EQ(B->ndim, 2);\n  ICHECK_EQ(C->ndim, 2);\n\n  ICHECK_EQ(ElementStride(A), 1);\n  ICHECK_EQ(ElementStride(B), 1);\n  ICHECK_EQ(ElementStride(C), 1);\n\n  // C can never be transposed.\n  ICHECK(!IsInPlaceTransposed(C));\n\n  // Reversed strides indicates an in-place transpose operation.\n  transa = IsInPlaceTransposed(A) ? !transa : transa;\n  transb = IsInPlaceTransposed(B) ? !transb : transb;\n\n  ICHECK(TypeMatch(B->dtype, kDLFloat, bit_depth));\n  ICHECK(TypeMatch(C->dtype, kDLFloat, bit_depth));\n  double alpha = args.size() > 5 ? args[5] : 1.0;\n  double beta = args.size() > 6 ? args[6] : 0.0;\n  op(transb, transa, ColumnCount(B, transb), RowCount(A, transa), ColumnCount(A, transa),\n     static_cast<typename TGemmOp::TDatatype>(alpha),\n     reinterpret_cast<typename TGemmOp::TDatatype*>(static_cast<char*>(B->data) + B->byte_offset),\n     ColumnStride(B),\n     reinterpret_cast<typename TGemmOp::TDatatype*>(static_cast<char*>(A->data) + A->byte_offset),\n     ColumnStride(A), static_cast<typename TGemmOp::TDatatype>(beta),\n     reinterpret_cast<typename TGemmOp::TDatatype*>(static_cast<char*>(C->data) + C->byte_offset),\n     ColumnStride(C));\n}\n\n// Call a column major blas.  Note that data is stored in tvm as row\n// major, so this we switch the arguments.\ntemplate <typename TGemmOp>\ninline void CallU8S8S32Gemm(TVMArgs args, TVMRetValue* ret, TGemmOp op) {\n  DLTensor* A = args[0];\n  DLTensor* B = args[1];\n  DLTensor* C = args[2];\n  bool transa = args[3];\n  bool transb = args[4];\n\n  // Set the sgemm attributes. Currently, support is limited to CblasFixOffset with all offsets\n  // equal to 0. This is sufficient for relay dense.\n  std::string offset_ctype = \"CblasFixOffset\";\n  int16_t offset_a = 0;\n  int16_t offset_b = 0;\n  int offset_c[1];\n  offset_c[0] = 0;\n\n  ICHECK_EQ(A->ndim, 2);\n  ICHECK_EQ(B->ndim, 2);\n  ICHECK_EQ(C->ndim, 2);\n\n  ICHECK_EQ(ElementStride(A), 1);\n  ICHECK_EQ(ElementStride(B), 1);\n  ICHECK_EQ(ElementStride(C), 1);\n\n  // C can never be transposed.\n  ICHECK(!IsInPlaceTransposed(C));\n\n  // Reversed strides indicates an in-place transpose operation.\n  transa = IsInPlaceTransposed(A) ? !transa : transa;\n  transb = IsInPlaceTransposed(B) ? !transb : transb;\n\n  ICHECK(TypeMatch(A->dtype, kDLUInt, 8));\n  ICHECK(TypeMatch(B->dtype, kDLInt, 8));\n  ICHECK(TypeMatch(C->dtype, kDLInt, 32));\n  double alpha = args.size() > 5 ? args[5] : 1.0;\n  double beta = args.size() > 6 ? args[6] : 0.0;\n  op(transb, transa, ColumnCount(B, transb), RowCount(A, transa), ColumnCount(A, transa),\n     static_cast<float>(alpha),\n     reinterpret_cast<void*>(static_cast<char*>(B->data) + B->byte_offset), ColumnStride(B),\n     offset_b, reinterpret_cast<void*>(static_cast<char*>(A->data) + A->byte_offset),\n     ColumnStride(A), offset_a, static_cast<float>(beta),\n     reinterpret_cast<int*>(static_cast<char*>(C->data) + C->byte_offset), ColumnStride(C),\n     offset_ctype, offset_c);\n}\n\ninline int ColumnStride3D(DLTensor* tensor) {\n  // If the tensor itself is transposed then it will have strides\n  // backward from what we expect.  Regardless, the max of the strides\n  // (the other stride is 1) is the column stride.\n  if (tensor->strides) {\n    return std::max(tensor->strides[1], tensor->strides[2]);\n  } else {\n    return tensor->shape[2];\n  }\n}\ninline int ElementStride3D(DLTensor* tensor) {\n  if (tensor->strides) {\n    return std::min(tensor->strides[1], tensor->strides[2]);\n  } else {\n    return 1;\n  }\n}\n// Reversed strides indicates an in-place transpose operation.\ninline bool IsInPlaceTransposed3D(DLTensor* tensor) {\n  return tensor->strides && (tensor->strides[2] > tensor->strides[1]);\n}\ninline int BatchCount3D(DLTensor* tensor) { return tensor->shape[0]; }\ninline int RowCount3D(DLTensor* tensor, bool trans) { return tensor->shape[trans ? 2 : 1]; }\ninline int ColumnCount3D(DLTensor* tensor, bool trans) { return tensor->shape[trans ? 1 : 2]; }\ntemplate <typename TBatchGemmOp>\ninline void CallBatchGemm(TVMArgs args, TVMRetValue* ret, TBatchGemmOp op) {\n  using DType = typename TBatchGemmOp::TDatatype;\n  DLTensor* A = args[0];\n  DLTensor* B = args[1];\n  DLTensor* C = args[2];\n  bool transa = args[3];\n  bool transb = args[4];\n\n  int bit_depth = sizeof(DType) * 8;\n\n  ICHECK_EQ(A->ndim, 3);\n  ICHECK_EQ(B->ndim, 3);\n  ICHECK_EQ(C->ndim, 3);\n\n  int batch_size = BatchCount3D(C);\n  ICHECK_EQ(ElementStride(A), 1);\n  ICHECK_EQ(ElementStride(B), 1);\n  ICHECK_EQ(ElementStride(C), 1);\n\n  // C can never be transposed.\n  ICHECK(!IsInPlaceTransposed3D(C));\n  // Reversed strides indicates an in-place transpose operation.\n  transa = IsInPlaceTransposed3D(A) ? !transa : transa;\n  transb = IsInPlaceTransposed3D(B) ? !transb : transb;\n\n  ICHECK(TypeMatch(B->dtype, kDLFloat, bit_depth));\n  ICHECK(TypeMatch(C->dtype, kDLFloat, bit_depth));\n\n  double alpha = args.size() > 5 ? args[5] : 1.0;\n  double beta = args.size() > 6 ? args[6] : 0.0;\n\n  int A_stride = A->shape[1] * A->shape[2];\n  int B_stride = B->shape[1] * B->shape[2];\n  int C_stride = C->shape[1] * C->shape[2];\n\n  // Broadcast A or B by changing its stride.\n  int batch_size_a = BatchCount3D(A);\n  int batch_size_b = BatchCount3D(B);\n  if (batch_size_a != batch_size_b) {\n    if (batch_size_a == 1) {\n      A_stride = 0;\n    } else if (batch_size_b == 1) {\n      B_stride = 0;\n    }\n  } else {\n    ICHECK_EQ(batch_size_a, batch_size);\n    ICHECK_EQ(batch_size_b, batch_size);\n  }\n\n  DType* A_data = reinterpret_cast<typename TBatchGemmOp::TDatatype*>(static_cast<char*>(A->data) +\n                                                                      A->byte_offset);\n  DType* B_data = reinterpret_cast<typename TBatchGemmOp::TDatatype*>(static_cast<char*>(B->data) +\n                                                                      B->byte_offset);\n  DType* C_data = reinterpret_cast<typename TBatchGemmOp::TDatatype*>(static_cast<char*>(C->data) +\n                                                                      C->byte_offset);\n  op(batch_size, transb, transa, ColumnCount3D(B, transb), RowCount3D(A, transa),\n     ColumnCount3D(A, transa), static_cast<typename TBatchGemmOp::TDatatype>(alpha), B_data,\n     B_stride, ColumnStride3D(B), A_data, A_stride, ColumnStride3D(A),\n     static_cast<typename TBatchGemmOp::TDatatype>(beta), C_data, C_stride, ColumnStride3D(C));\n}\n\n}  // namespace contrib\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_CBLAS_GEMM_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/coreml/coreml_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief CoreML runtime that can run coreml model\n *        containing only tvm PackedFunc.\n * \\file coreml_runtime.h\n */\n#ifndef TVM_RUNTIME_CONTRIB_COREML_COREML_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_COREML_COREML_RUNTIME_H_\n\n#import <CoreML/CoreML.h>\n#import <Foundation/Foundation.h>\n\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief CoreML model.\n */\nclass CoreMLModel {\n public:\n  /*!\n   * \\brief constructor\n   * \\param url The directory where compiled models are located.\n   */\n  explicit CoreMLModel(NSURL* url) {\n    url_ = url;\n    model_ = [MLModel modelWithContentsOfURL:url error:nil];\n    input_dict_ = [NSMutableDictionary dictionary];\n    output_ = nil;\n  }\n  /*!\n   * \\brief Invoke the coreml prediction.\n   */\n  void Invoke();\n  /*!\n   * \\brief set input to the model.\n   * \\param key The input name.\n   * \\param data_in The input data.\n   */\n  void SetInput(const std::string& key, DLTensor* data_in);\n  /*!\n   * \\brief Return NDArray for given output index.\n   * \\param index The output index.\n   *\n   * \\return NDArray corresponding to given output node index.\n   */\n  NDArray GetOutput(int index) const;\n  /*!\n   * \\brief Return the number of outputs\n   *\n   * \\return The number of outputs\n   */\n  int GetNumOutputs() const;\n\n  // CoreML model url\n  NSURL* url_;\n  // CoreML model\n  MLModel* model_;\n  // CoreML model input dictionary\n  NSMutableDictionary<NSString*, id>* input_dict_;\n  // CoreML model output\n  id<MLFeatureProvider> output_;\n};\n\n/*!\n * \\brief CoreML runtime.\n *\n *  This runtime can be accessed in various language via\n *  TVM runtime PackedFunc API.\n */\nclass CoreMLRuntime : public ModuleNode {\n public:\n  /*!\n   * \\brief Get member function to front-end.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  /*!\n   * \\brief Serialize the content of the mlmodelc directory and save it to\n   *        binary stream.\n   * \\param stream The binary stream to save to.\n   */\n  void SaveToBinary(dmlc::Stream* stream) final;\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const { return \"coreml\"; }\n\n  /*!\n   * \\brief Initialize the coreml runtime with coreml model and context.\n   * \\param symbol The symbol of this model.\n   * \\param model_path The compiled model path.\n   */\n  void Init(const std::string& symbol, const std::string& model_path);\n\n  /*! \\brief The symbol that represents the Core ML model. */\n  std::string symbol_;\n\n  /*! \\brief The Core ML model */\n  std::unique_ptr<CoreMLModel> model_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_COREML_COREML_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/cublas/cublas_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Use external cudnn utils function\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_CUBLAS_CUBLAS_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_CUBLAS_CUBLAS_UTILS_H_\n\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n#include <cuda_runtime_api.h>\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/logging.h>\n\n#include <cstdint>\n#if CUDART_VERSION >= 10010\n#include <cublasLt.h>\n#endif  // CUDART_VERSION >= 10010\n\nnamespace tvm {\nnamespace contrib {\n\ninline const char* GetCublasErrorString(int error) {\n  switch (error) {\n    case CUBLAS_STATUS_NOT_INITIALIZED:\n      return \"CUBLAS_STATUS_NOT_INITIALIZED\";\n    case CUBLAS_STATUS_ALLOC_FAILED:\n      return \"CUBLAS_STATUS_ALLOC_FAILED\";\n    case CUBLAS_STATUS_INVALID_VALUE:\n      return \"CUBLAS_STATUS_INVALID_VALUE\";\n    case CUBLAS_STATUS_ARCH_MISMATCH:\n      return \"CUBLAS_STATUS_ARCH_MISMATCH\";\n    case CUBLAS_STATUS_MAPPING_ERROR:\n      return \"CUBLAS_STATUS_MAPPING_ERROR\";\n    case CUBLAS_STATUS_EXECUTION_FAILED:\n      return \"CUBLAS_STATUS_EXECUTION_FAILED\";\n    case CUBLAS_STATUS_INTERNAL_ERROR:\n      return \"CUBLAS_STATUS_INTERNAL_ERROR\";\n    case CUBLAS_STATUS_NOT_SUPPORTED:\n      return \"CUBLAS_STATUS_NOT_SUPPORTED\";\n    case CUBLAS_STATUS_LICENSE_ERROR:\n      return \"CUBLAS_STATUS_LICENSE_ERROR\";\n  }\n  return \"Unrecognized error\";\n}\n\n#ifndef CHECK_CUBLAS_ERROR\n#define CHECK_CUBLAS_ERROR(fn)                                                            \\\n  do {                                                                                    \\\n    int error = static_cast<int>(fn);                                                     \\\n    ICHECK_EQ(error, CUBLAS_STATUS_SUCCESS) << \"CUBLAS: \" << GetCublasErrorString(error); \\\n  } while (0)  // ; intentionally left off.\n#endif         // CHECK_CUBLAS_ERROR\n\nstruct CuBlasThreadEntry {\n  CuBlasThreadEntry();\n  ~CuBlasThreadEntry();\n  cublasHandle_t handle{nullptr};\n  static CuBlasThreadEntry* ThreadLocal();\n};  // CuBlasThreadEntry\n\ninline cudaDataType_t GetCudaDataType(DLDataType type) {\n  if (type.code == kDLInt) {\n    switch (type.bits) {\n      case 8:\n        return CUDA_R_8I;\n      case 32:\n        return CUDA_R_32I;\n    }\n  } else if (type.code == kDLUInt) {\n    switch (type.bits) {\n      case 8:\n        return CUDA_R_8U;\n      case 32:\n        return CUDA_R_32U;\n    }\n  } else if (type.code == kDLFloat) {\n    switch (type.bits) {\n      case 16:\n        return CUDA_R_16F;\n      case 32:\n        return CUDA_R_32F;\n      case 64:\n        return CUDA_R_64F;\n    }\n  }\n  LOG(FATAL) << \"Unsupported cuda type\";\n  return CUDA_R_16F;\n}\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_CUBLAS_CUBLAS_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/cudnn/cudnn_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Use external cudnn utils function\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_CUDNN_CUDNN_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_CUDNN_CUDNN_UTILS_H_\n\n#include <cudnn.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n\n#include <string>\n\n#include \"../../cuda/cuda_common.h\"\n\nnamespace tvm {\nnamespace contrib {\n\n#define CUDNN_CALL(func)                                                       \\\n  {                                                                            \\\n    cudnnStatus_t e = (func);                                                  \\\n    ICHECK_EQ(e, CUDNN_STATUS_SUCCESS) << \"cuDNN: \" << cudnnGetErrorString(e); \\\n  }\n\n/*! breif Convert DLTensor type to CuDNN type */\nstruct CuDNNDataType {\n  static cudnnDataType_t DLTypeToCuDNNType(const DLDataType& dtype);\n  template <int v>\n  static const void* GetConst(cudnnDataType_t type);\n};  // struct CuDNNDataType\n\ninline void GetStride(int nbdim, const int* dims, int* strides) {\n  int mul = 1;\n  for (int i = nbdim - 1; i >= 0; --i) {\n    mul *= dims[i];\n    strides[i] = mul;\n  }\n}\n\ninline void GetCudnnStride(int nbdim, const int* dims, int* strides) {\n  int mul = 1;\n  for (int i = nbdim - 1; i >= 0; --i) {\n    strides[i] = mul;\n    mul *= dims[i];\n  }\n}\n\nstruct ConvEntry {\n  cudnnConvolutionDescriptor_t conv_desc;\n  cudnnConvolutionMode_t mode{CUDNN_CROSS_CORRELATION};\n  cudnnDataType_t data_type;\n  cudnnTensorFormat_t tensor_format;\n  cudnnTensorDescriptor_t input_desc;\n  cudnnFilterDescriptor_t filter_desc;\n  cudnnTensorDescriptor_t bias_desc;\n  cudnnActivationDescriptor_t activation_desc;\n  cudnnTensorDescriptor_t output_desc;\n  cudnnConvolutionFwdAlgo_t fwd_algo;\n  cudnnConvolutionBwdDataAlgo_t bwd_data_algo;\n  cudnnConvolutionBwdFilterAlgo_t bwd_filter_algo;\n  // cudnnMathType_t math_type;\n  Device device;\n  runtime::DeviceAPI* cuda_api;\n  void* workspace{nullptr};\n  size_t workspace_size{0};\n  ConvEntry();\n  ~ConvEntry();\n  void UpdateWorkspace(const size_t wsize);\n  void CleanWorkspace();\n};  // ConvThreadEntry\n\nstruct SoftmaxEntry {\n  cudnnSoftmaxMode_t mode;\n  cudnnDataType_t data_type;\n  cudnnTensorDescriptor_t shape_desc;\n  SoftmaxEntry();\n  ~SoftmaxEntry();\n};  // SoftmaxEntry\n\nstruct CuDNNThreadEntry {\n  CuDNNThreadEntry();\n  ~CuDNNThreadEntry();\n\n  bool exists() const { return handle; }\n\n  cudnnHandle_t handle{nullptr};\n  ConvEntry conv_entry;\n  SoftmaxEntry softmax_entry;\n  runtime::DeviceAPI* cuda_api{nullptr};\n  static CuDNNThreadEntry* ThreadLocal(bool check_exists = true);\n};  // CuDNNThreadEntry\n\nvoid SetConvDescriptors(CuDNNThreadEntry* entry_ptr, int format, int dims, int groups,\n                        const int pad[], const int stride[], const int dilation[], int64_t x_dim[],\n                        int64_t w_dim[], int64_t y_dim[], DLDataType data_dtype,\n                        const std::string& conv_dtype);\n\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_CUDNN_CUDNN_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/curand/helper_cuda_kernels.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_CONTRIB_CURAND_HELPER_CUDA_KERNELS_H_\n#define TVM_RUNTIME_CONTRIB_CURAND_HELPER_CUDA_KERNELS_H_\n\n#include <curand.h>\n#include <tvm/runtime/registry.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace curand {\n\n/*!\n * \\brief An auxiliary function to convert an FP32 array to FP16.\n * \\param src The source FP32 array.\n * \\param dst The destination FP16 array.\n * \\param num The number of elements in the array.\n */\nvoid ConvertFp32toFp16(const void* src, void* dst, int64_t num);\n\n}  // namespace curand\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_CURAND_HELPER_CUDA_KERNELS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/dnnl/dnnl_kernel.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/dnnl/dnnl_kernel.h\n * \\brief Use external dnnl library kernels.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_DNNL_DNNL_KERNEL_H_\n#define TVM_RUNTIME_CONTRIB_DNNL_DNNL_KERNEL_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/registry.h>\n\n#include <vector>\n\n#include \"dnnl.hpp\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing namespace dnnl;\n\nextern \"C\" TVM_DLL void dnnl_conv2d(float* data, float* weights, float* out, int p_N_, int p_C_,\n                                    int p_H_, int p_W_, int p_O_, int p_G_, int p_Ph0_, int p_Pw0_,\n                                    int p_Ph1_, int p_Pw1_, int p_Kh_, int p_Kw_, int p_Sh_,\n                                    int p_Sw_);\n\nextern \"C\" TVM_DLL void dnnl_fused_conv2d_relu(float* data, float* weights, float* out, int p_N_,\n                                               int p_C_, int p_H_, int p_W_, int p_O_, int p_G_,\n                                               int p_Ph0_, int p_Pw0_, int p_Ph1_, int p_Pw1_,\n                                               int p_Kh_, int p_Kw_, int p_Sh_, int p_Sw_);\n\nextern \"C\" TVM_DLL void dnnl_fused_conv2d_bias_relu(float* data, float* weights, float* bias,\n                                                    float* out, int p_N_, int p_C_, int p_H_,\n                                                    int p_W_, int p_O_, int p_G_, int p_Ph0_,\n                                                    int p_Pw0_, int p_Ph1_, int p_Pw1_, int p_Kh_,\n                                                    int p_Kw_, int p_Sh_, int p_Sw_);\n\nextern \"C\" TVM_DLL void dnnl_dense(float* data, float* weight, float* out, int p_B_, int p_I_,\n                                   int p_O_);\n\nextern \"C\" TVM_DLL void dnnl_relu(float* data, float* out, std::vector<int64_t> shape);\n\nextern \"C\" TVM_DLL void dnnl_bn(float* data, float* gamma, float* beta, float* mean,\n                                float* variance, float* out, float* new_mean, float* new_variance,\n                                int p_n_, int p_c_, int p_h_, int p_w_, int p_e_);\n\nextern \"C\" TVM_DLL void dnnl_binary_op(float* data, float* weight, float* out, int binary_algo,\n                                       std::vector<int64_t> shape);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_DNNL_DNNL_KERNEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/dnnl/dnnl_tensor_requisite.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/dnnl/dnnl_tensor_requisite.cc\n * \\brief Helper TR wrapper to simplify tensors processing\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_DNNL_DNNL_TENSOR_REQUISITE_H_\n#define TVM_RUNTIME_CONTRIB_DNNL_DNNL_TENSOR_REQUISITE_H_\n\n#include <dlpack/dlpack.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <limits>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n// TODO(@apeskov): Have to mute warning from dnnl headers.\n//  -Wzero-as-null-pointer-constant and -Wdocumentation-unknown-command\n#include <dnnl.hpp>\n\n#include \"dnnl_utils.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing namespace utils;\n\n/*!\n * \\brief Helper object to simplify tensor transformation description.\n *\n * Allow to specify original source tensor and future actions which should be applied to it.\n * Can be treated as sequence of reordering or reinterpretation of original source tensor.\n * Finally TR can be solved as proper interpretation of source memory buffer, or sequence of\n * dnnl::reorder operators which will provide desired data.\n *\n * \\note Empty TR object allow any manipulation. Empty TR will be returned.\n *\n * \\sa TensorRegistry\n *\n * Example:\n * \\code\n *   dnnl::memory src_mem = ...;  // 5D tensor, shape {5, 2, 128, 128, 8}\n *\n *   // Construct TR\n *   auto tr = TensorRequisite.AsIs(src_mem, eid);  // 5D\n *\n *   // describe sequence of layout transformation\n *   tr = tr.TreatAs(\"ABCD8b\");  // 4D\n *   tr = tr.Permute({0, 2, 3, 1});  // Permute axes NCHW -> NHWC\n *   tr = tr.Crop({1, 128, 128, 16}, {0, 0, 0});  // extract first batch element\n *   tr = tr.Squeeze(); // 1D\n *\n *   // register TR\n *   TensorRegistry t_reg;\n *   auto t_id = t_reg.register(tr);\n *\n *   // Get final dnnl::memory object\n *   auto solver = t_reg.MakeSolver(ext_tensor_provider);\n *   auto mem = solver(t_id);\n * \\endcode\n *\n */\nclass TensorRequisite {\n public:\n  using Tid = uint32_t;\n  static constexpr Tid kUndefinedTid = std::numeric_limits<uint32_t>::max() - 1;\n\n  /*! \\brief Empty constructor */\n  TensorRequisite() {}\n\n  /*! \\brief Construct TR on top of existing memory object */\n  static TensorRequisite AsIs(const dnnl::memory& mem, Tid id = kUndefinedTid) {\n    auto res = AsIs(mem.get_desc(), id);\n    if (mem.get_data_handle() != nullptr) res.mem_ = mem;\n    return res;\n  }\n\n  /*! \\brief Construct TR on top of existing memory descriptor object */\n  static TensorRequisite AsIs(const dnnl::memory::desc& desc, Tid id = kUndefinedTid) {\n    return {desc, {}, false, {}, id, false};\n  }\n\n  /*! \\brief return logical shape of tensor */\n  dnnl::memory::dims dims() const { return t_desc_.dims(); }\n\n  /*! \\brief return data type of tensor */\n  dnnl::memory::data_type data_type() const { return t_desc_.data_type(); }\n\n  /*! \\brief return tensor desc */\n  dnnl::memory::desc desc() const { return t_desc_; }\n\n  Tid eid() const {\n    auto res = kUndefinedTid;\n\n    if (!defined()) {\n      res = kUndefinedTid;\n    } else if (eid_ == kUndefinedTid) {\n      if (orig_) {\n        res = orig_->eid();\n      } else {\n        res = kUndefinedTid;\n      }\n    } else {\n      res = eid_;\n    }\n    return res;\n  }\n\n  /*! \\brief Make TR with backward dataflow */\n  TensorRequisite Backward() const {\n    if (!defined()) return *this;\n    ICHECK(orig_ == nullptr);\n    return {t_desc_, orig_, reinterpret_, mem_, eid_, true};\n  }\n\n  /*! \\brief Produce TR with permuted axes */\n  TensorRequisite Permute(const std::vector<int>& permutation) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.permute_axes(permutation);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with reinterpret data of original tr */\n  TensorRequisite Reshape(const dnnl::memory::dims& shape) const {\n    if (!defined()) return *this;  // nothing for empty TR\n    if (t_desc_.dims() == shape) return *this;\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.reshape(shape);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with broadcasted values */\n  TensorRequisite Broadcast(const dnnl::memory::dims& shape) const {\n    if (!defined()) return *this;  // nothing for empty TR\n    if (t_desc_.dims() == shape) return *this;\n    ICHECK(!reverse_data_flow_);\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n\n    // numpy like broadcast\n    auto extended_dims = t_desc_.dims();\n    auto one_filled = dnnl::memory::dims(shape.size() - extended_dims.size(), 1);\n    extended_dims.insert(extended_dims.begin(), one_filled.begin(), one_filled.end());\n    auto desc = t_desc_.reshape(extended_dims);\n    for (size_t i = 0; i < extended_dims.size(); i++) {\n      if (extended_dims[i] == shape[i]) continue;\n      ICHECK(extended_dims[i] == 1);\n      ICHECK(desc.data.dims[i] == desc.data.padded_dims[i]);\n\n      desc.data.dims[i] = shape[i];\n      desc.data.padded_dims[i] = shape[i];\n      desc.data.format_desc.blocking.strides[i] = 0;\n    }\n\n    // reinterpret memory buffer with new strides\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with sub memory view (ROI) */\n  TensorRequisite Crop(const dnnl::memory::dims& shape, const dnnl::memory::dims& offset) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    ICHECK_EQ(shape.size(), t_desc_.dims().size());\n    ICHECK_EQ(offset.size(), t_desc_.dims().size());\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.submemory_desc(shape, offset, /*allow_empty=*/true);\n\n    // Originally DNNL implementation is very limited. Let's slightly enhance it.\n    if (!desc && t_desc_.data.format_kind == dnnl_blocked) {\n      bool offset_is_zero =\n          std::all_of(offset.begin(), offset.end(), [](auto el) { return el == 0; });\n\n      dnnl::memory::dims block_sizes(t_desc_.dims().size(), 1);\n      for (int i = 0; i < t_desc_.data.format_desc.blocking.inner_nblks; i++)\n        block_sizes[t_desc_.data.format_desc.blocking.inner_idxs[i]] *=\n            t_desc_.data.format_desc.blocking.inner_blks[i];\n\n      bool shape_reduction_less_than_block = true;\n      for (int i = 0; i < t_desc_.data.ndims; i++) {\n        shape_reduction_less_than_block &= t_desc_.data.dims[i] - shape[i] < block_sizes[i];\n      }\n\n      // This is auto padded case. Just update dims value.\n      if (offset_is_zero && shape_reduction_less_than_block) {\n        desc = t_desc_;\n        std::copy(shape.begin(), shape.end(), desc.data.dims);\n      }\n    }\n\n    ICHECK(desc);\n\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with squeeze shape */\n  TensorRequisite Squeeze(const dnnl::memory::dims& dims_to_squeeze = {}) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    dnnl::memory::dims squeezed_dims;\n    if (dims_to_squeeze.empty()) {\n      for (auto d : t_desc_.dims())\n        if (d != 1) squeezed_dims.push_back(d);\n    } else {\n      for (size_t i = 0; i < t_desc_.dims().size(); i++)\n        if (std::find(dims_to_squeeze.begin(), dims_to_squeeze.end(), i) == dims_to_squeeze.end())\n          squeezed_dims.push_back(t_desc_.dims()[i]);\n    }\n\n    if (squeezed_dims.empty()) squeezed_dims = {1};\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.reshape(squeezed_dims);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with specified layout descriptor */\n  TensorRequisite RequestLayout(dnnl::memory::desc desc) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    // If it's the same desc just return self\n    if (desc == t_desc_) return *this;\n\n    ICHECK(t_desc_.dims() == desc.dims()) << \"Requested layout is not compatible with \"\n                                             \"presented shape\";\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    return {desc, orig, false, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Define which logical dims ordering is default for particular layout string. */\n  static std::string DefaultLogicLayoutFor(const std::string& layout) {\n    // Rank is all non digit marked dims\n    auto it = layout.begin();\n    while (it != layout.end() && !std::isdigit(*it)) it++;\n    int rank = std::distance(layout.begin(), it);\n\n    static const std::vector<std::string> sparse_dims = {\"W\", \"HW\", \"DHW\"};\n    if (layout.find(\"N\") != std::string::npos) return \"NC\" + sparse_dims[rank - 3];\n    if (layout.find(\"G\") != std::string::npos) return \"GOI\" + sparse_dims[rank - 4];\n    if (layout.find(\"O\") != std::string::npos) return \"OI\" + sparse_dims[rank - 3];\n\n    LOG(FATAL) << \"Unknown layout \" << layout << \"There is no default scheme to handle it\";\n    return {};\n  }\n\n  /*!\n   * \\brief Treat TR shape as described in layout string.\n   *\n   * Blocked dimensions will be concatenated and put into proper shape position corresponding to  .\n   * resulting_layout_logic argument. If desired logic layout was not provided it will be deduced\n   * automatically based on some internal heuristics.\n   *\n   * Limitation 1. Blocking dims should be dense. Dims marked with digits use natural strides.\n   * Limitation 2. Blocking dims are innermost. Dims marked like 8c, 4o goes after regular\n   *               dimensions. NC8cHW4h4cD is not valid tensor in terms of DNNL. And cannot be\n   *               achieved with memory reinterpretation, so data copy is required. Proper layout\n   *               looks like NCHWD_8c4h4c, first part is outer dims, second digits marked part is\n   *               innermost.\n   */\n  TensorRequisite TreatAs(const std::string& layout, std::string desired_logic_layout = \"\") const {\n    if (!defined()) return *this;\n    if (desired_logic_layout.empty()) desired_logic_layout = DefaultLogicLayoutFor(layout);\n\n    const auto origin_dims = dims();\n\n    // split layout string to tokens {size, tag} like {16, 'C'}, {4, 'O'}\n    std::vector<std::pair<int, char>> layout_tokens;\n    for (auto it = layout.begin(); it != layout.end();) {\n      auto start = it;\n      while (std::isdigit(*it)) it++;\n      int blk_size = start == it ? -1 : std::stoi(std::string{start, it});\n      layout_tokens.push_back({blk_size, std::toupper(*it)});\n      it++;\n    }\n\n    // check applicability of layout\n    auto it = layout_tokens.begin();\n    while (it != layout_tokens.end() && it->first == -1) it++;\n    int rank = std::distance(layout_tokens.begin(), it);\n    while (it != layout_tokens.end()) {\n      ICHECK_NE(it->first, -1) << \"DNNL limitation. Blocking dims should be innermost. \"\n                               << \"But received layout is \" << layout;\n      it++;\n    }\n\n    ICHECK_EQ(layout_tokens.size(), origin_dims.size());\n    ICHECK_EQ(rank, desired_logic_layout.size()) << layout;\n\n    std::vector<std::pair<int, char>> outermost_tokens(layout_tokens.begin(),\n                                                       layout_tokens.begin() + rank);\n    std::vector<std::pair<int, char>> innermost_tokens(layout_tokens.begin() + rank,\n                                                       layout_tokens.end());\n    // define dim resulting dim positions\n    std::map<char, int> dim_position_by_tag;\n    for (size_t i = 0; i < desired_logic_layout.size(); i++)\n      dim_position_by_tag[std::toupper(desired_logic_layout[i])] = i;\n\n    // Construct resulting desc by modifying original one\n    dnnl::memory::desc res_desc = t_desc_;\n\n    memset(&res_desc.data.format_desc.blocking, 0, sizeof(res_desc.data.format_desc.blocking));\n    std::fill(res_desc.data.dims, res_desc.data.dims + DNNL_MAX_NDIMS, 0);\n    std::fill(res_desc.data.padded_dims, res_desc.data.padded_dims + DNNL_MAX_NDIMS, 0);\n\n    res_desc.data.ndims = rank;\n    res_desc.data.format_desc.blocking.inner_nblks = innermost_tokens.size();\n\n    auto res_dims = res_desc.data.dims;\n    auto res_strides = res_desc.data.format_desc.blocking.strides;\n    auto res_inner_blks = res_desc.data.format_desc.blocking.inner_blks;\n    auto res_inner_idxs = res_desc.data.format_desc.blocking.inner_idxs;\n\n    std::fill(res_dims, res_dims + rank, 1);\n\n    int orig_dim_idx = 0;\n    for (const auto& p : outermost_tokens) {\n      auto tag = p.second;\n      auto dim_size = origin_dims[orig_dim_idx];\n\n      auto result_dim_position = dim_position_by_tag[tag];\n      res_dims[result_dim_position] *= dim_size;\n      res_strides[result_dim_position] = t_desc_.data.format_desc.blocking.strides[orig_dim_idx];\n      orig_dim_idx++;\n    }\n    for (const auto& p : innermost_tokens) {\n      auto tag = p.second;\n      auto dim_size = origin_dims[orig_dim_idx];\n      auto result_dim_position = dim_position_by_tag[tag];\n      ICHECK_EQ(p.first, dim_size)\n          << \"Blocking layout is not applicable to tensor with shape: \" << origin_dims\n          << \". Requested layout is \" << layout;\n\n      res_dims[result_dim_position] *= dim_size;\n      *res_inner_blks++ = dim_size;\n      *res_inner_idxs++ = result_dim_position;\n      orig_dim_idx++;\n    }\n\n    // Assume tensor is dense. There is no additional padding.\n    std::copy(res_desc.data.dims, res_desc.data.dims + rank, res_desc.data.padded_dims);\n\n    if (t_desc_ == res_desc) return *this;\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    return {res_desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*!\n   * \\brief Produce TR with unspecified layout.\n   *\n   * Cannot be registered in TensorRegistry. Only for querying DNNL for preferred layouts.\n   */\n  TensorRequisite LayoutAny() const {\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // Recreate tensor desc with layout 'any'\n    dnnl::memory::desc any_desc{t_desc_.dims(), t_desc_.data_type(), dnnl::memory::format_tag::any};\n    return {any_desc, orig, false, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Check is TR is constant. */\n  bool IsConstant() const {\n    if (orig_) return orig_->IsConstant();\n    return mem_.operator bool();\n  }\n\n  /*! \\brief Check is tensor is scalar. */\n  bool IsScalar() const { return t_desc_.dims().size() == 1 && t_desc_.dims()[0] == 1; }\n\n  /*! \\brief Return const data memory if available. */\n  dnnl::memory GetConstData() const {\n    if (mem_) return mem_;\n    if (!orig_) return {};\n\n    if (auto orig_const_data = orig_->GetConstData()) {\n      if (reinterpret_) {\n        return {t_desc_, orig_const_data.get_engine(), orig_const_data.get_data_handle()};\n      } else {\n        auto eng = orig_const_data.get_engine();\n        auto res = dnnl::memory{t_desc_, eng};\n        dnnl::reorder(orig_const_data, res).execute(dnnl::stream(eng), orig_const_data, res);\n        return res;\n      }\n    }\n    return {};\n  }\n\n  /*!\n   * \\brief Return const data memory in form of vector.\n   *\n   * Same as GetConstData but use std::vector instead of dnnl::memory. Works only for 1D tensor\n   * and scalar TRs. Useful for specification of 1D DNNL attributes like zero_point or\n   * per_channel_scale\n   */\n  template <typename T>\n  std::vector<T> GetConstDataLikeVec() const {\n    auto const_data = GetConstData();\n    auto desc = const_data.get_desc();\n    ICHECK(desc.data_type() == utils::DnnlDType<T>());\n    ICHECK(desc.dims().size() == 1);\n\n    auto size = desc.get_size() / sizeof(T);\n    auto ptr = static_cast<T*>(const_data.get_data_handle());\n\n    return std::vector<T>(ptr, ptr + size);\n  }\n\n  /*! \\brief Get value of constant scalar tensor if possible. */\n  template <typename T>\n  T GetConstScalarData() const {\n    ICHECK(IsConstant());\n    ICHECK(IsScalar());\n    auto const_data = GetConstData();\n    auto desc = const_data.get_desc();\n    ICHECK(desc.data_type() == utils::DnnlDType<T>());\n\n    auto ptr = static_cast<T*>(const_data.get_data_handle());\n    return *ptr;\n  }\n\n  /*! \\brief Check if tensor is not empty. */\n  bool defined() const { return !t_desc_.is_zero(); }\n\n  /*! \\brief Same as defined */\n  operator bool() const { return defined(); }\n\n  /*!\n   * \\brief Check if tensor represent a reversed data flow.\n   * Useful for describing output processing\n   */\n  bool IsReversed() const { return reverse_data_flow_; }\n\n private:\n  TensorRequisite(const dnnl::memory::desc& t_desc, const std::shared_ptr<TensorRequisite>& orig,\n                  bool reinterpret, const dnnl::memory& const_mem, uint32_t eid,\n                  bool reverse_data_flow)\n      : t_desc_(t_desc),\n        orig_(orig),\n        reinterpret_(reinterpret),\n        mem_(const_mem),\n        eid_(eid),\n        reverse_data_flow_(reverse_data_flow) {\n    if (mem_) ICHECK(!orig_ && !reverse_data_flow_ && eid_ == kUndefinedTid);\n    if (eid_ != kUndefinedTid) ICHECK(!orig_);\n  }\n\n  /* Descriptor of particular tensor  */\n  dnnl::memory::desc t_desc_ = {};\n  /* Parent TR object which is referred from this TR */\n  std::shared_ptr<TensorRequisite> orig_ = {};\n  /* Flag to specify which action should be done with orig TR, reordering or reinterpretation */\n  bool reinterpret_ = false;\n  /* Const memory object if available */\n  dnnl::memory mem_ = {};\n  /* Entry ID of tensor if available */\n  uint32_t eid_ = kUndefinedTid;\n\n  /*\n   * Flag to describe reverse data flow case\n   * All operation on queue will be executed in reverse order. Actual for dst tensor description\n   */\n  bool reverse_data_flow_ = false;\n\n  friend class TensorRegistry;\n};\n\n/*!\n * \\brief The registry of tensors. Implement matching of provided TRs and real memory buffers.\n *\n * Registration of TR performed by calling method Register(), which will return ArgId object.\n * ArgId can be mapped to real memory via memory solver created by method MakeSolver().\n */\nclass TensorRegistry {\n private:\n  enum ArgReqFlag {\n    CONST,        /// < Constant tensor. ExecutionCTX independent\n    TMP_STORAGE,  /// < Intermediate tensors. Stored inside TensorRegistry. Inaccessible outside\n    EXT_EID,      /// < External data. Input or Output.\n  };\n\n public:\n  struct ArgId {\n    TensorRegistry::ArgReqFlag flag_;\n    uint32_t idx_;\n  };\n\n  using Action = std::tuple<dnnl::primitive, std::unordered_map<int, ArgId>>;\n  using ActionQue = std::vector<Action>;\n  using DLTensorProvider = std::function<const DLTensor*(uint32_t)>;\n  using MemSolver = std::function<const dnnl::memory(ArgId)>;\n\n  TensorRegistry() = default;\n  TensorRegistry(const dnnl::engine& eng, const std::set<uint32_t>& ext_io_eid)\n      : tmp_mem_collection_(1), ext_io_eid_(ext_io_eid), eng_(eng), stream_(eng) {}\n\n  /*!\n   * \\brief Register TR to registry\n   *\n   * Resolution of TR may lead to introduction of intermediate memory buffers and additional\n   * transformation actions which should be performed before or after usage of corresponding memory\n   * buffer. Additional actions will be append to provided actions queue. Corresponding to\n   * tr.IsReversed() value actions should be executed before or after usage of resulting ArgId.\n   *\n   * \\param tr tensor requisite sequence to register\n   * \\param action resulting action queue. If TR resolution is required execution of some\n   *               transformation actions they will be put here\n   * \\return associated ArgId. Should be used as argument for MemSolver.\n   */\n  ArgId Register(const TensorRequisite& tr, ActionQue* action) {\n    // 1) Constant tensor. Direct reference\n    if (auto const_data = tr.GetConstData()) {\n      auto idx = const_mem_collection_.size();\n      const_mem_collection_.push_back(const_data);\n      return MakeArgReq(ArgReqFlag::CONST, static_cast<uint32_t>(idx));\n    }\n\n    // 2) EID mapped tensor. Direct reference\n    if (tr.eid_ != TensorRequisite::kUndefinedTid) {\n      if (ext_io_eid_.count(tr.eid_) == 0) {  // Not IO tensor, means it's intermediate\n        if (eid2idx_tmp_.count(tr.eid_)) {\n          auto idx = eid2idx_tmp_.at(tr.eid_);\n          return MakeArgReq(ArgReqFlag::TMP_STORAGE, idx);\n        } else {\n          // register himself\n          auto idx = tmp_mem_collection_.size();\n          tmp_mem_collection_.push_back(tr.t_desc_);\n          eid2idx_tmp_[tr.eid_] = idx;\n          return MakeArgReq(ArgReqFlag::TMP_STORAGE, static_cast<uint32_t>(idx));\n        }\n      } else {\n        auto idx = ext_mem_collection_.size();\n        ext_mem_collection_.push_back({tr.eid_, tr.t_desc_});\n        return MakeArgReq(ArgReqFlag::EXT_EID, static_cast<uint32_t>(idx));\n      }\n    }\n\n    // 3) Tensors with transform actions\n    if (tr.orig_) {\n      // recursive register of orig TR\n      auto orig_arg_req = Register(*tr.orig_, action);\n      if (tr.reinterpret_) {\n        return RegisterReinterpret(orig_arg_req, tr.t_desc_);\n      } else {\n        return RegisterReorder(orig_arg_req, tr.t_desc_, tr.reverse_data_flow_, action);\n      }\n    }\n\n    // 4) Scratchpad\n    ICHECK(!tr.orig_ && !tr.mem_ && tr.eid_ == TensorRequisite::kUndefinedTid);\n    auto idx = tmp_mem_collection_.size();\n    tmp_mem_collection_.push_back(tr.t_desc_);\n    tmp_mem_mapping_[idx] = 0;  // zero position tmp mem object is reserved for scratchpads\n\n    auto scratchpad_size = tr.t_desc_.get_size();\n    auto glob_scratchpad_size = tmp_mem_collection_[0].get_size();\n    if (scratchpad_size > glob_scratchpad_size) {\n      tmp_mem_collection_[0] =\n          dnnl::memory::desc({static_cast<dnnl::memory::dim>(scratchpad_size)},\n                             dnnl::memory::data_type::u8, dnnl::memory::format_tag::a);\n    }\n    return MakeArgReq(TMP_STORAGE, static_cast<uint32_t>(idx));\n  }\n\n  /*!\n   * \\brief Construct memory solver for all registered TRs.\n   * \\param ext_provider callback to resolve external IO buffers\n   * \\return memory solver object to match ArgId to dnnl::memory objects\n   */\n  MemSolver MakeSolver(const DLTensorProvider& ext_provider) const {\n    return MemSolverImpl(eng_, ext_provider, const_mem_collection_, ext_mem_collection_,\n                         tmp_mem_collection_, tmp_mem_mapping_);\n  }\n\n  void MarkInplace(const TensorRequisite& tr, const TensorRequisite& shared) {\n    const auto tr_id = tr.eid();\n    ICHECK(tr_id != TensorRequisite::kUndefinedTid);\n    const auto shared_id = shared.eid();\n    ICHECK(shared_id != TensorRequisite::kUndefinedTid);\n    eid2idx_tmp_[tr_id] = eid2idx_tmp_[shared_id];\n  }\n\n private:\n  ArgId RegisterReinterpret(ArgId src_ar, const dnnl::memory::desc& desc) {\n    switch (src_ar.flag_) {\n      case TMP_STORAGE: {\n        auto idx = tmp_mem_collection_.size();\n        tmp_mem_collection_.push_back(desc);\n        tmp_mem_mapping_[idx] = src_ar.idx_;\n        return MakeArgReq(TMP_STORAGE, idx);\n      }\n      case EXT_EID: {\n        auto ext_req = ext_mem_collection_[src_ar.idx_];\n        auto idx = ext_mem_collection_.size();\n        ext_mem_collection_.push_back({ext_req.first, desc});\n        return MakeArgReq(EXT_EID, idx);\n      }\n      default:\n        LOG(FATAL) << \"Unknown case\";\n    }\n    return {};\n  }\n\n  ArgId RegisterReorder(ArgId src_ar, const dnnl::memory::desc& desc, bool reverse_data_flow,\n                        ActionQue* action) {\n    ICHECK(src_ar.flag_ == TMP_STORAGE || src_ar.flag_ == EXT_EID);\n\n    auto src_desc = src_ar.flag_ == TMP_STORAGE ? tmp_mem_collection_[src_ar.idx_]\n                                                : ext_mem_collection_[src_ar.idx_].second;\n    auto idx = tmp_mem_collection_.size();\n    tmp_mem_collection_.push_back(desc);\n    auto dst_ar = MakeArgReq(TMP_STORAGE, idx);\n\n    // reorder action submit\n    if (reverse_data_flow) {\n      auto reorder_pd = dnnl::reorder::primitive_desc(eng_, desc, eng_, src_desc);\n      action->insert(action->begin(),\n                     {dnnl::reorder(reorder_pd), {{DNNL_ARG_FROM, dst_ar}, {DNNL_ARG_TO, src_ar}}});\n    } else {\n      auto reorder_pd = dnnl::reorder::primitive_desc(eng_, src_desc, eng_, desc);\n      action->push_back(\n          {dnnl::reorder(reorder_pd), {{DNNL_ARG_FROM, src_ar}, {DNNL_ARG_TO, dst_ar}}});\n    }\n    return dst_ar;\n  }\n  /*! \\brief Implementation of memory solver */\n  class MemSolverImpl {\n   public:\n    MemSolverImpl(const dnnl::engine& eng, const DLTensorProvider& ext_data_provider,\n                  const std::vector<dnnl::memory>& const_mems,\n                  const std::vector<std::pair<uint32_t, dnnl::memory::desc>>& ext_mems,\n                  const std::vector<dnnl::memory::desc>& tmp_mem_descs,\n                  const std::map<size_t, size_t>& tmp_mem_mapping)\n        : eng_(eng),\n          ext_data_provider_(ext_data_provider),\n          const_mems_(const_mems),\n          ext_mems_(ext_mems) {\n      // Construct temp memory objects on the fly. While we have no scratchpads\n      // support on VM/GraphExecutor level.\n      tmp_mems_.resize(tmp_mem_descs.size());\n      for (size_t i = 0; i < tmp_mem_descs.size(); i++) {\n        auto found = tmp_mem_mapping.find(i);\n\n        if (found != tmp_mem_mapping.end()) {\n          auto reuse_hdl = tmp_mems_[found->second].get_data_handle();\n          tmp_mems_[i] = dnnl::memory(tmp_mem_descs[i], eng_, reuse_hdl);\n        } else {\n          tmp_mems_[i] = dnnl::memory(tmp_mem_descs[i], eng_);\n        }\n      }\n    }\n\n    /*! \\brief Find memory object associated with provided ArgId */\n    dnnl::memory operator()(const ArgId& ar) const {\n      switch (ar.flag_) {\n        case CONST:\n          return const_mems_.at(ar.idx_);\n        case TMP_STORAGE:\n          return tmp_mems_.at(ar.idx_);\n        case EXT_EID: {\n          auto eid_and_desc = ext_mems_.at(ar.idx_);\n          auto eid = eid_and_desc.first;\n          auto desc = eid_and_desc.second;\n\n          auto ext_dl_tensor = ext_data_provider_(eid);\n          ICHECK(ext_dl_tensor->data);\n          return dnnl::memory{desc, eng_, ext_dl_tensor->data};\n        }\n      }\n      return {};\n    }\n\n   private:\n    const dnnl::engine& eng_;\n    const DLTensorProvider& ext_data_provider_;\n    const std::vector<dnnl::memory>& const_mems_;\n    const std::vector<std::pair<uint32_t, dnnl::memory::desc>>& ext_mems_;\n    std::vector<dnnl::memory> tmp_mems_;\n  };\n\n  ArgId MakeArgReq(ArgReqFlag flag, uint32_t idx) { return {flag, idx}; }\n\n  /* Collection of const memory objects. */\n  std::vector<dnnl::memory> const_mem_collection_;\n\n  /* Collection of intermediate memory descriptors. Zero position is reserved for scratchpads. */\n  std::vector<dnnl::memory::desc> tmp_mem_collection_;\n\n  /* Mapping of some temp buffer on previously registered. */\n  std::map<size_t, size_t> tmp_mem_mapping_;\n\n  /* Collection of external_intermediate memory objects.\n   *  first  - eid of external buffer to ask\n   *  second - t_desc describes how to treat external buffer */\n  std::vector<std::pair<uint32_t, dnnl::memory::desc>> ext_mem_collection_;\n\n  /* Map of eid to index of temp buffer in tmp_mem_collection_ */\n  std::unordered_map<uint32_t, size_t> eid2idx_tmp_;\n\n  /* List of external eid */\n  std::set<uint32_t> ext_io_eid_;\n\n  /* Engine of all tensors existing in this registry */\n  dnnl::engine eng_;\n\n  /* Execution stream use to reorder const data */\n  dnnl::stream stream_;\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_DNNL_DNNL_TENSOR_REQUISITE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/dnnl/dnnl_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/dnnl/dnnl_utils.cc\n * \\brief Some DNNL specific utility functions\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_DNNL_DNNL_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_DNNL_DNNL_UTILS_H_\n\n#include <cstdint>\n#include <ostream>\n#include <string>\n#include <vector>\n\n// TODO(@apeskov): Have to mute warning from dnnl headers.\n//  -Wzero-as-null-pointer-constant and -Wdocumentation-unknown-command\n#include <dnnl.hpp>\n\n#include \"tvm/runtime/data_type.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*!\n * \\brief Convert a DLPack data type to a DNNL data type.\n * \\param dltype The DLPack data type.\n * \\return The corresponding DNNL data type.\n */\ndnnl::memory::data_type dtype_dl2dnnl(DLDataType dltype);\n\n/*!\n * \\brief Converter TVM shape to DNNL dims\n * \\param shape tvm shape\n * \\return dims in terms of dnnl\n */\ndnnl::memory::dims shape_dl2dnnl(const std::vector<int64_t>& shape);\n\n/*!\n * \\brief Construct plain tensor descriptor\n * \\param shape provided shape\n * \\param dltype provided data type\n * \\return resulting plain tensor desc\n */\ndnnl::memory::desc MakePlainDesc(const std::vector<int64_t>& shape, DLDataType dltype);\n\nnamespace utils {\n\n/*! \\brief Pretty printer util for shape */\ninline std::ostream& operator<<(std::ostream& o, const dnnl::memory::dims& dims) {\n  o << \"[\";\n  auto d = dims.begin();\n  if (d != dims.end()) o << *d++;\n  while (d != dims.end()) o << \",\" << *d++;\n  o << \"]\";\n  return o;\n}\n\n/*! \\brief Pretty printer util for data type */\ninline std::ostream& operator<<(std::ostream& o, const dnnl::memory::data_type& type) {\n  std::string name = \"undef\";\n  switch (type) {\n    case dnnl::memory::data_type::undef:\n      name = \"undef\";\n      break;\n    case dnnl::memory::data_type::f32:\n      name = \"fp32\";\n      break;\n    case dnnl::memory::data_type::f16:\n      name = \"fp16\";\n      break;\n    case dnnl::memory::data_type::bf16:\n      name = \"bf16\";\n      break;\n    case dnnl::memory::data_type::s32:\n      name = \"i32\";\n      break;\n    case dnnl::memory::data_type::s8:\n      name = \"i8\";\n      break;\n    case dnnl::memory::data_type::u8:\n      name = \"u8\";\n      break;\n  }\n  o << name;\n  return o;\n}\n\n/*! \\brief Converter data type template arg to runtime object */\ntemplate <typename T>\ninline dnnl::memory::data_type DnnlDType();\n\ntemplate <>\ninline dnnl::memory::data_type DnnlDType<int>() {\n  return dnnl::memory::data_type::s32;\n}\n\ntemplate <>\ninline dnnl::memory::data_type DnnlDType<float>() {\n  return dnnl::memory::data_type::f32;\n}\n\ntemplate <>\ninline dnnl::memory::data_type DnnlDType<uint8_t>() {\n  return dnnl::memory::data_type::u8;\n}\n\ntemplate <>\ninline dnnl::memory::data_type DnnlDType<int8_t>() {\n  return dnnl::memory::data_type::s8;\n}\n\n}  // namespace utils\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_DNNL_DNNL_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/edgetpu/edgetpu_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief EdgeTPU runtime that can run tflite model compiled\n *        for EdgeTPU containing only tvm PackedFunc.\n * \\file edgetpu_runtime.h\n */\n#ifndef TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_\n\n#include <edgetpu.h>\n\n#include <memory>\n#include <string>\n\n#include \"../tflite/tflite_runtime.h\"\n#include \"edgetpu.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief EdgeTPU runtime.\n *\n *  This runtime can be accessed in various languages via\n *  the TVM runtime PackedFunc API.\n */\nclass EdgeTPURuntime : public TFLiteRuntime {\n public:\n  /*!\n   * \\brief Destructor of EdgeTPURuntime.\n   *\n   * NOTE: tflite::Interpreter member should be destruct before the EdgeTpuContext member\n   * destruction. If the order is reverse, occurs SEGV in the destructor of tflite::Interpreter.\n   */\n  ~EdgeTPURuntime() { interpreter_.reset(); }\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const final { return \"EdgeTPURuntime\"; }\n\n  /*!\n   * \\brief Initialize the edge TPU tflite runtime with tflite model and device.\n   * \\param tflite_model_bytes The tflite model.\n   * \\param dev The device where the tflite model will be executed on.\n   */\n  void Init(const std::string& tflite_model_bytes, Device dev);\n\n private:\n  std::shared_ptr<edgetpu::EdgeTpuContext> edgetpu_context_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/ethosn/ethosn_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ethosn_device.h\n * \\brief Arm(R) Ethos(TM)-N NPU device integration.\n */\n#ifndef TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_\n#define TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_\n\n#include <tvm/runtime/registry.h>\n\n#include <vector>\n\n#include \"ethosn_runtime.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace ethosn {\n\nnamespace dl = ::ethosn::driver_library;\n\nusing tvm::runtime::TVMArgs;\n\nbool Inference(tvm::runtime::TVMArgs args, dl::Network* npu,\n               const std::vector<uint32_t>& input_order, const std::vector<uint32_t>& output_order,\n               const std::vector<uint32_t>& input_sizes, const std::vector<uint32_t>& output_sizes);\n\n}  // namespace ethosn\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/ethosn/ethosn_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ethosn_runtime.h\n * \\brief Execution handling of Ethos-N command streams.\n */\n#ifndef TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_RUNTIME_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"ethosn_driver_library/Network.hpp\"\n#include \"ethosn_support_library/Support.hpp\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace ethosn {\n\nnamespace sl = ::ethosn::support_library;\nnamespace dl = ::ethosn::driver_library;\n\nstruct OrderedCompiledNetwork {\n  std::unique_ptr<sl::CompiledNetwork> compiled_cmm;\n  std::unique_ptr<dl::Network> runtime_cmm;\n  std::string name;\n  std::vector<uint32_t> inputs;\n  std::vector<uint32_t> outputs;\n  std::vector<uint32_t> input_sizes;\n  std::vector<uint32_t> output_sizes;\n};\n\nclass EthosnModule : public ModuleNode {\n public:\n  /*!\n   * \\brief The Ethos-N runtime module.\n   * \\param cmms A vector of compiled networks with input/output orders.\n   */\n  explicit EthosnModule(std::vector<OrderedCompiledNetwork>* cmms);\n\n  /*!\n   * \\brief Get a PackedFunc from the Ethos-N module.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The ObjectPtr that points to this module node.\n   * \\return The function pointer when it is found, otherwise, PackedFunc(nullptr).\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n  /*!\n   * \\brief Save a compiled network to a binary stream, which can then be\n   * serialized to disk.\n   * \\param stream The stream to save the binary.\n   * \\note See EthosnModule::LoadFromBinary for the serialization format.\n   */\n  void SaveToBinary(dmlc::Stream* stream) final;\n  /*!\n   * \\brief Load a compiled network from stream.\n   * \\param strm The binary stream to load.\n   * \\return The created Ethos-N module.\n   * \\note The serialization format is:\n   *\n   *       size_t : number of functions\n   *       [\n   *         std::string : name of function (symbol)\n   *         std::string : serialized command stream\n   *         size_t      : number of inputs\n   *         std::vector : order of inputs\n   *         std::vector : buffer sizes for inputs\n   *         size_t      : number of outputs\n   *         std::vector : order of outputs\n   *         std::vector : buffer sizes for outputs\n   *       ] * number of functions\n   */\n  static Module LoadFromBinary(void* strm);\n  /*!\n   * \\brief Save a module to a specified path.\n   * \\param path Where to save the serialized module.\n   */\n  void SaveToFile(const std::string& path, const std::string& format) override;\n\n  const char* type_key() const override { return \"ethos-n\"; }\n\n private:\n  /*! \\brief A map between ext_symbols (function names) and ordered compiled networks. */\n  std::map<std::string, OrderedCompiledNetwork> network_map_;\n};\n\n/*!\n * \\brief Error codes for evaluating the result of inference on the NPU.\n */\nenum class InferenceWaitErrorCode { kSuccess = 0, kTimeout = 1, kError = 2 };\n\n/*!\n * \\brief A helper class holding the status of inference on the NPU and\n * associated error message(s) if any occurred.\n *\n * Similar to the implementation of 'WaitStatus' in the driver stack:\n * https://github.com/ARM-software/ethos-n-driver-stack/blob/22.08/armnn-ethos-n-backend/workloads/EthosNPreCompiledWorkload.cpp#L48\n */\nclass InferenceWaitStatus {\n public:\n  InferenceWaitStatus() : error_code_(InferenceWaitErrorCode::kSuccess), error_description_(\"\") {}\n\n  explicit InferenceWaitStatus(InferenceWaitErrorCode errorCode, std::string errorDescription = \"\")\n      : error_code_(errorCode), error_description_(errorDescription) {}\n\n  InferenceWaitStatus(const InferenceWaitStatus&) = default;\n  InferenceWaitStatus(InferenceWaitStatus&&) = default;\n  InferenceWaitStatus& operator=(const InferenceWaitStatus&) = default;\n  InferenceWaitStatus& operator=(InferenceWaitStatus&&) = default;\n\n  explicit operator bool() const { return error_code_ == InferenceWaitErrorCode::kSuccess; }\n  InferenceWaitErrorCode GetErrorCode() const { return error_code_; }\n  std::string GetErrorDescription() const { return error_description_; }\n\n private:\n  InferenceWaitErrorCode error_code_;\n  std::string error_description_;\n};\n\n}  // namespace ethosn\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/ethosu/bare_metal/tvm_ethosu_runtime.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"tvm_ethosu_runtime.h\"\n\n#include <ethosu_driver.h>\n\nint32_t TVMEthosULaunch(tvm_device_ethos_u_t* context, void* cms_data, size_t cms_data_size,\n                        uint64_t* base_addrs, size_t* base_addrs_size, int num_tensors) {\n  struct ethosu_driver* driver = (struct ethosu_driver*)context;\n  int32_t result =\n      ethosu_invoke(driver, cms_data, cms_data_size, base_addrs, base_addrs_size, num_tensors);\n\n  // Map errors in invoke to TVM errors\n  if (result != 0) {\n    return -1;\n  }\n  return 0;\n}\n\nint32_t TVMDeviceEthosUActivate(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUOpen(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUClose(tvm_device_ethos_u_t* context) { return 0; }\nint32_t TVMDeviceEthosUDeactivate(tvm_device_ethos_u_t* context) { return 0; }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/ethosu/bare_metal/tvm_ethosu_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_ETHOSU_BARE_METAL_TVM_ETHOSU_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_ETHOSU_BARE_METAL_TVM_ETHOSU_RUNTIME_H_\n\n#include <ethosu_driver.h>\n#include <stddef.h>\n#include <stdint.h>\n\ntypedef void tvm_device_ethos_u_t;\n\nint32_t TVMEthosULaunch(tvm_device_ethos_u_t* resource_handle, void* cms_data, size_t cms_data_size,\n                        uint64_t* base_addrs, size_t* base_addrs_size, int num_tensors);\n\nint32_t TVMDeviceEthosUActivate(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUOpen(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUClose(tvm_device_ethos_u_t* context);\nint32_t TVMDeviceEthosUDeactivate(tvm_device_ethos_u_t* context);\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOSU_BARE_METAL_TVM_ETHOSU_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/json/json_node.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/json/json_node.h\n * \\brief The graph nodes used by JSON runtime.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_JSON_JSON_NODE_H_\n#define TVM_RUNTIME_CONTRIB_JSON_JSON_NODE_H_\n\n#include <dlpack/dlpack.h>\n#include <dmlc/json.h>\n#include <dmlc/memory_io.h>\n#include <tvm/runtime/data_type.h>\n\n#include <cstdint>\n#include <cstdio>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace json {\n\nusing namespace tvm::runtime;\nusing JSONGraphAttrs = std::unordered_map<std::string, dmlc::any>;\n\n/*!\n * \\brief The node entry in the serialized json graph.\n */\nclass JSONGraphNodeEntry {\n public:\n  // Constructors.\n  JSONGraphNodeEntry() = default;\n  JSONGraphNodeEntry(int id, int index, int version = 0)\n      : id_(id), index_(index), version_(version) {}\n\n  /*!\n   * \\brief Serialize a node entry.\n   * \\param writer The json writer.\n   */\n  void Save(dmlc::JSONWriter* writer) const {\n    writer->BeginArray();\n    writer->WriteArrayItem(id_);\n    writer->WriteArrayItem(index_);\n    writer->WriteArrayItem(version_);\n    writer->EndArray();\n  }\n\n  /*!\n   * \\brief Deserialize the json string into a node entry.\n   * \\param reader The json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    ICHECK(reader->NextArrayItem()) << \"invalid json format\";\n    reader->Read(&id_);\n    ICHECK(reader->NextArrayItem()) << \"invalid json format\";\n    reader->Read(&index_);\n    if (reader->NextArrayItem()) {\n      reader->Read(&version_);\n      ICHECK(!reader->NextArrayItem()) << \"invalid json format\";\n    } else {\n      version_ = 0;\n    }\n  }\n\n  /*! \\brief The json graph node ID. */\n  uint32_t id_;\n  /*! \\brief The entry index. */\n  uint32_t index_;\n  uint32_t version_;\n};\n\n/*!\n * \\brief The node of the serialized json graph. It includes an array of\n * entries.\n */\nclass JSONGraphNode {\n public:\n  // Constructors.\n  JSONGraphNode() = default;\n  JSONGraphNode(const std::string& name, const std::string& op_type,\n                const std::vector<JSONGraphNodeEntry>& inputs = {}, size_t num_outputs = 1) {\n    name_ = name;\n    op_type_ = op_type;\n    num_inputs_ = inputs.size();\n    inputs_ = inputs;\n    num_outputs_ = num_outputs;\n  }\n\n  /*!\n   * \\brief Serialize a node so that it can be saved to disk.\n   * \\param writer The json writer.\n   */\n  void Save(dmlc::JSONWriter* writer) {\n    writer->BeginObject();\n    writer->WriteObjectKeyValue(\"op\", op_type_);\n    writer->WriteObjectKeyValue(\"name\", name_);\n    if (!inputs_.empty()) {\n      SetAttr(\"num_inputs\", std::to_string(inputs_.size()));\n      SetAttr(\"num_outputs\", std::to_string(num_outputs_));\n      writer->WriteObjectKeyValue(\"inputs\", this->inputs_);\n    }\n    if (!attrs_.empty()) {\n      writer->WriteObjectKeyValue(\"attrs\", attrs_);\n    }\n    writer->EndObject();\n  }\n\n  /*!\n   * \\brief Load the attribute of a node in the json string.\n   * \\param reader The json reader.\n   */\n  void LoadAttrs(dmlc::JSONReader* reader) {\n    std::string key, value;\n    reader->BeginObject();\n    while (reader->NextObjectItem(&key)) {\n      if (key == \"num_inputs\") {\n        reader->Read(&value);\n        num_inputs_ = strtoul(value.c_str(), nullptr, 10);\n      } else if (key == \"num_outputs\") {\n        reader->Read(&value);\n        num_outputs_ = strtoul(value.c_str(), nullptr, 10);\n      } else if (key == \"dtype\") {\n        std::vector<std::string> tmp;\n        reader->BeginArray();\n        ICHECK(reader->NextArrayItem());\n        reader->Read(&tmp);\n        ICHECK(!reader->NextArrayItem());\n        for (const auto& it : tmp) {\n          dtype_.push_back(tvm::runtime::String2DLDataType(it));\n        }\n      } else if (key == \"shape\") {\n        reader->BeginArray();\n        ICHECK(reader->NextArrayItem());\n        reader->Read(&shape_);\n        ICHECK(!reader->NextArrayItem());\n      } else {\n        reader->BeginArray();\n        ICHECK(reader->NextArrayItem());\n        std::vector<std::string> tmp;\n        reader->Read(&tmp);\n        attrs_[key] = tmp;\n        ICHECK(!reader->NextArrayItem());\n      }\n    }\n    ICHECK_EQ(shape_.size(), dtype_.size());\n  }\n\n  /*!\n   * \\brief Load a node in the json string.\n   * \\param reader The json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginObject();\n    std::string key;\n    while (reader->NextObjectItem(&key)) {\n      if (key == \"op\") {\n        reader->Read(&op_type_);\n      } else if (key == \"name\") {\n        reader->Read(&name_);\n      } else if (key == \"inputs\") {\n        reader->Read(&inputs_);\n      } else if (key == \"attr\" || key == \"attrs\") {\n        this->LoadAttrs(reader);\n      } else {\n        LOG(FATAL) << \"Unknown key: \" << key;\n      }\n    }\n  }\n\n  /*!\n   * \\brief Check if a node is a leaf node, i.e. input to the graph.\n   *\n   * \\return True if the node has no input, otherwise, false.\n   */\n  bool IsLeaf() const { return inputs_.empty(); }\n\n  /*!\n   * \\brief Return the number of outputs of the node.\n   *\n   * \\return The number of the output.\n   */\n  uint32_t GetNumOutput() const { return num_outputs_; }\n\n  /*!\n   * \\brief Return the input entries.\n   *\n   * \\return The input entries.\n   */\n  std::vector<JSONGraphNodeEntry> GetInputs() const { return inputs_; }\n\n  /*!\n   * \\brief Return the op type.\n   *\n   * \\return The op type.\n   */\n  std::string GetOpType() const { return op_type_; }\n\n  /*!\n   * \\brief Return the op name.\n   *\n   * \\return The op name.\n   */\n  std::string GetOpName() const { return name_; }\n\n  /*!\n   * \\brief Return the op output shapes.\n   *\n   * \\return The shapes.\n   */\n  std::vector<std::vector<int64_t>> GetOpShape() const { return shape_; }\n\n  /*!\n   * \\brief Return the op types.\n   *\n   * \\return The types.\n   */\n  std::vector<DLDataType> GetOpDataType() const { return dtype_; }\n\n  /*!\n   * \\brief Set the number of outputs of the node.\n   *\n   * \\param num_outputs The number of output.\n   */\n  void SetNumOutput(uint32_t num_outputs) { num_outputs_ = num_outputs; }\n\n  /*!\n   * \\brief Get the value of an attribute in the node.\n   *\n   * \\tparam T The return type.\n   * \\param key The key for lookup.\n   *\n   * \\return The value.\n   */\n  template <typename T>\n  T GetAttr(const std::string& key) const {\n    ICHECK_GT(attrs_.count(key), 0U) << \"Key: \" << key << \"is not found\";\n    return dmlc::get<T>(attrs_.at(key));\n  }\n\n  /*!\n   * \\brief Set an attribute for the node.\n   *\n   * \\tparam ValueT The type of the value being stored.\n   * \\param key The key of the attribute.\n   * \\param value The value of the attribute.\n   */\n  template <typename ValueT>\n  void SetAttr(const std::string& key, const ValueT& value) {\n    attrs_[key] = value;\n  }\n\n  /*!\n   * \\brief Check if node has attribute.\n   *\n   * \\param key The key of the attribute.\n   *\n   * \\return True if attribute exists, false otherwise.\n   */\n  bool HasAttr(const std::string& key) const { return attrs_.find(key) != attrs_.end(); }\n\n  void CaptureAttrs(const JSONGraphNode& that) {\n    for (const auto& kv : that.attrs_) {\n      attrs_[kv.first] = kv.second;\n    }\n  }\n\n  virtual ~JSONGraphNode() {}\n\n private:\n  /*! \\brief The number of input. */\n  uint32_t num_inputs_{0};\n  /*! \\brief The number of output. */\n  uint32_t num_outputs_{1};\n  /*! \\brief The name of the op. It is the symbol that used for runtime lookup. */\n  std::string name_;\n  /*! \\brief The operator type, i.e. input is \"null\". */\n  std::string op_type_;\n  /*! \\brief The shape of the node. */\n  std::vector<std::vector<int64_t>> shape_;\n  /*! \\brief The type of the node. */\n  std::vector<DLDataType> dtype_;\n  /*! \\brief The inputs of the node. */\n  std::vector<JSONGraphNodeEntry> inputs_;\n  /*!\n   * \\brief Attribute of the node. For simplicity, we store all attribute as\n   * a list of std::string. It's the developer's resposibility to check the\n   * required attribute of a certain op and convert it into the needed type.\n   *\n   * For example, for conv2d, this map could contain:\n   *  attrs_[\"strides\"] = [\"1\", \"1\"]\n   *  attrs_[\"padding\"] = [\"0\", \"0\", \"0\", \"0\"]\n   *  attrs_[\"data_layout\"] = [\"NCHW\"]\n   *\n   * when creating an execution engine, developers may need to use these\n   * attributes and they can convert it into the needed type, i.e. padding to\n   * int\n   */\n  JSONGraphAttrs attrs_;\n\n  friend class JSONRuntimeBase;\n};\n\n}  // namespace json\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace dmlc {\nnamespace json {\ntemplate <typename T>\ninline bool SameType(const dmlc::any& data) {\n  return std::type_index(data.type()) == std::type_index(typeid(T));\n}\n\ntemplate <>\nstruct Handler<std::unordered_map<std::string, dmlc::any>> {\n  inline static void Write(dmlc::JSONWriter* writer,\n                           const std::unordered_map<std::string, dmlc::any>& data) {\n    for (const auto& kv : data) {\n      auto k = kv.first;\n      const dmlc::any& v = kv.second;\n      if (SameType<std::vector<dmlc::any>>(v)) {\n        writer->WriteObjectKeyValue(k, dmlc::get<std::vector<dmlc::any>>(v));\n      } else {\n        LOG(FATAL) << \"Not supported\";\n      }\n    }\n    writer->EndObject();\n  }\n  inline static void Read(dmlc::JSONReader* reader,\n                          std::unordered_map<std::string, dmlc::any>* data) {\n    LOG(FATAL) << \"Not implemented\";\n  }\n};\n\ntemplate <>\nstruct Handler<std::shared_ptr<tvm::runtime::json::JSONGraphNode>> {\n  inline static void Write(dmlc::JSONWriter* writer,\n                           const std::shared_ptr<tvm::runtime::json::JSONGraphNode>& data) {\n    data->Save(writer);\n  }\n\n  inline static void Read(dmlc::JSONReader* reader,\n                          std::shared_ptr<tvm::runtime::json::JSONGraphNode>* data) {\n    (*data)->Load(reader);\n  }\n};\n}  // namespace json\n}  // namespace dmlc\n\n#endif  // TVM_RUNTIME_CONTRIB_JSON_JSON_NODE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/json/json_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/json/json_runtime.h\n * \\brief Utilities for json runtime.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_JSON_JSON_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_JSON_JSON_RUNTIME_H_\n\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n\n#include <cstddef>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"json_node.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace json {\n\n/*!\n * \\brief A json runtime that executes the serialized JSON format. This runtime\n * can be extended by user defined runtime for execution.\n */\nclass JSONRuntimeBase : public ModuleNode {\n public:\n  JSONRuntimeBase(const std::string& symbol_name, const std::string& graph_json,\n                  const Array<String> const_names)\n      : symbol_name_(symbol_name), graph_json_(graph_json), const_names_(const_names) {\n    LoadGraph(graph_json_);\n  }\n\n  ~JSONRuntimeBase() override = default;\n\n  const char* type_key() const override { return \"json\"; }  // May be overridden\n\n  /*! \\brief Initialize a specific json runtime. */\n  virtual void Init(const Array<NDArray>& consts) = 0;\n\n  /*! \\brief Invoke the execution engine to inteprete a specific json runtime. */\n  virtual void Run() = 0;\n\n  /*!\n   * \\brief Get a packed function.\n   * \\param name The name/symbol of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The packed function.\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) override {\n    if (name == \"get_symbol\") {\n      return PackedFunc(\n          [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->symbol_name_; });\n    } else if (name == \"get_const_vars\") {\n      return PackedFunc(\n          [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->const_names_; });\n    } else if (this->symbol_name_ == name) {\n      return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {\n        ICHECK(this->initialized_) << \"The module has not been initialized\";\n\n        // Bind argument tensors to data entries.\n        this->SetInputOutputBuffers(args);\n        // Execute the subgraph.\n        this->Run();\n      });\n    } else if (\"__init_\" + this->symbol_name_ == name) {\n      // The function to initialize constant tensors.\n      return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {\n        ICHECK_EQ(args.size(), 1U);\n        std::lock_guard<std::mutex> guard(this->initialize_mutex_);\n        if (!this->initialized_) {\n          this->Init(args[0]);\n          this->initialized_ = true;\n        }\n        *rv = 0;\n      });\n    } else {\n      return PackedFunc(nullptr);\n    }\n  }\n\n  void SaveToBinary(dmlc::Stream* stream) override {\n    // Save the symbol\n    stream->Write(symbol_name_);\n    // Save the graph\n    stream->Write(graph_json_);\n    // Save the required const names\n    std::vector<std::string> consts;\n    for (const auto& it : const_names_) {\n      consts.push_back(it);\n    }\n    stream->Write(consts);\n  }\n\n  template <typename T,\n            typename = typename std::enable_if<std::is_base_of<JSONRuntimeBase, T>::value>::type>\n  static Module LoadFromBinary(void* strm) {\n    dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm);\n    std::string symbol;\n    std::string graph_json;\n    std::vector<std::string> consts;\n    // Load the symbol\n    ICHECK(stream->Read(&symbol)) << \"Loading symbol name failed\";\n    ICHECK(stream->Read(&graph_json)) << \"Loading graph json failed\";\n    ICHECK(stream->Read(&consts)) << \"Loading the const name list failed\";\n    Array<String> const_names;\n    for (const auto& it : consts) {\n      const_names.push_back(it);\n    }\n    auto n = make_object<T>(symbol, graph_json, const_names);\n    return Module(n);\n  }\n\n  /*!\n   * \\brief Get the JSON generated by codegen.\n   *\n   * \\param format the format to return.\n   * \\return A string of JSON.\n   */\n  std::string GetSource(const std::string& format = \"json\") override { return graph_json_; }\n\n protected:\n  /*!\n   * \\brief Set up the input and output buffers by binding their DLTensor pointers to the\n   * corresponding data entry.\n   *\n   * \\param args The packed args.\n   */\n  void SetInputOutputBuffers(const TVMArgs& args) {\n    ICHECK_EQ(args.size(), input_var_eid_.size() + outputs_.size())\n        << \"Found mismatch in the number of provided data entryies and required.\";\n\n    for (size_t i = 0; i < static_cast<size_t>(args.size()); i++) {\n      auto eid = i < input_var_eid_.size() ? input_var_eid_[i]\n                                           : EntryID(outputs_[i - input_var_eid_.size()]);\n      ICHECK(args[i].type_code() == kTVMNDArrayHandle || args[i].type_code() == kTVMDLTensorHandle)\n          << \"Expect NDArray or DLTensor as inputs\";\n\n      const DLTensor* arg;\n      if (args[i].IsObjectRef<NDArray>()) {\n        NDArray arr = args[i];\n        arg = arr.operator->();\n      } else {\n        arg = args[i].operator DLTensor*();\n      }\n\n      // Assign input/output the NDArray pointers to data entry so that we can directly\n      // read/write host buffers.\n      data_entry_[eid] = arg;\n    }\n  }\n\n  /*!\n   * \\brief Load the graph and record the entries for inputs and constants.\n   *\n   * \\param graph_json The graph in the json format.\n   */\n  void LoadGraph(const std::string& graph_json) {\n    std::istringstream is(graph_json);\n    dmlc::JSONReader reader(&is);\n    this->Load(&reader);\n    std::vector<std::string> consts;\n    for (size_t i = 0; i < input_nodes_.size(); i++) {\n      uint32_t nid = input_nodes_[i];\n      std::string name = nodes_[nid].name_;\n      if (nodes_[nid].op_type_ == \"input\") {\n        ICHECK_EQ(nodes_[nid].GetOpShape().size(), nodes_[nid].GetOpDataType().size());\n        for (size_t j = 0; j < nodes_[nid].GetOpShape().size(); ++j) {\n          input_var_eid_.push_back(EntryID(nid, j));\n        }\n        nodes_[nid].SetNumOutput(nodes_[nid].GetOpShape().size());\n      } else {\n        ICHECK_EQ(nodes_[nid].op_type_, \"const\");\n        auto pos = std::find(std::begin(const_names_), std::end(const_names_), name);\n        ICHECK(pos != std::end(const_names_)) << \"Found non-existent constant: \" << name;\n        const_idx_.push_back(nid);\n        consts.push_back(name);\n      }\n    }\n    ICHECK_EQ(consts.size(), const_names_.size())\n        << \"Found mismatch for the number of constants in the graph and required.\";\n\n    for (size_t i = 0; i < consts.size(); i++) {\n      ICHECK_EQ(consts[i], const_names_[i])\n          << \"The position of constant in the graph must be the same as the required.\";\n    }\n\n    // Reserve data entries.\n    data_entry_.resize(NumEntries());\n  }\n\n  /*!\n   * \\brief Set up the constants/weights for inference by binding their DLTensor pointer to\n   * the corresponding data entry.\n   *\n   * \\param consts A list of constant NDArray to be used.\n   */\n  void SetupConstants(const Array<NDArray>& consts) {\n    for (size_t i = 0; i < consts.size(); ++i) {\n      data_entry_[EntryID(const_idx_[i], 0)] = consts[i].operator->();\n    }\n  }\n\n  // Load the graph.\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginObject();\n    std::string key;\n    while (reader->NextObjectItem(&key)) {\n      if (key == \"nodes\") {\n        reader->Read(&nodes_);\n      } else if (key == \"arg_nodes\") {\n        reader->Read(&input_nodes_);\n      } else if (key == \"node_row_ptr\") {\n        reader->Read(&node_row_ptr_);\n      } else if (key == \"heads\") {\n        reader->Read(&outputs_);\n      } else {\n        LOG(FATAL) << \"Unknown key: \" << key;\n      }\n    }\n  }\n\n  // Get the node entry index.\n  uint32_t EntryID(uint32_t nid, uint32_t index) const { return node_row_ptr_[nid] + index; }\n\n  // Get the node entry index.\n  uint32_t EntryID(const JSONGraphNodeEntry& e) const { return EntryID(e.id_, e.index_); }\n\n  // Number of node entries.\n  uint32_t NumEntries() const { return node_row_ptr_.back(); }\n\n protected:\n  /*! \\brief The only subgraph name for this module. */\n  std::string symbol_name_;\n  /*! \\brief The graph. */\n  std::string graph_json_;\n  /*! \\brief The required constant names. */\n  Array<String> const_names_;\n  /*! \\brief The json graph nodes. */\n  std::vector<JSONGraphNode> nodes_;\n  /*! \\brief The input nodes, including variables and constants. */\n  std::vector<uint32_t> input_nodes_;\n  /*! \\brief Used for quick entry indexing. */\n  std::vector<uint32_t> node_row_ptr_;\n  /*! \\brief Output entries. */\n  std::vector<JSONGraphNodeEntry> outputs_;\n  /*! \\brief Data of that entry. */\n  std::vector<const DLTensor*> data_entry_;\n  /*! \\brief Map the input name to entry id. */\n  std::vector<uint32_t> input_var_eid_;\n  /*! \\brief input const node index. */\n  std::vector<uint32_t> const_idx_;\n  /*! \\brief Indicate if the engine has been initialized. */\n  bool initialized_{false};\n  /*! \\brief Initializer mutex*/\n  std::mutex initialize_mutex_;\n};\n\n}  // namespace json\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_JSON_JSON_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/miopen/miopen_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Use external miopen utils function\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_MIOPEN_MIOPEN_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_MIOPEN_MIOPEN_UTILS_H_\n\n#include <miopen/miopen.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n\n#include <string>\n\n#include \"../../rocm/rocm_common.h\"\n\nnamespace tvm {\nnamespace contrib {\nnamespace miopen {\n\nstd::string miopenGetErrorString(int error_code);\n\n#define MIOPEN_CALL(func)                                                             \\\n  {                                                                                   \\\n    miopenStatus_t e = (func);                                                        \\\n    ICHECK_EQ(e, miopenStatusSuccess) << \"miopen error: \" << miopenGetErrorString(e); \\\n  }\n\nstruct ConvEntry {\n  miopenConvolutionDescriptor_t conv_desc;\n  miopenConvolutionMode_t mode{miopenConvolution};\n  miopenTensorDescriptor_t filter_desc;\n  miopenDataType_t data_type{miopenFloat};\n  miopenTensorDescriptor_t input_desc;\n  miopenTensorDescriptor_t output_desc;\n  miopenConvFwdAlgorithm_t fwd_algo;\n  Device device;\n  runtime::DeviceAPI* rocm_api;\n  void* workspace{nullptr};\n  size_t workspace_size{0};\n  ConvEntry();\n  ~ConvEntry();\n  void UpdateWorkspace(const size_t wsize);\n  void CleanWorkspace();\n};  // ConvThreadEntry\n\nstruct SoftmaxEntry {\n  miopenTensorDescriptor_t shape_desc;\n  SoftmaxEntry();\n  ~SoftmaxEntry();\n};  // SoftmaxEntry\n\nstruct MIOpenThreadEntry {\n  MIOpenThreadEntry();\n  ~MIOpenThreadEntry();\n  miopenHandle_t handle{nullptr};\n  ConvEntry conv_entry;\n  SoftmaxEntry softmax_entry;\n  runtime::DeviceAPI* rocm_api{nullptr};\n  static MIOpenThreadEntry* ThreadLocal();\n};  // MIOpenThreadEntry\n\n}  // namespace miopen\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_MIOPEN_MIOPEN_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/mps/mps_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Use external mps utils function\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_MPS_MPS_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_MPS_MPS_UTILS_H_\n\n#import <MetalPerformanceShaders/MetalPerformanceShaders.h>\n#include <dmlc/thread_local.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/registry.h>\n\n#include <vector>\n\n#include \"../../metal/metal_common.h\"\n\nnamespace tvm {\nnamespace contrib {\n\n/*! breif Convert DLTensor type to MPS type */\nstruct MPSType {\n  static MPSDataType DLTypeToMPSType(const DLDataType& dtype);\n};  // struct MPSType\n\nstruct MetalThreadEntry {\n  MetalThreadEntry();\n  ~MetalThreadEntry();\n  MPSImage* AllocMPSImage(id<MTLDevice> dev, MPSImageDescriptor* desc);\n  MPSTemporaryImage* AllocTempImage(id<MTLCommandBuffer> cb, MPSImageDescriptor* desc);\n  runtime::metal::MetalWorkspace* metal_api{nullptr};\n  static MetalThreadEntry* ThreadLocal();\n  std::vector<MPSImage*> img_table;\n};  // MetalThreadEntry\n\n}  // namespace contrib\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_MPS_MPS_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/nnpack/nnpack_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file Use external nnpack library call.\n */\n#ifndef TVM_RUNTIME_CONTRIB_NNPACK_NNPACK_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_NNPACK_NNPACK_UTILS_H_\n#include <dmlc/thread_local.h>\n#include <nnpack.h>\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/registry.h>\n\nnamespace tvm {\nnamespace contrib {\nusing namespace runtime;\n\nstruct NNPackThreadLocalEntry {\n  pthreadpool_t threadpool{nullptr};\n  static NNPackThreadLocalEntry* ThreadLocal();\n};\n\nbool NNPackConfig(uint64_t nthreads);\n}  // namespace contrib\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_NNPACK_NNPACK_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tachikoma/tachikoma_kernel.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/tachikoma/tachikoma_kernel.h\n * \\brief Use external tachikoma library kernels.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_KERNEL_H_\n#define TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_KERNEL_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/registry.h>\n\n#include <vector>\n\n#include \"dnnl.hpp\"\n\nnamespace tachikoma = dnnl;\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing namespace tachikoma;\n\nextern \"C\" TVM_DLL void tachikoma_conv2d(float* data, float* weights, float* out, int p_N_, int p_C_,\n                                    int p_H_, int p_W_, int p_O_, int p_G_, int p_Ph0_, int p_Pw0_,\n                                    int p_Ph1_, int p_Pw1_, int p_Kh_, int p_Kw_, int p_Sh_,\n                                    int p_Sw_);\n\nextern \"C\" TVM_DLL void tachikoma_fused_conv2d_relu(float* data, float* weights, float* out, int p_N_,\n                                               int p_C_, int p_H_, int p_W_, int p_O_, int p_G_,\n                                               int p_Ph0_, int p_Pw0_, int p_Ph1_, int p_Pw1_,\n                                               int p_Kh_, int p_Kw_, int p_Sh_, int p_Sw_);\n\nextern \"C\" TVM_DLL void tachikoma_fused_conv2d_bias_relu(float* data, float* weights, float* bias,\n                                                    float* out, int p_N_, int p_C_, int p_H_,\n                                                    int p_W_, int p_O_, int p_G_, int p_Ph0_,\n                                                    int p_Pw0_, int p_Ph1_, int p_Pw1_, int p_Kh_,\n                                                    int p_Kw_, int p_Sh_, int p_Sw_);\n\nextern \"C\" TVM_DLL void tachikoma_dense(float* data, float* weight, float* out, int p_B_, int p_I_,\n                                   int p_O_);\n\nextern \"C\" TVM_DLL void tachikoma_relu(float* data, float* out, std::vector<int64_t> shape);\n\nextern \"C\" TVM_DLL void tachikoma_bn(float* data, float* gamma, float* beta, float* mean,\n                                float* variance, float* out, float* new_mean, float* new_variance,\n                                int p_n_, int p_c_, int p_h_, int p_w_, int p_e_);\n\nextern \"C\" TVM_DLL void tachikoma_binary_op(float* data, float* weight, float* out, int binary_algo,\n                                       std::vector<int64_t> shape);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_KERNEL_H_"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tachikoma/tachikoma_tensor_requisite.h",
        "content": "\n\n/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/tachikoma/tachikoma_tensor_requisite.cc\n * \\brief Helper TR wrapper to simplify tensors processing\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_TENSOR_REQUISITE_H_\n#define TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_TENSOR_REQUISITE_H_\n\n#include <dlpack/dlpack.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <limits>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n// TODO(@liaopeiyuan): Have to mute warning from tachikoma headers.\n//  -Wzero-as-null-pointer-constant and -Wdocumentation-unknown-command\n#include <dnnl.hpp>\n\nnamespace tachikoma = dnnl;\n\n#include \"tachikoma_utils.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing namespace utils;\n\n/*!\n * \\brief Helper object to simplify tensor transformation description.\n *\n * Allow to specify original source tensor and future actions which should be applied to it.\n * Can be treated as sequence of reordering or reinterpretation of original source tensor.\n * Finally TR can be solved as proper interpretation of source memory buffer, or sequence of\n * tachikoma::reorder operators which will provide desired data.\n *\n * \\note Empty TR object allow any manipulation. Empty TR will be returned.\n *\n * \\sa TensorRegistry\n *\n * Example:\n * \\code\n *   tachikoma::memory src_mem = ...;  // 5D tensor, shape {5, 2, 128, 128, 8}\n *\n *   // Construct TR\n *   auto tr = TensorRequisite.AsIs(src_mem, eid);  // 5D\n *\n *   // describe sequence of layout transformation\n *   tr = tr.TreatAs(\"ABCD8b\");  // 4D\n *   tr = tr.Permute({0, 2, 3, 1});  // Permute axes NCHW -> NHWC\n *   tr = tr.Crop({1, 128, 128, 16}, {0, 0, 0});  // extract first batch element\n *   tr = tr.Squeeze(); // 1D\n *\n *   // register TR\n *   TensorRegistry t_reg;\n *   auto t_id = t_reg.register(tr);\n *\n *   // Get final tachikoma::memory object\n *   auto solver = t_reg.MakeSolver(ext_tensor_provider);\n *   auto mem = solver(t_id);\n * \\endcode\n *\n */\nclass TensorRequisite {\n public:\n  using Tid = uint32_t;\n  static constexpr Tid kUndefinedTid = std::numeric_limits<uint32_t>::max() - 1;\n\n  /*! \\brief Empty constructor */\n  TensorRequisite() {}\n\n  /*! \\brief Construct TR on top of existing memory object */\n  static TensorRequisite AsIs(const tachikoma::memory& mem, Tid id = kUndefinedTid) {\n    auto res = AsIs(mem.get_desc(), id);\n    if (mem.get_data_handle() != nullptr) res.mem_ = mem;\n    return res;\n  }\n\n  /*! \\brief Construct TR on top of existing memory descriptor object */\n  static TensorRequisite AsIs(const tachikoma::memory::desc& desc, Tid id = kUndefinedTid) {\n    return {desc, {}, false, {}, id, false};\n  }\n\n  /*! \\brief return logical shape of tensor */\n  tachikoma::memory::dims dims() const { return t_desc_.dims(); }\n\n  /*! \\brief return data type of tensor */\n  tachikoma::memory::data_type data_type() const { return t_desc_.data_type(); }\n\n  /*! \\brief return tensor desc */\n  tachikoma::memory::desc desc() const { return t_desc_; }\n\n  /*! \\brief Make TR with backward dataflow */\n  TensorRequisite Backward() const {\n    if (!defined()) return *this;\n    ICHECK(orig_ == nullptr);\n    return {t_desc_, orig_, reinterpret_, mem_, eid_, true};\n  }\n\n  /*! \\brief Produce TR with permuted axes */\n  TensorRequisite Permute(const std::vector<int>& permutation) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.permute_axes(permutation);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with reinterpret data of original tr */\n  TensorRequisite Reshape(const tachikoma::memory::dims& shape) const {\n    if (!defined()) return *this;  // nothing for empty TR\n    if (t_desc_.dims() == shape) return *this;\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.reshape(shape);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with broadcasted values */\n  TensorRequisite Broadcast(const tachikoma::memory::dims& shape) const {\n    if (!defined()) return *this;  // nothing for empty TR\n    if (t_desc_.dims() == shape) return *this;\n    ICHECK(!reverse_data_flow_);\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n\n    // numpy like broadcast\n    auto extended_dims = t_desc_.dims();\n    auto one_filled = tachikoma::memory::dims(shape.size() - extended_dims.size(), 1);\n    extended_dims.insert(extended_dims.begin(), one_filled.begin(), one_filled.end());\n    auto desc = t_desc_.reshape(extended_dims);\n    for (size_t i = 0; i < extended_dims.size(); i++) {\n      if (extended_dims[i] == shape[i]) continue;\n      ICHECK(extended_dims[i] == 1);\n      ICHECK(desc.data.dims[i] == desc.data.padded_dims[i]);\n\n      desc.data.dims[i] = shape[i];\n      desc.data.padded_dims[i] = shape[i];\n      desc.data.format_desc.blocking.strides[i] = 0;\n    }\n\n    // reinterpret memory buffer with new strides\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with sub memory view (ROI) */\n  TensorRequisite Crop(const tachikoma::memory::dims& shape, const tachikoma::memory::dims& offset) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    ICHECK_EQ(shape.size(), t_desc_.dims().size());\n    ICHECK_EQ(offset.size(), t_desc_.dims().size());\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.submemory_desc(shape, offset, /*allow_empty=*/true);\n\n    // Originally Tachikoma implementation is very limited. Let's slightly enhance it.\n    if (!desc && t_desc_.data.format_kind == dnnl_blocked) {\n      bool offset_is_zero =\n          std::all_of(offset.begin(), offset.end(), [](auto el) { return el == 0; });\n\n      tachikoma::memory::dims block_sizes(t_desc_.dims().size(), 1);\n      for (int i = 0; i < t_desc_.data.format_desc.blocking.inner_nblks; i++)\n        block_sizes[t_desc_.data.format_desc.blocking.inner_idxs[i]] *=\n            t_desc_.data.format_desc.blocking.inner_blks[i];\n\n      bool shape_reduction_less_than_block = true;\n      for (int i = 0; i < t_desc_.data.ndims; i++) {\n        shape_reduction_less_than_block &= t_desc_.data.dims[i] - shape[i] < block_sizes[i];\n      }\n\n      // This is auto padded case. Just update dims value.\n      if (offset_is_zero && shape_reduction_less_than_block) {\n        desc = t_desc_;\n        std::copy(shape.begin(), shape.end(), desc.data.dims);\n      }\n    }\n\n    ICHECK(desc);\n\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with squeeze shape */\n  TensorRequisite Squeeze(const tachikoma::memory::dims& dims_to_squeeze = {}) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    tachikoma::memory::dims squeezed_dims;\n    if (dims_to_squeeze.empty()) {\n      for (auto d : t_desc_.dims())\n        if (d != 1) squeezed_dims.push_back(d);\n    } else {\n      for (size_t i = 0; i < t_desc_.dims().size(); i++)\n        if (std::find(dims_to_squeeze.begin(), dims_to_squeeze.end(), i) == dims_to_squeeze.end())\n          squeezed_dims.push_back(t_desc_.dims()[i]);\n    }\n\n    if (squeezed_dims.empty()) squeezed_dims = {1};\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // reinterpret memory buffer with new strides\n    auto desc = t_desc_.reshape(squeezed_dims);\n    return {desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Produce TR with specified layout descriptor */\n  TensorRequisite RequestLayout(tachikoma::memory::desc desc) const {\n    if (!defined()) return *this;  // nothing for empty TR\n\n    // If it's the same desc just return self\n    if (desc == t_desc_) return *this;\n\n    ICHECK(t_desc_.dims() == desc.dims()) << \"Requested layout is not compatible with \"\n                                             \"presented shape\";\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    return {desc, orig, false, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Define which logical dims ordering is default for particular layout string. */\n  static std::string DefaultLogicLayoutFor(const std::string& layout) {\n    // Rank is all non digit marked dims\n    auto it = layout.begin();\n    while (it != layout.end() && !std::isdigit(*it)) it++;\n    int rank = std::distance(layout.begin(), it);\n\n    static const std::vector<std::string> sparse_dims = {\"W\", \"HW\", \"DHW\"};\n    if (layout.find(\"N\") != std::string::npos) return \"NC\" + sparse_dims[rank - 3];\n    if (layout.find(\"G\") != std::string::npos) return \"GOI\" + sparse_dims[rank - 4];\n    if (layout.find(\"O\") != std::string::npos) return \"OI\" + sparse_dims[rank - 3];\n\n    LOG(FATAL) << \"Unknown layout \" << layout << \"There is no default scheme to handle it\";\n    return {};\n  }\n\n  /*!\n   * \\brief Treat TR shape as described in layout string.\n   *\n   * Blocked dimensions will be concatenated and put into proper shape position corresponding to  .\n   * resulting_layout_logic argument. If desired logic layout was not provided it will be deduced\n   * automatically based on some internal heuristics.\n   *\n   * Limitation 1. Blocking dims should be dense. Dims marked with digits use natural strides.\n   * Limitation 2. Blocking dims are innermost. Dims marked like 8c, 4o goes after regular\n   *               dimensions. NC8cHW4h4cD is not valid tensor in terms of Tachikoma. And cannot be\n   *               achieved with memory reinterpretation, so data copy is required. Proper layout\n   *               looks like NCHWD_8c4h4c, first part is outer dims, second digits marked part is\n   *               innermost.\n   */\n  TensorRequisite TreatAs(const std::string& layout, std::string desired_logic_layout = \"\") const {\n    if (!defined()) return *this;\n    if (desired_logic_layout.empty()) desired_logic_layout = DefaultLogicLayoutFor(layout);\n\n    const auto origin_dims = dims();\n\n    // split layout string to tokens {size, tag} like {16, 'C'}, {4, 'O'}\n    std::vector<std::pair<int, char>> layout_tokens;\n    for (auto it = layout.begin(); it != layout.end();) {\n      auto start = it;\n      while (std::isdigit(*it)) it++;\n      int blk_size = start == it ? -1 : std::stoi(std::string{start, it});\n      layout_tokens.push_back({blk_size, std::toupper(*it)});\n      it++;\n    }\n\n    // check applicability of layout\n    auto it = layout_tokens.begin();\n    while (it != layout_tokens.end() && it->first == -1) it++;\n    int rank = std::distance(layout_tokens.begin(), it);\n    while (it != layout_tokens.end()) {\n      ICHECK_NE(it->first, -1) << \"Tachikoma limitation. Blocking dims should be innermost. \"\n                               << \"But received layout is \" << layout;\n      it++;\n    }\n\n    ICHECK_EQ(layout_tokens.size(), origin_dims.size());\n    ICHECK_EQ(rank, desired_logic_layout.size()) << layout;\n\n    std::vector<std::pair<int, char>> outermost_tokens(layout_tokens.begin(),\n                                                       layout_tokens.begin() + rank);\n    std::vector<std::pair<int, char>> innermost_tokens(layout_tokens.begin() + rank,\n                                                       layout_tokens.end());\n    // define dim resulting dim positions\n    std::map<char, int> dim_position_by_tag;\n    for (size_t i = 0; i < desired_logic_layout.size(); i++)\n      dim_position_by_tag[std::toupper(desired_logic_layout[i])] = i;\n\n    // Construct resulting desc by modifying original one\n    tachikoma::memory::desc res_desc = t_desc_;\n\n    memset(&res_desc.data.format_desc.blocking, 0, sizeof(res_desc.data.format_desc.blocking));\n    std::fill(res_desc.data.dims, res_desc.data.dims + DNNL_MAX_NDIMS, 0);\n    std::fill(res_desc.data.padded_dims, res_desc.data.padded_dims + DNNL_MAX_NDIMS, 0);\n\n    res_desc.data.ndims = rank;\n    res_desc.data.format_desc.blocking.inner_nblks = innermost_tokens.size();\n\n    auto res_dims = res_desc.data.dims;\n    auto res_strides = res_desc.data.format_desc.blocking.strides;\n    auto res_inner_blks = res_desc.data.format_desc.blocking.inner_blks;\n    auto res_inner_idxs = res_desc.data.format_desc.blocking.inner_idxs;\n\n    std::fill(res_dims, res_dims + rank, 1);\n\n    int orig_dim_idx = 0;\n    for (const auto& p : outermost_tokens) {\n      auto tag = p.second;\n      auto dim_size = origin_dims[orig_dim_idx];\n\n      auto result_dim_position = dim_position_by_tag[tag];\n      res_dims[result_dim_position] *= dim_size;\n      res_strides[result_dim_position] = t_desc_.data.format_desc.blocking.strides[orig_dim_idx];\n      orig_dim_idx++;\n    }\n    for (const auto& p : innermost_tokens) {\n      auto tag = p.second;\n      auto dim_size = origin_dims[orig_dim_idx];\n      auto result_dim_position = dim_position_by_tag[tag];\n      ICHECK_EQ(p.first, dim_size)\n          << \"Blocking layout is not applicable to tensor with shape: \" << origin_dims\n          << \". Requested layout is \" << layout;\n\n      res_dims[result_dim_position] *= dim_size;\n      *res_inner_blks++ = dim_size;\n      *res_inner_idxs++ = result_dim_position;\n      orig_dim_idx++;\n    }\n\n    // Assume tensor is dense. There is no additional padding.\n    std::copy(res_desc.data.dims, res_desc.data.dims + rank, res_desc.data.padded_dims);\n\n    if (t_desc_ == res_desc) return *this;\n\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    return {res_desc, orig, true, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*!\n   * \\brief Produce TR with unspecified layout.\n   *\n   * Cannot be registered in TensorRegistry. Only for querying Tachikoma for preferred layouts.\n   */\n  TensorRequisite LayoutAny() const {\n    auto orig = std::make_shared<TensorRequisite>(*this);\n    // Recreate tensor desc with layout 'any'\n    tachikoma::memory::desc any_desc{t_desc_.dims(), t_desc_.data_type(), tachikoma::memory::format_tag::any};\n    return {any_desc, orig, false, {}, kUndefinedTid, reverse_data_flow_};\n  }\n\n  /*! \\brief Check is TR is constant. */\n  bool IsConstant() const {\n    if (orig_) return orig_->IsConstant();\n    return mem_.operator bool();\n  }\n\n  /*! \\brief Check is tensor is scalar. */\n  bool IsScalar() const { return t_desc_.dims().size() == 1 && t_desc_.dims()[0] == 1; }\n\n  /*! \\brief Return const data memory if available. */\n  tachikoma::memory GetConstData() const {\n    if (mem_) return mem_;\n    if (!orig_) return {};\n\n    if (auto orig_const_data = orig_->GetConstData()) {\n      if (reinterpret_) {\n        return {t_desc_, orig_const_data.get_engine(), orig_const_data.get_data_handle()};\n      } else {\n        auto eng = orig_const_data.get_engine();\n        auto res = tachikoma::memory{t_desc_, eng};\n        tachikoma::reorder(orig_const_data, res).execute(tachikoma::stream(eng), orig_const_data, res);\n        return res;\n      }\n    }\n    return {};\n  }\n\n  /*!\n   * \\brief Return const data memory in form of vector.\n   *\n   * Same as GetConstData but use std::vector instead of tachikoma::memory. Works only for 1D tensor\n   * and scalar TRs. Useful for specification of 1D Tachikoma attributes like zero_point or\n   * per_channel_scale\n   */\n  template <typename T>\n  std::vector<T> GetConstDataLikeVec() const {\n    auto const_data = GetConstData();\n    auto desc = const_data.get_desc();\n    ICHECK(desc.data_type() == utils::TachikomaDType<T>());\n    ICHECK(desc.dims().size() == 1 || desc.dims().size() == 3);\n\n    auto size = desc.get_size() / sizeof(T);\n    auto ptr = static_cast<T*>(const_data.get_data_handle());\n\n    return std::vector<T>(ptr, ptr + size);\n  }\n\n  /*! \\brief Get value of constant scalar tensor if possible. */\n  template <typename T>\n  T GetConstScalarData() const {\n    ICHECK(IsConstant());\n    ICHECK(IsScalar());\n    auto const_data = GetConstData();\n    auto desc = const_data.get_desc();\n    ICHECK(desc.data_type() == utils::TachikomaDType<T>());\n\n    auto ptr = static_cast<T*>(const_data.get_data_handle());\n    return *ptr;\n  }\n\n  /*! \\brief Check if tensor is not empty. */\n  bool defined() const { return !t_desc_.is_zero(); }\n\n  /*! \\brief Same as defined */\n  operator bool() const { return defined(); }\n\n  /*!\n   * \\brief Check if tensor represent a reversed data flow.\n   * Useful for describing output processing\n   */\n  bool IsReversed() const { return reverse_data_flow_; }\n\n private:\n  TensorRequisite(const tachikoma::memory::desc& t_desc, const std::shared_ptr<TensorRequisite>& orig,\n                  bool reinterpret, const tachikoma::memory& const_mem, uint32_t eid,\n                  bool reverse_data_flow)\n      : t_desc_(t_desc),\n        orig_(orig),\n        reinterpret_(reinterpret),\n        mem_(const_mem),\n        eid_(eid),\n        reverse_data_flow_(reverse_data_flow) {\n    if (mem_) ICHECK(!orig_ && !reverse_data_flow_ && eid_ == kUndefinedTid);\n    if (eid_ != kUndefinedTid) ICHECK(!orig_);\n  }\n\n  /* Descriptor of particular tensor  */\n  tachikoma::memory::desc t_desc_ = {};\n  /* Parent TR object which is referred from this TR */\n  std::shared_ptr<TensorRequisite> orig_ = {};\n  /* Flag to specify which action should be done with orig TR, reordering or reinterpretation */\n  bool reinterpret_ = false;\n  /* Const memory object if available */\n  tachikoma::memory mem_ = {};\n  /* Entry ID of tensor if available */\n  uint32_t eid_ = kUndefinedTid;\n\n  /*\n   * Flag to describe reverse data flow case\n   * All operation on queue will be executed in reverse order. Actual for dst tensor description\n   */\n  bool reverse_data_flow_ = false;\n\n  friend class TensorRegistry;\n};\n\n/*!\n * \\brief The registry of tensors. Implement matching of provided TRs and real memory buffers.\n *\n * Registration of TR performed by calling method Register(), which will return ArgId object.\n * ArgId can be mapped to real memory via memory solver created by method MakeSolver().\n */\nclass TensorRegistry {\n private:\n  enum ArgReqFlag {\n    CONST,        /// < Constant tensor. ExecutionCTX independent\n    TMP_STORAGE,  /// < Intermediate tensors. Stored inside TensorRegistry. Inaccessible outside\n    EXT_EID,      /// < External data. Input or Output.\n  };\n\n public:\n  struct ArgId {\n    TensorRegistry::ArgReqFlag flag_;\n    uint32_t idx_;\n  };\n\n  using Action = std::tuple<tachikoma::primitive, std::unordered_map<int, ArgId>>;\n  using ActionQue = std::vector<Action>;\n  using DLTensorProvider = std::function<const DLTensor*(uint32_t)>;\n  using MemSolver = std::function<const tachikoma::memory(ArgId)>;\n\n  TensorRegistry() = default;\n  TensorRegistry(const tachikoma::engine& eng, const std::set<uint32_t>& ext_io_eid)\n      : tmp_mem_collection_(1), ext_io_eid_(ext_io_eid), eng_(eng), stream_(eng) {}\n\n  /*!\n   * \\brief Register TR to registry\n   *\n   * Resolution of TR may lead to introduction of intermediate memory buffers and additional\n   * transformation actions which should be performed before or after usage of corresponding memory\n   * buffer. Additional actions will be append to provided actions queue. Corresponding to\n   * tr.IsReversed() value actions should be executed before or after usage of resulting ArgId.\n   *\n   * \\param tr tensor requisite sequence to register\n   * \\param action resulting action queue. If TR resolution is required execution of some\n   *               transformation actions they will be put here\n   * \\return associated ArgId. Should be used as argument for MemSolver.\n   */\n  ArgId Register(const TensorRequisite& tr, ActionQue* action) {\n    // 1) Constant tensor. Direct reference\n    if (auto const_data = tr.GetConstData()) {\n      auto idx = const_mem_collection_.size();\n      const_mem_collection_.push_back(const_data);\n      return MakeArgReq(ArgReqFlag::CONST, static_cast<uint32_t>(idx));\n    }\n\n    // 2) EID mapped tensor. Direct reference\n    if (tr.eid_ != TensorRequisite::kUndefinedTid) {\n      if (ext_io_eid_.count(tr.eid_) == 0) {  // Not IO tensor, means it's intermediate\n        if (eid2idx_tmp_.count(tr.eid_)) {\n          auto idx = eid2idx_tmp_.at(tr.eid_);\n          return MakeArgReq(ArgReqFlag::TMP_STORAGE, idx);\n        } else {\n          // register himself\n          auto idx = tmp_mem_collection_.size();\n          tmp_mem_collection_.push_back(tr.t_desc_);\n          eid2idx_tmp_[tr.eid_] = idx;\n          return MakeArgReq(ArgReqFlag::TMP_STORAGE, static_cast<uint32_t>(idx));\n        }\n      } else {\n        auto idx = ext_mem_collection_.size();\n        ext_mem_collection_.push_back({tr.eid_, tr.t_desc_});\n        return MakeArgReq(ArgReqFlag::EXT_EID, static_cast<uint32_t>(idx));\n      }\n    }\n\n    // 3) Tensors with transform actions\n    if (tr.orig_) {\n      // recursive register of orig TR\n      auto orig_arg_req = Register(*tr.orig_, action);\n      if (tr.reinterpret_) {\n        return RegisterReinterpret(orig_arg_req, tr.t_desc_);\n      } else {\n        return RegisterReorder(orig_arg_req, tr.t_desc_, tr.reverse_data_flow_, action);\n      }\n    }\n\n    // 4) Scratchpad\n    ICHECK(!tr.orig_ && !tr.mem_ && tr.eid_ == TensorRequisite::kUndefinedTid);\n    auto idx = tmp_mem_collection_.size();\n    tmp_mem_collection_.push_back(tr.t_desc_);\n    tmp_mem_mapping_[idx] = 0;  // zero position tmp mem object is reserved for scratchpads\n\n    auto scratchpad_size = tr.t_desc_.get_size();\n    auto glob_scratchpad_size = tmp_mem_collection_[0].get_size();\n    if (scratchpad_size > glob_scratchpad_size) {\n      tmp_mem_collection_[0] =\n          tachikoma::memory::desc({static_cast<tachikoma::memory::dim>(scratchpad_size)},\n                             tachikoma::memory::data_type::u8, tachikoma::memory::format_tag::a);\n    }\n    return MakeArgReq(TMP_STORAGE, static_cast<uint32_t>(idx));\n  }\n\n  /*!\n   * \\brief Construct memory solver for all registered TRs.\n   * \\param ext_provider callback to resolve external IO buffers\n   * \\return memory solver object to match ArgId to tachikoma::memory objects\n   */\n  MemSolver MakeSolver(const DLTensorProvider& ext_provider) const {\n    return MemSolverImpl(eng_, ext_provider, const_mem_collection_, ext_mem_collection_,\n                         tmp_mem_collection_, tmp_mem_mapping_);\n  }\n\n private:\n  ArgId RegisterReinterpret(ArgId src_ar, const tachikoma::memory::desc& desc) {\n    switch (src_ar.flag_) {\n      case TMP_STORAGE: {\n        auto idx = tmp_mem_collection_.size();\n        tmp_mem_collection_.push_back(desc);\n        tmp_mem_mapping_[idx] = src_ar.idx_;\n        return MakeArgReq(TMP_STORAGE, idx);\n      }\n      case EXT_EID: {\n        auto ext_req = ext_mem_collection_[src_ar.idx_];\n        auto idx = ext_mem_collection_.size();\n        ext_mem_collection_.push_back({ext_req.first, desc});\n        return MakeArgReq(EXT_EID, idx);\n      }\n      default:\n        LOG(FATAL) << \"Unknown case\";\n    }\n    return {};\n  }\n\n  ArgId RegisterReorder(ArgId src_ar, const tachikoma::memory::desc& desc, bool reverse_data_flow,\n                        ActionQue* action) {\n    ICHECK(src_ar.flag_ == TMP_STORAGE || src_ar.flag_ == EXT_EID);\n\n    auto src_desc = src_ar.flag_ == TMP_STORAGE ? tmp_mem_collection_[src_ar.idx_]\n                                                : ext_mem_collection_[src_ar.idx_].second;\n    auto idx = tmp_mem_collection_.size();\n    tmp_mem_collection_.push_back(desc);\n    auto dst_ar = MakeArgReq(TMP_STORAGE, idx);\n\n    // reorder action submit\n    if (reverse_data_flow) {\n      auto reorder_pd = tachikoma::reorder::primitive_desc(eng_, desc, eng_, src_desc);\n      action->insert(action->begin(),\n                     {tachikoma::reorder(reorder_pd), {{DNNL_ARG_FROM, dst_ar}, {DNNL_ARG_TO, src_ar}}});\n    } else {\n      auto reorder_pd = tachikoma::reorder::primitive_desc(eng_, src_desc, eng_, desc);\n      action->push_back(\n          {tachikoma::reorder(reorder_pd), {{DNNL_ARG_FROM, src_ar}, {DNNL_ARG_TO, dst_ar}}});\n    }\n    return dst_ar;\n  }\n  /*! \\brief Implementation of memory solver */\n  class MemSolverImpl {\n   public:\n    MemSolverImpl(const tachikoma::engine& eng, const DLTensorProvider& ext_data_provider,\n                  const std::vector<tachikoma::memory>& const_mems,\n                  const std::vector<std::pair<uint32_t, tachikoma::memory::desc>>& ext_mems,\n                  const std::vector<tachikoma::memory::desc>& tmp_mem_descs,\n                  const std::map<size_t, size_t>& tmp_mem_mapping)\n        : eng_(eng),\n          ext_data_provider_(ext_data_provider),\n          const_mems_(const_mems),\n          ext_mems_(ext_mems) {\n      // Construct temp memory objects on the fly. While we have no scratchpads\n      // support on VM/GraphExecutor level.\n      tmp_mems_.resize(tmp_mem_descs.size());\n      for (size_t i = 0; i < tmp_mem_descs.size(); i++) {\n        auto found = tmp_mem_mapping.find(i);\n\n        if (found != tmp_mem_mapping.end()) {\n          auto reuse_hdl = tmp_mems_[found->second].get_data_handle();\n          tmp_mems_[i] = tachikoma::memory(tmp_mem_descs[i], eng_, reuse_hdl);\n        } else {\n          tmp_mems_[i] = tachikoma::memory(tmp_mem_descs[i], eng_);\n        }\n      }\n    }\n\n    /*! \\brief Find memory object associated with provided ArgId */\n    tachikoma::memory operator()(const ArgId& ar) const {\n      switch (ar.flag_) {\n        case CONST:\n          return const_mems_.at(ar.idx_);\n        case TMP_STORAGE:\n          return tmp_mems_.at(ar.idx_);\n        case EXT_EID: {\n          auto eid_and_desc = ext_mems_.at(ar.idx_);\n          auto eid = eid_and_desc.first;\n          auto desc = eid_and_desc.second;\n\n          auto ext_dl_tensor = ext_data_provider_(eid);\n          ICHECK(ext_dl_tensor->data);\n          return tachikoma::memory{desc, eng_, ext_dl_tensor->data};\n        }\n      }\n      return {};\n    }\n\n   private:\n    const tachikoma::engine& eng_;\n    const DLTensorProvider& ext_data_provider_;\n    const std::vector<tachikoma::memory>& const_mems_;\n    const std::vector<std::pair<uint32_t, tachikoma::memory::desc>>& ext_mems_;\n    std::vector<tachikoma::memory> tmp_mems_;\n  };\n\n  ArgId MakeArgReq(ArgReqFlag flag, uint32_t idx) { return {flag, idx}; }\n\n  /* Collection of const memory objects. */\n  std::vector<tachikoma::memory> const_mem_collection_;\n\n  /* Collection of intermediate memory descriptors. Zero position is reserved for scratchpads. */\n  std::vector<tachikoma::memory::desc> tmp_mem_collection_;\n\n  /* Mapping of some temp buffer on previously registered. */\n  std::map<size_t, size_t> tmp_mem_mapping_;\n\n  /* Collection of external_intermediate memory objects.\n   *  first  - eid of external buffer to ask\n   *  second - t_desc describes how to treat external buffer */\n  std::vector<std::pair<uint32_t, tachikoma::memory::desc>> ext_mem_collection_;\n\n  /* Map of eid to index of temp buffer in tmp_mem_collection_ */\n  std::unordered_map<uint32_t, size_t> eid2idx_tmp_;\n\n  /* List of external eid */\n  std::set<uint32_t> ext_io_eid_;\n\n  /* Engine of all tensors existing in this registry */\n  tachikoma::engine eng_;\n\n  /* Execution stream use to reorder const data */\n  tachikoma::stream stream_;\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_TENSOR_REQUISITE_H_"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tachikoma/tachikoma_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/tachikoma/tachikoma_utils.cc\n * \\brief Some Tachikoma specific utility functions\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_UTILS_H_\n\n#include <cstdint>\n#include <ostream>\n#include <string>\n#include <vector>\n\n// TODO(@liaopeiyuan): Have to mute warning from tachikoma headers.\n//  -Wzero-as-null-pointer-constant and -Wdocumentation-unknown-command\n#include <dnnl.hpp>\n\nnamespace tachikoma = dnnl;\n\n#include \"tvm/runtime/data_type.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*!\n * \\brief Convert a DLPack data type to a Tachikoma data type.\n * \\param dltype The DLPack data type.\n * \\return The corresponding Tachikoma data type.\n */\ntachikoma::memory::data_type dtype_dl2tachikoma(DLDataType dltype);\n\n/*!\n * \\brief Converter TVM shape to Tachikoma dims\n * \\param shape tvm shape\n * \\return dims in terms of tachikoma\n */\ntachikoma::memory::dims shape_dl2tachikoma(const std::vector<int64_t>& shape);\n\n/*!\n * \\brief Construct plain tensor descriptor\n * \\param shape provided shape\n * \\param dltype provided data type\n * \\return resulting plain tensor desc\n */\ntachikoma::memory::desc MakePlainDesc(const std::vector<int64_t>& shape, DLDataType dltype);\n\nnamespace utils {\n\n/*! \\brief Pretty printer util for shape */\ninline std::ostream& operator<<(std::ostream& o, const tachikoma::memory::dims& dims) {\n  o << \"[\";\n  auto d = dims.begin();\n  if (d != dims.end()) o << *d++;\n  while (d != dims.end()) o << \",\" << *d++;\n  o << \"]\";\n  return o;\n}\n\n/*! \\brief Pretty printer util for data type */\ninline std::ostream& operator<<(std::ostream& o, const tachikoma::memory::data_type& type) {\n  std::string name = \"undef\";\n  switch (type) {\n    case tachikoma::memory::data_type::undef:\n      name = \"undef\";\n      break;\n    case tachikoma::memory::data_type::f32:\n      name = \"fp32\";\n      break;\n    case tachikoma::memory::data_type::f16:\n      name = \"fp16\";\n      break;\n    case tachikoma::memory::data_type::bf16:\n      name = \"bf16\";\n      break;\n    case tachikoma::memory::data_type::s32:\n      name = \"i32\";\n      break;\n    case tachikoma::memory::data_type::s8:\n      name = \"i8\";\n      break;\n    case tachikoma::memory::data_type::u8:\n      name = \"u8\";\n      break;\n  }\n  o << name;\n  return o;\n}\n\n/*! \\brief Converter data type template arg to runtime object */\ntemplate <typename T>\ninline tachikoma::memory::data_type TachikomaDType();\n\ntemplate <>\ninline tachikoma::memory::data_type TachikomaDType<int>() {\n  return tachikoma::memory::data_type::s32;\n}\n\ntemplate <>\ninline tachikoma::memory::data_type TachikomaDType<float>() {\n  return tachikoma::memory::data_type::f32;\n}\n\ntemplate <>\ninline tachikoma::memory::data_type TachikomaDType<uint8_t>() {\n  return tachikoma::memory::data_type::u8;\n}\n\ntemplate <>\ninline tachikoma::memory::data_type TachikomaDType<int8_t>() {\n  return tachikoma::memory::data_type::s8;\n}\n\n}  // namespace utils\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TACHIKOMA_TACHIKOMA_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tensorrt/tensorrt_builder.h",
        "content": "/* * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/contrib/tensorrt/tensorrt_builder.h\n * \\brief The TensorRTBuilder class can be used to convert a JSONRuntime graph into a TRT engine\n * which can be used for inference.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_BUILDER_H_\n#define TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_BUILDER_H_\n\n#include <tvm/runtime/ndarray.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../json/json_node.h\"\n#include \"NvInfer.h\"\n#include \"tensorrt_logger.h\"\n#include \"tensorrt_ops.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing JSONGraphNode = tvm::runtime::json::JSONGraphNode;\nusing JSONGraphNodeEntry = tvm::runtime::json::JSONGraphNodeEntry;\n\n/*!\n * \\brief The product of TensorRTBuilder which provides everything needed to\n * perform inference.\n */\nstruct TensorRTEngineAndContext {\n  nvinfer1::ICudaEngine* engine = nullptr;\n  nvinfer1::IExecutionContext* context = nullptr;\n  std::vector<std::string> inputs;\n  std::vector<std::string> outputs;\n};\n\n/*!\n * \\brief Converts a JSONRuntime graph into a TensorRT engine and execution context. Inputs,\n * constants, layers, and outputs can be added to construct the TensorRT network definition.\n * BuildEngine() will then use the network definition to build the TensorRT engine and context which\n * can be used to run inference - this phase can take a long time because TensorRT will query the\n * performance of all available kernels and fusions to optimize the engine.\n */\nclass TensorRTBuilder {\n public:\n  /*!\n   * \\brief Create TensorRT builder.\n   * \\param logger TensorRT logger to use for errors and warnings.\n   * \\param max_workspace_size Workspace size parameter for TensorRT engine build phase.\n   * \\param use_implicit_batch Whether to use implicit batch mode (default)\n   * \\param use_fp16 Whether to automatically convert a model to fp16\n   * \\param batch_size If use_implicit_batch,\n   */\n  TensorRTBuilder(TensorRTLogger* logger, const std::vector<const DLTensor*>& data_entry,\n                  size_t max_workspace_size, bool use_implicit_batch, bool use_fp16, int batch_size,\n                  nvinfer1::IInt8Calibrator* calibrator = nullptr);\n\n  /*!\n   * \\brief Add TensorRT input(s) for input node in network definition.\n   * \\param nid The input node id.\n   * \\param entry_id The index into data_entry_ for first entry in node.\n   * \\param node The input node.\n   */\n  void AddInput(int nid, uint32_t entry_id, const JSONGraphNode& node);\n\n  /*!\n   * \\brief Add TensorRT weight for input constant in network definition.\n   * \\param nid The input node id.\n   * \\param node The data tensor on CPU.\n   */\n  void AddConstant(int nid, const DLTensor* data);\n\n  /*!\n   * \\brief Add TensorRT layer for op node in network definition.\n   * \\param nid The input node id.\n   * \\param node The op node.\n   */\n  void AddLayer(int nid, const JSONGraphNode& node);\n\n  /*!\n   * \\brief Mark TensorRT output in network definition.\n   * \\param entry The output node entry.\n   * \\param entry_id The output node entry id.\n   */\n  void AddOutput(const JSONGraphNodeEntry& entry, uint32_t entry_id);\n\n  /*!\n   * \\brief Takes network definition and \"compiles\" a TensorRT engine which can be used for\n   * inference. This step is time confusing.\n   * \\return TRT engine, context, and input/output information.\n   */\n  TensorRTEngineAndContext BuildEngine();\n\n private:\n  /*! \\brief Convert a DLTensor to a TensorRT weight. */\n  nvinfer1::Weights GetDLTensorAsWeights(const DLTensor* dptr, DLDeviceType src_device);\n\n  /*! \\brief Convert an input to a Tensor if it is a Weight */\n  nvinfer1::ITensor* GetInputAsTensor(const TensorRTOpInput& input);\n\n  /*! \\brief Clean up resources used to create engine. */\n  void CleanUp();\n\n  /*! \\brief Maps a node to its outputs. */\n  std::unordered_map<int, std::vector<TensorRTOpInput>> node_output_map_;\n\n  /*! \\brief TensorRT builder. */\n  nvinfer1::IBuilder* builder_ = nullptr;\n\n#if TRT_VERSION_GE(6, 0, 1)\n  /*! \\brief TensorRT builder config. */\n  nvinfer1::IBuilderConfig* config_ = nullptr;\n#endif\n\n  /*! \\brief TensorRT network definition. */\n  nvinfer1::INetworkDefinition* network_ = nullptr;\n\n  /*! \\brief List of all weights held in memory. */\n  std::vector<nvinfer1::Weights> trt_weights_;\n\n  /*! \\brief Input and output tensors from TVM. */\n  const std::vector<const DLTensor*>& data_entry_;\n\n  /*! \\brief Map TensorRT binding name to index in data_entry_. */\n  std::unordered_map<std::string, uint32_t> entry_id_map_;\n\n  /*! \\brief Max workspace size in bytes for TRT. */\n  size_t max_workspace_size_;\n\n  /*! \\brief Whether to use implicit batch mode. */\n  bool use_implicit_batch_;\n\n  /*! \\brief Whether to automatically convert model to 16-bit floating point precision. */\n  bool use_fp16_;\n\n  /*! \\brief whether to automatically convert model to int8 precision */\n  bool use_int8_;\n\n  /*! \\brief Batch size to optimize for. */\n  int batch_size_;\n\n  /*! \\brief Input names. */\n  std::vector<std::string> network_input_names_;\n\n  /*! \\brief Output names. */\n  std::vector<std::string> network_output_names_;\n\n  /*! \\brief calibrator pointer to add batch data when using int8 mode */\n  /*! \\brief pointer will be nullptr when it is fp16 or fp32 precision */\n  nvinfer1::IInt8Calibrator* calibrator_;\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_BUILDER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tensorrt/tensorrt_calibrator.h",
        "content": "/* * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n\n * file runtime/contrib/tensorrt/tensorrt_builder.h\n * brief Contains TensorRTBuilder class which can be used to convert a relay\n * program into a TRT engine which can be used for inference.\n*/\n\n#ifndef TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_CALIBRATOR_H_\n#define TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_CALIBRATOR_H_\n\n#include <string>\n#include <vector>\n\n#include \"../../cuda/cuda_common.h\"\n#include \"NvInfer.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass TensorRTCalibrator : public nvinfer1::IInt8EntropyCalibrator2 {\n public:\n  TensorRTCalibrator(int batch_size, const std::vector<std::string>& input_names)\n      : batch_size_(batch_size), num_batches_calibrated_(0), input_names_(input_names) {}\n\n  ~TensorRTCalibrator() {\n    // Free calibration data\n    for (auto& inputs : data_) {\n      for (size_t i = 0; i < inputs.size(); ++i) {\n        delete[] inputs[i];\n      }\n    }\n    // Free buffers\n    for (size_t i = 0; i < buffers_.size(); ++i) {\n      CUDA_CALL(cudaFree(buffers_[i]));\n    }\n  }\n\n  void AddBatchData(const std::vector<void*>& bindings, const std::vector<size_t>& binding_sizes) {\n    // Copy data from GPU\n    std::vector<float*> data_host(bindings.size(), nullptr);\n    for (size_t i = 0; i < bindings.size(); ++i) {\n      data_host[i] = new float[batch_size_ * binding_sizes[i]];\n      CUDA_CALL(cudaMemcpy(static_cast<void*>(data_host[i]), bindings[i],\n                           batch_size_ * binding_sizes[i] * sizeof(float), cudaMemcpyDeviceToHost));\n    }\n    data_.push_back(data_host);\n    data_sizes_.push_back(binding_sizes);\n  }\n\n  int getBatchSize() const noexcept override { return batch_size_; }\n\n  /*!\n   * \\brief TensorRT will call this method to get next batch of data to\n   * calibrate with.\n   */\n  bool getBatch(void* bindings[], const char* names[], int nbBindings) noexcept override {\n    AllocateBuffersIfNotAllocated();\n    CHECK_EQ(input_names_.size(), nbBindings);\n    for (size_t i = 0; i < input_names_.size(); ++i) {\n      CHECK_EQ(input_names_[i], names[i]);\n      CUDA_CALL(cudaMemcpy(buffers_[i], data_[num_batches_calibrated_][i],\n                           batch_size_ * data_sizes_[num_batches_calibrated_][i] * sizeof(float),\n                           cudaMemcpyHostToDevice));\n      bindings[i] = buffers_[i];\n    }\n    num_batches_calibrated_++;\n    // TODO(trevmorr): Free data from previous batch?\n    return (num_batches_calibrated_ < static_cast<int>(data_.size()));\n  }\n\n  const void* readCalibrationCache(size_t& length) noexcept override {\n    if (calibration_cache_.empty()) return nullptr;\n    length = calibration_cache_.size();\n    return calibration_cache_.data();\n  }\n\n  void writeCalibrationCache(const void* cache, size_t length) noexcept override {\n    calibration_cache_.assign(static_cast<const char*>(cache), length);\n  }\n\n private:\n  /*! \\brief Batch size. */\n  int batch_size_;\n  /*! \\brief Number of batches already fed to calibrator. */\n  int num_batches_calibrated_;\n  /*! \\brief Storage for calibration cache. */\n  std::string calibration_cache_;\n\n  /*! \\brief Data to be used for calibration. */\n  std::vector<std::vector<float*>> data_;\n  /*! \\brief Number of elements for data to be used for calibration. */\n  std::vector<std::vector<size_t>> data_sizes_;\n\n  /*! \\brief Device buffers to be used for calibration. */\n  std::vector<void*> buffers_;\n\n  /*! \\brief Names of inputs */\n  const std::vector<std::string> input_names_;\n\n  /*! \\brief Allocate device memory buffers. data_sizes_ must already have one\n   * entry. */\n  void AllocateBuffersIfNotAllocated() {\n    if (!buffers_.empty()) return;\n    CHECK_GE(data_sizes_.size(), 1);\n    const int num_inputs = data_sizes_[0].size();\n    buffers_.assign(num_inputs, nullptr);\n    for (int i = 0; i < num_inputs; ++i) {\n      CUDA_CALL(cudaMalloc(&buffers_[i], data_sizes_[0][i] * sizeof(float)));\n    }\n  }\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_CALIBRATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tensorrt/tensorrt_logger.h",
        "content": "/* * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/contrib/tensorrt/tensorrt_logger.h\n * \\brief Contains TensorRTLogger class which is required by TRT and used to\n * print info, warnings, and errors.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_LOGGER_H_\n#define TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_LOGGER_H_\n\n#include <tvm/runtime/logging.h>\n\n#include \"NvInfer.h\"\n#include \"tensorrt_utils.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*! \\brief Logger for TensorRT info/warning/errors. */\nclass TensorRTLogger : public nvinfer1::ILogger {\n public:\n  TensorRTLogger() : TensorRTLogger(Severity::kWARNING) {}\n  explicit TensorRTLogger(Severity severity) : reportable_severity(severity) {}\n  void log(Severity severity, const char* msg) noexcept override {\n    // suppress messages with severity enum value greater than the reportable\n    if (severity > reportable_severity) return;\n\n    switch (severity) {\n      case Severity::kINTERNAL_ERROR:\n        LOG(ERROR) << \"INTERNAL_ERROR: \" << msg;\n        break;\n      case Severity::kERROR:\n        LOG(ERROR) << \"ERROR: \" << msg;\n        break;\n      case Severity::kWARNING:\n        LOG(WARNING) << \"WARNING: \" << msg;\n        break;\n      case Severity::kINFO:\n        LOG(INFO) << \"INFO: \" << msg;\n        break;\n#if TRT_VERSION_GE(5, 1, 5)\n      case Severity::kVERBOSE:\n        DLOG(INFO) << \"VERBOSE: \" << msg;\n        break;\n#endif\n      default:\n        LOG(INFO) << \"UNKNOWN: \" << msg;\n        break;\n    }\n  }\n\n private:\n  Severity reportable_severity{Severity::kWARNING};\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_LOGGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tensorrt/tensorrt_ops.h",
        "content": "/* * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/contrib/tensorrt/tensorrt_ops.h\n * \\brief Converters from Relay ops into TensorRT layers. Converters should\n * inherit from TensorRTOpConverter and implement the Convert() method.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_OPS_H_\n#define TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_OPS_H_\n\n#include <algorithm>\n#include <cmath>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../json/json_node.h\"\n#include \"NvInfer.h\"\n#include \"tensorrt_utils.h\"\n\n#if TRT_VERSION_GE(6, 0, 1)\n#define TRT_HAS_IMPLICIT_BATCH(params) (params->network->hasImplicitBatchDimension())\n#else\n#define TRT_HAS_IMPLICIT_BATCH(params) (true)\n#endif\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing JSONGraphNode = tvm::runtime::json::JSONGraphNode;\n\n/*!\n * \\brief An input to a op may be either kTensor in the case of nvinfer::ITensor*,\n * a kWeight for nvinfer1::Weights, or ignored (eg for the nn.pad value).\n */\nenum TensorRTInputType { kTensor, kWeight, kIgnored };\n\n/*!\n * \\brief An input to a TensorRTOpConverter. The type of the input is either kTensor\n * or kWeight. For kTensor, \"tensor\" contains the input tensor. For kWeight,\n * \"weight\" contains the input weight and \"weight_shape\" contains the shape.\n */\nstruct TensorRTOpInput {\n  /*! \\brief If type is kTensor, will store input tensor. */\n  nvinfer1::ITensor* tensor;\n\n  /*! \\brief If type is kWeight, will store input weight. */\n  nvinfer1::Weights weight;\n\n  /*! \\brief Whether the input is in tensor or weight. */\n  TensorRTInputType type;\n\n  /*! \\brief If type is kWeight, will store weight shape. */\n  std::vector<int> weight_shape;\n\n  explicit TensorRTOpInput(nvinfer1::ITensor* tensor)\n      : tensor(tensor), weight({tensor->getType(), nullptr, 0}), type(kTensor) {}\n  TensorRTOpInput(nvinfer1::Weights weight, const std::vector<int>& shape)\n      : tensor(nullptr), weight(weight), type(kWeight), weight_shape(shape) {}\n};\n\n/*! \\brief Parameters to convert an Op from Relay to TensorRT. */\nstruct TensorRTOpConverterParams {\n  /*! \\brief The TRT network that the new layer should be added to. */\n  nvinfer1::INetworkDefinition* network;\n  /*! \\brief Index of JSON node. */\n  int nid;\n  /*! \\brief The corresponding JSON node. */\n  const JSONGraphNode& node;\n  /*! \\brief The type of op. */\n  std::string op_name;\n  /*! \\brief Inputs to the op. */\n  std::vector<TensorRTOpInput> inputs;\n  /*! \\brief Outputs of the op should be populated here during Convert(). */\n  std::vector<nvinfer1::ITensor*> outputs;\n  /*! \\brief Any newly allocated weights should be stored here also. */\n  std::vector<nvinfer1::Weights>* trt_weights;\n\n  TensorRTOpConverterParams(nvinfer1::INetworkDefinition* network, int nid,\n                            const JSONGraphNode& node, std::vector<nvinfer1::Weights>* trt_weights)\n      : network(network), nid(nid), node(node), trt_weights(trt_weights) {\n    op_name = node.GetOpName();\n  }\n\n  std::string LayerName() const { return op_name + \"(\" + std::to_string(nid) + \")\"; }\n};\n\n/*! \\brief Base class for an op converter from Relay to TRT. */\nclass TensorRTOpConverter {\n public:\n  virtual ~TensorRTOpConverter() = default;\n\n  /*! \\brief Operator name. */\n  std::string op_name;\n  /*! \\brief Used to specify whether each input is tensor or weight. */\n  const std::vector<TensorRTInputType> input_types;\n  /*! \\brief If set to true, any number of tensor inputs can be used for the op. */\n  const bool variable_input_count;\n\n  /*!\n   * \\brief Converter subclasses should call this constructor to set\n   * input_types or variable_input_count.\n   * \\param input_types For each input to the op, there should be a\n   * corresponding entry in input_types to determine whether that input should\n   * be a tensor or a weight. TensorRTBuilder will prepare inputs in\n   * TensorRTOpConverter according to this.\n   * \\param variable_input_count If the op can have multiple inputs, set this to\n   * true. input_types vector will be ignored and any number of input tensors\n   * can be used for this op. All inputs will be tensors and not weights.\n   */\n  TensorRTOpConverter(std::string op_name, const std::vector<TensorRTInputType>& input_types,\n                      bool variable_input_count = false);\n\n  /*!\n   * \\brief Convert to TRT. Implementation should use inputs and attributes\n   * from the CallNode to add the corresponding TRT layers to network. Outputs\n   * should be pushed to outputs vector.\n   * \\param params Parameters for this op.\n   */\n  virtual void Convert(TensorRTOpConverterParams* params) const = 0;\n\n  /*!\n   * \\brief Helper function to reshape a tensor.\n   * \\param params Parameters for this op.\n   * \\param input Tensor to reshape.\n   * \\param new_shape New shape, does not include batch dim.\n   * \\return Reshaped tensor\n   */\n  nvinfer1::ITensor* Reshape(TensorRTOpConverterParams* params, nvinfer1::ITensor* input,\n                             const std::vector<int>& new_shape) const;\n\n  /*!\n   * \\brief Helper function to transpose a tensor.\n   * \\param params Parameters for this op.\n   * \\param input Tensor to transpose.\n   * \\param order New order of axes, does include batch dim.\n   * \\return Transposed tensor\n   */\n  nvinfer1::ITensor* Transpose(TensorRTOpConverterParams* params, nvinfer1::ITensor* input,\n                               const std::vector<int>& order) const;\n\n  /*!\n   * \\brief Helper function to convert an axis to TRT format.\n   * \\param axis Axis from TVM.\n   * \\param input_rank Rank of input, does not include batch dim.\n   * \\return Axis in TRT format.\n   */\n  int ConvertAxis(TensorRTOpConverterParams* params, int axis, int input_rank) const;\n\n  /*!\n   * \\brief Create constant that is broadcastable.\n   * \\param params Parameters for this op.\n   * \\param value Value of scalar.\n   * \\param broadcast_to_dims Dims that scalar should be broadcastable against.\n   * \\return Constant tensor.\n   */\n  nvinfer1::ITensor* CreateScalar(TensorRTOpConverterParams* params, float value,\n                                  const nvinfer1::Dims& broadcast_to_dims) const;\n\n  /*!\n   * \\brief Get pre/post padding values from padding attributes array.\n   * \\param padding Serialized padding from op attributes.\n   * \\param padding_is_asymmetric True if both pre and post are needed for asymmetric padding.\n   * \\param prepadding Prepadding value or symmetric padding values if !padding_is_asymmetric.\n   * \\param postpadding Postpadding value if padding_is_asymmetric.\n   */\n  void GetPadding(const std::vector<std::string>& padding, bool* use_asymmetric_padding,\n                  nvinfer1::DimsHW* prepadding, nvinfer1::DimsHW* postpadding) const;\n\n  /*!\n   * \\brief Get pre/post padding values from padding attributes array for volumetric ops.\n   * \\param padding Serialized padding from op attributes.\n   * \\param padding_is_asymmetric True if both pre and post are needed for asymmetric padding.\n   * \\param prepadding Prepadding value or symmetric padding values if !padding_is_asymmetric.\n   * \\param postpadding Postpadding value if padding_is_asymmetric.\n   */\n  void GetPadding3D(const std::vector<std::string>& padding, bool* use_asymmetric_padding,\n                    nvinfer1::Dims* prepadding, nvinfer1::Dims* postpadding) const;\n};\n\n/*!\n * \\brief Get the map of available TensorRTOpConverters, where the key is the name of the relay op.\n * \\return Map of TensorRTOpConverters.\n */\nconst std::unordered_map<std::string, std::unique_ptr<TensorRTOpConverter>>& GetOpConverters();\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_OPS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tensorrt/tensorrt_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/contrib/tensorrt/utils.h\n * \\brief Helper functions used by TensorRTBuilder or TensorRTOpConverters.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_UTILS_H_\n#define TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_UTILS_H_\n\n#include <string>\n#include <vector>\n\n#include \"NvInfer.h\"\n\n// There is a conflict between cpplint and clang-format-10.\n// clang-format off\n#define TRT_VERSION_GE(major, minor, patch)                                                    \\\n  ((NV_TENSORRT_MAJOR > major) || (NV_TENSORRT_MAJOR == major && NV_TENSORRT_MINOR > minor) || \\\n  (NV_TENSORRT_MAJOR == major && NV_TENSORRT_MINOR == minor && NV_TENSORRT_PATCH >= patch))\n// clang-format on\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*!\n * \\brief Helper function to convert an vector to TRT Dims.\n * \\param vec Vector.\n * \\return TRT Dims.\n */\ntemplate <typename T>\ninline nvinfer1::Dims VectorToTrtDims(const std::vector<T>& vec) {\n  nvinfer1::Dims dims;\n  // Dims(nbDims=0, d[0]=1) is used to represent a scalar in TRT.\n  dims.d[0] = 1;\n  dims.nbDims = vec.size();\n  for (size_t i = 0; i < vec.size(); ++i) {\n    dims.d[i] = vec[i];\n  }\n  return dims;\n}\n\n/*!\n * \\brief Helper function to convert TRT Dims to vector.\n * \\param vec TRT Dims.\n * \\return Vector.\n */\ninline std::vector<int> TrtDimsToVector(const nvinfer1::Dims& dims) {\n  return std::vector<int>(dims.d, dims.d + dims.nbDims);\n}\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TENSORRT_TENSORRT_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/tflite/tflite_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Tflite runtime that can run tflite model\n *        containing only tvm PackedFunc.\n * \\file tflite_runtime.h\n */\n#ifndef TVM_RUNTIME_CONTRIB_TFLITE_TFLITE_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_TFLITE_TFLITE_RUNTIME_H_\n\n#include <dlpack/dlpack.h>\n#include <tensorflow/lite/interpreter.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n#define CHECK_TFLITE_STATUS(ret) ICHECK_EQ(ret, kTfLiteOk)\n\n/*!\n * \\brief Tflite runtime.\n *\n *  This runtime can be accessed in various language via\n *  TVM runtime PackedFunc API.\n */\nclass TFLiteRuntime : public ModuleNode {\n public:\n  /*!\n   * \\brief Get member function to front-end.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const { return \"TFLiteRuntime\"; }\n\n  /*!\n   * \\brief Invoke the internal tflite interpreter and run the whole model in\n   * dependency order.\n   */\n  void Invoke();\n\n  /*!\n   * \\brief Initialize the tflite runtime with tflite model and device.\n   * \\param tflite_model_bytes The tflite model.\n   * \\param dev The device where the tflite model will be executed on.\n   */\n  void Init(const std::string& tflite_model_bytes, Device dev);\n\n  /*!\n   * \\brief set index-th input to the model.\n   * \\param index The input index.\n   * \\param data_in The input data.\n   */\n  void SetInput(int index, DLTensor* data_in);\n  /*!\n   * \\brief Return NDArray for given input index.\n   * \\param index The input index.\n   *\n   * \\return NDArray corresponding to given input node index.\n   */\n  NDArray GetInput(int index) const;\n  /*!\n   * \\brief Return NDArray for given output index.\n   * \\param index The output index.\n   *\n   * \\return NDArray corresponding to given output node index.\n   */\n  NDArray GetOutput(int index) const;\n  /*!\n   * \\brief Set the number of threads available to the interpreter.\n   * \\param num_threads The number of threads to be set.\n   */\n  void SetNumThreads(int num_threads);\n\n  // Buffer backing the interpreter's model\n  std::unique_ptr<char[]> flatBuffersBuffer_;\n  // TFLite interpreter\n  std::unique_ptr<tflite::Interpreter> interpreter_;\n  // TVM device\n  Device device_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_CONTRIB_TFLITE_TFLITE_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/verilator/verilator_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/verilator/verilator_device.h\n * \\brief Use external verilator device.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_DEVICE_H_\n#define TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_DEVICE_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\n/*! \\brief Verilator device resource context  */\ntypedef void* VerilatorHandle;\n\n/*!\n * \\brief Allocate a verilator device resource handle\n * \\return The verilator device handle.\n */\nextern \"C\" TVM_DLL VerilatorHandle VerilatorAlloc();\n\n/*!\n * \\brief Free a verilator device handle\n * \\param handle The verilator device handle to be freed.\n */\nextern \"C\" TVM_DLL void VerilatorDealloc(VerilatorHandle handle);\n\n/*!\n * \\brief Read verilator register or memory\n * \\param handle The verilator device handle.\n * \\param id The register or memory identifier.\n * \\param addr The register or memory address (word-level).\n * \\return The value of register or memory.\n */\nextern \"C\" TVM_DLL int VerilatorRead(VerilatorHandle handle, int id, int addr);\n\n/*!\n * \\brief Write verilator register or memory\n * \\param handle The verilator device handle.\n * \\param id The register or memory identifier.\n * \\param addr The register or memory address (word-level).\n * \\param value The value of register or memory.\n */\nextern \"C\" TVM_DLL void VerilatorWrite(VerilatorHandle handle, int id, int addr, int value);\n\n/*!\n * \\brief Reset Verilator for n clock cycles\n * \\param handle The verilator device handle.\n * \\param n The number of reset cycles.\n */\nextern \"C\" TVM_DLL void VerilatorReset(VerilatorHandle handle, int n);\n\n/*!\n * \\brief Run Verilator for n clock cycles\n * \\param handle The verilator device handle.\n * \\param n The number of run cycles.\n */\nextern \"C\" TVM_DLL void VerilatorRun(VerilatorHandle handle, int n);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/verilator/verilator_kernel.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/verilator/verilator_kernel.h\n * \\brief Use external verilator library kernels.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_KERNEL_H_\n#define TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_KERNEL_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include \"verilator_device.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nextern \"C\" TVM_DLL void verilator_add(VerilatorHandle handle, int* left, int* right, int* out,\n                                      int p_h_, int p_w_);\n\nextern \"C\" TVM_DLL void verilator_bias_add(VerilatorHandle handle, int* data, int* bias, int* out,\n                                           int p_n_, int p_c_, int p_h_, int p_w_);\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_KERNEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/verilator/verilator_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/contrib/verilator/verilator_runtime.h\n * \\brief A runtime for Verilator.\n */\n\n#ifndef TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_RUNTIME_H_\n\n#include <dlfcn.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/registry.h>\n\n#include <cstddef>\n#include <string>\n#include <vector>\n\n#include \"../../library_module.h\"\n#include \"../json/json_node.h\"\n#include \"../json/json_runtime.h\"\n#include \"verilator_device.h\"\n#include \"verilator_kernel.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace contrib {\n\nusing namespace tvm::runtime;\nusing namespace tvm::runtime::contrib;\nusing namespace tvm::runtime::json;\n\ntypedef VerilatorHandle (*VerilatorAllocFunc)();\ntypedef void (*VerilatorDeallocFunc)(VerilatorHandle);\ntypedef void (*VerilatorResetFunc)(VerilatorHandle, int);\ntypedef int (*VerilatorReadFunc)(VerilatorHandle, int, int);\ntypedef void (*VerilatorAddFunc)(VerilatorHandle, int*, int*, int*, int, int);\ntypedef void (*VerilatorBiasAddFunc)(VerilatorHandle, int*, int*, int*, int, int, int, int);\n\nclass VerilatorLibrary : public Library {\n public:\n  ~VerilatorLibrary();\n\n  /*! \\brief load library */\n  void Load(const std::string& name);\n\n  /*! \\brief get symbol from libray */\n  void* GetSymbol(const char* name) final;\n\n private:\n  /*! \\brief the library handle */\n  void* lib_handle_{nullptr};\n};\n\nclass VerilatorProfiler {\n public:\n  /*! \\brief the number of cycle counter */\n  uint32_t cycle_counter{0};\n\n  /*! \\brief clear the profiler */\n  void Clear();\n\n  /*! \\brief get profiler data */\n  std::string AsJSON();\n\n  /*! \\brief profiler constructor */\n  static VerilatorProfiler* ThreadLocal();\n};\n\nclass VerilatorRuntime : public JSONRuntimeBase {\n public:\n  VerilatorRuntime(const std::string& symbol_name, const std::string& graph_json,\n                   const Array<String> const_names)\n      : JSONRuntimeBase(symbol_name, graph_json, const_names) {\n    VLOG(0) << \"creating verilator runtime\";\n  }\n\n  ~VerilatorRuntime();\n\n  const char* type_key() const final { return \"verilator\"; }\n\n  /*! \\brief set verilator library */\n  void SetLibrary(const std::string& lib_name);\n\n  /*! \\brief set the number of reset cycles */\n  void SetResetCycles(const int cycles);\n\n  /*! \\brief enable profiler */\n  void EnableProfiler();\n\n  /*! \\brief set cycle counter register id */\n  void SetProfilerCycleCounterId(const int id);\n\n  /*! \\brief init verilator runtime */\n  void Init(const Array<NDArray>& consts) override;\n\n  /*! \\brief run verilator runtime */\n  void Run() override;\n\n private:\n  /*! \\brief the verilator library path */\n  String lib_path_;\n  /*! \\brief the verilator device */\n  VerilatorHandle device_{nullptr};\n  /*! \\brief the verilator library */\n  VerilatorLibrary* lib_{nullptr};\n  /*! \\brief the verilator profiler */\n  VerilatorProfiler* prof_{nullptr};\n  /*! \\brief the verilator read function */\n  VerilatorReadFunc read_{nullptr};\n  /*! \\brief the verilator reset cycles */\n  int reset_cycles_{1};\n  /*! \\brief the verilator profiler status */\n  bool prof_enable_{false};\n  /*! \\brief the verilator profiler cycle counter id */\n  int prof_cycle_counter_id_{0};\n};\n\n}  // namespace contrib\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_VERILATOR_VERILATOR_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/contrib/vitis_ai/vitis_ai_runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Vitis-AI runtime that can run model\n *        containing only tvm PackedFunc.\n * \\file vitis_ai_runtime.h\n */\n#ifndef TVM_RUNTIME_CONTRIB_VITIS_AI_VITIS_AI_RUNTIME_H_\n#define TVM_RUNTIME_CONTRIB_VITIS_AI_VITIS_AI_RUNTIME_H_\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n// clang-format off\n#include <memory>\n#include <string>\n#include <vector>\n// clang-format on\n#include <pyxir/pyxir.hpp>\n#include <pyxir/runtime/run_options.hpp>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief VAI runtime.\n *\n *  This runtime can be accessed in various language via\n *  TVM runtime PackedFunc API.\n */\nclass VitisAIRuntime : public ModuleNode {\n public:\n  /*!\n   * \\brief Create VitisAI runtime from serialized XGraph\n   * \\param symbol_name The name of the function.\n   * \\param const_names The names of each constant in the sub-graph.\n   * \\param serialized_rt_mod The serialized runtime module.\n   * \\param export_rt_mod_path The path to the file to be used for exporting the\n   *        PyXIR runtime module.\n   */\n  VitisAIRuntime(const std::string& symbol_name, const Array<String> const_names,\n                 const std::string& serialized_rt_mod, const std::string& export_rt_mod);\n\n  /*!\n   * \\brief Create VitisAI runtime from serialized XGraph\n   * \\param symbol_name The name of the function.\n   * \\param xgraph_str serialized XGraph representation\n   * \\param const_names The names of each constant in the sub-graph.\n   * \\param dpu_target The Vitis-AI DPU target identifier (e.g. DPUCADX8G, DPUCZDX8G-zcu104).\n   * \\param build_dir The directory to be used for Vitis-AI build files.\n   * \\param work_dir The directory to be used for Vitis-AI work files.\n   * \\param export_rt_mod_path The path to the file to be used for exporting the\n   *        PyXIR runtime module.\n   */\n  VitisAIRuntime(const std::string& symbol_name, const std::string& xgraph_str,\n                 const Array<String> const_names, const std::string& dpu_target,\n                 const std::string& build_dir, const std::string& work_dir,\n                 const std::string& export_runtime_module_path);\n\n  /*!\n   * \\brief Get member function to front-end.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const { return \"VitisAIRuntime\"; }\n\n  /*!\n   * \\brief Serialize the content of the pyxir directory and save it to\n   *        binary stream.\n   * \\param stream The binary stream to save to.\n   */\n  void SaveToBinary(dmlc::Stream* stream) final;\n\n private:\n  /*! \\brief The only subgraph name for this module */\n  std::string symbol_name_;\n  /*! \\brief The required constant names */\n  Array<String> const_names_;\n  /*! \\brief The runtime module */\n  pyxir::RtModHolder rt_mod_;\n  /*! \\brief The XGraph input tensor names in the order as provided by TVM */\n  std::vector<std::string> in_tensor_names_;\n  /*! \\brief The XGraph output tensor names in the order as provided by TVM */\n  std::vector<std::string> out_tensor_names_;\n  /*! \\brief The file path for exporting the runtime module if set */\n  std::string export_rt_mod_path_;\n  /*! \\brief Whether constant tensors have been initialized */\n  bool initialized_{false};\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CONTRIB_VITIS_AI_VITIS_AI_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/aot_executor/aot_executor.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file aot_executor.c\n * \\brief implement AoT executor in C\n */\n\n#include <inttypes.h>\n#include <string.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/aot_executor.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/module.h>\n#include <tvm/runtime/crt/packed_func.h>\n#include <tvm/runtime/crt/page_allocator.h>\n\nstatic void DumpMetadata(const TVMMetadata* md) {\n  LOG_DEBUG(\"%s:\\n\", __FUNCTION__);\n  LOG_DEBUG(\"\\tmod_name=%s\\n\", md->mod_name);\n  LOG_DEBUG(\"\\tversion=%\" PRId64 \"\\n\", md->version);\n  LOG_DEBUG(\"\\tnum_inputs=%\" PRId64 \"\\n\", md->num_inputs);\n  LOG_DEBUG(\"\\tnum_outputs=%\" PRId64 \"\\n\", md->num_outputs);\n  LOG_DEBUG(\"\\tnum_workspace_pools=%\" PRId64 \"\\n\", md->num_workspace_pools);\n  LOG_DEBUG(\"\\tnum_constant_pools=%\" PRId64 \"\\n\", md->num_constant_pools);\n\n  int i;\n\n  for (i = 0; i < md->num_inputs; ++i) {\n    LOG_DEBUG(\"\\tinput[%d]: %s\\n\", i, md->inputs[i].name);\n  }\n\n  for (i = 0; i < md->num_outputs; ++i) {\n    LOG_DEBUG(\"\\toutput[%d]: %s\\n\", i, md->outputs[i].name);\n  }\n\n  for (i = 0; i < md->num_workspace_pools; ++i) {\n    LOG_DEBUG(\"\\tworkspace_pools[%d]: %s\\n\", i, md->workspace_pools[i].name);\n  }\n\n  for (i = 0; i < md->num_constant_pools; ++i) {\n    LOG_DEBUG(\"\\tconstant_pools[%d]: %s\\n\", i, md->constant_pools[i].name_hint);\n  }\n}\n\nint TVMAotExecutor_GetNumInputs(TVMAotExecutor* executor) { return executor->metadata->num_inputs; }\n\nint TVMAotExecutor_GetNumOutputs(TVMAotExecutor* executor) {\n  return executor->metadata->num_outputs;\n}\n\nint TVMAotExecutor_GetInputIndex(TVMAotExecutor* executor, const char* name) {\n  int i;\n  int rv = -1;\n\n  const TVMMetadata* md = executor->metadata;\n  for (i = 0; i < md->num_inputs; ++i) {\n    if (!strcmp(md->inputs[i].name, name)) {\n      rv = i;\n      break;\n    }\n  }\n  CHECK_GE(rv, 0, \"cannot find '%s' among input.\", name);\n  return rv;\n}\n\nint TVMAotExecutor_Run(TVMAotExecutor* executor) {\n  const char* tvm_main_suffix = \"___tvm_main__\";\n  char tvm_main_name[TVM_CRT_MAX_STRLEN_FUNCTION_NAME];\n\n  {\n    const size_t max_strlen = TVM_CRT_MAX_STRLEN_FUNCTION_NAME;\n    size_t len = strnlen(executor->metadata->mod_name, max_strlen);\n    len += strnlen(tvm_main_suffix, max_strlen);\n\n    CHECK_LT(len, max_strlen, \"tvm_main name too long %zu\\n\", len);\n  }\n\n  // create main function name string, e.g. \"tvmgen_default___tvm_main__\"\n  snprintf(tvm_main_name, sizeof(tvm_main_name), \"%s%s\", executor->metadata->mod_name,\n           tvm_main_suffix);\n\n  TVMPackedFunc tvm_main;\n  TVMArgs temp_args;\n\n  CHECK_LE(executor->num_args, TVM_CRT_MAX_ARGS, \"too many args %\" PRId64 \"\\n\", executor->num_args);\n\n  int i;\n  for (i = 0; i < executor->num_args; ++i) {\n    temp_args.values[i].v_handle = &executor->args[i].dl_tensor;\n    temp_args.tcodes[i] = kTVMDLTensorHandle;\n  }\n  temp_args.values_count = executor->num_args;\n\n  int status =\n      TVMPackedFunc_InitModuleFunc(&tvm_main, executor->module_handle, tvm_main_name, &temp_args);\n\n  if (status != 0) {\n    return status;\n  }\n\n  CHECK_EQ(tvm_main.Call(&tvm_main), 0, \"call to %s failed\", tvm_main_name);\n\n  return 0;\n}\n\nint TVMAotExecutor_Init(TVMAotExecutor* executor, TVMModuleHandle module_handle,\n                        const DLDevice device, const char* module_name) {\n  executor->module_handle = module_handle;\n  executor->device = device;\n\n  // get a pointer to the PackedFunc get_c_metadata() which gives us access to the top-level\n  // metadata structure\n  TVMPackedFunc get_c_metadata;\n  TVMArgs temp_args;\n  temp_args.values_count = 0;\n\n  const char* tvmgen_prefix = \"tvmgen_\";\n  const char* get_c_metdata_suffix = \"_get_c_metadata\";\n  char get_c_metdata_name[TVM_CRT_MAX_STRLEN_FUNCTION_NAME];\n\n  {\n    size_t max_strlen = TVM_CRT_MAX_STRLEN_FUNCTION_NAME;\n    size_t len = strnlen(tvmgen_prefix, max_strlen);\n    len += strnlen(module_name, max_strlen);\n    len += strnlen(get_c_metdata_suffix, max_strlen);\n\n    CHECK_LT(len, max_strlen, \"get_c_metadata name too long %zu\\n\", len);\n  }\n\n  // create get_c_metadata() function name string, e.g. \"tvmgen_default_get_c_metadata()\"\n  snprintf(get_c_metdata_name, sizeof(get_c_metdata_name), \"%s%s%s\", tvmgen_prefix, module_name,\n           get_c_metdata_suffix);\n\n  int status = TVMPackedFunc_InitModuleFunc(&get_c_metadata, executor->module_handle,\n                                            get_c_metdata_name, &temp_args);\n  if (status != 0) {\n    return status;\n  }\n\n  CHECK_EQ(get_c_metadata.Call(&get_c_metadata), 0, \"get_c_metadata\");\n\n  // save the returned pointer to the top-level metadata\n  executor->metadata = (TVMMetadata*)get_c_metadata.ret_value.values[0].v_handle;\n\n  const TVMMetadata* md = executor->metadata;\n\n  DumpMetadata(md);\n\n  executor->num_args = md->num_inputs + md->num_outputs + md->num_workspace_pools;\n\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(executor->num_args * sizeof(*executor->args),\n                                                  executor->device, (void**)(&executor->args));\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n\n  int i;\n  int arg_idx = 0;\n  for (i = 0; i < md->num_inputs; ++i) {\n    LOG_DEBUG(\"input allocate[%d]: %s\\n\", i, md->inputs[i].name);\n\n    TVMNDArray* array = &executor->args[arg_idx++];\n\n    status = TVMNDArray_Empty(md->inputs[i].num_shape, md->inputs[i].shape, md->inputs[i].dtype,\n                              executor->device, array);\n    if (status != 0) {\n      return status;\n    }\n\n    TVMNDArray_IncrementReference(array);\n  }\n\n  for (i = 0; i < md->num_outputs; ++i) {\n    LOG_DEBUG(\"output allocate[%d]: %s\\n\", i, md->outputs[i].name);\n\n    TVMNDArray* array = &executor->args[arg_idx++];\n\n    status = TVMNDArray_Empty(md->outputs[i].num_shape, md->outputs[i].shape, md->outputs[i].dtype,\n                              executor->device, array);\n    if (status != 0) {\n      return status;\n    }\n\n    TVMNDArray_IncrementReference(array);\n  }\n\n  for (i = 0; i < md->num_workspace_pools; ++i) {\n    LOG_DEBUG(\"pools allocate[%d]: %s\\n\", i, md->workspace_pools[i].name);\n\n    status = TVMNDArray_Empty(md->workspace_pools[i].num_shape, md->workspace_pools[i].shape,\n                              md->workspace_pools[i].dtype, executor->device,\n                              &executor->args[arg_idx++]);\n    if (status != 0) {\n      return status;\n    }\n  }\n  CHECK_EQ(0, md->num_constant_pools, \"Constant pools not supported\");\n  return status;\n}\n\nint TVMAotExecutor_Create(TVMModuleHandle module_handle, const DLDevice device,\n                          TVMAotExecutor** executor, const char* module_name) {\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(**executor), device, (void**)executor);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n\n  memset(*executor, 0, sizeof(**executor));\n\n  return TVMAotExecutor_Init(*executor, module_handle, device, module_name);\n}\n\nint TVMAotExecutor_Release(TVMAotExecutor* executor, const DLDevice device) {\n  int status;\n\n  if (executor->num_args > 0) {\n    // free TVMNDArray data memory for each each argument\n    int i;\n    for (i = 0; i < executor->num_args; ++i) {\n      status = TVMNDArray_Release(&executor->args[i]);\n      if (status != 0) {\n        return status;\n      }\n    }\n\n    // free TVMNDArray argument list\n    status = TVMPlatformMemoryFree(executor->args, executor->device);\n    if (status != 0) {\n      return status;\n    }\n  }\n\n  status = TVMPlatformMemoryFree(executor, device);\n  if (status != 0) {\n    return status;\n  }\n\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/aot_executor_module/aot_executor_module.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file aot_executor_module.c\n * \\brief wrap aot_executor into a TVMModule for use with RPC.\n */\n\n#include <stdio.h>\n#include <tvm/runtime/crt/aot_executor.h>\n#include <tvm/runtime/crt/aot_executor_module.h>\n#include <tvm/runtime/crt/func_registry.h>\n#include <tvm/runtime/crt/module.h>\n\ntypedef struct {\n  TVMModule mod;\n  TVMAotExecutor* executor;\n} AotExecutorModule;\n\nstatic AotExecutorModule aot_executor;\n\nint32_t TVMAotExecutorModule_Create(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                    int* ret_tcodes, void* resource_handle) {\n  if (aot_executor.executor != NULL) {\n    return kTvmErrorExecutorModuleAlreadyCreated;\n  }\n\n  if (nargs != 3) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMModuleHandle || tcodes[1] != kDLDevice || tcodes[2] != kTVMStr) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  DLDevice dev = args[1].v_device;\n\n  if (dev.device_type != kDLCPU) {\n    return kTvmErrorExecutorModuleBadContext;\n  }\n\n  TVMAotExecutor_Create(args[0].v_handle, dev, &aot_executor.executor, args[2].v_str);\n\n  TVMModuleHandle out_mod;\n  int status = TVMModCreateFromCModule(&aot_executor.mod, &out_mod);\n  if (status != 0) {\n    ret_tcodes[0] = kTVMNullptr;\n    TVMAotExecutor_Release(aot_executor.executor, dev);\n    return status;\n  }\n\n  ret_values[0].v_handle = out_mod;\n  ret_tcodes[0] = kTVMModuleHandle;\n  return kTvmErrorNoError;\n}\n\nint32_t TVMAotExecutorModule_NotImplemented(TVMValue* args, int* tcodes, int nargs,\n                                            TVMValue* ret_values, int* ret_tcodes,\n                                            void* resource_handle) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\nint32_t TVMAotExecutorModule_GetInput(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                      int* ret_tcodes, void* resource_handle) {\n  int64_t index;\n\n  if (tcodes[0] == kTVMArgInt) {\n    if (args[0].v_int64 > TVMAotExecutor_GetNumInputs(aot_executor.executor)) {\n      return kTvmErrorFunctionCallInvalidArg;\n    }\n\n    index = args[0].v_int64;\n  } else {\n    index = TVMAotExecutor_GetInputIndex(aot_executor.executor, args[0].v_str);\n\n    if (index < 0) {\n      return kTvmErrorExecutorModuleNoSuchInput;\n    }\n  }\n\n  TVMNDArray* array = &aot_executor.executor->args[index];\n\n  TVMNDArray_IncrementReference(array);\n\n  ret_values[0].v_handle = (void*)(&array->dl_tensor);\n  ret_tcodes[0] = kTVMNDArrayHandle;\n\n  return 0;\n}\n\nint32_t TVMAotExecutorModule_GetOutput(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                       int* ret_tcodes, void* resource_handle) {\n  if (nargs != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (args[0].v_int64 > TVMAotExecutor_GetNumOutputs(aot_executor.executor)) {\n    return kTvmErrorFunctionCallInvalidArg;\n  }\n\n  // index past the input entries\n  int64_t index = args[0].v_int64 + TVMAotExecutor_GetNumInputs(aot_executor.executor);\n\n  TVMNDArray* array = &aot_executor.executor->args[index];\n\n  TVMNDArray_IncrementReference(array);\n\n  ret_values[0].v_handle = (void*)(&array->dl_tensor);\n  ret_tcodes[0] = kTVMNDArrayHandle;\n\n  return 0;\n}\n\nint32_t TVMAotExecutorModule_GetInputIndex(TVMValue* args, int* tcodes, int nargs,\n                                           TVMValue* ret_values, int* ret_tcodes,\n                                           void* resource_handle) {\n  if (nargs != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  int index = TVMAotExecutor_GetInputIndex(aot_executor.executor, args[0].v_str);\n\n  if (index < 0) {\n    return kTvmErrorExecutorModuleNoSuchInput;\n  }\n\n  ret_values[0].v_int64 = index;\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMAotExecutorModule_GetNumInputs(TVMValue* args, int* tcodes, int nargs,\n                                          TVMValue* ret_values, int* ret_tcodes,\n                                          void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  ret_values[0].v_int64 = TVMAotExecutor_GetNumInputs(aot_executor.executor);\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMAotExecutorModule_GetNumOutputs(TVMValue* args, int* tcodes, int nargs,\n                                           TVMValue* ret_values, int* ret_tcodes,\n                                           void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  ret_values[0].v_int64 = TVMAotExecutor_GetNumOutputs(aot_executor.executor);\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMAotExecutorModule_Run(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                 int* ret_tcodes, void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  return TVMAotExecutor_Run(aot_executor.executor);\n}\n\nstatic const TVMBackendPackedCFunc aot_executor_registry_funcs[] = {\n    &TVMAotExecutorModule_GetInput,        // get_input\n    &TVMAotExecutorModule_GetInputIndex,   // get_input_index\n    &TVMAotExecutorModule_NotImplemented,  // get_input_info (do not implement)\n    &TVMAotExecutorModule_GetNumInputs,    // get_num_inputs\n    &TVMAotExecutorModule_GetNumOutputs,   // get_num_outputs\n    &TVMAotExecutorModule_GetOutput,       // get_output\n    &TVMAotExecutorModule_NotImplemented,  // load_params (do not implement)\n    &TVMAotExecutorModule_Run,             // run\n    &TVMAotExecutorModule_NotImplemented,  // set_input (implemented via python wrapper)\n    &TVMAotExecutorModule_NotImplemented,  // share_params (do not implement)\n};\n\nstatic const TVMFuncRegistry aot_executor_registry = {\n    \"\\x0a\\0get_input\\0\"\n    \"get_input_index\\0\"\n    \"get_input_info\\0\"\n    \"get_num_inputs\\0\"\n    \"get_num_outputs\\0\"\n    \"get_output\\0\"\n    \"load_params\\0\"\n    \"run\\0\"\n    \"set_input\\0\"\n    \"share_params\\0\",\n    aot_executor_registry_funcs};\n\ntvm_crt_error_t TVMAotExecutorModule_Register() {\n  aot_executor.mod.registry = &aot_executor_registry;\n  aot_executor.executor = NULL;\n\n  return TVMFuncRegisterGlobal(\"tvm.aot_executor.create\", &TVMAotExecutorModule_Create, 0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/common/crt_backend_api.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n#include <assert.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/page_allocator.h>\n#include <tvm/runtime/crt/platform.h>\n\n#include \"crt_config.h\"\n\nvoid* TVMBackendAllocWorkspace(int device_type, int device_id, uint64_t nbytes, int dtype_code_hint,\n                               int dtype_bits_hint) {\n  tvm_crt_error_t err = kTvmErrorNoError;\n  void* ptr = 0;\n  DLDevice dev = {device_type, device_id};\n  assert(nbytes > 0);\n  err = TVMPlatformMemoryAllocate(nbytes, dev, &ptr);\n  CHECK_EQ(err, kTvmErrorNoError,\n           \"TVMBackendAllocWorkspace(%d, %d, %\" PRIu64 \", %d, %d) -> %\" PRId32, device_type,\n           device_id, nbytes, dtype_code_hint, dtype_bits_hint, err);\n  return ptr;\n}\n\nint TVMBackendFreeWorkspace(int device_type, int device_id, void* ptr) {\n  tvm_crt_error_t err = kTvmErrorNoError;\n  DLDevice dev = {device_type, device_id};\n  err = TVMPlatformMemoryFree(ptr, dev);\n  return err;\n}\n\nint TVMBackendParallelLaunch(FTVMParallelLambda flambda, void* cdata, int num_task) {\n  TVMParallelGroupEnv env;\n  env.num_task = 1;\n  flambda(0, &env, cdata);\n  return 0;\n}\n\nint TVMBackendRegisterSystemLibSymbol(const char* name, void* ptr) {\n  return TVMFuncRegisterGlobal(name, ptr, 0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/common/crt_runtime_api.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n#include <assert.h>\n#include <inttypes.h>\n#include <math.h>\n#include <stdarg.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/crt.h>\n#include <tvm/runtime/crt/func_registry.h>\n#include <tvm/runtime/crt/internal/common/ndarray.h>\n#include <tvm/runtime/crt/internal/graph_executor/graph_executor.h>\n#include <tvm/runtime/crt/platform.h>\n\n#if defined(_WIN32) || defined(WIN32)\n#include <windows.h>\n#elif __unix__\n#include <unistd.h>\n#endif\n\n// Handle internal errors\n\nstatic char g_last_error[1024];\n\nvoid TVMAPISetLastError(const char* msg) {\n  strncpy(g_last_error, msg, sizeof(g_last_error) - 1);\n  g_last_error[sizeof(g_last_error) - 1] = 0;\n}\n\n__attribute__((format(printf, 1, 2))) int TVMAPIErrorf(const char* msg, ...) {\n  va_list args;\n  int to_return;\n\n  va_start(args, msg);\n  to_return = vsnprintf(g_last_error, sizeof(g_last_error), msg, args);\n  va_end(args);\n\n  return to_return;\n}\n\nconst char* TVMGetLastError(void) { return g_last_error; }\n\n// Manipulate NDArray on target device\n\nint TVMArrayAlloc(const tvm_index_t* shape, int ndim, int dtype_code, int dtype_bits,\n                  int dtype_lanes, int device_type, int device_id, TVMArrayHandle* out) {\n  DLDataType dtype;\n  dtype.code = dtype_code;\n  dtype.bits = dtype_bits;\n  dtype.lanes = dtype_lanes;\n  DLDevice dev;\n  dev.device_type = (DLDeviceType)device_type;\n  dev.device_id = device_id;\n  TVMNDArray arr;\n  int status = TVMNDArray_Empty(ndim, shape, dtype, dev, &arr);\n  if (status != 0) {\n    return status;\n  }\n  **out = arr.dl_tensor;\n  return 0;\n}\n\nint TVMArrayFree(TVMArrayHandle handle) {\n  TVMNDArray* arr = (TVMNDArray*)handle;\n\n  return TVMNDArray_Release(arr);\n}\n\nint TVMDeviceAllocDataSpace(DLDevice dev, size_t nbytes, size_t alignment, DLDataType type_hint,\n                            void** out_data) {\n  if (alignment != 1) {\n    nbytes = (nbytes + alignment - 1) / alignment * alignment;\n  }\n  return TVMPlatformMemoryAllocate(nbytes, dev, out_data);\n}\n\nint TVMDeviceAllocDataSpaceWithScope(DLDevice dev, int ndim, const int64_t* shape, DLDataType dtype,\n                                     const char* mem_scope, void** out_data) {\n  size_t nbytes = 1;\n  for (int i = 0; i < ndim; ++i) {\n    nbytes *= shape[i];\n  }\n  nbytes *= (dtype.bits * dtype.lanes + 7) / 8;\n\n  int kAllocAlignment = 64;\n  size_t align = (dtype.bits / 8) * dtype.lanes;\n  if (align < kAllocAlignment) align = kAllocAlignment;\n  return TVMDeviceAllocDataSpace(dev, nbytes, align, dtype, out_data);\n}\n\nint TVMDeviceFreeDataSpace(DLDevice dev, void* ptr) { return TVMPlatformMemoryFree(ptr, dev); }\n\nstatic bool IsContiguous(const DLTensor* arr) {\n  if (arr->strides == NULL) return true;\n  int64_t expected_stride = 1;\n  for (int32_t i = arr->ndim; i != 0; --i) {\n    int32_t k = i - 1;\n    if (arr->strides[k] != expected_stride) return false;\n    expected_stride *= arr->shape[k];\n  }\n  return true;\n}\n\nint TVMDeviceCopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream) {\n  assert(IsContiguous(from) && IsContiguous(to));\n  size_t size = 1;\n  for (int i = 0; i < from->ndim; ++i) {\n    size *= from->shape[i];\n  }\n  size *= (from->dtype.bits * from->dtype.lanes + 7) / 8;\n  memcpy(((uint8_t*)to->data) + to->byte_offset, ((uint8_t*)from->data) + from->byte_offset, size);\n  return 0;\n}\n\nint TVMStreamCreate(int device_type, int device_id, TVMStreamHandle* out) {\n  out = NULL;\n  return 0;\n}\n\nint TVMStreamFree(int device_type, int device_id, TVMStreamHandle stream) { return 0; }\n\nint TVMSetStream(int device_type, int device_id, TVMStreamHandle stream) { return 0; }\n\nint TVMSynchronize(int device_type, int device_id, TVMStreamHandle stream) { return 0; }\n\nstatic TVMMutableFuncRegistry global_func_registry;\n\nint TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) {\n  return TVMMutableFuncRegistry_Set(&global_func_registry, name, f, override != 0);\n}\n\nstatic const TVMModule* registered_modules[TVM_CRT_MAX_REGISTERED_MODULES];\n\n/*! \\brief Passed as `module_index` to EncodeFunctionHandle. */\nstatic const tvm_module_index_t kGlobalFuncModuleIndex = TVM_CRT_MAX_REGISTERED_MODULES;\n\n/*! \\brief Special module handle for return values from RPCTimeEvaluator. */\nstatic const tvm_module_index_t kTimeEvaluatorModuleIndex = 0x7fff;\n\nstatic int DecodeModuleHandle(TVMModuleHandle handle, tvm_module_index_t* out_module_index) {\n  tvm_module_index_t module_index;\n\n  module_index = ((tvm_module_index_t)((uintptr_t)handle)) & ~0x8000;\n  if (module_index > TVM_CRT_MAX_REGISTERED_MODULES || registered_modules[module_index] == NULL) {\n    TVMAPIErrorf(\"invalid module handle: %08x\", module_index);\n    return -1;\n  }\n\n  *out_module_index = module_index;\n  return 0;\n}\n\nstatic TVMModuleHandle EncodeModuleHandle(tvm_module_index_t module_index) {\n  return (TVMModuleHandle)((uintptr_t)(module_index | 0x8000));\n}\n\nint TVMModCreateFromCModule(const TVMModule* mod, TVMModuleHandle* out_handle) {\n  tvm_module_index_t idx;\n\n  for (idx = 0; idx < TVM_CRT_MAX_REGISTERED_MODULES; idx++) {\n    if (registered_modules[idx] == NULL) {\n      registered_modules[idx] = mod;\n      *out_handle = EncodeModuleHandle(idx);\n      return 0;\n    }\n  }\n\n  return -1;\n}\n\nstatic const TVMModuleHandle kTVMModuleHandleUninitialized = (TVMModuleHandle)(~0UL);\n\nstatic TVMModuleHandle system_lib_handle;\n\nint TVMModFree(TVMModuleHandle mod) {\n  /* Never free system_lib_handler */\n  if (mod == system_lib_handle && system_lib_handle != kTVMModuleHandleUninitialized) {\n    return 0;\n  }\n\n  tvm_module_index_t module_index;\n  if (DecodeModuleHandle(mod, &module_index) != 0) {\n    return -1;\n  }\n\n  registered_modules[module_index] = NULL;\n  return 0;\n}\n\nstatic int SystemLibraryCreate(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_val,\n                               int* ret_type_codes) {\n  const TVMModule* system_lib;\n\n  if (system_lib_handle == kTVMModuleHandleUninitialized) {\n    system_lib = TVMSystemLibEntryPoint();\n    if (TVMModCreateFromCModule(system_lib, &system_lib_handle) != 0) {\n      TVMAPIErrorf(\"error registering system lib\");\n      return -1;\n    }\n  }\n\n  ret_val[0].v_handle = system_lib_handle;\n  ret_type_codes[0] = kTVMModuleHandle;\n  return 0;\n}\n\nstatic TVMFunctionHandle EncodeFunctionHandle(tvm_module_index_t module_index,\n                                              tvm_function_index_t function_index) {\n  return (TVMFunctionHandle)(\n      (((uintptr_t)(module_index | 0x8000) << (sizeof(tvm_function_index_t) * 8)) |\n       (function_index | 0x8000)));\n}\n\nstatic int DecodeFunctionHandle(TVMFunctionHandle handle, tvm_module_index_t* module_index,\n                                tvm_function_index_t* function_index) {\n  tvm_module_index_t unvalidated_module_index;\n  unvalidated_module_index =\n      (tvm_module_index_t)(((uintptr_t)handle) >> (sizeof(tvm_function_index_t) * 8));\n  unvalidated_module_index &= ~0x8000;\n\n  if (unvalidated_module_index != kTimeEvaluatorModuleIndex) {\n    if (unvalidated_module_index > kGlobalFuncModuleIndex) {\n      TVMAPIErrorf(\"invalid module handle: index=%08x\", unvalidated_module_index);\n      return -1;\n    } else if (unvalidated_module_index < kGlobalFuncModuleIndex &&\n               registered_modules[unvalidated_module_index] == NULL) {\n      TVMAPIErrorf(\"unregistered module: index=%08x\", unvalidated_module_index);\n      return -1;\n    }\n  }\n\n  *function_index = ((uint32_t)((uintptr_t)handle)) & ~0x8000;\n  *module_index = unvalidated_module_index;\n  return 0;\n}\n\nint TVMByteArrayFree(TVMByteArray* arr) {\n  DLDevice dev = {kDLCPU, 0};\n  int to_return = TVMPlatformMemoryFree((void*)arr->data, dev);\n  if (to_return != 0) {\n    return to_return;\n  }\n\n  return TVMPlatformMemoryFree((void*)arr, dev);\n}\n\ntvm_crt_error_t RunTimeEvaluator(tvm_function_index_t function_index, TVMValue* args,\n                                 int* type_codes, int num_args, TVMValue* ret_val,\n                                 int* ret_type_code);\n\nint TVMFuncCall(TVMFunctionHandle func_handle, TVMValue* arg_values, int* type_codes, int num_args,\n                TVMValue* ret_val, int* ret_type_code) {\n  tvm_module_index_t module_index;\n  tvm_function_index_t function_index;\n  void* resource_handle;\n  const TVMFuncRegistry* registry;\n  TVMBackendPackedCFunc func;\n\n  if (DecodeFunctionHandle(func_handle, &module_index, &function_index) != 0) {\n    return -1;\n  }\n\n  if (module_index == kTimeEvaluatorModuleIndex) {\n    return RunTimeEvaluator(function_index, arg_values, type_codes, num_args, ret_val,\n                            ret_type_code);\n  } else if (module_index == kGlobalFuncModuleIndex) {\n    resource_handle = NULL;\n    registry = &global_func_registry.registry;\n  } else {\n    resource_handle = (void*)registered_modules[module_index]->registry;\n    registry = registered_modules[module_index]->registry;\n  }\n\n  if (TVMFuncRegistry_GetByIndex(registry, function_index, &func) != 0) {\n    TVMAPIErrorf(\"invalid function index: %04\" PRIx16, function_index);\n    return -1;\n  }\n\n  ret_type_code[0] = kTVMNullptr;\n  ret_val[0].v_handle = NULL;\n  return func(arg_values, type_codes, num_args, ret_val, ret_type_code, resource_handle);\n}\n\nstatic tvm_crt_error_t FindFunctionOrSetAPIError(tvm_module_index_t module_index,\n                                                 const TVMFuncRegistry* registry, const char* name,\n                                                 TVMFunctionHandle* out) {\n  tvm_function_index_t function_index;\n  tvm_crt_error_t err = TVMFuncRegistry_Lookup(registry, name, &function_index);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n\n  *out = EncodeFunctionHandle(module_index, function_index);\n  return kTvmErrorNoError;\n}\n\nint TVMFuncGetGlobal(const char* name, TVMFunctionHandle* out) {\n  tvm_crt_error_t to_return =\n      FindFunctionOrSetAPIError(kGlobalFuncModuleIndex, &global_func_registry.registry, name, out);\n  // For compatibility with the C++ runtime equivalent, in src/runtime/registry.cc.\n  if (to_return == kTvmErrorFunctionNameNotFound) {\n    *out = NULL;\n    to_return = kTvmErrorNoError;\n  }\n  return to_return;\n}\n\nint TVMModGetFunction(TVMModuleHandle mod, const char* func_name, int query_imports,\n                      TVMFunctionHandle* out) {\n  tvm_module_index_t module_index;\n  if (DecodeModuleHandle(mod, &module_index) != 0) {\n    return -1;\n  }\n\n  return FindFunctionOrSetAPIError(module_index, registered_modules[module_index]->registry,\n                                   func_name, out);\n}\n\nint ModuleGetFunction(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_value,\n                      int* ret_type_codes) {\n  TVMModuleHandle mod;\n  const char* name;\n  int to_return;\n  int query_imports;\n\n  ret_value[0].v_handle = NULL;\n  ret_type_codes[0] = kTVMNullptr;\n  if (num_args != 3 || type_codes[0] != kTVMModuleHandle || type_codes[1] != kTVMStr ||\n      type_codes[2] != kDLInt) {\n    return 0;\n  }\n\n  mod = (TVMModuleHandle)args[0].v_handle;\n  name = args[1].v_str;\n  query_imports = args[2].v_int64 != 0;\n  to_return = TVMModGetFunction(mod, name, query_imports, &ret_value->v_handle);\n\n  if (to_return == 0) {\n    ret_type_codes[0] = kTVMPackedFuncHandle;\n  } else {\n    ret_value->v_handle = NULL;\n  }\n\n  // NOTE: For compatibility with C++ runtime API, return no error (but NULL function) when the\n  // function lookup failed.\n  if (to_return == kTvmErrorFunctionNameNotFound) {\n    to_return = kTvmErrorNoError;\n  }\n  return to_return;\n}\n\ntypedef struct TVMCReturnValue {\n  TVMValue* ret_val;\n  int* ret_type_code;\n} TVMCReturnValue;\n\nint TVMCFuncSetReturn(TVMRetValueHandle ret, TVMValue* value, int* type_code, int num_ret) {\n  TVMCReturnValue* ret_val;\n  int idx;\n\n  ret_val = (TVMCReturnValue*)ret;\n  for (idx = 0; idx < num_ret; idx++) {\n    ret_val->ret_val[idx] = value[idx];\n    ret_val->ret_type_code[idx] = type_code[idx];\n  }\n\n  return 0;\n}\n\nint TVMFuncFree(TVMFunctionHandle func) {\n  // A no-op, since we don't actually allocate anything in GetFunction.\n  return 0;\n}\n\nint RPCTimeEvaluator(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_val,\n                     int* ret_type_code);\n\n// Sends CRT max packet size.\nint RPCGetCRTMaxPacketSize(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_value,\n                           int* ret_type_codes) {\n  // 11 bytes is for microtvm overhead:\n  // packet start(2), length(4), session header(3), crc(2)\n  ret_value[0].v_int64 = TVM_CRT_MAX_PACKET_SIZE_BYTES - 11;\n  ret_type_codes[0] = kTVMArgInt;\n  return 0;\n}\n\n// Fill the tensor in args[0] with random data using TVMPlatformGenerateRandom.\nstatic int RandomFill(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_val,\n                      int* ret_type_code) {\n  if (num_args != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (type_codes[0] != kTVMDLTensorHandle) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  DLTensor* tensor = (DLTensor*)args[0].v_handle;\n  TVMNDArray arr = {*tensor, 0};\n  return TVMNDArray_RandomFill(&arr);\n}\n\ntvm_crt_error_t TVMInitializeRuntime() {\n  int idx = 0;\n  tvm_crt_error_t error = kTvmErrorNoError;\n\n  DLDevice dev = {kDLCPU, 0};\n\n  void* registry_backing_memory;\n  error = TVMPlatformMemoryAllocate(TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES, dev,\n                                    &registry_backing_memory);\n  if (error != kTvmErrorNoError) {\n    return error;\n  }\n\n  system_lib_handle = kTVMModuleHandleUninitialized;\n\n  error = TVMMutableFuncRegistry_Create(&global_func_registry, registry_backing_memory,\n                                        TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES);\n  for (idx = 0; idx < TVM_CRT_MAX_REGISTERED_MODULES; idx++) {\n    registered_modules[idx] = NULL;\n  }\n\n  if (error == kTvmErrorNoError) {\n    error = TVMFuncRegisterGlobal(\"runtime.SystemLib\", &SystemLibraryCreate, 0);\n  }\n\n  if (error == kTvmErrorNoError) {\n    error = TVMFuncRegisterGlobal(\"tvm.rpc.server.ModuleGetFunction\", &ModuleGetFunction, 0);\n  }\n\n  if (error == kTvmErrorNoError) {\n    error = TVMFuncRegisterGlobal(\"runtime.RPCTimeEvaluator\", &RPCTimeEvaluator, 0);\n  }\n\n  if (error == kTvmErrorNoError) {\n    error = TVMFuncRegisterGlobal(\"tvm.rpc.server.GetCRTMaxPacketSize\", &RPCGetCRTMaxPacketSize, 0);\n  }\n\n  if (error == kTvmErrorNoError) {\n    error = TVMFuncRegisterGlobal(\"tvm.contrib.random.random_fill\", &RandomFill, 0);\n  }\n\n  if (error != kTvmErrorNoError) {\n    TVMPlatformMemoryFree(registry_backing_memory, dev);\n  }\n\n  return error;\n}\n\ntypedef struct {\n  uint16_t function_index;\n  TVMFunctionHandle func_to_time;\n  DLDevice device;\n  int number;\n  int repeat;\n  int min_repeat_ms;\n  int limit_zero_time_iterations;\n  int cooldown_interval_ms;\n  int repeats_to_cooldown;\n} time_evaluator_state_t;\n\nstatic time_evaluator_state_t g_time_evaluator_state;\n\nint RPCTimeEvaluator(TVMValue* args, int* type_codes, int num_args, TVMValue* ret_val,\n                     int* ret_type_code) {\n  ret_val[0].v_handle = NULL;\n  ret_type_code[0] = kTVMNullptr;\n  if (num_args < 11) {\n    TVMAPIErrorf(\"not enough args\");\n    return kTvmErrorFunctionCallNumArguments;\n  }\n  if (type_codes[0] != kTVMModuleHandle || type_codes[1] != kTVMStr ||\n      type_codes[2] != kTVMArgInt || type_codes[3] != kTVMArgInt || type_codes[4] != kTVMArgInt ||\n      type_codes[5] != kTVMArgInt || type_codes[6] != kTVMArgInt || type_codes[7] != kTVMArgInt ||\n      type_codes[8] != kTVMArgInt || type_codes[9] != kTVMArgInt || type_codes[10] != kTVMStr) {\n    TVMAPIErrorf(\"one or more invalid arg types\");\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  TVMModuleHandle mod = (TVMModuleHandle)args[0].v_handle;\n  const char* name = args[1].v_str;\n  g_time_evaluator_state.device.device_type = args[2].v_int64;\n  g_time_evaluator_state.device.device_id = args[3].v_int64;\n  g_time_evaluator_state.number = args[4].v_int64;\n  g_time_evaluator_state.repeat = args[5].v_int64;\n  g_time_evaluator_state.min_repeat_ms = args[6].v_int64;\n  g_time_evaluator_state.limit_zero_time_iterations = args[7].v_int64;\n  g_time_evaluator_state.cooldown_interval_ms = args[8].v_int64;\n  g_time_evaluator_state.repeats_to_cooldown = args[9].v_int64;\n\n  int ret_code =\n      TVMModGetFunction(mod, name, /* query_imports */ 0, &g_time_evaluator_state.func_to_time);\n  if (ret_code != 0) {\n    return ret_code;\n  }\n\n  g_time_evaluator_state.function_index++;\n  ret_val[0].v_handle =\n      EncodeFunctionHandle(kTimeEvaluatorModuleIndex, g_time_evaluator_state.function_index);\n  ret_type_code[0] = kTVMPackedFuncHandle;\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t RunTimeEvaluator(tvm_function_index_t function_index, TVMValue* args,\n                                 int* type_codes, int num_args, TVMValue* ret_val,\n                                 int* ret_type_code) {\n  if (function_index != g_time_evaluator_state.function_index) {\n    return kTvmErrorTimeEvaluatorBadHandle;\n  }\n\n  // TODO(areusch): should *really* rethink needing to return doubles\n  DLDevice result_byte_dev = {kDLCPU, 0};\n  TVMByteArray* result_byte_arr = NULL;\n  tvm_crt_error_t err =\n      TVMPlatformMemoryAllocate(sizeof(TVMByteArray), result_byte_dev, (void*)&result_byte_arr);\n  if (err != kTvmErrorNoError) {\n    goto release_and_return;\n  }\n  result_byte_arr->data = NULL;\n  size_t data_size = sizeof(double) * g_time_evaluator_state.repeat;\n  err = TVMPlatformMemoryAllocate(data_size, result_byte_dev, (void**)&result_byte_arr->data);\n  if (err != kTvmErrorNoError) {\n    goto release_and_return;\n  }\n  result_byte_arr->size = data_size;\n\n  // skip first time call, to activate lazy compilation components.\n  err = TVMFuncCall(g_time_evaluator_state.func_to_time, args, type_codes, num_args, ret_val,\n                    ret_type_code);\n  if (err != kTvmErrorNoError) {\n    goto release_and_return;\n  }\n\n  double min_repeat_seconds = ((double)g_time_evaluator_state.min_repeat_ms) / 1000;\n  double* iter = (double*)result_byte_arr->data;\n  for (int i = 0; i < g_time_evaluator_state.repeat; i++) {\n    double curr_res_seconds = 0.0;\n    int absolute_zero_times = 0;\n    // do-while structure ensures we run even when `min_repeat_ms` isn't set (i.e., is 0).\n    do {\n      if (curr_res_seconds > 0.0) {\n        double a = (min_repeat_seconds / (curr_res_seconds / g_time_evaluator_state.number) + 1);\n        const double golden_ratio = 1.618;\n        double b = g_time_evaluator_state.number * golden_ratio;\n        g_time_evaluator_state.number = (int64_t)(a > b ? a : b);\n      }\n      err = TVMPlatformBeforeMeasurement();\n      if (err != kTvmErrorNoError) {\n        goto release_and_return;\n      }\n      err = TVMPlatformTimerStart();\n      if (err != kTvmErrorNoError) {\n        goto release_and_return;\n      }\n\n      for (int j = 0; j < g_time_evaluator_state.number; j++) {\n        err = TVMFuncCall(g_time_evaluator_state.func_to_time, args, type_codes, num_args, ret_val,\n                          ret_type_code);\n        if (err != kTvmErrorNoError) {\n          goto release_and_return;\n        }\n      }\n      err = TVMPlatformTimerStop(&curr_res_seconds);\n      if (err != kTvmErrorNoError) {\n        goto release_and_return;\n      }\n      err = TVMPlatformAfterMeasurement();\n      if (err != kTvmErrorNoError) {\n        goto release_and_return;\n      }\n      if (fpclassify(curr_res_seconds) == FP_ZERO) absolute_zero_times++;\n    } while (curr_res_seconds < min_repeat_seconds &&\n             absolute_zero_times < g_time_evaluator_state.limit_zero_time_iterations);\n    double mean_exec_seconds = curr_res_seconds / g_time_evaluator_state.number;\n    *iter = mean_exec_seconds;\n    iter++;\n    if (g_time_evaluator_state.cooldown_interval_ms > 0 &&\n        (i % g_time_evaluator_state.repeats_to_cooldown) == 0) {\n#if defined(_WIN32) || defined(WIN32)\n      Sleep(g_time_evaluator_state.cooldown_interval_ms);\n#elif __unix__\n      usleep(g_time_evaluator_state.cooldown_interval_ms * 1000);\n#else\n      TVMAPIErrorf(\n          \"No support for non-zero cooldown_interval_ms for this platform: Use \"\n          \"cooldown_interval_ms = 0\");\n      goto release_and_return;\n#endif\n    }\n  }\n\n  *ret_type_code = kTVMBytes;\n  ret_val->v_handle = result_byte_arr;\n  return err;\n\nrelease_and_return : {\n  tvm_crt_error_t release_err =\n      TVMPlatformMemoryFree((void*)result_byte_arr->data, result_byte_dev);\n  if (release_err != kTvmErrorNoError) {\n    release_err = TVMPlatformMemoryFree((void*)result_byte_arr, result_byte_dev);\n  }\n\n  if (err == kTvmErrorNoError && release_err != kTvmErrorNoError) {\n    err = release_err;\n  }\n}\n  return err;\n}\n\n// Default implementation, overridden by the platform runtime.\n__attribute__((weak)) tvm_crt_error_t TVMPlatformGenerateRandom(uint8_t* buffer, size_t num_bytes) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\n// Default implementation, overridden by the platform runtime.\n__attribute__((weak)) tvm_crt_error_t TVMPlatformBeforeMeasurement() { return kTvmErrorNoError; }\n\n// Default implementation, overridden by the platform runtime.\n__attribute__((weak)) tvm_crt_error_t TVMPlatformAfterMeasurement() { return kTvmErrorNoError; }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/common/func_registry.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file tvm/runtime/crt/func_registry.c\n * \\brief Defines implementations of generic string-based function lookup structs\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <tvm/runtime/crt/func_registry.h>\n\n/*!\n * \\brief strcmp against the next string in the registry, and return the end.\n *\n * Regardless of return value, after calling this function, cursor's value will be modified to\n * point at the \\0 at the end of the string it currently points to.\n *\n * \\param cursor Pointer to cursor to first string to compare.\n * \\param name Pointer to reference string.\n * \\return 0 if the string pointed to by cursor == name; non-zero otherwise.\n */\nint strcmp_cursor(const char** cursor, const char* name) {\n  int return_value = 0;\n  while (return_value == 0) {\n    char c = **cursor;\n    char n = *name;\n    return_value = ((int)c) - ((int)n);\n\n    if (n == 0 || c == 0) {\n      break;\n    }\n\n    name++;\n    (*cursor)++;\n  }\n\n  while (**cursor != 0) {\n    (*cursor)++;\n  }\n\n  return return_value;\n}\n\nuint16_t TVMFuncRegistry_GetNumFuncs(const TVMFuncRegistry* reg) {\n  uint16_t num_funcs;\n  memcpy(&num_funcs, reg->names, sizeof(num_funcs));\n  return num_funcs;\n}\n\nint TVMFuncRegistry_SetNumFuncs(const TVMFuncRegistry* reg, const uint16_t num_funcs) {\n  memcpy((char*)reg->names, &num_funcs, sizeof(num_funcs));\n  return 0;\n}\n\nconst char* TVMFuncRegistry_Get0thFunctionName(const TVMFuncRegistry* reg) {\n  // NOTE: first function name starts at index 2 to skip num_funcs.\n  return (reg->names + sizeof(uint16_t));\n}\n\ntvm_crt_error_t TVMFuncRegistry_Lookup(const TVMFuncRegistry* reg, const char* name,\n                                       tvm_function_index_t* function_index) {\n  tvm_function_index_t idx;\n  const char* reg_name_ptr = TVMFuncRegistry_Get0thFunctionName(reg);\n\n  idx = 0;\n  for (; *reg_name_ptr != '\\0'; reg_name_ptr++) {\n    if (!strcmp_cursor(&reg_name_ptr, name)) {\n      *function_index = idx;\n      return kTvmErrorNoError;\n    }\n\n    idx++;\n  }\n\n  return kTvmErrorFunctionNameNotFound;\n}\n\ntvm_crt_error_t TVMFuncRegistry_GetByIndex(const TVMFuncRegistry* reg,\n                                           tvm_function_index_t function_index,\n                                           TVMBackendPackedCFunc* out_func) {\n  uint16_t num_funcs;\n\n  num_funcs = TVMFuncRegistry_GetNumFuncs(reg);\n  if (function_index >= num_funcs) {\n    return kTvmErrorFunctionIndexInvalid;\n  }\n\n  *out_func = reg->funcs[function_index];\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMMutableFuncRegistry_Create(TVMMutableFuncRegistry* reg, uint8_t* buffer,\n                                              size_t buffer_size_bytes) {\n  if (buffer_size_bytes < kTvmAverageFuncEntrySizeBytes) {\n    return kTvmErrorBufferTooSmall;\n  }\n\n  reg->registry.names = (const char*)buffer;\n  buffer[0] = 0;  // number of functions present in buffer.\n  buffer[1] = 0;  // note that we combine the first two elements to form a 16-bit function index.\n  buffer[2] = 0;  // end of names list marker.\n\n  // compute a guess of the average size of one entry:\n  //  - assume average function name is around ~10 bytes\n  //  - 1 byte for \\0\n  //  - size of 1 function pointer\n  reg->max_functions = buffer_size_bytes / kTvmAverageFuncEntrySizeBytes;\n  reg->registry.funcs =\n      (TVMBackendPackedCFunc*)(buffer + buffer_size_bytes - reg->max_functions * sizeof(void*));\n\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t TVMMutableFuncRegistry_Set(TVMMutableFuncRegistry* reg, const char* name,\n                                           TVMBackendPackedCFunc func, int override) {\n  size_t idx;\n  char* reg_name_ptr = (char*)TVMFuncRegistry_Get0thFunctionName(&(reg->registry));\n\n  idx = 0;\n  // NOTE: safe to discard const qualifier here, since reg->registry.names was set from\n  // TVMMutableFuncRegistry_Create above.\n  for (; *reg_name_ptr != 0; reg_name_ptr++) {\n    if (!strcmp_cursor((const char**)&reg_name_ptr, name)) {\n      if (override == 0) {\n        return kTvmErrorFunctionAlreadyDefined;\n      }\n      ((TVMBackendPackedCFunc*)reg->registry.funcs)[idx] = func;\n      return kTvmErrorNoError;\n    }\n\n    idx++;\n  }\n\n  if (reg_name_ptr > ((const char*)reg->registry.funcs)) {\n    return kTvmErrorFunctionRegistryFull;\n  }\n\n  size_t name_len = strlen(name);\n  size_t names_bytes_remaining = ((const char*)reg->registry.funcs) - reg_name_ptr;\n  if (idx >= reg->max_functions || name_len + 1 > names_bytes_remaining) {\n    return kTvmErrorFunctionRegistryFull;\n  }\n\n  memcpy(reg_name_ptr, name, name_len + 1);\n  reg_name_ptr += name_len + 1;\n  *reg_name_ptr = 0;\n  ((TVMBackendPackedCFunc*)reg->registry.funcs)[idx] = func;\n\n  uint16_t num_funcs;\n  // increment num_funcs.\n  num_funcs = TVMFuncRegistry_GetNumFuncs(&(reg->registry)) + 1;\n  TVMFuncRegistry_SetNumFuncs(&(reg->registry), num_funcs);\n\n  return kTvmErrorNoError;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/common/ndarray.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file ndarray.c\n * \\brief NDArray container infratructure.\n */\n\n#include <tvm/runtime/crt/internal/common/ndarray.h>\n#include <tvm/runtime/crt/page_allocator.h>\n#include <tvm/runtime/crt/platform.h>\n\n#include \"crt_config.h\"\n\nstatic int Create(int32_t ndim, const tvm_index_t* shape, DLDataType dtype, DLDevice dev,\n                  TVMNDArray* array) {\n  memset(array, 0, sizeof(TVMNDArray));\n  array->dl_tensor.ndim = ndim;\n  tvm_crt_error_t err;\n  DLDevice dldev = {kDLCPU, 0};\n  err = TVMPlatformMemoryAllocate(sizeof(int64_t) * ndim, dldev, (void*)&array->dl_tensor.shape);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n  memcpy(array->dl_tensor.shape, shape, sizeof(int64_t) * ndim);\n  array->dl_tensor.dtype = dtype;\n  array->dl_tensor.device = dev;\n  array->dl_tensor.data = 0;\n  return 0;\n}\n\nint64_t TVMNDArray_DataSizeBytes(TVMNDArray* array) {\n  int64_t num_elems = 1;\n  int32_t idx;\n  for (idx = 0; idx < array->dl_tensor.ndim; ++idx) {\n    num_elems *= array->dl_tensor.shape[idx];\n  }\n  return (num_elems * array->dl_tensor.dtype.bits + 7) / 8;\n}\n\nint TVMNDArray_Empty(int32_t ndim, const tvm_index_t* shape, DLDataType dtype, DLDevice dev,\n                     TVMNDArray* array) {\n  int status = Create(ndim, shape, dtype, dev, array);\n  if (status != 0) {\n    return status;\n  }\n  int total_elem_bytes = TVMNDArray_DataSizeBytes(array);\n  array->dl_tensor.data =\n      TVMBackendAllocWorkspace(kDLCPU, 0, total_elem_bytes, dtype.code, dtype.bits);\n  memset(array->dl_tensor.data, 0, total_elem_bytes);\n  return 0;\n}\n\nint TVMNDArray_Load(TVMNDArray* ret, const char** strm) {\n  int32_t status = 0;\n  uint64_t header, reserved;\n  memcpy(&header, *strm, sizeof(header));\n  *strm += sizeof(header);\n  if (header != kTVMNDArrayMagic) {\n    fprintf(stderr, \"Invalid DLTensor file format\\n\");\n    status = -1;\n  }\n  memcpy(&reserved, *strm, sizeof(reserved));\n  *strm += sizeof(reserved);\n  DLDevice dev;\n  int ndim;  // sizeof ndim should match dlpack\n  DLDataType dtype;\n  memcpy(&dev, *strm, sizeof(dev));\n  *strm += sizeof(dev);\n  memcpy(&ndim, *strm, sizeof(ndim));\n  *strm += sizeof(ndim);\n  memcpy(&dtype, *strm, sizeof(dtype));\n  *strm += sizeof(dtype);\n  if ((ndim < 0) || (ndim > TVM_CRT_MAX_NDIM)) {\n    fprintf(stderr, \"Invalid ndim=%d: expected to be 0 ~ %d.\\n\", ndim, TVM_CRT_MAX_NDIM);\n    status = -1;\n  }\n  if (dev.device_type != kDLCPU) {\n    fprintf(stderr, \"Invalid DLTensor device: can only save as CPU tensor\\n\");\n    status = -1;\n  }\n  int64_t shape[TVM_CRT_MAX_NDIM] = {0};\n  int32_t idx;\n  if (ndim != 0) {\n    for (idx = 0; idx < ndim; idx++) {\n      memcpy(&shape[idx], *strm, sizeof(int64_t));\n      *strm += sizeof(shape[idx]);\n    }\n  }\n  status = TVMNDArray_Empty(ndim, shape, dtype, dev, ret);\n  if (status != 0) {\n    return status;\n  }\n  int64_t num_elems = 1;\n  int elem_bytes = (ret->dl_tensor.dtype.bits + 7) / 8;\n  for (idx = 0; idx < ret->dl_tensor.ndim; ++idx) {\n    num_elems *= ret->dl_tensor.shape[idx];\n  }\n  int64_t data_byte_size;\n  memcpy(&data_byte_size, *strm, sizeof(data_byte_size));\n  *strm += sizeof(data_byte_size);\n  if (!(data_byte_size == num_elems * elem_bytes)) {\n    fprintf(stderr,\n            \"invalid DLTensor file format: data_byte_size=%d, \"\n            \"while num_elems*elem_bytes=%d\\n\",\n            (int)data_byte_size, (int)(num_elems * elem_bytes));  // NOLINT(*)\n    status = -1;\n  }\n  memcpy(ret->dl_tensor.data, *strm, data_byte_size);\n  *strm += data_byte_size;\n\n  return status;\n}\n\nint TVMNDArray_CreateView(TVMNDArray* arr, const tvm_index_t* shape, int32_t ndim, DLDataType dtype,\n                          TVMNDArray* array_view) {\n  int status = Create(ndim, shape, dtype, arr->dl_tensor.device, array_view);\n  if (status != 0) {\n    return status;\n  }\n  array_view->dl_tensor.data = arr->dl_tensor.data;\n  return 0;\n}\n\nint TVMNDArray_RandomFill(TVMNDArray* arr) {\n  int64_t num_bytes = TVMNDArray_DataSizeBytes(arr);\n  if (num_bytes < 0 || num_bytes > SIZE_MAX) {\n    return kTvmErrorFunctionCallInvalidArg;\n  }\n\n  return TVMPlatformGenerateRandom(arr->dl_tensor.data, (size_t)num_bytes);\n}\n\nvoid TVMNDArray_IncrementReference(TVMNDArray* arr) { arr->reference_count++; }\n\nuint32_t TVMNDArray_DecrementReference(TVMNDArray* arr) {\n  if (arr->reference_count > 0) {\n    arr->reference_count--;\n  }\n\n  return arr->reference_count;\n}\n\nint TVMNDArray_Release(TVMNDArray* arr) {\n  tvm_crt_error_t err;\n  DLDevice dev = {kDLCPU, 0};\n\n  if (TVMNDArray_DecrementReference(arr) > 0) {\n    return 0;\n  }\n\n  err = TVMPlatformMemoryFree(arr->dl_tensor.data, dev);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  arr->dl_tensor.data = NULL;\n\n  err = TVMPlatformMemoryFree(arr->dl_tensor.shape, dev);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  arr->dl_tensor.shape = NULL;\n\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/common/packed_func.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file src/runtime/crt/common/packed_func.c\n * \\brief PackedFunc implementation.\n */\n#include <stdio.h>\n#include <string.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/packed_func.h>\n\nDLDataType String2DLDataType(const char* s) {\n  DLDataType t;\n  // handle None type\n  if (strlen(s) == 0) {\n    t.bits = 0;\n    t.lanes = 0;\n    t.code = kTVMOpaqueHandle;\n    return t;\n  }\n  t.bits = 32;\n  t.lanes = 1;\n  const char* scan;\n  if (!strncmp(s, \"int\", 3)) {\n    t.code = kDLInt;\n    scan = s + 3;\n  } else if (!strncmp(s, \"uint\", 4)) {\n    t.code = kDLUInt;\n    scan = s + 4;\n  } else if (!strncmp(s, \"float\", 5)) {\n    t.code = kDLFloat;\n    scan = s + 5;\n  } else if (!strncmp(s, \"bfloat\", 6)) {\n    t.code = kDLBfloat;\n    scan = s + 6;\n  } else if (!strncmp(s, \"handle\", 6)) {\n    t.code = kTVMOpaqueHandle;\n    t.bits = 64;  // handle uses 64 bit by default.\n    scan = s + 6;\n  } else if (!strcmp(s, \"bool\")) {\n    t.code = kDLUInt;\n    t.bits = 1;\n    t.lanes = 1;\n    return t;\n  } else {\n    scan = s;\n    fprintf(stderr, \"unknown type %s\\n\", s);\n  }\n  char* xdelim;\n  uint8_t bits = (uint8_t)(strtoul(scan, &xdelim, 10));\n  if (bits != 0) t.bits = bits;\n  char* endpt = xdelim;\n  if (*xdelim == 'x') {\n    t.lanes = (uint16_t)(strtoul(xdelim + 1, &endpt, 10));\n  }\n  if (!(endpt == s + strlen(s))) {\n    fprintf(stderr, \"unknown type %s\\n\", s);\n  }\n  return t;\n}\n\nint TVMPackedFunc_InitGlobalFunc(TVMPackedFunc* pf, const char* name, const TVMArgs* args) {\n  int status = 0;\n\n  pf->Call = &TVMPackedFunc_Call;\n  pf->SetArgs = &TVMPackedFunc_SetArgs;\n\n  status = TVMFuncGetGlobal(name, &pf->fexec);\n  if (status != 0) {\n    return status;\n  }\n\n  snprintf(pf->name, sizeof(pf->name), \"%s\", name);\n  TVMPackedFunc_SetArgs(pf, args);\n  return status;\n}\n\nint TVMPackedFunc_InitModuleFunc(TVMPackedFunc* pf, TVMModuleHandle module, const char* name,\n                                 const TVMArgs* args) {\n  int status = 0;\n\n  pf->Call = &TVMPackedFunc_Call;\n  pf->SetArgs = &TVMPackedFunc_SetArgs;\n\n  status = TVMModGetFunction(module, name, 0, &pf->fexec);\n  if (status != 0) {\n    return status;\n  }\n\n  snprintf(pf->name, sizeof(pf->name), \"%s\", name);\n  TVMPackedFunc_SetArgs(pf, args);\n  return status;\n}\n\nTVMArgs TVMArgs_Create(TVMValue* values, uint32_t* tcodes, uint32_t values_count) {\n  uint32_t idx;\n  TVMArgs args;\n  memset(&args, 0, sizeof(args));\n  for (idx = 0; idx < values_count; idx++) {\n    memcpy(args.values + idx, values + idx, sizeof(TVMValue));\n    args.tcodes[idx] = tcodes[idx];\n  }\n  args.values_count = values_count;\n  return args;\n}\n\nint TVMPackedFunc_Call(TVMPackedFunc* pf) {\n  pf->ret_value.values_count = 1;\n  pf->ret_value.tcodes[0] = kTVMNullptr;\n  return TVMFuncCall(pf->fexec, pf->args.values, pf->args.tcodes, pf->args.values_count,\n                     pf->ret_value.values, pf->ret_value.tcodes);\n}\n\nvoid TVMPackedFunc_SetArgs(TVMPackedFunc* pf, const TVMArgs* args) {\n  memcpy(&(pf->args), args, sizeof(TVMArgs));\n}\n\nTVMPackedFunc* g_fexecs;\nuint32_t g_fexecs_count;\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/contrib/stm32/ai_runtime_api.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ai_runtime_api.c\n * \\brief The runtime API for the TVM generated C code.\n */\n\n// LINT_C_FILE\n\n#include \"ai_runtime_api.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n// =======================================================\n//                    ai_network_t\n// =======================================================\n\ntypedef struct {\n  ai_model_info* info;\n  ai_tensor** inputs;\n  ai_tensor** outputs;\n  ai_ptr activations;\n  const char* error;\n} ai_network_t;\n\n//\n// .nn_models_info section\n//\nextern uintptr_t __models_section_start__;\nextern uintptr_t __models_section_end__;\n\nuint32_t _modelsSection_start = (uint32_t)(&__models_section_start__);\nuint32_t _modelsSection_end = (uint32_t)(&__models_section_end__);\n\n// =======================================================\n//                       Iterator\n// =======================================================\nai_model_iterator ai_model_iterator_begin() {\n  return _modelsSection_start;  // begin()\n}\n\nai_model_iterator ai_model_iterator_end() { return _modelsSection_end; }\n\nai_model_iterator ai_model_iterator_next(ai_model_iterator idx) {\n  return (idx + sizeof(ai_model_info));\n}\n\nai_model_info* ai_model_iterator_value(ai_model_iterator idx) { return (ai_model_info*)idx; }\n\n// =======================================================\n//   ai_create\n// =======================================================\nAI_API_ENTRY ai_status ai_create(ai_model_info* nn, ai_ptr activations, ai_handle* handle) {\n  uint32_t n_inputs = AI_MODEL_n_inputs(nn);\n  uint32_t n_outputs = AI_MODEL_n_outputs(nn);\n\n  ai_status status = AI_STATUS_OK;\n\n  //\n  // Create internal network representation\n  //\n  ai_network_t* network = (ai_network_t*)malloc(sizeof(ai_network_t));\n\n  network->info = nn;\n\n  for (int i = 0; i < n_inputs; i++) {\n    network->inputs = AI_MODEL_inputs(nn);\n  }\n  for (int i = 0; i < n_outputs; i++) {\n    network->outputs = AI_MODEL_outputs(nn);\n  }\n\n  network->activations = activations;\n\n  network->error = NULL;\n\n  const ai_ptr params = nn->ai_get_params();\n  status = nn->ai_create(params, activations);\n  if (status != AI_STATUS_OK) {\n    network->error = TVMGetLastError();\n  }\n\n  //\n  // Setup weights and activations\n  //\n  *handle = network;\n\n  return status;\n}\n\n// =======================================================\n//   ai_destroy\n// =======================================================\nAI_API_ENTRY ai_status ai_destroy(ai_handle handle) {\n  if (handle == NULL) {\n    return AI_STATUS_ERROR;\n  }\n\n  ai_network_t* network = (ai_network_t*)handle;\n\n  free(network);\n\n  return AI_STATUS_OK;\n}\n\n// =======================================================\n//   ai_get_error\n// =======================================================\nAI_API_ENTRY\nconst char* ai_get_error(ai_handle handle) {\n  if (handle == NULL) {\n    return \"Network handle is NULL\";\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  if (network->error == NULL) {\n    return \"\";\n  }\n  return network->error;\n}\n\n// =======================================================\n//   ai_get_input_size\n// =======================================================\nAI_API_ENTRY int32_t ai_get_input_size(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_n_inputs(network->info);\n}\n\n// =======================================================\n//   ai_get_output_size\n// =======================================================\nAI_API_ENTRY int32_t ai_get_output_size(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_n_outputs(network->info);\n}\n\n// =======================================================\n//   ai_get_input\n// =======================================================\nAI_API_ENTRY ai_tensor* ai_get_input(ai_handle handle, int32_t index) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  if (index >= AI_MODEL_n_inputs(network->info)) {\n    network->error = \"Input index out of range\";\n    return NULL;\n  }\n  return (network->inputs)[index];\n}\n\n// =======================================================\n//   ai_get_output\n// =======================================================\nAI_API_ENTRY ai_tensor* ai_get_output(ai_handle handle, int32_t index) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  if (index >= AI_MODEL_n_outputs(network->info)) {\n    network->error = \"Output index out of range\";\n    return NULL;\n  }\n  return (network->outputs)[index];\n}\n\n// =======================================================\n//   ai_run\n// =======================================================\nAI_API_ENTRY ai_status ai_run(ai_handle handle) {\n  if (handle == NULL) {\n    return AI_STATUS_ERROR;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n\n  ai_model_info* nn = network->info;\n\n  uint32_t n_inputs = AI_MODEL_n_inputs(nn);\n  uint32_t n_outputs = AI_MODEL_n_outputs(nn);\n  ai_status status = AI_STATUS_OK;\n\n  //\n  // Check that input tensors have been specified\n  //\n  uint32_t i;\n  for (i = 0; i < n_inputs; i++) {\n    ai_tensor* input_tensor = network->inputs[i];\n    DLTensor* input = &input_tensor->dltensor;\n    if (input->data == NULL) {\n      network->error = \"Network input NULL\";\n      return AI_STATUS_ERROR;\n    }\n  }\n  for (i = 0; i < n_outputs; i++) {\n    ai_tensor* output_tensor = network->outputs[i];\n    DLTensor* output = &output_tensor->dltensor;\n    if (output->data == NULL) {\n      network->error = \"Network output NULL\";\n      return AI_STATUS_ERROR;\n    }\n  }\n\n  status = nn->ai_run(network->inputs, network->outputs);\n\n  if (status != AI_STATUS_OK) {\n    const char* err = TVMGetLastError();\n    network->error = err;\n  }\n\n  return status;\n}\n\n// =======================================================\n//   ai_get_name\n// =======================================================\nconst char* ai_get_name(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_name(network->info);\n}\n\n// =======================================================\n//   ai_get_datetime\n// =======================================================\nconst char* ai_get_datetime(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_datetime(network->info);\n}\n\n// =======================================================\n//   ai_get_revision\n// =======================================================\nconst char* ai_get_revision(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_revision(network->info);\n}\n\n// =======================================================\n//   ai_get_tool_version\n// =======================================================\nconst char* ai_get_tool_version(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_tool_version(network->info);\n}\n\n// =======================================================\n//   ai_get_api_version\n// =======================================================\nconst char* ai_get_api_version(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_api_version(network->info);\n}\n\n// =======================================================\n//   ai_get_node_size\n// =======================================================\nuint32_t ai_get_node_size(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_n_nodes(network->info);\n}\n\n// =======================================================\n//   ai_get_activations_size\n// =======================================================\nuint32_t ai_get_activations_size(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_activations_size(network->info);\n}\n\n// =======================================================\n//   ai_get_params_size\n// =======================================================\nuint32_t ai_get_params_size(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return AI_MODEL_params_size(network->info);\n}\n\n// =======================================================\n//   ai_get_activations\n// =======================================================\nai_ptr ai_get_activations(ai_handle handle) {\n  if (handle == NULL) {\n    return 0;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return network->activations;\n}\n\n// =======================================================\n//   ai_get_params\n// =======================================================\nconst ai_ptr ai_get_params(ai_handle handle) {\n  if (handle == NULL) {\n    return NULL;\n  }\n  ai_network_t* network = (ai_network_t*)handle;\n  return network->info->ai_get_params();\n}\n\n// =======================================================\n//   ai_get_quantization\n// =======================================================\nconst ai_quantization_info* ai_get_quantization(ai_tensor* tensor) {\n  if (tensor == NULL) {\n    return NULL;\n  }\n  return tensor->quant;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/contrib/stm32/ai_runtime_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ai_runtime_api.h\n * \\brief The runtime API for the TVM generated C code.\n */\n\n#ifndef TVM_RUNTIME_CRT_CONTRIB_STM32_AI_RUNTIME_API_H_\n#define TVM_RUNTIME_CRT_CONTRIB_STM32_AI_RUNTIME_API_H_\n\n#include <inttypes.h>\n#include <stddef.h>\n#include <stdint.h>\n\n#include \"dlpack/dlpack.h\"              // From TVM\n#include \"tvm/runtime/c_runtime_api.h\"  // From TVM\n\n//\n// This describes current ai_runtime version\n//\n#define AI_PLATFORM_RUNTIME_MAJOR 1\n#define AI_PLATFORM_RUNTIME_MINOR 0\n#define AI_PLATFORM_RUNTIME_MICRO 0\n\n#define AI_STATIC static\n\n#if defined(_MSC_VER)\n#define AI_INLINE __inline\n#define AI_API_ENTRY __declspec(dllexport)\n#define AI_ALIGNED(x) /* AI_ALIGNED(x) */\n#elif defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__)\n#define AI_INLINE inline\n#define AI_API_ENTRY /* AI_API_ENTRY */\n#define AI_ALIGNED(x) AI_CONCAT(AI_ALIGNED_, x)\n#elif defined(__CC_ARM)\n#define AI_INLINE __inline\n#define AI_API_ENTRY __attribute__((visibility(\"default\")))\n#define AI_ALIGNED(x) __attribute__((aligned(x)))\n/* Keil disallows anonymous union initialization by default */\n#pragma anon_unions\n#elif defined(__GNUC__)\n#define AI_INLINE __inline\n#define AI_API_ENTRY __attribute__((visibility(\"default\")))\n#define AI_ALIGNED(x) __attribute__((aligned(x)))\n#else\n/* Dynamic libraries are not supported by the compiler */\n#define AI_API_ENTRY  /* AI_API_ENTRY */\n#define AI_ALIGNED(x) /* AI_ALIGNED(x) */\n#endif\n\n/*********************************************************/\n\ntypedef void* ai_handle;\n\n#define AI_HANDLE_PTR(ptr_) ((ai_handle)(ptr_))\n#define AI_HANDLE_NULL AI_HANDLE_PTR(NULL)\n\ntypedef uint8_t* ai_ptr;\n\ntypedef enum { AI_STATUS_OK = 0, AI_STATUS_ERROR = 1, AI_STATUS_DELEGATE_ERROR = 2 } ai_status;\n\n// =======================================================\n//                  ai_quantization_info\n//\n//   Parameters for asymmetric quantization across a dimension (i.e\n//   per output channel quantization).\n//   quantized_dimension specifies which dimension the scales and\n//   zero_points correspond to.\n//   For a particular value in quantized_dimension, quantized values\n//   can be converted back to float using:\n//     real_value = scale * (quantized_value - zero_point)\n// =======================================================\n\ntypedef struct {\n  /*!\n   * \\brief The quantization info, if quantized\n   */\n  float* scale;\n  int32_t* zero_point;\n  int32_t dim;\n} ai_quantization_info;\n\n// =======================================================\n//                       ai_tensor\n// =======================================================\n\ntypedef struct {\n  /*!\n   * \\brief The TVM tensor.\n   */\n  DLTensor dltensor;\n  /*!\n   * \\brief The quantization info, if quantized\n   */\n  ai_quantization_info* quant;\n} ai_tensor;\n\n// =======================================================\n//   get_dltensor\n// =======================================================\nAI_STATIC AI_INLINE DLTensor* get_dltensor(ai_tensor* tensor) { return &tensor->dltensor; }\n\n// =======================================================\n//   get_tensor_elts\n// =======================================================\nAI_STATIC AI_INLINE uint32_t get_tensor_elts(const ai_tensor* tensor) {\n  const DLTensor* t = &tensor->dltensor;\n  uint32_t elts = 1;\n  for (int i = 0; i < t->ndim; ++i) {\n    elts *= t->shape[i];\n  }\n  return elts;\n}\n\n// =======================================================\n//   get_tensor_size\n// =======================================================\nAI_STATIC AI_INLINE uint32_t get_tensor_size(const ai_tensor* tensor) {\n  const DLTensor* t = &tensor->dltensor;\n  uint32_t size = 1;\n  for (int i = 0; i < t->ndim; ++i) {\n    size *= t->shape[i];\n  }\n  size *= (t->dtype.bits * t->dtype.lanes + 7) / 8;\n  return size;\n}\n\n// =======================================================\n//                    ai_network_info\n// =======================================================\n\ntypedef struct {\n  const char* name;\n  const char* datetime;\n  const char* revision;\n  const char* tool_version;\n  const char* api_version;\n  uint16_t n_nodes;\n  uint8_t n_inputs;\n  uint8_t n_outputs;\n  uint32_t activations_size;\n  uint32_t params_size;\n  ai_ptr activations;\n  ai_tensor** inputs;\n  ai_tensor** outputs;\n  const ai_ptr (*ai_get_params)(void);\n  ai_status (*ai_create)(const ai_ptr weights, const ai_ptr activations);\n  ai_status (*ai_destroy)();\n  ai_status (*ai_run)(ai_tensor* input[], ai_tensor* output[]);\n} ai_model_info;\n\n#define AI_MODEL_name(x) (x->name)\n#define AI_MODEL_datetime(x) (x->datetime)\n#define AI_MODEL_revision(x) (x->revision)\n#define AI_MODEL_tool_version(x) (x->tool_version)\n#define AI_MODEL_api_version(x) (x->api_version)\n#define AI_MODEL_n_nodes(x) (x->n_nodes)\n#define AI_MODEL_n_inputs(x) (x->n_inputs)\n#define AI_MODEL_n_outputs(x) (x->n_outputs)\n#define AI_MODEL_activations_size(x) (x->activations_size)\n#define AI_MODEL_params_size(x) (x->params_size)\n#define AI_MODEL_inputs(x) (x->inputs)\n#define AI_MODEL_outputs(x) (x->outputs)\n#define AI_MODEL_activations(x) (x->activations)\n\n// =======================================================\n//                         Iterator\n//\n//   Usage:\n//\n//     for (ai_models_iterator it = ai_models_iterator_begin();\n//          it != ai_models_iterator_end();\n//          it = ai_models_iterator_next(it)) {\n//       const char * name = ai_models_iterator_value(it);\n//     }\n//\n// =======================================================\n\ntypedef uint32_t ai_model_iterator;\n\nai_model_iterator ai_model_iterator_begin();\nai_model_iterator ai_model_iterator_next(ai_model_iterator it);\nai_model_iterator ai_model_iterator_end();\nai_model_info* ai_model_iterator_value(ai_model_iterator it);\n\n// =======================================================\n//                    External Interface\n// =======================================================\n\nai_status ai_create(ai_model_info* nn, ai_ptr activations, ai_handle* handle);\n\nai_status ai_destroy(ai_handle handle);\n\nconst char* ai_get_error(ai_handle handle);\n\nint32_t ai_get_input_size(ai_handle handle);\n\nint32_t ai_get_output_size(ai_handle handle);\n\nai_tensor* ai_get_input(ai_handle handle, int32_t index);\n\nai_tensor* ai_get_output(ai_handle handle, int32_t index);\n\nai_status ai_run(ai_handle handle);\n\n//\n// Additional methods\n//\nconst char* ai_get_name(ai_handle handle);\nconst char* ai_get_datetime(ai_handle handle);\nconst char* ai_get_revision(ai_handle handle);\nconst char* ai_get_tool_version(ai_handle handle);\nconst char* ai_get_api_version(ai_handle handle);\n\nuint32_t ai_get_node_size(ai_handle handle);\nuint32_t ai_get_activations_size(ai_handle handle);\nuint32_t ai_get_params_size(ai_handle handle);\n\nai_ptr ai_get_activations(ai_handle handle);\nconst ai_ptr ai_get_params(ai_handle handle);\n\n//\n// Quantization\n//\nconst ai_quantization_info* ai_get_quantization(ai_tensor* tensor);\n\n#endif  // TVM_RUNTIME_CRT_CONTRIB_STM32_AI_RUNTIME_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/contrib/stm32/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt_config.h.template\n * \\brief Template for CRT configuration, to be modified on each target.\n */\n#ifndef TVM_RUNTIME_CRT_CONTRIB_STM32_CRT_CONFIG_H_\n#define TVM_RUNTIME_CRT_CONTRIB_STM32_CRT_CONFIG_H_\n\n#include <tvm/runtime/crt/logging.h>\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n#endif  // TVM_RUNTIME_CRT_CONTRIB_STM32_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/contrib/stm32/runtime.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime.c\n * \\brief A minimal \"C\" runtime support required by the TVM\n *        generated C code. Declared in \"runtime/c_backend_api.h\"\n *        and \"runtime/c_runtime_api.h\"\n */\n\n#include <assert.h>\n#include <malloc.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n\nstatic char* g_last_error = NULL;\n\n// ====================================================\n//   TVMPlatformMemoryAllocate\n// ====================================================\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n#ifdef __arm__\n  *out_ptr = malloc(num_bytes);\n#else  // _x86_\n  *out_ptr = malloc(num_bytes);\n#endif\n  return (*out_ptr == NULL) ? kTvmErrorPlatformNoMemory : kTvmErrorNoError;\n}\n\n// ====================================================\n//   TVMPlatformMemoryFree\n// ====================================================\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n  free(ptr);\n  return kTvmErrorNoError;\n}\n\n// ====================================================\n//   TVMFuncRegisterGlobal\n// ====================================================\nint TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) { return -1; }\n\n// ====================================================\n//   TVMPlatformAbort\n// ====================================================\nvoid __attribute__((noreturn)) TVMPlatformAbort(tvm_crt_error_t code) {\n  for (;;) {\n  }\n}\n\n// ====================================================\n//   TVMLogf\n// ====================================================\nvoid TVMLogf(const char* msg, ...) { return; }\n\n// ====================================================\n//   TVMAPISetLastError\n// ====================================================\nvoid TVMAPISetLastError(const char* msg) {\n  if (g_last_error) {\n    free(g_last_error);\n  }\n  uint32_t nbytes = strlen(msg) + 1;\n  g_last_error = malloc(nbytes);\n  snprintf(g_last_error, nbytes, \"%s\", msg);\n}\n\n// ====================================================\n//   TVMGetLastError\n// ====================================================\nconst char* TVMGetLastError(void) {\n  assert(g_last_error);\n  return g_last_error;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/crt_config-template.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt_config.h.template\n * \\brief Template for CRT configuration, to be modified on each target.\n */\n#ifndef TVM_RUNTIME_CRT_CRT_CONFIG_TEMPLATE_H_\n#define TVM_RUNTIME_CRT_CRT_CONFIG_TEMPLATE_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Support low-level debugging in MISRA-C runtime */\n#define TVM_CRT_DEBUG 0\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 2048\n\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\" */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! \\brief Maximum length of a PackedFunc function name. */\n#define TVM_CRT_MAX_FUNCTION_NAME_LENGTH_BYTES 30\n\n/*! \\brief Enable checks to enforce the stack allocator with a FIFO ordering. Off by default */\n// #define TVM_CRT_STACK_ALLOCATOR_ENABLE_FIFO_CHECK\n\n#endif  // TVM_RUNTIME_CRT_CRT_CONFIG_TEMPLATE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/graph_executor/graph_executor.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file graph_executor.c\n * \\brief implement graph executor in pure C\n */\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/internal/graph_executor/graph_executor.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/module.h>\n#include <tvm/runtime/crt/packed_func.h>\n#include <tvm/runtime/crt/page_allocator.h>\n\n#include \"crt_config.h\"\n\n#ifndef MAX\n#define MAX(a, b) (((a) > (b)) ? (a) : (b))\n#endif  // MAX\n\nuint32_t Shape_Accumulate(int64_t* shape, uint32_t ndim) {\n  int64_t accum = 1;\n  uint32_t idx;\n  for (idx = 0; idx < ndim; idx++) {\n    if (shape[idx] == 0) {\n      break;\n    }\n    accum *= shape[idx];\n  }\n  return accum;\n}\n\nint NodeEntry_Load(TVMGraphExecutorNodeEntry* entry, JSONReader* reader) {\n  int status = 0;\n  reader->BeginArray(reader);\n  if (!(reader->NextArrayItem(reader))) {\n    fprintf(stderr, \"invalid json format: failed to parse `node_id`\\n\");\n    status = -1;\n  }\n  reader->ReadUnsignedInteger(reader, &(entry->node_id));\n  if (!(reader->NextArrayItem(reader))) {\n    fprintf(stderr, \"invalid json format: failed to parse `index`\\n\");\n    status = -1;\n  }\n  reader->ReadUnsignedInteger(reader, &(entry->index));\n  if (reader->NextArrayItem(reader)) {\n    reader->ReadUnsignedInteger(reader, &(entry->version));\n    if (reader->NextArrayItem(reader)) {\n      fprintf(stderr, \"invalid json format: failed to parse `version`\\n\");\n      status = -1;\n    }\n  } else {\n    entry->version = 0;\n  }\n  return status;\n}\n\nvoid TVMGraphExecutorNode_LoadAttrs(TVMGraphExecutorNode* node, JSONReader* reader,\n                                    TVMOpParam* param) {\n  int bitmask = 0;\n  char key[20], value[TVM_CRT_MAX_STRLEN_FUNCTION_NAME];\n  memset(param, 0, sizeof(TVMOpParam));\n  memset(key, 0, sizeof(key));\n  memset(value, 0, sizeof(value));\n  reader->BeginObject(reader);\n  while (reader->NextObjectItem(reader, key, sizeof(key))) {\n    int status = reader->ReadString(reader, value, sizeof(value));\n    if (status != 0) {\n      fprintf(stderr, \"error reading value for key: %s\\n\", key);\n      break;\n    }\n    if (!strcmp(key, \"func_name\")) {\n      snprintf(param->func_name, sizeof(value), \"%s\", value);\n      bitmask |= 1;\n    } else if (!strcmp(key, \"num_inputs\")) {\n      param->num_inputs = strtoul(value, 0, 10);\n      bitmask |= 2;\n    } else if (!strcmp(key, \"num_outputs\")) {\n      param->num_outputs = strtoul(value, 0, 10);\n      bitmask |= 4;\n    } else if (!strcmp(key, \"flatten_data\")) {\n      param->flatten_data = strtoul(value, 0, 10);\n      bitmask |= 8;\n#if TVM_CRT_DEBUG\n    } else {\n      printf(\"do not support key %s\", key);\n#endif  // TVM_CRT_DEBUG\n    }\n  }\n  if (bitmask != (1 | 2 | 4 | 8)) {\n    fprintf(stderr, \"invalid format\\n\");\n  }\n}\n\nint TVMGraphExecutorNode_Load(TVMGraphExecutorNode* node, JSONReader* reader) {\n  int status = 0;\n  reader->BeginObject(reader);\n  int bitmask = 0;\n  char key[20];\n  while (reader->NextObjectItem(reader, key, sizeof(key))) {\n    if (!strcmp(key, \"op\")) {\n      status = reader->ReadString(reader, node->op_type, sizeof(node->op_type));\n      if (status != 0) {\n        fprintf(stderr, \"error reading op\\n\");\n        break;\n      }\n      bitmask |= 1;\n    } else if (!strcmp(key, \"name\")) {\n      status = reader->ReadString(reader, node->name, sizeof(node->name));\n      if (status != 0) {\n        fprintf(stderr, \"error reading name\\n\");\n        break;\n      }\n      bitmask |= 2;\n    } else if (!strcmp(key, \"inputs\")) {\n      size_t count = 0;\n      reader->BeginArray(reader);\n      size_t num_inputs = 0;\n      if (reader->ArrayLength(reader, &num_inputs) != 0) {\n        fprintf(stderr, \"error determining inputs array length\\n\");\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(\n          sizeof(TVMGraphExecutorNodeEntry) * num_inputs, dev, (void**)&node->inputs);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        return -1;\n      }\n      while (reader->NextArrayItem(reader)) {\n        if (count == num_inputs) {\n          fprintf(stderr, \"too many array elements\\n\");\n          return -1;\n        }\n\n        TVMGraphExecutorNodeEntry* inputs = node->inputs + count;\n        reader->BeginArray(reader);\n        if (!reader->NextArrayItem(reader)) {\n          fprintf(stderr, \"invalid json format\\n\");\n          status = -1;\n          break;\n        }\n        reader->ReadUnsignedInteger(reader, &(inputs->node_id));\n        if (!reader->NextArrayItem(reader)) {\n          fprintf(stderr, \"invalid json format\\n\");\n          status = -1;\n          break;\n        }\n        reader->ReadUnsignedInteger(reader, &(inputs->index));\n        if (reader->NextArrayItem(reader)) {\n          reader->ReadUnsignedInteger(reader, &(inputs->version));\n          if (reader->NextArrayItem(reader)) {\n            fprintf(stderr, \"invalid json format\\n\");\n            status = -1;\n            break;\n          }\n        } else {\n          inputs->version = 0;\n        }\n        count++;\n      }\n      node->inputs_count = count;\n      bitmask |= 4;\n    } else if (!strcmp(key, \"attr\") || !strcmp(key, \"attrs\")) {\n      TVMOpParam param;\n\n      TVMGraphExecutorNode_LoadAttrs(node, reader, &param);\n      memcpy(&node->param, &param, sizeof(param));\n    } else if (!strcmp(key, \"control_deps\")) {\n      fprintf(stderr, \"do not support key %s\", key);\n      status = -1;\n    } else {\n      fprintf(stderr, \"do not support key %s\", key);\n      status = -1;\n    }\n    if (status != 0) {\n      break;\n    }\n  }\n  if (bitmask != (1 | 2 | 4)) {\n    fprintf(stderr, \"invalid format\\n\");\n    status = -1;\n  }\n  return status;\n}\n\nTVMGraphExecutorNode TVMGraphExecutorNodeCreate() {\n  TVMGraphExecutorNode node;\n  memset(&node, 0, sizeof(TVMGraphExecutorNode));\n  node.LoadAttrs = TVMGraphExecutorNode_LoadAttrs;\n  node.Load = TVMGraphExecutorNode_Load;\n  return node;\n}\n\nint TVMGraphExecutorNodeRelease(TVMGraphExecutorNode* node) {\n  if (!node) {\n    return 0;\n  }\n  if (node->inputs) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(node->inputs, dev);\n    node->inputs = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n\n  return 0;\n}\n\nint TVMGraphExecutorGraphAttr_Load(TVMGraphExecutorGraphAttr* attr, JSONReader* reader) {\n  int status = 0;\n  int bitmask = 0;\n  char key[16], type[16];\n  uint32_t storage_id_count = 0;\n  uint32_t dltype_count = 0;\n  uint32_t shape_count = 0;\n  uint32_t device_index_count = 0;\n  reader->BeginObject(reader);\n  while (reader->NextObjectItem(reader, key, sizeof(key))) {\n    if (!strcmp(key, \"dltype\")) {\n      reader->BeginArray(reader);\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      status = reader->ReadString(reader, type, sizeof(type));\n      if (status != 0) {\n        fprintf(stderr, \"error reading dltype type\\n\");\n        break;\n      }\n      if (strcmp(type, \"list_str\")) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_str length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(TVM_CRT_MAX_STRLEN_DLTYPE * num_items, dev,\n                                                      (void**)&attr->dltype);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        return -1;\n      }\n      dltype_count = 0;\n      while (reader->NextArrayItem(reader)) {\n        if (dltype_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        status = reader->ReadString(reader, attr->dltype + dltype_count * TVM_CRT_MAX_STRLEN_DLTYPE,\n                                    TVM_CRT_MAX_STRLEN_DLTYPE);\n        if (status != 0) {\n          fprintf(stderr, \"error reading dltype array item\");\n          break;\n        }\n        dltype_count++;\n      }\n      attr->dltype_count = dltype_count;\n\n      if (reader->NextArrayItem(reader)) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      bitmask |= 1;\n    } else if (!strcmp(key, \"storage_id\")) {\n      reader->BeginArray(reader);\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      status = reader->ReadString(reader, type, sizeof(type));\n      if (status != 0) {\n        fprintf(stderr, \"error reading device_index array item\");\n      }\n      if (strcmp(type, \"list_int\")) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_str length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err =\n          TVMPlatformMemoryAllocate(sizeof(uint32_t) * num_items, dev, (void**)&attr->storage_id);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        return -1;\n      }\n      storage_id_count = 0;\n      while (reader->NextArrayItem(reader)) {\n        if (storage_id_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        reader->ReadUnsignedInteger(reader, &(attr->storage_id[storage_id_count]));\n        storage_id_count++;\n      }\n      if (reader->NextArrayItem(reader)) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      bitmask |= 2;\n    } else if (!strcmp(key, \"shape\")) {\n      reader->BeginArray(reader);\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      status = reader->ReadString(reader, type, sizeof(type));\n      if (status != 0) {\n        fprintf(stderr, \"error reading shape array item\\n\");\n        break;\n      }\n      if (strcmp(type, \"list_shape\")) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_str length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(\n          sizeof(int64_t) * TVM_CRT_MAX_NDIM * num_items, dev, (void**)&attr->shape);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      err = TVMPlatformMemoryAllocate(sizeof(uint32_t) * num_items, dev, (void**)&attr->ndim);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      shape_count = 0;\n      while (reader->NextArrayItem(reader)) {\n        if (shape_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        reader->BeginArray(reader);\n        int64_t* attr_shape_ptr = attr->shape + shape_count * TVM_CRT_MAX_NDIM;\n        reader->ReadInteger(reader, attr_shape_ptr + 0);\n        uint32_t ndim = 1;\n        if (reader->NextArrayItem(reader)) {\n          for (ndim = 1; ndim < TVM_CRT_MAX_NDIM; ndim++) {\n            if (reader->NextArrayItem(reader)) {\n              reader->ReadInteger(reader, attr_shape_ptr + ndim);\n            } else {\n              break;\n            }\n          }\n          if (ndim == TVM_CRT_MAX_NDIM) {\n            reader->NextArrayItem(reader);\n          }\n        }\n        attr->ndim[shape_count] = ndim;\n        shape_count++;\n      }\n      attr->shape_count = shape_count;\n      if (reader->NextArrayItem(reader)) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      bitmask |= 4;\n    } else if (!strcmp(key, \"device_index\")) {\n      reader->BeginArray(reader);\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      status = reader->ReadString(reader, type, sizeof(type));\n      if (status != 0) {\n        fprintf(stderr, \"error reading device_index array item\");\n        break;\n      }\n      if (strcmp(type, \"list_int\")) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_int length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err =\n          TVMPlatformMemoryAllocate(sizeof(uint32_t) * num_items, dev, (void**)&attr->device_index);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      device_index_count = 0;\n      while (reader->NextArrayItem(reader)) {\n        if (device_index_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        reader->ReadUnsignedInteger(reader, &(attr->device_index[device_index_count]));\n        device_index_count++;\n      }\n      if (reader->NextArrayItem(reader)) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n    } else {\n      reader->BeginArray(reader);\n      if (!(reader->NextArrayItem(reader))) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n      reader->ReadString(reader, type, sizeof(type));\n      if (!strcmp(type, \"list_int\")) {\n        if (!(reader->NextArrayItem(reader))) {\n          fprintf(stderr, \"Invalid json format\\n\");\n          status = -1;\n          break;\n        }\n        uint32_t temp_count = 0;\n        reader->BeginArray(reader);\n        while (reader->NextArrayItem(reader)) {\n          uint32_t temp;\n          reader->ReadUnsignedInteger(reader, &temp);\n          temp_count++;\n        }\n      } else if (!strcmp(type, \"size_t\")) {\n        if (!(reader->NextArrayItem(reader))) {\n          fprintf(stderr, \"Invalid json format\\n\");\n          status = -1;\n          break;\n        }\n        uint32_t temp;\n        reader->ReadUnsignedInteger(reader, &temp);\n      } else {\n        fprintf(stderr, \"cannot skip graph attr %s\", key);\n        status = -1;\n        break;\n      }\n      if (reader->NextArrayItem(reader)) {\n        fprintf(stderr, \"Invalid json format\\n\");\n        status = -1;\n        break;\n      }\n    }\n  }\n  if (bitmask != (1 | 2 | 4)) {\n    fprintf(stderr, \"invalid format\\n\");\n    status = -1;\n  }\n  return status;\n}\n\nint TVMGraphExecutorGraphAttr_Release(TVMGraphExecutorGraphAttr* attr) {\n  if (!attr) {\n    return 0;\n  }\n  if (attr->storage_id) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(attr->storage_id, dev);\n    attr->storage_id = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n  if (attr->device_index) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(attr->device_index, dev);\n    attr->device_index = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n  if (attr->dltype) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(attr->dltype, dev);\n    attr->dltype = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n  if (attr->shape) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(attr->shape, dev);\n    attr->shape = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n  if (attr->ndim) {\n    DLDevice dev = {kDLCPU, 0};\n    tvm_crt_error_t err = TVMPlatformMemoryFree(attr->ndim, dev);\n    attr->ndim = 0;\n    if (err != kTvmErrorNoError) {\n      return -1;\n    }\n  }\n\n  return 0;\n}\n\nint TVMGraphExecutor_Load(TVMGraphExecutor* executor, JSONReader* reader) {\n  int status = 0;\n  reader->BeginObject(reader);\n  int bitmask = 0;\n  char key[20];\n  while (reader->NextObjectItem(reader, key, sizeof(key))) {\n    if (!strcmp(key, \"nodes\")) {\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_int length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(TVMGraphExecutorNode) * num_items, dev,\n                                                      (void**)&executor->nodes);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      while (reader->NextArrayItem(reader)) {\n        if (executor->nodes_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        TVMGraphExecutorNode* node = executor->nodes + executor->nodes_count;\n        status = TVMGraphExecutorNode_Load(node, reader);\n        if (status != 0) {\n          fprintf(stderr, \"failed to load an element in `nodes` field in graph executor node.\\n\");\n          break;\n#if TVM_CRT_DEBUG\n        } else {\n          printf(\"loading: node (%u) %s loaded.\\n\", executor->nodes_count, node->name);\n#endif  // TVM_CRT_DEBUG\n        }\n        executor->nodes_count++;\n      }\n      bitmask |= 1;\n    } else if (!strcmp(key, \"arg_nodes\")) {\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_int length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(uint32_t) * num_items, dev,\n                                                      (void**)&executor->input_nodes);\n\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      while (reader->NextArrayItem(reader)) {\n        if (executor->input_nodes_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        uint32_t* node = executor->input_nodes + executor->input_nodes_count;\n        reader->ReadUnsignedInteger(reader, node);\n        executor->input_nodes_count++;\n      }\n      bitmask |= 2;\n    } else if (!strcmp(key, \"node_row_ptr\")) {\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_int length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(uint32_t) * num_items, dev,\n                                                      (void**)&executor->node_row_ptr);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      while (reader->NextArrayItem(reader)) {\n        if (executor->node_row_ptr_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        uint32_t count = executor->node_row_ptr_count;\n        uint32_t* node = executor->node_row_ptr + count;\n        reader->ReadUnsignedInteger(reader, node);\n        executor->node_row_ptr_count++;\n      }\n      bitmask |= 4;\n    } else if (!strcmp(key, \"heads\")) {\n      reader->BeginArray(reader);\n      size_t num_items = 0;\n      if (reader->ArrayLength(reader, &num_items) != 0) {\n        fprintf(stderr, \"error determing list_int length\\n\");\n        status = -1;\n        break;\n      }\n      DLDevice dev = {kDLCPU, 0};\n      tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(TVMGraphExecutorNodeEntry) * num_items,\n                                                      dev, (void**)&executor->outputs);\n      if (err != kTvmErrorNoError) {\n        fprintf(stderr, \"memory allocate error: %08x\", err);\n        status = -1;\n        break;\n      }\n      while (reader->NextArrayItem(reader)) {\n        if (executor->outputs_count == num_items) {\n          fprintf(stderr, \"array too big\\n\");\n          status = -1;\n          return status;\n        }\n        TVMGraphExecutorNodeEntry* entry = executor->outputs + executor->outputs_count;\n        status = NodeEntry_Load(entry, reader);\n        if (status != 0) {\n          fprintf(stderr, \"Fail to load an element in `heads` field in graph executor node.\\n\");\n          break;\n        }\n        executor->outputs_count++;\n      }\n      bitmask |= 8;\n    } else if (!strcmp(key, \"attrs\")) {\n      status = TVMGraphExecutorGraphAttr_Load(&(executor->attrs), reader);\n      if (status != 0) {\n        fprintf(stderr, \"Fail to load an element in `heads` field in graph executor node.\\n\");\n        break;\n      }\n      bitmask |= 16;\n    } else if (!strcmp(key, \"metadata\")) {\n      break;\n    } else {\n      fprintf(stderr, \"key %s is not supported\\n\", key);\n      status = -1;\n    }\n    if (status != 0) {\n      break;\n    }\n  }\n  if (!(bitmask == (1 | 2 | 4 | 8 | 16))) {\n    fprintf(stderr, \"invalid format\\n\");\n    status = -1;\n  }\n  return status;\n}\n\nuint32_t TVMGraphExecutor_GetEntryId(TVMGraphExecutor* executor, uint32_t nid, uint32_t index) {\n  return executor->node_row_ptr[nid] + index;\n}\n\n/*!\n * \\brief Get the number of input tensors allocated.\n * \\param executor The graph executor.\n * \\return the number of input tensors allocated.\n */\nint TVMGraphExecutor_GetNumInputs(TVMGraphExecutor* executor) {\n  return executor->input_nodes_count;\n}\n\n/*!\n * \\brief Get the input index given the name of input.\n * \\param executor The graph executor.\n * \\param name The name of the input.\n * \\return The index of input.\n */\nint TVMGraphExecutor_GetInputIndex(TVMGraphExecutor* executor, const char* name) {\n  uint32_t i;\n  int32_t rv = -1;\n  for (i = 0; i < executor->input_nodes_count; ++i) {\n    uint32_t nid = executor->input_nodes[i];\n    if (!strcmp(executor->nodes[nid].name, name)) {\n      rv = i;\n      break;\n    }\n  }\n  CHECK_GE(rv, 0, \"cannot find '%s' among input.\", name);\n  return rv;\n}\n\n/*!\n * \\brief set input to the graph based on name.\n * \\param executor The graph executor.\n * \\param name The name of the input.\n * \\param data_in The input data.\n */\nvoid TVMGraphExecutor_SetInput(TVMGraphExecutor* executor, const char* name, DLTensor* data_in) {\n  uint32_t index = TVMGraphExecutor_GetInputIndex(executor, name);\n  if (index >= executor->input_nodes_count) {\n    fprintf(stderr, \"given index is greater than num of input nodes.\\n\");\n  }\n  uint32_t eid = TVMGraphExecutor_GetEntryId(executor, executor->input_nodes[index], 0);\n  executor->data_entry[eid].dl_tensor.data = data_in->data;\n}\n\n/*!\n * \\brief Load parameters from parameter blob.\n * \\param executor The graph executor.\n * \\param param_blob A binary blob of parameter.\n * \\param param_size The parameter size.\n * \\return The result of this function execution.\n */\nint TVMGraphExecutor_LoadParams(TVMGraphExecutor* executor, const char* param_blob,\n                                const uint32_t param_size) {\n  int status = 0;\n  const char* bptr = param_blob;\n  uint64_t header, reserved;\n  memcpy(&header, bptr, sizeof(header));\n  bptr += sizeof(header);\n  if (header != kTVMNDArrayListMagic) {\n    fprintf(stderr, \"Invalid parameters file format\");\n    status = -1;\n  }\n  memcpy(&reserved, bptr, sizeof(reserved));\n  bptr += sizeof(reserved);\n\n  // read names\n  char* names = NULL;\n  DLDevice dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(\n      TVM_CRT_MAX_STRLEN_PARAM_NAME * executor->nodes_count, dev, (void**)&names);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    status = -1;\n    return status;\n  }\n  memset(names, 0, TVM_CRT_MAX_STRLEN_PARAM_NAME * executor->nodes_count);\n  uint64_t names_count;\n  int idx;\n  memcpy(&names_count, bptr, sizeof(names_count));\n  bptr += sizeof(names_count);\n  for (idx = 0; idx < names_count; idx++) {\n    uint64_t name_length;\n    memcpy(&name_length, bptr, sizeof(name_length));\n    bptr += sizeof(name_length);\n    if (name_length >= TVM_CRT_MAX_STRLEN_PARAM_NAME) {\n      fprintf(stderr, \"Error: function name longer than expected.\\n\");\n      status = -1;\n    }\n    memcpy(names + TVM_CRT_MAX_STRLEN_PARAM_NAME * idx, bptr, name_length);\n    bptr += name_length;\n  }\n\n  // read sizes\n  uint64_t sz;\n  memcpy(&sz, bptr, sizeof(sz));\n  bptr += sizeof(sz);\n  uint32_t size = sz;\n  if (size != names_count) {\n    fprintf(stderr, \"Invalid parameters file format\\n\");\n    status = -1;\n  }\n\n  for (idx = 0; idx < size; idx++) {\n    int32_t in_idx =\n        TVMGraphExecutor_GetInputIndex(executor, names + TVM_CRT_MAX_STRLEN_PARAM_NAME * idx);\n    CHECK_GT(in_idx, 0, \"Found param for non-existent input: %s\\n\",\n             names + TVM_CRT_MAX_STRLEN_PARAM_NAME * idx);\n    uint32_t eid = TVMGraphExecutor_GetEntryId(executor, executor->input_nodes[in_idx], 0);\n    if (!(eid < executor->data_entry_count)) {\n      fprintf(stderr, \"`entry_id`=%d is greater than expected(%d).\\n\", eid,\n              executor->data_entry_count);\n      status = -1;\n    }\n\n    if (executor->data_entry[eid].dl_tensor.shape) {\n      err = TVMPlatformMemoryFree(executor->data_entry[eid].dl_tensor.shape, dev);\n      if (err != kTvmErrorNoError) {\n        status = -1;\n      }\n      executor->data_entry[eid].dl_tensor.shape = 0;\n    }\n    if (executor->data_entry[eid].dl_tensor.data) {\n      err = TVMPlatformMemoryFree(executor->data_entry[eid].dl_tensor.data, dev);\n      if (err != kTvmErrorNoError) {\n        status = -1;\n      }\n      executor->data_entry[eid].dl_tensor.data = 0;\n    }\n    status |= TVMNDArray_Load(&(executor->data_entry[eid]), &bptr);\n#if TVM_CRT_DEBUG\n    TVMNDArray* entry = &(executor->data_entry[eid]);\n    printf(\"loading: param %s loaded, in_idx=%d, eid=%d, ndim=%d, data[0]=%f\\n\",\n           names + TVM_CRT_MAX_STRLEN_PARAM_NAME * idx, in_idx, eid, entry->dl_tensor.ndim,\n           ((float*)entry->dl_tensor.data)[0]);  // NOLINT(*)\n#endif                                           // TVM_CRT_DEBUG\n  }\n\n  // Release memory\n  err = TVMPlatformMemoryFree(names, dev);\n  if (err != kTvmErrorNoError) {\n    status = -1;\n    return status;\n  }\n\n  return status;\n}\n\n/*!\n * \\brief Run all the operations one by one.\n * \\param executor The graph executor.\n */\nvoid TVMGraphExecutor_Run(TVMGraphExecutor* executor) {\n  // setup the array and requirements.\n  uint32_t idx;\n  for (idx = 0; idx < executor->op_execs_count; ++idx) {\n    if (executor->op_execs[idx].fexec) {\n#if TVM_CRT_DEBUG\n      printf(\"calling: %s (%d)\\n\", executor->op_execs[idx].name, idx);\n#endif  // TVM_CRT_DEBUG\n      executor->op_execs[idx].Call(&(executor->op_execs[idx]));\n    }\n  }\n}\n\n/*!\n * \\brief Get the number of output tensors allocated.\n * \\param executor The graph executor.\n * \\return the number of output tensors allocated.\n */\nint TVMGraphExecutor_GetNumOutputs(TVMGraphExecutor* executor) { return executor->outputs_count; }\n\nint TVMGraphExecutor_GetOutput(TVMGraphExecutor* executor, const int32_t idx, DLTensor* out) {\n  int status = 0;\n  uint32_t nid = executor->outputs[idx].node_id;\n  uint32_t index = executor->outputs[idx].index;\n  uint32_t eid = TVMGraphExecutor_GetEntryId(executor, nid, index);\n\n  // copy data section to allocated output tensor\n  int32_t elem_bytes = out->dtype.bits / 8;\n  int64_t size = Shape_Accumulate(out->shape, out->ndim);\n  DLTensor* tensor = &(executor->data_entry[eid].dl_tensor);\n  CHECK(out->ndim == tensor->ndim);\n  CHECK(out->dtype.bits == tensor->dtype.bits);\n  CHECK(Shape_Accumulate(out->shape, out->ndim) == Shape_Accumulate(tensor->shape, tensor->ndim));\n  memcpy(out->data, tensor->data, size * elem_bytes);\n  return status;\n}\n\nint TVMGraphExecutor_SetupStorage(TVMGraphExecutor* executor) {\n  TVMPackedFunc lookup_linked_param;\n  int lookup_linked_param_valid;\n  uint32_t idx;\n\n  {\n    TVMArgs temp_args;\n    temp_args.values[0].v_int64 = 0;\n    temp_args.tcodes[0] = kTVMArgInt;\n    temp_args.values_count = 1;\n    lookup_linked_param_valid =\n        (TVMPackedFunc_InitModuleFunc(&lookup_linked_param, executor->module_handle,\n                                      \"_lookup_linked_param\", &temp_args) == 0);\n  }\n\n  // Grab saved optimization plan from graph.\n  TVMGraphExecutorGraphAttr* attrs = &(executor->attrs);\n  DLDataType* vtype = NULL;\n  DLDevice alloc_dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(DLDataType) * attrs->dltype_count,\n                                                  alloc_dev, (void**)&vtype);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    return -1;\n  }\n  for (idx = 0; idx < attrs->dltype_count; idx++) {\n    vtype[idx] = String2DLDataType(attrs->dltype + idx * TVM_CRT_MAX_STRLEN_DLTYPE);\n  }\n\n  // Size and device type of each storage pool entry.\n  TVMGraphExecutorPoolEntry* pool_entry = NULL;\n  err = TVMPlatformMemoryAllocate(sizeof(TVMGraphExecutorPoolEntry) * executor->nodes_count,\n                                  alloc_dev, (void**)&pool_entry);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    return -1;\n  }\n  memset(pool_entry, 0, sizeof(TVMGraphExecutorPoolEntry) * executor->nodes_count);\n  uint32_t pool_entry_count = 0;\n  // Find the maximum space size.\n  for (idx = 0; idx < attrs->shape_count; idx++) {\n    int storage_id = attrs->storage_id[idx];\n    // Use the fallback device if no device index is available.\n    int device_type = executor->devices[0].device_type;\n    uint32_t size = Shape_Accumulate(attrs->shape + idx * TVM_CRT_MAX_NDIM, attrs->ndim[idx]);\n    DLDataType t = vtype[idx];\n    uint32_t bits = t.bits * t.lanes;\n    size_t bytes = ((bits + 7U) / 8U) * size;\n\n    uint32_t sid = storage_id;\n    if (sid >= pool_entry_count) {\n      pool_entry_count = sid + 1;\n    }\n    pool_entry[sid].entry_id = idx;\n    pool_entry[sid].size = MAX(pool_entry[sid].size, bytes);\n    pool_entry[sid].device_type = device_type;\n  }\n\n  // Allocate the space.\n  err = TVMPlatformMemoryAllocate(sizeof(TVMGraphExecutorStorageEntry) * pool_entry_count,\n                                  alloc_dev, (void**)&executor->storage_pool);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    return -1;\n  }\n  for (idx = 0; idx < pool_entry_count; idx++) {\n    TVMGraphExecutorPoolEntry pit = pool_entry[idx];\n    DLDevice dev = executor->devices[0];\n    uint8_t did_find_linked_param = 0;\n    if (lookup_linked_param_valid) {\n      lookup_linked_param.args.values[0].v_int64 = idx;\n      CHECK_EQ(lookup_linked_param.Call(&lookup_linked_param), 0, \"lookup_linked_param\");\n\n      void* linked_param_data = lookup_linked_param.ret_value.values[0].v_handle;\n      if (linked_param_data != NULL) {\n        executor->storage_pool[executor->storage_pool_count].is_linked_param = 1;\n        DLTensor* tensor = &executor->storage_pool[executor->storage_pool_count].array.dl_tensor;\n        tensor->data = linked_param_data;\n        tensor->device = dev;\n        tensor->ndim = attrs->ndim[pit.entry_id];\n        tensor->shape = attrs->shape + idx * TVM_CRT_MAX_NDIM;\n        tensor->strides = NULL;\n        tensor->byte_offset = 0;\n        did_find_linked_param = 1;\n      }\n    }\n    if (did_find_linked_param == 0) {\n      DLDataType dtype = {kDLFloat, 32, 1};\n      int64_t shape[TVM_CRT_MAX_NDIM] = {\n          0,\n      };\n      shape[0] = (pit.size + 3) / 4;\n      int status = TVMNDArray_Empty(1, shape, dtype, dev,\n                                    &executor->storage_pool[executor->storage_pool_count].array);\n      CHECK_EQ(status, 0, \"fail to create storage_pool with idx=%d\\n\", idx);\n    }\n    executor->storage_pool_count++;\n  }\n\n  // Assign the pooled entries. A unified memory pool is used to simplify\n  // memory assignment for each node entry. The allocated memory on each device\n  // is mapped to this pool.\n  executor->data_entry_count = executor->node_row_ptr[executor->node_row_ptr_count - 1];\n  err = TVMPlatformMemoryAllocate(sizeof(TVMNDArray) * executor->data_entry_count, alloc_dev,\n                                  (void**)&executor->data_entry);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    return -1;\n  }\n  for (idx = 0; idx < executor->data_entry_count; ++idx) {\n    uint32_t storage_id = attrs->storage_id[idx];\n    CHECK(storage_id < executor->storage_pool_count);\n    int status = TVMNDArray_CreateView(&(executor->storage_pool[storage_id].array),\n                                       attrs->shape + idx * TVM_CRT_MAX_NDIM, attrs->ndim[idx],\n                                       vtype[idx], &executor->data_entry[idx]);\n    CHECK_EQ(status, 0, \"fail to create for node with idx=%d, storage_id=%u\\n\", idx, storage_id);\n\n    TVMNDArray_IncrementReference(&executor->data_entry[idx]);\n  }\n\n  // Release memory\n  err = TVMPlatformMemoryFree(vtype, alloc_dev);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory free error: %08x\", err);\n    return err;\n  }\n\n  err = TVMPlatformMemoryFree(pool_entry, alloc_dev);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory free error: %08x\", err);\n    return -1;\n  }\n\n  return 0;\n}\n\nint TVMGraphExecutor_SetupOpExecs(TVMGraphExecutor* executor) {\n  int status = 0;\n  uint32_t nid, idx;\n  executor->op_execs_count = executor->nodes_count;\n  DLDevice dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(TVMPackedFunc) * executor->op_execs_count,\n                                                  dev, (void**)&executor->op_execs);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    status = -1;\n    return status;\n  }\n  for (nid = 0; nid < executor->nodes_count; nid++) {\n    const TVMGraphExecutorNode* inode = executor->nodes + nid;\n    if (strcmp(inode->op_type, \"null\")) {\n      DLTensorPtr args[TVM_CRT_MAX_ARGS];\n      uint32_t args_count = 0;\n      for (idx = 0; idx < inode->inputs_count; idx++) {\n        const TVMGraphExecutorNodeEntry* entry = inode->inputs + idx;\n        uint32_t eid = TVMGraphExecutor_GetEntryId(executor, entry->node_id, entry->index);\n        args[idx] = &(executor->data_entry[eid].dl_tensor);\n        args_count++;\n      }\n      for (idx = 0; idx < inode->param.num_outputs; idx++) {\n        uint32_t eid = TVMGraphExecutor_GetEntryId(executor, nid, idx);\n        args[args_count] = &(executor->data_entry[eid].dl_tensor);\n        args_count++;\n      }\n      if (strcmp(inode->op_type, \"tvm_op\")) {\n        fprintf(stderr, \"Can only take tvm_op as op, but \\\"%s\\\" is found.\\n\", inode->op_type);\n        status = -1;\n        break;\n      }\n      if (args_count >= TVM_CRT_MAX_ARGS) {\n        fprintf(stderr, \"too many arguments: expected less than %d args, but got %d.\\n\",\n                TVM_CRT_MAX_ARGS, args_count);\n        status = -1;\n        break;\n      }\n#if TVM_CRT_DEBUG\n      printf(\"tvm_op: creating %s with node_id=%d\\n\", inode->param.func_name, nid);\n#endif  // TVM_CRT_DEBUG\n      TVMPackedFunc pf;\n      TVMGraphExecutor_CreateTVMOp(executor, &(inode->param), args, args_count, &pf);\n      executor->op_execs[nid] = pf;\n    } else {\n      memset(&executor->op_execs[nid], 0, sizeof(TVMPackedFunc));\n    }\n  }\n  return status;\n}\n\ntypedef struct TVMOpArgs {\n  DLTensor args[TVM_CRT_MAX_ARGS];\n  uint32_t args_count;\n  TVMValue arg_values[TVM_CRT_MAX_ARGS];\n  uint32_t arg_values_count;\n  uint32_t arg_tcodes[TVM_CRT_MAX_ARGS];\n  uint32_t arg_tcodes_count;\n  int64_t shape_data[TVM_CRT_MAX_ARGS];\n  uint32_t shape_data_count;\n} TVMOpArgs;\n\nint32_t TVMGraphExecutor_CreateTVMOp(TVMGraphExecutor* executor, const TVMOpParam* param,\n                                     DLTensorPtr* args, const uint32_t args_count,\n                                     TVMPackedFunc* pf) {\n  int status = 0;\n  uint32_t idx;\n  TVMOpArgs arg_ptr;\n  memset(&arg_ptr, 0, sizeof(TVMOpArgs));\n  arg_ptr.args_count = args_count;\n  if (param->flatten_data) {\n    arg_ptr.shape_data_count = arg_ptr.args_count;\n  }\n  for (idx = 0; idx < arg_ptr.args_count; ++idx) {\n    TVMValue v;\n    memset(&v, 0, sizeof(v));\n    DLTensor* t = &(arg_ptr.args[idx]);\n    /* v.v_handle = &((*args)[idx]); */\n    v.v_handle = args[idx];\n    arg_ptr.arg_values[idx] = v;\n    arg_ptr.arg_values_count++;\n    arg_ptr.arg_tcodes[idx] = kTVMNDArrayHandle;\n    arg_ptr.arg_tcodes_count++;\n    if (param->flatten_data) {\n      arg_ptr.shape_data[idx] = Shape_Accumulate(t->shape, t->ndim);\n      t->ndim = 1;\n      t->shape[0] = arg_ptr.shape_data[idx];\n    }\n  }\n  if (!strcmp(param->func_name, \"__nop\") || !strcmp(param->func_name, \"__copy\")) {\n    fprintf(stderr, \"%s function is not yet supported.\", param->func_name);\n    status = -1;\n  }\n\n  TVMArgs targs = TVMArgs_Create(arg_ptr.arg_values, arg_ptr.arg_tcodes, arg_ptr.arg_values_count);\n  status = TVMPackedFunc_InitModuleFunc(pf, executor->module_handle, param->func_name, &targs);\n\n  return status;\n}\n\n/*!\n * \\brief Initialize the graph executor with graph and device.\n * \\param graph_json The execution graph.\n * \\param module_handle The module containing the compiled functions for the host\n * processor.\n * \\param devs The device of the host and devices where graph nodes will be\n * executed on.\n * \\return 0 on success.\n */\nint TVMGraphExecutor_Init(TVMGraphExecutor* executor, const char* graph_json,\n                          TVMModuleHandle module_handle, const DLDevice* devs) {\n  JSONReader reader;\n  tvm_crt_error_t err = JSONReader_Create(graph_json, &reader);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n\n  TVMGraphExecutor_Load(executor, &reader);\n  err = JSONReader_Release(&reader);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n  executor->module_handle = module_handle;\n  executor->devices[0] = devs[0];\n\n  int status;\n  status = TVMGraphExecutor_SetupStorage(executor);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMGraphExecutor_SetupOpExecs(executor);\n\n  return status;\n}\n\nint TVMGraphExecutor_Create(const char* sym_json, TVMModuleHandle module_handle,\n                            const DLDevice* devs, TVMGraphExecutor** executor) {\n  DLDevice dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(TVMGraphExecutor), dev, (void**)executor);\n  if (err != kTvmErrorNoError) {\n    fprintf(stderr, \"memory allocate error: %08x\", err);\n    return -1;\n  }\n\n  memset(*executor, 0, sizeof(TVMGraphExecutor));\n  // init\n  return TVMGraphExecutor_Init(*executor, sym_json, module_handle, devs);\n}\n\nint TVMGraphExecutor_Release(TVMGraphExecutor** pptr) {\n  int status = 0;\n  int32_t idx;\n  TVMGraphExecutor* executor = (TVMGraphExecutor*)(*pptr);\n  for (idx = 0; idx < executor->nodes_count; ++idx) {\n    status = TVMGraphExecutorNodeRelease(&(executor->nodes[idx]));\n    if (status != 0) {\n      return status;\n    }\n  }\n  DLDevice dev = {kDLCPU, 0};\n  status = TVMPlatformMemoryFree(executor->nodes, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMGraphExecutorGraphAttr_Release(&(executor->attrs));\n  if (status != 0) {\n    return status;\n  }\n  for (idx = 0; idx < executor->storage_pool_count; ++idx) {\n    if (executor->storage_pool[idx].is_linked_param == 0) {\n      status = TVMNDArray_Release(&(executor->storage_pool[idx]).array);\n      if (status != 0) {\n        return status;\n      }\n    }\n  }\n  for (idx = 0; idx < executor->data_entry_count; ++idx) {\n    status = TVMPlatformMemoryFree(executor->data_entry[idx].dl_tensor.shape, dev);\n    if (status != 0) {\n      return status;\n    }\n  }\n  status = TVMPlatformMemoryFree(executor->input_nodes, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(executor->node_row_ptr, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(executor->outputs, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(executor->storage_pool, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(executor->data_entry, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(executor->op_execs, dev);\n  if (status != 0) {\n    return status;\n  }\n  status = TVMPlatformMemoryFree(*pptr, dev);\n  if (status != 0) {\n    return status;\n  }\n\n  if (g_fexecs) {\n    status = TVMPlatformMemoryFree(g_fexecs, dev);\n    g_fexecs = 0;\n    if (status != 0) {\n      return status;\n    }\n  }\n\n  return 0;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/graph_executor/load_json.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file load_json.c\n * \\brief Load graph from JSON file.\n */\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/crt/internal/graph_executor/load_json.h>\n#include <tvm/runtime/crt/page_allocator.h>\n#include <tvm/runtime/crt/platform.h>\n\n// the node entry structure in serialized format\ntypedef struct JSONNodeEntry {\n  uint32_t node_id;\n  uint32_t index;\n  uint32_t version;\n  void (*Load)(struct JSONNodeEntry* entry, JSONReader* reader);\n} JSONNodeEntry;\n\nvoid JSONNodeEntryLoad(JSONNodeEntry* entry, JSONReader* reader) {\n  reader->BeginArray(reader);\n  if (reader->NextArrayItem(reader)) {\n    fprintf(stderr, \"invalid json format\\n\");\n  }\n  reader->ReadUnsignedInteger(reader, &(entry->node_id));\n  if (reader->NextArrayItem(reader)) {\n    fprintf(stderr, \"invalid json format\\n\");\n  }\n  reader->ReadUnsignedInteger(reader, &(entry->index));\n  if (reader->NextArrayItem(reader)) {\n    reader->ReadUnsignedInteger(reader, &(entry->version));\n    if (!reader->NextArrayItem(reader)) {\n      fprintf(stderr, \"invalid json format\\n\");\n    }\n  } else {\n    entry->version = 0;\n  }\n}\n\n// implementation of Seq class\n\nvoid SeqPush(Seq* seq, uint32_t src) {\n  if (seq->size >= seq->allocated) {\n    printf(\"seq too large.\\n\");\n  }\n  seq->data[seq->size] = src;\n  seq->size += 1;\n}\n\nuint32_t* SeqBack(Seq* seq) {\n  if (seq->size >= seq->allocated) {\n    printf(\"seq too large.\\n\");\n  }\n  return seq->data + (seq->size - 1);\n}\n\nvoid SeqPop(Seq* seq) {\n  if (seq->size >= seq->allocated) {\n    printf(\"seq size is too large.\\n\");\n  }\n  if (seq->size == 0) {\n    printf(\"seq size is too small.\\n\");\n  }\n  seq->size -= 1;\n}\n\ntvm_crt_error_t SeqCreate(uint64_t len, Seq** seq) {\n  DLDevice dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryAllocate(sizeof(Seq), dev, (void**)seq);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  memset(*seq, 0, sizeof(Seq));\n  (*seq)->allocated = len;\n\n  err = TVMPlatformMemoryAllocate(sizeof(uint32_t) * len, dev, (void**)&(*seq)->data);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  (*seq)->push_back = SeqPush;\n  (*seq)->back = SeqBack;\n  (*seq)->pop_back = SeqPop;\n  return err;\n}\n\ntvm_crt_error_t SeqRelease(Seq* seq) {\n  DLDevice dev = {kDLCPU, 0};\n  tvm_crt_error_t err = TVMPlatformMemoryFree(seq->data, dev);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  return TVMPlatformMemoryFree(seq, dev);\n}\n\n// implementations of JSONReader\n\n/*!\n * \\brief Takes the next char from the input source.\n * \\return the next character.\n */\nchar JSONReader_NextChar(JSONReader* reader) {\n  char ch = reader->isptr[0];\n  reader->isptr += 1;\n  return ch;\n}\n\n/*!\n * \\brief Returns the next char from the input source.\n * \\return the next character.\n */\nchar JSONReader_PeekNextChar(JSONReader* reader) { return reader->isptr[0]; }\n\n/*!\n * \\brief Read next nonspace character.\n * \\return the next nonspace character.\n */\nchar JSONReader_NextNonSpace(JSONReader* reader) {\n  int ch;\n  do {\n    ch = reader->NextChar(reader);\n    if (ch == '\\n') {\n      ++(reader->line_count_n_);\n    }\n    if (ch == '\\r') {\n      ++(reader->line_count_r_);\n    }\n  } while (isspace(ch));\n  return ch;\n}\n\n/*!\n * \\brief Read just before next nonspace but not read that.\n * \\return the next nonspace character.\n */\nchar JSONReader_PeekNextNonSpace(JSONReader* reader) {\n  int ch;\n  while (1) {\n    ch = reader->PeekNextChar(reader);\n    if (ch == '\\n') {\n      ++(reader->line_count_n_);\n    }\n    if (ch == '\\r') {\n      ++(reader->line_count_r_);\n    }\n    if (!isspace(ch)) break;\n    reader->NextChar(reader);\n  }\n  return ch;\n}\n\n/*!\n * \\brief Parse next JSON string.\n * \\param out_str the output string. NULL to merely consume input and discard it.\n * \\param out_str_size Number of bytes available to write starting from out_str. Includes\n *      terminating \\0.\n * \\throw tvm::Error when next token is not string\n */\nint JSONReader_ReadString(JSONReader* reader, char* out_str, size_t out_str_size) {\n  int status = 0;\n  int ch = reader->NextNonSpace(reader);\n  size_t output_counter = 0;\n  while (output_counter < out_str_size || out_str == NULL) {\n    ch = reader->NextChar(reader);\n    if (ch == '\\\\') {\n      char sch = reader->NextChar(reader);\n      switch (sch) {\n        case 'r':\n          out_str[output_counter++] = '\\r';\n          break;\n        case 'n':\n          out_str[output_counter++] = '\\n';\n          break;\n        case '\\\\':\n          out_str[output_counter++] = '\\\\';\n          break;\n        case 't':\n          out_str[output_counter++] = '\\t';\n          break;\n        case '\\\"':\n          out_str[output_counter++] = '\\\"';\n          break;\n        default:\n          fprintf(stderr, \"unknown string escape %c\\n\", sch);\n          break;\n      }\n    } else {\n      if (ch == '\\\"') {\n        break;\n      }\n      if (out_str != NULL) {\n        out_str[output_counter++] = ch;\n      }\n    }\n    if (output_counter == out_str_size - 1) {\n      fprintf(stderr, \"Error: string size greater than buffer size (%zu).\\n\", out_str_size);\n      break;\n    }\n    if (ch == EOF || ch == '\\r' || ch == '\\n') {\n      fprintf(stderr, \"Error at line %zu, Expect \\'\\\"\\' but reach end of line\\n\",\n              reader->line_count_n_);\n      break;\n    }\n  }\n\n  if (out_str != NULL) {\n    out_str[output_counter] = 0;\n  }\n  return status;\n}\n\nint JSONReader_ReadUnsignedInteger(JSONReader* reader, unsigned int* out_value) {\n  int status = 0;\n  char* endptr;\n  const char* icstr = reader->isptr;\n  unsigned int number = strtol(icstr, &endptr, 10);\n  reader->isptr += endptr - icstr;\n  *out_value = number;\n  return status;\n}\n\nint JSONReader_ReadInteger(JSONReader* reader, int64_t* out_value) {\n  int status = 0;\n  char* endptr;\n  const char* icstr = reader->isptr;\n  int64_t number = strtol(icstr, &endptr, 10);\n  reader->isptr += endptr - icstr;\n  *out_value = number;\n  return status;\n}\n\n/*!\n * \\brief Begin parsing an object.\n * \\code\n *  string key;\n *  // value can be any type that is json serializable.\n *  string value;\n *  reader->BeginObject();\n *  while (reader->NextObjectItem(&key)) {\n *    // do somthing to key value\n *    reader->Read(&value);\n *  }\n * \\endcode\n */\nvoid JSONReader_BeginObject(JSONReader* reader) {\n  int ch = reader->NextNonSpace(reader);\n  if (!(ch == '{')) {\n    fprintf(stderr, \"Error at line %zu, Expect \\'{\\' but got \\'%c\\'\\n\", reader->line_count_n_, ch);\n  }\n  Seq* scope_counter_ = reader->scope_counter_;\n  scope_counter_->push_back(scope_counter_, 0);\n}\n\n/*!\n * \\brief Try to move to next object item.\n *  If this call is successful, user can proceed to call\n *  reader->Read to read in the value.\n * \\param out_key the key to the next object.\n * \\param out_key_size number of bytes available to write at out_key, including terminating \\0.\n * \\return true if the read is successful, false if we are at end of the object.\n */\nuint8_t JSONReader_NextObjectItem(JSONReader* reader, char* out_key, size_t out_key_size) {\n  uint8_t next = 1;\n  Seq* scope_counter_ = reader->scope_counter_;\n  if (scope_counter_->back(scope_counter_)[0] != 0) {\n    int ch = reader->NextNonSpace(reader);\n    if (ch == EOF) {\n      next = 0;\n    } else if (ch == '}') {\n      next = 0;\n    } else {\n      if (ch != ',') {\n        fprintf(stderr, \"Error at line %zu, JSON object expect \\'}\\' or \\',\\' but got \\'%c\\'\\n\",\n                reader->line_count_n_, ch);\n      }\n    }\n  } else {\n    int ch = reader->PeekNextNonSpace(reader);\n    if (ch == '}') {\n      reader->NextChar(reader);\n      next = 0;\n    }\n  }\n  if (!next) {\n    scope_counter_->pop_back(scope_counter_);\n    return 0;\n  } else {\n    scope_counter_->back(scope_counter_)[0] += 1;\n    int err = reader->ReadString(reader, out_key, out_key_size);\n    if (err != 0) {\n      fprintf(stderr, \"error reading key\");\n      return 0;\n    }\n    int ch = reader->NextNonSpace(reader);\n    if (ch != ':') {\n      fprintf(stderr, \"Error at line %zu, Expect \\':\\' but get \\'%c\\'\\n\", reader->line_count_n_,\n              ch);\n    }\n    return 1;\n  }\n}\n\n/*!\n * \\brief Begin parsing an array.\n * \\code\n *  // value can be any type that is json serializable.\n *  string value;\n *  reader->BeginArray();\n *  while (reader->NextArrayItem(&value)) {\n *    // do somthing to value\n *  }\n * \\endcode\n */\nvoid JSONReader_BeginArray(JSONReader* reader) {\n  int ch = reader->NextNonSpace(reader);\n  if (ch != '[') {\n    fprintf(stderr, \"Error at line %zu, Expect \\'[\\' but get \\'%c\\'\\n\", reader->line_count_n_, ch);\n  }\n  Seq* scope_counter_ = reader->scope_counter_;\n  scope_counter_->push_back(scope_counter_, 0);\n}\n\n/*!\n * \\brief Try to read the next element in the array.\n *  If this call is successful, user can proceed to call\n *  reader->Read to read in the value.\n * \\return true if the read is successful, false if we are at end of the array.\n */\nuint8_t JSONReader_NextArrayItem(JSONReader* reader) {\n  uint8_t next = 1;\n  Seq* scope_counter_ = reader->scope_counter_;\n  if (scope_counter_->back(scope_counter_)[0] != 0) {\n    int ch = reader->NextNonSpace(reader);\n    if (ch == EOF) {\n      next = 0;\n    } else if (ch == ']') {\n      next = 0;\n    } else {\n      if (ch != ',') {\n        fprintf(stderr, \"Error at line %zu, JSON object expect \\']\\' or \\',\\' but got \\'%c\\'\\n\",\n                reader->line_count_n_, ch);\n      }\n    }\n  } else {\n    int ch = reader->PeekNextNonSpace(reader);\n    if (ch == ']') {\n      reader->NextChar(reader);\n      next = 0;\n    }\n  }\n  if (!next) {\n    scope_counter_->pop_back(scope_counter_);\n    return 0;\n  } else {\n    scope_counter_->back(scope_counter_)[0] += 1;\n    return 1;\n  }\n}\n\n/*!\n * \\brief Determine the remaining length of the array to read.\n * \\param num_elements Pointer which receives the length.\n * \\return 0 if successful\n */\nint JSONReader_ArrayLength(JSONReader* reader, size_t* num_elements) {\n  int status = 0;\n  char* old_isptr = reader->isptr;\n  size_t old_line_count_r_ = reader->line_count_r_;\n  size_t old_line_count_n_ = reader->line_count_n_;\n  int old_scope_counter_back = *reader->scope_counter_->back(reader->scope_counter_);\n\n  typedef enum { kObject, kArray } item_type_t;\n  Seq* scopes;\n  tvm_crt_error_t err = SeqCreate(10, &scopes);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n  item_type_t json_item_type = kArray;\n  *num_elements = 0;\n  for (;;) {\n    int has_item = 0;\n    if (json_item_type == kArray) {\n      has_item = reader->NextArrayItem(reader);\n      if (scopes->size == 0 && has_item != 0) {\n        (*num_elements)++;\n      }\n    } else if (json_item_type == kObject) {\n      has_item = reader->NextObjectItem(reader, NULL, 0);\n    } else {\n      status = -1;\n      break;\n    }\n\n    if (has_item) {\n      char c = reader->PeekNextNonSpace(reader);\n      if (c == '\"') {\n        reader->ReadString(reader, NULL, 1024);\n      } else if (c == '[') {\n        reader->BeginArray(reader);\n        scopes->push_back(scopes, json_item_type);\n        json_item_type = kArray;\n      } else if (c == '{') {\n        reader->BeginObject(reader);\n        scopes->push_back(scopes, json_item_type);\n        json_item_type = kObject;\n      } else {\n        int64_t val;\n        reader->ReadInteger(reader, &val);\n      }\n    } else {\n      if (scopes->size > 0) {\n        json_item_type = *scopes->back(scopes);\n        scopes->pop_back(scopes);\n      } else {\n        break;\n      }\n    }\n  }\n\n  reader->isptr = old_isptr;\n  reader->line_count_r_ = old_line_count_r_;\n  reader->line_count_n_ = old_line_count_n_;\n  reader->scope_counter_->push_back(reader->scope_counter_, old_scope_counter_back);\n\n  err = SeqRelease(scopes);\n  if (err != kTvmErrorNoError) {\n    return -1;\n  }\n\n  return status;\n}\n\n/*!\n * \\brief Constructor.\n * \\param is the input source.\n */\ntvm_crt_error_t JSONReader_Create(const char* is, JSONReader* reader) {\n  memset(reader, 0, sizeof(JSONReader));\n  tvm_crt_error_t err = SeqCreate(200, &reader->scope_counter_);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n  reader->NextChar = JSONReader_NextChar;\n  reader->PeekNextChar = JSONReader_PeekNextChar;\n  reader->NextNonSpace = JSONReader_NextNonSpace;\n  reader->PeekNextNonSpace = JSONReader_PeekNextNonSpace;\n  reader->ReadString = JSONReader_ReadString;\n  reader->ReadUnsignedInteger = JSONReader_ReadUnsignedInteger;\n  reader->ReadInteger = JSONReader_ReadInteger;\n  reader->BeginArray = JSONReader_BeginArray;\n  reader->BeginObject = JSONReader_BeginObject;\n  reader->NextArrayItem = JSONReader_NextArrayItem;\n  reader->NextObjectItem = JSONReader_NextObjectItem;\n  reader->ArrayLength = JSONReader_ArrayLength;\n\n  DLDevice dev = {kDLCPU, 0};\n  err = TVMPlatformMemoryAllocate(strlen(is) + 1, dev, (void**)&reader->is_);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n\n  memset(reader->is_, 0, strlen(is) + 1);\n  snprintf(reader->is_, strlen(is) + 1, \"%s\", is);\n  reader->isptr = reader->is_;\n  return err;\n}\n\ntvm_crt_error_t JSONReader_Release(JSONReader* reader) {\n  tvm_crt_error_t err = SeqRelease(reader->scope_counter_);\n  if (err != kTvmErrorNoError) {\n    return err;\n  }\n\n  DLDevice dev = {kDLCPU, 0};\n  return TVMPlatformMemoryFree(reader->is_, dev);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/graph_executor_module/graph_executor_module.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file graph_executor_module.c\n * \\brief wrap graph_executor into a TVMModule for use with RPC.\n */\n\n#include <tvm/runtime/crt/func_registry.h>\n#include <tvm/runtime/crt/graph_executor.h>\n#include <tvm/runtime/crt/graph_executor_module.h>\n#include <tvm/runtime/crt/module.h>\n\n#include \"tvm/runtime/crt/internal/graph_executor/graph_executor.h\"\n\ntypedef struct {\n  TVMModule mod;\n  TVMGraphExecutor* executor;\n} GraphExecutorModule;\n\nstatic GraphExecutorModule graph_executor;\n\nint32_t TVMGraphExecutorModule_Create(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                      int* ret_tcodes, void* resource_handle) {\n  if (graph_executor.executor != NULL) {\n    return kTvmErrorExecutorModuleAlreadyCreated;\n  }\n\n  if (nargs != 4) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMStr || tcodes[1] != kTVMModuleHandle || tcodes[2] != kTVMArgInt ||\n      tcodes[3] != kTVMArgInt) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  if (args[2].v_int64 != kDLCPU || args[3].v_int64 != 0) {\n    return kTvmErrorExecutorModuleBadContext;\n  }\n\n  DLDevice dev = {(DLDeviceType)args[2].v_int64, (int)args[3].v_int64};\n  int ret_value =\n      TVMGraphExecutor_Create(args[0].v_str, args[1].v_handle, &dev, &graph_executor.executor);\n  if (ret_value != 0) {\n    return ret_value;\n  }\n\n  TVMModuleHandle out;\n  ret_value = TVMModCreateFromCModule(&graph_executor.mod, &out);\n  if (ret_value != 0) {\n    ret_tcodes[0] = kTVMNullptr;\n    TVMGraphExecutor_Release(&graph_executor.executor);\n    return ret_value;\n  }\n\n  ret_values[0].v_handle = out;\n  ret_tcodes[0] = kTVMModuleHandle;\n  return kTvmErrorNoError;\n}\n\nint32_t TVMGraphExecutorModule_GetInput(TVMValue* args, int* tcodes, int nargs,\n                                        TVMValue* ret_values, int* ret_tcodes,\n                                        void* resource_handle) {\n  if (nargs != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMStr) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  int index = TVMGraphExecutor_GetInputIndex(graph_executor.executor, args[0].v_str);\n  if (index < 0) {\n    return kTvmErrorExecutorModuleNoSuchInput;\n  }\n\n  uint32_t eid = TVMGraphExecutor_GetEntryId(graph_executor.executor,\n                                             graph_executor.executor->input_nodes[index], 0);\n\n  TVMNDArray* array = &graph_executor.executor->data_entry[eid];\n\n  TVMNDArray_IncrementReference(array);\n\n  ret_values[0].v_handle = (void*)(&array->dl_tensor);\n  ret_tcodes[0] = kTVMNDArrayHandle;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_GetInputIndex(TVMValue* args, int* tcodes, int nargs,\n                                             TVMValue* ret_values, int* ret_tcodes,\n                                             void* resource_handle) {\n  int index = TVMGraphExecutor_GetInputIndex(graph_executor.executor, args[0].v_str);\n\n  if (index < 0) {\n    return kTvmErrorExecutorModuleNoSuchInput;\n  }\n\n  ret_values[0].v_int64 = index;\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_GetNumInputs(TVMValue* args, int* tcodes, int nargs,\n                                            TVMValue* ret_values, int* ret_tcodes,\n                                            void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  ret_values[0].v_int64 = TVMGraphExecutor_GetNumInputs();\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_GetNumOutputs(TVMValue* args, int* tcodes, int nargs,\n                                             TVMValue* ret_values, int* ret_tcodes,\n                                             void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  ret_values[0].v_int64 = TVMGraphExecutor_GetNumOutputs(graph_executor.executor);\n  ret_tcodes[0] = kTVMArgInt;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_GetOutput(TVMValue* args, int* tcodes, int nargs,\n                                         TVMValue* ret_values, int* ret_tcodes,\n                                         void* resource_handle) {\n  if (nargs != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMArgInt) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  int output_index = args[0].v_int64;\n  if (output_index < 0 || output_index > TVMGraphExecutor_GetNumOutputs(graph_executor.executor)) {\n    return kTvmErrorExecutorModuleNoSuchInput;\n  }\n\n  uint32_t nid = graph_executor.executor->outputs[output_index].node_id;\n  uint32_t index = graph_executor.executor->outputs[output_index].index;\n  uint32_t eid = TVMGraphExecutor_GetEntryId(graph_executor.executor, nid, index);\n\n  TVMNDArray* array = &graph_executor.executor->data_entry[eid];\n\n  TVMNDArray_IncrementReference(array);\n\n  ret_values[0].v_handle = (void*)(&array->dl_tensor);\n  ret_tcodes[0] = kTVMNDArrayHandle;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_LoadParams(TVMValue* args, int* tcodes, int nargs,\n                                          TVMValue* ret_values, int* ret_tcodes,\n                                          void* resource_handle) {\n  if (nargs != 1) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMBytes) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  ret_tcodes[0] = kTVMNullptr;\n\n  TVMByteArray* arr = (TVMByteArray*)args[0].v_handle;\n  return TVMGraphExecutor_LoadParams(graph_executor.executor, arr->data, arr->size);\n}\n\nint32_t TVMGraphExecutorModule_Run(TVMValue* args, int* tcodes, int nargs, TVMValue* ret_values,\n                                   int* ret_tcodes, void* resource_handle) {\n  if (nargs != 0) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  TVMGraphExecutor_Run(graph_executor.executor);\n\n  ret_tcodes[0] = kTVMNullptr;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_SetInput(TVMValue* args, int* tcodes, int nargs,\n                                        TVMValue* ret_values, int* ret_tcodes,\n                                        void* resource_handle) {\n  if (nargs != 2) {\n    return kTvmErrorFunctionCallNumArguments;\n  }\n\n  if (tcodes[0] != kTVMStr || tcodes[1] != kTVMDLTensorHandle) {\n    return kTvmErrorFunctionCallWrongArgType;\n  }\n\n  TVMGraphExecutor_SetInput(graph_executor.executor, args[0].v_str, (DLTensor*)args[1].v_handle);\n\n  ret_tcodes[0] = kTVMNullptr;\n  return 0;\n}\n\nint32_t TVMGraphExecutorModule_NotImplemented(TVMValue* args, int* tcodes, int nargs,\n                                              TVMValue* ret_values, int* ret_tcodes,\n                                              void* resource_handle) {\n  return kTvmErrorFunctionCallNotImplemented;\n}\n\nstatic const TVMBackendPackedCFunc graph_executor_registry_funcs[] = {\n    &TVMGraphExecutorModule_GetInput,\n    &TVMGraphExecutorModule_GetInputIndex,\n    &TVMGraphExecutorModule_NotImplemented,  // get_input_info\n    &TVMGraphExecutorModule_GetNumInputs,\n    &TVMGraphExecutorModule_GetNumOutputs,\n    &TVMGraphExecutorModule_GetOutput,\n    &TVMGraphExecutorModule_LoadParams,\n    &TVMGraphExecutorModule_Run,\n    &TVMGraphExecutorModule_SetInput,\n    &TVMGraphExecutorModule_NotImplemented,  // share_params\n};\n\nstatic const TVMFuncRegistry graph_executor_registry = {\n    \"\\x08\\0get_input\\0\"\n    \"get_input_index\\0\"\n    \"get_input_info\\0\"\n    \"get_num_inputs\\0\"\n    \"get_num_outputs\\0\"\n    \"get_output\\0\"\n    \"load_params\\0\"\n    \"run\\0\"\n    \"set_input\\0\"\n    \"share_params\\0\",\n    graph_executor_registry_funcs};\n\ntvm_crt_error_t TVMGraphExecutorModule_Register() {\n  graph_executor.mod.registry = &graph_executor_registry;\n  graph_executor.executor = NULL;\n\n  return TVMFuncRegisterGlobal(\"tvm.graph_executor.create\", &TVMGraphExecutorModule_Create, 0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/host/microtvm_api_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport fcntl\nimport os\nimport os.path\nimport pathlib\nimport select\nimport shutil\nimport subprocess\nimport tarfile\nimport time\nimport re\n\nfrom tvm.micro.project_api import server\n\n\nPROJECT_DIR = pathlib.Path(os.path.dirname(__file__) or os.path.getcwd())\n\n\nMODEL_LIBRARY_FORMAT_RELPATH = \"model.tar\"\n\n\nIS_TEMPLATE = not os.path.exists(os.path.join(PROJECT_DIR, MODEL_LIBRARY_FORMAT_RELPATH))\n\n# Used this size to pass most CRT tests in TVM.\nMEMORY_SIZE_BYTES = 2 * 1024 * 1024\n\nMAKEFILE_FILENAME = \"Makefile\"\n\n\nclass Handler(server.ProjectAPIHandler):\n\n    BUILD_TARGET = \"build/main\"\n\n    def __init__(self):\n        super(Handler, self).__init__()\n        self._proc = None\n\n    def server_info_query(self, tvm_version):\n        return server.ServerInfo(\n            platform_name=\"host\",\n            is_template=IS_TEMPLATE,\n            model_library_format_path=\"\"\n            if IS_TEMPLATE\n            else PROJECT_DIR / MODEL_LIBRARY_FORMAT_RELPATH,\n            project_options=[\n                server.ProjectOption(\n                    \"verbose\",\n                    optional=[\"build\"],\n                    type=\"bool\",\n                    default=False,\n                    help=\"Run make with verbose output\",\n                ),\n                server.ProjectOption(\n                    \"memory_size_bytes\",\n                    optional=[\"generate_project\"],\n                    type=\"int\",\n                    default=MEMORY_SIZE_BYTES,\n                    help=\"Sets the value of MEMORY_SIZE_BYTES.\",\n                ),\n            ],\n        )\n\n    # These files and directories will be recursively copied into generated projects from the CRT.\n    CRT_COPY_ITEMS = (\"include\", \"Makefile\", \"src\")\n\n    # The build target given to make\n    BUILD_TARGET = \"build/main\"\n\n    def _populate_makefile(\n        self,\n        makefile_template_path: pathlib.Path,\n        makefile_path: pathlib.Path,\n        memory_size: int,\n    ):\n        \"\"\"Generate Makefile from template.\"\"\"\n        flags = {\n            \"MEMORY_SIZE_BYTES\": str(memory_size),\n        }\n\n        regex = re.compile(r\"([A-Z_]+) := (<[A-Z_]+>)\")\n        with open(makefile_path, \"w\") as makefile_f:\n            with open(makefile_template_path, \"r\") as makefile_template_f:\n                for line in makefile_template_f:\n                    m = regex.match(line)\n                    if m:\n                        var, token = m.groups()\n                        line = line.replace(token, flags[var])\n                    makefile_f.write(line)\n\n    def generate_project(self, model_library_format_path, standalone_crt_dir, project_dir, options):\n        # Make project directory.\n        project_dir.mkdir(parents=True)\n\n        # Copy ourselves to the generated project. TVM may perform further build steps on the generated project\n        # by launching the copy.\n        shutil.copy2(__file__, project_dir / os.path.basename(__file__))\n\n        # Place Model Library Format tarball in the special location, which this script uses to decide\n        # whether it's being invoked in a template or generated project.\n        project_model_library_format_path = project_dir / MODEL_LIBRARY_FORMAT_RELPATH\n        shutil.copy2(model_library_format_path, project_model_library_format_path)\n\n        # Extract Model Library Format tarball.into <project_dir>/model.\n        extract_path = project_dir / project_model_library_format_path.stem\n        with tarfile.TarFile(project_model_library_format_path) as tf:\n            os.makedirs(extract_path)\n            tf.extractall(path=extract_path)\n\n        # Populate CRT.\n        crt_path = project_dir / \"crt\"\n        os.mkdir(crt_path)\n        for item in self.CRT_COPY_ITEMS:\n            src_path = standalone_crt_dir / item\n            dst_path = crt_path / item\n            if os.path.isdir(src_path):\n                shutil.copytree(src_path, dst_path)\n            else:\n                shutil.copy2(src_path, dst_path)\n\n        # Populate Makefile\n        self._populate_makefile(\n            pathlib.Path(__file__).parent / f\"{MAKEFILE_FILENAME}.template\",\n            project_dir / MAKEFILE_FILENAME,\n            options.get(\"memory_size_bytes\", MEMORY_SIZE_BYTES),\n        )\n\n        # Populate crt-config.h\n        crt_config_dir = project_dir / \"crt_config\"\n        crt_config_dir.mkdir()\n        shutil.copy2(\n            os.path.join(os.path.dirname(__file__), \"..\", \"crt_config-template.h\"),\n            os.path.join(crt_config_dir, \"crt_config.h\"),\n        )\n\n        # Populate src/\n        src_dir = os.path.join(project_dir, \"src\")\n        os.mkdir(src_dir)\n        shutil.copy2(\n            os.path.join(os.path.dirname(__file__), \"main.cc\"), os.path.join(src_dir, \"main.cc\")\n        )\n\n    def build(self, options):\n        args = [\"make\"]\n        if options.get(\"verbose\"):\n            args.append(\"VERBOSE=1\")\n\n        args.append(self.BUILD_TARGET)\n\n        subprocess.check_call(args, cwd=PROJECT_DIR)\n\n    def flash(self, options):\n        pass  # Flashing does nothing on host.\n\n    def _set_nonblock(self, fd):\n        flag = fcntl.fcntl(fd, fcntl.F_GETFL)\n        fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)\n        new_flag = fcntl.fcntl(fd, fcntl.F_GETFL)\n        assert (new_flag & os.O_NONBLOCK) != 0, \"Cannot set file descriptor {fd} to non-blocking\"\n\n    def open_transport(self, options):\n        self._proc = subprocess.Popen(\n            [self.BUILD_TARGET], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0\n        )\n        self._set_nonblock(self._proc.stdin.fileno())\n        self._set_nonblock(self._proc.stdout.fileno())\n        return server.TransportTimeouts(\n            session_start_retry_timeout_sec=0,\n            session_start_timeout_sec=0,\n            session_established_timeout_sec=0,\n        )\n\n    def close_transport(self):\n        if self._proc is not None:\n            proc = self._proc\n            self._proc = None\n            proc.terminate()\n            proc.wait()\n\n    def _await_ready(self, rlist, wlist, timeout_sec=None, end_time=None):\n        if timeout_sec is None and end_time is not None:\n            timeout_sec = max(0, end_time - time.monotonic())\n\n        rlist, wlist, xlist = select.select(rlist, wlist, rlist + wlist, timeout_sec)\n        if not rlist and not wlist and not xlist:\n            raise server.IoTimeoutError()\n\n        return True\n\n    def read_transport(self, n, timeout_sec):\n        if self._proc is None:\n            raise server.TransportClosedError()\n\n        fd = self._proc.stdout.fileno()\n        end_time = None if timeout_sec is None else time.monotonic() + timeout_sec\n\n        try:\n            self._await_ready([fd], [], end_time=end_time)\n            to_return = os.read(fd, n)\n        except BrokenPipeError:\n            to_return = 0\n\n        if not to_return:\n            self.disconnect_transport()\n            raise server.TransportClosedError()\n\n        return to_return\n\n    def write_transport(self, data, timeout_sec):\n        if self._proc is None:\n            raise server.TransportClosedError()\n\n        fd = self._proc.stdin.fileno()\n        end_time = None if timeout_sec is None else time.monotonic() + timeout_sec\n\n        data_len = len(data)\n        while data:\n            self._await_ready([], [fd], end_time=end_time)\n            try:\n                num_written = os.write(fd, data)\n            except BrokenPipeError:\n                num_written = 0\n\n            if not num_written:\n                self.disconnect_transport()\n                raise server.TransportClosedError()\n\n            data = data[num_written:]\n\n\nif __name__ == \"__main__\":\n    server.main(Handler())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/include/tvm/runtime/crt/internal/common/func_registry.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file tvm/runtime/crt/include/tvm/runtime/crt/internal/common/func_registry.h\n * \\brief Abstract device memory management API\n */\n#ifndef TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_FUNC_REGISTRY_H_\n#define TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_FUNC_REGISTRY_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nint strcmp_cursor(const char** cursor, const char* name);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_FUNC_REGISTRY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/include/tvm/runtime/crt/internal/common/ndarray.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/include/tvm/runtime/crt/internal/common/ndarray.h\n * \\brief Abstract device memory management API\n */\n#ifndef TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_NDARRAY_H_\n#define TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_NDARRAY_H_\n\n#include <dlpack/dlpack.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n/*! \\brief Magic number for NDArray file */\nstatic const uint64_t kTVMNDArrayMagic = 0xDD5E40F096B4A13F;\n\n/*! \\brief Magic number for NDArray list file  */\nstatic const uint64_t kTVMNDArrayListMagic = 0xF7E58D4F05049CB7;\n\ntypedef struct TVMNDArray {\n  /*! \\brief the actual tensor in DLPack format. NOTE: this must be first element in struct */\n  DLTensor dl_tensor;\n\n  /*! \\brief count of references to TVMNDArray to avoid early freeing by host */\n  uint32_t reference_count;\n} TVMNDArray;\n\nint TVMNDArray_Create(int32_t ndim, const tvm_index_t* shape, DLDataType dtype, DLDevice dev,\n                      TVMNDArray* array);\n\nint64_t TVMNDArray_DataSizeBytes(TVMNDArray* array);\n\nint TVMNDArray_RandomFill(TVMNDArray* array);\n\nint TVMNDArray_Empty(int32_t ndim, const tvm_index_t* shape, DLDataType dtype, DLDevice dev,\n                     TVMNDArray* array);\n\nint TVMNDArray_Load(TVMNDArray* ret, const char** strm);\n\nint TVMNDArray_CreateView(TVMNDArray* arr, const tvm_index_t* shape, int32_t ndim, DLDataType dtype,\n                          TVMNDArray* array_view);\n\nvoid TVMNDArray_IncrementReference(TVMNDArray* arr);\n\nuint32_t TVMNDArray_DecrementReference(TVMNDArray* arr);\n\nint TVMNDArray_Release(TVMNDArray* arr);\n\n#endif  // TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_COMMON_NDARRAY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/include/tvm/runtime/crt/internal/graph_executor/graph_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/crt/include/tvm/runtime/crt/internal/graph_executor/graph_executor.h\n * \\brief Tiny graph executor that can run graph containing only tvm PackedFunc.\n */\n#ifndef TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n#define TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <tvm/runtime/crt/graph_executor.h>\n#include <tvm/runtime/crt/internal/common/ndarray.h>\n#include <tvm/runtime/crt/internal/graph_executor/load_json.h>\n#include <tvm/runtime/crt/module.h>\n\n// Memory pool entry.\ntypedef struct TVMGraphExecutorPoolEntry {\n  size_t size;\n  int device_type;\n  int entry_id;\n} TVMGraphExecutorPoolEntry;\n\n// Node entry\ntypedef struct TVMGraphExecutorNodeEntry {\n  uint32_t node_id;\n  uint32_t index;\n  uint32_t version;\n  // JSON Loader\n  void (*Load)(JSONReader* reader);\n} TVMGraphExecutorNodeEntry;\n\n// Storage entry.\ntypedef struct TVMGraphExecutorStorageEntry {\n  uint8_t is_linked_param;\n  TVMNDArray array;\n} TVMGraphExecutorStorageEntry;\n\n// Node\ntypedef struct TVMGraphExecutorNode {\n  // operator type in string\n  char op_type[16];\n  // name of the op\n  char name[TVM_CRT_MAX_STRLEN_FUNCTION_NAME];\n  // parameters\n  TVMOpParam param;\n  // inputs\n  TVMGraphExecutorNodeEntry* inputs;\n  // number of inputs\n  size_t inputs_count;\n  // control deps\n  uint32_t control_deps[20];\n  // JSON Loader\n  void (*LoadAttrs)(struct TVMGraphExecutorNode* node, JSONReader* reader, TVMOpParam* param);\n  // JSON Loader\n  int (*Load)(struct TVMGraphExecutorNode* node, JSONReader* reader);\n} TVMGraphExecutorNode;\n\ntypedef struct TVMGraphExecutor {\n  /*! \\brief The graph nodes. */\n  TVMGraphExecutorNode* nodes;\n  /*! \\brief The graph nodes counter. */\n  uint32_t nodes_count;\n  /*! \\brief The argument nodes. */\n  uint32_t* input_nodes;\n  uint32_t input_nodes_count;\n  /*! \\brief Used for quick entry indexing. */\n  uint32_t* node_row_ptr;\n  uint32_t node_row_ptr_count;\n  /*! \\brief Output entries. */\n  TVMGraphExecutorNodeEntry* outputs;\n  /*! \\brief Output entries counter. */\n  uint32_t outputs_count;\n  /*! \\brief Additional graph attributes. */\n  TVMGraphExecutorGraphAttr attrs;\n  /*! \\brief The code module that contains both host and device code. */\n  TVMModuleHandle module_handle;\n  /*! \\brief Execution context of all devices including the host. */\n  DLDevice devices[1];\n  uint32_t devices_count;\n  /*! \\brief Common storage pool for all devices. */\n  TVMGraphExecutorStorageEntry* storage_pool;\n  uint32_t storage_pool_count;\n  /*! \\brief Data entry of each node. */\n  TVMNDArray* data_entry;\n  uint32_t data_entry_count;\n  /*! \\brief Operator on each node. */\n  TVMPackedFunc* op_execs;\n  uint32_t op_execs_count;\n} TVMGraphExecutor;\n\ntypedef DLTensor* DLTensorPtr;\n\n// private functions\nuint32_t TVMGraphExecutor_GetEntryId(TVMGraphExecutor* executor, uint32_t nid, uint32_t index);\nvoid TVMGraphExecutor_SetInput(TVMGraphExecutor* executor, const char* name, DLTensor* data_in);\nint TVMGraphExecutor_LoadParams(TVMGraphExecutor* executor, const char* param_blob,\n                                const uint32_t param_size);\nvoid TVMGraphExecutor_Run(TVMGraphExecutor* executor);\nint TVMGraphExecutor_GetOutput(TVMGraphExecutor* executor, const int32_t idx, DLTensor* out);\n\nint32_t TVMGraphExecutor_CreateTVMOp(TVMGraphExecutor* executor, const TVMOpParam* param,\n                                     DLTensorPtr* args, const uint32_t args_count,\n                                     TVMPackedFunc* pf);\nint TVMGraphExecutor_Load(TVMGraphExecutor* executor, JSONReader* reader);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/include/tvm/runtime/crt/internal/graph_executor/load_json.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/crt/include/tvm/runtime/crt/internal/graph_executor/load_json.h\n * \\brief Lightweight JSON Reader that read save into C++ data structs.\n */\n#ifndef TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_LOAD_JSON_H_\n#define TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_LOAD_JSON_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <ctype.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <tvm/runtime/crt/error_codes.h>\n\nenum {\n  JSON_READ_TYPE_U8 = 1,\n  JSON_READ_TYPE_S8 = 2,\n  JSON_READ_TYPE_U16 = 3,\n  JSON_READ_TYPE_S16 = 4,\n  JSON_READ_TYPE_U32 = 5,\n  JSON_READ_TYPE_S32 = 6,\n  JSON_READ_TYPE_F32 = 7,\n  JSON_READ_TYPE_F64 = 8,\n  JSON_READ_TYPE_GRAPH_EXECUTOR_NODE = 9,\n  JSON_READ_TYPE_GRAPH_EXECUTOR_NODE_ENTRY = 10,\n  JSON_READ_TYPE_GRAPH_EXECUTOR_GRAPH_ATTR = 11\n};\n\ntypedef struct Seq {\n  uint32_t* data;\n  uint64_t allocated;\n  uint32_t size;\n  void (*push_back)(struct Seq* seq, uint32_t src);\n  uint32_t* (*back)(struct Seq* seq);\n  void (*pop_back)(struct Seq* seq);\n} Seq;\n\n/*!\n * \\brief Lightweight JSON Reader to read any STL compositions and structs.\n *  The user need to know the schema of the\n */\ntypedef struct JSONReader {\n  /*! \\brief internal reader string */\n  char* is_;\n  char* isptr;\n  /*! \\brief \"\\\\r\" counter */\n  size_t line_count_r_;\n  /*! \\brief \"\\\\n\" counter */\n  size_t line_count_n_;\n  /*!\n   * \\brief record how many element processed in\n   *  current array/object scope.\n   */\n  Seq* scope_counter_;\n\n  char (*NextChar)(struct JSONReader* reader);\n  char (*NextNonSpace)(struct JSONReader* reader);\n  char (*PeekNextChar)(struct JSONReader* reader);\n  char (*PeekNextNonSpace)(struct JSONReader* reader);\n  int (*ReadUnsignedInteger)(struct JSONReader* reader, unsigned int* out_value);\n  int (*ReadInteger)(struct JSONReader* reader, int64_t* out_value);\n  int (*ReadString)(struct JSONReader* reader, char* out_str, size_t out_str_size);\n  void (*BeginArray)(struct JSONReader* reader);\n  void (*BeginObject)(struct JSONReader* reader);\n  uint8_t (*NextObjectItem)(struct JSONReader* reader, char* out_key, size_t out_key_size);\n  uint8_t (*NextArrayItem)(struct JSONReader* reader);\n  int (*ArrayLength)(struct JSONReader* reader, size_t* num_elements);\n} JSONReader;\n\n/*!\n * \\brief Constructor of JSONReader class\n * \\param is the input source.\n * \\param reader Pointer to the JSONReader to initialize.\n * \\return kTvmErrorNoError on success.\n */\ntvm_crt_error_t JSONReader_Create(const char* is, JSONReader* reader);\n\n/*!\n * \\brief Deallocate dynamic memory used in the JSONReader instance.\n * NOTE: this doesn't actually free the passed-in reader itself, just dynamically-allocated members.\n * \\param reader Pointer to a JSONReader passed to JSONReader_Create.\n * \\return kTvmErrorNoError on success.\n */\ntvm_crt_error_t JSONReader_Release(JSONReader* reader);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_GRAPH_EXECUTOR_LOAD_JSON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/include/tvm/runtime/crt/internal/memory/page_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/crt/include/tvm/runtime/crt/internal/memory/page_allocator.h\n * \\brief Defines data types and functions used in the internal memory manager.\n *     Exposed for testing.\n */\n\n#ifndef TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_MEMORY_PAGE_ALLOCATOR_H_\n#define TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_MEMORY_PAGE_ALLOCATOR_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n#include <tvm/runtime/crt/page_allocator.h>\n\n#include \"crt_config.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*! \\brief A page in the DRAM */\ntypedef struct Page {\n  /*! \\brief Start location in page table */\n  tvm_index_t ptable_begin;\n  /*! \\brief The total number of pages */\n  tvm_index_t num_pages;\n  /*! \\brief Data */\n  uint8_t* data;\n} Page;\n\n// construct a new page\nPage PageCreate(uint8_t* memory_pool, size_t page_size_bytes, tvm_index_t ptable_begin,\n                tvm_index_t num_pages);\n\ntypedef struct PageTable {\n  // Pointer to beginning of memory pool.\n  uint8_t* memory_pool;\n  // Size of one page.\n  size_t page_size_bytes;\n\n  Page* page;\n  size_t max_pages;\n  size_t num_pages;\n  void (*resize)(struct PageTable* ptable, size_t size, Page* page);\n} PageTable;\n\ntypedef struct PageEntry {\n  uint8_t* addr;\n  Page page;\n} PageEntry;\n\ntypedef struct TLB {\n  PageEntry* entries;\n  size_t max_pages;\n  uint32_t num_pages;\n  void (*set)(struct TLB* tlb, uint8_t* data, Page* page);\n  PageEntry* (*find)(struct TLB* tlb, uint8_t* data);\n} TLB;\n\ntypedef struct IndexedEntry {\n  tvm_index_t index;\n  Page page;\n} IndexedEntry;\n\ntypedef struct MultiMap {\n  IndexedEntry* entries;\n  size_t max_entries;\n  size_t num_entries;\n  IndexedEntry* (*lower_bound)(struct MultiMap* map, uint32_t npage);\n  IndexedEntry* (*end)(struct MultiMap* map);\n  void (*erase)(struct MultiMap* map, IndexedEntry* entry);\n  void (*insert)(struct MultiMap* map, uint32_t npage, Page* p);\n} MultiMap;\n\n/*!\n * \\brief DRAM memory manager\n *  Implements simple paging to allow physical address translation.\n */\ntypedef struct MemoryManager {\n  // Public interface for this object.\n  MemoryManagerInterface interface;\n  // Physical address -> page\n  PageTable ptable;\n  // Virtual address -> page\n  TLB pmap;\n  // Free map\n  MultiMap free_map;\n} MemoryManager;\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  // TVM_RUNTIME_CRT_INCLUDE_TVM_RUNTIME_CRT_INTERNAL_MEMORY_PAGE_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/memory/page_allocator.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n// LINT_C_FILE\n\n/*!\n * \\file memory.c\n * \\brief Virtual memory manager\n *\n * To maximize portability, thread-safe feature has been dropped for now.\n */\n\n#include <inttypes.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/crt/error_codes.h>\n#include <tvm/runtime/crt/internal/memory/page_allocator.h>\n#include <tvm/runtime/crt/logging.h>\n#include <tvm/runtime/crt/platform.h>\n\n// construct a new page\nPage PageCreate(uint8_t* memory_pool, size_t page_size_bytes, tvm_index_t ptable_begin,\n                tvm_index_t num_pages) {\n  Page page;\n  page.ptable_begin = ptable_begin;\n  page.num_pages = num_pages;\n  page.data = memory_pool + ptable_begin * page_size_bytes;\n  return page;\n}\n\nvoid PageTable_Resize(struct PageTable* ptable, size_t new_size, Page* page) {\n  CHECK_LE(ptable->num_pages, new_size, \"size value (%zu) is smaller than expected (%zu).\",\n           new_size, ptable->num_pages);\n  for (uint32_t idx = ptable->num_pages; idx < new_size; idx++) {\n    ptable->page[idx] = *page;\n  }\n  ptable->num_pages = new_size;\n}\n\nvoid TLB_Set(TLB* tlb, uint8_t* data, Page* page) {\n  PageEntry* entry = tlb->find(tlb, data);\n  if (entry == 0) {\n    tlb->entries[tlb->num_pages].addr = data;\n    tlb->entries[tlb->num_pages].page = *page;\n    tlb->num_pages++;\n  } else {\n    entry->addr = data;\n    entry->page = *page;\n  }\n}\n\nPageEntry* TLB_Find(TLB* tlb, uint8_t* data) {\n  PageEntry* entry = 0;\n  for (uint32_t idx = 0; idx < tlb->num_pages; idx++) {\n    if (tlb->entries[idx].addr == data) {\n      entry = tlb->entries + idx;\n      break;\n    }\n  }\n  return entry;\n}\n\nIndexedEntry* MultiMap_LowerBound(struct MultiMap* map, uint32_t npage) {\n  IndexedEntry* entry = 0;\n  for (uint32_t idx = 0; idx < map->num_entries; idx++) {\n    if (map->entries[idx].index >= npage) {\n      entry = map->entries + idx;\n      break;\n    }\n  }\n  return entry;\n}\n\nIndexedEntry* MultiMap_End(struct MultiMap* map) {\n  IndexedEntry* entry = 0;\n  return entry;\n}\n\nvoid MultiMap_Erase(struct MultiMap* map, IndexedEntry* entry) {\n  for (uint32_t idx = 0; idx < map->num_entries; idx++) {\n    if ((map->entries + idx) == entry) {\n      // NOTE: do not use memcpy due to overlap.\n      for (uint32_t src_idx = idx + 1; src_idx < map->num_entries; src_idx++) {\n        map->entries[src_idx - 1] = map->entries[src_idx];\n      }\n      map->num_entries--;\n      break;\n    }\n  }\n}\n\nvoid MultiMap_Insert(struct MultiMap* map, uint32_t npage, Page* p) {\n  CHECK_LE(map->num_entries + 1, map->max_entries, \"invalid number of free pages.\");\n  for (uint32_t idx = map->num_entries; idx < (map->num_entries + npage); idx++) {\n    map->entries[map->num_entries].index = npage;\n    map->entries[map->num_entries].page = *p;\n  }\n  map->num_entries++;\n}\n\n/*!\n * \\brief Allocate memory from manager\n * \\param size The size of memory\n * \\return The virtual address\n */\ntvm_crt_error_t PageMemoryManager_Allocate(MemoryManagerInterface* interface, size_t num_bytes,\n                                           DLDevice dev, void** out_ptr) {\n  MemoryManager* mgr = (MemoryManager*)interface;\n\n  *out_ptr = 0;\n  PageTable* ptable = &(mgr->ptable);\n  tvm_index_t npage = (num_bytes + ptable->page_size_bytes - 1) / ptable->page_size_bytes;\n\n  MultiMap* free_map = &(mgr->free_map);\n  IndexedEntry* it = free_map->lower_bound(free_map, npage);\n  tvm_index_t start = 0;\n  if (it != free_map->end(free_map)) {\n    Page p = it->page;\n    free_map->erase(free_map, it);\n    *out_ptr = p.data;\n    start = p.ptable_begin;\n    npage = p.num_pages;\n  } else {\n    start = ptable->num_pages;\n    if ((unsigned)(start + npage) > ptable->max_pages) {\n#if TVM_CRT_DEBUG > 1\n      TVMLogf(\"insufficient memory, start=%\" PRId32 \", npage=%\" PRId32 \", total=%\" PRId32 \" / %zu\",\n              (int32_t)start, (int32_t)npage, (int32_t)(start + npage), mgr->pmap.max_pages);\n#endif\n      return kTvmErrorPlatformNoMemory;\n    }\n    /* insert page entry */\n    Page p = PageCreate(ptable->memory_pool, ptable->page_size_bytes, start, npage);\n    ptable->resize(ptable, start + npage, &p);\n    *out_ptr = p.data;\n    TLB* pmap = &(mgr->pmap);\n    pmap->set(pmap, *out_ptr, &p);\n  }\n  mgr->interface.vleak_size++;\n#if TVM_CRT_DEBUG > 1\n  TVMLogf(\"allocate: addr=%p, start=%\" PRId64 \"/%zu, npage=%\" PRId64 \", vleak=%d\\n\", data, start,\n          ptable->max_pages, npage, mgr->interface.vleak_size);\n#endif  // TVM_CRT_DEBUG\n  return kTvmErrorNoError;\n}\n\n/*!\n * \\brief Reallocate memory from manager\n * \\param ptr Pointer holding a pointer to the memory area to be reallocated\n * \\param num_bytes The size of memory now required.\n * \\return kTvmErrorNoError on success.\n */\ntvm_crt_error_t PageMemoryManager_Realloc(MemoryManagerInterface* interface, void** ptr,\n                                          tvm_index_t num_bytes) {\n  MemoryManager* mgr = (MemoryManager*)interface;\n\n  uint8_t* data = *((uint8_t**)ptr);  // NOLINT(*)\n  PageTable* ptable = &(mgr->ptable);\n  TLB* pmap = &(mgr->pmap);\n  MultiMap* free_map = &(mgr->free_map);\n  tvm_index_t start = 0;\n  tvm_index_t npage = (num_bytes + ptable->page_size_bytes - 1) / ptable->page_size_bytes;\n  if (ptr) {\n    // get page size for given pointer\n    CHECK_NE(pmap->num_pages, 0, \"invalid translation look-aside buffer.\");\n    PageEntry* entry = pmap->find(pmap, (uint8_t*)ptr);  // NOLINT(*)\n    CHECK_NE(entry, 0, \"no valid page entry found.\");\n    Page* pptr = &(entry->page);\n    // if the page size is smaller than target page size,\n    // try allocate new space\n    if (pptr->num_pages < npage) {\n      // TODO(liangfu): found out whether we can extend current entry\n      //\n      // insert new page entry\n      IndexedEntry* it = free_map->lower_bound(free_map, npage);\n      if (it != free_map->end(free_map)) {\n        data = it->page.data;\n        start = it->page.ptable_begin;\n        npage = it->page.num_pages;\n        free_map->erase(free_map, it);\n      } else {\n        start = ptable->num_pages;\n        if ((unsigned)(start + npage) > ptable->max_pages) {\n#if TVM_CRT_DEBUG > 1\n          TVMLogf(\"insufficient memory, start=%\" PRId64 \", npage=%\" PRId64 \", total=%\" PRId64 \"\",\n                  start, npage, start + npage);\n#endif\n          return kTvmErrorPlatformNoMemory;\n        }\n        Page p = PageCreate(mgr->ptable.memory_pool, mgr->ptable.page_size_bytes, start, npage);\n        ptable->resize(ptable, start + npage, &p);\n        data = p.data;\n        pmap->set(pmap, data, &p);\n      }\n      // copy previous data to the new entry\n      memcpy(data, ptr, ptable->page_size_bytes * pptr->num_pages);\n      // release memory\n      free_map->insert(free_map, pptr->num_pages, pptr);\n    } else {\n      start = pptr->ptable_begin;\n    }\n  } else {\n    IndexedEntry* it = free_map->lower_bound(free_map, npage);\n    if (it != free_map->end(free_map)) {\n      Page p = it->page;\n      free_map->erase(free_map, it);\n      data = p.data;\n      start = p.ptable_begin;\n      npage = p.num_pages;\n    } else {\n      PageTable* ptable = &(mgr->ptable);\n      start = ptable->num_pages;\n      if ((unsigned)(start + npage) > ptable->max_pages) {\n#if TVM_CRT_DEBUG > 1\n        TVMLogf(\"insufficient memory, start=%\" PRId64 \", npage=%\" PRId64 \", total=%\" PRId64 \"\",\n                start, npage, start + npage);\n#endif\n        /* insert page entry */\n        Page p = PageCreate(mgr->ptable.memory_pool, mgr->ptable.page_size_bytes, start, npage);\n        ptable->resize(ptable, start + npage, &p);\n        data = p.data;\n        TLB* pmap = &(mgr->pmap);\n        pmap->set(pmap, data, &p);\n      }\n      mgr->interface.vleak_size++;\n    }\n  }\n#if TVM_CRT_DEBUG > 1\n  TVMLogf(\"reallocate: addr=%p, start=%\" PRId64 \"/%zu, npage=%\" PRId64 \", vleak=%d, size=%zu\", data,\n          start, mgr->ptable.max_pages, npage, mgr->interface.vleak_size, size);\n#endif  // TVM_CRT_DEBUG\n  return kTvmErrorNoError;\n}\n\n/*!\n * \\brief Free the memory.\n * \\param interface Pointer to this structure.\n * \\param ptr A pointer returned from TVMPlatformMemoryAllocate which should be free'd.\n * \\param dev Execution device passed to TVMPlatformMemoryAllocate. Fixed to {kDLCPU, 0}.\n * \\return kTvmErrorNoError if successful; a descriptive error code otherwise.\n */\ntvm_crt_error_t PageMemoryManager_Free(MemoryManagerInterface* interface, void* ptr, DLDevice dev) {\n  MemoryManager* mgr = (MemoryManager*)interface;\n\n  TLB* pmap = &(mgr->pmap);\n  CHECK_NE(pmap->num_pages, 0, \"invalid translation look-aside buffer.\");\n  PageEntry* entry = pmap->find(pmap, (uint8_t*)ptr);  // NOLINT(*)\n  CHECK_NE(entry, 0, \"no valid page entry found.\");\n  Page* p = &(entry->page);\n  MultiMap* free_map = &(mgr->free_map);\n  free_map->insert(free_map, p->num_pages, p);\n  mgr->interface.vleak_size--;\n#if TVM_CRT_DEBUG > 1\n  TVMLogf(\"release: addr=%p, start=%\" PRId64 \"/%zu, npage=%zu, vleak=%d\", ptr,\n          entry->page.ptable_begin, mgr->ptable.max_pages, entry->page.num_pages,\n          mgr->interface.vleak_size);\n#endif  // TVM_CRT_DEBUG\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t PageMemoryManagerCreate(MemoryManagerInterface** interface, uint8_t* memory_pool,\n                                        size_t memory_pool_size_bytes,\n                                        size_t page_size_bytes_log2) {\n  memset(memory_pool, 0, memory_pool_size_bytes);\n\n  // Allocate enough space for MAX_PAGES.\n  size_t page_size_bytes = 1 << page_size_bytes_log2;\n  size_t metadata_bytes_per_page = sizeof(Page) + sizeof(PageEntry) + sizeof(IndexedEntry);\n  size_t bytes_needed_per_page = page_size_bytes + metadata_bytes_per_page;\n  size_t num_pages = (memory_pool_size_bytes - sizeof(MemoryManager)) / bytes_needed_per_page;\n\n  uint8_t* metadata_cursor = memory_pool + (num_pages << page_size_bytes_log2);\n  MemoryManager* manager = (MemoryManager*)metadata_cursor;\n  *interface = &manager->interface;\n  /* handle MemoryManager member functions */\n  manager->interface.Allocate = PageMemoryManager_Allocate;\n  //  manager->Realloc = MemoryManager_Reallocate;\n  manager->interface.Free = PageMemoryManager_Free;\n\n  metadata_cursor += sizeof(MemoryManager);\n\n  manager->interface.Allocate = PageMemoryManager_Allocate;\n  manager->interface.Free = PageMemoryManager_Free;\n  manager->ptable.memory_pool = memory_pool;\n\n  /* handle PageTable member functions */\n  manager->ptable.page = (Page*)metadata_cursor;\n  metadata_cursor += sizeof(Page) * num_pages;\n\n  manager->ptable.page_size_bytes = (1 << page_size_bytes_log2);\n  manager->ptable.max_pages = num_pages;\n  manager->ptable.resize = PageTable_Resize;\n\n  /* handle TLB member functions */\n  manager->pmap.entries = (PageEntry*)metadata_cursor;\n  metadata_cursor += sizeof(PageEntry) * num_pages;\n  manager->pmap.max_pages = num_pages;\n  manager->pmap.num_pages = 0;\n\n  manager->pmap.set = TLB_Set;\n  manager->pmap.find = TLB_Find;\n  /* handle free_map member functions */\n  manager->free_map.entries = (IndexedEntry*)metadata_cursor;\n  metadata_cursor += sizeof(IndexedEntry) * num_pages;\n  manager->free_map.max_entries = num_pages;\n  manager->free_map.lower_bound = MultiMap_LowerBound;\n  manager->free_map.end = MultiMap_End;\n  manager->free_map.erase = MultiMap_Erase;\n  manager->free_map.insert = MultiMap_Insert;\n\n  return kTvmErrorNoError;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/crt/memory/stack_allocator.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n// LINT_C_FILE\n#include <tvm/runtime/crt/stack_allocator.h>\n\ntvm_crt_error_t StackMemoryManager_Allocate_Body(tvm_workspace_t* tvm_runtime_workspace,\n                                                 int32_t nbytes, void** current_alloc,\n                                                 uint8_t do_lifo_check) {\n  // reserve bytes at the end of the allocation such that\n  // next_alloc % TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES == 0.\n  uint32_t offset_bytes =\n      (TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES - nbytes) & (TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES - 1);\n  uint8_t* workspace_end = tvm_runtime_workspace->workspace + tvm_runtime_workspace->workspace_size;\n  if (tvm_runtime_workspace->next_alloc + nbytes + offset_bytes > workspace_end) {\n    return kTvmErrorPlatformNoMemory;\n  }\n  (*current_alloc) = tvm_runtime_workspace->next_alloc;\n  uint8_t* next_alloc = tvm_runtime_workspace->next_alloc + nbytes + offset_bytes;\n  if (do_lifo_check != 0) {\n    if (next_alloc + STACK_ALLOCATOR_TAG_SIZE_BYTES > workspace_end) {\n      return kTvmErrorPlatformNoMemory;\n    }\n    const uint32_t total_size = (nbytes + offset_bytes + STACK_ALLOCATOR_TAG_SIZE_BYTES);\n    *((uint32_t*)next_alloc) = total_size ^ STACK_ALLOCATOR_TAG;\n    next_alloc += STACK_ALLOCATOR_TAG_SIZE_BYTES;\n  }\n\n  tvm_runtime_workspace->next_alloc = next_alloc;\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t StackMemoryManager_Allocate(tvm_workspace_t* tvm_runtime_workspace, int32_t nbytes,\n                                            void** current_alloc) {\n  uint8_t do_lifo_check = 0;\n#ifdef TVM_CRT_STACK_ALLOCATOR_ENABLE_LIFO_CHECK\n  do_lifo_check = 1;\n#endif\n  return StackMemoryManager_Allocate_Body(tvm_runtime_workspace, nbytes, current_alloc,\n                                          do_lifo_check);\n}\n\ntvm_crt_error_t StackMemoryManager_Free_Body(tvm_workspace_t* tvm_runtime_workspace, void* ptr,\n                                             uint8_t do_lifo_check) {\n  if (do_lifo_check != 0) {\n    uint32_t tag = *(((uint32_t*)tvm_runtime_workspace->next_alloc) - 1);\n    uint32_t actual_size = (tvm_runtime_workspace->next_alloc - (uint8_t*)ptr);\n    uint32_t expected_size = tag ^ STACK_ALLOCATOR_TAG;\n    if (expected_size != actual_size) {\n      return kTvmErrorPlatformStackAllocBadFree;\n    }\n  }\n  tvm_runtime_workspace->next_alloc = (uint8_t*)ptr;\n  return kTvmErrorNoError;\n}\n\ntvm_crt_error_t StackMemoryManager_Free(tvm_workspace_t* tvm_runtime_workspace, void* ptr) {\n  uint8_t do_lifo_check = 0;\n#ifdef TVM_CRT_STACK_ALLOCATOR_ENABLE_LIFO_CHECK\n  do_lifo_check = 1;\n#endif\n  return StackMemoryManager_Free_Body(tvm_runtime_workspace, ptr, do_lifo_check);\n}\n\ntvm_crt_error_t StackMemoryManager_Init(tvm_workspace_t* tvm_runtime_workspace,\n                                        uint8_t* g_aot_memory, size_t workspace_size) {\n  // We need to round up g_aot_memory in case it is not aligned to\n  // TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES.\n  uintptr_t unaligned_mask = TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES - 1;\n  uint8_t* memory_aligned =\n      (uint8_t*)(((uintptr_t)g_aot_memory + unaligned_mask) & ~unaligned_mask);\n  uint32_t offset = (uintptr_t)(memory_aligned - g_aot_memory);\n\n  tvm_runtime_workspace->next_alloc = memory_aligned;\n  tvm_runtime_workspace->workspace = memory_aligned;\n  tvm_runtime_workspace->workspace_size = workspace_size - offset;\n  return kTvmErrorNoError;\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/cuda/cuda_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda_common.h\n * \\brief Common utilities for CUDA\n */\n#ifndef TVM_RUNTIME_CUDA_CUDA_COMMON_H_\n#define TVM_RUNTIME_CUDA_CUDA_COMMON_H_\n\n#include <cuda_runtime.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n\n#include \"../workspace_pool.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n#define CUDA_DRIVER_CALL(x)                                             \\\n  {                                                                     \\\n    CUresult result = x;                                                \\\n    if (result != CUDA_SUCCESS && result != CUDA_ERROR_DEINITIALIZED) { \\\n      const char* msg;                                                  \\\n      cuGetErrorName(result, &msg);                                     \\\n      LOG(FATAL) << \"CUDAError: \" #x \" failed with error: \" << msg;     \\\n    }                                                                   \\\n  }\n\n#define CUDA_CALL(func)                                       \\\n  {                                                           \\\n    cudaError_t e = (func);                                   \\\n    ICHECK(e == cudaSuccess || e == cudaErrorCudartUnloading) \\\n        << \"CUDA: \" << cudaGetErrorString(e);                 \\\n  }\n\n/*! \\brief Thread local workspace */\nclass CUDAThreadEntry {\n public:\n  /*! \\brief The cuda stream */\n  cudaStream_t stream{nullptr};\n  /*! \\brief thread local pool*/\n  WorkspacePool pool;\n  /*! \\brief constructor */\n  CUDAThreadEntry();\n  // get the threadlocal workspace\n  static CUDAThreadEntry* ThreadLocal();\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CUDA_CUDA_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/cuda/cuda_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda_module.h\n * \\brief Execution handling of CUDA kernels\n */\n#ifndef TVM_RUNTIME_CUDA_CUDA_MODULE_H_\n#define TVM_RUNTIME_CUDA_CUDA_MODULE_H_\n\n#include <tvm/runtime/module.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Maximum number of GPU supported in CUDAModule */\nstatic constexpr const int kMaxNumGPUs = 32;\n\n/*!\n * \\brief create a cuda module from data.\n *\n * \\param data The module data, can be ptx, cubin\n * \\param fmt The format of the data, can be \"ptx\", \"cubin\"\n * \\param fmap The map function information map of each function.\n * \\param cuda_source Optional, cuda source file\n */\nModule CUDAModuleCreate(std::string data, std::string fmt,\n                        std::unordered_map<std::string, FunctionInfo> fmap,\n                        std::string cuda_source);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_CUDA_CUDA_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/file_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file file_utils.h\n * \\brief Minimum file manipulation utils for runtime.\n */\n#ifndef TVM_RUNTIME_FILE_UTILS_H_\n#define TVM_RUNTIME_FILE_UTILS_H_\n\n#include <tvm/runtime/container/map.h>\n#include <tvm/runtime/container/string.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief Get file format from given file name or format argument.\n * \\param file_name The name of the file.\n * \\param format The format of the file.\n */\nstd::string GetFileFormat(const std::string& file_name, const std::string& format);\n\n/*!\n * \\return the directory in which TVM stores cached files.\n *         May be set using TVM_CACHE_DIR; defaults to system locations.\n */\nstd::string GetCacheDir();\n\n/*!\n * \\brief Get meta file path given file name and format.\n * \\param file_name The name of the file.\n */\nstd::string GetMetaFilePath(const std::string& file_name);\n\n/*!\n * \\brief Get file basename (i.e. without leading directories)\n * \\param file_name The name of the file.\n * \\return the base name\n */\nstd::string GetFileBasename(const std::string& file_name);\n\n/*!\n * \\brief Load binary file into a in-memory buffer.\n * \\param file_name The name of the file.\n * \\param data The data to be loaded.\n */\nvoid LoadBinaryFromFile(const std::string& file_name, std::string* data);\n\n/*!\n * \\brief Load binary file into a in-memory buffer.\n * \\param file_name The name of the file.\n * \\param data The binary data to be saved.\n */\nvoid SaveBinaryToFile(const std::string& file_name, const std::string& data);\n\n/*!\n * \\brief Save meta data to file.\n * \\param file_name The name of the file.\n * \\param fmap The function info map.\n */\nvoid SaveMetaDataToFile(const std::string& file_name,\n                        const std::unordered_map<std::string, FunctionInfo>& fmap);\n\n/*!\n * \\brief Load meta data to file.\n * \\param file_name The name of the file.\n * \\param fmap The function info map.\n */\nvoid LoadMetaDataFromFile(const std::string& file_name,\n                          std::unordered_map<std::string, FunctionInfo>* fmap);\n\n/*!\n * \\brief Copy the content of an existing file to another file.\n * \\param src_file_name Path to the source file.\n * \\param dest_file_name Path of the destination file.  If this file already exists,\n *    replace its content.\n */\nvoid CopyFile(const std::string& src_file_name, const std::string& dest_file_name);\n\n/*!\n * \\brief Remove (unlink) a file.\n * \\param file_name The file name.\n */\nvoid RemoveFile(const std::string& file_name);\n\nconstexpr uint64_t kTVMNDArrayListMagic = 0xF7E58D4F05049CB7;\n/*!\n * \\brief Load parameters from a string.\n * \\param param_blob Serialized string of parameters.\n * \\return Map of parameter name to parameter value.\n */\nMap<String, NDArray> LoadParams(const std::string& param_blob);\n/*!\n * \\brief Load parameters from a stream.\n * \\param strm Stream to load parameters from.\n * \\return Map of parameter name to parameter value.\n */\nMap<String, NDArray> LoadParams(dmlc::Stream* strm);\n/*!\n * \\brief Serialize parameters to a byte array.\n * \\param params Parameters to save.\n * \\return String containing binary parameter data.\n */\nstd::string SaveParams(const Map<String, NDArray>& params);\n/*!\n * \\brief Serialize parameters to a stream.\n * \\param strm Stream to write to.\n * \\param params Parameters to save.\n */\nvoid SaveParams(dmlc::Stream* strm, const Map<String, NDArray>& params);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_FILE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/graph_executor/graph_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Tiny graph executor that can run graph\n *        containing only tvm PackedFunc.\n * \\file graph_executor.h\n */\n#ifndef TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n#define TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n\n#include <dlpack/dlpack.h>\n#include <dmlc/json.h>\n#include <dmlc/memory_io.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief macro to do C API call */\n#define TVM_CCALL(func)                     \\\n  {                                         \\\n    int ret = (func);                       \\\n    ICHECK_EQ(ret, 0) << TVMGetLastError(); \\\n  }\n\n/*! \\brief operator attributes about tvm op */\nstruct TVMOpParam {\n  std::string func_name;\n  std::unordered_map<std::string, ObjectRef> attrs;\n  uint32_t num_inputs;\n  uint32_t num_outputs;\n  uint32_t flatten_data;\n};\n\n/*!\n * \\brief Tiny graph executor.\n *\n *  This runtime can be accessible in various languages via\n *  TVM runtime PackedFunc API.\n */\nclass TVM_DLL GraphExecutor : public ModuleNode {\n  struct OpArgs {\n    std::vector<DLTensor> args;\n    std::vector<TVMValue> arg_values;\n    std::vector<int> arg_tcodes;\n    std::vector<int64_t> shape_data;\n  };\n\n public:\n  using ShapeInfo = Map<String, ObjectRef>;\n  using DtypeInfo = Map<String, ObjectRef>;\n  /*!\n   * \\brief Get member function to front-end\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const final { return \"GraphExecutor\"; }\n  void Run();\n\n  /*!\n   * \\brief Initialize the graph executor with graph and device.\n   * \\param graph_json The execution graph.\n   * \\param module The module containing the compiled functions for the host\n   *  processor.\n   * \\param devs The device of the host and devices where graph nodes will be\n   *  executed on.\n   * \\param lookup_linked_param_func If given, a PackedFunc invoked to lookup linked parameters\n   *  by storage_id. If not given, linked parameters are looked-up using an internal implementation,\n   *  which is not compatible with RPCModules. Default is nullptr.\n   */\n\n  void Init(const std::string& graph_json, tvm::runtime::Module module,\n            const std::vector<Device>& devs, const PackedFunc lookup_linked_param_func = nullptr);\n\n  /*!\n   * \\brief Get the input index given the name of input.\n   * \\param name The name of the input.\n   * \\return The index of input.\n   */\n  int GetInputIndex(const std::string& name);\n\n  /*!\n   * \\brief Get the input info of Graph by parsing the input nodes.\n   * \\return The shape and dtype tuple.\n   */\n  std::tuple<ShapeInfo, DtypeInfo> GetInputInfo() const;\n\n  /*!\n   * \\brief Get the output index given the name of output.\n   * \\param name The name of the output.\n   * \\return The index of output.\n   */\n  int GetOutputIndex(const std::string& name);\n\n  /*!\n   * \\brief set index-th input to the graph.\n   * \\param index The input index.\n   * \\param data_in The input data.\n   */\n  void SetInput(int index, DLTensor* data_in);\n  /*!\n   * \\brief set index-th input to the graph without copying the data\n   * \\param index The input index.\n   * \\param data_ref The input data that is referred.\n   */\n  void SetInputZeroCopy(int index, DLTensor* data_ref);\n  /*!\n   * \\brief set index-th output to the graph without copying the data.\n   * \\param index The output index.\n   * \\param data_ref The output data that is referred.\n   */\n  void SetOutputZeroCopy(int index, DLTensor* data_ref);\n  /*!\n   * \\brief Get the number of outputs\n   *\n   * \\return The number of outputs from graph.\n   */\n  int NumOutputs() const;\n  /*!\n   * \\brief Get the number of inputs\n   *\n   * \\return The number of inputs to the graph.\n   */\n  int NumInputs() const;\n  /*!\n   * \\brief Return NDArray for given input index.\n   * \\param index The input index.\n   *\n   * \\return NDArray corresponding to given input node index.\n   */\n  NDArray GetInput(int index) const;\n  /*!\n   * \\brief Return NDArray for given output index.\n   * \\param index The output index.\n   *\n   * \\return NDArray corresponding to given output node index.\n   */\n  NDArray GetOutput(int index) const;\n  /*!\n   * \\brief Copy index-th output to data_out.\n   * \\param index The output index.\n   * \\param data_out the output data.\n   */\n  void CopyOutputTo(int index, DLTensor* data_out);\n  /*!\n   * \\brief Load parameters from binary stream\n   * \\param strm The input stream.\n   */\n  void LoadParams(dmlc::Stream* strm);\n  /*!\n   * \\brief Load parameters from parameter blob.\n   * \\param param_blob A binary blob of parameter.\n   */\n  void LoadParams(const std::string& param_blob);\n\n  /*!\n   * \\brief Share parameters from pre-existing GraphExecutor instance.\n   * \\param other A GraphExecutor instance, previously with |LoadParams| called with the\n   * identical input |param_blob|.\n   * \\param strm The input stream.\n   */\n  void ShareParams(const GraphExecutor& other, dmlc::Stream* strm);\n\n  /*!\n   * \\brief Get total number of nodes.\n   * \\return Total number of nodes.\n   */\n  uint32_t GetNumOfNodes() const { return static_cast<uint32_t>(nodes_.size()); }\n\n  std::string GetNodeName(uint32_t nid) const { return nodes_[nid].name; }\n\n protected:\n  // Memory pool entry.\n  struct PoolEntry {\n    int device_type;\n    std::vector<int64_t> shape;\n    DLDataType dtype;\n    int param_data_entry;\n    NDArray linked_param;\n    std::string scope;\n    //    PoolEntry(int s, int dev_type, void* pre_linked_param) :\n    //        size(s), device_type(dev_type), pre_linked_param(std::move(pre_linked_param)) {}\n  };\n  // Node entry\n  struct NodeEntry {\n    uint32_t node_id;\n    uint32_t index;\n    uint32_t version;\n    inline bool operator==(const NodeEntry& other) const {\n      return node_id == other.node_id && index == other.index && version == other.version;\n    }\n    // JSON Loader\n    void Load(dmlc::JSONReader* reader) {\n      reader->BeginArray();\n      ICHECK(reader->NextArrayItem()) << \"invalid json format\";\n      reader->Read(&node_id);\n      ICHECK(reader->NextArrayItem()) << \"invalid json format\";\n      reader->Read(&index);\n      if (reader->NextArrayItem()) {\n        reader->Read(&version);\n        ICHECK(!reader->NextArrayItem()) << \"invalid json format\";\n      } else {\n        version = 0;\n      }\n    }\n  };\n  // Node\n  struct Node {\n    // operator type in string\n    std::string op_type;\n    // name of the op\n    std::string name;\n    // parameters\n    TVMOpParam param;\n    // inputs\n    std::vector<NodeEntry> inputs;\n    // control deps\n    std::vector<uint32_t> control_deps;\n\n    // JSON Loader\n    void LoadAttrs(dmlc::JSONReader* reader, TVMOpParam* param) {\n      int bitmask = 0;\n      std::string key, value;\n      reader->BeginObject();\n      while (reader->NextObjectItem(&key)) {\n        reader->Read(&value);\n        if (key == \"func_name\") {\n          param->func_name = value;\n          bitmask |= 1;\n        } else if (key == \"num_inputs\") {\n          param->num_inputs = strtoul(value.c_str(), nullptr, 10);\n          bitmask |= 2;\n        } else if (key == \"num_outputs\") {\n          param->num_outputs = strtoul(value.c_str(), nullptr, 10);\n          bitmask |= 4;\n        } else if (key == \"flatten_data\") {\n          param->flatten_data = strtoul(value.c_str(), nullptr, 10);\n          bitmask |= 8;\n        } else {\n          param->attrs[key] = String(value);\n        }\n      }\n      ICHECK_EQ(bitmask, 1 | 2 | 4 | 8) << \"invalid format\";\n    }\n    // JSON Loader\n    void Load(dmlc::JSONReader* reader) {\n      reader->BeginObject();\n      int bitmask = 0;\n      std::string key;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"op\") {\n          reader->Read(&op_type);\n          bitmask |= 1;\n        } else if (key == \"name\") {\n          reader->Read(&name);\n          bitmask |= 2;\n        } else if (key == \"inputs\") {\n          reader->Read(&inputs);\n          bitmask |= 4;\n        } else if (key == \"attr\" || key == \"attrs\") {\n          this->LoadAttrs(reader, &param);\n        } else if (key == \"control_deps\") {\n          reader->Read(&control_deps);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK_EQ(bitmask, 1 | 2 | 4) << \"invalid format\";\n    }\n  };\n  struct GraphAttr {\n    size_t storage_num_not_alloctaed{0};\n    std::vector<int> storage_id;\n    std::vector<int> device_index;\n    std::vector<std::string> dltype;\n    std::vector<std::string> storage_scope;\n    std::vector<std::vector<int64_t>> shape;\n    // The graph attribute fields.\n    void Load(dmlc::JSONReader* reader) {\n      reader->BeginObject();\n      int bitmask = 0;\n      std::string key, type;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"dltype\") {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          ICHECK_EQ(type, \"list_str\");\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&dltype);\n          ICHECK(!reader->NextArrayItem());\n          bitmask |= 1;\n        } else if (key == \"storage_id\") {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          ICHECK_EQ(type, \"list_int\");\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&storage_id);\n          ICHECK(!reader->NextArrayItem());\n          bitmask |= 2;\n        } else if (key == \"storage_scope\") {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          ICHECK_EQ(type, \"list_str\");\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&storage_scope);\n          ICHECK(!reader->NextArrayItem());\n          bitmask |= 1;\n        } else if (key == \"shape\") {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          ICHECK_EQ(type, \"list_shape\");\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&shape);\n          ICHECK(!reader->NextArrayItem());\n          bitmask |= 4;\n        } else if (key == \"device_index\") {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          ICHECK_EQ(type, \"list_int\");\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&device_index);\n          ICHECK(!reader->NextArrayItem());\n        } else {\n          reader->BeginArray();\n          ICHECK(reader->NextArrayItem());\n          reader->Read(&type);\n          if (type == \"list_int\") {\n            ICHECK(reader->NextArrayItem());\n            std::vector<int> temp;\n            reader->Read(&temp);\n          } else if (type == \"size_t\") {\n            ICHECK(reader->NextArrayItem());\n            size_t temp;\n            reader->Read(&temp);\n          } else {\n            LOG(FATAL) << \"cannot skip graph attr \" << key;\n          }\n          ICHECK(!reader->NextArrayItem());\n        }\n      }\n      ICHECK_EQ(bitmask, 1 | 2 | 4) << \"invalid format\";\n    }\n  };\n  // The graph attribute fields.\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginObject();\n    int bitmask = 0;\n    std::string key;\n    while (reader->NextObjectItem(&key)) {\n      if (key == \"nodes\") {\n        reader->Read(&nodes_);\n        bitmask |= 1;\n      } else if (key == \"arg_nodes\") {\n        reader->Read(&input_nodes_);\n        bitmask |= 2;\n      } else if (key == \"node_row_ptr\") {\n        reader->Read(&node_row_ptr_);\n        bitmask |= 4;\n      } else if (key == \"heads\") {\n        reader->Read(&outputs_);\n        bitmask |= 8;\n      } else if (key == \"attrs\") {\n        reader->Read(&attrs_);\n        bitmask |= 16;\n      } else if (key == \"metadata\") {\n        break;\n      } else {\n        LOG(FATAL) << \"key \" << key << \" is not supported\";\n      }\n    }\n    ICHECK_EQ(bitmask, 1 | 2 | 4 | 8 | 16) << \"invalid format\";\n  }\n  /*! \\brief PackedFunc to lookup a linked paramter from a local Module. */\n  void DefaultLookupLinkedParam(TVMArgs args, TVMRetValue* rv);\n  /*! \\brief Delete NDArray::Container with linked (i.e. static) data. */\n  static void LinkedNDArrayDeleter(Object* container);\n  /*! \\brief Setup the temporal storage */\n  void SetupStorage();\n  /*! \\brief Setup the executors. */\n  void SetupOpExecs();\n  /*!\n   * \\brief Check the legality of external DLTensor*.\n   * \\param external The external DLTensor*.\n   * \\param eid The data_enrty_ index.\n   */\n  void CheckExternalDLTensor(const DLTensor* external, uint32_t eid) const;\n  /*!\n   * \\brief Create an execution function given input.\n   * \\param attrs The node attributes.\n   * \\param args The arguments to the functor, including inputs and outputs.\n   * \\return The created executor.\n   */\n  std::pair<std::function<void()>, std::shared_ptr<OpArgs>> CreateTVMOp(\n      const TVMOpParam& attrs, const std::vector<DLTensor>& args);\n  // Get node entry index.\n  uint32_t entry_id(uint32_t nid, uint32_t index) const { return node_row_ptr_[nid] + index; }\n  // Get node entry index.\n  uint32_t entry_id(const NodeEntry& e) const { return entry_id(e.node_id, e.index); }\n  // Number of node entries.\n  uint32_t num_node_entries() const { return node_row_ptr_.back(); }\n  /*! \\brief The graph nodes. */\n  std::vector<Node> nodes_;\n  /*! \\brief The argument nodes. */\n  std::vector<uint32_t> input_nodes_;\n  /*! \\brief The parameter names. */\n  std::unordered_set<std::string> param_names_;\n  /*! \\brief Map of input names to input indices. */\n  std::unordered_map<std::string, uint32_t> input_map_;\n  /*! \\brief Map of output names to output indices. */\n  std::unordered_map<std::string, uint32_t> output_map_;\n  /*! \\brief Used for quick node input DLTensor* lookup given an input eid. */\n  std::vector<std::vector<DLTensor*>> input_dltensors_;\n  /*! \\brief Used for quick node output DLTensor* lookup given an output eid. */\n  std::vector<std::vector<DLTensor*>> output_dltensors_;\n  /*! \\brief Used for quick node(both model output and op input) DLTensor* lookup given an eid. */\n  std::vector<std::vector<DLTensor*>> both_output_opinput_dltensors_;\n  /*! \\brief Used for quick entry indexing. */\n  std::vector<uint32_t> node_row_ptr_;\n  /*! \\brief Output entries. */\n  std::vector<NodeEntry> outputs_;\n  /*! \\brief Additional graph attributes. */\n  GraphAttr attrs_;\n  /*! \\brief The code module that contains both host and device code. */\n  tvm::runtime::Module module_;\n  /*! \\brief Execution context of all devices including the host. */\n  std::vector<Device> devices_;\n  /*! \\brief Common storage pool for all devices. */\n  std::vector<NDArray> storage_pool_;\n  /*! \\brief Data entry of each node. */\n  std::vector<NDArray> data_entry_;\n  /*! \\brief Data alignment of each node. */\n  std::vector<size_t> data_alignment_;\n  /*! \\brief Operator on each node. */\n  std::vector<std::function<void()>> op_execs_;\n  /*! \\brief Linked parameter lookup function. */\n  PackedFunc lookup_linked_param_;\n  /*! \\brief Module's _lookup_linked_param function, used by DefaultLookupLinkedParam. */\n  PackedFunc module_lookup_linked_param_;\n  /*!\n   * \\brief True when module_lookup_linked_param_ is valid.\n   * When the module does not include linked parmeters, module_lookup_linked_param_ will be nullptr.\n   */\n  bool module_lookup_linked_param_valid_;\n};\n\nstd::vector<Device> GetAllDevice(const TVMArgs& args, int dev_start_arg);\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/graph_executor/graph_executor_factory.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/graph_executor/graph_executor_factory.h\n * \\brief Graph executor factory creating graph executor.\n */\n\n#ifndef TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_\n#define TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"./graph_executor.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass TVM_DLL GraphExecutorFactory : public runtime::ModuleNode {\n public:\n  /*!\n   * \\brief Construct the GraphExecutorFactory.\n   * \\param graph_json The execution graph.\n   * \\param params The params of graph.\n   * \\param module_name The module name of graph.\n   */\n  GraphExecutorFactory(const std::string& graph_json,\n                       const std::unordered_map<std::string, tvm::runtime::NDArray>& params,\n                       const std::string& module_name = \"default\");\n\n  /*!\n   * \\brief Get member function to front-end\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding member function.\n   */\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n\n  /*!\n   * \\return The type key of the executor.\n   */\n  const char* type_key() const final { return \"GraphExecutorFactory\"; }\n\n  /*!\n   * \\brief Save the module to binary stream.\n   * \\param stream The binary stream to save to.\n   */\n  void SaveToBinary(dmlc::Stream* stream) override;\n\n  /*!\n   * \\brief Create a specific executor module\n   * \\param devs The device of the host and devices where graph nodes will be\n   *  executed on.\n   * \\return created executor module\n   */\n  Module ExecutorCreate(const std::vector<Device>& devs);\n\n  /*!\n   * \\brief Create a specific debug executor module\n   * \\param devs The device of the host and devices where graph nodes will be\n   *  executed on.\n   * \\return created debug executor module\n   */\n  Module DebugExecutorCreate(const std::vector<Device>& devs);\n\n  /*!\n   * \\brief Create a specific cuda graph executor module\n   * \\param devs The device of the host and devices where graph nodes will be\n   *  executed on.\n   * \\return created cuda graph executor module\n   */\n  Module CudaGraphExecutorCreate(const std::vector<Device>& devs);\n\n  /*!\n   * \\brief Set params.\n   * \\param graph_executor The graph executor we want to set the params into.\n   * \\param params The graph params value we want to set.\n   */\n  void SetParams(GraphExecutor* graph_executor,\n                 const std::unordered_map<std::string, tvm::runtime::NDArray>& params) const {\n    std::unordered_map<std::string, tvm::runtime::NDArray> value = params;\n    // upload big arrays first to avoid memory issue in rpc mode\n    std::vector<std::string> keys;\n    for (const auto& p : value) {\n      keys.emplace_back(p.first);\n    }\n    std::sort(std::begin(keys), std::end(keys),\n              [&](const std::string& lhs, const std::string& rhs) -> bool {\n                auto lhs_size = GetDataSize(*value[lhs].operator->());\n                auto rhs_size = GetDataSize(*value[rhs].operator->());\n                return lhs_size > rhs_size;\n              });\n    for (const auto& key : keys) {\n      int in_idx = graph_executor->GetInputIndex(key);\n      if (in_idx >= 0) {\n        graph_executor->SetInput(in_idx, const_cast<DLTensor*>(value[key].operator->()));\n      }\n    }\n  }\n\n protected:\n  /*! \\brief The execution graph. */\n  std::string graph_json_;\n  /*! \\brief The params. */\n  std::unordered_map<std::string, tvm::runtime::NDArray> params_;\n  /*! \\brief module name */\n  std::string module_name_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nstruct Allocation;\n\nclass HexagonBuffer {\n public:\n  /* \\brief Allocate 1d (contiguous) memory within Hexagon accessible\n   * memory scopes.\n   *\n   * \\param nbytes The number of bytes of physical storage\n   * to allocate.\n   *\n   * \\param alignment The byte alignment to be used when allocating.\n   *\n   * \\param scope Optional storage scope indicating the memory\n   * space in which to allocate. Defaults to global system\n   * memory (DDR).\n   */\n  HexagonBuffer(size_t nbytes, size_t alignment, Optional<String> scope);\n\n  /* \\brief Allocate 2d (discontiguous) memory within Hexagon accessible\n   * memory scopes.\n   *\n   * \\param nallocs The number of allocations.\n   *\n   * \\param nbytes The number of bytes of physical storage\n   * to allocate per allocation.\n   *\n   * \\param alignment The byte alignment to be used when allocating.\n   *\n   * \\param scope Optional storage scope indicating the memory\n   * space in which to allocate. Defaults to global system\n   * memory (DDR).\n   */\n  HexagonBuffer(size_t nallocs, size_t nbytes, size_t alignment, Optional<String> scope);\n\n  //! \\brief Destruction deallocates the underlying allocations.\n  ~HexagonBuffer();\n\n  //! \\brief Prevent copy construction of HexagonBuffers.\n  HexagonBuffer(const HexagonBuffer&) = delete;\n\n  //! \\brief Prevent copy assignment with HexagonBuffers.\n  HexagonBuffer& operator=(const HexagonBuffer&) = delete;\n\n  //! \\brief Prevent move construction.\n  HexagonBuffer(HexagonBuffer&&) = delete;\n\n  //! \\brief Prevent move assignment.\n  HexagonBuffer& operator=(HexagonBuffer&&) = delete;\n\n  /*! \\brief Return data pointer into the buffer\n   *\n   * The returned pointer is intended for use as the runtime value\n   * corresponding to the `Var BufferNode::data` of a buffer.  The\n   * return type depends on the dimensionality of the buffer being\n   * accessed, and must be compatible with the usage defined in\n   * `CodeGenHexagon::CreateBufferPtr`.\n   *\n   * For a 1-d buffer, this pointer can be cast to a `T*` and accessed\n   * as a 1-d array (e.g. `static_cast<int32_t*>(GetPointer())[i]`).\n   * For a 2-d buffer, this pointer can be cast to a `T**` and\n   * accessed as a 2-d array\n   * (e.g. `static_cast<int32_t**>(GetPointer())[i][j]`).\n   */\n  void* GetPointer();\n\n  //! \\brief Memory scopes managed by a Hexagon Buffer.\n  enum class StorageScope {\n    //! \\brief System DDR corresponding to global storage.\n    kDDR,\n    /*! \\brief Vector tightly coupled memory corresponding to\n     *  global.vtcm storage.\n     */\n    kVTCM,\n  };\n\n  //! \\brief Return storage scope of underlying allocation.\n  StorageScope GetStorageScope() const;\n\n  /* \\brief Copy data from a Hexagon Buffer an external buffer.\n   *\n   * \\param data The pointer to the external buffer.\n   *\n   * \\param nbytes The number of bytes to copy.\n   */\n  void CopyTo(void* data, size_t nbytes) const;\n\n  /* \\brief Copy data from an external buffer to a Hexagon Buffer.\n   *\n   * \\param data The pointer to the external buffer.\n   *\n   * \\param nbytes The number of bytes to copy.\n   */\n  void CopyFrom(void* data, size_t nbytes);\n\n  /* \\brief Copy data from one Hexagon Buffer to another.\n   *\n   * \\param other The other Hexagon Buffer.\n   *\n   * \\param nbytes The number of bytes to copy.\n   */\n  void CopyFrom(const HexagonBuffer& other, size_t nbytes);\n\n private:\n  //! \\brief Return the total number of bytes in this buffer\n  size_t TotalBytes() const { return nbytes_per_allocation_ * allocations_.size(); }\n\n  //! \\brief Assign a storage scope to the buffer.\n  void SetStorageScope(Optional<String> scope);\n  /*! \\brief Array of raw pointer allocations required by the buffer.\n   *\n   *  For 1d (contiguous) storage a single allocation will result.\n   *  For 2d (discontiguous) storage `nallocs` allocations will result.\n   */\n  std::vector<void*> allocations_;\n  /*! \\brief Managed allocations which follow RAII and are released\n   *  during destruction.\n   */\n  std::vector<std::unique_ptr<Allocation>> managed_allocations_;\n  /*! \\brief The underlying storage type in which the allocation\n   *  resides.\n   */\n  size_t ndim_;\n  size_t nbytes_per_allocation_;\n  StorageScope storage_scope_;\n};\n\n/*! \\brief Structure used to track/coalesce memory copies */\nstruct MemoryCopy {\n  static std::vector<MemoryCopy> MergeAdjacent(std::vector<MemoryCopy> micro_copies);\n\n  MemoryCopy(void* dest, void* src, size_t num_bytes)\n      : dest(dest), src(src), num_bytes(num_bytes) {}\n\n  bool IsDirectlyBefore(const MemoryCopy& other) {\n    void* src_end = static_cast<unsigned char*>(src) + num_bytes;\n    void* dest_end = static_cast<unsigned char*>(dest) + num_bytes;\n    return (src_end == other.src) && (dest_end == other.dest);\n  }\n\n  void* dest;\n  void* src;\n  size_t num_bytes;\n};\n\n/*!\n */\nstruct BufferSet {\n  // Determine all copies that do not cross boundaries in either\n  // source or destination region.\n  static std::vector<MemoryCopy> MemoryCopies(const BufferSet& dest, const BufferSet& src,\n                                              size_t bytes_to_copy);\n\n  BufferSet(void* const* buffers, size_t num_regions, size_t region_size_bytes)\n      : buffers(buffers), num_regions(num_regions), region_size_bytes(region_size_bytes) {}\n\n  size_t TotalBytes() const { return num_regions * region_size_bytes; }\n\n  void* const* buffers;\n  size_t num_regions;\n  size_t region_size_bytes;\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_buffer_manager.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <memory>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"hexagon_buffer.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nclass HexagonBufferManager {\n public:\n  ~HexagonBufferManager() {\n    if (!hexagon_buffer_map_.empty()) {\n      DLOG(INFO) << \"HexagonBufferManager is not empty upon destruction\";\n    }\n  }\n\n  /*!\n   * \\brief Free a HexagonBuffer.\n   * \\param ptr Address of the HexagonBuffer as returned by `AllocateHexagonBuffer`.\n   */\n  void FreeHexagonBuffer(void* ptr) {\n    std::lock_guard<std::mutex> lock(map_mutex_);\n    auto it = hexagon_buffer_map_.find(ptr);\n    CHECK(it != hexagon_buffer_map_.end())\n        << \"Attempt made to free unknown or already freed allocation\";\n    CHECK(it->second != nullptr);\n    hexagon_buffer_map_.erase(it);\n  }\n  /*!\n   * \\brief Allocate a HexagonBuffer.\n   * \\param args Templated arguments to pass through to HexagonBuffer constructor.\n   */\n  template <typename... Args>\n  void* AllocateHexagonBuffer(Args&&... args) {\n    auto buf = std::make_unique<HexagonBuffer>(std::forward<Args>(args)...);\n    void* ptr = buf->GetPointer();\n    {\n      std::lock_guard<std::mutex> lock(map_mutex_);\n      hexagon_buffer_map_.insert({ptr, std::move(buf)});\n    }\n    return ptr;\n  }\n\n  //! \\brief Returns an iterator to the HexagonBuffer within the map.\n  HexagonBuffer* FindHexagonBuffer(void* ptr) {\n    std::lock_guard<std::mutex> lock(map_mutex_);\n    auto it = hexagon_buffer_map_.find(ptr);\n    if (it != hexagon_buffer_map_.end()) {\n      return it->second.get();\n    }\n    return nullptr;\n  }\n\n private:\n  //! \\brief Contains the HexagonBuffer objects managed by this class.\n  std::unordered_map<void*, std::unique_ptr<HexagonBuffer>> hexagon_buffer_map_;\n\n  //! \\brief Protects updates to the map.\n  std::mutex map_mutex_;\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file hexagon_utils.h\n */\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_\n\n#include <dlpack/dlpack.h>\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/object.h>\n#include <tvm/runtime/packed_func.h>\n\n#if defined(__hexagon__)\n#include <HAP_farf.h>\n#define HEXAGON_PRINT(level, ...) FARF(level, __VA_ARGS__)\n#else\n#include <cstdio>\n#define HEXAGON_PRINT(level, ...) printf(__VA_ARGS__)\n#endif\n\n#define HEXAGON_SAFE_CALL(api_call)                                               \\\n  do {                                                                            \\\n    int result = api_call;                                                        \\\n    if (result != 0) {                                                            \\\n      HEXAGON_PRINT(ERROR, \"ERROR: \" #api_call \" failed with error %d.\", result); \\\n      abort();                                                                    \\\n    }                                                                             \\\n  } while (0)\n\ninline bool IsHexagonDevice(DLDevice dev) { return dev.device_type == kDLHexagon; }\n\nconstexpr int kHexagonAllocAlignment = 2048;\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_device_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_\n\n#include <tvm/runtime/device_api.h>\n\n#include <map>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"hexagon_buffer.h\"\n#include \"hexagon_buffer_manager.h\"\n#include \"hexagon_power_manager.h\"\n#include \"hexagon_thread_manager.h\"\n#include \"hexagon_user_dma.h\"\n#include \"hexagon_vtcm_pool.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\n/*!\n * \\brief Hexagon Device API that is compiled and run on Hexagon.\n */\nclass HexagonDeviceAPI final : public DeviceAPI {\n public:\n  //! \\brief Retrieve the global singleton instance of the HexagonDeviceAPI.\n  static HexagonDeviceAPI* Global();\n\n  //! \\brief Constructor\n  HexagonDeviceAPI() {}\n\n  //! \\brief Destructor\n  ~HexagonDeviceAPI() {}\n\n  //! \\brief Ensures resource managers are in a good state for the runtime\n  void AcquireResources() {\n    CHECK_EQ(runtime_power_manager, nullptr);\n    runtime_power_manager = std::make_unique<HexagonPowerManager>();\n\n    CHECK_EQ(runtime_vtcm, nullptr);\n    runtime_vtcm = std::make_unique<HexagonVtcmPool>();\n\n    CHECK_EQ(runtime_hexbuffs, nullptr);\n    runtime_hexbuffs = std::make_unique<HexagonBufferManager>();\n\n    CHECK_EQ(runtime_threads, nullptr);\n    runtime_threads =\n        std::make_unique<HexagonThreadManager>(threads, stack_size, pipe_size, hw_resources);\n\n    CHECK_EQ(runtime_dma, nullptr);\n    runtime_dma = std::make_unique<HexagonUserDMA>();\n  }\n\n  //! \\brief Ensures all runtime resources are freed\n  void ReleaseResources() {\n    CHECK(runtime_dma) << \"runtime_dma was not created in AcquireResources\";\n    runtime_dma.reset();\n\n    CHECK(runtime_threads) << \"runtime_threads was not created in AcquireResources\";\n    runtime_threads.reset();\n\n    CHECK(runtime_hexbuffs) << \"runtime_hexbuffs was not created in AcquireResources\";\n    runtime_hexbuffs.reset();\n\n    CHECK(runtime_vtcm) << \"runtime_vtcm was not created in AcquireResources\";\n    runtime_vtcm.reset();\n\n    CHECK(runtime_power_manager) << \"runtime_power_manager was not created in AcquireResources\";\n    runtime_power_manager.reset();\n  }\n\n  /*! \\brief Currently unimplemented interface to specify the active\n   *  Hexagon device.\n   */\n  void SetDevice(Device dev) final{};\n\n  //! \\brief Return the queried Hexagon device attribute.\n  void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;\n\n  //! \\brief Currently unimplemented interface to synchronize a device stream.\n  void StreamSync(Device dev, TVMStreamHandle stream) final {}\n\n  //! \\note Standard memory allocation methods of the DeviceAPI interface.\n  //! \\brief Allocate a flat allocation of global memory wrapped in a HexagonBuffer.\n  void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;\n\n  //! \\brief Free the allocated HexagonBuffer.\n  void FreeDataSpace(Device dev, void* ptr) final;\n\n  /*! \\brief Request a dynamically allocated HexagonBuffer from a workspace pool.\n   *  \\returns The underlying allocation pointer.\n   */\n  void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;\n\n  //! Erase from HexagonBufferManager and free\n  void FreeWorkspace(Device dev, void* data) final;\n\n  /*!\n   * \\brief Allocate an Nd data space on device with memory scope support.\n   *\n   * If mem_scope is undefined or is \"global\", treat shape as the\n   * tensor shape, to be flattened into an allocation of 1-d physical\n   * memory.  This is done to maintain the semantics expected by callers of\n   * DeviceAPI::AllocDataSpace, in cases where it has a valid return value.\n   *\n   * For other values of mem_scope, the shape is the N-d physical\n   * shape of the allocation.\n   *\n   * \\param dev The device to perform the operation.\n   * \\param ndim The number of dimensions of allocated tensor.\n   * \\param shape The shape of allocated tensor.\n   * \\param dtype The element type.\n   * \\param mem_scope The memory scope of the allocated tensor.\n   * \\return The allocated HexagonBuffer pointer.\n   */\n  void* AllocDataSpace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,\n                       Optional<String> mem_scope) final;\n\n  /*!\n   * \\brief Allocate an Nd VTCM workspace.\n   * \\param dev The device to perform the operation.\n   * \\param ndim The number of dimensions of allocated tensor.\n   * \\param shape The shape of allocated tensor.\n   * \\param dtype The element type.\n   * \\return The allocated HexagonBuffer pointer.\n   */\n  void* AllocVtcmWorkspace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,\n                           Optional<String> mem_scope);\n\n  //! \\brief Free the allocated Nd VTCM workspace.\n  void FreeVtcmWorkspace(Device dev, void* ptr);\n\n  /*!\n   * \\brief Copy data from one storage to another.\n   * \\note This API is designed to support special memory with shape dependent layout.\n   *       DLTensor's are passed with shape information to support these cases.\n   * \\param from The source array.\n   * \\param to The target array.\n   * \\param stream Optional stream object.\n   */\n  void CopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream) final;\n\n  HexagonThreadManager* ThreadManager() {\n    CHECK(runtime_threads) << \"runtime_threads has not been created\";\n    return runtime_threads.get();\n  }\n\n  HexagonUserDMA* UserDMA() {\n    CHECK(runtime_dma) << \"runtime_dma has not been created\";\n    return runtime_dma.get();\n  }\n\n  HexagonVtcmPool* VtcmPool() {\n    CHECK(runtime_vtcm) << \"runtime_vtcm has not been created\";\n    return runtime_vtcm.get();\n  }\n\n protected:\n  //! Standard Device API interface to copy data from one storage to another.\n  void CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size,\n                      Device dev_from, Device dev_to, DLDataType type_hint,\n                      TVMStreamHandle stream) final;\n\n private:\n  /*! \\brief Helper to check if the device type is valid for the Hexagon Device API\n   *  \\return Boolean indicating whether the device type is valid\n   */\n  bool IsValidDevice(DLDevice dev) {\n    // Added kDLCPU since we use hexagon as a sub-target of LLVM which by default maps to kDLCPU\n    return (dev.device_type == kDLHexagon) || (dev.device_type == kDLCPU);\n  }\n\n  //! \\brief Manages runtime HexagonBuffer allocations\n  // runtime_hexbuffs is used for runtime allocations.  It is created with a call to\n  // AcquireResources, and destroyed on ReleaseResources.  The buffers in this manager are scoped\n  // to the lifetime of a user application session.\n  std::unique_ptr<HexagonBufferManager> runtime_hexbuffs;\n\n  //! \\brief Thread manager\n  std::unique_ptr<HexagonThreadManager> runtime_threads;\n  const unsigned threads{6};\n  const unsigned pipe_size{1000};\n  const unsigned stack_size{0x4000};  // 16KB\n  const std::vector<HardwareResourceType> hw_resources{DMA_0, HTP_0, HVX_0, HVX_1, HVX_2, HVX_3};\n\n  //! \\brief User DMA manager\n  std::unique_ptr<HexagonUserDMA> runtime_dma;\n\n  //! \\brief VTCM memory manager\n  std::unique_ptr<HexagonVtcmPool> runtime_vtcm;\n\n  //! \\brief Hexagon power manager\n  std::unique_ptr<HexagonPowerManager> runtime_power_manager;\n};\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_htp.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nclass HexagonHtp {\n public:\n  //! \\brief Constructor.\n  HexagonHtp();\n\n  //! \\brief Destructor.\n  ~HexagonHtp();\n\n  //! \\brief Prevent copy construction of HexagonHtp.\n  HexagonHtp(const HexagonHtp&) = delete;\n\n  //! \\brief Prevent copy assignment with HexagonHtp.\n  HexagonHtp& operator=(const HexagonHtp&) = delete;\n\n  //! \\brief Prevent move construction.\n  HexagonHtp(HexagonHtp&&) = delete;\n\n  //! \\brief Prevent move assignment.\n  HexagonHtp& operator=(HexagonHtp&&) = delete;\n\n  void Lock();\n  void Unlock();\n\n private:\n  //! \\brief Acquisition context ID\n  unsigned int context_id_;\n\n  void Acquire();\n  void Release();\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_hvx.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nclass HexagonHvx {\n public:\n  //! \\brief Constructor.\n  // TODO(HWE): Pass in a parameter for which HVX instance to bind\n  HexagonHvx();\n\n  //! \\brief Destructor.\n  ~HexagonHvx();\n\n  //! \\brief Prevent copy construction of HexagonHvx.\n  HexagonHvx(const HexagonHvx&) = delete;\n\n  //! \\brief Prevent copy assignment with HexagonHvx.\n  HexagonHvx& operator=(const HexagonHvx&) = delete;\n\n  //! \\brief Prevent move construction.\n  HexagonHvx(HexagonHvx&&) = delete;\n\n  //! \\brief Prevent move assignment.\n  HexagonHvx& operator=(HexagonHvx&&) = delete;\n\n  //! \\brief Lock one HVX to the calling thread.\n  void Lock();\n\n  //! \\brief Unlock the HVX for the calling thread.\n  void Unlock();\n\n  //! \\brief Number of HVX units reserved.\n  int ReservedCount() { return reserved_count_; }\n\n private:\n  int reserved_count_;\n\n  void Acquire();\n  void Release();\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_\n\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/module.h>\n\n#include <array>\n#include <memory>\n#include <set>\n#include <string>\n#include <unordered_map>\n\n#include \"../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Create a Hexagon module from data.\n * \\param data          The module data.\n * \\param fmt           The format of the data, can be \"obj\".\n * \\param fmap          The function information map of each function.\n * \\param asm_str       String with the generated assembly source.\n * \\param obj_str       String with the object file data.\n * \\param ir_str        String with the disassembled LLVM IR source.\n * \\param bc_str        String with the bitcode LLVM IR.\n */\nModule HexagonModuleCreate(std::string data, std::string fmt,\n                           std::unordered_map<std::string, FunctionInfo> fmap, std::string asm_str,\n                           std::string obj_str, std::string ir_str, std::string bc_str);\n\n/*!\n  \\brief Module implementation for compiled Hexagon binaries. It is suitable\n         for managing cross-compiled Hexagon code on a host machine.\n         See docstring for HexagonModuleCreate for\n         construction parameter details.\n */\nclass HexagonModuleNode : public runtime::ModuleNode {\n public:\n  HexagonModuleNode(std::string data, std::string fmt,\n                    std::unordered_map<std::string, FunctionInfo> fmap, std::string asm_str,\n                    std::string obj_str, std::string ir_str, std::string bc_str);\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) override;\n  std::string GetSource(const std::string& format) override;\n  const char* type_key() const final { return \"hexagon\"; }\n  void SaveToFile(const std::string& file_name, const std::string& format) override;\n  void SaveToBinary(dmlc::Stream* stream) override;\n\n protected:\n  std::string data_;\n  std::string fmt_;\n  std::unordered_map<std::string, FunctionInfo> fmap_;\n  std::string asm_;\n  std::string obj_;\n  std::string ir_;\n  std::string bc_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_power_manager.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nclass HexagonPowerManager {\n public:\n  //! \\brief Constructor.\n  HexagonPowerManager();\n\n  //! \\brief Destructor.\n  ~HexagonPowerManager();\n\n  //! \\brief Prevent copy construction of HexagonPowerManager.\n  HexagonPowerManager(const HexagonPowerManager&) = delete;\n\n  //! \\brief Prevent copy assignment with HexagonPowerManager.\n  HexagonPowerManager& operator=(const HexagonPowerManager&) = delete;\n\n  //! \\brief Prevent move construction.\n  HexagonPowerManager(HexagonPowerManager&&) = delete;\n\n  //! \\brief Prevent move assignment.\n  HexagonPowerManager& operator=(HexagonPowerManager&&) = delete;\n\n private:\n  //! \\brief Power context\n  void* hap_pwr_ctx_;\n\n  void PowerOnHVX();\n  void PowerOffHVX();\n  void PowerOnHTP();\n  void PowerOffHTP();\n  void SetAppType();\n  void SetDCVS();\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_thread_manager.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"hexagon_buffer.h\"\n#include \"hexagon_buffer_manager.h\"\n#include \"hexagon_common.h\"\n#include \"hexagon_htp.h\"\n#include \"hexagon_hvx.h\"\n#include \"qurt.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\ntypedef enum {\n  NONE = -1,\n  DMA_0 = 0,\n  HTP_0,\n  HVX_0,\n  HVX_1,\n  HVX_2,\n  HVX_3,\n  MAX,\n} HardwareResourceType;\n\nclass HexagonThreadManager {\n  //! \\brief Void function.\n  using voidfunc = void (*)(void*);\n  //! \\brief Semaphore ID.\n  using SyncPoint = unsigned;\n  //! \\brief Alignment of underlying memory allocations.\n  const unsigned MEM_ALIGNMENT = 32;\n  //! \\brief Minimum stack size in bytes per thread.\n  const unsigned MIN_STACK_SIZE_BYTES = 0x400;  // 1KB\n  //! \\brief Maximum stack size in bytes per thread.\n  const unsigned MAX_STACK_SIZE_BYTES = 0x10000;  // 64KB\n  //! \\brief Minimum pipe (or command buffer) size in words (or commands) per thread.\n  const unsigned MIN_PIPE_SIZE_WORDS = 10;\n  //! \\brief Maximum pipe (or command buffer) size in words (or commands) per thread.\n  const unsigned MAX_PIPE_SIZE_WORDS = 0x10000;  // 64K words\n\n public:\n  /*!\n   * \\brief Spawn a number of Hexagon threads with a given stack (in bytes) and pipe (a.k.a. command\n   * buffer; in words or commands) within the min and max values specified above.\n   * \\param num_threads Number of threads to spawn.\n   * \\param thread_stack_size_bytes Stack size in bytes per thread.\n   * \\param thread_pipe_size_words Pipe (or command buffer) size in words (or commands).\n   */\n  HexagonThreadManager(unsigned, unsigned thread_stack_size_bytes, unsigned thread_pipe_size_words,\n                       const std::vector<HardwareResourceType> = {});\n\n  //! \\brief Destructor\n  ~HexagonThreadManager();\n\n  /*!\n   * \\brief Get the spawned threads as stream handles.\n   * \\returns Vector of stream handles.\n   */\n  const std::vector<TVMStreamHandle> GetStreamHandles();\n\n  /*!\n   * \\brief Get the spawned threads as stream handles for a resource type.\n   * \\returns stream handle.\n   */\n  TVMStreamHandle GetStreamHandleByResourceType(HardwareResourceType type);\n\n  /*!\n   * \\brief Get the resource type for a stream handle\n   * \\returns stream handle.\n   */\n  HardwareResourceType GetResourceTypeForStreamHandle(TVMStreamHandle thread);\n\n  /*!\n   * \\brief Non-blocking dispatch of a void function and args on a given thread.\n   * \\param thread Stream handle of the thread on which to dispatch the void function.\n   * \\param f Void function to be dispatched.\n   * \\param args Arguments to pass to the void function.\n   * \\returns Boolean value indicating success or failure of the dispatch; user must either 1)\n   * `Start` threads executing to clear space in the pipe before retrying dispatch or 2) create a\n   * `HexagonThreadManager` with a larger pipe.\n   */\n  bool Dispatch(TVMStreamHandle thread, voidfunc f, void* args);\n  /*!\n   * \\brief Non-blocking signal of a semaphore with a given ID.\n   * \\param thread Stream handle of the thread which will signal the semaphore.\n   * \\param syncID ID of the semaphore to be signaled.\n   * \\returns Boolean value indicating success or failure of the dispatch of the signal; user must\n   * either 1) `Start` threads executing to clear space in the pipe before retrying dispatch or 2)\n   * create a `HexagonThreadManager` with a larger pipe.\n   */\n  bool Signal(TVMStreamHandle thread, SyncPoint syncID);\n  /*!\n   * \\brief Non-blocking wait on a semaphore with a given ID.\n   * \\param thread Stream handle of the thread which will wait on the semaphore.\n   * \\param syncID ID of the semaphore on which to wait.\n   * \\returns Boolean value indicating success or failure of the dispatch of the wait; user must\n   * either 1) `Start` threads executing to clear space in the pipe before retrying dispatch or 2)\n   * create a `HexagonThreadManager` with a larger pipe.\n   */\n  bool Wait(TVMStreamHandle thread, SyncPoint syncID);\n  /*!\n   * \\brief Creates a synchronization point between two threads by creating a semaphore,\n   *dispatching the `signal_thread` to signal that semaphore and dispatching the `wait_thread to\n   *wait on that semaphore.\n   * \\param signal_thread Stream handle for the thread which will signal the\n   *semaphore.\n   * \\param wait_thread Stream handle for the thread which will wait on the semaphore.\n   * \\returns Boolean value indicating success or failure of the combined dispatch of both the\n   *signal and the wait; user must either 1) `Start` threads executing to clear space in the pipe\n   *before retrying dispatch or 2) create a `HexagonThreadManager` with a larger pipe.\n   */\n  bool SyncFromTo(TVMStreamHandle signal_thread, TVMStreamHandle wait_thread);\n  //! \\brief Unblock threads to start execution.\n  void Start();\n  //! \\brief Unblock threads to start execution if `Start` has not already been called; blocking\n  //! call to wait until all threads have empty pipes.\n  void WaitOnThreads();\n\n private:\n  struct ThreadContext {\n    qurt_pipe_t* pipe;\n    unsigned index;\n    HardwareResourceType resource_type;\n    HexagonHvx* hvx;\n    HexagonHtp* htp;\n    uint64_t status;\n    ThreadContext(qurt_pipe_t* pipe, unsigned index, HardwareResourceType resource_type,\n                  HexagonHvx* hvx, HexagonHtp* htp)\n        : pipe(pipe), index(index), resource_type(resource_type), hvx(hvx), htp(htp), status(0) {\n      CHECK(resource_type == NONE || (hvx && htp))\n          << \"Missing resource manager pointer, type: \" << resource_type << \" hvx: \" << hvx\n          << \" htp: \" << htp;\n    }\n  };\n\n  //! \\brief Helper function to ensure the set of requested resources is valid.\n  void CheckResources();\n\n  //! \\brief Helper function for the constructor to spawn threads.\n  void SpawnThreads(unsigned thread_stack_size_bytes, unsigned thread_pipe_size_words);\n\n  //! \\brief Helper function for `Signal` and `Wait` to create, initialize and map semaphores by ID.\n  void CheckSemaphore(unsigned syncID);\n\n  //! \\brief Void function executed by a thread to signal a semaphore.\n  static void thread_signal(void* semaphore);\n\n  //! \\brief Void function executed by a thread to wait on a semaphore; used by `Wait`.\n  static void thread_wait(void* semaphore);\n\n  //! \\brief Void function executed by a thread to wait on and free a semaphore; used by\n  //! `SyncFromTo`.\n  static void thread_wait_free(void* semaphore);\n\n  //! \\brief Void function executed by a thread to exit at time of destruction.\n  static void thread_exit(void* context);\n\n  //! \\brief Void function executed by each thread as `main`.\n  static void thread_main(void* context);\n\n  //! \\brief Manages underlying HexagonBuffer allocations.\n  HexagonBufferManager hexbuffs_;\n\n  //! \\brief Number of threads allocatted.\n  unsigned nthreads_{0};\n\n  //! \\brief Pointer to the base of the stacks allocated for all threads; size = `nthreads` *\n  //! `thread_stack_size_bytes`.\n  void* stack_buffer_{nullptr};\n\n  //! \\brief Pointer to the base of the pipes (or command buffers) allocated for all threads; size =\n  //! `nthreads` * `thread_pipe_size_words` * sizeof(word).\n  void* pipe_buffer_{nullptr};\n\n  //! \\brief QURT thread structure for each spawned thread.\n  std::vector<qurt_thread_t> threads_;\n\n  //! \\brief QURT pipe (or command buffer) structure for each spawned thread.\n  std::vector<qurt_pipe_t> pipes_;\n\n  //! \\brief Thread context passed into each `thread_main` function.\n  std::vector<ThreadContext*> contexts_;\n\n  //! \\brief Semaphores used by `Signal` and `Wait` mapped by ID.\n  std::unordered_map<unsigned, qurt_sem_t*> semaphores_;\n\n  //! \\brief Start semaphore created at time of construction; signled by `Start`.\n  qurt_sem_t start_semaphore_;\n\n  /*!\n   *\\brief Encapsulate a void function pointer + arg pointer; sent via pipe to threads to execute.\n   */\n  struct Command {\n    voidfunc f;\n    void* args;\n    Command(voidfunc f, void* args) : f(f), args(args) {}\n  };\n\n  //! \\brief List of hardware resources\n  std::vector<HardwareResourceType> hw_resources_;\n\n  //! \\brief Whether or not resource managers should be created\n  bool create_resource_managers_{false};\n\n  //! \\brief HTP hardware resource.\n  // TODO(HWE): Move binding of HTP to a specific thread\n  std::unique_ptr<HexagonHtp> htp_;\n\n  //! \\brief HVX hardware resource.\n  // TODO(HWE): Move binding of individual HVX instances to a specific thread\n  std::unique_ptr<HexagonHvx> hvx_;\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_user_dma.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_\n\n#include \"hexagon_common.h\"\n#include \"hexagon_user_dma_descriptors.h\"\n#include \"hexagon_user_dma_instructions.h\"\n#include \"hexagon_user_dma_registers.h\"\n#include \"ring_buffer.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\n#define DMA_SUCCESS 0\n#define DMA_FAILURE -1\n#define DMA_RETRY 1\n#define MAX_DMA_DESCRIPTORS 100\n#define SYNC_DMA_QUEUE -1\n\nclass HexagonUserDMA {\n public:\n  HexagonUserDMA();\n  ~HexagonUserDMA();\n  HexagonUserDMA(const HexagonUserDMA&) = delete;\n  HexagonUserDMA& operator=(const HexagonUserDMA&) = delete;\n  HexagonUserDMA(HexagonUserDMA&&) = delete;\n  HexagonUserDMA& operator=(HexagonUserDMA&&) = delete;\n\n  /*!\n   * \\brief Initiate DMA to copy memory from source to destination address\n   * \\param dst Destination address\n   * \\param src Source address\n   * \\param length Length in bytes to copy\n   * \\returns Status: DMA_SUCCESS or DMA_FAILURE\n   */\n  int Copy(int queue_id, void* dst, void* src, uint32_t length);\n\n  /*!\n   * \\brief Wait until the number of DMAs in flight is less than or equal to some maximum\n   * \\param max_dmas_in_flight Maximum number of DMAs allowed to be in flight\n   * to satisfy the `Wait` e.g. use `Wait(0)` to wait on \"all\" outstanding DMAs to complete\n   */\n  void Wait(int queue_id, uint32_t max_dmas_in_flight);\n\n  /*!\n   * \\brief Poll the number of DMAs in flight\n   * \\returns Number of DMAs in flight\n   */\n  uint32_t Poll(int queue_id);\n\n private:\n  //! \\brief Initializes the Hexagon User DMA engine\n  unsigned int Init();\n\n  //! \\brief Calculates and returns the number of DMAs in flight\n  uint32_t DMAsInFlight(int queue_id);\n\n  //! \\brief Tracks whether the very first DMA has been executed\n  bool first_dma_ = true;\n\n  //! \\brief Tracks the tail DMA descriptor\n  void* tail_dma_desc_ = nullptr;\n\n  //! \\brief Storage for all DMA descriptors\n  QueuedRingBuffer<dma_desc_2d_t>* descriptors_ = nullptr;\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_user_dma_descriptors.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\n// NOTE: Using 2D descriptor size even for 1D descriptors\n#define DMA_DESC_2D_SIZE 32\n\n// DMA State\n// desc[0][3:0]\n#define DESC_STATE_MASK 0x0000000F\n#define DESC_STATE_SHIFT 0\n#define DESC_STATE_READY 0\n\n// desc[0][31:4]\n// Descriptors addresses must be (minimum) 16 byte aligned\n// -> Lower 4 bits masked to clear DMA Status\n// -> But, descriptor address is not shifted\n#define DESC_NEXT_MASK 0xFFFFFFF0\n#define DESC_NEXT_SHIFT 0\n\n// desc[1][23:0]\n#define DESC_LENGTH_MASK 0x00FFFFFF\n#define DESC_LENGTH_SHIFT 0\n\n// desc[1][25:24]\n#define DESC_DESCTYPE_MASK 0x03000000\n#define DESC_DESCTYPE_SHIFT 24\n#define DESC_DESCTYPE_1D 0\n#define DESC_DESCTYPE_2D 1\n\n// TODO(Straw): Definition?  Not in the spec.\n// desc[1][26]\n#define DESC_DSTCOMP_MASK 0x04000000\n#define DESC_DSTCOMP_SHIFT 26\n// desc[1][27]\n#define DESC_SRCCOMP_MASK 0x08000000\n#define DESC_SRCCOMP_SHIFT 27\n#define DESC_COMP_NONE 0\n#define DESC_COMP_DLBC 1\n\n// desc[1][28]\n#define DESC_BYPASSDST_MASK 0x10000000\n#define DESC_BYPASSDST_SHIFT 28\n// desc[1][29]\n#define DESC_BYPASSSRC_MASK 0x20000000\n#define DESC_BYPASSSRC_SHIFT 29\n#define DESC_BYPASS_OFF 0\n#define DESC_BYPASS_ON 1\n\n// desc[1][30]\n#define DESC_ORDER_MASK 0x40000000\n#define DESC_ORDER_SHIFT 30\n#define DESC_ORDER_NOORDER 0\n#define DESC_ORDER_ORDER 1\n\n// desc[1][31]\n#define DESC_DONE_MASK 0x80000000\n#define DESC_DONE_SHIFT 31\n#define DESC_DONE_INCOMPLETE 0\n#define DESC_DONE_COMPLETE 1\n\n// desc[2]\n#define DESC_SRC_MASK 0xFFFFFFFF\n#define DESC_SRC_SHIFT 0\n\n// desc[3]\n#define DESC_DST_MASK 0xFFFFFFFF\n#define DESC_DST_SHIFT 0\n\n// desc[4][25:24]\n#define DESC_CACHEALLOC_MASK 0x03000000\n#define DESC_CACHEALLOC_SHIFT 24\n#define DESC_CACHEALLOC_NONE 0\n#define DESC_CACHEALLOC_WRITEONLY 1\n#define DESC_CACHEALLOC_READONLY 2\n#define DESC_CACHEALLOC_READWRITE 3\n\n// TODO(Straw): Definition?  Not in the spec.\n// desc[4][31:28]\n#define DESC_PADDING_MASK 0xF0000000\n#define DESC_PADDING_SHIFT 28\n\n// desc[5][15:0]\n#define DESC_ROIWIDTH_MASK 0x0000FFFF\n#define DESC_ROIWIDTH_SHIFT 0\n\n// desc[5][31:16]\n#define DESC_ROIHEIGHT_MASK 0xFFFF0000\n#define DESC_ROIHEIGHT_SHIFT 16\n\n// desc[6][15:0]\n#define DESC_SRCSTRIDE_MASK 0x0000FFFF\n#define DESC_SRCSTRIDE_SHIFT 0\n\n// desc[6][31:16]\n#define DESC_DSTSTRIDE_MASK 0xFFFF0000\n#define DESC_DSTSTRIDE_SHIFT 16\n\n// desc[7][15:0]\n#define DESC_SRCWIDTHOFFSET_MASK 0x0000FFFF\n#define DESC_SRCWIDTHOFFSET_SHIFT 0\n\n// desc[7][31:16]\n#define DESC_DSTWIDTHOFFSET_MASK 0xFFFF0000\n#define DESC_DSTWIDTHOFFSET_SHIFT 16\n\n#define DMA_NULL_PTR 0\n\n/**************************/\n/* 1D (linear) descriptor */\n/**************************/\nstruct dma_desc_1d_t {\n  unsigned int next_state;\n  unsigned int done_order_bypass_comp_desctype_length;\n  unsigned int src;\n  unsigned int dst;\n};\n\n/***********************/\n/* 2D (box) descriptor */\n/***********************/\nstruct dma_desc_2d_t {\n  unsigned int next_state;\n  unsigned int done_order_bypass_comp_desctype_length;\n  unsigned int src;\n  unsigned int dst;\n  unsigned int allocation_padding;\n  unsigned int roiheight_roiwidth;\n  unsigned int dststride_srcstride;\n  unsigned int dstwidthoffset_srcwidthoffset;\n};\n\n// desc[0][3:0]\ninline void dma_desc_set_state(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->next_state) &= ~DESC_STATE_MASK;\n  (dma_desc_1d_ptr->next_state) |= ((v << DESC_STATE_SHIFT) & DESC_STATE_MASK);\n}\n\n// desc[0][31:4]\ninline void dma_desc_set_next(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->next_state) &= ~DESC_NEXT_MASK;\n  (dma_desc_1d_ptr->next_state) |= ((v << DESC_NEXT_SHIFT) & DESC_NEXT_MASK);\n}\n\n// desc[1][23:0]\ninline void dma_desc_set_length(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_LENGTH_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_LENGTH_SHIFT) & DESC_LENGTH_MASK);\n}\n\n// desc[1][25:24]\ninline void dma_desc_set_desctype(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DESCTYPE_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_DESCTYPE_SHIFT) & DESC_DESCTYPE_MASK);\n}\n\n// TODO(Straw): Definition?  Not in the spec.\n// desc[1][26]\ninline void dma_desc_set_dstcomp(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DSTCOMP_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_DSTCOMP_SHIFT) & DESC_DSTCOMP_MASK);\n}\n\n// TODO(Straw): Definition?  Not in the spec.\n// desc[1][27]\ninline void dma_desc_set_srccomp(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_SRCCOMP_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_SRCCOMP_SHIFT) & DESC_SRCCOMP_MASK);\n}\n\n// desc[1][28]\ninline void dma_desc_set_bypassdst(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_BYPASSDST_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_BYPASSDST_SHIFT) & DESC_BYPASSDST_MASK);\n}\n\n// desc[1][29]\ninline void dma_desc_set_bypasssrc(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_BYPASSSRC_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_BYPASSSRC_SHIFT) & DESC_BYPASSSRC_MASK);\n}\n\n// desc[1][30]\ninline void dma_desc_set_order(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_ORDER_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_ORDER_SHIFT) & DESC_ORDER_MASK);\n}\n\n// desc[1][31]\ninline void dma_desc_set_done(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DONE_MASK;\n  (dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=\n      ((v << DESC_DONE_SHIFT) & DESC_DONE_MASK);\n}\n\n// desc[1][31]\ninline unsigned int dma_desc_get_done(void* dma_desc_ptr) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  return (((dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) & DESC_DONE_MASK) >>\n          DESC_DONE_SHIFT);\n}\n\n// desc[2]\ninline void dma_desc_set_src(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->src) &= ~DESC_SRC_MASK;\n  (dma_desc_1d_ptr->src) |= ((v << DESC_SRC_SHIFT) & DESC_SRC_MASK);\n}\n\n// desc[3]\ninline void dma_desc_set_dst(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);\n  (dma_desc_1d_ptr->dst) &= ~DESC_DST_MASK;\n  (dma_desc_1d_ptr->dst) |= ((v << DESC_DST_SHIFT) & DESC_DST_MASK);\n}\n\n// desc[4][25:24]\ninline void dma_desc_set_cachealloc(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->allocation_padding) &= ~DESC_CACHEALLOC_MASK;\n  (dma_desc_2d_ptr->allocation_padding) |= ((v << DESC_CACHEALLOC_SHIFT) & DESC_CACHEALLOC_MASK);\n}\n\n// TODO(Straw): Definition?  Not in the spec.\n// desc[4][31:28]\ninline void dma_desc_set_padding(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->allocation_padding) &= ~DESC_PADDING_MASK;\n  (dma_desc_2d_ptr->allocation_padding) |= ((v << DESC_PADDING_SHIFT) & DESC_PADDING_MASK);\n}\n\n// desc[5][15:0]\ninline void dma_desc_set_roiwidth(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->roiheight_roiwidth) &= ~DESC_ROIWIDTH_MASK;\n  (dma_desc_2d_ptr->roiheight_roiwidth) |= ((v << DESC_ROIWIDTH_SHIFT) & DESC_ROIWIDTH_MASK);\n}\n\n// desc[5][31:16]\ninline void dma_desc_set_roiheight(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->roiheight_roiwidth) &= ~DESC_ROIHEIGHT_MASK;\n  (dma_desc_2d_ptr->roiheight_roiwidth) |= ((v << DESC_ROIHEIGHT_SHIFT) & DESC_ROIHEIGHT_MASK);\n}\n\n// desc[6][15:0]\ninline void dma_desc_set_srcstride(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->dststride_srcstride) &= ~DESC_SRCSTRIDE_MASK;\n  (dma_desc_2d_ptr->dststride_srcstride) |= ((v << DESC_SRCSTRIDE_SHIFT) & DESC_SRCSTRIDE_MASK);\n}\n\n// desc[6][31:16]\ninline void dma_desc_set_dststride(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->dststride_srcstride) &= ~DESC_DSTSTRIDE_MASK;\n  (dma_desc_2d_ptr->dststride_srcstride) |= ((v << DESC_DSTSTRIDE_SHIFT) & DESC_DSTSTRIDE_MASK);\n}\n\n// desc[7][15:0]\ninline void dma_desc_set_srcwidthoffset(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) &= ~DESC_SRCWIDTHOFFSET_MASK;\n  (dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) |=\n      ((v << DESC_SRCWIDTHOFFSET_SHIFT) & DESC_SRCWIDTHOFFSET_MASK);\n}\n\n// desc[7][31:16]\ninline void dma_desc_set_dstwidthoffset(void* dma_desc_ptr, unsigned int v) {\n  dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);\n  (dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) &= ~DESC_DSTWIDTHOFFSET_MASK;\n  (dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) |=\n      ((v << DESC_DSTWIDTHOFFSET_SHIFT) & DESC_DSTWIDTHOFFSET_MASK);\n}\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_user_dma_instructions.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\ninline unsigned int dmpause() {\n  unsigned int dm0 = 0;\n  asm volatile(\" %0 = dmpause\" : \"=r\"(dm0));\n  return dm0;\n}\n\ninline void dmstart(void* next) { asm volatile(\" dmstart(%0)\" : : \"r\"(next)); }\n\ninline void dmlink(void* tail, void* next) {\n  asm volatile(\" dmlink(%0, %1)\" : : \"r\"(tail), \"r\"(next));\n}\n\ninline unsigned int dmpoll() {\n  unsigned int dm0 = 0;\n  asm volatile(\" %0 = dmpoll\" : \"=r\"(dm0));\n  return dm0;\n}\n\ninline unsigned int dmwait() {\n  unsigned int dm0 = 0;\n  asm volatile(\" %0 = dmwait\" : \"=r\"(dm0));\n  return dm0;\n}\n\ninline void dmresume(unsigned int dm0) { asm volatile(\" dmresume(%0)\" : : \"r\"(dm0)); }\n\ninline unsigned int dmsyncht() {\n  unsigned int dm0 = 0;\n  asm volatile(\" %0 = dmsyncht\" : \"=r\"(dm0));\n  return dm0;\n}\n\ninline unsigned int dmtlbsynch() {\n  unsigned int dm0 = 0;\n  asm volatile(\" %0 = dmtlbsynch\" : \"=r\"(dm0));\n  return dm0;\n}\n\ninline unsigned int dmcfgrd(unsigned int dmindex) {\n  unsigned int data = 0;\n  asm volatile(\" %0 = dmcfgrd(%1)\" : \"=r\"(data) : \"r\"(dmindex));\n  return data;\n}\n\ninline void dmcfgwr(unsigned int dmindex, unsigned int data) {\n  asm volatile(\" dmcfgwr(%0, %1)\" : : \"r\"(dmindex), \"r\"(data));\n}\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_user_dma_registers.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\n/* Register offset */\n#define regDM0 0x0  // per engine configuration\n#define regDM1 0x1  // reserved\n#define regDM2 0x2  // global control shared by all DMA Engines\n#define regDM3 0x3  // reserved\n#define regDM4 0x4  // global error syndrome register shared by all DMA Engines\n#define regDM5 0x5  // global error syndrome register shared by all DMA Engines\n\n// DM0[1:0]\n#define DM0_STATUS_MASK 0x00000003\n#define DM0_STATUS_SHIFT 0\n#define DM0_STATUS_IDLE 0\n#define DM0_STATUS_RUN 1\n#define DM0_STATUS_ERROR 2\n\n// DM0[31:4]\n// Descriptors addresses must be (minimum) 16 byte aligned\n// -> Lower 4 bits masked to clear DMA Status\n// -> But, descriptor address is not shifted\n#define DM0_DESC_ADDR_MASK 0xFFFFFFF0\n#define DM0_DESC_ADDR_SHIFT 0\n\n// DM2[0]\n#define DM2_GUEST_MODE_STALL_MASK 0x00000001\n#define DM2_GUEST_MODE_STALL_SHIFT 0\n#define DM2_GUEST_MODE_STALL_YES 0\n#define DM2_GUEST_MODE_STALL_NO 1\n\n// DM2[1]\n#define DM2_MONITOR_MODE_STALL_MASK 0x00000002\n#define DM2_MONITOR_MODE_STALL_SHIFT 1\n#define DM2_MONITOR_MODE_STALL_YES 0\n#define DM2_MONITOR_MODE_STALL_NO 1\n\n// DM2[3]\n#define DM2_EXCEPTION_MODE_CONTINUE_MASK 0x00000008\n#define DM2_EXCEPTION_MODE_CONTINUE_SHIFT 3\n#define DM2_EXCEPTION_MODE_CONTINUE_YES 0\n#define DM2_EXCEPTION_MODE_CONTINUE_NO 1\n\n// DM2[4]\n#define DM2_DEBUG_MODE_CONTINUE_MASK 0x00000010\n#define DM2_DEBUG_MODE_CONTINUE_SHIFT 4\n#define DM2_DEBUG_MODE_CONTINUE_NO 0\n#define DM2_DEBUG_MODE_CONTINUE_YES 1\n\n// DM2[6:5]\n#define DM2_TRAFFIC_PRIORITY_MASK 0x00000060\n#define DM2_TRAFFIC_PRIORITY_SHIFT 5\n#define DM2_TRAFFIC_PRIORITY_IDLE 0\n#define DM2_TRAFFIC_PRIORITY_LOW 1\n#define DM2_TRAFFIC_PRIORITY_INHERIT 2\n#define DM2_TRAFFIC_PRIORITY_HIGH 3\n\n// DM2[7]\n#define DM2_DLBC_ENABLE_MASK 0x00000080\n#define DM2_DLBC_ENABLE_SHIFT 7\n#define DM2_DLBC_DISABLE 0\n#define DM2_DLBC_ENABLE 1\n\n// DM2[8]\n#define DM2_OOO_WRITE_MASK 0x00000100\n#define DM2_OOO_WRITE_SHIFT 8\n#define DM2_OOO_WRITE_ENABLE 0\n#define DM2_OOO_WRITE_DISABLE 1\n\n// DM2[9]\n#define DM2_ERROR_EXCEPTION_MASK 0x00000200\n#define DM2_ERROR_EXCEPTION_SHIFT 9\n#define DM2_ERROR_EXCEPTION_GENERATE_NO 0\n#define DM2_ERROR_EXCEPTION_GENERATE_YES 1\n\n// DM2[23:16]\n#define DM2_OUTSTANDING_READ_MASK 0x00FF0000\n#define DM2_OUTSTANDING_READ_SHIFT 16\n\n// DM2[31:24]\n#define DM2_OUTSTANDING_WRITE_MASK 0xFF000000\n#define DM2_OUTSTANDING_WRITE_SHIFT 24\n\n// DM4[0]\n#define DM4_ERROR_MASK 0x00000001\n#define DM4_ERROR_SHIFT 0\n#define DM4_ERROR_NO 0\n#define DM4_ERROR_YES 1\n\n// DM4[7:4]\n#define DM4_THREAD_ID_MASK 0x000000F0\n#define DM4_THREAD_ID_SHIFT 4\n\n// DM4[15:8]\n#define DM4_SYNDRONE_CODE_MASK 0x0000FF00\n#define DM4_SYNDRONE_CODE_SHIFT 8\n#define DM4_SYNDRONE_CODE_DM_COMMAND_ERROR 0\n#define DM4_SYNDRONE_CODE_DESCRIPTOR_INVALID_ALIGNMENT 1\n#define DM4_SYNDRONE_CODE_DESCRIPTOR_INVALID_TYPE 2\n#define DM4_SYNDRONE_CODE_UNSUPPORTED_ADDRESS 3\n#define DM4_SYNDRONE_CODE_UNSUPPORTED_BYPASS_MODE 4\n#define DM4_SYNDRONE_CODE_UNSUPPORTED_COMP_FORMAT 5\n#define DM4_SYNDRONE_CODE_DESCRIPTOR_ROI_ERROR 6\n#define DM4_SYNDRONE_CODE_BUS_ERROR_DESCRIPTOR_RW 7\n#define DM4_SYNDRONE_CODE_BUS_ERROR_L2_READ 8\n#define DM4_SYNDRONE_CODE_BUS_ERROR_L2_WRITE 9\n// TODO(Straw): Bus Error (10) on Compression Metadata?\n// TODO(Straw): Definition? Not in the spec.\n#define DM4_SYNDRONE_CODE_INVALID_ACCESS_RIGHTS 102\n#define DM4_SYNDRONE_CODE_DATA_TIMEOUT 103\n#define DM4_SYNDRONE_CODE_DATA_ABORT 104\n\n// DM5\n#define DM5_SYNDRONE_ADDR_MASK 0xFFFFFFFF\n#define DM5_SYNDRONE_ADDR_SHIFT 0\n\n// DM2[0]\nstatic inline unsigned int dm2_get_guest_mode(unsigned int cfg) {\n  return (cfg & DM2_GUEST_MODE_STALL_MASK) >> DM2_GUEST_MODE_STALL_SHIFT;\n}\n\n// DM2[0]\nstatic inline void dm2_set_guest_mode(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_GUEST_MODE_STALL_MASK;\n  *cfg |= ((v << DM2_GUEST_MODE_STALL_SHIFT) & DM2_GUEST_MODE_STALL_MASK);\n}\n\n// DM2[1]\nstatic inline unsigned int dm2_get_monitor_mode(unsigned int cfg) {\n  return (cfg & DM2_MONITOR_MODE_STALL_MASK) >> DM2_MONITOR_MODE_STALL_SHIFT;\n}\n\n// DM2[1]\nstatic inline void dm2_set_monitor_mode(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_MONITOR_MODE_STALL_MASK;\n  *cfg |= ((v << DM2_MONITOR_MODE_STALL_SHIFT) & DM2_MONITOR_MODE_STALL_MASK);\n}\n\n// DM2[3]\nstatic inline unsigned int dm2_get_exception_mode(unsigned int cfg) {\n  return (cfg & DM2_EXCEPTION_MODE_CONTINUE_MASK) >> DM2_EXCEPTION_MODE_CONTINUE_SHIFT;\n}\n\n// DM2[3]\nstatic inline void dm2_set_exception_mode(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_EXCEPTION_MODE_CONTINUE_MASK;\n  *cfg |= ((v << DM2_EXCEPTION_MODE_CONTINUE_SHIFT) & DM2_EXCEPTION_MODE_CONTINUE_MASK);\n}\n\n// DM2[4]\nstatic inline unsigned int dm2_get_debug_mode(unsigned int cfg) {\n  return (cfg & DM2_DEBUG_MODE_CONTINUE_MASK) >> DM2_DEBUG_MODE_CONTINUE_SHIFT;\n}\n\n// DM2[4]\nstatic inline void dm2_set_debug_mode(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_DEBUG_MODE_CONTINUE_MASK;\n  *cfg |= ((v << DM2_DEBUG_MODE_CONTINUE_SHIFT) & DM2_DEBUG_MODE_CONTINUE_MASK);\n}\n\n// DM2[6:5]\nstatic inline unsigned int dm2_get_priority(unsigned int cfg) {\n  return (cfg & DM2_TRAFFIC_PRIORITY_MASK) >> DM2_TRAFFIC_PRIORITY_SHIFT;\n}\n\n// DM2[6:5]\nstatic inline void dm2_set_priority(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_TRAFFIC_PRIORITY_MASK;\n  *cfg |= ((v << DM2_TRAFFIC_PRIORITY_SHIFT) & DM2_TRAFFIC_PRIORITY_MASK);\n}\n\n// DM2[7]\nstatic inline unsigned int dm2_get_dlbc_enable(unsigned int cfg) {\n  return (cfg & DM2_DLBC_ENABLE_MASK) >> DM2_DLBC_ENABLE_SHIFT;\n}\n\n// DM2[7]\nstatic inline void dm2_set_dlbc_enable(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_DLBC_ENABLE_MASK;\n  *cfg |= ((v << DM2_DLBC_ENABLE_SHIFT) & DM2_DLBC_ENABLE_MASK);\n}\n\n// DM2[8]\nstatic inline unsigned int dm2_get_ooo_write_ctrl(unsigned int cfg) {\n  return (cfg & DM2_OOO_WRITE_MASK) >> DM2_OOO_WRITE_SHIFT;\n}\n\n// DM2[8]\nstatic inline void dm2_set_ooo_write_ctrl(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_OOO_WRITE_MASK;\n  *cfg |= ((v << DM2_OOO_WRITE_SHIFT) & DM2_OOO_WRITE_MASK);\n}\n\n// DM2[9]\nstatic inline unsigned int dm2_get_error_exception_ctrl(unsigned int cfg) {\n  return (cfg & DM2_ERROR_EXCEPTION_MASK) >> DM2_ERROR_EXCEPTION_SHIFT;\n}\n\n// DM2[9]\nstatic inline void dm2_set_error_exception_ctrl(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_ERROR_EXCEPTION_MASK;\n  *cfg |= ((v << DM2_ERROR_EXCEPTION_SHIFT) & DM2_ERROR_EXCEPTION_MASK);\n}\n\n// DM2[23:16]\nstatic inline unsigned int dm2_get_outstanding_transactions_read(unsigned int cfg) {\n  return (cfg & DM2_OUTSTANDING_READ_MASK) >> DM2_OUTSTANDING_READ_SHIFT;\n}\n\n// DM2[23:16]\nstatic inline void dm2_set_outstanding_transactions_read(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_OUTSTANDING_READ_MASK;\n  *cfg |= ((v << DM2_OUTSTANDING_READ_SHIFT) & DM2_OUTSTANDING_READ_MASK);\n}\n\n// DM2[31:24]\nstatic inline unsigned int dm2_get_outstanding_transactions_write(unsigned int cfg) {\n  return (cfg & DM2_OUTSTANDING_WRITE_MASK) >> DM2_OUTSTANDING_WRITE_SHIFT;\n}\n\n// DM2[31:24]\nstatic inline void dm2_set_outstanding_transactions_write(unsigned int* cfg, unsigned int v) {\n  *cfg &= ~DM2_OUTSTANDING_WRITE_MASK;\n  *cfg |= ((v << DM2_OUTSTANDING_WRITE_SHIFT) & DM2_OUTSTANDING_WRITE_MASK);\n}\n\n/*--------------------------------------------------------------------------*/\n\n// DM4[0]\nstatic inline unsigned int dm4_get_error(unsigned int cfg) {\n  return (cfg & DM4_ERROR_MASK) >> DM4_ERROR_SHIFT;\n}\n\n// DM4[7:4]\nstatic inline unsigned int dm4_get_engine_id(unsigned int cfg) {\n  return (cfg & DM4_THREAD_ID_MASK) >> DM4_THREAD_ID_SHIFT;\n}\n\n// DM4[15:8]\nstatic inline unsigned int dm4_get_syndrone_code(unsigned int cfg) {\n  return (cfg & DM4_SYNDRONE_CODE_MASK) >> DM4_SYNDRONE_CODE_SHIFT;\n}\n\n/*--------------------------------------------------------------------------*/\n\n// DM5\nstatic inline unsigned int dm5_get_syndrone_addr(unsigned int cfg) {\n  return (cfg & DM5_SYNDRONE_ADDR_MASK) >> DM5_SYNDRONE_ADDR_SHIFT;\n}\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/hexagon_vtcm_pool.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_\n#define TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\nclass HexagonVtcmPool {\n public:\n  //! \\brief Allocates all of VTCM memory, and manages allocations from the runtime\n  HexagonVtcmPool();\n\n  //! \\brief Destruction deallocates the underlying VTCM allocation.\n  ~HexagonVtcmPool();\n\n  //! \\brief Prevent copy construction of HexagonVtcmPool.\n  HexagonVtcmPool(const HexagonVtcmPool&) = delete;\n\n  //! \\brief Prevent copy assignment with HexagonVtcmPool.\n  HexagonVtcmPool& operator=(const HexagonVtcmPool&) = delete;\n\n  //! \\brief Prevent move construction.\n  HexagonVtcmPool(HexagonVtcmPool&&) = delete;\n\n  //! \\brief Prevent move assignment.\n  HexagonVtcmPool& operator=(HexagonVtcmPool&&) = delete;\n\n  /* \\brief Allocate memory from the VTCM manager\n   *\n   * \\param nbytes The number of bytes to allocate.\n   */\n  void* Allocate(size_t nbytes);\n\n  /* \\brief Copy data from a Hexagon Buffer an external buffer.\n   *\n   * \\param ptr The pointer to the buffer to be freed.\n   *\n   * \\param nbytes The number of bytes to be freed.\n   */\n  void Free(void* ptr, size_t nbytes);\n\n  //! \\brief Returns the total number of bytes in this pool\n  size_t TotalBytes() { return reinterpret_cast<size_t>(vtcm_size_); }\n\n private:\n  //! \\brief Total size of VTCM pool\n  unsigned int vtcm_size_;\n\n  //! \\brief Pointer to the beginning of the pool\n  void* vtcm_data_;\n\n  //! \\brief Context for HAP_compute_res_*\n  unsigned int context_id_{0};\n\n  //! \\brief List of allocations\n  std::vector<std::pair<char*, size_t>> allocations_;\n\n  //! \\brief List of free segments\n  std::vector<std::pair<char*, size_t>> free_;\n\n  //! \\brief Mutext to protect access to the lists\n  std::mutex mutex_;\n\n  //! \\brief Debug only dump of the state of the lists\n  void DebugDump();\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/profiler/prof_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file prof_utils.h\n */\n#ifndef TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_\n#define TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_\n\n#include <string>\n\nbool WriteLWPOutput(const std::string&);\n\n#endif  // TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/ring_buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_RING_BUFFER_H_\n#define TVM_RUNTIME_HEXAGON_RING_BUFFER_H_\n\n#include <functional>\n#include <vector>\n\n#include \"hexagon_common.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace hexagon {\n\ntemplate <class T>\nclass RingBuffer {\n public:\n  //! \\brief Returns the number of Ts in flight\n  uint32_t InFlight() {\n    while (id_oldest_ < id_next_ && !in_flight_(GetAddr(id_oldest_))) {\n      id_oldest_++;\n    }\n    return id_next_ - id_oldest_;\n  }\n\n  //! \\brief Returns pointer to next T; null if ring buffer is full\n  T* Next() {\n    if (InFlight() == ring_buff_size_) {\n      return nullptr;\n    }\n    T* next = GetAddr(id_next_);\n    id_next_++;\n    return next;\n  }\n\n  /*! \\brief Creates a ring buffer for storage items of type T\n   *  \\param ring_buff_size Size of the ring buffer in number of Ts\n   *  \\param in_flight Function that determines whether a T is in flight\n   */\n  RingBuffer(uint32_t ring_buff_size, std::function<bool(T*)> in_flight)\n      : ring_buff_size_(ring_buff_size), in_flight_(in_flight) {\n    CHECK_NE(ring_buff_size, 0);\n    int ret = posix_memalign(reinterpret_cast<void**>(&ring_buff_ptr_), sizeof(T),\n                             sizeof(T) * ring_buff_size_);\n    CHECK_EQ(ret, 0);\n    CHECK_NE(ring_buff_ptr_, nullptr);\n  }\n\n  ~RingBuffer() { free(ring_buff_ptr_); }\n\n private:\n  //! \\brief Returns the address of a T given its index\n  T* GetAddr(uint32_t id) const {\n    uint32_t ring_buff_index = id % ring_buff_size_;\n    return ring_buff_ptr_ + ring_buff_index;\n  }\n\n  //! \\brief Pointer to the ring buffer\n  T* ring_buff_ptr_ = nullptr;\n\n  //! \\brief Size of the ring buffer in number of Ts\n  const uint32_t ring_buff_size_ = 0;\n\n  //! \\brief Function that determines whether a T is in flight\n  const std::function<bool(T*)> in_flight_;\n\n  //! \\brief Tracks the ID of the next T to be added to the ring buffer\n  uint32_t id_next_ = 0;\n\n  //! \\brief Tracks the ID of the oldest T in flight\n  uint32_t id_oldest_ = 0;\n};\n\n//! \\brief Separates a single RingBuffer into multiple virtual queues with each queue having a\n//! unique integer ID; queues allow for indepent users of the same RingBuffer while mainting overall\n//! FIFO ordering among all queues\ntemplate <class T>\nclass QueuedRingBuffer : RingBuffer<T> {\n public:\n  QueuedRingBuffer(uint32_t ring_buff_size, std::function<bool(T*)> in_flight)\n      : RingBuffer<T>(ring_buff_size, in_flight) {}\n\n  //! \\brief Returns pointer to next T; add the queue ID for tracking\n  T* Next(int queue_id) {\n    queue_ids_.push_back(queue_id);\n    return RingBuffer<T>::Next();\n  }\n\n  //! \\brief Returns the number of Ts in flight for a given queue ID\n  uint32_t InFlight(int queue_id) {\n    uint32_t in_flight = 0;\n    // look at the queue IDs for the RingBuffer entries in flight\n    for (size_t i = queue_ids_.size() - RingBuffer<T>::InFlight(); i < queue_ids_.size(); ++i) {\n      // increment return value if in flight queue ID matches\n      if (queue_ids_[i] == queue_id) {\n        in_flight++;\n      }\n    }\n    return in_flight;\n  }\n\n private:\n  std::vector<int> queue_ids_;\n};\n\n}  // namespace hexagon\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_HEXAGON_RING_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/hexagon/rpc/simulator/hexagon_sim_proto.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_\n#define TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_\n\nstruct Message {\n  enum : uint32_t {\n    kNone = 0,\n    kAck,\n    kTerminate,\n    kReceiveStart,\n    kReceiveEnd,\n    kSendStart,\n    kSendEnd,\n  };\n  enum : uint32_t {\n    null_va = 0,\n  };\n\n  uint32_t code;\n  uint32_t len;\n  uint32_t va;\n} __attribute__((packed));\n\n// Protocol:\n//\n// Copying data from host to remote:\n//\n// Host >-- [ kReceiveStart, len,      null_va ] --> Remote\n// * Remote client prepares a buffer with at least `len` bytes.\n// Host <-- [ kAck,          buf_size, buf_ptr ] <-- Remote\n// * Host writes `nbytes` into buffer, `nbytes` <= `len`.\n// Host >-- [ kReceiveEnd,   nbytes,   buf_ptr ] --> Remote\n// * Remote client processes the data.\n// Host <-- [ kAck,          ___,      ___     ] <-- Remote\n//\n// Copying data from remote to host:\n//\n// Host >-- [ kSendStart,    len,      null_va ] --> Remote\n// * Remote client returns pointer to the buffer with the data to be read.\n// * There should be at least `len` bytes ready in the buffer.\n// Host <-- [ kAck,          buf_size, buf_ptr ] <-- Remote\n// * Host reads `nbytes` from buffer, `nbytes` <= `buf_size`.\n// Host >-- [ kSendEnd   ,   nbytes,   buf_ptr ] --> Remote\n// * Remote client processes the data.\n// Host <-- [ kAck,          ___,      ___     ] <-- Remote\n//\n// Teminating server:\n//\n// Host >-- [ kTerminate,    ___,      ___     ] --> Remote\n// Host <-- [ kAck,          ___,      ___     ] <-- Remote\n// * Host continues execution of the client.\n// * Client terminates.\n\n#define DISPATCH_FUNCTION_NAME dispatch_875b2e3a28186123\n#define MESSAGE_BUFFER_NAME message_buffer_71d6a7b93c318d7e\n\n#endif  // TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/library_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file library_module.h\n * \\brief Module that builds from a libary of symbols.\n */\n#ifndef TVM_RUNTIME_LIBRARY_MODULE_H_\n#define TVM_RUNTIME_LIBRARY_MODULE_H_\n\n#include <tvm/runtime/c_backend_api.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/module.h>\n\n#include <functional>\n#include <string>\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Load a module with the given type key directly from the stream.\n *  This function wraps the registry mechanism used to store type based deserializers\n *  for each runtime::Module sub-class.\n *\n * \\param type_key The type key of the serialized module.\n * \\param stream A pointer to the stream containing the serialized module.\n * \\return module The deserialized module.\n */\nModule LoadModuleFromBinary(const std::string& type_key, dmlc::Stream* stream);\n\n/*!\n * \\brief Library is the common interface\n *  for storing data in the form of shared libaries.\n *\n * \\sa dso_library.cc\n * \\sa system_library.cc\n */\nclass Library : public Object {\n public:\n  // destructor.\n  virtual ~Library() {}\n  /*!\n   * \\brief Get the symbol address for a given name.\n   * \\param name The name of the symbol.\n   * \\return The symbol.\n   */\n  virtual void* GetSymbol(const char* name) = 0;\n  // NOTE: we do not explicitly create an type index and type_key here for libary.\n  // This is because we do not need dynamic type downcasting.\n};\n\n/*!\n * \\brief Wrap a TVMBackendPackedCFunc to packed function.\n * \\param faddr The function address\n * \\param mptr The module pointer node.\n */\nPackedFunc WrapPackedFunc(TVMBackendPackedCFunc faddr, const ObjectPtr<Object>& mptr);\n\n/*!\n * \\brief Utility to initialize conext function symbols during startup\n * \\param fgetsymbol A symbol lookup function.\n */\nvoid InitContextFunctions(std::function<void*(const char*)> fgetsymbol);\n\n/*!\n * \\brief Type alias for function to wrap a TVMBackendPackedCFunc.\n * \\param The function address imported from a module.\n * \\param mptr The module pointer node.\n * \\return Packed function that wraps the invocation of the function at faddr.\n */\nusing PackedFuncWrapper =\n    std::function<PackedFunc(TVMBackendPackedCFunc faddr, const ObjectPtr<Object>& mptr)>;\n\n/*! \\brief Return a library object interface over dynamic shared\n *  libraries in Windows and Linux providing support for\n *  loading/unloading and symbol lookup.\n *  \\param Full path to shared library.\n *  \\return Returns pointer to the Library providing symbol lookup.\n */\nObjectPtr<Library> CreateDSOLibraryObject(std::string library_path);\n\n/*!\n * \\brief Create a module from a library.\n *\n * \\param lib The library.\n * \\param wrapper Optional function used to wrap a TVMBackendPackedCFunc,\n * by default WrapPackedFunc is used.\n * \\return The corresponding loaded module.\n *\n * \\note This function can create multiple linked modules\n *       by parsing the binary blob section of the library.\n */\nModule CreateModuleFromLibrary(ObjectPtr<Library> lib, PackedFuncWrapper wrapper = WrapPackedFunc);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_LIBRARY_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/meta_data.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file meta_data.h\n * \\brief Meta data related utilities\n */\n#ifndef TVM_RUNTIME_META_DATA_H_\n#define TVM_RUNTIME_META_DATA_H_\n\n#include <dmlc/io.h>\n#include <dmlc/json.h>\n#include <tvm/runtime/executor_info.h>\n#include <tvm/runtime/metadata.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"runtime_base.h\"\n\nnamespace tvm {\nnamespace runtime {\n\ninline String get_name_mangled(const String& module_name, const String& name) {\n  std::stringstream ss;\n  ICHECK(module_name.defined());\n  ICHECK(name.defined());\n  ss << module_name << \"_\" << name;\n  return ss.str();\n}\n\n/*!\n * \\brief Create a metadata module object.\n *\n * \\param metadata Exported metadata structure.\n *\n * \\return The created metadata module.\n */\nModule MetadataModuleCreate(metadata::Metadata metadata);\n\nnamespace launch_param {\n\n/*! \\brief A tag to specify whether or not dynamic shared memory is used */\nconstexpr const char* kUseDynamicSharedMemoryTag = \"tir.use_dyn_shared_memory\";\n\n}  // namespace launch_param\n\n/*! \\brief function information needed by device */\nstruct FunctionInfo {\n  std::string name;\n  std::vector<DLDataType> arg_types;\n  std::vector<std::string> launch_param_tags;\n\n  void Save(dmlc::JSONWriter* writer) const;\n  void Load(dmlc::JSONReader* reader);\n  void Save(dmlc::Stream* writer) const;\n  bool Load(dmlc::Stream* reader);\n};\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace dmlc {\nDMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::FunctionInfo, true);\n}  // namespace dmlc\n#endif  // TVM_RUNTIME_META_DATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/metal/metal_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file metal_common.h\n * \\brief Metal common header\n */\n#ifndef TVM_RUNTIME_METAL_METAL_COMMON_H_\n#define TVM_RUNTIME_METAL_METAL_COMMON_H_\n\n#import <Metal/MTLBlitCommandEncoder.h>\n#import <Metal/MTLBuffer.h>\n#import <Metal/MTLCommandBuffer.h>\n#import <Metal/MTLCommandQueue.h>\n#import <Metal/MTLDevice.h>\n#import <Metal/MTLLibrary.h>\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <mutex>\n#include <string>\n#include <vector>\n\n#include \"../workspace_pool.h\"\n\n/* Macro for convenience in using AutoReleasePoolWrapper.\n * With this macro we can add AutoReleasePoolWrapper to our ObjC code in more\n * native way.\n *\n * For example, this is ObjC code with autoreleasepool:\n *     @autoreleasepool {\n *         // Some code\n *     }\n *\n * To avoid possible memory leaks when an exception will be generated, we\n * should update this code:\n *     AUTORELEASEPOOL { // Replace @autoreleasepool -> AUTORELEASEPOOL\n *         // Some code\n *     }; // Add semicolon after close bracket\n *\n * In macro AUTORELEASEPOOL we get the instance of AutoReleasePoolWrapper and\n * put a lambda function with code from autoreleasepool to the insertion\n * operator of AutoReleasePoolWrapper class.\n *\n * Note: If you want to return a value from the autoreleasepool, you should\n * declare the variable with result before AUTORELEASEPOOL macro. This variable\n * will be captured by reference and you can use it in the code in autorelease\n * pool. But you should write return statement after AUTORELEASEPOOL macro.\n */\n#define AUTORELEASEPOOL tvm::runtime::metal::AutoReleasePoolWrapper::GetInstance() << [&]()\n\nnamespace tvm {\nnamespace runtime {\nnamespace metal {\n/*!\n * \\brief Wrapper on autoreleasepool with exception handling\n *\n * \\note In case when the exception was thrown from the autoreleasepool, the\n * allocated resources won't be released in proper way. So, we handle exception\n * in autoreleasepool and after the autoreleasepool we rethrow this exception.\n */\nclass AutoReleasePoolWrapper {\n public:\n  static AutoReleasePoolWrapper& GetInstance();\n  template <typename T>\n  void operator<<(const T& f) {\n    std::exception_ptr eptr;\n    @autoreleasepool {\n      try {\n        f();\n      } catch (...) {\n        eptr = std::current_exception();\n      }\n    }\n    if (eptr) std::rethrow_exception(eptr);\n  }\n\n private:\n  AutoReleasePoolWrapper() = default;\n  ~AutoReleasePoolWrapper() = default;\n  AutoReleasePoolWrapper(const AutoReleasePoolWrapper&) = delete;\n  AutoReleasePoolWrapper& operator=(const AutoReleasePoolWrapper&) = delete;\n};\n\n/*!\n * \\brief Structure for error handling in queues\n */\nclass Stream {\n public:\n  explicit Stream(id<MTLDevice> device) : error_happened_(false) {\n    queue_ = [device newCommandQueue];\n  }\n  ~Stream() { [queue_ release]; }\n  id<MTLCommandBuffer> GetCommandBuffer() {\n    id<MTLCommandBuffer> cb = [queue_ commandBuffer];\n    [cb addCompletedHandler:^(id<MTLCommandBuffer> buffer) {\n      if (buffer.status == MTLCommandBufferStatusError) SetErrorStatus();\n    }];\n    return cb;\n  }\n  bool HasErrorHappened() { return error_happened_; }\n\n private:\n  void SetErrorStatus() { error_happened_ = true; }\n  // Queue\n  id<MTLCommandQueue> queue_;\n  // Check if error happened in one previous run\n  bool error_happened_;\n};\n\n/*!\n * \\brief Process global Metal workspace.\n */\nclass MetalWorkspace final : public DeviceAPI {\n public:\n  // the devices\n  std::vector<id<MTLDevice>> devices;\n  // Warp size constant\n  std::vector<int> warp_size;\n  // Whether it is initialized.\n  bool initialized_{false};\n  // the mutex for initialization\n  std::mutex mutex;\n  // Destructor\n  ~MetalWorkspace();\n  // Get device for given device\n  id<MTLDevice> GetDevice(Device dev) {\n    ICHECK_EQ(dev.device_type, kDLMetal);\n    ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < devices.size())\n        << \"Invalid Metal device_id=\" << dev.device_id;\n    return devices[dev.device_id];\n  }\n  // Initialize workspace\n  // Return false if already initialized, otherwise return true.\n  void Init();\n  // override device API\n  void SetDevice(Device dev) final;\n  void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;\n  void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;\n  void FreeDataSpace(Device dev, void* ptr) final;\n  TVMStreamHandle CreateStream(Device dev) final;\n  void FreeStream(Device dev, TVMStreamHandle stream) final;\n  void StreamSync(Device dev, TVMStreamHandle stream) final;\n  void SetStream(Device dev, TVMStreamHandle stream) final;\n  void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;\n  void FreeWorkspace(Device dev, void* data) final;\n  void ReinitializeStreams();\n\n  // get the global workspace\n  static MetalWorkspace* Global();\n\n protected:\n  void CopyDataFromTo(const void* from, size_t from_size, void* to, size_t to_size, size_t size,\n                      Device dev_from, Device dev_to, DLDataType type_hint,\n                      TVMStreamHandle stream) final;\n\n private:\n  // Pointers to default allocated streams\n  std::vector<Stream*> default_streams_;\n};\n\n/*! \\brief Thread local workspace */\nclass MetalThreadEntry {\n public:\n  /*! \\brief The current device */\n  Device device;\n  /*! \\brief The current stream */\n  std::vector<Stream*> stream;\n  /*! \\brief The shared buffer used for copy. */\n  std::vector<id<MTLBuffer>> temp_buffer_;\n  /*! \\brief workspace pool */\n  WorkspacePool pool;\n  // constructor\n  MetalThreadEntry() : pool(static_cast<DLDeviceType>(kDLMetal), MetalWorkspace::Global()) {\n    device.device_id = 0;\n    device.device_type = static_cast<DLDeviceType>(kDLMetal);\n  }\n  ~MetalThreadEntry();\n  // Get temp buffer with at least size under dev.\n  id<MTLBuffer> GetTempBuffer(Device dev, size_t size);\n  // get the global workspace\n  static MetalThreadEntry* ThreadLocal();\n};\n}  // namespace metal\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_METAL_METAL_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/metal/metal_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file metal_module.h\n * \\brief Execution handling of Metal kernels\n */\n#ifndef TVM_RUNTIME_METAL_METAL_MODULE_H_\n#define TVM_RUNTIME_METAL_METAL_MODULE_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*! \\brief Maximum number of GPU supported in MetalModule. */\nstatic constexpr const int kMetalMaxNumDevice = 32;\n\n/*!\n * \\brief create a metal module from data.\n *\n * \\param data The data content.\n * \\param fmt The format of the data, can be \"metal\" or \"metallib\"\n * \\param fmap The map function information map of each function.\n * \\param source Optional, source file\n */\nModule MetalModuleCreate(std::string data, std::string fmt,\n                         std::unordered_map<std::string, FunctionInfo> fmap, std::string source);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_METAL_METAL_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/micro/crt_config.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/runtime/crt/host/crt_config.h\n * \\brief CRT configuration for the host-linked CRT.\n */\n#ifndef TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n#define TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n\n/*! Log level of the CRT runtime */\n#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG\n\n/*! Support low-level debugging in MISRA-C runtime */\n#define TVM_CRT_DEBUG 0\n\n/*! Maximum supported dimension in NDArray */\n#define TVM_CRT_MAX_NDIM 6\n/*! Maximum supported arguments in generated functions */\n#define TVM_CRT_MAX_ARGS 10\n/*! Maximum supported string length in dltype, e.g. \"int8\", \"int16\", \"float32\" */\n#define TVM_CRT_MAX_STRLEN_DLTYPE 10\n/*! Maximum supported string length in function names */\n#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120\n/*! Maximum supported string length in parameter names */\n#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80\n\n/*! Maximum number of registered modules. */\n#define TVM_CRT_MAX_REGISTERED_MODULES 2\n\n/*! Size of the global function registry, in bytes. */\n#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512\n\n/*! Maximum packet size, in bytes, including the length header. */\n#define TVM_CRT_MAX_PACKET_SIZE_BYTES 8 * 1024\n\n/*! \\brief Maximum length of a PackedFunc function name. */\n#define TVM_CRT_MAX_FUNCTION_NAME_LENGTH_BYTES 30\n\n// #define TVM_CRT_FRAMER_ENABLE_LOGS\n\n#endif  // TVM_RUNTIME_MICRO_CRT_CONFIG_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/micro/micro_session.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file micro_session.h\n * \\brief session to manage multiple micro modules\n *\n * Each session consists of an interaction with a *single* logical device.\n * Within that interaction, multiple TVM modules can be loaded on the logical\n * device.\n *\n * Multiple sessions can exist simultaneously, but there is only ever one\n * *active* session. The idea of an active session mainly has implications for\n * the frontend, in that one must make a session active in order to allocate\n * new TVM objects on it. Aside from that, previously allocated objects can be\n * used even if the session which they belong to is not currently active.\n */\n#ifndef TVM_RUNTIME_MICRO_MICRO_SESSION_H_\n#define TVM_RUNTIME_MICRO_MICRO_SESSION_H_\n\n#endif  // TVM_RUNTIME_MICRO_MICRO_SESSION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/micro/standalone/microtvm_graph_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_\n#define TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_\n\n#include <dlpack/dlpack.h>\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <numeric>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"microtvm_runtime_api.h\"\n#include \"minimal_vector.h\"\n\nnamespace tvm {\nnamespace micro {\n\ntypedef int (*BackendPackedCFunc)(void* args, int* type_codes, int num_args);\n\n// dlopen/dlsym/dlclose abstraction.\nclass DSOModule {\n public:\n  explicit DSOModule(const std::string& name);\n  ~DSOModule();\n  BackendPackedCFunc GetFunction(const std::string& name) const;\n\n private:\n  void* GetSymbol(const char* name) const;\n  void* lib_handle_{nullptr};\n};\n\n// The graph attribute fields.\nstruct GraphAttr {\n  DynArray<int> storage_id;\n  DynArray<std::string> dltype;\n  DynArray<DynArray<int64_t>> shape;\n};\n\n// Memory pool entry.\nstruct PoolEntry {\n  size_t size;\n  int device_type;\n};\n\n// Node entry\nstruct NodeEntry {\n  uint32_t node_id;\n  uint32_t index;\n  uint32_t version;\n};\n\n// Operator attributes about TVMOp\nstruct TVMOpParam {\n  std::string func_name;\n  uint32_t num_inputs;\n  uint32_t num_outputs;\n  uint32_t flatten_data;\n};\n\n// Node\nstruct Node {\n  // operator type in string\n  std::string op_type;\n  // name of the op\n  std::string name;\n  // parameters\n  TVMOpParam param;\n  // inputs\n  DynArray<NodeEntry> inputs;\n};\n\n// Minimal NDArray abstraction\nclass NDArray {\n public:\n  // initialize NDArray with shape/dtype/device\n  static NDArray Empty(const DynArray<int64_t>& shape, DLDataType dtype, DLDevice dev);\n  // create a view of the NDArray storage, with the given shape/dtype\n  NDArray CreateView(const DynArray<int64_t>& shape, DLDataType dtype);\n  // Copy into the internal storage.\n  void CopyFrom(DLTensor* src);\n  // Copy out of the internal storage\n  void CopyTo(DLTensor* dst) const;\n  // View `this` as a DLTensor\n  DLTensor ToDLTensor();\n  ~NDArray();\n\n private:\n  // reference-counted storage\n  std::shared_ptr<void> storage_;\n  // tensor shape\n  DynArray<int64_t> shape_;\n  // tensor dtype\n  DLDataType dtype_;\n  // tensor device\n  DLDevice device_;\n};\n\n// Minimal GraphExecutor implementation\nclass MicroGraphExecutor {\n public:\n  // Construct a GraphExecutor with the given graph and DSOModule.\n  MicroGraphExecutor(const std::string& graph_json, DSOModule* module);\n  ~MicroGraphExecutor();\n  // Run the graph\n  void Run();\n  // Set the input at `index` to a copy of the tensor `data_in`\n  void SetInput(int index, DLTensor* data_in);\n  // Copy the output at `index` into `data_out`\n  void CopyOutputTo(int index, DLTensor* data_out);\n\n private:\n  void SetupStorage();\n  void SetupOpExecs();\n\n  uint32_t num_node_entries() const { return node_row_ptr_.back(); }\n  uint32_t entry_id(uint32_t nid, uint32_t index) const { return node_row_ptr_[nid] + index; }\n  uint32_t entry_id(const NodeEntry& e) const { return entry_id(e.node_id, e.index); }\n\n  DSOModule* module_;\n\n  // TODO(tulloch): these are essentially unused after construction.\n  // The graph nodes\n  DynArray<Node> nodes_;\n  // The argument noes\n  DynArray<uint32_t> input_nodes_;\n  // Used for quick entry indexing\n  DynArray<uint32_t> node_row_ptr_;\n  // Output entries\n  DynArray<NodeEntry> outputs_;\n  // Additional graph attributes\n  GraphAttr attrs_;\n  // Execution device\n  DLDevice device_{kDLCPU, 0};\n\n  // Common storage pool\n  DynArray<NDArray> storage_pool_;\n  // Data entry for each node\n  DynArray<NDArray> data_entry_;\n  // Operator for each node\n  DynArray<std::function<void()>> op_execs_;\n};\n\n}  // namespace micro\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/micro/standalone/microtvm_runtime_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_\n#define TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_\n\n#include <stdint.h>\n#include <stdlib.h>\n\n#include <cassert>\n\n// The subset of the TVM runtime API that is implemented by the minimal runtime API.\n\n#define TVM_MICRO_RUNTIME_API_BACKEND_API extern \"C\" __attribute__((weak, visibility(\"default\")))\n\nTVM_MICRO_RUNTIME_API_BACKEND_API int TVMBackendFreeWorkspace(int device_type, int device_id,\n                                                              void* ptr);\n\nTVM_MICRO_RUNTIME_API_BACKEND_API void* TVMBackendAllocWorkspace(int device_type, int device_id,\n                                                                 uint64_t nbytes,\n                                                                 int dtype_code_hint,\n                                                                 int dtype_bits_hint);\n\ntypedef struct {\n  void* sync_handle;\n  int32_t num_task;\n} TVMParallelGroupEnv;\n\ntypedef int (*FTVMParallelLambda)(int task_id, TVMParallelGroupEnv* penv, void* cdata);\n\nTVM_MICRO_RUNTIME_API_BACKEND_API int TVMBackendParallelLaunch(FTVMParallelLambda flambda,\n                                                               void* cdata, int num_task);\n\nTVM_MICRO_RUNTIME_API_BACKEND_API void TVMAPISetLastError(const char* msg);\nTVM_MICRO_RUNTIME_API_BACKEND_API const char* TVMGetLastError(void);\n\n#undef TVM_MICRO_RUNTIME_API_BACKEND_API\n\n#endif  // TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/micro/standalone/minimal_vector.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_\n#define TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_\n\n#include <algorithm>\n#include <cassert>\n#include <memory>\n\nnamespace tvm {\nnamespace micro {\n\n// A minimal wrapper, derived from https://github.com/Robbepop/dynarray/, that\n// supports a minimal subset of the std::vector API with a minimized code size.\ntemplate <typename T>\nstruct DynArray {\n  using value_type = T;\n  using size_type = size_t;\n  using difference_type = std::ptrdiff_t;\n  using reference = value_type&;\n  using const_reference = value_type const&;\n  using pointer = value_type*;\n  using const_pointer = value_type const*;\n  using iterator = pointer;\n  using const_iterator = const_pointer;\n  using reverse_iterator = std::reverse_iterator<iterator>;\n  using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n  explicit DynArray(size_type size = 0) { resize(size); }\n\n  DynArray(const DynArray& other) {\n    resize(other.size());\n    std::copy(other.begin(), other.end(), begin());\n  }\n\n  DynArray& operator=(const DynArray& other) {\n    resize(other.size());\n    std::copy(other.begin(), other.end(), begin());\n    return *this;\n  }\n\n  void resize(size_type size) {\n    if (size > 0) {\n      data_.reset(new T[size]);\n    } else {\n      data_.reset();\n    }\n    size_ = size;\n  }\n\n  size_type size() const { return size_; }\n\n  reference operator[](size_type pos) { return data_[pos]; }\n\n  const_reference operator[](size_type pos) const { return data_[pos]; }\n\n  pointer data() { return data_.get(); }\n\n  const_pointer data() const { return data_.get(); }\n\n  iterator begin() { return data_.get(); }\n\n  const_iterator begin() const { return data_.get(); }\n\n  const_iterator cbegin() const { return data_.get(); }\n\n  iterator end() { return data_.get() + size_; }\n\n  const_iterator end() const { return data_.get() + size_; }\n\n  const_iterator cend() const { return data_.get() + size_; }\n\n  reference front() { return data_[0]; }\n\n  const_reference front() const { return data_[0]; }\n\n  reference back() { return data_[size_ - 1]; }\n\n  const_reference back() const { return data_[size_ - 1]; }\n\n private:\n  std::unique_ptr<T[]> data_;\n  size_type size_;\n};\n\n}  // namespace micro\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/minrpc/minrpc_interfaces.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_\n#define TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include \"rpc_reference.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Return interface used in ExecInterface to generate and send the responses.\n */\nclass MinRPCReturnInterface {\n public:\n  virtual ~MinRPCReturnInterface() {}\n  /*! * \\brief sends a response to the client with kTVMNullptr in payload. */\n  virtual void ReturnVoid() = 0;\n\n  /*! * \\brief sends a response to the client with one kTVMOpaqueHandle in payload. */\n  virtual void ReturnHandle(void* handle) = 0;\n\n  /*! * \\brief sends an exception response to the client with a kTVMStr in payload. */\n  virtual void ReturnException(const char* msg) = 0;\n\n  /*! * \\brief sends a packed argument sequnce to the client. */\n  virtual void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) = 0;\n\n  /*! * \\brief sends a copy of the requested remote data to the client. */\n  virtual void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) = 0;\n\n  /*! * \\brief sends an exception response to the client with the last TVM erros as the message. */\n  virtual void ReturnLastTVMError() = 0;\n\n  /*! * \\brief internal error. */\n  virtual void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) = 0;\n};\n\n/*!\n * \\brief Execute interface used in MinRPCServer to process different received commands\n */\nclass MinRPCExecInterface {\n public:\n  virtual ~MinRPCExecInterface() {}\n\n  /*! * \\brief Execute an Initilize server command. */\n  virtual void InitServer(int num_args) = 0;\n\n  /*! * \\brief calls a function specified by the call_handle. */\n  virtual void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes,\n                              int num_args) = 0;\n\n  /*! * \\brief Execute a copy from remote command by sending the data described in arr to the client\n   */\n  virtual void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) = 0;\n\n  /*! * \\brief Execute a copy to remote command by receiving the data described in arr from the\n   * client */\n  virtual int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) = 0;\n\n  /*! * \\brief calls a system function specified by the code. */\n  virtual void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) = 0;\n\n  /*! * \\brief internal error. */\n  virtual void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) = 0;\n\n  /*! * \\brief return the ReturnInterface pointer that is used to generate and send the responses.\n   */\n  virtual MinRPCReturnInterface* GetReturnInterface() = 0;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/minrpc/minrpc_logger.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_\n#define TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <functional>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n\n#include \"minrpc_interfaces.h\"\n#include \"rpc_reference.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n#define PRINT_BYTES false\n\n/*!\n * \\brief Generates a user readeable log on the console\n */\nclass Logger {\n public:\n  Logger() {}\n\n  /*!\n   * \\brief this function logs a string\n   *\n   * \\param s the string to be logged.\n   */\n  void Log(const char* s) { os_ << s; }\n  void Log(std::string s) { os_ << s; }\n\n  /*!\n   * \\brief this function logs a numerical value\n   *\n   * \\param desc adds any necessary description before the value.\n   * \\param val is the value to be logged.\n   */\n  template <typename T>\n  void LogValue(const char* desc, T val) {\n    os_ << desc << val;\n  }\n\n  /*!\n   * \\brief this function logs the properties of a DLDevice\n   *\n   * \\param desc adds any necessary description before the DLDevice.\n   * \\param dev is the pointer to the DLDevice to be logged.\n   */\n  void LogDLDevice(const char* desc, DLDevice* dev) {\n    os_ << desc << \"(\" << dev->device_type << \",\" << dev->device_id << \")\";\n  }\n\n  /*!\n   * \\brief this function logs the properties of a DLDataType\n   *\n   * \\param desc adds any necessary description before the DLDataType.\n   * \\param data is the pointer to the DLDataType to be logged.\n   */\n  void LogDLData(const char* desc, DLDataType* data) {\n    os_ << desc << \"(\" << (uint16_t)data->code << \",\" << (uint16_t)data->bits << \",\" << data->lanes\n        << \")\";\n  }\n\n  /*!\n   * \\brief this function logs a handle name.\n   *\n   * \\param name is the name to be logged.\n   */\n  void LogHandleName(std::string name) {\n    if (name.length() > 0) {\n      os_ << \" <\" << name.c_str() << \">\";\n    }\n  }\n\n  /*!\n   * \\brief this function logs a TVMValue based on its type.\n   *\n   * \\param tcode the type_code of the value stored in TVMValue.\n   * \\param value is the TVMValue to be logged.\n   */\n  void LogTVMValue(int tcode, TVMValue value);\n\n  /*!\n   * \\brief this function output the log to the console.\n   */\n  void OutputLog();\n\n private:\n  std::stringstream os_;\n};\n\n/*!\n * \\brief A wrapper for a MinRPCReturns object, that also logs the responses.\n *\n * \\param next underlying MinRPCReturns that generates the responses.\n */\nclass MinRPCReturnsWithLog : public MinRPCReturnInterface {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param io The IO handler.\n   */\n  MinRPCReturnsWithLog(MinRPCReturnInterface* next, Logger* logger)\n      : next_(next), logger_(logger) {}\n\n  ~MinRPCReturnsWithLog() {}\n\n  void ReturnVoid();\n\n  void ReturnHandle(void* handle);\n\n  void ReturnException(const char* msg);\n\n  void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args);\n\n  void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes);\n\n  void ReturnLastTVMError();\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone);\n\n  /*!\n   * \\brief this function logs a list of TVMValues, and registers handle_name when needed.\n   *\n   * \\param values is the list of TVMValues.\n   * \\param tcodes is the list type_code of the TVMValues.\n   * \\param num_args is the number of items in the list.\n   */\n  void ProcessValues(const TVMValue* values, const int* tcodes, int num_args);\n\n  /*!\n   * \\brief this function is called when a new command is executed.\n   * It clears the handle_name_ and records the command code.\n   *\n   * \\param code the RPC command code.\n   */\n  void ResetHandleName(RPCCode code);\n\n  /*!\n   * \\brief appends name to the handle_name_.\n   *\n   * \\param name handle name.\n   */\n  void UpdateHandleName(const char* name);\n\n  /*!\n   * \\brief get the stored handle description.\n   *\n   * \\param handle the handle to get the description for.\n   */\n  void GetHandleName(void* handle);\n\n  /*!\n   * \\brief remove the handle description from handle_descriptions_.\n   *\n   * \\param handle the handle to remove the description for.\n   */\n  void ReleaseHandleName(void* handle);\n\n private:\n  /*!\n   * \\brief add the handle description to handle_descriptions_.\n   *\n   * \\param handle the handle to add the description for.\n   */\n  void RegisterHandleName(void* handle);\n\n  MinRPCReturnInterface* next_;\n  std::string handle_name_;\n  std::unordered_map<void*, std::string> handle_descriptions_;\n  RPCCode code_;\n  Logger* logger_;\n};\n\n/*!\n * \\brief A wrapper for a MinRPCExecute object, that also logs the responses.\n *\n * \\param next: underlying MinRPCExecute that processes the packets.\n */\nclass MinRPCExecuteWithLog : public MinRPCExecInterface {\n public:\n  MinRPCExecuteWithLog(MinRPCExecInterface* next, Logger* logger) : next_(next), logger_(logger) {\n    ret_handler_ = reinterpret_cast<MinRPCReturnsWithLog*>(next_->GetReturnInterface());\n  }\n\n  ~MinRPCExecuteWithLog() {}\n\n  void InitServer(int num_args);\n\n  void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args);\n\n  void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* temp_data);\n\n  int CopyToRemote(DLTensor* arr, uint64_t _num_bytes, uint8_t* _data_ptr);\n\n  void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args);\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone);\n\n  MinRPCReturnInterface* GetReturnInterface() { return next_->GetReturnInterface(); }\n\n private:\n  /*!\n   * \\brief this function logs a list of TVMValues, and updates handle_name when needed.\n   *\n   * \\param values is the list of TVMValues.\n   * \\param tcodes is the list type_code of the TVMValues.\n   * \\param num_args is the number of items in the list.\n   */\n  void ProcessValues(TVMValue* values, int* tcodes, int num_args);\n\n  /*!\n   * \\brief this function is called when a new command is executed.\n   *\n   * \\param code the RPC command code.\n   */\n  void SetRPCCode(RPCCode code);\n\n  MinRPCExecInterface* next_;\n  MinRPCReturnsWithLog* ret_handler_;\n  Logger* logger_;\n};\n\n/*!\n * \\brief A No-operation MinRPCReturns used within the MinRPCSniffer\n *\n * \\tparam TIOHandler* IO provider to provide io handling.\n */\ntemplate <typename TIOHandler>\nclass MinRPCReturnsNoOp : public MinRPCReturnInterface {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param io The IO handler.\n   */\n  explicit MinRPCReturnsNoOp(TIOHandler* io) : io_(io) {}\n  ~MinRPCReturnsNoOp() {}\n  void ReturnVoid() {}\n  void ReturnHandle(void* handle) {}\n  void ReturnException(const char* msg) {}\n  void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) {}\n  void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) {}\n  void ReturnLastTVMError() {}\n  void ThrowError(RPCServerStatus code, RPCCode info) {}\n\n private:\n  TIOHandler* io_;\n};\n\n/*!\n * \\brief A No-operation MinRPCExecute used within the MinRPCSniffer\n *\n * \\tparam ReturnInterface* ReturnInterface pointer to generate and send the responses.\n\n */\nclass MinRPCExecuteNoOp : public MinRPCExecInterface {\n public:\n  explicit MinRPCExecuteNoOp(MinRPCReturnInterface* ret_handler) : ret_handler_(ret_handler) {}\n  ~MinRPCExecuteNoOp() {}\n  void InitServer(int _num_args) {}\n  void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args) {}\n  void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* temp_data) {}\n  int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) { return 1; }\n  void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) {}\n  void ThrowError(RPCServerStatus code, RPCCode info) {}\n  MinRPCReturnInterface* GetReturnInterface() { return ret_handler_; }\n\n private:\n  MinRPCReturnInterface* ret_handler_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/minrpc/minrpc_server.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file minrpc_server.h\n * \\brief Minimum RPC server implementation,\n *        redirects all the calls to C runtime API.\n *\n * \\note This file do not depend on c++ std or c std,\n *       and only depends on TVM's C runtime API.\n */\n#ifndef TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_\n#define TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_\n\n#ifndef DMLC_LITTLE_ENDIAN\n#define DMLC_LITTLE_ENDIAN 1\n#endif\n\n#include <string.h>\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <memory>\n#include <utility>\n\n#include \"../../support/generic_arena.h\"\n#include \"minrpc_interfaces.h\"\n#include \"rpc_reference.h\"\n\n#ifndef MINRPC_CHECK\n#define MINRPC_CHECK(cond) \\\n  if (!(cond)) this->ThrowError(RPCServerStatus::kCheckError);\n#endif\n\nnamespace tvm {\nnamespace runtime {\n\nnamespace detail {\ntemplate <typename TIOHandler>\nclass PageAllocator;\n}\n\n/*!\n * \\brief Responses to a minimum RPC command.\n *\n * \\tparam TIOHandler IO provider to provide io handling.\n */\ntemplate <typename TIOHandler>\nclass MinRPCReturns : public MinRPCReturnInterface {\n public:\n  /*!\n   * \\brief Constructor.\n   * \\param io The IO handler.\n   */\n  explicit MinRPCReturns(TIOHandler* io) : io_(io) {}\n\n  void ReturnVoid() {\n    int32_t num_args = 1;\n    int32_t tcode = kTVMNullptr;\n    RPCCode code = RPCCode::kReturn;\n\n    uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode);\n\n    io_->MessageStart(packet_nbytes);\n    Write(packet_nbytes);\n    Write(code);\n    Write(num_args);\n    Write(tcode);\n    io_->MessageDone();\n  }\n\n  void ReturnHandle(void* handle) {\n    int32_t num_args = 1;\n    int32_t tcode = kTVMOpaqueHandle;\n    RPCCode code = RPCCode::kReturn;\n    uint64_t encode_handle = reinterpret_cast<uint64_t>(handle);\n    uint64_t packet_nbytes =\n        sizeof(code) + sizeof(num_args) + sizeof(tcode) + sizeof(encode_handle);\n\n    io_->MessageStart(packet_nbytes);\n    Write(packet_nbytes);\n    Write(code);\n    Write(num_args);\n    Write(tcode);\n    Write(encode_handle);\n    io_->MessageDone();\n  }\n\n  void ReturnException(const char* msg) { RPCReference::ReturnException(msg, this); }\n\n  void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) {\n    RPCReference::ReturnPackedSeq(arg_values, type_codes, num_args, this);\n  }\n\n  void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) {\n    RPCCode code = RPCCode::kCopyAck;\n    uint64_t packet_nbytes = sizeof(code) + num_bytes;\n\n    io_->MessageStart(packet_nbytes);\n    Write(packet_nbytes);\n    Write(code);\n    WriteArray(data_ptr, num_bytes);\n    io_->MessageDone();\n  }\n\n  void ReturnLastTVMError() {\n    const char* err = TVMGetLastError();\n    ReturnException(err);\n  }\n\n  void MessageStart(uint64_t packet_nbytes) { io_->MessageStart(packet_nbytes); }\n\n  void MessageDone() { io_->MessageDone(); }\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {\n    io_->Exit(static_cast<int>(code));\n  }\n\n  template <typename T>\n  void Write(const T& data) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return WriteRawBytes(&data, sizeof(T));\n  }\n\n  template <typename T>\n  void WriteArray(T* data, size_t count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return WriteRawBytes(data, sizeof(T) * count);\n  }\n\n private:\n  void WriteRawBytes(const void* data, size_t size) {\n    const uint8_t* buf = static_cast<const uint8_t*>(data);\n    size_t ndone = 0;\n    while (ndone < size) {\n      ssize_t ret = io_->PosixWrite(buf, size - ndone);\n      if (ret <= 0) {\n        this->ThrowError(RPCServerStatus::kWriteError);\n      }\n      buf += ret;\n      ndone += ret;\n    }\n  }\n\n  TIOHandler* io_;\n};\n\n/*!\n * \\brief Executing a minimum RPC command.\n *\n * \\tparam TIOHandler IO provider to provide io handling.\n * \\tparam MinRPCReturnInterface* handles response generatation and transmission.\n */\ntemplate <typename TIOHandler>\nclass MinRPCExecute : public MinRPCExecInterface {\n public:\n  MinRPCExecute(TIOHandler* io, MinRPCReturnInterface* ret_handler)\n      : io_(io), ret_handler_(ret_handler) {}\n\n  void InitServer(int num_args) {\n    MINRPC_CHECK(num_args == 0);\n    ret_handler_->ReturnVoid();\n  }\n\n  void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args) {\n    TVMValue ret_value[3];\n    int ret_tcode[3];\n\n    int call_ecode = TVMFuncCall(reinterpret_cast<void*>(call_handle), values, tcodes, num_args,\n                                 &(ret_value[1]), &(ret_tcode[1]));\n\n    if (call_ecode == 0) {\n      // Return value encoding as in LocalSession\n      int rv_tcode = ret_tcode[1];\n      ret_tcode[0] = kDLInt;\n      ret_value[0].v_int64 = rv_tcode;\n      if (rv_tcode == kTVMNDArrayHandle) {\n        ret_tcode[1] = kTVMDLTensorHandle;\n        ret_value[2].v_handle = ret_value[1].v_handle;\n        ret_tcode[2] = kTVMOpaqueHandle;\n        ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 3);\n      } else if (rv_tcode == kTVMBytes) {\n        ret_tcode[1] = kTVMBytes;\n        ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);\n        TVMByteArrayFree(reinterpret_cast<TVMByteArray*>(ret_value[1].v_handle));  // NOLINT(*)\n      } else if (rv_tcode == kTVMPackedFuncHandle || rv_tcode == kTVMModuleHandle) {\n        ret_tcode[1] = kTVMOpaqueHandle;\n        ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);\n      } else {\n        ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);\n      }\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) {\n    int call_ecode = 0;\n    if (arr->device.device_type != kDLCPU) {\n      DLTensor temp;\n      temp.data = static_cast<void*>(data_ptr);\n      temp.device = DLDevice{kDLCPU, 0};\n      temp.ndim = arr->ndim;\n      temp.dtype = arr->dtype;\n      temp.shape = arr->shape;\n      temp.strides = nullptr;\n      temp.byte_offset = 0;\n      call_ecode = TVMDeviceCopyDataFromTo(arr, &temp, nullptr);\n      // need sync to make sure that the copy is completed.\n      if (call_ecode == 0) {\n        call_ecode = TVMSynchronize(arr->device.device_type, arr->device.device_id, nullptr);\n      }\n    }\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnCopyFromRemote(data_ptr, num_bytes);\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) {\n    int call_ecode = 0;\n\n    int ret = ReadArray(data_ptr, num_bytes);\n    if (ret <= 0) return ret;\n\n    if (arr->device.device_type != kDLCPU) {\n      DLTensor temp;\n      temp.data = data_ptr;\n      temp.device = DLDevice{kDLCPU, 0};\n      temp.ndim = arr->ndim;\n      temp.dtype = arr->dtype;\n      temp.shape = arr->shape;\n      temp.strides = nullptr;\n      temp.byte_offset = 0;\n      call_ecode = TVMDeviceCopyDataFromTo(&temp, arr, nullptr);\n      // need sync to make sure that the copy is completed.\n      if (call_ecode == 0) {\n        call_ecode = TVMSynchronize(arr->device.device_type, arr->device.device_id, nullptr);\n      }\n    }\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n\n    return 1;\n  }\n\n  void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) {\n    switch (code) {\n      case RPCCode::kFreeHandle: {\n        SyscallFreeHandle(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kGetGlobalFunc: {\n        SyscallGetGlobalFunc(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevSetDevice: {\n        ret_handler_->ReturnException(\"SetDevice not supported\");\n        break;\n      }\n      case RPCCode::kDevGetAttr: {\n        ret_handler_->ReturnException(\"GetAttr not supported\");\n        break;\n      }\n      case RPCCode::kDevAllocData: {\n        SyscallDevAllocData(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevAllocDataWithScope: {\n        SyscallDevAllocDataWithScope(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevFreeData: {\n        SyscallDevFreeData(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevCreateStream: {\n        SyscallDevCreateStream(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevFreeStream: {\n        SyscallDevFreeStream(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevStreamSync: {\n        SyscallDevStreamSync(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kDevSetStream: {\n        SyscallDevSetStream(values, tcodes, num_args);\n        break;\n      }\n      case RPCCode::kCopyAmongRemote: {\n        SyscallCopyAmongRemote(values, tcodes, num_args);\n        break;\n      }\n      default: {\n        ret_handler_->ReturnException(\"Syscall not recognized\");\n        break;\n      }\n    }\n  }\n\n  void SyscallFreeHandle(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kTVMOpaqueHandle);\n    MINRPC_CHECK(tcodes[1] == kDLInt);\n\n    void* handle = values[0].v_handle;\n    int64_t type_code = values[1].v_int64;\n    int call_ecode;\n\n    if (type_code == kTVMNDArrayHandle) {\n      call_ecode = TVMArrayFree(static_cast<TVMArrayHandle>(handle));\n    } else if (type_code == kTVMPackedFuncHandle) {\n      call_ecode = TVMFuncFree(handle);\n    } else {\n      MINRPC_CHECK(type_code == kTVMModuleHandle);\n      call_ecode = TVMModFree(handle);\n    }\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallGetGlobalFunc(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 1);\n    MINRPC_CHECK(tcodes[0] == kTVMStr);\n    void* handle;\n    int call_ecode = TVMFuncGetGlobal(values[0].v_str, &handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnHandle(handle);\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallCopyAmongRemote(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 3);\n    // from dltensor\n    MINRPC_CHECK(tcodes[0] == kTVMDLTensorHandle);\n    // to dltensor\n    MINRPC_CHECK(tcodes[1] == kTVMDLTensorHandle);\n    // stream\n    MINRPC_CHECK(tcodes[2] == kTVMOpaqueHandle);\n\n    void* from = values[0].v_handle;\n    void* to = values[1].v_handle;\n    TVMStreamHandle stream = values[2].v_handle;\n\n    int call_ecode = TVMDeviceCopyDataFromTo(reinterpret_cast<DLTensor*>(from),\n                                             reinterpret_cast<DLTensor*>(to), stream);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevAllocData(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 4);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n    MINRPC_CHECK(tcodes[1] == kDLInt);\n    MINRPC_CHECK(tcodes[2] == kDLInt);\n    MINRPC_CHECK(tcodes[3] == kTVMDataType);\n\n    DLDevice dev = values[0].v_device;\n    int64_t nbytes = values[1].v_int64;\n    int64_t alignment = values[2].v_int64;\n    DLDataType type_hint = values[3].v_type;\n\n    void* handle;\n    int call_ecode = TVMDeviceAllocDataSpace(dev, nbytes, alignment, type_hint, &handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnHandle(handle);\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevAllocDataWithScope(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kTVMDLTensorHandle);\n    MINRPC_CHECK(tcodes[1] == kTVMNullptr || tcodes[1] == kTVMStr);\n\n    DLTensor* arr = static_cast<DLTensor*>(values[0].v_handle);\n    const char* mem_scope = (tcodes[1] == kTVMNullptr ? nullptr : values[1].v_str);\n    void* handle;\n    int call_ecode = TVMDeviceAllocDataSpaceWithScope(arr->device, arr->ndim, arr->shape,\n                                                      arr->dtype, mem_scope, &handle);\n    if (call_ecode == 0) {\n      ret_handler_->ReturnHandle(handle);\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevFreeData(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n    MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);\n\n    DLDevice dev = values[0].v_device;\n    void* handle = values[1].v_handle;\n\n    int call_ecode = TVMDeviceFreeDataSpace(dev, handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevCreateStream(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 1);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n\n    DLDevice dev = values[0].v_device;\n    void* handle;\n\n    int call_ecode = TVMStreamCreate(dev.device_type, dev.device_id, &handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnHandle(handle);\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevFreeStream(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n    MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);\n\n    DLDevice dev = values[0].v_device;\n    void* handle = values[1].v_handle;\n\n    int call_ecode = TVMStreamFree(dev.device_type, dev.device_id, handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevStreamSync(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n    MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);\n\n    DLDevice dev = values[0].v_device;\n    void* handle = values[1].v_handle;\n\n    int call_ecode = TVMSynchronize(dev.device_type, dev.device_id, handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void SyscallDevSetStream(TVMValue* values, int* tcodes, int num_args) {\n    MINRPC_CHECK(num_args == 2);\n    MINRPC_CHECK(tcodes[0] == kDLDevice);\n    MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);\n\n    DLDevice dev = values[0].v_device;\n    void* handle = values[1].v_handle;\n\n    int call_ecode = TVMSetStream(dev.device_type, dev.device_id, handle);\n\n    if (call_ecode == 0) {\n      ret_handler_->ReturnVoid();\n    } else {\n      ret_handler_->ReturnLastTVMError();\n    }\n  }\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {\n    ret_handler_->ThrowError(code, info);\n  }\n\n  MinRPCReturnInterface* GetReturnInterface() { return ret_handler_; }\n\n private:\n  template <typename T>\n  int ReadArray(T* data, size_t count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return ReadRawBytes(data, sizeof(T) * count);\n  }\n\n  int ReadRawBytes(void* data, size_t size) {\n    uint8_t* buf = static_cast<uint8_t*>(data);\n    size_t ndone = 0;\n    while (ndone < size) {\n      ssize_t ret = io_->PosixRead(buf, size - ndone);\n      if (ret <= 0) return ret;\n      ndone += ret;\n      buf += ret;\n    }\n    return 1;\n  }\n\n  TIOHandler* io_;\n  MinRPCReturnInterface* ret_handler_;\n};\n\n/*!\n * \\brief A minimum RPC server that only depends on the tvm C runtime..\n *\n *  All the dependencies are provided by the io arguments.\n *\n * \\tparam TIOHandler IO provider to provide io handling.\n *         An IOHandler needs to provide the following functions:\n *         - PosixWrite, PosixRead, Close: posix style, read, write, close API.\n *         - MessageStart(num_bytes), MessageDone(): framing APIs.\n *         - Exit: exit with status code.\n */\ntemplate <typename TIOHandler, template <typename> class Allocator = detail::PageAllocator>\nclass MinRPCServer {\n public:\n  using PageAllocator = Allocator<TIOHandler>;\n\n  /*!\n   * \\brief Constructor.\n   * \\param io The IO handler.\n   */\n  MinRPCServer(TIOHandler* io, std::unique_ptr<MinRPCExecInterface>&& exec_handler)\n      : io_(io), arena_(PageAllocator(io_)), exec_handler_(std::move(exec_handler)) {}\n\n  explicit MinRPCServer(TIOHandler* io)\n      : io_(io),\n        arena_(PageAllocator(io)),\n        ret_handler_(new MinRPCReturns<TIOHandler>(io_)),\n        exec_handler_(std::unique_ptr<MinRPCExecInterface>(\n            new MinRPCExecute<TIOHandler>(io_, ret_handler_))) {}\n\n  ~MinRPCServer() {\n    if (ret_handler_ != nullptr) {\n      delete ret_handler_;\n    }\n  }\n\n  /*! \\brief Process a single request.\n   *\n   * \\return true when the server should continue processing requests. false when it should be\n   *  shutdown.\n   */\n  bool ProcessOnePacket() {\n    RPCCode code;\n    uint64_t packet_len;\n\n    arena_.RecycleAll();\n    allow_clean_shutdown_ = true;\n\n    Read(&packet_len);\n    if (packet_len == 0) return true;\n    Read(&code);\n    allow_clean_shutdown_ = false;\n\n    if (code >= RPCCode::kSyscallCodeStart) {\n      HandleSyscallFunc(code);\n    } else {\n      switch (code) {\n        case RPCCode::kCallFunc: {\n          HandleNormalCallFunc();\n          break;\n        }\n        case RPCCode::kInitServer: {\n          HandleInitServer();\n          break;\n        }\n        case RPCCode::kCopyFromRemote: {\n          HandleCopyFromRemote();\n          break;\n        }\n        case RPCCode::kCopyToRemote: {\n          HandleCopyToRemote();\n          break;\n        }\n        case RPCCode::kShutdown: {\n          Shutdown();\n          return false;\n        }\n        default: {\n          this->ThrowError(RPCServerStatus::kUnknownRPCCode);\n          break;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  void HandleInitServer() {\n    uint64_t len;\n    Read(&len);\n    char* proto_ver = ArenaAlloc<char>(len + 1);\n    ReadArray(proto_ver, len);\n    TVMValue* values;\n    int* tcodes;\n    int num_args;\n    RecvPackedSeq(&values, &tcodes, &num_args);\n    exec_handler_->InitServer(num_args);\n  }\n\n  void Shutdown() {\n    arena_.FreeAll();\n    io_->Close();\n  }\n\n  void HandleNormalCallFunc() {\n    uint64_t call_handle;\n    TVMValue* values;\n    int* tcodes;\n    int num_args;\n\n    Read(&call_handle);\n    RecvPackedSeq(&values, &tcodes, &num_args);\n    exec_handler_->NormalCallFunc(call_handle, values, tcodes, num_args);\n  }\n\n  void HandleCopyFromRemote() {\n    DLTensor* arr = ArenaAlloc<DLTensor>(1);\n    uint64_t data_handle;\n    Read(&data_handle);\n    arr->data = reinterpret_cast<void*>(data_handle);\n    Read(&(arr->device));\n    Read(&(arr->ndim));\n    Read(&(arr->dtype));\n    arr->shape = ArenaAlloc<int64_t>(arr->ndim);\n    ReadArray(arr->shape, arr->ndim);\n    arr->strides = nullptr;\n    Read(&(arr->byte_offset));\n\n    uint64_t num_bytes;\n    Read(&num_bytes);\n\n    uint8_t* data_ptr;\n    if (arr->device.device_type == kDLCPU) {\n      data_ptr = reinterpret_cast<uint8_t*>(data_handle) + arr->byte_offset;\n    } else {\n      data_ptr = ArenaAlloc<uint8_t>(num_bytes);\n    }\n\n    exec_handler_->CopyFromRemote(arr, num_bytes, data_ptr);\n  }\n\n  void HandleCopyToRemote() {\n    DLTensor* arr = ArenaAlloc<DLTensor>(1);\n    uint64_t data_handle;\n    Read(&data_handle);\n    arr->data = reinterpret_cast<void*>(data_handle);\n    Read(&(arr->device));\n    Read(&(arr->ndim));\n    Read(&(arr->dtype));\n    arr->shape = ArenaAlloc<int64_t>(arr->ndim);\n    ReadArray(arr->shape, arr->ndim);\n    arr->strides = nullptr;\n    Read(&(arr->byte_offset));\n    uint64_t num_bytes;\n    Read(&num_bytes);\n    int ret;\n    if (arr->device.device_type == kDLCPU) {\n      uint8_t* dptr = reinterpret_cast<uint8_t*>(data_handle) + arr->byte_offset;\n      ret = exec_handler_->CopyToRemote(arr, num_bytes, dptr);\n    } else {\n      uint8_t* temp_data = ArenaAlloc<uint8_t>(num_bytes);\n      ret = exec_handler_->CopyToRemote(arr, num_bytes, temp_data);\n    }\n    if (ret == 0) {\n      if (allow_clean_shutdown_) {\n        Shutdown();\n        io_->Exit(0);\n      } else {\n        this->ThrowError(RPCServerStatus::kReadError);\n      }\n    }\n    if (ret == -1) {\n      this->ThrowError(RPCServerStatus::kReadError);\n    }\n  }\n\n  void HandleSyscallFunc(RPCCode code) {\n    TVMValue* values;\n    int* tcodes;\n    int num_args;\n    RecvPackedSeq(&values, &tcodes, &num_args);\n\n    exec_handler_->SysCallFunc(code, values, tcodes, num_args);\n  }\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {\n    io_->Exit(static_cast<int>(code));\n  }\n\n  template <typename T>\n  T* ArenaAlloc(int count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return arena_.template allocate_<T>(count);\n  }\n\n  template <typename T>\n  void Read(T* data) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    ReadRawBytes(data, sizeof(T));\n  }\n\n  template <typename T>\n  void ReadArray(T* data, size_t count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return ReadRawBytes(data, sizeof(T) * count);\n  }\n\n private:\n  void RecvPackedSeq(TVMValue** out_values, int** out_tcodes, int* out_num_args) {\n    RPCReference::RecvPackedSeq(out_values, out_tcodes, out_num_args, this);\n  }\n\n  void ReadRawBytes(void* data, size_t size) {\n    uint8_t* buf = static_cast<uint8_t*>(data);\n    size_t ndone = 0;\n    while (ndone < size) {\n      ssize_t ret = io_->PosixRead(buf, size - ndone);\n      if (ret == 0) {\n        if (allow_clean_shutdown_) {\n          Shutdown();\n          io_->Exit(0);\n        } else {\n          this->ThrowError(RPCServerStatus::kReadError);\n        }\n      }\n      if (ret == -1) {\n        this->ThrowError(RPCServerStatus::kReadError);\n      }\n      ndone += ret;\n      buf += ret;\n    }\n  }\n\n  /*! \\brief IO handler. */\n  TIOHandler* io_;\n  /*! \\brief internal arena. */\n  support::GenericArena<PageAllocator> arena_;\n  MinRPCReturns<TIOHandler>* ret_handler_ = nullptr;\n  std::unique_ptr<MinRPCExecInterface> exec_handler_;\n  /*! \\brief Whether we are in a state that allows clean shutdown. */\n  bool allow_clean_shutdown_{true};\n  static_assert(DMLC_LITTLE_ENDIAN == 1, \"MinRPC only works on little endian.\");\n};\n\nnamespace detail {\n// Internal allocator that redirects alloc to TVM's C API.\ntemplate <typename TIOHandler>\nclass PageAllocator {\n public:\n  using ArenaPageHeader = tvm::support::ArenaPageHeader;\n\n  explicit PageAllocator(TIOHandler* io) : io_(io) {}\n\n  ArenaPageHeader* allocate(size_t min_size) {\n    size_t npages = ((min_size + kPageSize - 1) / kPageSize);\n    void* data;\n\n    if (TVMDeviceAllocDataSpace(DLDevice{kDLCPU, 0}, npages * kPageSize, kPageAlign,\n                                DLDataType{kDLInt, 1, 1}, &data) != 0) {\n      io_->Exit(static_cast<int>(RPCServerStatus::kAllocError));\n    }\n\n    ArenaPageHeader* header = static_cast<ArenaPageHeader*>(data);\n    header->size = npages * kPageSize;\n    header->offset = sizeof(ArenaPageHeader);\n    return header;\n  }\n\n  void deallocate(ArenaPageHeader* page) {\n    if (TVMDeviceFreeDataSpace(DLDevice{kDLCPU, 0}, page) != 0) {\n      io_->Exit(static_cast<int>(RPCServerStatus::kAllocError));\n    }\n  }\n\n  static const constexpr int kPageSize = 2 << 10;\n  static const constexpr int kPageAlign = 8;\n\n private:\n  TIOHandler* io_;\n};\n}  // namespace detail\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/minrpc/minrpc_server_logging.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_\n#define TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_\n\n#include <memory>\n#include <utility>\n\n#include \"minrpc_logger.h\"\n#include \"minrpc_server.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief A minimum RPC server that logs the received commands.\n *\n * \\tparam TIOHandler IO provider to provide io handling.\n */\ntemplate <typename TIOHandler>\nclass MinRPCServerWithLog {\n public:\n  explicit MinRPCServerWithLog(TIOHandler* io)\n      : ret_handler_(io),\n        ret_handler_wlog_(&ret_handler_, &logger_),\n        exec_handler_(io, &ret_handler_wlog_),\n        exec_handler_ptr_(new MinRPCExecuteWithLog(&exec_handler_, &logger_)),\n        next_(io, std::move(exec_handler_ptr_)) {}\n\n  bool ProcessOnePacket() { return next_.ProcessOnePacket(); }\n\n private:\n  Logger logger_;\n  MinRPCReturns<TIOHandler> ret_handler_;\n  MinRPCExecute<TIOHandler> exec_handler_;\n  MinRPCReturnsWithLog ret_handler_wlog_;\n  std::unique_ptr<MinRPCExecuteWithLog> exec_handler_ptr_;\n  MinRPCServer<TIOHandler> next_;\n};\n\n/*!\n * \\brief A minimum RPC server that only logs the outgoing commands and received responses.\n * (Does not process the packets or respond to them.)\n *\n * \\tparam TIOHandler IO provider to provide io handling.\n */\ntemplate <typename TIOHandler, template <typename> class Allocator = detail::PageAllocator>\nclass MinRPCSniffer {\n public:\n  using PageAllocator = Allocator<TIOHandler>;\n  explicit MinRPCSniffer(TIOHandler* io)\n      : io_(io),\n        arena_(PageAllocator(io_)),\n        ret_handler_(io_),\n        ret_handler_wlog_(&ret_handler_, &logger_),\n        exec_handler_(&ret_handler_wlog_),\n        exec_handler_ptr_(new MinRPCExecuteWithLog(&exec_handler_, &logger_)),\n        next_(io_, std::move(exec_handler_ptr_)) {}\n\n  bool ProcessOnePacket() { return next_.ProcessOnePacket(); }\n\n  void ProcessOneResponse() {\n    RPCCode code;\n    uint64_t packet_len = 0;\n\n    if (!Read(&packet_len)) return;\n    if (packet_len == 0) {\n      OutputLog();\n      return;\n    }\n    if (!Read(&code)) return;\n    switch (code) {\n      case RPCCode::kReturn: {\n        int32_t num_args;\n        int* type_codes;\n        TVMValue* values;\n        RPCReference::RecvPackedSeq(&values, &type_codes, &num_args, this);\n        ret_handler_wlog_.ReturnPackedSeq(values, type_codes, num_args);\n        break;\n      }\n      case RPCCode::kException: {\n        ret_handler_wlog_.ReturnException(\"\");\n        break;\n      }\n      default: {\n        OutputLog();\n        break;\n      }\n    }\n  }\n\n  void OutputLog() { logger_.OutputLog(); }\n\n  void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {\n    logger_.Log(\"-> \");\n    logger_.Log(RPCServerStatusToString(code));\n    OutputLog();\n  }\n\n  template <typename T>\n  T* ArenaAlloc(int count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return arena_.template allocate_<T>(count);\n  }\n\n  template <typename T>\n  bool Read(T* data) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return ReadRawBytes(data, sizeof(T));\n  }\n\n  template <typename T>\n  bool ReadArray(T* data, size_t count) {\n    static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,\n                  \"need to be trival\");\n    return ReadRawBytes(data, sizeof(T) * count);\n  }\n\n private:\n  bool ReadRawBytes(void* data, size_t size) {\n    uint8_t* buf = reinterpret_cast<uint8_t*>(data);\n    size_t ndone = 0;\n    while (ndone < size) {\n      ssize_t ret = io_->PosixRead(buf, size - ndone);\n      if (ret <= 0) {\n        this->ThrowError(RPCServerStatus::kReadError);\n        return false;\n      }\n      ndone += ret;\n      buf += ret;\n    }\n    return true;\n  }\n\n  Logger logger_;\n  TIOHandler* io_;\n  support::GenericArena<PageAllocator> arena_;\n  MinRPCReturnsNoOp<TIOHandler> ret_handler_;\n  MinRPCReturnsWithLog ret_handler_wlog_;\n  MinRPCExecuteNoOp exec_handler_;\n  std::unique_ptr<MinRPCExecuteWithLog> exec_handler_ptr_;\n  MinRPCServer<TIOHandler> next_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/minrpc/rpc_reference.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_reference.h\n * \\brief Common header defining the communication code used in the RPC protocol.\n */\n#ifndef TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_\n#define TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief The current RPC procotol version. */\nconstexpr const char* kRPCProtocolVer = \"0.8.0\";\n\n// When tvm.rpc.server.GetCRTMaxPacketSize global function is not registered.\nconst uint64_t kRPCMaxTransferSizeBytesDefault = UINT64_MAX;\n\n/*! \\brief The RPC code */\nenum class RPCCode : int {\n  kNone,\n  kShutdown,\n  kInitServer,\n  kCallFunc,\n  kReturn,\n  kException,\n  kCopyFromRemote,\n  kCopyToRemote,\n  kCopyAck,\n  // The following are syscall code that can send over CallRemote\n  kSyscallCodeStart,\n  kGetGlobalFunc = kSyscallCodeStart,\n  kFreeHandle,\n  kDevSetDevice,\n  kDevGetAttr,\n  kDevAllocData,\n  kDevFreeData,\n  kDevStreamSync,\n  kCopyAmongRemote,\n  kDevAllocDataWithScope,\n  kDevCreateStream,\n  kDevFreeStream,\n  kDevSetStream,\n};\n\n/*!\n * \\brief List of potential error status during rpc communication.\n */\nenum class RPCServerStatus : int {\n  kSuccess = 0,\n  kInvalidTypeCodeObject,\n  kInvalidTypeCodeNDArray,\n  kInvalidDLTensorFieldStride,\n  kInvalidDLTensorFieldByteOffset,\n  kUnknownTypeCode,\n  kUnknownRPCCode,\n  kRPCCodeNotSupported,\n  kUnknownRPCSyscall,\n  kCheckError,\n  kReadError,\n  kWriteError,\n  kAllocError\n};\n\ninline const char* RPCCodeToString(RPCCode code) {\n  switch (code) {\n    case RPCCode::kShutdown:\n      return \"kShutdown\";\n    case RPCCode::kInitServer:\n      return \"kInitServer\";\n    case RPCCode::kCallFunc:\n      return \"kCallFunc\";\n    case RPCCode::kReturn:\n      return \"kReturn\";\n    case RPCCode::kException:\n      return \"kException\";\n    case RPCCode::kCopyFromRemote:\n      return \"kCopyFromRemote\";\n    case RPCCode::kCopyToRemote:\n      return \"kCopyToRemote\";\n    case RPCCode::kCopyAck:\n      return \"kCopyAck\";\n    // The following are syscall code that can send over CallRemote\n    case RPCCode::kGetGlobalFunc:\n      return \"kGetGlobalFunc\";\n    case RPCCode::kFreeHandle:\n      return \"kFreeHandle\";\n    case RPCCode::kDevSetDevice:\n      return \"kDevSetDevice\";\n    case RPCCode::kDevGetAttr:\n      return \"kDevGetAttr\";\n    case RPCCode::kDevAllocData:\n      return \"kDevAllocData\";\n    case RPCCode::kDevFreeData:\n      return \"kDevFreeData\";\n    case RPCCode::kDevCreateStream:\n      return \"kDevCreateStream\";\n    case RPCCode::kDevFreeStream:\n      return \"kDevFreeStream\";\n    case RPCCode::kDevStreamSync:\n      return \"kDevStreamSync\";\n    case RPCCode::kDevSetStream:\n      return \"kDevSetStream\";\n    case RPCCode::kCopyAmongRemote:\n      return \"kCopyAmongRemote\";\n    case RPCCode::kDevAllocDataWithScope:\n      return \"kDevAllocDataWithScope\";\n    default:\n      return \"\";\n  }\n}\n\n/*!\n * \\brief Convert RPC server status to string.\n * \\param status The status.\n * \\return The corresponding string.\n */\ninline const char* RPCServerStatusToString(RPCServerStatus status) {\n  switch (status) {\n    case RPCServerStatus::kSuccess:\n      return \"kSuccess\";\n    case RPCServerStatus::kInvalidTypeCodeObject:\n      return \"kInvalidTypeCodeObject\";\n    case RPCServerStatus::kInvalidTypeCodeNDArray:\n      return \"kInvalidTypeCodeNDArray\";\n    case RPCServerStatus::kInvalidDLTensorFieldStride:\n      return \"kInvalidDLTensorFieldStride\";\n    case RPCServerStatus::kInvalidDLTensorFieldByteOffset: {\n      return \"kInvalidDLTensorFieldByteOffset\";\n    }\n    case RPCServerStatus::kUnknownTypeCode:\n      return \"kUnknownTypeCode\";\n    case RPCServerStatus::kUnknownRPCCode:\n      return \"kUnknownRPCCode\";\n    case RPCServerStatus::kRPCCodeNotSupported:\n      return \"RPCCodeNotSupported\";\n    case RPCServerStatus::kUnknownRPCSyscall:\n      return \"kUnknownRPCSyscall\";\n    case RPCServerStatus::kCheckError:\n      return \"kCheckError\";\n    case RPCServerStatus::kReadError:\n      return \"kReadError\";\n    case RPCServerStatus::kWriteError:\n      return \"kWriteError\";\n    case RPCServerStatus::kAllocError:\n      return \"kAllocError\";\n    default:\n      return \"\";\n  }\n}\n\n/*!\n * \\brief Reference implementation of the communication protocol.\n *\n * \\note The implementation is intentionally written via template\n *       so it can be used in a dependency free setting.\n *\n * \\sa src/runtime/rpc/device/min_rpc_server.h\n */\nstruct RPCReference {\n  /*!\n   * \\brief Auxiliary class to get the packed sequence.\n   * \\tparam TChannel The channel to throw errror.\n   */\n  template <typename TChannel>\n  struct PackedSeqNumBytesGetter {\n   public:\n    explicit PackedSeqNumBytesGetter(TChannel* channel) : channel_(channel) {}\n\n    template <typename T>\n    void Write(const T& value) {\n      num_bytes_ += sizeof(T);\n    }\n\n    template <typename T>\n    void WriteArray(const T* value, size_t num) {\n      num_bytes_ += sizeof(T) * num;\n    }\n\n    void ThrowError(RPCServerStatus status) { channel_->ThrowError(status); }\n\n    uint64_t num_bytes() const { return num_bytes_; }\n\n   private:\n    TChannel* channel_;\n    uint64_t num_bytes_{0};\n  };\n\n  /*!\n   * \\return the length of the str.\n   * \\param str the string.\n   * \\return The length.\n   */\n  static uint64_t StrLength(const char* str) {\n    uint64_t len = 0;\n    while (str[len] != '\\0') ++len;\n    return len;\n  }\n\n  /*!\n   * \\brief Get the total nbytes to be sent in the packed sequence.\n   *\n   * \\param arg_values The values to be sent over.\n   * \\param type_codes The type codes to be sent over.\n   * \\param num_args Number of argument.\n   * \\param client_mode Whether it is a client to server call.\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   * \\return The total number of bytes.\n   */\n  template <typename TChannel>\n  static uint64_t PackedSeqGetNumBytes(const TVMValue* arg_values, const int* type_codes,\n                                       int num_args, bool client_mode, TChannel* channel) {\n    PackedSeqNumBytesGetter<TChannel> getter(channel);\n    SendPackedSeq(arg_values, type_codes, num_args, client_mode, &getter);\n    return getter.num_bytes();\n  }\n\n  template <typename TChannelPtr>\n  static void SendDLTensor(TChannelPtr channel, DLTensor* arr) {\n    DLDevice dev;\n    uint64_t data;\n    // When we return NDArray, we directly return\n    // the space and the context\n    // The client will be further wrapping\n    dev = arr->device;\n    data = reinterpret_cast<uint64_t>(arr->data);\n    channel->Write(data);\n    channel->Write(dev);\n    channel->Write(arr->ndim);\n    channel->Write(arr->dtype);\n    channel->WriteArray(arr->shape, arr->ndim);\n    if (arr->strides != nullptr) {\n      channel->ThrowError(RPCServerStatus::kInvalidDLTensorFieldStride);\n    }\n    channel->Write(arr->byte_offset);\n    return;\n  }\n\n  template <typename TChannelPtr>\n  static DLTensor* ReceiveDLTensor(TChannelPtr channel) {\n    uint64_t handle;\n    channel->Read(&handle);\n    DLTensor* arr = channel->template ArenaAlloc<DLTensor>(1);\n    DLTensor& tensor = *arr;\n    tensor.data = reinterpret_cast<void*>(handle);\n    channel->Read(&(tensor.device));\n    channel->Read(&(tensor.ndim));\n    channel->Read(&(tensor.dtype));\n    tensor.shape = channel->template ArenaAlloc<int64_t>(tensor.ndim);\n    channel->ReadArray(tensor.shape, tensor.ndim);\n    tensor.strides = nullptr;\n    channel->Read(&(tensor.byte_offset));\n    return arr;\n  }\n\n  /*!\n   * \\brief Send packed argument sequnce to the other peer.\n   *\n   * This function serves as the foundational communication primitive between peers.\n   *\n   * TVMValue sequence encoding protocol(according to the type):\n   *\n   * - int/float/uint/bytes/str: Serialize all content.\n   * - DLTensor: send meta-data, send data handle as opaque handle(via uint64_t)\n   * - OpaqueHandle: send as uint64_t\n   * - ModuleHandle, PackedFuncHandle: send as uint64_t,\n   *   The support to Module/PackedFuncHandle are reserved for arguments\n   *   in the CallFunc from a client to server only.\n   *   Note that we cannot simply take these argument out(as the handle)\n   *   refers to a value on the remote(instead of local).\n   *\n   * \\param arg_values The values to be sent over.\n   * \\param type_codes The type codes to be sent over.\n   * \\param num_args Number of argument.\n   * \\param client_mode Whether it is a client to server call.\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   */\n  template <typename TChannel>\n  static void SendPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args,\n                            bool client_mode, TChannel* channel) {\n    channel->Write(num_args);\n    channel->WriteArray(type_codes, num_args);\n\n    // Argument packing.\n    for (int i = 0; i < num_args; ++i) {\n      int tcode = type_codes[i];\n      TVMValue value = arg_values[i];\n      switch (tcode) {\n        case kDLInt:\n        case kDLUInt:\n        case kDLFloat: {\n          channel->template Write<int64_t>(value.v_int64);\n          break;\n        }\n        case kTVMDataType: {\n          channel->Write(value.v_type);\n          // padding\n          int32_t padding = 0;\n          channel->template Write<int32_t>(padding);\n          break;\n        }\n        case kDLDevice: {\n          channel->Write(value.v_device);\n          break;\n        }\n\n        case kTVMPackedFuncHandle:\n        case kTVMModuleHandle: {\n          if (!client_mode) {\n            channel->ThrowError(RPCServerStatus::kInvalidTypeCodeObject);\n          }\n          // always send handle in 64 bit.\n          uint64_t handle = reinterpret_cast<uint64_t>(value.v_handle);\n          channel->Write(handle);\n          break;\n        }\n        case kTVMOpaqueHandle: {\n          // always send handle in 64 bit.\n          uint64_t handle = reinterpret_cast<uint64_t>(value.v_handle);\n          channel->Write(handle);\n          break;\n        }\n        case kTVMNDArrayHandle: {\n          channel->ThrowError(RPCServerStatus::kInvalidTypeCodeNDArray);\n          break;\n        }\n        case kTVMDLTensorHandle: {\n          DLTensor* arr = static_cast<DLTensor*>(value.v_handle);\n          SendDLTensor(channel, arr);\n          break;\n        }\n        case kTVMNullptr:\n          break;\n        case kTVMStr: {\n          const char* s = value.v_str;\n          uint64_t len = StrLength(s);\n          channel->Write(len);\n          channel->WriteArray(s, len);\n          break;\n        }\n        case kTVMBytes: {\n          TVMByteArray* bytes = static_cast<TVMByteArray*>(arg_values[i].v_handle);\n          uint64_t len = bytes->size;\n          channel->Write(len);\n          channel->WriteArray(bytes->data, len);\n          break;\n        }\n        default: {\n          channel->ThrowError(RPCServerStatus::kUnknownTypeCode);\n          break;\n        }\n      }\n    }\n  }\n\n  /*!\n   * \\brief Receive packed seq from the channel.\n   *\n   * \\param out_arg_values The values to be received.\n   * \\param out_tcodes The type codes to be received.\n   * \\param out_num_args Number of argument.\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   * \\note The temporary space are populated via an arena inside channel.\n   */\n  template <typename TChannel>\n  static void RecvPackedSeq(TVMValue** out_values, int** out_tcodes, int* out_num_args,\n                            TChannel* channel) {\n    // receive number of args\n    int num_args;\n    channel->Read(&num_args);\n    *out_num_args = num_args;\n\n    if (num_args == 0) {\n      *out_values = nullptr;\n      *out_tcodes = nullptr;\n      return;\n    }\n\n    TVMValue* values = channel->template ArenaAlloc<TVMValue>(num_args);\n    int* tcodes = channel->template ArenaAlloc<int>(num_args);\n    *out_values = values;\n    *out_tcodes = tcodes;\n\n    // receive type code.\n    channel->ReadArray(tcodes, num_args);\n\n    // receive arguments\n    for (int i = 0; i < num_args; ++i) {\n      auto& value = values[i];\n      switch (tcodes[i]) {\n        case kDLInt:\n        case kDLUInt:\n        case kDLFloat: {\n          channel->template Read<int64_t>(&(value.v_int64));\n          break;\n        }\n        case kTVMDataType: {\n          channel->Read(&(value.v_type));\n          int32_t padding = 0;\n          channel->template Read<int32_t>(&padding);\n          break;\n        }\n        case kDLDevice: {\n          channel->Read(&(value.v_device));\n          break;\n        }\n        case kTVMPackedFuncHandle:\n        case kTVMModuleHandle:\n        case kTVMOpaqueHandle: {\n          // always send handle in 64 bit.\n          uint64_t handle;\n          channel->Read(&handle);\n          value.v_handle = reinterpret_cast<void*>(handle);\n          break;\n        }\n        case kTVMNullptr: {\n          value.v_handle = nullptr;\n          break;\n        }\n        case kTVMStr: {\n          uint64_t len;\n          channel->Read(&len);\n          char* str = channel->template ArenaAlloc<char>(len + 1);\n          str[len] = '\\0';\n          channel->ReadArray(str, len);\n          value.v_str = str;\n          break;\n        }\n        case kTVMBytes: {\n          uint64_t len;\n          channel->Read(&len);\n          TVMByteArray* arr = channel->template ArenaAlloc<TVMByteArray>(1);\n          char* data = channel->template ArenaAlloc<char>(len);\n          arr->size = len;\n          arr->data = data;\n          channel->ReadArray(data, len);\n          value.v_handle = arr;\n          break;\n        }\n        case kTVMDLTensorHandle: {\n          value.v_handle = ReceiveDLTensor(channel);\n          break;\n        }\n        default: {\n          channel->ThrowError(RPCServerStatus::kUnknownTypeCode);\n          break;\n        }\n      }\n    }\n  }\n\n  /*!\n   * \\brief Return an exception packet.\n   *\n   * \\param msg The error message.\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   */\n  template <typename TChannel>\n  static void ReturnException(const char* msg, TChannel* channel) {\n    RPCCode code = RPCCode::kException;\n    int32_t num_args = 1;\n    int32_t tcode = kTVMStr;\n    uint64_t len = StrLength(msg);\n\n    uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode) + sizeof(len) + len;\n\n    channel->MessageStart(packet_nbytes);\n    channel->Write(packet_nbytes);\n    channel->Write(code);\n    channel->Write(num_args);\n    channel->Write(tcode);\n    channel->Write(len);\n    channel->WriteArray(msg, len);\n    channel->MessageDone();\n  }\n\n  /*!\n   * \\brief Return a normal packed sequence packet.\n   *\n   * \\param msg The error message.\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   */\n  template <typename TChannel>\n  static void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args,\n                              TChannel* channel) {\n    RPCCode code = RPCCode::kReturn;\n\n    uint64_t packet_nbytes =\n        sizeof(code) + PackedSeqGetNumBytes(arg_values, type_codes, num_args, false, channel);\n\n    channel->MessageStart(packet_nbytes);\n    channel->Write(packet_nbytes);\n    channel->Write(code);\n    SendPackedSeq(arg_values, type_codes, num_args, false, channel);\n    channel->MessageDone();\n  }\n\n  /*!\n   * \\brief Return a null(void) packet.\n   *\n   * \\param channel The communication channel handler.\n   * \\tparam TChannel The type of the communication channel.\n   */\n  template <typename TChannel>\n  static void ReturnVoid(TChannel* channel) {\n    int32_t num_args = 1;\n    int32_t tcode = kTVMNullptr;\n    RPCCode code = RPCCode::kReturn;\n\n    uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode);\n\n    channel->MessageStart(packet_nbytes);\n    channel->Write(packet_nbytes);\n    channel->Write(code);\n    channel->Write(num_args);\n    channel->Write(tcode);\n    channel->MessageDone();\n  }\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/object_internal.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*\n * \\file src/runtime/object_internal.h\n * \\brief Expose a few functions for CFFI purposes.\n *        This file is not intended to be used\n */\n#ifndef TVM_RUNTIME_OBJECT_INTERNAL_H_\n#define TVM_RUNTIME_OBJECT_INTERNAL_H_\n\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Internal object namespace to expose\n *        certain util functions for FFI.\n */\nclass ObjectInternal {\n public:\n  /*!\n   * \\brief Retain an object handle.\n   */\n  static void ObjectRetain(TVMObjectHandle obj) {\n    if (obj != nullptr) {\n      static_cast<Object*>(obj)->IncRef();\n    }\n  }\n\n  /*!\n   * \\brief Free an object handle.\n   */\n  static void ObjectFree(TVMObjectHandle obj) {\n    if (obj != nullptr) {\n      static_cast<Object*>(obj)->DecRef();\n    }\n  }\n  /*!\n   * \\brief Check of obj derives from the type indicated by type index.\n   * \\param obj The original object.\n   * \\param type_index The type index of interest.\n   * \\return The derivation checking result.\n   */\n  static bool DerivedFrom(const Object* obj, uint32_t type_index) {\n    return obj->DerivedFrom(type_index);\n  }\n  /*!\n   * \\brief Expose TypeKey2Index\n   * \\param type_key The original type key.\n   * \\return the corresponding index.\n   */\n  static uint32_t ObjectTypeKey2Index(const std::string& type_key) {\n    return Object::TypeKey2Index(type_key);\n  }\n  /*!\n   * \\brief Convert ModuleHandle to module node pointer.\n   * \\param handle The module handle.\n   * \\return the corresponding module node pointer.\n   */\n  static ModuleNode* GetModuleNode(TVMModuleHandle handle) {\n    // NOTE: we will need to convert to Object\n    // then to ModuleNode in order to get the correct\n    // address translation\n    return static_cast<ModuleNode*>(static_cast<Object*>(handle));\n  }\n  /*!\n   * \\brief Move the ObjectPtr inside ObjectRef out\n   * \\param obj The ObjectRef\n   * \\return The result ObjectPtr\n   */\n  static ObjectPtr<Object> MoveObjectPtr(ObjectRef* obj) {\n    ObjectPtr<Object> data = std::move(obj->data_);\n    return data;\n  }\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OBJECT_INTERNAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/aocl/aocl_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file aocl_common.h\n * \\brief AOCL common header\n */\n#ifndef TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_\n#define TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_\n\n#include <memory>\n\n#include \"../opencl_common.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace cl {\n\n/*!\n * \\brief Process global AOCL workspace.\n */\nclass AOCLWorkspace final : public OpenCLWorkspace {\n public:\n  // override OpenCL device API\n  void Init() final;\n  bool IsOpenCLDevice(Device dev) final;\n  OpenCLThreadEntry* GetThreadEntry() final;\n  // get the global workspace\n  static OpenCLWorkspace* Global();\n};\n\n/*! \\brief Thread local workspace for AOCL */\nclass AOCLThreadEntry : public OpenCLThreadEntry {\n public:\n  // constructor\n  AOCLThreadEntry()\n      : OpenCLThreadEntry(static_cast<DLDeviceType>(kDLAOCL), AOCLWorkspace::Global()) {}\n\n  // get the global workspace\n  static AOCLThreadEntry* ThreadLocal();\n};\n}  // namespace cl\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/aocl/aocl_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file aocl_module.h\n * \\brief Execution handling of OpenCL kernels for AOCL\n */\n#ifndef TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_\n#define TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief create a opencl module for AOCL from data.\n *\n * \\param data The module data.\n * \\param fmt The format of the data, can be \"aocx\"\n * \\param fmap The map function information map of each function.\n */\nModule AOCLModuleCreate(std::string data, std::string fmt,\n                        std::unordered_map<std::string, FunctionInfo> fmap, std::string source);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/opencl_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file opencl_common.h\n * \\brief OpenCL common header\n */\n#ifndef TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_\n#define TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/profiling.h>\n\n/* There are many OpenCL platforms that do not yet support OpenCL 2.0,\n * hence we use 1.2 APIs, some of which are now deprecated.  In order\n * to turn off the deprecation warnings (elevated to errors by\n * -Werror) we explicitly disable the 1.2 deprecation warnings.\n *\n * At the point TVM supports minimum version 2.0, we can remove this\n * define.\n */\n#define CL_USE_DEPRECATED_OPENCL_1_2_APIS\n\n/* Newer releases of OpenCL header files (after May 2018) work with\n * any OpenCL version, with an application's target version\n * specified. Setting the target version disables APIs from after that\n * version, and sets appropriate USE_DEPRECATED macros.  The above\n * macro for CL_USE_DEPRECATED_OPENCL_1_2_APIS is still needed in case\n * we are compiling against the earlier version-specific OpenCL header\n * files.  This also allows us to expose the OpenCL version through\n * tvm.runtime.Device.\n */\n#define CL_TARGET_OPENCL_VERSION 120\n\n#ifdef __APPLE__\n#include <OpenCL/opencl.h>\n#else\n#include <CL/opencl.h>\n#endif\n\n#include <memory>\n#include <mutex>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../file_utils.h\"\n#include \"../meta_data.h\"\n#include \"../pack_args.h\"\n#include \"../texture.h\"\n#include \"../thread_storage_scope.h\"\n#include \"../workspace_pool.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace cl {\n\nstatic_assert(sizeof(cl_mem) == sizeof(void*), \"Required to store cl_mem inside void*\");\n\ninline const char* CLGetErrorString(cl_int error) {\n  switch (error) {\n    case CL_SUCCESS:\n      return \"CL_SUCCESS\";\n    case CL_DEVICE_NOT_FOUND:\n      return \"CL_DEVICE_NOT_FOUND\";\n    case CL_DEVICE_NOT_AVAILABLE:\n      return \"CL_DEVICE_NOT_AVAILABLE\";\n    case CL_COMPILER_NOT_AVAILABLE:\n      return \"CL_COMPILER_NOT_AVAILABLE\";\n    case CL_MEM_OBJECT_ALLOCATION_FAILURE:\n      return \"CL_MEM_OBJECT_ALLOCATION_FAILURE\";\n    case CL_OUT_OF_RESOURCES:\n      return \"CL_OUT_OF_RESOURCES\";\n    case CL_OUT_OF_HOST_MEMORY:\n      return \"CL_OUT_OF_HOST_MEMORY\";\n    case CL_PROFILING_INFO_NOT_AVAILABLE:\n      return \"CL_PROFILING_INFO_NOT_AVAILABLE\";\n    case CL_MEM_COPY_OVERLAP:\n      return \"CL_MEM_COPY_OVERLAP\";\n    case CL_IMAGE_FORMAT_MISMATCH:\n      return \"CL_IMAGE_FORMAT_MISMATCH\";\n    case CL_IMAGE_FORMAT_NOT_SUPPORTED:\n      return \"CL_IMAGE_FORMAT_NOT_SUPPORTED\";\n    case CL_BUILD_PROGRAM_FAILURE:\n      return \"CL_BUILD_PROGRAM_FAILURE\";\n    case CL_MAP_FAILURE:\n      return \"CL_MAP_FAILURE\";\n    case CL_INVALID_VALUE:\n      return \"CL_INVALID_VALUE\";\n    case CL_INVALID_DEVICE_TYPE:\n      return \"CL_INVALID_DEVICE_TYPE\";\n    case CL_INVALID_PLATFORM:\n      return \"CL_INVALID_PLATFORM\";\n    case CL_INVALID_DEVICE:\n      return \"CL_INVALID_DEVICE\";\n    case CL_INVALID_CONTEXT:\n      return \"CL_INVALID_CONTEXT\";\n    case CL_INVALID_QUEUE_PROPERTIES:\n      return \"CL_INVALID_QUEUE_PROPERTIES\";\n    case CL_INVALID_COMMAND_QUEUE:\n      return \"CL_INVALID_COMMAND_QUEUE\";\n    case CL_INVALID_HOST_PTR:\n      return \"CL_INVALID_HOST_PTR\";\n    case CL_INVALID_MEM_OBJECT:\n      return \"CL_INVALID_MEM_OBJECT\";\n    case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:\n      return \"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\";\n    case CL_INVALID_IMAGE_SIZE:\n      return \"CL_INVALID_IMAGE_SIZE\";\n    case CL_INVALID_SAMPLER:\n      return \"CL_INVALID_SAMPLER\";\n    case CL_INVALID_BINARY:\n      return \"CL_INVALID_BINARY\";\n    case CL_INVALID_BUILD_OPTIONS:\n      return \"CL_INVALID_BUILD_OPTIONS\";\n    case CL_INVALID_PROGRAM:\n      return \"CL_INVALID_PROGRAM\";\n    case CL_INVALID_PROGRAM_EXECUTABLE:\n      return \"CL_INVALID_PROGRAM_EXECUTABLE\";\n    case CL_INVALID_KERNEL_NAME:\n      return \"CL_INVALID_KERNEL_NAME\";\n    case CL_INVALID_KERNEL_DEFINITION:\n      return \"CL_INVALID_KERNEL_DEFINITION\";\n    case CL_INVALID_KERNEL:\n      return \"CL_INVALID_KERNEL\";\n    case CL_INVALID_ARG_INDEX:\n      return \"CL_INVALID_ARG_INDEX\";\n    case CL_INVALID_ARG_VALUE:\n      return \"CL_INVALID_ARG_VALUE\";\n    case CL_INVALID_ARG_SIZE:\n      return \"CL_INVALID_ARG_SIZE\";\n    case CL_INVALID_KERNEL_ARGS:\n      return \"CL_INVALID_KERNEL_ARGS\";\n    case CL_INVALID_WORK_DIMENSION:\n      return \"CL_INVALID_WORK_DIMENSION\";\n    case CL_INVALID_WORK_GROUP_SIZE:\n      return \"CL_INVALID_WORK_GROUP_SIZE\";\n    case CL_INVALID_WORK_ITEM_SIZE:\n      return \"CL_INVALID_WORK_ITEM_SIZE\";\n    case CL_INVALID_GLOBAL_OFFSET:\n      return \"CL_INVALID_GLOBAL_OFFSET\";\n    case CL_INVALID_EVENT_WAIT_LIST:\n      return \"CL_INVALID_EVENT_WAIT_LIST\";\n    case CL_INVALID_EVENT:\n      return \"CL_INVALID_EVENT\";\n    case CL_INVALID_OPERATION:\n      return \"CL_INVALID_OPERATION\";\n    case CL_INVALID_GL_OBJECT:\n      return \"CL_INVALID_GL_OBJECT\";\n    case CL_INVALID_BUFFER_SIZE:\n      return \"CL_INVALID_BUFFER_SIZE\";\n    case CL_INVALID_MIP_LEVEL:\n      return \"CL_INVALID_MIP_LEVEL\";\n    default:\n      return \"Unknown OpenCL error code\";\n  }\n}\n\ninline cl_channel_type DTypeToOpenCLChannelType(DLDataType data_type) {\n  DataType dtype(data_type);\n  if (dtype == DataType::Float(32)) {\n    return CL_FLOAT;\n  } else if (dtype == DataType::Float(16)) {\n    return CL_HALF_FLOAT;\n  } else if (dtype == DataType::Int(8)) {\n    return CL_SIGNED_INT8;\n  } else if (dtype == DataType::Int(16)) {\n    return CL_SIGNED_INT16;\n  } else if (dtype == DataType::Int(32)) {\n    return CL_SIGNED_INT32;\n  } else if (dtype == DataType::UInt(8)) {\n    return CL_UNSIGNED_INT8;\n  } else if (dtype == DataType::UInt(16)) {\n    return CL_UNSIGNED_INT16;\n  } else if (dtype == DataType::UInt(32)) {\n    return CL_UNSIGNED_INT32;\n  }\n  LOG(FATAL) << \"data type is not supported in OpenCL runtime yet: \" << dtype;\n  return CL_FLOAT;\n}\n\n/*!\n * \\brief Protected OpenCL call\n * \\param func Expression to call.\n */\n#define OPENCL_CHECK_ERROR(e) \\\n  { ICHECK(e == CL_SUCCESS) << \"OpenCL Error, code=\" << e << \": \" << cl::CLGetErrorString(e); }\n\n#define OPENCL_CALL(func)  \\\n  {                        \\\n    cl_int e = (func);     \\\n    OPENCL_CHECK_ERROR(e); \\\n  }\n\nclass OpenCLThreadEntry;\n\n/*!\n * \\brief Process global OpenCL workspace.\n */\nclass OpenCLWorkspace : public DeviceAPI {\n public:\n  // type key\n  std::string type_key;\n  // global platform id\n  cl_platform_id platform_id;\n  // global platform name\n  std::string platform_name;\n  // global context of this process\n  cl_context context{nullptr};\n  // whether the workspace it initialized.\n  bool initialized_{false};\n  // the device type\n  std::string device_type;\n  // the devices\n  std::vector<cl_device_id> devices;\n  // the queues\n  std::vector<cl_command_queue> queues;\n  // the events\n  std::vector<std::vector<cl_event>> events;\n  // Number of registered kernels\n  // Used to register kernel into the workspace.\n  size_t num_registered_kernels{0};\n  // The version counter, used\n  size_t timestamp{0};\n  // Ids that are freed by kernels.\n  std::vector<size_t> free_kernel_ids;\n  // the mutex for initialization\n  std::mutex mu;\n  // destructor\n  ~OpenCLWorkspace() {\n    if (context != nullptr) {\n      OPENCL_CALL(clReleaseContext(context));\n    }\n  }\n  // Initialzie the device.\n  void Init(const std::string& type_key, const std::string& device_type,\n            const std::string& platform_name = \"\");\n  virtual void Init() { Init(\"opencl\", \"gpu\"); }\n  // Check whether the context is OpenCL or not.\n  virtual bool IsOpenCLDevice(Device dev) { return dev.device_type == kDLOpenCL; }\n  // get the queue of the device\n  cl_command_queue GetQueue(Device dev) {\n    ICHECK(IsOpenCLDevice(dev));\n    this->Init();\n    ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < queues.size())\n        << \"Invalid OpenCL device_id=\" << dev.device_id;\n    return queues[dev.device_id];\n  }\n  // get the event queue of the context\n  std::vector<cl_event>& GetEventQueue(Device dev) {\n    ICHECK(IsOpenCLDevice(dev));\n    this->Init();\n    ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < queues.size())\n        << \"Invalid OpenCL device_id=\" << dev.device_id;\n    return events[dev.device_id];\n  }\n  // is current clCommandQueue in profiling mode\n  bool IsProfiling(Device dev) {\n    cl_command_queue queue = GetQueue(dev);\n    cl_command_queue_properties prop;\n\n    OPENCL_CALL(clGetCommandQueueInfo(queue, CL_QUEUE_PROPERTIES,\n                                      sizeof(cl_command_queue_properties), &prop, nullptr));\n\n    return prop & CL_QUEUE_PROFILING_ENABLE;\n  }\n\n  // override device API\n  void SetDevice(Device dev) final;\n  void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;\n  void* AllocDataSpace(Device dev, size_t size, size_t alignment, DLDataType type_hint) final;\n  void* AllocDataSpace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,\n                       Optional<String> mem_scope = NullOpt) final;\n  void FreeDataSpace(Device dev, void* ptr) final;\n  void StreamSync(Device dev, TVMStreamHandle stream) final;\n  void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;\n  void FreeWorkspace(Device dev, void* data) final;\n\n  // Texture (image2d_t) alloca APIs\n  cl_mem AllocTexture(Device dev, size_t width, size_t height, DLDataType type_hint);\n  void* AllocTextureWorkspace(Device dev, size_t width, size_t height, DLDataType type_hint);\n  void FreeTextureWorkspace(Device dev, void* data);\n\n  /*!\n   * \\brief Get the thread local ThreadEntry\n   */\n  virtual OpenCLThreadEntry* GetThreadEntry();\n\n  // get the global workspace\n  static OpenCLWorkspace* Global();\n\n  void CopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream) final;\n};\n\n/*! \\brief Thread local workspace */\nclass OpenCLThreadEntry {\n public:\n  // The kernel entry and version.\n  struct KTEntry {\n    // The kernel handle.\n    cl_kernel kernel{nullptr};\n    // timestamp used to recognize stale kernel\n    size_t version{0};\n  };\n  /*! \\brief The current device */\n  Device device;\n  /*! \\brief The thread-local kernel table */\n  std::vector<KTEntry> kernel_table;\n  /*! \\brief workspace pool */\n  WorkspacePool pool;\n  /*! \\brief texture pool */\n  TexturePool texture_pool;\n  // constructor\n  OpenCLThreadEntry(DLDeviceType device_type, DeviceAPI* device_api)\n      : pool(device_type, device_api), texture_pool(device_type, device_api) {\n    device.device_id = 0;\n    device.device_type = device_type;\n  }\n  OpenCLThreadEntry() : OpenCLThreadEntry(kDLOpenCL, OpenCLWorkspace::Global()) {}\n\n  // get the global workspace\n  static OpenCLThreadEntry* ThreadLocal();\n};\n\n/*! \\brief OpenCL runtime buffer structure with tracked memory layout\n    TODO(tvm-team): Uncouple use of storage scope and data layout by using the transform_layout\n    schedule primitive to express the desired texture layout. This will require supporting Nd\n    indices in BufferLoad and BufferStore in CodegenOpenCL, and ensuring Nd allocations for\n    texture are correctly routed to the AllocateTexture packed function in the OpenCL DeviceAPI.\n*/\nstruct BufferDescriptor {\n  enum class MemoryLayout {\n    /*! \\brief One dimensional buffer in row-major layout*/\n    kBuffer1D,\n    /*! \\brief Two dimensional texture w/ width = axis[-1]\n     *          e.g. image2d[height=NCH, width=W]\n     */\n    kImage2DActivation,\n    /*! \\brief Two dimensional texture w/ height = axis[0]\n     *         e.g. image2d[height=O, width=IHW]\n     */\n    kImage2DWeight,\n    /*! \\brief Two dimensional texture w/ height = axis[1]\n     *         e.g. image2d[height=NH, width=WC]\n     */\n    kImage2DNHWC,\n  };\n  BufferDescriptor() = default;\n  explicit BufferDescriptor(Optional<String> scope) : layout(MemoryLayoutFromScope(scope)) {}\n  static MemoryLayout MemoryLayoutFromScope(Optional<String> mem_scope);\n  static String ScopeFromMemoryLayout(MemoryLayout mem_scope);\n\n  cl_mem buffer{nullptr};\n  MemoryLayout layout{MemoryLayout::kBuffer1D};\n};\n}  // namespace cl\n\n// Module to support thread-safe multi-device execution.\n// OpenCL runtime is a bit tricky because clSetKernelArg is not thread-safe\n// To make the call thread-safe, we create a thread-local kernel table\n// and lazily install new kernels into the kernel table when the kernel is called.\n// The kernels are recycled when the module get destructed.\nclass OpenCLModuleNode : public ModuleNode {\n public:\n  // Kernel table reference entry.\n  struct KTRefEntry {\n    size_t kernel_id;\n    size_t version;\n  };\n  explicit OpenCLModuleNode(std::string data, std::string fmt,\n                            std::unordered_map<std::string, FunctionInfo> fmap, std::string source)\n      : data_(data), fmt_(fmt), fmap_(fmap), source_(source) {}\n  // destructor\n  ~OpenCLModuleNode();\n\n  /*!\n   * \\brief Get the global workspace\n   */\n  virtual cl::OpenCLWorkspace* GetGlobalWorkspace();\n\n  const char* type_key() const final { return workspace_->type_key.c_str(); }\n\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n  void SaveToFile(const std::string& file_name, const std::string& format) final;\n  void SaveToBinary(dmlc::Stream* stream) final;\n  std::string GetSource(const std::string& format) final;\n  // Initialize the programs\n  void Init();\n  // install a new kernel to thread local entry\n  cl_kernel InstallKernel(cl::OpenCLWorkspace* w, cl::OpenCLThreadEntry* t,\n                          const std::string& func_name, const KTRefEntry& e);\n\n private:\n  // The workspace, need to keep reference to use it in destructor.\n  // In case of static destruction order problem.\n  cl::OpenCLWorkspace* workspace_;\n  // the binary data\n  std::string data_;\n  // The format\n  std::string fmt_;\n  // function information table.\n  std::unordered_map<std::string, FunctionInfo> fmap_;\n  // Module local mutex\n  std::mutex build_lock_;\n  // The OpenCL source.\n  std::string source_;\n  // Mapping from primitive name to cl program for each device.\n  std::unordered_map<std::string, std::vector<cl_program>> programs_;\n  // kernel id cache\n  std::unordered_map<std::string, KTRefEntry> kid_map_;\n  // kernels build so far.\n  std::vector<cl_kernel> kernels_;\n  // parsed kernel data\n  std::unordered_map<std::string, std::string> parsed_kernels_;\n};\n\n/*! \\brief OpenCL timer node */\nclass OpenCLTimerNode : public TimerNode {\n public:\n  // Timer start\n  virtual void Start() {\n    this->duration = 0;\n    if (count_timer_execs == 0) {\n      cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).clear();\n      // Very first call of Start() leads to the recreation of\n      // OpenCL command queue in profiling mode. This allows to run profile after inference.\n      recreateCommandQueue();\n    }\n    ++count_timer_execs;\n    // set new first idx in event queue\n    if (event_start_idxs.size() < count_timer_execs) {\n      event_start_idxs.push_back(0);\n    }\n  }\n  // Timer stop\n  virtual void Stop() {\n    std::vector<cl_event> evt_queue = cl::OpenCLWorkspace::Global()->GetEventQueue(dev_);\n    cl_ulong start, end;\n    size_t start_idx = event_start_idxs[count_timer_execs - 1];\n\n    if (cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).size() > 0) {\n      OPENCL_CALL(clWaitForEvents(1, &(cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).back())));\n      for (size_t i = start_idx; i < evt_queue.size(); ++i) {\n        auto& kevt = evt_queue[i];\n        OPENCL_CALL(clGetEventProfilingInfo(kevt, CL_PROFILING_COMMAND_START, sizeof(cl_ulong),\n                                            &start, nullptr));\n        OPENCL_CALL(clGetEventProfilingInfo(kevt, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end,\n                                            nullptr));\n        this->duration += (end - start);\n      }\n    }\n    // update event index for current call nesting\n    event_start_idxs[count_timer_execs - 1] = evt_queue.size();\n    --count_timer_execs;\n  }\n  virtual int64_t SyncAndGetElapsedNanos() { return this->duration; }\n  // destructor\n  virtual ~OpenCLTimerNode() {\n    // Profiling session ends, recreate clCommandQueue in non-profiling mode\n    // This will disable collection of cl_events in case of executing inference after profile\n    if (count_timer_execs == 0) {\n      recreateCommandQueue();\n      event_start_idxs.clear();\n    }\n  }\n  // constructor\n  OpenCLTimerNode() {}\n  explicit OpenCLTimerNode(Device dev) : dev_(dev) {}\n\n  static constexpr const char* _type_key = \"OpenCLTimerNode\";\n  static size_t count_timer_execs;\n  static std::vector<size_t> event_start_idxs;\n  TVM_DECLARE_FINAL_OBJECT_INFO(OpenCLTimerNode, TimerNode);\n\n private:\n  int64_t duration;\n  Device dev_;\n\n  void recreateCommandQueue() {\n    cl_command_queue_properties prop;\n\n    if (!cl::OpenCLWorkspace::Global()->IsProfiling(dev_)) {\n      prop = CL_QUEUE_PROFILING_ENABLE;\n    } else {\n      prop = 0;\n    }\n\n    auto queue = cl::OpenCLWorkspace::Global()->GetQueue(dev_);\n\n    OPENCL_CALL(clFlush(queue));\n    OPENCL_CALL(clFinish(queue));\n    OPENCL_CALL(clReleaseCommandQueue(queue));\n\n    cl_int err_code;\n    cl_device_id did = cl::OpenCLWorkspace::Global()->devices[dev_.device_id];\n    auto profiling_queue =\n        clCreateCommandQueue(cl::OpenCLWorkspace::Global()->context, did, prop, &err_code);\n    OPENCL_CHECK_ERROR(err_code);\n    cl::OpenCLWorkspace::Global()->queues[dev_.device_id] = profiling_queue;\n  }\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/opencl_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file opencl_module.h\n * \\brief Execution handling of OPENCL kernels\n */\n#ifndef TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_\n#define TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief create a opencl module for GPU devices from data.\n *\n * \\param data The module data.\n * \\param fmt The format of the data, can be \"clbin\", \"cl\"\n * \\param fmap The map function information map of each function.\n */\nModule OpenCLModuleCreate(std::string data, std::string fmt,\n                          std::unordered_map<std::string, FunctionInfo> fmap, std::string source);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/sdaccel/sdaccel_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file sdaccel_common.h\n * \\brief SDAccel common header\n */\n#ifndef TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_\n#define TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_\n\n#include <memory>\n\n#include \"../opencl_common.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace cl {\n\n/*!\n * \\brief Process global SDAccel workspace.\n */\nclass SDAccelWorkspace final : public OpenCLWorkspace {\n public:\n  // override OpenCL device API\n  void Init() final;\n  bool IsOpenCLDevice(Device dev) final;\n  OpenCLThreadEntry* GetThreadEntry() final;\n  // get the global workspace\n  static OpenCLWorkspace* Global();\n};\n\n/*! \\brief Thread local workspace for SDAccel*/\nclass SDAccelThreadEntry : public OpenCLThreadEntry {\n public:\n  // constructor\n  SDAccelThreadEntry()\n      : OpenCLThreadEntry(static_cast<DLDeviceType>(kDLSDAccel), SDAccelWorkspace::Global()) {}\n\n  // get the global workspace\n  static SDAccelThreadEntry* ThreadLocal();\n};\n}  // namespace cl\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/opencl/sdaccel/sdaccel_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file sdaccel_module.h\n * \\brief Execution handling of OPENCL kernels for SDAccel FPGAs\n */\n#ifndef TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_\n#define TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief create a opencl module for SDAccel from data.\n *\n * \\param data The module data.\n * \\param fmt The format of the data, can be \"xclbin\", \"awsxclbin\"\n * \\param fmap The map function information map of each function.\n */\nModule SDAccelModuleCreate(std::string data, std::string fmt,\n                           std::unordered_map<std::string, FunctionInfo> fmap, std::string source);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/pack_args.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file pack_args.h\n * \\brief Utility to pack TVMArgs to other type-erased fution calling convention.\n *\n *  Two type erased function signatures are supported.\n *   - cuda_style(void** args, int num_args);\n *      - Pack everything by address\n *   - metal_style(void** buffers, int num_buffers,\n *                 union_32bit args[N], int num_args);\n *      - Pack buffer by address, pack rest parameter into 32bit union buffer.\n */\n#ifndef TVM_RUNTIME_PACK_ARGS_H_\n#define TVM_RUNTIME_PACK_ARGS_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <cstring>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief argument union type of 32bit.\n */\nunion ArgUnion32 {\n  int32_t v_int32;\n  uint32_t v_uint32;\n  float v_float32;\n};\n\n/*!\n * \\brief argument union type of 64 bit, for use by Vulkan and Metal runtime.\n */\nunion ArgUnion64 {\n  int32_t v_int32[2];\n  uint32_t v_uint32[2];\n  float v_float32[2];\n  int64_t v_int64;\n  uint64_t v_uint64;\n  double v_float64;\n};\n/*!\n * \\brief Create a packed function from void addr types.\n *\n * \\param f with signiture (TVMArgs args, TVMRetValue* rv, void* void_args)\n * \\param arg_types The arguments type information.\n * \\tparam F the function type\n *\n * \\return The wrapped packed function.\n */\ntemplate <typename F>\ninline PackedFunc PackFuncVoidAddr(F f, const std::vector<DLDataType>& arg_types);\n/*!\n * \\brief Create a packed function that from function only packs buffer arguments.\n *\n * \\param f with signiture (TVMArgs args, TVMRetValue* rv, ArgUnion* pack_args)\n * \\param arg_types The arguments type information.\n * \\tparam F the function type\n *\n * \\return The wrapped packed function.\n */\ntemplate <typename F>\ninline PackedFunc PackFuncNonBufferArg(F f, const std::vector<DLDataType>& arg_types);\n/*!\n * \\brief Create a packed function that from function that takes a packed arguments.\n *\n * \\param f with signature (TVMArgs args, TVMRetValue* rv, void* pack_args, size_t nbytes)\n * \\param arg_types The arguments that wish to get from\n * \\tparam F the function type\n *\n * \\return The wrapped packed function.\n */\ntemplate <typename F>\ninline PackedFunc PackFuncPackedArg(F f, const std::vector<DLDataType>& arg_types);\n/*!\n * \\brief Extract number of buffer argument from the argument types.\n * \\param arg_types The argument types.\n * \\return number of buffer arguments\n */\ninline size_t NumBufferArgs(const std::vector<DLDataType>& arg_types);\n\n// implementations details\nnamespace detail {\ntemplate <typename T, int kSize>\nclass TempArray {\n public:\n  explicit TempArray(int size) {}\n  T* data() { return data_; }\n\n private:\n  T data_[kSize];\n};\ntemplate <typename T>\nclass TempArray<T, 0> {\n public:\n  explicit TempArray(int size) : data_(size) {}\n  T* data() { return data_.data(); }\n\n private:\n  std::vector<T> data_;\n};\n\n/*! \\brief conversion code used in void arg. */\nenum ArgConvertCode {\n  INT64_TO_INT64,\n  INT64_TO_INT32,\n  INT64_TO_UINT32,\n  FLOAT64_TO_FLOAT32,\n  FLOAT64_TO_FLOAT64,\n  HANDLE_TO_HANDLE\n};\n\ninline ArgConvertCode GetArgConvertCode(DLDataType t) {\n  ICHECK_EQ(t.lanes, 1U) << \"Cannot pass vector type argument to devic function for now\";\n  if (t.code == kDLInt) {\n    if (t.bits == 64U) return INT64_TO_INT64;\n    if (t.bits == 32U) return INT64_TO_INT32;\n  } else if (t.code == kDLUInt) {\n    if (t.bits == 32U) return INT64_TO_UINT32;\n  } else if (t.code == kDLFloat) {\n    if (t.bits == 64U) return FLOAT64_TO_FLOAT64;\n    if (t.bits == 32U) return FLOAT64_TO_FLOAT32;\n  } else if (t.code == kTVMOpaqueHandle) {\n    return HANDLE_TO_HANDLE;\n  }\n  LOG(FATAL) << \"Cannot handle \" << t << \" as device function argument\";\n  return HANDLE_TO_HANDLE;\n}\n\ntemplate <int N, typename F>\ninline PackedFunc PackFuncVoidAddr_(F f, const std::vector<ArgConvertCode>& codes) {\n  int num_args = static_cast<int>(codes.size());\n  auto ret = [f, codes, num_args](TVMArgs args, TVMRetValue* ret) {\n    TempArray<void*, N> addr_(num_args);\n    TempArray<ArgUnion32, N> holder_(num_args);\n    void** addr = addr_.data();\n    ArgUnion32* holder = holder_.data();\n    for (int i = 0; i < num_args; ++i) {\n      switch (codes[i]) {\n        case INT64_TO_INT64:\n        case FLOAT64_TO_FLOAT64:\n        case HANDLE_TO_HANDLE: {\n          addr[i] = (void*)&(args.values[i]);  // NOLINT(*)\n          break;\n        }\n        case INT64_TO_INT32: {\n          holder[i].v_int32 = static_cast<int32_t>(args.values[i].v_int64);\n          addr[i] = &(holder[i]);\n          break;\n        }\n        case INT64_TO_UINT32: {\n          holder[i].v_uint32 = static_cast<uint32_t>(args.values[i].v_int64);\n          addr[i] = &(holder[i]);\n          break;\n        }\n        case FLOAT64_TO_FLOAT32: {\n          holder[i].v_float32 = static_cast<float>(args.values[i].v_float64);\n          addr[i] = &(holder[i]);\n          break;\n        }\n      }\n    }\n    f(args, ret, addr);\n  };\n  return PackedFunc(ret);\n}\n\ntemplate <int N, typename F>\ninline PackedFunc PackFuncNonBufferArg_(F f, int base, const std::vector<ArgConvertCode>& codes) {\n  int num_args = static_cast<int>(codes.size());\n  auto ret = [f, codes, base, num_args](TVMArgs args, TVMRetValue* ret) {\n    TempArray<ArgUnion64, N> holder_(num_args);\n    ArgUnion64* holder = holder_.data();\n    for (int i = 0; i < num_args; ++i) {\n      switch (codes[i]) {\n        case INT64_TO_INT64: {\n          holder[i].v_int64 = args.values[base + i].v_int64;\n          break;\n        }\n        case FLOAT64_TO_FLOAT64: {\n          holder[i].v_float64 = args.values[base + i].v_float64;\n          break;\n        }\n        case INT64_TO_INT32: {\n          holder[i].v_int32[0] = static_cast<int32_t>(args.values[base + i].v_int64);\n          break;\n        }\n        case INT64_TO_UINT32: {\n          holder[i].v_uint32[0] = static_cast<uint32_t>(args.values[base + i].v_int64);\n          break;\n        }\n        case FLOAT64_TO_FLOAT32: {\n          holder[i].v_float32[0] = static_cast<float>(args.values[base + i].v_float64);\n          break;\n        }\n        case HANDLE_TO_HANDLE: {\n          LOG(FATAL) << \"not reached\";\n          break;\n        }\n      }\n    }\n    f(args, ret, holder);\n  };\n  return PackedFunc(ret);\n}\n\ntemplate <int N, typename F>\ninline PackedFunc PackFuncPackedArg_(F f, const std::vector<ArgConvertCode>& codes) {\n  int num_args = static_cast<int>(codes.size());\n  auto ret = [f, codes, num_args](TVMArgs args, TVMRetValue* ret) {\n    TempArray<uint64_t, N> pack_(num_args);\n    int32_t* pack = reinterpret_cast<int32_t*>(pack_.data());\n    int32_t* ptr = pack;\n    static_assert(sizeof(TVMValue) == 8, \"invariant\");\n    static_assert(sizeof(void*) % sizeof(int32_t) == 0, \"invariant\");\n    for (int i = 0; i < num_args; ++i) {\n      switch (codes[i]) {\n        case HANDLE_TO_HANDLE: {\n          std::memcpy(ptr, &(args.values[i].v_handle), sizeof(void*));\n          ptr += sizeof(void*) / sizeof(int32_t);\n          break;\n        }\n        case INT64_TO_INT64:\n        case FLOAT64_TO_FLOAT64: {\n          std::memcpy(ptr, &args.values[i], sizeof(TVMValue));\n          ptr += 2;\n          break;\n        }\n        case INT64_TO_INT32: {\n          *ptr = static_cast<int32_t>(args.values[i].v_int64);\n          ++ptr;\n          break;\n        }\n        case INT64_TO_UINT32: {\n          *reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(args.values[i].v_int64);\n          ++ptr;\n          break;\n        }\n        case FLOAT64_TO_FLOAT32: {\n          *reinterpret_cast<float*>(ptr) = static_cast<float>(args.values[i].v_float64);\n          ++ptr;\n          break;\n        }\n        default: {\n          LOG(FATAL) << \"not reached\";\n          break;\n        }\n      }\n    }\n    f(args, ret, pack, (ptr - pack) * sizeof(int32_t));\n  };\n  return PackedFunc(ret);\n}\n}  // namespace detail\n\ntemplate <typename F>\ninline PackedFunc PackFuncVoidAddr(F f, const std::vector<DLDataType>& arg_types) {\n  std::vector<detail::ArgConvertCode> codes(arg_types.size());\n  for (size_t i = 0; i < arg_types.size(); ++i) {\n    codes[i] = detail::GetArgConvertCode(arg_types[i]);\n  }\n  size_t num_void_args = arg_types.size();\n  // specialization\n  if (num_void_args <= 4) {\n    return detail::PackFuncVoidAddr_<4>(f, codes);\n  } else if (num_void_args <= 8) {\n    return detail::PackFuncVoidAddr_<8>(f, codes);\n  } else {\n    return detail::PackFuncVoidAddr_<0>(f, codes);\n  }\n}\n\ninline size_t NumBufferArgs(const std::vector<DLDataType>& arg_types) {\n  size_t base = arg_types.size();\n  for (size_t i = 0; i < arg_types.size(); ++i) {\n    if (arg_types[i].code != kTVMOpaqueHandle) {\n      base = i;\n      break;\n    }\n  }\n  for (size_t i = base; i < arg_types.size(); ++i) {\n    ICHECK(arg_types[i].code != kTVMOpaqueHandle) << \"Device function need to be organized\";\n  }\n  return base;\n}\n\ntemplate <typename F>\ninline PackedFunc PackFuncNonBufferArg(F f, const std::vector<DLDataType>& arg_types) {\n  size_t num_buffer = NumBufferArgs(arg_types);\n  std::vector<detail::ArgConvertCode> codes;\n  for (size_t i = num_buffer; i < arg_types.size(); ++i) {\n    codes.push_back(detail::GetArgConvertCode(arg_types[i]));\n  }\n  int base = static_cast<int>(num_buffer);\n  size_t nargs = codes.size();\n  // specialization\n  if (nargs <= 4) {\n    return detail::PackFuncNonBufferArg_<4>(f, base, codes);\n  } else {\n    return detail::PackFuncNonBufferArg_<0>(f, base, codes);\n  }\n}\n\ntemplate <typename F>\ninline PackedFunc PackFuncPackedArg(F f, const std::vector<DLDataType>& arg_types) {\n  std::vector<detail::ArgConvertCode> codes;\n  for (size_t i = 0; i < arg_types.size(); ++i) {\n    codes.push_back(detail::GetArgConvertCode(arg_types[i]));\n  }\n  size_t nargs = codes.size();\n  // specialization\n  if (nargs <= 4) {\n    return detail::PackFuncPackedArg_<4>(f, codes);\n  } else {\n    return detail::PackFuncPackedArg_<0>(f, codes);\n  }\n}\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_PACK_ARGS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/pipeline/pipeline_executor.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief pipeline executor\n * \\file pipeline_executor.h\n */\n#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_\n#define TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_\n\n#include <tvm/relay/expr.h>\n#include <tvm/runtime/registry.h>\n\n#include <array>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"pipeline_scheduler.h\"\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief pipeline executor.\n *  This executor class use the module list and dependency configuration of modules as\n *  the parameters and executes these modules on heterogeneous targets in a pipeline\n *  parallel manner to improve throughput.\n *\n *  This executor can be accessed by various language via TVM runtime PackedFunc API.\n */\nclass TVM_DLL PipelineExecutor : public ModuleNode {\n public:\n  /*!\n   * \\Return the type key of the executor.\n   */\n  const char* type_key() const final { return \"PipelineExecutor\"; }\n  /*!\n   * \\brief Initialize the pipeline executor with module array and JSON text.\n   * \\param modules The module list used for building pipeline.\n   * \\param pipeline_json The configuration of modules dependencies.\n   */\n  void Init(const std::vector<Module>& modules, const std::string& pipeline_json);\n  /*!\n   * \\brief Use the information of mod_config to create a list of graph executor.\n   * \\param mod_config The configuration information generated by the library export function call.\n   */\n  std::vector<Module> CreateGraphModules(const ModuleConfig& mod_config);\n  /*!\n   * \\brief Give frontends an access to packed functions.\n   * \\param name The name of the function.\n   * \\param sptr_to_self The pointer to the module node.\n   * \\return The corresponding packed function.\n   */\n  virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);\n  /*!\n   * \\brief Using the global input name to get the index, and also get the input interface name\n     of corresponding subgraph from the input connection configuration.\n   * \\param The global input name.\n   * \\return Returning the index and the input interface name of corresponding subgraph.\n   */\n  Array<String> GetInputPipeplineMap(std::string input_name);\n  /*!\n   * \\brief This function return a module index for the global parameters group name.\n   * \\param name The parameters group name.\n   * \\return Returning a runtime module index.\n   */\n  int GetParamsGroupPipelineMap(const std::string& name);\n  /*!\n   * \\brief Use the input name to set the input data of pipeline executor.\n   * \\param input_name The input name.\n   * \\param data_in The input data.\n   */\n  void SetInput(std::string input_name, DLTensor* data_in);\n  /*!\n   * \\brief Use the input name to get the input data.\n   * \\param input name The input name.\n   * \\return Return input data.\n   */\n  NDArray GetInput(std::string input_name);\n  /*!\n   * \\brief Getting the count of running pipeline.\n   */\n  int GetExecutionCount();\n  /*!\n   * \\brief Use the parameters group name to get the specific backend runtime then use\n   *  the param_key_name to set param data for the said backend runtime.\n   * \\param param_group_name The parameters group name.\n   * \\param param_key_name The parameter key name.\n   * \\param data_in The parameter value.\n   */\n  void SetParam(std::string param_group_name, std::string param_key_name, DLTensor* data_in);\n  /*!\n   * \\brief Get the number of outputs.\n   *\n   * \\return The number of outputs.\n   */\n  int NumOutputs() const { return num_outputs_; }\n  /*!\\brief Run the pipeline executor.*/\n  void Run();\n  int NumInputs();\n  /*!\n   * \\brief Get a list output data.\n   * \\return A list of output data.\n   */\n  Array<NDArray> GetOutput();\n  /*!\n   * \\brief A pipeline params with a specific name correspond with the params of a specific\n   *  backend module, this function return the module index for the params name.\n   * \\param name The parameters group name.\n   * \\return Return backend runtime module index.\n   */\n  int GetParamModuleIndex(const std::string& name);\n  /*!\n   * \\brief A pipeline input with a specific name correspond with a input of a specific\n   *  backend module, this function return a module index and a input index in \"pair\"\n   *  form for a input name.\n   *  return Return a module index and a input index.\n   */\n  std::pair<int, int> GetInputIndex(const std::string& name);\n  /*!\\brief Load the module files information.*/\n  ModuleConfig& LoadModuleConfig(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      std::string key;\n      reader->BeginObject();\n      int mod_idx = -1;\n      std::string lib_name;\n      std::string json_name;\n      std::string params_name;\n      std::string dev;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"mod_idx\") {\n          reader->Read(&mod_idx);\n        } else if (key == \"lib_name\") {\n          reader->Read(&lib_name);\n        } else if (key == \"json_name\") {\n          reader->Read(&json_name);\n        } else if (key == \"params_name\") {\n          reader->Read(&params_name);\n        } else if (key == \"dev\") {\n          reader->Read(&dev);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK(mod_idx >= 0) << \"Invalid mod_idx value \" << mod_idx;\n      // Load the lib, json, and params information.\n      ICHECK(!lib_name.empty()) << \"lib_name is empty.\";\n      ICHECK(!json_name.empty()) << \"json_name is empty.\";\n      ICHECK(!params_name.empty()) << \"params_name is empty.\";\n      mod_config_[mod_idx] = GraphModuleLoadInfo(lib_name, json_name, params_name, dev);\n    }\n    return mod_config_;\n  }\n\n private:\n  /*!\\brief The class used to execute and schedule the pipeline logic.*/\n  PipelineScheduler pipeline_scheduler_;\n  /*!\\brief The dependency information of each graph runtime module of the pipeline.*/\n  ConfigPipelineExecution pipeline_config_;\n  /*!\\brief The map of global input and subgraph input.*/\n  InputConnectionConfig input_connection_config_;\n  /*!\\brief The map includes global parameters groups and runtime modules.*/\n  ParamConnectionConfig param_connection_config_;\n  /*!\\brief The module information used to create the graph runtimes.*/\n  ModuleConfig mod_config_;\n  /*!\\brief How many outputs are in this pipeline executor.*/\n  size_t num_outputs_ = 0;\n  /*!The list of backend runtime module.*/\n  std::vector<std::shared_ptr<BackendRuntime>> runtimes_;\n  std::shared_ptr<GlobalRuntime> global_runtime_;\n  /*!\\brief Json loader.*/\n  void LoadConfig(dmlc::JSONReader* reader) {\n    reader->BeginObject();\n    std::string key;\n    while (reader->NextObjectItem(&key)) {\n      if (key == \"module_connection\") {\n        reader->Read(&pipeline_config_);\n      } else if (key == \"input_connection\") {\n        reader->Read(&input_connection_config_);\n      } else if (key == \"param_connection\") {\n        reader->Read(&param_connection_config_);\n      } else {\n        LOG(FATAL) << \"do not support key \" << key;\n      }\n    }\n    return;\n  }\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/pipeline/pipeline_scheduler.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_\n#define TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n\n#include <fstream>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"pipeline_struct.h\"\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief The class that executes the pipeline logic,it is used to initialize the thread pool,\n    execute and schedule pipeline tasks, allocate and manage memory, etc.\n */\nclass PipelineScheduler {\n public:\n  /*!\n   * \\brief Initialize the pipeline.\n   * \\param modules The list of graph executor module.\n   * \\param pipeline_config The dependency information of each graph executor module.\n   */\n  std::shared_ptr<GlobalRuntime> PipelineInit(const std::vector<Module>& modules,\n                                              const ConfigPipelineExecution& pipeline_config,\n                                              const InputConnectionConfig& input_connection_config);\n  /*!\n   * \\brief Running the pipeline logic.\n   * \\param runtimes A list of backend runtime modules.\n   */\n  void PipelineRun(const std::vector<std::shared_ptr<BackendRuntime>>& runtimes);\n  /*!\n   * \\brief Get a list of outputs.\n   */\n  Array<NDArray> PipelineGetOutput();\n\n private:\n  /*!\\brief The list of graph executors.*/\n  std::vector<Module> graph_modules_;\n  /*!\\brief A list of NDArray used to storage outputs.*/\n  Array<NDArray> output_arrays_;\n  /*!\\brief The global runtime to represent the pipeline executor.*/\n  std::shared_ptr<GlobalRuntime> global_runtime_;\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/pipeline/pipeline_struct.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_\n#define TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_\n#include <assert.h>\n#include <dlpack/dlpack.h>\n#include <dmlc/json.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/threading_backend.h>\n\n#include <atomic>\n#include <condition_variable>\n#include <functional>\n#include <limits>\n#include <memory>\n#include <string>\n#include <thread>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"spsc_queue.h\"\nnamespace tvm {\nnamespace runtime {\n#define GLOBAL_MODULE_INDEX -1\n/*!\n *\\brief The function is used to build the binding configuration for a runtime. The first\n * 'int' is the output index of the current runtime, the second 'int' is the index of child\n * runtime, and the 'string' is the input name of child runtime.\n */\nusing BindingConfigParseFunc = std::function<void(int, int, std::string)>;\n/*!\n *\\brief The 'pair' includes the module output index and the global output index.\n * The first 'int' is the module output index, and the second 'int' is the global output index.\n */\nusing GlobalOutputPair = std::pair<int, int>;\n/*!\n *\\brief The pair includes the module index and the module output index.\n * The first 'int' is the module index, and the second 'int' is the module output index.\n */\nusing ModuleOutputPair = std::pair<int, int>;\n/*!\n *\\brief The pair includes the runtime module index and the module input index.\n * The first 'int' is the module index, and the second 'int' is the module input index.\n */\nusing ModuleInputPair = std::pair<int, int>;\n/*!\\brief The runtime module interface type.*/\nenum InterfaceType {\n  INPUT = 0,\n  OUTPUT,\n};\n/*!\\brief The state of the pipeline.*/\nenum PipelineState {\n  STOPPED = 0,\n  RUNNING,\n  STOPPING,\n};\n/*!\n *\\brief The structure includes the module index and the module output index.\n */\nstruct ModuleInterfaceID {\n  ModuleInterfaceID() { SetID(0, 0, INPUT); }\n  ModuleInterfaceID(int runtime_index, int runtime_interface_index, InterfaceType type = INPUT) {\n    SetID(runtime_index, runtime_interface_index, type);\n  }\n  /*!\n   * \\brief Set the value of ID.\n   * \\param runtime_index The index of runtime.\n   * \\param runtime_interface_index The index of interface.\n   * \\param type The type of the interface.\n   */\n  void SetID(int runtime_index, int runtime_interface_index, InterfaceType type) {\n    runtime_idx = runtime_index;\n    runtime_interface_idx = runtime_interface_index;\n    interface_type = type;\n  }\n  int runtime_idx;\n  union {\n    /*!\\brief The output interface index.*/\n    int runtime_output_idx;\n    /*!\\brief The input interface index.*/\n    int runtime_input_idx;\n    /*!\\brief The interface index.*/\n    int runtime_interface_idx;\n  };\n  /*!\\brief The interface type*/\n  InterfaceType interface_type;\n  ModuleInterfaceID& operator=(const struct ModuleInterfaceID& id) {\n    SetID(id.runtime_idx, id.runtime_interface_idx, id.interface_type);\n    return *this;\n  }\n  bool operator==(const struct ModuleInterfaceID& id) const {\n    return id.interface_type == interface_type &&\n           id.runtime_interface_idx == runtime_interface_idx && id.runtime_idx == runtime_idx;\n  }\n};\n/*!brief The hash function used to generate the hash value for the \"ModuleInterfaceID\" variable.*/\nstruct ModuleIDHash {\n  bool operator()(const ModuleInterfaceID& id) const {\n    int offset = sizeof(std::size_t) / 3;\n    return id.interface_type | id.runtime_interface_idx << offset | id.runtime_idx << offset * 2;\n  }\n};\n/*!\\brief The data notification structure.*/\nclass DataNotify {\n private:\n  /*!\\brief The 'contitional variable' is used to wait for notification.*/\n  std::condition_variable notify_cv_;\n  /*!\\brief The mutex is used to protect the 'conditional variable'.*/\n  std::mutex mutex_;\n  /*!\\brief Whether a data is ready or not.*/\n  bool data_ready_ = false;\n  /*!\\brief Whether the thread should exit or not.*/\n  std::atomic<bool> exit_state_{false};\n  /*!\\brief The 'ModuleInterfaceID' of an interface which sent this notification.*/\n  ModuleInterfaceID notification_source_;\n\n public:\n  /*!\n   * \\brief Constructing the DataNotify class.\n   * \\param source_interface_id The id of a runtime interface which is sending out the data\n   *  notification.\n   */\n  explicit DataNotify(ModuleInterfaceID source_interface_id) {\n    notification_source_ = source_interface_id;\n  }\n  /*!\n   * \\brief Getting the notification target.\n   * \\return The ID of the interface which is sending out the notification.\n   */\n  ModuleInterfaceID GetNotifySource(void) { return notification_source_; }\n  /*!\n   *\\brief Waiting for the notification.\n   *\\return Returning the value 'false' when the notification is in a 'exit' state, else\n   * return true.\n   */\n  bool Wait(void) {\n    std::unique_lock<std::mutex> lock(mutex_);\n    notify_cv_.wait(lock, [&] { return this->data_ready_; });\n    data_ready_ = false;\n    return !GetExitState();\n  }\n  /*!brief Sending the notification in which the related data is ready.*/\n  void Notify(void) {\n    {\n      std::lock_guard<std::mutex> lock(mutex_);\n      data_ready_ = true;\n    }\n    notify_cv_.notify_one();\n  }\n  /*!brief Sending the notification when the notification state changes into 'exit'.*/\n  void ExitNotify(void) {\n    exit_state_.store(true, std::memory_order_release);\n    Notify();\n  }\n  /*!\n   *\\brief Getting the 'exit state'.\n   *\\return Returning the value of 'exit_state_'\n   */\n  bool GetExitState(void) { return exit_state_.load(std::memory_order_acquire); }\n};\n/*!\\brief The container used to store the forwarding data of the pipeline.*/\nclass QueueData {\n public:\n  explicit QueueData(DLTensor* data) {\n    if (data_ == data) {\n      LOG(FATAL) << \"The value of 'data'(\" << data << \") is the same as 'data_'(\" << data_ << \")\";\n    }\n    data_ = data;\n    SetAsDataOwner(false);\n  }\n  QueueData() { SetAsDataOwner(true); }\n  /*!\\brief Doing a deep copy for the 'QueueData' structure.*/\n  QueueData& operator=(const QueueData& data) {\n    CreateCopyFrom(data.GetDLData());\n    return *this;\n  }\n  QueueData& operator=(const NDArray& from) {\n    CreateCopyFrom(const_cast<DLTensor*>(from.operator->()));\n    return *this;\n  }\n  QueueData& operator=(const DLTensor* from) {\n    CreateCopyFrom(from);\n    return *this;\n  }\n  /*!\\brief Create a deep copy of the 'DLTensor' data.*/\n  DLTensor* CreateCopyFrom(const DLTensor* from) {\n    if (!from) {\n      LOG(FATAL) << \"the 'from' pointer is a null pointer!\";\n      return nullptr;\n    }\n    size_t fromLen = tvm::runtime::GetDataSize(*from);\n    size_t toLen = data_ ? tvm::runtime::GetDataSize(*data_) : 0;\n    if (fromLen != toLen) {\n      // If this container ownes the variable 'data_', then recreating the 'data_' variable.\n      if (IsDataOwner()) {\n        if (data_) {\n          TVMArrayFree(data_);\n          data_ = nullptr;\n        }\n        TVMArrayAlloc(from->shape, from->ndim, from->dtype.code, from->dtype.bits,\n                      from->dtype.lanes, from->device.device_type, from->device.device_id, &data_);\n      } else {\n        LOG(FATAL) << \"The 'from' data is not matched with the  'data_'.\";\n      }\n    }\n    TVMArrayCopyFromTo(const_cast<DLTensor*>(from), data_, nullptr);\n    return data_;\n  }\n  /*!\\brief Return a pointer to the 'DLTensor' data.*/\n  DLTensor* GetDLData() const { return data_; }\n  ~QueueData() {\n    if (IsDataOwner() && data_) {\n      TVMArrayFree(data_);\n      data_ = nullptr;\n    }\n  }\n\n private:\n  /*!\\brief Pointer to the forwarding data.*/\n  DLTensor* data_ = nullptr;\n  /*!\\brief Whether this container is the owner of the 'data_'.*/\n  bool is_data_owner_ = false;\n  /*!\\brief Set the current container as the owner of the 'data_'.*/\n  void SetAsDataOwner(bool is_owner) { is_data_owner_ = is_owner; }\n  /*!Check whether the current container is the owner of the 'data_'.*/\n  bool IsDataOwner() const { return is_data_owner_; }\n};\n/*!\n * \\brief All binding information of an output interface.\n */\nclass ConfigBindings {\n public:\n  /*!\\brief Whether this binding is bound to the PipelineExecutor output interface.*/\n  bool IsGlobalOutput() const { return global_output_index_ > -1; }\n  /*!\\brief Getting the global output index in the current binding.*/\n  int GetGlobalOutputIndex() const { return global_output_index_; }\n  /*!\\brief Returning the binding configuration.*/\n  std::unordered_map<int, std::string>& Get() { return bindings_; }\n  /*!\n   * \\brief Enumerating the binding configuration.\n   * \\param parse_function The function is used to parse the binding configuration.\n   * \\param output_idx The index of output interface is used for parsing.\n   */\n  void VisitOutput(BindingConfigParseFunc parse_function, int output_idx) {\n    for (auto output : bindings_) {\n      parse_function(output_idx, output.first, output.second);\n    }\n    if (IsGlobalOutput()) {\n      parse_function(output_idx, GLOBAL_MODULE_INDEX, std::to_string(global_output_index_));\n    }\n  }\n  /*!\n   * \\brief Create a module interface map from JSONReader.\n   * \\param reader JSON reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      std::string key;\n      reader->BeginObject();\n      std::string input_name;\n      int mod_idx = std::numeric_limits<int>::min();\n      // Whether the output binding is global.\n      bool global_binding = false;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"mod_idx\") {\n          reader->Read(&mod_idx);\n        } else if (key == \"input_name\") {\n          reader->Read(&input_name);\n        } else if (key == \"global_output_index\") {\n          // There should be only one global binding.\n          ICHECK(global_output_index_ < 0);\n          reader->Read(&global_output_index_);\n          // When the key value is 'global_output_index', it means that this output is bound to\n          // a global interface.\n          global_binding = true;\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      // When this output is bound to a global interface, check if the global interface index\n      // start from 0.\n      if (global_binding) {\n        ICHECK(global_output_index_ >= 0);\n      } else {\n        // When this output is bound to a graph executor module interface, check if the module\n        // index start from 0.\n        ICHECK(mod_idx >= 0);\n        bindings_[mod_idx] = input_name;\n      }\n    }\n  }\n\n private:\n  /*!\\brief Output interface binding information, 'int' is the index of the module that\n   *  uses this output data as the input interface data, 'string' is the input interface name\n   *  of the module.\n   */\n  std::unordered_map<int, std::string> bindings_;\n  /*! The index value of the global interface to which the current output are bound.*/\n  int global_output_index_ = std::numeric_limits<int>::min();\n};\n/*!\n * \\brief The binding information of all outputs of a module.\n */\nclass ConfigRuntime {\n public:\n  ConfigRuntime& operator=(const ConfigRuntime& output) {\n    output_binding_map_ = output.GetOutBindings();\n    cpu_affinity_ = output.GetCPUAffinity();\n    return *this;\n  }\n\n  ConfigBindings& operator[](const int key) {\n    ICHECK(output_binding_map_.find(key) != output_binding_map_.end());\n    return output_binding_map_[key];\n  }\n  /*!\n   * \\brief Store the CPU affinity settings.\n   * \\param cpu_affinity The CPU affinity settings in the text form.\n   */\n  void StoreCPUAffinity(std::string cpu_affinity) { cpu_affinity_ = cpu_affinity; }\n  /*!\n   * \\brief Getting the setting of the cpu affinity.\n   * \\param Returning the cpu affinity in text form.\n   */\n  std::string GetCPUAffinity() const { return cpu_affinity_; }\n  /*!\n   * \\brief Enumerating the output configuration.\n   * \\param parse_function The callback function is used to parse the binding configeration.\n   */\n  void VisitOutputConfig(BindingConfigParseFunc parse_function) {\n    for (auto output : output_binding_map_) {\n      output.second.VisitOutput(parse_function, output.first);\n    }\n  }\n  /*!brief Return the variable \"output_binding_map_\".*/\n  std::unordered_map<int, ConfigBindings> GetOutBindings() const { return output_binding_map_; }\n  /*!\n   *\\brief This function is used to verify whether ConfigRuntime is successfully loaded.\n   *\\return Return true to indicate that this class has not been successfully loaded.\n   */\n  bool Empty() { return output_binding_map_.empty(); }\n  /*!\n   * \\brief The pipeline outputs is the final outputs of pipeline, this function is used to\n   *  get how many pipeline outputs are in this Outputmap\n   * \\return Number of pipeline outputs.\n   */\n  size_t GetGlobalOutputNum(void) const {\n    size_t num_output = 0;\n    for (auto bindings : output_binding_map_) {\n      num_output += bindings.second.IsGlobalOutput() ? 1 : 0;\n    }\n    return num_output;\n  }\n  /*!\n   *\\brief Getting the map which includes the global outputs and the current module outputs.\n   *\\return A list of \"GlobalOutputPair\".\n   */\n  std::vector<GlobalOutputPair> GetGlobalConfigOutputBindings(void) const {\n    std::vector<GlobalOutputPair> ret;\n    for (auto bindings : output_binding_map_) {\n      if (bindings.second.IsGlobalOutput()) {\n        ret.push_back(GlobalOutputPair(bindings.first, bindings.second.GetGlobalOutputIndex()));\n      }\n    }\n    return ret;\n  }\n  /*!\n   * \\brief Create an output binding map from JSONReader.\n   * \\param reader Json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      std::string key;\n      reader->BeginObject();\n      int output_idx = -1;\n      ConfigBindings binding;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"output_idx\") {\n          reader->Read(&output_idx);\n        } else if (key == \"dependencies\") {\n          reader->Read(&binding);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK(output_idx >= 0);\n      output_binding_map_[output_idx] = binding;\n    }\n  }\n\n private:\n  /*!\\brief The map of output binding, 'int' is the output interface index.*/\n  std::unordered_map<int, ConfigBindings> output_binding_map_;\n  /*!\\brief The cpu affinity setting for the tvm thread pool.*/\n  std::string cpu_affinity_;\n};\n\n/*!\n * \\brief The binding or dependency information of each module output interface.\n */\nclass ConfigPipelineExecution {\n public:\n  ConfigRuntime& operator[](int key) {\n    ICHECK(config_.find(key) != config_.end());\n    return config_[key];\n  }\n  /*Get the cpu affinity settings.*/\n  std::string GetCPUAffinity(int runtime_idx) {\n    auto config = config_.find(runtime_idx);\n    if (config == config_.end()) {\n      LOG(FATAL) << \"Do not finding the runtime \" << runtime_idx;\n    }\n    auto config_runtime = config->second;\n    return config_runtime.GetCPUAffinity();\n  }\n  /*!\n   * \\brief Enumerating the binding configuration for a specified runtime.\n   * \\param parse_function The callback function is used to parse the binding configuration.\n   * \\param runtime_index The index of a runtime is used to parse the binding configuration.\n   */\n  void VisitRuntimeOutputConfig(BindingConfigParseFunc parse_function, int runtime_index) {\n    auto config = config_.find(runtime_index);\n    if (config == config_.end()) {\n      LOG(FATAL) << \"Do not finding the runtime \" << runtime_index;\n    }\n    config->second.VisitOutputConfig(parse_function);\n  }\n  /*\n   *!\\brief This function is used to verify whether config is loaded successfully.\n   * \\return Return \"true\" to indicate that this class has not been successfully loaded.\n   */\n  bool Empty() { return config_.empty(); }\n  /*!\n   *\\brief Check if the module index existing in the \"config\".\n   */\n  bool FindModuleInConfig(int mod_idx) { return config_.find(mod_idx) != config_.end(); }\n  /*!\n   * \\brief Getting the number of global outputs.\n   * \\return The number of outputs in the entire pipeline.\n   */\n  size_t GetGlobalOutputNum() const {\n    size_t num_output = 0;\n    for (auto mod_output : config_) {\n      num_output += mod_output.second.GetGlobalOutputNum();\n    }\n    return num_output;\n  }\n  /*\n   *!\\brief Get the map of global outputs and module outputs.\n   */\n  std::unordered_map<int, ModuleOutputPair> GetGlobalConfigOutputBindings(void) const {\n    return global_output_map_;\n  }\n  /*\n   *!\\brief Parsing the configuration.\n   */\n  void ParseConfiguration(const std::unordered_map<int, ConfigRuntime>& config) {\n    if (config.empty()) {\n      LOG(FATAL) << \"The Configuration loading not finish yet.\";\n    }\n    for (auto mod_output : config) {\n      // Using the global output index as the key to create a map including global index and\n      // module output index.\n      const std::vector<GlobalOutputPair>& global_output =\n          mod_output.second.GetGlobalConfigOutputBindings();\n\n      for (auto output : global_output) {\n        global_output_map_[output.second] = ModuleOutputPair(mod_output.first, output.first);\n      }\n    }\n    return;\n  }\n  /*!\n   * \\brief Create a pipeline config from JSONReader.\n   * \\param reader Json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      std::string key;\n      reader->BeginObject();\n      int mod_idx = -1;\n      ConfigRuntime output;\n      std::string dev;\n      std::string cpu_affinity;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"mod_idx\") {\n          reader->Read(&mod_idx);\n        } else if (key == \"dev\") {\n          reader->Read(&dev);\n        } else if (key == \"output\") {\n          reader->Read(&output);\n        } else if (key == \"cpu_affinity\") {\n          reader->Read(&cpu_affinity);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK(mod_idx >= 0) << \"Invalid mod_idx value \" << mod_idx;\n      // Check if the output is successfully read.\n      ICHECK(!output.Empty()) << \"Invalid output binding result.\";\n      // Store the cpu affinity into the 'ConfigRuntime' structure.\n      output.StoreCPUAffinity(cpu_affinity);\n      // Build the mapping of mod_idx and \"ConfigRuntime\".\n      config_[mod_idx] = output;\n    }\n    // Doing the configuration parsing after the loading finished.\n    ParseConfiguration(config_);\n  }\n\n private:\n  /*\n   *!\\brief The key is the module index, this variable records all module pipeline configuration\n   * information.\n   */\n  std::unordered_map<int, ConfigRuntime> config_;\n  /*\n   *\\brief The key is the global output index, and the map is including global outputs index and\n   * the module outputs pair.\n   */\n  std::unordered_map<int, ModuleOutputPair> global_output_map_;\n};\n\nstruct InputConnectionConfig {\n  /*!\\brief The key(\"string\") is the name of global module input interfaces. The value(\"pair\")\n   * includes the index of graph module and the name of a graph module input interface.\n   */\n  std::unordered_map<std::string, std::pair<int, std::string>> input_connection;\n  /*!\\brief The map includes the global input name and global input index.*/\n  std::unordered_map<std::string, int> input_name_index_map;\n  /*!\n   * \\brief The map not only includes the runtime index ,but also the pair of global interface\n   *  and runtime interface.\n   */\n  std::unordered_map<int, std::vector<std::pair<std::string, std::string>>> input_runtime_map;\n  std::pair<int, std::string> operator[](const std::string key) {\n    if (input_connection.find(key) == input_connection.end()) {\n      LOG(FATAL) << \"Not find the key \" << key;\n    }\n    return input_connection[key];\n  }\n  /*!\\brief Returns the number of global inputs through the input_runtime_map list size.*/\n  int GetInputNum() { return input_runtime_map.size(); }\n\n  /*!\n   * \\brief Getting the global input index through the input name.\n   * \\param input_name The global input name.\n   */\n  int GetInputIndex(std::string input_name) {\n    auto input_index_iter = input_name_index_map.find(input_name);\n    if (input_index_iter == input_name_index_map.end()) {\n      LOG(FATAL) << \"Do not finding the input name! \" << input_name;\n    }\n    return input_index_iter->second;\n  }\n  /*!\\brief Enumerating the input binding configuration for a specified runtime.*/\n  void VisitConfig(BindingConfigParseFunc parse_function, int runtime_index) {\n    auto config = input_runtime_map.find(runtime_index);\n    // Only do the processing when there are input configuration in the runtime.\n    if (config != input_runtime_map.end()) {\n      for (auto x : config->second) {\n        int input_index = GetInputIndex(x.first);\n        parse_function(input_index, runtime_index, x.second);\n      }\n    }\n  }\n  /*!\n   * \\brief Create an input connection config from JSONReader.\n   * \\param reader Json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    int global_interface_index = 0;\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      reader->BeginObject();\n      std::string key;\n      std::string global_interface_name;\n      std::string module_interface_name;\n      int mod_idx = -1;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"global_interface_name\") {\n          reader->Read(&global_interface_name);\n          input_name_index_map[global_interface_name] = global_interface_index++;\n        } else if (key == \"mod_idx\") {\n          reader->Read(&mod_idx);\n        } else if (key == \"module_interface_name\") {\n          reader->Read(&module_interface_name);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK(mod_idx >= 0) << \"Invalid mod_idx value \" << mod_idx;\n      ICHECK(!global_interface_name.empty()) << \"Invalid global interface name value\";\n      ICHECK(!module_interface_name.empty()) << \"Invalid module interface name value\";\n      input_connection[global_interface_name] = make_pair(mod_idx, module_interface_name);\n      // Creating a map which not only includes the runtime index, but also the pair of gloal\n      // interface, and runtime interface.\n      input_runtime_map[mod_idx].push_back(\n          std::make_pair(global_interface_name, module_interface_name));\n    }\n  }\n};\n\n/*!\n * \\brief A map includes global module parameters groups and graph modudles.\n */\nstruct ParamConnectionConfig {\n  /*!\\brief Mapping from the name of a global module parameters group to the index of a runtime\n   *  module.\n   */\n  std::unordered_map<std::string, int> param_connection;\n  bool Empty() { return param_connection.empty(); }\n  int operator[](const std::string key) {\n    if (param_connection.find(key) == param_connection.end()) {\n      LOG(FATAL) << \"do not support key \" << key;\n    }\n    return param_connection[key];\n  }\n  /*!\n   * \\brief Load from JSONReader.\n   * \\param reader Json reader.\n   */\n  void Load(dmlc::JSONReader* reader) {\n    reader->BeginArray();\n    while (reader->NextArrayItem()) {\n      reader->BeginObject();\n      std::string key;\n      std::string global_param_name;\n      int mod_idx = -1;\n      while (reader->NextObjectItem(&key)) {\n        if (key == \"global_param_name\") {\n          reader->Read(&global_param_name);\n        } else if (key == \"mod_idx\") {\n          reader->Read(&mod_idx);\n        } else {\n          LOG(FATAL) << \"do not support key \" << key;\n        }\n      }\n      ICHECK(mod_idx >= 0) << \"Invalid module index value \" << mod_idx;\n      ICHECK(!global_param_name.empty()) << \"Invalid global parameter group name value\";\n      param_connection[global_param_name] = mod_idx;\n    }\n  }\n};\n/*!\n * \\brief The single consumer single producer queue which is used to forward data between two\n * interfaces of backend cores.\n */\nusing ForwardQueue = SPSCLockFreeQueue<QueueData, ModuleInterfaceID>;\nusing ForwardQueueMap =\n    std::unordered_map<ModuleInterfaceID, std::shared_ptr<ForwardQueue>, ModuleIDHash>;\n/*!\\brief The basic class for runtime.*/\nclass BasicRuntime {\n  using ModuleInputPairList = std::vector<std::pair<std::shared_ptr<BasicRuntime>, int>>;\n\n public:\n  explicit BasicRuntime(int runtime_idx) : runtime_idx_(runtime_idx) {}\n  /*!\\brief Return the index of the current module.*/\n  int GetModuleIndex() { return runtime_idx_; }\n  /*!\\brief Setting the data into this runtime via the input index.*/\n  virtual void SetInput(const int index, DLTensor* data_in) {}\n  /*!\n   * \\brief Sending a notification when data is ready.\n   * \\param input_index The index of an input interface which have data ready.\n   */\n  virtual void ParentNotify(int input_index) {}\n  /*!\n   *\\brief Creating a parent notification.\n   *\\param input_index The input index of the 'current runtime'.\n   *\\param parent_idx The index of 'parent runtime' which will send the notification.\n   *\\param parent_output_idx The output index of the 'parent runtime' which will send\n   * the notification.\n   */\n  void CreateParentsNotify(int input_index, int parent_idx, int parent_output_idx) {\n    if (parents_notify_.find(input_index) != parents_notify_.end()) {\n      LOG(FATAL) << \"The notification associated with the input interface \" << input_index\n                 << \" in runtime \" << runtime_idx_ << \" already been created!\";\n      return;\n    }\n    parents_notify_[input_index] =\n        std::make_shared<DataNotify>(ModuleInterfaceID(parent_idx, parent_output_idx, OUTPUT));\n  }\n\n protected:\n  /*!\\brief The index of runtime indicates the runtime position in the pipeline.*/\n  int runtime_idx_;\n  /*!\\brief A list of runtime which depends on the current runtime.*/\n  std::unordered_map<int, ModuleInputPairList> children_;\n  /*!\\brief The map includes the runtime input index and the notification data structure.*/\n  std::unordered_map<int, std::shared_ptr<DataNotify>> parents_notify_;\n  /*!\n   * \\brief There is a list of SPSC input queues in which the input interface would poll the\n   *  data comed from other backend cores.\n   */\n  std::unordered_map<int, std::shared_ptr<ForwardQueue>> input_queue_;\n\n  /*!\n   * \\brief A list of SPSC forward queues in which the parent interface will push the data to\n   *  other backend cores.\n   */\n  std::unordered_map<int, ForwardQueueMap> forward_queue_;\n  /*!\\brief The state of the pipeline.*/\n  std::atomic<PipelineState> pipeline_state_{STOPPED};\n  /*!\n   * \\brief Generate the ID of an input queue.\n   * \\param runtime_index The index of backend runtime.\n   * \\param interface_index The index of the interface.\n   * \\param type The type of the interface.\n   */\n  ModuleInterfaceID GenerateQueueID(int runtime_index, int interface_index, InterfaceType type) {\n    return ModuleInterfaceID(runtime_index, interface_index, type);\n  }\n  /*!\n   * \\brief Forwarding the data into the child runtimes.\n   * \\param forward_queue_map The map includes the id and the queue.\n   * \\param child_runtime The child runtime.\n   * \\param child_input_index The child runtime index.\n   * \\param data The data is used for forwarding.\n   */\n  bool ForwardData(const ForwardQueueMap* forward_queue_map,\n                   std::shared_ptr<BasicRuntime> child_runtime, int child_input_index,\n                   const DLTensor* data) {\n    auto child_runtime_index = child_runtime->GetModuleIndex();\n    auto queue_id = GenerateQueueID(child_runtime_index, child_input_index, INPUT);\n    if (forward_queue_map->find(queue_id) == forward_queue_map->end()) {\n      LOG(FATAL) << \"Not find the associated queue of the runtime(\" << child_runtime_index\n                 << \").input(\" << child_input_index << \") which is connected with runtime(\"\n                 << runtime_idx_;\n    }\n    auto forward_queue = forward_queue_map->at(queue_id);\n    // If the queue is full, keep try until the push get success or the pipeline run into\n    // a STOP state.\n    while (!forward_queue->Push<const DLTensor*>(data)) {\n      if (PipelineIsStop()) {\n        LOG(INFO) << \"The forwarding process is stopped after the pipeline status is changed\"\n                  << \" into stop.\";\n        return false;\n      }\n    }\n    child_runtime->ParentNotify(child_input_index);\n    return true;\n  }\n  /*!\n   * \\brief Creating a forwarding queue for the pair of an output interface and an input interface.\n   * \\param forward_inf_idx The index of an interface which will send the forwarding data.\n   * \\param child_runtime The backend runtime which owns the input interface.\n   * \\param input_index The index of an input interface. This interface will receive the\n   * forwarding data.\n   */\n  void CreateForwardingQueue(int forward_inf_idx, std::shared_ptr<BasicRuntime> child_runtime,\n                             int input_index) {\n    auto queue_id = GenerateQueueID(child_runtime->GetModuleIndex(), input_index, INPUT);\n    // The forwarding queue map of a specified output interface.\n    auto& queue_map = forward_queue_[forward_inf_idx];\n    if (queue_map.find(queue_id) != queue_map.end()) {\n      LOG(FATAL) << \"The queue \" << queue_id.runtime_idx << \".\" << queue_id.runtime_interface_idx\n                 << \" is already created!\";\n      return;\n    }\n    auto queue = std::make_shared<ForwardQueue>(queue_id);\n    queue_map[queue_id] = queue;\n    // Use the created queue as the consumer queue for the input interface of this forwarding\n    // pair.\n    child_runtime->AppendInputQueue(input_index, queue);\n  }\n  /*!\n   * \\brief Setting  the consumer queue for the input interface.\n   * \\param input_index The index of the input interface.\n   * \\param queue The consumer queue.\n   */\n  void AppendInputQueue(int input_index, std::shared_ptr<ForwardQueue> queue) {\n    input_queue_[input_index] = queue;\n  }\n  /*!\\brief Checking if the pipeline is stopped or stopping.*/\n  const bool PipelineIsStop() const {\n    auto state = pipeline_state_.load(std::memory_order_acquire);\n    return state == STOPPING || state == STOPPED;\n  }\n};\n/*\n *!\\brief Backend Runtime.\n */\nclass BackendRuntime : public BasicRuntime {\n private:\n  /*!The cpu affinity settings for this runtime.*/\n  std::string cpu_affinity_ = \"\";\n  /*!\\brief The Runtime module of a backend graph executor.*/\n  Module module_;\n  /*\\brief The thread is associated with the current runtime*/\n  std::thread thread_;\n  /*!\\brief The execution count of the 'RunPipeline' function. */\n  uint32_t pipeline_execution_count_ = 0;\n  /*!\n   *\\brief In order to transfer data from one backend runtime to another, we need a local\n   * tensor variable as a medium. \"input_tensor_local_copy_\" is a map including\n   * input data and local tensor vairable.\n   */\n  std::unordered_map<DLTensor*, DLTensor*> input_tensor_local_copy_;\n  /*!\\brief The packed functions.*/\n  tvm::runtime::PackedFunc set_input_;\n  tvm::runtime::PackedFunc get_input_;\n  tvm::runtime::PackedFunc get_output_;\n  tvm::runtime::PackedFunc get_num_output_;\n  tvm::runtime::PackedFunc get_num_inputs_;\n  tvm::runtime::PackedFunc get_input_index_;\n  tvm::runtime::PackedFunc run_;\n  /*!\\brief The worker thread is used to execute the runtimes in pipeline.*/\n  void StartWorkThread() {\n    SetPipelineState(RUNNING);\n    if (runtime_idx_ == 0) {\n      this->SetCPUAffinity();\n    } else {\n      // Only launching the worker thread for the runtimes after the first runtime.\n      thread_ = std::thread([&]() {\n        this->SetCPUAffinity();\n        while (!this->WaitAndLoadPipelineData()) {\n          if (!this->RunPipeline()) {\n            break;\n          }\n        }\n        VLOG(1) << \"Runtime \" << this->runtime_idx_ << \" exit.\";\n      });\n    }\n    return;\n  }\n  /*!\\brief Setting the state of the pipeline.*/\n  void SetPipelineState(PipelineState state) {\n    pipeline_state_.store(state, std::memory_order_release);\n  }\n  /*!\\brief Stopping the threads in pipeline.*/\n  void StopPipeline() {\n    SetPipelineState(STOPPING);\n    for (auto notify : parents_notify_) {\n      notify.second->ExitNotify();\n    }\n    if (thread_.joinable()) {\n      thread_.join();\n    }\n    SetPipelineState(STOPPED);\n  }\n  /*!\n   * \\brief Waiting for the internal forwarding data.\n   * \\return Returning 'true' when getting a 'exit' notification otherwise returning 'false'.\n   */\n  bool WaitAndLoadPipelineData() {\n    std::unordered_map<int, std::shared_ptr<DataNotify>> notifys = parents_notify_;\n    bool exit_notify = false;\n    while (!notifys.empty() && !exit_notify) {\n      auto notify = notifys.begin();\n      // Breaking the loop when the notification is in the exit state.\n      if ((exit_notify = notify->second->GetExitState())) break;\n      // Getting the source which sends this notification.\n      auto target_input_interface_index = notify->first;\n      // Loading the binding data.\n      while (!this->LoadBindingData(target_input_interface_index)) {\n        // Waiting for the notification.\n        if (!notify->second->Wait()) {\n          exit_notify = true;\n          break;\n        }\n      }\n      notifys.erase(notify);\n    }\n    return exit_notify;\n  }\n  /*!\n   * \\brief Loading the binding data.\n   * \\param input_index The index of the interface which will receive the forwarding data.\n   * \\return Returning 'true' when data is loaded successfully, otherwise returning 'false'.\n   */\n  bool LoadBindingData(int input_index) {\n    if (input_queue_.find(input_index) == input_queue_.end()) {\n      LOG(FATAL) << \"Not finding the associated input queue of the input \" << input_index << \" !\";\n      return false;\n    }\n    auto queue = input_queue_[input_index];\n    QueueData data;\n    // TODO(huajsj): Doing the 'SetInput' inside the poll function to avoid one time data copy.\n    if (!queue->Poll<QueueData>(&data)) {\n      return false;\n    }\n    SetInput(input_index, data.GetDLData());\n    return true;\n  }\n  /*!\n   * \\brief Forwarding the output data into the child runtimes.\n   * \\return bool Return false when the \"PipelineIsStop\" function returns true or this function\n   *  reaches some errors. Otherwise, return true.\n   */\n  bool ForwardingOutputDataToChildren(void) {\n    for (auto child : children_) {\n      auto output_idx = child.first;\n      if (forward_queue_.find(output_idx) == forward_queue_.end()) {\n        LOG(FATAL) << \"Not find the forwarding queue map for output(\" << output_idx << \")!\";\n        return false;\n      }\n      NDArray output = GetOutput(output_idx);\n      auto forward_queue_map = forward_queue_[output_idx];\n      // Notifying the 'children runtime' that the forwarding data are ready.\n      for (auto module_pair : child.second) {\n        auto child_runtime = module_pair.first;\n        auto child_input_index = module_pair.second;\n        auto output_data = const_cast<DLTensor*>(output.operator->());\n        if (!ForwardData(&forward_queue_map, child_runtime, child_input_index, output_data)) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n  /*!\n   * \\brief Copying from a given tensor and using 'CPU' as the device.\n   */\n  inline DLTensor* CopyDLTensorToCPU(const DLTensor* from) {\n    DLTensor* ret = NULL;\n    TVMArrayAlloc(from->shape, from->ndim, from->dtype.code, from->dtype.bits, from->dtype.lanes,\n                  kDLCPU, 0, &ret);\n    return ret;\n  }\n  /*!\\brief Creating a new NDArray with same shape and data type as the given DLTensor.*/\n  NDArray CreateNDArrayFromDLTensor(const DLTensor* from) {\n    std::vector<int64_t> shape;\n    for (int i = 0; i < from->ndim; i++) {\n      shape.push_back(from->shape[i]);\n    }\n    auto ndarray = NDArray::Empty(shape, from->dtype, from->device);\n    ndarray.CreateView(shape, from->dtype);\n    return ndarray;\n  }\n  /*\n   *\\brief Copying data from one DLTensor to another.\n   */\n  void CopyFromTo(DLTensor* from, DLTensor* to) {\n    // When the 'from' device and the 'to' device are not the same, we use a temporary CPU\n    // DLTensor as the bridge.\n    if (from->device.device_type != to->device.device_type && from->device.device_type != kDLCPU &&\n        to->device.device_type != kDLCPU) {\n      DLTensor* dltensor_local = nullptr;\n      if (input_tensor_local_copy_.find(to) == input_tensor_local_copy_.end()) {\n        dltensor_local = CopyDLTensorToCPU(from);\n        input_tensor_local_copy_[to] = dltensor_local;\n      } else {\n        dltensor_local = input_tensor_local_copy_[to];\n      }\n      TVMArrayCopyFromTo(from, dltensor_local, nullptr);\n      from = dltensor_local;\n    }\n\n    TVMArrayCopyFromTo(from, to, nullptr);\n  }\n  /*!\\brief Setting the cpu affinity for the tvm threads pool in the current BackendRuntime.*/\n  void SetCPUAffinity(void) {\n    if (cpu_affinity_.empty()) {\n      return;\n    }\n    auto affinity_mode = tvm::runtime::threading::ThreadGroup::kSpecifyThreadShareAllCore;\n    std::istringstream istr(cpu_affinity_);\n    std::string affinity;\n    std::vector<unsigned int> cpus;\n    while (getline(istr, affinity, ',')) {\n      cpus.push_back(std::stoi(affinity));\n    }\n    tvm::runtime::threading::Configure(affinity_mode, 0, cpus);\n  }\n\n public:\n  BackendRuntime(Module mod, int mod_idx) : BasicRuntime(mod_idx), module_(mod) {\n    get_input_index_ = module_.GetFunction(\"get_input_index\");\n    get_num_output_ = module_.GetFunction(\"get_num_outputs\");\n    get_num_inputs_ = module_.GetFunction(\"get_num_inputs\");\n    set_input_ = module_.GetFunction(\"set_input\");\n    get_input_ = module_.GetFunction(\"get_input\");\n    get_output_ = module_.GetFunction(\"get_output\");\n    run_ = module_.GetFunction(\"run\");\n  }\n  ~BackendRuntime() {\n    for (auto data : input_tensor_local_copy_) {\n      TVMArrayFree(data.second);\n    }\n    StopPipeline();\n  }\n  /*!\n   * \\brief Getting the times of using pipeline function.\n   * \\return The times of using pipeline function.\n   */\n  int GetExecutionCount() const { return pipeline_execution_count_; }\n  /*!\n   * \\brief Initializing data structures for the pipeline execution.\n   * \\param config The pipeline configueration.\n   * \\param runtimes A list of BackendRuntime.\n   */\n  void InitializePipeline(ConfigPipelineExecution config,\n                          std::vector<std::shared_ptr<BackendRuntime>>* runtimes,\n                          std::shared_ptr<BasicRuntime> global_runtime) {\n    // Getting the current BackendRuntime's cpu affinity setting.\n    cpu_affinity_ = config.GetCPUAffinity(runtime_idx_);\n    // Getting the 'binding configuration' for each child runtime.\n    config.VisitRuntimeOutputConfig(\n        [&](int output_idx, int child_idx, std::string child_input_name) {\n          std::shared_ptr<BasicRuntime> child_runtime = nullptr;\n          int input_index;\n          if (GLOBAL_MODULE_INDEX == child_idx) {\n            int global_output_index = std::stoi(child_input_name);\n            input_index = global_output_index;\n            child_runtime = global_runtime;\n          } else {\n            int runtime_idx_max = runtimes->size();\n            if (child_idx < 0 || child_idx >= runtime_idx_max) {\n              LOG(FATAL) << \"The runtime index \" << child_idx << \" is out of the range.\";\n            }\n            auto runtime = runtimes->at(child_idx);\n            ICHECK(runtime->GetModuleIndex() == child_idx);\n            input_index = runtime->GetInputIndex(child_input_name);\n            if (input_index < 0) {\n              LOG(FATAL) << \"Can not find the input \" << input_index << \"in runtime \" << child_idx;\n            }\n            child_runtime = runtime;\n          }\n          ICHECK(child_runtime != nullptr);\n          children_[output_idx].push_back(std::make_pair(child_runtime, input_index));\n          child_runtime->CreateParentsNotify(input_index, runtime_idx_, output_idx);\n          VLOG(1) << \" parent_idx.output:\" << runtime_idx_ << \".\" << output_idx\n                  << \" child.input:\" << child_idx << \".\" << input_index;\n          // Creating the pipeline forwarding queue.\n          this->CreateForwardingQueue(output_idx, child_runtime, input_index);\n        },\n        runtime_idx_);\n\n    StartWorkThread();\n  }\n  /*!\n   * \\brief Notifying an input is ready.\n   * \\param input_index The index of 'input interface' which is ready for data.\n   */\n  void ParentNotify(int input_index) {\n    auto notify = parents_notify_.find(input_index);\n    if (notify == parents_notify_.end()) {\n      LOG(FATAL) << \"Can not find the input for index \" << input_index << \" in runtime\"\n                 << runtime_idx_;\n      return;\n    }\n    notify->second->Notify();\n  }\n  /*!\\brief Creating a NDArray containing same shape and data type with a module output. */\n  NDArray CreateFromOutput(int idx) {\n    NDArray data = get_output_(idx);\n    return CreateNDArrayFromDLTensor(const_cast<DLTensor*>(data.operator->()));\n  }\n  /*!\\brief Return the number of output*/\n  int NumOutputs() const { return get_num_output_(); }\n  /*!\\brief Return the number of input*/\n  int NumInputs() const { return get_num_inputs_(); }\n  /*!\\brief Setting the data to this runtime via input index.*/\n  void SetInput(const int index, DLTensor* data_in) {\n    NDArray input = get_input_(index);\n    DLTensor* dltensor_input = const_cast<DLTensor*>(input.operator->());\n    CopyFromTo(data_in, dltensor_input);\n  }\n  /*!\\brief Setting the data to the current runtime moduel via the input name. */\n  void SetInput(const std::string name, DLTensor* data_in) {\n    int index = this->GetInputIndex(name);\n    SetInput(index, data_in);\n  }\n  /*!\\brief Getting the input data via the input index.*/\n  NDArray GetInput(int index) const { return get_input_(index); }\n  /*!\\bief Getting the input data via the input name.*/\n  int GetInputIndex(const std::string& name) { return get_input_index_(name); }\n  /*!\\brief Using the output index to get the module output.*/\n  NDArray GetOutput(int index) { return get_output_(index); }\n  /*!\\brief Running the runtime.*/\n  void Run() { run_(); }\n  /*!\n   * \\brief Running the runtime in the pipeline mode.\n   * \\return Returning false if the forwarding function failed. Otherwise, returning true.;\n   */\n  bool RunPipeline() {\n    Run();\n    bool ret = ForwardingOutputDataToChildren();\n    pipeline_execution_count_++;\n    return ret;\n  }\n};\n/*!\n * \\brief This global runtime represents the pipeline executor and exposes the input and output\n *  interface.\n */\nclass GlobalRuntime : public BasicRuntime {\n public:\n  explicit GlobalRuntime(int runtime_idx) : BasicRuntime(runtime_idx) {}\n  /**/\n  std::vector<std::shared_ptr<BackendRuntime>> GetRuntimeList() { return runtimes_; }\n  /*!\\brief Push the data into the queue for the current runtime.*/\n  void SetPipelineInput(const std::string input_name, DLTensor* data_in) {\n    auto input_index = input_config_.GetInputIndex(input_name);\n    auto child_iter = children_.find(input_index);\n    if (child_iter == children_.end()) {\n      return;\n    }\n    auto forward_queue_map = forward_queue_[input_index];\n    // Notifying the 'children runtime' that the forwarding data are ready.\n    for (auto module_pair : child_iter->second) {\n      auto child_runtime = module_pair.first;\n      auto child_input_index = module_pair.second;\n      // No need to go through the forward queue when the runtime is the first one.\n      if (child_runtime->GetModuleIndex() == 0) {\n        child_runtime->SetInput(child_input_index, data_in);\n      } else {\n        if (!ForwardData(&forward_queue_map, child_runtime, child_input_index, data_in)) {\n          return;\n        }\n      }\n    }\n    return;\n  }\n  /*!\\brief Whether the output data is ready.*/\n  bool DataIsReady(bool wait_data) {\n    bool data_ready = true;\n    for (auto queue_pair : input_queue_) {\n      auto queue = queue_pair.second;\n      if (queue->Empty()) {\n        data_ready = false;\n        break;\n      }\n    }\n    if (!data_ready && wait_data) {\n      // TODO(huajsj): Waitting the data ready message.\n    }\n    return data_ready;\n  }\n  /*!\\brief Get the output data.*/\n  bool GetOutput(Array<NDArray>* outputs, bool wait_data = false) {\n    if (!DataIsReady(wait_data)) {\n      return false;\n    }\n    for (auto queue_pair : input_queue_) {\n      auto output_index = queue_pair.first;\n      auto queue = queue_pair.second;\n      QueueData data(const_cast<DLTensor*>(((*outputs)[output_index]).operator->()));\n      if (!queue->Poll<QueueData>(&data)) {\n        LOG(FATAL) << \"There is no data in the data queue, it should not happen!\";\n      }\n    }\n    return true;\n  }\n  /*!\\brief Initialized the data structures for pipeline.*/\n  void InitializePipeline(InputConnectionConfig input_config,\n                          const std::vector<std::shared_ptr<BackendRuntime>> runtimes) {\n    input_config_ = input_config;\n    runtimes_ = runtimes;\n    for (auto child_runtime : runtimes) {\n      int runtime_idx = child_runtime->GetModuleIndex();\n      input_config.VisitConfig(\n          [&](int input_index, int child_idx, std::string child_input_name) {\n            auto child_input_index = child_runtime->GetInputIndex(child_input_name);\n            if (child_input_index < 0) {\n              LOG(FATAL) << \"Can not find the input \" << child_input_name << \"in runtime \"\n                         << child_idx;\n            }\n            children_[input_index].push_back(std::make_pair(child_runtime, child_input_index));\n            // Only create notify and queue for the runtime after the first runtime.\n            if (runtime_idx != 0) {\n              child_runtime->CreateParentsNotify(input_index, GLOBAL_MODULE_INDEX,\n                                                 child_input_index);\n              // Creating the pipeline forwarding queue.\n              this->CreateForwardingQueue(input_index, child_runtime, child_input_index);\n            }\n          },\n          runtime_idx);\n    }\n  }\n\n private:\n  std::vector<std::shared_ptr<BackendRuntime>> runtimes_;\n  InputConnectionConfig input_config_;\n};\n/*!\n * \\brief The information used to initialize the graph executor module, the information\n *  come from the export library function call.\n */\nstruct GraphModuleLoadInfo {\n  GraphModuleLoadInfo(const std::string& lib, const std::string& json, const std::string& params,\n                      const std::string& device)\n      : lib_name(lib), json_name(json), params_name(params), dev(device) {}\n  GraphModuleLoadInfo() { ; }\n  std::string lib_name;\n  std::string json_name;\n  std::string params_name;\n  std::string dev;\n};\n/*! The Module information of each module.The 'int' is module index. */\nusing ModuleConfig = std::unordered_map<int, GraphModuleLoadInfo>;\n};      // namespace runtime\n};      // namespace tvm\n#endif  //  TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/pipeline/spsc_queue.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_\n#define TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_\n#include <cstddef>\n#include <thread>\n/*!\\brief A single producer and single consumer lock free queue.\n */\ntemplate <typename SlotType, typename IDType = int, int QueueLength = 1024>\nclass SPSCLockFreeQueue {\n public:\n  explicit SPSCLockFreeQueue(IDType id) : id_(id) {}\n  /*A read barrier enforcing the CPU to performe the reads before this barrier.*/\n  inline void read_barrier() { std::atomic_thread_fence(std::memory_order_acquire); }\n  /*A write barrier enforcing the CPU to performe the writes before this barrier.*/\n  inline void write_barrier() { std::atomic_thread_fence(std::memory_order_release); }\n  /*!\\brief Checking whether the queue is full.*/\n  bool Full() {\n    read_barrier();\n    return ((tail_ + 1) % len_) == head_;\n  }\n  /*!brief Checking whether the queue is empty.*/\n  bool Empty() {\n    read_barrier();\n    return head_ == tail_;\n  }\n  /*!\n   * \\brief Pushing the data into the queue. Only a single producer will call this function.\n   * \\param data The data which is pushed into the queue.\n   * \\return Return false when the queue is full. Otherwise, return true.\n   */\n  template <typename data_type>\n  bool Push(const data_type& data) {\n    if (Full()) return false;\n    queue_[tail_] = data;\n    write_barrier();\n    tail_ = (tail_ + 1) % len_;\n    return true;\n  }\n  /*!\n   * \\brief Poll the data from the front of the queue. Only the single consumer will call this\n   *  function.\n   * \\param data A pointer to the structure which stores the polled data..\n   * \\return Returning false when the queue is empty. Otherwise, return true.\n   */\n  template <typename data_type>\n  bool Poll(data_type* data) {\n    if (Empty()) return false;\n    *data = queue_[head_];\n    write_barrier();\n    head_ = (head_ + 1) % len_;\n    return true;\n  }\n\n private:\n  /*!\\brief The pointer points to the first slot with valid data in the queue.*/\n  size_t head_ = 0;\n  /*!\\brief The end of the queue at which elements are added.*/\n  size_t tail_ = 0;\n  /*!\\brief The length of the queue.*/\n  size_t len_ = QueueLength;\n  /*!\\brief The queue used to store the data.*/\n  SlotType queue_[QueueLength];\n  /*!\\brief The ID of the queue.*/\n  IDType id_;\n};\n#endif  // TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rocm/rocm_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm_common.h\n * \\brief Common utilities for ROCM\n */\n#ifndef TVM_RUNTIME_ROCM_ROCM_COMMON_H_\n#define TVM_RUNTIME_ROCM_ROCM_COMMON_H_\n\n#include <hip/hip_runtime_api.h>\n#include <hip/hip_version.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n\n#include \"../workspace_pool.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n#define ROCM_DRIVER_CALL(x)                                                                    \\\n  {                                                                                            \\\n    hipError_t result = x;                                                                     \\\n    if (result != hipSuccess && result != hipErrorDeinitialized) {                             \\\n      LOG(FATAL) << \"ROCM HIP Error: \" #x \" failed with error: \" << hipGetErrorString(result); \\\n    }                                                                                          \\\n  }\n\n#define ROCM_CALL(func)                                              \\\n  {                                                                  \\\n    hipError_t e = (func);                                           \\\n    ICHECK(e == hipSuccess) << \"ROCM HIP: \" << hipGetErrorString(e); \\\n  }\n\n/*! \\brief Thread local workspace */\nclass ROCMThreadEntry {\n public:\n  /*! \\brief The hip stream */\n  hipStream_t stream{nullptr};\n  /*! \\brief thread local pool*/\n  WorkspacePool pool;\n  /*! \\brief constructor */\n  ROCMThreadEntry();\n  // get the threadlocal workspace\n  static ROCMThreadEntry* ThreadLocal();\n};\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_ROCM_ROCM_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rocm/rocm_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rocm_module.h\n * \\brief Execution handling of ROCM kernels\n */\n#ifndef TVM_RUNTIME_ROCM_ROCM_MODULE_H_\n#define TVM_RUNTIME_ROCM_ROCM_MODULE_H_\n\n#include <tvm/runtime/module.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Maximum number of GPU supported in ROCMModule */\nstatic constexpr const int kMaxNumGPUs = 32;\n\n/*!\n * \\brief create a rocm module from data.\n *\n * \\param data The module data, can be hsaco\n * \\param fmt The format of the data, can be \"hsaco\"\n * \\param fmap The map function information map of each function.\n * \\param rocm_source Optional, rocm source file\n */\nModule ROCMModuleCreate(std::string data, std::string fmt,\n                        std::unordered_map<std::string, FunctionInfo> fmap, std::string rocm_source,\n                        std::string assembly);\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_ROCM_ROCM_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_channel.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_channel.h\n * \\brief Communication endpoints to connect local and remote RPC sessions.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_CHANNEL_H_\n#define TVM_RUNTIME_RPC_RPC_CHANNEL_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Abstract channel interface used to create RPCEndpoint.\n */\nclass RPCChannel {\n public:\n  /*! \\brief virtual destructor */\n  virtual ~RPCChannel() {}\n  /*!\n   * \\brief Send data over to the channel.\n   * \\param data The data pointer.\n   * \\param size The size fo the data.\n   * \\return The actual bytes sent.\n   */\n  virtual size_t Send(const void* data, size_t size) = 0;\n  /*!\n   * \\brief Recv data from channel.\n   *\n   * \\param data The data pointer.\n   * \\param size The size fo the data.\n   * \\return The actual bytes received.\n   */\n  virtual size_t Recv(void* data, size_t size) = 0;\n};\n\n/*!\n * \\brief RPC channel which callback\n * frontend (Python/Java/etc.)'s send & recv function\n */\nclass CallbackChannel final : public RPCChannel {\n public:\n  /*!\n   * \\brief Constructor.\n   *\n   * \\param fsend The send function, takes in a TVMByteArray and returns the\n   *              number of bytes sent in that array. Returns -1 if error happens.\n   * \\param frecv The recv function, takes an expected maximum size, and return\n   *              a byte array with the actual amount of data received.\n   */\n  explicit CallbackChannel(PackedFunc fsend, PackedFunc frecv)\n      : fsend_(std::move(fsend)), frecv_(std::move(frecv)) {}\n\n  ~CallbackChannel() {}\n  /*!\n   * \\brief Send data over to the channel.\n   * \\param data The data pointer.\n   * \\param size The size fo the data.\n   * \\return The actual bytes sent.\n   */\n  size_t Send(const void* data, size_t size) final;\n  /*!\n   * \\brief Recv data from channel.\n   *\n   * \\param data The data pointer.\n   * \\param size The size fo the data.\n   * \\return The actual bytes received.\n   */\n  size_t Recv(void* data, size_t size) final;\n\n private:\n  PackedFunc fsend_;\n  PackedFunc frecv_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_CHANNEL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_channel_logger.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_channel_logger.h\n * \\brief A wrapper for RPCChannel with a NanoRPCListener for logging the commands.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_\n#define TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <memory>\n#include <utility>\n\n#include \"../../support/ssize.h\"\n#include \"../minrpc/minrpc_server_logging.h\"\n#include \"rpc_channel.h\"\n\n#define RX_BUFFER_SIZE 65536\n\nnamespace tvm {\nnamespace runtime {\n\nclass Buffer {\n public:\n  Buffer(uint8_t* data, size_t data_size_bytes)\n      : data_{data}, capacity_{data_size_bytes}, num_valid_bytes_{0}, read_cursor_{0} {}\n\n  size_t Write(const uint8_t* data, size_t data_size_bytes) {\n    size_t num_bytes_available = capacity_ - num_valid_bytes_;\n    size_t num_bytes_to_copy = data_size_bytes;\n    if (num_bytes_available < num_bytes_to_copy) {\n      num_bytes_to_copy = num_bytes_available;\n    }\n\n    memcpy(&data_[num_valid_bytes_], data, num_bytes_to_copy);\n    num_valid_bytes_ += num_bytes_to_copy;\n    return num_bytes_to_copy;\n  }\n\n  size_t Read(uint8_t* data, size_t data_size_bytes) {\n    size_t num_bytes_to_copy = data_size_bytes;\n    size_t num_bytes_available = num_valid_bytes_ - read_cursor_;\n    if (num_bytes_available < num_bytes_to_copy) {\n      num_bytes_to_copy = num_bytes_available;\n    }\n\n    memcpy(data, &data_[read_cursor_], num_bytes_to_copy);\n    read_cursor_ += num_bytes_to_copy;\n    return num_bytes_to_copy;\n  }\n\n  void Clear() {\n    num_valid_bytes_ = 0;\n    read_cursor_ = 0;\n  }\n\n  size_t Size() const { return num_valid_bytes_; }\n\n private:\n  /*! \\brief pointer to data buffer. */\n  uint8_t* data_;\n\n  /*! \\brief The total number of bytes available in data_.*/\n  size_t capacity_;\n\n  /*! \\brief number of valid bytes in the buffer. */\n  size_t num_valid_bytes_;\n\n  /*! \\brief Read cursor position. */\n  size_t read_cursor_;\n};\n\n/*!\n * \\brief A simple IO handler for MinRPCSniffer.\n *\n * \\tparam Buffer* buffer to store received data.\n */\nclass SnifferIOHandler {\n public:\n  explicit SnifferIOHandler(Buffer* receive_buffer) : receive_buffer_(receive_buffer) {}\n\n  void MessageStart(size_t message_size_bytes) {}\n\n  ssize_t PosixWrite(const uint8_t* buf, size_t buf_size_bytes) { return 0; }\n\n  void MessageDone() {}\n\n  ssize_t PosixRead(uint8_t* buf, size_t buf_size_bytes) {\n    return receive_buffer_->Read(buf, buf_size_bytes);\n  }\n\n  void Close() {}\n\n  void Exit(int code) {}\n\n private:\n  Buffer* receive_buffer_;\n};\n\n/*!\n * \\brief A simple rpc session that logs the received commands.\n */\nclass NanoRPCListener {\n public:\n  NanoRPCListener()\n      : receive_buffer_(receive_storage_, receive_storage_size_bytes_),\n        io_(&receive_buffer_),\n        rpc_server_(&io_) {}\n\n  void Listen(const uint8_t* data, size_t size) { receive_buffer_.Write(data, size); }\n\n  void ProcessTxPacket() {\n    rpc_server_.ProcessOnePacket();\n    ClearBuffer();\n  }\n\n  void ProcessRxPacket() {\n    rpc_server_.ProcessOneResponse();\n    ClearBuffer();\n  }\n\n private:\n  void ClearBuffer() { receive_buffer_.Clear(); }\n\n private:\n  size_t receive_storage_size_bytes_ = RX_BUFFER_SIZE;\n  uint8_t receive_storage_[RX_BUFFER_SIZE];\n  Buffer receive_buffer_;\n  SnifferIOHandler io_;\n  MinRPCSniffer<SnifferIOHandler> rpc_server_;\n\n  void HandleCompleteMessage() { rpc_server_.ProcessOnePacket(); }\n\n  static void HandleCompleteMessageCb(void* context) {\n    static_cast<NanoRPCListener*>(context)->HandleCompleteMessage();\n  }\n};\n\n/*!\n * \\brief A wrapper for RPCChannel, that also logs the commands sent.\n *\n * \\tparam std::unique_ptr<RPCChannel>&& underlying RPCChannel unique_ptr.\n */\nclass RPCChannelLogging : public RPCChannel {\n public:\n  explicit RPCChannelLogging(std::unique_ptr<RPCChannel>&& next) { next_ = std::move(next); }\n\n  size_t Send(const void* data, size_t size) {\n    listener_.ProcessRxPacket();\n    listener_.Listen((const uint8_t*)data, size);\n    listener_.ProcessTxPacket();\n    return next_->Send(data, size);\n  }\n\n  size_t Recv(void* data, size_t size) {\n    size_t ret = next_->Recv(data, size);\n    listener_.Listen((const uint8_t*)data, size);\n    return ret;\n  }\n\n private:\n  std::unique_ptr<RPCChannel> next_;\n  NanoRPCListener listener_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_endpoint.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_endpoint.h\n * \\brief Communication endpoints to connect local and remote RPC sessions.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_ENDPOINT_H_\n#define TVM_RUNTIME_RPC_RPC_ENDPOINT_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <memory>\n#include <mutex>\n#include <string>\n#include <utility>\n\n#include \"../../support/ring_buffer.h\"\n#include \"../minrpc/rpc_reference.h\"\n#include \"rpc_channel.h\"\n#include \"rpc_channel_logger.h\"\n#include \"rpc_session.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n// Magic header for RPC data plane\nconst int kRPCMagic = 0xff271;\n// magic header for RPC tracker(control plane)\nconst int kRPCTrackerMagic = 0x2f271;\n// sucess response\nconst int kRPCSuccess = kRPCMagic + 0;\n// cannot found matched key in server\nconst int kRPCMismatch = kRPCMagic + 2;\n\n/*! \\brief Enumeration code for the RPC tracker */\nenum class TrackerCode : int {\n  kFail = -1,\n  kSuccess = 0,\n  kPing = 1,\n  kStop = 2,\n  kPut = 3,\n  kRequest = 4,\n  kUpdateInfo = 5,\n  kSummary = 6,\n  kGetPendingMatchKeys = 7\n};\n\n/*!\n * \\brief Communication endpoints to connect local and remote RPC sessions.\n *        An endpoint can either be a client or a server.\n */\nclass RPCEndpoint {\n public:\n  /*! \\brief virtual destructor\n   * Closes the connection if the connection hasn't already been closed.\n   */\n  ~RPCEndpoint();\n\n  /*!\n   *  \\brief Shutdown RPC connection.\n   *\n   *  Shutdown has no effect if the connection has already been shut down.\n   *  Shutdown will wait for all output currently queued from the RPC connection (i.e. The user\n   * doesn't need to wait for completion before calling Shutdown.) Any further use of objects that\n   * depended on the endpoint (e.g. A tvm.nd.array allocated on the remote RPC session) may throw an\n   * exception when used.\n   */\n  void Shutdown();\n\n  /*!\n   *  \\brief The server loop that server runs to handle RPC calls.\n   */\n  void ServerLoop();\n  /*!\n   * \\brief Message handling function for an async IO event driven server.\n   *\n   *  Called when the server receives a message or an IO event update.\n   *  Event driven handler will never call recv on the channel\n   *  and always relies on the ServerIOEventHandler to receive the data.\n   *\n   * \\param in_bytes The incoming bytes.\n   * \\param event_flag  1: read_available, 2: write_avaiable.\n   * \\return State flag.\n   *     1: continue running, no need to write,\n   *     2: need to write\n   *     0: shutdown\n   */\n  int ServerAsyncIOEventHandler(const std::string& in_bytes, int event_flag);\n\n  /*!\n   * \\brief Initalize the session on the remote that will be used to back all the RPC requests.\n   *\n   *  If no session constructor arguments is passed, LocalSession will be used in the remote.\n   *  Otherwise the remote serving session will be constructed using the arguments\n   *  specified in the session_constructor_args.\n   *\n   *  The construction rule can be summarized as follows:\n   *\n   * \\code\n   *\n   *  auto args = session_constructor_args;\n   *  int n = args.size();\n   *  if (n != 0) {\n   *    std::string constructor = args[0];\n   *    server.serving_session_ = GetGlobalFunc(constructor)(\n   *        args[1], args[2] ... args[n - 1])\n   *  } else {\n   *    server.serving_session_ = LocalSession();\n   *  }\n   * \\endcode\n   *\n   * \\param session_constructor_args Optional sequence of the remote sesssion constructor.\n   */\n  void InitRemoteSession(TVMArgs session_constructor_args);\n\n  /*!\n   * \\brief Call into remote function\n   * \\param handle The function handle\n   * \\param arg_values The argument values.\n   * \\param arg_type_codes the type codes of the argument.\n   * \\param num_args Number of arguments.\n   * \\param fencode_return The function to receive return value encodings.\n   */\n  void CallFunc(RPCSession::PackedFuncHandle handle, const TVMValue* arg_values,\n                const int* arg_type_codes, int num_args, RPCSession::FEncodeReturn encode_return);\n  /*!\n   * \\brief Copy bytes into remote array content.\n   * \\param from The source host data.\n   * \\param from_offset The byte offeset in the from.\n   * \\param to The target array.\n   * \\param to_offset The byte offset in the to.\n   * \\param nbytes The size of the memory in bytes.\n   * \\param dev_to The target device.\n   * \\param type_hint Hint of content data type.\n   */\n  void CopyToRemote(void* from_bytes, DLTensor* to, uint64_t nbytes);\n  /*!\n   * \\brief Copy bytes from remote array content.\n   * \\param from The source host data.\n   * \\param from_offset The byte offeset in the from.\n   * \\param to The target array.\n   * \\param to_offset The byte offset in the to.\n   * \\param nbytes The size of the memory in bytes.\n   * \\param dev_from The source device.\n   * \\param type_hint Hint of content data type.\n   */\n  void CopyFromRemote(DLTensor* from, void* to_bytes, uint64_t nbytes);\n\n  /*!\n   * \\brief Call a remote defined system function with arguments.\n   * \\param fcode The function code.\n   * \\param args The arguments\n   * \\return The returned remote value.\n   */\n  template <typename... Args>\n  inline TVMRetValue SysCallRemote(RPCCode fcode, Args&&... args);\n  /*!\n   * \\brief Create a RPC session with given channel.\n   * \\param channel The communication channel.\n   * \\param name The local name of the session, used for debug\n   * \\param remote_key The remote key of the session\n   *   if remote_key equals \"%toinit\", we need to re-intialize\n   *   it by event handler.\n   * \\param fcleanup The cleanup Packed function.\n   */\n  static std::shared_ptr<RPCEndpoint> Create(std::unique_ptr<RPCChannel> channel, std::string name,\n                                             std::string remote_key,\n                                             TypedPackedFunc<void()> fcleanup = nullptr);\n\n private:\n  class EventHandler;\n  // Handle events until receives a return\n  // Also flushes channels so that the function advances.\n  RPCCode HandleUntilReturnEvent(bool client_mode, RPCSession::FEncodeReturn setreturn);\n  // Initalization\n  void Init();\n  // Internal channel.\n  std::unique_ptr<RPCChannel> channel_;\n\n  // Internal mutex\n  std::mutex mutex_;\n  // Internal ring buffer.\n  support::RingBuffer reader_, writer_;\n  // Event handler.\n  std::shared_ptr<EventHandler> handler_;\n  // syscall remote with specified function code.\n  PackedFunc syscall_remote_;\n  // The name of the session.\n  std::string name_;\n  // The remote key\n  std::string remote_key_;\n  // Invoked when the RPC session is terminated\n  TypedPackedFunc<void()> fcleanup_;\n};\n\n/*!\n * \\brief Create an RPC client session from an RPC client endpoint.\n * \\param endpoint The endpoint.\n * \\return The created session.\n */\nstd::shared_ptr<RPCSession> CreateClientSession(std::shared_ptr<RPCEndpoint> endpoint);\n\n// implementation of inline functions\ntemplate <typename... Args>\ninline TVMRetValue RPCEndpoint::SysCallRemote(RPCCode code, Args&&... args) {\n  return syscall_remote_(static_cast<int>(code), std::forward<Args>(args)...);\n}\n\n/*!\n * \\brief Calculates overhead size of a CopyToRemote packet.\n * \\param to DLTensor to copy.\n * \\param code RPCCode for this transfer.\n * \\param nbytes Number of bytes to transfer.\n * \\return The remote-copy packet overhead size.\n */\nuint64_t RemoteCopyCalculatePacketOverheadSize(DLTensor* tensor, RPCCode code, uint64_t nbytes);\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_ENDPOINT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_local_session.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_local_session.h\n * \\brief Local session that directs all request to the local runtime API.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_\n#define TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_\n\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <functional>\n#include <string>\n#include <utility>\n\n#include \"rpc_session.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief A local session that directly use the handle repr of the\n *        local tvm runtime objects on the same process.\n */\nclass LocalSession : public RPCSession {\n public:\n  // function overrides\n  PackedFuncHandle GetFunction(const std::string& name) override;\n\n  void CallFunc(PackedFuncHandle func, const TVMValue* arg_values, const int* arg_type_codes,\n                int num_args, const FEncodeReturn& fencode_return) override;\n\n  void CopyToRemote(void* from_bytes, DLTensor* to, uint64_t nbytes) override;\n\n  void CopyFromRemote(DLTensor* from, void* to_bytes, uint64_t nbytes) override;\n\n  void FreeHandle(void* handle, int type_code) override;\n\n  DeviceAPI* GetDeviceAPI(Device dev, bool allow_missing = false) override;\n\n  bool IsLocalSession() const override { return true; }\n\n protected:\n  /*!\n   * \\brief internal encode return function.\n   * \\param rv The return value.\n   * \\param encode_return The encoding function.\n   */\n  void EncodeReturn(TVMRetValue rv, const FEncodeReturn& encode_return);\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_session.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_session.h\n * \\brief Base RPC session interface.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_SESSION_H_\n#define TVM_RUNTIME_RPC_RPC_SESSION_H_\n\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <functional>\n#include <memory>\n#include <string>\n\n#include \"../minrpc/rpc_reference.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief The interface of all remote RPC sessions.\n *\n *  It contains all the necessary interface to implement\n *  remote call and resource management.\n *\n *  The interface is designed to allow easy proxy-chaining\n *  by forward requests to another RPCSession.\n */\nclass RPCSession {\n public:\n  /*! \\brief PackedFunc Handle in the remote. */\n  using PackedFuncHandle = void*;\n\n  /*! \\brief Module handle in the remote. */\n  using ModuleHandle = void*;\n\n  /*! \\brief NDArray handle in the remote. */\n  using NDArrayHandle = void*;\n\n  /*!\n   * \\brief Callback to send an encoded return values via encode_args.\n   *\n   * \\param encode_args The arguments that we can encode the return values into.\n   *\n   * Encoding convention (as list of arguments):\n   * - str/float/int/byte: [tcode: int, value: TVMValue] value follows PackedFunc convention.\n   * - PackedFunc/Module: [tcode: int, handle: void*]\n   * - NDArray: [tcode: int,  meta: DLTensor*, nd_handle: void*]\n   *            DLTensor* contains the meta-data as well as handle into the remote data.\n   *            nd_handle can be used for deletion.\n   */\n  using FEncodeReturn = std::function<void(TVMArgs encoded_args)>;\n\n  /*!\n   * \\brief Callback to send an encoded return values via encode_args.\n   *\n   * \\param status The return status, can be RPCCode::kReturn or RPCCode::kException.\n   * \\param encode_args The arguments that we can encode the return values into.\n   */\n  using FAsyncCallback = std::function<void(RPCCode status, TVMArgs encoded_args)>;\n\n  /*! \\brief Destructor.*/\n  virtual ~RPCSession() {}\n\n  /*!\n   * \\brief Get function in the session.\n   * \\param name The name of the function.\n   * \\return The function handle.\n   */\n  virtual PackedFuncHandle GetFunction(const std::string& name) = 0;\n\n  /*!\n   * \\brief Call into a remote Packed function.\n   *\n   *  Calling convention:\n   *\n   *  - type_code is follows the PackedFunc convention.\n   *  - int/float/string/bytes follows the PackedFunc convention, all data are local.\n   *  - PackedFunc/Module and future remote objects: pass remote handle instead.\n   *  - NDArray/DLTensor: pass a DLTensor pointer, the data field of DLTensor\n   *                      points to a remote data handle returned by the Device API.\n   *                      The meta-data of the DLTensor sits on local.\n   *\n   *  The caller populates the arguments and manages these arguments.\n   *\n   *  The callee can change the content of arg_values and arg_type_codes\n   *  if they want to do inplace modify and forward.\n   *\n   *  The callee need to store the return value into ret_value.\n   *  - PackedFunc/Module are stored as void*\n   *  - NDArray is stored as local NDArray, whose data field is a remote handle.\n   *    Notably the NDArray's deleter won't delete remote handle.\n   *    It is up to the user of the RPCSession to such wrapping.\n   *  - In short, remote handles are \"moved\" as return values\n   *    and the callee needs to explicitly manage them by calling\n   *    the deleter functions when they are no longer needed.\n   *\n   * \\param func The function handle.\n   * \\param arg_values The argument values.\n   * \\param arg_type_codes the type codes of the argument.\n   * \\param num_args Number of arguments.\n   * \\param fencode_return The function to set the return value,\n   *                       if not called, return value is null.\n   */\n  virtual void CallFunc(PackedFuncHandle func, const TVMValue* arg_values,\n                        const int* arg_type_codes, int num_args,\n                        const FEncodeReturn& fencode_return) = 0;\n\n  /*!\n   * \\brief Copy bytes into remote array content.\n   * \\param local_from_bytes The source host data.\n   * \\param remote_to The target array.\n   * \\param nbytes The size of the memory in bytes.\n   */\n  virtual void CopyToRemote(void* local_from_bytes, DLTensor* remote_to, uint64_t nbytes) = 0;\n  /*!\n   * \\brief Copy bytes from remote array content.\n   * \\param remote_from The source host data.\n   * \\param local_to_bytes The target array.\n   * \\param nbytes The size of the memory in bytes.\n   */\n  virtual void CopyFromRemote(DLTensor* remote_from, void* local_to_bytes, uint64_t nbytes) = 0;\n\n  /*!\n   * \\brief Free a remote function.\n   * \\param handle The remote handle, can be NDArray/PackedFunc/Module\n   * \\param type_code The type code of the underlying type.\n   */\n  virtual void FreeHandle(void* handle, int type_code) = 0;\n\n  /*!\n   * \\brief Get device API that represents the remote\n   *  actions that can be taken on the remote.\n   *\n   *  The caller can then call into the Alloc/Free functions\n   *  to allocate free spaces and taking the pointer as the handle.\n   *\n   *  The device API is guaranteed to be alive during the\n   *  lifetime of the Session.\n   *\n   * \\param dev The remote device.\n   * \\param allow_missing Whether can we return nullptr if it is not available.\n   *\n   * \\return The device API.\n   */\n  virtual DeviceAPI* GetDeviceAPI(Device dev, bool allow_missing = false) = 0;\n\n  /*!\n   * \\brief Whether the session is a local session and we can directly\n   *        the data handle returned by the session and treat it as pointer\n   *        to the local memory.\n   *\n   * This information is useful for RPC server to directly copy into the\n   * local memory without creating a temporary buffer.\n   *\n   * \\return Whether it is a local session.\n   */\n  virtual bool IsLocalSession() const = 0;\n\n  // Asynchrous variant of API\n  // These APIs are used by the RPC server to allow sessions that\n  // have special implementations for the async functions.\n  //\n  // In the async APIs, an exception is returned by the passing\n  // async_error=true, encode_args=[error_msg].\n\n  /*!\n   * \\brief Whether the session is async.\n   *\n   * If the session is not async, its Aync implementations\n   * simply calls into the their synchronize counterparts,\n   * and the callback is guaranteed to be called before the async function finishes.\n   *\n   * \\return the async state.\n   *\n   * \\note We can only use async session in an Event driven RPC server.\n   */\n  virtual bool IsAsync() const;\n\n  /*!\n   * \\brief Asynchrously call func.\n   * \\param func The function handle.\n   * \\param arg_values The argument values.\n   * \\param arg_type_codes the type codes of the argument.\n   * \\param num_args Number of arguments.\n   *\n   * \\param callback The callback to pass the return value or exception.\n   */\n  virtual void AsyncCallFunc(PackedFuncHandle func, const TVMValue* arg_values,\n                             const int* arg_type_codes, int num_args, FAsyncCallback callback);\n\n  /*!\n   * \\brief Asynchrous version of CopyToRemote.\n   *\n   * \\param local_from_bytes The source host data.\n   * \\param remote_to The target array.\n   * \\param nbytes The size of the memory in bytes.\n   * \\param on_complete The callback to signal copy complete.\n   * \\note All the allocated memory in local_from, and remote_to\n   *       must stay alive until on_compelete is called.\n   */\n  virtual void AsyncCopyToRemote(void* local_from_bytes, DLTensor* remote_to, uint64_t nbytes,\n                                 FAsyncCallback on_complete);\n\n  /*!\n   * \\brief Asynchrous version of CopyFromRemote.\n   *\n   * \\param remote_from The source host data.\n   * \\param local_to_bytes The target array.\n   * \\param nbytes The size of the memory in bytes.\n   * \\param on_complete The callback to signal copy complete.\n   * \\note All the allocated memory in remote_from, and local_to\n   *       must stay alive until on_compelete is called.\n   */\n  virtual void AsyncCopyFromRemote(DLTensor* remote_from, void* local_to_bytes, uint64_t nbytes,\n                                   FAsyncCallback on_complete);\n  /*!\n   * \\brief Asynchrously wait for all events in dev, stream compeletes.\n   * \\param dev The device.\n   * \\param stream The stream to wait on.\n   * \\param on_complete The callback to signal copy complete.\n   */\n  virtual void AsyncStreamWait(Device dev, TVMStreamHandle stream, FAsyncCallback on_compelte);\n\n  /*!\n   * \\return The session table index of the session.\n   */\n  int table_index() const { return table_index_; }\n\n  /*!\n   * \\brief Try get session from the global session table by table index.\n   * \\param table_index The table index of the session.\n   * \\return The shared_ptr to the session, can be nullptr.\n   */\n  static std::shared_ptr<RPCSession> Get(int table_index);\n\n  /*!\n   * \\brief Shutdown RPC connection.\n   */\n  virtual void Shutdown() {}\n\n protected:\n  /*!\n   * \\brief Send an exception to the callback.\n   * \\param msg The exception message.\n   */\n  void SendException(FAsyncCallback callback, const char* msg);\n\n private:\n  /*! \\brief index of this session in RPC session table */\n  int table_index_{0};\n  /*! \\brief Insert the current session to the session table.*/\n  static void InsertToSessionTable(std::shared_ptr<RPCSession> sess);\n  // friend declaration\n  friend Module CreateRPCSessionModule(std::shared_ptr<RPCSession> sess);\n};\n\n/*!\n * \\brief Remote space handle cell used by the RPC runtime API.\n *\n *  When we allocate space using a rpc device, the data pointer\n *  points to an allocated RemoteSpace.\n */\nstruct RemoteSpace {\n  /*! \\brief The remote data handle. */\n  void* data;\n  /*! \\brief Reference to the underlying RPC session. */\n  std::shared_ptr<RPCSession> sess;\n};\n\n/*!\n * \\brief Create a Global RPC module that refers to the session.\n * \\param sess The RPC session of the global module.\n * \\return The created module.\n */\nModule CreateRPCSessionModule(std::shared_ptr<RPCSession> sess);\n\n/*!\n * \\brief Get the session module from a RPC session Module.\n * \\param mod The input module(must be an RPCModule).\n * \\return The internal RPCSession.\n */\nstd::shared_ptr<RPCSession> RPCModuleGetSession(Module mod);\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_SESSION_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/rpc/rpc_socket_impl.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file rpc_socket_impl.h\n * \\brief Socket based RPC implementation.\n */\n#ifndef TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_\n#define TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief RPCServerLoop Start the rpc server loop.\n * \\param sockfd Socket file descriptor\n */\nvoid RPCServerLoop(int sockfd);\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/runtime_base.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime_base.h\n * \\brief Base of all C APIs\n */\n#ifndef TVM_RUNTIME_RUNTIME_BASE_H_\n#define TVM_RUNTIME_RUNTIME_BASE_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n\n#include <stdexcept>\n\n/*! \\brief  macro to guard beginning and end section of all functions */\n#define API_BEGIN() try {\n/*! \\brief every function starts with API_BEGIN();\n     and finishes with API_END() or API_END_HANDLE_ERROR */\n#define API_END()                                         \\\n  }                                                       \\\n  catch (::tvm::runtime::EnvErrorAlreadySet & _except_) { \\\n    return -2;                                            \\\n  }                                                       \\\n  catch (std::exception & _except_) {                     \\\n    return TVMAPIHandleException(_except_);               \\\n  }                                                       \\\n  return 0;  // NOLINT(*)\n/*!\n * \\brief every function starts with API_BEGIN();\n *   and finishes with API_END() or API_END_HANDLE_ERROR\n *   The finally clause contains procedure to cleanup states when an error happens.\n */\n#define API_END_HANDLE_ERROR(Finalize)                    \\\n  }                                                       \\\n  catch (::tvm::runtime::EnvErrorAlreadySet & _except_) { \\\n    return -2;                                            \\\n  }                                                       \\\n  catch (std::exception & _except_) {                     \\\n    Finalize;                                             \\\n    return TVMAPIHandleException(_except_);               \\\n  }                                                       \\\n  return 0;  // NOLINT(*)\n\n/*!\n * \\brief handle exception throwed out\n * \\param e the exception\n * \\return the return value of API after exception is handled\n */\nint TVMAPIHandleException(const std::exception& e);\n\n#endif  // TVM_RUNTIME_RUNTIME_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/source_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file source_utils.h\n * \\brief Minimum source manipulation utils for runtime.\n */\n\n#ifndef TVM_RUNTIME_SOURCE_UTILS_H_\n#define TVM_RUNTIME_SOURCE_UTILS_H_\n\n#include <string>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief Split the source file on separate kernels by specified delimiter.\n * \\param source The source code of the kernels.\n * \\param delimiter The delimiter which is using for splitting kernels.\n * \\return Mapping from primitive name to kernel source\n */\nstd::unordered_map<std::string, std::string> SplitKernels(std::string source,\n                                                          std::string delimiter = \"// Function: \");\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_SOURCE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/stackvm/stackvm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file stackvm.h\n * \\brief A simple stack-based virtual machine.\n *\n *  This can be used to interepret host side code\n *  to setup calls into device functions\n *  when only Runtime compilation for device is available(via NVRTC or OpenCL).\n */\n#ifndef TVM_RUNTIME_STACKVM_STACKVM_H_\n#define TVM_RUNTIME_STACKVM_STACKVM_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\nusing runtime::operator<<;\n\n/*!\n * \\brief A simple stack-based virtual machine program.\n */\nclass StackVM {\n public:\n  /*!\n   * \\brief Invoke the StackVM program.\n   * \\param args The arguments to the StackVM.\n   * \\param mod_ctx The module context used in running.\n   */\n  void Run(const TVMArgs& args, runtime::ModuleNode* mod_ctx) const;\n  /*!\n   * \\brief The opcode of stack vm\n   * \\note Notation\n   *  - sp Stack pointer\n   *  - pc Program pointer\n   */\n  enum OpCode {\n    // integer ops\n    ADD_I64,\n    SUB_I64,\n    MUL_I64,\n    DIV_I64,\n    MOD_I64,\n    EQ_I64,\n    LT_I64,\n    LE_I64,\n    // floating ops\n    ADD_F64,\n    SUB_F64,\n    MUL_F64,\n    DIV_F64,\n    EQ_F64,\n    LT_F64,\n    LE_F64,\n    // Pointer comparison\n    EQ_HANDLE,\n    /*!\n     * \\brief Routine to load data from address with const offset.\n     * \\code\n     *  stack[sp].v_int64 = ((DType*)stack[sp].v_handle)[code[pc + 1].v_int];\n     *  pc = pc + 2;\n     * \\endcode\n     */\n    ARRAY_LOAD_UINT32,\n    ARRAY_LOAD_INT32,\n    ARRAY_LOAD_INT64,\n    ARRAY_LOAD_FP64,\n    ARRAY_LOAD_HANDLE,\n    ARRAY_LOAD_TVMVALUE,\n    /*!\n     * \\brief Routine to store data from constant offset.\n     * \\code\n     *  ((DType*)stack[sp - 1].v_handle)[code[pc + 1].v_int] = stack[sp];\n     *  pc = pc + 2;\n     *  sp = sp - 2;\n     * \\endcode\n     */\n    ARRAY_STORE_UINT32,\n    ARRAY_STORE_INT32,\n    ARRAY_STORE_INT64,\n    ARRAY_STORE_FP64,\n    ARRAY_STORE_HANDLE,\n    ARRAY_STORE_TVMVALUE,\n    // logical ops\n    NOT,\n    /*!\n     * \\brief Add address by an offset.\n     * \\code\n     *  stack[sp - 1].v_handle = ((char*)stack[sp - 1].v_handle + stack[sp].v_int64);\n     *  sp = sp - 1;\n     * \\endcode\n     */\n    ADDR_ADD,\n    /*!\n     * \\brief push integer fetched from next pc position into stack\n     * \\code\n     *  stack[sp + 1].v_int64 = code[pc + 1].v_int;\n     *  pc = pc + 2;\n     *  sp = sp + 1;\n     * \\endcode\n     */\n    PUSH_I64,\n    /*!\n     * \\brief push a value given relative index on the stack\n     * \\code\n     *  stack[sp + 1] = stack[sp + code[pc + 1].v_int];\n     *  pc = pc + 2;\n     *  sp = sp + 1;\n     * \\endcode\n     */\n    PUSH_VALUE,\n    /*!\n     * \\brief Load data from heap to top of stack\n     * \\code\n     *  stack[sp + 1] = heap[code[pc + 1].v_int];\n     *  pc = pc + 2;\n     *  sp = sp + 1;\n     * \\endcode\n     */\n    LOAD_HEAP,\n    /*!\n     * \\brief Store data to heap\n     * \\code\n     *  heap[code[pc + 1].v_int] = stack[sp];\n     *  sp = sp - 1;\n     * \\endcode\n     */\n    STORE_HEAP,\n    /*! \\brief pop value from top of the stack */\n    POP,\n    /*!\n     * \\brief select based on operands.\n     * \\code\n     *  stack[sp - 2] = stack[sp].v_int64 ? stack[sp - 2] : stack[sp - 1]\n     *  sp = sp - 2;\n     * \\endcode\n     */\n    SELECT,\n    /*!\n     * \\brief Assert condition is true.\n     * \\code\n     *  ICHECK(stack[sp]) << str_data[code[pc + 1].v_int];\n     *  sp = sp - 1;\n     * \\endcode\n     */\n    ASSERT,\n    /*!\n     * \\brief Relative Jump if the condition is true,\n     *  Does not change the stack status.\n     * \\code\n     *  if (stack[sp]) {\n     *    pc += code[pc + 1].v_int\n     *  } else {\n     *    pc = pc + 2;\n     *  }\n     * \\endcode\n     */\n    RJUMP_IF_TRUE,\n    /*!\n     * \\brief Relative Jump if the condition is true,\n     *  Does not change the stack status.\n     * \\code\n     *  if (stack[sp]) {\n     *    pc += code[pc + 1].v_int\n     *  } else {\n     *    pc = pc + 2;\n     *  }\n     * \\endcode\n     */\n    RJUMP_IF_FALSE,\n    /*!\n     * \\brief Relative jump to a location.\n     * \\code\n     *  pc += code[pc + 1].v_int;\n     * \\endcode\n     */\n    RJUMP,\n    /*!\n     * \\brief debug instruction.\n     * \\code\n     *  ICHECK_EQ(sp, code[pc + 1]).v_int;\n     *  pc += 2;\n     * \\code\n     */\n    ASSERT_SP,\n    /*!\n     * \\brief call an extern packed function\n     * \\code\n     *  value_stack = stack[sp - 1].v_handle;\n     *  type_stack = stack[sp - 0].v_handle;\n     *  call_fid = code[pc + 1].v_int;\n     *  begin = code[pc + 2].v_int;\n     *  end = code[pc + 3].v_int;\n     *  num_args = end - begin - 1;\n     *  f = extern_func[call_fid];\n     *  stack[sp - 1] = f(&value_stack[begin:end-1], type_stack[begin:end-1], num_args);\n     *  sp = sp - 1;\n     *  // The type codes are hidden in the code space.\n     *  pc = pc + 4\n     * \\endcode\n     */\n    CALL_PACKED_LOWERED,\n    // Allocate things on stack\n    /*!\n     * \\brief allocate data from stack.\n     * \\code\n     *  num = code[pc + 1].v_int;\n     *  void* addr = &stack[sp];\n     *  sp = sp + num;\n     *  stack[sp].v_handle = addr;\n     *  pc = pc + 1;\n     * \\endcode\n     */\n    TVM_STACK_ALLOCA_BY_8BYTE,\n    /*!\n     * \\brief allocate data from device.\n     * \\code\n     *  device_type = stack[sp - 2].v_int64;\n     *  device_id = stack[sp - 1].v_int64;\n     *  nbytes = stack[sp].v_int64;\n     *  stack[sp - 2].v_handle = device_alloca(device_type, device_id, nbytes);\n     *  sp = sp - 2;\n     *  pc = pc + 1;\n     * \\endcode\n     */\n    TVM_DEVICE_ALLOCA,\n    /*!\n     * \\brief free data into device.\n     * \\code\n     *  device_type = stack[sp - 2].v_int64;\n     *  device_id = stack[sp - 1].v_int64;\n     *  ptr = stack[sp].v_handle;\n     *  stack[sp - 2].v_int64 = device_free(device_type, device_id, ptr);\n     *  sp = sp - 2;\n     *  pc = pc + 1;\n     * \\endcode\n     */\n    TVM_DEVICE_FREE,\n    /*!\n     * \\brief throw last error\n     */\n    TVM_THROW_LAST_ERROR,\n    /*!\n     * \\brief get data from structure.\n     * \\code\n     *  index = code[pc + 1].v_int;\n     *  field = code[pc + 2].v_int;\n     *  stack[sp] = ((StructType*)stack[sp].v_handle)[index]->field;\n     *  pc = pc + 3\n     * \\endcode\n     */\n    TVM_STRUCT_GET,\n    /*!\n     * \\brief set data into structure.\n     * \\code\n     *  index = code[pc + 1].v_int;\n     *  field = code[pc + 2].v_int;\n     *  ((StructType*)stack[sp - 1].v_handle)[index]->field = stack[sp];\n     *  pc = pc + 3\n     *  sp = sp - 1\n     * \\endcode\n     */\n    TVM_STRUCT_SET\n  };\n  /*! \\brief The kind of structure field info */\n  enum StructFieldKind : int {\n    // array head address\n    kArrAddr,\n    kArrData,\n    kArrShape,\n    kArrStrides,\n    kArrNDim,\n    kArrTypeCode,\n    kArrTypeBits,\n    kArrTypeLanes,\n    kArrByteOffset,\n    kArrDeviceId,\n    kArrDeviceType,\n    kArrKindBound_,\n    // TVMValue field\n    kTVMValueContent,\n    kTVMValueKindBound_\n  };\n  /*! \\brief The code structure */\n  union Code {\n    OpCode op_code;\n    int v_int;\n  };\n  /*! \\brief The state object of StackVM */\n  struct State {\n    /*! \\brief The execution stack */\n    std::vector<TVMValue> stack;\n    /*! \\brief The global heap space */\n    std::vector<TVMValue> heap;\n    /*! \\brief stack pointer  */\n    int64_t sp{0};\n    /*! \\brief program counter */\n    int64_t pc{0};\n    /*! \\brief The current module context of stackvm */\n    runtime::ModuleNode* mod_ctx{nullptr};\n  };\n  /*! \\brief Initialize local cache*/\n  void InitCache();\n  /*!\n   * \\brief Save stackvm program to an output stream\n   * \\param strm The output stream\n   */\n  void Save(dmlc::Stream* strm) const;\n  /*!\n   * \\brief Load stackvm program from output stream\n   * \\param strm The output stream\n   */\n  bool Load(dmlc::Stream* strm);\n  /*!\n   * \\brief Print instruction at location pc\n   * \\param os The ostream\n   * \\param pc The pc\n   * \\return the pc to next instruction.\n   */\n  int64_t PrintCode(std::ostream& os, int64_t pc) const;  // NOLINT(*)\n  /*! \\brief Get thread local state of the stack VM */\n  static State* ThreadLocalState();\n  // The code below are programs\n  /*! \\brief The instructions */\n  std::vector<Code> code;\n  /*! \\brief constant error messages */\n  std::vector<std::string> str_data;\n  /*! \\brief Extern functions */\n  std::vector<std::string> extern_func_name;\n  /*! \\brief name of each heap id */\n  std::vector<std::string> heap_id_name;\n  /*! \\brief The memory size needed */\n  size_t heap_size{0};\n  /*! \\brief The stack size required */\n  size_t stack_size{1024};\n  /*!\n   * \\brief Convert I64 opcode to F64 Ones\n   * \\param code The op code.\n   * \\return the F64 op code.\n   */\n  static OpCode CodeI64ToF64(OpCode code) {\n    switch (code) {\n      case ADD_I64:\n        return ADD_F64;\n      case SUB_I64:\n        return SUB_F64;\n      case MUL_I64:\n        return MUL_F64;\n      case DIV_I64:\n        return DIV_F64;\n      case EQ_I64:\n        return EQ_F64;\n      case LT_I64:\n        return LT_F64;\n      case LE_I64:\n        return LE_F64;\n      case MOD_I64:\n        LOG(FATAL) << \"cannot handle mod for float\";\n        return ADD_F64;\n      default:\n        LOG(FATAL) << \"cannot handle op \" << code;\n        return ADD_F64;\n    }\n  }\n  /*!\n   * \\brief Get load opcode for type t\n   * \\param t the type code.\n   * \\return The load opcode\n   */\n  static OpCode GetLoad(DLDataType t) {\n    ICHECK_EQ(t.lanes, 1U);\n    if (t.code == kTVMOpaqueHandle) return ARRAY_LOAD_HANDLE;\n    if (t.code == kDLInt) {\n      switch (t.bits) {\n        case 32:\n          return ARRAY_LOAD_INT32;\n        case 64:\n          return ARRAY_LOAD_INT64;\n      }\n    } else if (t.code == kDLUInt) {\n      switch (t.bits) {\n        case 32:\n          return ARRAY_LOAD_UINT32;\n      }\n    } else if (t.code == kDLFloat) {\n      switch (t.bits) {\n        case 64:\n          return ARRAY_LOAD_FP64;\n      }\n    }\n    LOG(FATAL) << \"Cannot load type \" << t;\n    return ARRAY_LOAD_FP64;\n  }\n  /*!\n   * \\brief Get store opcode for type t\n   * \\param t the type code.\n   * \\return The load opcode\n   */\n  static OpCode GetStore(DLDataType t) {\n    ICHECK_EQ(t.lanes, 1U);\n    if (t.code == kTVMOpaqueHandle) return ARRAY_STORE_HANDLE;\n    if (t.code == kDLInt) {\n      switch (t.bits) {\n        case 32:\n          return ARRAY_STORE_INT32;\n        case 64:\n          return ARRAY_STORE_INT64;\n      }\n    } else if (t.code == kDLUInt) {\n      switch (t.bits) {\n        case 32:\n          return ARRAY_STORE_UINT32;\n      }\n    } else if (t.code == kDLFloat) {\n      switch (t.bits) {\n        case 64:\n          return ARRAY_STORE_FP64;\n      }\n    }\n    LOG(FATAL) << \"Cannot store type \" << t;\n    return ARRAY_STORE_FP64;\n  }\n  friend std::ostream& operator<<(std::ostream& os, const StackVM& vm);  // NOLINT(*)\n\n private:\n  //  execute the stack vm with given state\n  void Run(State* state) const;\n  // get extern function.\n  const PackedFunc& GetExtern(State* s, int fid) const;\n  // cached extern function\n  mutable std::vector<PackedFunc> extern_func_cache_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace dmlc {\nDMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::StackVM, true);\n}\n#endif  // TVM_RUNTIME_STACKVM_STACKVM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/stackvm/stackvm_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file stackvm_module.h\n * \\brief StackVM module\n */\n#ifndef TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_\n#define TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_\n\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"stackvm.h\"\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief create a stackvm module\n *\n * \\param fmap The map from name to function\n * \\param entry_func The entry function name.\n * \\return The created module\n */\nModule StackVMModuleCreate(std::unordered_map<std::string, StackVM> fmap, std::string entry_func);\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/static_library.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/static_library.h\n * \\brief Represents a generic '.o' static library which can be linked into the final output\n * dynamic library by export_library.\n */\n\n#ifndef TVM_RUNTIME_STATIC_LIBRARY_H_\n#define TVM_RUNTIME_STATIC_LIBRARY_H_\n\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/module.h>\n\n#include <array>\n#include <memory>\n#include <set>\n#include <string>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Returns a static library with the contents loaded from filename which exports\n * func_names with the usual packed-func calling convention.\n */\nModule LoadStaticLibrary(const std::string& filename, Array<String> func_names);\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_STATIC_LIBRARY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/texture.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file texture.h\n * \\brief Texture utilities\n */\n#ifndef TVM_RUNTIME_TEXTURE_H_\n#define TVM_RUNTIME_TEXTURE_H_\n\n#include <tvm/runtime/device_api.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Structure to represent flattened texture shape */\ntemplate <typename T>\nstruct Texture2DShape {\n  T width;\n  T height;\n  T channel;\n};\n\n/*!\n * \\param shape_rank Rank N of the Nd-shape\n * \\param convention Storage scope convention to use for flattening\n * \\return The axis separator that defines the Nd shape partitioning in 2d\n */\ninline size_t DefaultTextureLayoutSeparator(size_t shape_rank,\n                                            std::string convention = \"global.texture\") {\n  // Texture activation:\n  // e.g. [N,C,H,W,c] -> Texture2d[N*C*H, W, c]\n  // Texture weight:\n  // e.g. [O,I,H,W,c] -> Texture2d[O, I*H*W, c]\n  size_t separator = 0;\n  if (convention == \"global.texture\") {\n    separator = shape_rank - 2;\n  } else if (convention == \"global.texture-weight\") {\n    separator = 1;\n  } else if (convention == \"global.texture-nhwc\") {\n    if (shape_rank == 3) {\n      separator = 1;\n    } else {\n      separator = 2;\n    }\n  } else {\n    LOG(FATAL) << \"Encountered unknown texture lowering convention: \" << convention;\n  }\n  return separator;\n}\n\n/*!\n * \\param shape Nd shape\n * \\param rank Number of dimensions N of the Nd shape\n * \\param axis The axis separator that splits the Nd axes into two sets\n * \\return Width and height of the 2d shape\n */\ntemplate <typename T, typename S>\nTexture2DShape<T> ApplyTexture2DFlattening(const S& shape, size_t rank, size_t axis) {\n  ICHECK(axis < rank)\n      << \"Number of axes to flatten into rows must be less than shape rank for 2d flattening\";\n  Texture2DShape<T> texture{1, 1, shape[rank - 1]};\n  for (size_t i = 0; i < rank - 1; i++) {\n    if (i < axis) {\n      texture.height *= shape[i];\n    } else {\n      texture.width *= shape[i];\n    }\n  }\n  return texture;\n}\n\ninline bool IsTextureStorage(std::string scope) {\n  return scope.find(\"texture\") != std::string::npos;\n}\n\nclass TVM_DLL Pool2D {\n public:\n  Pool2D() = default;\n  void* Alloc(Device dev, DeviceAPI* device, size_t width, size_t height, DLDataType type_hint);\n  void Free(void* data);\n  // Release all resources immediately\n  void Release(Device dev, DeviceAPI* device);\n\n protected:\n  struct Entry {\n    void* data;\n    size_t x;\n    size_t y;\n    DLDataType type;\n  };\n  std::vector<Entry> free_list_;\n  std::vector<Entry> allocated_;\n};\n\n/*!\n * \\brief A two dimensional storage pool that recycles temporal workspace\n * allocations for dynamically allocated texture. See AllocTexture docstring\n * for approach to allocation and reuse.\n */\nclass TVM_DLL TexturePool {\n public:\n  /*!\n   * \\brief Create pool with specific device type and device.\n   * \\param device_type The device type.\n   * \\param device_api The device API.\n   */\n  TexturePool(DLDeviceType device_type, DeviceAPI* device_api);\n  /*! \\brief destructor */\n  ~TexturePool();\n\n  /*!\n   * \\brief Allocate a two dimensional temporal texture workspace on device\n   *\n   * \\note Two dimensional texture workspaces will be grown and reused\n   * according to the following strategy:\n   *  - Choose the workspace which minimizes the amount of memory required to\n   *    grow the workspace to fit the request.\n   *  - If a set of workspaces exist that fit the current request without\n   *    expansion, choose the workspace of that set which most closely\n   *    matches the request size, minimizing wasted space.\n   *\n   * \\param dev The context of allocation.\n   * \\param width The width of the 2d texture to be allocated.\n   * \\param height The height of the 2d texture to be allocated.\n   * \\param type_hint The type of elements.\n   */\n  void* AllocTexture(Device dev, size_t width, size_t height, DLDataType type_hint);\n  /*!\n   * \\brief Free temporal texture in backend execution.\n   *\n   * \\param dev The context of allocation.\n   * \\param ptr The pointer to be freed.\n   */\n  void FreeTexture(Device dev, void* ptr);\n\n private:\n  /*! \\brief pool of device local array */\n  std::vector<Pool2D*> array_;\n  /*! \\brief device type this pool support */\n  DLDeviceType device_type_;\n  /*! \\brief The device API */\n  DeviceAPI* device_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_TEXTURE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/thread_map.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_THREAD_MAP_H_\n#define TVM_RUNTIME_THREAD_MAP_H_\n\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <shared_mutex>\n#include <thread>\n#include <unordered_map>\n#include <utility>\n\nnamespace tvm {\nnamespace runtime {\n\n/*! \\brief Container to hold one value per thread\n *\n * Similar to thread_local, but intended for use as a non-static or\n * non-block variable, such as class member variables.  All member\n * functions are thread-safe to call.  If only the current thread's\n * value is accessed, no additional synchronization is required.  If\n * another thread's stored values are accessed, external\n * synchronization may be required.\n *\n * Calls that only require access to already-existing values will not\n * block each other.  Calls that require constructing a new value will\n * block any other calls.\n *\n * \\tparam T The object type to be held.  For instantiation of\n * ThreadMap<T> and for calls to ThreadMap<T>::Get, only a forward\n * declaration is required.  For calls to ThreadMap<T>::GetOrMake, a\n * full class definition is required.\n */\ntemplate <typename T>\nclass ThreadMap {\n public:\n  ThreadMap() {}\n\n  /*! \\brief Return the current thread's stored object, if it exists.\n   *\n   * \\return If it exists, a pointer to the stored object.  Otherwise,\n   * returns nullptr.\n   */\n  const T* Get() const { return this->Get(std::this_thread::get_id()); }\n\n  /*! \\brief Return the stored object for a given thread, if it exists.\n   *\n   * \\param id The thread whose object should be returned.\n   *\n   * \\return If it exists, a pointer to the stored object.  Otherwise,\n   * returns nullptr.\n   */\n  const T* Get(std::thread::id id) const {\n    std::shared_lock<std::shared_timed_mutex> lock(mutex_);\n    auto res = values_.find(id);\n    if (res == values_.end()) {\n      return nullptr;\n    } else {\n      return res->second.get();\n    }\n  }\n\n  /*! \\brief Return the current thread's stored object, if it exists.\n   *\n   * \\return If it exists, a pointer to the stored object.  Otherwise,\n   * returns nullptr.\n   */\n  T* Get() { return const_cast<T*>(const_cast<const ThreadMap<T>*>(this)->Get()); }\n\n  /*! \\brief Return the stored object for a given thread, if it exists.\n   *\n   * \\param id The thread whose object should be returned.\n   *\n   * \\return If it exists, a pointer to the stored object.  Otherwise,\n   * returns nullptr.\n   */\n  T* Get(std::thread::id id) {\n    return const_cast<T*>(const_cast<const ThreadMap<T>*>(this)->Get(id));\n  }\n\n  /*! \\brief Return the current thread's stored object, making it if\n   * necessary.\n   *\n   * Since this method can modify the stored map, there is no\n   * non-const version available.\n   *\n   * \\tparam Params Types of the stored object's constructor arguments\n   *\n   * \\return A reference to the stored object\n   */\n  template <typename... Params>\n  T& GetOrMake(Params&&... params) {\n    return GetOrMake(std::this_thread::get_id(), std::forward<Params>(params)...);\n  }\n\n  /*! \\brief Return the stored object for a given thread, making it if\n   * necessary\n   *\n   * Since this method can modify the stored map, there is no\n   * non-const version available.\n   *\n   * \\tparam Params Types of the stored object's constructor arguments\n   *\n   * \\param id The thread whose object should be returned.\n   *\n   * \\param params Arguments to the stored object's constructor.  Only\n   * used if the specified thread does not currently exist in the map.\n   *\n   * \\return A reference to the stored object\n   */\n  template <typename... Params>\n  T& GetOrMake(std::thread::id id, Params&&... params) {\n    // Try to get stored value first, which would only require shared\n    // access.\n    if (T* output = Get(id)) {\n      return *output;\n    }\n\n    // Not in map, need exclusive lock to write\n    std::unique_lock<std::shared_timed_mutex> lock(mutex_);\n\n    // Check again, in case another thread got the unique lock first\n    // and already constructed the object.\n    auto res = values_.find(id);\n    if (res != values_.end()) {\n      return *res->second;\n    }\n\n    // No value exists, make one and return it.\n    std::unique_ptr<T>& new_val = values_[id] =\n        std::make_unique<T>(std::forward<Params>(params)...);\n    return *new_val;\n  }\n\n  /*! \\brief Clears all values held by the ThreadMap\n   *\n   * Calling Clear() invalidates any pointers/references previously\n   * returned by Get/GetOrMake.\n   *\n   */\n  void Clear() {\n    std::unique_lock<std::shared_timed_mutex> lock(mutex_);\n    values_.clear();\n  }\n\n private:\n  //! \\brief Mutex to protect values_\n  mutable std::shared_timed_mutex mutex_;\n\n  //! \\brief Map containing stored values\n  std::unordered_map<std::thread::id, std::unique_ptr<T>> values_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_THREAD_MAP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/thread_storage_scope.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file thread_storage_scope.h\n * \\brief Extract launch parameters configuration from TVMArgs.\n */\n#ifndef TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_\n#define TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_\n\n#include <tvm/runtime/metadata.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <string>\n#include <vector>\n\n#include \"meta_data.h\"\n\nnamespace tvm {\nnamespace runtime {\n\n/*!\n * \\brief Memory hierachy rank in the storage system\n * \\note The global rank and shared rank have one to one\n *       correspondence to the thread rank.\n */\nenum class StorageRank {\n  /*! \\brief global memory */\n  kGlobal = 0,\n  /*! \\brief shared memory among thread group */\n  kShared = 1,\n  /*!\n   * \\brief reserved for warp memory.\n   *  This is only used by programming model.\n   *  There is no such memory usually in GPU.\n   *  Instead, we can simulate it by registers and shuffle.\n   */\n  kWarp = 2,\n  /*! \\brief thread local memory */\n  kLocal = 3,\n  /*! \\brief wmma scope memory of matrix_a */\n  kWMMAMatrixA = 4,\n  /*! \\brief wmma scope memory of matrix_b */\n  kWMMAMatrixB = 5,\n  /*! \\brief wmma scope memory of accumulator */\n  kWMMAAccumulator = 6,\n  /*! \\brief global scope texture memory */\n  kTexture = 7,\n};\n\n/*!\n * \\param thread_scope_rank The thread scope rank\n * \\return default storage rank given the thread scope\n */\ninline StorageRank DefaultStorageRank(int thread_scope_rank) {\n  switch (thread_scope_rank) {\n    case -1:\n      return StorageRank::kGlobal;\n    case 0:\n      return StorageRank::kShared;\n    case 1:\n      return StorageRank::kLocal;\n    default: {\n      LOG(FATAL) << \"unknown rank\";\n      return StorageRank::kGlobal;\n    }\n  }\n}\n\n/*! \\brief class to represent storage scope */\nstruct StorageScope {\n  /*! \\brief The rank of the storage */\n  StorageRank rank{StorageRank::kGlobal};\n  /*! \\brief tag for special purpose memory. */\n  std::string tag;\n  // comparator\n  inline bool operator==(const StorageScope& other) const {\n    return rank == other.rank && tag == other.tag;\n  }\n  inline bool operator!=(const StorageScope& other) const { return !(*this == other); }\n  inline std::string to_string() const {\n    std::string ret;\n    switch (rank) {\n      case StorageRank::kGlobal:\n        return \"global\" + tag;\n      case StorageRank::kShared:\n        return \"shared\" + tag;\n      case StorageRank::kWarp:\n        return \"warp\" + tag;\n      case StorageRank::kLocal:\n        return \"local\" + tag;\n      case StorageRank::kWMMAMatrixA:\n        return \"wmma.matrix_a\" + tag;\n      case StorageRank::kWMMAMatrixB:\n        return \"wmma.matrix_b\" + tag;\n      case StorageRank::kWMMAAccumulator:\n        return \"wmma.accumulator\" + tag;\n      case StorageRank::kTexture:\n        return \"texture\" + tag;\n      default:\n        LOG(FATAL) << \"unknown storage scope\";\n        return \"\";\n    }\n  }\n  /*!\n   * \\brief Create storage scope from string\n   * \\param s The string to be parsed.\n   * \\return The storage scope.\n   */\n  static StorageScope Create(const std::string& s) {\n    StorageScope r;\n    if (s.empty()) {\n      r.rank = StorageRank::kGlobal;\n    } else if (s.compare(0, 6, \"global\") == 0) {\n      r.rank = StorageRank::kGlobal;\n      r.tag = s.substr(6, std::string::npos);\n    } else if (s.compare(0, 6, \"shared\") == 0) {\n      r.rank = StorageRank::kShared;\n      r.tag = s.substr(6, std::string::npos);\n    } else if (s.compare(0, 4, \"warp\") == 0) {\n      r.rank = StorageRank::kWarp;\n      r.tag = s.substr(4, std::string::npos);\n    } else if (s.compare(0, 5, \"local\") == 0) {\n      r.rank = StorageRank::kLocal;\n      r.tag = s.substr(5, std::string::npos);\n    } else if (s.compare(0, 13, \"wmma.matrix_a\") == 0) {\n      r.rank = StorageRank::kWMMAMatrixA;\n      r.tag = s.substr(13, std::string::npos);\n    } else if (s.compare(0, 13, \"wmma.matrix_b\") == 0) {\n      r.rank = StorageRank::kWMMAMatrixB;\n      r.tag = s.substr(13, std::string::npos);\n    } else if (s.compare(0, 16, \"wmma.accumulator\") == 0) {\n      r.rank = StorageRank::kWMMAAccumulator;\n      r.tag = s.substr(16, std::string::npos);\n    } else if (s.compare(0, 7, \"texture\") == 0) {\n      r.rank = StorageRank::kTexture;\n      r.tag = s.substr(7, std::string::npos);\n    } else {\n      LOG(FATAL) << \"unknown storage scope \" << s;\n    }\n    return r;\n  }\n};\n\n/*! \\brief class to represent thread scope */\nstruct ThreadScope {\n  /*! \\brief The rank of thread scope */\n  int rank{0};\n  /*! \\brief the dimension index under the rank */\n  int dim_index{0};\n  /*!\n   * \\brief Create storage scope from string\n   * \\param s The string to be parsed.\n   * \\return The storage scope.\n   */\n  static ThreadScope Create(const std::string& s) {\n    ThreadScope r;\n    if (s.compare(0, 7, \"vthread\") == 0 || s == \"cthread\") {\n      // virtual thread at the same level as local\n      r.rank = 1;\n      r.dim_index = -1;\n    } else if (s.compare(0, 9, \"blockIdx.\") == 0) {\n      r.rank = 0;\n      r.dim_index = static_cast<int>(s[9] - 'x');\n    } else if (s.compare(0, 10, \"threadIdx.\") == 0) {\n      r.rank = 1;\n      r.dim_index = static_cast<int>(s[10] - 'x');\n    } else {\n      LOG(FATAL) << \"Unknown threadscope \" << s;\n    }\n    return r;\n  }\n};\n\n/*! \\brief workload specification */\nstruct ThreadWorkLoad {\n  // array, first three are thread configuration.\n  size_t work_size[6];\n  // Dynamic shared memory allocation size in bytes.\n  size_t dyn_shmem_size{0};\n  /*!\n   * \\param i The block dimension.\n   * \\return i-th block dim\n   */\n  inline size_t block_dim(size_t i) const { return work_size[i + 3]; }\n  /*!\n   * \\param i The grid dimension.\n   * \\return i-th grid dim\n   */\n  inline size_t grid_dim(size_t i) const { return work_size[i]; }\n};\n/*! \\brief Launch parameters configuration */\nclass LaunchParamConfig {\n public:\n  void Init(size_t base, const std::vector<std::string>& launch_param_tags) {\n    base_ = base;\n    std::vector<bool> filled(6, false);\n    for (size_t i = 0; i < launch_param_tags.size(); ++i) {\n      const std::string& tag = launch_param_tags[i];\n      if (tag == launch_param::kUseDynamicSharedMemoryTag) {\n        ICHECK_EQ(i, launch_param_tags.size() - 1)\n            << \"kUseDynamicSharedMemoryTag should be the last tag in launch_param_tags.\";\n        use_dyn_shared_memory_ = true;\n      } else {\n        ThreadScope ts = ThreadScope::Create(tag);\n        arg_index_map_.push_back(ts.rank * 3 + ts.dim_index);\n        filled[ts.rank * 3 + ts.dim_index] = true;\n      }\n    }\n    work_dim_ = 1;\n    for (int i = 0; i < 3; ++i) {\n      if (filled[i] || filled[i + 3]) {\n        work_dim_ = i + 1;\n      }\n    }\n  }\n  // extract workload from arguments.\n  ThreadWorkLoad Extract(TVMArgs x) const {\n    ThreadWorkLoad w;\n    std::fill(w.work_size, w.work_size + 6, 1);\n    for (size_t i = 0; i < arg_index_map_.size(); ++i) {\n      // Dynamic shapes can result in 0 dim size. Guard to ensure that the dim size is at least 1.\n      size_t size = static_cast<size_t>(x.values[base_ + i].v_int64);\n      if (size > 0) {\n        w.work_size[arg_index_map_[i]] = size;\n      }\n    }\n    if (use_dyn_shared_memory_) {\n      w.dyn_shmem_size = static_cast<size_t>(x.values[base_ + arg_index_map_.size()].v_int64);\n    }\n    return w;\n  }\n  // return the work dim\n  size_t work_dim() const { return work_dim_; }\n\n private:\n  /*! \\brief base axis */\n  size_t base_;\n  /*! \\brief The worker dimension */\n  size_t work_dim_;\n  /*! \\brief The index mapping. */\n  std::vector<uint32_t> arg_index_map_;\n  /*! \\brief Whether or not use dynamic shared memory. */\n  bool use_dyn_shared_memory_{false};\n};\n\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace std {\ntemplate <>\nstruct hash<::tvm::runtime::StorageScope> {\n  std::size_t operator()(const ::tvm::runtime::StorageScope& k) const {\n    return static_cast<size_t>(k.rank);\n  }\n};\n}  // namespace std\n#endif  // TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vm/naive_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/naive_allocator.h\n */\n#ifndef TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_\n#define TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_\n\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/vm/memory_manager.h>\n\n#include <atomic>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\nclass NaiveAllocator final : public Allocator {\n public:\n  explicit NaiveAllocator(Device dev) : Allocator(kNaive), used_memory_(0), device_(dev) {}\n\n  Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) override {\n    Buffer buf;\n    buf.device = device_;\n    buf.size = nbytes;\n    buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, nbytes, alignment, type_hint);\n    used_memory_.fetch_add(nbytes, std::memory_order_relaxed);\n    DLOG(INFO) << \"allocate \" << nbytes << \" B, used memory \" << used_memory_ << \" B\";\n    return buf;\n  }\n\n  void Free(const Buffer& buffer) override {\n    DeviceAPI::Get(device_)->FreeDataSpace(buffer.device, buffer.data);\n    used_memory_.fetch_sub(buffer.size, std::memory_order_relaxed);\n    DLOG(INFO) << \"free \" << buffer.size << \" B, used memory \" << used_memory_ << \" B\";\n  }\n\n  size_t UsedMemory() const override { return used_memory_.load(std::memory_order_relaxed); }\n\n private:\n  std::atomic<size_t> used_memory_;\n  Device device_;\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vm/pooled_allocator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime/pooled_allocator.h\n */\n#ifndef TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_\n#define TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_\n\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/vm/memory_manager.h>\n\n#include <atomic>\n#include <mutex>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\nclass PooledAllocator final : public Allocator {\n public:\n  static constexpr size_t kDefaultPageSize = 4096;\n\n  explicit PooledAllocator(Device dev, size_t page_size = kDefaultPageSize)\n      : Allocator(kPooled), page_size_(page_size), used_memory_(0), device_(dev) {}\n\n  ~PooledAllocator() { ReleaseAll(); }\n\n  Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) override {\n    std::lock_guard<std::recursive_mutex> lock(mu_);\n    size_t size = ((nbytes + page_size_ - 1) / page_size_) * page_size_;\n    auto&& it = memory_pool_.find(size);\n    if (it != memory_pool_.end() && !it->second.empty()) {\n      auto&& pool = it->second;\n      auto ret = pool.back();\n      pool.pop_back();\n      return ret;\n    }\n    Buffer buf;\n    buf.device = device_;\n    buf.size = size;\n    try {\n      buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);\n    } catch (InternalError& err) {\n      LOG(WARNING) << \"PooledAllocator got InternalError during allocation: \" << err.message();\n      LOG(WARNING) << \"Trying to release all unused memory and reallocate...\";\n      ReleaseAll();\n      buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);\n    }\n\n    used_memory_.fetch_add(size, std::memory_order_relaxed);\n    VLOG(1) << \"allocate \" << size << \" B, used memory \" << used_memory_ << \" B\";\n    return buf;\n  }\n\n  void Free(const Buffer& buffer) override {\n    std::lock_guard<std::recursive_mutex> lock(mu_);\n    if (memory_pool_.find(buffer.size) == memory_pool_.end()) {\n      memory_pool_.emplace(buffer.size, std::vector<Buffer>{});\n    }\n    memory_pool_.at(buffer.size).push_back(buffer);\n    VLOG(1) << \"reclaim buffer \" << buffer.size;\n  }\n\n  size_t UsedMemory() const override { return used_memory_.load(std::memory_order_relaxed); }\n\n private:\n  void ReleaseAll() {\n    std::lock_guard<std::recursive_mutex> lock(mu_);\n    for (auto const& it : memory_pool_) {\n      auto const& pool = it.second;\n      for (auto const& buf : pool) {\n        DeviceAPI::Get(buf.device)->FreeDataSpace(buf.device, buf.data);\n      }\n    }\n    memory_pool_.clear();\n    used_memory_ = 0;\n    VLOG(1) << \"release all buffers\";\n  }\n\n private:\n  size_t page_size_;\n  std::atomic<size_t> used_memory_;\n  std::unordered_map<size_t, std::vector<Buffer>> memory_pool_;\n  std::recursive_mutex mu_;\n  Device device_;\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vm/profiler/vm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/vm/profiler/vm.h\n * \\brief The Relay debug virtual machine.\n */\n\n#ifndef TVM_RUNTIME_VM_PROFILER_VM_H_\n#define TVM_RUNTIME_VM_PROFILER_VM_H_\n\n#include <tvm/runtime/profiling.h>\n#include <tvm/runtime/vm/vm.h>\n\n#include <memory>\n#include <optional>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\nclass VirtualMachineDebug : public VirtualMachine {\n public:\n  VirtualMachineDebug() : VirtualMachine(), prof_({}) {}\n\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n\n  void LoadExecutable(const ObjectPtr<Executable>& exec) final;\n\n  ~VirtualMachineDebug() {}\n\n private:\n  void InvokePacked(Index packed_index, const PackedFunc& func, Index arg_count, Index output_size,\n                    const std::vector<ObjectRef>& args) final;\n  void OpStartHook(Instruction instr) final;\n  void OpStopHook() final;\n\n  std::unordered_map<Index, std::string> packed_index_map_;\n  std::optional<profiling::Profiler> prof_;\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_PROFILER_VM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vm/serialize_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/runtime/vm/serialize_utils.h\n * \\brief Definitions of helpers for serializing and deserializing a Relay VM.\n */\n#ifndef TVM_RUNTIME_VM_SERIALIZE_UTILS_H_\n#define TVM_RUNTIME_VM_SERIALIZE_UTILS_H_\n\n#include <dmlc/memory_io.h>\n#include <tvm/runtime/vm/executable.h>\n\n#include <functional>\n#include <string>\n#include <vector>\n\n#include \"../../support/utils.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vm {\n\n/*! \\brief The magic number for the serialized VM bytecode file  */\nconstexpr uint64_t kTVMVMBytecodeMagic = 0xD225DE2F4214151D;\n\ntemplate <typename T>\nstatic inline uint64_t VectorHash(uint64_t key, const std::vector<T>& values) {\n  for (const auto& it : values) {\n    key = support::HashCombine(key, it);\n  }\n  return key;\n}\n\n// A struct to hold the funciton info in the code section.\nstruct VMFunctionSerializer {\n  /*! \\brief The name of the VMFunction. */\n  std::string name;\n  /*! \\brief The number of registers used by the VMFunction. */\n  Index register_file_size;\n  /*! \\brief The number of instructions in the VMFunction. */\n  size_t num_instructions;\n  /*! \\brief The parameters of the VMFunction. */\n  std::vector<std::string> params;\n  /*! \\brief The index for the devices holding each parameter of the VMFunction. */\n  std::vector<Index> param_device_indexes;\n\n  VMFunctionSerializer() = default;\n\n  VMFunctionSerializer(const std::string& name, Index register_file_size, size_t num_instructions,\n                       const std::vector<std::string>& params,\n                       const std::vector<Index>& param_device_indexes)\n      : name(name),\n        register_file_size(register_file_size),\n        num_instructions(num_instructions),\n        params(params),\n        param_device_indexes(param_device_indexes) {}\n\n  /*!\n   * \\brief Load the serialized function header.\n   * \\param strm The stream used to load data.\n   * \\return True if successful. Otherwise, false.\n   */\n  bool Load(dmlc::Stream* strm) {\n    std::vector<std::string> func_info;\n    if (!strm->Read(&func_info)) return false;\n    ICHECK_EQ(func_info.size(), 3U) << \"Failed to decode the vm function.\"\n                                    << \"\\n\";\n    name = func_info[0];\n    register_file_size = std::stoll(func_info[1]);\n    // Get the number of instructions.\n    num_instructions = static_cast<size_t>(std::stoll(func_info[2]));\n    if (!strm->Read(&params)) return false;\n    if (!strm->Read(&param_device_indexes)) return false;\n    return true;\n  }\n\n  /*!\n   * \\brief Save the VM function header into the serialized form.\n   * \\param strm The stream used to save data.\n   */\n  void Save(dmlc::Stream* strm) const {\n    std::vector<std::string> func_info;\n    func_info.push_back(name);\n    func_info.push_back(std::to_string(register_file_size));\n    func_info.push_back(std::to_string(num_instructions));\n    strm->Write(func_info);\n    strm->Write(params);\n    strm->Write(param_device_indexes);\n  }\n};\n\nstruct VMInstructionSerializer {\n  /*! \\brief The opcode of the instruction. */\n  Index opcode;\n  /*! \\brief The fields of the instruction. */\n  std::vector<Index> fields;\n\n  VMInstructionSerializer() = default;\n\n  VMInstructionSerializer(Index opcode, const std::vector<Index>& fields)\n      : opcode(opcode), fields(fields) {}\n\n  /*!\n   * \\brief Compute the hash of the serialized instruction.\n   * \\return The hash that combines the opcode and all fields of the VM\n   * instruction.\n   */\n  Index Hash() const {\n    uint64_t key = static_cast<uint64_t>(opcode);\n    key = VectorHash(key, fields);\n    return key;\n  }\n\n  /*!\n   * \\brief Load the serialized instruction.\n   * \\param strm The stream used to load data.\n   * \\return True if successful. Otherwise, false.\n   */\n  bool Load(dmlc::Stream* strm) {\n    std::vector<Index> instr;\n    if (!strm->Read(&instr)) return false;\n    ICHECK_GE(instr.size(), 2U);\n    Index loaded_hash = instr[0];\n    opcode = instr[1];\n\n    for (size_t i = 2; i < instr.size(); i++) {\n      fields.push_back(instr[i]);\n    }\n\n    Index hash = Hash();\n    ICHECK_EQ(loaded_hash, hash) << \"Found mismatch in hash for opcode: \" << opcode << \"\\n\";\n    return true;\n  }\n\n  /*!\n   * \\brief Save the instruction into the serialized form.\n   * \\param strm The stream used to save data.\n   */\n  void Save(dmlc::Stream* strm) const {\n    Index hash = Hash();\n    std::vector<Index> serialized({hash, opcode});\n    serialized.insert(serialized.end(), fields.begin(), fields.end());\n    strm->Write(serialized);\n  }\n};\n\n}  // namespace vm\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VM_SERIALIZE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_amdrgp.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanDevice;\n\nclass VulkanStreamProfiler {\n public:\n  enum state { READY = 0, RUNNING, RESET };\n\n  explicit VulkanStreamProfiler(const VulkanDevice* device);\n\n  virtual ~VulkanStreamProfiler() {}\n\n  virtual void reset() { curr_state_ = RESET; }\n\n  virtual void ready() {\n    if (curr_state_ == RESET) {\n      curr_state_ = READY;\n    }\n  }\n\n  virtual void capture() = 0;\n\n protected:\n  const VulkanDevice* device_;\n  state curr_state_;\n  bool available_;\n};\n\nclass AmdRgpProfiler : public VulkanStreamProfiler {\n public:\n  explicit AmdRgpProfiler(const VulkanDevice* device) : VulkanStreamProfiler(device) {}\n\n  void capture();\n};\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_\n\n#include <vulkan/vulkan_core.h>\n\n#include <memory>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanDevice;\n\nclass VulkanBuffer {\n public:\n  /* \\brief Allocate memory on the device\n   *\n   * \\param device Which device should have the memory allocation.\n   * The VulkanDevice given should outlive the VulkanBuffer.\n   *\n   * \\param nbytes Size of the buffer in bytes\n   *\n   * \\param usage The usage flags for the buffer (e.g. transfer\n   * source, transfer dest, storage buffer, etc.)\n   *\n   * \\param mem_type_index The memory type to index.  This should be\n   * an index to a compatible memory located in\n   * VkPhysicalDeviceMemoryProperties.\n   */\n  VulkanBuffer(const VulkanDevice& device, size_t nbytes, VkBufferUsageFlags usage,\n               uint32_t mem_type_index);\n\n  //! \\brief Destructor, deallocates the memory and buffer.\n  ~VulkanBuffer();\n\n  // Forbid copy assignment/constructor\n  VulkanBuffer(const VulkanBuffer&) = delete;\n  VulkanBuffer& operator=(const VulkanBuffer&) = delete;\n\n  // Allow move assignment/constructor\n  VulkanBuffer(VulkanBuffer&&);\n  VulkanBuffer& operator=(VulkanBuffer&&);\n\n private:\n  /*! \\brief Whether this buffer should be allocated using dedicated\n   * allocation\n   *\n   * In typical usage, there will be one VkDeviceMemory that has a\n   * large number of VkBuffers pointing to it.  Currently, the TVM\n   * Vulkan runtime has a single VkBuffer for each VkDeviceMemory.  In\n   * this case, there can be performance benefits by explicitly\n   * marking this as a dedicated allocation.  The function returns\n   * true if the device supports the dedicated allocation extension,\n   * and the buffer either requires or has better performance with a\n   * dedicated allocation.\n   *\n   * \\param[out] nbytes If using dedicated allocation, the number of\n   * bytes required for the allocation.  If not using dedicated\n   * allocation, this value is unchanged.\n   *\n   * \\returns Whether the allocation should use the dedicated\n   * allocation extension.\n   */\n  static bool UseDedicatedAllocation(const VulkanDevice& device, VkBuffer buffer,\n                                     VkDeviceSize* nbytes);\n\n  // TODO(elunderberg): Move copy functionality into the buffer class\n  // so these don't need to be public.\n public:\n  /*! \\brief Pointer to the device that owns this buffer.\n   *\n   * Assumes that the VulkanBuffer will be destructed before the\n   * VulkanDevice, and this will never be a dangling reference.\n   * Stores a VkDevice and not a VulkanDevice, because the\n   * VulkanDevice may be moved to a different location while the\n   * VulkanBuffer is alive.\n   */\n  VkDevice device_{VK_NULL_HANDLE};\n\n  //! \\brief Handle to the logical buffer on the device\n  VkBuffer buffer{VK_NULL_HANDLE};\n\n  //! \\brief Handle to the physical device memory\n  VkDeviceMemory memory{VK_NULL_HANDLE};\n\n  friend class VulkanHostVisibleBuffer;\n};\n\n/*! \\brief A struct to represent Vulkan buffers backed by host visible memory */\nclass VulkanHostVisibleBuffer {\n public:\n  /* \\brief Allocate memory on the device, visible to the host\n   *\n   * \\param device Which GPU device should have the memory allocation.\n   * The VulkanDevice specified should outlive the VulkanBuffer.\n   *\n   * \\param nbytes Size of the buffer in bytes\n   *\n   * \\param usage The usage flags for the buffer (e.g. transfer\n   * source, transfer dest, storage buffer, etc.)\n   *\n   * \\param mem_type_index The memory type to index.  This should be\n   * an index to a compatible memory located in\n   * VkPhysicalDeviceMemoryProperties.\n   */\n  VulkanHostVisibleBuffer(const VulkanDevice& device, size_t nbytes, VkBufferUsageFlags usage,\n                          uint32_t mem_type_index);\n\n  //! \\brief Unmap memory and deallocate.\n  ~VulkanHostVisibleBuffer();\n\n  // Forbid copy assignment/constructor\n  VulkanHostVisibleBuffer(const VulkanHostVisibleBuffer&) = delete;\n  VulkanHostVisibleBuffer& operator=(const VulkanHostVisibleBuffer&) = delete;\n\n  // Allow move assignment/constructor\n  VulkanHostVisibleBuffer(VulkanHostVisibleBuffer&&);\n  VulkanHostVisibleBuffer& operator=(VulkanHostVisibleBuffer&&);\n\n private:\n  // TODO(elunderberg): Move copy functionality into the buffer class\n  // so these don't need to be public.\n public:\n  VulkanBuffer vk_buf;\n  void* host_addr{nullptr};\n  size_t size{0};\n};\n\nusing VulkanStagingBuffer = VulkanHostVisibleBuffer;\nusing VulkanUniformBuffer = VulkanHostVisibleBuffer;\n\nVulkanHostVisibleBuffer* GetOrAllocate(\n    int device_id, size_t size, VkBufferUsageFlags usage, uint32_t mem_type_index,\n    std::unordered_map<size_t, std::unique_ptr<VulkanHostVisibleBuffer>>* buffers_ptr,\n    bool sync_before_realloc = false);\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n#include <vulkan/vulkan.h>\n\n#include <memory>\n#include <mutex>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\n/*! \\brief Maximum number of GPU supported in VulkanModule. */\nstatic constexpr const int kVulkanMaxNumDevice = 8;\n\n/*! \\brief TVM Vulkan binary pack magic number */\nstatic constexpr const int kVulkanModuleMagic = 0x02700027;\n\nconst int kMaxPushConstantsBytes = 128;\n\n/*! \\brief A mask used when we attach additional information to shaders */\nenum ShaderMetaDataFlagMask { kUseUBO = 0 };\n\ninline const char* VKGetErrorString(VkResult error) {\n  switch (error) {\n    case VK_SUCCESS:\n      return \"VK_SUCCESS\";\n    case VK_NOT_READY:\n      return \"VK_NOT_READY\";\n    case VK_TIMEOUT:\n      return \"VK_TIMEOUT\";\n    case VK_EVENT_SET:\n      return \"VK_EVENT_SET\";\n    case VK_EVENT_RESET:\n      return \"VK_EVENT_RESET\";\n    case VK_INCOMPLETE:\n      return \"VK_INCOMPLETE\";\n    case VK_ERROR_OUT_OF_HOST_MEMORY:\n      return \"VK_ERROR_OUT_OF_HOST_MEMORY\";\n    case VK_ERROR_OUT_OF_DEVICE_MEMORY:\n      return \"VK_ERROR_OUT_OF_DEVICE_MEMORY\";\n    case VK_ERROR_INITIALIZATION_FAILED:\n      return \"VK_ERROR_INITIALIZATION_FAILED\";\n    case VK_ERROR_DEVICE_LOST:\n      return \"VK_ERROR_DEVICE_LOST\";\n    case VK_ERROR_MEMORY_MAP_FAILED:\n      return \"VK_ERROR_MEMORY_MAP_FAILED\";\n    case VK_ERROR_LAYER_NOT_PRESENT:\n      return \"VK_ERROR_LAYER_NOT_PRESENT\";\n    case VK_ERROR_EXTENSION_NOT_PRESENT:\n      return \"VK_ERROR_EXTENSION_NOT_PRESENT\";\n    case VK_ERROR_FEATURE_NOT_PRESENT:\n      return \"VK_ERROR_FEATURE_NOT_PRESENT\";\n    case VK_ERROR_INCOMPATIBLE_DRIVER:\n      return \"VK_ERROR_INCOMPATIBLE_DRIVER\";\n    case VK_ERROR_TOO_MANY_OBJECTS:\n      return \"VK_ERROR_TOO_MANY_OBJECTS\";\n    case VK_ERROR_FORMAT_NOT_SUPPORTED:\n      return \"VK_ERROR_FORMAT_NOT_SUPPORTED\";\n    case VK_ERROR_FRAGMENTED_POOL:\n      return \"VK_ERROR_FRAGMENTED_POOL\";\n    default:\n      return \"Unknown Vulkan error code\";\n  }\n}\n\n/*!\n * \\brief Protected Vulkan call\n * \\param func Expression to call.\n */\n#define VULKAN_CHECK_ERROR(__e)                                       \\\n  {                                                                   \\\n    ICHECK(__e == VK_SUCCESS) << \"Vulkan Error, code=\" << __e << \": \" \\\n                              << vulkan::VKGetErrorString(__e);       \\\n  }\n\n#define VULKAN_CALL(func)    \\\n  {                          \\\n    VkResult __e = (func);   \\\n    VULKAN_CHECK_ERROR(__e); \\\n  }\n\nstd::vector<const char*> FindEnabledExtensions(const std::vector<VkExtensionProperties>& ext_prop,\n                                               const std::vector<const char*>& required_extensions,\n                                               const std::vector<const char*>& optional_extensions);\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_device.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <memory>\n#include <mutex>\n#include <shared_mutex>\n#include <string>\n#include <thread>\n#include <unordered_map>\n#include <vector>\n\n#include \"../thread_map.h\"\n#include \"vulkan/vulkan_core.h\"\n#include \"vulkan_buffer.h\"\n#include \"vulkan_stream.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanInstance;\nclass VulkanDevice;\n\nstruct VulkanDescriptorTemplateKHRFunctions {\n  explicit VulkanDescriptorTemplateKHRFunctions(VkDevice device);\n\n  PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR{nullptr};\n  PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR{nullptr};\n  PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR{nullptr};\n  PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR{nullptr};\n};\n\nstruct VulkanGetBufferMemoryRequirements2Functions {\n  explicit VulkanGetBufferMemoryRequirements2Functions(VkDevice device);\n\n  PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR{nullptr};\n};\n\nstruct VulkanQueueInsertDebugUtilsLabelFunctions {\n  explicit VulkanQueueInsertDebugUtilsLabelFunctions(VkInstance instance);\n\n  PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT{nullptr};\n};\n\n/*!\n * \\brief Stores the capabilities/limits queried from the physical device.\n *\n * The member variables here have a 1-1 mapping to Target parameters,\n * if target->GetTargetDeviceType()==kDLVulkan.  A separate struct is used\n * to maintain the boundary between the Vulkan runtime in\n * libtvm_runtime.so, and the Target object in libtvm.so.\n */\nstruct VulkanDeviceProperties {\n  VulkanDeviceProperties() {}\n  VulkanDeviceProperties(const VulkanInstance& instance, const VulkanDevice& device);\n\n  bool supports_float16{false};\n  bool supports_float32{true};\n  bool supports_float64{false};\n  bool supports_int8{false};\n  bool supports_int16{false};\n  bool supports_int32{true};\n  bool supports_int64{false};\n  bool supports_8bit_buffer{false};\n  bool supports_16bit_buffer{false};\n  bool supports_storage_buffer_storage_class{false};\n  bool supports_push_descriptor{false};\n  bool supports_dedicated_allocation{false};\n  bool supports_integer_dot_product{false};\n  uint32_t supported_subgroup_operations{0};\n  uint32_t max_num_threads{1};\n  uint32_t thread_warp_size{1};\n  uint32_t max_block_size_x{1};\n  uint32_t max_block_size_y{1};\n  uint32_t max_block_size_z{1};\n  uint32_t max_push_constants_size{128};\n  uint32_t max_uniform_buffer_range{16384};\n  uint32_t max_storage_buffer_range{1 << 27};\n  uint32_t max_per_stage_descriptor_storage_buffer{4};\n  uint32_t max_shared_memory_per_block{16384};\n  std::string device_type{\"unknown_device_type\"};\n  std::string device_name{\"unknown_device_name\"};\n  std::string driver_name{\"unknown_driver_name\"};\n  uint32_t driver_version{0};\n  uint32_t vulkan_api_version{VK_API_VERSION_1_0};\n  uint32_t max_spirv_version{0x10000};\n};\n\n/*! \\brief Handle to the Vulkan API's VkDevice\n *\n * Handles all setup and teardown of the class.  The owner of the\n * VulkanDevice object is responsible for ensuring that it remains\n * alive as long as any object that accesses that device is used.\n */\nclass VulkanDevice {\n public:\n  VulkanDevice(const VulkanInstance& instance, VkPhysicalDevice phy_dev);\n  ~VulkanDevice();\n\n  // Allow move constructor/assignment\n  VulkanDevice(VulkanDevice&&);\n  VulkanDevice& operator=(VulkanDevice&&);\n\n  // Disable copy constructor/assignment\n  VulkanDevice(const VulkanDevice&) = delete;\n  VulkanDevice& operator=(const VulkanDevice&) = delete;\n\n  /*! \\brief Expose the internal VkDevice\n   *\n   * Allows the managed class to be passed to Vulkan APIs as if it\n   * were the VkDevice handler itself.\n   */\n  operator VkDevice() const { return device_; }\n\n  /*! \\brief Expose the internal VkPhysicalDevice\n   *\n   * Allows the managed class to be passed to Vulkan APIs as if it\n   * were the VkPhysicalDevice handler itself.\n   */\n  operator VkPhysicalDevice() const { return physical_device_; }\n\n  /*! \\brief Returns whether this device supports Vulkan compute operations.\n   *\n   * If the device does not support Vulkan compute operations, it\n   * should not be used any further.\n   */\n  bool SupportsCompute() const;\n\n  /*! \\brief Calls vkQueueSubmit to run work on the GPU\n   *\n   * Currently only supports submitting a single VkSubmitInfo at a\n   * time.  Handles mutexing internally, safe to call from multiple\n   * CPU threads.\n   *\n   * \\param submit_info The job submission information to be passed to\n   * vkQueueSubmit.\n   *\n   * \\param fence Optional fence to be passed to vkQueueSubmit,\n   * signals once the command buffers submitted have completed.\n   */\n  void QueueSubmit(VkSubmitInfo submit_info, VkFence fence) const;\n\n  /*! \\brief Checks if the device has an extension enabled\n   *\n   * Returns true if the device was initialized with the extension\n   * given.\n   *\n   * \\param query The name of the extension to check.\n   */\n  bool HasExtension(const char* query) const;\n\n  //! \\brief Return the VulkanStream for the current CPU thread\n  VulkanStream& ThreadLocalStream();\n\n  //! \\brief Return the VulkanStream for the current CPU thread\n  const VulkanStream& ThreadLocalStream() const;\n\n  /*! \\brief Return the staging buffer for the current CPU thread\n   *\n   * This function may re-allocate the staging buffer depending on the\n   * size of the previously allocated buffer.\n   *\n   * \\param min_size The size in bytes of the staging buffer to be\n   * returned.  The buffer may be larger than requested, depending on\n   * previous use.\n   */\n  VulkanStagingBuffer& ThreadLocalStagingBuffer(size_t min_size);\n\n  /*! \\brief Allocate the uniform buffer for the current CPU thread\n   *\n   * \\param min_size The minimum size in bytes of the uniformn buffer\n   * to be allocated.  If a larger uniform buffer has already been\n   * allocated, no allocation is performed.\n   */\n  void AllocateThreadLocalUniformBuffer(size_t min_size);\n\n  /*! \\brief Return the uniform buffer for the current CPU thread\n   *\n   * Assumes that AllocateThreadLocalUniformBuffer has previously been\n   * called, with a min_size greater than or equal to the min_size of\n   * the current call.  If this is not the case, will throw an\n   * exception.\n   *\n   * \\param min_size The minimum size in bytes of the uniform buffer to be\n   * returned.\n   */\n  VulkanUniformBuffer& ThreadLocalUniformBuffer(size_t min_size);\n\n  // Cached device properties, queried through Vulkan API.\n  VulkanDeviceProperties device_properties{};\n\n  // Memory type index for staging.\n  uint32_t staging_mtype_index{0};\n  // whether staging is coherent\n  bool coherent_staging{false};\n\n  std::unique_ptr<VulkanDescriptorTemplateKHRFunctions> descriptor_template_khr_functions{nullptr};\n  std::unique_ptr<VulkanGetBufferMemoryRequirements2Functions>\n      get_buffer_memory_requirements_2_functions{nullptr};\n  std::unique_ptr<VulkanQueueInsertDebugUtilsLabelFunctions>\n      queue_insert_debug_utils_label_functions{nullptr};\n  // Memory type index for compute\n  uint32_t compute_mtype_index{0};\n\n  // queue family_index;\n  uint32_t queue_family_index{uint32_t(-1)};\n\n  bool UseImmediate() const { return descriptor_template_khr_functions != nullptr; }\n\n  bool UseDebugUtilsLabel() const { return queue_insert_debug_utils_label_functions != nullptr; }\n\n  VkQueue Queue() const { return queue; }\n\n private:\n  /*! \\brief Helper function for move assignment/construction\n   *\n   * Named \"do_swap\" instead of \"swap\" because otherwise cpplint.py\n   * thinks that it needs the <utility> header include.\n   */\n  void do_swap(VulkanDevice&& other);\n\n  /*! \\brief Returns a queue family capable of running Vulkan compute\n   * operations\n   */\n  uint32_t SelectComputeQueueFamily() const;\n\n  /*! \\brief Returns the extensions to be enabled.\n   *\n   * All char* in the returned vector point to static memory\n   * allocations, and do not require cleanup.\n   */\n  std::vector<const char*> SelectEnabledExtensions() const;\n\n  /*! \\brief Initialize the VkDevice\n   *\n   * Called during VulkanDevice construction.  Assumes that\n   * queue_family_index, device_properties, and enabled_extensions\n   * have been set.\n   */\n  void CreateVkDevice(const VulkanInstance& instance);\n\n  //! \\brief Handle to the Vulkan API physical device\n  VkPhysicalDevice physical_device_{nullptr};\n\n  /*! \\brief Extensions enabled for this device\n   *\n   * Based on supported extensions queried from physical_device_ prior\n   * to creating device_.  Contains only statically allocated string\n   * literals, no cleanup required.\n   */\n  std::vector<const char*> enabled_extensions;\n\n  //! \\brief Handle to the Vulkan API logical device\n  VkDevice device_{nullptr};\n\n  //! \\brief Mutex to protect access to queue\n  mutable std::mutex queue_mutex;\n\n  /*! \\brief Handle to Vulkan API VkQueue.\n   *\n   * Work can be executed by submitted to this queue using\n   * VulkanDevice::QueueSubmit.\n   */\n  VkQueue queue{nullptr};\n\n  /*! \\brief The VulkanStream for each CPU thread.\n   *\n   * To mimic the semantics of cudaSetDevice and cuLaunchKernel, each\n   * CPU thread must have a separate stream of execution.  The\n   * ThreadMap is declared mutable so that the streams can be lazily\n   * generated.\n   */\n  mutable ThreadMap<VulkanStream> stream_per_thread;\n\n  //! \\brief The VulkanStagingBuffer for each CPU thread.\n  ThreadMap<VulkanStagingBuffer> staging_buffer_per_thread;\n\n  //! \\brief The VulkanUniformBuffer for each CPU thread.\n  ThreadMap<VulkanUniformBuffer> uniform_buffer_per_thread;\n};\n\nuint32_t FindMemoryType(const VulkanDevice& device, VkBufferCreateInfo info,\n                        VkMemoryPropertyFlags req_prop);\n\nVkBufferCreateInfo MakeBufferCreateInfo(size_t nbytes, VkBufferUsageFlags usage);\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_device_api.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_\n\n#include <tvm/runtime/device_api.h>\n#include <vulkan/vulkan_core.h>\n\n#include <string>\n#include <vector>\n\n#include \"../thread_map.h\"\n#include \"../workspace_pool.h\"\n#include \"vulkan/vulkan_core.h\"\n#include \"vulkan_device.h\"\n#include \"vulkan_instance.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanDeviceAPI final : public DeviceAPI {\n public:\n  static VulkanDeviceAPI* Global();\n  VulkanDeviceAPI();\n  ~VulkanDeviceAPI();\n\n  // Implement active device\n  void SetDevice(Device dev) final;\n  void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;\n\n  // Implement memory management required by DeviceAPI\n  void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;\n  void FreeDataSpace(Device dev, void* ptr) final;\n  void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;\n  void FreeWorkspace(Device dev, void* data) final;\n\n  // Current vulkan implementation has one \"stream\" per CPU thread,\n  // with all commands writing into a single command buffer that is\n  // submitted on a call to StreamSync.  Therefore, for now, these are\n  // mostly no-ops.  If needed in the future, could have multiple\n  // command buffers to act as multiple streams.\n  TVMStreamHandle CreateStream(Device dev) final;\n  void FreeStream(Device dev, TVMStreamHandle stream) final;\n  void SyncStreamFromTo(Device dev, TVMStreamHandle event_src, TVMStreamHandle event_dst) final;\n  void StreamSync(Device dev, TVMStreamHandle stream) final;\n  void SetStream(Device dev, TVMStreamHandle stream) final;\n\n protected:\n  void CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size,\n                      Device dev_from, Device dev_to, DLDataType type_hint,\n                      TVMStreamHandle stream) final;\n\n  // End of required methods for the DeviceAPI interface\n\n public:\n  /*! \\brief Return the currently active VulkanDevice\n   *\n   * The active device can be set using VulkanDeviceAPI::SetDevice.\n   * Each CPU thread has its own active device, mimicking the\n   * semantics of cudaSetDevice.\n   */\n  VulkanDevice& GetActiveDevice();\n\n  /*! \\brief Return the currently active VulkanDevice\n   *\n   * The active device can be set using VulkanDeviceAPI::SetDevice.\n   * Each CPU thread has its own active device, mimicking the\n   * semantics of cudaSetDevice.\n   */\n  int GetActiveDeviceID();\n\n  /*! \\brief Return the VulkanDevice associated with a specific device_id\n   *\n   * These are constructed during VulkanDeviceAPI initialization, so\n   * this function returns immediately.\n   */\n  const VulkanDevice& device(size_t device_id) const;\n\n  /*! \\brief Return the VulkanDevice associated with a specific device_id\n   *\n   * These are constructed during VulkanDeviceAPI initialization, so\n   * this function returns immediately.\n   */\n  VulkanDevice& device(size_t device_id);\n\n  /*! \\brief Returns a property to be stored in a target.\n   *\n   * Returns the results of feature/property queries done during the\n   * device initialization.\n   */\n  void GetTargetProperty(Device dev, const std::string& property, TVMRetValue* rv) final;\n\n private:\n  std::vector<uint32_t> GetComputeQueueFamilies(VkPhysicalDevice phy_dev);\n\n  /*! \\brief The Vulkan API instance owned by the VulkanDeviceAPI\n   *\n   * Holds and manages VkInstance.\n   */\n  VulkanInstance instance_;\n\n  /*! \\brief Handles to the Vulkan devices\n   *\n   * The physical devices.  These are constructed after the instance_,\n   * and must be destructed before the instance_.\n   */\n  std::vector<VulkanDevice> devices_;\n\n  /*! \\brief One pool of device memory for each CPU thread.\n   *\n   * These allocate memory based on the devices stored in devices_.\n   * The memory pools must be destructed before devices_.\n   */\n  ThreadMap<WorkspacePool> pool_per_thread;\n\n  /*! \\brief The index of the active device for each CPU thread.\n   *\n   * To mimic the semantics of cudaSetDevice, each CPU thread can set\n   * the device on which functions should run.  If unset, the active\n   * device defaults to device_id == 0.\n   */\n  ThreadMap<int> active_device_id_per_thread;\n};\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_instance.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_\n\n#include <vector>\n\n#include \"vulkan/vulkan_core.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanInstance {\n public:\n  VulkanInstance();\n  ~VulkanInstance();\n\n  // Allow move assignment/construction\n  VulkanInstance(VulkanInstance&&);\n  VulkanInstance& operator=(VulkanInstance&&);\n\n  // Forbid copy assignment/construction\n  VulkanInstance(const VulkanInstance&) = delete;\n  VulkanInstance& operator=(const VulkanInstance&) = delete;\n\n  /*! \\brief Expose the internal VkInstance\n   *\n   * Allows the managed class to be passed to Vulkan APIs as if it\n   * were the VkInstance handler itself.\n   */\n  operator VkInstance() const { return instance_; }\n\n  /*! \\brief Checks if the device has an extension enabled\n   *\n   * Returns true if the device was initialized with the extension\n   * given.\n   *\n   * \\param query The name of the extension to check.\n   */\n  bool HasExtension(const char* query) const;\n\n  /*! \\brief Return all accessible physical devices\n   *\n   * Wrapper around vkEnumeratePhysicalDevices.\n   */\n  std::vector<VkPhysicalDevice> GetPhysicalDevices() const;\n\n private:\n  /*! \\brief Helper function for move assignment/construction\n   *\n   * Named \"do_swap\" instead of \"swap\" because otherwise cpplint.py\n   * thinks that it needs the <utility> header include.\n   */\n  void do_swap(VulkanInstance&& other);\n\n  /*! \\brief Extensions enabled for this instance\n   *\n   * Based on supported extensions queried through\n   * vkEnumerateInstanceExtensionProperties, prior to creating\n   * instance_.  Contains only statically allocated string literals,\n   * no cleanup required.\n   */\n  std::vector<const char*> enabled_extensions_;\n\n  //! \\brief The Vulkan API instance handle\n  VkInstance instance_{nullptr};\n};\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_\n\n#include <string>\n#include <unordered_map>\n\n#include \"../meta_data.h\"\n#include \"vulkan_shader.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\nModule VulkanModuleCreate(std::unordered_map<std::string, VulkanShader> smap,\n                          std::unordered_map<std::string, FunctionInfo> fmap, std::string source);\n\n}  // namespace vulkan\n\nusing vulkan::VulkanModuleCreate;\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_shader.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/packed_func.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nstruct VulkanShader {\n  /*! \\brief header flag */\n  uint32_t flag{0};\n  /*! \\brief Data segment */\n  std::vector<uint32_t> data;\n\n  void Save(dmlc::Stream* writer) const {\n    writer->Write(flag);\n    writer->Write(data);\n  }\n  bool Load(dmlc::Stream* reader) {\n    if (!reader->Read(&flag)) return false;\n    if (!reader->Read(&data)) return false;\n    return true;\n  }\n};\n\n}  // namespace vulkan\n\nusing vulkan::VulkanShader;\n}  // namespace runtime\n}  // namespace tvm\n\nnamespace dmlc {\nDMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::vulkan::VulkanShader, true);\n}  // namespace dmlc\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_stream.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_\n\n#include <functional>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\n#include \"vulkan_amdrgp.h\"\n#include \"vulkan_common.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nclass VulkanDevice;\n\nclass VulkanStreamState {\n public:\n  VkCommandBuffer cmd_buffer_;\n  VkFence fence_;\n};\n\n// Used to identify state that should only be used once-per-stream.\nstruct VulkanStreamToken {\n  VkDescriptorSet descriptor_set_{VK_NULL_HANDLE};\n  std::vector<VkBuffer> buffers_;\n};\n\n/*!\n *  \\brief Wrapper around a vulkan command buffer\n *\n *  The VulkanStream collects commands into a VkCommandBuffer.  When a\n *  newly submitted command requires resources reserved by an\n *  already-submitted command, all of the queued commands are\n *  submitted to the GPU, and the CPU waits for all queued commands to\n *  finish.  The queued commands can also be explicitly pushed/waited\n *  on by calling VulkanStream::Synchronize.\n *\n *  Currently, there exists one VulkanStream for each GPU device, for\n *  each CPU thread.  Each time a VulkanWrappedFunc is called, it is\n *  submitted to the VulkanStream associated with the submitting CPU\n *  thread, and associated the thread-specific active device set by\n *  `DeviceAPI::SetDevice`.\n */\nclass VulkanStream {\n public:\n  explicit VulkanStream(const VulkanDevice* device);\n\n  ~VulkanStream();\n\n  /*! \\brief Push the kernel onto the stream's command buffer.\n   *\n   * If device.UseImmediate() is true, the kernel is executed\n   * immediately to update the command buffer.  Otherwise, it is added\n   * to the list of deferred updates to be pushed onto the command\n   * buffer.\n   *\n   * Assumes that there are no descriptor sets or buffers accessed by this kernel.\n   *\n   */\n  void Launch(const std::function<void(VulkanStreamState*)>& kernel);\n\n  /*! \\brief Push the kernel onto the stream's command buffer.\n   *\n   * Can only be called if device.UseImmediate() is false.  The\n   * kernel is delayed, and isn't pushed to the command buffer until\n   * all kernels are collected.\n   *\n   * \\param deferred_initializer Updates the descriptor set.  Only\n   * called if the deferred_token has differences from\n   *\n   * \\param deferred_kernel Submits updates to the command buffer.\n   *\n   * \\param deferred_token Indicates which descriptor set and buffers\n   * are accessed by this kernel.  No two kernels in the command\n   * buffer can use the same descriptor set.\n   *\n   */\n  void LaunchDeferred(const std::function<void()>& deferred_initializer,\n                      const std::function<void(VulkanStreamState*)>& deferred_kernel,\n                      const VulkanStreamToken& deferred_token);\n\n  // reset profiler state\n  void ProfilerReset() {\n    if (profiler_) {\n      profiler_->reset();\n    }\n  }\n\n  // set profiler to READY state after reset\n  void ProfilerReady() {\n    if (profiler_) {\n      profiler_->ready();\n    }\n  }\n\n  // Synchronize the current stream `state_` with respect to the host.\n  void Synchronize();\n\n private:\n  const VulkanDevice* device_;\n  std::unique_ptr<VulkanStreamState> state_;\n  // An index of deferred tokens, allowing us to efficiently detect duplicated\n  // deferred_initializer blocks.\n  std::unordered_map<VkDescriptorSet, std::vector<VulkanStreamToken>> deferred_tokens_;\n  std::vector<std::function<void(VulkanStreamState*)>> deferred_kernels_;\n  VkCommandPool cmd_pool_;\n  VulkanStreamProfiler* profiler_ = nullptr;\n};\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/vulkan/vulkan_wrapped_func.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_\n#define TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_\n\n#include <array>\n#include <memory>\n#include <mutex>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../meta_data.h\"\n#include \"../pack_args.h\"\n#include \"../thread_storage_scope.h\"\n#include \"vulkan/vulkan_core.h\"\n#include \"vulkan_common.h\"\n#include \"vulkan_device.h\"\n#include \"vulkan_shader.h\"\n\nnamespace tvm {\nnamespace runtime {\nnamespace vulkan {\n\nstruct VulkanPipeline {\n  VulkanDevice* device{nullptr};\n  VkShaderModule shader{VK_NULL_HANDLE};\n  VkDescriptorSetLayout descriptor_set_layout{VK_NULL_HANDLE};\n  VkDescriptorPool descriptor_pool{VK_NULL_HANDLE};\n  VkDescriptorSet descriptor_set{VK_NULL_HANDLE};\n  VkPipelineLayout pipeline_layout{VK_NULL_HANDLE};\n  VkPipeline pipeline{VK_NULL_HANDLE};\n  VkDescriptorUpdateTemplateKHR descriptor_update_template{VK_NULL_HANDLE};\n  bool use_ubo{false};\n};\n\nclass VulkanModuleNode;\n\n// a wrapped function class to get packed func.\nclass VulkanWrappedFunc {\n public:\n  void Init(VulkanModuleNode* m, ObjectPtr<Object> sptr, const std::string& func_name,\n            size_t num_buffer_args, size_t num_pack_args,\n            const std::vector<std::string>& launch_param_tags);\n\n  void operator()(TVMArgs args, TVMRetValue* rv, const ArgUnion64* pack_args) const;\n\n private:\n  // internal module\n  VulkanModuleNode* m_;\n  // the resource holder\n  ObjectPtr<Object> sptr_;\n  // v The name of the function.\n  std::string func_name_;\n  // Number of buffer arguments\n  size_t num_buffer_args_;\n  // number of packed arguments.\n  size_t num_pack_args_;\n  // launch parameters configuration\n  LaunchParamConfig launch_param_config_;\n  // Device state cache per device.\n  // mark as mutable, to enable lazy initialization\n  mutable std::array<std::shared_ptr<VulkanPipeline>, kVulkanMaxNumDevice> scache_;\n};\n\nclass VulkanModuleNode final : public runtime::ModuleNode {\n public:\n  explicit VulkanModuleNode(std::unordered_map<std::string, VulkanShader> smap,\n                            std::unordered_map<std::string, FunctionInfo> fmap, std::string source)\n      : smap_(smap), fmap_(fmap), source_(source) {}\n  ~VulkanModuleNode();\n\n  const char* type_key() const final { return \"vulkan\"; }\n\n  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;\n\n  std::shared_ptr<VulkanPipeline> GetPipeline(size_t device_id, const std::string& func_name,\n                                              size_t num_pack_args);\n\n  void SaveToFile(const std::string& file_name, const std::string& format) final;\n\n  void SaveToBinary(dmlc::Stream* stream) final;\n  std::string GetSource(const std::string& format) final;\n\n private:\n  // function information table.\n  std::unordered_map<std::string, VulkanShader> smap_;\n  // function information table.\n  std::unordered_map<std::string, FunctionInfo> fmap_;\n  // The format\n  std::string fmt_{\"vulkan\"};\n  // The source\n  std::string source_;\n\n  // Guards accesses to `ecache_`\n  std::mutex mutex_;\n  std::array<std::unordered_map<std::string, std::shared_ptr<VulkanPipeline>>, kVulkanMaxNumDevice>\n      ecache_;\n};\n\n}  // namespace vulkan\n}  // namespace runtime\n}  // namespace tvm\n\n#endif  // TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/runtime/workspace_pool.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file workspace_pool.h\n * \\brief Workspace pool utility.\n */\n#ifndef TVM_RUNTIME_WORKSPACE_POOL_H_\n#define TVM_RUNTIME_WORKSPACE_POOL_H_\n\n#include <tvm/runtime/device_api.h>\n\n#include <memory>\n#include <vector>\n\nnamespace tvm {\nnamespace runtime {\n/*!\n * \\brief A workspace pool to manage\n *\n *  \\note We have the following assumption about backend temporal\n *   workspace allocation, and will optimize for such assumption,\n *   some of these assumptions can be enforced by the compiler.\n *\n *  - Only a few allocation will happen, and space will be released after use.\n *  - The release order is usually in reverse order of allocate\n *  - Repeative pattern of same allocations over different runs.\n */\nclass TVM_DLL WorkspacePool {\n public:\n  /*!\n   * \\brief Create pool with specific device type and device.\n   * \\param device_type The device type.\n   * \\param device_api The device API.\n   */\n  WorkspacePool(DLDeviceType device_type, DeviceAPI* device_api);\n  /*! \\brief destructor */\n  ~WorkspacePool();\n  /*!\n   * \\brief Allocate temporal workspace.\n   * \\param dev The device of allocation.\n   * \\param size The size to be allocated.\n   */\n  void* AllocWorkspace(Device dev, size_t size);\n  /*!\n   * \\brief Free temporal workspace in backend execution.\n   *\n   * \\param dev The device of allocation.\n   * \\param ptr The pointer to be freed.\n   */\n  void FreeWorkspace(Device dev, void* ptr);\n\n private:\n  class Pool;\n  /*! \\brief pool of device local array */\n  std::vector<Pool*> array_;\n  /*! \\brief device type this pool support */\n  DLDeviceType device_type_;\n  /*! \\brief The device API */\n  DeviceAPI* device_;\n};\n\n}  // namespace runtime\n}  // namespace tvm\n#endif  // TVM_RUNTIME_WORKSPACE_POOL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/script/ir_builder/tir/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_\n#define TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_\n\n#include <tvm/script/ir_builder/tir/frame.h>\n#include <tvm/script/ir_builder/tir/ir.h>\n#include <tvm/tir/stmt.h>\n\nnamespace tvm {\nnamespace script {\nnamespace ir_builder {\nnamespace tir {\n\n/*!\n * \\brief Add tir Stmt to the top frame in IRBuilder frame stack.\n * \\param stmt The Stmt.\n */\ninline void AddToParent(tvm::tir::Stmt stmt) {\n  IRBuilder builder = IRBuilder::Current();\n  if (builder->frames.empty()) {\n    ICHECK(!builder->result.defined()) << \"ValueError: Builder.result has already been set\";\n    builder->result = stmt;\n  } else if (const auto* tir_frame = builder->frames.back().as<TIRFrameNode>()) {\n    GetRef<TIRFrame>(tir_frame)->stmts.push_back(stmt);\n  } else {\n    LOG(FATAL) << \"TypeError: Unsupported frame type: \" << builder->frames.back();\n  }\n}\n\n/*!\n * \\brief Convert array of tir Stmt to single Stmt.\n * \\param stmt The array of Stmt.\n * \\return The SeqStmt.\n */\ninline tvm::tir::Stmt AsStmt(const Array<tvm::tir::Stmt>& stmt) {\n  using namespace tvm::tir;\n  if (stmt.empty()) {\n    return tvm::tir::Evaluate(0);\n  } else if (stmt.size() == 1) {\n    return stmt[0];\n  } else {\n    return SeqStmt(stmt);\n  }\n}\n\n/*!\n * \\brief Check whether the top frame in IRBuilder frame stack is PrimFuncFrame.\n * \\param method The method name to be printed when throwing exception.\n * \\return The top frame of PrimFuncFrame.\n */\ninline PrimFuncFrame FindPrimFuncFrame(const String& method) {\n  if (Optional<PrimFuncFrame> frame = IRBuilder::Current()->GetLastFrame<PrimFuncFrame>()) {\n    return frame.value();\n  }\n  LOG(FATAL) << \"ValueError: PrimFunc frame not find. Please ensure '\" << method\n             << \"' is called under T.prim_func()\";\n  throw;\n}\n\n/*!\n * \\brief Check whether the top frame in IRBuilder frame stack is BlockFrame.\n * \\param method The method name to be printed when throwing exception.\n * \\return The top frame of BlockFrame.\n */\ninline BlockFrame FindBlockFrame(const String& method) {\n  if (Optional<BlockFrame> frame = IRBuilder::Current()->GetLastFrame<BlockFrame>()) {\n    return frame.value();\n  }\n  LOG(FATAL) << \"ValueError: Block frame not find. Please ensure '\" << method\n             << \"' is called under T.block()\";\n  throw;\n}\n\n/*!\n * \\brief Check whether the top frame in IRBuilder frame stack is IfFrame.\n * \\param method The method name to be printed when throwing exception.\n * \\return The top frame of IfFrame.\n */\ninline IfFrame FindIfFrame(const String& method) {\n  if (Optional<IfFrame> frame = IRBuilder::Current()->GetLastFrame<IfFrame>()) {\n    return frame.value();\n  } else {\n    LOG(FATAL) << \"ValueError: IfThenElse frame not find. Please ensure '\" << method\n               << \"' is called under T.if_()\";\n  }\n  throw;\n}\n\n/*!\n * \\brief Convert BufferLoad to BufferRegion.\n * \\param buffer_load The BufferLoad.\n * \\return The converted BufferRegion.\n */\ninline tvm::tir::BufferRegion BufferRegionFromLoad(tvm::tir::BufferLoad buffer_load) {\n  Array<Range> ranges;\n  for (const PrimExpr& index : buffer_load->indices) {\n    ranges.push_back(Range::FromMinExtent(index, IntImm(index->dtype, 1)));\n  }\n  return tvm::tir::BufferRegion(buffer_load->buffer, ranges);\n}\n\n}  // namespace tir\n}  // namespace ir_builder\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/script/printer/base_doc_printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_\n#define TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_\n\n#include <tvm/script/printer/doc.h>\n#include <tvm/script/printer/doc_printer.h>\n\n#include <limits>\n#include <memory>\n#include <ostream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\n/*! \\brief Range of byte offsets in a string */\nusing ByteSpan = std::pair<size_t, size_t>;\n\n/*! \\brief Options to customize DocPrinter's output */\nstruct DocPrinterOptions {\n  /*! \\brief Number of spaces for one level of indentation */\n  int indent_spaces = 4;\n\n  /*! \\brief Whether to print the line numbers */\n  bool print_line_numbers = false;\n\n  /*!\n   * \\brief Number of context lines to print around the underlined text.\n   *\n   * If set to a non-default value `n`, only print `n` context lines before and after\n   * the underlined pieces of text.\n   */\n  size_t num_context_lines = std::numeric_limits<size_t>::max();\n};\n\n/*!\n * \\brief DocPrinter is responsible for printing Doc tree into text format\n * \\details This is the base class for translating Doc into string.\n *          Each target language needs to have its subclass of DocPrinter\n *          to define the actual logic of printing Doc.\n *\n * \\sa Doc\n */\nclass DocPrinter {\n public:\n  /*!\n   * \\brief The constructor of DocPrinter\n   *\n   * \\param options the option for printer\n   */\n  explicit DocPrinter(const DocPrinterOptions& options);\n  virtual ~DocPrinter() = default;\n\n  /*!\n   * \\brief Append a doc into the final content\n   *\n   * \\param doc the Doc to be printed\n   *\n   * \\sa GetString\n   */\n  void Append(const Doc& doc);\n\n  /*!\n   * \\brief Append a doc to the final content\n   *\n   * \\param doc  Doc to be printed\n   * \\param path_to_underline  Object path to be underlined\n   *\n   * \\sa GetString\n   */\n  void Append(const Doc& doc, Optional<ObjectPath> path_to_underline);\n\n  /*!\n   * \\brief Get the printed string of all Doc appended\n   *\n   * The content of each Doc in the returned string will\n   * appear in the same order as they are appended.\n   *\n   * \\sa Append\n   */\n  String GetString() const;\n\n protected:\n  /*!\n   * \\brief Get the printed string\n   *\n   * It will dispatch to the PrintTypedDoc method based on\n   * the actual type of Doc.\n   *\n   * \\sa PrintTypedDoc\n   */\n  void PrintDoc(const Doc& doc);\n\n  /*!\n   * \\brief Virtual method to print a LiteralDoc\n   */\n  virtual void PrintTypedDoc(const LiteralDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an IdDoc\n   */\n  virtual void PrintTypedDoc(const IdDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an AttrAccessDoc\n   */\n  virtual void PrintTypedDoc(const AttrAccessDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an IndexDoc\n   */\n  virtual void PrintTypedDoc(const IndexDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an OperationDoc\n   */\n  virtual void PrintTypedDoc(const OperationDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a CallDoc\n   */\n  virtual void PrintTypedDoc(const CallDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a LambdaDoc\n   */\n  virtual void PrintTypedDoc(const LambdaDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a ListDoc\n   */\n  virtual void PrintTypedDoc(const ListDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a TupleDoc\n   */\n  virtual void PrintTypedDoc(const TupleDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a DictDoc\n   */\n  virtual void PrintTypedDoc(const DictDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a SliceDoc\n   */\n  virtual void PrintTypedDoc(const SliceDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a StmtBlockDoc\n   */\n  virtual void PrintTypedDoc(const StmtBlockDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an AssignDoc\n   */\n  virtual void PrintTypedDoc(const AssignDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an IfDoc\n   */\n  virtual void PrintTypedDoc(const IfDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a WhileDoc\n   */\n  virtual void PrintTypedDoc(const WhileDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a ForDoc\n   */\n  virtual void PrintTypedDoc(const ForDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a ScopeDoc\n   */\n  virtual void PrintTypedDoc(const ScopeDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an ExprStmtDoc\n   */\n  virtual void PrintTypedDoc(const ExprStmtDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print an AssertDoc\n   */\n  virtual void PrintTypedDoc(const AssertDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a ReturnDoc\n   */\n  virtual void PrintTypedDoc(const ReturnDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a FunctionDoc\n   */\n  virtual void PrintTypedDoc(const FunctionDoc& doc) = 0;\n\n  /*!\n   * \\brief Virtual method to print a ClassDoc\n   */\n  virtual void PrintTypedDoc(const ClassDoc& doc) = 0;\n\n  /*!\n   * \\brief Increase the indent level of any content to be\n   *        printed after this call\n   */\n  void IncreaseIndent() { indent_ += options_.indent_spaces; }\n\n  /*!\n   * \\brief Decrease the indent level of any content to be\n   *        printed after this call\n   */\n  void DecreaseIndent() { indent_ -= options_.indent_spaces; }\n\n  /*!\n   * \\brief Add a new line into the output stream\n   *\n   * \\sa output_\n   */\n  std::ostream& NewLine() {\n    output_ << \"\\n\";\n    line_starts_.push_back(output_.tellp());\n    output_ << std::string(indent_, ' ');\n    return output_;\n  }\n\n  /*!\n   * \\brief The output stream of printer\n   *\n   * All printed content will be stored in this stream and returned\n   * when GetString is called.\n   *\n   * \\sa GetString\n   */\n  std::ostringstream output_;\n\n private:\n  void MarkSpan(const ByteSpan& span, const ObjectPath& path);\n\n  /*! \\brief Options to customize certain aspects of the output */\n  DocPrinterOptions options_;\n\n  /*! \\brief the current level of indent */\n  int indent_ = 0;\n\n  /*! \\brief For each line in the output_, byte offset of its first character */\n  std::vector<size_t> line_starts_;\n\n  /*! \\brief Path of the object that we would like to underline */\n  Optional<ObjectPath> path_to_underline_;\n\n  /*!\n   * \\brief Candidate spans to be underlined, until we find a better match.\n   * (A better match is an object with a longer path that is still a prefix of path_to_underline_.)\n   */\n  std::vector<ByteSpan> current_underline_candidates_;\n\n  /*! \\brief Path length of the objects that are current candidates for underlining. */\n  int current_max_path_length_;\n\n  /*! \\brief Spans that we have already committed to underline. */\n  std::vector<ByteSpan> underlines_;\n};\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/script/printer/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SCRIPT_PRINTER_UTILS_H_\n#define TVM_SCRIPT_PRINTER_UTILS_H_\n\n#include <tvm/script/printer/doc.h>\n#include <tvm/script/printer/ir_docsifier.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace script {\nnamespace printer {\n\ntemplate <typename DocType, typename NodeType>\nArray<DocType> AsDocArray(const TracedArray<NodeType>& refs, const IRDocsifier& ir_docsifier) {\n  Array<DocType> result;\n  for (auto ref : refs) {\n    result.push_back(ir_docsifier->AsExprDoc(ref));\n  }\n  return result;\n}\n\ntemplate <typename DocType, typename NodeType>\nArray<DocType> AsDocArray(std::initializer_list<NodeType>&& refs, const IRDocsifier& ir_docsifier) {\n  Array<DocType> result;\n  for (auto& ref : refs) {\n    result.push_back(ir_docsifier->AsExprDoc(ref));\n  }\n  return result;\n}\n\ntemplate <typename RefType>\nArray<ExprDoc> AsExprDocArray(const TracedArray<RefType>& refs, const IRDocsifier& ir_docsifier) {\n  return AsDocArray<ExprDoc>(refs, ir_docsifier);\n}\n\ntemplate <typename RefType>\nArray<ExprDoc> AsExprDocArray(std::initializer_list<RefType>&& refs,\n                              const IRDocsifier& ir_docsifier) {\n  return AsDocArray<ExprDoc>(std::move(refs), ir_docsifier);\n}\n\ninline DictDoc AsDictDoc(const TracedMap<String, ObjectRef>& dict,\n                         const IRDocsifier& ir_docsifier) {\n  Array<ExprDoc> keys;\n  Array<ExprDoc> values;\n\n  for (auto p : dict) {\n    keys.push_back(LiteralDoc::Str(p.first));\n    values.push_back(ir_docsifier->AsExprDoc(p.second));\n  }\n\n  auto doc = DictDoc(keys, values);\n  doc->source_paths.push_back(dict.GetPath());\n  return doc;\n}\n\ntemplate <typename T>\ninline ListDoc AsListDoc(const TracedArray<T>& arr, const IRDocsifier& ir_docsifier) {\n  auto ret = ListDoc(AsExprDocArray(arr, ir_docsifier));\n  ret->source_paths.push_back(arr.GetPath());\n  return ret;\n}\n\ntemplate <typename T>\ninline TupleDoc AsTupleDoc(const TracedArray<T>& arr, const IRDocsifier& ir_docsifier) {\n  auto ret = TupleDoc(AsExprDocArray(arr, ir_docsifier));\n  ret->source_paths.push_back(arr.GetPath());\n  return ret;\n}\n\n}  // namespace printer\n}  // namespace script\n}  // namespace tvm\n\n#endif  // TVM_SCRIPT_PRINTER_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/arena.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file arena.h\n * \\brief Arena allocator that allocates\n *  memory chunks and frees them all during destruction time.\n */\n#ifndef TVM_SUPPORT_ARENA_H_\n#define TVM_SUPPORT_ARENA_H_\n\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\n#include \"generic_arena.h\"\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief Simple page allocator that uses new and delete.\n */\nclass SimplePageAllocator {\n public:\n  /*!\n   * \\brief Allocate a new page.\n   * \\param min_size Minimum size of the page.\n   * \\return The allocated page.\n   * \\note This function can return a bigger page to meet the min_size requirement.\n   */\n  ArenaPageHeader* allocate(size_t min_size) {\n    size_t npages = ((min_size + kPageSize - 1) / kPageSize);\n    ArenaPageHeader* header = reinterpret_cast<ArenaPageHeader*>(new Page[npages]);\n    header->size = npages * kPageSize;\n    header->offset = sizeof(ArenaPageHeader);\n    return header;\n  }\n  /*!\n   * \\brief De-allocate an allocate page.\n   * \\param page The page to be de-allocated.\n   */\n  void deallocate(ArenaPageHeader* page) { delete[] reinterpret_cast<Page*>(page); }\n\n  static const constexpr int kPageSize = 16 << 10;\n  static const constexpr int kPageAlign = 1024;\n\n private:\n  // page size 16 KB\n  // The page data type;\n  using Page = std::aligned_storage<kPageSize, kPageAlign>::type;\n};\n\nusing Arena = GenericArena<SimplePageAllocator>;\n\n/*!\n * \\brief Link list node\n * \\tparam T the content data type\n */\ntemplate <typename T>\nstruct LinkNode {\n  /*! \\brief The content value */\n  T value;\n  /*! \\brief pointer to the next location */\n  LinkNode<T>* next{nullptr};\n};\n/*!\n * \\brief LinkedList structure\n * \\tparam T the content data type\n * \\note This is a simple data structure that can be used together with the arena.\n * \\sa LinkNode\n */\ntemplate <typename T>\nstruct LinkedList {\n  /*! \\brief Head pointer */\n  LinkNode<T>* head{nullptr};\n  /*! \\brief Tail pointer */\n  LinkNode<T>* tail{nullptr};\n  /*!\n   * \\brief Push a new node to the end of the linked list.\n   * \\param node The node to be pushed.\n   */\n  void Push(LinkNode<T>* node) {\n    node->next = nullptr;\n    if (this->tail != nullptr) {\n      this->tail->next = node;\n      this->tail = node;\n    } else {\n      head = tail = node;\n    }\n  }\n};\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_ARENA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/array.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SUPPORT_ARRAY_H_\n#define TVM_SUPPORT_ARRAY_H_\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief Checks if two arrays contain the same objects\n * \\tparam T The type of objects in the array\n * \\param a The first array\n * \\param b The second array\n * \\return A boolean indicating if they are the same\n */\ntemplate <class T>\ninline bool ArrayWithSameContent(const Array<T>& a, const Array<T>& b) {\n  if (a.size() != b.size()) {\n    return false;\n  }\n  int n = a.size();\n  for (int i = 0; i < n; ++i) {\n    if (!a[i].same_as(b[i])) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/*!\n * \\brief Checks if two arrays contain the same objects\n * \\tparam T The type of objects in the array\n * \\param a The first array\n * \\param b The second array\n * \\return A boolean indicating if they are the same\n */\ntemplate <class T>\ninline bool ArrayWithSameContent(const std::vector<T*>& a, const std::vector<T*>& b) {\n  if (a.size() != b.size()) {\n    return false;\n  }\n  int n = a.size();\n  for (int i = 0; i < n; ++i) {\n    if (a[i] != b[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/*!\n * \\brief Convert a tvm::runtime::Array to std::vector\n * \\tparam TSrc The type of elements in the source Array\n * \\tparam TDst The type of elements in the result vector\n * \\return The result vector\n */\ntemplate <class TSrc, class TDst>\ninline std::vector<TDst> AsVector(const Array<TSrc>& vec);\n\n/*!\n * \\brief Convert a std::vector to tvm::runtime::Array\n * \\tparam TSrc The type of elements in the source vector\n * \\tparam TDst The type of elements in the result Array\n * \\return The result vector\n */\ntemplate <class TSrc, class TDst>\ninline Array<TDst> AsArray(const std::vector<TSrc>& vec);\n\n/*!\n * \\brief Get the shape tuple as array\n * \\param shape The shape tuple\n * \\return An array of the shape tuple\n */\ninline Array<Integer> AsArray(const ShapeTuple& shape) {\n  Array<Integer> result;\n  result.reserve(shape->size);\n  for (ShapeTuple::index_type i : shape) {\n    result.push_back(Integer(i));\n  }\n  return result;\n}\n\n/*!\n * \\brief Concatenate a list of arrays into a single array\n * \\tparam T The type of elements in the arrays\n * \\tparam Iterator The type of the iterator into the list of arrays\n * \\param begin The begin iterator to the array list\n * \\param end The end iterator to the array list\n * \\return The concatenated array\n */\ntemplate <class T, class Iterator>\ninline Array<T> ConcatArrayList(Iterator begin, Iterator end) {\n  int size = 0;\n  for (Iterator it = begin; it != end; ++it) {\n    size += (*it).size();\n  }\n  Array<T> result;\n  result.reserve(size);\n  for (Iterator it = begin; it != end; ++it) {\n    const auto& item = *it;\n    result.insert(result.end(), item.begin(), item.end());\n  }\n  return result;\n}\n\n/********** Implementation details of AsVector<TSrc, TDst> **********/\n\nnamespace details {\n\ntemplate <class TSrc, class TDst>\nstruct AsVectorImpl {};\n\ntemplate <class TSrc>\nstruct AsVectorImpl<TSrc, TSrc> {\n  inline std::vector<TSrc> operator()(const Array<TSrc>& vec) const {\n    return std::vector<TSrc>(vec.begin(), vec.end());\n  }\n};\n\ntemplate <class TSrcObjectRef>\nstruct AsVectorImpl<TSrcObjectRef, int> {\n  inline std::vector<int> operator()(const Array<TSrcObjectRef>& vec) const {\n    std::vector<int> results;\n    for (const TSrcObjectRef& x : vec) {\n      const auto* n = x.template as<IntImmNode>();\n      ICHECK(n) << \"TypeError: Expects IntImm, but gets: \" << x->GetTypeKey();\n      results.push_back(n->value);\n    }\n    return results;\n  }\n};\n\ntemplate <class TSrcObjectRef>\nstruct AsVectorImpl<TSrcObjectRef, int64_t> {\n  inline std::vector<int64_t> operator()(const Array<TSrcObjectRef>& vec) const {\n    std::vector<int64_t> results;\n    for (const TSrcObjectRef& x : vec) {\n      const auto* n = x.template as<IntImmNode>();\n      ICHECK(n) << \"TypeError: Expects IntImm, but gets: \" << x->GetTypeKey();\n      results.push_back(n->value);\n    }\n    return results;\n  }\n};\n\ntemplate <class TSrcObjectRef>\nstruct AsVectorImpl<TSrcObjectRef, double> {\n  inline std::vector<double> operator()(const Array<TSrcObjectRef>& array) const {\n    std::vector<double> results;\n    for (const TSrcObjectRef& x : array) {\n      const auto* n = x.template as<FloatImmNode>();\n      ICHECK(n) << \"TypeError: Expects FloatImm, but gets: \" << x->GetTypeKey();\n      results.push_back(n->value);\n    }\n    return results;\n  }\n};\n}  // namespace details\n\n/********** Implementation details of AsArray<TSrc, TDst> **********/\n\nnamespace details {\n\ntemplate <class TSrc, class TDst>\nstruct AsArrayImpl {};\n\ntemplate <class TSrc>\nstruct AsArrayImpl<TSrc, TSrc> {\n  inline Array<TSrc> operator()(const std::vector<TSrc>& vec) const {\n    return Array<TSrc>(vec.begin(), vec.end());\n  }\n};\n\ntemplate <class TDstObjectRef>\nstruct AsArrayImpl<int, TDstObjectRef> {\n  inline Array<TDstObjectRef> operator()(const std::vector<int>& vec) const {\n    Array<TDstObjectRef> result;\n    result.reserve(vec.size());\n    for (int x : vec) {\n      result.push_back(Integer(x));\n    }\n    return result;\n  }\n};\n\ntemplate <class TDstObjectRef>\nstruct AsArrayImpl<int64_t, TDstObjectRef> {\n  inline Array<TDstObjectRef> operator()(const std::vector<int64_t>& vec) const {\n    Array<TDstObjectRef> result;\n    result.reserve(vec.size());\n    for (int64_t x : vec) {\n      result.push_back(Integer(x));\n    }\n    return result;\n  }\n};\n\ntemplate <class TDstObjectRef>\nstruct AsArrayImpl<double, TDstObjectRef> {\n  inline Array<TDstObjectRef> operator()(const std::vector<double>& vec) const {\n    Array<TDstObjectRef> result;\n    result.reserve(vec.size());\n    for (double x : vec) {\n      result.push_back(FloatImm(tvm::DataType::Float(64), x));\n    }\n    return result;\n  }\n};\n\n}  // namespace details\n\ntemplate <class TSrc, class TDst>\ninline std::vector<TDst> AsVector(const Array<TSrc>& vec) {\n  return details::AsVectorImpl<TSrc, TDst>()(vec);\n}\n\ntemplate <class TSrc, class TDst>\ninline Array<TDst> AsArray(const std::vector<TSrc>& vec) {\n  return details::AsArrayImpl<TSrc, TDst>()(vec);\n}\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_ARRAY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/base64.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file base64.h\n * \\brief data stream support to input and output from/to base64 stream\n *   base64 is easier to store and pass as text format in mapreduce\n */\n#ifndef TVM_SUPPORT_BASE64_H_\n#define TVM_SUPPORT_BASE64_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <cctype>\n#include <cstdio>\n#include <string>\n\nnamespace tvm {\nnamespace support {\n/*! \\brief namespace of base64 decoding and encoding table */\nnamespace base64 {\n// decoding table\nconst char DecodeTable[] = {\n    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,\n    62,  // '+'\n    0,  0,  0,\n    63,                                      // '/'\n    52, 53, 54, 55, 56, 57, 58, 59, 60, 61,  // '0'-'9'\n    0,  0,  0,  0,  0,  0,  0,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14,\n    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,  // 'A'-'Z'\n    0,  0,  0,  0,  0,  0,  26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,\n    42, 43, 44, 45, 46, 47, 48, 49, 50, 51,  // 'a'-'z'\n};\n// encoding table\nstatic const char EncodeTable[] =\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}  // namespace base64\n\n/*!\n * \\brief Buffer reader from stream to avoid\n *  virtual call overhead on each read.\n */\nclass StreamBufferReader {\n public:\n  explicit StreamBufferReader(size_t buffer_size) { buffer_.resize(buffer_size); }\n  /*!\n   * \\brief set input stream\n   * \\param stream The stream to be set\n   */\n  void set_stream(dmlc::Stream* stream) {\n    stream_ = stream;\n    read_len_ = read_ptr_ = 1;\n  }\n  /*!\n   * \\return allows quick read using get char\n   */\n  int GetChar() {\n    while (true) {\n      if (read_ptr_ < read_len_) {\n        return static_cast<int>(buffer_[read_ptr_++]);\n      } else {\n        read_len_ = stream_->Read(&buffer_[0], buffer_.length());\n        if (read_len_ == 0) return EOF;\n        read_ptr_ = 0;\n      }\n    }\n  }\n  /*! \\return whether we are reaching the end of file */\n  bool AtEnd() const { return read_len_ == 0; }\n\n private:\n  /*! \\brief the underlying stream */\n  dmlc::Stream* stream_{nullptr};\n  /*! \\brief buffer to hold data */\n  std::string buffer_;\n  /*! \\brief length of valid data in buffer */\n  size_t read_len_{1};\n  /*! \\brief pointer in the buffer */\n  size_t read_ptr_{1};\n};\n\n/*!\n * \\brief Input stream from base64 encoding\n */\nclass Base64InStream : public dmlc::Stream {\n public:\n  explicit Base64InStream(dmlc::Stream* fs) : reader_(256) { reader_.set_stream(fs); }\n  /*!\n   * \\brief initialize the stream position to beginning of next base64 stream\n   * \\note call this function before actually start read\n   */\n  void InitPosition(void) {\n    // get a character\n    do {\n      temp_ch_ = reader_.GetChar();\n    } while (isspace(temp_ch_));\n  }\n  /*! \\brief whether current position is end of a base64 stream */\n  bool IsEOF(void) const { return num_prev_ == 0 && (temp_ch_ == EOF || isspace(temp_ch_)); }\n  // override read function.\n  virtual size_t Read(void* ptr, size_t size) {\n    using base64::DecodeTable;\n    if (size == 0) return 0;\n    // use tlen to record left size\n    size_t tlen = size;\n    unsigned char* cptr = static_cast<unsigned char*>(ptr);\n    // if anything left, load from previous buffered result\n    if (num_prev_ != 0) {\n      if (num_prev_ == 2) {\n        if (tlen >= 2) {\n          *cptr++ = buf_prev[0];\n          *cptr++ = buf_prev[1];\n          tlen -= 2;\n          num_prev_ = 0;\n        } else {\n          // assert tlen == 1\n          *cptr++ = buf_prev[0];\n          --tlen;\n          buf_prev[0] = buf_prev[1];\n          num_prev_ = 1;\n        }\n      } else {\n        // assert num_prev_ == 1\n        *cptr++ = buf_prev[0];\n        --tlen;\n        num_prev_ = 0;\n      }\n    }\n    if (tlen == 0) return size;\n    int nvalue;\n    // note: everything goes with 4 bytes in Base64\n    // so we process 4 bytes a unit\n    while (tlen && temp_ch_ != EOF && !isspace(temp_ch_)) {\n      // first byte\n      nvalue = DecodeTable[temp_ch_] << 18;\n      {\n        // second byte\n        temp_ch_ = reader_.GetChar();\n        ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << \"invalid base64 format\";\n        nvalue |= DecodeTable[temp_ch_] << 12;\n        *cptr++ = (nvalue >> 16) & 0xFF;\n        --tlen;\n      }\n      {\n        // third byte\n        temp_ch_ = reader_.GetChar();\n        ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << \"invalid base64 format\";\n        // handle termination\n        if (temp_ch_ == '=') {\n          temp_ch_ = reader_.GetChar();\n          ICHECK(temp_ch_ == '=') << \"invalid base64 format\";\n          temp_ch_ = reader_.GetChar();\n          ICHECK(temp_ch_ == EOF || isspace(temp_ch_)) << \"invalid base64 format\";\n          break;\n        }\n        nvalue |= DecodeTable[temp_ch_] << 6;\n        if (tlen) {\n          *cptr++ = (nvalue >> 8) & 0xFF;\n          --tlen;\n        } else {\n          buf_prev[num_prev_++] = (nvalue >> 8) & 0xFF;\n        }\n      }\n      {\n        // fourth byte\n        temp_ch_ = reader_.GetChar();\n        ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << \"invalid base64 format\";\n        if (temp_ch_ == '=') {\n          temp_ch_ = reader_.GetChar();\n          ICHECK(temp_ch_ == EOF || isspace(temp_ch_)) << \"invalid base64 format\";\n          break;\n        }\n        nvalue |= DecodeTable[temp_ch_];\n        if (tlen) {\n          *cptr++ = nvalue & 0xFF;\n          --tlen;\n        } else {\n          buf_prev[num_prev_++] = nvalue & 0xFF;\n        }\n      }\n      // get next char\n      temp_ch_ = reader_.GetChar();\n    }\n    if (kStrictCheck) {\n      ICHECK_EQ(tlen, 0) << \"Base64InStream: read incomplete\";\n    }\n    return size - tlen;\n  }\n  virtual void Write(const void* ptr, size_t size) {\n    LOG(FATAL) << \"Base64InStream do not support write\";\n  }\n\n private:\n  // internal reader\n  StreamBufferReader reader_;\n  int temp_ch_{0};\n  int num_prev_{0};\n  unsigned char buf_prev[2];\n  // whether we need to do strict check\n  static const bool kStrictCheck = false;\n};\n\n/*!\n * \\brief Stream to write to base64 format.\n */\nclass Base64OutStream : public dmlc::Stream {\n public:\n  explicit Base64OutStream(dmlc::Stream* fp) : fp_(fp) {}\n  virtual void Write(const void* ptr, size_t size) {\n    using base64::EncodeTable;\n    size_t tlen = size;\n    const unsigned char* cptr = static_cast<const unsigned char*>(ptr);\n    while (tlen) {\n      while (buf__top_ < 3 && tlen != 0) {\n        buf_[++buf__top_] = *cptr++;\n        --tlen;\n      }\n      if (buf__top_ == 3) {\n        // flush 4 bytes out\n        PutChar(EncodeTable[buf_[1] >> 2]);\n        PutChar(EncodeTable[((buf_[1] << 4) | (buf_[2] >> 4)) & 0x3F]);\n        PutChar(EncodeTable[((buf_[2] << 2) | (buf_[3] >> 6)) & 0x3F]);\n        PutChar(EncodeTable[buf_[3] & 0x3F]);\n        buf__top_ = 0;\n      }\n    }\n  }\n  virtual size_t Read(void* ptr, size_t size) {\n    LOG(FATAL) << \"Base64OutStream do not support read\";\n    return 0;\n  }\n  /*!\n   * \\brief finish writing of all current base64 stream, do some post processing\n   * \\param endch character to put to end of stream, if it is EOF, then nothing will be appended.\n   */\n  void Finish(int endch = EOF) {\n    using base64::EncodeTable;\n    if (buf__top_ == 1) {\n      PutChar(EncodeTable[buf_[1] >> 2]);\n      PutChar(EncodeTable[(buf_[1] << 4) & 0x3F]);\n      PutChar('=');\n      PutChar('=');\n    }\n    if (buf__top_ == 2) {\n      PutChar(EncodeTable[buf_[1] >> 2]);\n      PutChar(EncodeTable[((buf_[1] << 4) | (buf_[2] >> 4)) & 0x3F]);\n      PutChar(EncodeTable[(buf_[2] << 2) & 0x3F]);\n      PutChar('=');\n    }\n    buf__top_ = 0;\n    if (endch != EOF) PutChar(endch);\n    this->Flush();\n  }\n\n private:\n  static constexpr size_t kBufferSize = 256;\n\n  dmlc::Stream* fp_{nullptr};\n  int buf__top_{0};\n  unsigned char buf_[4];\n  std::string out_buf_;\n\n  void PutChar(char ch) {\n    out_buf_ += ch;\n    if (out_buf_.length() >= kBufferSize) Flush();\n  }\n  void Flush(void) {\n    if (out_buf_.length() != 0) {\n      fp_->Write(&out_buf_[0], out_buf_.length());\n      out_buf_.clear();\n    }\n  }\n};\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_BASE64_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/generic_arena.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file arena.h\n * \\brief Arena allocator that allocates memory chunks and frees them all during destruction time.\n *\n * NOTE: This file is portable to bare-metal embedded devices. Don't use operator new (without\n * placement parameters) or malloc.\n */\n#ifndef TVM_SUPPORT_GENERIC_ARENA_H_\n#define TVM_SUPPORT_GENERIC_ARENA_H_\n\n#ifndef TVM_ARENA_HAS_DESTRUCTOR\n#define TVM_ARENA_HAS_DESTRUCTOR 1\n#endif\n\n#include <stddef.h>\n\n#include <utility>\n\nnamespace tvm {\nnamespace support {\n\nnamespace {\ntemplate <typename T>              // For lvalues (T is T&),\nT&& forward(T&& param) {           // take/return lvalue refs.\n  return static_cast<T&&>(param);  // For rvalues (T is T),\n}  // take/return rvalue refs.\n}  // namespace\n\n/*!\n * \\brief An arena page header.\n */\nstruct ArenaPageHeader {\n  /*! \\brief points to the next page. */\n  ArenaPageHeader* next;\n  /*!\n   * \\brief Total size of the page.\n   */\n  size_t size;\n  /*! \\brief memory allocator offset inside page. */\n  size_t offset;\n};\n\n/*!\n * \\brief Arena allocator that allocates memory from continuous\n *  chunk and frees them all only during destruction.\n */\ntemplate <typename PageAllocator>\nclass GenericArena {\n public:\n  explicit GenericArena(PageAllocator alloc = PageAllocator()) : alloc_(alloc) {\n    // eagerly allocate the first page.\n    head_ = tail_ = alloc_.allocate(1);\n    head_->next = nullptr;\n  }\n\n#if TVM_ARENA_HAS_DESTRUCTOR\n  ~GenericArena() { this->FreeAll(); }\n#endif\n\n  /*! \\brief Free all pages. */\n  void FreeAll() {\n    FreePageList(&head_);\n    FreePageList(&free_list_);\n  }\n  /*! \\brief Recycle all the pages in the arena */\n  void RecycleAll() {\n    // put all the current list to the free list.\n    tail_->next = free_list_;\n    // allocate the first in the free list to head\n    free_list_ = head_->next;\n    head_->next = nullptr;\n    // Reset the head.\n    head_->offset = sizeof(ArenaPageHeader);\n    tail_ = head_;\n  }\n  /*!\n   * \\brief Allocate a space from Arena for type T\n   * \\param T the data type to be allocated\n   * \\param count Numberof elements\n   * \\note The space of T is not initialized.\n   */\n  template <typename T>\n  T* allocate_(int count = 1) {\n    static_assert(PageAllocator::kPageAlign % alignof(T) == 0, \"To large alignment\");\n    return static_cast<T*>(Alloc(sizeof(T) * count, alignof(T)));\n  }\n  /*!\n   * \\brief Create a new instance of type T.\n   * \\param args The constructor argument.\n   * \\tparam T the type to be created.\n   * \\tparam Args Arguments to the constructor.\n   *\n   * \\return The allocated object.\n   * \\note The type T must be simple type, or only contain\n   *  memory allocated from the same arena.\n   *  Otherwise the destructor needs to be called explicitly.\n   */\n  template <typename T, typename... Args>\n  T* make(Args&&... args) {\n    T* ptr = allocate_<T>();\n    new (ptr) T(forward<Args>(args)...);\n    return ptr;\n  }\n\n private:\n  /*! \\brief internal page allocator. */\n  PageAllocator alloc_;\n  /* \\brief The head of the allocated list. */\n  ArenaPageHeader* head_{nullptr};\n  /*! \\brief The tail of the allocated list. */\n  ArenaPageHeader* tail_{nullptr};\n  /* \\brief List of free pages. */\n  ArenaPageHeader* free_list_{nullptr};\n  /*!\n   * \\brief Align ptr by upper bound.\n   * \\param offset The offset value.\n   * \\param align The alignment requirement.\n   */\n  size_t UpperAlign(size_t offset, size_t align) {\n    return offset + (align - (offset % align)) % align;\n  }\n  /*!\n   * \\brief Internal aligned alloc function.\n   * \\param size The size of the memory.\n   * \\param align The alignment requirement.\n   */\n  void* Alloc(size_t size, size_t align) {\n    size_t offset = UpperAlign(head_->offset, align);\n    if (offset + size <= head_->size) {\n      head_->offset = offset + size;\n      return reinterpret_cast<char*>(head_) + offset;\n    } else {\n      ArenaPageHeader* new_head;\n      offset = UpperAlign(sizeof(ArenaPageHeader), align);\n      if (free_list_ != nullptr && offset + size <= free_list_->size) {\n        new_head = free_list_;\n        free_list_ = free_list_->next;\n      } else {\n        new_head = alloc_.allocate(offset + size);\n      }\n      new_head->next = head_;\n      new_head->offset = offset + size;\n      head_ = new_head;\n      return reinterpret_cast<char*>(head_) + offset;\n    }\n  }\n  /*!\n   * \\brief Free all the pages in the list.\n   * \\param ptr The head ptr.\n   */\n  void FreePageList(ArenaPageHeader** ptr) {\n    // delete all the allocated pages.\n    while (ptr[0] != nullptr) {\n      ArenaPageHeader* temp = ptr[0];\n      ptr[0] = ptr[0]->next;\n      alloc_.deallocate(temp);\n    }\n  }\n};\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_GENERIC_ARENA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/hexdump.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file support/hexdump.h\n * \\brief Print hex representation of BLOBs.\n */\n#ifndef TVM_SUPPORT_HEXDUMP_H_\n#define TVM_SUPPORT_HEXDUMP_H_\n\n#include <iomanip>\n#include <sstream>\n#include <string>\n\nnamespace tvm {\nnamespace support {\n\n/*! \\brief generate a hexdump of some binary data.\n * \\param s Binary data to print.\n * \\param os stream that receives the hexdump.\n */\nvoid HexDump(const std::string& s, std::ostream& os);\n\n/*! \\brief return a string containing a hexdump of the data in s */\ninline std::string HexDump(const std::string& s) {\n  std::stringstream ss;\n  HexDump(s, ss);\n  return ss.str();\n}\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_HEXDUMP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/nd_int_set.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SUPPORT_ND_INT_SET_H_\n#define TVM_SUPPORT_ND_INT_SET_H_\n\n#include <tvm/arith/int_set.h>\n#include <tvm/ir/expr.h>\n\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n\n/*! \\brief An N-dimensional integer set representing a rectangle region */\nusing NDIntSet = std::vector<arith::IntSet>;\n\n/*!\n * \\brief Construct an N-dimensional integer set representing a region.\n * \\param region The region.\n * \\return The constructed set.\n */\ninline NDIntSet NDIntSetFromRegion(const tir::Region& region) {\n  NDIntSet result;\n  result.reserve(region.size());\n  for (const Range& range : region) {\n    result.push_back(arith::IntSet::FromRange(range));\n  }\n  return result;\n}\n\n/*!\n * \\brief Construct an N-dimensional integer set representing a shape.\n * \\param shape The shape which is an array of the length of each dimension.\n * \\return The constructed set.\n */\ninline NDIntSet NDIntSetFromShape(const Array<PrimExpr>& shape) {\n  PrimExpr zero = Integer(0);\n  NDIntSet result;\n  result.reserve(shape.size());\n  for (const PrimExpr& extent : shape) {\n    result.push_back(arith::IntSet::FromMinExtent(zero, extent));\n  }\n  return result;\n}\n\n/*!\n * \\brief Construct an N-dimensional integer set representing a point.\n * \\param indices The N-dimensional indices representing the point.\n * \\return The constructed set.\n */\ninline NDIntSet NDIntSetFromPoint(const Array<PrimExpr>& indices) {\n  NDIntSet result;\n  result.reserve(indices.size());\n  for (const PrimExpr& index : indices) {\n    result.push_back(arith::IntSet::SinglePoint(index));\n  }\n  return result;\n}\n\n/*!\n * \\brief Create a union set of two sets, possibly relaxed. The RHS set will be combined into the\n *        LHS set.\n * \\param lhs The first N-dimensional integer set\n * \\param rhs The second N-dimensional integer set\n */\ninline void NDIntSetUnionWith(NDIntSet* lhs, const NDIntSet& rhs) {\n  ICHECK_EQ(lhs->size(), rhs.size());\n  int ndim = rhs.size();\n  for (int i = 0; i < ndim; ++i) {\n    arith::IntSet& int_set = lhs->at(i);\n    int_set = arith::Union({int_set, rhs.at(i)});\n  }\n}\n\n/*!\n * \\brief Union a list of N-dimensional integer sets\n * \\param nd_int_sets The N-dimensional integer sets to be merged.\n * \\return The result of the union\n */\ninline NDIntSet NDIntSetUnion(const std::vector<NDIntSet>& nd_int_sets) {\n  ICHECK(!nd_int_sets.empty());\n  int n = nd_int_sets.size();\n  if (n == 1) {\n    return nd_int_sets[0];\n  }\n  int ndim = nd_int_sets[0].size();\n  for (int i = 1; i < n; ++i) {\n    ICHECK_EQ(nd_int_sets[i].size(), ndim);\n  }\n  NDIntSet result;\n  result.reserve(ndim);\n  Array<arith::IntSet> int_sets(n, arith::IntSet{nullptr});\n  for (int dim = 0; dim < ndim; ++dim) {\n    for (int i = 0; i < n; ++i) {\n      int_sets.Set(i, nd_int_sets[i][dim]);\n    }\n    result.push_back(arith::Union(int_sets));\n  }\n  return result;\n}\n\n/*!\n * \\brief Create an empty N-dimensional integer set.\n * \\param ndim The number of dimensions.\n * \\return The constructed set.\n */\ninline NDIntSet NDIntSetEmpty(int ndim) {\n  return std::vector<arith::IntSet>(ndim, arith::IntSet::Nothing());\n}\n\n/*!\n * \\brief The N-dimensional version of EvalSet.\n * \\param nd_int_set The N-dimensional integer set to be evaluated.\n * \\param dom_map The domain of each variable.\n * \\return An N-dimensional integer set that can cover all the possible values of the N-dimensional\n *         integer set.\n * \\sa EvalSet\n */\ninline NDIntSet NDIntSetEval(\n    const NDIntSet& nd_int_set,\n    const std::unordered_map<const tir::VarNode*, arith::IntSet>& dom_map) {\n  NDIntSet ret;\n  ret.reserve(nd_int_set.size());\n  for (const arith::IntSet& s : nd_int_set) {\n    ret.push_back(EvalSet(s, dom_map));\n  }\n  return ret;\n}\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_ND_INT_SET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/pipe.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file pipe.h\n * \\brief Platform independent pipe, used for IPC.\n */\n#ifndef TVM_SUPPORT_PIPE_H_\n#define TVM_SUPPORT_PIPE_H_\n\n#include <dmlc/io.h>\n#include <tvm/runtime/logging.h>\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <errno.h>\n#include <unistd.h>\n\n#include <cstdlib>\n#include <cstring>\n#endif\n\nnamespace tvm {\nnamespace support {\n\n/*! \\brief Platform independent pipe */\nclass Pipe : public dmlc::Stream {\n public:\n#ifdef _WIN32\n  using PipeHandle = HANDLE;\n#else\n  using PipeHandle = int;\n#endif\n  /*! \\brief Construct a pipe from system handle. */\n  explicit Pipe(int64_t handle) : handle_(static_cast<PipeHandle>(handle)) {}\n  /*! \\brief destructor */\n  ~Pipe() { Flush(); }\n  using Stream::Read;\n  using Stream::Write;\n  /*!\n   * \\brief reads data from a file descriptor\n   * \\param ptr pointer to a memory buffer\n   * \\param size block size\n   * \\return the size of data read\n   */\n  size_t Read(void* ptr, size_t size) final {\n    if (size == 0) return 0;\n#ifdef _WIN32\n    DWORD nread;\n    ICHECK(ReadFile(handle_, static_cast<TCHAR*>(ptr), &nread, nullptr))\n        << \"Read Error: \" << GetLastError();\n#else\n    ssize_t nread;\n    nread = read(handle_, ptr, size);\n    ICHECK_GE(nread, 0) << \"Write Error: \" << strerror(errno);\n#endif\n    return static_cast<size_t>(nread);\n  }\n  /*!\n   * \\brief write data to a file descriptor\n   * \\param ptr pointer to a memory buffer\n   * \\param size block size\n   * \\return the size of data read\n   */\n  void Write(const void* ptr, size_t size) final {\n    if (size == 0) return;\n#ifdef _WIN32\n    DWORD nwrite;\n    ICHECK(WriteFile(handle_, static_cast<const TCHAR*>(ptr), &nwrite, nullptr) &&\n           static_cast<size_t>(nwrite) == size)\n        << \"Write Error: \" << GetLastError();\n#else\n    ssize_t nwrite;\n    nwrite = write(handle_, ptr, size);\n    ICHECK_EQ(static_cast<size_t>(nwrite), size) << \"Write Error: \" << strerror(errno);\n#endif\n  }\n  /*!\n   * \\brief Flush the pipe;\n   */\n  void Flush() {\n#ifdef _WIN32\n    FlushFileBuffers(handle_);\n#endif\n  }\n  /*! \\brief close the pipe */\n  void Close() {\n#ifdef _WIN32\n    CloseHandle(handle_);\n#else\n    close(handle_);\n#endif\n  }\n\n private:\n  PipeHandle handle_;\n};\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_PIPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/ring_buffer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ring_buffer.h\n * \\brief this file aims to provide a wrapper of sockets\n */\n#ifndef TVM_SUPPORT_RING_BUFFER_H_\n#define TVM_SUPPORT_RING_BUFFER_H_\n\n#include <algorithm>\n#include <cstring>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n/*!\n * \\brief Ring buffer class for data buffering in IO.\n *  Enables easy usage for sync and async mode.\n */\nclass RingBuffer {\n public:\n  /*! \\brief Initial capacity of ring buffer. */\n  static const int kInitCapacity = 4 << 10;\n  /*! \\brief constructor */\n  RingBuffer() : ring_(kInitCapacity) {}\n  /*! \\return number of bytes available in buffer. */\n  size_t bytes_available() const { return bytes_available_; }\n  /*! \\return Current capacity of buffer. */\n  size_t capacity() const { return ring_.size(); }\n  /*!\n   *  Reserve capacity to be at least n.\n   *  Will only increase capacity if n is bigger than current capacity.\n   *\n   *  The effect of Reserve only lasts before the next call to Reserve.\n   *  Other functions in the ring buffer can also call into the reserve.\n   *\n   * \\param n The size of capacity.\n   */\n  void Reserve(size_t n) {\n    if (ring_.size() < n) {\n      size_t old_size = ring_.size();\n      size_t new_size = static_cast<size_t>(n * 1.2);\n      ring_.resize(new_size);\n      if (head_ptr_ + bytes_available_ > old_size) {\n        // copy the ring overflow part into the tail.\n        size_t ncopy = head_ptr_ + bytes_available_ - old_size;\n        memcpy(&ring_[0] + old_size, &ring_[0], ncopy);\n      }\n    } else if (ring_.size() > n * 8 && ring_.size() > kInitCapacity) {\n      // shrink too large temporary buffer to\n      // avoid out of memory on some embedded devices\n      if (bytes_available_ != 0) {\n        // move existing bytes to the head.\n        size_t old_bytes = bytes_available_;\n        std::vector<char> tmp(old_bytes);\n        Read(&tmp[0], old_bytes);\n\n        memcpy(&ring_[0], &tmp[0], old_bytes);\n        bytes_available_ = old_bytes;\n      }\n      // shrink the ring.\n      size_t new_size = kInitCapacity;\n      new_size = std::max(new_size, n);\n      new_size = std::max(new_size, bytes_available_);\n\n      ring_.resize(new_size);\n      ring_.shrink_to_fit();\n      head_ptr_ = 0;\n    }\n  }\n\n  /*!\n   * \\brief Perform a non-blocking read from buffer\n   *  size must be smaller than this->bytes_available()\n   * \\param data the data pointer.\n   * \\param size The number of bytes to read.\n   */\n  void Read(void* data, size_t size) {\n    ICHECK_GE(bytes_available_, size);\n    size_t ncopy = std::min(size, ring_.size() - head_ptr_);\n    memcpy(data, &ring_[0] + head_ptr_, ncopy);\n    if (ncopy < size) {\n      memcpy(reinterpret_cast<char*>(data) + ncopy, &ring_[0], size - ncopy);\n    }\n    head_ptr_ = (head_ptr_ + size) % ring_.size();\n    bytes_available_ -= size;\n  }\n  /*!\n   * \\brief Read data from buffer with and put them to non-blocking send function.\n   *\n   * \\param fsend A send function handle to put the data to.\n   * \\param max_nbytes Maximum number of bytes can to read.\n   * \\tparam FSend A non-blocking function with signature size_t (const void* data, size_t size);\n   */\n  template <typename FSend>\n  size_t ReadWithCallback(FSend fsend, size_t max_nbytes) {\n    size_t size = std::min(max_nbytes, bytes_available_);\n    ICHECK_NE(size, 0U);\n    size_t ncopy = std::min(size, ring_.size() - head_ptr_);\n    size_t nsend = fsend(&ring_[0] + head_ptr_, ncopy);\n    bytes_available_ -= nsend;\n    if (ncopy == nsend && ncopy < size) {\n      size_t nsend2 = fsend(&ring_[0], size - ncopy);\n      bytes_available_ -= nsend2;\n      nsend += nsend2;\n    }\n    return nsend;\n  }\n  /*!\n   * \\brief Write data into buffer, always ensures all data is written.\n   * \\param data The data pointer\n   * \\param size The size of data to be written.\n   */\n  void Write(const void* data, size_t size) {\n    this->Reserve(bytes_available_ + size);\n    size_t tail = head_ptr_ + bytes_available_;\n    if (tail >= ring_.size()) {\n      memcpy(&ring_[0] + (tail - ring_.size()), data, size);\n    } else {\n      size_t ncopy = std::min(ring_.size() - tail, size);\n      memcpy(&ring_[0] + tail, data, ncopy);\n      if (ncopy < size) {\n        memcpy(&ring_[0], reinterpret_cast<const char*>(data) + ncopy, size - ncopy);\n      }\n    }\n    bytes_available_ += size;\n  }\n  /*!\n   * \\brief Written data into the buffer by give it a non-blocking callback function.\n   *\n   * \\param frecv A receive function handle\n   * \\param max_nbytes Maximum number of bytes can write.\n   * \\tparam FRecv A non-blocking function with signature size_t (void* data, size_t size);\n   */\n  template <typename FRecv>\n  size_t WriteWithCallback(FRecv frecv, size_t max_nbytes) {\n    this->Reserve(bytes_available_ + max_nbytes);\n    size_t nbytes = max_nbytes;\n    size_t tail = head_ptr_ + bytes_available_;\n    if (tail >= ring_.size()) {\n      size_t nrecv = frecv(&ring_[0] + (tail - ring_.size()), nbytes);\n      bytes_available_ += nrecv;\n      return nrecv;\n    } else {\n      size_t ncopy = std::min(ring_.size() - tail, nbytes);\n      size_t nrecv = frecv(&ring_[0] + tail, ncopy);\n      bytes_available_ += nrecv;\n      if (nrecv == ncopy && ncopy < nbytes) {\n        size_t nrecv2 = frecv(&ring_[0], nbytes - ncopy);\n        bytes_available_ += nrecv2;\n        nrecv += nrecv2;\n      }\n      return nrecv;\n    }\n  }\n\n private:\n  // buffer head\n  size_t head_ptr_{0};\n  // number of bytes occupied in the buffer.\n  size_t bytes_available_{0};\n  // The internal data ring.\n  std::vector<char> ring_;\n};\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_RING_BUFFER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/scalars.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file src/support/scalars.h\n * \\brief Helpers for converting between scalars in native, text, TIR immediate and NDArray forms.\n */\n\n#ifndef TVM_SUPPORT_SCALARS_H_\n#define TVM_SUPPORT_SCALARS_H_\n\n#include <string>\n#include <utility>\n\n#include \"tvm/ir/expr.h\"\n#include \"tvm/relay/expr.h\"\n#include \"tvm/runtime/ndarray.h\"\n\nnamespace tvm {\nnamespace support {\n\n/*! \\brief Returns true if a tensor of empty shape and given dtype is considered a Relay scalar. */\nbool IsSimpleScalarDtype(DataType dtype);\n\n/*! \\brief Returns true if \\p constant_node is a float/int/bool scalar. */\nbool IsSimpleScalar(const relay::ConstantNode* constant_node);\n\n/*! \\brief Returns NDArray 'scalar' for given TIR immediate. */\nruntime::NDArray IntImmToNDArray(const IntImm& int_imm);\nruntime::NDArray FloatImmToNDArray(const FloatImm& float_imm);\nruntime::NDArray BoolToNDArray(bool value);\n\n/*! \\brief Returns Relay literal text for NDArray 'scalar'. */\nstd::string NDArrayScalarToString(const runtime::NDArray& data);\n\n/*! \\brief Returns Relay literal text for given TIR immediate. */\nstd::string IntImmToString(const IntImm& int_imm);\nstd::string FloatImmToString(const FloatImm& float_imm);\n\n/*!\n * \\brief Returns TIR immediate for given value and width. Result will be null if value is\n * out of range in width. Note however for floating point we don't check if the value is\n * representable without loss of precision.\n */\nIntImm ValueToIntImm(int64_t value, int width);\nFloatImm ValueToFloatImm(double value, int width);\n\n// 2^15 * (1 + 1023/1024)\n// See https://en.wikipedia.org/wiki/Half-precision_floating-point_format\nconstexpr double kMaxFloat16 = 65504.0;\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_SCALARS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/socket.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file socket.h\n * \\brief this file aims to provide a wrapper of sockets\n * \\author Tianqi Chen\n */\n#ifndef TVM_SUPPORT_SOCKET_H_\n#define TVM_SUPPORT_SOCKET_H_\n\n#if defined(_WIN32)\n\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n\n#include <winsock2.h>\n#include <ws2tcpip.h>\n\n#ifdef _MSC_VER\n#pragma comment(lib, \"Ws2_32.lib\")\n#endif\n#else\n#include <arpa/inet.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <sys/ioctl.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <unistd.h>\n#endif\n#include <tvm/runtime/logging.h>\n#include <tvm/runtime/registry.h>\n\n#include <cstring>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../support/ssize.h\"\n#include \"../support/utils.h\"\n\n#if defined(_WIN32)\nstatic inline int poll(struct pollfd* pfd, int nfds, int timeout) {\n  return WSAPoll(pfd, nfds, timeout);\n}\n#else\n#include <sys/poll.h>\n#endif  // defined(_WIN32)\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief Get current host name.\n * \\return The hostname.\n */\ninline std::string GetHostName() {\n  std::string buf;\n  buf.resize(256);\n  ICHECK_NE(gethostname(&buf[0], 256), -1);\n  return std::string(buf.c_str());\n}\n\n/*!\n * \\brief ValidateIP validates an ip address.\n * \\param ip The ip address in string format localhost or x.x.x.x format\n * \\return result of operation.\n */\ninline bool ValidateIP(std::string ip) {\n  if (ip == \"localhost\") {\n    return true;\n  }\n  struct sockaddr_in sa_ipv4;\n  struct sockaddr_in6 sa_ipv6;\n  bool is_ipv4 = inet_pton(AF_INET, ip.c_str(), &(sa_ipv4.sin_addr));\n  bool is_ipv6 = inet_pton(AF_INET6, ip.c_str(), &(sa_ipv6.sin6_addr));\n  return is_ipv4 || is_ipv6;\n}\n\n/*!\n * \\brief Common data structure for network address.\n */\nstruct SockAddr {\n  sockaddr_storage addr;\n  SockAddr() {}\n  /*!\n   * \\brief construct address by url and port\n   * \\param url The url of the address\n   * \\param port The port of the address.\n   */\n  SockAddr(const char* url, int port) { this->Set(url, port); }\n\n  /*!\n   * \\brief SockAddr Get the socket address from tracker.\n   * \\param tracker The url containing the ip and port number. Format is ('192.169.1.100', 9090)\n   * \\return SockAddr parsed from url.\n   */\n  explicit SockAddr(const std::string& url) {\n    size_t sep = url.find(\",\");\n    std::string host = url.substr(2, sep - 3);\n    std::string port = url.substr(sep + 1, url.length() - 1);\n    ICHECK(ValidateIP(host)) << \"Url address is not valid \" << url;\n    if (host == \"localhost\") {\n      host = \"127.0.0.1\";\n    }\n    this->Set(host.c_str(), std::stoi(port));\n  }\n\n  /*!\n   * \\brief set the address\n   * \\param host the url of the address\n   * \\param port the port of address\n   */\n  void Set(const char* host, int port) {\n    addrinfo hints;\n    memset(&hints, 0, sizeof(hints));\n    hints.ai_family = PF_UNSPEC;\n    hints.ai_flags = AI_PASSIVE;\n    hints.ai_socktype = SOCK_STREAM;\n    addrinfo* res = nullptr;\n    int sig = getaddrinfo(host, nullptr, &hints, &res);\n    ICHECK(sig == 0 && res != nullptr) << \"cannot obtain address of \" << host;\n    switch (res->ai_family) {\n      case AF_INET: {\n        sockaddr_in* addr4 = reinterpret_cast<sockaddr_in*>(&addr);\n        memcpy(addr4, res->ai_addr, res->ai_addrlen);\n        addr4->sin_port = htons(port);\n        addr4->sin_family = AF_INET;\n      } break;\n      case AF_INET6: {\n        sockaddr_in6* addr6 = reinterpret_cast<sockaddr_in6*>(&addr);\n        memcpy(addr6, res->ai_addr, res->ai_addrlen);\n        addr6->sin6_port = htons(port);\n        addr6->sin6_family = AF_INET6;\n      } break;\n      default:\n        ICHECK(false) << \"cannot decode address\";\n    }\n    freeaddrinfo(res);\n  }\n  /*! \\brief return port of the address */\n  int port() const {\n    return ntohs((addr.ss_family == AF_INET6)\n                     ? reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_port\n                     : reinterpret_cast<const sockaddr_in*>(&addr)->sin_port);\n  }\n  /*! \\brief return the ip address family */\n  int ss_family() const { return addr.ss_family; }\n  /*! \\return a string representation of the address */\n  std::string AsString() const {\n    std::string buf;\n    buf.resize(256);\n\n    const void* sinx_addr = nullptr;\n    if (addr.ss_family == AF_INET6) {\n      const in6_addr& addr6 = reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_addr;\n      sinx_addr = reinterpret_cast<const void*>(&addr6);\n    } else if (addr.ss_family == AF_INET) {\n      const in_addr& addr4 = reinterpret_cast<const sockaddr_in*>(&addr)->sin_addr;\n      sinx_addr = reinterpret_cast<const void*>(&addr4);\n    } else {\n      ICHECK(false) << \"illegal address\";\n    }\n\n#ifdef _WIN32\n    const char* s = inet_ntop(addr.ss_family, (PVOID)sinx_addr,  // NOLINT(*)\n                              &buf[0], buf.length());\n#else\n    const char* s =\n        inet_ntop(addr.ss_family, sinx_addr, &buf[0], static_cast<socklen_t>(buf.length()));\n#endif\n    ICHECK(s != nullptr) << \"cannot decode address\";\n    std::ostringstream os;\n    os << s << \":\" << port();\n    return os.str();\n  }\n};\n/*!\n * \\brief base class containing common operations of TCP and UDP sockets\n */\nclass Socket {\n public:\n#if defined(_WIN32)\n  using sock_size_t = int;\n  using SockType = SOCKET;\n#else\n  using SockType = int;\n  using sock_size_t = size_t;\n  static constexpr int INVALID_SOCKET = -1;\n#endif\n  /*! \\brief the file descriptor of socket */\n  SockType sockfd;\n  /*!\n   * \\brief set this socket to use non-blocking mode\n   * \\param non_block whether set it to be non-block, if it is false\n   *        it will set it back to block mode\n   */\n  void SetNonBlock(bool non_block) {\n#ifdef _WIN32\n    u_long mode = non_block ? 1 : 0;\n    if (ioctlsocket(sockfd, FIONBIO, &mode) != NO_ERROR) {\n      Socket::Error(\"SetNonBlock\");\n    }\n#else\n    int flag = fcntl(sockfd, F_GETFL, 0);\n    if (flag == -1) {\n      Socket::Error(\"SetNonBlock-1\");\n    }\n    if (non_block) {\n      flag |= O_NONBLOCK;\n    } else {\n      flag &= ~O_NONBLOCK;\n    }\n    if (fcntl(sockfd, F_SETFL, flag) == -1) {\n      Socket::Error(\"SetNonBlock-2\");\n    }\n#endif\n  }\n  /*!\n   * \\brief bind the socket to an address\n   * \\param addr The address to be binded\n   */\n  void Bind(const SockAddr& addr) {\n    if (bind(sockfd, reinterpret_cast<const sockaddr*>(&addr.addr),\n             (addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) ==\n        -1) {\n      Socket::Error(\"Bind\");\n    }\n  }\n  /*!\n   * \\brief try bind the socket to host, from start_port to end_port\n   * \\param host host address to bind the socket\n   * \\param start_port starting port number to try\n   * \\param end_port ending port number to try\n   * \\return the port successfully bind to, return -1 if failed to bind any port\n   */\n  inline int TryBindHost(std::string host, int start_port, int end_port) {\n    for (int port = start_port; port < end_port; ++port) {\n      SockAddr addr(host.c_str(), port);\n      if (bind(sockfd, reinterpret_cast<sockaddr*>(&addr.addr),\n               (addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) ==\n          0) {\n        return port;\n      } else {\n        LOG(WARNING) << \"Bind failed to \" << host << \":\" << port;\n      }\n#if defined(_WIN32)\n      if (WSAGetLastError() != WSAEADDRINUSE) {\n        Socket::Error(\"TryBindHost\");\n      }\n#else\n      if (errno != EADDRINUSE) {\n        Socket::Error(\"TryBindHost\");\n      }\n#endif\n    }\n    return -1;\n  }\n  /*! \\brief get last error code if any */\n  int GetSockError() const {\n    int error = 0;\n    socklen_t len = sizeof(error);\n    if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len) != 0) {\n      Error(\"GetSockError\");\n    }\n    return error;\n  }\n  /*! \\brief check if anything bad happens */\n  bool BadSocket() const {\n    if (IsClosed()) return true;\n    int err = GetSockError();\n    if (err == EBADF || err == EINTR) return true;\n    return false;\n  }\n  /*! \\brief check if socket is already closed */\n  bool IsClosed() const { return sockfd == INVALID_SOCKET; }\n  /*! \\brief close the socket */\n  void Close() {\n    if (sockfd != INVALID_SOCKET) {\n#ifdef _WIN32\n      closesocket(sockfd);\n#else\n      close(sockfd);\n#endif\n      sockfd = INVALID_SOCKET;\n    } else {\n      Error(\"Socket::Close double close the socket or close without create\");\n    }\n  }\n  /*!\n   * \\return last error of socket operation\n   */\n  static int GetLastError() {\n#ifdef _WIN32\n    return WSAGetLastError();\n#else\n    return errno;\n#endif\n  }\n  /*! \\return whether last error was would block */\n  static bool LastErrorWouldBlock() {\n    int errsv = GetLastError();\n#ifdef _WIN32\n    return errsv == WSAEWOULDBLOCK;\n#else\n    return errsv == EAGAIN || errsv == EWOULDBLOCK;\n#endif\n  }\n  /*!\n   * \\brief start up the socket module\n   *   call this before using the sockets\n   */\n  static void Startup() {\n#ifdef _WIN32\n    WSADATA wsa_data;\n    if (WSAStartup(MAKEWORD(2, 2), &wsa_data) == -1) {\n      Socket::Error(\"Startup\");\n    }\n    if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {\n      WSACleanup();\n      LOG(FATAL) << \"Could not find a usable version of Winsock.dll\";\n    }\n#endif\n  }\n  /*!\n   * \\brief shutdown the socket module after use, all sockets need to be closed\n   */\n  static void Finalize() {\n#ifdef _WIN32\n    WSACleanup();\n#endif\n  }\n  /*!\n   * \\brief Report an socket error.\n   * \\param msg The error message.\n   */\n  static void Error(const char* msg) {\n    int errsv = GetLastError();\n#ifdef _WIN32\n    LOG(FATAL) << \"Socket \" << msg << \" Error:WSAError-code=\" << errsv;\n#else\n    LOG(FATAL) << \"Socket \" << msg << \" Error:\" << strerror(errsv);\n#endif\n  }\n\n  /*!\n   * \\brief Call a function and retry if an EINTR error is encountered.\n   *\n   *  Socket operations can return EINTR when the interrupt handler\n   *  is registered by the execution environment(e.g. python).\n   *  We should retry if there is no KeyboardInterrupt recorded in\n   *  the environment.\n   *\n   * \\note This function is needed to avoid rare interrupt event\n   *       in long running server code.\n   *\n   * \\param func The function to retry.\n   * \\return The return code returned by function f or error_value on retry failure.\n   */\n  template <typename FuncType>\n  ssize_t RetryCallOnEINTR(FuncType func) {\n    ssize_t ret = func();\n    // common path\n    if (ret != -1) return ret;\n    // less common path\n    do {\n      if (GetLastError() == EINTR) {\n        // Call into env check signals to see if there are\n        // environment specific(e.g. python) signal exceptions.\n        // This function will throw an exception if there is\n        // if the process received a signal that requires TVM to return immediately (e.g. SIGINT).\n        runtime::EnvCheckSignals();\n      } else {\n        // other errors\n        return ret;\n      }\n      ret = func();\n    } while (ret == -1);\n    return ret;\n  }\n\n protected:\n  explicit Socket(SockType sockfd) : sockfd(sockfd) {}\n};\n\n/*!\n * \\brief a wrapper of TCP socket that hopefully be cross platform\n */\nclass TCPSocket : public Socket {\n public:\n  TCPSocket() : Socket(INVALID_SOCKET) {}\n  /*!\n   * \\brief construct a TCP socket from existing descriptor\n   * \\param sockfd The descriptor\n   */\n  explicit TCPSocket(SockType sockfd) : Socket(sockfd) {}\n  /*!\n   * \\brief enable/disable TCP keepalive\n   * \\param keepalive whether to set the keep alive option on\n   */\n  void SetKeepAlive(bool keepalive) {\n    int opt = static_cast<int>(keepalive);\n    if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<char*>(&opt), sizeof(opt)) <\n        0) {\n      Socket::Error(\"SetKeepAlive\");\n    }\n  }\n  /*!\n   * \\brief create the socket, call this before using socket\n   * \\param af domain\n   */\n  void Create(int af = PF_INET) {\n    sockfd = socket(af, SOCK_STREAM, 0);\n    if (sockfd == INVALID_SOCKET) {\n      Socket::Error(\"Create\");\n    }\n  }\n  /*!\n   * \\brief perform listen of the socket\n   * \\param backlog backlog parameter\n   */\n  void Listen(int backlog = 16) { listen(sockfd, backlog); }\n  /*!\n   * \\brief get a new connection\n   * \\return The accepted socket connection.\n   */\n  TCPSocket Accept() {\n    SockType newfd = RetryCallOnEINTR([&]() { return accept(sockfd, nullptr, nullptr); });\n    if (newfd == INVALID_SOCKET) {\n      Socket::Error(\"Accept\");\n    }\n    return TCPSocket(newfd);\n  }\n  /*!\n   * \\brief get a new connection\n   * \\param addr client address from which connection accepted\n   * \\return The accepted socket connection.\n   */\n  TCPSocket Accept(SockAddr* addr) {\n    socklen_t addrlen = sizeof(addr->addr);\n    SockType newfd = RetryCallOnEINTR(\n        [&]() { return accept(sockfd, reinterpret_cast<sockaddr*>(&addr->addr), &addrlen); });\n    if (newfd == INVALID_SOCKET) {\n      Socket::Error(\"Accept\");\n    }\n    return TCPSocket(newfd);\n  }\n  /*!\n   * \\brief decide whether the socket is at OOB mark\n   * \\return 1 if at mark, 0 if not, -1 if an error occurred\n   */\n  int AtMark() const {\n#ifdef _WIN32\n    unsigned long atmark;  // NOLINT(*)\n    if (ioctlsocket(sockfd, SIOCATMARK, &atmark) != NO_ERROR) return -1;\n#else\n    int atmark;\n    if (ioctl(sockfd, SIOCATMARK, &atmark) == -1) return -1;\n#endif\n    return static_cast<int>(atmark);\n  }\n  /*!\n   * \\brief connect to an address\n   * \\param addr the address to connect to\n   * \\return whether connect is successful\n   */\n  bool Connect(const SockAddr& addr) {\n    return connect(\n               sockfd, reinterpret_cast<const sockaddr*>(&addr.addr),\n               (addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == 0;\n  }\n  /*!\n   * \\brief send data using the socket\n   * \\param buf_ the pointer to the buffer\n   * \\param len the size of the buffer\n   * \\param flag extra flags\n   * \\return size of data actually sent\n   *         return -1 if error occurs\n   */\n  ssize_t Send(const void* buf_, size_t len, int flag = 0) {\n    const char* buf = reinterpret_cast<const char*>(buf_);\n    return RetryCallOnEINTR(\n        [&]() { return send(sockfd, buf, static_cast<sock_size_t>(len), flag); });\n  }\n  /*!\n   * \\brief receive data using the socket\n   * \\param buf_ the pointer to the buffer\n   * \\param len the size of the buffer\n   * \\param flags extra flags\n   * \\return size of data actually received\n   *         return -1 if error occurs\n   */\n  ssize_t Recv(void* buf_, size_t len, int flags = 0) {\n    char* buf = reinterpret_cast<char*>(buf_);\n    return RetryCallOnEINTR(\n        [&]() { return recv(sockfd, buf, static_cast<sock_size_t>(len), flags); });\n  }\n  /*!\n   * \\brief perform block write that will attempt to send all data out\n   *    can still return smaller than request when error occurs\n   * \\param buf_ the pointer to the buffer\n   * \\param len the size of the buffer\n   * \\return size of data actually sent\n   */\n  size_t SendAll(const void* buf_, size_t len) {\n    const char* buf = reinterpret_cast<const char*>(buf_);\n    size_t ndone = 0;\n    while (ndone < len) {\n      ssize_t ret = RetryCallOnEINTR(\n          [&]() { return send(sockfd, buf, static_cast<ssize_t>(len - ndone), 0); });\n      if (ret == -1) {\n        if (LastErrorWouldBlock()) return ndone;\n        Socket::Error(\"SendAll\");\n      }\n      buf += ret;\n      ndone += ret;\n    }\n    return ndone;\n  }\n  /*!\n   * \\brief perform block read that will attempt to read all data\n   *    can still return smaller than request when error occurs\n   * \\param buf_ the buffer pointer\n   * \\param len length of data to recv\n   * \\return size of data actually sent\n   */\n  size_t RecvAll(void* buf_, size_t len) {\n    char* buf = reinterpret_cast<char*>(buf_);\n    size_t ndone = 0;\n    while (ndone < len) {\n      ssize_t ret = RetryCallOnEINTR(\n          [&]() { return recv(sockfd, buf, static_cast<sock_size_t>(len - ndone), MSG_WAITALL); });\n      if (ret == -1) {\n        if (LastErrorWouldBlock()) {\n          LOG(FATAL) << \"would block\";\n          return ndone;\n        }\n        Socket::Error(\"RecvAll\");\n      }\n      if (ret == 0) return ndone;\n      buf += ret;\n      ndone += ret;\n    }\n    return ndone;\n  }\n  /*!\n   * \\brief Send the data to remote.\n   * \\param data The data to be sent.\n   */\n  void SendBytes(std::string data) {\n    int datalen = data.length();\n    ICHECK_EQ(SendAll(&datalen, sizeof(datalen)), sizeof(datalen));\n    ICHECK_EQ(SendAll(data.c_str(), datalen), datalen);\n  }\n  /*!\n   * \\brief Receive the data to remote.\n   * \\return The data received.\n   */\n  std::string RecvBytes() {\n    int datalen = 0;\n    ICHECK_EQ(RecvAll(&datalen, sizeof(datalen)), sizeof(datalen));\n    std::string data;\n    data.resize(datalen);\n    ICHECK_EQ(RecvAll(&data[0], datalen), datalen);\n    return data;\n  }\n};\n\n/*! \\brief helper data structure to perform poll */\nstruct PollHelper {\n public:\n  /*!\n   * \\brief add file descriptor to watch for read\n   * \\param fd file descriptor to be watched\n   */\n  inline void WatchRead(TCPSocket::SockType fd) {\n    auto& pfd = fds[fd];\n    pfd.fd = fd;\n    pfd.events |= POLLIN;\n  }\n  /*!\n   * \\brief add file descriptor to watch for write\n   * \\param fd file descriptor to be watched\n   */\n  inline void WatchWrite(TCPSocket::SockType fd) {\n    auto& pfd = fds[fd];\n    pfd.fd = fd;\n    pfd.events |= POLLOUT;\n  }\n  /*!\n   * \\brief add file descriptor to watch for exception\n   * \\param fd file descriptor to be watched\n   */\n  inline void WatchException(TCPSocket::SockType fd) {\n    auto& pfd = fds[fd];\n    pfd.fd = fd;\n    pfd.events |= POLLPRI;\n  }\n  /*!\n   * \\brief Check if the descriptor is ready for read\n   * \\param fd file descriptor to check status\n   */\n  inline bool CheckRead(TCPSocket::SockType fd) const {\n    const auto& pfd = fds.find(fd);\n    return pfd != fds.end() && ((pfd->second.events & POLLIN) != 0);\n  }\n  /*!\n   * \\brief Check if the descriptor is ready for write\n   * \\param fd file descriptor to check status\n   */\n  inline bool CheckWrite(TCPSocket::SockType fd) const {\n    const auto& pfd = fds.find(fd);\n    return pfd != fds.end() && ((pfd->second.events & POLLOUT) != 0);\n  }\n  /*!\n   * \\brief Check if the descriptor has any exception\n   * \\param fd file descriptor to check status\n   */\n  inline bool CheckExcept(TCPSocket::SockType fd) const {\n    const auto& pfd = fds.find(fd);\n    return pfd != fds.end() && ((pfd->second.events & POLLPRI) != 0);\n  }\n  /*!\n   * \\brief wait for exception event on a single descriptor\n   * \\param fd the file descriptor to wait the event for\n   * \\param timeout the timeout counter, can be negative, which means wait until the event happen\n   * \\return 1 if success, 0 if timeout, and -1 if error occurs\n   */\n  inline static int WaitExcept(TCPSocket::SockType fd, long timeout = -1) {  // NOLINT(*)\n    pollfd pfd;\n    pfd.fd = fd;\n    pfd.events = POLLPRI;\n    return poll(&pfd, 1, timeout);\n  }\n\n  /*!\n   * \\brief perform poll on the set defined, read, write, exception\n   * \\param timeout specify timeout in milliseconds(ms) if negative, means poll will block\n   * \\return\n   */\n  inline void Poll(long timeout = -1) {  // NOLINT(*)\n    std::vector<pollfd> fdset;\n    fdset.reserve(fds.size());\n    for (auto kv : fds) {\n      fdset.push_back(kv.second);\n    }\n    int ret = poll(fdset.data(), fdset.size(), timeout);\n    if (ret == -1) {\n      Socket::Error(\"Poll\");\n    } else {\n      for (auto& pfd : fdset) {\n        auto revents = pfd.revents & pfd.events;\n        if (!revents) {\n          fds.erase(pfd.fd);\n        } else {\n          fds[pfd.fd].events = revents;\n        }\n      }\n    }\n  }\n\n  std::unordered_map<TCPSocket::SockType, pollfd> fds;\n};\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_SOCKET_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/ssize.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ssize.h\n * \\brief this file aims to define ssize_t for Windows platform\n */\n\n#ifndef TVM_SUPPORT_SSIZE_H_\n#define TVM_SUPPORT_SSIZE_H_\n\n#if defined(_MSC_VER)\n#if defined(_WIN32)\nusing ssize_t = int32_t;\n#else\nusing ssize_t = int64_t;\n#endif\n#endif\n\n#endif  // TVM_SUPPORT_SSIZE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/str_escape.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *\n * \\file support/str_escape.h\n * \\brief Print escape sequence of a string.\n */\n#ifndef TVM_SUPPORT_STR_ESCAPE_H_\n#define TVM_SUPPORT_STR_ESCAPE_H_\n\n#include <sstream>\n#include <string>\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief Create a stream with escape.\n * \\param data The data\n * \\param size The size of the string.\n * \\param use_octal_escape True to use octal escapes instead of hex. If producing C\n *      strings, use octal escapes to avoid ambiguously-long hex escapes.\n * \\return the Result string.\n */\ninline std::string StrEscape(const char* data, size_t size, bool use_octal_escape = false) {\n  std::ostringstream stream;\n  for (size_t i = 0; i < size; ++i) {\n    unsigned char c = data[i];\n    if (c >= ' ' && c <= '~' && c != '\\\\' && c != '\"') {\n      stream << c;\n    } else {\n      stream << '\\\\';\n      switch (c) {\n        case '\"':\n          stream << '\"';\n          break;\n        case '\\\\':\n          stream << '\\\\';\n          break;\n        case '\\t':\n          stream << 't';\n          break;\n        case '\\r':\n          stream << 'r';\n          break;\n        case '\\n':\n          stream << 'n';\n          break;\n        default:\n          if (use_octal_escape) {\n            stream << static_cast<unsigned char>('0' + ((c >> 6) & 0x03))\n                   << static_cast<unsigned char>('0' + ((c >> 3) & 0x07))\n                   << static_cast<unsigned char>('0' + (c & 0x07));\n          } else {\n            const char* hex_digits = \"0123456789ABCDEF\";\n            stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];\n          }\n      }\n    }\n  }\n  return stream.str();\n}\n\n/*!\n * \\brief Create a stream with escape.\n * \\param data The data\n * \\param size The size of the string.\n * \\return the Result string.\n */\ninline std::string StrEscape(const std::string& val) { return StrEscape(val.data(), val.length()); }\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_STR_ESCAPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/table_printer.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_SUPPORT_TABLE_PRINTER_H_\n#define TVM_SUPPORT_TABLE_PRINTER_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n\n/*!\n * \\brief TablePrinter is a helper class to print a table.\n *\n * \\code\n *\n * TablePrinter p;\n * p.Row() << \"ID\"\n *         << \"Latency (ms)\"\n *         << \"Speed (GFLOPS)\"\n *         << \"Trials\";\n * p.Separator();\n * p.Row() << 0 << 0.072 << 4208.59 << 6656;\n * p.Row() << 1 << 0.020 << 3804.24 << 7296;\n * p.Row() << 2 << 0.003 << 1368.10 << 320;\n * p.Row() << 3 << 0.010 << 117.75 << 128;\n * p.Row() << 4 << 0.002 << 23.75 << 320;\n * p.Row() << 5 << 0.004 << 1696.18 << 704;\n * p.Row() << 6 << 0.002 << 69.89 << 320;\n * p.Row() << 7 << 0.047 << 6394.42 << 4352;\n * p.Separator();\n * std::cout << tab.AsStr();\n *\n * \\endcode\n */\nclass TablePrinter {\n  struct Line;\n\n public:\n  /*! \\brief Create a new row */\n  inline Line Row();\n  /*! \\brief Create a row separator */\n  inline void Separator();\n  /*! \\brief Converts TablePrinter to a string */\n  inline std::string AsStr() const;\n\n private:\n  std::vector<std::vector<std::string>> tab_;\n  friend struct Line;\n\n  /*! \\brief A helper class to print a specific row in the table */\n  struct Line {\n    inline Line& operator<<(int x);\n    inline Line& operator<<(int64_t x);\n    inline Line& operator<<(double x);\n    inline Line& operator<<(const std::string& x);\n\n   private:\n    TablePrinter* p;\n    friend class TablePrinter;\n  };\n};\n\ninline TablePrinter::Line& TablePrinter::Line::operator<<(int x) {\n  p->tab_.back().push_back(std::to_string(x));\n  return *this;\n}\n\ninline TablePrinter::Line& TablePrinter::Line::operator<<(int64_t x) {\n  p->tab_.back().push_back(std::to_string(x));\n  return *this;\n}\n\ninline TablePrinter::Line& TablePrinter::Line::operator<<(double x) {\n  std::ostringstream os;\n  os << std::fixed << std::setprecision(4) << x;\n  p->tab_.back().push_back(os.str());\n  return *this;\n}\n\ninline TablePrinter::Line& TablePrinter::Line::operator<<(const std::string& x) {\n  p->tab_.back().push_back(x);\n  return *this;\n}\n\ninline TablePrinter::Line TablePrinter::Row() {\n  tab_.emplace_back();\n  Line line;\n  line.p = this;\n  return line;\n}\n\ninline void TablePrinter::Separator() { tab_.emplace_back(); }\n\ninline std::string TablePrinter::AsStr() const {\n  constexpr char kRowSep = '-';\n  constexpr char kColSep = '|';\n  if (tab_.empty()) return \"\";\n  std::vector<size_t> column_width;\n  for (const std::vector<std::string>& row : tab_) {\n    if (row.size() > column_width.size()) {\n      column_width.resize(row.size(), 0);\n    }\n    for (size_t i = 0; i < row.size(); ++i) {\n      column_width[i] = std::max(column_width[i], row[i].size());\n    }\n  }\n  ICHECK(!column_width.empty());\n  size_t total_width =\n      std::accumulate(column_width.begin(), column_width.end(), 0) + 3 * column_width.size() - 1;\n  bool is_first = true;\n  std::ostringstream os;\n  for (const std::vector<std::string>& row : tab_) {\n    if (is_first) {\n      is_first = false;\n    } else {\n      os << '\\n';\n    }\n    if (row.empty()) {\n      os << std::string(total_width, kRowSep);\n      continue;\n    }\n    for (size_t i = 0; i < column_width.size(); ++i) {\n      if (i != 0) {\n        os << kColSep;\n      }\n      std::string s = (i < row.size()) ? row[i] : \"\";\n      os << std::string(column_width[i] + 1 - s.size(), ' ') << s << ' ';\n    }\n  }\n  return os.str();\n}\n\n}  // namespace support\n}  // namespace tvm\n\n#endif  // TVM_SUPPORT_TABLE_PRINTER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/support/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file utils.h\n * \\brief Defines some common utility function..\n */\n#ifndef TVM_SUPPORT_UTILS_H_\n#define TVM_SUPPORT_UTILS_H_\n\n#include <stdio.h>\n#ifndef _WIN32\n#include <sys/types.h>\n#ifndef __hexagon__\n#include <sys/wait.h>\n#endif  // __hexagon__\n#endif  // _WIN32\n\n#include <tvm/runtime/container/string.h>\n\n#include <algorithm>\n#include <array>\n#include <cctype>\n#include <cstdlib>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace support {\n/*!\n * \\brief TVMPOpen wrapper of popen between windows / unix.\n * \\param command executed command\n * \\param type \"r\" is for reading or \"w\" for writing.\n * \\return normal standard stream\n */\n#ifndef __hexagon__\ninline FILE* TVMPOpen(const char* command, const char* type) {\n#if defined(_WIN32)\n  return _popen(command, type);\n#else\n  return popen(command, type);\n#endif\n}\n#endif  // __hexagon__\n\n/*!\n * \\brief TVMPClose wrapper of pclose between windows / linux\n * \\param stream the stream needed to be close.\n * \\return exit status\n */\n#ifndef __hexagon__\ninline int TVMPClose(FILE* stream) {\n#if defined(_WIN32)\n  return _pclose(stream);\n#else\n  return pclose(stream);\n#endif\n}\n#endif  // __hexagon__\n\n/*!\n * \\brief TVMWifexited wrapper of WIFEXITED between windows / linux\n * \\param status The status field that was filled in by the wait or waitpid function\n * \\return the exit code of the child process\n */\n#ifndef __hexagon__\ninline int TVMWifexited(int status) {\n#if defined(_WIN32)\n  return (status != 3);\n#else\n  return WIFEXITED(status);\n#endif\n}\n#endif  // __hexagon__\n\n/*!\n * \\brief TVMWexitstatus wrapper of WEXITSTATUS between windows / linux\n * \\param status The status field that was filled in by the wait or waitpid function.\n * \\return the child process exited normally or not\n */\n#ifndef __hexagon__\ninline int TVMWexitstatus(int status) {\n#if defined(_WIN32)\n  return status;\n#else\n  return WEXITSTATUS(status);\n#endif\n}\n#endif  // __hexagon__\n\n/*!\n * \\brief IsNumber check whether string is a number.\n * \\param str input string\n * \\return result of operation.\n */\ninline bool IsNumber(const std::string& str) {\n  return !str.empty() &&\n         std::find_if(str.begin(), str.end(), [](char c) { return !std::isdigit(c); }) == str.end();\n}\n\n/*!\n * \\brief split Split the string based on delimiter\n * \\param str Input string\n * \\param delim The delimiter.\n * \\return vector of strings which are splitted.\n */\ninline std::vector<std::string> Split(const std::string& str, char delim) {\n  std::string item;\n  std::istringstream is(str);\n  std::vector<std::string> ret;\n  while (std::getline(is, item, delim)) {\n    ret.push_back(item);\n  }\n  return ret;\n}\n\n/*!\n * \\brief Check whether the string starts with a given prefix.\n * \\param str The given string.\n * \\param prefix The given prefix.\n * \\return Whether the prefix matched.\n */\ninline bool StartsWith(const String& str, const char* prefix) {\n  size_t n = str.length();\n  for (size_t i = 0; i < n; i++) {\n    if (prefix[i] == '\\0') return true;\n    if (str.data()[i] != prefix[i]) return false;\n  }\n  // return true if the str is equal to the prefix\n  return prefix[n] == '\\0';\n}\n\n/*!\n * \\brief EndsWith check whether the strings ends with\n * \\param value The full string\n * \\param end The end substring\n * \\return bool The result.\n */\ninline bool EndsWith(std::string const& value, std::string const& end) {\n  if (end.size() <= value.size()) {\n    return std::equal(end.rbegin(), end.rend(), value.rbegin());\n  }\n  return false;\n}\n\n/*!\n * \\brief Execute the command\n * \\param cmd The command we want to execute\n * \\param err_msg The error message if we have\n * \\return executed output status\n */\n#ifndef __hexagon__\ninline int Execute(std::string cmd, std::string* err_msg) {\n  std::array<char, 128> buffer;\n  std::string result;\n  cmd += \" 2>&1\";\n  FILE* fd = TVMPOpen(cmd.c_str(), \"r\");\n  while (fgets(buffer.data(), buffer.size(), fd) != nullptr) {\n    *err_msg += buffer.data();\n  }\n  int status = TVMPClose(fd);\n  if (TVMWifexited(status)) {\n    return TVMWexitstatus(status);\n  }\n  return 255;\n}\n#endif  // __hexagon__\n\n/*!\n * \\brief hash an object and combines uint64_t key with previous keys\n *\n * This hash function is stable across platforms.\n *\n * \\param key The left operand.\n * \\param value The right operand.\n * \\return the combined result.\n */\ntemplate <typename T, std::enable_if_t<std::is_convertible<T, uint64_t>::value, bool> = true>\ninline uint64_t HashCombine(uint64_t key, const T& value) {\n  // XXX: do not use std::hash in this function. This hash must be stable\n  // across different platforms and std::hash is implementation dependent.\n  return key ^ (uint64_t(value) + 0x9e3779b9 + (key << 6) + (key >> 2));\n}\n\n/*!\n * \\brief Return whether a boolean flag is set as an environment variable.\n *\n * Returns true if the environment variable is set to a non-zero\n * integer, or to a non-empty string that is not an integer.\n *\n * Returns false if the environment variable is unset, if the\n * environment variable is set to the integer zero, or if the\n * environment variable is an empty string.\n */\ninline bool BoolEnvironmentVar(const char* varname) {\n  const char* var = std::getenv(varname);\n  if (!var) {\n    return false;\n  }\n\n  int x = 0;\n  std::istringstream is(var);\n  if (is >> x) {\n    return x;\n  }\n\n  return *var;\n}\n\n}  // namespace support\n}  // namespace tvm\n#endif  // TVM_SUPPORT_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/build_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n *  Common build utilities\n * \\file build_common.h\n */\n#ifndef TVM_TARGET_BUILD_COMMON_H_\n#define TVM_TARGET_BUILD_COMMON_H_\n\n#include <tvm/ir/module.h>\n#include <tvm/runtime/registry.h>\n#include <tvm/target/codegen.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/stmt.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"../runtime/meta_data.h\"\n\nnamespace tvm {\nnamespace codegen {\n\ninline std::unordered_map<std::string, runtime::FunctionInfo> ExtractFuncInfo(const IRModule& mod) {\n  std::unordered_map<std::string, runtime::FunctionInfo> fmap;\n\n  for (auto kv : mod->functions) {\n    ICHECK(kv.second->IsInstance<tir::PrimFuncNode>()) << \"Can only lower IR Module with PrimFuncs\";\n    auto f = Downcast<tir::PrimFunc>(kv.second);\n\n    runtime::FunctionInfo info;\n    for (size_t i = 0; i < f->params.size(); ++i) {\n      info.arg_types.push_back(f->params[i].dtype());\n    }\n    if (auto opt = f->GetAttr<Array<tir::IterVar>>(tir::attr::kDeviceThreadAxis)) {\n      auto thread_axis = opt.value();\n      for (size_t i = 0; i < thread_axis.size(); ++i) {\n        info.launch_param_tags.push_back(thread_axis[i]->thread_tag);\n      }\n    }\n    if (auto opt = f->GetAttr<Integer>(tir::attr::kDeviceUseDynSharedMemory)) {\n      if (opt.value().IntValue() != 0) {\n        info.launch_param_tags.push_back(runtime::launch_param::kUseDynamicSharedMemoryTag);\n      }\n    }\n    auto global_symbol = f->GetAttr<String>(tvm::attr::kGlobalSymbol);\n    fmap[static_cast<std::string>(global_symbol.value())] = info;\n  }\n  return fmap;\n}\n\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_BUILD_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/datatype/registry.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_TARGET_DATATYPE_REGISTRY_H_\n#define TVM_TARGET_DATATYPE_REGISTRY_H_\n\n#include <tvm/runtime/packed_func.h>\n#include <tvm/runtime/registry.h>\n\n#include <string>\n#include <unordered_map>\n\nnamespace tvm {\nnamespace datatype {\n\n/*!\n * \\brief Registry for custom datatypes.\n *\n * Adding custom datatypes currently requires two steps:\n * 1. Register the datatype with the registry via a call to\n *    datatype::Registry::Register. This can also be done in Python\n *    directly---see the TVM globals registered in the corresponding .cc file.\n *    Currently, user should manually choose a type name and a type code,\n *    ensuring that neither conflict with existing types.\n * 2. Use TVM_REGISTER_GLOBAL to register the lowering functions needed to\n *    lower the custom datatype. In general, these will look like:\n *      For Casts: tvm.datatype.lower.<target>.Cast.<type>.<src_type>\n *        Example: tvm.datatype.lower.llvm.Cast.myfloat.float for a Cast from\n *                 float to myfloat.\n * For intrinsic Calls: tvm.datatype.lower.<target>.Call.intrin.<name>.<type>\n *             Example: tvm.datatype.lower.llvm.Call.intrin.sqrt.myfloat\n *  For other ops: tvm.datatype.lower.<target>.<op>.<type>\n *       Examples: tvm.datatype.lower.llvm.Add.myfloat\n *                 tvm.datatype.lower.llvm.FloatImm.posit\n */\nclass Registry {\n public:\n  /*!\n   * \\brief Get the global custom datatype registry singleton\n   */\n  static Registry* Global();\n\n  /*!\n   * \\brief Register custom datatype\n   * Register a custom datatype with the given type name and type code. Currently, the type code is\n   * manually allocated by the user, and the user must ensure that no two custom types share the\n   * same code. Generally, this should be straightforward, as the user will be manually registering\n   * all of their custom types.\n   * \\param type_name The name of the type, e.g. \"posites2\"\n   * \\param type_code The type code, which should be greater than TVMArgTypeCode::kTVMExtEnd\n   */\n  void Register(const std::string& type_name, uint8_t type_code);\n\n  /*!\n   * \\brief Get type code from type name\n   * \\param type_name The type name\n   * \\return The type code\n   */\n  uint8_t GetTypeCode(const std::string& type_name);\n\n  /*!\n   * \\brief Get type name from type code\n   * \\param type_code The type code\n   * \\return The type name\n   */\n  std::string GetTypeName(uint8_t type_code);\n\n  /*!\n   * \\brief Get bool representing whether type is registered, given the type code\n   * \\param type_code The type code\n   * \\return bool representing whether the type is registered\n   */\n  inline bool GetTypeRegistered(uint8_t type_code) {\n    return code_to_name_.find(type_code) != code_to_name_.end();\n  }\n\n  /*!\n   * \\brief Get bool representing whether type is registered, given the type name\n   * \\param type_name The type name\n   * \\return bool representing whether the type is registered\n   */\n  inline bool GetTypeRegistered(std::string type_name) {\n    return name_to_code_.find(type_name) != name_to_code_.end();\n  }\n\n private:\n  // TODO(gus) is there a typedef for the code?\n  std::unordered_map<uint8_t, std::string> code_to_name_;\n  std::unordered_map<std::string, uint8_t> name_to_code_;\n};\n\n/*!\n * \\brief Convert scalar value to a custom datatype format\n * \\param type_code The custom datatype to convert to, specified by type code\n * \\param value The floating point value to convert\n * \\return The value, encoded in the bits of a uint64_t\n */\nuint64_t ConvertConstScalar(uint8_t type_code, double value);\n\n/*!\n * \\brief Get a function returning the minimum value for a datatype.\n * \\param type_code The datatype\n * \\return Function which takes the width of the datatype and returns the min value\n */\nconst runtime::PackedFunc* GetMinFunc(uint8_t type_code);\n\n/*!\n * \\brief Get lowering function for Cast ops\n * \\param target The target we are lowering to, e.g. \"llvm\"\n * \\param type_code The datatype being cast to\n * \\param src_type_code The datatype being cast from\n * \\return Lowering function for Cast ops for the provided target, type, and source type\n */\nconst runtime::PackedFunc* GetCastLowerFunc(const std::string& target, uint8_t type_code,\n                                            uint8_t src_type_code);\n\n/*!\n * \\brief Get lowering function for FloatImms\n * \\param target The target we are lowering to, e.g. \"llvm\"\n * \\param type_code The datatype of the FloatImm\n * \\return Lowering function for FloatImms for the provided target and type\n */\nconst runtime::PackedFunc* GetFloatImmLowerFunc(const std::string& target, uint8_t type_code);\n\n/*!\n * \\brief Get lowering function for intrinsic Calls/pure intrinsic Calls\n * \\param target The target we are lowering to, e.g. \"llvm\"\n * \\param type_code The datatype of the Call\n * \\param name The intrinsic name\n * \\return Lowering function for intrinsic Calls for the provided target and type\n */\nconst runtime::PackedFunc* GetIntrinLowerFunc(const std::string& target, const std::string& name,\n                                              uint8_t type_code);\n\n/*!\n * \\brief Get lowering function for other ops\n * \\param target The target we are lowering to, e.g. \"llvm\"\n * \\param type_code The datatype of the op\n * \\return Lowering function for other ops for the provided target and type\n */\n#define DEFINE_GET_LOWER_FUNC_(OP)                                                       \\\n  inline const runtime::PackedFunc* Get##OP##LowerFunc(const std::string& target,        \\\n                                                       uint8_t type_code) {              \\\n    return runtime::Registry::Get(\"tvm.datatype.lower.\" + target + \".\" #OP \".\" +         \\\n                                  datatype::Registry::Global()->GetTypeName(type_code)); \\\n  }\n\nDEFINE_GET_LOWER_FUNC_(Add)\nDEFINE_GET_LOWER_FUNC_(Sub)\nDEFINE_GET_LOWER_FUNC_(Mul)\nDEFINE_GET_LOWER_FUNC_(Div)\nDEFINE_GET_LOWER_FUNC_(Mod)\nDEFINE_GET_LOWER_FUNC_(Min)\nDEFINE_GET_LOWER_FUNC_(Max)\nDEFINE_GET_LOWER_FUNC_(EQ)\nDEFINE_GET_LOWER_FUNC_(NE)\nDEFINE_GET_LOWER_FUNC_(LT)\nDEFINE_GET_LOWER_FUNC_(LE)\nDEFINE_GET_LOWER_FUNC_(GT)\nDEFINE_GET_LOWER_FUNC_(GE)\n// Later changes may need to add more lowering functions as we support workloads with more ops.\n\n}  // namespace datatype\n}  // namespace tvm\n\n#endif  // TVM_TARGET_DATATYPE_REGISTRY_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/func_registry_generator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * Defines functions that generate FuncRegistry structs for C runtime.\n * \\file func_registry_generator.h\n */\n#ifndef TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_\n#define TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_\n\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/string.h>\n\n#include <string>\n#include <vector>\n\nusing tvm::runtime::Array;\nusing tvm::runtime::String;\n\nnamespace tvm {\nnamespace target {\n\nstd::string GenerateFuncRegistryNames(const Array<String>& function_names);\n\n}  // namespace target\n}  // namespace tvm\n\n#endif  // TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/intrin_rule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file intrin_rule.h\n * \\brief Utility to generate intrinsic rules\n */\n#ifndef TVM_TARGET_INTRIN_RULE_H_\n#define TVM_TARGET_INTRIN_RULE_H_\n\n#include <tvm/runtime/registry.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n\nnamespace tvm {\nnamespace codegen {\nnamespace intrin {\nusing namespace tir;\n\n// Add float suffix to the intrinsics\nstruct FloatSuffix {\n  std::string operator()(DataType t, std::string name) const {\n    if (t == DataType::Float(32)) {\n      return name + 'f';\n    } else if (t == DataType::Float(64)) {\n      return name;\n    } else {\n      return \"\";\n    }\n  }\n};\n\n// Return the intrinsic name\nstruct Direct {\n  std::string operator()(DataType t, std::string name) const { return name; }\n};\n\n// Call pure extern function.\ntemplate <typename T>\ninline PrimExpr DispatchPureExtern(const PrimExpr& e) {\n  const CallNode* call = e.as<CallNode>();\n  ICHECK(call != nullptr);\n  // Use string based dispatch to extern for backward compact\n  // TODO(tvm-team) replace once the new dispatching system is inplace.\n  const OpNode* op = call->op.as<OpNode>();\n  ICHECK(op != nullptr);\n  std::string name = op->name;\n  ICHECK_EQ(name.substr(0, 4), \"tir.\");\n  name = T()(call->dtype, name.substr(4));\n\n  if (name.length() != 0) {\n    Array<PrimExpr> new_args = {StringImm(name)};\n    for (auto arg : call->args) {\n      new_args.push_back(arg);\n    }\n    return Call(call->dtype, builtin::call_pure_extern(), new_args);\n  } else {\n    return e;\n  }\n}\n\n}  // namespace intrin\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_INTRIN_RULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/codegen_blob.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_blob.h\n * \\brief Code Generation of blob data\n */\n#ifndef TVM_TARGET_LLVM_CODEGEN_BLOB_H_\n#define TVM_TARGET_LLVM_CODEGEN_BLOB_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <memory>\n#include <string>\n\nnamespace llvm {\nclass Module;\n}\n\nnamespace tvm {\nnamespace codegen {\n\nclass LLVMTarget;\n\n/**\n * \\brief Code Generation of blob data\n *\n * \\param data Blob data\n * \\param system_lib Whether expose as system library.\n * \\param target_triple LLVM target triple\n *\n * \\return LLVM module and LLVM context\n */\nstd::unique_ptr<llvm::Module> CodeGenBlob(const std::string& data, bool system_lib,\n                                          LLVMTarget* llvm_target);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_CODEGEN_BLOB_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/codegen_cpu.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_llvm_cpu.h\n * \\brief Common base class for generating into LLVM IR on CPU host.\n */\n#ifndef TVM_TARGET_LLVM_CODEGEN_CPU_H_\n#define TVM_TARGET_LLVM_CODEGEN_CPU_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"codegen_llvm.h\"\n\nnamespace llvm {\nclass BasicBlock;\nclass Constant;\nclass DIBuilder;\nclass DIType;\nclass Function;\nclass FunctionType;\nclass GlobalVariable;\nclass LLVMContext;\nclass MDNode;\nclass StructType;\nclass TargetMachine;\nclass Type;\nclass Value;\n\n// Used in std::unique_ptr\nclass Module;\n}  // namespace llvm\n\nnamespace tvm {\nnamespace codegen {\n\nclass LLVMTarget;\n\n// CPU host code generation\nclass CodeGenCPU : public CodeGenLLVM {\n public:\n  CodeGenCPU();\n  virtual ~CodeGenCPU();\n\n  void Init(const std::string& module_name, LLVMTarget* llvm_target, bool system_lib,\n            bool dynamic_lookup, bool target_c_runtime) override;\n  void AddFunction(const PrimFunc& f) override;\n  void AddMainFunction(const std::string& entry_func_name) override;\n  std::unique_ptr<llvm::Module> Finish() override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  llvm::Value* CreateIntrinsic(const CallNode* op) override;\n  llvm::Value* CreateCallExtern(Type ret_type, String global_symbol, const Array<PrimExpr>& args,\n                                bool skip_first_arg) override;\n\n  /*!\n   * \\brief A CPU-specific function to create the FuncRegistry.\n   * \\param func_names List of functions to be included, in order.\n   */\n  void DefineFunctionRegistry(Array<String> func_names);\n\n  /*!\n   * \\brief Serialize the metadata object as data, and implement get_c_metadata function.\n   * \\param metadata The metadata which should be serialized.\n   */\n  void DefineMetadata(runtime::metadata::Metadata metadata);\n\n protected:\n  void AddStartupFunction() final;\n  // meta data\n  llvm::MDNode* md_tbaa_ctx_ptr_{nullptr};\n  // TVM related data types\n  llvm::Type* t_tvm_shape_index_{nullptr};\n  llvm::Type* t_tvm_func_handle_{nullptr};\n  llvm::StructType* t_tvm_device_{nullptr};\n  llvm::StructType* t_tvm_type_{nullptr};\n  llvm::StructType* t_tvm_array_{nullptr};\n  llvm::StructType* t_tvm_value_{nullptr};\n  llvm::StructType* t_tvm_parallel_group_env_{nullptr};\n\n  llvm::FunctionType* ftype_tvm_backend_packed_c_func_{nullptr};\n  llvm::StructType* t_tvm_crt_func_registry_{nullptr};\n  llvm::StructType* t_tvm_crt_module_{nullptr};\n\n  llvm::FunctionType* ftype_tvm_parallel_lambda_{nullptr};\n  llvm::FunctionType* ftype_tvm_func_call_{nullptr};\n  llvm::FunctionType* ftype_tvm_get_func_from_env_{nullptr};\n  llvm::FunctionType* ftype_tvm_api_set_last_error_{nullptr};\n  llvm::FunctionType* ftype_tvm_parallel_launch_{nullptr};\n  llvm::FunctionType* ftype_tvm_parallel_barrier_{nullptr};\n  llvm::FunctionType* ftype_tvm_register_system_symbol_{nullptr};\n  // Lazy entry for function call.\n  llvm::FunctionType* ftype_tvm_static_init_callback_{nullptr};\n  llvm::FunctionType* ftype_tvm_static_init_{nullptr};\n\n private:\n  // the parallel group information\n  struct ParallelEnv {\n    Var task_id;\n    Var num_task;\n    bool stride_pattern{false};\n    bool in_parallel_loop{false};\n    int parallel_loop_count{0};\n    llvm::Value* penv{nullptr};\n  };\n  // Get runtime functions\n  void InitGlobalContext(bool dynamic_lookup);\n  llvm::GlobalVariable* InitContextPtr(llvm::Type* type, std::string name);\n  llvm::Value* GetContextPtr(llvm::GlobalVariable* gv);\n  llvm::Value* RuntimeTVMFuncCall();\n  llvm::Value* RuntimeTVMGetFuncFromEnv();\n  llvm::Value* RuntimeTVMAPISetLastError();\n  llvm::Value* RuntimeTVMParallelLaunch();\n  llvm::Value* RuntimeTVMParallelBarrier();\n  llvm::Value* CreateStaticHandle();\n  llvm::Value* GetPackedFuncHandle(const std::string& str);\n  TypedPointer PackClosureData(const Array<Var>& fields, uint64_t* num_bytes,\n                               std::string struct_name = \"\");\n  TypedPointer CreateStructRefPtr(DataType t, llvm::Value* buffer, llvm::Value* index, int kind);\n  void UnpackClosureData(TypedPointer cdata, const Array<Var>& fields,\n                         std::unordered_map<const VarNode*, llvm::Value*>* vmap);\n  // Make packed call.\n  struct PackedCall {\n    llvm::Value* ret_value;\n    llvm::Value* ret_tcode;\n    llvm::BasicBlock* end_block;\n  };\n  PackedCall MakeCallPackedLowered(const Array<PrimExpr>& args, const DataType& r_type,\n                                   const int64_t begin, const int64_t end, bool use_string_lookup);\n  // create call into tvm packed function.\n  llvm::Value* CreateCallPacked(const CallNode* op, bool use_string_lookup);\n  // Create trace call into tvm packed function.\n  llvm::Value* CreateCallTracePacked(const CallNode* op);\n  // Create static initialization\n  void CreateStaticInit(const std::string& init_fname, const Stmt& body);\n  // Create parallel launch\n  void CreateParallelLaunch(const Stmt& body, int num_task, std::string name = \"\");\n  // Create a new compute scope.\n  void CreateComputeScope(const AttrStmtNode* op);\n  // Check if the call to packed function is successful\n  // if not directly finalize function and pass on return code.\n  // return the end block after the check\n  llvm::BasicBlock* CheckCallSuccess(llvm::Value* retcode);\n  // Context for injection lookup\n  llvm::GlobalVariable* gv_mod_ctx_{nullptr};\n  llvm::GlobalVariable* gv_tvm_func_call_{nullptr};\n  llvm::GlobalVariable* gv_tvm_get_func_from_env_{nullptr};\n  llvm::GlobalVariable* gv_tvm_api_set_last_error_{nullptr};\n  llvm::GlobalVariable* gv_tvm_parallel_launch_{nullptr};\n  llvm::GlobalVariable* gv_tvm_parallel_barrier_{nullptr};\n  std::unordered_map<String, llvm::GlobalVariable*> gv_func_map_;\n  // context for direct dynamic lookup\n  llvm::Function* f_tvm_func_call_{nullptr};\n  llvm::Function* f_tvm_get_func_from_env_{nullptr};\n  llvm::Function* f_tvm_api_set_last_error_{nullptr};\n  llvm::Function* f_tvm_parallel_launch_{nullptr};\n  llvm::Function* f_tvm_parallel_barrier_{nullptr};\n  llvm::Function* f_tvm_register_system_symbol_{nullptr};\n  // Current parallel environment scope.\n  ParallelEnv parallel_env_;\n  // global to packed function handle\n  std::unordered_map<std::string, llvm::GlobalVariable*> func_handle_map_;\n  // List of symbols to be exported to TVM system lib.\n  std::vector<std::pair<std::string, llvm::Constant*>> export_system_symbols_;\n  // List of functions to be registered in the FuncRegistry, if generated.\n  std::vector<std::pair<std::string, llvm::Function*>> registry_functions_;\n  // internal debug information, to be populated by\n  std::unique_ptr<DebugInfo> dbg_info_;\n  bool target_c_runtime_;\n  bool is_system_lib_;\n\n  // Get the DWARF type corresponding to the LLVM type |ty|. The current API in practice only\n  // generates |int32|, and |int8*|.\n  llvm::DIType* GetDebugType(const Type& ty_tir, llvm::Type* ty_llvm);\n  // Adds the DWARF debug information for |function| to |dbg_info_|.\n  void AddDebugInformation(PrimFunc f_tir, llvm::Function* f_llvm);\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_CODEGEN_CPU_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/codegen_llvm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_llvm.h\n * \\brief Common base class for generating into LLVM IR\n */\n#ifndef TVM_TARGET_LLVM_CODEGEN_LLVM_H_\n#define TVM_TARGET_LLVM_CODEGEN_LLVM_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <llvm/ADT/ArrayRef.h>\n#include <llvm/ADT/StringRef.h>\n#include <llvm/IR/BasicBlock.h>\n#include <llvm/IR/ConstantFolder.h>\n#include <llvm/IR/Constants.h>\n#include <llvm/IR/DerivedTypes.h>\n#if TVM_LLVM_VERSION >= 150\n#include <llvm/IR/FMF.h>\n#else\n#include <llvm/IR/Operator.h>\n#endif\n#include <llvm/IR/GlobalValue.h>\n#include <llvm/IR/IRBuilder.h>\n#include <llvm/IR/Instructions.h>\n#include <llvm/IR/Intrinsics.h>\n#include <llvm/Support/Casting.h>\n#if TVM_LLVM_VERSION >= 140\n#include <llvm/MC/TargetRegistry.h>\n#else\n#include <llvm/Support/TargetRegistry.h>\n#endif\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/ir/module.h>\n#include <tvm/target/codegen.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op.h>\n#include <tvm/tir/op_attr_types.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../../runtime/thread_storage_scope.h\"\n#include \"../../tir/transforms/ir_utils.h\"\n#include \"codegen_params.h\"\n\nnamespace llvm {\nclass Argument;\nclass CallInst;\nclass Function;\nclass GlobalVariable;\nclass Instruction;\nclass PassManagerBuilder;\nclass DIFile;\nclass DICompileUnit;\nclass MDNode;\n\n// Used in std::unique_ptr\nclass Module;\nclass DataLayout;\nclass DIBuilder;\nclass MDBuilder;\n}  // namespace llvm\n\nnamespace tvm {\nnamespace codegen {\n\nclass LLVMTarget;\n\nusing namespace tir;\n\n/*!\n * \\brief A base class to generate a LLVM.\n */\nclass CodeGenLLVM : public ExprFunctor<llvm::Value*(const PrimExpr&)>,\n                    public StmtFunctor<void(const Stmt&)> {\n public:\n  CodeGenLLVM();           // Do not make it default here.\n  virtual ~CodeGenLLVM();  // Do not make it default here.\n\n  /*!\n   * \\brief Create new code generator based on target machine.\n   * \\param tm The target machine\n   * \\return The created llvm generator.\n   */\n  static std::unique_ptr<CodeGenLLVM> Create(LLVMTarget* llvm_target);\n  /*!\n   * \\brief Initialize the code generator with given context\n   * \\param module_name The name of the module.\n   * \\param tm Target machine model\n   * \\param ctx The context.\n   * \\param system_lib Whether to insert system library registration.\n   * \\param dynamic_lookup Whether dynamically lookup runtime function\n   *                       or use the runtime function table passed by caller.\n   * \\param target_c_runtime If true, generate a module to be executed by the C runtime. In practice\n   *                       this option influences whether global ctors are used.\n   */\n  virtual void Init(const std::string& module_name, LLVMTarget* llvm_target, bool system_lib,\n                    bool dynamic_lookup, bool target_c_runtime);\n\n  /*!\n   * \\brief Turn on fast math flags for floating point operations.\n   * \\param fmf FastMathFlags to use for code generation.\n   */\n  void SetFastMathFlags(llvm::FastMathFlags fmf);\n\n  /*!\n   * \\brief Compile and add function f to the current module.\n   * \\param f The function to be added.\n   */\n  virtual void AddFunction(const PrimFunc& f);\n  /*!\n   * \\brief Add main function as the entry name\n   * \\param entry_func_name The name of entry function to be added.\n   */\n  virtual void AddMainFunction(const std::string& entry_func_name);\n  /*!\n   * \\brief Finish current pass of codegen, get the module.\n   * \\return the created module.\n   */\n  virtual std::unique_ptr<llvm::Module> Finish();\n  /*!\n   * \\brief Add functions from the (unordered) range to the current module in a deterministic order.\n   *        The range consists of objects convertible to PrimFunc.\n   * \\param begin The beginning of the range.\n   * \\param end The end of the range.\n   * \\param pfunc Converter function from the range element type to PrimFunc.\n   */\n  template <typename IterType, typename ConvType>\n  void AddFunctionsOrdered(IterType begin, IterType end, ConvType pfunc);\n  /*!\n   * \\brief Add functions from the (unordered) range of elements of type PrimFunc to the current\n   *        module in a deterministic order.\n   * \\param begin The beginning of the range.\n   * \\param end The end of the range.\n   */\n  template <typename IterType>\n  void AddFunctionsOrdered(IterType begin, IterType end) {\n    this->AddFunctionsOrdered(begin, end, [](auto f) { return f; });\n  }\n  /*!\n   * \\brief Add mod to be linked with the generated module\n   * \\param mod The module to be linked.\n   */\n  void AddLinkModule(std::unique_ptr<llvm::Module>&& mod);\n  /*!\n   * \\brief Create Value for expression e\n   * \\param e The expression to be created value for.\n   * \\return created value.\n   */\n  llvm::Value* MakeValue(const PrimExpr& e) { return VisitExpr(e); }\n  // Short hande code to get a constant int 32\n  llvm::Constant* ConstInt32(int64_t value) const {\n    return llvm::ConstantInt::getSigned(t_int32_, value);\n  }\n  // override codegen\n  llvm::Value* VisitExpr_(const VarNode* op) override;\n  llvm::Value* VisitExpr_(const CastNode* op) override;\n  llvm::Value* VisitExpr_(const IntImmNode* op) override;\n  llvm::Value* VisitExpr_(const FloatImmNode* op) override;\n  llvm::Value* VisitExpr_(const StringImmNode* op) override;\n  llvm::Value* VisitExpr_(const AddNode* op) override;\n  llvm::Value* VisitExpr_(const SubNode* op) override;\n  llvm::Value* VisitExpr_(const MulNode* op) override;\n  llvm::Value* VisitExpr_(const DivNode* op) override;\n  llvm::Value* VisitExpr_(const ModNode* op) override;\n  llvm::Value* VisitExpr_(const MinNode* op) override;\n  llvm::Value* VisitExpr_(const MaxNode* op) override;\n  llvm::Value* VisitExpr_(const LTNode* op) override;\n  llvm::Value* VisitExpr_(const LENode* op) override;\n  llvm::Value* VisitExpr_(const GTNode* op) override;\n  llvm::Value* VisitExpr_(const GENode* op) override;\n  llvm::Value* VisitExpr_(const EQNode* op) override;\n  llvm::Value* VisitExpr_(const NENode* op) override;\n  llvm::Value* VisitExpr_(const AndNode* op) override;\n  llvm::Value* VisitExpr_(const OrNode* op) override;\n  llvm::Value* VisitExpr_(const NotNode* op) override;\n  llvm::Value* VisitExpr_(const SelectNode* op) override;\n  llvm::Value* VisitExpr_(const LetNode* op) override;\n  llvm::Value* VisitExpr_(const LoadNode* op) override;\n  llvm::Value* VisitExpr_(const BufferLoadNode* op) override;\n  llvm::Value* VisitExpr_(const CallNode* op) override;\n  llvm::Value* VisitExpr_(const RampNode* op) override;\n  llvm::Value* VisitExpr_(const ShuffleNode* op) override;\n  llvm::Value* VisitExpr_(const BroadcastNode* op) override;\n  // stmt\n  void VisitStmt_(const StoreNode* op) override;\n  void VisitStmt_(const BufferStoreNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const WhileNode* op) override;\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const AllocateNode* op) override;\n  void VisitStmt_(const AllocateConstNode* op) override;\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const LetStmtNode* op) override;\n  void VisitStmt_(const SeqStmtNode* op) override;\n  void VisitStmt_(const EvaluateNode* op) override;\n\n  // Get constant string\n  llvm::Constant* GetConstString(const std::string& str);\n\n  llvm::Constant* GetGlobalConstant(\n      llvm::Constant* const_data, const std::string& name = \"\",\n      llvm::GlobalValue::LinkageTypes linkage_type = llvm::GlobalValue::InternalLinkage);\n\n protected:\n  /*!\n   * \\brief Address and type pair to assist in handling opaque pointers.\n   */\n  struct TypedPointer {\n    TypedPointer() = default;\n    TypedPointer(llvm::Type* t, llvm::Value* a) : type(t), addr(a) {}\n    llvm::Type* type = nullptr;  /*!< Type of the value pointed to. */\n    llvm::Value* addr = nullptr; /*!< Address of the value.         */\n  };\n  /*! \\brief The storage information */\n  struct StorageInfo {\n    /*! \\brief The alignment of allocation */\n    int alignment{0};\n  };\n  /*!\n   * \\brief Convert tvm::runtime::String into llvm::StringRef\n   */\n  static llvm::StringRef MakeStringRef(const String& string) {\n    return llvm::StringRef(string.c_str(), string.size());\n  }\n  /*!\n   * \\brief Execute falloca at the beginning of the\n   *  currrent function and obtain its return value.\n   *\n   *  This is a helper function to make sure that\n   *  alloca always happen in the beginning of the function.\n   *\n   * \\param falloca The allocation function to be executed.\n   * \\tparam F The function to be executed.\n   * \\return The result.\n   */\n  template <typename F>\n  llvm::AllocaInst* WithFunctionEntry(F falloca) {\n    llvm::BasicBlock* current = builder_->GetInsertBlock();\n    llvm::BasicBlock* entry = &(function_->getEntryBlock());\n    builder_->SetInsertPoint(entry, entry->begin());\n    llvm::AllocaInst* res = falloca();\n    builder_->SetInsertPoint(current);\n    return res;\n  }\n  // create intrinstic given call\n  virtual llvm::Value* CreateIntrinsic(const CallNode* op);\n  // create extern function call\n  // skip first arg mode used for call extern intrinsic.\n  virtual llvm::Value* CreateCallExtern(Type ret_type, String global_symbol,\n                                        const Array<PrimExpr>& args, bool skip_first_arg);\n\n  /*! \\brief Insert a printf() call to the generated LLVM\n   *\n   * This is intended solely for debugging purposes.  After calling\n   * printf(), immediately calls fflush() to flush the stdout buffer\n   * in case of segfault.\n   */\n  virtual void CreatePrintf(const std::string& format, llvm::ArrayRef<llvm::Value*> format_args);\n\n  /*! \\brief Lookup return address, for debugging purposes\n   *\n   * This is intended solely for debugging purposes.  Calls the\n   * `llvm::Intrinsic::returnaddress`, returning the return address of\n   * the current function call.\n   *\n   * \\param level Look up the return address of a frame `level` steps\n   * above the current stack frame.\n   */\n  llvm::Value* CreateLookupReturnAddress(unsigned int level = 0);\n\n  // Get the corresponding thread index\n  virtual llvm::Value* GetThreadIndex(const IterVar& iv);\n  // Get the corresponding thread index\n  virtual llvm::Value* CreateStorageSync(const CallNode* op);\n  // apply optimization on the module.\n  virtual void InitPassManagerBuilder(llvm::PassManagerBuilder* builder);\n  // Scalarize by iterating elements of e.\n  // f is a callback that takes index and v.\n  void Scalarize(const PrimExpr& e, std::function<void(int i, llvm::Value* v)> f);\n\n  /* \\brief Helper function for handling buffer access\n   *\n   * \\param buffer The buffer being accessed\n   *\n   * \\param indices The indices at which the buffer is being accessed.\n   *\n   * \\param value_dtype The datatype to be read from (BufferLoad) or\n   * written to (BufferStore) the buffer.\n   *\n   * \\param make_instruction A callback function that generates that\n   * actual call.\n   *\n   *       - buffer_ptr: A typed pointer to the element being accessed\n   *\n   *       - subelement_i: The index of a vectorized type to be\n   *         stored/loaded.  If -1, indicates that the entire type,\n   *         vector or scalar, should be written.\n   *\n   *       - alignment: The alignment to be used for the read/write.\n   *\n   *       - is_volatile: Whether the read/write should be volatile.\n   *\n   *       - Should return the generated expression.\n   */\n  void BufferAccessHelper(\n      Buffer buffer, Array<PrimExpr> indices, DataType value_dtype,\n      std::function<llvm::Instruction*(TypedPointer buffer_ptr, int subelement_i, int alignment,\n                                       bool is_volatile)>\n          make_instruction);\n  // Initialize target\n  virtual void InitTarget();\n  // Add module startup function if needed.\n  virtual void AddStartupFunction() {}\n  // apply optimization on the module.\n  virtual void Optimize();\n  // Get the maximim storage align bits of buffer pointer given storage scope.\n  virtual int NativeVectorBits(const runtime::StorageScope& storage_scope) const;\n  // Get correct address space depending on the backend\n  virtual unsigned GetGlobalAddressSpace() const;\n  void AddFunctionInternal(const PrimFunc& f, bool ret_void);\n  // Create extern call\n  llvm::CallInst* CreateCallExtern(llvm::Type* ret, const std::string& name,\n                                   const std::vector<llvm::Value*>& value);\n  /*!\n   * \\brief Get the LLVM Type for a given runtime type.\n   * \\param dtype The runtime dtype.\n   *\n   * \\note Only use this function for dealing with PrimTypes.\n   *       For Call and Var that could have more refined types,\n   *       use GetLLVMType instead.\n   *\n   * \\return LLVM type of dtype\n   */\n  llvm::Type* DTypeToLLVMType(const DataType& dtype) const;\n  /*!\n   * \\brief Get the LLVM Type for a given type.\n   * \\param dtype The runtime dtype.\n   * \\param type The corresponding TVM Type.\n   */\n  llvm::Type* GetLLVMType(const Type& type) const;\n  /*!\n   * \\brief Get the LLVM Type for a given type.\n   * \\param dtype The runtime dtype.\n   * \\param type The corresponding TVM Type.\n   */\n  llvm::Type* GetLLVMType(const PrimExpr& expr) const;\n  /*!\n   * \\brief Get the declaration of the LLVM intrinsic based on the intrinsic\n   *        id, and the type of the actual call.\n   *\n   * \\param id The intrinsic id.\n   * \\param ret_type The call return type.\n   * \\param arg_types The types of the call arguments.\n   *\n   * \\return Return the llvm::Function pointer, or nullptr if the declaration\n   *         could not be generated (e.g. if the argument/return types do not\n   *         match).\n   */\n  llvm::Function* GetIntrinsicDecl(llvm::Intrinsic::ID id, llvm::Type* ret_type,\n                                   llvm::ArrayRef<llvm::Type*> arg_types);\n  /*!\n   * \\brief Set target-related attributes on the LLVM function \\p func. This\n   *        includes \"target-cpu\" and \"target-features\" if present.\n   *\n   * \\param func The function to set attributes on.\n   */\n  void SetTargetAttributes(llvm::Function* func);\n  /*!\n   * \\brief Emit LLVM IR for conversion functions __extendhfsf2 and __truncsfhf2\n   *        into the current llvm::Module.\n   *\n   * \\param use_float16_abi Whether to use floating-point or integer ABI.\n   */\n  void EmitFloat16ConversionBuiltins(bool use_float16_abi);\n\n  /*!\n   * \\brief Get the number of elements in the given vector value.\n   * \\param vec The value, must be of a vector type.\n   */\n  inline int GetVectorNumElements(llvm::Value* vec);\n  // initialize the function state.\n  void InitFuncState();\n  // Get alignment given index.\n  void GetAlignment(DataType t, const VarNode* buf_var, const PrimExpr& index, int* p_alignment,\n                    int* p_native_bits);\n  // Returns whether the LLVM type has padding for alignment\n  bool HasAlignmentPadding(DataType dtype);\n  // do a scalarize call with f\n  llvm::Value* CreateScalarizedCall(const CallNode* op, llvm::Function* f,\n                                    const std::vector<llvm::Value*>& args);\n  // handle module import\n  void HandleImport(const std::string& code);\n  // cast operatpr\n  llvm::Value* CreateCast(DataType from, DataType to, llvm::Value* value);\n  // comparison op\n  llvm::Value* GetVarValue(const VarNode* v) const;\n  llvm::Value* CreateLT(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateLE(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateGT(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateGE(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateAdd(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateSub(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateMul(DataType t, llvm::Value* a, llvm::Value* b);\n  llvm::Value* CreateBroadcast(llvm::Value* value, int lanes);\n  virtual TypedPointer CreateBufferPtr(llvm::Value* buffer_ptr, DataType buffer_element_dtype,\n                                       llvm::ArrayRef<llvm::Value*> indices, DataType value_dtype);\n  // Vector concatenation.\n  llvm::Value* CreateVecSlice(llvm::Value* vec, int begin, int extent);\n  llvm::Value* CreateVecFlip(llvm::Value* vec);\n  llvm::Value* CreateVecConcat(std::vector<llvm::Value*> vecs);\n  llvm::Value* CreateVecPad(llvm::Value* vec, int target_lanes);\n  // Create serial for\n  void CreateSerialFor(llvm::Value* begin, llvm::Value* end, llvm::Value* stride,\n                       const Var& loop_var, const Stmt& body);\n  // add alias information.\n  void AddAliasInfo(llvm::Instruction* inst, const VarNode* buffer_var, PrimExpr index,\n                    DataType access_dtype);\n\n  llvm::GlobalVariable* AllocateSharedMemory(DataType dtype, size_t size,\n                                             unsigned int shared_address_space, int alignment,\n                                             llvm::GlobalValue::LinkageTypes linkage);\n\n  /*!\n   * \\brief Get the `i`th argument to the given function, respecting LLVM API changes.\n   *\n   * NOTE: in LLVM < 10.0, the underlying API returns a const llvm::Argument*. To provide a uniform\n   * API, const is removed here. Proper usage of LLVM APIs depends on having a non-const Argument*,\n   * so we take this appraoch here rather than adding const.\n   *\n   * \\param function The function containing the arguments.\n   * \\param i The index of the argument to retrieve.\n   * \\return The retrieved argument.\n   */\n  llvm::Argument* GetArg(const llvm::Function* function, int i) const {\n#if TVM_LLVM_VERSION >= 100\n    return function->getArg(i);\n#elif TVM_LLVM_VERSION >= 50\n    return const_cast<llvm::Argument*>(&function->arg_begin()[i]);\n#else\n    return const_cast<llvm::Argument*>(&*std::next(function->arg_begin(), i));\n#endif\n  }\n\n  // The IRBuilder.\n  using IRBuilder = llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>;\n  // The current function\n  llvm::Function* function_;\n  // Internal builder\n  std::unique_ptr<IRBuilder> builder_;\n  // The module to be returned;\n  std::unique_ptr<llvm::Module> module_;\n  std::unique_ptr<llvm::DataLayout> data_layout_;\n  // Internal metabuilder\n  std::unique_ptr<llvm::MDBuilder> md_builder_;\n  // llvm target info\n  LLVMTarget* llvm_target_{nullptr};\n  // helpful data types\n  llvm::Type* t_void_{nullptr};\n  llvm::PointerType* t_void_p_{nullptr};\n  llvm::Type* t_int_{nullptr};\n  llvm::Type* t_char_{nullptr};\n  llvm::Type* t_int8_{nullptr};\n  llvm::Type* t_int16_{nullptr};\n  llvm::Type* t_int32_{nullptr};\n  llvm::Type* t_int64_{nullptr};\n  llvm::Type* t_float64_{nullptr};\n  // meta data\n  llvm::MDNode* md_very_likely_branch_{nullptr};\n  llvm::MDNode* md_tbaa_root_{nullptr};\n  llvm::MDNode* md_tbaa_alias_set_{nullptr};\n  // modules to be linked.\n  std::vector<std::unique_ptr<llvm::Module>> link_modules_;\n  /*! \\brief native vector bits of current targetx*/\n  int native_vector_bits_{0};\n  /*! \\brief the storage scope of allocation */\n  std::unordered_map<const VarNode*, StorageInfo> alloc_storage_info_;\n  // The definition of local variable.\n  std::unordered_map<const VarNode*, llvm::Value*> var_map_;\n  // global strings\n  std::unordered_map<std::string, llvm::Constant*> str_map_;\n  // Whether current function is restricted\n  bool is_restricted_{true};\n  // The analyzer information\n  std::unique_ptr<arith::Analyzer> analyzer_;\n  // set of var that are not restricted(can alias)\n  std::unordered_set<const VarNode*> alias_var_set_;\n  // set of volatile buffer.\n  std::unordered_set<const VarNode*> volatile_buf_;\n  // deep comparison of PrimExpr\n  ExprDeepEqual deep_equal_;\n  // binding of let variables. Enables duplicate var defs that map to same value\n  std::unordered_map<Var, const LetNode*, ObjectPtrHash, ObjectPtrEqual> let_binding_;\n  // Cache potential common path ops to slightly improve lookup time.\n  // global symbol table.\n  OpAttrMap<TGlobalSymbol> op_attr_global_symbol_ = Op::GetAttrMap<TGlobalSymbol>(\"TGlobalSymbol\");\n  const Op& builtin_call_extern_ = builtin::call_extern();\n  const Op& builtin_call_pure_extern_ = builtin::call_pure_extern();\n  const Op& builtin_call_llvm_intrin_ = builtin::call_llvm_intrin();\n  const Op& builtin_call_llvm_pure_intrin_ = builtin::call_llvm_pure_intrin();\n  const Op& builtin_lookup_param_ = builtin::lookup_param();\n  const Op& builtin_tvm_call_cpacked_lowered_ = builtin::tvm_call_cpacked_lowered();\n\n  /*! \\brief Helper struct for debug infos. */\n  struct DebugInfo {\n    ~DebugInfo();  // Because of the std::unique_ptr.\n    std::unique_ptr<llvm::DIBuilder> di_builder_;\n    llvm::DICompileUnit* compilation_unit_{nullptr};\n    llvm::DIFile* file_{nullptr};\n  };\n  /*!\n   * \\brief Create a new DebugInfo struct from the given Module that\n   *  initializes file and compilation_unit_ to TVM defaults.\n   */\n  static std::unique_ptr<DebugInfo> CreateDebugInfo(llvm::Module* module);\n};\n\ninline int CodeGenLLVM::GetVectorNumElements(llvm::Value* vec) {\n#if TVM_LLVM_VERSION >= 120\n  return llvm::cast<llvm::FixedVectorType>(vec->getType())->getNumElements();\n#else\n  return llvm::cast<llvm::VectorType>(vec->getType())->getNumElements();\n#endif\n}\n\ntemplate <typename IterType, typename ConvType>\nvoid CodeGenLLVM::AddFunctionsOrdered(IterType begin, IterType end, ConvType pfunc) {\n  std::vector<PrimFunc> funcs;\n  for (auto it = begin; it != end; ++it) {\n    funcs.push_back(pfunc(*it));\n  }\n  std::sort(funcs.begin(), funcs.end(), [](PrimFunc func_a, PrimFunc func_b) {\n    std::string name_a = func_a->GetAttr<String>(tvm::attr::kGlobalSymbol).value();\n    std::string name_b = func_b->GetAttr<String>(tvm::attr::kGlobalSymbol).value();\n    return name_a < name_b;\n  });\n  for (auto& f : funcs) {\n    auto global_symbol = f->GetAttr<String>(tvm::attr::kGlobalSymbol);\n    AddFunction(f);\n  }\n}\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_CODEGEN_LLVM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/codegen_params.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_params.h\n */\n\n#ifndef TVM_TARGET_LLVM_CODEGEN_PARAMS_H_\n#define TVM_TARGET_LLVM_CODEGEN_PARAMS_H_\n\n#include <tvm/runtime/ndarray.h>\n\nnamespace llvm {\nclass ConstantArray;\nclass LLVMContext;\n}  // namespace llvm\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n * \\brief Convert an NDArray to an LLVM array of constants.\n *\n * The supplied NDArray is flattened, and each element is converted to the appropriate LLVM type.\n *\n * \\param ctx LLVM context used to create the various primitive datatypes.\n * \\param arr NDArray to convert.\n * \\return LLVM array containing the array data.\n */\nllvm::ConstantArray* NDArrayToLLVMArray(llvm::LLVMContext* ctx, tvm::runtime::NDArray arr);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_LLVM_CODEGEN_PARAMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/intrin_rule_llvm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file intrin_rule_llvm.h\n * \\brief Common utilities for llvm intrinsics.\n */\n#ifndef TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_\n#define TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <tvm/runtime/registry.h>\n#include <tvm/target/codegen.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n\nnamespace tvm {\nnamespace codegen {\n// num_signature means number of arguments used to query signature\ntemplate <unsigned id, int num_signature>\ninline PrimExpr DispatchLLVMPureIntrin(const PrimExpr& e) {\n  const tir::CallNode* call = e.as<tir::CallNode>();\n  ICHECK(call != nullptr);\n  Array<PrimExpr> cargs;\n  // intrin id.\n  cargs.push_back(IntImm(DataType::UInt(32), id));\n  cargs.push_back(IntImm(DataType::UInt(32), num_signature));\n\n  for (PrimExpr arg : call->args) {\n    cargs.push_back(arg);\n  }\n  return tir::Call(call->dtype, tir::builtin::call_llvm_pure_intrin(), cargs);\n}\n\ntemplate <unsigned id, int num_signature>\ninline PrimExpr DispatchLLVMIntrin(const PrimExpr& e) {\n  const tir::CallNode* call = e.as<tir::CallNode>();\n  ICHECK(call != nullptr);\n  Array<PrimExpr> cargs;\n  // intrin id.\n  cargs.push_back(IntImm(DataType::UInt(32), id));\n  cargs.push_back(IntImm(DataType::UInt(32), num_signature));\n  for (PrimExpr arg : call->args) {\n    cargs.push_back(arg);\n  }\n  return tir::Call(call->dtype, tir::builtin::call_llvm_intrin(), cargs);\n}\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/llvm_instance.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*! \\file llvm_instance.h\n */\n#ifndef TVM_TARGET_LLVM_LLVM_INSTANCE_H_\n#define TVM_TARGET_LLVM_LLVM_INSTANCE_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <llvm/ADT/ArrayRef.h>\n#if TVM_LLVM_VERSION >= 150\n#include <llvm/IR/FMF.h>\n#else\n#include <llvm/IR/Operator.h>\n#endif\n#include <llvm/Support/CodeGen.h>\n#include <llvm/Target/TargetOptions.h>\n#include <tvm/ir/expr.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/container/optional.h>\n#include <tvm/runtime/container/string.h>\n#include <tvm/target/target.h>\n\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace llvm {\nclass LLVMContext;\nclass MemoryBuffer;\nclass Module;\nclass TargetMachine;\n}  // namespace llvm\n\nnamespace tvm {\nnamespace codegen {\n\nclass LLVMTarget;\n\n/*!\n * \\class LLVMInstance\n * \\brief LLVMInstance is a class that (conceptually) starts and stops LLVM.\n *        All uses of LLVM should take place within a lifetime of an object\n *        of this class.\n *\n * E.g.\n * ```{.cpp}\n * {\n *   LLVMInstance llvm_instance;\n *   ...\n *   someFunctionFromLLVM(...);\n *   ...\n * }\n * // no more calls to LLVM here\n * ```\n * In addition to that, LLVMInstance provides an LLVM context (llvm::LLVMContext).\n * The context is a structure in LLVM where common IR constructs are maintained,\n * (such as types, constants, etc.) so that they can be identified by their\n * address (i.e. pointer comparison). Because of that, it's important to use\n * the same context throughout compilation.\n *\n * At the moment the \"starting\" of LLVM performs initialization of LLVM, but\n * \"stopping\" doesn't do anything. In the future, if such a need arises, this\n * functionality may be extended to perform dlopen/dlclose of the LLVM-based\n * code in TVM.\n *\n * This class provides means to deserialize an LLVM module, either from text\n * (in a string), or from a file. In either case, the serialized module can\n * be LLVM IR assembly, or binary bitcode enconding.\n */\nclass LLVMInstance {\n public:\n  /*!\n   * \\brief Constructs LLVMInstance\n   */\n  LLVMInstance();\n  /*!\n   * \\brief Destroys LLVMInstance object\n   */\n  ~LLVMInstance();  // Must not be \"= default\" here in the header file.\n\n  /*!\n   * \\brief Get the LLVM context for this scope.\n   */\n  std::shared_ptr<llvm::LLVMContext> GetContext() const { return ctx_; }\n\n  /*!\n   * \\brief Create `llvm::Module` from a string.\n   *\n   * Parse the string in \\param llvm_ir, and return the `llvm::Module`.\n   * At the moment this function will abort if the parsing fails.\n   * \\param llvm_ir string with the LLVM IR assembly or bitcode\n   * \\return created `llvm::Module`\n   */\n  std::unique_ptr<llvm::Module> ParseIR(const std::string& llvm_ir) const;\n  /*!\n   * \\brief Load `llvm::Module` from a given file\n   *\n   * Read the file \\param file_name, and return the `llvm::Module`.\n   * At the moment this function will abort if reading of the file or creation\n   * of the module fails.\n   * \\param file_name file with the LLVM IR assembly or bitcode\n   * \\return created `llvm::Module`\n   */\n  std::unique_ptr<llvm::Module> LoadIR(const std::string& file_name) const;\n\n private:\n  std::unique_ptr<llvm::Module> ParseBuffer(const llvm::MemoryBuffer& buffer) const;\n\n  std::shared_ptr<llvm::LLVMContext> ctx_;\n};\n\n/*!\n * \\class LLVMTargetInfo\n * \\brief Summary of information for this TVM target relevant to LLVM code\n *        generation.\n *\n * This class contains all information that LLVM needs for code generation for\n * a particular target. The purpose of this class is only to provide information\n * in an easily-accessible form (for example for querying the target properties).\n *\n * Note that objects of this class must be created within the lifetime of an\n * LLVMInstance object.\n */\nclass LLVMTargetInfo {\n public:\n  /*!\n   * \\brief Constructs LLVMTargetInfo from `Target`\n   * \\param scope LLVMInstance object\n   * \\param target TVM Target object for target \"llvm\"\n   */\n  LLVMTargetInfo(LLVMInstance& scope, const Target& target);  // NOLINT(runtime/references)\n  /*!\n   * \\brief Constructs LLVMTargetInfo from target string\n   * \\param scope LLVMInstance object\n   * \\param target TVM target string for target \"llvm\"\n   */\n  // NOLINTNEXTLINE(runtime/references)\n  LLVMTargetInfo(LLVMInstance& scope, const std::string& target_str);\n  /*!\n   * \\brief Destroys LLVMTargetInfo object\n   */\n  ~LLVMTargetInfo();\n\n  /*!\n   * \\brief Returns string representation (as TVM target) of the LLVMTargetInfo\n   * \\return Target string\n   *\n   * Note: If the LLVMTargetInfo object was created from a string `s`, the string\n   * returned here may not be exactly equal to `s`. For example, if the CPU\n   * was \"default\", the returned string will have CPU set to the detected host\n   * CPU.\n   */\n  std::string str() const;\n\n  /*!\n   * \\brief Return LLVM's `TargetMachine`, or nullptr\n   * \\param allow_missing do not abort if the target machine cannot be created,\n   *        return nullptr instead\n   * \\return Pointer to the `TargetMachine` object (or nullptr if it cannot be\n   *         created, \\see allow_missing)\n   */\n  llvm::TargetMachine* GetOrCreateTargetMachine(bool allow_missing = false);\n\n  /*!\n   * \\brief Get the target triple\n   * \\return the target triple\n   */\n  const std::string& GetTargetTriple() const { return triple_; }\n  /*!\n   * \\brief Get the CPU name\n   * \\return the CPU name: the detected host CPU if the original TVM target\n   *         specified it as \"default\"\n   */\n  const std::string& GetCPU() const { return cpu_; }\n  /*!\n   * \\brief Get the list of LLVM target features\n   * \\return array of individual feature strings\n   */\n  llvm::ArrayRef<std::string> GetTargetFeatures() const { return attrs_; }\n  /*!\n   * \\brief Get the LLVM target feature string\n   * \\return comma-separated list of LLVM target features\n   */\n  std::string GetTargetFeatureString() const;\n  /*!\n   * \\brief Get the LLVM target options\n   * \\return `llvm::TargetOptions` object for this target\n   */\n  const llvm::TargetOptions& GetTargetOptions() const { return target_options_; }\n  /*!\n   * \\brief Get fast math flags\n   * \\return `llvm::FastMathFlags` for this target\n   */\n  llvm::FastMathFlags GetFastMathFlags() const { return fast_math_flags_; }\n  /*!\n   * \\brief Get the LLVM optimization level\n   * \\return optimization level for this target\n   */\n  llvm::CodeGenOpt::Level GetOptLevel() const { return opt_level_; }\n\n  /*!\n   * \\class Option\n   * \\brief Internal representation of command-line option\n   */\n  struct Option {\n    enum class OptType {\n      Invalid = 0,  //!< placeholder, indicates parsing error\n      Bool,         //!< enum value corresponding to type string \"bool\"\n      Int,          //!< enum value corresponding to type string \"int\"\n      UInt,         //!< enum value corresponding to type string \"uint\"\n      String,       //!< enum value corresponding to type string \"string\"\n    };\n    std::string name;  //!< option name\n    OptType type;      //!< type of the option value\n    struct {\n      union {\n        bool b;          //!< bool option value\n        int i;           //!< int option value\n        unsigned u = 0;  //!< unsigned option value\n      };\n      std::string s;  //!< string option value\n    } value;          //!< option value specified in the option string\n  };\n\n  /*!\n   * \\brief Get LLVM command line options\n   * \\return the list of LLVM command line options specified for this target\n   */\n  const std::vector<Option>& GetCommandLineOptions() const { return llvm_options_; }\n\n  /*!\n   * \\brief Parse a string from the `cl-opt` target attribute\n   * \\param str the option string\n   * \\return parsed `Option` object, if parsing failed the type member will be\n   *         set to `Option::OptType::Invalid`\n   */\n  static Option ParseOptionString(const std::string& str);\n\n  /*!\n   * \\brief Checks if the settings in this object that describe global state\n   *        match the current global state\n   * \\return true or false correspondingly\n   * \\note The global state can be modified by command line options. This\n   *       function checks if the specified options differ from their current\n   *       values.\n   */\n  bool MatchesGlobalState() const;\n\n protected:\n  /*!\n   * \\brief Get the current value of given LLVM option\n   * \\param opt Option with \"type\" and \"name\" set\n   * Fills in the \"value\" field in the provided Option argument, or sets the\n   * \"type\" to Invalid if the option value cannot be obtained.\n   */\n  void GetOptionValue(Option* opt) const;\n\n private:\n  std::string triple_;\n  std::string cpu_;\n  std::vector<std::string> attrs_;\n  std::vector<Option> llvm_options_;\n  llvm::TargetOptions target_options_;\n  llvm::FastMathFlags fast_math_flags_;\n  llvm::CodeGenOpt::Level opt_level_;\n  llvm::Reloc::Model reloc_model_ = llvm::Reloc::PIC_;\n  llvm::CodeModel::Model code_model_ = llvm::CodeModel::Small;\n  std::shared_ptr<llvm::TargetMachine> target_machine_;\n};\n\n/*!\n * \\class LLVMTarget\n * \\brief Information used by LLVM for code generation for particular target\n *\n * In addition to all information that LLVM needs for code generation for\n * a particular target, objects of this class handle saving and restoring\n * global LLVM state that may be affected by these flags. This way, code\n * generation for each LLVM-based target in TVM will start with the same LLVM\n * global state.\n *\n * Note that objects of this class must be created within the lifetime of an\n * LLVMInstance object.\n */\nclass LLVMTarget : public LLVMTargetInfo {\n public:\n  /*!\n   * \\brief Constructs LLVMTarget from `Target`\n   * \\param scope LLVMInstance object\n   * \\param target_info Target info object for target \"llvm\"\n   */\n  LLVMTarget(LLVMInstance& scope, const LLVMTargetInfo& target_info);  // NOLINT(runtime/references)\n  /*!\n   * \\brief Constructs LLVMTarget from `Target`\n   * \\param scope LLVMInstance object\n   * \\param target TVM Target object for target \"llvm\"\n   */\n  LLVMTarget(LLVMInstance& scope, const Target& target);  // NOLINT(runtime/references)\n  /*!\n   * \\brief Constructs LLVMTarget from target string\n   * \\param scope LLVMInstance object\n   * \\param target TVM target string for target \"llvm\"\n   */\n  LLVMTarget(LLVMInstance& scope, const std::string& target_str);  // NOLINT(runtime/references)\n  /*!\n   * \\brief Destroys LLVMTarget object\n   */\n  ~LLVMTarget();\n\n  /*!\n   * \\brief Get the LLVMInstance object from which the LLVMTarget object was\n   *        created\n   * \\return The enclosing LLVMInstance object\n   */\n  const LLVMInstance& GetInstance() const { return instance_; }\n  /*!\n   * \\brief Get the current LLVM context\n   * \\return the current LLVM context\n   */\n  llvm::LLVMContext* GetContext() const;\n  /*!\n   * \\brief Extract the target string from given `llvm::Module`\n   * \\param module LLVM module with the TVM target string embedded as metadata\n   * \\return the target string from module's metadata\n   */\n  static std::string GetTargetMetadata(const llvm::Module& module);\n  /*!\n   * \\brief Embed target string as metadata in given `llvm::Module`\n   * \\param module the module to insert the target string into\n   */\n  void SetTargetMetadata(llvm::Module* module) const;\n\n  // Stubs to enable use with `With`.\n  void EnterWithScope() {}\n  void ExitWithScope() {}\n\n private:\n  std::vector<Option> saved_llvm_options_;\n\n  /*!\n   * \\brief Apply or revert command-line LLVM options\n   * \\param apply_otherwise_revert if true, apply the options (saving previous\n   *        values, if false, then restore the saved values\n   * \\param dry_run if true, do not make any changes (or save anything)\n   * \\return true is changes were made (or would have been made in a dry run),\n   *         false otherwise\n   */\n  bool ApplyLLVMOptions(bool apply_otherwise_revert, bool dry_run = false);\n\n  const LLVMInstance& instance_;\n  std::weak_ptr<llvm::LLVMContext> ctx_;\n\n  /*!\n   * \\brief Global singleton flag indicating whether LLVM's global state has\n   *        been modified or not (via command-line flags). There can only be\n   *        a single such modification in effect at any given time.\n   */\n  static bool modified_llvm_state_;\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_LLVM_INSTANCE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/llvm/llvm_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file llvm_module.h\n * \\brief Declares top-level shared functions related to the LLVM codegen.\n */\n\n#ifndef TVM_TARGET_LLVM_LLVM_MODULE_H_\n#define TVM_TARGET_LLVM_LLVM_MODULE_H_\n\n#ifdef TVM_LLVM_VERSION\n\n#include <tvm/relay/runtime.h>\n#include <tvm/runtime/container/array.h>\n#include <tvm/runtime/metadata.h>\n#include <tvm/runtime/module.h>\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace codegen {\n\nruntime::Module CreateLLVMCppMetadataModule(runtime::metadata::Metadata metadata, Target target,\n                                            tvm::relay::Runtime runtime);\n\nruntime::Module CreateLLVMCrtMetadataModule(const Array<runtime::Module>& modules, Target target,\n                                            tvm::relay::Runtime runtime);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_LLVM_VERSION\n#endif  // TVM_TARGET_LLVM_LLVM_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/metadata.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/metadata.h\n * \\brief Extends Metadata for use in the compiler.\n */\n#ifndef TVM_TARGET_METADATA_H_\n#define TVM_TARGET_METADATA_H_\n#include <tvm/ir/memory_pools.h>\n#include <tvm/runtime/metadata.h>\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace tvm {\nnamespace target {\nnamespace metadata {\n\n/*!\n * \\brief Subclass of MetadataNode that implements the VisitAttrs reflection method.\n *\n * This implementation (and other such Visitable subclasses) is compiled into libtvm.so, but not\n * libtvm_runtime.so, because reflection is not supported in libtvm_runtime.so over code size\n * concerns. It is used during compilation by the generic metadata code-generators.\n */\nclass VisitableMetadataNode : public ::tvm::runtime::metadata::MetadataNode {\n public:\n  explicit VisitableMetadataNode(const struct ::TVMMetadata* data) : MetadataNode{data} {}\n  VisitableMetadataNode() : MetadataNode{nullptr} {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    int64_t version_cpp{version()};\n    v->Visit(\"version\", &version_cpp);\n    auto inputs_array = Array<ObjectRef>();\n    auto inputs_accessor = inputs();\n    inputs_array.reserve(num_inputs());\n    for (int64_t i = 0; i < num_inputs(); ++i) {\n      inputs_array.push_back(::tvm::runtime::metadata::TensorInfo{inputs_accessor[i]});\n    }\n    ::tvm::runtime::metadata::MetadataArray inputs_metadata_array{\n        inputs_array, ::tvm::runtime::metadata::MetadataKind::kMetadata,\n        ::tvm::runtime::metadata::TensorInfoNode::_type_key};\n    v->Visit(\"inputs\", &inputs_metadata_array);\n    int64_t num_inputs_cpp = num_inputs();\n    v->Visit(\"num_inputs\", &num_inputs_cpp);\n    auto outputs_array = Array<ObjectRef>();\n    auto outputs_accessor = outputs();\n    outputs_array.reserve(num_outputs());\n    for (int64_t i = 0; i < num_outputs(); ++i) {\n      outputs_array.push_back(::tvm::runtime::metadata::TensorInfo{outputs_accessor[i]});\n    }\n    ::tvm::runtime::metadata::MetadataArray outputs_metadata_array{\n        outputs_array, ::tvm::runtime::metadata::MetadataKind::kMetadata,\n        ::tvm::runtime::metadata::TensorInfoNode::_type_key};\n    v->Visit(\"outputs\", &outputs_metadata_array);\n    int64_t num_outputs_cpp = num_outputs();\n    v->Visit(\"num_outputs\", &num_outputs_cpp);\n    auto pools_array = Array<ObjectRef>();\n    auto pools_accessor = workspace_pools();\n    pools_array.reserve(num_workspace_pools());\n    for (int64_t i = 0; i < num_workspace_pools(); ++i) {\n      pools_array.push_back(::tvm::runtime::metadata::TensorInfo{pools_accessor[i]});\n    }\n    ::tvm::runtime::metadata::MetadataArray workspace_pools_metadata_array{\n        pools_array, ::tvm::runtime::metadata::MetadataKind::kMetadata,\n        ::tvm::runtime::metadata::TensorInfoNode::_type_key};\n    v->Visit(\"workspace_pools\", &workspace_pools_metadata_array);\n    int64_t num_workspace_pools_cpp = num_workspace_pools();\n    v->Visit(\"num_workspace_pools\", &num_workspace_pools_cpp);\n\n    auto consts_array = Array<ObjectRef>();\n    auto consts_accessor = constant_pools();\n    consts_array.reserve(num_constant_pools());\n    for (int64_t i = 0; i < num_constant_pools(); ++i) {\n      consts_array.push_back(::tvm::runtime::metadata::ConstantInfoMetadata{consts_accessor[i]});\n    }\n\n    int64_t num_const_pools_cpp = num_constant_pools();\n    ::tvm::runtime::metadata::MetadataArray constant_pools_metadata_array{\n        consts_array, ::tvm::runtime::metadata::MetadataKind::kMetadata,\n        ::tvm::runtime::metadata::ConstantInfoMetadataNode::_type_key};\n    v->Visit(\"constant_pools\", &constant_pools_metadata_array);\n    v->Visit(\"num_constant_pools\", &num_const_pools_cpp);\n    ::std::string mod_name_cpp{data()->mod_name};\n    v->Visit(\"mod_name\", &mod_name_cpp);\n  }\n};\n\n/*!\n * \\brief Subclass of MetadataNode which also owns the backing C structures.\n *\n * This class (and other InMemory subclasses) are used during compilation to instantiate Metadata\n * instances whose storage lives outside of .rodata. This class exists because the Module returned\n * from tvm.relay.build must also be ready to run inference.\n */\nclass InMemoryMetadataNode : public ::tvm::target::metadata::VisitableMetadataNode {\n public:\n  InMemoryMetadataNode()\n      : InMemoryMetadataNode(0 /* version */, {} /* inputs */, {} /* outputs */,\n                             {} /* workspace_pools */, {} /* constant_pools */, \"\" /* mod_name */) {\n  }\n  InMemoryMetadataNode(int64_t version,\n                       const ::std::vector<::tvm::runtime::metadata::TensorInfo>& inputs,\n                       const ::std::vector<::tvm::runtime::metadata::TensorInfo>& outputs,\n                       const ::std::vector<::tvm::runtime::metadata::TensorInfo>& workspace_pools,\n                       const ::std::vector<::tvm::ConstantInfo>& constant_pools,\n                       const ::tvm::runtime::String mod_name)\n      : VisitableMetadataNode{&storage_},\n        inputs_{new struct TVMTensorInfo[inputs.size()]},\n        inputs_objs_{inputs},\n        outputs_{new struct TVMTensorInfo[outputs.size()]},\n        outputs_objs_{outputs},\n        workspace_pools_{new struct TVMTensorInfo[workspace_pools.size()]},\n        workspace_pools_objs_{workspace_pools},\n        constant_pools_{new struct TVMConstantInfo[constant_pools.size()]},\n        constant_pools_objs_{constant_pools},\n        mod_name_{mod_name},\n        storage_{version, nullptr, 0ull,    nullptr, 0ull,\n                 nullptr, 0ull,    nullptr, 0ull,    mod_name_.c_str()} {\n    storage_.inputs = inputs_.get();\n    storage_.num_inputs = inputs.size();\n    for (unsigned int i = 0; i < inputs.size(); ++i) {\n      inputs_.get()[i] = *inputs[i]->data();\n    }\n    storage_.outputs = outputs_.get();\n    storage_.num_outputs = outputs.size();\n    for (unsigned int i = 0; i < outputs.size(); ++i) {\n      outputs_.get()[i] = *outputs[i]->data();\n    }\n    storage_.workspace_pools = workspace_pools_.get();\n    storage_.num_workspace_pools = workspace_pools.size();\n    for (unsigned int i = 0; i < workspace_pools.size(); ++i) {\n      workspace_pools_.get()[i] = *workspace_pools[i]->data();\n    }\n    storage_.constant_pools = constant_pools_.get();\n    storage_.num_constant_pools = constant_pools.size();\n    for (size_t i = 0; i < constant_pools.size(); ++i) {\n      constant_pools_.get()[i].name_hint = constant_pools[i]->name_hint.c_str();\n      constant_pools_.get()[i].byte_offset = constant_pools[i]->byte_offset.IntValue();\n\n      std::string bytes;\n      dmlc::MemoryStringStream stream(&bytes);\n      auto data = constant_pools[i]->data;\n      data.Save(&stream);\n      // Allocated mem freed in destructor\n      constant_pools_.get()[i].data_len = bytes.size();\n      char* a = reinterpret_cast<char*>(malloc(bytes.size()));\n      constant_pools_.get()[i].data_bytes = a;\n      memcpy(a, bytes.c_str(), bytes.size());\n    }\n  }\n\n  ~InMemoryMetadataNode() {\n    // frees allocated mem for const_objs_\n    for (int i = 0; i < storage_.num_constant_pools; ++i) {\n      free(const_cast<void*>(constant_pools_.get()[i].data_bytes));\n    }\n  }\n\n private:\n  ::std::unique_ptr<struct TVMTensorInfo[]> inputs_;\n  std::vector<::tvm::runtime::metadata::TensorInfo> inputs_objs_;\n  ::std::unique_ptr<struct TVMTensorInfo[]> outputs_;\n  std::vector<::tvm::runtime::metadata::TensorInfo> outputs_objs_;\n  ::std::unique_ptr<struct TVMTensorInfo[]> workspace_pools_;\n  std::vector<::tvm::runtime::metadata::TensorInfo> workspace_pools_objs_;\n  ::std::unique_ptr<struct TVMConstantInfo[]> constant_pools_;\n  std::vector<::tvm::ConstantInfo> constant_pools_objs_;\n  ::std::string mod_name_;\n  struct ::TVMMetadata storage_;\n};\n\nclass VisitableTensorInfoNode : public ::tvm::runtime::metadata::TensorInfoNode {\n public:\n  explicit VisitableTensorInfoNode(const struct ::TVMTensorInfo* data) : TensorInfoNode{data} {}\n  VisitableTensorInfoNode() : TensorInfoNode{nullptr} {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    ::std::string name_cpp{data()->name};\n    v->Visit(\"name\", &name_cpp);\n    auto shape_array = Array<ObjectRef>();\n    auto shape_accessor = shape();\n    shape_array.reserve(num_shape());\n    for (int64_t i = 0; i < num_shape(); ++i) {\n      shape_array.push_back(::tvm::Integer{static_cast<int>(shape_accessor[i])});\n    }\n    ::tvm::runtime::metadata::MetadataArray shape_metadata_array{\n        shape_array, ::tvm::runtime::metadata::MetadataKind::kInt64, nullptr};\n    v->Visit(\"shape\", &shape_metadata_array);\n    int64_t num_shape_cpp = num_shape();\n    v->Visit(\"num_shape\", &num_shape_cpp);\n    ::tvm::runtime::DataType dtype_cpp{dtype()};\n    v->Visit(\"dtype\", &dtype_cpp);\n  }\n};\n\nclass InMemoryTensorInfoNode : public ::tvm::target::metadata::VisitableTensorInfoNode {\n public:\n  InMemoryTensorInfoNode() : InMemoryTensorInfoNode(\"\", {}, ::tvm::runtime::DataType(0, 0, 0)) {}\n  InMemoryTensorInfoNode(const ::tvm::runtime::String& name, const ::std::vector<int64_t>& shape,\n                         ::tvm::runtime::DataType dtype)\n      : VisitableTensorInfoNode{&storage_},\n        name_{name},\n        shape_{new int64_t[shape.size()]()},\n        storage_{name_.c_str(), nullptr, 0, dtype} {\n    storage_.shape = shape_.get();\n    storage_.num_shape = shape.size();\n    for (unsigned int i = 0; i < shape.size(); ++i) {\n      shape_.get()[i] = shape[i];\n    }\n  }\n\n private:\n  ::std::string name_;\n  ::std::unique_ptr<int64_t[]> shape_;\n  struct ::TVMTensorInfo storage_;\n};\n\nclass VisitableConstantInfoMetadataNode\n    : public ::tvm::runtime::metadata::ConstantInfoMetadataNode {\n public:\n  explicit VisitableConstantInfoMetadataNode(const struct ::TVMConstantInfo* data)\n      : ConstantInfoMetadataNode{data} {}\n  VisitableConstantInfoMetadataNode() : ConstantInfoMetadataNode{nullptr} {}\n\n  void VisitAttrs(AttrVisitor* v) {\n    ::std::string name_cpp{name_hint()};\n    v->Visit(\"name_hint\", &name_cpp);\n\n    uint64_t byte_offset_cpp{byte_offset()};\n    v->Visit(\"byte_offset\", &byte_offset_cpp);\n\n    ::tvm::runtime::NDArray data_cpp = data();\n    v->Visit(\"data\", &data_cpp);\n  }\n};\n\n}  // namespace metadata\n}  // namespace target\n}  // namespace tvm\n\n#endif  // TVM_TARGET_METADATA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/metadata_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file metadata_module.h\n * \\brief Declares functions that build MetadataModules for C++ and C runtimes.\n */\n\n#ifndef TVM_TARGET_METADATA_MODULE_H_\n#define TVM_TARGET_METADATA_MODULE_H_\n\n#include <tvm/relay/executor.h>\n#include <tvm/relay/runtime.h>\n#include <tvm/runtime/module.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/target/target.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"../relay/backend/utils.h\"\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n * \\brief Create a metadata module wrapper. The helper is used by different\n *        codegens, such as graph executor codegen and the vm compiler.\n *\n * \\param params The metadata for initialization of all modules.\n * \\param target_module the internal module that is compiled by tvm.\n * \\param ext_modules The external modules that needs to be imported inside the metadata\n * module(s).\n * \\param target The target that all the modules are compiled for\n * \\param runtime The runtime to codegen for\n * \\param metadata Module metadata\n * \\return The created metadata module that manages initialization of metadata.\n */\nruntime::Module CreateMetadataModule(\n    const std::unordered_map<std::string, runtime::NDArray>& params, runtime::Module target_module,\n    const Array<runtime::Module>& ext_modules, Target target, tvm::relay::Runtime runtime,\n    tvm::relay::Executor executor, relay::backend::ExecutorCodegenMetadata metadata);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_METADATA_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/metadata_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/metadata_utils.h\n * \\brief Declares utilty functions and classes for emitting metadata.\n */\n#ifndef TVM_TARGET_METADATA_UTILS_H_\n#define TVM_TARGET_METADATA_UTILS_H_\n\n#include <tvm/runtime/data_type.h>\n#include <tvm/runtime/ndarray.h>\n#include <tvm/runtime/object.h>\n\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n\n#include \"metadata.h\"\n\nnamespace tvm {\nnamespace codegen {\nnamespace metadata {\n\n/*!\n * \\brief Construct a unique string \"address\" for a struct member from a vector of pieces.\n *\n * In codegen, it is frequently necessary to assemble a C-style identifier for an\n * otherwise-anonymous member of Metadata. For instance, suppose Metadata declares an array:\n * struct TVMMetadata {\n *   int64_t* shape;\n * };\n *\n * In order to properly initialize this struct, the array must be declared separately with a global\n * name. This function produces such a name, here termed \"address.\"\n *\n * \\param parts A vector of pieces, typically the struct member names which identify the path to\n *  this member.\n * \\return The joined pieces.\n */\nstd::string AddressFromParts(const std::vector<std::string>& parts);\n\n/*!\n * \\brief A prefix in metadata symbol names.\n * This prefix is typically given to AddressFromParts as the 0th item in parts.\n */\nstatic constexpr const char* kMetadataGlobalSymbol = \"kTvmgenMetadata\";\n\n/*!\n * \\brief Post-order traverse metadata to discover arrays which need to be forward-defined.\n */\nclass DiscoverArraysVisitor : public AttrVisitor {\n public:\n  /*! \\brief Models a single array discovered in this visitor.\n   * Conatains two fields:\n   *  0. An address which uniquely identifies the array in this Metadata instance.\n   *  1. The discovered MetadataArray.\n   */\n  using DiscoveredArray = std::tuple<std::string, runtime::metadata::MetadataArray>;\n  explicit DiscoverArraysVisitor(std::vector<DiscoveredArray>* queue);\n\n  void Visit(const char* key, double* value) final;\n  void Visit(const char* key, int64_t* value) final;\n  void Visit(const char* key, uint64_t* value) final;\n  void Visit(const char* key, int* value) final;\n  void Visit(const char* key, bool* value) final;\n  void Visit(const char* key, std::string* value) final;\n  void Visit(const char* key, DataType* value) final;\n  void Visit(const char* key, runtime::NDArray* value) final;\n  void Visit(const char* key, void** value) final;\n\n  void Visit(const char* key, ObjectRef* value) final;\n\n private:\n  /*! \\brief The queue to be filled with discovered arrays. */\n  std::vector<DiscoveredArray>* queue_;\n\n  /*! \\brief Tracks the preceding address pieces. */\n  std::vector<std::string> address_parts_;\n};\n\n/*!\n * \\brief Post-order traverse Metadata to discover all complex types which need to be\n * forward-defined. This visitor finds one defined() MetadataBase instance for each unique subclass\n * present inside Metadata in the order in which the subclass was first discovered.\n */\nclass DiscoverComplexTypesVisitor : public AttrVisitor {\n public:\n  /*! \\brief Construct a new instance.\n   * \\param queue An ordered map which holds the\n   */\n  explicit DiscoverComplexTypesVisitor(std::vector<runtime::metadata::MetadataBase>* queue)\n      : queue_{queue} {\n    int i = 0;\n    for (auto q : *queue) {\n      type_key_to_position_[q->GetTypeKey()] = i++;\n    }\n  }\n\n  void Visit(const char* key, double* value) final;\n  void Visit(const char* key, int64_t* value) final;\n  void Visit(const char* key, uint64_t* value) final;\n  void Visit(const char* key, int* value) final;\n  void Visit(const char* key, bool* value) final;\n  void Visit(const char* key, std::string* value) final;\n  void Visit(const char* key, DataType* value) final;\n  void Visit(const char* key, runtime::NDArray* value) final;\n  void Visit(const char* key, void** value) final;\n\n  void Visit(const char* key, ObjectRef* value) final;\n\n  void Discover(runtime::metadata::MetadataBase metadata);\n\n private:\n  bool DiscoverType(std::string type_key);\n\n  void DiscoverInstance(runtime::metadata::MetadataBase md);\n\n  std::vector<runtime::metadata::MetadataBase>* queue_;\n\n  /*! \\brief map type_index to index in queue_. */\n  std::unordered_map<std::string, int> type_key_to_position_;\n};\n\n}  // namespace metadata\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_METADATA_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/parsers/aprofile.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/parsers/aprofile.h\n * \\brief Target Parser for Arm(R) Cortex(R) A-Profile CPUs\n */\n\n#ifndef TVM_TARGET_PARSERS_APROFILE_H_\n#define TVM_TARGET_PARSERS_APROFILE_H_\n\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace target {\nnamespace parsers {\nnamespace aprofile {\n\nbool IsArch(TargetJSON target);\nTargetJSON ParseTarget(TargetJSON target);\n\n}  // namespace aprofile\n}  // namespace parsers\n}  // namespace target\n}  // namespace tvm\n\n#endif  // TVM_TARGET_PARSERS_APROFILE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/parsers/cpu.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/parsers/cpu.h\n * \\brief Target Parser for CPU Target's\n */\n\n#ifndef TVM_TARGET_PARSERS_CPU_H_\n#define TVM_TARGET_PARSERS_CPU_H_\n\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace target {\nnamespace parsers {\nnamespace cpu {\n\nTargetJSON ParseTarget(TargetJSON target);\n\n}  // namespace cpu\n}  // namespace parsers\n}  // namespace target\n}  // namespace tvm\n\n#endif  // TVM_TARGET_PARSERS_CPU_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/parsers/mprofile.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tvm/target/parsers/mprofile.h\n * \\brief Target Parser for Arm(R) Cortex(R) M-Profile CPUs\n */\n\n#ifndef TVM_TARGET_PARSERS_MPROFILE_H_\n#define TVM_TARGET_PARSERS_MPROFILE_H_\n\n#include <tvm/target/target.h>\n\nnamespace tvm {\nnamespace target {\nnamespace parsers {\nnamespace mprofile {\n\nbool IsArch(TargetJSON target);\nTargetJSON ParseTarget(TargetJSON target);\n\n}  // namespace mprofile\n}  // namespace parsers\n}  // namespace target\n}  // namespace tvm\n\n#endif  // TVM_TARGET_PARSERS_MPROFILE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_c.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_c.h\n * \\brief Common utilities to generated C style code.\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_C_H_\n#define TVM_TARGET_SOURCE_CODEGEN_C_H_\n\n#include <tvm/ir/op.h>\n#include <tvm/target/codegen.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op_attr_types.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../tir/transforms/ir_utils.h\"\n#include \"codegen_source_base.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nusing namespace tir;\n/*!\n * \\brief A base class to generate C code.\n *\n *  CodeGenC have two modes: generate SSA formed C code or normal form.\n *\n * **NOTE** CodeGenC does not aim at generating C codes consumed by MSVC or GCC,\n * Rather, it's providing infrastructural abstraction for C variants like CUDA\n * and OpenCL-C. You might find some odd variant features, e.g., type `int3` for\n * a vector of 3 `int`s. For native C code generator, see `CodeGenLLVM`.\n */\nclass CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,\n                 public StmtFunctor<void(const Stmt&)>,\n                 public CodeGenSourceBase {\n public:\n  /*!\n   * \\brief Initialize the code generator.\n   * \\param output_ssa Whether output SSA.\n   */\n  void Init(bool output_ssa);\n  /*!\n   * \\brief Add the function to the generated module.\n   * \\param f The function to be compiled.\n   * \\param whether to append return 0 in the end.\n   */\n  void AddFunction(const PrimFunc& f);\n  /*!\n   * \\brief Finalize the compilation and return the code.\n   * \\return The code.\n   */\n  std::string Finish();\n  /*!\n   * \\brief Print the Stmt n to CodeGenC->stream\n   * \\param n The statement to be printed.\n   */\n  void PrintStmt(const Stmt& n) { VisitStmt(n); }\n  /*!\n   * \\brief Print the expression n(or its ssa id if in ssa mode) into os\n   * \\param n The expression to be printed.\n   * \\param os The output stream\n   */\n  void PrintExpr(const PrimExpr& n, std::ostream& os);\n  /*!\n   * \\brief Same as PrintExpr, but simply returns result string\n   * \\param n The expression to be printed.\n   */\n  std::string PrintExpr(const PrimExpr& n) {\n    std::ostringstream os;\n    PrintExpr(n, os);\n    return os.str();\n  }\n  // The following parts are overloadable print operations.\n  /*!\n   * \\brief Print the function header before the argument list\n   *\n   *  Example: stream << \"void\";\n   */\n  virtual void PrintFuncPrefix();  // NOLINT(*)\n  /*!\n   * \\brief Print extra function attributes\n   *\n   *  Example: __launch_bounds__(256) for CUDA functions\n   */\n  virtual void PrintExtraAttrs(const PrimFunc& f);\n  /*!\n   * \\brief Print the final return at the end the function.\n   */\n  virtual void PrintFinalReturn();  // NOLINT(*)\n  /*!\n   * \\brief Insert statement before function body.\n   * \\param f The function to be compiled.\n   */\n  virtual void PreFunctionBody(const PrimFunc& f) {}\n  /*!\n   * \\brief Initialize codegen state for generating f.\n   * \\param f The function to be compiled.\n   */\n  virtual void InitFuncState(const PrimFunc& f);\n  // expression\n  void VisitExpr_(const VarNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const LoadNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const BufferLoadNode* op, std::ostream& os) override;  // NOLINT(*)\n  void VisitExpr_(const LetNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const CallNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const AddNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const SubNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const MulNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const DivNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const ModNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const MinNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const MaxNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const EQNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const NENode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const LTNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const LENode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const GTNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const GENode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const AndNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const OrNode* op, std::ostream& os) override;          // NOLINT(*)\n  void VisitExpr_(const CastNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const NotNode* op, std::ostream& os) override;         // NOLINT(*)\n  void VisitExpr_(const SelectNode* op, std::ostream& os) override;      // NOLINT(*)\n  void VisitExpr_(const RampNode* op, std::ostream& os) override;        // NOLINT(*)\n  void VisitExpr_(const ShuffleNode* op, std::ostream& os) override;     // NOLINT(*)\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) override;   // NOLINT(*)\n  void VisitExpr_(const IntImmNode* op, std::ostream& os) override;      // NOLINT(*)\n  void VisitExpr_(const FloatImmNode* op, std::ostream& os) override;    // NOLINT(*)\n  void VisitExpr_(const StringImmNode* op, std::ostream& os) override;   // NOLINT(*)\n  // statment\n  void VisitStmt_(const LetStmtNode* op) override;\n  void VisitStmt_(const StoreNode* op) override;\n  void VisitStmt_(const BufferStoreNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const WhileNode* op) override;\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const AllocateNode* op) override;\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const EvaluateNode* op) override;\n  void VisitStmt_(const SeqStmtNode* op) override;\n  void VisitStmt_(const AllocateConstNode* op) override;\n  void VisitStmt_(const DeclBufferNode* op) override;\n\n  /*!\n   * \\brief Print expr representing the thread tag\n   * \\param IterVar iv The thread index to be binded;\n   */\n  virtual void BindThreadIndex(const IterVar& iv);                             // NOLINT(*)\n  virtual void PrintStorageScope(const std::string& scope, std::ostream& os);  // NOLINT(*)\n  virtual void PrintStorageSync(const CallNode* op);                           // NOLINT(*)\n  // Binary vector op.\n  virtual void PrintVecBinaryOp(const std::string& op, DataType op_type, PrimExpr lhs, PrimExpr rhs,\n                                std::ostream& os);  // NOLINT(*)\n  // print vector load\n  virtual std::string GetVecLoad(DataType t, const BufferNode* buffer, PrimExpr base);\n  // print vector store\n  virtual void PrintVecStore(const BufferNode* buffer, DataType t, PrimExpr base,\n                             const std::string& value);  // NOLINT(*)\n  // print load of single element\n  virtual void PrintVecElemLoad(const std::string& vec, DataType t, int i,\n                                std::ostream& os);  // NOLINT(*)\n  // print store of single element.\n  virtual void PrintVecElemStore(const std::string& vec, DataType t, int i,\n                                 const std::string& value);\n  // Get a cast type from to\n  virtual std::string CastFromTo(std::string value, DataType from, DataType target);\n  // Get load of single element with expression\n  virtual void PrintVecElemLoadExpr(DataType t, int i, const std::string& value, std::ostream& os);\n  // Print restrict keyword for a given Var if applicable\n  virtual void PrintRestrict(const Var& v, std::ostream& os);\n\n  virtual void SetConstantsByteAlignment(Integer constants_byte_alignment) {\n    constants_byte_alignment_ = constants_byte_alignment;\n  }\n\n protected:\n  // Print reference to struct location\n  std::string GetStructRef(DataType t, const PrimExpr& buffer, const PrimExpr& index, int kind);\n  // Print reference to a buffer as type t in index.\n  virtual std::string GetBufferRef(DataType t, const BufferNode* buffer, PrimExpr index);\n\n  /*!\n   * \\brief Handle volatile loads.\n   *\n   * This is to workaround a bug in CUDA cuda_fp16.h. Volatile accesses\n   * to shared memory are required for reductions. However, __half class\n   * does not implement volatile member functions. CUDA codegen will cast\n   * away volatile qualifier from CUDA __half types.\n   */\n  virtual void HandleVolatileLoads(const std::string& value, const BufferLoadNode* op,\n                                   std::ostream& os) {\n    // By default, do nothing but print the loaded value.\n    os << value;\n  }\n\n  /*!\n   * \\brief Check if scope is part of type in the target language.\n   *\n   * **NOTE** In OpenCL, __local is part of type, so \"__local int *\"\n   * is legal. This is not the case for CUDA, where \"__shared__\"\n   * or \"__constant__\" is not part of type but a storage class (like\n   * C/C++ static).\n   */\n  virtual bool IsScopePartOfType() const { return true; }\n\n  /*!\n   * \\brief Print external function call.\n   * \\param ret_type The return type.\n   * \\param global_symbol The symbolc of the target function.\n   * \\param args The arguments to the function.\n   * \\param skip_first_arg Whether to skip the first arguments.\n   * \\param os The output stream.\n   */\n  virtual void PrintCallExtern(Type ret_type, String global_symbol, const Array<PrimExpr>& args,\n                               bool skip_first_arg, std::ostream& os);  // NOLINT(*)\n  /*!\n   * \\brief If buffer is allocated as type t.\n   * \\param buf_var The buffer variable.\n   * \\param t The type to be checked.\n   */\n  bool HandleTypeMatch(const VarNode* buf_var, DataType t) const;\n  /*!\n   * \\brief Register the data type of buf_var\n   * \\param buf_var The buffer variable.\n   * \\param t The type to be checked.\n   */\n  void RegisterHandleType(const VarNode* buf_var, DataType t);\n  // override\n  void PrintSSAAssign(const std::string& target, const std::string& src, DataType t) final;\n  /*! \\brief reserves common C keywords */\n  void ReserveKeywordsAsUnique();\n\n  /*! \\brief Check if buf_var is volatile or not. */\n  bool IsVolatile(const VarNode* buf_var) const { return volatile_buf_.count(buf_var) != 0; }\n\n  /*! \\brief restrict keyword */\n  std::string restrict_keyword_{\"\"};\n  /*! \\brief the storage scope of allocation */\n  std::unordered_map<const VarNode*, std::string> alloc_storage_scope_;\n  /*! \\brief the data type of allocated buffers */\n  std::unordered_map<const VarNode*, DataType> handle_data_type_;\n  /*! \\brief Record of ops that have pre-defined global symbol. */\n  OpAttrMap<TGlobalSymbol> op_attr_global_symbol_ = Op::GetAttrMap<TGlobalSymbol>(\"TGlobalSymbol\");\n  // cache commonly used ops\n  const Op& builtin_call_extern_ = builtin::call_extern();\n  const Op& builtin_call_pure_extern_ = builtin::call_pure_extern();\n  Integer constants_byte_alignment_ = 16;\n\n private:\n  /*! \\brief whether to print in SSA form */\n  bool print_ssa_form_{false};\n  /*! \\brief set of volatile buf access */\n  std::unordered_set<const VarNode*> volatile_buf_;\n  // deep comparison of PrimExpr\n  ExprDeepEqual deep_equal_;\n  // binding of let variables. Enables duplicate var defs that map to same value\n  std::unordered_map<Var, const LetNode*, ObjectPtrHash, ObjectPtrEqual> let_binding_;\n};\n\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_SOURCE_CODEGEN_C_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_c_host.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_c_host.h\n * \\brief Generate C host code.\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_C_HOST_H_\n#define TVM_TARGET_SOURCE_CODEGEN_C_HOST_H_\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"codegen_c.h\"\n#include \"tvm/target/codegen.h\"\n#include \"tvm/tir/expr.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nclass CodeGenCHost : public CodeGenC {\n public:\n  CodeGenCHost();\n  void Init(bool output_ssa, bool emit_asserts, std::string target_str,\n            const std::unordered_set<std::string>& devices);\n\n  void InitGlobalContext();\n  void AddFunction(const PrimFunc& f);\n  /*!\n   * \\brief Add functions from the (unordered) range to the current module in a deterministic\n   * order. This helps with debugging.\n   *\n   * \\param functions A vector of unordered range of current module.\n   */\n  void AddFunctionsOrdered(std::vector<std::pair<tvm::GlobalVar, tvm::BaseFunc>> functions);\n  void DefineModuleName();\n\n  void PrintType(DataType t, std::ostream& os) final;  // NOLINT(*)\n  void PrintFuncPrefix() final;                        // NOLINT(*)\n  void PrintFinalReturn() final;                       // NOLINT(*)\n\n  // overload visitor functions\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) final;  // NOLINT(*)\n  void VisitExpr_(const CallNode* op, std::ostream& os);             // NOLINT(*)\n  // overload min and max to use the ternary operator, so we don't rely on the\n  // standard library implementations\n  void VisitExpr_(const MinNode* op, std::ostream& os) final;  // NOLINT(*)\n  void VisitExpr_(const MaxNode* op, std::ostream& os) final;  // NOLINT(*)\n\n  void VisitStmt_(const AssertStmtNode* op) final;  // NOLINT(*)\n\n  Array<String> GetFunctionNames() { return function_names_; }\n\n private:\n  /* \\brief Internal structure to store information about function calls */\n  struct FunctionInfo {\n    /* \\brief function name */\n    std::string func_name;\n    /* number of arguments required by the function */\n    int64_t num_args;\n    /* \\brief name of resource_handle to pass */\n    std::string resource_handle_name;\n  };\n  std::string module_name_;\n  /* \\brief mapping global packed func to the unique name */\n  std::unordered_map<std::string, std::string> declared_globals_;\n  /* \\brief names of the functions declared in this module */\n  Array<String> function_names_;\n  /*! \\brief whether to emit asserts in the resulting C code */\n  bool emit_asserts_;\n\n  FunctionInfo GetFunctionInfo(const CallNode* op, bool has_resource_handle);\n  std::string GetPackedName(const CallNode* op);\n  void PrintGetFuncFromBackend(const std::string& func_name, const std::string& packed_func_name);\n  void PrintFuncCall(const std::string& packed_func_name, int num_args);\n  void PrintFuncCallC(const std::string& packed_func_name, int num_args,\n                      const std::string& resource_handle_name);\n\n  /*!\n   * \\brief Print ternary conditional operator implementing binary `op`\n   * Forces the operands to be in SSA form.\n   * \\param op binary operator being expressed\n   * \\param compare string representation of comparison operator\n   * \\param os stream reference to print into\n   */\n  template <typename T>\n  inline void PrintTernaryCondExpr(const T* op, const char* compare,\n                                   std::ostream& os);  // NOLINT(*)\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_C_HOST_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_cuda.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_cuda.h\n * \\brief Utility to generate cuda code\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_CUDA_H_\n#define TVM_TARGET_SOURCE_CODEGEN_CUDA_H_\n\n#include <tvm/target/codegen.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"codegen_c.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nclass CodeGenCUDA final : public CodeGenC {\n public:\n  CodeGenCUDA();\n  void Init(bool output_ssa);\n  std::string Finish();\n  bool need_include_path() {\n    return (enable_fp16_ || enable_bf16_ || enable_int8_ || need_math_constants_h_ || need_mma_h_);\n  }\n  // override behavior\n  void PrintFuncPrefix() final;\n  void PrintExtraAttrs(const PrimFunc& f) final;\n  void VisitStmt_(const ForNode* op) final;\n  void PrintStorageSync(const CallNode* op) final;\n  void PrintStorageScope(const std::string& scope, std::ostream& os) final;  // NOLINT(*)\n  void PrintVecBinaryOp(const std::string& op, DataType t, PrimExpr lhs, PrimExpr rhs,\n                        std::ostream& os) final;       // NOLINT(*)\n  void PrintType(DataType t, std::ostream& os) final;  // NOLINT(*)\n  void PrintVecElemLoad(const std::string& vec, DataType t, int i,\n                        std::ostream& os) final;  // NOLINT(*)\n  void PrintVecElemStore(const std::string& vec, DataType t, int i, const std::string& value) final;\n  void BindThreadIndex(const IterVar& iv) final;  // NOLINT(*)\n  void PrintVecElemLoadExpr(DataType t, int i, const std::string& value, std::ostream& os) final;\n  // overload visitor\n  void VisitExpr_(const RampNode* op, std::ostream& os) final;       // NOLINT(*)\n  void VisitExpr_(const ShuffleNode* op, std::ostream& os) final;    // NOLINT(*)\n  void VisitExpr_(const SelectNode* op, std::ostream& os) final;     // NOLINT(*)\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) final;  // NOLINT(*)\n  void VisitExpr_(const FloatImmNode* op, std::ostream& os) final;\n  void VisitExpr_(const CallNode* op, std::ostream& os) final;\n  void VisitExpr_(const CastNode* op, std::ostream& os) final;\n  void VisitStmt_(const EvaluateNode* op) final;\n  void VisitStmt_(const AllocateNode* op) final;\n  void VisitStmt_(const AttrStmtNode* op) final;\n\n protected:\n  void PrintCallExtern(Type ret_type, String global_symbol, const Array<PrimExpr>& args,\n                       bool skip_first_arg, std::ostream& os) final;  // NOLINT(*)\n\n private:\n  // Handle volatile loads\n  void HandleVolatileLoads(const std::string& value, const BufferLoadNode* op,\n                           std::ostream& os) final;\n\n  // Whether scope such as \"__shared__\" or \"__constant__\"  is part of type.\n  bool IsScopePartOfType() const final { return false; }\n\n  // Whether global barrier is needed.\n  bool need_global_barrier_{false};\n  // Global barrier state\n  std::string vid_global_barrier_state_;\n  // Global barrier expected node.\n  std::string vid_global_barrier_expect_;\n  // whether enable fp16\n  bool enable_fp16_{false};\n  // whether enable bf16\n  bool enable_bf16_{false};\n  // whether enable int8\n  bool enable_int8_{false};\n  // whether enable warp shuffle intrinsics\n  bool enable_warp_shuffle_{false};\n  // whether need math_constants.h\n  bool need_math_constants_h_{false};\n  // whether need mma.h\n  bool need_mma_h_{false};\n  // Op attribute map\n  OpAttrMap<bool> op_need_warp_shuffle_ = Op::GetAttrMap<bool>(\"cuda.need_warp_shuffle\");\n\n  std::unordered_map<const VarNode*, std::string> fragment_shapes;\n  std::unordered_map<const VarNode*, std::string> fragment_layouts;\n  friend void PrintConst(const FloatImmNode* op, std::ostream& os, CodeGenCUDA* p);\n  void PrintWmmaScope(const std::string& scope, DataType t, const VarNode* variable,\n                      std::ostream& os);\n  int32_t GetWmmaFragmentSize(const std::string& scope, const VarNode* variable, int32_t size);\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_CUDA_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_metal.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_metal.h\n * \\brief Generate Metal device code.\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_METAL_H_\n#define TVM_TARGET_SOURCE_CODEGEN_METAL_H_\n\n#include <tvm/target/codegen.h>\n\n#include <string>\n\n#include \"codegen_c.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nclass CodeGenMetal final : public CodeGenC {\n public:\n  explicit CodeGenMetal(Target target);\n  // override print thread tag.\n  void PrintArgUnionDecl();\n  void AddFunction(const PrimFunc& f);  // NOLINT(*)\n  void InitFuncState(const PrimFunc& f) final;\n  void PrintStorageScope(const std::string& scope, std::ostream& os) final;  // NOLINT(*)\n  void PrintStorageSync(const CallNode* op) final;                           // NOLINT(*)\n  void PrintType(DataType t, std::ostream& os) final;                        // NOLINT(*)\n  void BindThreadIndex(const IterVar& iv) final;                             // NOLINT(*)\n  // print load of single element\n  void PrintVecElemLoad(const std::string& vec, DataType t, int i,\n                        std::ostream& os) final;  // NOLINT(*)\n  // print store of single element.\n  void PrintVecElemStore(const std::string& vec, DataType t, int i, const std::string& value) final;\n  // overload visitor\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) final;  // NOLINT(*)\n  void VisitExpr_(const CallNode* op, std::ostream& os) final;       // NOLINT(*)\n  void VisitExpr_(const FloatImmNode* op, std::ostream& os) final;\n  // reuse parent's function.\n  using CodeGenC::PrintType;\n\n private:\n  int thread_index_bits_{32};\n  Target target_;\n};\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_METAL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_opencl.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_opencl.h\n * \\brief Generate OpenCL device code.\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_OPENCL_H_\n#define TVM_TARGET_SOURCE_CODEGEN_OPENCL_H_\n\n#include <tvm/target/codegen.h>\n\n#include <string>\n#include <unordered_map>\n\n#include \"codegen_c.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nclass CodeGenOpenCL final : public CodeGenC {\n public:\n  CodeGenOpenCL();\n  std::string Finish();\n\n  // override print thread tag.\n  void InitFuncState(const PrimFunc& f) final;\n  void PrintFuncPrefix() final;                                              // NOLINT(*)\n  void PreFunctionBody(const PrimFunc& f) final;                             // NOLINT(*)\n  void BindThreadIndex(const IterVar& iv) final;                             // NOLINT(*)\n  void PrintStorageScope(const std::string& scope, std::ostream& os) final;  // NOLINT(*)\n  void PrintStorageSync(const CallNode* op) final;                           // NOLINT(*)\n  void PrintType(DataType t, std::ostream& os) final;                        // NOLINT(*)\n  void PrintType(const Type& type, std::ostream& os) final;                  // NOLINT(*)\n  std::string GetVecLoad(DataType t, const BufferNode* buffer, PrimExpr base) final;\n  void PrintVecStore(const BufferNode* buffer, DataType t, PrimExpr base,\n                     const std::string& value) final;  // NOLINT(*)\n  // the address of load/store\n  void PrintVecAddr(const BufferNode* buffer, DataType t, PrimExpr base,\n                    std::ostream& os);                                           // NOLINT(*)\n  void PrintRestrict(const Var& v, std::ostream& os) final;                      // NOLINT(*)\n  std::string CastFromTo(std::string value, DataType from, DataType target);     // NOLINT(*)\n  std::string CastTo(std::string value, DataType target);                        // NOLINT(*)\n  void SetTextureScope(const std::unordered_map<const VarNode*, std::string>&);  // NOLINT(*)\n\n  // overload visitor\n  void VisitStmt_(const AllocateNode* op) final;                     // NOLINT(*)\n  void VisitExpr_(const BroadcastNode* op, std::ostream& os) final;  // NOLINT(*)\n  void VisitExpr_(const CallNode* op, std::ostream& os) final;       // NOLINT(*)\n  void VisitExpr_(const CastNode* op, std::ostream& os) final;       // NOLINT(*)\n  void VisitExpr_(const FloatImmNode* op, std::ostream& os) final;   // NOLINT(*)\n  void VisitStmt_(const StoreNode* op) final;                        // NOLINT(*)\n  void VisitStmt_(const BufferStoreNode* op) final;                  // NOLINT(*)\n\n  // overload min and max to avoid ambiguous call errors\n  void VisitExpr_(const MinNode* op, std::ostream& os) final;\n  void VisitExpr_(const MaxNode* op, std::ostream& os) final;\n  void VisitExpr_(const AndNode* op, std::ostream& os) final;\n  void VisitExpr_(const OrNode* op, std::ostream& os) final;\n  void VisitExpr_(const SelectNode* op, std::ostream& os) final;\n\n private:\n  // whether enable fp16 and fp64 extension\n  bool enable_fp16_{false};\n  bool enable_fp64_{false};\n  // Whether to enable atomics extension.\n  bool enable_atomics_{false};\n  // Whether to enable sampler or sampler-less texture reads,\n  // where the choice depends on the OpenCL version used.\n  bool enable_compliant_texture_reads_{false};\n  // Key to disable use of texture SSA in certain scenarios. For example,\n  // when loaded value is stored directly to a user declared l-value buffer\n  bool need_texture_ssa_{true};\n  // Mapping from buffer to allocation size.\n  // Useful to track when a scalar store of a vectorized texture load is required.\n  std::unordered_map<const Object*, size_t> allocation_size_;\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_OPENCL_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_params.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_params.h\n */\n\n#ifndef TVM_TARGET_SOURCE_CODEGEN_PARAMS_H_\n#define TVM_TARGET_SOURCE_CODEGEN_PARAMS_H_\n\n#include <tvm/runtime/ndarray.h>\n\n#include <iostream>\n#include <string>\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n * \\brief Write a C representation of arr to os.\n *\n * This function generates a comma-separated, indented list of C integer listeals suitable for use\n * in an initializer. The NDArray is flattened and then the list is produced element by element.\n * For the int16_t NDArray [-3, -2, -1, 0, 1, 2, 3, ...], and indent_chars = 4, the following output\n * is produced:\n *     -0x0003, -0x0002, -0x0001, +0x0000, +0x0001, +0x0002, +0x0003\n *\n * \\param arr The array to generate\n * \\param indent_chars Number of chars to indent\n * \\param os Output stream where the array data should be written.\n */\nvoid NDArrayDataToC(::tvm::runtime::NDArray arr, int indent_chars, std::ostream& os,\n                    const std::string& eol = \"\\n\");\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_PARAMS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_source_base.h",
        "content": "\n/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_source_base.h\n * \\brief Common utilities to source code in text form.\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_SOURCE_BASE_H_\n#define TVM_TARGET_SOURCE_CODEGEN_SOURCE_BASE_H_\n\n#include <tvm/ir/name_supply.h>\n#include <tvm/runtime/metadata.h>\n#include <tvm/target/codegen.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n\n#include <functional>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../runtime/meta_data.h\"\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n * \\brief A base class to generate source code.\n * Contains helper utilities to generate nest and ssa form.\n */\nclass CodeGenSourceBase {\n public:\n  virtual ~CodeGenSourceBase() = default;\n  /*!\n   * \\brief Register constant value appeared in expresion tree\n   *  This avoid generated a ssa id for each appearance of the value\n   * \\param value The constant value.\n   */\n  void MarkConst(std::string value);\n  /*!\n   * Print Type representation of type type.\n   * \\param t The type representation.\n   * \\param os The stream to print the ctype into\n   */\n  virtual void PrintType(DataType type, std::ostream& os);  // NOLINT(*)\n  /*!\n   * Print Type representation of type type.\n   * \\param type The type representation.\n   * \\param os The stream to print the ctype into\n   */\n  virtual void PrintType(const Type& type, std::ostream& os);  // NOLINT(*)\n\n protected:\n  /*! \\brief entry in ssa assign map */\n  struct SSAEntry {\n    /*! \\brief The value id */\n    std::string vid;\n    /*! \\brief The scope id, used to check if this entry is invalid. */\n    int scope_id;\n  };\n  /*! \\brief Clear the states that might relates to function generation */\n  void ClearFuncState();\n  /*! \\brief print the current indented value */\n  void PrintIndent();\n  /*!\n   * \\brief Allocate a variable name for a newly defined var.\n   * \\param v The variable.\n   * \\return the variable name.\n   */\n  std::string AllocVarID(const tir::VarNode* v);\n  /*!\n   * \\brief Get a variable name.\n   * \\param v The variable.\n   * \\return the variable name.\n   */\n  std::string GetVarID(const tir::VarNode* v) const;\n  /*!\n   * \\brief Get the SSA ID corresponds to src\n   *  If necessary, generate new assignment\n   * \\param src The source expression\n   * \\param t The type of the expression.\n   */\n  std::string SSAGetID(std::string src, DataType t);\n  /*!\n   * \\brief mark the beginning of a new scope\n   * \\return The scope id.\n   */\n  int BeginScope();\n  /*!\n   * \\brief mark the end of an old scope.\n   * \\param scope_id The scope id to be ended.\n   */\n  void EndScope(int scope_id);\n  /*!\n   * \\brief Print assignment of src to the id in ssa entry.\n   * \\param target id of target variable.\n   * \\param src The source expression.\n   * \\param t The type of target.\n   */\n  virtual void PrintSSAAssign(const std::string& target, const std::string& src, DataType t) = 0;\n\n  /*! \\brief the declaration stream */\n  std::ostringstream decl_stream;\n  /*! \\brief the stream to be printed */\n  std::ostringstream stream;\n  /*! \\brief name of each variable */\n  std::unordered_map<const tir::VarNode*, std::string> var_idmap_;\n  /*! \\brief NameSupply for allocation */\n  NameSupply name_supply_ = NameSupply(\"\");\n\n private:\n  /*! \\brief assignment map of ssa */\n  std::unordered_map<std::string, SSAEntry> ssa_assign_map_;\n  /*! \\brief array to check whether we are inside certain scope */\n  std::vector<bool> scope_mark_;\n  /*! \\brief The current indentation value */\n  int indent_{0};\n};\n\n/*!\n * \\brief Create a source module for viewing.\n * \\param code The code to be viewed.\n * \\param fmt The code. format.\n */\nruntime::Module SourceModuleCreate(std::string code, std::string fmt);\n\n/*!\n * \\brief Create a C source module for viewing and compiling GCC code.\n * \\param code The code to be viewed.\n * \\param fmt The code format.\n * \\param func_names The name of functions inside the runtime module.\n * \\param const_vars. The constant variables that the c source module needs.\n * \\return The created module.\n */\nruntime::Module CSourceModuleCreate(const String& code, const String& fmt,\n                                    const Array<String>& func_names,\n                                    const Array<String>& const_vars = {});\n\n/*!\n * \\brief Wrap the submodules in a metadata module.\n * \\param params The variable to constant mapping that is collected by the host\n *        module.\n * \\param target_module The main TIR-lowered internal runtime module\n * \\param modules All the external modules that needs to be imported inside the metadata module(s).\n * \\param target The target that all the modules are compiled for\n * \\param metadata Metadata which should be exported to the runtime.\n * \\return The wrapped module.\n */\nruntime::Module CreateMetadataModule(\n    const std::unordered_map<std::string, runtime::NDArray>& params, runtime::Module target_module,\n    const Array<runtime::Module>& ext_modules, Target target, runtime::metadata::Metadata metadata);\n\n/*!\n * \\brief Create a source module for viewing and limited saving for device.\n * \\param data The code data to be viewed.\n * \\param fmt The code. format.\n * \\param fmap The map function information map of each function.\n * \\param type_key The type_key of the runtime module of this source code\n * \\param fget_source a closure to replace default get source behavior.\n */\nruntime::Module DeviceSourceModuleCreate(\n    std::string data, std::string fmt, std::unordered_map<std::string, runtime::FunctionInfo> fmap,\n    std::string type_key, std::function<std::string(const std::string&)> fget_source = nullptr);\n\n/*!\n * \\brief Wrap the submodules that are to be wrapped in a c-source metadata module for C runtime.\n * \\param modules The modules to be wrapped.\n * \\param target the target the modules are compiled for.\n * \\param metadata the metadata needed for code generation.\n * \\return The wrapped module.\n */\nruntime::Module CreateCSourceCrtMetadataModule(const Array<runtime::Module>& modules, Target target,\n                                               runtime::metadata::Metadata metadata);\n\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_SOURCE_CODEGEN_SOURCE_BASE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/codegen_vhls.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n5B5B */\n\n/*!\n * \\file codegen_vhls.h\n * \\brief Utility to generate vhls code\n */\n#ifndef TVM_TARGET_SOURCE_CODEGEN_VHLS_H_\n#define TVM_TARGET_SOURCE_CODEGEN_VHLS_H_\n\n#include <tvm/target/codegen.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n\n#include \"codegen_c.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nclass CodeGenVivadoHLS final : public CodeGenC {\n public:\n  void Init(bool output_ssa);\n  void PrintType(DataType t, std::ostream& os);\n\n  void PrintFuncPrefix() final;\n  void PreFunctionBody(const PrimFunc& f) final;\n  void VisitExpr_(const MinNode* op, std::ostream& os) final;\n  void VisitExpr_(const MaxNode* op, std::ostream& os) final;\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_CODEGEN_VHLS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/literal/cuda_half_t.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file cuda_half_t.h\n * \\brief half_t (fp16) definition for cuda codegen.\n */\n#ifndef TVM_TARGET_SOURCE_LITERAL_CUDA_HALF_T_H_\n#define TVM_TARGET_SOURCE_LITERAL_CUDA_HALF_T_H_\n\nstatic constexpr const char* _cuda_half_t_def = R\"(\ntypedef unsigned short uint16_t;\ntypedef unsigned char uint8_t;\ntypedef signed char int8_t;\ntypedef int int32_t;\ntypedef unsigned long long uint64_t;\ntypedef unsigned int uint32_t;\n\n#define TVM_FORCE_INLINE inline __attribute__((always_inline))\n#define TVM_XINLINE TVM_FORCE_INLINE __device__ __host__\n#define TVM_ALIGNED(x) __attribute__ ((aligned(x)))\n#define TVM_HALF_OPERATOR(RTYPE, OP)                              \\\n  TVM_XINLINE RTYPE operator OP (half a, half b) {                \\\n    return RTYPE(float(a) OP float(b));                           \\\n  }                                                               \\\n  template<typename T>                                            \\\n  TVM_XINLINE RTYPE operator OP (half a, T b) {                   \\\n    return RTYPE(float(a) OP float(b));                           \\\n  }                                                               \\\n  template<typename T>                                            \\\n  TVM_XINLINE RTYPE operator OP (T a, half b) {                   \\\n    return RTYPE(float(a) OP float(b));                           \\\n  }\n\n#define TVM_HALF_ASSIGNOP(AOP, OP)                                \\\n  template<typename T>                                            \\\n  TVM_XINLINE half operator AOP (const T& a) {                    \\\n    return *this = half(float(*this) OP float(a));                \\\n  }                                                               \\\n  template<typename T>                                            \\\n  TVM_XINLINE half operator AOP (const volatile T& a) volatile {  \\\n    return *this = half(float(*this) OP float(a));                \\\n  }\n\nclass TVM_ALIGNED(2) half {\n public:\n  uint16_t half_;\n\n  static TVM_XINLINE half Binary(uint16_t value) {\n    half res;\n    res.half_ = value;\n    return res;\n  }\n\n  TVM_XINLINE half() {}\n\n  TVM_XINLINE half(const float& value) { constructor(value); }\n  TVM_XINLINE explicit half(const double& value) { constructor(value); }\n  TVM_XINLINE explicit half(const int8_t& value) { constructor(value); }\n  TVM_XINLINE explicit half(const uint8_t& value) { constructor(value); }\n  TVM_XINLINE explicit half(const int32_t& value) { constructor(value); }\n  TVM_XINLINE explicit half(const uint32_t& value) { constructor(value); }\n  TVM_XINLINE explicit half(const long long& value) { constructor(value); }\n  TVM_XINLINE explicit half(const uint64_t& value) { constructor(value); }\n\n  TVM_XINLINE operator float() const {                          \\\n    return float(half2float(half_));                            \\\n  }                                                             \\\n  TVM_XINLINE operator float() const volatile {                 \\\n    return float(half2float(half_));                            \\\n  }\n\n\n  TVM_HALF_ASSIGNOP(+=, +)\n  TVM_HALF_ASSIGNOP(-=, -)\n  TVM_HALF_ASSIGNOP(*=, *)\n  TVM_HALF_ASSIGNOP(/=, /)\n\n  TVM_XINLINE half operator+() {\n    return *this;\n  }\n\n  TVM_XINLINE half operator-() {\n    return half(-float(*this));\n  }\n\n  TVM_XINLINE half operator=(const half& a) {\n    half_ = a.half_;\n    return a;\n  }\n\n  template<typename T>\n  TVM_XINLINE half operator=(const T& a) {\n    return *this = half(a);\n  }\n\n  TVM_XINLINE half operator=(const half& a) volatile {\n    half_ = a.half_;\n    return a;\n  }\n\n  template<typename T>\n  TVM_XINLINE half operator=(const T& a) volatile {\n    return *this = half(a);\n  }\n\n private:\n  union Bits {\n    float f;\n    int32_t si;\n    uint32_t ui;\n  };\n\n  static int const fp16FractionBits = 10;\n  static int const fp32FractionBits = 23;\n  static int32_t const fp32FractionMask = ~(~0u << fp32FractionBits);   // == 0x7fffff\n  static int32_t const fp32HiddenBit = 1 << fp32FractionBits;   // == 0x800000\n  static int const shift = fp32FractionBits - fp16FractionBits;   // == 13\n  static int const shiftSign = 16;\n  static int32_t const expAdjust = 127 - 15;   // exp32-127 = exp16-15, so exp16 = exp32 - (127-15)\n\n  static int32_t const infN = 0x7F800000;   // flt32 infinity\n  static int32_t const maxN = 0x477FFFFF;   // max flt32 that's a flt16 normal after >> by shift\n  static int32_t const minN = 0x38800000;   // min flt16 normal as a flt32\n  static int32_t const maxZ = 0x33000000;   // max fp32 number that's still rounded to zero in fp16\n  static int32_t const signN = 0x80000000;  // flt32 sign bit\n\n  static int32_t const infC = infN >> shift;\n  static int32_t const nanN = (infC + 1) << shift;   // minimum flt16 nan as a flt32\n  static int32_t const maxC = maxN >> shift;\n  static int32_t const minC = minN >> shift;\n  static int32_t const signC = signN >> shiftSign;  // flt16 sign bit\n\n  static int32_t const mulN = 0x52000000;  // (1 << 23) / minN\n  static int32_t const mulC = 0x33800000;  // minN / (1 << (23 - shift))\n\n  static int32_t const subC = 0x003FF;  // max flt32 subnormal down shifted\n  static int32_t const norC = 0x00400;  // min flt32 normal down shifted\n\n  static int32_t const maxD = infC - maxC - 1;\n  static int32_t const minD = minC - subC - 1;\n\n  TVM_XINLINE uint16_t float2half(const float& value) const {\n    Bits v;\n    v.f = value;\n    uint32_t sign = v.si & signN;    // grab sign bit\n    v.si ^= sign;                    // clear sign bit from v\n    sign >>= shiftSign;              // logical shift sign to fp16 position\n\n    if (v.si <= maxZ) {\n      // Handle eventual zeros here to ensure\n      // vshift will not exceed 32 below.\n      v.ui = 0;\n    } else if (v.si < minN) {\n      // Handle denorms\n      uint32_t exp32 = v.ui >> fp32FractionBits;\n      int32_t exp16 = exp32 - expAdjust;\n      // If exp16 == 0 (just into the denorm range), then significant should be shifted right 1.\n      // Smaller (so negative) exp16 values should result in greater right shifts.\n      uint32_t vshift = 1 - exp16;\n      uint32_t significand = fp32HiddenBit | (v.ui & fp32FractionMask);\n      v.ui = significand >> vshift;\n      v.ui += (v.ui & 0x3fff) != 0x1000 || (significand & 0x7ff) ? 0x1000 : 0;\n    } else if (v.si <= maxN) {\n      // Handle norms\n      v.ui += (v.ui & 0x3fff) != 0x1000 ? 0x1000 : 0;\n      v.ui -= expAdjust << fp32FractionBits;\n    } else if (v.si <= infN) {\n      v.si = infN;\n    } else if (v.si < nanN) {\n      v.si = nanN;\n    }\n\n    v.ui >>= shift;\n    return sign | (v.ui & 0x7fff);\n  }\n\n  // Same as above routine, except for addition of volatile keyword\n  TVM_XINLINE uint16_t float2half(\n    const volatile float& value) const volatile {\n    Bits v;\n    v.f = value;\n    uint32_t sign = v.si & signN;    // grab sign bit\n    v.si ^= sign;                    // clear sign bit from v\n    sign >>= shiftSign;              // logical shift sign to fp16 position\n\n    if (v.si <= maxZ) {\n      // Handle eventual zeros here to ensure\n      // vshift will not exceed 32 below.\n      v.ui = 0;\n    } else if (v.si < minN) {\n      // Handle denorms\n      uint32_t exp32 = v.ui >> fp32FractionBits;\n      int32_t exp16 = exp32 - expAdjust;\n      // If exp16 == 0 (just into the denorm range), then significant should be shifted right 1.\n      // Smaller (so negative) exp16 values should result in greater right shifts.\n      uint32_t vshift = 1 - exp16;\n      uint32_t significand = fp32HiddenBit | (v.ui & fp32FractionMask);\n      v.ui = significand >> vshift;\n      v.ui += (v.ui & 0x3fff) != 0x1000 || (significand & 0x7ff) ? 0x1000 : 0;\n    } else if (v.si <= maxN) {\n      // Handle norms\n      v.ui += (v.ui & 0x3fff) != 0x1000 ? 0x1000 : 0;\n      v.ui -= expAdjust << fp32FractionBits;\n    } else if (v.si <= infN) {\n      v.si = infN;\n    } else if (v.si < nanN) {\n      v.si = nanN;\n    }\n\n    v.ui >>= shift;\n    return sign | (v.ui & 0x7fff);\n  }\n\n  TVM_XINLINE float half2float(const uint16_t& value) const {\n    Bits v;\n    v.ui = value;\n    int32_t sign = v.si & signC;\n    v.si ^= sign;\n    sign <<= shiftSign;\n    v.si ^= ((v.si + minD) ^ v.si) & -(v.si > subC);\n    v.si ^= ((v.si + maxD) ^ v.si) & -(v.si > maxC);\n    Bits s;\n    s.si = mulC;\n    s.f *= v.si;\n    int32_t mask = -(norC > v.si);\n    v.si <<= shift;\n    v.si ^= (s.si ^ v.si) & mask;\n    v.si |= sign;\n    return v.f;\n  }\n\n  TVM_XINLINE float half2float(\n    const volatile uint16_t& value) const volatile {\n    Bits v;\n    v.ui = value;\n    int32_t sign = v.si & signC;\n    v.si ^= sign;\n    sign <<= shiftSign;\n    v.si ^= ((v.si + minD) ^ v.si) & -(v.si > subC);\n    v.si ^= ((v.si + maxD) ^ v.si) & -(v.si > maxC);\n    Bits s;\n    s.si = mulC;\n    s.f *= v.si;\n    int32_t mask = -(norC > v.si);\n    v.si <<= shift;\n    v.si ^= (s.si ^ v.si) & mask;\n    v.si |= sign;\n    return v.f;\n  }\n\n  template<typename T>\n  TVM_XINLINE void constructor(const T& value) {\n    half_ = float2half(float(value));\n  }\n};\n\nTVM_HALF_OPERATOR(half, +)\nTVM_HALF_OPERATOR(half, -)\nTVM_HALF_OPERATOR(half, *)\nTVM_HALF_OPERATOR(half, /)\nTVM_HALF_OPERATOR(bool, >)\nTVM_HALF_OPERATOR(bool, <)\nTVM_HALF_OPERATOR(bool, >=)\nTVM_HALF_OPERATOR(bool, <=)\n\nTVM_XINLINE half __float2half_rn(const float a) {\n  return half(a);\n}\n)\";\n\nstatic constexpr const char* _cuda_half_util = R\"(\n// Pack two half values.\nstatic inline __device__ __host__ unsigned\n__pack_half2(const half x, const half y) {\n  unsigned v0 = *((unsigned short *)&x);\n  unsigned v1 = *((unsigned short *)&y);\n  return (v1 << 16) | v0;\n}\n\n// Some fp16 math functions are not supported in cuda_fp16.h,\n// so we define them here to make sure the generated CUDA code\n// is valid.\n#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 530)\n#define CUDA_UNSUPPORTED_HALF_MATH_BINARY(HALF_MATH_NAME, FP32_MATH_NAME) \\\nstatic inline __device__ __host__ half HALF_MATH_NAME(half x, half y) {   \\\n  float tmp_x = __half2float(x);                                          \\\n  float tmp_y = __half2float(y);                                          \\\n  float result = FP32_MATH_NAME(tmp_x, tmp_y);                            \\\n  return __float2half(result);                                            \\\n}\n\n#define CUDA_UNSUPPORTED_HALF_MATH_UNARY(HALF_MATH_NAME, FP32_MATH_NAME) \\\nstatic inline __device__ __host__ half HALF_MATH_NAME(half x) {          \\\n  float tmp_x = __half2float(x);                                         \\\n  float result = FP32_MATH_NAME(tmp_x);                                  \\\n  return __float2half(result);                                           \\\n}\n\nCUDA_UNSUPPORTED_HALF_MATH_BINARY(hpow, powf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(htanh, tanhf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(htan, tanf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(hatan, atanf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(herf, erf)\n\n#undef CUDA_UNSUPPORTED_HALF_MATH_BINARY\n#undef CUDA_UNSUPPORTED_HALF_MATH_UNARY\n\n#endif\n)\";\n\nstatic constexpr const char* _cuda_bfloat16_util = R\"(\n// Pack two bfloat16 values.\nstatic inline __device__ __host__ unsigned\n__pack_nv_bfloat162(const nv_bfloat16 x, const nv_bfloat16 y) {\n  unsigned v0 = *((unsigned short *)&x);\n  unsigned v1 = *((unsigned short *)&y);\n  return (v1 << 16) | v0;\n}\n\n// Some bfp16 math functions are not supported in cuda_bfp16.h,\n// so we define them here to make sure the generated CUDA code\n// is valid.\n#define CUDA_UNSUPPORTED_HALF_MATH_BINARY(HALF_MATH_NAME, FP32_MATH_NAME) \\\nstatic inline __device__ __host__ nv_bfloat16 HALF_MATH_NAME(nv_bfloat16 x, nv_bfloat16 y) {   \\\n  float tmp_x = __bfloat162float(x);                                      \\\n  float tmp_y = __bfloat162float(y);                                      \\\n  float result = FP32_MATH_NAME(tmp_x, tmp_y);                            \\\n  return __float2bfloat16(result);                                        \\\n}\n\n#define CUDA_UNSUPPORTED_HALF_MATH_UNARY(HALF_MATH_NAME, FP32_MATH_NAME) \\\nstatic inline __device__ __host__ nv_bfloat16 HALF_MATH_NAME(nv_bfloat16 x) {          \\\n  float tmp_x = __bfloat162float(x);                                     \\\n  float result = FP32_MATH_NAME(tmp_x);                                  \\\n  return __float2bfloat16(result);                                       \\\n}\n\nCUDA_UNSUPPORTED_HALF_MATH_BINARY(hpow, powf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(htanh, tanhf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(htan, tanf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(hatan, atanf)\nCUDA_UNSUPPORTED_HALF_MATH_UNARY(herf, erf)\n\n#undef CUDA_UNSUPPORTED_HALF_MATH_BINARY\n#undef CUDA_UNSUPPORTED_HALF_MATH_UNARY\n)\";\n\nstatic constexpr const char* _cuda_warp_intrinsic_util = R\"(\n#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)\n#define __shfl_sync(mask, var, lane, width) \\\n        __shfl((var), (lane), (width))\n\n#define __shfl_down_sync(mask, var, offset, width) \\\n        __shfl_down((var), (offset), (width))\n\n#define __shfl_up_sync(mask, var, offset, width) \\\n        __shfl_up((var), (offset), (width))\n#endif\n\n)\";\n\n#endif  // TVM_TARGET_SOURCE_LITERAL_CUDA_HALF_T_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/ptx.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ptx.h\n * \\brief Code generation with inlined PTX code.\n */\n#ifndef TVM_TARGET_SOURCE_PTX_H_\n#define TVM_TARGET_SOURCE_PTX_H_\n\n#include <tvm/runtime/logging.h>\n\n#include <string>\n#include <tuple>\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n * \\brief Print MMA assembly string given parameters.\n * \\param shape The shape string mMnNkK\n * \\param A_layout The layout of multiplicand A, can be either \"row\" or \"col\".\n * \\param B_layout The layout of multiplicand B, can be either \"row\" or \"col\".\n * \\param A_dtype The data type of multiplicand A.\n * \\param B_dtype The data type of multiplicand B.\n * \\param C_dtype The data type of multiplicand C.\n * \\param a_ptr Pointer to buffer A.\n * \\param a_offset The offset of element in A.\n * \\param b_ptr Pointer to buffer B.\n * \\param b_offset The offset of element in B.\n * \\param c_ptr Pointer to buffer C.\n * \\param c_offset The offset of element in C.\n * \\param metadata Pointer to metadata buffer (only used for sparse mma).\n * \\param metadata_offset The offset of element in metadata.\n * \\param sparsity_selector The sparsity selector in sparse mma.\n * \\param bit_op The bit operator used in 1-bit mma, can be either \"xor\" or \"and\".\n * \\param sparse Whether it's sparse mma or not.\n * \\param saturate Whether saturate output or not.\n */\nstd::string PrintMMAAssembly(const std::string& shape, const std::string& A_layout,\n                             const std::string& B_layout, const std::string& A_dtype,\n                             const std::string& B_dtype, const std::string& C_dtype,\n                             const std::string& a_ptr, const std::string& a_offset,\n                             const std::string& b_ptr, const std::string& b_offset,\n                             const std::string& c_ptr, const std::string& c_offset,\n                             const std::string& metadata, const std::string& metadata_offset,\n                             const std::string& sparsity_selector, const std::string& bit_op,\n                             bool sparse, bool saturate);\n\n/*!\n * \\brief Print ldmatrix assembly string given parameters.\n * \\param trans: whether the matrix is loaded in column major format or not.\n * \\param num: number of matrices to load.\n * \\param type: The data type in the matrix, .b16 is the only accepted data type.\n * \\param local_ptr: pointer to local buffer.\n * \\param local_elem_offset: The offset of the element to store in the local buffer.\n * \\param smem_ptr: pointer to the shared memory buffer to load.\n * \\param smem_elem_offset: The offset of the start element of the row to load in shared memory.\n */\nstd::string PrintLoadMatrixAssembly(bool trans, int num, const std::string& type,\n                                    const std::string& local_ptr,\n                                    const std::string& local_elem_offset,\n                                    const std::string& smem_ptr,\n                                    const std::string& smem_elem_offset);\n\n/*!\n * \\brief Print ptx cp.async assembly string given parameters.\n * \\param shared_ptr: The pointer to the destination shared memory.\n * \\param shared_elem_offset: The offset into the shared memory.\n * \\param global_ptr: The pointer to the global memory.\n * \\param global_elem_offset: The offset into the global memory.\n * \\param bytes: The number of bytes to copy, valid values are 4, 8, and 16.\n */\nstd::string PrintCpAsyncAssembly(const std::string& shared_ptr,\n                                 const std::string& shared_elem_offset,\n                                 const std::string& global_ptr,\n                                 const std::string& global_elem_offset, const std::string& bytes);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_PTX_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/source/source_module.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file source_module.h\n * \\brief Source code module\n */\n\n#ifndef TVM_TARGET_SOURCE_SOURCE_MODULE_H_\n#define TVM_TARGET_SOURCE_SOURCE_MODULE_H_\n\n#include <tvm/relay/runtime.h>\n#include <tvm/runtime/metadata.h>\n#include <tvm/runtime/module.h>\n#include <tvm/target/target.h>\n\n#include \"../../relay/backend/utils.h\"\n#include \"../../runtime/meta_data.h\"\n\nnamespace tvm {\nnamespace codegen {\n\n/*!\n\n * \\brief Wrap the submodules that are to be wrapped in a c-source metadata module for C runtime.\n * \\param modules The modules to be wrapped.\n * \\param target the target the modules are compiled for.\n * \\param runtime the runtime to code generate against\n * \\param metadata Compiler-generated metadata exported to runtime.\n * \\param aot_metadata If supplied, metadata for the AOTExecutor module.\n * \\return The wrapped module.\n */\nruntime::Module CreateCSourceCrtMetadataModule(const Array<runtime::Module>& modules, Target target,\n                                               relay::Runtime runtime,\n                                               relay::backend::ExecutorCodegenMetadata metadata,\n                                               runtime::metadata::Metadata aot_metadata);\n\n/*!\n * \\brief Create C++-runtime targeted metadata module for \"c\" backend.\n * \\param metadata Compiler-generated metadata.\n */\nruntime::Module CreateCSourceCppMetadataModule(runtime::metadata::Metadata metadata);\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SOURCE_SOURCE_MODULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/spirv/codegen_spirv.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ir_builder.h\n * \\brief Utility for building SPIRV code block\n */\n#ifndef TVM_TARGET_SPIRV_CODEGEN_SPIRV_H_\n#define TVM_TARGET_SPIRV_CODEGEN_SPIRV_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/target/target.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../runtime/thread_storage_scope.h\"\n#include \"../../runtime/vulkan/vulkan_shader.h\"\n#include \"ir_builder.h\"\n#include \"spirv_support.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nusing namespace tir;\n\n/*!\n * \\brief Code generator into SPIRV\n */\nclass CodeGenSPIRV : public ExprFunctor<spirv::Value(const PrimExpr&)>,\n                     public StmtFunctor<void(const Stmt&)> {\n public:\n  /*!\n   * \\brief Initialize the codegen based on a specific target.\n   *\n   * \\param target The target for which code should be generated.  The\n   * device_type for this target must be kDLVulkan.\n   */\n  CodeGenSPIRV(Target target);\n\n  /*!\n   * \\brief Compile and add function f to the current module.\n   * \\param f The function to be added.\n   * \\param name The name of the target function.\n   * \\return The final spirv module.\n   */\n  virtual runtime::VulkanShader BuildFunction(const PrimFunc& f, const std::string& name);\n  /*!\n   * \\brief Create Value for expression e\n   * \\param e The expression to be created value for.\n   * \\return created value.\n   */\n  spirv::Value MakeValue(const PrimExpr& e) { return VisitExpr(e); }\n  // override codegen\n  spirv::Value VisitExpr_(const VarNode* op) override;\n  spirv::Value VisitExpr_(const CastNode* op) override;\n  spirv::Value VisitExpr_(const IntImmNode* op) override;\n  spirv::Value VisitExpr_(const FloatImmNode* op) override;\n  spirv::Value VisitExpr_(const StringImmNode* op) override;\n  spirv::Value VisitExpr_(const AddNode* op) override;\n  spirv::Value VisitExpr_(const SubNode* op) override;\n  spirv::Value VisitExpr_(const MulNode* op) override;\n  spirv::Value VisitExpr_(const DivNode* op) override;\n  spirv::Value VisitExpr_(const ModNode* op) override;\n  spirv::Value VisitExpr_(const MinNode* op) override;\n  spirv::Value VisitExpr_(const MaxNode* op) override;\n  spirv::Value VisitExpr_(const LTNode* op) override;\n  spirv::Value VisitExpr_(const LENode* op) override;\n  spirv::Value VisitExpr_(const GTNode* op) override;\n  spirv::Value VisitExpr_(const GENode* op) override;\n  spirv::Value VisitExpr_(const EQNode* op) override;\n  spirv::Value VisitExpr_(const NENode* op) override;\n  spirv::Value VisitExpr_(const AndNode* op) override;\n  spirv::Value VisitExpr_(const OrNode* op) override;\n  spirv::Value VisitExpr_(const NotNode* op) override;\n  spirv::Value VisitExpr_(const SelectNode* op) override;\n  spirv::Value VisitExpr_(const LetNode* op) override;\n  spirv::Value VisitExpr_(const CallNode* op) override;\n  spirv::Value VisitExpr_(const RampNode* op) override;\n  spirv::Value VisitExpr_(const BroadcastNode* op) override;\n  spirv::Value VisitExpr_(const BufferLoadNode* op) override;\n  // stmt\n  void VisitStmt_(const BufferStoreNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const WhileNode* op) override;\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const AllocateNode* op) override;\n  void VisitStmt_(const AttrStmtNode* op) override;\n  void VisitStmt_(const AssertStmtNode* op) override;\n  void VisitStmt_(const LetStmtNode* op) override;\n  void VisitStmt_(const SeqStmtNode* op) override;\n  void VisitStmt_(const EvaluateNode* op) override;\n\n protected:\n  /*! \\brief Storage information for a buffer */\n  struct StorageInfo {\n    /*! \\brief The name of the tir::Var for the buffer\n     *\n     * Used for error messages.\n     */\n    std::string name_hint;\n\n    /*! \\brief Whether it is volatile */\n    bool is_volatile{false};\n\n    /*! \\brief Whether the element type of the buffer is known.\n     *\n     * This value is determined based on the type_annotation of the\n     * buffer variable (AllocateNode) or of the parameter (shader\n     * arguments).\n     */\n    bool element_type_known{false};\n\n    /*! \\brief The known element type of the buffer.\n     *\n     * This value is determined based on the type_annotation of the\n     * buffer variable (AllocateNode) or of the parameter (shader\n     * arguments).\n     */\n    DataType element_type{DataType()};\n\n    /* \\brief Check that the access type matches the known type\n     *\n     * Asserts that the type given is the same as the type previously\n     * stored in this array.\n     *\n     * @param type The data type being stored/loaded in the buffer\n     *\n     * @param index_lanes The number of lanes of the index.  The\n     * number of lanes in the value being stored/loaded should be the\n     * product of the number of lanes of the buffer element type and\n     * the number of lanes of the index.\n     */\n    void CheckContentType(DataType type, int index_lanes = 1) {\n      ICHECK(element_type_known) << \"Cannot check element type of buffer \" << name_hint\n                                 << \" no previous element type defined\";\n      DataType expected_type = element_type.with_lanes(index_lanes * element_type.lanes());\n      ICHECK_EQ(type, expected_type) << \"Attempted to access buffer \" << name_hint\n                                     << \" as element type \" << type << \" using an index of size \"\n                                     << index_lanes << \" when the element type is \" << element_type;\n    }\n\n    // Update content type if it hasn't been updated.\n    void SetContentType(DataType type, std::string name_hint) {\n      ICHECK(!element_type_known) << \"Cannot set element type of buffer \" << name_hint\n                                  << \" a second time.\";\n      this->element_type = type;\n      this->name_hint = name_hint;\n      element_type_known = true;\n    }\n  };\n  // Reset the state so it works for a new function.\n  void InitFuncState();\n  // Get the thread index\n  spirv::Value GetThreadIndex(const IterVar& iv, const PrimExpr& extent);\n\n  spirv::Value CreateStorageSync(const CallNode* op);\n  void Scalarize(const PrimExpr& e, std::function<void(int i, spirv::Value v)> f);\n\n  // SPIRV-related capabilities of the target\n  SPIRVSupport spirv_support_;\n\n  // The builder\n  std::unique_ptr<spirv::IRBuilder> builder_;\n\n  // Work group size of three\n  uint32_t workgroup_size_[3];\n\n  // Likely branch\n  uint32_t weight_likely_branch_{128};\n\n  /* The data type used for the backing array for booleans.\n   *\n   * Currently matched to the data type used in Buffer::vstore and\n   * Buffer::vload.  In the future, this should be the smallest\n   * integer type supported by the device, as not all Vulkan\n   * implementations support int8.\n   */\n  DataType boolean_storage_type_{DataType::Int(8)};\n\n  // the storage scope of allocation\n  std::unordered_map<const VarNode*, StorageInfo> storage_info_;\n\n  // The definition of local variable.\n  std::unordered_map<const VarNode*, spirv::Value> var_map_;\n\n  // The analyzer.\n  std::unique_ptr<arith::Analyzer> analyzer_;\n\n  // deep comparison of PrimExpr\n  ExprDeepEqual deep_equal_;\n\n  // binding of let variables. Enables duplicate var defs that map to same value\n  std::unordered_map<Var, const LetNode*, ObjectPtrHash, ObjectPtrEqual> let_binding_;\n\n  // Running total of the number of bytes of shared memory used.\n  // Checked against the max_shared_memory_per_group\n  size_t shared_memory_bytes_used_{0};\n};\n\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SPIRV_CODEGEN_SPIRV_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/spirv/ir_builder.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ir_builder.h\n * \\brief Utility for building SPIRV code block\n */\n#ifndef TVM_TARGET_SPIRV_IR_BUILDER_H_\n#define TVM_TARGET_SPIRV_IR_BUILDER_H_\n\n#include <tvm/runtime/packed_func.h>\n#include <tvm/tir/expr.h>\n\n// clang-format off\n#include <algorithm>\n#include <map>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <tuple>\n#include <spirv.hpp>\n// clang-format on\n\n#include \"spirv_support.h\"\n\nnamespace tvm {\nnamespace codegen {\nnamespace spirv {\n\n/*! \\brief Represent the SPIRV Type */\nstruct SType {\n  /*! \\brief The Id to represent type */\n  uint32_t id{0};\n  /*! \\brief corresponding TVM type */\n  tvm::DataType type;\n  /*! \\brief content type id if it is a pointer/struct-array class */\n  uint32_t element_type_id{0};\n  /*! \\brief The storage class, if it is a pointer */\n  spv::StorageClass storage_class{spv::StorageClassMax};\n};\n\nenum ValueKind {\n  kNormal,\n  kConstant,\n  kVectorPtr,\n  kStructArrayPtr,\n  kPushConstantPtr,\n  kFunction,\n  kExtInst,\n  kUniformPtr\n};\n\n/*! \\brief Represent the SPIRV Value */\nstruct Value {\n  /*! \\brief The Id to represent value */\n  uint32_t id{0};\n  /*! \\brief The data type */\n  SType stype;\n  /*! \\brief additional flags about the value */\n  ValueKind flag{kNormal};\n};\n\n/*! \\brief Represent the SPIRV Label */\nstruct Label {\n  /*! \\brief The Id to represent label */\n  uint32_t id{0};\n};\n\n/*!\n * \\brief A SPIRV instruction,\n *  can be used as handle to modify its content later\n */\nclass Instr {\n public:\n  /*! \\return the word count */\n  uint32_t WordCount() const { return word_count_; }\n  /*!\n   * \\brief Access idx-th word of instruction\n   * \\param idx The index\n   * \\return reference to idx-th word.\n   */\n  uint32_t& operator[](uint32_t idx) {\n    ICHECK_LT(idx, word_count_);\n    return (*data_)[begin_ + idx];\n  }\n\n private:\n  friend class InstrBuilder;\n  /*!\n   * \\brief the data that backs this instruction\n   *  Have to use vector reference because\n   *  vector can change.\n   */\n  std::vector<uint32_t>* data_{nullptr};\n  /*! \\brief begin location of instruction */\n  uint32_t begin_{0};\n  /*! \\brief work count */\n  uint32_t word_count_{0};\n};\n\n/*! \\brief Representation of phi value */\nstruct PhiValue : public Value {\n  /*! \\brief The corresponding instr */\n  Instr instr;\n  /*!\n   * \\brief Add incoming information of a PhiValue\n   * \\param index The location of Phi\n   * \\param value The value to come\n   * \\param parent The parent label.\n   */\n  void SetIncoming(uint32_t index, const Value& value, const Label& parent) {\n    ICHECK_EQ(this->stype.id, value.stype.id);\n    instr[3 + index * 2] = value.id;\n    instr[3 + index * 2 + 1] = parent.id;\n  }\n};\n\n/*!\n * \\brief Helper class to build SPIRV instruction.\n *\n * \\code\n *\n *  std::vector<uint32_t> func_seg_vec_;\n *  InstrBuilder ib;\n *\n *  // construct and append to the end of func_seg_vec_;\n *  ib.Begin(spv::OpIAdd)\n *    .Add(result).Add(v1).Add(v2)\n *    .Commit(&func_seg_vec_);\n *\n * \\endcode\n */\nclass InstrBuilder {\n public:\n  /*!\n   * \\brief Begin construction of instruction.\n   * \\param op The op code\n   * \\return reference to self.\n   */\n  InstrBuilder& Begin(spv::Op op) {  // NOLINT(*);\n    // finish previous build\n    ICHECK_EQ(data_.size(), 0U);\n    op_ = op;\n    data_.push_back(0);\n    return *this;\n  }\n  /*!\n   * \\brief Add v to end of instruction.\n   * \\param v The value to be appended to the instruction.\n   * \\return reference to self.\n   */\n  InstrBuilder& Add(const Value& v) {\n    data_.push_back(v.id);\n    return *this;\n  }\n  /*!\n   * \\brief Add v to end of instruction.\n   * \\param v The type to be appended to the instruction.\n   * \\return reference to self.\n   */\n  InstrBuilder& Add(const SType& v) {\n    data_.push_back(v.id);\n    return *this;\n  }\n  /*!\n   * \\brief Add v to end of instruction.\n   * \\param v The label to be appended to the instruction.\n   * \\return reference to self.\n   */\n  InstrBuilder& Add(const Label& v) {\n    data_.push_back(v.id);\n    return *this;\n  }\n  /*!\n   * \\brief Add a word to end of instruction.\n   * \\param v The value to be added.\n   * \\return reference to self.\n   */\n  InstrBuilder& Add(const uint32_t& v) {\n    data_.push_back(v);\n    return *this;\n  }\n  /*!\n   * \\brief Add string literal of end of instruction.\n   * \\param v The string literal to be appended.\n   * \\return reference to self.\n   */\n  InstrBuilder& Add(const std::string& v) {\n    const uint32_t kWordSize = sizeof(uint32_t);\n    uint32_t nwords = (static_cast<uint32_t>(v.length()) + kWordSize) / kWordSize;\n    size_t begin = data_.size();\n    data_.resize(begin + nwords, 0U);\n    std::copy(v.begin(), v.end(), reinterpret_cast<char*>(&data_[begin]));\n    return *this;\n  }\n  /*!\n   * \\brief add sequence of values to instruction\n   * \\param args The instruction sequence\n   * \\return reference to self.\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  InstrBuilder& AddSeq(Args&&... args) {\n    AddSeqHelper helper;\n    helper.builder = this;\n    runtime::detail::for_each(helper, std::forward<Args>(args)...);\n    return *this;\n  }\n  /*!\n   * \\brief Finish build, commit the current\n   *   instruction to the end of seg.\n   *\n   * \\param seg The code segment to commit to\n   * \\return The result instruction.\n   */\n  Instr Commit(std::vector<uint32_t>* seg) {\n    Instr ret;\n    ret.data_ = seg;\n    ret.begin_ = seg->size();\n    ret.word_count_ = static_cast<uint32_t>(data_.size());\n    data_[0] = op_ | (ret.word_count_ << spv::WordCountShift);\n    seg->insert(seg->end(), data_.begin(), data_.end());\n    data_.clear();\n    return ret;\n  }\n\n private:\n  // current op code.\n  spv::Op op_;\n  // The internal data to store code\n  std::vector<uint32_t> data_;\n  // helper class to support variadic arguments\n  struct AddSeqHelper {\n    // The reference to builder\n    InstrBuilder* builder;\n    // invoke function\n    template <typename T>\n    void operator()(size_t, const T& v) const {\n      builder->Add(v);\n    }\n  };\n};\n\n/*!\n * \\brief Builder to build up a single SPIR-V module\n *\n *  This is a thin wrapper to build SPIRV binary.\n *  SPIRV adopts structure control-flow.\n *  We can build the code by always appending to the end of the\n *  binary code block and revisit some\n *\n *  This IRBuilder did not introduce concept of BasicBlock.\n *  instead instructions are append to end of each segment.\n */\nclass IRBuilder {\n public:\n  /*!\n   * \\brief Initialize the codegen based on a specific feature set.\n   *\n   * \\param support The features in SPIRV that are supported by the\n   * target device.\n   */\n  explicit IRBuilder(const SPIRVSupport& support);\n\n  /*! \\brief Initialize header */\n  void InitHeader();\n  /*! \\brief Initialize the predefined contents */\n  void InitPreDefs();\n  /*!\n   * \\brief Import additional extension libraries.\n   * \\param name The name of the library.\n   * \\return The finalized binary instruction.\n   */\n  Value ExtInstImport(const std::string& name) {\n    auto it = ext_inst_tbl_.find(name);\n    if (it != ext_inst_tbl_.end()) {\n      return it->second;\n    }\n    Value val = NewValue(SType(), kExtInst);\n    ib_.Begin(spv::OpExtInstImport).AddSeq(val, name).Commit(&extended_instruction_section_);\n    ext_inst_tbl_[name] = val;\n    return val;\n  }\n  /*!\n   * \\brief Get the final binary built from the builder\n   * \\return The finalized binary instruction.\n   */\n  std::vector<uint32_t> Finalize();\n\n  /*!\n   * \\brief Create new label\n   * \\return The created new label\n   */\n  Label NewLabel() {\n    Label label;\n    label.id = id_counter_++;\n    return label;\n  }\n  /*!\n   * \\brief Start a new block with given label\n   * \\param label The label we use.\n   */\n  void StartLabel(Label label) {\n    MakeInst(spv::OpLabel, label);\n    curr_label_ = label;\n  }\n  /*! \\return The current label */\n  Label CurrentLabel() const { return curr_label_; }\n  /*!\n   * \\brief Add code to debug segment.\n   * \\param op The operator\n   * \\param args The instruction sequence\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  void Debug(spv::Op op, Args&&... args) {\n    ib_.Begin(op).AddSeq(std::forward<Args>(args)...).Commit(&debug_);\n  }\n\n  /*!\n   * \\brief Set the name of a value or label\n   * \\param obj The object to be named\n   * \\param name The name of the object\n   * \\tparams Obj The type of the object being named.  Typically a Label or Value.\n   */\n  template <typename Obj>\n  void SetName(Obj&& obj, const std::string& name) {\n    Debug(spv::OpName, std::forward<Obj>(obj), name);\n  }\n\n  /*!\n   * \\brief Add Execution mode to a function.\n   * \\param func The function value\n   * \\param args The instruction sequence\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  void ExecutionMode(Value func, Args&&... args) {\n    ib_.Begin(spv::OpExecutionMode).AddSeq(func, std::forward<Args>(args)...).Commit(&exec_mode_);\n  }\n  /*!\n   * \\brief Add code to decorate segment.\n   * \\param op The operator\n   * \\param args The instruction sequence\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  void Decorate(spv::Op op, Args&&... args) {\n    ib_.Begin(op).AddSeq(std::forward<Args>(args)...).Commit(&decorate_);\n  }\n  /*!\n   * \\brief Add code to global segment.\n   * \\param op The operator\n   * \\param args The instruction sequence\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  void DeclareGlobal(spv::Op op, Args&&... args) {\n    ib_.Begin(op).AddSeq(std::forward<Args>(args)...).Commit(&global_);\n  }\n  /*!\n   * \\brief Make a new instruction and append it to end of function segment.\n   *\n   * \\param op The operator\n   * \\param args The instruction sequence\n   * \\return The result SSA value.\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  Instr MakeInst(spv::Op op, Args&&... args) {\n    return ib_.Begin(op).AddSeq(std::forward<Args>(args)...).Commit(&function_);\n  }\n  /*!\n   * \\brief Make a new SSA value,\n   *\n   * \\param op The operator.\n   * \\param out_type The result type.\n   * \\param args The instruction sequence\n   * \\return The result SSA value.\n   * \\tparams Args The positional arguments\n   */\n  template <typename... Args>\n  Value MakeValue(spv::Op op, const SType& out_type, Args&&... args) {\n    Value val = NewValue(out_type, kNormal);\n    MakeInst(op, out_type, val, std::forward<Args>(args)...);\n    return val;\n  }\n  /*!\n   * \\brief Make a phi value.\n   *\n   * \\param out_type The output data type.\n   * \\param num_incoming number of incoming blocks.\n   * \\return The result Phi value.\n   */\n  PhiValue MakePhi(const SType& out_type, uint32_t num_incoming);\n  /*!\n   * \\brief Create a GLSL450 call\n   *\n   * \\param ret_type The result type.\n   * \\param inst_id The instance id of the function.\n   * \\param args The arguments\n   * \\return The result value.\n   */\n  Value CallGLSL450(const SType& ret_type, uint32_t inst_id, const std::vector<Value>& args);\n\n  /*!\n   * \\brief Create a SPIRV_KHR_integer_dot_product call\n   *\n   * \\param ret_type The result type.\n   * \\param args The arguments\n   * \\return The result value.\n   */\n  Value CallKHRIntegerDotProduct(const SType& ret_type, const std::vector<Value>& args,\n                                 const DataType& dtype);\n\n  /*!\n   * \\brief Build vector by concatenating components\n   *\n   * \\param vec The vector component\n   * \\tparams Args The positional arguments\n   */\n  Value Concat(const std::vector<Value>& vec);\n  /*!\n   * \\brief Get the spirv type for a given tvm data type.\n   * \\param dtype The data type.\n   * \\return The corresponding spirv type.\n   */\n  SType GetSType(const tvm::DataType& dtype);\n  /*!\n   * \\brief Get the pointer type that points to value_type\n   * \\param value_type.\n   * \\param storage_class The storage class\n   * \\return The corresponding spirv type.\n   */\n  SType GetPointerType(const SType& value_type, spv::StorageClass storage_class);\n  /*!\n   * \\brief Get a struct{ value_type[num_elems] } type.\n   * \\param value_type the content value type.\n   * \\param num_elems number of elements in array\n   *   num_elems = 0 means runtime array with BufferBlock Decoration\n   * \\param interface_block if this array type for interface blocks(input, output, uniform,\n   *   storage buffer).\n   *\n   * \\return The corresponding spirv type.\n   */\n  SType GetStructArrayType(const SType& value_type, uint32_t num_elems, bool interface_block);\n  /*!\n   * \\brief Get a struct array access with a given index.\n   * \\param ptr_type The pointer type.\n   * \\param buffer The buffer ptr to struct array\n   * \\param index The array index.\n   */\n  Value StructArrayAccess(const SType& ptr_type, Value buffer, Value index);\n  /*!\n   * \\brief Create a cast that cast value to dst_type\n   * \\param dst_type The target type.\n   * \\param value the source value.\n   * \\return The result value\n   */\n  Value Cast(const SType& dst_type, Value value);\n  /*\n   * \\brief Create a const integer.\n   * \\param dtype The content data type.\n   * \\param value The data value.\n   */\n  Value IntImm(const SType& dtype, int64_t value);\n  /*\n   * \\brief Create a const unsigned integer.\n   * \\param dtype The content data type.\n   * \\param value The data value.\n   */\n  Value UIntImm(const SType& dtype, uint64_t value);\n  /*\n   * \\brief Create a const float.\n   * \\param dtype The content data type.\n   * \\param value The data value.\n   */\n  Value FloatImm(const SType& dtype, double value);\n  /*\n   * \\brief Declare buffer argument of function\n   *\n   * \\param arg_type The type of argument.\n   * \\param descriptor_set The descriptor set we want to use.\n   * \\param binding The binding location in descriptor set.\n   * \\param The argument type.\n   */\n  Value BufferArgument(const SType& value_type, uint32_t descriptor_set, uint32_t binding);\n\n  /*!\n   * \\brief Declare POD arguments through push constants.\n   *\n   * \\note Only call this function once!\n   * \\param value_types The values in the push constant\n   * \\return reference to self.\n   */\n  Value DeclarePushConstant(const std::vector<SType>& value_types);\n  /*!\n   * \\brief Get i-th push constant\n   * \\param v_type The value type\n   * \\param index The push constant index\n   * \\return the value of push constant\n   */\n  Value GetPushConstant(Value ptr_push_const, const SType& v_type, uint32_t index);\n\n  /*!\n   * \\brief Declare POD arguments through uniform buffer.\n   *\n   * \\note Only call this function once!\n   * \\param value_types The values in the uniform buffer\n   * \\param descriptor_set The descriptor set we want to use\n   * \\param binding The binding location in descriptor set\n   * \\return reference to self.\n   */\n  Value DeclareUniformBuffer(const std::vector<SType>& value_types, uint32_t descriptor_set,\n                             uint32_t binding);\n  /*!\n   * \\brief Get i-th uniform constant\n   * \\param v_type The value type\n   * \\param index The uniform index\n   * \\return the value of uniform constant\n   */\n  Value GetUniform(Value ptr_ubo, const SType& v_type, uint32_t index);\n  /*!\n   * \\brief Declare a new function\n   * \\return The created function ID.\n   */\n  Value NewFunction();\n  /*!\n   * \\brief Declare the entry point for a kernel function. This should be\n   * invoked after building the function so the builder is aware of which\n   * variables to declare as part of the function's interface.\n   * \\param func The previously declared function.\n   * \\param name Name of the entry point.\n   */\n  void CommitKernelFunction(const Value& func, const std::string& name);\n  /*!\n   * \\brief Start function scope.\n   * \\param func function to be started.\n   */\n  void StartFunction(const Value& func);\n  /*!\n   * \\brief Set the local size of the function\n   * \\param func function of interest\n   * \\param local_size The local workgroup_size\n   */\n  void SetLocalSize(const Value& func, uint32_t local_size[3]);\n  /*\n   * \\brief Allocate space\n   * \\param value_type The content value type\n   * \\param num_elems Number of elements to allocate.\n   * \\param storage_class The storage class we want to store to.\n   */\n  Value Allocate(const SType& value_type, uint32_t num_elems, spv::StorageClass storage_class);\n  /*\n   * \\brief Get the i-th workgroup id.\n   * \\return The value representing the workgroup id.\n   */\n  Value GetWorkgroupID(uint32_t dim_index);\n  /*\n   * \\brief Get the i-th local id.\n   * \\return The value representing the local id.\n   */\n  Value GetLocalID(uint32_t dim_index);\n  // Expressions\n  Value Add(Value a, Value b);\n  Value Sub(Value a, Value b);\n  Value Mul(Value a, Value b);\n  Value Div(Value a, Value b);\n  Value Mod(Value a, Value b);\n  Value EQ(Value a, Value b);\n  Value NE(Value a, Value b);\n  Value LT(Value a, Value b);\n  Value LE(Value a, Value b);\n  Value GT(Value a, Value b);\n  Value GE(Value a, Value b);\n  Value Select(Value cond, Value a, Value b);\n\n private:\n  /*!\n   * \\brief Create new value\n   * \\return The created new label\n   */\n  Value NewValue(const SType& stype, ValueKind flag) {\n    Value val;\n    val.id = id_counter_++;\n    val.stype = stype;\n    val.flag = flag;\n    return val;\n  }\n\n  /*! \\brief Get a built-in value provided by SPIR-V\n   *\n   *  \\param built_in The SPIR-V built-in array to access.  For\n   *  example, spv::BuiltInLocalInvocationId to access the thread\n   *  id.\n   *\n   *  \\param index The index of the built-in array to access.\n   *\n   *  \\param name The name of the value being accessed.  For\n   *  example, \"threadIdx.x\".  This is for debug purposes, and is\n   *  used to tag the variable with OpName.\n   */\n  Value GetBuiltInValue(spv::BuiltIn built_in, uint32_t index, const std::string& name = \"\");\n\n  /*!\n   * \\brief The common function to declare push constants or uniform buffer\n   * \\param value_types The values in the push constants or uniform buffer\n   * \\param storage_class An enum defined by SPIR-V indicating push constant or uniform\n   * \\param kind An enum indicating push constant or uniform\n   * \\return The created new label\n   */\n  Value DeclareStorageVariable(const std::vector<SType>& value_types,\n                               spv::StorageClass storage_class, ValueKind kind);\n\n  /*!\n   * \\brief The common function to decorate storage buffer or uniform buffer arguments.\n   * \\param val The Value to be decorated.\n   * \\param descriptor_set The index of the descriptor set containing the buffer's descriptor\n   * \\param binding The index of the buffer's descriptor within the descriptor set\n   */\n  void DecorateBufferArgument(Value val, uint32_t descriptor_set, uint32_t binding);\n\n  // get constant given value encoded in uint64_t\n  Value GetConst_(const SType& dtype, const uint64_t* pvalue);\n  // declare type\n  SType DeclareType(const DataType& dtype);\n\n  // Declare the appropriate SPIR-V capabilities and extensions to use\n  // this data type.\n  void AddCapabilityFor(const DataType& dtype);\n\n  /*! \\brief SPIRV-related capabilities of the target\n   *\n   * This SPIRVSupport object is owned by the same CodeGenSPIRV\n   * object that owns the IRBuilder.  Therefore, safe to use a\n   * reference as the CodeGenSPIRV will live longer.\n   */\n  const SPIRVSupport& spirv_support_;\n\n  /*! \\brief internal instruction builder  */\n  InstrBuilder ib_;\n  /*! \\brief Current label */\n  Label curr_label_;\n  /*! \\brief The current maximum id */\n  uint32_t id_counter_{1};\n  /*! \\brief glsl 450 extension */\n  Value ext_glsl450_;\n  /*! \\brief Special cache int32, fp32, void*/\n  SType t_bool_, t_int32_, t_uint32_, t_fp32_, t_void_, t_void_func_;\n  /*! \\brief quick cache for const one i32 */\n  Value const_i32_zero_;\n\n  /*! \\brief The cached values for built-in arrays\n   *\n   *  Maps from a tuple of spv::BuiltIn enum to the Value containing\n   *  that built-in array.  For example,\n   *  ``built_in_tbl_[spv::BuiltInLocalInvocationId]`` is the array\n   *  of invocation ids, equivalent to an array of ``threadIdx.x``,\n   *  ``threadIdx.y``, and ``threadIdx.z`` in CUDA.\n   *\n   *  These are declared in the global section of the shader.\n   */\n  std::unordered_map<spv::BuiltIn, Value> built_in_tbl_;\n\n  /*! \\brief The cached values for built-in values\n   *\n   *  Maps from a tuple of (spv::BuiltIn enum, index) to the value\n   *  stored at that index of the built-in array.  For example,\n   *  ``built_in_tbl_[{spv::BuiltInLocalInvocationId, 0}]`` is the\n   *  first index of the invocation id, equivalent to\n   *  ``threadIdx.x`` in CUDA.\n   *\n   *  These are declared in the first block of the function, in the\n   *  ``function_scope_vars_`` section.\n   */\n  std::map<std::tuple<spv::BuiltIn, uint32_t>, Value> built_in_values_tbl_;\n\n  /*! \\brief whether push constant is defined */\n  Value push_const_;\n  /*! \\brief map from type code to the type */\n  std::unordered_map<uint32_t, SType> pod_type_tbl_;\n  /*! \\brief map from value to array type */\n  std::map<std::tuple<uint32_t, uint32_t, bool>, SType> struct_array_type_tbl_;\n  /*! \\brief map from value to its pointer type */\n  std::map<std::pair<uint32_t, spv::StorageClass>, SType> pointer_type_tbl_;\n  /*! \\brief map from constant int to its value */\n  std::map<std::pair<uint32_t, uint64_t>, Value> const_tbl_;\n  /*! \\brief map from name of a ExtInstImport to its value */\n  std::map<std::string, Value> ext_inst_tbl_;\n\n  /*! \\brief Header segment\n   *\n   * 5 words long, described in \"First Words of Physical Layout\"\n   * section of SPIR-V documentation.\n   */\n  std::vector<uint32_t> header_;\n  /*! \\brief SPIR-V capabilities used by this module. */\n  std::set<spv::Capability> capabilities_used_;\n  /*! \\brief SPIR-V extensions used by this module. */\n  std::set<std::string> extensions_used_;\n  /*! \\brief entry point segment */\n  std::vector<uint32_t> extended_instruction_section_;\n  /*! \\brief entry point segment */\n  std::vector<uint32_t> entry_;\n  /*! \\brief Header segment */\n  std::vector<uint32_t> exec_mode_;\n  /*! \\brief Debug segment */\n  std::vector<uint32_t> debug_;\n  /*! \\brief Annotation segment */\n  std::vector<uint32_t> decorate_;\n  /*! \\brief Global segment: types, variables, types */\n  std::vector<uint32_t> global_;\n  /*! \\brief Function header segment\n   *\n   * Contains the start of function (spv::OpFunction), first label\n   * (spv::OpLabel), and all array allocations (spv::OpVariable).\n   */\n  std::vector<uint32_t> func_header_;\n  /*! \\brief Function-scope variable declarations\n   *\n   * Contains variable declarations that should be accessible\n   * throughout the entire kernel (e.g. threadIdx.x).  This must be\n   * separate from func_header_, because the function-level\n   * spv::OpVariable declarations must come first in the first block\n   * of a function.\n   */\n  std::vector<uint32_t> function_scope_vars_;\n  /*! \\brief Function segment */\n  std::vector<uint32_t> function_;\n};\n\n}  // namespace spirv\n}  // namespace codegen\n}  // namespace tvm\n\n#endif  // TVM_TARGET_SPIRV_IR_BUILDER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/spirv/spirv_support.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file spirv_support\n *\n * \\brief Utility for determining which spirv capabilities a TVM\n * target supports.\n */\n#ifndef TVM_TARGET_SPIRV_SPIRV_SUPPORT_H_\n#define TVM_TARGET_SPIRV_SPIRV_SUPPORT_H_\n\n#include <tvm/target/target.h>\n#include <vulkan/vulkan_core.h>\n\nnamespace tvm {\nnamespace codegen {\n\n/*! \\brief Represents which support a Vulkan driver has that are relevant to codegen */\nstruct SPIRVSupport {\n  /*! \\brief Determine spirv capabilities from a vulkan target.\n   */\n  explicit SPIRVSupport(Target target);\n\n  /*! \\brief The Vulkan API version supported by the device.\n   *\n   *  Vulkan struct: VkPhysicalDeviceProperties\n   *  Device property: apiVersion\n   *\n   *  If VK_KHR_driver_properties is present, will also check the\n   *  driver conformance version.  If the version advertised does not\n   *  pass the Vulkan conformance test, vulkan_api_version will be the\n   *  latest Vulkan version that does pass the conformance test\n   *  instead.\n   */\n  uint32_t vulkan_api_version{VK_MAKE_VERSION(1, 0, 0)};\n\n  /*!\n   * \\brief The supported subgroup operations\n   *\n   * Vulkan extension: VK_KHR_driver_properties\n   * Minimum vulkan version: 1.1\n   * Vulkan struct: VkPhysicalDeviceSubgroupProperties\n   * Device property: supportedOperations\n   *\n   * Requires vulkan 1.1 or higher to use.  If the\n   * VK_KHR_driver_properties extension is not present in order to\n   * query this value, or if the driver does not support vulkan 1.0,\n   * then this value will be set to 0.\n   *\n   */\n  uint32_t supported_subgroup_operations{0};\n\n  /*!\n   * \\brief The maximum size (bytes) of push constants\n   *\n   * Vulkan struct: VkPhysicalDeviceLimits\n   * Device property: maxPushConstantsSize\n   *\n   * The maxPushConstantsSize from VkPhysicalDeviceLimits.\n   * Default value is from Vulkan spec, \"Required Limits\" table.\n   * Implementations may have a larger limit.\n   */\n  uint32_t max_push_constants_size{128};\n\n  /*!\n   * \\brief The maximum size (bytes) of a uniform buffer.\n   *\n   * Vulkan struct: VkPhysicalDeviceLimits\n   * Device property: maxUniformBufferRange\n   *\n   * Default value is from Vulkan spec, \"Required Limits\" table.\n   * Implementations may have a larger limit.\n   */\n  uint32_t max_uniform_buffer_range{16384};\n\n  /*!\n   * \\brief The maximum size (bytes) of a storage buffer.\n   *\n   * Vulkan struct: VkPhysicalDeviceLimits\n   * Device property: maxStorageBufferRange\n   *\n   * Default value is from Vulkan spec, \"Required Limits\" table.\n   * Implementations may have a larger limit.\n   */\n  uint32_t max_storage_buffer_range{1 << 27};\n\n  /*!\n   * \\brief The maximum amount of shared memory usable by a shader\n   *\n   * Vulkan extension: N/A\n   * Vulkan struct: VkPhysicalDeviceLimits\n   * Device Property: maxComputeSharedMemorySize\n   * SPV Extension name: N/A\n   * SPV Capability: N/A\n   *\n   * The maximum amount of shared memory (Workgroup scope) that may be\n   * allocated by a shader.  Default value is from Vulkan spec,\n   * \"Required Limits\" table.  Implementations may have a larger\n   * limit.\n   */\n  uint32_t max_shared_memory_per_block{16384};\n\n  /*!\n   * \\brief The maximum number of storage buffers accessible by a single shader.\n   *\n   * Vulkan struct: VkPhysicalDeviceLimits\n   * Device property: maxPerStageDescriptorStorageBuffers\n   *\n   * Default value is from Vulkan spec, \"Required Limits\" table.\n   * Implementations may have a larger limit, frequently much larger.\n   * (e.g. GTX 1080 has max of 2^20)\n   */\n  uint32_t max_per_stage_descriptor_storage_buffers{4};\n\n  /*!\n   * \\brief Whether the driver supports StorageClassStorageBuffer\n   *\n   * Vulkan extension: VK_KHR_storage_buffer_storage_class\n   * Device property: N/A\n   * SPV Extension: SPV_KHR_storage_buffer_storage_class\n   * SPV Capability: N/A\n   *\n   * If support is present, access push constants and UBO as\n   * block-decorated StorageClassStorageBuffer.  Otherwise, access as\n   * buffer-block-decorated StorageClassUniform.  SPIRV 1.3 deprecated\n   * BufferBlock, so this should always be true drivers that support\n   * SPIRV 1.3.\n   *\n   */\n  bool supports_storage_buffer_storage_class{false};\n\n  /*!\n   * \\brief Whether the driver supports reading/writing to 16-bit values\n   *\n   * Vulkan extension: VK_KHR_8bit_storage\n   * Vulkan struct: VkPhysicalDevice8BitStorageFeaturesKHR\n   * Device property: storageBuffer8BitAccess\n   * SPV extension: SPV_KHR_8bit_storage\n   * SPV Capability: StorageBuffer8BitAccess\n   *\n   * If support is present, can read/write 8-bit values, but doesn't\n   * necessarily provide 8-bit operations.\n   *\n   * If support is present, will declare StorageBuffer8BitAccess as\n   * needed.  If support is not present, will throw error if a\n   * PrimFunc calls for this functionality.  Unlike\n   * StorageUniform16BitAccess, no fallback to\n   * \"StorageUniformBufferBlock8\" is needed, as VK_KHR_8bit_storage\n   * requires VK_KHR_storage_buffer_storage_class to also be present.\n   *\n   */\n  bool supports_storage_buffer_8bit_access{false};\n\n  /*!\n   * \\brief Whether the driver supports reading/writing to 16-bit values\n   *\n   * Vulkan extension: VK_KHR_16bit_storage\n   * Vulkan struct: VkPhysicalDevice16BitStorageFeaturesKHR\n   * Device property: storageBuffer16BitAccess\n   * SPV extension: SPV_KHR_16bit_storage\n   * SPV Capability: StorageBuffer16BitAccess, StorageUniformBufferBlock16\n   *\n   * If support is present, can read/write 16-bit values, but doesn't\n   * necessarily provide 16-bit operations.\n   *\n   * If support is present, will declare either\n   * StorageBuffer16BitAccess or StorageUniformBufferBlock16 as\n   * needed, selecting based on the value of\n   * supports_StorageBufferStorageClass.  If support is not present,\n   * will throw error if a PrimFunc calls for this functionality.\n   */\n  bool supports_storage_buffer_16bit_access{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving 16-bit floats\n   *\n   * Vulkan extension: VK_KHR_shader_float16_int8\n   * Vulkan struct: VkPhysicalDeviceShaderFloat16Int8FeaturesKHR\n   * Device Property: shaderFloat16\n   * SPV Extension name: N/A\n   * SPV Capability: Float16, Float16Buffer\n   *\n   * If support is present, can perform 16-bit float operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to create a 16-bit float.\n   */\n  bool supports_float16{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving 16-bit floats\n   *\n   * Vulkan extension: N/A\n   * Vulkan struct: VkPhysicalDeviceFeatures\n   * Device Property: shaderFloat64\n   * SPV Extension name: N/A\n   * SPV Capability: Float64\n   *\n   * If support is present, can perform 64-bit float operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to create a 64-bit float.\n   */\n  bool supports_float64{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving 8-bit ints\n   *\n   * Vulkan extension: VK_KHR_shader_float16_int8\n   * Vulkan struct: VkPhysicalDeviceShaderFloat16Int8FeaturesKHR\n   * Device Property: shaderInt8\n   * SPV Extension name: N/A\n   * SPV Capability: Int8\n   *\n   * If support is present, can perform 8-bit int operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to create a 8-bit int.\n   */\n  bool supports_int8{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving 8-bit ints\n   *\n   * Vulkan extension: N/A\n   * Vulkan struct: VkPhysicalDeviceFeatures\n   * Device Property: shaderInt16\n   * SPV Extension name: N/A\n   * SPV Capability: Int16\n   *\n   * If support is present, can perform 16-bit int operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to create a 16-bit int.\n   */\n  bool supports_int16{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving 64-bit ints\n   *\n   * Vulkan extension: N/A\n   * Vulkan struct: VkPhysicalDeviceFeatures\n   * Device Property: shaderInt64\n   * SPV Extension name: N/A\n   * SPV Capability: Int64\n   *\n   * If support is present, can perform 64-bit int operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to create a 64-bit int.\n   */\n  bool supports_int64{false};\n\n  /*!\n   * \\brief Whether the driver supports operations involving integer dot product.\n   *\n   * Vulkan extension: VK_KHR_shader_integer_dot_product\n   * SPV Extension name: SPV_KHR_integer_dot_product\n   * SPV Capability: spv::CapabilityDotProductKHR,\n   *                 spv::CapabilityDotProductInput4x8BitPackedKHR);\n   *\n   * If support is present, can perform integer dot product operations.  If\n   * support is not present, codegen will throw exception on\n   * attempting to perform integer dot product.\n   */\n  bool supports_integer_dot_product{false};\n};\n\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_SPIRV_SPIRV_SUPPORT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/target/stackvm/codegen_stackvm.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file codegen_stack_vm.h\n * \\brief Codegen into Simple Stack VM.\n */\n#ifndef TVM_TARGET_STACKVM_CODEGEN_STACKVM_H_\n#define TVM_TARGET_STACKVM_CODEGEN_STACKVM_H_\n\n#include <tvm/target/codegen.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"../../runtime/stackvm/stackvm.h\"\n\nnamespace tvm {\nnamespace codegen {\n\nusing namespace tir;\nusing runtime::StackVM;\n\n/*!\n * \\brief A base class to generate a stack VM.\n *  This module is used to generate host wrapper\n *  into device function when only device JIT is available.\n */\nclass CodeGenStackVM : public ExprFunctor<void(const PrimExpr&)>,\n                       public StmtFunctor<void(const Stmt&)> {\n public:\n  /*!\n   * \\brief Generate a stack VM representing\n   * \\param f The function to be compiled\n   * \\param device_funcs The extern device functions to be linked.\n   * \\note Only call compile once,\n   *  create a new codegen object each time.\n   */\n  StackVM Compile(const PrimFunc& f);\n  /*! \\brief Push stmt to generate new code */\n  void Push(const Stmt& n);\n  /*! \\brief Push expr to generate new code */\n  void Push(const PrimExpr& n) { VisitExpr(n); }\n  /*!\n   * \\brief Push the opcode to the code.\n   * \\param opcode The code to be pushed.\n   */\n  void PushOp(StackVM::OpCode opcode);\n  /*!\n   * \\brief Push the opcode and operand to the code.\n   * \\param opcode The opcode.\n   * \\param operand The operand to be pushed.\n   * \\return operand_index, indicating location of operand\n   */\n  int64_t PushOp(StackVM::OpCode opcode, int operand);\n  /*!\n   * \\brief Set the relative jump offset to be offset.\n   * \\param operand_index The indexed returned by PushOp.\n   * \\param operand The operand to be set.\n   */\n  void SetOperand(int64_t operand_index, int64_t operand);\n  /*! \\return The current program pointer */\n  int64_t GetPC() const { return static_cast<int64_t>(vm_.code.size()); }\n  /*!\n   * \\brief Get string id in vm\n   * \\param key The string to get id.\n   * \\return the id of the string.\n   */\n  int GetStrID(const std::string& key);\n  /*!\n   * \\brief Allocate a variable name for a newly defined var.\n   * \\param v The variable.\n   * \\return the heap index of the var.\n   */\n  int AllocVarID(const VarNode* v);\n  /*!\n   * \\brief Get a variable name.\n   * \\param v The variable.\n   * \\return the heap index of the var.\n   */\n  int GetVarID(const VarNode* v) const;\n  // Push binary operator\n  void PushBinary(StackVM::OpCode op_int64, const PrimExpr& a, const PrimExpr& b);\n  // push cast;\n  void PushCast(DataType dst, DataType src);\n  // overloadable functions\n  // expression\n  void VisitExpr_(const VarNode* op) final;\n  void VisitExpr_(const LoadNode* op) final;\n  void VisitExpr_(const BufferLoadNode* op) final;\n  void VisitExpr_(const LetNode* op) final;\n  void VisitExpr_(const CallNode* op) final;\n  void VisitExpr_(const AddNode* op) final;\n  void VisitExpr_(const SubNode* op) final;\n  void VisitExpr_(const MulNode* op) final;\n  void VisitExpr_(const DivNode* op) final;\n  void VisitExpr_(const ModNode* op) final;\n  void VisitExpr_(const MinNode* op) final;\n  void VisitExpr_(const MaxNode* op) final;\n  void VisitExpr_(const EQNode* op) final;\n  void VisitExpr_(const NENode* op) final;\n  void VisitExpr_(const LTNode* op) final;\n  void VisitExpr_(const LENode* op) final;\n  void VisitExpr_(const GTNode* op) final;\n  void VisitExpr_(const GENode* op) final;\n  void VisitExpr_(const AndNode* op) final;\n  void VisitExpr_(const OrNode* op) final;\n  void VisitExpr_(const CastNode* op) final;\n  void VisitExpr_(const NotNode* op) final;\n  void VisitExpr_(const SelectNode* op) final;\n  void VisitExpr_(const RampNode* op) final;\n  void VisitExpr_(const BroadcastNode* op) final;\n  void VisitExpr_(const IntImmNode* op) final;\n  void VisitExpr_(const FloatImmNode* op) final;\n  void VisitExpr_(const StringImmNode* op) final;\n  // statment\n  void VisitStmt_(const LetStmtNode* op) final;\n  void VisitStmt_(const StoreNode* op) final;\n  void VisitStmt_(const BufferStoreNode* op) final;\n  void VisitStmt_(const ForNode* op) final;\n  void VisitStmt_(const IfThenElseNode* op) final;\n  void VisitStmt_(const AllocateNode* op) final;\n  void VisitStmt_(const AttrStmtNode* op) final;\n  void VisitStmt_(const AssertStmtNode* op) final;\n  void VisitStmt_(const EvaluateNode* op) final;\n  void VisitStmt_(const SeqStmtNode* op) final;\n\n private:\n  bool debug_{false};\n  /*! \\brief The vm to be generated */\n  StackVM vm_;\n  /*! \\brief id of each variable */\n  std::unordered_map<const VarNode*, int> var_idmap_;\n  /*! \\brief id of each string */\n  std::unordered_map<std::string, int> str_idmap_;\n  /*! \\brief id of each global function */\n  std::unordered_map<std::string, int> extern_fun_idmap_;\n\n  Op backend_alloc_workspace_op_ = Op::Get(\"tir.TVMBackendAllocWorkspace\");\n  Op backend_free_workspace_op_ = Op::Get(\"tir.TVMBackendFreeWorkspace\");\n};\n\n}  // namespace codegen\n}  // namespace tvm\n#endif  // TVM_TARGET_STACKVM_CODEGEN_STACKVM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/autodiff/ad_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ad_utils.h\n * \\brief Helper utilities to implement auto-differentiation.\n */\n#ifndef TVM_TE_AUTODIFF_AD_UTILS_H_\n#define TVM_TE_AUTODIFF_AD_UTILS_H_\n\n#include <tvm/arith/int_solver.h>\n#include <tvm/te/operation.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace te {\n\n/*!\n * \\brief Clone iter vars and return both the new vars and the substitution from old to new.\n *\n * \\param vars The original iter vars.\n * \\return A pair containing the array of new iter vars and the map from old vars to new ones.\n */\nstd::pair<Array<IterVar>, Map<Var, PrimExpr>> CloneIterVars(const Array<IterVar>& vars);\n\n/*!\n * \\brief Clone reduction by cloning the axis variables.\n * \\param expr A reduction expr to clone. Non-reduction expressions are left intact.\n */\nPrimExpr CloneReduction(const PrimExpr& expr);\n\n/*!\n * \\brief Create a tensor from an expression. The expression may be a reduction, in which\n *  case its body will be correctly duplicated if it is a multi-valued reduction.\n *\n * \\param expr The expr which will be the tensor's body.\n * \\param axis The input variables with ranges.\n * \\param name The tensor's name.\n * \\param tag The tensor's tag.\n * \\param attrs The tensor's attrs.\n * \\param clone_axis Whether to clone the given axis and perform substitution.\n * \\return A tensor.\n */\nTensor TensorFromExpr(const PrimExpr& expr, const Array<IterVar>& axis,\n                      const std::string& name = \"tensor\", const std::string& tag = \"\",\n                      const Map<String, ObjectRef>& attrs = {}, bool clone_axis = true);\n\nTensor TransformTensorBody(\n    const Tensor& tensor,\n    const std::function<PrimExpr(const PrimExpr&, const Array<IterVar>&)>& func);\n\nTensor TransformTensorBody(const Tensor& tensor,\n                           const std::function<PrimExpr(const PrimExpr&)>& func);\n\n/*!\n * \\brief Inline tensors access recursively.\n *\n *  This function will inline tensors recursively until it reaches a tensor which is impossible to\n *  inline (a reduction if \\p inline_reductions is false, a non-compute tensor, a tensor which is\n *  not from \\p inlineable). It won't descend into non-inlinable tensors' bodies.\n *\n * \\param tensor The tensor whose body to transform.\n * \\param inlineable A list of tensors which are allowed to be inlined. If empty, try\n *  to inline all tensors.\n * \\param inline_reductions Whether to inline reductions (this may result in top-level reduction\n *  nodes).\n *\n * \\return An inlined tensor\n */\nTVM_DLL Tensor InlineTensorAccess(const Tensor& tensor,\n                                  const Array<Tensor>& inlineable = Array<Tensor>(),\n                                  bool inline_reductions = false);\n\n/*!\n * \\brief Inline tensors access at the tail.\n * \\param tensor The tensor whose body to transform.\n * \\return An inlined tensor\n */\nTVM_DLL Tensor InlineTailTensorAccess(const Tensor& tensor);\n\n/*!\n * \\brief Simplify an iteration domain.\n *\n *  An iteration domain is basically an array of variables and a condition. The function will do the\n *  following:\n *  - Replace div and mod operations with new variables (optional).\n *  - Extract (in)equalities from the condition.\n *  - Perform Fourier-Motzkin elimination.\n *  - Shear the domain of iteration (e.g. if `y <= x <= y + 2` then x will be replaced with `y + d`\n *    where `d` is a new variable such that `0 <= d <= 2`).\n *  - Remove redundant variables.\n *  - Infer new variable ranges (hopefully more precise).\n *\n * \\param iter_domains The original domain.\n * \\param eliminate_div_mod Whether to eliminate div and mod by introducing new variables.\n */\nTVM_DLL arith::IntConstraintsTransform SimplifyDomain(const arith::IntConstraints& iter_domains,\n                                                      bool eliminate_div_mod = true);\n\n/*!\n * \\brief Perform lifting of conditions of being possible to be non-zero together with\n *  applying some transformations like simplifying the reduction domain. Works only with\n *  this particular tensor's body, i.e. doesn't perform inlining.\n *\n * \\param tensor The original tensor;\n * \\param vranges Optional map from free variables to their value ranges.\n * \\return An optimized tensor.\n */\nTVM_DLL Tensor RemoveJacobianAndLiftNonzeroCond(const Tensor& tensor,\n                                                const Map<Var, Range>& vranges = Map<Var, Range>());\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_AUTODIFF_AD_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/operation/compute_op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Helper utilities to implement compute_op.\n * \\file compute_op.h\n */\n#ifndef TVM_TE_OPERATION_COMPUTE_OP_H_\n#define TVM_TE_OPERATION_COMPUTE_OP_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace te {\n// loop nest structure for general compute\n// This the loop nest structured used in compute.\n// Does not include the loop body.\nstruct ComputeLoopNest {\n  // The common number of loops between init and main\n  size_t num_common_loop;\n  // predicates for the initialize loop\n  std::vector<PrimExpr> init_predicates;\n  // Initialization nest involved.\n  std::vector<std::vector<Stmt>> init_nest;\n  // Value map for the init code\n  std::unordered_map<IterVar, PrimExpr> init_vmap;\n  // Predicates for the main update loop\n  std::vector<PrimExpr> main_predicates;\n  // The general loop nest\n  std::vector<std::vector<Stmt>> main_nest;\n  // Value map for the IterVar.\n  std::unordered_map<IterVar, PrimExpr> main_vmap;\n\n  /*!\n   * \\brief constructor to build ComputeOpNest\n   * \\param self The pointer to compute op.\n   * \\param stage The scxhedule stage.\n   * \\param dom_map The domain map.\n   * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1\n   * \\return The constructed loop nest\n   */\n  static ComputeLoopNest Create(const BaseComputeOpNode* self, const Stage& stage,\n                                const std::unordered_map<IterVar, Range>& dom_map,\n                                bool debug_keep_trivial_loop);\n};\n\n/*!\n * \\brief Build body of compute for cross thread reduction pattern.\n * \\param self The pointer to ComputeOpNode\n * \\param stage The schedule stage.\n * \\param dom_map The domain map.\n * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1\n * \\return The created statement.\n */\nStmt MakeCrossThreadReduction(const ComputeOpNode* self, const Stage& stage,\n                              const std::unordered_map<IterVar, Range>& dom_map,\n                              bool debug_keep_trivial_loop);\n\n/*!\n * \\brief Build body of compute for tensorization.\n * \\param self The pointer to ComputeOpNode\n * \\param stage The schedule stage.\n * \\param dom_map The domain map.\n * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1\n * \\return The created statement.\n */\nStmt MakeTensorize(const ComputeOpNode* self, const Stage& stage,\n                   const std::unordered_map<IterVar, Range>& dom_map, bool debug_keep_trivial_loop);\n\n/*!\n * \\brief Transform the update part when there is no init func in tensorizing\n * \\param stage The stage for tensorizing.\n * \\param dom_map The range of each iter var.\n * \\param n The loop nest structured used in compute.\n * \\param body The body func in tensorize intrin\n * \\param update The update func in tensorize intrin\n * \\return Transformed result.\n */\nStmt TransformUpdate(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                     const ComputeLoopNest& n, Stmt body, Stmt update);\n}  // namespace te\n}  // namespace tvm\n\n#endif  // TVM_TE_OPERATION_COMPUTE_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/operation/create_primfunc.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TVM_TE_OPERATION_CREATE_PRIMFUNC_H_\n#define TVM_TE_OPERATION_CREATE_PRIMFUNC_H_\n\n#include <tvm/runtime/container/array.h>\n#include <tvm/te/tensor.h>\n#include <tvm/tir/function.h>\n\nnamespace tvm {\nnamespace tir {\n\n/*! \\brief Use Tensor Expression to create a schedulable TensorIR func. */\nPrimFunc CreatePrimFunc(const Array<te::Tensor>& arg_list);\n\n/*! \\brief The same as above but create a PrimFunc with AllocateConstNode. If the size of the\n * constants array is N, the last N tensors in arg_list will be treated as constant tensors.\n * Constant tensors will not be part of the parameters of the created PrimFunc, instead constants\n * will be embedded in the body as AllocateConstNode.\n */\nPrimFunc CreatePrimFuncWithConstants(const Array<te::Tensor>& arg_list,\n                                     const Array<runtime::NDArray>& constants);\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TE_OPERATION_CREATE_PRIMFUNC_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/operation/hybrid_op.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\brief Helper utilities to implement hybrid_op.\n * \\file hybrid_op.h\n */\n#ifndef TVM_TE_OPERATION_HYBRID_OP_H_\n#define TVM_TE_OPERATION_HYBRID_OP_H_\n\n#include <tvm/te/schedule.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../tir/transforms/arg_binder.h\"\n#include \"../../tir/transforms/ir_utils.h\"\n#include \"../schedule/message_passing.h\"\n\nnamespace tvm {\nnamespace te {\n\n/*!\n * \\brief Find all the iteration variables in the given statement body.\n * \\param stmt The body to be inspected.\n */\nstd::vector<IterVar> GatherLoopVars(Stmt stmt);\n\n/*!\n * \\brief Replace the tensor reference (especially in Provide's) in stmt by the replace map.\n * \\param stmt The statement to be processed.\n * \\param replace The replacement rule.\n */\nStmt ReplaceProvideTensor(Stmt stmt, const std::unordered_map<Tensor, Tensor>& replace);\n\n/*!\n * \\brief Apply the schedule manipulation on the function body.\n * \\param stmt The statement to be processed.\n * \\param dom_map The extents of the iterative variables may be used.\n * \\param stage The schedule information to be applied.\n */\nStmt ApplySchedule(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                   Stmt stmt);\n\n/*!\n * \\brief Apply loop splits and fuses in the schedule on the function body.\n * \\param stage The schedule information to be applied.\n * \\param dom_map The extents of the iterative variables may be used.\n * \\param stmt The statement to be processed.\n */\nStmt ApplyLoopShapes(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                     Stmt stmt);\n\n/*!\n * \\brief Apply loop annotation in the schedule on the function body.\n * \\param stage The schedule information to be applied.\n * \\param rebased The map specifies the rebase, a.k.a rename, relationship of these variables.\n * \\param stmt The statement to be processed.\n */\nStmt ApplyLoopAnnotations(const Stage& stage, const std::unordered_map<IterVar, IterVar>& rebased,\n                          Stmt stmt);\n\n/*!\n * \\brief Apply loop order in the schedule on the function body.\n * \\param stage The schedule information to be applied.\n * \\param dom_map The extents of the iterative variables may be used.\n * \\param rebased The map specifies the rebase, a.k.a rename, relationship of these variables.\n * \\param stmt The statement to be processed.\n */\nStmt ApplyLoopOrder(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                    const std::unordered_map<IterVar, IterVar>& rebased, Stmt stmt);\n\n}  // namespace te\n}  // namespace tvm\n\n#endif  // TVM_TE_OPERATION_HYBRID_OP_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/operation/op_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file op_utils.h\n * \\brief Common utility used in operator construction.\n */\n#ifndef TVM_TE_OPERATION_OP_UTILS_H_\n#define TVM_TE_OPERATION_OP_UTILS_H_\n\n#include <tvm/te/schedule.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"../../tir/transforms/arg_binder.h\"\n#include \"../../tir/transforms/ir_utils.h\"\n#include \"../schedule/message_passing.h\"\n\nnamespace tvm {\nnamespace te {\n\nusing tir::MergeNest;\n\n/*!\n * \\brief Build loop nest for stage.\n *\n * \\param stage The stage to create a loop nest.\n * \\param dom_map The range of each iter var.\n * \\param begin_iter_pos The beginning position of leaf_iter_vars to generate loop.\n * \\param new_loop_var Whether create new loop variable.\n * \\param skip_iter Whether skip certain iteration.\n * \\param p_value_map The result value of each IterVar.\n * \\param debug_keep_trivial_loop Whether keep trivial loops with extent of 1\n */\nstd::vector<std::vector<Stmt>> MakeLoopNest(const Stage& stage,\n                                            const std::unordered_map<IterVar, Range>& dom_map,\n                                            size_t begin_iter_pos, bool new_loop_var,\n                                            const std::unordered_set<IterVar>& skip_iter,\n                                            std::unordered_map<IterVar, PrimExpr>* p_value_map,\n                                            bool debug_keep_trivial_loop);\n\n/*!\n * \\brief Create a nest of if checking the predicates.\n *\n * \\param predicates The predicates to be checked.\n * \\return List of If nest that checks the predicates.\n */\nstd::vector<Stmt> MakeIfNest(const std::vector<PrimExpr>& predicates);\n\n/*!\n * \\brief Replace the tensor reference (especially in Call's) in stmt by the replace map.\n * \\param stmt The statement to be processed.\n * \\param replace The replacement rule.\n */\nStmt ReplaceTensor(Stmt stmt, const std::unordered_map<Tensor, Tensor>& replace);\n/*!\n * \\brief Replace the tensor reference (especially in Call's) in primExpr by the replace map.\n * \\param expr The expression to be processed.\n * \\param replace The replacement rule.\n */\nPrimExpr ReplaceTensor(PrimExpr expr, const std::unordered_map<Tensor, Tensor>& replace);\n\n/*!\n * \\brief Substitute the variables of stmt by value map.\n * \\param stmt the statment\n * \\param value_map The value map.\n * \\return Substituted result.\n */\nStmt Substitute(Stmt stmt, const std::unordered_map<IterVar, PrimExpr>& value_map);\n\n/*!\n * \\brief Substitute the variables of primExpr by value map.\n * \\param expr the expression to be processed.\n * \\param value_map The value map.\n * \\return Substituted result.\n */\nPrimExpr Substitute(PrimExpr expr, const std::unordered_map<IterVar, PrimExpr>& value_map);\n\n/*!\n * \\brief Converts Halide ForKind to its corresponding IterVarType\n * \\param kind The ForKind to be converted\n */\nIterVarType ForKindToIterVarType(tir::ForKind kind);\n\n/*!\n * \\brief Converts IterVarType to its corresponding Halide ForKind\n * \\param iter_type The IterVarType to be converted\n */\ntir::ForKind IterVarTypeToForKind(IterVarType iter_type);\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_OPERATION_OP_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/schedule/graph.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file graph.h\n * \\brief Utilities to get information about schedule graph.\n */\n#ifndef TVM_TE_SCHEDULE_GRAPH_H_\n#define TVM_TE_SCHEDULE_GRAPH_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace te {\n\n/*!\n * \\brief data structure of Operation->Tensors it reads\n */\nusing ReadGraph = Map<Operation, Array<Tensor>>;\n\n/*!\n * \\brief AttachPath maps op-> a list of IterVar\n */\nusing AttachPath = Map<Operation, Array<IterVar>>;\n\n/*!\n * \\brief The map between tensor and operation it feeds to.\n */\nusing FeedGraph = std::unordered_map<Tensor, std::vector<Operation>>;\n\n/*!\n * \\brief Get read graph of each operation to all the\n *  Tensors that it directly depends on.\n *\n *  The result map contains Operations needed to finish root Operation.\n * \\param roots The root operation.\n * \\return The result map.\n */\nReadGraph CreateReadGraph(const Array<Operation>& roots);\n\n/*!\n * \\brief Get minimum subgraph between outputs and inputs.\n *  The operations contains node which input-reachable from any inputs\n *  output reachable to any outputs.\n *\n *  The inputs won't be included in the subgraph, the outputs will be included.\n *\n * \\param outputs The outputs of the subgraph\n * \\param inputs The inputs to the subgraph.\n * \\param include_inputs Whether to include inputs\n *\n * \\return The subgraph.\n */\nArray<Operation> GetSubGraph(const Array<Tensor>& outputs, const Array<Tensor>& inputs,\n                             bool include_inputs);\n\n/*!\n * \\brief Get a post DFS ordered of operations in the graph.\n * \\param roots The root of the graph.\n * \\param g The read graph.\n * \\return vector order of Operations in PostDFS order.\n *\n * \\note PostDFSOrder is a special case of Topoligical order,\n *   and can be used when topoligical order is needed.\n */\nArray<Operation> PostDFSOrder(const Array<Operation>& roots, const ReadGraph& g);\n\n/*!\n * \\brief Create feedgraph for given Schedule\n * \\param  g The read graph.\n * \\return The created feedgraph.\n */\nFeedGraph CreateFeedGraph(const ReadGraph& g);\n\n/*!\n * \\brief Create AttachPath that  maps op-> a list of IterVar\n *  That represents the loop nest op sits in from inner most to outermost\n *  Also inserts attach_stage for scan updates when needed.\n *\n * \\param sch The schedule.\n * \\return The attach path.\n */\nAttachPath CreateAttachPath(Schedule sch);\n\n/*!\n * \\brief Get all operations inside the recursion of scan.\n * \\param scan_op The scan node ops.\n * \\return The body operations, in read dependency order.\n */\nArray<Operation> ScanGetBody(const Operation& scan_op);\n\n/*!\n * \\brief Analyze each spatial dimension of scan's result.\n *  Give check on whether each dimension is fix point,\n *  An axis is a fixed point if it only refers back to itself in recursion\n *  and it is not used in axis of other recursion field.\n *\n *  next_state[t, ..., axis, ...] = f(prev_state[t-1, ...,axis,...]\n *\n * \\param scan The scan node.\n * \\return Map of spatial_axis -> IntImm\n */\nMap<IterVar, PrimExpr> ScanFixPointAnalysis(const Operation& scan);\n\n}  // namespace te\n}  // namespace tvm\n\n#endif  // TVM_TE_SCHEDULE_GRAPH_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/schedule/message_passing.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file message_passing.h\n * \\brief Common utilities to do message passing\n *  on the schedule hyper graph.\n */\n#ifndef TVM_TE_SCHEDULE_MESSAGE_PASSING_H_\n#define TVM_TE_SCHEDULE_MESSAGE_PASSING_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/te/operation.h>\n#include <tvm/te/schedule.h>\n#include <tvm/tir/expr.h>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace tvm {\nnamespace te {\n/*!\n * \\brief Downward inference of domain of each IterVar.\n *  Caller set the range of the root, then the function\n *  propagates it towards the leaves.\n *\n * \\param stage The stage to operate on.\n * \\param p_state The state of the message passing.\n * \\param analyzer Analyzer context, storing information about bounds in p_state.\n * \\param allow_missing Whether allow missing value.\n */\nvoid PassDownDomain(const Stage& stage, std::unordered_map<IterVar, Range>* p_state,\n                    arith::Analyzer* analyzer, bool allow_missing = false);\n\n/*!\n * \\param Upward inference of index of each IterVar.\n *  given index assignement of the leaves,\n *\n * \\param stage The stage to operate on.\n * \\param dom_map The domain map of each iteration variable's domain.\n * \\param p_state The index state of each IterVar.\n * \\param allow_missing Whether allow missing value.\n */\nvoid PassUpIndex(const Stage& stage, const Map<IterVar, Range>& dom_map,\n                 std::unordered_map<IterVar, PrimExpr>* p_state, bool allow_missing = false);\n\n/*!\n * \\param Downward inference of index of each IterVar.\n *  given index assignement of roots.\n *\n * \\param stage The stage to operate on.\n * \\param dom_map The domain map of each iteration variable's domain.\n * \\param p_state The index state of each IterVar.\n * \\param allow_missing Whether allow missing value.\n */\nvoid PassDownIndex(const Stage& stage, const Map<IterVar, Range>& dom_map,\n                   std::unordered_map<IterVar, PrimExpr>* p_state, bool allow_missing = false);\n\n/*!\n * \\param Upward inference of domain set of each IterVar.\n *  given domain assignment of the leaves,\n *\n * \\param stage The stage to operate on.\n * \\param dom_map The domain map of each iteration variable's maximum domain.\n * \\param p_state The index state of each IterVar.\n */\nvoid PassUpDomain(const Stage& stage, const std::unordered_map<IterVar, Range>& dom_map,\n                  std::unordered_map<IterVar, IntSet>* p_state);\n\n/*!\n * \\brief Upward message passing of bitmask with or relation.\n * \\param stage The stage to operate on.\n * \\param p_state The index state of each IterVar.\n * \\param allow_missing Whether allow missing value.\n */\nvoid PassUpBitMaskOr(const Stage& stage, std::unordered_map<IterVar, int>* p_state,\n                     bool allow_missing = false);\n\n/*!\n * \\brief Downward message passing of bitmask with or relation.\n * \\param stage The stage to operate on.\n * \\param p_state The index state of each IterVar.\n * \\param allow_missing Whether allow missing value.\n */\nvoid PassDownBitMaskOr(const Stage& stage, std::unordered_map<IterVar, int>* p_state,\n                       bool allow_missing = false);\n\n/*!\n * \\brief Create boundary check predicates given remapped value of root\n * \\param stage The stage we operate on\n * \\param dom_map The domain map of each value.\n * \\param value_map The value map of the root iter var.\n * \\param skip_ivar_domain Whether we skip check for IterVar's original domain.\n * \\param skip_iter The set of variables to skip bound condition.\n * \\return List of predicates that we need to check.\n */\nstd::vector<PrimExpr> MakeBoundCheck(const Stage& stage, const Map<IterVar, Range>& dom_map,\n                                     const std::unordered_map<IterVar, PrimExpr>& value_map,\n                                     bool skip_ivar_domain,\n                                     const std::unordered_set<IterVar>& skip_iter);\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_SCHEDULE_MESSAGE_PASSING_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/te/schedule/operation_inline.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file operation_inline.h\n */\n#ifndef TVM_TE_SCHEDULE_OPERATION_INLINE_H_\n#define TVM_TE_SCHEDULE_OPERATION_INLINE_H_\n\n#include <tvm/te/operation.h>\n#include <tvm/te/tensor.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt.h>\n\nnamespace tvm {\nnamespace te {\n\n/*!\n * \\brief inline all calls of f in stmt.\n *\n * \\param stmt The statement to apply inline optimization.\n * \\param op The op to be inlined.\n * \\param args The arguments variable of the function.\n * \\param body The definition body of the function.\n * \\return The result stmt\n *\n * \\note All the passes in this file uses SSA form and outputs SSA form.\n */\nStmt Inline(Stmt stmt, Operation op, Array<Var> args, PrimExpr body);\n\n}  // namespace te\n}  // namespace tvm\n#endif  // TVM_TE_SCHEDULE_OPERATION_INLINE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/analysis/check_contains.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file check_contains.h\n * \\brief Interface of the analysis that tells if an expression contains\n           a node that satisfies a given predicate.\n */\n\n#ifndef TVM_TIR_ANALYSIS_CHECK_CONTAINS_H_\n#define TVM_TIR_ANALYSIS_CHECK_CONTAINS_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt_functor.h>  // For the class StmtExprVisitor\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Visitor which tells if a given expression or statement contains a subexpression\n          that satisfies a given predicate\n */\nclass CheckContains : public StmtExprVisitor {\n public:\n  // Toplevel (static) functions\n  static bool ExprContains(const PrimExpr& expr, std::function<bool(const PrimExpr&)> predicate);\n  static bool StmtContains(const Stmt& stmt, std::function<bool(const PrimExpr&)> predicate);\n\n protected:\n  // Constructor\n  explicit CheckContains(std::function<bool(const PrimExpr&)> predicate);\n\n  void VisitExpr(const PrimExpr& expr) override;\n  void VisitStmt(const Stmt& stmt) override;\n\n private:\n  std::function<bool(const PrimExpr&)> predicate_;\n  bool contains_it_ = false;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_ANALYSIS_CHECK_CONTAINS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/analysis/device_constraint_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/analysis/device_constraint_utils.cc\n * \\brief Utilities for extracting and applying device-related constraints to \\p PrimFunc\n * parameters.\n *\n * These utilities are used by the \\p PlanDevices pass to extract memory (aka 'storage') scope\n * information from \\p PrimFuncs and convert them back into \\p VirtualDevice form w.r.t. the\n * original Relay type of the \\p PrimFunc (ie before flattening of tuple arguments/results and\n * conversion to destination-passing style aka DPS).\n *\n * A utility is also supplied to go the other way: impose memory scopes on \\p PrimFunc parameters.\n * However that's still in EXPERIMENTAL form.\n *\n * We may extend these utilities to also gather/apply layout information should we add that to\n * \\p VirtualDevice.\n */\n\n#ifndef TVM_TIR_ANALYSIS_DEVICE_CONSTRAINT_UTILS_H_\n#define TVM_TIR_ANALYSIS_DEVICE_CONSTRAINT_UTILS_H_\n\n#include <tvm/target/virtual_device.h>\n#include <tvm/tir/function.h>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * A Relay Function with type:\n * \\code\n *   fn((Tensor[...], Tensor[...]), Tensor[...]) -> (Tensor[...], Tensor[...])\n *       ^            ^             ^                ^            ^\n *       a            b             c                d            e\n * \\endcode\n * will be represented by a TIR PrimFunc in flattened and DPS form with at least 5 argument a..e.\n * \\code\n *   primfn(a: handle, b: handle, c: handle, d: handle, e: handle) {\n *     buffers = { ... }\n *     buffer_map = { ... }\n *     ...\n *   }\n * \\endcode\n *\n * Each such PrimFunc argument will me mapped to a \\p Buffer who's underlying \\p data \\p Var\n * has a \\p PointerType.\n *\n * The PrimFunc may have additional non-pointer arguments, eg for:\n *  - scalar inputs and tensor dimensions\n *  - device contexts\n * Those should be ignored here since they have no counterpart in the Relay Function.\n *\n * We'll need helpers to map on-the-fly between the Relay and TIR view of functions.\n */\n\n/*!\n * \\brief Returns the \\p VirtualDevices capturing the memory (aka storage) scope constraints for all\n * the arguments and result of \\p prim_func. However the result will be w.r.t. the \\p prim_func's\n * representation as a Relay \\p Function of \\p relay_func_type_ before lowering and conversion to\n * DPS.\n */\nArray<VirtualDevice> GetPrimFuncArgAndResultConstraints(const tir::PrimFunc& prim_func,\n                                                        const FuncType& relay_func_type);\n\n/*\n * \\brief Returns \\p prim_func written to capture the memory (aka storage) scope constraints\n * for each of the \\p prim_func's parameters given by \\p arg_and_result_virtual_devices. However,\n * \\p arg_and_result_virtual_devices should be w.r.t. the \\p prim_func's representation as a Relay\n * \\p Function of \\p relay_func_type before lowering and conversion to DPS.\n *\n * CAUTION: This is experimental. The resulting \\p PrimFunc may not have fully accounted for all\n * new memory scopes.\n */\nPrimFunc ApplyPrimFuncArgAndResultConstraints(\n    const PrimFunc& prim_func, const FuncType& relay_func_type,\n    const Array<VirtualDevice>& arg_and_result_virtual_devices);\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_ANALYSIS_DEVICE_CONSTRAINT_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/ir/buffer_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/*!\n * \\file tir/ir/buffer_common.h\n * \\brief Common utils for buffer access\n */\n#ifndef TVM_TIR_IR_BUFFER_COMMON_H_\n#define TVM_TIR_IR_BUFFER_COMMON_H_\n\n#include <tvm/ir/type.h>\n#include <tvm/runtime/data_type.h>\n\n#include <optional>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Returns the type of object pointed to.\n *\n * \\param type The type to be checked.\n *\n * \\return An std::optional<DataType> object. If the type is a pointer\n * to a primitive type, the object has a value which is the pointed-to\n * type. Otherwise the object is nullopt.\n */\ninline std::optional<runtime::DataType> GetPointerType(const Type& type) {\n  if (type.defined()) {\n    if (auto* ptr_type = type.as<PointerTypeNode>()) {\n      if (auto* prim_type = ptr_type->element_type.as<PrimTypeNode>()) {\n        return prim_type->dtype;\n      }\n    }\n  }\n\n  return std::nullopt;\n}\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_IR_BUFFER_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/ir/functor_common.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#include <tvm/runtime/container/array.h>\n\n/*!\n * \\file tir/ir/functor_common.h\n * \\brief Common utils for implementing functors\n */\n#ifndef TVM_TIR_IR_FUNCTOR_COMMON_H_\n#define TVM_TIR_IR_FUNCTOR_COMMON_H_\n\nnamespace tvm {\nnamespace tir {\n\n// Implementation of Visitors\ntemplate <typename T, typename F>\ninline void VisitArray(const Array<T>& arr, F fvisit) {\n  for (size_t i = 0; i < arr.size(); i++) {\n    fvisit(arr[i]);\n  }\n}\n\ntemplate <typename T, typename F>\ninline Array<T> MutateArray(Array<T> arr, F fmutate) {\n  return arr.Map(fmutate);\n}\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_IR_FUNCTOR_COMMON_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/ir/script/script_complete.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file tir/ir/script/script_complete.h\n * \\brief Used by TVM Script parser to expand incomplete TIR input\n */\n#ifndef TVM_TIR_IR_SCRIPT_SCRIPT_COMPLETE_H_\n#define TVM_TIR_IR_SCRIPT_SCRIPT_COMPLETE_H_\n#include <tvm/runtime/registry.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>\n\nnamespace tvm {\nnamespace tir {\n\nPrimFunc ScriptComplete(PrimFunc func, const Array<Buffer>& root_allocates);\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_IR_SCRIPT_SCRIPT_COMPLETE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/analysis.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_ANALYSIS_H_\n#define TVM_TIR_SCHEDULE_ANALYSIS_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/ir/op.h>\n#include <tvm/tir/index_map.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/state.h>\n\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"../../runtime/thread_storage_scope.h\"\n\nnamespace tvm {\nnamespace tir {\n\n/******** Verification ********/\n/*!\n * \\brief Verifies the sref tree state is consistent with the IR\n * \\param self The schedule state containing the sref to be verified\n * \\throw An exception will be thrown if the sref tree is not valid\n */\nvoid VerifySRefTree(const ScheduleState& self);\n/*!\n * \\brief Verifies the cached flags in the schedule state, including:\n * - affine_binding\n * - region_cover\n * - stage_pipeline\n * \\param self The schedule state to be verified\n * \\throw An exception will be thrown if some srefs are not valid\n */\nvoid VerifyCachedFlags(const ScheduleState& self);\n\n/******** IR Module ********/\n/*!\n * \\brief Get PrimFunc and GlobalVar that the root block belongs to\n * \\param mod The IRModule\n * \\param root_block The root block of the PrimFunc\n * \\param result_g_var The result GlobalVar\n * \\return The result PrimFunc where the root block belongs to\n * \\note This function returns the pointer instead of ObjectRef to avoid later copy-on-write\n */\nconst PrimFuncNode* GetRootPrimFunc(const IRModule& mod, const StmtNode* root_block,\n                                    GlobalVar* result_g_var);\n\n/*!\n * \\brief Get the root node of the sref tree, which is the root block of the PrimFunc.\n * \\param sref The given sref.\n * \\return The root node of the sref tree which contains the given node.\n */\nStmtSRef GetSRefTreeRoot(const StmtSRef& sref);\n\n/******** Scope ********/\n/*!\n * \\brief Checks if scope the specified sref is in is a stage-pipeline and return it\n * \\param self The schedule state\n * \\param sref The sref whose scope is to be checked\n * \\param require_stage_pipeline A boolean indicating whether to check stage pipeline\n * \\throw ScheduleError if\n * 1) the sref has been the root of the AST (so it has no scope root), or\n * 2) require_stage_pipeline = true, but its scope root is not a stage pipeline\n * \\return The block sref to the scope root\n */\nStmtSRef GetScopeRoot(const ScheduleState& self, const StmtSRef& sref, bool require_stage_pipeline);\n\n/*!\n * \\brief The information of a block scope, including the leaf blocks,\n * as well as the loop types (spatial, reduction) for each loop in the scope.\n */\nstruct ScopeBlockLoopInfo {\n  /*! \\brief A list of the leaf blocks, from left to right */\n  std::vector<BlockRealize> realizes;\n  /*! \\brief The loop vars bound to spatial block iters */\n  std::unordered_set<const VarNode*> spatial_vars;\n  /*! \\brief The loop vars bound to non-spatial block iters */\n  std::unordered_set<const VarNode*> non_spatial_vars;\n};\n\n/*!\n * \\brief Inspect the scope of the given sref\n * \\param scope_block The root block of the scope\n * \\return The information of the scope\n */\nScopeBlockLoopInfo GetScopeBlockLoopInfo(const Block& scope_block);\n\n/*!\n * \\brief Checks whether the block is a complete block under the scope\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\param scope_root_sref The sref to the root block of the scope that `block_sref` is in\n * \\return A boolean indicating if the block is a complete block\n * \\note Definition of a complete block:\n * 1) All block vars are data parallel\n * 2) Dominant: the block is the only writer of its output,\n * dominating the reader of its output buffers\n * 3) No overlap between the buffers the block reads and writes\n */\nbool IsCompleteBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                     const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check if the block is a complete block under the scope\n * \\param self The schedule state\n * \\param block_sref The sref to the block whose completeness is to be checked\n * \\param scope_root_sref The scope root of the block\n * \\throw ScheduleError If the block is not a complete block\n */\nvoid CheckCompleteBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                        const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check whether the block is a reduction block under the scope\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\param scope_root_sref The sref to the root block of the scope that `block_sref` is in\n * \\return A boolean indicating if the block is a reduction block\n * \\note Definition of a reduction block:\n * 1) The block has the `init` statement\n * 2) All the block bindings are quasi-affine expressions\n * 3) All block vars are either data parallel block vars or reduction block vars\n * 4) Dominant: the block is the only writer of its output, dominating the reader of its output\n * buffers\n * 5) The reduction block vars are not used to index the output buffers\n */\nbool IsReductionBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                      const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check if the block is a reduction block under the scope\n * \\param self The schedule state\n * \\param block_sref The sref of the block to be checked\n * \\param scope_root_sref The scope root of the block\n * \\throw ScheduleError If the block is not a reduction block\n */\nvoid CheckReductionBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                         const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check if the block is a complete block or a reduction block under the scope\n * \\param self The schedule state\n * \\param block_sref The sref of the block to be checked\n * \\param scope_root_sref The scope root of the block\n * \\throw ScheduleError If the block is neither a complete block nor a reduction block\n */\nvoid CheckCompleteOrReductionBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                                   const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check the subtree compact dataflow property. The scope root may have one or more subtrees\n *        rooted at its direct children, and this property requires all the blocks of the subtree\n *        that the specified sref is in to be local complete block or local reduction block.\n * \\param self The schedule state\n * \\param subtree_root The sref of the subtree root to be checked\n */\nvoid CheckSubtreeCompactDataflow(const ScheduleState& self, const StmtSRef& subtree_root);\n/*!\n * \\brief Check if the block is an output block, i.e. the block writes to at least a buffer that is\n * not allocated under the current scope\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\param scope_root_sref The scope root of the block\n * \\return A boolean flag indicating if the block is an output block\n */\nbool IsOutputBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                   const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Check if the block is not an output block, i.e. all the buffers the block writes to\n * are allocated under the current scope\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\param scope_root_sref The scope root of the block\n * \\throw ScheduleError if the block is an output block\n */\nvoid CheckNotOutputBlock(const ScheduleState& self, const StmtSRef& block_sref,\n                         const StmtSRef& scope_root_sref);\n\n/*!\n * \\brief Extracts the types of the block vars\n * \\param block_sref The block to be checked\n * \\return A vector of types of the block vars\n */\nstd::vector<IterVarType> GetBlockVarTypes(const StmtSRef& block_sref);\n\n/*!\n * \\brief Checks if a block could be considered as a \"write cache\"\n * \\param block_sref The block to be checked\n * \\return A boolean flag indicating if the block is a write cache\n */\nbool IsWriteCache(const StmtSRef& block_sref);\n\n/******** Binding ********/\n/*!\n * \\brief Verifies if the block binding in a specific BlockRealize is an affine binding.\n * The binding can be represented as an injective affine map from the loop iterators.\n * \\param realize The BlockRealize to be analyzed\n * \\param loop_var_ranges The ranges of the loop variables\n * \\param analyzer The analyzer\n * \\return A boolean flag indicating if the binding is affine\n */\nbool IsAffineBinding(const BlockRealize& realize, const Map<Var, Range>& loop_var_ranges,\n                     arith::Analyzer* analyzer);\n\n/*!\n * \\brief Check whether a block has an affine binding using the cached flag, and throw an exception\n * if the block does not have an affine binding.\n * \\param self The schedule state\n * \\param block The block to be checked\n * \\throw ScheduleError If the input block does not have an affine binding\n */\nvoid CheckAffineBinding(const ScheduleState& self, Block block);\n\n/*!\n * \\brief Check whether a block has an affine binding under the high exclusive sref node,\n * throw an exception if the block does not have an affine binding.\n * \\param self The schedule state\n * \\param block The block to be checked\n * \\param high_exclusive The highest sref node\n * \\throw ScheduleError If the input block does not have an affine binding\n */\nvoid CheckPartialAffineBinding(const ScheduleState& self, Block block,\n                               const Optional<StmtSRef>& high_exclusive);\n\n/*!\n * \\brief Extracts the ranges of loop variables in a path of the sref tree\n * \\param low_inclusive The lowest node in the path\n * \\param high_exclusive The highest node in the path, defaults to the scope root if not specified\n * \\param extra_relax_scope If the scope is not global, the method will look beyond the limit and\n * retrieve extra domains. For example,\n * - if the storage scope is warp, it will look upwards for threadIdx.x\n * - if the storage scope is shared, it will look for threadIdx.x/y/z\n * \\return The loop domain\n */\nMap<Var, Range> LoopDomainOfSRefTreePath(const StmtSRef& low_inclusive,\n                                         const Optional<StmtSRef>& high_exclusive = NullOpt,\n                                         const runtime::StorageScope& extra_relax_scope =  //\n                                         runtime::StorageScope{runtime::StorageRank::kGlobal, \"\"});\n\n/*!\n * \\brief Returns the block var binding\n * \\param realize The BlockRealize to be analyzed\n * \\return The block var binding\n */\nMap<Var, PrimExpr> GetBindings(const BlockRealize& realize);\n\n/*!\n * \\brief Get the vars involved in the bindings of data parallel block vars and reduction block\n * vars, respectively\n * \\param block_realize The BlockRealize to be analyzed\n * \\param data_par_vars The vars that appear in the binding of any data parallel block iter\n * \\param reduce_vars The vars that appear in the binding of any reduction block iter\n * \\return A boolean indicating whether the block has block iters that is neither a data parallel\n * block iter nor a reduction block iter\n */\nbool GetVarsTouchedByBlockIters(const BlockRealize& block_realize,\n                                std::unordered_set<const VarNode*>* data_par_vars,\n                                std::unordered_set<const VarNode*>* reduce_vars);\n\n/******** Loop properties ********/\n/*!\n * \\brief Check the loop starts with zero.\n * \\param self The schedule state\n * \\param loop_sref The StmtSRef that points to the loop to be checked\n * \\param analyzer The arithmetic analyzer\n * \\throw ScheduleError If the loop doesn't starts with zero.\n */\nvoid CheckLoopStartsWithZero(const ScheduleState& self, const StmtSRef& loop_sref,\n                             arith::Analyzer* analyzer);\n\n/*!\n * \\brief Check whether a block has a trivial binding, i.e. each block var is bound to a outer loop,\n * from outer to inner.\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\throw ScheduleError If the block does not have trivial bindings\n */\nvoid CheckBlockHasTrivialBinding(const ScheduleState& self, const StmtSRef& block_sref);\n\n/******** Block-loop relation ********/\n\n/*!\n * \\brief Gets StmtSRefs of leaf blocks of a scope where a specific block/loop is in\n * \\param self The schedule state\n * \\param parent_sref The StmtSRef that points to the parent block/loop\n * \\return A list of StmtSRefs of leaf block\n */\nArray<StmtSRef> GetChildBlockSRefOnSRefTree(const ScheduleState& self, const StmtSRef& parent_sref);\n\n/*!\n * \\brief Gets the BlockRealize of the leaf blocks of a scope where a specific block/loop is in\n * \\param parent_sref The StmtSRef that points to the parent block/loop\n * \\return A list of leaf BlockRealize\n */\nArray<BlockRealize> GetChildBlockRealizeOnSRefTree(const StmtSRef& parent_sref);\n\n/*!\n * \\brief Get the BlockRealize of the single child block of the block or loop specified by\n * `parent_sref` on SRef tree, or throw an exception if there is 0 or multiple child blocks\n * \\param self The schedule state\n * \\param parent_sref The StmtSRef that points to the parent block/loop\n * \\return The BlockRealize of the single child block\n * \\throw ScheduleError If there is 0 or multiple child blocks\n */\nBlockRealize CheckGetSingleChildBlockRealizeOnSRefTree(const ScheduleState& self,\n                                                       const StmtSRef& parent_sref);\n\n/*!\n * \\brief Get the BlockRealize of the input block\n * \\param self The schedule state\n * \\param block_sref The StmtSRef of the queried block\n * \\return The BlockRealize of the input block\n */\nBlockRealize GetBlockRealize(const ScheduleState& self, const StmtSRef& block_sref);\n\n/*!\n * \\brief Get the IterVarType of the specific loop, according to the blocks it's bound to\n * \\param loop_sref The loop to be checked\n * \\return The IterVarType of the specific loop\n */\nIterVarType GetLoopIterType(const StmtSRef& loop_sref);\n\n/*!\n * \\brief Get the lowest common ancestor of an array of blocks or loops on the sref tree\n * \\param srefs The block srefs or loop srefs whose lowest common ancestor is to be queried\n * \\return The lowest common ancestor of the input block srefs or loop srefs\n * \\note The input array is required to have at least one sref\n */\nStmtSRef GetSRefLowestCommonAncestor(const Array<StmtSRef>& srefs);\n\n/*!\n * \\brief Checks if the given block has been applied by multi-level tiling. We check this by\n *        examine the block's annotation.\n * \\param block_sref The block to be checked\n * \\return A boolean indicating whether the block has been multi-level tiled.\n */\nbool HasBeenMultiLevelTiled(const StmtSRef& block_sref);\n\n/*!\n * \\brief Collect all the feasible compute-at locations of the input block\n * \\param self The schedule state\n * \\param block_sref The block whose compute-at locations are to be collected\n * \\return All the feasible compute-at locations of the input block, given as an array of loop srefs\n *         and an array of their indices among the outer loops of the input block\n */\nstd::pair<Array<StmtSRef>, std::vector<int>> CollectComputeLocation(const ScheduleState& self,\n                                                                    const StmtSRef& block_sref);\n\n/******** Producer-consumer relation ********/\n\n/*!\n * \\brief Get the producer blocks to the given block under the given scope\n * \\param block_sref The block whose producers are to be retrieved\n * \\param scope The block scope where the given block is in\n * \\return The producer blocks of the specified block\n */\nArray<StmtSRef> GetProducers(const StmtSRef& block_sref, const BlockScope& scope);\n\n/*!\n * \\brief Get the consumer blocks to the given block under the given scope\n * \\param block_sref The block whose consumers are to be retrieved\n * \\param scope The block scope where the given block is in\n * \\return The consumer blocks of the specified block\n */\nArray<StmtSRef> GetConsumers(const StmtSRef& block_sref, const BlockScope& scope);\n\n/*!\n * \\brief A solution to split a ordered list of subtrees into two parts,\n * where producers are on the LHS and consumers are on the RHS.\n * For example, subtree[0, 3) are on the LHS, and subtree[3, 6) are on the RHS.\n */\nstruct ProducerConsumerSplit {\n  /*! \\brief Indicates that all producers fall into `subtrees[0, last_producer_position]` */\n  int last_producer_position;\n  /*! \\brief Indicates that all consumers fall into `subtrees[first_consumer_position, ...)` */\n  int first_consumer_position;\n  /*! \\brief The number of given producers visited in `subtrees` */\n  int n_producers_visited;\n  /*! \\brief The number of given consumers visited in `subtrees` */\n  int n_consumers_visited;\n  /*!\n   * \\brief Find a split among the given `subtree`\n   * \\param state The schedule state\n   * \\param subtrees The ordered list of subtrees to be split\n   * \\param producer_block_srefs The producers\n   * \\param consumer_block_srefs The consumers\n   * \\param block2realize If not null, the corresponding BlockRealize to each block in the scope\n   * will be saved in this map\n   * \\return The valid split points are (last_producer_position, first_consumer_position]\n   * \\throw ScheduleError is not valid split is found\n   */\n  static ProducerConsumerSplit Find(\n      const ScheduleState& state, const Array<Stmt>& subtrees,\n      const Array<StmtSRef>& producer_block_srefs, const Array<StmtSRef>& consumer_block_srefs,\n      std::unordered_map<const BlockNode*, const BlockRealizeNode*>* block2realize);\n};\n\n/******** Block-buffer relation ********/\n\n/*!\n * \\brief Get the n-th read or write buffer of the given block.\n * \\param self The schedule state.\n * \\param block The queried block.\n * \\param n The index of the queried buffer.\n * \\param index_type The type of the buffer index, kRead or kWrite.\n * \\return The buffer of the n-th read/write region of the block.\n * \\throw ScheduleError If the buffer index is out of bound.\n */\nBuffer GetNthAccessBuffer(const ScheduleState& self, const Block& block, int n,\n                          BufferIndexType index_type);\n\n/*!\n * \\brief Get the n-th read or write buffer of the given block.\n * \\param self The schedule state.\n * \\param block The queried block.\n * \\param n The index of the queried buffer.\n * \\param index_type The type of the buffer index, kRead or kWrite.\n * \\return The n-th read/write region of the block.\n * \\throw ScheduleError If the buffer index is out of bound.\n */\nBufferRegion GetNthAccessBufferRegion(const ScheduleState& self, const Block& block, int n,\n                                      BufferIndexType index_type);\n\n/*!\n * \\brief Find the defining site of the buffer in the given block and its ancestors\n * \\param block_sref The block sref\n * \\param buffer The buffer\n * \\return The defining site of the buffer and whether the buffer is allocated (otherwise the\n *         buffer is from match_buffer).\n */\nstd::pair<Optional<StmtSRef>, bool> GetBufferDefiningSite(const StmtSRef& block_sref,\n                                                          const Buffer& buffer);\n\n/******** Reduction Block Related ********/\n\n/*!\n * \\brief Get the init values and the BufferStore updates from the input reduction block\n * \\param self The schedule state, used for error reporting\n * \\param block The block from which the init values and BufferStore updates are extracted from\n * \\return The extracted init values and BufferStore updates\n * \\throw ScheduleError If rfactor or cross-thread reduction cannot be applied to the block\n */\nstd::pair<Array<PrimExpr>, Array<BufferStore>> GetInitValuesAndUpdatesFromReductionBlock(\n    const Optional<ScheduleState>& self, Block block);\n\n/*!\n * \\brief Check whether the input array of IterVars only contains data-parallel and reduction block\n * iters\n * \\param iters The input array of IterVars to be checked\n * \\return A boolean indicating whether the input array of IterVars only contains data-parallel and\n * reduction block iters\n */\nbool ContainsOnlyDataParAndReductionBlockIter(const Array<IterVar>& iters);\n\n/*!\n * \\brief Check whether the block's reduction block iters are not used to index the block's output\n * buffers\n * \\param block The block to be checked\n * \\return A boolean indicating whether the block's reduction block iters are not used to index the\n * block's output buffer\n */\nbool ReductionIterNotIndexOutputBuffer(const Block& block);\n\n/*!\n * \\brief Given a list of reduction identities and a list of reduction combiners, detect the\n * corresponding commutative reducer, and extract the combiner LHS values and combiner RHS values\n * \\param self The schedule state\n * \\param identities The reduction identities to be analyzed\n * \\param combiners The reduction combiners to be analyzed\n * \\return The corresponding CommReducer, combiner LHS values and combiner RHS values\n * \\throw ScheduleError If no corresponding commutative reducer can be matched\n */\nstd::tuple<CommReducer, Array<PrimExpr>, Array<PrimExpr>> GetReducerAndCombinerLhsRhs(\n    const Optional<ScheduleState>& self, const Array<PrimExpr>& identities,\n    const Array<BufferStore>& combiners);\n\n/******** Commutative Reducer ********/\n\n/*!\n * \\brief Get the list of the registered reducer-getter functions\n * \\return The list of the registered reducer-getter functions\n * \\sa ReducerRegistry\n */\nstd::vector<runtime::TypedPackedFunc<Optional<CommReducer>(Array<PrimExpr>)>> GetReducerGetters();\n\n/*!\n * \\brief Given the input identities and the combiner BufferStores of a reduction, extract the\n * corresponding commutative reducer, LHS values and RHS values, if possible.\n * \\param identities The identities of the reduction\n * \\param combiners The combiners of the reduction\n * \\param result_reducer The extracted CommReducer\n * \\param lhs The extracted LHS values of the reducer\n * \\param rhs The extracted RHS values of the reducer\n * \\return A boolean indicating whether a corresponding commutative reducer is found\n */\nbool FromIdentityCombiner(const Array<PrimExpr>& identities, const Array<BufferStore>& combiners,\n                          CommReducer* result_reducer, Array<PrimExpr>* lhs, Array<PrimExpr>* rhs);\n\n/******** Misc ********/\n\n/*!\n * \\brief Check whether the input storage scope string is valid. Throw an error if not.\n * \\param self The schedule state\n * \\param storage_scope The storage scope string to be checked\n * \\throw ScheduleError If the input storage scope is not valid\n */\nvoid CheckStorageScope(const ScheduleState& self, String storage_scope);\n\n/*!\n * \\brief Checks if a block could be successfully computed inline into its consumer\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\return A boolean indicating whether the block could be successfully computed inline\n */\nbool CanComputeInline(const ScheduleState& self, const StmtSRef& block_sref);\n\n/*!\n * \\brief Checks if a block could be successfully computed inline into its producer\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\return A boolean indicating whether the block could be successfully computed inline\n */\nbool CanReverseComputeInline(const ScheduleState& self, const StmtSRef& block_sref);\n\n/*!\n * \\brief Checks if a producer block could be successfully computed at the specific loop.\n * \\param self The schedule state\n * \\param block_sref The block to be moved\n * \\param loop_sref The loop where the block to be moved to\n * \\param preserve_unit_loops Whether to keep the trivial loops whose extents are 1\n * \\return A boolean indicating whether the block could be successfully compute at the specific loop\n */\nbool CanComputeAt(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& loop_sref,\n                  bool preserve_unit_loops);\n\n/*!\n * \\brief Checks if a consumer block could be successfully computed at the specific loop.\n * \\param self The schedule state\n * \\param block_sref The block to be moved\n * \\param loop_sref The loop where the block to be moved to\n * \\param preserve_unit_loops Whether to keep the trivial loops whose extents are 1\n * \\return A boolean indicating whether the block could be successfully reverse compute at the\n * specific loop\n */\nbool CanReverseComputeAt(const ScheduleState& self, const StmtSRef& block_sref,\n                         const StmtSRef& loop_sref, bool preserve_unit_loops);\n\n/*!\n * \\brief Provided the access pattern to a buffer, suggest one of the possible layout\n * transformation to minimize the locality of the access pattern.\n * \\param buffer The buffer to be transformed\n * \\param indices The access pattern to the buffer\n * \\param loops The loops above the buffer\n * \\param predicate The predicate of the access\n * \\param analyzer Arithmetic analyzer\n */\nOptional<IndexMap> SuggestIndexMap(const Buffer& buffer, const Array<PrimExpr>& indices,\n                                   const Array<For>& loops, const PrimExpr& predicate,\n                                   arith::Analyzer* analyzer);\n\n/*!\n * \\brief Checks if the given AST contains the specific operators\n * \\param stmt The AST statement to be checked\n * \\param ops The list of operators to be checked\n * \\return A boolean indicating whether the AST contains the specific operators\n */\nbool HasOp(const Stmt& stmt, const Array<Op>& ops);\n\n/*!\n * \\brief Checks if the given AST statement contains if-then-else, including\n * 1) IfThenElse statement\n * 2) Select expression\n * 3) The operator `tir.if_then_else`\n * 4) non-constant-true Block predicates\n * \\param stmt The AST statement to be checked\n * \\return A boolean indicating whether the statement contains the if-then-else pattern\n */\nbool HasIfThenElse(const Stmt& stmt);\n\n/*!\n * \\brief Given the read/write region, extract the pattern of their index correspondence\n * namely, the mapping from read index to the write index.\n * \\param read_region The read region\n * \\param write_region The write region\n * \\return A tuple of booleans, the extracted pattern\n * 0) exists: if the pattern is found\n * 1) surjective: if the pattern is surjective, i.e. each write index is mapped at least once\n *    e.g. A[i, j] = B[i, i, j]\n * 2) injective: if the pattern is injective, i.e. each write index is mapped at most once.\n *    e.g. A[i, j] = B[i]\n * 3) ordered: if the mapping is ordered\n * 4) no_const_read: if there is no constant indexing in the read indices,\n *    e.g. A[i, j] = B[0, i, j]\n * 5) no_shift_read: if there is no constant shift in the read indices,\n *    e.g. A[i, j] = B[i + 1, j]\n */\nstd::tuple</*exists=*/bool,\n           /*surjective=*/bool,\n           /*injective=*/bool,\n           /*ordered=*/bool,\n           /*no_const_read=*/bool,\n           /*no_shift_read=*/bool>\nAnalyzeReadWritePattern(const BufferRegion& read_region, const BufferRegion& write_region);\n\n/*!\n * \\brief Check if the block is a data parallel block, i.e. all the block vars are data parallel\n * \\param block_sref The block to be checked\n * \\return A boolean flag indicating if the block is a data parallel block\n */\nbool IsSpatial(const StmtSRef& block_sref);\n\n/*!\n * \\brief Check whether a block has a trivial binding, i.e. each block var is bound to a outer loop,\n * from outer to inner.\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\return A boolean flag indicating if the block has a trivial binding\n */\nbool IsTrivialBinding(const ScheduleState& self, const StmtSRef& block_sref);\n\n/*!\n * \\brief Checks if the given block has data reuse opportunity and thus multi-level tiling is\n * beneficial.\n * \\param self The schedule state\n * \\param block_sref The block to be checked\n * \\return A boolean indicating whether the block has data reuse opportunity\n */\nbool NeedsMultiLevelTiling(const ScheduleState& self, const StmtSRef& block_sref);\n\n/*!\n * \\brief Checks if all the blocks in the PrimFunc is spatial\n * \\param func The PrimFunc to be checked\n * \\return A boolean indicating whether all the blocks in the PrimFunc is spatial\n */\nbool IsSpatialPrimFunc(const PrimFunc& func);\n\n/*!\n * \\brief Checks if the rfactor or cross thread reduction is beneficial to the given block.\n * \\param self The schedule state.\n * \\param block_sref The block to be checked.\n * \\param max_parallel_extent The maximum parallel jobs on the target.\n * \\param max_parallel_basic The maximum cores on the target.\n * \\return A boolean indicating whether the operation is beneficial.\n */\nbool NeedsRFactorOrCrossThreadReduction(const tir::ScheduleState& self,   //\n                                        const tir::StmtSRef& block_sref,  //\n                                        int64_t max_parallel_extent,      //\n                                        int64_t max_parallel_basic);\n\n/*!\n * \\brief Analyze the buffer region under the sref tree path [dom_low_inclusive, dom_high_exclusive)\n * Relaxation of the region may be used in upper-bound analysis, i.e. some extra region may be added\n * to the result.\n * \\param region The buffer region to be analyzed\n * \\param dom_low_inclusive The lowest node in the sref tree path\n * \\param dom_high_exclusive The highest node in the sref tree path\n * \\return An n-dimensional integer set\n */\nArray<arith::IntSet> AnalyzeRegionUpperBound(const BufferRegion& region, const PrimExpr& predicate,\n                                             const StmtSRef& dom_low_inclusive,\n                                             const StmtSRef& dom_high_exclusive,\n                                             arith::Analyzer* analyzer);\n\n/*!\n * \\brief Analyze the buffer region under the sref tree path [dom_low_inclusive, dom_high_exclusive)\n * Some subregion may be discarded during the lower-bound analysis.\n * \\param realize The block realize that touches the buffer region\n * \\param region The buffer region to be analyzed\n * \\param dom_low_inclusive The lowest node in the sref tree path\n * \\param dom_high_exclusive The highest node in the sref tree path\n * \\param analyzer The analyzer\n * \\return An n-dimensional integer set\n */\nArray<arith::IntSet> AnalyzeRegionLowerBound(const BufferRegion& region, const PrimExpr& predicate,\n                                             const StmtSRef& dom_low_inclusive,\n                                             const StmtSRef& dom_high_exclusive,\n                                             arith::Analyzer* analyzer);\n\n/*!\n * \\brief Check if buffer indices are all Vars and extr\n * \\param buffer_access The BufferLoad or BufferStore\n * \\return The indices if the indices are all Vars, otherwise NullOpt\n */\ntemplate <typename T>\nOptional<Array<Var>> CheckTrivialBufferIndices(const T& buffer_access) {\n  Array<Var> indices;\n  for (const PrimExpr& index : buffer_access->indices) {\n    const VarNode* var = index.as<VarNode>();\n    if (var == nullptr) {\n      return NullOpt;\n    }\n    indices.push_back(GetRef<Var>(var));\n  }\n  return indices;\n}\n\n/*!\n * \\brief Simplify non-trivial expressions\n * \\param expr The expression to be simplified\n * \\param analyzer The analyzer\n * \\return The simplified expression\n *\n * During scheduling, we often need preserve block iters in trivial expressions that can be\n * simplified to constant values for further scheduling and analysis because simplifing away the\n * block iters may result in loss of information for further analysis.\n */\nPrimExpr SimplifyNonTrivialExpr(const PrimExpr& expr, arith::Analyzer* analyzer);\n\n/*! \\brief Necessary information used for tensorization */\nclass TensorizeInfoNode : public Object {\n public:\n  /*! \\brief Maps loops in a target block to the ones in an intrinsic description */\n  Map<tir::StmtSRef, tir::For> loop_map;\n  /*! \\brief Maps loops in an intrinsic description to its index, outer to inner */\n  Map<tir::For, Integer> desc_loop_indexer;\n  /*! \\brief Optional padded extents of the block iters when padding is needed to match the\n   * intrinsic description\n   */\n  Optional<Array<Integer>> block_iter_paddings;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"loop_map\", &loop_map);\n    v->Visit(\"desc_loop_indexer\", &desc_loop_indexer);\n    v->Visit(\"block_iter_paddings\", &block_iter_paddings);\n  }\n\n  static constexpr const char* _type_key = \"tir.schedule.TensorizeInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(TensorizeInfoNode, Object);\n};\n\nclass TensorizeInfo : public ObjectRef {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(TensorizeInfo, ObjectRef, TensorizeInfoNode);\n};\n\n/*!\n * \\brief Establish a mapping between loops in a target block and an intrinsic description\n * \\param self The schedule state to be tensorized\n * \\param block_sref The target block to match against\n * \\param desc_func The prim func describing the computation to be tensorized\n * \\param allow_padding Whether to allow padding the block iters to match the intrinsic description\n * \\return TensorizeInfo structure if a valid mapping is found, NullOpt otherwise\n */\nOptional<TensorizeInfo> GetTensorizeLoopMapping(const tir::ScheduleState& self,\n                                                const tir::StmtSRef& block_sref,\n                                                const tir::PrimFunc& desc_func, bool allow_padding);\n\n/*\uff01\\brief Necessary information used to perform transformations for tensorization */\nclass AutoTensorizeMappingInfoNode : public Object {\n public:\n  /*! \\brief Possible mappings to apply to block iters */\n  Array<IndexMap> mappings;\n\n  /* Additional information from AutoTensorizeComparator */\n\n  /*! \\brief Mapping from LHS buffer to RHS buffer */\n  Map<Buffer, Buffer> lhs_buffer_map;\n  /*! \\brief Buffer indices on RHS */\n  Map<Buffer, Array<PrimExpr>> rhs_buffer_indices;\n  /*! \\brief Block iters on LHS */\n  Array<IterVar> lhs_iters;\n  /*! \\brief Block iters on RHS */\n  Array<IterVar> rhs_iters;\n\n  void VisitAttrs(AttrVisitor* v) {\n    v->Visit(\"mappings\", &mappings);\n    v->Visit(\"lhs_buffer_map\", &lhs_buffer_map);\n    v->Visit(\"rhs_buffer_indices\", &rhs_buffer_indices);\n    v->Visit(\"lhs_iters\", &lhs_iters);\n    v->Visit(\"rhs_iters\", &rhs_iters);\n  }\n\n  static constexpr const char* _type_key = \"tir.schedule.AutoTensorizeMappingInfo\";\n  TVM_DECLARE_FINAL_OBJECT_INFO(AutoTensorizeMappingInfoNode, Object);\n};\n\nclass AutoTensorizeMappingInfo : public ObjectRef {\n public:\n  TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(AutoTensorizeMappingInfo, ObjectRef,\n                                            AutoTensorizeMappingInfoNode);\n};\n\n/*!\n * \\brief Get mapping info between a target block and an intrinsic description including layout\n * transformations to apply.\n * \\param self The schedule state\n * \\param block_sref The compute block for auto tensorization\n * \\param desc_func The prim func describing the computation to be tensorized\n * \\return AutoTensorizeMappingInfo structure if a potential mapping is found, NullOpt otherwise.\n * \\note Returning a valid AutoTensorizeMappingInfo doesn't guarantee the block can be tensorized.\n * We will need to apply the suggested layout transformations and then match against the tensor\n * intrinsics.\n */\nOptional<AutoTensorizeMappingInfo> GetAutoTensorizeMappingInfo(const ScheduleState& self,\n                                                               const StmtSRef& block_sref,\n                                                               const PrimFunc& desc_func);\n\n/*!\n * \\brief Perform basic checks for auto tensorization applicability, such as the structure of\n * arithmetic operations and data types.\n * \\param sch The schedule to be tensorized\n * \\param block_rv The compute block for auto tensorization\n * \\param desc_func The prim func describing the computation to be tensorized\n * \\return true if basic conditions are met.\n */\nbool CheckAutoTensorizeApplicable(const tir::Schedule& sch, const tir::BlockRV& block_rv,\n                                  const tir::PrimFunc& desc_func);\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_ANALYSIS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/concrete_schedule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_CONCRETE_SCHEDULE_H_\n#define TVM_TIR_SCHEDULE_CONCRETE_SCHEDULE_H_\n\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"./utils.h\"\n\nnamespace tvm {\nnamespace tir {\n\nclass ConcreteScheduleNode : public ScheduleNode {\n  friend class Schedule;\n  friend class ScheduleCopier;\n\n public:\n  using TSymbolTable = Map<ObjectRef, ObjectRef>;\n\n protected:\n  /*! \\brief The internal state of scheduling */\n  ScheduleState state_;\n  /*! \\brief The function to be worked on. */\n  Optional<GlobalVar> func_working_on_;\n  /*! \\brief The level of error rendering */\n  ScheduleErrorRenderLevel error_render_level_;\n  /*! \\brief A symbol table that maps random variables to concrete StmtSRef/Integers */\n  TSymbolTable symbol_table_;\n  /*! \\brief A persistent stateless arithmetic analyzer. */\n  std::unique_ptr<arith::Analyzer> analyzer_;\n  /*! \\brief The value of random state for sampling. */\n  support::LinearCongruentialEngine::TRandState rand_state_;\n\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `state_` is not visited\n    // `func_working_on_` is not visited\n    // `error_render_level_` is not visited\n    // `symbol_table_` is not visited\n    // `analyzer_` is not visited\n    // `rgnd_state_` is not visited\n  }\n\n  virtual ~ConcreteScheduleNode() = default;\n\n public:\n  ScheduleState state() const final { return state_; }\n  Optional<Trace> trace() const override { return NullOpt; }\n  void WorkOn(const String& func_name) final;\n  Schedule Copy() override;\n  void Seed(support::LinearCongruentialEngine::TRandState seed) final;\n  support::LinearCongruentialEngine::TRandState ForkSeed() final;\n\n public:\n  /******** Lookup random variables ********/\n  inline Block Get(const BlockRV& block_rv) const final;\n  inline For Get(const LoopRV& loop_rv) const final;\n  inline PrimExpr Get(const ExprRV& expr_rv) const final;\n  inline StmtSRef GetSRef(const BlockRV& block_rv) const final;\n  inline StmtSRef GetSRef(const LoopRV& loop_rv) const final;\n  inline bool HasBlock(const BlockRV& block_rv) const final;\n  inline Array<StmtSRef> GetSRefs(const Array<BlockRV>& rvs) const;\n  inline Array<StmtSRef> GetSRefs(const Array<LoopRV>& rvs) const;\n  void RemoveRV(const BlockRV& block_rv) final { RemoveFromSymbolTable(block_rv); }\n  void RemoveRV(const LoopRV& loop_rv) final { RemoveFromSymbolTable(loop_rv); }\n  void RemoveRV(const ExprRV& expr_rv) final { RemoveFromSymbolTable(expr_rv); }\n  using ScheduleNode::GetSRef;\n\n public:\n  /******** Schedule: Sampling ********/\n  ExprRV SampleCategorical(const Array<Integer>& candidates, const Array<FloatImm>& probs,\n                           Optional<Integer> decision = NullOpt) override;\n  Array<ExprRV> SamplePerfectTile(const LoopRV& loop_rv, int n, int max_innermost_factor,\n                                  Optional<Array<Integer>> decision = NullOpt) override;\n  LoopRV SampleComputeLocation(const BlockRV& block_rv,\n                               Optional<Integer> decision = NullOpt) override;\n  /******** Schedule: Get blocks & loops ********/\n  BlockRV GetBlock(const String& name, const Optional<String>& func_name) override;\n  Array<LoopRV> GetLoops(const BlockRV& block_rv) override;\n  Array<BlockRV> GetChildBlocks(const BlockRV& block_rv) override;\n  Array<BlockRV> GetChildBlocks(const LoopRV& loop_rv) override;\n  Array<BlockRV> GetProducers(const BlockRV& block_rv) override;\n  Array<BlockRV> GetConsumers(const BlockRV& block_rv) override;\n  /******** Schedule: Transform loops ********/\n  LoopRV Fuse(const Array<LoopRV>& loop_rvs, bool preserve_unit_iters) override;\n  Array<LoopRV> Split(const LoopRV& loop_rv, const Array<Optional<ExprRV>>& factors,\n                      bool preserve_unit_iters) override;\n  void Reorder(const Array<LoopRV>& ordered_loop_rvs) override;\n  LoopRV AddUnitLoop(const BlockRV& block_rv) override;\n  LoopRV AddUnitLoop(const LoopRV& loop_rv) override;\n  /******** Schedule: Manipulate ForKind ********/\n  void Parallel(const LoopRV& loop_rv) override;\n  void Vectorize(const LoopRV& loop_rv) override;\n  void Bind(const LoopRV& loop_rv, const String& thread_axis) override;\n  void Unroll(const LoopRV& loop_rv) override;\n  /******** Schedule: Insert cache stages ********/\n  BlockRV CacheRead(const BlockRV& block_rv, int read_buffer_index, const String& storage_scope,\n                    const Array<BlockRV> consumer_blocks = {}) override;\n  BlockRV CacheWrite(const BlockRV& block_rv, int write_buffer_index,\n                     const String& storage_scope) override;\n  Array<BlockRV> CacheInplace(const BlockRV& block_rv, int read_buffer_index,\n                              const String& storage_scope) override;\n  Array<BlockRV> CacheIndex(const BlockRV& block_rv, int write_buffer_index) override;\n  BlockRV ReIndex(const BlockRV& block_rv, int buffer_index,\n                  BufferIndexType buffer_index_type) override;\n  /******** Schedule: Compute location ********/\n  void ComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv, bool preserve_unit_loops,\n                 int index = -1) override;\n  void ReverseComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv, bool preserve_unit_loops,\n                        int index = -1) override;\n  void ComputeInline(const BlockRV& block) override;\n  void ReverseComputeInline(const BlockRV& block) override;\n  /******** Schedule: Reduction ********/\n  BlockRV RFactor(const LoopRV& loop_rv, int factor_axis) override;\n  BlockRV DecomposeReduction(const BlockRV& block_rv, const LoopRV& loop_rv) override;\n  void PadEinsum(const BlockRV& block_rv, const Array<Integer>& padding) override;\n  /******** Schedule: Block annotation ********/\n  void StorageAlign(const BlockRV& block_rv, int buffer_index, int axis, int factor,\n                    int offset) override;\n  void SetScope(const BlockRV& block_rv, int buffer_index, const String& storage_scope) override;\n  /******** Schedule: Blockize & Tensorize ********/\n  BlockRV Blockize(const LoopRV& loop_rv) override;\n  void Tensorize(const BlockRV& block_rv, const String& intrin) override;\n  void Tensorize(const LoopRV& loop_rv, const String& intrin) override;\n  /******** Schedule: Annotation ********/\n  void Annotate(const LoopRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) override;\n  void Unannotate(const LoopRV& loop_rv, const String& ann_key) override;\n  void Annotate(const BlockRV& block_rv, const String& ann_key, const ObjectRef& ann_val) override;\n  void Unannotate(const BlockRV& block_rv, const String& ann_key) override;\n  /******** Schedule: Layout transformation ********/\n  void TransformLayout(const BlockRV& block_rv, int buffer_index, BufferIndexType buffer_index_type,\n                       const IndexMap& index_map, const Optional<IndexMap>& pad_value) override;\n  void TransformBlockLayout(const BlockRV& block_rv, const IndexMap& index_map) override;\n  void SetAxisSeparator(const BlockRV& block_rv, int buffer_index,\n                        BufferIndexType buffer_index_type,\n                        const Array<IntImm>& axis_separators) override;\n  /******** Schedule: Padding decomposition ********/\n  BlockRV DecomposePadding(const BlockRV& block_rv, const LoopRV& loop_rv) override;\n  /******** Schedule: Buffer transformation ********/\n  void RollingBuffer(const BlockRV& block_rv, int write_buffer_index) override;\n  /******** Schedule: Misc ********/\n  void EnterPostproc() override {}\n\n protected:\n  /******** Utility functions ********/\n  /*!\n   * \\brief Copy the schedule state, as well as the symbol table\n   * \\param new_state The ScheduleState copied\n   * \\param new_symbol_table The symbol table copied\n   */\n  void Copy(ScheduleState* new_state, TSymbolTable* new_symbol_table) const;\n  /*!\n   * \\brief Add srefs as random variables into the symbol table\n   * \\tparam T The type of the random variables\n   * \\param srefs The srefs to be added to the symbol table\n   * \\return The new random variables created\n   */\n  template <class T>\n  inline Array<T> CreateRV(const Array<StmtSRef>& srefs);\n  /*!\n   * \\brief Add an sref as a random variable into the symbol table\n   * \\tparam T The type of the random variable\n   * \\param sref The sref to be added to the symbol table\n   * \\return The new random variable created\n   */\n  template <class T>\n  inline T CreateRV(const StmtSRef& sref);\n  /*!\n   * \\brief Add an integer as a random variable into the symbol table\n   * \\param value The integer to be added to the symbol table\n   * \\return The new random variable created\n   */\n  inline ExprRV CreateRV(int64_t value);\n  /*!\n   * \\brief Add a list of integers as random variables into the symbol table\n   * \\param value The list of integers to be added to the symbol table\n   * \\return The new random variables created\n   */\n  inline Array<ExprRV> CreateRV(const std::vector<int64_t>& value);\n  /*! \\brief Remove a random variable from the symbol table */\n  inline void RemoveFromSymbolTable(const ObjectRef& rv);\n  /*!\n   * \\brief Check the annotation value is valid and look up the random variable. Raises an exception\n   * if the type of the annotation value is not allowed.\n   * \\param The annotation value.\n   * \\return The annotation value with random variables substituted with their values.\n   */\n  ObjectRef CheckAndGetAnnotationValue(const ObjectRef& ann_val);\n};\n\n// implementations\n\n/******** Lookup random variables ********/\n\ninline Block ConcreteScheduleNode::Get(const BlockRV& block_rv) const {\n  StmtSRef sref = this->GetSRef(block_rv);\n  const BlockNode* block = TVM_SREF_TO_BLOCK(sref);\n  return GetRef<Block>(block);\n}\n\ninline For ConcreteScheduleNode::Get(const LoopRV& loop_rv) const {\n  StmtSRef sref = this->GetSRef(loop_rv);\n  const ForNode* loop = TVM_SREF_TO_FOR(sref);\n  return GetRef<For>(loop);\n}\n\ninline PrimExpr ConcreteScheduleNode::Get(const ExprRV& expr_rv) const {\n  PrimExpr transformed = Substitute(expr_rv, [this](const Var& var) -> Optional<PrimExpr> {\n    auto it = this->symbol_table_.find(var);\n    if (it == this->symbol_table_.end()) {\n      LOG(FATAL) << \"IndexError: Cannot find corresponding ExprRV: \" << var;\n    }\n    const ObjectRef& obj = (*it).second;\n    const auto* int_imm = TVM_TYPE_AS(obj, IntImmNode);\n    return Integer(int_imm->value);\n  });\n  return this->analyzer_->Simplify(transformed);\n}\n\ninline bool ConcreteScheduleNode::HasBlock(const BlockRV& block_rv) const {\n  auto it = this->symbol_table_.find(block_rv);\n  if (it == this->symbol_table_.end()) {\n    return false;\n  }\n  const ObjectRef& obj = (*it).second;\n  const auto* sref = obj.as<StmtSRefNode>();\n  if (sref == nullptr || sref->stmt == nullptr) {\n    return false;\n  }\n  return true;\n}\n\ninline StmtSRef ConcreteScheduleNode::GetSRef(const BlockRV& block_rv) const {\n  auto it = this->symbol_table_.find(block_rv);\n  if (it == this->symbol_table_.end()) {\n    LOG(FATAL) << \"IndexError: Cannot find corresponding BlockRV: \" << block_rv;\n  }\n  const ObjectRef& obj = (*it).second;\n  const auto* sref = obj.as<StmtSRefNode>();\n  if (sref == nullptr) {\n    LOG(FATAL) << \"ValueError: BlockRV's corresponding type is invalid: \"\n               << (obj.defined() ? obj->GetTypeKey() : \"None\");\n  }\n  if (sref->stmt == nullptr) {\n    LOG(FATAL) << \"ValueError: The block no longer exists in the IRModule\";\n  }\n  return GetRef<StmtSRef>(sref);\n}\n\ninline StmtSRef ConcreteScheduleNode::GetSRef(const LoopRV& loop_rv) const {\n  static StmtSRef inline_mark = StmtSRef::InlineMark();\n  static StmtSRef root_mark = StmtSRef::RootMark();\n  auto it = this->symbol_table_.find(loop_rv);\n  if (it == this->symbol_table_.end()) {\n    LOG(FATAL) << \"IndexError: Cannot find corresponding LoopRV: \" << loop_rv;\n  }\n  const ObjectRef& obj = (*it).second;\n  if (obj.same_as(inline_mark)) {\n    return inline_mark;\n  }\n  if (obj.same_as(root_mark)) {\n    return root_mark;\n  }\n  const auto* sref = obj.as<StmtSRefNode>();\n  if (sref == nullptr) {\n    LOG(FATAL) << \"ValueError: LoopRV's corresponding type is invalid: \"\n               << (obj.defined() ? obj->GetTypeKey() : \"None\");\n  }\n  if (sref->stmt == nullptr) {\n    LOG(FATAL) << \"ValueError: The loop no longer exists in the IRModule\";\n  }\n  return GetRef<StmtSRef>(sref);\n}\n\ntemplate <class T>\ninline Array<StmtSRef> GetSRefsHelper(const ConcreteScheduleNode* sch, const Array<T>& rvs) {\n  Array<StmtSRef> result;\n  result.reserve(rvs.size());\n  for (const T& rv : rvs) {\n    result.push_back(sch->GetSRef(rv));\n  }\n  return result;\n}\n\ninline Array<StmtSRef> ConcreteScheduleNode::GetSRefs(const Array<BlockRV>& rvs) const {\n  return GetSRefsHelper(this, rvs);\n}\n\ninline Array<StmtSRef> ConcreteScheduleNode::GetSRefs(const Array<LoopRV>& rvs) const {\n  return GetSRefsHelper(this, rvs);\n}\n\n/******** Adding/Removing elements in the symbol table ********/\n\ntemplate <class T>\ninline Array<T> ConcreteScheduleNode::CreateRV(const Array<StmtSRef>& srefs) {\n  Array<T> result;\n  result.reserve(srefs.size());\n  for (const StmtSRef& sref : srefs) {\n    T rv;\n    this->symbol_table_.Set(rv, sref);\n    result.push_back(rv);\n  }\n  return result;\n}\n\ntemplate <class T>\ninline T ConcreteScheduleNode::CreateRV(const StmtSRef& sref) {\n  T rv;\n  this->symbol_table_.Set(rv, sref);\n  return std::move(rv);\n}\n\ninline ExprRV ConcreteScheduleNode::CreateRV(int64_t value) {\n  Var rv(\"v\" + std::to_string(this->symbol_table_.size() + 1), DataType::Int(32));\n  this->symbol_table_.Set(rv, Integer(static_cast<int32_t>(value)));\n  return std::move(rv);\n}\n\ninline Array<ExprRV> ConcreteScheduleNode::CreateRV(const std::vector<int64_t>& value) {\n  Array<ExprRV> results;\n  results.reserve(value.size());\n  for (int64_t v : value) {\n    results.push_back(CreateRV(v));\n  }\n  return results;\n}\n\ninline void ConcreteScheduleNode::RemoveFromSymbolTable(const ObjectRef& obj) {\n  auto it = this->symbol_table_.find(obj);\n  if (it != this->symbol_table_.end()) {\n    this->symbol_table_.erase(obj);\n  } else {\n    LOG(FATAL) << \"IndexError: Cannot find the object in the symbol table: \" << obj;\n    throw;\n  }\n}\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_CONCRETE_SCHEDULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/error.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_ERROR_H_\n#define TVM_TIR_SCHEDULE_ERROR_H_\n#include <tvm/tir/schedule/state.h>\n\n#include <string>\n#include <utility>\n\nnamespace tvm {\nnamespace tir {\n\n/*! \\brief Error that happens during TensorIR scheduling */\nclass ScheduleError : public tvm::runtime::Error {\n public:\n  /*! \\brief Base constructor */\n  ScheduleError() : tvm::runtime::Error(\"\") {}\n  /*! \\brief The error occurred in this IRModule */\n  virtual IRModule mod() const = 0;\n  /*! \\brief The locations of interest that we want to point out */\n  virtual Array<ObjectRef> LocationsOfInterest() const = 0;\n  /*!\n   * \\brief Returns an error string template for rendering, corresponds to the \"detail\" mode.\n   * \\sa ScheduleErrorRenderLevel\n   * \\note The template is a string, e.g.\n   * \"Some error occurred on block {0} and loop {1} blah blah\"\n   * And renderer will replace {0} and {1} according to the list provided LocationsOfInterest. Right\n   * now it only printed out all the locations in plain text, but in the future, we may want to mark\n   * the IR with underscores and attach names to each location of interest, like what synr does.\n   */\n  virtual String DetailRenderTemplate() const = 0;\n  /*!\n   * \\brief Returns an error string without needing to render, corresponds to the \"fast\" mode\n   * \\sa ScheduleErrorRenderLevel\n   */\n  virtual String FastErrorString() const = 0;\n  /*! \\brief Render the ScheduleError with the template provided by `DetailRenderTemplate` */\n  String RenderReport(const String& primitive) const;\n};\n\nclass LoopPositionError : public ScheduleError {\n public:\n  explicit LoopPositionError(IRModule mod, For loop, Block block, const std::string& primitive)\n      : mod_(std::move(mod)),\n        loop_(std::move(loop)),\n        block_(std::move(block)),\n        primitive_(primitive) {}\n\n  String FastErrorString() const final {\n    return \"ScheduleError: \" + primitive_ + \" expect the loop to be an ancestor of block\";\n  }\n\n  String DetailRenderTemplate() const final {\n    std::ostringstream os;\n    os << \"ScheduleError: The input loop {0} of \" << primitive_\n       << \" is required to be be an ancestor of block {1}.\";\n    return os.str();\n  }\n\n  IRModule mod() const final { return mod_; }\n  Array<ObjectRef> LocationsOfInterest() const final { return {loop_, block_}; }\n\n  IRModule mod_;\n  For loop_;\n  Block block_;\n  std::string primitive_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_ERROR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/instruction_traits.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_INSTRUCTION_TRAITS_H_\n#define TVM_TIR_SCHEDULE_INSTRUCTION_TRAITS_H_\n\n#include <tvm/tir/schedule/instruction.h>\n#include <tvm/tir/schedule/schedule.h>\n\n#include <algorithm>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Register an InstructionKind using a trait class\n * \\param InstructionKindTraits A traits class of an InstructionKind\n *\n * Example:\n *\n * \\code\n *\n * struct SomeInstructionKindTraits {\n *   static constexpr const char* kName = \"name-of-the-instruction\";\n *   static constexpr bool kIsPure = false;\n *\n *   // Convertible to `InstructionKindNode::FInstructionApply`\n *   static Array<ObjectRef> ApplyToSchedule(\n *      const tir::Schedule& sch,\n *      const Array<ObjectRef>& inputs,\n *      const Array<ObjectRef>& attrs,\n *      const Optional<ObjectRef>& decision);\n *\n *   // Convertible to `InstructionKindNode::FInstructionAsPython`\n *   static String AsPython(\n *      const Array<String>& inputs,\n *      const Array<ObjectRef>& attrs,\n *      const Optional<ObjectRef>& decision,\n *      const Array<String>& outputs);\n *\n *   // Convertible to `InstructionKindNode::FInstructionAttrsAsJSON`\n *   static ObjectRef AttrsAsJSON(\n *      const Array<ObjectRef>& attrs);\n *\n *   // Convertible to `InstructionKindNode::FInstructionAttrsFromJSON`\n *   static Array<ObjectRef> AttrsFromJSON(\n *      const ObjectRef& attrs_record);\n * };\n *\n * TVM_REGISTER_INST_KIND_TRAITS(SomeInstructionKindTraits);\n *\n * \\endcode\n */\n#define TVM_REGISTER_INST_KIND_TRAITS(InstructionKindTraits)         \\\n  TVM_REGISTER_INST_KIND(InstructionKindTraits::kName)               \\\n      .set_is_pure(InstructionKindTraits::kIsPure)                   \\\n      .set_apply_to_schedule(InstructionKindTraits::ApplyToSchedule) \\\n      .set_attrs_as_json(InstructionKindTraits::AttrsAsJSON)         \\\n      .set_attrs_from_json(InstructionKindTraits::AttrsFromJSON)     \\\n      .set_as_python(InstructionKindTraits::AsPython)\n\n/*!\n * \\brief A helper to conveniently register an InstructionKind. When inherited in curiously\n * recursive template pattern, the derived class `TTraits` only needs to define two functions on the\n * unpacked inputs, and the helper handles unpacking and downcasting. See the example for more\n * details.\n *\n * \\tparam TTraits The derived class\n *\n * Example:\n *\n * \\code\n *\n * struct SamplePerfectTileTraits : public UnpackedInstTraits<SamplePerfectTileTraits> {\n *   // The name of this kind of instruction\n *   static constexpr const char* kName = \"SamplePerfectTile\";\n *   // A boolean indicating if the instruction is pure, i.e. change nothing in the schedule state\n *   static constexpr bool kIsPure = true;\n *   // The number of inputs in this kind of instruction\n *   static constexpr size_t kNumInputs = 1;\n *   // The number of attributes in this kind of instruction\n *   static constexpr size_t kNumAttrs = 2;\n *   // The number of decisions in this kind of instruction (only 0 or 1 is allowed)\n *   static constexpr size_t kNumDecisions = 1;\n *\n *   // Calling convention:\n *   // - All the arguments must be ObjectRef\n *   // - The 1st argument is Schedule\n *   // - The next `kNumInputs` arguments are input random variables\n *   // - The next `kNumAttrs` arguments are attributes\n *   // - The next argument is decision, if `kNumDecisions == 1`\n *   static Array<Var> UnpackedApplyToSchedule(\n *      Schedule sch,\n *      LoopRV loop_rv,\n *      Integer n,\n *      Integer max_innermost_factor,\n *      Optional<Array<Integer>> decision) {\n *     return sch->SamplePerfectTile(loop_rv, n->value, max_innermost_factor->value, decision);\n *   }\n *\n *   // Calling convention:\n *   // - All the arguments must be ObjectRef\n *   // - The 1st argument is an array containing names of output random variables\n *   // - The next `kNumInputs` arguments are names of input random variables\n *   // - The next `kNumAttrs` arguments are attributes\n *   // - The next argument is decision, if `kNumDecisions == 1`\n *   static String UnpackedAsPython(\n *      Array<String> outputs,\n *      String loop_rv,\n *      Integer n,\n *      Integer max_innermost_factor,\n *      Optional<Array<Integer>> decision) {\n *     PythonAPICall py(\"sample_perfect_tile\");\n *     py.Input(\"loop\", loop_rv);\n *     py.Input(\"n\", n->value);\n *     py.Input(\"max_innermost_factor\", max_innermost_factor->value);\n *     py.Decision(decision);\n *     py.OutputList(outputs);\n *     return py.Str();\n *   }\n *\n *   template <typename>\n *   friend struct UnpackedInstTraits;\n * };\n *\n * TVM_REGISTER_INST_KIND(SamplePerfectTileTraits);\n * \\endcode\n */\ntemplate <class TTraits>\nstruct UnpackedInstTraits {\n  /*!\n   * \\brief Unpack the arguments in the calling convention, and feed them into\n   * `TTraits::UnpackedApplyToSchedule`\n   * \\sa InstructionKindNode::f_apply_to_schedule\n   */\n  static Array<ObjectRef> ApplyToSchedule(const Schedule& sch, const Array<ObjectRef>& inputs,\n                                          const Array<ObjectRef>& attrs,\n                                          const Optional<ObjectRef>& decision);\n\n  /*!\n   * \\brief Unpack the arguments in the calling convention, and feed them into\n   * `TTraits::UnpackedAsPython`\n   * \\sa InstructionKindNode::f_as_python\n   */\n  static String AsPython(const Array<ObjectRef>& inputs, const Array<ObjectRef>& attrs,\n                         const Optional<ObjectRef>& decision, const Array<String>& outputs);\n\n  /*! \\brief No customized serializer by default */\n  static constexpr std::nullptr_t AttrsAsJSON = nullptr;\n\n  /*! \\brief No customized deserializer by default */\n  static constexpr std::nullptr_t AttrsFromJSON = nullptr;\n\n protected:\n  template <size_t index_offset>\n  static TVM_ALWAYS_INLINE void _SetInputs(const runtime::TVMArgsSetter& setter,\n                                           const Array<ObjectRef>& inputs);\n  template <size_t index_offset>\n  static TVM_ALWAYS_INLINE void _SetAttrs(const runtime::TVMArgsSetter& setter,\n                                          const Array<ObjectRef>& attrs);\n  template <size_t index_offset>\n  static TVM_ALWAYS_INLINE void _SetDecision(const runtime::TVMArgsSetter& setter,\n                                             const Optional<ObjectRef>& decision);\n  static TVM_ALWAYS_INLINE Array<ObjectRef> _ConvertOutputs(const TVMRetValue& rv);\n};\n\n/*!\n * \\brief A helper class that constructs schedule API call in python syntax,\n * which helps convert an Inst to a python statement.\n * \\sa InstructionKindNode::f_as_python\n */\nclass PythonAPICall {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param method_name The name of the schedule API to be called\n   */\n  explicit PythonAPICall(String method_name) : method_name_(method_name), output_(NullOpt) {}\n  /*! \\brief Add an integer input */\n  inline void Input(String arg_name, int arg);\n  /*! \\brief Add an integer input */\n  inline void Input(String arg_name, int64_t arg);\n  /*! \\brief Add a bool input */\n  inline void Input(String arg_name, bool arg);\n  /*! \\brief Add a double input */\n  inline void Input(String arg_name, double arg);\n  /*! \\brief Add an input random variable */\n  inline void Input(String arg_name, String arg);\n  /*! \\brief Add an input, dispatched to different implementations according to the object's type */\n  inline void Input(String arg_name, ObjectRef arg);\n  /*! \\brief Add the decision */\n  inline void Decision(ObjectRef decision);\n  /*!\n   * \\brief Add a single output random variable\n   * \\param unit_array An array containing only one element\n   */\n  inline void SingleOutput(Array<String> unit_array);\n  /*! \\brief Add a list of output random variables */\n  inline void OutputList(Array<String> outputs);\n  /*! \\returns The schedule API call in python syntax */\n  inline String Str() const;\n\n private:\n  /*! \\brief Converts a TVM object to python string and print to the output stream */\n  inline void AsPythonString(const ObjectRef& obj, std::ostream& os);\n\n private:\n  /*! \\brief The name of the API to call */\n  String method_name_;\n  /*! \\brief The output of the instruction */\n  Optional<String> output_;\n  /*! \\brief The names of input arguments */\n  std::vector<String> arg_names_;\n  /*! \\brief The values of input arguments */\n  std::vector<String> args_;\n};\n\n/********** implementation details **********/\n\n// forward declaration\nnamespace details {\n\ntemplate <typename... Args>\nstruct _ArgsPacker;\n\ntemplate <>\nstruct _ArgsPacker<> {\n  static constexpr bool checked = true;\n};\n\ntemplate <typename TObjectRef, typename... Args>\nstruct _ArgsPacker<TObjectRef, Args...> {\n  static constexpr bool checked =\n      std::is_base_of<ObjectRef, TObjectRef>::value && _ArgsPacker<Args...>::checked;\n};\n\ntemplate <typename T>\nstruct _MethodType {};\n\ntemplate <typename TReturn, typename... Args>\nstruct _MethodType<TReturn(Args...)> {\n  using return_type = TReturn;\n  using argument_type = _ArgsPacker<Args...>;\n};\n\ntemplate <typename T>\nstruct _NumArgs {};\n\ntemplate <typename TReturn, typename... Args>\nstruct _NumArgs<TReturn(Args...)> {\n  static constexpr size_t value = sizeof...(Args);\n};\n\ntemplate <typename>\nstruct _IsTVMArray : std::false_type {};\n\ntemplate <typename T>\nstruct _IsTVMArray<runtime::Array<T>> : std::true_type {};\n\ntemplate <typename T>\nstruct _IsSingleObject\n    : std::integral_constant<bool, std::is_base_of<ObjectRef, T>::value && !_IsTVMArray<T>::value> {\n};\n\ntemplate <class T>\nusing ReturnType = typename _MethodType<std::remove_cv_t<T>>::return_type;\n\ntemplate <class T>\nstatic constexpr bool ArgumentAreAllObjects =\n    _MethodType<std::remove_cv_t<T>>::argument_type::checked;\n\ntemplate <class T>\nstatic constexpr size_t NumArgs = _NumArgs<std::remove_cv_t<T>>::value;\n\ntemplate <class T>\nstatic constexpr int IsTVMArray = _IsTVMArray<std::remove_cv_t<T>>::value;\n\ntemplate <class T>\nstatic constexpr int IsSingleObject = _IsSingleObject<std::remove_cv_t<T>>::value;\n\n};  // namespace details\n\ntemplate <class TTraits>\nArray<ObjectRef> UnpackedInstTraits<TTraits>::ApplyToSchedule(const Schedule& sch,\n                                                              const Array<ObjectRef>& inputs,\n                                                              const Array<ObjectRef>& attrs,\n                                                              const Optional<ObjectRef>& decision) {\n  using method_type = decltype(TTraits::UnpackedApplyToSchedule);\n  using return_type = details::ReturnType<method_type>;\n  static_assert(details::ArgumentAreAllObjects<method_type>,\n                \"All arguments to `UnpackedApplyToSchedule` must be subclasses of ObjectRef\");\n  constexpr size_t kNumArgs = details::NumArgs<method_type>;\n  constexpr size_t kNumInputs = TTraits::kNumInputs;\n  constexpr size_t kNumAttrs = TTraits::kNumAttrs;\n  constexpr size_t kNumDecisions = TTraits::kNumDecisions;\n  static_assert(kNumArgs == 1 + kNumInputs + kNumAttrs + kNumDecisions,\n                \"length of argument list mismatch\");\n  TVMValue tvm_values[kNumArgs];\n  int tvm_type_codes[kNumArgs];\n  runtime::TVMArgsSetter setter(tvm_values, tvm_type_codes);\n  setter(0, sch);\n  TTraits::template _SetInputs<1>(setter, inputs);\n  TTraits::template _SetAttrs<1 + kNumInputs>(setter, attrs);\n  TTraits::template _SetDecision<1 + kNumInputs + kNumAttrs>(setter, decision);\n  PackedFunc pf([](const TVMArgs& args, TVMRetValue* rv) -> void {\n    using runtime::detail::unpack_call;\n    constexpr size_t kNumArgs = details::NumArgs<method_type>;\n    ICHECK_EQ(args.size(), kNumArgs);\n    unpack_call<return_type, kNumArgs>(nullptr, TTraits::UnpackedApplyToSchedule, args, rv);\n  });\n  TVMRetValue rv;\n  pf.CallPacked(TVMArgs(tvm_values, tvm_type_codes, kNumArgs), &rv);\n  return TTraits::_ConvertOutputs(rv);\n}\n\ntemplate <class TTraits>\nString UnpackedInstTraits<TTraits>::AsPython(const Array<ObjectRef>& inputs,\n                                             const Array<ObjectRef>& attrs,\n                                             const Optional<ObjectRef>& decision,\n                                             const Array<String>& outputs) {\n  using method_type = decltype(TTraits::UnpackedAsPython);\n  using return_type = details::ReturnType<method_type>;\n  static_assert(details::ArgumentAreAllObjects<method_type>,\n                \"All arguments to `UnpackedAsPython` must be subclasses of ObjectRef\");\n  constexpr size_t kNumArgs = details::NumArgs<method_type>;\n  constexpr size_t kNumInputs = TTraits::kNumInputs;\n  constexpr size_t kNumAttrs = TTraits::kNumAttrs;\n  constexpr size_t kNumDecisions = TTraits::kNumDecisions;\n  static_assert(kNumArgs == 1 + kNumInputs + kNumAttrs + kNumDecisions,\n                \"length of argument list mismatch\");\n  TVMValue tvm_values[kNumArgs];\n  int tvm_type_codes[kNumArgs];\n  runtime::TVMArgsSetter setter(tvm_values, tvm_type_codes);\n  setter(0, outputs);\n  TTraits::template _SetInputs<1>(setter, inputs);\n  TTraits::template _SetAttrs<1 + kNumInputs>(setter, attrs);\n  TTraits::template _SetDecision<1 + kNumInputs + kNumAttrs>(setter, decision);\n  PackedFunc pf([](const TVMArgs& args, TVMRetValue* rv) -> void {\n    using runtime::detail::unpack_call;\n    constexpr size_t kNumArgs = details::NumArgs<method_type>;\n    ICHECK_EQ(args.size(), kNumArgs);\n    unpack_call<return_type, kNumArgs>(nullptr, TTraits::UnpackedAsPython, args, rv);\n  });\n  TVMRetValue rv;\n  pf.CallPacked(TVMArgs(tvm_values, tvm_type_codes, kNumArgs), &rv);\n  String result = rv;\n  return result;\n}\n\ntemplate <class TTraits>\ntemplate <size_t index_offset>\nTVM_ALWAYS_INLINE void UnpackedInstTraits<TTraits>::_SetInputs(const runtime::TVMArgsSetter& setter,\n                                                               const Array<ObjectRef>& inputs) {\n  constexpr size_t kNumInputs = TTraits::kNumInputs;\n  ICHECK_EQ(kNumInputs, inputs.size())\n      << \"ValueError: Incorrect kNumInputs for instruction: \" << TTraits::kName;\n  const ObjectRef* ptr = inputs.template as<ArrayNode>()->begin();\n  for (size_t i = 0; i < kNumInputs; ++i) {\n    setter(i + index_offset, *(ptr + i));\n  }\n}\n\ntemplate <class TTraits>\ntemplate <size_t index_offset>\nTVM_ALWAYS_INLINE void UnpackedInstTraits<TTraits>::_SetAttrs(const runtime::TVMArgsSetter& setter,\n                                                              const Array<ObjectRef>& attrs) {\n  constexpr size_t kNumAttrs = TTraits::kNumAttrs;\n  ICHECK_EQ(kNumAttrs, attrs.size())\n      << \"ValueError: Incorrect kNumAttrs for instruction: \" << TTraits::kName;\n  const ObjectRef* ptr = attrs.as<ArrayNode>()->begin();\n  for (size_t i = 0; i < kNumAttrs; ++i) {\n    setter(i + index_offset, *(ptr + i));\n  }\n}\n\ntemplate <class TTraits>\ntemplate <size_t index_offset>\nTVM_ALWAYS_INLINE void UnpackedInstTraits<TTraits>::_SetDecision(\n    const runtime::TVMArgsSetter& setter, const Optional<ObjectRef>& decision) {\n  constexpr size_t kNumDecisions = TTraits::kNumDecisions;\n  static_assert(kNumDecisions <= 1, \"an instruction is supposed to have at most 1 decision\");\n  if (kNumDecisions == 1) {\n    setter(index_offset, decision);\n  } else {\n    ICHECK(!decision.defined());\n  }\n}\n\ntemplate <class TTraits>\nTVM_ALWAYS_INLINE Array<ObjectRef> UnpackedInstTraits<TTraits>::_ConvertOutputs(\n    const TVMRetValue& rv) {\n  using method_type = decltype(TTraits::UnpackedApplyToSchedule);\n  using return_type = details::ReturnType<method_type>;\n  constexpr int is_array = details::IsTVMArray<return_type>;\n  constexpr int is_single_obj = details::IsSingleObject<return_type>;\n  constexpr int is_void = std::is_void<return_type>::value;\n  static_assert(is_array || is_single_obj || is_void, \"return type not supported\");\n  static_assert(is_array + is_single_obj + is_void == 1, \"internal template error\");\n  if (is_void) {\n    return {};\n  } else if (is_single_obj) {\n    ObjectRef obj = rv;\n    return {obj};\n  } else if (is_array) {\n    ObjectRef obj = rv;\n    const ArrayNode* array = obj.as<ArrayNode>();\n    return GetRef<Array<ObjectRef>>(array);\n  }\n}\n\n/********** PythonAPICall **********/\n\ninline void PythonAPICall::AsPythonString(const ObjectRef& obj, std::ostream& os) {\n  if (!obj.defined()) {\n    os << \"None\";\n  } else if (const auto* str = obj.as<runtime::StringObj>()) {\n    os << str->data;\n  } else if (const auto* int_imm = obj.as<IntImmNode>()) {\n    os << int_imm->value;\n  } else if (const auto* float_imm = obj.as<FloatImmNode>()) {\n    os.precision(17);\n    os << float_imm->value;\n  } else if (const auto* array = obj.as<ArrayNode>()) {\n    os << '[';\n    bool is_first = true;\n    for (const ObjectRef& e : *array) {\n      if (is_first) {\n        is_first = false;\n      } else {\n        os << \", \";\n      }\n      AsPythonString(e, os);\n    }\n    os << ']';\n  } else if (const auto* dict = obj.as<MapNode>()) {\n    os << '{';\n    bool is_first = true;\n    std::vector<std::pair<std::string, std::string>> dict_items;\n    for (auto it = dict->begin(); it != dict->end(); ++it) {\n      std::ostringstream ks;\n      AsPythonString(it->first, ks);\n      std::ostringstream vs;\n      AsPythonString(it->second, vs);\n      dict_items.emplace_back(ks.str(), vs.str());\n    }\n    std::sort(dict_items.begin(), dict_items.end(),\n              [](const auto& p1, const auto& p2) { return p1.first < p2.first; });\n    for (const auto& kv : dict_items) {\n      if (is_first) {\n        is_first = false;\n      } else {\n        os << \", \";\n      }\n      os << '\\\"' << kv.first << \"\\\": \" << kv.second;\n    }\n    os << '}';\n  } else {\n    LOG(FATAL) << \"ValueError: Cannot translate type '\" << obj->GetTypeKey()\n               << \"' to python. Its value is: \" << obj;\n    throw;\n  }\n}\n\nvoid PythonAPICall::Input(String arg_name, int arg) {\n  arg_names_.emplace_back(std::move(arg_name));\n  args_.push_back(std::to_string(arg));\n}\n\nvoid PythonAPICall::Input(String arg_name, int64_t arg) {\n  arg_names_.emplace_back(std::move(arg_name));\n  args_.push_back(std::to_string(arg));\n}\n\nvoid PythonAPICall::Input(String arg_name, bool arg) {\n  static const char* true_str = \"True\";\n  static const char* false_str = \"False\";\n  arg_names_.emplace_back(std::move(arg_name));\n  if (arg) {\n    args_.push_back(true_str);\n  } else {\n    args_.push_back(false_str);\n  }\n}\n\nvoid PythonAPICall::Input(String arg_name, double arg) {\n  arg_names_.emplace_back(std::move(arg_name));\n  std::ostringstream os;\n  os.precision(17);\n  os << arg;\n  args_.push_back(os.str());\n}\n\nvoid PythonAPICall::Input(String arg_name, String arg) {\n  arg_names_.emplace_back(std::move(arg_name));\n  args_.emplace_back(std::move(arg));\n}\n\nvoid PythonAPICall::Input(String arg_name, ObjectRef arg) {\n  arg_names_.emplace_back(std::move(arg_name));\n  std::ostringstream os;\n  AsPythonString(arg, os);\n  args_.push_back(os.str());\n}\n\nvoid PythonAPICall::Decision(ObjectRef decision) {\n  if (decision.defined()) {\n    this->Input(\"decision\", decision);\n  }\n}\n\nvoid PythonAPICall::SingleOutput(Array<String> unit_array) {\n  ICHECK_EQ(unit_array.size(), 1);\n  this->output_ = unit_array[0];\n}\n\nvoid PythonAPICall::OutputList(Array<String> outputs) {\n  if (outputs.empty()) {\n    return;\n  }\n  if (outputs.size() == 1) {\n    this->output_ = outputs[0] + \",\";\n    return;\n  }\n  std::ostringstream os;\n  os << outputs[0];\n  for (int i = 1, n = outputs.size(); i < n; ++i) {\n    os << \", \" << outputs[i];\n  }\n  this->output_ = os.str();\n}\n\nString PythonAPICall::Str() const {\n  std::ostringstream os;\n  if (output_.defined()) {\n    os << output_.value() << \" = \";\n  }\n  os << \"sch.\" << method_name_ << '(';\n  int n = args_.size();\n  for (int i = 0; i < n; ++i) {\n    if (i > 0) {\n      os << \", \";\n    }\n    if (arg_names_[i].empty()) {\n      os << args_[i];\n    } else {\n      os << arg_names_[i] << '=' << args_[i];\n    }\n  }\n  os << ')';\n  return os.str();\n}\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_INSTRUCTION_TRAITS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/ir_comparator.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_IR_COMPARATOR_H_\n#define TVM_TIR_SCHEDULE_IR_COMPARATOR_H_\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"./utils.h\"\n\nnamespace tvm {\nnamespace tir {\n\nusing ExprComparator = ExprFunctor<bool(const PrimExpr& n, const PrimExpr& other)>;\nusing StmtComparator = StmtFunctor<bool(const Stmt& n, const Stmt& other)>;\n\n/*! \\brief Deep comparison to check if two IR ASTs are equivalent for tensorization*/\nclass TensorizeComparator : public ExprComparator, public StmtComparator {\n public:\n  /*!\n   * \\brief Constructor of TensorizeComparator\n   * \\param assert_mode Whether to raise an error if the two IR ASTs do not match.\n   * \\param lhs_mod The IRModule of the LHS. This is used for error reporting.\n   */\n  explicit TensorizeComparator(IRModule lhs_mod, bool assert_mode = true)\n      : lhs_mod_(std::move(lhs_mod)), assert_mode_(assert_mode) {}\n\n  bool VisitExpr(const PrimExpr& n, const PrimExpr& other) override;\n  bool VisitStmt(const Stmt& n, const Stmt& other) override;\n\n  bool VisitStmt_(const ForNode* op, const Stmt& other) override;\n  bool VisitStmt_(const SeqStmtNode* op, const Stmt& other) override;\n  bool VisitStmt_(const BufferStoreNode* op, const Stmt& other) override;\n  bool VisitStmt_(const BlockRealizeNode* op, const Stmt& other) override;\n  bool VisitStmt_(const BlockNode* op, const Stmt& other) override;\n\n  bool VisitExpr_(const AddNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const SubNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const MulNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const DivNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const ModNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const EQNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const NENode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const LTNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const LENode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const GTNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const GENode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const AndNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const OrNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const MinNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const MaxNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const FloorDivNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const FloorModNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const IntImmNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const FloatImmNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const CastNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const VarNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const BufferLoadNode* op, const PrimExpr& other) override;\n  bool VisitExpr_(const SelectNode* op, const PrimExpr& other) override;\n\n  /*! \\brief Map from RHS buffer to LHS buffer */\n  std::unordered_map<Buffer, Buffer, ObjectHash, ObjectEqual> rhs_buffer_map_;\n  /*! \\brief Base indices of the LHS buffer. */\n  std::unordered_map<Buffer, std::vector<PrimExpr>, ObjectPtrHash, ObjectPtrEqual> buffer_indices_;\n\n protected:\n  bool DefEqual(const Var& lhs, const Var& rhs);\n  virtual bool CompareBuffer(const Buffer& lhs, const Buffer& rhs);\n  bool CompareBufferRegion(const BufferRegion& lhs, const BufferRegion& rhs);\n  bool CompareAnnotation(const std::pair<String, ObjectRef>& lhs,\n                         const std::pair<String, ObjectRef>& rhs);\n  bool CompareAnnotationMap(const Map<String, ObjectRef>& lhs, const Map<String, ObjectRef>& rhs);\n  template <typename T>\n  bool CompareBufferAccess(const T* lhs, const T* rhs);\n  template <typename T, typename Self, typename F>\n  bool CompareArray(const Array<T>& lhs, const Array<T>& rhs, F Self::*cmp);\n  bool CompareRange(const Range& lhs, const Range& rhs);\n  bool CompareIterVar(const IterVar& lhs, const IterVar& rhs);\n  void EmitError(const std::string& error_message);\n\n  /*! \\brief IRModule of the LHS stmt. */\n  IRModule lhs_mod_;\n  /*! \\brief Whether assertion mode is enabled. */\n  bool assert_mode_;\n  /*! \\brief Whether it is visiting the scope block (the outermost block). */\n  bool is_scope_block = true;\n  /*! \\brief The arithmetic analyzer. */\n  arith::Analyzer analyzer_;\n  /*! \\brief Additional error messages. Only used when assert_mode is true. */\n  std::vector<std::string> error_messages_;\n  // variable remap if any\n  std::unordered_map<ObjectRef, ObjectRef, ObjectPtrHash, ObjectPtrEqual> equal_map_;\n};\n\n/*!\n * \\brief IR comparator for auto tensorization.\n * This comparator is used to extract correspondence between the IR of the workload (LHS) and the\n * tensor intrin (RHS). Unlike `TensorizeComparator`, this comparator has relaxed requirements\n * during comparison. It ignores the loop structure (number of loops and their extents) and buffer\n * indices. It only requires the LHS and the RHS to have the same arithmetic operations and the same\n * dtype. With such relaxed requirements, workloads that can only match the tensor intrin after\n * certain transformations (e.g. im2col for conv2d) are allowed for auto tensorization.\n */\nclass AutoTensorizeComparator : public TensorizeComparator {\n public:\n  explicit AutoTensorizeComparator(const IRModule& lhs_mod)\n      : TensorizeComparator(lhs_mod, /* assert_mode=*/false) {}\n\n private:\n  bool VisitExprDefault_(const Object* op, const PrimExpr& other) override;\n  bool VisitStmtDefault_(const Object* op, const Stmt& other) override;\n\n  bool VisitStmt_(const BlockNode* op, const Stmt& other) override;\n  bool VisitStmt_(const BufferStoreNode* op, const Stmt& other) override;\n\n  bool VisitExpr_(const BufferLoadNode* op, const PrimExpr& other) override;\n\n  bool CompareBuffer(const Buffer& lhs, const Buffer& rhs) override;\n  template <typename T>\n  bool CompareBufferAccess(const T* lhs, const T* rhs);\n\n public:\n  // Additional information extracted from LHS (the workload) and RHS (the tensor intrin).\n\n  /*! \\brief Block iters in the LHS stmt. */\n  std::vector<IterVar> lhs_iters_;\n  /*! \\brief Block iters in the RHS stmt. */\n  std::vector<IterVar> rhs_iters_;\n  /*! \\brief The buffer and its access indices in the LHS stmt. */\n  std::unordered_map<Buffer, Array<PrimExpr>, ObjectPtrHash, ObjectPtrEqual>\n      lhs_buffer_indices_map_;\n  /*! \\brief The buffer and its access indices in the RHS stmt. */\n  std::unordered_map<Buffer, Array<PrimExpr>, ObjectPtrHash, ObjectPtrEqual>\n      rhs_buffer_indices_map_;\n  /*! \\brief Map from LHS buffer to RHS buffer */\n  std::unordered_map<Buffer, Buffer, ObjectHash, ObjectEqual> lhs_buffer_map_;\n\n private:\n  /*! \\brief The domain of the inner block iters. */\n  Map<Var, arith::IntSet> inner_iter_dom_map_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_IR_COMPARATOR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/primitive.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_PRIMITIVE_H_\n#define TVM_TIR_SCHEDULE_PRIMITIVE_H_\n\n#include <tvm/support/random_engine.h>\n#include <tvm/tir/schedule/state.h>\n\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\n/******** Schedule: Sampling ********/\n/*!\n * \\brief Sample a random integer from a given range.\n * \\param rand_state The pointer to schedule's random state.\n * \\param min_inclusive The minimum value of the range, inclusive.\n * \\param max_exclusive The maximum value of the range, exclusive.\n * \\return The random integer sampled in the given range.\n */\nTVM_DLL int32_t SampleInt(support::LinearCongruentialEngine::TRandState* rand_state,\n                          int32_t min_inclusive, int32_t max_exclusive);\n/*!\n * \\brief Sample k random integers from given range without replacement, i.e, no duplication.\n * \\param rand_state The pointer to schedule's random state\n * \\param n The range is defined as 0 to n-1.\n * \\param k The total number of samples.\n * \\return The randomly selected samples from the n candidates.\n */\nstd::vector<int32_t> SampleWithoutReplacement(\n    support::LinearCongruentialEngine::TRandState* rand_state, int32_t n, int32_t k);\n/*!\n * \\brief Sample once category from candidates according to the probability weights.\n * \\param rand_state The pointer to schedule's random state\n * \\param candidates The candidates\n * \\param probs The probability distribution of the candidates\n * \\param decision The sampling decision, if any\n * \\return The random variable sampled from candidates\n */\nTVM_DLL int64_t SampleCategorical(support::LinearCongruentialEngine::TRandState* rand_state,\n                                  const Array<Integer>& candidates, const Array<FloatImm>& probs,\n                                  Optional<Integer>* decision);\n/*!\n * \\brief Create a sampling function that does multinomial sampling.\n * \\param rand_state The random state.\n * \\param weights The weights for multinomial sampling.\n * \\return The multinomial sampling function.\n */\nTVM_DLL std::function<int32_t()> MakeMultinomialSampler(\n    support::LinearCongruentialEngine::TRandState* rand_state, const std::vector<double>& weights);\n/*!\n * \\brief Sample the factors to perfect tile a specific loop\n * \\param rand_state The random state\n * \\param extent The loop extent to be tiled\n * \\param n_split The number of tiles to be sampled\n * \\return A list of length `n`, the random perfect tile sizes sampled\n */\nTVM_DLL std::vector<int64_t> SamplePerfectTile(\n    support::LinearCongruentialEngine::TRandState* rand_state,  //\n    int32_t extent, int32_t n_splits);\n/*!\n * \\brief Sample the factors to perfect tile a specific loop\n * \\param rand_state The random state\n * \\param extent The loop extent to be tiled\n * \\param n_split The number of tiles to be sampled\n * \\param max_innermost_factor The maximum tile size allowed to be sampled in the innermost loop\n * \\return A list of length `n`, the random perfect tile sizes sampled\n */\nTVM_DLL std::vector<int64_t> SamplePerfectTile(\n    support::LinearCongruentialEngine::TRandState* rand_state,  //\n    int32_t extent, int32_t n_split, int32_t max_innermost_factor);\n/*!\n * \\brief Sample the factors to perfect tile a specific loop\n * \\param rand_state The random state\n * \\param loop_sref The loop to be tiled\n * \\param n_split The number of tiles to be sampled\n * \\param max_innermost_factor The maximum tile size allowed to be sampled in the innermost loop\n * \\param decision The sampling decision\n * \\return A list of length `n`, the random perfect tile sizes sampled\n */\nTVM_DLL std::vector<int64_t> SamplePerfectTile(\n    support::LinearCongruentialEngine::TRandState* rand_state,  //\n    const tir::StmtSRef& loop_sref, int32_t n_split, int32_t max_innermost_factor,\n    Optional<Array<Integer>>* decision);\n/*!\n * \\brief Sample a compute-at location of the given block\n * \\param self The schedule state\n * \\param rand_state The random state\n * \\param block_sref The sref of the block whose compute-at location is to be sampled\n * \\param decision The sampling decision\n * \\return The sampled loop where the input block is to be computed at\n */\nTVM_DLL tir::StmtSRef SampleComputeLocation(\n    tir::ScheduleState self, support::LinearCongruentialEngine::TRandState* rand_state,\n    const tir::StmtSRef& block_sref, Optional<Integer>* decision);\n\n/******** Schedule: Get blocks & loops ********/\n/*!\n * \\brief Retrieves blocks in a specific function with its name\n * \\param self The schedule state\n * \\param name The name of the blocks to be retrieved\n * \\param gvar The function to be retrieved\n * \\return A list of blocks with the specific name\n */\nArray<StmtSRef> GetBlocks(const ScheduleState& self, const String& name, const GlobalVar& gv);\n/*!\n * \\brief Gets the parent loops of the block in its scope, from outer to inner\n * \\param self The schedule state\n * \\param block_sref The query block\n * \\return A list of loops above the given block in its scope, from outer to inner\n */\nArray<StmtSRef> GetLoops(const StmtSRef& block_sref);\n/*!\n * \\brief Get the leaf blocks of a specific block/loop\n * \\param self The schedule state\n * \\param parent_sref The query block/loop\n * \\return A list of leaf blocks inside a specific block/loop\n */\nArray<StmtSRef> GetChildBlocks(const ScheduleState& self, const StmtSRef& parent_sref);\n/*!\n * \\brief Get the producers of a specific block\n * \\param self The schedule state\n * \\param block_sref The block in the query\n * \\return A list of blocks, the producers of the given block\n */\nArray<StmtSRef> GetProducers(const ScheduleState& self, const StmtSRef& block_sref);\n/*!\n * \\brief Get the consumers of a specific block\n * \\param self The schedule state\n * \\param block_rv The block in the query\n * \\return A list of blocks, the consumers of the given block\n */\nArray<StmtSRef> GetConsumers(const ScheduleState& self, const StmtSRef& block_sref);\n/******** Schedule: Transform loops ********/\n/*!\n * Split a loop into a list of consecutive loops. It requires:\n * 1) The loop can't have annotation or thread binding.\n * 2) The loop must start with 0.\n * \\param self The state of the schedule\n * \\param loop_sref The sref to the loop being split\n * \\param factors The splitting factors\n * \\param preserve_unit_iters Whether or not to preserve unit iterators in block bindings\n * \\return An array of srefs to the loops after splitting\n */\nTVM_DLL Array<StmtSRef> Split(ScheduleState self, const StmtSRef& loop_sref,\n                              const Array<PrimExpr>& factors, bool preserve_unit_iters);\n/*!\n * \\brief Fuse a list of consecutive loops into one. It requires:\n * 1) The loops can't have annotations or thread bindings.\n * 2) The inner loop must be the only child of the outer loop.\n * 3) All loops must start with 0.\n * 4) The domain of a loop to be fused cannot depend on another loop to be fused.\n * \\param self The state of the schedule\n * \\param loop_srefs An array of srefs to the loops to be fused\n * \\param preserve_unit_iters Whether or not to preserve unit iterators in block bindings\n * \\return The sref to the fused loop\n */\nTVM_DLL StmtSRef Fuse(ScheduleState self, const Array<StmtSRef>& loop_srefs,\n                      bool preserve_unit_loops);\n/*!\n * \\brief Reorder a list of loops. It doesn't require the loops to be consecutive.\n * It requires:\n * 1) The loops are in the same chain. That means: the loops can be ordered to [l_1, l_2, ... ,\n *     l_n] where l_i is an ancestor of l_{i+1} and there are only single-branch loops between\n *     l_1 and l_n (which also indicates they are under the same scope).\n * 2) After reordering, the domain of an outer loop cannot depend on any of the inner loops.\n * 3) For every block under the loop nests, its block binding must be affine, and the block\n *    variables must be either data parallel or reduction.\n * 4) No duplicated loops are allowed in the arguments.\n * \\param self The state of the schedule\n * \\param ordered_loop_srefs An array of srefs which indicates the new order of loops\n */\nTVM_DLL void Reorder(ScheduleState self, const Array<StmtSRef>& ordered_loop_srefs);\n\n/*!\n * \\brief Create a new unit loop on top of the specific block or loop.\n * \\param sref The block/loop above which the new thread_binding loop is created\n * \\param extent The extent of the new thread_binding loop\n * \\param thread_axis The thread axis of the new thread_binding loop\n * \\param attrs Extra loop attributes\n * \\return The new thread_binding loop\n */\nTVM_DLL StmtSRef AddUnitLoop(ScheduleState self, StmtSRef sref);\n\n/******** Schedule: Manipulate ForKind ********/\n/*!\n * \\brief Parallelize the input loop. It requires:\n * 1) The scope block that the loop is in should have stage-pipeline property\n * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n * bindings\n * 3) For each block under the loop, the loop can only be contained in data-parallel block iters'\n * bindings\n * \\param self The state of the schedule\n * \\param loop_sref The sref of the loop to be parallelized\n */\nTVM_DLL void Parallel(ScheduleState self, const StmtSRef& loop_sref);\n/*!\n * \\brief Vectorize the input loop. It requires:\n * 1) The scope block that the loop is in should have stage-pipeline property\n * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n * bindings\n * 3) For each block under the loop, the loop can only be contained in data-parallel block iters'\n * bindings\n * \\param self The state of the schedule\n * \\param loop_sref The sref of the loop to be vectorized\n */\nTVM_DLL void Vectorize(ScheduleState self, const StmtSRef& loop_sref);\n/*!\n * \\brief Bind the input loop to the given thread axis. It requires:\n * 1) The scope block that the loop is in should have stage-pipeline property\n * 2) All the blocks under the loop are complete blocks or reduction blocks, and have affine\n * bindings\n * 3) For each block under the loop, if the thread axis starts with \"threadIdx`, the loop can only\n * be contained in data-parallel block iter and reduction block iters' bindings. Otherwise the\n * loop can only be contained in data-parallel block iters' bindings\n * \\param self The state of the schedule\n * \\param loop_sref The sref of the loop to be bound to the thread axis\n * \\param thread_axis The thread axis to be bound to the loop\n */\nTVM_DLL void Bind(ScheduleState self, const StmtSRef& loop_sref, const IterVar& thread_axis);\n/*!\n * \\brief Unroll the input loop. It requires nothing\n * \\param self The state of the schedule\n * \\param loop_sref The loop to be unrolled\n */\nTVM_DLL void Unroll(ScheduleState self, const StmtSRef& loop_sref);\n/******** Schedule: Insert cache stages ********/\n/*!\n * \\brief Create a block that reads a buffer region into a read cache. It requires:\n * 1) There is at most one block who writes the buffer in the scope.\n * 2) The scope block have stage-pipeline property.\n * \\param self The state of the schedule\n * \\param block_sref The consumer block of the target buffer.\n * \\param read_buffer_index The index of the buffer in block's read region.\n * \\param storage_scope The target storage scope.\n * \\param consumer_blocks Array of blocks that consume the cache.\n * \\return The cache stage block.\n */\nTVM_DLL StmtSRef CacheRead(ScheduleState self, const StmtSRef& block_sref, int read_buffer_index,\n                           const String& storage_scope, const Array<StmtSRef> consumer_blocks = {});\n/*!\n * \\brief Create a block that writes a buffer region into a write cache. It requires:\n * 1) There is only one block that writes the target buffer.\n * 2) The scope block have stage-pipeline property.\n * \\param self The state of the schedule\n * \\param block_sref The producer of the buffer\n * \\param write_buffer_index The index of the buffer in block's write region\n * \\param storage_scope The target storage scope\n * \\return The cache stage block.\n */\nTVM_DLL StmtSRef CacheWrite(ScheduleState self, const StmtSRef& block_sref, int write_buffer_index,\n                            const String& storage_scope);\n/*!\n *!\n * \\brief Create 2 blocks that read&write a buffer region into a read/write cache.\n * It requires the the target block both read & write the target buffer.\n * \\param self The state of the schedule\n * \\param block_sref The target block operates on the target buffer.\n * \\param read_buffer_index The index of the buffer in block's read region.\n * \\param storage_scope The target storage scope\n * \\return The cache stage blocks, cache read block together with cache write block.\n */\nTVM_DLL Array<StmtSRef> CacheInplace(ScheduleState self, const StmtSRef& block_sref,\n                                     int read_buffer_index, const String& storage_scope);\n/*!\n * \\brief Create a block to cache precomputed index for later use.\n * if there is no index computation, keep unchanged.\n * \\param block_sref The target block\n * \\param buffer_index The index of the target buffer in block's read region,\n * \\return The cache stage block.\n */\nTVM_DLL Array<StmtSRef> CacheIndex(ScheduleState self, const StmtSRef& block_sref,\n                                   int buffer_index);\n/*!\n *!\n * \\brief Create a block that read/write a buffer region into a read/write cache with reindexing.\n * The layout of the cache will be the same as by the iterators of the block that reads/writes the\n * buffer. It requires:\n * 1) There is only one block who reads/writes the target buffer\n * 2) There is only one buffer load/store of this buffer in the block\n * \\param self The state of the schedule\n * \\param block_sref The block operates on the target buffer.\n * \\param buffer_index The index of the buffer in block's read or write region.\n * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n * \\return The reindex stage block.\n */\nTVM_DLL StmtSRef ReIndex(ScheduleState self, const StmtSRef& block_sref, int buffer_index,\n                         BufferIndexType buffer_index_type);\n/******** Schedule: Compute location ********/\n/*!\n * \\brief Move a producer block under the specific loop, and regenerate the\n * loops induced by the block so that the buffer region produced by the producer block could\n * cover those regions consumed by its consumer blocks under the given loop. It requires:\n * 1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n * 2) The scope block has stage-pipeline property\n * 3) The subtree of the scope block, where the given block is in, satisfies the compact dataflow\n * condition. i.e. all the blocks in the scope block's subtree must be either complete block or\n * reduction block\n * 4) The block is not an output block with regard to the scope block, i.e. the buffers written by\n * the block are allocated under the scope block\n * 5) All the consumers of the block are under the given loop\n *\n * \\param self The schedule state\n * \\param block_sref The block to be moved\n * \\param loop_sref The loop where the block to be moved to\n * \\param index The block index of the loop body subtree blocks:\n * - `index = -1` means inserted into the last possible insertion point;\n * - `index = -2` means inserted into the first possible insertion point;\n * - Otherwise, `index` is a nonnegative number that indicates the insertion point\n */\nTVM_DLL void ComputeAt(ScheduleState self, const StmtSRef& block_sref, const StmtSRef& loop_sref,\n                       bool preserve_unit_loops, int index = -1);\n/*!\n * \\brief Move a consumer block under the specific loop, and regenerate the\n * loops induced by the block so that the buffer region consumed by the consumer block could\n * cover those regions produced by its producer blocks under the given loop. It requires:\n * 1) `block` and `loop` are under the same scope, `loop` is not the ancestor of `block`\n * 2) The scope block has stage-pipeline property\n * 3) The subtree of the scope block, where the given block is in, satisfies the compact dataflow\n * condition. i.e. all the blocks in the scope block's subtree must be either complete block or\n * reduction block\n * 4) All the producers of the block are under the given loop\n *\n * \\param self The schedule state\n * \\param block_sref The block to be moved\n * \\param loop_sref The loop where the block to be moved to\n * \\param preserve_unit_loops Whether to keep the trivial loops whose extents are 1\n * \\param index The block index of the loop body subtree blocks:\n * - `index = -1` means inserted into the last possible insertion point;\n * - `index = -2` means inserted into the first possible insertion point;\n * - Otherwise, `index` is a nonnegative number that indicates the insertion point\n */\nTVM_DLL void ReverseComputeAt(ScheduleState self, const StmtSRef& block_sref,\n                              const StmtSRef& loop_sref, bool preserve_unit_loops, int index = -1);\n/*!\n * \\brief Inline a block into its consumer(s). It requires:\n * 1) The block is a complete non-root block, which only produces one buffer\n * 2) The block must not be the only leaf in the scope.\n * 3) The body of the block must be a BufferStore statement in the form of,\n *    A[i, j, k, ...] = ...\n * where the indices of the LHS are all distinct atomic variables,\n * and no variables other than those indexing variables are allowed in the statement.\n * \\param self The state of the schedule\n * \\param block_sref The sref to the block to be inlined to its consumer(s)\n */\nTVM_DLL void ComputeInline(ScheduleState self, const StmtSRef& block_sref);\n/*!\n * \\brief Inline a block into its only producer. It requires:\n * 1) The block is a complete non-root block, which only produces and consumers one buffer\n * 2) The block must not be the only leaf in the scope.\n * 3) The only producer of the block is a read-after-write producer and a complete non-root block\n * 4) The body of the block must be a BufferStore statement in the form of,\n *    B[f(i, j, k, ...)] = g(i, j, k, A[i, j, k, ...] ...)\n * where the indices of each `BufferLoad` on the RHS are all distinct atomic variables,\n * and no variables other than those indexing variables are allowed in the statement.\n * \\param self The state of the schedule\n * \\param block_sref The sref to the block to be inlined to its producer\n */\nTVM_DLL void ReverseComputeInline(ScheduleState self, const StmtSRef& block_sref);\n/******** Schedule: Reduction ********/\n/*!\n * \\brief Decompose a reduction block into two separate blocks.\n * a) The init block, which is translated from the init statement of the reduction block;\n * b) The update block, which is the original block without init statement.\n *\n * The init block is inserted right before the given loop.\n *\n * The schedule primitive requires:\n * 1) The input block is a reduction block.\n * 2) The input loop is the ancestor of the block.\n * 3) The input loop is not lower than all the loops related to reduce block var.\n * \\param block_rv The reduction block to be decomposed\n * \\param loop_rv The loop above which the init block is inserted before.\n * \\return The init block\n */\nTVM_DLL StmtSRef DecomposeReduction(ScheduleState self, const StmtSRef& block_sref,\n                                    const StmtSRef& loop_sref);\n/*!\n * \\brief Factor a reduction block by the specified loop\n * \\details See python/tvm/tir/schedule/schedule.py\n * \\param self The state of the schedule\n * \\param loop_sref The loop outside block for which we want to do rfactor\n * \\param factor_axis The position where the new dimension is placed in the new introduced rfactor\n *                    buffer. Suppose the original reduction block writes to buffer `B` with\n *                    ndim(B) dimensions, then `factor_axis` should be in range `[-ndim(B) - 1,\n *                    ndim(B)]`, and the negative index will be normalized to a non-negative one\n * \\return The sref of the rfactor block\n */\nTVM_DLL StmtSRef RFactor(ScheduleState self, const StmtSRef& loop_sref, int factor_axis);\n/******** Schedule: Block annotation ********/\n/*! \\brief The quad used by StorageAlign for (buffer_idx, axis, factor, offset) */\nusing StorageAlignTuple = Array<Integer>;\n/*! \\brief A list of StorageAlignTuple, used by StorageAlign */\nusing StorageAlignAnnotation = Array<StorageAlignTuple>;\n/*!\n * \\brief Set alignment requirement for specific dimension such that\n *        stride[axis] == k * factor + offset for some k. This is useful to set memory layout for\n *        more friendly memory access pattern. For example, we can set alignment to be factor=2,\n *        offset=1 to avoid bank conflict for thread access on higher dimension in GPU shared\n *        memory.\n * \\param self The state of the schedule\n * \\param block_sref The producer block of the buffer\n * \\param buffer_index The index of the buffer in block's write region\n * \\param axis The dimension to be specified for alignment\n * \\param factor The factor multiple of alignment\n * \\param offset The required offset factor\n */\nTVM_DLL void StorageAlign(ScheduleState self, const StmtSRef& block_sref, int buffer_index,\n                          int axis, int factor, int offset);\n/*!\n * \\brief Set the storage scope of a buffer, where the buffer is specified by the a block and a\n * write-index\n * \\param self The state of the schedule\n * \\param block_sref The sref of the producer block of the buffer\n * \\param buffer_index The index of the buffer in block's write region\n * \\param storage_scope The storage scope to be set\n */\nTVM_DLL void SetScope(ScheduleState self, const StmtSRef& block_sref, int buffer_index,\n                      const String& storage_scope);\n/*!\n * \\brief Set the axis separator of a buffer, where the buffer is specified by a block and a read\n * or write index\n * \\param block_rv The block that accesses the target buffer.\n * \\param buffer_index The index of the buffer in block's read or write region.\n * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n * \\param axis_separators The axis separator of the buffer\n */\nTVM_DLL void SetAxisSeparator(ScheduleState self, const StmtSRef& block_sref, int buffer_index,\n                              BufferIndexType buffer_index_type,\n                              const Array<IntImm>& axis_separators);\n\n/******** Schedule: Blockize & Tensorize ********/\n\n/*!\n * \\brief Convert the subtree rooted at a specific loop into a block.\n * \\param self The state of the schedule\n * \\param loop_sref The root of the subtree\n * \\return The new block\n */\nTVM_DLL StmtSRef Blockize(ScheduleState self, const StmtSRef& loop_sref);\n\n/*!\n * \\brief Tensorize the computation enclosed by loop with the tensor intrinsic.\n * \\param self The state of the schedule\n * \\param block_or_loop_sref The block or loop to be tensorized.\n * \\param intrin The tensor intrinsic.\n */\nTVM_DLL void Tensorize(ScheduleState self, const StmtSRef& block_or_loop_sref,\n                       const TensorIntrin& intrin);\n\n/******** Schedule: Annotation ********/\n/*!\n * \\brief Annotate a block/loop with a key value pair\n * \\param self The state of the schedule\n * \\param sref The block/loop sref to be annotated\n * \\param ann_key The annotation key\n * \\param ann_val The annotation value\n */\nTVM_DLL void Annotate(ScheduleState self, const StmtSRef& sref, const String& ann_key,\n                      const ObjectRef& ann_val);\n/*!\n * \\brief Unannotate a block/loop's annotation with key ann_key\n * \\param self The state of the schedule\n * \\param sref The block/loop to be unannotated\n * \\param ann_key The annotation key\n */\nTVM_DLL void Unannotate(ScheduleState self, const StmtSRef& sref, const String& ann_key);\n\n/******** Schedule: Layout transformation ********/\n/*!\n * \\brief Apply a transformation represented by IndexMap to buffer\n * \\details The indices and the access region to the target buffer is transformed by the given\n * index_map. The index_map is also used to infer the new shape of the buffer. Buffer must be\n * one of the parameter of the function, or allocated in some blocks (it cannot be a buffer\n * subregion created via match_buffer).\n * \\param self The state of the schedule\n * \\param block_sref The block sref that accesses the target buffer.\n * \\param buffer_index The index of the buffer in block's read or write region.\n * \\param buffer_index_type The type of the buffer index, kRead or kWrite.\n * \\param index_map The transformation to apply.\n * \\param pad_value The value to write into padding introduced by the transformation.\n */\nTVM_DLL void TransformLayout(ScheduleState self, const StmtSRef& block_sref, int buffer_index,\n                             BufferIndexType buffer_index_type, const IndexMap& index_map,\n                             const Optional<IndexMap>& pad_value);\n\n/*!\n * \\brief Apply a transformation represented by IndexMap to block\n * \\details The block iters and the block body are transformed by the given index_map.\n * Outer loops corresponding to each new block iter are regenerated.\n * The index_map is required to be bijective affine since we need its inverse mapping.\n * \\param self The state of the schedule\n * \\param block_sref The block sref that refers to the block to be transformed\n * \\param index_map The transformation to apply.\n */\nTVM_DLL void TransformBlockLayout(ScheduleState self, const StmtSRef& block_sref,\n                                  const IndexMap& index_map);\n\n/******** Schedule: Padding ********/\n/*!\n * \\brief Decompose a padding block into a block filling const pad values and a block\n * writing in-bound values.\n * \\param block_sref The block sref that match the padding pattern.\n * \\param loop_sref The loop above which the const filling block is inserted before.\n * \\return The padding value filling block sref.\n */\nTVM_DLL StmtSRef DecomposePadding(ScheduleState self, const StmtSRef& block_sref,\n                                  const StmtSRef& loop_sref);\n\n/*!\n * \\brief Pad the computation of Einsum.\n * \\param self The state of the schedule\n * \\param block_sref The block sref that matches the Einsum pattern.\n * \\param padding The padding for each block iter.\n */\nTVM_DLL void PadEinsum(ScheduleState self, const StmtSRef& block_sref,\n                       const Array<Integer>& padding);\n\n/******** Schedule: Buffer transformation ********/\n/*!\n * \\brief Compute the target buffer via rolling buffering.\n * \\details This primitive selects the outermost rollable axis with a positive bound overlap that\n * appears in the block's ancestor loops as `rolling axis`, fold and circularize the buffer along\n * the rolling dimension, append block predicate to avoid recomputing overlapping elements.\n * It requires:\n * 1) The buffer to be an intermediate buffer defined via `alloc_buffer`.\n * 2) The LCA of the producer and consumer of the buffer is a for loop, typically,\n *    the producer and consumer of the buffer are cascaded through compute_at.\n * 3) The access region of the buffer has at least one dimension that contains\n *    a positive bound overlap.\n * \\param block_rv The producer block of the buffer.\n * \\param write_buffer_index The index of the buffer in block's write region.\n */\nTVM_DLL void RollingBuffer(ScheduleState self, const StmtSRef& block_sref, int write_buffer_index);\n/******** Schedule: Misc ********/\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_PRIMITIVE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/traced_schedule.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_TRACED_SCHEDULE_H_\n#define TVM_TIR_SCHEDULE_TRACED_SCHEDULE_H_\n\n#include \"./concrete_schedule.h\"\n\nnamespace tvm {\nnamespace tir {\n\nclass TracedScheduleNode : public ConcreteScheduleNode {\n  friend class Schedule;\n\n protected:\n  Trace trace_;\n\n public:\n  void VisitAttrs(tvm::AttrVisitor* v) {\n    // `state_` is not visited\n    // `error_render_level_` is not visited\n    // `symbol_table_` is not visited\n    // `analyzer_` is not visitied\n    // `trace_` is not visited\n  }\n\n  ~TracedScheduleNode() = default;\n\n public:\n  Optional<Trace> trace() const final { return trace_; }\n  Schedule Copy() final;\n\n public:\n  /******** Schedule: Sampling ********/\n  ExprRV SampleCategorical(const Array<Integer>& candidates, const Array<FloatImm>& probs,\n                           Optional<Integer> decision = NullOpt) final;\n  Array<ExprRV> SamplePerfectTile(const LoopRV& loop_rv, int n, int max_innermost_factor,\n                                  Optional<Array<Integer>> decision = NullOpt) final;\n  LoopRV SampleComputeLocation(const BlockRV& block_rv, Optional<Integer> decision = NullOpt) final;\n  /******** Schedule: Get blocks & loops ********/\n  BlockRV GetBlock(const String& name, const Optional<String>& func_name) final;\n  Array<LoopRV> GetLoops(const BlockRV& block_rv) final;\n  Array<BlockRV> GetChildBlocks(const BlockRV& block_rv) final;\n  Array<BlockRV> GetChildBlocks(const LoopRV& loop_rv) final;\n  Array<BlockRV> GetProducers(const BlockRV& block_rv) final;\n  Array<BlockRV> GetConsumers(const BlockRV& block_rv) final;\n  /******** Schedule: Transform loops ********/\n  LoopRV Fuse(const Array<LoopRV>& loop_rvs, bool preserve_unit_iters) final;\n  Array<LoopRV> Split(const LoopRV& loop_rv, const Array<Optional<ExprRV>>& factor_rvs,\n                      bool preserve_unit_iters) final;\n  void Reorder(const Array<LoopRV>& ordered_loop_rvs) final;\n  LoopRV AddUnitLoop(const BlockRV& block_rv) final;\n  LoopRV AddUnitLoop(const LoopRV& loop_rv) final;\n  /******** Schedule: Manipulate ForKind ********/\n  void Parallel(const LoopRV& loop_rv) final;\n  void Vectorize(const LoopRV& loop_rv) final;\n  void Bind(const LoopRV& loop_rv, const String& thread_axis) final;\n  void Unroll(const LoopRV& loop_rv) final;\n  /******** Schedule: Insert cache stages ********/\n  BlockRV CacheRead(const BlockRV& block_rv, int read_buffer_index, const String& storage_scope,\n                    const Array<BlockRV> consumer_blocks = {}) final;\n  BlockRV CacheWrite(const BlockRV& block_rv, int write_buffer_index,\n                     const String& storage_scope) final;\n  Array<BlockRV> CacheInplace(const BlockRV& block_rv, int read_buffer_index,\n                              const String& storage_scope) final;\n  BlockRV ReIndex(const BlockRV& block_rv, int buffer_index,\n                  BufferIndexType buffer_index_type) final;\n  Array<BlockRV> CacheIndex(const BlockRV& block_rv, int buffer_index) final;\n  /******** Schedule: Compute location ********/\n  void ComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv, bool preserve_unit_loops,\n                 int index = -1) final;\n  void ReverseComputeAt(const BlockRV& block_rv, const LoopRV& loop_rv, bool preserve_unit_loops,\n                        int index = -1) final;\n  void ComputeInline(const BlockRV& block_rv) final;\n  void ReverseComputeInline(const BlockRV& block_rv) final;\n  /******** Schedule: Reduction ********/\n  BlockRV DecomposeReduction(const BlockRV& block_rv, const LoopRV& loop_rv) final;\n  BlockRV RFactor(const LoopRV& loop_rv, int factor_axis) final;\n  /******** Schedule: Block annotation ********/\n  void StorageAlign(const BlockRV& block_rv, int buffer_index, int axis, int factor,\n                    int offset) final;\n  void SetScope(const BlockRV& block_rv, int buffer_index, const String& storage_scope) final;\n  /******** Schedule: Blockize & Tensorize ********/\n  BlockRV Blockize(const LoopRV& loop_rv) final;\n  void Tensorize(const BlockRV& block_rv, const String& intrin) final;\n  void Tensorize(const LoopRV& loop_rv, const String& intrin) final;\n  /******** Schedule: Annotation ********/\n  void Annotate(const LoopRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) override;\n  void Unannotate(const LoopRV& loop_rv, const String& ann_key) override;\n  void Annotate(const BlockRV& block_rv, const String& ann_key, const ObjectRef& ann_val) override;\n  void Unannotate(const BlockRV& block_rv, const String& ann_key) override;\n  /******** Schedule: Layout transformation ********/\n  void TransformLayout(const BlockRV& block_rv, int buffer_index, BufferIndexType buffer_index_type,\n                       const IndexMap& index_map, const Optional<IndexMap>& pad_value) override;\n  void TransformBlockLayout(const BlockRV& block_rv, const IndexMap& index_map) override;\n  void SetAxisSeparator(const BlockRV& block_rv, int buffer_index,\n                        BufferIndexType buffer_index_type,\n                        const Array<IntImm>& axis_separators) final;\n  /******** Schedule: Padding ********/\n  BlockRV DecomposePadding(const BlockRV& block_rv, const LoopRV& loop_rv) final;\n  void PadEinsum(const BlockRV& block_rv, const Array<Integer>& padding) final;\n  /******** Schedule: Buffer transformation ********/\n  void RollingBuffer(const BlockRV& block_rv, int write_buffer_index) final;\n  /******** Schedule: Misc ********/\n  void EnterPostproc() final;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_TRACED_SCHEDULE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/transform.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_TRANSFORM_H_\n#define TVM_TIR_SCHEDULE_TRANSFORM_H_\n\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/state.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <unordered_map>\n#include <utility>\n\n#include \"../../arith/ir_mutator_with_analyzer.h\"\n#include \"../ir/functor_common.h\"\n\nnamespace tvm {\nnamespace tir {\n\n/******** Annotation ********/\n\n/*!\n * \\brief Create a new block with the given annotation added\n * \\param block The block with original annotation\n * \\param attr_key The annotation key to be added\n * \\param attr_value The annotation value to be added\n * \\return A new block with the given annotation as its last annotation\n */\nBlock WithAnnotation(const BlockNode* block, const String& attr_key, const ObjectRef& attr_value);\n\n/******** Buffer Related ********/\n\n/*!\n * \\brief Create a new buffer by changing the storage scope.\n * \\param buffer The given buffer.\n * \\param scope The target storage scope.\n * \\return The new buffer with target storage scope.\n */\nBuffer WithScope(const Buffer& buffer, const String& scope);\n\n/*!\n * \\brief Replaces the buffer within the specific sequence of regions\n * \\param regions The regions whose buffers are to be replaced\n * \\param source The buffer to be replaced\n * \\param target The buffer to be replaced to\n * \\return The new sequence of regions after replacement\n */\nArray<BufferRegion> ReplaceBuffer(Array<BufferRegion> regions, const Buffer& source,\n                                  const Buffer& target);\n\n/*!\n * \\brief Replaces the buffer within the specific sequence of match_buffers\n * \\param match_buffers The match_buffers whose buffers are to be replaced\n * \\param source The buffer to be replaced\n * \\param target The buffer to be replaced to\n * \\return The new sequence of match_buffers after replacement\n */\nArray<MatchBufferRegion> ReplaceBuffer(Array<MatchBufferRegion> match_buffers, const Buffer& source,\n                                       const Buffer& target);\n\n/*!\n * \\brief Replaces the buffer region within the specific sequence of regions\n * \\param regions The regions to be replaced\n * \\param source_buffer The buffer to whose region is to be replaced\n * \\param target The buffer region to be replaced to\n * \\return The new sequence of regions after replacement\n */\nArray<BufferRegion> ReplaceBufferRegion(Array<BufferRegion> regions, const Buffer& source_buffer,\n                                        const BufferRegion& target);\n\n/*!\n * \\brief Replaces the buffer region within the specific sequence of match_buffers\n * \\param regions The match_buffers to be replaced\n * \\param source_buffer The buffer to whose region is to be replaced\n * \\param target The buffer region to be replaced to\n * \\return The new sequence of match_buffers after replacement\n */\nArray<MatchBufferRegion> ReplaceBufferRegion(Array<MatchBufferRegion> match_buffers,\n                                             const Buffer& source_buffer,\n                                             const BufferRegion& target);\n\n/*!\n * \\brief A helper mutator which recursively replaces the old buffer with the new buffer and\n * collects the block sref reuse information for the following replacement.\n *\n * If the buffer to be replaced in used as the source in `match_buffers`, depending the specific\n * use cases, the target buffers in `match_buffers` may also need to be mutated. In this\n * case, this class should be subclassed to explicitly handle `match_buffers`.\n */\nclass ReplaceBufferMutator : public StmtExprMutator {\n public:\n  /*!\n   * \\brief The constructor\n   * \\param old_buffer The old buffer\n   * \\param new_buffer The new buffer\n   * \\param block_sref_reuse Optional map to record mapping between old and new blocks that reuse\n   *        sref.\n   */\n  ReplaceBufferMutator(const Buffer& old_buffer, Buffer new_buffer,\n                       Map<Block, Block>* block_sref_reuse);\n\n  ReplaceBufferMutator(const Map<Buffer, Buffer>& buffer_map, Map<Block, Block>* block_sref_reuse);\n\n protected:\n  using StmtExprMutator::VisitExpr_;\n  using StmtExprMutator::VisitStmt_;\n\n  PrimExpr VisitExpr_(const VarNode* var) final;\n\n  template <typename Node>\n  Node VisitBufferAccess(Node node) {\n    auto it = buffer_var_map_.find(node->buffer->data.get());\n    if (it != buffer_var_map_.end()) {\n      node.CopyOnWrite()->buffer = it->second;\n    }\n    return node;\n  }\n\n  Stmt VisitStmt_(const BufferStoreNode* op) final;\n\n  PrimExpr VisitExpr_(const BufferLoadNode* op) final;\n\n  virtual MatchBufferRegion VisitMatchBufferRegion(const MatchBufferRegion& match_buffer);\n\n  Stmt VisitStmt_(const BlockNode* block) override;\n\n  /*!\n   * \\brief A mapping which maps old buffer vars to new buffers, including the buffers defined in\n   * MatchBufferRegion.\n   */\n  std::unordered_map<const VarNode*, Buffer> buffer_var_map_;\n  /*! \\brief The block sref reuse map for the following replacement */\n  Map<Block, Block>* block_sref_reuse_;\n};\n\n/******** Block Removal ********/\n\n/*!\n * \\brief Construct a new AST, with a specific sref tree leaf removed.\n * The leaf's ancestors who have only a single child will be removed too.\n * \\param leaf_block_sref The block/loop sref to the sref tree leaf to be removed\n * \\param src_stmt The root of the subtree where the replacement begins\n * \\param tgt_stmt The root of the subtree after the replacement\n * \\return A boolean indicating if the leaf can be removed successfully\n * \\note Read before use:\n * 1) Removal is not conducted beyond scope-level.\n * 2) This method only works properly when the scope root is a stage pipeline.\n *\n * An example of the removal plan, say we are removing the leaf block \"B\" from the AST.\n *\n *  \\code\n *    with block([], \"scope_root\"):\n *        ...\n *        with block([128, 128], \"B\") as [vi, vj]:\n *            B[vi, vj] = A[vi, vj] + 1.0\n *        with block([128, 128], \"C\") as [vi, vj]:\n *            C[vi, vj] = B[vi, vj] * 2.0\n *  \\endcode\n *\n * Ths method does not mutate the AST, instead it returns the a `(src_stmt, tgt_stmt)` pair as a\n * plan to substitute certain pieces of the IR.\n *\n * In our example, it returns block \"scope_root\" as `src_stmt`, and the result `tgt_stmt` is:\n *\n *  \\code\n *    with block([], \"scope_root\"):\n *        ...\n *        with block([128, 128], \"C\") as [vi, vj]:\n *            C[vi, vj] = B[vi, vj] * 2.0\n *  \\endcode\n */\nvoid LeafBlockRemovalPlan(const ScheduleState& self, const StmtSRef& leaf_block_sref,\n                          Stmt* src_stmt, Stmt* tgt_stmt);\n\n/*!\n * \\brief Tile a subset of loops in the block according to the given tensor intrinsic.\n * \\param self The schedule to which tiling is applied\n * \\param block_rv The block whose subset of loops will be tiled\n * \\param intrin_name The name of a tensor intrinsic, must be registerd via\n * TensorIntrin.register(...) beforehand\n * \\param allow_padding Whether to allow padding when tiling\n * \\return LoopRV corresponding to the outermost loop of a\n * block tiled according to the given intrin, NullOpt if a valid loop mapping is not found\n */\nOptional<tir::LoopRV> TileWithTensorIntrin(const tir::Schedule& sch, const tir::BlockRV& block_rv,\n                                           const String& intrin_name, bool allow_padding = false);\n\n/******** Block mutation ********/\n\n/*!\n * \\brief Simplifier for indices of buffer access and block buffer access regions.\n */\nclass BlockBufferAccessSimplifier : public arith::IRMutatorWithAnalyzer {\n public:\n  /*!\n   * \\brief Simplify indices of buffer access and block buffer access regions in the statement\n   * \\param stmt The statement to be simplified\n   * \\param analyzer The arithmetic analyzer\n   * \\return The simplified statement\n   */\n  static Stmt Simplify(const Stmt& stmt, arith::Analyzer* analyzer) {\n    BlockBufferAccessSimplifier simplifier(analyzer);\n    return simplifier(stmt);\n  }\n\n private:\n  explicit BlockBufferAccessSimplifier(arith::Analyzer* analyzer)\n      : IRMutatorWithAnalyzer(analyzer) {}\n\n  using IRMutatorWithAnalyzer::VisitExpr_;\n  using IRMutatorWithAnalyzer::VisitStmt_;\n\n  void SimplifyAccessRegion(Array<BufferRegion>* old_access_regions);\n  void SimplifyBufferIndices(Array<PrimExpr>* indices);\n\n  Stmt VisitStmt_(const BlockNode* op) final;\n  Stmt VisitStmt_(const BufferStoreNode* op) final;\n  PrimExpr VisitExpr_(const BufferLoadNode* op) final;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_TRANSFORM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/schedule/utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_TIR_SCHEDULE_UTILS_H_\n#define TVM_TIR_SCHEDULE_UTILS_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/arith/int_set.h>\n#include <tvm/arith/iter_affine_map.h>\n#include <tvm/tir/analysis.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op.h>\n#include <tvm/tir/schedule/instruction.h>\n#include <tvm/tir/schedule/schedule.h>\n#include <tvm/tir/schedule/state.h>\n#include <tvm/tir/schedule/trace.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n\n#include \"../../arith/pattern_match.h\"\n#include \"../../node/attr_registry.h\"\n#include \"../../printer/text_printer.h\"\n#include \"../../runtime/thread_storage_scope.h\"\n#include \"../../support/array.h\"\n#include \"../../support/nd_int_set.h\"\n#include \"./analysis.h\"\n#include \"./error.h\"\n#include \"./instruction_traits.h\"\n#include \"./primitive.h\"\n#include \"./transform.h\"\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief A helper macro to convert an sref to the statement it points to,\n * then check if the downcasting succeeded.\n * \\param Result The result variable, used for checking\n * \\param SRef The SRef to be cast\n * \\param Type The type to be cast to, can be Block or For\n */\n#define TVM_SREF_AS_OR_ERR(Result, SRef, Type) \\\n  SRef->StmtAs<Type>();                        \\\n  ICHECK(Result)\n\n/*!\n * \\brief A helper macro to convert an sref to the block it points to,\n *\n * Throws an internal error if downcasting fails.  The variable name\n * in the parent scope is used for the error message.\n *\n * \\param SRef The SRef to be cast\n */\n#define TVM_SREF_TO_BLOCK(SRef)                                                                    \\\n  [&]() {                                                                                          \\\n    auto result = TVM_SREF_AS_OR_ERR(result, (SRef), ::tvm::tir::BlockNode)                        \\\n                  << \"TypeError: Expects StmtSRef `\" << #SRef << \"` points to `Block`, but gets: \" \\\n                  << ((SRef)->stmt ? (SRef)->stmt->GetTypeKey() : \"None\");                         \\\n    return result;                                                                                 \\\n  }()\n\n/*!\n * \\brief A helper macro to convert an sref to the for-loop it points to\n *\n * Throws an internal error if downcasting fails.  The variable name\n * in the parent scope is used for the error message.\n *\n * \\param SRef The SRef to be cast\n */\n#define TVM_SREF_TO_FOR(SRef)                                                                     \\\n  [&]() {                                                                                         \\\n    auto result = TVM_SREF_AS_OR_ERR(result, (SRef), ::tvm::tir::ForNode)                         \\\n                  << \"TypeError: Expects StmtSRef `\" << #SRef << \"` points to `Loop`, but gets: \" \\\n                  << ((SRef)->stmt ? (SRef)->stmt->GetTypeKey() : \"None\");                        \\\n    return result;                                                                                \\\n  }()\n\n/*!\n * \\brief Downcast a TVM ObjectRef to its corresponding container using `ObjectRef::as<Type>`,\n * then check if the downcasting succeeded.\n * \\param Result The result variable, used for checking\n * \\param From The ObjectRef to be downcast\n * \\param Type The type to be downcast to\n */\n#define TVM_TYPE_AS_OR_ERR(Result, From, Type) \\\n  From.as<Type>();                             \\\n  ICHECK(Result)\n\n/*!\n * \\brief Downcast a TVM ObjectRef to its corresponding container using `ObjectRef::as<Type>`,\n * throwing an internal error if downcast fails.\n * \\param Result The result variable, used for checking\n * \\param From The ObjectRef to be downcast\n * \\param Type The type to be downcast to\n */\n#define TVM_TYPE_AS(From, Type)                                                               \\\n  [&]() {                                                                                     \\\n    auto result = TVM_TYPE_AS_OR_ERR(result, (From), Type)                                    \\\n                  << \"TypeError: Expects `\" << #From << \"` to have type `\" << Type::_type_key \\\n                  << \"`, but gets: \" << ((From).defined() ? (From)->GetTypeKey() : \"None\");   \\\n    return result;                                                                            \\\n  }()\n\n/*!\n * \\brief Convert an array of loop StmtSRefs to an array of loops\n * \\param loop_srefs The loop StmtSRefs to be converted\n * \\return The conversion result loops\n */\ninline Array<For> LoopSRefs2Loops(const Array<StmtSRef>& loop_srefs) {\n  Array<For> loops;\n  loops.reserve(loop_srefs.size());\n  for (StmtSRef loop_sref : loop_srefs) {\n    const ForNode* loop = TVM_SREF_TO_FOR(loop_sref);\n    loops.push_back(GetRef<For>(loop));\n  }\n  return loops;\n}\n\n/*!\n * \\brief Convert an array of block rvs to an array of block StmtSRefs\n * \\param sch The schedule used to evaluate the random variables\n * \\param block_rvs The random variables to be converted\n * \\return The conversion result srefs\n */\ninline Array<StmtSRef> BlockRVs2StmtSRefs(const Schedule& sch, const Array<BlockRV>& block_rvs) {\n  Array<StmtSRef> block_srefs;\n  block_srefs.reserve(block_rvs.size());\n  for (const BlockRV& block_rv : block_rvs) {\n    block_srefs.push_back(sch->GetSRef(block_rv));\n  }\n  return block_srefs;\n}\n\n/******** Storage scope ********/\n\n/*!\n * \\brief Determine if iterators of a storage scope should be relaxed\n * under a specific thread scope\n * \\param storage_scope The storage scope that the iterators are on\n * \\param thread_scope The thread scope to be relaxed\n * \\return A boolean indicating the result\n */\ninline bool CanRelaxStorageUnderThread(const runtime::StorageScope& storage_scope,\n                                       const runtime::ThreadScope& thread_scope) {\n  if (storage_scope.rank == runtime::StorageRank::kWarp) {\n    // for warp memory, we only relax threadIdx.x\n    return thread_scope.rank == 1 && thread_scope.dim_index == 0;\n  }\n  return static_cast<int>(storage_scope.rank) <= static_cast<int>(thread_scope.rank);\n}\n\n/******** SeqStmt ********/\n\n/*!\n * \\brief Remove a specific Stmt from a SeqStmt. If a SeqStmt contains a BlockRealize,\n * whose block is the Stmt to be removed, then remove that BlockRealize too.\n * \\param seq The SeqStmt to be removed from\n * \\param to_remove The Stmt to be removed\n * \\return The removal result\n */\ninline Stmt RemoveFromSeqStmt(const SeqStmt& seq, const Stmt& to_remove) {\n  ICHECK_GT(seq->size(), 1);\n  Array<Stmt> new_stmts;\n  new_stmts.reserve(seq->size());\n  for (const Stmt& stmt : seq->seq) {\n    if (to_remove.same_as(stmt)) {\n      continue;\n    }\n    if (const auto* realize = stmt.as<BlockRealizeNode>()) {\n      if (to_remove.same_as(realize->block)) {\n        continue;\n      }\n    }\n    new_stmts.push_back(stmt);\n  }\n  return SeqStmt::Flatten(new_stmts);\n}\n\n/*!\n * \\brief Convert a Stmt to an Array.\n * \\param stmt The Stmt to be converted to\n * \\return If the Stmt is SeqStmt, then returns the sequence;\n * Otherwise, returns a single-element Array with the Stmt inside.\n */\ninline Array<Stmt> AsArray(const Stmt& stmt) {\n  if (const auto* seq_stmt = stmt.as<SeqStmtNode>()) {\n    return seq_stmt->seq;\n  }\n  return {stmt};\n}\n\n/*!\n * \\brief Checks of a statement is a SeqStmt that contains multiple statements\n * \\param stmt The statement to be checked\n * \\return A boolean indicating the result\n */\ninline bool IsSingleStmt(const Stmt& stmt) {\n  if (const auto* seq_stmt = stmt.as<SeqStmtNode>()) {\n    return seq_stmt->seq.size() == 1;\n  }\n  return true;\n}\n\n/******** IterVar ********/\n\n/*!\n * \\brief Create a new IterVar for the input For loop, with specified name and type\n * \\param loop The loop to be created from\n * \\param name The name of the new IterVar\n * \\param iter_var_type The type of the new IterVar\n * \\return The newly created IterVar\n */\ninline IterVar IterVarFromLoop(const For& loop, String name, IterVarType iter_var_type) {\n  return IterVar(Range::FromMinExtent(loop->min, loop->extent),\n                 Var(std::move(name), loop->loop_var.dtype()), iter_var_type);\n}\n\n/*!\n * \\brief Get the thread scope bound to the specific loop\n * \\param loop The loop to be inspected\n * \\return The thread scope bound to the loop\n */\ninline runtime::ThreadScope GetThreadScope(const ForNode* loop) {\n  if (loop->kind == ForKind::kThreadBinding) {\n    return runtime::ThreadScope::Create(loop->thread_binding.value()->thread_tag);\n  }\n  return runtime::ThreadScope{-1, -1};\n}\n\n/*!\n * \\brief Check if the thread scope is blockIdx\n * \\param thread_scope The thread scope to be checked\n * \\return True if the thread scope is blockIdx\n */\ninline bool IsBlockIdx(const runtime::ThreadScope& thread_scope) {\n  return thread_scope.rank == 0;  // The rank of blockIdx is 0\n}\n\n/*!\n * \\brief Check if the thread scope is threadIdx\n * \\param thread_scope The thread scope to be checked\n * \\return True if the thread scope is threadIdx\n */\ninline bool IsThreadIdx(const runtime::ThreadScope& thread_scope) {\n  return thread_scope.rank == 1 && thread_scope.dim_index >= 0;\n}\n\n/**************** Loop extents ****************/\n\n/*!\n * \\brief Get the extents of a loop\n * \\param loop The loop to be queried\n * \\return The extent of the loop, nullptr if the extent is not constant\n */\ninline const int64_t* GetLoopIntExtent(const ForNode* loop) { return as_const_int(loop->extent); }\n\n/*!\n * \\brief Get the extents of a loop\n * \\param loop_sref The loop to be queried\n * \\return The extent of the loop, nullptr if the extent is not constant\n */\ninline const int64_t* GetLoopIntExtent(const StmtSRef& loop_sref) {\n  const ForNode* loop = TVM_SREF_TO_FOR(loop_sref);\n  return as_const_int(loop->extent);\n}\n\n/*!\n * \\brief Check if an expression consists of a single variable,\n * or a variable plus/minus an constant integer shift\n * \\param expr The expression to be checked\n * \\return The single variable in the expression, or NullOpt if the expression is neither a variable\n * or a constant shift from a variable\n */\ninline Optional<Var> AnalyzeVarWithShift(const PrimExpr& expr, Optional<IntImm>* constant) {\n  if (const auto* var = expr.as<VarNode>()) {\n    *constant = NullOpt;\n    return GetRef<Var>(var);\n  }\n  arith::PVar<Var> var;\n  arith::PVar<IntImm> shift;\n  // match: \"var + shift\"\n  if ((var + shift).Match(expr) || (shift + var).Match(expr)) {\n    *constant = shift.Eval();\n    return var.Eval();\n  }\n  // match: \"var - shift\"\n  if ((var - shift).Match(expr)) {\n    IntImm result = shift.Eval();\n    *constant = IntImm(result->dtype, -result->value);\n    return var.Eval();\n  }\n  return NullOpt;\n}\n\n/******** Annotation ********/\n\n/*!\n * \\brief Get the annotation on a Block/For\n * \\tparam TObjectRef The type of the annotation value\n * \\param sref The sref to the block or the for loop\n * \\param ann_key The annotation key to be looked up\n * \\return NullOpt if not found; otherwise the annotation value\n */\ntemplate <class TObjectRef, class TStmtNode>\ninline Optional<TObjectRef> GetAnn(const TStmtNode* stmt, const String& ann_key) {\n  const Map<String, ObjectRef>* annotations = &stmt->annotations;\n  for (const auto& ann : *annotations) {\n    if (ann.first == ann_key) {\n      return Downcast<TObjectRef>(ann.second);\n    }\n  }\n  return NullOpt;\n}\n\n/*!\n * \\brief Get the annotation on a Block/For\n * \\tparam TObjectRef The type of the annotation value\n * \\param sref The sref to the block or the for loop\n * \\param ann_key The annotation key to be looked up\n * \\return NullOpt if not found; otherwise the annotation value\n */\ntemplate <class TObjectRef>\ninline Optional<TObjectRef> GetAnn(const StmtSRef& sref, const String& ann_key) {\n  if (const auto* loop = sref->StmtAs<ForNode>()) {\n    return GetAnn<TObjectRef, ForNode>(loop, ann_key);\n  } else if (const auto* block = sref->StmtAs<BlockNode>()) {\n    return GetAnn<TObjectRef, BlockNode>(block, ann_key);\n  } else {\n    LOG(FATAL) << \"TypeError: Unknown type of sref: \" << sref->stmt->GetTypeKey();\n    throw;\n  }\n}\n\n/*!\n * \\brief Check if a Block/For has a specific pair of annotation key and values\n * \\param sref The sref to the block or the for loop\n * \\param ann_key The annotation key to be checked\n * \\param ann_val The annotation value to be checked\n * \\return Whether a Block/For has a specific pair of annotation key and values\n */\ninline bool HasAnn(const StmtSRef& sref, const String& ann_key, const String& ann_val) {\n  Optional<String> result = GetAnn<String>(sref, ann_key);\n  return result.defined() && result.value() == ann_val;\n}\n\n/*!\n * \\brief Check if a Block/For has a specific pair of annotation key and values\n * \\param sref The sref to the block or the for loop\n * \\param ann_key The annotation key to be checked\n * \\param ann_val The boolean annotation value to be checked\n * \\return Whether a Block/For has a specific pair of annotation key and values\n */\ninline bool HasAnn(const StmtSRef& sref, const String& ann_key, bool ann_val) {\n  Optional<Bool> result = GetAnn<Bool>(sref, ann_key);\n  return result.defined() && result.value() == ann_val;\n}\n\n/********** Helper Functions for RuleAddRFactor and RuleCrossThreadReduction **********/\n\n/*!\n * \\brief Reorder the reduction loops to innermost positions if needed.\n * \\param sch The schedule\n * \\param block_rv The block where to apply the reorder\n * \\param fused_reduce_loop The fusion-generated loop to return.\n * \\param num_spatial_loops The number of spatial loops to return.\n * \\note Before invoking this helper function, make sure that the block has only spatial and\n *       reduction loop axes.\n */\ninline void ReorderAndFuseReductionLoops(const tir::Schedule& sch, const tir::BlockRV& block_rv,\n                                         tir::LoopRV* fused_reduce_loop,\n                                         size_t* num_spatial_loops) {\n  Array<tir::LoopRV> loops = sch->GetLoops(block_rv);\n  Array<tir::StmtSRef> loop_srefs;\n  for (const tir::LoopRV& loop_rv : loops) {\n    loop_srefs.push_back(sch->GetSRef(loop_rv));\n  }\n\n  Array<tir::LoopRV> new_order;\n  // Step 1. Add spatial loops.\n  *num_spatial_loops = 0;\n  for (size_t i = 0; i < loops.size(); ++i) {\n    if (GetLoopIterType(loop_srefs[i]) == tir::kDataPar) {\n      new_order.push_back(loops[i]);\n      (*num_spatial_loops)++;\n    }\n  }\n  // Step 2. Add reduction loops.\n  Array<tir::LoopRV> reduction_loops;\n  for (size_t i = 0; i < loops.size(); ++i) {\n    if (GetLoopIterType(loop_srefs[i]) == tir::kCommReduce) {\n      new_order.push_back(loops[i]);\n      reduction_loops.push_back(loops[i]);\n    }\n  }\n  // Step 3. Apply reordering if new_order differs from the original order.\n  ICHECK_EQ(new_order.size(), loops.size());\n  for (size_t i = 0; i < loops.size(); ++i) {\n    if (!new_order[i].same_as(loops[i])) {\n      sch->Reorder(new_order);\n      break;\n    }\n  }\n  // Step 4. Fuse all the reduction loops if there are multiple reduction loops.\n  CHECK(!reduction_loops.empty()) << \"ValueError: There should be at least one reduction loop\";\n  if (reduction_loops.size() > 1) {\n    *fused_reduce_loop = sch->Fuse(reduction_loops);\n  } else {\n    *fused_reduce_loop = reduction_loops[0];\n  }\n}\n\n/******** Helper functions for enum conversion ********/\n\n/*!\n * \\brief Convert BufferIndexType to String\n * \\param buffer_index_type The BufferIndexType value to convert\n * \\return The string representation of BufferIndexType\n */\ninline String BufferIndexType2Str(BufferIndexType buffer_index_type) {\n  if (buffer_index_type == BufferIndexType::kRead) {\n    return \"read\";\n  } else {\n    ICHECK(buffer_index_type == BufferIndexType::kWrite);\n    return \"write\";\n  }\n}\n\n/******** Utilities for retrieving information about blocks ********/\n\n/*! \\brief Returns the names of the blocks in the provided module. */\ninline std::unordered_set<std::string> GetBlockNames(const IRModule& mod) {\n  struct BlockNameCollector : public tir::StmtVisitor {\n    void VisitStmt_(const tir::BlockNode* block) override {\n      block_names.insert(block->name_hint);\n      StmtVisitor::VisitStmt(block->body);\n    }\n    std::unordered_set<std::string> block_names;\n  };\n\n  auto prim_func = tir::FindEntryFunc(mod, nullptr);\n  BlockNameCollector collector;\n  collector(prim_func->body);\n  return collector.block_names;\n}\n\n/*! \\brief Query if the given block name exists in the module associated with the schedule */\ninline bool HasBlock(const Schedule& sch, const std::string& block_name) {\n  auto block_names = GetBlockNames(sch->mod());\n  return block_names.count(block_name);\n}\n\n/******** Utilites for trace application ********/\n\n/*!\n * \\brief Translate the input objects using the provided substitution map.\n * \\param inputs The input objects.\n * \\param rv_map The substitution map for variables.\n * \\return The transformed objects.\n */\nArray<ObjectRef> TranslateInputRVs(const Array<ObjectRef>& inputs,\n                                   const std::unordered_map<const Object*, const Object*>& rv_map);\n\n/*!\n * \\brief Update the variable substitution map according to the new outputs.\n * \\param old_outputs The previous outputs of a schedule instruction.\n * \\param new_outputs The new outputs of the same schedule instruction.\n * \\param rv_map The substitution map for variables.\n */\nvoid TranslateAddOutputRVs(const Array<ObjectRef>& old_outputs, const Array<ObjectRef>& new_outputs,\n                           std::unordered_map<const Object*, const Object*>* rv_map);\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_SCHEDULE_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/arg_binder.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file arg_binder.h\n * \\brief Helper utility to match and bind arguments.\n */\n#ifndef TVM_TIR_TRANSFORMS_ARG_BINDER_H_\n#define TVM_TIR_TRANSFORMS_ARG_BINDER_H_\n\n#include <tvm/arith/analyzer.h>\n#include <tvm/tir/buffer.h>\n#include <tvm/tir/expr.h>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Helper utility to generate match and bind of arguments.\n *\n * \\note There is many places in TVM IR where we need argument bindings.\n *\n *  Consider a function f(tA(shape=var(n)), tB(shape=3), tC(shape=(n+2)).\n *  Here n is a undefined variable that is decided by the outside, tB imposes\n *  a constraint such that it can only take tensor with shape 3, tC imposes\n *  another constraint that it's shape must equals n + 2.\n *  So if we call it with f(bufferA, bufferB, bufferC), we need to generate\n *  the following binding sequence:\n *  - define n = bufferA.shape[0]\n *  - assert bufferB.shape[0] == 3\n *  - assert bufferB.shape[1] == n + 3\n *\n *  In general, this is a constraint solving problem. We have simplified assumption\n *  over the binding declaration, such that we require the variable occurred in\n *  constraint must be declared in argument list. So it is illegal to have signature\n *  f(tA(shape=(n+3))) without any argument variable corresponds to n, even though\n *  it is already enough to derive n from the input argument.\n */\nclass ArgBinder {\n public:\n  /*!\n   * \\brief Constructor\n   * \\param def_map A definition map that contains definition of known variables.\n   *   ArgBinder will update this def_map when adding new definitions.\n   */\n  explicit ArgBinder(std::unordered_map<const VarNode*, PrimExpr>* def_map) : def_map_(def_map) {}\n  /*!\n   * \\brief Try to bind arg to value, generate constraint if necessary.\n   * \\param arg The argument to be binded.\n   * \\param value The target expression value\n   * \\param arg_name argument name.\n   * \\param with_let Whether add lets during bind\n   */\n  void Bind(const PrimExpr& arg, const PrimExpr& value, const std::string& arg_name,\n            bool with_let = false);\n  /*!\n   * \\brief Bind array to array\n   * \\param arg The argument to be binded.\n   * \\param value The target expression value\n   * \\param arg_name argument name.\n   */\n  void BindArray(const Array<PrimExpr>& arg, const Array<PrimExpr>& value,\n                 const std::string& arg_name);\n  /*!\n   * \\brief Bind symbolic buffer to another symbolic buffer\n   * \\param arg The argument to be binded.\n   * \\param value The target expression value\n   * \\param arg_name argument name.\n   * \\param fuzzy_match If enabled, we allow value's dimension to be smaller than arg, as long as\n   * arg's higher dimensions are of 1.\n   */\n  void BindBuffer(const Buffer& arg, const Buffer& value, const std::string& arg_name,\n                  bool fuzzy_match);\n  /*!\n   * \\brief Bind symbolic buffer to a DLTensor handle.\n   * \\param buffer The argument buffer to be binded.\n   * \\param device_type The device id to be binded.\n   * \\param device_id The device id to be binded.\n   * \\param handle The DLTensor handle.\n   * \\param arg_name argument name.\n   */\n  void BindDLTensor(const Buffer& buffer, const PrimExpr& device_type, const PrimExpr& device_id,\n                    const Var& handle, const std::string& arg_name);\n\n  /*! \\return The defs generated in binding. */\n  const std::vector<Var>& defs() const { return defs_; }\n  /*! \\return The asserts generated in binding */\n  const std::vector<Stmt>& asserts() const { return asserts_; }\n  /*!\n   * \\brief Initialization nest generated\n   *  This is only non-empty when BindDLTensor is called.\n   *\n   * \\note The binder may choose to generate a let statement\n   *  and simply put def_map to map Variable to itself,\n   *  or update def_map to directly map to new value and not generate let statement.\n   *\n   *  Let statement is usually generated when bind to DLTensor and memory load is involved.\n   * \\return The initialization nest generated during binding.\n   */\n  const std::vector<Stmt>& init_nest() const { return init_nest_; }\n  /*! \\return Handle data type of the data */\n  const Map<Var, PrimExpr>& def_handle_dtype() const { return def_handle_dtype_; }\n\n private:\n  // Internal bind function\n  bool Bind_(const PrimExpr& arg, const PrimExpr& value, const std::string& arg_name,\n             bool with_lets);\n  /*! \\brief The definition map, can be uses to substitute */\n  std::unordered_map<const VarNode*, PrimExpr>* def_map_;\n  /*! \\brief defs generated in the current binder */\n  std::vector<Var> defs_;\n  /*! \\brief Initialize nest */\n  std::vector<Stmt> init_nest_;\n  /*! \\brief handle data type in the defintiions */\n  Map<Var, PrimExpr> def_handle_dtype_;\n  /*! \\brief asserts generated */\n  std::vector<Stmt> asserts_;\n  /*! \\brief internal analyzer. */\n  arith::Analyzer analyzer_;\n};\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_TRANSFORMS_ARG_BINDER_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/common_subexpr_elim.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file common_subexpr_elim.h\n * \\brief Interface of the Common Subexpressions Elimination (CSE) pass which rewrites statements\n           and expressions in order to eliminate redundant computations. In order to achieve that,\n           common (sub-)expressions are introduced into variables with let-in bindings, and the\n           places where the expression was used are replaced with the freshly introduced variable.\n */\n\n#ifndef TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_H_\n#define TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/expr_functor.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>  // For the class StmtExprMutator\n#include <tvm/tir/var.h>\n\n#include <utility>  // For std::pair\n#include <vector>\n\n#include \"common_subexpr_elim_tools.h\"  // For the class MaybeValue\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief A context is a vector of pairs that associates Var to MaybeValue\n          (which are either an expression or nothing)\n */\nusing Context = std::vector<std::pair<Var, MaybeValue>>;\n\n/*!\n * \\brief Mutator that performs Common Subexpression Elimination (CSE) for the body of a\n          PrimFunc, mutating both its expressions and statements.\n */\nclass CommonSubexpressionEliminator : public StmtExprMutator {\n public:\n  // Toplevel (static) function\n  static Stmt PerformCSE(const Stmt& stmt, const Context& context_init, bool identify_equiv_terms);\n\n  PrimExpr VisitExpr(const PrimExpr& expr) override;\n  Stmt VisitStmt(const Stmt& stmt) override;\n\n  int GetNbVarGenerated();\n\n protected:\n  // Constructor\n  CommonSubexpressionEliminator(const Stmt& stmt, const Context& context_init,\n                                bool identify_equiv_terms);\n\n  PrimExpr VisitExpr_(const LetNode* op) override;\n\n  Stmt VisitStmt_(const LetStmtNode* op) override;\n  Stmt VisitStmt_(const ForNode* op) override;\n\n private:\n  Stmt initial_body_;     // Kept for checking if names of new variables already exist\n  Context context_;       // Context associating variables to (maybe) definitions\n  int num_last_try_ = 0;  // Number of the last variable tried\n  int nb_var_ = 0;        // Number of variables introduced by the CSE pass\n\n  bool identify_equiv_terms_ = false;\n\n  static bool ForbiddenComputation(const PrimExpr& expr);\n  static bool IsEligibleComputation(const PrimExpr& expr);\n  static bool CanContainEligibleComputations(const PrimExpr& expr);\n  static bool OrderOnExprAndFrequency(std::pair<PrimExpr, size_t> a, std::pair<PrimExpr, size_t> b);\n  Var GenerateNewVar(DataType type_annotation);\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/common_subexpr_elim_tools.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file common_subexpr_elim_tools.h\n * \\brief Interface of analysis tools and utility functions used\n           by the Common Subexpression Elimination (CSE) pass.\n */\n\n#ifndef TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_TOOLS_H_\n#define TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_TOOLS_H_\n\n#include <tvm/runtime/container/string.h>\n#include <tvm/tir/analysis.h>  // For the ExprDeepEqual analysis\n#include <tvm/tir/expr.h>\n#include <tvm/tir/expr_functor.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>  // For the class StmtExprVisitor\n\n#include <optional>\n#include <unordered_map>  // For the hashtable datatype\n#include <utility>        // For pairs datatype\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief A computation table is a hashtable which associates to each expression being computed\n          a number (which is the number of time that it is computed)\n          It is important to note that the hash used is a StructuralHash (and not an ObjectPtrHash)\n          as we need to hash similarly deeply equal terms.\n          The comparison used is ExprDeepEqual, which is stricter than StructuralEqual (as it does\n          not do variables remapping), so it is compatible with StructuralHash (intended to be used\n          with StructuralEqual).\n */\nusing ComputationTable = std::unordered_map<PrimExpr, size_t, StructuralHash, ExprDeepEqual>;\n\n/*!\n * \\brief A cache of computations is made of a pair of two hashtables, which respectively associate\n          to each statement or expression of the program its computation table. Its purpose is\n          to avoid the CSE pass from recomputing repeatedly the same tables of computations.\n */\nstruct ComputationCache {\n  // Part of the cache for statements\n  // It maps each known statement to its computation table\n  std::unordered_map<Stmt, ComputationTable, ObjectPtrHash, ObjectPtrEqual>\n      cache_stmt_table_computations_;\n\n  // Part of the cache for expressions\n  // It maps each known expression to its computation table\n  std::unordered_map<PrimExpr, ComputationTable, ObjectPtrHash, ObjectPtrEqual>\n      cache_expr_table_computations_;\n};\n\n/*!\n * \\brief Visitor which returns in a hashtable the (syntatic) computations done by an expression\n          or by a statement.\n * \\note Computations here are considered syntactically, meaning that semantically equivalent\n          computations that are not syntactically the same are not merged together.\n */\nclass ComputationsDoneBy : public StmtExprVisitor {\n public:\n  // Toplevel (static) methods\n  static ComputationTable GetComputationsDoneBy(\n      const PrimExpr& expr, std::function<bool(const PrimExpr&)> is_eligible_computation,\n      std::function<bool(const PrimExpr&)> can_contain_computations);\n  static ComputationTable GetComputationsDoneBy(\n      const Stmt& stmt, std::function<bool(const PrimExpr&)> is_eligible_computation,\n      std::function<bool(const PrimExpr&)> can_contain_computations);\n\n protected:\n  // Constructor\n  ComputationsDoneBy(std::function<bool(const PrimExpr&)> is_eligible_computation,\n                     std::function<bool(const PrimExpr&)> can_contain_computations);\n\n  void VisitExpr(const PrimExpr& expr) override;\n  void VisitStmt(const Stmt& stmt) override;\n\n  void VisitStmt_(const IfThenElseNode* op) override;\n  void VisitStmt_(const ForNode* op) override;\n  void VisitStmt_(const WhileNode* op) override;\n\n private:\n  static ComputationTable ComputationsDoneByChildrenOf(\n      const PrimExpr& expr, std::function<bool(const PrimExpr&)> is_eligible_computation,\n      std::function<bool(const PrimExpr&)> can_contain_computations);\n  static ComputationTable ComputationsDoneByChildrenOf(\n      const Stmt& stmt, std::function<bool(const PrimExpr&)> is_eligible_computation,\n      std::function<bool(const PrimExpr&)> can_contain_computations);\n\n  // The predicate used for knowing which computations are eligible\n  std::function<bool(const PrimExpr&)> is_eligible_computation_;\n  // The predicate used for knowing in which nodes we can search for eligible computations\n  std::function<bool(const PrimExpr&)> can_contain_computations_;\n  // The object being constructed and \"returned\" by the VisitExpr()/VisitStmt() methods\n  ComputationTable table_of_computations_;\n  // Cache for preventing to compute repeatedly the computations done by the same stmt or expr\n  static ComputationCache cache_;\n};\n\n/*!\n * \\brief Visitor that computes the *direct* subexpressions of a given expression.\n * \\note Returns only the direct subexpressions of the given expressions, not all the subexprs.\n          So for instance, for (A+(B+C)) it will return A and (B+C) if they are eligible,\n          but not B and C.\n */\nclass DirectSubexpr : public ExprVisitor {\n public:\n  // Toplevel (static) function\n  static std::vector<PrimExpr> GetDirectSubexpressions(\n      const PrimExpr& expr, std::function<bool(const PrimExpr&)> is_eligible_computation,\n      std::function<bool(const PrimExpr&)> can_contain_computations);\n\n protected:\n  // Constructor\n  DirectSubexpr(std::function<bool(const PrimExpr&)> is_eligible_computation,\n                std::function<bool(const PrimExpr&)> can_contain_computations);\n\n  void VisitExpr(const PrimExpr& expr) override;\n\n private:\n  // The predicate used for knowing which computations are eligible\n  std::function<bool(const PrimExpr&)> is_eligible_computation_;\n  // The predicate used for knowing in which nodes we can search for eligible subexpressions\n  std::function<bool(const PrimExpr&)> can_contain_computations_;\n\n  // We haven't entered the VisitExpr() method yet\n  bool entered_ = false;\n  // The vector of direct subexpressions that we are building\n  std::vector<PrimExpr> direct_subexpr_;\n};\n\n/*!\n * \\brief Visitor which tells if a given expression or statement uses a given variable name.\n          This is used by the CSE pass to make sure that we do not reuse existing names,\n          even though having the same name does not mean that it's the same variable, but it's\n          clearer for dumps.\n */\nclass UsesVarName : public StmtExprVisitor {\n public:\n  // Toplevel (static) methods\n  static bool ExprUsesVarName(const PrimExpr& expr, String var_name);\n  static bool StmtUsesVarName(const Stmt& stmt, String var_name);\n\n protected:\n  // Constructor\n  explicit UsesVarName(String var_name);\n\n  void VisitExpr(const PrimExpr& expr) override;\n  void VisitStmt(const Stmt& stmt) override;\n\n private:\n  String var_name_;\n  bool uses_var_name_ = false;\n};\n\n/*!\n * \\brief Various utility functions for the CSE pass\n */\nvoid PrintComputationTable(const ComputationTable& table);\n\nusing MaybeValue = std::optional<PrimExpr>;\n\nbool EqualTerms(const PrimExpr& a, const PrimExpr& b);\n// Used for deciding the (decidable) equivalence relation\nPrimExpr NormalizeTerm(const PrimExpr& expr, bool do_normalization);\n// The equivalence relation, which is the syntactical equality when `identify_equiv_terms` is false\nbool EquivalentTerms(const PrimExpr& a, const PrimExpr& b, bool identify_equiv_terms);\nstd::vector<std::pair<PrimExpr, size_t>> SyntacticToSemanticComputations(\n    const ComputationTable& table, bool identify_equiv_terms);\nbool PredicateIntroVarForComputation(const PrimExpr& computation, size_t nb_times_seen);\n\n// Polymorphic (functional) map on a vector, which builds a news vector with the same number of\n// elements, where each element is the application of a given function on the corresponding element\n// in the input vector.\ntemplate <typename A, typename B>\nstd::vector<B> VectorMap(const std::vector<A>& input, std::function<B(const A&)> fun) {\n  std::vector<B> result;\n  size_t size = input.size();\n  // For efficiency, allocate immediately the size needed as the result will have\n  // the same size as the input\n  result.reserve(size);\n\n  for (size_t i = 0; i < size; i++) {\n    result.push_back(fun(input[i]));\n  }\n\n  return result;\n}\n// Explicitely instanciate the template function for A=std::pair<Var,MaybeValue> and B=Var\ntemplate std::vector<Var> VectorMap(const std::vector<std::pair<Var, MaybeValue>>&,\n                                    std::function<Var(const std::pair<Var, MaybeValue>&)>);\n\nvoid InsertElemToSortedSemanticComputations(std::vector<std::pair<PrimExpr, size_t>>* sorted_vec,\n                                            const std::pair<PrimExpr, size_t>& pair);\nvoid InsertVectorToSortedSemanticComputations(std::vector<std::pair<PrimExpr, size_t>>* sorted_vec,\n                                              const std::vector<PrimExpr>& vec_to_add,\n                                              bool identify_equiv_terms);\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_TRANSFORMS_COMMON_SUBEXPR_ELIM_TOOLS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/ir_utils.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file ir_utils.h\n * \\brief Helper functions to construct and compose IR nodes.\n */\n#ifndef TVM_TIR_TRANSFORMS_IR_UTILS_H_\n#define TVM_TIR_TRANSFORMS_IR_UTILS_H_\n\n#include <tvm/arith/int_set.h>\n#include <tvm/runtime/device_api.h>\n#include <tvm/support/with.h>\n#include <tvm/tir/builtin.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/function.h>\n#include <tvm/tir/op.h>\n\n#include <limits>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nnamespace tvm {\nnamespace tir {\n/*!\n * \\brief combine the nest stmt, whose body is not defined.\n * \\param nest A list of For and LetStmt, whose body is not defined.\n * \\param body body\n * \\return The combined Stmt\n */\nStmt MergeNest(const std::vector<Stmt>& nest, Stmt body);\n\n/*!\n * \\brief combine the nest stmt, whose body is not defined.\n * \\param nest A list of For and LetStmt, whose body is not defined.\n * \\param body body\n * \\return The combined Stmt\n */\nStmt MergeNest(const std::vector<std::vector<Stmt>>& nest, Stmt body);\n\n/*!\n * \\brief update array with an unary function\n * \\param arr array\n * \\param fupdate an unary function\n * \\tparam T type of array element\n * \\tparam F type of the unary function\n * \\return if update happens, return the new array, else return the\n *  original array\n */\ntemplate <typename T, typename F>\ninline Array<T> UpdateArray(Array<T> arr, F fupdate) {\n  std::vector<T> new_arr(arr.size());\n  bool changed = false;\n  for (size_t i = 0; i < arr.size(); ++i) {\n    T old_elem = arr[i];\n    T new_elem = fupdate(old_elem);\n    if (!new_elem.same_as(old_elem)) changed = true;\n    new_arr[i] = new_elem;\n  }\n  if (!changed) {\n    return arr;\n  } else {\n    return Array<T>(new_arr);\n  }\n}\n\n/*!\n * \\brief Get construct from struct\n * \\param dtype The data type.\n * \\param handle the struct handle.\n * \\param index the offset index.\n * \\param kind The data kind.\n * \\return the get expression.\n */\ninline PrimExpr TVMStructGet(DataType dtype, Var handle, int index,\n                             builtin::TVMStructFieldKind kind) {\n  Array<PrimExpr> args = {handle, make_const(DataType::Int(32), index),\n                          make_const(DataType::Int(32), static_cast<int>(kind))};\n  return Call(dtype, builtin::tvm_struct_get(), args);\n}\n\n/*!\n * \\brief Address of handle + offset\n * \\param handle the array handle.\n * \\param dtype The data type.\n * \\param offset the offset index.\n */\ninline PrimExpr AddressOffset(Var handle, DataType dtype, int offset) {\n  PrimExpr offset_expr = make_const(DataType::Int(32), offset * dtype.lanes());\n  Buffer dummy_buf(handle, dtype, {offset_expr + 1}, {}, 0, handle->name_hint, 0, 0, kDefault);\n  BufferLoad buf_load(dummy_buf, {offset_expr});\n\n  return Call(DataType::Handle(), builtin::address_of(), {buf_load});\n}\n\n/*!\n * \\brief Address of handle + offset\n * \\param handle the array handle.\n * \\param dtype The data type.\n * \\param offset the offset index.\n */\ninline PrimExpr AddressOffset(Var handle, DataType dtype, PrimExpr offset) {\n  if (dtype.lanes() != 1) {\n    offset = offset * make_const(offset.dtype(), dtype.lanes());\n    offset = Ramp(offset, make_const(offset.dtype(), 1), dtype.lanes());\n  }\n\n  Buffer dummy_buf(handle, dtype.element_of(), {offset + 1}, {}, 0, handle->name_hint, 0, 0,\n                   kDefault);\n  BufferLoad buf_load(dummy_buf, {offset});\n\n  return Call(DataType::Handle(), builtin::address_of(), {buf_load});\n}\n\n/*!\n * \\brief Set value into struct.\n * \\param handle the struct handle.\n * \\param index the offset index.\n * \\param kind The data kind.\n * \\param value The value to be set.\n * \\return the set stmt.\n */\ninline Stmt TVMStructSet(Var handle, int index, builtin::TVMStructFieldKind kind, PrimExpr value) {\n  Array<PrimExpr> args = {handle, make_const(DataType::Int(32), index),\n                          make_const(DataType::Int(32), static_cast<int>(kind)), value};\n  return Evaluate(Call(DataType::Int(32), builtin::tvm_struct_set(), args));\n}\n\n/*!\n * \\brief Get the type that is passed around TVM PackedFunc API.\n * \\param t The original type.\n * \\return The corresponding API type.\n */\ninline DataType APIType(DataType t) {\n  if (t.is_handle()) return t;\n  ICHECK_EQ(t.lanes(), 1) << \"Cannot pass vector type through packed API.\";\n  if (t.is_uint() || t.is_int()) return DataType::Int(64);\n  ICHECK(t.is_float());\n  return DataType::Float(64);\n}\n\n/*!\n * \\brief Rule to get allocation alignment requirement for a given const array.\n * \\param type The type of allocation.\n * \\param const_size The constant size of the array.\n * \\return the alignment\n */\ninline int GetTempAllocaAlignment(DataType type, int32_t const_size) {\n  int align = runtime::kTempAllocaAlignment;\n  if (const_size > 0) {\n    int64_t const_s = static_cast<int64_t>(const_size) * type.bits() * type.lanes() / 8;\n    while (align > const_s) {\n      align = align / 2;\n    }\n  }\n  return align;\n}\n\n/*!\n * \\brief Create an int32 constant\n * \\param index the value of the constant\n * \\return the PrimExpr that represents the constant\n */\ninline PrimExpr ConstInt32(size_t index) {\n  ICHECK_LE(index, std::numeric_limits<int>::max());\n  return make_const(DataType::Int(32), static_cast<int>(index));\n}\n\n/*!\n * \\brief Allocate TVMValues on the stack\n * \\param type type of allocation\n * \\param num number of TVMValues to allocate\n * \\return PrimExpr representing the TVMValue\n */\ninline PrimExpr StackAlloca(std::string type, size_t num) {\n  Array<PrimExpr> args = {StringImm(type), ConstInt32(num)};\n  return Call(DataType::Handle(), builtin::tvm_stack_alloca(), args);\n}\n\n/*!\n * \\brief Convert a IR node to be SSA form.\n * \\param stmt The source statement to be converted.\n * \\return The converted form.\n */\nStmt ConvertSSA(Stmt stmt);\n\n/*!\n * \\brief Return the storage scope associated with a buffer variable.\n * \\param buffer_var The input buffer variable.\n * \\return A string representing the storage scope of this buffer variable.\n */\nString GetPtrStorageScope(Var buffer_var);\n\n/*!\n * \\brief Convert match buffer target buffer access indices to original one.\n * \\param indices The indices of the target buffer\n * \\return The indices of source buffer.\n */\nArray<PrimExpr> ConvertIndices(const MatchBufferRegion& match_buffer,\n                               const Array<PrimExpr>& indices);\n\n/*!\n * \\brief Convert match buffer target buffer region to original one.\n * \\param region The sub-region of the target buffer\n * \\return The region of source buffer.\n */\nRegion ConvertRegion(const MatchBufferRegion& match_buffer, const Region& region);\n\n/*!\n * \\brief Check if a given PrimFunc originated from a TE schedule.\n *\n * Internally this checks for the `from_legacy_te_schedule` attr of the PrimFunc.\n *\n * \\param f PrimFunc to check\n * \\return Whether or not the PrimFunc was created from a te schedule\n */\nBool IsFromLegacyTESchedule(PrimFunc f);\n\n/*!\n *\\brief Context helper to update domain map within conditional scope.\n *\n * Assume the condition is `0 <= i && i < 9` and global domain of i is [0, 20], thus `bounds[i]` is\n * [0, 8]. Then `With<ConditionalBoundsContext> ctx(condition, &relax_map, &hint_map, true)` step\n *into scope where dom_map[i] is [0, 8] and `With<ConditionalBoundsContext> ctx(condition,\n *&relax_map, &hint_map, false)` step into scope where dom_map[i] is [9, 20]\n */\nclass ConditionalBoundsContext {\n private:\n  friend class With<ConditionalBoundsContext>;\n  /*!\n   * \\brief Construct a condition bounds context.\n   * \\param condition The condition holds on true branch.\n   * \\param relax_map The domain map for relaxed vars to update.\n   * \\param hint_map The domain map for free vars to update.\n   * \\param is_true_branch Whether step into the branch where condition bounds holds.\n   */\n  ConditionalBoundsContext(const PrimExpr& condition,\n                           std::unordered_map<const VarNode*, arith::IntSet>* relax_map,\n                           std::unordered_map<const VarNode*, arith::IntSet>* hint_map,\n                           bool is_true_branch);\n  void EnterWithScope();\n  void ExitWithScope();\n\n  /*! \\brief Helper to solve related variable's bound within conditional scope.*/\n  Map<Var, Range> GetVarBoundsFromCondition();\n\n  /*! \\brief the condition holds on true branch. */\n  const PrimExpr& condition_;\n  /*! \\brief domain map for relaxed vars to update */\n  std::unordered_map<const VarNode*, arith::IntSet>* relax_map_;\n  /*! \\brief domain map for free vars to update */\n  std::unordered_map<const VarNode*, arith::IntSet>* hint_map_;\n  /*! \\brief whether is on true branch */\n  bool is_true_branch_;\n  /*! \\brief used to record and restore original var bounds */\n  std::unordered_map<const VarNode*, arith::IntSet> origin_map_;\n};\n\n// Information of tensor core fragment.\nstruct FragmentInfo {\n  // fragment shape\n  int m, n, k;\n  // fragment layout (row-major or column-major)\n  std::string layout;\n  // scope of the fragment (wmma.matrix_a, wmma.matrix_b, or wmma.accumulator)\n  std::string scope;\n  FragmentInfo() = default;\n  FragmentInfo(int _m, int _n, int _k, const std::string& _layout, const std::string& _scope)\n      : m(_m), n(_n), k(_k), layout(_layout), scope(_scope) {}\n\n  int GetSize() const {\n    if (scope == \"wmma.matrix_a\") {\n      return m * k;\n    } else if (scope == \"wmma.matrix_b\") {\n      return n * k;\n    } else if (scope == \"wmma.accumulator\") {\n      return m * n;\n    } else {\n      ICHECK(0);\n      throw;\n    }\n  }\n};\n\n/*!\n * \\brief Extract information of tensor core fragment from the IR.\n * \\param stmt The stmt to visit.\n * \\return Map from buffer variables to the fragment info.\n */\nstd::unordered_map<const VarNode*, FragmentInfo> GetTensorCoreFragmentInfo(const Stmt& stmt);\n\n// Return the queue id and the in-flight count associated with the given\n// attr::async_wait_queue_scope annotation.\nstd::pair<PrimExpr, PrimExpr> GetAsyncWaitAttributes(const AttrStmtNode* op);\n\n/*!\n * \\brief Bind a subset of parameter tensors to constants, replacing them by AllocateConst nodes.\n * \\param f The function to bind constants to.\n * \\param constants Raw constant data. If the size of this array is N, the last N parameter tensors\n * will be removed from the signature and instead AllocateConst nodes will be introduced in the\n * function body.\n * \\return The updated function.\n */\nPrimFunc BindParams(PrimFunc f, const Array<runtime::NDArray>& constants);\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_TRANSFORMS_IR_UTILS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/replace_selected_expr.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file replace_selected_expr.h\n * \\brief Interface of the pass that replaces in a statement\n           or expression all the subexpressions that are selected\n           with a predicate by another expression.\n */\n\n#ifndef TVM_TIR_TRANSFORMS_REPLACE_SELECTED_EXPR_H_\n#define TVM_TIR_TRANSFORMS_REPLACE_SELECTED_EXPR_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/expr_functor.h>\n#include <tvm/tir/stmt.h>\n#include <tvm/tir/stmt_functor.h>  // For the class StmtExprMutator\n\nnamespace tvm {\nnamespace tir {\n\n/*!\n * \\brief Mutator for replacing the expressions selected by a predicate in a statement and/or\n          in an expression, which only replace inside of nodes in which it is allowed to perform\n          replacecements (given by a second predicate)\n */\nclass ReplaceSelectedExpr : public StmtExprMutator {\n public:\n  // Toplevel (static) functions\n  static PrimExpr ReplaceSelectedExprInExpr(\n      const PrimExpr& expr, std::function<bool(const PrimExpr&)> predicate_selector,\n      const PrimExpr& new_expr, std::function<bool(const PrimExpr&)> can_replace_inside);\n  static Stmt ReplaceSelectedExprInStmt(const Stmt& stmt,\n                                        std::function<bool(const PrimExpr&)> predicate_selector,\n                                        const PrimExpr& new_expr,\n                                        std::function<bool(const PrimExpr&)> can_replace_inside);\n\n protected:\n  // Constructor\n  ReplaceSelectedExpr(std::function<bool(const PrimExpr&)> predicate_selector,\n                      const PrimExpr& new_expr,\n                      std::function<bool(const PrimExpr&)> can_replace_inside);\n\n  PrimExpr VisitExpr(const PrimExpr& expr) override;\n\n private:\n  // The predicate used for selecting what will be replaced\n  std::function<bool(const PrimExpr&)> predicate_selector_;\n  // The expression used for replacing\n  const PrimExpr& new_expr_;\n  // The predicate used for knowning inside which nodes we can do rewriting\n  // (i.e. in which nodes it can recurse)\n  std::function<bool(const PrimExpr&)> can_replace_inside_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n\n#endif  // TVM_TIR_TRANSFORMS_REPLACE_SELECTED_EXPR_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/storage_access.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file storage_access.h\n * \\brief Common data structure for storage access analysis.\n */\n#ifndef TVM_TIR_TRANSFORMS_STORAGE_ACCESS_H_\n#define TVM_TIR_TRANSFORMS_STORAGE_ACCESS_H_\n\n#include <tvm/arith/int_set.h>\n#include <tvm/ir/attrs.h>\n#include <tvm/tir/expr.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <unordered_map>\n#include <vector>\n\n#include \"../../runtime/thread_storage_scope.h\"\n\nnamespace tvm {\nnamespace tir {\n\nusing runtime::StorageRank;\nusing runtime::StorageScope;\n/*!\n * \\brief Base class of storage access analysis\n */\nclass StorageAccessVisitor : public StmtExprVisitor {\n public:\n  /*! \\brief Storage access type */\n  enum AccessType {\n    kRead,\n    kWrite,\n    kSync,\n    kAlloc,\n    // acquired version of read, only need to handle WAR dep.\n    kReadAcquire\n  };\n  /*! \\brief An access entry */\n  struct AccessEntry {\n    /*! \\brief The thread index that access this entry */\n    Array<IterVar> threads;\n    /*! \\brief The buffer variable, if any */\n    Var buffer = NullValue<Var>();\n    /*! \\brief The access data type */\n    DataType dtype;\n    /*! \\brief The touched access range\n     *\n     * Has one IntSet for each index in the buffer being accessed.\n     */\n    Array<arith::IntSet> touched;\n    /*! \\brief The type of access */\n    AccessType type;\n    /*! \\brief The storage scope */\n    StorageScope scope;\n    /*! \\brief Whether the access is double buffer write */\n    bool double_buffer_write = false;\n  };\n  /*! \\brief Access pattern about a single statement */\n  struct StmtEntry {\n    /*! \\brief The statement */\n    const Object* stmt;\n    /*! \\brief access patterns in the statement */\n    std::vector<AccessEntry> access;\n  };\n  // override visitor pattern\n  void VisitExpr_(const LoadNode* op) final;\n  void VisitStmt_(const StoreNode* op) final;\n  void VisitExpr_(const BufferLoadNode* op) final;\n  void VisitStmt_(const BufferStoreNode* op) final;\n  void VisitStmt_(const EvaluateNode* op) final;\n  void VisitStmt_(const AttrStmtNode* op) final;\n  void VisitStmt_(const ForNode* op) final;\n  void VisitStmt_(const IfThenElseNode* op) final;\n  void VisitStmt_(const WhileNode* op) final;\n  void VisitExpr_(const CallNode* op) final;\n\n protected:\n  StorageAccessVisitor() { scope_.push_back(std::vector<StmtEntry>()); }\n  /*! \\return number of conditions in the current scope. */\n  int condition_counter() const { return condition_counter_; }\n  /*! \\return whether we are in device environment. */\n  bool in_device_env() const { return in_device_env_; }\n  /*! \\return environment threads */\n  const Array<IterVar>& env_threads() const { return env_threads_; }\n  /*!\n   * \\brief Whether we need analyze the buffer in current scope.\n   * \\param buffer The buffer to be checked\n   * \\param scope The scope of the buffer.\n   * \\return Whether the analysis of buffer is enabled.\n   */\n  virtual bool Enabled(const VarNode* buffer, const StorageScope& scope) const { return true; }\n  /*!\n   * \\brief Summarize the sequence of operations into parent.\n   *\n   *  Insert synchronization if necessary and remove un-necessary\n   *  memory access which are already synced.\n   *\n   * \\param seq The sequence of the access operations.\n   * \\param loop Pass loop node if it is a loop, otherwise nullptr.\n   * \\return The summarized sequence that represent access that\n   *  the parent should taken care of to synchronize.\n   */\n  virtual std::vector<AccessEntry> Summarize(std::vector<StmtEntry> seq, const ForNode* loop) = 0;\n  /*!\n   * \\brief Get the scope of the buffer array.\n   * \\return The scope of the final buffer array.\n   */\n  StorageScope GetScope(Var buffer_var) const;\n  // access scope\n  std::vector<std::vector<StmtEntry>> scope_;\n\n private:\n  // whether access appending is enabled.\n  bool allow_append_{false};\n  // Whether we are in device environment\n  bool in_device_env_{false};\n  // Whether we are inside condition.\n  int condition_counter_{0};\n  // The current double buffer write scope.\n  const VarNode* double_buffer_write_{nullptr};\n  // the current free stmt entry.\n  StmtEntry curr_stmt_;\n  // The involving threads\n  Array<IterVar> env_threads_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_TRANSFORMS_STORAGE_ACCESS_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "src/tir/transforms/update_pointer_storage_scope.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file update_pointer_storage_scope.h\n * \\brief A pass to update storage scopes for buffer variables.\n */\n#ifndef TVM_TIR_TRANSFORMS_UPDATE_POINTER_STORAGE_SCOPE_H_\n#define TVM_TIR_TRANSFORMS_UPDATE_POINTER_STORAGE_SCOPE_H_\n\n#include <tvm/tir/expr.h>\n#include <tvm/tir/op.h>\n#include <tvm/tir/stmt_functor.h>\n\n#include <unordered_map>\n\nnamespace tvm {\nnamespace tir {\n\nclass UpdatePointerStorageScope : public StmtExprMutator {\n public:\n  explicit UpdatePointerStorageScope(\n      const std::unordered_map<const VarNode*, String>& new_storage_scopes);\n\n  virtual PrimExpr VisitExpr_(const VarNode*);\n  virtual PrimExpr VisitExpr_(const LoadNode*);\n  virtual PrimExpr VisitExpr_(const BufferLoadNode*);\n  virtual Stmt VisitStmt_(const AllocateNode*);\n  virtual Stmt VisitStmt_(const StoreNode*);\n  virtual Stmt VisitStmt_(const BufferStoreNode*);\n\n private:\n  template <typename Node>\n  Node UpdateBufferAccess(Node node);\n\n  Buffer GetUpdatedBuffer(Buffer buf);\n\n  std::unordered_map<const VarNode*, Var> new_var_remap_;\n  std::unordered_map<const BufferNode*, Buffer> new_buffer_remap_;\n};\n\n}  // namespace tir\n}  // namespace tvm\n#endif  // TVM_TIR_TRANSFORMS_UPDATE_POINTER_STORAGE_SCOPE_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "test.py",
        "content": "import tvm\nfrom tvm import relay, ir\nfrom tvm.relay import testing\nfrom tvm.mrt.utils import *\n\nfrom tvm.mrt import api, runtime, image, extool, data\nfrom tvm.mrt import stats, dataset\nfrom tvm.mrt import utils\n\nimport sys\nimport numpy as np\n\nbatch_size = 1\n\ndef load_model_from_mx() -> (ir.IRModule, ParametersT):\n    import mxnet as mx\n    spath, ppath = gluon.save_model(\"resnet18_v1\", ctx=mx.cpu())\n    print(spath, ppath)\n    symbol, params = gluon.load_model(spath, ppath)\n    return relay.frontend.from_mxnet(symbol, arg_params=params)\n\n\n\nif False:\n    num_class = 10\n    image_shape = (1, 28, 28)\n    mod, params = testing.mlp.get_workload(\n            num_classes=num_class,\n            image_shape=image_shape,\n            batch_size=batch_size)\nelse:\n    num_class = 1000\n    image_shape = (3, 224, 224)\n    out_shape = (batch_size, num_class)\n    #  mod, params = load_model_from_mx()\n    #  mod, params = testing.resnet.get_workload(\n    #          batch_size=batch_size,\n    #          num_classes=num_class,\n    #          num_layers=18,\n    #          image_shape=image_shape,)\n\ndata_shape = (batch_size,) + image_shape\n\ndef load_model_from_torch() -> (ir.IRModule, ParametersT):\n    import torch\n    from torchvision import models\n\n    weights = models.ResNet18_Weights.IMAGENET1K_V1\n    model = models.resnet18(weights=weights)\n    model = model.eval()\n    input_data = torch.randn(data_shape)\n    script_module = torch.jit.trace(model, [input_data]).eval()\n    return relay.frontend.from_pytorch(\n            script_module, [ (\"input\", data_shape) ])\n\nmod, params = load_model_from_torch()\n\nmod: tvm.IRModule = mod\nfunc: relay.function.Function = mod[\"main\"]\nexpr: ir.RelayExpr = func.body\n\n#  expr.simple_raw_print(mod[\"main\"].body, params)\n\n\nrelay.Var\nrelay.var\nrelay.nn.conv2d\nrelay.nn.batch_flatten\nrelay.nn.batch_norm\nrelay.Tuple\nrelay.TupleGetItem\nrelay.expr.TupleWrapper\nir.tensor_type.TensorType\nir.type.TupleType\n\n# mrt_model = model.from_mod(mod, params)\n# mrt_model = mrt_model.set_input_shape((16,) + image_shape)\n# mrt_model.print()\n# mod = mrt_model.to_mod()\n# mod: tvm.IRModule = relay.transform.InferType()(mod)\n# print(mod.astext(show_meta_data=False))\n\n#  tr = api.Trace(\"init\", expr, params).infer_type()\n\nfrom tvm.mrt import trace\nfrom tvm.mrt.symbol import *\ntr = trace.Trace.from_expr(expr, params)\n\n@filter_operators(TUPLE_GET_ITEM_NAME)\ndef fuse_batch_norm(expr: relay.expr.Call, params: ParametersT):\n    if extool.op_name(expr.tuple_value) == \"nn.batch_norm\":\n        return expr.tuple_value.args[0]\n    assert False\n\n#  tr = tr.transform(fuse_batch_norm)\n\nfrom tvm.mrt.calibrate import Calibrator\n#  def calibrate(sym: Symbol, params: ParametersT):\n#      #  print(\"apply calibrate for {}\".format(sym))\n#      data = None\n#      if is_input(sym, params):\n#          data = np.random.randn(*sym.shape).astype(sym.dtype)\n#          data = tvm.nd.array(data)\n#      elif is_param(sym, params):\n#          data = params[sym.name]\n#      return sym.clone(Calibrator, init_data=data)\n\ntvm.nd.NDArray\ntr.print()\n#  calibrate_tr = tr.transform(calibrate)\ncalibrate_tr = tr.transform(Calibrator.apply())\n\nprint(\"\\n\\n\\n\")\ndef _cast(sym: Calibrator, params: ParametersT):\n    print(\"cast: \", sym.output[0].shape)\ncalibrate_tr.transform(_cast)\nsys.exit(1)\n# ctx = tvm.runtime.cuda(1)\n\nfrom tvm.mrt.fuse import FusionOp\ndef fuse(sym: Symbol, params: ParametersT):\n    return sym.clone(FusionOp, params=params)\n\nfuse_tr = tr.transform(fuse)\n\nsys.exit(1)\n\n#  print(\"\\n\", expr.astext(show_meta_data=False))\nfrom torch.utils.data import DataLoader\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\nimport PIL\n\ndef to_tensor(img: PIL.Image.Image):\n    img = img.resize(image_shape[1:])\n    img = np.array(img).astype(\"float32\")\n    img = np.transpose(img, (2, 1, 0))\n    return img\n\nval_data = datasets.ImageFolder(\n        path.join(utils.MRT_DATASET_ROOT, \"imagenet/val\"),\n        transform=to_tensor)\ndata_loader = DataLoader(val_data, batch_size=1)\n\n#  class TorchImageNet(dataset.Dataset):\n#      def __init__(self):\n#          self.data_loader = data_loader\n#          self._max = len(self.data_loader)\n#          self.reset()\n\n#      def reset(self):\n#          self._iter = iter(self.data_loader)\n\n#      def next(self):\n#          try:\n#              data, label = next(self._iter)\n#              return data.numpy(), label.numpy()\n#          except Exception as e:\n#              return None\n\n#  data, label = next(iter(data_loader))\n#  data, label = data.numpy(), label.numpy()\n#  print(type(data), data.shape, type(label), label)\n#  sys.exit(1)\n\n# tr.print()\n# outs = tr.calibrate()\n# print(outs.keys())\n\n# tr_eval = tr.eval(ctx)\n# runtime.multiple_validate(tr_eval, TorchImageNet(),\n#         stats.ClassificationOutput,)\n\n# test accuracy\n#  data = image.get_real_image(*image_shape[1:])\nres = tr.run(data, device=ctx)\n#  res = mrt_model.run(data)\n#  print(res.shape, res.dtype)\n# input_data = data.random_inputs(new_expr, params)\n# res = runtime.infer(new_expr, input_data)\nout = stats.ClassificationOutput()\nout.merge([res[0], [0,]])\nout.dl_info()\nprint(\"labels: \", dataset.ImageNet().labels(out.dl_top5[0]))\n\n# fuse pass: fold_constant, fuse_batch_norm, quantize\n\n# compare accuracy\n\n# to_cvm\n\n# for k, v in params.items():\n#     print(k, type(v))\n#     continue\n# set show_meta_data=True if you want to show meta data\n# print(mod.astext(show_meta_data=False))\n\n# @ir.transform.module_pass(opt_level=2)\n# def transform(mod, ctx):\n#     tp = relay.TensorType((10,), \"float32\")\n#     x = relay.var(\"x\", tp)\n#     func = relay.Function([x], relay.abs(x))\n#     gv = relay.GlobalVar(\"myabs\")\n#     # new_mod = tvm.IRModule({gv: func})\n#     new_mod = tvm.IRModule()\n#     new_mod[\"myabs\"] = func\n#     new_mod.update(mod)\n#     return new_mod\n\n# print(relay.analysis.all_vars(mod[\"main\"]))\n\n# module_pass = transform\n# assert isinstance(module_pass, ir.transform.ModulePass)\n# assert module_pass.info.opt_level == 2\n\nx = relay.var(\"x\", shape=(1, 3, 28, 28), dtype=\"float32\")\ny = relay.var(\"y\", shape=(28,), dtype=\"float32\")\nout = x + y\nout = relay.abs(out)\na = relay.Constant(tvm.nd.array(np.ones((28,), dtype=\"float32\")))\nb = relay.Constant(tvm.nd.array(np.ones((28,), dtype=\"float32\")))\nc = a + b\nout = out + c\nrelay.analysis.post_order_visit(out, _collect_ops)\n\nmod = tvm.IRModule()\nmod[\"main\"] = relay.Function([x, y], out)\nmod = relay.transform.FoldConstant()(mod)\n\nprint(mod.astext(show_meta_data=False))\nsys.exit(1)\n\n# mod = tvm.IRModule()\n# mod[\"main\"] = relay.Function([x, y], out)\n# print(str(mod))\n\n# mod = module_pass(mod)\n# print(\"2\", str(mod))\n\n# # out = mod[\"myabs\"](out)\n# # mod[\"main\"] = relay.Function([x, y], out)\n# # print(\"1\", str(mod))\n\n# # mod = create_relay_module_from_model() # Output: Figure 1\nimport pprint\nfrom tvm.relay.op.contrib import register\nfrom tvm.relay.op.contrib import cvm\npattern_table = register.get_pattern_table(\"cvm\")\npprint.pprint([p[0] for p in pattern_table])\nmod = relay.transform.MergeComposite(pattern_table)(mod)\n#  mod = relay.transform.AnnotateTarget([\"dnnl\"])(mod) # Output: Figure 2\n#  mod = relay.transform.MergeCompilerRegions()(mod) # Output: Figure 3\n#  mod = relay.transform.PartitionGraph()(mod) # Output: Figure 4\nprint(\"3\", mod.astext(show_meta_data=False))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/crt/buffer_write_stream.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#ifndef TESTS_CRT_BUFFER_WRITE_STREAM_H_\n#define TESTS_CRT_BUFFER_WRITE_STREAM_H_\n\n#include <inttypes.h>\n#include <tvm/runtime/crt/rpc_common/frame_buffer.h>\n#include <tvm/runtime/crt/rpc_common/write_stream.h>\n\n#include <string>\n\nusing ::tvm::runtime::micro_rpc::FrameBuffer;\nusing ::tvm::runtime::micro_rpc::WriteStream;\n\ntemplate <unsigned int N>\nclass BufferWriteStream : public WriteStream {\n public:\n  ssize_t Write(const uint8_t* data, size_t data_size_bytes) override {\n    return buffer_.Write(data, data_size_bytes);\n  }\n\n  void Reset() {\n    buffer_.Clear();\n    packet_done_ = false;\n  }\n\n  inline bool packet_done() { return packet_done_; }\n\n  inline bool is_valid() { return is_valid_; }\n\n  void PacketDone(bool is_valid) override {\n    EXPECT_FALSE(packet_done_);\n    packet_done_ = true;\n    is_valid_ = is_valid;\n  }\n\n  std::string BufferContents() { return std::string((const char*)buffer_data_, buffer_.Size()); }\n\n  static constexpr unsigned int capacity() { return N; }\n\n private:\n  bool packet_done_{false};\n  bool is_valid_{false};\n  uint8_t buffer_data_[N];\n  FrameBuffer buffer_{buffer_data_, N};\n};\n\n#endif  // TESTS_CRT_BUFFER_WRITE_STREAM_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/crt/contrib/stm32/src/main.c",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include <inttypes.h>\n#include <math.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"ai_runtime_api.h\"\n#include \"network.h\"\n#include \"network_data.h\"\n\n//\n// Network that we are testing\n//\nextern ai_model_info network_network;\n\n//\n// Dummy: for the runtime\n//\nuint32_t __models_section_start__ = (uint32_t)&network_network;\nuint32_t __models_section_end__ = (uint32_t)&network_network + sizeof(ai_model_info);\n\nstatic ai_model_info* _model_p = &network_network;\n\n//\n// Global handle to reference the instantiated NN\n//\nstatic ai_handle _network = AI_HANDLE_NULL;\n\nstatic uint8_t LoadInputImg(const char* filename, ai_tensor* input);\nstatic int32_t quantize_val(float val, ai_quantization_info* quant);\nstatic float dequantize_val(int32_t val, ai_quantization_info* quant);\n\n// =================================================================\n//   Convert_Fixed_To_Float\n// =================================================================\nstatic float Convert_Fixed_To_Float(uint8_t data, int8_t fl) {\n  uint8_t val = data;\n  float x;\n  if (fl >= 0) {\n    x = ((float)val) / (float)(1 << fl);  // NOLINT\n  } else {\n    x = ((float)val) / (1 / (float)(1 << fl));  // NOLINT\n  }\n  return x;\n}\n\n// =======================================================\n//    error\n// =======================================================\nstatic void error(const char* fmt, ...) {\n  va_list vp;\n  char emsg[512];\n  int32_t loc = 0;\n\n  //\n  // Prepare main error message:\n  //\n  va_start(vp, fmt);\n  loc += vsprintf(&emsg[loc], fmt, vp);\n  va_end(vp);\n\n  // fputs (emsg, stderr);\n  // fflush (stderr);\n\n  fprintf(stderr, \" #### Error: %s.\\n\", emsg);\n\n  exit(-1);\n}\n\n// ==================================================\n//   aiLogErr\n// ==================================================\nstatic void aiLogErr(const char* fct, const char* msg) {\n  if (fct) {\n    printf(\"E: AI error: %s - %s\\r\\n\", fct, msg);\n  } else {\n    printf(\"E: AI error - %s\\r\\n\", msg);\n  }\n}\n\n// ==================================================\n//   aiPrintLayoutBuffer\n// ==================================================\nstatic void aiPrintLayoutBuffer(const char* msg, int idx, ai_tensor* tensor) {\n  DLTensor* dltensor = get_dltensor(tensor);\n  DLDataType dtype = dltensor->dtype;\n\n  printf(\"%s[%d] \", msg, idx);\n  printf(\" (%u, %u, %u)\", dtype.code, dtype.bits, dtype.lanes);\n  //\n  // Quantization info exists for input/output tensors\n  //\n  const ai_quantization_info* quant = ai_get_quantization(tensor);\n  if (quant != NULL) {\n    printf(\" -- TODO: quantization info \\n\");\n  }\n\n  int32_t size = get_tensor_size(tensor);\n  printf(\" %d bytes, shape=(\", size);\n  for (int i = 0; i < dltensor->ndim; ++i) {\n    printf(\"%d,\", (int32_t)dltensor->shape[i]);\n  }\n  printf(\"), address = 0x%08x\\r\\n\", (unsigned int)dltensor->data);\n}\n\n// ==================================================\n//   aiPrintNetworkInfo\n// ==================================================\nstatic void aiPrintNetworkInfo(ai_handle network) {\n  const char* name = ai_get_name(network);\n  const char* datetime = ai_get_datetime(network);\n  const char* revision = ai_get_revision(network);\n  const char* tool_version = ai_get_tool_version(network);\n  const char* api_version = ai_get_api_version(network);\n\n  uint32_t n_nodes = ai_get_node_size(network);\n  uint32_t n_inputs = ai_get_input_size(network);\n  uint32_t n_outputs = ai_get_output_size(network);\n\n  uint32_t activations_size = ai_get_activations_size(network);\n  uint32_t params_size = ai_get_params_size(network);\n\n  printf(\"Network configuration...\\r\\n\");\n  printf(\" Model name         : %s\\r\\n\", name);\n  printf(\" Compile datetime   : %s\\r\\n\", datetime);\n  printf(\" Tool revision      : %s (%s)\\r\\n\", revision, tool_version);\n  printf(\" API version        : %s\\r\\n\", api_version);\n  printf(\"Network info...\\r\\n\");\n  printf(\"  nodes             : %d\\r\\n\", n_nodes);\n  printf(\"  activation        : %d bytes\\r\\n\", activations_size);\n  printf(\"  params            : %d bytes\\r\\n\", params_size);\n  printf(\"  inputs/outputs    : %u/%u\\r\\n\", n_inputs, n_outputs);\n}\n\n// ======================================================\n//   aiInit\n// ======================================================\nstatic int aiInit(void) {\n  ai_status err = AI_STATUS_OK;\n\n  const char* nn_name = AI_MODEL_name(_model_p);\n  ai_ptr built_in_activations = AI_MODEL_activations(_model_p);\n\n  //\n  // Creating the network\n  //\n  printf(\"Creating the network \\\"%s\\\"..\\r\\n\", nn_name);\n\n  err = ai_create(_model_p, built_in_activations, &_network);\n  if (err != AI_STATUS_OK) {\n    const char* msg = ai_get_error(_network);\n    aiLogErr(\"ai_create\", msg);\n    return -1;\n  }\n\n  //\n  // Query the created network to get relevant info from it\n  //\n  aiPrintNetworkInfo(_network);\n\n  uint32_t n_inputs = ai_get_input_size(_network);\n  uint32_t n_outputs = ai_get_output_size(_network);\n  uint32_t activations_size = ai_get_activations_size(_network);\n  uint32_t params_size = ai_get_params_size(_network);\n\n  const ai_ptr params = ai_get_params(_network);\n  ai_ptr activations = ai_get_activations(_network);\n\n  printf(\"Weights buffer     : 0x%08x %d bytes)\\r\\n\", (unsigned int)params,\n         (unsigned int)params_size);\n  printf(\"Activation buffer  : 0x%08x (%d bytes) %s\\r\\n\", (unsigned int)activations,\n         (unsigned int)activations_size,\n         ((uint32_t)activations & (uint32_t)0xFF000000) ? \"internal\" : \"external\");\n\n  printf(\"Inputs:\\r\\n\");\n  for (int i = 0; i < n_inputs; i++) {\n    ai_tensor* input = ai_get_input(_network, i);\n    aiPrintLayoutBuffer(\"   I\", i, input);\n  }\n\n  printf(\"Outputs:\\r\\n\");\n  for (int i = 0; i < n_outputs; i++) {\n    ai_tensor* output = ai_get_output(_network, i);\n    aiPrintLayoutBuffer(\"   O\", i, output);\n  }\n\n  return 0;\n}\n\n// ======================================================\n//   aiDeInit\n// ======================================================\nstatic void aiDeInit(void) {\n  ai_status err = AI_STATUS_OK;\n\n  printf(\"Releasing the network(s)...\\r\\n\");\n\n  if (ai_destroy(_network) != AI_STATUS_OK) {\n    const char* err = ai_get_error(_network);\n    aiLogErr(\"ai_destroy\", err);\n  }\n  _network = AI_HANDLE_NULL;\n  return;\n}\n\n// =================================================================\n//   argmax\n//\n//   Description  : return argument of table maximum value\n//   Argument     : Vector_db *vec: table\n//   Return Value : int: index of max value\n// =================================================================\nstatic uint8_t argmax(int8_t* vec, uint32_t num) {\n  uint32_t i;\n  uint8_t arg = 0;\n  int8_t imax = vec[0];\n  for (i = 1; i < num; i++) {\n    imax = (imax > vec[i]) ? imax : vec[i];\n    if (imax == vec[i]) {\n      arg = i;\n    }\n  }\n  return (arg);\n}\n\n// ======================================================\n//   aiRun\n// ======================================================\nstatic int aiRun(void) {\n  ai_status err = AI_STATUS_OK;\n\n  //\n  // Inputs\n  //\n  ai_tensor* input = ai_get_input(_network, 0);\n  if (input == NULL) {\n    const char* err = ai_get_error(_network);\n    aiLogErr(\"ai_run\", err);\n    return -1;\n  }\n\n  //\n  // Outputs\n  //\n  ai_tensor* output = ai_get_output(_network, 0);\n  if (output == NULL) {\n    const char* err = ai_get_error(_network);\n    aiLogErr(\"ai_run\", err);\n    return -1;\n  }\n\n  DLDataType out_dtype = output->dltensor.dtype;\n  if (out_dtype.lanes > 1) {\n    printf(\"E: vector outputs are not supported ...\\r\\n\");\n    return -1;\n  }\n\n  uint32_t elts = get_tensor_elts(output);\n\n  char outfile_name[128];\n  sprintf(outfile_name, \"%s/tvm_results.txt\", BUILD_PATH);  // NOLINT\n  FILE* outfile = fopen(outfile_name, \"w\");\n\n  for (int i = 0; i <= 9; i++) {\n    char image[128];\n\n    sprintf(image, \"%s/0%d.raw\", IMAGE_PATH, i);  // NOLINT\n    printf(\"Loading input image %s ... \\n\", image);\n    if (LoadInputImg(image, input) != 0) {\n      error(\"Loading image %s\\n\", image);\n    }\n\n    //\n    // Run the inference\n    //\n    printf(\"Running the network\\r\\n\");\n\n    if (ai_run(_network) != AI_STATUS_OK) {\n      const char* err = ai_get_error(_network);\n      aiLogErr(\"ai_run\", err);\n      return -1;\n    }\n\n    const ai_quantization_info* output_quant = ai_get_quantization(output);\n    if (output_quant == NULL) {\n      //\n      // Floating point model\n      //\n      float* probabilities = (float*)output->dltensor.data;  // NOLINT\n      for (int i = 0; i < elts; i++) {\n        float val = probabilities[i];\n        // printf (\" -- probability[%d] = %g \\n\", i, val);\n        fprintf(outfile, \"%g \", val);\n      }\n\n    } else {\n      //\n      // Quantized model\n      //\n      if (out_dtype.code == kDLInt) {\n        int8_t* probabilities = (int8_t*)output->dltensor.data;  // NOLINT\n        for (int i = 0; i < elts; i++) {\n          int8_t qval = probabilities[i];\n          // printf (\" -- probability[%d] = %d \\n\", i, qval);\n          float val = dequantize_val(qval, output_quant);\n          fprintf(outfile, \"%g \", val);\n        }\n      } else {\n        uint8_t* probabilities = (uint8_t*)output->dltensor.data;  // NOLINT\n        for (int i = 0; i < elts; i++) {\n          uint8_t qval = probabilities[i];\n          // printf (\" -- probability[%d] = %d \\n\", i, qval);\n          float val = dequantize_val(qval, output_quant);\n          fprintf(outfile, \"%g \", val);\n        }\n      }\n    }\n    fprintf(outfile, \"\\n\");\n  }\n  fclose(outfile);\n\n  return 0;\n}\n\n// =================================================================\n//   quantize_val\n// =================================================================\nstatic int32_t quantize_val(float val, ai_quantization_info* quant) {\n  float new_val;\n  float input_scale = quant->scale[0];\n  int32_t input_zero_point = quant->zero_point[0];\n  new_val = val / input_scale + input_zero_point;\n  return (int32_t)new_val;\n}\n\n// =================================================================\n//   dequantize_val\n// =================================================================\nstatic float dequantize_val(int32_t val, ai_quantization_info* quant) {\n  float new_val;\n  float output_scale = quant->scale[0];\n  int32_t output_zero_point = quant->zero_point[0];\n  new_val = (val - output_zero_point) * output_scale;\n  return new_val;\n}\n\n// =================================================================\n//   LoadInputImg\n// =================================================================\nuint8_t LoadInputImg(const char* filename, ai_tensor* input) {\n  DLDataType dtype = input->dltensor.dtype;\n\n  const ai_quantization_info* input_quant = ai_get_quantization(input);\n\n  if (dtype.lanes > 1) {\n    printf(\"E: vector inputs are not supported ...\\r\\n\");\n    return -1;\n  }\n\n  if (dtype.code == kDLBfloat) {\n    printf(\"E: Double float inputs are not supported ...\\r\\n\");\n    return -1;\n  }\n\n  FILE* file = fopen(filename, \"r\");\n  if (file == NULL) {\n    printf(\"== File %s not found\\n\", filename);\n    return (-1);\n  }\n\n  //\n  // Find file size\n  //\n  fseek(file, 0L, SEEK_END);\n  size_t img_size = ftell(file);\n  (void)fseek(file, 0L, SEEK_SET);\n\n  // printf (\"== Image size = %d\\n\", img_size);\n\n  uint8_t* image = (uint8_t*)malloc(img_size);  // NOLINT\n  size_t size = fread(image, 1, img_size, file);\n  if (size != img_size) {\n    perror(\"fread\");\n    printf(\"== Problem reading %s\\n\", filename);\n    return (-1);\n  }\n\n  fclose(file);\n\n  uint32_t x;\n  uint8_t* p = image;\n  uint8_t* pg = (uint8_t*)input->dltensor.data;  // NOLINT\n\n  for (x = 0; x < img_size; x++) {\n    uint8_t val = p[x];\n    //\n    // Input image needs to be normalized into [0..1] interval\n    //\n    float nval = ((float)val) / 255.0;  // NOLINT\n    if (input_quant != NULL) {\n      if (dtype.code == kDLInt) {\n        int8_t qval = quantize_val(nval, input_quant);\n        *pg = qval;\n        pg += sizeof(int8_t);\n      } else {\n        uint8_t qval = quantize_val(nval, input_quant);\n        *pg = qval;\n        pg += sizeof(uint8_t);\n      }\n    } else {\n      *(float*)pg = nval;  // NOLINT\n      pg += sizeof(float);\n    }\n  }\n\n  free(image);\n\n  return 0;\n}\n\n// ======================================================\n//   main\n// ======================================================\nint main(int argc, char* argv[]) {\n  int status;\n\n  status = aiInit();\n  if (status != 0) {\n    printf(\"Error initializing.\\n\");\n  }\n\n  status = aiRun();\n  if (status != 0) {\n    printf(\"Error running.\\n\");\n  }\n\n  aiDeInit();\n\n  return (0);\n}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/add_asf_header.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Helper tool to add ASF header to files that cannot be handled by Rat.\"\"\"\nimport os\nimport sys\n\nheader_cstyle = \"\"\"\n/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\"\"\".strip()\n\nheader_mdstyle = \"\"\"\n<!--- Licensed to the Apache Software Foundation (ASF) under one -->\n<!--- or more contributor license agreements.  See the NOTICE file -->\n<!--- distributed with this work for additional information -->\n<!--- regarding copyright ownership.  The ASF licenses this file -->\n<!--- to you under the Apache License, Version 2.0 (the -->\n<!--- \"License\"); you may not use this file except in compliance -->\n<!--- with the License.  You may obtain a copy of the License at -->\n\n<!---   http://www.apache.org/licenses/LICENSE-2.0 -->\n\n<!--- Unless required by applicable law or agreed to in writing, -->\n<!--- software distributed under the License is distributed on an -->\n<!--- \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->\n<!--- KIND, either express or implied.  See the License for the -->\n<!--- specific language governing permissions and limitations -->\n<!--- under the License. -->\n\"\"\".strip()\n\nheader_pystyle = \"\"\"\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\".strip()\n\nheader_rststyle = \"\"\"\n..  Licensed to the Apache Software Foundation (ASF) under one\n    or more contributor license agreements.  See the NOTICE file\n    distributed with this work for additional information\n    regarding copyright ownership.  The ASF licenses this file\n    to you under the Apache License, Version 2.0 (the\n    \"License\"); you may not use this file except in compliance\n    with the License.  You may obtain a copy of the License at\n\n..    http://www.apache.org/licenses/LICENSE-2.0\n\n..  Unless required by applicable law or agreed to in writing,\n    software distributed under the License is distributed on an\n    \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n    KIND, either express or implied.  See the License for the\n    specific language governing permissions and limitations\n    under the License.\n\"\"\".strip()\n\nheader_groovystyle = \"\"\"\n// Licensed to the Apache Software Foundation (ASF) under one\n// or more contributor license agreements.  See the NOTICE file\n// distributed with this work for additional information\n// regarding copyright ownership.  The ASF licenses this file\n// to you under the Apache License, Version 2.0 (the\n// \"License\"); you may not use this file except in compliance\n// with the License.  You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.  See the License for the\n// specific language governing permissions and limitations\n// under the License.\n\"\"\".strip()\n\nheader_cmdstyle = \"\"\"\n:: Licensed to the Apache Software Foundation (ASF) under one\n:: or more contributor license agreements.  See the NOTICE file\n:: distributed with this work for additional information\n:: regarding copyright ownership.  The ASF licenses this file\n:: to you under the Apache License, Version 2.0 (the\n:: \"License\"); you may not use this file except in compliance\n:: with the License.  You may obtain a copy of the License at\n::\n::   http://www.apache.org/licenses/LICENSE-2.0\n::\n:: Unless required by applicable law or agreed to in writing,\n:: software distributed under the License is distributed on an\n:: \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n:: KIND, either express or implied.  See the License for the\n:: specific language governing permissions and limitations\n:: under the License.\n\"\"\".strip()\n\nFMT_MAP = {\n    \"sh\": header_pystyle,\n    \"cc\": header_cstyle,\n    \"c\": header_cstyle,\n    \"mm\": header_cstyle,\n    \"m\": header_cstyle,\n    \"go\": header_cstyle,\n    \"java\": header_cstyle,\n    \"h\": header_cstyle,\n    \"py\": header_pystyle,\n    \"toml\": header_pystyle,\n    \"yml\": header_pystyle,\n    \"yaml\": header_pystyle,\n    \"rs\": header_cstyle,\n    \"md\": header_mdstyle,\n    \"cmake\": header_pystyle,\n    \"mk\": header_pystyle,\n    \"rst\": header_rststyle,\n    \"gradle\": header_groovystyle,\n    \"tcl\": header_pystyle,\n    \"xml\": header_mdstyle,\n    \"storyboard\": header_mdstyle,\n    \"pbxproj\": header_cstyle,\n    \"plist\": header_mdstyle,\n    \"xcworkspacedata\": header_mdstyle,\n    \"html\": header_mdstyle,\n    \"bat\": header_cmdstyle,\n}\n\n\ndef copyright_line(line):\n    # Following two items are intentionally break apart\n    # so that the copyright detector won\"t detect the file itself.\n    if line.find(\"Copyright \" + \"(c)\") != -1:\n        return True\n    # break pattern into two lines to avoid false-negative check\n    spattern1 = \"Copyright\"\n    if line.find(spattern1) != -1 and line.find(\"by\") != -1:\n        return True\n    return False\n\n\ndef add_header(fname, header):\n    \"\"\"Add header to file\"\"\"\n    if not os.path.exists(fname):\n        print(\"Cannot find %s ...\" % fname)\n        return\n\n    lines = open(fname).readlines()\n\n    has_asf_header = False\n    has_copyright = False\n\n    for i, l in enumerate(lines):\n        if l.find(\"Licensed to the Apache Software Foundation\") != -1:\n            has_asf_header = True\n        elif copyright_line(l):\n            has_copyright = True\n            lines[i] = \"\"\n\n    if has_asf_header and not has_copyright:\n        print(\"Skip file %s ...\" % fname)\n        return\n\n    with open(fname, \"w\") as outfile:\n        skipline = False\n        ext = os.path.splitext(fname)[1][1:]\n\n        if not lines:\n            skipline = False  # File is enpty\n        elif lines[0][:2] == \"#!\":\n            skipline = True\n        elif lines[0][:2] == \"<?\":\n            skipline = True\n        elif lines[0].startswith(\"<html>\"):\n            skipline = True\n        elif lines[0].startswith(\"// !$\"):\n            skipline = True\n\n        if skipline:\n            outfile.write(lines[0])\n            if not has_asf_header:\n                outfile.write(header + \"\\n\\n\")\n            outfile.write(\"\".join(lines[1:]))\n        else:\n            if not has_asf_header:\n                outfile.write(header + \"\\n\\n\")\n            outfile.write(\"\".join(lines))\n    if not has_asf_header:\n        print(\"Add header to %s\" % fname)\n    if has_copyright:\n        print(\"Removed copyright line from %s\" % fname)\n\n\ndef main(args):\n    if len(args) != 2:\n        print(\"Usage: python add_asf_header.py <file_list>\")\n\n    for l in open(args[1]):\n        if l.startswith(\"---\"):\n            continue\n        if l.find(\"File:\") != -1:\n            l = l.split(\":\")[-1]\n        fname = l.strip()\n        if len(fname) == 0:\n            continue\n        suffix = fname.split(\".\")[-1]\n        if suffix in FMT_MAP:\n            add_header(fname, FMT_MAP[suffix])\n        elif os.path.basename(fname) == \"gradle.properties\":\n            add_header(fname, FMT_MAP[\"h\"])\n        else:\n            print(\"Cannot handle %s ...\" % fname)\n\n\nif __name__ == \"__main__\":\n    main(sys.argv)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/check_cmake_options.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport re\nfrom pathlib import Path\n\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\n\nLIBINFO_CC = REPO_ROOT / \"src\" / \"support\" / \"libinfo.cc\"\nLIBINFO_CMAKE = REPO_ROOT / \"cmake\" / \"modules\" / \"LibInfo.cmake\"\nCMAKELISTS = REPO_ROOT / \"CMakeLists.txt\"\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(\n        description=\"Check that CMake options are mirrored to libinfo.cc\"\n    )\n\n    with open(CMAKELISTS) as f:\n        cmake = f.readlines()\n\n    with open(LIBINFO_CC) as f:\n        libinfo = f.read()\n\n    with open(LIBINFO_CMAKE) as f:\n        libinfo_cmake = f.read()\n\n    # Read tvm_options from CMakeLists.txt\n    options = []\n    for line in cmake:\n        m = re.search(r\"tvm_option\\((.*?) \", line)\n        if m is not None:\n            options.append(m.groups()[0])\n\n    # Check that each option is present in libinfo.cc\n    missing_lines = []\n    for option in options:\n        expected_line = f'      {{\"{option}\", TVM_INFO_{option}}},'\n        if expected_line not in libinfo:\n            missing_lines.append(expected_line)\n\n    error = False\n    if len(missing_lines) > 0:\n        missing_lines = \"\\n\".join(missing_lines)\n        print(\n            f\"Missing these lines from {LIBINFO_CC.relative_to(REPO_ROOT)}, please update it\\n{missing_lines}\"\n        )\n        error = True\n\n    # Check that each option has a compile defintion in LibInfo.cmake\n    missing_cmake_lines = []\n    for option in options:\n        expected_line = f'    TVM_INFO_{option}=\"${{{option}}}\"'\n        if expected_line not in libinfo_cmake:\n            missing_cmake_lines.append(expected_line)\n\n    if len(missing_cmake_lines) > 0:\n        missing_cmake_lines = \"\\n\".join(missing_cmake_lines)\n        print(\n            f\"Missing these lines from {LIBINFO_CMAKE.relative_to(REPO_ROOT)}, please update it\\n{missing_cmake_lines}\"\n        )\n        error = True\n\n    if error:\n        exit(1)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/check_file_type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Helper tool to check file types that are allowed to checkin.\"\"\"\nimport os\nimport sys\nimport subprocess\n\n# List of file types we allow\nALLOW_EXTENSION = {\n    # source code\n    \"cc\",\n    \"c\",\n    \"h\",\n    \"s\",\n    \"rs\",\n    \"m\",\n    \"mm\",\n    \"g4\",\n    \"gradle\",\n    \"js\",\n    \"tcl\",\n    \"scala\",\n    \"java\",\n    \"go\",\n    \"ts\",\n    \"sh\",\n    \"py\",\n    \"pyi\",\n    \"pxi\",\n    \"pyd\",\n    \"pyx\",\n    \"cu\",\n    \"bat\",\n    # relay text format\n    \"rly\",\n    # configurations\n    \"mk\",\n    \"in\",\n    \"cmake\",\n    \"xml\",\n    \"toml\",\n    \"yml\",\n    \"yaml\",\n    \"json\",\n    # docs\n    \"txt\",\n    \"md\",\n    \"rst\",\n    # sgx\n    \"edl\",\n    \"lds\",\n    # ios\n    \"pbxproj\",\n    \"plist\",\n    \"xcworkspacedata\",\n    \"storyboard\",\n    \"xcscheme\",\n    # hw/chisel\n    \"sbt\",\n    \"properties\",\n    \"v\",\n    \"sdc\",\n    # generated parser\n    \"interp\",\n    \"tokens\",\n    # interface definition\n    \"idl\",\n    # opencl file\n    \"cl\",\n    # zephyr config file\n    \"conf\",\n    # arduino sketch file\n    \"ino\",\n    # linker scripts\n    \"ld\",\n    # Jinja2 templates\n    \"j2\",\n}\n\n# List of file names allowed\nALLOW_FILE_NAME = {\n    \".gitignore\",\n    \".eslintignore\",\n    \".gitattributes\",\n    \"README\",\n    \"Makefile\",\n    \"Doxyfile\",\n    \"pylintrc\",\n    \"condarc\",\n    \"rat-excludes\",\n    \"log4j.properties\",\n    \".clang-format\",\n    \".gitmodules\",\n    \"CODEOWNERSHIP\",\n    \".scalafmt.conf\",\n    \"Cargo.lock\",\n    \"with_the_same_user\",\n}\n\n# List of specific files allowed in relpath to <proj_root>\nALLOW_SPECIFIC_FILE = {\n    \"LICENSE\",\n    \"NOTICE\",\n    \"KEYS\",\n    \"DISCLAIMER\",\n    \"Jenkinsfile\",\n    \"mypy.ini\",\n    # cargo config\n    \"rust/runtime/tests/test_wasm32/.cargo/config\",\n    \"rust/tvm-graph-rt/tests/test_wasm32/.cargo/config\",\n    \"apps/sgx/.cargo/config\",\n    \"apps/wasm-standalone/wasm-graph/.cargo/config\",\n    # html for demo purposes\n    \"web/apps/browser/rpc_server.html\",\n    # images are normally not allowed\n    # discuss with committers before add more images\n    \"apps/android_rpc/app/src/main/res/mipmap-hdpi/ic_launcher.png\",\n    \"apps/android_rpc/app/src/main/res/mipmap-mdpi/ic_launcher.png\",\n    # documentation related files\n    \"docs/_static/css/tvm_theme.css\",\n    \"docs/_static/img/tvm-logo-small.png\",\n    \"docs/_static/img/tvm-logo-square.png\",\n    # pytest config\n    \"pytest.ini\",\n    # microTVM tests\n    \"tests/micro/testdata/mnist/digit-2.jpg\",\n    \"tests/micro/testdata/mnist/digit-9.jpg\",\n    \"tests/micro/testdata/mnist/mnist-8.onnx\",\n    # microTVM Zephyr runtime\n    \"apps/microtvm/zephyr/template_project/CMakeLists.txt.template\",\n    \"apps/microtvm/zephyr/template_project/qemu-hack/qemu-system-arm\",\n    \"apps/microtvm/zephyr/template_project/qemu-hack/qemu-system-xilinx-aarch64\",\n    \"apps/microtvm/zephyr/template_project/qemu-hack/qemu-system-i386\",\n    \"apps/microtvm/zephyr/template_project/qemu-hack/qemu-system-riscv32\",\n    \"apps/microtvm/zephyr/template_project/qemu-hack/qemu-system-riscv64\",\n    \"apps/microtvm/zephyr/template_project/fvp-hack/FVP_Corstone_SSE-300_Ethos-U55\",\n    \"apps/microtvm/zephyr/template_project/app-overlay/nucleo_l4r5zi.overlay\",\n    # microTVM Arduino runtime\n    \"apps/microtvm/arduino/template_project/Makefile.template\",\n    # microTVM CRT\n    \"src/runtime/crt/host/Makefile.template\",\n    # microTVM Virtual Machines\n    \"apps/microtvm/poetry.lock\",\n    \"apps/microtvm/reference-vm/Vagrantfile\",\n    \"apps/microtvm/reference-vm/base-box/Vagrantfile.packer-template\",\n    # Hexagon\n    \"src/runtime/hexagon/rpc/android_bash.sh.template\",\n    \"src/runtime/hexagon/profiler/lwp_handler.S\",\n}\n\n\ndef filename_allowed(name):\n    \"\"\"Check if name is allowed by the current policy.\n\n    Paramaters\n    ----------\n    name : str\n        Input name\n\n    Returns\n    -------\n    allowed : bool\n        Whether the filename is allowed.\n    \"\"\"\n    arr = name.rsplit(\".\", 1)\n    if arr[-1] in ALLOW_EXTENSION:\n        return True\n\n    if os.path.basename(name) in ALLOW_FILE_NAME:\n        return True\n\n    if os.path.basename(name).startswith(\"Dockerfile\"):\n        return True\n\n    if name.startswith(\"3rdparty\"):\n        return True\n\n    if name in ALLOW_SPECIFIC_FILE:\n        return True\n\n    return False\n\n\ndef copyright_line(line):\n    # Following two items are intentionally break apart\n    # so that the copyright detector won't detect the file itself.\n    if line.find(\"Copyright \" + \"(c)\") != -1:\n        return True\n    # break pattern into two lines to avoid false-negative check\n    spattern1 = \"Copyright\"\n    if line.find(spattern1) != -1 and line.find(\"by\") != -1:\n        return True\n    return False\n\n\ndef check_asf_copyright(fname):\n    if fname.endswith(\".png\"):\n        return True\n    if not os.path.isfile(fname):\n        return True\n    has_asf_header = False\n    has_copyright = False\n    try:\n        for line in open(fname):\n            if line.find(\"Licensed to the Apache Software Foundation\") != -1:\n                has_asf_header = True\n            if copyright_line(line):\n                has_copyright = True\n            if has_asf_header and has_copyright:\n                return False\n    except UnicodeDecodeError:\n        pass\n    return True\n\n\ndef main():\n    cmd = [\"git\", \"ls-files\"]\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n    (out, _) = proc.communicate()\n    assert proc.returncode == 0, f'{\" \".join(cmd)} errored: {out}'\n    res = out.decode(\"utf-8\")\n    flist = res.split()\n    error_list = []\n\n    for fname in flist:\n        if not filename_allowed(fname):\n            error_list.append(fname)\n\n    if error_list:\n        report = \"------File type check report----\\n\"\n        report += \"\\n\".join(error_list)\n        report += \"\\nFound %d files that are not allowed\\n\" % len(error_list)\n        report += (\n            \"We do not check in binary files into the repo.\\n\"\n            \"If necessary, please discuss with committers and\"\n            \"modify tests/lint/check_file_type.py to enable the file you need.\\n\"\n        )\n        sys.stderr.write(report)\n        sys.stderr.flush()\n        sys.exit(-1)\n\n    asf_copyright_list = []\n\n    for fname in res.split():\n        if not check_asf_copyright(fname):\n            asf_copyright_list.append(fname)\n\n    if asf_copyright_list:\n        report = \"------File type check report----\\n\"\n        report += \"\\n\".join(asf_copyright_list) + \"\\n\"\n        report += \"------Found %d files that has ASF header with copyright message----\\n\" % len(\n            asf_copyright_list\n        )\n        report += \"--- Files with ASF header do not need Copyright lines.\\n\"\n        report += \"--- Contributors retain copyright to their contribution by default.\\n\"\n        report += \"--- If a file comes with a different license, consider put it under the 3rdparty folder instead.\\n\"\n        report += \"---\\n\"\n        report += \"--- You can use the following steps to remove the copyright lines\\n\"\n        report += \"--- Create file_list.txt in your text editor\\n\"\n        report += \"--- Copy paste the above content in file-list into file_list.txt\\n\"\n        report += \"--- python3 tests/lint/add_asf_header.py file_list.txt\\n\"\n        sys.stderr.write(report)\n        sys.stderr.flush()\n        sys.exit(-1)\n\n    print(\"check_file_type.py: all checks passed..\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/check_request_hook.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport fnmatch\nimport re\nfrom pathlib import Path\nfrom typing import List, Optional\n\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\nEXPECTED = \"\"\"\n# sphinx_gallery_start_ignore\nfrom tvm import testing\n\ntesting.utils.install_request_hook(depth=3)\n# sphinx_gallery_end_ignore\n\"\"\".rstrip()\nIGNORE_PATTERNS = [\"*/micro_tvmc.py\", \"*/micro_train.py\"]\nAPACHE_HEADER_LINES = 16\n\n\ndef find_code_block_line(lines: List[str]) -> Optional[int]:\n    \"\"\"\n    This returns the index in 'lines' of the first line of code in the tutorial\n    or none if there are no code blocks.\n    \"\"\"\n    in_multiline_string = False\n    in_sphinx_directive = False\n\n    i = 0\n    lines = lines[APACHE_HEADER_LINES:]\n    while i < len(lines):\n        line = lines[i].strip()\n        if '\"\"\"' in line:\n            in_multiline_string = not in_multiline_string\n        elif \"# sphinx_gallery_\" in line:\n            in_sphinx_directive = not in_sphinx_directive\n        elif line.startswith(\"#\") or in_sphinx_directive or in_multiline_string or line == \"\":\n            pass\n        else:\n            return i\n        i += 1\n\n    return None\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(\n        description=\"Check that all tutorials/docs override urllib.request.Request\"\n    )\n    parser.add_argument(\n        \"--fix\", action=\"store_true\", help=\"Insert expected code into erroring files\"\n    )\n    args = parser.parse_args()\n\n    gallery_files = (REPO_ROOT / \"gallery\").glob(\"**/*.py\")\n    # gallery_files = [x for x in gallery_files if \"cross_compi\" in str(x)]\n\n    errors = []\n    for file in gallery_files:\n        skip = False\n        for ignored_file in IGNORE_PATTERNS:\n            if fnmatch.fnmatch(str(file), ignored_file):\n                skip = True\n                break\n        if skip:\n            continue\n\n        with open(file) as f:\n            content = f.read()\n\n        if EXPECTED not in content:\n            errors.append((file, None))\n            continue\n\n        index = content.index(EXPECTED)\n        line = content.count(\"\\n\", 0, index) + EXPECTED.count(\"\\n\") + 2\n        expected = find_code_block_line(content.split(\"\\n\"))\n\n        if expected is not None and line < expected:\n            errors.append((file, (line, expected)))\n\n    if args.fix:\n        for error, line_info in errors:\n            with open(error) as f:\n                content = f.read()\n\n            # Note: There must be a little bit of care taken here since inserting\n            # the block between a comment and multiline string will lead to an\n            # empty code block in the HTML output\n            if \"from __future__\" in content:\n                # Place after the last __future__ import\n                new_content = re.sub(\n                    r\"((?:from __future__.*?\\n)+)\", r\"\\1\\n\" + EXPECTED, content, flags=re.MULTILINE\n                )\n            else:\n                # Place in the first codeblock\n                lines = content.split(\"\\n\")\n                position = find_code_block_line(lines)\n                if position is None:\n                    new_content = \"\\n\".join(lines) + EXPECTED + \"\\n\"\n                else:\n                    print(position)\n                    new_content = (\n                        \"\\n\".join(lines[:position])\n                        + EXPECTED\n                        + \"\\n\\n\"\n                        + \"\\n\".join(lines[position:])\n                    )\n\n            with open(error, \"w\") as f:\n                f.write(new_content)\n    else:\n        # Don't fix, just check and print an error message\n        if len(errors) > 0:\n            print(\n                f\"These {len(errors)} file(s) did not contain the expected text to \"\n                \"override urllib.request.Request, it was at the wrong position, or \"\n                \"the whitespace is incorrect.\\n\"\n                \"You can run 'python3 tests/lint/check_request_hook.py --fix' to \"\n                \"automatically fix these errors:\\n\"\n                f\"{EXPECTED}\\n\\nFiles:\"\n            )\n            for file, line_info in errors:\n                if line_info is None:\n                    print(f\"{file} (missing hook)\")\n                else:\n                    actual, expected = line_info\n                    print(f\"{file} (misplaced hook at {actual}, expected at {expected})\")\n            exit(1)\n        else:\n            print(\"All files successfully override urllib.request.Request\")\n            exit(0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/filter_untracked.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport os.path\nimport subprocess\nimport sys\n\n\ndef check_output(args, **kw):\n    proc = subprocess.Popen(args, **kw, stdout=subprocess.PIPE)\n    out, _ = proc.communicate()\n    if proc.returncode:\n        sys.stderr.write(\"exited with code %d: %s\\n\" % (proc.returncode, \" \".join(args)))\n        sys.exit(2)\n\n    if sys.version_info[0] == 2:\n        return unicode(out, \"utf-8\")\n    else:\n        return str(out, \"utf-8\")\n\n\ndef main():\n    script_dir = os.path.dirname(__file__) or os.getcwd()\n    toplevel_dir = check_output([\"git\", \"rev-parse\", \"--show-toplevel\"], cwd=script_dir).strip(\"\\n\")\n    # NOTE: --ignore-submodules because this can drag in some problems related to mounting a git\n    # worktree in the docker VM in a different location than it exists on the host. The problem\n    # isn't quite clear, but anyhow it shouldn't be necessary to filter untracked files in\n    # submodules here.\n    git_status_output = check_output([\"git\", \"status\", \"-s\", \"--ignored\"], cwd=toplevel_dir)\n    untracked = [\n        line[3:]\n        for line in git_status_output.split(\"\\n\")\n        if line.startswith(\"?? \") or line.startswith(\"!! \")\n    ]\n\n    # also add .git in case rat picks up files in .git or the .git file (if a worktree).\n    toplevel_git_dentry = os.path.join(toplevel_dir, \".git\")\n    if os.path.isfile(toplevel_git_dentry):\n        untracked.append(\".git\")\n    else:\n        untracked.append(\".git/\")\n\n    for line in sys.stdin:\n        cleaned_line = line\n        if line[:2] == \"./\":\n            cleaned_line = line[2:]\n        cleaned_line = cleaned_line.strip(\"\\n\")\n        if any(\n            (cleaned_line.startswith(u) if u[-1] == \"/\" else cleaned_line == u) for u in untracked\n        ):\n            continue\n\n        sys.stdout.write(line)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/lint/trailing_newlines.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport fileinput\nimport os\n\n\ndef has_one_trailing_newline(filename: str) -> bool:\n    \"\"\"\n    Returns True if 'filename' has a single trailing newline\n    \"\"\"\n    with open(filename, \"rb\") as f:\n        start_bytes = len(f.read(2))\n        if start_bytes == 0:\n            # empty file\n            return True\n        elif start_bytes == 1:\n            # 1 byte file\n            return False\n        else:\n            # skip to the end\n            f.seek(-2, os.SEEK_END)\n            end_bytes = f.read(2)\n\n            # should be a non-newline followed by a newline\n            return end_bytes[0] != ord(\"\\n\") and end_bytes[1] == ord(\"\\n\")\n\n\nif __name__ == \"__main__\":\n    exit_code = 1\n    for line in fileinput.input():\n        filename = line.rstrip()\n        if not has_one_trailing_newline(filename):\n            exit_code = 0\n            print(filename)\n    exit(exit_code)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/arduino/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\npytest_plugins = [\n    \"tvm.micro.testing.pytest_plugin\",\n]\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n    parser.addoption(\n        \"--arduino-cli-cmd\",\n        default=\"arduino-cli\",\n        help=\"Path to `arduino-cli` command for flashing device.\",\n    )\n\n\ndef pytest_configure(config):\n    config.addinivalue_line(\n        \"markers\", \"requires_hardware: mark test to run only when an Arduino board is connected\"\n    )\n\n\n@pytest.fixture(scope=\"session\")\ndef arduino_cli_cmd(request):\n    return request.config.getoption(\"--arduino-cli-cmd\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/arduino/test_arduino_error_detection.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport pytest\n\nfrom tvm.micro.project_api.server import ServerError\n\nimport test_utils\nimport tvm.testing\n\n\n@pytest.fixture\ndef project(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    return test_utils.make_kws_project(board, arduino_cli_cmd, microtvm_debug, workspace_dir)\n\n\ndef test_blank_project_compiles(workspace_dir, project):\n    project.build()\n\n\n# Add a bug (an extra curly brace) and make sure the project doesn't compile\ndef test_bugged_project_compile_fails(workspace_dir, project):\n    with open(workspace_dir / \"project\" / \"project.ino\", \"a\") as main_file:\n        main_file.write(\"}\\n\")\n    with pytest.raises(ServerError):\n        project.build()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/arduino/test_arduino_rpc_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThis unit test simulates an autotuning workflow, where we:\n1. Instantiate the Arduino RPC server project\n2. Build and flash that project onto our target board\n\n\"\"\"\n\nimport pathlib\nimport sys\nimport numpy as np\nimport onnx\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom PIL import Image\nfrom tvm import relay\nfrom tvm.relay.testing import byoc\nfrom tvm.relay.backend import Executor, Runtime\n\nimport test_utils\n\n\ndef _make_session(model, arduino_board, arduino_cli_cmd, workspace_dir, mod, build_config):\n    project = tvm.micro.generate_project(\n        str(test_utils.TEMPLATE_PROJECT_DIR),\n        mod,\n        workspace_dir / \"project\",\n        {\n            \"board\": arduino_board,\n            \"arduino_cli_cmd\": arduino_cli_cmd,\n            \"project_type\": \"host_driven\",\n            \"verbose\": bool(build_config.get(\"debug\")),\n        },\n    )\n    project.build()\n    project.flash()\n    return tvm.micro.Session(project.transport())\n\n\ndef _make_sess_from_op(\n    model, arduino_board, arduino_cli_cmd, workspace_dir, op_name, sched, arg_bufs, build_config\n):\n    target = tvm.target.target.micro(model)\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.build(sched, arg_bufs, target=target, runtime=runtime, name=op_name)\n\n    return _make_session(model, arduino_board, arduino_cli_cmd, workspace_dir, mod, build_config)\n\n\ndef _make_add_sess(model, arduino_board, arduino_cli_cmd, workspace_dir, build_config):\n    A = tvm.te.placeholder((2,), dtype=\"int8\")\n    B = tvm.te.placeholder((1,), dtype=\"int8\")\n    C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name=\"C\")\n    sched = tvm.te.create_schedule(C.op)\n    return _make_sess_from_op(\n        model, arduino_board, arduino_cli_cmd, workspace_dir, \"add\", sched, [A, B, C], build_config\n    )\n\n\n# The same test code can be executed on both the QEMU simulation and on real hardware.\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_compile_runtime(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_basic_add(sess):\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        system_lib.get_function(\"add\")(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([6, 7])).all()\n\n    with _make_add_sess(model, board, arduino_cli_cmd, workspace_dir, build_config) as sess:\n        test_basic_add(sess)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_platform_timer(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_basic_add(sess):\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        time_eval_f = system_lib.time_evaluator(\n            \"add\", sess.device, number=20, repeat=3, min_repeat_ms=40\n        )\n        result = time_eval_f(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([6, 7])).all()\n        assert result.mean > 0\n        assert len(result.results) == 3\n\n    with _make_add_sess(model, board, arduino_cli_cmd, workspace_dir, build_config) as sess:\n        test_basic_add(sess)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_relay(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    \"\"\"Testing a simple relay graph\"\"\"\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    shape = (10,)\n    dtype = \"int8\"\n\n    # Construct Relay program.\n    x = relay.var(\"x\", relay.TensorType(shape=shape, dtype=dtype))\n    xx = relay.multiply(x, x)\n    z = relay.add(xx, relay.const(np.ones(shape=shape, dtype=dtype)))\n    func = relay.Function([x], z)\n\n    target = tvm.target.target.micro(model)\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(func, target=target, runtime=runtime)\n\n    with _make_session(model, board, arduino_cli_cmd, workspace_dir, mod, build_config) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            mod.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**mod.get_params())\n        x_in = np.random.randint(10, size=shape[0], dtype=dtype)\n        graph_mod.run(x=x_in)\n        result = graph_mod.get_output(0).numpy()\n        tvm.testing.assert_allclose(graph_mod.get_input(0).numpy(), x_in)\n        tvm.testing.assert_allclose(result, x_in * x_in + 1)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_onnx(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    \"\"\"Testing a simple ONNX model.\"\"\"\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # Load test images.\n    this_dir = pathlib.Path(__file__).parent\n    mnist_testdata = this_dir.parent / \"testdata\" / \"mnist\"\n    digit_2 = Image.open(mnist_testdata / \"digit-2.jpg\").resize((28, 28))\n    digit_2 = np.asarray(digit_2).astype(\"float32\")\n    digit_2 = np.expand_dims(digit_2, axis=0)\n\n    digit_9 = Image.open(mnist_testdata / \"digit-9.jpg\").resize((28, 28))\n    digit_9 = np.asarray(digit_9).astype(\"float32\")\n    digit_9 = np.expand_dims(digit_9, axis=0)\n\n    # Load ONNX model and convert to Relay.\n    onnx_model = onnx.load(mnist_testdata / \"mnist-8.onnx\")\n    shape = {\"Input3\": (1, 1, 28, 28)}\n    relay_mod, params = relay.frontend.from_onnx(onnx_model, shape=shape, freeze_params=True)\n    relay_mod = relay.transform.DynamicToStatic()(relay_mod)\n\n    target = tvm.target.target.micro(model)\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        executor = Executor(\"graph\", {\"link-params\": True})\n        lowered = relay.build(relay_mod, target, params=params, executor=executor, runtime=runtime)\n        graph = lowered.get_graph_json()\n\n    with _make_session(\n        model, board, arduino_cli_cmd, workspace_dir, lowered, build_config\n    ) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            graph, session.get_system_lib(), session.device\n        )\n\n        # Send the digit-2 image and confirm that the correct result is returned.\n        graph_mod.set_input(\"Input3\", tvm.nd.array(digit_2))\n        graph_mod.run()\n        result = graph_mod.get_output(0).numpy()\n        print(result)\n        assert np.argmax(result) == 2\n\n        # Send the digit-9 image and confirm that the correct result is returned.\n        graph_mod.set_input(\"Input3\", tvm.nd.array(digit_9))\n        graph_mod.run()\n        result = graph_mod.get_output(0).numpy()\n        assert np.argmax(result) == 9\n\n\ndef check_result(\n    relay_mod,\n    model,\n    arduino_board,\n    arduino_cli_cmd,\n    workspace_dir,\n    map_inputs,\n    out_shape,\n    result,\n    build_config,\n):\n    \"\"\"Helper function to verify results\"\"\"\n    TOL = 1e-5\n    target = tvm.target.target.micro(model)\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(relay_mod, target=target, runtime=runtime)\n\n    with _make_session(\n        model, arduino_board, arduino_cli_cmd, workspace_dir, mod, build_config\n    ) as session:\n        rt_mod = tvm.micro.create_local_graph_executor(\n            mod.get_graph_json(), session.get_system_lib(), session.device\n        )\n        rt_mod.set_input(**mod.get_params())\n        for name, data in map_inputs.items():\n            rt_mod.set_input(name, data)\n        rt_mod.set_input(**mod.get_params())\n        rt_mod.run()\n\n        out_shapes = out_shape if isinstance(out_shape, list) else [out_shape]\n        results = result if isinstance(result, list) else [result]\n\n        for idx, shape in enumerate(out_shapes):\n            out = tvm.nd.empty(shape, device=session.device)\n            out = rt_mod.get_output(idx, out)\n            tvm.testing.assert_allclose(out.numpy(), results[idx], rtol=TOL, atol=TOL)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_byoc_microtvm(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    \"\"\"This is a simple test case to check BYOC capabilities of microTVM\"\"\"\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    x = relay.var(\"x\", shape=(10, 10))\n    w0 = relay.var(\"w0\", shape=(10, 10))\n    w1 = relay.var(\"w1\", shape=(10, 10))\n    w2 = relay.var(\"w2\", shape=(10, 10))\n    w3 = relay.var(\"w3\", shape=(10, 10))\n    w4 = relay.var(\"w4\", shape=(10, 10))\n    w5 = relay.var(\"w5\", shape=(10, 10))\n    w6 = relay.var(\"w6\", shape=(10, 10))\n    w7 = relay.var(\"w7\", shape=(10, 10))\n\n    # C compiler\n    z0 = relay.add(x, w0)\n    p0 = relay.subtract(z0, w1)\n    q0 = relay.multiply(p0, w2)\n\n    z1 = relay.add(x, w3)\n    p1 = relay.subtract(z1, w4)\n    q1 = relay.multiply(p1, w5)\n\n    # Other parts on TVM\n    z2 = relay.add(x, w6)\n    q2 = relay.subtract(z2, w7)\n\n    r = relay.concatenate((q0, q1, q2), axis=0)\n    f = relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r)\n    mod = tvm.IRModule()\n    ann = byoc.CcompilerAnnotator()\n    mod[\"main\"] = ann.visit(f)\n    mod = tvm.relay.transform.PartitionGraph()(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    w_data = []\n    for _ in range(8):\n        w_data.append(np.random.rand(10, 10).astype(\"float32\"))\n\n    map_inputs = {\"w{}\".format(i): w_data[i] for i in range(8)}\n    map_inputs[\"x\"] = x_data\n    check_result(\n        relay_mod=mod,\n        map_inputs=map_inputs,\n        out_shape=(30, 10),\n        result=np.concatenate(\n            (\n                ((x_data + w_data[0]) - w_data[1]) * w_data[2],\n                ((x_data + w_data[3]) - w_data[4]) * w_data[5],\n                x_data + w_data[6] - w_data[7],\n            ),\n            axis=0,\n        ),\n        model=model,\n        build_config=build_config,\n        arduino_board=board,\n        arduino_cli_cmd=arduino_cli_cmd,\n        workspace_dir=workspace_dir,\n    )\n\n\ndef _make_add_sess_with_shape(\n    model, arduino_board, arduino_cli_cmd, workspace_dir, shape, build_config\n):\n    A = tvm.te.placeholder(shape, dtype=\"int8\")\n    C = tvm.te.compute(A.shape, lambda i: A[i] + A[i], name=\"C\")\n    sched = tvm.te.create_schedule(C.op)\n    return _make_sess_from_op(\n        model, arduino_board, arduino_cli_cmd, workspace_dir, \"add\", sched, [A, C], build_config\n    )\n\n\n@pytest.mark.parametrize(\n    \"shape,\",\n    [\n        pytest.param((1 * 1024,), id=\"(1*1024)\"),\n        pytest.param((4 * 1024,), id=\"(4*1024)\"),\n        pytest.param((16 * 1024,), id=\"(16*1024)\"),\n    ],\n)\n@tvm.testing.requires_micro\n@pytest.mark.requires_hardware\ndef test_rpc_large_array(board, arduino_cli_cmd, microtvm_debug, workspace_dir, shape):\n    \"\"\"Test large RPC array transfer.\"\"\"\n    model = test_utils.ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_tensors(sess):\n        a_np = np.random.randint(low=-128, high=127, size=shape, dtype=\"int8\")\n\n        A_data = tvm.nd.array(a_np, device=sess.device)\n        assert (A_data.numpy() == a_np).all()\n        C_data = tvm.nd.array(np.zeros(shape, dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.zeros(shape)).all()\n\n    with _make_add_sess_with_shape(\n        model, board, arduino_cli_cmd, workspace_dir, shape, build_config\n    ) as sess:\n        test_tensors(sess)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/arduino/test_arduino_workflow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pathlib\nimport re\nimport shutil\nimport sys\nimport pytest\n\nimport tvm.testing\n\nimport test_utils\n\n\"\"\"\nThis unit test simulates a simple user workflow, where we:\n1. Generate a base sketch using a simple audio model\n2. Modify the .ino file, much like a user would\n3. Compile the sketch for the target board\n-- If physical hardware is present --\n4. Upload the sketch to a connected board\n5. Open a serial connection to the board\n6. Use serial connection to ensure model behaves correctly\n\"\"\"\n\n# Since these tests are sequential, we'll use the same project/workspace\n# directory for all tests in this file. Note that --board can't be loaded\n# from the fixture, since the fixture is function scoped (it has to be\n# for the tests to be named correctly via parameterization).\n@pytest.fixture(scope=\"module\")\ndef workflow_workspace_dir(request):\n    board = request.config.getoption(\"--board\")\n    return test_utils.make_workspace_dir(\"arduino_workflow\", board)\n\n\n@pytest.fixture(scope=\"module\")\ndef project_dir(workflow_workspace_dir):\n    return workflow_workspace_dir / \"project\"\n\n\n# We MUST pass workspace_dir, not project_dir, or the workspace will be dereferenced\n# too soon. We can't use the board fixture either for the reason mentioned above.\n@pytest.fixture(scope=\"module\")\ndef project(request, arduino_cli_cmd, microtvm_debug, workflow_workspace_dir):\n    board = request.config.getoption(\"--board\")\n    return test_utils.make_kws_project(\n        board, arduino_cli_cmd, microtvm_debug, workflow_workspace_dir\n    )\n\n\ndef _get_directory_elements(directory):\n    return set(f.name for f in directory.iterdir())\n\n\ndef test_project_folder_structure(project_dir, project):\n    assert set([\"microtvm_api_server.py\", \"project.ino\", \"src\"]).issubset(\n        _get_directory_elements(project_dir)\n    )\n\n    source_dir = project_dir / \"src\"\n    assert _get_directory_elements(source_dir) == set(\n        [\"model\", \"standalone_crt\", \"model.c\", \"model.h\"]\n    )\n\n\ndef test_project_model_integrity(project_dir, project):\n    model_dir = project_dir / \"src\" / \"model\"\n    assert _get_directory_elements(model_dir) == set(\n        [\"default_lib0.c\", \"default_lib1.c\", \"default_lib2.c\", \"model.tar\"]\n    )\n\n\ndef test_model_header_templating(project_dir, project):\n    # Ensure model.h was templated with correct WORKSPACE_SIZE\n    with (project_dir / \"src\" / \"model.h\").open() as f:\n        model_h = f.read()\n        workspace_size_defs = re.findall(r\"\\#define WORKSPACE_SIZE ([0-9]*)\", model_h)\n        assert workspace_size_defs\n        assert len(workspace_size_defs) == 1\n\n        # Make sure the WORKSPACE_SIZE we define is a reasonable size. We don't want\n        # to set an exact value, as this test shouldn't break if an improvement to\n        # TVM causes the amount of memory needed to decrease.\n        workspace_size = int(workspace_size_defs[0])\n        assert workspace_size < 30000\n        assert workspace_size > 10000\n\n\ndef test_import_rerouting(project_dir, project):\n    # Check one file to ensure imports were rerouted\n    runtime_path = project_dir / \"src\" / \"standalone_crt\" / \"src\" / \"runtime\"\n    c_backend_api_path = runtime_path / \"crt\" / \"common\" / \"crt_backend_api.c\"\n    assert c_backend_api_path.exists()\n\n    with c_backend_api_path.open() as f:\n        c_backend_api_c = f.read()\n        assert '#include \"inttypes.h\"' in c_backend_api_c\n        assert \"include/tvm/runtime/crt/platform.h\" in c_backend_api_c\n\n\n# Build on top of the generated project by replacing the\n# top-level .ino fileand adding data input files, much\n# like a user would\n@pytest.fixture(scope=\"module\")\ndef modified_project(project_dir, project):\n    this_dir = pathlib.Path(__file__).parent\n    kws_testdata_dir = this_dir.parent / \"testdata\" / \"kws\"\n    arduino_testdata_dir = this_dir / \"testdata\"\n\n    shutil.copy2(arduino_testdata_dir / \"project.ino\", project_dir / \"project.ino\")\n\n    project_data_dir = project_dir / \"src\" / \"data\"\n    project_data_dir.mkdir()\n    for sample in [\"yes.c\", \"no.c\", \"silence.c\", \"unknown.c\"]:\n        shutil.copy2(kws_testdata_dir / sample, project_data_dir / sample)\n\n    return project\n\n\n@pytest.fixture(scope=\"module\")\ndef compiled_project(modified_project):\n    modified_project.build()\n    return modified_project\n\n\ndef test_compile_yes_no_project(project_dir, project, compiled_project):\n    build_dir = project_dir / \"build\"\n    assert build_dir.exists()\n    first_build_file = next(build_dir.iterdir(), None)\n    assert first_build_file is not None\n\n\n\"\"\"------------------------------------------------------------\nIf we're not running on real hardware, no further tests are run\n------------------------------------------------------------\"\"\"\n\n\n@pytest.fixture(scope=\"module\")\ndef uploaded_project(compiled_project):\n    compiled_project.flash()\n    return compiled_project\n\n\n\"\"\" Sample serial output:\n\ncategory,runtime,yes,no,silence,unknown\nyes,56762,115,-123,-125,-123,\nno,56762,-128,4,-123,-9,\nsilence,56792,-128,-118,107,-117,\nunknown,56792,-128,-125,-128,125,\n\"\"\"\nSERIAL_OUTPUT_HEADERS = \"category,runtime,yes,no,silence,unknown\"\n\n\n@pytest.fixture(scope=\"module\")\ndef serial_output(uploaded_project):\n    transport = uploaded_project.transport()\n    transport.open()\n    out = transport.read(2048, 60)\n    out_str = out.decode(\"utf-8\")\n    out_lines = out_str.split(\"\\r\\n\")\n\n    assert SERIAL_OUTPUT_HEADERS in out_lines\n    headers_index = out_lines.index(SERIAL_OUTPUT_HEADERS)\n    data_lines = out_lines[headers_index + 1 : headers_index + 5]\n    split_lines = [line.split(\",\") for line in data_lines]\n\n    return [[line[0]] + list(map(int, line[1:6])) for line in split_lines]\n\n\nTENSORFLOW_EVALUATIONS = {\n    \"yes\": [115, -123, -125, -123],\n    \"no\": [-128, 4, -123, -9],\n    \"silence\": [-128, -118, 107, -117],\n    \"unknown\": [-128, -125, -128, 125],\n}\nMAX_PREDICTION_DIFFERENCE = 2\n\n\n@pytest.mark.requires_hardware\ndef test_project_inference_correctness(serial_output):\n    predictions = {line[0]: line[2:] for line in serial_output}\n\n    for sample, prediction in predictions.items():\n        # Due to rounding issues, we don't get the *exact* same\n        # values as Tensorflow gives, but they're pretty close\n\n        reference_prediction = TENSORFLOW_EVALUATIONS[sample]\n        deltas = [prediction[i] - reference_prediction[i] for i in range(4)]\n        assert max(deltas) < MAX_PREDICTION_DIFFERENCE\n\n\nMAX_INFERENCE_TIME_US = 200 * 1000\nMAX_INFERENCE_TIME_RANGE_US = 1000\n\n\n@pytest.mark.requires_hardware\ndef test_project_inference_runtime(serial_output):\n    runtimes_us = [line[1] for line in serial_output]\n\n    # Inference time will vary based on architecture\n    # and clock speed. However, anything more than 200 ms\n    # is way too long. Each inference takes ~60 ms on the\n    # Sony spresense, running at 156 MHz\n    assert max(runtimes_us) < MAX_INFERENCE_TIME_US\n\n    # Clock speeds should be consistent for each input. On\n    # the Sony spresense, they vary by <100 us. Note that\n    # running with other attached hardware (like the\n    # Spresense extension board) may cause this check to fail\n    range_runtimes_us = max(runtimes_us) - min(runtimes_us)\n    assert range_runtimes_us < MAX_INFERENCE_TIME_RANGE_US\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/arduino/test_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport pathlib\nimport requests\nimport datetime\n\nimport tvm.micro\nimport tvm.target.target\nfrom tvm.micro import project\nfrom tvm import relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.testing.utils import fetch_model_from_url\n\nTEMPLATE_PROJECT_DIR = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"arduino\"))\n\nBOARDS = TEMPLATE_PROJECT_DIR / \"boards.json\"\n\n\ndef arduino_boards() -> dict:\n    \"\"\"Returns a dict mapping board to target model\"\"\"\n    with open(BOARDS) as f:\n        board_properties = json.load(f)\n\n    boards_model = {board: info[\"model\"] for board, info in board_properties.items()}\n    return boards_model\n\n\nARDUINO_BOARDS = arduino_boards()\n\n\ndef make_workspace_dir(test_name, board):\n    filepath = pathlib.Path(__file__)\n    board_workspace = (\n        filepath.parent\n        / f\"workspace_{test_name}_{board}\"\n        / datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\")\n    )\n\n    number = 0\n    while board_workspace.exists():\n        number += 1\n        board_workspace = pathlib.Path(str(board_workspace) + f\"-{number}\")\n    board_workspace.parent.mkdir(exist_ok=True, parents=True)\n    t = tvm.contrib.utils.tempdir(board_workspace)\n    return t\n\n\ndef make_kws_project(board, arduino_cli_cmd, microtvm_debug, workspace_dir):\n    this_dir = pathlib.Path(__file__).parent\n    model = ARDUINO_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    mod, params = fetch_model_from_url(\n        url=\"https://github.com/tensorflow/tflite-micro/raw/main/tensorflow/lite/micro/examples/micro_speech/micro_speech.tflite\",\n        model_format=\"tflite\",\n        sha256=\"09e5e2a9dfb2d8ed78802bf18ce297bff54281a66ca18e0c23d69ca14f822a83\",\n    )\n\n    target = tvm.target.target.micro(model)\n    runtime = Runtime(\"crt\")\n    executor = Executor(\"aot\", {\"unpacked-api\": True})\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = relay.build(mod, target, runtime=runtime, executor=executor, params=params)\n\n    return tvm.micro.generate_project(\n        str(TEMPLATE_PROJECT_DIR),\n        mod,\n        workspace_dir / \"project\",\n        {\n            \"board\": board,\n            \"arduino_cli_cmd\": arduino_cli_cmd,\n            \"project_type\": \"example_project\",\n            \"verbose\": bool(build_config.get(\"debug\")),\n        },\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/common/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/common/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n\npytest_plugins = [\n    \"tvm.micro.testing.pytest_plugin\",\n]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/common/test_autotune.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom io import StringIO\nimport json\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.micro.testing\nfrom tvm.testing.utils import fetch_model_from_url\n\nTUNING_RUNS_PER_OPERATOR = 2\n\n\n@pytest.mark.requires_hardware\n@tvm.testing.requires_micro\ndef test_kws_autotune_workflow(platform, board, tmp_path):\n    mod, params = fetch_model_from_url(\n        url=\"https://github.com/tensorflow/tflite-micro/raw/main/tensorflow/lite/micro/examples/micro_speech/micro_speech.tflite\",\n        model_format=\"tflite\",\n        sha256=\"09e5e2a9dfb2d8ed78802bf18ce297bff54281a66ca18e0c23d69ca14f822a83\",\n    )\n    target = tvm.micro.testing.get_target(platform, board)\n\n    str_io_logs = tvm.micro.testing.tune_model(\n        platform, board, target, mod, params, TUNING_RUNS_PER_OPERATOR\n    )\n    assert isinstance(str_io_logs, StringIO)\n\n    str_logs = str_io_logs.getvalue().rstrip().split(\"\\n\")\n    logs = list(map(json.loads, str_logs))\n\n    # Some tuning tasks don't have any config space, and will only be run once\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        tasks = tvm.autotvm.task.extract_from_program(mod[\"main\"], {}, target)\n    assert len(tasks) <= len(logs) <= len(tasks) * TUNING_RUNS_PER_OPERATOR\n\n    # Check we tested both operators\n    op_names = list(map(lambda x: x[\"input\"][1], logs))\n    assert op_names[0] == op_names[1] == \"conv2d_nhwc_spatial_pack.arm_cpu\"\n\n    # Make sure we tested different code. != does deep comparison in Python 3\n    assert logs[0][\"config\"][\"index\"] != logs[1][\"config\"][\"index\"]\n    assert logs[0][\"config\"][\"entity\"] != logs[1][\"config\"][\"entity\"]\n\n    # Compile the best model with AOT and connect to it\n    str_io_logs.seek(0)\n    with tvm.micro.testing.create_aot_session(\n        platform,\n        board,\n        target,\n        mod,\n        params,\n        build_dir=tmp_path,\n        tune_logs=str_io_logs,\n    ) as session:\n        aot_executor = tvm.runtime.executor.aot_executor.AotModule(session.create_aot_executor())\n\n        samples = (\n            np.random.randint(low=-127, high=128, size=(1, 1960), dtype=np.int8) for x in range(3)\n        )\n\n        # Validate perforance across random runs\n        runtimes = [\n            runtime\n            for _, runtime in tvm.micro.testing.predict_labels_aot(\n                session, aot_executor, samples, runs_per_sample=20\n            )\n        ]\n        # `time` is the average time taken to execute model inference on the\n        # device, measured in seconds. It does not include the time to upload\n        # the input data via RPC. On slow boards like the Arduino Due, time\n        # is around 0.12 (120 ms), so this gives us plenty of buffer.\n        assert np.median(runtimes) < 1\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/common/test_tvmc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport subprocess\nimport shlex\nimport sys\nimport logging\nimport tempfile\nimport pathlib\nimport sys\nimport os\nimport shutil\n\nimport tvm\nimport tvm.testing\nfrom tvm.contrib.download import download_testdata\n\nTVMC_COMMAND = [sys.executable, \"-m\", \"tvm.driver.tvmc\"]\n\nMODEL_URL = \"https://github.com/tensorflow/tflite-micro/raw/main/tensorflow/lite/micro/examples/micro_speech/micro_speech.tflite\"\nMODEL_FILE = \"micro_speech.tflite\"\n\n# TODO(mehrdadh): replace this with _main from tvm.driver.tvmc.main\n# Issue: https://github.com/apache/tvm/issues/9612\ndef _run_tvmc(cmd_args: list, *args, **kwargs):\n    \"\"\"Run a tvmc command and return the results\"\"\"\n    cmd_args_list = TVMC_COMMAND + cmd_args\n    cwd_str = \"\" if \"cwd\" not in kwargs else f\" (in cwd: {kwargs['cwd']})\"\n    logging.debug(\"run%s: %s\", cwd_str, \" \".join(shlex.quote(a) for a in cmd_args_list))\n    return subprocess.check_call(cmd_args_list, *args, **kwargs)\n\n\n@tvm.testing.requires_micro\ndef test_tvmc_exist(platform, board):\n    cmd_result = _run_tvmc([\"micro\", \"-h\"])\n    assert cmd_result == 0\n\n\n@tvm.testing.requires_micro\n@pytest.mark.parametrize(\n    \"output_dir,\",\n    [pathlib.Path(\"./tvmc_relative_path_test\"), pathlib.Path(tempfile.mkdtemp())],\n)\ndef test_tvmc_model_build_only(platform, board, output_dir):\n    target = tvm.micro.testing.get_target(platform, board)\n\n    if not os.path.isabs(output_dir):\n        out_dir_temp = os.path.abspath(output_dir)\n        if os.path.isdir(out_dir_temp):\n            shutil.rmtree(out_dir_temp)\n        os.mkdir(out_dir_temp)\n\n    model_path = download_testdata(MODEL_URL, MODEL_FILE, module=\"data\")\n    tar_path = str(output_dir / \"model.tar\")\n    project_dir = str(output_dir / \"project\")\n\n    runtime = \"crt\"\n    executor = \"graph\"\n\n    cmd_result = _run_tvmc(\n        [\n            \"compile\",\n            model_path,\n            f\"--target={target}\",\n            f\"--runtime={runtime}\",\n            f\"--runtime-crt-system-lib\",\n            str(1),\n            f\"--executor={executor}\",\n            \"--executor-graph-link-params\",\n            str(0),\n            \"--output\",\n            tar_path,\n            \"--output-format\",\n            \"mlf\",\n            \"--pass-config\",\n            \"tir.disable_vectorize=1\",\n            \"--disabled-pass=AlterOpLayout\",\n        ]\n    )\n    assert cmd_result == 0, \"tvmc failed in step: compile\"\n\n    create_project_cmd = [\n        \"micro\",\n        \"create-project\",\n        project_dir,\n        tar_path,\n        platform,\n        \"--project-option\",\n        \"project_type=host_driven\",\n        f\"board={board}\",\n    ]\n\n    cmd_result = _run_tvmc(create_project_cmd)\n    assert cmd_result == 0, \"tvmc micro failed in step: create-project\"\n\n    build_cmd = [\"micro\", \"build\", project_dir, platform]\n    cmd_result = _run_tvmc(build_cmd)\n    assert cmd_result == 0, \"tvmc micro failed in step: build\"\n    shutil.rmtree(output_dir)\n\n\n@pytest.mark.requires_hardware\n@tvm.testing.requires_micro\n@pytest.mark.parametrize(\n    \"output_dir,\",\n    [pathlib.Path(\"./tvmc_relative_path_test\"), pathlib.Path(tempfile.mkdtemp())],\n)\ndef test_tvmc_model_run(platform, board, output_dir):\n    target = tvm.micro.testing.get_target(platform, board)\n\n    if not os.path.isabs(output_dir):\n        out_dir_temp = os.path.abspath(output_dir)\n        if os.path.isdir(out_dir_temp):\n            shutil.rmtree(out_dir_temp)\n        os.mkdir(out_dir_temp)\n\n    model_path = model_path = download_testdata(MODEL_URL, MODEL_FILE, module=\"data\")\n    tar_path = str(output_dir / \"model.tar\")\n    project_dir = str(output_dir / \"project\")\n\n    runtime = \"crt\"\n    executor = \"graph\"\n\n    cmd_result = _run_tvmc(\n        [\n            \"compile\",\n            model_path,\n            f\"--target={target}\",\n            f\"--runtime={runtime}\",\n            f\"--runtime-crt-system-lib\",\n            str(1),\n            f\"--executor={executor}\",\n            \"--executor-graph-link-params\",\n            str(0),\n            \"--output\",\n            tar_path,\n            \"--output-format\",\n            \"mlf\",\n            \"--pass-config\",\n            \"tir.disable_vectorize=1\",\n            \"--disabled-pass=AlterOpLayout\",\n        ]\n    )\n    assert cmd_result == 0, \"tvmc failed in step: compile\"\n\n    create_project_cmd = [\n        \"micro\",\n        \"create-project\",\n        project_dir,\n        tar_path,\n        platform,\n        \"--project-option\",\n        \"project_type=host_driven\",\n        f\"board={board}\",\n    ]\n\n    cmd_result = _run_tvmc(create_project_cmd)\n    assert cmd_result == 0, \"tvmc micro failed in step: create-project\"\n\n    build_cmd = [\"micro\", \"build\", project_dir, platform]\n    cmd_result = _run_tvmc(build_cmd)\n\n    assert cmd_result == 0, \"tvmc micro failed in step: build\"\n\n    flash_cmd = [\"micro\", \"flash\", project_dir, platform]\n    cmd_result = _run_tvmc(flash_cmd)\n    assert cmd_result == 0, \"tvmc micro failed in step: flash\"\n\n    run_cmd = [\n        \"run\",\n        \"--device\",\n        \"micro\",\n        project_dir,\n    ]\n    run_cmd += [\"--fill-mode\", \"random\"]\n    cmd_result = _run_tvmc(run_cmd)\n    assert cmd_result == 0, \"tvmc micro failed in step: run\"\n    shutil.rmtree(output_dir)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/project_api/test_arduino_microtvm_api_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom unittest import mock\n\nfrom packaging import version\nimport pytest\n\nimport tvm\nfrom tvm.micro.project_api import server\n\nsys.path.insert(0, tvm.micro.get_microtvm_template_projects(\"arduino\"))\nimport microtvm_api_server\n\nsys.path.pop(0)\n\n\nclass TestGenerateProject:\n    DEFAULT_OPTIONS = {\"arduino_cli_cmd\": \"arduino-cli\", \"board\": \"nano33ble\"}\n\n    def _set_pathlib_path_exists(self, value):\n        with mock.patch.object(Path, \"exists\") as mock_exists:\n            mock_exists.return_value = value\n\n    @mock.patch(\"pathlib.Path\")\n    def test_find_modified_include_path(self, mock_pathlib_path):\n        handler = microtvm_api_server.Handler()\n\n        project_dir = mock_pathlib_path(\"/dummy/project\")\n        file_path = (\n            project_dir\n            / \"src\"\n            / \"standalone_crt\"\n            / \"src\"\n            / \"runtime\"\n            / \"crt\"\n            / \"graph_executor\"\n            / \"load_json.c\"\n        )\n\n        # Should return C standard libs unmodified\n        clib_output = handler._find_modified_include_path(project_dir, file_path, \"math.h\")\n        assert clib_output == \"math.h\"\n\n        # If import already works, should return unmodified\n        valid_arduino_import = \"../../../../include/tvm/runtime/crt/platform.h\"\n        self._set_pathlib_path_exists(True)\n        valid_output = handler._find_modified_include_path(\n            project_dir, file_path, valid_arduino_import\n        )\n        assert valid_output == valid_arduino_import\n\n    # Format for arduino-cli v0.18.2\n    BOARD_CONNECTED_V18 = (\n        \"Port         Type              Board Name          FQBN                        Core             \\n\"\n        \"/dev/ttyACM0 Serial Port (USB) Arduino Nano 33 BLE arduino:mbed_nano:nano33ble arduino:mbed_nano\\n\"\n        \"/dev/ttyACM1 Serial Port (USB) Arduino Nano 33     arduino:mbed_nano:nano33    arduino:mbed_nano\\n\"\n        \"/dev/ttyS4   Serial Port       Unknown                                                          \\n\"\n        \"\\n\"\n    )\n    # Format for arduino-cli v0.21.1 and above\n    BOARD_CONNECTED_V21 = (\n        \"Port         Protocol Type Board Name FQBN                        Core             \\n\"\n        \"/dev/ttyACM0 serial                   arduino:mbed_nano:nano33ble arduino:mbed_nano\\n\"\n        \"\\n\"\n    )\n    BOARD_DISCONNECTED_V21 = (\n        \"Port       Protocol Type        Board Name FQBN Core\\n\"\n        \"/dev/ttyS4 serial   Serial Port Unknown\\n\"\n        \"\\n\"\n    )\n\n    def test_parse_connected_boards(self):\n        h = microtvm_api_server.Handler()\n        boards = h._parse_connected_boards(self.BOARD_CONNECTED_V21)\n        assert list(boards) == [\n            {\n                \"port\": \"/dev/ttyACM0\",\n                \"protocol\": \"serial\",\n                \"type\": \"\",\n                \"board name\": \"\",\n                \"fqbn\": \"arduino:mbed_nano:nano33ble\",\n                \"core\": \"arduino:mbed_nano\",\n            }\n        ]\n\n    @mock.patch(\"subprocess.run\")\n    def test_auto_detect_port(self, mock_run):\n        process_mock = mock.Mock()\n        handler = microtvm_api_server.Handler()\n\n        # Test it returns the correct port when a board is connected\n        mock_run.return_value.stdout = bytes(self.BOARD_CONNECTED_V18, \"utf-8\")\n        assert handler._auto_detect_port(self.DEFAULT_OPTIONS) == \"/dev/ttyACM0\"\n\n        # Should work with old or new arduino-cli version\n        mock_run.return_value.stdout = bytes(self.BOARD_CONNECTED_V21, \"utf-8\")\n        assert handler._auto_detect_port(self.DEFAULT_OPTIONS) == \"/dev/ttyACM0\"\n\n        # Test it raises an exception when no board is connected\n        mock_run.return_value.stdout = bytes(self.BOARD_DISCONNECTED_V21, \"utf-8\")\n        with pytest.raises(microtvm_api_server.BoardAutodetectFailed):\n            handler._auto_detect_port(self.DEFAULT_OPTIONS)\n\n        # Test that the FQBN needs to match EXACTLY\n        handler._get_fqbn = mock.MagicMock(return_value=\"arduino:mbed_nano:nano33\")\n        mock_run.return_value.stdout = bytes(self.BOARD_CONNECTED_V18, \"utf-8\")\n        assert (\n            handler._auto_detect_port({**self.DEFAULT_OPTIONS, \"board\": \"nano33\"}) == \"/dev/ttyACM1\"\n        )\n\n    BAD_CLI_VERSION = \"arduino-cli  Version: 0.7.1 Commit: 7668c465 Date: 2019-12-31T18:24:32Z\\n\"\n    GOOD_CLI_VERSION = \"arduino-cli  Version: 0.21.1 Commit: 9fcbb392 Date: 2022-02-24T15:41:45Z\\n\"\n\n    @mock.patch(\"subprocess.run\")\n    def test_auto_detect_port(self, mock_run):\n        handler = microtvm_api_server.Handler()\n        mock_run.return_value.stdout = bytes(self.GOOD_CLI_VERSION, \"utf-8\")\n        arduino_cli_cmd = self.DEFAULT_OPTIONS.get(\"arduino_cli_cmd\")\n        warning_as_error = self.DEFAULT_OPTIONS.get(\"warning_as_error\")\n\n        cli_command = handler._get_arduino_cli_cmd(arduino_cli_cmd)\n        handler._check_platform_version(cli_command=cli_command, warning_as_error=warning_as_error)\n        assert handler._version == version.parse(\"0.21.1\")\n\n        handler = microtvm_api_server.Handler()\n        mock_run.return_value.stdout = bytes(self.BAD_CLI_VERSION, \"utf-8\")\n        with pytest.raises(server.ServerError) as error:\n            handler._check_platform_version(cli_command=cli_command, warning_as_error=True)\n        mock_run.reset_mock()\n\n    @mock.patch(\"subprocess.run\")\n    def test_flash_retry(self, mock_run):\n        mock_run.return_value.stdout = bytes(self.GOOD_CLI_VERSION, \"utf-8\")\n\n        def side_effect(cmd, *args, **kwargs):\n            if cmd[1] == \"flash\":\n                raise subprocess.TimeoutExpired(cmd, kwargs[\"timeout\"])\n            return mock.DEFAULT\n\n        mock_run.side_effect = side_effect\n\n        handler = microtvm_api_server.Handler()\n        handler._port = \"/dev/ttyACM0\"\n\n        # handler.flash will try flashing `handler.FLASH_MAX_RETRIES` times,\n        # after which it will raise a TimeoutExpired exception of its own\n        with pytest.raises(RuntimeError):\n            handler.flash(self.DEFAULT_OPTIONS)\n\n        # Test we checked version then called upload once per retry attempt,\n        # plus once to verify arduino-cli version.\n        assert mock_run.call_count == handler.FLASH_MAX_RETRIES + 1\n\n    @mock.patch(\"subprocess.run\")\n    def test_flash(self, mock_run):\n        mock_run.return_value.stdout = bytes(self.GOOD_CLI_VERSION, \"utf-8\")\n\n        handler = microtvm_api_server.Handler()\n        handler._port = \"/dev/ttyACM0\"\n\n        # Test no exception thrown when command works\n        handler.flash(self.DEFAULT_OPTIONS)\n\n        # Test we checked version then called upload\n        assert mock_run.call_count == 2\n        assert mock_run.call_args_list[0][0] == ([\"arduino-cli\", \"version\"],)\n        assert mock_run.call_args_list[1][0][0][0:2] == [\"make\", \"flash\"]\n        mock_run.reset_mock()\n\n        # Test exception raised when `arduino-cli upload` returns error code\n        mock_run.side_effect = subprocess.CalledProcessError(2, [])\n        with pytest.raises(subprocess.CalledProcessError):\n            handler.flash(self.DEFAULT_OPTIONS)\n\n        # Version information should be cached and not checked again\n        mock_run.assert_called_once()\n        assert mock_run.call_args[0][0][0:2] == [\"make\", \"flash\"]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/project_api/test_project_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.micro.project_api import server\nfrom tvm.relay.backend import Runtime\nfrom tvm.micro.testing import get_target\n\nAPI_GENERATE_PROJECT = \"generate_project\"\nAPI_BUILD = \"build\"\nAPI_FLASH = \"flash\"\nAPI_OPEN_TRANSPORT = \"open_transport\"\n\nPLATFORM_ARDUINO = \"arduino\"\nPLATFORM_ZEPHYR = \"zephyr\"\n\n\nplatform = tvm.testing.parameter(PLATFORM_ARDUINO, PLATFORM_ZEPHYR)\n\n\n@tvm.testing.requires_micro\ndef test_default_options_exist(platform):\n    sys.path.insert(0, tvm.micro.get_microtvm_template_projects(platform))\n    import microtvm_api_server\n\n    platform_options = microtvm_api_server.PROJECT_OPTIONS\n    default_options = server.default_project_options()\n\n    option_names = []\n    for option in platform_options:\n        option_names.append(option.name)\n\n    for option in default_options:\n        assert option.name in option_names\n\n\n@tvm.testing.requires_micro\ndef test_project_minimal_options(platform):\n    \"\"\"Test template project with minimum projectOptions\"\"\"\n    shape = (10,)\n    dtype = \"int8\"\n    x = relay.var(\"x\", relay.TensorType(shape=shape, dtype=dtype))\n    xx = relay.multiply(x, x)\n    z = relay.add(xx, relay.const(np.ones(shape=shape, dtype=dtype)))\n    func = relay.Function([x], z)\n    ir_mod = tvm.IRModule.from_expr(func)\n\n    if platform == \"arduino\":\n        board = \"due\"\n    elif platform == \"zephyr\":\n        board = \"qemu_x86\"\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    target = get_target(platform, board)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(ir_mod, target=target, runtime=runtime)\n\n    project_options = {\n        \"project_type\": \"host_driven\",\n        \"board\": board,\n    }\n\n    temp_dir = tvm.contrib.utils.tempdir()\n    project = tvm.micro.generate_project(\n        tvm.micro.get_microtvm_template_projects(platform),\n        mod,\n        temp_dir / \"project\",\n        project_options,\n    )\n    project.build()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/stm32/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm.target.target\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/stm32/test_code_emitter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport shutil\nimport struct\nimport sys\n\nimport numpy as np\n\nimport tensorflow as tf\n\nimport tvm\nimport tvm.relay as relay\nfrom tvm.micro.contrib import stm32\nfrom tvm.contrib.download import download\nfrom tvm import testing\n\nimport conftest\n\nNUM_ITERATIONS = 10\n\n# =========================================================\n#   get_data\n# =========================================================\ndef get_data(in_data_shapes, in_data_dtypes):\n    \"\"\"Generate a uint8 image.\"\"\"\n    assert len(in_data_shapes) == 1, \"Only single input models are supported.\"\n    in_data = OrderedDict()\n    for shape_name, shape in in_data_shapes.items():\n        for dtype_name, dtype in in_data_dtypes.items():\n            if dtype_name == shape_name:\n                in_data[shape_name] = np.random.uniform(size=shape).astype(dtype)\n                in_data = np.random.uniform(size=shape).astype(\"uint8\")\n                break\n        if shape_name not in in_data.keys():\n            raise ValueError(\"Shape and dtype dictionaries do not fit.\")\n\n    return in_data\n\n\n# ==================================================================\n#   dump_image\n# ==================================================================\ndef dump_image(filename, image):\n    # Flatten image\n    image_data = image.flatten()\n    outputRaw = []\n    # Raw binary format\n    for i in range(0, len(image_data)):\n        outputRaw.append(struct.pack(\"<B\", int(image_data[i]) & 0xFF))\n\n    # Dump image in raw binary format\n    f = open(filename, \"wb\")\n    for i in range(0, len(outputRaw)):\n        f.write(outputRaw[i])\n    f.close()\n\n\n# ==================================================================\n#   scale_input_data\n# ==================================================================\ndef scale_input_data(input_details, data):\n    if input_details[\"dtype\"] == np.uint8 or input_details[\"dtype\"] == np.int8:\n        input_scale, input_zero_point = input_details[\"quantization\"]\n        print(\n            \"== TFLite input quantization: scale={}, zero={}\".format(input_scale, input_zero_point)\n        )\n        data = data / input_scale + input_zero_point\n    data = data.astype(input_details[\"dtype\"])\n    return data\n\n\n# ==================================================================\n#   scale_output_data\n# ==================================================================\ndef scale_output_data(output_details, data):\n    if output_details[\"dtype\"] == np.uint8 or output_details[\"dtype\"] == np.int8:\n        output_scale, output_zero_point = output_details[\"quantization\"]\n        print(\n            \"== TFLite output quantization: scale={}, zero={}\".format(\n                output_scale, output_zero_point\n            )\n        )\n        data = data.astype(np.float32)\n        data = (data - output_zero_point) * output_scale\n    return data\n\n\n# ========================================================\n#   get_tflite_model\n# ========================================================\ndef get_tflite_model(model_path):\n\n    #\n    # Load TFLite model and allocate tensors.\n    #\n    interpreter = tf.lite.Interpreter(model_path=model_path)\n    interpreter.allocate_tensors()\n    #\n    # Get input and output tensors.\n    #\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    #\n    # Figure out shapes and\n    #\n\n    shape_dict = {}\n    dtype_dict = {}\n\n    for input in input_details:\n        input_name = input[\"name\"]\n        input_shape = input[\"shape\"].tolist()\n        input_dtype = str(np.dtype(input[\"dtype\"]))\n        shape_dict[input_name] = input_shape\n        dtype_dict[input_name] = input_dtype\n\n    #\n    # Save the model\n    #\n\n    #\n    # Load the TFLite Model for TVM:\n    #\n    # https://docs.tvm.ai/tutorials/frontend/from_tflite.html\n    # https://jackwish.net/tflite/docs/\n\n    model_buf = open(model_path, \"rb\").read()\n\n    #\n    # Get TFLite model from buffer\n    #\n    try:\n        import tflite\n\n        model = tflite.Model.GetRootAsModel(model_buf, 0)\n        assert isinstance(model, tflite.Model)\n    except AttributeError:\n        import tflite.Model\n\n        model = tflite.Model.Model.GetRootAsModel(model_buf, 0)\n        assert isinstance(model, tflite.Model.Model)\n\n    print(\"TVM: Importing a TFLite model ...\")\n\n    return model, shape_dict, dtype_dict\n\n\n# ========================================================\n#   extract_tflite_quantization\n# ========================================================\n\n\ndef _make_qnn_params(quantization):\n    qnn_params = {}\n    qnn_params[\"min\"] = quantization.MinAsNumpy()\n    qnn_params[\"max\"] = quantization.MaxAsNumpy()\n    qnn_params[\"scale\"] = quantization.ScaleAsNumpy()\n    qnn_params[\"zero_point\"] = quantization.ZeroPointAsNumpy()\n    qnn_params[\"dim\"] = quantization.QuantizedDimension()\n    # print(\"  Quantization: ({}, {}), s={}, z={}, dim={}\".format(min, max, scale, zero_point, dim))\n    return qnn_params\n\n\ndef extract_tflite_quantization(model):\n\n    assert model.SubgraphsLength() == 1, \"only support one subgraph (main subgraph)\"\n\n    subgraph = model.Subgraphs(0)\n\n    quantization_info = {}\n\n    # model inputs / outputs\n    model_inputs = subgraph.InputsAsNumpy()\n    model_outputs = subgraph.OutputsAsNumpy()\n\n    for node_id in model_inputs:\n        tensor = subgraph.Tensors(node_id)\n        tensor_name = tensor.Name().decode(\"utf-8\")\n        tensor_type = tensor.Type()\n        dl_tensor_name = stm32.get_input_tensor_name(tensor_name)\n\n        quantization = tensor.Quantization()\n        if quantization is not None:\n            qnn_params = _make_qnn_params(quantization)\n            quantization_info[dl_tensor_name] = qnn_params\n\n    for node_id in model_outputs:\n        tensor = subgraph.Tensors(node_id)\n        tensor_name = tensor.Name().decode(\"utf-8\")\n        tensor_type = tensor.Type()\n        #\n        # TODO: TVM does not preserve the output tensor names.\n        #       Eventually, we should be able to form a valid name.\n        #\n        dl_tensor_name = stm32.get_output_tensor_name(tensor_name, 0)\n\n        quantization = tensor.Quantization()\n        if quantization is not None:\n            qnn_params = _make_qnn_params(quantization)\n            quantization_info[dl_tensor_name] = qnn_params\n\n    return quantization_info\n\n\n# ========================================================\n#   run_tflite_model\n# ========================================================\ndef run_tflite_model(model_path, image_data):\n    #\n    # Load TFLite model and allocate tensors.\n    #\n    interpreter = tf.lite.Interpreter(model_path=model_path)\n    interpreter.allocate_tensors()\n    #\n    # Get input and output tensors.\n    #\n    input_details = interpreter.get_input_details()[0]\n    output_details = interpreter.get_output_details()[0]\n\n    #\n    # Run test images\n    #\n    tf_results = np.empty(shape=[NUM_ITERATIONS, 10], dtype=np.float)\n    for i, image in enumerate(image_data):\n        #\n        # Normalize the input data\n        #\n        image = image / 255.0\n        image = scale_input_data(input_details, image)\n        interpreter.set_tensor(input_details[\"index\"], image)\n        interpreter.invoke()\n        tf_results[i] = interpreter.get_tensor(output_details[\"index\"])\n        tf_results[i] = scale_output_data(output_details, tf_results[i])\n\n        print(f\"== [{i}] TFLite Output:\")\n        print(tf_results[i])\n\n    return tf_results\n\n\n# ========================================================\n#   run_tvm_model\n# ========================================================\ndef run_tvm_model(build_dir, model_name, target_dir, image_path):\n\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n\n    tvm_results_name = os.path.join(build_dir, \"tvm_results.txt\")\n\n    #\n    # Build the model\n    #\n    tvm_dir = os.path.join(curr_path, \"..\", \"..\", \"..\")\n    test_dir = os.path.join(tvm_dir, \"tests\", \"crt\", \"contrib\", \"stm32\")\n\n    command = f\"make -f {test_dir}/Makefile TVM_PATH={tvm_dir} MODEL_PATH={target_dir} BUILD_PATH={build_dir} IMAGE_PATH={image_path}\"\n    print(f\"{command}\")\n    os.system(command)\n    #\n    # Run\n    #\n    command = f\"{target_dir}/{model_name}.exe\"\n    print(f\"{command}\")\n    os.system(command)\n\n    tvm_results = np.loadtxt(tvm_results_name)\n    print(f\"== TVM Output:\\n {tvm_results}\")\n\n    #\n    # Clean temporary image files\n    #\n    if os.path.exists(tvm_results_name):\n        os.remove(tvm_results_name)\n\n    return tvm_results\n\n\n# ========================================================\n#   check_network\n# ========================================================\ndef check_network(build_dir, target_name, model_path, image_path):\n\n    model_name = \"network\"\n\n    model, shape_dict, dtype_dict = get_tflite_model(model_path)\n\n    #\n    # Generate random input data\n    #\n    image_data = []\n    for i in range(NUM_ITERATIONS):\n        assert len(shape_dict) == 1, \"Only single input models are supported.\"\n        image_shape = list(shape_dict.values())[0]\n        in_data = np.random.randint(0, 255, size=image_shape).astype(\"uint8\")\n        # Write raw data for using with the TVM implementation\n        filename = os.path.join(image_path, \"{:02d}.raw\".format(i))\n        dump_image(filename, in_data)\n        image_data.append(in_data)\n\n    mod, params = relay.frontend.from_tflite(model, shape_dict, dtype_dict)\n\n    #\n    # Build a TVM C module for the ARM CPU (without compiling the kernels\n    # library to the object code form):\n    #\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        rt_module = relay.build(mod, target=\"c -device=arm_cpu\", params=params)\n\n    #\n    # Export model library format\n    #\n    target_dir = os.path.join(build_dir, target_name + \"_gen\")\n\n    if os.path.exists(target_dir):\n        print(f'Removing existing \"{target_dir}\" directory')\n        try:\n            shutil.rmtree(target_dir)\n        except OSError as err:\n            raise ValueError(f\"emit_code.Error: {target_dir} : {err.strerror}\")\n\n    mlf_tar_path = os.path.join(build_dir, target_name + \"_lib.tar\")\n    import tvm.micro as micro\n\n    micro.export_model_library_format(rt_module, mlf_tar_path)\n\n    emitter = stm32.CodeEmitter()\n    quantization = extract_tflite_quantization(model)\n    emitter.parse_library_format(mlf_tar_path, quantization)\n    emitter.emit_code(target_dir, model_name)\n\n    #\n    # Results\n    #\n    tf_results = run_tflite_model(model_path, image_data)\n    tvm_results = run_tvm_model(build_dir, model_name, target_dir, image_path)\n\n    check_result(tf_results, tvm_results)\n\n\n# ========================================================\n#   check_result\n# ========================================================\ndef check_result(tflite_results, tvm_results):\n    \"\"\"Helper function to verify results\"\"\"\n\n    #\n    # MNIST quantized uint8 results in one single difference of\n    # ~ 0.004 so just escape this\n    #\n    ATOL = 1e-3\n    RTOL = 0.5\n\n    tvm.testing.assert_allclose(tflite_results, tvm_results, rtol=RTOL, atol=ATOL)\n\n\n# ========================================================\n#   test_mnist\n# ========================================================\ndef test_mnist():\n    DEBUG = False\n    tempdir_root = None\n    if DEBUG:\n        tempdir_root = os.path.join(\n            curr_path,\n            f\"workspace\",\n            \"test_mnist\",\n            datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\"),\n        )\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    model_path = os.path.join(curr_path, \"models/mnist.tflite\")\n    build_dir = tvm.contrib.utils.tempdir(tempdir_root)\n    model_url = \"https://storage.googleapis.com/download.tensorflow.org/models/tflite/digit_classifier/mnist.tflite\"\n    download(model_url, model_path)\n    check_network(build_dir.path, \"mnist\", model_path, build_dir.path)\n\n\nif __name__ == \"__main__\":\n    sys.exit(pytest.main([os.path.dirname(__file__)] + sys.argv[1:]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/testdata/kws/no.c",
        "content": "/*\n * This work is a derivative of \"Speech Commands V2\" by Google, used under CC BY 4.0.\n */\n\nstatic const char input_no[1960] = {\n    0x80, 0x80, 0x80, 0xc5, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc5, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc5, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb4,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xcf, 0xe4, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0xdb, 0xe4, 0xc5, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x2f, 0x1e, 0x7,  0xe4, 0xc5, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x52, 0x41, 0x4b, 0x3a, 0x20, 0xf6, 0xcf, 0xb4,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0xb4, 0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xc5, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0x80, 0x80,\n    0x62, 0x53, 0x5d, 0x51, 0x4a, 0xf9, 0xe4, 0xb4, 0xc5, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xc5, 0x80, 0x80, 0x80, 0xc5, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0xb4, 0xc5, 0x80, 0xcf, 0x80, 0x41, 0x49, 0x6a, 0x5d, 0x75, 0x62, 0x75, 0x63,\n    0x7a, 0x65, 0x7b, 0x64, 0x78, 0x62, 0x75, 0x5d, 0x71, 0x5b, 0x37, 0xd,  0x3,  0xf6, 0xec, 0xd6,\n    0x32, 0x2a, 0x1a, 0xf6, 0x42, 0x4b, 0x3f, 0xe0, 0xe4, 0xcf, 0xf3, 0xef, 0xf3, 0xfb, 0x3,  0x0,\n    0x6d, 0x56, 0x6e, 0x57, 0x69, 0x55, 0x72, 0x5d, 0x66, 0x52, 0x6e, 0x5d, 0x6f, 0x46, 0x64, 0x52,\n    0x62, 0x42, 0x4e, 0x29, 0x32, 0xe,  0x25, 0x35, 0x56, 0x49, 0x4d, 0x42, 0x5d, 0x57, 0x61, 0x34,\n    0x1c, 0x5,  0x20, 0x17, 0x17, 0x17, 0x24, 0x20, 0x76, 0x65, 0x7a, 0x63, 0x7b, 0x65, 0x7b, 0x5d,\n    0x70, 0x53, 0x73, 0x61, 0x70, 0x53, 0x66, 0x57, 0x63, 0x52, 0x5c, 0x3a, 0x54, 0x4d, 0x6b, 0x5f,\n    0x78, 0x66, 0x7a, 0x64, 0x7b, 0x64, 0x75, 0x56, 0x5a, 0x46, 0x4b, 0x3d, 0x46, 0x3e, 0x4e, 0x3f,\n    0x68, 0x58, 0x6e, 0x57, 0x6d, 0x5f, 0x76, 0x5a, 0x6e, 0x57, 0x75, 0x5d, 0x67, 0x53, 0x68, 0x50,\n    0x67, 0x53, 0x6c, 0x59, 0x68, 0x5a, 0x6a, 0x53, 0x65, 0x5a, 0x74, 0x56, 0x6d, 0x5c, 0x6b, 0x4a,\n    0x50, 0x46, 0x58, 0x48, 0x66, 0x56, 0x59, 0x46, 0x5e, 0x43, 0x61, 0x44, 0x61, 0x50, 0x6e, 0x55,\n    0x67, 0x5a, 0x63, 0x4e, 0x5f, 0x3b, 0x63, 0x52, 0x5e, 0x4e, 0x67, 0x4d, 0x62, 0x51, 0x6a, 0x4e,\n    0x62, 0x48, 0x69, 0x55, 0x66, 0x50, 0x62, 0x50, 0x59, 0x40, 0x4c, 0x41, 0x6c, 0x55, 0x5a, 0x3f,\n    0x58, 0x3c, 0x5b, 0x28, 0x50, 0x3d, 0x62, 0x4b, 0x5b, 0x55, 0x62, 0x43, 0x5d, 0x3c, 0x50, 0x37,\n    0x55, 0x2d, 0x55, 0x49, 0x59, 0x48, 0x53, 0x3e, 0x53, 0x46, 0x64, 0x53, 0x61, 0x3f, 0x5e, 0x2e,\n    0x4d, 0x39, 0x4e, 0x41, 0x61, 0x4a, 0x53, 0x36, 0x52, 0x35, 0x55, 0x2a, 0x4f, 0x3a, 0x5a, 0x3e,\n    0x55, 0x4f, 0x5e, 0x37, 0x4d, 0x34, 0x4c, 0x37, 0x4e, 0x28, 0x50, 0x36, 0x53, 0x39, 0x49, 0x2b,\n    0x4f, 0x39, 0x5c, 0x47, 0x51, 0x35, 0x5d, 0x1b, 0x3f, 0x2b, 0x46, 0x3b, 0x5d, 0x44, 0x5a, 0x35,\n    0x4d, 0x35, 0x4e, 0x30, 0x4b, 0x3f, 0x57, 0x35, 0x59, 0x3f, 0x45, 0xd,  0x2b, 0x4,  0x45, 0x26,\n    0x48, 0x36, 0x47, 0x26, 0x44, 0x39, 0x50, 0x2e, 0x46, 0x2f, 0x55, 0x43, 0x4c, 0x23, 0x52, 0x2f,\n    0x3f, 0x25, 0x43, 0x2d, 0x3b, 0xf9, 0x4d, 0x29, 0x44, 0x1b, 0x35, 0x38, 0x48, 0x3a, 0x46, 0x3c,\n    0x5d, 0x29, 0x43, 0x5,  0x4a, 0xd,  0x26, 0xb4, 0x28, 0xcf, 0x3c, 0x13, 0x25, 0x2,  0x32, 0xf9,\n    0x2f, 0x1e, 0x4d, 0x19, 0x3a, 0x2,  0x3c, 0x7,  0x3c, 0x12, 0x3c, 0x10, 0xdb, 0x80, 0x37, 0x24,\n    0x42, 0x21, 0x3a, 0x30, 0x4a, 0x28, 0x32, 0x31, 0x48, 0xe7, 0x2d, 0x80, 0x19, 0xf9, 0x2d, 0xf3,\n    0x32, 0x2,  0x24, 0xb4, 0x14, 0x80, 0x22, 0xb4, 0x35, 0x3,  0x40, 0xf,  0x30, 0x80, 0x26, 0x80,\n    0x26, 0xcf, 0x21, 0x80, 0x80, 0x80, 0xf5, 0xef, 0x28, 0x80, 0x4b, 0x34, 0x3c, 0xdb, 0x34, 0x12,\n    0x44, 0xe0, 0x26, 0x80, 0x1d, 0x80, 0xd6, 0x80, 0x21, 0xe4, 0x80, 0x80, 0xb4, 0x80, 0xf6, 0x11,\n    0x2b, 0xff, 0x3e, 0x16, 0x1f, 0x80, 0x21, 0xf6, 0x14, 0xd6, 0x27, 0xcf, 0x80, 0x80, 0x0,  0xec,\n    0x48, 0xd6, 0x3b, 0x0,  0x36, 0x1d, 0x28, 0xcf, 0x2d, 0xef, 0x25, 0x80, 0xcf, 0x80, 0xf5, 0x80,\n    0xa,  0x80, 0x11, 0x80, 0x80, 0x80, 0xf8, 0xe4, 0x10, 0xea, 0x2a, 0xf1, 0x21, 0x80, 0xcf, 0x80,\n    0x3,  0xe7, 0x1a, 0xb4, 0x80, 0x80, 0xe0, 0xdb, 0x31, 0xe0, 0x32, 0xc,  0x30, 0x80, 0x0,  0xc5,\n    0x34, 0x80, 0x2,  0x80, 0xf1, 0x80, 0xcf, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x2,  0x80, 0x14, 0x80, 0xd6, 0x80, 0x80, 0x80, 0xfb, 0xdb, 0x8,  0x80, 0x80, 0x80, 0xe4, 0xe7,\n    0x28, 0xc5, 0x1e, 0xdb, 0x2a, 0xb4, 0x80, 0x80, 0x30, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xf8, 0xb4, 0x17, 0x80, 0xcf, 0x80, 0x80, 0x80,\n    0x0,  0xcf, 0x12, 0x80, 0x80, 0x80, 0xdb, 0xb4, 0xe4, 0x80, 0x21, 0xb4, 0x2a, 0x80, 0x80, 0x80,\n    0x13, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xf3, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xfd, 0x80, 0x80, 0x80, 0xe0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xe4, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/testdata/kws/silence.c",
        "content": "/*\n * This work is a derivative of \"Speech Commands V2\" by Google, used under CC BY 4.0.\n */\n\nstatic const char input_silence[1960] = {\n    0x23, 0x17, 0xe0, 0x3,  0x9,  0xe7, 0xe7, 0xdb, 0xcf, 0xc5, 0xe0, 0xdb, 0xc5, 0xcf, 0xef, 0xcf,\n    0xcf, 0xdb, 0xef, 0xdb, 0xe7, 0xc5, 0x5,  0x3,  0xfc, 0xe7, 0xf6, 0xdb, 0xcf, 0xe7, 0x9,  0xef,\n    0xef, 0xdb, 0xcf, 0xe7, 0xe0, 0xe7, 0xe0, 0xc5, 0xff, 0xe0, 0x4,  0xcf, 0xdb, 0xb4, 0x80, 0xdb,\n    0xef, 0x80, 0xc5, 0xe4, 0x9,  0xe4, 0xcf, 0xc5, 0xdb, 0xcf, 0xdb, 0xcf, 0xf5, 0xdb, 0xe7, 0xcf,\n    0xef, 0xe4, 0xe7, 0xe4, 0xe7, 0xdb, 0xdb, 0xcf, 0xc5, 0xdb, 0xcf, 0xcf, 0xcf, 0xb4, 0xcf, 0xcf,\n    0x13, 0xef, 0xf5, 0x80, 0x80, 0x80, 0xc5, 0xcf, 0xcf, 0x80, 0x80, 0xcf, 0xf5, 0xcf, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0xcf, 0xf9, 0xdb, 0xcf, 0x80, 0x80, 0xcf, 0xe7, 0xdb, 0xfb, 0xe4, 0xdb, 0xcf,\n    0xe7, 0xcf, 0xe7, 0xb4, 0xdb, 0xe4, 0xcf, 0xb4, 0xfb, 0x0,  0x6,  0xd6, 0xec, 0xb4, 0x80, 0xb4,\n    0x80, 0x80, 0x80, 0x80, 0xf3, 0xb4, 0xdb, 0xdb, 0xc5, 0xb4, 0xc5, 0x80, 0xcf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xea, 0xea, 0xe4, 0xe4, 0xd6,\n    0xef, 0xb4, 0xc5, 0xc5, 0xd6, 0xc5, 0xe4, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xcf, 0xc5, 0x0,  0xdb,\n    0xb4, 0xb4, 0xdb, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0xc5, 0xcf, 0xb4,\n    0xcf, 0xcf, 0xe0, 0xcf, 0xcf, 0x80, 0xb4, 0x80, 0xec, 0xd6, 0xe0, 0xc5, 0xb4, 0xb4, 0xcf, 0x80,\n    0xcf, 0xb4, 0xcf, 0x80, 0xd6, 0xc5, 0x80, 0x80, 0xdb, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xcf, 0x80, 0x80, 0x80, 0xcf, 0xb4, 0xd6, 0xb4, 0xd6, 0xb4, 0xf1, 0xc5, 0xc5, 0x80, 0xb4, 0x80,\n    0x11, 0xc5, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xc5, 0xcf, 0xb4, 0x80,\n    0xe4, 0xb4, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0xcf, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0xb4,\n    0xd6, 0xc5, 0xb4, 0x80, 0xc5, 0x80, 0xb4, 0x80, 0xcf, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xb4, 0xc5, 0xe4, 0xc5, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xef, 0x80, 0xc5, 0xb4, 0xc5, 0xc5, 0xc5, 0xcf, 0xd6, 0xc5, 0xf5, 0xb4, 0xcf, 0x80,\n    0xe4, 0xc5, 0xb4, 0xe0, 0xd6, 0xb4, 0xcf, 0x80, 0xb4, 0xc5, 0xcf, 0x80, 0xe0, 0xc5, 0xd6, 0x80,\n    0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0xb4, 0xc5, 0x80, 0xd6, 0xb4, 0xe0, 0xb4, 0xb4, 0xc5,\n    0xc5, 0xb4, 0xc5, 0x80, 0xc5, 0xc5, 0xd6, 0x80, 0x80, 0x80, 0xf8, 0x80, 0x80, 0xb4, 0xd6, 0x80,\n    0xd6, 0xb4, 0xb4, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0xb4, 0xcf, 0xcf, 0xe7, 0x80, 0xb4, 0x80,\n    0xc5, 0x80, 0xc5, 0x80, 0xb4, 0x80, 0xb4, 0xb4, 0xc5, 0x80, 0xb4, 0x80, 0xc5, 0x80, 0xe0, 0x80,\n    0xef, 0x80, 0xcf, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb4, 0xb4, 0xfd, 0xb4, 0x80, 0xb4,\n    0xe0, 0x80, 0xcf, 0xb4, 0xb4, 0x80, 0xe7, 0xb4, 0xe7, 0xb4, 0xb4, 0xd6, 0xb4, 0x80, 0xe0, 0xc5,\n    0x80, 0x80, 0xc5, 0xc5, 0xd6, 0x80, 0xc5, 0x80, 0xdb, 0xc5, 0xea, 0x80, 0x80, 0x80, 0xb4, 0x80,\n    0xb4, 0x80, 0xe0, 0x80, 0x80, 0x80, 0xc5, 0xb4, 0x80, 0x80, 0xd6, 0x80, 0xb4, 0x80, 0xb4, 0x80,\n    0x80, 0xb4, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xe7, 0xb4, 0xc5, 0x80, 0xd6, 0x80,\n    0xe7, 0xc5, 0xdb, 0x80, 0xdb, 0xcf, 0xe0, 0x80, 0x80, 0x80, 0xc5, 0xb4, 0xdb, 0x80, 0xef, 0xc5,\n    0x80, 0x80, 0x80, 0x80, 0xc5, 0xb4, 0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xd6, 0x80,\n    0xc5, 0xb4, 0xdb, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xe0, 0x80, 0x80, 0xb4, 0xf6, 0xdb, 0xc5, 0x80,\n    0x80, 0x80, 0xc5, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xc5, 0x80, 0xb4, 0xb4, 0xd6, 0xb4, 0xd6, 0x80,\n    0x80, 0xb4, 0xd6, 0xb4, 0x80, 0x80, 0xdb, 0xb4, 0xf3, 0xb4, 0xdb, 0x80, 0x80, 0x80, 0xc5, 0x80,\n    0x1d, 0xcf, 0x16, 0x12, 0x17, 0xc,  0x23, 0x2,  0x1,  0xc5, 0xc5, 0xb4, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0xc5, 0xd6, 0xc5, 0xb4, 0xc5, 0xdb, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb4, 0xb4, 0xdb, 0xc5,\n    0xe4, 0x80, 0xdb, 0x80, 0xc5, 0xb4, 0x80, 0x80, 0x78, 0x64, 0x7a, 0x64, 0x76, 0x60, 0x67, 0x55,\n    0x5a, 0x3a, 0x37, 0x24, 0xf6, 0xc5, 0x14, 0x17, 0x1e, 0x18, 0x31, 0x39, 0x44, 0x43, 0x49, 0x3e,\n    0x39, 0x23, 0x18, 0x17, 0x42, 0x41, 0x40, 0x34, 0x39, 0x34, 0x37, 0x30, 0x38, 0x23, 0x22, 0x9,\n    0x75, 0x63, 0x73, 0x63, 0x77, 0x58, 0x73, 0x5f, 0x64, 0x4d, 0x57, 0x41, 0x58, 0x46, 0x36, 0x32,\n    0x45, 0x51, 0x64, 0x56, 0x72, 0x61, 0x67, 0x57, 0x60, 0x52, 0x49, 0x4e, 0x61, 0x53, 0x62, 0x57,\n    0x67, 0x50, 0x66, 0x56, 0x63, 0x52, 0x5e, 0x3d, 0x6b, 0x5a, 0x70, 0x5d, 0x72, 0x50, 0x6c, 0x56,\n    0x67, 0x5a, 0x69, 0x49, 0x5a, 0x4f, 0x56, 0x50, 0x61, 0x50, 0x6c, 0x5d, 0x71, 0x5d, 0x6e, 0x56,\n    0x6c, 0x58, 0x69, 0x55, 0x6c, 0x57, 0x65, 0x57, 0x6c, 0x56, 0x68, 0x4c, 0x61, 0x58, 0x66, 0x44,\n    0x68, 0x52, 0x6b, 0x56, 0x6c, 0x60, 0x6e, 0x52, 0x72, 0x4e, 0x5b, 0x4d, 0x56, 0x4e, 0x68, 0x51,\n    0x69, 0x5a, 0x6a, 0x5a, 0x72, 0x54, 0x6f, 0x5d, 0x75, 0x5f, 0x67, 0x57, 0x65, 0x48, 0x5c, 0x4c,\n    0x66, 0x52, 0x68, 0x52, 0x63, 0x53, 0x64, 0x44, 0x5f, 0x44, 0x60, 0x49, 0x69, 0x60, 0x71, 0x51,\n    0x6c, 0x59, 0x6c, 0x53, 0x62, 0x4b, 0x5c, 0x4e, 0x61, 0x4c, 0x6a, 0x5c, 0x69, 0x4b, 0x6b, 0x56,\n    0x6b, 0x40, 0x5d, 0x43, 0x6c, 0x55, 0x60, 0x3f, 0x5f, 0x4d, 0x69, 0x52, 0x64, 0x4d, 0x64, 0x41,\n    0x59, 0x3b, 0x55, 0x35, 0x67, 0x55, 0x71, 0x5a, 0x69, 0x58, 0x65, 0x48, 0x5e, 0x4e, 0x6a, 0x55,\n    0x69, 0x55, 0x73, 0x5c, 0x68, 0x35, 0x64, 0x57, 0x6a, 0x43, 0x57, 0x42, 0x63, 0x4c, 0x71, 0x57,\n    0x60, 0x43, 0x5a, 0x44, 0x5c, 0x3e, 0x5d, 0x3e, 0x57, 0x31, 0x46, 0x7,  0x56, 0x4b, 0x73, 0x52,\n    0x64, 0x4b, 0x5b, 0x4a, 0x66, 0x4f, 0x69, 0x4d, 0x69, 0x56, 0x6e, 0x3e, 0x4b, 0x37, 0x5c, 0x44,\n    0x56, 0x24, 0x4f, 0x2a, 0x46, 0x3b, 0x61, 0x4e, 0x61, 0x43, 0x5d, 0x45, 0x5e, 0x44, 0x50, 0x3c,\n    0x56, 0x2d, 0x45, 0x4,  0x50, 0x40, 0x64, 0x57, 0x69, 0x4d, 0x64, 0x50, 0x62, 0x4e, 0x67, 0x4e,\n    0x62, 0x56, 0x67, 0x3c, 0x48, 0x23, 0x58, 0x43, 0x53, 0x28, 0x3b, 0xcf, 0x48, 0x48, 0x5c, 0x40,\n    0x4d, 0x37, 0x4e, 0x3c, 0x56, 0x20, 0x3d, 0x11, 0x37, 0xc5, 0x4a, 0xd6, 0x2d, 0x2b, 0x57, 0x4e,\n    0x5a, 0x44, 0x60, 0x43, 0x5a, 0x3f, 0x5c, 0x41, 0x67, 0x50, 0x60, 0x2f, 0x36, 0x1c, 0x54, 0x3e,\n    0x4f, 0xc,  0x2d, 0x80, 0x36, 0x22, 0x50, 0x41, 0x5f, 0x3e, 0x50, 0x3f, 0x5f, 0x3d, 0x46, 0x19,\n    0x41, 0xfd, 0x33, 0xd6, 0x25, 0x2,  0x40, 0x2f, 0x59, 0x3a, 0x4f, 0x3d, 0x47, 0x23, 0x52, 0x32,\n    0x5c, 0x3e, 0x45, 0xcf, 0xd,  0xdb, 0x42, 0x2a, 0x3f, 0x80, 0x15, 0x80, 0xe4, 0xb4, 0x36, 0x28,\n    0x49, 0x39, 0x52, 0x3a, 0x5a, 0x39, 0x52, 0xb,  0x26, 0x80, 0x27, 0xc5, 0x2f, 0xf6, 0x45, 0x24,\n    0x40, 0x29, 0x52, 0x33, 0x43, 0xfc, 0x33, 0x1d, 0x44, 0x17, 0x2e, 0x80, 0x80, 0x80, 0xb4, 0x80,\n    0x80, 0x80, 0x24, 0x80, 0xb4, 0x80, 0x34, 0x32, 0x4c, 0x32, 0x4b, 0x30, 0x54, 0x3f, 0x51, 0x30,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xe4, 0x80, 0x1,  0x80, 0x26, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xfd, 0x80, 0x80, 0x80, 0xb4, 0x80,\n    0x29, 0xe0, 0xe0, 0xc5, 0x27, 0x80, 0x1b, 0x7,  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x23, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xf9, 0x80, 0x80, 0x80, 0x80, 0x80, 0xd6, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xf5, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xe0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x1d, 0xe4, 0x11, 0xb4, 0x32, 0xa,\n    0x6,  0x80, 0x80, 0x80, 0xd6, 0x80, 0x1c, 0xd,  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x15, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xf8, 0xcf, 0x10, 0x80, 0x17, 0x80, 0x1e, 0x80, 0xff, 0xec, 0x25, 0x80, 0x1c, 0x23,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x11, 0xb4, 0x2,  0x80, 0x30, 0x8,\n    0x15, 0x80, 0x6,  0x20, 0x36, 0xf8, 0x2e, 0x18, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0xf3, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xd,  0x4,  0xa,  0xea, 0x37, 0x24, 0x2a, 0xc,  0x39, 0x26, 0x43, 0x5,  0x2d, 0x1f,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x14, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7,  0xcf, 0xf,  0xef, 0x32, 0xd,\n    0x2a, 0x14, 0x37, 0x1,  0x32, 0x0,  0x38, 0x10, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x1c, 0x80, 0x80, 0x80, 0x28, 0xdb, 0xe4, 0xe0, 0xb4, 0x80, 0x16, 0xcf, 0x1b, 0xb4,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb4, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/testdata/kws/unknown.c",
        "content": "/*\n * This work is a derivative of \"Speech Commands V2\" by Google, used under CC BY 4.0.\n */\n\nstatic const char input_unknown[1960] = {\n    0x78, 0x66, 0x7a, 0x63, 0x78, 0x62, 0x6d, 0x52, 0x58, 0x19, 0x0,  0xcf, 0x80, 0x80, 0x80, 0x80,\n    0xcf, 0xc5, 0xc5, 0xc5, 0x80, 0x80, 0x80, 0xc5, 0xc5, 0xe7, 0xe0, 0x80, 0x80, 0xc5, 0x80, 0xcf,\n    0xc5, 0xc5, 0x80, 0xc5, 0xcf, 0xe7, 0xe0, 0xdb, 0x72, 0x4b, 0x65, 0x60, 0x70, 0x50, 0x73, 0x59,\n    0x60, 0x4f, 0x4d, 0x3c, 0x11, 0xff, 0xc5, 0xc5, 0xdb, 0xdb, 0xcf, 0xec, 0xe7, 0xcf, 0xcf, 0x2,\n    0x31, 0x4d, 0x4c, 0xe7, 0xdb, 0xc5, 0x80, 0xcf, 0xef, 0xe4, 0x4,  0xff, 0xf5, 0xec, 0xef, 0x5,\n    0x6c, 0x4b, 0x56, 0x54, 0x6a, 0x47, 0x6f, 0x5b, 0x63, 0x55, 0x4c, 0x41, 0x2d, 0x22, 0x20, 0x3a,\n    0x4e, 0xf1, 0xcf, 0xfc, 0x19, 0xf3, 0xe7, 0x2d, 0x48, 0x4e, 0x5b, 0x80, 0xcf, 0xcf, 0x80, 0x80,\n    0x80, 0xdb, 0x3,  0xfb, 0xf5, 0xea, 0x0,  0xf5, 0x62, 0x40, 0x46, 0x47, 0x62, 0x41, 0x68, 0x53,\n    0x5f, 0x51, 0x57, 0x4e, 0x5b, 0x51, 0x58, 0x4b, 0x62, 0x2b, 0xef, 0x44, 0x5d, 0x41, 0x49, 0x5c,\n    0x62, 0x56, 0x58, 0x2f, 0xc5, 0xb4, 0xcf, 0xcf, 0xc5, 0xe0, 0xf9, 0xe7, 0x7,  0xf5, 0xa,  0xfc,\n    0x5b, 0x39, 0x35, 0x3d, 0x5c, 0x37, 0x5d, 0x49, 0x57, 0x49, 0x63, 0x57, 0x61, 0x55, 0x5e, 0x4d,\n    0x64, 0x4b, 0x63, 0x58, 0x5c, 0x49, 0x5f, 0x57, 0x6a, 0x56, 0x68, 0x41, 0x15, 0xf1, 0x7,  0xf1,\n    0xf9, 0xef, 0xfd, 0xfb, 0xc,  0xf6, 0x5,  0xef, 0x5a, 0x40, 0x4a, 0x44, 0x69, 0x57, 0x55, 0x50,\n    0x63, 0x49, 0x67, 0x5a, 0x72, 0x60, 0x70, 0x5a, 0x71, 0x61, 0x77, 0x63, 0x75, 0x5e, 0x71, 0x52,\n    0x6f, 0x5f, 0x78, 0x64, 0x78, 0x5d, 0x56, 0x57, 0x56, 0x28, 0x39, 0x3b, 0x58, 0x49, 0x3d, 0x33,\n    0x58, 0x3f, 0x2a, 0x50, 0x6c, 0x53, 0x6a, 0x5b, 0x69, 0x57, 0x6e, 0x5e, 0x73, 0x60, 0x74, 0x5a,\n    0x75, 0x61, 0x76, 0x60, 0x75, 0x59, 0x6e, 0x4c, 0x6b, 0x4c, 0x6b, 0x58, 0x74, 0x61, 0x6e, 0x36,\n    0x49, 0x41, 0x5b, 0x5d, 0x6e, 0x57, 0x5e, 0x44, 0x50, 0x30, 0x3a, 0x46, 0x5f, 0x3c, 0x64, 0x4e,\n    0x5d, 0x53, 0x69, 0x55, 0x6a, 0x57, 0x69, 0x52, 0x71, 0x5a, 0x6b, 0x47, 0x5f, 0x4d, 0x61, 0x43,\n    0x5b, 0x37, 0x59, 0x3e, 0x57, 0x3f, 0x53, 0xe,  0x44, 0x47, 0x5c, 0x43, 0x62, 0x51, 0x5d, 0x3f,\n    0x4a, 0x2a, 0x39, 0x3f, 0x59, 0x37, 0x5c, 0x40, 0x58, 0x50, 0x65, 0x4e, 0x65, 0x52, 0x67, 0x54,\n    0x6f, 0x52, 0x59, 0x3b, 0x57, 0x48, 0x61, 0x49, 0x54, 0xf8, 0x3e, 0x2d, 0x4e, 0x3e, 0x50, 0xc,\n    0x3e, 0x53, 0x67, 0x2d, 0x4c, 0x3b, 0x4f, 0x2a, 0x43, 0x14, 0x46, 0x37, 0x50, 0x23, 0x58, 0x36,\n    0x57, 0x48, 0x63, 0x46, 0x67, 0x4e, 0x65, 0x55, 0x6d, 0x4c, 0x55, 0x35, 0x41, 0x3b, 0x58, 0x3f,\n    0x53, 0x2f, 0x44, 0x25, 0x48, 0x37, 0x58, 0xe4, 0x4d, 0x48, 0x53, 0x2b, 0x41, 0x28, 0x4a, 0x2d,\n    0x3d, 0x5,  0x44, 0x29, 0x44, 0x1c, 0x5c, 0x3b, 0x53, 0x35, 0x5a, 0x3b, 0x60, 0x45, 0x61, 0x50,\n    0x64, 0x3a, 0x43, 0x1f, 0x35, 0x23, 0x4d, 0x4a, 0x5e, 0x3c, 0x4d, 0x30, 0x51, 0x2e, 0x51, 0xf3,\n    0x4d, 0x3e, 0x50, 0x1a, 0x34, 0xfc, 0x44, 0x27, 0x37, 0xf8, 0x3a, 0x9,  0x32, 0x33, 0x5d, 0x37,\n    0x57, 0x35, 0x5d, 0x3b, 0x58, 0x31, 0x60, 0x45, 0x50, 0xff, 0x3a, 0xe0, 0x24, 0x3,  0x24, 0x3a,\n    0x4f, 0xe,  0x32, 0x1d, 0x46, 0x2d, 0x45, 0x4,  0x56, 0x3d, 0x50, 0x7,  0xa,  0x80, 0x3a, 0x1f,\n    0x31, 0xe0, 0x43, 0x3,  0x26, 0x3a, 0x5b, 0x34, 0x56, 0x30, 0x58, 0x2e, 0x53, 0x1f, 0x61, 0x3f,\n    0x3f, 0x80, 0x2f, 0xe4, 0x2f, 0x14, 0x30, 0x1e, 0x50, 0xe0, 0x22, 0x0,  0x4b, 0x2d, 0x39, 0xdb,\n    0x56, 0x3e, 0x46, 0x34, 0x2d, 0x80, 0x29, 0x5,  0x2f, 0xc5, 0x46, 0xfb, 0x1c, 0x3a, 0x56, 0x26,\n    0x53, 0x2b, 0x4e, 0x8,  0x53, 0x25, 0x65, 0x3a, 0xf,  0x80, 0xf5, 0x80, 0xb,  0xd6, 0x1e, 0x7,\n    0x55, 0xd6, 0x6,  0x80, 0x2c, 0x0,  0x11, 0xe4, 0x3e, 0x26, 0x41, 0x25, 0x2c, 0x80, 0x1d, 0x2,\n    0x2a, 0xd6, 0x45, 0xec, 0x4,  0x3c, 0x54, 0x20, 0x4d, 0x12, 0x49, 0xf6, 0x57, 0x32, 0x61, 0x23,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xb,  0xe7, 0x3b, 0x80, 0xc5, 0x80, 0xc5, 0x80, 0xcf, 0xdb,\n    0x14, 0x1d, 0x3d, 0x36, 0x3f, 0x80, 0x19, 0xfc, 0x1f, 0x80, 0x40, 0xea, 0x8,  0x3c, 0x52, 0x22,\n    0x3a, 0xf8, 0x49, 0x3,  0x58, 0x21, 0x3c, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc5, 0x80,\n    0xf6, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x37, 0x2d, 0x3b, 0x1b, 0x31, 0x80, 0x16, 0xf5,\n    0xf3, 0x80, 0x3e, 0xcf, 0xec, 0x3b, 0x4e, 0x12, 0x4,  0x80, 0x4f, 0x26, 0x5a, 0x1a, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xfc, 0xb4,\n    0x2c, 0x0,  0x1b, 0x2a, 0x2f, 0x80, 0xc,  0xdb, 0xd6, 0x80, 0x44, 0xfd, 0x11, 0x33, 0x44, 0xd6,\n    0x8,  0x80, 0x4e, 0xe,  0x26, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0x1,  0x80, 0xe7, 0x80, 0x80, 0x80, 0x80, 0x80, 0x14, 0xdb,\n    0xf8, 0x80, 0x48, 0x0,  0x7,  0xe7, 0x18, 0x80, 0xef, 0x80, 0x36, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xdb, 0x80, 0x80, 0x80, 0x80, 0x80, 0x17, 0x80, 0x80, 0x80, 0x48, 0x6,  0x10, 0x80, 0xf1, 0x80,\n    0x24, 0x80, 0x7,  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x3c, 0xf1, 0x7,  0x80, 0xc5, 0x80, 0x33, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xe0, 0x80, 0x26, 0x80, 0xcf, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xf6, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/testdata/kws/yes.c",
        "content": "/*\n * This work is a derivative of \"Speech Commands V2\" by Google, used under CC BY 4.0.\n */\n\nstatic const char input_yes[1960] = {\n    0x7c, 0x66, 0x79, 0x65, 0x7d, 0x67, 0x7c, 0x67, 0x7c, 0x66, 0x7c, 0x67, 0x7c, 0x67, 0x7d, 0x66,\n    0x7c, 0x67, 0x7d, 0x66, 0x7c, 0x67, 0x7d, 0x66, 0x7c, 0x67, 0x7d, 0x67, 0x7d, 0x67, 0x7d, 0x67,\n    0x7d, 0x67, 0x7d, 0x67, 0x7d, 0x67, 0x7d, 0x67, 0x52, 0x57, 0x78, 0x5a, 0x67, 0x53, 0x6f, 0x4b,\n    0x6d, 0x5c, 0x71, 0x52, 0x66, 0x4d, 0x6e, 0x56, 0x73, 0x50, 0x5f, 0x54, 0x6d, 0x55, 0x6a, 0x5b,\n    0x6f, 0x57, 0x68, 0x50, 0x71, 0x58, 0x6d, 0x57, 0x69, 0x55, 0x6a, 0x55, 0x6c, 0x59, 0x6c, 0x5a,\n    0x5b, 0x3c, 0x54, 0x44, 0x58, 0x4f, 0x66, 0x30, 0x58, 0x50, 0x61, 0x3d, 0x67, 0x36, 0x5b, 0x4d,\n    0x64, 0x51, 0x6a, 0x4d, 0x60, 0x4b, 0x61, 0x53, 0x69, 0x54, 0x60, 0x47, 0x5c, 0x4d, 0x63, 0x45,\n    0x64, 0x4d, 0x63, 0x4b, 0x67, 0x50, 0x68, 0x4d, 0x64, 0x4b, 0x64, 0x4e, 0x5f, 0x3d, 0x53, 0x42,\n    0x59, 0x39, 0x57, 0x43, 0x5e, 0x3a, 0x44, 0x3b, 0x56, 0x3c, 0x5c, 0x46, 0x66, 0x4c, 0x61, 0x3e,\n    0x5d, 0x49, 0x55, 0x48, 0x5d, 0x45, 0x5a, 0x48, 0x5f, 0x41, 0x59, 0x49, 0x5a, 0x46, 0x5d, 0x3b,\n    0x51, 0x3d, 0x4c, 0x44, 0x57, 0x37, 0x54, 0x43, 0x4f, 0xa,  0x32, 0x28, 0x5b, 0x3a, 0x5e, 0x47,\n    0x4d, 0x2b, 0x57, 0x4a, 0x5d, 0x34, 0x52, 0x3e, 0x50, 0x38, 0x54, 0x30, 0x53, 0x41, 0x57, 0x39,\n    0x5c, 0x3c, 0x53, 0x41, 0x5a, 0x1e, 0x4e, 0x41, 0x4d, 0x2c, 0x3e, 0x18, 0x4c, 0x1c, 0x36, 0x11,\n    0x4b, 0x32, 0x52, 0x2f, 0x50, 0x2d, 0x4e, 0x20, 0x50, 0x3c, 0x4a, 0x16, 0x44, 0x22, 0x48, 0x29,\n    0x4d, 0x34, 0x4e, 0x2c, 0x52, 0x2e, 0x46, 0x35, 0x4b, 0x14, 0x50, 0x33, 0x53, 0x3e, 0x50, 0x2d,\n    0x4a, 0x0,  0x4b, 0x3a, 0x47, 0x16, 0x45, 0x32, 0x45, 0x10, 0x42, 0x23, 0x49, 0x39, 0x41, 0x10,\n    0x48, 0x32, 0x4e, 0x30, 0x40, 0x34, 0x46, 0x39, 0x54, 0xf5, 0x49, 0x38, 0x53, 0x2c, 0x4a, 0x37,\n    0x51, 0x2c, 0x46, 0x2f, 0x4c, 0x2a, 0x4d, 0x2b, 0x3d, 0x2f, 0x4e, 0x20, 0x1e, 0x7,  0x41, 0x8,\n    0x39, 0xd,  0x46, 0x20, 0x3b, 0x2a, 0x3f, 0x20, 0x40, 0xe,  0x4e, 0x2e, 0x3e, 0x21, 0x4f, 0x16,\n    0x2e, 0x35, 0x54, 0x32, 0x41, 0x1c, 0x48, 0x2a, 0x44, 0xc,  0x48, 0x21, 0x41, 0x19, 0x48, 0x2a,\n    0x3d, 0x21, 0x44, 0xb4, 0x41, 0x14, 0x3e, 0x2b, 0x45, 0x23, 0x50, 0x28, 0x3e, 0x1f, 0x43, 0x26,\n    0x46, 0x1b, 0x48, 0x12, 0x44, 0x2d, 0x47, 0x22, 0x3c, 0x32, 0x48, 0x26, 0x2f, 0x21, 0x45, 0x17,\n    0x43, 0x22, 0x43, 0x1d, 0x44, 0x28, 0x4d, 0x14, 0x56, 0x23, 0x40, 0x2c, 0x34, 0x80, 0x44, 0xf,\n    0x37, 0x16, 0x49, 0x21, 0x34, 0x1e, 0x3f, 0x22, 0x2b, 0x16, 0x34, 0x28, 0x43, 0x2d, 0x43, 0x11,\n    0x49, 0x1a, 0x46, 0x20, 0x46, 0x21, 0x3d, 0x17, 0x3d, 0x28, 0x3e, 0xf5, 0x33, 0x15, 0x39, 0x20,\n    0x4d, 0x2d, 0x36, 0x80, 0x1a, 0xdb, 0x3e, 0x17, 0x3b, 0x1f, 0x40, 0x17, 0x2b, 0xcf, 0x39, 0x2d,\n    0x4d, 0x2b, 0x35, 0xf6, 0x44, 0x29, 0x3d, 0x24, 0x30, 0x17, 0x3b, 0x28, 0x44, 0xd,  0x38, 0x20,\n    0x3b, 0xf3, 0x45, 0x19, 0x4c, 0x24, 0x37, 0x15, 0xf3, 0xb4, 0x3c, 0x28, 0x36, 0xf3, 0x44, 0x1b,\n    0x48, 0x25, 0x1d, 0xd6, 0x25, 0xcf, 0x3a, 0x9,  0x3f, 0xfc, 0x31, 0xf1, 0x41, 0x24, 0x44, 0x17,\n    0x45, 0x20, 0x42, 0x2,  0x33, 0xb4, 0x31, 0x1b, 0x43, 0x18, 0x2c, 0x14, 0x44, 0xa,  0x43, 0x7,\n    0x4,  0x80, 0x2b, 0xf3, 0x49, 0x2a, 0x47, 0xea, 0x3b, 0xec, 0x30, 0xfb, 0x3c, 0x18, 0x35, 0xff,\n    0x14, 0x18, 0x39, 0x7,  0x3c, 0x5,  0xa,  0xf,  0x35, 0x12, 0x3a, 0x0,  0x2d, 0xc,  0x46, 0x13,\n    0x3e, 0x23, 0x3f, 0x18, 0x3a, 0x16, 0x35, 0xf5, 0x3a, 0x1b, 0x4e, 0x2d, 0x3c, 0xef, 0x3c, 0xfc,\n    0x2e, 0xa,  0x32, 0xb4, 0x23, 0xfb, 0x3e, 0x16, 0x40, 0xe,  0x24, 0x3,  0x44, 0x24, 0x3b, 0xa,\n    0x19, 0x80, 0x28, 0x1a, 0x3b, 0xfb, 0x2a, 0xf,  0x31, 0x4,  0x3a, 0x4,  0x2d, 0xec, 0x29, 0xa,\n    0x25, 0xb4, 0x20, 0xb4, 0x35, 0x1b, 0x31, 0xb4, 0x7,  0xc,  0x4b, 0x1b, 0x1c, 0x80, 0x28, 0xd6,\n    0x23, 0x16, 0x2d, 0xf8, 0x35, 0xf6, 0x45, 0x11, 0x1d, 0xc5, 0x2a, 0xf6, 0x37, 0xea, 0x36, 0x11,\n    0x3f, 0x7,  0x36, 0x11, 0x2e, 0xf1, 0x3b, 0x11, 0x16, 0x2a, 0x3a, 0x6,  0x37, 0xcf, 0x18, 0x80,\n    0x30, 0xd6, 0x14, 0xf1, 0x16, 0xfc, 0x28, 0xe4, 0x3d, 0xe0, 0x2d, 0x80, 0x26, 0xec, 0x3d, 0xf8,\n    0x36, 0xcf, 0x11, 0xef, 0x2c, 0x16, 0x2d, 0xff, 0x35, 0x12, 0x3e, 0xa,  0x35, 0xd,  0x2f, 0xf9,\n    0x3f, 0x2d, 0x40, 0x80, 0xe7, 0x6,  0x2a, 0x80, 0x34, 0x4,  0x5,  0x1d, 0x3d, 0x12, 0x1e, 0xa,\n    0x3f, 0x26, 0x2b, 0xfb, 0x2b, 0x80, 0x26, 0x80, 0x1e, 0x15, 0x24, 0xdb, 0x2a, 0xd6, 0x2b, 0x80,\n    0x6,  0xdb, 0x26, 0xfd, 0x37, 0xec, 0x2a, 0xec, 0x2,  0x1c, 0x3c, 0xe7, 0x11, 0x80, 0xf3, 0xfd,\n    0x3a, 0x1,  0x28, 0x17, 0x3a, 0xdb, 0xf6, 0x80, 0x2,  0xd6, 0x21, 0xcf, 0x2a, 0xdb, 0xf,  0x80,\n    0x2b, 0x17, 0x24, 0xcf, 0x2e, 0xcf, 0x30, 0xf8, 0xa,  0xf1, 0x26, 0xe7, 0x2d, 0xf5, 0x31, 0xef,\n    0x25, 0x80, 0x1,  0xfb, 0xd6, 0x80, 0x19, 0x1c, 0x37, 0xfb, 0x39, 0x11, 0x2c, 0x80, 0x23, 0x18,\n    0x33, 0xf8, 0x2e, 0xd,  0x34, 0xcf, 0x2b, 0xf1, 0x21, 0x80, 0x29, 0x80, 0x1f, 0xe4, 0xe,  0xb,\n    0x25, 0xc5, 0x1f, 0xc5, 0x21, 0x0,  0x19, 0x80, 0xef, 0x80, 0xb,  0xe4, 0x1c, 0xcf, 0x33, 0x16,\n    0x3e, 0x7,  0x21, 0xf5, 0x2f, 0x0,  0x2e, 0xef, 0x23, 0x6,  0x3d, 0xe7, 0x23, 0xe7, 0x26, 0xd6,\n    0x40, 0xfd, 0x30, 0x80, 0xa,  0xf5, 0x35, 0x0,  0x32, 0xf8, 0x20, 0xcf, 0x2d, 0xef, 0x32, 0x13,\n    0x3c, 0x1c, 0x0,  0xfc, 0x26, 0xe0, 0x26, 0xd6, 0xec, 0x80, 0x16, 0xf3, 0xb4, 0xf1, 0x31, 0xcf,\n    0x1f, 0x80, 0x7,  0xf6, 0x19, 0xfd, 0xe7, 0x80, 0x1,  0x80, 0x1c, 0x2,  0x2f, 0x80, 0x2f, 0x80,\n    0x26, 0x4,  0x1c, 0xb4, 0x4,  0xdb, 0x1e, 0xcf, 0x2a, 0x80, 0xdb, 0x80, 0x1a, 0xea, 0x31, 0xa,\n    0x18, 0x23, 0x39, 0xf8, 0x36, 0x22, 0x25, 0xc5, 0x1f, 0x80, 0x26, 0xef, 0x34, 0x80, 0x19, 0xe7,\n    0x2d, 0xe0, 0x17, 0xe4, 0x2f, 0x17, 0x34, 0x7,  0x31, 0xef, 0x25, 0xe0, 0x1e, 0xf8, 0x1d, 0xdb,\n    0xfd, 0xb,  0x11, 0x80, 0x11, 0x80, 0xe7, 0xcf, 0x32, 0x80, 0xc,  0xdb, 0xa,  0x80, 0xf9, 0x80,\n    0x14, 0x14, 0x35, 0x80, 0x2c, 0xf9, 0x1f, 0xdb, 0x1b, 0xea, 0x11, 0x80, 0x26, 0xc5, 0xb,  0xb4,\n    0xb,  0x80, 0x7,  0xef, 0x22, 0x6,  0x20, 0xe0, 0x0,  0x80, 0x1a, 0x1c, 0x25, 0xfb, 0x2f, 0x80,\n    0x80, 0xea, 0x31, 0x19, 0x3c, 0xf,  0x23, 0x80, 0x16, 0x0,  0x38, 0xf1, 0x21, 0xea, 0x2c, 0x80,\n    0x1e, 0xec, 0x2a, 0xe4, 0x7,  0x80, 0xf8, 0x80, 0x9,  0xd6, 0x20, 0xc5, 0x18, 0x80, 0x0,  0x14,\n    0x2a, 0xcf, 0x1d, 0x80, 0xc,  0xe4, 0x1c, 0xa,  0x3a, 0x24, 0x1b, 0x80, 0xf8, 0x80, 0x8,  0x80,\n    0x9,  0x80, 0x20, 0xdb, 0x20, 0xd6, 0x2d, 0x19, 0x1a, 0xd6, 0x25, 0x80, 0xb4, 0x80, 0x38, 0x12,\n    0x17, 0xec, 0x14, 0x80, 0x20, 0xb4, 0x13, 0xdb, 0xb,  0x80, 0xfc, 0x15, 0x2f, 0x0,  0xdb, 0x80,\n    0xf5, 0x0,  0x8,  0xcf, 0xf8, 0xe4, 0xc,  0x13, 0x34, 0x80, 0x17, 0x80, 0xe7, 0x80, 0x11, 0xcf,\n    0x2f, 0xf6, 0x5,  0xdb, 0x27, 0x6,  0xf1, 0x80, 0x11, 0xc5, 0x24, 0x80, 0x11, 0xea, 0xa,  0x80,\n    0x23, 0x1,  0x16, 0xf3, 0xfb, 0x80, 0x15, 0x13, 0x33, 0x6,  0xfc, 0x80, 0xd6, 0x80, 0x10, 0x80,\n    0x1a, 0xf5, 0x11, 0x80, 0x9,  0xc5, 0xf,  0xcf, 0xef, 0xc5, 0x1b, 0xf9, 0x8,  0x80, 0x20, 0xc5,\n    0x1c, 0xdb, 0x1f, 0x80, 0x1e, 0xf3, 0x12, 0xea, 0x26, 0xcf, 0x16, 0xcf, 0x2,  0xd6, 0x7,  0x80,\n    0x24, 0x80, 0xf9, 0xcf, 0x1a, 0xb4, 0x26, 0xc5, 0xfb, 0x80, 0xfc, 0xc5, 0xef, 0xcf, 0x28, 0x80,\n    0x19, 0xcf, 0x28, 0xea, 0x2c, 0xc5, 0x2f, 0xc,  0x1,  0xec, 0x2d, 0xb4, 0x14, 0x80, 0xc,  0xec,\n    0xf5, 0xdb, 0x0,  0xc5, 0x20, 0x80, 0x21, 0x1,  0x0,  0x80, 0xa,  0x80, 0x29, 0x80, 0xdb, 0x7,\n    0xf,  0xb4, 0x23, 0xfb, 0x27, 0xdb, 0x22, 0xec, 0x21, 0x80, 0xd6, 0xb4, 0x15, 0xd6, 0x11, 0x80,\n    0x1f, 0xc5, 0x1a, 0xb4, 0x7,  0xe0, 0x21, 0xcf, 0x14, 0x16, 0x2a, 0x80, 0x80, 0x80, 0xa,  0xe7,\n    0x6,  0x80, 0xb4, 0x80, 0xf,  0x80, 0xfc, 0xe4, 0x13, 0x80, 0x19, 0xb4, 0xd,  0xb4, 0xdb, 0xc5,\n    0x18, 0x80, 0x21, 0xb4, 0x2d, 0xc5, 0xf1, 0xdb, 0xf,  0x80, 0x23, 0xd6, 0x28, 0x80, 0xea, 0xd6,\n    0xe7, 0xcf, 0x11, 0xe4, 0xec, 0x2,  0x20, 0xb4, 0x29, 0xdb, 0x6,  0x80, 0xef, 0x80, 0xe0, 0x80,\n    0x4,  0xc5, 0x32, 0xb4, 0x2f, 0x80, 0x7,  0xb4, 0xe0, 0x80, 0xf5, 0x80, 0x5,  0xb4, 0x8,  0xcf,\n    0x1f, 0xf6, 0x28, 0xdb, 0x1b, 0xff, 0x12, 0x80, 0x2a, 0xff, 0x2f, 0xfc, 0xcf, 0x80, 0xc,  0xf1,\n    0x21, 0x80, 0x2,  0x1,  0x2d, 0xf8, 0xf9, 0xf3, 0x25, 0x80, 0xdb, 0x80, 0xd6, 0x80, 0xc,  0xe4,\n    0x1b, 0xc5, 0xe0, 0xec, 0xec, 0x80, 0x6,  0xb4, 0xf5, 0xcf, 0xc,  0x80, 0x1,  0xf6, 0x1d, 0x80,\n    0xe7, 0x80, 0xf3, 0x80, 0xc5, 0x80, 0xf6, 0x80, 0x1b, 0xcf, 0x11, 0x80, 0xd6, 0x80, 0x80, 0x80,\n    0xdb, 0x80, 0xec, 0x80, 0x19, 0xe0, 0x2,  0x80, 0x19, 0xef, 0x16, 0x80, 0xd6, 0x80, 0xe7, 0x80,\n    0x11, 0xd6, 0xfc, 0x80, 0xa,  0xd6, 0x17, 0xe7, 0xe4, 0x80, 0xb4, 0xb4, 0x1d, 0xb4, 0xf,  0x80,\n    0x32, 0xfb, 0x1b, 0xdb, 0x25, 0xec, 0xf5, 0x80, 0xd6, 0xef, 0x23, 0xec, 0x14, 0x80, 0xe0, 0xdb,\n    0xf9, 0x80, 0xcf, 0x80, 0xff, 0xb4, 0xd,  0x80, 0xe4, 0x80, 0x0,  0xc5, 0x1f, 0xdb, 0x23, 0xe0,\n    0x1,  0x80, 0x80, 0x80, 0xcf, 0x80, 0xb4, 0x80, 0xe0, 0xf6, 0x1d, 0xcf, 0xdb, 0x80, 0xdb, 0x80,\n    0x80, 0xb4, 0xb,  0x80, 0x80, 0x80, 0x1d, 0x80, 0x4,  0xe4, 0xf5, 0x80, 0x80, 0x80, 0x4,  0x80,\n    0xe4, 0x80, 0xfc, 0x80, 0xd6, 0x80, 0xf9, 0x80, 0x80, 0xb4, 0xc,  0x80, 0x26, 0xf9, 0x80, 0x80,\n    0xb4, 0x80, 0xf1, 0x80, 0x80, 0x80, 0xf3, 0xb4, 0x0,  0x80, 0x2,  0xcf, 0xb4, 0xea, 0x14, 0x80,\n    0x18, 0x80, 0xcf, 0x80, 0xd,  0x80, 0xe0, 0x80, 0x16, 0x80, 0xf8, 0xc5, 0x11, 0xb4, 0xf8, 0x80,\n    0x80, 0x80, 0x80, 0x80, 0xe4, 0xe,  0x1c, 0x80, 0xfc, 0xb4, 0x2a, 0x6,  0x31, 0x10, 0x1c, 0x80,\n    0xfd, 0xfc, 0xc,  0xe7, 0xea, 0x80, 0xe7, 0xd6, 0xd,  0xb4, 0x22, 0xf1, 0x7,  0xb4, 0x1d, 0xf6,\n    0x11, 0xd6, 0x28, 0x80, 0xc5, 0xb4, 0x1f, 0xe0, 0x80, 0x80, 0x80, 0x80, 0xfb, 0xe7, 0xc,  0x80,\n    0xdb, 0x80, 0xcf, 0x80, 0x80, 0x80, 0xd6, 0xc5, 0xf,  0x80, 0x80, 0xb4, 0x1b, 0x80, 0x0,  0xdb,\n    0xf5, 0x80, 0x80, 0x80, 0x15, 0xec, 0xf,  0x80, 0xd6, 0x80, 0x80, 0xb4, 0xc,  0xd6, 0xd6, 0x80,\n    0xd6, 0xd6, 0x9,  0x80, 0x80, 0x80, 0x3,  0xc5, 0x9,  0x80, 0x80, 0x80, 0xe4, 0x80, 0xf3, 0x80,\n    0x10, 0xea, 0xb4, 0x80, 0xdb, 0xf3, 0xa,  0x80, 0xc5, 0x80, 0xef, 0x80, 0xc5, 0x80, 0xec, 0x80,\n    0xff, 0x80, 0xa,  0xc5, 0xf1, 0x80, 0xb4, 0x80, 0xe0, 0x80, 0xfb, 0x80, 0xf8, 0x80, 0x3,  0x80,\n    0xc,  0xcf, 0x80, 0xd6, 0xe0, 0x80, 0x80, 0xb4, 0xcf, 0xc5, 0x28, 0xd6, 0x17, 0x80, 0x80, 0x80,\n    0xc5, 0xec, 0x14, 0x80, 0xf3, 0x80, 0xf8, 0x80, 0xf3, 0x80, 0xcf, 0x80, 0xf8, 0xe0, 0xea, 0x80,\n    0xc5, 0x0,  0x35, 0xea, 0x3,  0x80, 0x80, 0x80, 0x17, 0xf,  0x16, 0x80, 0x19, 0xd6, 0x80, 0x80,\n    0x80, 0x80, 0xe0, 0x80, 0xfd, 0x80, 0x4,  0xfc, 0x1e, 0x80, 0xef, 0x80, 0xef, 0xf1, 0x1f, 0x80,\n    0xfc, 0x80, 0xe7, 0x80, 0xff, 0x80, 0xf8, 0x80, 0x80, 0x80, 0x17, 0x80, 0xcf, 0xfb, 0x1c, 0x0,\n    0x26, 0x11, 0x16, 0x80, 0x80, 0xb4, 0x80, 0x80, 0x80, 0xcf, 0xf3, 0x80, 0x14, 0xb4, 0xdb, 0x5,\n    0x19, 0x80, 0xd6, 0x80, 0xf5, 0x80, 0x17, 0xc5, 0x0,  0xc5, 0xcf, 0xc5, 0x4,  0x80, 0x5,  0x80,\n    0xa,  0x80, 0x19, 0xd6, 0x28, 0x5,  0xea, 0x80, 0x80, 0x80, 0x80, 0xec, 0xd,  0x80, 0x80, 0x80,\n    0x2,  0x80, 0xf1, 0x80, 0x80, 0x80, 0xd6, 0x80, 0xd6, 0x80, 0xdb, 0x80, 0xf3, 0x80, 0xff, 0x80,\n    0x80, 0xc5, 0x20, 0x80, 0xea, 0x80, 0xb4, 0x80, 0x22, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc5, 0x80,\n    0x15, 0x80, 0x24, 0xc5, 0xfc, 0x80, 0xb,  0xe4, 0xcf, 0x80, 0x80, 0x80, 0xe7, 0xa,  0x1,  0xdb,\n    0x12, 0x80, 0xf5, 0x80, 0x80, 0x80, 0xa,  0xd6, 0xfd, 0xf5, 0xfc, 0xcf, 0xe,  0x80, 0xd6, 0x80,\n    0x80, 0x80, 0xef, 0x80, 0xfd, 0xc5, 0x12, 0xea, 0x20, 0x80, 0xe0, 0xdb, 0xc5, 0xd6, 0x1a, 0x80,\n    0x80, 0xd6, 0x14, 0xc5, 0x80, 0x80, 0x80, 0xb4, 0x80, 0x80, 0xc5, 0xb4, 0xe4, 0xb4, 0xf6, 0x3,\n    0xfc, 0x80, 0x80, 0x80, 0xfb, 0x80, 0x0,  0xe4, 0x80, 0x80, 0xb4, 0x80, 0x5,  0xb4, 0x80, 0x80,\n    0x19, 0xd6, 0xe0, 0x80, 0x80, 0x80, 0xb4, 0xc5, 0xb4, 0x80, 0xfb, 0x4,  0x13, 0x80, 0xf,  0xc5,\n    0x2,  0xec, 0xb4, 0xb4, 0xef, 0x80, 0xe0, 0x80, 0xcf, 0xf5, 0x1,  0x80, 0xe4, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0x80, 0x1,  0x1c, 0x80, 0x80, 0x80, 0xc5, 0xcf, 0xc,  0x80, 0x80, 0x80, 0x80, 0x80,\n    0x80, 0x80, 0xfb, 0xc5, 0xcf, 0xdb, 0xcf, 0x80, 0xd6, 0x80, 0xea, 0x80, 0x80, 0x80, 0xd6, 0x80,\n    0x80, 0xcf, 0xf9, 0xdb, 0xf8, 0x80, 0xdb, 0xb4, 0xff, 0xe0, 0xb4, 0x80, 0x80, 0x80, 0x80, 0x80,\n    0xea, 0x80, 0xc5, 0x80, 0x80, 0x80, 0xe0, 0xec, 0xf5, 0x80, 0x80, 0x80, 0x17, 0x80, 0xcf, 0x80,\n    0xf8, 0xf6, 0xe7, 0x80, 0xd6, 0x80, 0xcf, 0x80, 0x80, 0x80, 0xb4, 0x80, 0xe4, 0x80, 0xf8, 0x80,\n    0x80, 0x80, 0xdb, 0x80, 0xfb, 0x80, 0x80, 0x80, 0xf3, 0x80, 0x11, 0xc5, 0x80, 0x80, 0xb4, 0x80,\n    0x80, 0x80, 0xd6, 0x80, 0xec, 0xb4, 0x14, 0xb4, 0xf3, 0x80, 0xf9, 0x80, 0x8,  0x80, 0x80, 0x80,\n    0xe7, 0x80, 0x80, 0xc5, 0xf1, 0x80, 0xf3, 0x80};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\npytest_plugins = [\n    \"tvm.micro.testing.pytest_plugin\",\n]\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n    parser.addoption(\n        \"--west-cmd\", default=\"west\", help=\"Path to `west` command for flashing device.\"\n    )\n    parser.addoption(\n        \"--use-fvp\",\n        action=\"store_true\",\n        default=False,\n        help=\"If set true, use the FVP emulator to run the test\",\n    )\n\n\n@pytest.fixture(scope=\"session\")\ndef west_cmd(request):\n    return request.config.getoption(\"--west-cmd\")\n\n\n@pytest.fixture\ndef use_fvp(request):\n    return request.config.getoption(\"--use-fvp\")\n\n\n@pytest.fixture(autouse=True)\ndef xfail_on_fvp(request, use_fvp):\n    \"\"\"mark the tests as xfail if running on fvp.\"\"\"\n    if request.node.get_closest_marker(\"xfail_on_fvp\"):\n        if use_fvp:\n            request.node.add_marker(\n                pytest.mark.xfail(reason=\"checking corstone300 reliability on CI\")\n            )\n\n\ndef pytest_configure(config):\n    config.addinivalue_line(\n        \"markers\",\n        \"xfail_on_fvp(): mark test as xfail on fvp\",\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/test_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport io\nimport os\nimport json\nimport pathlib\nimport tarfile\nimport tempfile\nimport logging\n\nimport numpy as np\n\nfrom urllib.request import urlopen, urlretrieve\nfrom urllib.error import HTTPError\nimport json\nimport requests\n\nimport tvm.micro\nfrom tvm.micro import export_model_library_format\nfrom tvm.micro.model_library_format import generate_c_interface_header\nfrom tvm.micro.testing.utils import (\n    mlf_extract_workspace_size_bytes,\n    aot_transport_init_wait,\n    aot_transport_find_message,\n)\n\nTEMPLATE_PROJECT_DIR = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"zephyr\"))\n\nBOARDS = TEMPLATE_PROJECT_DIR / \"boards.json\"\n\n_LOG = logging.getLogger(__name__)\n\n\ndef zephyr_boards() -> dict:\n    \"\"\"Returns a dict mapping board to target model\"\"\"\n    with open(BOARDS) as f:\n        board_properties = json.load(f)\n\n    boards_model = {board: info[\"model\"] for board, info in board_properties.items()}\n    return boards_model\n\n\nZEPHYR_BOARDS = zephyr_boards()\n\n\ndef qemu_boards(board: str):\n    \"\"\"Returns True if board is QEMU.\"\"\"\n    with open(BOARDS) as f:\n        board_properties = json.load(f)\n\n    qemu_boards = [name for name, board in board_properties.items() if board[\"is_qemu\"]]\n    return board in qemu_boards\n\n\ndef has_fpu(board: str):\n    \"\"\"Returns True if board has FPU.\"\"\"\n    with open(BOARDS) as f:\n        board_properties = json.load(f)\n\n    fpu_boards = [name for name, board in board_properties.items() if board[\"fpu\"]]\n    return board in fpu_boards\n\n\ndef build_project(\n    temp_dir, zephyr_board, west_cmd, mod, build_config, simd=False, extra_files_tar=None\n):\n    project_dir = temp_dir / \"project\"\n\n    with tempfile.TemporaryDirectory() as tar_temp_dir:\n        model_tar_path = pathlib.Path(tar_temp_dir) / \"model.tar\"\n        export_model_library_format(mod, model_tar_path)\n\n        workspace_size = mlf_extract_workspace_size_bytes(model_tar_path)\n        project_options = {\n            \"extra_files_tar\": extra_files_tar,\n            \"project_type\": \"aot_standalone_demo\",\n            \"west_cmd\": west_cmd,\n            \"verbose\": bool(build_config.get(\"debug\")),\n            \"board\": zephyr_board,\n            \"compile_definitions\": [\n                # TODO(mehrdadh): It fails without offset.\n                f\"-DWORKSPACE_SIZE={workspace_size + 128}\",\n            ],\n        }\n        if simd:\n            project_options[\"config_main_stack_size\"] = 1536\n\n        project = tvm.micro.project.generate_project_from_mlf(\n            str(TEMPLATE_PROJECT_DIR), project_dir, model_tar_path, project_options\n        )\n        project.build()\n    return project, project_dir\n\n\ndef create_header_file(tensor_name, npy_data, output_path, tar_file):\n    \"\"\"\n    This method generates a header file containing the data contained in the numpy array provided.\n    It is used to capture the tensor data (for both inputs and expected outputs).\n    \"\"\"\n    header_file = io.StringIO()\n    header_file.write(\"#include <stddef.h>\\n\")\n    header_file.write(\"#include <stdint.h>\\n\")\n    header_file.write(\"#include <dlpack/dlpack.h>\\n\")\n    header_file.write(f\"const size_t {tensor_name}_len = {npy_data.size};\\n\")\n\n    if npy_data.dtype == \"int8\":\n        header_file.write(f\"int8_t {tensor_name}[] =\")\n    elif npy_data.dtype == \"int32\":\n        header_file.write(f\"int32_t {tensor_name}[] = \")\n    elif npy_data.dtype == \"uint8\":\n        header_file.write(f\"uint8_t {tensor_name}[] = \")\n    elif npy_data.dtype == \"float32\":\n        header_file.write(f\"float {tensor_name}[] = \")\n    else:\n        raise ValueError(\"Data type not expected.\")\n\n    header_file.write(\"{\")\n    for i in np.ndindex(npy_data.shape):\n        header_file.write(f\"{npy_data[i]}, \")\n    header_file.write(\"};\\n\\n\")\n\n    header_file_bytes = bytes(header_file.getvalue(), \"utf-8\")\n    raw_path = pathlib.Path(output_path) / f\"{tensor_name}.h\"\n    ti = tarfile.TarInfo(name=str(raw_path))\n    ti.size = len(header_file_bytes)\n    ti.mode = 0o644\n    ti.type = tarfile.REGTYPE\n    tar_file.addfile(ti, io.BytesIO(header_file_bytes))\n\n\n# TODO move CMSIS integration to microtvm_api_server.py\n# see https://discuss.tvm.apache.org/t/tvm-capturing-dependent-libraries-of-code-generated-tir-initially-for-use-in-model-library-format/11080\ndef loadCMSIS(temp_dir):\n    REPO_PATH = \"ARM-software/CMSIS_5\"\n    BRANCH = \"master\"\n    API_PATH_URL = f\"https://api.github.com/repos/{REPO_PATH}/git/trees\"\n    RAW_PATH_URL = f\"https://raw.githubusercontent.com/{REPO_PATH}/{BRANCH}\"\n\n    url = \"https://api.github.com/repos/ARM-software/CMSIS_5/git/trees/master?recursive=1\"\n    r = requests.get(url)\n    res = r.json()\n\n    include_trees = {}\n\n    for file in res[\"tree\"]:\n        if file[\"path\"] in {\"CMSIS/DSP/Include\", \"CMSIS/DSP/Include/dsp\", \"CMSIS/NN/Include\"}:\n            include_trees.update({file[\"path\"]: file[\"sha\"]})\n\n    for path, sha in include_trees.items():\n        url = f\"{API_PATH_URL}/{sha}\"\n        content = json.load(urlopen(url))\n        temp_path = f\"{temp_dir}\"\n        if path == \"CMSIS/DSP/Include/dsp\":\n            temp_path = f\"{temp_dir}/dsp\"\n            if not os.path.isdir(temp_path):\n                os.makedirs(temp_path)\n        for item in content[\"tree\"]:\n            if item[\"type\"] == \"blob\":\n                file_name = item[\"path\"]\n                file_url = f\"{RAW_PATH_URL}/{path}/{file_name}\"\n                print(file_name, \"   \", file_url)\n                try:\n                    urlretrieve(file_url, f\"{temp_path}/{file_name}\")\n                except HTTPError as e:\n                    print(f\"Failed to download {file_url}: {e}\")\n\n\ndef run_model(project):\n    project.flash()\n\n    with project.transport() as transport:\n        aot_transport_init_wait(transport)\n        transport.write(b\"infer%\", timeout_sec=5)\n        result_line = aot_transport_find_message(transport, \"result\", timeout_sec=60)\n\n    result_line = result_line.strip(\"\\n\")\n    result_line = result_line.split(\":\")\n    result = int(result_line[1])\n    time = int(result_line[2])\n    _LOG.info(f\"Result: {result}\\ttime: {time} ms\")\n\n    return result, time\n\n\ndef generate_project(\n    temp_dir, board, west_cmd, lowered, build_config, sample, output_shape, output_type, load_cmsis\n):\n    with tempfile.NamedTemporaryFile() as tar_temp_file:\n        with tarfile.open(tar_temp_file.name, \"w:gz\") as tf:\n            with tempfile.TemporaryDirectory() as tar_temp_dir:\n                model_files_path = os.path.join(tar_temp_dir, \"include\")\n                os.mkdir(model_files_path)\n                if load_cmsis:\n                    loadCMSIS(model_files_path)\n                    tf.add(\n                        model_files_path, arcname=os.path.relpath(model_files_path, tar_temp_dir)\n                    )\n                header_path = generate_c_interface_header(\n                    lowered.libmod_name, [\"input_1\"], [\"Identity\"], [], {}, [], 0, model_files_path\n                )\n                tf.add(header_path, arcname=os.path.relpath(header_path, tar_temp_dir))\n\n            create_header_file(\"input_data\", sample, \"include\", tf)\n            create_header_file(\n                \"output_data\", np.zeros(shape=output_shape, dtype=output_type), \"include\", tf\n            )\n\n        project, project_dir = build_project(\n            temp_dir,\n            board,\n            west_cmd,\n            lowered,\n            build_config,\n            simd=load_cmsis,\n            extra_files_tar=tar_temp_file.name,\n        )\n\n    return project, project_dir\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/test_zephyr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport logging\nimport os\nimport pathlib\nimport logging\n\nimport pytest\nimport numpy as np\n\nimport onnx\nfrom PIL import Image\n\nimport tvm\nimport tvm.testing\nimport tvm.relay as relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.relay.testing import byoc\nfrom tvm.contrib import utils\nfrom tvm.micro.testing.utils import check_tune_log\n\nimport test_utils\n\n_LOG = logging.getLogger(__name__)\n\n\ndef _make_sess_from_op(\n    temp_dir, model, zephyr_board, west_cmd, op_name, sched, arg_bufs, build_config, use_fvp\n):\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    target = tvm.target.target.micro(model)\n    target = tvm.target.Target(target=target, host=target)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.build(sched, arg_bufs, target=target, runtime=runtime, name=op_name)\n\n    return _make_session(temp_dir, zephyr_board, west_cmd, mod, build_config, use_fvp)\n\n\ndef _make_session(temp_dir, zephyr_board, west_cmd, mod, build_config, use_fvp):\n    config_main_stack_size = None\n    if test_utils.qemu_boards(zephyr_board):\n        config_main_stack_size = 1536\n\n    project_options = {\n        \"project_type\": \"host_driven\",\n        \"west_cmd\": west_cmd,\n        \"verbose\": bool(build_config.get(\"debug\")),\n        \"board\": zephyr_board,\n        \"arm_fvp_path\": \"/opt/arm/FVP_Corstone_SSE-300/models/Linux64_GCC-6.4/FVP_Corstone_SSE-300_Ethos-U55\",\n        \"use_fvp\": bool(use_fvp),\n    }\n    if config_main_stack_size is not None:\n        project_options[\"config_main_stack_size\"] = config_main_stack_size\n\n    project = tvm.micro.generate_project(\n        str(test_utils.TEMPLATE_PROJECT_DIR),\n        mod,\n        temp_dir / \"project\",\n        project_options,\n    )\n    project.build()\n    project.flash()\n    return tvm.micro.Session(project.transport())\n\n\ndef _make_add_sess(temp_dir, model, zephyr_board, west_cmd, build_config, use_fvp, dtype=\"int8\"):\n    A = tvm.te.placeholder((2,), dtype=dtype)\n    B = tvm.te.placeholder((1,), dtype=dtype)\n    C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name=\"C\")\n    sched = tvm.te.create_schedule(C.op)\n    return _make_sess_from_op(\n        temp_dir, model, zephyr_board, west_cmd, \"add\", sched, [A, B, C], build_config, use_fvp\n    )\n\n\n# The same test code can be executed on both the QEMU simulation and on real hardware.\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_add_uint(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_basic_add(sess):\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        system_lib.get_function(\"add\")(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([6, 7])).all()\n\n    with _make_add_sess(workspace_dir, model, board, west_cmd, build_config, use_fvp) as sess:\n        test_basic_add(sess)\n\n\n# The same test code can be executed on both the QEMU simulation and on real hardware.\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_add_float(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    if not test_utils.has_fpu(board):\n        pytest.skip(f\"FPU not enabled for {board}\")\n\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_basic_add(sess):\n        A_data = tvm.nd.array(np.array([2.5, 3.5], dtype=\"float32\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2.5, 3.5])).all()\n        B_data = tvm.nd.array(np.array([4.5], dtype=\"float32\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4.5])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"float32\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        system_lib.get_function(\"add\")(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([7, 8])).all()\n\n    with _make_add_sess(\n        workspace_dir, model, board, west_cmd, build_config, use_fvp, dtype=\"float32\"\n    ) as sess:\n        test_basic_add(sess)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_platform_timer(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_basic_add(sess):\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        time_eval_f = system_lib.time_evaluator(\n            \"add\", sess.device, number=20, repeat=3, min_repeat_ms=40\n        )\n        result = time_eval_f(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([6, 7])).all()\n        assert result.mean > 0\n        assert len(result.results) == 3\n\n    with _make_add_sess(workspace_dir, model, board, west_cmd, build_config, use_fvp) as sess:\n        test_basic_add(sess)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_relay(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Testing a simple relay graph\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    shape = (10,)\n    dtype = \"int8\"\n\n    # Construct Relay program.\n    x = relay.var(\"x\", relay.TensorType(shape=shape, dtype=dtype))\n    xx = relay.multiply(x, x)\n    z = relay.add(xx, relay.const(np.ones(shape=shape, dtype=dtype)))\n    func = relay.Function([x], z)\n    ir_mod = tvm.IRModule.from_expr(func)\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    target = tvm.target.target.micro(model)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(ir_mod, target=target, runtime=runtime)\n\n    with _make_session(workspace_dir, board, west_cmd, mod, build_config, use_fvp) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            mod.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**mod.get_params())\n        x_in = np.random.randint(10, size=shape[0], dtype=dtype)\n        graph_mod.run(x=x_in)\n        result = graph_mod.get_output(0).numpy()\n        tvm.testing.assert_allclose(graph_mod.get_input(0).numpy(), x_in)\n        tvm.testing.assert_allclose(result, x_in * x_in + 1)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_onnx(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Testing a simple ONNX model.\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    this_dir = pathlib.Path(os.path.dirname(__file__))\n    mnist_testdata = this_dir.parent / \"testdata\" / \"mnist\"\n    digit_2 = Image.open(mnist_testdata / \"digit-2.jpg\").resize((28, 28))\n    digit_2 = np.asarray(digit_2).astype(\"float32\")\n    digit_2 = np.expand_dims(digit_2, axis=0)\n\n    digit_9 = Image.open(mnist_testdata / \"digit-9.jpg\").resize((28, 28))\n    digit_9 = np.asarray(digit_9).astype(\"float32\")\n    digit_9 = np.expand_dims(digit_9, axis=0)\n\n    # Load ONNX model and convert to Relay.\n    onnx_model = onnx.load(mnist_testdata / \"mnist-8.onnx\")\n    shape = {\"Input3\": (1, 1, 28, 28)}\n    relay_mod, params = relay.frontend.from_onnx(onnx_model, shape=shape, freeze_params=True)\n    relay_mod = relay.transform.DynamicToStatic()(relay_mod)\n\n    # We add the link-params=True option to ensure the model parameters are compiled in.\n    # There is currently a bug preventing the host_driven environment from receiving\n    # the model weights when set using graph_mod.set_input().\n    # See: https://github.com/apache/tvm/issues/7567\n    target = tvm.target.target.micro(model)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        executor = Executor(\"graph\", {\"link-params\": True})\n        runtime = Runtime(\"crt\", {\"system-lib\": True})\n        lowered = relay.build(relay_mod, target, params=params, executor=executor, runtime=runtime)\n        graph = lowered.get_graph_json()\n\n    with _make_session(workspace_dir, board, west_cmd, lowered, build_config, use_fvp) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            graph, session.get_system_lib(), session.device\n        )\n\n        # Send the digit-2 image and confirm that the correct result is returned.\n        graph_mod.set_input(\"Input3\", tvm.nd.array(digit_2))\n        graph_mod.run()\n        result = graph_mod.get_output(0).numpy()\n        assert np.argmax(result) == 2\n\n        # Send the digit-9 image and confirm that the correct result is returned.\n        graph_mod.set_input(\"Input3\", tvm.nd.array(digit_9))\n        graph_mod.run()\n        result = graph_mod.get_output(0).numpy()\n        assert np.argmax(result) == 9\n\n\ndef check_result(\n    temp_dir,\n    relay_mod,\n    model,\n    zephyr_board,\n    west_cmd,\n    map_inputs,\n    out_shape,\n    result,\n    build_config,\n    use_fvp,\n):\n    \"\"\"Helper function to verify results\"\"\"\n    TOL = 1e-5\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    target = tvm.target.target.micro(model)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(relay_mod, target=target, runtime=runtime)\n\n    with _make_session(temp_dir, zephyr_board, west_cmd, mod, build_config, use_fvp) as session:\n        rt_mod = tvm.micro.create_local_graph_executor(\n            mod.get_graph_json(), session.get_system_lib(), session.device\n        )\n        rt_mod.set_input(**mod.get_params())\n        for name, data in map_inputs.items():\n            rt_mod.set_input(name, data)\n        rt_mod.set_input(**mod.get_params())\n        rt_mod.run()\n\n        out_shapes = out_shape if isinstance(out_shape, list) else [out_shape]\n        results = result if isinstance(result, list) else [result]\n\n        for idx, shape in enumerate(out_shapes):\n            out = tvm.nd.empty(shape, device=session.device)\n            out = rt_mod.get_output(idx, out)\n            tvm.testing.assert_allclose(out.numpy(), results[idx], rtol=TOL, atol=TOL)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_byoc_microtvm(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"This is a simple test case to check BYOC capabilities of microTVM\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    x = relay.var(\"x\", shape=(10, 10))\n    w0 = relay.var(\"w0\", shape=(10, 10))\n    w1 = relay.var(\"w1\", shape=(10, 10))\n    w2 = relay.var(\"w2\", shape=(10, 10))\n    w3 = relay.var(\"w3\", shape=(10, 10))\n    w4 = relay.var(\"w4\", shape=(10, 10))\n    w5 = relay.var(\"w5\", shape=(10, 10))\n    w6 = relay.var(\"w6\", shape=(10, 10))\n    w7 = relay.var(\"w7\", shape=(10, 10))\n\n    # C compiler\n    z0 = relay.add(x, w0)\n    p0 = relay.subtract(z0, w1)\n    q0 = relay.multiply(p0, w2)\n\n    z1 = relay.add(x, w3)\n    p1 = relay.subtract(z1, w4)\n    q1 = relay.multiply(p1, w5)\n\n    # Other parts on TVM\n    z2 = relay.add(x, w6)\n    q2 = relay.subtract(z2, w7)\n\n    r = relay.concatenate((q0, q1, q2), axis=0)\n    f = relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r)\n    mod = tvm.IRModule()\n    ann = byoc.CcompilerAnnotator()\n    mod[\"main\"] = ann.visit(f)\n    mod = tvm.relay.transform.PartitionGraph()(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    w_data = []\n    for _ in range(8):\n        w_data.append(np.random.rand(10, 10).astype(\"float32\"))\n\n    map_inputs = {\"w{}\".format(i): w_data[i] for i in range(8)}\n    map_inputs[\"x\"] = x_data\n    check_result(\n        temp_dir=workspace_dir,\n        relay_mod=mod,\n        map_inputs=map_inputs,\n        out_shape=(30, 10),\n        result=np.concatenate(\n            (\n                ((x_data + w_data[0]) - w_data[1]) * w_data[2],\n                ((x_data + w_data[3]) - w_data[4]) * w_data[5],\n                x_data + w_data[6] - w_data[7],\n            ),\n            axis=0,\n        ),\n        model=model,\n        zephyr_board=board,\n        west_cmd=west_cmd,\n        build_config=build_config,\n        use_fvp=use_fvp,\n    )\n\n\ndef _make_add_sess_with_shape(\n    temp_dir, model, zephyr_board, west_cmd, shape, build_config, use_fvp\n):\n    A = tvm.te.placeholder(shape, dtype=\"int8\")\n    C = tvm.te.compute(A.shape, lambda i: A[i] + A[i], name=\"C\")\n    sched = tvm.te.create_schedule(C.op)\n    return _make_sess_from_op(\n        temp_dir, model, zephyr_board, west_cmd, \"add\", sched, [A, C], build_config, use_fvp\n    )\n\n\n@pytest.mark.parametrize(\n    \"shape,\",\n    [\n        pytest.param((1 * 1024,), id=\"(1*1024)\"),\n        pytest.param((4 * 1024,), id=\"(4*1024)\"),\n        pytest.param((16 * 1024,), id=\"(16*1024)\"),\n    ],\n)\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_rpc_large_array(workspace_dir, board, west_cmd, microtvm_debug, shape, use_fvp):\n    \"\"\"Test large RPC array transfer.\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # NOTE: run test in a nested function so cPython will delete arrays before closing the session.\n    def test_tensors(sess):\n        a_np = np.random.randint(low=-128, high=127, size=shape, dtype=\"int8\")\n\n        A_data = tvm.nd.array(a_np, device=sess.device)\n        assert (A_data.numpy() == a_np).all()\n        C_data = tvm.nd.array(np.zeros(shape, dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.zeros(shape)).all()\n\n    with _make_add_sess_with_shape(\n        workspace_dir, model, board, west_cmd, shape, build_config, use_fvp\n    ) as sess:\n        test_tensors(sess)\n\n\n@pytest.mark.xfail(strict=False, reason=\"See https://github.com/apache/tvm/issues/10297\")\n@tvm.testing.requires_micro\ndef test_autotune_conv2d(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Test AutoTune for microTVM Zephyr\"\"\"\n    if board != \"qemu_x86\":\n        pytest.xfail(f\"Autotune fails on {board}.\")\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n\n    # Create a Relay model\n    data_shape = (1, 3, 16, 16)\n    weight_shape = (8, 3, 5, 5)\n    data = relay.var(\"data\", relay.TensorType(data_shape, \"float32\"))\n    weight = relay.var(\"weight\", relay.TensorType(weight_shape, \"float32\"))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        kernel_layout=\"OIHW\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight], y)\n    mod = tvm.IRModule.from_expr(f)\n    mod = relay.transform.InferType()(mod)\n\n    data_sample = np.random.rand(data_shape[0], data_shape[1], data_shape[2], data_shape[3]).astype(\n        \"float32\"\n    )\n    weight_sample = np.random.rand(\n        weight_shape[0], weight_shape[1], weight_shape[2], weight_shape[3]\n    ).astype(\"float32\")\n    params = {mod[\"main\"].params[1].name_hint: weight_sample}\n\n    target = tvm.target.target.micro(model)\n    pass_context = tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True})\n    with pass_context:\n        tasks = tvm.autotvm.task.extract_from_program(mod[\"main\"], {}, target)\n    assert len(tasks) > 0\n\n    config_main_stack_size = None\n    if test_utils.qemu_boards(board):\n        config_main_stack_size = 1536\n\n    project_options = {\n        \"board\": board,\n        \"west_cmd\": west_cmd,\n        \"verbose\": 1,\n        \"project_type\": \"host_driven\",\n        \"use_fvp\": bool(use_fvp),\n    }\n    if config_main_stack_size is not None:\n        project_options[\"config_main_stack_size\"] = config_main_stack_size\n\n    module_loader = tvm.micro.AutoTvmModuleLoader(\n        template_project_dir=test_utils.TEMPLATE_PROJECT_DIR,\n        project_options=project_options,\n    )\n\n    timeout = 200\n    builder = tvm.autotvm.LocalBuilder(\n        timeout=timeout,\n        n_parallel=1,\n        build_kwargs={\"build_option\": {\"tir.disable_vectorize\": True}},\n        do_fork=True,\n        build_func=tvm.micro.autotvm_build_func,\n        runtime=runtime,\n    )\n    runner = tvm.autotvm.LocalRunner(\n        number=1, repeat=1, timeout=timeout, module_loader=module_loader\n    )\n\n    measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner)\n\n    log_path = pathlib.Path(\"zephyr_autotune.log\")\n    if log_path.exists():\n        log_path.unlink()\n\n    n_trial = 10\n    for task in tasks:\n        tuner = tvm.autotvm.tuner.GATuner(task)\n        tuner.tune(\n            n_trial=n_trial,\n            measure_option=measure_option,\n            callbacks=[\n                tvm.autotvm.callback.log_to_file(str(log_path)),\n                tvm.autotvm.callback.progress_bar(n_trial, si_prefix=\"M\"),\n            ],\n            si_prefix=\"M\",\n        )\n        assert tuner.best_flops > 0\n\n    check_tune_log(log_path)\n\n    # Build without tuning\n    with pass_context:\n        lowered = tvm.relay.build(mod, target=target, runtime=runtime, params=params)\n\n    temp_dir = utils.tempdir()\n    with _make_session(temp_dir, board, west_cmd, lowered, build_config, use_fvp) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            lowered.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**lowered.get_params())\n        graph_mod.run(data=data_sample)\n        expected_output = graph_mod.get_output(0).numpy()\n        del graph_mod\n\n    # Build using autotune logs\n    with tvm.autotvm.apply_history_best(str(log_path)):\n        with pass_context:\n            lowered_tuned = tvm.relay.build(mod, target=target, runtime=runtime, params=params)\n\n    temp_dir = utils.tempdir()\n    with _make_session(temp_dir, board, west_cmd, lowered_tuned, build_config, use_fvp) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            lowered_tuned.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**lowered_tuned.get_params())\n        graph_mod.run(data=data_sample)\n        output = graph_mod.get_output(0).numpy()\n        del graph_mod\n\n    tvm.testing.assert_allclose(output, expected_output, rtol=1e-4, atol=1e-5)\n\n\n@tvm.testing.requires_micro\ndef test_schedule_build_with_cmsis_dependency(\n    workspace_dir, board, west_cmd, microtvm_debug, use_fvp\n):\n    \"\"\"Test Relay schedule with CMSIS dependency. This test shows if microTVM Auto tuning\n    with Zephyr breaks if CMSIS dependency was required for a schedule.\n    \"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    target = tvm.target.target.micro(model, options=[\"-keys=arm_cpu,cpu\"])\n\n    if not target.features.has_dsp:\n        pytest.skip(f\"ISA does not support DSP. target: {target}\")\n\n    # Create a Relay conv2d\n    data_shape = (1, 16, 16, 3)\n    weight_shape = (5, 5, 8, 3)\n    data = relay.var(\"data\", relay.TensorType(data_shape, \"int8\"))\n    weight = relay.var(\"weight\", relay.TensorType(weight_shape, \"int8\"))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    func = relay.Function([data, weight], y)\n    ir_mod = tvm.IRModule.from_expr(func)\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(ir_mod, target=target, runtime=runtime)\n\n    project_options = {\n        \"project_type\": \"host_driven\",\n        \"west_cmd\": west_cmd,\n        \"verbose\": bool(build_config.get(\"debug\")),\n        \"board\": board,\n        \"cmsis_path\": os.getenv(\"CMSIS_PATH\"),\n        \"use_fvp\": bool(use_fvp),\n    }\n\n    project_dir = workspace_dir / \"project\"\n    project = tvm.micro.generate_project(\n        str(test_utils.TEMPLATE_PROJECT_DIR),\n        mod,\n        project_dir,\n        project_options,\n    )\n    project.build()\n\n    with open(project_dir / \"CMakeLists.txt\", \"r\") as cmake_f:\n        cmake_content = cmake_f.read()\n\n    assert \"CMSIS/DSP/Include\" in cmake_content\n    assert \"CMSIS/DSP/Include/dsp\" in cmake_content\n    assert \"CMSIS/DSP/Include\" in cmake_content\n    assert \"CMSIS/NN/Include\" in cmake_content\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/test_zephyr_aot_exec.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport logging\nimport os\nimport pathlib\nimport sys\nimport logging\n\nimport pytest\nimport numpy as np\n\nimport onnx\nfrom PIL import Image\n\nimport tvm\nimport tvm.testing\nimport tvm.relay as relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.relay.testing import byoc\nfrom tvm.contrib import utils\nfrom tvm.micro.testing.utils import check_tune_log\nfrom tvm._ffi import get_global_func, register_func\n\nimport test_utils\n\n\ndef _make_session(workspace_dir, zephyr_board, west_cmd, mod, build_config, use_fvp):\n    config_main_stack_size = None\n    if test_utils.qemu_boards(zephyr_board):\n        # fyi: qemu_riscv64 seems to be the greediest stack user\n        config_main_stack_size = 4096\n    else:\n        # increase stack size for HW platforms\n        config_main_stack_size = 2048\n\n    project_options = {\n        \"project_type\": \"host_driven\",\n        \"west_cmd\": west_cmd,\n        \"verbose\": bool(build_config.get(\"debug\")),\n        \"board\": zephyr_board,\n        \"arm_fvp_path\": \"/opt/arm/FVP_Corstone_SSE-300/models/Linux64_GCC-6.4/FVP_Corstone_SSE-300_Ethos-U55\",\n        \"use_fvp\": bool(use_fvp),\n    }\n    if config_main_stack_size is not None:\n        project_options[\"config_main_stack_size\"] = config_main_stack_size\n\n    project = tvm.micro.generate_project(\n        str(test_utils.TEMPLATE_PROJECT_DIR),\n        mod,\n        workspace_dir / \"project\",\n        project_options,\n    )\n    project.build()\n    project.flash()\n    return tvm.micro.Session(project.transport())\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_relay(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Testing a simple relay graph\"\"\"\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    shape = (10,)\n    dtype = \"int8\"\n\n    # Construct Relay program.\n    x = relay.var(\"x\", relay.TensorType(shape=shape, dtype=dtype))\n    xx = relay.multiply(x, x)\n    z = relay.add(xx, relay.const(np.ones(shape=shape, dtype=dtype)))\n    func = relay.Function([x], z)\n    ir_mod = tvm.IRModule.from_expr(func)\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"aot\")\n    target = tvm.target.target.micro(model)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(ir_mod, target=target, runtime=runtime, executor=executor)\n\n    with _make_session(workspace_dir, board, west_cmd, mod, build_config, use_fvp) as session:\n\n        aot_executor = tvm.runtime.executor.aot_executor.AotModule(session.create_aot_executor())\n\n        x_in = np.random.randint(10, size=shape[0], dtype=dtype)\n        aot_executor.run(x=x_in)\n        result = aot_executor.get_output(0).numpy()\n        tvm.testing.assert_allclose(aot_executor.get_input(0).numpy(), x_in)\n        tvm.testing.assert_allclose(result, x_in * x_in + 1)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail_on_fvp()\ndef test_aot_executor(workspace_dir, board, west_cmd, microtvm_debug, use_fvp):\n    \"\"\"Test use of the AOT executor with microTVM.\"\"\"\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    shape = (10,)\n    dtype = \"int8\"\n\n    print(\"test_relay: construct relay program\\n\")\n\n    # Construct Relay program.\n    relay_mod = tvm.parser.fromtext(\n        \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8]) {\n          %0 = %a + %b;\n          %0\n      }\"\"\"\n    )\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"aot\")\n    target = tvm.target.target.micro(model)\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(relay_mod, target=target, runtime=runtime, executor=executor)\n\n    def do_test():\n\n        aot_executor = tvm.runtime.executor.aot_executor.AotModule(session.create_aot_executor())\n\n        assert aot_executor.get_input_index(\"a\") == 0\n        assert aot_executor.get_input_index(\"b\") == 1\n\n        assert aot_executor.get_num_inputs() == 2\n        assert aot_executor.get_num_outputs() == 1\n\n        A_np = np.array([[2, 3]], dtype=\"uint8\")\n        B_np = np.array([[4, 7]], dtype=\"uint8\")\n\n        A_data = aot_executor.get_input(\"a\").copyfrom(A_np)\n        B_data = aot_executor.get_input(\"b\").copyfrom(B_np)\n\n        aot_executor.run()\n\n        out = aot_executor.get_output(0)\n        assert (out.numpy() == np.array([6, 10])).all()\n\n        B_np_new = np.array([[5, 8]])\n        aot_executor.set_input(\"b\", B_np_new)\n        assert (B_data.numpy() == B_np_new).all()\n\n    with _make_session(workspace_dir, board, west_cmd, mod, build_config, use_fvp) as session:\n        do_test()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/test_zephyr_aot_exec_standalone.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport io\nimport logging\nimport os\nimport sys\nimport logging\nimport pathlib\nimport tarfile\nimport tempfile\n\nimport pytest\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.micro.project_api import server\nimport tvm.relay as relay\nfrom tvm.relay.backend import Executor, Runtime\n\nfrom tvm.contrib.download import download_testdata\n\nimport test_utils\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\", \"mps3_an547\"])\ndef test_tflite(workspace_dir, board, west_cmd, microtvm_debug):\n    \"\"\"Testing a TFLite model.\"\"\"\n    model = test_utils.ZEPHYR_BOARDS[board]\n    input_shape = (1, 49, 10, 1)\n    output_shape = (1, 12)\n    build_config = {\"debug\": microtvm_debug}\n\n    model_url = \"https://github.com/tlc-pack/web-data/raw/25fe99fb00329a26bd37d3dca723da94316fd34c/testdata/microTVM/model/keyword_spotting_quant.tflite\"\n    model_path = download_testdata(model_url, \"keyword_spotting_quant.tflite\", module=\"model\")\n\n    # Import TFLite model\n    tflite_model_buf = open(model_path, \"rb\").read()\n    try:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n    # Load TFLite model and convert to Relay\n    relay_mod, params = relay.frontend.from_tflite(\n        tflite_model, shape_dict={\"input_1\": input_shape}, dtype_dict={\"input_1 \": \"int8\"}\n    )\n\n    target = tvm.target.target.micro(model)\n    executor = Executor(\n        \"aot\", {\"unpacked-api\": True, \"interface-api\": \"c\", \"workspace-byte-alignment\": 4}\n    )\n    runtime = Runtime(\"crt\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lowered = relay.build(relay_mod, target, params=params, runtime=runtime, executor=executor)\n\n    sample_url = \"https://github.com/tlc-pack/web-data/raw/967fc387dadb272c5a7f8c3461d34c060100dbf1/testdata/microTVM/data/keyword_spotting_int8_6.pyc.npy\"\n    sample_path = download_testdata(sample_url, \"keyword_spotting_int8_6.pyc.npy\", module=\"data\")\n    sample = np.load(sample_path)\n\n    project, _ = test_utils.generate_project(\n        workspace_dir,\n        board,\n        west_cmd,\n        lowered,\n        build_config,\n        sample,\n        output_shape,\n        \"int8\",\n        load_cmsis=False,\n    )\n\n    result, time = test_utils.run_model(project)\n    assert result == 6\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\", \"mps3_an547\"])\ndef test_qemu_make_fail(workspace_dir, board, west_cmd, microtvm_debug):\n    \"\"\"Testing QEMU make fail.\"\"\"\n    if board not in [\"qemu_x86\", \"mps2_an521\", \"mps3_an547\"]:\n        pytest.skip(msg=\"Only for QEMU targets.\")\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n    build_config = {\"debug\": microtvm_debug}\n    shape = (10,)\n    dtype = \"float32\"\n\n    # Construct Relay program.\n    x = relay.var(\"x\", relay.TensorType(shape=shape, dtype=dtype))\n    xx = relay.multiply(x, x)\n    z = relay.add(xx, relay.const(np.ones(shape=shape, dtype=dtype)))\n    func = relay.Function([x], z)\n    ir_mod = tvm.IRModule.from_expr(func)\n\n    target = tvm.target.target.micro(model)\n    executor = Executor(\"aot\")\n    runtime = Runtime(\"crt\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lowered = relay.build(ir_mod, target, executor=executor, runtime=runtime)\n\n    sample = np.zeros(shape=shape, dtype=dtype)\n    project, project_dir = test_utils.generate_project(\n        workspace_dir,\n        board,\n        west_cmd,\n        lowered,\n        build_config,\n        sample,\n        shape,\n        dtype,\n        load_cmsis=False,\n    )\n\n    file_path = pathlib.Path(project_dir) / \"build\" / \"build.ninja\"\n    assert file_path.is_file(), f\"[{file_path}] does not exist.\"\n\n    # Remove a file to create make failure.\n    os.remove(file_path)\n    project.flash()\n    with pytest.raises(server.JSONRPCError) as excinfo:\n        project.transport().open()\n    assert \"QEMU setup failed\" in str(excinfo.value)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/micro/zephyr/test_zephyr_armv7m.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom json import load\nimport logging\nimport os\nimport pathlib\nimport sys\nimport tarfile\nimport tempfile\n\nimport pytest\nimport numpy as np\n\nimport tvm\nimport tvm.rpc\nimport tvm.micro\nimport tvm.testing\nfrom tvm import relay\n\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.backend import Executor, Runtime\n\nimport test_utils\n\n_LOG = logging.getLogger(__name__)\n\n\ndef _open_tflite_model():\n    # Import TFLite model\n\n    model_url = \"https://github.com/tlc-pack/web-data/raw/b2f3c02427b67267a00fd968ba1fce28fc833028/testdata/microTVM/model/mnist_model_quant.tflite\"\n    model_path = download_testdata(model_url, \"mnist_model_quant.tflite\", module=\"model\")\n\n    tflite_model_buf = open(model_path, \"rb\").read()\n\n    try:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n    relay_mod, params = relay.frontend.from_tflite(tflite_model)\n\n    return relay_mod, params\n\n\ndef _get_test_data(testdata_dir):\n\n    from PIL import Image\n\n    image_files = [\"digit-2.jpg\"]\n\n    for file in image_files:\n        img = Image.open(testdata_dir / file).resize((28, 28))\n        img = np.asarray(img).astype(\"uint8\")\n        sample = np.reshape(img, -1)\n\n    output_shape = (1, 10)\n\n    return sample, output_shape\n\n\ndef _apply_desired_layout_simd(relay_mod):\n\n    desired_layouts = {\"qnn.conv2d\": [\"NHWC\", \"HWOI\"], \"nn.conv2d\": [\"NHWC\", \"HWOI\"]}\n\n    seq = tvm.transform.Sequential(\n        [relay.transform.RemoveUnusedFunctions(), relay.transform.ConvertLayout(desired_layouts)]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        return seq(relay_mod)\n\n\ndef _apply_desired_layout_no_simd(relay_mod):\n\n    desired_layouts = {\"qnn.conv2d\": [\"NHWC\", \"HWIO\"], \"nn.conv2d\": [\"NHWC\", \"HWIO\"]}\n\n    seq = tvm.transform.Sequential(\n        [relay.transform.RemoveUnusedFunctions(), relay.transform.ConvertLayout(desired_layouts)]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        return seq(relay_mod)\n\n\n@tvm.testing.requires_micro\n@pytest.mark.skip_boards([\"mps2_an521\"])\n@pytest.mark.xfail(reason=\"due https://github.com/apache/tvm/issues/12619\")\ndef test_armv7m_intrinsic(workspace_dir, board, west_cmd, microtvm_debug):\n    \"\"\"Testing a ARM v7m SIMD extension.\"\"\"\n    if board not in [\n        \"mps2_an521\",\n        \"stm32f746g_disco\",\n        \"nucleo_f746zg\",\n        \"nucleo_l4r5zi\",\n        \"nrf5340dk_nrf5340_cpuapp\",\n    ]:\n        pytest.skip(msg=\"Platform does not support ARM v7m SIMD extension.\")\n\n    model = test_utils.ZEPHYR_BOARDS[board]\n\n    build_config = {\"debug\": microtvm_debug}\n\n    this_dir = pathlib.Path(os.path.dirname(__file__))\n    testdata_dir = this_dir.parent / \"testdata\" / \"mnist\"\n\n    relay_mod, params = _open_tflite_model()\n\n    sample, output_shape = _get_test_data(testdata_dir)\n\n    relay_mod_simd = _apply_desired_layout_simd(relay_mod)\n    # kernel layout \"HWIO\" is not supported by arm_cpu SIMD extension (see tvm\\python\\relay\\op\\strategy\\arm_cpu.py)\n    relay_mod_no_simd = _apply_desired_layout_no_simd(relay_mod)\n\n    target = tvm.target.target.micro(model, options=[\"-keys=cpu\"])\n    target_simd = tvm.target.target.micro(model, options=[\"-keys=arm_cpu,cpu\"])\n\n    executor = Executor(\"aot\", {\"unpacked-api\": True, \"interface-api\": \"c\"})\n    runtime = Runtime(\"crt\")\n\n    workspace_dir_simd = workspace_dir / \"simd\"\n    workspace_dir_no_simd = workspace_dir / \"nosimd\"\n\n    os.makedirs(workspace_dir_simd, exist_ok=True)\n    os.makedirs(workspace_dir_no_simd, exist_ok=True)\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lowered_simd = relay.build(\n            relay_mod_simd, target_simd, params=params, runtime=runtime, executor=executor\n        )\n        lowered_no_simd = relay.build(\n            relay_mod_no_simd, target, params=params, runtime=runtime, executor=executor\n        )\n\n        simd_project, _ = test_utils.generate_project(\n            workspace_dir_simd,\n            board,\n            west_cmd,\n            lowered_simd,\n            build_config,\n            sample,\n            output_shape,\n            \"float32\",\n            load_cmsis=True,\n        )\n        result_simd, time_simd = test_utils.run_model(simd_project)\n\n        no_simd_project, _ = test_utils.generate_project(\n            workspace_dir_no_simd,\n            board,\n            west_cmd,\n            lowered_no_simd,\n            build_config,\n            sample,\n            output_shape,\n            \"float32\",\n            load_cmsis=False,\n        )\n        result_no_simd, time_no_simd = test_utils.run_model(no_simd_project)\n\n    assert result_no_simd == result_simd == 2\n\n    # Time performance measurements on QEMU emulator are always equal to zero.\n    if board not in [\n        \"mps2_an521\",\n        \"mps3_an547\",\n    ]:\n        assert time_no_simd > time_simd\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/all-platform-minimal-test/test_minimal_target_codegen_llvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"LLVM enablement tests.\"\"\"\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.contrib import utils\nimport numpy as np\nimport ctypes\nimport math\nimport re\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_add_pipeline():\n    \"\"\"all-platform-minimal-test: Check LLVM enablement.\"\"\"\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    AA = te.compute((n,), lambda *i: A(*i), name=\"A\")\n    BB = te.compute((n,), lambda *i: B(*i), name=\"B\")\n    T = te.compute(A.shape, lambda *i: AA(*i) + BB(*i), name=\"T\")\n    C = te.compute(A.shape, lambda *i: T(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    xo1, xo2 = s[C].split(xo, factor=13)\n    s[C].parallel(xo2)\n    s[C].pragma(xo1, \"parallel_launch_point\")\n    s[C].pragma(xo2, \"parallel_stride_pattern\")\n    s[C].pragma(xo2, \"parallel_barrier_when_finish\")\n    s[C].vectorize(xi)\n\n    def check_llvm():\n        # Specifically allow offset to test codepath when offset is available\n        Ab = tvm.tir.decl_buffer(\n            A.shape, A.dtype, elem_offset=te.size_var(\"Aoffset\"), offset_factor=8, name=\"A\"\n        )\n        binds = {A: Ab}\n        # BUILD and invoke the kernel.\n        f = tvm.build(s, [A, B, C], \"llvm\", binds=binds)\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_llvm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/all-platform-minimal-test/test_runtime_ndarray.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Basic runtime enablement test.\"\"\"\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nimport tvm.testing\n\n\n@tvm.testing.uses_gpu\ndef test_nd_create():\n    for target, dev in tvm.testing.enabled_targets():\n        for dtype in [\"uint8\", \"int8\", \"uint16\", \"int16\", \"uint32\", \"int32\", \"float32\"]:\n            x = np.random.randint(0, 10, size=(3, 4))\n            x = np.array(x, dtype=dtype)\n            y = tvm.nd.array(x, device=dev)\n            z = y.copyto(dev)\n            assert y.dtype == x.dtype\n            assert y.shape == x.shape\n            assert isinstance(y, tvm.nd.NDArray)\n            np.testing.assert_equal(x, y.numpy())\n            np.testing.assert_equal(x, z.numpy())\n        # no need here, just to test usablity\n        dev.sync()\n\n\ndef test_fp16_conversion():\n    n = 100\n\n    for (src, dst) in [(\"float32\", \"float16\"), (\"float16\", \"float32\")]:\n        A = te.placeholder((n,), dtype=src)\n        B = te.compute((n,), lambda i: A[i].astype(dst))\n\n        s = te.create_schedule([B.op])\n        func = tvm.build(s, [A, B], \"llvm\")\n\n        x_tvm = tvm.nd.array(100 * np.random.randn(n).astype(src) - 50)\n        y_tvm = tvm.nd.array(100 * np.random.randn(n).astype(dst) - 50)\n\n        func(x_tvm, y_tvm)\n\n        expected = x_tvm.numpy().astype(dst)\n        real = y_tvm.numpy()\n\n        tvm.testing.assert_allclose(expected, real)\n\n\ndef test_dtype():\n    dtype = tvm.DataType(\"handle\")\n    assert dtype.type_code == tvm.DataTypeCode.HANDLE\n\n\nif __name__ == \"__main__\":\n    test_nd_create()\n    test_fp16_conversion()\n    test_dtype()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/all-platform-minimal-test/test_runtime_packed_func.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test packed function FFI.\"\"\"\nimport tvm\nfrom tvm import te\nimport tvm.testing\nimport numpy as np\n\n\ndef test_get_global():\n    targs = (10, 10.0, \"hello\")\n    # register into global function table\n    @tvm.register_func\n    def my_packed_func(*args):\n        assert tuple(args) == targs\n        return 10\n\n    # get it out from global function table\n    f = tvm.get_global_func(\"my_packed_func\")\n    assert isinstance(f, tvm.runtime.PackedFunc)\n    y = f(*targs)\n    assert y == 10\n\n\ndef test_get_callback_with_node():\n    x = tvm.runtime.convert(10)\n\n    def test(y):\n        assert y.handle != x.handle\n        return y\n\n    f2 = tvm.runtime.convert(test)\n    # register into global function table\n    @tvm.register_func\n    def my_callback_with_node(y, f):\n        assert y == x\n        return f(y)\n\n    # get it out from global function table\n    f = tvm.get_global_func(\"my_callback_with_node\")\n    assert isinstance(f, tvm.runtime.PackedFunc)\n    y = f(x, f2)\n    assert y.value == 10\n\n\ndef test_return_func():\n    def addy(y):\n        def add(x):\n            return tvm.runtime.convert(x + y)\n\n        return add\n\n    myf = tvm.runtime.convert(addy)\n    f = myf(10)\n    assert f(11).value == 21\n\n\ndef test_convert():\n    # convert a function to tvm function\n    targs = (10, 10.0, \"hello\", 10)\n\n    def myfunc(*args):\n        assert tuple(args) == targs\n\n    f = tvm.runtime.convert(myfunc)\n    assert isinstance(f, tvm.runtime.PackedFunc)\n\n\ndef test_byte_array():\n    s = \"hello\"\n    a = bytearray(s, encoding=\"ascii\")\n\n    def myfunc(ss):\n        assert ss == a\n\n    f = tvm.runtime.convert(myfunc)\n    f(a)\n\n\ndef test_empty_array():\n    def myfunc(ss):\n        assert tuple(ss) == ()\n\n    x = tvm.runtime.convert(())\n    tvm.runtime.convert(myfunc)(x)\n\n\ndef test_device():\n    def test_device_func(dev):\n        assert tvm.cuda(7) == dev\n        return tvm.cpu(0)\n\n    x = test_device_func(tvm.cuda(7))\n    assert x == tvm.cpu(0)\n    x = tvm.opencl(10)\n    x = tvm.testing.device_test(x, x.device_type, x.device_id)\n    assert x == tvm.opencl(10)\n\n\ndef test_rvalue_ref():\n    def callback(x, expected_count):\n        assert expected_count == tvm.testing.object_use_count(x)\n        return x\n\n    f = tvm.runtime.convert(callback)\n\n    def check0():\n        x = tvm.tir.Var(\"x\", \"int32\")\n        assert tvm.testing.object_use_count(x) == 1\n        f(x, 2)\n        y = f(x._move(), 1)\n        assert x.handle.value == None\n\n    def check1():\n        x = tvm.tir.Var(\"x\", \"int32\")\n        assert tvm.testing.object_use_count(x) == 1\n        y = f(x, 2)\n        z = f(x._move(), 2)\n        assert x.handle.value == None\n        assert y.handle.value is not None\n\n    check0()\n    check1()\n\n\ndef test_numpy_scalar():\n    maxint = (1 << 63) - 1\n    assert tvm.testing.echo(np.int64(maxint)) == maxint\n\n\ndef test_ndarray_args():\n    def check(arr):\n        assert not arr.is_view\n        assert tvm.testing.object_use_count(arr) == 2\n\n    fcheck = tvm.runtime.convert(check)\n    x = tvm.nd.array([1, 2, 3])\n    fcheck(x)\n    assert tvm.testing.object_use_count(x) == 1\n\n\nif __name__ == \"__main__\":\n    test_ndarray_args()\n    test_numpy_scalar()\n    test_rvalue_ref()\n    test_empty_array()\n    test_get_global()\n    test_get_callback_with_node()\n    test_convert()\n    test_return_func()\n    test_byte_array()\n    test_device()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/ci/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for CI scripts\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/ci/test_ci.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test various CI scripts and GitHub Actions workflows\"\"\"\nimport shutil\nimport subprocess\nimport json\nimport textwrap\nimport sys\nimport logging\nfrom pathlib import Path\n\nimport pytest\nimport tvm.testing\n\nfrom .test_utils import REPO_ROOT, TempGit, run_script\n\n# pylint: disable=wrong-import-position,wrong-import-order\nsys.path.insert(0, str(REPO_ROOT / \"ci\"))\nsys.path.insert(0, str(REPO_ROOT / \"ci\" / \"scripts\"))\n\nimport scripts\n\n# pylint: enable=wrong-import-position,wrong-import-order\n\n\ndef parameterize_named(**kwargs):\n    keys = next(iter(kwargs.values())).keys()\n    return pytest.mark.parametrize(\n        \",\".join(keys), [tuple(d.values()) for d in kwargs.values()], ids=kwargs.keys()\n    )\n\n\n# pylint: disable=line-too-long\nTEST_DATA_SKIPPED_BOT = {\n    \"found-diff-no-additional\": {\n        \"main_xml_file\": \"unittest/file1.xml\",\n        \"main_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"pr_xml_file\": \"unittest/file2.xml\",\n        \"pr_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                        <testcase classname=\"ctypes.tests.python.unittest.test_roofline\"\n                                  name=\"test_estimate_peak_bandwidth[cuda]\" time=\"4.679\">\n                            <skipped message=\"This is another skippe test\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"additional_tests_to_check\": \"\"\"{\n                    \"unittest\": [\"dummy_class#dummy_test\"],\n                    \"unittest_GPU\": [\"another_dummy_class#another_dummy_test\"]\n                }\n                \"\"\",\n        \"target_url\": \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        \"s3_prefix\": \"tvm-jenkins-artifacts-prod\",\n        \"jenkins_prefix\": \"ci.tlcpack.ai\",\n        \"common_main_build\": \"\"\"{\"build_number\": \"4115\", \"state\": \"success\"}\"\"\",\n        \"commit_sha\": \"sha1234\",\n        \"expected_body\": \"The list below shows tests that ran in main sha1234 but were skipped in the CI build of sha1234:\\n```\\nunittest -> ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\\nunittest -> ctypes.tests.python.unittest.test_roofline#test_estimate_peak_bandwidth[cuda]\\n```\\nA detailed report of ran tests is [here](https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/testReport/).\",\n    },\n    \"found-diff-skipped-additional\": {\n        \"main_xml_file\": \"unittest/file1.xml\",\n        \"main_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"pr_xml_file\": \"unittest/file2.xml\",\n        \"pr_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                        <testcase classname=\"ctypes.tests.python.unittest.test_roofline\"\n                                  name=\"test_estimate_peak_bandwidth[cuda]\" time=\"4.679\">\n                            <skipped message=\"This is another skippe test\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"additional_tests_to_check\": \"\"\"{\n                    \"unittest\": [\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\", \"dummy_class#dummy_test\"],\n                    \"unittest_GPU\": [\"another_dummy_class#another_dummy_test\"]\n                }\n                \"\"\",\n        \"target_url\": \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        \"s3_prefix\": \"tvm-jenkins-artifacts-prod\",\n        \"jenkins_prefix\": \"ci.tlcpack.ai\",\n        \"common_main_build\": \"\"\"{\"build_number\": \"4115\", \"state\": \"success\"}\"\"\",\n        \"commit_sha\": \"sha1234\",\n        \"expected_body\": \"The list below shows tests that ran in main sha1234 but were skipped in the CI build of sha1234:\\n```\\nunittest -> ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\\nunittest -> ctypes.tests.python.unittest.test_roofline#test_estimate_peak_bandwidth[cuda]\\n```\\n\\nAdditional tests that were skipped in the CI build and present in the [`required_tests_to_run`](https://github.com/apache/tvm/blob/main/ci/scripts/required_tests_to_run.json) file:\\n```\\nunittest -> ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\\n```\\nA detailed report of ran tests is [here](https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/testReport/).\",\n    },\n    \"no-diff\": {\n        \"main_xml_file\": \"unittest/file1.xml\",\n        \"main_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"pr_xml_file\": \"unittest/file2.xml\",\n        \"pr_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"additional_tests_to_check\": \"\"\"{\n                }\n                \"\"\",\n        \"target_url\": \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        \"s3_prefix\": \"tvm-jenkins-artifacts-prod\",\n        \"jenkins_prefix\": \"ci.tlcpack.ai\",\n        \"common_main_build\": \"\"\"{\"build_number\": \"4115\", \"state\": \"success\"}\"\"\",\n        \"commit_sha\": \"sha1234\",\n        \"expected_body\": \"No diff in skipped tests with main found in this branch for commit sha1234.\\nA detailed report of ran tests is [here](https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/testReport/).\",\n    },\n    \"no-diff-skipped-additional\": {\n        \"main_xml_file\": \"unittest/file1.xml\",\n        \"main_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"pr_xml_file\": \"unittest/file2.xml\",\n        \"pr_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                <testsuites>\n                    <testsuite errors=\"0\" failures=\"0\" hostname=\"13e7c5f749d8\" name=\"python-unittest-gpu-0-shard-1-ctypes\" skipped=\"102\"\n                               tests=\"165\" time=\"79.312\" timestamp=\"2022-08-10T22:39:36.673781\">\n                        <testcase classname=\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy\"\n                                  name=\"test_sketch_search_policy_cuda_rpc_runner\" time=\"9.679\">\n                            <skipped message=\"This test is skipped\" type=\"pytest.skip\">\n                                Skipped\n                            </skipped>\n                        </testcase>\n                    </testsuite>\n                </testsuites>\n                \"\"\",\n        \"additional_tests_to_check\": \"\"\"{\n                    \"unittest\": [\"dummy_class#dummy_test\", \"ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\"],\n                    \"unittest_GPU\": [\"another_dummy_class#another_dummy_test\"]\n                }\n                \"\"\",\n        \"target_url\": \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        \"s3_prefix\": \"tvm-jenkins-artifacts-prod\",\n        \"jenkins_prefix\": \"ci.tlcpack.ai\",\n        \"common_main_build\": \"\"\"{\"build_number\": \"4115\", \"state\": \"success\"}\"\"\",\n        \"commit_sha\": \"sha1234\",\n        \"expected_body\": \"No diff in skipped tests with main found in this branch for commit sha1234.\\n\\nAdditional tests that were skipped in the CI build and present in the [`required_tests_to_run`](https://github.com/apache/tvm/blob/main/ci/scripts/required_tests_to_run.json) file:\\n```\\nunittest -> ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\\n```\\nA detailed report of ran tests is [here](https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/testReport/).\",\n    },\n    \"unable-to-run\": {\n        \"main_xml_file\": \"unittest/file1.xml\",\n        \"main_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                    <testsuites>\n                    </testsuites>\n                    \"\"\",\n        \"pr_xml_file\": \"unittest/file2.xml\",\n        \"pr_xml_content\": \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n                    <testsuites>\n                    </testsuites>\n                    \"\"\",\n        \"additional_tests_to_check\": \"\"\"{\n                    \"unittest\": [\"ctypes.tests.python.unittest.test_auto_scheduler_search_policy#test_sketch_search_policy_cuda_rpc_runner\", \"dummy_class#dummy_test\"],\n                    \"unittest_GPU\": [\"another_dummy_class#another_dummy_test\"]\n                }\n                \"\"\",\n        \"target_url\": \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        \"s3_prefix\": \"tvm-jenkins-artifacts-prod\",\n        \"jenkins_prefix\": \"ci.tlcpack.ai\",\n        \"common_main_build\": \"\"\"{\"build_number\": \"4115\", \"state\": \"failed\"}\"\"\",\n        \"commit_sha\": \"sha1234\",\n        \"expected_body\": \"Unable to run tests bot because main failed to pass CI at sha1234.\",\n    },\n}\n# pylint: enable=line-too-long\n\n\n@tvm.testing.skip_if_wheel_test\n@parameterize_named(**TEST_DATA_SKIPPED_BOT)\n# pylint: enable=line-too-long\ndef test_skipped_tests_comment(\n    caplog,\n    tmpdir_factory,\n    main_xml_file,\n    main_xml_content,\n    pr_xml_file,\n    pr_xml_content,\n    additional_tests_to_check,\n    target_url,\n    s3_prefix,\n    jenkins_prefix,\n    common_main_build,\n    commit_sha,\n    expected_body,\n):\n    \"\"\"\n    Test that a comment with a link to the docs is successfully left on PRs\n    \"\"\"\n\n    def write_xml_file(root_dir, xml_file, xml_content):\n        shutil.rmtree(root_dir, ignore_errors=True)\n        file = root_dir / xml_file\n        file.parent.mkdir(parents=True)\n        with open(file, \"w\") as f:\n            f.write(textwrap.dedent(xml_content))\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    pr_test_report_dir = Path(git.cwd) / \"pr-reports\"\n    write_xml_file(pr_test_report_dir, pr_xml_file, pr_xml_content)\n    main_test_report_dir = Path(git.cwd) / \"main-reports\"\n    write_xml_file(main_test_report_dir, main_xml_file, main_xml_content)\n    with open(Path(git.cwd) / \"required_tests_to_run.json\", \"w\") as f:\n        f.write(additional_tests_to_check)\n\n    pr_data = {\n        \"commits\": {\n            \"nodes\": [\n                {\n                    \"commit\": {\n                        \"oid\": commit_sha,\n                        \"statusCheckRollup\": {\n                            \"contexts\": {\n                                \"nodes\": [\n                                    {\n                                        \"context\": \"tvm-ci/pr-head\",\n                                        \"targetUrl\": target_url,\n                                    }\n                                ]\n                            }\n                        },\n                    }\n                }\n            ]\n        }\n    }\n    with caplog.at_level(logging.INFO):\n        comment = scripts.github_skipped_tests_comment.get_skipped_tests_comment(\n            pr=pr_data,\n            github=None,\n            s3_prefix=s3_prefix,\n            jenkins_prefix=jenkins_prefix,\n            common_commit_sha=commit_sha,\n            pr_test_report_dir=pr_test_report_dir,\n            main_test_report_dir=main_test_report_dir,\n            common_main_build=json.loads(common_main_build),\n            additional_tests_to_check_file=Path(git.cwd) / \"required_tests_to_run.json\",\n        )\n    assert_in(expected_body, comment)\n    assert_in(f\"with target {target_url}\", caplog.text)\n\n\n@tvm.testing.skip_if_wheel_test\n@parameterize_named(\n    doc_link=dict(\n        target_url=\"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\",\n        base_url=\"https://pr-docs.tlcpack.ai\",\n        commit_sha=\"SHA\",\n        expected_body=\"Built docs for commit SHA can be found \"\n        \"[here](https://pr-docs.tlcpack.ai/PR-11594/3/docs/index.html).\",\n    )\n)\ndef test_docs_comment(target_url, base_url, commit_sha, expected_body):\n    \"\"\"\n    Test that a comment with a link to the docs is successfully left on PRs\n    \"\"\"\n    pr_data = {\n        \"commits\": {\n            \"nodes\": [\n                {\n                    \"commit\": {\n                        \"oid\": commit_sha,\n                        \"statusCheckRollup\": {\n                            \"contexts\": {\n                                \"nodes\": [\n                                    {\n                                        \"context\": \"tvm-ci/pr-head\",\n                                        \"targetUrl\": target_url,\n                                    }\n                                ]\n                            }\n                        },\n                    }\n                }\n            ]\n        }\n    }\n    comment = scripts.github_docs_comment.get_doc_url(\n        pr=pr_data,\n        base_docs_url=base_url,\n    )\n    assert_in(expected_body, comment)\n\n\n@tvm.testing.skip_if_wheel_test\n@parameterize_named(\n    cc_no_one=dict(\n        pr_body=\"abc\", requested_reviewers=[], existing_review_users=[], expected_reviewers=[]\n    ),\n    cc_abc=dict(\n        pr_body=\"cc @abc\",\n        requested_reviewers=[],\n        existing_review_users=[],\n        expected_reviewers=[\"abc\"],\n    ),\n    bad_cc_line=dict(\n        pr_body=\"cc @\", requested_reviewers=[], existing_review_users=[], expected_reviewers=[]\n    ),\n    cc_multiple=dict(\n        pr_body=\"cc @abc @def\",\n        requested_reviewers=[],\n        existing_review_users=[],\n        expected_reviewers=[\"abc\", \"def\"],\n    ),\n    with_existing=dict(\n        pr_body=\"some text cc @abc @def something else\",\n        requested_reviewers=[],\n        existing_review_users=[],\n        expected_reviewers=[\"abc\", \"def\"],\n    ),\n    with_existing_split=dict(\n        pr_body=\"some text cc @abc @def something else\\n\\n another cc @zzz z\",\n        requested_reviewers=[],\n        existing_review_users=[],\n        expected_reviewers=[\"abc\", \"def\", \"zzz\"],\n    ),\n    with_existing_request=dict(\n        pr_body=\"some text cc @abc @def something else\\n\\n another cc @zzz z\",\n        requested_reviewers=[\"abc\"],\n        existing_review_users=[],\n        expected_reviewers=[\"def\", \"zzz\"],\n    ),\n    with_existing_reviewers=dict(\n        pr_body=\"some text cc @abc @def something else\\n\\n another cc @zzz z\",\n        requested_reviewers=[\"abc\"],\n        existing_review_users=[\"abc\"],\n        expected_reviewers=[\"def\", \"zzz\"],\n    ),\n    with_no_reviewers=dict(\n        pr_body=\"some text cc @abc @def something else\\n\\n another cc @zzz z\",\n        requested_reviewers=[],\n        existing_review_users=[\"abc\"],\n        expected_reviewers=[\"def\", \"zzz\"],\n    ),\n)\ndef test_cc_reviewers(\n    tmpdir_factory, pr_body, requested_reviewers, existing_review_users, expected_reviewers\n):\n    \"\"\"\n    Test that reviewers are added from 'cc @someone' messages in PRs\n    \"\"\"\n    reviewers_script = REPO_ROOT / \"ci\" / \"scripts\" / \"github_cc_reviewers.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    reviews = [{\"user\": {\"login\": r}} for r in existing_review_users]\n    requested_reviewers = [{\"login\": r} for r in requested_reviewers]\n    proc = run_script(\n        [reviewers_script, \"--dry-run\", \"--testing-reviews-json\", json.dumps(reviews)],\n        env={\n            \"PR\": json.dumps(\n                {\"number\": 1, \"body\": pr_body, \"requested_reviewers\": requested_reviewers}\n            )\n        },\n        cwd=git.cwd,\n    )\n\n    assert f\"After filtering existing reviewers, adding: {expected_reviewers}\" in proc.stdout\n\n\n@parameterize_named(\n    # Missing expected tvm-ci/branch test\n    missing_tvm_ci_branch=dict(\n        statuses=[\n            {\n                \"context\": \"test\",\n                \"state\": \"SUCCESS\",\n            }\n        ],\n        expected_rc=1,\n        expected_output=\"No good commits found in the last 1 commits\",\n    ),\n    # Only has the right passing test\n    has_expected_test=dict(\n        statuses=[\n            {\n                \"context\": \"tvm-ci/branch\",\n                \"state\": \"SUCCESS\",\n            }\n        ],\n        expected_rc=0,\n        expected_output=\"Found last good commit: 123: hello\",\n    ),\n    # Check with many statuses\n    many_statuses=dict(\n        statuses=[\n            {\n                \"context\": \"tvm-ci/branch\",\n                \"state\": \"SUCCESS\",\n            },\n            {\n                \"context\": \"tvm-ci/branch2\",\n                \"state\": \"SUCCESS\",\n            },\n            {\n                \"context\": \"tvm-ci/branch3\",\n                \"state\": \"FAILED\",\n            },\n        ],\n        expected_rc=1,\n        expected_output=\"No good commits found in the last 1 commits\",\n    ),\n    many_success_statuses=dict(\n        statuses=[\n            {\n                \"context\": \"tvm-ci/branch\",\n                \"state\": \"SUCCESS\",\n            },\n            {\n                \"context\": \"tvm-ci/branch2\",\n                \"state\": \"SUCCESS\",\n            },\n            {\n                \"context\": \"tvm-ci/branch3\",\n                \"state\": \"SUCCESS\",\n            },\n        ],\n        expected_rc=0,\n        expected_output=\"Found last good commit: 123: hello\",\n    ),\n)\ndef test_update_branch(tmpdir_factory, statuses, expected_rc, expected_output):\n    \"\"\"\n    Test that the last-successful branch script updates successfully\n    \"\"\"\n    update_script = REPO_ROOT / \"ci\" / \"scripts\" / \"update_branch.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    commit = {\n        \"statusCheckRollup\": {\"contexts\": {\"nodes\": statuses}},\n        \"oid\": \"123\",\n        \"messageHeadline\": \"hello\",\n    }\n    data = {\n        \"data\": {\n            \"repository\": {\n                \"defaultBranchRef\": {\"target\": {\"history\": {\"edges\": [], \"nodes\": [commit]}}}\n            }\n        }\n    }\n    proc = run_script(\n        [update_script, \"--dry-run\", \"--testonly-json\", json.dumps(data)],\n        cwd=git.cwd,\n        check=False,\n    )\n\n    if proc.returncode != expected_rc:\n        raise RuntimeError(f\"Wrong return code:\\nstdout:\\n{proc.stdout}\\n\\nstderr:\\n{proc.stderr}\")\n\n    if expected_output not in proc.stdout:\n        raise RuntimeError(\n            f\"Missing {expected_output}:\\nstdout:\\n{proc.stdout}\\n\\nstderr:\\n{proc.stderr}\"\n        )\n\n\n# pylint: disable=line-too-long\n@parameterize_named(\n    author_gate=dict(\n        pr_author=\"abc\",\n        comments=[],\n        expected=\"Skipping comment for author abc\",\n    ),\n    new_comment=dict(\n        pr_author=\"driazati\",\n        comments=[],\n        expected=\"No existing comment found\",\n    ),\n    update_comment=dict(\n        pr_author=\"driazati\",\n        comments=[\n            {\n                \"author\": {\"login\": \"github-actions\"},\n                \"databaseId\": \"comment456\",\n                \"body\": \"<!---bot-comment--> abc\",\n            }\n        ],\n        expected=\"PATCH to https://api.github.com/repos/apache/tvm/issues/comments/comment456\",\n    ),\n    new_body=dict(\n        pr_author=\"driazati\",\n        comments=[],\n        expected=\"Commenting \"\n        + textwrap.dedent(\n            \"\"\"\n        <!---bot-comment-->\n\n        Thanks for contributing to TVM! Please refer to the contributing guidelines https://tvm.apache.org/docs/contribute/ for useful information and tips. Please request code reviews from [Reviewers](https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers) by @-ing them in a comment.\n\n        <!--bot-comment-ccs-start-->\n         * the cc<!--bot-comment-ccs-end--><!--bot-comment-skipped-tests-start-->\n         * the skipped tests<!--bot-comment-skipped-tests-end--><!--bot-comment-docs-start-->\n         * the docs<!--bot-comment-docs-end-->\n        \"\"\"\n        ).strip(),\n    ),\n    update_body=dict(\n        pr_author=\"driazati\",\n        comments=[\n            {\n                \"author\": {\"login\": \"github-actions\"},\n                \"databaseId\": \"comment456\",\n                \"body\": textwrap.dedent(\n                    \"\"\"\n        <!---bot-comment-->\n\n        Thanks for contributing to TVM! Please refer to the contributing guidelines https://tvm.apache.org/docs/contribute/ for useful information and tips. Please request code reviews from [Reviewers](https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers) by @-ing them in a comment.\n\n        <!--bot-comment-ccs-start-->\n         * the cc<!--bot-comment-ccs-end--><!--bot-comment-something-tests-start-->\n         * something else<!--bot-comment-something-tests-end--><!--bot-comment-docs-start-->\n         * the docs<!--bot-comment-docs-end-->\n        \"\"\"\n                ).strip(),\n            }\n        ],\n        expected=\"Commenting \"\n        + textwrap.dedent(\n            \"\"\"\n        <!---bot-comment-->\n\n        Thanks for contributing to TVM! Please refer to the contributing guidelines https://tvm.apache.org/docs/contribute/ for useful information and tips. Please request code reviews from [Reviewers](https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers) by @-ing them in a comment.\n\n        <!--bot-comment-ccs-start-->\n         * the cc<!--bot-comment-ccs-end--><!--bot-comment-something-tests-start-->\n         * something else<!--bot-comment-something-tests-end--><!--bot-comment-docs-start-->\n         * the docs<!--bot-comment-docs-end--><!--bot-comment-skipped-tests-start-->\n         * the skipped tests<!--bot-comment-skipped-tests-end-->\n        \"\"\"\n        ).strip(),\n    ),\n)\n# pylint: enable=line-too-long\ndef test_pr_comment(tmpdir_factory, pr_author, comments, expected):\n    \"\"\"\n    Test the PR commenting bot\n    \"\"\"\n    comment_script = REPO_ROOT / \"ci\" / \"scripts\" / \"github_pr_comment.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    target_url = \"https://ci.tlcpack.ai/job/tvm/job/PR-11594/3/display/redirect\"\n    commit = {\n        \"commit\": {\n            \"oid\": \"sha1234\",\n            \"statusCheckRollup\": {\n                \"contexts\": {\n                    \"nodes\": [\n                        {\n                            \"context\": \"tvm-ci/pr-head\",\n                            \"targetUrl\": target_url,\n                        }\n                    ]\n                }\n            },\n        }\n    }\n    data = {\n        \"[1] POST - https://api.github.com/graphql\": {},\n        \"[2] POST - https://api.github.com/graphql\": {\n            \"data\": {\n                \"repository\": {\n                    \"pullRequest\": {\n                        \"number\": 1234,\n                        \"comments\": {\n                            \"nodes\": comments,\n                        },\n                        \"author\": {\n                            \"login\": pr_author,\n                        },\n                        \"commits\": {\n                            \"nodes\": [commit],\n                        },\n                    }\n                }\n            }\n        },\n    }\n    comments = {\n        \"ccs\": \"the cc\",\n        \"docs\": \"the docs\",\n        \"skipped-tests\": \"the skipped tests\",\n    }\n    proc = run_script(\n        [\n            comment_script,\n            \"--dry-run\",\n            \"--test-data\",\n            json.dumps(data),\n            \"--test-comments\",\n            json.dumps(comments),\n            \"--pr\",\n            \"1234\",\n        ],\n        stderr=subprocess.STDOUT,\n        cwd=git.cwd,\n    )\n    assert_in(expected, proc.stdout)\n\n\n@parameterize_named(\n    dont_skip_main=dict(\n        commands=[],\n        should_skip=False,\n        pr_title=\"[skip ci] test\",\n        why=\"ci should not be skipped on main\",\n    ),\n    dont_skip_main_with_commit=dict(\n        commands=[\n            [\"commit\", \"--allow-empty\", \"--message\", \"[skip ci] commit 1\"],\n        ],\n        should_skip=False,\n        pr_title=\"[skip ci] test\",\n        why=\"ci should not be skipped on main\",\n    ),\n    skip_on_new_branch=dict(\n        commands=[\n            [\"checkout\", \"-b\", \"some_new_branch\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"[skip ci] commit 1\"],\n        ],\n        should_skip=True,\n        pr_title=\"[skip ci] test\",\n        why=\"ci should be skipped on a branch with [skip ci] in the last commit\",\n    ),\n    no_skip_in_pr_title=dict(\n        commands=[\n            [\"checkout\", \"-b\", \"some_new_branch\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"[skip ci] commit 1\"],\n        ],\n        should_skip=False,\n        pr_title=\"[no skip ci] test\",\n        why=\"ci should not be skipped on a branch with \"\n        \"[skip ci] in the last commit but not the PR title\",\n    ),\n    skip_in_pr_title=dict(\n        commands=[\n            [\"checkout\", \"-b\", \"some_new_branch\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"[skip ci] commit 1\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"commit 2\"],\n        ],\n        should_skip=True,\n        pr_title=\"[skip ci] test\",\n        why=\"ci should be skipped with [skip ci] in the PR title\",\n    ),\n    skip_in_pr_title_many_commits=dict(\n        commands=[\n            [\"checkout\", \"-b\", \"some_new_branch\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"commit 1\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"commit 2\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"commit 3\"],\n            [\"commit\", \"--allow-empty\", \"--message\", \"commit 4\"],\n        ],\n        should_skip=True,\n        pr_title=\"[skip ci] test\",\n        why=\"ci should be skipped with [skip ci] in the PR title\",\n    ),\n    skip_anywhere_in_title=dict(\n        commands=[\n            [\"checkout\", \"-b\", \"some_new_branch\"],\n        ],\n        should_skip=True,\n        pr_title=\"[something][skip ci] test\",\n        why=\"skip ci tag should work anywhere in title\",\n    ),\n)\ndef test_skip_ci(tmpdir_factory, commands, should_skip, pr_title, why):\n    \"\"\"\n    Test that CI is skipped when it should be\n    \"\"\"\n    skip_ci_script = REPO_ROOT / \"ci\" / \"scripts\" / \"git_skip_ci.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n\n    git.run(\"config\", \"user.name\", \"ci\")\n    git.run(\"config\", \"user.email\", \"email@example.com\")\n    git.run(\"commit\", \"--allow-empty\", \"--message\", \"base commit\")\n    for command in commands:\n        git.run(*command)\n    pr_number = \"1234\"\n    proc = run_script(\n        [skip_ci_script, \"--pr\", pr_number, \"--pr-title\", pr_title],\n        cwd=git.cwd,\n        check=False,\n    )\n    expected = 0 if should_skip else 1\n    if proc.returncode != expected:\n        raise RuntimeError(\n            f\"Unexpected return code {proc.returncode} \"\n            f\"(expected {expected}) in {why}:\\n{proc.stdout}\"\n        )\n\n\n@parameterize_named(\n    no_file=dict(files=[], should_skip=True),\n    readme=dict(files=[\"README.md\"], should_skip=True),\n    c_file=dict(files=[\"test.c\"], should_skip=False),\n    c_and_readme=dict(files=[\"test.c\", \"README.md\"], should_skip=False),\n    src_file_and_readme=dict(\n        files=[\"src/autotvm/feature_visitor.cc\", \"README.md\"], should_skip=False\n    ),\n    yaml_and_readme=dict(files=[\".asf.yaml\", \"docs/README.md\"], should_skip=True),\n)\ndef test_skip_globs(tmpdir_factory, files, should_skip):\n    \"\"\"\n    Test that CI is skipped if only certain files are edited\n    \"\"\"\n    script = REPO_ROOT / \"ci\" / \"scripts\" / \"git_skip_ci_globs.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n\n    proc = run_script(\n        [\n            script,\n            \"--files\",\n            \",\".join(files),\n        ],\n        check=False,\n        cwd=git.cwd,\n    )\n\n    if should_skip:\n        assert proc.returncode == 0\n    else:\n        assert proc.returncode == 1\n\n\ndef all_time_keys(time):\n    return {\n        \"updatedAt\": time,\n        \"lastEditedAt\": time,\n        \"createdAt\": time,\n        \"publishedAt\": time,\n    }\n\n\n@parameterize_named(\n    draft=dict(\n        pull_request={\n            \"isDraft\": True,\n            \"number\": 2,\n        },\n        check=\"Checking 0 of 1 fetched\",\n    ),\n    not_draft=dict(\n        pull_request={\n            \"isDraft\": False,\n            \"number\": 2,\n        },\n        check=\"Checking 0 of 1 fetched\",\n    ),\n    week_old=dict(\n        pull_request={\n            \"number\": 123,\n            \"url\": \"https://github.com/apache/tvm/pull/123\",\n            \"body\": \"cc @someone\",\n            \"isDraft\": False,\n            \"author\": {\"login\": \"user\"},\n            \"reviews\": {\"nodes\": []},\n            **all_time_keys(\"2022-01-18T17:54:19Z\"),\n            \"comments\": {\"nodes\": []},\n        },\n        check=\"Pinging reviewers ['someone'] on https://github.com/apache/tvm/pull/123\",\n    ),\n    # Old comment, ping\n    old_comment=dict(\n        pull_request={\n            \"number\": 123,\n            \"url\": \"https://github.com/apache/tvm/pull/123\",\n            \"body\": \"cc @someone\",\n            \"isDraft\": False,\n            \"author\": {\"login\": \"user\"},\n            \"reviews\": {\"nodes\": []},\n            **all_time_keys(\"2022-01-18T17:54:19Z\"),\n            \"comments\": {\n                \"nodes\": [\n                    {\n                        **all_time_keys(\"2022-01-18T17:54:19Z\"),\n                        \"bodyText\": \"abc\",\n                    },\n                ]\n            },\n        },\n        check=\"Pinging reviewers ['someone'] on https://github.com/apache/tvm/pull/123\",\n    ),\n    # New comment, don't ping\n    new_comment=dict(\n        pull_request={\n            \"number\": 123,\n            \"url\": \"https://github.com/apache/tvm/pull/123\",\n            \"body\": \"cc @someone\",\n            \"isDraft\": False,\n            \"author\": {\"login\": \"user\"},\n            \"reviews\": {\"nodes\": []},\n            **all_time_keys(\"2022-01-18T17:54:19Z\"),\n            \"comments\": {\n                \"nodes\": [\n                    {**all_time_keys(\"2022-01-27T17:54:19Z\"), \"bodyText\": \"abc\"},\n                ]\n            },\n        },\n        check=\"Not pinging PR 123\",\n    ),\n)\ndef test_ping_reviewers(tmpdir_factory, pull_request, check):\n    \"\"\"\n    Test that reviewers are messaged after a time period of inactivity\n    \"\"\"\n    reviewers_script = REPO_ROOT / \"ci\" / \"scripts\" / \"ping_reviewers.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n\n    data = {\n        \"data\": {\n            \"repository\": {\n                \"pullRequests\": {\n                    \"nodes\": [pull_request],\n                    \"edges\": [],\n                }\n            }\n        }\n    }\n    proc = run_script(\n        [\n            reviewers_script,\n            \"--dry-run\",\n            \"--wait-time-minutes\",\n            \"1\",\n            \"--cutoff-pr-number\",\n            \"5\",\n            \"--pr-json\",\n            json.dumps(data),\n            \"--now\",\n            \"2022-01-26T17:54:19Z\",\n        ],\n        cwd=git.cwd,\n    )\n    assert_in(check, proc.stdout)\n\n\ndef assert_in(needle: str, haystack: str):\n    \"\"\"\n    Check that 'needle' is in 'haystack'\n    \"\"\"\n    if needle not in haystack:\n        raise AssertionError(f\"item not found:\\n{needle}\\nin:\\n{haystack}\")\n\n\n@tvm.testing.skip_if_wheel_test\n@parameterize_named(\n    no_cc=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"abc\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n            hello\n            \"\"\".strip()\n            ),\n        },\n        check=\"No one to cc, exiting\",\n    ),\n    no_additional_cc=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"abc\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n            hello\n\n            cc @test\n            \"\"\".strip()\n            ),\n        },\n        check=\"No one to cc, exiting\",\n    ),\n    cc_update=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                something\"\"\"\n            ),\n        },\n        check=\"would have updated issues/1234 with {'body': \"\n        \"'\\\\nhello\\\\n\\\\nsomething\\\\n\\\\ncc @person1 @person2 @person4'}\",\n    ),\n    already_cced=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                cc @person1 @person2 @person4\"\"\"\n            ),\n        },\n        check=\"No one to cc, exiting\",\n    ),\n    not_already_cced=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"[something] A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                something\"\"\"\n            ),\n        },\n        check=\"would have updated issues/1234 with {'body': \"\n        \"'\\\\nhello\\\\n\\\\nsomething\\\\n\\\\ncc @person1 @person2 @person4'}\",\n    ),\n    no_new_ccs=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"[something] A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                cc @person1 @person2 @person4\"\"\"\n            ),\n        },\n        check=\"No one to cc, exiting\",\n    ),\n    mismatching_tags=dict(\n        source_type=\"PR\",\n        data={\n            \"title\": \"[something] A title\",\n            \"number\": 1234,\n            \"draft\": False,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                cc @person1 @person2 @person4\"\"\"\n            ),\n        },\n        check=\"No one to cc, exiting\",\n    ),\n    draft_pr=dict(\n        source_type=\"PR\",\n        data={\n            \"title\": \"[something] A title\",\n            \"number\": 1234,\n            \"draft\": True,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": textwrap.dedent(\n                \"\"\"\n                hello\n\n                cc @person1 @person2 @person4\"\"\"\n            ),\n        },\n        check=\"Terminating since 1234 is a draft\",\n    ),\n    edit_inplace=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"[something] A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": \"`mold` and `lld` can be a much faster alternative to `ld` from gcc. \"\n            \"We should modify our CMakeLists.txt to detect and use these when possible. cc @person1\"\n            \"\\n\\ncc @person4\",\n        },\n        check=\"would have updated issues/1234 with {'body': '`mold` and `lld` can be a much\"\n        \" faster alternative to `ld` from gcc. We should modify our CMakeLists.txt to \"\n        \"detect and use these when possible. cc @person1\\\\n\\\\ncc @person2 @person4'}\",\n    ),\n    edit_out_of_place=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"[something3] A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [{\"name\": \"something2\"}],\n            \"body\": \"@person2 @SOME1-ONE-\",\n        },\n        check=\"Dry run, would have updated issues/1234 with\"\n        \" {'body': '@person2 @SOME1-ONE-\\\\n\\\\ncc @person1'}\",\n    ),\n    atted_but_not_cced=dict(\n        source_type=\"ISSUE\",\n        data={\n            \"title\": \"[] A title\",\n            \"number\": 1234,\n            \"user\": {\n                \"login\": \"person5\",\n            },\n            \"labels\": [],\n            \"body\": \"@person2 @SOME1-ONE-\",\n        },\n        check=\"No one to cc, exiting\",\n    ),\n)\ndef test_github_tag_teams(tmpdir_factory, source_type, data, check):\n    \"\"\"\n    Check that individuals are tagged from team headers\n    \"\"\"\n    tag_script = REPO_ROOT / \"ci\" / \"scripts\" / \"github_tag_teams.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n\n    issue_body = \"\"\"\n    some text\n    [temporary] opt-in: @person5\n\n    - something: @person1 @person2\n    - something3: @person1 @person2 @SOME1-ONE-\n    - something else @person1 @person2\n    - something else2: @person1 @person2\n    - something-else @person1 @person2\n    \"\"\"\n    comment1 = \"\"\"\n    another thing: @person3\n    another-thing @person3\n    \"\"\"\n    comment2 = \"\"\"\n    something @person4\n    @person5\n    \"\"\"\n    teams = {\n        \"data\": {\n            \"repository\": {\n                \"issue\": {\n                    \"body\": issue_body,\n                    \"comments\": {\"nodes\": [{\"body\": comment1}, {\"body\": comment2}]},\n                }\n            }\n        }\n    }\n    env = {\n        source_type: json.dumps(data),\n    }\n    proc = run_script(\n        [\n            tag_script,\n            \"--dry-run\",\n            \"--team-issue-json\",\n            json.dumps(teams),\n        ],\n        stderr=subprocess.STDOUT,\n        cwd=git.cwd,\n        env=env,\n    )\n\n    assert_in(check, proc.stdout)\n\n\n@tvm.testing.skip_if_wheel_test\n@parameterize_named(\n    same_tags=dict(\n        tlcpackstaging_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T00:00:00.123456Z\",\n                    \"name\": \"123-123-abc\",\n                },\n            ]\n        },\n        tlcpack_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T00:00:00.123456Z\",\n                    \"name\": \"123-123-abc\",\n                },\n            ]\n        },\n        expected=\"Tag names were the same, no update needed\",\n        expected_images=[],\n    ),\n    staging_update=dict(\n        tlcpackstaging_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T01:00:00.123456Z\",\n                    \"name\": \"234-234-abc-staging\",\n                },\n                {\n                    \"last_updated\": \"2022-06-01T00:00:00.123456Z\",\n                    \"name\": \"456-456-abc\",\n                },\n            ]\n        },\n        tlcpack_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T00:00:00.123456Z\",\n                    \"name\": \"123-123-abc\",\n                },\n            ]\n        },\n        expected=\"Using tlcpackstaging tag on tlcpack\",\n        expected_images=[\n            \"ci_arm = 'tlcpack/ci-arm:456-456-abc'\",\n        ],\n    ),\n    tlcpack_update=dict(\n        tlcpackstaging_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T00:00:00.123456Z\",\n                    \"name\": \"123-123-abc\",\n                },\n            ]\n        },\n        tlcpack_body={\n            \"results\": [\n                {\n                    \"last_updated\": \"2022-06-01T00:01:00.123456Z\",\n                    \"name\": \"234-234-abc\",\n                },\n            ]\n        },\n        expected=\"Found newer image, using: tlcpack\",\n        expected_images=[\n            \"ci_arm = 'tlcpack/ci-arm:234-234-abc'\",\n        ],\n    ),\n)\ndef test_open_docker_update_pr(\n    tmpdir_factory, tlcpackstaging_body, tlcpack_body, expected, expected_images\n):\n    \"\"\"Test workflow to open a PR to update Docker images\"\"\"\n    tag_script = REPO_ROOT / \"ci\" / \"scripts\" / \"open_docker_update_pr.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    git.run(\"config\", \"user.name\", \"ci\")\n    git.run(\"config\", \"user.email\", \"email@example.com\")\n    images = [\n        \"ci_arm\",\n        \"ci_cortexm\",\n        \"ci_cpu\",\n        \"ci_gpu\",\n        \"ci_hexagon\",\n        \"ci_i386\",\n        \"ci_lint\",\n        \"ci_minimal\",\n        \"ci_riscv\",\n        \"ci_wasm\",\n    ]\n\n    docker_data = {}\n    for image in images:\n        docker_data[f\"repositories/tlcpackstaging/{image}/tags\"] = tlcpackstaging_body\n        docker_data[f\"repositories/tlcpack/{image.replace('_', '-')}/tags\"] = tlcpack_body\n\n    proc = run_script(\n        [\n            tag_script,\n            \"--dry-run\",\n            \"--testing-docker-data\",\n            json.dumps(docker_data),\n        ],\n        cwd=git.cwd,\n        env={\"GITHUB_TOKEN\": \"1234\"},\n        stderr=subprocess.STDOUT,\n    )\n\n    for line in expected_images:\n        if line not in proc.stdout:\n            raise RuntimeError(f\"Missing line {line} in output:\\n{proc.stdout}\")\n\n    assert_in(expected, proc.stdout)\n\n\n@parameterize_named(\n    use_tlcpack=dict(\n        images=[\"ci_arm=tlcpack/ci-arm:abc-abc-123\", \"ci_lint=tlcpack/ci-lint:abc-abc-234\"],\n        expected={\n            \"ci_arm\": \"tlcpack/ci-arm:abc-abc-123\",\n            \"ci_lint\": \"tlcpack/ci-lint:abc-abc-234\",\n        },\n    ),\n    use_staging=dict(\n        images=[\"ci_arm2=tlcpack/ci-arm2:abc-abc-123\"],\n        expected={\n            \"ci_arm2\": \"tlcpackstaging/ci_arm2:abc-abc-123\",\n        },\n    ),\n)\ndef test_determine_docker_images(tmpdir_factory, images, expected):\n    \"\"\"Test script to decide whether to use tlcpack or tlcpackstaging for images\"\"\"\n    script = REPO_ROOT / \"ci\" / \"scripts\" / \"determine_docker_images.py\"\n\n    git_dir = tmpdir_factory.mktemp(\"tmp_git_dir\")\n\n    docker_data = {\n        \"repositories/tlcpack/ci-arm/tags/abc-abc-123\": {},\n        \"repositories/tlcpack/ci-lint/tags/abc-abc-234\": {},\n    }\n\n    run_script(\n        [\n            script,\n            \"--testing-docker-data\",\n            json.dumps(docker_data),\n            \"--base-dir\",\n            git_dir,\n        ]\n        + images,\n        cwd=git_dir,\n    )\n\n    for expected_filename, expected_image in expected.items():\n        with open(Path(git_dir) / expected_filename) as f:\n            actual_image = f.read()\n\n        assert actual_image == expected_image\n\n\n@parameterize_named(\n    invalid_name=dict(\n        changed_files=[],\n        name=\"abc\",\n        check=\"Image abc is not using new naming scheme\",\n        expected_code=1,\n    ),\n    no_hash=dict(\n        changed_files=[], name=\"123-123-abc\", check=\"No extant hash found\", expected_code=1\n    ),\n    no_changes=dict(\n        changed_files=[[\"test.txt\"]],\n        name=None,\n        check=\"Did not find changes, no rebuild necessary\",\n        expected_code=0,\n    ),\n    docker_changes=dict(\n        changed_files=[[\"test.txt\"], [\"docker/test.txt\"]],\n        name=None,\n        check=\"Found docker changes\",\n        expected_code=2,\n    ),\n)\ndef test_should_rebuild_docker(tmpdir_factory, changed_files, name, check, expected_code):\n    \"\"\"\n    Check that the Docker images are built when necessary\n    \"\"\"\n    tag_script = REPO_ROOT / \"ci\" / \"scripts\" / \"should_rebuild_docker.py\"\n\n    git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n    git.run(\"config\", \"user.name\", \"ci\")\n    git.run(\"config\", \"user.email\", \"email@example.com\")\n\n    git_path = Path(git.cwd)\n    for i, commits in enumerate(changed_files):\n        for filename in commits:\n            path = git_path / filename\n            path.parent.mkdir(exist_ok=True, parents=True)\n            path.touch()\n            git.run(\"add\", filename)\n\n        git.run(\"commit\", \"-m\", f\"message {i}\")\n\n    if name is None:\n        ref = \"HEAD\"\n        if len(changed_files) > 1:\n            ref = f\"HEAD~{len(changed_files) - 1}\"\n        proc = git.run(\"rev-parse\", ref, stdout=subprocess.PIPE)\n        last_hash = proc.stdout.strip()\n        name = f\"123-123-{last_hash}\"\n\n    docker_data = {\n        \"repositories/tlcpack\": {\n            \"results\": [\n                {\n                    \"name\": \"ci-something\",\n                },\n                {\n                    \"name\": \"something-else\",\n                },\n            ],\n        },\n        \"repositories/tlcpack/ci-something/tags\": {\n            \"results\": [{\"name\": name}, {\"name\": name + \"old\"}],\n        },\n    }\n\n    proc = run_script(\n        [\n            tag_script,\n            \"--testing-docker-data\",\n            json.dumps(docker_data),\n        ],\n        stderr=subprocess.STDOUT,\n        cwd=git.cwd,\n        check=False,\n    )\n\n    assert_in(check, proc.stdout)\n    assert proc.returncode == expected_code\n\n\n@parameterize_named(\n    passing=dict(\n        title=\"[something] a change\",\n        body=\"something\",\n        expected=\"All checks passed\",\n        expected_code=0,\n    ),\n    period=dict(\n        title=\"[something] a change.\",\n        body=\"something\",\n        expected=\"trailing_period: FAILED\",\n        expected_code=1,\n    ),\n    empty_body=dict(\n        title=\"[something] a change\",\n        body=None,\n        expected=\"non_empty: FAILED\",\n        expected_code=1,\n    ),\n)\ndef test_pr_linter(title, body, expected, expected_code):\n    \"\"\"\n    Test the PR linter\n    \"\"\"\n    tag_script = REPO_ROOT / \"ci\" / \"scripts\" / \"check_pr.py\"\n    pr_data = {\n        \"title\": title,\n        \"body\": body,\n    }\n    proc = run_script(\n        [\n            tag_script,\n            \"--pr\",\n            1234,\n            \"--pr-data\",\n            json.dumps(pr_data),\n        ],\n        check=False,\n    )\n    assert proc.returncode == expected_code\n    assert_in(expected, proc.stdout)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/ci/test_script_converter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTest the conversion of bash to rst\n\"\"\"\n\nimport sys\n\nimport tvm\nfrom tvm.contrib import utils\n\n# this has to be after the sys.path patching, so ignore pylint\n# pylint: disable=wrong-import-position,wrong-import-order\nfrom .test_utils import REPO_ROOT\n\nsys.path.insert(0, str(REPO_ROOT / \"docs\"))\nfrom script_convert import (\n    bash_to_python,\n    BASH,\n    BASH_IGNORE,\n    BASH_MULTILINE_COMMENT_START,\n    BASH_MULTILINE_COMMENT_END,\n)\n\n# pylint: enable=wrong-import-position,wrong-import-order\n\n\ndef test_bash_cmd():\n    \"\"\"Test that a bash command gets turned into a rst code block\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(BASH)\n        src_f.write(\"\\n\")\n        src_f.write(\"tvmc\\n\")\n        src_f.write(BASH)\n        src_f.write(\"\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = \"# .. code-block:: bash\\n\" \"#\\n\" \"#\\t  tvmc\\n\" \"#\\n\"\n\n    assert generated_cmd == expected_cmd\n\n\ndef test_bash_ignore_cmd():\n    \"\"\"Test that ignored bash commands are not turned into code blocks\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(\"# start\\n\")\n        src_f.write(BASH_IGNORE)\n        src_f.write(\"\\n\")\n        src_f.write(\"tvmc\\n\")\n        src_f.write(BASH_IGNORE)\n        src_f.write(\"\\n\")\n        src_f.write(\"# end\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = \"# start\\n\" \"# end\\n\"\n    assert generated_cmd == expected_cmd\n\n\ndef test_no_command():\n    \"\"\"Test a file with no code blocks\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(\"# start\\n\")\n        src_f.write(\"# description\\n\")\n        src_f.write(\"end\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = \"# start\\n\" \"# description\\n\" \"end\\n\"\n    assert generated_cmd == expected_cmd\n\n\ndef test_text_and_bash_command():\n    \"\"\"Test a file with a bash code block\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(\"# start\\n\")\n        src_f.write(BASH)\n        src_f.write(\"\\n\")\n        src_f.write(\"tvmc\\n\")\n        src_f.write(BASH)\n        src_f.write(\"\\n\")\n        src_f.write(\"# end\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = \"# start\\n\" \"# .. code-block:: bash\\n\" \"#\\n\" \"#\\t  tvmc\\n\" \"#\\n\" \"# end\\n\"\n\n    assert generated_cmd == expected_cmd\n\n\ndef test_last_line_break():\n    \"\"\"Test that line endings are correct\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(\"# start\\n\")\n        src_f.write(\"# end\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = \"# start\\n\" \"# end\\n\"\n\n    assert generated_cmd == expected_cmd\n\n\ndef test_multiline_comment():\n    \"\"\"Test that bash comments are inserted correctly\"\"\"\n    temp = utils.tempdir()\n    src_path = temp / \"src.sh\"\n    dest_path = temp / \"dest.py\"\n\n    with open(src_path, \"w\") as src_f:\n        src_f.write(BASH_MULTILINE_COMMENT_START)\n        src_f.write(\"\\n\")\n        src_f.write(\"comment\\n\")\n        src_f.write(BASH_MULTILINE_COMMENT_END)\n        src_f.write(\"\\n\")\n\n    bash_to_python(src_path, dest_path)\n\n    with open(dest_path, \"r\") as dest_f:\n        generated_cmd = dest_f.read()\n\n    expected_cmd = '\"\"\"\\n' \"comment\\n\" '\"\"\"\\n'\n\n    assert generated_cmd == expected_cmd\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/ci/test_tvmbot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTest the @tvm-bot merge code\n\"\"\"\n\nimport json\nfrom pathlib import Path\nfrom typing import Dict, Any\n\nimport tvm\nfrom .test_utils import REPO_ROOT, TempGit, run_script\n\n\nSUCCESS_EXPECTED_OUTPUT = \"\"\"\nDry run, would have merged with url=pulls/10786/merge and data={\n  \"commit_title\": \"[Hexagon] 2-d allocation cleanup (#10786)\",\n  \"commit_message\": \"- Added device validity check in allocation. HexagonDeviceAPI should only be called for CPU/Hexagon types.\\\\n\\\\n- Check for \\\\\"global.vtcm\\\\\" scope instead of \\\\\"vtcm\\\\\".  The ccope of N-d allocations produced by `LowerVtcmAlloc` should be `\\\\\"global.vtcm\\\\\"`.  The previous check allowed unsupported scope such as `\\\\\"local.vtcm\\\\\"`.\\\\n\\\\n- Remove `vtcmallocs` entry after calling free.\\\\n\\\\nPreviously, the vtcm allocation map kept dangling pointers to `HexagonBuffer` objects after they had been freed.\\\\n\\\\n- Rename N-d alloc and free packed functions.  Since most of the similar device functions use snake case, renaming `*.AllocND` to `*.alloc_nd` and `*.FreeND` to `*.free_nd`.\\\\n\\\\n\\\\ncc someone\\\\n\\\\n\\\\nCo-authored-by: Adam Straw <astraw@octoml.ai>\",\n  \"sha\": \"6f04bcf57d07f915a98fd91178f04d9e92a09fcd\",\n  \"merge_method\": \"squash\"\n}\n\"\"\".strip()\n\n\nclass _TvmBotTest:\n    NUMBER = 10786\n\n    def preprocess_data(self, data: Dict[str, Any]):\n        \"\"\"\n        Used to pre-process PR data before running the test. Override as\n        necessary to edit data for specific test cases.\n        \"\"\"\n        return data\n\n    @tvm.testing.skip_if_wheel_test\n    def test(self, tmpdir_factory):\n        \"\"\"\n        Run the tvm-bot script using the data from preprocess_data\n        \"\"\"\n        mergebot_script = REPO_ROOT / \"ci\" / \"scripts\" / \"github_tvmbot.py\"\n        test_json_dir = Path(__file__).resolve().parent / \"sample_prs\"\n        with open(test_json_dir / f\"pr{self.NUMBER}.json\") as f:\n            test_data = json.load(f)\n\n        # Update testing data with replacements / additions\n        test_data = self.preprocess_data(test_data)\n\n        git = TempGit(tmpdir_factory.mktemp(\"tmp_git_dir\"))\n\n        comment = {\n            \"body\": self.COMMENT,\n            \"id\": 123,\n            \"user\": {\n                \"login\": self.USER,\n            },\n        }\n        allowed_users = [{\"login\": \"abc\"}, {\"login\": \"other-abc\"}]\n\n        proc = run_script(\n            [\n                mergebot_script,\n                \"--pr\",\n                self.NUMBER,\n                \"--dry-run\",\n                \"--run-url\",\n                \"https://example.com\",\n                \"--testing-pr-json\",\n                json.dumps(test_data),\n                \"--testing-collaborators-json\",\n                json.dumps(allowed_users),\n                \"--testing-mentionable-users-json\",\n                json.dumps(allowed_users),\n                \"--trigger-comment-json\",\n                json.dumps(comment),\n            ],\n            env={\n                \"TVM_BOT_JENKINS_TOKEN\": \"123\",\n                \"GH_ACTIONS_TOKEN\": \"123\",\n            },\n            cwd=git.cwd,\n        )\n\n        if self.EXPECTED not in proc.stderr:\n            raise RuntimeError(f\"{proc.stderr}\\ndid not contain\\n{self.EXPECTED}\")\n\n\nclass TestNoRequest(_TvmBotTest):\n    \"\"\"\n    A PR for which the mergebot runs but no merge is requested\n    \"\"\"\n\n    COMMENT = \"@tvm-bot do something else\"\n    USER = \"abc\"\n    EXPECTED = \"Command 'do something else' did not match anything\"\n\n    def preprocess_data(self, data: Dict[str, Any]):\n        data[\"reviews\"][\"nodes\"][0][\"body\"] = \"nothing\"\n        return data\n\n\nclass TestSuccessfulMerge(_TvmBotTest):\n    \"\"\"\n    Everything is fine so this PR will merge\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = SUCCESS_EXPECTED_OUTPUT\n\n\nclass TestBadCI(_TvmBotTest):\n    \"\"\"\n    A PR which failed CI and cannot merge\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Cannot merge, these CI jobs are not successful on\"\n\n    def preprocess_data(self, data: Dict[str, Any]):\n        # Mark the Jenkins build as failed\n        contexts = data[\"commits\"][\"nodes\"][0][\"commit\"][\"statusCheckRollup\"][\"contexts\"][\"nodes\"]\n        for context in contexts:\n            if \"context\" in context and context[\"context\"] == \"tvm-ci/pr-head\":\n                context[\"state\"] = \"FAILED\"\n        return data\n\n\nclass TestOldReview(_TvmBotTest):\n    \"\"\"\n    A PR with passing CI and approving reviews on an old commit so it cannot merge\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Cannot merge, did not find any approving reviews\"\n\n    def preprocess_data(self, data: Dict[str, Any]) -> Dict[str, Any]:\n        data[\"reviews\"][\"nodes\"][0][\"commit\"][\"oid\"] = \"abc12345\"\n        return data\n\n\nclass TestMissingJob(_TvmBotTest):\n    \"\"\"\n    PR missing an expected CI job and cannot merge\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Cannot merge, missing expected jobs\"\n\n    def preprocess_data(self, data: Dict[str, Any]) -> Dict[str, Any]:\n        contexts = data[\"commits\"][\"nodes\"][0][\"commit\"][\"statusCheckRollup\"][\"contexts\"][\"nodes\"]\n        for context in contexts:\n            if \"context\" in context and context[\"context\"] == \"tvm-ci/pr-head\":\n                context[\"context\"] = \"something\"\n        return data\n\n\nclass TestInvalidAuthor(_TvmBotTest):\n    \"\"\"\n    Merge requester is not a committer and cannot merge\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"not-abc\"\n    EXPECTED = \"Failed auth check 'collaborators', quitting\"\n\n\nclass TestUnauthorizedComment(_TvmBotTest):\n    \"\"\"\n    Check that a merge comment not from a CONTRIBUTOR is rejected\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"not-abc2\"\n    EXPECTED = \"Failed auth check 'collaborators'\"\n\n\nclass TestNoReview(_TvmBotTest):\n    \"\"\"\n    Check that a merge request without any reviews is rejected\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Cannot merge, did not find any approving reviews from users with write access\"\n\n    def preprocess_data(self, data: Dict[str, Any]) -> Dict[str, Any]:\n        data[\"reviews\"][\"nodes\"] = []\n        return data\n\n\nclass TestChangesRequested(_TvmBotTest):\n    \"\"\"\n    Check that a merge request with a 'Changes Requested' review is rejected\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Cannot merge, found [this review]\"\n\n    def preprocess_data(self, data: Dict[str, Any]) -> Dict[str, Any]:\n        data[\"reviews\"][\"nodes\"][0][\"state\"] = \"CHANGES_REQUESTED\"\n        data[\"reviews\"][\"nodes\"][0][\"url\"] = \"http://example.com\"\n        return data\n\n\nclass TestCoAuthors(_TvmBotTest):\n    \"\"\"\n    Check that a merge request with co-authors generates the correct commit message\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Co-authored-by: Some One <someone@email.com>\"\n\n    def preprocess_data(self, data: Dict[str, Any]) -> Dict[str, Any]:\n        data[\"authorCommits\"][\"nodes\"][0][\"commit\"][\"authors\"][\"nodes\"].append(\n            {\"name\": \"Some One\", \"email\": \"someone@email.com\"}\n        )\n        return data\n\n\nclass TestRerunCI(_TvmBotTest):\n    \"\"\"\n    Start a new CI job\n    \"\"\"\n\n    COMMENT = \"@tvm-bot rerun\"\n    USER = \"abc\"\n    EXPECTED = \"Rerunning ci with\"\n\n\nclass TestRerunPermissions(_TvmBotTest):\n    \"\"\"\n    Start a new CI job as an unauthorized user\n    \"\"\"\n\n    COMMENT = \"@tvm-bot rerun\"\n    USER = \"someone\"\n    EXPECTED = \"Failed auth check 'metionable_users', quitting\"\n\n\nclass TestRerunNonAuthor(_TvmBotTest):\n    \"\"\"\n    Start a new CI job as a mentionable user\n    \"\"\"\n\n    COMMENT = \"@tvm-bot rerun\"\n    USER = \"other-abc\"\n    EXPECTED = \"Passed auth check 'metionable_users', continuing\"\n\n\nclass TestIgnoreJobs(_TvmBotTest):\n    \"\"\"\n    Ignore GitHub Actions jobs that don't start with CI /\n    \"\"\"\n\n    COMMENT = \"@tvm-bot merge\"\n    USER = \"abc\"\n    EXPECTED = \"Dry run, would have merged\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/ci/test_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nConstants used in various CI tests\n\"\"\"\nimport subprocess\nimport pathlib\nfrom typing import List, Any\n\nREPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent.parent\n\n\nclass TempGit:\n    \"\"\"\n    A wrapper to run commands in a directory (specifically for use in CI tests)\n    \"\"\"\n\n    def __init__(self, cwd):\n        self.cwd = cwd\n        # Jenkins git is too old and doesn't have 'git init --initial-branch',\n        # so init and checkout need to be separate steps\n        self.run(\"init\", stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n        self.run(\"checkout\", \"-b\", \"main\", stderr=subprocess.PIPE)\n        self.run(\"remote\", \"add\", \"origin\", \"https://github.com/apache/tvm.git\")\n\n    def run(self, *args, **kwargs):\n        \"\"\"\n        Run a git command based on *args\n        \"\"\"\n        proc = subprocess.run(\n            [\"git\"] + list(args), encoding=\"utf-8\", cwd=self.cwd, check=False, **kwargs\n        )\n        if proc.returncode != 0:\n            raise RuntimeError(f\"git command failed: '{args}'\")\n\n        return proc\n\n\ndef run_script(command: List[Any], check: bool = True, **kwargs):\n    \"\"\"\n    Wrapper to run a script and print its output if there was an error\n    \"\"\"\n    command = [str(c) for c in command]\n    kwargs_to_send = {\n        \"stdout\": subprocess.PIPE,\n        \"stderr\": subprocess.PIPE,\n        \"encoding\": \"utf-8\",\n    }\n    kwargs_to_send.update(kwargs)\n    proc = subprocess.run(\n        command,\n        check=False,\n        **kwargs_to_send,\n    )\n    if check and proc.returncode != 0:\n        raise RuntimeError(f\"Process failed:\\nstdout:\\n{proc.stdout}\\n\\nstderr:\\n{proc.stderr}\")\n\n    return proc\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport tvm\nimport pytest\n\ncollect_ignore = []\nif sys.platform.startswith(\"win\"):\n    collect_ignore.append(\"frontend/caffe\")\n    collect_ignore.append(\"frontend/caffe2\")\n    collect_ignore.append(\"frontend/coreml\")\n    collect_ignore.append(\"frontend/darknet\")\n    collect_ignore.append(\"frontend/keras\")\n    collect_ignore.append(\"frontend/mxnet\")\n    collect_ignore.append(\"frontend/pytorch\")\n    collect_ignore.append(\"frontend/tensorflow\")\n    collect_ignore.append(\"frontend/tflite\")\n    collect_ignore.append(\"frontend/onnx\")\n    collect_ignore.append(\"driver/tvmc/test_autoscheduler.py\")\n    collect_ignore.append(\"unittest/test_auto_scheduler_cost_model.py\")  # stack overflow\n    # collect_ignore.append(\"unittest/test_auto_scheduler_measure.py\") # exception ignored\n    collect_ignore.append(\"unittest/test_auto_scheduler_search_policy.py\")  # stack overflow\n    # collect_ignore.append(\"unittest/test_auto_scheduler_measure.py\") # exception ignored\n\n    collect_ignore.append(\"unittest/test_tir_intrin.py\")\n\n\ndef pytest_addoption(parser):\n    parser.addoption(\n        \"--enable-corstone300-tests\",\n        action=\"store_true\",\n        default=False,\n        help=\"Run Corstone-300 FVP tests\",\n    )\n\n\ndef pytest_collection_modifyitems(config, items):\n    if not config.getoption(\"--enable-corstone300-tests\"):\n        for item in items:\n            if \"corstone300\" in item.keywords:\n                item.add_marker(\n                    pytest.mark.skip(\n                        reason=\"Need --enable-corstone300-tests option to run this test\"\n                    )\n                )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for Arm Compute Library\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom itertools import zip_longest, combinations\nimport json\nimport os\nimport warnings\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import rpc\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.op.contrib import arm_compute_lib\nfrom tvm.contrib import utils\nfrom tvm.autotvm.measure import request_remote\n\n\nclass Device:\n    \"\"\"\n    Configuration for Arm Compute Library tests.\n\n    Check tests/python/contrib/arm_compute_lib/ for the presence of an test_config.json file.\n    This file can be used to override the default configuration here which will attempt to run the Arm\n    Compute Library runtime tests locally if the runtime is available. Changing the configuration\n    will allow these runtime tests to be offloaded to a remote Arm device via a tracker for example.\n\n    Notes\n    -----\n        The test configuration will be loaded once when the class is created. If the configuration\n        changes between tests, any changes will not be picked up.\n\n    Parameters\n    ----------\n    device : RPCSession\n        Allows tests to connect to and use remote device.\n\n    Attributes\n    ----------\n    connection_type : str\n        Details the type of RPC connection to use. Options:\n        local - Use the local device,\n        tracker - Connect to a tracker to request a remote device,\n        remote - Connect to a remote device directly.\n    host : str\n        Specify IP address or hostname of remote target.\n    port : int\n        Specify port number of remote target.\n    target : str\n        The compilation target.\n    device_key : str\n        The device key of the remote target. Use when connecting to a remote device via a tracker.\n    cross_compile : str\n        Specify path to cross compiler to use when connecting a remote device from a non-arm platform.\n    \"\"\"\n\n    connection_type = \"local\"\n    host = \"127.0.0.1\"\n    port = 9090\n    target = \"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\"\n    device_key = \"\"\n    cross_compile = \"\"\n\n    def __init__(self):\n        \"\"\"Keep remote device for lifetime of object.\"\"\"\n        self.device = self._get_remote()\n\n    @classmethod\n    def _get_remote(cls):\n        \"\"\"Get a remote (or local) device to use for testing.\"\"\"\n        if cls.connection_type == \"tracker\":\n            device = request_remote(cls.device_key, cls.host, cls.port, timeout=1000)\n        elif cls.connection_type == \"remote\":\n            device = rpc.connect(cls.host, cls.port)\n        elif cls.connection_type == \"local\":\n            device = rpc.LocalSession()\n        else:\n            raise ValueError(\n                \"connection_type in test_config.json should be one of: \" \"local, tracker, remote.\"\n            )\n\n        return device\n\n    @classmethod\n    def load(cls, file_name):\n        \"\"\"Load test config\n\n        Load the test configuration by looking for file_name relative\n        to the test_arm_compute_lib directory.\n        \"\"\"\n        location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n        config_file = os.path.join(location, file_name)\n        if not os.path.exists(config_file):\n            warnings.warn(\n                \"Config file doesn't exist, resuming Arm Compute Library tests with default config.\"\n            )\n            return\n        with open(config_file, mode=\"r\") as config:\n            test_config = json.load(config)\n\n        cls.connection_type = test_config[\"connection_type\"]\n        cls.host = test_config[\"host\"]\n        cls.port = test_config[\"port\"]\n        cls.target = test_config[\"target\"]\n        cls.device_key = test_config.get(\"device_key\") or \"\"\n        cls.cross_compile = test_config.get(\"cross_compile\") or \"\"\n\n\ndef get_cpu_op_count(mod):\n    \"\"\"Traverse graph counting ops offloaded to TVM.\"\"\"\n\n    class Counter(tvm.relay.ExprVisitor):\n        def __init__(self):\n            super().__init__()\n            self.count = 0\n\n        def visit_call(self, call):\n            if isinstance(call.op, tvm.ir.Op):\n                self.count += 1\n\n            super().visit_call(call)\n\n    c = Counter()\n    c.visit(mod[\"main\"])\n    return c.count\n\n\ndef skip_runtime_test():\n    \"\"\"Skip test if it requires the runtime and it's not present.\"\"\"\n    # ACL codegen not present.\n    if not tvm.get_global_func(\"relay.ext.arm_compute_lib\", True):\n        print(\"Skip because Arm Compute Library codegen is not available.\")\n        return True\n\n    # Remote device is in use or ACL runtime not present\n    # Note: Ensure that the device config has been loaded before this check\n    if (\n        not Device.connection_type != \"local\"\n        and not arm_compute_lib.is_arm_compute_runtime_enabled()\n    ):\n        print(\"Skip because runtime isn't present or a remote device isn't being used.\")\n        return True\n\n\ndef skip_codegen_test():\n    \"\"\"Skip test if it requires the ACL codegen and it's not present.\"\"\"\n    if not tvm.get_global_func(\"relay.ext.arm_compute_lib\", True):\n        print(\"Skip because Arm Compute Library codegen is not available.\")\n        return True\n\n\ndef build_module(\n    mod,\n    target,\n    params=None,\n    enable_acl=True,\n    tvm_ops=0,\n    acl_partitions=1,\n    disabled_ops=[\"concatenate\"],\n):\n    \"\"\"Build module with option to build for ACL.\"\"\"\n    if isinstance(mod, tvm.relay.expr.Call):\n        mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n        if enable_acl:\n            mod = arm_compute_lib.partition_for_arm_compute_lib(\n                mod, params, disabled_ops=disabled_ops\n            )\n            tvm_op_count = get_cpu_op_count(mod)\n            assert tvm_op_count == tvm_ops, \"Got {} TVM operators, expected {}\".format(\n                tvm_op_count, tvm_ops\n            )\n            partition_count = 0\n            for global_var in mod.get_global_vars():\n                if \"arm_compute_lib\" in global_var.name_hint:\n                    partition_count += 1\n\n            assert (\n                acl_partitions == partition_count\n            ), \"Got {} Arm Compute Library partitions, expected {}\".format(\n                partition_count, acl_partitions\n            )\n        relay.backend.te_compiler.get().clear()\n        return relay.build(mod, target=target, params=params)\n\n\ndef build_and_run(\n    mod,\n    inputs,\n    outputs,\n    params,\n    device,\n    enable_acl=True,\n    no_runs=1,\n    tvm_ops=0,\n    acl_partitions=1,\n    config=None,\n    disabled_ops=[\"concatenate\"],\n):\n    \"\"\"Build and run the relay module.\"\"\"\n    if config is None:\n        config = {}\n\n    try:\n        lib = build_module(\n            mod, device.target, params, enable_acl, tvm_ops, acl_partitions, disabled_ops\n        )\n    except Exception as e:\n        err_msg = \"The module could not be built.\\n\"\n        if config:\n            err_msg += f\"The test failed with the following parameters: {config}\\n\"\n        err_msg += str(e)\n        raise Exception(err_msg)\n\n    lib = update_lib(lib, device.device, device.cross_compile)\n    gen_module = graph_executor.GraphModule(lib[\"default\"](device.device.cpu(0)))\n    gen_module.set_input(**inputs)\n    out = []\n    for _ in range(no_runs):\n        gen_module.run()\n        out.append([gen_module.get_output(i) for i in range(outputs)])\n    return out\n\n\ndef update_lib(lib, device, cross_compile):\n    \"\"\"Export the library to the remote/local device.\"\"\"\n    lib_name = \"mod.so\"\n    temp = utils.tempdir()\n    lib_path = temp.relpath(lib_name)\n    if cross_compile:\n        lib.export_library(lib_path, cc=cross_compile)\n    else:\n        lib.export_library(lib_path)\n    device.upload(lib_path)\n    lib = device.load_module(lib_name)\n    return lib\n\n\ndef verify(answers, atol, rtol, verify_saturation=False, config=None):\n    \"\"\"Compare the array of answers. Each entry is a list of outputs.\"\"\"\n    if config is None:\n        config = {}\n\n    if len(answers) < 2:\n        raise RuntimeError(f\"No results to compare: expected at least two, found {len(answers)}\")\n    for answer in zip_longest(*answers):\n        for outs in combinations(answer, 2):\n            try:\n                if verify_saturation:\n                    assert (\n                        np.count_nonzero(outs[0].numpy() == 255) < 0.25 * outs[0].numpy().size\n                    ), \"Output is saturated: {}\".format(outs[0])\n                    assert (\n                        np.count_nonzero(outs[0].numpy() == 0) < 0.25 * outs[0].numpy().size\n                    ), \"Output is saturated: {}\".format(outs[0])\n                tvm.testing.assert_allclose(outs[0].numpy(), outs[1].numpy(), rtol=rtol, atol=atol)\n            except AssertionError as e:\n                err_msg = \"Results not within the acceptable tolerance.\\n\"\n                if config:\n                    err_msg += f\"The test failed with the following parameters: {config}\\n\"\n                err_msg += str(e)\n                raise AssertionError(err_msg)\n\n\ndef extract_acl_modules(module):\n    \"\"\"Get the ACL module(s) from llvm module.\"\"\"\n    return list(\n        filter(lambda mod: mod.type_key == \"arm_compute_lib\", module.get_lib().imported_modules)\n    )\n\n\ndef verify_codegen(\n    module,\n    known_good_codegen,\n    num_acl_modules=1,\n    tvm_ops=0,\n    target=\"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\",\n    disabled_ops=[\"concatenate\"],\n):\n    \"\"\"Check acl codegen against a known good output.\"\"\"\n    module = build_module(\n        module,\n        target,\n        tvm_ops=tvm_ops,\n        acl_partitions=num_acl_modules,\n        disabled_ops=disabled_ops,\n    )\n    acl_modules = extract_acl_modules(module)\n\n    assert len(acl_modules) == num_acl_modules, (\n        f\"The number of Arm Compute Library modules produced ({len(acl_modules)}) does not \"\n        f\"match the expected value ({num_acl_modules}).\"\n    )\n\n    for mod in acl_modules:\n        source = mod.get_source(\"json\")\n        codegen = json.loads(source)[\"nodes\"]\n        # remove input and const names as these cannot be predetermined\n        for node in range(len(codegen)):\n            if codegen[node][\"op\"] == \"input\" or codegen[node][\"op\"] == \"const\":\n                codegen[node][\"name\"] = \"\"\n        codegen_str = json.dumps(codegen, sort_keys=True, indent=2)\n        known_good_codegen_str = json.dumps(known_good_codegen, sort_keys=True, indent=2)\n\n        assert codegen_str == known_good_codegen_str, (\n            f\"The JSON produced by codegen does not match the expected result. \\n\"\n            f\"Actual={codegen_str} \\n\"\n            f\"Expected={known_good_codegen_str}\"\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_add.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration reshape tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\n\nfrom test_arm_compute_lib.infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom test_arm_compute_lib.infrastructure import Device\n\n_qnn_params = {\n    \"lhs_scale\": relay.const(0.0156863, \"float32\"),\n    \"lhs_zero_point\": relay.const(127, \"int32\"),\n    \"rhs_scale\": relay.const(0.0117647, \"float32\"),\n    \"rhs_zero_point\": relay.const(85, \"int32\"),\n    \"output_scale\": relay.const(0.0235294, \"float32\"),\n    \"output_zero_point\": relay.const(128, \"int32\"),\n}\n\n\ndef _get_model(shape, dtype, var_names, op, op_params):\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    b = relay.var(next(var_names), shape=shape, dtype=dtype)\n    return op(a, b, **op_params)\n\n\ndef _get_expected_codegen(shape, dtype, op_name, qnn_params):\n    input_a = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    input_b = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    input_qnn = [\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\n                \"shape\": [[list(qnn_params[_].data.shape)]],\n                \"dtype\": [[qnn_params[_].data.dtype]],\n            },\n        }\n        for _ in qnn_params\n    ]\n    inputs = [input_a, input_b, *input_qnn]\n    node = {\n        \"op\": \"kernel\",\n        \"name\": op_name,\n        \"inputs\": [[_, 0, 0] for _ in range(len(inputs))],\n        \"attrs\": {\n            \"num_inputs\": str(len(inputs)),\n            \"num_outputs\": \"1\",\n            \"shape\": [[list(shape)]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    if qnn_params:\n        node[\"attrs\"][\"lhs_axis\"] = [[\"-1\"]]\n        node[\"attrs\"][\"rhs_axis\"] = [[\"-1\"]]\n\n    return [*inputs, node]\n\n\ndef test_runtime_add():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    for dtype, low, high, atol, rtol, op, op_params in [\n        (\"float32\", -127, 128, 1e-7, 1e-7, relay.add, {}),\n        (\"uint8\", 0, 255, 0.0, 1.0, relay.qnn.op.add, _qnn_params),\n    ]:\n        shape = (2, 2)\n        for inputs in [\n            {\n                \"a\": tvm.nd.array(np.random.uniform(low, high, shape).astype(dtype)),\n                \"b\": tvm.nd.array(np.random.uniform(low, high, shape).astype(dtype)),\n            }\n        ]:\n            outputs = []\n            func = _get_model(shape, dtype, iter(inputs), op, op_params)\n            for acl in [True, False]:\n                outputs.append(build_and_run(func, inputs, 1, None, device, enable_acl=acl)[0])\n\n            config = {\n                \"shape\": shape,\n                \"dtype\": dtype,\n                \"inputs\": inputs,\n                \"operation\": op,\n                \"op_params\": op_params,\n            }\n\n            verify(outputs, atol=atol, rtol=rtol, config=config, verify_saturation=False)\n\n\ndef test_codegen_add():\n    if skip_codegen_test():\n        return\n\n    inputs = {\"a\", \"b\"}\n    for dtype, op_name, op, qnn_params in [\n        (\"float32\", \"add\", relay.add, {}),\n        (\"uint8\", \"qnn.add\", relay.qnn.op.add, _qnn_params),\n    ]:\n        for shape in [(1, 1), (2, 2, 2), (3, 3, 3, 3)]:\n            func = _get_model(shape, dtype, iter(inputs), op, qnn_params)\n            exp_codegen = _get_expected_codegen(shape, dtype, op_name, qnn_params)\n            verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_codegen_add()\n    test_runtime_add()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_concatenate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration concatenate tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\n\nfrom test_arm_compute_lib.infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom test_arm_compute_lib.infrastructure import Device\n\n\ndef _get_model(input_shape_a, input_shape_b, input_shape_c, axis, dtype, var_names):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    a = relay.var(next(var_names), shape=input_shape_a, dtype=dtype)\n    b = relay.var(next(var_names), shape=input_shape_b, dtype=dtype)\n    c = relay.var(next(var_names), shape=input_shape_c, dtype=dtype)\n    out = relay.concatenate([a, b, c], axis)\n    return out\n\n\ndef _get_expected_codegen(input_shape_a, input_shape_b, input_shape_c, axis, dtype):\n    node = {\n        \"op\": \"kernel\",\n        \"name\": \"concatenate\",\n        \"inputs\": [\n            [0, 0, 0],\n            [1, 0, 0],\n            [2, 0, 0],\n        ],\n        \"attrs\": {\n            \"num_outputs\": \"1\",\n            \"num_inputs\": \"3\",\n            \"dtype\": [[dtype]],\n            \"axis\": [[str(axis)]],\n            \"shape\": [[[6, 234, 234, 256]]],\n        },\n    }\n\n    input_a = {\n        \"op\": \"input\",\n        \"name\": \"\",\n        \"attrs\": {\n            \"shape\": [[input_shape_a]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    input_b = {\n        \"op\": \"input\",\n        \"name\": \"\",\n        \"attrs\": {\n            \"shape\": [[input_shape_b]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    input_c = {\n        \"op\": \"input\",\n        \"name\": \"\",\n        \"attrs\": {\n            \"shape\": [[input_shape_c]],\n            \"dtype\": [[dtype]],\n        },\n    }\n    return [input_a, input_b, input_c, node]\n\n\ndef test_concatenate():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    for input_shape_a, input_shape_b, input_shape_c, axis, dtype in [\n        ([1, 234, 234, 256], [2, 234, 234, 256], [3, 234, 234, 256], 0, \"float32\"),\n        ([1, 1, 234, 256], [1, 2, 234, 256], [1, 3, 234, 256], 1, \"float32\"),\n        ([1, 234, 234, 1], [1, 234, 234, 2], [1, 234, 234, 3], -1, \"float32\"),\n        ([1, 234, 234, 256], [2, 234, 234, 256], [3, 234, 234, 256], -4, \"float32\"),\n        ([1, 234, 234, 256], [2, 234, 234, 256], [3, 234, 234, 256], 0, \"uint8\"),\n        ([1, 1, 234, 256], [1, 2, 234, 256], [1, 3, 234, 256], 1, \"uint8\"),\n        ([1, 234, 234, 1], [1, 234, 234, 2], [1, 234, 234, 3], -1, \"uint8\"),\n        ([1, 234, 234, 256], [2, 234, 234, 256], [3, 234, 234, 256], -4, \"uint8\"),\n    ]:\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.randn(*input_shape_a).astype(dtype)),\n            \"b\": tvm.nd.array(np.random.randn(*input_shape_b).astype(dtype)),\n            \"c\": tvm.nd.array(np.random.randn(*input_shape_c).astype(dtype)),\n        }\n        func = _get_model(\n            inputs[\"a\"].shape, inputs[\"b\"].shape, inputs[\"c\"].shape, axis, dtype, iter(inputs)\n        )\n        for acl in [False, True]:\n            outputs.append(\n                build_and_run(func, inputs, 1, None, device, enable_acl=acl, disabled_ops=[])[0]\n            )\n\n        config = {\n            \"input_shape_a\": input_shape_a,\n            \"input_shape_b\": input_shape_b,\n            \"input_shape_c\": input_shape_c,\n            \"axis\": axis,\n            \"dtype\": dtype,\n        }\n        verify(outputs, atol=1e-7, rtol=1e-7, config=config)\n\n\ndef test_codegen_concatenate():\n    if skip_codegen_test():\n        return\n    shape_a = [1, 234, 234, 256]\n    shape_b = [2, 234, 234, 256]\n    shape_c = [3, 234, 234, 256]\n    axis = 0\n    inputs = {\"a\", \"b\", \"c\"}\n    for dtype in [\"float32\"]:\n        args = (shape_a, shape_b, shape_c, axis, dtype)\n        func = _get_model(*args, iter(inputs))\n        exp_codegen = _get_expected_codegen(*args)\n        verify_codegen(func, exp_codegen, 1, disabled_ops=[])\n\n\nif __name__ == \"__main__\":\n    test_concatenate()\n    test_codegen_concatenate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration conv2d tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\n\nfrom test_arm_compute_lib.infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom test_arm_compute_lib.infrastructure import Device\n\n\ndef _get_model(\n    shape,\n    kernel_h,\n    kernel_w,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    channels,\n    var_names,\n    has_bias=False,\n    has_activation=False,\n    has_pad=False,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    if has_pad:\n        p = ((0, 0), (padding[0], padding[0]), (padding[1], padding[1]), (0, 0))\n        a = relay.nn.pad(a, pad_width=p)\n        padding = (0, 0, 0, 0)\n    else:\n        if len(padding) == 2:\n            padding = (padding[0], padding[1], padding[0], padding[1])\n        shape = (shape[0], shape[1] + padding[0] * 2, shape[2] + padding[1] * 2, shape[3])\n    is_depthwise = shape[3] == channels == groups\n    weight_format = \"HWOI\" if is_depthwise else \"HWIO\"\n    if weight_format == \"HWIO\":\n        weight_shape = (kernel_h, kernel_w, shape[3] // groups, channels)\n    else:\n        weight_shape = (kernel_h, kernel_w, channels, shape[3] // groups)\n    w = tvm.nd.array(np.random.uniform(-128, 127, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.nn.conv2d(\n        a,\n        weights,\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=weight_format,\n        dilation=dilation,\n        strides=strides,\n        padding=padding,\n        groups=groups,\n        channels=channels,\n        out_dtype=dtype,\n    )\n    params = {\"w\": w}\n    if has_bias:\n        bias_shape = weight_shape[2] if is_depthwise else weight_shape[3]\n        b = tvm.nd.array(np.random.uniform(-128, 127, bias_shape).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.nn.bias_add(out, biasc, axis=3)\n        params[\"b\"] = b\n    if has_activation:\n        out = relay.nn.relu(out)\n    return out, params\n\n\ndef _get_qnn_params(input_zp, input_sc, kernel_zp, kernel_sc, kernel_h, kernel_w, channels):\n    \"\"\"Get output qnn parameters given input and kernel parameters.\"\"\"\n    input_max = input_sc * (255 - input_zp)\n    input_min = -input_sc * input_zp\n    kernel_max = kernel_sc * (255 - kernel_zp)\n    kernel_min = -kernel_sc * kernel_zp\n    output_limits = [\n        kernel_max * kernel_h * kernel_w * channels * input_max,\n        kernel_min * kernel_h * kernel_w * channels * input_max,\n        kernel_min * kernel_h * kernel_w * channels * input_min,\n        kernel_max * kernel_h * kernel_w * channels * input_min,\n    ]\n    output_max = max(output_limits)\n    output_min = min(output_limits)\n    output_sc = (output_max - output_min) / 255\n    output_zp = -int(output_min / output_sc)\n    return output_zp, output_sc\n\n\ndef _get_qnn_model(\n    shape,\n    kernel_h,\n    kernel_w,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    channels,\n    input_zp,\n    input_sc,\n    kernel_zp,\n    kernel_sc,\n    output_zp,\n    output_sc,\n    var_names,\n    has_bias=False,\n    has_activation=False,\n    has_pad=False,\n):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    if has_pad:\n        p = ((0, 0), (padding[0], padding[0]), (padding[1], padding[1]), (0, 0))\n        a = relay.nn.pad(a, pad_width=p, pad_value=input_zp, pad_mode=\"constant\")\n        padding = (0, 0, 0, 0)\n    else:\n        if len(padding) == 2:\n            padding = (padding[0], padding[1], padding[0], padding[1])\n        shape = (shape[0], shape[1] + padding[0] * 2, shape[2] + padding[1] * 2, shape[3])\n    is_depthwise = shape[3] == channels == groups\n    weight_format = \"HWOI\" if is_depthwise else \"HWIO\"\n    if weight_format == \"HWIO\":\n        weight_shape = (kernel_h, kernel_w, shape[3] // groups, channels)\n    else:\n        weight_shape = (kernel_h, kernel_w, channels, shape[3] // groups)\n    w = tvm.nd.array(np.random.uniform(0, 255, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.qnn.op.conv2d(\n        a,\n        weights,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n        input_scale=relay.const(input_sc, \"float32\"),\n        kernel_scale=relay.const(kernel_sc, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=weight_format,\n        dilation=dilation,\n        strides=strides,\n        padding=padding,\n        groups=groups,\n        channels=channels,\n        out_dtype=\"int32\",\n    )\n    params = {\"w\": w}\n    if has_bias:\n        bias_shape = weight_shape[2] if is_depthwise else weight_shape[3]\n        b = tvm.nd.array(np.random.uniform(-128, 127, bias_shape).astype(\"int32\"))\n        biasc = relay.const(b, \"int32\")\n        out = relay.nn.bias_add(out, biasc, axis=3)\n        params[\"b\"] = b\n    if has_activation:\n        out = relay.nn.relu(out)\n    req = relay.qnn.op.requantize(\n        out,\n        relay.const(input_sc * kernel_sc, \"float32\"),  # input scale\n        relay.const(0, \"int32\"),  # input zero point\n        relay.const(output_sc, \"float32\"),  # output scale\n        relay.const(output_zp, \"int32\"),  # output zero point\n        out_dtype=\"uint8\",\n    )\n    return req, params\n\n\ndef _get_expected_codegen(\n    shape,\n    kernel_h,\n    kernel_w,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    channels,\n    has_bias=False,\n    has_activation=False,\n):\n    if len(padding) == 2:\n        padding = (padding[0], padding[1], padding[0], padding[1])\n    output_height = ((shape[1] - kernel_h + padding[0] + padding[2]) / strides[0]) + 1\n    output_width = ((shape[2] - kernel_w + padding[1] + padding[3]) / strides[1]) + 1\n    output_shape = (1, int(output_height), int(output_width), channels)\n    out_dtype = \"int32\" if dtype == \"uint8\" else \"float32\"\n    is_depthwise = shape[3] == channels == groups\n    weight_format = \"IHWO\" if is_depthwise else \"OHWI\"\n    if weight_format == \"IHWO\":\n        weight_shape = (shape[3] // groups, kernel_h, kernel_w, channels)\n    else:\n        weight_shape = (channels, kernel_h, kernel_w, shape[3] // groups)\n    if is_depthwise:\n        name = \"nn.depthwise_conv2d\"\n    else:\n        name = \"nn.conv2d\"\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": name,\n        \"inputs\": [],\n        \"attrs\": {\n            \"groups\": [[str(groups)]],\n            \"num_outputs\": \"1\",\n            \"data_layout\": [[\"NHWC\"]],\n            \"kernel_layout\": [[weight_format]],\n            \"channels\": [[str(channels)]],\n            \"dilation\": [[str(dilation[0]), str(dilation[1])]],\n            \"out_layout\": [[\"\"]],\n            \"out_dtype\": [[out_dtype]],\n            \"kernel_size\": [[str(kernel_h), str(kernel_w)]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"padding\": [[str(p) for p in padding]],\n            \"strides\": [[str(s) for s in strides]],\n        },\n    }\n\n    if has_activation:\n        node[\"attrs\"][\"activation_type\"] = [[\"relu\"]]\n\n    inputs = [\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[str(dtype)]]}},\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\"shape\": [[list(weight_shape)]], \"dtype\": [[str(dtype)]]},\n        },\n    ]\n\n    # qnn.conv2d params, input and kernel\n    if dtype == \"uint8\":\n        node[\"name\"] = \"qnn.\" + node[\"name\"].split(\".\")[1]\n        for param_dtype in [\"int32\", \"float32\"]:\n            for _ in range(2):\n                inputs.append(\n                    {\n                        \"op\": \"const\",\n                        \"name\": \"\",\n                        \"attrs\": {\"shape\": [[[]]], \"dtype\": [[param_dtype]]},\n                    }\n                )\n\n    if has_bias:\n        bias_dtype = \"int32\" if dtype == \"uint8\" else \"float32\"\n        inputs.append(\n            {\n                \"op\": \"const\",\n                \"name\": \"\",\n                \"attrs\": {\n                    \"shape\": [[[1, 1, 1, weight_shape[3] if is_depthwise else weight_shape[0]]]],\n                    \"dtype\": [[bias_dtype]],\n                },\n            }\n        )\n\n    # qnn.conv2d params, output\n    if dtype == \"uint8\":\n        for param_dtype in [\"float32\", \"int32\"]:\n            inputs.append(\n                {\"op\": \"const\", \"name\": \"\", \"attrs\": {\"shape\": [[[]]], \"dtype\": [[param_dtype]]}}\n            )\n\n    input_idx = 0\n    for _ in range(len(inputs)):\n        node[\"inputs\"].append([input_idx, 0, 0])\n        input_idx += 1\n    node[\"attrs\"][\"num_inputs\"] = str(len(inputs))\n    inputs.append(node)\n    return inputs\n\n\ndef test_conv2d():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    dtype = \"float32\"\n    trials = [\n        # Normal convolution\n        [2, 2, (1, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, False, False), False],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (12, 15, 16), (False, False, True), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, True, False), False],\n        [3, 3, (1, 1), (1, 1), (1, 1), 16, (12, 15, 16), (False, False, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [1, 3, (1, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, True), False],\n        [2, 2, (2, 2), (1, 1), (1, 1), 4, (20, 20, 20), (False, True, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, False), False],\n        [3, 3, (1, 1), (2, 2), (1, 1), 16, (10, 10, 14), (False, True, True), False],\n        # Depth-wise convolution\n        [3, 3, (1, 1), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, True), True],\n        [5, 5, (2, 2), (1, 1), (1, 1), 20, (20, 20, 20), (False, True, False), True],\n        [3, 3, (2, 2), (2, 2), (1, 1), 14, (10, 10, 14), (True, False, False), True],\n        [5, 5, (0, 0), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, False), True],\n        [3, 3, (1, 1), (2, 2), (1, 1), 14, (10, 10, 14), (False, True, True), True],\n    ]\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        shape,\n        composite,\n        is_depthwise,\n    ) in trials:\n        shape = (1, *shape)\n        if is_depthwise:\n            groups = shape[3]\n        else:\n            groups = 1\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(-128, 127, shape).astype(dtype)),\n        }\n\n        func, params = _get_model(\n            shape,\n            kernel_h,\n            kernel_w,\n            pad,\n            stride,\n            dilation,\n            groups,\n            dtype,\n            out_channels,\n            iter(inputs),\n            has_pad=composite[0],\n            has_bias=composite[1],\n            has_activation=composite[2],\n        )\n        for acl in [False, True]:\n            outputs.append(build_and_run(func, inputs, 1, params, device, enable_acl=acl)[0])\n\n        config = {\n            \"shape\": shape,\n            \"groups\": groups,\n            \"kernel size\": (kernel_h, kernel_w),\n            \"padding\": pad,\n            \"stride\": stride,\n            \"dilation\": dilation,\n            \"out channels\": out_channels,\n            \"composite operators (pad, bias, activation)\": composite,\n        }\n        verify(outputs, atol=0.002, rtol=0.01, config=config)\n\n\ndef test_codegen_conv2d():\n    if skip_codegen_test():\n        return\n\n    dtype = \"float32\"\n    trials = [\n        # Normal convolution\n        [2, 2, (1, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, False, False), False],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (12, 15, 16), (False, False, True), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, True, False), False],\n        [3, 3, (1, 1), (1, 1), (1, 1), 16, (12, 15, 16), (False, False, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [1, 3, (1, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, True), False],\n        [2, 2, (2, 2), (1, 1), (1, 1), 4, (20, 20, 20), (False, True, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, False), False],\n        [3, 3, (1, 1), (2, 2), (1, 1), 16, (10, 10, 14), (False, True, True), False],\n        # Depth-wise convolution\n        [3, 3, (1, 1), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, True), True],\n        [5, 5, (2, 2), (1, 1), (1, 1), 20, (20, 20, 20), (False, True, False), True],\n        [3, 3, (2, 2), (2, 2), (1, 1), 14, (10, 10, 14), (True, False, False), True],\n        [5, 5, (0, 0), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, False), True],\n        [3, 3, (1, 1), (2, 2), (1, 1), 14, (10, 10, 14), (False, True, True), True],\n    ]\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        shape,\n        composite,\n        is_depthwise,\n    ) in trials:\n        shape = (1, *shape)\n        if is_depthwise:\n            groups = shape[3]\n        else:\n            groups = 1\n        inputs = {\"a\"}\n\n        args = (shape, kernel_h, kernel_w, pad, stride, dilation, groups, dtype, out_channels)\n\n        func, params = _get_model(\n            *args,\n            var_names=iter(inputs),\n            has_pad=composite[0],\n            has_bias=composite[1],\n            has_activation=composite[2],\n        )\n        exp_codegen = _get_expected_codegen(\n            *args, has_bias=composite[1], has_activation=composite[2]\n        )\n        verify_codegen(func, exp_codegen, 1)\n\n\ndef test_qnn_conv2d():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n    trials = [\n        # Normal convolution\n        [2, 2, (1, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, False, False), False],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (12, 15, 16), (False, False, True), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, True, False), False],\n        [3, 3, (1, 1), (1, 1), (1, 1), 16, (12, 15, 16), (False, False, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [1, 3, (1, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, True), False],\n        [2, 2, (2, 2), (1, 1), (1, 1), 4, (20, 20, 20), (False, True, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, False), False],\n        [3, 3, (1, 1), (2, 2), (1, 1), 16, (10, 10, 14), (False, True, True), False],\n        # Depth-wise convolution\n        [3, 3, (1, 1), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, True), True],\n        [5, 5, (2, 2), (1, 1), (1, 1), 20, (20, 20, 20), (False, True, False), True],\n        [3, 3, (2, 2), (2, 2), (1, 1), 14, (10, 10, 14), (True, False, False), True],\n        [5, 5, (0, 0), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, False), True],\n        [3, 3, (1, 1), (2, 2), (1, 1), 14, (10, 10, 14), (False, True, True), True],\n    ]\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        shape,\n        composite,\n        is_depthwise,\n    ) in trials:\n        shape = (1, *shape)\n        if is_depthwise:\n            groups = shape[3]\n        else:\n            groups = 1\n        outputs = []\n        inputs = {\"a\": tvm.nd.array(np.random.uniform(0, 255, shape).astype(dtype))}\n\n        input_zp = 100\n        input_sc = 0.5\n        kernel_zp = 25\n        kernel_sc = 0.03\n        output_zp, output_sc = _get_qnn_params(\n            input_zp, input_sc, kernel_zp, kernel_sc, kernel_h, kernel_w, shape[3]\n        )\n\n        func, params = _get_qnn_model(\n            shape,\n            kernel_h,\n            kernel_w,\n            pad,\n            stride,\n            dilation,\n            groups,\n            dtype,\n            out_channels,\n            input_zp,\n            input_sc,\n            kernel_zp,\n            kernel_sc,\n            output_zp,\n            output_sc,\n            iter(inputs),\n            has_pad=composite[0],\n            has_bias=composite[1],\n            has_activation=composite[2],\n        )\n        for acl in [False, True]:\n            outputs.append(build_and_run(func, inputs, 1, params, device, enable_acl=acl)[0])\n\n        config = {\n            \"shape\": shape,\n            \"groups\": groups,\n            \"kernel size\": (kernel_h, kernel_w),\n            \"padding\": pad,\n            \"stride\": stride,\n            \"dilation\": dilation,\n            \"out channels\": out_channels,\n            \"composite operators (pad, bias, activation)\": composite,\n            \"input scale\": input_sc,\n            \"input zero point\": input_zp,\n            \"kernel scale\": kernel_sc,\n            \"kernel zero point\": kernel_zp,\n            \"output scale\": output_sc,\n            \"output zero point\": output_zp,\n        }\n\n        atol = 2 if is_depthwise else 1\n        verify(outputs, atol=atol, rtol=0, config=config, verify_saturation=True)\n\n\ndef test_codegen_qnn_conv2d():\n    if skip_codegen_test():\n        return\n\n    dtype = \"uint8\"\n    trials = [\n        # Normal convolution\n        [2, 2, (1, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, False, False), False],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (12, 15, 16), (False, False, True), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (10, 10, 14), (False, True, False), False],\n        [3, 3, (1, 1), (1, 1), (1, 1), 16, (12, 15, 16), (False, False, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [1, 3, (1, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, True), False],\n        [2, 2, (2, 2), (1, 1), (1, 1), 4, (20, 20, 20), (False, True, False), False],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (10, 10, 14), (True, False, False), False],\n        [3, 3, (2, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, False), False],\n        [3, 3, (1, 1), (2, 2), (1, 1), 16, (10, 10, 14), (False, True, True), False],\n        # Depth-wise convolution\n        [3, 3, (1, 1), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, True), True],\n        [5, 5, (2, 2), (1, 1), (1, 1), 20, (20, 20, 20), (False, True, False), True],\n        [3, 3, (2, 2), (2, 2), (1, 1), 14, (10, 10, 14), (True, False, False), True],\n        [5, 5, (0, 0), (1, 1), (1, 1), 20, (20, 20, 20), (False, False, False), True],\n        [3, 3, (1, 1), (2, 2), (1, 1), 14, (10, 10, 14), (False, True, True), True],\n    ]\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        shape,\n        composite,\n        is_depthwise,\n    ) in trials:\n        shape = (1, *shape)\n        if is_depthwise:\n            groups = shape[3]\n        else:\n            groups = 1\n        inputs = {\"a\"}\n\n        input_zp = 100\n        input_sc = 0.5\n        kernel_zp = 25\n        kernel_sc = 0.03\n        output_zp, output_sc = _get_qnn_params(\n            input_zp, input_sc, kernel_zp, kernel_sc, kernel_h, kernel_w, shape[3]\n        )\n\n        args = (shape, kernel_h, kernel_w, pad, stride, dilation, groups, dtype, out_channels)\n\n        func, params = _get_qnn_model(\n            *args,\n            input_zp=input_zp,\n            input_sc=input_sc,\n            kernel_zp=kernel_zp,\n            kernel_sc=kernel_sc,\n            output_zp=output_zp,\n            output_sc=output_sc,\n            var_names=iter(inputs),\n            has_pad=composite[0],\n            has_bias=composite[1],\n            has_activation=composite[2],\n        )\n        exp_codegen = _get_expected_codegen(\n            *args, has_bias=composite[1], has_activation=composite[2]\n        )\n        verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n    test_qnn_conv2d()\n    test_codegen_conv2d()\n    test_codegen_qnn_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration dense tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\nfrom test_arm_compute_lib.infrastructure import (\n    Device,\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\n\n\ndef _get_model(shape, weight_shape, units, dtype, var_names, has_bias=False):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    w = tvm.nd.array(np.random.uniform(-128, 127, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.nn.dense(a, weights, units=units, out_dtype=dtype)\n    params = {\"w\": w}\n    if has_bias:\n        b = tvm.nd.array(np.random.randint(-128, 127, weight_shape[0]).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.nn.bias_add(out, biasc)\n        params[\"b\"] = b\n    return out, params\n\n\ndef _get_qnn_params(input_zp, input_sc, kernel_zp, kernel_sc, kernel_h, kernel_w):\n    \"\"\"Get output qnn parameters given input and kernel parameters.\"\"\"\n    input_max = input_sc * (255 - input_zp)\n    input_min = -input_sc * input_zp\n    kernel_max = kernel_sc * (255 - kernel_zp)\n    kernel_min = -kernel_sc * kernel_zp\n    output_limits = [\n        kernel_max * kernel_h * kernel_w * input_max,\n        kernel_min * kernel_h * kernel_w * input_max,\n        kernel_min * kernel_h * kernel_w * input_min,\n        kernel_max * kernel_h * kernel_w * input_min,\n    ]\n    output_max = max(output_limits)\n    output_min = min(output_limits)\n    output_sc = (output_max - output_min) / 255\n    output_zp = -int(output_min / output_sc)\n    return output_zp, output_sc\n\n\ndef _get_qnn_model(\n    shape,\n    weight_shape,\n    units,\n    dtype,\n    input_zp,\n    input_sc,\n    kernel_zp,\n    kernel_sc,\n    output_zp,\n    output_sc,\n    var_names,\n    has_bias=False,\n):\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    w = tvm.nd.array(np.random.uniform(-128, 127, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.qnn.op.dense(\n        a,\n        weights,\n        units=units,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n        input_scale=relay.const(input_sc, \"float32\"),\n        kernel_scale=relay.const(kernel_sc, \"float32\"),\n        out_dtype=\"int32\",\n    )\n    params = {\"w\": w}\n    if has_bias:\n        b = tvm.nd.array(np.random.randint(0, 255, weight_shape[0]).astype(\"int32\"))\n        biasc = relay.const(b, \"int32\")\n        out = relay.nn.bias_add(out, biasc)\n        params[\"b\"] = b\n    out = relay.qnn.op.requantize(\n        out,\n        relay.const(input_sc * kernel_sc, \"float32\"),  # input scale\n        relay.const(0, \"int32\"),  # input zero point\n        relay.const(output_sc, \"float32\"),  # output scale\n        relay.const(output_zp, \"int32\"),  # output zero point\n        out_dtype=\"uint8\",\n    )\n    return out, params\n\n\ndef _get_expected_codegen(shape, weight_shape, units, dtype, has_bias=False):\n    output_shape = (shape[0], units)\n    out_dtype = \"int32\" if dtype == \"uint8\" else \"float32\"\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": \"nn.dense\",\n        \"inputs\": [],\n        \"attrs\": {\n            \"num_outputs\": \"1\",\n            \"out_dtype\": [[out_dtype]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"units\": [[str(units)]],\n        },\n    }\n\n    inputs = [\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[str(dtype)]]}},\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\"shape\": [[list(weight_shape)]], \"dtype\": [[str(dtype)]]},\n        },\n    ]\n\n    # qnn.dense params, input and kernel\n    if dtype == \"uint8\":\n        node[\"name\"] = \"qnn.dense\"\n        for param_dtype in [\"int32\", \"float32\"]:\n            for _ in range(2):\n                inputs.append(\n                    {\n                        \"op\": \"const\",\n                        \"name\": \"\",\n                        \"attrs\": {\"shape\": [[[]]], \"dtype\": [[param_dtype]]},\n                    }\n                )\n\n    if has_bias:\n        bias_dtype = \"int32\" if dtype == \"uint8\" else \"float32\"\n        bias_shape = (\n            [1, weight_shape[0]]\n            if dtype == \"float32\" and weight_shape[0] != 1\n            else [weight_shape[0]]\n        )\n        inputs.append(\n            {\n                \"op\": \"const\",\n                \"name\": \"\",\n                \"attrs\": {\"shape\": [[bias_shape]], \"dtype\": [[bias_dtype]]},\n            }\n        )\n\n    # qnn.dense params, output\n    if dtype == \"uint8\":\n        for param_dtype in [\"float32\", \"int32\"]:\n            inputs.append(\n                {\"op\": \"const\", \"name\": \"\", \"attrs\": {\"shape\": [[[]]], \"dtype\": [[param_dtype]]}}\n            )\n\n    input_idx = 0\n    for _ in range(len(inputs)):\n        node[\"inputs\"].append([input_idx, 0, 0])\n        input_idx += 1\n    node[\"attrs\"][\"num_inputs\"] = str(len(inputs))\n    inputs.append(node)\n    return inputs\n\n\ndef test_dense():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n    dtype = \"float32\"\n    trials = [\n        [(1, 128), (16, 128), 16, True],\n        [(1, 128), (16, 128), 16, False],\n        [(32, 32), (32, 32), 32, True],\n        [(32, 32), (32, 32), 32, False],\n        [(1, 64), (1, 64), 1, True],\n        [(1, 64), (1, 64), 1, False],\n        [(11, 2), (2, 2), 2, True],\n        [(11, 2), (2, 2), 2, False],\n    ]\n    for shape, weight_shape, units, composite in trials:\n        outputs = []\n        inputs = {\"a\": tvm.nd.array(np.random.uniform(-128, 127, shape).astype(dtype))}\n        func, params = _get_model(\n            shape, weight_shape, units, dtype, var_names=iter(inputs), has_bias=composite\n        )\n        for acl in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func,\n                    inputs,\n                    1,\n                    params,\n                    device,\n                    enable_acl=acl,\n                )[0]\n            )\n        config = {\n            \"shape\": shape,\n            \"weight_shape\": weight_shape,\n            \"units\": units,\n            \"dtype\": dtype,\n            \"composite operators (bias)\": composite,\n        }\n        verify(outputs, atol=0.001, rtol=0.01, config=config)\n\n\ndef test_codegen_dense():\n    if skip_codegen_test():\n        return\n\n    np.random.seed(0)\n    dtype = \"float32\"\n    trials = [\n        [(1, 128), (16, 128), 16, True],\n        [(1, 128), (16, 128), 16, False],\n        [(32, 32), (32, 32), 32, True],\n        [(32, 32), (32, 32), 32, False],\n        [(1, 64), (1, 64), 1, True],\n        [(1, 64), (1, 64), 1, False],\n        [(11, 2), (2, 2), 2, True],\n        [(11, 2), (2, 2), 2, False],\n    ]\n    for shape, weight_shape, units, composite in trials:\n        inputs = {\"a\"}\n\n        args = (shape, weight_shape, units, dtype)\n\n        func, params = _get_model(*args, var_names=iter(inputs), has_bias=composite)\n        exp_codegen = _get_expected_codegen(*args, has_bias=composite)\n        verify_codegen(func, exp_codegen)\n\n\ndef test_qnn_dense():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n    trials = [\n        [(1, 2), (2, 2), 2, True],\n        [(1, 2), (2, 2), 2, False],\n        [(4, 4), (4, 4), 4, True],\n        [(4, 4), (4, 4), 4, False],\n        [(16, 16), (4, 16), 4, True],\n        [(16, 16), (4, 16), 4, False],\n        [(1, 128), (16, 128), 16, True],\n        [(1, 128), (16, 128), 16, False],\n        [(32, 32), (32, 32), 32, True],\n        [(32, 32), (32, 32), 32, False],\n        [(1, 64), (1, 64), 1, True],\n        [(1, 64), (1, 64), 1, False],\n    ]\n    for shape, weight_shape, units, composite in trials:\n        outputs = []\n        inputs = {\"a\": tvm.nd.array(np.random.uniform(0, 255, shape).astype(dtype))}\n        input_zp = 100\n        input_sc = 0.5\n        kernel_zp = 50\n        kernel_sc = 0.03\n        output_zp, output_sc = _get_qnn_params(\n            input_zp, input_sc, kernel_zp, kernel_sc, weight_shape[0], weight_shape[1]\n        )\n\n        func, params = _get_qnn_model(\n            shape,\n            weight_shape,\n            units,\n            dtype,\n            input_zp,\n            input_sc,\n            kernel_zp,\n            kernel_sc,\n            output_zp,\n            output_sc,\n            var_names=iter(inputs),\n            has_bias=composite,\n        )\n\n        for acl in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func,\n                    inputs,\n                    1,\n                    params,\n                    device,\n                    enable_acl=acl,\n                )[0]\n            )\n\n        config = {\n            \"shape\": shape,\n            \"weight_shape\": weight_shape,\n            \"units\": units,\n            \"dtype\": dtype,\n            \"composite operators (bias)\": composite,\n            \"input scale\": input_sc,\n            \"input zero point\": input_zp,\n            \"kernel scale\": kernel_sc,\n            \"kernel zero point\": kernel_zp,\n            \"output scale\": output_sc,\n            \"output zero point\": output_zp,\n        }\n        verify(outputs, atol=1, rtol=0, config=config, verify_saturation=True)\n\n\ndef test_codegen_qnn_dense():\n    if skip_codegen_test():\n        return\n\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n    trials = [\n        [(1, 2), (2, 2), 2, True],\n        [(1, 2), (2, 2), 2, False],\n        [(4, 4), (4, 4), 4, True],\n        [(4, 4), (4, 4), 4, False],\n        [(16, 16), (4, 16), 4, True],\n        [(16, 16), (4, 16), 4, False],\n        [(1, 128), (16, 128), 16, True],\n        [(1, 128), (16, 128), 16, False],\n        [(32, 32), (32, 32), 32, True],\n        [(32, 32), (32, 32), 32, False],\n        [(1, 64), (1, 64), 1, True],\n        [(1, 64), (1, 64), 1, False],\n    ]\n    for shape, weight_shape, units, composite in trials:\n        inputs = {\"a\"}\n        args = (shape, weight_shape, units, dtype)\n\n        input_zp = 100\n        input_sc = 0.5\n        kernel_zp = 25\n        kernel_sc = 0.03\n        output_zp, output_sc = _get_qnn_params(\n            input_zp, input_sc, kernel_zp, kernel_sc, weight_shape[0], weight_shape[1]\n        )\n\n        func, params = _get_qnn_model(\n            *args,\n            var_names=iter(inputs),\n            input_zp=input_zp,\n            input_sc=input_sc,\n            kernel_zp=kernel_zp,\n            kernel_sc=kernel_sc,\n            output_zp=output_zp,\n            output_sc=output_sc,\n            has_bias=composite,\n        )\n        exp_codegen = _get_expected_codegen(*args, has_bias=composite)\n        verify_codegen(func, exp_codegen)\n\n\nif __name__ == \"__main__\":\n    test_dense()\n    test_qnn_dense()\n    test_codegen_dense()\n    test_codegen_qnn_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_maximum.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration reshape tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\n\nfrom .infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom .infrastructure import Device\n\n\ndef _get_model(input_shape, dtype, var_names):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    a = relay.var(next(var_names), shape=input_shape, dtype=dtype)\n    b = relay.var(next(var_names), shape=input_shape, dtype=dtype)\n    max = relay.maximum(a, b)\n    return max\n\n\ndef _get_expected_codegen(shape, dtype):\n    node = {\n        \"op\": \"kernel\",\n        \"name\": \"maximum\",\n        \"inputs\": [[0, 0, 0], [1, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n            \"shape\": [[list(shape)]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    inputs = [\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}},\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}},\n    ]\n    inputs.append(node)\n    return inputs\n\n\ndef test_maximum():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    for dtype, low, high, atol, rtol in [\n        (\"float32\", -127, 128, 0.001, 0.001),\n        (\"float32\", -1, 1, 0.001, 0.001),\n    ]:\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(low, high, (100, 100)).astype(dtype)),\n            \"b\": tvm.nd.array(np.random.uniform(low, high, (100, 100)).astype(dtype)),\n        }\n        outputs = []\n        func = _get_model(inputs[\"a\"].shape, dtype, iter(inputs))\n\n        for acl in [False, True]:\n            outputs.append(build_and_run(func, inputs, 1, None, device, enable_acl=acl)[0])\n\n        verify(outputs, atol=1e-7, rtol=1e-7)\n\n\ndef test_codegen_maximum():\n    if skip_codegen_test():\n        return\n\n    shape = (100, 100)\n    inputs = {\"a\", \"b\"}\n    for dtype in [\"float32\"]:\n        args = (shape, dtype)\n        func = _get_model(*args, iter(inputs))\n        exp_codegen = _get_expected_codegen(*args)\n        verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_maximum()\n    test_codegen_maximum()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_network.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library network tests.\"\"\"\n\nfrom distutils.version import LooseVersion\n\nimport numpy as np\nimport pytest\nfrom tvm import relay\n\nfrom test_arm_compute_lib.infrastructure import Device, skip_runtime_test, build_and_run, verify\n\n\ndef _build_and_run_network(mod, params, inputs, device, tvm_ops, acl_partitions, atol, rtol):\n    \"\"\"Helper function to build and run a network.\"\"\"\n    data = {}\n    np.random.seed(0)\n\n    for name, (shape, dtype) in inputs.items():\n        if dtype == \"uint8\":\n            low, high = 0, 255\n        else:\n            low, high = -127, 128\n        data[name] = np.random.uniform(low, high, shape).astype(dtype)\n\n    outputs = []\n    for acl in [False, True]:\n        outputs.append(\n            build_and_run(\n                mod,\n                data,\n                1,\n                params,\n                device,\n                enable_acl=acl,\n                tvm_ops=tvm_ops,\n                acl_partitions=acl_partitions,\n            )[0]\n        )\n    verify(outputs, atol=atol, rtol=rtol, verify_saturation=False)\n\n\ndef _get_tflite_model(tflite_model_path, inputs_dict):\n    \"\"\"Convert TFlite graph to relay.\"\"\"\n    try:\n        import tflite.Model\n    except ImportError:\n        pytest.skip(\"Missing Tflite support\")\n\n    with open(tflite_model_path, \"rb\") as f:\n        tflite_model_buffer = f.read()\n\n    try:\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buffer, 0)\n    except AttributeError:\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buffer, 0)\n    shape_dict = {}\n    dtype_dict = {}\n    for input in inputs_dict:\n        input_shape, input_dtype = inputs_dict[input]\n        shape_dict[input] = input_shape\n        dtype_dict[input] = input_dtype\n\n    return relay.frontend.from_tflite(tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict)\n\n\ndef _get_keras_model(keras_model, inputs_dict):\n    \"\"\"Convert Keras graph to relay.\"\"\"\n    inputs = {}\n    for name, (shape, _) in inputs_dict.items():\n        inputs[keras_model.input_names[0]] = shape\n    return relay.frontend.from_keras(keras_model, inputs, layout=\"NHWC\")\n\n\ndef test_vgg16():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n\n    def get_model():\n        try:\n            from keras.applications import VGG16\n        except ImportError:\n            pytest.skip(\"Missing Keras Package\")\n\n        vgg16 = VGG16(include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000)\n        inputs = {vgg16.input_names[0]: ((1, 224, 224, 3), \"float32\")}\n        mod, params = _get_keras_model(vgg16, inputs)\n        return mod, params, inputs\n\n    _build_and_run_network(\n        *get_model(),\n        device=device,\n        tvm_ops=4,\n        acl_partitions=21,\n        atol=0.002,\n        rtol=0.01,\n    )\n\n\ndef test_mobilenet():\n    keras = pytest.importorskip(\"keras\")\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n\n    def get_model():\n        try:\n            from keras.applications import MobileNet\n        except ImportError:\n            pytest.skip(\"Missing keras module\")\n\n        mobilenet = MobileNet(\n            include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000\n        )\n        inputs = {mobilenet.input_names[0]: ((1, 224, 224, 3), \"float32\")}\n        mod, params = _get_keras_model(mobilenet, inputs)\n        return mod, params, inputs\n\n    if keras.__version__ < LooseVersion(\"2.9\"):\n        # This can be removed after we migrate to TF/Keras >= 2.9\n        expected_tvm_ops = 56\n        expected_acl_partitions = 31\n    else:\n        # In Keras >= 2.7, one reshape operator was removed\n        # from the MobileNet model, so it impacted this test\n        # which now needs to be reduce in by 1\n        # The change in Keras is `b6abfaed1326e3c`\n        expected_tvm_ops = 55\n        expected_acl_partitions = 30\n\n    _build_and_run_network(\n        *get_model(),\n        device=device,\n        tvm_ops=expected_tvm_ops,\n        acl_partitions=expected_acl_partitions,\n        atol=0.002,\n        rtol=0.01,\n    )\n\n\ndef test_quantized_mobilenet():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    try:\n        import tvm.relay.testing.tf as tf_testing\n    except ImportError:\n        pytest.skip(\"Missing Tflite support\")\n\n    device = Device()\n\n    def get_model():\n        model_path = tf_testing.get_workload_official(\n            \"https://storage.googleapis.com/download.tensorflow.org/\"\n            \"models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\",\n            \"mobilenet_v1_1.0_224_quant.tflite\",\n        )\n        inputs = {\"input\": ((1, 224, 224, 3), \"uint8\")}\n        mod, params = _get_tflite_model(model_path, inputs_dict=inputs)\n        return mod, params, inputs\n\n    _build_and_run_network(\n        *get_model(),\n        device=device,\n        tvm_ops=3,\n        acl_partitions=30,\n        atol=10,\n        rtol=0,\n    )\n\n\ndef test_squeezenet():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    try:\n        import tvm.relay.testing.tf as tf_testing\n    except ImportError:\n        pytest.skip(\"Missing TF Support\")\n\n    device = Device()\n\n    def get_model():\n        model_path = tf_testing.get_workload_official(\n            \"https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/upload_20180427/squeezenet_2018_04_27.tgz\",\n            \"squeezenet.tflite\",\n        )\n        inputs = {\"Placeholder\": ((1, 224, 224, 3), \"float32\")}\n        mod, params = _get_tflite_model(model_path, inputs_dict=inputs)\n        return mod, params, inputs\n\n    _build_and_run_network(\n        *get_model(),\n        device=device,\n        tvm_ops=9,\n        acl_partitions=31,\n        atol=8,\n        rtol=0,\n    )\n\n\nif __name__ == \"__main__\":\n    test_vgg16()\n    test_mobilenet()\n    test_quantized_mobilenet()\n    test_squeezenet()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration pooling tests.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import relay, testing\n\nfrom test_arm_compute_lib.infrastructure import (\n    Device,\n    build_and_run,\n    skip_codegen_test,\n    skip_runtime_test,\n    verify,\n    verify_codegen,\n)\n\n\ndef _calculate_output_shape(shape, sizes, padding, strides, dilation):\n    \"\"\"Calculate pooling output shape.\"\"\"\n    height_receptive_field = (sizes[0] - 1) * dilation[0] + 1\n    width_receptive_field = (sizes[1] - 1) * dilation[1] + 1\n    output_height = ((shape[1] - height_receptive_field + padding[0] + padding[2]) / strides[0]) + 1\n    output_width = ((shape[2] - width_receptive_field + padding[1] + padding[3]) / strides[1]) + 1\n    return 1, int(output_height), int(output_width), shape[3]\n\n\ndef _get_pooling_model(\n    shape, dtype, typef, sizes, strides, dilation, padding, ceil_mode, count_include_pad, var_names\n):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    if len(padding) == 2:\n        padding = (padding[0], padding[1], padding[0], padding[1])\n    out = relay.var(next(var_names), shape=shape, dtype=dtype)\n\n    if typef == \"nn.max_pool2d\":\n        out = relay.nn.max_pool2d(\n            out,\n            pool_size=sizes,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            ceil_mode=ceil_mode,\n            layout=\"NHWC\",\n        )\n    elif typef == \"nn.avg_pool2d\":\n        if dtype == \"uint8\":\n            out = relay.cast(out, \"int32\")\n        out = relay.nn.avg_pool2d(\n            out,\n            pool_size=sizes,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n            layout=\"NHWC\",\n        )\n        if dtype == \"uint8\":\n            out = relay.cast(out, \"uint8\")\n    elif typef == \"nn.l2_pool2d\":\n        out = relay.power(out, relay.const(2.0))\n        out = relay.nn.avg_pool2d(\n            out,\n            pool_size=sizes,\n            strides=strides,\n            padding=padding,\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n            layout=\"NHWC\",\n        )\n        out = relay.sqrt(out)\n    else:\n        raise ValueError(\"Function not supported\")\n\n    return out\n\n\ndef _get_global_pooling_model(shape, dtype, typef, var_names):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    out = relay.var(next(var_names), shape=shape, dtype=dtype)\n\n    if typef == \"nn.global_max_pool2d\":\n        out = relay.nn.global_max_pool2d(out, layout=\"NHWC\")\n    elif typef == \"nn.global_avg_pool2d\":\n        if dtype == \"uint8\":\n            out = relay.cast(out, \"int32\")\n        out = relay.nn.global_avg_pool2d(out, layout=\"NHWC\")\n        if dtype == \"uint8\":\n            out = relay.cast(out, \"uint8\")\n    else:\n        raise ValueError(\"Function not supported\")\n\n    return out\n\n\ndef _get_expected_pooling_codegen(\n    shape, dtype, typef, sizes, strides, dilation, padding, ceil_mode, count_include_pad\n):\n    if len(padding) == 2:\n        padding = (padding[0], padding[1], padding[0], padding[1])\n    output_shape = _calculate_output_shape(shape, sizes, padding, strides, dilation)\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": typef,\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n            \"layout\": [[\"NHWC\"]],\n            \"out_layout\": [[\"\"]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"padding\": [[str(p) for p in padding]],\n            \"strides\": [[str(s) for s in strides]],\n            \"dilation\": [[str(d) for d in dilation]],\n            \"pool_size\": [[str(s) for s in sizes]],\n            \"ceil_mode\": [[str(1 if ceil_mode else 0)]],\n        },\n    }\n\n    if typef == \"nn.avg_pool2d\" or typef == \"nn.l2_pool2d\":\n        node[\"attrs\"][\"count_include_pad\"] = [[\"1\" if count_include_pad else \"0\"]]\n\n    input = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    return [input, node]\n\n\ndef _get_expected_global_pooling_codegen(shape, dtype, typef):\n    node = {\n        \"op\": \"kernel\",\n        \"name\": typef,\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n            \"layout\": [[\"NHWC\"]],\n            \"out_layout\": [[\"\"]],\n            \"shape\": [[[1, 1, 1, shape[3]]]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    input = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    return [input, node]\n\n\ndef test_pooling():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    fp32_dtype = (\"float32\", -127, 128, 0.001, 0.001)\n    uint8_dtype = (\"uint8\", 0, 255, 1, 0)\n    # fmt: off\n    trials = [\n        [\"nn.max_pool2d\", fp32_dtype,  (3, 3), (2, 2), (1, 1), (0, 0), False, False, (27, 27, 512), (0, 1),],\n        [\"nn.max_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 0), False, True,  (16, 16, 16),  (0, 1),],\n        [\"nn.max_pool2d\", fp32_dtype,  (3, 3), (2, 2), (1, 1), (1, 1), True,  True,  (15, 15, 16),  (0, 1),],\n        [\"nn.max_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16),  (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (3, 3), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16),  (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (2, 2), (2, 2), (1, 1), (1, 1), True,  True,  (15, 15, 16),  (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (2, 2), (2, 2), (3, 2), (1, 1), True,  True,  (15, 15, 16),  (1, 0),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (1, 1), False, False, (16, 16, 16),  (0, 1),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 0), False, True,  (16, 16, 16),  (0, 1),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (3, 3), (2, 2), (3, 2), (0, 1), True,  False, (15, 15, 16),  (1, 0),],\n        # 20.05: \"exclude_padding equal false is not supported for AVG Pooling with padding on quantized types\"\n        # [\"nn.avg_pool2d\", uint8_dtype, (2, 2), (2, 2), (1, 1), False, True, (16, 16, 16)],\n        [\"nn.avg_pool2d\", uint8_dtype, (3, 3), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16),  (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 1), True,  False, (16, 16, 16),  (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (3, 3), (2, 2), (1, 1), (0, 0), False, False, (16, 16, 16),  (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (2, 2), (2, 2), (1, 1), (1, 1), False, True,  (15, 15, 16),  (0, 1),],\n    ]\n    # fmt: on\n    for (\n        typef,\n        (dtype, low, high, atol, rtol),\n        size,\n        stride,\n        dilation,\n        pad,\n        ceil_mode,\n        count_include_pad,\n        input_shape,\n        (tvm_ops, acl_partitions),\n    ) in trials:\n        shape = (1, *input_shape)\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(low, high, shape).astype(dtype)),\n        }\n\n        func = _get_pooling_model(\n            shape,\n            dtype,\n            typef,\n            size,\n            stride,\n            dilation,\n            pad,\n            ceil_mode,\n            count_include_pad,\n            iter(inputs),\n        )\n\n        config = {\n            \"size\": size,\n            \"stride\": stride,\n            \"shape\": shape,\n            \"pooling type\": typef,\n            \"dtype\": dtype,\n            \"padding\": pad,\n            \"dilation\": dilation,\n            \"ceil_mode\": ceil_mode,\n            \"count_include_pad\": count_include_pad,\n            \"inputs\": inputs,\n        }\n        verify_saturation = True if dtype == \"uint8\" else False\n        for acl in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func,\n                    inputs,\n                    1,\n                    None,\n                    device,\n                    enable_acl=acl,\n                    tvm_ops=tvm_ops,\n                    acl_partitions=acl_partitions,\n                    config=config,\n                )[0]\n            )\n\n        verify(outputs, atol=atol, rtol=rtol, config=config, verify_saturation=verify_saturation)\n\n\ndef test_global_pooling():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    fp32_dtype = (\"float32\", -127, 128, 0.001, 0.001)\n    uint8_dtype = (\"uint8\", 0, 255, 1, 0)\n\n    trials = [\n        [\"nn.global_max_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", fp32_dtype, (9, 9, 16)],\n        [\"nn.global_max_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", uint8_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", uint8_dtype, (9, 9, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (9, 9, 16)],\n        [\"nn.global_avg_pool2d\", uint8_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", uint8_dtype, (8, 8, 16)],\n    ]\n\n    for typef, (dtype, low, high, atol, rtol), input_shape in trials:\n        shape = (1, *input_shape)\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(low, high, shape).astype(dtype)),\n        }\n\n        func = _get_global_pooling_model(shape, dtype, typef, iter(inputs))\n        config = {\n            \"shape\": shape,\n            \"pooling type\": typef,\n            \"dtype\": dtype,\n        }\n        verify_saturation = True if dtype == \"uint8\" else False\n\n        for acl in [False, True]:\n            outputs.append(\n                build_and_run(func, inputs, 1, None, device, enable_acl=acl, config=config)[0]\n            )\n\n        verify(outputs, atol=atol, rtol=rtol, config=config, verify_saturation=verify_saturation)\n\n\ndef test_codegen_pooling():\n    if skip_codegen_test():\n        return\n\n    fp32_dtype = (\"float32\", -127, 128)\n    uint8_dtype = (\"uint8\", 0, 255)\n    # fmt: off\n    trials = [\n        [\"nn.max_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 0), False,  True, (16, 16, 16), (0, 1),],\n        [\"nn.max_pool2d\", fp32_dtype,  (3, 3), (2, 2), (1, 1), (1, 1),  True,  True, (15, 15, 16), (0, 1),],\n        [\"nn.max_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (3, 3), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (2, 2), (2, 2), (1, 1), (1, 1),  True,  True, (15, 15, 16), (0, 1),],\n        [\"nn.max_pool2d\", uint8_dtype, (2, 2), (2, 2), (3, 2), (1, 1),  True,  True, (15, 15, 16), (1, 0),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (1, 1), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (1, 1), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 0), False,  True, (16, 16, 16), (0, 1),],\n        [\"nn.avg_pool2d\", fp32_dtype,  (3, 3), (2, 2), (3, 2), (0, 1),  True, False, (15, 15, 16), (1, 0),],\n        [\"nn.avg_pool2d\", uint8_dtype, (2, 2), (2, 2), (1, 1), (1, 1), False,  True, (16, 16, 16), (0, 1),],\n        [\"nn.avg_pool2d\", uint8_dtype, (3, 3), (2, 2), (1, 1), (0, 1), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (2, 2), (2, 2), (1, 1), (0, 1),  True, False, (15, 15, 16), (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (3, 3), (2, 2), (1, 1), (0, 0), False, False, (16, 16, 16), (0, 1),],\n        [\"nn.l2_pool2d\",  fp32_dtype,  (2, 2), (2, 2), (1, 1), (1, 1), False,  True, (15, 15, 16), (0, 1),],\n    ]\n    # fmt: on\n    for (\n        typef,\n        (dtype, low, high),\n        size,\n        stride,\n        dilation,\n        pad,\n        ceil_mode,\n        count_include_pad,\n        input_shape,\n        (tvm_ops, acl_partitions),\n    ) in trials:\n        shape = (1, *input_shape)\n        inputs = {\"a\"}\n        args = (shape, dtype, typef, size, stride, dilation, pad, False, False)\n        func = _get_pooling_model(*args, iter(inputs))\n        exp_codegen = _get_expected_pooling_codegen(*args)\n\n        verify_codegen(func, exp_codegen, acl_partitions, tvm_ops)\n\n\ndef test_codegen_global_pooling():\n    if skip_codegen_test():\n        return\n\n    fp32_dtype = (\"float32\", -127, 128)\n    uint8_dtype = (\"uint8\", 0, 255)\n\n    trials = [\n        [\"nn.global_max_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", fp32_dtype, (9, 9, 16)],\n        [\"nn.global_max_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", uint8_dtype, (8, 8, 16)],\n        [\"nn.global_max_pool2d\", uint8_dtype, (9, 9, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", fp32_dtype, (9, 9, 16)],\n        [\"nn.global_avg_pool2d\", uint8_dtype, (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", uint8_dtype, (8, 8, 16)],\n    ]\n\n    for typef, (dtype, low, high), input_shape in trials:\n        shape = (1, *input_shape)\n        inputs = {\"a\"}\n        args = (shape, dtype, typef)\n        func = _get_global_pooling_model(*args, iter(inputs))\n        exp_codegen = _get_expected_global_pooling_codegen(*args)\n        verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_pooling()\n    test_global_pooling()\n    test_codegen_pooling()\n    test_codegen_global_pooling()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library integration reshape tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\n\nfrom .infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom .infrastructure import Device\n\n\ndef _get_model(input_shape, output_shape, dtype, var_names):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    a = relay.var(next(var_names), shape=input_shape, dtype=dtype)\n    reshape = relay.reshape(a, output_shape)\n    return reshape\n\n\ndef _get_expected_codegen(input_shape, output_shape, dtype):\n    node = {\n        \"op\": \"kernel\",\n        \"name\": \"reshape\",\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n            \"newshape\": [[str(s) for s in output_shape]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"allowzero\": [[\"0\"]],\n        },\n    }\n\n    input = {\n        \"op\": \"input\",\n        \"name\": \"\",\n        \"attrs\": {\"shape\": [[list(input_shape)]], \"dtype\": [[dtype]]},\n    }\n\n    return [input, node]\n\n\ndef test_reshape():\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    for dtype, low, high, atol, rtol in [\n        (\"float32\", -127, 128, 0.001, 0.001),\n        (\"uint8\", 0, 255, 0, 0),\n    ]:\n        inputs = {\"a\": tvm.nd.array(np.random.uniform(low, high, (1, 1, 1, 1000)).astype(dtype))}\n\n        for new_shape in [(1, 1000), (10, 10, 10), (10, 100, 1), (1, 1000, 1)]:\n            outputs = []\n            func = _get_model(inputs[\"a\"].shape, new_shape, dtype, iter(inputs))\n            for acl in [False, True]:\n                outputs.append(build_and_run(func, inputs, 1, None, device, enable_acl=acl)[0])\n\n            config = {\n                \"new shape\": inputs[\"a\"].shape,\n                \"shape\": new_shape,\n                \"dtype\": dtype,\n            }\n            verify(outputs, atol=1e-7, rtol=1e-7, config=config)\n\n\ndef test_codegen_reshape():\n    if skip_codegen_test():\n        return\n\n    shape = (1, 1, 1, 1000)\n    inputs = {\"a\"}\n    for dtype in [\"float32\", \"uint8\"]:\n        for new_shape in [(1, 1000), (10, 10, 10), (10, 100, 1)]:\n            args = (shape, new_shape, dtype)\n            func = _get_model(*args, iter(inputs))\n            exp_codegen = _get_expected_codegen(*args)\n            verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_reshape()\n    test_codegen_reshape()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_arm_compute_lib/test_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Arm Compute Library runtime tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\n\nfrom .infrastructure import skip_runtime_test, build_and_run, verify\nfrom .infrastructure import Device\n\n\ndef test_multiple_ops():\n    \"\"\"\n    Test multiple operators destined for ACL.\n    The ACL runtime will expect these ops as 2 separate functions for\n    the time being.\n    \"\"\"\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    def get_model(input_shape, var_names):\n        \"\"\"Return a model and any parameters it may have.\"\"\"\n        a = relay.var(next(var_names), shape=input_shape, dtype=\"float32\")\n        out = relay.reshape(a, (1, 1, 1000))\n        out = relay.reshape(out, (1, 1000))\n        return out\n\n    inputs = {\"a\": tvm.nd.array(np.random.uniform(0, 1, (1, 1, 1, 1000)).astype(\"float32\"))}\n\n    outputs = []\n    for acl in [False, True]:\n        func = get_model(inputs[\"a\"].shape, iter(inputs))\n        outputs.append(\n            build_and_run(func, inputs, 1, None, device, enable_acl=acl, acl_partitions=2)[0]\n        )\n    verify(outputs, atol=0.002, rtol=0.01)\n\n\ndef test_heterogeneous():\n    \"\"\"\n    Test to check if offloading only supported operators works,\n    while leaving unsupported operators computed via tvm.\n    \"\"\"\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n    np.random.seed(0)\n\n    def get_model(input_shape, var_names):\n        \"\"\"Return a model and any parameters it may have.\"\"\"\n        a = relay.var(next(var_names), shape=input_shape, dtype=\"float32\")\n        out = relay.reshape(a, (1, 1, 1000))\n        out = relay.sigmoid(out)\n        out = relay.reshape(out, (1, 1000))\n        return out\n\n    inputs = {\"a\": tvm.nd.array(np.random.uniform(-127, 128, (1, 1, 1, 1000)).astype(\"float32\"))}\n\n    outputs = []\n    for acl in [False, True]:\n        func = get_model(inputs[\"a\"].shape, iter(inputs))\n        outputs.append(\n            build_and_run(\n                func, inputs, 1, None, device, enable_acl=acl, tvm_ops=1, acl_partitions=2\n            )[0]\n        )\n    verify(outputs, atol=0.002, rtol=0.01)\n\n\ndef test_multiple_runs():\n    \"\"\"\n    Test that multiple runs of an operator work.\n    \"\"\"\n    Device.load(\"test_config.json\")\n\n    if skip_runtime_test():\n        return\n\n    device = Device()\n\n    def get_model():\n        a = relay.var(\"a\", shape=(1, 28, 28, 512), dtype=\"float32\")\n        w = tvm.nd.array(np.ones((256, 1, 1, 512), dtype=\"float32\"))\n        weights = relay.const(w, \"float32\")\n        conv = relay.nn.conv2d(\n            a,\n            weights,\n            kernel_size=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n            strides=(1, 1),\n            padding=(0, 0),\n            dilation=(1, 1),\n        )\n        params = {\"w\": w}\n        return conv, params\n\n    inputs = {\n        \"a\": tvm.nd.array(np.random.uniform(-127, 128, (1, 28, 28, 512)).astype(\"float32\")),\n    }\n\n    func, params = get_model()\n    outputs = build_and_run(func, inputs, 1, params, device, enable_acl=True, no_runs=3)\n    verify(outputs, atol=0.002, rtol=0.01)\n\n\nif __name__ == \"__main__\":\n    test_multiple_ops()\n    test_heterogeneous()\n    test_multiple_runs()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for BNNS\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom itertools import zip_longest, combinations\nimport json\nimport os\nimport warnings\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import rpc\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.op.contrib.bnns import partition_for_bnns\nfrom tvm.contrib import utils\nfrom tvm.autotvm.measure import request_remote\nfrom tvm.relay.analysis import analysis\n\n\nclass Device:\n    \"\"\"\n    Common device configuration for python tests.\n\n    Check tests/python/contrib/arm_compute_lib/ for the presence of an test_config.json file.\n    This file can be used to override the default configuration here which will attempt to run the BNNS\n    runtime tests locally if the runtime is available. Changing the configuration will allow these\n    runtime tests to be offloaded to a remote device with BNNS via a tracker for example.\n\n    Notes\n    -----\n        The test configuration will be loaded once when the class is created. If the configuration\n        changes between tests, any changes will not be picked up.\n\n\n    Attributes\n    ----------\n    connection_type : str\n        Details the type of RPC connection to use. Options:\n        local - Use the local device,\n        tracker - Connect to a tracker to request a remote device,\n        remote - Connect to a remote device directly.\n    host : str\n        Specify IP address or hostname of remote target.\n    port : int\n        Specify port number of remote target.\n    target : str\n        The compilation target.\n    device_key : str\n        The device key of the remote target. Use when connecting to a remote device via a tracker.\n    cross_compile : str\n        Specify path to cross compiler to use when connecting a remote device from a non-arm platform.\n    \"\"\"\n\n    connection_type = \"local\"\n    host = \"127.0.0.1\"\n    port = 9090\n    target = \"llvm\"\n    device_key = \"\"\n    cross_compile = \"\"\n\n    def __init__(self):\n        \"\"\"Keep remote device for lifetime of object.\"\"\"\n        self.device = self._get_remote()\n\n    @classmethod\n    def _get_remote(cls):\n        \"\"\"Get a remote (or local) device to use for testing.\"\"\"\n        if cls.connection_type == \"tracker\":\n            device = request_remote(cls.device_key, cls.host, cls.port, timeout=1000)\n        elif cls.connection_type == \"remote\":\n            device = rpc.connect(cls.host, cls.port)\n        elif cls.connection_type == \"local\":\n            device = rpc.LocalSession()\n        else:\n            raise ValueError(\n                \"connection_type in test_config.json should be one of: \" \"local, tracker, remote.\"\n            )\n\n        return device\n\n    @classmethod\n    def load(cls, file_name):\n        \"\"\"Load test config\n\n        Load the test configuration by looking for file_name relative\n        to the test_bnns directory.\n        \"\"\"\n        location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n        config_file = os.path.join(location, file_name)\n        if not os.path.exists(config_file):\n            warnings.warn(\"Config file doesn't exist, resuming tests with default config.\")\n            return\n        with open(config_file, mode=\"r\") as config:\n            test_config = json.load(config)\n\n        cls.connection_type = test_config[\"connection_type\"]\n        cls.host = test_config[\"host\"]\n        cls.port = test_config[\"port\"]\n        cls.target = test_config[\"target\"]\n        cls.device_key = test_config.get(\"device_key\") or \"\"\n        cls.cross_compile = test_config.get(\"cross_compile\") or \"\"\n\n\nDevice.target = \"llvm\"\n\n\ndef skip_runtime_test():\n    \"\"\"Skip test if it requires the runtime and it's not present.\"\"\"\n    # BNNS codegen not present.\n    if not tvm.get_global_func(\"relay.ext.bnns\", True):\n        print(\"Skip because BNNS codegen is not available.\")\n        return True\n    return False\n\n\ndef skip_codegen_test():\n    \"\"\"Skip test if it requires the BNNS codegen and it's not present.\"\"\"\n    if not tvm.get_global_func(\"relay.ext.bnns\", True):\n        print(\"Skip because BNNS codegen is not available.\")\n        return True\n\n\ndef build_module(mod, target, params=None, enable_bnns=True, tvm_ops=0):\n    \"\"\"Build module with option to build for BNNS.\"\"\"\n    if isinstance(mod, tvm.relay.expr.Call):\n        mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3):\n        if enable_bnns:\n            mod = partition_for_bnns(mod)\n        relay.backend.te_compiler.get().clear()\n        return relay.build(mod, target=target, params=params)\n\n\ndef build_and_run(\n    mod,\n    inputs,\n    outputs,\n    params,\n    device,\n    enable_bnns=True,\n    no_runs=1,\n    tvm_ops=0,\n    config=None,\n):\n    \"\"\"Build and run the relay module.\"\"\"\n    if config is None:\n        config = {}\n\n    try:\n        lib = build_module(mod, device.target, params, enable_bnns, tvm_ops)\n    except Exception as e:\n        err_msg = \"The module could not be built.\\n\"\n        if config:\n            err_msg += f\"The test failed with the following parameters: {config}\\n\"\n        err_msg += str(e)\n        raise Exception(err_msg)\n\n    lib = update_lib(lib, device.device, device.cross_compile)\n    gen_module = graph_executor.GraphModule(lib[\"default\"](device.device.cpu(0)))\n    gen_module.set_input(**inputs)\n    out = []\n    for _ in range(no_runs):\n        gen_module.run()\n        out.append([gen_module.get_output(i) for i in range(outputs)])\n    return out\n\n\ndef update_lib(lib, device, cross_compile):\n    \"\"\"Export the library to the remote/local device.\"\"\"\n    lib_name = \"mod.so\"\n    temp = utils.tempdir()\n    lib_path = temp.relpath(lib_name)\n    if cross_compile:\n        lib.export_library(lib_path, cc=cross_compile)\n    else:\n        lib.export_library(lib_path)\n    device.upload(lib_path)\n    lib = device.load_module(lib_name)\n    return lib\n\n\ndef extract_bnns_modules(module):\n    \"\"\"Get the BNNS module(s) from llvm module.\"\"\"\n    return list(filter(lambda mod: mod.type_key == \"bnns_json\", module.get_lib().imported_modules))\n\n\ndef verify(answers, atol, rtol, verify_saturation=False, config=None):\n    \"\"\"Compare the array of answers. Each entry is a list of outputs.\"\"\"\n    if config is None:\n        config = {}\n\n    if len(answers) < 2:\n        raise RuntimeError(f\"No results to compare: expected at least two, found {len(answers)}\")\n    for answer in zip_longest(*answers):\n        for outs in combinations(answer, 2):\n            try:\n                if verify_saturation:\n                    assert (\n                        np.count_nonzero(outs[0].numpy() == 255) < 0.25 * outs[0].numpy().size\n                    ), \"Output is saturated: {}\".format(outs[0])\n                    assert (\n                        np.count_nonzero(outs[0].numpy() == 0) < 0.25 * outs[0].numpy().size\n                    ), \"Output is saturated: {}\".format(outs[0])\n                tvm.testing.assert_allclose(outs[0].numpy(), outs[1].numpy(), rtol=rtol, atol=atol)\n            except AssertionError as e:\n                err_msg = \"Results not within the acceptable tolerance.\\n\"\n                if config:\n                    err_msg += f\"The test failed with the following parameters: {config}\\n\"\n                err_msg += str(e)\n                raise AssertionError(err_msg)\n\n\ndef verify_codegen(\n    module,\n    known_good_codegen,\n    num_bnns_modules,\n    tvm_ops=0,\n    target=Device.target,\n):\n    \"\"\"Check BNNS codegen against a known good output.\"\"\"\n    module = build_module(module, target, tvm_ops=tvm_ops)\n    bnns_modules = extract_bnns_modules(module)\n\n    assert len(bnns_modules) == num_bnns_modules, (\n        f\"The number of BNNS modules produced ({len(bnns_modules)}) does not \"\n        f\"match the expected value ({num_bnns_modules}).\"\n    )\n\n    for mod in bnns_modules:\n        source = mod.get_source(\"json\")\n        codegen = json.loads(source)[\"nodes\"]\n        # remove input and const names as these cannot be predetermined\n        for node in range(len(codegen)):\n            if codegen[node][\"op\"] == \"input\" or codegen[node][\"op\"] == \"const\":\n                codegen[node][\"name\"] = \"\"\n        codegen_str = json.dumps(codegen, sort_keys=True, indent=2)\n        known_good_codegen_str = json.dumps(known_good_codegen, sort_keys=True, indent=2)\n\n        assert codegen_str == known_good_codegen_str, (\n            f\"The JSON produced by codegen does not match the expected result. \\n\"\n            f\"Actual={codegen_str} \\n\"\n            f\"Expected={known_good_codegen_str}\"\n        )\n\n\ndef compare_inference_with_ref(func, params, atol=0.002, rtol=0.007):\n    \"\"\"Compare scoring results for compilation with and without BNNS.\n\n    Provided function will be compiled two times with and without BNNS.\n    The scoring results for both type of compilation will be compared\n    with provided atol and rtol. The input data will be automatically\n    generated based of shape and dtype info provided for var nodes.\n\n    \"\"\"\n    # Generate input tensor values\n    inputs = {}\n    for free_param in analysis.free_vars(func):\n        name = free_param.name_hint\n        dtype = free_param.type_annotation.dtype\n        shape = [s.value for s in free_param.type_annotation.shape]\n        inputs[name] = tvm.nd.array(np.random.uniform(0, 127, shape).astype(dtype))\n\n    # Run for both type of compilation\n    device = Device()\n    outputs = []\n    for bnns in [False, True]:\n        outputs.append(build_and_run(func, inputs, 1, params, device, enable_bnns=bnns)[0])\n\n    # Compare result tensors\n    verify(outputs, atol=atol, rtol=rtol)\n\n\ndef generate_trials(space, r_factor=3):\n    \"\"\"Generates a series of trials.\n\n    This algorithm generates a series of non-deterministic trials given a\n    space of options to test. A trial is generated by pulling a value from\n    each option in the space. On some occasions the values are shuffled to\n    ensure a different trial on each r_factor iteration. The algorithm ensures\n    that each value from an option is used at least once. The total number of\n    trials is determined by the r_factor * the option with the largest number\n    of values.\n\n    Parameters\n    ----------\n    space: List[List[Any]]\n        A list of different options with varying values to test.\n    r_factor: Optional[int]\n        The repeat factor.\n\n    Returns\n    -------\n    result: List[Tuple]\n        A list of trials specifying values for each option.\n\n    \"\"\"\n    np.random.seed(0)\n    max_len = 1\n    for option in space:\n        max_len = max(max_len, len(option))\n\n    num_trials = r_factor * max_len\n    trials = []\n    for i in range(num_trials):\n        trial = []\n        for option in space:\n            if i % len(option) == 0:\n                np.random.shuffle(option)\n            trial.append(option[i % len(option)])\n\n        trials.append(trial)\n\n    return trials\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS integration conv2d tests.\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\n\nfrom .infrastructure import skip_runtime_test, compare_inference_with_ref, generate_trials\n\n# TODO: Missed cases\n#   1. Bias as add with 3d const tensor. Lead to additional unsqueeze op between\n#   2. Check unsupported cases of fusion. Like bias add with axis != 1, add with broadcast by spatial dims\n#   3. Check if bias/weights is not constants. Should fallback into LLVM or decompose it\n#   4. Check if bias/weights is constants expr. Should works somehow.\n\n\ndef _get_model(\n    shape,\n    kernel=(3, 3),\n    padding=(1, 1),\n    strides=(1, 1),\n    dilation=(1, 1),\n    groups=1,\n    dtype=\"float32\",\n    channels=-1,  # -1 means same as input channels\n    bias_type=\"none\",\n    activation_type=\"none\",\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    if channels == -1:\n        channels = shape[1]\n\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    weight_shape = (channels, shape[1] // groups, *kernel)\n    w = tvm.nd.array(np.random.uniform(-128, 127, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.nn.conv2d(\n        a,\n        weights,\n        kernel_size=kernel,\n        dilation=dilation,\n        strides=strides,\n        padding=padding,\n        groups=groups,\n        channels=channels,\n        out_dtype=dtype,\n    )\n    params = {\"w\": w}\n    if bias_type == \"bias_add\":\n        b = tvm.nd.array(np.random.uniform(-10, 10, weight_shape[0]).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.nn.bias_add(out, biasc, axis=1)\n        params[\"b\"] = b\n    elif bias_type == \"add_3d\" or bias_type == \"add_4d\":\n        bias_shape = (\n            (weight_shape[0], 1, 1) if bias_type == \"add_3d\" else (1, weight_shape[0], 1, 1)\n        )\n        b = tvm.nd.array(np.random.uniform(-10, 10, bias_shape).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.add(out, biasc)\n        params[\"b\"] = b\n\n    if activation_type == \"relu\":\n        out = relay.nn.relu(out)\n    elif activation_type == \"sigmoid\":\n        out = relay.op.sigmoid(out)\n    return out, params\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_conv2d():\n    np.random.seed(0)\n\n    kernel_hs = [1, 2, 3, 5]\n    kernel_ws = [1, 2, 3, 5]\n    pad = [(1, 1), (2, 2), (2, 1)]\n    strides = [(1, 1), (2, 2)]\n    dilation = [(1, 1)]\n    out_channels = [1, 4, 8, 16]\n    input_shapes = [(10, 10, 14), (12, 15, 16), (20, 20, 20)]\n    batches = [1, 2]\n    groups = [1, 2]\n    bias_kind = [\"none\", \"add_3d\", \"add_4d\", \"bias.add\"]\n    activation_kind = [\"none\", \"relu\", \"sigmoid\"]\n    trials = generate_trials(\n        [\n            kernel_hs,\n            kernel_ws,\n            pad,\n            strides,\n            dilation,\n            out_channels,\n            input_shapes,\n            groups,\n            batches,\n            bias_kind,\n            activation_kind,\n        ],\n        3,\n    )\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        input_shapes,\n        group,\n        batch,\n        bias,\n        activation,\n    ) in trials:\n        if out_channels % group != 0:\n            continue\n        func, params = _get_model(\n            shape=(batch, *input_shapes),\n            kernel=(kernel_h, kernel_w),\n            padding=pad,\n            strides=stride,\n            dilation=dilation,\n            groups=group,\n            channels=out_channels,\n            bias_type=bias,\n            activation_type=activation,\n        )\n        compare_inference_with_ref(func, params)\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_conv2d_dw():\n    if skip_runtime_test():\n        return\n\n    np.random.seed(0)\n    shape = [4, 5, 5]\n\n    for batch in [1, 2]:\n        mod, params = _get_model(shape=(batch, *shape), groups=shape[0])\n        compare_inference_with_ref(mod, params)\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_conv2d_with_oc1():\n    if skip_runtime_test():\n        return\n\n    np.random.seed(0)\n    shape = [3, 5, 5]\n\n    for batch in [1, 2]:\n        for bias in [\"none\", \"add_4d\"]:\n            mod, params = _get_model(shape=(batch, *shape), channels=1, bias_type=bias)\n            compare_inference_with_ref(mod, params)\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n    test_conv2d_dw()\n    test_conv2d_with_oc1()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_conv2d_patterns.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS pattern detection check\"\"\"\n\nimport tvm\nfrom tvm import relay\nimport numpy as np\n\nfrom tvm.relay.op.contrib.bnns import partition_for_bnns\n\nfp32 = \"float32\"\n\n\ndef partition(exp):\n    \"\"\"Apply BNNS specific partitioning transformation\"\"\"\n    mod = tvm.IRModule.from_expr(exp)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = partition_for_bnns(mod)\n    return mod\n\n\ndef is_op_fused(func, op_name):\n    is_fused = False\n\n    def visit(op):\n        if (\n            isinstance(op, tvm.relay.function.Function)\n            and op_name in op.attrs[\"PartitionedFromPattern\"]\n        ):\n            nonlocal is_fused\n            is_fused = True\n\n    tvm.relay.analysis.post_order_visit(func.body, visit)\n    return is_fused\n\n\ndef test_pattern_conv2d_with_bias_add():\n    for axis in (1, 2):\n        a = relay.var(\"a\", shape=(2, 7, 8, 8), dtype=fp32)\n        w = relay.const(np.random.uniform(-10, 10, (8, 7, 3, 3)).astype(fp32))\n        res = relay.nn.conv2d(a, w, kernel_size=(3, 3), padding=(1, 1), channels=8, out_dtype=fp32)\n        b = relay.const(np.random.uniform(-10, 10, 8).astype(fp32))\n        res = relay.nn.bias_add(res, b, axis=axis)\n\n        mod = partition(res)\n        bias_is_fused = is_op_fused(mod[\"tvmgen_default_bnns_main_0\"], \"nn.bias_add\")\n\n        assert bias_is_fused if axis == 1 else not bias_is_fused\n\n\ndef test_pattern_conv2d_with_add():\n    workloads = {8: False, (8, 1): False, (8, 1, 1): True, (1, 8, 1, 1): True}\n\n    for b_shape, should_be_fused in workloads.items():\n        a = relay.var(\"a\", shape=(2, 7, 8, 8), dtype=fp32)\n        w = relay.const(np.random.uniform(-10, 10, (8, 7, 3, 3)).astype(fp32))\n        res = relay.nn.conv2d(a, w, kernel_size=(3, 3), padding=(1, 1), channels=8, out_dtype=fp32)\n        b = relay.const(np.random.uniform(-10, 10, b_shape).astype(fp32))\n        res = relay.add(res, b)\n\n        mod = partition(res)\n        bias_is_fused = is_op_fused(mod[\"tvmgen_default_bnns_main_0\"], \"add\")\n\n        assert bias_is_fused == should_be_fused\n\n\ndef test_pattern_conv2d_with_non_cons_weights():\n    for const_weights in (True, False):\n        a = relay.var(\"a\", shape=(2, 7, 8, 8), dtype=fp32)\n        if const_weights:\n            w = relay.const(np.random.uniform(-10, 10, (8, 7, 3, 3)).astype(fp32))\n        else:\n            w = relay.var(\"w\", shape=(8, 7, 3, 3), dtype=fp32)\n\n        res = relay.nn.conv2d(a, w, kernel_size=(3, 3), padding=(1, 1), channels=8, out_dtype=fp32)\n\n        mod = partition(res)\n        use_bnns = len(mod.get_global_vars()) == 2  # GlobalVar: \"main\" and \"bnns_0\"\n\n        assert use_bnns == const_weights\n\n\ndef test_pattern_conv2d_with_non_cons_bias():\n    a = relay.var(\"a\", shape=[2, 7, 8, 8], dtype=fp32)\n    w = relay.const(np.random.uniform(-10, 10, (8, 7, 3, 3)).astype(fp32))\n    res = relay.nn.conv2d(a, w, kernel_size=(3, 3), padding=(1, 1), channels=8, out_dtype=fp32)\n    b = relay.var(\"b\", shape=[8], dtype=fp32)\n    res = relay.nn.bias_add(res, b, axis=1)\n\n    mod = partition(res)\n    bias_is_fused = is_op_fused(mod[\"tvmgen_default_bnns_main_0\"], \"nn.bias_add\")\n\n    assert not bias_is_fused\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS integration dense tests.\"\"\"\n\nimport numpy as np\nimport math\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom .infrastructure import (\n    Device,\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n    generate_trials,\n)\n\n\ndef _get_model(shape, weight_shape, units, dtype, var_names, has_bias=False, has_gelu=False):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(next(var_names), shape=shape, dtype=dtype)\n    w = tvm.nd.array(np.random.uniform(-128, 127, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.nn.dense(a, weights, units=units, out_dtype=dtype)\n    params = {\"w\": w}\n    if has_bias:\n        b = tvm.nd.array(np.random.randint(-128, 127, weight_shape[0]).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.op.add(out, biasc)\n        params[\"b\"] = b\n    if has_gelu:\n        const1 = relay.const(0.044715)\n        const2 = relay.const(math.sqrt(2 / math.pi))\n        bias = out\n        out = relay.op.power(bias, relay.const(3.0, \"float32\"))\n        out = relay.op.multiply(out, const1)\n        out = relay.op.add(out, bias)\n        out = relay.op.multiply(out, const2)\n        out = relay.op.tanh(out)\n        out = relay.op.add(out, relay.const(1, \"float32\"))\n        out = relay.op.multiply(out, relay.const(0.5))\n        out = relay.op.multiply(out, bias)\n    return out, params\n\n\ndef _get_expected_codegen(shape, weight_shape, units, dtype, has_bias=False, has_gelu=False):\n    output_shape = (shape[0], units)\n    name = \"nn.dense\"\n    if has_bias is True:\n        name = \"bnns.dense_bias\"\n    if has_bias is True and has_gelu is True:\n        name = \"bnns.dense_bias_gelu\"\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": name,\n        \"inputs\": [],\n        \"attrs\": {\n            \"num_outputs\": \"1\",\n            \"out_dtype\": [[\"float32\"]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"units\": [[str(units)]],\n        },\n    }\n\n    inputs = [\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[str(dtype)]]}},\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\"shape\": [[list(weight_shape)]], \"dtype\": [[str(dtype)]]},\n        },\n    ]\n\n    if has_bias:\n        inputs.append(\n            {\n                \"op\": \"const\",\n                \"name\": \"\",\n                \"attrs\": {\"shape\": [[[weight_shape[0]]]], \"dtype\": [[\"float32\"]]},\n            }\n        )\n\n    input_idx = 0\n    for _ in range(len(inputs)):\n        node[\"inputs\"].append([input_idx, 0, 0])\n        input_idx += 1\n    node[\"attrs\"][\"num_inputs\"] = str(len(inputs))\n    inputs.append(node)\n    return inputs\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_dense():\n    device = Device()\n    np.random.seed(0)\n\n    dtype = [\"float32\"]\n    shape = [\n        ((1, 128), (16, 128), 16),\n        ((32, 32), (32, 32), 32),\n        ((1, 64), (1, 64), 1),\n        ((11, 2), (2, 2), 2),\n        ((2, 2), (1, 2), 1),\n    ]\n    composite = [False, True]\n    trials = generate_trials([dtype, shape, composite, composite], 3)\n\n    for dtype, (shape, weight_shape, units), with_bias, with_gelu in trials:\n        outputs = []\n        inputs = {\"a\": tvm.nd.array(np.random.uniform(-128, 127, shape).astype(dtype))}\n        func, params = _get_model(\n            shape,\n            weight_shape,\n            units,\n            dtype,\n            var_names=iter(inputs),\n            has_bias=with_bias,\n            has_gelu=with_gelu,\n        )\n        for bnns in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func,\n                    inputs,\n                    1,\n                    params,\n                    device,\n                    enable_bnns=bnns,\n                )[0]\n            )\n\n        config = {\n            \"shape\": shape,\n            \"weight_shape\": weight_shape,\n            \"units\": units,\n            \"dtype\": dtype,\n            \"with_bias\": with_bias,\n            \"with_gelu\": with_gelu,\n        }\n        verify(outputs, atol=0.001, rtol=0.01, config=config)\n\n\n@pytest.mark.skipif(skip_codegen_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_codegen_dense():\n    np.random.seed(0)\n\n    dtype = [\"float32\"]\n    shape = [\n        ((1, 128), (16, 128), 16),\n        ((32, 32), (32, 32), 32),\n        ((1, 64), (1, 64), 1),\n        ((11, 2), (2, 2), 2),\n        ((2, 2), (1, 2), 1),\n    ]\n    composite = [False, True]\n    trials = generate_trials([dtype, shape, composite, composite], 3)\n\n    for dtype, (shape, weight_shape, units), with_bias, with_gelu in trials:\n        inputs = {\"a\"}\n\n        args = (shape, weight_shape, units, dtype)\n\n        func, params = _get_model(\n            *args, var_names=iter(inputs), has_bias=with_bias, has_gelu=with_gelu\n        )\n        exp_codegen = _get_expected_codegen(*args, has_bias=with_bias, has_gelu=with_gelu)\n        verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_dense()\n    test_codegen_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS integration dense tests.\"\"\"\n\nimport numpy as np\nimport math\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\nfrom .infrastructure import (\n    Device,\n    skip_runtime_test,\n    skip_codegen_test,\n    verify_codegen,\n    build_and_run,\n    verify,\n    generate_trials,\n)\n\n\ndef _get_model(a_shape, b_shape, dtype, var_names, is_a_constant=False, is_b_constant=False):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(next(var_names), shape=a_shape, dtype=dtype)\n    b = relay.var(next(var_names), shape=b_shape, dtype=dtype)\n    params = {}\n    if is_b_constant is True:\n        b = tvm.nd.array(np.random.uniform(-128, 127, b_shape).astype(dtype))\n        params[\"b\"] = b\n        b = relay.const(b, dtype)\n    if is_a_constant is True:\n        a = tvm.nd.array(np.random.uniform(-128, 127, a_shape).astype(dtype))\n        params[\"a\"] = a\n        a = relay.const(a, dtype)\n    out = relay.nn.batch_matmul(a, b)\n    return out, params\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_matmul():\n    device = Device()\n    np.random.seed(0)\n    dtype = \"float32\"\n\n    # C[N, I, J] = A[N, I, K] * B[N, J, K]\n    shapes_config = [\n        # B, I, J, K\n        [1, 4, 4, 3],\n        [1, 16, 32, 32],\n        [2, 1, 1, 3],\n        [2, 16, 32, 32],\n        [5, 1, 1, 3],\n    ]\n    data_config = [\n        # A_is_constant, B_is_constant\n        [False, True],\n        [True, False],\n        [False, False],\n    ]\n\n    for N, I, J, K in shapes_config:\n        a_shape = [N, I, K]\n        b_shape = [N, J, K]\n        for is_a_constant, is_b_constant in data_config:\n            outputs = []\n            inputs = {\n                \"a\": tvm.nd.array(np.random.uniform(-128, 127, a_shape).astype(dtype)),\n                \"b\": tvm.nd.array(np.random.uniform(-128, 127, b_shape).astype(dtype)),\n            }\n            func, params = _get_model(\n                a_shape,\n                b_shape,\n                dtype,\n                var_names=iter(inputs),\n                is_a_constant=is_a_constant,\n                is_b_constant=is_b_constant,\n            )\n            for enable_bnns in [False, True]:\n                outputs.append(\n                    build_and_run(\n                        func,\n                        inputs,\n                        1,\n                        params,\n                        device,\n                        enable_bnns=enable_bnns,\n                    )[0]\n                )\n\n            config = {\n                \"a_shape\": a_shape,\n                \"b_shape\": b_shape,\n                \"dtype\": dtype,\n            }\n            verify(outputs, atol=0.001, rtol=0.01, config=config)\n\n\nif __name__ == \"__main__\":\n    test_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_normalization.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS integration normalization tests.\"\"\"\n\nimport numpy as np\nimport math\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\nfrom .infrastructure import (\n    Device,\n    skip_runtime_test,\n    skip_codegen_test,\n    verify_codegen,\n    build_and_run,\n    verify,\n    generate_trials,\n)\n\n\ndef _get_model(\n    shape, b_shape, s_shape, dtype, var_names, axis=1, epsilon=1e-5, center=True, scale=True\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    src = relay.var(next(var_names), shape=shape, dtype=dtype)\n    params = {}\n    b = tvm.nd.array(np.random.uniform(-128, 127, b_shape).astype(dtype))\n    params[\"b\"] = b\n    b = relay.const(b, dtype)\n    s = tvm.nd.array(np.random.uniform(-128, 127, b_shape).astype(dtype))\n    params[\"b\"] = s\n    s = relay.const(s, dtype)\n    out = relay.nn.instance_norm(src, s, b, axis, epsilon, center, scale)\n\n    return out, params\n\n\ndef _get_expected_codegen(shape, axis, center, scale, dtype, offload_on_bnns):\n    output_shape = shape\n    name = \"nn.instance_norm\"\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": name,\n        \"inputs\": [],\n        \"attrs\": {\n            \"num_outputs\": \"1\",\n            \"axis\": [[str(axis)]],\n            \"center\": [[str(int(center))]],\n            \"scale\": [[str(int(scale))]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"epsilon\": [[\"1.0000000000000001e-05\"]],\n        },\n    }\n\n    inputs = [\n        {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[str(dtype)]]}},\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\"shape\": [[[shape[axis]]]], \"dtype\": [[str(dtype)]]},\n        },\n        {\n            \"op\": \"const\",\n            \"name\": \"\",\n            \"attrs\": {\"shape\": [[[shape[axis]]]], \"dtype\": [[str(dtype)]]},\n        },\n    ]\n\n    input_idx = 0\n    for _ in range(len(inputs)):\n        node[\"inputs\"].append([input_idx, 0, 0])\n        input_idx += 1\n    node[\"attrs\"][\"num_inputs\"] = str(len(inputs))\n    inputs.append(node)\n    return inputs\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_normalization():\n    device = Device()\n    np.random.seed(0)\n    dtype = \"float32\"\n\n    shapes_config = [\n        [1, 2, 3, 4],\n        [3, 2, 3, 4],\n        [2, 2, 3],\n        [16, 32, 32],\n        [5, 3],\n    ]\n    axes = [-1, 0, 1, 2]\n\n    for shape in shapes_config:\n        for axis in axes:\n            if len(shape) == 2 and axis != 0:\n                continue\n            for center in [False, True]:\n                for scale in [False, True]:\n                    outputs = []\n                    inputs = {\n                        \"src\": tvm.nd.array(np.random.uniform(-128, 127, shape).astype(dtype)),\n                    }\n                    func, params = _get_model(\n                        shape,\n                        [shape[axis]],\n                        [shape[axis]],\n                        dtype,\n                        var_names=iter(inputs),\n                        axis=axis,\n                        center=center,\n                        scale=scale,\n                    )\n                    for enable_bnns in [False, True]:\n                        outputs.append(\n                            build_and_run(\n                                func,\n                                inputs,\n                                1,\n                                params,\n                                device,\n                                enable_bnns=enable_bnns,\n                            )[0]\n                        )\n\n                    config = {\n                        \"dtype\": dtype,\n                    }\n                    verify(outputs, atol=0.001, rtol=0.01, config=config)\n\n\n@pytest.mark.skipif(skip_codegen_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_codegen_normalization():\n    np.random.seed(0)\n\n    dtype = \"float32\"\n    shapes_config = [\n        [1, 2, 3, 4],\n        [3, 2, 3, 4],\n        [2, 2, 3],\n        [16, 32, 32],\n        [5, 3],\n    ]\n    axes = [-1, 0, 1, 2]\n\n    def check_normalization(rank, axis):\n        if rank < 3 or rank > 4:\n            return False\n        if axis == 0 and rank == 3 or axis == 1 and rank == 4:\n            return True\n        return False\n\n    for shape in shapes_config:\n        for axis in axes:\n            if len(shape) == 2 and axis != 0:\n                continue\n            for center in [False, True]:\n                for scale in [False, True]:\n                    inputs = {\"src\"}\n\n                    args = (shape, axis, center, scale, dtype)\n\n                    func, params = _get_model(\n                        shape,\n                        [shape[axis]],\n                        [shape[axis]],\n                        dtype,\n                        var_names=iter(inputs),\n                        axis=axis,\n                        center=center,\n                        scale=scale,\n                    )\n\n                    offload_on_bnns = check_normalization(len(shape), axis)\n                    if offload_on_bnns is True:\n                        bnns_blocks = 1\n                    else:\n                        bnns_blocks = 0\n                    exp_codegen = _get_expected_codegen(*args, offload_on_bnns)\n                    verify_codegen(func, exp_codegen, bnns_blocks)\n\n\nif __name__ == \"__main__\":\n    test_normalization()\n    test_codegen_normalization()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_onnx_topologies.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS pattern detection check\"\"\"\n\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.contrib import utils, graph_executor\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.op.contrib.bnns import partition_for_bnns\n\nimport numpy as np\n\npytest.importorskip(\"onnx\")\n\nbnns_is_absent = tvm.get_global_func(\"relay.ext.bnns\", True) is None\n\nTARGET = \"llvm\"\nINPUT_SHAPE = [1, 3, 224, 224]\n\nBASE_MODEL_URL = \"https://github.com/onnx/models/raw/bd206494e8b6a27b25e5cf7199dbcdbfe9d05d1c/\"\nMODEL_URL_COLLECTION = {\n    \"BERT\": \"text/machine_comprehension/bert-squad/model/bertsquad-10.onnx\",\n    \"MobileNet-v2\": \"vision/classification/mobilenet/model/mobilenetv2-7.onnx\",\n    \"ResNet50-v1\": \"vision/classification/resnet/model/resnet50-v1-7.onnx\",\n    \"ResNet50-v2\": \"vision/classification/resnet/model/resnet50-v2-7.onnx\",\n    \"SqueezeNet-v1.1\": \"vision/classification/squeezenet/model/squeezenet1.1-7.onnx\",\n    \"SqueezeNet-v1.0\": \"vision/classification/squeezenet/model/squeezenet1.0-7.onnx\",\n    \"Inception-v1\": \"vision/classification/inception_and_googlenet/inception_v1/model/inception-v1-7.onnx\",\n    \"Inception-v2\": \"vision/classification/inception_and_googlenet/inception_v2/model/inception-v2-7.onnx\",\n}\n\n\ndef get_onnx_input_name(model):\n    inputs = [node.name for node in model.graph.input]\n    initializer = [node.name for node in model.graph.initializer]\n\n    inputs = list(set(inputs) - set(initializer))\n    return inputs\n\n\ndef get_model_url(model_name):\n    return BASE_MODEL_URL + MODEL_URL_COLLECTION[model_name]\n\n\ndef get_name_from_url(url):\n    return url[url.rfind(\"/\") + 1 :].strip()\n\n\ndef find_of_download(model_name):\n    model_url = get_model_url(model_name)\n    model_file_name = get_name_from_url(model_url)\n    return download_testdata(model_url, model_file_name, module=\"models\")\n\n\ndef get_model(model_name):\n    model_path = find_of_download(model_name)\n    onnx_model = onnx.load(model_path)\n    input_names = get_onnx_input_name(onnx_model)\n    input_dict = {}\n    for name in input_names:\n        input_dict[name] = INPUT_SHAPE  # TODO: hardcode\n    mod, params = relay.frontend.from_onnx(onnx_model, input_dict, freeze_params=True)\n    return mod, params, input_dict\n\n\ndef simplify_model(mod):\n    \"\"\"\n    Simplify execution graph\n\n    At least merge BatchNorm into convolution. For this purpose decompose BN primitive\n    into simple operation which can be calculated as const expr and after that merged\n    into nearest conv/dense primitive.\n    \"\"\"\n    seq = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.FoldConstant(),\n            transform.SimplifyInference(),\n            transform.FoldScaleAxis(),\n        ]\n    )\n    return seq(mod)\n\n\ndef process(model_name):\n    temp = utils.tempdir()\n    model, params, input_dict = get_model(model_name)\n\n    def run(mod, target, simplify=True, with_bnns=False):\n        with tvm.transform.PassContext(opt_level=3):\n            if simplify:\n                mod = simplify_model(mod)\n            if with_bnns:\n                mod = partition_for_bnns(mod)\n            graph_module = relay.build(mod, target=target, params=params)\n\n        lib_name = \"deploy.tar\"\n        path_dso = temp.relpath(lib_name)\n        graph_module.export_library(path_dso)\n\n        dev = tvm.cpu(0)\n        loaded_lib = tvm.runtime.load_module(path_dso)\n\n        module = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        module.run()\n        return module.get_output(0).numpy()\n\n    res_llvm = run(model, TARGET, simplify=True, with_bnns=False)\n    res_bnns = run(model, TARGET, simplify=True, with_bnns=True)\n\n    tvm.testing.assert_allclose(\n        res_llvm,\n        res_bnns,\n        atol=0.002,\n        rtol=0.007,\n    )\n\n\n@pytest.mark.skip(reason=\"Manually disabled because of huge complexity\")\n@pytest.mark.skipif(bnns_is_absent, reason=\"BNNS runtime is absent\")\n@pytest.mark.parametrize(\"model_name\", MODEL_URL_COLLECTION.keys())\ndef test_topology(model_name):\n    process(model_name)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_bnns/test_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"BNNS integration pooling tests.\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm import testing\nfrom .infrastructure import (\n    skip_runtime_test,\n    skip_codegen_test,\n    build_and_run,\n    verify,\n    verify_codegen,\n)\nfrom .infrastructure import Device\n\n\ndef _calculate_output_shape(shape, sizes, padding, strides):\n    \"\"\"Calculate pooling output shape.\"\"\"\n    output_height = ((shape[2] - sizes[0] + padding[0] + padding[2]) / strides[0]) + 1\n    output_width = ((shape[3] - sizes[1] + padding[1] + padding[3]) / strides[1]) + 1\n    return 1, shape[1], int(output_height), int(output_width)\n\n\ndef _get_pooling_model(\n    shape, dtype, typef, sizes, strides, padding, ceil_mode, count_include_pad, var_names\n):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    if len(padding) == 2:\n        padding = (padding[0], padding[1], padding[0], padding[1])\n    out = relay.var(next(var_names), shape=shape, dtype=dtype)\n\n    if typef == \"nn.max_pool2d\":\n        out = relay.nn.max_pool2d(\n            out,\n            pool_size=sizes,\n            strides=strides,\n            padding=padding,\n            ceil_mode=ceil_mode,\n        )\n    elif typef == \"nn.avg_pool2d\":\n        out = relay.nn.avg_pool2d(\n            out,\n            pool_size=sizes,\n            strides=strides,\n            padding=padding,\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n        )\n    else:\n        raise ValueError(\"Function not supported\")\n\n    return out\n\n\ndef _get_global_pooling_model(shape, dtype, typef, var_names):\n    \"\"\"Return a model and any parameters it may have.\"\"\"\n    out = relay.var(next(var_names), shape=shape, dtype=dtype)\n\n    if typef == \"nn.global_max_pool2d\":\n        out = relay.nn.global_max_pool2d(out)\n    elif typef == \"nn.global_avg_pool2d\":\n        out = relay.nn.global_avg_pool2d(out)\n    else:\n        raise ValueError(\"Function not supported\")\n\n    return out\n\n\ndef _get_expected_pooling_codegen(\n    shape, dtype, typef, sizes, strides, padding, ceil_mode, count_include_pad\n):\n    if len(padding) == 2:\n        padding = (padding[0], padding[1], padding[0], padding[1])\n    output_shape = _calculate_output_shape(shape, sizes, padding, strides)\n\n    node = {\n        \"op\": \"kernel\",\n        \"name\": typef,\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n            \"layout\": [[\"NCHW\"]],\n            \"shape\": [[list(output_shape)]],\n            \"dtype\": [[dtype]],\n            \"padding\": [[str(p) for p in padding]],\n            \"strides\": [[str(s) for s in strides]],\n            \"pool_size\": [[str(s) for s in sizes]],\n            \"ceil_mode\": [[str(1 if ceil_mode else 0)]],\n        },\n    }\n\n    if typef == \"nn.avg_pool2d\" or typef == \"nn.l2_pool2d\":\n        node[\"attrs\"][\"count_include_pad\"] = [[\"1\" if count_include_pad else \"0\"]]\n\n    input = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    return [input, node]\n\n\ndef _get_expected_global_pooling_codegen(shape, dtype, typef):\n    node = {\n        \"op\": \"kernel\",\n        \"name\": typef,\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n            \"layout\": [[\"NCHW\"]],\n            \"shape\": [[[1, shape[1], 1, 1]]],\n            \"dtype\": [[dtype]],\n        },\n    }\n\n    input = {\"op\": \"input\", \"name\": \"\", \"attrs\": {\"shape\": [[list(shape)]], \"dtype\": [[dtype]]}}\n    return [input, node]\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_pooling():\n    device = Device()\n    np.random.seed(0)\n\n    dtype = \"float32\"\n    trials = [\n        [\"nn.max_pool2d\", (3, 3), (2, 2), (0, 0), False, False, (27, 27, 512)],\n        [\"nn.max_pool2d\", (2, 2), (2, 2), (0, 0), False, True, (16, 16, 16)],\n        [\"nn.max_pool2d\", (3, 3), (2, 2), (1, 1), True, True, (15, 15, 16)],\n        [\"nn.max_pool2d\", (2, 2), (2, 2), (0, 1), False, False, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (2, 2), (2, 2), (1, 1), False, False, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (2, 2), (2, 2), (0, 0), False, True, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (3, 3), (2, 2), (0, 1), True, False, (15, 15, 16)],\n    ]\n\n    for (\n        typef,\n        size,\n        stride,\n        pad,\n        ceil_mode,\n        count_include_pad,\n        input_shape,\n    ) in trials:\n        shape = (1, *input_shape)\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(-127, 128, shape).astype(dtype)),\n        }\n\n        func = _get_pooling_model(\n            shape, dtype, typef, size, stride, pad, ceil_mode, count_include_pad, iter(inputs)\n        )\n\n        config = {\n            \"size\": size,\n            \"stride\": stride,\n            \"shape\": shape,\n            \"pooling type\": typef,\n            \"dtype\": dtype,\n            \"padding\": pad,\n            \"ceil_mode\": ceil_mode,\n            \"count_include_pad\": count_include_pad,\n            \"inputs\": inputs,\n        }\n\n        params = None\n        for enable_bnns in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func, inputs, 1, params, device, enable_bnns=enable_bnns, config=config\n                )[0]\n            )\n\n        verify(outputs, atol=0.001, rtol=0.001, config=config)\n\n\n@pytest.mark.skipif(skip_runtime_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_global_pooling():\n    device = Device()\n    np.random.seed(0)\n\n    dtype = \"float32\"\n\n    trials = [\n        [\"nn.global_max_pool2d\", (8, 8, 16)],\n        [\"nn.global_max_pool2d\", (9, 9, 16)],\n        [\"nn.global_max_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (9, 9, 16)],\n    ]\n\n    for typef, input_shape in trials:\n        shape = (1, *input_shape)\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(-127, 128, shape).astype(dtype)),\n        }\n\n        func = _get_global_pooling_model(shape, dtype, typef, iter(inputs))\n        config = {\n            \"shape\": shape,\n            \"pooling type\": typef,\n            \"dtype\": dtype,\n        }\n\n        for enable_bnns in [False, True]:\n            outputs.append(\n                build_and_run(\n                    func, inputs, 1, None, device, enable_bnns=enable_bnns, config=config\n                )[0]\n            )\n\n        verify(outputs, atol=0.001, rtol=0.001, config=config)\n\n\n@pytest.mark.skipif(skip_codegen_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_codegen_pooling():\n    dtype = \"float32\"\n\n    trials = [\n        [\"nn.max_pool2d\", (2, 2), (2, 2), (0, 0), False, True, (16, 16, 16)],\n        [\"nn.max_pool2d\", (3, 3), (2, 2), (1, 1), True, True, (15, 15, 16)],\n        [\"nn.max_pool2d\", (2, 2), (2, 2), (0, 1), False, False, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (2, 2), (2, 2), (1, 1), False, False, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (2, 2), (2, 2), (0, 0), False, True, (16, 16, 16)],\n        [\"nn.avg_pool2d\", (3, 3), (2, 2), (0, 1), True, False, (15, 15, 16)],\n    ]\n\n    for (\n        typef,\n        size,\n        stride,\n        pad,\n        ceil_mode,\n        count_include_pad,\n        input_shape,\n    ) in trials:\n        shape = (1, *input_shape)\n        inputs = {\"a\"}\n        args = (shape, dtype, typef, size, stride, pad, False, False)\n        func = _get_pooling_model(*args, iter(inputs))\n        exp_codegen = _get_expected_pooling_codegen(*args)\n        verify_codegen(func, exp_codegen, 1)\n\n\n@pytest.mark.skipif(skip_codegen_test(), reason=\"Skip because BNNS codegen is not available\")\ndef test_codegen_global_pooling():\n    dtype = \"float32\"\n\n    trials = [\n        [\"nn.global_max_pool2d\", (8, 8, 16)],\n        [\"nn.global_max_pool2d\", (9, 9, 16)],\n        [\"nn.global_max_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (8, 8, 16)],\n        [\"nn.global_avg_pool2d\", (9, 9, 16)],\n    ]\n\n    for typef, input_shape in trials:\n        shape = (1, *input_shape)\n        inputs = {\"a\"}\n        args = (shape, dtype, typef)\n        func = _get_global_pooling_model(*args, iter(inputs))\n        exp_codegen = _get_expected_global_pooling_codegen(*args)\n        verify_codegen(func, exp_codegen, 1)\n\n\nif __name__ == \"__main__\":\n    test_pooling()\n    test_global_pooling()\n    test_codegen_pooling()\n    test_codegen_global_pooling()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cblas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\nimport numpy as np\nimport tvm.topi.testing\nfrom tvm.contrib import cblas\nfrom tvm.contrib import mkl\nfrom tvm.contrib import dnnl\nimport tvm.testing\n\n\ndef verify_matmul_add(m, l, n, lib, transa=False, transb=False, dtype=\"float32\"):\n    bias = te.var(\"bias\", dtype=dtype)\n    ashape = (l, n) if transa else (n, l)\n    bshape = (m, l) if transb else (l, m)\n    A = te.placeholder(ashape, name=\"A\", dtype=dtype)\n    B = te.placeholder(bshape, name=\"B\", dtype=dtype)\n    C = lib.matmul(A, B, transa, transb)\n    D = te.compute(C.shape, lambda i, j: C[i, j] + bias, name=\"D\")\n    s = te.create_schedule(D.op)\n\n    def get_numpy(a, b, bb, transa, transb):\n        if transa:\n            a = a.transpose()\n        if transb:\n            b = b.transpose()\n        return np.dot(a, b) + bb\n\n    def compile(f, name=\"test_matmul_add\", ext=\".so\"):\n        path = name + ext\n        f.export_library(path)\n        mod = tvm.runtime.load_module(path)\n        f = mod[name]\n        return f\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(lib.__name__ + \".matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        name = \"test_matmul_add\"\n        f = tvm.build(s, [A, B, D, bias], target, name=name)\n        if target == \"c\":\n            f = compile(f, name)\n        a = tvm.nd.array(np.random.uniform(size=ashape).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=bshape).astype(B.dtype), dev)\n        d = tvm.nd.array(np.zeros((n, m), dtype=D.dtype), dev)\n        bb = 10.0\n        f(a, b, d, bb)\n        tvm.testing.assert_allclose(\n            d.numpy(), get_numpy(a.numpy(), b.numpy(), bb, transa, transb), rtol=1e-5\n        )\n\n    verify(\"llvm\")\n    verify(\"c\")\n\n\ndef test_matmul_add():\n    verify_matmul_add(235, 128, 1024, cblas)\n    verify_matmul_add(235, 128, 1024, cblas, True, False)\n    verify_matmul_add(235, 128, 1024, cblas, False, True)\n    verify_matmul_add(235, 128, 1024, cblas, True, True)\n    verify_matmul_add(235, 128, 1024, mkl)\n    verify_matmul_add(235, 128, 1024, mkl, True, False)\n    verify_matmul_add(235, 128, 1024, mkl, False, True)\n    verify_matmul_add(235, 128, 1024, mkl, True, True)\n    verify_matmul_add(235, 128, 1024, dnnl)\n    verify_matmul_add(235, 128, 1024, dnnl, True, False)\n    verify_matmul_add(235, 128, 1024, dnnl, False, True)\n    verify_matmul_add(235, 128, 1024, dnnl, True, True)\n    verify_matmul_add(1, 16, 4, cblas)\n    verify_matmul_add(1, 16, 3, cblas, True, False)\n    verify_matmul_add(1, 16, 3, cblas, False, False)\n    verify_matmul_add(1, 16, 3, cblas, True, True)\n    verify_matmul_add(1, 16, 4, mkl)\n    verify_matmul_add(1, 16, 3, mkl, True, False)\n    verify_matmul_add(1, 16, 3, mkl, False, False)\n    verify_matmul_add(1, 16, 3, mkl, True, True)\n    verify_matmul_add(1, 16, 4, dnnl)\n    verify_matmul_add(1, 16, 3, dnnl, True, False)\n    verify_matmul_add(1, 16, 3, dnnl, False, False)\n    verify_matmul_add(1, 16, 3, dnnl, True, True)\n\n\ndef verify_quantized_matmul_add(m, l, n, transa=False, transb=False):\n    if not tvm.get_global_func(\"tvm.contrib.mkl.matmul_u8s8s32\", True):\n        pytest.skip(\"Quantized dense is supported only for MKL. TVM GPU CI uses openblas\")\n    data_dtype = \"uint8\"\n    kernel_dtype = \"int8\"\n    out_dtype = \"int32\"\n    bias = te.var(\"bias\", dtype=out_dtype)\n    ashape = (l, n) if transa else (n, l)\n    bshape = (m, l) if transb else (l, m)\n    A = te.placeholder(ashape, name=\"A\", dtype=data_dtype)\n    B = te.placeholder(bshape, name=\"B\", dtype=kernel_dtype)\n    C = mkl.matmul_u8s8s32(A, B, transa, transb, dtype=out_dtype)\n    D = te.compute(C.shape, lambda i, j: C[i, j] + bias, name=\"D\")\n    s = te.create_schedule(D.op)\n\n    def get_numpy(a, b, bb, transa, transb):\n        if transa:\n            a = a.transpose()\n        if transb:\n            b = b.transpose()\n        return np.dot(a, b) + bb\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(\"tvm.contrib.mkl.matmul_u8s8s32\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        f = tvm.build(s, [A, B, D, bias], target)\n        a = tvm.nd.array(np.random.randint(low=0, high=50, size=ashape).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.randint(low=0, high=50, size=bshape).astype(B.dtype), dev)\n        d = tvm.nd.array(np.zeros((n, m), dtype=D.dtype), dev)\n        bb = 10\n        f(a, b, d, bb)\n        tvm.testing.assert_allclose(\n            d.numpy(),\n            get_numpy(a.numpy().astype(\"int32\"), b.numpy().astype(\"int32\"), bb, transa, transb),\n            rtol=1e-5,\n        )\n\n    verify()\n\n\ndef test_quantized_matmul_add():\n    verify_quantized_matmul_add(235, 128, 1024)\n    verify_quantized_matmul_add(235, 128, 1024, True, False)\n    verify_quantized_matmul_add(235, 128, 1024, False, True)\n    verify_quantized_matmul_add(235, 128, 1024, True, True)\n    verify_quantized_matmul_add(1, 16, 4)\n    verify_quantized_matmul_add(1, 16, 3, True, False)\n    verify_quantized_matmul_add(1, 16, 3, False, True)\n    verify_quantized_matmul_add(1, 16, 3, True, True)\n\n\ndef verify_batch_matmul(\n    batch_a, batch_b, m, l, n, lib, transa=False, transb=False, iterative=False, dtype=\"float32\"\n):\n    batch = max(batch_a, batch_b)\n    ashape = (batch_a, l, n) if transa else (batch_a, n, l)\n    bshape = (batch_b, m, l) if transb else (batch_b, l, m)\n    A = te.placeholder(ashape, name=\"A\", dtype=dtype)\n    B = te.placeholder(bshape, name=\"B\", dtype=dtype)\n    C = lib.batch_matmul(A, B, transa, transb)\n    D = te.compute(C.shape, lambda k, i, j: C[k, i, j], name=\"D\")\n    s = te.create_schedule(D.op)\n\n    def get_numpy(a, b, transa, transb):\n        if transa:\n            a = a.transpose(0, 2, 1)\n        if not transb:\n            b = b.transpose(0, 2, 1)\n        return tvm.topi.testing.batch_matmul(a, b)\n\n    def compile(f, name=\"test_batch_matmul\", ext=\".so\"):\n        path = name + ext\n        f.export_library(path)\n        mod = tvm.runtime.load_module(path)\n        f = mod[name]\n        return f\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(lib.__name__ + \".matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        name = \"test_batch_matmul\"\n        f = tvm.build(s, [A, B, D], target, name=name)\n        if target == \"c\":\n            f = compile(f, name)\n        a = tvm.nd.array(np.random.uniform(size=ashape).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=bshape).astype(B.dtype), dev)\n        d = tvm.nd.array(np.zeros((batch, n, m), dtype=D.dtype), dev)\n        f(a, b, d)\n        tvm.testing.assert_allclose(\n            d.numpy(), get_numpy(a.numpy(), b.numpy(), transa, transb), rtol=1e-5\n        )\n\n    verify(\"llvm\")\n    verify(\"c\")\n\n\ndef test_batch_matmul():\n    verify_batch_matmul(16, 16, 235, 128, 1024, cblas)\n    verify_batch_matmul(16, 16, 235, 128, 1024, cblas, True, False)\n    verify_batch_matmul(16, 16, 235, 128, 1024, cblas, False, True)\n    verify_batch_matmul(16, 16, 235, 128, 1024, cblas, True, True)\n    verify_batch_matmul(16, 16, 235, 128, 1024, mkl)\n    verify_batch_matmul(16, 16, 235, 128, 1024, mkl, True, False)\n    verify_batch_matmul(16, 16, 235, 128, 1024, mkl, False, True)\n    verify_batch_matmul(16, 16, 235, 128, 1024, mkl, True, True)\n    verify_batch_matmul(16, 1, 235, 128, 1024, cblas)\n    verify_batch_matmul(1, 16, 235, 128, 1024, cblas)\n    verify_batch_matmul(16, 1, 235, 128, 1024, cblas, iterative=True)\n    verify_batch_matmul(1, 16, 235, 128, 1024, cblas, iterative=True)\n    verify_batch_matmul(16, 1, 235, 128, 1024, mkl)\n    verify_batch_matmul(1, 16, 235, 128, 1024, mkl)\n    verify_batch_matmul(16, 1, 235, 128, 1024, mkl, iterative=True)\n    verify_batch_matmul(1, 16, 235, 128, 1024, mkl, iterative=True)\n    verify_batch_matmul(1, 1, 1, 16, 3, cblas)\n    verify_batch_matmul(1, 1, 1, 16, 3, cblas, True, False)\n    verify_batch_matmul(1, 1, 1, 16, 3, cblas, False, False)\n    verify_batch_matmul(1, 1, 1, 16, 3, cblas, True, True)\n    verify_batch_matmul(1, 1, 1, 16, 3, cblas, iterative=True)\n    verify_batch_matmul(1, 1, 1, 16, 3, mkl)\n    verify_batch_matmul(1, 1, 1, 16, 3, mkl, True, False)\n    verify_batch_matmul(1, 1, 1, 16, 3, mkl, False, False)\n    verify_batch_matmul(1, 1, 1, 16, 3, mkl, True, True)\n    verify_batch_matmul(1, 1, 1, 16, 3, mkl, iterative=True)\n\n\nif __name__ == \"__main__\":\n    test_matmul_add()\n    test_quantized_matmul_add()\n    test_batch_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_clml/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for CLML\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_clml/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport tvm\nimport pytest\nfrom test_clml.infrastructure import Device\n\n\n@pytest.fixture(scope=\"session\")\ndef device():\n    return Device()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_clml/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom itertools import zip_longest, combinations\nimport json\nimport os\nimport warnings\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm import rpc\n\n# from tvm.contrib.debugger import debug_runtime as graph_executor\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.op.contrib import clml\nfrom tvm.contrib import utils\nfrom tvm import autotvm\nfrom tvm.autotvm.measure import request_remote\nfrom tvm.relay.expr_functor import ExprMutator, Call\n\n\nclass Device:\n    \"\"\"\n    Configuration for CLML tests.\n\n    Check tests/python/contrib/clml/ for the presence of an test_config.json file.\n    This file can be used to override the default configuration here which will attempt to run the Arm\n    Compute Library runtime tests locally if the runtime is available. Changing the configuration\n    will allow these runtime tests to be offloaded to a remote Arm device via a tracker for example.\n\n    Notes\n    -----\n        The test configuration will be loaded once when the the class is created. If the configuration\n        changes between tests, any changes will not be picked up.\n\n    Parameters\n    ----------\n    device : RPCSession\n        Allows tests to connect to and use remote device.\n\n    Attributes\n    ----------\n    connection_type : str\n        Details the type of RPC connection to use. Options:\n        local - Use the local device,\n        tracker - Connect to a tracker to request a remote device,\n        remote - Connect to a remote device directly.\n    host : str\n        Specify IP address or hostname of remote target.\n    port : int\n        Specify port number of remote target.\n    target : str\n        The compilation target.\n    device_key : str\n        The device key of the remote target. Use when connecting to a remote device via a tracker.\n    cross_compile : str\n        Specify path to cross compiler to use when connecting a remote device from a non-arm platform.\n    \"\"\"\n\n    connection_type = \"tracker\"\n    host = os.getenv(\"TVM_TRACKER_HOST\", \"localhost\")\n    port = int(os.getenv(\"TVM_TRACKER_PORT\", 9090))\n    target = \"opencl\"\n    target_host = \"llvm -mtriple=aarch64-linux-gnu\"\n    device_key = \"android\"\n    cross_compile = os.getenv(\"TVM_NDK_CC\", \"aarch64-linux-android-g++\")\n\n    def __init__(self):\n        \"\"\"Keep remote device for lifetime of object.\"\"\"\n        self.device = self._get_remote()\n\n    @classmethod\n    def _get_remote(cls):\n        \"\"\"Get a remote (or local) device to use for testing.\"\"\"\n        if cls.connection_type == \"tracker\":\n            device = request_remote(cls.device_key, cls.host, cls.port, timeout=1000)\n        elif cls.connection_type == \"remote\":\n            device = rpc.connect(cls.host, cls.port)\n        elif cls.connection_type == \"local\":\n            device = rpc.LocalSession()\n        else:\n            raise ValueError(\n                \"connection_type in test_config.json should be one of: \" \"local, tracker, remote.\"\n            )\n\n        return device\n\n\ndef skip_codegen_test():\n    \"\"\"Skip test if it requires the CLML codegen and it's not present.\"\"\"\n    if not tvm.get_global_func(\"relay.ext.clml\", True):\n        print(\"Skip because CLML codegen is not available.\")\n        return True\n\n\ndef build_module(mod, target, target_host, params=None, enable_clml=True, tune_log=\"\"):\n    \"\"\"Build module with option to build for CLML.\"\"\"\n    if isinstance(mod, tvm.relay.expr.Call):\n        mod = tvm.IRModule.from_expr(mod)\n\n    with autotvm.apply_history_best(tune_log):\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            if enable_clml:\n                mod = clml.partition_for_clml(mod, params)\n            relay.backend.te_compiler.get().clear()\n            return relay.build(mod, target=target, target_host=target_host, params=params)\n\n\ndef build_and_run(\n    mod, inputs, outputs, params, device, enable_clml=True, no_runs=1, config=None, tune_log=\"\"\n):\n    \"\"\"Build and run the relay module.\"\"\"\n    if config is None:\n        config = {}\n\n    try:\n        libm = build_module(mod, device.target, device.target_host, params, enable_clml, tune_log)\n\n        clml_modules = extract_clml_modules(libm)\n        for mod in clml_modules:\n            source = mod.get_source(\"json\")\n            codegen = json.loads(source)[\"nodes\"]\n            # remove input and const names as these cannot be predetermined\n            for node in range(len(codegen)):\n                if codegen[node][\"op\"] == \"input\" or codegen[node][\"op\"] == \"const\":\n                    codegen[node][\"name\"] = \"\"\n            codegen_str = json.dumps(codegen, sort_keys=True, indent=2)\n\n    except Exception as e:\n        err_msg = \"The module could not be built.\\n\"\n        if config:\n            err_msg += f\"The test failed with the following parameters: {config}\\n\"\n        err_msg += str(e)\n        raise Exception(err_msg)\n\n    lib = update_lib(libm, device.device, device.cross_compile)\n    gen_module = graph_executor.GraphModule(lib[\"default\"](device.device.cl(0)))\n    gen_module.set_input(**inputs)\n    out = []\n    for _ in range(no_runs):\n        gen_module.run()\n        out.append([gen_module.get_output(i) for i in range(outputs)])\n    time_f = gen_module.module.time_evaluator(\"run\", device.device.cl(0), number=1)\n    cost = time_f().mean\n    print(\"%g secs/iteration\\n\" % cost)\n    return out\n\n\ndef update_lib(lib, device, cross_compile):\n    \"\"\"Export the library to the remote/local device.\"\"\"\n    lib_name = \"mod.so\"\n    temp = utils.tempdir()\n    lib_path = temp.relpath(lib_name)\n    if cross_compile:\n        lib.export_library(lib_path, cc=cross_compile)\n    else:\n        lib.export_library(lib_path)\n    device.upload(lib_path)\n    lib = device.load_module(lib_name)\n    return lib\n\n\ndef extract_clml_modules(module):\n    \"\"\"Get the CLML module(s) from llvm module.\"\"\"\n    return list(filter(lambda mod: mod.type_key == \"clml\", module.get_lib().imported_modules))\n\n\ndef verify_codegen(\n    module,\n    known_good_codegen,\n    num_clml_modules=1,\n    tvm_ops=0,\n    target=\"llvm -mtriple=aarch64-linux-gnu\",\n):\n    \"\"\"Check clml codegen against a known good output.\"\"\"\n    module = build_module(module, target, tvm_ops=tvm_ops, clml_partitions=num_clml_modules)\n    clml_modules = extract_clml_modules(module)\n\n    assert len(clml_modules) == num_clml_modules, (\n        f\"The number of CLML modules produced ({len(clml_modules)}) does not \"\n        f\"match the expected value ({num_clml_modules}).\"\n    )\n\n    for mod in clml_modules:\n        source = mod.get_source(\"json\")\n        codegen = json.loads(source)[\"nodes\"]\n        # remove input and const names as these cannot be predetermined\n        for node in range(len(codegen)):\n            if codegen[node][\"op\"] == \"input\" or codegen[node][\"op\"] == \"const\":\n                codegen[node][\"name\"] = \"\"\n        codegen_str = json.dumps(codegen, sort_keys=True, indent=2)\n        known_good_codegen_str = json.dumps(known_good_codegen, sort_keys=True, indent=2)\n\n        assert codegen_str == known_good_codegen_str, (\n            f\"The JSON produced by codegen does not match the expected result. \\n\"\n            f\"Actual={codegen_str} \\n\"\n            f\"Expected={known_good_codegen_str}\"\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_clml/test_network.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"OpenCL ML network tests.\"\"\"\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import utils\nfrom test_clml.infrastructure import build_and_run, Device\nimport pytest\n\n\ndef _build_and_run_network(mod, params, inputs, data, device, atol, rtol, tvm_log=\"\"):\n    \"\"\"Helper function to build and run a network.\"\"\"\n\n    outputs = []\n    for clml in [True, False]:\n        outputs.append(\n            build_and_run(mod, data, 1, params, device, enable_clml=clml, tune_log=tvm_log)[0][0]\n        )\n    return outputs\n\n\ndef _get_keras_model(keras_model, inputs_dict, data):\n    \"\"\"Convert Keras graph to relay.\"\"\"\n    inputs = {}\n    for name, (shape, _) in inputs_dict.items():\n        inputs[keras_model.input_names[0]] = shape\n\n    from tensorflow.keras.layers import Input\n    from tensorflow.keras.models import Model\n\n    def get_bottom_top_model(model, layer_name):\n        layer = model.get_layer(layer_name)\n        bottom_input = model.layers[0].input\n        bottom_output = layer.output\n        bottom_model = Model(bottom_input, bottom_output)\n        return bottom_model\n\n    keras_model = get_bottom_top_model(keras_model, \"predictions\")\n    ref_output = keras_model.predict(data[\"input_1\"].transpose(0, 2, 3, 1))\n\n    mod, params = relay.frontend.from_keras(keras_model, inputs, layout=\"NCHW\")\n    return mod, params, ref_output\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef test_mobilenet(device, dtype):\n    def get_model():\n        from tensorflow.keras.applications import MobileNet\n        import tensorflow as tf\n\n        tf.keras.backend.clear_session()\n\n        mobilenet = MobileNet(\n            include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000\n        )\n        inputs = {mobilenet.input_names[0]: ((1, 3, 224, 224), \"float32\")}\n\n        data = {}\n        np.random.seed(0)\n\n        for name, (shape, dtype) in inputs.items():\n            if dtype == \"uint8\":\n                low, high = 0, 1\n            else:\n                low, high = -1, 1\n            data[name] = np.random.uniform(low, high, shape).astype(dtype)\n\n        mod, params, ref_outputs = _get_keras_model(mobilenet, inputs, data)\n        return mod, params, inputs, data, ref_outputs\n\n    mod, params, inputs, input_data, ref_outputs = get_model()\n    outputs = _build_and_run_network(\n        mod, params, inputs, input_data, device=device, atol=1e-5, rtol=1e-5\n    )\n\n    # test\n    print(\"OpenCL:\", outputs[0].asnumpy().shape)\n    print(\"CLML:\", outputs[1].asnumpy().shape)\n\n    opencl_sort = np.argsort(outputs[1].asnumpy()).flatten()\n    clml_sort = np.argsort(outputs[0].asnumpy()).flatten()\n\n    tvm.testing.assert_allclose(opencl_sort[:10], clml_sort[:10], rtol=1e-5, atol=1e-5)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef test_inception_v3(device, dtype):\n    def get_model():\n        from tensorflow.keras.applications import InceptionV3\n        import tensorflow as tf\n\n        tf.keras.backend.clear_session()\n\n        inceptionV3 = InceptionV3(\n            include_top=True, weights=None, input_shape=(299, 299, 3), classes=1000\n        )\n        inputs = {inceptionV3.input_names[0]: ((1, 3, 299, 299), \"float16\")}\n\n        data = {}\n        np.random.seed(0)\n        for name, (shape, dtype) in inputs.items():\n            if dtype == \"uint8\":\n                low, high = 0, 1\n            else:\n                low, high = -2, 1\n            data[name] = np.random.uniform(low, high, shape).astype(dtype)\n\n        mod, params, ref_outputs = _get_keras_model(inceptionV3, inputs, data)\n        return mod, params, inputs, data, ref_outputs\n\n    mod, params, inputs, input_data, ref_outputs = get_model()\n    outputs = _build_and_run_network(\n        mod, params, inputs, input_data, device=device, atol=1e-5, rtol=1e-5\n    )\n\n    opencl_sort = np.argsort(outputs[1].asnumpy()).flatten()\n    clml_sort = np.argsort(outputs[0].asnumpy()).flatten()\n\n    tvm.testing.assert_allclose(opencl_sort[:5], clml_sort[:5], rtol=1e-5, atol=1e-5)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef test_resnet50v2(device, dtype):\n    def get_model():\n        from tensorflow.keras.applications import ResNet50V2\n        import tensorflow as tf\n\n        tf.keras.backend.clear_session()\n\n        model = ResNet50V2(include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000)\n        inputs_dict = {model.input_names[0]: ((1, 3, 224, 224), \"float32\")}\n\n        data = {}\n        np.random.seed(0)\n\n        for name, (shape, dtype) in inputs_dict.items():\n            if dtype == \"uint8\":\n                low, high = 0, 1\n            else:\n                low, high = -1, 1\n            data[name] = np.random.uniform(low, high, shape).astype(dtype)\n\n        \"\"\"Convert Keras graph to relay.\"\"\"\n        inputs = {}\n        for name, (shape, _) in inputs_dict.items():\n            inputs[model.input_names[0]] = shape\n\n        ref_outputs = model.predict(data[\"input_1\"].transpose(0, 2, 3, 1))\n\n        mod, params = relay.frontend.from_keras(model, inputs, layout=\"NCHW\")\n\n        return mod, params, inputs, data, ref_outputs\n\n    mod, params, inputs, input_data, ref_outputs = get_model()\n    outputs = _build_and_run_network(\n        mod, params, inputs, input_data, device=device, atol=1e-5, rtol=1e-5\n    )\n\n    # test\n    print(\"OpenCL:\", outputs[0].asnumpy().shape)\n    print(\"CLML:\", outputs[1].asnumpy().shape)\n\n    opencl_sort = np.argsort(outputs[1].asnumpy()).flatten()\n    clml_sort = np.argsort(outputs[0].asnumpy()).flatten()\n\n    tvm.testing.assert_allclose(opencl_sort[:10], clml_sort[:10], rtol=1e-5, atol=1e-5)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_clml/test_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"CLML integration conv2d tests.\"\"\"\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.ir import IRModule\nfrom tvm.contrib import utils\nfrom test_clml.infrastructure import build_and_run, Device, skip_codegen_test\nimport pytest\n\n\ndef _get_conv_model(\n    shape,\n    kernel_h,\n    kernel_w,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    channels,\n    var,\n    has_bias=False,\n    has_activation=False,\n    has_pad=False,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(next(iter(var)), shape=shape, dtype=dtype)\n    input_arr = var[next(iter(var))]\n    if has_pad:\n        p = ((0, 0), (padding[0], padding[0]), (padding[1], padding[1]), (0, 0))\n        a = relay.nn.pad(a, pad_width=p)\n        padding = (0, 0, 0, 0)\n    else:\n        if len(padding) == 2:\n            padding = (padding[0], padding[1], padding[0], padding[1])\n        shape = (shape[0], shape[1], shape[2] + padding[0] * 2, shape[3] + padding[1] * 2)\n    is_depthwise = shape[1] == channels == groups\n\n    weight_format = \"OIHW\" if is_depthwise else \"OIHW\"\n    if weight_format == \"IOHW\":\n        weight_shape = (shape[1] // groups, channels, kernel_h, kernel_w)\n    else:\n        weight_shape = (channels, shape[1] // groups, kernel_h, kernel_w)\n\n    w = tvm.nd.array(np.random.uniform(-1, 1, weight_shape).astype(dtype))\n    weights = relay.const(w, dtype)\n    out = relay.nn.conv2d(\n        a,\n        weights,\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NCHW\",\n        kernel_layout=weight_format,\n        dilation=dilation,\n        strides=strides,\n        padding=padding,\n        groups=groups,\n        channels=channels,\n        out_dtype=dtype,\n    )\n    params = {\"w\": w}\n    if has_bias:\n        bias_shape = weight_shape[2] if is_depthwise else weight_shape[0]\n        b = tvm.nd.array(np.random.uniform(-1, 1, bias_shape).astype(dtype))\n        biasc = relay.const(b, dtype)\n        out = relay.nn.bias_add(out, biasc, axis=1)\n        params[\"b\"] = b\n\n    if has_activation:\n        out = relay.nn.relu(out)\n\n    print(\"Out:\", out)\n\n    return out, params\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float32\"])\n@tvm.testing.requires_openclml\ndef test_conv2d(device, dtype):\n    trials = [\n        # Normal convolution\n        [3, 3, (1, 1), (1, 1), (1, 1), 4, (14, 10, 10), (False, False, False)],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (15, 16, 12), (False, False, True)],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (14, 10, 10), (False, True, False)],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (14, 10, 10), (False, True, True)],\n        # Normal convolution\n        [2, 2, (1, 1), (1, 1), (1, 1), 4, (14, 10, 10), (False, False, False)],\n        [2, 1, (2, 2), (1, 1), (1, 1), 7, (16, 12, 15), (False, False, True)],\n        [3, 3, (2, 1), (1, 1), (1, 1), 4, (14, 10, 10), (False, True, False)],\n        [3, 3, (1, 1), (1, 1), (1, 1), 16, (16, 12, 15), (False, False, False)],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (14, 10, 10), (False, False, False)],\n        [1, 3, (1, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, True)],\n        [2, 2, (2, 2), (1, 1), (1, 1), 4, (20, 20, 20), (False, True, False)],\n        [5, 5, (1, 1), (2, 2), (1, 1), 4, (14, 10, 10), (False, False, False)],\n        [3, 3, (2, 1), (1, 1), (1, 1), 7, (20, 20, 20), (False, False, False)],\n        [3, 3, (1, 1), (2, 2), (1, 1), 16, (14, 10, 10), (False, True, True)],\n    ]\n\n    for (\n        kernel_h,\n        kernel_w,\n        pad,\n        stride,\n        dilation,\n        out_channels,\n        shape,\n        composite,\n    ) in trials:\n        shape = (1, *shape)\n        groups = 1\n        outputs = []\n        inputs = {\n            \"a\": tvm.nd.array(np.random.uniform(-1, 1, shape).astype(dtype)),\n        }\n\n        func, params = _get_conv_model(\n            shape,\n            kernel_h,\n            kernel_w,\n            pad,\n            stride,\n            dilation,\n            groups,\n            dtype,\n            out_channels,\n            inputs,\n            has_pad=composite[0],\n            has_bias=composite[1],\n            has_activation=composite[2],\n        )\n        opencl_out = build_and_run(func, inputs, 1, params, device, enable_clml=False)[0]\n        clml_out = build_and_run(func, inputs, 1, params, device, enable_clml=True)[0]\n\n        tvm.testing.assert_allclose(\n            clml_out[0].asnumpy(), opencl_out[0].asnumpy(), rtol=1e-5, atol=1e-5\n        )\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef _test_batchnorm(device, dtype):\n    in_shape = (1, 8, 64, 64)\n    channels = 8\n\n    input_arr = tvm.nd.array(np.random.uniform(-1, 1, in_shape).astype(dtype))\n    inp = relay.var(\"a\", shape=in_shape, dtype=dtype)\n    gamma_arr = tvm.nd.array(np.random.uniform(-1, 1, (channels)).astype(dtype))\n    beta_arr = tvm.nd.array(np.random.uniform(-1, 1, (channels)).astype(dtype))\n    gamma = relay.const(gamma_arr, dtype)\n    beta = relay.const(beta_arr, dtype)\n\n    mean_arr = tvm.nd.array(np.mean(input_arr.asnumpy(), axis=(0, 2, 3), keepdims=False))\n    mean = relay.const(mean_arr)\n    variance_arr = tvm.nd.array(np.var(input_arr.asnumpy(), axis=(0, 2, 3), keepdims=False))\n    variance = relay.const(variance_arr)\n\n    params = {}\n\n    func = relay.nn.batch_norm(inp, gamma, beta, mean, variance, axis=1, epsilon=0.0001)[0]\n    mod = IRModule.from_expr(func)\n\n    inputs = {\n        \"a\": input_arr,\n    }\n\n    opencl_out = build_and_run(mod, inputs, 1, params, device, enable_clml=False)[0]\n    clml_out = build_and_run(mod, inputs, 1, params, device, enable_clml=True)[0]\n\n    tvm.testing.assert_allclose(\n        clml_out[0].asnumpy(), opencl_out[0].asnumpy(), rtol=1e-5, atol=1e-5\n    )\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef test_concat(device, dtype):\n    in_shape_1 = (1, 16, 16, 16)\n    in_shape_2 = (1, 16, 16, 16)\n    a = relay.var(\"input_1\", shape=in_shape_1, dtype=dtype)\n    b = relay.var(\"input_2\", shape=in_shape_2, dtype=dtype)\n    low, high = -1, 1\n    inputs = {\n        \"input_1\": tvm.nd.array(np.random.uniform(-1, 1, in_shape_1).astype(dtype)),\n        \"input_2\": tvm.nd.array(np.random.uniform(-1, 1, in_shape_2).astype(dtype)),\n    }\n\n    params = {}\n    func = relay.concatenate((a, b), axis=1)\n    mod = IRModule.from_expr(func)\n\n    opencl_out = build_and_run(mod, inputs, 1, params, device, enable_clml=False)[0]\n    clml_out = build_and_run(mod, inputs, 1, params, device, enable_clml=True)[0]\n\n    tvm.testing.assert_allclose(\n        clml_out[0].asnumpy(), opencl_out[0].asnumpy(), rtol=1e-3, atol=1e-3\n    )\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\"])\n@tvm.testing.requires_openclml\ndef test_avgpool(device, dtype):\n    trials = [\n        # input size         pool_size stride  paading\n        [(1, 64, 147, 147), (3, 3), (2, 2), (0, 0, 0, 0), \"max\"],\n        [(1, 192, 71, 71), (3, 3), (2, 2), (0, 0, 0, 0), \"max\"],\n        [(1, 288, 35, 35), (3, 3), (2, 2), (0, 0, 0, 0), \"max\"],\n        [(1, 768, 17, 17), (3, 3), (2, 2), (0, 0, 0, 0), \"max\"],\n        [(1, 2048, 17, 17), (3, 3), (2, 2), (0, 0, 0, 0), \"max\"],\n        [(1, 192, 35, 35), (3, 3), (1, 1), (0, 0, 1, 1), \"avg\"],\n        [(1, 256, 35, 35), (3, 3), (1, 1), (0, 0, 1, 1), \"avg\"],\n        [(1, 288, 35, 35), (3, 3), (1, 1), (0, 0, 1, 1), \"avg\"],\n        [(1, 768, 17, 17), (3, 3), (1, 1), (0, 0, 1, 1), \"avg\"],\n        [(1, 1280, 8, 8), (3, 3), (1, 1), (0, 0, 1, 1), \"avg\"],\n    ]\n    params = {}\n    for (\n        input_shape,\n        pool_size,\n        stride,\n        padding,\n        pooling_type,\n    ) in trials:\n        a = relay.var(\"input_1\", shape=input_shape, dtype=dtype)\n        input_arr = tvm.nd.array(np.random.uniform(-1, 1, input_shape).astype(dtype))\n        inputs = {\n            \"input_1\": input_arr,\n        }\n\n        if pooling_type == \"max\":\n            func = relay.nn.max_pool2d(a, pool_size=pool_size, strides=stride, padding=padding)\n        else:\n            func = relay.nn.avg_pool2d(a, pool_size=pool_size, strides=stride, padding=padding)\n        mod = IRModule.from_expr(func)\n\n        opencl_out = build_and_run(mod, inputs, 1, params, device, enable_clml=False)[0]\n        clml_out = build_and_run(mod, inputs, 1, params, device, enable_clml=True)[0]\n\n        tvm.testing.assert_allclose(\n            clml_out[0].asnumpy(), opencl_out[0].asnumpy(), rtol=1e-3, atol=1e-3\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for CMSIS-NN\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_binary_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: binary ops\"\"\"\n\nimport itertools\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\nfrom tvm.testing.aot import generate_ref_data, AOTTestModel, compile_and_run\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_USMP_CORSTONE300_RUNNER,\n)\n\nfrom .utils import (\n    skip_if_no_reference_system,\n    make_module,\n    make_qnn_relu,\n    get_range_for_dtype_str,\n    assert_partitioned_function,\n    assert_no_external_function,\n    create_test_runner,\n)\n\n\ndef generate_tensor_constant():\n    rng = np.random.default_rng(12321)\n    dtype = \"int8\"\n    shape = (1, 16, 16, 3)\n    values = tvm.nd.array(\n        rng.integers(np.iinfo(dtype).min, high=np.iinfo(dtype).max, size=shape, dtype=dtype)\n    )\n    return relay.const(values, dtype)\n\n\ndef generate_scalar_constant():\n    dtype = \"int8\"\n    return relay.const(-30, dtype)\n\n\ndef generate_variable(name, dtype=\"int8\"):\n    return relay.var(name, shape=(1, 16, 16, 3), dtype=dtype)\n\n\ndef make_model(\n    op,\n    input_0,\n    input_1,\n    input_0_scale,\n    input_0_zero_point,\n    input_1_scale,\n    input_1_zero_point,\n    relu_type=\"NONE\",\n    out_scale=1.0 / 256,\n    out_zero_point=-128,\n):\n    \"\"\"Create a Relay Function / network model\"\"\"\n    binary_op = op(\n        input_0,\n        input_1,\n        relay.const(input_0_scale, \"float32\"),\n        relay.const(input_0_zero_point, \"int32\"),\n        relay.const(input_1_scale, \"float32\"),\n        relay.const(input_1_zero_point, \"int32\"),\n        relay.const(out_scale, \"float32\"),\n        relay.const(out_zero_point, \"int32\"),\n    )\n    return make_qnn_relu(binary_op, relu_type, out_scale, out_zero_point, \"int8\")\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.qnn.op.mul, relay.qnn.op.add])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\", \"NONE\"])\n@pytest.mark.parametrize(\n    [\n        \"input_0_scale\",\n        \"input_0_zero_point\",\n        \"input_1_scale\",\n        \"input_1_zero_point\",\n    ],\n    [[0.256, 33, 0.256, 33], [0.0128, -64, 0.0128, -64], [0.0128, -64, 0.256, 33]],\n)\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_op_int8(\n    op,\n    relu_type,\n    input_0_scale,\n    input_0_zero_point,\n    input_1_scale,\n    input_1_zero_point,\n    compiler_cpu,\n    cpu_flags,\n):\n    \"\"\"Tests QNN binary operator for CMSIS-NN\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    dtype = \"int8\"\n    shape = [1, 16, 16, 3]\n    model = make_model(\n        op,\n        generate_variable(\"input_0\"),\n        generate_variable(\"input_1\"),\n        input_0_scale,\n        input_0_zero_point,\n        input_1_scale,\n        input_1_zero_point,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    inputs = {\n        \"input_0\": np.random.randint(in_min, high=in_max, size=shape, dtype=dtype),\n        \"input_1\": np.random.randint(in_min, high=in_max, size=shape, dtype=dtype),\n    }\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            output_tolerance=1,\n        ),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.qnn.op.mul, relay.qnn.op.add])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\", \"NONE\"])\ndef test_same_input_to_binary_op(op, relu_type):\n    \"\"\"Tests QNN binary operator for CMSIS-NN where both inputs are the same\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    dtype = \"int8\"\n    shape = [1, 16, 16, 3]\n    input_ = generate_variable(\"input\")\n    input_scale = 0.256\n    input_zero_point = 33\n\n    model = make_model(\n        op,\n        input_,\n        input_,\n        input_scale,\n        input_zero_point,\n        input_scale,\n        input_zero_point,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # Check if the number of internal function parameter is 1\n    cmsisnn_global_func = cmsisnn_mod[\"tvmgen_default_cmsis_nn_main_0\"]\n    assert (\n        isinstance(cmsisnn_global_func.body, tvm.relay.expr.Call)\n        and len(cmsisnn_global_func.body.args) == 1\n    ), \"Composite function for the binary op should have only 1 parameter.\"\n\n    # validate the output\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    inputs = {\n        \"input\": np.random.randint(in_min, high=in_max, size=shape, dtype=dtype),\n    }\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef parameterize_for_constant_inputs(test):\n    \"\"\"Generates parameters in such a way so that at least one of the inputs is a constant,\n    both can't be variables, both can't be scalars.\n    \"\"\"\n    op = [relay.qnn.op.mul, relay.qnn.op.add]\n    input_0 = [generate_variable(\"input_0\"), generate_tensor_constant(), generate_scalar_constant()]\n    input_1 = [generate_variable(\"input_1\"), generate_tensor_constant(), generate_scalar_constant()]\n    all_combinations = itertools.product(op, input_0, input_1)\n    all_combinations = filter(\n        lambda parameters: not (\n            (\n                isinstance(parameters[1], tvm.relay.expr.Var)\n                and isinstance(parameters[2], tvm.relay.expr.Var)\n            )\n            or (\n                isinstance(parameters[1], tvm.relay.expr.Constant)\n                and isinstance(parameters[2], tvm.relay.expr.Constant)\n                and parameters[1].data.numpy().ndim == 0\n                and parameters[2].data.numpy().ndim == 0\n            )\n        ),\n        all_combinations,\n    )\n    return pytest.mark.parametrize(\n        [\"op\", \"input_0\", \"input_1\"],\n        all_combinations,\n    )(test)\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@parameterize_for_constant_inputs\ndef test_constant_input_int8(op, input_0, input_1):\n    \"\"\"Tests binary ops where one of the operands is a constant\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    dtype = \"int8\"\n    shape = [1, 16, 16, 3]\n    input_0_scale = 0.256\n    input_0_zero_point = 33\n    input_1_scale = 0.128\n    input_1_zero_point = -24\n    model = make_model(\n        op,\n        input_0,\n        input_1,\n        input_0_scale,\n        input_0_zero_point,\n        input_1_scale,\n        input_1_zero_point,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    inputs = {}\n    if isinstance(input_0, tvm.relay.expr.Var):\n        inputs.update({\"input_0\": np.random.randint(in_min, high=in_max, size=shape, dtype=dtype)})\n    if isinstance(input_1, tvm.relay.expr.Var):\n        inputs.update({\"input_1\": np.random.randint(in_min, high=in_max, size=shape, dtype=dtype)})\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.qnn.op.mul, relay.qnn.op.add])\ndef test_both_scalar_inputs_int8(\n    op,\n):\n    \"\"\"Tests binary ops where both operands are scalars\"\"\"\n    input_scale = 0.256\n    input_zero_point = 33\n    model = make_model(\n        op,\n        generate_scalar_constant(),\n        generate_scalar_constant(),\n        input_scale,\n        input_zero_point,\n        input_scale,\n        input_zero_point,\n    )\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.qnn.op.mul, relay.qnn.op.add])\n@pytest.mark.parametrize([\"input_dtype\"], [[\"uint8\"], [\"int16\"]])\ndef test_invalid_parameters(\n    op,\n    input_dtype,\n):\n    \"\"\"Tests binary ops for non int8 dtypes\"\"\"\n    input_scale = 0.256\n    input_zero_point = 33\n    model = make_model(\n        op,\n        generate_variable(\"input_0\", input_dtype),\n        generate_variable(\"input_1\", input_dtype),\n        input_scale,\n        input_zero_point,\n        input_scale,\n        input_zero_point,\n    )\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Conv2D\"\"\"\nimport itertools\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\n\nfrom tvm.testing.aot import (\n    generate_ref_data,\n    AOTTestModel,\n    compile_models,\n    compile_and_run,\n    run_and_check,\n)\nfrom tvm.micro.testing.aot_test_utils import AOT_USMP_CORSTONE300_RUNNER\nfrom .utils import (\n    make_module,\n    get_range_for_dtype_str,\n    get_same_padding,\n    get_conv2d_qnn_params,\n    get_kernel_bias_dtype,\n    make_qnn_relu,\n    assert_partitioned_function,\n    assert_no_external_function,\n    create_test_runner,\n    CheckForPadsWithinCompositeFunc,\n)\n\n\ndef make_model(\n    shape,\n    kernel_shape,\n    input_zero_point,\n    input_scale,\n    kernel_zero_point,\n    kernel_scale,\n    output_zero_point,\n    output_scale,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    kernel_dtype,\n    bias_dtype,\n    out_channels,\n    kernel_layout,\n    enable_bias,\n    relu_type,\n    input_op=None,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    if input_op:\n        op = input_op\n    else:\n        op = relay.var(\"input\", shape=shape, dtype=dtype)\n\n    h_index = kernel_layout.index(\"H\")\n    w_index = kernel_layout.index(\"W\")\n    kernel_h = kernel_shape[h_index]\n    kernel_w = kernel_shape[w_index]\n    p = (0, 0, 0, 0)\n    if padding == \"SAME\":\n        p = get_same_padding((shape[1], shape[2]), (kernel_h, kernel_w), dilation, strides)\n\n    rng = np.random.default_rng(12321)\n    kernel = tvm.nd.array(\n        rng.integers(\n            np.iinfo(kernel_dtype).min,\n            high=np.iinfo(kernel_dtype).max,\n            size=kernel_shape,\n            dtype=kernel_dtype,\n        )\n    )\n    kernel_const = relay.const(kernel, kernel_dtype)\n    conv2d_kernel_sc = kernel_scale[0] if out_channels == 1 else kernel_scale\n    conv = relay.qnn.op.conv2d(\n        op,\n        kernel_const,\n        input_zero_point=relay.const(input_zero_point, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zero_point, \"int32\"),\n        input_scale=relay.const(input_scale, \"float32\"),\n        kernel_scale=relay.const(conv2d_kernel_sc, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=kernel_layout,\n        dilation=dilation,\n        strides=strides,\n        groups=groups,\n        channels=out_channels,\n        padding=p,\n        out_dtype=bias_dtype,\n    )\n    bias = tvm.nd.array(rng.integers(0, high=10, size=(out_channels,), dtype=bias_dtype))\n    bias_const = relay.const(bias, bias_dtype)\n    last_op = relay.nn.bias_add(conv, bias_const, axis=3) if enable_bias else conv\n    requant_input_sc = [sc * input_scale for sc in kernel_scale]\n    requant_input_sc = requant_input_sc[0] if out_channels == 1 else requant_input_sc\n    last_op = relay.qnn.op.requantize(\n        last_op,\n        relay.const(requant_input_sc, \"float32\"),\n        relay.const(0, \"int32\"),\n        relay.const(output_scale, \"float32\"),\n        relay.const(output_zero_point, \"int32\"),\n        out_dtype=dtype,\n    )\n    last_op = make_qnn_relu(last_op, relu_type, output_scale, output_zero_point, dtype)\n    params = {\"w\": kernel, \"b\": bias}\n    return last_op, params\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"enable_bias\", [True, False])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale, out_channels\",\n    [(10, 0.0128, [0.11, 0.22], 2)],\n)\ndef test_conv2d_number_primfunc_args(\n    padding,\n    enable_bias,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n):\n    \"\"\"Tests number of arguments in Conv2D primfunc\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    ifm_shape = (1, 64, 100, 4)\n    kernel_size = (3, 3)\n    strides = (1, 1)\n    dilation = (1, 1)\n    dtype = \"int8\"\n    groups = 1\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    relu_type = \"RELU\"\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # compile the model\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n\n    compiled_models = compile_models(\n        AOTTestModel(module=cmsisnn_mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api,\n        use_unpacked_api,\n    )\n\n    # validate number of TIR primfunc args\n    expected_num_params = 6 if enable_bias else 5\n    cmsisnn_tir_mod = None\n    for target, mod in compiled_models[0].executor_factory.lowered_ir_mods.items():\n        if target.kind.name == \"cmsis-nn\":\n            cmsisnn_tir_mod = mod\n\n    cmsisnn_func = cmsisnn_tir_mod[\"tvmgen_default_cmsis_nn_main_0\"]\n    assert (\n        len(cmsisnn_func.params) == expected_num_params\n    ), \"Generated unexpected number of function arguments.\"\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"int16\"])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\"])\n@pytest.mark.parametrize(\"enable_bias\", [True, False])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale, out_channels\",\n    [(10, 0.0128, [0.11, 0.22], 2), (-64, 1, [1, 0.0256, 1.37], 3)],\n)\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_conv2d_symmetric_padding(\n    dtype,\n    padding,\n    enable_bias,\n    relu_type,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n    compiler_cpu,\n    cpu_flags,\n):\n    \"\"\"Tests QNN Conv2D where the padding is symmetric on both sides of input\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    ifm_shape = (1, 64, 100, 4)\n    kernel_size = (3, 3)\n    strides = (1, 1)\n    dilation = (1, 1)\n    groups = 1\n    # input_zero_point is not handled by TFLM when int16\n    input_zero_point = input_zero_point if dtype == \"int8\" else 0\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\", \"NONE\"])\n@pytest.mark.parametrize(\"enable_bias\", [True, False])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale, out_channels\",\n    [(10, 0.0128, [0.11, 0.22], 2), (-64, 1, [1, 0.0256, 1.37], 3)],\n)\ndef test_conv2d_asymmetric_padding(\n    padding,\n    enable_bias,\n    relu_type,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n):\n    \"\"\"Tests QNN Conv2D where the padding is asymmetric on different sides of input\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    dtype = \"int8\"\n    ifm_shape = (1, 25, 25, 12)\n    kernel_size = (5, 5)\n    strides = (2, 2)\n    dilation = (1, 1)\n    groups = 1\n    input_zero_point = input_zero_point if dtype == \"int8\" else 0\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 25, 25, 12), (1, 64, 100, 4)])\n@pytest.mark.parametrize(\n    \"pad_width\",\n    [\n        ((0, 0), (0, 1), (1, 2), (0, 0)),\n        ((0, 0), (1, 1), (1, 1), (0, 0)),\n        ((0, 0), (2, 2), (3, 4), (0, 0)),\n    ],\n)\ndef test_pad_conv2d_fusion_int8(\n    ifm_shape,\n    pad_width,\n):\n    \"\"\"Tests QNN Conv2D where the padding is asymmetric on different sides of input\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    ifm_shape = (1, 25, 25, 12)\n    kernel_size = (5, 5)\n    strides = (2, 2)\n    dilation = (1, 1)\n    padding = \"SAME\"\n    dtype = \"int8\"\n    enable_bias = True\n    relu_type = \"NONE\"\n    input_zero_point = 10\n    input_scale = 0.0128\n    kernel_scale = [0.11, 0.22]\n    out_channels = 2\n    groups = 1\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n    )\n\n    invar = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n    pad = relay.nn.pad(\n        invar,\n        pad_width=pad_width,  # ((), (top, bottom), (left, right), ())\n        pad_value=input_zero_point,\n        pad_mode=\"constant\",\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n        input_op=pad,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod, False)\n\n    # check pad is not present inside CMSIS-NN partitioned function\n    cmsisnn_func = None\n    for var in cmsisnn_mod.get_global_vars():\n        if \"cmsis_nn_main_0\" in var.name_hint:\n            cmsisnn_func = cmsisnn_mod[var]\n            pad_verifier = CheckForPadsWithinCompositeFunc()\n            pad_verifier.visit_function(cmsisnn_func)\n            pad_verifier.assert_no_pads_within_func()\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\n    \"ifm_shape, pad_width, conv2d_padding\",\n    [\n        [(1, 25, 25, 12), ((0, 0), (0, 2), (1, 2), (0, 0)), \"SAME\"],\n        [(1, 64, 100, 4), ((0, 0), (1, 3), (1, 1), (0, 0)), \"VALID\"],\n        [(1, 55, 55, 3), ((0, 0), (2, 1), (3, 5), (0, 0)), \"SAME\"],\n    ],\n)\ndef test_invalid_pad_conv2d_fusion_int8(\n    ifm_shape,\n    pad_width,\n    conv2d_padding,\n):\n    \"\"\"Tests QNN Conv2D where the padding is asymmetric on different sides of input\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    ifm_shape = (1, 25, 25, 12)\n    kernel_size = (5, 5)\n    strides = (2, 2)\n    dilation = (1, 1)\n    dtype = \"int8\"\n    enable_bias = True\n    relu_type = \"NONE\"\n    input_zero_point = 10\n    input_scale = 0.0128\n    kernel_scale = [0.11, 0.22]\n    out_channels = 2\n    groups = 1\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n    )\n\n    invar = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n    pad = relay.nn.pad(\n        invar,\n        pad_width=pad_width,  # ((), (top, bottom), (left, right), ())\n        pad_value=input_zero_point,\n        pad_mode=\"constant\",\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        conv2d_padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n        input_op=pad,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # check pad is only present inside main function\n    cmsisnn_func = None\n    for var in cmsisnn_mod.get_global_vars():\n        if \"cmsis_nn_main_0\" in var.name_hint:\n            cmsisnn_func = cmsisnn_mod[var]\n            pad_verifier = CheckForPadsWithinCompositeFunc()\n            pad_verifier.visit_function(cmsisnn_func)\n            pad_verifier.assert_no_pads_within_func()\n        else:\n            main_func = cmsisnn_mod[var]\n            pad_verifier = CheckForPadsWithinCompositeFunc()\n            pad_verifier.visit_function(main_func)\n            pad_verifier.assert_pads_within_func()\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n# pylint: disable=import-outside-toplevel\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 55, 55, 3)])\n@pytest.mark.parametrize(\"kernel_shape\", [(3, 2), (1, 3)])\n@pytest.mark.parametrize(\"strides, dilation\", [((3, 2), (1, 1))])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"activation\", [\"NONE\", \"RELU\"])\ndef test_conv2d_int8_tflite(ifm_shape, kernel_shape, strides, dilation, padding, activation):\n    \"\"\"Compares TVM output against TFLite output\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n    dtype = \"int8\"\n\n    from tvm.relay.testing.tflite import TFLiteModel\n\n    tfl_model = TFLiteModel(dtype)\n    conv2d_function = tfl_model.create_conv2d_single(\n        kernel_shape, strides, padding, dilation, activation\n    )\n    tfl_model.create_tflite_model(conv2d_function, [ifm_shape])\n    relay_mod, relay_params = tfl_model.convert_to_relay()\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(relay_mod, relay_params)\n\n    # validate pattern matching\n    assert_partitioned_function(relay_mod, cmsisnn_mod)\n\n    # validate CMSIS-NN output against TFLite output\n    input_map, output_map, output_tolerance = tfl_model.generate_reference_data()\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=input_map,\n            outputs=output_map,\n            params=relay_params,\n            output_tolerance=output_tolerance,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"int16\"])\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 28, 28, 12), (1, 64, 100, 4)])\n@pytest.mark.parametrize(\"kernel_size\", [(3, 3)])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (1, 1))])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\"])\n@pytest.mark.parametrize(\n    \"depth_multiplier, enable_bias\",\n    [(1, True), (3, True)],\n)\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale, out_channels\",\n    [(10, 0.0128, [0.11, 0.22], 2), (-64, 1, [1, 0.0256, 1.37], 3)],\n)\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_depthwise(\n    dtype,\n    ifm_shape,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    enable_bias,\n    relu_type,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n    depth_multiplier,\n    compiler_cpu,\n    cpu_flags,\n):\n    \"\"\"Tests QNN Depthwise int8 op via CMSIS-NN\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    groups = 1\n    input_zero_point = input_zero_point if dtype == \"int8\" else 0\n    kernel_layout = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n    kernel_zero_point = 0\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    groups = ifm_shape[3]\n    kernel_layout = \"HWOI\"\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3], depth_multiplier)\n    out_channels = ifm_shape[3] * depth_multiplier\n    ks_len = len(kernel_scale)\n    kernel_scale = [kernel_scale[i % ks_len] for i in range(out_channels)]\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n        is_depthwise=True,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (1, 1))])\n@pytest.mark.parametrize(\"relu_type\", [\"RELU\", \"NONE\"])\n@pytest.mark.parametrize(\"depth_multiplier\", [1, 3])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale\",\n    [\n        (\n            10,\n            0.0128,\n            [0.11, 0.22],\n        ),\n        (\n            -64,\n            1,\n            [1, 0.0256, 1.37],\n        ),\n    ],\n)\ndef test_relay_conv2d_cmsisnn_depthwise_int8(\n    padding,\n    strides,\n    dilation,\n    relu_type,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    depth_multiplier,\n):\n    \"\"\"Tests QNN Depthwise int8 op via CMSIS-NN\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    dtype = \"int8\"\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    ifm_shape = (1, 24, 24, 1)\n    groups = ifm_shape[3]\n    input_zero_point = input_zero_point if dtype == \"int8\" else 0\n    kernel_layout = \"HWIO\"\n    (kernel_h, kernel_w) = (3, 3)\n    kernel_shape = (kernel_h, kernel_w, ifm_shape[3], depth_multiplier)\n    out_channels = ifm_shape[3] * depth_multiplier\n    enable_bias = True\n    ks_len = len(kernel_scale)\n    kernel_zero_point = 0\n    kernel_scale = [kernel_scale[i % ks_len] for i in range(out_channels)]\n\n    kernel_dtype, bias_dtype = get_kernel_bias_dtype(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        input_dtype=dtype,\n        kernel_dtype=kernel_dtype,\n        output_dtype=dtype,\n        is_depthwise=True,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        kernel_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        kernel_dtype,\n        bias_dtype,\n        out_channels,\n        kernel_layout,\n        enable_bias,\n        relu_type,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # generate reference output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=ifm_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n\n    # validate presence of depthwise convolution\n    compiled_models = compile_models(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        interface_api,\n        use_unpacked_api,\n        pass_config=test_runner.pass_config,\n    )\n\n    cmsisnn_tir_mod = None\n    for target, mod in compiled_models[0].executor_factory.lowered_ir_mods.items():\n        if target.kind.name == \"cmsis-nn\":\n            cmsisnn_tir_mod = mod\n\n    cmsisnn_func = cmsisnn_tir_mod[\"tvmgen_default_cmsis_nn_main_0\"]\n    call_extern = None\n    # This happens when context buffer is init in case depthM != 1\n    if isinstance(cmsisnn_func.body, tvm.tir.stmt.Evaluate):\n        call_extern = cmsisnn_func.body.value\n    else:\n        call_extern = cmsisnn_func.body.body.value\n    assert (\n        call_extern.args[0].value == \"arm_depthwise_conv_wrapper_s8\"\n    ), \"Relay Conv2D should be mapped to CMSIS-NN Depthwise Convolution.\"\n\n    # validate the output\n    run_and_check(\n        models=compiled_models,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\ndef parameterize_for_invalid_model(test):\n    \"\"\"Generates non-int8 non-int16 inputs\"\"\"\n    in_dtype = [\"uint8\", \"int8\", \"int16\"]\n    kernel_dtype = [\"uint8\", \"int8\"]\n    kernel_zero_point = [-33, 10, 0]\n    input_zero_point = [64, 0]\n    all_combinations = itertools.product(\n        in_dtype, kernel_dtype, kernel_zero_point, input_zero_point\n    )\n    all_combinations = filter(\n        lambda parameters: not (\n            (parameters[0] == \"int8\" or (parameters[0] == \"int16\" and parameters[3] == 0))\n            and parameters[1] == \"int8\"\n            and parameters[2] == 0\n        ),\n        all_combinations,\n    )\n    return pytest.mark.parametrize(\n        [\"in_dtype\", \"kernel_dtype\", \"kernel_zero_point\", \"input_zero_point\"],\n        all_combinations,\n    )(test)\n\n\n@tvm.testing.requires_cmsisnn\n@parameterize_for_invalid_model\ndef test_invalid_parameters(\n    in_dtype,\n    kernel_dtype,\n    kernel_zero_point,\n    input_zero_point,\n):\n    \"\"\"Tests Depthwise op for non int8 inputs\"\"\"\n    ifm_shape = (1, 28, 28, 12)\n    out_channels = 2\n    input_scale = 1\n    kernel_scale = [0.11, 0.0237]\n\n    kernel_layout = \"HWIO\"\n    kernel_shape = [3, 3, ifm_shape[3], out_channels]\n    _, bias_dtype = get_kernel_bias_dtype(in_dtype)\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        in_dtype,\n        kernel_dtype,\n        in_dtype,\n        is_depthwise=False,\n    )\n    model, params = make_model(\n        shape=ifm_shape,\n        kernel_shape=kernel_shape,\n        input_zero_point=input_zero_point,\n        input_scale=input_scale,\n        kernel_zero_point=kernel_zero_point,\n        kernel_scale=kernel_scale,\n        output_zero_point=output_zero_point,\n        output_scale=output_scale,\n        padding=\"SAME\",\n        strides=(1, 1),\n        dilation=(1, 1),\n        groups=1,\n        dtype=in_dtype,\n        kernel_dtype=kernel_dtype,\n        bias_dtype=bias_dtype,\n        out_channels=out_channels,\n        kernel_layout=kernel_layout,\n        enable_bias=True,\n        relu_type=\"NONE\",\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n    assert_no_external_function(cmsisnn_mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_extract_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: extract_constants pass\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\n\ntvm._ffi._init_api(\"relay.ext.cmsisnn.transform\", __name__)\n\n\nclass CheckFunctionsForConstants(tvm.relay.ExprVisitor):\n    \"\"\"Provides methods to test number of constants present in a function\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.num_constants_ = 0\n\n    def visit_call(self, call):\n        super().visit_call(call)\n        for arg in call.args:\n            if isinstance(arg, relay.Constant) and arg.data.numpy().ndim > 0:\n                self.num_constants_ += 1\n\n    def check_num_constants(self):\n        assert self.num_constants_ == 0, \"Functions should not have constant arguments in Calls\"\n\n\ndef set_external_func_attr(func, compiler, ext_symbol):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compiler)\n    func = func.with_attr(\"global_symbol\", ext_symbol)\n    return func\n\n\ndef set_composite_func_attr(func, name):\n    func = func.with_attr(\"Composite\", name)\n    return func\n\n\n@tvm.testing.requires_cmsisnn\ndef test_external_function():\n    \"\"\"Tests the pass ExternConstants when the function is a global function\"\"\"\n    input1_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    input1_const = relay.const(input1_data, \"float32\")\n    binary_op = input0 + input1_const\n    extern_func = relay.Function([input0], binary_op, relay.TensorType((8, 8), \"float32\"))\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n\n    arg = relay.var(\"arg\", shape=(8, 8))\n    call_extern_func = relay.Call(global_var, [arg])\n    main_func = relay.Function([arg], call_extern_func, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    constant_verifier = CheckFunctionsForConstants()\n    constant_verifier.visit_function(mod[global_var])\n    constant_verifier.check_num_constants()\n    relay.transform.InferType()(mod)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_nested_function():\n    \"\"\"Tests the pass ExternConstants when a composite function\n    is present within global function\n    \"\"\"\n    input1_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    input1_const = relay.const(input1_data, \"float32\")\n    binary_op0 = input0 + input1_const\n    binary_op1 = binary_op0 * relay.const(5.0, \"float32\")\n    local_func = relay.Function([input0], binary_op1, relay.TensorType((8, 8), \"float32\"))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn\")\n\n    arg = relay.var(\"arg\", shape=(8, 8))\n    call_local_func = relay.Call(local_func, [arg])\n    extern_func = relay.Function([arg], call_local_func, relay.TensorType((8, 8), \"float32\"))\n\n    global_arg = relay.var(\"garg\", shape=(8, 8))\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [global_arg])\n    main_func = relay.Function([global_arg], call_extern_func, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    constant_verifier = CheckFunctionsForConstants()\n    constant_verifier.visit_function(mod[global_var])\n    constant_verifier.check_num_constants()\n    relay.transform.InferType()(mod)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_internal_function_with_duplicate_arguments():\n    \"\"\"Tests the pass ExternConstants when a composite function\n    is present within global function with repeating arguments\n    to one of the binary ops.\n    \"\"\"\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    binary_op0 = input0 + input0\n    binary_op1 = binary_op0 * relay.const(5.0, \"float32\")\n    local_func = relay.Function([input0], binary_op1, relay.TensorType((8, 8), \"float32\"))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn\")\n\n    arg = relay.var(\"arg\", shape=(8, 8))\n    call_local_func = relay.Call(local_func, [arg])\n    extern_func = relay.Function([arg], call_local_func, relay.TensorType((8, 8), \"float32\"))\n\n    global_arg = relay.var(\"global_var\", shape=(8, 8))\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [global_arg])\n    main_func = relay.Function([global_arg], call_extern_func, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    constant_verifier = CheckFunctionsForConstants()\n    constant_verifier.visit_function(mod[global_var])\n    constant_verifier.check_num_constants()\n    relay.transform.InferType()(mod)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_multiple_functions():\n    \"\"\"Tests the pass ExternConstants when global function\n    contains multiple composite functions inside it\n    \"\"\"\n    f0_input1_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    f0_input0 = relay.var(\"f0_in0\", shape=(8, 8))\n    f0_input1_const = relay.const(f0_input1_data, \"float32\")\n    f0_binary_op = f0_input0 + f0_input1_const\n    f0_func = relay.Function([f0_input0], f0_binary_op, relay.TensorType((8, 8), \"float32\"))\n    f0_func = set_composite_func_attr(f0_func, \"cmsis-nn\")\n\n    f1_input1_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    f1_input0 = relay.var(\"f1_in0\", shape=(8, 8))\n    f1_input1_const = relay.const(f1_input1_data, \"float32\")\n    f1_binary_op = f1_input0 + f1_input1_const\n    f1_func = relay.Function([f1_input0], f1_binary_op, relay.TensorType((8, 8), \"float32\"))\n    f1_func = set_composite_func_attr(f1_func, \"cmsis-nn\")\n\n    arg0 = relay.var(\"arg0\", shape=(8, 8))\n    call_local_func0 = relay.Call(f0_func, [arg0])\n    call_local_func1 = relay.Call(f1_func, [call_local_func0])\n    extern_func = relay.Function([arg0], call_local_func1, relay.TensorType((8, 8), \"float32\"))\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    global_var = relay.GlobalVar(\"cmsis-nn\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [input0])\n    main_func = relay.Function([input0], call_extern_func, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    constant_verifier = CheckFunctionsForConstants()\n    constant_verifier.visit_function(mod[global_var])\n    constant_verifier.check_num_constants()\n    relay.transform.InferType()(mod)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_main_function():\n    \"\"\"Tests the pass ExternConstants on main function\"\"\"\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    input1 = relay.var(\"input1\", shape=(8, 8))\n    binary_op = input0 + input1\n    extern_func = relay.Function([input0, input1], binary_op, relay.TensorType((8, 8), \"float32\"))\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n\n    arg = relay.var(\"arg\", shape=(8, 8))\n    input_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    input_const = relay.const(input_data, \"float32\")\n    binary_op = arg + input_const\n    call_extern_func = relay.Call(global_var, [arg, binary_op])\n    main_func = relay.Function([arg], call_extern_func, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    check_for_constants = CheckFunctionsForConstants()\n    check_for_constants.visit_call(mod[main_var].body)\n    assert (\n        check_for_constants.num_constants_ == 1\n    ), \"main() should have same number of arguments as before\"\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"external_compiler\", [\"cmsis-nn\", \"other_compiler\"])\ndef test_multiple_functions_non_cmsisnn_compiler(external_compiler):\n    \"\"\"Tests the pass ExternConstants on non CMSIS-NN targets\"\"\"\n    y20_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    x20 = relay.var(\"x20\", shape=(8, 8))\n    y20_const = relay.const(y20_data, \"float32\")\n    z20 = x20 + y20_const\n    f20 = relay.Function([x20], z20, relay.TensorType((8, 8), \"float32\"))\n    f20 = set_composite_func_attr(f20, \"cmsis-nn.qnn_op_1\")\n    x10 = relay.var(\"x10\", shape=(8, 8))\n    call_local_func0 = relay.Call(f20, [x10])\n    extern_func0 = relay.Function([x10], call_local_func0, relay.TensorType((8, 8), \"float32\"))\n\n    y21_data = np.random.uniform(0, 1, (8, 8)).astype(\"float32\")\n    x21 = relay.var(\"x21\", shape=(8, 8))\n    y21_const = relay.const(y21_data, \"float32\")\n    z21 = x21 + y21_const\n    f21 = relay.Function([x21], z21, relay.TensorType((8, 8), \"float32\"))\n    f21 = set_composite_func_attr(f21, \"cmsis-nn.qnn_op_2\")\n    x11 = relay.var(\"x11\", shape=(8, 8))\n    call_local_func1 = relay.Call(f21, [x11])\n    extern_func1 = relay.Function([x11], call_local_func1, relay.TensorType((8, 8), \"float32\"))\n\n    input0 = relay.var(\"input0\", shape=(8, 8))\n    global_var0 = relay.GlobalVar(\"external_function_0\")\n    extern_func0 = set_external_func_attr(extern_func0, external_compiler, global_var0.name_hint)\n    call_extern_func0 = relay.Call(global_var0, [input0])\n    global_var1 = relay.GlobalVar(\"external_function_1\")\n    extern_func1 = set_external_func_attr(extern_func1, external_compiler, global_var1.name_hint)\n    call_extern_func1 = relay.Call(global_var1, [call_extern_func0])\n    main_func = relay.Function([input0], call_extern_func1, relay.TensorType((8, 8), \"float32\"))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var0] = extern_func0\n    mod[global_var1] = extern_func1\n    mod[main_var] = main_func\n\n    mod = ExtractConstantsFromPartitionedFunction()(mod)\n    check_for_constants = CheckFunctionsForConstants()\n    check_for_constants.visit_call(mod[main_var].body)\n\n    num_extracted_constants = 0\n    if external_compiler == \"cmsis-nn\":\n        num_extracted_constants = 2\n\n    assert (\n        check_for_constants.num_constants_ == num_extracted_constants\n    ), \"main() should have same number of arguments as before\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_fully_connected.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Fully Connected\"\"\"\nimport itertools\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\n\nfrom tvm.testing.aot import generate_ref_data, AOTTestModel, compile_and_run\nfrom .utils import (\n    make_module,\n    get_range_for_dtype_str,\n    get_conv2d_qnn_params,\n    make_qnn_relu,\n    assert_partitioned_function,\n    assert_no_external_function,\n    create_test_runner,\n)\n\n\ndef make_model(\n    in_shape,  # [batchsize, in_channels]\n    kernel_shape,  # [out_channels, num_inputs]\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    output_zero_point,\n    output_scale,\n    dtype,\n    kernel_dtype,\n    out_channels,\n    enable_bias,\n    relu_type=\"NONE\",\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    input_ = relay.var(\"input\", shape=in_shape, dtype=dtype)\n    rng = np.random.default_rng(12321)\n    weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(kernel_dtype).min,\n            high=np.iinfo(kernel_dtype).max,\n            size=kernel_shape,\n            dtype=kernel_dtype,\n        )\n    )\n    weight_const = relay.const(weight, kernel_dtype)\n    dense = relay.qnn.op.dense(\n        input_,\n        weight_const,\n        input_zero_point=relay.const(input_zero_point, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zero_point, \"int32\"),\n        input_scale=relay.const(input_scale, \"float32\"),\n        kernel_scale=relay.const(kernel_scale, \"float32\"),\n        units=out_channels,\n        out_dtype=\"int32\",\n    )\n\n    bias = tvm.nd.array(rng.integers(0, high=10, size=(out_channels,), dtype=\"int32\"))\n    bias_const = relay.const(bias, \"int32\")\n    last_op = relay.nn.bias_add(dense, bias_const) if enable_bias else dense\n    requant_input_sc = input_scale * kernel_scale\n    last_op = relay.qnn.op.requantize(\n        last_op,\n        relay.const(requant_input_sc, \"float32\"),\n        relay.const(0, \"int32\"),\n        relay.const(output_scale, \"float32\"),\n        relay.const(output_zero_point, \"int32\"),\n        out_dtype=dtype,\n    )\n    last_op = make_qnn_relu(last_op, relu_type, output_scale, output_zero_point, dtype)\n    params = {\"w\": weight, \"b\": bias}\n    return last_op, params\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"in_shape\", [(2, 28), (1, 64)])\n@pytest.mark.parametrize(\"out_channels\", [12, 128])\n@pytest.mark.parametrize(\"enable_bias\", [False, True])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale\",\n    [(10, 0.0128, 0.11), (-64, 0.0256, 1.37)],\n)\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_op_int8(\n    in_shape,\n    enable_bias,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n    compiler_cpu,\n    cpu_flags,\n):\n    \"\"\"Test QNN fully connected layer\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    dtype = \"int8\"\n    kernel_zero_point = 0\n    kernel_shape = [out_channels, in_shape[1]]\n    conv2d_kernel_shape = (1, 1, kernel_shape[0], kernel_shape[1])\n    in_min, in_max = get_range_for_dtype_str(dtype)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        conv2d_kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        dtype,\n    )\n\n    model, params = make_model(\n        in_shape,\n        kernel_shape,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        dtype,\n        dtype,\n        out_channels,\n        enable_bias,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    rng = np.random.default_rng(12345)\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=in_shape, dtype=dtype)}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef parameterize_for_invalid_model(test):\n    \"\"\"Generates parameters for non int8 inputs to fully connected layer\"\"\"\n    in_dtype = [\"uint8\", \"int8\"]\n    kernel_dtype = [\"uint8\", \"int8\"]\n    kernel_zero_point = [-33, 10, 0]\n    all_combinations = itertools.product(in_dtype, kernel_dtype, kernel_zero_point)\n    all_combinations = filter(\n        lambda parameters: not (\n            parameters[0] == \"int8\" and parameters[1] == \"int8\" and parameters[2] == 0\n        ),\n        all_combinations,\n    )\n    return pytest.mark.parametrize(\n        [\"in_dtype\", \"kernel_dtype\", \"kernel_zero_point\"],\n        all_combinations,\n    )(test)\n\n\n@tvm.testing.requires_cmsisnn\n@parameterize_for_invalid_model\ndef test_invalid_parameters(\n    in_dtype,\n    kernel_dtype,\n    kernel_zero_point,\n):\n    \"\"\"Tests fully connected layer with non int8 inputs\"\"\"\n    in_shape = (2, 28)\n    out_channels = 2\n    input_scale = 1\n    input_zero_point = 24\n    kernel_scale = [0.11, 0.0237]\n\n    kernel_shape = [out_channels, in_shape[1]]\n    conv2d_kernel_shape = [1, 1, kernel_shape[0], kernel_shape[1]]\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        conv2d_kernel_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        in_dtype,\n        kernel_dtype,\n        in_dtype,\n    )\n    model, params = make_model(\n        in_shape=in_shape,\n        kernel_shape=kernel_shape,\n        input_zero_point=input_zero_point,\n        kernel_zero_point=kernel_zero_point,\n        input_scale=input_scale,\n        kernel_scale=kernel_scale,\n        output_zero_point=output_zero_point,\n        output_scale=output_scale,\n        dtype=in_dtype,\n        kernel_dtype=kernel_dtype,\n        out_channels=out_channels,\n        enable_bias=True,\n    )\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate pattern matching\n    assert_no_external_function(cmsisnn_mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_fuse_pads.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: fuse_pads pass\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom .utils import CheckForPadsWithinCompositeFunc\n\ntvm._ffi._init_api(\"relay.ext.cmsisnn.transform\", __name__)\n\n\ndef set_external_func_attr(func, compiler, ext_symbol):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compiler)\n    func = func.with_attr(\"global_symbol\", ext_symbol)\n    return func\n\n\ndef set_composite_func_attr(func, name):\n    func = func.with_attr(\"Composite\", name)\n    return func\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, pad_width, conv2d_padding, ofm_shape\",\n    [\n        [(1, 25, 25, 12), ((0, 0), (0, 2), (1, 2), (0, 0)), (1, 1, 1, 1), (1, 26, 28, 2)],\n        [(1, 64, 100, 4), ((0, 0), (1, 3), (1, 1), (0, 0)), (0, 0, 0, 0), (1, 64, 100, 2)],\n        [(1, 55, 55, 3), ((0, 0), (2, 1), (3, 5), (0, 0)), (0, 0, 1, 1), (1, 57, 59, 2)],\n    ],\n)\ndef test_invalid_padding_for_fusion(ifm_shape, pad_width, conv2d_padding, ofm_shape):\n    \"\"\"Negative tests for pads preceding Conv2D that cannot be fused.\"\"\"\n    dtype = \"int8\"\n    kernel_size = (3, 3)\n    ofm_channels = 2\n    local_input = relay.var(\"local_input\", shape=ifm_shape, dtype=dtype)\n    pad = relay.nn.pad(\n        local_input,\n        pad_width=pad_width,  # ((), (top, bottom), (left, right), ())\n        pad_value=10,\n        pad_mode=\"constant\",\n    )\n    rng = np.random.default_rng(12321)\n    local_weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(dtype).min,\n            high=np.iinfo(dtype).max,\n            size=(ofm_channels, kernel_size[0], kernel_size[1], ifm_shape[3]),\n            dtype=dtype,\n        )\n    )\n    local_weight = relay.const(local_weight, dtype)\n    conv2d = relay.qnn.op.conv2d(\n        pad,\n        local_weight,\n        relay.const(1, \"int32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"float32\"),\n        data_layout=\"NHWC\",\n        kernel_layout=\"OHWI\",\n        channels=ofm_channels,\n        kernel_size=(3, 3),\n        padding=conv2d_padding,\n        out_dtype=\"int32\",\n    )\n    requantize = relay.qnn.op.requantize(\n        conv2d,\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        axis=0,\n        out_dtype=dtype,\n    )\n    local_func = relay.Function(relay.analysis.free_vars(requantize), requantize)\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_conv2d\")\n\n    mod = tvm.IRModule()\n    ext_input = relay.var(\"ext_input\", shape=ifm_shape, dtype=dtype)\n    call_local_func = relay.Call(local_func, [ext_input])\n    extern_func = relay.Function(relay.analysis.free_vars(call_local_func), call_local_func)\n    extern_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", extern_var.name_hint)\n    mod[extern_var] = extern_func\n\n    main_input = relay.var(\"main_input\", shape=ifm_shape, dtype=dtype)\n    call_extern_func = relay.Call(extern_var, [main_input])\n    main_func = relay.Function([main_input], call_extern_func, relay.TensorType(ofm_shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n\n    error_regex = r\"Difference on each side of a dimension should be either 0 or 1\"\n\n    with pytest.raises(tvm.TVMError, match=error_regex):\n        mod = CMSISNNFusePads()(mod)\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, pad_width, conv2d_padding, ofm_shape\",\n    [\n        [(1, 25, 25, 12), ((0, 0), (0, 1), (1, 2), (0, 0)), (1, 1, 1, 1), (1, 26, 28, 2)],\n        [(1, 64, 100, 4), ((0, 0), (1, 1), (1, 1), (0, 0)), (0, 0, 0, 0), (1, 64, 100, 2)],\n        [(1, 55, 55, 3), ((0, 0), (2, 1), (3, 2), (0, 0)), (0, 0, 1, 1), (1, 57, 59, 2)],\n    ],\n)\ndef test_pad_conv2d_fusion_noncmsisnn_target(ifm_shape, pad_width, conv2d_padding, ofm_shape):\n    \"\"\"Tests the pads and conv2d fusion for non-cmsisnn targets.\n    It is expected that pad will not be fused with Conv2D in this case.\n    \"\"\"\n    dtype = \"int8\"\n    kernel_size = (3, 3)\n    ofm_channels = 2\n    local_input = relay.var(\"local_input\", shape=ifm_shape, dtype=dtype)\n    pad = relay.nn.pad(\n        local_input,\n        pad_width=pad_width,  # ((), (top, bottom), (left, right), ())\n        pad_value=10,\n        pad_mode=\"constant\",\n    )\n    rng = np.random.default_rng(12321)\n    local_weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(dtype).min,\n            high=np.iinfo(dtype).max,\n            size=(ofm_channels, kernel_size[0], kernel_size[1], ifm_shape[3]),\n            dtype=dtype,\n        )\n    )\n    local_weight = relay.const(local_weight, dtype)\n    conv2d = relay.qnn.op.conv2d(\n        pad,\n        local_weight,\n        relay.const(1, \"int32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"float32\"),\n        data_layout=\"NHWC\",\n        kernel_layout=\"OHWI\",\n        channels=ofm_channels,\n        kernel_size=(3, 3),\n        padding=conv2d_padding,\n        out_dtype=\"int32\",\n    )\n    requantize = relay.qnn.op.requantize(\n        conv2d,\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        axis=0,\n        out_dtype=dtype,\n    )\n    local_func = relay.Function(relay.analysis.free_vars(requantize), requantize)\n    local_func = set_composite_func_attr(local_func, \"noncmsis-nn.qnn_conv2d\")\n\n    mod = tvm.IRModule()\n    ext_input = relay.var(\"ext_input\", shape=ifm_shape, dtype=dtype)\n    call_local_func = relay.Call(local_func, [ext_input])\n    extern_func = relay.Function(relay.analysis.free_vars(call_local_func), call_local_func)\n    extern_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"noncmsis-nn\", extern_var.name_hint)\n    mod[extern_var] = extern_func\n\n    main_input = relay.var(\"main_input\", shape=ifm_shape, dtype=dtype)\n    call_extern_func = relay.Call(extern_var, [main_input])\n    main_func = relay.Function([main_input], call_extern_func, relay.TensorType(ofm_shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n\n    mod = CMSISNNFusePads()(mod)\n    pad_verifier = CheckForPadsWithinCompositeFunc()\n    pad_verifier.visit_function(mod[extern_var])\n    pad_verifier.assert_pads_within_func()\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, pad_width, conv2d_padding, ofm_shape\",\n    [\n        [(1, 25, 25, 12), ((0, 0), (0, 1), (1, 2), (0, 0)), (1, 1, 1, 1), (1, 26, 28, 2)],\n        [(1, 64, 100, 4), ((0, 0), (1, 1), (1, 1), (0, 0)), (0, 0, 0, 0), (1, 64, 100, 2)],\n        [(1, 55, 55, 3), ((0, 0), (2, 1), (3, 2), (0, 0)), (0, 0, 1, 1), (1, 57, 59, 2)],\n    ],\n)\ndef test_pad_conv2d_fusion(ifm_shape, pad_width, conv2d_padding, ofm_shape):\n    \"\"\"Tests the pads and conv2d fusion.\"\"\"\n    dtype = \"int8\"\n    kernel_size = (3, 3)\n    ofm_channels = 2\n    local_input = relay.var(\"local_input\", shape=ifm_shape, dtype=dtype)\n    pad = relay.nn.pad(\n        local_input,\n        pad_width=pad_width,  # ((), (top, bottom), (left, right), ())\n        pad_value=10,\n        pad_mode=\"constant\",\n    )\n    rng = np.random.default_rng(12321)\n    local_weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(dtype).min,\n            high=np.iinfo(dtype).max,\n            size=(ofm_channels, kernel_size[0], kernel_size[1], ifm_shape[3]),\n            dtype=dtype,\n        )\n    )\n    local_weight = relay.const(local_weight, dtype)\n    conv2d = relay.qnn.op.conv2d(\n        pad,\n        local_weight,\n        relay.const(1, \"int32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"float32\"),\n        data_layout=\"NHWC\",\n        kernel_layout=\"OHWI\",\n        channels=ofm_channels,\n        kernel_size=(3, 3),\n        padding=conv2d_padding,\n        out_dtype=\"int32\",\n    )\n    requantize = relay.qnn.op.requantize(\n        conv2d,\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        axis=0,\n        out_dtype=dtype,\n    )\n    local_func = relay.Function(relay.analysis.free_vars(requantize), requantize)\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_conv2d\")\n\n    mod = tvm.IRModule()\n    ext_input = relay.var(\"ext_input\", shape=ifm_shape, dtype=dtype)\n    call_local_func = relay.Call(local_func, [ext_input])\n    extern_func = relay.Function(relay.analysis.free_vars(call_local_func), call_local_func)\n    extern_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", extern_var.name_hint)\n    mod[extern_var] = extern_func\n\n    main_input = relay.var(\"main_input\", shape=ifm_shape, dtype=dtype)\n    call_extern_func = relay.Call(extern_var, [main_input])\n    main_func = relay.Function([main_input], call_extern_func, relay.TensorType(ofm_shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n\n    mod = CMSISNNFusePads()(mod)\n    pad_verifier = CheckForPadsWithinCompositeFunc()\n    pad_verifier.visit_function(mod[extern_var])\n    pad_verifier.assert_no_pads_within_func()\n\n\ndef test_without_preceding_pad():\n    \"\"\"Tests the pass FusePads when padding is not present before qnn.conv2d.\"\"\"\n    dtype = \"int8\"\n    ifm_shape = (1, 56, 56, 64)\n    ofm_shape = (1, 56, 56, 64)\n    local_input = relay.var(\"local_input\", shape=ifm_shape, dtype=dtype)\n    rng = np.random.default_rng(12321)\n    local_weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(dtype).min,\n            high=np.iinfo(dtype).max,\n            size=(64, 3, 3, 64),\n            dtype=dtype,\n        )\n    )\n    local_weight = relay.const(local_weight, dtype)\n    conv2d = relay.qnn.op.conv2d(\n        local_input,\n        local_weight,\n        relay.const(1, \"int32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"float32\"),\n        data_layout=\"NHWC\",\n        kernel_layout=\"OHWI\",\n        channels=64,\n        kernel_size=(3, 3),\n        padding=(1, 1, 1, 1),\n        out_dtype=\"int32\",\n    )\n    requantize = relay.qnn.op.requantize(\n        conv2d,\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        relay.const(1, \"float32\"),\n        relay.const(1, \"int32\"),\n        axis=0,\n        out_dtype=dtype,\n    )\n    relu = relay.nn.relu(requantize)\n    local_func = relay.Function(relay.analysis.free_vars(relu), relu)\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_conv2d\")\n\n    mod = tvm.IRModule()\n    ext_input = relay.var(\"ext_input\", shape=ifm_shape, dtype=dtype)\n    call_local_func = relay.Call(local_func, [ext_input])\n    extern_func = relay.Function(relay.analysis.free_vars(call_local_func), call_local_func)\n    extern_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", extern_var.name_hint)\n    mod[extern_var] = extern_func\n\n    main_input = relay.var(\"main_input\", shape=ifm_shape, dtype=dtype)\n    call_extern_func = relay.Call(extern_var, [main_input])\n    main_func = relay.Function(relay.analysis.free_vars(call_extern_func), call_extern_func)\n    main_func = relay.Function([main_input], call_extern_func, relay.TensorType(ofm_shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n\n    mod = CMSISNNFusePads()(mod)\n    pad_verifier = CheckForPadsWithinCompositeFunc()\n    pad_verifier.visit_function(mod[extern_var])\n    pad_verifier.assert_no_pads_within_func()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_generate_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: generate_constants pass\"\"\"\nimport math\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\n\nfrom .utils import (\n    make_module,\n    get_same_padding,\n    get_conv2d_qnn_params,\n    make_qnn_relu,\n)\n\ntvm._ffi._init_api(\"relay.ext.cmsisnn.transform\", __name__)\n\n\ndef quantize_scale(scale):\n    multiplier, shift = math.frexp(scale)\n    multiplier_q31 = round(multiplier * (1 << 31))\n    return multiplier_q31, shift\n\n\nclass CheckGeneratedConstants(tvm.relay.ExprVisitor):\n    \"\"\"Provides methods to compare against expected quantization parameters\"\"\"\n\n    def __init__(self, enable_bias, multiplier, shift):\n        super().__init__()\n        self.num_constant_args_ = 0\n        self.enable_bias_ = enable_bias\n        self.multiplier_ = multiplier\n        self.shift_ = shift\n\n    def visit_call(self, call):\n        \"\"\"Tests if the multiplier and shift constants required by CMSIS-NN API were generated\"\"\"\n        super().visit_call(call)\n        if isinstance(call.op, tvm.ir.expr.GlobalVar):\n            multiplier = call.args[2]\n            shift = call.args[6] if self.enable_bias_ else call.args[5]\n            assert isinstance(\n                multiplier, relay.expr.Constant\n            ), \"Expected quantized multiplier at argument#3\"\n            assert isinstance(\n                shift, relay.expr.Constant\n            ), \"Expected a constant while looking for quantized shift\"\n            multiplier = multiplier.data.numpy()\n            shift = shift.data.numpy()\n            tvm.testing.assert_allclose(multiplier, self.multiplier_, atol=100, rtol=1e-10)\n            tvm.testing.assert_allclose(shift, self.shift_, atol=1, rtol=1e-5)\n\n\ndef make_model(\n    shape,\n    kernel_shape,\n    input_zero_point,\n    input_scale,\n    kernel_zero_point,\n    kernel_scale,\n    output_zero_point,\n    output_scale,\n    padding,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    kernel_dtype,\n    out_channels,\n    weight_format,\n    enable_bias,\n    relu_type,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    h_index = weight_format.index(\"H\")\n    w_index = weight_format.index(\"W\")\n    kernel_h = kernel_shape[h_index]\n    kernel_w = kernel_shape[w_index]\n    a = relay.var(\"input\", shape=shape, dtype=dtype)\n    p = (0, 0, 0, 0)\n    if padding == \"SAME\":\n        p = get_same_padding((shape[1], shape[2]), (kernel_h, kernel_w), dilation, strides)\n        a = relay.nn.pad(\n            a,\n            pad_width=[(0, 0), (p[0], p[2]), (p[1], p[3]), (0, 0)],\n            pad_value=input_zero_point,\n            pad_mode=\"constant\",\n        )\n        shape = (shape[0], shape[1] + p[0] + p[2], shape[2] + p[1] + p[3], shape[3])\n\n    weight_shape = (kernel_h, kernel_w, shape[3] // groups, out_channels)\n    rng = np.random.default_rng(12321)\n    weight = tvm.nd.array(\n        rng.integers(\n            np.iinfo(kernel_dtype).min,\n            high=np.iinfo(kernel_dtype).max,\n            size=weight_shape,\n            dtype=kernel_dtype,\n        )\n    )\n    weight_const = relay.const(weight, kernel_dtype)\n    conv = relay.qnn.op.conv2d(\n        a,\n        weight_const,\n        input_zero_point=relay.const(input_zero_point, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zero_point, \"int32\"),\n        input_scale=relay.const(input_scale, \"float32\"),\n        kernel_scale=relay.const(kernel_scale, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=weight_format,\n        dilation=dilation,\n        strides=strides,\n        groups=groups,\n        channels=out_channels,\n        padding=p,\n        out_dtype=\"int32\",\n    )\n    bias = tvm.nd.array(rng.integers(0, high=10, size=(out_channels,), dtype=\"int32\"))\n    bias_const = relay.const(bias, \"int32\")\n    last_op = relay.nn.bias_add(conv, bias_const, axis=3) if enable_bias else conv\n    requant_input_sc = [sc * input_scale for sc in kernel_scale]\n    last_op = relay.qnn.op.requantize(\n        last_op,\n        relay.const(requant_input_sc, \"float32\"),\n        relay.const(0, \"int32\"),\n        relay.const(output_scale, \"float32\"),\n        relay.const(output_zero_point, \"int32\"),\n        out_dtype=dtype,\n    )\n    last_op = make_qnn_relu(last_op, relu_type, output_scale, output_zero_point, dtype)\n    params = {\"w\": weight, \"b\": bias}\n    return last_op, params\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"enable_bias\", [True, False])\n@pytest.mark.parametrize(\n    \"input_zero_point, input_scale, kernel_scale, out_channels\",\n    [(10, 0.0128, [0.11, 0.22], 2), (-64, 1, [1, 0.0256, 1.37], 3)],\n)\ndef test_op_int8(\n    enable_bias,\n    input_zero_point,\n    input_scale,\n    kernel_scale,\n    out_channels,\n):\n    \"\"\"Tests for CMSIS-NN constants when the dtype is int8\"\"\"\n    ifm_shape = (1, 28, 28, 3)\n    padding = \"VALID\"\n    strides = (1, 1)\n    dilation = (1, 1)\n    kernel_size = (3, 3)\n    kernel_zero_point = 0\n    groups = 1\n    weight_format = \"HWIO\"\n    kernel_h = kernel_size[0]\n    kernel_w = kernel_size[1]\n    dtype = \"int8\"\n    relu_type = \"RELU\"\n\n    weight_shape = (kernel_h, kernel_w, ifm_shape[3] // groups, out_channels)\n\n    output_scale, output_zero_point = get_conv2d_qnn_params(\n        weight_shape,\n        input_scale,\n        input_zero_point,\n        kernel_scale,\n        kernel_zero_point,\n        dtype,\n        dtype,\n        dtype,\n        False,\n    )\n\n    model, params = make_model(\n        ifm_shape,\n        weight_shape,\n        input_zero_point,\n        input_scale,\n        kernel_zero_point,\n        kernel_scale,\n        output_zero_point,\n        output_scale,\n        padding,\n        strides,\n        dilation,\n        groups,\n        dtype,\n        dtype,\n        out_channels,\n        weight_format,\n        enable_bias,\n        relu_type,\n    )\n    mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(mod, params)\n    multiplier_array = []\n    shift_array = []\n    for i in range(out_channels):\n        multiplier, shift = quantize_scale(input_scale * kernel_scale[i] / output_scale)\n        multiplier_array.append(multiplier)\n        shift_array.append(shift)\n    CheckGeneratedConstants(enable_bias, multiplier_array, shift_array).visit_function(\n        cmsisnn_mod[\"main\"]\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_invalid_graphs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Tests invalid graphs\"\"\"\nimport numpy as np\nimport tvm\n\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_USMP_CORSTONE300_RUNNER,\n)\nfrom .utils import (\n    skip_if_no_reference_system,\n    get_range_for_dtype_str,\n)\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\ndef test_empty_function():\n    \"\"\"Test partitioned function without composite function\"\"\"\n    original_model = \"\"\"\n#[version = \"0.0.5\"]\ndef @main(%data : Tensor[(16, 29), int8]) -> Tensor[(16, 29), int8] {\n    add(%data, %data)\n}\n\"\"\"\n    cmsisnn_model = \"\"\"\n#[version = \"0.0.5\"]\ndef @tvmgen_default_cmsis_nn_main_1(%i1: Tensor[(16, 29), int8], Inline=1, Compiler=\"cmsis-nn\", global_symbol=\"tvmgen_default_cmsis_nn_main_1\", Primitive=1) -> Tensor[(16, 29), int8] {\n  add(%i1, %i1)\n}\ndef @main(%data : Tensor[(16, 29), int8]) -> Tensor[(16, 29), int8] {\n  %1 = @tvmgen_default_cmsis_nn_main_1(%data) /* ty=Tensor[(16, 29), int8] */;\n  %1\n}\n\"\"\"\n    orig_mod = tvm.parser.fromtext(original_model)\n    cmsisnn_mod = tvm.parser.fromtext(cmsisnn_model)\n    params = {}\n\n    # validate the output\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n    dtype = \"int8\"\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    rng = np.random.default_rng(12345)\n    inputs = {\"data\": rng.integers(in_min, high=in_max, size=(16, 29), dtype=dtype)}\n    outputs = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=outputs,\n            params=params,\n            output_tolerance=0,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_networks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN: testing with networks\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.op.contrib import cmsisnn\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n    AOT_USMP_CORSTONE300_RUNNER,\n)\nfrom .utils import skip_if_no_reference_system, get_range_for_dtype_str\n\n# pylint: disable=import-outside-toplevel\ndef _convert_to_relay(\n    tflite_model_buf,\n    input_data,\n    input_node,\n):\n    \"\"\"Converts TFLite model to Relay module and params\"\"\"\n\n    def convert_to_list(x):\n        if not isinstance(x, list):\n            x = [x]\n        return x\n\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except ImportError:\n        raise ImportError(\"The tflite package must be installed\")\n\n    input_data = convert_to_list(input_data)\n    input_node = convert_to_list(input_node)\n\n    shape_dict = {}\n    dtype_dict = {}\n    for i, name in enumerate(input_node):\n        shape_dict[name] = input_data[i].shape\n        dtype_dict[name] = input_data[i].dtype.name\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict\n    )\n\n    return mod, params\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_package(\"tflite\")\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"test_runner\", [AOT_CORSTONE300_RUNNER, AOT_USMP_CORSTONE300_RUNNER])\ndef test_cnn_small(test_runner):\n    \"\"\"Download a small network and tests TVM via CMSIS-NN output against TFLite output\"\"\"\n    # download the model\n    base_url = (\n        \"https://github.com/ARM-software/ML-zoo/raw/\"\n        \"48a22ee22325d15d2371a6df24eb7d67e21dcc97\"\n        \"/models/keyword_spotting/cnn_small/tflite_int8\"\n    )\n    file_to_download = \"cnn_s_quantized.tflite\"\n    file_saved = \"cnn_s_quantized_15Dec2021.tflite\"\n    model_file = download_testdata(\"{}/{}\".format(base_url, file_to_download), file_saved)\n\n    with open(model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    input_shape = (1, 490)\n    dtype = \"int8\"\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    rng = np.random.default_rng(12345)\n    input_data = rng.integers(in_min, high=in_max, size=input_shape, dtype=dtype)\n\n    orig_mod, params = _convert_to_relay(tflite_model_buf, input_data, \"input\")\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod, params)\n\n    # validate CMSIS-NN output against CPU output\n    interface_api = \"c\"\n    use_unpacked_api = True\n    inputs = {\"input\": input_data}\n    params = {}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Pooling\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\n\nfrom tvm.testing.aot import (\n    generate_ref_data,\n    AOTTestModel,\n    compile_and_run,\n)\nfrom tvm.micro.testing.aot_test_utils import AOT_USMP_CORSTONE300_RUNNER\nfrom .utils import (\n    make_module,\n    get_range_for_dtype_str,\n    get_same_padding,\n    make_qnn_relu,\n    assert_partitioned_function,\n    assert_no_external_function,\n    create_test_runner,\n)\n\n\ndef make_model(\n    pool_op,\n    shape=(1, 28, 28, 12),\n    pool_size=(3, 3),\n    strides=(2, 2),\n    padding=\"VALID\",\n    dtype=\"int8\",\n    scale=1,\n    zero_point=-33,\n    relu_type=\"RELU\",\n    layout=\"NHWC\",\n    input_op=None,\n):\n    \"\"\"Return a model and any parameters it may have,\n    all parameters are defaulted to known good values\n    \"\"\"\n    if input_op:\n        op = input_op\n    else:\n        op = relay.var(\"input\", shape=shape, dtype=dtype)\n    pad_ = (0, 0, 0, 0)\n    if padding == \"SAME\":\n        dilation = (1, 1)\n        pad_ = get_same_padding((shape[1], shape[2]), pool_size, dilation, strides)\n        op = relay.nn.pad(\n            op,\n            pad_width=[(0, 0), (pad_[0], pad_[2]), (pad_[1], pad_[3]), (0, 0)],\n            pad_value=zero_point,\n            pad_mode=\"constant\",\n        )\n    if pool_op.__name__ == relay.nn.avg_pool2d.__name__:\n        op = relay.cast(op, \"int32\")\n    op = pool_op(\n        op, pool_size=pool_size, strides=strides, padding=pad_, ceil_mode=True, layout=layout\n    )\n    if pool_op.__name__ == relay.nn.avg_pool2d.__name__:\n        op = relay.cast(op, dtype)\n    op = make_qnn_relu(op, relu_type, scale, zero_point, dtype)\n    return op\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"in_shape\", [(1, 28, 28, 12), (1, 64, 100, 4)])\n@pytest.mark.parametrize(\n    \"pool_size, strides, padding\", [((3, 3), (2, 2), \"SAME\"), ((2, 2), (1, 1), \"VALID\")]\n)\n@pytest.mark.parametrize(\"relu_type\", [\"NONE\", \"RELU\"])\n@pytest.mark.parametrize(\"pool_type\", [relay.nn.max_pool2d, relay.nn.avg_pool2d])\n@pytest.mark.parametrize(\"zero_point, scale\", [(-34, 0.0256)])\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_op_int8(\n    in_shape,\n    pool_size,\n    strides,\n    padding,\n    relu_type,\n    pool_type,\n    zero_point,\n    scale,\n    compiler_cpu,\n    cpu_flags,\n):\n    \"\"\"Tests QNN pooling op for int8 inputs\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    dtype = \"int8\"\n\n    model = make_model(\n        pool_op=pool_type,\n        shape=in_shape,\n        pool_size=pool_size,\n        strides=strides,\n        padding=padding,\n        scale=scale,\n        zero_point=zero_point,\n        relu_type=relu_type,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    np.random.seed(0)\n    inputs = {\n        \"input\": np.random.randint(in_min, high=in_max, size=in_shape, dtype=\"int8\"),\n    }\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=None,\n            output_tolerance=1,\n        ),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\n    \"pool_size, strides, padding\", [((3, 3), (2, 2), \"SAME\"), ((2, 2), (1, 1), \"VALID\")]\n)\n@pytest.mark.parametrize(\"relu_type\", [\"NONE\", \"RELU\"])\ndef test_int8_pool_with_float32_input(\n    pool_size,\n    strides,\n    padding,\n    relu_type,\n):\n    \"\"\"Tests QNN maxpool partitions with float32 input\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    in_shape = (1, 28, 28, 12)\n    zero_point, scale = (-34, 0.0256)\n\n    input_ = relay.var(\"input\", shape=in_shape, dtype=\"float32\")\n    op = relay.op.add(input_, input_)\n    op = relay.qnn.op.quantize(op, relay.const(scale), relay.const(zero_point), -1, \"int8\")\n\n    model = make_model(\n        pool_op=relay.nn.max_pool2d,\n        shape=in_shape,\n        pool_size=pool_size,\n        strides=strides,\n        padding=padding,\n        scale=scale,\n        zero_point=zero_point,\n        relu_type=relu_type,\n        input_op=op,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    np.random.seed(0)\n    inputs = {\"input\": np.random.uniform(0, 1, in_shape).astype(\"float32\")}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs)\n    compile_and_run(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=None,\n            output_tolerance=1,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.nn.avg_pool2d, relay.nn.max_pool2d])\ndef test_invalid_datatype(op):\n    \"\"\"Checks CMSIS-NN partitioning for non int8 dtype\"\"\"\n    model = make_model(pool_op=op, dtype=\"int64\")\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.nn.avg_pool2d, relay.nn.max_pool2d])\ndef test_invalid_batch_size(op):\n    \"\"\"Checks CMSIS-NN partitioning when batch size is not 1\"\"\"\n    model = make_model(\n        pool_op=op,\n        shape=(2, 28, 28, 12),\n    )\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"op\", [relay.nn.avg_pool2d, relay.nn.max_pool2d])\ndef test_invalid_layout(op):\n    \"\"\"Checks CMSIS-NN partitioning when layout is not NHWC\"\"\"\n    model = make_model(pool_op=op, layout=\"NCHW\")\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_remove_reshapes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Reshape removal\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\n\nfrom tvm.testing.aot import (\n    generate_ref_data,\n    AOTTestModel,\n    compile_models,\n    run_and_check,\n)\nfrom tvm.micro.testing.aot_test_utils import AOT_USMP_CORSTONE300_RUNNER\nfrom .utils import (\n    make_module,\n    get_range_for_dtype_str,\n    get_same_padding,\n    make_qnn_relu,\n    assert_partitioned_function,\n)\n\n\ndef make_model(\n    pool_op,\n    shape=(1, 28, 28, 12),\n    pool_size=(3, 3),\n    strides=(2, 2),\n    padding=\"VALID\",\n    dtype=\"int8\",\n    scale=1,\n    zero_point=-33,\n    relu_type=\"RELU\",\n    layout=\"NHWC\",\n    input_op=None,\n):\n    \"\"\"Return a model and any parameters it may have,\n    all parameters are defaulted to known good values\n    \"\"\"\n    if input_op:\n        op = input_op\n    else:\n        op = relay.var(\"input\", shape=shape, dtype=dtype)\n    pad_ = (0, 0, 0, 0)\n    if padding == \"SAME\":\n        dilation = (1, 1)\n        pad_ = get_same_padding((shape[1], shape[2]), pool_size, dilation, strides)\n        op = relay.nn.pad(\n            op,\n            pad_width=[(0, 0), (pad_[0], pad_[2]), (pad_[1], pad_[3]), (0, 0)],\n            pad_value=zero_point,\n            pad_mode=\"constant\",\n        )\n    if pool_op.__name__ == relay.nn.avg_pool2d.__name__:\n        op = relay.cast(op, \"int32\")\n    op = pool_op(\n        op, pool_size=pool_size, strides=strides, padding=pad_, ceil_mode=True, layout=layout\n    )\n    if pool_op.__name__ == relay.nn.avg_pool2d.__name__:\n        op = relay.cast(op, dtype)\n    op = make_qnn_relu(op, relu_type, scale, zero_point, dtype)\n    return op\n\n\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\ndef test_reshape_removal(padding):\n    \"\"\"Tests reshape is removed from the network\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_USMP_CORSTONE300_RUNNER\n\n    in_shape = (1, 28, 28, 12)\n    pool_size = (3, 3)\n    strides = (2, 2)\n    relu_type = \"NONE\"\n    zero_point, scale = (-34, 0.0256)\n\n    max_pool = make_model(\n        pool_op=relay.nn.max_pool2d,\n        shape=in_shape,\n        pool_size=pool_size,\n        strides=strides,\n        padding=padding,\n        scale=scale,\n        zero_point=zero_point,\n        relu_type=relu_type,\n    )\n    new_shape = (1, 28, 28, 3) if padding == \"VALID\" else (1, 30, 30, 3)\n    reshape = relay.reshape(max_pool, newshape=new_shape)\n\n    model = make_model(\n        pool_op=relay.nn.avg_pool2d,\n        shape=new_shape,\n        pool_size=pool_size,\n        strides=strides,\n        padding=padding,\n        scale=scale,\n        zero_point=zero_point,\n        relu_type=relu_type,\n        input_op=reshape,\n    )\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # generate reference output\n    rng = np.random.default_rng(12345)\n    in_min, in_max = get_range_for_dtype_str(\"int8\")\n    inputs = {\"input\": rng.integers(in_min, high=in_max, size=in_shape, dtype=\"int8\")}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params=None)\n\n    # validate presence of depthwise convolution\n    compiled_models = compile_models(\n        AOTTestModel(\n            module=cmsisnn_mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=None,\n            output_tolerance=1,\n        ),\n        interface_api,\n        use_unpacked_api,\n        pass_config=test_runner.pass_config,\n    )\n\n    main_mod = None\n    for target, mod in compiled_models[0].executor_factory.lowered_ir_mods.items():\n        if target.kind.name == \"c\":\n            main_mod = mod\n\n    # when padding=\"SAME\", extra padding is introduced which causes Reshape to be fused with the\n    # Pad. RemoveReshapes pass cannot remove a fused Reshape. Whereas padding=\"VALID\" doesn't need\n    # an extra Pad layer. In this case, the pass removes the Reshape from the graph.\n    reshapes_present = any([\"reshape\" in gv.name_hint for gv in main_mod.get_global_vars()])\n    check_reshapes = reshapes_present if padding == \"SAME\" else not reshapes_present\n    expected_reshapes = \"a\" if padding == \"SAME\" else \"No\"\n    assert check_reshapes, \"Expeting {} reshape layer(s).\".format(expected_reshapes)\n\n    # validate the output\n    run_and_check(\n        models=compiled_models,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_scalar_to_tensor_constant.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: scalar_to_tensor_constant pass\"\"\"\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\n\ntvm._ffi._init_api(\"relay.ext.cmsisnn.transform\", __name__)\n\n\ndef generate_variable(name, shape, dtype=\"int8\"):\n    return relay.var(name, shape=shape, dtype=dtype)\n\n\ndef make_binary_op(\n    op,\n    input_0,\n    input_1,\n    input_0_scale,\n    input_0_zero_point,\n    input_1_scale,\n    input_1_zero_point,\n    out_scale=1.0 / 256,\n    out_zero_point=-128,\n):\n    \"\"\"Create a Relay Function / network model\"\"\"\n    return op(\n        input_0,\n        input_1,\n        relay.const(input_0_scale, \"float32\"),\n        relay.const(input_0_zero_point, \"int32\"),\n        relay.const(input_1_scale, \"float32\"),\n        relay.const(input_1_zero_point, \"int32\"),\n        relay.const(out_scale, \"float32\"),\n        relay.const(out_zero_point, \"int32\"),\n    )\n\n\nclass CheckFunctionsForConstants(tvm.relay.ExprVisitor):\n    \"\"\"Provides method to test number of scalar constants present in a function\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.num_constants_ = 0\n\n    def visit_call(self, call):\n        super().visit_call(call)\n        for arg in call.args:\n            if isinstance(arg, relay.Constant) and arg.data.numpy().ndim > 0:\n                self.num_constants_ += 1\n\n    def check_num_constants(self):\n        assert self.num_constants_ == 0, \"Functions should not have constant arguments in Calls\"\n\n\ndef set_external_func_attr(func, compiler, ext_symbol):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compiler)\n    func = func.with_attr(\"global_symbol\", ext_symbol)\n    return func\n\n\ndef set_composite_func_attr(func, name):\n    func = func.with_attr(\"Composite\", name)\n    return func\n\n\n@tvm.testing.requires_cmsisnn\ndef test_single_scalar_position_0():\n    \"\"\"Tests conversion to tensor constant when first operand is a scalar\"\"\"\n    dtype = \"int8\"\n    shape = (8, 8)\n    operand0 = generate_variable(\"operand0\", None, dtype)\n    operand1 = generate_variable(\"operand1\", shape, dtype)\n    binary_op = make_binary_op(\n        relay.qnn.op.add,\n        operand0,\n        operand1,\n        input_0_scale=0.0128,\n        input_0_zero_point=32,\n        input_1_scale=0.256,\n        input_1_zero_point=-64,\n    )\n\n    local_func = relay.Function([operand0, operand1], binary_op, relay.TensorType(shape, dtype))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n    arg0 = relay.expr.const(3, dtype)\n    arg1 = relay.var(\"arg1\", shape=shape, dtype=dtype)\n    call_local_func = relay.Call(local_func, [arg0, arg1])\n    extern_func = relay.Function([arg1], call_local_func, relay.TensorType(shape, dtype))\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [x])\n    main_func = relay.Function([x], call_extern_func, relay.TensorType(shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n    mod = ScalarToTensorConstants()(mod)\n    mod = relay.transform.InferType()(mod)\n    check_for_constants = CheckFunctionsForConstants()\n    check_for_constants.visit_call(mod[global_var].body)\n    assert (\n        check_for_constants.num_constants_ == 1\n    ), \"Scalar constant wasn't converted into tensor constant\"\n\n\n@tvm.testing.requires_cmsisnn\ndef test_single_scalar_position_1():\n    \"\"\"Tests conversion to tensor constant when second operand is a scalar\"\"\"\n    dtype = \"int8\"\n    shape = (8, 8)\n    operand0 = generate_variable(\"operand0\", shape, dtype)\n    operand1 = generate_variable(\"operand1\", None, dtype)\n    binary_op = make_binary_op(\n        relay.qnn.op.add,\n        operand0,\n        operand1,\n        input_0_scale=0.0128,\n        input_0_zero_point=32,\n        input_1_scale=0.256,\n        input_1_zero_point=-64,\n    )\n\n    local_func = relay.Function([operand0, operand1], binary_op, relay.TensorType(shape, dtype))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n    arg0 = relay.var(\"arg0\", shape=shape, dtype=dtype)\n    arg1 = relay.expr.const(3, dtype)\n    call_local_func = relay.Call(local_func, [arg0, arg1])\n    extern_func = relay.Function([arg0], call_local_func, relay.TensorType(shape, dtype))\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [x])\n    main_func = relay.Function([x], call_extern_func, relay.TensorType(shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n    mod = ScalarToTensorConstants()(mod)\n    mod = relay.transform.InferType()(mod)\n    check_for_constants = CheckFunctionsForConstants()\n    check_for_constants.visit_call(mod[global_var].body)\n    assert (\n        check_for_constants.num_constants_ == 1\n    ), \"Scalar constant wasn't converted into tensor constant\"\n\n\n@tvm.testing.requires_cmsisnn\ndef test_primary_operands_all_scalars():\n    \"\"\"Tests conversion to tensor constants all operands are scalars\"\"\"\n    dtype = \"int8\"\n    shape = None\n    operand0 = generate_variable(\"operand0\", None, dtype)\n    operand1 = generate_variable(\"operand1\", None, dtype)\n    binary_op = make_binary_op(\n        relay.qnn.op.add,\n        operand0,\n        operand1,\n        input_0_scale=0.0128,\n        input_0_zero_point=32,\n        input_1_scale=0.256,\n        input_1_zero_point=-64,\n    )\n\n    local_func = relay.Function([operand0, operand1], binary_op, relay.TensorType(shape, dtype))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n    arg0 = relay.expr.const(7, dtype)\n    arg1 = relay.expr.const(3, dtype)\n    call_local_func = relay.Call(local_func, [arg0, arg1])\n    extern_func = relay.Function([], call_local_func, relay.TensorType(shape, dtype))\n\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [])\n    main_func = relay.Function([], call_extern_func, relay.TensorType(shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n    mod = ScalarToTensorConstants()(mod)\n    new_mod = relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(mod[global_var].body, new_mod[global_var].body)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_all_primary_operands_tensor_constants():\n    \"\"\"Tests conversion to tensor constants all operands are tensors\"\"\"\n    dtype = \"int8\"\n    shape = (1, 3, 3, 32)\n    operand0 = generate_variable(\"operand0\", shape, dtype)\n    operand1 = generate_variable(\"operand1\", shape, dtype)\n    binary_op = make_binary_op(\n        relay.qnn.op.add,\n        operand0,\n        operand1,\n        input_0_scale=0.0128,\n        input_0_zero_point=32,\n        input_1_scale=0.256,\n        input_1_zero_point=-64,\n    )\n\n    local_func = relay.Function([operand0, operand1], binary_op, relay.TensorType(shape, dtype))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n    rng = np.random.default_rng(12345)\n    arg0 = relay.const(rng.integers(-128, high=127, size=shape, dtype=dtype))\n    arg1 = relay.const(rng.integers(-128, high=127, size=shape, dtype=dtype))\n    call_local_func = relay.Call(local_func, [arg0, arg1])\n    extern_func = relay.Function([], call_local_func, relay.TensorType(shape, dtype))\n\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [])\n    main_func = relay.Function([], call_extern_func, relay.TensorType(shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n    mod = ScalarToTensorConstants()(mod)\n    new_mod = relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(mod[global_var].body, new_mod[global_var].body)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_duplicate_constant_arguments():\n    \"\"\"Tests the pass when repeating operands are arguments to the binary op\"\"\"\n    dtype = \"int8\"\n    shape = (1, 3, 3, 32)\n    operand0 = generate_variable(\"operand0\", shape, dtype)\n    operand1 = generate_variable(\"operand1\", shape, dtype)\n    binary_op = make_binary_op(\n        relay.qnn.op.add,\n        operand0,\n        operand0,\n        input_0_scale=0.0128,\n        input_0_zero_point=32,\n        input_1_scale=0.256,\n        input_1_zero_point=-64,\n    )\n\n    local_func = relay.Function([operand0, operand1], binary_op, relay.TensorType(shape, dtype))\n    local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n    rng = np.random.default_rng(12345)\n    arg0 = relay.const(rng.integers(-128, high=127, size=shape, dtype=dtype))\n    call_local_func = relay.Call(local_func, [arg0, arg0])\n    extern_func = relay.Function([], call_local_func, relay.TensorType(shape, dtype))\n\n    global_var = relay.GlobalVar(\"external_function\")\n    extern_func = set_external_func_attr(extern_func, \"cmsis-nn\", global_var.name_hint)\n    call_extern_func = relay.Call(global_var, [])\n    main_func = relay.Function([], call_extern_func, relay.TensorType(shape, dtype))\n    main_var = relay.GlobalVar(\"main\")\n\n    mod = tvm.IRModule()\n    mod[global_var] = extern_func\n    mod[main_var] = main_func\n\n    mod = relay.transform.InferType()(mod)\n    mod = ScalarToTensorConstants()(mod)\n    new_mod = relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(mod[global_var].body, new_mod[global_var].body)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_non_cmsisnn_ext_func():\n    \"\"\"Non CMSISNN functions should not be altered.\"\"\"\n\n    def get_mod():\n        operand1 = relay.var(\"operand1\", shape=None)\n        operand2 = relay.var(\"operand2\", shape=None)\n        binary_op = operand1 + operand2\n        local_func = relay.Function(\n            [operand1, operand2], binary_op, relay.TensorType((), \"float32\")\n        )\n        local_func = set_composite_func_attr(local_func, \"cmsis-nn.qnn_add\")\n\n        arg0 = relay.expr.const(5, \"float32\")\n        arg1 = relay.expr.const(3, \"float32\")\n        call_local_func = relay.Call(local_func, [arg0, arg1])\n        extern_func = relay.Function([], call_local_func, relay.TensorType((), \"float32\"))\n\n        global_var = relay.GlobalVar(\"external_function\")\n        extern_func = set_external_func_attr(extern_func, \"foo\", global_var.name_hint)\n        call_extern_func = relay.Call(global_var, [])\n        main_func = relay.Function([], call_extern_func, relay.TensorType((), \"float32\"))\n        main_var = relay.GlobalVar(\"main\")\n\n        mod = tvm.IRModule()\n        mod[global_var] = extern_func\n        mod[main_var] = main_func\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    expected = get_mod()[\"external_function\"].body\n    actual = ScalarToTensorConstants()(get_mod())[\"external_function\"].body\n    assert tvm.ir.structural_equal(expected, actual)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/test_softmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN integration tests: Softmax\"\"\"\nimport itertools\n\nimport numpy as np\nimport pytest\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.op.contrib import cmsisnn\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\n\nfrom .utils import (\n    skip_if_no_reference_system,\n    make_module,\n    get_range_for_dtype_str,\n    assert_partitioned_function,\n    assert_no_external_function,\n    create_test_runner,\n)\n\n\ndef make_model(\n    shape, in_dtype, out_dtype, in_zero_point, in_scale, out_zero_point=-128, out_scale=1.0 / 256\n):\n    \"\"\"Create a Relay Function / network model\"\"\"\n    a = relay.var(\"in0\", shape=shape, dtype=in_dtype)\n    dequantize = relay.qnn.op.dequantize(\n        a,\n        input_scale=relay.const(in_scale, \"float32\"),\n        input_zero_point=relay.const(in_zero_point, \"int32\"),\n    )\n    softmax = relay.nn.softmax(dequantize)\n    model = relay.qnn.op.quantize(\n        softmax,\n        output_scale=relay.const(out_scale, \"float32\"),\n        output_zero_point=relay.const(out_zero_point, \"int32\"),\n        out_dtype=out_dtype,\n    )\n    return model\n\n\n@skip_if_no_reference_system\n@tvm.testing.requires_cmsisnn\n@pytest.mark.parametrize([\"zero_point\", \"scale\"], [[33, 0.256], [-64, 0.0128]])\n@pytest.mark.parametrize(\n    \"compiler_cpu, cpu_flags\", [(\"cortex-m55\", \"+nomve\"), (\"cortex-m55\", \"\"), (\"cortex-m7\", \"\")]\n)\ndef test_op_int8(zero_point, scale, compiler_cpu, cpu_flags):\n    \"\"\"Tests int8 QNN Softmax for CMSIS-NN\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = True\n\n    dtype = \"int8\"\n    shape = [1, 16, 16, 3]\n    model = make_model(shape, dtype, dtype, zero_point, scale)\n    orig_mod = make_module(model)\n\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n\n    # validate pattern matching\n    assert_partitioned_function(orig_mod, cmsisnn_mod)\n\n    # validate the output\n    in_min, in_max = get_range_for_dtype_str(dtype)\n    np.random.seed(0)\n    input_data = np.random.randint(in_min, high=in_max, size=shape, dtype=dtype)\n    inputs = {\"in0\": input_data}\n    params = {}\n    output_list = generate_ref_data(orig_mod[\"main\"], inputs, params)\n    compile_and_run(\n        AOTTestModel(module=cmsisnn_mod, inputs=inputs, outputs=output_list, params=params),\n        create_test_runner(compiler_cpu, cpu_flags),\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef parameterize_for_invalid_model(test):\n    \"\"\"Generates parameters for non int8 input and output of Softmax\"\"\"\n    in_dtype = [\"uint8\", \"int8\"]\n    out_dtype = [\"uint8\", \"int8\"]\n    zero_point = [-128, 64]\n    scale = [1.0 / 256, 0.2]\n    out_zero_point = [-128, 33]\n    out_scale = [1.0 / 256, 0.2]\n    all_combinations = itertools.product(\n        in_dtype, out_dtype, zero_point, scale, out_zero_point, out_scale\n    )\n    all_combinations = filter(\n        lambda parameters: not (\n            parameters[0] == \"int8\"\n            and parameters[1] == \"int8\"\n            and parameters[4] == -128\n            and parameters[5] == 1.0 / 256\n        ),\n        all_combinations,\n    )\n    return pytest.mark.parametrize(\n        [\"in_dtype\", \"out_dtype\", \"zero_point\", \"scale\", \"out_zero_point\", \"out_scale\"],\n        all_combinations,\n    )(test)\n\n\n@parameterize_for_invalid_model\n@tvm.testing.requires_cmsisnn\ndef test_invalid_parameters(in_dtype, out_dtype, zero_point, scale, out_zero_point, out_scale):\n    \"\"\"Tests for non int8 input and output of Softmax\"\"\"\n    model = make_model(\n        [1, 16, 16, 3], in_dtype, out_dtype, zero_point, scale, out_zero_point, out_scale\n    )\n\n    orig_mod = make_module(model)\n    cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod)\n    assert_no_external_function(cmsisnn_mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cmsisnn/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"CMSIS-NN functions for testing networks\"\"\"\n\nimport math\nfrom typing import List, Union, Tuple\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestRunner\n\n\ndef skip_if_no_reference_system(func):\n    return tvm.testing.skip_if_32bit(reason=\"Reference system unavailable in i386 container\")(func)\n\n\ndef count_num_calls(mod):\n    \"\"\"Counts number of CallNode(s) in the IRModule\"\"\"\n\n    class CallCounter(relay.ExprVisitor):\n        def __init__(self):\n            super().__init__()\n            self.count = 0\n\n        def visit_call(self, call):\n            if isinstance(call.op, tvm.ir.Op):\n                self.count += 1\n\n            super().visit_call(call)\n\n    counter = CallCounter()\n    for var in mod.get_global_vars():\n        counter.visit(mod[var.name_hint])\n    return counter.count\n\n\ndef assert_partitioned_function(orig_mod, cmsisnn_mod, expected_ops_unchanged=True):\n    \"\"\"\n    if KCompiler attribute is missing, this function raises an assertion.\n\n    Parameters\n    ----------\n    orig_mod : IRModule\n        Pre-partitioning module\n    cmsisnn_mod : IRModule\n        Post-partitioning module\n    is_num_calls_same: bool\n        Are number of CallNode(s) before and after partitioning expected to be the same\n    \"\"\"\n    attrs = [\n        cmsisnn_mod[var.name_hint].attrs\n        for var in cmsisnn_mod.get_global_vars()\n        if cmsisnn_mod[var.name_hint].attrs\n    ]\n    assert any(attrs), \"At least one function with external attributes was expected.\"\n\n    compilers = [\n        key == \"Compiler\" and value == \"cmsis-nn\" for attr in attrs for key, value in attr.items()\n    ]\n    assert any(compilers), \"Module does not contain function for cmsisnn target.\"\n\n    if expected_ops_unchanged:\n        assert count_num_calls(orig_mod) == count_num_calls(\n            cmsisnn_mod\n        ), \"Number of calls changed during partitioning\"\n\n\ndef assert_no_external_function(mod):\n    attrs = [mod[var.name_hint].attrs for var in mod.get_global_vars() if mod[var.name_hint].attrs]\n    assert not any(attrs), \"No function should have an external attribute.\"\n\n\ndef get_range_for_dtype_str(dtype):\n    \"\"\"\n    Produces the min,max for a give data type.\n\n    Parameters\n    ----------\n    dtype : str\n        a type string (e.g., int8)\n\n    Returns\n    -------\n    type_info.min : int\n        the minimum of the range\n    type_info.max : int\n        the maximum of the range\n    \"\"\"\n\n    try:\n        type_info = np.iinfo(dtype)\n    except ValueError:\n        type_info = np.finfo(dtype)\n    return type_info.min, type_info.max\n\n\ndef make_module(func):\n    \"\"\"Creates IRModule from Function\"\"\"\n    func = relay.Function(relay.analysis.free_vars(func), func)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    return mod\n\n\ndef get_same_padding(in_shape, kernel, dilation, stride):\n    \"\"\"\n    Provides CMSIS-NN padding when output dim == input dim.\n    This is TFLu's \"SAME\" padding case.\n    \"\"\"\n    dilated_kernel_h = dilation[0] * (kernel[0] - 1) + 1\n    out = int(math.ceil(float(in_shape[0]) / float(stride[0])))\n    pad = max(0, (out - 1) * stride[0] + dilated_kernel_h - in_shape[0])\n    pad_top = pad // 2\n    pad_bottom = pad - pad_top\n\n    dilated_kernel_w = dilation[1] * (kernel[1] - 1) + 1\n    out = int(math.ceil(float(in_shape[1]) / float(stride[1])))\n    pad = max(0, (out - 1) * stride[1] + dilated_kernel_w - in_shape[1])\n    pad_left = pad // 2\n    pad_right = pad - pad_left\n    return [pad_top, pad_left, pad_bottom, pad_right]\n\n\ndef get_kernel_bias_dtype(input_dtype):\n    \"\"\"\n    Returns (kernel_dtype, bias_dtype) based on input's dtype.\n    \"\"\"\n    # uint8 corresponds to an invalid case, so returning int types\n    # does not cause tests to break\n    if input_dtype in (\"int8\", \"uint8\"):\n        return (\"int8\", \"int32\")\n    elif input_dtype == \"int16\":\n        return (\"int8\", \"int64\")\n    raise ValueError(\"Invalid dtype provided to get_kernel_bias_dtype()\")\n\n\ndef get_conv2d_qnn_params(\n    kernel_shape: List[int],\n    input_scale: float,\n    input_zp: int,\n    kernel_scale: Union[float, List[float]],\n    kernel_zp: int,\n    input_dtype: str = \"int8\",\n    kernel_dtype: str = \"int8\",\n    output_dtype: str = \"int8\",\n    is_depthwise: bool = False,\n) -> Tuple[float, int]:\n    \"\"\"\n    Calculate the output quantization parameters for convolution based on the input and\n    kernel quantization paramters and the data types.\n\n    Parameters\n    ----------\n    kernel_shape : List[int]\n        shape of the kernel\n    input_scale : float\n        scale of the input tensor\n    input_zp : int\n        zero point of the input tensor\n    kernel_scale : Union[float, List[float]]\n        scale(s) of the kernel tensor\n    kernel_zp : int\n        zero point of the kernel tensor\n    is_depthwise : bool\n        whether it is a depthwise convolution\n    input_dtype : str\n        data type of the input tensor\n    kernel_dtype : str\n        data type of the kernel tensor\n    output_dtype : str\n        data type of the output tensor\n\n    Returns\n    -------\n    output_scale : float\n        scale of the output tensor\n    output_zp : int\n        zero point of the output tensor\n    \"\"\"\n    input_dtype_min, input_dtype_max = get_range_for_dtype_str(input_dtype)\n    input_max = input_scale * (input_dtype_max - input_zp)\n    input_min = input_scale * (input_dtype_min - input_zp)\n\n    kernel_dtype_min, kernel_dtype_max = get_range_for_dtype_str(kernel_dtype)\n    kernel_sc_max = np.max(kernel_scale)\n    kernel_max = kernel_sc_max * (kernel_dtype_max - kernel_zp)\n\n    kernel_sc_min = np.min(kernel_scale)\n    kernel_min = kernel_sc_min * (kernel_dtype_min - kernel_zp)\n\n    kernel_h = kernel_shape[1]\n    kernel_w = kernel_shape[2]\n    channels = kernel_shape[3]\n    num_elements = kernel_h * kernel_w * channels\n    # Adjust the result if it is a depthwise convolution\n    if is_depthwise:\n        num_elements = num_elements / channels\n\n    # The smallest and largest possible values in the unquantized output tensor\n    output_limits = [\n        kernel_max * input_max * num_elements,\n        kernel_min * input_max * num_elements,\n        kernel_min * input_min * num_elements,\n        kernel_max * input_min * num_elements,\n    ]\n\n    output_max = max(output_limits)\n    output_min = min(output_limits)\n    output_dtype_min, output_dtype_max = get_range_for_dtype_str(output_dtype)\n\n    output_scale = (output_max - output_min) / (output_dtype_max - output_dtype_min)\n    output_zp = int(output_dtype_min - (output_min / output_scale))\n\n    return output_scale, output_zp\n\n\ndef make_qnn_relu(expr, fused_activation_fn, scale, zero_point, dtype):\n    \"\"\"Mimics convert_qnn_fused_activation_function from TFLite frontend\"\"\"\n    quantize = lambda x: float(int(round(x / scale)) + zero_point)\n\n    # Get min/max of the output dtype. This will be used to ensure that clip a_min/a_max are not\n    # beyond the dtype range.\n    qmin, qmax = get_range_for_dtype_str(dtype)\n\n    # The input expr is a quantized tensor with its scale and zero point. We calculate the\n    # suitable clip off points based on these scale and zero point.\n    if fused_activation_fn == \"NONE\":\n        return expr\n    if fused_activation_fn == \"RELU6\":\n        return tvm.relay.op.clip(expr, a_min=max(qmin, quantize(0)), a_max=min(qmax, quantize(6.0)))\n    if fused_activation_fn == \"RELU_N1_TO_1\":\n        return tvm.relay.op.clip(\n            expr, a_min=max(qmin, quantize(-1.0)), a_max=min(qmax, quantize(1.0))\n        )\n    if fused_activation_fn == \"RELU\":\n        return tvm.relay.op.clip(expr, a_min=max(qmin, quantize(0.0)), a_max=qmax)\n    raise ValueError(\"Invalid argument provided with fused_activation_fn\")\n\n\nclass CheckForPadsWithinCompositeFunc(tvm.relay.ExprVisitor):\n    \"\"\"Provides method to test number of pads present inside the function being visited.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.num_pads_ = 0\n\n    def visit_call(self, call):\n        super().visit_call(call)\n        if (\n            isinstance(call, tvm.relay.Call)\n            and isinstance(call.op, tvm.ir.op.Op)\n            and call.op.name == \"nn.pad\"\n        ):\n            self.num_pads_ += 1\n\n    def assert_no_pads_within_func(self):\n        assert self.num_pads_ == 0, \"CMSIS-NN composite function should not have pads.\"\n\n    def assert_pads_within_func(self):\n        assert self.num_pads_ > 0, \"Composite function should have pads within it.\"\n\n\ndef create_test_runner(compiler_cpu=\"cortex-m55\", cpu_flags=\"\"):\n    \"\"\"\n    Creates AOT test runner for CMSIS-NN tests.\n\n    Parameters\n    ----------\n    compiler_cpu : str\n       Equivalent of gcc option mcpu\n       Options:  cortex-m55, cortex-m7\n    cpu_flags: str\n        Disable Arm(R) Cortex(R)-M profile vector extension (mve)\n        Options:\n        Arm(R) Cortex(R)-M55: when null +mve is set by default.\n            +nomve disables vector extensions.\n        Arm(R) Cortex(R)-M7 does not support mve.\n    \"\"\"\n    # cmsis_cpu is used to find out start up code inside CMSIS package\n    cmsis_cpu = \"ARMCM7\" if compiler_cpu == \"cortex-m7\" else \"ARMCM55\"\n    mfloat_abi = \"soft\" if compiler_cpu == \"cortex-m7\" else \"hard\"\n    return AOTTestRunner(\n        makefile=\"corstone300\",\n        prologue=\"\"\"\n        uart_init();\n        \"\"\",\n        includes=[\"uart.h\"],\n        pass_config={\n            \"relay.ext.cmsisnn.options\": {\n                \"mcpu\": compiler_cpu + cpu_flags,\n            },\n            \"tir.usmp.enable\": True,\n            \"tir.disable_storage_rewrite\": True,\n        },\n        parameters={\n            \"ARM_CPU\": cmsis_cpu,\n            \"MCPU\": compiler_cpu,\n            \"MCPU_FLAGS\": cpu_flags,\n            \"MFLOAT_ABI\": mfloat_abi,\n        },\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_coreml_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nfrom unittest import mock\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.contrib.target import coreml as _coreml\n\nrequires_coremltools = tvm.testing.requires_package(\"coremltools\")\n\n\ndef _has_xcode():\n    try:\n        tvm.contrib.xcode.xcrun([])\n        return True\n    except FileNotFoundError:\n        pass\n\n    return False\n\n\ndef _create_graph():\n    shape = (10, 10)\n    mod = tvm.IRModule()\n\n    x = relay.var(\"x\", shape=shape)\n    y = relay.var(\"y\", shape=shape)\n    z = x + x\n    p = y * y\n    func = relay.Function([x, y], p - z)\n    mod[\"main\"] = func\n\n    return mod\n\n\ndef _create_graph_annotated():\n    shape = (10, 10)\n    target = \"coremlcompiler\"\n    mod = tvm.IRModule()\n\n    # function 0\n    f0_i0 = relay.var(target + \"_0_i0\", shape=shape)\n    func0 = relay.Function([f0_i0], f0_i0 * f0_i0)\n\n    func0 = func0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func0 = func0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func0 = func0.with_attr(\"Compiler\", target)\n    func0 = func0.with_attr(\"global_symbol\", target + \"_0\")\n    gv0 = relay.GlobalVar(target + \"_0\")\n    mod[gv0] = func0\n\n    # function 2\n    f2_i0 = relay.var(target + \"_2_i0\", shape=shape)\n    func2 = relay.Function([f2_i0], f2_i0 + f2_i0)\n\n    func2 = func2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func2 = func2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func2 = func2.with_attr(\"Compiler\", target)\n    func2 = func2.with_attr(\"global_symbol\", target + \"_2\")\n    gv2 = relay.GlobalVar(target + \"_2\")\n    mod[gv2] = func2\n    mod = relay.transform.InferType()(mod)\n\n    # body\n    x = relay.var(\"x\", shape=shape)\n    y = relay.var(\"y\", shape=shape)\n    func = relay.Function([x, y], gv0(y) - gv2(x))\n    mod[\"main\"] = func\n    mod = relay.transform.InferType()(mod)\n\n    return mod\n\n\n@pytest.mark.xfail(\n    reason=\"Currently failing test.  See tracking issue https://github.com/apache/tvm/issues/8901\"\n)\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_annotate():\n    mod = _create_graph()\n    mod = transform.AnnotateTarget(\"coremlcompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    expected = _create_graph_annotated()\n    assert tvm.ir.structural_equal(mod, expected, map_free_vars=True)\n\n\n@pytest.mark.skipif(not _has_xcode(), reason=\"Xcode is not available\")\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_compile_and_run():\n    dev = tvm.cpu()\n    target = \"llvm\"\n    tol = 1e-3\n\n    with relay.build_config(opt_level=3):\n        lib = relay.build(_create_graph_annotated(), target=target)\n    m = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    shape = (10, 10)\n    x_data = np.random.rand(*shape).astype(\"float32\")\n    y_data = np.random.rand(*shape).astype(\"float32\")\n\n    m.set_input(\"x\", x_data)\n    m.set_input(\"y\", y_data)\n    m.run()\n    out = tvm.nd.empty(shape, device=dev)\n    out = m.get_output(0, out)\n\n    expected = (y_data * y_data) - (x_data + x_data)\n    tvm.testing.assert_allclose(out.numpy(), expected, rtol=tol, atol=tol)\n\n\n@mock.patch(\"tvm.contrib.coreml_runtime.create\")\n@mock.patch(\"tvm.contrib.xcode.compile_coreml\")\ndef _construct_model(func, m1, m2):\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    mod = transform.AnnotateTarget(\"coremlcompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    fcompile = tvm._ffi.get_global_func(\"relay.ext.coremlcompiler\")\n\n    for var, func in mod.functions.items():\n        if func.attrs and \"Compiler\" in func.attrs and func.attrs[\"Compiler\"] == \"coremlcompiler\":\n            fcompile(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_add():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = x + x\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_multiply():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = x * x\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_clip():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.clip(x, a_min=0.0, a_max=1.0)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_batch_flatten():\n    shape = (10, 10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.batch_flatten(x)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_expand_dims():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.expand_dims(x, axis=0)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n    y = relay.expand_dims(x, axis=-1)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_relu():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.relu(x)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_softmax():\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.softmax(x, axis=1)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_conv2d():\n    x = relay.var(\"x\", shape=(1, 3, 224, 224))\n    w = relay.const(np.zeros((16, 3, 3, 3), dtype=\"float32\"))\n    y = relay.nn.conv2d(x, w, strides=[2, 2], padding=[1, 1, 1, 1], kernel_size=[3, 3])\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\n@tvm.testing.uses_gpu\n@requires_coremltools\ndef test_global_avg_pool2d():\n    shape = (10, 10, 10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.global_avg_pool2d(x)\n    func = relay.Function([x], y)\n    _construct_model(func)\n\n\nif __name__ == \"__main__\":\n    test_annotate()\n    test_compile_and_run()\n    test_add()\n    test_multiply()\n    test_clip()\n    test_expand_dims()\n    test_relu()\n    test_batch_flatten()\n    test_softmax()\n    test_conv2d()\n    test_global_avg_pool2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_coreml_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.contrib import utils, xcode, coreml_runtime\n\nimport pytest\nimport os\n\nproxy_host = os.environ.get(\"TVM_IOS_RPC_PROXY_HOST\", \"127.0.0.1\")\nproxy_port = os.environ.get(\"TVM_IOS_RPC_PROXY_PORT\", 9090)\ndestination = os.environ.get(\"TVM_IOS_RPC_DESTINATION\", \"\")\nkey = \"iphone\"\n\n\n@pytest.mark.skip(\"skip because coremltools is not available in CI\")\ndef test_coreml_runtime():\n\n    import coremltools\n    from coremltools.models.neural_network import NeuralNetworkBuilder\n\n    def create_coreml_model():\n        shape = (2,)\n        alpha = 2\n\n        inputs = [\n            (\"input0\", coremltools.models.datatypes.Array(*shape)),\n            (\"input1\", coremltools.models.datatypes.Array(*shape)),\n        ]\n        outputs = [\n            (\"output0\", coremltools.models.datatypes.Array(*shape)),\n            (\"output1\", coremltools.models.datatypes.Array(*shape)),\n        ]\n        builder = NeuralNetworkBuilder(inputs, outputs)\n        builder.add_elementwise(\n            name=\"Add\", input_names=[\"input0\", \"input1\"], output_name=\"output0\", mode=\"ADD\"\n        )\n        builder.add_elementwise(\n            name=\"Mul\", alpha=alpha, input_names=[\"input0\"], output_name=\"output1\", mode=\"MULTIPLY\"\n        )\n        return coremltools.models.MLModel(builder.spec)\n\n    def verify(coreml_model, model_path, dev):\n        coreml_model = create_coreml_model()\n\n        out_spec = coreml_model.output_description._fd_spec\n        out_names = [spec.name for spec in out_spec]\n\n        # inference via coremltools\n        inputs = {}\n        for in_spec in coreml_model.input_description._fd_spec:\n            name = in_spec.name\n            shape = in_spec.type.multiArrayType.shape\n            inputs[name] = np.random.random_sample(shape)\n\n        coreml_outputs = [coreml_model.predict(inputs)[name] for name in out_names]\n\n        # inference via tvm coreml runtime\n        runtime = coreml_runtime.create(\"main\", model_path, dev)\n        for name in inputs:\n            runtime.set_input(name, tvm.nd.array(inputs[name], dev))\n        runtime.invoke()\n        tvm_outputs = [runtime.get_output(i).numpy() for i in range(runtime.get_num_outputs())]\n\n        for c_out, t_out in zip(coreml_outputs, tvm_outputs):\n            np.testing.assert_almost_equal(c_out, t_out, 3)\n\n    def check_remote(coreml_model):\n        temp = utils.tempdir()\n        compiled_model = xcode.compile_coreml(coreml_model, out_dir=temp.temp_dir)\n        xcode.popen_test_rpc(\n            proxy_host, proxy_port, key, destination=destination, libs=[compiled_model]\n        )\n        compiled_model = os.path.basename(compiled_model)\n        remote = rpc.connect(proxy_host, proxy_port, key=key)\n        dev = remote.cpu(0)\n        verify(coreml_model, compiled_model, dev)\n\n    def check_local(coreml_model):\n        temp = utils.tempdir()\n        compiled_model = xcode.compile_coreml(coreml_model, out_dir=temp.temp_dir)\n        dev = tvm.cpu(0)\n        verify(coreml_model, compiled_model, dev)\n\n    coreml_model = create_coreml_model()\n    check_remote(coreml_model)\n    check_local(coreml_model)\n\n\nif __name__ == \"__main__\":\n    test_coreml_runtime()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cublas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nimport numpy as np\nfrom tvm.contrib import cublas\nfrom tvm.contrib import cublaslt\nfrom tvm.contrib import graph_executor\nimport tvm.testing\nfrom tvm.relay.op.contrib import get_pattern_table\nfrom tvm.relay.op.contrib.cublas import partition_for_cublas\n\n\ndef verify_matmul_add(in_dtype, out_dtype, rtol=1e-5):\n    n = 1024\n    l = 128\n    m = 236\n    A = te.placeholder((n, l), name=\"A\", dtype=in_dtype)\n    B = te.placeholder((l, m), name=\"B\", dtype=in_dtype)\n    C = cublas.matmul(A, B, dtype=out_dtype)\n    s = te.create_schedule(C.op)\n\n    def verify(target=\"cuda\"):\n        if not tvm.get_global_func(\"tvm.contrib.cublas.matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cuda(0)\n        f = tvm.build(s, [A, B, C], target)\n        a = tvm.nd.array(np.random.uniform(0, 128, size=(n, l)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(0, 128, size=(l, m)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(\n            c.numpy(), np.dot(a.numpy().astype(C.dtype), b.numpy().astype(C.dtype)), rtol=rtol\n        )\n\n    verify()\n\n\ndef roundoff(v, d):\n    return int(np.floor((v + d - 1) / d) * d)\n\n\ndef verify_matmul_add_igemm(in_dtype, out_dtype, rtol=1e-5):\n    n = 1024\n    l = 1024\n    m = 1024\n    L = roundoff(l, 32)\n    N = roundoff(n, 8)\n    N_out = roundoff(n, 32)\n\n    A = te.placeholder((N, L), name=\"A\", dtype=in_dtype)\n    B = te.placeholder((m, L), name=\"B\", dtype=in_dtype)\n    # C has CUBLASLT_ORDER_COL32 layout, thus a different shape\n    C = cublaslt.matmul(A, B, False, True, m, N_out, dtype=out_dtype)\n    s = te.create_schedule(C.op)\n\n    def verify(target=\"cuda\"):\n        if not tvm.get_global_func(\"tvm.contrib.cublaslt.matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cuda(0)\n        f = tvm.build(s, [A, B, C], target)\n        a_old = np.random.uniform(0, 128, size=(n, l))\n        b_old = np.random.uniform(0, 128, size=(l, m))\n\n        # Transform a to become CUBLASLT_ORDER_COL4_4R2_8C layout\n        a_new = np.hstack((a_old.astype(A.dtype), np.zeros([n, L - l])))\n        a_new = np.vstack((a_new.astype(A.dtype), np.zeros([N - n, L])))\n        a_even = np.vsplit(a_new[::2], N / 8)\n        a_odd = np.vsplit(a_new[1::2], N / 8)\n        a_new = [None] * (len(a_even) + len(a_odd))\n        a_new[::2] = a_even\n        a_new[1::2] = a_odd\n        a_new = np.vstack(a_new)\n        a_new = np.vstack(\n            np.vstack(np.vstack(np.hsplit(i, 8)).reshape([4, 32]) for i in np.vsplit(j, N / 4))\n            for j in np.hsplit(a_new, L / 32)\n        )\n        a_new = a_new.reshape([N, L])\n        # Transform b to become CUBLASLT_ORDER_COL32 layout\n        b_new = np.vstack(\n            np.hsplit(np.hstack((b_old.T.astype(B.dtype), np.zeros([m, L - l]))), L / 32)\n        )\n        b_new = b_new.reshape([m, L])\n\n        a = tvm.nd.array(a_new.astype(A.dtype), dev)\n        b = tvm.nd.array(b_new.astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((m, N_out), dtype=C.dtype), dev)\n        f(a, b, c)\n        # Transform output c from layout CUBLASLT_ORDER_COL32 to row major layout\n        c_out = c.numpy()\n        c_out = c_out.reshape([int(m * N_out / 32), 32])\n        c_out = np.hstack(np.vsplit(c_out, int(N_out / 32)))\n        c_out = c_out[:, :n]\n        c_out = c_out.T\n        tvm.testing.assert_allclose(\n            c_out, np.dot(a_old.astype(C.dtype), b_old.astype(C.dtype)), rtol=rtol\n        )\n\n    verify()\n\n\ndef verify_batch_matmul(Ashape, Bshape, Cshape, in_dtype, out_dtype, rtol=1e-5):\n    A = te.placeholder(Ashape, name=\"A\", dtype=in_dtype)\n    B = te.placeholder(Bshape, name=\"B\", dtype=in_dtype)\n    C = cublas.batch_matmul(A, B, dtype=out_dtype)\n    s = te.create_schedule(C.op)\n\n    dev = tvm.cuda(0)\n    f = tvm.build(s, [A, B, C], \"cuda\")\n\n    if \"int\" in in_dtype:\n        a = tvm.nd.array(np.random.uniform(1, 10, size=Ashape).astype(in_dtype), dev)\n        b = tvm.nd.array(np.random.uniform(1, 10, size=Bshape).astype(in_dtype), dev)\n    else:\n        a = tvm.nd.array(np.random.uniform(size=Ashape).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=Bshape).astype(B.dtype), dev)\n\n    c = tvm.nd.array(np.zeros(Cshape, dtype=C.dtype), dev)\n    f(a, b, c)\n    tvm.testing.assert_allclose(\n        c.numpy(),\n        np.matmul(a.numpy().astype(C.dtype), b.numpy().astype(C.dtype)).astype(C.dtype),\n        rtol=rtol,\n    )\n\n\n@tvm.testing.requires_cuda\ndef test_matmul_add():\n    verify_matmul_add(\"float\", \"float\", rtol=1e-3)\n    verify_matmul_add(\"float16\", \"float\")\n    verify_matmul_add(\"float16\", \"float16\", rtol=1e-2)\n    verify_matmul_add(\"int8\", \"int32\")\n\n\n@tvm.testing.requires_cuda\ndef test_matmul_add_igemm():\n    verify_matmul_add_igemm(\"int8\", \"int32\")\n\n\n@tvm.testing.requires_cuda\ndef test_batch_matmul():\n    if not tvm.get_global_func(\"tvm.contrib.cublas.matmul\", True):\n        print(\"skip because extern function is not available\")\n        return\n\n    verify_batch_matmul((16, 1024, 128), (16, 128, 236), (16, 1024, 236), \"float\", \"float\")\n    verify_batch_matmul((16, 1024, 128), (1, 128, 236), (16, 1024, 236), \"float\", \"float\")\n    verify_batch_matmul((16, 1024, 128), (16, 128, 236), (16, 1024, 236), \"float16\", \"float\")\n    verify_batch_matmul((16, 1024, 128), (1, 128, 236), (16, 1024, 236), \"float16\", \"float\")\n    verify_batch_matmul(\n        (16, 1024, 128), (16, 128, 236), (16, 1024, 236), \"float16\", \"float16\", rtol=1e-2\n    )\n    verify_batch_matmul(\n        (16, 1024, 128), (1, 128, 236), (16, 1024, 236), \"float16\", \"float16\", rtol=1e-2\n    )\n\n    verify_batch_matmul((16, 1024, 128), (16, 128, 236), (16, 1024, 236), \"int8\", \"int32\")\n\n\ndef _verify_cublas_relay(expr):\n    np.random.seed(42)\n\n    mod = tvm.IRModule.from_expr(expr)\n    mod = relay.transform.InferType()(mod)\n    func = mod[\"main\"]\n    cublas_mod = partition_for_cublas(mod)\n    assert len(cublas_mod.get_global_vars()) == 2\n\n    input_data = []\n    for param in func.params:\n        shape = [int(x) for x in param.checked_type.shape]\n        input_data.append(\n            (param.name_hint, np.random.uniform(0, 32, size=shape).astype(param.checked_type.dtype))\n        )\n\n    # Test against CPU reference\n    cuda_config = (tvm.target.cuda(), tvm.cuda(), cublas_mod)\n    cpu_config = (tvm.target.Target(\"llvm\"), tvm.cpu(), mod)\n    outputs = []\n    for target, dev, test_mod in [cuda_config, cpu_config]:\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(test_mod, target=target, target_host=cpu_config[0])\n            module = graph_executor.GraphModule(lib[\"default\"](dev))\n            for name, data in input_data:\n                module.set_input(name, tvm.nd.array(data, dev))\n\n            module.run()\n            out_type = func.body.checked_type\n            outputs.append(\n                module.get_output(0, tvm.nd.empty(out_type.shape, dtype=out_type.dtype)).numpy()\n            )\n\n    tvm.testing.assert_allclose(\n        outputs[0],\n        outputs[1],\n        rtol=1e-2,\n    )\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,m,k,transpose_a,transpose_b\",\n    [\n        (64, 128, 32, False, False),\n        (17, 32, 16, True, False),\n        (24, 17, 12, False, True),\n        (96, 4, 17, True, True),\n    ],\n)\n@pytest.mark.parametrize(\n    \"in_dtype,out_dtype\",\n    [\n        (\"float32\", \"float32\"),\n        (\"float16\", \"float16\"),\n        (\"float16\", \"float32\"),\n        (\"int8\", \"int32\"),\n        (\"float64\", \"float64\"),\n        (\"int8\", \"float32\"),\n    ],\n)\ndef test_relay_cublas_matmul(n, m, k, in_dtype, out_dtype, transpose_a, transpose_b):\n    unsupported_configs = [\n        (17, 32, 16, \"int8\", \"float32\", True, False),\n        (96, 4, 17, \"int8\", \"float32\", True, True),\n        (17, 32, 16, \"int8\", \"int32\", True, False),\n        (96, 4, 17, \"int8\", \"int32\", True, True),\n    ]\n    if (n, m, k, in_dtype, out_dtype, transpose_a, transpose_b) in unsupported_configs:\n        pytest.skip(\"Unsupported parameters.\")\n\n    a_shape = (k, n) if transpose_a else (n, k)\n    b_shape = (m, k) if transpose_b else (k, m)\n    a = tvm.relay.var(\"A\", tvm.relay.TensorType(a_shape, in_dtype))\n    b = tvm.relay.var(\"B\", tvm.relay.TensorType(b_shape, in_dtype))\n    # Directly use matmul because nn.matmul sometimes defers to nn.dense\n    matmul = relay.op.nn._make.matmul(a, b, None, out_dtype, transpose_a, transpose_b)\n    _verify_cublas_relay(matmul)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,m,k\",\n    [\n        (64, 128, 32),\n        (17, 32, 16),\n        (24, 17, 12),\n        (96, 4, 17),\n    ],\n)\n@pytest.mark.parametrize(\n    \"in_dtype,out_dtype\",\n    [\n        (\"float32\", \"float32\"),\n        (\"float16\", \"float16\"),\n        (\"float16\", \"float32\"),\n        (\"int8\", \"int32\"),\n        (\"float64\", \"float64\"),\n        (\"int8\", \"float32\"),\n    ],\n)\ndef test_relay_cublas_dense(n, m, k, in_dtype, out_dtype):\n    unsupported_configs = [\n        (96, 4, 17, \"int8\", \"float32\"),\n        (96, 4, 17, \"int8\", \"int32\"),\n    ]\n    if (n, m, k, in_dtype, out_dtype) in unsupported_configs:\n        pytest.skip(\"Unsupported parameters.\")\n\n    data = tvm.relay.var(\"data\", tvm.relay.TensorType((n, k), in_dtype))\n    weight = tvm.relay.var(\"weight\", tvm.relay.TensorType((m, k), in_dtype))\n    dense = relay.op.nn.dense(data, weight, out_dtype=out_dtype)\n    _verify_cublas_relay(dense)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,m,k,batch_a,batch_b,transpose_a,transpose_b\",\n    [\n        (64, 128, 32, 16, 16, False, False),\n        (17, 32, 16, 16, 1, True, False),\n        (24, 17, 12, 17, 17, False, True),\n        (96, 4, 17, 53, 1, True, True),\n    ],\n)\n@pytest.mark.parametrize(\n    \"in_dtype,out_dtype\",\n    [\n        (\"float32\", \"float32\"),\n        (\"float16\", \"float16\"),\n        (\"float16\", \"float32\"),\n        (\"int8\", \"int32\"),\n        (\"float64\", \"float64\"),\n        (\"int8\", \"float32\"),\n    ],\n)\ndef test_relay_cublas_batch_matmul(\n    n, m, k, batch_a, batch_b, in_dtype, out_dtype, transpose_a, transpose_b\n):\n    unsupported_configs = [\n        (17, 32, 16, 16, 1, \"int8\", \"float32\", True, False),\n        (96, 4, 17, 53, 1, \"int8\", \"float32\", True, True),\n        (17, 32, 16, 16, 1, \"int8\", \"int32\", True, False),\n        (96, 4, 17, 53, 1, \"int8\", \"int32\", True, True),\n    ]\n    if (\n        n,\n        m,\n        k,\n        batch_a,\n        batch_b,\n        in_dtype,\n        out_dtype,\n        transpose_a,\n        transpose_b,\n    ) in unsupported_configs:\n        pytest.skip(\"Unsupported parameters.\")\n\n    a_shape = (batch_a, k, n) if transpose_a else (batch_a, n, k)\n    b_shape = (batch_b, m, k) if transpose_b else (batch_b, k, m)\n    a = tvm.relay.var(\"A\", tvm.relay.TensorType(a_shape, in_dtype))\n    b = tvm.relay.var(\"B\", tvm.relay.TensorType(b_shape, in_dtype))\n    batch_matmul = relay.op.nn.batch_matmul(a, b, out_dtype, transpose_a, transpose_b)\n    _verify_cublas_relay(batch_matmul)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,m,k\",\n    [\n        (64, 128, 32),\n        (17, 32, 16),\n        (24, 17, 12),\n        (96, 4, 17),\n    ],\n)\n@pytest.mark.parametrize(\n    \"in_dtype,out_dtype\",\n    [\n        (\"float32\", \"float32\"),\n        (\"float16\", \"float16\"),\n        (\"float16\", \"float32\"),\n        (\"int8\", \"int32\"),\n        (\"float64\", \"float64\"),\n        (\"int8\", \"float32\"),\n    ],\n)\ndef test_relay_cublas_dense(n, m, k, in_dtype, out_dtype):\n    unsupported_configs = [\n        (96, 4, 17, \"int8\", \"float32\"),\n        (96, 4, 17, \"int8\", \"int32\"),\n    ]\n    if (n, m, k, in_dtype, out_dtype) in unsupported_configs:\n        pytest.skip(\"Unsupported parameters.\")\n\n    data = tvm.relay.var(\"data\", tvm.relay.TensorType((n, k), in_dtype))\n    weight = tvm.relay.var(\"weight\", tvm.relay.TensorType((m, k), in_dtype))\n    dense = relay.op.nn.dense(data, weight, out_dtype=out_dtype)\n    _verify_cublas_relay(dense)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cudnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.contrib import cudnn\nfrom tvm.contrib.nvcc import have_fp16\nfrom tvm.contrib import graph_executor\nimport numpy as np\nimport tvm.topi.testing\nimport tvm.testing\nfrom tvm.relay.op.contrib.cudnn import partition_for_cudnn\n\n\nrequires_cudnn = pytest.mark.skipif(\n    tvm.get_global_func(\"tvm.contrib.cudnn.conv2d.forward\", True) is None,\n    reason=\"CuDNN is not enabled\",\n)\n\n\ndef verify_conv2d(data_dtype, conv_dtype, tensor_format=0, groups=1):\n    in_channel = 4\n    out_channel = 16\n    filter_h = 3\n    filter_w = 3\n    pad_h = 1\n    pad_w = 1\n    stride_h = 1\n    stride_w = 1\n    dilation_h = 1\n    dilation_w = 1\n    batch = 3\n    height = 32\n    width = 32\n\n    if data_dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n        print(\"Skip because gpu does not have fp16 support\")\n        return\n\n    # schedule\n    if tensor_format == 0:\n        xshape = [batch, in_channel, height, width]\n        wshape = [out_channel, in_channel // groups, filter_h, filter_w]\n    else:\n        xshape = [batch, height, width, in_channel]\n        wshape = [out_channel, filter_h, filter_w, in_channel // groups]\n\n    X = te.placeholder(xshape, name=\"X\", dtype=data_dtype)\n    W = te.placeholder(wshape, name=\"W\", dtype=data_dtype)\n    Y = cudnn.conv_forward(\n        X,\n        W,\n        [pad_h, pad_w],\n        [stride_h, stride_w],\n        [dilation_h, dilation_w],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        conv_dtype=conv_dtype,\n        algo=-1,\n        groups=groups,\n    )\n    yshape = [x.value for x in Y.shape]\n    s = te.create_schedule(Y.op)\n\n    # validation\n    dev = tvm.cuda(0)\n    f = tvm.build(s, [X, W, Y], \"cuda --host=llvm\", name=\"conv2d\")\n    x_np = np.random.uniform(-1, 1, xshape).astype(data_dtype)\n    w_np = np.random.uniform(-1, 1, wshape).astype(data_dtype)\n    y_np = np.zeros(yshape).astype(data_dtype)\n    x = tvm.nd.array(x_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    y = tvm.nd.array(y_np, dev)\n    if tensor_format == 0:\n        c_np = tvm.topi.testing.conv2d_nchw_python(x_np, w_np, 1, 1, groups=groups)\n    elif tensor_format == 1:\n        wt = w_np.transpose((1, 2, 3, 0))  # OHWI => HWIO\n        c_np = tvm.topi.testing.conv2d_nhwc_python(x_np, wt, 1, 1, groups=groups)\n\n    f(x, w, y)\n    tvm.testing.assert_allclose(y.numpy(), c_np, atol=1e-2, rtol=1e-2)\n\n\n@tvm.testing.requires_gpu\n@requires_cudnn\ndef test_conv2d():\n    verify_conv2d(\"float32\", \"float32\", tensor_format=0)\n    verify_conv2d(\"float16\", \"float32\", tensor_format=1)\n    verify_conv2d(\"float16\", \"float16\", tensor_format=0)\n    verify_conv2d(\"float16\", \"float16\", tensor_format=1)\n    verify_conv2d(\"int8\", \"int32\", tensor_format=1)\n\n    verify_conv2d(\"float32\", \"float32\", tensor_format=0, groups=2)\n    verify_conv2d(\"float16\", \"float32\", tensor_format=1, groups=2)\n    verify_conv2d(\"float16\", \"float16\", tensor_format=0, groups=2)\n    verify_conv2d(\"int8\", \"int32\", tensor_format=1, groups=2)\n\n\ndef verify_conv3d(data_dtype, conv_dtype, tensor_format=0, groups=1):\n    in_channel = 4\n    out_channel = 16\n    filter_d = 3\n    filter_h = 3\n    filter_w = 3\n    pad_d = 1\n    pad_h = 1\n    pad_w = 1\n    stride_d = 1\n    stride_h = 1\n    stride_w = 1\n    dilation_d = 1\n    dilation_h = 1\n    dilation_w = 1\n    batch = 3\n    depth = 32\n    height = 32\n    width = 32\n\n    # schedule\n    xshape = [batch, in_channel, depth, height, width]\n    wshape = [out_channel, in_channel // groups, filter_d, filter_h, filter_w]\n\n    X = te.placeholder(xshape, name=\"X\", dtype=data_dtype)\n    W = te.placeholder(wshape, name=\"W\", dtype=data_dtype)\n    Y = cudnn.conv_forward(\n        X,\n        W,\n        [pad_d, pad_h, pad_w],\n        [stride_d, stride_h, stride_w],\n        [dilation_d, dilation_h, dilation_w],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        algo=-1,\n        conv_dtype=conv_dtype,\n        groups=groups,\n    )\n    yshape = [x.value for x in Y.shape]\n    s = te.create_schedule(Y.op)\n\n    # validation\n    dev = tvm.cuda(0)\n    f = tvm.build(s, [X, W, Y], target=\"cuda --host=llvm\", name=\"conv3d\")\n    x_np = np.random.uniform(-1, 1, xshape).astype(data_dtype)\n    w_np = np.random.uniform(-1, 1, wshape).astype(data_dtype)\n    y_np = np.zeros(yshape).astype(data_dtype)\n    x = tvm.nd.array(x_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    y = tvm.nd.array(y_np, dev)\n    if tensor_format == 0:\n        c_np = tvm.topi.testing.conv3d_ncdhw_python(x_np, w_np, 1, 1, groups)\n    else:\n        raise AssertionError(\"For now, conv3d tensor format only support: 0(NCHW)\")\n\n    f(x, w, y)\n    tvm.testing.assert_allclose(y.numpy(), c_np, atol=3e-5, rtol=1e-4)\n\n\n@tvm.testing.requires_gpu\n@requires_cudnn\ndef test_conv3d():\n    verify_conv3d(\"float32\", \"float32\", tensor_format=0)\n    verify_conv3d(\"float32\", \"float32\", tensor_format=0, groups=2)\n\n\ndef verify_softmax(shape, axis, dtype=\"float32\", log_softmax=False):\n    cudnn_op = cudnn.log_softmax if log_softmax else cudnn.softmax\n    testing_op = (\n        tvm.topi.testing.log_softmax_python if log_softmax else tvm.topi.testing.softmax_python\n    )\n\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = cudnn_op(A, axis)\n    s = te.create_schedule([B.op])\n\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    b_np = testing_op(a_np)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    f = tvm.build(s, [A, B], target=\"cuda --host=llvm\", name=\"softmax\")\n    f(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3)\n\n\ndef verify_softmax_4d(shape, dtype=\"float32\", log_softmax=False):\n    cudnn_op = cudnn.log_softmax if log_softmax else cudnn.softmax\n    testing_op = (\n        tvm.topi.testing.log_softmax_python if log_softmax else tvm.topi.testing.softmax_python\n    )\n\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = cudnn_op(A, axis=1)\n    s = te.create_schedule([B.op])\n\n    dev = tvm.cuda(0)\n    n, c, h, w = shape\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    b_np = testing_op(a_np.transpose(0, 2, 3, 1).reshape(h * w, c))\n    b_np = b_np.reshape(n, h, w, c).transpose(0, 3, 1, 2)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    f = tvm.build(s, [A, B], target=\"cuda --host=llvm\", name=\"softmax\")\n    f(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3)\n\n\n@tvm.testing.requires_gpu\n@requires_cudnn\ndef test_softmax():\n    verify_softmax((32, 10), -1)\n    verify_softmax((3, 4), -1)\n    verify_softmax((1, 5), -1, \"float64\")\n    verify_softmax_4d((1, 16, 256, 256))\n    verify_softmax_4d((1, 16, 256, 256), \"float64\")\n\n    verify_softmax((32, 10), -1, log_softmax=True)\n    verify_softmax((3, 4), -1, log_softmax=True)\n    verify_softmax((1, 5), -1, \"float64\", log_softmax=True)\n    verify_softmax_4d((1, 16, 256, 256), log_softmax=True)\n    verify_softmax_4d((1, 16, 256, 256), \"float64\", log_softmax=True)\n\n\ndef verify_conv2d_backward_data(data_dtype, conv_dtype, tensor_format=0, tol=1e-5):\n    batch = 3\n    in_channel = 4\n    out_channel = 16\n    filter_h, filter_w = 3, 3\n    pad_h, pad_w = 1, 1\n    stride_h, stride_w = 1, 1\n    height, width = 32, 32\n\n    if tensor_format == 0:\n        xshape = [batch, in_channel, height, width]\n        wshape = [out_channel, in_channel, filter_h, filter_w]\n        oshape = xshape\n        oshape[1] = out_channel\n        ref_func = tvm.topi.testing.conv2d_transpose_nchw_python\n    else:\n        xshape = [batch, height, width, in_channel]\n        wshape = [out_channel, filter_h, filter_w, in_channel]\n        oshape = xshape\n        oshape[3] = out_channel\n        ref_func = lambda dy_np, w_np, strides, padding, out_pad: tvm.topi.testing.conv2d_transpose_nhwc_python(\n            dy_np, np.transpose(w_np, [1, 2, 3, 0]), \"HWOI\", strides, padding, out_pad\n        )\n\n    dy_np = np.random.uniform(-1, 1, oshape).astype(data_dtype)\n    w_np = np.random.uniform(-1, 1, wshape).astype(data_dtype)\n\n    if data_dtype == \"float16\":\n        dx_np = ref_func(\n            dy_np.astype(\"float32\"),\n            w_np.astype(\"float32\"),\n            (stride_h, stride_w),\n            (pad_h, pad_w),\n            (0, 0),\n        )\n        dx_np = dx_np.astype(\"float16\")\n    else:\n        dx_np = ref_func(dy_np, w_np, (stride_h, stride_w), (pad_h, pad_w), (0, 0))\n\n    dy = te.placeholder(oshape, name=\"dy\", dtype=data_dtype)\n    w = te.placeholder(wshape, name=\"dw\", dtype=data_dtype)\n    dx = cudnn.conv_backward_data(\n        dy,\n        w,\n        [pad_h, pad_w],\n        [stride_h, stride_w],\n        [1, 1],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        conv_dtype=conv_dtype,\n        groups=1,\n    )\n\n    s = te.create_schedule(dx.op)\n\n    dev = tvm.cuda(0)\n    f = tvm.build(s, [dy, w, dx], \"cuda --host=llvm\", name=\"conv2d_backward_data\")\n\n    dy = tvm.nd.array(dy_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    dx = tvm.nd.array(dx_np, dev)\n\n    f(dy, w, dx)\n    tvm.testing.assert_allclose(dx.numpy(), dx_np, atol=tol, rtol=tol)\n\n\n@tvm.testing.requires_gpu\n@requires_cudnn\ndef test_conv2d_backward_data():\n    verify_conv2d_backward_data(\"float32\", \"float32\", tensor_format=0, tol=1e-5)\n    verify_conv2d_backward_data(\"float32\", \"float32\", tensor_format=1, tol=1e-2)\n    # The scipy convolve function does not support fp16, so the reference will be computed with\n    # fp32. Use larger tolerance to be on the safe side (1e-2 also seems mostly ok).\n    verify_conv2d_backward_data(\"float16\", \"float16\", tensor_format=1, tol=1e-1)\n\n\ndef verify_conv2d_backward_filter(data_dtype, conv_dtype, tensor_format=0, tol=1e-5):\n    batch = 3\n    in_channel = 4\n    out_channel = 16\n    filter_h, filter_w = 3, 3\n    pad_h, pad_w = 1, 1\n    stride_h, stride_w = 1, 1\n    height, width = 32, 32\n\n    if tensor_format == 0:\n        x_shape = [batch, in_channel, height, width]\n        dy_shape = [batch, out_channel, height, width]\n    else:\n        x_shape = [batch, height, width, in_channel]\n        dy_shape = [batch, height, width, out_channel]\n\n    x_np = np.random.uniform(-1, 1, x_shape).astype(data_dtype)\n    dy_np = np.random.uniform(-1, 1, dy_shape).astype(data_dtype)\n\n    dw_np = tvm.topi.testing.conv2d_backward_weight_python(\n        dy_np,\n        x_np,\n        (filter_h, filter_w),\n        (stride_h, stride_w),\n        (pad_h, pad_w),\n        \"NCHW\" if tensor_format == 0 else \"NHWC\",\n    )\n\n    x = te.placeholder(x_shape, name=\"x\", dtype=data_dtype)\n    dy = te.placeholder(dy_shape, name=\"dy\", dtype=data_dtype)\n    dw = cudnn.conv_backward_filter(\n        dy,\n        x,\n        (filter_h, filter_w),\n        [pad_h, pad_w],\n        [stride_h, stride_w],\n        [1, 1],\n        conv_mode=1,\n        tensor_format=tensor_format,\n        conv_dtype=conv_dtype,\n    )\n\n    s = te.create_schedule(dw.op)\n\n    dev = tvm.cuda(0)\n    f = tvm.build(s, [dy, x, dw], \"cuda --host=llvm\", name=\"conv2d_backward_filter\")\n\n    x = tvm.nd.array(x_np, dev)\n    dy = tvm.nd.array(dy_np, dev)\n    dw = tvm.nd.array(dw_np, dev)\n\n    f(dy, x, dw)\n    tvm.testing.assert_allclose(dw.numpy(), dw_np, atol=tol, rtol=tol)\n\n\n@tvm.testing.requires_gpu\n@requires_cudnn\ndef test_conv2d_backward_filter():\n    verify_conv2d_backward_filter(\"float32\", \"float32\", tensor_format=0, tol=1e-2)\n    verify_conv2d_backward_filter(\"float32\", \"float32\", tensor_format=1, tol=1e-2)\n\n\ntest_kwargs_default_2d = {\n    \"tensor_format\": 0,\n    \"pad\": [1, 1],\n    \"stride\": [1, 1],\n    \"dilation\": [1, 1],\n    \"x_shape\": [16, 4, 32, 32],\n    \"w_shape\": [8, 4, 3, 3],\n    \"groups\": 1,\n    \"conv_dtype\": \"float32\",\n    \"data_dtype\": \"float32\",\n}\ntest_kwargs_default_3d = {\n    \"tensor_format\": 0,\n    \"pad\": [1, 1, 1],\n    \"stride\": [1, 1, 1],\n    \"dilation\": [1, 1, 1],\n    \"x_shape\": [16, 4, 32, 32, 32],\n    \"w_shape\": [8, 4, 3, 3, 3],\n    \"groups\": 1,\n    \"conv_dtype\": \"float32\",\n    \"data_dtype\": \"float32\",\n}\nconv_output_shape_conditions = {\n    \"2d_small\": test_kwargs_default_2d,\n    \"2d_large\": {\n        **test_kwargs_default_2d,\n        \"x_shape\": [16, 32, 512, 1024],\n        \"w_shape\": [8, 32, 5, 5],\n    },\n    \"2d_pad\": {**test_kwargs_default_2d, \"pad\": [2, 3]},\n    \"2d_stride\": {**test_kwargs_default_2d, \"stride\": [2, 3]},\n    \"2d_dilation\": {**test_kwargs_default_2d, \"dilation\": [2, 3]},\n    \"2d_groups\": {**test_kwargs_default_2d, \"groups\": 4, \"w_shape\": [8, 1, 3, 3]},\n    \"2d_NHWC\": {\n        **test_kwargs_default_2d,\n        \"tensor_format\": 1,\n        \"x_shape\": [16, 32, 32, 4],\n        \"w_shape\": [8, 3, 3, 4],\n    },\n    \"2d_NCHW_VECT_C\": {\n        **test_kwargs_default_2d,\n        \"tensor_format\": 2,\n        \"w_shape\": [8, 16, 3, 3],\n        \"data_dtype\": \"int8x4\",\n    },\n    \"3d_small\": test_kwargs_default_3d,\n    \"3d_large\": {\n        **test_kwargs_default_3d,\n        \"x_shape\": [16, 32, 64, 128, 256],\n        \"w_shape\": [8, 32, 5, 5, 5],\n    },\n    \"3d_pad\": {**test_kwargs_default_3d, \"pad\": [2, 3, 4]},\n    \"3d_stride\": {**test_kwargs_default_3d, \"stride\": [2, 3, 4]},\n    \"3d_dilation\": {**test_kwargs_default_3d, \"dilation\": [2, 3, 4]},\n    \"3d_groups\": {**test_kwargs_default_3d, \"groups\": 4, \"w_shape\": [8, 1, 3, 3, 3]},\n    \"3d_NCHW_VECT_C\": {\n        **test_kwargs_default_3d,\n        \"tensor_format\": 2,\n        \"w_shape\": [8, 16, 3, 3, 3],\n        \"data_dtype\": \"int8x4\",\n    },\n}\n\n\n@pytest.fixture(\n    params=[pytest.param(kwargs, id=name) for name, kwargs in conv_output_shape_conditions.items()]\n)\ndef conv_output_shape_kwargs(request):\n    return request.param\n\n\ndef _verify_cudnn_relay(expr):\n    np.random.seed(42)\n\n    mod = tvm.IRModule.from_expr(expr)\n    mod = relay.transform.InferType()(mod)\n    func = mod[\"main\"]\n    cudnn_mod = partition_for_cudnn(mod)\n    assert len(cudnn_mod.get_global_vars()) == 2\n\n    input_data = []\n    for param in func.params:\n        shape = [int(x) for x in param.checked_type.shape]\n        input_data.append(\n            (\n                param.name_hint,\n                np.random.uniform(-32, 32, size=shape).astype(param.checked_type.dtype),\n            )\n        )\n\n    cuda_config = (tvm.target.cuda(), tvm.cuda(), cudnn_mod)\n    cpu_config = (tvm.target.Target(\"llvm\"), tvm.cpu(), mod)\n    outputs = []\n    for target, dev, test_mod in [cuda_config, cpu_config]:\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(test_mod, target=target, target_host=cpu_config[0])\n            module = graph_executor.GraphModule(lib[\"default\"](dev))\n            for name, data in input_data:\n                module.set_input(name, tvm.nd.array(data, dev))\n\n            module.run()\n            out_type = func.body.checked_type\n            outputs.append(\n                module.get_output(0, tvm.nd.empty(out_type.shape, dtype=out_type.dtype)).numpy()\n            )\n\n    tvm.testing.assert_allclose(\n        outputs[0],\n        outputs[1],\n        rtol=1e-3,\n        atol=30,\n    )\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"shape,axis\",\n    [\n        ((200,), 0),\n        ((13, 27), 0),\n        ((44, 12, 67), 1),\n        ((1, 16, 16, 8), 2),\n        ((2, 4, 6, 8, 10), 3),\n    ],\n)\n@pytest.mark.parametrize(\n    \"dtype\",\n    [\n        \"float32\",\n        \"float16\",\n        \"float64\",\n    ],\n)\ndef test_relay_cudnn_softmax(shape, axis, dtype):\n    x = tvm.relay.var(\"x\", tvm.relay.TensorType(shape, dtype))\n    softmax = relay.op.nn.softmax(x, axis=axis)\n    _verify_cudnn_relay(softmax)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"shape,axis\",\n    [\n        ((32, 16), -1),\n        ((13, 27), 1),\n    ],\n)\n@pytest.mark.parametrize(\n    \"dtype\",\n    [\n        \"float32\",\n        \"float16\",\n        \"float64\",\n    ],\n)\ndef test_relay_cudnn_log_softmax(shape, axis, dtype):\n    x = tvm.relay.var(\"x\", tvm.relay.TensorType(shape, dtype))\n    log_softmax = relay.op.nn.log_softmax(x, axis=axis)\n    _verify_cudnn_relay(log_softmax)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,h,w,ci,co,groups\",\n    [\n        (1, 16, 20, 8, 16, 1),\n        (10, 17, 19, 16, 8, 4),\n    ],\n)\n@pytest.mark.parametrize(\n    \"kh,kw,padding\",\n    [\n        (1, 1, (3, 1, 3, 1)),\n        (3, 3, (1, 2)),\n        (7, 2, (0, 0)),\n    ],\n)\n@pytest.mark.parametrize(\n    \"strides,dilation,dtype\",\n    [\n        ((1, 1), (1, 1), \"float32\"),\n        ((2, 1), (2, 2), \"float16\"),\n        ((3, 3), (1, 2), \"float64\"),\n    ],\n)\ndef test_relay_cudnn_conv2d(n, h, w, ci, co, kh, kw, strides, dilation, padding, groups, dtype):\n    data = tvm.relay.var(\"data\", tvm.relay.TensorType((n, ci, h, w), dtype))\n    weight = tvm.relay.var(\"weight\", tvm.relay.TensorType((co, ci // groups, kh, kw), dtype))\n    conv2d = relay.op.nn.conv2d(\n        data,\n        weight,\n        groups=groups,\n        channels=co,\n        kernel_size=(kh, kw),\n        strides=strides,\n        dilation=dilation,\n        padding=padding,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n    )\n    _verify_cudnn_relay(conv2d)\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"n,h,w,ci,co,groups\",\n    [\n        (1, 16, 20, 8, 16, 1),\n        (10, 17, 19, 16, 8, 4),\n    ],\n)\n@pytest.mark.parametrize(\n    \"kh,kw,padding,strides,dilation,dtype\",\n    [\n        (1, 1, (3, 1, 3, 1), (1, 1), (1, 1), \"float32\"),\n        (3, 3, (1, 2), (2, 1), (2, 2), \"float16\"),\n        (7, 2, (0, 0), (3, 3), (1, 2), \"float64\"),\n    ],\n)\n@pytest.mark.parametrize(\"activation\", [True, False])\ndef test_relay_cudnn_conv2d_bias_act(\n    n, h, w, ci, co, kh, kw, strides, dilation, padding, groups, dtype, activation\n):\n    data = tvm.relay.var(\"data\", tvm.relay.TensorType((n, ci, h, w), dtype))\n    weight = tvm.relay.var(\"weight\", tvm.relay.TensorType((co, ci // groups, kh, kw), dtype))\n    bias = relay.var(\"bias\", relay.TensorType((co,), dtype))\n    conv2d = relay.op.nn.conv2d(\n        data,\n        weight,\n        groups=groups,\n        channels=co,\n        kernel_size=(kh, kw),\n        strides=strides,\n        dilation=dilation,\n        padding=padding,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n    )\n    out = relay.op.nn.bias_add(conv2d, bias)\n    if activation:\n        out = relay.op.nn.relu(out)\n\n    _verify_cudnn_relay(out)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_cutlass.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport logging\nimport math\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.cudnn import conv_output_shape\nimport numpy as np\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.relay.op.contrib.cutlass import partition_for_cutlass\nfrom tvm.relay.transform import FirstOrderGradient, ToMixedPrecision, InferType\nfrom tvm.contrib.cutlass import (\n    has_cutlass,\n    num_cutlass_partitions,\n    finalize_modules,\n    finalize_modules_vm,\n)\nimport tvm.testing\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef has_cublas():\n    return tvm.get_global_func(\"tvm.contrib.cublas.matmul\", True) != None\n\n\ndef get_ref_rt_mod(mod, params, target=\"cuda\"):\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, params=params)\n    dev = tvm.device(target, 0)\n    rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    return rt_mod, dev\n\n\ndef get_ref_vm(mod, params, target=\"cuda\"):\n    with tvm.transform.PassContext(opt_level=3):\n        vm_exec = relay.vm.compile(mod, target=target, params=params)\n        code, lib = vm_exec.save()\n    dev = tvm.device(target, 0)\n    vm_exec = tvm.runtime.vm.Executable.load_exec(code, lib)\n    return VirtualMachine(vm_exec, dev), dev\n\n\ndef get_output(rt_mod, names, inputs):\n    for name, inp in zip(names, inputs):\n        rt_mod.set_input(name, inp)\n    rt_mod.run()\n    return rt_mod.get_output(0).asnumpy()\n\n\ndef get_output_vm(vm, names, inputs):\n    params = dict(zip(names, inputs))\n    return vm.invoke(\"main\", **params).numpy()\n\n\ndef get_dense_with_shape(\n    data_shape, weight_shape, out_dtype=\"float16\", data_dtype=\"float16\", weight_dtype=\"float16\"\n):\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=weight_dtype)\n    return relay.nn.dense(data, weight, out_dtype=out_dtype)\n\n\ndef get_dense(M, N, K, out_dtype=\"float16\", data_dtype=\"float16\", weight_dtype=\"float16\"):\n    return get_dense_with_shape((M, K), (N, K), out_dtype, data_dtype, weight_dtype)\n\n\ndef get_dense_bias(M, N, K, out_dtype=\"float16\"):\n    dense = get_dense(M, N, K, out_dtype=out_dtype)\n    bias = relay.var(\"bias\", shape=(N,), dtype=out_dtype)\n    return relay.nn.bias_add(dense, bias)\n\n\ndef get_dense_bias_relu(M, N, K, out_dtype=\"float16\"):\n    return relay.nn.relu(get_dense_bias(M, N, K, out_dtype=out_dtype))\n\n\ndef get_dense_bias_gelu(M, N, K, out_dtype=\"float16\"):\n    bias_add = get_dense_bias(M, N, K, out_dtype)\n    mul = bias_add * relay.const((1.0 / math.sqrt(2.0)), dtype=out_dtype)\n    if out_dtype == \"float16\":\n        erf = relay.cast(relay.op.erf(relay.cast(mul, \"float32\")), \"float16\")\n    else:\n        erf = relay.op.erf(mul)\n    mul_half = erf * relay.const(0.5, dtype=out_dtype)\n    add = mul_half + relay.const(0.5, dtype=out_dtype)\n    return add * bias_add\n\n\ndef get_batch_matmul_with_shape(x_shape, y_shape, out_dtype=\"float16\"):\n    x = relay.var(\"x\", shape=x_shape, dtype=\"float16\")\n    y = relay.var(\"y\", shape=y_shape, dtype=\"float16\")\n    return relay.nn.batch_matmul(x, y, out_dtype=out_dtype)\n\n\ndef get_batch_matmul(batch, M, N, K, out_dtype=\"float16\"):\n    return get_batch_matmul_with_shape((batch, M, K), (batch, N, K), out_dtype=\"float16\")\n\n\ndef get_conv2d_nchw(\n    d_shape,\n    w_shape,\n    padding,\n    strides=(1, 1),\n    out_dtype=\"float16\",\n    data_dtype=\"float16\",\n    weight_dtype=\"float16\",\n):\n    data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=w_shape, dtype=weight_dtype)\n    out_channel = w_shape[0]\n    return relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=padding,\n        strides=strides,\n        out_dtype=out_dtype,\n    )\n\n\ndef get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    conv2d = get_conv2d_nchw(d_shape, w_shape, padding, out_dtype=out_dtype)\n    bias = relay.var(\"bias\", shape=(w_shape[0],), dtype=out_dtype)\n    return relay.nn.bias_add(conv2d, bias)\n\n\ndef silu(x):\n    return x * relay.sigmoid(x)\n\n\ndef hardswish(x, out_dtype=\"float16\"):\n    return x * (\n        relay.clip(x + relay.const(3, dtype=out_dtype), a_min=0, a_max=6)\n        / relay.const(6, dtype=out_dtype)\n    )\n\n\ndef get_conv2d_nchw_bias_relu(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    return relay.nn.relu(get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype))\n\n\ndef get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    return relay.sigmoid(get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype))\n\n\ndef get_conv2d_nchw_bias_silu(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    conv_out = get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype)\n    return silu(conv_out)\n\n\ndef get_conv2d_nchw_bias_hardswish(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    conv_out = get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype)\n    return hardswish(conv_out, out_dtype)\n\n\ndef get_conv2d_nchw_bias_residual(d_shape, w_shape, padding, out_dtype=\"float16\"):\n    data = relay.var(\"data\", shape=d_shape, dtype=\"float16\")\n    weight = relay.var(\"weight\", shape=w_shape, dtype=\"float16\")\n    bias = relay.var(\"bias\", shape=(w_shape[0],), dtype=out_dtype)\n    out_channel = w_shape[0]\n    conv2d = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=padding,\n        out_dtype=out_dtype,\n    )\n    bias_add = relay.nn.bias_add(conv2d, bias)\n    return bias_add, data\n\n\ndef get_conv2d_transpose_nchw(\n    d_shape,\n    w_shape,\n    padding,\n    output_padding,\n    strides,\n    out_dtype=\"float32\",\n    data_dtype=\"float32\",\n    weight_dtype=\"float32\",\n):\n    data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=w_shape, dtype=weight_dtype)\n    out_channel = w_shape[1]\n    return relay.nn.conv2d_transpose(\n        data=data,\n        weight=weight,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=padding,\n        output_padding=output_padding,\n        strides=strides,\n        out_dtype=out_dtype,\n    )\n\n\ndef get_conv2d_backward_weight(\n    d_shape,\n    w_shape,\n    o_shape,\n    padding,\n    strides,\n    out_dtype=\"float32\",\n    data_dtype=\"float32\",\n    weight_dtype=\"float32\",\n):\n    grad = relay.var(\"grad\", shape=o_shape, dtype=weight_dtype)\n    data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n    out_channel = o_shape[1]\n    return relay.nn.conv2d_backward_weight(\n        grad=grad,\n        data=data,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=padding,\n        strides=strides,\n        out_dtype=out_dtype,\n    )\n\n\ndef convert_conv2d_layout(mod, desired_layouts):\n    with tvm.transform.PassContext(opt_level=3):\n        seq = tvm.transform.Sequential([relay.transform.ConvertLayout(desired_layouts)])\n        return seq(mod)\n\n\ndef get_random_ndarray(shape, dtype):\n    if dtype == \"int8\":\n        return np.random.randint(-128, 128, shape).astype(dtype)\n    elif dtype == \"uint8\":\n        return np.random.randint(0, 256, shape).astype(dtype)\n    return np.random.uniform(-1, 1, shape).astype(dtype)\n\n\ndef profile_and_build(\n    mod,\n    params,\n    sm,\n    split_k_slices=[1],\n    tmp_dir=\"./tmp\",\n    use_fast_math=False,\n    use_3xtf32=True,\n):\n    logging.info(\"before partitioning:\\n%s\", mod)\n    mod = partition_for_cutlass(mod)\n    logging.info(\"after partitioning:\\n%s\", mod)\n\n    num_cutlass_partition = num_cutlass_partitions(mod)\n    host = tvm.target.Target(\"llvm\")\n    cuda = tvm.target.Target(\"cuda\", host=host)\n    cutlass = tvm.target.Target(\n        {\n            \"kind\": \"cutlass\",\n            \"sm\": sm,\n            \"use_3xtf32\": use_3xtf32,\n            \"split_k_slices\": split_k_slices,\n            \"profile_all_alignments\": False,\n            \"find_first_valid\": True,\n            \"use_multiprocessing\": True,\n            \"use_fast_math\": use_fast_math,\n            \"tmp_dir\": tmp_dir,\n        },\n        host=host,\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=[cuda, cutlass], params=params)\n    lib = finalize_modules(lib, \"compile.so\", tmp_dir)\n    dev = tvm.device(\"cuda\", 0)\n    rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    return rt_mod, dev, num_cutlass_partition\n\n\ndef profile_and_build_vm(\n    mod,\n    params,\n    sm,\n    split_k_slices=[1],\n    tmp_dir=\"./tmp\",\n    use_fast_math=False,\n    use_3xtf32=True,\n):\n    mod = partition_for_cutlass(mod)\n    num_cutlass_partition = num_cutlass_partitions(mod)\n    host = tvm.target.Target(\"llvm\")\n    cuda = tvm.target.Target(\"cuda\", host=host)\n    cutlass = tvm.target.Target(\n        {\n            \"kind\": \"cutlass\",\n            \"sm\": sm,\n            \"use_3xtf32\": use_3xtf32,\n            \"split_k_slices\": split_k_slices,\n            \"profile_all_alignments\": False,\n            \"find_first_valid\": True,\n            \"use_multiprocessing\": True,\n            \"use_fast_math\": use_fast_math,\n            \"tmp_dir\": tmp_dir,\n        },\n        host=host,\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        vm_exec = relay.vm.compile(mod, target=[cuda, cutlass], params=params)\n    vm_exec = finalize_modules_vm(vm_exec, \"compile.so\", tmp_dir)\n    dev = tvm.device(\"cuda\", 0)\n    return VirtualMachine(vm_exec, dev), dev, num_cutlass_partition\n\n\ndef verify_dense(\n    func,\n    M,\n    N,\n    K,\n    ref_target=\"cuda\",\n    sm=80,\n    atol=1e-5,\n    rtol=1e-5,\n    run_benchmark=False,\n    data_dtype=\"float16\",\n    weight_dtype=\"float16\",\n    use_3xtf32=True,\n):\n    assert has_cutlass()\n    if sm < 80 and data_dtype == \"float32\":\n        return\n\n    mod = tvm.IRModule.from_expr(func)\n    typ = relay.transform.InferType()(mod)[\"main\"].body.checked_type\n    out_dtype = typ.dtype\n    use_vm = any(isinstance(s, tvm.tir.Any) for s in typ.shape)\n    np_data = get_random_ndarray((M, K), data_dtype)\n    np_weight = get_random_ndarray((N, K), weight_dtype)\n    np_bias = get_random_ndarray((N,), out_dtype)\n\n    params = {\"weight\": np_weight, \"bias\": np_bias}\n\n    if use_vm:\n        if ref_target == \"cuda\" and out_dtype == \"float16\":\n            # Uncomment \"return\" below to see the accuracy difference of static vs dynamic TVM native fp16 dense\n            # The static one can use a tensorcore schedule, but the dynamic one cannot\n            rt_mod, dev = get_ref_vm(tvm.IRModule.from_expr(get_dense(M, N, K)), params)\n            num_partition = 1\n            logging.warning(\n                \"The reference fp16 dense with dynamic shape using fp16 accumulation has accuracy issues.\"\n            )\n            return\n        else:\n            rt_mod, dev, num_partition = profile_and_build_vm(\n                mod, params, sm, use_3xtf32=use_3xtf32\n            )\n\n        rt_mod_ref, dev = get_ref_vm(mod, params, target=ref_target)\n        x = tvm.nd.array(np_data, device=dev)\n        out = get_output_vm(rt_mod, [\"data\"], [x])\n        ref_out = get_output_vm(rt_mod_ref, [\"data\"], [x])\n    else:\n        rt_mod_ref, dev = get_ref_rt_mod(mod, params, target=ref_target)\n        rt_mod, dev, num_partition = profile_and_build(mod, params, sm, use_3xtf32=use_3xtf32)\n        x = tvm.nd.array(np_data, device=dev)\n        out = get_output(rt_mod, [\"data\"], [x])\n        ref_out = get_output(rt_mod_ref, [\"data\"], [x])\n\n    assert num_partition > 0\n    np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)\n\n    if run_benchmark:\n        print(\"CUTLASS:\", rt_mod.benchmark(dev, number=1, repeat=600))\n        print(\"TVM with target %s:\" % ref_target, rt_mod_ref.benchmark(dev, number=1, repeat=600))\n\n\ndef verify_batch_matmul(\n    func, batch, M, N, K, ref_target=\"cuda\", sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n):\n    assert has_cutlass()\n    mod = tvm.IRModule.from_expr(func)\n    typ = relay.transform.InferType()(mod)[\"main\"].body.checked_type\n    use_vm = any(isinstance(s, tvm.tir.Any) for s in typ.shape)\n    x_np = np.random.uniform(-1, 1, (batch, M, K)).astype(\"float16\")\n    y_np = np.random.uniform(-1, 1, (batch, N, K)).astype(\"float16\")\n\n    if use_vm:\n        rt_mod, dev, num_partition = profile_and_build_vm(mod, {}, sm)\n        rt_mod_ref, dev = get_ref_vm(mod, {}, target=ref_target)\n        assert num_partition > 0\n        x = tvm.nd.array(x_np, device=dev)\n        y = tvm.nd.array(y_np, device=dev)\n        out = get_output_vm(rt_mod, [\"x\", \"y\"], [x, y])\n        ref_out = get_output_vm(rt_mod_ref, [\"x\", \"y\"], [x, y])\n    else:\n        rt_mod, dev, num_partition = profile_and_build(mod, {}, sm)\n        rt_mod_ref, dev = get_ref_rt_mod(mod, {})\n        assert num_partition > 0\n\n        x = tvm.nd.array(x_np, device=dev)\n        y = tvm.nd.array(y_np, device=dev)\n        out = get_output(rt_mod, [\"x\", \"y\"], [x, y])\n        ref_out = get_output(rt_mod_ref, [\"x\", \"y\"], [x, y])\n\n    np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)\n\n    if run_benchmark:\n        print(\"CUTLASS:\", rt_mod.benchmark(dev, number=1, repeat=600))\n        print(\"TVM Tensorcore (no tuning):\", rt_mod_ref.benchmark(dev, number=1, repeat=600))\n\n\nM = 96\nN = 64\nK = 64\n\n\n@tvm.testing.requires_cutlass\ndef test_dense():\n    verify_dense(get_dense(M, N, K), M, N, K)\n    verify_dense(get_dense(M, N, K, out_dtype=\"float32\"), M, N, K)\n    # Test align1 case\n    verify_dense(get_dense_bias(M, N + 1, K), M, N + 1, K)\n    # int8\n    verify_dense(\n        get_dense(M, N, K, \"int32\", \"int8\", \"int8\"), M, N, K, data_dtype=\"int8\", weight_dtype=\"int8\"\n    )\n\n    dense_fp32 = get_dense(M, N, K, \"float32\", \"float32\", \"float32\")\n    # tf32\n    verify_dense(\n        dense_fp32,\n        M,\n        N,\n        K,\n        data_dtype=\"float32\",\n        weight_dtype=\"float32\",\n        use_3xtf32=False,\n        atol=1e-2,\n        rtol=1e-2,\n    )\n    # 3xtf32\n    verify_dense(\n        dense_fp32,\n        M,\n        N,\n        K,\n        data_dtype=\"float32\",\n        weight_dtype=\"float32\",\n    )\n\n\n@tvm.testing.requires_cutlass\ndef test_dense_bias():\n    verify_dense(get_dense_bias(M, N, K), M, N, K)\n    verify_dense(get_dense_bias(M, N, K, out_dtype=\"float32\"), M, N, K)\n\n\n@tvm.testing.requires_cutlass\ndef test_dense_bias_relu():\n    verify_dense(get_dense_bias_relu(M, N, K), M, N, K)\n    verify_dense(get_dense_bias_relu(M, N, K, out_dtype=\"float32\"), M, N, K)\n\n\n@tvm.testing.requires_cutlass\ndef test_dense_bias_gelu():\n    verify_dense(get_dense_bias_gelu(M, N, K), M, N, K, atol=1e-3, rtol=1e-3)\n    verify_dense(get_dense_bias_gelu(M, N, K, out_dtype=\"float32\"), M, N, K, atol=1e-3, rtol=1e-3)\n\n\n@tvm.testing.requires_cutlass\ndef test_dense_dynamic():\n    data_shape = (relay.Any(), K)\n    weight_shape = (relay.Any(), K)\n\n    if has_cublas():\n        # TVM native fp16 dense (without tensorcore), using fp16 accum, seems to have accuracy issues\n        # Use cublas as a reference\n\n        verify_dense(\n            get_dense_with_shape(data_shape, weight_shape),\n            M,\n            N,\n            K,\n            ref_target=\"cuda -libs=cublas\",\n        )\n\n    verify_dense(\n        get_dense_with_shape(data_shape, weight_shape, out_dtype=\"float32\"),\n        M,\n        N,\n        K,\n        atol=1e-4,\n        rtol=1e-4,\n    )\n\n\n@tvm.testing.requires_cutlass\ndef test_batch_matmul():\n    batch = 8\n    verify_batch_matmul(get_batch_matmul(batch, M, N, K), batch, M, N, K)\n    verify_batch_matmul(get_batch_matmul(batch, M, N, K, out_dtype=\"float32\"), batch, M, N, K)\n\n    if has_cublas():\n        # Test dynamic shape batch_matmul\n        # AutoTVM does not seem to support it\n        x_shape = (relay.Any(), relay.Any(), K)\n        y_shape = (relay.Any(), relay.Any(), K)\n\n        verify_batch_matmul(\n            get_batch_matmul_with_shape(x_shape, y_shape),\n            batch,\n            M,\n            N,\n            K,\n            ref_target=\"cuda -libs=cublas\",\n        )\n\n\ndef verify_conv2d_common(\n    expr_nchw,  # can be dynamic batch\n    expr_ref,  # always static batch\n    input_names,\n    inputs,\n    params,\n    sm=80,\n    split_k_slices=[1],\n    atol=1e-5,\n    rtol=1e-5,\n    use_cudnn_ref=False,\n    run_benchmark=False,\n    use_fast_math=False,\n    ref_target=\"cuda\",\n    use_vm=False,\n):\n    assert has_cutlass()\n    if sm < 80 and inputs[0].dtype == \"float32\":\n        return\n\n    mod_nchw = tvm.IRModule.from_expr(expr_nchw)\n    mod_ref = tvm.IRModule.from_expr(expr_ref)\n\n    if use_vm:\n        profile_and_build_func = profile_and_build_vm\n        get_output_func = get_output_vm\n        ref_build_func = get_ref_vm\n    else:\n        profile_and_build_func = profile_and_build\n        get_output_func = get_output\n        ref_build_func = get_ref_rt_mod\n\n    mod_weight_ohwi = convert_conv2d_layout(\n        mod_nchw,\n        {\n            \"nn.conv2d\": [\"NHWC\", \"OHWI\"],\n            \"nn.conv2d_transpose\": [\"NHWC\", \"IHWO\"],\n            \"nn.conv2d_backward_weight\": [\"NHWC\", \"OHWI\"],\n        },\n    )\n\n    rt_mod, _, num_cutlass_partition = profile_and_build_func(\n        mod_weight_ohwi, params, sm, split_k_slices, use_fast_math=use_fast_math\n    )\n    out = get_output_func(rt_mod, input_names, inputs)\n\n    assert num_cutlass_partition > 0\n\n    if use_cudnn_ref:\n        rt_mod_ref, dev = ref_build_func(\n            convert_conv2d_layout(mod_ref, {\"nn.conv2d\": [\"NHWC\", \"OHWI\"]}),\n            params,\n            target=\"cuda -libs=cudnn\",\n        )\n    else:\n        rt_mod_ref, dev = ref_build_func(\n            convert_conv2d_layout(mod_ref, {\"nn.conv2d\": [\"NHWC\", \"HWIO\"]}),\n            params,\n            target=ref_target,\n        )\n\n    ref_out = get_output_func(rt_mod_ref, input_names, inputs)\n\n    if run_benchmark:\n        print(\"CUTLASS:\", rt_mod.benchmark(dev, number=1, repeat=600))\n        print(\"TVM Tensorcore (no tuning):\", rt_mod_ref.benchmark(dev, number=1, repeat=600))\n\n    np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)\n\n\ndef verify_conv2d(\n    expr_nchw,  # can be dynamic batch\n    expr_ref,  # always static batch\n    d_shape,\n    w_shape,\n    sm=80,\n    atol=1e-5,\n    rtol=1e-5,\n    use_cudnn_ref=False,\n    run_benchmark=False,\n    use_fast_math=False,\n    data_dtype=\"float16\",\n    weight_dtype=\"float16\",\n    ref_target=\"cuda\",\n    use_vm=False,\n):\n    mod_nchw = tvm.IRModule.from_expr(expr_nchw)\n    typ = relay.transform.InferType()(mod_nchw)[\"main\"].body.checked_type\n\n    use_vm = use_vm or any(isinstance(s, tvm.tir.Any) for s in typ.shape)\n\n    np_data = get_random_ndarray(d_shape, data_dtype)\n    np_weight = get_random_ndarray(w_shape, weight_dtype)\n    np_bias = get_random_ndarray((w_shape[0],), typ.dtype)\n    params = {\"weight\": np_weight, \"bias\": np_bias}\n\n    split_k_slices = [1]\n\n    return verify_conv2d_common(\n        expr_nchw,\n        expr_ref,\n        [\"data\"],\n        [np_data],\n        params,\n        sm,\n        split_k_slices,\n        atol,\n        rtol,\n        use_cudnn_ref,\n        run_benchmark,\n        use_fast_math,\n        ref_target,\n        use_vm,\n    )\n\n\ndef verify_conv2d_backward_weight(\n    expr_nchw,  # can be dynamic batch\n    expr_ref,  # always static batch\n    grad_shape,\n    data_shape,\n    sm=80,\n    split_k_slices=[1],\n    atol=1e-5,\n    rtol=1e-5,\n    use_cudnn_ref=False,\n    use_fast_math=False,\n    grad_dtype=\"float16\",\n    data_dtype=\"float16\",\n    ref_target=\"cuda\",\n    use_vm=False,\n):\n    np_grad = get_random_ndarray(grad_shape, grad_dtype)\n    np_data = get_random_ndarray(data_shape, data_dtype)\n    params = {}\n    input_names = [\"grad\", \"data\"]\n    return verify_conv2d_common(\n        expr_nchw,\n        expr_ref,\n        input_names,\n        [np_grad, np_data],\n        params,\n        sm,\n        split_k_slices,\n        atol,\n        rtol,\n        use_cudnn_ref,\n        False,\n        use_fast_math,\n        ref_target,\n        use_vm,\n    )\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d():\n    padding = (1, 1)\n    for IC in [3, 16]:\n        d_shape = (16, IC, 32, 32)\n        w_shape = (32, IC, 3, 3)\n        mod_nchw = get_conv2d_nchw(d_shape, w_shape, padding)\n\n        verify_conv2d(\n            mod_nchw,\n            mod_nchw,\n            d_shape,\n            w_shape,\n            sm=80,\n            atol=1e-5,\n            rtol=1e-5,\n            use_cudnn_ref=(IC == 3),  # The autotvm kernel has an accuracy issue with IC == 3 case\n            run_benchmark=False,\n        )\n\n    d_shape = (16, 16, 32, 32)\n    w_shape = (32, 16, 3, 3)\n    padding = (1, 1)\n    dyn_batch_shape = (relay.Any(),) + d_shape[1:]\n\n    mod_nchw = get_conv2d_nchw(d_shape, w_shape, padding)\n    mod_dyn = get_conv2d_nchw(dyn_batch_shape, w_shape, padding)\n\n    verify_conv2d(\n        mod_dyn, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n    for data_dtype, weight_dtype, out_dtype in [\n        (\"float32\", \"float32\", \"float32\"),  # 3xtf32\n        (\"int8\", \"int8\", \"int32\"),\n        (\"uint8\", \"int8\", \"int32\"),\n    ]:\n        expr = get_conv2d_nchw(\n            d_shape,\n            w_shape,\n            padding,\n            out_dtype=out_dtype,\n            data_dtype=data_dtype,\n            weight_dtype=weight_dtype,\n        )\n\n        verify_conv2d(\n            expr,\n            expr,\n            d_shape,\n            w_shape,\n            sm=80,\n            atol=1e-5,\n            rtol=1e-5,\n            run_benchmark=False,\n            data_dtype=data_dtype,\n            weight_dtype=weight_dtype,\n            ref_target=\"llvm\",\n        )\n\n    # align1 + int8 case\n    d_shape = (16, 3, 32, 32)\n    w_shape = (32, 3, 3, 3)\n    mod_nchw = get_conv2d_nchw(\n        d_shape, w_shape, padding, out_dtype=\"int32\", data_dtype=\"uint8\", weight_dtype=\"int8\"\n    )\n\n    verify_conv2d(\n        mod_nchw,\n        mod_nchw,\n        d_shape,\n        w_shape,\n        sm=80,\n        atol=1e-5,\n        rtol=1e-5,\n        ref_target=\"llvm\",\n        data_dtype=\"uint8\",\n        weight_dtype=\"int8\",\n    )\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d_fusion():\n    d_shape = (16, 16, 32, 32)\n    w_shape = (32, 16, 3, 3)\n    padding = (1, 1)\n\n    mod_nchw = get_conv2d_nchw_bias(d_shape, w_shape, padding)\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n    mod_nchw = get_conv2d_nchw_bias_relu(d_shape, w_shape, padding)\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n    mod_nchw = get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype=\"float16\")\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n    verify_conv2d(\n        mod_nchw,\n        mod_nchw,\n        d_shape,\n        w_shape,\n        sm=80,\n        atol=1e-3,\n        rtol=1e-3,\n        run_benchmark=False,\n        use_fast_math=True,\n    )\n\n    mod_nchw = get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype=\"float32\")\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n    mod_nchw = get_conv2d_nchw_bias_silu(d_shape, w_shape, padding, out_dtype=\"float32\")\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n    mod_nchw = get_conv2d_nchw_bias_hardswish(d_shape, w_shape, padding, out_dtype=\"float16\")\n    verify_conv2d(\n        mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False\n    )\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d_residual_block():\n    d_shape = (16, 16, 32, 32)\n    w_shape = (16, 16, 3, 3)\n    padding = (1, 1)\n\n    bias_add, residual_input = get_conv2d_nchw_bias_residual(d_shape, w_shape, padding)\n\n    for func, tol in [\n        (relay.nn.relu(bias_add + residual_input), 1e-5),\n        (relay.nn.relu(bias_add) + residual_input, 1e-5),\n        (relay.sigmoid(bias_add) * residual_input, 1e-5),\n        (relay.nn.relu(silu(bias_add) * residual_input), 1e-5),\n        # HardSwish requires higher tolerance since vectoring the residual block epilogue\n        # in cutlass.\n        # TODO(masahi): Invesitigate this issue\n        (relay.nn.relu(hardswish(bias_add) + residual_input), 1e-3),\n    ]:\n        verify_conv2d(func, func, d_shape, w_shape, sm=80, atol=tol, rtol=tol, run_benchmark=False)\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d_transpose():\n    OC = 8\n    IC = 16\n    d_shape = (16, IC, 32, 32)\n    w_shape = (OC, IC, 3, 3)\n    padding = (1, 1)\n    dtype = \"float32\"\n\n    for strides in [(1, 1), (2, 2)]:\n        o_shape = conv_output_shape(\n            0, padding, strides, (1, 1), d_shape, (OC, IC, 3, 3), \"float32\", \"float32\"\n        )\n        output_padding = (1, 1) if strides[0] > 1 else (0, 0)\n        mod_nchw = get_conv2d_transpose_nchw(\n            o_shape,\n            w_shape,\n            padding,\n            output_padding,\n            strides,\n            out_dtype=dtype,\n            data_dtype=dtype,\n            weight_dtype=dtype,\n        )\n\n        verify_conv2d(\n            mod_nchw,\n            mod_nchw,\n            o_shape,\n            w_shape,\n            sm=80,\n            atol=1e-3,\n            rtol=1e-3,\n            use_cudnn_ref=False,\n            run_benchmark=False,\n            data_dtype=dtype,\n            weight_dtype=dtype,\n        )\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d_backward_weight():\n    OC = 8\n    IC = 16\n    d_shape = (16, IC, 32, 32)\n    w_shape = (OC, IC, 3, 3)\n    dtype = \"float16\"\n\n    for strides in [(1, 1), (2, 2)]:\n        o_shape = (16, OC, 32 // strides[0], 32 // strides[1])\n        padding = (1, 1)\n\n        mod_nchw = get_conv2d_backward_weight(\n            d_shape,\n            w_shape,\n            o_shape,\n            padding,\n            strides,\n            out_dtype=\"float32\",\n            data_dtype=dtype,\n            weight_dtype=dtype,\n        )\n\n        for split_k_slices in [1, 8]:\n            verify_conv2d_backward_weight(\n                mod_nchw,\n                mod_nchw,\n                o_shape,\n                d_shape,\n                sm=80,\n                split_k_slices=[split_k_slices],\n                atol=1e-3,\n                rtol=1e-3,\n                use_cudnn_ref=False,\n                grad_dtype=dtype,\n                data_dtype=dtype,\n            )\n\n\n@tvm.testing.requires_cutlass\ndef test_conv2d_bwd():\n    IC = 16\n    OC = 8\n    dshape = (16, IC, 32, 32)\n    wshape = (OC, IC, 3, 3)\n    padding = (0, 0)\n    strides = (1, 1)\n\n    conv = get_conv2d_nchw(\n        dshape,\n        wshape,\n        padding,\n        strides=strides,\n        out_dtype=\"float32\",\n        data_dtype=\"float32\",\n        weight_dtype=\"float32\",\n    )\n    fwd_mod = InferType()(tvm.IRModule.from_expr(conv))\n\n    # Note: large difference in tvm and cutlass Wgrad results if use fp16.\n    # Cutlass wgrad uses fp32 accumulation even if the output is fp16.\n    use_fp16 = False\n    verify_dgrad = False  # False to verify wgrad\n    tol = 1e-5 if verify_dgrad else 1e-4  # Wgrad slightly less accurate\n\n    if use_fp16:\n        fwd_mod = ToMixedPrecision(\"float16\")(fwd_mod)\n\n    fwd_bwd_func = FirstOrderGradient()(fwd_mod)[\"main\"]\n\n    bwd_func = relay.Function(\n        fwd_bwd_func.params,\n        relay.TupleGetItem(relay.TupleGetItem(fwd_bwd_func.body, 1), 0 if verify_dgrad else 1),\n    )\n\n    verify_conv2d(\n        bwd_func,\n        bwd_func,\n        dshape,\n        wshape,\n        sm=80,\n        atol=1e-2 if use_fp16 else tol,\n        rtol=1e-2 if use_fp16 else tol,\n        use_cudnn_ref=False,\n        data_dtype=\"float32\",\n        weight_dtype=\"float32\",\n        use_vm=True,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_dlpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib.dlpack import to_pytorch_func\n\n\ndef verify_torch_dlpack():\n    a = np.random.randn(1337)\n    tvm_a = tvm.nd.array(a)\n    np.testing.assert_equal(tvm.nd.from_dlpack(tvm_a.to_dlpack()).numpy(), a)\n\n    try:\n        import torch\n        import torch.utils.dlpack\n\n        x = torch.rand(56, 56)\n        tvm_x = tvm.nd.from_dlpack(torch.utils.dlpack.to_dlpack(x))\n        np.testing.assert_equal(x.numpy(), tvm_x.numpy())\n        y = tvm.nd.from_dlpack(tvm_x)\n        np.testing.assert_equal(y.numpy(), tvm_x.numpy())\n        np.testing.assert_equal(\n            torch.utils.dlpack.from_dlpack(y.to_dlpack()).numpy(), tvm_x.numpy()\n        )\n\n        n = tvm.runtime.convert(137)\n        xx = torch.rand(137, 137)\n        yy = torch.rand(137, 137)\n        zz2 = torch.empty(137, 137)\n        zz = xx.mm(yy)\n        XX = te.placeholder((n, n), name=\"X\")\n        YY = te.placeholder((n, n), name=\"Y\")\n\n        k = te.reduce_axis((0, n), name=\"k\")\n        ZZ = te.compute((n, n), lambda i, j: te.sum(XX[i, k] * YY[k, j], axis=k))\n        s = te.create_schedule(ZZ.op)\n        # No need to speficy target_host if it's llvm\n        # Otherwise you will need to specify the target and target_host\n        f = tvm.build(s, [XX, YY, ZZ], name=\"f\")\n\n        f_pytorch = to_pytorch_func(f)\n        zz2 = torch.empty(137, 137)\n        f_pytorch(xx, yy, zz2)\n        tvm.testing.assert_allclose(zz.numpy(), zz2.numpy(), rtol=1e-4, atol=1e-4)\n\n    except ImportError:\n        pass\n\n\ndef test_torch_dlpack():\n    # Run dlpack interoperability test a few times to make sure it's stable.\n    for i in range(5):\n        verify_torch_dlpack()\n\n\nif __name__ == \"__main__\":\n    test_torch_dlpack()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_dnnl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport itertools\nimport numpy as np\nimport sys\nimport subprocess\nimport math\nimport collections\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\nfrom tvm.relay.op.contrib import dnnl\nimport tvm.testing\n\n\nhas_dnnl_codegen = pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.dnnl\", True), reason=\"DNNL codegen not available\"\n)\n\nrun_module = tvm.testing.parameter(\n    pytest.param(False, marks=[has_dnnl_codegen, *tvm.testing.requires_llvm.marks()]),\n    pytest.param(True, marks=[has_dnnl_codegen, *tvm.testing.requires_llvm.marks()]),\n    ids=[\"compile\", \"run\"],\n)\n\n_bf16_supported = None\n\n\ndef bf16_supported():\n    global _bf16_supported\n    if _bf16_supported is None:\n        _bf16_supported = False\n        if sys.platform.startswith(\"darwin\"):\n            cpu_info = subprocess.check_output(\"sysctl -a\", shell=True).strip().decode()\n            for line in cpu_info.split(\"\\n\"):\n                if line.startswith(\"hw.optional.avx512f\"):\n                    _bf16_supported = bool(int(line.split(\":\", 1)[1]))\n        elif sys.platform.startswith(\"linux\"):\n            _bf16_supported = \"avx512\" in open(\"/proc/cpuinfo\", \"r\").read()\n    return _bf16_supported\n\n\ndef partition_for_dnnl(mod, params=None, alter_layout=True, prune_subgraphs=True):\n    \"\"\"Partition the graph greedily offloading supported operators to DNNL.\n\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n    Returns\n    -------\n    mod : Module\n        Annotated and partitioned module.\n    \"\"\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", dnnl.legalize_group_conv):\n        with TempOpAttr(\"nn.conv2d_transpose\", \"FTVMLegalize\", dnnl.legalize_group_conv):\n            seq = tvm.transform.Sequential(\n                [\n                    transform.CanonicalizeOps(),\n                    transform.InferType(),\n                    transform.SimplifyInference(),\n                    transform.FoldConstant(),\n                    transform.FoldScaleAxis(),\n                    # fold consecutive add ops to simplify pattern `conv2d-bias_add-bn-relu`\n                    transform.SimplifyExpr(),\n                    transform.FoldConstant(),\n                    # alter group conv /conv_transpose layout to `GOIHW` / `GIOHW`\n                    transform.Legalize(),\n                    transform.FoldConstant(),\n                ]\n            )\n            with tvm.transform.PassContext(opt_level=3):\n                mod = seq(mod)\n    if alter_layout:\n        with TempOpAttr(\"nn.conv1d\", \"FTVMAlterOpLayout\", dnnl.alter_conv):\n            with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", dnnl.alter_conv):\n                with TempOpAttr(\"nn.conv3d\", \"FTVMAlterOpLayout\", dnnl.alter_conv):\n                    with TempOpAttr(\n                        \"nn.conv2d_transpose\", \"FTVMAlterOpLayout\", dnnl.alter_conv_transpose\n                    ):\n                        with TempOpAttr(\n                            \"nn.conv3d_transpose\", \"FTVMAlterOpLayout\", dnnl.alter_conv_transpose\n                        ):\n                            alter_layout_seq = tvm.transform.Sequential(\n                                [\n                                    transform.AlterOpLayout(),\n                                    transform.FoldConstant(),\n                                ]\n                            )\n                            with tvm.transform.PassContext(opt_level=3):\n                                mod = alter_layout_seq(mod)\n\n    mod = dnnl.rewrite_layer_norm(mod)\n    mod = dnnl.rewrite_dense_bias_gelu_reshape_last(mod)\n    mod = dnnl.legalize_qnn_for_dnnl(mod)\n\n    byoc_seq = tvm.transform.Sequential(\n        [\n            transform.MergeComposite(dnnl.pattern_table()),\n            transform.AnnotateTarget(\"dnnl\"),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        mod = byoc_seq(mod)\n        if prune_subgraphs:\n            mod = dnnl.prune_dnnl_subgraphs(mod)\n    return mod\n\n\ndef vmobj_to_list(o):\n    if isinstance(o, tvm.nd.NDArray):\n        o_np = o.numpy()\n        if o_np.dtype == np.uint16:\n            o_np = np.left_shift(o_np.astype(\"uint32\"), 16).view(\"<f4\")\n        return [o_np]\n    elif isinstance(o, tvm.runtime.container.ADT) or isinstance(o, list):\n        return [vmobj_to_list(f) for f in o]\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef assert_result_dict_holds(result_dict):\n    for k1, k2 in itertools.combinations(result_dict, 2):\n        res1 = vmobj_to_list(result_dict[k1])\n        res2 = vmobj_to_list(result_dict[k2])\n        for r1, r2 in zip(res1, res2):\n            # ignore the accuracy checking if only one bf16 result presents\n            if (\"bf16\" in k1) == (\"bf16\" in k2):\n                tvm.testing.assert_allclose(r1, r2, rtol=1e-3, atol=1e-3)\n\n\ndef check_dnnl_used(mod, subgraph_num=None):\n    num_dnnl_subgraphs = sum([1 if \"dnnl\" in gv.name_hint else 0 for gv in mod.get_global_vars()])\n    if subgraph_num:\n        assert num_dnnl_subgraphs == subgraph_num\n    else:\n        assert num_dnnl_subgraphs >= 1\n\n\ndef run_and_verify(mod, input, params, target, run_module, subgraph_num=None, test_bf16=True):\n    dev = tvm.cpu()\n    result_dict = dict()\n    for mode in [\"graph\", \"vm\"]:\n        configs = [\n            (False, False, False),\n            (True, False, False),\n            (True, True, False),\n        ]\n        if test_bf16 and bf16_supported():\n            configs += [(True, False, True), (True, True, True)]\n\n        for use_dnnl, alter_layout, use_bf16 in configs:\n            result_key = (\n                mode\n                + (\"_dnnl\" if use_dnnl else \"\")\n                + (\"_layout\" if alter_layout else \"\")\n                + (\"_bf16\" if use_bf16 else \"_fp32\")\n            )\n            processed_mod = mod\n            if use_bf16:\n                processed_mod = relay.transform.ToMixedPrecision(\"bfloat16\")(processed_mod)\n                if tvm.ir.structural_equal(processed_mod, mod):\n                    print(\"can not convert to bfloat16, skipping...\")\n                    continue\n            if use_dnnl:\n                processed_mod = partition_for_dnnl(processed_mod, params, alter_layout)\n                check_dnnl_used(processed_mod)\n            with tvm.transform.PassContext(opt_level=3):\n                func = relay.create_executor(\n                    mode, mod=processed_mod, device=dev, target=target\n                ).evaluate()\n            if run_module:\n                if isinstance(input, dict):\n                    result_dict[result_key] = func(**input, **params)\n                else:\n                    result_dict[result_key] = func(input, **params)\n\n    if run_module:\n        assert_result_dict_holds(result_dict)\n\n\ndef run_and_verify_func(\n    config, run_module, subgraph_num=None, target=\"llvm\", dtype=\"float32\", test_bf16=True\n):\n    \"\"\"Test a Relay func by compiling, running, and comparing TVM and DNNL outputs.\n    Parameters\n    ----------\n    config : Tuple[relay.Function, Dict[str, NDArray], List[str]]\n        A tuple containing 1) The function to test, 2) A dictionary of var names to input shapes and\n        3) A list of which vars should be considered params.\n    run_module: bool\n        If True, the built module will be run after being compiled.\n    \"\"\"\n    f, input_shapes, is_param = config\n    params = {x: np.random.uniform(-1, 1, input_shapes[x]).astype(dtype) for x in is_param}\n    input_dict = {\n        k: np.random.uniform(-1, 1, v).astype(dtype)\n        for k, v in input_shapes.items()\n        if k not in is_param\n    }\n    run_and_verify(\n        f,\n        input_dict,\n        params,\n        subgraph_num=subgraph_num,\n        target=target,\n        run_module=run_module,\n        test_bf16=test_bf16,\n    )\n\n\ndef add_activation(activation, out, dic, param_lst):\n    if activation == \"relu\":\n        return relay.nn.relu(out), dic, param_lst\n    elif activation == \"tanh\":\n        return relay.tanh(out), dic, param_lst\n    elif activation == \"sigmoid\":\n        return relay.sigmoid(out), dic, param_lst\n    elif activation == \"clip\":\n        return relay.clip(out, 0.0, 6.0), dic, param_lst\n    elif activation == \"swish\":\n        sig_out = relay.sigmoid(out)\n        out = relay.multiply(out, sig_out)\n        return out, dic, param_lst\n    elif activation == \"gelu\":\n        out = gelu_helper(out)\n        return out, dic, param_lst\n    elif activation == \"mish\":\n        exp = relay.exp(out)\n        add = relay.add(exp, relay.const(1.0))\n        log = relay.log(add)\n        tanh = relay.tanh(log)\n        out = relay.multiply(out, tanh)\n        return out, dic, param_lst\n    else:\n        return out, dic, param_lst\n\n\ndef get_conv1d(\n    x_shape=((1, 3, 224)),\n    k_shape=(16, 3, 3),\n    groups=1,\n    padding=(1, 1),\n    strides=(1),\n    dilation=(1),\n    channels=None,\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv1d(\n        x,\n        kernel,\n        kernel_size=k_shape[2:3],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        channels=k_shape[0],\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv1d_bias(x_shape=(1, 3, 224), k_shape=(10, 3, 3), activation=None, dtype=\"float32\"):\n    conv, dic, param_lst = get_conv1d(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv1d_bias_bn_relu(x_shape=(1, 3, 224), k_shape=(10, 3, 3), dtype=\"float32\"):\n    conv1d_bias, dic, param_lst = get_conv1d_bias(x_shape, k_shape, dtype=dtype)\n    beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n    moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n    conv1d_bias_bn, _, _ = relay.nn.batch_norm(\n        conv1d_bias,\n        gamma=gamma,\n        beta=beta,\n        moving_mean=moving_mean,\n        moving_var=moving_var,\n        axis=1,\n        center=True,\n        scale=True,\n        epsilon=1e-5,\n    )\n    return relay.nn.relu(conv1d_bias_bn), dic, param_lst\n\n\ndef get_conv2d(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(16, 32, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    dilation=(1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv2d(\n        x,\n        kernel,\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        channels=k_shape[0],\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_transpose(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(32, 16, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv2d_transpose(\n        x,\n        kernel,\n        channels=k_shape[1] * groups,\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_weights_const(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(16, 32, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    dilation=(1, 1),\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv2d(\n        x,\n        kernel,\n        channels=k_shape[0],\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n    )\n    dic = {\"x\": x_shape}\n    param_lst = []\n    return out, dic, param_lst\n\n\ndef get_conv2d_bias(\n    x_shape=(1, 32, 8, 8), k_shape=(16, 32, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv2d_weights_const(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_transpose_bias(\n    x_shape=(1, 32, 8, 8), k_shape=(32, 16, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv2d_transpose(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[1],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[1],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_bias_bn_relu(x_shape=(1, 32, 8, 8), k_shape=(16, 32, 3, 3), dtype=\"float32\"):\n    conv2d_bias, dic, param_lst = get_conv2d_bias(x_shape, k_shape, dtype=dtype)\n    beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n    moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n    conv2d_bias_bn, _, _ = relay.nn.batch_norm(\n        conv2d_bias,\n        gamma=gamma,\n        beta=beta,\n        moving_mean=moving_mean,\n        moving_var=moving_var,\n        axis=1,\n        center=True,\n        scale=True,\n        epsilon=1e-5,\n    )\n    return relay.nn.relu(conv2d_bias_bn), dic, param_lst\n\n\ndef get_layer_norm(x_shape=(1, 49, 64), dtype=\"float32\"):\n    dic = {\"input\": x_shape}\n    param_lst = []\n    input = relay.var(\"input\", shape=x_shape)\n    beta = relay.const(np.zeros(x_shape[2]).astype(dtype))\n    gamma = relay.const(np.ones(x_shape[2]).astype(dtype))\n    out = relay.nn.layer_norm(input, gamma=gamma, beta=beta)\n    return out, dic, param_lst\n\n\ndef get_conv3d(\n    x_shape=(1, 32, 8, 8, 8),\n    k_shape=(16, 32, 3, 3, 3),\n    groups=1,\n    padding=(0, 0, 0),\n    strides=(1, 1, 1),\n    dilation=(1, 1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv3d(\n        x,\n        kernel,\n        channels=k_shape[0],\n        kernel_size=k_shape[2:],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_transpose(\n    x_shape=(1, 32, 8, 8, 8),\n    k_shape=(32, 16, 3, 3, 3),\n    groups=1,\n    padding=(0, 0, 0),\n    strides=(1, 1, 1),\n    output_padding=(0, 0, 0),\n    activation=None,\n    dtype=\"float32\",\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv3d_transpose(\n        x,\n        kernel,\n        channels=k_shape[1],\n        kernel_size=k_shape[2:5],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        output_padding=output_padding,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_bias(\n    x_shape=(1, 32, 8, 8, 8), k_shape=(16, 32, 3, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv3d(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_transpose_bias(\n    x_shape=(1, 32, 8, 8, 8), k_shape=(32, 16, 3, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv3d_transpose(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[1],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[1],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef gelu_helper(data):\n    const1 = relay.const(math.sqrt(2.0))\n    const2 = relay.const(1.0)\n    const3 = relay.const(0.5)\n    divisor = relay.op.divide(data, const1)\n    val_erf = relay.op.erf(divisor)\n    added_erf = relay.op.add(val_erf, const2)\n    mul1 = relay.op.multiply(data, added_erf)\n    out = relay.op.multiply(mul1, const3)\n    return out\n\n\ndef get_dense(\n    x_shape=(1, 16), k_shape=(32, 16), activation=None, has_reshape=False, dtype=\"float32\"\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.dense(x, kernel, units=k_shape[0])\n    # out = relay.nn.dense(x, kernel, units=None)\n    if has_reshape:\n        out = relay.reshape(out, newshape=(1, x_shape[0], k_shape[0]))\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n\n    if activation == \"gelu\":\n        out = gelu_helper(out)\n    return out, dic, param_lst\n\n\ndef get_bmm(\n    x_shape=(1, 16, 8), k_shape=(1, 4, 8), dtype=\"float32\", transpose_a=False, transpose_b=True\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.batch_matmul(\n        x, kernel, out_dtype=dtype, transpose_a=transpose_a, transpose_b=transpose_b\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return out, dic, param_lst\n\n\ndef test_bmm(run_module, dtype=\"float32\"):\n    x_shape = (1, 2, 4)\n    k_shape = (1, 3, 4)\n\n    dense, dic, param_lst = get_bmm(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    k_shape_t = (1, 4, 3)\n    dense, dic, param_lst = get_bmm(x_shape, k_shape_t, dtype=dtype, transpose_b=False)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef get_dense_bias(\n    x_shape=(1, 16),\n    k_shape=(32, 16),\n    activation=None,\n    has_reshape=False,\n    use_add=False,\n    dtype=\"float32\",\n):\n    dense, dic, param_lst = get_dense(\n        x_shape=x_shape, k_shape=k_shape, has_reshape=has_reshape, dtype=dtype\n    )\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    if use_add:\n        out = relay.add(dense, bias)\n    else:\n        out = relay.nn.bias_add(dense, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n\n    if activation == \"gelu\":\n        out = gelu_helper(out)\n    return out, dic, param_lst\n\n\ndef test_dnnl_not_compatible(run_module, target=\"llvm\", dtype=\"float32\"):\n    xshape = (1, 32, 14, 14)\n    x_data = np.random.uniform(-1, 1, xshape).astype(dtype)\n\n    x = relay.var(\"x\", shape=(xshape), dtype=dtype)\n    y = relay.add(x, x)\n    z = relay.cast(relay.cast(y, \"int32\"), \"float32\")\n    out = relay.nn.relu(z)\n    f = relay.Function([x], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = partition_for_dnnl(mod)\n    for mode in [\"graph\", \"vm\"]:\n        with tvm.transform.PassContext(opt_level=3):\n            func = relay.create_executor(mode, mod=mod, device=tvm.cpu(0), target=target).evaluate()\n            if run_module:\n                results = func(x_data)\n\n\ndef test_multiple_outputs(run_module, dtype=\"float32\"):\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 3), dtype=dtype)\n        y = relay.var(\"y\", shape=(1, 3), dtype=dtype)\n        z = relay.add(x, y)\n        w = relay.add(z, y)\n        out = relay.Tuple((z, w))\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": (1, 3), \"y\": (1, 3)}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, dtype=dtype)\n\n\ndef test_elementwise(run_module, dtype=\"float32\"):\n    def get_graph(op, x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = op(x)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    for op in [\n        relay.abs,\n        relay.exp,\n        relay.log,\n        relay.sqrt,\n        relay.nn.relu,\n        relay.tanh,\n        relay.sigmoid,\n    ]:\n        run_and_verify_func(get_graph(op), run_module=run_module)\n\n\ndef test_clip(run_module, dtype=\"float32\"):\n    def get_graph(x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.clip(x, a_min=-0.2, a_max=0.4)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_leaky_relu(run_module, dtype=\"float32\"):\n    def get_graph(x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.nn.leaky_relu(x, alpha=0.1)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_softmax(run_module, dtype=\"float32\"):\n    def get_graph(x_shape, axis):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.nn.softmax(x, axis=axis)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph((1, 1000), axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 1000), axis=-1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 3, 4), axis=-2), run_module=run_module)\n    run_and_verify_func(get_graph((1, 3, 4), axis=1), run_module=run_module)\n\n\ndef test_conv1d(run_module, dtype=\"float32\"):\n    conv1d, dic, param_lst = get_conv1d(channels=16, dtype=dtype)\n    conv1d = tvm.IRModule.from_expr(conv1d)\n    config = conv1d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    x_shape = (1, 32, 224)\n    k_shape = (16, 32, 3)\n    conv1d_bias, dic, param_lst = get_conv1d(x_shape, k_shape, dtype=dtype)\n    conv1d_bias = tvm.IRModule.from_expr(conv1d_bias)\n    config = conv1d_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv1d_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 3, 224)\n    k_shape = (16, 3, 3)\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\"]\n    for a in activation_lst:\n        conv1d, dic, param_lst = get_conv1d(x_shape, k_shape, activation=a, dtype=dtype)\n        conv1d = tvm.IRModule.from_expr(conv1d)\n        config = conv1d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv1d_bias, dic, param_lst = get_conv1d_bias(x_shape, k_shape, activation=a, dtype=dtype)\n        conv1d_bias = tvm.IRModule.from_expr(conv1d_bias)\n        config = conv1d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    for k_shape, groups in [((16, 32, 3, 3), 1), ((32, 1, 3, 3), 32), ((32, 2, 3, 3), 16)]:\n        for padding in [(0, 0), (1, 1)]:\n            for strides in [(1, 1), (2, 2)]:\n                for dilation in [(1, 1), (2, 2)]:\n                    conv2d, dic, param_lst = get_conv2d(\n                        x_shape=x_shape,\n                        k_shape=k_shape,\n                        groups=groups,\n                        padding=padding,\n                        strides=strides,\n                        dilation=dilation,\n                        dtype=dtype,\n                    )\n                    conv2d = tvm.IRModule.from_expr(conv2d)\n                    config = conv2d, dic, param_lst\n                    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_weights_const(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n    conv2d, dic, param_lst = get_conv2d_weights_const(x_shape, k_shape, dtype=dtype)\n    conv2d = tvm.IRModule.from_expr(conv2d)\n    config = conv2d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    x_shape = (1, 3, 8, 8)\n    k_shape = (16, 3, 3, 3)\n    conv2d, dic, param_lst = get_conv2d_weights_const(x_shape, k_shape, dtype=dtype)\n    conv2d = tvm.IRModule.from_expr(conv2d)\n    config = conv2d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv2d, dic, param_lst = get_conv2d(x_shape, k_shape, activation=a, dtype=dtype)\n        conv2d = tvm.IRModule.from_expr(conv2d)\n        config = conv2d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv2d_bias, dic, param_lst = get_conv2d_bias(x_shape, k_shape, activation=a, dtype=dtype)\n        conv2d_bias = tvm.IRModule.from_expr(conv2d_bias)\n        config = conv2d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv2d_bias_bn_relu, dic, param_lst = get_conv2d_bias_bn_relu(x_shape, k_shape, dtype=dtype)\n    conv2d_bias_bn_relu = tvm.IRModule.from_expr(conv2d_bias_bn_relu)\n    config = conv2d_bias_bn_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv2d_bias_bn_relu, dic, param_lst = get_conv2d_bias_bn_relu(x_shape, k_shape, dtype=dtype)\n    conv2d_bias_bn_relu = tvm.IRModule.from_expr(conv2d_bias_bn_relu)\n    config = conv2d_bias_bn_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_bias_sum_relu(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n\n    def get_conv2d_bn_sum_relu(x_shape, k_shape, dtype=\"float32\"):\n        out, dic, param_lst = get_conv2d_bias(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n        beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n        gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n        moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n        moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n        out, _, _ = relay.nn.batch_norm(\n            out,\n            gamma=gamma,\n            beta=beta,\n            moving_mean=moving_mean,\n            moving_var=moving_var,\n            axis=1,\n            center=True,\n            scale=True,\n            epsilon=1e-5,\n        )\n        sum_in = relay.var(\"sum_in\", shape=x_shape, dtype=dtype)\n        kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n        conv_sum = relay.nn.conv2d(\n            sum_in,\n            kernel,\n            channels=k_shape[0],\n            kernel_size=k_shape[2:4],\n            groups=1,\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n        )\n        # sum over two conv2d outputs to meet inplace condition\n        out = relay.add(out, conv_sum)\n        dic[\"sum_in\"] = x_shape\n        return relay.nn.relu(out), dic, param_lst\n\n    conv2d_bn_sum_relu, dic, param_lst = get_conv2d_bn_sum_relu(x_shape, k_shape, dtype=dtype)\n    conv2d_bn_sum_relu = tvm.IRModule.from_expr(conv2d_bn_sum_relu)\n    config = conv2d_bn_sum_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_transpose(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    for k_shape, groups in [((32, 16, 3, 3), 1), ((32, 1, 3, 3), 32), ((32, 4, 3, 3), 16)]:\n        for padding in [(0, 0), (1, 1)]:\n            for strides in [(1, 1), (2, 2)]:\n                conv2d_transpose, dic, param_lst = get_conv2d_transpose(\n                    x_shape=x_shape,\n                    k_shape=k_shape,\n                    groups=groups,\n                    padding=padding,\n                    strides=strides,\n                    dtype=dtype,\n                )\n                conv2d_transpose = tvm.IRModule.from_expr(conv2d_transpose)\n                config = conv2d_transpose, dic, param_lst\n                run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_transpose_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv2d, dic, param_lst = get_conv2d_transpose(activation=a, dtype=dtype)\n        conv2d = tvm.IRModule.from_expr(conv2d)\n        config = conv2d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv2d_bias, dic, param_lst = get_conv2d_transpose_bias(activation=a, dtype=dtype)\n        conv2d_bias = tvm.IRModule.from_expr(conv2d_bias)\n        config = conv2d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d(run_module, dtype=\"float32\"):\n    conv3d, dic, param_lst = get_conv3d(dtype=dtype)\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d, dic, param_lst = get_conv3d(padding=(0, 0, 0, 1, 1, 1), dtype=dtype)\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d, dic, param_lst = get_conv3d(\n        x_shape=(1, 3, 8, 8, 8), k_shape=(16, 3, 3, 3, 3), dtype=dtype\n    )\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv3d, dic, param_lst = get_conv3d(activation=a, dtype=dtype)\n        conv3d = tvm.IRModule.from_expr(conv3d)\n        config = conv3d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv3d_bias, dic, param_lst = get_conv3d_bias(activation=a, dtype=dtype)\n        conv3d_bias = tvm.IRModule.from_expr(conv3d_bias)\n        config = conv3d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_transpose(run_module, dtype=\"float32\"):\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(dtype=dtype)\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(strides=(2, 2, 2), dtype=dtype)\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(\n        strides=(2, 2, 2), output_padding=(1, 1, 1), dtype=dtype\n    )\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_transpose_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv3d, dic, param_lst = get_conv3d_transpose(activation=a, dtype=dtype)\n        conv3d = tvm.IRModule.from_expr(conv3d)\n        config = conv3d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv3d_bias, dic, param_lst = get_conv3d_transpose_bias(activation=a, dtype=dtype)\n        conv3d_bias = tvm.IRModule.from_expr(conv3d_bias)\n        config = conv3d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_dense(run_module, dtype=\"float32\"):\n    x_shape = (1, 16)\n    k_shape = (32, 16)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape=(1, 16), dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, activation=\"gelu\", dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_dense_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 16)\n    k_shape = (32, 16)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense_bias, dic, param_lst = get_dense_bias(x_shape, k_shape, dtype=dtype)\n    dense_bias = tvm.IRModule.from_expr(dense_bias)\n    config = dense_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense_bias, dic, param_lst = get_dense_bias(x_shape, k_shape, activation=\"gelu\", dtype=dtype)\n    dense_bias = tvm.IRModule.from_expr(dense_bias)\n    config = dense_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_pool2d(run_module, dtype=\"float32\"):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 32, 32),\n        pool_size=(2, 2),\n        strides=(2, 2),\n        padding=(0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n            )\n        out = tvm.IRModule.from_expr(out)\n        return out, {\"x\": x_shape}, []\n\n    for pool_size in [(2, 2), (3, 3)]:\n        for strides in [(1, 1), (2, 2)]:\n            for padding in [(0, 0), (1, 1), (0, 0, 1, 1)]:\n                for ceil_mode in [False]:\n                    # Skip \"the padding size is larger than or equal to the filter size for exclusive-counting pooling\"\n                    if pool_size == (2, 2) and padding == (0, 0, 1, 1):\n                        continue\n                    for count_include_pad in [False, True]:\n                        # Skip \"inclusive-counted blended or average pooling is not supported in combination with asymmetric padding\"\n                        if count_include_pad and (padding == (0, 0, 1, 1) or strides == (2, 2)):\n                            continue\n                        run_and_verify_func(\n                            get_graph(\n                                relay.nn.avg_pool2d,\n                                pool_size=pool_size,\n                                strides=strides,\n                                padding=padding,\n                                ceil_mode=ceil_mode,\n                                count_include_pad=count_include_pad,\n                            ),\n                            run_module=run_module,\n                        )\n                    run_and_verify_func(\n                        get_graph(\n                            relay.nn.max_pool2d,\n                            pool_size=pool_size,\n                            strides=strides,\n                            padding=padding,\n                            ceil_mode=ceil_mode,\n                        ),\n                        run_module=run_module,\n                    )\n\n\ndef test_global_avg_pooling2d(run_module, dtype=\"float32\"):\n    x_shape = (1, 3, 32, 32)\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    out = relay.nn.global_avg_pool2d(x)\n    out = tvm.IRModule.from_expr(out)\n    config = out, {\"x\": x_shape}, []\n    run_and_verify_func(config, run_module=run_module)\n\n\ndef test_pool3d(run_module, dtype=\"float32\"):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 8, 32, 32),\n        pool_size=(2, 2, 2),\n        strides=(2, 2, 2),\n        padding=(0, 0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n        dtype=\"float32\",\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n            )\n        out = tvm.IRModule.from_expr(out)\n        return out, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(relay.nn.avg_pool3d), run_module=run_module)\n    run_and_verify_func(get_graph(relay.nn.max_pool3d), run_module=run_module)\n    run_and_verify_func(\n        get_graph(relay.nn.max_pool3d, padding=(0, 0, 0, 1, 1, 1)), run_module=run_module\n    )\n    run_and_verify_func(get_graph(relay.nn.max_pool3d, strides=(1, 1, 1)), run_module=run_module)\n\n\ndef test_prune_dnnl_subgraph(run_module):\n    \"\"\"In this test, OP \"add\" should be offloaded from dnnl codegen.\"\"\"\n\n    def get_graph():\n        x1 = relay.var(\"x1\", shape=(1, 32, 56, 56))\n        x2 = relay.var(\"x2\", shape=(1, 32, 56, 56))\n        bias = relay.var(\"bias\", shape=(32,))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        y = relay.nn.conv2d(\n            x1,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.nn.bias_add(y, bias)\n        y = relay.nn.relu(y)\n        y = relay.nn.global_max_pool2d(y)\n        y = relay.add(y, x2)\n        dic = {\n            \"x1\": (1, 32, 56, 56),\n            \"x2\": (1, 32, 56, 56),\n            \"weight\": (32, 32, 3, 3),\n            \"bias\": (32,),\n        }\n        param_lst = [\"weight\", \"bias\"]\n        out = tvm.IRModule.from_expr(y)\n        return out, dic, param_lst\n\n    run_and_verify_func(get_graph(), subgraph_num=1, run_module=run_module, test_bf16=False)\n\n\ndef test_layer_norm(run_module, dtype=\"float32\"):\n    x_shape = (1, 49, 64)\n\n    ln, dic, param_lst = get_layer_norm(x_shape, dtype=dtype)\n    ln = tvm.IRModule.from_expr(ln)\n    config = ln, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_rewrite_dense_bias_gelu_reshape_last(run_module, dtype=\"float32\"):\n    def get_graph(act=None):\n        x_shape = (1, 16)\n        k_shape = (32, 16)\n\n        dense_bias, dic, param_lst = get_dense_bias(\n            x_shape, k_shape, activation=act, has_reshape=True, use_add=True, dtype=dtype\n        )\n        dense_bias = tvm.IRModule.from_expr(dense_bias)\n        processed_dense_bias = partition_for_dnnl(\n            dense_bias, params=None, alter_layout=False, prune_subgraphs=False\n        )\n        check_dnnl_used(processed_dense_bias, 1)\n\n        return dense_bias, dic, param_lst\n\n    run_and_verify_func(\n        get_graph(\"gelu\"), subgraph_num=1, run_module=run_module, dtype=dtype, test_bf16=False\n    )\n    run_and_verify_func(\n        get_graph(), subgraph_num=1, run_module=run_module, dtype=dtype, test_bf16=False\n    )\n\n\ndef test_resnetv1_rewrite(run_module, dtype=\"float32\"):\n    def get_graph():\n        data_shape = (1, 256, 56, 56)\n        w_shapes = [\n            (64, 256, 1, 1),\n            (64, 64, 3, 3),\n            (256, 64, 1, 1),\n            (128, 256, 1, 1),\n            (128, 128, 3, 3),\n            (512, 128, 1, 1),\n            (512, 256, 1, 1),\n        ]\n        x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n        wights = [relay.const(np.random.randint(0, 1, w).astype(dtype)) for w in w_shapes]\n        biases = [relay.const(np.random.randint(0, 1, w[0]).astype(dtype)) for w in w_shapes]\n\n        conv1 = relay.nn.conv2d(\n            x,\n            wights[0],\n            channels=w_shapes[0][0],\n            kernel_size=w_shapes[0][2:4],\n            padding=(w_shapes[0][2] // 2, w_shapes[0][3] // 2),\n        )\n        conv1 = relay.nn.bias_add(conv1, biases[0])\n        conv1 = relay.nn.relu(conv1)\n\n        conv2 = relay.nn.conv2d(\n            conv1,\n            wights[1],\n            channels=w_shapes[1][0],\n            kernel_size=w_shapes[1][2:4],\n            padding=(w_shapes[1][2] // 2, w_shapes[1][3] // 2),\n        )\n        conv2 = relay.nn.bias_add(conv2, biases[1])\n        conv2 = relay.nn.relu(conv2)\n\n        conv3 = relay.nn.conv2d(\n            conv2,\n            wights[2],\n            channels=w_shapes[2][0],\n            kernel_size=w_shapes[2][2:4],\n            padding=(w_shapes[2][2] // 2, w_shapes[2][3] // 2),\n        )\n        conv3 = relay.nn.bias_add(conv3, biases[2])\n        conv3 = relay.add(conv3, x)\n        conv3 = relay.nn.relu(conv3)\n\n        left_conv4 = relay.nn.conv2d(\n            conv3,\n            wights[3],\n            channels=w_shapes[3][0],\n            strides=(2, 2),\n            kernel_size=w_shapes[3][2:4],\n            padding=(w_shapes[3][2] // 2, w_shapes[3][3] // 2),\n        )\n        left_conv4 = relay.nn.bias_add(left_conv4, biases[3])\n        left_conv4 = relay.nn.relu(left_conv4)\n\n        left_conv5 = relay.nn.conv2d(\n            left_conv4,\n            wights[4],\n            channels=w_shapes[4][0],\n            kernel_size=w_shapes[4][2:4],\n            padding=(w_shapes[4][2] // 2, w_shapes[4][3] // 2),\n        )\n        left_conv5 = relay.nn.bias_add(left_conv5, biases[4])\n        left_conv5 = relay.nn.relu(left_conv5)\n\n        left_conv6 = relay.nn.conv2d(\n            left_conv5,\n            wights[5],\n            channels=w_shapes[5][0],\n            kernel_size=w_shapes[5][2:4],\n            padding=(w_shapes[5][2] // 2, w_shapes[5][3] // 2),\n        )\n        left_conv6 = relay.nn.bias_add(left_conv6, biases[5])\n\n        right_conv7 = relay.nn.conv2d(\n            conv3,\n            wights[6],\n            channels=w_shapes[6][0],\n            strides=(2, 2),\n            kernel_size=w_shapes[6][2:4],\n            padding=(w_shapes[6][2] // 2, w_shapes[6][3] // 2),\n        )\n        right_conv7 = relay.nn.bias_add(right_conv7, biases[6])\n\n        out = relay.add(left_conv6, right_conv7)\n        out = relay.nn.relu(out)\n\n        dic = {\"x\": data_shape}\n        param_lst = []\n        return out, dic, param_lst\n\n    net, dic, param_lst = get_graph()\n    net = tvm.IRModule.from_expr(net)\n    config = net, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_fuse_pad_avg_pool(run_module, dtype=\"float32\"):\n    def get_graph():\n        data_shape = (1, 768, 17, 17)\n        x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n        out = relay.nn.pad(x, pad_width=[[0, 0], [0, 0], [1, 1], [1, 1]])\n        out = relay.nn.avg_pool2d(out, pool_size=[3, 3])\n        dic = {\"x\": data_shape}\n        param_lst = []\n        return out, dic, param_lst\n\n    net, dic, param_lst = get_graph()\n    net = tvm.IRModule.from_expr(net)\n    config = net, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef permute_shape(shape, l_from=\"\", l_to=\"\"):\n    res_shape = []\n    for label in l_to:\n        pos = l_from.find(label)\n        res_shape.append(shape[pos])\n\n    return res_shape\n\n\ndef expand_dim(shape, rank=0):\n    assert len(shape) == 1\n    return shape + [1] * (rank - 1)\n\n\ndef filler_uni(low=0, high=1):\n    def filler_func(shape):\n        return np.random.uniform(low, high, shape)\n\n    return filler_func\n\n\nclass QnnBuilder:\n    def __init__(self, qnn_profile=None):\n        self._args = {}\n        self._args_op = []\n        self._qp = qnn_profile\n\n    def arg(self, shape=[], dtype=\"float32\", filler=filler_uni(), is_const=True):\n        if isinstance(filler, (int, float)):\n            value = np.full(shape, filler).astype(dtype)\n        else:\n            value = filler(shape).astype(dtype)\n\n        if is_const:\n            res = relay.const(value, dtype=dtype)\n        else:\n            name = f\"in_{len(self._args)}\"\n            res = relay.var(name, shape=shape, dtype=dtype)\n            self._args[name] = value\n            self._args_op.append(res)\n\n        return res\n\n    def make_zp(self, mean_val, num_ch=1, dispersion=0.2):\n        if num_ch == 1:\n            return self.arg(shape=[], dtype=\"int32\", filler=mean_val)\n        else:\n            low = int(mean_val * (1 - dispersion))\n            high = int(mean_val * (1 + dispersion))\n            return self.arg(shape=[num_ch], dtype=\"int32\", filler=filler_uni(low, high))\n\n    def make_scl(self, mean_val, num_ch=1, dispersion=0.2):\n        if num_ch == 1:\n            return self.arg(shape=[], dtype=\"float32\", filler=mean_val)\n        else:\n            low = mean_val * (1 - dispersion)\n            high = mean_val * (1 + dispersion)\n            return self.arg(shape=[num_ch], dtype=\"float32\", filler=filler_uni(low, high))\n\n    def make_zp_and_scl(self, name, num_ch=1, dispersion=0.2):\n        is_per_channel = getattr(self._qp, f\"{name}_pc\")\n        zp_val = getattr(self._qp, f\"{name}_zp\")\n        scl_val = getattr(self._qp, f\"{name}_scl\")\n\n        zp = self.make_zp(zp_val, num_ch if is_per_channel else 1, dispersion)\n        scl = self.make_scl(scl_val, num_ch if is_per_channel else 1, dispersion)\n        return zp, scl\n\n    def finalize(self, op):\n        func = relay.Function(self._args_op, op)\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        return mod, self._args\n\n\ndef check_fully_annotated(mod, desired_compiler):\n    matched_ops = []\n    other_ops = []\n\n    def _visit(node):\n        if isinstance(node, tvm.relay.Call):\n            op = node.op\n            if isinstance(op, relay.GlobalVar):\n                func = mod[op]\n                if \"Compiler\" in func.attrs and func.attrs[\"Compiler\"] == desired_compiler:\n                    matched_ops.append(op)\n                    return\n            else:\n                other_ops.append(op)\n\n    tvm.relay.analysis.post_order_visit(mod[\"main\"].body, _visit)\n\n    assert len(other_ops) == 0 and len(matched_ops) != 0, \"Model is not fully DNNL compiled\"\n\n\ndef check_result(\n    mod,\n    ref_mod,\n    map_inputs,\n    tol=1e-5,\n    target=\"llvm\",\n    device=tvm.cpu(),\n    params=None,\n    ref_result=None,\n    atol=None,\n    desired_compiler=\"dnnl\",\n):\n    if atol is None:\n        atol = tol\n\n    if desired_compiler is not None:\n        check_fully_annotated(mod, desired_compiler)\n\n    if ref_result is None:\n        # Run the reference result\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            ref_lib = relay.build(ref_mod, target=target, params=params)\n        ref_rt_mod = tvm.contrib.graph_executor.GraphModule(ref_lib[\"default\"](device))\n\n        for name, data in map_inputs.items():\n            ref_rt_mod.set_input(name, data)\n        ref_rt_mod.run()\n        out = ref_rt_mod.get_output(0)\n        ref_result = out.numpy()\n\n    def check_vm_result():\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            exe = relay.vm.compile(mod, target=target, params=params)\n        code, lib = exe.save()\n        exe = tvm.runtime.vm.Executable.load_exec(code, lib)\n        vm = tvm.runtime.vm.VirtualMachine(exe, device)\n        output = vm.run(**map_inputs)\n        tvm.testing.assert_allclose(output.numpy(), ref_result, rtol=tol, atol=atol)\n\n    def check_graph_executor_result():\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target, params=params)\n        rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](device))\n\n        rt_mod.run(**map_inputs)\n        output = rt_mod.get_output(0)\n        tvm.testing.assert_allclose(output.numpy(), ref_result, rtol=tol, atol=atol)\n\n    check_vm_result()\n    check_graph_executor_result()\n\n\nConvProfile = collections.namedtuple(\n    \"ConvProfile\",\n    [\n        \"SHAPE\",\n        \"KER\",\n        \"STR\",\n        \"PAD\",\n        \"DEL\",\n        \"OC\",\n        \"GR\",\n        \"D_LAYOUT\",\n        \"K_LAYOUT\",\n    ],\n)\nbase_conv = ConvProfile(\n    SHAPE=[1, 8, 5, 5],\n    KER=[3, 3],\n    STR=[1, 1],\n    PAD=[1, 1],\n    DEL=[1, 1],\n    OC=16,\n    GR=1,\n    D_LAYOUT=\"NCHW\",\n    K_LAYOUT=\"OIHW\",\n)\nbase_conv_nhwc = base_conv._replace(D_LAYOUT=\"NHWC\", K_LAYOUT=\"HWIO\")\nbase_conv_dilated = base_conv._replace(PAD=[2, 2], DEL=[2, 2])\nbase_conv_no_pad = base_conv._replace(PAD=[0, 0])\nbase_conv_no_pad_nhwc = base_conv_no_pad._replace(D_LAYOUT=\"NHWC\", K_LAYOUT=\"HWIO\")\nbase_conv_group_no_pad = base_conv_no_pad._replace(GR=2)\nbase_conv_dw_no_pad = base_conv_no_pad._replace(SHAPE=[1, 16, 5, 5], GR=16)\n\n\nDenseProfile = collections.namedtuple(\"DenseProfile\", [\"N\", \"IC\", \"OC\"])\nbase_dense_profile = DenseProfile(N=2, IC=10, OC=16)\n\nArgConstConfig = collections.namedtuple(\"ArgConstConfig\", [\"Data\", \"Weights\", \"Bias\", \"Sum\"])\nacp_regular = ArgConstConfig(Data=False, Weights=True, Bias=True, Sum=None)\nacp_no_bias = ArgConstConfig(Data=False, Weights=True, Bias=None, Sum=None)\nacp_with_sum = ArgConstConfig(Data=False, Weights=True, Bias=True, Sum=False)\nacp_no_bias_with_sum = ArgConstConfig(Data=False, Weights=True, Bias=None, Sum=False)\n\nQuantizationConfig = collections.namedtuple(\n    \"QuantizationConfig\",\n    [\n        \"d_zp\",\n        \"d_scl\",\n        \"d_pc\",\n        \"k_zp\",\n        \"k_scl\",\n        \"k_pc\",\n        \"rq_zp\",\n        \"rq_scl\",\n        \"rq_pc\",\n        \"sum_zp\",\n        \"sum_scl\",\n        \"sum_pc\",\n        \"o_zp\",\n        \"o_scl\",\n        \"o_pc\",\n    ],\n)\n\nqp_regular = QuantizationConfig(\n    d_zp=0,\n    d_scl=0.2,\n    d_pc=False,\n    k_zp=0,\n    k_scl=0.1,\n    k_pc=False,\n    rq_zp=30,\n    rq_scl=0.2,\n    rq_pc=False,\n    sum_zp=15,\n    sum_scl=0.3,\n    sum_pc=False,\n    o_zp=5,\n    o_scl=0.2,\n    o_pc=False,\n)\nqp_asymmetric_data = qp_regular._replace(\n    d_zp=3, rq_zp=10, rq_scl=0.1, sum_zp=15, sum_scl=0.3, o_zp=4\n)\n\nqnn_conv_profiles = tvm.testing.parameter(\n    by_dict={\n        #  Pattern qnn.conv2d + qnn.requantize\n        \"Base\": (base_conv, acp_regular, qp_regular),\n        \"NHWC\": (base_conv_nhwc, acp_regular, qp_regular),\n        #  Asymmetric input. NOTE: No pad! Input ZP is not compatible with padding\n        \"Group\": (base_conv_group_no_pad, acp_regular, qp_asymmetric_data),\n        \"DW\": (base_conv_dw_no_pad, acp_regular, qp_asymmetric_data),\n        \"NoBias\": (base_conv, acp_no_bias, qp_regular),\n        \"AsymmetricInput\": (base_conv_no_pad, acp_regular, qp_asymmetric_data),\n        \"AsymmetricInput_NHWC\": (base_conv_no_pad_nhwc, acp_regular, qp_asymmetric_data),\n        #  Pattern Conv2d + Requantize + Sum\n        \"WithSum\": (base_conv_no_pad, acp_with_sum, qp_asymmetric_data),\n        \"WithSum_NHWC\": (base_conv_no_pad_nhwc, acp_with_sum, qp_asymmetric_data),\n        \"WithSum_NoBias\": (base_conv_no_pad, acp_no_bias_with_sum, qp_asymmetric_data),\n    }\n)\n\n\n@has_dnnl_codegen\ndef test_qnn_conv2d(qnn_conv_profiles):\n    def generate_model(p, c, q):\n        np.random.seed(0)\n\n        N, IC, IH, IW = p.SHAPE\n        d_shape = p.SHAPE\n        w_shape = [p.OC, IC, *p.KER]\n        b_shape = [p.OC]\n        s_shape = [\n            p.SHAPE[0],\n            p.OC,\n            (IH + 2 * p.PAD[0] - (p.KER[0] - 1) * p.DEL[0] - 1) // p.STR[0] + 1,\n            (IW + 2 * p.PAD[1] - (p.KER[1] - 1) * p.DEL[1] - 1) // p.STR[1] + 1,\n        ]\n\n        if p.GR != 1:\n            w_shape[1] //= p.GR\n\n        d_shape = permute_shape(d_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        s_shape = permute_shape(s_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        w_shape = permute_shape(w_shape, l_from=\"OIHW\", l_to=p.K_LAYOUT)\n\n        c_dim = p.D_LAYOUT.find(\"C\")\n        b_shape = expand_dim(b_shape, rank=len(p.D_LAYOUT) - c_dim)\n\n        bld = QnnBuilder(qnn_profile=q)\n\n        # Start build a test graph\n        data = bld.arg(shape=d_shape, dtype=\"uint8\", is_const=c.Data, filler=filler_uni(0, 20))\n        d_zp, d_scl = bld.make_zp_and_scl(\"d\", IC)\n\n        # Convolution\n        wgh = bld.arg(shape=w_shape, dtype=\"int8\", is_const=c.Weights, filler=filler_uni(-20, 20))\n        w_zp, w_scl = bld.make_zp_and_scl(\"k\")\n\n        op = tvm.relay.qnn.op.conv2d(\n            data,\n            wgh,\n            d_zp,\n            w_zp,\n            d_scl,\n            w_scl,\n            kernel_size=p.KER,\n            padding=p.PAD,\n            strides=p.STR,\n            dilation=p.DEL,\n            groups=p.GR,\n            channels=p.OC,\n            out_dtype=\"int32\",\n            data_layout=p.D_LAYOUT,\n            kernel_layout=p.K_LAYOUT,\n        )\n        # Optional bias\n        if c.Bias is not None:\n            bias = bld.arg(\n                shape=b_shape, dtype=\"int32\", is_const=c.Bias, filler=filler_uni(-50, 50)\n            )\n            op = tvm.relay.add(op, bias)\n\n        # Re-quantization\n        rq_in_zp = bld.make_zp(0)\n        rq_in_scl = bld.make_scl(q.d_scl * q.k_scl)  # in real cases that should be a vector\n        rq_out_zp, rq_out_scl = bld.make_zp_and_scl(\"rq\")\n\n        op = tvm.relay.qnn.op.requantize(\n            op, rq_in_scl, rq_in_zp, rq_out_scl, rq_out_zp, out_dtype=\"int32\"\n        )\n        op = tvm.relay.clip(\n            op, a_min=0.0, a_max=255.0\n        )  # pytorch frontend specific, I guess it's redundant\n        op = tvm.relay.cast(op, dtype=\"uint8\")\n\n        # Optional sum (ResNet like)\n        if c.Sum is not None:\n            sum_in = bld.arg(dtype=\"uint8\", shape=s_shape, filler=filler_uni(0, 10), is_const=c.Sum)\n\n            lhs_zp, lhs_scl = bld.make_zp_and_scl(\"rq\")\n            rhs_zp, rhs_scl = bld.make_zp_and_scl(\"sum\")\n            out_zp, out_scl = bld.make_zp_and_scl(\"o\")\n\n            op = tvm.relay.qnn.op.add(op, sum_in, lhs_scl, lhs_zp, rhs_scl, rhs_zp, out_scl, out_zp)\n            op = tvm.relay.clip(op, a_min=0.0, a_max=255.0)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p, quant_p = qnn_conv_profiles\n    ref_mod, args = generate_model(conv_p, arg_p, quant_p)\n    mod = partition_for_dnnl(ref_mod)\n\n    # atol=1 means int values should match with +-1 quantum value tolerance\n    check_result(mod, ref_mod, args, tol=1e-10, atol=1, desired_compiler=\"dnnl\")\n\n\nconv_profiles = tvm.testing.parameter(\n    by_dict={\n        \"Base\": (base_conv, acp_regular),\n        \"NHWC\": (base_conv_nhwc, acp_regular),\n        \"Group\": (base_conv_group_no_pad, acp_regular),\n        \"DW\": (base_conv_dw_no_pad, acp_regular),\n        \"Dilated\": (base_conv_dilated, acp_regular),\n    }\n)\n\n\n@has_dnnl_codegen\ndef test_conv2d_plus(conv_profiles):\n    def generate_model(p, c):\n        np.random.seed(0)\n\n        N, IC, IH, IW = p.SHAPE\n        d_shape = p.SHAPE\n        w_shape = [p.OC, IC, *p.KER]\n        b_shape = [p.OC]\n        s_shape = [\n            p.SHAPE[0],\n            p.OC,\n            (IH + 2 * p.PAD[0] - (p.KER[0] - 1) * p.DEL[0] - 1) // p.STR[0] + 1,\n            (IW + 2 * p.PAD[1] - (p.KER[1] - 1) * p.DEL[1] - 1) // p.STR[1] + 1,\n        ]\n\n        if p.GR != 1:\n            w_shape[1] //= p.GR\n\n        d_shape = permute_shape(d_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        s_shape = permute_shape(s_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        w_shape = permute_shape(w_shape, l_from=\"OIHW\", l_to=p.K_LAYOUT)\n\n        c_dim = p.D_LAYOUT.find(\"C\")\n        # b_shape = expand_dim(b_shape, rank=len(p.D_LAYOUT) - c_dim)\n\n        bld = QnnBuilder()\n\n        op = bld.arg(shape=d_shape, dtype=\"float32\", is_const=c.Data)\n        wgh = bld.arg(shape=w_shape, dtype=\"float32\", is_const=c.Weights)\n        op = tvm.relay.nn.conv2d(\n            op,\n            wgh,\n            kernel_size=p.KER,\n            padding=p.PAD,\n            strides=p.STR,\n            dilation=p.DEL,\n            groups=p.GR,\n            channels=p.OC,\n            out_dtype=\"float32\",\n            data_layout=p.D_LAYOUT,\n            kernel_layout=p.K_LAYOUT,\n        )\n\n        if c.Bias is not None:\n            bias = bld.arg(shape=b_shape, dtype=\"float32\", is_const=c.Bias)\n            op = tvm.relay.nn.bias_add(op, bias, axis=c_dim)\n\n        if c.Sum is not None:\n            sum_in = bld.arg(shape=s_shape, dtype=\"float32\", is_const=c.Sum)\n            op = tvm.relay.op.add(op, sum_in)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p = conv_profiles\n    ref_mod, args = generate_model(conv_p, arg_p)\n    mod = partition_for_dnnl(ref_mod, alter_layout=False)\n    check_result(mod, ref_mod, args, tol=1e-5, desired_compiler=\"dnnl\")\n\n\nqnn_dense_profiles = tvm.testing.parameter(\n    by_dict={\n        #  Pattern Dense + Requantize\n        \"Base\": (base_dense_profile, acp_regular, qp_regular),\n        \"AsymmetricInput\": (base_dense_profile, acp_regular, qp_asymmetric_data),\n        #  Pattern Dense + Requantize + Sum\n        \"AsymmetricInput_Sum\": (base_dense_profile, acp_with_sum, qp_asymmetric_data),\n    }\n)\n\n\n@has_dnnl_codegen\ndef test_qnn_dense(qnn_dense_profiles):\n    def generate_model(p, c, q):\n        np.random.seed(0)\n\n        d_shape = [p.N, p.IC]\n        w_shape = [p.OC, p.IC]\n        b_shape = [p.OC]\n        s_shape = [p.N, p.OC]\n\n        bld = QnnBuilder(qnn_profile=q)\n\n        # Start build a test graph\n        data = bld.arg(shape=d_shape, dtype=\"uint8\", is_const=c.Data, filler=filler_uni(0, 20))\n        d_zp, d_scl = bld.make_zp_and_scl(\"d\", p.IC)\n\n        # Convolution\n        wgh = bld.arg(shape=w_shape, dtype=\"int8\", is_const=c.Weights, filler=filler_uni(-20, 20))\n        w_zp, w_scl = bld.make_zp_and_scl(\"k\")\n\n        op = tvm.relay.qnn.op.dense(\n            data, wgh, d_zp, w_zp, d_scl, w_scl, units=p.OC, out_dtype=\"int32\"\n        )\n        # Optional bias\n        if c.Bias is not None:\n            bias = bld.arg(\n                shape=b_shape, dtype=\"int32\", is_const=c.Bias, filler=filler_uni(-50, 50)\n            )\n            op = tvm.relay.add(op, bias)\n\n        # Re-quantization\n        rq_in_zp = bld.make_zp(0)\n        rq_in_scl = bld.make_scl(q.d_scl * q.k_scl)  # in real cases that should be a vector\n        rq_out_zp, rq_out_scl = bld.make_zp_and_scl(\"rq\")\n\n        op = tvm.relay.qnn.op.requantize(\n            op, rq_in_scl, rq_in_zp, rq_out_scl, rq_out_zp, out_dtype=\"int32\"\n        )\n        op = tvm.relay.clip(\n            op, a_min=0.0, a_max=255.0\n        )  # pytorch frontend specific, I guess it's redundant\n        op = tvm.relay.cast(op, dtype=\"uint8\")\n\n        # Optional sum (ResNet like)\n        if c.Sum is not None:\n            sum_in = bld.arg(dtype=\"uint8\", shape=s_shape, filler=filler_uni(0, 10), is_const=c.Sum)\n\n            lhs_zp, lhs_scl = bld.make_zp_and_scl(\"rq\")\n            rhs_zp, rhs_scl = bld.make_zp_and_scl(\"sum\")\n            out_zp, out_scl = bld.make_zp_and_scl(\"o\")\n\n            op = tvm.relay.qnn.op.add(op, sum_in, lhs_scl, lhs_zp, rhs_scl, rhs_zp, out_scl, out_zp)\n            op = tvm.relay.clip(op, a_min=0.0, a_max=255.0)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p, quant_p = qnn_dense_profiles\n    ref_mod, args = generate_model(conv_p, arg_p, quant_p)\n    mod = partition_for_dnnl(ref_mod)\n\n    # atol=1 means int values should match with +-1 quantum value tolerance\n    check_result(mod, ref_mod, args, tol=1e-10, atol=1, desired_compiler=\"dnnl\")\n\n\ndense_profiles = tvm.testing.parameter(\n    by_dict={\n        \"Base\": (base_dense_profile, acp_regular),\n        \"WithSum\": (base_dense_profile, acp_with_sum),\n    }\n)\n\n\n@has_dnnl_codegen\ndef test_dense_plus(dense_profiles):\n    def generate_model(p, c):\n        np.random.seed(0)\n\n        d_shape = [p.N, p.IC]\n        w_shape = [p.OC, p.IC]\n        b_shape = [p.OC]\n        s_shape = [p.N, p.OC]\n\n        c_dim = 1\n\n        bld = QnnBuilder()\n\n        op = bld.arg(shape=d_shape, dtype=\"float32\", is_const=c.Data)\n        wgh = bld.arg(shape=w_shape, dtype=\"float32\", is_const=c.Weights)\n        op = tvm.relay.nn.dense(op, wgh, out_dtype=\"float32\")\n\n        if c.Bias is not None:\n            bias = bld.arg(shape=b_shape, dtype=\"float32\", is_const=c.Bias)\n            op = tvm.relay.nn.bias_add(op, bias, axis=c_dim)\n\n        if c.Sum is not None:\n            sum_in = bld.arg(shape=s_shape, dtype=\"float32\", is_const=c.Sum)\n            op = tvm.relay.op.add(op, sum_in)\n\n        return bld.finalize(op)\n\n    dense_p, arg_p = dense_profiles\n    ref_mod, args = generate_model(dense_p, arg_p)\n    mod = partition_for_dnnl(ref_mod)\n    check_result(mod, ref_mod, args, tol=1e-5, desired_compiler=\"dnnl\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_edgetpu_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.contrib import utils, tflite_runtime\n\n# import tflite_runtime.interpreter as tflite\n\n# NOTE: This script was tested on tensorflow/tflite (v2.4.1)\n\n\ndef skipped_test_tflite_runtime():\n    def get_tflite_model_path(target_edgetpu):\n        # Return a path to the model\n        edgetpu_path = os.getenv(\"EDGETPU_PATH\", \"/home/mendel/edgetpu\")\n        # Obtain mobilenet model from the edgetpu repo path\n        if target_edgetpu:\n            model_path = os.path.join(\n                edgetpu_path, \"test_data/mobilenet_v1_1.0_224_quant_edgetpu.tflite\"\n            )\n        else:\n            model_path = os.path.join(edgetpu_path, \"test_data/mobilenet_v1_1.0_224_quant.tflite\")\n        return model_path\n\n    def init_interpreter(model_path, target_edgetpu):\n        # Initialize interpreter\n        if target_edgetpu:\n            edgetpu_path = os.getenv(\"EDGETPU_PATH\", \"/home/mendel/edgetpu\")\n            libedgetpu = os.path.join(edgetpu_path, \"libedgetpu/direct/aarch64/libedgetpu.so.1\")\n            interpreter = tflite.Interpreter(\n                model_path=model_path, experimental_delegates=[tflite.load_delegate(libedgetpu)]\n            )\n        else:\n            interpreter = tflite.Interpreter(model_path=model_path)\n        return interpreter\n\n    def check_remote(server, target_edgetpu=False):\n        tflite_model_path = get_tflite_model_path(target_edgetpu)\n\n        # inference via tflite interpreter python apis\n        interpreter = init_interpreter(tflite_model_path, target_edgetpu)\n        interpreter.allocate_tensors()\n        input_details = interpreter.get_input_details()\n        output_details = interpreter.get_output_details()\n\n        input_shape = input_details[0][\"shape\"]\n        tflite_input = np.array(np.random.random_sample(input_shape), dtype=np.uint8)\n        interpreter.set_tensor(input_details[0][\"index\"], tflite_input)\n        interpreter.invoke()\n        tflite_output = interpreter.get_tensor(output_details[0][\"index\"])\n\n        # inference via remote tvm tflite runtime\n        remote = rpc.connect(server.host, server.port)\n        dev = remote.cpu(0)\n        if target_edgetpu:\n            runtime_target = \"edge_tpu\"\n        else:\n            runtime_target = \"cpu\"\n\n        with open(tflite_model_path, \"rb\") as model_fin:\n            runtime = tflite_runtime.create(model_fin.read(), dev, runtime_target)\n            runtime.set_input(0, tvm.nd.array(tflite_input, dev))\n            runtime.invoke()\n            out = runtime.get_output(0)\n            np.testing.assert_equal(out.numpy(), tflite_output)\n\n    # Target CPU on coral board\n    check_remote(rpc.Server(\"127.0.0.1\"))\n    # Target EdgeTPU on coral board\n    check_remote(rpc.Server(\"127.0.0.1\"), target_edgetpu=True)\n\n\nif __name__ == \"__main__\":\n    # skipped_test_tflite_runtime()\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for Arm(R) Ethos(TM)-N\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/_infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Expose test functions to the Python front end\"\"\"\n\nimport tvm._ffi\n\ntvm._ffi._init_api(\"relay.ethos-n.test.infra\", __name__)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N test functions\"\"\"\n\nfrom __future__ import absolute_import, print_function\nfrom hashlib import md5\nfrom itertools import zip_longest, combinations\nimport os\nfrom typing import Tuple\nimport math\n\nimport numpy as np\nfrom PIL import Image\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib import utils, graph_executor, download\nfrom tvm.relay.op.contrib import partition_for_ethosn\nfrom tvm.driver.tvmc.target import parse_target\n\nfrom . import _infrastructure\n\n\ndef get_real_image(im_height, im_width):\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download.download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    x = np.array(image).astype(\"uint8\")\n    data = np.reshape(x, (1, im_height, im_width, 3))\n    return data\n\n\ndef assert_lib_hash(lib, golden):\n    \"\"\"Check that the Ethos-N runtime modules in a library hash to the same values\n    as given by the golden hash(es).\n\n    If there's only one Ethos-N module, the golden hash may be provided as a str.\n    If there's multiple, a set of golden hashes should be provided to correspond\n    with each Ethos-N module that is expected.\n\n    This function is used to ensure that no change is made which alters the output\n    of a compilation. If such a change is made deliberately (eg. to fix a bug) then\n    the golden hash should be updated after verifying on hardware that the behaviour\n    is still correct.\n\n    This method is used because of the lack of hardware availability in upstream CI.\n    \"\"\"\n    # Convert str hash into a set of hashes\n    if isinstance(golden, str):\n        golden = {golden}\n\n    temp = utils.tempdir()\n    path = temp.relpath(\"lib.cmm\")\n    hash_set = set()\n    for mod in lib.imported_modules:\n        if mod.type_key == \"ethos-n\":\n            mod.save(path)\n            with open(path, \"rb\") as compiled_model:\n                lib_hash = md5(compiled_model.read()).hexdigest()\n            hash_set.add(lib_hash)\n\n    assert hash_set == golden, \"Expected hash: {} Got hash: {}\".format(golden, hash_set)\n\n\ndef make_module(func, params):\n    func = relay.Function(relay.analysis.free_vars(func), func)\n    if params:\n        relay.build_module.bind_params_by_name(func, params)\n    mod = tvm.IRModule.from_expr(func)\n    return relay.transform.InferType()(mod)\n\n\ndef make_ethosn_composite(ethosn_expr, name):\n    variables = relay.analysis.free_vars(ethosn_expr)\n    inner_vars = [relay.Var(v.name_hint, v.type_annotation) for v in variables]\n    func = relay.Function(inner_vars, ethosn_expr)\n    func = func.with_attr(\"Composite\", name)\n    call = relay.Call(func, variables)\n    return call\n\n\ndef make_ethosn_partition(ethosn_expr):\n    \"\"\"Make an Ethos(TM)-N partition.\"\"\"\n\n    # Create an Ethos-N global function\n    mod = tvm.IRModule({})\n    variables = relay.analysis.free_vars(ethosn_expr)\n    # NB: it is illegal to reuse variables inside and outside a scope in Relay\n    # if you want to duplicate types and names you must re-allocate them.\n    fresh_vars = [relay.Var(v.name_hint, v.type_annotation) for v in variables]\n    binds = {}\n    for var, fresh_var in zip(variables, fresh_vars):\n        binds[var] = fresh_var\n    ethosn_expr_fresh = relay.bind(ethosn_expr, binds)\n    func = relay.Function(fresh_vars, ethosn_expr_fresh)\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", \"ethos-n\")\n    func = func.with_attr(\"global_symbol\", \"ethos-n_0\")\n    global_var = relay.GlobalVar(\"ethos-n_0\")\n    mod[global_var] = func\n    mod = relay.transform.InferType()(mod)\n\n    # These are the vars to call the Ethos-N partition with\n    more_vars = relay.analysis.free_vars(ethosn_expr)\n    # Call the Ethos-N partition in main\n    call_fn1 = global_var(*more_vars)\n    mod[\"main\"] = relay.Function(more_vars, call_fn1)\n    return relay.transform.InferType()(mod)\n\n\ndef get_host_op_count(mod):\n    \"\"\"Return the number of host operators.\"\"\"\n\n    class Counter(tvm.relay.ExprVisitor):\n        def __init__(self):\n            super().__init__()\n            self.count = 0\n\n        def visit_call(self, call):\n            if isinstance(call.op, tvm.ir.Op):\n                self.count += 1\n            super().visit_call(call)\n\n    c = Counter()\n    c.visit(mod[\"main\"])\n    return c.count\n\n\ndef build(\n    mod, params, npu=True, expected_host_ops=0, npu_partitions=1, additional_config_args=None\n):\n    \"\"\"Build a network with or without Ethos-N offloading.\n\n    Parameters\n    ----------\n    mod : IRModule\n        The Relay module to build.\n    params : dict of str to NDArray\n        The weights to build with.\n    npu : bool, optional\n        Whether to build with Ethos-N offloading.\n    expected_host_ops : int, optional\n        The number of ops expected to remain on the host.\n    npu_partitions : int, optional\n        The number of Ethos-N partitions expected.\n    additional_config_args : dict, optional\n        Additional compiler config options for the NPU.\n    \"\"\"\n    relay.backend.te_compiler.get().clear()\n    if not additional_config_args:\n        additional_config_args = {}\n    npu_config = {**get_ethosn_device_options(), **additional_config_args}\n    print(npu_config)\n    with tvm.transform.PassContext(opt_level=3, config={\"relay.ext.ethos-n.options\": npu_config}):\n        with tvm.target.Target(\"llvm\"):\n            if npu:\n                mod = partition_for_ethosn(mod, params)\n                host_op_count = get_host_op_count(mod)\n                assert (\n                    host_op_count == expected_host_ops\n                ), \"Got {} host operators, expected {}\".format(host_op_count, expected_host_ops)\n\n                attrs = [\n                    mod[var.name_hint].attrs\n                    for var in mod.get_global_vars()\n                    if mod[var.name_hint].attrs\n                ]\n                partition_count = sum(\n                    [\n                        key == \"Compiler\" and value == \"ethos-n\"\n                        for attr in attrs\n                        for key, value in attr.items()\n                    ]\n                )\n                assert (\n                    npu_partitions == partition_count\n                ), \"Got {} ethos-n partitions, expected {}\".format(partition_count, npu_partitions)\n\n            return relay.build(mod, params=params)\n\n\ndef run(lib, inputs, outputs, npu=True):\n    \"\"\"Run a module with specified inputs.\n\n    Parameters\n    ----------\n    lib : runtime.Module\n        The runtime module.\n    inputs : dict of str to NDArray\n        The input dictionary.\n    outputs : int\n        The expected number of outputs.\n    npu : bool\n        Whether or not any part of the lib is offloaded to Ethos-N.\n        If it's false (i.e. it's all running on the CPU), we set\n        the mocked result equal to the output so that a subsequent\n        mocked run on the NPU returns the same value.\n\n    Returns\n    -------\n    out : list of NDArray\n        The results.\n\n    \"\"\"\n    # Export and load lib to confirm this works\n    lib_name = \"mod.so\"\n    temp = utils.tempdir()\n    lib_path = temp.relpath(lib_name)\n    lib.export_library(lib_path)\n    lib = tvm.runtime.load_module(lib_path)\n    module = graph_executor.GraphModule(lib[\"default\"](tvm.cpu()))\n    module.set_input(**inputs)\n    module.run()\n    out = [module.get_output(i) for i in range(outputs)]\n    if not npu:\n        inference_result(out)\n    return out\n\n\ndef build_and_run(\n    mod,\n    inputs,\n    outputs,\n    params,\n    npu=True,\n    expected_host_ops=0,\n    npu_partitions=1,\n    additional_config_args=None,\n):\n    \"\"\"\n    Convenient wrapper for building and running a module on the NPU.\n    \"\"\"\n    lib = build(mod, params, npu, expected_host_ops, npu_partitions, additional_config_args)\n    return run(lib, inputs, outputs, npu)\n\n\ndef verify(answers, dtype, atol, rtol=1e-07, verify_saturation=True):\n    \"\"\"Compare the array of answers. Each entry is a list of outputs\"\"\"\n    if len(answers) < 2:\n        print(\"No results to compare: expected at least two, found \", len(answers))\n    for answer in zip_longest(*answers):\n        for outs in combinations(answer, 2):\n            if verify_saturation:\n                assert (\n                    np.count_nonzero(outs[0].numpy() == np.iinfo(dtype).max)\n                    < 0.25 * outs[0].numpy().size\n                ), \"Output is saturated: {}\".format(outs[0])\n                assert (\n                    np.count_nonzero(outs[0].numpy() == np.iinfo(dtype).min)\n                    < 0.25 * outs[0].numpy().size\n                ), \"Output is saturated: {}\".format(outs[0])\n            tvm.testing.assert_allclose(outs[0].numpy(), outs[1].numpy(), rtol=rtol, atol=atol)\n\n\ndef inference_result(outputs):\n    \"\"\"Set the expected results of an Ethos inference, if the testing\n    infrastructure is available. This assumes that the entire graph\n    was offloaded to the neural processor.\"\"\"\n    if tvm.get_global_func(\"relay.ethos-n.test.infra.inference_result\", True):\n        return _infrastructure.inference_result(*outputs)\n    return False\n\n\ndef test_error(mod, params, err_msg):\n    \"\"\"Test an operator error message.\"\"\"\n\n    caught = None\n    with tvm.transform.PassContext(\n        opt_level=3, config={\"relay.ext.ethos-n.options\": get_ethosn_device_options()}\n    ):\n        with tvm.target.Target(\"llvm\"):\n            try:\n                mod = relay.transform.InferType()(mod)\n                relay.build(mod, params=params)\n            except tvm.error.TVMError as error:\n                caught = error.args[0]\n            finally:\n                relay.backend.te_compiler.get().clear()\n\n    assert caught is not None\n    assert err_msg in caught, caught\n\n\ndef get_conv2d(var, shape, dtype):\n    \"\"\"Standard convolution to test activation functions\"\"\"\n\n    weight_shape = (1, 1, shape[3], 1)\n    weights_array = tvm.nd.array(np.ones(weight_shape, dtype))\n    weights = relay.const(weights_array, dtype)\n    conv = relay.qnn.op.conv2d(\n        var,\n        weights,\n        input_zero_point=relay.const(0, \"int32\"),\n        kernel_zero_point=relay.const(0, \"int32\"),\n        input_scale=relay.const(1.0, \"float32\"),\n        kernel_scale=relay.const(1.0, \"float32\"),\n        kernel_size=(1, 1),\n        channels=1,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    b = tvm.nd.array(np.zeros((shape[0],), \"int32\"))\n    biasc = relay.const(b, \"int32\")\n    bias = relay.nn.bias_add(conv, biasc, axis=0)\n    req = relay.qnn.op.requantize(\n        bias,\n        relay.const(1.0, \"float32\"),  # input zero scale\n        relay.const(0, \"int32\"),  # input zero point\n        relay.const(1.1, \"float32\"),  # output zero scale\n        relay.const(0, \"int32\"),  # output zero point\n        out_dtype=dtype,\n    )\n    params = {\"w\": weights_array, \"b\": b}\n    return req, params\n\n\ndef get_conv2d_qnn_params(\n    dtype, input_zp, input_sc, kernel_zp, kernel_sc, kernel_h, kernel_w, channels\n):\n    \"\"\"Return Conv2D QNN params.\"\"\"\n\n    kernel_sc = (\n        kernel_sc.numpy() if isinstance(kernel_sc, tvm.runtime.ndarray.NDArray) else [kernel_sc]\n    )\n    dtype_min = np.iinfo(dtype).min\n    dtype_max = np.iinfo(dtype).max\n\n    input_max = input_sc * (dtype_max - input_zp)\n    input_min = input_sc * (dtype_min - input_zp)\n\n    kernel_max = max(kernel_sc) * (dtype_max - kernel_zp)\n    kernel_min = min(kernel_sc) * (dtype_min - kernel_zp)\n\n    output_limits = [\n        kernel_max * kernel_h * kernel_w * channels * input_max,\n        kernel_min * kernel_h * kernel_w * channels * input_max,\n        kernel_min * kernel_h * kernel_w * channels * input_min,\n        kernel_max * kernel_h * kernel_w * channels * input_min,\n    ]\n    output_max = max(output_limits)\n    output_min = min(output_limits)\n\n    output_sc = (output_max - output_min) / (dtype_max - dtype_min)\n    output_zp = int(dtype_min - (output_min / output_sc))\n    return output_zp, output_sc\n\n\ndef get_same_padding(\n    data: Tuple[int, int],\n    kernel: Tuple[int, int],\n    dilation: Tuple[int, int],\n    stride: Tuple[int, int],\n) -> Tuple[int, int, int, int]:\n    \"\"\"\n    Get the padding values required for 'SAME' padding.\n\n    Parameters\n    ----------\n    data : Tuple[int, int]\n        The height and width of the data respectively.\n    kernel : Tuple[int, int]\n        The height and width of the kernel respectively.\n    dilation : Tuple[int, int]\n        The dilation of the kernel.\n    stride : Tuple[int, int]\n        The stride of the kernel.\n\n    Returns\n    -------\n    Tuple[int, int, int, int]\n        The padding values for top, left, bottom and right respectively.\n    \"\"\"\n    dilated_kernel_h = dilation[0] * (kernel[0] - 1) + 1\n    dilated_kernel_w = dilation[1] * (kernel[1] - 1) + 1\n    out = int(math.ceil(float(data[0]) / float(stride[0])))\n    pad = max(0, (out - 1) * stride[0] + dilated_kernel_h - data[0])\n    pad_top = pad // 2\n    pad_bottom = pad - pad_top\n\n    out = int(math.ceil(float(data[1]) / float(stride[1])))\n    pad = max(0, (out - 1) * stride[1] + dilated_kernel_w - data[1])\n    pad_left = pad // 2\n    pad_right = pad - pad_left\n    return (pad_top, pad_left, pad_bottom, pad_right)\n\n\ndef get_ethosn_device_options():\n    \"\"\"Determine the NPU configuration used for testing.\"\"\"\n    default_target_string = \"ethos-n -variant=n78 -tops=1 -ple_ratio=2\"\n    target_string = os.getenv(\"ETHOSN_TEST_TARGET_CONFIG\", default_target_string)\n    target = parse_target(target_string)\n    return target[0][\"opts\"]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_addition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration addition tests\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    lhs_shape,\n    rhs_shape,\n    lhs_zp,\n    lhs_sc,\n    rhs_zp,\n    rhs_sc,\n    out_zp,\n    out_sc,\n    dtype,\n    lhs_is_constant=False,\n    rhs_is_constant=False,\n    constant_data=None,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    if lhs_is_constant:\n        a_data = np.array(constant_data, dtype=dtype).reshape(lhs_shape)\n        a = relay.const(a_data, dtype=dtype)\n    else:\n        a = relay.var(\"a\", shape=lhs_shape, dtype=dtype)\n\n    if rhs_is_constant:\n        b_data = np.array(constant_data, dtype=dtype).reshape(rhs_shape)\n        np.random.randint(data_min, data_max + 1, size=rhs_shape, dtype=dtype)\n        b = relay.const(b_data, dtype=dtype)\n    else:\n        b = relay.var(\"b\", shape=rhs_shape, dtype=dtype)\n\n    model = relay.qnn.op.add(\n        lhs=a,\n        rhs=b,\n        lhs_scale=relay.const(lhs_sc, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zp, \"int32\"),\n        rhs_scale=relay.const(rhs_sc, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zp, \"int32\"),\n        output_scale=relay.const(out_sc, \"float32\"),\n        output_zero_point=relay.const(out_zp, \"int32\"),\n    )\n    return model\n\n\ndef _get_addition_qnn_params(dtype):\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    lhs_zp = np.random.randint(data_min, data_max)\n    lhs_sc = np.random.random() * 2\n    rhs_zp = np.random.randint(data_min, data_max)\n    rhs_sc = np.random.random() * 2\n\n    input1_max = lhs_sc * (255 - lhs_zp)\n    input1_min = -lhs_sc * lhs_zp\n    input2_max = rhs_sc * (255 - rhs_zp)\n    input2_min = -rhs_sc * rhs_zp\n    output_max = input1_max + input2_max\n    output_min = input1_min + input2_min\n    output_sc = (output_max - output_min) / 255\n    output_zp = -int(output_min / output_sc)\n    return lhs_zp, lhs_sc, rhs_zp, rhs_sc, output_zp, output_sc\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 22, 9, 9), (1, 27, 21, 16)])\ndef test_addition(dtype, shape):\n    \"\"\"Compare Addition output with TVM.\"\"\"\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc = _get_addition_qnn_params(dtype)\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=shape, dtype=dtype)),\n        \"b\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=shape, dtype=dtype)),\n    }\n    model = _get_model(shape, shape, lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc, dtype)\n    for npu in [False, True]:\n        mod = tei.make_module(model, [])\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"lhs_shape,lhs_is_constant,rhs_shape,rhs_is_constant\",\n    [\n        ((1, 4, 4, 8), False, (1, 1, 1, 8), True),\n        ((4,), True, (1, 16, 12, 4), False),\n        ((1, 1, 1, 8), True, (1, 4, 4, 8), False),\n        ((1, 16, 12, 4), False, (4,), True),\n    ],\n)\ndef test_addition_to_depthwise(dtype, lhs_shape, lhs_is_constant, rhs_shape, rhs_is_constant):\n    \"\"\"Compare addition to depthwise with TVM.\"\"\"\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc = _get_addition_qnn_params(dtype)\n\n    constant_shape = lhs_shape if lhs_is_constant else rhs_shape\n    constant_data = np.random.randint(data_min, data_max + 1, size=constant_shape, dtype=dtype)\n\n    model = _get_model(\n        lhs_shape,\n        rhs_shape,\n        lhs_zp,\n        lhs_sc,\n        rhs_zp,\n        rhs_sc,\n        out_zp,\n        out_sc,\n        dtype,\n        lhs_is_constant=lhs_is_constant,\n        rhs_is_constant=rhs_is_constant,\n        constant_data=constant_data,\n    )\n    input_shape = rhs_shape if lhs_is_constant else lhs_shape\n    input_name = \"b\" if lhs_is_constant else \"a\"\n    inputs = {\n        input_name: tvm.nd.array(\n            np.random.randint(data_min, data_max + 1, size=input_shape, dtype=dtype)\n        )\n    }\n    outputs = []\n    for npu in [False, True]:\n        mod = tei.make_module(model, {})\n        outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu))\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"lhs_shape,lhs_is_constant,rhs_shape,rhs_is_constant\",\n    [\n        ((1, 2, 8, 4), False, None, True),\n        ((1, 5, 6, 7), False, (1, 1, 1, 1), True),\n        (None, True, (1, 2, 8, 4), False),\n        ((1, 1, 1, 1), True, (1, 5, 6, 7), False),\n    ],\n)\ndef test_addition_to_reinterpret_quantize(lhs_shape, lhs_is_constant, rhs_shape, rhs_is_constant):\n    \"\"\"Compare addition to depthwise with TVM.\"\"\"\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    # Add can only be offloaded as a reinterpret quantize operation if\n    # it is an identity operation. We must choose the quantization and\n    # constant data carefully to maske sure that this is the case.\n    if lhs_is_constant:\n        rhs_zp = 128\n        rhs_sc = 0.0078125\n        lhs_zp = 0\n        lhs_sc = 0.003921568859368563\n    else:\n        lhs_zp = 128\n        lhs_sc = 0.0078125\n        rhs_zp = 0\n        rhs_sc = 0.003921568859368563\n    out_zp = 0\n    out_sc = 0.007814894430339336\n    constant_data = 255\n\n    model = _get_model(\n        lhs_shape,\n        rhs_shape,\n        lhs_zp,\n        lhs_sc,\n        rhs_zp,\n        rhs_sc,\n        out_zp,\n        out_sc,\n        dtype,\n        lhs_is_constant=lhs_is_constant,\n        rhs_is_constant=rhs_is_constant,\n        constant_data=constant_data,\n    )\n    input_shape = rhs_shape if lhs_is_constant else lhs_shape\n    input_name = \"b\" if lhs_is_constant else \"a\"\n    inputs = {\n        input_name: tvm.nd.array(\n            np.random.randint(data_min, data_max + 1, size=input_shape, dtype=dtype)\n        )\n    }\n    outputs = []\n    for npu in [False, True]:\n        mod = tei.make_module(model, {})\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,shape,err_msg\",\n    [\n        (\n            \"uint8\",\n            (2, 4, 4, 4),\n            \"batch size=2, batch size must = 1; batch size=2, batch size must = 1\",\n        ),\n        (\n            \"int16\",\n            (1, 4, 4, 4),\n            \"dtype='int16', dtype must be either uint8, int8 or int32; dtype='int16', \"\n            \"dtype must be either uint8, int8 or int32\",\n        ),\n    ],\n)\ndef test_addition_failure(dtype, shape, err_msg):\n    \"\"\"Check addition error messages.\"\"\"\n    np.random.seed(0)\n\n    lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc = _get_addition_qnn_params(dtype)\n\n    model = _get_model(shape, shape, lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc, dtype)\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_add\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"NPU codegen tests\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\n@requires_ethosn\ndef test_compile_with_unsupported_variant():\n    \"\"\"Test compilation with unsupported variant.\"\"\"\n    dtype = \"int8\"\n    input_shape = (1, 2, 2, 2)\n\n    x = relay.var(\"x\", shape=input_shape, dtype=dtype)\n    y = relay.reshape(x, newshape=(1, 1, 1, 8))\n    mod = tei.make_ethosn_partition(y)\n\n    additional_config_args = {\n        \"variant\": \"foo\",\n        \"inline_non_compute_intensive_partitions\": False,\n    }\n\n    inputs = {\n        \"x\": np.random.randint(\n            low=np.iinfo(dtype).min, high=np.iinfo(dtype).max, size=input_shape, dtype=dtype\n        )\n    }\n\n    with pytest.raises(tvm.TVMError, match=r\"Unknown NPU type\"):\n        tei.build_and_run(mod, inputs, 1, {}, True, additional_config_args=additional_config_args)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_concatenate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Concatenate tests for Arm(R) Ethos(TM)-N\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_inputs(shapes, dtype):\n    inputs = {}\n    for i, shape in enumerate(shapes):\n        inputs[\"in\" + str(i)] = tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        )\n\n    return inputs\n\n\ndef _get_model(shapes, dtype, axis):\n    tup = []\n    for i, shape in enumerate(shapes):\n        a = relay.var(\"in\" + str(i), shape=shape, dtype=dtype)\n        tup.append(a)\n\n    zeroi = relay.const(1, \"int32\")\n    zerof = relay.const(0.5, \"float32\")\n    con = relay.qnn.op.concatenate(\n        tup,\n        input_scales=[zerof] * len(shapes),\n        input_zero_points=[zeroi] * len(shapes),\n        output_scale=zerof,\n        output_zero_point=zeroi,\n        axis=axis,\n    )\n    return con\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shapes,axis\",\n    [\n        ([(1, 4), (1, 6)], 1),\n        ([(1, 16, 4), (1, 16, 4)], 1),\n        ([(1, 25, 4, 16)] * 3, 3),\n        ([(1, 25, 4, 16), (1, 25, 5, 16), (1, 25, 6, 16)], 2),\n        ([(1, 4), (1, 6)], -1),\n        ([(1, 16, 4), (1, 16, 4)], -2),\n    ],\n)\ndef test_concatenate(dtype, shapes, axis):\n    \"\"\"Compare Concatenate output with TVM.\"\"\"\n    np.random.seed(0)\n\n    outputs = []\n    inputs = _get_inputs(shapes, dtype)\n    for npu in [False, True]:\n        model = _get_model(shapes, dtype, axis)\n        mod = tei.make_module(model, {})\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n        tei.verify(outputs, dtype, 0)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shapes,dtype,axis,err_msg\",\n    [\n        ([(1, 4, 4, 4, 4), (1, 4, 4, 4, 4)], \"uint8\", 1, \"dimensions=5, dimensions must be <= 4;\"),\n        (\n            [(1, 4, 4, 4), (1, 4, 4, 4)],\n            \"uint8\",\n            3,\n            \"Concatenation along the channels dimension (axis 3) \"\n            \"requires input tensors with a multiple of 16 channels;\",\n        ),\n        (\n            [(1, 4, 4, 4), (1, 4, 4, 4)],\n            \"int16\",\n            2,\n            \"dtype='int16', dtype must be either uint8, int8 or int32; dtype='int16', \"\n            \"dtype must be either uint8, int8 or int32;\",\n        ),\n        (\n            [(2, 4, 4, 4), (2, 4, 4, 4)],\n            \"uint8\",\n            2,\n            \"batch size=2, batch size must = 1; batch size=2, batch size must = 1;\",\n        ),\n        (\n            [(1, 4, 4, 4)],\n            \"uint8\",\n            0,\n            \"Concatenation cannot be performed along batch axis (axis 0);\",\n        ),\n    ],\n)\ndef test_concatenate_failure(shapes, dtype, axis, err_msg):\n    \"\"\"Check Concatenate error messages.\"\"\"\n    model = _get_model(shapes, dtype, axis)\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_constant_duplication.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test that constants aren't duplicated for Arm(R) Ethos(TM)-N\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model():\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    shape = (1, 4, 4, 4)\n    kernel_h = 3\n    kernel_w = 3\n    out_channels = 8\n\n    a = relay.var(\"a\", shape=shape, dtype=\"uint8\")\n    add_const_value = tvm.nd.array(np.random.randint(0, high=10, size=shape, dtype=\"uint8\"))\n    add_const = relay.const(add_const_value, \"uint8\")\n    a = relay.add(a, add_const)\n    weight_shape = (kernel_h, kernel_w, shape[3], out_channels)\n    weights_array = tvm.nd.array(\n        np.random.randint(low=0, high=255, size=weight_shape, dtype=\"uint8\")\n    )\n    weights = relay.const(weights_array, \"uint8\")\n    conv = relay.qnn.op.conv2d(\n        a,\n        weights,\n        input_zero_point=relay.const(0, \"int32\"),\n        kernel_zero_point=relay.const(0, \"int32\"),\n        input_scale=relay.const(0.3, \"float32\"),\n        kernel_scale=relay.const(0.4, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        dilation=(1, 1),\n        strides=(1, 1),\n        groups=1,\n        channels=out_channels,\n        padding=(0, 0, 0, 0),\n        out_dtype=\"int32\",\n    )\n    b = tvm.nd.array(np.random.randint(0, high=10, size=(out_channels,), dtype=\"int32\"))\n    biasc = relay.const(b, \"int32\")\n    bias = relay.nn.bias_add(conv, biasc, axis=3)\n    req = relay.qnn.op.requantize(\n        bias,\n        relay.const(0.3 * 0.4, \"float32\"),  # input zero scale\n        relay.const(0, \"int32\"),  # input zero point\n        relay.const(0.4, \"float32\"),  # output zero scale\n        relay.const(0, \"int32\"),  # output zero point\n        out_dtype=\"uint8\",\n    )\n    params = {\"w\": weights_array, \"b\": b}\n    return req, params\n\n\n@requires_ethosn\ndef test_constant_duplication():\n    \"\"\"Test that constants are not duplicated.\"\"\"\n\n    np.random.seed(0)\n    model, params = _get_model()\n    mod = tei.make_module(model, params)\n    res = tei.build(mod, params, npu=True, expected_host_ops=1)\n    for key, value in res.params.items():\n        assert key == \"p0\"\n        assert value.numpy().size == 64\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration conv2d tests\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    shape,\n    kernel_h,\n    kernel_w,\n    input_zp,\n    input_sc,\n    kernel_zp,\n    kernel_sc,\n    output_zp,\n    output_sc,\n    pad,\n    strides,\n    dilation,\n    groups,\n    dtype,\n    out_channels,\n    weight_format,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    if pad in (\"op\", \"both\"):\n        p = tei.get_same_padding((shape[1], shape[2]), (kernel_h, kernel_w), dilation, strides)\n        a = relay.nn.pad(\n            a,\n            pad_width=[(0, 0), (p[0], p[2]), (p[1], p[3]), (0, 0)],\n            pad_value=input_zp,\n            pad_mode=\"constant\",\n        )\n        shape = (shape[0], shape[1] + p[0] + p[2], shape[2] + p[1] + p[3], shape[3])\n\n    p = tei.get_same_padding((shape[1], shape[2]), (kernel_h, kernel_w), dilation, strides)\n    if weight_format == \"HWIO\":\n        weight_shape = (kernel_h, kernel_w, shape[3] // groups, out_channels)\n    else:\n        weight_shape = (kernel_h, kernel_w, out_channels, 1)\n    weights_array = tvm.nd.array(\n        np.random.randint(\n            np.iinfo(dtype).min, high=np.iinfo(dtype).max + 1, size=weight_shape, dtype=dtype\n        )\n    )\n    weights = relay.const(weights_array, dtype)\n    conv = relay.qnn.op.conv2d(\n        a,\n        weights,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n        input_scale=relay.const(input_sc, \"float32\"),\n        kernel_scale=relay.const(kernel_sc, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        data_layout=\"NHWC\",\n        kernel_layout=weight_format,\n        dilation=dilation,\n        strides=strides,\n        groups=groups,\n        channels=out_channels,\n        padding=p if pad in (\"attr\", \"both\") else (0, 0, 0, 0),\n        out_dtype=\"int32\",\n    )\n    bias_data = tvm.nd.array(\n        np.random.randint(\n            np.iinfo(dtype).min, high=np.iinfo(dtype).max + 1, size=(out_channels,), dtype=\"int32\"\n        )\n    )\n    biasc = relay.const(bias_data, \"int32\")\n    bias = relay.nn.bias_add(conv, biasc, axis=3)\n    if isinstance(kernel_sc, tvm.runtime.ndarray.NDArray):\n        req_input_sc = [sc * input_sc for sc in kernel_sc.numpy()]\n    else:\n        req_input_sc = input_sc * kernel_sc\n    req = relay.qnn.op.requantize(\n        bias,\n        relay.const(req_input_sc, \"float32\"),  # input zero scale\n        relay.const(0, \"int32\"),  # input zero point\n        relay.const(output_sc, \"float32\"),  # output zero scale\n        relay.const(output_zp, \"int32\"),  # output zero point\n        out_dtype=dtype,\n    )\n    params = {\"w\": weights_array, \"b\": bias_data}\n    return req, params\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,qnn_per_channel\", [(\"uint8\", False), (\"int8\", False), (\"int8\", True)]\n)\n@pytest.mark.parametrize(\"pad,stride\", [(\"attr\", (2, 2)), (\"none\", (2, 2)), (\"op\", (1, 1))])\n@pytest.mark.parametrize(\n    \"shape,out_channels,kernel_size\",\n    [\n        [(1, 17, 20, 26), 4, (3, 1)],\n        [(1, 9, 20, 30), 7, (1, 5)],\n        [(1, 21, 21, 22), 8, (2, 2)],\n    ],\n)\ndef test_conv2d(\n    dtype,\n    shape,\n    out_channels,\n    kernel_size,\n    pad,\n    stride,\n    qnn_per_channel,\n):\n    \"\"\"Compare Conv2D output with TVM.\"\"\"\n    np.random.seed(0)\n\n    dilation = (1, 1)\n    groups = 1\n    weight_format = \"HWIO\"\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min,\n                np.iinfo(dtype).max + 1,\n                size=shape,\n                dtype=dtype,\n            )\n        ),\n    }\n    input_zp = np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max)\n    input_sc = np.random.random() * 2\n    if qnn_per_channel:\n        kernel_sc = tvm.nd.array(\n            np.random.uniform(low=0, high=2, size=(out_channels,)).astype(np.float32)\n        )\n    else:\n        kernel_sc = np.random.random() * 2\n    kernel_zp = (\n        0 if dtype == \"int8\" else np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max)\n    )\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, kernel_zp, kernel_sc, kernel_size[0], kernel_size[1], shape[3]\n    )\n    model, params = _get_model(\n        shape,\n        kernel_size[0],\n        kernel_size[1],\n        input_zp,\n        input_sc,\n        kernel_zp,\n        kernel_sc,\n        output_zp,\n        output_sc,\n        pad,\n        stride,\n        dilation,\n        groups,\n        dtype,\n        out_channels,\n        weight_format,\n    )\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(tei.build_and_run(mod, inputs, 1, params, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,qnn_per_channel\", [(\"uint8\", False), (\"int8\", False), (\"int8\", True)]\n)\n@pytest.mark.parametrize(\"pad,stride\", [(\"attr\", (2, 2)), (\"none\", (2, 2)), (\"op\", (1, 1))])\n@pytest.mark.parametrize(\n    \"shape,kernel_size\",\n    [\n        [(1, 17, 20, 28), (3, 3)],\n        [(1, 9, 20, 30), (5, 5)],\n        [(1, 21, 21, 22), (2, 2)],\n    ],\n)\ndef test_conv2d_depthwise(\n    dtype,\n    shape,\n    kernel_size,\n    pad,\n    stride,\n    qnn_per_channel,\n):\n    \"\"\"Compare Conv2D output with TVM.\"\"\"\n    np.random.seed(0)\n\n    dilation = (1, 1)\n    out_channels = shape[3]\n    groups = out_channels\n    weight_format = \"HWOI\"\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min,\n                np.iinfo(dtype).max + 1,\n                size=shape,\n                dtype=dtype,\n            )\n        ),\n    }\n    input_zp = np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max)\n    input_sc = np.random.random() * 2\n    if qnn_per_channel:\n        kernel_sc = tvm.nd.array(\n            np.random.uniform(low=0, high=2, size=(out_channels,)).astype(np.float32)\n        )\n    else:\n        kernel_sc = np.random.random() * 2\n    kernel_zp = (\n        0 if dtype == \"int8\" else np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max)\n    )\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, kernel_zp, kernel_sc, kernel_size[0], kernel_size[1], shape[3]\n    )\n    model, params = _get_model(\n        shape,\n        kernel_size[0],\n        kernel_size[1],\n        input_zp,\n        input_sc,\n        kernel_zp,\n        kernel_sc,\n        output_zp,\n        output_sc,\n        pad,\n        stride,\n        dilation,\n        groups,\n        dtype,\n        out_channels,\n        weight_format,\n    )\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(tei.build_and_run(mod, inputs, 1, params, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,pad,stride,dilation,err_msg\",\n    [\n        (\n            (1, 4, 4, 4),\n            \"both\",\n            (1, 1),\n            (1, 1),\n            \"both op and attr padding exist, must be either op/attr only or no padding\",\n        ),\n        (\n            (1, 4, 4, 4),\n            \"none\",\n            (1, 1, 1),\n            (1, 1),\n            \"stride size=3, stride size must = 2\",\n        ),\n        (\n            (1, 4, 4, 4),\n            \"none\",\n            (1, 1),\n            (2, 1),\n            \"dilation=[2, 1], dilation must = [1, 1]\",\n        ),\n        (\n            (2, 4, 4, 4),\n            \"none\",\n            (1, 1),\n            (1, 1),\n            \"batch size=2, batch size must = 1\",\n        ),\n    ],\n)\ndef test_conv2d_failure(shape, pad, stride, dilation, err_msg):\n    \"\"\"Check Conv2D error messages.\"\"\"\n    np.random.seed(0)\n\n    kernel_size = (2, 2)\n    groups = 1\n    dtype = \"uint8\"\n    out_channels = 8\n    weight_format = \"HWIO\"\n\n    model, _ = _get_model(\n        shape,\n        kernel_size[0],\n        kernel_size[1],\n        0,\n        1,\n        0,\n        1,\n        0,\n        1,\n        pad,\n        stride,\n        dilation,\n        groups,\n        dtype,\n        out_channels,\n        weight_format,\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_conv2d\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n\n\n@requires_ethosn\ndef test_conv2d_out_of_range_scale():\n    \"\"\"Check Conv2D scale out of range error.\"\"\"\n    np.random.seed(0)\n\n    input_sc = 1024\n    kernel_sc = 1024\n    output_sc = 1\n\n    model, _ = _get_model(\n        (1, 4, 4, 4),\n        1,\n        1,\n        0,\n        input_sc,\n        0,\n        kernel_sc,\n        0,\n        output_sc,\n        \"none\",\n        (1, 1),\n        (1, 1),\n        1,\n        \"uint8\",\n        8,\n        \"HWIO\",\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_conv2d\")\n    mod = tei.make_ethosn_partition(model)\n\n    expected_err_msg = (\n        \"Overall scale (of the input * weights / output) should be in the range (2^-32, 65536)\"\n    )\n    tei.test_error(mod, {}, expected_err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration conv2d tests\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    shape,\n    kernel_h,\n    kernel_w,\n    input_zp,\n    input_sc,\n    kernel_zp,\n    kernel_sc,\n    output_zp,\n    output_sc,\n    stride,\n    dilation,\n    groups,\n    kernel_layout,\n    dtype,\n    out_channels,\n    bias,\n):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    p = tei.get_same_padding((shape[1], shape[2]), (kernel_h, kernel_w), dilation, stride)\n    weight_shape = (shape[3], out_channels // groups, kernel_h, kernel_w)\n\n    weight_data = tvm.nd.array(\n        np.random.randint(\n            np.iinfo(dtype).min,\n            high=(np.iinfo(dtype).max + 1),\n            size=weight_shape,\n            dtype=dtype,\n        )\n    )\n    weights = relay.const(weight_data, dtype)\n    op = relay.qnn.op.conv2d_transpose(\n        a,\n        weights,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        input_scale=relay.const(input_sc, \"float32\"),\n        kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n        kernel_scale=relay.const(kernel_sc, \"float32\"),\n        kernel_size=(kernel_h, kernel_w),\n        padding=p,\n        strides=stride,\n        dilation=dilation,\n        data_layout=\"NHWC\",\n        kernel_layout=kernel_layout,\n        out_dtype=\"int32\",\n        channels=out_channels,\n        groups=groups,\n    )\n    if bias:\n        bias_data = tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min,\n                high=np.iinfo(dtype).max + 1,\n                size=(out_channels,),\n                dtype=\"int32\",\n            )\n        )\n        biasc = relay.const(bias_data, \"int32\")\n        op = relay.nn.bias_add(op, biasc, axis=3)\n\n    if isinstance(kernel_sc, tvm.runtime.ndarray.NDArray):\n        req_input_sc = [sc * input_sc for sc in kernel_sc.numpy()]\n    else:\n        req_input_sc = input_sc * kernel_sc\n\n    op = relay.qnn.op.requantize(\n        op,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        input_scale=relay.const(req_input_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        output_scale=relay.const(output_sc, \"float32\"),\n        axis=3,\n        rounding=\"UPWARD\",\n        out_dtype=dtype,\n    )\n    params = {\"w\": weight_data}\n    if bias:\n        params[\"b\"] = bias_data\n    return op, params\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"ifm_shape,strides,kernel_size,out_channels,bias\",\n    [\n        ((1, 2, 2, 1), (2, 2), (1, 1), 1, False),\n        ((1, 2, 2, 5), (2, 2), (3, 5), 4, False),\n        ((1, 7, 7, 4), (2, 2), (7, 9), 8, True),\n    ],\n)\ndef test_conv2d_transpose(ifm_shape, strides, kernel_size, out_channels, dtype, bias):\n    \"\"\"Check transpose convolution output with TVM.\"\"\"\n    np.random.seed(0)\n\n    kernel_layout = \"IOHW\"\n    dilation = (1, 1)\n    groups = 1\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    kernel_zp = np.random.randint(data_min, data_max)\n    kernel_sc = np.random.random() * 4\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, kernel_zp, kernel_sc, ifm_shape[1], ifm_shape[2], ifm_shape[3]\n    )\n\n    model, params = _get_model(\n        shape=ifm_shape,\n        kernel_h=kernel_size[0],\n        kernel_w=kernel_size[1],\n        input_zp=input_zp,\n        input_sc=input_sc,\n        kernel_zp=kernel_zp,\n        kernel_sc=kernel_sc,\n        output_zp=output_zp,\n        output_sc=output_sc,\n        stride=strides,\n        dilation=dilation,\n        groups=groups,\n        kernel_layout=kernel_layout,\n        dtype=dtype,\n        out_channels=out_channels,\n        bias=bias,\n    )\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=ifm_shape, dtype=dtype))\n    }\n\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(tei.build_and_run(mod, inputs, 1, params, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape, stride, dilation, groups, err_msg\",\n    [\n        (\n            (1, 4, 4, 4),\n            (1, 1, 1),\n            (1, 1),\n            1,\n            \"stride size=3, stride size must = 2\",\n        ),\n        (\n            (1, 4, 4, 4),\n            (2, 2),\n            (2, 2),\n            2,\n            \"dilation=[2, 2], dilation must = [1, 1]\",\n        ),\n        (\n            (2, 4, 4, 4),\n            (1, 1),\n            (1, 1),\n            1,\n            \"batch size=2, batch size must = 1\",\n        ),\n    ],\n)\ndef test_conv2d_transpose_failure(\n    shape,\n    stride,\n    dilation,\n    groups,\n    err_msg,\n    dtype,\n):\n    \"\"\"\n    Test transpose_conv2d error messages.\n    \"\"\"\n    np.random.seed(0)\n    out_channels = 8\n\n    model, _ = _get_model(\n        shape=shape,\n        kernel_h=1,\n        kernel_w=1,\n        input_zp=0,\n        input_sc=1,\n        kernel_zp=0,\n        kernel_sc=1,\n        output_zp=0,\n        output_sc=1,\n        stride=stride,\n        dilation=dilation,\n        groups=groups,\n        kernel_layout=\"IOHW\",\n        dtype=dtype,\n        out_channels=out_channels,\n        bias=False,\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_conv2d_transpose\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_convert_equivalents.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Unit tests for the convert equivalents pass.\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom tvm.relay.op.contrib.ethosn import ConvertEquivalents\nfrom tvm.relay import ExprVisitor\n\nfrom . import infrastructure as tei\nfrom .test_addition import _get_addition_qnn_params\n\n\ndef _assert_structural_equal(a, b):\n    \"\"\"Check structural equality of two Relay expressions.\"\"\"\n    reason = (\n        \"Actual and expected relay functions are not equal. \"\n        \"ConvertEquivalents is not correctly transforming the input \"\n        \"graph.\"\n    )\n    assert tvm.ir.structural_equal(a, b), reason\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\"shape,channels\", [((1, 4, 4, 8), 8), ((1, 16, 12, 4), 4)])\n@pytest.mark.parametrize(\"reverse_inputs\", [True, False])\ndef test_multiply_to_depthwise(dtype, shape, channels, reverse_inputs):\n    \"\"\"Check that multiply is correctly converted to a depthwise operation.\"\"\"\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    input2_zp = np.random.randint(data_min, data_max)\n    input2_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, input2_zp, input2_sc, 1, 1, shape[3]\n    )\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    constant_shape = (1, 1, 1, channels)\n    y_data = np.random.randint(data_min, data_max + 1, size=constant_shape, dtype=dtype)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.mul(\n            y if reverse_inputs else x,\n            x if reverse_inputs else y,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp, \"int32\"),\n            relay.const(input2_sc, \"float32\"),\n            relay.const(input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_mul_to_depthwise\")\n        return tei.make_ethosn_partition(composite)\n\n    def expected():\n        constant_shape_hwoi = (1, 1, channels, 1)\n        y_data_hwoi = y_data.reshape(constant_shape_hwoi)\n        y_hwoi = relay.const(y_data_hwoi, dtype=dtype)\n        expr = relay.qnn.op.conv2d(\n            x,\n            y_hwoi,\n            relay.const(input2_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(input_zp if reverse_inputs else input2_zp, \"int32\"),\n            relay.const(input2_sc if reverse_inputs else input_sc, \"float32\"),\n            relay.const(input_sc if reverse_inputs else input2_sc, \"float32\"),\n            (1, 1),\n            channels,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            channels,\n            \"NHWC\",\n            \"HWOI\",\n            \"NHWC\",\n            \"int32\",\n        )\n        expr = relay.nn.bias_add(expr, relay.const(np.zeros((channels,), dtype=\"int32\")), axis=3)\n        expr = relay.qnn.op.requantize(\n            expr,\n            relay.const(input2_sc if reverse_inputs else input_sc, \"float32\"),\n            relay.const(input2_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n            out_dtype=dtype,\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_conv2d\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n    mod = ConvertEquivalents()(mod)\n    expected_mod = expected()\n    _assert_structural_equal(mod[\"ethos-n_0\"], expected_mod[\"ethos-n_0\"])\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,shape,constant_shape\",\n    [(\"int8\", (1, 4, 4), (4,)), (\"int16\", (1, 16, 12, 4), (1, 1, 1, 4))],\n)\ndef test_unsupported_multiply_to_depthwise(dtype, shape, constant_shape):\n    \"\"\"Check that unsupported variants of multiply to depthwise are not converted.\"\"\"\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    input2_zp = np.random.randint(data_min, data_max)\n    input2_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, input2_zp, input2_sc, 1, 1, shape[-1]\n    )\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y_data = np.random.randint(data_min, data_max + 1, size=constant_shape, dtype=dtype)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.mul(\n            x,\n            y,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp, \"int32\"),\n            relay.const(input2_sc, \"float32\"),\n            relay.const(input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_mul_to_depthwise\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n\n    error_regex = (\n        r'Operation \"ethos-n.qnn_mul_to_depthwise\" was marked '\n        r\"as having a valid conversion, but it could not be converted.\"\n    )\n\n    with pytest.raises(tvm.TVMError, match=error_regex):\n        mod = ConvertEquivalents()(mod)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,constant_shape\",\n    [((1, 4, 4, 8), (1, 1, 1, 1)), ((1, 16, 12, 4), None)],\n)\n@pytest.mark.parametrize(\"reverse_inputs\", [True, False])\ndef test_multiply_to_reinterpret_quantize(shape, constant_shape, reverse_inputs):\n    \"\"\"Check that multiply is correctly converted to a reinterpret quantize operation.\"\"\"\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n\n    # Multiply can only be offloaded as a reinterpret quantize operation if\n    # it is an identity option. We must choose the quantization and constant\n    # data carefully to make sure that this is the case.\n    input_zp = 0\n    input_sc = 0.007814894430339336\n    input2_zp = 0\n    input2_sc = 0.5\n    output_zp = 0\n    output_sc = 0.9963990449905396\n    constant_data = 255\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y_data = np.array(constant_data, dtype=dtype).reshape(constant_shape)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.mul(\n            y if reverse_inputs else x,\n            x if reverse_inputs else y,\n            relay.const(input2_sc if reverse_inputs else input_sc, \"float32\"),\n            relay.const(input2_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(input_sc if reverse_inputs else input2_sc, \"float32\"),\n            relay.const(input_zp if reverse_inputs else input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_mul_to_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    def expected():\n        expr = relay.qnn.op.requantize(\n            x,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n            out_dtype=dtype,\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n    mod = ConvertEquivalents()(mod)\n    expected_mod = expected()\n    _assert_structural_equal(mod[\"ethos-n_0\"], expected_mod[\"ethos-n_0\"])\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,shape,constant_shape\",\n    [(\"int16\", (1, 16, 12, 4), None)],\n)\ndef test_unsupported_multiply_to_reinterpret_quantize(dtype, shape, constant_shape):\n    \"\"\"\n    Check that unsupported variants of multiply conversion to reinterpret\n    quantize are not converted.\n    \"\"\"\n    np.random.seed(0)\n\n    # Multiply can only be offloaded as a reinterpret quantize operation if\n    # it is an identity option. We must choose the quantization and constant\n    # data carefully to make sure that this is the case.\n    input_zp = 0\n    input_sc = 0.007814894430339336\n    input2_zp = 0\n    input2_sc = 0.5\n    output_zp = 0\n    output_sc = 0.9963990449905396\n    constant_data = 255\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y_data = np.array(constant_data, dtype=dtype).reshape(constant_shape)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.mul(\n            x,\n            y,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp, \"int32\"),\n            relay.const(input2_sc, \"float32\"),\n            relay.const(input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_mul_to_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n\n    error_regex = (\n        r'Operation \"ethos-n.qnn_mul_to_reinterpret_quantize\" was marked '\n        r\"as having a valid conversion, but it could not be converted.\"\n    )\n\n    with pytest.raises(tvm.TVMError, match=error_regex):\n        mod = ConvertEquivalents()(mod)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"reverse_inputs\", [True, False])\ndef test_add_to_depthwise(reverse_inputs):\n    \"\"\"\n    Check that add is converted correctly.\n    \"\"\"\n    dtype = \"uint8\"\n    lhs_shape = (1, 2, 4, 8)\n    rhs_shape = (1, 1, 1, 8)\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc = _get_addition_qnn_params(dtype)\n\n    x = relay.var(\"x\", shape=lhs_shape, dtype=dtype)\n    y_data = np.random.randint(data_min, data_max + 1, size=rhs_shape, dtype=dtype)\n\n    def before():\n        y = relay.const(y_data)\n        expr = relay.qnn.op.add(\n            lhs=y if reverse_inputs else x,\n            rhs=x if reverse_inputs else y,\n            lhs_scale=relay.const(lhs_sc, \"float32\"),\n            lhs_zero_point=relay.const(lhs_zp, \"int32\"),\n            rhs_scale=relay.const(rhs_sc, \"float32\"),\n            rhs_zero_point=relay.const(rhs_zp, \"int32\"),\n            output_scale=relay.const(out_sc, \"float32\"),\n            output_zero_point=relay.const(out_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_add_to_depthwise\")\n        return tei.make_ethosn_partition(composite)\n\n    class ConversionChecker(ExprVisitor):\n        \"\"\"\n        Pass to check the new composite function is in the expected format.\n        \"\"\"\n\n        sequence = [\"qnn.conv2d\", \"nn.bias_add\", \"qnn.requantize\"]\n\n        # pylint: disable=invalid-name\n        def visit_function(self, fn):\n            composite_name = fn.attrs[\"Composite\"]\n            expected = \"ethos-n.qnn_conv2d\"\n            assert (\n                composite_name == expected\n            ), f\"Expected Composite attribute {expected} but got {composite_name}\"\n            super().visit_function(fn)\n\n        def visit_call(self, call):\n            op_name = call.op.name\n            expected_name = self.sequence.pop()\n            assert op_name == expected_name, f\"Got operator {op_name} but expected {expected_name}\"\n            super().visit_call(call)\n\n    mod = before()\n    mod = ConvertEquivalents()(mod)\n    mod = ConversionChecker().visit(mod[\"ethos-n_0\"].body.op)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,lhs_shape,rhs_shape\", [(\"uint8\", (1, 4, 4), (1, 1, 4)), (\"int16\", (1, 4, 4, 4), (4,))]\n)\ndef test_unsupported_add_to_depthwise(dtype, lhs_shape, rhs_shape):\n    \"\"\"Check that unsupported variants of add are not converted.\"\"\"\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    lhs_zp, lhs_sc, rhs_zp, rhs_sc, out_zp, out_sc = _get_addition_qnn_params(dtype)\n\n    x = relay.var(\"x\", shape=lhs_shape, dtype=dtype)\n    y_data = np.random.randint(data_min, data_max + 1, size=rhs_shape, dtype=dtype)\n\n    def before():\n        y = relay.const(y_data)\n        expr = relay.qnn.op.add(\n            lhs=x,\n            rhs=y,\n            lhs_scale=relay.const(lhs_sc, \"float32\"),\n            lhs_zero_point=relay.const(lhs_zp, \"int32\"),\n            rhs_scale=relay.const(rhs_sc, \"float32\"),\n            rhs_zero_point=relay.const(rhs_zp, \"int32\"),\n            output_scale=relay.const(out_sc, \"float32\"),\n            output_zero_point=relay.const(out_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_add_to_depthwise\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n\n    error_regex = (\n        r'Operation \"ethos-n.qnn_add_to_depthwise\" was marked '\n        r\"as having a valid conversion, but it could not be converted.\"\n    )\n\n    with pytest.raises(tvm.TVMError, match=error_regex):\n        mod = ConvertEquivalents()(mod)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,constant_shape\",\n    [\n        ((1, 4, 4, 8), (1, 1, 1, 1)),\n        ((1, 16, 12, 4), None),\n    ],\n)\n@pytest.mark.parametrize(\"reverse_inputs\", [True, False])\ndef test_add_to_reinterpret_quantize(shape, constant_shape, reverse_inputs):\n    \"\"\"Check that add is correctly converted to a reinterpret quantize operation.\"\"\"\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n\n    # Add can only be offloaded as a reinterpret quantize operation if\n    # it is an identity option. We must choose the quantization and constant\n    # data carefully to make sure that this is the case.\n    input_zp = 128\n    input_sc = 0.0078125\n    input2_zp = 0\n    input2_sc = 0.003921568859368563\n    output_zp = 0\n    output_sc = 0.007814894430339336\n    constant_data = 255\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y_data = np.array(constant_data, dtype=dtype).reshape(constant_shape)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.add(\n            y if reverse_inputs else x,\n            x if reverse_inputs else y,\n            relay.const(input2_sc if reverse_inputs else input_sc, \"float32\"),\n            relay.const(input2_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(input_sc if reverse_inputs else input2_sc, \"float32\"),\n            relay.const(input_zp if reverse_inputs else input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_add_to_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    def expected():\n        expr = relay.qnn.op.requantize(\n            x,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp if reverse_inputs else input_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n            out_dtype=dtype,\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n    mod = ConvertEquivalents()(mod)\n    expected_mod = expected()\n    _assert_structural_equal(mod[\"ethos-n_0\"], expected_mod[\"ethos-n_0\"])\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,shape,constant_shape\",\n    [\n        (\"int16\", (1, 16, 12, 4), None),\n    ],\n)\ndef test_unsupported_add_to_reinterpret_quantize(dtype, shape, constant_shape):\n    \"\"\"Check that unsupported variants of add to reinterpret quantize are not converted.\"\"\"\n    np.random.seed(0)\n\n    # Add can only be offloaded as a reinterpret quantize operation if\n    # it is an identity option. We must choose the quantization and constant\n    # data carefully to make sure that this is the case.\n    input_zp = 128\n    input_sc = 0.0078125\n    input2_zp = 0\n    input2_sc = 0.003921568859368563\n    output_zp = 0\n    output_sc = 0.007814894430339336\n    constant_data = 255\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y_data = np.array(constant_data, dtype=dtype).reshape(constant_shape)\n\n    def before():\n        y = relay.const(y_data, dtype=dtype)\n        expr = relay.qnn.op.add(\n            x,\n            y,\n            relay.const(input_sc, \"float32\"),\n            relay.const(input_zp, \"int32\"),\n            relay.const(input2_sc, \"float32\"),\n            relay.const(input2_zp, \"int32\"),\n            relay.const(output_sc, \"float32\"),\n            relay.const(output_zp, \"int32\"),\n        )\n        composite = tei.make_ethosn_composite(expr, \"ethos-n.qnn_add_to_reinterpret_quantize\")\n        return tei.make_ethosn_partition(composite)\n\n    mod = before()\n\n    error_regex = (\n        r'Operation \"ethos-n.qnn_add_to_reinterpret_quantize\" was marked '\n        r\"as having a valid conversion, but it could not be converted.\"\n    )\n\n    with pytest.raises(tvm.TVMError, match=error_regex):\n        mod = ConvertEquivalents()(mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration depth-to-space tests\"\"\"\n\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, block, dtype, layout):\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    depth = relay.nn.depth_to_space(a, layout=layout, block_size=block)\n    return depth\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape\",\n    [\n        (1, 16, 16, 16),\n        (1, 64, 32, 16),\n    ],\n)\ndef test_depth_to_space(dtype, shape):\n    \"\"\"Compare Depth To Space output with TVM.\"\"\"\n    np.random.seed(0)\n\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        )\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(shape, 2, dtype, \"NHWC\")\n        mod = tei.make_module(model, {})\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,block,dtype,layout,err_msg\",\n    [\n        ((2, 16, 16, 16), 2, \"uint8\", \"NHWC\", \"batch size=2, batch size must = 1\"),\n        (\n            (1, 16, 16, 16),\n            2,\n            \"int16\",\n            \"NHWC\",\n            \"dtype='int16', dtype must be either uint8, int8 or int32;\",\n        ),\n        ((1, 16, 16, 16), 4, \"uint8\", \"NHWC\", \"Only block size of 2 is supported\"),\n        ((1, 16, 16, 16), 2, \"uint8\", \"NCHW\", \"Input layer must be NHWC or NHWCB\"),\n    ],\n)\ndef test_depth_to_space_failure(shape, block, dtype, layout, err_msg):\n    \"\"\"Check Depth To Space error messages.\"\"\"\n    model = _get_model(shape, block, dtype, layout)\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_fullyconnected.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration fully connected tests\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    shape, weight_shape, input_zp, input_sc, kernel_zp, kernel_sc, output_zp, output_sc, dtype\n):\n    \"\"\"Return a model an any parameters it may have\"\"\"\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    weights_array = tvm.nd.array(\n        np.random.randint(\n            np.iinfo(dtype).min, high=np.iinfo(dtype).max, size=weight_shape, dtype=dtype\n        )\n    )\n    weights = relay.const(weights_array, dtype)\n    dense = relay.qnn.op.dense(\n        a,\n        weights,\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zp, \"int32\"),\n        input_scale=relay.const(input_sc, \"float32\"),\n        kernel_scale=relay.const(kernel_sc, \"float32\"),\n        units=weight_shape[0],\n        out_dtype=\"int32\",\n    )\n    b = tvm.nd.array(np.random.randint(0, high=255, size=(weight_shape[0],), dtype=\"int32\"))\n    biasc = relay.const(b, \"int32\")\n    bias = relay.nn.bias_add(dense, biasc)\n    req = relay.qnn.op.requantize(\n        bias,\n        relay.const(input_sc * kernel_sc, \"float32\"),  # input zero scale\n        relay.const(input_zp * kernel_zp, \"int32\"),  # input zero point\n        relay.const(output_sc, \"float32\"),  # output zero scale\n        relay.const(output_zp, \"int32\"),  # output zero point\n        out_dtype=dtype,\n    )\n    params = {\"w\": weights_array, \"b\": b}\n    return req, params\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,out_channels\",\n    [\n        ((1, 1024), 64),\n        ((1, 16384), 1),\n        ((1, 1280), 1000),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_fullyconnected(shape, out_channels, dtype):\n    \"\"\"Compare Fully Connected output with TVM.\"\"\"\n\n    np.random.seed(0)\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=shape, dtype=dtype)),\n    }\n    outputs = []\n\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    kernel_zp = np.random.randint(data_min, data_max)\n    kernel_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype,\n        input_zp,\n        input_sc,\n        kernel_zp,\n        kernel_sc,\n        shape[0],\n        shape[1],\n        1,\n    )\n    model, params = _get_model(\n        shape,\n        (out_channels, shape[1]),\n        input_zp,\n        input_sc,\n        kernel_zp,\n        kernel_sc,\n        output_zp,\n        output_sc,\n        dtype,\n    )\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(tei.build_and_run(mod, inputs, 1, params, npu=npu))\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,weight_shape,err_msg\",\n    [\n        (\n            (1, 1, 1, 64),\n            (1, 64),\n            \"Weights tensor must have I dimension equal to the number\"\n            \" of channels of the input tensor.;\",\n        ),\n        ((1024, 64), (1, 64), \"batch size=1024, batch size must = 1;\"),\n    ],\n)\ndef test_fullyconnected_failure(shape, weight_shape, err_msg):\n    \"\"\"Check Fully Connected error messages.\"\"\"\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n\n    model, _ = _get_model(\n        shape,\n        weight_shape,\n        0,\n        1,\n        0,\n        1,\n        0,\n        1,\n        dtype,\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_fc\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n\n\n@requires_ethosn\ndef test_fullyconnected_scale_out_of_range():\n    \"\"\"Check Fully Connected out of range scale error message.\"\"\"\n    np.random.seed(0)\n\n    input_sc = 1024\n    kernel_sc = 1024\n    output_sc = 1\n\n    model, _ = _get_model(\n        (1, 64),\n        (1, 64),\n        0,\n        input_sc,\n        0,\n        kernel_sc,\n        0,\n        output_sc,\n        \"uint8\",\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_fc\")\n    mod = tei.make_ethosn_partition(model)\n    expected_error_msg = (\n        \"Overall scale (of the input * weights / output) should be in the range (2^-32, 65536)\"\n    )\n    tei.test_error(mod, {}, expected_error_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_inline_partitions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTests for the 'InlineNonComputeIntensivePartitions' pass.\n\"\"\"\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom tvm.relay.op.contrib.ethosn import InlineNonComputeIntensivePartitions\n\nfrom . import infrastructure as tei\n\n\ndef _assert_structural_equal(a, b):\n    \"\"\"Check structural equality of two Relay expressions.\"\"\"\n    reason = (\n        \"Actual and expected relay functions are not equal. \"\n        \"InlineNonComputeIntensiveSubgraphs is not correctly \"\n        \"transforming the input graph.\"\n    )\n    assert tvm.ir.structural_equal(a, b, map_free_vars=True), reason\n\n\n@requires_ethosn\ndef test_single_reshape():\n    \"\"\"Check that a single reshape is inlined correctly.\"\"\"\n\n    def get_reshape():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        return relay.reshape(x, newshape=(2, 2, 4))\n\n    def before():\n        reshape = get_reshape()\n        return tei.make_ethosn_partition(reshape)\n\n    def expected():\n        reshape = get_reshape()\n        mod = tvm.IRModule.from_expr(reshape)\n        return relay.transform.InferType()(mod)\n\n    mod = before()\n    mod = InlineNonComputeIntensivePartitions()(mod)\n    expected_mod = expected()\n    _assert_structural_equal(mod, expected_mod)\n\n\n@requires_ethosn\ndef test_multiple_non_compute_intensive_ops():\n    \"\"\"\n    Check that a partitioned function is correctly inlined\n    when it contains multiple non-compute intensive operations.\n    \"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(2, 2, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 2, 2, 4))\n        x = relay.clip(x, 0.0, 1.0)\n        x = relay.reshape(x, newshape=(2, 2, 4))\n        return relay.clip(x, 0.0, 1.0)\n\n    def before():\n        func = get_graph()\n        return tei.make_ethosn_partition(func)\n\n    def expected():\n        func = get_graph()\n        mod = tvm.IRModule.from_expr(func)\n        return relay.transform.InferType()(mod)\n\n    mod = before()\n    mod = InlineNonComputeIntensivePartitions()(mod)\n    expected_mod = expected()\n    _assert_structural_equal(mod, expected_mod)\n\n\n@requires_ethosn\ndef test_compute_intensive_ops():\n    \"\"\"\n    Check that a partitioned function that is considered\n    compute intensive is not inlined.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x, layout=\"NHWC\")\n        x = relay.reshape(x, newshape=(2, 2, 4))\n        return tei.make_ethosn_partition(x)\n\n    mod = before()\n    transformed_mod = InlineNonComputeIntensivePartitions()(mod)\n    for global_var in mod.get_global_vars():\n        _assert_structural_equal(mod[global_var], transformed_mod[global_var])\n\n\n@requires_ethosn\ndef test_multiple_partitioned_functions():\n    \"\"\"\n    Tests the pass on a number of partitioned functions.\n    \"\"\"\n\n    def before():\n        composite_func_name = \"ethos-n_0\"\n        inp = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n\n        # partitioned func 1 (non compute intensive)\n        x = relay.reshape(inp, newshape=(1, 2, 2, 4))\n        partitioned_func_1 = tei.make_ethosn_partition(x)[composite_func_name]\n        gv_1 = relay.GlobalVar(\"ethos-n_0\")\n\n        # partitioned func 2 (compute intensive)\n        x = relay.nn.max_pool2d(inp, layout=\"NHWC\")\n        partitioned_func_2 = tei.make_ethosn_partition(x)[composite_func_name]\n        gv_2 = relay.GlobalVar(\"ethos-n_1\")\n\n        # partitioned func 3 (non compute intensive)\n        x = relay.clip(inp, 0.0, 1.0)\n        partitioned_func_3 = tei.make_ethosn_partition(x)[composite_func_name]\n        gv_3 = relay.GlobalVar(\"ethos-n_2\")\n\n        mod = tvm.IRModule({})\n        mod[gv_1] = partitioned_func_1\n        mod[gv_2] = partitioned_func_2\n        mod[gv_3] = partitioned_func_3\n        main_expr = relay.Call(gv_1, [inp])\n        main_expr = relay.Call(gv_2, [main_expr])\n        main_expr = relay.Call(gv_3, [main_expr])\n        mod[\"main\"] = relay.Function([inp], main_expr)\n        return relay.transform.InferType()(mod)\n\n    def expected():\n        composite_func_name = \"ethos-n_0\"\n        inp = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n\n        # partitioned func 2 (compute intensive)\n        x = relay.nn.max_pool2d(inp, layout=\"NHWC\")\n        partitioned_func_2 = tei.make_ethosn_partition(x)[composite_func_name]\n        gv_2 = relay.GlobalVar(\"ethos-n_1\")\n\n        mod = tvm.IRModule({})\n        mod[gv_2] = partitioned_func_2\n        main_expr = relay.reshape(inp, newshape=(1, 2, 2, 4))\n        main_expr = relay.Call(gv_2, [main_expr])\n        main_expr = relay.clip(main_expr, 0.0, 1.0)\n        mod[\"main\"] = relay.Function([inp], main_expr)\n        return relay.transform.InferType()(mod)\n\n    mod = before()\n    mod = InlineNonComputeIntensivePartitions()(mod)\n    expected_mod = expected()\n    for global_var in mod.get_global_vars():\n        _assert_structural_equal(mod[global_var.name_hint], expected_mod[global_var.name_hint])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_leaky_relu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Integration tests for Leaky ReLU\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype, alpha):\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    x = relay.qnn.op.dequantize(\n        x,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n    )\n    x = relay.nn.leaky_relu(x, alpha=alpha)\n    return relay.qnn.op.quantize(\n        x,\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=dtype,\n    )\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 52, 52, 3), (1, 3, 8, 2)])\n@pytest.mark.parametrize(\"alpha\", [0.001, 0.5678])\ndef test_leaky_relu(dtype, shape, alpha):\n    \"\"\"Compare Leaky ReLU output with TVM.\"\"\"\n\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    zp_min = iinfo.min\n    zp_max = iinfo.max\n    input_zp = zp_min + 120\n    input_sc = 0.0068132\n    output_zp = zp_min + 128\n    output_sc = 0.0078125\n\n    inputs = {\"x\": tvm.nd.array(np.random.randint(zp_min, high=zp_max, size=shape, dtype=dtype))}\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype, alpha)\n        mod = tei.make_module(model, [])\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"int8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 14, 14, 2)])\n@pytest.mark.parametrize(\"alpha\", [-1.34, 2.32, 1, 0])\ndef test_leaky_relu_unsupported_alpha(dtype, shape, alpha):\n    \"\"\"Test unsupported values of alpha (<= 0, >= 1) in Leaky ReLU.\"\"\"\n\n    iinfo = np.iinfo(dtype)\n    zp_min = iinfo.min\n\n    err_msg = f\"leaky relu alpha must be less than 1 and greater than 0, but was {alpha}\"\n\n    model = _get_model(shape, zp_min + 120, 0.0068132, zp_min + 128, 0.0078125, dtype, alpha)\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_leaky_relu\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_mean.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration mean tests\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, axis, keepdims, input_zp, input_sc, output_zp, output_sc, dtype):\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    casted = relay.op.cast(a, \"int32\")\n    mean = relay.mean(casted, axis, keepdims)\n    model = relay.qnn.op.requantize(\n        mean,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=dtype,\n    )\n    return model\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 7, 7, 2048), (1, 8, 8)])\ndef test_mean(dtype, shape):\n    \"\"\"Compare Mean output with TVM.\"\"\"\n\n    np.random.seed(0)\n\n    zp_min = np.iinfo(dtype).min\n    zp_max = np.iinfo(dtype).max\n\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(zp_min, high=zp_max + 1, size=shape, dtype=dtype)),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(\n            shape, [1, 2], True, zp_min + 128, 0.0784314, zp_min + 128, 0.0784314, dtype=dtype\n        )\n        mod = tei.make_module(model, [])\n        outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"uint8\"])\ndef test_mean_non_equal_quantization(dtype):\n    \"\"\"Test mean is not offloaded when quantization is not equal.\"\"\"\n\n    np.random.seed(0)\n\n    shape = (1, 7, 7, 2048)\n    zp_min = np.iinfo(dtype).min\n\n    model = _get_model(shape, [1, 2], True, zp_min + 120, 0.0068132, zp_min + 128, 0.0078125, dtype)\n    mod = tei.make_module(model, [])\n    tei.build(mod, {}, npu=True, expected_host_ops=3, npu_partitions=0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_multiply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Integration tests for Multiply.\"\"\"\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    shape,\n    constant_shape,\n    input_zp,\n    input_sc,\n    input2_zp,\n    input2_sc,\n    output_zp,\n    output_sc,\n    dtype,\n    reverse_inputs=False,\n    constant_data=None,\n):\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    if constant_data:\n        y_data = np.array(constant_data, dtype=dtype).reshape(constant_shape)\n    else:\n        y_data = np.random.randint(data_min, data_max + 1, size=constant_shape, dtype=dtype)\n    y = relay.const(y_data, dtype=dtype)\n\n    out = relay.qnn.op.mul(\n        y if reverse_inputs else x,\n        x if reverse_inputs else y,\n        relay.const(input_sc, \"float32\"),\n        relay.const(input_zp, \"int32\"),\n        relay.const(input2_sc, \"float32\"),\n        relay.const(input2_zp, \"int32\"),\n        relay.const(output_sc, \"float32\"),\n        relay.const(output_zp, \"int32\"),\n    )\n    params = {\"y\": y_data}\n    return out, params\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape,constant_shape\",\n    [((1, 4, 4, 8), (1, 1, 1, 8)), ((1, 16, 12, 4), (4,))],\n)\n@pytest.mark.parametrize(\"reverse_inputs\", [False, True])\ndef test_multiply_to_depthwise(dtype, shape, constant_shape, reverse_inputs):\n    \"\"\"Compare Multiply -> Depthwise conversion output with TVM.\"\"\"\n\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    input2_zp = np.random.randint(data_min, data_max)\n    input2_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, input2_zp, input2_sc, 1, 1, shape[3]\n    )\n\n    model, params = _get_model(\n        shape,\n        constant_shape,\n        input_zp,\n        input_sc,\n        input2_zp,\n        input2_sc,\n        output_zp,\n        output_sc,\n        dtype,\n        reverse_inputs,\n    )\n    inputs = {\"x\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=shape, dtype=dtype))}\n    outputs = []\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(tei.build_and_run(mod, inputs, 1, params, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,constant_shape\", [((1, 4, 5, 8), (1, 1, 1, 1)), ((1, 3, 7, 10), None)]\n)\n@pytest.mark.parametrize(\"reverse_inputs\", [False, True])\ndef test_multiply_to_reinterpret_quantize(shape, constant_shape, reverse_inputs):\n    \"\"\"Compare Multiply -> Reinterpret Quantize conversion output with TVM.\"\"\"\n    np.random.seed(0)\n\n    dtype = \"uint8\"\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n\n    # Multiply can only be offloaded as a reinterpret quantize operation if\n    # it is an identity option. We must choose the quantization and constant\n    # data carefully to make sure that this is the case.\n    input_zp = 0\n    input_sc = 0.007814894430339336\n    input2_zp = 0\n    input2_sc = 0.5\n    output_zp = 0\n    output_sc = 0.9963990449905396\n    constant_data = 255\n\n    model, params = _get_model(\n        shape,\n        constant_shape,\n        input_zp,\n        input_sc,\n        input2_zp,\n        input2_sc,\n        output_zp,\n        output_sc,\n        dtype,\n        reverse_inputs,\n        constant_data,\n    )\n    inputs = {\"x\": tvm.nd.array(np.random.randint(data_min, data_max + 1, size=shape, dtype=dtype))}\n    outputs = []\n    for npu in [False, True]:\n        mod = tei.make_module(model, params)\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                params,\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\ndef test_multiply_multiple_inputs_unsupported():\n    \"\"\"Check multiply operator with two inputs is not offloaded.\"\"\"\n\n    np.random.seed(0)\n\n    shape = (1, 4, 5, 6)\n    dtype = \"int8\"\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    input2_zp = np.random.randint(data_min, data_max)\n    input2_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, input2_zp, input2_sc, 1, 1, shape[3]\n    )\n\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y = relay.var(\"y\", shape=shape, dtype=dtype)\n    model = relay.qnn.op.mul(\n        x,\n        y,\n        relay.const(input_sc, \"float32\"),\n        relay.const(input_zp, \"int32\"),\n        relay.const(input2_sc, \"float32\"),\n        relay.const(input2_zp, \"int32\"),\n        relay.const(output_sc, \"float32\"),\n        relay.const(output_zp, \"int32\"),\n    )\n\n    expected_host_ops = 1\n    npu_partitions = 0\n    for npu in [False, True]:\n        mod = tei.make_module(model, {})\n        tei.build(\n            mod,\n            {},\n            npu=npu,\n            expected_host_ops=expected_host_ops,\n            npu_partitions=npu_partitions,\n        )\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"dtype,shape,constant_shape\",\n    [\n        (\"int16\", (1, 4, 5, 6), (1, 1, 1, 6)),\n        (\"int8\", (1, 1, 3), (1, 1, 1, 3)),\n        (\"int8\", (1, 2, 4, 8), (1, 2, 4, 8)),\n    ],\n)\ndef test_multiply_unsupported(dtype, shape, constant_shape):\n    \"\"\"Check multiply operator with unsupported attributes is not offloaded.\"\"\"\n\n    np.random.seed(0)\n\n    iinfo = np.iinfo(dtype)\n    data_min = iinfo.min\n    data_max = iinfo.max\n    input_zp = np.random.randint(data_min, data_max)\n    input_sc = np.random.random() * 2\n    input2_zp = np.random.randint(data_min, data_max)\n    input2_sc = np.random.random() * 2\n    output_zp, output_sc = tei.get_conv2d_qnn_params(\n        dtype, input_zp, input_sc, input2_zp, input2_sc, 1, 1, shape[-1]\n    )\n\n    model, params = _get_model(\n        shape,\n        constant_shape,\n        input_zp,\n        input_sc,\n        input2_zp,\n        input2_sc,\n        output_zp,\n        output_sc,\n        dtype,\n        reverse_inputs=False,\n        constant_data=False,\n    )\n\n    expected_host_ops = 1\n    npu_partitions = 0\n    for npu in [False, True]:\n        mod = tei.make_module(model, {})\n        tei.build(\n            mod,\n            params,\n            npu=npu,\n            expected_host_ops=expected_host_ops,\n            npu_partitions=npu_partitions,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_networks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position, wrong-import-order\n\n\"\"\"Arm(R) Ethos(TM)-N integration end-to-end network tests\"\"\"\n\nimport pytest\n\npytest.importorskip(\"tflite\")\npytest.importorskip(\"tensorflow\")\n\nimport tflite.Model\n\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom tvm.contrib import download\nimport tvm.relay.testing.tf as tf_testing\n\nfrom . import infrastructure as tei\n\n\ndef _get_tflite_model(tflite_model_path, inputs_dict, dtype):\n    with open(tflite_model_path, \"rb\") as f:\n        tflite_model_buffer = f.read()\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buffer, 0)\n    shape_dict = {}\n    dtype_dict = {}\n    for value in inputs_dict:\n        input_shape = inputs_dict[value]\n        shape_dict[value] = input_shape\n        dtype_dict[value] = dtype\n\n    return relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict=shape_dict,\n        dtype_dict=dtype_dict,\n    )\n\n\ndef _test_image_network(\n    model_url,\n    model_sub_path,\n    input_dict,\n    compile_hash,\n    output_count,\n    host_ops=0,\n    npu_partitions=1,\n    run=False,\n):\n    \"\"\"Test an image network.\n\n    Parameters\n    ----------\n    model_url : str\n        The URL to the model.\n    model_sub_path : str\n        The name of the model file.\n    input_dict : dict\n        The input dict.\n    compile_hash : str, set\n        The compile hash(es) to check the compilation output against.\n    output_count : int\n        The expected number of outputs.\n    host_ops : int\n        The expected number of host operators.\n    npu_partitions : int\n        The expected number of Ethos-N partitions.\n    run : bool\n        Whether or not to try running the network. If hardware isn't\n        available, the run will still take place but with a mocked\n        inference function, so the results will be incorrect. This is\n        therefore just to test the runtime flow is working rather than\n        to check the correctness/accuracy.\n\n    \"\"\"\n\n    def get_model():\n        if model_url[-3:] in (\"tgz\", \"zip\"):\n            model_path = tf_testing.get_workload_official(\n                model_url,\n                model_sub_path,\n            )\n        else:\n            model_path = download.download_testdata(\n                model_url,\n                model_sub_path,\n            )\n        return _get_tflite_model(model_path, input_dict, \"uint8\")\n\n    inputs = {}\n    for input_name in input_dict:\n        input_shape = input_dict[input_name]\n        inputs[input_name] = tei.get_real_image(input_shape[1], input_shape[2])\n\n    mod, params = get_model()\n    m = tei.build(mod, params, npu=True, expected_host_ops=host_ops, npu_partitions=npu_partitions)\n    tei.assert_lib_hash(m.get_lib(), compile_hash)\n    if run:\n        tei.run(m, inputs, output_count, npu=True)\n\n\n@requires_ethosn\ndef test_mobilenet_v1():\n    \"\"\"Compare compile hashes for mobilenetv1 with an expected result.\"\"\"\n    # If this test is failing due to a hash mismatch, please notify @lhutton1 and\n    # @Leo-arm. The hash is there to catch any changes in the behaviour of the\n    # codegen, which could come about from either a change in Support Library\n    # version or a change in the Ethos-N codegen. To update this requires running\n    # on hardware that isn't available in CI.\n    _compile_hash = {\"c37fec1f214c7f93ce49ee4e3b587969\"}\n    _test_image_network(\n        model_url=\"https://storage.googleapis.com/download.tensorflow.org/\"\n        \"models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\",\n        model_sub_path=\"mobilenet_v1_1.0_224_quant.tflite\",\n        input_dict={\"input\": (1, 224, 224, 3)},\n        compile_hash=_compile_hash,\n        output_count=1,\n        host_ops=3,\n        npu_partitions=1,\n        run=True,\n    )\n\n\n@requires_ethosn\ndef test_resnet_50_int8():\n    \"\"\"Compare compile hashes for resnet50 with an expected result.\"\"\"\n    # If this test is failing due to a hash mismatch, please notify @lhutton1 and\n    # @Leo-arm. The hash is there to catch any changes in the behaviour of the\n    # codegen, which could come about from either a change in Support Library\n    # version or a change in the Ethos-N codegen. To update this requires running\n    # on hardware that isn't available in CI.\n    _compile_hash = {\n        \"f16dc9caa8e696bc5da8a5c6a644eb72\",\n        \"41acecca37b2735bd580f6ec38d8c2e0\",\n    }\n    _test_image_network(\n        model_url=\"https://raw.githubusercontent.com/dmlc/web-data/main/tensorflow/\"\n        \"models/Quantized/resnet_50_quantized.tflite\",\n        model_sub_path=\"resnet_50_quantized.tflite\",\n        input_dict={\"input\": (1, 224, 224, 3)},\n        compile_hash=_compile_hash,\n        output_count=1,\n        host_ops=10,\n        npu_partitions=2,\n    )\n\n\n@requires_ethosn\ndef test_inception_v3():\n    \"\"\"Compare compile hashes for inceptionv3 with an expected result.\"\"\"\n    # If this test is failing due to a hash mismatch, please notify @lhutton1 and\n    # @Leo-arm. The hash is there to catch any changes in the behaviour of the\n    # codegen, which could come about from either a change in Support Library\n    # version or a change in the Ethos-N codegen. To update this requires running\n    # on hardware that isn't available in CI.\n    _compile_hash = {\"cff892eb15944756f22dad4b83c756d2\"}\n    _test_image_network(\n        model_url=\"https://storage.googleapis.com/download.tensorflow.org/\"\n        \"models/tflite_11_05_08/inception_v3_quant.tgz\",\n        model_sub_path=\"inception_v3_quant.tflite\",\n        input_dict={\"input\": (1, 299, 299, 3)},\n        compile_hash=_compile_hash,\n        output_count=1,\n        host_ops=0,\n        npu_partitions=1,\n    )\n\n\n@requires_ethosn\ndef test_inception_v4():\n    \"\"\"Compare compile hashes for inceptionv4 with an expected result.\"\"\"\n    # If this test is failing due to a hash mismatch, please notify @lhutton1 and\n    # @Leo-arm. The hash is there to catch any changes in the behaviour of the\n    # codegen, which could come about from either a change in Support Library\n    # version or a change in the Ethos-N codegen. To update this requires running\n    # on hardware that isn't available in CI.\n    _compile_hash = {\"c00c119506b34c8e87f81aa009b42431\"}\n    _test_image_network(\n        model_url=\"https://storage.googleapis.com/download.tensorflow.org/\"\n        \"models/inception_v4_299_quant_20181026.tgz\",\n        model_sub_path=\"inception_v4_299_quant.tflite\",\n        input_dict={\"input\": (1, 299, 299, 3)},\n        compile_hash=_compile_hash,\n        output_count=1,\n        host_ops=3,\n        npu_partitions=1,\n    )\n\n\n@requires_ethosn\ndef test_ssd_mobilenet_v1():\n    \"\"\"Compare compile hashes for ssdmobilenetv1 with an expected result.\"\"\"\n    # If this test is failing due to a hash mismatch, please notify @lhutton1 and\n    # @Leo-arm. The hash is there to catch any changes in the behaviour of the\n    # codegen, which could come about from either a change in Support Library\n    # version or a change in the Ethos-N codegen. To update this requires running\n    # on hardware that isn't available in CI.\n    _compile_hash = {\"ec2b78852192058f88b64d45c26620d5\", \"f68cbeaaba03874ea735ce3f5eab9227\"}\n    _test_image_network(\n        model_url=\"https://storage.googleapis.com/download.tensorflow.org/\"\n        \"models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip\",\n        model_sub_path=\"detect.tflite\",\n        input_dict={\"normalized_input_image_tensor\": (1, 300, 300, 3)},\n        compile_hash=_compile_hash,\n        output_count=4,\n        host_ops=27,\n        npu_partitions=2,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration pooling tests\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, typef, sizes, strides, pads, layout, dtype):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    req = relay.var(\"a\", shape=shape, dtype=dtype)\n    if typef is relay.nn.avg_pool2d:\n        req = relay.cast(req, \"int32\")\n    req = typef(req, pool_size=sizes, strides=strides, padding=pads, ceil_mode=True, layout=layout)\n    if typef is relay.nn.avg_pool2d:\n        req = relay.cast(req, dtype)\n    return req\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape,typef,size,stride,pad\",\n    [\n        ((1, 8, 8, 8), relay.nn.max_pool2d, (2, 2), (2, 2), (0, 0, 0, 0)),\n        ((1, 9, 9, 9), relay.nn.max_pool2d, (3, 3), (2, 2), (0, 0, 0, 0)),\n        ((1, 8, 8, 8), relay.nn.avg_pool2d, (3, 3), (1, 1), (1, 1, 1, 1)),\n    ],\n)\ndef test_pooling(dtype, shape, typef, size, stride, pad):\n    \"\"\"Compare Pooling output with TVM.\"\"\"\n    np.random.seed(0)\n\n    layout = \"NHWC\"\n\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                low=np.iinfo(dtype).min, high=np.iinfo(dtype).max + 1, size=shape, dtype=dtype\n            )\n        ),\n    }\n    outputs = []\n    model = _get_model(shape, typef, size, stride, pad, layout, dtype)\n    for npu in [False, True]:\n        mod = tei.make_module(model, {})\n        outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,size,stride,layout,dtype,err_msg\",\n    [\n        (\n            (2, 8, 8, 8),\n            (2, 2),\n            (2, 2),\n            \"NHWC\",\n            \"uint8\",\n            \"batch size=2, batch size must = 1\",\n        ),\n        (\n            (1, 8, 8, 8),\n            (2, 2),\n            (2, 2),\n            \"NHWC\",\n            \"int16\",\n            \"dtype='int16', dtype must be either uint8, int8 or int32\",\n        ),\n        (\n            (1, 8, 8, 8),\n            (2, 2),\n            (2, 2),\n            \"NCHW\",\n            \"uint8\",\n            \"data format=NCHW, data format must = NHWC\",\n        ),\n        (\n            (1, 8, 8, 8),\n            (2, 2),\n            (2, 2, 2),\n            \"NHWC\",\n            \"uint8\",\n            \"stride size=3, stride size must = 2\",\n        ),\n        (\n            (1, 8, 8, 8),\n            (2, 2, 2),\n            (2, 2),\n            \"NHWC\",\n            \"uint8\",\n            \"dimensions=3, dimensions must = 2\",\n        ),\n    ],\n)\ndef test_pooling_failure(shape, size, stride, layout, dtype, err_msg):\n    \"\"\"Check Pooling error messages.\"\"\"\n\n    typef = relay.nn.max_pool2d\n    pad = (0, 0, 0, 0)\n\n    model = _get_model(shape, typef, size, stride, pad, layout, dtype)\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_relu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration relu tests\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, dtype, a_min, a_max):\n    assert a_min >= np.iinfo(dtype).min and a_max <= np.iinfo(dtype).max\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    relu = relay.clip(a, a_min=a_min, a_max=a_max)\n    return relu\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,a_min,a_max,dtype\",\n    [\n        ((1, 4, 4, 4), 65, 178, \"uint8\"),\n        ((1, 8, 4, 2), 1, 254, \"uint8\"),\n        ((1, 8, 4, 2), -100, 100, \"int8\"),\n        ((1, 16), -120, -20, \"int8\"),\n    ],\n)\ndef test_relu(dtype, shape, a_min, a_max):\n    \"\"\"Compare Relu output with TVM.\"\"\"\n    np.random.seed(0)\n\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                low=np.iinfo(dtype).min,\n                high=np.iinfo(dtype).max + 1,\n                size=shape,\n                dtype=dtype,\n            )\n        ),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(inputs[\"a\"].shape, dtype, a_min, a_max)\n        mod = tei.make_module(model, {})\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,dtype,a_min,a_max,err_msg\",\n    [\n        ((1, 4, 4, 4, 4), \"uint8\", 65, 78, \"dimensions=5, dimensions must be <= 4\"),\n        ((1, 8, 4, 2), \"int16\", 1, 254, \"dtype='int16', dtype must be either uint8, int8 or int32\"),\n        ((1, 8, 4, 2), \"uint8\", 254, 1, \"Relu has lower bound > upper bound\"),\n        ((2, 2, 2, 2), \"uint8\", 1, 63, \"batch size=2, batch size must = 1; \"),\n    ],\n)\ndef test_relu_failure(shape, dtype, a_min, a_max, err_msg):\n    \"\"\"Check Relu error messages.\"\"\"\n    model = _get_model(shape, dtype, a_min, a_max)\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_requantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration requantize tests\"\"\"\n\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, input_zp, input_sc, output_zp, output_sc, in_dtype, out_dtype):\n    a = relay.var(\"a\", shape=shape, dtype=in_dtype)\n    model = relay.qnn.op.requantize(\n        data=a,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=out_dtype,\n    )\n    return model\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"in_dtype\", [\"int8\", \"uint8\"])\n@pytest.mark.parametrize(\"out_dtype\", [\"int8\", \"uint8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 52, 52, 3)])\ndef test_requantize(in_dtype, out_dtype, shape):\n    \"\"\"Compare Requantize output with TVM.\"\"\"\n\n    np.random.seed(0)\n    low = 0 if in_dtype == \"uint8\" else -5\n    high = low + 10\n    input_zp = (high + low) / 2\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(low=low, high=high, size=shape, dtype=in_dtype)),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(\n            shape=shape,\n            input_zp=input_zp,\n            input_sc=0.002,\n            output_zp=10,\n            output_sc=0.008,\n            in_dtype=in_dtype,\n            out_dtype=out_dtype,\n        )\n        mod = tei.make_module(model, [])\n        x = tei.build_and_run(\n            mod,\n            inputs,\n            1,\n            {},\n            npu=npu,\n            additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n        )\n        outputs.append(x)\n\n    tei.verify(outputs, out_dtype, 1)\n\n\n@requires_ethosn\ndef test_requantize_mixed_precision_with_following_op():\n    \"\"\"\n    Checks a requantize operation that changes precision from uint8 to int8 with a\n    following add op.\n    \"\"\"\n\n    np.random.seed(0)\n    shape = (1, 4, 6, 8)\n    in_sc = 0.012566\n    in_zp = 131\n    out_sc = 0.012566\n    out_zp = 3\n    in_dtype = \"uint8\"\n    out_dtype = \"int8\"\n\n    def get_model():\n        a = relay.var(\"a\", shape=shape, dtype=in_dtype)\n        b = relay.var(\"b\", shape=shape, dtype=out_dtype)\n        req = relay.qnn.op.requantize(\n            data=a,\n            input_scale=relay.const(in_sc, \"float32\"),\n            input_zero_point=relay.const(in_zp, \"int32\"),\n            output_scale=relay.const(out_sc, \"float32\"),\n            output_zero_point=relay.const(out_zp, \"int32\"),\n            out_dtype=out_dtype,\n        )\n        req = relay.qnn.op.add(\n            req,\n            b,\n            lhs_scale=relay.const(out_sc, \"float32\"),\n            lhs_zero_point=relay.const(out_zp, \"int32\"),\n            rhs_scale=relay.const(out_sc, \"float32\"),\n            rhs_zero_point=relay.const(out_zp, \"int32\"),\n            output_scale=relay.const(out_sc, \"float32\"),\n            output_zero_point=relay.const(out_zp, \"int32\"),\n        )\n        return req\n\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                low=np.iinfo(in_dtype).min, high=np.iinfo(in_dtype).max, size=shape, dtype=in_dtype\n            )\n        ),\n        \"b\": tvm.nd.array(\n            np.random.randint(\n                low=np.iinfo(out_dtype).min,\n                high=np.iinfo(out_dtype).max,\n                size=shape,\n                dtype=out_dtype,\n            )\n        ),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = get_model()\n        mod = tei.make_module(model, {})\n        x = tei.build_and_run(\n            mod,\n            inputs,\n            1,\n            {},\n            npu=npu,\n            additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n        )\n        outputs.append(x)\n\n    tei.verify(outputs, out_dtype, 1)\n\n\n@requires_ethosn\ndef test_requantize_failure():\n    \"\"\"Check Requantize error messages.\"\"\"\n\n    input_sc = 0.8\n    output_sc = (input_sc / 128) - 0.0001\n    model = _get_model(\n        shape=(1, 52, 52, 3),\n        input_zp=0,\n        input_sc=input_sc,\n        output_zp=0,\n        output_sc=output_sc,\n        in_dtype=\"int8\",\n        out_dtype=\"int8\",\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_requantize\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, \"Output scale must be bigger than input scale / 128\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration reshape tests\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(input_shape, output_shape, dtype):\n    \"\"\"Return a model and any parameters it may have\"\"\"\n    a = relay.var(\"a\", shape=input_shape, dtype=dtype)\n    req = relay.reshape(a, output_shape)\n    return req, {}\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"input_shape, output_shape\",\n    [\n        ((1, 15, 4, 1), (1, 60)),\n        ((1, 15, 4, 1), (1, 30, 2)),\n        ((1, 15, 4, 1), (1, 4, 15, 1)),\n        ((1, 15, 4, 1), (1, 12, 5, 1)),\n        ((1, 15, 4, 1), (1, 0, 2, 2)),\n        ((1, 15, 4, 1), (1, -1, 2, 1)),\n        ((1, 15, 4, 1), (1, -2)),\n        ((1, 15, 4, 1), (1, -3, 1, 1)),\n        ((1, 15, 4, 1), (1, -4, 3, 5, 4)),\n        ((1, 15, 4, 1), (0, -1, -2)),\n        ((1, 15, 4, 1), (0, -1, -3, 1)),\n        ((1, 15, 4, 1), (1, -4, -1, 5, 4)),\n    ],\n)\ndef test_reshape(dtype, input_shape, output_shape):\n    \"\"\"Compare Reshape output with TVM.\"\"\"\n\n    np.random.seed(0)\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                low=np.iinfo(dtype).min,\n                high=np.iinfo(dtype).max + 1,\n                size=input_shape,\n                dtype=dtype,\n            )\n        )\n    }\n    outputs = []\n    for npu in [False, True]:\n        model, params = _get_model(input_shape, output_shape, dtype)\n        mod = tei.make_module(model, params)\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                params,\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"input_shape, output_shape\",\n    [\n        (\n            (1, 13, 13, 255),\n            (1, 13, 13, 3, 85),\n        ),\n    ],\n)\ndef test_reshape_failure(input_shape, output_shape):\n    \"\"\"Check Resize is not offloaded.\"\"\"\n\n    model, params = _get_model(input_shape, output_shape, \"int8\")\n    mod = tei.make_module(model, params)\n    tei.build(\n        mod,\n        params,\n        expected_host_ops=1,\n        npu_partitions=0,\n        additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_resize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration resize tests\"\"\"\n\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(\n    shape,\n    dtype,\n    size,\n    input_zp,\n    input_sc,\n    output_zp,\n    output_sc,\n    coordinate_transformation_mode,\n    rounding_method,\n):\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    resize = relay.image.resize2d(\n        data=x,\n        size=size,\n        layout=\"NHWC\",\n        method=\"nearest_neighbor\",\n        coordinate_transformation_mode=coordinate_transformation_mode,\n        rounding_method=rounding_method,\n    )\n    model = relay.qnn.op.requantize(\n        resize,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=dtype,\n    )\n    return model\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape, size, coordinate_transformation_mode, rounding_method\",\n    [\n        ((1, 4, 4, 2), (8, 8), \"half_pixel\", \"round_prefer_ceil\"),\n        ((1, 4, 4, 2), (7, 7), \"asymmetric\", \"floor\"),\n        ((1, 4, 8, 3), (8, 16), \"half_pixel\", \"round_prefer_ceil\"),\n        ((1, 4, 8, 3), (7, 15), \"asymmetric\", \"floor\"),\n    ],\n)\ndef test_resize(dtype, shape, size, coordinate_transformation_mode, rounding_method):\n    \"\"\"Compare Resize output with TVM.\"\"\"\n\n    np.random.seed(0)\n    zp_min = np.iinfo(dtype).min\n    zp_max = np.iinfo(dtype).max\n    inputs = {\n        \"x\": tvm.nd.array(np.random.randint(zp_min, high=zp_max + 1, size=shape, dtype=dtype)),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(\n            shape=shape,\n            dtype=dtype,\n            size=size,\n            input_zp=zp_min + 128,\n            input_sc=0.0784314,\n            output_zp=zp_min + 128,\n            output_sc=0.0784314,\n            coordinate_transformation_mode=coordinate_transformation_mode,\n            rounding_method=rounding_method,\n        )\n        mod = tei.make_module(model, {})\n        x = tei.build_and_run(mod, inputs, 1, {}, npu=npu)\n        outputs.append(x)\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"size,err_msg\",\n    [\n        (\n            (30, 20),\n            \"Requested height isn't supported\",\n        ),\n        (\n            (20, 30),\n            \"Requested width isn't supported\",\n        ),\n    ],\n)\ndef test_resize_failure(size, err_msg):\n    \"\"\"Check Resize error messages.\"\"\"\n    dtype = \"int8\"\n    zp_min = np.iinfo(dtype).min\n\n    model = _get_model(\n        shape=(1, 10, 10, 1),\n        dtype=dtype,\n        size=size,\n        input_zp=zp_min + 128,\n        input_sc=0.0784314,\n        output_zp=zp_min + 128,\n        output_sc=0.0784314,\n        coordinate_transformation_mode=\"half_pixel\",\n        rounding_method=\"round_prefer_ceil\",\n    )\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_resize\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_sigmoid.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N integration sigmoid tests\"\"\"\n\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype):\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    dequantize = relay.qnn.op.dequantize(\n        a,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n    )\n    sigmoid = relay.sigmoid(dequantize)\n    model = relay.qnn.op.quantize(\n        sigmoid,\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=dtype,\n    )\n    return model\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape\",\n    [\n        (1, 16, 16, 16),\n        (1, 8, 8),\n    ],\n)\ndef test_sigmoid(dtype, shape):\n    \"\"\"Compare Sigmoid output with TVM.\"\"\"\n    np.random.seed(0)\n\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        ),\n    }\n    outputs = []\n    for npu in [False, True]:\n        for _ in range(1, 2):\n            if dtype == \"uint8\":\n                input_zp = 0\n                output_zp = 0\n            else:\n                input_zp = 127\n                output_zp = -128\n            model = _get_model(shape, input_zp, 0.02, output_zp, 1.0 / 256.0, dtype)\n            mod = tei.make_module(model, [])\n            outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu))\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,input_zp,input_sc,output_zp,output_sc,err_msg\",\n    [\n        ((2, 4, 4, 4), 64, 0.2, 0, 1 / 256, \"batch size=2, batch size must = 1\"),\n        (\n            (1, 4, 4, 4),\n            64,\n            0.2,\n            3,\n            1,\n            \"output quantization params=(3, 1), must = (0, 1/256)\",\n        ),\n    ],\n)\ndef test_sigmoid_failure(shape, input_zp, input_sc, output_zp, output_sc, err_msg):\n    \"\"\"Check Sigmoid error messages.\"\"\"\n\n    dtype = \"uint8\"\n\n    model = _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype)\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_sigmoid\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_split.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Split tests for Arm(R) Ethos(TM)-N\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\n\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, dtype, splits, axis):\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    split = relay.op.split(a, indices_or_sections=splits, axis=axis)\n    return split.astuple()\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape,splits,axis\",\n    [\n        ((1, 16, 16, 32), (2, 7, 10), 2),\n        ((1, 12, 8, 16), 3, 1),\n    ],\n)\ndef test_split(dtype, shape, splits, axis):\n    \"\"\"Compare Split output with TVM.\"\"\"\n    np.random.seed(0)\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        )\n    }\n    for npu in [False, True]:\n        model = _get_model(shape, dtype, splits, axis)\n        mod = tei.make_module(model, {})\n        output_count = splits if isinstance(splits, int) else len(splits) + 1\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                output_count,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n        tei.verify(outputs, dtype, 0)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\n    \"shape,dtype,splits,axis,err_msg\",\n    [\n        ((1, 4, 4, 4, 4), \"uint8\", 4, 2, \"dimensions=5, dimensions must be <= 4;\"),\n        ((1, 4, 4, 4), \"int16\", 4, 2, \"dtype='int16', dtype must be either uint8, int8 or int32;\"),\n        ((2, 4, 4, 4), \"uint8\", 4, 2, \"batch size=2, batch size must = 1;\"),\n        ((1, 4, 4, 4), \"uint8\", 1, 0, \"Split cannot be performed along batch axis (axis 0);\"),\n        (\n            (1, 4, 4, 4),\n            \"uint8\",\n            4,\n            3,\n            \"Split along the channels dimension (axis 3) requires all output sizes \"\n            \"(specified in splitInfo.m_Sizes) to be multiples of 16;\",\n        ),\n    ],\n)\ndef test_split_failure(shape, dtype, splits, axis, err_msg):\n    \"\"\"Check Split error messages.\"\"\"\n    model = _get_model(shape, dtype, splits, axis)\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_tanh.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N NPU integration tanh tests\"\"\"\n\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom . import infrastructure as tei\n\n\ndef _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype):\n    a = relay.var(\"a\", shape=shape, dtype=dtype)\n    dequantize = relay.qnn.op.dequantize(\n        a,\n        input_scale=relay.const(input_sc, \"float32\"),\n        input_zero_point=relay.const(input_zp, \"int32\"),\n    )\n    tanh = relay.tanh(dequantize)\n    model = relay.qnn.op.quantize(\n        tanh,\n        output_scale=relay.const(output_sc, \"float32\"),\n        output_zero_point=relay.const(output_zp, \"int32\"),\n        out_dtype=dtype,\n    )\n    return model\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\"shape\", [(1, 52, 52, 3)])\ndef test_tanh(dtype, shape):\n    \"\"\"Compare Tanh output with TVM.\"\"\"\n\n    zp_min = np.iinfo(dtype).min\n    zp_max = np.iinfo(dtype).max\n\n    np.random.seed(0)\n    inputs = {\n        \"a\": tvm.nd.array(np.random.randint(zp_min, high=zp_max, size=shape, dtype=dtype)),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = _get_model(shape, zp_min + 120, 0.0250629, zp_min + 128, 0.0078125, dtype)\n        mod = tei.make_module(model, [])\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape, input_zp, input_sc, output_zp, output_sc, err_msg\",\n    [\n        (\n            (1, 16, 16, 16),\n            120,\n            0.0250629,\n            64,\n            0.0078125,\n            \"output quantization params=(64, 0.0078125), must = ({test_zp}, 1/256);\",\n        )\n    ],\n)\ndef test_tanh_failure(shape, input_zp, input_sc, output_zp, output_sc, err_msg, dtype):\n    \"\"\"Check Tanh error messages.\"\"\"\n\n    test_zp = 0 if dtype == \"int8\" else 128\n    model = _get_model(shape, input_zp, input_sc, output_zp, output_sc, dtype)\n    model = tei.make_ethosn_composite(model, \"ethos-n.qnn_tanh\")\n    mod = tei.make_ethosn_partition(model)\n    tei.test_error(mod, {}, err_msg.format(test_zp=test_zp))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosn/test_topologies.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Arm(R) Ethos(TM)-N tests for complex network topologies.\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_ethosn\nfrom tvm.relay.op.contrib.ethosn import Available, ethosn_available\n\nfrom . import infrastructure as tei\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_split_add_concat(dtype):\n    \"\"\"Test a model with split, add and contatenate.\"\"\"\n\n    def get_model(input_shape, dtype, var_names):\n        \"\"\"Return a model\"\"\"\n\n        a = relay.var(next(var_names), shape=input_shape, dtype=dtype)\n        split_scale = relay.const(0.25, \"float32\")\n        split_zp = relay.const(100, \"int32\")\n        add_scale = relay.const(0.75, \"float32\")\n        add_zp = relay.const(120, \"int32\")\n        axis = 2\n\n        split = relay.split(a, indices_or_sections=4, axis=axis)\n        b = relay.qnn.op.add(\n            split[0],\n            split[1],\n            lhs_scale=split_scale,\n            lhs_zero_point=split_zp,\n            rhs_scale=split_scale,\n            rhs_zero_point=split_zp,\n            output_scale=add_scale,\n            output_zero_point=add_zp,\n        )\n        conc = relay.qnn.op.concatenate(\n            [b, split[2], split[3]],\n            input_scales=(add_scale, split_scale, split_scale),\n            input_zero_points=(add_zp, split_zp, split_zp),\n            output_scale=add_scale,\n            output_zero_point=add_zp,\n            axis=axis,\n        )\n        return conc\n\n    np.random.seed(0)\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 16, 16, 4), dtype=dtype\n            )\n        ),\n    }\n\n    outputs = []\n    for npu in [False, True]:\n        model = get_model(inputs[\"a\"].shape, dtype, iter(inputs))\n        mod = tei.make_module(model, [])\n\n        expected_host_ops = 0\n        npu_partitions = 1\n\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                1,\n                {},\n                npu=npu,\n                expected_host_ops=expected_host_ops,\n                npu_partitions=npu_partitions,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    if outputs:\n        tei.verify(outputs, dtype, 2)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_multiple_command_streams(dtype):\n    \"\"\"Check that multiple Ethos-N partitions are correctly handled.\n\n    If there's more than one Ethos-N graph partition, more than one command\n    stream will be created. This should be handled correctly by both the\n    Ethos-N codegen and Ethos-N runtime module. This test checks against a\n    simple graph which creates two Ethos-N partitions and checks the result\n    against an 'all-CPU' run through TVM.\n    \"\"\"\n\n    def get_model(dtype):\n        \"\"\"\n        max_pool2d\n             |\n            abs\n             |\n        max_pool2d\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 4, 4, 4), dtype=dtype)\n        out = relay.nn.max_pool2d(x, (2, 2), (2, 2), layout=\"NHWC\")  # supported\n        out = relay.op.abs(out)  # not supported\n        out = relay.nn.max_pool2d(out, (2, 2), (2, 2), layout=\"NHWC\")  # supported\n        return out\n\n    np.random.seed(0)\n    inputs = {\n        \"x\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 4, 4, 4), dtype=dtype\n            )\n        )\n    }\n    model = get_model(dtype)\n    mod = tei.make_module(model, {})\n\n    # Mock inference is only supported when the whole graph is offloaded to the NPU\n    if ethosn_available() == Available.SW_ONLY:\n        tei.build(mod, {}, npu=True, expected_host_ops=1, npu_partitions=2)\n    else:\n        tei.build_and_run(mod, inputs, 1, {}, npu=True, expected_host_ops=1, npu_partitions=2)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_output_order(dtype):\n    \"\"\"Test the output order.\"\"\"\n\n    def get_model(input_shape, dtype, var_names):\n        \"\"\"Return a model\"\"\"\n\n        min_value = np.iinfo(dtype).min\n        max_value = np.iinfo(dtype).max\n        a = relay.var(next(var_names), shape=input_shape, dtype=dtype)\n\n        op_z = relay.op.clip(a, min_value, max_value)\n        op_b = relay.op.clip(op_z, min_value, min_value + 15)\n        op_c = relay.op.clip(op_z, min_value + 16, min_value + 31)\n        op_d = relay.op.clip(op_z, min_value + 32, min_value + 47)\n        op_e = relay.op.clip(op_z, min_value + 48, min_value + 63)\n        op_f = relay.op.clip(op_z, min_value + 64, min_value + 79)\n        op_g = relay.op.clip(op_z, min_value + 80, min_value + 95)\n        op_h = relay.op.clip(op_z, min_value + 96, min_value + 111)\n        op_i = relay.op.clip(op_z, min_value + 112, max_value)\n        return relay.Tuple((op_d, op_c, op_e, op_f, op_i, op_b, op_h, op_g))\n\n    np.random.seed(0)\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 16, 16, 4), dtype=dtype\n            )\n        ),\n    }\n\n    outputs = []\n    for npu in [False, True]:\n        model = get_model(inputs[\"a\"].shape, dtype, iter(inputs))\n        mod = tei.make_module(model, [])\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                8,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_output_order_different_sizes(dtype):\n    \"\"\"\n    Test the output order when there are multiple outputs of different sizes.\n    \"\"\"\n\n    np.random.seed(0)\n    input_name = \"a\"\n    input_shape = (1, 8, 8, 4)\n    dtype_min = np.iinfo(dtype).min\n    dtype_max = np.iinfo(dtype).max\n\n    def get_model():\n        var = relay.var(input_name, shape=input_shape, dtype=dtype)\n        clip = relay.op.clip(var, dtype_min, dtype_max)\n        max_pool = relay.nn.max_pool2d(clip, (2, 2), (2, 2), ceil_mode=True, layout=\"NHWC\")\n        mean = relay.op.cast(clip, \"int32\")\n        mean = relay.mean(mean, axis=[1, 2], keepdims=True)\n        mean = relay.qnn.op.requantize(\n            mean,\n            input_scale=relay.const(0.0784314, \"float32\"),\n            input_zero_point=relay.const(dtype_min + 128, \"int32\"),\n            output_scale=relay.const(0.0784314, \"float32\"),\n            output_zero_point=relay.const(dtype_min + 128, \"int32\"),\n            out_dtype=dtype,\n        )\n\n        return relay.Tuple((mean, max_pool, clip))\n\n    inputs = {\n        input_name: tvm.nd.array(\n            np.random.randint(dtype_min, dtype_max + 1, size=input_shape, dtype=dtype)\n        ),\n    }\n\n    outputs = []\n    for npu in [False, True]:\n        model = get_model()\n        mod = tei.make_module(model, [])\n        outputs.append(\n            tei.build_and_run(mod, inputs, 3, {}, npu=npu, expected_host_ops=0, npu_partitions=1)\n        )\n\n    tei.verify(outputs, dtype, 1)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\n@pytest.mark.parametrize(\n    \"shape,splits,axis\",\n    [\n        ((1, 16, 16, 32), (2, 7, 10), 2),\n    ],\n)\ndef test_split_with_asym_concats(dtype, shape, splits, axis):\n    \"\"\"Test a model with split and contatenates.\"\"\"\n    np.random.seed(0)\n\n    def get_model(shape, dtype, splits, axis):\n        a = relay.var(\"a\", shape=shape, dtype=dtype)\n        split = relay.op.split(a, indices_or_sections=splits, axis=axis)\n        zeroi = relay.const(1, \"int32\")\n        zerof = relay.const(0.5, \"float32\")\n        con1 = relay.qnn.op.concatenate(\n            [split[0], split[1]],\n            input_scales=[zerof] * 2,\n            input_zero_points=[zeroi] * 2,\n            output_scale=zerof,\n            output_zero_point=zeroi,\n            axis=axis,\n        )\n        con2 = relay.qnn.op.concatenate(\n            [split[2], split[3]],\n            input_scales=[zerof] * 2,\n            input_zero_points=[zeroi] * 2,\n            output_scale=zerof,\n            output_zero_point=zeroi,\n            axis=axis,\n        )\n        return relay.Tuple((con2, con1))\n\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        )\n    }\n    for npu in [False, True]:\n        model = get_model(shape, dtype, splits, axis)\n        mod = tei.make_module(model, {})\n\n        expected_host_ops = 0\n        npu_partitions = 1\n\n        # Mock inference is only supported when the whole graph is offloaded to the NPU\n        if ethosn_available() == Available.SW_ONLY:\n            tei.build(\n                mod,\n                {},\n                npu=npu,\n                expected_host_ops=expected_host_ops,\n                npu_partitions=npu_partitions,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        else:\n            outputs.append(\n                tei.build_and_run(\n                    mod,\n                    inputs,\n                    2,\n                    {},\n                    npu=npu,\n                    expected_host_ops=expected_host_ops,\n                    npu_partitions=npu_partitions,\n                    additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n                )\n            )\n\n    if outputs:\n        tei.verify(outputs, dtype, 0)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_output_tuple_propagation(dtype):\n    \"\"\"This tests the case where the output tuple must be inferred\n    as having dummy tensor information.\"\"\"\n\n    def get_model(dtype):\n        a = relay.var(\"a\", shape=(1, 4, 4, 16), dtype=dtype)\n        split = relay.op.split(a, indices_or_sections=4, axis=2)\n        return relay.Tuple((split[0], split[1], split[2], split[3]))\n\n    np.random.seed(0)\n    outputs = []\n    inputs = {\n        \"a\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 4, 4, 16), dtype=dtype\n            )\n        )\n    }\n    for npu in [False, True]:\n        model = get_model(dtype)\n        mod = tei.make_module(model, {})\n        outputs.append(\n            tei.build_and_run(\n                mod,\n                inputs,\n                4,\n                {},\n                npu=npu,\n                additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n            )\n        )\n\n    tei.verify(outputs, dtype, 0)\n\n\n@requires_ethosn\n@pytest.mark.parametrize(\"dtype\", [\"uint8\", \"int8\"])\ndef test_input_tuples(dtype):\n    \"\"\"Test a model with a tuple as input.\"\"\"\n\n    def get_model(shapes, dtype, axis):\n        tup = []\n        for i, shape in enumerate(shapes):\n            a = relay.var(\"in\" + str(i), shape=shape, dtype=dtype)\n            tup.append(a)\n\n        zeroi = relay.const(1, \"int32\")\n        zerof = relay.const(0.5, \"float32\")\n        con = relay.qnn.op.concatenate(\n            tup,\n            input_scales=[zerof] * len(shapes),\n            input_zero_points=[zeroi] * len(shapes),\n            output_scale=zerof,\n            output_zero_point=zeroi,\n            axis=axis,\n        )\n\n        return con\n\n    np.random.seed(0)\n    inputs = {\n        \"in0\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 4), dtype=dtype\n            )\n        ),\n        \"in1\": tvm.nd.array(\n            np.random.randint(\n                np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=(1, 6), dtype=dtype\n            )\n        ),\n    }\n    outputs = []\n    for npu in [False, True]:\n        model = get_model([(1, 4), (1, 6)], dtype, 1)\n        if not npu:\n            mod = tei.make_module(model, {})\n        else:\n            mod = tei.make_ethosn_partition(model)\n        lib = tei.build(\n            mod,\n            {},\n            npu=False,\n            additional_config_args={\"inline_non_compute_intensive_partitions\": False},\n        )\n        outputs.append(tei.run(lib, inputs, 1, npu=npu))\n\n    tei.verify(outputs, dtype, 0)\n\n\n@requires_ethosn\ndef test_inline_non_compute_intensive_operations():\n    \"\"\"Tests the case when a subgraph is unpartitioned.\"\"\"\n    np.random.seed(0)\n    dtype = \"int8\"\n    shape = (1, 2, 2, 4)\n\n    inp = relay.var(\"x\", shape=shape, dtype=dtype)\n    reshape = relay.reshape(inp, newshape=(1, 1, 4, 4))\n\n    inputs = {\n        \"x\": tvm.nd.array(\n            np.random.randint(np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype)\n        ),\n    }\n    outputs = []\n\n    for npu in [False, True]:\n        mod = tei.make_module(reshape, {})\n        outputs.append(\n            tei.build_and_run(mod, inputs, 1, {}, npu=npu, expected_host_ops=1, npu_partitions=0)\n        )\n\n    tei.verify(outputs, dtype, 0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test infrastructure for Arm(R) Ethos(TM)-U NPU related tests\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test infrastructure for the NPU cascader\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nethosu_enabled = True\ntry:\n    import ethosu.vela\nexcept ImportError:\n    ethosu_enabled = False\n\nimport tvm.contrib.ethosu.cascader as cs\n\n\n@pytest.fixture\ndef FLASH():\n    return cs.MemoryRegion(\n        name=\"FLASH\",\n        size=10**7,\n        read_bandwidth=4,\n        write_bandwidth=4,\n        read_latency=0,\n        write_latency=0,\n        burst_length=1,\n    )\n\n\n@pytest.fixture\ndef DRAM():\n    return cs.MemoryRegion(\n        name=\"DRAM\",\n        size=10**9,\n        read_bandwidth=8,\n        write_bandwidth=8,\n        read_latency=0,\n        write_latency=0,\n        burst_length=1,\n    )\n\n\n@pytest.fixture\ndef SRAM():\n    return cs.MemoryRegion(\n        name=\"SRAM\",\n        size=10**6,\n        read_bandwidth=16,\n        write_bandwidth=16,\n        read_latency=0,\n        write_latency=0,\n        burst_length=1,\n    )\n\n\nif ethosu_enabled:\n    import tvm\n    from tvm import relay\n    from tvm.relay.testing import run_opt_pass\n\n    from .infra import create_te_graph\n    from ..infra import (\n        make_ethosu_conv2d,\n        make_ethosu_depthwise_conv2d,\n        make_ethosu_binary_elementwise,\n    )\n\n    def make_TwoConv2DTE():\n        def _get_func():\n            ifm = relay.var(\"ifm\", shape=(1, 12, 12, 8), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm,\n                ifm_channels=8,\n                ofm_channels=32,\n                kernel_shape=(1, 1),\n                padding=(0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n                activation=\"NONE\",\n                ifm_layout=\"NHWC\",\n                ofm_layout=\"NHCWB16\",\n            )\n            conv2 = make_ethosu_conv2d(\n                ifm=conv1,\n                ifm_channels=32,\n                ofm_channels=16,\n                kernel_shape=(3, 3),\n                padding=(1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n                activation=\"NONE\",\n                ifm_layout=\"NHCWB16\",\n                ofm_layout=\"NHWC\",\n            )\n            func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def TwoConv2DTE():\n        return make_TwoConv2DTE()\n\n    @pytest.fixture\n    def TwoConv2DGraph():\n        _, te_graph, const_dict = make_TwoConv2DTE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    def make_TwoConv2DWithSliceTE():\n        def _get_func():\n            ifm = relay.var(\"ifm\", shape=(1, 12, 12, 8), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm,\n                ifm_channels=8,\n                ofm_channels=64,\n                kernel_shape=(1, 1),\n                padding=(0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n                activation=\"NONE\",\n                ifm_layout=\"NHWC\",\n                ofm_layout=\"NHWC\",\n            )\n            strided_slice = relay.strided_slice(conv1, [0, 0, 0, 0], [1, 6, 6, 128])\n            conv2 = make_ethosu_conv2d(\n                ifm=strided_slice,\n                ifm_channels=64,\n                ofm_channels=16,\n                kernel_shape=(3, 3),\n                padding=(1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n                activation=\"NONE\",\n                ifm_layout=\"NHWC\",\n                ofm_layout=\"NHCWB16\",\n            )\n            func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def TwoConv2DWithSliceTE():\n        return make_TwoConv2DWithSliceTE()\n\n    @pytest.fixture\n    def TwoConv2DWithSliceGraph():\n        _, te_graph, const_dict = make_TwoConv2DWithSliceTE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    def make_MobileNetv2DiamondTE():\n        def _get_func():\n            ifm = relay.var(\"ifm\", shape=(1, 56, 56, 96), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm,\n                ifm_channels=96,\n                ofm_channels=24,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv2 = make_ethosu_conv2d(\n                ifm=conv1,\n                ifm_channels=24,\n                ofm_channels=144,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth1 = make_ethosu_depthwise_conv2d(\n                ifm=conv2,\n                channels=144,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv3 = make_ethosu_conv2d(\n                ifm=depth1,\n                ifm_channels=144,\n                ofm_channels=24,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            add1 = make_ethosu_binary_elementwise(\n                ifm=conv1,\n                ifm2=conv3,\n                ifm_channels=24,\n                ifm2_channels=24,\n                operator_type=\"ADD\",\n                ofm_dtype=\"int8\",\n            )\n            func = relay.Function(relay.analysis.free_vars(add1), add1)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def MobileNetv2DiamondTE():\n        return make_MobileNetv2DiamondTE()\n\n    @pytest.fixture\n    def MobileNetv2DiamondGraph():\n        _, te_graph, const_dict = make_MobileNetv2DiamondTE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    def make_BinaryTE():\n        def _get_func():\n            ifm_a = relay.var(\"ifm_a\", shape=(1, 8, 8, 8), dtype=\"int8\")\n            ifm_b = relay.var(\"ifm_b\", shape=(1, 8, 8, 8), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm_a,\n                ifm_channels=8,\n                ofm_channels=8,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv2 = make_ethosu_conv2d(\n                ifm=ifm_b,\n                ifm_channels=8,\n                ofm_channels=8,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            add1 = make_ethosu_binary_elementwise(\n                ifm=conv1,\n                ifm2=conv2,\n                ifm_channels=8,\n                ifm2_channels=8,\n                operator_type=\"ADD\",\n                ofm_dtype=\"int8\",\n            )\n            func = relay.Function(relay.analysis.free_vars(add1), add1)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def BinaryTE():\n        return make_BinaryTE()\n\n    @pytest.fixture\n    def BinaryGraph():\n        _, te_graph, const_dict = make_BinaryTE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    def make_MobileNetv1StartTE():\n        def _get_func():\n            ifm = relay.var(\"ifm\", shape=(1, 224, 224, 3), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm,\n                ifm_channels=3,\n                ofm_channels=32,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            depth1 = make_ethosu_depthwise_conv2d(\n                ifm=conv1,\n                channels=32,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv2 = make_ethosu_conv2d(\n                ifm=depth1,\n                ifm_channels=32,\n                ofm_channels=64,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth2 = make_ethosu_depthwise_conv2d(\n                ifm=conv2,\n                channels=64,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            conv3 = make_ethosu_conv2d(\n                ifm=depth2,\n                ifm_channels=64,\n                ofm_channels=128,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth3 = make_ethosu_depthwise_conv2d(\n                ifm=conv3,\n                channels=128,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv4 = make_ethosu_conv2d(\n                ifm=depth3,\n                ifm_channels=128,\n                ofm_channels=128,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth4 = make_ethosu_depthwise_conv2d(\n                ifm=conv4,\n                channels=128,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            func = relay.Function(relay.analysis.free_vars(depth4), depth4)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def MobileNetv1StartTE():\n        return make_MobileNetv1StartTE()\n\n    @pytest.fixture\n    def MobileNetv1StartGraph():\n        _, te_graph, const_dict = make_MobileNetv1StartTE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    def make_MobileNetv1TE():\n        def _get_func():\n            ifm = relay.var(\"ifm\", shape=(1, 224, 224, 3), dtype=\"int8\")\n            conv1 = make_ethosu_conv2d(\n                ifm=ifm,\n                ifm_channels=3,\n                ofm_channels=32,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            depth1 = make_ethosu_depthwise_conv2d(\n                ifm=conv1,\n                channels=32,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv2 = make_ethosu_conv2d(\n                ifm=depth1,\n                ifm_channels=32,\n                ofm_channels=64,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth2 = make_ethosu_depthwise_conv2d(\n                ifm=conv2,\n                channels=64,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            conv3 = make_ethosu_conv2d(\n                ifm=depth2,\n                ifm_channels=64,\n                ofm_channels=128,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth3 = make_ethosu_depthwise_conv2d(\n                ifm=conv3,\n                channels=128,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv4 = make_ethosu_conv2d(\n                ifm=depth3,\n                ifm_channels=128,\n                ofm_channels=128,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth4 = make_ethosu_depthwise_conv2d(\n                ifm=conv4,\n                channels=128,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            conv5 = make_ethosu_conv2d(\n                ifm=depth4,\n                ifm_channels=128,\n                ofm_channels=256,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth5 = make_ethosu_depthwise_conv2d(\n                ifm=conv5,\n                channels=256,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv6 = make_ethosu_conv2d(\n                ifm=depth5,\n                ifm_channels=256,\n                ofm_channels=256,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth6 = make_ethosu_depthwise_conv2d(\n                ifm=conv6,\n                channels=256,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            conv7 = make_ethosu_conv2d(\n                ifm=depth6,\n                ifm_channels=256,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth7 = make_ethosu_depthwise_conv2d(\n                ifm=conv7,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv8 = make_ethosu_conv2d(\n                ifm=depth7,\n                ifm_channels=512,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth8 = make_ethosu_depthwise_conv2d(\n                ifm=conv8,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv9 = make_ethosu_conv2d(\n                ifm=depth8,\n                ifm_channels=512,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth9 = make_ethosu_depthwise_conv2d(\n                ifm=conv9,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv10 = make_ethosu_conv2d(\n                ifm=depth9,\n                ifm_channels=512,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth10 = make_ethosu_depthwise_conv2d(\n                ifm=conv10,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv11 = make_ethosu_conv2d(\n                ifm=depth10,\n                ifm_channels=512,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth11 = make_ethosu_depthwise_conv2d(\n                ifm=conv11,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv12 = make_ethosu_conv2d(\n                ifm=depth11,\n                ifm_channels=512,\n                ofm_channels=512,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth12 = make_ethosu_depthwise_conv2d(\n                ifm=conv12,\n                channels=512,\n                kernel_shape=(3, 3),\n                padding=(0, 0, 1, 1),\n                strides=(2, 2),\n                dilation=(1, 1),\n            )\n            conv13 = make_ethosu_conv2d(\n                ifm=depth12,\n                ifm_channels=512,\n                ofm_channels=1024,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            depth13 = make_ethosu_depthwise_conv2d(\n                ifm=conv13,\n                channels=1024,\n                kernel_shape=(3, 3),\n                padding=(1, 1, 1, 1),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            conv14 = make_ethosu_conv2d(\n                ifm=depth13,\n                ifm_channels=1024,\n                ofm_channels=1024,\n                kernel_shape=(1, 1),\n                padding=(0, 0, 0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n            )\n            func = relay.Function(relay.analysis.free_vars(conv14), conv14)\n            func = run_opt_pass(func, relay.transform.InferType())\n            return func\n\n        func = _get_func()\n        te_graph, const_dict = create_te_graph(func)\n        sch = tvm.te.create_schedule([t.op for t in te_graph.outputs])\n        return sch, te_graph, const_dict\n\n    @pytest.fixture\n    def MobileNetv1TE():\n        return make_MobileNetv1TE()\n\n    @pytest.fixture\n    def MobileNetv1Graph():\n        _, te_graph, const_dict = make_MobileNetv1TE()\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n        return cs.create_cascader_graph(te_graph, const_dict, device_config)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/infra.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nethosu_enabled = True\ntry:\n    import ethosu.vela\nexcept ImportError:\n    ethosu_enabled = False\n\nimport tvm\nfrom tvm import relay\nimport tvm.contrib.ethosu.cascader as cs\nimport numpy as np\n\n\ndef make_options(\n    cascade_region: cs.MemoryRegion,\n    max_proposals: int = 1,\n    stripe_factors: int = 1,\n    max_plan_size: int = 1,\n    max_open_plans: int = 8,\n    max_closed_plans: int = 32,\n    always_copy_size: int = 1024,\n    disable_pareto_plans: bool = False,\n    disable_pareto_proposals: bool = False,\n    enable_striping: bool = True,\n):\n    return cs.CascaderOptions(\n        cascade_region=cascade_region,\n        max_proposals=max_proposals,\n        stripe_factors=stripe_factors,\n        max_plan_size=max_plan_size,\n        max_open_plans=max_open_plans,\n        max_closed_plans=max_closed_plans,\n        always_copy_size=always_copy_size,\n        disable_pareto_plans=disable_pareto_plans,\n        disable_pareto_proposals=disable_pareto_proposals,\n        enable_striping=enable_striping,\n    )\n\n\ndef make_simple_home_map(graph, var_region, const_region):\n    home_map = {}\n    for tensor in graph.tensor_order:\n        if tensor.is_constant:\n            home_map[tensor] = [const_region]\n        else:\n            home_map[tensor] = [var_region]\n\n    return home_map\n\n\nif ethosu_enabled:\n    from tvm.relay.backend.contrib.ethosu.tir.compiler import extract_constants, lower_to_te\n    from tvm.relay.backend.contrib.ethosu.te.common import get_layout_transform_matrices\n\n    def create_te_graph(func):\n        func, consts = extract_constants(func)\n        mod = tvm.IRModule.from_expr(func)\n        func = relay.transform.InferType()(mod)[\"main\"]\n        te_graph = lower_to_te(func)\n        return te_graph, consts\n\n    def make_matrices(\n        op_type,\n        kernel,\n        stride,\n        padding,\n        ifm_layout,\n        ofm_layout,\n        dilation=(1, 1),\n        ifm_channels=1,\n        ofm_channels=1,\n    ):\n        kernel_h, kernel_w = kernel\n        stride_h, stride_w = stride\n        dilation_h, dilation_w = dilation\n        dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n        dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n\n        nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(ofm_channels)\n\n        if op_type == \"ethosu_conv2d\":\n            ifm_matrix = [\n                [1, 0, 0, 0, 0],\n                [0, stride_h, 0, 0, (dilated_kernel_h - stride_h)],\n                [0, 0, stride_w, 0, (dilated_kernel_w - stride_w)],\n                [0, 0, 0, 0, ifm_channels],\n                [0, 0, 0, 0, 1],\n            ]\n            weight_matrix = [\n                [0, 0, 0, 1, 0],\n                [0, 0, 0, 0, kernel_h],\n                [0, 0, 0, 0, kernel_w],\n                [0, 0, 0, 0, ifm_channels],\n                [0, 0, 0, 0, 1],\n            ]\n        elif op_type == \"ethosu_depthwise_conv2d\":\n            ifm_matrix = [\n                [1, 0, 0, 0, 0],\n                [0, stride_h, 0, 0, (dilated_kernel_h - stride_h)],\n                [0, 0, stride_w, 0, (dilated_kernel_w - stride_w)],\n                [0, 0, 0, 1, 0],\n                [0, 0, 0, 0, 1],\n            ]\n            weight_matrix = [\n                [0, 0, 0, 1, 0],\n                [0, 0, 0, 0, kernel_h],\n                [0, 0, 0, 0, kernel_w],\n                [0, 0, 0, 0, 1],\n                [0, 0, 0, 0, 1],\n            ]\n        elif op_type == \"ethosu_pooling\":\n            ifm_matrix = [\n                [1, 0, 0, 0, 0],\n                [0, stride_h, 0, 0, (dilated_kernel_h - stride_h)],\n                [0, 0, stride_w, 0, (dilated_kernel_w - stride_w)],\n                [0, 0, 0, 1, 0],\n                [0, 0, 0, 0, 1],\n            ]\n            weight_matrix = [\n                [0, 0, 0, 0, 0],\n                [0, 0, 0, 0, 0],\n                [0, 0, 0, 0, 0],\n                [0, 0, 0, 0, 0],\n                [0, 0, 0, 0, 0],\n            ]\n        scale_bias_matrix = [\n            [0, 0, 0, 1, 0],\n            [0, 0, 0, 0, 10],\n            [0, 0, 0, 0, 1],\n        ]\n        if ofm_layout == \"NHCWB16\":\n            ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n            weight_matrix = np.matmul(weight_matrix, nhcwb16_to_nhwc).tolist()\n            scale_bias_matrix = np.matmul(scale_bias_matrix, nhcwb16_to_nhwc).tolist()\n        if ifm_layout == \"NHCWB16\":\n            ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n\n        ifm_offset = (\n            [0, -padding[0], -padding[1], 0]\n            if ifm_layout == \"NHWC\"\n            else [0, -padding[0], 0, -padding[1], 0]\n        )\n        weight_offset = [0, 0, 0, 0]\n        scale_bias_offset = [0, 0]\n        return (\n            ifm_matrix,\n            ifm_offset,\n            weight_matrix,\n            weight_offset,\n            scale_bias_matrix,\n            scale_bias_offset,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_calculate_memory_pressure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position\n\n\"\"\"\nTest memory pressure is calculated correctly from used memory annotations.\n\"\"\"\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.codegen import _calculate_memory_pressure\nfrom tvm.contrib.ethosu.cascader.scheduler import extract_memory_info\nfrom tvm import WorkspacePoolInfo, PoolInfoProperties\n\n\ndef _npu_and_non_npu_functions():\n    mod = tvm.IRModule({})\n\n    # NPU function 1\n    x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    max_pool = relay.nn.max_pool2d(x)\n    composite_func = relay.Function([x], max_pool)\n    composite_func = composite_func.with_attr(\"Composite\", \"ethos-u.pooling\")\n    inp = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [32])\n    npu_compiler_func1 = compiler_func.with_attr(\"Compiler\", \"ethos-u\")\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = npu_compiler_func1\n\n    # Non-NPU function\n    x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    max_pool = relay.abs(x)\n    composite_func = relay.Function([x], max_pool)\n    composite_func = composite_func.with_attr(\"Composite\", \"foo.unary_elementwise\")\n    inp = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [32])\n    non_npu_compiler_func = compiler_func.with_attr(\"Compiler\", \"foo\")\n    g2 = relay.GlobalVar(\"g2\")\n    mod[g2] = non_npu_compiler_func\n\n    # NPU function 2\n    x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    max_pool = relay.abs(x)\n    composite_func = relay.Function([x], max_pool)\n    composite_func = composite_func.with_attr(\"Composite\", \"ethos-u.unary_elementwise\")\n    inp = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [32])\n    npu_compiler_func2 = compiler_func.with_attr(\"Compiler\", \"ethos-u\")\n    g3 = relay.GlobalVar(\"g3\")\n    mod[g3] = npu_compiler_func2\n\n    # Main\n    inp = relay.var(\"main_input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call1 = relay.Call(g1, [inp])\n    call2 = relay.Call(g2, [call1])\n    call3 = relay.Call(g3, [call2])\n    main_func = relay.Function([inp], call3)\n    main_func = main_func.with_attr(\"io_used_memory\", 32)\n    mod[\"main\"] = main_func\n    return mod\n\n\ndef _parallel_npu_functions():\n    mod = tvm.IRModule({})\n\n    # NPU function 1\n    x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    max_pool = relay.nn.max_pool2d(x)\n    composite_func = relay.Function([x], max_pool)\n    composite_func = composite_func.with_attr(\"Composite\", \"ethos-u.pooling\")\n    inp = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [32])\n    npu_compiler_func1 = compiler_func.with_attr(\"Compiler\", \"ethos-u\")\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = npu_compiler_func1\n\n    # NPU function 2\n    x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    abs_op = relay.abs(x)\n    composite_func = relay.Function([x], abs_op)\n    composite_func = composite_func.with_attr(\"Composite\", \"ethos-u.unary_elementwise\")\n    inp = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [32 + 16])\n    npu_compiler_func2 = compiler_func.with_attr(\"Compiler\", \"ethos-u\")\n    g2 = relay.GlobalVar(\"g2\")\n    mod[g2] = npu_compiler_func2\n\n    # Main\n    inp = relay.var(\"main_input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call1 = relay.Call(g1, [inp])\n    call2 = relay.Call(g2, [inp])\n    concat = relay.concatenate([call1, call2], axis=3)\n    main_func = relay.Function([inp], concat)\n    main_func = main_func.with_attr(\"io_used_memory\", 32)\n    mod[\"main\"] = main_func\n    return mod\n\n\ndef _full_offload():\n    mod = tvm.IRModule({})\n\n    # NPU function\n    x = relay.var(\"x\", shape=(1, 4, 4, 16), dtype=\"int8\")\n    max_pool = relay.nn.max_pool2d(x)\n    composite_func = relay.Function([x], max_pool)\n    composite_func = composite_func.with_attr(\"Composite\", \"ethos-u.pooling\")\n    inp = relay.var(\"input\", shape=(1, 4, 4, 16), dtype=\"int8\")\n    compiler_func = relay.Function([inp], composite_func)\n    compiler_func = compiler_func.with_attr(\"used_memory\", [256 + 256])\n    npu_compiler_func = compiler_func.with_attr(\"Compiler\", \"ethos-u\")\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = npu_compiler_func\n\n    # Main\n    inp = relay.var(\"main_input\", shape=(1, 4, 4, 16), dtype=\"int8\")\n    call = relay.Call(g1, [inp])\n    main_func = relay.Function([inp], call)\n    main_func = main_func.with_attr(\"io_used_memory\", 256 + 256)\n    mod[\"main\"] = main_func\n    return mod\n\n\n@pytest.mark.parametrize(\n    \"model_func,use_workspace_io,expected_memory_pressure\",\n    [\n        (_npu_and_non_npu_functions, True, (16 + 16) + (16 + 16)),\n        (_npu_and_non_npu_functions, False, (16 + 16) + (16 + 16) - (16 + 16)),\n        (_parallel_npu_functions, True, (16 + 16) + (16 + 16 + 16)),\n        (_parallel_npu_functions, False, (16 + 16) + (16 + 16 + 16) - (16 + 16)),\n        (_full_offload, True, (256 + 256)),\n        (_full_offload, False, (256 + 256) - (256 + 256)),\n    ],\n)\ndef test_calculate_memory_pressure_pass(model_func, use_workspace_io, expected_memory_pressure):\n    \"\"\"\n    Test that memory pressure is correctly calculated for NPU external functions.\n    \"\"\"\n\n    mod = model_func()\n    with tvm.transform.PassContext(config={\"tir.usmp.use_workspace_io\": use_workspace_io}):\n        memory_pressure = _calculate_memory_pressure(mod)\n    assert memory_pressure == expected_memory_pressure\n\n\ndef test_extract_memory_info():\n    \"\"\"\n    Test memory pressure value correctly reduces the workspace size.\n    \"\"\"\n    initial_pool_size = 2000\n    memory_pressure = 500\n    memory_pool = WorkspacePoolInfo(\n        \"SRAM\",\n        [tvm.target.Target(\"c\"), tvm.target.Target(\"ethos-u\")],\n        PoolInfoProperties(\n            size_hint_bytes=initial_pool_size,\n            read_bandwidth_bytes_per_cycle=16,\n            write_bandwidth_bytes_per_cycle=16,\n            target_burst_bytes={tvm.target.Target(\"ethos-u\"): 1},\n        ),\n    )\n\n    sram = extract_memory_info(memory_pool, memory_pressure)\n    assert sram.size == initial_pool_size - memory_pressure\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_binary_elementwise_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\nimport math\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.binary_elementwise import (\n    match_ethosu_binary_elementwise,\n    binary_elementwise_compute,\n)\nfrom tvm.relay.backend.contrib.ethosu.te.common import get_layout_transform_matrices\n\n\ndef _make_matrices(broadcast, ifm_layout, ifm2_layout, ofm_layout, ofm_channels):\n    broadcast_h, broadcast_w, broadcast_c = broadcast\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(ofm_channels)\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    ifm2_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, (1 - broadcast_h), 0, 0, broadcast_h],\n        [0, 0, (1 - broadcast_w), 0, broadcast_w],\n        [0, 0, 0, (1 - broadcast_c), broadcast_c],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n        ifm2_matrix = np.matmul(ifm2_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n    if ifm2_layout == \"NHCWB16\":\n        ifm2_matrix = np.matmul(nhwc_to_nhcwb16, ifm2_matrix).tolist()\n\n    return (ifm_matrix, ifm2_matrix)\n\n\n@pytest.mark.parametrize(\n    \"ofm_shape\",\n    [\n        [1, 12, 15, 128],\n        [1, 16, 16, 16],\n        [1, 1, 1, 1024],\n        [1, 73, 51, 20],\n        [1, 124, 172, 5],\n    ],\n)\n@pytest.mark.parametrize(\"ifm2_broadcast\", [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]])\n@pytest.mark.parametrize(\"ifm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ifm2_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ofm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"op_type\", [\"MUL\", \"ADD\", \"MIN\"])\ndef test_ethosu_binary_elementwise_matcher(\n    ofm_shape, ifm2_broadcast, ifm_layout, ifm2_layout, ofm_layout, op_type\n):\n    ifm_shape = ofm_shape.copy()\n    ifm2_shape = [1] + [1 if (b == 1) else a for a, b in zip(ofm_shape[1:], ifm2_broadcast)]\n    ifm_channels = ifm_shape[3]\n    ifm2_channels = ifm2_shape[3]\n    ofm_channels = ofm_shape[3]\n    nhwc_to_nhcwb16, _ = get_layout_transform_matrices(ofm_channels)\n    broadcast = [1 if a == 1 else 0 for a in ifm2_shape[1:]]\n    if ifm_layout == \"NHCWB16\":\n        ifm_shape = [\n            int(math.ceil(n))\n            for n in np.matmul(\n                nhwc_to_nhcwb16,\n                ifm_shape\n                + [\n                    1,\n                ],\n            ).tolist()[:-1]\n        ]\n    if ifm2_layout == \"NHCWB16\":\n        ifm2_shape = [\n            int(math.ceil(n))\n            for n in np.matmul(\n                nhwc_to_nhcwb16,\n                ifm2_shape\n                + [\n                    1,\n                ],\n            ).tolist()[:-1]\n        ]\n    if ofm_layout == \"NHCWB16\":\n        ofm_shape = [\n            int(math.ceil(n))\n            for n in np.matmul(\n                nhwc_to_nhcwb16,\n                ofm_shape\n                + [\n                    1,\n                ],\n            ).tolist()[:-1]\n        ]\n        order = [1, 2, 4, 3, 0]\n    else:\n        order = [1, 2, 3, 4]\n\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    ifm2 = te.placeholder(ifm2_shape, dtype=\"int8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = binary_elementwise_compute(\n        ifm=ifm,\n        ifm2=ifm2,\n        lut=lut,\n        operator_type=op_type,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ifm2_scale=1,\n        ifm2_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        ifm_channels=ifm_channels,\n        ifm2_channels=ifm2_channels,\n        reversed_operands=False,\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        rounding_mode=\"TFL\",\n        ifm_layout=ifm_layout,\n        ifm2_layout=ifm2_layout,\n        ofm_layout=ofm_layout,\n        ofm_dtype=\"int8\",\n    )\n    ifm_propagator = out.op.attrs[\"ifm_propagator\"]\n    ifm2_propagator = out.op.attrs[\"ifm2_propagator\"]\n\n    offset = [0] * len(ofm_shape)\n    stripes = [0] * len(ofm_shape)\n    output_stripe_config = cs.StripeConfig(ofm_shape, ofm_shape, ofm_shape, order, stripes, offset)\n\n    (ifm_transform, ifm2_transform) = _make_matrices(\n        broadcast, ifm_layout, ifm2_layout, ofm_layout, ofm_channels\n    )\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_binary_elementwise(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 2\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[1].transform == ifm2_transform\n\n    propagated_ifm = ifm_propagator.propagate(output_stripe_config).shape\n    propagated_ifm2 = ifm2_propagator.propagate(output_stripe_config).shape\n\n    # The layout transforms that have the exact number of output channels in them\n    # will lose no information about the number of channels\n    assert ifm_shape == propagated_ifm\n    assert ifm2_shape == propagated_ifm2\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_block_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\nimport math\n\nimport tvm\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.common import get_layout_transform_matrices\n\nfrom .infra import make_matrices\n\n\n@pytest.mark.parametrize(\n    \"test_id, op_type, activation, kernel, stride, dilation, padding, in_shape, out_shape\",\n    [\n        # Conv2D\n        (\n            0,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (34, 19),\n            (2, 2),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 266, 111, 15),\n            (1, 117, 47, 15),\n        ),\n        (\n            1,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (14, 14),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 125, 63, 64),\n            (1, 112, 50, 128),\n        ),\n        (\n            2,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (7, 1),\n            (2, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 13, 4, 12),\n            (1, 4, 4, 511),\n        ),\n        (\n            3,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (5, 5),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 96, 16, 276),\n            (1, 92, 12, 16),\n        ),\n        (\n            4,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (5, 5),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 96, 16, 276),\n            (1, 92, 12, 1),\n        ),\n        (\n            5,\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (3, 3),\n            (1, 1),\n            (2, 2),\n            (0, 0, 0, 0),\n            (1, 62, 94, 32),\n            (1, 58, 90, 16),\n        ),\n        # Depthwise Conv2D\n        (\n            6,\n            \"ethosu_depthwise_conv2d\",\n            \"NONE\",\n            (3, 5),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 77, 23, 18),\n            (1, 75, 19, 18),\n        ),\n        (\n            7,\n            \"ethosu_depthwise_conv2d\",\n            \"NONE\",\n            (3, 3),\n            (2, 2),\n            (1, 1),\n            (1, 1, 1, 1),\n            (1, 25, 10, 276),\n            (1, 13, 5, 276),\n        ),\n        # Pooling\n        (\n            8,\n            \"ethosu_pooling\",\n            \"NONE\",\n            (13, 5),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 13, 5, 276),\n            (1, 1, 1, 276),\n        ),\n        (\n            9,\n            \"ethosu_pooling\",\n            \"NONE\",\n            (7, 3),\n            (2, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 317, 14, 21),\n            (1, 156, 12, 21),\n        ),\n    ],\n)\n@pytest.mark.parametrize(\n    \"layouts\",\n    [\n        (\"NHWC\", \"NHWC\"),\n        (\"NHCWB16\", \"NHCWB16\"),\n        (\"NHWC\", \"NHCWB16\"),\n        (\"NHCWB16\", \"NHWC\"),\n    ],\n)\n@pytest.mark.parametrize(\n    \"acc_config, expected_block_configs\",\n    [\n        (\n            \"ethos-u55-32\",\n            [\n                # Conv2D\n                ((1, 8, 4, 16), (1, 8, 1, 4, 16)),\n                ((1, 6, 5, 16), (1, 6, 1, 5, 16)),\n                ((1, 4, 4, 96), (1, 4, 6, 4, 16)),\n                ((1, 8, 4, 16), (1, 8, 1, 4, 16)),\n                ((1, 10, 6, 4), (1, 5, 1, 12, 4), (1, 8, 1, 4, 16)),\n                ((1, 6, 5, 16), (1, 6, 1, 5, 16)),\n                # Depthwise Conv2D\n                ((1, 6, 10, 16), (1, 4, 1, 12, 16)),\n                ((1, 8, 5, 16), (1, 6, 1, 5, 16)),\n                # Pooling\n                ((1, 1, 1, 128), (1, 1, 4, 1, 16)),\n                ((1, 9, 6, 16), (1, 8, 1, 4, 16)),\n            ],\n        ),\n        (\n            \"ethos-u55-64\",\n            [\n                # Conv2D\n                ((1, 8, 4, 16), (1, 8, 1, 4, 16)),\n                ((1, 6, 5, 16), (1, 6, 1, 5, 16)),\n                ((1, 4, 4, 96), (1, 4, 6, 4, 16)),\n                ((1, 8, 4, 16), (1, 8, 1, 4, 16)),\n                ((1, 10, 6, 8), (1, 8, 1, 4, 16)),\n                ((1, 6, 5, 16), (1, 6, 1, 5, 16)),\n                # Depthwise Conv2D\n                ((1, 6, 10, 16), (1, 4, 1, 12, 16)),\n                ((1, 8, 5, 16), (1, 6, 1, 5, 16)),\n                # Pooling\n                ((1, 1, 1, 128), (1, 1, 4, 1, 16)),\n                ((1, 9, 6, 16), (1, 8, 1, 4, 16)),\n            ],\n        ),\n        (\n            \"ethos-u55-128\",\n            [\n                # Conv2D\n                ((1, 7, 6, 16), (1, 7, 1, 6, 16)),\n                ((1, 5, 8, 16), (1, 5, 1, 8, 16)),\n                ((1, 4, 4, 128), (1, 4, 8, 4, 16)),\n                ((1, 16, 4, 16), (1, 16, 1, 4, 16)),\n                ((1, 8, 12, 8), (1, 10, 1, 6, 16)),\n                ((1, 10, 6, 16), (1, 10, 1, 6, 16), (1, 6, 1, 6, 16)),\n                # Depthwise Conv2D\n                ((1, 7, 10, 16), (1, 7, 1, 10, 16), (1, 6, 1, 10, 16)),\n                ((1, 10, 6, 16), (1, 10, 1, 6, 16), (1, 6, 1, 6, 16)),\n                # Pooling\n                # ((1, 1, 2, 16), (1, 1, 1, 2, 16)),\n                ((1, 1, 2, 128), (1, 1, 4, 2, 16)),\n                ((1, 10, 6, 16), (1, 9, 1, 6, 16)),\n            ],\n        ),\n        (\n            \"ethos-u55-256\",\n            [\n                # Conv2D\n                ((1, 14, 8, 16), (1, 14, 1, 8, 16)),\n                ((1, 16, 8, 16), (1, 16, 1, 8, 16)),\n                ((1, 4, 4, 128), (1, 4, 8, 4, 16)),\n                ((1, 32, 4, 16), (1, 10, 12, 16), (1, 32, 1, 4, 16), (1, 10, 1, 12, 16)),\n                ((1, 20, 12, 8), (1, 10, 1, 12, 16)),\n                ((1, 12, 10, 16), (1, 12, 1, 10, 16)),\n                # Depthwise Conv2D\n                ((1, 8, 20, 16), (1, 6, 1, 20, 16), (1, 6, 2, 20, 16)),\n                ((1, 14, 6, 16), (1, 12, 1, 6, 16)),\n                # Pooling\n                # ((1, 2, 2, 16), (1, 2, 1, 2, 16)),\n                ((1, 2, 2, 128), (1, 2, 6, 2, 16)),\n                ((1, 10, 12, 16), (1, 10, 1, 12, 16)),\n            ],\n        ),\n    ],\n)\ndef test_best_block_config(\n    test_id,\n    op_type,\n    activation,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    in_shape,\n    out_shape,\n    layouts,\n    acc_config,\n    expected_block_configs,\n):\n    ofm_channels = out_shape[3]\n    ifm_channels = in_shape[3]\n\n    nhwc_to_nhcwb16, _ = get_layout_transform_matrices(ofm_channels)\n\n    ifm_matrix, ifm_offset, weight_matrix, weight_offset, _, _ = make_matrices(\n        op_type,\n        kernel,\n        stride,\n        padding,\n        layouts[0],\n        layouts[1],\n        dilation,\n        ifm_channels,\n        ofm_channels,\n    )\n\n    if layouts[0] == \"NHCWB16\":\n        in_shape = [\n            int(math.ceil(n)) for n in np.matmul(nhwc_to_nhcwb16, in_shape + (1,)).tolist()[:-1]\n        ]\n    if layouts[1] == \"NHCWB16\":\n        out_shape = [\n            int(math.ceil(n)) for n in np.matmul(nhwc_to_nhcwb16, out_shape + (1,)).tolist()[:-1]\n        ]\n\n    propagator = cs.Propagator(ifm_matrix, ifm_offset)\n    weight_propagator = cs.Propagator(weight_matrix, weight_offset)\n\n    subkernels = ((kernel[0] + 7) // 8) * ((kernel[1] + 7) // 8)\n\n    op_attrs = {\n        \"op\": op_type,\n        \"activation\": activation,\n        \"stride_h\": stride[0],\n        \"stride_w\": stride[1],\n        \"dilation_h\": dilation[0],\n        \"dilation_w\": dilation[1],\n    }\n\n    device_config = cs.EthosuDeviceConfig(acc_config)\n    block_configs = device_config.get_valid_block_configs(\n        propagator,\n        op_attrs,\n        out_shape,\n        ofm_channels,\n        ifm_channels,\n        layouts[1],\n        layouts[0],\n        \"int8\",\n        \"int8\",\n        kernel[0],\n        kernel[1],\n    )\n\n    output_quantum = [1, 1, 2, 8]\n    if layouts[1] == \"NHCWB16\":\n        output_quantum = [1, 1, 1, 2, 8]\n\n    # Create EthosUPart\n    te_subgraph = cs.TESubgraph([], None)\n    part = cs.EthosuPart(\n        te_subgraph,\n        [propagator, weight_propagator],\n        output_quantum,\n        subkernels,\n        block_configs,\n        1,\n    )\n    # Add tensors\n    input_tensor = cs.Tensor(in_shape, \"int8\")\n    part.set_input(0, input_tensor)\n    if op_type == \"ethosu_conv2d\":\n        weight_tensor = cs.Tensor([ofm_channels, kernel[0], kernel[1], ifm_channels], \"int8\")\n        part.set_input(1, weight_tensor)\n    elif op_type == \"ethosu_depthwise_conv2d\":\n        weight_tensor = cs.Tensor([ofm_channels, kernel[0], kernel[1], 1], \"int8\")\n        part.set_input(1, weight_tensor)\n\n    output_tensor = cs.Tensor(out_shape, \"int8\")\n    part.set_output(output_tensor)\n\n    order = [1, 2, 3, 4] if layouts[1] == \"NHCWB16\" else [1, 2, 4, 3, 0]\n    stripes = [1] * len(output_quantum)\n    offset = [0] * len(output_quantum)\n\n    stripe_config = cs.StripeConfig(out_shape, out_shape, out_shape, order, stripes, offset)\n\n    block = part.get_block_config(stripe_config)\n    block_shape = tuple(int(a) for a in block.output_shape)\n\n    assert block_shape in expected_block_configs[test_id]\n\n\n@pytest.mark.parametrize(\n    \"ofm_layout, block_config_str, expected_block_shape\",\n    [\n        (\"NHWC\", \"4x4x8\", [1, 4, 4, 8]),\n        (\"NHCWB16\", \"4x4x8\", [1, 4, 1, 4, 16]),\n        (\"NHCWB16\", \"4x4x24\", [1, 4, 2, 4, 16]),\n    ],\n)\ndef test_force_block_config_kernelwise(ofm_layout, block_config_str, expected_block_shape):\n    op_type = \"ethosu_pooling\"\n    activation = \"NONE\"\n    kernel = (2, 2)\n    stride = (2, 2)\n    padding = (0, 0)\n    dilation = (1, 1)\n    ifm_channels = 32\n    out_shape = (1, 8, 10, 16)\n\n    ifm_matrix, ifm_offset, _, _, _, _ = make_matrices(\n        op_type, kernel, stride, padding, \"NHWC\", ofm_layout, dilation, ifm_channels\n    )\n\n    ofm_channels = out_shape[3]\n\n    propagator = cs.Propagator(ifm_matrix, ifm_offset)\n\n    op_attrs = {\n        \"op\": op_type,\n        \"activation\": activation,\n        \"stride_h\": stride[0],\n        \"stride_w\": stride[1],\n        \"dilation_h\": dilation[0],\n        \"dilation_w\": dilation[1],\n    }\n\n    config = {\n        \"enable_cascader\": True,\n        \"dev_force_block_config\": block_config_str,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-128\")\n        block_configs = device_config.get_valid_block_configs(\n            propagator,\n            op_attrs,\n            out_shape,\n            ofm_channels,\n            ifm_channels,\n            ofm_layout,\n            \"NHWC\",\n            \"int8\",\n            \"int8\",\n            kernel[0],\n            kernel[1],\n        )\n\n    assert len(block_configs) == 1\n    assert block_configs[0].output_shape == expected_block_shape\n\n\n@pytest.mark.parametrize(\n    \"ofm_layout, block_config_str, expected_block_shape\",\n    [\n        (\"NHWC\", \"4x4x8\", [1, 4, 4, 8]),\n        (\"NHCWB16\", \"4x4x8\", [1, 4, 1, 4, 16]),\n        (\"NHCWB16\", \"4x4x24\", [1, 4, 2, 4, 16]),\n    ],\n)\ndef test_force_block_config_elementwise(ofm_layout, block_config_str, expected_block_shape):\n    op_type = \"ethosu_elementwise_unary\"\n    op_str = \"ABS\"\n    activation = \"NONE\"\n    ofm_shape = (1, 8, 10, 16)\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    ifm_offset = [0, 0, 0, 0]\n\n    propagator = cs.Propagator(ifm_matrix, ifm_offset)\n\n    op_attrs = {\n        \"op\": op_type,\n        \"operator_type\": op_str,\n        \"activation\": activation,\n        \"clip_min\": 0,\n        \"clip_max\": 0,\n        \"rounding_mode\": \"TFL\",\n    }\n\n    config = {\n        \"enable_cascader\": True,\n        \"dev_force_block_config\": block_config_str,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        device_config = cs.EthosuDeviceConfig(\"ethos-u55-128\")\n        block_configs = device_config.get_elementwise_block_config(\n            propagator,\n            None,\n            op_attrs,\n            ofm_shape,\n            ofm_layout,\n            \"NWHC\",\n            None,\n            \"int8\",\n            \"int8\",\n        )\n\n    assert len(block_configs) == 1\n    assert block_configs[0].output_shape == expected_block_shape\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_conv2d_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.convolution import match_ethosu_conv2d, conv2d_compute\n\nfrom .infra import make_matrices\n\n\n@pytest.mark.parametrize(\"kernel\", [(3, 3), (2, 1), (3, 5)])\n@pytest.mark.parametrize(\"stride\", [(1, 1), (2, 1), (3, 2)])\n@pytest.mark.parametrize(\"dilation\", [(1, 1), (2, 1), (3, 2)])\n@pytest.mark.parametrize(\"padding\", [(0, 0, 0, 0), (3, 2, 3, 2), (2, 1, 0, 1)])\n@pytest.mark.parametrize(\"ifm_channels\", [8, 57])\n@pytest.mark.parametrize(\"ifm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ofm_layout\", [\"NHWC\", \"NHCWB16\"])\ndef test_ethosu_conv2d_matcher(\n    kernel, stride, dilation, padding, ifm_channels, ifm_layout, ofm_layout\n):\n    if ifm_layout == \"NHWC\":\n        ifm_shape = (1, 12, 15, ifm_channels)\n    else:\n        ifm_shape = (1, 12, 1 + ((ifm_channels - 1) // 16), 15, 16)\n    ofm_channels = 8\n    kernel_h, kernel_w = kernel\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    weight = te.placeholder((ofm_channels, kernel_h, kernel_w, ifm_channels), dtype=\"int8\")\n    scale_bias = te.placeholder((ofm_channels, 10), dtype=\"uint8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = conv2d_compute(\n        ifm=ifm,\n        weight=weight,\n        scale_bias=scale_bias,\n        lut=lut,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        weight_zero_point=0,\n        strides=stride,\n        padding=padding,\n        dilation=dilation,\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        upscale=\"NONE\",\n        rounding_mode=\"TFL\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    (\n        ifm_transform,\n        ifm_offset,\n        weight_transform,\n        weight_offset,\n        scale_bias_transform,\n        scale_bias_offset,\n    ) = make_matrices(\n        \"ethosu_conv2d\",\n        kernel,\n        stride,\n        padding,\n        ifm_layout,\n        ofm_layout,\n        dilation,\n        ifm_channels,\n        ofm_channels,\n    )\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_conv2d(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 3\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[0].offset == ifm_offset\n    assert part.propagators[1].transform == weight_transform\n    assert part.propagators[1].offset == weight_offset\n    assert part.propagators[2].transform == scale_bias_transform\n    assert part.propagators[2].offset == scale_bias_offset\n\n\n@pytest.mark.parametrize(\n    \"ifm_layout, ofm_layout, ifm_channels, expected_cycles\",\n    [\n        (\"NHWC\", \"NHWC\", 24, 2304),\n        (\"NHCWB16\", \"NHWC\", 12, 2352),\n        (\"NHWC\", \"NHCWB16\", 38, 7056),\n        (\"NHCWB16\", \"NHCWB16\", 55, 4608),\n    ],\n)\ndef test_ethosu_conv2d_block_config_from_matcher(\n    ifm_layout, ofm_layout, ifm_channels, expected_cycles\n):\n    ofm_channels = 10\n    ifm_height = 123\n    ifm_width = 155\n\n    ifm_shape = (\n        (1, ifm_height, ifm_width, ifm_channels)\n        if ifm_layout == \"NHWC\"\n        else (1, ifm_height, 1 + ((ifm_channels - 1) // 16), ifm_width, 16)\n    )\n    weight_shape = (ofm_channels, 3, 3, ifm_channels)\n    scale_bias_shape = (ofm_channels, 10)\n\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    weight = te.placeholder(weight_shape, dtype=\"int8\")\n    scale_bias = te.placeholder(scale_bias_shape, dtype=\"uint8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = conv2d_compute(\n        ifm=ifm,\n        weight=weight,\n        scale_bias=scale_bias,\n        lut=lut,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        weight_zero_point=0,\n        strides=(1, 1),\n        padding=(0, 0, 0, 0),\n        dilation=(1, 1),\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        upscale=\"NONE\",\n        rounding_mode=\"TFL\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_conv2d(out, device_config)\n\n    ofm_shape = [int(i) for i in part.subgraph.output_tensor.shape]\n\n    # Add inputs and outputs to the part\n    input_tensor = cs.Tensor(ifm_shape, \"int8\")\n    part.set_input(0, input_tensor)\n    weight_tensor = cs.Tensor(weight_shape, \"int8\")\n    part.set_input(1, weight_tensor)\n    scale_bias_tensor = cs.Tensor(scale_bias_shape, \"int8\")\n    part.set_input(2, scale_bias_tensor)\n    output_tensor = cs.Tensor(ofm_shape, \"int8\")\n    part.set_output(output_tensor)\n\n    # Create a stripe of a size of the output tensor\n    order = [1, 2, 3, 4] if ofm_layout == \"NHWC\" else [1, 2, 4, 3, 0]\n    stripes = [1] * len(order)\n    offset = [0] * len(order)\n\n    stripe_config = cs.StripeConfig(ofm_shape, ofm_shape, ofm_shape, order, stripes, offset)\n\n    block = part.get_block_config(stripe_config)\n\n    # Since we dont know the values of the variables we passed to the get_valid_block_configs in\n    # the matcher, best we can do is to verify the compute cycle count since the channels have a\n    # significant effect on it\n    assert block.compute_cycles == expected_cycles\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_depthwise2d_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.depthwise import (\n    match_ethosu_depthwise_conv2d,\n    depthwise_conv2d_compute,\n)\nfrom .infra import make_matrices\n\n\n@pytest.mark.parametrize(\"kernel\", [(3, 3), (2, 1), (3, 5)])\n@pytest.mark.parametrize(\"stride\", [(1, 1), (2, 1), (3, 2)])\n@pytest.mark.parametrize(\"dilation\", [(1, 1), (2, 1), (3, 2)])\n@pytest.mark.parametrize(\"padding\", [(0, 0, 0, 0), (3, 2, 3, 2), (2, 1, 0, 1)])\n@pytest.mark.parametrize(\"ifm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ofm_layout\", [\"NHWC\", \"NHCWB16\"])\ndef test_ethosu_depthwise2d_matcher(kernel, stride, dilation, padding, ifm_layout, ofm_layout):\n    ofm_channels = 57\n    if ifm_layout == \"NHWC\":\n        ifm_shape = (1, 12, 15, ofm_channels)\n    else:\n        ifm_shape = (1, 12, 1 + ((ofm_channels - 1) // 16), 15, 16)\n    kernel_h, kernel_w = kernel\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    weight = te.placeholder((ofm_channels, kernel_h, kernel_w, 1), dtype=\"int8\")\n    scale_bias = te.placeholder((ofm_channels, 10), dtype=\"uint8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = depthwise_conv2d_compute(\n        ifm=ifm,\n        weight=weight,\n        scale_bias=scale_bias,\n        lut=lut,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        weight_zero_point=0,\n        strides=stride,\n        padding=padding,\n        dilation=dilation,\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        rounding_mode=\"TFL\",\n        upscale=\"NONE\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n        ofm_dtype=ifm.dtype,\n    )\n    (\n        ifm_transform,\n        ifm_offset,\n        weight_transform,\n        weight_offset,\n        scale_bias_transform,\n        scale_bias_offset,\n    ) = make_matrices(\n        \"ethosu_depthwise_conv2d\",\n        kernel,\n        stride,\n        padding,\n        ifm_layout,\n        ofm_layout,\n        dilation,\n        ofm_channels=ofm_channels,\n    )\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_depthwise_conv2d(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 3\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[0].offset == ifm_offset\n    assert part.propagators[1].transform == weight_transform\n    assert part.propagators[1].offset == weight_offset\n    assert part.propagators[2].transform == scale_bias_transform\n    assert part.propagators[2].offset == scale_bias_offset\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_identity_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.identity import match_ethosu_identity, identity_compute\nfrom .infra import make_matrices\n\n\ndef test_ethosu_identity_matcher():\n    ofm_channels = 21\n    ifm_shape = (1, 12, 15, ofm_channels)\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = identity_compute(\n        ifm=ifm,\n        lut=lut,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        activation=\"NONE\",\n    )\n\n    length = len(ifm.shape)\n    ifm_transform = np.identity(length + 1).tolist()\n    ifm_offset = np.zeros(length, dtype=\"int64\").tolist()\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_identity(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 1\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[0].offset == ifm_offset\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_inline_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom tvm import te\nfrom tvm.topi.transform import reshape\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.inline import match_ethosu_inline\n\n\ndef test_ethosu_inline_matcher():\n    ifm_shape = (2, 5, 6)\n    new_shape = (2, 30)\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    out = reshape(ifm, new_shape)\n    ifm_transform = [\n        [0, 0, ifm_shape[0]],\n        [0, 0, ifm_shape[1]],\n        [0, 0, ifm_shape[2]],\n        [0, 0, 1],\n    ]\n    ifm_offset = [0, 0, 0]\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_inline(out, device_config)\n\n    assert isinstance(part, cs.InlinePart)\n    assert len(part.propagators) == 1\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[0].offset == ifm_offset\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_part.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.contrib.ethosu.cascader.graph import BufferMode\nfrom tvm.contrib.ethosu.cascader.parts import EthosuPart\n\n\ndef test_ethosu_part():\n    te_subgraph = cs.TESubgraph([], None)\n    output_quantum = [1, 2, 2, 8]\n    propagator = cs.Propagator(\n        [[1, 0, 0, 0, 2], [0, 1, 0, 0, 2], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]],\n        [0, 0, 0, 0],\n    )\n    stripe_config = cs.StripeConfig(\n        [1, 4, 4, 16], [1, 64, 72, 96], [1, 4, 4, 16], [1, 2, 3, 4], [1, 16, 13, 6], [0, 0, 0, 0]\n    )\n    subkernels = 3\n\n    valid_block_configs = [cs.BlockConfig([1, 2, 4, 16], [1, 2, 4, 16], 15000, 7500)]\n\n    part = EthosuPart(\n        te_subgraph,\n        [propagator],\n        output_quantum,\n        subkernels,\n        valid_block_configs,\n        1,\n    )\n    input_tensor = cs.Tensor(shape=[1, 66, 74, 16], dtype=\"int8\")\n    part.set_input(0, input_tensor)\n    output_tensor = cs.Tensor(shape=[1, 66, 74, 16], dtype=\"int8\")\n    part.set_output(output_tensor)\n\n    assert part.get_stripe_align_hint() == output_quantum\n    # Check that the performance model runs, don't verify output\n    part.get_performance_info(stripe_config, BufferMode.ROLLING)\n    part.get_performance_info(stripe_config, BufferMode.RECOMPUTE)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_part_performance.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom functools import reduce\nimport numpy as np\nimport math\n\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.contrib.ethosu.cascader.device_config import _Shape\n\nfrom .infra import make_matrices\n\n\n@pytest.mark.parametrize(\n    \"acc_config, expected\",\n    [\n        (\"ethos-u55-256\", (1, 0.125, 0.75, 0.375, 0.75)),\n        (\"ethos-u55-128\", (1, 0.25, 1.5, 0.75, 0.75)),\n        (\"ethos-u55-64\", (1, 0.5, 3, 1.5, 1.5)),\n        (\"ethos-u55-32\", (2, 1, 6, 3, 3)),\n    ],\n)\ndef test_device_config_cycles(acc_config, expected):\n    device_config = cs.EthosuDeviceConfig(acc_config)\n\n    conv_type = \"ethosu_conv2d\"\n    conv_str = None\n    conv_ifm_dtype = \"int8\"\n    conv_ofm_dtype = \"int8\"\n    conv_activation = \"LUT\"\n    conv_cycles = device_config._get_output_cycles(\n        conv_type, conv_str, conv_ifm_dtype, conv_ofm_dtype, conv_activation\n    )\n    assert conv_cycles == expected[0]\n\n    pool_type = \"ethosu_pooling\"\n    pool_str = \"MAX\"\n    pool_ifm_dtype = \"int8\"\n    pool_ofm_dtype = \"int8\"\n    pool_activation = \"NONE\"\n    pool_cycles = device_config._get_output_cycles(\n        pool_type, pool_str, pool_ifm_dtype, pool_ofm_dtype, pool_activation\n    )\n    assert pool_cycles == expected[1]\n\n    add_type = \"ethosu_binary_elementwise\"\n    add_str = \"ADD\"\n    add_ifm_dtype = \"int8\"\n    add_ofm_dtype = \"int8\"\n    add_activation = \"NONE\"\n    add_cycles = device_config._get_output_cycles(\n        add_type, add_str, add_ifm_dtype, add_ofm_dtype, add_activation\n    )\n    assert add_cycles == expected[2]\n\n    mul_type = \"ethosu_binary_elementwise\"\n    mul_str = \"MUL\"\n    mul_ifm_dtype = \"int8\"\n    mul_ofm_dtype = \"int8\"\n    mul_activation = \"NONE\"\n    mul_cycles = device_config._get_output_cycles(\n        mul_type, mul_str, mul_ifm_dtype, mul_ofm_dtype, mul_activation\n    )\n    assert mul_cycles == expected[3]\n\n    mul_32_type = \"ethosu_binary_elementwise\"\n    mul_32_str = \"MUL\"\n    mul_32_ifm_dtype = \"int8\"\n    mul_32_ofm_dtype = \"int32\"\n    mul_32_activation = \"NONE\"\n    mul_32_cycles = device_config._get_output_cycles(\n        mul_32_type, mul_32_str, mul_32_ifm_dtype, mul_32_ofm_dtype, mul_32_activation\n    )\n    assert mul_32_cycles == expected[4]\n\n\n@pytest.mark.parametrize(\n    \"accelerator, op_type, activation, kernel, stride, dilation, padding, in_shape, out_shape, block_shape, input_block_shape, expected\",\n    [\n        (\n            \"ethos-u55-128\",\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (3, 3),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 16, 16, 96),\n            (1, 16, 16, 96),\n            (1, 8, 8, 16),\n            (1, 10, 10, 32),\n            167733,\n        ),\n        (\n            \"ethos-u55-128\",\n            \"ethosu_conv2d\",\n            \"NONE\",\n            (10, 4),\n            (2, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 58, 13, 1),\n            (1, 25, 10, 276),\n            (1, 6, 10, 32),\n            (1, 18, 14, 8),\n            174105,\n        ),\n        (\n            \"ethos-u55-128\",\n            \"ethosu_depthwise_conv2d\",\n            \"NONE\",\n            (3, 3),\n            (2, 2),\n            (1, 1),\n            (1, 1, 1, 1),\n            (1, 25, 10, 276),\n            (1, 13, 5, 276),\n            (1, 7, 6, 16),\n            (1, 15, 14, 16),\n            17590,\n        ),\n        (\n            \"ethos-u55-128\",\n            \"ethosu_depthwise_conv2d\",\n            \"NONE\",\n            (4, 9),\n            (1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 28, 81, 42),\n            (1, 25, 73, 41),\n            (1, 4, 16, 16),\n            (1, 7, 24, 16),\n            173414,\n        ),\n    ],\n)\ndef test_conv_performance(\n    accelerator,\n    op_type,\n    activation,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    in_shape,\n    out_shape,\n    block_shape,\n    input_block_shape,\n    expected,\n):\n    ifm_channels = in_shape[3]\n    ifm_matrix, ifm_offset, weight_matrix, weight_offset, _, _ = make_matrices(\n        op_type,\n        kernel,\n        stride,\n        padding,\n        \"NHWC\",\n        \"NHWC\",\n        dilation,\n        ifm_channels,\n    )\n\n    propagator = cs.Propagator(ifm_matrix, ifm_offset)\n    weight_propagator = cs.Propagator(weight_matrix, weight_offset)\n\n    subkernels = ((kernel[0] + 7) // 8) * ((kernel[1] + 7) // 8)\n\n    device_config = cs.EthosuDeviceConfig(accelerator)\n\n    output_cycles = device_config._get_output_cycles(op_type, \"\", \"int8\", \"int8\", activation)\n    output_cycles *= reduce(lambda a, b: a * b, block_shape, 1)\n    is_partkernel = device_config.is_partkernel(\n        op_type, ifm_channels, \"int8\", kernel[0] * kernel[1]\n    )\n    compute_cycles = device_config._estimate_compute_cycles_per_block(\n        op_type,\n        _Shape(block_shape),\n        _Shape(input_block_shape),\n        kernel[0],\n        kernel[1],\n        ifm_channels,\n        \"int8\",\n        is_partkernel,\n    )\n    block_configs = [\n        cs.BlockConfig(input_block_shape, block_shape, compute_cycles, int(output_cycles))\n    ]\n\n    output_quantum = [1, 1, 2, 8]\n    te_subgraph = cs.TESubgraph([], None)\n    part = cs.EthosuPart(\n        te_subgraph,\n        [propagator, weight_propagator],\n        output_quantum,\n        subkernels,\n        block_configs,\n        1,\n    )\n    part.set_input(0, cs.Tensor(in_shape, \"int8\"))\n    part.set_input(1, cs.Tensor([ifm_channels, kernel[0], kernel[1], out_shape[-1]], \"int8\"))\n    part.set_output(cs.Tensor(out_shape, \"int8\"))\n\n    stripes = [1] * len(output_quantum)\n    offset = [0] * len(output_quantum)\n    order = [1, 2, 3, 4]\n\n    stripe_config = cs.StripeConfig(out_shape, out_shape, out_shape, order, stripes, offset)\n\n    compute_cycles = part.get_performance_info(stripe_config, cs.BufferMode.ROLLING).compute_cycles\n    tolerance = expected * 0.1\n\n    assert expected - tolerance <= compute_cycles <= expected + tolerance\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_pooling_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.pooling import match_ethosu_pooling, pooling_compute\nfrom .infra import make_matrices\n\n\n@pytest.mark.parametrize(\"pool_shape\", [(3, 3), (2, 1), (3, 5)])\n@pytest.mark.parametrize(\"stride\", [(1, 1), (2, 1), (3, 2)])\n@pytest.mark.parametrize(\"padding\", [(0, 0, 0, 0), (3, 2, 3, 2), (2, 1, 0, 1)])\n@pytest.mark.parametrize(\"ifm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ofm_layout\", [\"NHWC\", \"NHCWB16\"])\ndef test_ethosu_pooling_matcher(pool_shape, stride, padding, ifm_layout, ofm_layout):\n    ofm_channels = 21\n    if ifm_layout == \"NHWC\":\n        ifm_shape = (1, 12, 15, ofm_channels)\n    else:\n        ifm_shape = (1, 12, 1 + ((ofm_channels - 1) // 16), 15, 16)\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = pooling_compute(\n        ifm=ifm,\n        lut=lut,\n        pooling_type=\"MAX\",\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        pool_shape=pool_shape,\n        ofm_channels=ofm_channels,\n        strides=stride,\n        padding=padding,\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        rounding_mode=\"TFL\",\n        upscale=\"NONE\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    (ifm_transform, ifm_offset, _, _, _, _) = make_matrices(\n        \"ethosu_pooling\",\n        pool_shape,\n        stride,\n        padding,\n        ifm_layout,\n        ofm_layout,\n        ofm_channels=ofm_channels,\n    )\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_pooling(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 1\n    assert part.propagators[0].transform == ifm_transform\n    assert part.propagators[0].offset == ifm_offset\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_ethosu_unary_elementwise_matcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\nimport math\n\nfrom tvm import te\nimport tvm.contrib.ethosu.cascader as cs\nfrom tvm.relay.backend.contrib.ethosu.te.unary_elementwise import (\n    match_ethosu_unary_elementwise,\n    unary_elementwise_compute,\n)\nfrom tvm.relay.backend.contrib.ethosu.te.common import get_layout_transform_matrices\n\n\ndef _make_matrices(ifm_layout, ofm_layout, ofm_channels):\n    nhwc_to_nhcwb16, nhcwb16_to_nhwc = get_layout_transform_matrices(ofm_channels)\n    ifm_matrix = [\n        [1, 0, 0, 0, 0],\n        [0, 1, 0, 0, 0],\n        [0, 0, 1, 0, 0],\n        [0, 0, 0, 1, 0],\n        [0, 0, 0, 0, 1],\n    ]\n    if ofm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(ifm_matrix, nhcwb16_to_nhwc).tolist()\n    if ifm_layout == \"NHCWB16\":\n        ifm_matrix = np.matmul(nhwc_to_nhcwb16, ifm_matrix).tolist()\n\n    return ifm_matrix\n\n\n@pytest.mark.parametrize(\n    \"ofm_shape\",\n    [\n        [1, 12, 15, 128],\n        [1, 16, 16, 16],\n        [1, 1, 1, 1024],\n        [1, 53, 91, 7],\n        [1, 182, 12, 72],\n    ],\n)\n@pytest.mark.parametrize(\"ifm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"ofm_layout\", [\"NHWC\", \"NHCWB16\"])\n@pytest.mark.parametrize(\"op_type\", [\"ABS\", \"CLZ\"])\ndef test_ethosu_unary_elementwise_matcher(ofm_shape, ifm_layout, ofm_layout, op_type):\n    ifm_shape = ofm_shape.copy()\n    ofm_channels = ofm_shape[3]\n    nhwc_to_nhcwb16, _ = get_layout_transform_matrices(ofm_channels)\n    if ifm_layout == \"NHCWB16\":\n        ifm_shape = [\n            int(math.ceil(n))\n            for n in np.matmul(\n                nhwc_to_nhcwb16,\n                ifm_shape\n                + [\n                    1,\n                ],\n            ).tolist()[:-1]\n        ]\n    if ofm_layout == \"NHCWB16\":\n        ofm_shape = [\n            int(math.ceil(n))\n            for n in np.matmul(\n                nhwc_to_nhcwb16,\n                ofm_shape\n                + [\n                    1,\n                ],\n            ).tolist()[:-1]\n        ]\n        order = [1, 2, 4, 3, 0]\n    else:\n        order = [1, 2, 3, 4]\n\n    ifm = te.placeholder(ifm_shape, dtype=\"int8\")\n    lut = te.placeholder((), dtype=\"uint8\")\n    out = unary_elementwise_compute(\n        ifm=ifm,\n        lut=lut,\n        operator_type=op_type,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        ofm_channels=ofm_channels,\n        activation=\"NONE\",\n        clip_min=0,\n        clip_max=0,\n        rounding_mode=\"TFL\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    ifm_propagator = out.op.attrs[\"ifm_propagator\"]\n\n    offset = [0] * len(ofm_shape)\n    stripes = [0] * len(ofm_shape)\n    output_stripe_config = cs.StripeConfig(ofm_shape, ofm_shape, ofm_shape, order, stripes, offset)\n\n    ifm_transform = _make_matrices(ifm_layout, ofm_layout, ofm_channels)\n\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    part = match_ethosu_unary_elementwise(out, device_config)\n\n    assert isinstance(part, cs.EthosuPart)\n    assert len(part.propagators) == 1\n    assert part.propagators[0].transform == ifm_transform\n\n    propagated_ifm = ifm_propagator.propagate(output_stripe_config).shape\n\n    # The layout transforms that have the exact number of output channels in them\n    # will lose no information about the number of channels\n    assert ifm_shape == propagated_ifm\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm.contrib.ethosu.cascader as cs\n\n\ndef test_tensor():\n    shape = [1, 2, 3]\n    dtype = \"uint8\"\n    is_constant = True\n    compression_ratio = 0.5\n    size = 6\n    tensor = cs.Tensor(shape, dtype, is_constant, compression_ratio)\n    assert tensor.shape == shape\n    assert tensor.dtype == dtype\n    assert tensor.is_constant == is_constant\n    assert tensor.compression_ratio == compression_ratio\n    assert tensor.size == size\n\n\ndef test_inline_part():\n    subgraph = cs.TESubgraph([], None)\n    part = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[0, 1, 0], [1, 0, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    output_stripe_config = cs.StripeConfig([2, 4], [8, 8], [2, 4], [1, 2], [4, 2], [0, 0])\n    input_stripe_config = cs.StripeConfig([4, 2], [8, 8], [4, 2], [2, 1], [2, 4], [0, 0])\n\n    assert part.input_tensors == [None]\n    assert part.output_tensor == None\n    assert len(part.propagators) == 1\n    assert part.in_line == True\n    assert part.get_stripe_align_hint() == [1, 1]\n    performance_info = part.get_performance_info(output_stripe_config, cs.BufferMode.RECOMPUTE)\n    assert performance_info.compute_cycles == 0\n    assert performance_info.read_bytes == [0]\n    assert performance_info.write_bytes == 0\n    input_stripe_configs = part.calculate_input_stripe_configs(output_stripe_config)\n    assert len(input_stripe_configs) == 1\n    assert input_stripe_configs[0] == input_stripe_config\n\n\ndef test_small_graph():\n    subgraph = cs.TESubgraph([], None)\n    part_a = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n            cs.Propagator(\n                [[0, 1, 0], [1, 0, 0], [0, 0, 1]],\n                [-1, -1],\n            ),\n        ],\n    )\n    part_b = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([10, 10], \"uint8\")\n    tensor_2 = cs.Tensor([9, 9], \"uint8\")\n    tensor_3 = cs.Tensor([10, 10], \"uint8\")\n    tensor_4 = cs.Tensor([10, 10], \"uint8\")\n\n    part_a.set_input(0, tensor_1)\n    part_a.set_input(1, tensor_2)\n    part_a.set_output(tensor_3)\n    tensor_1.add_consumer(part_a)\n    tensor_2.add_consumer(part_a)\n    tensor_3.add_producer(part_a)\n    part_b.set_input(0, tensor_3)\n    part_b.set_output(tensor_4)\n    tensor_3.add_consumer(part_b)\n    tensor_4.add_producer(part_b)\n\n    assert part_a.input_tensors == [tensor_1, tensor_2]\n    assert part_a.output_tensor == tensor_3\n    assert part_b.input_tensors == [tensor_3]\n    assert part_b.output_tensor == tensor_4\n\n    assert tensor_1.producers == []\n    assert tensor_1.consumers == [part_a]\n    assert tensor_2.producers == []\n    assert tensor_2.consumers == [part_a]\n    assert tensor_3.producers == [part_a]\n    assert tensor_3.consumers == [part_b]\n    assert tensor_4.producers == [part_b]\n    assert tensor_4.consumers == []\n\n    graph = cs.CascaderGraph([tensor_1, tensor_2], [tensor_4])\n    assert graph.input_tensors == [tensor_1, tensor_2]\n    assert graph.output_tensors == [tensor_4]\n    assert graph.part_order == [part_b, part_a]\n    for i, part in enumerate(graph.part_order):\n        assert graph.get_part_id(part) == i\n\n\ndef test_create_cascader_graph(TwoConv2DWithSliceTE):\n    _, te_graph, const_dict = TwoConv2DWithSliceTE\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    graph = cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    output_tensor = graph.output_tensors[0]\n    assert output_tensor.shape == [1, 6, 1, 6, 16]\n    assert len(output_tensor.producers) == 1\n    assert not output_tensor.is_constant\n\n    conv2_part = output_tensor.producers[0]\n    assert isinstance(conv2_part, cs.EthosuPart)\n    assert len(conv2_part.input_tensors) == 3\n\n    assert conv2_part.input_tensors[0].shape == [1, 6, 6, 64]\n    assert len(conv2_part.input_tensors[0].producers) == 1\n    assert not conv2_part.input_tensors[0].is_constant\n\n    assert conv2_part.input_tensors[1].shape == [16, 3, 3, 64]\n    assert len(conv2_part.input_tensors[1].producers) == 0\n    assert conv2_part.input_tensors[1].is_constant\n\n    assert conv2_part.input_tensors[2].shape == [16, 10]\n    assert len(conv2_part.input_tensors[2].producers) == 0\n    assert conv2_part.input_tensors[2].is_constant\n\n    slice_part = conv2_part.input_tensors[0].producers[0]\n    assert isinstance(slice_part, cs.InlinePart)\n    assert len(slice_part.input_tensors) == 1\n\n    assert slice_part.input_tensors[0].shape == [1, 12, 12, 64]\n    assert len(slice_part.input_tensors[0].producers) == 1\n    assert not slice_part.input_tensors[0].is_constant\n\n    conv1_part = slice_part.input_tensors[0].producers[0]\n    assert isinstance(conv1_part, cs.EthosuPart)\n    assert len(conv1_part.input_tensors) == 3\n\n    assert conv1_part.input_tensors[0].shape == [1, 12, 12, 8]\n    assert len(conv1_part.input_tensors[0].producers) == 0\n    assert not conv1_part.input_tensors[0].is_constant\n\n    assert conv1_part.input_tensors[1].shape == [64, 1, 1, 8]\n    assert len(conv1_part.input_tensors[1].producers) == 0\n    assert conv1_part.input_tensors[1].is_constant\n\n    assert conv1_part.input_tensors[2].shape == [64, 10]\n    assert len(conv1_part.input_tensors[2].producers) == 0\n    assert conv1_part.input_tensors[2].is_constant\n\n\ndef test_create_diamond_graph(MobileNetv2DiamondTE):\n    _, te_graph, const_dict = MobileNetv2DiamondTE\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    graph = cs.create_cascader_graph(te_graph, const_dict, device_config)\n\n    output_tensor = graph.output_tensors[0]\n    assert output_tensor.shape == [1, 56, 56, 24]\n    assert len(output_tensor.producers) == 1\n    assert not output_tensor.is_constant\n\n    add1_part = output_tensor.producers[0]\n    assert isinstance(add1_part, cs.EthosuPart)\n    assert len(add1_part.input_tensors) == 2\n    assert graph.get_part_id(add1_part) == 0\n\n    assert add1_part.input_tensors[0].shape == [1, 56, 56, 24]\n    assert len(add1_part.input_tensors[0].producers) == 1\n    assert not add1_part.input_tensors[0].is_constant\n\n    assert add1_part.input_tensors[1].shape == [1, 56, 56, 24]\n    assert len(add1_part.input_tensors[0].producers) == 1\n    assert not add1_part.input_tensors[0].is_constant\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position,invalid-name\n\n\"\"\"\nTest the cascader in the compilation flow.\n\"\"\"\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.codegen import _create_cascader\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom tvm.contrib.ethosu.cascader import MemoryRegion, EthosuDeviceConfig\n\nfrom .. import infra as test_infra\nfrom . import infra as cascader_test_infra\n\n\ndef _ethos_u55_cascader():\n    sram = MemoryRegion(\n        name=\"SRAM\",\n        size=10**6,\n        read_bandwidth=16,\n        write_bandwidth=16,\n        read_latency=0,\n        write_latency=0,\n        burst_length=1,\n    )\n    flash = MemoryRegion(name=\"FLASH\", size=10**7, read_bandwidth=4, write_bandwidth=4)\n\n    device_config = EthosuDeviceConfig(\"ethos-u55-256\")\n    cascader_options = cascader_test_infra.make_options(\n        cascade_region=sram,\n        max_proposals=64,\n        stripe_factors=4,\n        max_plan_size=10,\n        max_open_plans=8,\n        max_closed_plans=32,\n        always_copy_size=1024,\n        disable_pareto_plans=False,\n        disable_pareto_proposals=False,\n        enable_striping=False,\n    )\n    return _create_cascader(\n        options=cascader_options,\n        io_region=sram,\n        constant_region=flash,\n        working_regions=[sram],\n        device_config=device_config,\n    )\n\n\ndef _compile_model(relay_function):\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay_function\n    mod = relay.transform.InferType()(mod)\n    tir_mod = _lower_to_tir(mod[\"main\"], _ethos_u55_cascader())[0]\n    return tir_mod[\"main\"]\n\n\ndef _create_single_conv2d():\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    conv1 = test_infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    func = relay.Function(relay.analysis.free_vars(conv1), conv1)\n    return func\n\n\ndef _create_double_conv2d():\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    conv1 = test_infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    conv2 = test_infra.make_ethosu_conv2d(conv1, 4, 4, (1, 3), (1, 1), (1, 1), (1, 1))\n    func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n    return func\n\n\ndef _create_scalar_add():\n    ifm = relay.var(\"x\", shape=(1, 5, 4, 3), dtype=\"int8\")\n    ifm2 = relay.const(np.ones((1, 1, 1, 1)), dtype=\"int8\")\n    add = test_infra.make_ethosu_binary_elementwise(\n        ifm, ifm2, ifm_channels=3, ifm2_channels=1, operator_type=\"ADD\", ofm_dtype=\"int8\"\n    )\n    func = relay.Function(relay.analysis.free_vars(add), add)\n    return func\n\n\ndef test_single_conv_compute_cycles_hint():\n    \"\"\"\n    Check the \"compute_cycles_hint\" annotation remains in the lowering flow\n    for single convolution.\n    \"\"\"\n    primfunc = _compile_model(_create_single_conv2d())\n    ops = primfunc.body.body.seq\n    compute_cycles_hints = [2944, 320]\n    for op, compute_cycle_hint in zip(ops, compute_cycles_hints):\n        assert op.attr_key == \"pragma_compute_cycles_hint\"\n        assert op.value == compute_cycle_hint\n\n\ndef test_double_conv_compute_cycles_hint():\n    \"\"\"\n    Check the \"compute_cycles_hint\" annotation remains in the lowering flow\n    for double convolution.\n    \"\"\"\n    primfunc = _compile_model(_create_double_conv2d())\n    ops = primfunc.body.body.body.body.seq\n    compute_cycles_hints = [2944, 1408, 320, 240]\n    for op, compute_cycle_hint in zip(ops, compute_cycles_hints):\n        assert op.attr_key == \"pragma_compute_cycles_hint\"\n        assert op.value == compute_cycle_hint\n\n\ndef test_scalar_add_compute_cycles_hint():\n    \"\"\"\n    Check the \"compute_cycles_hint\" annotation remains in the lowering flow\n    for add with scalar values.\n    \"\"\"\n    primfunc = _compile_model(_create_scalar_add())\n    ops = primfunc.body.body.seq\n\n    compute_cycles_hints = [16, 24]\n    for op, compute_cycle_hint in zip(ops, compute_cycles_hints):\n        assert op.attr_key == \"pragma_compute_cycles_hint\"\n        assert op.value == compute_cycle_hint\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_memory_reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\nimport tensorflow as tf\nimport tflite.Model\nfrom tvm import relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.micro import model_library_format as mlf\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nimport tvm\nfrom tvm import WorkspaceMemoryPools, WorkspacePoolInfo, PoolInfoProperties\nfrom tvm.relay.backend.contrib.ethosu.codegen import extract_memory_info\n\nfrom .. import infra\n\n\ndef _get_compilation_config(accel_type, enable_cascader, enable_striping):\n    enable_usmp = True\n\n    target = tvm.target.Target(\"c\")\n    ethosu_target = tvm.target.Target(\"ethos-u\")\n    runtime = Runtime(\"crt\")\n\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": 16,\n            \"interface-api\": \"c\",\n            \"unpacked-api\": True,\n        },\n    )\n    pass_config = {\n        \"tir.disable_vectorize\": True,\n        \"relay.ext.ethos-u.options\": {\n            \"accelerator_config\": accel_type,\n            \"enable_cascader\": enable_cascader,\n            \"enable_striping\": enable_striping,\n        },\n        \"tir.usmp.enable\": enable_usmp,\n        \"tir.usmp.algorithm\": \"hill_climb\",\n        \"tir.disable_storage_rewrite\": enable_usmp,\n    }\n\n    return target, ethosu_target, runtime, executor, pass_config\n\n\ndef _get_ethosu_workspace_size(\n    mod, params, accel_type, pool_size, enable_cascader, enable_striping\n):\n\n    target, ethosu_target, runtime, executor, pass_config = _get_compilation_config(\n        accel_type, enable_cascader, enable_striping\n    )\n\n    workspace_memory_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"SRAM\",\n                [target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=pool_size,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            ),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3, config=pass_config):\n        lib = tvm.relay.build(\n            mod,\n            target,\n            executor=executor,\n            runtime=runtime,\n            workspace_memory_pools=workspace_memory_pools,\n            params=params,\n        )\n\n    mlf_memory_map = mlf._build_function_memory_map(lib.function_metadata)\n    return mlf_memory_map[\"main\"][0][\"workspace_size_bytes\"]\n\n\n@pytest.mark.parametrize(\n    \"accel_type, expected_ws_size_without_striping, expected_ws_size_with_striping\",\n    [\n        (\"ethos-u55-256\", 1067520, 14208),\n        (\"ethos-u55-128\", 1067520, 4080),\n        (\"ethos-u55-64\", 1067520, 4080),\n        (\"ethos-u55-32\", 1067504, 4064),\n    ],\n)\ndef test_double_conv2d(\n    accel_type, expected_ws_size_without_striping, expected_ws_size_with_striping\n):\n    np.random.seed(1)\n    ifm_shape = (1, 321, 212, 6)\n\n    @tf.function\n    def tf_graph(x):\n        ofm_channels = 10\n        conv2d = tf.nn.conv2d(\n            x,\n            filters=tf.constant(\n                np.random.uniform(size=[3, 2, ifm_shape[3], ofm_channels]),  # HWIO\n                dtype=tf.float32,\n            ),\n            strides=(1, 1),\n            padding=\"VALID\",\n            dilations=(2, 1),\n        )\n        conv2d = tf.nn.conv2d(\n            conv2d,\n            filters=tf.constant(\n                np.random.uniform(size=(1, 1, ofm_channels, 3)),  # HWIO\n                dtype=tf.float32,\n            ),\n            strides=(3, 2),\n            padding=\"SAME\",\n            dilations=(1, 1),\n        )\n\n        return conv2d\n\n    _, tflite_graph = infra.get_tflite_graph(tf_graph, [ifm_shape])\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n\n    # Run the graph without the cascader, with lots of memory\n    pool_size = 2000000\n    workspace_size_cascader_disabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=False, enable_striping=False\n    )\n    workspace_size_cascader_enabled_striping_disabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=True, enable_striping=False\n    )\n    # if striping is not done, it should be same as cacader disabled\n    assert workspace_size_cascader_disabled == workspace_size_cascader_enabled_striping_disabled\n\n    # Run the same graph with the cascader, giving it less memory to persuade cascder to cascade\n    pool_size = 600000\n    workspace_size_cascader_enabled_striping_enabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=True, enable_striping=True\n    )\n\n    assert workspace_size_cascader_disabled == expected_ws_size_without_striping\n    assert workspace_size_cascader_enabled_striping_enabled == expected_ws_size_with_striping\n\n\n@pytest.mark.parametrize(\n    \"accel_type, expected_ws_size_without_striping, expected_ws_size_with_striping\",\n    [\n        (\"ethos-u55-256\", 180288, 15312),\n        (\"ethos-u55-128\", 180288, 15312),\n        (\"ethos-u55-64\", 180288, 14544),\n        (\"ethos-u55-32\", 180272, 14544),\n    ],\n)\ndef test_depthwise2d_conv2d_pooling(\n    accel_type, expected_ws_size_without_striping, expected_ws_size_with_striping\n):\n    np.random.seed(2)\n    ifm_shape = (1, 80, 75, 3)\n\n    @tf.function\n    def tf_graph(x):\n        # This graph will execute as one cascade\n        ofm_channels = 7\n        conv2d = tf.nn.conv2d(\n            x,\n            filters=tf.constant(\n                np.random.uniform(size=[3, 2, ifm_shape[3], ofm_channels]),  # HWIO\n                dtype=tf.float32,\n            ),\n            strides=(1, 1),\n            padding=\"VALID\",\n            dilations=(1, 1),\n        )\n        depthwise2d = tf.nn.depthwise_conv2d(\n            conv2d,\n            tf.constant(np.random.uniform(size=(3, 3, ofm_channels, 1)), dtype=tf.float32),  # HWC1\n            strides=(1, 1, 1, 1),\n            padding=\"VALID\",\n            dilations=(1, 1),\n        )\n        relu = tf.nn.relu(depthwise2d)\n        conv2d = tf.nn.conv2d(\n            relu,\n            filters=tf.constant(\n                np.random.uniform(size=[3, 2, ofm_channels, 2]),  # HWIO\n                dtype=tf.float32,\n            ),\n            strides=(1, 1),\n            padding=\"SAME\",\n            dilations=(1, 1),\n        )\n        max_pool = tf.nn.max_pool(conv2d, (3, 3), (1, 1), \"SAME\")\n\n        return max_pool\n\n    _, tflite_graph = infra.get_tflite_graph(tf_graph, [ifm_shape])\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n\n    # Run the graph without the cascader, with lots of memory\n    pool_size = 10**6\n    workspace_size_cascader_disabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=False, enable_striping=False\n    )\n    workspace_size_cascader_enabled_striping_disabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=True, enable_striping=False\n    )\n    # if striping is not done, it should be same as cacader disabled\n    assert workspace_size_cascader_disabled == workspace_size_cascader_enabled_striping_disabled\n\n    # Run the same graph with the cascader, giving it less memory to persuade cascder to cascade\n    pool_size = 50000\n    workspace_size_cascader_enabled_striping_enabled = _get_ethosu_workspace_size(\n        mod, params, accel_type, pool_size, enable_cascader=True, enable_striping=True\n    )\n\n    assert workspace_size_cascader_disabled == expected_ws_size_without_striping\n    assert workspace_size_cascader_enabled_striping_enabled == expected_ws_size_with_striping\n\n\ndef test_multiple_memory_pools():\n    \"\"\"\n    The cascader does not support multiple workspace memory\n    pools. Check the correct error is thrown.\n    \"\"\"\n    np.random.seed(2)\n    ifm_shape = (1, 80, 75, 3)\n\n    target, ethosu_target, runtime, executor, pass_config = _get_compilation_config(\n        \"ethos-u55-256\", True, True\n    )\n    workspace_memory_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"SRAM\",\n                [target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=1,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            ),\n            WorkspacePoolInfo(\n                \"SRAM\",\n                [target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=1,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            ),\n        ]\n    )\n\n    @tf.function\n    def tf_graph(x):\n        return tf.nn.max_pool(x, (3, 3), (1, 1), \"SAME\")\n\n    _, tflite_graph = infra.get_tflite_graph(tf_graph, [ifm_shape])\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n\n    with pytest.raises(ValueError) as e:\n        with tvm.transform.PassContext(opt_level=3, config=pass_config):\n            tvm.relay.build(\n                mod,\n                target,\n                executor=executor,\n                runtime=runtime,\n                workspace_memory_pools=workspace_memory_pools,\n                params=params,\n            )\n\n    expected_reason = \"Exactly one workspace pool needs to be provided for the U55 cascader\"\n    on_error = \"A ValueError was caught but its reason is not the expected one.\"\n    assert expected_reason in str(e.value), on_error\n\n\ndef test_missing_memory_pools():\n    \"\"\"\n    The cascader requires memory pools to be present, check the correct error\n    is thrown when there aren't any.\n    \"\"\"\n    np.random.seed(2)\n    ifm_shape = (1, 80, 75, 3)\n\n    target, _, runtime, executor, pass_config = _get_compilation_config(\"ethos-u55-256\", True, True)\n\n    @tf.function\n    def tf_graph(x):\n        return tf.nn.max_pool(x, (3, 3), (1, 1), \"SAME\")\n\n    _, tflite_graph = infra.get_tflite_graph(tf_graph, [ifm_shape])\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n\n    with pytest.raises(ValueError) as e:\n        with tvm.transform.PassContext(opt_level=3, config=pass_config):\n            tvm.relay.build(\n                mod,\n                target,\n                executor=executor,\n                runtime=runtime,\n                workspace_memory_pools=None,\n                params=params,\n            )\n\n    expected_reason = \"Workspace memory pool needs to be provided for the U55 cascader\"\n    on_error = \"A ValueError was caught but its reason is not the expected one.\"\n    assert expected_reason in str(e.value), on_error\n\n\ndef test_invalid_accelerator():\n    \"\"\"\n    Check an error is thrown when an unsupported accelerator configuration\n    is used.\n    \"\"\"\n    np.random.seed(2)\n    ifm_shape = (1, 80, 75, 3)\n\n    target, ethosu_target, runtime, executor, pass_config = _get_compilation_config(\n        \"ethos-u65-256\", True, True\n    )\n    workspace_memory_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"SRAM\",\n                [target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=1,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            ),\n        ]\n    )\n\n    @tf.function\n    def tf_graph(x):\n        return tf.nn.max_pool(x, (3, 3), (1, 1), \"SAME\")\n\n    _, tflite_graph = infra.get_tflite_graph(tf_graph, [ifm_shape])\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n\n    with pytest.raises(ValueError) as e:\n        with tvm.transform.PassContext(opt_level=3, config=pass_config):\n            tvm.relay.build(\n                mod,\n                target,\n                executor=executor,\n                runtime=runtime,\n                workspace_memory_pools=workspace_memory_pools,\n                params=params,\n            )\n\n    expected_reason = \"Cascading is not supported for the U65 accelerator\"\n    on_error = \"A ValueError was caught but its reason is not the expected one.\"\n    assert expected_reason in str(e.value), on_error\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_pareto.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.tir import IntImm\nfrom tvm.contrib.ethosu.cascader.pareto import (\n    _get_pareto_frontier,\n    _thin_vector,\n    _pareto_cull_plans,\n)\nfrom tvm.contrib.ethosu.cascader import (\n    Plan,\n    StripeConfig,\n    TensorConfig,\n    TensorConfigState,\n    BufferMode,\n    Tensor,\n)\n\nimport pytest\nimport numpy as np\n\n\ndef _ref_get_pareto_frontier(costs):\n    is_efficient = np.ones(costs.shape[0], dtype=bool)\n    for i, c in enumerate(costs):\n        if is_efficient[i]:\n            is_efficient[is_efficient] = np.any(\n                costs[is_efficient] < c, axis=1\n            )  # Keep any point with a lower cost\n            is_efficient[i] = True  # And keep self\n    return is_efficient\n\n\ndef _ref_thin_vector(vec, max_size):\n    if max_size < 1:\n        return []\n    if len(vec) <= max_size or len(vec) == 0:\n        return vec\n    if max_size == 1:\n        return [vec[0]]\n    samples = np.linspace(0, len(vec), max_size - 1, endpoint=False).astype(int)\n    samples = np.append(samples, len(vec) - 1)\n    return vec[samples]\n\n\ndef _ref_pareto_cull_plans(plans, points):\n    if len(plans) <= points:\n        return plans\n    plans = np.array(sorted(plans, key=lambda x: x.memory_usage))\n    costs = []\n    for plan in plans:\n        costs.append(np.array([plan.memory_usage, plan.cycles]))\n    is_efficient = _ref_get_pareto_frontier(np.array(costs))\n    culled_plans = plans[is_efficient]\n    thinned_plans = (\n        culled_plans\n        if len(culled_plans) <= points\n        else _ref_thin_vector(np.array(culled_plans), points)\n    )\n    return thinned_plans\n\n\n@pytest.mark.parametrize(\"num_costs\", [1, 10, 30, 100, 300, 1000])\ndef test_get_pareto_frontier(num_costs):\n    cost_low = 1\n    cost_high = 100\n    dims = 2\n    costs = []\n    for i in range(num_costs):\n        costs.append(list(np.random.randint(cost_low, cost_high, size=(dims,))))\n    reference = list(_ref_get_pareto_frontier(np.array(costs)))\n    result = _get_pareto_frontier(costs)\n    assert result == reference\n\n\n@pytest.mark.parametrize(\"vec_length\", [0, 1, 10, 25, 100])\n@pytest.mark.parametrize(\"max_size\", [0, 1, 2, 5, 11, 51])\ndef test_thin_vector(vec_length, max_size):\n    def _make_vector(length):\n        vector = []\n        for i in range(length):\n            obj = IntImm(\"int32\", i)\n            vector.append(obj)\n\n        return vector\n\n    vector = _make_vector(vec_length)\n    reference = list(_ref_thin_vector(np.array(vector), max_size))\n    result = _thin_vector(vector, max_size)\n    assert result == reference\n\n\n@pytest.mark.parametrize(\"num_plans\", [0, 1, 10, 25, 100])\n@pytest.mark.parametrize(\"max_plans\", [0, 1, 2, 5, 11, 51])\ndef test_pareto_cull_plans(num_plans, max_plans, SRAM):\n    memory_usage_low = 1\n    memory_usage_high = 1000\n    cycles_low = 100\n    cycles_high = 10000\n\n    def _make_plan(memory_usage, cycles):\n        output_config = TensorConfig(\n            tensor=Tensor([1], \"int8\"),\n            home_region=SRAM,\n            state=TensorConfigState.BOUNDARY,\n            buffer_mode=BufferMode.RECOMPUTE,\n            stripe_configs=[StripeConfig([1], [1], [1], [1], [1], [0])],\n        )\n        return Plan(\n            tensor_configs={},\n            open_configs=[],\n            output_config=output_config,\n            part_group=[],\n            interior_region=SRAM,\n            memory_usage=memory_usage,\n            cycles=cycles,\n        )\n\n    def _make_plans(num):\n        plans = []\n        for _ in range(num):\n            memory_usage = np.random.randint(memory_usage_low, memory_usage_high)\n            cycles = np.random.randint(cycles_low, cycles_high)\n            plan = _make_plan(memory_usage, cycles)\n            plans.append(plan)\n\n        return plans\n\n    plans = _make_plans(num_plans)\n    reference = list(_ref_pareto_cull_plans(plans, max_plans))\n    result = _pareto_cull_plans(plans, max_plans, False)\n    assert result == reference\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_plan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm.contrib.ethosu.cascader as cs\n\nimport pytest\n\n\ndef test_plan(DRAM, SRAM):\n    subgraph = cs.TESubgraph([], None)\n    part = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([10, 10], \"uint8\")\n    tensor_2 = cs.Tensor([10, 10], \"uint8\")\n\n    part.set_input(0, tensor_1)\n    part.set_output(tensor_2)\n    tensor_1.add_consumer(part)\n    tensor_2.add_producer(part)\n\n    output_stripe_config = cs.StripeConfig(\n        shape=[5, 5],\n        extent=[10, 10],\n        strides=[5, 5],\n        order=[1, 2],\n        stripes=[2, 2],\n        offset=[0, 0],\n    )\n    tensor_config_out = cs.TensorConfig(\n        tensor=tensor_2,\n        home_region=DRAM,\n        state=cs.TensorConfigState.BOUNDARY,\n        buffer_mode=cs.BufferMode.RECOMPUTE,\n        stripe_configs=[output_stripe_config],\n        copy_tensor=False,\n    )\n    input_stripe_config = part.calculate_input_stripe_configs(output_stripe_config)[0]\n    tensor_config_in = cs.TensorConfig(\n        tensor=tensor_1,\n        home_region=DRAM,\n        state=cs.TensorConfigState.INTERIOR,\n        buffer_mode=cs.BufferMode.ROLLING,\n        stripe_configs=[input_stripe_config],\n        copy_tensor=False,\n    )\n    tensor_configs = {tensor_1: tensor_config_in, tensor_2: tensor_config_out}\n    open_configs = frozenset([tensor_config_in])\n    part_group = frozenset([part])\n    interior_region = SRAM\n    memory_usage = 100\n    cycles = 20\n    plan = cs.Plan(\n        tensor_configs=tensor_configs,\n        open_configs=open_configs,\n        output_config=tensor_config_out,\n        part_group=part_group,\n        interior_region=interior_region,\n        memory_usage=memory_usage,\n        cycles=cycles,\n    )\n\n    assert plan.tensor_configs == tensor_configs\n    assert plan.open_configs == open_configs\n    assert plan.output_config == tensor_config_out\n    assert plan.part_group == part_group\n    assert plan.interior_region == interior_region\n    assert plan.memory_usage == memory_usage\n    assert plan.cycles == cycles\n\n\ndef test_plan_merge(DRAM, SRAM):\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 2, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    part_2 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n            cs.Propagator(\n                [[0, 0, 6], [0, 0, 6], [0, 0, 1]],\n                [0, 0],\n            ),\n            cs.Propagator(\n                [[1, 0], [0, 1]],\n                [0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([20, 20], \"uint8\")\n    tensor_2 = cs.Tensor([10, 10], \"uint8\")\n    tensor_3 = cs.Tensor([6, 6], \"uint8\")\n    tensor_4 = cs.Tensor([10], \"uint8\")\n    tensor_5 = cs.Tensor([10, 10], \"uint8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    part_2.set_input(0, tensor_2)\n    part_2.set_input(1, tensor_3)\n    part_2.set_input(2, tensor_4)\n    part_2.set_output(tensor_5)\n    tensor_2.add_consumer(part_2)\n    tensor_3.add_consumer(part_2)\n    tensor_4.add_consumer(part_2)\n    tensor_5.add_producer(part_2)\n\n    output_stripe_config = cs.StripeConfig(\n        shape=[5, 5],\n        extent=[10, 10],\n        strides=[5, 5],\n        order=[1, 2],\n        stripes=[2, 2],\n        offset=[0, 0],\n    )\n    tensor_config_5 = cs.TensorConfig(\n        tensor=tensor_5,\n        home_region=DRAM,\n        state=cs.TensorConfigState.BOUNDARY,\n        buffer_mode=cs.BufferMode.RECOMPUTE,\n        stripe_configs=[output_stripe_config],\n        copy_tensor=False,\n    )\n    input_stripe_configs = part_2.calculate_input_stripe_configs(output_stripe_config)\n    tensor_config_4 = cs.TensorConfig(\n        tensor=tensor_4,\n        home_region=DRAM,\n        state=cs.TensorConfigState.BOUNDARY,\n        buffer_mode=cs.BufferMode.RECOMPUTE,\n        stripe_configs=[input_stripe_configs[2]],\n        copy_tensor=False,\n    )\n    tensor_config_3 = cs.TensorConfig(\n        tensor=tensor_3,\n        home_region=SRAM,\n        state=cs.TensorConfigState.INTERIOR,\n        buffer_mode=cs.BufferMode.RECOMPUTE,\n        stripe_configs=[input_stripe_configs[1]],\n        copy_tensor=False,\n    )\n    tensor_config_2 = cs.TensorConfig(\n        tensor=tensor_2,\n        home_region=SRAM,\n        state=cs.TensorConfigState.INTERIOR,\n        buffer_mode=cs.BufferMode.ROLLING,\n        stripe_configs=[input_stripe_configs[0]],\n        copy_tensor=False,\n    )\n    input_stripe_config = part_1.calculate_input_stripe_configs(input_stripe_configs[0])[0]\n    tensor_config_1 = cs.TensorConfig(\n        tensor=tensor_1,\n        home_region=DRAM,\n        state=cs.TensorConfigState.BOUNDARY,\n        buffer_mode=cs.BufferMode.ROLLING,\n        stripe_configs=[input_stripe_config],\n        copy_tensor=False,\n    )\n    tensor_configs = {tensor_1: tensor_config_1, tensor_2: tensor_config_2}\n    open_configs = frozenset([tensor_config_2])\n    part_group = frozenset([part_1])\n    interior_region = SRAM\n    memory_usage = 100\n    cycles = 20\n    plan_1 = cs.Plan(\n        tensor_configs=tensor_configs,\n        open_configs=open_configs,\n        output_config=tensor_config_2,\n        part_group=part_group,\n        interior_region=interior_region,\n        memory_usage=memory_usage,\n        cycles=cycles,\n    )\n\n    tensor_configs = {\n        tensor_2: tensor_config_2,\n        tensor_3: tensor_config_3,\n        tensor_4: tensor_config_4,\n        tensor_5: tensor_config_5,\n    }\n    open_configs = frozenset([tensor_config_2, tensor_config_3])\n    part_group = frozenset([part_2])\n    interior_region = SRAM\n    memory_usage = 200\n    cycles = 30\n    plan_2 = cs.Plan(\n        tensor_configs=tensor_configs,\n        open_configs=open_configs,\n        output_config=tensor_config_5,\n        part_group=part_group,\n        interior_region=interior_region,\n        memory_usage=memory_usage,\n        cycles=cycles,\n    )\n\n    merged_plan = plan_1.merge(plan_2)\n\n    assert merged_plan.tensor_configs == {\n        tensor_1: tensor_config_1,\n        tensor_2: tensor_config_2,\n        tensor_3: tensor_config_3,\n        tensor_4: tensor_config_4,\n        tensor_5: tensor_config_5,\n    }\n    assert merged_plan.open_configs == frozenset([tensor_config_3])\n    assert merged_plan.output_config == tensor_config_5\n    assert merged_plan.part_group == frozenset([part_1, part_2])\n    assert merged_plan.interior_region == interior_region\n    assert merged_plan.memory_usage == plan_1.memory_usage + plan_2.memory_usage\n    assert merged_plan.cycles == plan_1.cycles + plan_2.cycles\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_plan_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm.contrib.ethosu.cascader as cs\nfrom .infra import make_simple_home_map, make_options, ethosu_enabled\n\nfrom tvm.contrib.ethosu.cascader.plan_generator import (\n    _generate_output_stripe_configs,\n    _generate_single_plans,\n    _generate_graph_plans,\n)\n\n\n@pytest.mark.parametrize(\"stripe_factors\", [3, 4, 8, 16, 10])\ndef test_generate_output_stripe_configs_disable_striping(stripe_factors):\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 2, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([800, 800], \"uint8\")\n    tensor_2 = cs.Tensor([400, 400], \"uint8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    assert (\n        len(\n            _generate_output_stripe_configs(\n                part_1, stripe_factors, enable_striping=False, multi_dimensional=False\n            )\n        )\n        == 1\n    )\n\n\ndef test_generate_output_stripe_configs_multi_dimensional():\n    stripe_factors = 3\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 2, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([800, 800], \"uint8\")\n    tensor_2 = cs.Tensor([400, 400], \"uint8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    expected_stripe_configs = {\n        cs.StripeConfig([1, 1], [400, 400], [1, 1], [1, 2], [400, 400], [0, 0]),\n        cs.StripeConfig([1, 1], [400, 400], [1, 1], [2, 1], [400, 400], [0, 0]),\n        cs.StripeConfig([200, 1], [400, 400], [200, 1], [1, 2], [2, 400], [0, 0]),\n        cs.StripeConfig([200, 1], [400, 400], [200, 1], [2, 1], [2, 400], [0, 0]),\n        cs.StripeConfig([400, 1], [400, 400], [400, 1], [2, 1], [1, 400], [0, 0]),\n        cs.StripeConfig([1, 200], [400, 400], [1, 200], [1, 2], [400, 2], [0, 0]),\n        cs.StripeConfig([1, 200], [400, 400], [1, 200], [2, 1], [400, 2], [0, 0]),\n        cs.StripeConfig([200, 200], [400, 400], [200, 200], [2, 1], [2, 2], [0, 0]),\n        cs.StripeConfig([200, 200], [400, 400], [200, 200], [1, 2], [2, 2], [0, 0]),\n        cs.StripeConfig([400, 200], [400, 400], [400, 200], [2, 1], [1, 2], [0, 0]),\n        cs.StripeConfig([1, 400], [400, 400], [1, 400], [1, 2], [400, 1], [0, 0]),\n        cs.StripeConfig([200, 400], [400, 400], [200, 400], [1, 2], [2, 1], [0, 0]),\n        cs.StripeConfig([400, 400], [400, 400], [400, 400], [1, 2], [1, 1], [0, 0]),\n    }\n\n    output_stripe_configs = _generate_output_stripe_configs(\n        part=part_1, stripe_factors=stripe_factors, enable_striping=True, multi_dimensional=True\n    )\n\n    assert len(output_stripe_configs) == len(expected_stripe_configs)\n    assert set(output_stripe_configs) == expected_stripe_configs\n\n\ndef test_generate_output_stripe_configs_uncascadable_axis():\n    stripe_factors = 3\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 0, 200], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([800, 200], \"uint8\")\n    tensor_2 = cs.Tensor([400, 400], \"uint8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    expected_stripe_configs = {\n        cs.StripeConfig([1, 400], [400, 400], [1, 400], [1, 2], [400, 1], [0, 0]),\n        cs.StripeConfig([200, 400], [400, 400], [200, 400], [1, 2], [2, 1], [0, 0]),\n        cs.StripeConfig([400, 400], [400, 400], [400, 400], [1, 2], [1, 1], [0, 0]),\n    }\n\n    output_stripe_configs = _generate_output_stripe_configs(\n        part=part_1, stripe_factors=stripe_factors, enable_striping=True, multi_dimensional=True\n    )\n\n    assert len(output_stripe_configs) == len(expected_stripe_configs)\n    assert set(output_stripe_configs) == expected_stripe_configs\n\n\ndef test_generate_output_stripe_configs_single_dimension():\n    stripe_factors = 3\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 2, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([800, 800], \"uint8\")\n    tensor_2 = cs.Tensor([400, 400], \"uint8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    expected_stripe_configs = {\n        cs.StripeConfig([400, 1], [400, 400], [400, 1], [2, 1], [1, 400], [0, 0]),\n        cs.StripeConfig([400, 200], [400, 400], [400, 200], [2, 1], [1, 2], [0, 0]),\n        cs.StripeConfig([1, 400], [400, 400], [1, 400], [1, 2], [400, 1], [0, 0]),\n        cs.StripeConfig([200, 400], [400, 400], [200, 400], [1, 2], [2, 1], [0, 0]),\n        cs.StripeConfig([400, 400], [400, 400], [400, 400], [1, 2], [1, 1], [0, 0]),\n    }\n\n    output_stripe_configs = _generate_output_stripe_configs(\n        part=part_1, stripe_factors=stripe_factors, enable_striping=True, multi_dimensional=False\n    )\n\n    assert len(output_stripe_configs) == len(expected_stripe_configs)\n    assert set(output_stripe_configs) == expected_stripe_configs\n\n\ndef test_generate_single_plans(SRAM, DRAM):\n    subgraph = cs.TESubgraph([], None)\n    part_1 = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[2, 0, 0], [0, 2, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([800, 800], \"int8\")\n    tensor_2 = cs.Tensor([400, 400], \"int8\")\n\n    part_1.set_input(0, tensor_1)\n    part_1.set_output(tensor_2)\n    tensor_1.add_consumer(part_1)\n    tensor_2.add_producer(part_1)\n\n    home_map = {\n        tensor_1: [SRAM, DRAM],\n        tensor_2: [SRAM],\n    }\n    options = make_options(cascade_region=SRAM, stripe_factors=1)\n    output_stripe_configs = _generate_output_stripe_configs(\n        part_1,\n        options.stripe_factors,\n        enable_striping=True,\n        multi_dimensional=True,\n    )\n    plans = _generate_single_plans(part_1, output_stripe_configs, home_map, options)\n    for plan in plans:\n        assert plan.interior_region == SRAM\n        assert plan.part_group == frozenset([part_1])\n        assert set(plan.tensor_configs.keys()) == set([tensor_1, tensor_2])\n        for open_config in plan.open_configs:\n            assert open_config.state == cs.TensorConfigState.INTERIOR\n\n\ndef test_generate_graph_plans(SRAM, DRAM):\n    num_part_groups = 3\n    stripe_factors = 4\n    max_plan_size = 10\n    subgraph = cs.TESubgraph([], None)\n    part_a = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n            cs.Propagator(\n                [[0, 1, 0], [1, 0, 0], [0, 0, 1]],\n                [-1, -1],\n            ),\n        ],\n    )\n    part_b = cs.InlinePart(\n        subgraph,\n        [\n            cs.Propagator(\n                [[1, 0, 0], [0, 1, 0], [0, 0, 1]],\n                [0, 0],\n            ),\n        ],\n    )\n    tensor_1 = cs.Tensor([10, 10], \"int8\")\n    tensor_2 = cs.Tensor([9, 9], \"int8\")\n    tensor_3 = cs.Tensor([10, 10], \"int8\")\n    tensor_4 = cs.Tensor([10, 10], \"int8\")\n\n    part_a.set_input(0, tensor_1)\n    part_a.set_input(1, tensor_2)\n    part_a.set_output(tensor_3)\n    tensor_1.add_consumer(part_a)\n    tensor_2.add_consumer(part_a)\n    tensor_3.add_producer(part_a)\n    part_b.set_input(0, tensor_3)\n    part_b.set_output(tensor_4)\n    tensor_3.add_consumer(part_b)\n    tensor_4.add_producer(part_b)\n\n    graph = cs.CascaderGraph([tensor_1, tensor_2], [tensor_4])\n    home_map = {\n        tensor_1: [SRAM, DRAM],\n        tensor_2: [SRAM],\n        tensor_3: [SRAM],\n        tensor_4: [SRAM, DRAM],\n    }\n\n    options = make_options(\n        cascade_region=SRAM,\n        stripe_factors=stripe_factors,\n        max_plan_size=max_plan_size,\n    )\n    closed_plans = _generate_graph_plans(graph, home_map, options)\n\n    assert len(closed_plans) == num_part_groups\n\n\nif ethosu_enabled:\n\n    def test_plan_generator_two_conv2d(FLASH, SRAM, TwoConv2DGraph):\n        num_part_groups = 3\n        graph = TwoConv2DGraph\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            stripe_factors=4,\n            max_plan_size=10,\n        )\n\n        closed_plans = _generate_graph_plans(graph, home_map, options)\n\n        assert len(closed_plans) == num_part_groups\n\n    def test_plan_generator_two_conv2d_with_slice(FLASH, SRAM, TwoConv2DWithSliceGraph):\n        num_part_groups = 4  # Note this is not 6 because 'slice' has an opaque Propagator\n        graph = TwoConv2DWithSliceGraph\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            stripe_factors=4,\n            max_plan_size=10,\n        )\n\n        closed_plans = _generate_graph_plans(graph, home_map, options)\n\n        assert len(closed_plans) == num_part_groups\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_propagator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom math import isclose\nfrom tvm.contrib.ethosu.cascader import StripeConfig, Propagator\n\n\ndef test_propagator():\n    transform = [\n        [1, 0, 0, 0],\n        [0, 1 / 2, 0, 0],\n        [0, 0, -1, 0],\n        [0, 0, 0, 1],\n    ]\n    offset = [-1, 1, 2]\n    propagator = Propagator(\n        transform=transform,\n        offset=offset,\n    )\n    assert list(propagator.offset) == offset\n    for i, row in enumerate(transform):\n        for j, value in enumerate(row):\n            assert isclose(propagator.transform[i][j], value)\n\n\n@pytest.mark.parametrize(\n    [\"propagator\", \"input_stripe_config\", \"output_stripe_config\"],\n    [\n        (\n            Propagator(\n                transform=[\n                    [1, 0, 0, 0, 0],\n                    [0, 1, 0, 0, 0],\n                    [0, 0, 0, 1 / 16, 0],\n                    [0, 0, 1, 0, 0],\n                    [0, 0, 0, 0, 16],\n                    [0, 0, 0, 0, 1],\n                ],\n                offset=[0, 0, 0, 0, 0],\n            ),\n            StripeConfig(\n                shape=[1, 12, 14, 36],\n                extent=[1, 24, 18, 72],\n                strides=[1, 12, 14, 36],\n                order=[1, 2, 3, 4],\n                stripes=[1, 2, 2, 2],\n                offset=[0, 0, 0, 0],\n            ),\n            StripeConfig(\n                shape=[1, 12, 3, 14, 16],\n                extent=[1, 24, 5, 18, 16],\n                strides=[1, 12, 2.25, 14, 0],\n                order=[1, 2, 4, 3, 0],\n                stripes=[1, 2, 2, 2, 1],\n                offset=[0, 0, 0, 0, 0],\n            ),\n        ),\n        (\n            Propagator(\n                transform=[\n                    [0.5, 0, 0],\n                    [0, 0.5, 0],\n                    [0, 0, 1],\n                ],\n                offset=[0, 0],\n            ),\n            StripeConfig(\n                shape=[3, 5],\n                extent=[27, 50],\n                strides=[3, 5],\n                order=[1, 2],\n                stripes=[9, 10],\n                offset=[0, 0],\n            ),\n            StripeConfig(\n                shape=[2, 3],\n                extent=[14, 25],\n                strides=[1.5, 2.5],\n                order=[1, 2],\n                stripes=[9, 10],\n                offset=[0, 0],\n            ),\n        ),\n        (\n            Propagator(\n                transform=[\n                    [2, 0, 0, 4],\n                    [0, 1, 0, 2],\n                    [0, 0, 0, 8],\n                    [0, 0, 0, 1],\n                ],\n                offset=[-2, -1, 0],\n            ),\n            StripeConfig(\n                shape=[4, 6, 32],\n                extent=[48, 60, 64],\n                strides=[4, 6, 32],\n                order=[1, 2, 3],\n                stripes=[12, 10, 2],\n                offset=[0, 0, 0],\n            ),\n            StripeConfig(\n                shape=[12, 8, 8],\n                extent=[100, 62, 8],\n                strides=[8, 6, 0],\n                order=[1, 2, 0],\n                stripes=[12, 10, 1],\n                offset=[-2, -1, 0],\n            ),\n        ),\n    ],\n)\ndef test_propagate(propagator, input_stripe_config, output_stripe_config):\n    result_stripe_config = propagator.propagate(input_stripe_config)\n    assert result_stripe_config == output_stripe_config\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_proposal_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nfrom tvm.contrib.ethosu.cascader.proposal_generator import generate_proposals\n\nfrom .infra import make_simple_home_map, make_options, ethosu_enabled\n\n\nif ethosu_enabled:\n\n    def test_generate_proposals(FLASH, SRAM, TwoConv2DGraph):\n        graph = TwoConv2DGraph\n        min_sram = 3700\n        max_sram = 11700\n        input_configs = 1\n        parts = 2\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=32,\n            stripe_factors=4,\n            max_plan_size=10,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n\n        for proposal in proposals:\n            assert 0 < len(proposal.plans) <= parts\n            assert len(proposal.input_tensor_configs) == input_configs\n            assert len(proposal.part_group) == parts\n            assert min_sram < proposal.memory_usage < max_sram\n            assert proposal.cycles > 0\n\n    def test_generate_proposals_binary(FLASH, SRAM, BinaryGraph):\n        graph = BinaryGraph\n        input_configs = 2\n        parts = 3\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=32,\n            stripe_factors=4,\n            max_plan_size=10,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n\n        for proposal in proposals:\n            assert 0 < len(proposal.plans) <= parts\n            assert len(proposal.input_tensor_configs) == input_configs\n            assert len(proposal.part_group) == parts\n            assert proposal.cycles > 0\n\n    def test_generate_proposals_mobilenetv1_start(FLASH, SRAM, MobileNetv1StartGraph):\n        graph = MobileNetv1StartGraph\n        min_sram = 200000\n        max_sram = 1300000\n        input_configs = 1\n        parts = 8\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=32,\n            stripe_factors=5,\n            max_plan_size=10,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n\n        for proposal in proposals:\n            assert 0 < len(proposal.plans) <= parts\n            assert len(proposal.input_tensor_configs) == input_configs\n            assert len(proposal.part_group) == parts\n            assert min_sram < proposal.memory_usage < max_sram\n            assert proposal.cycles > 0\n\n    def test_generate_proposals_mobilenetv1(FLASH, SRAM, MobileNetv1Graph):\n        graph = MobileNetv1Graph\n        min_sram = 200000\n        max_sram = 1300000\n        input_configs = 1\n        parts = 27\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=32,\n            stripe_factors=5,\n            max_plan_size=10,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n\n        for proposal in proposals:\n            assert 0 < len(proposal.plans) <= parts\n            assert len(proposal.input_tensor_configs) == input_configs\n            assert len(proposal.part_group) == parts\n            assert min_sram < proposal.memory_usage < max_sram\n            assert proposal.cycles > 0\n\n    def test_generate_proposals_mobilenetv2diamond(FLASH, SRAM, MobileNetv2DiamondGraph):\n        graph = MobileNetv2DiamondGraph\n        min_sram = 370000\n        max_sram = 990000\n        input_configs = 1\n        parts = 5\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=64,\n            stripe_factors=5,\n            max_plan_size=10,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n\n        for proposal in proposals:\n            assert 0 < len(proposal.plans) <= parts\n            assert len(proposal.input_tensor_configs) == input_configs\n            assert len(proposal.part_group) == parts\n            assert min_sram < proposal.memory_usage < max_sram\n            assert proposal.cycles > 0\n\n    def test_generate_proposals_mobilenetv1_disable_striping(FLASH, SRAM, MobileNetv1Graph):\n        graph = MobileNetv1Graph\n        home_map = make_simple_home_map(graph, SRAM, FLASH)\n        options = make_options(\n            cascade_region=SRAM,\n            max_proposals=32,\n            stripe_factors=5,\n            max_plan_size=10,\n            enable_striping=False,\n        )\n\n        proposals = generate_proposals(graph, home_map, options)\n        assert len(proposals) == 1\n        proposal = proposals[0]\n        for plan in proposal.plans:\n            for stripe_config in plan.output_config.stripe_configs:\n                for shape_dim, stride_dim in list(zip(stripe_config.shape, stripe_config.strides)):\n                    # The striding and shape sizes in each dimension should be the same\n                    # if striping is disabled\n                    assert int(shape_dim) == int(stride_dim)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position, invalid-name\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm.contrib.ethosu.cascader as cs\n\nfrom . import infra\n\n\ndef test_cascade(SRAM, FLASH, TwoConv2DWithSliceTE, TwoConv2DTE, MobileNetv1StartTE, MobileNetv1TE):\n    fixtures = [\n        TwoConv2DTE,\n        TwoConv2DWithSliceTE,\n        MobileNetv1StartTE,\n        MobileNetv1TE,\n    ]\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    for sch, te_graph, const_dict in fixtures:\n        options = infra.make_options(\n            cascade_region=SRAM,\n            max_proposals=64,\n            stripe_factors=4,\n            max_plan_size=10,\n            max_open_plans=8,\n            max_closed_plans=32,\n            always_copy_size=1024,\n            disable_pareto_plans=False,\n            disable_pareto_proposals=False,\n        )\n        cs.cascade(sch, te_graph, const_dict, options, SRAM, FLASH, [SRAM], device_config)\n\n\ndef test_compute_cycles_annotation(SRAM, FLASH, TwoConv2DTE):\n    device_config = cs.EthosuDeviceConfig(\"ethos-u55-256\")\n    options = infra.make_options(\n        cascade_region=SRAM,\n        max_proposals=64,\n        stripe_factors=4,\n        max_plan_size=10,\n        max_open_plans=8,\n        max_closed_plans=32,\n        always_copy_size=1024,\n        disable_pareto_plans=False,\n        disable_pareto_proposals=False,\n        enable_striping=False,\n    )\n    sch, te_graph, const_dict = TwoConv2DTE\n    cs.cascade(sch, te_graph, const_dict, options, SRAM, FLASH, [SRAM], device_config)\n\n    # Stages that should have compute cycle annotations\n    # [copy, copy, conv2d, copy, conv2d]\n    stages = [6, 8, 9, 18, 19]\n    # Expected hints for each operation\n    compute_cycles_hints = [4096, 5120, 1440, 2560, 3072]\n\n    for stage, compute_cycles_hint in zip(stages, compute_cycles_hints):\n        op = sch.stages[stage]\n        op_iter_vars = op.leaf_iter_vars[0]\n        op_attrs = op.iter_var_attrs[op_iter_vars]\n        assert op_attrs.pragma_keys[0] == \"compute_cycles_hint\"\n        assert op_attrs.pragma_values[0] == compute_cycles_hint\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_stripe_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom tvm.contrib.ethosu.cascader.stripe_config import StripeConfig, count_stripes\n\n\ndef test_stripe_config():\n    shape = [1, 2, 3]\n    extent = [2, 3, 4]\n    strides = [3, 4, 5]\n    order = [4, 5, 6]\n    stripes = [5, 6, 7]\n    offset = [6, 7, 8]\n    hash_value = 3107995860559090954\n    stripe_config = StripeConfig(\n        shape=shape,\n        extent=extent,\n        strides=strides,\n        order=order,\n        stripes=stripes,\n        offset=offset,\n    )\n    assert stripe_config.shape == shape\n    assert stripe_config.extent == extent\n    assert stripe_config.strides == strides\n    assert stripe_config.order == order\n    assert stripe_config.stripes == stripes\n    assert stripe_config.offset == offset\n    assert hash(stripe_config) == hash_value\n\n\n@pytest.mark.parametrize(\n    \"mismatch\", [None, \"shape\", \"extent\", \"strides\", \"order\", \"stripes\", \"offset\"]\n)\ndef test_stripe_config_equal(mismatch):\n    init_dict = {\n        \"shape\": [1, 2, 3],\n        \"extent\": [2, 3, 4],\n        \"strides\": [3, 4, 5],\n        \"order\": [4, 5, 6],\n        \"stripes\": [5, 6, 7],\n        \"offset\": [6, 7, 8],\n    }\n    stripe_config_a = StripeConfig(**init_dict)\n    if mismatch:\n        init_dict[mismatch] = [1, 1, 1]\n    stripe_config_b = StripeConfig(**init_dict)\n    if not mismatch:\n        assert stripe_config_a == stripe_config_b\n    else:\n        assert stripe_config_a != stripe_config_b\n\n\n@pytest.mark.parametrize(\n    [\"stripe_config\", \"expected_stripe_counts\"],\n    [\n        (\n            StripeConfig(\n                shape=[3, 3, 3],\n                extent=[9, 9, 9],\n                strides=[3, 3, 3],\n                order=[1, 2, 3],\n                stripes=[3, 3, 3],\n                offset=[0, 0, 0],\n            ),\n            {\n                (3, 3, 3): 27,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[3, 3],\n                extent=[10, 10],\n                strides=[2, 2],\n                order=[1, 2],\n                stripes=[5, 5],\n                offset=[0, 0],\n            ),\n            {\n                (3, 3): 16,\n                (2, 3): 4,\n                (3, 2): 4,\n                (2, 2): 1,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[3, 3, 9],\n                extent=[9, 9, 9],\n                strides=[3, 3, 0],\n                order=[1, 2, 3],\n                stripes=[3, 3, 1],\n                offset=[0, 0, 0],\n            ),\n            {\n                (3, 3, 9): 9,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[5, 5],\n                extent=[8, 8],\n                strides=[5, 5],\n                order=[1, 2],\n                stripes=[2, 2],\n                offset=[0, 0],\n            ),\n            {\n                (5, 5): 1,\n                (3, 5): 1,\n                (5, 3): 1,\n                (3, 3): 1,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[5, 5],\n                extent=[8, 8],\n                strides=[5, 5],\n                order=[1, 2],\n                stripes=[2, 2],\n                offset=[-1, -2],\n            ),\n            {\n                (4, 3): 2,\n                (4, 5): 2,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[13, 7],\n                extent=[128, 73],\n                strides=[13, 7],\n                order=[1, 2],\n                stripes=[11, 12],\n                offset=[-10, -5],\n            ),\n            {\n                (3, 1): 1,\n                (3, 2): 1,\n                (8, 7): 10,\n                (8, 2): 1,\n                (13, 7): 90,\n                (13, 1): 9,\n                (8, 1): 1,\n                (3, 7): 10,\n                (13, 2): 9,\n            },\n        ),\n    ],\n)\ndef test_count_stripes(stripe_config, expected_stripe_counts):\n    assert count_stripes(stripe_config) == expected_stripe_counts\n\n\n@pytest.mark.parametrize(\n    [\"stripe_config\", \"expected_stripe_counts\"],\n    [\n        (\n            StripeConfig(\n                shape=[4, 4],\n                extent=[16, 16],\n                strides=[2, 2],\n                order=[1, 2],\n                stripes=[7, 7],\n                offset=[0, 0],\n            ),\n            {\n                (4, 4): 1,\n                (2, 4): 6,\n                (4, 2): 6,\n                (2, 2): 36,\n            },\n        ),\n        (\n            StripeConfig(\n                shape=[4, 4],\n                extent=[8, 8],\n                strides=[2, 2],\n                order=[1, 2],\n                stripes=[6, 3],\n                offset=[-5, 0],\n            ),\n            {\n                (1, 4): 2,\n                (2, 4): 3,\n                (2, 2): 6,\n                (1, 2): 4,\n            },\n        ),\n    ],\n)\ndef test_count_stripes_sliding_window(stripe_config, expected_stripe_counts):\n    assert count_stripes(stripe_config, enable_sliding_window=True) == expected_stripe_counts\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/cascader/test_tensor_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.contrib.ethosu.cascader import (\n    StripeConfig,\n    Tensor,\n    MemoryRegion,\n    TensorConfig,\n    TensorConfigState,\n    BufferMode,\n)\n\nimport pytest\n\n\ndef test_tensor_config(DRAM, SRAM):\n    stripe_config = StripeConfig(\n        shape=[1, 2, 3],\n        extent=[2, 3, 4],\n        strides=[3, 4, 5],\n        order=[4, 5, 6],\n        stripes=[5, 6, 7],\n        offset=[6, 7, 8],\n    )\n    tensor = Tensor(\n        shape=[10, 10, 10],\n        dtype=\"int8\",\n    )\n    home_region = DRAM\n    state = TensorConfigState.BOUNDARY\n    buffer_mode = BufferMode.ROLLING\n    copy_tensor = True\n    copy_region = SRAM\n    tensor_config = TensorConfig(\n        tensor=tensor,\n        home_region=home_region,\n        state=state,\n        buffer_mode=buffer_mode,\n        stripe_configs=[stripe_config],\n        copy_tensor=copy_tensor,\n        copy_region=copy_region,\n    )\n\n    assert tensor_config.tensor == tensor\n    assert tensor_config.home_region == home_region\n    assert tensor_config.state == state\n    assert tensor_config.buffer_mode == buffer_mode\n    assert tensor_config.stripe_configs == [stripe_config]\n    assert tensor_config.copy_tensor == copy_tensor\n    assert tensor_config.copy_region == copy_region\n    assert hash(tensor_config) != 0\n\n\ndef test_get_rolling_buffer(DRAM):\n    stripe_config = StripeConfig(\n        shape=[9, 4, 7],\n        extent=[9, 16, 21],\n        strides=[3, 5, 7],\n        order=[1, 3, 2],\n        stripes=[1, 3, 3],\n        offset=[0, 0, 0],\n    )\n    tensor = Tensor(shape=[9, 16, 21], dtype=\"int32\", compression_ratio=0.5)\n    tensor_config = TensorConfig(\n        tensor=tensor,\n        home_region=DRAM,\n        state=TensorConfigState.BOUNDARY,\n        buffer_mode=BufferMode.ROLLING,\n        stripe_configs=[stripe_config],\n    )\n\n    assert tensor_config.get_buffer_size() == 2016\n\n\ndef test_get_recompute_buffer(DRAM):\n    stripe_config = StripeConfig(\n        shape=[4, 5, 7],\n        extent=[6, 7, 14],\n        strides=[2, 3, 7],\n        order=[1, 3, 2],\n        stripes=[2, 2, 2],\n        offset=[0, 0, 0],\n    )\n    tensor = Tensor(shape=[6, 7, 14], dtype=\"int32\", compression_ratio=0.5)\n    tensor_config = TensorConfig(\n        tensor=tensor,\n        home_region=DRAM,\n        state=TensorConfigState.BOUNDARY,\n        buffer_mode=BufferMode.RECOMPUTE,\n        stripe_configs=[stripe_config],\n    )\n\n    assert tensor_config.get_buffer_size() == 280\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/infra.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis module provides infrastructure to verify the correctness of\nthe command stream produced.\nCurrently it will invoke vela to generate a vela-optimized tflite\nin which the command stream is contained as a custom operator.\nThis class include methods to parse the custom operator to extract\nthe command stream and perform an equivalency check for single operator\ntest cases.\n\"\"\"\nfrom typing import List\n\nimport os\nimport struct\nimport numpy as np\nimport tflite.Model\nimport math\nfrom enum import IntEnum\nimport tensorflow as tf\n\nfrom ethosu.vela.register_command_stream_generator import CmdMode\nfrom ethosu.vela.register_command_stream_generator import cmd0\nfrom ethosu.vela.register_command_stream_generator import cmd1\n\nimport tvm\nfrom tvm import relay\nimport tvm.relay.backend.contrib.ethosu.op as ethosu_ops\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.relay.expr_functor import ExprMutator\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.backend.contrib.ethosu import preprocess\nimport tvm.relay.testing.tf as tf_testing\nfrom tvm import WorkspaceMemoryPools, WorkspacePoolInfo, PoolInfoProperties\n\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.testing.aot import (\n    AOTCompiledTestModel,\n    AOTDataLinkage,\n    AOTTestModel,\n    AOTTestRunner,\n    compile_models,\n    run_and_check,\n)\n\n\nclass AttachType(IntEnum):\n    kGroupRoot = 1\n    kInline = 2\n    kInlinedAlready = 3\n    kScope = 4\n    kScanUpdate = 5\n\n\ndef print_payload(payload):\n    cmds = deserialize_command_stream(payload)\n    for cmd_val in cmds:\n        cmd, val = parse_cmd(cmd_val)\n        s = str(cmd)\n        s = s.ljust(40)\n        s += str(val)\n        print(s)\n\n\ndef parse_cmd(binary_cmd):\n    code = binary_cmd[0] & 0x0000FFFF  # lower 16 bits\n    param = binary_cmd[0] >> 16  # higher 16 bits\n    payload_mode = CmdMode(code & CmdMode.Mask)\n    if payload_mode == CmdMode.Payload32:\n        command = cmd1(code & CmdMode.CmdOpMask)\n        value = binary_cmd[1]\n    else:\n        command = cmd0(code & CmdMode.CmdOpMask)\n        value = param\n    return command, value\n\n\ndef deserialize_command_stream(blob):\n    assert isinstance(blob, bytes)\n    payload_bytes = struct.unpack(\"<{0}I\".format(len(blob) // 4), blob)\n    cmms = []\n    # remove_header\n    payload_bytes = payload_bytes[8:]\n    idx = 0\n    while idx < len(payload_bytes):\n        cmd = []\n        code = payload_bytes[idx]\n        idx += 1\n        cmd.append(code)\n        payload_mode = CmdMode(code & CmdMode.Mask)\n        if payload_mode == CmdMode.Payload32:\n            value = payload_bytes[idx]\n            idx += 1\n            cmd.append(value)\n        cmms.append(cmd)\n    return cmms\n\n\ndef _get_workspace_size_define_macro(pool_name: str, model_name=\"default\") -> str:\n    \"\"\"This function converts pool names to compiler generated\n    workspace pool size macros\"\"\"\n\n    prefix = \"TVMGEN_\" + model_name.upper() + \"_\"\n    postfix = \"_WORKSPACE_POOL_SIZE\"\n    return prefix + pool_name.upper() + postfix\n\n\ndef create_test_runner(\n    accel=\"ethos-u55-256\",\n    enable_usmp=True,\n    enable_cascader=False,\n    enable_striping=False,\n    workspace_pools=None,\n):\n\n    file_dir = os.path.dirname(os.path.abspath(__file__))\n    test_root = os.path.join(file_dir, \"reference_system\")\n    _, ethosu_variant, ethosu_macs = accel.split(\"-\")\n    ethosu_variant = ethosu_variant.upper()\n\n    prologue = \"\"\"\n    uart_init();\n    EthosuInit();\n\n    struct ethosu_driver* ethos_u = ethosu_reserve_driver();\n    \"\"\"\n\n    if workspace_pools:\n        for pool in workspace_pools.pools:\n            prologue = (\n                prologue\n                + f\"\"\"\n    #ifdef {_get_workspace_size_define_macro(pool.pool_name)}\n    __attribute__((section(\".bss.noinit.tvm\"), aligned(16)))\n    static uint8_t {pool.pool_name}[{_get_workspace_size_define_macro(pool.pool_name)}];\n    #endif\n\n            \"\"\"\n            )\n\n    return AOTTestRunner(\n        makefile=\"corstone300\",\n        prologue=prologue,\n        epilogue=\"\"\"\n        ethosu_release_driver(ethos_u);\n        \"\"\",\n        includes=[\"uart.h\", \"ethosu_55.h\", \"ethosu_mod.h\", \"hard_fault.h\"],\n        parameters={\n            \"ETHOSU_TEST_ROOT\": test_root,\n            \"NPU_MACS\": ethosu_macs,\n            \"NPU_VARIANT\": ethosu_variant,\n        },\n        pass_config={\n            \"relay.ext.ethos-u.options\": {\n                \"accelerator_config\": accel,\n                \"enable_cascader\": enable_cascader,\n                \"enable_striping\": enable_striping,\n            },\n            \"tir.usmp.enable\": enable_usmp,\n            \"tir.usmp.algorithm\": \"hill_climb\",\n            \"tir.disable_storage_rewrite\": enable_usmp,\n        },\n    )\n\n\ndef build_source(\n    module,\n    inputs,\n    outputs,\n    test_runner,\n    output_tolerance=0,\n    workspace_pools=None,\n):\n    return compile_models(\n        models=AOTTestModel(\n            module=module,\n            inputs=inputs,\n            outputs=outputs,\n            output_tolerance=output_tolerance,\n            extra_memory_in_bytes=0,\n        ),\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        workspace_memory_pools=workspace_pools,\n        workspace_byte_alignment=16,\n        pass_config=test_runner.pass_config,\n    )\n\n\ndef verify_source(models: List[AOTCompiledTestModel], test_runner):\n    \"\"\"\n    This method verifies the generated source from an NPU module by building it and running on an FVP.\n    \"\"\"\n    interface_api = \"c\"\n    run_and_check(\n        models,\n        test_runner,\n        interface_api,\n        workspace_byte_alignment=16,\n        data_linkage=AOTDataLinkage(section=\"ethosu_scratch\", alignment=16),\n    )\n\n\nclass InputGenerator:\n    def __init__(self, random_state):\n        self._random_state = random_state\n\n    def generate(self, size, dtype):\n        if dtype == np.float32:\n            print(\"random float32\")\n            return self._random_state.uniform(-1, 1, size).astype(dtype)\n        else:\n            print(\"random (u)int min=%d max=%d\", np.iinfo(dtype).min, np.iinfo(dtype).max)\n            low = np.iinfo(dtype).min\n            high = np.iinfo(dtype).max + 1\n            return self._random_state.randint(low, high, size, dtype)\n\n\ndef generate_ref_data_tflite(model):\n    \"\"\"\n    This method generates reference data by running the specified model on tflite with random input data.\n    The random input data and generated output data are returned.\n    \"\"\"\n    expected_output_data = {}\n\n    interpreter = tf.lite.Interpreter(\n        model_content=model,\n        experimental_op_resolver_type=tf.lite.experimental.OpResolverType.BUILTIN_REF,\n    )\n\n    interpreter.allocate_tensors()\n\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    # Initialize random generators with a fixed seed to get deterministic results\n    seed = 0\n    random_state = np.random.RandomState(seed)\n\n    inputgen = InputGenerator(random_state)\n\n    # Generate input data\n    input_data = {\n        input_detail[\"name\"]: inputgen.generate(\n            input_detail[\"shape\"],\n            input_detail[\"dtype\"],\n        )\n        for input_detail in input_details\n    }\n    input_index = {input_detail[\"name\"]: input_detail[\"index\"] for input_detail in input_details}\n\n    for input_name in input_data.keys():\n        data = input_data[input_name]\n        index = input_index[input_name]\n        interpreter.set_tensor(index, data)\n    interpreter.invoke()\n\n    expected_output_data = {\n        output_detail[\"name\"]: interpreter.get_tensor(output_detail[\"index\"])\n        for output_detail in output_details\n    }\n\n    return input_data, expected_output_data\n\n\ndef get_tflite_model(model_url):\n    \"\"\"Get a TFLite model from URL.\"\"\"\n    tflite_model_file = tf_testing.get_workload_official(model_url[0], model_url[1])\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    return tflite_model_buf\n\n\ndef get_tflite_graph(tf_func, shapes, ranges=None):\n    tensor_specs = [tf.TensorSpec(shape, dtype=tf.float32) for shape in shapes]\n    if not ranges:\n        ranges = [(0, 1) for _ in shapes]\n    concrete_func = tf_func.get_concrete_function(*tensor_specs)\n\n    # Convert the model\n    def representative_dataset():\n        for _ in range(100):\n            inputs = []\n            for i, shape in enumerate(shapes):\n                data = np.random.uniform(\n                    low=ranges[i][0], high=ranges[i][1], size=tuple(shape)\n                ).astype(\"float32\")\n                inputs.append(data)\n\n            yield inputs\n\n    converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    converter.representative_dataset = representative_dataset\n    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n    converter.inference_input_type = tf.int8\n    converter.inference_output_type = tf.int8\n    tflite_graph = converter.convert()\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, params = relay.frontend.from_tflite(tflite_model)\n    mod = partition_for_ethosu(relay_module, params)\n    return mod, tflite_graph\n\n\ndef compare_ethosu_with_reference(\n    mod,\n    input_data,\n    output_data,\n    accel_type: str,\n    output_tolerance=0,\n    print_cmm=False,\n    enable_cascader=None,\n):\n    if enable_cascader is None:\n        enable_cascader = \"u65\" not in accel_type\n    pool_name = \"my_memory_pool\"\n    host_target = tvm.target.Target(\"c\")\n    ethosu_target = tvm.target.Target(\"ethos-u\")\n    workspace_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                pool_name,\n                [host_target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=2400000,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            )\n        ]\n    )\n    test_runner = create_test_runner(\n        accel_type,\n        enable_usmp=True,\n        enable_cascader=enable_cascader,\n        enable_striping=False,\n        workspace_pools=workspace_pools,\n    )\n    compiled_models = build_source(\n        mod,\n        input_data,\n        output_data,\n        test_runner,\n        workspace_pools=workspace_pools,\n        output_tolerance=output_tolerance,\n    )\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    if print_cmm:\n        get_artifacts = tvm._ffi.get_global_func(\"runtime.module.ethos-u.get_artifacts\")\n        compilation_artifacts = get_artifacts(ethosu_module)\n        cmms = bytes.fromhex(compilation_artifacts[0].command_stream)\n        print_payload(cmms)\n\n    verify_source(compiled_models, test_runner)\n\n\ndef compare_tvm_with_tflite(\n    tf_func,\n    shapes,\n    accel_type,\n    ranges=None,\n    output_tolerance=0,\n    print_cmm=False,\n    enable_cascader=None,\n):\n    mod, tflite_graph = get_tflite_graph(tf_func, shapes, ranges)\n\n    # Generate reference data\n    input_data, output_data = generate_ref_data_tflite(tflite_graph)\n\n    compare_ethosu_with_reference(\n        mod,\n        input_data,\n        output_data,\n        accel_type,\n        output_tolerance=output_tolerance,\n        print_cmm=print_cmm,\n        enable_cascader=enable_cascader,\n    )\n\n\nclass EthosUAnnotator(ExprMutator):\n    \"\"\"Annotate entire graph for Ethos-U offload\"\"\"\n\n    def __init__(self):\n        super(EthosUAnnotator, self).__init__()\n        self.compiler = \"ethos-u\"\n        self.last_call = True\n\n    def visit_call(self, call):\n        curr_last = self.last_call\n        self.last_call = False\n\n        params = []\n        for arg in call.args:\n            param = super().visit(arg)\n            if isinstance(param, relay.expr.Var):\n                param = compiler_begin(param, self.compiler)\n            params.append(param)\n\n        new_call = relay.Call(call.op, params, call.attrs)\n        if curr_last:\n            new_call = compiler_end(new_call, self.compiler)\n        return new_call\n\n    def visit_constant(self, constant):\n        new_constant = compiler_begin(constant, self.compiler)\n        return new_constant\n\n\ndef create_ethosu_partition(mod):\n    mod[\"main\"] = EthosUAnnotator().visit(mod[\"main\"])\n    mod = relay.transform.MergeCompilerRegions()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.PartitionGraph()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = preprocess.preprocess_ext_io()(mod)\n    return mod\n\n\ndef generate_weights_data(shape, dtype):\n    size = 1\n    for dim in shape:\n        size *= dim\n    return (np.arange(size) % 255).reshape(shape).astype(dtype)\n\n\ndef get_convolutional_args(call, include_buffers=False, remove_constants=False):\n    \"\"\"A method to extract the arguments from conv2d or depthwise_conv2d extern call.\"\"\"\n    args = call.args\n    conv_args = []\n    remove_indices = [0]\n\n    if remove_constants:\n        remove_indices += [41, 42, 44, 45]\n\n    for i, arg in enumerate(args):\n        if i in remove_indices:\n            continue\n        elif isinstance(arg, tvm.tir.expr.IntImm) or isinstance(arg, tvm.tir.expr.FloatImm):\n            conv_args.append(arg.value)\n        elif isinstance(arg, tvm.tir.expr.BufferLoad) and not include_buffers:\n            conv_args.append(arg.indices[0])\n        else:\n            conv_args.append(arg)\n\n    return conv_args\n\n\ndef compute_ofm_shape(ifm_shape, padding, kernel_shape, strides, dilation=[1, 1]):\n    assert len(strides) == 2\n    assert len(dilation) == 2\n    assert len(kernel_shape) == 2\n    if isinstance(padding, tuple):\n        h = (\n            ifm_shape[1] - (kernel_shape[0] - 1) * dilation[0] + padding[0] + padding[2]\n        ) // strides[0]\n        w = (\n            ifm_shape[2] - (kernel_shape[1] - 1) * dilation[1] + padding[1] + padding[3]\n        ) // strides[1]\n    elif padding.lower() == \"valid\":\n        h = math.ceil((ifm_shape[1] - (kernel_shape[0] - 1) * dilation[0]) / strides[0])\n        w = math.ceil((ifm_shape[2] - (kernel_shape[1] - 1) * dilation[1]) / strides[1])\n    elif padding.lower() == \"same\":\n        h = math.ceil(ifm_shape[1] / strides[0])\n        w = math.ceil(ifm_shape[2] / strides[1])\n    ofm_shape = [ifm_shape[0], h, w, ifm_shape[3]]\n    return ofm_shape\n\n\ndef compute_padding_shape(ifm_shape, ofm_shape, padding, kernel_shape, strides, dilation=[1, 1]):\n    assert len(strides) == 2\n    assert len(dilation) == 2\n    assert len(kernel_shape) == 2\n    if padding.lower() == \"valid\":\n        return [0, 0, 0, 0]\n    if padding.lower() == \"same\":\n        effective_kernel_shape = [\n            dilation[0] * (kernel_shape[0] - 1) + 1,\n            dilation[1] * (kernel_shape[1] - 1) + 1,\n        ]\n        pad_along_height = max(\n            (ofm_shape[1] - 1) * strides[0] + effective_kernel_shape[0] - ifm_shape[1], 0\n        )\n        pad_along_width = max(\n            (ofm_shape[2] - 1) * strides[1] + effective_kernel_shape[1] - ifm_shape[2], 0\n        )\n        pad_top = pad_along_height // 2\n        pad_bottom = pad_along_height - pad_top\n        pad_left = pad_along_width // 2\n        pad_right = pad_along_width - pad_left\n        return [pad_top, pad_left, pad_bottom, pad_right]\n\n\ndef make_ethosu_conv2d(\n    ifm,\n    ifm_channels,\n    ofm_channels,\n    kernel_shape,\n    padding,\n    strides,\n    dilation,\n    lut=relay.const([], dtype=\"int8\"),\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    weight_dtype=\"int8\",\n    scale_bias_dtype=\"uint8\",\n    rounding_mode=\"TFL\",\n    upscale=\"NONE\",\n):\n    # conv params\n    weight_shape = (ofm_channels, kernel_shape[0], kernel_shape[1], ifm_channels)\n    padding = get_pad_tuple(padding, kernel_shape)\n\n    scale_bias_data = generate_weights_data((weight_shape[0], 10), scale_bias_dtype)\n    scale_bias = relay.const(scale_bias_data, dtype=scale_bias_dtype)\n    weight_data = generate_weights_data(weight_shape, weight_dtype)\n    weight = relay.const(weight_data, dtype=weight_dtype)\n    conv = ethosu_ops.ethosu_conv2d(\n        ifm,\n        weight,\n        scale_bias,\n        lut=lut,\n        ifm_scale=0.5,\n        ifm_zero_point=10,\n        weight_zero_point=12,\n        ofm_scale=0.25,\n        ofm_zero_point=14,\n        kernel_shape=kernel_shape,\n        ofm_channels=ofm_channels,\n        strides=strides,\n        padding=padding,\n        dilation=dilation,\n        activation=activation,\n        clip_min=10 if activation == \"CLIP\" else 0,\n        clip_max=100 if activation == \"CLIP\" else 0,\n        rounding_mode=rounding_mode,\n        upscale=upscale,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    return conv\n\n\ndef make_ethosu_depthwise_conv2d(\n    ifm,\n    channels,\n    kernel_shape,\n    padding,\n    strides,\n    dilation,\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    weight_dtype=\"int8\",\n    scale_bias_dtype=\"uint8\",\n    rounding_mode=\"TFL\",\n):\n    # params\n    weight_shape = (channels, kernel_shape[0], kernel_shape[1], 1)\n    padding = get_pad_tuple(padding, kernel_shape)\n\n    scale_bias_data = generate_weights_data((weight_shape[0], 10), scale_bias_dtype)\n    scale_bias = relay.const(scale_bias_data, dtype=scale_bias_dtype)\n    weight_data = generate_weights_data(weight_shape, weight_dtype)\n    weight = relay.const(weight_data, dtype=weight_dtype)\n    depthwise = ethosu_ops.ethosu_depthwise_conv2d(\n        ifm,\n        weight,\n        scale_bias,\n        lut=relay.const([], dtype=\"int8\"),\n        ifm_scale=0.6,\n        ifm_zero_point=11,\n        weight_zero_point=13,\n        ofm_scale=0.26,\n        ofm_zero_point=15,\n        kernel_shape=kernel_shape,\n        ofm_channels=channels,\n        strides=strides,\n        padding=padding,\n        dilation=dilation,\n        activation=activation,\n        clip_min=15 if activation == \"CLIP\" else 0,\n        clip_max=105 if activation == \"CLIP\" else 0,\n        rounding_mode=rounding_mode,\n        upscale=\"NONE\",\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    return depthwise\n\n\ndef get_pooling_args(call, include_buffers=False):\n    args = call.args\n    pooling_args = []\n\n    for i, arg in enumerate(args):\n        if isinstance(arg, tvm.tir.expr.IntImm) or isinstance(arg, tvm.tir.expr.FloatImm):\n            pooling_args.append(arg.value)\n        elif isinstance(arg, tvm.tir.expr.BufferLoad) and not include_buffers:\n            pooling_args.append(arg.indices[0])\n        else:\n            pooling_args.append(arg)\n\n    return pooling_args\n\n\ndef make_ethosu_pooling(\n    ifm,\n    pooling_type,\n    pool_shape,\n    ofm_channels,\n    strides,\n    padding,\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    rounding_mode=\"TFL\",\n    upscale=\"NONE\",\n):\n    pooling = ethosu_ops.ethosu_pooling(\n        ifm,\n        lut=relay.const([], dtype=\"int8\"),\n        pooling_type=pooling_type,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        pool_shape=pool_shape,\n        ofm_channels=ofm_channels,\n        strides=strides,\n        padding=padding,\n        activation=activation,\n        clip_min=10 if activation == \"CLIP\" else 0,\n        clip_max=100 if activation == \"CLIP\" else 0,\n        rounding_mode=rounding_mode,\n        upscale=upscale,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    return pooling\n\n\ndef get_binary_elementwise_args(call, include_buffers=False):\n    args = call.args\n    binary_elementwise_args = []\n\n    for i, arg in enumerate(args):\n        if isinstance(arg, tvm.tir.expr.IntImm) or isinstance(arg, tvm.tir.expr.FloatImm):\n            binary_elementwise_args.append(arg.value)\n        elif isinstance(arg, tvm.tir.expr.BufferLoad) and not include_buffers:\n            binary_elementwise_args.append(arg.indices[0])\n        else:\n            binary_elementwise_args.append(arg)\n\n    return binary_elementwise_args\n\n\ndef make_ethosu_binary_elementwise(\n    ifm,\n    ifm2,\n    ifm_channels,\n    ifm2_channels,\n    operator_type,\n    ofm_dtype,\n    reversed_operands=False,\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ifm2_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    rounding_mode=\"TFL\",\n):\n    ethosu_binary_elementwise = ethosu_ops.ethosu_binary_elementwise(\n        ifm=ifm,\n        ifm2=ifm2,\n        lut=relay.const([], dtype=\"int8\"),\n        operator_type=operator_type,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ifm2_scale=1,\n        ifm2_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        ifm_channels=ifm_channels,\n        ifm2_channels=ifm2_channels,\n        reversed_operands=reversed_operands,\n        activation=activation,\n        ofm_dtype=ofm_dtype,\n        clip_min=10 if activation == \"CLIP\" else 0,\n        clip_max=100 if activation == \"CLIP\" else 0,\n        rounding_mode=rounding_mode,\n        ifm_layout=ifm_layout,\n        ifm2_layout=ifm2_layout,\n        ofm_layout=ofm_layout,\n    )\n    return ethosu_binary_elementwise\n\n\ndef make_ethosu_identity(\n    ifm,\n    lut=relay.const([], dtype=\"int8\"),\n    ifm_scale=1,\n    ifm_zero_point=0,\n    ofm_scale=1,\n    ofm_zero_point=0,\n    activation=\"NONE\",\n):\n    identity = ethosu_ops.ethosu_identity(\n        ifm,\n        lut=lut,\n        ifm_scale=ifm_scale,\n        ifm_zero_point=ifm_zero_point,\n        ofm_scale=ofm_scale,\n        ofm_zero_point=ofm_zero_point,\n        activation=activation,\n    )\n    return identity\n\n\ndef make_ethosu_unary_elementwise(\n    ifm,\n    ofm_channels,\n    operator_type,\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    rounding_mode=\"TFL\",\n):\n    ethosu_unary_elementwise = ethosu_ops.ethosu_unary_elementwise(\n        ifm=ifm,\n        lut=relay.const([], dtype=\"int8\"),\n        operator_type=operator_type,\n        ifm_scale=1,\n        ifm_zero_point=0,\n        ofm_scale=1,\n        ofm_zero_point=0,\n        ofm_channels=ofm_channels,\n        activation=activation,\n        clip_min=10 if activation == \"CLIP\" else 0,\n        clip_max=100 if activation == \"CLIP\" else 0,\n        rounding_mode=rounding_mode,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    return ethosu_unary_elementwise\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/reference_system/ethosu_55.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_55_H_\n#define TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_55_H_\n\n/* Define Arm(R) Ethos(TM)-U55 specific IRQs & base address */\n#define ETHOSU_NPU_FAIL (1 << 4)\n#define ETHOSU_IRQ ((IRQn_Type)56)\n#define ETHOSU_BASE_ADDRESS ((void*)0x48102000)\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_55_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/reference_system/ethosu_mod.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_MOD_H_\n#define TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_MOD_H_\n\n#include <ARMCM55.h>\n// TODO(@grant-arm): Remove device specific information once RTOS support is available\n#include <ethosu_driver.h>\n#include <stdio.h>\n\n#include \"ethosu_55.h\"\n\nstruct ethosu_driver ethosu0_driver;\n\nvoid ethosuIrqHandler0() { ethosu_irq_handler(&ethosu0_driver); }\n\n// Initialize Arm(R) Ethos(TM)-U NPU driver\nint EthosuInit() {\n  if (ethosu_init(&ethosu0_driver, (void*)ETHOSU_BASE_ADDRESS, NULL, 0, 1, 1)) {\n    printf(\"Failed to initialize NPU.\\n\");\n    return -1;\n  }\n\n  // Assumes SCB->VTOR points to RW memory\n  NVIC_SetVector(ETHOSU_IRQ, (uint32_t)&ethosuIrqHandler0);\n  NVIC_EnableIRQ(ETHOSU_IRQ);\n\n  return 0;\n}\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOS_U_ETHOSU_MOD_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/reference_system/hard_fault.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n#ifndef TVM_RUNTIME_CONTRIB_ETHOS_U_HARD_FAULT_H_\n#define TVM_RUNTIME_CONTRIB_ETHOS_U_HARD_FAULT_H_\n\nstruct ExcContext {\n  uint32_t r0;\n  uint32_t r1;\n  uint32_t r2;\n  uint32_t r3;\n  uint32_t r12;\n  uint32_t lr;\n  uint32_t pc;\n  uint32_t xPsr;\n};\nvoid HardFault_Handler() {\n  int irq;\n  struct ExcContext* e;\n  uint32_t sp;\n  asm volatile(\n      \"mrs %0, ipsr            \\n\"  // Read IPSR (Exception number)\n      \"sub %0, #16             \\n\"  // Get it into IRQn_Type range\n      \"tst lr, #4              \\n\"  // Select the stack which was in use\n      \"ite eq                  \\n\"\n      \"mrseq %1, msp           \\n\"\n      \"mrsne %1, psp           \\n\"\n      \"mov %2, sp              \\n\"\n      : \"=r\"(irq), \"=r\"(e), \"=r\"(sp));\n  printf(\"Hard fault. irq=%d, pc=0x%08lu, lr=0x%08lu, xpsr=0x%08lu, sp=0x%08lu\\n\", irq, e->pc,\n         e->lr, e->xPsr, sp);\n  printf(\"%11s cfsr=0x%08lu bfar=0x%08lu\\n\", \"\", SCB->CFSR, SCB->BFAR);\n  printf(\"EXITTHESIM\\n\");\n  while (1 == 1)\n    ;\n}\n\n#endif  // TVM_RUNTIME_CONTRIB_ETHOS_U_HARD_FAULT_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_attr_passing.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu import util\n\n\ndef test_compiler_attr():\n    config = {\n        \"accelerator_config\": \"ethos-u55-32\",\n    }\n    with tvm.transform.PassContext(opt_level=3, config={\"relay.ext.ethos-u.options\": config}):\n        with tvm.target.Target(\"c\"):\n            compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n            accel_config_str = compiler_attrs.accelerator_config\n            assert accel_config_str == config[\"accelerator_config\"]\n\n\ndef test_compiler_attr_default():\n    default_config = {\n        \"accelerator_config\": \"ethos-u55-256\",\n    }\n    with tvm.transform.PassContext(opt_level=3):\n        with tvm.target.Target(\"c\"):\n            compiler_attrs = tvm.get_global_func(\"relay.ext.ethos-u.get_compiler_attrs\")()\n            accel_config_str = compiler_attrs.accelerator_config\n            assert accel_config_str == default_config[\"accelerator_config\"]\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\nimport tflite.Model\n\nimport tvm\nimport tensorflow as tf\nfrom tvm import relay\n\nfrom tvm.relay.backend.contrib.ethosu import util\n\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.testing.aot import generate_ref_data\n\nfrom . import infra\n\n\nACCEL_TYPES = [\"ethos-u55-256\", \"ethos-u55-128\", \"ethos-u55-64\", \"ethos-u55-32\", \"ethos-u65-256\"]\n\n\ndef is_u55_accel_type(accel_type):\n    return \"u55\" in accel_type\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES + [\"ethos-u65-512\"])\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 299, 299, 2), (1, 55, 55, 3)])\n@pytest.mark.parametrize(\"kernel_shape\", [(3, 2), (1, 3)])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (2, 1)), ((3, 2), (1, 1))])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"activation\", [\"NONE\", \"RELU\"])\ndef test_ethosu_conv2d_single(\n    ifm_shape,\n    kernel_shape,\n    strides,\n    dilation,\n    padding,\n    accel_type,\n    activation,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def conv2d(x):\n        # Use tf.nn API to create the model\n        tf_strides = [1, strides[0], strides[1], 1]\n        op = tf.nn.conv2d(\n            x,\n            filters=tf.constant(\n                np.random.uniform(size=[kernel_shape[0], kernel_shape[1], ifm_shape[3], 3]),\n                dtype=tf.float32,\n            ),\n            strides=tf_strides,\n            padding=padding,\n            dilations=dilation,\n        )\n        if activation == \"RELU\":\n            op = tf.nn.relu(op)\n        return op\n\n    infra.compare_tvm_with_tflite(conv2d, [ifm_shape], accel_type)\n\n\ndef test_tflite_conv2d_with_separate_pad():\n    np.random.seed(0)\n\n    ifm_shape = (1, 55, 34, 3)\n    kernel_shape = (3, 2)\n    strides = (1, 1)\n    dilation = (2, 1)\n    padding = (0, 0, 1, 1)\n\n    @tf.function\n    def conv2d(x):\n        tf_strides = [1, strides[0], strides[1], 1]\n        op = tf.pad(\n            x,\n            [[0, 0], [padding[0], padding[2]], [padding[1], padding[3]], [0, 0]],\n            \"CONSTANT\",\n        )\n        weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 3]\n        weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n        return tf.nn.conv2d(\n            op,\n            weight,\n            strides=tf_strides,\n            padding=\"VALID\",\n            dilations=dilation,\n        )\n\n    infra.compare_tvm_with_tflite(conv2d, [ifm_shape], \"ethos-u55-256\")\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 214, 227, 2), (1, 27, 42, 3)])\n@pytest.mark.parametrize(\"kernel_shape\", [(3, 2), (1, 3)])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (2, 1)), ((3, 2), (1, 1))])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES + [\"ethos-u65-512\"])\n@pytest.mark.parametrize(\"activation\", [\"NONE\", \"RELU\"])\ndef test_ethosu_conv2d_double(\n    ifm_shape,\n    kernel_shape,\n    strides,\n    dilation,\n    padding,\n    accel_type,\n    activation,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def conv2d_double(x):\n        # Use tf.nn API to create the model with two convolutions\n        op = tf.nn.conv2d(\n            x,\n            filters=tf.constant(\n                np.random.uniform(size=[kernel_shape[0], kernel_shape[1], ifm_shape[3], 5]),\n                dtype=tf.float32,\n            ),\n            strides=strides,\n            padding=padding,\n            dilations=dilation,\n        )\n        # Second convolution\n        op2 = tf.nn.conv2d(\n            op,\n            filters=tf.constant(\n                np.random.uniform(size=(kernel_shape[0], kernel_shape[1], 5, 3)),\n                dtype=tf.float32,\n            ),\n            strides=strides,\n            padding=padding,\n            dilations=dilation,\n        )\n        if activation == \"RELU\":\n            op2 = tf.nn.relu(op2)\n        return op2\n\n    infra.compare_tvm_with_tflite(conv2d_double, [ifm_shape], accel_type)\n\n\n@pytest.mark.parametrize(\"weight_min, weight_max\", [(0.0, 1e-11), (-1e10, 1e10)])\ndef test_out_of_range_scaling(weight_min, weight_max):\n    np.random.seed(0)\n    ifm_shape = (1, 6, 6, 2)\n    strides = (1, 1)\n    kernel_shape = (1, 1)\n    dilation = (1, 1)\n    padding = \"SAME\"\n    activation = \"RELU\"\n    accel_type = \"ethos-u55-128\"\n\n    @tf.function\n    def conv_invalid_scale(x):\n        # Use tf.nn API to create the model\n        tf_strides = [1, strides[0], strides[1], 1]\n        weights = np.random.uniform(size=[kernel_shape[0], kernel_shape[1], 2, 2])\n        # Overwrite to force quantization that produces out of range shift values\n        weights[0][0][0][0] = weight_min\n        weights[0][0][1][0] = weight_max\n        op = tf.nn.conv2d(\n            x,\n            filters=tf.constant(\n                weights,\n                dtype=tf.float32,\n            ),\n            strides=tf_strides,\n            padding=padding,\n            dilations=dilation,\n        )\n        if activation == \"RELU\":\n            op = tf.nn.relu(op)\n        return op\n\n    infra.compare_tvm_with_tflite(conv_invalid_scale, [ifm_shape], accel_type)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 55, 55, 3), (1, 23, 32, 7)])\n@pytest.mark.parametrize(\n    \"kernel_shape, activation_function\",\n    [((3, 3), \"RELU\"), ((1, 2), \"NONE\")],\n)\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (2, 2)), ((3, 2), (1, 1))])\ndef test_tflite_depthwise_conv2d(\n    accel_type,\n    ifm_shape,\n    kernel_shape,\n    padding,\n    strides,\n    dilation,\n    activation_function,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def depthwise_conv2d(x):\n        weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 1]\n        weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n        # The input strides to the TensorFlow API needs to be of shape 1x4\n        tf_strides = [1, strides[0], strides[1], 1]\n        op = tf.nn.depthwise_conv2d(\n            x, weight, strides=tf_strides, padding=padding, dilations=dilation\n        )\n        if activation_function == \"RELU\":\n            op = tf.nn.relu(op)\n        return op\n\n    infra.compare_tvm_with_tflite(depthwise_conv2d, [ifm_shape], accel_type)\n\n\ndef test_tflite_depthwise_conv2d_with_separate_pad():\n    np.random.seed(0)\n\n    ifm_shape = (1, 23, 32, 7)\n    kernel_shape = (1, 2)\n    strides = (3, 2)\n    dilation = (1, 1)\n    padding = (0, 0, 1, 1)\n\n    @tf.function\n    def depthwise_conv2d(x):\n        tf_strides = [1, strides[0], strides[1], 1]\n        op = tf.pad(\n            x,\n            [[0, 0], [padding[0], padding[2]], [padding[1], padding[3]], [0, 0]],\n            \"CONSTANT\",\n        )\n        weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 1]\n        weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n        return tf.nn.depthwise_conv2d(\n            op,\n            weight,\n            strides=tf_strides,\n            padding=\"VALID\",\n            dilations=dilation,\n        )\n\n    infra.compare_tvm_with_tflite(depthwise_conv2d, [ifm_shape], \"ethos-u55-256\")\n\n\n@pytest.mark.parametrize(\n    \"accel_type\",\n    ACCEL_TYPES,\n)\n@pytest.mark.parametrize(\"pooling_type\", [\"MAX\", \"AVG\"])\n@pytest.mark.parametrize(\"ifm_shape\", [[1, 3, 4, 3], [1, 4, 5, 2]])\n@pytest.mark.parametrize(\n    \"pool_shape, strides, activation_function, padding\",\n    [([1, 2], [1, 2], \"NONE\", \"SAME\"), ([2, 3], [2, 3], \"RELU\", \"VALID\")],\n)\ndef test_ethosu_pooling(\n    accel_type,\n    ifm_shape,\n    pooling_type,\n    strides,\n    pool_shape,\n    activation_function,\n    padding,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def pooling(x):\n        if pooling_type == \"MAX\":\n            op = tf.nn.max_pool(x, pool_shape, strides, padding)\n        elif pooling_type == \"AVG\":\n            op = tf.nn.avg_pool(x, pool_shape, strides, padding)\n        if activation_function == \"RELU\":\n            op = tf.nn.relu(op)\n        return op\n\n    infra.compare_tvm_with_tflite(pooling, [ifm_shape], accel_type)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"operator_type\", [\"ADD\", \"SUB\", \"MUL\", \"MIN\", \"MAX\"])\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape\",\n    [\n        ([1, 2, 3, 4], [1, 2, 3, 4]),\n        ([1, 2, 3, 4], [1, 1, 1, 1]),\n        ([1, 1, 1, 1], [1, 2, 3, 4]),\n        ([1, 4, 4], [4, 1]),\n    ],\n)\n@pytest.mark.parametrize(\"activation_function\", [\"NONE\", \"RELU\"])\ndef test_ethosu_binary_elementwise(\n    accel_type,\n    operator_type,\n    ifm_shape,\n    ifm2_shape,\n    activation_function,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def binary_elementwise(lhs, rhs):\n        if operator_type == \"ADD\":\n            op = tf.math.add(lhs, rhs)\n        elif operator_type == \"SUB\":\n            op = tf.math.subtract(lhs, rhs)\n        elif operator_type == \"MUL\":\n            op = tf.math.multiply(lhs, rhs)\n        elif operator_type == \"MIN\":\n            op = tf.math.minimum(lhs, rhs)\n        elif operator_type == \"MAX\":\n            op = tf.math.maximum(lhs, rhs)\n        if activation_function == \"RELU\":\n            op = tf.nn.relu(op)\n        return op\n\n    infra.compare_tvm_with_tflite(\n        binary_elementwise,\n        shapes=[ifm_shape, ifm2_shape],\n        ranges=[(0, 1), (0, 2)],\n        accel_type=accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape\",\n    [\n        ([4], [4]),\n        ([4], [1, 2, 3, 4]),\n        ([1, 4, 4], [4, 1]),\n    ],\n)\ndef test_binary_add_with_non_4d_shapes(\n    request,\n    accel_type,\n    ifm_shape,\n    ifm2_shape,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def binary_elementwise(lhs, rhs):\n        return tf.math.add(lhs, rhs)\n\n    infra.compare_tvm_with_tflite(\n        binary_elementwise,\n        shapes=[ifm_shape, ifm2_shape],\n        ranges=[(0, 1), (0, 2)],\n        accel_type=accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/12634\")\n@pytest.mark.parametrize(\n    \"accel_type\",\n    ACCEL_TYPES,\n)\n@pytest.mark.parametrize(\n    \"ifm_shape, axis, keep_dims, use_same_quantization\",\n    [\n        # mean to depthwise + multiply\n        [(1, 8, 16, 16), (1, 2), True, False],\n        [(1, 3, 4), (0, 1), True, False],\n        [(1, 65, 2, 1), (1, 2), True, False],  # special case when h > 64\n        # mean to average pool\n        [(1, 8, 16, 16), (2,), False, True],\n        [(3, 3, 4), (0,), True, True],\n        [(8, 5), (0,), False, True],\n        # mean to depthwise\n        [(1, 8, 16, 16), (2,), True, False],\n        [(1, 8, 16, 16), (2, 1), False, False],\n        [(8, 4), (0,), False, False],\n    ],\n)\ndef test_mean(accel_type, ifm_shape, axis, keep_dims, use_same_quantization):\n    np.random.seed(0)\n    dtype = \"int8\"\n\n    def create_mod_from_tflite():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                op = tf.math.reduce_mean(x, axis=axis, keepdims=keep_dims)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_graph = converter.convert()\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n        mod, _ = relay.frontend.from_tflite(\n            tflite_model,\n            shape_dict={\"ifm\": ifm_shape},\n            dtype_dict={\"ifm\": dtype},\n        )\n        input_data, output_data = infra.generate_ref_data_tflite(tflite_graph)\n        return mod, input_data, output_data\n\n    def create_mod_from_relay():\n        ifm = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n        cast = relay.cast(ifm, dtype=\"int32\")\n        mean = relay.mean(cast, axis=axis, keepdims=keep_dims)\n        requantize = relay.qnn.op.requantize(\n            mean,\n            input_scale=relay.const(1.0, dtype=\"float32\"),\n            input_zero_point=relay.const(0, dtype=\"int32\"),\n            output_scale=relay.const(1.0, dtype=\"float32\"),\n            output_zero_point=relay.const(0, dtype=\"int32\"),\n        )\n\n        func = relay.Function(relay.analysis.free_vars(requantize), requantize)\n        mod = tvm.IRModule.from_expr(func)\n\n        input_data = {\"input\": np.random.randint(low=-127, high=128, size=ifm_shape, dtype=dtype)}\n        output_data = generate_ref_data(mod, input_data)\n        return mod, input_data, output_data\n\n    mod, input_data, output_data = (\n        create_mod_from_relay() if use_same_quantization else create_mod_from_tflite()\n    )\n    mod = partition_for_ethosu(mod)\n\n    test_runner = infra.create_test_runner(accel_type)\n    compiled_models = infra.build_source(mod, input_data, output_data, test_runner)\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    get_artifacts = tvm._ffi.get_global_func(\"runtime.module.ethos-u.get_artifacts\")\n    compilation_artifacts = get_artifacts(ethosu_module)\n    cmms = bytes.fromhex(compilation_artifacts[0].command_stream)\n    infra.print_payload(cmms)\n    infra.verify_source(compiled_models, test_runner)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"uint8\"])\n@pytest.mark.parametrize(\"constant\", [np.ones((1, 1, 1, 1)), np.array(1)])\ndef test_elementwise_add_from_constant_scalar(accel_type, dtype, constant):\n    np.random.seed(0)\n    ifm_shape = (1, 4, 4, 8)\n\n    def create_relay_graph():\n        inp = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n        scalar = relay.const(constant, dtype=dtype)\n        add = relay.qnn.op.add(\n            inp,\n            scalar,\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n        )\n        return tvm.IRModule.from_expr(relay.Function(relay.analysis.free_vars(add), add))\n\n    cpu_mod = create_relay_graph()\n    ethosu_mod = partition_for_ethosu(cpu_mod)\n\n    # Generate reference data\n    input_data = {\n        \"input\": np.random.randint(\n            low=np.iinfo(dtype).min, high=np.iinfo(dtype).max, size=ifm_shape, dtype=dtype\n        ),\n    }\n    output_data = generate_ref_data(cpu_mod, input_data)\n\n    # Scalar constants are not supported by the cascader\n    infra.compare_ethosu_with_reference(\n        ethosu_mod, input_data, output_data, accel_type, enable_cascader=False\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape\",\n    [\n        ([1, 2, 3, 4], [1, 2, 3, 4]),\n        ([1, 2, 3, 4], [1, 1, 3, 1]),\n        ([1, 1, 3, 1], [1, 2, 3, 4]),\n    ],\n)\ndef test_ethosu_left_shift_binary_elemwise(\n    accel_type,\n    ifm_shape,\n    ifm2_shape,\n):\n    np.random.seed(0)\n    dtype = \"int32\"\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n        ifm2 = relay.var(\"ifm2\", shape=ifm2_shape, dtype=dtype)\n        c1 = relay.left_shift(ifm, ifm2)\n        return tvm.IRModule.from_expr(relay.Function([ifm, ifm2], c1))\n\n    cpu_mod = create_model()\n\n    # Generate reference data\n    in_min, in_max = util.get_range_for_dtype_str(dtype)\n    input_data = {\n        \"ifm\": np.random.randint(in_min, high=in_max, size=ifm_shape, dtype=dtype),\n        \"ifm2\": np.random.randint(0, high=32, size=ifm2_shape, dtype=dtype),\n    }\n    output_data = generate_ref_data(cpu_mod, input_data)\n    ethosu_mod = partition_for_ethosu(cpu_mod)\n\n    infra.compare_ethosu_with_reference(ethosu_mod, input_data, output_data, accel_type)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape, reversed_operands, ofm_dtype\",\n    [\n        ([1, 2, 3, 4], [1, 2, 3, 4], False, \"int8\"),\n        ([1, 2, 3, 1], [1, 1, 3, 1], False, \"int32\"),\n        ([1, 1, 3, 1], [1, 2, 3, 1], True, \"int32\"),\n    ],\n)\ndef test_ethosu_right_shift_binary_elemwise(\n    ifm_shape, ifm2_shape, reversed_operands, accel_type, ofm_dtype\n):\n    np.random.seed(0)\n    dtype = \"int32\"\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n        ifm2 = relay.var(\"ifm2\", shape=ifm2_shape, dtype=dtype)\n        shr_op = infra.make_ethosu_binary_elementwise(\n            ifm, ifm2, ifm_shape[3], ifm2_shape[3], \"SHR\", ofm_dtype, reversed_operands\n        )\n        return tvm.IRModule.from_expr(relay.Function([ifm, ifm2], shr_op))\n\n    def generate_output_data(input_data):\n        lhs = input_data[\"ifm\"]\n        rhs = input_data[\"ifm2\"]\n        if reversed_operands:\n            lhs = np.broadcast_to(lhs, ifm2_shape)\n            lhs, rhs = rhs, lhs\n        else:\n            rhs = np.broadcast_to(rhs, ifm_shape)\n\n        def rounding_right_shift(lhs, rhs):\n            r = 1 << (rhs - 1)\n            return (lhs + r) >> rhs\n\n        return [\n            np.array([rounding_right_shift(x[0], x[1]) for x in zip(lhs.flat, rhs.flat)]).astype(\n                ofm_dtype\n            )\n        ]\n\n    cpu_mod = create_model()\n\n    # Generate reference data\n    in_min, in_max = util.get_range_for_dtype_str(dtype)\n    in_min, in_max = 18, 19\n    lhs = np.random.randint(in_min, high=in_max, size=ifm_shape, dtype=dtype)\n    rhs = np.random.randint(1, high=2, size=ifm2_shape, dtype=dtype)\n    input_data = {\n        \"ifm\": lhs,\n        \"ifm2\": rhs,\n    }\n    output_data = {\"output\": generate_output_data(input_data)[0]}\n    ethosu_mod = infra.create_ethosu_partition(cpu_mod)\n\n    infra.compare_ethosu_with_reference(ethosu_mod, input_data, output_data, accel_type)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape\", [(3, 2), (1, 15, 11, 7), (3, 1, 12), (400,)])\n@pytest.mark.parametrize(\"ifm_scale, ifm_zp, ofm_scale, ofm_zp\", [(1, 0, 1, 0), (0.015, 3, 0.2, 5)])\ndef test_ethosu_identity_codegen(\n    request, ifm_shape, ifm_scale, ifm_zp, ofm_scale, ofm_zp, accel_type\n):\n    np.random.seed(0)\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        identity = infra.make_ethosu_identity(\n            ifm,\n            ifm_scale=ifm_scale,\n            ifm_zero_point=ifm_zp,\n            ofm_scale=ofm_scale,\n            ofm_zero_point=ofm_zp,\n        )\n        return tvm.IRModule.from_expr(relay.Function([ifm], identity))\n\n    def generate_output_data(input_data):\n        requant_data = (ifm_scale * (input_data[\"ifm\"] - ifm_zp)) / ofm_scale + ofm_zp\n        return [np.round(np.clip(requant_data, -128, 127)).astype(\"int8\")]\n\n    cpu_mod = create_model()\n    input_data = {\"ifm\": np.random.randint(-120, high=120, size=ifm_shape, dtype=\"int8\")}\n    output_data = {\"output\": generate_output_data(input_data)[0]}\n    ethosu_mod = infra.create_ethosu_partition(cpu_mod)\n\n    infra.compare_ethosu_with_reference(\n        ethosu_mod,\n        input_data,\n        output_data,\n        accel_type,\n        output_tolerance=1,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, new_shape\",\n    [\n        ((1, 4, 1, 2), (1, 1, 1, 8)),\n        ((12, 20), (1, 6, 4, 10)),\n        ((12, 20), (6, 4, 10)),\n        ((20,), (4, 5)),\n        ((12, 2, 10), (0, -3)),\n        ((11, 3, 25), (-1,)),\n        ((8, 7, 3), (-4, 1, 8, -2)),\n    ],\n)\ndef test_relay_reshape_codegen(ifm_shape, new_shape, accel_type):\n    np.random.seed(0)\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        reshape = relay.op.reshape(ifm, newshape=new_shape)\n        return tvm.IRModule.from_expr(relay.Function([ifm], reshape))\n\n    cpu_mod = create_model()\n    input_data = {\"ifm\": np.random.randint(-128, high=127, size=ifm_shape, dtype=\"int8\")}\n    output_data = generate_ref_data(cpu_mod, input_data)\n    ethosu_mod = infra.create_ethosu_partition(cpu_mod)\n\n    infra.compare_ethosu_with_reference(\n        ethosu_mod,\n        input_data,\n        output_data,\n        accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, begin, size\",\n    [\n        ([1, 10, 50, 4], [0, 5, 11, 2], [1, 5, 11, 1]),\n        ([15, 17, 3], [3, 0, 1], [8, 17, 2]),\n        ([7, 6043], [0, 704], [1, 2860]),\n        ([5000], [123], [2151]),\n    ],\n)\ndef test_tflite_slice(request, accel_type, ifm_shape, begin, size):\n    np.random.seed(0)\n\n    @tf.function\n    def slice_func(x):\n        return tf.slice(x, begin, size)\n\n    infra.compare_tvm_with_tflite(\n        slice_func, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, begin, end\",\n    [([1, 1, 5, 8], [0, 0, 0, 0], [1, 1, 2, 3]), ([1, 3, 3], [0, 1, 2], [1, 2, 3])],\n)\ndef test_tflite_strided_slice(accel_type, ifm_shape, begin, end):\n    np.random.seed(0)\n\n    @tf.function\n    def strided_slice_func(x):\n        return tf.strided_slice(x, begin, end)\n\n    infra.compare_tvm_with_tflite(\n        strided_slice_func, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"operator_type\", [\"ABS\"])\n@pytest.mark.parametrize(\n    \"ifm_shape\",\n    [[1, 5, 12, 4], [1, 1, 2], [4, 3, 2], [10, 20], [345]],\n)\ndef test_ethosu_unary_elementwise(\n    request,\n    accel_type,\n    operator_type,\n    ifm_shape,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def abs_func(x):\n        if operator_type == \"ABS\":\n            op = tf.math.abs(x)\n        return op\n\n    infra.compare_tvm_with_tflite(\n        abs_func,\n        [ifm_shape],\n        accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\ndef test_ethosu_section_name():\n    np.random.seed(0)\n\n    @tf.function\n    def depthwise_conv2d(x):\n        weight_shape = [3, 3, 3, 1]\n        weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n        tf_strides = [1, 1, 1, 1]\n        op = tf.nn.depthwise_conv2d(x, weight, strides=tf_strides, padding=\"SAME\", dilations=(2, 2))\n        return op\n\n    mod, tflite_graph = infra.get_tflite_graph(depthwise_conv2d, [(1, 55, 55, 3)])\n\n    # Generate reference data\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_graph)\n\n    test_runner = infra.create_test_runner()\n    compiled_models = infra.build_source(mod, input_data, output_data, test_runner)\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    source = ethosu_module.get_source()\n    assert (\n        '__attribute__((section(\".rodata.tvm\"), aligned(16))) static int8_t tvmgen_default_ethos_u_main_0_cms_data_data'\n        in source\n    )\n    assert (\n        '__attribute__((section(\".rodata.tvm\"), aligned(16))) static int8_t tvmgen_default_ethos_u_main_0_weights'\n        in source\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\ndef test_ethosu_clz(accel_type):\n    np.random.seed(0)\n    ifm_shape = (1, 42, 5, 4)\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int32\")\n        clz = infra.make_ethosu_unary_elementwise(ifm, 4, \"CLZ\")\n        return tvm.IRModule.from_expr(relay.Function([ifm], clz))\n\n    def generate_output_data(input_data):\n        def clz_comp(n):\n            n_bin = np.binary_repr(n)\n            if n_bin[0] == \"-\":\n                return 0\n            else:\n                return 32 - len(n_bin)\n\n        return [\n            np.array([clz_comp(i) for i in input_data[\"ifm\"].ravel()])\n            .reshape(ifm_shape)\n            .astype(\"int32\")\n        ]\n\n    cpu_mod = create_model()\n    input_data = {\"ifm\": np.random.randint(-500000, high=500000, size=ifm_shape, dtype=\"int32\")}\n    output_data = {\"output\": generate_output_data(input_data)[0]}\n    ethosu_mod = infra.create_ethosu_partition(cpu_mod)\n\n    infra.compare_ethosu_with_reference(ethosu_mod, input_data, output_data, accel_type)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\ndef test_tflite_tanh(accel_type):\n    np.random.seed(0)\n    ifm_shape = [1, 115, 32, 7]\n\n    @tf.function\n    def tanh_func(x):\n        op = tf.nn.tanh(x)\n        return op\n\n    infra.compare_tvm_with_tflite(\n        tanh_func, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 5, 5, 3), (1, 12, 9, 1)])\ndef test_tflite_hard_swish(accel_type, ifm_shape):\n    np.random.seed(0)\n\n    @tf.function\n    def hard_swish_func(x):\n        op = tf.keras.layers.Lambda(\n            lambda x: x * tf.keras.activations.relu(x + 3.0, max_value=6.0) / 6.0\n        )(x)\n        return op\n\n    infra.compare_tvm_with_tflite(hard_swish_func, [ifm_shape], accel_type, ranges=[(-1, 1)])\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"shapes, axis\",\n    [\n        ([(2, 3), (4, 3)], 0),\n        ([(3, 2, 1), (3, 1, 1)], 1),\n        ([(10,), (13,), (14,)], 0),\n        ([(1, 5, 2, 1), (1, 5, 7, 1), (1, 5, 3, 1)], 2),\n    ],\n)\ndef test_tflite_concat(shapes, axis, accel_type):\n    np.random.seed(0)\n\n    @tf.function\n    def concat_func(*inputs):\n        op = tf.concat(list(inputs), axis)\n        return op\n\n    infra.compare_tvm_with_tflite(concat_func, shapes, accel_type, enable_cascader=False)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\ndef test_tflite_sigmoid(accel_type):\n    np.random.seed(0)\n    ifm_shape = [1, 135, 41, 6]\n\n    @tf.function\n    def sigmoid_function(x):\n        op = tf.nn.sigmoid(x)\n        return op\n\n    infra.compare_tvm_with_tflite(\n        sigmoid_function, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n# This codegen test checks both, split and split_v\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape, num_or_size_splits, axis\",\n    [\n        ((1, 4, 6, 8), (1, 3, 4), 3),\n        ((4, 6, 8), 2, 0),\n        ((50,), 25, 0),\n        ((5, 11), 1, 1),\n        ((13,), (13,), 0),\n        ((22, 7), (4, -1), 1),\n    ],\n)\ndef test_tflite_split(accel_type, ifm_shape, num_or_size_splits, axis):\n    np.random.seed(0)\n\n    @tf.function\n    def split_func(x):\n        op = tf.split(x, num_or_size_splits, axis=axis)\n        return op\n\n    infra.compare_tvm_with_tflite(split_func, [ifm_shape], accel_type, enable_cascader=False)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,ifm_scale,ifm_zp,ofm_scale,ofm_zp\",\n    [\n        [(1, 8, 8, 3), 1.0, 0, 1.0, 0],\n        [(1, 20, 30, 3), 1.345, 34, 0.32, -23],\n    ],\n)\ndef test_ethosu_requantize(accel_type, ifm_shape, ifm_scale, ifm_zp, ofm_scale, ofm_zp):\n    np.random.seed(0)\n    dtype = \"int8\"\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        requantize = relay.qnn.op.requantize(\n            ifm,\n            relay.const(ifm_scale, dtype=\"float32\"),\n            relay.const(ifm_zp, dtype=\"int32\"),\n            relay.const(ofm_scale, dtype=\"float32\"),\n            relay.const(ofm_zp, dtype=\"int32\"),\n        )\n        return tvm.IRModule.from_expr(relay.Function([ifm], requantize))\n\n    cpu_mod = create_model()\n    input_data = {\"ifm\": np.random.randint(-128, high=127, size=ifm_shape, dtype=dtype)}\n    output_data = generate_ref_data(cpu_mod, input_data)\n    ethosu_mod = partition_for_ethosu(cpu_mod)\n\n    infra.compare_ethosu_with_reference(\n        ethosu_mod,\n        input_data,\n        output_data,\n        accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape,axis\", [((2,), 0), ((1, 3, 3), 2)])\ndef test_tflite_expand_dims(accel_type, ifm_shape, axis):\n    np.random.seed(0)\n\n    @tf.function\n    def expand_dims_func(x):\n        return tf.expand_dims(x, axis=axis)\n\n    infra.compare_tvm_with_tflite(\n        expand_dims_func, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,axis\", [((1, 1, 2, 1), 0), ((1, 3, 3, 1), 3), ((1, 1, 2, 1), None)]\n)\ndef test_tflite_squeeze(accel_type, ifm_shape, axis):\n    np.random.seed(0)\n\n    @tf.function\n    def squeeze_func(x):\n        return tf.squeeze(x, axis=axis)\n\n    infra.compare_tvm_with_tflite(\n        squeeze_func, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,size\",\n    [[(1, 2, 2, 1), (4, 4)], [(1, 4, 7, 3), (8, 14)], [(1, 3, 5, 3), (3, 5)]],\n)\ndef test_tflite_resize2d_nearest_neighbor(accel_type, ifm_shape, size):\n    np.random.seed(0)\n    align_corners = False\n\n    @tf.function\n    def resize_model(x):\n        return tf.compat.v1.image.resize_nearest_neighbor(\n            x, size, align_corners=align_corners, half_pixel_centers=False\n        )\n\n    infra.compare_tvm_with_tflite(\n        resize_model, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,size,align_corners\",\n    [\n        [(1, 2, 2, 1), (4, 4), False],\n        [(1, 4, 7, 3), (8, 14), False],\n        [(1, 2, 2, 1), (3, 3), True],\n        [(1, 4, 7, 3), (7, 13), True],\n        [(1, 3, 5, 3), (3, 5), False],\n    ],\n)\ndef test_tflite_resize2d_bilinear(accel_type, ifm_shape, size, align_corners):\n    np.random.seed(0)\n\n    @tf.function\n    def resize_model(x):\n        return tf.compat.v1.image.resize_bilinear(\n            x, size, align_corners=align_corners, half_pixel_centers=False\n        )\n\n    infra.compare_tvm_with_tflite(\n        resize_model, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,ofm_shape,kernel_shape,padding\",\n    [\n        [(1, 2, 2, 1), (1, 4, 4, 1), (3, 3), \"SAME\"],\n        [(1, 2, 2, 1), (1, 9, 9, 1), (7, 7), \"VALID\"],\n        [(1, 2, 4, 3), (1, 4, 8, 3), (5, 3), \"SAME\"],\n        [(1, 10, 5, 3), (1, 21, 13, 3), (3, 5), \"VALID\"],\n    ],\n)\n@pytest.mark.parametrize(\"has_bias\", [False, True])\ndef test_tflite_transpose_convolution(\n    accel_type, ifm_shape, ofm_shape, kernel_shape, padding, has_bias\n):\n    np.random.seed(0)\n    dilations = (1, 1)\n    strides = (2, 2)\n\n    @tf.function\n    def conv2d_transpose(x):\n        weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], ofm_shape[3]]\n        weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n        bias_shape = ofm_shape[3]\n        bias = tf.constant(np.random.uniform(size=bias_shape), dtype=tf.float32)\n        tf_strides = [1, strides[0], strides[1], 1]\n        op = tf.nn.conv2d_transpose(\n            x,\n            weight,\n            output_shape=ofm_shape,\n            strides=tf_strides,\n            padding=padding,\n            dilations=dilations,\n        )\n        if has_bias:\n            op = tf.nn.bias_add(op, bias)\n        return op\n\n    infra.compare_tvm_with_tflite(\n        conv2d_transpose,\n        [ifm_shape],\n        accel_type=accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shapes,axis\",\n    [\n        ([(1, 2, 2), (1, 2, 2), (1, 2, 2)], 2),\n        ([(5, 4), (5, 4)], 1),\n        ([(1,), (1,)], 0),\n        ([(3, 1), (3, 1), (3, 1), (3, 1)], 0),\n    ],\n)\ndef test_tflite_pack(accel_type, ifm_shapes, axis):\n    np.random.seed(0)\n\n    @tf.function\n    def pack_func(*inputs):\n        return tf.stack(inputs, axis=axis)\n\n    infra.compare_tvm_with_tflite(pack_func, ifm_shapes, accel_type, enable_cascader=False)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\n    \"ifm_shape,axis\",\n    [[(1, 2, 3, 4), 1], [(2, 3), 1], [(5, 6, 7), 2]],\n)\ndef test_tflite_unpack(accel_type, ifm_shape, axis):\n    np.random.seed(0)\n\n    @tf.function\n    def unpack_func(x):\n        return tf.unstack(x, axis=axis)\n\n    infra.compare_tvm_with_tflite(unpack_func, [ifm_shape], accel_type, enable_cascader=False)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 15, 15, 3), (1, 8, 9, 1)])\n@pytest.mark.parametrize(\"alpha\", [0.2, 0.634])\ndef test_tflite_leaky_relu(accel_type, ifm_shape, alpha):\n    np.random.seed(0)\n\n    @tf.function\n    def leaky_relu_func(x):\n        return tf.nn.leaky_relu(x, alpha=alpha)\n\n    infra.compare_tvm_with_tflite(\n        leaky_relu_func,\n        [ifm_shape],\n        accel_type,\n        enable_cascader=is_u55_accel_type(accel_type),\n        ranges=[(-1, 1)],\n    )\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 14), (1, 151)])\n@pytest.mark.parametrize(\"ofm_channels\", [32, 64])\n@pytest.mark.parametrize(\"use_bias\", [True, False])\n@pytest.mark.parametrize(\"activation_function\", [\"RELU\", \"NONE\"])\ndef test_tflite_fully_connected(\n    accel_type,\n    ifm_shape,\n    ofm_channels,\n    use_bias,\n    activation_function,\n):\n    np.random.seed(0)\n\n    @tf.function\n    def fully_connected(x):\n        bias_shape = ofm_channels\n        bias = tf.constant(np.random.uniform(size=bias_shape), dtype=tf.float32)\n        w = tf.constant(\n            np.random.uniform(size=[ifm_shape[1], ofm_channels]),\n            dtype=tf.float32,\n        )\n        x = tf.matmul(x, w)\n        if use_bias:\n            x = tf.nn.bias_add(x, bias)\n        if activation_function:\n            x = tf.nn.relu(x)\n        return x\n\n    infra.compare_tvm_with_tflite(\n        fully_connected, [ifm_shape], accel_type, enable_cascader=is_u55_accel_type(accel_type)\n    )\n\n\nif __name__ == \"__main__\":\n    import sys\n    import pytest\n\n    sys.exit(pytest.main([__file__] + sys.argv[1:]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom . import infra\n\n\ndef _create_single_conv2d():\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    conv1 = infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    func = relay.Function(relay.analysis.free_vars(conv1), conv1)\n    return func\n\n\ndef _create_double_conv2d():\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    conv1 = infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    conv2 = infra.make_ethosu_conv2d(conv1, 4, 7, (2, 2), (1, 1), (1, 1), (1, 1))\n    func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n    return func\n\n\ndef _create_non_linear_conv2d():\n    shape = (1, 8, 8, 4)\n    ifm1 = relay.var(\"x\", shape=shape, dtype=\"int8\")\n    ifm2 = relay.var(\"y\", shape=shape, dtype=\"int8\")\n    conv1 = infra.make_ethosu_conv2d(ifm1, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    conv2 = infra.make_ethosu_conv2d(ifm2, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n    add = infra.make_ethosu_binary_elementwise(conv1, conv2, shape[3], shape[3], \"ADD\", \"int8\")\n    func = relay.Function(relay.analysis.free_vars(add), add)\n    return func\n\n\n@pytest.mark.parametrize(\n    \"relay_function, arg_count\",\n    [(_create_single_conv2d, 2), (_create_double_conv2d, 2), (_create_non_linear_conv2d, 3)],\n)\ndef test_lower_to_tir_arg_count(relay_function, arg_count):\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay_function()\n    mod = relay.transform.InferType()(mod)\n    tir_mod = _lower_to_tir(mod[\"main\"])[0]\n    primfunc = tir_mod[\"main\"]\n    assert len(primfunc.params) == arg_count\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_copy_compute_reordering.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.relay.backend.contrib.ethosu.tir.passes import CopyComputeReordering\n\n# fmt: off\n@tvm.script.ir_module\nclass AllOperatorsWithWeights:\n    @T.prim_func\n    def main() -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([8192], \"int8\")\n        buffer2 = T.buffer_decl([128], \"uint8\")\n        buffer3 = T.buffer_decl([32], \"uint8\")\n        buffer4 = T.buffer_decl([112], \"uint8\")\n        buffer5 = T.buffer_decl([32], \"uint8\")\n        buffer6 = T.buffer_decl([112], \"uint8\")\n        buffer7 = T.buffer_decl([32], \"uint8\")\n        buffer8 = T.buffer_decl([112], \"uint8\")\n        buffer9 = T.buffer_decl([32], \"uint8\")\n        buffer10 = T.buffer_decl([2048], \"int8\")\n        # body\n        p1 = T.decl_buffer([128], \"uint8\")\n        p2 = T.decl_buffer([112], \"uint8\")\n        p3 = T.decl_buffer([112], \"uint8\")\n        p4 = T.decl_buffer([32], \"uint8\")\n        p5 = T.decl_buffer([32], \"uint8\")\n        p6 = T.decl_buffer([32], \"uint8\")\n        p7 = T.decl_buffer([112], \"uint8\")\n        p8 = T.decl_buffer([32], \"uint8\")\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 112, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p5[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, 12, p5[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 112, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 32, p6[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 112, 12, p6[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 112, p7[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer9[0], 32, p8[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p8[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n# fmt: on\n\n\ndef test_all_operators_with_weights_max_copy_movements_0():\n    test_mod = CopyComputeReordering(0)(AllOperatorsWithWeights)\n    reference_mod = AllOperatorsWithWeights\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_all_operators_with_weights_max_copy_movements_1():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer2 = T.buffer_decl([128], \"uint8\")\n            buffer3 = T.buffer_decl([32], \"uint8\")\n            buffer4 = T.buffer_decl([112], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            buffer6 = T.buffer_decl([112], \"uint8\")\n            buffer7 = T.buffer_decl([32], \"uint8\")\n            buffer8 = T.buffer_decl([112], \"uint8\")\n            buffer9 = T.buffer_decl([32], \"uint8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1 = T.decl_buffer([128], \"uint8\")\n            p2 = T.decl_buffer([112], \"uint8\")\n            p3 = T.decl_buffer([112], \"uint8\")\n            p4 = T.decl_buffer([32], \"uint8\")\n            p5 = T.decl_buffer([32], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            p7 = T.decl_buffer([112], \"uint8\")\n            p8 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 112, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 112, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, 12, p5[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 112, p7[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer9[0], 32, p8[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 112, 12, p6[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p8[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(1)(AllOperatorsWithWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_all_operators_with_weights_max_copy_movements_2():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer2 = T.buffer_decl([128], \"uint8\")\n            buffer3 = T.buffer_decl([32], \"uint8\")\n            buffer4 = T.buffer_decl([112], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            buffer6 = T.buffer_decl([112], \"uint8\")\n            buffer7 = T.buffer_decl([32], \"uint8\")\n            buffer8 = T.buffer_decl([112], \"uint8\")\n            buffer9 = T.buffer_decl([32], \"uint8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1 = T.decl_buffer([128], \"uint8\")\n            p2 = T.decl_buffer([112], \"uint8\")\n            p3 = T.decl_buffer([112], \"uint8\")\n            p4 = T.decl_buffer([32], \"uint8\")\n            p5 = T.decl_buffer([32], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            p7 = T.decl_buffer([112], \"uint8\")\n            p8 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 112, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 112, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 112, p7[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer9[0], 32, p8[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, 12, p5[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 112, 12, p6[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p8[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(2)(AllOperatorsWithWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass AllOperatorsWithoutWeights:\n    @T.prim_func\n    def main() -> None:\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([36], \"int8\")\n        buffer2 = T.buffer_decl([9], \"int8\")\n        # body\n        p1 = T.decl_buffer([96], \"int8\")\n        T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 3, 4, 3, 3, 0, 4, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 12, 3, 1, \"int8\", 3, 2, 3, 3, 0, 2, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 32, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 3, 2, 3, 3, 0, 2, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 32, 16, 1, \"int8\", 3, 1, 3, 3, 0, 1, buffer2[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 3, 1, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n# fmt: on\n\n\n@pytest.mark.parametrize(\"max_copy_movements\", [0, 1, 2])\ndef test_all_operators_without_weights(max_copy_movements):\n    test_mod = CopyComputeReordering(max_copy_movements)(AllOperatorsWithoutWeights)\n    reference_mod = AllOperatorsWithoutWeights\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass OperatorsWithAndWithoutWeights:\n    @T.prim_func\n    def main() -> None:\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([97156], \"int8\")\n        buffer2 = T.buffer_decl([80], \"uint8\")\n        buffer3 = T.buffer_decl([64], \"uint8\")\n        buffer4 = T.buffer_decl([96], \"uint8\")\n        buffer5 = T.buffer_decl([32], \"uint8\")\n        # body\n        p1 = T.decl_buffer([390336], \"int8\")\n        p2 = T.decl_buffer([80], \"uint8\")\n        p3 = T.decl_buffer([64], \"uint8\")\n        p4 = T.decl_buffer([390336], \"int8\")\n        p5 = T.decl_buffer([96], \"uint8\")\n        p6 = T.decl_buffer([32], \"uint8\")\n        T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p5[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p6[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 3, 214, 0, 114, buffer3[0], 0, 0, 0, T.float32(0.104816), -128, \"NHWC\", 342, 3, 1, 3, 1, 1, 1, 1, 2, p5[0], 96, 0, p6[0], 32, 0, 1, 0, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n# fmt: on\n\n\ndef test_operators_with_and_without_weights_max_copy_movements_0():\n    test_mod = CopyComputeReordering(0)(OperatorsWithAndWithoutWeights)\n    reference_mod = OperatorsWithAndWithoutWeights\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_operators_with_and_without_weights_max_copy_movements_1():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer2 = T.buffer_decl([80], \"uint8\")\n            buffer3 = T.buffer_decl([64], \"uint8\")\n            buffer4 = T.buffer_decl([96], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            # body\n            p1 = T.decl_buffer([390336], \"int8\")\n            p2 = T.decl_buffer([80], \"uint8\")\n            p3 = T.decl_buffer([64], \"uint8\")\n            p4 = T.decl_buffer([390336], \"int8\")\n            p5 = T.decl_buffer([96], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 3, 214, 0, 114, buffer3[0], 0, 0, 0, T.float32(0.104816), -128, \"NHWC\", 342, 3, 1, 3, 1, 1, 1, 1, 2, p5[0], 96, 0, p6[0], 32, 0, 1, 0, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(1)(OperatorsWithAndWithoutWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_operators_with_and_without_weights_max_copy_movements_2():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer2 = T.buffer_decl([80], \"uint8\")\n            buffer3 = T.buffer_decl([64], \"uint8\")\n            buffer4 = T.buffer_decl([96], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            # body\n            p1 = T.decl_buffer([390336], \"int8\")\n            p2 = T.decl_buffer([80], \"uint8\")\n            p3 = T.decl_buffer([64], \"uint8\")\n            p4 = T.decl_buffer([390336], \"int8\")\n            p5 = T.decl_buffer([96], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 3, 214, 0, 114, buffer3[0], 0, 0, 0, T.float32(0.104816), -128, \"NHWC\", 342, 3, 1, 3, 1, 1, 1, 1, 2, p5[0], 96, 0, p6[0], 32, 0, 1, 0, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(2)(OperatorsWithAndWithoutWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass CopyToBufferWithLocalScope:\n    @T.prim_func\n    def main() -> None:\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([64], \"uint8\")\n        buffer2 = T.buffer_decl([48], \"uint8\")\n        buffer3 = T.buffer_decl([48], \"uint8\")\n        buffer4 = T.buffer_decl([256], \"uint8\")\n        buffer5 = T.buffer_decl([16], \"uint8\")\n        buffer6 = T.buffer_decl([48], \"uint8\")\n        buffer7 = T.buffer_decl([256], \"uint8\")\n        buffer8 = T.buffer_decl([64], \"uint8\")\n        # body\n        p1 = T.decl_buffer([48], \"uint8\")\n        p2 = T.decl_buffer([48], \"uint8\")\n        p3 = T.decl_buffer([256], \"int8\", scope=\"local\")\n        p4 = T.decl_buffer([256], \"int8\")\n        p5 = T.decl_buffer([16], \"uint8\")\n        p6 = T.decl_buffer([48], \"uint8\")\n        p7 = T.decl_buffer([256], \"int8\", scope=\"local\")\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 48, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 48, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 256, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer1[0], 0, 0, 0, T.float32(0.00392081), -128, \"NHWC\", 16, 4, 1, \"int8\", 4, 4, 4, 4, 0, 4, p4[0], 0, 0, 0, T.float32(0.00839574), -128, \"NHCWB16\", 64, 16, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, 0, p2[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 16, p5[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 48, p6[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 256, p7[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, p4[0], 0, 0, 0, T.float32(0.0078125), 0, \"NHCWB16\", 64, 16, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer8[0], 0, 0, 0, T.float32(0.00372155), -128, \"NHWC\", 16, 4, 1, 1, 1, 1, 1, 1, 1, p5[0], 16, 0, p6[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n# fmt: on\n\n\ndef test_copy_to_buffer_with_local_scope_max_copy_movements_0():\n    test_mod = CopyComputeReordering(0)(CopyToBufferWithLocalScope)\n    reference_mod = CopyToBufferWithLocalScope\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\n@pytest.mark.parametrize(\"max_copy_movements\", [1, 2])\ndef test_copy_to_buffer_with_local_scope_max_copy_movements_n(max_copy_movements):\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([64], \"uint8\")\n            buffer2 = T.buffer_decl([48], \"uint8\")\n            buffer3 = T.buffer_decl([48], \"uint8\")\n            buffer4 = T.buffer_decl([256], \"uint8\")\n            buffer5 = T.buffer_decl([16], \"uint8\")\n            buffer6 = T.buffer_decl([48], \"uint8\")\n            buffer7 = T.buffer_decl([256], \"uint8\")\n            buffer8 = T.buffer_decl([64], \"uint8\")\n            # body\n            p1 = T.decl_buffer([48], \"uint8\")\n            p2 = T.decl_buffer([48], \"uint8\")\n            p3 = T.decl_buffer([256], \"int8\", scope=\"local\")\n            p4 = T.decl_buffer([256], \"int8\")\n            p5 = T.decl_buffer([16], \"uint8\")\n            p6 = T.decl_buffer([48], \"uint8\")\n            p7 = T.decl_buffer([256], \"int8\", scope=\"local\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 48, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 48, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 256, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 16, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 48, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer1[0], 0, 0, 0, T.float32(0.00392081), -128, \"NHWC\", 16, 4, 1, \"int8\", 4, 4, 4, 4, 0, 4, p4[0], 0, 0, 0, T.float32(0.00839574), -128, \"NHCWB16\", 64, 16, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, 0, p2[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 256, p7[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, p4[0], 0, 0, 0, T.float32(0.0078125), 0, \"NHCWB16\", 64, 16, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer8[0], 0, 0, 0, T.float32(0.00372155), -128, \"NHWC\", 16, 4, 1, 1, 1, 1, 1, 1, 1, p5[0], 16, 0, p6[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(max_copy_movements)(CopyToBufferWithLocalScope)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_multiple_prim_funcs():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main():\n            T.evaluate(0)\n\n        @T.prim_func\n        def abc():\n            T.evaluate(0)\n    # fmt: on\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the CopyComputeReordering pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        CopyComputeReordering(1)(InputModule)\n\n\ndef test_no_main_prim_func():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def abs():\n            T.evaluate(0)\n    # fmt: on\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the CopyComputeReordering pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        CopyComputeReordering(1)(InputModule)\n\n\ndef test_default_max_copy_movements():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer2 = T.buffer_decl([80], \"uint8\")\n            buffer3 = T.buffer_decl([64], \"uint8\")\n            buffer4 = T.buffer_decl([96], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            # body\n            p1 = T.decl_buffer([390336], \"int8\")\n            p2 = T.decl_buffer([80], \"uint8\")\n            p3 = T.decl_buffer([64], \"uint8\")\n            p4 = T.decl_buffer([390336], \"int8\")\n            p5 = T.decl_buffer([96], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 3, 214, 0, 114, buffer3[0], 0, 0, 0, T.float32(0.104816), -128, \"NHWC\", 342, 3, 1, 3, 1, 1, 1, 1, 2, p5[0], 96, 0, p6[0], 32, 0, 1, 0, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering()(OperatorsWithAndWithoutWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_pass_context_option_max_copy_movements():\n    # fmt: off\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer2 = T.buffer_decl([80], \"uint8\")\n            buffer3 = T.buffer_decl([64], \"uint8\")\n            buffer4 = T.buffer_decl([96], \"uint8\")\n            buffer5 = T.buffer_decl([32], \"uint8\")\n            # body\n            p1 = T.decl_buffer([390336], \"int8\")\n            p2 = T.decl_buffer([80], \"uint8\")\n            p3 = T.decl_buffer([64], \"uint8\")\n            p4 = T.decl_buffer([390336], \"int8\")\n            p5 = T.decl_buffer([96], \"uint8\")\n            p6 = T.decl_buffer([32], \"uint8\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, p1[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 5, 214, 0, 114, p4[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 3, 214, 0, 114, buffer3[0], 0, 0, 0, T.float32(0.104816), -128, \"NHWC\", 342, 3, 1, 3, 1, 1, 1, 1, 2, p5[0], 96, 0, p6[0], 32, 0, 1, 0, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    with tvm.transform.PassContext(\n        config={\"tir.contrib.ethos-u.copy_compute_reordering_max_copy_movements\": 2}\n    ):\n        test_mod = CopyComputeReordering()(OperatorsWithAndWithoutWeights)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_reordering_based_on_cycles():\n    # fmt: off\n    @tvm.script.ir_module\n    class ModuleBefore:\n        @T.prim_func\n        def main(placeholder: T.Buffer[97156, \"int8\"], placeholder_encoded: T.Buffer[208, \"uint8\"], placeholder_encoded_1: T.Buffer[112, \"uint8\"], placeholder_encoded_2: T.Buffer[96, \"uint8\"], placeholder_encoded_3: T.Buffer[112, \"uint8\"], ethosu_write: T.Buffer[43672, \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\", \"from_legacy_te_schedule\": True})\n            ax0_ax1_fused_ax2_fused_ax3_fused = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_1 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_2 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_3 = T.var(\"int32\")\n            nn = T.var(\"int32\")\n            nn_1 = T.var(\"int32\")\n            nn_2 = T.var(\"int32\")\n            nn_3 = T.var(\"int32\")\n            nn_4 = T.var(\"int32\")\n            nn_5 = T.var(\"int32\")\n            # body\n            placeholder_d_global = T.decl_buffer([208], \"uint8\")\n            placeholder_d_global_1 = T.decl_buffer([112], \"uint8\")\n            placeholder_d_global_2 = T.decl_buffer([96], \"uint8\")\n            placeholder_d_global_3 = T.decl_buffer([112], \"uint8\")\n            ethosu_write_1 = T.decl_buffer([195168], \"int8\")\n            ethosu_write_2 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_3 = T.decl_buffer([174688], \"int8\")\n            ethosu_write_4 = T.decl_buffer([174688], \"int8\")\n            ethosu_write_5 = T.decl_buffer([174688], \"int8\")\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1792):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded[0], 208, placeholder_d_global[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 250):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 227, 2, 214, 0, 227, placeholder[0], 0, 0, 0, T.float32(0.0039215679280459881), -128, \"NHWC\", 454, 2, 1, \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, 3, 3, 2, 2, 1, 1, placeholder_d_global[0], 160, T.int8(-1), T.int8(-1), 0, placeholder_d_global[160], 48, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 12, 10, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 112, placeholder_d_global_1[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 467):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_1[0], 64, 0, placeholder_d_global_1[64], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_2[0], 96, placeholder_d_global_2[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 441):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_3[0], 0, 0, 0, T.float32(0.0057637207210063934), -128, \"NHCWB16\", 1696, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_2[0], 48, 0, placeholder_d_global_2[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 439):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_4, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 439):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_5[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_3[0], 112, placeholder_d_global_3[0], dtype=\"handle\"))\n            T.attr(T.iter_var(nn_5, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 22340)\n            T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_5[0], 0, 0, 0, T.float32(0.0057637207210063934), -128, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write[0], 0, 0, 0, T.float32(0.0057619437575340271), -128, \"NHWC\", 424, 4, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_3[0], 64, 0, placeholder_d_global_3[64], 48, 1, 2, 1, 2, \"NONE\", 0, 0, \"TFL\", \"NONE\", 14, 18, 8, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ModuleAfter:\n        @T.prim_func\n        def main(placeholder: T.Buffer[97156, \"int8\"], placeholder_encoded: T.Buffer[208, \"uint8\"], placeholder_encoded_1: T.Buffer[112, \"uint8\"], placeholder_encoded_2: T.Buffer[96, \"uint8\"], placeholder_encoded_3: T.Buffer[112, \"uint8\"], ethosu_write: T.Buffer[43672, \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\", \"from_legacy_te_schedule\": True})\n            ax0_ax1_fused_ax2_fused_ax3_fused = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_1 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_2 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_3 = T.var(\"int32\")\n            nn = T.var(\"int32\")\n            nn_1 = T.var(\"int32\")\n            nn_2 = T.var(\"int32\")\n            nn_3 = T.var(\"int32\")\n            nn_4 = T.var(\"int32\")\n            nn_5 = T.var(\"int32\")\n            # body\n            placeholder_d_global = T.decl_buffer([208], \"uint8\")\n            placeholder_d_global_1 = T.decl_buffer([112], \"uint8\")\n            placeholder_d_global_2 = T.decl_buffer([96], \"uint8\")\n            placeholder_d_global_3 = T.decl_buffer([112], \"uint8\")\n            ethosu_write_1 = T.decl_buffer([195168], \"int8\")\n            ethosu_write_2 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_3 = T.decl_buffer([174688], \"int8\")\n            ethosu_write_4 = T.decl_buffer([174688], \"int8\")\n            ethosu_write_5 = T.decl_buffer([174688], \"int8\")\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1792):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded[0], 208, placeholder_d_global[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 112, placeholder_d_global_1[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 250):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 227, 2, 214, 0, 227, placeholder[0], 0, 0, 0, T.float32(0.0039215679280459881), -128, \"NHWC\", 454, 2, 1, \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, 3, 3, 2, 2, 1, 1, placeholder_d_global[0], 160, T.int8(-1), T.int8(-1), 0, placeholder_d_global[160], 48, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 12, 10, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_2[0], 96, placeholder_d_global_2[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 467):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_1[0], 64, 0, placeholder_d_global_1[64], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1024):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_3[0], 112, placeholder_d_global_3[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 441):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_3[0], 0, 0, 0, T.float32(0.0057637207210063934), -128, \"NHCWB16\", 1696, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_2[0], 48, 0, placeholder_d_global_2[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 439):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_4, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 439):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_5[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1696, 16, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            T.attr(T.iter_var(nn_5, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 22340)\n            T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write_5[0], 0, 0, 0, T.float32(0.0057637207210063934), -128, \"NHCWB16\", 1696, 16, 1, \"int8\", 103, 106, 4, 103, 0, 106, ethosu_write[0], 0, 0, 0, T.float32(0.0057619437575340271), -128, \"NHWC\", 424, 4, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global_3[0], 64, 0, placeholder_d_global_3[64], 48, 1, 2, 1, 2, \"NONE\", 0, 0, \"TFL\", \"NONE\", 14, 18, 8, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(reorder_by_cycles=True)(ModuleBefore)\n    reference_mod = ModuleAfter\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\ndef test_reordering_based_on_cycles_luts_present():\n    # fmt: off\n    @tvm.script.ir_module\n    class ModuleBefore:\n        @T.prim_func\n        def main(placeholder: T.Buffer[97156, \"int8\"], placeholder_encoded: T.Buffer[208, \"uint8\"], placeholder_encoded_1: T.Buffer[112, \"uint8\"], placeholder_1: T.Buffer[256, \"int8\"], placeholder_encoded_2: T.Buffer[96, \"uint8\"], placeholder_2: T.Buffer[256, \"int8\"], placeholder_3: T.Buffer[256, \"int8\"], ethosu_write: T.Buffer[46200, \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\", \"from_legacy_te_schedule\": True})\n            ax0_ax1_fused_ax2_fused_ax3_fused = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_1 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_2 = T.var(\"int32\")\n            nn = T.var(\"int32\")\n            nn_1 = T.var(\"int32\")\n            nn_2 = T.var(\"int32\")\n            nn_3 = T.var(\"int32\")\n            nn_4 = T.var(\"int32\")\n            nn_5 = T.var(\"int32\")\n            # body\n            placeholder_d_d_global = T.decl_buffer([208], \"uint8\")\n            placeholder_d_d_global_1 = T.decl_buffer([112], \"uint8\")\n            placeholder_d_global = T.decl_buffer([96], \"uint8\")\n            ethosu_write_1 = T.decl_buffer([195168], \"int8\")\n            placeholder_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            ethosu_write_2 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_3 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_4 = T.decl_buffer([184800], \"int8\")\n            placeholder_d_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            ethosu_write_5 = T.decl_buffer([184800], \"int8\")\n            placeholder_d_d_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1792):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded[0], 208, placeholder_d_d_global[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 73668):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 227, 2, 214, 0, 227, placeholder[0], 0, 0, 0, T.float32(0.0039215679280459881), -128, \"NHWC\", 454, 2, 1, \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, 3, 3, 2, 2, 1, 1, placeholder_d_d_global[0], 160, T.int8(-1), T.int8(-1), 0, placeholder_d_d_global[160], 48, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 12, 10, 16, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_1[0], 256, placeholder_local[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 384):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 112, placeholder_d_d_global_1[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 330):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_d_global_1[0], 64, 0, placeholder_d_d_global_1[64], 48, 0, 0, 0, 0, \"SIGMOID\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 411):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 458):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_2[0], 256, placeholder_d_local[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1500):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_2[0], 96, placeholder_d_global[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_4, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 10464):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_4[0], 0, 0, 0, T.float32(0.00390625), -128, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_5[0], 0, 0, 0, T.float32(0.00381289585493505), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global[0], 48, 0, placeholder_d_global[48], 48, 1, 2, 1, 2, \"TANH\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_3[0], 256, placeholder_d_d_local[0], dtype=\"handle\"))\n            T.attr(T.iter_var(nn_5, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 5253)\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_5[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 440, 4, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 4, 64, 8, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ModuleAfter:\n        @T.prim_func\n        def main(placeholder: T.Buffer[97156, \"int8\"], placeholder_encoded: T.Buffer[208, \"uint8\"], placeholder_encoded_1: T.Buffer[112, \"uint8\"], placeholder_1: T.Buffer[256, \"int8\"], placeholder_encoded_2: T.Buffer[96, \"uint8\"], placeholder_2: T.Buffer[256, \"int8\"], placeholder_3: T.Buffer[256, \"int8\"], ethosu_write: T.Buffer[46200, \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\", \"from_legacy_te_schedule\": True})\n            ax0_ax1_fused_ax2_fused_ax3_fused = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_1 = T.var(\"int32\")\n            ax0_ax1_fused_ax2_fused_ax3_fused_2 = T.var(\"int32\")\n            nn = T.var(\"int32\")\n            nn_1 = T.var(\"int32\")\n            nn_2 = T.var(\"int32\")\n            nn_3 = T.var(\"int32\")\n            nn_4 = T.var(\"int32\")\n            nn_5 = T.var(\"int32\")\n            # body\n            placeholder_d_d_global = T.decl_buffer([208], \"uint8\")\n            placeholder_d_d_global_1 = T.decl_buffer([112], \"uint8\")\n            placeholder_d_global = T.decl_buffer([96], \"uint8\")\n            ethosu_write_1 = T.decl_buffer([195168], \"int8\")\n            placeholder_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            ethosu_write_2 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_3 = T.decl_buffer([184800], \"int8\")\n            ethosu_write_4 = T.decl_buffer([184800], \"int8\")\n            placeholder_d_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            ethosu_write_5 = T.decl_buffer([184800], \"int8\")\n            placeholder_d_d_local = T.decl_buffer([256], \"int8\", scope=\"local\")\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1792):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded[0], 208, placeholder_d_d_global[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 384):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 112, placeholder_d_d_global_1[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 73668):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 227, 2, 214, 0, 227, placeholder[0], 0, 0, 0, T.float32(0.0039215679280459881), -128, \"NHWC\", 454, 2, 1, \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, 3, 3, 2, 2, 1, 1, placeholder_d_d_global[0], 160, T.int8(-1), T.int8(-1), 0, placeholder_d_d_global[160], 48, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 12, 10, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(ax0_ax1_fused_ax2_fused_ax3_fused_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 1500):\n                T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_2[0], 96, placeholder_d_global[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_1[0], 256, placeholder_local[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_1, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 330):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 107, 114, 4, 107, 0, 114, ethosu_write_1[0], 0, 0, 0, T.float32(0.009109782986342907), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(0.0066184266470372677), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_d_global_1[0], 64, 0, placeholder_d_d_global_1[64], 48, 0, 0, 0, 0, \"SIGMOID\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_2, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 411):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_2[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_3, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 458):\n                T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 2, 64, 16, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_2[0], 256, placeholder_d_local[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(nn_4, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 10464):\n                T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_4[0], 0, 0, 0, T.float32(0.00390625), -128, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_5[0], 0, 0, 0, T.float32(0.00381289585493505), -128, \"NHCWB16\", 1760, 16, 1, 3, 2, 1, 1, 2, 2, placeholder_d_global[0], 48, 0, placeholder_d_global[48], 48, 1, 2, 1, 2, \"TANH\", 0, 0, \"TFL\", \"NONE\", 8, 16, 16, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_3[0], 256, placeholder_d_d_local[0], dtype=\"handle\"))\n            T.attr(T.iter_var(nn_5, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 5253)\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write_5[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1760, 16, 1, \"int8\", 105, 110, 4, 105, 0, 110, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 440, 4, 1, \"MAX\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 4, 64, 8, dtype=\"handle\"))\n    # fmt: on\n\n    test_mod = CopyComputeReordering(reorder_by_cycles=True)(ModuleBefore)\n    reference_mod = ModuleAfter\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_create_tiles.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm.script\nfrom tvm.relay.backend.contrib.ethosu.tir.dma import Tiles, create_tiles\nfrom tvm.script import tir as T\n\n\ndef check_tiles_equal(tiles, expected):\n    assert tiles.height_0 == expected.height_0\n    assert tiles.height_1 == expected.height_1\n    assert tiles.width_0 == expected.width_0\n    if isinstance(tiles.address_0, int):\n        assert tiles.address_0 == expected.address_0\n    else:\n        assert tiles.address_0.buffer == expected.address_0.buffer\n        assert tiles.address_0.indices[0] == expected.address_0.indices[0]\n    if isinstance(tiles.address_1, int):\n        assert tiles.address_1 == expected.address_1\n    else:\n        assert tiles.address_1.buffer == expected.address_1.buffer\n        assert tiles.address_1.indices[0] == expected.address_1.indices[0]\n    if isinstance(tiles.address_2, int):\n        assert tiles.address_2 == expected.address_2\n    else:\n        assert tiles.address_2.buffer == expected.address_2.buffer\n        assert tiles.address_2.indices[0] == expected.address_2.indices[0]\n\n\ndef test_create_tiles_h():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder1: T.Buffer[(100,), \"int8\"], placeholder2: T.Buffer[(100,), \"int8\"]) -> None:\n            T.attr(\"i0\", \"pragma_layout\", \"NHCWB16\")\n            for i0 in T.serial(0, 1):\n                for i1 in T.serial(0, 6):\n                    for i2 in T.serial(0, 1):\n                        for i3 in T.serial(0, 1):\n                            for i4 in T.serial(0, 16):\n                                placeholder1[((i1*16) + i4)] = placeholder2[((T.floormod((i1 + 4), 6)*16) + i4)]\n\n        __tvm_meta__ = None\n    # fmt: on\n\n    stmt = Module[\"main\"].body\n    tiles = create_tiles(stmt)\n    buffer = stmt.body.body.body.body.body.body.value.buffer\n    expected = Tiles(\n        height_0=tvm.tir.expr.IntImm(\"int32\", 2),\n        height_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        width_0=tvm.tir.expr.IntImm(\"int32\", 1),\n        address_0=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 64)]),\n        address_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        address_2=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 0)]),\n    )\n    check_tiles_equal(tiles, expected)\n\n\ndef test_create_tiles_w():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder1: T.Buffer[(100,), \"int8\"], placeholder2: T.Buffer[(100,), \"int8\"]) -> None:\n            T.attr(\"i0\", \"pragma_layout\", \"NHCWB16\")\n            for i0 in T.serial(0, 1):\n                for i1 in T.serial(0, 1):\n                    for i2 in T.serial(0, 1):\n                        for i3 in T.serial(0, 6):\n                            for i4 in T.serial(0, 16):\n                                placeholder1[((i3*16) + i4)] = placeholder2[((T.floormod((i3 + 4), 6)*16) + i4)]\n\n        __tvm_meta__ = None\n    # fmt: on\n\n    stmt = Module[\"main\"].body\n    tiles = create_tiles(stmt)\n    buffer = stmt.body.body.body.body.body.body.value.buffer\n    expected = Tiles(\n        height_0=tvm.tir.expr.IntImm(\"int32\", 1),\n        height_1=tvm.tir.expr.IntImm(\"int32\", 1),\n        width_0=tvm.tir.expr.IntImm(\"int32\", 2),\n        address_0=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 64)]),\n        address_1=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 0)]),\n        address_2=tvm.tir.expr.IntImm(\"int32\", 0),\n    )\n    check_tiles_equal(tiles, expected)\n\n\ndef test_create_tiles_wrong_var_stride():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder1: T.Buffer[(100,), \"int8\"], placeholder2: T.Buffer[(100,), \"int8\"]) -> None:\n            T.attr(\"i0\", \"pragma_layout\", \"NHCWB16\")\n            for i0 in T.serial(0, 1):\n                for i1 in T.serial(0, 6):\n                    for i2 in T.serial(0, 1):\n                        for i3 in T.serial(0, 1):\n                            for i4 in T.serial(0, 16):\n                                placeholder1[((i1*16) + i4)] = placeholder2[((T.floormod((i1 + 4), 6)*8) + i4)]\n\n        __tvm_meta__ = None\n    # fmt: on\n\n    stmt = Module[\"main\"].body\n    tiles = create_tiles(stmt)\n    buffer = stmt.body.body.body.body.body.body.value.buffer\n    expected = Tiles(\n        height_0=tvm.tir.expr.IntImm(\"int32\", 6),\n        height_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        width_0=tvm.tir.expr.IntImm(\"int32\", 1),\n        address_0=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 32)]),\n        address_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        address_2=tvm.tir.expr.IntImm(\"int32\", 0),\n    )\n    check_tiles_equal(tiles, expected)\n\n\ndef test_create_tiles_multiple_var_occurrences():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder1: T.Buffer[(100,), \"int8\"], placeholder2: T.Buffer[(100,), \"int8\"]) -> None:\n            T.attr(\"i0\", \"pragma_layout\", \"NHWC\")\n            for i0 in T.serial(0, 1):\n                for i1 in T.serial(0, 5):\n                    for i2 in T.serial(0, 6):\n                        for i3 in T.serial(0, 4):\n                            placeholder1[(((i1*24) + (i2*4)) + i3)] = placeholder2[(((((T.floordiv((i1 - 1), 2)*48) + (T.floormod((i1 + 1), 2)*24)) + (i2*4)) + i3) + 96)]\n\n        __tvm_meta__ = None\n    # fmt: on\n\n    stmt = Module[\"main\"].body\n    tiles = create_tiles(stmt)\n    buffer = stmt.body.body.body.body.body.value.buffer\n    expected = Tiles(\n        height_0=tvm.tir.expr.IntImm(\"int32\", 5),\n        height_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        width_0=tvm.tir.expr.IntImm(\"int32\", 6),\n        address_0=tvm.tir.BufferLoad(buffer, [tvm.tir.expr.IntImm(\"int32\", 72)]),\n        address_1=tvm.tir.expr.IntImm(\"int32\", 0),\n        address_2=tvm.tir.expr.IntImm(\"int32\", 0),\n    )\n    check_tiles_equal(tiles, expected)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_encode_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport numpy as np\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm import relay\nfrom tvm.script import tir as T\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import OperatorCompute\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import copy_constants\nfrom tvm.relay.backend.contrib.ethosu import tir_to_cs_translator\n\nfrom .infra import make_ethosu_conv2d, make_ethosu_binary_elementwise\n\n\n# fmt: off\n@tvm.script.ir_module\nclass WeightStreamOnlyU55:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([160], \"uint8\")\n        buffer3 = T.buffer_decl([144], \"uint8\")\n        buffer5 = T.buffer_decl([144], \"uint8\")\n        buffer7 = T.buffer_decl([144], \"uint8\")\n        buffer8 = T.buffer_decl([32], \"uint8\")\n        # body\n        p1_data = T.allocate([160], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([160], \"uint8\", data=p1_data)\n        p2_data = T.allocate([144], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([144], \"uint8\", data=p2_data)\n        buffer9 = T.buffer_decl([144], \"uint8\", data=p1.data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 160, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 144, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, T.int8(-1), T.int8(-1), 12, p1[128], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 144, buffer9[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, T.int8(-1), T.int8(-1), 12, p2[112], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 144, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, buffer9[0], 112, T.int8(-1), T.int8(-1), 12, buffer9[112], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, T.int8(-1), T.int8(-1), 12, p2[112], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass WeightStreamOnlyU65:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        # buffer definition\n        buffer_encoded_1 = T.buffer_decl([192], dtype=\"uint8\")\n        buffer_encoded_2_1 = T.buffer_decl([192], dtype=\"uint8\")\n        buffer_encoded_4_1 = T.buffer_decl([208], dtype=\"uint8\")\n        buffer_encoded_6_1 = T.buffer_decl([192], dtype=\"uint8\")\n        # body\n        p1_data = T.allocate([208], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([208], \"uint8\", data=p1_data)\n        p2_data = T.allocate([192], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([192], \"uint8\", data=p2_data)\n        p3 = T.buffer_decl([192], dtype=\"uint8\", data=p1.data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_1[0], 192, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_2_1[0], 192, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 80, p3[80], 80, 12, p3[160], 16, p3[176], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_4_1[0], 208, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 80, p2[80], 80, 12, p2[160], 16, p2[176], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_6_1[0], 192, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 96, p1[96], 80, 12, p1[176], 16, p1[192], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 80, p2[80], 80, 12, p2[160], 16, p2[176], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"accelerator, reference_mod, reference_const_sizes\",\n    [\n        (\n            \"ethos-u55-128\",\n            WeightStreamOnlyU55,\n            [160, 144, 144, 144],\n        ),\n        (\n            \"ethos-u65-512\",\n            WeightStreamOnlyU65,\n            [192, 192, 208, 192],\n        ),\n    ],\n)\ndef test_weight_stream_only(accelerator, reference_mod, reference_const_sizes):\n    def _planner(cached_func, const_dict, sch):\n        weights = cached_func.inputs[1]\n        bias = cached_func.inputs[2]\n        out = cached_func.outputs[0]\n        conv_compute = OperatorCompute.from_output(out)\n        co = conv_compute.split(sch, 3, 2)\n        cache_weights = sch.cache_read(weights, \"global\", [conv_compute.op])\n        cache_bias = sch.cache_read(bias, \"global\", [conv_compute.op])\n        sch[cache_weights].compute_at(sch[out], co)\n        sch[cache_bias].compute_at(sch[out], co)\n\n    def _get_func():\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            ifm,\n            32,\n            8,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    config = {\n        \"accelerator_config\": accelerator,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        func = _get_func()\n        mod, consts = _lower_to_tir(func, cascader=_planner)\n        script = mod.script(show_meta=True)\n        test_mod = tvm.script.from_source(script)\n        tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n        test_const_size = [value.size for value in list(consts.values())]\n        assert reference_const_sizes.sort() == test_const_size.sort()\n\n\n# fmt: off\n@tvm.script.ir_module\nclass RereadWeightsU55:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([384], \"uint8\")\n        # body\n        p1_data = T.allocate([384], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([384], \"uint8\", data=p1_data)\n        p2_data = T.allocate([384], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([384], \"uint8\", data=p2_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 384, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 384, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 304, T.int8(-1), T.int8(-1), 12, p1[304], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[256], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[64], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 304, T.int8(-1), T.int8(-1), 12, p2[304], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass RereadWeightsU65:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        # buffer definition\n        placeholder_encoded_1 = T.buffer_decl([464], \"uint8\")\n        # body\n        p1_data = T.allocate([464], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([464], \"uint8\", data=p1_data)\n        p2_data = T.allocate([464], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([464], \"uint8\", data=p2_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 464, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 464, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p1[368], 48, p1[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[256], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[64], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 192, p2[192], 176, 12, p2[368], 48, p2[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"accelerator, reference_mod, reference_const_sizes\",\n    [\n        (\n            \"ethos-u55-128\",\n            RereadWeightsU55,\n            [384],\n        ),\n        (\n            \"ethos-u65-512\",\n            RereadWeightsU65,\n            [464],\n        ),\n    ],\n)\ndef test_re_read_weights(accelerator, reference_mod, reference_const_sizes):\n    def _cascader(cached_func, const_dict, sch):\n        weights = cached_func.inputs[1]\n        bias = cached_func.inputs[2]\n        out = cached_func.outputs[0]\n        conv_compute = OperatorCompute.from_output(out)\n        co = conv_compute.split(sch, 2, 8)\n        cache_weights = sch.cache_read(weights, \"global\", [conv_compute.op])\n        cache_bias = sch.cache_read(bias, \"global\", [conv_compute.op])\n        sch[cache_weights].compute_at(sch[out], co)\n        sch[cache_bias].compute_at(sch[out], co)\n\n    def _get_func():\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            ifm,\n            32,\n            8,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    config = {\n        \"accelerator_config\": accelerator,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        func = _get_func()\n        mod, consts = _lower_to_tir(func, cascader=_cascader)\n        script = mod.script(show_meta=True)\n        test_mod = tvm.script.from_source(script)\n        tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n        test_const_size = [value.size for value in list(consts.values())]\n        assert reference_const_sizes.sort() == test_const_size.sort()\n\n\n# fmt: off\n@tvm.script.ir_module\nclass DirectReadOnlyU55:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([592], \"uint8\")\n        buffer_1 = T.buffer_decl([160], \"uint8\")\n        buffer_2 = T.buffer_decl([160], \"uint8\")\n        buffer_3 = T.buffer_decl([80], \"uint8\")\n        # body\n        ethosu_write_1_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        ethosu_write_1 = T.buffer_decl([4096], \"int8\", data=ethosu_write_1_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, buffer[0], 592, T.int8(-1), T.int8(-1), 12, buffer_1[0], 160, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 8, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, buffer_2[0], 160, T.int8(-1), T.int8(-1), 12, buffer_3[0], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass DirectReadOnlyU65:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        # buffer definition\n        placeholder_encoded = T.buffer_decl([608], dtype=\"uint8\")\n        placeholder_encoded_1 = T.buffer_decl([160], dtype=\"uint8\")\n        placeholder_encoded_2 = T.buffer_decl([208], dtype=\"uint8\")\n        placeholder_encoded_3 = T.buffer_decl([96], dtype=\"uint8\")\n        # body\n        ethosu_write_2_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        ethosu_write_2 = T.buffer_decl([4096], \"int8\", data=ethosu_write_2_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, placeholder_encoded[0], 304, placeholder_encoded[304], 304, 12, placeholder_encoded_1[0], 80, placeholder_encoded_1[80], 80, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 8, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_encoded_2[0], 112, placeholder_encoded_2[112], 96, 12, placeholder_encoded_3[0], 48, placeholder_encoded_3[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"accelerator, reference_mod, reference_const_sizes\",\n    [\n        (\n            \"ethos-u55-128\",\n            DirectReadOnlyU55,\n            [592, 160, 160, 80],\n        ),\n        (\n            \"ethos-u65-512\",\n            DirectReadOnlyU65,\n            [608, 160, 208, 96],\n        ),\n    ],\n)\ndef test_direct_read_only(accelerator, reference_mod, reference_const_sizes):\n    def _get_func():\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv1 = make_ethosu_conv2d(\n            ifm,\n            32,\n            16,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        conv2 = make_ethosu_conv2d(\n            conv1,\n            16,\n            8,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    config = {\n        \"accelerator_config\": accelerator,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        func = _get_func()\n        mod, consts = _lower_to_tir(func)\n\n        script = mod.script(show_meta=True)\n        test_mod = tvm.script.from_source(script)\n        tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n        test_const_size = [value.size for value in list(consts.values())]\n        assert reference_const_sizes.sort() == test_const_size.sort()\n\n\n# fmt: off\n@tvm.script.ir_module\nclass MixedReadU55:\n    @T.prim_func\n    def main(ifm: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([112], \"uint8\")\n        buffer3 = T.buffer_decl([112], \"uint8\")\n        buffer5 = T.buffer_decl([112], \"uint8\")\n        buffer7 = T.buffer_decl([112], \"uint8\")\n        buffer9 = T.buffer_decl([592], \"uint8\")\n        buffer10 = T.buffer_decl([160], \"uint8\")\n        # body\n        p1_data = T.allocate([112], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([112], \"uint8\", data=p1_data)\n        p3_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p3 = T.buffer_decl([4096], \"int8\", data=p3_data)\n        p2_data = T.allocate([112], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([112], \"uint8\", data=p2_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 112, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, ifm[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 16, 16, 0, 16, p3[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, buffer9[0], 592, T.int8(-1), T.int8(-1), 12, buffer10[0], 160, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 112, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 80, T.int8(-1), T.int8(-1), 12, p1[80], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 112, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 80, T.int8(-1), T.int8(-1), 12, p2[80], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 112, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 80, T.int8(-1), T.int8(-1), 12, p1[80], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 80, T.int8(-1), T.int8(-1), 12, p2[80], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass MixedReadU65:\n    @T.prim_func\n    def main(ifm: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n\n        # buffer definition\n        buffer1 = T.buffer_decl([128], dtype=\"uint8\")\n        buffer2 = T.buffer_decl([128], dtype=\"uint8\")\n        buffer3 = T.buffer_decl([128], dtype=\"uint8\")\n        buffer4 = T.buffer_decl([608], dtype=\"uint8\")\n        buffer5 = T.buffer_decl([160], dtype=\"uint8\")\n        buffer6 = T.buffer_decl([128], dtype=\"uint8\")\n        p1_data = T.allocate([128], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([128], \"uint8\", data=p1_data)\n        p2_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([4096], \"int8\", data=p2_data)\n        p3_data = T.allocate([128], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p3 = T.buffer_decl([128], \"uint8\", data=p3_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 128, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, ifm[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 16, 16, 0, 16, p2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, buffer4[0], 304, buffer4[304], 304, 12, buffer5[0], 80, buffer5[80], 80, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, p1[48], 48, 12, p1[96], 16, p1[112], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 128, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 48, p3[48], 48, 12, p3[96], 16, p3[112], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 128, p3[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, p1[48], 48, 12, p1[96], 16, p1[112], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, p2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 48, p3[48], 48, 12, p3[96], 16, p3[112], 16, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"accelerator, reference_mod, reference_const_sizes\",\n    [\n        (\n            \"ethos-u55-128\",\n            MixedReadU55,\n            [592, 160, 112, 112, 112, 112],\n        ),\n        (\n            \"ethos-u65-512\",\n            MixedReadU65,\n            [608, 160, 128, 128, 128, 128],\n        ),\n    ],\n)\ndef test_mixed_read(accelerator, reference_mod, reference_const_sizes):\n    def _planner(cached_func, const_dict, sch):\n        weight = cached_func.inputs[4]\n        scale_bias = cached_func.inputs[5]\n        out = cached_func.outputs[0]\n        conv_compute = OperatorCompute.from_output(out)\n        co = conv_compute.split(sch, 3, 2)\n        cache_weight = sch.cache_read(weight, \"global\", [conv_compute.op])\n        cache_scale_bias = sch.cache_read(scale_bias, \"global\", [conv_compute.op])\n        sch[cache_weight].compute_at(sch[out], co)\n        sch[cache_scale_bias].compute_at(sch[out], co)\n\n    def _get_func():\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv1 = make_ethosu_conv2d(\n            ifm,\n            32,\n            16,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        conv2 = make_ethosu_conv2d(\n            conv1,\n            16,\n            8,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    config = {\n        \"accelerator_config\": accelerator,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        func = _get_func()\n        mod, consts = _lower_to_tir(func, cascader=_planner)\n\n        script = mod.script(show_meta=True)\n        test_mod = tvm.script.from_source(script)\n        tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n        test_const_size = [value.size for value in list(consts.values())]\n        assert reference_const_sizes.sort() == test_const_size.sort()\n\n\ndef test_constant_as_input():\n    \"\"\"Test to check that constants specified as inputs aren't\n    interpreted as an encoded constant.\"\"\"\n\n    def get_graph():\n        dtype = \"uint8\"\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=dtype)\n        conv1 = make_ethosu_conv2d(\n            ifm,\n            32,\n            16,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        scalar = relay.const(np.ones((1, 1, 1, 1), dtype=dtype), dtype=dtype)\n        add1 = make_ethosu_binary_elementwise(\n            conv1, scalar, ifm_channels=32, ifm2_channels=1, operator_type=\"ADD\", ofm_dtype=dtype\n        )\n        func = relay.Function(relay.analysis.free_vars(add1), add1)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    tir_mod, params = _lower_to_tir(get_graph(), copy_constants())\n\n    # Check tile address for the scalar constant input hasn't been\n    # overwritten.\n    extern_calls = tir_mod[\"main\"].body.body.body.body\n    binary_elementwise = extern_calls[-1].value\n    args = binary_elementwise.args\n\n    reason = \"Tile address overwritten\"\n    assert args[26] == 0, reason\n    assert args[27] == 0, reason\n    assert args[28] == 0, reason\n\n    # More generally, check compiles successfully to make sure\n    # nothing else was overrwritten.\n    # With Target Hooks the TIR module needs a target attached\n    # and lowered via make unpacked API.\n    tir_mod[\"main\"] = tir_mod[\"main\"].with_attr(\"target\", tvm.target.Target(\"ethos-u\"))\n    tir_mod = tvm.tir.transform.MakeUnpackedAPI()(tir_mod)\n    tir_to_cs_translator.translate(tir_mod, params)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_extract_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import extract_constants\n\nimport numpy as np\n\n\ndef test_extract_constants_single():\n    def _get_func():\n        var_input = relay.var(\"data\", shape=(10, 10), dtype=\"uint8\")\n        const_data = np.random.uniform(0, 255, (10, 10)).astype(\"uint8\")\n        const_input = relay.const(const_data, dtype=\"uint8\")\n        out = relay.add(var_input, const_input)\n        func = relay.Function(relay.analysis.free_vars(out), out)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func, const_input\n\n    def _expected():\n        var_input1 = relay.var(\"data\", shape=(10, 10), dtype=\"uint8\")\n        var_input2 = relay.var(\"p1\", shape=(10, 10), dtype=\"uint8\")\n        out = relay.add(var_input1, var_input2)\n        func = relay.Function(relay.analysis.free_vars(out), out)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func, const = _get_func()\n    new_func, const_dict = extract_constants(func)\n    assert tvm.ir.structural_equal(new_func, _expected())\n    assert 1 in const_dict\n    assert (const_dict[1] == const.data.asnumpy()).all()\n\n\ndef test_extract_constants_multi():\n    def _get_func():\n        var_input1 = relay.var(\"data1\", shape=(10, 10), dtype=\"uint8\")\n        var_input2 = relay.var(\"data2\", shape=(10, 10), dtype=\"uint8\")\n        const_data_1 = np.random.uniform(0, 255, (10, 10)).astype(\"uint8\")\n        const_data_2 = np.random.uniform(0, 255, (10, 10)).astype(\"uint8\")\n        const_data_3 = np.random.uniform(0, 255, (10, 10)).astype(\"uint8\")\n        const_data_4 = np.random.uniform(0, 255, (10, 10)).astype(\"uint8\")\n        const_input_1 = relay.const(const_data_1, dtype=\"uint8\")\n        const_input_2 = relay.const(const_data_2, dtype=\"uint8\")\n        const_input_3 = relay.const(const_data_3, dtype=\"uint8\")\n        const_input_4 = relay.const(const_data_4, dtype=\"uint8\")\n        out = relay.add(var_input1, var_input2)\n        out = relay.add(out, const_input_1)\n        out = relay.add(out, const_input_2)\n        out = relay.add(out, const_input_3)\n        out = relay.add(out, const_input_4)\n        func = relay.Function(relay.analysis.free_vars(out), out)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func, [const_input_1, const_input_2, const_input_3, const_input_4]\n\n    def _expected():\n        var_input1 = relay.var(\"data1\", shape=(10, 10), dtype=\"uint8\")\n        var_input2 = relay.var(\"data2\", shape=(10, 10), dtype=\"uint8\")\n        var_input3 = relay.var(\"p1\", shape=(10, 10), dtype=\"uint8\")\n        var_input4 = relay.var(\"p2\", shape=(10, 10), dtype=\"uint8\")\n        var_input5 = relay.var(\"p3\", shape=(10, 10), dtype=\"uint8\")\n        var_input6 = relay.var(\"p4\", shape=(10, 10), dtype=\"uint8\")\n        out = relay.add(var_input1, var_input2)\n        out = relay.add(out, var_input3)\n        out = relay.add(out, var_input4)\n        out = relay.add(out, var_input5)\n        out = relay.add(out, var_input6)\n        func = relay.Function(relay.analysis.free_vars(out), out)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func, consts = _get_func()\n    new_func, const_dict = extract_constants(func)\n    assert tvm.ir.structural_equal(new_func, _expected())\n    for i, const in enumerate(consts):\n        assert i + 2 in const_dict\n        assert (const_dict[i + 2] == consts[i].data.asnumpy()).all()\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_hoist_allocates.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTesting the pass that moves allocate nodes to the body of the function.\n\"\"\"\n# pylint: disable=wrong-import-position\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.relay.backend.contrib.ethosu.tir.passes import HoistAllocates\n\n\nclass ExtractAllocateInfo:\n    \"\"\"\n    Extracts information from allocate nodes which we will use as sanity to check the allocate\n    after mutation.\n    \"\"\"\n\n    def __init__(self):\n        self.allocates_info = []\n\n    def __call__(self, mod):\n        tvm.tir.stmt_functor.ir_transform(mod[\"main\"].body, self._pre_visit, None, [\"tir.Allocate\"])\n        return self.allocates_info\n\n    def _pre_visit(self, stmt):\n        self.allocates_info.append(\n            {\"extents\": stmt.extents, \"dtype\": stmt.dtype, \"condition\": stmt.condition}\n        )\n\n\ndef CheckAllocates(allocate_info):  # pylint: disable=invalid-name\n    \"\"\"\n    Checks that all allocates have been visited before an external call has been visited and\n    checks that the information for each allocate is what is expected. Additionally, the pass\n    checks the body of the tir after the final allocate statement is flat (it contains no\n    sequence statement).\n    \"\"\"\n\n    allocate_idx = 0\n    expected_num_allocates = len(allocate_info)\n    num_seq_stmts = 0\n\n    def _pre_visit(stmt):\n        nonlocal allocate_idx, expected_num_allocates, num_seq_stmts\n\n        if isinstance(stmt, tvm.tir.Allocate):\n            expected = allocate_info[allocate_idx]\n            assert (\n                stmt.extents == expected[\"extents\"]\n            ), f\"Allocate extents {stmt.extents} did not match expected {expected['extents']}\"\n            assert (\n                stmt.dtype == expected[\"dtype\"]\n            ), f\"Allocate dtype {stmt.dtype} did not match expected {expected['dtype']}\"\n            assert (\n                stmt.condition == expected[\"condition\"]\n            ), f\"Allocate condition {stmt.condition} did not match expected {expected['condition']}\"\n\n            allocate_idx += 1\n        elif isinstance(stmt, tvm.tir.SeqStmt):\n            num_seq_stmts += 1\n            assert num_seq_stmts <= expected_num_allocates, (\n                \"Encountered a SeqStmt after all allocates have been visited, was the \"\n                \"body flattened correctly?\"\n            )\n        else:\n            assert (\n                allocate_idx == expected_num_allocates\n            ), \"A call node was visited before all allocates\"\n\n    def _ftransform(f, mod, ctx):\n        f.with_body(\n            tvm.tir.stmt_functor.ir_transform(\n                f.body, _pre_visit, None, [\"tir.Allocate\", \"tir.Call\", \"tir.SeqStmt\"]\n            )\n        )\n\n    return tvm.tir.transform.prim_func_pass(_ftransform, opt_level=0)\n\n\ndef test_double_convolution():\n    \"\"\"\n    Test to check the HoistAllocates pass works on a function with two convolutions.\n    \"\"\"\n\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(3402,), \"int8\"], placeholder_encoded: T.Buffer[(128,), \"uint8\"], placeholder_encoded_1: T.Buffer[(32,), \"uint8\"], placeholder_encoded_2: T.Buffer[(128,), \"uint8\"], placeholder_encoded_3: T.Buffer[(32,), \"uint8\"], ethosu_write: T.Buffer[(3402,), \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            T.preflattened_buffer(placeholder, [1, 27, 42, 3], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(placeholder_encoded, [3, 3, 2, 3], dtype=\"int8\")\n            T.preflattened_buffer(placeholder_encoded_1, [3, 10], dtype=\"uint8\")\n            T.preflattened_buffer(placeholder_encoded_2, [3, 3, 2, 3], dtype=\"int8\")\n            T.preflattened_buffer(placeholder_encoded_3, [3, 10], dtype=\"uint8\")\n            T.preflattened_buffer(ethosu_write, [1, 27, 42, 3], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            placeholder_global_data = T.allocate([128], \"uint8\", \"global\")\n            placeholder_global = T.buffer_decl([128], \"uint8\", data=placeholder_global_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded[0], 128, placeholder_global[0], dtype=\"handle\"))\n            placeholder_d_global_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_1[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n            ethosu_write_2_data = T.allocate([18144], \"int8\", \"global\")\n            ethosu_write_2 = T.buffer_decl([18144], \"int8\", data=ethosu_write_2_data)\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 27, 42, 3, 27, 0, 42, placeholder[0], 0, 0, 0, T.float32(0.0039215646684169769), -128, \"NHWC\", 126, 3, 1, \"int8\", 27, 42, 3, 27, 0, 42, ethosu_write_2[0], 0, 0, 0, T.float32(0.031308155506849289), -128, \"NHCWB16\", 672, 16, 1, 2, 3, 1, 1, 1, 2, placeholder_global[0], 128, 0, placeholder_d_global[0], 32, 2, 0, 2, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            placeholder_d_global_1_data = T.allocate([128], \"uint8\", \"global\")\n            placeholder_d_global_1 = T.buffer_decl([128], \"uint8\", data=placeholder_d_global_1_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_2[0], 128, placeholder_d_global_1[0], dtype=\"handle\"))\n            placeholder_d_global_2_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global_2 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_2_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_encoded_3[0], 32, placeholder_d_global_2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 27, 42, 3, 27, 0, 42, ethosu_write_2[0], 0, 0, 0, T.float32(0.031308155506849289), -128, \"NHCWB16\", 672, 16, 1, \"int8\", 27, 42, 3, 27, 0, 42, ethosu_write[0], 0, 0, 0, T.float32(0.23604340851306915), -128, \"NHWC\", 126, 3, 1, 2, 3, 1, 1, 1, 2, placeholder_d_global_1[0], 128, 0, placeholder_d_global_2[0], 32, 2, 0, 2, 1, \"CLIP\", -128, 127, \"TFL\", \"NONE\", dtype=\"handle\"))\n    # fmt: on\n\n    mod = Module\n    allocate_info = ExtractAllocateInfo()(mod)\n    mod = HoistAllocates()(mod)\n    CheckAllocates(allocate_info)(mod)\n\n\ndef test_identities():\n    \"\"\"\n    Test to check the HoistAllocates pass works on a function with multiple identity\n    operations, with no copy operations.\n    \"\"\"\n\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(24,), \"int8\"], T_concat: T.Buffer[(24,), \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            T.preflattened_buffer(placeholder, [1, 2, 3, 4], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(T_concat, [24], dtype=\"int8\", data=T_concat.data)\n            # body\n            ethosu_write_data = T.allocate([12], \"int8\", \"global\")\n            ethosu_write = T.buffer_decl([12], \"int8\", data=ethosu_write_data)\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 3, 4, 1, 0, 3, placeholder[12], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            ethosu_write_1_data = T.allocate([12], \"int8\", \"global\")\n            ethosu_write_1 = T.buffer_decl([12], \"int8\", data=ethosu_write_1_data)\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write_1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 12, 1, 1, 12, 0, 1, ethosu_write_1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 1, 1, \"int8\", 12, 1, 1, 12, 0, 1, T_concat[12], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 1, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            ethosu_write_2_data = T.allocate([12], \"int8\", \"global\")\n            ethosu_write_2 = T.buffer_decl([12], \"int8\", data=ethosu_write_2_data)\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 3, 4, 1, 0, 3, placeholder[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            ethosu_write_3_data = T.allocate([12], \"int8\", \"global\")\n            ethosu_write_3 = T.buffer_decl([12], \"int8\", data=ethosu_write_3_data)\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 3, 4, 1, 0, 3, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 12, 1, 1, 12, 0, 1, ethosu_write_3[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 1, 1, \"int8\", 12, 1, 1, 12, 0, 1, T_concat[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 1, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", dtype=\"handle\"))\n    # fmt: on\n\n    mod = Module\n    allocate_info = ExtractAllocateInfo()(mod)\n    mod = HoistAllocates()(mod)\n    CheckAllocates(allocate_info)(mod)\n\n\ndef test_outer_seq_stmt():\n    \"\"\"\n    Test to check the HoistAllocates pass works on a function where the outer-most statement is\n    a sequence statement, rather than the usual allocate.\n    \"\"\"\n\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"], buffer_encoded: T.Buffer[(128,), \"uint8\"], buffer_encoded_1: T.Buffer[(32,), \"uint8\"], buffer_encoded_2: T.Buffer[(112,), \"uint8\"], buffer_encoded_3: T.Buffer[(32,), \"uint8\"], buffer_encoded_4: T.Buffer[(112,), \"uint8\"], buffer_encoded_5: T.Buffer[(32,), \"uint8\"], buffer_encoded_6: T.Buffer[(112,), \"uint8\"], buffer_encoded_7: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            with T.allocate([128], \"uint8\", \"global\") as placeholder_global_data:\n                placeholder_global = T.buffer_decl([128], \"uint8\", data=placeholder_global_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded[0], 128, placeholder_global[0], dtype=\"handle\"))\n                placeholder_d_global_data = T.allocate([32], \"uint8\", \"global\")\n                placeholder_d_global = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_1[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 128, 12, placeholder_d_global[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.allocate([112], \"uint8\", \"global\") as placeholder_global_1_data:\n                placeholder_global_1 = T.buffer_decl([112], \"uint8\", data=placeholder_global_1_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_2[0], 112, placeholder_global_1[0], dtype=\"handle\"))\n                placeholder_d_global_1_data = T.allocate([32], \"uint8\", \"global\")\n                placeholder_d_global_1 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_1_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_3[0], 32, placeholder_d_global_1[0], dtype=\"handle\"))\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_1[0], 112, 12, placeholder_d_global_1[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.allocate([112], \"uint8\", \"global\") as placeholder_global_2_data:\n                placeholder_global_2 = T.buffer_decl([112], \"uint8\", data=placeholder_global_2_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_4[0], 112, placeholder_global_2[0], dtype=\"handle\"))\n                placeholder_d_global_2_data = T.allocate([32], \"uint8\", \"global\")\n                placeholder_d_global_2 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_2_data)\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_5[0], 32, placeholder_d_global_2[0], dtype=\"handle\"))\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_2[0], 112, 12, placeholder_d_global_2[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            placeholder_global_3_data = T.allocate([112], \"uint8\", \"global\")\n            placeholder_global_3 = T.buffer_decl([112], \"uint8\", data=placeholder_global_3_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_6[0], 112, placeholder_global_3[0], dtype=\"handle\"))\n            placeholder_d_global_3_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global_3 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_3_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_7[0], 32, placeholder_d_global_3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_3[0], 112, 12, placeholder_d_global_3[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    mod = Module\n    allocate_info = ExtractAllocateInfo()(mod)\n    mod = HoistAllocates()(mod)\n    CheckAllocates(allocate_info)(mod)\n\n\ndef test_allocate_without_seq_stmt():\n    \"\"\"\n    Tests the case when an allocate statement does not have a sequence statement as its body.\n    \"\"\"\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"], buffer_encoded: T.Buffer[(128,), \"uint8\"], buffer_encoded_1: T.Buffer[(32,), \"uint8\"], buffer_encoded_2: T.Buffer[(112,), \"uint8\"], buffer_encoded_3: T.Buffer[(32,), \"uint8\"], buffer_encoded_4: T.Buffer[(112,), \"uint8\"], buffer_encoded_5: T.Buffer[(32,), \"uint8\"], buffer_encoded_6: T.Buffer[(112,), \"uint8\"], buffer_encoded_7: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            placeholder_global_data = T.allocate([128], \"uint8\", \"global\")\n            placeholder_global = T.buffer_decl([128], \"uint8\", data=placeholder_global_data)\n            placeholder_global_1_data = T.allocate([112], \"uint8\", \"global\")\n            placeholder_global_1 = T.buffer_decl([112], \"uint8\", data=placeholder_global_1_data)\n            placeholder_global_2_data = T.allocate([112], \"uint8\", \"global\")\n            placeholder_global_2 = T.buffer_decl([112], \"uint8\", data=placeholder_global_2_data)\n            placeholder_d_global_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_data)\n            placeholder_d_global_1_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global_1 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_1_data)\n            placeholder_d_global_2_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global_2 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_2_data)\n            placeholder_global_3_data = T.allocate([112], \"uint8\", \"global\")\n            placeholder_global_3 = T.buffer_decl([112], \"uint8\", data=placeholder_global_3_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded[0], 128, placeholder_global[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_1[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 128, 12, placeholder_d_global[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_2[0], 112, placeholder_global_1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_3[0], 32, placeholder_d_global_1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_1[0], 112, 12, placeholder_d_global_1[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_4[0], 112, placeholder_global_2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_5[0], 32, placeholder_d_global_2[0], dtype=\"handle\"))\n            placeholder_d_global_3_data = T.allocate([32], \"uint8\", \"global\")\n            placeholder_d_global_3 = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_3_data)\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_2[0], 112, 12, placeholder_d_global_2[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_6[0], 112, placeholder_global_3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer_encoded_7[0], 32, placeholder_d_global_3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global_3[0], 112, 12, placeholder_d_global_3[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    mod = Module\n    allocate_info = ExtractAllocateInfo()(mod)\n    mod = HoistAllocates()(mod)\n    CheckAllocates(allocate_info)(mod)\n\n\ndef test_multiple_prim_funcs():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main():\n            T.evaluate(0)\n\n        @T.prim_func\n        def abc():\n            T.evaluate(0)\n\n    mod = Module\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the HoistAllocates pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        mod = HoistAllocates()(mod)\n\n\ndef test_no_main_prim_func():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def abs():\n            T.evaluate(0)\n\n    mod = Module\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the HoistAllocates pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        mod = HoistAllocates()(mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_identity_optimizer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTest the identity optimizer pass that removes redundant identity\noperations from the microNPU codegen.\n\"\"\"\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tensorflow as tf\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.relay.backend.contrib.ethosu.codegen import relay_to_tir\nfrom tvm.relay.backend.contrib.ethosu.codegen import IdentityOptimizer\n\nfrom . import infra\n\n\ndef _optimize(func, optimize=True):\n    \"\"\"Create IRModule and run identity optimizer pass.\"\"\"\n    func = func.with_attr(\"Compiler\", \"ethos-u\")\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    if optimize:\n        mod = IdentityOptimizer()(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(func, relay.Function) else entry.body\n\n\ndef _assert_structural_equal(a, b):\n    \"\"\"Check structural equality of two Relay expressions.\"\"\"\n    reason = (\n        \"Actual and expected relay functions are not equal. \"\n        \"IdentityOptimizer is not correctly removing redundant \"\n        \"identity operations.\"\n    )\n    assert tvm.ir.structural_equal(a, b), reason\n\n\ndef test_simple_reshape_identity_removal():\n    \"\"\"Check identity is removed when there is a reshape in\n    the graph and a compute operation follows.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = infra.make_ethosu_conv2d(x, 4, 4, (1, 1), (0, 0), (1, 1), (1, 1))\n        x = relay.reshape(x, newshape=(1, 4, 4, 1))\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        x = infra.make_ethosu_unary_elementwise(x, 1, \"ABS\")\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_simple_strided_slice_identity_removal():\n    \"\"\"Check identity is removed when there is a strided slice\n    in the graph and a compute operation follows.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = infra.make_ethosu_pooling(x, \"MAX\", (1, 1), 4, (1, 1), (0, 0))\n        x = relay.strided_slice(x, begin=[0, 0, 0, 0], end=[1, 2, 2, 2])\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        x = infra.make_ethosu_pooling(x, \"MAX\", (1, 1), 2, (1, 1), (0, 0))\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_no_identity():\n    \"\"\"Check the graph is not affected when there is no identity in the graph.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = infra.make_ethosu_conv2d(x, 4, 4, (1, 1), (0, 0), (1, 1), (1, 1))\n        x = infra.make_ethosu_pooling(x, \"MAX\", (1, 1), 4, (1, 1), (0, 0))\n        x = infra.make_ethosu_depthwise_conv2d(x, 4, (1, 1), (0, 0), (1, 1), (1, 1))\n        x = infra.make_ethosu_unary_elementwise(x, 4, \"ABS\")\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_reshape_last():\n    \"\"\"Check that an identity as a leaf of the graph is not removed.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = infra.make_ethosu_conv2d(x, 4, 4, (1, 1), (0, 0), (1, 1), (1, 1))\n        x = relay.reshape(x, newshape=(1, 4, 4, 1))\n        x = infra.make_ethosu_identity(x)\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_requantize_identity_no_removal():\n    \"\"\"Check that an identity that actually performs a requantize isn't removed.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 1, 4, 4))\n        x = infra.make_ethosu_identity(\n            x, ifm_scale=0.5, ifm_zero_point=1, ofm_scale=0.3, ofm_zero_point=2\n        )\n        x = infra.make_ethosu_unary_elementwise(x, 4, \"ABS\")\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_activation_identity_no_removal():\n    \"\"\"Check thst an identity with an activation isn't removed.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 1, 4, 4))\n        x = infra.make_ethosu_identity(x, activation=\"LUT\")\n        x = infra.make_ethosu_unary_elementwise(x, 4, \"ABS\")\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_multiple_output_identity():\n    \"\"\"Check that an identity is removed when it has multiple outputs.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        y = infra.make_ethosu_unary_elementwise(x, 4, \"ABS\")\n        z = infra.make_ethosu_unary_elementwise(x, 4, \"ABS\")\n        out = relay.concatenate((y, z), axis=0)\n        return relay.Function(relay.analysis.free_vars(x), out)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_many_output_identity():\n    \"\"\"Check an identity with many outputs. It cannot be removed due\n    to having a strided slice as output.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 1, 4, 4))\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        outputs = []\n        for _ in range(4):\n            outputs.append(infra.make_ethosu_unary_elementwise(x, 4, \"ABS\"))\n        ss = relay.strided_slice(x, begin=(0, 0, 0, 0), end=(1, 1, 4, 4))\n        identity_2 = infra.make_ethosu_identity(ss)\n        outputs.append(identity_2)\n        out = relay.concatenate(outputs, axis=0)\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_identity_before_concatenate_no_removal():\n    \"\"\"Check that an identity isn't removed when the operator\n    following it is a concatenate operation.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 1, 4, 4), dtype=\"int8\")\n        y = relay.var(\"y\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        z = relay.var(\"z\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 2, 2, 4))\n        y = relay.strided_slice(y, begin=(0, 0, 0, 0), end=(1, 2, 2, 4))\n        x = infra.make_ethosu_identity(x)\n        y = infra.make_ethosu_identity(y)\n        out = relay.concatenate([x, y, z], axis=0)\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_identity_removal_with_multiple_transform_ops():\n    \"\"\"Check that only an identity directly parent to a compute\n    operation is removed.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.strided_slice(x, begin=[0, 0, 0, 0], end=[1, 2, 2, 2])\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        x = relay.reshape(x, newshape=(1, 1, 1, 8))\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n        x = infra.make_ethosu_unary_elementwise(x, 8, \"ABS\")\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_identity_removal_on_binary_elementwise():\n    \"\"\"Check identities before binary elementwise are removed correctly.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        y = relay.var(\"y\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        if not get_expected:\n            x = infra.make_ethosu_identity(x)\n            y = infra.make_ethosu_identity(y)\n        z = infra.make_ethosu_binary_elementwise(x, y, 4, 4, \"ADD\", \"int8\")\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_identity_single_removal_on_binary_elementwise():\n    \"\"\"Check that identity on the second input of the binary elementwise\n    operation is removed while the other input has no identity.\"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 4, 1, 4), dtype=\"int8\")\n        y = relay.var(\"y\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        y = relay.reshape(y, newshape=(1, 4, 1, 4))\n        if not get_expected:\n            y = infra.make_ethosu_identity(y)\n        z = infra.make_ethosu_binary_elementwise(x, y, 4, 4, \"ADD\", \"int8\")\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_multiple_transform_ops_with_reduction_in_dimensionality():\n    \"\"\"Removal of an identity operation between two transform operations is usually okay.\n    However, if the dimensionality of the input is reduced by the second transformation\n    operation, it can lead to an output mismatch. Checking that the pass doesn't remove\n    an identity given this case.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.strided_slice(x, begin=(0, 0, 0, 0), end=(1, 2, 2, 2))\n        x = infra.make_ethosu_identity(x)\n        x = relay.reshape(x, newshape=(1, 2, 4))\n        x = infra.make_ethosu_identity(x)\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    actual = _optimize(get_graph())\n    expected = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(actual, expected)\n\n\ndef test_identity_optimizer_runs_in_compilation_pipeline():\n    \"\"\"Checks that the identity optimization pass is run as part of the NPU compilation pipeline.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 4, 4, 4), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 1, 16, 4))\n        x = relay.nn.max_pool2d(x, layout=\"NHWC\")\n        func = relay.Function(relay.analysis.free_vars(x), x)\n        return tvm.IRModule.from_expr(func)\n\n    mod = get_graph()\n    mod = partition_for_ethosu(mod)\n    mod = relay_to_tir(mod)\n\n    external_gv_name = mod[\"main\"].body.op.name_hint\n    prim_func = mod[external_gv_name]\n\n    # Check for hints in the TIR prim func that the identity optimization pass\n    # has ran. There should not be an identity in the prim func.\n    assert prim_func.body.value.args[0] == \"ethosu_pooling\"\n\n\ndef test_same_output():\n    \"\"\"Check that the output remains the same when the identity\n    optimizer pass removes some identities inserted during legalization.\"\"\"\n    ifm_shapes = [(1, 1, 25, 8), (1, 5, 5, 8)]\n\n    @tf.function\n    def model(x, y):\n        x = tf.reshape(x, (1, 5, 5, 8))\n        z = tf.add(x, y)\n        z = tf.reshape(z, (1, 1, 25, 8))\n        return z\n\n    infra.compare_tvm_with_tflite(model, ifm_shapes, \"ethos-u55-256\", enable_cascader=False)\n\n\ndef test_multi_output_identity_has_same_output():\n    \"\"\"Check that the output remains the same with an identity with\n    multiple outputs.\"\"\"\n    ifm_shape = (1, 1, 64, 16)\n\n    @tf.function\n    def model(x):\n        x = tf.reshape(x, (1, 8, 8, 16))\n        outputs = []\n        for _ in range(4):\n            outputs.append(tf.nn.max_pool2d(x, 1, 1, \"VALID\"))\n        outputs.append(tf.reshape(x, (1, 8, 8, 16)))\n        y = tf.concat(outputs, axis=0)\n        return y\n\n    infra.compare_tvm_with_tflite(model, [ifm_shape], \"ethos-u55-256\", enable_cascader=False)\n\n\ndef test_multiple_transform_ops_same_output():\n    \"\"\"Check case of identity removal between transform ops and\n    then without, making sure they have the same output.\"\"\"\n    ifm_shape = (1, 2, 2, 4)\n\n    @tf.function\n    def model(x):\n        x = tf.reshape(x, (1, 1, 4, 4))\n        x = tf.slice(x, (0, 0, 0, 0), (1, 1, 4, 3))\n        x = tf.reshape(x, (12,))\n        return x\n\n    infra.compare_tvm_with_tflite(model, [ifm_shape], \"ethos-u55-256\", enable_cascader=False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_layout_optimizer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test the layout optimization pass. This pass is used to\nconvert subgraphs to the preferred layout of NHCWB16.\n\"\"\"\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nimport tflite.Model\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.relay.backend.contrib.ethosu.codegen import LayoutOptimizer\nfrom tvm.relay.backend.contrib.ethosu.codegen import relay_to_tir\n\nfrom . import infra\n\n\ndef _optimize(func, optimize=True):\n    \"\"\"Create IRModule and run layout optimizer pass.\"\"\"\n    func = func.with_attr(\"Compiler\", \"ethos-u\")\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    if optimize:\n        mod = LayoutOptimizer()(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(func, relay.Function) else entry.body\n\n\ndef _assert_structural_equal(a, b):\n    \"\"\"Check structural equality of two Relay expressions.\"\"\"\n    reason = (\n        \"Actual and expected relay functions are not equal. \"\n        \"LayoutOptimizer is not correctly converting layouts.\"\n    )\n    assert tvm.ir.structural_equal(a, b), reason\n\n\ndef _compile_and_compare_model(tflite_graph, ifm_shape, dtype):\n    \"\"\"Compare running result of compilation against TFLite.\"\"\"\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\n            \"ifm\": ifm_shape,\n        },\n        dtype_dict={\n            \"ifm\": dtype,\n        },\n    )\n    mod = partition_for_ethosu(mod, params)\n\n    # Generate reference data\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_graph)\n\n    test_runner = infra.create_test_runner(\"ethos-u55-256\")\n    compiled_models = infra.build_source(\n        mod,\n        input_data,\n        output_data,\n        test_runner,\n        output_tolerance=0,\n    )\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    get_artifacts = tvm._ffi.get_global_func(\"runtime.module.ethos-u.get_artifacts\")\n    compilation_artifacts = get_artifacts(ethosu_module)\n    cmms = bytes.fromhex(compilation_artifacts[0].command_stream)\n    infra.print_payload(cmms)\n    infra.verify_source(compiled_models, test_runner)\n\n\ndef test_single_convolution():\n    \"\"\"Test a single convolution to make sure the layouts remain\n    unaltered.\n    \"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n        x = infra.make_ethosu_conv2d(\n            ifm=x,\n            ifm_channels=8,\n            ofm_channels=8,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_convolution():\n    \"\"\"Test layout optimization pass on linear chain of convolutions. I.e,\n\n    conv_1\n      |\n    conv_2\n      |\n    conv_3\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n        for i in range(3):\n            ifm_layout = \"NHCWB16\" if get_expected and i != 0 else \"NHWC\"\n            ofm_layout = \"NHCWB16\" if get_expected and i != 2 else \"NHWC\"\n            x = infra.make_ethosu_conv2d(\n                ifm=x,\n                ifm_channels=8,\n                ofm_channels=8,\n                kernel_shape=(1, 1),\n                padding=(0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n                ifm_layout=ifm_layout,\n                ofm_layout=ofm_layout,\n            )\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_depthwise_convolution():\n    \"\"\"Test layout optimization pass on multiple depthwise convolutions.\n\n    depthwise_conv_1\n           |\n    depthwise_conv_2\n           |\n    depthwise_conv_3\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n        for i in range(3):\n            ifm_layout = \"NHCWB16\" if get_expected and i != 0 else \"NHWC\"\n            ofm_layout = \"NHCWB16\" if get_expected and i != 2 else \"NHWC\"\n            x = infra.make_ethosu_depthwise_conv2d(\n                ifm=x,\n                channels=4,\n                kernel_shape=(1, 1),\n                padding=(0, 0),\n                strides=(1, 1),\n                dilation=(1, 1),\n                ifm_layout=ifm_layout,\n                ofm_layout=ofm_layout,\n            )\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_ignore_transform_operations():\n    \"\"\"Test layout optimization pass ignores transform operations\n    such as reshape and strided slice.\n\n       conv_1\n         |\n      reshape\n         |\n    strided_slice\n         |\n       conv_2\n    \"\"\"\n\n    def get_graph():\n        in_1 = relay.var(\"x\", shape=(1, 16, 16, 8), dtype=\"int8\")\n        conv_1 = infra.make_ethosu_conv2d(\n            ifm=in_1,\n            ifm_channels=8,\n            ofm_channels=8,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        reshape = relay.reshape(conv_1, (1, 16, 16, 8))\n        strided_slice = relay.strided_slice(reshape, (0, 0, 0, 0), (1, 16, 16, 8))\n        conv_2 = infra.make_ethosu_conv2d(\n            ifm=strided_slice,\n            ifm_channels=8,\n            ofm_channels=8,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(conv_2), conv_2)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_ignore_concatenate():\n    \"\"\"Test layout optimization pass ignores the concatenate operation,\n    when layout transformation cannot occur.\n\n    in_1     in_2\n      \\       /\n       \\   conv_1\n        \\   /\n       concat\n         |\n       conv_2\n    \"\"\"\n\n    def get_graph():\n        in_1 = relay.var(\"x\", shape=(1, 16, 16, 8), dtype=\"int8\")\n        in_2 = relay.var(\"y\", shape=(1, 16, 16, 8), dtype=\"int8\")\n        conv_1 = infra.make_ethosu_conv2d(\n            ifm=in_2,\n            ifm_channels=8,\n            ofm_channels=8,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        concat = relay.concatenate([in_1, conv_1], axis=1)\n        conv_2 = infra.make_ethosu_conv2d(\n            ifm=concat,\n            ifm_channels=8,\n            ofm_channels=4,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(conv_2), conv_2)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_ignore_concatnate_with_layout_transform():\n    \"\"\"Test the layout optimization pass ignores the concatenate\n    operation and performs a layout transformation.\n\n     in_1       in_2\n      \\          /\n     pool_1   pool_2\n        \\      /\n         concat\n           |\n         pool_3\n    \"\"\"\n\n    def get_graph():\n        in_1 = relay.var(\"x\", shape=(1, 16, 16, 8), dtype=\"int8\")\n        in_2 = relay.var(\"y\", shape=(1, 16, 16, 8), dtype=\"int8\")\n        pool_1 = infra.make_ethosu_pooling(\n            in_1,\n            \"MAX\",\n            (1, 1),\n            ofm_channels=8,\n            strides=(1, 1),\n            padding=(0, 0),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        pool_2 = infra.make_ethosu_pooling(\n            in_2,\n            \"MAX\",\n            (1, 1),\n            ofm_channels=8,\n            strides=(1, 1),\n            padding=(0, 0),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        concat = relay.concatenate([pool_1, pool_2], axis=1)\n        pool_3 = infra.make_ethosu_pooling(\n            concat,\n            \"MAX\",\n            (1, 1),\n            ofm_channels=8,\n            strides=(1, 1),\n            padding=(0, 0),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(pool_3), pool_3)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_inputs():\n    \"\"\"Test the layout optimization pass works as expected when there\n    are multiple inputs in the graph.\n\n    pool_1 pool_2 pool_3\n      \\     |      /\n       \\    |    /\n         concat\n           |\n         conv\n    \"\"\"\n\n    def get_graph():\n        poolings = []\n        for _ in range(3):\n            inp = relay.var(\"x\", shape=(1, 3, 3, 4), dtype=\"int8\")\n            pool = infra.make_ethosu_pooling(\n                inp,\n                \"MAX\",\n                (1, 1),\n                ofm_channels=4,\n                strides=(1, 1),\n                padding=(0, 0),\n                ifm_layout=\"NHWC\",\n                ofm_layout=\"NHWC\",\n            )\n            poolings.append(pool)\n        concat = relay.concatenate(poolings, axis=0)\n        conv = infra.make_ethosu_conv2d(\n            ifm=concat,\n            ifm_channels=8,\n            ofm_channels=4,\n            kernel_shape=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(conv), conv)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_outputs():\n    \"\"\"Test the layout optimization pass works as expected when there\n    are multiple outputs in the graph.\n\n          pool_1\n       /    |   \\\n  pool_2 pool_3 pool_4\n        \\   |   /\n         concat\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        in_1 = relay.var(\"x\", shape=(1, 4, 4, 8), dtype=\"int8\")\n        pool_1 = infra.make_ethosu_pooling(\n            in_1,\n            \"MAX\",\n            (1, 1),\n            ofm_channels=4,\n            strides=(1, 1),\n            padding=(0, 0),\n            ifm_layout=\"NHWC\",\n            ofm_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n        )\n        poolings = []\n        for _ in range(3):\n            poolings.append(\n                infra.make_ethosu_pooling(\n                    pool_1,\n                    \"MAX\",\n                    (1, 1),\n                    ofm_channels=4,\n                    strides=(1, 1),\n                    padding=(0, 0),\n                    ifm_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n                    ofm_layout=\"NHWC\",\n                )\n            )\n        concat = relay.concatenate(poolings, axis=0)\n        return relay.Function(relay.analysis.free_vars(concat), concat)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_binary_elementwise():\n    \"\"\"Test the layout optimization pass works as expected for\n    binary elementwise operations.\n\n    add_1  add_2\n      \\     /\n       \\   /\n       add_3\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        in_1 = relay.var(\"x\", shape=(1, 2, 2, 2), dtype=\"int8\")\n        in_2 = relay.var(\"y\", shape=(1, 2, 2, 2), dtype=\"int8\")\n        in_3 = relay.var(\"z\", shape=(1, 2, 2, 2), dtype=\"int8\")\n        add_1 = infra.make_ethosu_binary_elementwise(\n            in_1,\n            in_2,\n            ifm_channels=2,\n            ifm2_channels=2,\n            operator_type=\"ADD\",\n            ofm_dtype=\"int8\",\n            ifm_layout=\"NHWC\",\n            ifm2_layout=\"NHWC\",\n            ofm_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n        )\n        add_2 = infra.make_ethosu_binary_elementwise(\n            in_2,\n            in_3,\n            ifm_channels=2,\n            ifm2_channels=2,\n            operator_type=\"ADD\",\n            ofm_dtype=\"int8\",\n            ifm_layout=\"NHWC\",\n            ifm2_layout=\"NHWC\",\n            ofm_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n        )\n        add_3 = infra.make_ethosu_binary_elementwise(\n            add_1,\n            add_2,\n            ifm_channels=2,\n            ifm2_channels=2,\n            operator_type=\"ADD\",\n            ofm_dtype=\"int8\",\n            ifm_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n            ifm2_layout=\"NHCWB16\" if get_expected else \"NHWC\",\n            ofm_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(add_3), add_3)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_pooling():\n    \"\"\"Test the layout optimization pass works as expected for\n    multiple pooling operations.\n\n    pool_1\n      |\n    pool_2\n      |\n    pool_3\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n        for i in range(3):\n            ifm_layout = \"NHCWB16\" if get_expected and i != 0 else \"NHWC\"\n            ofm_layout = \"NHCWB16\" if get_expected and i != 2 else \"NHWC\"\n            x = infra.make_ethosu_pooling(\n                x,\n                \"MAX\",\n                (1, 1),\n                ofm_channels=4,\n                strides=(1, 1),\n                padding=(0, 0),\n                ifm_layout=ifm_layout,\n                ofm_layout=ofm_layout,\n            )\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_multiple_unary_elementwise():\n    \"\"\"Test the layout optimization pass works as expected for multiple\n    unary elementwise operations.\n\n    abs_1\n      |\n    abs_2\n      |\n    abs_3\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        x = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n        for i in range(3):\n            ifm_layout = \"NHCWB16\" if get_expected and i != 0 else \"NHWC\"\n            ofm_layout = \"NHCWB16\" if get_expected and i != 2 else \"NHWC\"\n            x = infra.make_ethosu_unary_elementwise(\n                x,\n                ofm_channels=4,\n                operator_type=\"ABS\",\n                ifm_layout=ifm_layout,\n                ofm_layout=ofm_layout,\n            )\n        return relay.Function(relay.analysis.free_vars(x), x)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_op_without_ethosu_consumer():\n    \"\"\"Test the layout optimization pass works as expected when\n    there is a case that the output layout should not be altered\n    since not all consumers are NPU operations (in this case conv).\n\n    depthwise\n        |\n      conv\n      /  \\\n     |  pool\n     \\   /\n    (concat)\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        exp_layout = \"NHCWB16\" if get_expected else \"NHWC\"\n\n        x = relay.var(\"x\", shape=(1, 2, 2, 2), dtype=\"int8\")\n        depthwise = infra.make_ethosu_depthwise_conv2d(\n            x, 2, (1, 1), (0, 0), (1, 1), (0, 0), ofm_layout=exp_layout\n        )\n        conv = infra.make_ethosu_conv2d(\n            depthwise,\n            2,\n            2,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (0, 0),\n            ifm_layout=exp_layout,\n        )\n        pool = infra.make_ethosu_pooling(conv, \"MAX\", (1, 1), 2, (1, 1), (0, 0))\n        concat = relay.concatenate([conv, pool], axis=0)\n        return relay.Function(relay.analysis.free_vars(concat), concat)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_diamond_graph():\n    \"\"\"\n    Test the layout optimizer pass works as expected on a diamond graph\n    with a case where the operation dominating the output operation\n    cannot be altered, but operations within the diamond can.\n\n      pool_1\n        |\n      pool_2\n      /   \\\n     |  pool_3\n     |     |\n     |  pool_4\n     |     |\n     |  pool_5\n     \\    /\n    (concat)\n    \"\"\"\n\n    def get_graph(get_expected=False):\n        exp_layout = \"NHCWB16\" if get_expected else \"NHWC\"\n        x = relay.var(\"x\", shape=(1, 2, 2, 2), dtype=\"int8\")\n        pool_1 = infra.make_ethosu_pooling(\n            x, \"MAX\", (1, 1), 2, (1, 1), (0, 0), ofm_layout=exp_layout\n        )\n        pool_2 = infra.make_ethosu_pooling(\n            pool_1, \"MAX\", (1, 1), 2, (1, 1), (0, 0), ifm_layout=exp_layout\n        )\n        pool_3 = infra.make_ethosu_pooling(\n            pool_2, \"MAX\", (1, 1), 2, (1, 1), (0, 0), ofm_layout=exp_layout\n        )\n        pool_4 = infra.make_ethosu_pooling(\n            pool_3, \"MAX\", (1, 1), 2, (1, 1), (0, 0), ifm_layout=exp_layout, ofm_layout=exp_layout\n        )\n        pool_5 = infra.make_ethosu_pooling(\n            pool_4, \"MAX\", (1, 1), 2, (1, 1), (0, 0), ifm_layout=exp_layout\n        )\n        concat = relay.concatenate([pool_2, pool_5], axis=0)\n        return relay.Function(relay.analysis.free_vars(concat), concat)\n\n    a = _optimize(get_graph())\n    b = _optimize(get_graph(get_expected=True), optimize=False)\n    _assert_structural_equal(a, b)\n\n\ndef test_same_output_multiple_convolutions():\n    \"\"\"Test running the layout optimization pass with multiple convolutions\n    gives same output as TFLite.\"\"\"\n\n    np.random.seed(0)\n    dtype = \"int8\"\n    ifm_shape = (1, 8, 8, 32)\n    kernel_shape = (1, 1, 32, 32)\n\n    def create_model():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                for _ in range(3):\n                    x = tf.nn.conv2d(\n                        x,\n                        filters=tf.constant(np.random.uniform(size=kernel_shape), dtype=tf.float32),\n                        strides=(1, 1),\n                        padding=\"SAME\",\n                        data_format=\"NHWC\",\n                        dilations=1,\n                    )\n                return x\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        return converter.convert()\n\n    _compile_and_compare_model(create_model(), ifm_shape, dtype)\n\n\ndef test_same_output_multiple_pooling():\n    \"\"\"Test running the layout optimization pass with multiple pooling\n    operations gives same output as TFLite.\"\"\"\n\n    np.random.seed(0)\n    dtype = \"int8\"\n    ifm_shape = (1, 4, 2, 7)\n\n    def create_model():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                for _ in range(2):\n                    x = tf.nn.max_pool2d(x, (1, 1), (1, 1), \"SAME\", \"NHWC\")\n                return x\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        return converter.convert()\n\n    _compile_and_compare_model(create_model(), ifm_shape, dtype)\n\n\ndef test_layout_optimizer_runs_in_compilation_pipeline():\n    \"\"\"Checks that the layout optimization pass runs as part of the NPU compilation\n    pipeline.\"\"\"\n\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 4, 4, 4), dtype=\"int8\")\n        for _ in range(2):\n            x = relay.nn.max_pool2d(x, layout=\"NHWC\")\n\n        func = relay.Function(relay.analysis.free_vars(x), x)\n        return tvm.IRModule.from_expr(func)\n\n    mod = get_graph()\n    mod = partition_for_ethosu(mod)\n    mod = relay_to_tir(mod)\n\n    external_gv_name = mod[\"main\"].body.op.name_hint\n    prim_func = mod[external_gv_name]\n\n    # Check for hints in the TIR prim func that the layout optimization pass has ran\n    ops = prim_func.body.body.seq\n    max_pool1, max_pool2 = ops\n\n    assert str(max_pool1.value.args[31]) == '\"NHCWB16\"'\n    assert str(max_pool2.value.args[14]) == '\"NHCWB16\"'\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__] + sys.argv[1:])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_legalize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport math\n\nimport numpy as np\nimport tensorflow as tf\nimport tflite.Model\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu import legalize, preprocess\nfrom tvm.relay import dataflow_pattern\nfrom tvm.relay.op.contrib import ethosu\nfrom tvm.relay.backend.contrib.ethosu import util\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.frontend.tflite import get_pad_value\n\nfrom . import infra\n\n\ndef partition_ethosu_by_table(mod, pattern_table):\n    \"\"\"In case only the legalization part is supported for an operator, we don't\n    want to add the operator's pattern to the pattern table so that the compiler\n    wouldn't attempt to offload an operator without full stack support.\"\"\"\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.MergeComposite(pattern_table)(mod)\n    mod = relay.transform.AnnotateTarget(\"ethos-u\")(mod)\n    mod = relay.transform.MergeCompilerRegions()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.PartitionGraph()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = preprocess.preprocess_ext_io()(mod)\n    return mod\n\n\ndef test_split_indices_legalize():\n    def create_graph(axis):\n        x = relay.var(\"x\", shape=(1, 50, 50, 3))\n        x_relu = relay.nn.relu(x)\n        split_output = relay.split(x_relu, [5, 20, 45], axis).tuple_value\n        return relay.Function([x], split_output)\n\n    def expected_mod_axis1():\n        expected_ir_string = \"\"\"\n        #[version = \"0.0.5\"]\n        def @tvmgen_default_ethos_u_main_0(%x: Tensor[(1, 50, 50, 3), float32]) -> (Tensor[(1, 5, 50, 3), float32],\\\n                                                               Tensor[(1, 15, 50, 3), float32],\\\n                                                               Tensor[(1, 25, 50, 3), float32],\\\n                                                               Tensor[(1, 5, 50, 3), float32]) {\n          %0 = nn.relu(%x) /* ty=Tensor[(1, 50, 50, 3), float32] */;\n          %1 = strided_slice(%0, begin=[0, 0, 0, 0], end=[1, 5, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 5, 50, 3), float32] */;\n          %2 = strided_slice(%0, begin=[0, 5, 0, 0], end=[1, 20, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 15, 50, 3), float32] */;\n          %3 = strided_slice(%0, begin=[0, 20, 0, 0], end=[1, 45, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 25, 50, 3), float32] */;\n          %4 = strided_slice(%0, begin=[0, 45, 0, 0], end=[1, 50, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 5, 50, 3), float32] */;\n          (%1, %2, %3, %4)\n        }\n        \"\"\"\n        return tvm.parser.fromtext(expected_ir_string)\n\n    def expected_mod_axis2():\n        expected_ir_string = \"\"\"\n        #[version = \"0.0.5\"]\n        def @tvmgen_default_ethos_u_main_0(%x: Tensor[(1, 50, 50, 3), float32]) -> (Tensor[(1, 50, 5, 3), float32],\\\n                                                               Tensor[(1, 50, 15, 3), float32],\\\n                                                               Tensor[(1, 50, 25, 3), float32],\\\n                                                               Tensor[(1, 50, 5, 3), float32]) {\n          %0 = nn.relu(%x) /* ty=Tensor[(1, 50, 50, 3), float32] */;\n          %1 = strided_slice(%0, begin=[0, 0, 0, 0], end=[1, 50, 5, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 5, 3), float32] */;\n          %2 = strided_slice(%0, begin=[0, 0, 5, 0], end=[1, 50, 20, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 15, 3), float32] */;\n          %3 = strided_slice(%0, begin=[0, 0, 20, 0], end=[1, 50, 45, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 25, 3), float32] */;\n          %4 = strided_slice(%0, begin=[0, 0, 45, 0], end=[1, 50, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 5, 3), float32] */;\n          (%1, %2, %3, %4)\n        }\n        \"\"\"\n        return tvm.parser.fromtext(expected_ir_string)\n\n    rewrite_split = [legalize.PartitionedSplitRewriter(), legalize.SplitRewriter()]\n\n    mod_axis1 = tvm.IRModule()\n    func = create_graph(1)\n    for r in rewrite_split:\n        func = dataflow_pattern.rewrite(r, func)\n    mod_axis1[\"tvmgen_default_ethos_u_main_0\"] = func\n    expected_axis1 = expected_mod_axis1()\n    tvm.ir.assert_structural_equal(mod_axis1, expected_axis1)\n\n    mod_axis2 = tvm.IRModule()\n    func = create_graph(2)\n    for r in rewrite_split:\n        func = dataflow_pattern.rewrite(r, func)\n    mod_axis2[\"tvmgen_default_ethos_u_main_0\"] = func\n    expected_axis2 = expected_mod_axis2()\n    tvm.ir.assert_structural_equal(mod_axis2, expected_axis2)\n\n\ndef test_split_sections_legalize():\n    def create_graph(axis, sections):\n        x = relay.var(\"x\", shape=(1, 50, 50, 3))\n        x_abs = relay.abs(x)\n        split_output = relay.split(x_abs, sections, axis).tuple_value\n        outputs = list()\n        for section_idx in range(sections):\n            split_single_out = relay.TupleGetItem(split_output, section_idx)\n            tanh = relay.tanh(split_single_out)\n            outputs.append(tanh)\n        tuple_out = relay.Tuple(outputs)\n        return relay.Function([x], tuple_out)\n\n    def expected_mod_axis1():\n        expected_ir_string = \"\"\"\n        #[version = \"0.0.5\"]\n        def @tvmgen_default_ethos_u_main_0(%x: Tensor[(1, 50, 50, 3), float32]) -> (Tensor[(1, 10, 50, 3), float32],\\\n                                                               Tensor[(1, 10, 50, 3), float32],\\\n                                                               Tensor[(1, 10, 50, 3), float32],\\\n                                                               Tensor[(1, 10, 50, 3), float32],\\\n                                                               Tensor[(1, 10, 50, 3), float32]) {\n          %0 = abs(%x) /* ty=Tensor[(1, 50, 50, 3), float32] */;\n          %1 = strided_slice(%0, begin=[0, 0, 0, 0], end=[1, 10, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %2 = strided_slice(%0, begin=[0, 10, 0, 0], end=[1, 20, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %3 = strided_slice(%0, begin=[0, 20, 0, 0], end=[1, 30, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %4 = strided_slice(%0, begin=[0, 30, 0, 0], end=[1, 40, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %5 = strided_slice(%0, begin=[0, 40, 0, 0], end=[1, 50, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %6 = (%1, %2, %3, %4, %5);\n          %7 = %6.0;\n          %8 = tanh(%7) /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %9 = %6.1;\n          %10 = tanh(%9) /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %11 = %6.2;\n          %12 = tanh(%11) /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %13 = %6.3;\n          %14 = tanh(%13) /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          %15 = %6.4;\n          %16 = tanh(%15) /* ty=Tensor[(1, 10, 50, 3), float32] */;\n          (%8, %10, %12, %14, %16)\n        }\n        \"\"\"\n        return tvm.parser.fromtext(expected_ir_string)\n\n    def expected_mod_axis2():\n        expected_ir_string = \"\"\"\n        #[version = \"0.0.5\"]\n        def @tvmgen_default_ethos_u_main_0(%x: Tensor[(1, 50, 50, 3), float32]) -> (Tensor[(1, 50, 10, 3), float32],\\\n                                                               Tensor[(1, 50, 10, 3), float32],\\\n                                                               Tensor[(1, 50, 10, 3), float32],\\\n                                                               Tensor[(1, 50, 10, 3), float32],\\\n                                                               Tensor[(1, 50, 10, 3), float32]) {\n          %0 = abs(%x) /* ty=Tensor[(1, 50, 50, 3), float32] */;\n          %1 = strided_slice(%0, begin=[0, 0, 0, 0], end=[1, 50, 10, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %2 = strided_slice(%0, begin=[0, 0, 10, 0], end=[1, 50, 20, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %3 = strided_slice(%0, begin=[0, 0, 20, 0], end=[1, 50, 30, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %4 = strided_slice(%0, begin=[0, 0, 30, 0], end=[1, 50, 40, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %5 = strided_slice(%0, begin=[0, 0, 40, 0], end=[1, 50, 50, 3], strides=[1], axes=None)\\\n           /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %6 = (%1, %2, %3, %4, %5);\n          %7 = %6.0;\n          %8 = tanh(%7) /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %9 = %6.1;\n          %10 = tanh(%9) /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %11 = %6.2;\n          %12 = tanh(%11) /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %13 = %6.3;\n          %14 = tanh(%13) /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          %15 = %6.4;\n          %16 = tanh(%15) /* ty=Tensor[(1, 50, 10, 3), float32] */;\n          (%8, %10, %12, %14, %16)\n        }\n        \"\"\"\n        return tvm.parser.fromtext(expected_ir_string)\n\n    rewrite_split = [legalize.PartitionedSplitRewriter(), legalize.SplitRewriter()]\n\n    mod_axis1 = tvm.IRModule()\n    func = create_graph(1, 5)\n    for r in rewrite_split:\n        func = dataflow_pattern.rewrite(r, func)\n    mod_axis1[\"tvmgen_default_ethos_u_main_0\"] = func\n    expected_axis1 = expected_mod_axis1()\n    tvm.ir.assert_structural_equal(mod_axis1, expected_axis1)\n\n    mod_axis2 = tvm.IRModule()\n    func = create_graph(2, 5)\n    for r in rewrite_split:\n        func = dataflow_pattern.rewrite(r, func)\n    mod_axis2[\"tvmgen_default_ethos_u_main_0\"] = func\n    expected_axis2 = expected_mod_axis2()\n    tvm.ir.assert_structural_equal(mod_axis2, expected_axis2)\n\n\nINVERSE_LAYOUT_TRANSFORM_OHWI_MAP = {\n    \"HWIO\": [1, 2, 3, 0],\n    \"HWOI\": [1, 2, 0, 3],\n    \"OWHI\": [0, 1, 2, 3],\n}\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 299, 299, 3), (1, 55, 55, 3)])\n@pytest.mark.parametrize(\"kernel_shape\", [(3, 2), (1, 3)])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (2, 1)), ((3, 2), (1, 1))])\n@pytest.mark.parametrize(\"activation\", [None, \"RELU\"])\ndef test_tflite_conv2d_legalize(ifm_shape, kernel_shape, padding, strides, dilation, activation):\n    dtype = \"int8\"\n\n    def create_tflite_graph_single():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, input_shape):\n                op = tf.nn.conv2d(\n                    input_shape,\n                    filters=tf.constant(\n                        np.random.uniform(size=(kernel_shape[0], kernel_shape[1], 3, 3)),\n                        dtype=tf.float32,\n                    ),\n                    strides=strides,\n                    padding=padding,\n                    data_format=\"NHWC\",\n                    dilations=dilation,\n                )\n                if activation:\n                    op = tf.nn.relu(op)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        ofm_channels = op.attrs.ofm_channels\n\n        # check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n        assert ifm.shape[3] == ofm_channels\n\n        # check OFM\n        ofm = op.checked_type\n        expected_ofm_shape = infra.compute_ofm_shape(\n            ifm_shape, padding, kernel_shape, strides, dilation\n        )\n        assert list(ofm.shape) == list(expected_ofm_shape)\n        assert str(ofm.dtype) == dtype\n        assert ofm.shape[3] == ofm_channels\n\n        # check weights\n        weights_ohwi = op.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert weights_ohwi.shape[0] == ofm_channels\n        assert weights_ohwi.shape[1] == kernel_shape[0]\n        assert weights_ohwi.shape[2] == kernel_shape[1]\n        assert weights_ohwi.shape[3] == 3\n\n        # Check that scale_bias matches weight tensor\n        assert list(op.args[2].checked_type.shape)[0] == ofm_channels\n\n        expected_padding = infra.compute_padding_shape(\n            ifm_shape,\n            expected_ofm_shape,\n            padding,\n            (kernel_shape[0], kernel_shape[1]),\n            strides,\n            dilation,\n        )\n        assert list(op.attrs.padding) == list(expected_padding)\n        assert list(op.attrs.strides) == list(strides)\n        assert list(op.attrs.dilation) == list(dilation)\n        if activation == \"RELU\":\n            assert str(op.attrs.activation) == \"CLIP\"\n\n    conv2d_pattern_table = [\n        (\n            ethosu.QnnConv2DParams.composite_name,\n            ethosu.qnn_conv2d_pattern(),\n            lambda pat: ethosu.QnnConv2DParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph_single()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, conv_params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], conv_params)\n    mod = partition_ethosu_by_table(mod, conv2d_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.Conv2DRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_tflite_conv2d_with_separate_padding_legalize():\n    dtype = \"int8\"\n    ifm_shape = (1, 55, 34, 3)\n    kernel_shape = (3, 2)\n    strides = (1, 1)\n    dilation = (2, 1)\n    padding = (0, 0, 1, 1)\n\n    def create_tflite_graph_single():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                tf_strides = [1, strides[0], strides[1], 1]\n                op = tf.pad(\n                    x,\n                    [[0, 0], [padding[0], padding[2]], [padding[1], padding[3]], [0, 0]],\n                    \"CONSTANT\",\n                )\n                weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 3]\n                weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n                return tf.nn.conv2d(\n                    op,\n                    weight,\n                    strides=tf_strides,\n                    padding=\"VALID\",\n                    dilations=dilation,\n                )\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        ofm_channels = op.attrs.ofm_channels\n\n        # check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n        assert ifm.shape[3] == ofm_channels\n\n        # check OFM\n        ofm = op.checked_type\n        expected_ofm_shape = infra.compute_ofm_shape(\n            ifm_shape, padding, kernel_shape, strides, dilation\n        )\n        assert list(ofm.shape) == list(expected_ofm_shape)\n        assert str(ofm.dtype) == dtype\n        assert ofm.shape[3] == ofm_channels\n\n        # check weights\n        weights_ohwi = op.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert weights_ohwi.shape[0] == ofm_channels\n        assert weights_ohwi.shape[1] == kernel_shape[0]\n        assert weights_ohwi.shape[2] == kernel_shape[1]\n        assert weights_ohwi.shape[3] == 3\n\n        # Check that scale_bias matches weight tensor\n        assert list(op.args[2].checked_type.shape)[0] == ofm_channels\n\n        assert list(op.attrs.padding) == list(padding)\n        assert list(op.attrs.strides) == list(strides)\n        assert list(op.attrs.dilation) == list(dilation)\n\n    conv2d_pattern_table = [\n        (\n            ethosu.QnnConv2DParams.composite_name,\n            ethosu.qnn_conv2d_pattern(),\n            lambda pat: ethosu.QnnConv2DParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph_single()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, conv_params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], conv_params)\n    mod = partition_ethosu_by_table(mod, conv2d_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.Conv2DRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 299, 299, 3), (1, 123, 17, 7)])\n@pytest.mark.parametrize(\"kernel_shape\", [(7, 3), (22, 5)])\n@pytest.mark.parametrize(\"padding\", [\"SAME\", \"VALID\"])\n@pytest.mark.parametrize(\"strides, dilation\", [((1, 1), (2, 1)), ((3, 2), (1, 1))])\n@pytest.mark.parametrize(\"activation\", [\"RELU\", None])\ndef test_tflite_depthwise_conv_2d_legalize(\n    ifm_shape, kernel_shape, padding, strides, dilation, activation\n):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def depthwise_conv2d(self, x):\n                weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 1]\n                weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n                # The input strides to the TensorFlow API needs to be of shape 1x4\n                tf_strides = [1, strides[0], strides[1], 1]\n                op = tf.nn.depthwise_conv2d(\n                    x, weight, strides=tf_strides, padding=padding, dilations=dilation\n                )\n                if activation:\n                    op = tf.nn.relu(op)\n                return op\n\n        model = Model()\n        concrete_func = model.depthwise_conv2d.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        ofm_channels = op.attrs.ofm_channels\n\n        # check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n        assert ifm.shape[3] == ofm_channels\n\n        # check OFM\n        ofm = op.checked_type\n        expected_ofm_shape = infra.compute_ofm_shape(\n            ifm_shape, padding, kernel_shape, strides, dilation\n        )\n        assert list(ofm.shape) == list(expected_ofm_shape)\n        assert str(ofm.dtype) == dtype\n        assert ofm.shape[3] == ofm_channels\n\n        # check weights\n        weights_ohwi = op.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert weights_ohwi.shape[0] == ofm_channels\n        assert weights_ohwi.shape[1] == kernel_shape[0]\n        assert weights_ohwi.shape[2] == kernel_shape[1]\n        assert weights_ohwi.shape[3] == 1  # only depth multiplier 1 is supported\n\n        # Check that scale_bias matches weight tensor\n        assert list(op.args[2].checked_type.shape)[0] == ofm_channels\n\n        expected_padding = infra.compute_padding_shape(\n            ifm_shape, expected_ofm_shape, padding, kernel_shape, strides, dilation\n        )\n        assert list(op.attrs.padding) == list(expected_padding)\n        assert op.attrs.ofm_channels == ofm_channels\n        assert list(op.attrs.strides) == list(strides)\n        assert list(op.attrs.dilation) == list(dilation)\n        if activation == \"RELU\":\n            assert str(op.attrs.activation) == \"CLIP\"\n\n    depthwise_pattern_table = [\n        (\n            ethosu.QnnDepthwiseConv2DParams.composite_name,\n            ethosu.qnn_depthwise_conv2d_pattern(),\n            lambda pat: ethosu.QnnDepthwiseConv2DParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = partition_ethosu_by_table(mod, depthwise_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.DepthwiseConv2DRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_tflite_depthwise_conv2d_with_separate_padding_legalize():\n    dtype = \"int8\"\n    ifm_shape = (1, 23, 32, 7)\n    kernel_shape = (1, 2)\n    strides = (3, 2)\n    dilation = (1, 1)\n    padding = (0, 0, 1, 1)\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                tf_strides = [1, strides[0], strides[1], 1]\n                op = tf.pad(\n                    x,\n                    [[0, 0], [padding[0], padding[2]], [padding[1], padding[3]], [0, 0]],\n                    \"CONSTANT\",\n                )\n                weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], 1]\n                weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n                return tf.nn.depthwise_conv2d(\n                    op,\n                    weight,\n                    strides=tf_strides,\n                    padding=\"VALID\",\n                    dilations=dilation,\n                )\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        ofm_channels = op.attrs.ofm_channels\n\n        # check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n        assert ifm.shape[3] == ofm_channels\n\n        # check OFM\n        ofm = op.checked_type\n        expected_ofm_shape = infra.compute_ofm_shape(\n            ifm_shape, padding, kernel_shape, strides, dilation\n        )\n        assert list(ofm.shape) == list(expected_ofm_shape)\n        assert str(ofm.dtype) == dtype\n        assert ofm.shape[3] == ofm_channels\n\n        # check weights\n        weights_ohwi = op.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert weights_ohwi.shape[0] == ofm_channels\n        assert weights_ohwi.shape[1] == kernel_shape[0]\n        assert weights_ohwi.shape[2] == kernel_shape[1]\n        assert weights_ohwi.shape[3] == 1  # only depth multiplier 1 is supported\n\n        # Check that scale_bias matches weight tensor\n        assert list(op.args[2].checked_type.shape)[0] == ofm_channels\n\n        assert list(op.attrs.padding) == list(padding)\n        assert op.attrs.ofm_channels == ofm_channels\n        assert list(op.attrs.strides) == list(strides)\n        assert list(op.attrs.dilation) == list(dilation)\n\n    depthwise_pattern_table = [\n        (\n            ethosu.QnnDepthwiseConv2DParams.composite_name,\n            ethosu.qnn_depthwise_conv2d_pattern(),\n            lambda pat: ethosu.QnnDepthwiseConv2DParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = partition_ethosu_by_table(mod, depthwise_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.DepthwiseConv2DRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"pooling_type\", [\"MAX\", \"AVG\"])\n@pytest.mark.parametrize(\"ifm_shape\", [[1, 3, 4, 3], [1, 4, 5, 2]])\n@pytest.mark.parametrize(\n    \"pool_shape, strides, activation_function, padding\",\n    [([1, 2], [1, 2], \"NONE\", \"SAME\"), ([2, 3], [2, 3], \"RELU\", \"VALID\")],\n)\ndef test_tflite_pool2d_legalize(\n    ifm_shape, pooling_type, strides, pool_shape, activation_function, padding\n):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                if pooling_type == \"MAX\":\n                    op = tf.nn.max_pool(x, pool_shape, strides, padding)\n                elif pooling_type == \"AVG\":\n                    op = tf.nn.avg_pool(x, pool_shape, strides, padding)\n                if activation_function == \"RELU\":\n                    op = tf.nn.relu(op)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        ofm_shape = infra.compute_ofm_shape(ifm_shape, padding, pool_shape, strides)\n        op = ext_func.body\n        assert list(op.args[0].checked_type.shape) == ifm_shape\n        assert op.args[0].checked_type.dtype == dtype\n        assert list(op.checked_type.shape) == ofm_shape\n        assert op.checked_type.dtype == dtype\n        assert op.attrs.pooling_type == pooling_type\n        assert list(op.attrs.strides) == strides\n        assert list(op.attrs.padding) == infra.compute_padding_shape(\n            ifm_shape, ofm_shape, padding, pool_shape, strides\n        )\n        assert list(op.attrs.pool_shape) == pool_shape\n        assert op.attrs.ofm_channels == ifm_shape[3]\n        if activation_function == \"RELU\":\n            assert str(op.attrs.activation) == \"CLIP\"\n\n    if pooling_type == \"MAX\":\n        rewriter = legalize.MaxPoolingRewriter()\n        pattern_table = [\n            (\n                ethosu.MaxPool2DParams.composite_name,\n                ethosu.qnn_maxpool2d_pattern(),\n                lambda pat: ethosu.MaxPool2DParams(pat).is_valid(),\n            ),\n        ]\n    elif pooling_type == \"AVG\":\n        rewriter = legalize.AvgPoolingRewriter()\n        pattern_table = [\n            (\n                ethosu.AvgPool2DParams.composite_name,\n                ethosu.qnn_avgpool2d_pattern(),\n                lambda pat: ethosu.AvgPool2DParams(pat).is_valid(),\n            ),\n        ]\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"x\": ifm_shape},\n        dtype_dict={\"x\": dtype},\n    )\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"operator_type\", [\"ADD\", \"SUB\", \"MUL\", \"MIN\", \"MAX\"])\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape, reversed_operands\",\n    [\n        ([1, 2, 3, 4], [1, 2, 3, 4], False),\n        ([1, 2, 3, 4], [1, 1, 3, 1], False),\n        ([1, 1, 3, 1], [1, 2, 3, 4], True),\n        ([1, 4, 4], [4, 1], False),\n        ([4], [4], False),\n        ([4], [1, 2, 3, 4], True),\n        ([1, 4, 4], [4, 1], False),\n    ],\n)\n@pytest.mark.parametrize(\"activation_function\", [\"NONE\", \"RELU\"])\ndef test_tflite_binary_elemwise_legalize(\n    operator_type,\n    ifm_shape,\n    ifm2_shape,\n    reversed_operands,\n    activation_function,\n):\n    np.random.seed(0)\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x, y):\n                if operator_type == \"ADD\":\n                    op = tf.math.add(x, y)\n                elif operator_type == \"SUB\":\n                    op = tf.math.subtract(x, y)\n                elif operator_type == \"MUL\":\n                    op = tf.math.multiply(x, y)\n                elif operator_type == \"MIN\":\n                    op = tf.math.minimum(x, y)\n                elif operator_type == \"MAX\":\n                    op = tf.math.maximum(x, y)\n                if activation_function == \"RELU\":\n                    op = tf.nn.relu(op)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32), tf.TensorSpec(ifm2_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                data2 = np.random.rand(*tuple(ifm2_shape)) * 2\n                yield [data.astype(np.float32), data2.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        out_shape = ifm2_shape if reversed_operands else ifm_shape\n        shapes = [ifm_shape, ifm2_shape]\n        ifm_index, ifm2_index = (1, 0) if reversed_operands else (0, 1)\n        op = ext_func.body\n\n        has_reshaped_output = False\n        shapes_padded = [[1] * (4 - len(s)) + s for s in shapes]\n        out_padded = [1] * (4 - len(out_shape)) + out_shape\n        if op.op.name != \"contrib.ethosu.binary_elementwise\":\n            has_reshaped_output = True\n            op = op.args[0]\n\n        assert list(op.args[0].checked_type.shape) == shapes_padded[ifm_index]\n        assert list(op.args[1].checked_type.shape) == shapes_padded[ifm2_index]\n        assert op.args[0].checked_type.dtype == dtype\n        assert list(op.checked_type.shape) == out_padded\n        assert op.checked_type.dtype == dtype\n        assert op.attrs.operator_type == operator_type\n        assert op.attrs.reversed_operands == reversed_operands\n        if activation_function == \"RELU\":\n            assert str(op.attrs.activation) == \"CLIP\"\n\n            if operator_type in [\"MIN\", \"MAX\"]:\n                # MIN and MAX with an activation must have a requantize operation\n                # baked into the output. To check the extra requantize node was\n                # picked up by the pattern, we can make sure the quantization\n                # information is not default.\n                assert float(op.attrs.ifm_scale) != 1.0\n                assert int(op.attrs.ifm_zero_point) != 0\n                assert float(op.attrs.ifm2_scale) != 1.0\n                assert int(op.attrs.ifm2_zero_point) != 0\n                assert float(op.attrs.ofm_scale) != 1.0\n                assert int(op.attrs.ofm_zero_point) != 0\n\n        if has_reshaped_output:\n            assert list(ext_func.body.checked_type.shape) == out_shape\n\n    if operator_type == \"ADD\":\n        rewriter = legalize.AddRewriter()\n        pattern_table = [\n            (\n                ethosu.AddParams.composite_name,\n                ethosu.qnn_add_pattern(),\n                lambda pat: ethosu.AddParams(pat).is_valid(),\n            ),\n        ]\n    elif operator_type == \"SUB\":\n        rewriter = legalize.SubRewriter()\n        pattern_table = [\n            (\n                ethosu.SubParams.composite_name,\n                ethosu.qnn_subtract_pattern(),\n                lambda pat: ethosu.SubParams(pat).is_valid(),\n            ),\n        ]\n    elif operator_type == \"MUL\":\n        rewriter = legalize.MulRewriter()\n        pattern_table = [\n            (\n                ethosu.MulParams.composite_name,\n                ethosu.qnn_mul_pattern(),\n                lambda pat: ethosu.MulParams(pat).is_valid(),\n            ),\n        ]\n    elif operator_type == \"MIN\":\n        rewriter = legalize.MinRewriter()\n        pattern_table = [\n            (\n                ethosu.MinParams.composite_name,\n                ethosu.minimum_pattern(),\n                lambda pat: ethosu.MinParams(pat).is_valid(),\n            ),\n        ]\n    elif operator_type == \"MAX\":\n        rewriter = legalize.MaxRewriter()\n        pattern_table = [\n            (\n                ethosu.MaxParams.composite_name,\n                ethosu.maximum_pattern(),\n                lambda pat: ethosu.MaxParams(pat).is_valid(),\n            ),\n        ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"x\": ifm_shape, \"y\": ifm2_shape},\n        dtype_dict={\"x\": dtype, \"y\": dtype},\n    )\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_binary_add_from_constant_scalar():\n    dtype = \"uint8\"\n    ifm_shape = (1, 4, 4, 8)\n\n    def create_graph():\n        inp = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n        scalar = relay.const(np.ones((1, 1, 1, 1), dtype=dtype), dtype=dtype)\n        add = relay.qnn.op.add(\n            inp,\n            scalar,\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n        )\n        func = relay.Function(relay.analysis.free_vars(add), add)\n        return tvm.IRModule.from_expr(func)\n\n    def verify(ext_func):\n        op = ext_func.body\n        assert list(op.args[0].checked_type.shape) == [1, 4, 4, 8]\n        assert list(op.args[1].checked_type.shape) == [1, 1, 1, 1]\n        assert op.args[0].checked_type.dtype == \"uint8\"\n        assert list(op.checked_type.shape) == [1, 4, 4, 8]\n        assert op.checked_type.dtype == \"uint8\"\n        assert op.attrs.operator_type == \"ADD\"\n\n    rewriter = legalize.AddRewriter()\n    pattern_table = [\n        (\n            ethosu.AddParams.composite_name,\n            ethosu.qnn_add_pattern(),\n            lambda pat: ethosu.AddParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = create_graph()\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape, reversed_operands\",\n    [\n        ([1, 2, 3, 4], [1, 2, 3, 4], False),\n        ([1, 2, 3, 4], [1, 1, 3, 1], False),\n        ([1, 1, 3, 1], [1, 2, 3, 4], True),\n    ],\n)\ndef test_ethosu_left_shift_binary_elemwise_legalize(ifm_shape, ifm2_shape, reversed_operands):\n    dtype = \"int32\"\n    operator_type = \"SHL\"\n\n    def create_graph():\n        input1 = relay.var(\"x1\", shape=ifm_shape, dtype=dtype)\n        input2 = relay.var(\"x2\", shape=ifm2_shape, dtype=dtype)\n        c1 = relay.left_shift(input1, input2)\n        f = relay.Function([input1, input2], c1)\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n        return mod\n\n    def verify(ext_func):\n        out_shape = ifm2_shape if reversed_operands else ifm_shape\n        shapes = [ifm_shape, ifm2_shape]\n        ifm_index, ifm2_index = (1, 0) if reversed_operands else (0, 1)\n        op = ext_func.body\n        assert list(op.args[0].checked_type.shape) == shapes[ifm_index]\n        assert list(op.args[1].checked_type.shape) == shapes[ifm2_index]\n        assert op.args[0].checked_type.dtype == dtype\n        assert list(op.checked_type.shape) == out_shape\n        assert op.checked_type.dtype == dtype\n        assert op.attrs.operator_type == operator_type\n        assert op.attrs.reversed_operands == reversed_operands\n        assert str(op.attrs.activation) == \"NONE\"\n\n    rewriter = legalize.ShlRewriter()\n    pattern_table = [\n        (\n            ethosu.ShlParams.composite_name,\n            ethosu.shl_pattern(),\n            lambda pat: ethosu.ShlParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = create_graph()\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, new_shape\",\n    [\n        ((1, 4, 1, 2), (4, 2)),\n        ((1, 5, 1, 20), (100,)),\n        ((12, 20), (1, 6, 4, 10)),\n        ((30,), (10, 1, 3)),\n    ],\n)\ndef test_relay_reshape_legalize(ifm_shape, new_shape):\n\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    reshape = relay.op.reshape(ifm, new_shape)\n    func = relay.Function([ifm], reshape)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    mod = relay.transform.InferType()(mod)\n\n    reshape_pattern_table = [\n        (\n            ethosu.ReshapeParams.composite_name,\n            ethosu.reshape_pattern(),\n            lambda pat: ethosu.ReshapeParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = partition_ethosu_by_table(mod, reshape_pattern_table)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.ReshapeRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.NoOpRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    ext_func = mod[\"tvmgen_default_ethos_u_main_0\"]\n\n    identity = ext_func.body\n    assert identity.op.name == \"contrib.ethosu.identity\"\n\n    # check that the reshape is still there\n    reshape = identity.args[0]\n    assert reshape.op.name == \"reshape\"\n\n    # check that identity's output shape matches reshape's output shape\n    assert tuple(identity.checked_type.shape) == new_shape\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, begin, size\",\n    [\n        ([1, 10, 50, 4], [0, 5, 11, 2], [1, 5, 11, 1]),\n        ([15, 17, 3], [3, 0, 1], [8, 17, 2]),\n        ([7, 6043], [0, 704], [1, 2860]),\n        ([5000], [123], [2151]),\n    ],\n)\ndef test_tflite_slice(ifm_shape, begin, size):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def slice_func(self, x):\n                return tf.slice(x, begin, size)\n\n        model = Model()\n\n        # Save the model\n        concrete_func = model.slice_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        identity = ext_func.body\n        assert identity.op.name == \"contrib.ethosu.identity\"\n\n        # check that the strided_slice is still there\n        strided_slice = identity.args[0]\n        assert strided_slice.op.name == \"strided_slice\"\n\n        # check that identity's output shape matches strided slice's output shape\n        assert list(identity.checked_type.shape) == size\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    strided_slice_pattern_table = [\n        (\n            ethosu.StridedSliceParams.composite_name,\n            ethosu.strided_slice_pattern(),\n            lambda pat: ethosu.StridedSliceParams(pat).is_valid(),\n        ),\n    ]\n    mod = partition_ethosu_by_table(mod, strided_slice_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.StridedSliceRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.NoOpRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, begin, end\",\n    [([1, 1, 5, 8], [0, 0, 0, 0], [1, 1, 2, 3]), ([1, 3, 3], [0, 1, 2], [1, 2, 3])],\n)\ndef test_tflite_strided_slice(ifm_shape, begin, end):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def strided_slice_func(self, x):\n                return tf.strided_slice(x, begin, end)\n\n        model = Model()\n\n        # Save the model\n        concrete_func = model.strided_slice_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        identity = ext_func.body\n        assert identity.op.name == \"contrib.ethosu.identity\"\n\n        # check that the strided_slice is still there\n        strided_slice = identity.args[0]\n        assert strided_slice.op.name == \"strided_slice\"\n\n        # check that identity's output shape matches strided slice's output shape\n        size = list(np.array(end) - np.array(begin))\n        assert list(identity.checked_type.shape) == size\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    strided_slice_pattern_table = [\n        (\n            ethosu.StridedSliceParams.composite_name,\n            ethosu.strided_slice_pattern(),\n            lambda pat: ethosu.StridedSliceParams(pat).is_valid(),\n        ),\n    ]\n    mod = partition_ethosu_by_table(mod, strided_slice_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.StridedSliceRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.NoOpRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"operator_type\", [\"ABS\"])\n@pytest.mark.parametrize(\n    \"ifm_shape\",\n    [[1, 2, 3, 4], [1, 7, 3], [8, 3, 1], [11, 22], [300]],\n)\ndef test_tflite_unary_elemwise_legalize(\n    operator_type,\n    ifm_shape,\n):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def abs_func(self, x):\n                if operator_type == \"ABS\":\n                    op = tf.math.abs(x)\n                return op\n\n        model = Model()\n\n        # Save the model\n        concrete_func = model.abs_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        out_shape = ifm_shape\n        func_body = ext_func.body\n\n        # If we legalized the unary elementwise op into 4D\n        if func_body.op.name == \"reshape\":\n            reshape = func_body\n            unary = func_body.args[0]\n            reshape2 = unary.args[0]\n\n            # Check the input to the reshape\n            reshape2_in_shape = [i for i in reshape2.args[0].checked_type.shape]\n            assert reshape2_in_shape == ifm_shape\n\n            # Check that the unary elementwise operator is 4D after reshape\n            assert len(unary.checked_type.shape) == 4\n            assert unary.args[0].checked_type.dtype == dtype\n\n            # Check that the output of the graph has the same shape as input\n            reshape_out_shape = [i for i in reshape.checked_type.shape]\n            assert reshape_out_shape == ifm_shape\n            assert unary.attrs.operator_type == operator_type\n\n        else:\n            unary = func_body\n\n            # Check the IFM\n            assert list(unary.args[0].checked_type.shape) == ifm_shape\n            assert unary.args[0].checked_type.dtype == dtype\n\n            # Check the OFM\n            assert list(unary.checked_type.shape) == out_shape\n            assert unary.checked_type.dtype == dtype\n\n            # operator type check\n            assert unary.attrs.operator_type == operator_type\n\n    if operator_type == \"ABS\":\n        rewriter = legalize.AbsRewriter()\n        pattern_table = [\n            (\n                ethosu.AbsParams.composite_name,\n                ethosu.abs_pattern(),\n                lambda pat: ethosu.AbsParams(pat).is_valid(),\n            ),\n        ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = partition_ethosu_by_table(mod, pattern_table)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_tflite_tanh_legalize():\n    dtype = \"int8\"\n    ifm_shape = (1, 241, 132, 7)\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tanh_func(self, x):\n                op = tf.math.tanh(x)\n                return op\n\n        model = Model()\n        concrete_func = model.tanh_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod = ethosu.partition_for_ethosu(mod, params)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.TanhRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    func_body = mod[\"tvmgen_default_ethos_u_main_0\"].body\n    assert func_body.op.name == \"contrib.ethosu.identity\"\n    assert func_body.attrs.activation == \"TANH\"\n    assert tuple(func_body.args[0].checked_type.shape) == (ifm_shape)\n    assert tuple(func_body.args[1].checked_type.shape) == (256,)\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, axis, keep_dims, use_same_quantization\",\n    [\n        # mean to depthwise + multiply\n        [(1, 8, 16, 16), (1, 2), True, False],\n        [(1, 8, 16, 16), (2, 1), True, False],\n        [(1, 3, 4), (0, 1), True, False],\n        [(8, 5), (1, 0), True, False],\n        [(1, 65, 2, 1), (1, 2), True, False],  # special case when h > 64\n        # mean to average pool\n        [(1, 8, 16, 16), (1,), True, True],\n        [(1, 8, 16, 16), (2,), False, True],\n        [(1, 8, 16, 16), (1, 2), False, True],\n        [(3, 3, 4), (0,), True, True],\n        [(3, 3, 4), (1,), False, True],\n        [(8, 5), (0,), False, True],\n        [(8, 5), (1,), True, True],\n        # mean to depthwise\n        [(1, 8, 16, 16), (1,), True, False],\n        [(1, 8, 16, 16), (2,), True, False],\n        [(1, 8, 16, 16), (1, 2), False, False],\n        [(8, 4), (0,), False, False],\n    ],\n)\ndef test_mean(ifm_shape, axis, keep_dims, use_same_quantization):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                op = tf.math.reduce_mean(x, axis=axis, keepdims=keep_dims)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model, 0)\n\n        mod, _ = relay.frontend.from_tflite(\n            tflite_model,\n            shape_dict={\"input\": ifm_shape},\n            dtype_dict={\"input\": dtype},\n        )\n        return mod\n\n    def create_relay_graph_with_same_quantization():\n        ifm = relay.var(\"input\", shape=ifm_shape, dtype=dtype)\n        cast = relay.cast(ifm, dtype=\"int32\")\n        mean = relay.mean(cast, axis=axis, keepdims=keep_dims)\n        requantize = relay.qnn.op.requantize(\n            mean,\n            input_scale=relay.const(1.0, dtype=\"float32\"),\n            input_zero_point=relay.const(0, dtype=\"int32\"),\n            output_scale=relay.const(1.0, dtype=\"float32\"),\n            output_zero_point=relay.const(0, dtype=\"int32\"),\n        )\n\n        func = relay.Function(relay.analysis.free_vars(requantize), requantize)\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    def verify(ext_func):\n        out_var = ext_func.body\n\n        next_op = out_var\n        mul_op = None\n        pooling_op = None\n        depthwise_op = None\n        if (\n            isinstance(next_op, relay.expr.Call)\n            and isinstance(next_op.op, tvm.ir.op.Op)\n            and next_op.op.name == \"reshape\"\n        ):\n            next_op = next_op.args[0]\n        if util.is_named_ethosu_op(next_op, \"binary_elementwise\"):\n            mul_op = next_op\n            next_op = next_op.args[0]\n        if util.is_named_ethosu_op(next_op, \"pooling\"):\n            pooling_op = next_op\n            next_op = next_op.args[0]\n        if util.is_named_ethosu_op(next_op, \"depthwise_conv2d\"):\n            depthwise_op = next_op\n            next_op = next_op.args[0]\n        while (\n            isinstance(next_op, relay.expr.Call)\n            and isinstance(next_op.op, tvm.ir.op.Op)\n            and next_op.op.name == \"reshape\"\n        ):\n            next_op = next_op.args[0]\n        in_var = next_op\n\n        def calculate_expected_output_shape():\n            for i in range(len(ifm_shape)):\n                if i in axis:\n                    if keep_dims:\n                        yield 1\n                else:\n                    yield ifm_shape[i]\n\n        out_shape = tuple(calculate_expected_output_shape())\n\n        # check IFM\n        assert tuple(in_var.checked_type.shape) == ifm_shape\n        assert in_var.checked_type.dtype == dtype\n\n        # check OFM\n        assert tuple(out_var.checked_type.shape) == out_shape\n        assert out_var.checked_type.dtype == dtype\n\n        # check expected legalization case\n        if axis in [(1, 2), (2, 1), (0, 1), (1, 0)] and keep_dims and dtype == \"int8\":\n            assert depthwise_op and mul_op\n            assert mul_op.attrs.operator_type == \"MUL\"\n        elif pooling_op:\n            attrs = pooling_op.attrs\n            assert (\n                attrs.ifm_scale == attrs.ofm_scale and attrs.ifm_zero_point == attrs.ofm_zero_point\n            )\n        else:\n            assert depthwise_op\n            assert not mul_op\n\n    rewriter = legalize.MeanRewriter()\n    pattern_table = [\n        (\n            ethosu.MeanParams.composite_name,\n            ethosu.mean_pattern(),\n            lambda pat: ethosu.MeanParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = (\n        create_relay_graph_with_same_quantization()\n        if use_same_quantization\n        else create_tflite_graph()\n    )\n    mod = partition_ethosu_by_table(mod, pattern_table)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"shapes, axis\",\n    [\n        ([(2, 3), (4, 3)], 0),\n        ([(10, 2, 1), (10, 14, 1)], 1),\n        ([(10,), (13,), (14,)], 0),\n        ([(1, 5, 2, 1), (1, 5, 7, 1), (1, 5, 3, 1)], 2),\n    ],\n)\ndef test_tflite_concat_legalize(shapes, axis):\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, shapes, axis):\n                op = tf.concat(shapes, axis)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            [tf.TensorSpec(shape, tf.float32) for shape in shapes], axis\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                datas = [np.random.rand(*shape) for shape in shapes]\n                yield [data.astype(np.float32) for data in datas]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        new_concat_axis = np.sum(shape[axis] for shape in shapes)\n        out_shape = list(shapes[0])\n        out_shape[axis] = new_concat_axis\n\n        op = ext_func.body\n        for i, _ in enumerate(shapes):\n            assert list(op.args[0][i].checked_type.shape) == list(shapes[i])\n\n        assert list(op.checked_type.shape) == out_shape\n        assert op.checked_type.dtype == \"int8\"\n\n    concat_pattern_table = [\n        (\n            ethosu.ConcatParams.composite_name,\n            ethosu.concat_pattern(),\n            lambda pat: ethosu.ConcatParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={(\"ifm\" + str(i)): shape for i, shape in enumerate(shapes)},\n        dtype_dict={(\"ifm\" + str(i)): \"int8\" for i, _ in enumerate(shapes)},\n    )\n    mod = partition_ethosu_by_table(relay_module, concat_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.ConcatRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.NoOpRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_tflite_sigmoid_legalize():\n    dtype = \"int8\"\n    ifm_shape = (1, 237, 91, 7)\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def sigmoid_func(self, x):\n                op = tf.math.sigmoid(x)\n                return op\n\n        model = Model()\n        concrete_func = model.sigmoid_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_output_type = tf.int8\n        converter.inference_input_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod = ethosu.partition_for_ethosu(mod, params)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.SigmoidRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    func_body = mod[\"tvmgen_default_ethos_u_main_0\"].body\n    assert func_body.op.name == \"contrib.ethosu.identity\"\n    assert func_body.attrs.activation == \"SIGMOID\"\n    assert tuple(func_body.args[0].checked_type.shape) == (ifm_shape)\n    assert tuple(func_body.args[1].checked_type.shape) == (256,)\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, num_or_size_splits, axis\",\n    [\n        ((1, 4, 6, 8), 3, 2),\n        ((4, 6, 8), 2, 0),\n        ((5, 15), 3, 1),\n        ((3, 7), 1, 1),\n        ((100,), 25, 0),\n    ],\n)\ndef test_tflite_split_legalize(ifm_shape, num_or_size_splits, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x, num_or_size_splits, axis):\n                op = tf.split(x, num_or_size_splits, axis=axis)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32), num_or_size_splits, axis\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        # dig out the split\n        single_output_split = num_or_size_splits == 1\n        split = (\n            ext_func.body.tuple_value\n            if single_output_split\n            else ext_func.body.args[0][0].args[0].tuple_value\n        )\n        assert split.op.name == \"split\"\n\n        # Split is specified by number of equal chunks\n        assert split.attrs.indices_or_sections == num_or_size_splits\n\n        assert split.attrs.axis == axis\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = ethosu.partition_for_ethosu(mod)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.PartitionedSplitRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, num_or_size_splits, axis\",\n    [\n        ((1, 4, 6, 8), (1, 3, 4), 3),\n        ((10, 18, 4), (1, 4, 3, 2), 0),\n        ((22, 7), (4, -1), 1),\n        ((25,), (25,), 0),\n    ],\n)\ndef test_tflite_split_v_legalize(ifm_shape, num_or_size_splits, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x, num_or_size_splits, axis):\n                # TF split gets converted into TFLite's split_v\n                op = tf.split(x, num_or_size_splits, axis=axis)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32), num_or_size_splits, axis\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        # dig out the split\n        single_output_split = len(num_or_size_splits) == 1\n        split = (\n            ext_func.body.tuple_value\n            if single_output_split\n            else ext_func.body.args[0][0].args[0].tuple_value\n        )\n        assert split.op.name == \"split\"\n\n        # Split is specified by the size of sections, so converting num_or_size_splits\n        # into the indices where the tensor is split at since this is how split is represented\n        # in Relay\n        split_sections = [] if single_output_split else [num_or_size_splits[0]]\n        for split_size in num_or_size_splits[1:-1]:\n            sec = split_sections[-1] + split_size\n            split_sections.append(sec)\n        assert list(split.attrs.indices_or_sections) == split_sections\n\n        assert split.attrs.axis == axis\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = ethosu.partition_for_ethosu(mod)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.PartitionedSplitRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,ifm_scale,ifm_zp,ofm_scale,ofm_zp\",\n    [[(1, 8, 8, 3), 1.0, 0, 1.0, 0], [(1, 20, 30, 3), 1.345, 34, 0.32, -23]],\n)\ndef test_ethosu_requantize(ifm_shape, ifm_scale, ifm_zp, ofm_scale, ofm_zp):\n    dtype = \"int8\"\n\n    def create_model():\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        requantize = relay.qnn.op.requantize(\n            ifm,\n            relay.const(ifm_scale, dtype=\"float32\"),\n            relay.const(ifm_zp, dtype=\"int32\"),\n            relay.const(ofm_scale, dtype=\"float32\"),\n            relay.const(ofm_zp, dtype=\"int32\"),\n        )\n        return tvm.IRModule.from_expr(relay.Function([ifm], requantize))\n\n    def verify(ext_func):\n        op = ext_func.body\n\n        # Check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n\n        # Check OFM\n        ofm = op.checked_type\n        assert list(ofm.shape) == list(ifm_shape)\n        assert str(ofm.dtype) == dtype\n\n        # Check quantization params\n        assert math.isclose(op.attrs.ifm_scale, ifm_scale, abs_tol=1e-7)\n        assert op.attrs.ifm_zero_point == ifm_zp\n        assert math.isclose(op.attrs.ofm_scale, ofm_scale, abs_tol=1e-7)\n        assert op.attrs.ofm_zero_point == ofm_zp\n\n    rewriter = legalize.RequantizeRewriter()\n    pattern_table = [\n        (\n            ethosu.RequantizeParams.composite_name,\n            ethosu.requantize_pattern(),\n            lambda pat: ethosu.RequantizeParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = create_model()\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\ndef test_multiple_requantize_offload():\n    \"\"\"\n    Testing requantize offload in the case one requantize operation is part of\n    an existing pattern (in this case Mean: cast->mean->requantize) and the\n    other is a stand-alone requantize.\n    \"\"\"\n\n    def create_model():\n        ifm = relay.var(\"input\", shape=(1, 3, 3, 4), dtype=\"int8\")\n        cast = relay.cast(ifm, dtype=\"int32\")\n        mean = relay.mean(cast, axis=1, keepdims=True)\n        requantize = relay.qnn.op.requantize(\n            mean,\n            input_scale=relay.const(1.0, dtype=\"float32\"),\n            input_zero_point=relay.const(0, dtype=\"int32\"),\n            output_scale=relay.const(1.0, dtype=\"float32\"),\n            output_zero_point=relay.const(0, dtype=\"int32\"),\n        )\n        requantize = relay.qnn.op.requantize(\n            requantize,\n            input_scale=relay.const(1.0, dtype=\"float32\"),\n            input_zero_point=relay.const(0, dtype=\"int32\"),\n            output_scale=relay.const(1.0, dtype=\"float32\"),\n            output_zero_point=relay.const(0, dtype=\"int32\"),\n        )\n        return tvm.IRModule.from_expr(relay.Function([ifm], requantize))\n\n    def verify(ext_func):\n        # If mean operation and separate requantize were offloaded correctly,\n        # there should only be a pooling operation followed by an identity\n        # operation leagalized.\n        op = ext_func.body\n        assert op.op.name == \"contrib.ethosu.identity\"\n        op = op.args[0]\n        assert ext_func.body.args[0].op.name == \"contrib.ethosu.pooling\"\n        op = op.args[0]\n        assert isinstance(op, relay.Var)\n\n    mod = create_model()\n    mod = ethosu.partition_for_ethosu(mod)\n    mod = legalize.LegalizeEthosU()(mod)\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"ifm_shape,axis\", [((2,), 0), ((1, 3, 3), 2)])\ndef test_tflite_expand_dims(ifm_shape, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                return tf.expand_dims(x, axis=axis)\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        expected_shape = list(ifm_shape)\n        expected_shape.insert(axis, 1)\n\n        # Check IFM\n        assert list(op.args[0].checked_type.shape) == list(ifm_shape)\n        assert op.args[0].checked_type.dtype == dtype\n\n        # Check OFM\n        assert list(op.checked_type.shape) == expected_shape\n        assert op.checked_type.dtype == dtype\n\n        # Check op\n        assert op.op.name == \"reshape\"\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = ethosu.partition_for_ethosu(mod)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.ExpandDimsRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.ReshapeRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,axis\", [((1, 1, 2, 1), 0), ((1, 3, 3, 1), 3), ((1, 1, 2, 1), None)]\n)\ndef test_tflite_squeeze(ifm_shape, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                return tf.squeeze(x, axis=axis)\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body\n        expected_shape = list(ifm_shape)\n        if isinstance(axis, int):\n            expected_shape = ifm_shape[:axis] + ifm_shape[axis + 1 :]\n        else:\n            expected_shape = list(filter(lambda a: a != 1, expected_shape))\n\n        # Check IFM\n        assert list(op.args[0].checked_type.shape) == list(ifm_shape)\n        assert op.args[0].checked_type.dtype == dtype\n\n        # Check OFM\n        assert list(op.checked_type.shape) == list(expected_shape)\n        assert op.checked_type.dtype == dtype\n\n        # Check op\n        assert op.op.name == \"reshape\"\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = ethosu.partition_for_ethosu(mod)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.SqueezeRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.ReshapeRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,size\",\n    [\n        [(1, 2, 2, 1), (4, 4)],\n        [(1, 4, 7, 3), (8, 14)],\n        [(1, 3, 5, 3), (3, 5)],\n    ],\n)\ndef test_tflite_resize2d_nearest_neighbor(ifm_shape, size):\n    align_corners = False\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        @tf.function\n        def resize_model(x):\n            return tf.compat.v1.image.resize_nearest_neighbor(\n                x, size, align_corners=align_corners, half_pixel_centers=False\n            )\n\n        concrete_func = resize_model.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model, 0)\n\n        mod, _ = relay.frontend.from_tflite(\n            tflite_model,\n            shape_dict={\"input\": ifm_shape},\n            dtype_dict={\"input\": dtype},\n        )\n        return mod\n\n    def verify(ext_func):\n        op = ext_func.body\n        in_var = op.args[0]\n\n        # check IFM\n        assert tuple(in_var.checked_type.shape) == ifm_shape\n        assert in_var.checked_type.dtype == dtype\n\n        # check OFM\n        attrs = dict(op.attrs)\n        out_shape = (ifm_shape[0], size[0], size[1], ifm_shape[3])\n        assert tuple(op.checked_type.shape) == out_shape\n        assert op.checked_type.dtype == dtype\n\n        # Check Op attributes\n        if size[0] == ifm_shape[1] and size[1] == ifm_shape[2]:\n            assert op.op.name == \"contrib.ethosu.identity\"\n        else:\n            assert attrs[\"pooling_type\"] == \"AVG\"\n            assert attrs[\"upscale\"] == \"NEAREST\"\n\n    rewriter = legalize.Resize2dRewriter()\n    pattern_table = [\n        (\n            ethosu.Resize2dParams.composite_name,\n            ethosu.resize2d_pattern(),\n            lambda pat: ethosu.Resize2dParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = create_tflite_graph()\n    mod = partition_ethosu_by_table(mod, pattern_table)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,size,align_corners\",\n    [\n        [(1, 2, 2, 1), (4, 4), False],\n        [(1, 4, 7, 3), (8, 14), False],\n        [(1, 2, 2, 1), (3, 3), True],\n        [(1, 4, 7, 3), (7, 13), True],\n        [(1, 3, 5, 3), (3, 5), False],\n    ],\n)\ndef test_tflite_resize2d_bilinear(ifm_shape, size, align_corners):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        @tf.function\n        def resize_model(x):\n            return tf.compat.v1.image.resize_bilinear(\n                x, size, align_corners=align_corners, half_pixel_centers=False\n            )\n\n        concrete_func = resize_model.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model, 0)\n\n        mod, _ = relay.frontend.from_tflite(\n            tflite_model,\n            shape_dict={\"input\": ifm_shape},\n            dtype_dict={\"input\": dtype},\n        )\n        return mod\n\n    def verify(ext_func):\n        op = ext_func.body\n        in_var = op.args[0]\n\n        # check IFM\n        assert tuple(in_var.checked_type.shape) == ifm_shape\n        assert in_var.checked_type.dtype == dtype\n\n        # check OFM\n        attrs = dict(op.attrs)\n        out_shape = (ifm_shape[0], size[0], size[1], ifm_shape[3])\n        assert tuple(op.checked_type.shape) == out_shape\n        assert op.checked_type.dtype == dtype\n\n        # Check Op attributes\n        if size[0] == ifm_shape[1] and size[1] == ifm_shape[2]:\n            assert op.op.name == \"contrib.ethosu.identity\"\n        else:\n            assert attrs[\"pooling_type\"] == \"AVG\"\n            assert attrs[\"upscale\"] == \"NEAREST\"\n\n            # Check padding\n            if align_corners:\n                assert list(attrs[\"padding\"]) == [0, 0, 0, 0]\n            else:\n                assert list(attrs[\"padding\"]) == [0, 0, 1, 1]\n\n    rewriter = legalize.Resize2dRewriter()\n    pattern_table = [\n        (\n            ethosu.Resize2dParams.composite_name,\n            ethosu.resize2d_pattern(),\n            lambda pat: ethosu.Resize2dParams(pat).is_valid(),\n        ),\n    ]\n\n    mod = create_tflite_graph()\n    mod = partition_ethosu_by_table(mod, pattern_table)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,ofm_shape,kernel_shape,padding\",\n    [\n        [(1, 2, 2, 1), (1, 4, 4, 1), (3, 3), \"SAME\"],\n        [(1, 2, 2, 1), (1, 9, 9, 1), (7, 7), \"VALID\"],\n        [(1, 2, 4, 3), (1, 4, 8, 3), (3, 3), \"SAME\"],\n        [(1, 10, 5, 3), (1, 21, 13, 3), (3, 5), \"VALID\"],\n    ],\n)\n@pytest.mark.parametrize(\"has_bias\", [False, True])\ndef test_tflite_transpose_convolution(ifm_shape, ofm_shape, kernel_shape, padding, has_bias):\n    dtype = \"int8\"\n    dilations = (1, 1)\n    strides = (2, 2)\n\n    def create_tflite_graph():\n        @tf.function\n        def conv2d_transpose(x):\n            bias_shape = ofm_shape[3]\n            bias = tf.constant(np.random.uniform(size=bias_shape), dtype=tf.float32)\n            weight_shape = [kernel_shape[0], kernel_shape[1], ifm_shape[3], ofm_shape[3]]\n            weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n            tf_strides = [1, strides[0], strides[1], 1]\n            op = tf.nn.conv2d_transpose(\n                x,\n                weight,\n                output_shape=ofm_shape,\n                strides=tf_strides,\n                padding=padding,\n                dilations=dilations,\n            )\n            if has_bias:\n                op = tf.nn.bias_add(op, bias)\n            return op\n\n        concrete_func = conv2d_transpose.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model, 0)\n\n        mod, params = relay.frontend.from_tflite(\n            tflite_model,\n            shape_dict={\"input\": ifm_shape},\n            dtype_dict={\"input\": dtype},\n        )\n        return mod, params\n\n    def verify(ext_func):\n        strided_slice = ext_func.body\n        conv = strided_slice.args[0]\n        ofm_channels = conv.attrs.ofm_channels\n\n        # Check IFM\n        ifm = conv.args[0].checked_type\n        assert list(ifm.shape) == list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n        assert ifm.shape[3] == ofm_channels\n\n        # Check OFM\n        ofm = strided_slice.checked_type\n        assert list(ofm.shape) == list(ofm_shape)\n        assert str(ofm.dtype) == dtype\n        assert ofm.shape[3] == ofm_channels\n\n        # Check weights\n        weights_ohwi = conv.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert list(weights_ohwi.shape) == [\n            ofm_channels,\n            kernel_shape[0],\n            kernel_shape[1],\n            ifm_shape[3],\n        ]\n\n        # Check that scale_bias matches weight tensor\n        assert list(conv.args[2].checked_type.shape)[0] == ofm_channels\n\n        # Calculate expected padding for conv2d op\n        if padding == \"VALID\":\n            expected_padding = [0, 0, 0, 0]\n        elif padding == \"SAME\":\n            pad_top, pad_bottom = get_pad_value(ofm_shape[1], kernel_shape[0], strides[0])\n            pad_left, pad_right = get_pad_value(ofm_shape[2], kernel_shape[1], strides[1])\n            expected_padding = [pad_top, pad_left, pad_bottom, pad_right]\n        pad_top = kernel_shape[0] - 1 - expected_padding[0]\n        pad_left = kernel_shape[1] - 1 - expected_padding[1]\n        pad_bottom = kernel_shape[0] - 1 - expected_padding[2]\n        pad_right = kernel_shape[1] - 1 - expected_padding[3]\n        if strides == [2, 2]:\n            pad_bottom -= 1\n            pad_right -= 1\n        expected_padding = [pad_top, pad_left, pad_bottom, pad_right]\n        assert list(conv.attrs.padding) == list(expected_padding)\n\n        assert list(conv.attrs.strides) == [1, 1]\n\n    rewriter = legalize.Conv2DTransposeRewriter()\n    pattern_table = [\n        (\n            ethosu.QnnConv2DTransposeParams.composite_name,\n            ethosu.qnn_conv2d_transpose_pattern(),\n            lambda pat: ethosu.QnnConv2DTransposeParams(pat).is_valid(),\n        ),\n    ]\n\n    mod, params = create_tflite_graph()\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = partition_ethosu_by_table(mod, pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        rewriter, mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shapes,axis\",\n    [\n        ([(1, 2, 2), (1, 2, 2), (1, 2, 2)], 2),\n        ([(5, 4), (5, 4)], 1),\n        ([(1,), (1,)], 0),\n        ([(3, 1), (3, 1), (3, 1), (3, 1)], 0),\n    ],\n)\ndef test_tflite_pack(ifm_shapes, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, inputs, axis):\n                return tf.stack(inputs, axis=axis)\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            [tf.TensorSpec(shape, tf.float32) for shape in ifm_shapes], axis\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                datas = [np.random.rand(*shape) for shape in ifm_shapes]\n                yield [data.astype(np.float32) for data in datas]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        new_pack_axis = len(ifm_shapes)\n        ifm_shape = list(ifm_shapes[0])\n        op = ext_func.body\n\n        after_reshape = ifm_shape[:axis] + [1] + ifm_shape[axis:]\n        out_shape = ifm_shape[:axis] + [new_pack_axis] + ifm_shape[axis:]\n\n        assert op.op.name == \"concatenate\"\n\n        # Check shapes after expand_dims (legalized as reshape)\n        for i in range(len(ifm_shapes)):\n            assert list(op.args[0][i].checked_type.shape) == after_reshape\n            assert op.args[0][i].checked_type.dtype == dtype\n\n        # Check output\n        assert list(op.checked_type.shape) == out_shape\n        assert op.checked_type.dtype == dtype\n\n    pack_pattern_table = [\n        (\n            ethosu.ConcatParams.composite_name,\n            ethosu.concat_pattern(),\n            lambda pat: ethosu.ConcatParams(pat).is_valid(),\n        ),\n        (\n            ethosu.ExpandDimsParams.composite_name,\n            ethosu.expand_dims_pattern(),\n            lambda pat: ethosu.ExpandDimsParams(pat).is_valid(),\n        ),\n        (\n            ethosu.ReshapeParams.composite_name,\n            ethosu.reshape_pattern(),\n            lambda pat: ethosu.ReshapeParams(pat).is_valid(),\n        ),\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={(\"ifm\" + str(i)): shape for i, shape in enumerate(ifm_shapes)},\n        dtype_dict={(\"ifm\" + str(i)): dtype for i, _ in enumerate(ifm_shapes)},\n    )\n    mod = partition_ethosu_by_table(relay_module, pack_pattern_table)\n\n    seq = [\n        legalize.ConcatRewriter(),\n        legalize.ExpandDimsRewriter(),\n        legalize.ReshapeRewriter(),\n        legalize.NoOpRewriter(),\n    ]\n    for legalizer in seq:\n        mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n            legalizer, mod[\"tvmgen_default_ethos_u_main_0\"]\n        )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape,axis\",\n    [[(1, 2, 3, 4), 1], [(2, 3), 1], [(5, 6, 7), 2]],\n)\ndef test_tflite_unpack(ifm_shape, axis):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x, axis):\n                return tf.unstack(x, axis=axis)\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32), axis\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        outputs = ext_func.body.args[0].fields\n        shape = list(ifm_shape)\n        unpacked_shape = shape[:axis] + shape[axis + 1 :]\n        split_shape = shape[:axis] + [1] + shape[axis + 1 :]\n\n        assert len(outputs) == shape[axis]\n\n        for i, output in enumerate(outputs):\n            expr = output.args[0].args[0]\n            expr = expr.tuple_value[expr.index]\n            expr = expr.args[0]\n\n            # Checking expected unpacked output shape.\n            # Squeeze is legalized to a reshape.\n            assert expr.op.name == \"reshape\"\n            assert list(expr.checked_type.shape) == unpacked_shape\n            assert output.checked_type.dtype == dtype\n\n            expr = expr.args[0]\n            expr = expr.tuple_value[expr.index]\n            expr = expr.args[0]\n\n            # Check input is split correctly\n            assert list(expr.args[0].checked_type.shape) == shape\n            assert list(expr.checked_type.shape) == split_shape\n            assert expr.checked_type.dtype == dtype\n\n            # Check split attrs\n            begin_shape = [0] * len(ifm_shape)\n            begin_shape[axis] = i\n            assert list(expr.attrs.begin) == begin_shape\n            end_shape = shape[:axis] + [i + 1] + shape[axis + 1 :]\n            assert list(expr.attrs.end) == end_shape\n            assert list(expr.attrs.strides) == [1]\n\n    pack_pattern_table = [\n        (\n            ethosu.SplitParams.composite_name,\n            ethosu.split_pattern(),\n            lambda pat: ethosu.SplitParams(pat).is_valid(),\n        ),\n        (\n            ethosu.SqueezeParams.composite_name,\n            ethosu.squeeze_pattern(),\n            lambda pat: ethosu.SqueezeParams(pat).is_valid(),\n        ),\n        (\n            ethosu.ReshapeParams.composite_name,\n            ethosu.reshape_pattern(),\n            lambda pat: ethosu.ReshapeParams(pat).is_valid(),\n        ),\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = partition_ethosu_by_table(mod, pack_pattern_table)\n\n    seq = [\n        legalize.PartitionedSplitRewriter(),\n        legalize.SplitRewriter(),\n        legalize.SqueezeRewriter(),\n        legalize.ReshapeRewriter(),\n        legalize.NoOpRewriter(),\n    ]\n    for legalizer in seq:\n\n        mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n            legalizer, mod[\"tvmgen_default_ethos_u_main_0\"]\n        )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 15, 15, 3), (1, 8, 9, 1)])\n@pytest.mark.parametrize(\"alpha\", [0.2, 0.634])\ndef test_tflite_leaky_relu(ifm_shape, alpha):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def leaky_relu_func(self, x):\n                return tf.nn.leaky_relu(x, alpha=alpha)\n\n        model = Model()\n        concrete_func = model.leaky_relu_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32),\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    def verify(ext_func):\n        func_body = ext_func.body\n        assert func_body.op.name == \"contrib.ethosu.identity\"\n        assert func_body.attrs.activation == \"LUT\"\n        assert tuple(func_body.args[0].checked_type.shape) == (ifm_shape)\n        assert tuple(func_body.args[1].checked_type.shape) == (256,)\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, _ = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = ethosu.partition_for_ethosu(mod)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.LeakyReLURewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod[\"tvmgen_default_ethos_u_main_0\"] = relay.transform.InferType()(mod)[\n        \"tvmgen_default_ethos_u_main_0\"\n    ]\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 14), (1, 151)])\n@pytest.mark.parametrize(\"ofm_channels\", [32, 64])\n@pytest.mark.parametrize(\"use_bias\", [True, False])\n@pytest.mark.parametrize(\"activation_function\", [\"RELU\", \"NONE\"])\ndef test_tflite_fully_connected(\n    ifm_shape,\n    ofm_channels,\n    use_bias,\n    activation_function,\n):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def fully_connected(self, x):\n                bias_shape = ofm_channels\n                bias = tf.constant(np.random.uniform(size=bias_shape), dtype=tf.float32)\n                w = tf.constant(\n                    np.random.uniform(size=[ifm_shape[1], ofm_channels]),\n                    dtype=tf.float32,\n                )\n                x = tf.matmul(x, w)\n                if use_bias:\n                    x = tf.nn.bias_add(x, bias)\n                if activation_function:\n                    x = tf.nn.relu(x)\n                return x\n\n        model = Model()\n        concrete_func = model.fully_connected.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(ext_func):\n        op = ext_func.body.args[0]\n        ofm_channels = op.attrs.ofm_channels\n\n        # check IFM\n        ifm = op.args[0].checked_type\n        assert list(ifm.shape) == [1, 1] + list(ifm_shape)\n        assert str(ifm.dtype) == dtype\n\n        # check OFM\n        ofm = op.checked_type\n        assert list(ofm.shape) == [1, 1, 1, ofm_channels]\n        assert str(ofm.dtype) == dtype\n\n        # check weights\n        weights_ohwi = op.args[1].data.asnumpy()\n        assert str(weights_ohwi.dtype) == dtype\n        assert list(weights_ohwi.shape) == [ofm_channels, 1, 1, ifm_shape[1]]\n\n        # Check that scale_bias matches weight tensor\n        assert list(op.args[2].checked_type.shape)[0] == ofm_channels\n\n        assert list(op.attrs.padding) == [0, 0, 0, 0]\n        assert list(op.attrs.strides) == [1, 1]\n        assert list(op.attrs.dilation) == [1, 1]\n        if activation_function == \"RELU\":\n            assert str(op.attrs.activation) == \"CLIP\"\n\n    fc_pattern_table = [\n        (\n            ethosu.FullyConnectedParams.composite_name,\n            ethosu.qnn_fc_pattern(),\n            lambda pat: ethosu.FullyConnectedParams(pat).is_valid(),\n        )\n    ]\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, fc_params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], fc_params)\n    mod = partition_ethosu_by_table(mod, fc_pattern_table)\n\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.FullyConnectedRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [(1, 5, 5, 3), (1, 12, 9, 1)])\ndef test_tflite_hard_swish(ifm_shape):\n    dtype = \"int8\"\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_function(self, x):\n                op = tf.keras.layers.Lambda(\n                    lambda x: x * tf.keras.activations.relu(x + 3.0, max_value=6.0) / 6.0\n                )(x)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, tf.float32)\n        )\n\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n\n        return tflite_model\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n\n    mod = ethosu.partition_for_ethosu(mod, params)\n    mod[\"tvmgen_default_ethos_u_main_0\"] = dataflow_pattern.rewrite(\n        legalize.HardSwishRewriter(), mod[\"tvmgen_default_ethos_u_main_0\"]\n    )\n    mod = relay.transform.InferType()(mod)\n\n    func_body = mod[\"tvmgen_default_ethos_u_main_0\"].body\n    assert func_body.op.name == \"contrib.ethosu.identity\"\n    assert func_body.attrs.activation == \"LUT\"\n    assert tuple(func_body.args[0].checked_type.shape) == (ifm_shape)\n    assert tuple(func_body.args[1].checked_type.shape) == (256,)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_legalize_no_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport numpy as np\nimport tensorflow as tf\nimport tflite.Model\n\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu import legalize\nfrom tvm.relay.op.contrib import ethosu\nfrom tvm.relay.build_module import bind_params_by_name\n\n# There's a bug in TFLite converter which doesn't allow us to create single operator\n# reshape and strided_slice graphs, so in order to have some testing coverage for these\n# operators starting from TFLite, we test them alongside other operators\ndef test_tflite_reshape_and_strided_slice():\n    dtype = \"int8\"\n    ifm_shape = [1, 8, 3, 6]\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def model_func(self, x):\n                weight_shape = [3, 3, 6, 1]  # HWO1\n                weight = tf.constant(np.random.uniform(size=weight_shape), dtype=tf.float32)\n                op = tf.nn.depthwise_conv2d(x, weight, strides=[1, 1, 1, 1], padding=\"SAME\")\n                op = tf.nn.relu(op)\n                op = tf.reshape(op, [1, 8, 6, 3])\n                op = tf.nn.pool(op, [2, 2], \"MAX\")\n                op = tf.strided_slice(op, [0, 2, 3, 1], [1, 6, 5, 2])\n                return op\n\n        model = Model()\n        concrete_func = model.model_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    def verify(func):\n        # This TFLite graph gets lowered into\n        # deptwhise_conv2d -> clip -> reshape -> max_pool -> strided_slice -> reshape\n        # which gets legalized into ethosu_depthwise_conv2d -> reshape -> ehtosu_identity\n        # -> ethosu_pooling -> strided_slice -> identity -> reshape -> identity\n\n        identity3 = func.body\n        reshape2 = identity3.args[0]\n        identity2 = reshape2.args[0]\n        strided_slice = identity2.args[0]\n        max_pool = strided_slice.args[0]\n        identity1 = max_pool.args[0]\n        reshape1 = identity1.args[0]\n        depthwise_conv2d = reshape1.args[0]\n\n        assert identity3.op.name == \"contrib.ethosu.identity\"\n        assert reshape2.op.name == \"reshape\"\n        assert identity2.op.name == \"contrib.ethosu.identity\"\n        assert strided_slice.op.name == \"strided_slice\"\n        assert max_pool.op.name == \"contrib.ethosu.pooling\"\n        assert identity1.op.name == \"contrib.ethosu.identity\"\n        assert reshape1.op.name == \"reshape\"\n        assert depthwise_conv2d.op.name == \"contrib.ethosu.depthwise_conv2d\"\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = ethosu.partition_for_ethosu(mod)\n    mod = legalize.LegalizeEthosU()(mod)\n\n    verify(mod[\"tvmgen_default_ethos_u_main_0\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_lookup_table.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport numpy as np\nimport tflite.Model\n\nimport tvm\nimport tensorflow as tf\nfrom tvm import relay\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.relay.build_module import bind_params_by_name  # type: ignore\n\nfrom . import infra\n\n\nACCEL_TYPES = [\"ethos-u55-256\", \"ethos-u55-128\", \"ethos-u55-64\", \"ethos-u55-32\"]\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\ndef test_tflite_lut_activations(accel_type):\n\n    dtype = \"int8\"\n    ifm_shape = (1, 55, 55, 3)\n\n    def create_tflite_graph():\n        class Model(tf.Module):\n            @tf.function\n            def tf_func(self, x):\n                weight_shape = (3, 3, ifm_shape[3], 4)\n                weight = tf.constant(\n                    np.random.uniform(low=0, high=0.3, size=weight_shape), dtype=tf.float32\n                )\n                # The input strides to the TensorFlow API needs to be of shape 1x4\n                op = tf.nn.conv2d(x, weight, strides=(1, 2, 2, 1), padding=\"SAME\", dilations=(1, 1))\n                op = tf.nn.tanh(op)\n                op = tf.nn.tanh(op)\n\n                weight_shape2 = (2, 3, 4, 1)\n                weight2 = tf.constant(\n                    np.random.uniform(low=0, high=0.3, size=weight_shape2), dtype=tf.float32\n                )\n                op = tf.nn.depthwise_conv2d(\n                    op, weight2, strides=(1, 1, 1, 1), padding=\"VALID\", dilations=(2, 2)\n                )\n                op = tf.nn.sigmoid(op)\n                op = tf.nn.max_pool(op, (1, 1), strides=(1, 1, 1, 1), padding=\"SAME\")\n                op = tf.nn.tanh(op)\n                return op\n\n        model = Model()\n        concrete_func = model.tf_func.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = 0.7 * np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    tflite_graph = create_tflite_graph()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    relay_module, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": dtype},\n    )\n    mod = partition_for_ethosu(relay_module, params)\n\n    # Generate reference data\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_graph)\n\n    test_runner = infra.create_test_runner(accel_type)\n    compiled_models = infra.build_source(\n        mod,\n        input_data,\n        output_data,\n        test_runner,\n    )\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    get_artifacts = tvm._ffi.get_global_func(\"runtime.module.ethos-u.get_artifacts\")\n    compilation_artifacts = get_artifacts(ethosu_module)\n    cmms = bytes.fromhex(compilation_artifacts[0].command_stream)\n    infra.print_payload(cmms)\n    infra.verify_source(compiled_models, test_runner)\n\n\n@pytest.mark.parametrize(\"accel_type\", ACCEL_TYPES)\ndef test_random_lut(accel_type):\n\n    dtype = \"int8\"\n    ifm_shape = (1, 55, 55, 3)\n\n    lut_data = np.random.randint(-128, high=127, size=[256])\n    lut_data_map = {idx: lut_data[idx + 128] for idx in range(-128, 128)}\n\n    in_data = np.random.randint(-128, high=127, size=ifm_shape, dtype=dtype)\n    out_data = np.array([lut_data_map[i] for i in in_data.ravel()]).reshape(ifm_shape).astype(dtype)\n\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm0 = relay.var(\"ifm0\", shape=ifm_shape, dtype=dtype)\n    lut1 = relay.var(\"lut1\", shape=(256,), dtype=\"uint8\")\n\n    identity = infra.make_ethosu_identity(ifm0, lut=lut1, activation=\"LUT\")\n    glb_ethosu = relay.GlobalVar(\"tvmgen_default_ethos_u_main_0\")\n\n    func = (\n        relay.Function([ifm0, lut1], identity)\n        .with_attr(\"Inline\", 1)\n        .with_attr(\"Compiler\", \"ethos-u\")\n        .with_attr(\"global_symbol\", \"tvmgen_default_ethos_u_main_0\")\n        .with_attr(\"Primitive\", 1)\n    )\n\n    params = {\"lut1\": tvm.nd.array(lut_data.astype(\"uint8\"))}\n    func = bind_params_by_name(func, params)\n\n    mod = tvm.IRModule()\n    mod[glb_ethosu] = func\n    mod = relay.transform.InferType()(mod)\n\n    call = relay.Call(glb_ethosu, [ifm])\n    mod[\"main\"] = relay.Function([ifm], call)\n    mod = relay.transform.InferType()(mod)\n\n    test_runner = infra.create_test_runner(accel_type)\n    compiled_models = infra.build_source(\n        mod,\n        {\"ifm\": in_data},\n        {\"output\": out_data},\n        test_runner,\n    )\n\n    # Assumes only two runtime.Modules are created -- i.e. single offload module\n    ethosu_module = compiled_models[0].executor_factory.lib.imported_modules[0].imported_modules[0]\n\n    # Verify generated C source\n    get_artifacts = tvm._ffi.get_global_func(\"runtime.module.ethos-u.get_artifacts\")\n    compilation_artifacts = get_artifacts(ethosu_module)\n    cmms = bytes.fromhex(compilation_artifacts[0].command_stream)\n    infra.print_payload(cmms)\n    infra.verify_source(compiled_models, test_runner)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_lower_to_te.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_te\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import OperatorCompute\nimport tvm.relay.backend.contrib.ethosu.op as ethosu_ops\n\n\ndef test_ethosu_conv2d():\n    ifm = relay.var(\"ifm\", shape=(1, 10, 20, 30), dtype=\"uint8\")\n    weight = relay.var(\"weight\", shape=(40, 3, 3, 30), dtype=\"uint8\")\n    scale_bias = relay.var(\"scale_bias\", shape=(40, 10), dtype=\"uint8\")\n    lut = relay.var(\"lut\", shape=(), dtype=\"uint8\")\n    conv = ethosu_ops.ethosu_conv2d(\n        ifm,\n        weight,\n        scale_bias,\n        lut,\n        ifm_scale=0.5,\n        ifm_zero_point=10,\n        weight_zero_point=12,\n        ofm_scale=0.25,\n        ofm_zero_point=14,\n        ofm_channels=40,\n        padding=(1, 1, 1, 1),\n        kernel_shape=(3, 3),\n        strides=(1, 1),\n        dilation=(1, 1),\n    )\n    expr = relay.Function(relay.analysis.free_vars(conv), conv)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = relay.transform.InferType()(mod)\n    lowered = lower_to_te(mod[\"main\"])\n    assert len(lowered.outputs) == 1\n    assert len(lowered.inputs) == 4\n    conv2d_compute = OperatorCompute.from_output(lowered.outputs[0])\n    assert conv2d_compute.op.name == \"ethosu_conv2d\"\n    input_shapes = set()\n    for inp in lowered.inputs:\n        input_shapes.add(tuple([x.value for x in inp.shape]))\n    assert input_shapes == {(40, 10), (1, 10, 20, 30), (40, 3, 3, 30), ()}\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_lut_optimizer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test the pass that removes unnecssary identity operation if the identity\nuses LUT and the preceding operator is LUT capable and doesn't already have a LUT.\n\"\"\"\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tensorflow as tf\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.codegen import LUTsOptimizer\nfrom tvm.relay.backend.contrib.ethosu.codegen import relay_to_tir\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\n\nfrom . import infra\n\n\ndef test_merge_lut_into_conv():\n    \"\"\"If an operator that has a LUT attribute is followed by an identity operator\n    with LUT, we can merge the two operataors.\"\"\"\n\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    lut1 = relay.const([i for i in range(256)], dtype=\"int8\")\n    lut2 = relay.const([i for i in reversed(range(256))], dtype=\"int8\")\n\n    def before():\n        conv1 = infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n        id1 = infra.make_ethosu_identity(conv1, lut=lut1, activation=\"TANH\")\n        conv2 = infra.make_ethosu_conv2d(id1, 4, 7, (2, 2), (1, 1), (1, 1), (1, 1))\n        id2 = infra.make_ethosu_identity(conv2, lut=lut2, activation=\"SIGMOID\")\n\n        func = relay.Function(relay.analysis.free_vars(id2), id2)\n        func = func.with_attr(\"Compiler\", \"ethos-u\")\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    def after():\n        conv1 = infra.make_ethosu_conv2d(\n            ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1), lut=lut1, activation=\"TANH\"\n        )\n        conv2 = infra.make_ethosu_conv2d(\n            conv1, 4, 7, (2, 2), (1, 1), (1, 1), (1, 1), lut=lut2, activation=\"SIGMOID\"\n        )\n\n        func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n        func = func.with_attr(\"Compiler\", \"ethos-u\")\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = LUTsOptimizer()(before())\n    mod = relay.transform.InferType()(mod)\n\n    assert tvm.ir.structural_equal(mod, after())\n\n\ndef test_multiple_luts():\n    \"\"\"Test that when an operation already has a LUT, we don't overwrite that LUT\"\"\"\n\n    ifm = relay.var(\"x\", shape=(1, 8, 8, 4), dtype=\"int8\")\n    lut1 = relay.const([i for i in range(256)], dtype=\"int8\")\n    lut2 = relay.const([i for i in reversed(range(256))], dtype=\"int8\")\n\n    def before():\n        conv1 = infra.make_ethosu_conv2d(ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1))\n        id1 = infra.make_ethosu_identity(conv1, lut=lut1, activation=\"TANH\")\n        id2 = infra.make_ethosu_identity(id1, lut=lut2, activation=\"TANH\")\n\n        func = relay.Function(relay.analysis.free_vars(id2), id2)\n        func = func.with_attr(\"Compiler\", \"ethos-u\")\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    def after():\n        conv1 = infra.make_ethosu_conv2d(\n            ifm, 4, 4, (3, 3), (1, 1), (1, 1), (1, 1), lut=lut1, activation=\"TANH\"\n        )\n        id2 = infra.make_ethosu_identity(conv1, lut=lut2, activation=\"TANH\")\n\n        func = relay.Function(relay.analysis.free_vars(id2), id2)\n        func = func.with_attr(\"Compiler\", \"ethos-u\")\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = LUTsOptimizer()(before())\n    mod = relay.transform.InferType()(mod)\n\n    assert tvm.ir.structural_equal(mod, after())\n\n\ndef test_lut_optimizer_runs_in_compilation_pipeline():\n    \"\"\"Test that the LUT optimization pass runs as part of the NPU compilation pipeline.\"\"\"\n    ifm_shape = (1, 4, 4, 4)\n\n    @tf.function\n    def get_graph(x):\n        weight1 = tf.constant(np.random.uniform(size=(1, 1, 4, 4)), dtype=tf.float32)\n        op = tf.nn.conv2d(x, weight1, (1, 1), \"VALID\")\n        op = tf.nn.tanh(op)\n        weight2 = tf.constant(np.random.uniform(size=(1, 1, 4, 1)), dtype=tf.float32)\n        op = tf.nn.depthwise_conv2d(op, weight2, (1, 1, 1, 1), \"VALID\")\n        return tf.nn.tanh(op)\n\n    mod, _ = infra.get_tflite_graph(get_graph, [ifm_shape])\n    mod = partition_for_ethosu(mod)\n    mod = relay_to_tir(mod)\n\n    external_gv_name = mod[\"main\"].body.op.name_hint\n    prim_func = mod[external_gv_name]\n\n    # Check for hints in the TIR prim func that the LUT optimization pass has ran.\n    # If the module was optimized, there should be no identity operations.\n    def check_identity(stmt):\n        if isinstance(stmt, tvm.tir.expr.Call):\n            assert stmt.args[0] != \"ethosu_identity\"\n\n    tvm.tir.stmt_functor.post_order_visit(prim_func.body, check_identity)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_merge_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.relay.backend.contrib.ethosu.tir.passes import MergeConstants\nimport numpy as np\n\n\ndef check_const_dictionaries(const_dict, new_const_dict):\n    assert list(const_dict) == list(new_const_dict)\n    for key, value in const_dict.items():\n        new_value = new_const_dict[key]\n        assert len(value) == len(new_value)\n        for i in range(len(value)):\n            assert value[i] == new_value[i]\n\n\ndef test_only_one_operator():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(128,), \"uint8\"], buffer3: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1_data = T.allocate([128], \"uint8\", \"global\")\n            p1 = T.buffer_decl([128], \"uint8\", data=p1_data)\n            p4_data = T.allocate([32], \"uint8\", \"global\")\n            p4 = T.buffer_decl([32], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(160,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p4_data = T.allocate([160], \"uint8\", \"global\")\n            p4 = T.buffer_decl([160], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 160, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p4[0], 128, 12, p4[128], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n    const_dict = {\n        0: np.array([0, 10], dtype=np.uint8),\n        1: np.array([1, 11], dtype=np.uint8),\n    }\n    new_const_dict = {0: np.concatenate((const_dict[0], const_dict[1]))}\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_all_operators_with_weights():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(128,), \"uint8\"], buffer3: T.Buffer[(32,), \"uint8\"], buffer4: T.Buffer[(112,), \"uint8\"], buffer5: T.Buffer[(32,), \"uint8\"], buffer6: T.Buffer[(112,), \"uint8\"], buffer7: T.Buffer[(32,), \"uint8\"], buffer8: T.Buffer[(112,), \"uint8\"], buffer9: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1_data = T.allocate([128], \"uint8\", \"global\")\n            p1 = T.buffer_decl([128], \"uint8\", data=p1_data)\n            p2_data = T.allocate([112], \"uint8\", \"global\")\n            p2 = T.buffer_decl([112], \"uint8\", data=p2_data)\n            p3_data = T.allocate([112], \"uint8\", \"global\")\n            p3 = T.buffer_decl([112], \"uint8\", data=p3_data)\n            p4_data = T.allocate([32], \"uint8\", \"global\")\n            p4 = T.buffer_decl([32], \"uint8\", data=p4_data)\n            p5_data = T.allocate([32], \"uint8\", \"global\")\n            p5 = T.buffer_decl([32], \"uint8\", data=p5_data)\n            p6_data = T.allocate([32], \"uint8\", \"global\")\n            p6 = T.buffer_decl([32], \"uint8\", data=p6_data)\n            p7_data = T.allocate([112], \"uint8\", \"global\")\n            p7 = T.buffer_decl([112], \"uint8\", data=p7_data)\n            p8_data = T.allocate([3], \"uint8\", \"global\")\n            p8 = T.buffer_decl([3], \"uint8\", data=p8_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 112, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 112, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 32, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, 12, p5[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 112, p7[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer9[0], 32, p8[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 112, 12, p6[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p8[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(160,), \"uint8\"], buffer4: T.Buffer[(144,), \"uint8\"], buffer6: T.Buffer[(144,), \"uint8\"], buffer8: T.Buffer[(144,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p4_data = T.allocate([160], \"uint8\", \"global\")\n            p4 = T.buffer_decl([160], \"uint8\", data=p4_data)\n            p7_data = T.allocate([144], \"uint8\", \"global\")\n            p7 = T.buffer_decl([144], \"uint8\", data=p7_data)\n            p10_data = T.allocate([144], \"uint8\", \"global\")\n            p10 = T.buffer_decl([144], \"uint8\", data=p10_data)\n            p11_data = T.allocate([144], \"uint8\", \"global\")\n            p11 = T.buffer_decl([144], \"uint8\", data=p11_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 160, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 144, p7[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p4[0], 128, 12, p4[128], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 144, p10[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p7[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 144, p11[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p10[0], 112, 12, p10[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p11[0], 112, 12, p11[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {\n        0: np.array([0], dtype=np.uint8),\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n        3: np.array([3], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n        6: np.array([6], dtype=np.uint8),\n        7: np.array([7], dtype=np.uint8),\n    }\n    new_const_dict = {\n        0: np.concatenate((const_dict[0], const_dict[1])),\n        1: np.concatenate((const_dict[2], const_dict[3])),\n        2: np.concatenate((const_dict[4], const_dict[5])),\n        3: np.concatenate((const_dict[6], const_dict[7])),\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_operators_with_and_without_weights():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(80,), \"uint8\"], buffer3: T.Buffer[(64,), \"uint8\"]) -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer0 = T.buffer_decl([390336], \"int8\")\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer6 = T.buffer_decl([390336], \"int8\")\n            # body\n            p2_data = T.allocate([80], \"uint8\", \"global\")\n            p2 = T.buffer_decl([80], \"uint8\", data=p2_data)\n            p3_data = T.allocate([64], \"uint8\", \"global\")\n            p3 = T.buffer_decl([64], \"uint8\", data=p3_data)\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, buffer0[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 80, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 64, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, buffer0[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, buffer6[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p2[0], 80, 0, p3[0], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(144,), \"uint8\"]) -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer0 = T.buffer_decl([390336], \"int8\")\n            buffer1 = T.buffer_decl([97156], \"int8\")\n            buffer6 = T.buffer_decl([390336], \"int8\")\n            # body\n            p3_data = T.allocate([144], \"uint8\", \"global\")\n            p3 = T.buffer_decl([144], \"uint8\", data=p3_data)\n            T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 214, 227, 2, 214, 0, 227, buffer1[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 454, 2, 1, \"int8\", 214, 114, 2, 214, 0, 114, buffer0[0], 0, 0, 0, T.float32(1), 0, \"NHCWB16\", 1824, 16, 1, \"MAX\", 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 144, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 214, 114, 2, 214, 0, 114, buffer0[0], 0, 0, 0, T.float32(0.00392157), -128, \"NHCWB16\", 1824, 16, 1, \"int8\", 214, 114, 5, 214, 0, 114, buffer6[0], 0, 0, 0, T.float32(0.0174839), -128, \"NHCWB16\", 1824, 16, 1, 3, 1, 1, 1, 1, 2, p3[0], 80, 0, p3[80], 64, 0, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {\n        0: np.array([0], dtype=np.uint8),\n        1: np.array([1], dtype=np.uint8),\n    }\n    new_const_dict = {0: np.concatenate((const_dict[0], const_dict[1]))}\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_copy_to_buffer_with_local_scope():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer1: T.Buffer[(64,), \"uint8\"],\n        buffer2: T.Buffer[(48,), \"uint8\"],\n        buffer3: T.Buffer[(256,), \"uint8\"],\n        buffer4: T.Buffer[(256,), \"uint8\"],\n        buffer5: T.Buffer[(16,), \"uint8\"],\n        buffer6: T.Buffer[(48,), \"uint8\"],\n        buffer7: T.Buffer[(256,), \"uint8\"],\n        buffer8: T.Buffer[(64,), \"uint8\"],\n        buffer9: T.Buffer[(256,), \"int8\"],\n        ) -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([48], \"uint8\", \"global\")\n            p1 = T.buffer_decl([48], \"uint8\", data=p1_data)\n            p2_data = T.allocate([48], \"uint8\", \"global\")\n            p2 = T.buffer_decl([48], \"uint8\", data=p2_data)\n            p3_data = T.allocate([256], \"int8\", \"local\")\n            p3 = T.buffer_decl([256], \"int8\", data=p3_data, scope=\"local\")\n            p5_data = T.allocate([16], \"uint8\", \"global\")\n            p5 = T.buffer_decl([16], \"uint8\", data=p5_data)\n            p6_data = T.allocate([48], \"uint8\", \"global\")\n            p6 = T.buffer_decl([48], \"uint8\", data=p6_data)\n            p7_data = T.allocate([256], \"int8\", \"local\")\n            p7 = T.buffer_decl([256], \"int8\", data=p7_data, scope=\"local\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 48, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 48, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 256, p3[0], dtype=\"handle\")) # Local\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 16, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 48, p6[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer1[0], 0, 0, 0, T.float32(0.00392081), -128, \"NHWC\", 16, 4, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer9[0], 0, 0, 0, T.float32(0.00839574), -128, \"NHCWB16\", 64, 16, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, 0, p2[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 256, p7[0], dtype=\"handle\")) # Local\n            T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer9[0], 0, 0, 0, T.float32(0.0078125), 0, \"NHCWB16\", 64, 16, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer8[0], 0, 0, 0, T.float32(0.00372155), -128, \"NHWC\", 16, 4, 1, 1, 1, 1, 1, 1, 1, p5[0], 16, 0, p6[0], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer1: T.Buffer[(64,), \"uint8\"],\n            buffer2: T.Buffer[(96,), \"uint8\"],\n            buffer4: T.Buffer[(256,), \"uint8\"],\n            buffer5: T.Buffer[(64,), \"uint8\"],\n            buffer7: T.Buffer[(256,), \"uint8\"],\n            buffer8: T.Buffer[(64,), \"uint8\"],\n            buffer9: T.Buffer[(256,), \"int8\"],\n            ) -> None:\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([96], \"uint8\", \"global\")\n            p1 = T.buffer_decl([96], \"uint8\", data=p1_data)\n            p2_data = T.allocate([64], \"uint8\", \"global\")\n            p2 = T.buffer_decl([64], \"uint8\", data=p2_data)\n            p3_data = T.allocate([256], \"int8\", \"local\")\n            p3 = T.buffer_decl([256], \"int8\", data=p3_data, scope=\"local\")\n            p7_data = T.allocate([256], \"int8\", \"local\")\n            p7 = T.buffer_decl([256], \"int8\", data=p7_data, scope=\"local\")\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 96, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 256, p3[0], dtype=\"handle\")) # Local\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 64, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer1[0], 0, 0, 0, T.float32(0.00392081), -128, \"NHWC\", 16, 4, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer9[0], 0, 0, 0, T.float32(0.00839574), -128, \"NHCWB16\", 64, 16, 1, 1, 1, 1, 1, 1, 1, p1[0], 48, 0, p1[48], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 256, p7[0], dtype=\"handle\")) # Local\n            T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 4, 4, 4, 4, 0, 4, buffer9[0], 0, 0, 0, T.float32(0.0078125), 0, \"NHCWB16\", 64, 16, 1, \"int8\", 4, 4, 4, 4, 0, 4, buffer8[0], 0, 0, 0, T.float32(0.00372155), -128, \"NHWC\", 16, 4, 1, 1, 1, 1, 1, 1, 1, p2[0], 16, 0, p2[16], 48, 0, 0, 0, 0, \"TANH\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n        3: np.array([3], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n        6: np.array([6], dtype=np.uint8),\n    }\n    new_const_dict = {\n        1: np.concatenate((const_dict[1], const_dict[2])),\n        2: const_dict[3],\n        3: np.concatenate((const_dict[4], const_dict[5])),\n        4: const_dict[6],\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_no_copies():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main() -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            placeholder = T.buffer_decl([20], \"int8\")\n            ethosu_write = T.buffer_decl([16], \"int8\")\n            # body\n            ethosu_write_4_data = T.allocate([16], \"int8\", \"global\")\n            ethosu_write_4 = T.buffer_decl([16], \"int8\", data=ethosu_write_4_data)\n            T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 1, 4, 4, 1, 0, 4, placeholder[0], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 4, 1, \"int8\", 1, 4, 1, 1, 0, 4, placeholder[16], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 1, 1, \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write_4[0], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 4, 1, \"MAX\", 0, \"CLIP\", -128, 127, \"TFL\", 1, 4, 4, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main() -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            placeholder = T.buffer_decl([20], \"int8\")\n            ethosu_write = T.buffer_decl([16], \"int8\")\n            # body\n            ethosu_write_4_data = T.allocate([16], \"int8\", \"global\")\n            ethosu_write_4 = T.buffer_decl([16], \"int8\", data=ethosu_write_4_data)\n            T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 1, 4, 4, 1, 0, 4, placeholder[0], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 4, 1, \"int8\", 1, 4, 1, 1, 0, 4, placeholder[16], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 1, 1, \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write_4[0], 0, 0, 0, T.float32(0.00783747), -128, \"NHWC\", 1, 4, 1, \"MAX\", 0, \"CLIP\", -128, 127, \"TFL\", 1, 4, 4, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_identity\", \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write_4[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"int8\", 1, 4, 4, 1, 0, 4, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1, 4, 1, \"AVG\", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {}\n    new_const_dict = {}\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_copies_to_the_same_buffer():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(128,), \"uint8\"], buffer3: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1_data = T.allocate([128], \"uint8\", \"global\")\n            p1 = T.buffer_decl([128], \"uint8\", data=p1_data)\n            p4_data = T.allocate([32], \"uint8\", \"global\")\n            p4 = T.buffer_decl([32], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(160,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p5_data = T.allocate([160], \"uint8\", \"global\")\n            p5 = T.buffer_decl([160], \"uint8\", data=p5_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 160, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p5[0], 128, 12, p5[128], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 160, p5[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p5[0], 128, 12, p5[128], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {\n        0: np.array([0], dtype=np.uint8),\n        1: np.array([1], dtype=np.uint8),\n    }\n    new_const_dict = {0: np.concatenate((const_dict[0], const_dict[1]))}\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_read_from_the_same_buffer():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(368,), \"uint8\"], buffer2: T.Buffer[(96,), \"uint8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # buffer definition\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            p1_data = T.allocate([368], \"uint8\", \"global\")\n            p1 = T.buffer_decl([368], \"uint8\", data=p1_data)\n            p2_data = T.allocate([96], \"uint8\", \"global\")\n            p2 = T.buffer_decl([96], \"uint8\", data=p2_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 368, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 96, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p2[0], 48, p2[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        __tvm_meta__ = None\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(464,), \"uint8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([464], \"uint8\", \"global\")\n            p1 = T.buffer_decl([464], \"uint8\", data=p1_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 464, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p1[368], 48, p1[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n    # fmt: on\n\n    const_dict = {\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n    }\n    new_const_dict = {1: np.concatenate((const_dict[1], const_dict[2]))}\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_arbitrary_argument_order():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(368,), \"uint8\"], buffer2: T.Buffer[(96,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"], buffer3: T.Buffer[(368,), \"uint8\"], buffer4: T.Buffer[(96,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # buffer definition\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            p1_data = T.allocate([368], \"uint8\", \"global\")\n            p1 = T.buffer_decl([368], \"uint8\", data=p1_data)\n            p2_data = T.allocate([96], \"uint8\", \"global\")\n            p2 = T.buffer_decl([96], \"uint8\", data=p2_data)\n            p3_data = T.allocate([368], \"uint8\", \"global\")\n            p3 = T.buffer_decl([368], \"uint8\", data=p3_data)\n            p4_data = T.allocate([96], \"uint8\", \"global\")\n            p4 = T.buffer_decl([96], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 368, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 96, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p2[0], 48, p2[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 368, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 192, p3[192], 176, 12, p4[0], 48, p4[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        __tvm_meta__ = None\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(464,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"], buffer2: T.Buffer[(464,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([464], \"uint8\", \"global\")\n            p1 = T.buffer_decl([464], \"uint8\", data=p1_data)\n            p2_data = T.allocate([464], \"uint8\", \"global\")\n            p2 = T.buffer_decl([464], \"uint8\", data=p2_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 464, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p1[368], 48, p1[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 464, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 192, p2[192], 176, 12, p2[368], 48, p2[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n    # fmt: on\n\n    const_dict = {\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n    }\n    new_const_dict = {\n        1: np.concatenate((const_dict[1], const_dict[2])),\n        3: np.concatenate((const_dict[4], const_dict[5])),\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, False)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_arbitrary_argument_order_const_split():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(368,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"], buffer2: T.Buffer[(96,), \"uint8\"], buffer3: T.Buffer[(368,), \"uint8\"], buffer4: T.Buffer[(96,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # buffer definition\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            p1_data = T.allocate([368], \"uint8\", \"global\")\n            p1 = T.buffer_decl([368], \"uint8\", data=p1_data)\n            p2_data = T.allocate([96], \"uint8\", \"global\")\n            p2 = T.buffer_decl([96], \"uint8\", data=p2_data)\n            p3_data = T.allocate([368], \"uint8\", \"global\")\n            p3 = T.buffer_decl([368], \"uint8\", data=p3_data)\n            p4_data = T.allocate([96], \"uint8\", \"global\")\n            p4 = T.buffer_decl([96], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 368, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 96, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p2[0], 48, p2[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 368, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 192, p3[192], 176, 12, p4[0], 48, p4[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        __tvm_meta__ = None\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(464,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"], buffer2: T.Buffer[(464,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([464], \"uint8\", \"global\")\n            p1 = T.buffer_decl([464], \"uint8\", data=p1_data)\n            p2_data = T.allocate([464], \"uint8\", \"global\")\n            p2 = T.buffer_decl([464], \"uint8\", data=p2_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 464, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p1[368], 48, p1[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 464, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 192, p2[192], 176, 12, p2[368], 48, p2[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n    # fmt: on\n\n    const_dict = {\n        1: np.array([1], dtype=np.uint8),\n        3: np.array([3], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n    }\n    new_const_dict = {\n        1: np.concatenate((const_dict[1], const_dict[3])),\n        3: np.concatenate((const_dict[4], const_dict[5])),\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_arbitrary_argument_order_const_split_mixed():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(368,), \"uint8\"], buffer2: T.Buffer[(368,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"], buffer3: T.Buffer[(96,), \"uint8\"], buffer4: T.Buffer[(96,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # buffer definition\n            T.preflattened_buffer(placeholder, [1, 16, 16, 32], dtype=\"int8\", data=placeholder.data)\n            T.preflattened_buffer(ethosu_write, [1, 16, 16, 8], dtype=\"int8\", data=ethosu_write.data)\n            # body\n            p1_data = T.allocate([368], \"uint8\", \"global\")\n            p1 = T.buffer_decl([368], \"uint8\", data=p1_data)\n            p2_data = T.allocate([368], \"uint8\", \"global\")\n            p2 = T.buffer_decl([368], \"uint8\", data=p2_data)\n            p3_data = T.allocate([96], \"uint8\", \"global\")\n            p3 = T.buffer_decl([96], \"uint8\", data=p3_data)\n            p4_data = T.allocate([96], \"uint8\", \"global\")\n            p4 = T.buffer_decl([96], \"uint8\", data=p4_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 368, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 96, p3[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p3[0], 48, p3[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 368, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 96, p4[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 192, p2[192], 176, 12, p4[0], 48, p4[48], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        __tvm_meta__ = None\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(8192,), \"int8\"], buffer1: T.Buffer[(464,), \"uint8\"], buffer2: T.Buffer[(464,), \"uint8\"], ethosu_write: T.Buffer[(4096,), \"int8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            p1_data = T.allocate([464], \"uint8\", \"global\")\n            p1 = T.buffer_decl([464], \"uint8\", data=p1_data)\n            p2_data = T.allocate([464], \"uint8\", \"global\")\n            p2 = T.buffer_decl([464], \"uint8\", data=p2_data)\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 464, p1[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 192, p1[192], 176, 12, p1[368], 48, p1[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 464, p2[0], dtype=\"handle\"))\n            T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 8, 32, 16, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 8, 8, 16, 0, 8, ethosu_write[2048], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 192, p2[192], 176, 12, p2[368], 48, p2[416], 48, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n    # fmt: on\n\n    const_dict = {\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n    }\n    new_const_dict = {\n        1: np.concatenate((const_dict[1], const_dict[4])),\n        2: np.concatenate((const_dict[2], const_dict[5])),\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_cycle_count():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(128,), \"uint8\"], buffer3: T.Buffer[(32,), \"uint8\"], buffer4: T.Buffer[(112,), \"uint8\"], buffer5: T.Buffer[(32,), \"uint8\"], buffer6: T.Buffer[(112,), \"uint8\"], buffer7: T.Buffer[(32,), \"uint8\"], buffer8: T.Buffer[(112,), \"uint8\"], buffer9: T.Buffer[(32,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            v1a = T.var(\"int32\")\n            v1b = T.var(\"int32\")\n            v1c = T.var(\"int32\")\n            v2a = T.var(\"int32\")\n            v2b = T.var(\"int32\")\n            v2c = T.var(\"int32\")\n            v3a = T.var(\"int32\")\n            v3b = T.var(\"int32\")\n            v3c = T.var(\"int32\")\n            v4a = T.var(\"int32\")\n            v4b = T.var(\"int32\")\n            v4c = T.var(\"int32\")\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p1_data = T.allocate([128], \"uint8\", \"global\")\n            p1 = T.buffer_decl([128], \"uint8\", data=p1_data)\n            p2_data = T.allocate([112], \"uint8\", \"global\")\n            p2 = T.buffer_decl([112], \"uint8\", data=p2_data)\n            p3_data = T.allocate([112], \"uint8\", \"global\")\n            p3 = T.buffer_decl([112], \"uint8\", data=p3_data)\n            p4_data = T.allocate([32], \"uint8\", \"global\")\n            p4 = T.buffer_decl([32], \"uint8\", data=p4_data)\n            p5_data = T.allocate([32], \"uint8\", \"global\")\n            p5 = T.buffer_decl([32], \"uint8\", data=p5_data)\n            p6_data = T.allocate([32], \"uint8\", \"global\")\n            p6 = T.buffer_decl([32], \"uint8\", data=p6_data)\n            p7_data = T.allocate([112], \"uint8\", \"global\")\n            p7 = T.buffer_decl([112], \"uint8\", data=p7_data)\n            p8_data = T.allocate([3], \"uint8\", \"global\")\n            p8 = T.buffer_decl([3], \"uint8\", data=p8_data)\n            with T.attr(T.iter_var(v1a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 100):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 128, p1[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v1b, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 101):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 32, p4[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v2a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 102):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 112, p2[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v2b, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 103):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer5[0], 32, p5[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v1c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 300):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p1[0], 128, 12, p4[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v3a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 104):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 112, p3[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v3b, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 105):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer7[0], 32, p6[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v2c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 301):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p2[0], 112, 12, p5[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v4a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 106):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 112, p7[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v4b, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 107):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer9[0], 32, p8[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v3c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 302):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p3[0], 112, 12, p6[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v4c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 303):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p8[0], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n\n\n    @tvm.script.ir_module\n    class ReferenceModule:\n        @T.prim_func\n        def main(buffer2: T.Buffer[(160,), \"uint8\"], buffer4: T.Buffer[(144,), \"uint8\"], buffer6: T.Buffer[(144,), \"uint8\"], buffer8: T.Buffer[(144,), \"uint8\"]) -> None:\n            # function attr dict\n            T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n            v1a = T.var(\"int32\")\n            v1c = T.var(\"int32\")\n            v2a = T.var(\"int32\")\n            v2c = T.var(\"int32\")\n            v3a = T.var(\"int32\")\n            v3c = T.var(\"int32\")\n            v4a = T.var(\"int32\")\n            v4c = T.var(\"int32\")\n            buffer1 = T.buffer_decl([8192], \"int8\")\n            buffer10 = T.buffer_decl([2048], \"int8\")\n            # body\n            p4_data = T.allocate([160], \"uint8\", \"global\")\n            p4 = T.buffer_decl([160], \"uint8\", data=p4_data)\n            p7_data = T.allocate([144], \"uint8\", \"global\")\n            p7 = T.buffer_decl([144], \"uint8\", data=p7_data)\n            p10_data = T.allocate([144], \"uint8\", \"global\")\n            p10 = T.buffer_decl([144], \"uint8\", data=p10_data)\n            p11_data = T.allocate([144], \"uint8\", \"global\")\n            p11 = T.buffer_decl([144], \"uint8\", data=p11_data)\n            with T.attr(T.iter_var(v1a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 201):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer2[0], 160, p4[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v2a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 205):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer4[0], 144, p7[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v1c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 300):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p4[0], 128, 12, p4[128], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v3a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 209):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer6[0], 144, p10[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v2c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 301):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p7[0], 112, 12, p7[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v4a, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 213):\n                T.evaluate(T.call_extern(\"ethosu_copy\", buffer8[0], 144, p11[0], dtype=\"handle\"))\n            with T.attr(T.iter_var(v3c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 302):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p10[0], 112, 12, p10[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n            with T.attr(T.iter_var(v4c, None, \"DataPar\", \"\"), \"pragma_compute_cycles_hint\", 303):\n                T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, buffer1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, buffer10[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, p11[0], 112, 12, p11[112], 32, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    # fmt: on\n\n    const_dict = {\n        0: np.array([0], dtype=np.uint8),\n        1: np.array([1], dtype=np.uint8),\n        2: np.array([2], dtype=np.uint8),\n        3: np.array([3], dtype=np.uint8),\n        4: np.array([4], dtype=np.uint8),\n        5: np.array([5], dtype=np.uint8),\n        6: np.array([6], dtype=np.uint8),\n        7: np.array([7], dtype=np.uint8),\n    }\n    new_const_dict = {\n        0: np.concatenate((const_dict[0], const_dict[1])),\n        1: np.concatenate((const_dict[2], const_dict[3])),\n        2: np.concatenate((const_dict[4], const_dict[5])),\n        3: np.concatenate((const_dict[6], const_dict[7])),\n    }\n    test_mod, const_dict = MergeConstants(const_dict)(InputModule)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod, reference_mod, True)\n    check_const_dictionaries(const_dict, new_const_dict)\n\n\ndef test_multiple_prim_funcs():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def main():\n            T.evaluate(0)\n\n        @T.prim_func\n        def abc():\n            T.evaluate(0)\n    # fmt: on\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the MergeConstants pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        MergeConstants({})(InputModule)\n\n\ndef test_no_main_prim_func():\n    # fmt: off\n    @tvm.script.ir_module\n    class InputModule:\n        @T.prim_func\n        def abs():\n            T.evaluate(0)\n    # fmt: on\n\n    err_rgx = (\n        r\"Expected a single primitive function called 'main'. \"\n        r\"Please run the MergeConstants pass in conjunction with the LowerToTIR\\(\\) pass.\"\n    )\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        MergeConstants({})(InputModule)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_networks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument, wrong-import-position\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport numpy as np\n\nfrom tvm.relay.op.contrib.ethosu import partition_for_ethosu\nfrom tvm.micro import model_library_format as mlf\nfrom tvm import WorkspaceMemoryPools, WorkspacePoolInfo, PoolInfoProperties\nimport tvm\nfrom tvm.testing.aot import convert_to_relay\n\nfrom . import infra\n\n\nMOBILENET_V1_URL = (\n    \"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\",\n    \"mobilenet_v1_1.0_224_quant.tflite\",\n)\n\nMOBILENET_V2_URL = (\n    \"https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz\",\n    \"mobilenet_v2_1.0_224_quant.tflite\",\n)\n\n\n@pytest.mark.parametrize(\n    \"accel_type, model_url, workspace_size\",\n    [\n        (\"ethos-u65-256\", MOBILENET_V1_URL, 1793376),\n        (\"ethos-u65-256\", MOBILENET_V2_URL, 2217152),\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1793376),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 2217152),\n        (\"ethos-u55-128\", MOBILENET_V2_URL, 2217152),\n        (\"ethos-u55-64\", MOBILENET_V2_URL, 2217152),\n        (\"ethos-u55-32\", MOBILENET_V2_URL, 2217152),\n    ],\n)\ndef test_networks_without_usmp(accel_type, model_url, workspace_size):\n    np.random.seed(23)\n    tflite_model_buf = infra.get_tflite_model(model_url)\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_model_buf)\n    mod, params = convert_to_relay(tflite_model_buf)\n    mod = partition_for_ethosu(mod, params)\n    test_runner = infra.create_test_runner(accel_type, enable_usmp=False)\n    compiled_models = infra.build_source(mod, input_data, output_data, test_runner)\n    mlf_memory_map = mlf._build_function_memory_map(\n        compiled_models[0].executor_factory.function_metadata\n    )\n    assert mlf_memory_map[\"main\"][0][\"workspace_size_bytes\"] == workspace_size\n    infra.verify_source(compiled_models, test_runner)\n\n\n@pytest.mark.parametrize(\n    \"accel_type, model_url, workspace_size\",\n    [\n        (\"ethos-u65-256\", MOBILENET_V1_URL, 1206880),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1509408),\n    ],\n)\ndef test_networks_with_usmp(accel_type, model_url, workspace_size):\n    np.random.seed(23)\n    tflite_model_buf = infra.get_tflite_model(model_url)\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_model_buf)\n    mod, params = convert_to_relay(tflite_model_buf)\n    mod = partition_for_ethosu(mod, params)\n    test_runner = infra.create_test_runner(accel_type, enable_usmp=True)\n    compiled_models = infra.build_source(mod, input_data, output_data, test_runner)\n    allocated_pool_info = list(\n        dict(compiled_models[0].executor_factory.executor_codegen_metadata.pool_inputs).values()\n    )[0]\n    assert allocated_pool_info.allocated_size == workspace_size\n    infra.verify_source(compiled_models, test_runner)\n\n\n@pytest.mark.parametrize(\n    \"accel_type, model_url, workspace_size\",\n    [\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1205872),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1509408),\n    ],\n)\ndef test_networks_with_usmp_and_cascader_wo_striping(accel_type, model_url, workspace_size):\n    np.random.seed(23)\n\n    pool_name = \"my_memory_pool\"\n    host_target = tvm.target.Target(\"c\")\n    ethosu_target = tvm.target.Target(\"ethos-u\")\n    workspace_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                pool_name,\n                [host_target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=2400000,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            )\n        ]\n    )\n    tflite_model_buf = infra.get_tflite_model(model_url)\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_model_buf)\n    mod, params = convert_to_relay(tflite_model_buf)\n    mod = partition_for_ethosu(mod, params)\n    test_runner = infra.create_test_runner(\n        accel_type,\n        enable_usmp=True,\n        enable_cascader=True,\n        enable_striping=False,\n        workspace_pools=workspace_pools,\n    )\n    compiled_models = infra.build_source(\n        mod, input_data, output_data, test_runner, workspace_pools=workspace_pools\n    )\n    infra.verify_source(compiled_models, test_runner)\n\n    allocated_pool_info = list(\n        dict(compiled_models[0].executor_factory.executor_codegen_metadata.pool_inputs).values()\n    )[0]\n    assert allocated_pool_info.allocated_size == workspace_size\n\n\n@pytest.mark.parametrize(\n    \"accel_type, model_url, workspace_size\",\n    [\n        # Checks the same test case multiple times to make sure its not flaky\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1010000),\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1010000),\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1010000),\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1010000),\n        (\"ethos-u55-256\", MOBILENET_V1_URL, 1010000),\n        # Checks the same test case multiple times to make sure its not flaky\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1400000),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1400000),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1400000),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1400000),\n        (\"ethos-u55-256\", MOBILENET_V2_URL, 1400000),\n    ],\n)\ndef test_networks_with_usmp_and_cascader_with_striping(accel_type, model_url, workspace_size):\n    np.random.seed(23)\n\n    pool_name = \"my_memory_pool\"\n    host_target = tvm.target.Target(\"c\")\n    ethosu_target = tvm.target.Target(\"ethos-u\")\n    workspace_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                pool_name,\n                [host_target, ethosu_target],\n                PoolInfoProperties(\n                    size_hint_bytes=workspace_size,\n                    read_bandwidth_bytes_per_cycle=16,\n                    write_bandwidth_bytes_per_cycle=16,\n                    target_burst_bytes={ethosu_target: 1},\n                ),\n            )\n        ]\n    )\n    tflite_model_buf = infra.get_tflite_model(model_url)\n    input_data, output_data = infra.generate_ref_data_tflite(tflite_model_buf)\n    mod, params = convert_to_relay(tflite_model_buf)\n    mod = partition_for_ethosu(mod, params)\n    test_runner = infra.create_test_runner(\n        accel_type,\n        enable_usmp=True,\n        enable_cascader=True,\n        enable_striping=True,\n        workspace_pools=workspace_pools,\n    )\n    compiled_models = infra.build_source(\n        mod, input_data, output_data, test_runner, workspace_pools=workspace_pools\n    )\n    infra.verify_source(compiled_models, test_runner)\n\n    allocated_pool_info = list(\n        dict(compiled_models[0].executor_factory.executor_codegen_metadata.pool_inputs).values()\n    )[0]\n    assert allocated_pool_info.allocated_size <= workspace_size\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_outline_compiler_functions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTest the outline compiler functions pass.\n\"\"\"\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu.codegen import OutlineCompilerFunctions\n\n\ndef test_outline_compiler_functions():\n    compiler_name = \"my-compiler\"\n    wrong_compiler_name = \"wrong-compiler\"\n\n    def before():\n        inp = relay.var(\"input\")\n\n        # Inlined functions for \"my-compiler\"\n        x = relay.var(\"x\", shape=(1, 2, 2, 4))\n        x = relay.reshape(x, newshape=(1, 4, 4))\n        x = relay.Function(relay.analysis.free_vars(x), x)\n        x = x.with_attr(\"Compiler\", compiler_name)\n        x = x.with_attr(\"global_symbol\", \"ext_func\")\n\n        # Inlined function for \"wrong-compiler\"\n        y = relay.var(\"y\", shape=(1, 4, 4))\n        y = relay.reshape(y, newshape=(1, 16))\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        y = y.with_attr(\"Compiler\", wrong_compiler_name)\n        y = y.with_attr(\"global_symbol\", \"ext_func_2\")\n\n        out = relay.Call(x, [inp])\n        out = relay.Call(y, [out])\n        out = relay.Function([inp], out)\n        return tvm.ir.IRModule.from_expr(out)\n\n    def expected():\n        mod = tvm.ir.IRModule()\n\n        inp = relay.var(\"input\")\n\n        x = relay.var(\"x\", shape=(1, 2, 2, 4))\n        x = relay.reshape(x, newshape=(1, 4, 4))\n        x = relay.Function(relay.analysis.free_vars(x), x)\n        x = x.with_attr(\"Compiler\", compiler_name)\n        x = x.with_attr(\"global_symbol\", \"ext_func\")\n        mod[\"ext_func\"] = x\n\n        y = relay.var(\"y\", shape=(1, 4, 4))\n        y = relay.reshape(y, newshape=(1, 16))\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        y = y.with_attr(\"Compiler\", wrong_compiler_name)\n        y = y.with_attr(\"global_symbol\", \"ext_func_2\")\n\n        out = relay.Call(mod.get_global_var(\"ext_func\"), [inp])\n        out = relay.Call(y, [out])\n        mod[\"main\"] = relay.Function([inp], out)\n        return mod\n\n    after = OutlineCompilerFunctions(compiler_name)(before())\n    exp = expected()\n\n    global_vars = [str(gv) for gv in after.get_global_vars()]\n    assert \"@ext_func\" in global_vars\n    assert \"@ext_func_2\" not in global_vars\n    assert tvm.ir.structural_equal(after[\"ext_func\"], exp[\"ext_func\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_partition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=wrong-import-position\n\n\"\"\"\nTests to check that the NPU partitioning frontend partitions\nonly supported operations.\n\"\"\"\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.contrib import ethosu\n\n\n@pytest.mark.parametrize(\n    \"count_include_pad,pool_shape,padding\",\n    [\n        (True, [2, 2], [0, 0, 0, 0]),\n        (False, [2, 2], [4, 4, 5, 5]),\n        (False, [9, 9], [1, 1, 1, 1]),\n    ],\n)\ndef test_invalid_avg_pool2d(count_include_pad, pool_shape, padding):\n    \"\"\"\n    Test unsupported variants of avg_pool2d don't get partitioned.\n    \"\"\"\n    ifm_shape = [1, 4, 4, 3]\n    strides = [2, 2]\n\n    def get_graph():\n        x = relay.var(\"x\", shape=ifm_shape, dtype=\"int8\")\n        x = relay.cast(x, dtype=\"int32\")\n        x = relay.nn.avg_pool2d(\n            x,\n            pool_shape,\n            strides,\n            padding=padding,\n            layout=\"NHWC\",\n            count_include_pad=count_include_pad,\n        )\n        x = relay.cast(x, dtype=\"int8\")\n        func = relay.Function(relay.analysis.free_vars(x), x)\n        return tvm.IRModule.from_expr(func)\n\n    mod = relay.transform.InferType()(get_graph())\n    partitioned_mod = ethosu.partition_for_ethosu(mod)\n    assert tvm.ir.structural_equal(mod, partitioned_mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_placeholder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"This file contains a placeholder test that always run\"\"\"\n\n\ndef test_placeholder():\n    \"\"\"\n    This test always run on every docker image.\n    Otherwise, pytest will return exit code 5\n    and breaks CI in the docker images where\n    microNPU tests are not run.\n    \"\"\"\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_preprocess.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.contrib.ethosu import preprocess\n\n\ndef set_func_attr(func, compile_name, symbol_name):\n    \"\"\"\n    Helper function to attach attributes to the external function.\n    \"\"\"\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compile_name)\n    func = func.with_attr(\"global_symbol\", symbol_name)\n    return func\n\n\ndef test_single_io():\n    \"\"\"\n    This test will test the pass wont touch external functions that\n    have a single input and a single output.\n    \"\"\"\n\n    def create_graph():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            x_int = relay.var(\"x_int\", shape=(10, 10))\n            z0 = relay.nn.relu(x_int)\n            f1 = relay.Function([x_int], z0)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(10, 10))\n\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        r = relay.Call(glb_symbol_f1, [x])\n        main = relay.Function([x], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = create_graph()\n    exp = create_graph()\n    mod = preprocess.preprocess_ext_io()(mod)\n    assert tvm.ir.structural_equal(mod, exp, map_free_vars=True)\n\n\ndef test_2ins_single_out():\n    \"\"\"\n    The test is check two inputs and a single output of external function\n    \"\"\"\n\n    def create_graph():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            x_int = relay.var(\"x_int\", shape=(10, 10))\n            w0_int = relay.var(\"w0_int\", shape=(10, 10))\n            z0 = relay.add(x_int, w0_int)\n\n            f1 = relay.Function([x_int, w0_int], z0)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n\n        x = relay.var(\"x\", shape=(10, 10))\n        w0 = relay.var(\"w0\", shape=(10, 10))\n\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        r = relay.Call(glb_symbol_f1, [x, w0])\n        main = relay.Function([x, w0], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    def expected():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            ifms_int = relay.var(\"ifms_int\", shape=[200])\n\n            # splits\n            (x_int_flat, w0_int_flat) = relay.split(ifms_int, [100])\n            # reshapes\n            x_int = relay.reshape(x_int_flat, newshape=(10, 10))\n            w0_int = relay.reshape(w0_int_flat, newshape=(10, 10))\n\n            z0 = relay.add(x_int, w0_int)\n            f1 = relay.Function([ifms_int], z0)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n\n        x = relay.var(\"x\", shape=(10, 10))\n        w0 = relay.var(\"w0\", shape=(10, 10))\n\n        # reshapes\n        x_reshaped = relay.reshape(x, newshape=100)\n        w0_reshaped = relay.reshape(w0, newshape=100)\n\n        # concat\n        ifms = relay.concatenate((x_reshaped, w0_reshaped), 0)\n\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        r = relay.Call(glb_symbol_f1, [ifms])\n        main = relay.Function([x, w0], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = create_graph()\n    exp = expected()\n    mod = preprocess.preprocess_ext_io()(mod)\n    assert tvm.ir.structural_equal(mod, exp, map_free_vars=True)\n\n\ndef test_single_in_2outs():\n    \"\"\"\n    The test is to check a single input and two outputs of external function\n    \"\"\"\n\n    def create_graph():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            x_int = relay.var(\"x_int\", shape=(10, 10))\n\n            p0 = relay.nn.relu(x_int)\n            q0 = relay.tanh(x_int)\n            f1_o_tuple = relay.Tuple([p0, q0])\n\n            f1 = relay.Function([x_int], f1_o_tuple)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(10, 10))\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        pq_tuple = relay.Call(glb_symbol_f1, [x])\n        p0 = relay.TupleGetItem(pq_tuple, 0)\n        q0 = relay.TupleGetItem(pq_tuple, 1)\n        r = relay.concatenate((p0, q0), axis=0)\n        main = relay.Function([x], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    def expected():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            x_int = relay.var(\"x_int\", shape=(10, 10))\n\n            p0 = relay.nn.relu(x_int)\n            q0 = relay.tanh(x_int)\n\n            # reshapes\n            p0_reshaped = relay.reshape(p0, newshape=100)\n            q0_reshaped = relay.reshape(q0, newshape=100)\n            ofms = relay.concatenate((p0_reshaped, q0_reshaped), 0)\n\n            f1 = relay.Function([x_int], ofms)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(10, 10))\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        ofms = relay.Call(glb_symbol_f1, [x])\n\n        # splits\n        (p0_flat, q0_flat) = relay.split(ofms, [100])\n        # reshapes\n        p0_flat_reshaped = relay.reshape(p0_flat, newshape=(10, 10))\n        q0_flat_reshaped = relay.reshape(q0_flat, newshape=(10, 10))\n        # original output\n        tuple_out = relay.Tuple([p0_flat_reshaped, q0_flat_reshaped])\n\n        p0 = relay.TupleGetItem(tuple_out, 0)\n        q0 = relay.TupleGetItem(tuple_out, 1)\n        r = relay.concatenate((p0, q0), axis=0)\n        main = relay.Function([x], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = create_graph()\n    exp = expected()\n    mod = relay.transform.InferType()(mod)\n    mod = preprocess.preprocess_ext_io()(mod)\n    assert tvm.ir.structural_equal(mod, exp, map_free_vars=True)\n\n\ndef test_4ins_2outs():\n    \"\"\"\n    The test is to check a 4 inputs and two outputs of external function.\n    This just stand as a general test for multiple ins/outs.\n    \"\"\"\n\n    def create_graph():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            x_int = relay.var(\"x_int\", shape=(10, 10))\n            w0_int = relay.var(\"w0_int\", shape=(10, 10))\n            w1_int = relay.var(\"w1_int\", shape=(10, 10))\n            w2_int = relay.var(\"w2_int\", shape=(10, 10))\n\n            z0 = relay.add(x_int, w0_int)\n            p0 = relay.subtract(z0, w1_int)\n            q0 = relay.multiply(z0, w2_int)\n            f1_o_tuple = relay.Tuple([p0, q0])\n\n            f1 = relay.Function([x_int, w0_int, w1_int, w2_int], f1_o_tuple)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n\n        x = relay.var(\"x\", shape=(10, 10))\n        w0 = relay.var(\"w0\", shape=(10, 10))\n        w1 = relay.var(\"w1\", shape=(10, 10))\n        w2 = relay.var(\"w2\", shape=(10, 10))\n\n        glb_symbol_f1, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        pq_tuple = relay.Call(glb_symbol_f1, [x, w0, w1, w2])\n\n        p0 = relay.TupleGetItem(pq_tuple, 0)\n        q0 = relay.TupleGetItem(pq_tuple, 1)\n        r = relay.concatenate((p0, q0), axis=0)\n        main = relay.Function([x, w0, w1, w2], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    def expected():\n        def create_external_func1(mod_, compiler_name, symbol_name):\n            ifms_int = relay.var(\"ifms_int\", shape=[400])\n\n            # splits\n            (x_int_flat, w0_int_flat, w1_int_flat, w2_int_flat) = relay.split(\n                ifms_int, [100, 200, 300]\n            )\n            # reshapes\n            x_int = relay.reshape(x_int_flat, newshape=(10, 10))\n            w0_int = relay.reshape(w0_int_flat, newshape=(10, 10))\n            w1_int = relay.reshape(w1_int_flat, newshape=(10, 10))\n            w2_int = relay.reshape(w2_int_flat, newshape=(10, 10))\n\n            z0 = relay.add(x_int, w0_int)\n            p0 = relay.subtract(z0, w1_int)\n            q0 = relay.multiply(z0, w2_int)\n            # f1_o_tuple = relay.Tuple([p0, q0])\n\n            # reshapes\n            p0_reshaped = relay.reshape(p0, newshape=100)\n            q0_reshaped = relay.reshape(q0, newshape=100)\n            ofms = relay.concatenate((p0_reshaped, q0_reshaped), 0)\n\n            f1 = relay.Function([ifms_int], ofms)\n            f1 = set_func_attr(f1, compiler_name, symbol_name)\n            glb_f1 = relay.GlobalVar(symbol_name)\n            mod_[glb_f1] = f1\n            mod_ = relay.transform.InferType()(mod_)\n            return glb_f1, mod_\n\n        mod = tvm.IRModule()\n\n        x = relay.var(\"x\", shape=(10, 10))\n        w0 = relay.var(\"w0\", shape=(10, 10))\n        w1 = relay.var(\"w1\", shape=(10, 10))\n        w2 = relay.var(\"w2\", shape=(10, 10))\n\n        # reshapes\n        x_reshaped = relay.reshape(x, newshape=100)\n        w0_reshaped = relay.reshape(w0, newshape=100)\n        w1_reshaped = relay.reshape(w1, newshape=100)\n        w2_reshaped = relay.reshape(w2, newshape=100)\n\n        # concat\n        ifms = relay.concatenate((x_reshaped, w0_reshaped, w1_reshaped, w2_reshaped), 0)\n\n        # call\n        glb_func, mod = create_external_func1(mod, \"ethos-u\", \"ethosu_0\")\n        ofms = relay.Call(glb_func, [ifms])\n\n        # splits\n        (p0_flat, q0_flat) = relay.split(ofms, [100])\n        # reshapes\n        p0_flat_reshaped = relay.reshape(p0_flat, newshape=(10, 10))\n        q0_flat_reshaped = relay.reshape(q0_flat, newshape=(10, 10))\n        # original output\n        tuple_out = relay.Tuple([p0_flat_reshaped, q0_flat_reshaped])\n\n        p0 = relay.TupleGetItem(tuple_out, 0)\n        q0 = relay.TupleGetItem(tuple_out, 1)\n\n        r = relay.concatenate((p0, q0), axis=0)\n        main = relay.Function([x, w0, w1, w2], r)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = create_graph()\n    exp = expected()\n    mod = preprocess.preprocess_ext_io()(mod)\n    assert tvm.ir.structural_equal(mod, exp, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_remove_concatenates.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nimport tvm.script\nfrom tvm.script import tir as T\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_conv2d\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ReferenceModule:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(1536,), \"int8\"], placeholder_1: T.Buffer[(1280,), \"int8\"], T_concat: T.Buffer[(4096,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([2992], \"uint8\")\n        buffer_1 = T.buffer_decl([160], \"uint8\")\n        buffer_2 = T.buffer_decl([2992], \"uint8\")\n        buffer_3 = T.buffer_decl([160], \"uint8\")\n        buffer_4 = T.buffer_decl([2992], \"uint8\")\n        buffer_5 = T.buffer_decl([160], \"uint8\")\n        buffer_6 = T.buffer_decl([2992], \"uint8\")\n        buffer_7 = T.buffer_decl([160], \"uint8\")\n        # body\n        T_concat_1_data = T.allocate([2816], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        T_concat_1 = T.buffer_decl([2816], \"int8\", data=T_concat_1_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 10, 16, 8, 0, 10, placeholder_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 160, 16, 1, \"int8\", 8, 10, 16, 8, 0, 10, T_concat_1[192], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 352, 16, 1, 3, 3, 1, 1, 1, 1, buffer[0], 2992, T.int8(-1), T.int8(-1), 12, buffer_1[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 10, 16, 8, 0, 10, T_concat_1[192], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 352, 16, 1, \"int8\", 8, 10, 16, 8, 0, 10, T_concat[352], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 512, 16, 1, 3, 3, 1, 1, 1, 1, buffer_2[0], 2992, T.int8(-1), T.int8(-1), 12, buffer_3[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 12, 16, 8, 0, 12, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 192, 16, 1, \"int8\", 8, 12, 16, 8, 0, 12, T_concat_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 352, 16, 1, 3, 3, 1, 1, 1, 1, buffer_4[0], 2992, T.int8(-1), T.int8(-1), 12, buffer_5[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 22, 16, 8, 0, 22, T_concat_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 352, 16, 1, \"int8\", 8, 22, 16, 8, 0, 22, T_concat[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 512, 16, 1, 3, 3, 1, 1, 1, 1, buffer_6[0], 2992, T.int8(-1), T.int8(-1), 12, buffer_7[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_concat():\n    def _get_func():\n        ifm1 = relay.var(\"ifm1\", shape=(1, 8, 12, 16), dtype=\"int8\")\n        ifm2 = relay.var(\"ifm2\", shape=(1, 8, 10, 16), dtype=\"int8\")\n        conv1 = make_ethosu_conv2d(ifm1, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))\n        conv2 = make_ethosu_conv2d(ifm2, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))\n        conc1 = relay.concatenate((conv1, conv2), axis=2)\n        conv3 = make_ethosu_conv2d(conc1, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))\n        conv4 = make_ethosu_conv2d(conv2, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))\n        conc2 = relay.concatenate((conv3, conv4), axis=2)\n        func = relay.Function(relay.analysis.free_vars(conc2), conc2)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func = _get_func()\n    mod, _ = _lower_to_tir(func)\n    script = mod.script(show_meta=True)\n    test_mod = tvm.script.from_source(script)\n\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_binary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir import spec\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_binary_elementwise, get_binary_elementwise_args\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape, ifm_channels, ifm2_channels, ifm_layout, ofm_layout, rounding_mode\",\n    [\n        ((1, 5, 9, 3), (1, 5, 9, 3), 3, 3, \"NHWC\", \"NHWC\", \"TFL\"),\n        ((1, 8, 3, 9, 16), (1, 8, 3, 9, 16), 40, 40, \"NHCWB16\", \"NHCWB16\", \"NATURAL\"),\n        ((1, 8, 3, 9, 16), (1, 8, 3, 9, 16), 40, 40, \"NHCWB16\", \"NHWC\", \"TRUNCATE\"),\n        ((1, 8, 9, 40), (1, 8, 9, 40), 40, 40, \"NHWC\", \"NHCWB16\", \"TFL\"),\n        # Broadcast\n        ((1, 5, 9, 3), (1, 1, 9, 1), 3, 1, \"NHWC\", \"NHWC\", \"NATURAL\"),\n        ((1, 8, 9, 40), (1, 1, 1, 1), 40, 1, \"NHWC\", \"NHCWB16\", \"TRUNCATE\"),\n    ],\n)\n@pytest.mark.parametrize(\"operator_type\", [\"ADD\", \"SUB\", \"MUL\", \"MIN\", \"MAX\"])\n@pytest.mark.parametrize(\"activation\", [\"NONE\", \"CLIP\"])\ndef test_binary_elementwise_single(\n    ifm_shape,\n    ifm2_shape,\n    ifm_channels,\n    ifm2_channels,\n    ifm_layout,\n    ofm_layout,\n    rounding_mode,\n    operator_type,\n    activation,\n):\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm2_shape, dtype=dtype)\n\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        dtype,\n        False,\n        activation,\n        ifm_layout,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n    )\n    func = relay.Function(relay.analysis.free_vars(binary_elementwise), binary_elementwise)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_binary_elementwise_args(stmt))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3] if ifm_shape[2] != 1 else 1\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3] if ifm_shape[1] != 1 else 1\n\n        ifm2_stride_c = 1\n        ifm2_stride_w = ifm2_shape[3] if ifm2_shape[2] != 1 else 1\n        ifm2_stride_h = ifm2_shape[2] * ifm2_shape[3] if ifm2_shape[1] != 1 else 1\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[2]\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3]\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n\n        ifm2_stride_w = 16\n        ifm2_stride_c = 16 * ifm2_shape[3]\n        ifm2_stride_h = 16 * ifm2_shape[2] * ifm2_shape[3]\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[3]\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = ifm_channels if ofm_width > 1 else 1\n        ofm_stride_h = ifm_channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width\n        ofm_stride_h = 16 * ofm_width * ((ifm_channels - 1) // 16 + 1)\n\n    serial_binary_elementwise = spec.SerialBinaryElementwise(\n        ifm=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ifm_shape[1],\n            width=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            channels=ifm_channels,\n            tile_height_0=ifm_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm_stride_h,\n            stride_w=ifm_stride_w,\n            stride_c=ifm_stride_c,\n        ),\n        ifm2=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ifm2_shape[1],\n            width=ifm2_shape[2] if ifm_layout == \"NHWC\" else ifm2_shape[3],\n            channels=ifm2_channels,\n            tile_height_0=ifm2_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm2_shape[2] if ifm_layout == \"NHWC\" else ifm2_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm2_stride_h,\n            stride_w=ifm2_stride_w,\n            stride_c=ifm2_stride_c,\n        ),\n        ofm=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ofm_height,\n            width=ofm_width,\n            channels=ifm_channels,\n            tile_height_0=ofm_height,\n            tile_height_1=0,\n            tile_width_0=ofm_width,\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ofm_layout,\n            stride_h=ofm_stride_h,\n            stride_w=ofm_stride_w,\n            stride_c=ofm_stride_c,\n        ),\n        operator_type=operator_type,\n        reversed_operands=False,\n        activation=spec.SerialActivation(\n            op=activation,\n            clip_min=10 if activation == \"CLIP\" else 0,\n            clip_max=100 if activation == \"CLIP\" else 0,\n        ),\n        rounding_mode=rounding_mode,\n        block_config=spec.SerialBlockConfig(0, 0, 0),\n    )\n\n    assert data[0] == [\"ethosu_binary_elementwise\"] + list(serial_binary_elementwise)\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm2_shape, ifm_channels, ifm2_channels, ifm_layout, ofm_layout\",\n    [\n        ((1, 5, 9, 3), (1, 5, 9, 3), 3, 3, \"NHWC\", \"NHWC\"),\n        ((1, 8, 3, 9, 16), (1, 8, 3, 9, 16), 40, 40, \"NHCWB16\", \"NHCWB16\"),\n        ((1, 8, 3, 9, 16), (1, 8, 3, 9, 16), 40, 40, \"NHCWB16\", \"NHWC\"),\n        ((1, 8, 9, 40), (1, 8, 9, 40), 40, 40, \"NHWC\", \"NHCWB16\"),\n        # Broadcast\n        ((1, 5, 9, 3), (1, 1, 9, 1), 3, 1, \"NHWC\", \"NHWC\"),\n        ((1, 8, 9, 40), (1, 1, 1, 1), 40, 1, \"NHWC\", \"NHCWB16\"),\n    ],\n)\n@pytest.mark.parametrize(\"operator_type\", [\"SHR\", \"SHL\"])\n@pytest.mark.parametrize(\"rounding_mode\", [\"TFL\", \"NATURAL\", \"TRUNCATE\"])\ndef test_shift_binary_elementwise_single(\n    ifm_shape,\n    ifm2_shape,\n    ifm_channels,\n    ifm2_channels,\n    ifm_layout,\n    ofm_layout,\n    operator_type,\n    rounding_mode,\n):\n    dtype = \"int32\"\n    activation = \"NONE\"  # Only NONE is available if the activation type is int32\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm2_shape, dtype=dtype)\n\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        dtype,\n        False,\n        \"NONE\",\n        ifm_layout,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n    )\n    func = relay.Function(relay.analysis.free_vars(binary_elementwise), binary_elementwise)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_binary_elementwise_args(stmt))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3] if ifm_shape[2] != 1 else 1\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3] if ifm_shape[1] != 1 else 1\n\n        ifm2_stride_c = 1\n        ifm2_stride_w = ifm2_shape[3] if ifm2_shape[2] != 1 else 1\n        ifm2_stride_h = ifm2_shape[2] * ifm2_shape[3] if ifm2_shape[1] != 1 else 1\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[2]\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3]\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n\n        ifm2_stride_w = 16\n        ifm2_stride_c = 16 * ifm2_shape[3]\n        ifm2_stride_h = 16 * ifm2_shape[2] * ifm2_shape[3]\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[3]\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = ifm_channels if ofm_width > 1 else 1\n        ofm_stride_h = ifm_channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width\n        ofm_stride_h = 16 * ofm_width * ((ifm_channels - 1) // 16 + 1)\n\n    serial_binary_elementwise = spec.SerialBinaryElementwise(\n        ifm=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ifm_shape[1],\n            width=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            channels=ifm_channels,\n            tile_height_0=ifm_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm_stride_h,\n            stride_w=ifm_stride_w,\n            stride_c=ifm_stride_c,\n        ),\n        ifm2=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ifm2_shape[1],\n            width=ifm2_shape[2] if ifm_layout == \"NHWC\" else ifm2_shape[3],\n            channels=ifm2_channels,\n            tile_height_0=ifm2_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm2_shape[2] if ifm_layout == \"NHWC\" else ifm2_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm2_stride_h,\n            stride_w=ifm2_stride_w,\n            stride_c=ifm2_stride_c,\n        ),\n        ofm=spec.SerialFeatureMap(\n            data_type=dtype,\n            height=ofm_height,\n            width=ofm_width,\n            channels=ifm_channels,\n            tile_height_0=ofm_height,\n            tile_height_1=0,\n            tile_width_0=ofm_width,\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ofm_layout,\n            stride_h=ofm_stride_h,\n            stride_w=ofm_stride_w,\n            stride_c=ofm_stride_c,\n        ),\n        operator_type=operator_type,\n        reversed_operands=False,\n        activation=spec.SerialActivation(\n            op=activation,\n            clip_min=0,\n            clip_max=0,\n        ),\n        rounding_mode=rounding_mode,\n        block_config=spec.SerialBlockConfig(0, 0, 0),\n    )\n\n    assert data[0] == [\"ethosu_binary_elementwise\"] + list(serial_binary_elementwise)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import total_cascader\nfrom .infra import make_ethosu_conv2d\n\n\ndef _create_serial_conv2d_params(\n    ifm_shape,\n    ifm_channels,\n    ofm_channels,\n    kernel_shape,\n    padding,\n    strides,\n    dilation,\n    activation=\"NONE\",\n    ifm_layout=\"NHWC\",\n    ofm_layout=\"NHWC\",\n    rounding_mode=\"TFL\",\n    upscale=\"NONE\",\n):\n    dtype = \"int8\"\n    dilated_kernel_h = (kernel_shape[0] - 1) * dilation[0] + 1\n    dilated_kernel_w = (kernel_shape[1] - 1) * dilation[1] + 1\n    upscale_factor = 2 if upscale != \"NONE\" else 1\n\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3]\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3]\n        ofm_height = (\n            ifm_shape[1] * upscale_factor - dilated_kernel_h + padding[0] + padding[2]\n        ) // strides[0] + 1\n        ofm_width = (\n            ifm_shape[2] * upscale_factor - dilated_kernel_w + padding[1] + padding[3]\n        ) // strides[1] + 1\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3]\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n        ofm_height = (\n            ifm_shape[1] * upscale_factor - dilated_kernel_h + padding[0] + padding[2]\n        ) // strides[0] + 1\n        ofm_width = (\n            ifm_shape[3] * upscale_factor - dilated_kernel_w + padding[1] + padding[3]\n        ) // strides[1] + 1\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = ofm_channels if ofm_width > 1 else 1\n        ofm_stride_h = ofm_channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width\n        ofm_stride_h = 16 * ofm_width * ((ofm_channels - 1) // 16 + 1)\n\n    return [\n        dtype,\n        ifm_shape[1],\n        ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n        ifm_channels,\n        ifm_shape[1],\n        0,\n        ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n        0,\n        0,\n        0,\n        0,\n        0.5,\n        10,\n        ifm_layout,\n        ifm_stride_h,\n        ifm_stride_w,\n        ifm_stride_c,\n        dtype,\n        ofm_height,\n        ofm_width,\n        ofm_channels,\n        ofm_height,\n        0,\n        ofm_width,\n        0,\n        0,\n        0,\n        0,\n        0.25,\n        14,\n        ofm_layout,\n        ofm_stride_h,\n        ofm_stride_w,\n        ofm_stride_c,\n        kernel_shape[1],\n        kernel_shape[0],\n        strides[1],\n        strides[0],\n        dilation[1],\n        dilation[0],\n        12,\n        padding[0],\n        padding[1],\n        padding[2],\n        padding[3],\n        activation,\n        10 if activation == \"CLIP\" else 0,\n        100 if activation == \"CLIP\" else 0,\n        rounding_mode,\n        upscale,\n        0,\n        0,\n        0,\n    ]\n\n\ndef get_conv2d_args(call, include_buffers=False, remove_constants=False):\n    \"\"\"A method to extract the arguments from conv2d extern call.\"\"\"\n    args = call.args\n    conv_args = []\n    remove_indices = [0]\n\n    # call.args[41]: BufferLoad for the first half of the weights\n    # call.args[42]: length of the load of the first half of the weights\n    # call.args[43]: BufferLoad for the second half of the weights\n    # call.args[44]: length of the load of the second half of the weights\n    # call.args[46]: BufferLoad for the first half of the bias\n    # call.args[47]: length of the load of the first half of the bias\n    # call.args[48]: BufferLoad for the second half of the bias\n    # call.args[49]: length of the load of the second half of the bias\n    if remove_constants:\n        remove_indices += [41, 42, 43, 44, 46, 47, 48, 49]\n\n    for i, arg in enumerate(args):\n        if i in remove_indices:\n            continue\n        elif isinstance(arg, tvm.tir.expr.IntImm) or isinstance(arg, tvm.tir.expr.FloatImm):\n            conv_args.append(arg.value)\n        elif isinstance(arg, tvm.tir.expr.BufferLoad) and not include_buffers:\n            conv_args.append(arg.indices[0])\n        else:\n            conv_args.append(arg)\n\n    return conv_args\n\n\n@pytest.mark.parametrize(\n    \"trial\",\n    [\n        [\n            (1, 8, 8, 3),\n            3,\n            16,\n            (1, 1),\n            (2, 1, 2, 1),\n            (1, 1),\n            (1, 1),\n            \"CLIP\",\n            \"NHWC\",\n            \"NHWC\",\n            \"TFL\",\n            \"NONE\",\n        ],\n        [\n            (1, 8, 8, 3),\n            3,\n            16,\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            (1, 1),\n            \"NONE\",\n            \"NHWC\",\n            \"NHWC\",\n            \"NATURAL\",\n            \"NONE\",\n        ],\n        [\n            (1, 1, 1, 1),\n            1,\n            16,\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            (1, 1),\n            \"CLIP\",\n            \"NHWC\",\n            \"NHWC\",\n            \"TRUNCATE\",\n            \"NONE\",\n        ],\n        [\n            (1, 7, 9, 4),\n            4,\n            13,\n            (3, 2),\n            (1, 2, 1, 2),\n            (2, 1),\n            (1, 2),\n            \"NONE\",\n            \"NHWC\",\n            \"NHWC\",\n            \"TFL\",\n            \"NONE\",\n        ],\n        [\n            (1, 8, 2, 8, 16),\n            18,\n            12,\n            (1, 1),\n            (2, 1, 2, 1),\n            (1, 1),\n            (1, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHWC\",\n            \"NATURAL\",\n            \"ZEROS\",\n        ],\n        [\n            (1, 7, 9, 4),\n            4,\n            71,\n            (3, 2),\n            (1, 2, 0, 2),\n            (2, 1),\n            (1, 2),\n            \"CLIP\",\n            \"NHWC\",\n            \"NHCWB16\",\n            \"TRUNCATE\",\n            \"ZEROS\",\n        ],\n        [\n            (1, 4, 12, 9, 16),\n            182,\n            67,\n            (2, 3),\n            (6, 3, 6, 2),\n            (2, 2),\n            (1, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHCWB16\",\n            \"TFL\",\n            \"ZEROS\",\n        ],\n        [\n            (1, 7, 9, 4),\n            4,\n            13,\n            (3, 2),\n            (1, 2, 0, 3),\n            (2, 1),\n            (2, 2),\n            \"CLIP\",\n            \"NHWC\",\n            \"NHWC\",\n            \"NATURAL\",\n            \"NEAREST\",\n        ],\n        [\n            (1, 7, 9, 4),\n            4,\n            71,\n            (3, 2),\n            (1, 2, 0, 2),\n            (2, 1),\n            (2, 2),\n            \"CLIP\",\n            \"NHWC\",\n            \"NHCWB16\",\n            \"TRUNCATE\",\n            \"NEAREST\",\n        ],\n        [\n            (1, 13, 12, 19, 16),\n            182,\n            67,\n            (1, 3),\n            (5, 3, 2, 3),\n            (2, 1),\n            (2, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHCWB16\",\n            \"TFL\",\n            \"NEAREST\",\n        ],\n    ],\n)\ndef test_conv2d_single(trial):\n    def _get_func(\n        ifm_shape,\n        ifm_channels,\n        ofm_channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        activation,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n        upscale,\n    ):\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            ifm,\n            ifm_channels,\n            ofm_channels,\n            kernel_shape,\n            padding,\n            strides,\n            dilation,\n            activation=activation,\n            ifm_layout=ifm_layout,\n            ofm_layout=ofm_layout,\n            rounding_mode=rounding_mode,\n            upscale=upscale,\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    # TODO(@mbaret) Fix the tests for these known failures\n    # These are anticipated to actually be correct, just a testing issue to do with\n    # equivalent convolutions.\n    known_failures = [\n        [(1, 3, 12, 9, 16), 182, 67, (2, 3), (1, 3), (2, 2), (1, 1), \"CLIP\", \"NHCWB16\", \"NHCWB16\"],\n        [(1, 2, 12, 9, 16), 182, 67, (1, 3), (6, 3), (2, 2), (1, 1), \"CLIP\", \"NHCWB16\", \"NHCWB16\"],\n    ]\n    func = _get_func(*trial)\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_conv2d_args(stmt, remove_constants=True))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n\n    answer = _create_serial_conv2d_params(*trial)\n    assert data[0] == answer, data[0]\n\n\n# fmt: off\n@tvm.script.ir_module\nclass Conv2dDoubleCascade1:\n    @T.prim_func\n    def main(placeholder_5: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(512,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([304], \"uint8\")\n        buffer_1 = T.buffer_decl([80], \"uint8\")\n        buffer_2 = T.buffer_decl([320], \"uint8\")\n        buffer_3 = T.buffer_decl([160], \"uint8\")\n        # body\n        ethosu_write_2_data = T.allocate([1024], \"int8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        ethosu_write_2 = T.buffer_decl([1024], \"int8\", data=ethosu_write_2_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 4, 3, 8, 0, 4, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 8, 4, 32, 8, 0, 4, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 32, 1, 1, 1, 1, 1, 1, 1, buffer_3[0], 160, T.int8(-1), T.int8(-1), 12, buffer_2[0], 320, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 4, 32, 8, 0, 4, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 128, 32, 1, \"int8\", 8, 4, 8, 8, 0, 4, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 1, 1, 1, 1, 1, 1, buffer[0], 304, T.int8(-1), T.int8(-1), 12, buffer_1[0], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 4, 3, 8, 0, 4, placeholder_5[12], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 8, 4, 32, 8, 0, 4, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 32, 1, 1, 1, 1, 1, 1, 1, buffer_3[0], 160, T.int8(-1), T.int8(-1), 12, buffer_2[0], 320, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 4, 32, 8, 0, 4, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 128, 32, 1, \"int8\", 8, 4, 8, 8, 0, 4, ethosu_write_1[32], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 1, 1, 1, 1, 1, 1, buffer[0], 304, T.int8(-1), T.int8(-1), 12, buffer_1[0], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dDoubleCascade2:\n    @T.prim_func\n    def main(placeholder_5: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(512,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([80], \"uint8\")\n        buffer_1 = T.buffer_decl([320], \"uint8\")\n        buffer_2 = T.buffer_decl([1312], \"uint8\")\n        buffer_3 = T.buffer_decl([2608], \"uint8\")\n        # body\n        ethosu_write_2_data = T.allocate([1536], \"int8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        ethosu_write_2 = T.buffer_decl([1536], \"int8\", data=ethosu_write_2_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 6, 8, 3, 6, 0, 8, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 5, 8, 32, 5, 0, 8, ethosu_write_2[256], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 3, 3, 1, 1, 1, 1, buffer_2[0], 1312, T.int8(-1), T.int8(-1), 12, buffer_1[0], 320, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 8, 32, 5, 0, 8, ethosu_write_2[256], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"int8\", 4, 8, 8, 4, 0, 8, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 3, 3, 1, 1, 1, 1, buffer_3[0], 2608, T.int8(-1), T.int8(-1), 12, buffer[0], 80, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 6, 8, 3, 6, 0, 8, placeholder_5[48], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 5, 8, 32, 5, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 3, 3, 1, 1, 1, 1, buffer_2[0], 1312, T.int8(-1), T.int8(-1), 12, buffer_1[0], 320, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 8, 32, 5, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"int8\", 4, 8, 8, 4, 0, 8, ethosu_write_1[256], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 3, 3, 1, 1, 1, 1, buffer_3[0], 2608, T.int8(-1), T.int8(-1), 12, buffer[0], 80, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dDoubleCascade3:\n    @T.prim_func\n    def main(placeholder_5: T.Buffer[(768,), \"int8\"], ethosu_write_1: T.Buffer[(640,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([1744], \"uint8\")\n        buffer_1 = T.buffer_decl([80], \"uint8\")\n        buffer_2 = T.buffer_decl([320], \"uint8\")\n        buffer_3 = T.buffer_decl([880], \"uint8\")\n        # body\n        ethosu_write_2_data = T.allocate([2560], \"int8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        ethosu_write_2 = T.buffer_decl([2560], \"int8\", data=ethosu_write_2_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 16, 3, 8, 0, 16, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 48, 3, 1, \"int8\", 8, 8, 32, 8, 0, 8, ethosu_write_2[512], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 2, 3, 2, 1, 2, 1, buffer_3[0], 880, T.int8(-1), T.int8(-1), 12, buffer_2[0], 320, T.int8(-1), T.int8(-1), 2, 1, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 8, 32, 8, 0, 8, ethosu_write_2[512], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"int8\", 8, 4, 8, 8, 0, 4, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 32, 8, 1, 2, 3, 2, 1, 2, 1, buffer[0], 1744, T.int8(-1), T.int8(-1), 12, buffer_1[0], 80, T.int8(-1), T.int8(-1), 2, 1, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 12, 16, 3, 12, 0, 16, placeholder_5[192], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 48, 3, 1, \"int8\", 10, 8, 32, 10, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 2, 3, 2, 1, 2, 1, buffer_3[0], 880, T.int8(-1), T.int8(-1), 12, buffer_2[0], 320, T.int8(-1), T.int8(-1), 0, 1, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 10, 8, 32, 10, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"int8\", 8, 4, 8, 8, 0, 4, ethosu_write_1[256], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 32, 8, 1, 2, 3, 2, 1, 2, 1, buffer[0], 1744, T.int8(-1), T.int8(-1), 12, buffer_1[0], 80, T.int8(-1), T.int8(-1), 0, 1, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 16, 3, 4, 0, 16, placeholder_5[576], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 48, 3, 1, \"int8\", 4, 8, 32, 4, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 2, 3, 2, 1, 2, 1, buffer_3[0], 880, T.int8(-1), T.int8(-1), 12, buffer_2[0], 320, T.int8(-1), T.int8(-1), 0, 1, 2, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 8, 32, 4, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"int8\", 4, 4, 8, 4, 0, 4, ethosu_write_1[512], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 32, 8, 1, 2, 3, 2, 1, 2, 1, buffer[0], 1744, T.int8(-1), T.int8(-1), 12, buffer_1[0], 80, T.int8(-1), T.int8(-1), 0, 1, 2, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dDoubleCascade4:\n    @T.prim_func\n    def main(placeholder_5: T.Buffer[(1024,), \"int8\"], ethosu_write_1: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([1456], \"uint8\")\n        buffer_1 = T.buffer_decl([352], \"uint8\")\n        buffer_2 = T.buffer_decl([272], \"uint8\")\n        buffer_3 = T.buffer_decl([11040], \"uint8\")\n        # body\n        ethosu_write_2_data = T.allocate([2304], \"int8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        ethosu_write_2 = T.buffer_decl((2304,), \"int8\", data=ethosu_write_2_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 6, 8, 3, 6, 0, 8, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 128, 16, 1, \"int8\", 5, 8, 35, 5, 0, 8, ethosu_write_2[384], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 384, 16, 128, 3, 3, 1, 1, 1, 1, buffer[0], 1456, T.int8(-1), T.int8(-1), 12, buffer_1[0], 352, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 8, 35, 5, 0, 8, ethosu_write_2[384], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 384, 16, 128, \"int8\", 4, 8, 26, 4, 0, 8, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 256, 16, 128, 3, 3, 1, 1, 1, 1, buffer_3[0], 11040, T.int8(-1), T.int8(-1), 12, buffer_2[0], 272, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 6, 8, 3, 6, 0, 8, placeholder_5[256], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 128, 16, 1, \"int8\", 5, 8, 35, 5, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 384, 16, 128, 3, 3, 1, 1, 1, 1, buffer[0], 1456, T.int8(-1), T.int8(-1), 12, buffer_1[0], 352, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 8, 35, 5, 0, 8, ethosu_write_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 384, 16, 128, \"int8\", 4, 8, 26, 4, 0, 8, ethosu_write_1[1024], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 256, 16, 128, 3, 3, 1, 1, 1, 1, buffer_3[0], 11040, T.int8(-1), T.int8(-1), 12, buffer_2[0], 272, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dDoubleCascade5:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(192,), \"int8\"], ethosu_write: T.Buffer[(8192,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([320], \"uint8\")\n        buffer_2 = T.buffer_decl([304], \"uint8\")\n        buffer_3 = T.buffer_decl([80], \"uint8\")\n        # body\n        ethosu_write_1_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        ethosu_write_1 = T.buffer_decl([4096], \"int8\", data=ethosu_write_1_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 8, 3, 4, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 8, 16, 32, 8, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 512, 32, 1, 1, 1, 1, 1, 1, 1, buffer[0], 160, T.int8(-1), T.int8(-1), 12, buffer_1[0], 320, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"ZEROS\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 16, 32, 8, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 32, 8, 16, 0, 32, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 8, 1, 1, 1, 1, 1, 1, 1, buffer_2[0], 304, T.int8(-1), T.int8(-1), 12, buffer_3[0], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"ZEROS\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 4, 8, 3, 4, 0, 8, placeholder[96], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"int8\", 8, 16, 32, 8, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 512, 32, 1, 1, 1, 1, 1, 1, 1, buffer[0], 160, T.int8(-1), T.int8(-1), 12, buffer_1[0], 320, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"ZEROS\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 16, 32, 8, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 32, 8, 16, 0, 32, ethosu_write[4096], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 8, 1, 1, 1, 1, 1, 1, 1, buffer_2[0], 304, T.int8(-1), T.int8(-1), 12, buffer_3[0], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"ZEROS\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dDoubleCascade6:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(1024,), \"int8\"], ethosu_write: T.Buffer[(32768,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([1456], \"uint8\")\n        buffer_1 = T.buffer_decl([352], \"uint8\")\n        buffer_2 = T.buffer_decl([11040], \"uint8\")\n        buffer_3 = T.buffer_decl([272], \"uint8\")\n        # body\n        ethosu_write_1_data = T.allocate([12288], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        ethosu_write_1 = T.buffer_decl([12288], \"int8\", data=ethosu_write_1_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 8, 3, 8, 0, 8, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 128, 16, 1, \"int8\", 16, 16, 35, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 768, 16, 256, 3, 3, 1, 1, 1, 1, buffer[0], 1456, T.int8(-1), T.int8(-1), 12, buffer_1[0], 352, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NEAREST\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 35, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHCWB16\", 768, 16, 256, \"int8\", 32, 32, 26, 32, 0, 32, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHCWB16\", 1024, 16, 512, 3, 3, 1, 1, 1, 1, buffer_2[0], 11040, T.int8(-1), T.int8(-1), 12, buffer_3[0], 272, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NEAREST\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"trial\",\n    [\n        [\n            Conv2dDoubleCascade1,\n            (1, 8, 8, 3),\n            3,\n            32,\n            8,\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            (1, 1),\n            \"NHWC\",\n            \"NONE\",\n            (1, 8, 4, 8),\n        ],\n        [\n            Conv2dDoubleCascade2,\n            (1, 8, 8, 3),\n            3,\n            32,\n            8,\n            (3, 3),\n            (1, 1, 1, 1),\n            (1, 1),\n            (1, 1),\n            \"NHWC\",\n            \"NONE\",\n            (1, 4, 8, 8),\n        ],\n        [\n            Conv2dDoubleCascade3,\n            (1, 16, 16, 3),\n            3,\n            32,\n            8,\n            (3, 2),\n            (2, 1, 2, 1),\n            (1, 2),\n            (1, 2),\n            \"NHWC\",\n            \"NONE\",\n            (1, 8, 4, 8),\n        ],\n        [\n            Conv2dDoubleCascade4,\n            (1, 8, 1, 8, 16),\n            3,\n            35,\n            26,\n            (3, 3),\n            (1, 1, 1, 1),\n            (1, 1),\n            (1, 1),\n            \"NHCWB16\",\n            \"NONE\",\n            (1, 4, 2, 8, 16),\n        ],\n        [\n            Conv2dDoubleCascade5,\n            (1, 8, 8, 3),\n            3,\n            32,\n            8,\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            (1, 1),\n            \"NHWC\",\n            \"ZEROS\",\n            (1, 16, 32, 8),\n        ],\n        [\n            Conv2dDoubleCascade6,\n            (1, 8, 1, 8, 16),\n            3,\n            35,\n            26,\n            (3, 3),\n            (1, 1, 1, 1),\n            (1, 1),\n            (1, 1),\n            \"NHCWB16\",\n            \"NEAREST\",\n            (1, 32, 2, 32, 16),\n        ],\n    ],\n)\ndef test_conv2d_double_cascade(trial):\n    def _get_func(\n        ifm_shape,\n        ifm_channels,\n        mid_channels,\n        ofm_channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        layout,\n        upscale,\n    ):\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        conv1 = make_ethosu_conv2d(\n            ifm,\n            ifm_channels,\n            mid_channels,\n            kernel_shape,\n            padding,\n            strides,\n            dilation,\n            activation=\"NONE\",\n            ifm_layout=layout,\n            ofm_layout=layout,\n            upscale=upscale,\n        )\n        conv2 = make_ethosu_conv2d(\n            conv1,\n            mid_channels,\n            ofm_channels,\n            kernel_shape,\n            padding,\n            strides,\n            dilation,\n            activation=\"NONE\",\n            ifm_layout=layout,\n            ofm_layout=layout,\n            upscale=upscale,\n        )\n        func = relay.Function(relay.analysis.free_vars(conv2), conv2)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    reference_mod = trial[0]\n    params = trial[1:]\n    func = _get_func(*params[:-1])\n    mod, _ = _lower_to_tir(func, cascader=total_cascader(params[-1]))\n    script = mod.script(show_meta=True)\n    mod = tvm.script.from_source(script)\n    tvm.ir.assert_structural_equal(mod[\"main\"], reference_mod[\"main\"], True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass Conv2dInlineCopy1:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(960,), \"int8\"], ethosu_write_1: T.Buffer[(1024,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([848], \"uint8\")\n        buffer_1 = T.buffer_decl([160], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 8, 8, 4, 8, 0, 8, placeholder_3[120], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 96, 8, 1, \"int8\", 8, 8, 16, 8, 0, 8, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 16, 1, 3, 3, 1, 1, 1, 1, buffer[0], 848, T.int8(-1), T.int8(-1), 12, buffer_1[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dInlineCopy2:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(315,), \"int8\"], ethosu_write_1: T.Buffer[(240,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([656], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 3, 5, 3, 3, 0, 5, placeholder_3[146], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 45, 5, 1, \"int8\", 3, 5, 16, 3, 0, 5, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 80, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 656, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 1, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"trial\",\n    [\n        [Conv2dInlineCopy1, (1, 10, 12, 8), (0, 1, 3, 0), (1, 9, 11, 4)],\n        [Conv2dInlineCopy2, (1, 7, 9, 5), (0, 3, 2, 1), (1, 6, 7, 4)],\n    ],\n)\ndef test_conv2d_inline_copy(trial):\n    def _get_func(ifm_shape, lower, upper, ofm_channels=16):\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        sliced = relay.strided_slice(ifm, lower, upper)\n        conv = make_ethosu_conv2d(\n            sliced, upper[3] - lower[3], ofm_channels, (3, 3), (1, 1), (1, 1), (1, 1)\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    reference_mod = trial[0]\n    params = trial[1:]\n    func = _get_func(*params)\n    mod, _ = _lower_to_tir(func)\n    script = mod.script(show_meta=True)\n    mod = tvm.script.from_source(script)\n    tvm.ir.assert_structural_equal(mod[\"main\"], reference_mod[\"main\"], True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass Conv2dInlineReshape1:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(768,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([848], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[72], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[384], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dInlineReshape2:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(768,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([848], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[72], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[384], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dInlineReshape3:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(768,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([848], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[72], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[384], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass Conv2dInlineReshape4:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(192,), \"int8\"], ethosu_write_1: T.Buffer[(768,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([160], \"uint8\")\n        buffer_1 = T.buffer_decl([848], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 1, 1, 0, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 5, 6, 4, 5, 0, 6, placeholder_3[72], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 4, 1, \"int8\", 4, 6, 16, 4, 0, 6, ethosu_write_1[384], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 96, 16, 1, 3, 3, 1, 1, 1, 1, buffer_1[0], 848, T.int8(-1), T.int8(-1), 12, buffer[0], 160, T.int8(-1), T.int8(-1), 0, 1, 1, 1, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    \"trial\",\n    [\n        [Conv2dInlineReshape1, (4, 6, 8, 1), (1, 8, 6, 4), \"NHWC\"],\n        [Conv2dInlineReshape2, (1, 4 * 6, 8), (1, 8, 6, 4), \"NHWC\"],\n        [Conv2dInlineReshape3, (4 * 6 * 8, 1), (1, 8, 6, 4), \"NHWC\"],\n        [Conv2dInlineReshape4, (4 * 6 * 8,), (1, 8, 6, 4), \"NHWC\"],\n    ],\n)\ndef test_conv2d_inline_reshape(trial):\n    def _get_func(ifm_shape, reshaped, ifm_layout):\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        ifm_reshaped = relay.reshape(ifm, reshaped)\n        conv = make_ethosu_conv2d(\n            ifm_reshaped,\n            reshaped[3],\n            16,\n            (3, 3),\n            (1, 1),\n            (1, 1),\n            (1, 1),\n            activation=\"NONE\",\n            ifm_layout=ifm_layout,\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    reference_mod = trial[0]\n    params = trial[1:]\n    func = _get_func(*params)\n    mod, _ = _lower_to_tir(func, cascader=total_cascader((1, 4, 6, 16)))\n    script = mod.script(show_meta=True)\n    mod = tvm.script.from_source(script)\n    tvm.ir.assert_structural_equal(mod[\"main\"], reference_mod[\"main\"], True)\n\n\n# TODO(@mbaret) Fix this case\n@pytest.mark.xfail(raises=Exception, strict=True)\ndef test_conv2d_big_pad():\n    def _get_func():\n        ifm_shape = (1, 2, 2, 8)\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            ifm, ifm_shape[3], 16, (1, 1), (7, 7), (1, 1), (1, 1), ifm_layout=\"NHWC\"\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func = _get_func()\n    mod, _ = _lower_to_tir(func, cascader=total_cascader((1, 4, 4, 16)))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_copy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import copy_constants, OperatorCompute\n\nfrom .infra import make_ethosu_conv2d\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ReferenceModule:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(8192,), \"int8\"], ethosu_write_1: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer_1 = T.buffer_decl([384], \"uint8\")\n        # body\n        placeholder_global_data = T.allocate([384], \"uint8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        placeholder_global = T.buffer_decl([384], \"uint8\", data=placeholder_global_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_1[0], 384, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 8, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 304, T.int8(-1), T.int8(-1), 12, placeholder_global[304], 80, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_copy():\n    def _get_func():\n        data = relay.var(\"data\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            data,\n            32,\n            8,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func = _get_func()\n    mod, _ = _lower_to_tir(func, cascader=copy_constants())\n\n    script = mod.script(show_meta=True)\n    test_mod = tvm.script.from_source(script)\n    reference_mod = ReferenceModule\n    tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass WeightStream:\n    @T.prim_func\n    def main(placeholder_5: T.Buffer[(8192,), \"int8\"], ethosu_write_1: T.Buffer[(4096,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer = T.buffer_decl([528], \"uint8\")\n        buffer_2 = T.buffer_decl([336], \"uint8\")\n        # body\n        placeholder_d_global_data = T.allocate([528], \"uint8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        placeholder_d_global = T.buffer_decl([528], \"uint8\", data=placeholder_d_global_data)\n        placeholder_d_global_1_data = T.allocate([336], \"uint8\", \"global\", annotations={\"disable_lower_builtin\": True})\n        placeholder_d_global_1 = T.buffer_decl([336], \"uint8\", data=placeholder_d_global_1_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer[0], 528, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_2[0], 336, placeholder_d_global_1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 10, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, placeholder_d_global[0], 416, T.int8(-1), T.int8(-1), 12, placeholder_d_global[416], 112, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder_5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 6, 16, 0, 16, ethosu_write_1[10], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, placeholder_d_global_1[0], 272, T.int8(-1), T.int8(-1), 12, placeholder_d_global_1[272], 64, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_weight_stream():\n    def _cascader(cached_func, const_dict, sch):\n        weight = cached_func.inputs[1]\n        scale_bias = cached_func.inputs[2]\n        out = cached_func.outputs[0]\n        conv_compute = OperatorCompute.from_output(out)\n        co = conv_compute.split(sch, 3, 10)\n        cache_weight = sch.cache_read(weight, \"global\", [conv_compute.op])\n        cache_scale_bias = sch.cache_read(scale_bias, \"global\", [conv_compute.op])\n        sch[cache_weight].compute_at(sch[out], co)\n        sch[cache_scale_bias].compute_at(sch[out], co)\n\n    def _get_func():\n        ifm = relay.var(\"ifm\", shape=(1, 16, 16, 32), dtype=\"int8\")\n        conv = make_ethosu_conv2d(\n            ifm,\n            32,\n            16,\n            (1, 1),\n            (0, 0),\n            (1, 1),\n            (1, 1),\n        )\n        func = relay.Function(relay.analysis.free_vars(conv), conv)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func = _get_func()\n    mod, _ = _lower_to_tir(func, cascader=_cascader)\n\n    script = mod.script(show_meta=True)\n    test_mod = tvm.script.from_source(script)\n    reference_mod = WeightStream\n    tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_depthwise_conv2d, get_convolutional_args\n\n\n@pytest.mark.parametrize(\n    \"trial\",\n    [\n        [(1, 8, 8, 3), 3, (3, 2), (0, 0), (1, 1), (1, 1), \"CLIP\", \"NHWC\", \"NHWC\", \"TFL\"],\n        [(1, 8, 8, 3), 3, (1, 1), (2, 1), (1, 1), (1, 1), \"NONE\", \"NHWC\", \"NHWC\", \"NATURAL\"],\n        [(1, 8, 8, 3), 3, (1, 1), (0, 0), (1, 1), (1, 1), \"NONE\", \"NHWC\", \"NHWC\", \"TRUNCATE\"],\n        [(1, 1, 1, 1), 1, (1, 1), (0, 0), (1, 1), (1, 1), \"CLIP\", \"NHWC\", \"NHWC\", \"TFL\"],\n        [(1, 7, 9, 4), 4, (3, 2), (1, 2), (2, 1), (1, 2), \"NONE\", \"NHWC\", \"NHWC\", \"NATURAL\"],\n        [\n            (1, 8, 2, 8, 16),\n            18,\n            (1, 1),\n            (2, 1),\n            (1, 1),\n            (1, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHWC\",\n            \"TRUNCATE\",\n        ],\n        [(1, 7, 9, 40), 40, (3, 2), (1, 2), (2, 1), (1, 2), \"CLIP\", \"NHWC\", \"NHCWB16\", \"TFL\"],\n        [\n            (1, 4, 12, 9, 16),\n            182,\n            (2, 3),\n            (6, 3),\n            (2, 2),\n            (1, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHCWB16\",\n            \"NATURAL\",\n        ],\n        [(1, 7, 9, 4), 4, (3, 2), (1, 2), (2, 1), (2, 2), \"CLIP\", \"NHWC\", \"NHWC\", \"TRUNCATE\"],\n        [(1, 7, 9, 41), 41, (3, 2), (1, 2), (2, 1), (2, 2), \"CLIP\", \"NHWC\", \"NHCWB16\", \"TFL\"],\n        [\n            (1, 13, 12, 19, 16),\n            182,\n            (1, 3),\n            (5, 3),\n            (2, 1),\n            (2, 1),\n            \"CLIP\",\n            \"NHCWB16\",\n            \"NHCWB16\",\n            \"NATURAL\",\n        ],\n    ],\n)\n@tvm.testing.skip_parameterizations(\n    \"trial3\", reason=\"See https://github.com/apache/tvm/issues/12841\"\n)\ndef test_depthwise_conv2d_single(request, trial):\n    def _get_func(\n        ifm_shape,\n        channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        activation,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n    ):\n        ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n        depthwise = make_ethosu_depthwise_conv2d(\n            ifm,\n            channels,\n            kernel_shape,\n            padding,\n            strides,\n            dilation,\n            activation,\n            ifm_layout,\n            ofm_layout,\n            \"int8\",\n            \"uint8\",\n            rounding_mode,\n        )\n        func = relay.Function(relay.analysis.free_vars(depthwise), depthwise)\n        func = run_opt_pass(func, relay.transform.InferType())\n        return func\n\n    func = _get_func(*trial)\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_convolutional_args(stmt, remove_constants=True))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n    (\n        ifm_shape,\n        channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        activation,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n    ) = trial\n    dilated_kernel_h = (kernel_shape[0] - 1) * dilation[0] + 1\n    dilated_kernel_w = (kernel_shape[1] - 1) * dilation[1] + 1\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3]\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3]\n        ofm_height = (ifm_shape[1] - dilated_kernel_h + padding[0] + padding[0]) // strides[0] + 1\n        ofm_width = (ifm_shape[2] - dilated_kernel_w + padding[1] + padding[1]) // strides[1] + 1\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3]\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n        ofm_height = (ifm_shape[1] - dilated_kernel_h + padding[0] + padding[0]) // strides[0] + 1\n        ofm_width = (ifm_shape[3] - dilated_kernel_w + padding[1] + padding[1]) // strides[1] + 1\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = channels if ofm_width > 1 else 1\n        ofm_stride_h = channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width\n        ofm_stride_h = 16 * ofm_width * ((channels - 1) // 16 + 1)\n\n    answer = [\n        \"int8\",\n        ifm_shape[1],\n        ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n        channels,\n        ifm_shape[1],\n        0,\n        ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n        0,\n        0,\n        0,\n        0,\n        0.6,\n        11,\n        ifm_layout,\n        ifm_stride_h,\n        ifm_stride_w,\n        ifm_stride_c,\n        \"int8\",\n        ofm_height,\n        ofm_width,\n        channels,\n        ofm_height,\n        0,\n        ofm_width,\n        0,\n        0,\n        0,\n        0,\n        0.26,\n        15,\n        ofm_layout,\n        ofm_stride_h,\n        ofm_stride_w,\n        ofm_stride_c,\n        kernel_shape[1],\n        kernel_shape[0],\n        strides[1],\n        strides[0],\n        dilation[1],\n        dilation[0],\n        13,\n        padding[0],\n        padding[1],\n        padding[0],\n        padding[1],\n        activation,\n        15 if activation == \"CLIP\" else 0,\n        105 if activation == \"CLIP\" else 0,\n        rounding_mode,\n        \"NONE\",\n        0,\n        0,\n        0,\n    ]\n    assert data[0] == answer, data[0]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_identity.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir import spec\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_identity, get_pooling_args\n\n\n@pytest.mark.parametrize(\"ifm_shape\", [[1, 5, 9, 3], [20, 14, 7], [31, 40], [101]])\ndef test_identity(ifm_shape):\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    identity = make_ethosu_identity(ifm)\n\n    func = relay.Function(relay.analysis.free_vars(identity), identity)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_pooling_args(stmt))\n\n    # Construct the ifm shape that the initial ifm shape gets legalized into\n    ref_ifm_shape = ifm_shape\n\n    if len(ref_ifm_shape) < 4:\n        ref_ifm_shape = [1] + ref_ifm_shape\n\n    while len(ref_ifm_shape) < 4:\n        ref_ifm_shape.append(1)\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n    ifm_stride_c = 1\n    ifm_stride_w = ref_ifm_shape[3]\n    ifm_stride_h = ref_ifm_shape[2] * ref_ifm_shape[3]\n    ofm_height = ref_ifm_shape[1]\n    ofm_width = ref_ifm_shape[2]\n    ofm_channels = ref_ifm_shape[3]\n    ofm_stride_c = 1\n    ofm_stride_w = ofm_channels if ofm_width > 1 else 1\n    ofm_stride_h = ofm_channels * ofm_width if ofm_height > 1 else 1\n\n    # The identity operator TIR gets converted into serial pooling\n    serial_pooling = spec.SerialPooling(\n        ifm=spec.SerialFeatureMap(\n            data_type=\"int8\",\n            height=ref_ifm_shape[1],\n            width=ref_ifm_shape[2],\n            channels=ofm_channels,\n            tile_height_0=ref_ifm_shape[1],\n            tile_height_1=0,\n            tile_width_0=ref_ifm_shape[2],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=\"NHWC\",\n            stride_h=ifm_stride_h,\n            stride_w=ifm_stride_w,\n            stride_c=ifm_stride_c,\n        ),\n        ofm=spec.SerialFeatureMap(\n            data_type=\"int8\",\n            height=ofm_height,\n            width=ofm_width,\n            channels=ofm_channels,\n            tile_height_0=ofm_height,\n            tile_height_1=0,\n            tile_width_0=ofm_width,\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=\"NHWC\",\n            stride_h=ofm_stride_h,\n            stride_w=ofm_stride_w,\n            stride_c=ofm_stride_c,\n        ),\n        pooling_type=\"AVG\",\n        pool_shape=spec.SerialKernel(1, 1, 1, 1, 1, 1),\n        padding=spec.SerialPadding(0, 0, 0, 0),\n        activation=spec.SerialActivation(op=\"NONE\", clip_min=0, clip_max=0),\n        upscale=\"NONE\",\n        rounding_mode=\"TFL\",\n        block_config=spec.SerialBlockConfig(0, 0, 0),\n    )\n\n    assert data[0] == [\"ethosu_identity\"] + list(serial_pooling)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir import spec\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_pooling, get_pooling_args\n\n\ndef _create_serial_pooling(\n    ifm_shape,\n    ofm_channels,\n    ifm_layout,\n    ofm_layout,\n    pool_shape,\n    pooling_type,\n    strides,\n    padding,\n    activation=\"NONE\",\n    rounding_mode=\"TFL\",\n    upscale=\"NONE\",\n):\n    upscale_factor = 2 if upscale != \"NONE\" else 1\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3]\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3]\n        ofm_height = (\n            ifm_shape[1] * upscale_factor - pool_shape[0] + padding[0] + padding[2]\n        ) // strides[0] + 1\n        ofm_width = (\n            ifm_shape[2] * upscale_factor - pool_shape[1] + padding[1] + padding[3]\n        ) // strides[1] + 1\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3] if ofm_channels >= 16 else 1\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n        ofm_height = (\n            ifm_shape[1] * upscale_factor - pool_shape[0] + padding[0] + padding[2]\n        ) // strides[0] + 1\n        ofm_width = (\n            ifm_shape[3] * upscale_factor - pool_shape[1] + padding[1] + padding[3]\n        ) // strides[1] + 1\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = ofm_channels if ofm_width > 1 else 1\n        ofm_stride_h = ofm_channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width if ofm_channels >= 16 else 1\n        ofm_stride_h = 16 * ofm_width * ((ofm_channels - 1) // 16 + 1)\n\n    return spec.SerialPooling(\n        ifm=spec.SerialFeatureMap(\n            data_type=\"int8\",\n            height=ifm_shape[1],\n            width=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            channels=ofm_channels,\n            tile_height_0=ifm_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm_stride_h,\n            stride_w=ifm_stride_w,\n            stride_c=ifm_stride_c,\n        ),\n        ofm=spec.SerialFeatureMap(\n            data_type=\"int8\",\n            height=ofm_height,\n            width=ofm_width,\n            channels=ofm_channels,\n            tile_height_0=ofm_height,\n            tile_height_1=0,\n            tile_width_0=ofm_width,\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ofm_layout,\n            stride_h=ofm_stride_h,\n            stride_w=ofm_stride_w,\n            stride_c=ofm_stride_c,\n        ),\n        pooling_type=pooling_type,\n        pool_shape=spec.SerialKernel(\n            width=pool_shape[1],\n            height=pool_shape[0],\n            stride_w=strides[1],\n            stride_h=strides[0],\n            dilation_w=1,\n            dilation_h=1,\n        ),\n        padding=spec.SerialPadding(\n            top=padding[0], left=padding[1], bottom=padding[2], right=padding[3]\n        ),\n        activation=spec.SerialActivation(\n            op=activation,\n            clip_min=10 if activation == \"CLIP\" else 0,\n            clip_max=100 if activation == \"CLIP\" else 0,\n        ),\n        rounding_mode=rounding_mode,\n        upscale=upscale,\n        block_config=spec.SerialBlockConfig(0, 0, 0),\n    )\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ofm_channels, ifm_layout, ofm_layout, rounding_mode, upscale\",\n    [\n        ((1, 5, 9, 3), 3, \"NHWC\", \"NHWC\", \"TFL\", \"NONE\"),\n        ((1, 8, 3, 9, 16), 40, \"NHCWB16\", \"NHCWB16\", \"NATURAL\", \"NONE\"),\n        ((1, 8, 3, 9, 16), 40, \"NHCWB16\", \"NHWC\", \"TRUNCATE\", \"ZEROS\"),\n        ((1, 8, 9, 40), 40, \"NHWC\", \"NHCWB16\", \"TFL\", \"ZEROS\"),\n        ((1, 8, 9, 8), 8, \"NHWC\", \"NHCWB16\", \"TFL\", \"NEAREST\"),\n        ((1, 5, 9, 3), 3, \"NHWC\", \"NHWC\", \"TFL\", \"NEAREST\"),\n    ],\n)\n@pytest.mark.parametrize(\"pooling_type\", [\"AVG\", \"MAX\"])\n@pytest.mark.parametrize(\"activation\", [\"NONE\", \"CLIP\"])\ndef test_pooling_single(\n    ifm_shape,\n    ofm_channels,\n    ifm_layout,\n    ofm_layout,\n    pooling_type,\n    activation,\n    rounding_mode,\n    upscale,\n):\n    pool_shape = (3, 2)\n    strides = (1, 2)\n\n    # When strides are not (1, 1) it is possible to create invalid\n    # padding configurations. It is possible to construct a pooling\n    # operation with invalid padding, but the compiler will account\n    # for this and adjust the padding accordingly, leading to a\n    # mismatch between the expected and actual result. Therefore,\n    # hardcoded padding values are used for each case.\n    padding = (1, 1, 1, 0) if upscale == \"NONE\" else (0, 0, 0, 0)\n\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    pooling = make_ethosu_pooling(\n        ifm,\n        pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        activation,\n        ifm_layout,\n        ofm_layout,\n        rounding_mode,\n        upscale,\n    )\n    func = relay.Function(relay.analysis.free_vars(pooling), pooling)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_pooling_args(stmt))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n\n    serial_pooling = _create_serial_pooling(\n        ifm_shape,\n        ofm_channels,\n        ifm_layout,\n        ofm_layout,\n        pool_shape,\n        pooling_type,\n        strides,\n        padding,\n        activation,\n        rounding_mode,\n        upscale,\n    )\n    assert data[0] == [\"ethosu_pooling\"] + list(serial_pooling)\n\n\ndef test_correct_stride_with_multiple_pooling():\n    \"\"\"Testing a specific case of two pooling operations with NHWC inputs/outputs\n    but a NHCWB16 intermediate tensor. This lead to elements being accessed in the\n    wrong order by the NPU, due to incorrect stride values being calculated.\"\"\"\n\n    ifm_shape = (1, 4, 4, 8)\n    ofm_channels = 8\n    pooling_type = \"MAX\"\n    pool_shape = (1, 1)\n    strides = (1, 1)\n    padding = (0, 0, 0, 0)\n\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    op = make_ethosu_pooling(\n        ifm,\n        pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        ifm_layout=\"NHWC\",\n        ofm_layout=\"NHCWB16\",\n    )\n    op = make_ethosu_pooling(\n        op,\n        pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        ifm_layout=\"NHCWB16\",\n        ofm_layout=\"NHWC\",\n    )\n    func = relay.Function(relay.analysis.free_vars(op), op)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(get_pooling_args(stmt))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n\n    serial_pooling_1 = _create_serial_pooling(\n        [1, 4, 4, 8],\n        8,\n        \"NHWC\",\n        \"NHCWB16\",\n        pool_shape,\n        pooling_type,\n        strides,\n        padding,\n    )\n    serial_pooling_2 = _create_serial_pooling(\n        [1, 4, 1, 4, 16],\n        8,\n        \"NHCWB16\",\n        \"NHWC\",\n        pool_shape,\n        pooling_type,\n        strides,\n        padding,\n    )\n\n    assert data[0] == [\"ethosu_pooling\"] + list(serial_pooling_1)\n    assert data[1] == [\"ethosu_pooling\"] + list(serial_pooling_2)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_replace_unary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nimport tvm.script\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.relay.backend.contrib.ethosu.tir import spec\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import _lower_to_tir\nfrom .infra import make_ethosu_unary_elementwise\n\n\ndef _get_unary_elementwise_args(call, include_buffers=False, remove_constants=False):\n    args = call.args\n    unary_elementwise_args = []\n\n    for i, arg in enumerate(args):\n        if isinstance(arg, tvm.tir.expr.IntImm) or isinstance(arg, tvm.tir.expr.FloatImm):\n            unary_elementwise_args.append(arg.value)\n        elif isinstance(arg, tvm.tir.expr.BufferLoad) and not include_buffers:\n            unary_elementwise_args.append(arg.indices[0])\n        else:\n            unary_elementwise_args.append(arg)\n\n    return unary_elementwise_args\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm_channels, ifm_layout, ofm_layout, rounding_mode\",\n    [\n        ((1, 5, 9, 3), 3, \"NHWC\", \"NHWC\", \"TFL\"),\n        ((1, 8, 3, 9, 16), 40, \"NHCWB16\", \"NHCWB16\", \"NATURAL\"),\n        ((1, 8, 3, 9, 16), 40, \"NHCWB16\", \"NHWC\", \"TRUNCATE\"),\n        ((1, 8, 9, 40), 40, \"NHWC\", \"NHCWB16\", \"TFL\"),\n    ],\n)\n@pytest.mark.parametrize(\"operator_type, data_type\", [(\"ABS\", \"int8\"), (\"CLZ\", \"int32\")])\n@pytest.mark.parametrize(\"activation\", [\"NONE\"])\ndef test_unary_elementwise_single(\n    ifm_shape,\n    ifm_channels,\n    ifm_layout,\n    ofm_layout,\n    rounding_mode,\n    operator_type,\n    activation,\n    data_type,\n):\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=data_type)\n\n    unary_elementwise = make_ethosu_unary_elementwise(\n        ifm, ifm_channels, operator_type, activation, ifm_layout, ofm_layout, rounding_mode\n    )\n    func = relay.Function(relay.analysis.free_vars(unary_elementwise), unary_elementwise)\n    func = run_opt_pass(func, relay.transform.InferType())\n    mod, _ = _lower_to_tir(func)\n    data = []\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.Call):\n            data.append(_get_unary_elementwise_args(stmt, remove_constants=True))\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, _visit)\n    if ifm_layout == \"NHWC\":\n        ifm_stride_c = 1\n        ifm_stride_w = ifm_shape[3] if ifm_shape[2] != 1 else 1\n        ifm_stride_h = ifm_shape[2] * ifm_shape[3] if ifm_shape[1] != 1 else 1\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[2]\n    else:\n        ifm_stride_w = 16\n        ifm_stride_c = 16 * ifm_shape[3]\n        ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]\n\n        ofm_height = ifm_shape[1]\n        ofm_width = ifm_shape[3]\n\n    if ofm_layout == \"NHWC\":\n        ofm_stride_c = 1\n        ofm_stride_w = ifm_channels if ofm_width > 1 else 1\n        ofm_stride_h = ifm_channels * ofm_width if ofm_height > 1 else 1\n    else:\n        ofm_stride_w = 16\n        ofm_stride_c = 16 * ofm_width\n        ofm_stride_h = 16 * ofm_width * ((ifm_channels - 1) // 16 + 1)\n\n    serial_unary_elementwise = spec.SerialUnaryElementwise(\n        ifm=spec.SerialFeatureMap(\n            data_type=data_type,\n            height=ifm_shape[1],\n            width=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            channels=ifm_channels,\n            tile_height_0=ifm_shape[1],\n            tile_height_1=0,\n            tile_width_0=ifm_shape[2] if ifm_layout == \"NHWC\" else ifm_shape[3],\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ifm_layout,\n            stride_h=ifm_stride_h,\n            stride_w=ifm_stride_w,\n            stride_c=ifm_stride_c,\n        ),\n        ofm=spec.SerialFeatureMap(\n            data_type=data_type,\n            height=ofm_height,\n            width=ofm_width,\n            channels=ifm_channels,\n            tile_height_0=ofm_height,\n            tile_height_1=0,\n            tile_width_0=ofm_width,\n            tile_address_0=0,\n            tile_address_1=0,\n            tile_address_2=0,\n            tile_address_3=0,\n            scale=1.0,\n            zero_point=0,\n            layout=ofm_layout,\n            stride_h=ofm_stride_h,\n            stride_w=ofm_stride_w,\n            stride_c=ofm_stride_c,\n        ),\n        operator_type=operator_type,\n        activation=spec.SerialActivation(\n            op=activation,\n            clip_min=10 if activation == \"CLIP\" else 0,\n            clip_max=100 if activation == \"CLIP\" else 0,\n        ),\n        rounding_mode=rounding_mode,\n        block_config=spec.SerialBlockConfig(0, 0, 0),\n    )\n\n    assert data[0] == [\"ethosu_unary_elementwise\"] + list(serial_unary_elementwise)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_rolling_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import OperatorCompute\nimport tvm.relay.backend.contrib.ethosu.codegen as codegen\nimport tensorflow as tf\nfrom . import infra\n\n\n@pytest.mark.parametrize(\n    \"axis, ifm_shape, pool_shape\",\n    [\n        (1, (1, 12, 1, 2), (3, 1)),\n        (1, (1, 12, 12, 2), (3, 3)),\n        (2, (1, 1, 12, 2), (1, 3)),\n        (2, (1, 12, 12, 2), (3, 3)),\n    ],\n)\ndef test_rolling_buffer_2_layers(axis, ifm_shape, pool_shape):\n    accel_type = \"ethos-u55-256\"\n    strides = (1, 1)\n\n    @tf.function\n    def tf_model(x):\n        padding = \"VALID\"\n        pool_0 = tf.nn.max_pool(x, pool_shape, strides, padding)\n        pool_1 = tf.nn.max_pool(pool_0, pool_shape, strides, padding)\n        return pool_1\n\n    def _cascader(cached_func, const_dict, sch):\n        pool_b_out = cached_func.outputs[0]\n        pool_b_compute = OperatorCompute.from_output(pool_b_out)\n\n        pool_a_out = pool_b_compute.read.op.input_tensors[0]\n        pool_a_compute = OperatorCompute.from_output(pool_a_out)\n\n        outer = pool_b_compute.split(sch, axis=axis, val=4)\n        pool_a_compute.compute_at(sch, stage=sch[pool_b_out], axis=outer)\n        pool_a_compute.rolling_buffer(sch)\n\n    codegen.SCHEDULER = lambda: _cascader\n    infra.compare_tvm_with_tflite(tf_model, [ifm_shape], accel_type)\n\n\n@pytest.mark.parametrize(\n    \"axis, ifm_shape, pool_shape\",\n    [\n        (1, (1, 12, 1, 2), (3, 1)),\n        (1, (1, 12, 1, 17), (3, 1)),\n        (1, (1, 12, 12, 2), (3, 3)),\n        (1, (1, 12, 12, 17), (3, 3)),\n        (2, (1, 1, 12, 2), (1, 3)),\n        (2, (1, 1, 12, 17), (1, 3)),\n        (2, (1, 12, 12, 2), (3, 3)),\n        (2, (1, 12, 12, 17), (3, 3)),\n    ],\n)\ndef test_rolling_buffer_3_layers(axis, ifm_shape, pool_shape):\n    accel_type = \"ethos-u55-256\"\n    strides = (1, 1)\n\n    @tf.function\n    def tf_model(x):\n        padding = \"VALID\"\n        pool_0 = tf.nn.max_pool(x, pool_shape, strides, padding)\n        pool_1 = tf.nn.max_pool(pool_0, pool_shape, strides, padding)\n        pool_2 = tf.nn.max_pool(pool_1, pool_shape, strides, padding)\n        return pool_2\n\n    def _cascader(cached_func, const_dict, sch):\n        pool_b_out = cached_func.outputs[0]\n        pool_b_compute = OperatorCompute.from_output(pool_b_out)\n\n        pool_a_out = pool_b_compute.read.op.input_tensors[0]\n        pool_a_compute = OperatorCompute.from_output(pool_a_out)\n\n        outer = pool_b_compute.split(sch, axis=axis, val=4)\n        pool_a_compute.compute_at(sch, stage=sch[pool_b_out], axis=outer)\n        pool_a_compute.rolling_buffer(sch)\n\n    codegen.SCHEDULER = lambda: _cascader\n    infra.compare_tvm_with_tflite(tf_model, [ifm_shape], accel_type)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm import te, topi\nfrom tvm.relay.backend.contrib.ethosu.tir.scheduler import (\n    tile_nd,\n    schedule_pragmas,\n    inline_no_ops,\n    total_cascader,\n    copy_constants,\n    schedule_cache_reads,\n    copy_luts,\n)\nfrom tvm.relay.backend.contrib.ethosu.tir.compiler import (\n    lower_to_te,\n    extract_constants,\n    _lower_to_tir,\n)\nfrom .infra import (\n    AttachType,\n    make_ethosu_conv2d,\n    make_ethosu_identity,\n    make_ethosu_binary_elementwise,\n)\n\n\nclass TestTEGraph:\n    def __init__(self, inputs, outputs):\n        self.inputs = inputs\n        self.outputs = outputs\n\n\ndef test_tile_nd():\n    input = te.placeholder((12, 12), dtype=\"uint8\", name=\"input\")\n    out = topi.nn.relu(input)\n    sch = te.create_schedule([out.op])\n    outer_iters, inner_iters = tile_nd(sch, out, (3, 4))\n    assert tuple(sch[out].leaf_iter_vars) == (*outer_iters, *inner_iters)\n\n\ndef test_schedule_pragmas():\n    input = te.placeholder((12, 12), dtype=\"uint8\", name=\"input\")\n    out = te.compute(\n        (12, 12),\n        lambda i, j: input[i, j],\n        attrs={\n            \"op\": \"unity\",\n            \"info\": 1,\n        },\n    )\n    sch = te.create_schedule([out.op])\n    sch[out].split(out.op.axis[0], 3)\n    schedule_pragmas(sch)\n    iter_var = sch[out].leaf_iter_vars[1]\n    assert list(sch[out].iter_var_attrs[iter_var].pragma_keys) == [\"op\", \"info\"]\n    assert list(sch[out].iter_var_attrs[iter_var].pragma_values) == [\"unity\", 1]\n\n\ndef test_schedule_pragmas_for_const():\n    input = te.placeholder((12, 12), dtype=\"uint8\", name=\"input\")\n    const = te.compute((), lambda: 2)\n    add = topi.add(input, const)\n    sch = te.create_schedule([add.op])\n    schedule_pragmas(sch)\n\n\ndef test_inline_no_ops():\n    input = relay.var(\"input\", shape=(12, 12), dtype=\"uint8\")\n    slice = relay.strided_slice(input, [0, 0], [6, 6])\n    relu1 = relay.nn.relu(slice)\n    reshape = relay.reshape(relu1, (36,))\n    relu2 = relay.nn.relu(reshape)\n    func = relay.Function(relay.analysis.free_vars(relu2), relu2)\n    func = run_opt_pass(func, relay.transform.InferType())\n\n    cached_func = lower_to_te(func)\n    sch = te.create_schedule([cached_func.outputs[0].op])\n    inline_no_ops(cached_func, sch)\n    reshape_tensor = cached_func.outputs[0].op.input_tensors[0]\n    slice_tensor = reshape_tensor.op.input_tensors[0].op.input_tensors[0]\n    assert sch[reshape_tensor].attach_type == AttachType.kInline\n    assert sch[slice_tensor].attach_type == AttachType.kInline\n\n\ndef test_total_cascader():\n    input = te.placeholder((12, 12), dtype=\"uint8\", name=\"input\")\n    relu1 = topi.nn.relu(input)\n    relu2 = topi.nn.relu(relu1)\n    relu3 = topi.nn.relu(relu2)\n    sch = te.create_schedule([relu3.op])\n    cascader = total_cascader((4, 4))\n    cascader(TestTEGraph([input], [relu3]), {}, sch)\n    assert sch[relu1].attach_type == AttachType.kScope\n    assert sch[relu2].attach_type == AttachType.kScope\n    assert sch[relu3].attach_type == AttachType.kGroupRoot\n    # Check that the attaches are at the correct iter var\n    assert sch[relu1].attach_ivar == sch[relu3].leaf_iter_vars[1]\n    assert sch[relu2].attach_ivar == sch[relu3].leaf_iter_vars[1]\n\n\ndef test_copy_constants():\n    ifm_a = relay.var(\"IFM_A\", shape=(1, 26, 26, 32), dtype=\"int8\")\n    conv_a = make_ethosu_conv2d(ifm_a, 32, 8, (3, 3), (0, 0), (1, 1), (1, 1))\n    conv_b = make_ethosu_conv2d(conv_a, 8, 4, (1, 1), (0, 0), (1, 1), (1, 1))\n    func = relay.Function(relay.analysis.free_vars(conv_b), conv_b)\n    func = run_opt_pass(func, relay.transform.InferType())\n\n    func, const_dict = extract_constants(func)\n    cached_func = lower_to_te(func)\n\n    sch = te.create_schedule([cached_func.outputs[0].op])\n    planner = copy_constants()\n    planner(cached_func, const_dict, sch)\n    assert len(sch.stages) == 23\n    assert \".global\" in sch.stages[6].op.name\n    assert \".global\" in sch.stages[8].op.name\n    assert \".global\" in sch.stages[17].op.name\n    assert \".global\" in sch.stages[19].op.name\n\n\n# This test makes sure that constants and LUTs have a correct storage scope\ndef test_copy_luts():\n    ifm_shape = (1, 33, 33, 11)\n    ifm = relay.var(\"IFM\", shape=ifm_shape, dtype=\"int8\")\n    lut = relay.const([i for i in range(256)], dtype=\"int8\")\n    conv = make_ethosu_conv2d(\n        ifm, ifm_shape[3], 8, (3, 3), (0, 0), (1, 1), (1, 1), lut=lut, activation=\"TANH\"\n    )\n    identity = make_ethosu_identity(conv, lut=lut, activation=\"TANH\")\n    func = relay.Function(relay.analysis.free_vars(identity), identity)\n    func = run_opt_pass(func, relay.transform.InferType())\n\n    func, const_dict = extract_constants(func)\n    te_graph = lower_to_te(func)\n\n    sch = te.create_schedule([te_graph.outputs[0].op])\n    copy_constants()(te_graph, const_dict, sch)\n    copy_luts()(te_graph, const_dict, sch)\n    assert len(sch.stages) == 17\n    assert \".global\" in sch.stages[6].op.name\n    assert \".global\" in sch.stages[8].op.name\n    assert \".local\" in sch.stages[10].op.name\n\n\ndef test_schedule_cache_reads():\n    a = te.placeholder((12, 12), dtype=\"uint8\", name=\"a\")\n    b = te.placeholder((12, 12), dtype=\"uint8\", name=\"b\")\n    add = topi.add(a, b)\n    sch = te.create_schedule([add.op])\n    cr = sch.cache_read(b, \"global\", [add])\n    schedule_cache_reads(sch)\n    assert len(sch.stages) == 4\n    assert len(sch[cr].leaf_iter_vars) == 1\n    iv = sch[cr].leaf_iter_vars[0]\n    assert list(sch[cr].iter_var_attrs[iv].pragma_keys) == [\"op\"]\n    assert list(sch[cr].iter_var_attrs[iv].pragma_values) == [\"ethosu_copy\"]\n\n\n# fmt: off\n@tvm.script.ir_module\nclass DiamondGraphTir:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(301056,), \"int8\"], ethosu_write: T.Buffer[(75264,), \"int8\"]) -> None:\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        buffer1 = T.buffer_decl([2848], \"uint8\")\n        buffer3 = T.buffer_decl([976], \"uint8\")\n        p1_data = T.allocate([2848], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p1 = T.buffer_decl([2848], \"uint8\", data=p1_data)\n        p2_data = T.allocate([976], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p2 = T.buffer_decl([976], \"uint8\", data=p2_data)\n        p5_data = T.allocate([75264], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p5 = T.buffer_decl([75264], \"int8\", data=p5_data)\n        p6_data = T.allocate([75264], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        p6 = T.buffer_decl([75264], \"int8\", data=p6_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer1[0], 2848, p1[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer3[0], 976, p2[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 56, 56, 96, 56, 0, 56, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 5376, 96, 1, \"int8\", 56, 56, 24, 56, 0, 56, p5[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 1344, 24, 1, 1, 1, 1, 1, 1, 1, p1[0], 2608, T.int8(-1), T.int8(-1), 12, p1[2608], 240, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 56, 56, 24, 56, 0, 56, p5[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 1344, 24, 1, \"int8\", 56, 56, 24, 56, 0, 56, p6[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 1344, 24, 1, 1, 1, 1, 1, 1, 1, p2[0], 736, T.int8(-1), T.int8(-1), 12, p2[736], 240, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 56, 56, 24, 56, 0, 56, p5[0], 0, 0, 0,T.float32(1), 0, \"NHWC\", 1344, 24, 1, \"int8\", 56, 56, 24, 56, 0, 56, p6[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1344, 24, 1, \"int8\", 56, 56, 24, 56, 0, 56, ethosu_write[0], 0, 0, 0, T.float32(1), 0, \"NHWC\", 1344, 24, 1, \"ADD\", 0, \"NONE\", 0, 0, \"TFL\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_schedule_diamond_graph():\n    ifm_a = relay.var(\"IFM_A\", shape=(1, 56, 56, 96), dtype=\"int8\")\n    conv_a = make_ethosu_conv2d(ifm_a, 96, 24, (1, 1), (0, 0), (1, 1), (1, 1))\n    conv_b = make_ethosu_conv2d(conv_a, 24, 24, (1, 1), (0, 0), (1, 1), (1, 1))\n    add = make_ethosu_binary_elementwise(conv_a, conv_b, 24, 24, \"ADD\", \"int8\")\n\n    func = relay.Function(relay.analysis.free_vars(add), add)\n    func = run_opt_pass(func, relay.transform.InferType())\n\n    test_mod, _ = _lower_to_tir(func, copy_constants())\n    reference_mod = DiamondGraphTir\n    tvm.ir.assert_structural_equal(test_mod[\"main\"], reference_mod[\"main\"], True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport numpy as np\n\nimport tvm\nfrom tvm.tir import stmt_functor\nfrom tvm.script import tir as T\nfrom tvm.relay.backend.contrib.ethosu import tir_to_cs_translator\nfrom tvm.relay.backend.contrib.ethosu import util\nimport ethosu.vela.api as vapi\n\n\n# fmt: off\n\"\"\"A sample tir test case for translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosUConv2D:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(8192,), \"int8\"], ethosu_conv2d_1: T.Buffer[(1024,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_4 = T.buffer_decl([1], \"uint8\")\n        placeholder_5 = T.buffer_decl([1], \"uint8\")\n        # body\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 8, 8, 3, 8, 0, 8, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"uint8\", 8, 8, 16, 8, 0, 8, ethosu_conv2d_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 16, 1, 1, 1, 1, 1, 1, 1, placeholder_4[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_5[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"CLIP\", 0, 255, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"uint8\"))\n# fmt: on\n\n\n# fmt: off\n\"\"\"A sample tir test case with multiple convolutions for translator\"\"\"\n@tvm.script.ir_module\nclass MultiEthosUConv2D:\n    @T.prim_func\n    def main(placeholder_6: T.Buffer[(192,), \"int8\"], ethosu_conv2d_1: T.Buffer[(512,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_9 = T.buffer_decl([1], \"uint8\")\n        placeholder_7 = T.buffer_decl([1], \"uint8\")\n        placeholder_8 = T.buffer_decl([1], \"uint8\")\n        placeholder_5 = T.buffer_decl([1], \"uint8\")\n        # body\n        ethosu_conv2d_2 = T.decl_buffer([1024], \"uint8\")\n        ethosu_conv2d_3 = T.decl_buffer([2048], \"uint8\")\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 4, 8, 3, 4, 0, 8, placeholder_6[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"uint8\", 4, 8, 32, 4, 0, 8, ethosu_conv2d_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 1, 1, 1, 1, 1, 1, placeholder_7[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_8[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"uint8\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 4, 8, 32, 4, 0, 8, ethosu_conv2d_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"uint8\", 4, 8, 8, 4, 0, 8, ethosu_conv2d_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_9[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_5[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"CLIP\", 0, 255, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"uint8\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 4, 8, 3, 4, 0, 8, placeholder_6[96], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 24, 3, 1, \"uint8\", 4, 8, 32, 4, 0, 8, ethosu_conv2d_2[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 32, 1, 1, 1, 1, 1, 1, 1, placeholder_7[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_8[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"CLIP\", 0, 255, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"uint8\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 4, 8, 32, 4, 0, 8, ethosu_conv2d_2[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 32, 1, \"uint8\", 4, 8, 8, 4, 0, 8, ethosu_conv2d_1[256], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 64, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_9[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_5[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"CLIP\", 0, 255, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"uint8\"))\n# fmt: on\n\n\n# fmt: off\n\"\"\"A sample tir test case with copy operations for translator\"\"\"\n@tvm.script.ir_module\nclass MultiEthosUCopy:\n    @T.prim_func\n    def main(placeholder_3: T.Buffer[(8192,), \"int8\"], ethosu_conv2d_1: T.Buffer[(2048,), \"int8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_5 = T.buffer_decl([1], \"int32\")\n        placeholder_4 = T.buffer_decl([1], \"uint8\")\n        # body\n        placeholder_global = T.decl_buffer([256], \"uint8\")\n        placeholder_d_global = T.decl_buffer([8], \"int32\")\n        T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_4[0], 256,  placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", placeholder_5[0], 8, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"uint8\", 16, 16, 32, 16, 0, 16, placeholder_3[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"uint8\", 16, 16, 8, 16, 0, 16, ethosu_conv2d_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 0, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 0, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"CLIP\", 0, 255, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n# fmt: on\n\n\n# fmt: off\n\"\"\"A TIR test module of weight streaming\"\"\"\n@tvm.script.ir_module\nclass WeightStreamOnly:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        buffer = T.buffer_decl([1], \"uint8\")\n        buffer_1 = T.buffer_decl([1], \"uint8\")\n        buffer_2 = T.buffer_decl([1], \"uint8\")\n        buffer_3 = T.buffer_decl([1], \"uint8\")\n        buffer_4 = T.buffer_decl([1], \"uint8\")\n        buffer_5 = T.buffer_decl([1], \"uint8\")\n        buffer_6 = T.buffer_decl([1], \"uint8\")\n        buffer_7 = T.buffer_decl([1], \"uint8\")\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True,\n                     \"global_symbol\": \"main\", \"tir.noalias\": True,\n                     \"constants\": {buffer.name: buffer,\n                                       buffer_1.name: buffer_1,\n                                       buffer_2.name: buffer_2,\n                                       buffer_3.name: buffer_3,\n                                       buffer_4.name: buffer_4,\n                                       buffer_5.name: buffer_5,\n                                       buffer_6.name: buffer_6,\n                                       buffer_7.name: buffer_7}})\n        # body\n        placeholder_global_data = T.allocate([128], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        placeholder_global = T.decl_buffer([128], \"uint8\", data=placeholder_global_data)\n        placeholder_d_global_data = T.allocate([32], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        placeholder_d_global = T.decl_buffer([32], \"uint8\", data=placeholder_d_global_data)\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer[0], 128, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_1[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 128, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_2[0], 112, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_3[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 112, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_4[0], 112, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_5[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 112, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_6[0], 112, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_7[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 112, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A TIR test module of weight streaming and direct reading\"\"\"\n@tvm.script.ir_module\nclass MixedRead:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(8192,), \"int8\"], ethosu_write: T.Buffer[(2048,), \"int8\"]) -> None:\n        buffer = T.buffer_decl([1], \"uint8\")\n        buffer_1 = T.buffer_decl([1], \"uint8\")\n        buffer_2 = T.buffer_decl([1], \"uint8\")\n        buffer_3 = T.buffer_decl([1], \"uint8\")\n        buffer_4 = T.buffer_decl([1], \"uint8\")\n        buffer_5 = T.buffer_decl([1], \"uint8\")\n        buffer_6 = T.buffer_decl([1], \"uint8\")\n        buffer_7 = T.buffer_decl([1], \"uint8\")\n        buffer_8 = T.buffer_decl([1], \"uint8\")\n        buffer_9 = T.buffer_decl([1], \"uint8\")\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True,\n                     \"global_symbol\": \"main\", \"tir.noalias\": True,\n                     \"constants\": {buffer.name: buffer,\n                                   buffer_1.name: buffer_1,\n                                   buffer_2.name: buffer_2,\n                                   buffer_3.name: buffer_3,\n                                   buffer_4.name: buffer_4,\n                                   buffer_5.name: buffer_5,\n                                   buffer_6.name: buffer_6,\n                                   buffer_7.name: buffer_7,\n                                   buffer_8.name: buffer_8,\n                                   buffer_9.name: buffer_9}})\n        # body\n        ethosu_write_1_data = T.allocate([4096], \"int8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        ethosu_write_1 = T.buffer_decl([4096], \"int8\", data=ethosu_write_1_data)\n        placeholder_global_data = T.allocate([80], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        placeholder_global = T.buffer_decl([80], \"uint8\", data=placeholder_global_data)\n        placeholder_d_global_data = T.allocate([32], \"uint8\", \"global\", annotations={\"disable_lower_builtin\":True})\n        placeholder_d_global = T.buffer_decl([32], \"uint8\", data=placeholder_d_global_data)\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 32, 16, 0, 16, placeholder[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 512, 32, 1, \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 256, 16, 1, 1, 1, 1, 1, 1, 1, buffer[0], 592, T.int8(-1), T.int8(-1), 12, buffer_1[0], 160, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_2[0], 80, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_3[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[0], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 80, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_4[0], 80, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_5[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[2], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 80, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_6[0], 80, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_7[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[4], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 80, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_8[0], 80, placeholder_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_9[0], 32, placeholder_d_global[0], dtype=\"handle\"))\n        T.evaluate(T.call_extern(\"ethosu_conv2d\", \"int8\", 16, 16, 16, 16, 0, 16, ethosu_write_1[0], 0, 0, 0, T.float32(0.5), 10, \"NHWC\", 256, 16, 1, \"int8\", 16, 16, 2, 16, 0, 16, ethosu_write[6], 0, 0, 0, T.float32(0.25), 14, \"NHWC\", 128, 8, 1, 1, 1, 1, 1, 1, 1, placeholder_global[0], 80, T.int8(-1), T.int8(-1), 12, placeholder_d_global[0], 32, T.int8(-1), T.int8(-1), 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"handle\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_buffer_info_extraction():\n    test_cases = [\n        {\n            # Stimulus\n            \"tir_module\": SingleEthosUConv2D,\n            \"param_dict\": {\n                tvm.tir.Var(\"placeholder_4\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 3, 16], \"uint8\"\n                ),\n                tvm.tir.Var(\"placeholder_5\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [16], \"int32\"\n                ),\n            },\n            # Reference Outputs\n            \"data_buffers\": {\n                \"placeholder_3\": (\n                    [1, 8, 8, 3],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.input_or_output,\n                ),\n                \"ethosu_conv2d_1\": (\n                    [1, 8, 8, 16],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.input_or_output,\n                ),\n            },\n        },\n        {\n            \"tir_module\": MultiEthosUConv2D,\n            \"param_dict\": {\n                tvm.tir.Var(\"placeholder_7\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 3, 32], \"uint8\"\n                ),\n                tvm.tir.Var(\"placeholder_8\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [32], \"int32\"\n                ),\n                tvm.tir.Var(\"placeholder_8\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 32, 8], \"uint8\"\n                ),\n                tvm.tir.Var(\"placeholder_5\", \"uint8\"): np.random.randint(\n                    np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [8], \"int32\"\n                ),\n            },\n            # Reference Outputs\n            \"data_buffers\": {\n                \"placeholder_6\": (\n                    [1, 8, 8, 3],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.input_or_output,\n                ),\n                \"ethosu_conv2d_1\": (\n                    [1, 8, 8, 8],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.input_or_output,\n                ),\n                \"ethosu_conv2d_2\": (\n                    [1024],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.scratch,\n                ),\n                \"ethosu_conv2d_3\": (\n                    [2048],\n                    \"uint8\",\n                    tir_to_cs_translator.BufferType.scratch,\n                ),\n            },\n        },\n    ]\n    for test_case in test_cases:\n        # With Target Hooks the TIR module needs a target attached\n        # and lowered via make unpacked API.\n        tir_mod = test_case[\"tir_module\"]\n        tir_mod[\"main\"] = tir_mod[\"main\"].with_attr(\"target\", tvm.target.Target(\"ethos-u\"))\n        tir_mod = tvm.tir.transform.MakeUnpackedAPI()(tir_mod)\n        buffer_info = tir_to_cs_translator.extract_buffer_info(tir_mod, test_case[\"param_dict\"])\n        for buffer_var, info in buffer_info.items():\n            if buffer_var in test_case[\"param_dict\"].keys():\n                assert (\n                    info.values.flatten() == test_case[\"param_dict\"][buffer_var].flatten()\n                ).all()\n                assert info.dtype == test_case[\"param_dict\"][buffer_var].dtype\n                info.btype == tir_to_cs_translator.BufferType.constant\n            else:\n                buffer_name = buffer_var.name\n                assert info.btype == test_case[\"data_buffers\"][buffer_name][2]\n\n\ndef test_translate_ethosu_conv2d():\n    test_cases = [\n        {\n            # Stimulus\n            \"tir_module\": SingleEthosUConv2D,\n            \"param_dict\": {\n                1: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 3, 16], \"uint8\"\n                ),\n                2: np.random.randint(np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [16], \"int32\"),\n            },\n            # Reference outputs\n            \"ref\": [\n                {\n                    \"ifm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(8, 8, 3),\n                        \"tiles\": vapi.NpuTileBox(8, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.5, 10),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(24, 3, 1),\n                    },\n                    \"ofm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(8, 8, 16),\n                        \"tiles\": vapi.NpuTileBox(8, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.25, 14),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(128, 16, 1),\n                    },\n                    \"kernel\": vapi.NpuKernel(\n                        w=1, h=1, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1\n                    ),\n                    \"padding\": vapi.NpuPadding(top=0, left=0, bottom=0, right=0),\n                    \"activation\": {\n                        \"op\": vapi.NpuActivationOp.NONE_OR_RELU,\n                        \"min\": -3.5,\n                        \"max\": 60.25,\n                    },\n                    \"rounding_mode\": vapi.NpuRoundingMode.TFL,\n                    \"ifm_upscale\": vapi.NpuResamplingMode.NONE,\n                    \"w_zero_point\": 12,\n                }\n            ],\n        },\n        {\n            \"tir_module\": MultiEthosUConv2D,\n            \"param_dict\": {\n                1: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 3, 32], \"uint8\"\n                ),\n                2: np.random.randint(np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [32], \"int32\"),\n                3: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [1, 1, 32, 8], \"uint8\"\n                ),\n                4: np.random.randint(np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [8], \"int32\"),\n            },\n            # Reference Outputs\n            \"ref\": [\n                {\n                    \"ifm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 3),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.5, 10),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(24, 3, 1),\n                    },\n                    \"ofm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 32),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.25, 14),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(256, 32, 1),\n                    },\n                    \"kernel\": vapi.NpuKernel(\n                        w=1, h=1, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1\n                    ),\n                    \"padding\": vapi.NpuPadding(top=0, left=0, bottom=0, right=0),\n                    \"activation\": {\"op\": None},\n                    \"rounding_mode\": vapi.NpuRoundingMode.TFL,\n                    \"ifm_upscale\": vapi.NpuResamplingMode.NONE,\n                    \"w_zero_point\": 12,\n                },\n                {\n                    \"ifm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 32),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.5, 10),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(256, 32, 1),\n                    },\n                    \"ofm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 8),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.25, 14),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(64, 8, 1),\n                    },\n                    \"kernel\": vapi.NpuKernel(\n                        w=1, h=1, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1\n                    ),\n                    \"padding\": vapi.NpuPadding(top=0, left=0, bottom=0, right=0),\n                    \"activation\": {\n                        \"op\": vapi.NpuActivationOp.NONE_OR_RELU,\n                        \"min\": -3.5,\n                        \"max\": 60.25,\n                    },\n                    \"rounding_mode\": vapi.NpuRoundingMode.TFL,\n                    \"ifm_upscale\": vapi.NpuResamplingMode.NONE,\n                    \"w_zero_point\": 12,\n                },\n                {\n                    \"ifm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 3),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.5, 10),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(24, 3, 1),\n                    },\n                    \"ofm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 32),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.25, 14),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(256, 32, 1),\n                    },\n                    \"kernel\": vapi.NpuKernel(\n                        w=1, h=1, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1\n                    ),\n                    \"padding\": vapi.NpuPadding(top=0, left=0, bottom=0, right=0),\n                    \"activation\": {\n                        \"op\": vapi.NpuActivationOp.NONE_OR_RELU,\n                        \"min\": -3.5,\n                        \"max\": 60.25,\n                    },\n                    \"rounding_mode\": vapi.NpuRoundingMode.TFL,\n                    \"ifm_upscale\": vapi.NpuResamplingMode.NONE,\n                    \"w_zero_point\": 12,\n                },\n                {\n                    \"ifm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 32),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.5, 10),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(256, 32, 1),\n                    },\n                    \"ofm\": {\n                        \"data_type\": vapi.NpuDataType.UINT8,\n                        \"shape\": vapi.NpuShape3D(4, 8, 8),\n                        \"tiles\": vapi.NpuTileBox(4, 0, 8, [0, 0, 0, 0]),\n                        \"quantization\": vapi.NpuQuantization(0.25, 14),\n                        \"layout\": vapi.NpuLayout.NHWC,\n                        \"strides\": vapi.NpuShape3D(64, 8, 1),\n                    },\n                    \"kernel\": vapi.NpuKernel(\n                        w=1, h=1, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1\n                    ),\n                    \"padding\": vapi.NpuPadding(top=0, left=0, bottom=0, right=0),\n                    \"activation\": {\n                        \"op\": vapi.NpuActivationOp.NONE_OR_RELU,\n                        \"min\": -3.5,\n                        \"max\": 60.25,\n                    },\n                    \"rounding_mode\": vapi.NpuRoundingMode.TFL,\n                    \"ifm_upscale\": vapi.NpuResamplingMode.NONE,\n                    \"w_zero_point\": 12,\n                },\n            ],\n        },\n    ]\n\n    def extract_ethosu_conv2d_extern_calls(mod):\n        \"\"\"This function will obtain all ethosu_conv2d\n        calls from a NPU TIR module\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            This is a NPU TIR Module\n\n        Returns\n        -------\n        list\n            of tvm.tir.Call objects\n            that are tir extern calls\n            for ethosu_conv2d\n        \"\"\"\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_conv2d_calls = list()\n\n        def populate_ethosu_conv2d_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_conv2d\"\n            ):\n                ethosu_conv2d_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_conv2d_calls)\n        return ethosu_conv2d_calls\n\n    for test_case in test_cases:\n        ethosu_conv2d_calls = extract_ethosu_conv2d_extern_calls(test_case[\"tir_module\"])\n        for idx, ethosu_conv2d_call in enumerate(ethosu_conv2d_calls):\n            ref = test_case[\"ref\"][idx]\n            npu_op, w_zero_point = tir_to_cs_translator.translate_ethosu_conv2d(ethosu_conv2d_call)\n            # Compare IFM\n            assert npu_op.ifm.data_type == ref[\"ifm\"][\"data_type\"]\n            assert npu_op.ifm.shape == ref[\"ifm\"][\"shape\"]\n            assert npu_op.ifm.tiles.height_0 == ref[\"ifm\"][\"tiles\"].height_0\n            assert npu_op.ifm.tiles.height_1 == ref[\"ifm\"][\"tiles\"].height_1\n            assert npu_op.ifm.tiles.width_0 == ref[\"ifm\"][\"tiles\"].width_0\n            assert npu_op.ifm.quantization == ref[\"ifm\"][\"quantization\"]\n            assert npu_op.ifm.layout == ref[\"ifm\"][\"layout\"]\n            assert npu_op.ifm.strides == ref[\"ifm\"][\"strides\"]\n            # Compare OFM\n            assert npu_op.ofm.data_type == ref[\"ofm\"][\"data_type\"]\n            assert npu_op.ofm.shape == ref[\"ofm\"][\"shape\"]\n            assert npu_op.ofm.tiles.height_0 == ref[\"ofm\"][\"tiles\"].height_0\n            assert npu_op.ofm.tiles.height_1 == ref[\"ofm\"][\"tiles\"].height_1\n            assert npu_op.ofm.tiles.width_0 == ref[\"ofm\"][\"tiles\"].width_0\n            assert npu_op.ofm.quantization == ref[\"ofm\"][\"quantization\"]\n            assert npu_op.ofm.layout == ref[\"ofm\"][\"layout\"]\n            assert npu_op.ofm.strides == ref[\"ofm\"][\"strides\"]\n            # Compare kernel and padding\n            assert npu_op.kernel.__dict__ == ref[\"kernel\"].__dict__\n            assert npu_op.padding == ref[\"padding\"]\n            # Compare activation\n            if ref[\"activation\"][\"op\"] is None:\n                assert npu_op.activation is None\n            else:\n                assert npu_op.activation.op_type == ref[\"activation\"][\"op\"]\n                assert npu_op.activation.min == ref[\"activation\"][\"min\"]\n                assert npu_op.activation.max == ref[\"activation\"][\"max\"]\n            # Compare rounding mode\n            assert npu_op.rounding_mode == ref[\"rounding_mode\"]\n            # Compare ifm upscaling\n            assert npu_op.ifm_upscale == ref[\"ifm_upscale\"]\n            # Compare weight quantization parameters\n            assert w_zero_point == ref[\"w_zero_point\"]\n\n\n# fmt: off\n\"\"\"A ethosu_depthwise_conv2d tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuDepthwiseConv2D:\n    @T.prim_func\n    def main(placeholder: T.handle, placeholder_1: T.handle, placeholder_2: T.handle, ethosu_depthwise_conv2d: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_1, [18], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_2, [30], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_3 = T.match_buffer(placeholder, [192], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_depthwise_conv2d_1 = T.match_buffer(ethosu_depthwise_conv2d, [126], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 8, 8, 3, 8, 0, 8, placeholder_3[0], 0, 0, 0, T.float32(0.6), 11, \"NHWC\", 24, 3, 1, \"int8\", 6, 7, 3, 6, 0, 7, ethosu_depthwise_conv2d_1[0], 0, 0, 0, T.float32(0.26), 15, \"NHWC\", 21, 3, 1, 2, 3, 1, 1, 1, 1, placeholder_4[0], 18, 13, placeholder_5[0], 30, 0, 0, 0, 0, \"CLIP\", 15, 105, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_translate_ethosu_depthwise_conv2d():\n    def extract_ethosu_depthwise_conv2d_extern_call(mod):\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_depthwise_conv2d_calls = list()\n\n        def populate_ethosu_depthwise_conv2d_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_depthwise_conv2d\"\n            ):\n                ethosu_depthwise_conv2d_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_depthwise_conv2d_calls)\n        return ethosu_depthwise_conv2d_calls[0]\n\n    depthwise_conv2d_call = extract_ethosu_depthwise_conv2d_extern_call(SingleEthosuDepthwiseConv2D)\n    npu_op, w_zero_point = tir_to_cs_translator.translate_ethosu_depthwise_conv2d(\n        depthwise_conv2d_call\n    )\n\n    assert npu_op.ifm.data_type == vapi.NpuDataType.INT8\n    assert npu_op.ifm.shape == vapi.NpuShape3D(8, 8, 3)\n    assert npu_op.ifm.tiles.height_0 == vapi.NpuTileBox(8, 0, 8, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm.tiles.height_1 == vapi.NpuTileBox(8, 0, 8, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm.tiles.width_0 == vapi.NpuTileBox(8, 0, 8, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm.quantization == pytest.approx(vapi.NpuQuantization(0.6, 11))\n    assert npu_op.ifm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm.strides == vapi.NpuShape3D(24, 3, 1)\n    # Compare OFM\n    assert npu_op.ofm.data_type == vapi.NpuDataType.INT8\n    assert npu_op.ofm.shape == vapi.NpuShape3D(6, 7, 3)\n    assert npu_op.ofm.tiles.height_0 == vapi.NpuTileBox(6, 0, 8, [0, 0, 0, 0]).height_0\n    assert npu_op.ofm.tiles.height_1 == vapi.NpuTileBox(6, 0, 7, [0, 0, 0, 0]).height_1\n    assert npu_op.ofm.tiles.width_0 == vapi.NpuTileBox(6, 0, 7, [0, 0, 0, 0]).width_0\n    assert npu_op.ofm.quantization == pytest.approx(vapi.NpuQuantization(0.26, 15))\n    assert npu_op.ofm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ofm.strides == vapi.NpuShape3D(21, 3, 1)\n    # Compare kernel and padding\n    assert (\n        npu_op.kernel.__dict__\n        == vapi.NpuKernel(w=2, h=3, stride_x=1, stride_y=1, dilation_x=1, dilation_y=1).__dict__\n    )\n    assert npu_op.padding == vapi.NpuPadding(top=0, left=0, bottom=0, right=0)\n    # Compare activation\n    assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    assert npu_op.activation.min == 0\n    assert npu_op.activation.max == pytest.approx(23.4)\n    # Compare rounding mode\n    assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL\n    # Compare ifm upscaling\n    assert npu_op.ifm_upscale == vapi.NpuResamplingMode.NONE\n    # Compare weight quantization parameters\n    assert w_zero_point == 13\n\n\ndef test_translate_ethosu_copy():\n    def extract_ethosu_copy_extern_calls(mod):\n        \"\"\"This function will obtain all ethosu_conv2d\n        calls from a NPU TIR module\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            This is a NPU TIR Module\n\n        Returns\n        -------\n        list\n            of tvm.tir.Call objects\n            that are tir extern calls\n            for ethosu_conv2d\n        \"\"\"\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_copy_calls = list()\n\n        def populate_ethosu_copy_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_copy\"\n            ):\n                ethosu_copy_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_copy_calls)\n        return ethosu_copy_calls\n\n    test_cases = [\n        {\n            # Stimulus\n            \"tir_module\": MultiEthosUCopy,\n            \"param_dict\": {\n                1: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [8, 1, 1, 32], \"uint8\"\n                ),\n                2: np.random.randint(np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [8], \"int32\"),\n            },\n            # Reference outputs\n            \"ref\": [\n                {\n                    \"src\": \"placeholder_4\",\n                    \"dest\": \"placeholder_global\",\n                    \"length\": 256,\n                },\n                {\n                    \"src\": \"placeholder_5\",\n                    \"dest\": \"placeholder_d_global\",\n                    \"length\": 32,\n                },\n            ],\n        },\n    ]\n\n    for test_case in test_cases:\n        ethosu_copy_calls = extract_ethosu_copy_extern_calls(test_case[\"tir_module\"])\n        for idx, ethosu_copy_call in enumerate(ethosu_copy_calls):\n            npu_dma_op = tir_to_cs_translator.translate_ethosu_tir_call_extern(ethosu_copy_call)\n            assert npu_dma_op.src.address.buffer.name == test_case[\"ref\"][idx][\"src\"]\n            assert npu_dma_op.dest.address.buffer.name == test_case[\"ref\"][idx][\"dest\"]\n            assert npu_dma_op.src.length == test_case[\"ref\"][idx][\"length\"]\n            assert npu_dma_op.dest.length == test_case[\"ref\"][idx][\"length\"]\n\n\n# fmt: off\n@tvm.script.ir_module\nclass MixedConstantDatatypes:\n    @T.prim_func\n    def main(placeholder_4: T.Buffer[(2048,), \"int8\"], ethosu_write_1: T.Buffer[(16,), \"int8\"]) -> None:\n        buffer = T.buffer_decl([1], \"uint8\")\n        buffer_1 = T.buffer_decl([1], \"uint8\")\n        buffer_2 = T.buffer_decl([1], \"int16\")\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True,\n                     \"global_symbol\": \"main\", \"tir.noalias\": True,\n                     \"constants\": {buffer.name: buffer,\n                                   buffer_1.name: buffer_1,\n                                   buffer_2.name: buffer_2}})\n        # body\n        placeholder_global = T.decl_buffer([272], \"uint8\")\n        placeholder_d_global = T.decl_buffer([160], \"uint8\")\n        ethosu_write_2 = T.decl_buffer([16], \"int16\")\n        placeholder_d_global_1 = T.decl_buffer([1], \"int16\")\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_1[0], 272, placeholder_global[0], dtype=\"uint8\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer[0], 160, placeholder_d_global[0], dtype=\"uint8\"))\n        T.evaluate(T.call_extern(\"ethosu_depthwise_conv2d\", \"int8\", 8, 16, 16, 8, 0, 16, placeholder_4[0], 0, 0, 0, T.float32(0.0039215548895299435), -128, \"NHWC\", 256, 16, 1, \"int16\", 1, 1, 16, 1, 0, 1, ethosu_write_2[0], 0, 0, 0, T.float32(0.0023205536417663097), -128, \"NHWC\", 1, 1, 1, 16, 8, 1, 1, 1, 1, placeholder_global[0], 272, 0, placeholder_d_global[0], 160, 0, 0, 0, 0, \"NONE\", 0, 0, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"int16\"))\n        T.evaluate(T.call_extern(\"ethosu_copy\", buffer_2[0], 1, placeholder_d_global_1[0], dtype=\"int16\"))\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int16\", 1, 1, 16, 1, 0, 1, ethosu_write_2[0], 0, 0, 0, T.float32(0.0023205536417663097), -128, \"NHWC\", 1, 1, 1, \"int16\", 1, 1, 1, 1, 0, 1, placeholder_d_global_1[0], 0, 0, 0, T.float32(0.0078125018482064768), 0, \"NHWC\", 1, 1, 1, \"int8\", 1, 1, 16, 1, 0, 1, ethosu_write_1[0], 0, 0, 0, T.float32(0.0023205536417663097), -128, \"NHWC\", 1, 1, 1, \"MUL\", 0, \"NONE\", 0, 0, \"NATURAL\", 0, 0, 0, dtype=\"int8\"))\n# fmt: on\n\n\ndef test_assign_addresses():\n    test_cases = [\n        {\n            # Stimulus\n            \"tir_module\": WeightStreamOnly,\n            \"param_dict\": {\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [128], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_1\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_2\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [112], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_3\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_4\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [112], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_5\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_6\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [112], \"uint8\"\n                ),\n                WeightStreamOnly[\"main\"].attrs[\"constants\"][\"buffer_7\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n            },\n        },\n        {\n            # Stimulus\n            \"tir_module\": MixedRead,\n            \"param_dict\": {\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [592], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_1\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [160], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_2\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [80], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_3\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_4\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [80], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_5\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_6\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [80], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_7\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_8\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [80], \"uint8\"\n                ),\n                MixedRead[\"main\"].attrs[\"constants\"][\"buffer_9\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [32], \"uint8\"\n                ),\n            },\n        },\n        {\n            # Stimulus\n            \"tir_module\": MixedConstantDatatypes,\n            \"param_dict\": {\n                MixedConstantDatatypes[\"main\"].attrs[\"constants\"][\"buffer\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [160], \"uint8\"\n                ),\n                MixedConstantDatatypes[\"main\"].attrs[\"constants\"][\"buffer_2\"]: np.random.randint(\n                    np.iinfo(\"int16\").min, np.iinfo(\"int16\").max, [1], \"int16\"\n                ),\n                MixedConstantDatatypes[\"main\"].attrs[\"constants\"][\"buffer_1\"]: np.random.randint(\n                    np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [272], \"uint8\"\n                ),\n            },\n        },\n    ]\n\n    def extract_call_extern_list(mod):\n        \"\"\"This function will obtain all ethosu_conv2d\n        calls from a NPU TIR module\n        Parameters\n        ----------\n        mod : tvm.IRModule\n            This is a NPU TIR Module\n\n        Returns\n        -------\n        list\n            of tvm.tir.Call objects\n            that are tir extern calls\n            for ethosu_conv2d\n        \"\"\"\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        extern_calls = list()\n\n        def populate_extern_calls(stmt):\n            if isinstance(stmt, tvm.tir.Call) and stmt.op.name == \"tir.call_extern\":\n                extern_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_extern_calls)\n        return extern_calls\n\n    def collect_tir_buffer_info(npu_ops):\n        \"\"\"This is run prior to address assigning to collect tir buffer information\n        for verification later on\"\"\"\n        _npu_op_tir_buffers = dict()\n        for npu_op in npu_ops:\n            if isinstance(npu_op, vapi.NpuDmaOperation):\n                _npu_op_tir_buffers[npu_op] = (npu_op.src.address, npu_op.dest.address)\n            elif issubclass(type(npu_op), vapi.NpuBlockOperation):\n                _npu_op_tir_buffers[npu_op] = (\n                    npu_op.ifm.tiles.addresses[0],\n                    npu_op.ofm.tiles.addresses[0],\n                    npu_op.weights,\n                    npu_op.biases,\n                )\n        return _npu_op_tir_buffers\n\n    def _check_buffer(address, region, length, buffer_var):\n        \"\"\"Checks whether the buffer information is valid with\n        original tir buffers.\n        - If its constant, this will check\n          the slice in the constant tensor has the values.\n        - If its scratch, this will check\n          the slice is within scratch and does not have conflicts\n          with other scratch tensors.\n        - If its input/output, this will check the\n          address is zero\n        \"\"\"\n        inverse_region_map = {\n            0: tir_to_cs_translator.BufferType.constant,\n            1: tir_to_cs_translator.BufferType.scratch,\n            3: tir_to_cs_translator.BufferType.input,\n            4: tir_to_cs_translator.BufferType.output,\n        }\n        buffer_type = inverse_region_map[region]\n        buffer_dtype = buffer_var.type_annotation.element_type.dtype\n        dtype_bytes = np.iinfo(np.dtype(buffer_dtype)).bits // 8\n        if buffer_type == tir_to_cs_translator.BufferType.constant:\n            ref = buffer_info[buffer_var].values\n            hex_from = address * dtype_bytes * 2\n            hex_to = hex_from + length * dtype_bytes * 2\n            constant_hex = constant_hex_string[hex_from:hex_to]\n            constant_tensor = np.frombuffer(bytearray.fromhex(constant_hex), dtype=buffer_dtype)\n            np.array_equal(constant_tensor, ref)\n            # Every buffer is adjusted to align to 16 bytes\n            length = util.round_up(length, 16)\n            # Mark these constants are read at least once\n            constant_tensor_read_mask[address : address + length] = np.ones(\n                length, dtype=buffer_dtype\n            )\n        elif buffer_type == tir_to_cs_translator.BufferType.scratch:\n            assert address < tvmbaw_workspace_size\n\n            size_in_bytes = allocate_node_sizes[buffer_var]\n            # Every buffer is adjusted to align to 16 bytes\n            size_in_bytes = util.round_up(size_in_bytes, 16)\n            assert address + size_in_bytes <= tvmbaw_workspace_size\n            # The scratch area should not be used by any other buffer\n            assert not tvmbaw_workspace_mask[address : address + size_in_bytes].any()\n            # The scratch area is marked as used\n            tvmbaw_workspace_mask[address : address + size_in_bytes] = np.ones(\n                size_in_bytes, dtype=\"uint8\"\n            )\n        elif buffer_type == tir_to_cs_translator.BufferType.input:\n            assert address == 0\n        else:\n            assert buffer_type == tir_to_cs_translator.BufferType.output\n            assert address == 0\n\n    def _get_allocate_node_sizes(mod):\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n        _allocate_node_sizes = dict()\n\n        def analyze_remaining_allocates(stmt):\n            if isinstance(stmt, tvm.tir.stmt.Allocate):\n                allocate = stmt\n                pointer_type = allocate.buffer_var.type_annotation\n                storage_scope = pointer_type.storage_scope\n                if storage_scope == \"global\":\n                    dtype_bytes = np.iinfo(np.dtype(allocate.dtype)).bits // 8\n                    size_in_bytes = int(dtype_bytes * np.prod(list(allocate.extents)))\n                    # Every memory address the NPU access have to be 16 byte aligned\n                    size_in_bytes = util.round_up(size_in_bytes, 16)\n                    _allocate_node_sizes[allocate.buffer_var] = size_in_bytes\n\n        tvm.tir.stmt_functor.post_order_visit(primfunc.body, analyze_remaining_allocates)\n        return _allocate_node_sizes\n\n    def verify(npu_ops):\n        \"\"\"This wrapper verifies the allocated addresses matches with original tir buffers\"\"\"\n        checked_buffers = set()\n\n        def check_buffer(address, region, length, buffer_var):\n            if buffer_var not in checked_buffers:\n                _check_buffer(address, region, length, buffer_var)\n                checked_buffers.add(buffer_var)\n\n        for npu_op in npu_ops:\n            if isinstance(npu_op, vapi.NpuDmaOperation):\n                src_tir_buffer_var = npu_op_tir_buffers[npu_op][0].buffer.data\n                check_buffer(\n                    npu_op.src.address, npu_op.src.region, npu_op.src.length, src_tir_buffer_var\n                )\n                dest_tir_load = npu_op_tir_buffers[npu_op][1].buffer.data\n                check_buffer(\n                    npu_op.dest.address,\n                    npu_op.dest.region,\n                    npu_op.dest.length,\n                    dest_tir_load,\n                )\n            elif issubclass(type(npu_op), vapi.NpuBlockOperation):\n                ifm_tir_buffer_var = npu_op_tir_buffers[npu_op][0].buffer.data\n                ifm_length = (\n                    npu_op.ifm.shape.height * npu_op.ifm.shape.width * npu_op.ifm.shape.depth\n                )\n                check_buffer(\n                    npu_op.ifm.tiles.addresses[0],\n                    npu_op.ifm.region,\n                    ifm_length,\n                    ifm_tir_buffer_var,\n                )\n                ofm_tir_buffer_var = npu_op_tir_buffers[npu_op][1].buffer.data\n                ofm_length = (\n                    npu_op.ofm.shape.height * npu_op.ofm.shape.width * npu_op.ofm.shape.depth\n                )\n                check_buffer(\n                    npu_op.ofm.tiles.addresses[0],\n                    npu_op.ofm.region,\n                    ofm_length,\n                    ofm_tir_buffer_var,\n                )\n                for idx, weight in enumerate(npu_op_tir_buffers[npu_op][2]):\n                    assert isinstance(weight, vapi.NpuAddressRange)\n                    check_buffer(\n                        npu_op.weights[idx].address,\n                        npu_op.weights[idx].region,\n                        npu_op.weights[idx].length,\n                        weight.address.buffer.data,\n                    )\n                for idx, bias in enumerate(npu_op_tir_buffers[npu_op][3]):\n                    assert isinstance(bias, vapi.NpuAddressRange)\n                    check_buffer(\n                        npu_op.biases[idx].address,\n                        npu_op.biases[idx].region,\n                        npu_op.biases[idx].length,\n                        bias.address.buffer.data,\n                    )\n\n    for test_case in test_cases:\n        tir_mod = test_case[\"tir_module\"]\n        tir_mod[\"main\"] = tir_mod[\"main\"].with_attr(\"target\", tvm.target.Target(\"ethos-u\"))\n        tir_mod = tvm.tir.transform.MakeUnpackedAPI()(tir_mod)\n        candidate_regions_for_scratch = [5, 2, 1]\n        (\n            scratch_region_map,\n            tvmbaw_workspace_size,\n            _,\n        ) = tir_to_cs_translator.analyze_scratch_memory_acesses(\n            tir_mod, candidate_regions_for_scratch\n        )\n        allocate_node_sizes = _get_allocate_node_sizes(tir_mod)\n        buffer_info = tir_to_cs_translator.extract_buffer_info(tir_mod, test_case[\"param_dict\"])\n        extern_calls = extract_call_extern_list(tir_mod)\n        _npu_ops = list()\n        for extern_call in extern_calls:\n            _npu_ops.append(tir_to_cs_translator.translate_ethosu_tir_call_extern(extern_call))\n        npu_op_tir_buffers = collect_tir_buffer_info(_npu_ops)\n        (_npu_ops, constant_hex_string) = tir_to_cs_translator.assign_addresses(\n            buffer_info, _npu_ops, scratch_region_map\n        )\n        tvmbaw_workspace_mask = np.zeros(tvmbaw_workspace_size, dtype=\"uint8\")\n        constant_tensor_read_mask = np.zeros(len(constant_hex_string) // 2, dtype=\"uint8\")\n        verify(_npu_ops)\n        # This will be only 1 if all allocated scratch is used.\n        assert np.prod(tvmbaw_workspace_mask) == 1\n        # This will be only 1 if all constant tensors is read at least once.\n        assert np.prod(constant_tensor_read_mask) == 1\n\n\n# fmt: off\n\"\"\"A ethosu_pooling tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuPooling:\n    @T.prim_func\n    def main(placeholder: T.handle, placeholder_3: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [75], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_pooling\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_4[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 5, 3, 5, 0, 5, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 15, 3, 1, \"AVG\", 2, 3, 2, 1, 1, 1, 1, 1, 1, 0, \"CLIP\", 10, 100, \"TFL\", \"NONE\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_translate_ethosu_pooling():\n    def extract_ethosu_pooling_extern_call(mod):\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_pooling_calls = list()\n\n        def populate_ethosu_pooling_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_pooling\"\n            ):\n                ethosu_pooling_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_pooling_calls)\n        return ethosu_pooling_calls[0]\n\n    pooling_call = extract_ethosu_pooling_extern_call(SingleEthosuPooling)\n    npu_op = tir_to_cs_translator.translate_ethosu_pooling(pooling_call)\n\n    assert npu_op.ifm.data_type == vapi.NpuDataType.INT8\n    assert npu_op.ifm.shape == vapi.NpuShape3D(5, 9, 3)\n    assert npu_op.ifm.tiles.height_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm.tiles.height_1 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm.tiles.width_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ifm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm.strides == vapi.NpuShape3D(27, 3, 1)\n    # Compare OFM\n    assert npu_op.ofm.data_type == vapi.NpuDataType.INT8\n    assert npu_op.ofm.shape == vapi.NpuShape3D(5, 5, 3)\n    assert npu_op.ofm.tiles.height_0 == vapi.NpuTileBox(5, 0, 5, [0, 0, 0, 0]).height_0\n    assert npu_op.ofm.tiles.height_1 == vapi.NpuTileBox(5, 0, 5, [0, 0, 0, 0]).height_1\n    assert npu_op.ofm.tiles.width_0 == vapi.NpuTileBox(5, 0, 5, [0, 0, 0, 0]).width_0\n    assert npu_op.ofm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ofm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ofm.strides == vapi.NpuShape3D(15, 3, 1)\n    # Compare pooling_type\n    assert npu_op.sub_op_type == vapi.NpuPoolingOp.AVERAGE\n    # Compare kernel and padding\n    assert (\n        npu_op.kernel.__dict__\n        == vapi.NpuKernel(w=2, h=3, stride_x=2, stride_y=1, dilation_x=1, dilation_y=1).__dict__\n    )\n    assert npu_op.padding == vapi.NpuPadding(top=1, left=1, bottom=1, right=0)\n    # Compare activation\n    assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n    assert npu_op.activation.min == 10\n    assert npu_op.activation.max == 100\n    # Compare rounding mode\n    assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL\n    # Compare ifm upscaling\n    assert npu_op.ifm_upscale == vapi.NpuResamplingMode.NONE\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise ADD tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseAdd:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(\n            placeholder, [270], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1\n        )\n        ethosu_write_2 = T.match_buffer(\n            ethosu_write, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1\n        )\n        # body\n        T.evaluate(T.call_extern( \"ethosu_binary_elementwise\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"ADD\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n\n    __tvm_meta__ = None\n# fmt: on\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SUB tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseSub:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"SUB\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise MUL tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMul:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"MUL\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise MIN tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMin:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"MIN\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise Max tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMax:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int8\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"MAX\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SHR tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseShr:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int32\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int32\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int32\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"SHR\", 0, \"NONE\", 0, 0, \"TFL\", 0, 0, 0, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SHL tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseShl:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [270], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [135], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int32\", 5, 9, 3, 5, 0, 9, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int32\", 5, 9, 3, 5, 0, 9, placeholder_2[135], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"int32\", 5, 9, 3, 5, 0, 9, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 27, 3, 1, \"SHL\", 0, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\"operator_type\", [\"ADD\", \"SUB\", \"MUL\", \"MIN\", \"MAX\", \"SHR\", \"SHL\"])\ndef test_translate_ethosu_binary_elementwise(operator_type):\n    if operator_type == \"SHR\" or operator_type == \"SHL\":\n        data_type = vapi.NpuDataType.INT32\n        data_type_bytes = 4\n    else:\n        data_type = vapi.NpuDataType.INT8\n        data_type_bytes = 1\n\n    def extract_ethosu_binary_elementwise_call_extern(mod):\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_binary_elementwise_calls = list()\n\n        def populate_ethosu_binary_elementwise_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_binary_elementwise\"\n            ):\n                ethosu_binary_elementwise_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_binary_elementwise_calls)\n        return ethosu_binary_elementwise_calls[0]\n\n    if operator_type == \"ADD\":\n        binary_elementwise = SingleEthosuBinaryElementwiseAdd\n    elif operator_type == \"SUB\":\n        binary_elementwise = SingleEthosuBinaryElementwiseSub\n    elif operator_type == \"MUL\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMul\n    elif operator_type == \"MIN\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMin\n    elif operator_type == \"MAX\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMax\n    elif operator_type == \"SHR\":\n        binary_elementwise = SingleEthosuBinaryElementwiseShr\n    elif operator_type == \"SHL\":\n        binary_elementwise = SingleEthosuBinaryElementwiseShl\n    binary_elementwise_call = extract_ethosu_binary_elementwise_call_extern(binary_elementwise)\n    npu_op = tir_to_cs_translator.translate_ethosu_binary_elementwise(binary_elementwise_call)\n\n    # Compare IFM\n    assert npu_op.ifm.data_type == data_type\n    assert npu_op.ifm.shape == vapi.NpuShape3D(5, 9, 3)\n    assert npu_op.ifm.tiles.height_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm.tiles.height_1 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm.tiles.width_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ifm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm.strides == vapi.NpuShape3D(\n        27 * data_type_bytes, 3 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare IFM2\n    assert npu_op.ifm2.data_type == data_type\n    assert npu_op.ifm2.shape == vapi.NpuShape3D(5, 9, 3)\n    assert npu_op.ifm2.tiles.height_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm2.tiles.height_1 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm2.tiles.width_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm2.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ifm2.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm2.strides == vapi.NpuShape3D(\n        27 * data_type_bytes, 3 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare OFM\n    assert npu_op.ofm.data_type == data_type\n    assert npu_op.ofm.shape == vapi.NpuShape3D(5, 9, 3)\n    assert npu_op.ofm.tiles.height_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_0\n    assert npu_op.ofm.tiles.height_1 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).height_1\n    assert npu_op.ofm.tiles.width_0 == vapi.NpuTileBox(5, 0, 9, [0, 0, 0, 0]).width_0\n    assert npu_op.ofm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ofm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ofm.strides == vapi.NpuShape3D(\n        27 * data_type_bytes, 3 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare op type\n    if operator_type == \"ADD\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.ADD\n    elif operator_type == \"SUB\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SUB\n    elif operator_type == \"MUL\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MUL\n    elif operator_type == \"MIN\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MIN\n    elif operator_type == \"MAX\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MAX\n    elif operator_type == \"SHR\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SHR\n    elif operator_type == \"SHL\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SHL\n    # Compare reversed_operands\n    assert npu_op.reversed_operands == False\n    # Compare activation\n    if operator_type == \"SHR\":\n        assert npu_op.activation is None\n    else:\n        assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n        assert npu_op.activation.min == 10\n        assert npu_op.activation.max == 100\n    # Compare rounding mode\n    assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise ADD with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseAddBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int8\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int8\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"ADD\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SUB with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseSubBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int8\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int8\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"SUB\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise MUL with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMulBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int8\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int8\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"MUL\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise MIN with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMinBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int8\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int8\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"MIN\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise MAX with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseMaxBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int8\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int8\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int8\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"MAX\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int8\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SHR with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseShrBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int32\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int32\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int32\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"SHR\", 1, \"NONE\", 0, 0, \"TFL\", 0, 0, 0, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n\"\"\"A ethosu_binary_elementwise SHL with broadcasting tir testcase for the translator\"\"\"\n@tvm.script.ir_module\nclass SingleEthosuBinaryElementwiseShlBroadcasting:\n    @T.prim_func\n    def main(placeholder: T.handle, ethosu_write: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [27], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        ethosu_write_2 = T.match_buffer(ethosu_write, [24], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"ethosu_binary_elementwise\", \"int32\", 2, 3, 4, 2, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"int32\", 1, 3, 1, 1, 0, 3, placeholder_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 1, 1, 1, \"int32\", 2, 3, 4, 2, 0, 3, ethosu_write_2[0], 0, 0, 0, T.float32(1.0), 0, \"NHWC\", 12, 4, 1, \"SHL\", 1, \"CLIP\", 10, 100, \"TFL\", 0, 0, 0, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\"operator_type\", [\"ADD\", \"SUB\", \"MUL\", \"MIN\", \"MAX\", \"SHR\", \"SHL\"])\ndef test_translate_ethosu_binary_elementwise_broadcasting(operator_type):\n    if operator_type == \"SHR\" or operator_type == \"SHL\":\n        data_type = vapi.NpuDataType.INT32\n        data_type_bytes = 4\n    else:\n        data_type = vapi.NpuDataType.INT8\n        data_type_bytes = 1\n\n    def extract_ethosu_binary_elementwise_broadcasting_call_extern(mod):\n        # There should only be a single function\n        assert len(mod.functions.items()) == 1\n        primfunc = mod.functions.items()[0][1]\n\n        ethosu_binary_elementwise_calls = list()\n\n        def populate_ethosu_binary_elementwise_calls(stmt):\n            if (\n                isinstance(stmt, tvm.tir.Call)\n                and stmt.op.name == \"tir.call_extern\"\n                and stmt.args[0] == \"ethosu_binary_elementwise\"\n            ):\n                ethosu_binary_elementwise_calls.append(stmt)\n\n        stmt_functor.post_order_visit(primfunc.body, populate_ethosu_binary_elementwise_calls)\n        return ethosu_binary_elementwise_calls[0]\n\n    if operator_type == \"ADD\":\n        binary_elementwise = SingleEthosuBinaryElementwiseAddBroadcasting\n    elif operator_type == \"SUB\":\n        binary_elementwise = SingleEthosuBinaryElementwiseSubBroadcasting\n    elif operator_type == \"MUL\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMulBroadcasting\n    elif operator_type == \"MIN\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMinBroadcasting\n    elif operator_type == \"MAX\":\n        binary_elementwise = SingleEthosuBinaryElementwiseMaxBroadcasting\n    elif operator_type == \"SHR\":\n        binary_elementwise = SingleEthosuBinaryElementwiseShrBroadcasting\n    elif operator_type == \"SHL\":\n        binary_elementwise = SingleEthosuBinaryElementwiseShlBroadcasting\n    binary_elementwise_call = extract_ethosu_binary_elementwise_broadcasting_call_extern(\n        binary_elementwise\n    )\n    npu_op = tir_to_cs_translator.translate_ethosu_binary_elementwise(binary_elementwise_call)\n\n    # Compare IFM\n    assert npu_op.ifm.data_type == data_type\n    assert npu_op.ifm.shape == vapi.NpuShape3D(2, 3, 4)\n    assert npu_op.ifm.tiles.height_0 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm.tiles.height_1 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm.tiles.width_0 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ifm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm.strides == vapi.NpuShape3D(\n        12 * data_type_bytes, 4 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare IFM2\n    assert npu_op.ifm2.data_type == data_type\n    assert npu_op.ifm2.shape == vapi.NpuShape3D(1, 3, 1)\n    assert npu_op.ifm2.tiles.height_0 == vapi.NpuTileBox(1, 0, 3, [0, 0, 0, 0]).height_0\n    assert npu_op.ifm2.tiles.height_1 == vapi.NpuTileBox(1, 0, 3, [0, 0, 0, 0]).height_1\n    assert npu_op.ifm2.tiles.width_0 == vapi.NpuTileBox(1, 0, 3, [0, 0, 0, 0]).width_0\n    assert npu_op.ifm2.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ifm2.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ifm2.strides == vapi.NpuShape3D(\n        1 * data_type_bytes, 1 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare OFM\n    assert npu_op.ofm.data_type == data_type\n    assert npu_op.ofm.shape == vapi.NpuShape3D(2, 3, 4)\n    assert npu_op.ofm.tiles.height_0 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).height_0\n    assert npu_op.ofm.tiles.height_1 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).height_1\n    assert npu_op.ofm.tiles.width_0 == vapi.NpuTileBox(2, 0, 3, [0, 0, 0, 0]).width_0\n    assert npu_op.ofm.quantization == vapi.NpuQuantization(1.0, 0)\n    assert npu_op.ofm.layout == vapi.NpuLayout.NHWC\n    assert npu_op.ofm.strides == vapi.NpuShape3D(\n        12 * data_type_bytes, 4 * data_type_bytes, 1 * data_type_bytes\n    )\n    # Compare op type\n    if operator_type == \"ADD\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.ADD\n    elif operator_type == \"SUB\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SUB\n    elif operator_type == \"MUL\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MUL\n    elif operator_type == \"MIN\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MIN\n    elif operator_type == \"MAX\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.MAX\n    elif operator_type == \"SHR\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SHR\n    elif operator_type == \"SHL\":\n        assert npu_op.sub_op_type == vapi.NpuElementWiseOp.SHL\n    # Compare reversed_operands\n    assert npu_op.reversed_operands == True\n    # Compare activation\n    if operator_type == \"SHR\":\n        assert npu_op.activation is None\n    else:\n        assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU\n        assert npu_op.activation.min == 10\n        assert npu_op.activation.max == 100\n    # Compare rounding mode\n    assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_type_inference.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\n\nfrom tvm import relay, TVMError\nfrom tvm.relay.testing import run_opt_pass\nfrom .infra import make_ethosu_conv2d\nfrom .infra import make_ethosu_depthwise_conv2d\nfrom .infra import make_ethosu_pooling\nfrom .infra import make_ethosu_binary_elementwise\nfrom .infra import make_ethosu_identity\nfrom .infra import make_ethosu_unary_elementwise\n\n\n@pytest.mark.parametrize(\n    [\"ifm_shape\", \"ifm_layout\"], [((1, 56, 72, 55), \"NHWC\"), ((1, 56, 4, 72, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\n    \"ofm_shape,ofm_layout\", [((1, 54, 38, 122), \"NHWC\"), ((1, 54, 8, 38, 16), \"NHCWB16\")]\n)\ndef test_ethosu_conv2d_type_inference(\n    ifm_shape,\n    ifm_layout,\n    ofm_shape,\n    ofm_layout,\n):\n    ifm_channels = 55\n    ofm_channels = 122\n    kernel_shape = (3, 2)\n    padding = (0, 1, 2, 3)\n    strides = (1, 2)\n    dilation = (2, 1)\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    conv2d = make_ethosu_conv2d(\n        ifm,\n        ifm_channels,\n        ofm_channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    func = relay.Function([ifm], conv2d)\n    func = run_opt_pass(func, relay.transform.InferType())\n    assert tuple(func.body.checked_type.shape) == ofm_shape\n\n\n@pytest.mark.parametrize(\n    \"ifm_dtype,weight_dtype,scale_bias_dtype\",\n    [(\"float32\", \"int8\", \"uint8\"), (\"int8\", \"float32\", \"uint8\"), (\"int8\", \"int8\", \"float32\")],\n)\ndef test_ethosu_conv2d_invalid_dtypes(ifm_dtype, weight_dtype, scale_bias_dtype):\n    ifm_channels = 55\n    ofm_channels = 122\n    kernel_shape = (3, 2)\n    padding = (0, 1, 2, 3)\n    strides = (1, 2)\n    dilation = (2, 1)\n    ifm = relay.var(\"ifm\", shape=(1, 56, 72, 55), dtype=ifm_dtype)\n    conv2d = make_ethosu_conv2d(\n        ifm,\n        ifm_channels,\n        ofm_channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        weight_dtype=weight_dtype,\n        scale_bias_dtype=scale_bias_dtype,\n    )\n    func = relay.Function([ifm], conv2d)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_conv2d_invalid_upscale_method():\n    invalid_upscale_method = \"FOO\"\n    ifm_channels = 55\n    ofm_channels = 122\n    kernel_shape = (3, 2)\n    padding = (0, 1, 2, 3)\n    strides = (1, 2)\n    dilation = (2, 1)\n    ifm = relay.var(\"ifm\", shape=(1, 56, 72, 55), dtype=\"int8\")\n    conv2d = make_ethosu_conv2d(\n        ifm,\n        ifm_channels,\n        ofm_channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        weight_dtype=\"int8\",\n        scale_bias_dtype=\"uint8\",\n        upscale=invalid_upscale_method,\n    )\n    func = relay.Function([ifm], conv2d)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm_layout\", [((1, 46, 71, 55), \"NHWC\"), ((1, 46, 4, 71, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\n    \"ofm_shape, ofm_layout\", [((1, 44, 37, 55), \"NHWC\"), ((1, 44, 4, 37, 16), \"NHCWB16\")]\n)\ndef test_ethosu_depthwise_conv2d_type_inference(\n    ifm_shape,\n    ifm_layout,\n    ofm_shape,\n    ofm_layout,\n):\n    channels = 55\n    kernel_shape = (3, 2)\n    padding = (0, 1, 2, 3)\n    strides = (1, 2)\n    dilation = (2, 1)\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=\"int8\")\n    depthwise_conv2d = make_ethosu_depthwise_conv2d(\n        ifm,\n        channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    func = relay.Function([ifm], depthwise_conv2d)\n    func = run_opt_pass(func, relay.transform.InferType())\n    assert tuple(func.body.checked_type.shape) == ofm_shape\n\n\n@pytest.mark.parametrize(\n    \"ifm_dtype,weight_dtype,scale_bias_dtype\",\n    [(\"float32\", \"int8\", \"uint8\"), (\"int8\", \"float32\", \"uint8\"), (\"int8\", \"int8\", \"float32\")],\n)\ndef test_ethosu_depthwise_conv2d_invalid_dtypes(ifm_dtype, weight_dtype, scale_bias_dtype):\n    channels = 55\n    kernel_shape = (3, 2)\n    padding = (0, 1, 2, 3)\n    strides = (1, 2)\n    dilation = (2, 1)\n    dilation = (2, 1)\n    ifm = relay.var(\"ifm\", shape=(1, 56, 72, 55), dtype=ifm_dtype)\n    depthwise_conv2d = make_ethosu_depthwise_conv2d(\n        ifm,\n        channels,\n        kernel_shape,\n        padding,\n        strides,\n        dilation,\n        weight_dtype=weight_dtype,\n        scale_bias_dtype=scale_bias_dtype,\n    )\n    func = relay.Function([ifm], depthwise_conv2d)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm_layout\", [((1, 56, 72, 55), \"NHWC\"), ((1, 56, 4, 72, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\n    \"ofm_shape, ofm_layout\", [((1, 56, 38, 55), \"NHWC\"), ((1, 56, 4, 38, 16), \"NHCWB16\")]\n)\ndef test_ethosu_pooling_type_inference(\n    ifm_shape,\n    ifm_layout,\n    ofm_shape,\n    ofm_layout,\n):\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    pooling_type = \"AVG\"\n    pool_shape = (3, 2)\n    ofm_channels = 55\n    strides = (1, 2)\n    padding = (0, 1, 2, 3)\n    pooling = make_ethosu_pooling(\n        ifm,\n        pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    func = relay.Function([ifm], pooling)\n    func = run_opt_pass(func, relay.transform.InferType())\n    assert tuple(func.body.checked_type.shape) == ofm_shape\n    assert func.body.checked_type.dtype == dtype\n\n\ndef test_ethosu_pooling_invalid_pooling_type():\n    invalid_pooling_type = \"A\"\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=[1, 56, 72, 55], dtype=dtype)\n    pool_shape = (3, 2)\n    ofm_channels = 55\n    strides = (1, 2)\n    padding = (0, 1, 2, 3)\n    pooling = make_ethosu_pooling(\n        ifm,\n        invalid_pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n    )\n    func = relay.Function([ifm], pooling)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_pooling_invalid_dtype():\n    invalid_dtype = \"int32\"\n    ifm = relay.var(\"ifm\", shape=[1, 56, 72, 55], dtype=invalid_dtype)\n    pooling_type = \"MAX\"\n    pool_shape = (3, 2)\n    ofm_channels = 55\n    strides = (1, 2)\n    padding = (0, 1, 2, 3)\n    pooling = make_ethosu_pooling(\n        ifm,\n        pooling_type,\n        pool_shape,\n        ofm_channels,\n        strides,\n        padding,\n    )\n    func = relay.Function([ifm], pooling)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_pooling_invalid_upscale_method():\n    invalid_upscale_method = \"FOO\"\n    ifm = relay.var(\"ifm\", shape=[1, 56, 72, 55], dtype=\"int8\")\n    pooling = make_ethosu_pooling(\n        ifm,\n        \"MAX\",\n        (3, 2),\n        55,\n        (1, 2),\n        (0, 1, 2, 3),\n        upscale=invalid_upscale_method,\n    )\n    func = relay.Function([ifm], pooling)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm_layout\", [((1, 4, 5, 33), \"NHWC\"), ((1, 4, 3, 5, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\n    \"ofm_shape, ofm_layout\", [((1, 4, 5, 33), \"NHWC\"), ((1, 4, 3, 5, 16), \"NHCWB16\")]\n)\ndef test_ethosu_binary_elementwise_type_inference(\n    ifm_shape,\n    ifm_layout,\n    ofm_shape,\n    ofm_layout,\n):\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm_shape, dtype=dtype)\n    operator_type = \"ADD\"\n    ifm_channels, ifm2_channels = 33, 33\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        dtype,\n        ifm_layout=ifm_layout,\n        ifm2_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    func = relay.Function([ifm, ifm2], binary_elementwise)\n    func = run_opt_pass(func, relay.transform.InferType())\n    assert tuple(func.body.checked_type.shape) == ofm_shape\n    assert func.body.checked_type.dtype == dtype\n\n\ndef test_ethosu_binary_elementwise_invalid_operator_type():\n    invalid_operator_type = \"A\"\n    ifm_shape = [1, 4, 5, 33]\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm_shape, dtype=dtype)\n    ifm_channels, ifm2_channels = 33, 33\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        invalid_operator_type,\n        dtype,\n    )\n    func = relay.Function([ifm, ifm2], binary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_binary_elementwise_invalid_data_types():\n    dtype = \"int8\"\n    dtype2 = \"int32\"\n    operator_type = \"ADD\"\n    ifm_shape = [1, 4, 5, 33]\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm_shape, dtype=dtype2)\n    ifm_channels, ifm2_channels = 33, 33\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        dtype,\n    )\n    func = relay.Function([ifm, ifm2], binary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\"operator_type\", [\"MIN\", \"MAX\"])\ndef test_ethosu_binary_elementwise_min_max_invalid_data_type(operator_type):\n    invalid_dtype = \"int32\"\n    ifm_shape = [1, 4, 5, 33]\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=invalid_dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm_shape, dtype=invalid_dtype)\n    ifm_channels, ifm2_channels = 33, 33\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        invalid_dtype,\n    )\n    func = relay.Function([ifm, ifm2], binary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\"invalid_dtype\", [\"int8\", \"uint8\"])\n@pytest.mark.parametrize(\"operator_type\", [\"RHS\", \"SHR\"])\ndef test_ethosu_binary_elementwise_shift_invalid_data_type(invalid_dtype, operator_type):\n    ifm_shape = [1, 4, 5, 33]\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=invalid_dtype)\n    ifm2 = relay.var(\"ifm2\", shape=ifm_shape, dtype=invalid_dtype)\n    ifm_channels, ifm2_channels = 33, 33\n    binary_elementwise = make_ethosu_binary_elementwise(\n        ifm,\n        ifm2,\n        ifm_channels,\n        ifm2_channels,\n        operator_type,\n        invalid_dtype,\n    )\n    func = relay.Function([ifm, ifm2], binary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\"shape\", [(1, 56, 72, 55), (241, 7, 755), (28, 44), (5003,)])\ndef test_ethosu_identity_type_inference(shape):\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=shape, dtype=dtype)\n    identity = make_ethosu_identity(ifm)\n    func = relay.Function([ifm], identity)\n    func = run_opt_pass(func, relay.transform.InferType())\n    assert tuple(func.body.checked_type.shape) == shape\n    assert func.body.checked_type.dtype == dtype\n\n\ndef test_ethosu_identity_invalid_shape():\n    invalid_shape = [1, 2, 3, 4, 5]\n    dtype = \"int8\"\n    ifm = relay.var(\"ifm\", shape=invalid_shape, dtype=dtype)\n\n    identity = make_ethosu_identity(ifm)\n    func = relay.Function([ifm], identity)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_identity_invalid_dtype():\n    invalid_dtype = \"int32\"\n    ifm = relay.var(\"ifm\", shape=[6000], dtype=invalid_dtype)\n\n    identity = make_ethosu_identity(ifm)\n    func = relay.Function([ifm], identity)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\n@pytest.mark.parametrize(\n    \"ifm_shape, ifm_layout\", [((1, 4, 5, 33), \"NHWC\"), ((1, 4, 3, 5, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\n    \"ofm_shape, ofm_layout\", [((1, 4, 5, 33), \"NHWC\"), ((1, 4, 3, 5, 16), \"NHCWB16\")]\n)\n@pytest.mark.parametrize(\"operator_type, data_type\", [(\"ABS\", \"int8\"), (\"CLZ\", \"int32\")])\ndef test_ethosu_unary_elementwise_type_inference(\n    ifm_shape,\n    ifm_layout,\n    ofm_shape,\n    ofm_layout,\n    operator_type,\n    data_type,\n):\n    ifm = relay.var(\"ifm\", shape=ifm_shape, dtype=data_type)\n    ofm_channels = 33\n    unary_elementwise = make_ethosu_unary_elementwise(\n        ifm,\n        ofm_channels,\n        operator_type,\n        ifm_layout=ifm_layout,\n        ofm_layout=ofm_layout,\n    )\n    f = relay.Function([ifm], unary_elementwise)\n    f = run_opt_pass(f, relay.transform.InferType())\n    assert tuple(f.body.checked_type.shape) == ofm_shape\n\n\ndef test_ethosu_unary_elementwise_invalid_operator_type():\n    ifm = relay.var(\"ifm\", shape=(1, 3, 7, 12), dtype=\"int8\")\n    invalid_op_type = \"ABBBS\"\n    unary_elementwise = make_ethosu_unary_elementwise(\n        ifm,\n        12,\n        invalid_op_type,\n    )\n    func = relay.Function([ifm], unary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\ndef test_ethosu_unary_elementwise_invalid_dtype():\n    invalid_dtype = \"int32\"\n    ifm = relay.var(\"ifm\", shape=(1, 5, 15, 25), dtype=invalid_dtype)\n\n    unary_elementwise = make_ethosu_unary_elementwise(\n        ifm,\n        25,\n        \"ABS\",\n    )\n    func = relay.Function([ifm], unary_elementwise)\n    with pytest.raises(TVMError):\n        run_opt_pass(func, relay.transform.InferType())\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_ethosu/test_vela_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\npytest.importorskip(\"ethosu.vela\")\nimport numpy as np\nfrom ethosu.vela import api as vapi\nfrom unittest.mock import patch\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\nfrom tvm.relay.backend.contrib.ethosu import vela_api\nimport tvm.relay.backend.contrib.ethosu.tir_to_cs_translator as tirtocs\n\nACCEL_TYPES = [\n    vapi.NpuAccelerator.Ethos_U55_256,\n    vapi.NpuAccelerator.Ethos_U55_128,\n    vapi.NpuAccelerator.Ethos_U55_64,\n    vapi.NpuAccelerator.Ethos_U55_32,\n]\n\n\n\"\"\"Test case 1\"\"\"\n\n\n@tvm.script.ir_module\nclass Module1:\n    @T.prim_func\n    def main(\n        placeholder: T.handle,\n        placeholder_1: T.handle,\n        placeholder_2: T.handle,\n        ethosu_conv2d: T.handle,\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_3 = T.match_buffer(\n            placeholder, [192], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        placeholder_4 = T.match_buffer(\n            placeholder_1, [48], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        placeholder_5 = T.match_buffer(\n            placeholder_2, [16], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1\n        )\n        ethosu_conv2d_1 = T.match_buffer(\n            ethosu_conv2d, [1024], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        # body\n        T.evaluate(\n            T.call_extern(\n                \"ethosu_conv2d\",\n                \"uint8\",\n                8,\n                8,\n                3,\n                8,\n                0,\n                8,\n                placeholder_3[0],\n                0,\n                0,\n                0,\n                T.float32(0.5),\n                10,\n                \"NHWC\",\n                24,\n                3,\n                1,\n                \"uint8\",\n                8,\n                8,\n                16,\n                8,\n                0,\n                8,\n                ethosu_conv2d_1[0],\n                0,\n                0,\n                0,\n                T.float32(0.25),\n                14,\n                \"NHWC\",\n                128,\n                16,\n                1,\n                1,\n                1,\n                1,\n                1,\n                1,\n                1,\n                placeholder_4[0],\n                0,\n                12,\n                placeholder_5[0],\n                0,\n                0,\n                0,\n                0,\n                0,\n                \"CLIP\",\n                0,\n                0,\n                \"TFL\",\n                \"NONE\",\n                dtype=\"uint8\",\n            )\n        )\n\n    __tvm_meta__ = None\n\n\n\"\"\"Test case 2 with per-channel quantization\"\"\"\n\n\n@tvm.script.ir_module\nclass Module2:\n    @T.prim_func\n    def main(\n        placeholder: T.handle,\n        placeholder_1: T.handle,\n        placeholder_2: T.handle,\n        placeholder_6: T.handle,\n        ethosu_conv2d: T.handle,\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        placeholder_3 = T.match_buffer(\n            placeholder, [192], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        placeholder_4 = T.match_buffer(\n            placeholder_1, [48], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        placeholder_5 = T.match_buffer(\n            placeholder_2, [16], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1\n        )\n        # Per-channel weight scales\n        placeholder_7 = T.match_buffer(\n            placeholder_6, [16], dtype=\"float32\", elem_offset=0, align=64, offset_factor=1\n        )\n        ethosu_conv2d_1 = T.match_buffer(\n            ethosu_conv2d, [1024], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1\n        )\n        # body\n        T.evaluate(\n            T.call_extern(\n                \"ethosu_conv2d\",\n                \"uint8\",\n                8,\n                8,\n                3,\n                8,\n                0,\n                8,\n                placeholder_3[0],\n                0,\n                0,\n                0,\n                T.float32(0.5),\n                10,\n                \"NHWC\",\n                24,\n                3,\n                1,\n                \"uint8\",\n                8,\n                8,\n                16,\n                8,\n                0,\n                8,\n                ethosu_conv2d_1[0],\n                0,\n                0,\n                0,\n                T.float32(0.25),\n                14,\n                \"NHWC\",\n                128,\n                16,\n                1,\n                1,\n                1,\n                1,\n                1,\n                1,\n                1,\n                placeholder_4[0],\n                0,\n                12,\n                placeholder_5[0],\n                0,\n                0,\n                0,\n                0,\n                0,\n                \"CLIP\",\n                0,\n                0,\n                \"TFL\",\n                \"NONE\",\n                dtype=\"uint8\",\n            )\n        )\n\n    __tvm_meta__ = None\n\n\ndef test_get_optimal_block_config():\n    block_configs_cases = [\n        {\n            \"test\": [\n                vapi.NpuShape3D(10, 20, 8),\n                vapi.NpuShape3D(10, 30, 16),\n                vapi.NpuShape3D(10, 40, 32),\n            ],\n            \"ref\": vapi.NpuShape3D(10, 40, 32),\n        },\n        {\n            \"test\": [\n                vapi.NpuShape3D(10, 20, 8),\n                vapi.NpuShape3D(10, 50, 32),\n                vapi.NpuShape3D(10, 40, 32),\n            ],\n            \"ref\": vapi.NpuShape3D(10, 50, 32),\n        },\n        {\n            \"test\": [\n                vapi.NpuShape3D(50, 50, 8),\n                vapi.NpuShape3D(10, 30, 32),\n                vapi.NpuShape3D(8, 8, 64),\n            ],\n            \"ref\": vapi.NpuShape3D(8, 8, 64),\n        },\n    ]\n\n    for test_case in block_configs_cases:\n        assert vela_api._get_optimal_block_config(test_case[\"test\"]) == test_case[\"ref\"]\n\n\n@pytest.mark.parametrize(\n    \"block_config_str, expected_block_config\",\n    [(\"4x4x8\", vapi.NpuShape3D(4, 4, 8)), (\"3x7x16\", vapi.NpuShape3D(3, 7, 16))],\n)\ndef test_force_block_config(block_config_str, expected_block_config):\n    config = {\n        \"dev_force_block_config\": block_config_str,\n    }\n    with tvm.transform.PassContext(config={\"relay.ext.ethos-u.options\": config}):\n        block_config = vela_api.get_optimal_block_config(None, vapi.NpuAccelerator.Ethos_U55_128)\n        assert block_config == expected_block_config\n\n\ndef test_compress_weights():\n    test_vecs = [\n        {\n            # Stimulus\n            \"accel\": vapi.NpuAccelerator.Ethos_U55_256,\n            \"block_depth\": 8,\n            \"ifm_dtype\": np.uint8,\n            \"shape\": (3, 3, 16, 64),\n            \"layout\": \"HWIO\",\n            \"zero_point\": np.int64(134),\n            \"dilation\": (1, 1),\n            \"is_depthwise\": False,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.PART_KERNEL_FIRST,\n        },\n        {\n            # Stimulus\n            \"accel\": vapi.NpuAccelerator.Ethos_U55_256,\n            \"block_depth\": 8,\n            \"ifm_dtype\": np.uint8,\n            \"shape\": (3, 3, 32, 64),\n            \"layout\": \"HWIO\",\n            \"zero_point\": np.int64(134),\n            \"dilation\": (1, 1),\n            \"is_depthwise\": False,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.DEPTH_FIRST,\n        },\n        {\n            # Stimulus\n            \"accel\": vapi.NpuAccelerator.Ethos_U55_256,\n            \"block_depth\": 8,\n            \"ifm_dtype\": np.int16,\n            \"shape\": (3, 3, 16, 64),\n            \"layout\": \"HWIO\",\n            \"zero_point\": np.int64(134),\n            \"dilation\": (1, 1),\n            \"is_depthwise\": False,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.DEPTH_FIRST,\n        },\n        # Pass-through value check\n        {\n            # Stimulus\n            \"accel\": vapi.NpuAccelerator.Ethos_U55_128,\n            \"block_depth\": 16,\n            \"ifm_dtype\": np.uint8,\n            \"shape\": (243, 152, 7, 1),\n            \"layout\": \"HWOI\",\n            \"zero_point\": np.int64(110),\n            \"dilation\": (2, 2),\n            \"is_depthwise\": True,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.DEPTH_FIRST,\n        },\n        {\n            # Stimulus\n            \"accel\": vapi.NpuAccelerator.Ethos_U55_128,\n            \"block_depth\": 32,\n            \"ifm_dtype\": np.uint8,\n            \"shape\": (64, 67, 35, 8),\n            \"layout\": \"OHWI\",\n            \"zero_point\": np.int64(100),\n            \"dilation\": (1, 2),\n            \"is_depthwise\": False,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.PART_KERNEL_FIRST,\n        },\n    ]\n\n    def verify(test_vec, mock_obj):\n        layout_transform_indices = {\n            \"HWIO\": (3, 0, 1, 2),\n            \"HWOI\": (2, 0, 1, 3),\n            \"OHWI\": (0, 1, 2, 3),\n        }\n\n        assert mock_obj\n        mock_obj.assert_called_once()\n        assert mock_obj.call_args[1][\"accelerator\"] == test_vec[\"accel\"]\n        assert mock_obj.call_args[1][\"accelerator\"] == test_vec[\"accel\"]\n        ishape = test_vec[\"shape\"]\n        shape_owhi = (\n            ishape[layout_transform_indices[test_vec[\"layout\"]][0]],\n            ishape[layout_transform_indices[test_vec[\"layout\"]][1]],\n            ishape[layout_transform_indices[test_vec[\"layout\"]][2]],\n            ishape[layout_transform_indices[test_vec[\"layout\"]][3]],\n        )\n        assert mock_obj.call_args[1][\"weights_volume\"].shape == shape_owhi\n        assert mock_obj.call_args[1][\"dilation_xy\"] == test_vec[\"dilation\"]\n        assert mock_obj.call_args[1][\"ifm_bitdepth\"] == np.iinfo(test_vec[\"ifm_dtype\"]).bits\n        assert mock_obj.call_args[1][\"ofm_block_depth\"] == test_vec[\"block_depth\"]\n        assert mock_obj.call_args[1][\"is_depthwise\"] == test_vec[\"is_depthwise\"]\n        assert mock_obj.call_args[1][\"block_traversal\"] == test_vec[\"block_traversal\"]\n\n    def create_mock(test_vec):\n        with patch(\"ethosu.vela.api.npu_encode_weights\") as mock_npu_encode_weights:\n            ifm_bitdepth = np.iinfo(test_vec[\"ifm_dtype\"]).bits\n            ifm_dtype = test_vec[\"ifm_dtype\"]\n            max = np.iinfo(ifm_dtype).max\n            min = np.iinfo(ifm_dtype).min\n            values = np.random.randint(min, max, test_vec[\"shape\"], ifm_dtype)\n            vela_api.compress_weights(\n                weights=values,\n                weights_zp=test_vec[\"zero_point\"],\n                weights_layout=test_vec[\"layout\"],\n                ifm_bitdepth=ifm_bitdepth,\n                block_depth=test_vec[\"block_depth\"],\n                dilation=test_vec[\"dilation\"],\n                accel_config=test_vec[\"accel\"],\n                is_depthwise=test_vec[\"is_depthwise\"],\n            )\n            return mock_npu_encode_weights\n\n    for tv in test_vecs:\n        mock_obj = create_mock(tv)\n        verify(tv, mock_obj)\n\n\ndef test_pack_biases():\n    test_vecs = [\n        {\n            # Stimulus\n            \"bias_length\": 3,\n            \"ifm_scale\": np.single(1.11111111),\n            \"ifm_dtype\": np.uint8,\n            \"weight_scales\": np.array(\n                [np.single(0.91111111), np.single(1.01111111), np.single(1.11111111)]\n            ),\n            \"ofm_scale\": np.single(1.2),\n            \"is_activation_tanh_or_sigmoid\": False,\n            # Reference outputs\n            \"hw_scales\": (1811663288, 2010504240, 1104672703),\n            \"hw_shifts\": (31, 31, 30),\n        },\n        {\n            # Stimulus\n            \"bias_length\": 3,\n            \"ifm_scale\": np.single(1.11111111),\n            \"ifm_dtype\": np.int8,\n            \"weight_scales\": np.array(\n                [np.single(0.91111111), np.single(1.01111111), np.single(1.11111111)]\n            ),\n            \"ofm_scale\": np.single(1.2),\n            \"is_activation_tanh_or_sigmoid\": False,\n            # Reference outputs\n            \"hw_scales\": (1811663185, 2010504312, 1104672720),\n            \"hw_shifts\": (31, 31, 30),\n        },\n        {\n            # Stimulus\n            \"bias_length\": 3,\n            \"ifm_scale\": np.single(1.11111111),\n            \"ifm_dtype\": np.int16,\n            \"weight_scales\": np.array(\n                [np.single(0.91111111), np.single(1.01111111), np.single(1.11111111)]\n            ),\n            \"ofm_scale\": np.single(1.2),\n            \"is_activation_tanh_or_sigmoid\": False,\n            # Reference outputs\n            \"hw_scales\": (27644, 30678, 16856),\n            \"hw_shifts\": (15, 15, 14),\n        },\n    ]\n\n    def verify(test_vec, mock_obj, packed_biases):\n        assert mock_obj\n        for idx, val in enumerate(test_vec[\"bias_values\"]):\n            assert val == mock_obj.call_args_list[idx][0][0]\n            assert test_vec[\"hw_scales\"][idx] == mock_obj.call_args_list[idx][0][1]\n            assert test_vec[\"hw_shifts\"][idx] == mock_obj.call_args_list[idx][0][2]\n\n    def create_mock(test_vec):\n        with patch(\"ethosu.vela.api.npu_encode_bias\") as mock_npu_encode_bias:\n            mock_npu_encode_bias.return_value = bytearray(10)\n            ifm_dtype = test_vec[\"ifm_dtype\"]\n            max = np.iinfo(ifm_dtype).max\n            min = np.iinfo(ifm_dtype).min\n            # tvm will always create biases in int32\n            biases = np.random.randint(min, max, test_vec[\"bias_length\"], np.int32)\n            packed_biases = vela_api.pack_biases(\n                biases=biases,\n                ifm_scale=test_vec[\"ifm_scale\"],\n                ifm_dtype=test_vec[\"ifm_dtype\"],\n                weight_scales=test_vec[\"weight_scales\"],\n                ofm_scale=test_vec[\"ofm_scale\"],\n                is_activation_tanh_or_sigmoid=test_vec[\"is_activation_tanh_or_sigmoid\"],\n            )\n            test_vec[\"bias_values\"] = biases\n            return mock_npu_encode_bias, packed_biases\n        return None\n\n    for _test_vec in test_vecs:\n        mock_obj, packed_biases = create_mock(_test_vec)\n        verify(_test_vec, mock_obj, packed_biases)\n\n\ndef extract_ethosu_conv2d_extern_calls(mod):\n    \"\"\"This function will obtain all ethosu_conv2d\n    calls from a NPU TIR module\n\n    Parameters\n    ----------\n    mod : tvm.IRModule\n        This is a NPU TIR Module\n\n    Returns\n    -------\n    list\n        List of tvm.tir.Call objects\n        that are tir extern calls\n        for ethosu_conv2d\n    \"\"\"\n    # There should only be a single function\n    assert len(mod.functions.items()) == 1\n    primfunc = mod.functions.items()[0][1]\n\n    ethosu_conv2d_calls = list()\n\n    def populate_ethosu_conv2d_calls(stmt):\n        if (\n            isinstance(stmt, tvm.tir.Call)\n            and stmt.op.name == \"T.call_extern\"\n            and stmt.args[0] == \"ethosu_conv2d\"\n        ):\n            ethosu_conv2d_calls.append(stmt)\n\n    stmt_functor.post_order_visit(primfunc.body, populate_ethosu_conv2d_calls)\n    return ethosu_conv2d_calls\n\n\n@pytest.mark.parametrize(\n    \"accel\",\n    ACCEL_TYPES,\n)\ndef test_encode_weights(accel):\n    test_vecs = [\n        {\n            # Stimulus\n            \"tir_module\": Module1,\n            \"param_dict\": {\n                1: np.random.randint(np.iinfo(\"uint8\").min, np.iinfo(\"uint8\").max, [48], \"uint8\"),\n                2: np.random.randint(np.iinfo(\"int32\").min, np.iinfo(\"int32\").max, [16], \"int32\"),\n            },\n            \"accel_type\": accel,\n            # Reference outputs\n            \"block_traversal\": vapi.NpuBlockTraversal.PART_KERNEL_FIRST,\n        },\n    ]\n\n    def create_mock(test_vec):\n        with patch(\"ethosu.vela.api.npu_encode_weights\") as mock_enc_w:\n            with patch(\"ethosu.vela.api.npu_find_block_configs\") as mock_blk_cfg:\n                mock_blk_cfg.return_value = [vapi.NpuShape3D(8, 8, 8)]\n                ethosu_conv2d_calls = extract_ethosu_conv2d_extern_calls(test_vec[\"tir_module\"])\n                buffer_info = tirtocs.extract_buffer_info(\n                    test_vec[\"tir_module\"], test_vec[\"param_dict\"]\n                )\n                for ethosu_conv2d_call in ethosu_conv2d_calls:\n                    npu_op, _ = tirtocs.translate_ethosu_conv2d(ethosu_conv2d_call)\n                    weights = buffer_info[npu_op.weights[0].address.buffer_var][0]\n                    vela_api.encode_weights(ethosu_conv2d_call, weights, accel)\n                return mock_enc_w\n\n    def verify(test_vec, mock_enc_w):\n        ethosu_conv2d_calls = extract_ethosu_conv2d_extern_calls(test_vec[\"tir_module\"])\n        buffer_info = tirtocs.extract_buffer_info(test_vec[\"tir_module\"], test_vec[\"param_dict\"])\n        for ethosu_conv2d_call in ethosu_conv2d_calls:\n            npu_op, w_zero_point = tirtocs.translate_ethosu_conv2d(ethosu_conv2d_call)\n            weights = buffer_info[npu_op.weights[0].address.buffer_var][0]\n\n            assert mock_enc_w.call_args[1][\"accelerator\"] == accel\n            assert (\n                mock_enc_w.call_args[1][\"weights_volume\"].flatten()\n                == weights.astype(np.int64) - w_zero_point\n            ).all()\n            assert mock_enc_w.call_args[1][\"dilation_xy\"] == (\n                npu_op.kernel.dilation_x,\n                npu_op.kernel.dilation_y,\n            )\n            assert mock_enc_w.call_args[1][\"dilation_xy\"] == (\n                npu_op.kernel.dilation_x,\n                npu_op.kernel.dilation_y,\n            )\n            assert mock_enc_w.call_args[1][\"ifm_bitdepth\"] == npu_op.ifm.data_type.size_in_bits()\n            assert mock_enc_w.call_args[1][\"block_traversal\"] == test_vec[\"block_traversal\"]\n\n    for _test_vec in test_vecs:\n        _mock_enc_w = create_mock(_test_vec)\n        verify(_test_vec, _mock_enc_w)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_gemm_acc16.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.topi.x86.tensor_intrin import dot_16x1x16_uint8_int8_int16\n\n\ndef benchmark_fc_int8_acc16():\n    m = 128\n    n = 128\n    k = 128\n\n    X = te.placeholder((m, k), name=\"X\", dtype=\"uint8\")\n    W = te.placeholder((n, k), name=\"W\", dtype=\"int8\")\n\n    peak = 512 / 16 * 2 * 2 * 2\n    gops_per_mm = 2 * n * m * k\n    print(\"Peak {} Gops/s \\n\".format(peak))\n\n    def verify(target=\"llvm -mcpu=skylake-avx512\"):\n        if not tvm.runtime.enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n\n        dev = tvm.device(target, 0)\n        X = te.placeholder((m, k), name=\"X\", dtype=\"uint8\")\n        W = te.placeholder((n, k), name=\"W\", dtype=\"int8\")\n        pc = dot_16x1x16_uint8_int8_int16()\n        ak = te.reduce_axis((0, k), name=\"k\")\n\n        packedW = te.placeholder((n // 128, 128 * (k // 2), 2), name=\"packedW\", dtype=\"int8\")\n        t_fc = te.compute(\n            (m, n),\n            lambda i, j: te.sum(\n                X[i, ak].astype(\"int16\")\n                * packedW[j // 128, (ak // 2) * 128 + j % 128, ak % 2].astype(\"int16\"),\n                axis=ak,\n            ),\n            name=\"F\",\n        )\n\n        t_sch = te.create_schedule(t_fc.op)\n        a_x, a_y = t_fc.op.axis\n        (a_k,) = t_fc.op.reduce_axis\n\n        a_yo, a_yi = t_sch[t_fc].split(a_y, factor=128)\n        a_ko, a_ki = t_sch[t_fc].split(a_k, factor=2)\n\n        a_xo, a_xi = t_sch[t_fc].split(a_x, factor=128)\n        a_koo, a_koi = t_sch[t_fc].split(a_ko, factor=32)\n        t_sch[t_fc].reorder(a_yo, a_xo, a_koo, a_xi, a_koi, a_yi, a_ki)\n\n        t_sch[t_fc].tensorize(a_yi, pc)\n        # print(tvm.lower(t_sch, [X, packedW, t_fc], simple_mode=True))\n        t_func = tvm.build(t_sch, [X, packedW, t_fc], target, name=\"intrinsic\")\n        t_evaluator = t_func.time_evaluator(t_func.entry_name, dev, number=10)\n\n        # generate the plain data\n        a_ = np.random.uniform(1, 10, size=(m, k)).astype(\"uint8\")\n        b_ = np.random.uniform(1, 10, size=(n, k)).astype(\"int8\")\n\n        packW = np.random.uniform(1, 10, size=(n // 128, 128 * (k // 2), 2)).astype(\"int8\")\n        # This occurs in pre_compute stage\n        for r_idx in range(n // 128):\n            for s_idx in range(128 * (k // 2)):\n                for t_idx in range(2):\n                    packW[r_idx][s_idx][t_idx] = b_[r_idx * 128 + s_idx % 128][\n                        s_idx // 128 * 2 + t_idx\n                    ]\n\n        x = tvm.nd.array(a_, dev)\n        w = tvm.nd.array(packW, dev)\n        y = tvm.nd.array(np.zeros((m, n), dtype=\"int16\"), dev)\n\n        result = t_evaluator(x, w, y)\n        gops_per_sec = gops_per_mm / result.mean / 1e9\n        tvm.testing.assert_allclose(y.numpy(), np.dot(a_, b_.T), rtol=1e-5)\n        print(\n            \"Tensorization: running time: {:.3f} ms, {:.2f} Gops/s, effiency: {:.2f}.\".format(\n                result.mean * 1000, gops_per_sec, gops_per_sec / peak\n            )\n        )\n        # t_func.export_library(\"gemm_tensorize.o\")\n\n    verify()\n\n\nif __name__ == \"__main__\":\n    benchmark_fc_int8_acc16()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_gemm_acc32_vnni.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nfrom tvm.topi.x86.tensor_intrin import dot_16x1x16_uint8_int8_int32_cascadelake\nfrom tvm.topi.x86.tensor_intrin import dot_16x1x16_uint8_int8_int32\nimport pytest\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.skip(\"skip because feature not enabled\")\ndef test_fc_int8_acc32():\n    m = 1024\n    n = 1024\n    k = 1024\n\n    X = te.placeholder((m, k), name=\"X\", dtype=\"uint8\")\n    W = te.placeholder((n, k), name=\"W\", dtype=\"int8\")\n\n    peak = 280\n    print(\"Peak {} Gops/s\".format(peak))\n    memory_ops = m * k + n * k + 2 * m * n\n    gops_per_mm = 2 * m * n * k\n\n    # For LLVM < 8.0, it shows \"'cascadelake' is not a recognized processor for this target\n    # (ignoring processor)\" error with the following setting. After LLVM 8.0 is enabled in the\n    # test, we should use cascadelake setting.\n    def verify(target=\"llvm -mcpu=cascadelake\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n\n        dev = tvm.device(target, 0)\n        pc = dot_16x1x16_uint8_int8_int32_cascadelake()\n        ak = te.reduce_axis((0, k), name=\"k\")\n        packedW = te.placeholder((n // 16, 16 * (k // 4), 4), name=\"packedW\", dtype=\"int8\")\n\n        t_fc = te.compute(\n            (m, n),\n            lambda i, j: te.sum(\n                X[i, ak].astype(\"int32\")\n                * packedW[\n                    tvm.tir.indexdiv(j, 16), tvm.tir.indexdiv(ak, 4) * 16 + j % 16, ak % 4\n                ].astype(\"int32\"),\n                axis=ak,\n            ),\n            name=\"F\",\n        )\n        t_sch = te.create_schedule(t_fc.op)\n        a_x, a_y = t_fc.op.axis\n        (a_k,) = t_fc.op.reduce_axis\n\n        a_yo, a_yi = t_sch[t_fc].split(a_y, factor=16)\n        a_xo, a_xi = t_sch[t_fc].split(a_x, factor=32)\n        a_ko, a_ki = t_sch[t_fc].split(a_k, factor=4)\n        a_koo, a_koi = t_sch[t_fc].split(a_ko, factor=4)\n        t_sch[t_fc].reorder(a_yo, a_xo, a_xi, a_koo, a_koi, a_yi, a_ki)\n\n        t_sch[t_fc].unroll(a_koi)\n        t_sch[t_fc].tensorize(a_yi, pc)\n\n        t_func = tvm.build(t_sch, [X, packedW, t_fc], target, name=\"intrinsic\")\n        t_evaluator = t_func.time_evaluator(t_func.entry_name, dev, number=10)\n\n        # generate the plain data\n        a_ = np.random.uniform(1, 10, size=(m, k)).astype(\"uint8\")\n        b_ = np.random.uniform(1, 10, size=(n, k)).astype(\"int8\")\n\n        packW = np.random.uniform(1, 10, size=(n // 16, 16 * (k // 4), 4)).astype(\"int8\")\n        # This occurs in pre_compute stage\n        for r_idx in range(n // 16):\n            for s_idx in range(16 * (k // 4)):\n                for t_idx in range(4):\n                    packW[r_idx][s_idx][t_idx] = b_[r_idx * 16 + s_idx % 16][\n                        (s_idx // 16) * 4 + t_idx\n                    ]\n\n        x = tvm.nd.array(a_, dev)\n        w = tvm.nd.array(packW, dev)\n        y = tvm.nd.array(np.zeros((m, n), dtype=\"int32\"), dev)\n        result = t_evaluator(x, w, y)\n\n        gops_per_sec = gops_per_mm / result.mean / 1e9\n        # verify the correctness\n        tvm.testing.assert_allclose(y.numpy(), np.dot(a_, b_.T), rtol=0)\n        print(\n            \"Tensorization: running time: {:.3f} ms, {:.2f} Gops/s, effiency: {:.2f}\".format(\n                result.mean * 1000, gops_per_sec, gops_per_sec / peak\n            )\n        )\n        t_func.export_library(\"tensorize_acc32.o\")\n\n    verify()\n\n\nif __name__ == \"__main__\":\n    # The test requires Cascade Lake and newer Intel machines to generate the\n    # correct AVX512 VNNI instruction. So, disabling the test.\n\n    # test_fc_int8_acc32()\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Testing infrastructure for Hexagon \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/benchmark_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Utility functions used for benchmarks \"\"\"\n\nimport csv\nimport os\nimport tempfile\n\nimport pytest\n\nfrom tvm.contrib.hexagon.tools import HEXAGON_SIMULATOR_NAME\n\n\ndef skip_benchmarks_flag_and_reason():\n    \"\"\"\n    Returns one of these tuples:\n        (False, '') or\n        (True, (a string describing why the test should be skipped))\n\n    NOTE: This function is a temporary measure to prevent the TVM CI system\n    running benchmark scripts every time the CI pre-commit hook executes.\n    This should go away when a better system is in place to govern when various\n    tests / benchmarks are executed.\n    \"\"\"\n    asn = os.environ.get(\"ANDROID_SERIAL_NUMBER\")\n\n    if asn == HEXAGON_SIMULATOR_NAME:\n        return (True, \"Skipping benchmarks when  ANDROID_SERIAL_NUMBER='simluator'\")\n\n    return (False, \"\")\n\n\nclass UnsupportedException(Exception):\n    \"\"\"\n    Indicates that the specified benchmarking configuration is known to\n    currently be unsupported.  The Exception message may provide more detail.\n    \"\"\"\n\n\nclass NumericalAccuracyException(Exception):\n    \"\"\"\n    Indicates that the benchmarking configuration appeared to run successfully,\n    but the output data didn't have the expected accuracy.\n    \"\"\"\n\n\nclass BenchmarksTable:\n    \"\"\"\n    Stores/reports the result of benchmark runs.\n\n    Each line item has a status: success, fail, or skip.\n\n    Each 'success' line item must include benchmark data,\n    in the form provided by TVM's `time_evaluator` mechanism.\n\n    Each line item may also specify values for any subset of\n    the columns provided to the table's construstor.\n    \"\"\"\n\n    BUILTIN_COLUMN_NAMES = set(\n        [\n            \"row_status\",\n            \"timings_min_usecs\",\n            \"timings_max_usecs\",\n            \"timings_median_usecs\",\n            \"timings_mean_usecs\",\n            \"timings_stddev_usecs\",\n        ]\n    )\n\n    def __init__(self):\n        self._line_items = []\n\n    def validate_user_supplied_kwargs(self, kwarg_dict):\n        name_conflicts = set(kwarg_dict).intersection(self.BUILTIN_COLUMN_NAMES)\n\n        if name_conflicts:\n            name_list = \", \".join(name_conflicts)\n            raise Exception(f\"Attempting to supply values for built-in column names: {name_list}\")\n\n    def record_success(self, timings, **kwargs):\n        \"\"\"\n        `timings` : Assumed to have the structure and meaning of\n          the timing results provided by TVM's `time_evaluator`\n          mechanism.\n\n        `kwargs` : Optional values for any of the other columns\n          defined for this benchmark table.\n        \"\"\"\n        self.validate_user_supplied_kwargs(kwargs)\n        line_item = kwargs\n\n        line_item[\"row_status\"] = \"SUCCESS\"\n\n        line_item[\"timings_min_usecs\"] = timings.min * 1000000\n        line_item[\"timings_max_usecs\"] = timings.max * 1000000\n        line_item[\"timings_median_usecs\"] = timings.median * 1000000\n        line_item[\"timings_stddev_usecs\"] = timings.std * 1000000\n        line_item[\"timings_mean_usecs\"] = timings.mean * 1000000\n\n        self._line_items.append(line_item)\n\n    def record_skip(self, **kwargs):\n        self.validate_user_supplied_kwargs(kwargs)\n\n        line_item = dict(kwargs)\n        line_item[\"row_status\"] = \"SKIP\"\n        self._line_items.append(line_item)\n\n    def record_fail(self, **kwargs):\n        self.validate_user_supplied_kwargs(kwargs)\n\n        line_item = dict(kwargs)\n        line_item[\"row_status\"] = \"FAIL\"\n        self._line_items.append(line_item)\n\n    def has_fail(self):\n        \"\"\"\n        Returns True if the table contains at least one 'fail' line item,\n        otherwise returns False.\n        \"\"\"\n        return any(item[\"row_status\"] == \"FAIL\" for item in self._line_items)\n\n    def print_csv(self, f, column_name_order, timing_decimal_places=3):\n        \"\"\"\n        Print the benchmark results as a csv.\n\n        `f` : The output stream.\n\n        `column_name_order`: an iterable sequence of column names, indicating the\n           left-to-right ordering of columns in the CSV output.\n\n           The CSV output will contain only those columns that are mentioned in\n           this list.\n\n        `timing_decimal_places`: for the numeric timing values, this is the\n           number of decimal places to provide in the printed output.\n           For example, a value of 3 is equivalent to the Python formatting string\n           `'{:.3f}'`\n        \"\"\"\n        writer = csv.DictWriter(\n            f, column_name_order, dialect=\"excel-tab\", restval=\"\", extrasaction=\"ignore\"\n        )\n\n        writer.writeheader()\n\n        for line_item_dict in self._line_items:\n            # Use a copy of the line-item dictionary, because we might do some modifications\n            # for the sake of rendering...\n            csv_line_dict = dict(line_item_dict)\n\n            for col_name in [\n                \"timings_min_usecs\",\n                \"timings_max_usecs\",\n                \"timings_median_usecs\",\n                \"timings_stddev_usecs\",\n                \"timings_mean_usecs\",\n            ]:\n                if col_name in csv_line_dict:\n                    old_value = csv_line_dict[col_name]\n                    assert isinstance(old_value, float), (\n                        f\"Formatting code assumes that column {col_name} is\"\n                        f\" some col_nameind of float, but its actual type is {type(old_value)}\"\n                    )\n                    str_value = f\"{old_value:>0.{timing_decimal_places}f}\"\n                    csv_line_dict[col_name] = str_value\n\n            writer.writerow(csv_line_dict)\n\n\ndef get_benchmark_id(keys_dict):\n    \"\"\"\n    Given a dictionary with the distinguishing characteristics of a particular benchmark\n    line item, compute a string that uniquely identifies the benchmark.\n\n    The returned string:\n    - is a valid directory name on the host's file systems, and\n    - should be easy for humans to parse\n\n    Note that the insertion order for `keys_dict` affects the computed name.\n    \"\"\"\n    # Creat a copy, because we might be modifying it.\n    keys_dict_copy = dict(keys_dict)\n\n    # Sniff for shape-like lists, because we want them in a form that's both\n    # readable and filesystem-friendly...\n    for k, v in keys_dict_copy.items():\n        if isinstance(v, (list, tuple)):\n            v_str = \"_\".join([str(x) for x in v])\n            keys_dict_copy[k] = v_str\n\n    return \"-\".join([f\"{k}:{v}\" for k, v in keys_dict_copy.items()])\n\n\ndef get_benchmark_decription(keys_dict):\n    \"\"\"\n    Similar to `get_benchmark_id`, but the focus is on human-readability.\n\n    The returned string contains no line-breaks, but may contain spaces and\n    other characters that make it unsuitable for use as a filename.\n    \"\"\"\n    return \" \".join([f\"{k}={v}\" for k, v in keys_dict.items()])\n\n\n@pytest.fixture(scope=\"class\")\ndef benchmark_group(request):\n    \"\"\"This fixture provides some initialization / finalization logic for groups of related\n    benchmark runs.\n    See the fixture implementation below for details.\n\n    The fixture's mechanics are described here: https://stackoverflow.com/a/63047695\n\n    TODO: There may be cleaner ways to let each class that uses this fixture provide its\n    own value for `csv_column_order`.\n\n    TODO: In the future we may wish to break this fixture up in to several smaller ones.\n\n    The overall contract for a class (e.g. `MyTest`) using this fixture is as follows:\n\n        https://stackoverflow.com/a/63047695\n\n        @pytest.mark.usefixtures(\"benchmark_group\")\n        class MyTest:\n\n        # The fixture requires that this class variable is defined before\n        # the fixture's finalizer-logic executes.\n        #\n        # This is used as an argument to BenchmarkTable.print_csv(...) after\n        # all of MyTest's unit tests have executed.\n        csv_column_order = [\n            ...\n            ]\n\n        # Before the MyTest's first unit test executes, the fixture will populate the\n        # following class variables:\n        MyTest.working_dir     : str\n        MyTest.benchmark_table : BenchmarkTable\"\"\"\n    working_dir = tempfile.mkdtemp()\n    table = BenchmarksTable()\n\n    request.cls.working_dir = working_dir\n    request.cls.benchmark_table = table\n\n    yield\n\n    tabular_output_filename = os.path.join(working_dir, \"benchmark-results.csv\")\n\n    if not hasattr(request.cls, \"csv_column_order\"):\n        raise Exception('Classes using this fixture must have a member named \"csv_column_order\"')\n\n    with open(tabular_output_filename, \"w\", encoding=\"UTF-8\") as csv_file:\n        table.print_csv(csv_file, request.cls.csv_column_order)\n\n    print()\n    print(\"*\" * 80)\n    print(f\"BENCHMARK RESULTS FILE: {tabular_output_filename}\")\n    print(\"*\" * 80)\n    print()\n\n    if table.has_fail() > 0:\n        pytest.fail(\"At least one benchmark configuration failed\", pytrace=False)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Hexagon testing fixtures used to deduce testing argument\n    values from testing parameters \"\"\"\n\n# Disabling invalid-name check as the name is expected to be exactly this by pytest\n# pylint: disable=invalid-name\npytest_plugins = [\n    \"tvm.contrib.hexagon.pytest_plugin\",\n]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/conv2d/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Testing infrastructure for Hexagon/TOPI/Conv2d \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/conv2d/test_conv2d_blocked.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Hexagon contrib tests for blocked conv2d \"\"\"\n\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te, topi\nfrom tvm.topi import testing\n\nfrom ..infrastructure import (\n    build_and_run,\n    conv2d_compute,\n    conv2d_verify,\n    get_block_shape,\n    get_packed_filter_shape,\n    get_packed_shape,\n)\n\n\ndef conv2d_nhwc8h8w32c(\n    shape_input,\n    pad,\n    stride,\n    dilation,\n    shape_filter,\n    k_split_factor,\n    h_split_factor,\n    dtype,\n    storage_scope=\"global\",\n):\n    \"\"\"\n    Conv2d wherein the input activation is defined by its\n    logical NHWC layout.  The filter is provided in its physical\n    packed layout (oihw8i32o4i).  The input is padded and then packed\n    into its physical packed layout (nhwc8h8w32c).  The resulting\n    computation is in the same physical packed layout (nhwc8h8w32c).\n    \"\"\"\n\n    # nhwc layout\n    logical_input = te.placeholder(shape_input, dtype=dtype, name=\"logical_input\")\n\n    # oihw8i32o4i layout\n    filt_packed = te.placeholder(shape_filter, dtype=dtype, name=\"packed_filter\")\n\n    block_h, block_w, block_c = get_block_shape()\n\n    # Calculate padded input\n    _, height, width, _ = shape_input\n    pad_h = (block_h - ((height + pad[1]) % block_h)) % block_h\n    pad_w = (block_w - ((width + pad[3]) % block_w)) % block_w\n    padded_input = topi.nn.pad(\n        logical_input,\n        [0, pad[0], pad[2], 0],\n        [0, pad_h, pad_w, 0],\n        pad_value=0,\n        name=\"padded_input\",\n    )\n\n    # Calculate packed input\n    packed_shape = get_packed_shape(padded_input.shape)\n    packed_input = te.compute(\n        packed_shape,\n        lambda n, ho, wo, co, hi, wi, ci: padded_input[\n            n, ho * block_h + hi, wo * block_w + wi, co * block_c + ci\n        ],\n        name=\"packed_input\",\n    )\n\n    output_shape, compute = conv2d_compute(packed_input, filt_packed, pad, stride, dilation)\n    packed_output = te.compute(output_shape, compute, name=\"packed_output\")\n    s = te.create_schedule(packed_output.op)\n\n    # Ensure the padding and array packing is performed inline\n    s[padded_input].compute_inline()\n    s[packed_input].compute_inline()\n\n    # cache reads and writes\n    cached_input = s.cache_read(packed_input, storage_scope, [packed_output])\n    cached_filt = s.cache_read(filt_packed, storage_scope, [packed_output])\n    cached_output = s.cache_write(packed_output, storage_scope)\n\n    # cache write schedule\n    batch, h_outer, w_outer, k_outer, h_inner, w_inner, k_inner = s[packed_output].op.axis\n    koo, koi = s[packed_output].split(k_outer, factor=k_split_factor)\n    hoo, hoi = s[packed_output].split(h_outer, factor=h_split_factor)\n    s[packed_output].reorder(batch, koo, hoo, koi, hoi, w_outer, h_inner, w_inner, k_inner)\n    s[cached_output].compute_at(s[packed_output], hoo)\n\n    # compute schedule\n    batch, h_outer, w_outer, k_outer, h_inner, w_inner, k_inner = s[cached_output].op.axis\n    _, _, reduce_c = s[cached_output].op.reduce_axis\n    rco, rci = s[cached_output].split(reduce_c, factor=block_c)\n    koo, koi = s[cached_output].split(k_outer, factor=k_split_factor)\n    hoo, hoi = s[cached_output].split(h_outer, factor=h_split_factor)\n    s[cached_output].reorder(\n        batch, koo, hoo, koi, hoi, w_outer, rco, h_inner, w_inner, k_inner, rci\n    )\n    s[cached_input].compute_at(s[cached_output], hoo)\n    s[cached_filt].compute_at(s[cached_output], hoo)\n\n    binds = {}\n    if storage_scope and storage_scope != \"global\":\n        with tvm.transform.PassContext():\n            input_buffer = tvm.tir.decl_buffer(\n                packed_shape, name=\"Xb\", dtype=dtype, scope=storage_scope\n            )\n            output_buffer = tvm.tir.decl_buffer(\n                output_shape, name=\"Yb\", dtype=dtype, scope=storage_scope\n            )\n            binds = {logical_input: input_buffer, packed_output: output_buffer}\n\n    return (s, [logical_input, filt_packed, packed_output], binds)\n\n\nclass BaseConv2d:\n    \"\"\"Base class for conv2d tests\"\"\"\n\n    # input\n    batch = tvm.testing.parameter(1)\n    in_size = tvm.testing.parameter(64)\n    in_channel = tvm.testing.parameter(64)\n    # conv2d\n    pad = tvm.testing.parameter(0)\n    stride = tvm.testing.parameter(1)\n    kernel_size = tvm.testing.parameter(1, 3)\n    out_channel = tvm.testing.parameter(128)\n    # schedule params\n    k_split_factor = tvm.testing.parameter(1, 2)\n    h_split_factor = tvm.testing.parameter(1, 2)\n    dtype = tvm.testing.parameter(\"float32\")\n\n\nclass TestConv2dPackedFilter(BaseConv2d):\n    \"\"\"Conv2d packed filter test class\"\"\"\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    @tvm.testing.skip_if_32bit(reason=\"Test known to be flaky on i386 machines\")\n    def test_conv2d(\n        self,\n        batch,\n        in_size,\n        in_channel,\n        pad,\n        stride,\n        kernel_size,\n        out_channel,\n        k_split_factor,\n        h_split_factor,\n        dtype,\n        target,\n    ):\n        \"\"\"conv2d test\"\"\"\n        # TODO: no support for dilation\n        dilation = 1\n\n        shape_input = [batch, in_size, in_size, in_channel]\n        shape_filter_oihw = [out_channel, in_channel, kernel_size, kernel_size]\n        shape_filter_oihw8i32o4i = get_packed_filter_shape(shape_filter_oihw)\n\n        inputs = [\n            np.random.uniform(0, 255, size=shape_input).astype(dtype),\n            np.random.uniform(0, 255, size=shape_filter_oihw8i32o4i).astype(dtype),\n        ]\n        np_filter = (\n            inputs[1]\n            .transpose(0, 5, 1, 4, 6, 2, 3)\n            .reshape(shape_filter_oihw)\n            .transpose(2, 3, 1, 0)\n        )\n        ref_output = testing.conv2d_nhwc_python(inputs[0], np_filter, stride, pad)\n        output = build_and_run(\n            inputs,\n            conv2d_nhwc8h8w32c,\n            target,\n            target,\n            shape_input=shape_input,\n            pad=(pad, pad, pad, pad),\n            stride=(stride, stride),\n            dilation=(dilation, dilation),\n            shape_filter=shape_filter_oihw8i32o4i,\n            k_split_factor=k_split_factor,\n            h_split_factor=h_split_factor,\n            dtype=dtype,\n        )\n\n        conv2d_verify(output, ref_output, dtype)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/conv2d/test_conv2d_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" back-to-back conv2d Hexagon test for stripe scheduling \"\"\"\n\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te, topi\nfrom tvm.topi import testing\n\nfrom ..infrastructure import (\n    build_and_run,\n    conv2d_compute,\n    conv2d_verify,\n    get_block_shape,\n    get_packed_filter_shape,\n    get_packed_shape,\n)\n\n\ndef conv2dconv2d_nhwc8h8w32c(\n    shape_input,\n    pad1,\n    stride1,\n    dilation1,\n    shape_filter1,\n    pad2,\n    stride2,\n    dilation2,\n    shape_filter2,\n    k_split_factor,\n    h_split_factor,\n    dtype,\n    storage_scope=\"global\",\n):\n    \"\"\"\n    Conv2d -> Conv2d wherein the input activation is defined by its\n    logical NHWC layout.  The filter is provided in its physical\n    packed layout (oihw8i32o4i).  The input is padded and then packed\n    into its physical packed layout (nhwc8h8w32c).  The resulting\n    computation is in the same physical packed layout (nhwc8h8w32c).\n    \"\"\"\n\n    # nhwc layout\n    logical_input = te.placeholder(shape_input, dtype=dtype, name=\"logical_input\")\n\n    # oihw8i32o4i layout\n    filt_packed1 = te.placeholder(shape_filter1, dtype=dtype, name=\"packed_filter1\")\n    filt_packed2 = te.placeholder(shape_filter2, dtype=dtype, name=\"packed_filter2\")\n\n    block_h, block_w, block_c = get_block_shape()\n\n    # Calculate padded input\n    _, height, width, _ = shape_input\n    pad_h = (block_h - ((height + pad1[1]) % block_h)) % block_h\n    pad_w = (block_w - ((width + pad1[3]) % block_w)) % block_w\n    padded_input = topi.nn.pad(\n        logical_input,\n        [0, pad1[0], pad1[2], 0],\n        [0, pad_h, pad_w, 0],\n        pad_value=0,\n        name=\"padded_input\",\n    )\n\n    # Calculate packed input\n    packed_shape = get_packed_shape(padded_input.shape)\n    packed_input = te.compute(\n        packed_shape,\n        lambda n, ho, wo, co, hi, wi, ci: padded_input[\n            n, ho * block_h + hi, wo * block_w + wi, co * block_c + ci\n        ],\n        name=\"packed_input\",\n    )\n\n    output_shape1, compute1 = conv2d_compute(packed_input, filt_packed1, pad1, stride1, dilation1)\n    temp_output = te.compute(output_shape1, compute1, name=\"temp_output\")\n\n    output_shape2, compute2 = conv2d_compute(temp_output, filt_packed2, pad2, stride2, dilation2)\n    packed_output = te.compute(output_shape2, compute2, name=\"packed_output\")\n    s = te.create_schedule(packed_output.op)\n\n    # Ensure the padding and array packing is performed inline\n    s[padded_input].compute_inline()\n    s[packed_input].compute_inline()\n\n    # cache reads and writes\n    packed_input_cached = s.cache_read(packed_input, storage_scope, [temp_output])\n    filt_packed1_cached = s.cache_read(filt_packed1, storage_scope, [temp_output])\n    filt_packed2_cached = s.cache_read(filt_packed2, storage_scope, [packed_output])\n    packed_output_cached = s.cache_write(packed_output, storage_scope)\n\n    # conv2d #1 schedule\n    n, h_outer, w_outer, k_outer, h_inner, w_inner, k_inner = s[temp_output].op.axis\n    _, _, reduce_channel = s[temp_output].op.reduce_axis\n    rco, rci = s[temp_output].split(reduce_channel, factor=block_c)\n    koo, koi = s[temp_output].split(k_outer, factor=k_split_factor)\n    hoo, hoi = s[temp_output].split(h_outer, factor=h_split_factor)\n    s[temp_output].reorder(n, koo, hoo, koi, hoi, w_outer, rco, h_inner, w_inner, k_inner, rci)\n    s[packed_input_cached].compute_at(s[temp_output], hoo)\n    s[filt_packed1_cached].compute_at(s[temp_output], hoo)\n\n    # cache write schedule\n    n, h_outer, w_outer, k_outer, h_inner, w_inner, k_inner = s[packed_output].op.axis\n    koo, koi = s[packed_output].split(k_outer, factor=k_split_factor)\n    hoo, hoi = s[packed_output].split(h_outer, factor=h_split_factor)\n    s[packed_output].reorder(n, koo, hoo, koi, hoi, w_outer, h_inner, w_inner, k_inner)\n    s[packed_output_cached].compute_at(s[packed_output], hoo)\n\n    # conv2d #2 schedule\n    n, h_outer, w_outer, k_outer, h_inner, w_inner, k_inner = s[packed_output_cached].op.axis\n    _, _, reduce_channel = s[packed_output_cached].op.reduce_axis\n    rco, rci = s[packed_output_cached].split(reduce_channel, factor=block_c)\n    koo, koi = s[packed_output_cached].split(k_outer, factor=k_split_factor)\n    hoo, hoi = s[packed_output_cached].split(h_outer, factor=h_split_factor)\n    s[packed_output_cached].reorder(\n        n, koo, hoo, koi, hoi, w_outer, rco, h_inner, w_inner, k_inner, rci\n    )\n    s[temp_output].compute_at(s[packed_output_cached], hoo)\n    s[filt_packed2_cached].compute_at(s[packed_output_cached], hoo)\n\n    binds = {}\n    if storage_scope and storage_scope != \"global\":\n        with tvm.transform.PassContext():\n            input_buffer = tvm.tir.decl_buffer(\n                packed_shape, name=\"Xb\", dtype=dtype, scope=storage_scope\n            )\n            output_buffer = tvm.tir.decl_buffer(\n                output_shape2, name=\"Yb\", dtype=dtype, scope=storage_scope\n            )\n            binds = {logical_input: input_buffer, packed_output: output_buffer}\n\n    return (s, [logical_input, filt_packed1, filt_packed2, packed_output], binds)\n\n\nclass BaseConv2dConv2d:\n    \"\"\"Base class for conv2d-conv2d tests\"\"\"\n\n    # input\n    batch = tvm.testing.parameter(1)\n    in_size = tvm.testing.parameter(64)\n    in_channel = tvm.testing.parameter(128)\n    # conv2d #1\n    pad1 = tvm.testing.parameter(0)\n    stride1 = tvm.testing.parameter(1)\n    kernel_size1 = tvm.testing.parameter(1, 3)\n    out_channel1 = tvm.testing.parameter(128)\n    # conv2d #2\n    stride2 = tvm.testing.parameter(1)\n    kernel_size2 = tvm.testing.parameter(1, 3)\n    out_channel2 = tvm.testing.parameter(128)\n    # schedule params\n    k_split_factor = tvm.testing.parameter(1, 2)\n    h_split_factor = tvm.testing.parameter(1, 2)\n    dtype = tvm.testing.parameter(\"float32\")\n\n\nclass TestConv2dConv2dPackedFilter(BaseConv2dConv2d):\n    \"\"\"Conv2d-Conv2d packed filter test class\"\"\"\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    @tvm.testing.skip_if_32bit(reason=\"Test known to be flaky on i386 machines\")\n    def test_conv2d(\n        self,\n        batch,\n        in_size,\n        in_channel,\n        pad1,\n        stride1,\n        kernel_size1,\n        out_channel1,\n        stride2,\n        kernel_size2,\n        out_channel2,\n        k_split_factor,\n        h_split_factor,\n        dtype,\n        target,\n    ):\n        \"\"\"conv2d-conv2d test\"\"\"\n        # TODO: no support for padding in conv2d #2\n        pad2 = 0\n\n        # TODO: no support for dilation\n        dilation1 = 1\n        dilation2 = 1\n\n        shape_input = [batch, in_size, in_size, in_channel]\n        shape_filter1_oihw = [out_channel1, in_channel, kernel_size1, kernel_size1]\n        shape_filter1_oihw8i32o4i = get_packed_filter_shape(shape_filter1_oihw)\n\n        shape_filter2_oihw = [out_channel2, out_channel1, kernel_size2, kernel_size2]\n        shape_filter2_oihw8i32o4i = get_packed_filter_shape(shape_filter2_oihw)\n\n        inputs = [\n            np.random.uniform(0, 255, size=shape_input).astype(dtype),\n            np.random.uniform(0, 255, size=shape_filter1_oihw8i32o4i).astype(dtype),\n            np.random.uniform(0, 255, size=shape_filter2_oihw8i32o4i).astype(dtype),\n        ]\n        np_filter1 = (\n            inputs[1]\n            .transpose(0, 5, 1, 4, 6, 2, 3)\n            .reshape(shape_filter1_oihw)\n            .transpose(2, 3, 1, 0)\n        )\n        np_filter2 = (\n            inputs[2]\n            .transpose(0, 5, 1, 4, 6, 2, 3)\n            .reshape(shape_filter2_oihw)\n            .transpose(2, 3, 1, 0)\n        )\n        temp_output = testing.conv2d_nhwc_python(inputs[0], np_filter1, stride1, pad1)\n        ref_output = testing.conv2d_nhwc_python(temp_output, np_filter2, stride2, pad2)\n        output = build_and_run(\n            inputs,\n            conv2dconv2d_nhwc8h8w32c,\n            target,\n            target,\n            shape_input=shape_input,\n            pad1=(pad1, pad1, pad1, pad1),\n            stride1=(stride1, stride1),\n            dilation1=(dilation1, dilation1),\n            shape_filter1=shape_filter1_oihw8i32o4i,\n            pad2=(pad2, pad2, pad1, pad1),\n            stride2=(stride2, stride2),\n            dilation2=(dilation2, dilation2),\n            shape_filter2=shape_filter2_oihw8i32o4i,\n            k_split_factor=k_split_factor,\n            h_split_factor=h_split_factor,\n            dtype=dtype,\n        )\n\n        conv2d_verify(output, ref_output, dtype)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" Hexagon testing infrastructure \"\"\"\n\nimport numpy\nimport tvm\nfrom tvm import te\n\n\ndef ceildiv(o, d):\n    assert o >= 0\n    assert d >= 0\n    return tvm.tir.floordiv(o + d - 1, d)\n\n\n# defines inner block shape: 8h8w32c\ndef get_block_shape():\n    return 8, 8, 32\n\n\n# defines inner filter block shape: 8i32o41\ndef get_filter_block_shape():\n    return 8, 32, 4\n\n\n# input: locgical shape in nhwc layout\n# output:  physical packed shape in nhw8h8w32c layout\ndef get_packed_shape(logical_shape_nhwc):\n    assert len(logical_shape_nhwc) == 4\n    physical_shape_nhwc8h8w32c = [logical_shape_nhwc[0]]\n    block_shape = get_block_shape()\n    off_h, off_w, off_c = block_shape\n    physical_shape_nhwc8h8w32c.append(ceildiv(logical_shape_nhwc[1], off_h))\n    physical_shape_nhwc8h8w32c.append(ceildiv(logical_shape_nhwc[2], off_w))\n    physical_shape_nhwc8h8w32c.append(ceildiv(logical_shape_nhwc[3], off_c))\n    physical_shape_nhwc8h8w32c.extend(block_shape)\n    return physical_shape_nhwc8h8w32c\n\n\n# input: physical packed shape in nhw8h8w32c layout\n# output: logical shape in nhwc layout\ndef get_logical_shape(physical_shape_nhwc8h8w32c):\n    assert len(physical_shape_nhwc8h8w32c) == 7\n    logical_shape_nhwc = [physical_shape_nhwc8h8w32c[0]]\n    logical_shape_nhwc.append(physical_shape_nhwc8h8w32c[1] * physical_shape_nhwc8h8w32c[4])\n    logical_shape_nhwc.append(physical_shape_nhwc8h8w32c[2] * physical_shape_nhwc8h8w32c[5])\n    logical_shape_nhwc.append(physical_shape_nhwc8h8w32c[3] * physical_shape_nhwc8h8w32c[6])\n    return logical_shape_nhwc\n\n\ndef get_packed_filter_shape(logical_shape_oihw):\n    \"\"\"return packed filter shape\n\n    Parameters\n    ----------\n    logical_shape_oihw :\n       logical shape in oihw layout\n\n    Returns\n    -------\n    physical_shape_oihw8i32o4i :\n        physical packed shape in oihw8i3204i layout\n    \"\"\"\n    assert len(logical_shape_oihw) == 4\n    filter_block_shape = get_filter_block_shape()\n    filter_Cio, filter_Ki, filter_Cii = filter_block_shape\n    filter_Ci = filter_Cio * filter_Cii\n    physical_shape_oihw8i32o4i = []\n    physical_shape_oihw8i32o4i.append(int(ceildiv(logical_shape_oihw[0], filter_Ki)))\n    physical_shape_oihw8i32o4i.append(int(ceildiv(logical_shape_oihw[1], filter_Ci)))\n    physical_shape_oihw8i32o4i.append(logical_shape_oihw[2])\n    physical_shape_oihw8i32o4i.append(logical_shape_oihw[3])\n    physical_shape_oihw8i32o4i.extend(filter_block_shape)\n    return physical_shape_oihw8i32o4i\n\n\ndef build_and_run(inputs, func, target: str, target_host: str, *args, **kwargs):\n    \"\"\"build and run the function func\"\"\"\n    schedule, placeholders, binds = func(*args, **kwargs)\n\n    func = tvm.build(\n        schedule, placeholders, target=tvm.target.Target(target, host=target_host), binds=binds\n    )\n    dev = tvm.device(target)\n    tensors = []\n    for tensor in inputs:\n        tensors.append(tvm.nd.array(tensor, dev))\n    tensors.append(\n        tvm.nd.array(\n            numpy.zeros([i.value for i in placeholders[-1].shape], dtype=placeholders[-1].dtype),\n            dev,\n        )\n    )\n    func(*tensors)\n\n    return tensors[-1].asnumpy()\n\n\ndef get_conv2d_nhwc_shape(shape_nhwc, kernel_size, strides, padding, dilation, out_channels):\n    assert len(shape_nhwc) == 4\n    kernel = []\n    kernel.append((kernel_size[0] - 1) * dilation[0] + 1)\n    kernel.append((kernel_size[1] - 1) * dilation[1] + 1)\n    return (\n        shape_nhwc[0],\n        (shape_nhwc[1] - kernel[0] + padding[0] + padding[1]) // strides[0] + 1,\n        (shape_nhwc[2] - kernel[1] + padding[2] + padding[3]) // strides[1] + 1,\n        out_channels,\n    )\n\n\ndef conv2d_verify(output, ref_output, dtype):\n    \"\"\"transpose and reshape output and compare with ref_output\"\"\"\n    # nhwc8h8w32c -> nhwc\n    logical_output_shape = get_logical_shape(output.shape)\n    output = output.transpose(0, 1, 4, 2, 5, 3, 6).reshape(logical_output_shape)\n\n    # slice output to match ref_output shape\n    # e.g. 8x8 spatial 3x3 filter = 6x6 ref output\n    # but still 8x8 output given the blocked layout\n    output = output[\n        0 : ref_output.shape[0] : 1,\n        0 : ref_output.shape[1] : 1,\n        0 : ref_output.shape[2] : 1,\n        0 : ref_output.shape[3] : 1,\n    ]\n\n    if \"int\" in dtype:\n        tol = {\"atol\": 0, \"rtol\": 0}\n    elif dtype == \"float32\":\n        tol = {\"rtol\": 1e-4, \"atol\": 2e-4}\n    tvm.testing.assert_allclose(output, ref_output, **tol)\n\n\ndef conv2d_compute(X, filt, pad, stride, dilation):\n    \"\"\"Define conv2d compute\"\"\"\n    block_shape = get_block_shape()\n    block_H, block_W, block_C = block_shape\n    filter_c_io, _, filter_c_ii = get_filter_block_shape()\n    filter_c_i = filter_c_io * filter_c_ii\n\n    shape_filter = filt.shape\n    kernel_size = tuple(shape_filter[2:4])\n    out_channels = shape_filter[0] * shape_filter[5]\n\n    logical_input_shape = get_logical_shape(X.shape)\n    logical_output_shape = get_conv2d_nhwc_shape(\n        logical_input_shape,\n        kernel_size,\n        stride,\n        pad,\n        dilation,\n        out_channels,\n    )\n\n    output_shape = get_packed_shape(logical_output_shape)\n    rh = te.reduce_axis((0, kernel_size[0]), name=\"rh\")\n    rw = te.reduce_axis((0, kernel_size[1]), name=\"rw\")\n    rc = te.reduce_axis((0, logical_input_shape[3]), name=\"rc\")\n\n    def compute(n, ho, wo, ko, hi, wi, ki):\n        h = ho * block_H + hi\n        h_contig = h * stride[0] + rh\n        h_block_id = h_contig // block_H\n        h_block_offset = h_contig % block_H\n\n        w = wo * block_W + wi\n        w_contig = w * stride[1] + rw\n        w_block_id = w_contig // block_W\n        w_block_offset = w_contig % block_W\n\n        c_block_id = rc // block_C\n        c_block_offset = rc % block_C\n\n        rco = rc // filter_c_i\n        rcio = (rc % filter_c_i) // filter_c_ii\n        rcii = rc % filter_c_ii\n\n        return te.sum(\n            X[\n                n,\n                h_block_id,\n                w_block_id,\n                c_block_id,\n                h_block_offset,\n                w_block_offset,\n                c_block_offset,\n            ]\n            * filt[ko, rco, rh, rw, rcio, ki, rcii],\n            axis=[rh, rw, rc],\n        )\n\n    return output_shape, compute\n\n\ndef transform_numpy(arr_np, current_layout: str, new_layout: str):\n    \"\"\"Reshape and transpose numpy array according to the specified layout\"\"\"\n    if current_layout == \"nhwc\":\n        if new_layout == \"nhwc\":\n            return arr_np\n        if new_layout in [\"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-1d\"]:\n            n, h, w, c = arr_np.shape\n            return arr_np.reshape([n, h // 8, 8, w // 4, 2, 2, c // 32, 32]).transpose(\n                0, 1, 3, 6, 2, 4, 7, 5\n            )\n        if new_layout in [\"nhwc-4h2w32c2w-2d\"]:\n            n, h, w, c = arr_np.shape\n            return arr_np.reshape([n, h // 4, 4, w // 4, 2, 2, c // 32, 32]).transpose(\n                0, 1, 3, 6, 2, 4, 7, 5\n            )\n        if new_layout in [\"n11c-1024c-2d\", \"n11c-1024c-1d\"]:\n            n, h, w, c = arr_np.shape\n            assert h == 1 and w == 1, \"The size of h and w must be 1\"\n            return arr_np.reshape([n, 1, 1, c // 1024, 1024])\n        if new_layout == \"nc-1024-2d\":\n            n, c = arr_np.shape\n            return arr_np.reshape([n, c // 1024, 1024])\n        if new_layout == \"nhwc-1024c-2d\":\n            N, H, W, C = arr_np.shape\n            return arr_np.reshape([N, H, W, C // 1024, 1024])\n        if new_layout == \"nc-2048-2d\":\n            N, C = arr_np.shape\n            return arr_np.reshape([N, C // 2048, 2048])\n        if new_layout == \"nhwc-2048c-2d\":\n            N, H, W, C = arr_np.shape\n            return arr_np.reshape([N, H, W, C // 2048, 2048])\n        if new_layout == \"nhwc-8h8w32c-2d\":\n            n, h, w, c = arr_np.shape\n            return arr_np.reshape([n, h // 8, 8, w // 8, 8, c // 32, 32]).transpose(\n                0, 1, 3, 5, 2, 4, 6\n            )\n        if new_layout == \"n11c-2048c-2d\":\n            n, h, w, c = arr_np.shape\n            assert h == 1 and w == 1, \"The size of h and w must be 1\"\n            return arr_np.reshape([n, h, w, c // 2048, 2048])\n        raise RuntimeError(f\"Unexpected new_layout '{new_layout}'\")\n\n    if current_layout == \"nc\":\n        n, c = arr_np.shape\n        if new_layout in [\"nc-1024c-2d\"]:\n            return arr_np.reshape([n, c // 1024, 1024])\n        if new_layout in [\"nc-512c-2d\"]:\n            return arr_np.reshape([n, c // 512, 512])\n        if new_layout in [\"nc-2048c-2d\"]:\n            return arr_np.reshape([n, c // 2048, 2048])\n        raise RuntimeError(f\"Unexpected new_layout '{new_layout}'\")\n\n    if current_layout == \"nhw\":\n        if new_layout in [\"nhw-32h16w-2d\"]:\n            n, h, w = arr_np.shape\n            return arr_np.reshape([n, h // 32, 32, w // 16, 16]).transpose(0, 1, 3, 2, 4)\n\n        raise RuntimeError(f\"Unexpected new_layout '{new_layout}'\")\n\n    raise RuntimeError(f\"Unexpected current_layout '{current_layout}'\")\n\n\ndef quantize_np(arr_np: numpy.ndarray, dtype: str):\n    \"\"\"\n    Returns quantized array along with scale and zero-point\n\n    Parameters\n    ----------\n    arr_np: numpy.ndarray\n        Input numpy array to be quantized\n    dtype: str\n        dtype of the quantized array: \"uint8\", \"int8\", etc\n\n    Returns\n    -------\n    quant_np: numpy.ndarray\n        Quantized numpy array\n    scale: float\n        Scale\n    zero_point: int\n        Value corresponding to float 0\n\n    \"\"\"\n    if dtype == \"uint8\":\n        qmax = 255\n        qmin = 0\n    elif dtype == \"int8\":\n        qmax = 127\n        qmin = -128\n    else:\n        raise RuntimeError(f\"Unsupported quantized data type '{dtype}'\")\n    fmin = numpy.amin(arr_np)\n    fmax = numpy.amax(arr_np)\n\n    # Include floating-point zero in the range\n    if fmax < 0:\n        fmax = 0.0\n    elif fmin > 0:\n        fmin = 0.0\n\n    scale = (fmax - fmin) / (qmax - qmin)\n    zero_point = numpy.rint((fmax * qmin - fmin * qmax) / (fmax - fmin)).astype(\"int32\")\n    quant_np = (arr_np / scale + zero_point).astype(dtype)\n    return quant_np, scale, zero_point\n\n\ndef get_hexagon_target(cpu_ver: str) -> tvm.target.Target:\n    \"\"\"Creates a Hexagon target\"\"\"\n    target = tvm.target.hexagon(cpu_ver)\n    return tvm.target.Target(target, host=target)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/metaschedule_e2e/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Demonstration of end-to-end MetaSchedule tuning.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/metaschedule_e2e/export_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Hexagon MetaSchedule test helper functions.\"\"\"\n\nimport torch\nfrom torchvision.models import resnet\nfrom torchvision.models.quantization import resnet as qresnet\n\nimport tvm\nfrom tvm import relay\n\n\ndef export_resnet50_fp16():\n    \"\"\"Export Resnet50 FP16.\"\"\"\n    model = resnet.resnet50(pretrained=True).eval()\n\n    pt_inp = torch.randn(1, 3, 224, 224)\n\n    script_module = torch.jit.trace(model, pt_inp).eval()\n\n    input_name = \"image\"\n    input_shapes = [(input_name, pt_inp.shape)]\n    mod, params = relay.frontend.from_pytorch(script_module, input_shapes)\n    mod = relay.transform.ToMixedPrecision(\"float16\")(mod)\n\n    with open(\"resnet50_fp16.json\", \"w\") as file:\n        file.write(tvm.ir.save_json(mod))\n\n    with open(\"resnet50_fp16.params\", \"wb\") as file:\n        file.write(relay.save_param_dict(params))\n\n\ndef export_resnet50_int8():\n    \"\"\"Export Resnet50 INT8.\"\"\"\n\n    def quantize_model(model, inp):\n        model.fuse_model()\n        model.qconfig = torch.quantization.get_default_qconfig(\"fbgemm\")\n        torch.quantization.prepare(model, inplace=True)\n        model(inp)\n        torch.quantization.convert(model, inplace=True)\n\n    model = qresnet.resnet50(pretrained=True).eval()\n\n    pt_inp = torch.randn(1, 3, 224, 224)\n    quantize_model(model, pt_inp)\n\n    script_module = torch.jit.trace(model, pt_inp).eval()\n\n    input_name = \"image\"\n    input_shapes = [(input_name, pt_inp.shape)]\n    mod, params = relay.frontend.from_pytorch(\n        script_module, input_shapes, keep_quantized_weight=True\n    )\n\n    with open(\"resnet50_int8.json\", \"w\") as file:\n        file.write(tvm.ir.save_json(mod))\n\n    with open(\"resnet50_int8.params\", \"wb\") as file:\n        file.write(relay.save_param_dict(params))\n\n\nif __name__ == \"__main__\":\n    export_resnet50_fp16()\n    export_resnet50_int8()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/metaschedule_e2e/test_resnet50_fp16.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test Resnet50 float16 with MetaSchedule\"\"\"\n\nimport os\nimport tempfile\n\nimport pytest\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm import meta_schedule as ms\nfrom tvm.contrib.hexagon.meta_schedule import get_hexagon_local_builder, get_hexagon_rpc_runner\nfrom tvm.relay.backend import Executor\n\nfrom ..infrastructure import get_hexagon_target\n\n\ndef convert_conv2d_layout(mod, desired_layouts):\n    with tvm.transform.PassContext(opt_level=3):\n        seq = tvm.transform.Sequential([relay.transform.ConvertLayout(desired_layouts)])\n        return seq(mod)\n\n\n@pytest.mark.skip(\"End-to-end tuning is skipped on CI.\")\n@tvm.testing.requires_hexagon\ndef test_resnet50(hexagon_launcher):\n    \"\"\"Test Resnet50.\"\"\"\n    model_json = \"resnet50_fp16.json\"\n    target_llvm = tvm.target.Target(\"llvm\")\n    target_hexagon = get_hexagon_target(\"v69\")\n    model_params = \"resnet50_fp16.params\"\n\n    if not os.path.exists(model_json):\n        pytest.skip(msg=\"Run python export_models.py first.\")\n\n    with open(model_json, \"r\") as file:\n        mod = tvm.ir.load_json(file.read())\n\n    with open(model_params, \"rb\") as file:\n        params = relay.load_param_dict(file.read())\n\n    mod = convert_conv2d_layout(mod, {\"nn.conv2d\": [\"NHWC\", \"HWIO\"]})\n\n    inp = np.random.randn(1, 3, 224, 224).astype(\"float32\")\n    input_name = \"image\"\n\n    executor = Executor(\"graph\", {\"link-params\": True})\n    # This line is necessary for link-params to take effect during\n    # task extraction and relay.build(...).\n    mod = mod.with_attr(\"executor\", executor)\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=target_hexagon,\n            params=params,\n            work_dir=work_dir,\n            # for faster tuning\n            max_trials_global=20000,\n            max_trials_per_task=8,\n            num_trials_per_iter=8,\n            strategy=\"replay-trace\",\n            # max_trials_global=20000,\n            # num_trials_per_iter=32,\n            # max_trials_per_task=128,\n            # strategy=\"evolutionary\",\n            builder=get_hexagon_local_builder(),\n            runner=get_hexagon_rpc_runner(hexagon_launcher, number=20),\n            # Without this, the same workloads with different constant weights\n            # are treated as distinct tuning tasks.\n            module_equality=\"ignore-ndarray\",\n        )\n\n        hexagon_lowered = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=target_hexagon,\n            params=params,\n        )\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            params=params,\n        )\n\n        llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n        llvm_graph_mod.set_input(input_name, inp.copy())\n        llvm_graph_mod.run()\n        ref_result = llvm_graph_mod.get_output(0).numpy()\n\n    with hexagon_launcher.create_session() as session:\n        graph_mod = session.get_executor_from_factory(hexagon_lowered)\n        graph_mod.set_input(input_name, inp.copy())\n\n        graph_mod.run()\n        hexagon_output = graph_mod.get_output(0).numpy()\n\n        # Example output: max and mean abs difference with the reference: 0.1406 0.0126\n        print(\n            \"max and mean abs difference with the reference:\",\n            np.max(np.abs(ref_result - hexagon_output)),\n            np.mean(np.abs(ref_result - hexagon_output)),\n        )\n        tvm.testing.assert_allclose(ref_result, hexagon_output, atol=2e-1)\n\n        time_ms = graph_mod.benchmark(session.device, number=1, repeat=20).mean * 1e3\n\n        print(\"time elapsed: \", time_ms)\n\n        debug_ex = session.get_graph_debug_executor(\n            hexagon_lowered.get_graph_json(), hexagon_lowered.lib\n        )\n        print(debug_ex.profile(input_name=inp.copy()))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/metaschedule_e2e/test_resnet50_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test Resnet50 int8 with MetaSchedule\"\"\"\n\nimport os\nimport tempfile\nfrom typing import Optional\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm._ffi import register_func\nfrom tvm.contrib.hexagon.meta_schedule import (\n    get_hexagon_local_builder,\n    get_hexagon_rpc_runner,\n)\nfrom tvm.meta_schedule import postproc, schedule_rule\nfrom tvm.tir.schedule import BlockRV, Schedule\nfrom tvm.tir.schedule.analysis import has_block\nfrom tvm.tir.tensor_intrin.hexagon import VRMPY_u8i8i32_INTRIN, VRMPY_u8u8i32_INTRIN\n\nfrom ..infrastructure import get_hexagon_target\n\nMODEL_JSON = \"resnet50_int8.json\"\nEXECUTOR = relay.backend.Executor(\"graph\", {\"link-params\": True})\nTARGET_LLVM = tvm.target.Target(\"llvm\")\nTARGET_HEXAGON = get_hexagon_target(\"v68\")\nMODEL_PARAMS = \"resnet50_int8.params\"\n\n\ndef tune_vrmpy_auto_tensorize(mod, params, hexagon_launcher):\n    \"\"\"Tune VRMPY with auto tensorization.\"\"\"\n    sch_rules = [\n        schedule_rule.ApplyCustomRule(),\n        schedule_rule.AutoInline(\n            into_producer=False,\n            into_consumer=True,\n            inline_const_tensor=True,\n            disallow_if_then_else=True,\n            require_injective=True,\n            require_ordered=True,\n            disallow_op=[\"tir.exp\"],\n        ),\n        # VRMPY_u8i8i32_INTRIN is used for conv2d. See topi/hexagon/conv2d_alter_op.py\n        # for why we use different intrins for conv2d and dense.\n        schedule_rule.MultiLevelTilingWithIntrin(\n            VRMPY_u8i8i32_INTRIN,\n            structure=\"SRSRS\",\n            tile_binds=None,\n            max_innermost_factor=64,\n            vector_load_lens=None,\n            reuse_read=None,\n            reuse_write=schedule_rule.ReuseType(\n                req=\"may\",\n                levels=[1, 2],\n                scope=\"global\",\n            ),\n        ),\n        # VRMPY_u8u8i32_INTRIN is used for dense\n        schedule_rule.MultiLevelTilingWithIntrin(\n            VRMPY_u8u8i32_INTRIN,\n            structure=\"SRSRS\",\n            tile_binds=None,\n            max_innermost_factor=64,\n            vector_load_lens=None,\n            reuse_read=None,\n            reuse_write=schedule_rule.ReuseType(\n                req=\"may\",\n                levels=[1, 2],\n                scope=\"global\",\n            ),\n        ),\n        schedule_rule.ParallelizeVectorizeUnroll(\n            max_jobs_per_core=16,\n            max_vectorize_extent=128,\n            unroll_max_steps=[0, 16, 64, 512],\n            unroll_explicit=True,\n        ),\n    ]\n\n    postprocs = [\n        postproc.RewriteParallelVectorizeUnroll(),\n        postproc.RewriteReductionBlock(),\n        postproc.RewriteTensorize(vectorize_init_loop=True),\n    ]\n\n    # This line is necessary for link-params to take effect during\n    # task extraction and relay.build(...).\n    mod = mod.with_attr(\"executor\", EXECUTOR)\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=TARGET_HEXAGON,\n            params=params,\n            work_dir=work_dir,\n            # for faster tuning\n            max_trials_global=20000,\n            max_trials_per_task=8,\n            num_trials_per_iter=8,\n            strategy=\"replay-trace\",\n            # max_trials_global=20000,\n            # num_trials_per_iter=32,\n            # max_trials_per_task=128,\n            # strategy=\"evolutionary\",\n            builder=get_hexagon_local_builder(),\n            runner=get_hexagon_rpc_runner(hexagon_launcher, number=20),\n            space=ms.space_generator.PostOrderApply(\n                sch_rules=sch_rules,\n                postprocs=postprocs,\n                mutator_probs={},\n            ),\n            # This enables anchor-block tuning, where different subgraphs\n            # with the same anchor block workload will be identified as equal.\n            # It reduces the number of conv2d tuning tasks in the int8 resnet50 model\n            # from 36 to 23, with negligible performance difference.\n            module_equality=\"anchor-block\",\n        )\n\n        return ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=TARGET_HEXAGON,\n            params=params,\n        )\n\n\n@pytest.mark.skip(\"End-to-end tuning is skipped on CI.\")\n@tvm.testing.requires_hexagon\ndef test_resnet50(hexagon_launcher):\n    \"\"\"Test Resnet50.\"\"\"\n    if not os.path.exists(MODEL_JSON):\n        pytest.skip(msg=\"Run python export_models.py first.\")\n\n    with open(MODEL_JSON, \"r\") as file:\n        mod = tvm.ir.load_json(file.read())\n\n    with open(MODEL_PARAMS, \"rb\") as file:\n        params = relay.load_param_dict(file.read())\n    inp = np.random.randn(1, 3, 224, 224).astype(\"float32\")\n    input_name = \"image\"\n\n    do_tune = True\n\n    if do_tune:\n        hexagon_lowered = tune_vrmpy_auto_tensorize(mod, params, hexagon_launcher)\n    else:\n        with tvm.transform.PassContext(opt_level=3):\n            hexagon_lowered = relay.build(\n                mod,\n                tvm.target.Target(TARGET_HEXAGON, host=TARGET_HEXAGON),\n                params=params,\n                executor=EXECUTOR,\n            )\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            mod,\n            tvm.target.Target(TARGET_LLVM, host=TARGET_LLVM),\n            params=params,\n        )\n\n    with hexagon_launcher.create_session() as session:\n        graph_mod = session.get_executor_from_factory(hexagon_lowered)\n        graph_mod.set_input(input_name, inp.copy())\n        graph_mod.run()\n        hexagon_output = graph_mod.get_output(0).numpy()\n\n        llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n        llvm_graph_mod.set_input(input_name, inp.copy())\n        llvm_graph_mod.run()\n        ref_result = llvm_graph_mod.get_output(0).numpy()\n\n        np.testing.assert_allclose(ref_result, hexagon_output, atol=1e-4, rtol=1e-5)\n\n        time_ms = graph_mod.benchmark(session.device, number=1, repeat=20).mean * 1e3\n\n        print(\"time elapsed: \", time_ms)\n\n        debug_ex = session.get_graph_debug_executor(\n            hexagon_lowered.get_graph_json(), hexagon_lowered.lib\n        )\n        print(debug_ex.profile(input_name=inp.copy()))\n\n\ndef _schedule_packed_8x8x32_conv2d():\n    \"\"\"Manually schedule a conv2d block, created from TE compute op via CreatePrimFunc,\n    using 8x8x32 packed layout.\n    \"\"\"\n\n    def schedule_fn(sch, conv2d_block: Optional[BlockRV] = None) -> bool:\n        if conv2d_block is None:\n            if has_block(sch, \"conv2d_NCHWc_int8\"):\n                conv2d_block = sch.get_block(\"conv2d_NCHWc_int8\")\n            else:\n                return False\n\n        assert \"conv2d_NCHWc_int8\" in sch.get(conv2d_block).annotations[\"schedule_rule\"]\n\n        # Apply scheduling\n\n        post_blocks = sch.get_consumers(conv2d_block)\n        if len(post_blocks) > 0:\n            # Fuse all intermediate post ops into the last op.\n            # This is equivalent to the traverse_inline function used in TE schedules.\n            while True:\n                next_post_blocks = []\n                for post_block in post_blocks:\n                    next_consumers = sch.get_consumers(post_block)\n                    if len(next_consumers) > 0:\n                        sch.compute_inline(post_block)\n                    next_post_blocks += next_consumers\n                if len(next_post_blocks) == 0:\n                    assert len(post_blocks) == 1\n                    outer_block = post_blocks[0]\n                    break\n                post_blocks = next_post_blocks\n        else:\n            outer_block = conv2d_block\n\n        # Move the conv2d mma into the injective post mma compute block\n        if outer_block != conv2d_block:\n            loops = sch.get_loops(outer_block)\n            # TODO(csullivan): Currently does all post conv2d mma steps\n            # directly after accumulation for one spatial pixel. May\n            # be desirable to do this with coarser spatial granularity\n            sch.compute_at(conv2d_block, loops[4])\n\n        def index_map_nchw32c_nchw8h8w32c(n_batch, channel, height, width, channel_32):\n            return [n_batch, channel, height // 8, width // 8, height % 8, width % 8, channel_32]\n\n        # Add cache for input and output activation layout transform,\n        # note that weight is already in correct layout\n        input_cache = sch.cache_read(conv2d_block, 0, \"global\")  # pylint: disable=unused-variable\n        output_cache = sch.cache_write(outer_block, 0, \"global\")  # pylint: disable=unused-variable\n        # Transform the layout of the input\n        sch.transform_layout(\n            conv2d_block, (\"read\", 0), index_map=index_map_nchw32c_nchw8h8w32c, pad_value=0\n        )\n        # Transform the layout of the int32 accumulator\n        sch.transform_layout(\n            conv2d_block, (\"write\", 0), index_map=index_map_nchw32c_nchw8h8w32c, pad_value=0\n        )\n        # Transform the layout of the output\n        sch.transform_layout(\n            outer_block, (\"write\", 0), index_map=index_map_nchw32c_nchw8h8w32c, pad_value=0\n        )\n        return True\n\n    return schedule_fn\n\n\ndef tune_packed_8x8x32_template(mod, params, hexagon_launcher):\n    \"\"\"Generate packed 8*8*32 template.\"\"\"\n\n    def schedule_rule_conv2d_packed_8x8x32(sch: Schedule, conv2d_block: BlockRV):\n        _schedule_packed_8x8x32_conv2d()(sch, conv2d_block)\n        return [sch]\n\n    register_func(\"meta_schedule.conv2d_NCHWc_int8.hexagon\", schedule_rule_conv2d_packed_8x8x32)\n\n    def schedule_conv2d_for_tune(sch: Schedule):\n        _schedule_packed_8x8x32_conv2d()(sch)\n\n    # This line is necessary for link-params to take effect during\n    # task extraction and relay.build(...).\n    mod = mod.with_attr(\"executor\", EXECUTOR)\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=TARGET_HEXAGON,\n            params=params,\n            work_dir=work_dir,\n            max_trials_global=20000,\n            max_trials_per_task=1,\n            num_trials_per_iter=1,\n            strategy=\"replay-trace\",\n            builder=get_hexagon_local_builder(),\n            runner=get_hexagon_rpc_runner(hexagon_launcher, number=20),\n            # Apply MS auto scheduling rules for all blocks, but utilize\n            # the custom block scheduling strategy registered above for\n            # blocks annotated as `schedule_rule:meta_schedule.conv2d_NCHWc_int8`\n            # space=ms.space_generator.PostOrderApply(\n            #     f_block_filter=None,\n            #     sch_rules=\"from-target\",\n            #     postprocs=[],\n            #     mutator_probs=\"from-target\",\n            # ),\n            # Constrain search space to only be the single\n            # schedule provided for all blocks. No auto\n            # scheduling will be possible.\n            space=ms.space_generator.ScheduleFn(\n                schedule_conv2d_for_tune,\n                sch_rules=[],\n                postprocs=[],\n                mutator_probs={},\n            ),\n            # Without this, the same workloads with different constant weights\n            # are treated as distinct tuning tasks.\n            module_equality=\"ignore-ndarray\",\n        )\n        return ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            target=TARGET_HEXAGON,\n            params=params,\n        )\n\n\n@pytest.mark.skip(\"End-to-end tuning is skipped on CI.\")\n@tvm.testing.requires_hexagon\ndef test_packed_8x8x32_resnet50(hexagon_launcher):\n    \"\"\"Test packed 8*8*32 Resnet50\"\"\"\n    if not os.path.exists(MODEL_JSON):\n        pytest.skip(msg=\"Run python export_models.py first.\")\n\n    with open(MODEL_JSON, \"r\") as file:\n        mod = tvm.ir.load_json(file.read())\n\n    with open(MODEL_PARAMS, \"rb\") as file:\n        params = relay.load_param_dict(file.read())\n    inp = np.random.randn(1, 3, 224, 224).astype(\"float32\")\n    input_name = \"image\"\n\n    do_tune = True\n\n    if do_tune:\n        hexagon_lowered = tune_packed_8x8x32_template(mod, params, hexagon_launcher)\n    else:\n        with tvm.transform.PassContext(opt_level=3):\n            hexagon_lowered = relay.build(\n                mod,\n                tvm.target.Target(TARGET_HEXAGON, host=TARGET_HEXAGON),\n                params=params,\n                executor=EXECUTOR,\n            )\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            mod,\n            tvm.target.Target(TARGET_LLVM, host=TARGET_LLVM),\n            params=params,\n        )\n\n    with hexagon_launcher.start_session() as session:\n        graph_mod = session.get_executor_from_factory(hexagon_lowered)\n        graph_mod.set_input(input_name, inp.copy())\n        graph_mod.run()\n        hexagon_output = graph_mod.get_output(0).numpy()\n\n        llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n        llvm_graph_mod.set_input(input_name, inp.copy())\n        llvm_graph_mod.run()\n        ref_result = llvm_graph_mod.get_output(0).numpy()\n\n        np.testing.assert_allclose(ref_result, hexagon_output, atol=1e-4, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/pytest_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Hexagon pytest utility functions \"\"\"\n\nfrom typing import List, Optional, Union\nimport collections\nimport numpy as np\n\n\ndef get_test_id(*test_params, test_param_descs: List[Optional[str]] = None) -> str:\n    \"\"\"\n    An opinionated alternative to pytest's default algorithm for generating a\n    test's ID string.  Intended to make it easier for human readers to\n    interpret the test IDs.\n\n    'test_params': The sequence of pytest parameter values supplied to some unit\n       test.\n\n    'test_param_descs': An (optional) means to provide additional text for some/all of the\n       paramuments in 'test_params'.\n\n       If provided, then len(test_params) must equal len(test_param_descs).\n       Each element test_param_descs that is a non-empty string will be used\n       in some sensible way in this function's returned string.\n    \"\"\"\n\n    assert len(test_params) > 0\n\n    if test_param_descs is None:\n        test_param_descs = [None] * len(test_params)\n    else:\n        assert len(test_param_descs) == len(test_params)\n\n    def get_single_param_chunk(param_val, param_desc: Optional[str]):\n        if isinstance(param_val, list):\n            # Like str(list), but avoid the whitespace padding.\n            val_str = \"[\" + \",\".join(str(x) for x in param_val) + \"]\"\n            need_prefix_separator = False\n\n        elif isinstance(param_val, bool):\n            if param_val:\n                val_str = \"T\"\n            else:\n                val_str = \"F\"\n            need_prefix_separator = True\n\n        elif isinstance(param_val, TensorContentConstant):\n            val_str = f\"const[{param_val.elem_value}]\"\n            need_prefix_separator = True\n\n        elif isinstance(param_val, TensorContentDtypeMin):\n            val_str = \"min\"\n            need_prefix_separator = True\n\n        elif isinstance(param_val, TensorContentDtypeMax):\n            val_str = \"max\"\n            need_prefix_separator = True\n\n        elif isinstance(param_val, TensorContentRandom):\n            val_str = \"random\"\n            need_prefix_separator = True\n\n        elif isinstance(param_val, TensorContentSequentialCOrder):\n            val_str = f\"seqC[start:{param_val.start_value},inc:{param_val.increment}]\"\n            need_prefix_separator = True\n\n        else:\n            val_str = str(param_val)\n            need_prefix_separator = True\n\n        if param_desc and need_prefix_separator:\n            return f\"{param_desc}:{val_str}\"\n        elif param_desc and not need_prefix_separator:\n            return f\"{param_desc}{val_str}\"\n        else:\n            return val_str\n\n    chunks = [\n        get_single_param_chunk(param_val, param_desc)\n        for param_val, param_desc in zip(test_params, test_param_descs)\n    ]\n    return \"-\".join(chunks)\n\n\ndef get_multitest_ids(\n    multitest_params_list: List[List], param_descs: Optional[List[Optional[str]]]\n) -> List[str]:\n    \"\"\"\n    A convenience function for classes that use both 'tvm.testing.parameters' and 'get_test_id'.\n\n    This function provides a workaround for a specific quirk in Python, where list-comprehension\n    can't necessarily access the value of another class-variable, discused here:\n    https://stackoverflow.com/q/13905741\n    \"\"\"\n    return [\n        get_test_id(*single_test_param_list, test_param_descs=param_descs)\n        for single_test_param_list in multitest_params_list\n    ]\n\n\ndef get_numpy_dtype_info(dtype) -> Union[np.finfo, np.iinfo]:\n    \"\"\"\n    Return an appropriate 'np.iinfo' or 'np.finfo' object corresponding to\n    the specified Numpy dtype.\n\n    'dtype' must be a value that 'numpy.dtype(...)' can handle.\n    \"\"\"\n    np_dtype = np.dtype(dtype)\n    kind = np_dtype.kind\n\n    if kind == \"f\":\n        return np.finfo(np_dtype)\n    elif kind == \"i\":\n        return np.iinfo(np_dtype)\n    else:\n        raise TypeError(f\"dtype ({dtype}) must indicate some floating-point or integral data type\")\n\n\nTensorContentConstant = collections.namedtuple(\"TensorContentConstant\", [\"elem_value\"])\nTensorContentSequentialCOrder = collections.namedtuple(\n    \"TensorContentSequentialCOrder\", [\"start_value\", \"increment\"]\n)\nTensorContentRandom = collections.namedtuple(\"TensorContentRandom\", [])\nTensorContentDtypeMin = collections.namedtuple(\"TensorContentDtypeMin\", [])\nTensorContentDtypeMax = collections.namedtuple(\"TensorContentDtypeMax\", [])\n\n\ndef create_populated_numpy_ndarray(\n    input_shape: Union[list, tuple], dtype: str, input_tensor_populator\n) -> np.ndarray:\n    \"\"\"\n    Create a numpy tensor with the specified shape, dtype, and content.\n    \"\"\"\n    itp = input_tensor_populator  # just for brevity\n\n    if isinstance(itp, TensorContentConstant):\n        return np.full(tuple(input_shape), itp.elem_value, dtype=dtype)\n\n    elif isinstance(itp, TensorContentDtypeMin):\n        info = get_numpy_dtype_info(dtype)\n        return np.full(tuple(input_shape), info.min, dtype=dtype)\n\n    elif isinstance(itp, TensorContentDtypeMax):\n        info = get_numpy_dtype_info(dtype)\n        return np.full(tuple(input_shape), info.max, dtype=dtype)\n\n    elif isinstance(itp, TensorContentRandom):\n        return np.random.random(input_shape).astype(dtype)\n\n    elif isinstance(itp, TensorContentSequentialCOrder):\n        a = np.empty(tuple(input_shape), dtype)\n\n        with np.nditer(a, op_flags=[\"writeonly\"], order=\"C\") as iterator:\n            next_elem_val = itp.start_value\n            for elem in iterator:\n                elem[...] = next_elem_val\n                next_elem_val += itp.increment\n        return a\n\n    else:\n        raise ValueError(f\"Unexpected input_tensor_populator type: {type(itp)}\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_2d_physical_buffers.py",
        "content": "#!/usr/bin/env python3\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test 2d physical buffers \"\"\"\n\nimport contextlib\n\nimport numpy as np\nimport pytest\nimport tvm\n\n# Needed to register the link_shared packedfunc.\nimport tvm.contrib.hexagon\nimport tvm.testing\nfrom tvm import te\nfrom tvm.contrib.hexagon.pytest_plugin import requires_hexagon_toolchain\nfrom tvm.tir.stmt_functor import post_order_visit\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom .infrastructure import get_hexagon_target\n\n# Disabling invalid name as pylint assumes global variables as constants and\n# expects them to be all upper-case. Since these are used as\n# tvm.testing.parameters, if they are made upper-case, the functions which take\n# them as arguments would also need to be upper-case, and pylint would complain\n# there as well\n# pylint: disable=invalid-name\n\nschedule_type = tvm.testing.parameter(\"TE\", \"TIR\")\n\ndtype = tvm.testing.parameter(\"int8\")\nbatch_size = tvm.testing.parameter(\n    16,\n    2,\n)\ninput_channels = tvm.testing.parameter(\n    32,\n)\ninput_image_shape = tvm.testing.parameter(\n    by_dict={\n        \"8x8\": (8, 8),\n        \"32x32\": (32, 32),\n    }\n)\n\ninput_layout = tvm.testing.parameter(\n    \"nhwc\",\n    \"nchw-8h8w32c-1d\",\n)\noutput_layout = tvm.testing.parameter(\n    \"nhwc\",\n    \"nchw-8h8w32c-1d\",\n)\nworking_layout, working_scope = tvm.testing.parameters(\n    (\"nhwc\", \"global\"),\n    (\"nhwc\", \"global.vtcm\"),\n    (\"nchw-8h8w32c-1d\", \"global\"),\n    (\"nchw-8h8w32c-1d\", \"global.vtcm\"),\n    # 2-d memory may only occur in vtcm memory\n    (\"nchw-8h8w32c-2d\", \"global.vtcm\"),\n)\n\n# pylint: enable=invalid-name\n\n\n@tvm.testing.fixture\ndef target_host():\n    \"\"\"Return tvm target.Target with host attached\"\"\"\n    return get_hexagon_target(\"v68\")\n\n\n# Disabling redefined-outer-name for the whole file as there isn't any easy\n# solution yet to refactor tvm.testing.fixture fixtures that avoid redefining\n# outer variable names\n# pylint: disable=redefined-outer-name\n\n\n@tvm.testing.fixture\ndef input_shape(batch_size, input_channels, input_image_shape):\n    return [batch_size, *input_image_shape, input_channels]\n\n\ndef transform_shape(shape, layout):\n    if layout == \"nhwc\":\n        return shape\n    if layout in [\"nchw-8h8w32c-1d\", \"nchw-8h8w32c-2d\"]:\n        batch, height, width, channel = shape\n        return [batch, (channel + 31) // 32, (height + 7) // 8, (width + 7) // 8, 8, 8, 32]\n    raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n\ndef transform_numpy(arr_np, layout):\n    if layout == \"nhwc\":\n        return arr_np\n    if layout in [\"nchw-8h8w32c-1d\", \"nchw-8h8w32c-2d\"]:\n        batch, height, width, channel = arr_np.shape\n        return arr_np.reshape([batch, height // 8, 8, width // 8, 8, channel // 32, 32]).transpose(\n            0, 5, 1, 3, 2, 4, 6\n        )\n    raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n\n@tvm.testing.fixture\ndef transformed_input_shape(input_shape, input_layout):\n    return transform_shape(input_shape, input_layout)\n\n\n@tvm.testing.fixture\ndef transformed_output_shape(output_shape, output_layout):\n    return transform_shape(output_shape, output_layout)\n\n\n@tvm.testing.fixture\ndef input_np(input_shape, dtype):\n    return (100 * np.random.uniform(size=input_shape)).astype(dtype)\n\n\n@tvm.testing.fixture\ndef transformed_input_np(input_np, input_layout):\n    return transform_numpy(input_np, input_layout)\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, output_layout):\n    return transform_numpy(expected_output_np, output_layout)\n\n\ndef layout_transform_1d(batch, height, width, channel):\n    return [\n        batch,\n        channel // 32,\n        height // 8,\n        width // 8,\n        height % 8,\n        width % 8,\n        channel % 32,\n    ]\n\n\ndef layout_transform_2d(batch, height, width, channel):\n    return [\n        batch,\n        channel // 32,\n        height // 8,\n        width // 8,\n        te.AXIS_SEPARATOR,\n        height % 8,\n        width % 8,\n        channel % 32,\n    ]\n\n\ndef extract_buffers(stmt):\n    buffers = []\n\n    def visitor(node):\n        if isinstance(node, (tvm.tir.BufferLoad, tvm.tir.BufferStore, tvm.tir.BufferRealize)):\n            buffers.append(node.buffer)\n\n    post_order_visit(stmt, visitor)\n    return buffers\n\n\nclass TestElementWise:\n    \"\"\"TestElementWise\"\"\"\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np):\n        return 2 * input_np\n\n    @tvm.testing.fixture\n    def output_shape(self, input_shape):\n        return input_shape\n\n    @tvm.testing.fixture\n    def schedule_args(\n        self,\n        schedule_type,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        working_layout,\n        working_scope,\n    ):\n        \"\"\"Create and return the schedule and input args after applying layout transform\"\"\"\n        if schedule_type == \"TE\":\n\n            return self._te_schedule_args(\n                input_shape, dtype, input_layout, output_layout, working_layout, working_scope\n            )\n        elif schedule_type == \"TIR\":\n            return self._tir_schedule_args(\n                input_shape, dtype, input_layout, output_layout, working_layout, working_scope\n            )\n\n        else:\n            raise ValueError(f\"Unknown schedule type: {schedule_type}\")\n\n    def _te_tensors(self, input_shape, dtype):\n        input_tensor = te.placeholder(input_shape, dtype, name=\"Input\")\n        output_tensor = te.compute(\n            shape=input_tensor.shape,\n            fcompute=lambda *indices: (2 * input_tensor[indices]).astype(dtype),\n            name=\"Output\",\n        )\n        return input_tensor, output_tensor\n\n    def _te_schedule_args(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        working_layout,\n        working_scope,\n    ):\n        input_tensor, output_tensor = self._te_tensors(input_shape, dtype)\n\n        schedule = te.create_schedule(output_tensor.op)\n\n        write_cache = schedule.cache_write(output_tensor, working_scope)\n        read_cache = schedule.cache_read(input_tensor, working_scope, [write_cache])\n\n        def apply_transform(tensor, layout):\n            if layout == \"nhwc\":\n                return None\n            if layout == \"nchw-8h8w32c-1d\":\n                return schedule[tensor].transform_layout(layout_transform_1d)\n            if layout == \"nchw-8h8w32c-2d\":\n                return schedule[tensor].transform_layout(layout_transform_2d)\n            raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n        apply_transform(input_tensor, input_layout)\n        compute_loopnest = apply_transform(output_tensor, output_layout) or output_tensor.op.axis\n        schedule[write_cache].compute_at(schedule[output_tensor], compute_loopnest[0])\n\n        apply_transform(read_cache, working_layout)\n        apply_transform(write_cache, working_layout)\n\n        return [schedule, [input_tensor, output_tensor]]\n\n    def _tir_schedule_args(\n        self, input_shape, dtype, input_layout, output_layout, working_layout, working_scope\n    ):\n        tensors = self._te_tensors(input_shape, dtype)\n\n        sch = tvm.tir.Schedule(te.create_prim_func(tensors))\n\n        cache_read_block = sch.cache_read(\"Output\", 0, working_scope)\n        cache_write_block = sch.cache_write(\"Output\", 0, working_scope)\n\n        def apply_transform(block, buffer_name, layout):\n            if layout == \"nhwc\":\n                pass\n            elif layout == \"nchw-8h8w32c-1d\":\n                sch.transform_layout(block, buffer_name, layout_transform_1d)\n            elif layout == \"nchw-8h8w32c-2d\":\n                sch.transform_layout(block, buffer_name, layout_transform_2d)\n            else:\n                raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n        apply_transform(cache_read_block, (\"read\", 0), input_layout)\n        apply_transform(cache_read_block, (\"write\", 0), working_layout)\n        apply_transform(cache_write_block, (\"read\", 0), working_layout)\n        apply_transform(cache_write_block, (\"write\", 0), output_layout)\n\n        return [sch.mod]\n\n    @tvm.testing.fixture\n    def ir_module(self, schedule_args):\n        # If the two buffers are accessed with the same indices, CSE\n        # will replace them with a Let binding.  Since this makes it\n        # harder to test what the transformed indices are, disabling\n        # the CSE pass for this test.\n        with tvm.transform.PassContext(disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n            return tvm.lower(*schedule_args)\n\n    @tvm.testing.fixture\n    def uses_unsupported_physical_dimensions(  # pylint: disable=invalid-name\n        self, target_host, input_layout, working_layout, output_layout\n    ):\n        uses_2d_memory = \"nchw-8h8w32c-2d\" in [input_layout, working_layout, output_layout]\n        can_handle_2d_memory = target_host.kind.name == \"hexagon\"\n\n        return uses_2d_memory and not can_handle_2d_memory\n\n    def test_param_shapes(self, ir_module, transformed_input_shape, transformed_output_shape):\n        func = ir_module[\"main\"]\n        primfunc_input_shape, primfunc_output_shape = [\n            list(func.preflattened_buffer_map[param].shape) for param in func.params\n        ]\n        assert primfunc_input_shape == transformed_input_shape\n        assert primfunc_output_shape == transformed_output_shape\n\n    def test_cache_shape(self, ir_module, input_layout, working_layout, output_layout):\n        \"\"\"Test function to check expected_physical_dimensions for cached buffers\"\"\"\n        func = ir_module[\"main\"]\n        for buffer in extract_buffers(func.body):\n            buffer_layout = {\n                \"Input\": input_layout,\n                \"Input.global\": working_layout,\n                \"Output.global\": working_layout,\n                \"Input.global.vtcm\": working_layout,\n                \"Output.global.vtcm\": working_layout,\n                \"Output\": output_layout,\n            }[buffer.name.replace(\"_\", \".\")]\n\n            expected_physical_dimensions = {\n                \"nhwc\": 1,\n                \"nchw-8h8w32c-1d\": 1,\n                \"nchw-8h8w32c-2d\": 2,\n            }[buffer_layout]\n\n            assert len(buffer.shape) == expected_physical_dimensions\n\n    def test_lower(self, schedule_args):\n        return tvm.lower(*schedule_args)\n\n    @requires_hexagon_toolchain\n    def test_build(self, schedule_args, target_host, input_layout, working_layout, output_layout):\n        \"\"\"Testing build success/failure\n\n        * On Hexagon targets, build must succeed for both 1-d and 2-d memory.\n        * On non-Hexagon targets, build must succeed 1-d memory.\n        * On non-Hexagon targets, build must fail and report an error for 2-d memory.\n        \"\"\"\n        # contextlib.nullcontext wasn't added until python3.7, and the\n        # CI currently runs on python3.6.  Therefore, using ExitStack\n        # to manage an optional context instead.\n        stack = contextlib.ExitStack()\n\n        with stack:\n            is_hexagon = target_host.kind.name == \"hexagon\"\n            uses_2d_memory = \"nchw-8h8w32c-2d\" in [input_layout, working_layout, output_layout]\n            if uses_2d_memory and not is_hexagon:\n                stack.enter_context(pytest.raises(tvm.TVMError))\n\n            tvm.build(*schedule_args, target=target_host)\n\n    @tvm.testing.fixture\n    def runtime_module(self, schedule_args, target_host):\n        if target_host.kind.name != \"hexagon\":\n            pytest.skip(\"Only running on hexagon\")\n\n        return tvm.build(*schedule_args, target=target_host)\n\n    @tvm.testing.requires_hexagon\n    def test_execute(\n        self,\n        runtime_module,\n        transformed_input_np,\n        transformed_expected_output_np,\n        input_layout,\n        output_layout,\n        hexagon_session,\n    ):\n        \"\"\"Test execution of computes with 2d physical buffers\"\"\"\n        if input_layout == \"nchw-8h8w32c-2d\":\n            input_axis_separators = [4]\n        else:\n            input_axis_separators = []\n\n        if output_layout == \"nchw-8h8w32c-2d\":\n            output_axis_separators = [4]\n        else:\n            output_axis_separators = []\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=input_axis_separators,\n        )\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=np.zeros_like(transformed_expected_output_np),\n            axis_separators=output_axis_separators,\n        )\n\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_arr, output_arr)\n        output_np = output_arr.numpy()\n\n        np.testing.assert_array_equal(output_np, transformed_expected_output_np)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_async_dma_pipeline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test different strategies for loading data into vtcm before running HVX workloads. \"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom numpy.random import default_rng\nfrom tvm.script import tir as T\n\nVRMPY_SIZE_B = 128\nVRMPY_SIZE_INT32 = 32\n\n\ndef conv_approximation(size_a, size_w):\n    \"\"\"Conv approximation.\"\"\"\n    a_shape = (size_a, VRMPY_SIZE_B)\n    w_shape = (size_w, VRMPY_SIZE_B)\n    out_shape = (size_a, VRMPY_SIZE_INT32)\n\n    @T.prim_func\n    def operator(a_input: T.handle, b_input: T.handle, c_output: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a_input, a_shape, dtype=\"uint8\")\n        w_buffer = T.match_buffer(b_input, w_shape, dtype=\"uint8\")\n        c_buffer = T.match_buffer(c_output, out_shape, dtype=\"int32\")\n        for n, index_0 in T.grid(size_a, size_w):\n            with T.block(\"c_buffer\"):\n                vn_index, vi_index = T.axis.remap(\"SR\", [n, index_0])\n                T.reads(\n                    a_buffer[vn_index, 0:VRMPY_SIZE_B],\n                    w_buffer[vi_index, 0:VRMPY_SIZE_B],\n                    c_buffer[vn_index, 0:VRMPY_SIZE_INT32],\n                )\n                T.writes(c_buffer[vn_index, 0:VRMPY_SIZE_INT32])\n                with T.init():\n                    for x in T.serial(VRMPY_SIZE_INT32):\n                        c_buffer[vn_index, x] = 0\n                c_buffer[vn_index, T.ramp(0, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.acc.128B\"),\n                    T.uint32(3),\n                    c_buffer[vn_index, T.ramp(0, 1, 32)],\n                    T.reinterpret(a_buffer[vn_index, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(w_buffer[vi_index, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int32x32\",\n                )\n        # Currently async DMA lowering does not add any wait to the end of schedules so\n        # for timing purposes we are manually adding a wait to ensure that all copies\n        # are complete when the schedule exits.\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.dma_wait\",\n                0,  # QueueId\n                0,  # Wait for 0 in flight\n                dtype=\"int32\",\n            )\n        )\n\n    return tvm.tir.Schedule(operator)\n\n\ndef evaluate(\n    hexagon_session,\n    sch,\n    a_data,\n    b_data,\n    c_data,\n    expected_output=None,\n    use_async_copy=0,\n    merge_async_commit_queue_scope=False,\n):\n    \"\"\"Evaluate function.\"\"\"\n    target_hexagon = tvm.target.hexagon(\"v68\", link_params=True)\n    with tvm.transform.PassContext(\n        config={\n            \"tir.use_async_copy\": use_async_copy,\n            \"tir.merge_async_commit_queue_scope\": merge_async_commit_queue_scope,\n        }\n    ):\n        func_tir = tvm.build(\n            sch.mod[\"main\"], target=tvm.target.Target(target_hexagon, host=target_hexagon)\n        )\n    module = hexagon_session.load_module(func_tir)\n\n    a_hexagon = tvm.runtime.ndarray.array(a_data, device=hexagon_session.device)\n    b_hexagon = tvm.runtime.ndarray.array(b_data, device=hexagon_session.device)\n    c_hexagon = tvm.runtime.ndarray.array(c_data, device=hexagon_session.device)\n\n    if tvm.testing.utils.IS_IN_CI:\n        # Run with reduced number and repeat for CI\n        timer = module.time_evaluator(\"__tvm_main__\", hexagon_session.device, number=1, repeat=1)\n    else:\n        timer = module.time_evaluator(\"__tvm_main__\", hexagon_session.device, number=10, repeat=10)\n\n    time = timer(a_hexagon, b_hexagon, c_hexagon)\n    if expected_output is not None:\n        tvm.testing.assert_allclose(c_hexagon.asnumpy(), expected_output)\n    return round(time.mean * 1000, 4)\n\n\ndef get_single_dma_schedule(size_a, size_w):\n    \"\"\"Generate single DMA schedule.\"\"\"\n    a_shape = (size_a, VRMPY_SIZE_B)\n    w_shape = (size_w, VRMPY_SIZE_B)\n    out_shape = (size_a, VRMPY_SIZE_INT32)\n\n    a_bytes = size_a * VRMPY_SIZE_B\n    w_bytes = size_w * VRMPY_SIZE_B\n\n    @T.prim_func\n    def operator(a_input: T.handle, b_input: T.handle, c_output: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a_input, a_shape, dtype=\"uint8\", scope=\"global\")\n        w_buffer = T.match_buffer(b_input, w_shape, dtype=\"uint8\", scope=\"global\")\n        c_buffer = T.match_buffer(c_output, out_shape, dtype=\"int32\", scope=\"global\")\n        a_global_vtcm = T.alloc_buffer(a_shape, dtype=\"uint8\", scope=\"global\")\n        w_global_vtcm = T.alloc_buffer(w_shape, dtype=\"uint8\", scope=\"global\")\n        c_global_vtcm = T.alloc_buffer(out_shape, dtype=\"int32\", scope=\"global\")\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    a_global_vtcm.data,\n                    T.tvm_stack_make_shape(size_a, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    a_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    a_buffer.data,\n                    T.tvm_stack_make_shape(size_a, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    a_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.Cast(\"int\", a_bytes),\n                dtype=\"int32\",\n            )\n        )\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    w_global_vtcm.data,\n                    T.tvm_stack_make_shape(size_w, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    w_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    w_buffer.data,\n                    T.tvm_stack_make_shape(size_w, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    w_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.Cast(\"int\", w_bytes),\n                dtype=\"int32\",\n            )\n        )\n        for n, index_0 in T.grid(size_a, size_w):\n            with T.block(\"c_buffer\"):\n                vn_index, vi_index = T.axis.remap(\"SR\", [n, index_0])\n                T.reads(\n                    a_global_vtcm[vn_index, 0:VRMPY_SIZE_B],\n                    w_global_vtcm[vi_index, 0:VRMPY_SIZE_B],\n                    c_global_vtcm[vn_index, 0:VRMPY_SIZE_INT32],\n                )\n                T.writes(c_global_vtcm[vn_index, 0:VRMPY_SIZE_INT32])\n                with T.init():\n                    for x in T.serial(VRMPY_SIZE_INT32):\n                        c_global_vtcm[vn_index, x] = 0\n                c_global_vtcm[vn_index, T.ramp(0, 1, 32)] += T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(a_global_vtcm[vn_index, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(w_global_vtcm[vi_index, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int32x32\",\n                )\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    c_buffer.data,\n                    T.tvm_stack_make_shape(size_a, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    c_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    c_global_vtcm.data,\n                    T.tvm_stack_make_shape(size_a, VRMPY_SIZE_B, dtype=\"handle\"),\n                    0,\n                    2,\n                    c_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.Cast(\"int\", a_bytes),\n                dtype=\"int32\",\n            )\n        )\n\n    sch = tvm.tir.Schedule(operator)\n\n    return sch\n\n\ndef get_fake_conv_vtcm_schedule(size_a, size_w, blocks=2):\n    \"\"\"Generate fake conv schedule with VTCM.\"\"\"\n    sch = conv_approximation(size_a, size_w)\n\n    compute_block = sch.get_block(\"c_buffer\")\n    sch.cache_read(compute_block, 1, \"global.vtcm\")\n\n    n = sch.get_loops(compute_block)[0]\n    n_outer, _ = sch.split(n, [blocks, None])\n\n    cache_read_block_a = sch.cache_read(compute_block, 0, \"global.vtcm\")\n    sch.compute_at(cache_read_block_a, n_outer)\n    sch.fuse(*sch.get_loops(cache_read_block_a)[1:])\n\n    cache_write_block_c = sch.cache_write(compute_block, 0, \"global.vtcm\")\n    sch.reverse_compute_at(cache_write_block_c, n_outer)\n    sch.fuse(*sch.get_loops(cache_write_block_c)[1:])\n\n    return sch\n\n\ndef get_multi_input_fake_conv_vtcm_schedule(size_a, size_w, blocks=2):\n    \"\"\"Generate multi input fake Conv using VTCM.\"\"\"\n    sch = conv_approximation(size_a, size_w)\n\n    compute_block = sch.get_block(\"c_buffer\")\n\n    n = sch.get_loops(compute_block)[0]\n    n_outer, _ = sch.split(n, [blocks, None])\n\n    cache_read_block_a = sch.cache_read(compute_block, 0, \"global.vtcm\")\n    sch.compute_at(cache_read_block_a, n_outer)\n    sch.fuse(*sch.get_loops(cache_read_block_a)[1:])\n\n    cache_read_block_b = sch.cache_read(compute_block, 1, \"global.vtcm\")\n    sch.compute_at(cache_read_block_b, n_outer)\n    sch.fuse(*sch.get_loops(cache_read_block_b)[1:])\n\n    cache_write_block_c = sch.cache_write(compute_block, 0, \"global.vtcm\")\n    sch.reverse_compute_at(cache_write_block_c, n_outer)\n    sch.fuse(*sch.get_loops(cache_write_block_c)[1:])\n\n    return sch\n\n\ndef print_results(test_key, runtimes):\n    print(test_key)\n    for runtime in runtimes.items():\n        print(\"-{} took {} ms\".format(runtime[0], runtime[1]))\n    print()\n\n\nclass TestAsyncDMAPipeline:\n    \"\"\"Async DMA pipeline test class.\"\"\"\n\n    # Removed most of these to speedup CI.\n    size_a = tvm.testing.parameter(\n        1024,\n        64 * 64,\n        128 * 64,\n    )\n\n    size_w = tvm.testing.parameter(\n        1 * 1,\n        3 * 3,\n        9 * 9,\n    )\n\n    @tvm.testing.fixture\n    def input_a(self, size_a):\n        return default_rng().integers(0, 8, (size_a, VRMPY_SIZE_B), dtype=\"uint8\")\n\n    @tvm.testing.fixture\n    def input_w(self, size_w):\n        return default_rng().integers(0, 8, (size_w, VRMPY_SIZE_B), dtype=\"uint8\")\n\n    @tvm.testing.fixture\n    def expected_output(self, size_a, size_w, input_a, input_w):\n        \"\"\"Generate expected output.\"\"\"\n        if tvm.testing.utils.IS_IN_CI and (size_a > 1024 or size_w > 1):\n            pytest.skip(\"Skipping test since it takes too long in CI.\")\n        expected_result = np.zeros((size_a, VRMPY_SIZE_INT32), dtype=\"int32\")\n        for n in range(size_a):\n            for x in range(size_w):\n                for index_0 in range(VRMPY_SIZE_INT32):\n                    for r_index in range(4):\n                        expected_result[n, index_0] += np.uint32(\n                            input_a[n, index_0 * 4 + r_index]\n                        ) * np.uint32(input_w[x, index_0 * 4 + r_index])\n        return expected_result\n\n    @tvm.testing.requires_hexagon\n    def test_loading_vtcm_for_vrmpy(\n        self,\n        hexagon_session,\n        size_a,\n        size_w,\n        input_a,\n        input_w,\n        expected_output,\n    ):\n        \"\"\"VTCM for VRMPY test.\"\"\"\n\n        if tvm.testing.utils.IS_IN_CI and (size_a > 1024 or size_w > 1):\n            pytest.skip(\"Skipping test since it takes too long in CI.\")\n\n        sch = conv_approximation(size_a, size_w)\n        base_runtime = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n        )\n\n        sch = get_fake_conv_vtcm_schedule(size_a, size_w)\n        base_vtcm_runtime = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n        )\n\n        sch = get_fake_conv_vtcm_schedule(size_a, size_w)\n        n = sch.get_loops(sch.get_block(\"c_buffer\"))[0]\n        sch.annotate(n, \"software_pipeline_stage\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_order\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_async_stages\", [0])\n        async_input_runtime = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n        )\n\n        sch = get_fake_conv_vtcm_schedule(size_a, size_w)\n        n = sch.get_loops(sch.get_block(\"c_buffer\"))[0]\n        sch.annotate(n, \"software_pipeline_stage\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_order\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_async_stages\", [0, 2])\n        async_input_output = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n        )\n\n        sch = get_fake_conv_vtcm_schedule(size_a, size_w)\n        n = sch.get_loops(sch.get_block(\"c_buffer\"))[0]\n        sch.annotate(n, \"software_pipeline_stage\", [0, 3, 6])\n        sch.annotate(n, \"software_pipeline_order\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_async_stages\", [0, 6])\n        async_larger_buffers = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n        )\n\n        sch = get_multi_input_fake_conv_vtcm_schedule(size_a, size_w)\n        n = sch.get_loops(sch.get_block(\"c_buffer\"))[0]\n        sch.annotate(n, \"software_pipeline_stage\", [0, 0, 1, 2])\n        sch.annotate(n, \"software_pipeline_order\", [0, 1, 2, 3])\n        sch.annotate(n, \"software_pipeline_async_stages\", [0, 2])\n        async_multi_input_output = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n            merge_async_commit_queue_scope=False,\n        )\n\n        sch = get_fake_conv_vtcm_schedule(size_a, size_w)\n        n = sch.get_loops(sch.get_block(\"c_buffer\"))[0]\n        sch.annotate(n, \"software_pipeline_stage\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_order\", [0, 1, 2])\n        sch.annotate(n, \"software_pipeline_async_stages\", [2])\n        async_output_runtime = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n            use_async_copy=1,\n        )\n\n        sch = get_single_dma_schedule(size_a, size_w)\n        single_dma_runtime = evaluate(\n            hexagon_session,\n            sch,\n            input_a,\n            input_w,\n            np.zeros(expected_output.shape, \"int32\"),\n            expected_output,\n        )\n\n        # Total transfer size is equal to the size of\n        # a_buffer + w_buffer + c_buffer which is equal to 2 * size_a * 128 + size_w * 128\n        transfer_mb = round((2 * size_a * VRMPY_SIZE_B + size_w * VRMPY_SIZE_B) / 1e6, 2)\n\n        # Total number of operations can be calculated given\n        # the total number of vrmpy calls (size_a * size_w) * operations\n        # per vrmpy accumulate (128 multiplies + 3 adds for reduction\n        # per lane + 1 add for accumulate per lane)\n        complexity = round(size_a * size_w * (VRMPY_SIZE_B * 4) / 1e9, 3)\n        print_results(\n            (\n                f\"Test with a_buffer.size: {size_a * VRMPY_SIZE_B}, w_buffer.size:\"\n                f\" {size_w * VRMPY_SIZE_B}, computational complexity of {complexity} GOPs\"\n                f\", and total memory transfer of {transfer_mb} MB...\"\n            ),\n            {\n                \"without_vtcm\": base_runtime,\n                \"synchronous_dma\": single_dma_runtime,\n                \"base_vtcm\": base_vtcm_runtime,\n                \"async_dma_input\": async_input_runtime,\n                \"async_dma_output\": async_output_runtime,\n                \"async_dma_input_output\": async_input_output,\n                \"async_dma_multi_input_output\": async_multi_input_output,\n                \"async_input_output_runtime_larger_buffers\": async_larger_buffers,\n            },\n        )\n\n\n# from tvm.script import tir as T\n@tvm.script.ir_module\nclass ModulePipelined:\n    \"\"\"Pipelined module class.\"\"\"\n\n    # pylint: disable=no-self-argument\n    @T.prim_func\n    def main(\n        p0_buffer: T.Buffer[(1, 1, 230, 230, 4), \"uint8\"],\n        p1_buffer: T.Buffer[(2, 1, 7, 7, 1, 32, 4), \"int8\"],\n        t_cast: T.Buffer[(1, 2, 112, 112, 32), \"int32\"],\n    ) -> None:\n        # pylint: disable=missing-function-docstring\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        conv2d_nchwc_int8 = T.alloc_buffer([1, 2, 112, 112, 32], dtype=\"int32\", scope=\"global.vtcm\")\n        p0_global_vtcm = T.alloc_buffer([1, 1, 230, 230, 4], dtype=\"uint8\", scope=\"global.vtcm\")\n        p1_global_vtcm = T.alloc_buffer([2, 1, 7, 7, 1, 32, 4], dtype=\"int8\", scope=\"global.vtcm\")\n        for ax0, ax1, ax2, ax3, ax4, ax5, ax6 in T.grid(2, 1, 7, 7, 1, 32, 4):\n            with T.block(\"p1_global.vtcm\"):\n                v0_ind, v1_ind, v2_ind, v3_ind, v4_ind, v5_ind, v6_ind = T.axis.remap(\n                    \"SSSSSSS\", [ax0, ax1, ax2, ax3, ax4, ax5, ax6]\n                )\n                T.reads(p1_buffer[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind, v5_ind, v6_ind])\n                T.writes(p1_global_vtcm[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind, v5_ind, v6_ind])\n                p1_global_vtcm[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind, v5_ind, v6_ind] = p1_buffer[\n                    v0_ind, v1_ind, v2_ind, v3_ind, v4_ind, v5_ind, v6_ind\n                ]\n        for p_outer in T.serial(4):\n            for index_0 in T.serial(55876):\n                with T.block(\"p0_global.vtcm\"):\n                    v0_ind = T.axis.spatial(1, 0)\n                    v1_ind = T.axis.spatial(1, 0)\n                    v2_ind = T.axis.spatial(230, p_outer * 56 + index_0 // 916)\n                    v3_ind = T.axis.spatial(230, index_0 % 916 // 4)\n                    v4_ind = T.axis.spatial(4, index_0 % 4)\n                    T.reads(p0_buffer[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind])\n                    T.writes(p0_global_vtcm[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind])\n                    p0_global_vtcm[v0_ind, v1_ind, v2_ind, v3_ind, v4_ind] = p0_buffer[\n                        v0_ind, v1_ind, v2_ind, v3_ind, v4_ind\n                    ]\n            for index_0 in T.parallel(28):\n                for index_1, index_2, index_3 in T.grid(2, 14, 8):\n                    with T.block(\"conv2d_NCHWc_int8_o_init\"):\n                        n = T.axis.spatial(1, 0)\n                        oc_chunk = T.axis.spatial(2, index_1)\n                        o_height = T.axis.spatial(\n                            112, (p_outer * 28 + index_0) // 14 * 14 + index_2\n                        )\n                        o_width = T.axis.spatial(112, (p_outer * 28 + index_0) % 14 * 8 + index_3)\n                        oc_block_o = T.axis.spatial(1, 0)  # pylint: disable=unused-variable\n                        T.reads()\n                        T.writes(conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32])\n                        for i4_1 in T.vectorized(32):\n                            with T.block(\"conv2d_NCHWc_int8_init\"):\n                                oc_block_i_init = T.axis.spatial(32, i4_1)\n                                T.reads()\n                                T.writes(\n                                    conv2d_nchwc_int8[\n                                        n, oc_chunk, o_height, o_width, oc_block_i_init\n                                    ]\n                                )\n                                conv2d_nchwc_int8[\n                                    n, oc_chunk, o_height, o_width, oc_block_i_init\n                                ] = 0\n                for i1_1, i5_1, i6_1, i2_2, i3_2 in T.grid(2, 7, 7, 14, 8):\n                    with T.block(\"conv2d_NCHWc_int8_o_update\"):\n                        n = T.axis.spatial(1, 0)\n                        oc_chunk = T.axis.spatial(2, i1_1)\n                        o_height = T.axis.spatial(112, (p_outer * 28 + index_0) // 14 * 14 + i2_2)\n                        o_width = T.axis.spatial(112, (p_outer * 28 + index_0) % 14 * 8 + i3_2)\n                        oc_block_o = T.axis.spatial(1, 0)  # pylint: disable=unused-variable\n                        k_height = T.axis.reduce(7, i5_1)\n                        k_width = T.axis.reduce(7, i6_1)\n                        ic_outer = T.axis.reduce(1, 0)\n                        ic_f_inner = T.axis.reduce(1, 0)\n                        ic_s_inner_o = T.axis.reduce(1, 0)  # pylint: disable=unused-variable\n                        T.reads(\n                            conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32],\n                            p0_global_vtcm[\n                                n,\n                                ic_outer,\n                                o_height * 2 + k_height,\n                                o_width * 2 + k_width,\n                                ic_f_inner * 4 : ic_f_inner * 4 + 4,\n                            ],\n                            p1_global_vtcm[\n                                oc_chunk, ic_outer, k_height, k_width, ic_f_inner, 0:32, 0:4\n                            ],\n                        )\n                        T.writes(conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32])\n                        a_buffer = T.match_buffer(\n                            p0_global_vtcm[\n                                n,\n                                ic_outer,\n                                o_height * 2 + k_height,\n                                o_width * 2 + k_width,\n                                ic_f_inner * 4 : ic_f_inner * 4 + 4,\n                            ],\n                            [4],\n                            dtype=\"uint8\",\n                            offset_factor=1,\n                            scope=\"global.vtcm\",\n                        )\n                        b_buffer = T.match_buffer(\n                            p1_global_vtcm[\n                                oc_chunk, ic_outer, k_height, k_width, ic_f_inner, 0:32, 0:4\n                            ],\n                            [32, 4],\n                            dtype=\"int8\",\n                            offset_factor=1,\n                            scope=\"global.vtcm\",\n                        )\n                        c_buffer = T.match_buffer(\n                            conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32],\n                            [32],\n                            dtype=\"int32\",\n                            offset_factor=1,\n                            scope=\"global.vtcm\",\n                        )\n                        a_u8x4: T.uint8x4 = a_buffer[0:4]\n                        a_i32: T.int32 = T.reinterpret(a_u8x4, dtype=\"int32\")\n                        b_i8x128 = b_buffer[0, 0:128]\n                        b_i32x32: T.int32x32 = T.reinterpret(b_i8x128, dtype=\"int32x32\")\n                        c_buffer[0:32] = T.call_llvm_pure_intrin(\n                            4217,\n                            T.uint32(3),\n                            c_buffer[0:32],\n                            T.broadcast(a_i32, 32),\n                            b_i32x32,\n                            dtype=\"int32x32\",\n                        )\n            for index_0 in T.serial(200704):\n                with T.block(\"conv2d_nchwc_int8.vtcm\"):\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(2, index_0 % 7168 // 3584)\n                    ax2_1 = T.axis.spatial(\n                        112, (p_outer * 28 + index_0 // 7168) // 14 * 14 + index_0 % 3584 // 256\n                    )\n                    ax3_1 = T.axis.spatial(\n                        112, (p_outer * 28 + index_0 // 7168) % 14 * 8 + index_0 % 256 // 32\n                    )\n                    ax4 = T.axis.spatial(32, index_0 % 32)\n                    T.reads(conv2d_nchwc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                    T.writes(t_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                    t_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4] = conv2d_nchwc_int8[\n                        ax0_1, ax1_1, ax2_1, ax3_1, ax4\n                    ]\n\n\n# from tvm.script import tir as T\n@tvm.script.ir_module\nclass ModuleBase:\n    \"\"\"Base module test class.\"\"\"\n\n    # pylint: disable=no-self-argument\n    @T.prim_func\n    def main(\n        p0_buffer: T.Buffer[(1, 1, 230, 230, 4), \"uint8\"],\n        p1_buffer: T.Buffer[(2, 1, 7, 7, 1, 32, 4), \"int8\"],\n        t_cast: T.Buffer[(1, 2, 112, 112, 32), \"int32\"],\n    ) -> None:\n        # pylint: disable=missing-function-docstring\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # buffer definition\n        # body\n        # with T.block(\"root\")\n        conv2d_nchwc_int8 = T.alloc_buffer([1, 2, 112, 112, 32], dtype=\"int32\")\n        for i0_0_i1_0_i2_0_i3_0_fused in T.parallel(\n            112, annotations={\"pragma_auto_unroll_max_step\": 64, \"pragma_unroll_explicit\": 1}\n        ):\n            for i4_0_0 in T.serial(1):  # pylint: disable=unused-variable\n                for i1_1_init, i2_1_init, i3_1_init, i1_2_init, i2_2_init, i3_2_init in T.grid(\n                    2, 1, 1, 1, 14, 8\n                ):\n                    with T.block(\"conv2d_NCHWc_int8_o_init\"):\n                        n = T.axis.spatial(1, 0)\n                        oc_chunk = T.axis.spatial(2, i1_1_init + i1_2_init)\n                        o_height = T.axis.spatial(\n                            112, i0_0_i1_0_i2_0_i3_0_fused // 14 * 14 + i2_1_init * 14 + i2_2_init\n                        )\n                        o_width = T.axis.spatial(\n                            112, i0_0_i1_0_i2_0_i3_0_fused % 14 * 8 + i3_1_init * 8 + i3_2_init\n                        )\n                        oc_block_o = T.axis.spatial(1, 0)  # pylint: disable=unused-variable\n                        T.reads()\n                        T.writes(conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32])\n                        for i4_1 in T.vectorized(32):\n                            with T.block(\"conv2d_NCHWc_int8_init\"):\n                                oc_block_i_init = T.axis.spatial(32, i4_1)\n                                T.reads()\n                                T.writes(\n                                    conv2d_nchwc_int8[\n                                        n, oc_chunk, o_height, o_width, oc_block_i_init\n                                    ]\n                                )\n                                conv2d_nchwc_int8[\n                                    n, oc_chunk, o_height, o_width, oc_block_i_init\n                                ] = 0\n                for i5_0, i6_0, i7_0, i8_0, i9_0_0 in T.grid(  # pylint: disable=unused-variable\n                    1, 1, 1, 1, 1\n                ):  # pylint: disable=unused-variable\n                    for (\n                        i0_1,  # pylint: disable=unused-variable\n                        i1_1,\n                        i2_1,\n                        i3_1,\n                        i4_0_1,  # pylint: disable=unused-variable\n                        i5_1,\n                        i6_1,\n                        i7_1,  # pylint: disable=unused-variable\n                        i8_1,  # pylint: disable=unused-variable\n                        i9_0_1,  # pylint: disable=unused-variable\n                        i0_2,  # pylint: disable=unused-variable\n                        i1_2,\n                        i2_2,\n                        i3_2,\n                        i4_0_2,  # pylint: disable=unused-variable\n                    ) in T.grid(1, 2, 1, 1, 1, 7, 7, 1, 1, 1, 1, 1, 14, 8, 1):\n                        with T.block(\"conv2d_NCHWc_int8_o_update\"):\n                            n = T.axis.spatial(1, 0)\n                            oc_chunk = T.axis.spatial(2, i1_1 + i1_2)\n                            o_height = T.axis.spatial(\n                                112, i0_0_i1_0_i2_0_i3_0_fused // 14 * 14 + i2_1 * 14 + i2_2\n                            )\n                            o_width = T.axis.spatial(\n                                112, i0_0_i1_0_i2_0_i3_0_fused % 14 * 8 + i3_1 * 8 + i3_2\n                            )\n                            oc_block_o = T.axis.spatial(1, 0)  # pylint: disable=unused-variable\n                            k_height = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                            k_width = T.axis.reduce(7, i6_0 * 7 + i6_1)\n                            ic_outer = T.axis.reduce(1, 0)\n                            ic_f_inner = T.axis.reduce(1, 0)\n                            ic_s_inner_o = T.axis.reduce(1, 0)  # pylint: disable=unused-variable\n                            T.reads(\n                                conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32],\n                                p0_buffer[\n                                    n,\n                                    ic_outer,\n                                    o_height * 2 + k_height,\n                                    o_width * 2 + k_width,\n                                    ic_f_inner * 4 : ic_f_inner * 4 + 4,\n                                ],\n                                p1_buffer[\n                                    oc_chunk, ic_outer, k_height, k_width, ic_f_inner, 0:32, 0:4\n                                ],\n                            )\n                            T.writes(conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32])\n                            a_buffer = T.match_buffer(\n                                p0_buffer[\n                                    n,\n                                    ic_outer,\n                                    o_height * 2 + k_height,\n                                    o_width * 2 + k_width,\n                                    ic_f_inner * 4 : ic_f_inner * 4 + 4,\n                                ],\n                                [4],\n                                dtype=\"uint8\",\n                                offset_factor=1,\n                            )\n                            b_buffer = T.match_buffer(\n                                p1_buffer[\n                                    oc_chunk, ic_outer, k_height, k_width, ic_f_inner, 0:32, 0:4\n                                ],\n                                [32, 4],\n                                dtype=\"int8\",\n                                offset_factor=1,\n                            )\n                            c_buffer = T.match_buffer(\n                                conv2d_nchwc_int8[n, oc_chunk, o_height, o_width, 0:32],\n                                [32],\n                                dtype=\"int32\",\n                                offset_factor=1,\n                            )\n                            a_u8x4: T.uint8x4 = a_buffer[0:4]\n                            a_i32: T.int32 = T.reinterpret(a_u8x4, dtype=\"int32\")\n                            b_i8x128 = b_buffer[0, 0:128]\n                            b_i32x32: T.int32x32 = T.reinterpret(b_i8x128, dtype=\"int32x32\")\n                            c_buffer[0:32] = T.call_llvm_pure_intrin(\n                                4217,\n                                T.uint32(3),\n                                c_buffer[0:32],\n                                T.broadcast(a_i32, 32),\n                                b_i32x32,\n                                dtype=\"int32x32\",\n                            )\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 2, 14, 8):\n                        for ax4_fused in T.vectorized(32):\n                            with T.block(\"T_cast_2\"):\n                                ax0_1, ax1_1 = T.axis.remap(\"SS\", [ax0, ax1])\n                                ax2_1 = T.axis.spatial(\n                                    112, i0_0_i1_0_i2_0_i3_0_fused // 14 * 14 + ax2\n                                )\n                                ax3_1 = T.axis.spatial(\n                                    112, i0_0_i1_0_i2_0_i3_0_fused % 14 * 8 + ax3\n                                )\n                                ax4 = T.axis.spatial(32, ax4_fused)\n                                T.reads(conv2d_nchwc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                                T.writes(t_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                                t_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4] = conv2d_nchwc_int8[\n                                    ax0_1, ax1_1, ax2_1, ax3_1, ax4\n                                ]\n\n\n@tvm.testing.requires_hexagon\ndef test_meta(hexagon_session):\n    \"\"\"Test meta.\"\"\"\n    if tvm.testing.utils.IS_IN_CI:\n        pytest.skip(\"Skipping test since it takes too long in CI.\")\n\n    a_data = default_rng().integers(1, 8, (1, 1, 230, 230, 4), dtype=\"uint8\")\n    w_data = default_rng().integers(1, 8, (2, 1, 7, 7, 1, 32, 4), dtype=\"int8\")\n    c_data = np.zeros((1, 2, 112, 112, 32), dtype=\"int32\")\n\n    sch = tvm.tir.Schedule(ModuleBase)\n    base_runtime = evaluate(hexagon_session, sch, a_data, w_data, c_data)\n\n    sch = tvm.tir.Schedule(ModulePipelined)\n    compute_block = sch.get_block(\"conv2d_NCHWc_int8_o_update\")\n    outer = sch.get_loops(compute_block)[0]\n\n    unscheduled_vtcm_runtime = evaluate(\n        hexagon_session, sch, a_data, w_data, c_data, use_async_copy=1\n    )\n\n    sch = tvm.tir.Schedule(ModulePipelined)\n    compute_block = sch.get_block(\"conv2d_NCHWc_int8_o_update\")\n    outer = sch.get_loops(compute_block)[0]\n\n    sch.annotate(outer, \"software_pipeline_stage\", [0, 1, 2])\n    sch.annotate(outer, \"software_pipeline_order\", [0, 1, 2])\n    sch.annotate(outer, \"software_pipeline_async_stages\", [0, 2])\n\n    pipeline_runtime = evaluate(hexagon_session, sch, a_data, w_data, c_data, use_async_copy=1)\n\n    transfer_mb = round((a_data.size + w_data.size + c_data.size) / 1e6, 2)\n    print_results(\n        (\n            f\"Test with a_buffer.size: {a_data.size}, w_buffer.size: {w_data.size}\"\n            f\", and total memory transfer of {transfer_mb} MB...\"\n        ),\n        {\n            \"without_vtcm\": base_runtime,\n            \"unscheduled_vtcm_runtime\": unscheduled_vtcm_runtime,\n            \"pipeline_runtime\": pipeline_runtime,\n        },\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_autotvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Minimal example of tuning on hexagon. \"\"\"\n\nimport contextlib\nimport os\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import autotvm, te\nfrom tvm.autotvm.tuner import GATuner, XGBTuner\n\nfrom .infrastructure import get_hexagon_target\n\n\n@autotvm.template(\"demo_template\")\ndef demo_template():\n    \"\"\"Initial demo template\"\"\"\n    size_m, size_n, size_k = [1024] * 3\n    input1 = te.placeholder((size_m, size_k), dtype=\"float32\")\n    input2 = te.placeholder((size_n, size_k), dtype=\"float32\")\n    k = te.reduce_axis((0, 1024), name=\"k\")\n    output = te.compute(\n        (size_m, size_n), lambda i, j: te.sum(input1[i, k] * input2[j, k], axis=[k])\n    )\n\n    s = te.create_schedule(output.op)\n    cfg = autotvm.get_config()\n\n    _, _ = s[output].op.axis\n    (k_iter,) = s[output].op.reduce_axis\n\n    cfg.define_split(\"k_split\", k_iter, num_outputs=2)\n    _, _ = cfg[\"k_split\"].apply(s, output, k_iter)\n\n    return s, [input1, input2, output]\n\n\nclass HexagonModuleLoader:\n    \"\"\"HexagonModuleLoader\"\"\"\n\n    def __init__(self, hexagon_session, pre_load_function=None) -> None:\n        self.pre_load_function = pre_load_function\n        self.hexagon_session = hexagon_session\n\n    @contextlib.contextmanager\n    def __call__(self, remote_kwargs, build_result):\n        remote = self.hexagon_session._rpc\n        if self.pre_load_function is not None:\n            self.pre_load_function(remote, build_result)\n\n        try:\n            yield remote, self.hexagon_session.load_module(build_result)\n        finally:\n            pass\n\n\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=2048,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n    \"\"\"Tune tasks with different tuners\"\"\"\n\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n        if tuner in (\"xgb\", \"xgb-rank\"):\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"xgb_knob\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"knob\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n@pytest.mark.skip(reason=\"AutoTVM tuning is not yet enabled on Hexagon\")\n@tvm.testing.requires_hexagon\ndef test_autotvm(hexagon_session):\n    \"\"\"Top level test function for testing autotvm\"\"\"\n    logfilename = \"./hexagon.autotvm.log\"\n\n    options = {\n        \"log_filename\": logfilename,\n        \"early_stopping\": None,\n        \"measure_option\": autotvm.measure_option(\n            builder=autotvm.LocalBuilder(timeout=15),\n            runner=autotvm.RPCRunner(\n                module_loader=HexagonModuleLoader(hexagon_session),\n                key=hexagon_session._remote_kw[\"key\"],\n                host=hexagon_session._remote_kw[\"host\"],\n                port=hexagon_session._remote_kw[\"port\"],\n                number=3,\n                timeout=15,\n                min_repeat_ms=150,\n                # cooldown_interval=150\n            ),\n        ),\n    }\n    task = autotvm.task.create(\n        \"demo_template\",\n        args=[],\n        target=get_hexagon_target(\"v68\"),\n    )\n    tune_tasks([task], **options)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_benchmark_elemwise_add.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" benchmark_elemwise_add \"\"\"\n\nimport os\nimport os.path\nimport sys\nimport tempfile\n\nimport numpy as np\nimport pytest\n\nimport tvm.script\nimport tvm.testing\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.script import tir as T\n\nfrom . import benchmark_util as bu\nfrom .infrastructure import get_hexagon_target\n\n_SHOULD_SKIP_BENCHMARKS, _SKIP_BENCHMARKS_REASON = bu.skip_benchmarks_flag_and_reason()\n\n# This is a fixed detail of the v68 architecture.\nHVX_VECTOR_BYTES = 128\n\n# NOTE on server ports:\n# These tests use different port numbers for the RPC server (7070 + ...).\n# The reason is that an RPC session cannot be gracefully closed without\n# triggering TIME_WAIT state on the server socket. This prevents another\n# server to bind to the same port until the wait time elapses.\n\n_BT = bu.BenchmarksTable()\n\n_CSV_COLUMN_ORDER = [\n    # Identifies which TE-compute / TIRScript is used as the basis for the\n    # benchmarked primfunc. Only needs to be meaningful to humans.\n    \"basic_kernel\",\n    # The tensors' element type\n    \"dtype\",\n    # When applicable, indicates the particular variation of schedules\n    # apply by the Python code. Decoding this may require looking at this\n    # script's source code.\n    \"sched_type\",\n    # The memory location of the tensors used during the execution of\n    # the primfunc.  We currently assume just one location.\n    # This will likely need to be generalized as we add more sophisticated\n    # primfuncs.\n    \"mem_scope\",\n    # For primfuncs that treat tensor buffers as collections of 1D vectors,\n    # this is the number of vectors in each tensor.\n    # This will likely need to be generalized as we add more sophisticated\n    # primfuncs.\n    \"num_vectors_per_tensor\",\n    # Reserved columns defined by the BenchmarksTable class.\n    \"row_status\",\n    \"timings_min_usecs\",\n    \"timings_max_usecs\",\n    \"timings_median_usecs\",\n    \"timings_mean_usecs\",\n    \"timings_stddev_usecs\",\n    # For benchmarks that produce files on the host file system, this indicates\n    # their location. Useful for post-mortem investigation of benchmark results.\n    \"host_files_dir_path\",\n    # Miscellaneous comments about the benchmark.\n    \"comments\",\n]\n\n_HOST_OUTPUT_DIR = tempfile.mkdtemp()\n\n_PRIMFUNC_NAME = \"elemwise_add\"\n\nprint(\"-\" * 80)\nprint(\"OUTPUT DIRECTORY: {}\".format(_HOST_OUTPUT_DIR))\nprint(\"-\" * 80)\nprint()\n\n\ndef _get_irmod_elemwise_add(shape: list, dtype: str, mem_scope: str) -> tvm.ir.module.IRModule:\n    \"\"\"\n    Return an IRModule containing a single primfunc, expressed as NS-TIR.\n\n    The primfunc implements elementwise-add. Its signature is (A,B,C), where\n    A and B are the input tensors, and C is the output tensor.\n    All three tensors have the specfied shape, dtype, and mem_scope.\n\n    If the specified primfunc is known to be unsupported, raise an UnsupportedExcetion.\n    \"\"\"\n    assert len(shape) == 2\n\n    # TVMScript can reference simple Python variables, but it doesn't\n    # curently support more complex Python expressions...\n    (\n        dim0_size,\n        dim1_size,\n    ) = shape\n\n    if mem_scope == \"global.vtcm\":\n        raise bu.UnsupportedException(\"This benchmark kernel does not yet support VTCM buffers.\")\n\n        # This check is currently elided by the one above, but it should become relevant as soon\n        # as we add VTCM support to this kernel generator.\n        #\n        # Also: The VTCM budget is a very rough estimate, based only on experience.\n        # Assuming that it's even reasonable to use a hard-coded estimate AT ALL, this number\n        # may need tweaking.\n\n        # The below code is commented is commented to avoid unreachable error\n        # with pylint. Please enable this once the kernel starts supporting\n        # VTCM buffers\n\n        # Code starts below:\n        # ---- ------ -----\n        # estimated_vtcm_budget_bytes = HVX_VECTOR_BYTES * 1024\n\n        # dtype_bits = tvm._ffi.runtime_ctypes.DataType(dtype).bits\n        # assert dtype_bits % 8 == 0\n        # dtype_bytes = dtype_bits // 8\n\n        # num_vtcm_tensors = 3\n        # estimated_vtcm_needed_bytes = shape[0] * shape[1] * dtype_bytes * num_vtcm_tensors\n\n        # if estimated_vtcm_needed_bytes > estimated_vtcm_budget_bytes:\n        #     raise bu.UnsupportedException(\"Expect to exceed VTCM budget.\")\n\n    @tvm.script.ir_module\n    class BenchmarkModule:\n        \"\"\"Elementwise STIR module for benchmarking\"\"\"\n\n        # pylint: disable=no-self-argument,invalid-name,missing-function-docstring\n        @T.prim_func\n        def main(a: T.handle, b: T.handle, c: T.handle):\n            # We exchange data between function by handles, which are similar to pointer.\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n\n            A = T.match_buffer(a, shape, dtype=dtype)\n            B = T.match_buffer(b, shape, dtype=dtype)\n            C = T.match_buffer(c, shape, dtype=dtype)\n\n            for i in range(dim0_size):\n                for j in range(dim1_size):\n                    C[i, j] = A[i, j] + B[i, j]\n\n        # pylint: enable=no-self-argument,invalid-name,missing-function-docstring\n\n    return BenchmarkModule\n\n\ndef _benchmark_hexagon_elementwise_add_kernel(\n    hexagon_session: Session, shape: list, dtype: str, mem_scope: str\n):\n    \"\"\"\n    Generate and benchmark a single elementwise-add kernel for Hexagon.\n\n    Produce these outputs:\n      - Printed status updates / results to stdout and/or stderr.\n\n      - Create a new subdirectory under _HOST_OUTPUT_DIR, and populate it with\n        various logs and intermediate files.\n\n      - Add to _BT a row describing this benchmark run.\n    \"\"\"\n    # Represent the benchmark details in a form required by the benchmark table\n    # and for other logging...\n    keys_dict = {\n        \"basic_kernel\": \"ewise-add\",\n        \"dtype\": dtype,\n        \"shape\": shape,\n        \"mem_scope\": mem_scope,\n    }\n\n    desc = bu.get_benchmark_decription(keys_dict)\n\n    # Create the host-side directory for this benchmark run's files / logs...\n    host_files_dir_name = bu.get_benchmark_id(keys_dict)\n    host_files_dir_path = os.path.join(_HOST_OUTPUT_DIR, host_files_dir_name)\n    os.mkdir(host_files_dir_path)\n\n    keys_dict[\"host_files_dir_path\"] = host_files_dir_path\n\n    log_file_path = os.path.join(host_files_dir_path, \"out.txt\")\n    with open(log_file_path, \"w\", encoding=\"UTF-8\") as log_file:\n        print(f\"CONFIGURATION: {desc}\")\n        log_file.write(f\"CONFIGURATION: {desc}\\n\")\n\n        try:\n            ns_tir_module = _get_irmod_elemwise_add(shape, dtype, mem_scope)\n\n            # Dump the primfunc NS-TIR (as text) to the log file...\n            lowered_mod = tvm.lower(ns_tir_module, _PRIMFUNC_NAME)\n            log_file.write(\"LOWERED IR MODULE:\\n\")\n            log_file.write(str(lowered_mod))\n            log_file.write(\"\\n\")\n\n            # Lower the primfunc's IRModule to Hexagon object code...\n            input1 = tvm.te.placeholder(shape, dtype=dtype)\n            input2 = tvm.te.placeholder(shape, dtype=dtype)\n            output = tvm.te.placeholder(shape, dtype=dtype)\n\n            built_module: tvm.driver.build_module.OperatorModule = tvm.build(\n                ns_tir_module,\n                [\n                    input1,\n                    input2,\n                    output,\n                ],\n                get_hexagon_target(\"v69\"),\n                name=_PRIMFUNC_NAME,\n            )\n\n            # Create an actual Hexagon-native shared object file, initially stored on the\n            # host's file system...\n            host_dso_binary_path = os.path.join(host_files_dir_path, \"test_binary.so\")\n            built_module.save(host_dso_binary_path)\n            print(f\"SAVED BINARY TO HOST PATH: {host_dso_binary_path}\")\n\n            # Upload the .so to the Android device's file system (or wherever is appropriate\n            # when using the Hexagon simulator)...\n            target_dso_binary_filename = \"test_binary.so\"\n            target_dso_binary_pathname = hexagon_session.upload(\n                host_dso_binary_path, target_dso_binary_filename\n            )\n\n            # Generate our testing / validation data...\n            (\n                host_numpy_input1_data,\n                host_numpy_input2_data,\n                host_numpy_output_data_expected,\n            ) = _get_elemwise_add_reference_value_tensors(shape, dtype)\n\n            # On the target device / simulator, make our Hexagon-native shared object\n            # available for use...\n            loaded_hexagon_module: tvm.runtime.module.Module = hexagon_session.load_module(\n                target_dso_binary_pathname\n            )\n\n            # Create the target-side tensors to hold the primfunc's inputs and outputs...\n            input1_data = tvm.nd.empty(shape, dtype, hexagon_session.device, mem_scope)\n            input2_data = tvm.nd.empty(shape, dtype, hexagon_session.device, mem_scope)\n            output_data = tvm.nd.empty(shape, dtype, hexagon_session.device, mem_scope)\n\n            # Populate the primfunc's input tensors...\n            input1_data.copyfrom(host_numpy_input1_data)\n            input2_data.copyfrom(host_numpy_input2_data)\n\n            # Actually benchmark the primfunc...\n            timer = loaded_hexagon_module.time_evaluator(\n                \"main\", hexagon_session.device, number=10, repeat=1\n            )\n            timing_result = timer(input1_data, input2_data, output_data)\n\n            print(f\"TIMING RESULT: {timing_result}\")\n            log_file.write(f\"TIMING RESULT: {timing_result}\\n\")\n\n            # Verify that the computation actually happened, and produced the correct result.\n            result = output_data.numpy()\n\n            if dtype == \"float16\":\n                # These are the closest tolerance we currently expect / require for these\n                # kernels.  They may be changed in the future.\n                rel_tolerance = 0.005\n                abs_tolerance = 2.0\n            elif dtype == \"int8\":\n                rel_tolerance = 0\n                abs_tolerance = 0\n            else:\n                raise Exception(f\"Unexpected dtype: {dtype}\")\n\n            # TODO: We're assuming that *any* assertion thrown by 'assert_allclose' is because\n            # the numerical differences were too large.  But ideally this code would\n            # differentiate between (a) numerical difference errors, which should simply be\n            # recorded as a failed benchmark run, vs. (b) more serious errors that should\n            # kill the overall script.\n            try:\n                tvm.testing.assert_allclose(\n                    result, host_numpy_output_data_expected, rel_tolerance, abs_tolerance\n                )\n            except AssertionError as err:\n                raise bu.NumericalAccuracyException(str(err))\n\n            _BT.record_success(timing_result, **keys_dict)\n\n        except bu.NumericalAccuracyException as err:\n            print()\n            print(\"FAIL: Numerical accuracy error. See log file.\")\n\n            log_file.write(\"\\n\")\n            log_file.write(f\"FAIL: {err}\\n\")\n\n            _BT.record_fail(**keys_dict, comments=\"Numerical accuracy error. See log file.\")\n\n        except bu.UnsupportedException as err:\n            print()\n            print(f\"SKIP: {err}\")\n\n            log_file.write(\"\\n\")\n            log_file.write(f\"SKIP: {err}\\n\")\n\n            _BT.record_skip(**keys_dict, comments=f\"Unsupported configuration: {err}\")\n\n\ndef _get_elemwise_add_reference_value_tensors(shape: list, dtype: str):\n    \"\"\"\n    Return [A:np.array, B:np.array, C:np.array]\n\n    `A`, `B`, and `C` are reference data used to exercise and validate\n    an elementwise-add kernel: C = A+B.\n\n    NOTE: These data are primarily meant for performance testing.\n    The values may be helpful in detecting correctness issues, but that's\n    a secondary consideration here.\n    \"\"\"\n    assert len(shape) == 2\n\n    input1 = np.ndarray(shape, dtype=dtype)\n    input2 = np.ndarray(shape, dtype=dtype)\n\n    np_dtype = input1.dtype\n\n    if np_dtype.kind in [\"i\", \"u\"]:\n        # We allow overflow for integer types because it tends to be well-behaved\n        # and well-understood...\n        min_value = np.iinfo(np_dtype).min\n        max_value = np.iinfo(np_dtype).max\n\n        next_value = min_value\n\n        for i in range(shape[0]):\n            for j in range(shape[1]):\n                input1[i, j] = next_value\n                input2[i, j] = next_value * 2\n                next_value += 1\n\n    elif np_dtype.kind == \"f\":\n        # NOTE: For simplicity, we avoid test data that that require\n        # well-defined behavior on floating-point overflow.\n        # But it may be reasonable to test that in the future.\n        min_value = np.finfo(np_dtype).min\n        max_value = np.finfo(np_dtype).max\n\n        min_input_value = min_value / 2.0 + 1\n        max_input_value = max_value / 2.0 - 2\n        delta = (max_input_value - min_input_value) / (shape[0] * shape[1])\n\n        next_value = min_input_value\n\n        for i in range(shape[0]):\n            for j in range(shape[1]):\n                input1[i, j] = next_value\n                input2[i, j] = next_value + 1\n                next_value += delta\n\n    else:\n        assert False, f\"Unexpected data type: {np_dtype}\"\n\n    output = input1 + input2\n    return [\n        input1,\n        input2,\n        output,\n    ]\n\n\n@pytest.mark.skipif(_SHOULD_SKIP_BENCHMARKS, reason=_SKIP_BENCHMARKS_REASON)\n@tvm.testing.requires_hexagon\ndef test_elemwise_add(hexagon_session: Session):\n    \"\"\"Main elementwise add test function\"\"\"\n    for dtype in [\n        \"int8\",\n        \"float16\",\n    ]:\n\n        for mem_scope in [\n            \"global\",\n            \"global.vtcm\",\n        ]:\n\n            # These numbers are fairly arbitrary, but they're meant to stress memory/caches to\n            # various extents.\n            for num_vectors_per_tensor in [\n                1,\n                16,\n                64,\n                512,\n                2048,\n            ]:\n\n                dtype_bits = tvm._ffi.runtime_ctypes.DataType(dtype).bits\n                assert dtype_bits % 8 == 0\n                dtype_bytes = dtype_bits // 8\n\n                elem_per_hvx_vector = HVX_VECTOR_BYTES // dtype_bytes\n\n                shape = [\n                    num_vectors_per_tensor,\n                    elem_per_hvx_vector,\n                ]\n\n                print()\n                _benchmark_hexagon_elementwise_add_kernel(hexagon_session, shape, dtype, mem_scope)\n\n    print(\"-\" * 80)\n    print(f\"OUTPUT DIRECTORY: {_HOST_OUTPUT_DIR}\")\n    print(\"-\" * 80)\n    print()\n\n    tabular_output_filename = os.path.join(_HOST_OUTPUT_DIR, \"benchmark-results.csv\")\n    with open(tabular_output_filename, \"w\", encoding=\"UTF-8\") as csv_file:\n        _BT.print_csv(csv_file, _CSV_COLUMN_ORDER)\n\n    print(f\"BENCHMARK RESULTS FILE: {tabular_output_filename}\")\n\n    _BT.print_csv(sys.stdout, _CSV_COLUMN_ORDER)\n\n    if _BT.has_fail() > 0:\n        pytest.fail(\"At least one benchmark configuration failed\", pytrace=False)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_benchmark_maxpool2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThis module serves two purposes:\n    (1) Demonstrates how to write Python code that exercises various\n        Hexagon-related algorithms / features.\n\n    (2) Benchmark the resulting primfuncs.\n\nCurrent limitations:\n    - Input shapes are limited to NHWC --> NHWC_8h8w32c.\n\n    - Testing parameters (input shapes, dtypes, etc.) currently\n      support only one value for each parameter.\n\n    - height, width, channel must be integer multiples of 8, 8, and 32,\n      respectively.  I.e., partial blocks aren't currently\n      supported by this script.\n\n    - Requires that I/O tensors reside in \"global.VTCM\" memory,\n      rather than \"global\" memory.\n      This prevents benchmarking with I/O tensors that are too\n      large to fit into availble VTCM.\n\n    - The script only develops one primfunc.\n      Future revisions to this script are expected to add more\n      primfuncs and demonstrate more coding strategies.\n\"\"\"\n\nfrom typing import List\nimport copy\nimport os\n\nimport pytest\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import te, topi, tir\nfrom tvm.topi import testing\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom .infrastructure import get_hexagon_target\nfrom . import benchmark_util as bu\n\n# Pytest seems to require that fixture names exist in the current module.\n# E.g., it doesn't allow: @pytest.mark.usefixtures(\"bu.benchmark_group\")\nBENCHMARK_GROUP = bu.benchmark_group\n\n_SHOULD_SKIP_BENCHMARKS, _SKIP_BENCHMARKS_REASON = bu.skip_benchmarks_flag_and_reason()\n\n\ndef _ceil_div(numerator, denominator):\n    return (numerator + (denominator - 1)) // denominator\n\n\ndef _int8_nhwc_8h8w32c_map(n_batch, height, width, channel):\n    return [\n        n_batch,\n        height // 8,\n        width // 8,\n        channel // 32,\n        te.AXIS_SEPARATOR,\n        height % 8,\n        width % 8,\n        channel % 32,\n    ]\n\n\ndef _int8_nhwc_8h8w32c_shape(n_batch, height, width, channel) -> List[int]:\n    return [\n        n_batch,\n        _ceil_div(height, 8),\n        _ceil_div(width, 8),\n        _ceil_div(channel, 32),\n        8,\n        8,\n        32,\n    ]\n\n\ndef _int8_nhwc_8h8w32c_xform_immediate(arr_in: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Return a deep copy of 'arr_in', transformed from a NWHC to\n    NHWC-8h8wc32 shape.  Any newly created array elements have value 0.\n    \"\"\"\n    stage1 = copy.copy(arr_in)\n\n    (\n        n_batch,\n        height,\n        width,\n        channel,\n    ) = stage1.shape\n\n    (\n        h_minor,\n        w_minor,\n        c_minor,\n    ) = [8, 8, 32]\n\n    h_major = _ceil_div(height, h_minor)\n    w_major = _ceil_div(width, w_minor)\n    c_major = _ceil_div(channel, c_minor)\n\n    # This handles cases where the dimensions of arr_in are not cleanly divided\n    # by the minor block size, i.e. [8, 8, 32].\n    #\n    # Any additional array elements that this creates will ahve value 0.\n    # We shouldn't actually care what value is used for those elements, because they\n    # shouldn't be treated as meaningful by any of our algorithms.\n    if (height % h_minor) or (width % w_minor) or (channel % c_minor):\n        stage1.resize(\n            (n_batch, h_major * h_minor, w_major * w_minor, c_major * c_minor), refcheck=False\n        )\n\n    stage2 = stage1.reshape(n_batch, h_major, h_minor, w_major, w_minor, c_major, c_minor)\n    stage3 = stage2.transpose(0, 1, 3, 5, 2, 4, 6)\n    return stage3\n\n\ndef _create_test_input(shape, dtype: str) -> np.ndarray:\n    np_dtype = np.dtype(dtype)\n    min_value = np.iinfo(np_dtype).min\n    max_value = np.iinfo(np_dtype).max\n    return np.random.randint(low=min_value, high=max_value, size=tuple(shape), dtype=np.int8)\n\n\n@pytest.mark.usefixtures(\"BENCHMARK_GROUP\")\nclass TestMaxPool2D:\n    \"\"\"maxpool2D base test class\"\"\"\n\n    csv_column_order = [\n        # Identifies which TE-compute / TIRScript is used as the basis for the\n        # benchmarked primfunc. Only needs to be meaningful to humans.\n        \"basic_kernel\",\n        # When applicable, indicates the particular variation of schedules\n        # apply by the Python code. Decoding this may require looking at this\n        # script's source code.\n        \"sched_type\",\n        # Values directly based on test parameters...\n        \"input_shape_4d\",\n        \"block_shape\",\n        \"dtype\",\n        \"kernel\",\n        \"stride\",\n        \"dilation\",\n        \"padding\",\n        \"io_tensor_mem_scope\",\n        # Reserved columns defined by the BenchmarksTable class.\n        \"row_status\",\n        \"timings_min_usecs\",\n        \"timings_max_usecs\",\n        \"timings_median_usecs\",\n        \"timings_mean_usecs\",\n        \"timings_stddev_usecs\",\n        # For benchmarks that produce files on the host file system, this indicates\n        # their location. Useful for post-mortem investigation of benchmark results.\n        \"host_files_dir_path\",\n        # Miscellaneous comments about the benchmark.\n        \"comments\",\n    ]\n\n    dtype = tvm.testing.parameter(\"int8\")\n\n    # FIXME(cconvey): The script currently fails when height, width, or channel is not an\n    # integer multiple of 8, 8, or 32, respectively.\n    n_batch = tvm.testing.parameter(1)\n    height = tvm.testing.parameter(*[x * 8 for x in [1, 4, 16]])\n    width = tvm.testing.parameter(*[x * 8 for x in [1, 4, 16]])\n    channel = tvm.testing.parameter(*[x * 32 for x in [1, 2]])\n\n    kernel = tvm.testing.parameter((1, 1), (3, 3))\n    stride = tvm.testing.parameter((1, 1))\n    dilation = tvm.testing.parameter((1, 1))\n    padding = tvm.testing.parameter((0, 0, 0, 0))\n    io_tensor_mem_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @pytest.mark.skipif(_SHOULD_SKIP_BENCHMARKS, reason=_SKIP_BENCHMARKS_REASON)\n    @tvm.testing.requires_hexagon\n    def test_maxpool2d_nhwc(\n        self,\n        n_batch,\n        height,\n        width,\n        channel,\n        dtype,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        io_tensor_mem_scope,\n        hexagon_session: Session,\n    ):\n        \"\"\"Test maxpool2d NHWC\"\"\"\n\n        keys_dict = {\n            \"basic_kernel\": \"max_pool2d\",\n            \"sched_type\": 1,\n            \"input_shape_4d\": [n_batch, height, width, channel],\n            \"block_shape\": [8, 8, 32],\n            \"dtype\": dtype,\n            \"kernel\": kernel,\n            \"stride\": stride,\n            \"dilation\": dilation,\n            \"padding\": padding,\n            \"io_tensor_mem_scope\": io_tensor_mem_scope,\n        }\n\n        desc = bu.get_benchmark_decription(keys_dict)\n\n        # Create the host-side directory for this benchmark run's files / logs...\n        host_files_dir_name = bu.get_benchmark_id(keys_dict)\n        host_files_dir_path = os.path.join(self.working_dir, host_files_dir_name)\n        os.mkdir(host_files_dir_path)\n\n        keys_dict[\"host_files_dir_path\"] = host_files_dir_path\n\n        log_file_path = os.path.join(host_files_dir_path, \"out.txt\")\n        with open(log_file_path, \"w\") as log_file:\n            print(f\"CONFIGURATION: {desc}\")\n            log_file.write(f\"CONFIGURATION: {desc}\\n\")\n\n            try:\n                input_tensor_shape_4d = [n_batch, height, width, channel]\n                input_tensor_shape_7d = _int8_nhwc_8h8w32c_shape(n_batch, height, width, channel)\n\n                data = te.placeholder(tuple(input_tensor_shape_4d), dtype=dtype)\n\n                output = topi.nn.pool2d(\n                    data, kernel, stride, dilation, padding, \"max\", layout=\"NHWC\"\n                )\n                primfunc = te.create_prim_func([data, output])\n\n                sch = tir.Schedule(primfunc, debug_mask=\"all\")\n\n                sch.transform_layout(\n                    block=\"tensor\", buffer=\"placeholder\", index_map=_int8_nhwc_8h8w32c_map\n                )\n\n                built_module = tvm.build(\n                    sch.mod,\n                    target=get_hexagon_target(\"v69\"),\n                )\n\n                # Save a local copy of the Hexagon object code (in the form of a .so file)\n                # to allow post-mortem inspection.\n                host_dso_binary_path = os.path.join(host_files_dir_path, \"test_binary.so\")\n                built_module.save(host_dso_binary_path)\n                print(f\"SAVED BINARY TO HOST PATH: {host_dso_binary_path}\")\n\n                hexagon_mod = hexagon_session.load_module(built_module)\n\n                # Generate the input tensor's data.\n                # Note that we'll eventually need it in two different layouts:\n                # (1) NHWC as an argument to testing.poolnd_python.\n                # (2) NHWC_8h8w32c for as an argument to our Hexagon primfunc.\n                # a_numpy_4d = np.random.randint(low=-128, high=127,\n                #   size=input_tensor_shape_4d, dtype=np.int8)\n                a_numpy_4d = _create_test_input(input_tensor_shape_4d, dtype)\n\n                ref_output_4d = testing.poolnd_python(\n                    a_numpy_4d.astype(\"int32\"),\n                    kernel,\n                    stride,\n                    dilation,\n                    padding[0:2],\n                    padding[2:],\n                    pool_type=\"max\",\n                    dtype=\"int32\",\n                    layout=\"NHWC\",\n                ).astype(dtype)\n\n                output_tensor_shape_4d = ref_output_4d.shape\n\n                a_numpy_7d = _int8_nhwc_8h8w32c_xform_immediate(a_numpy_4d)\n\n                a_hexagon_7d = allocate_hexagon_array(\n                    hexagon_session.device,\n                    tensor_shape=input_tensor_shape_7d,\n                    axis_separators=[4],\n                    dtype=dtype,\n                    mem_scope=io_tensor_mem_scope,\n                )\n\n                c_hexagon_4d = allocate_hexagon_array(\n                    hexagon_session.device,\n                    tensor_shape=output_tensor_shape_4d,\n                    axis_separators=[],\n                    dtype=dtype,\n                    mem_scope=io_tensor_mem_scope,\n                )\n\n                a_hexagon_7d.copyfrom(a_numpy_7d)\n\n                if dtype == \"int8\":\n                    rel_tolerance = 0\n                    abs_tolerance = 0\n                else:\n                    assert False, f\"TODO: decide acceptable tolerances for dtype {dtype}\"\n\n                timer = hexagon_mod.time_evaluator(\n                    \"main\", hexagon_session.device, number=10, repeat=1\n                )\n                timing_result = timer(a_hexagon_7d, c_hexagon_4d)\n\n                try:\n                    tvm.testing.assert_allclose(\n                        ref_output_4d, c_hexagon_4d.numpy(), rtol=rel_tolerance, atol=abs_tolerance\n                    )\n                except AssertionError as exception:\n                    raise bu.NumericalAccuracyException(str(exception))\n\n            except bu.NumericalAccuracyException as exception:\n                print()\n                print(f\"FAIL: Numerical accuracy error. See log file.\")\n\n                log_file.write(\"\\n\")\n                log_file.write(f\"FAIL: {exception}\\n\")\n\n                self.benchmark_table.record_fail(\n                    **keys_dict, comments=f\"Numerical accuracy error. See log file.\"\n                )\n\n            except bu.UnsupportedException as exception:\n                print()\n                print(f\"SKIP: {exception}\")\n\n                log_file.write(\"\\n\")\n                log_file.write(f\"SKIP: {exception}\\n\")\n\n                self.benchmark_table.record_skip(\n                    **keys_dict, comments=f\"Unsupported configuration: {exception}\"\n                )\n\n            self.benchmark_table.record_success(timing_result, **keys_dict)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_cache_read_write.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Lower cache_read and cache_write to Hexagon DMA via tensorize \"\"\"\n\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\n\ndef intrin_mem_copy(shape, dtype, dst_scope, src_scope):\n    \"\"\"Define and return tensor intrinsic for mem copy\"\"\"\n    src = te.placeholder(shape=shape, dtype=dtype, name=\"src\")\n    dst = te.compute(shape, lambda i: src[i], name=\"dst\")\n    size = shape[0] * np.dtype(dtype).itemsize\n\n    src_buffer = tvm.tir.decl_buffer(\n        shape,\n        dtype,\n        scope=src_scope,\n        offset_factor=1,\n        name=\"mem_copy_src_buffer\",\n    )\n\n    dst_buffer = tvm.tir.decl_buffer(\n        shape,\n        dtype,\n        scope=dst_scope,\n        offset_factor=1,\n        name=\"mem_copy_dst_buffer\",\n    )\n\n    zero_indices = [0 for _ in shape]\n\n    def intrin_func(ins, outs):\n        ir_builder = tvm.tir.ir_builder.create()\n\n        _src = ins[0]\n        _dst = outs[0]\n\n        dst_handle = ir_builder.buffer_ptr(dst_buffer)\n        src_handle = ir_builder.buffer_ptr(src_buffer)\n\n        ir_builder.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.mem_copy\",\n                tvm.tir.call_intrin(\"handle\", \"tir.address_of\", dst_handle[zero_indices]),\n                tvm.tir.call_intrin(\"handle\", \"tir.address_of\", src_handle[zero_indices]),\n                size,\n            )\n        )\n        return ir_builder.get()\n\n    return te.decl_tensor_intrin(dst.op, intrin_func, binds={src: src_buffer, dst: dst_buffer})\n\n\ndef verify(hexagon_session: Session, schedule, x_tensor, y_tensor, z_tensor, size):\n    \"\"\"Verify correctness with reference from numpy\"\"\"\n    print(tvm.lower(schedule, [x_tensor, y_tensor, z_tensor]))\n\n    func = tvm.build(\n        schedule,\n        [x_tensor, y_tensor, z_tensor],\n        get_hexagon_target(\"v68\"),\n        name=\"dmacpy\",\n    )\n\n    mod = hexagon_session.load_module(func)\n    x_array = tvm.nd.array(\n        np.random.randint(low=-128, high=127, size=size, dtype=x_tensor.dtype),\n        device=hexagon_session.device,\n    )\n    y_array = tvm.nd.array(\n        np.random.randint(low=-128, high=127, size=size, dtype=y_tensor.dtype),\n        device=hexagon_session.device,\n    )\n    z_array = tvm.nd.array(\n        np.random.randint(low=-128, high=127, size=size, dtype=z_tensor.dtype),\n        device=hexagon_session.device,\n    )\n    mod[\"dmacpy\"](x_array, y_array, z_array)\n\n    ref = x_array.numpy() + y_array.numpy()\n    np.testing.assert_equal(z_array.numpy(), ref)\n\n\n@tvm.testing.requires_hexagon\ndef test_cache_read_write(hexagon_session: Session):\n    \"\"\"Test cache_read and cache_write to global.vtcm for hexagon\"\"\"\n    size = 128\n    outer_shape = (size,)\n    factor = 16\n    inner_shape = (factor,)\n    dtype = \"int8\"\n\n    x_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"x\")\n    y_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"y\")\n    z_tensor = te.compute(outer_shape, lambda i: x_tensor[i] + y_tensor[i], name=\"z\")\n    s = te.create_schedule(z_tensor.op)\n\n    x_vtcm = s.cache_read(x_tensor, \"global.vtcm\", [z_tensor])\n    y_vtcm = s.cache_read(y_tensor, \"global.vtcm\", [z_tensor])\n    z_vtcm = s.cache_write(z_tensor, \"global.vtcm\")\n\n    zouter, _ = s[z_vtcm].split(z_vtcm.op.axis[0], factor=factor)\n\n    s[x_vtcm].compute_at(s[z_vtcm], zouter)\n    s[y_vtcm].compute_at(s[z_vtcm], zouter)\n\n    mem_copy_read = intrin_mem_copy(inner_shape, dtype, \"global.vtcm\", \"global\")\n\n    (cache_read_x,) = s[x_vtcm].op.axis\n    s[x_vtcm].tensorize(cache_read_x, mem_copy_read)\n\n    (cache_read_y,) = s[y_vtcm].op.axis\n    s[y_vtcm].tensorize(cache_read_y, mem_copy_read)\n\n    mem_copy_write = intrin_mem_copy(outer_shape, dtype, \"global\", \"global.vtcm\")\n\n    (cache_write_z,) = s[z_tensor].op.axis\n    s[z_tensor].tensorize(cache_write_z, mem_copy_write)\n\n    verify(hexagon_session, s, x_tensor, y_tensor, z_tensor, size)\n\n\ndef layout_transform_2d(n):\n    return [n // 16, te.AXIS_SEPARATOR, n % 16]\n\n\n@tvm.testing.requires_hexagon\ndef test_cache_read_write_2d(hexagon_session: Session):\n    \"\"\"Test 2D cache_read and cache_write to global.vtcm for hexagon\"\"\"\n    size = 128\n    outer_shape = (size,)\n    factor = 16\n    inner_shape = (factor,)\n    dtype = \"int8\"\n\n    x_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"x\")\n    y_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"y\")\n    z_tensor = te.compute(outer_shape, lambda i: x_tensor[i] + y_tensor[i], name=\"z\")\n    s = te.create_schedule(z_tensor.op)\n\n    x_vtcm = s.cache_read(x_tensor, \"global.vtcm\", [z_tensor])\n    y_vtcm = s.cache_read(y_tensor, \"global.vtcm\", [z_tensor])\n    z_vtcm = s.cache_write(z_tensor, \"global.vtcm\")\n\n    layout_x_vtcm = s[x_vtcm].transform_layout(layout_transform_2d)\n    layout_y_vtcm = s[y_vtcm].transform_layout(layout_transform_2d)\n    _ = s[z_vtcm].transform_layout(layout_transform_2d)\n\n    mem_copy_read = intrin_mem_copy(inner_shape, dtype, \"global.vtcm\", \"global\")\n    s[x_vtcm].tensorize(layout_x_vtcm[1], mem_copy_read)\n    s[y_vtcm].tensorize(layout_y_vtcm[1], mem_copy_read)\n\n    # The loop schedule over `z` is not modified when calling `transform_layout`\n    # on `z_vtcm` above therefore we must call `split` to modify the loop schedule\n    # over `z` to match the layout of `z_vtcm` such that we can accurately write\n    # `z_vtcm` back to `z` using memory copy intrinsic\n    _, zinner = s[z_tensor].split(z_tensor.op.axis[0], factor=factor)\n    mem_copy_write = intrin_mem_copy(inner_shape, dtype, \"global\", \"global.vtcm\")\n    s[z_tensor].tensorize(zinner, mem_copy_write)\n\n    verify(hexagon_session, s, x_tensor, y_tensor, z_tensor, size)\n\n\n@T.prim_func\ndef scale_by_two(buffer_a: T.Buffer[(8192,), \"int8\"], buffer_c: T.Buffer[(8192,), \"int8\"]):\n    for i in T.serial(\n        0,\n        8192,\n    ):\n        with T.block(\"C\"):\n            buffer_c[i] = buffer_a[i] * T.int8(2)\n\n\ndef test_vtcm_lowering():\n    \"\"\"Test lowering with vtcm mem scope\"\"\"\n    mod = tvm.IRModule.from_expr(scale_by_two.with_attr(\"global_symbol\", \"main\"))\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    block_c = sch.get_block(\"C\")\n    (flat,) = sch.get_loops(block_c)\n    outer, _, _, _ = sch.split(flat, factors=[8, 4, 2, 128])\n    cache_block = sch.cache_read(block_c, 0, storage_scope=\"global.vtcm\")\n    sch.compute_at(cache_block, outer)\n    lowered = tvm.lower(sch.mod[\"main\"])\n\n    def ir_module_has_allocate_nodes(irmod):\n        nallocs = 0\n\n        def _visit(stmt):\n            nonlocal nallocs\n            if isinstance(stmt, tvm.tir.Allocate):\n                nallocs += 1\n\n        tvm.tir.stmt_functor.post_order_visit(irmod[\"main\"].body, _visit)\n        return nallocs\n\n    assert not ir_module_has_allocate_nodes(lowered), (\n        \"AllocateNode found in lowered IRModule, \"\n        \"VTCM allocations should have been lowered to tir.nd_mem_alloc_with_scope\"\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_fixed_point_conversion.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTest float to fixed-point conversion. We do it by constructing a numpy array with the\nwide range of floating-point values. These values are converted into the\nfixed-point value using topi.hexagon.utils.get_fixed_point_value. Then, these values are\nconverted back into float using scale_factor provided by the function. These converted\nfloating point values are then compared against the original values and an assertion is\nraised if they happened to be outside of the expected tolerance.\n\"\"\"\n\nimport math\nimport struct\nimport numpy as np\nimport tvm.topi.hexagon.utils as utils\n\n\nclass TestFixedPointConversion:\n    \"\"\"Fixed point conversation test class\"\"\"\n\n    def test_fixed_point_conversion(self):\n        \"\"\"Test fixed point conversion\"\"\"\n        # Construct array with wide range of values\n        fp1 = np.random.uniform(0.00001, 0.0002, size=(10))\n        fp2 = np.random.uniform(0.001, 0.02, size=(10))\n        fp3 = np.random.uniform(1, 20, size=(10))\n        fp4 = np.random.uniform(900, 1000, size=(10))\n        fp5 = np.random.uniform(1e9, 1e10, size=(10))\n\n        # Test for values with largest possible exponent as per IEEE-754 floating-point\n        # standard (actual exp value = 127, stored exp value = 254).\n        fp6 = np.random.uniform(2.4e38, 2.5e38, size=(1))\n\n        # Test for very small floating-point values.\n        fp7 = np.random.uniform(1.4e-34, 1.7e-34, size=(1))\n\n        float_arr = np.concatenate((fp1, fp2, fp3, fp4, fp5, fp6, fp7))\n        for flp in float_arr:\n            fxp, rsh = utils.get_fixed_point_value(flp, \"int16\")\n            # Compute scale_factor using rsh (rsh is log2 of the scale_factor). While doing this,\n            # we use IEEE-754 floating-point representation since rsh can be negative or positive.\n\n            scale = ((rsh + 127) & 0xFF) << 23  # Add bias (127) and position it into exponent bits\n            scale_i = struct.pack(\"I\", scale)  # Pack it as integer\n            scale_f = struct.unpack(\"f\", scale_i)  # Unpack as float\n\n            converted_flp = fxp / scale_f[0]\n            assert math.isclose(flp, converted_flp, rel_tol=1e-2)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_fixed_point_multiply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test Fixed Point Multiply on Hexagon.\"\"\"\n\nimport re\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.backend import Executor\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.contrib.hexagon.pytest_plugin import HEXAGON_AOT_LLVM_TARGET\n\nfrom .infrastructure import get_hexagon_target\n\n\n@tvm.testing.requires_hexagon\ndef test_vmpy_intrinsic_presence():\n    \"\"\"\n    check intrinsic lowering for fixed_point_multiply operation.\n    GraphExecutor is used here since get_source(\"asm\") is not supported with aot.\n    \"\"\"\n    ishape = (1, 128)\n    a = relay.var(\"a\", relay.TensorType(ishape, \"int32\"))\n\n    y = relay.fixed_point_multiply(a, 1395864320, 1)  # 1.3\n\n    relay_mod = tvm.IRModule.from_expr(y)\n\n    params = {}\n    executor = Executor(\"graph\", {\"link-params\": True})\n\n    with tvm.transform.PassContext(opt_level=3):\n        hexagon_lowered = tvm.relay.build(\n            relay_mod,\n            get_hexagon_target(\"v68\"),\n            executor=executor,\n            params=params,\n        )\n\n    asm = hexagon_lowered.lib.get_source(\"asm\")\n\n    # Check that 'vmpye' instruction was generated in asm file.\n    vmpye_regex = re.compile(r\"v\\d{1,2}.w = vmpye\\(v\\d{1,2}.w,v\\d{1,2}.uh\\)\")\n    assert vmpye_regex.search(asm) is not None\n\n    # Check that 'vmpyo' instruction was generated in asm file.\n    vmpyo_regex = re.compile(r\"v\\d{1,2}.w \\+= vmpyo\\(v\\d{1,2}.w,v\\d{1,2}.h\\):<<1:rnd:sat:shift\")\n    assert vmpyo_regex.search(asm) is not None\n\n\ndef build_module(relay_mod, target):\n    params = {}\n    executor = Executor(\"aot\", {\"link-params\": True})\n    lowered = tvm.relay.build(\n        relay_mod,\n        tvm.target.Target(target, host=target),\n        executor=executor,\n        params=params,\n    )\n    return lowered\n\n\ndef run_module(mod, inputs):\n    mod.set_input(**inputs)\n    mod.run()\n    output = mod.get_output(0).numpy()\n    return output\n\n\nclass TestFixedPointMultiply:\n    \"\"\"Fixed point Multiply test class\"\"\"\n\n    in_scale_const, out_scale_const = tvm.testing.parameters(\n        (1.3, 30.0),\n        (1.37, 1.0),\n        (0.6, 1.0),\n        ((1.7, 0.6), 1.0),\n        ((0.007, 1.9), 1.0),\n    )\n\n    multiplier, shift = tvm.testing.parameters(\n        (1288490240, -2),  # 0.15\n        (1395864320, 1),  # 1.3\n        (1288490188, 0),  # 0.6\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_fixed_point_multiply(self, hexagon_session: Session, multiplier: int, shift: int):\n        \"\"\"Fixed point multiply test.\"\"\"\n        ishape = (6, 32)\n        a = relay.var(\"a\", relay.TensorType(ishape, \"int32\"))\n        fpm = relay.fixed_point_multiply(a, multiplier, shift)\n        relay_mod = tvm.IRModule.from_expr(fpm)\n\n        with tvm.transform.PassContext(opt_level=3):\n            # Compile for Hexagon...\n            hexagon_lowered = build_module(relay_mod, HEXAGON_AOT_LLVM_TARGET)\n\n            # Compile for LLVM...\n            llvm_lowered = build_module(relay_mod, tvm.target.Target(\"llvm\"))\n\n        data_in = np.arange(-96, 96).reshape(ishape)\n        inputs = {\"a\": data_in}\n\n        # Run hexagon...\n        hexagon_mod = hexagon_session.get_executor_from_factory(hexagon_lowered)\n        hexagon_output = run_module(hexagon_mod, inputs)\n\n        # Run llvm...\n        llvm_mod = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n        expected_output = run_module(llvm_mod, inputs)\n\n        tvm.testing.assert_allclose(hexagon_output, expected_output)\n\n    @tvm.testing.requires_hexagon\n    def test_per_channel(self, hexagon_session: Session, in_scale_const, out_scale_const):\n        \"\"\"Per channel multiply test.\"\"\"\n        ishape = [1, 128, 56, 56]\n        axis = 1\n        a = relay.var(\"a\", shape=ishape, dtype=\"int32\")\n\n        # Make list of input scales from in_scale_const parameter.\n        if isinstance(in_scale_const, tuple):\n            in_scale = list(in_scale_const) * (ishape[axis] // len(in_scale_const))\n        else:\n            in_scale = [in_scale_const] * ishape[axis]\n        assert len(in_scale) == ishape[axis]\n\n        # qnn.requantize is lowered to fixed_point_multiply if zp == 0 and in_dtype == out_dtype.\n        iscale = relay.const(in_scale)\n        izero = relay.const(0)\n        oscale = relay.const(out_scale_const)\n        ozero = relay.const(0)\n        op = relay.qnn.op.requantize(a, iscale, izero, oscale, ozero, axis=axis, out_dtype=\"int32\")\n        mod = tvm.IRModule.from_expr(op)\n\n        with tvm.transform.PassContext(opt_level=3):\n            # Compile for Hexagon...\n            hexagon_lowered = build_module(mod, HEXAGON_AOT_LLVM_TARGET)\n\n            # Compile for LLVM...\n            llvm_lowered = build_module(mod, tvm.target.Target(\"llvm\"))\n\n        a_np = np.random.randint(-1000, 1000, size=np.prod(ishape)).reshape(ishape)\n        inputs = {\"a\": a_np}\n\n        # Run hexagon...\n        hexagon_mod = hexagon_session.get_executor_from_factory(hexagon_lowered)\n        hexagon_output = run_module(hexagon_mod, inputs)\n\n        # Run llvm...\n        llvm_mod = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n        expected_output = run_module(llvm_mod, inputs)\n\n        tvm.testing.assert_allclose(hexagon_output, expected_output)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_launcher.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,missing-function-docstring,redefined-outer-name\n\"\"\" Test rpc based launcher for hexagon \"\"\"\nimport pytest\n\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import relay, te\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.contrib.hexagon.build import HexagonLauncherRPC\nfrom tvm.contrib.hexagon.hexagon_profiler import HexagonProfiler\n\nfrom .infrastructure import get_hexagon_target\n\n\n@tvm.testing.requires_hexagon\ndef test_add(hexagon_session: Session):\n    \"\"\"Test simple add\"\"\"\n    dtype = \"int8\"\n    placeholder_a = tvm.te.placeholder((2,), dtype=dtype)\n    placeholder_b = tvm.te.placeholder((1,), dtype=dtype)\n    compute_c = tvm.te.compute(\n        placeholder_a.shape, lambda i: placeholder_a[i] + placeholder_b[0], name=\"C\"\n    )\n    sched = tvm.te.create_schedule(compute_c.op)\n\n    func = tvm.build(\n        sched,\n        [placeholder_a, placeholder_b, compute_c],\n        get_hexagon_target(\"v68\"),\n        name=\"add\",\n    )\n\n    mod = hexagon_session.load_module(func)\n\n    a_data = tvm.nd.array(np.array([2, 3], dtype=dtype), device=hexagon_session.device)\n    assert (a_data.numpy() == np.array([2, 3])).all()\n    b_data = tvm.nd.array(np.array([4], dtype=dtype), device=hexagon_session.device)\n    assert (b_data.numpy() == np.array([4])).all()\n    c_data = tvm.nd.array(np.array([0, 0], dtype=dtype), device=hexagon_session.device)\n    assert (c_data.numpy() == np.array([0, 0])).all()\n    mod[\"add\"](a_data, b_data, c_data)\n    assert (c_data.numpy() == np.array([6, 7])).all()\n\n\n@tvm.testing.requires_hexagon\ndef test_add_vtcm(hexagon_session: Session):\n    \"\"\"Test add on VTCM\"\"\"\n    dtype = \"int8\"\n    placeholder_a = tvm.te.placeholder((2,), dtype=dtype)\n    placeholder_b = tvm.te.placeholder((1,), dtype=dtype)\n    compute_c = tvm.te.compute(\n        placeholder_a.shape, lambda i: placeholder_a[i] + placeholder_b[0], name=\"C\"\n    )\n    sched = tvm.te.create_schedule(compute_c.op)\n\n    func = tvm.build(\n        sched,\n        [placeholder_a, placeholder_b, compute_c],\n        get_hexagon_target(\"v68\"),\n        name=\"add\",\n    )\n\n    mod = hexagon_session.load_module(func)\n\n    a_data = tvm.nd.empty(\n        placeholder_a.shape, placeholder_a.dtype, hexagon_session.device, \"global.vtcm\"\n    )\n    a_data.copyfrom(np.array([2, 3]))\n\n    b_data = tvm.nd.empty(\n        placeholder_b.shape, placeholder_b.dtype, hexagon_session.device, \"global.vtcm\"\n    )\n    b_data.copyfrom(np.array([4]))\n\n    c_data = tvm.nd.empty(compute_c.shape, compute_c.dtype, hexagon_session.device, \"global.vtcm\")\n    c_data.copyfrom(np.array([0, 0]))\n\n    mod[\"add\"](a_data, b_data, c_data)\n    result = c_data.numpy()\n    assert (result == np.array([6, 7])).all()\n\n\nclass TestMatMul:\n    \"\"\"Test matmul class\"\"\"\n\n    size_m = tvm.testing.parameter(32)\n    size_n = tvm.testing.parameter(32)\n    size_k = tvm.testing.parameter(32)\n\n    @tvm.testing.requires_hexagon\n    def test_matmul(self, hexagon_session, size_m, size_n, size_k):\n        \"\"\"Test matmul\"\"\"\n        placeholder_x = te.placeholder((size_m, size_k), dtype=\"float32\")\n        placeholder_y = te.placeholder((size_k, size_n), dtype=\"float32\")\n        reduce_k1 = te.reduce_axis((0, size_k), name=\"k1\")\n        compute_z = te.compute(\n            (size_m, size_n),\n            lambda i, j: te.sum(\n                placeholder_x[i, reduce_k1] * placeholder_y[reduce_k1, j], axis=[reduce_k1]\n            ),\n        )\n        schedule = te.create_schedule(compute_z.op)\n\n        func = tvm.build(\n            schedule,\n            [placeholder_x, placeholder_y, compute_z],\n            get_hexagon_target(\"v68\"),\n        )\n\n        mod = hexagon_session.load_module(func)\n\n        x_data = np.random.uniform(size=[i.value for i in placeholder_x.shape]).astype(\n            placeholder_x.dtype\n        )\n        y_data = np.random.uniform(size=[i.value for i in placeholder_y.shape]).astype(\n            placeholder_y.dtype\n        )\n        z_data = np.zeros([i.value for i in compute_z.shape], dtype=compute_z.dtype)\n\n        x_array = tvm.nd.array(x_data, device=hexagon_session.device)\n        y_array = tvm.nd.array(y_data, device=hexagon_session.device)\n        z_array = tvm.nd.array(z_data, device=hexagon_session.device)\n        mod(x_array, y_array, z_array)\n\n        target_llvm = tvm.target.Target(\"llvm\")\n        mod = tvm.build(\n            schedule,\n            [placeholder_x, placeholder_y, compute_z],\n            tvm.target.Target(target_llvm, host=target_llvm),\n        )\n        device = tvm.cpu(0)\n        xtcpu = tvm.nd.array(x_data, device)\n        ytcpu = tvm.nd.array(y_data, device)\n        ztcpu = tvm.nd.array(z_data, device)\n        mod(xtcpu, ytcpu, ztcpu)\n\n        tvm.testing.assert_allclose(z_array.numpy(), ztcpu.numpy(), rtol=1e-4)\n\n\n@tvm.testing.requires_hexagon\ndef test_graph_executor(hexagon_session: Session):\n    \"\"\"Test graph executor\"\"\"\n    dtype = \"float32\"\n    data = relay.var(\"data\", relay.TensorType((1, 64, 64, 3), dtype))\n    weight = relay.var(\"weight\", relay.TensorType((5, 5, 3, 8), dtype))\n    conv2d_op = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight], conv2d_op)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    runtime = Runtime(\"cpp\")\n    executor = Executor(\"graph\")\n\n    weight_in = np.random.rand(5, 5, 3, 8).astype(dtype=dtype)\n    data_in = np.random.rand(1, 64, 64, 3).astype(dtype=dtype)\n    params = {\"weight\": weight_in}\n    inputs = {\"data\": data_in}\n\n    with tvm.transform.PassContext(opt_level=3):\n        lowered = tvm.relay.build(\n            relay_mod,\n            get_hexagon_target(\"v68\"),\n            runtime=runtime,\n            executor=executor,\n        )\n\n    graph_mod = hexagon_session.get_executor_from_factory(lowered)\n    graph_mod.set_input(**params)\n    graph_mod.run(**inputs)\n    hexagon_output = graph_mod.get_output(0).numpy()\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=runtime,\n            executor=executor,\n        )\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(**params)\n    llvm_graph_mod.run(**inputs)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\n@tvm.testing.requires_hexagon\ndef test_graph_executor_multiple_conv2d(hexagon_session: Session):\n    \"\"\"Test multiple conv2d nodes with graph_executor\"\"\"\n    dtype = \"float32\"\n    input_shape = (1, 8, 8, 3)\n    w1_shape = (5, 5, 3, 1)\n    w2_shape = (5, 5, 1, 3)\n    data = relay.var(\"data\", relay.TensorType(input_shape, dtype))\n    weight1 = relay.var(\"weight1\", relay.TensorType(w1_shape, dtype))\n    weight2 = relay.var(\"weight2\", relay.TensorType(w2_shape, dtype))\n    conv2d_op1 = relay.nn.conv2d(\n        data,\n        weight1,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    conv2d_op2 = relay.nn.conv2d(\n        conv2d_op1,\n        weight2,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight1, weight2], conv2d_op2)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    runtime = Runtime(\"cpp\")\n    executor = Executor(\"graph\")\n\n    with tvm.transform.PassContext(opt_level=3):\n        lowered = tvm.relay.build(\n            relay_mod,\n            get_hexagon_target(\"v68\"),\n            runtime=runtime,\n            executor=executor,\n        )\n\n    weight1_data = np.random.rand(w1_shape[0], w1_shape[1], w1_shape[2], w1_shape[3]).astype(\n        dtype=dtype\n    )\n    weight2_data = np.random.rand(w2_shape[0], w2_shape[1], w2_shape[2], w2_shape[3]).astype(\n        dtype=dtype\n    )\n    input_data = np.random.rand(\n        input_shape[0], input_shape[1], input_shape[2], input_shape[3]\n    ).astype(dtype=dtype)\n\n    params = {\"weight1\": weight1_data, \"weight2\": weight2_data}\n    inputs = {\"data\": input_data}\n\n    graph_mod = hexagon_session.get_executor_from_factory(lowered)\n    graph_mod.set_input(**params)\n    graph_mod.run(**inputs)\n    hexagon_output = graph_mod.get_output(0).numpy()\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=runtime,\n            executor=executor,\n        )\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(**params)\n    llvm_graph_mod.run(**inputs)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\n@tvm.testing.requires_hexagon\ndef test_aot_executor(hexagon_session: Session, aot_host_target, aot_target):\n    \"\"\"Test AOT executor\"\"\"\n    dtype = \"float32\"\n    input_shape = (1, 128, 128, 3)\n    w_shape = (5, 5, 3, 8)\n    data = relay.var(\"data\", relay.TensorType(input_shape, dtype))\n    weight = relay.var(\"weight\", relay.TensorType(w_shape, dtype))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight], y)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    weight_data = np.random.rand(w_shape[0], w_shape[1], w_shape[2], w_shape[3]).astype(dtype=dtype)\n    input_data = np.random.rand(\n        input_shape[0], input_shape[1], input_shape[2], input_shape[3]\n    ).astype(dtype=dtype)\n\n    params = {\"weight\": weight_data}\n    inputs = {\"data\": input_data}\n\n    with tvm.transform.PassContext(opt_level=3):\n        lowered = tvm.relay.build(\n            relay_mod,\n            params=params,\n            target=tvm.target.Target(aot_target, host=aot_host_target),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\", {\"unpacked-api\": False, \"interface-api\": \"packed\"}),\n        )\n\n    aot_mod = hexagon_session.get_executor_from_factory(lowered)\n    aot_mod.set_input(**inputs)\n    aot_mod.run()\n    hexagon_output = aot_mod.get_output(0).numpy()\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"graph\"),\n        )\n\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(**params)\n    llvm_graph_mod.run(**inputs)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\n@tvm.testing.requires_hexagon\ndef test_aot_executor_multiple_conv2d(hexagon_session: Session, aot_host_target, aot_target):\n    \"\"\"Test multiple conv2d nodes with AOT executor\"\"\"\n    dtype = \"float32\"\n    input_shape = (1, 8, 8, 3)\n    w1_shape = (5, 5, 3, 1)\n    w2_shape = (5, 5, 1, 3)\n    data = relay.var(\"data\", relay.TensorType(input_shape, dtype))\n    weight1 = relay.var(\"weight1\", relay.TensorType(w1_shape, dtype))\n    weight2 = relay.var(\"weight2\", relay.TensorType(w2_shape, dtype))\n    conv2d_op1 = relay.nn.conv2d(\n        data,\n        weight1,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    conv2d_op2 = relay.nn.conv2d(\n        conv2d_op1,\n        weight2,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight1, weight2], conv2d_op2)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    weight1_data = np.random.rand(w1_shape[0], w1_shape[1], w1_shape[2], w1_shape[3]).astype(\n        dtype=dtype\n    )\n    weight2_data = np.random.rand(w2_shape[0], w2_shape[1], w2_shape[2], w2_shape[3]).astype(\n        dtype=dtype\n    )\n    input_data = np.random.rand(\n        input_shape[0], input_shape[1], input_shape[2], input_shape[3]\n    ).astype(dtype=dtype)\n\n    params = {\"weight1\": weight1_data, \"weight2\": weight2_data}\n    inputs = {\"data\": input_data}\n\n    with tvm.transform.PassContext(opt_level=3):\n        lowered = tvm.relay.build(\n            relay_mod,\n            params=params,\n            target=tvm.target.Target(aot_target, host=aot_host_target),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\", {\"unpacked-api\": False, \"interface-api\": \"packed\"}),\n        )\n\n    aot_mod = hexagon_session.get_executor_from_factory(lowered)\n    aot_mod.set_input(**inputs)\n    aot_mod.run()\n    hexagon_output = aot_mod.get_output(0).numpy()\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"graph\"),\n        )\n\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(**params)\n    llvm_graph_mod.run(**inputs)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\ndata_dtype = tvm.testing.parameter(\"int8\", \"uint8\")\nweight_dtype = tvm.testing.parameter(\"int8\", \"uint8\")\n\n\n@tvm.testing.requires_hexagon\ndef test_conv2d_relay_vrmpy(hexagon_session, data_dtype, weight_dtype):\n    if data_dtype == \"int8\" and weight_dtype == \"uint8\":\n        pytest.skip(\"(i8, u8) input pair is not supported\")\n\n    def get_conv2d_nchw(d_shape, w_shape, padding, strides=(1, 1)):\n        out_dtype = \"int32\"\n\n        data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n        weight = relay.var(\"weight\", shape=w_shape, dtype=weight_dtype)\n        out_channel = w_shape[0]\n        return relay.nn.conv2d(\n            data=data,\n            weight=weight,\n            kernel_size=w_shape[2:],\n            channels=out_channel,\n            padding=padding,\n            strides=strides,\n            out_dtype=out_dtype,\n        )\n\n    target_hexagon = tvm.target.hexagon(\"v68\")\n    target = tvm.target.Target(target_hexagon, host=target_hexagon)\n    I, O, H, W = 64, 256, 56, 56\n    kH = kW = 3\n    padding = (1, 1)\n    strides = (1, 1)\n\n    data_shape = (1, I, H, W)\n    weight_shape = (O, I, kH, kW)\n    bias_shape = (weight_shape[0],)\n\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"int32\")\n\n    conv2d = get_conv2d_nchw(\n        data_shape,\n        weight_shape,\n        padding,\n        strides=strides,\n    )\n    bias_add = relay.nn.bias_add(conv2d, bias)\n    mod = tvm.IRModule.from_expr(bias_add)\n\n    if data_dtype == \"uint8\":\n        data_np = np.random.uniform(0, 255, size=data_shape).astype(\"uint8\")\n    else:\n        data_np = np.random.uniform(-128, 127, size=data_shape).astype(\"int8\")\n\n    if weight_dtype == \"uint8\":\n        weight_np = np.random.uniform(0, 255, size=weight_shape).astype(\"uint8\")\n    else:\n        weight_np = np.random.uniform(-128, 127, size=weight_shape).astype(\"int8\")\n\n    bias_np = np.random.randint(low=-127, high=128, size=bias_shape).astype(\"int32\")\n    params = {\"weight\": weight_np, \"bias\": bias_np}\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight_np, bias_np])\n        .numpy()\n    )\n\n    with tvm.transform.PassContext(\n        opt_level=3,\n    ):\n        executor = relay.backend.Executor(\"graph\", {\"link-params\": True})\n        lib = relay.build(mod, target=target, params=params, executor=executor)\n\n    asm = lib.lib.get_source(\"asm\")\n    assert \"vrmpy\" in asm\n\n    rt_mod = hexagon_session.get_executor_from_factory(lib)\n\n    rt_mod.set_input(\"data\", data_np)\n\n    rt_mod.run()\n\n    out = rt_mod.get_output(0).numpy()\n\n    np.testing.assert_equal(out, ref)\n\n\n@tvm.testing.requires_hexagon\ndef test_dense_relay_vrmpy(hexagon_session, data_dtype, weight_dtype):\n    if data_dtype == \"int8\" and weight_dtype == \"uint8\":\n        pytest.skip(\"(i8, u8) input pair is not supported\")\n\n    target_hexagon = tvm.target.hexagon(\"v68\")\n    target = tvm.target.Target(target_hexagon, host=target_hexagon)\n\n    M = 128\n    N = 1000\n    K = 2048\n    data_shape = (M, K)\n    weight_shape = (N, K)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=weight_dtype)\n\n    dense = relay.nn.dense(data, weight, out_dtype=\"int32\")\n\n    if data_dtype == \"uint8\":\n        data_np = np.random.uniform(0, 255, size=data_shape).astype(\"uint8\")\n    else:\n        data_np = np.random.uniform(-128, 127, size=data_shape).astype(\"int8\")\n\n    if weight_dtype == \"uint8\":\n        weight_np = np.random.uniform(0, 255, size=weight_shape).astype(\"uint8\")\n    else:\n        weight_np = np.random.uniform(-128, 127, size=weight_shape).astype(\"int8\")\n\n    bias_np = np.random.uniform(1, 10, size=(weight_shape[0],)).astype(\"int32\")\n\n    params = {\"weight\": weight_np, \"bias\": bias_np}\n\n    bias = relay.var(\"bias\", shape=(weight_shape[0],), dtype=\"int32\")\n    bias_add = relay.nn.bias_add(dense, bias)\n    mod = tvm.IRModule.from_expr(bias_add)\n\n    with tvm.transform.PassContext(\n        opt_level=3,\n    ):\n        executor = relay.backend.Executor(\"graph\", {\"link-params\": True})\n        lib = relay.build(mod, target=target, params=params, executor=executor)\n\n    asm = lib.lib.get_source(\"asm\")\n    assert \"vrmpy\" in asm\n\n    rt_mod = hexagon_session.get_executor_from_factory(lib)\n\n    rt_mod.set_input(\"data\", data_np)\n\n    rt_mod.run()\n\n    out = rt_mod.get_output(0).numpy()\n\n    ref = np.dot(data_np.astype(\"int32\"), weight_np.transpose().astype(\"int32\"))\n    ref += bias_np\n\n    np.testing.assert_equal(out, ref)\n\n\n@tvm.testing.requires_hexagon\ndef test_lwp(\n    hexagon_server_process,\n    hexagon_launcher: HexagonLauncherRPC,\n    hexagon_session: Session,\n    hexagon_debug,\n):\n    dtype = \"float32\"\n    data = relay.var(\"data\", relay.TensorType((1, 64, 64, 3), dtype))\n    weight = relay.var(\"weight\", relay.TensorType((5, 5, 3, 8), dtype))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n\n    f = relay.Function([data, weight], y)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    target_hexagon = tvm.target.hexagon(\"v68\")\n    runtime = Runtime(\"cpp\")\n    executor = Executor(\"graph\")\n\n    weight_in = np.random.rand(5, 5, 3, 8).astype(dtype=dtype)\n    data_in = np.random.rand(1, 64, 64, 3).astype(dtype=dtype)\n    params = {\"weight\": weight_in}\n    inputs = {\"data\": data_in}\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.instrument_lwp\": True}):\n        lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_hexagon, host=target_hexagon),\n            runtime=runtime,\n            executor=executor,\n        )\n        # Create HexagonProfiler object\n        dso_binary = \"test_binary.so\"\n        profiler = HexagonProfiler(dso_binary, lowered, hexagon_server_process, hexagon_debug)\n\n    graph_mod = hexagon_session.get_executor_from_factory(lowered)\n    graph_mod.set_input(**params)\n    graph_mod.run(**inputs)\n    hexagon_output = graph_mod.get_output(0).numpy()\n\n    # Get lightweight profiling output as a CSV file\n    profiler.get_profile_output(hexagon_launcher, hexagon_session)\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=runtime,\n            executor=executor,\n        )\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(weight=weight_in)\n    llvm_graph_mod.run(data=data_in)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\n@tvm.testing.requires_hexagon\ndef test_lwp_multiple_conv2d(\n    hexagon_server_process,\n    hexagon_launcher: HexagonLauncherRPC,\n    hexagon_session: Session,\n    hexagon_debug,\n):\n    dtype = \"float32\"\n    input_shape = (1, 8, 8, 3)\n    w1_shape = (5, 5, 3, 1)\n    w2_shape = (5, 5, 1, 3)\n    data = relay.var(\"data\", relay.TensorType(input_shape, dtype))\n    weight1 = relay.var(\"weight1\", relay.TensorType(w1_shape, dtype))\n    weight2 = relay.var(\"weight2\", relay.TensorType(w2_shape, dtype))\n    y1 = relay.nn.conv2d(\n        data,\n        weight1,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    y2 = relay.nn.conv2d(\n        y1,\n        weight2,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight1, weight2], y2)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    target_hexagon = tvm.target.hexagon(\"v68\")\n    runtime = Runtime(\"cpp\")\n    executor = Executor(\"graph\")\n\n    weight1_data = np.random.rand(w1_shape[0], w1_shape[1], w1_shape[2], w1_shape[3]).astype(\n        dtype=dtype\n    )\n    weight2_data = np.random.rand(w2_shape[0], w2_shape[1], w2_shape[2], w2_shape[3]).astype(\n        dtype=dtype\n    )\n    input_data = np.random.rand(\n        input_shape[0], input_shape[1], input_shape[2], input_shape[3]\n    ).astype(dtype=dtype)\n\n    params = {\"weight1\": weight1_data, \"weight2\": weight2_data}\n    inputs = {\"data\": input_data}\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.instrument_lwp\": True}):\n        lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_hexagon, host=target_hexagon),\n            runtime=runtime,\n            executor=executor,\n        )\n        # Create HexagonProfiler object\n        dso_binary = \"test_binary.so\"\n        profiler = HexagonProfiler(dso_binary, lowered, hexagon_server_process, hexagon_debug)\n\n    graph_mod = hexagon_session.get_executor_from_factory(lowered)\n    graph_mod.set_input(**params)\n    graph_mod.run(**inputs)\n    hexagon_output = graph_mod.get_output(0).numpy()\n\n    # Get lightweight profiling output as a CSV file\n    profiler.get_profile_output(hexagon_launcher, hexagon_session)\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=runtime,\n            executor=executor,\n        )\n    llvm_graph_mod = tvm.contrib.graph_executor.GraphModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_graph_mod.set_input(**params)\n    llvm_graph_mod.run(**inputs)\n    expected_output = llvm_graph_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_maxpool2d_blocked.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Contrib tests for blocked conv2d and maxpool2d\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te, topi\nfrom tvm.topi import testing\n\nfrom .infrastructure import build_and_run, get_block_shape, get_packed_shape\n\n\n# Blocked layout: NHWC8h8w32c :: [N, H//8, W//8, C//32, 8h, 8w, 32c]\ndef maxpool2d_logical(\n    shape_nhwc,\n    window_shape,\n    stride,\n    padding,\n    dtype,\n    storage_scope=\"global\",\n):\n    \"\"\"\n    Maxpool2d TE wherein the input activation is defined by its\n    logical NHWC shape. The packed physical layout for the\n    activation is nhwc8h8w32c.\n    \"\"\"\n\n    block_h, block_w, block_c = get_block_shape()\n    shape = get_packed_shape(shape_nhwc)\n    logical_output_shape = (\n        shape_nhwc[0],\n        (shape_nhwc[1] - window_shape[0] + padding[0] + padding[1]) // stride[0] + 1,\n        (shape_nhwc[2] - window_shape[1] + padding[2] + padding[3]) // stride[0] + 1,\n        shape_nhwc[3],\n    )\n    output_shape = get_packed_shape(logical_output_shape)\n\n    _, height, width, _ = shape_nhwc\n    placeholder_x = te.placeholder(shape_nhwc, dtype=dtype)\n\n    # Combination of padding required by maxpool operator and padding to evenly divisible\n    # number of blocks. Note that this padding should be inlined in the schedule so\n    # as to avoid input copying.\n    pad_h = (block_h - ((height + padding[1]) % block_h)) % block_h\n    pad_w = (block_w - ((width + padding[3]) % block_w)) % block_w\n    x_pad = topi.nn.pad(\n        placeholder_x, [0, padding[0], padding[2], 0], [0, pad_h, pad_w, 0], pad_value=0\n    )\n\n    # Calculate packed layout\n    x_packed = te.compute(\n        shape,\n        lambda n, ho, wo, co, hi, wi, ci: x_pad[\n            n, ho * block_h + hi, wo * block_w + wi, co * block_c + ci\n        ],\n    )\n\n    reduce_h = te.reduce_axis((0, window_shape[0]), name=\"rh\")\n    reduce_w = te.reduce_axis((0, window_shape[1]), name=\"rw\")\n\n    def compute(batch, h_outer, w_outer, c_outer, h_inner, w_inner, c_inner):\n        # Construct blockized strided maxpool height indices\n        h = h_outer * block_h + h_inner\n        h_contig = h * stride[0] + reduce_h\n        h_block_id = h_contig // block_h\n        h_block_offset = h_contig % block_h\n\n        # Construct blockized strided maxpool width indices\n        w_idx = w_outer * block_w + w_inner\n        w_contig = w_idx * stride[1] + reduce_w\n        w_block_id = w_contig // block_w\n        w_block_offset = w_contig % block_w\n\n        return te.max(\n            x_packed[\n                batch, h_block_id, w_block_id, c_outer, h_block_offset, w_block_offset, c_inner\n            ],\n            axis=[reduce_h, reduce_w],\n        )\n\n    compute_y = te.compute(output_shape, compute)\n    schedule = te.create_schedule(compute_y.op)\n\n    # Ensure the padding and array packing is performed inline\n    schedule[x_pad].compute_inline()\n    schedule[x_packed].compute_inline()\n\n    binds = {}\n    if storage_scope and storage_scope != \"global\":\n        with tvm.transform.PassContext():\n            x_buffer = tvm.tir.decl_buffer(shape, name=\"Xb\", dtype=dtype, scope=storage_scope)\n            y_buffer = tvm.tir.decl_buffer(\n                output_shape, name=\"Yb\", dtype=dtype, scope=storage_scope\n            )\n            binds = {placeholder_x: x_buffer, compute_y: y_buffer}\n\n    return (schedule, [placeholder_x, compute_y], binds)\n\n\nclass BaseMaxPooling:\n    batch = tvm.testing.parameter(1)\n    in_size = tvm.testing.parameter(8, 112)\n    in_channel = tvm.testing.parameter(64)\n    window_size = tvm.testing.parameter(3)\n    stride = tvm.testing.parameter(2)\n    pad = tvm.testing.parameter(1)\n    dtype = tvm.testing.parameter(\"float32\")\n\n\nclass TestMaxPooling(BaseMaxPooling):\n    \"\"\"Test MaxPool class\"\"\"\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_maxpool(self, shape_nhwc, window_size, stride, pad, dtype, target):\n        \"\"\"Test blocked maxpool\"\"\"\n        inputs = [np.random.uniform(0, 255, size=shape_nhwc).astype(dtype)]\n        ref_output = testing.poolnd_python(\n            inputs[0],\n            (window_size, window_size),\n            strides=(stride, stride),\n            dilation=(1, 1),\n            padding_before=(pad, pad),\n            padding_after=(pad, pad),\n            pool_type=\"max\",\n        )\n        output = build_and_run(\n            inputs,\n            maxpool2d_logical,\n            target,\n            target,\n            shape_nhwc,\n            window_shape=(window_size, window_size),\n            stride=(stride, stride),\n            padding=(pad, pad, pad, pad),\n            dtype=dtype,\n        )\n        return output, ref_output\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_memory_alloc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test memory allocation.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom .infrastructure import get_hexagon_target\n\n\ndef generated_func(shape: tuple, dtype: str, axis_separators: list):\n    \"\"\"Generate element wise function.\"\"\"\n    dim0, dim1 = shape\n\n    @T.prim_func\n    def elwise(a: T.handle, b: T.handle):\n        a_buffer = T.match_buffer(a, shape, dtype=dtype, axis_separators=axis_separators)\n        b_buffer = T.match_buffer(b, shape, dtype=dtype, axis_separators=axis_separators)\n\n        for i, j in T.grid(dim0, dim1):\n            with T.block(\"compute\"):\n                b_buffer[i, j] = a_buffer[i, j] * T.cast(2, dtype=dtype)\n\n    return elwise\n\n\nclass TestMemoryAlloc:\n    \"\"\"Memory allocation test.\"\"\"\n\n    dtype = tvm.testing.parameter(\"int8\")\n    shape = tvm.testing.parameter((128, 128))\n\n    (scope, axis_separators,) = tvm.testing.parameters(\n        (\"global\", []),\n        (\"global.vtcm\", []),\n        (\"global.vtcm\", [1]),\n        (\"global.ddr\", []),\n        (\"global.ddr\", [1]),\n    )\n\n    def test_global_axis_separator(self, hexagon_session, shape, dtype, scope, axis_separators):\n        \"\"\"Test with global axis separator.\"\"\"\n        mod1 = tvm.build(\n            generated_func(shape, dtype, axis_separators),\n            target=get_hexagon_target(\"v69\"),\n        )\n        mod2 = hexagon_session.load_module(mod1)\n\n        a_np = np.ones(shape=shape, dtype=dtype)\n        a = allocate_hexagon_array(\n            hexagon_session.device, data=a_np, mem_scope=scope, axis_separators=axis_separators\n        )\n\n        b_np = np.zeros(shape=shape, dtype=dtype)\n        b = allocate_hexagon_array(\n            hexagon_session.device, data=b_np, mem_scope=scope, axis_separators=axis_separators\n        )\n\n        mod2(a, b)\n        tvm.testing.assert_allclose(a.numpy() * 2, b.numpy(), atol=1e-4, rtol=1e-4)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_meta_schedule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test rpc based launcher for hexagon \"\"\"\nimport tempfile\n\nimport numpy as np\nimport pytest\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay, te\nfrom tvm.contrib.hexagon.meta_schedule import (\n    get_hexagon_local_builder,\n    get_hexagon_rpc_runner,\n)\nfrom tvm.meta_schedule import postproc, schedule_rule\nfrom tvm.meta_schedule.arg_info import TensorInfo\nfrom tvm.meta_schedule.builder import BuilderInput\nfrom tvm.meta_schedule.runner import RunnerInput\nfrom tvm.script import tir as T\nfrom tvm.tir import FloatImm\nfrom tvm.tir.tensor_intrin.hexagon import VRMPY_u8u8i32_INTRIN\n\nfrom .infrastructure import get_hexagon_target\n\nMATMUL_N = 16\nMATMUL_M = 32\n\n\n@tvm.script.ir_module\nclass MatmulModule:\n    \"\"\"Matmultest class\"\"\"\n\n    # pylint: disable=no-self-argument\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # type: ignore\n        # pylint: disable=missing-function-docstring\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, (16, 16), \"float32\")\n        b_buffer = T.match_buffer(b, (16, 16), \"float32\")\n        c_buffer = T.match_buffer(c, (16, 16), \"float32\")\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"matmul\"):\n                vi_axis, vj_axis, vk_axis = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    c_buffer[vi_axis, vj_axis] = 0.0  # type: ignore\n                c_buffer[vi_axis, vj_axis] = (\n                    c_buffer[vi_axis, vj_axis]\n                    + a_buffer[vi_axis, vk_axis] * b_buffer[vk_axis, vj_axis]\n                )\n\n\n@tvm.testing.requires_hexagon\ndef test_builder_runner(hexagon_launcher):\n    \"\"\"Test builder and runner.\"\"\"\n    if hexagon_launcher.is_simulator():\n        pytest.skip(msg=\"Tuning on simulator not supported.\")\n\n    mod = MatmulModule\n\n    builder = get_hexagon_local_builder()\n    runner = get_hexagon_rpc_runner(hexagon_launcher, number=1, repeat=1, min_repeat_ms=0)\n\n    (builder_result,) = builder.build([BuilderInput(mod, get_hexagon_target(\"v68\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    # Run the module\n    (runner_future,) = runner.run([runner_input])\n    runner_result = runner_future.result()\n\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n\n\ndef dense_compute(m, n, k):\n    \"\"\"dense compute\"\"\"\n    X = te.placeholder((m, k), name=\"X\", dtype=\"uint8\")\n    packed_width = te.placeholder((n // 32, k // 4, 32, 4), name=\"packed_width\", dtype=\"uint8\")\n\n    axis_k = te.reduce_axis((0, k), name=\"k\")\n    out = te.compute(\n        (m, n),\n        lambda i, j: te.sum(\n            X[i, axis_k].astype(\"int32\")\n            * packed_width[\n                tvm.tir.indexdiv(j, 32), tvm.tir.indexdiv(axis_k, 4), j % 32, axis_k % 4\n            ].astype(\"int32\"),\n            axis=axis_k,\n        ),\n        name=\"compute\",\n    )\n    return [X, packed_width, out]\n\n\ndef schedule_dense(sch, block, m_size, do_tune):\n    \"\"\"dense schedule\"\"\"\n    a_y, a_x, _ = sch.get_loops(block)[-3:]\n\n    if do_tune:\n        y_factors = sch.sample_perfect_tile(a_y, n=2, max_innermost_factor=128)\n        a_yo, a_yi = sch.split(a_y, factors=y_factors)\n    else:\n        a_yo, a_yi = sch.split(a_y, factors=[None, min(m_size, 32)])\n\n    a_xo, a_xi = sch.split(a_x, factors=[None, 32])\n    sch.reorder(a_yo, a_xo, a_yi, a_xi)\n\n    a_xi, a_k = sch.get_loops(block)[-2:]\n    a_ko, a_ki = sch.split(a_k, factors=[None, 4])\n    sch.reorder(a_ko, a_xi, a_ki)\n\n    fused = sch.fuse(a_yo, a_xo)\n\n    sch.parallel(fused)\n\n    dec = sch.decompose_reduction(block, a_ko)\n\n    init_loop = sch.get_loops(dec)[-1]\n    sch.vectorize(init_loop)\n\n    sch.tensorize(a_xi, VRMPY_u8u8i32_INTRIN)\n\n\ndef verify_dense(sch, target, m_size, n_size, k_size, hexagon_session):\n    \"\"\"Verify dense operator.\"\"\"\n    f = tvm.build(sch.mod[\"main\"], target=target, name=\"dense\")\n    mod = hexagon_session.load_module(f)\n    dev = hexagon_session.device\n\n    a_np = np.random.uniform(1, 10, size=(m_size, k_size)).astype(\"uint8\")\n    b_np = np.random.uniform(1, 10, size=(n_size, k_size)).astype(\"uint8\")\n    c_np = np.dot(a_np.astype(\"int32\"), b_np.transpose().astype(\"int32\"))\n\n    pack_width = np.random.uniform(1, 10, size=(n_size // 32, (k_size // 4), 32, 4)).astype(\"uint8\")\n\n    for r_idx in range(n_size // 32):\n        for k_output in range(k_size // 4):\n            for s_idx in range(32):\n                for t_idx in range(4):\n                    pack_width[r_idx][k_output][s_idx][t_idx] = b_np[r_idx * 32 + s_idx][\n                        k_output * 4 + t_idx\n                    ]\n\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(pack_width, dev)\n    c = tvm.nd.array(np.zeros((m_size, n_size), dtype=\"int32\"), dev)\n\n    mod(a, b, c)\n    np.testing.assert_equal(c.numpy(), c_np)\n\n    evaluator = mod.time_evaluator(mod.entry_name, dev, number=10)\n    gflops = (n_size * m_size * k_size) * 2 / 1e9\n    time_ms = evaluator(a, b, c).mean * 1e3\n    print(\"%f ms, %f GOPS\" % (time_ms, gflops / (time_ms / 1e3)))\n\n\n@tvm.testing.requires_hexagon\ndef test_vrmpy_dense(hexagon_launcher):\n    \"\"\"Test vector reduce muliply dense.\"\"\"\n    if hexagon_launcher.is_simulator():\n        pytest.skip(msg=\"Tuning on simulator not supported.\")\n\n    do_tune = True\n\n    m_size, n_size, k_size = 128, 768, 768\n    workload = te.create_prim_func(dense_compute(m_size, n_size, k_size))\n\n    if not do_tune:\n        ir_module = tvm.IRModule({\"main\": workload})\n        sch = tvm.tir.Schedule(ir_module)\n        block = sch.get_block(\"compute\")\n        schedule_dense(sch, block, m_size, do_tune)\n    else:\n        with tempfile.TemporaryDirectory() as work_dir:\n\n            def schedule_dense_for_tune(sch):\n                block = sch.get_block(\"compute\")\n                return schedule_dense(sch, block, None, True)\n\n            target = get_hexagon_target(\"v69\")\n            database = ms.tir_integration.tune_tir(\n                mod=workload,\n                target=target,\n                work_dir=work_dir,\n                max_trials_global=8,\n                space=ms.space_generator.ScheduleFn(\n                    schedule_dense_for_tune,\n                    sch_rules=[],\n                    postprocs=[],\n                    mutator_probs={},\n                ),\n                strategy=\"replay-trace\",\n                builder=get_hexagon_local_builder(),\n                runner=get_hexagon_rpc_runner(hexagon_launcher, number=10),\n            )\n            sch = ms.tir_integration.compile_tir(database, workload, target)\n\n    with hexagon_launcher.create_session() as session:\n        verify_dense(sch, get_hexagon_target(\"v68\"), m_size, n_size, k_size, session)\n\n\n# This is an example of a schedule found by vrmpy auto tensorization.\n# It gets 440 GFLOPS on SD888.\n@tvm.script.ir_module\nclass ModuleVRMPYAutoTensorize:\n    \"\"\"Vector Reduce Multimply auto tensorize test class.\"\"\"\n\n    # pylint: disable=no-self-argument\n    @T.prim_func\n    def main(  # type: ignore\n        X: T.Buffer[(128, 768), \"uint8\"],  # type: ignore\n        packed_width: T.Buffer[(24, 192, 32, 4), \"uint8\"],  # type: ignore\n        compute: T.Buffer[(128, 768), \"int32\"],  # type: ignore\n    ) -> None:\n        # pylint: disable=missing-function-docstring\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0_0_i1_0_0_fused in T.parallel(\n            512, annotations={\"pragma_auto_unroll_max_step\": 64, \"pragma_unroll_explicit\": 1}\n        ):\n            for i0_1_init, i1_0_1_init, i0_2_init, i1_0_2_init in T.grid(2, 3, 1, 1):\n                with T.block(\"compute_o_init\"):\n                    i = T.axis.spatial(128, i0_0_i1_0_0_fused // 8 * 2 + i0_1_init + i0_2_init)\n                    j_o = T.axis.spatial(24, i1_0_2_init + i0_0_i1_0_0_fused % 8 * 3 + i1_0_1_init)\n                    T.reads()\n                    T.writes(compute[i, j_o * 32 : j_o * 32 + 32])  # type: ignore\n                    for i1_1 in T.vectorized(32):\n                        with T.block(\"compute_init\"):\n                            j_i_init = T.axis.spatial(32, i1_1)\n                            T.reads()\n                            T.writes(compute[i, j_o * 32 + j_i_init])\n                            compute[i, j_o * 32 + j_i_init] = 0  # type: ignore\n            for i2_0_0, i0_1, i1_0_1, i2_0_1, i0_2, i1_0_2 in T.grid(32, 2, 3, 6, 1, 1):\n                with T.block(\"compute_o_update\"):\n                    i = T.axis.spatial(128, i0_0_i1_0_0_fused // 8 * 2 + i0_1 + i0_2)\n                    j_o = T.axis.spatial(24, i1_0_2 + i0_0_i1_0_0_fused % 8 * 3 + i1_0_1)\n                    k_o = T.axis.reduce(192, i2_0_0 * 6 + i2_0_1)\n                    T.reads(\n                        compute[i, j_o * 32 : j_o * 32 + 32],  # type: ignore\n                        X[i, k_o * 4 : k_o * 4 + 4],  # type: ignore\n                        packed_width[j_o, k_o, 0:32, 0:4],  # type: ignore\n                    )\n                    T.writes(compute[i, j_o * 32 : j_o * 32 + 32])  # type: ignore\n                    a_buffer = T.match_buffer(\n                        X[i, k_o * 4 : k_o * 4 + 4],\n                        [4],\n                        dtype=\"uint8\",\n                        offset_factor=1,  # type: ignore\n                    )\n                    b_buffer = T.match_buffer(\n                        packed_width[j_o, k_o, 0:32, 0:4], [32, 4], dtype=\"uint8\", offset_factor=1\n                    )\n                    c_buffer = T.match_buffer(\n                        compute[i, j_o * 32 : j_o * 32 + 32],\n                        [32],\n                        dtype=\"int32\",\n                        offset_factor=1,  # type: ignore\n                    )\n                    a_u8x4: T.uint8x4 = a_buffer[0:4]  # type: ignore\n                    a_i32: T.int32 = T.reinterpret(a_u8x4, dtype=\"int32\")  # type: ignore\n                    b_i32x32: T.int32x32 = T.reinterpret(\n                        b_buffer[0, 0:128], dtype=\"int32x32\"\n                    )  # type: ignore\n                    c_buffer[0:32] = T.call_llvm_pure_intrin(  # type: ignore\n                        4390, T.uint32(3), c_buffer[0:32], b_i32x32, a_i32, dtype=\"int32x32\"\n                    )\n\n\n@tvm.testing.requires_hexagon\ndef test_vrmpy_dense_auto_tensorize(hexagon_launcher):\n    \"\"\"Test VRMPY dense operator.\"\"\"\n    if hexagon_launcher.is_simulator():\n        pytest.skip(msg=\"Tuning on simulator not supported.\")\n\n    m_size, n_size, k_size = 128, 768, 768\n    workload = te.create_prim_func(dense_compute(m_size, n_size, k_size))\n\n    sch_rules = [\n        schedule_rule.MultiLevelTilingWithIntrin(\n            VRMPY_u8u8i32_INTRIN,\n            structure=\"SRSRS\",\n            tile_binds=None,\n            max_innermost_factor=64,\n            vector_load_lens=None,\n            reuse_read=None,\n            reuse_write=schedule_rule.ReuseType(\n                req=\"may\",\n                levels=[1, 2],\n                scope=\"global\",\n            ),\n        ),\n        schedule_rule.ParallelizeVectorizeUnroll(\n            max_jobs_per_core=16,\n            max_vectorize_extent=128,\n            unroll_max_steps=[0, 16, 64, 512],\n            unroll_explicit=True,\n        ),\n    ]\n\n    postprocs = [\n        postproc.RewriteParallelVectorizeUnroll(),\n        postproc.RewriteReductionBlock(),\n        postproc.RewriteTensorize(vectorize_init_loop=True),\n    ]\n\n    # Make this to False to compile and run the best tuned schedule\n    run_tuning = True\n    if run_tuning:\n        with tempfile.TemporaryDirectory() as work_dir:\n            target = get_hexagon_target(\"v68\")\n            database = ms.tir_integration.tune_tir(\n                mod=workload,\n                target=target,\n                max_trials_global=8,\n                num_trials_per_iter=8,\n                work_dir=work_dir,\n                space=ms.space_generator.PostOrderApply(\n                    f_block_filter=None,\n                    sch_rules=sch_rules,\n                    postprocs=postprocs,\n                    mutator_probs={},\n                ),\n                builder=get_hexagon_local_builder(),\n                runner=get_hexagon_rpc_runner(hexagon_launcher, number=10),\n            )\n            sch = ms.tir_integration.compile_tir(database, workload, target)\n    else:\n        sch = tvm.tir.Schedule(ModuleVRMPYAutoTensorize, debug_mask=\"all\")\n\n    with hexagon_launcher.create_session() as session:\n        verify_dense(sch, get_hexagon_target(\"v68\"), m_size, n_size, k_size, session)\n\n\n@tvm.testing.requires_hexagon\ndef test_conv2d_relay_auto_schedule(hexagon_launcher):\n    \"\"\"Test conv2d using auto schedule.\"\"\"\n    if hexagon_launcher.is_simulator():\n        pytest.skip(msg=\"Tuning on simulator not supported.\")\n\n    i_size, o_size, h_size, w_size = 64, 64, 56, 56\n    k_height_size = k_width_size = 3\n\n    strides = (1, 1)\n    padding = (1, 1)\n\n    d_shape = (1, h_size, w_size, i_size)\n    w_shape = (k_height_size, k_width_size, i_size, o_size)\n    bias_shape = (1, 1, 1, w_shape[3])\n    out_channel = w_shape[3]\n\n    data = relay.var(\"data\", shape=d_shape, dtype=\"float16\")\n    weight = relay.var(\"weight\", shape=w_shape, dtype=\"float16\")\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float16\")\n    conv2d = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=(k_height_size, k_width_size),\n        channels=out_channel,\n        padding=padding,\n        strides=strides,\n        out_dtype=\"float16\",\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    mod = tvm.IRModule.from_expr(conv2d + bias)\n    mod = mod.with_attr(\"executor\", relay.backend.Executor(\"graph\", {\"link-params\": True}))\n\n    data_np = np.random.randn(*d_shape).astype(\"float16\")\n    weight_np = np.random.randn(*w_shape).astype(\"float16\")\n    bias_np = np.random.randn(*bias_shape).astype(\"float16\")\n    params = {\"weight\": weight_np, \"bias\": bias_np}\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight_np, bias_np])\n        .numpy()\n    )\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        target = get_hexagon_target(\"v69\")\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            params=params,\n            target=target,\n            max_trials_global=8,\n            strategy=\"replay-trace\",\n            work_dir=work_dir,\n            builder=get_hexagon_local_builder(),\n            runner=get_hexagon_rpc_runner(hexagon_launcher, number=20),\n        )\n        lib = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            params=params,\n            target=target,\n        )\n\n    with hexagon_launcher.create_session() as session:\n        rt_mod = session.get_executor_from_factory(lib)\n\n        rt_mod.set_input(\"data\", data_np)\n\n        rt_mod.run()\n\n        out = rt_mod.get_output(0).numpy()\n        # Fairly loose check since fp16 results between x86 and Hexagon have\n        # non-trivial difference.\n        assert np.mean(np.abs(ref - out)) < 0.5\n\n\n@tvm.testing.requires_hexagon\ndef test_dense_relay_auto_schedule(hexagon_launcher):\n    \"\"\"\n    This is for testing RewriteLayout postproc. Without this postproc,\n    dense on Hexagon is extremely slow.\n    \"\"\"\n    if hexagon_launcher.is_simulator():\n        pytest.skip(msg=\"Tuning on simulator not supported.\")\n\n    target_hexagon = tvm.target.hexagon(\"v69\")\n    target = tvm.target.Target(target_hexagon, host=target_hexagon)\n\n    data_shape = (128, 128)\n    weight_shape = (128, 128)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float16\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float16\")\n    dense = relay.nn.dense(data, weight)\n    mod = tvm.IRModule.from_expr(dense)\n    mod = mod.with_attr(\"executor\", relay.backend.Executor(\"graph\", {\"link-params\": True}))\n\n    weight_np = np.random.randn(*weight_shape).astype(\"float32\")\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    params = {\"weight\": weight_np}\n    ref = np.dot(data_np, weight_np.transpose())\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        target = get_hexagon_target(\"v69\")\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            params=params,\n            target=target,\n            max_trials_global=8,\n            strategy=\"replay-trace\",\n            work_dir=work_dir,\n            builder=get_hexagon_local_builder(),\n            runner=get_hexagon_rpc_runner(hexagon_launcher, number=20),\n        )\n        lib = ms.relay_integration.compile_relay(\n            database=database,\n            mod=mod,\n            params=params,\n            target=target,\n        )\n\n    with hexagon_launcher.create_session() as session:\n        rt_mod = session.get_executor_from_factory(lib)\n\n        rt_mod.set_input(\"data\", data_np)\n\n        rt_mod.run()\n\n        out = rt_mod.get_output(0).numpy()\n        # Fairly loose check since fp16 results between x86 and Hexagon have\n        # non-trivial difference.\n        assert np.mean(np.abs(ref - out)) < 0.1\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test mobilenet model with aot executor\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.relay.backend import Executor, Runtime\n\n\ndef get_mobilenet():\n    \"\"\"Download and import mobilenet model with ONNX\"\"\"\n    import onnx  # pylint: disable=import-outside-toplevel\n\n    model_url = \"https://github.com/onnx/models/raw/main/vision/classification/mobilenet/model/mobilenetv2-7.onnx\"  # pylint: disable=line-too-long\n    model_path = tvm.contrib.download.download_testdata(\n        model_url, \"mobilenetv2-7.onnx\", module=\"onnx\"\n    )\n    return onnx.load(model_path)\n\n\n@pytest.mark.parametrize(\"enable_usmp\", [False, True])\n@tvm.testing.requires_hexagon\ndef test_mobilenet_aot(hexagon_session: Session, aot_host_target, aot_target, enable_usmp):\n    \"\"\"Test mobilenet with aot executor\"\"\"\n    dtype = \"float32\"\n    onnx_model = get_mobilenet()\n\n    data_in = np.random.rand(1, 3, 224, 224).astype(dtype=dtype)\n\n    input_name = \"data\"\n    shape_dict = {input_name: data_in.shape}\n    relay_mod, params = relay.frontend.from_onnx(onnx_model, shape_dict, freeze_params=True)\n    inputs = {input_name: data_in}\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    config = {\"tir.usmp.enable\": enable_usmp}\n    with tvm.transform.PassContext(opt_level=3, config=config):\n        hexagon_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(aot_target, host=aot_host_target),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\", {\"unpacked-api\": False, \"interface-api\": \"packed\"}),\n            params=params,\n        )\n\n    hexagon_mod = hexagon_session.get_executor_from_factory(hexagon_lowered)\n    hexagon_mod.set_input(**inputs)\n    hexagon_mod.run()\n    hexagon_output = hexagon_mod.get_output(0).numpy()\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\", {\"interface-api\": \"packed\"}),\n            params=params,\n        )\n\n    llvm_mod = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_mod.set_input(**inputs)\n    llvm_mod.run()\n    expected_output = llvm_mod.get_output(0).numpy()\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_parallel_hvx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTest parallelizing HVX workloads and compare them to single thread examples.\n\"\"\"\nimport numpy as np\nfrom numpy.random import default_rng\n\nimport tvm\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\nTEST_OUTPUT_TEMPLATE = (\n    \"Test {} with {} operations... \\n\"\n    \"    -Single Thread: {} ms \\n\"\n    \"    -Parallel: {} ms\\n    -Speedup: {}x\\n\"\n)\n\n\ndef get_vrmpy_shape_dtypes(operations):\n    return ((operations, 128), \"uint8\", (operations, 128), \"uint8\", (operations, 32), \"int32\")\n\n\ndef get_vmpy_vadd_shape_dtype(operations):\n    return ((operations, 128), \"uint8\", (operations, 128), \"uint8\", (operations, 128), \"int16\")\n\n\ndef vmpy_expected_producer(shape, a, b):\n    expected = np.zeros(shape, dtype=\"int16\")\n    for n in range(shape[0]):\n        for i in range(0, 128, 2):\n            expected[n, i // 2] = np.int16(a[n, i]) * np.int16(b[n, i])\n        for i in range(1, 128, 2):\n            expected[n, i // 2 + 64] = np.int16(a[n, i]) * np.int16(b[n, i])\n    return expected\n\n\ndef vadd_expected_producer(shape, a, b):\n    expected = np.zeros(shape, dtype=\"int16\")\n    for n in range(shape[0]):\n        for i in range(0, 128, 2):\n            expected[n, i // 2] = np.int16(a[n, i]) + np.int16(b[n, i])\n        for i in range(1, 128, 2):\n            expected[n, i // 2 + 64] = np.int16(a[n, i]) + np.int16(b[n, i])\n    return expected\n\n\ndef vrmpy_expected_producer(shape, a, b):\n    expected = np.zeros(shape, dtype=\"int32\")\n    for n in range(shape[0]):\n        for i in range(32):\n            for r_ind in range(4):\n                expected[n, i] = expected[n, i] + np.uint32(a[n, i * 4 + r_ind]) * np.uint32(\n                    b[n, i * 4 + r_ind]\n                )\n    return expected\n\n\ndef get_vmpy_operator(operations):\n    \"\"\"Generate vector multiply operator\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\")\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\")\n        c_buffer = T.match_buffer(c, [operations, 128], dtype=\"int16\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind, T.ramp(0, 1, 128)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vmpybusv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(a_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(b_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int16x128\",\n                )\n\n    return operator\n\n\ndef get_vadd_operator(operations):\n    \"\"\"Generate vadd operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\")\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\")\n        c_buffer = T.match_buffer(c, [operations, 128], dtype=\"int16\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind, T.ramp(0, 1, 128)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vaddubh.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(a_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(b_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int16x128\",\n                )\n\n    return operator\n\n\ndef get_vrmpy_operator(operations):\n    \"\"\"Generate vrmpy operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\")\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\")\n        c_buffer = T.match_buffer(c, [operations, 32], dtype=\"int32\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind, T.ramp(0, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(a_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(b_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int32x32\",\n                )\n\n    return operator\n\n\ndef evaluate(hexagon_session, shape_dtypes, expected_output_producer, sch):\n    \"\"\"Evaluate schedule.\"\"\"\n    a_shape, a_dtype, b_shape, b_dtype, c_shape, c_dtype = shape_dtypes\n\n    func_tir = tvm.build(sch.mod[\"main\"], target=get_hexagon_target(\"v68\"))\n    module = hexagon_session.load_module(func_tir)\n\n    rng = default_rng()\n    a = rng.integers(0, 16, a_shape, dtype=a_dtype)\n    b = rng.integers(0, 16, b_shape, dtype=b_dtype)\n    c = np.zeros(c_shape, dtype=c_dtype)\n\n    a_hexagon = tvm.runtime.ndarray.array(a, device=hexagon_session.device)\n    b_hexagon = tvm.runtime.ndarray.array(b, device=hexagon_session.device)\n    c_hexagon = tvm.runtime.ndarray.array(c, device=hexagon_session.device)\n\n    # These are reduced for CI but number=100 and repeat=10 does a good job of removing noise.\n    number = 1\n    repeat = 1\n\n    timer = module.time_evaluator(\n        \"__tvm_main__\", hexagon_session.device, number=number, repeat=repeat\n    )\n    runtime = timer(a_hexagon, b_hexagon, c_hexagon)\n    tvm.testing.assert_allclose(c_hexagon.asnumpy(), expected_output_producer(c_shape, a, b))\n\n    return round(runtime.mean * 1000, 6)\n\n\nclass TestMatMulVec:\n    \"\"\"MatMul test class.\"\"\"\n\n    (\n        operation_name,\n        operator_producer,\n        shape_dtypes_producer,\n        expected_output_producer,\n    ) = tvm.testing.parameters(\n        (\"vrmpy\", get_vrmpy_operator, get_vrmpy_shape_dtypes, vrmpy_expected_producer),\n        (\"vmpy\", get_vmpy_operator, get_vmpy_vadd_shape_dtype, vmpy_expected_producer),\n        (\"vadd\", get_vadd_operator, get_vmpy_vadd_shape_dtype, vadd_expected_producer),\n    )\n\n    # Experimentally best split factor but all multiples of 4 perform pretty well.\n    # This is because there are 4 HVX untis available on the device and pipelining\n    # works best with parallels of the number of available HVX.\n    split_factor = tvm.testing.parameter(4)\n\n    # Removed most of these to speedup CI.\n    operation_count = tvm.testing.parameter(\n        128,\n        # 256,\n        # 512,\n        # Single thread runs faster since L2 cache can handle the entire request quickly\n        # 1024,\n        # 2048,\n        # Significant performance degredation once the inputs and outputs cannot all fit in L2\n        # 4096,\n        # 8192,\n        # 16384,\n    )\n\n    @tvm.testing.requires_hexagon\n    def test(\n        self,\n        hexagon_session,\n        operation_count,\n        operation_name,\n        operator_producer,\n        shape_dtypes_producer,\n        expected_output_producer,\n        split_factor,\n    ):\n        \"\"\"Test function handler.\"\"\"\n\n        sch = tvm.tir.Schedule(operator_producer(operation_count))\n        single_thread_runtime = evaluate(\n            hexagon_session, shape_dtypes_producer(operation_count), expected_output_producer, sch\n        )\n\n        sch = tvm.tir.Schedule(operator_producer(operation_count))\n        block = sch.get_block(\"c_buffer\")\n        b = sch.get_loops(block)\n        b_output, _ = sch.split(b[0], factors=[split_factor, None])\n        sch.parallel(b_output)\n\n        parallel_runtime = evaluate(\n            hexagon_session, shape_dtypes_producer(operation_count), expected_output_producer, sch\n        )\n\n        speedup = round(single_thread_runtime / parallel_runtime, 2)\n\n        print(\n            TEST_OUTPUT_TEMPLATE.format(\n                operation_name, operation_count, single_thread_runtime, parallel_runtime, speedup\n            )\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_parallel_hvx_load_vtcm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test different strategies for loading data into vtcm before running HVX workloads. \"\"\"\n\nimport numpy as np\nimport tvm\nfrom numpy.random import default_rng\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\nTEST_OUTPUT_TEMPLATE = (\n    \"Test with {} MB of data to load... \\n\"\n    \"    -No VTCM: {} Gops \\n    -Basic VTCM: {} Gops \\n\"\n    \"    -Vectorized: {} Gops\\n    -Vectorized and\"\n    \" Parallelized: {} Gops\\n    -Preallocated and Vectorized: {} Gops\\n\"\n    \"    -Preallocated, Vectorized, and Parallelized: {} Gops\\n\"\n    \"    -Single DMA: {} Gops\\n    -Preloaded: {} Gops\\n\"\n)\n\n\ndef apply_parallel_unroll_vectorize(sch, blocks, outer_split, unroll_split, vector_split):\n    \"\"\"Apply parallel unroll vectorized.\"\"\"\n    for block in blocks:\n        vb_index, vi_index = sch.get_loops(block)\n        v = sch.fuse(vb_index, vi_index)\n        vbo, vbi, vio, vii = sch.split(  # pylint: disable=unused-variable\n            v, factors=[outer_split, None, unroll_split, vector_split]\n        )  # pylint: disable=unused-variable\n        sch.vectorize(vii)\n        sch.unroll(vio)\n        sch.parallel(vbo)\n    return sch\n\n\ndef apply_unroll_vectorize(sch, blocks, unroll_split, vector_split):\n    for block in blocks:\n        vb_index, vi_index = sch.get_loops(block)\n        v = sch.fuse(vb_index, vi_index)\n        _, vio, vii = sch.split(v, factors=[None, unroll_split, vector_split])\n        sch.vectorize(vii)\n        sch.unroll(vio)\n    return sch\n\n\ndef apply_vrmpy_parallelization(sch):\n    block = sch.get_block(\"c_buffer\")\n    b = sch.get_loops(block)\n    b_outer, _ = sch.split(b[0], factors=[4, None])\n    sch.parallel(b_outer)\n    return sch\n\n\ndef apply_vtcm_cache_read_write(sch):\n    block = sch.get_block(\"c_buffer\")\n    sch.cache_read(block, 0, \"global.vtcm\")\n    sch.cache_read(block, 1, \"global.vtcm\")\n    sch.cache_write(block, 0, \"global.vtcm\")\n    return sch\n\n\ndef vrmpy(operations):\n    \"\"\"Generate VRMPY operator\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\", align=128)\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\", align=128)\n        c_buffer = T.match_buffer(c, [operations, 32], dtype=\"int32\", align=128)\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind, T.ramp(0, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(a_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    T.reinterpret(b_buffer[vn_ind, T.ramp(0, 1, 128)], dtype=\"int32x32\"),\n                    dtype=\"int32x32\",\n                )\n\n    return operator\n\n\ndef preloaded_vrmpy(operations):\n    \"\"\"Generate preloaded VRMPY operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(\n            a,\n            [T.cast(operations, \"int32\") * 128],\n            dtype=\"uint8\",\n            align=128,\n            scope=\"global.vtcm\",\n        )\n        b_buffer = T.match_buffer(\n            b,\n            [T.cast(operations, \"int32\") * 128],\n            dtype=\"uint8\",\n            align=128,\n            scope=\"global.vtcm\",\n        )\n        c_buffer = T.match_buffer(\n            c, [T.cast(operations, \"int32\") * 32], dtype=\"int32\", align=128, scope=\"global.vtcm\"\n        )\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[T.ramp(T.cast(vn_ind, \"int32\") * 32, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(\n                        a_buffer[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)], dtype=\"int32x32\"\n                    ),\n                    T.reinterpret(\n                        b_buffer[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)], dtype=\"int32x32\"\n                    ),\n                    dtype=\"int32x32\",\n                )\n\n    return operator\n\n\ndef preallocated_vrmpy(operations):\n    \"\"\"Generate preallocated VRMPY operator.\"\"\"\n    size = operations * 128\n    out_size = operations * 32\n\n    @T.prim_func\n    def operator(\n        a: T.handle, b: T.handle, c: T.handle, a_v: T.handle, b_v: T.handle, c_v: T.handle\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\", align=128, scope=\"global\")\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\", align=128, scope=\"global\")\n        c_buffer = T.match_buffer(c, [operations, 32], dtype=\"int32\", align=128, scope=\"global\")\n        a_global_vtcm = T.match_buffer(a_v, [size], dtype=\"uint8\", align=128, scope=\"global.vtcm\")\n        b_global_vtcm = T.match_buffer(b_v, [size], dtype=\"uint8\", align=128, scope=\"global.vtcm\")\n        c_global_vtcm = T.match_buffer(\n            c_v, [out_size], dtype=\"int32\", align=128, scope=\"global.vtcm\"\n        )\n        for n, i in T.grid(operations, 128):\n            with T.block(\"a_buffer_global.vtcm\"):\n                vn_ind, vi_index = T.axis.remap(\"SS\", [n, i])\n                a_global_vtcm[vn_ind * 128 + vi_index] = a_buffer[vn_ind, vi_index]\n        for n, i in T.grid(operations, 128):\n            with T.block(\"b_buffer_global.vtcm\"):\n                vn_ind, vi_index = T.axis.remap(\"SS\", [n, i])\n                b_global_vtcm[vn_ind * 128 + vi_index] = b_buffer[vn_ind, vi_index]\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 32, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(\n                        a_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)],\n                        dtype=\"int32x32\",\n                    ),\n                    T.reinterpret(\n                        b_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)],\n                        dtype=\"int32x32\",\n                    ),\n                    dtype=\"int32x32\",\n                )\n        for n, i in T.grid(operations, 32):\n            with T.block(\"c_buffer_global.vtcm\"):\n                vn_ind, vi_index = T.axis.remap(\"SS\", [n, i])\n                c_buffer[vn_ind, vi_index] = c_global_vtcm[vn_ind * 32 + vi_index]\n\n    return operator\n\n\ndef preallocated_single_dma_vrmpy(operations):\n    \"\"\"Generate preallocated single DMA VRMPY operator.\"\"\"\n    size = operations * 128\n    out_size = operations * 32\n\n    @T.prim_func\n    def operator(\n        a: T.handle,\n        b: T.handle,\n        c: T.handle,\n        a_v: T.handle,\n        b_v: T.handle,\n        c_v: T.handle,\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations, 128], dtype=\"uint8\", align=128, scope=\"global\")\n        b_buffer = T.match_buffer(b, [operations, 128], dtype=\"uint8\", align=128, scope=\"global\")\n        c_buffer = T.match_buffer(c, [operations, 32], dtype=\"int32\", align=128, scope=\"global\")\n        a_global_vtcm = T.match_buffer(a_v, [size], dtype=\"uint8\", align=128, scope=\"global.vtcm\")\n        b_global_vtcm = T.match_buffer(b_v, [size], dtype=\"uint8\", align=128, scope=\"global.vtcm\")\n        c_global_vtcm = T.match_buffer(\n            c_v, [out_size], dtype=\"int32\", align=128, scope=\"global.vtcm\"\n        )\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    a_global_vtcm.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    a_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    a_buffer.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    a_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.cast(size, dtype=\"int\"),\n                dtype=\"int32\",\n            )\n        )\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    b_global_vtcm.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    b_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    b_buffer.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    b_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.cast(size, dtype=\"int\"),\n                dtype=\"int32\",\n            )\n        )\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 32, 1, 32)] = T.call_llvm_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.hexagon.V6.vrmpyubv.128B\"),\n                    T.uint32(2),\n                    T.reinterpret(\n                        a_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)],\n                        dtype=\"int32x32\",\n                    ),\n                    T.reinterpret(\n                        b_global_vtcm[T.ramp(T.cast(vn_ind, \"int32\") * 128, 1, 128)],\n                        dtype=\"int32x32\",\n                    ),\n                    dtype=\"int32x32\",\n                )\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    c_buffer.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    c_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    c_global_vtcm.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    c_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.cast(size, dtype=\"int\"),\n                dtype=\"int32\",\n            )\n        )\n\n    return operator\n\n\ndef evaluate_result(operations, tag, time, result, expected_output):\n    transfer_mb = round(3 * operations * 128 / 1e6, 2)\n    gops = round(operations * 128 * 3 / time.mean / 1e9, 3)\n    mean_ms = round(time.mean * 1000, 6)\n\n    print(f\"\\ntest_{transfer_mb}MB_{tag} took {mean_ms} ms @ GOPS: {gops}\")\n    tvm.testing.assert_allclose(result, expected_output)\n\n\ndef setup_and_run(hexagon_session, sch, a, b, c, operations, mem_scope=\"global\"):\n    \"\"\"Setup and run operator.\"\"\"\n    func_tir = tvm.build(sch.mod[\"main\"], target=get_hexagon_target(\"v69\"))\n    module = hexagon_session.load_module(func_tir)\n\n    a_hexagon = tvm.runtime.ndarray.array(a, device=hexagon_session.device, mem_scope=mem_scope)\n    b_hexagon = tvm.runtime.ndarray.array(b, device=hexagon_session.device, mem_scope=mem_scope)\n    c_hexagon = tvm.runtime.ndarray.array(c, device=hexagon_session.device, mem_scope=mem_scope)\n\n    # These are reduced for CI but number=100 and repeat=10 does a good job of removing noise.\n    number = 1\n    repeat = 1\n\n    timer = module.time_evaluator(\n        \"__tvm_main__\", hexagon_session.device, number=number, repeat=repeat\n    )\n    time = timer(a_hexagon, b_hexagon, c_hexagon)\n    gops = round(operations * 128 * 3 / time.mean / 1e9, 4)\n    return gops, c_hexagon.asnumpy()\n\n\ndef setup_and_run_preallocated(hexagon_session, sch, a, b, c, operations):\n    \"\"\"Setup and run for preallocated.\"\"\"\n    func_tir = tvm.build(sch.mod[\"main\"], target=get_hexagon_target(\"v69\"))\n    module = hexagon_session.load_module(func_tir)\n\n    a_vtcm = np.zeros((a.size), dtype=\"uint8\")\n    b_vtcm = np.zeros((b.size), dtype=\"uint8\")\n    c_vtcm = np.zeros((c.size), dtype=\"int32\")\n\n    a_hexagon = tvm.runtime.ndarray.array(a, device=hexagon_session.device, mem_scope=\"global\")\n    b_hexagon = tvm.runtime.ndarray.array(b, device=hexagon_session.device, mem_scope=\"global\")\n    c_hexagon = tvm.runtime.ndarray.array(c, device=hexagon_session.device, mem_scope=\"global\")\n    a_vtcm_hexagon = tvm.runtime.ndarray.array(\n        a_vtcm, device=hexagon_session.device, mem_scope=\"global.vtcm\"\n    )\n    b_vtcm_hexagon = tvm.runtime.ndarray.array(\n        b_vtcm, device=hexagon_session.device, mem_scope=\"global.vtcm\"\n    )\n    c_vtcm_hexagon = tvm.runtime.ndarray.array(\n        c_vtcm, device=hexagon_session.device, mem_scope=\"global.vtcm\"\n    )\n\n    # These are reduced for CI but number=100 and repeat=10 does a good job of removing noise.\n    number = 1\n    repeat = 1\n\n    timer = module.time_evaluator(\n        \"__tvm_main__\", hexagon_session.device, number=number, repeat=repeat\n    )\n    time = timer(a_hexagon, b_hexagon, c_hexagon, a_vtcm_hexagon, b_vtcm_hexagon, c_vtcm_hexagon)\n    gops = round(operations * 128 * 3 / time.mean / 1e9, 4)\n    return gops, c_hexagon.asnumpy()\n\n\nclass TestMatMulVec:\n    \"\"\"MatMul test class.\"\"\"\n\n    # Removed most of these to speedup CI.\n    operations = tvm.testing.parameter(\n        1024,\n        # 2048,\n        # 4096,\n        # 5 * 2048,  # 3.93MB of total transfer\n        # 16384, #Only works on 8Gen1 HDK's\n        # 5 * 4096,  # 7.86MB of total transfer. Only works on 8Gen1 HDK's\n    )\n\n    # Experimentally best configurations for the memcopy\n    outer_split = tvm.testing.parameter(4)\n    unroll_split = tvm.testing.parameter(8)\n    vector_split = tvm.testing.parameter(64)\n    c_vector_split = tvm.testing.parameter(16)\n    c_vector_split_unallocated = tvm.testing.parameter(8)\n\n    @tvm.testing.fixture\n    def input_a(self, operations):\n        return default_rng().integers(0, 16, (operations, 128), dtype=\"uint8\")\n\n    @tvm.testing.fixture\n    def input_b(self, operations):\n        return default_rng().integers(0, 16, (operations, 128), dtype=\"uint8\")\n\n    @tvm.testing.fixture\n    def input_c(self, operations):\n        return np.zeros((operations, 32), dtype=\"int32\")\n\n    @tvm.testing.fixture\n    def expected_output(self, operations, input_a, input_b, input_c):\n        expected_output = np.zeros(input_c.shape, dtype=\"int32\")\n        for n in range(operations):\n            for i in range(32):\n                for r_ind in range(4):  # pylint: disable=unused-variable\n                    expected_output[n, i] = expected_output[n, i] + np.uint32(\n                        input_a[n, i * 4 + r_ind]\n                    ) * np.uint32(input_b[n, i * 4 + r_ind])\n        return expected_output\n\n    @tvm.testing.requires_hexagon\n    def test_loading_vtcm_for_vrmpy(\n        self,\n        hexagon_session,\n        operations,\n        input_a,\n        input_b,\n        input_c,\n        expected_output,\n        outer_split,\n        unroll_split,\n        vector_split,\n        c_vector_split,\n        c_vector_split_unallocated,\n    ):\n        \"\"\"Load VTCM for VRMPY operator test.\"\"\"\n        # Run parallel vrmpy without loading to VTCM.\n        sch = tvm.tir.Schedule(vrmpy(operations))\n        sch = apply_vrmpy_parallelization(sch)\n        base_runtime, result = setup_and_run(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with basic memory loads to VTCM.\n        sch = tvm.tir.Schedule(vrmpy(operations))\n        sch = apply_vtcm_cache_read_write(sch)\n        sch = apply_vrmpy_parallelization(sch)\n        basic_load_runtime, result = setup_and_run(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with vectorized memory loads to VTCM.\n        sch = tvm.tir.Schedule(vrmpy(operations))\n        sch = apply_vtcm_cache_read_write(sch)\n        sch = apply_vrmpy_parallelization(sch)\n        sch = apply_unroll_vectorize(\n            sch,\n            [sch.get_block(\"a_buffer_global.vtcm\"), sch.get_block(\"b_buffer_global.vtcm\")],\n            unroll_split,\n            vector_split,\n        )\n        sch = apply_unroll_vectorize(\n            sch, [sch.get_block(\"c_buffer_global.vtcm\")], unroll_split, c_vector_split_unallocated\n        )\n        vectorized_runtime, result = setup_and_run(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with vectorized and parallelized memory loads to VTCM.\n        sch = tvm.tir.Schedule(vrmpy(operations))\n        sch = apply_vtcm_cache_read_write(sch)\n        sch = apply_vrmpy_parallelization(sch)\n        sch = apply_parallel_unroll_vectorize(\n            sch,\n            [sch.get_block(\"a_buffer_global.vtcm\"), sch.get_block(\"b_buffer_global.vtcm\")],\n            outer_split,\n            unroll_split,\n            vector_split,\n        )\n        sch = apply_parallel_unroll_vectorize(\n            sch,\n            [sch.get_block(\"c_buffer_global.vtcm\")],\n            outer_split,\n            unroll_split,\n            c_vector_split_unallocated,\n        )\n        vectorized_parallelized_runtime, result = setup_and_run(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with preallocated and vectorized memory loads to VTCM.\n        sch = tvm.tir.Schedule(preallocated_vrmpy(operations))\n        sch = apply_vrmpy_parallelization(sch)\n        sch = apply_unroll_vectorize(\n            sch,\n            [sch.get_block(\"a_buffer_global.vtcm\"), sch.get_block(\"b_buffer_global.vtcm\")],\n            unroll_split,\n            vector_split,\n        )\n        sch = apply_unroll_vectorize(\n            sch, [sch.get_block(\"c_buffer_global.vtcm\")], unroll_split, c_vector_split\n        )\n        preallocated_vectorized_runtime, result = setup_and_run_preallocated(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        result = result.reshape((operations, 32))\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with preallocated, vectorized, and parallelized memory loads to VTCM.\n        sch = tvm.tir.Schedule(preallocated_vrmpy(operations))\n        sch = apply_vrmpy_parallelization(sch)\n        sch = apply_parallel_unroll_vectorize(\n            sch,\n            [sch.get_block(\"a_buffer_global.vtcm\"), sch.get_block(\"b_buffer_global.vtcm\")],\n            outer_split,\n            unroll_split,\n            vector_split,\n        )\n        sch = apply_parallel_unroll_vectorize(\n            sch, [sch.get_block(\"c_buffer_global.vtcm\")], outer_split, unroll_split, c_vector_split\n        )\n        prealloc_vector_parallelized, result = setup_and_run_preallocated(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        result = result.reshape((operations, 32))\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with preallocated single dma memory load to VTCM.\n        sch = tvm.tir.Schedule(preallocated_single_dma_vrmpy(operations))\n        sch = apply_vrmpy_parallelization(sch)\n        single_dma_runtime, result = setup_and_run_preallocated(\n            hexagon_session, sch, input_a, input_b, input_c, operations\n        )\n        result = result.reshape((operations, 32))\n        tvm.testing.assert_allclose(result, expected_output)\n\n        # Run parallel vrmpy with data preloaded in VTCM.\n        sch = tvm.tir.Schedule(preloaded_vrmpy(operations))\n        sch = apply_vrmpy_parallelization(sch)\n        input_a = input_a.reshape(operations * 128)\n        input_b = input_b.reshape(operations * 128)\n        input_c = input_c.reshape(operations * 32)\n        preloaded_runtime, result = setup_and_run(\n            hexagon_session, sch, input_a, input_b, input_c, operations, \"global.vtcm\"\n        )\n        result = result.reshape((operations, 32))\n        tvm.testing.assert_allclose(result, expected_output)\n\n        transfer_mb = round(3 * operations * 128 / 1e6, 2)\n        print(\n            TEST_OUTPUT_TEMPLATE.format(\n                transfer_mb,\n                base_runtime,\n                basic_load_runtime,\n                vectorized_runtime,\n                vectorized_parallelized_runtime,\n                preallocated_vectorized_runtime,\n                prealloc_vector_parallelized,\n                single_dma_runtime,\n                preloaded_runtime,\n            )\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_parallel_scalar.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test parallelism for multiple different scalar workloads. \"\"\"\n\nimport numpy as np\nfrom numpy.random import default_rng\n\nimport tvm\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\nTEST_OUTPUT_TEMPLATE = (\n    \"Test {} with {} operations... \\n\"\n    \"    -Single Thread: {} ms \\n\"\n    \"    -Parallel: {} ms\\n    -Speedup: {}x\\n\"\n)\n\n\ndef get_add_operator(operations):\n    \"\"\"Generate add operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations], dtype=\"float64\")\n        b_buffer = T.match_buffer(b, [operations], dtype=\"float64\")\n        c_buffer = T.match_buffer(c, [operations], dtype=\"float64\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind] = a_buffer[vn_ind] + b_buffer[vn_ind]\n\n    return operator\n\n\ndef get_multiply_operator(operations):\n    \"\"\"Generate multiply operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations], dtype=\"float64\")\n        b_buffer = T.match_buffer(b, [operations], dtype=\"float64\")\n        c_buffer = T.match_buffer(c, [operations], dtype=\"float64\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind] = a_buffer[vn_ind] * b_buffer[vn_ind]\n\n    return operator\n\n\ndef get_sub_operator(operations):\n    \"\"\"Generate subtract operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a_buffer = T.match_buffer(a, [operations], dtype=\"float64\")\n        b_buffer = T.match_buffer(b, [operations], dtype=\"float64\")\n        c_buffer = T.match_buffer(c, [operations], dtype=\"float64\")\n        for n in T.grid(operations):\n            with T.block(\"c_buffer\"):\n                vn_ind = T.axis.remap(\"S\", [n])\n                c_buffer[vn_ind] = a_buffer[vn_ind] - b_buffer[vn_ind]\n\n    return operator\n\n\ndef evaluate(hexagon_session, operations, expected, sch):\n    \"\"\"Evalute schedule.\"\"\"\n    shape = operations\n    dtype = \"float64\"\n\n    func_tir = tvm.build(sch.mod[\"main\"], target=get_hexagon_target(\"v68\"))\n    module = hexagon_session.load_module(func_tir)\n\n    rng = default_rng()\n    a = rng.random(shape, dtype=dtype)\n    b = rng.random(shape, dtype=dtype)\n    c = np.zeros(shape, dtype=dtype)\n\n    a_hexagon = tvm.runtime.ndarray.array(a, device=hexagon_session.device)\n    b_hexagon = tvm.runtime.ndarray.array(b, device=hexagon_session.device)\n    c_hexagon = tvm.runtime.ndarray.array(c, device=hexagon_session.device)\n\n    # These are reduced for CI but number=100 and repeat=10 does a good job of removing noise.\n    number = 1\n    repeat = 1\n\n    timer = module.time_evaluator(\n        \"__tvm_main__\", hexagon_session.device, number=number, repeat=repeat\n    )\n    runtime = timer(a_hexagon, b_hexagon, c_hexagon)\n\n    tvm.testing.assert_allclose(c_hexagon.asnumpy(), expected(a, b))\n\n    return round(runtime.mean * 1000, 6)\n\n\nclass TestMatMulVec:\n    \"\"\"MatMul test class.\"\"\"\n\n    (operation_name, operator_producer, expected_output_producer,) = tvm.testing.parameters(\n        (\"add\", get_add_operator, (lambda a, b: a + b)),\n        (\"mul\", get_multiply_operator, (lambda a, b: a * b)),\n        (\"sub\", get_sub_operator, (lambda a, b: a - b)),\n    )\n\n    # Removed most of these to speedup CI.\n    operations = tvm.testing.parameter(\n        128,\n        # 256,\n        # 512,\n        # Single thread runs faster since L2 cache can handle the entire request quickly\n        # 1024,\n        # 2048,\n        # Significant performance degredation once the inputs and outputs cannot all fit in L2\n        # 4096,\n        # 8192,\n        # 16384,\n    )\n\n    split_factor = tvm.testing.parameter(4)\n\n    @tvm.testing.requires_hexagon\n    def test_add(\n        self,\n        hexagon_session,\n        operation_name,\n        operator_producer,\n        expected_output_producer,\n        operations,\n        split_factor,\n    ):\n        \"\"\"Test Add operator.\"\"\"\n\n        sch = tvm.tir.Schedule(operator_producer(operations))\n        single_thread_runtime = evaluate(hexagon_session, operations, expected_output_producer, sch)\n\n        sch = tvm.tir.Schedule(operator_producer(operations))\n        block = sch.get_block(\"c_buffer\")\n        b = sch.get_loops(block)\n        b_output, _ = sch.split(b[0], factors=[split_factor, None])\n        sch.parallel(b_output)\n        parallel_runtime = evaluate(hexagon_session, operations, expected_output_producer, sch)\n\n        speedup = round(single_thread_runtime / parallel_runtime, 2)\n        print(\n            TEST_OUTPUT_TEMPLATE.format(\n                operation_name, operations, single_thread_runtime, parallel_runtime, speedup\n            )\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_run_unit_tests.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" capture gtest output and return over FFI \"\"\"\n\nimport tvm\nfrom tvm.contrib.hexagon.session import Session\n\n\n# use pytest -sv to observe gtest output\n# use --gtest_args to pass arguments to gtest\n# for example to run all \"foo\" tests twice and observe gtest output run\n# pytest -sv <this file> --gtests_args=\"--gtest_filter=*foo* --gtest_repeat=2\"\n@tvm.testing.requires_hexagon\ndef test_run_unit_tests(hexagon_session: Session, gtest_args):\n    \"\"\"Try running gtest unit tests and capture output and error code\"\"\"\n    try:\n        func = hexagon_session._rpc.get_function(\"hexagon.run_unit_tests\")\n    except:\n        print(\n            (\n                \"This test requires TVM Runtime to be built with a Hexagon gtest\"\n                \"version using Hexagon API cmake flag\"\n                \"-DUSE_HEXAGON_GTEST=/path/to/hexagon/sdk/utils/googletest/gtest\"\n            )\n        )\n        raise\n\n    gtest_error_code_and_output = func(gtest_args)\n    gtest_error_code = int(gtest_error_code_and_output.splitlines()[0])\n    gtest_output = gtest_error_code_and_output.split(\"\\n\", 1)[-1]\n    print(gtest_output)\n    if gtest_error_code != 0:\n        raise RuntimeError(\n            f\"Hexagon gtest retruned non-zero error code = {gtest_error_code}:\\n{gtest_output}\"\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_sigmoid.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Sigmoid operator tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import tir\nfrom tvm import topi\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom .infrastructure import get_hexagon_target\n\n\ndef sigmoid_compute(sigmoid_input):\n    return topi.sigmoid(sigmoid_input)\n\n\ndef sigmoid_stir_schedule(sigmoid_input, sigmoid_output):\n    sigmoid_func = te.create_prim_func([sigmoid_input, sigmoid_output])\n    sch = tir.Schedule(sigmoid_func, debug_mask=\"all\")\n    block = sch.get_block(\"compute\")\n\n    (n,) = sch.get_loops(block)\n    sch.vectorize(n)\n    return sch\n\n\nclass BaseSigmoid:\n    (in_shape, dtype, min_val, max_val,) = tvm.testing.parameters(\n        ((64,), \"float16\", -8.0, 8.0),\n        ((64,), \"float16\", -6.0, 7.0),\n        ((64,), \"float16\", -10.0, 15.0),\n        ((64,), \"float16\", -10.0, 0.0),\n        ((64,), \"float16\", 0.0, 10.0),\n    )\n\n\nclass TestSigmoid(BaseSigmoid):\n    \"\"\"Sigmoid test class.\"\"\"\n\n    @tvm.testing.fixture\n    def input_np(self, in_shape, dtype, min_val, max_val):\n        return np.random.uniform(low=min_val, high=max_val, size=in_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def ref_output_np(self, input_np):\n        output_np = 1 / (1 + np.exp(-input_np))\n        return output_np\n\n    @tvm.testing.requires_hexagon\n    def test_sigmoid(\n        self,\n        in_shape,\n        dtype,\n        input_np,\n        ref_output_np,\n        hexagon_session,\n    ):\n        \"\"\"Sigmoid test.\"\"\"\n        input_tensor = te.placeholder(in_shape, name=\"input_tensor\", dtype=dtype)\n\n        output_tensor = sigmoid_compute(input_tensor)\n\n        tir_s = sigmoid_stir_schedule(input_tensor, output_tensor)\n\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=input_np,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=ref_output_np.shape,\n            dtype=ref_output_np.dtype,\n        )\n\n        func_name = \"sigmoid\"\n        with tvm.transform.PassContext(opt_level=3):\n            runtime_module = tvm.build(tir_s.mod, target=get_hexagon_target(\"v69\"), name=func_name)\n\n        assert \"hvx_sigmoid\" in runtime_module.get_source(\"asm\")\n        assert \"vmin\" in runtime_module.get_source(\"asm\")\n        assert \"vmax\" in runtime_module.get_source(\"asm\")\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n\n        tvm.testing.assert_allclose(\n            output_np,\n            ref_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_software_pipeline_async.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Async software pipeline tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\n\ndef compute(comp_type, outer, inner, dtype):\n    \"\"\"Generate compute function.\"\"\"\n    if comp_type == \"single_input\":\n\n        @T.prim_func\n        def a_plus_1_primfunc(\n            a_buffer: T.Buffer[(outer, inner), dtype], out: T.Buffer[(outer, inner), dtype]\n        ):\n            for i in T.serial(outer):\n                for j in T.serial(inner):\n                    with T.block(\"compute\"):\n                        with T.block():\n                            out[i, j] = a_buffer[i, j] + T.cast(1, dtype)\n\n        return a_plus_1_primfunc\n    else:\n\n        @T.prim_func\n        def a_plus_b_plus_1_primfunc(\n            a_buffer: T.Buffer[(outer, inner), dtype],\n            b_buffer: T.Buffer[(outer, inner), dtype],\n            out: T.Buffer[(outer, inner), dtype],\n        ):\n            for i in T.serial(outer):\n                for j in T.serial(inner):\n                    with T.block(\"compute\"):\n                        with T.block():\n                            out[i, j] = a_buffer[i, j] + b_buffer[i, j] + T.cast(1, dtype)\n\n        return a_plus_b_plus_1_primfunc\n\n\nclass TestAsyncSoftwarePipeline:\n    \"\"\"Async software pipeline test class.\"\"\"\n\n    outer = tvm.testing.parameter(8, 16)\n    inner = tvm.testing.parameter(64, 128)\n    dtype = tvm.testing.parameter(\"uint8\", \"float16\")\n    scope = tvm.testing.parameter(\"global\", \"global.vtcm\")\n    # TODO(Joseph) Turn on \"multi_input_diffQ\" compute type once we have upstreamed\n    # changes in the InjectSoftwarePipeline pass to alleviate this restriction:\n    # 'a_buffer dependency on multiple async stages is not supported'\n    comp_type = tvm.testing.parameter(\"single_input\", \"multi_input_sameQ\")\n    # TODO(Straw) Add back \"cache_write\" schedule type once we have upstreamed\n    # buffer dependency analysis in InjectSoftwarePipeline pass\n    # to insert approprite TIR \"wait\" attributes for this schedule\n    sched_type = tvm.testing.parameter(\"cache_read\", \"cache_read_write\")\n\n    @tvm.testing.fixture\n    def data(self, comp_type, outer, inner, dtype):\n        out_np = np.random.uniform(low=0, high=128, size=(outer, inner)).astype(dtype)\n        a_np = np.random.uniform(low=0, high=128, size=(outer, inner)).astype(dtype)\n        if comp_type == \"single_input\":\n            return out_np, a_np\n        else:\n            b_np = np.random.uniform(low=0, high=128, size=(outer, inner)).astype(dtype)\n            return out_np, a_np, b_np\n\n    @tvm.testing.fixture\n    def verify(self, dtype):\n        def check(out, ref):\n            if \"int\" in dtype:\n                np.testing.assert_equal(out.numpy(), ref)\n            else:\n                np.testing.assert_allclose(out.numpy(), ref, rtol=1e-3, atol=1e-3)\n\n        return check\n\n    @tvm.testing.fixture\n    def reference(self, comp_type):\n        \"\"\"Returns reference data.\"\"\"\n        if comp_type == \"single_input\":\n\n            def a_plus_1_ref(a):\n                return a + 1\n\n            return a_plus_1_ref\n        else:\n\n            def a_plus_b_plus_1_ref(a, b):\n                return a + b + 1\n\n            return a_plus_b_plus_1_ref\n\n    @tvm.testing.fixture\n    def schedule(self, comp_type, sched_type, outer, inner, dtype, scope):\n        \"\"\"Generate schedule.\"\"\"\n        sch = tir.Schedule(compute(comp_type, outer, inner, dtype))\n\n        compute_block = sch.get_block(\"compute\")\n        i, _ = sch.get_loops(compute_block)\n\n        if \"read\" in sched_type:\n            cache_read_a = sch.cache_read(compute_block, 0, scope)\n            sch.compute_at(cache_read_a, i)\n\n            if \"multi_input\" in comp_type:\n                cache_read_b = sch.cache_read(compute_block, 1, scope)\n                sch.compute_at(cache_read_b, i)\n\n        if \"write\" in sched_type:\n            cache_write_out = sch.cache_write(compute_block, 0, scope)\n            sch.reverse_compute_at(cache_write_out, i)\n\n        if \"read\" in sched_type and \"write\" in sched_type:\n            if comp_type == \"single_input\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 1, 2])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1, 2])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0, 2])\n            elif comp_type == \"multi_input_sameQ\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 0, 1, 2])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1, 2, 3])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0, 2])\n            elif comp_type == \"multi_input_diffQ\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 1, 2, 3])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1, 2, 3])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0, 1, 2])\n\n        elif \"read\" in sched_type:\n            if comp_type == \"single_input\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 1])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0])\n            elif comp_type == \"multi_input_sameQ\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 0, 1])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1, 2])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0])\n            elif comp_type == \"multi_input_diffQ\":\n                sch.annotate(i, \"software_pipeline_stage\", [0, 1, 2])\n                sch.annotate(i, \"software_pipeline_order\", [0, 1, 2])\n                sch.annotate(i, \"software_pipeline_async_stages\", [0, 1])\n\n        elif \"write\" in sched_type:\n            sch.annotate(i, \"software_pipeline_stage\", [0, 1])\n            sch.annotate(i, \"software_pipeline_order\", [0, 1])\n            sch.annotate(i, \"software_pipeline_async_stages\", [1])\n\n        return sch\n\n    @tvm.testing.requires_hexagon\n    def test_async_software_pipeline(\n        self, hexagon_launcher, comp_type, data, reference, schedule, verify\n    ):\n        \"\"\"Async software pipeline test.\"\"\"\n        out_np = data[0]\n        a_np = data[1]\n        if comp_type == \"single_input\":\n            ref = reference(a_np)\n        else:\n            b_np = data[2]\n            ref = reference(a_np, b_np)\n\n        with tvm.transform.PassContext(\n            config={\"tir.use_async_copy\": 1, \"tir.merge_async_commit_queue_scope\": False}\n        ):\n            # tvm.lower(schedule.mod[\"main\"]).show()\n            func = tvm.build(schedule.mod[\"main\"], target=get_hexagon_target(\"v68\"))\n\n        with hexagon_launcher.create_session() as hexagon_session:\n            dev = hexagon_session.device\n            mod = hexagon_session.load_module(func)\n            out = tvm.nd.array(out_np, device=dev)\n            a = tvm.nd.array(a_np, device=dev)\n            if comp_type == \"single_input\":\n                mod(a, out)\n            else:\n                b = tvm.nd.array(b_np, device=dev)\n                mod(a, b, out)\n\n            verify(out, ref)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_thread_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Add hexagon thread pool test\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.contrib.hexagon\nimport tvm.script\nimport tvm.testing\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\n\n@tvm.script.ir_module\nclass ElemwiseSumIRModule:\n    \"\"\"IRModule definition for elementwise sum\"\"\"\n\n    # pylint: disable=no-self-argument,invalid-name,missing-function-docstring\n    @T.prim_func\n    def elemwise_sum_serial(a: T.handle, b: T.handle, c: T.handle, n: T.int32):\n        T.func_attr({\"global_symbol\": \"elemwise_sum_serial\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (n,), dtype=\"float32\")\n        B = T.match_buffer(b, (n,), dtype=\"float32\")\n        C = T.match_buffer(c, (n,), dtype=\"float32\")\n        for i in T.serial(n):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(n, i)\n                C[vi] = A[vi] + B[vi]\n\n    @T.prim_func\n    def elemwise_sum_parallel(a: T.handle, b: T.handle, c: T.handle, n: T.int32):\n        T.func_attr({\"global_symbol\": \"elemwise_sum_parallel\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (n,), dtype=\"float32\")\n        B = T.match_buffer(b, (n,), dtype=\"float32\")\n        C = T.match_buffer(c, (n,), dtype=\"float32\")\n        for i in T.parallel(n):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(n, i)\n                C[vi] = A[vi] + B[vi]\n\n    # pylint: enable=no-self-argument,invalid-name,missing-function-docstring\n\n\ndef generate_add_test_data(hexagon_session: Session, n=128 * 1024):\n    a = tvm.nd.array(np.random.uniform(size=n).astype(\"float32\"), hexagon_session.device)\n    b = tvm.nd.array(np.random.uniform(size=n).astype(\"float32\"), hexagon_session.device)\n    c = tvm.nd.array(np.zeros(n, dtype=\"float32\"), hexagon_session.device)\n    return (a, b, c, n)\n\n\ndef benchmark_func(mod, name, args, hexagon_session):\n    (a, b, c, n) = args\n    evaluator = mod.time_evaluator(name, hexagon_session.device, number=100)\n    return evaluator(a, b, c, n).mean\n\n\n@tvm.testing.requires_hexagon\ndef test_speedup(hexagon_session: Session, capsys):\n    \"\"\"Test speedup\"\"\"\n    func = tvm.build(\n        ElemwiseSumIRModule,\n        target=get_hexagon_target(\"v68\"),\n    )\n    mod = hexagon_session.load_module(func)\n    args = generate_add_test_data(hexagon_session)\n    parallel_mean = benchmark_func(mod, \"elemwise_sum_parallel\", args, hexagon_session)\n    serial_mean = benchmark_func(mod, \"elemwise_sum_serial\", args, hexagon_session)\n\n    with capsys.disabled():\n        print(\"... speedup of {:.2f}\".format(serial_mean / parallel_mean), end=\" \")\n\n\n@tvm.testing.requires_hexagon\ndef test_elemwise_sum_parallel(hexagon_session: Session):\n    \"\"\"Test parallel elementwise sum\"\"\"\n    func = tvm.build(\n        ElemwiseSumIRModule,\n        target=get_hexagon_target(\"v68\"),\n    )\n    mod = hexagon_session.load_module(func)\n\n    (a, b, c, n) = generate_add_test_data(hexagon_session)\n    mod[\"elemwise_sum_parallel\"](a, b, c, n)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_usmp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"USMP tests\"\"\"\n\nimport numpy as np\nimport pytest\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.testing.usmp import is_tvm_backendallocworkspace_calls\n\n\n@pytest.mark.parametrize(\"usmp_enabled\", [False, True])\n@tvm.testing.requires_hexagon\ndef test_conv2d(hexagon_session: Session, aot_host_target, aot_target, usmp_enabled):\n    \"\"\"Try conv2d on AOT target with usmp_enabled and check for TVMBackendAllocWorkspace calls\"\"\"\n    dtype = \"float32\"\n    input_shape = (1, 8, 8, 3)\n    w1_shape = (5, 5, 3, 1)\n    w2_shape = (5, 5, 1, 3)\n    data = relay.var(\"data\", relay.TensorType(input_shape, dtype))\n    weight1 = relay.var(\"weight1\", relay.TensorType(w1_shape, dtype))\n    weight2 = relay.var(\"weight2\", relay.TensorType(w2_shape, dtype))\n    outpu1 = relay.nn.conv2d(\n        data,\n        weight1,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    output2 = relay.nn.conv2d(\n        outpu1,\n        weight2,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight1, weight2], output2)\n    relay_mod = tvm.IRModule.from_expr(f)\n    relay_mod = relay.transform.InferType()(relay_mod)\n\n    weight1_data = np.random.rand(w1_shape[0], w1_shape[1], w1_shape[2], w1_shape[3]).astype(\n        dtype=dtype\n    )\n    weight2_data = np.random.rand(w2_shape[0], w2_shape[1], w2_shape[2], w2_shape[3]).astype(\n        dtype=dtype\n    )\n    input_data = np.random.rand(\n        input_shape[0], input_shape[1], input_shape[2], input_shape[3]\n    ).astype(dtype=dtype)\n\n    params = {\"weight1\": weight1_data, \"weight2\": weight2_data}\n    inputs = {\"data\": input_data}\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.usmp.enable\": usmp_enabled}):\n        lowered = tvm.relay.build(\n            relay_mod,\n            params=params,\n            target=tvm.target.Target(aot_target, host=aot_host_target),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\", {\"unpacked-api\": False, \"interface-api\": \"packed\"}),\n        )\n\n    assert is_tvm_backendallocworkspace_calls(lowered.lib) != usmp_enabled\n\n    aot_mod = hexagon_session.get_executor_from_factory(lowered)\n    aot_mod.set_input(**inputs)\n    aot_mod.run()\n    hexagon_output = aot_mod.get_output(0).numpy()\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            runtime=Runtime(\"cpp\"),\n            executor=Executor(\"aot\"),\n        )\n\n    llvm_mod = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](tvm.cpu(0)))\n    llvm_mod.set_input(**params)\n    llvm_mod.run(**inputs)\n    expected_output = llvm_mod.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(hexagon_output, expected_output, rtol=1e-4, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_vtcm_bandwidth.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test theoretical bandwith for data transfers to VTCM for different strategies.\"\"\"\n\nimport numpy as np\nfrom numpy.random import default_rng\n\nimport tvm\nfrom tvm.script import tir as T\n\nfrom .infrastructure import get_hexagon_target\n\nMB = 1024**2\nKB = 1024\nTEST_OUTPUT_TEMPLATE = (\n    \"Test bandwidth with buffer size {}MB... \\n\"\n    \"    -Base: {} GBps \\n    -Vectorized: {} GBps\\n\"\n    \"    -Vectorized and Parallelized: {} GBps\\n\"\n    \"    -Single DMA Copy: {} GBps\\n\"\n)\n\n\ndef memcopy_operator(size):\n    \"\"\"Generate memory copy operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, a_v: T.handle) -> None:\n        a_buffer = T.match_buffer(a, size, dtype=\"int8\", align=128, scope=\"global\")\n        a_global_vtcm = T.match_buffer(a_v, size, dtype=\"int8\", align=128, scope=\"global.vtcm\")\n        for ax0 in T.serial(size):\n            with T.block(\"A_global.vtcm\"):\n                v0_ind = T.axis.spatial(size, ax0)\n                T.reads(a_buffer[v0_ind])\n                T.writes(a_global_vtcm[v0_ind])\n                a_global_vtcm[v0_ind] = a_buffer[v0_ind]\n\n    return operator\n\n\ndef single_dma_operator(size):\n    \"\"\"Generate single dma operator.\"\"\"\n\n    @T.prim_func\n    def operator(a: T.handle, a_v: T.handle) -> None:\n        a_buffer = T.match_buffer(a, size, dtype=\"int8\", align=128, scope=\"global\")\n        a_global_vtcm = T.match_buffer(a_v, size, dtype=\"int8\", align=128, scope=\"global.vtcm\")\n        T.evaluate(\n            T.tvm_call_packed(\n                \"device_api.hexagon.mem_copy_DLTensor\",\n                T.tvm_stack_make_array(\n                    a_global_vtcm.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    a_global_vtcm.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    a_buffer.data,\n                    T.tvm_stack_make_shape(size, dtype=\"handle\"),\n                    0,\n                    1,\n                    a_buffer.dtype,\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.cast(size, dtype=\"int\"),\n                dtype=\"int32\",\n            )\n        )\n\n    return operator\n\n\ndef evaluate(hexagon_session, sch, size):\n    \"\"\"Evaluate schedule.\"\"\"\n    a_shape = size\n\n    func_tir = tvm.build(sch.mod[\"main\"], target=get_hexagon_target(\"v69\"))\n    module = hexagon_session.load_module(func_tir)\n\n    rng = default_rng()\n    a = rng.integers(-128, 127, a_shape, dtype=\"int8\")\n    a_vtcm = np.zeros(a_shape, dtype=\"int8\")\n\n    a_hexagon = tvm.runtime.ndarray.array(a, device=hexagon_session.device, mem_scope=\"global\")\n    a_vtcm_hexagon = tvm.runtime.ndarray.array(\n        a_vtcm, device=hexagon_session.device, mem_scope=\"global.vtcm\"\n    )\n\n    # These are reduced for CI but number=100 and repeat=10 does a good job of removing noise.\n    number = 1\n    repeat = 1\n\n    timer = module.time_evaluator(\n        \"__tvm_main__\", hexagon_session.device, number=number, repeat=repeat\n    )\n    runtime = timer(a_hexagon, a_vtcm_hexagon)\n\n    gbps = round((size / 2**30) / runtime.mean, 4)\n    tvm.testing.assert_allclose(a_vtcm_hexagon.asnumpy(), a)\n\n    return gbps\n\n\nclass TestMatMulVec:\n    \"\"\"MatMul test class.\"\"\"\n\n    # Removed most of these to speedup CI.\n    size = tvm.testing.parameter(\n        # 10 * KB,\n        # 20 * KB,\n        # 40 * KB,\n        # 80 * KB,\n        # 160 * KB,\n        # 320 * KB,\n        640 * KB,\n        # MB,\n        # 2 * MB,\n        # 3 * MB,\n        # 4 * MB,\n        # 8 * MB,  # Only works on 8gen1 HDKs\n    )\n\n    outer_split = tvm.testing.parameter(4)\n    unroll_split = tvm.testing.parameter(2)\n    vector_split = tvm.testing.parameter(128)\n\n    @tvm.testing.requires_hexagon\n    def test_bandwidth(self, hexagon_session, size, outer_split, unroll_split, vector_split):\n        \"\"\"Test bandwidth.\"\"\"\n        # Run the base memcopy operator.\n        sch = tvm.tir.Schedule(memcopy_operator(size))\n        base_gpbs = evaluate(hexagon_session, sch, size)\n\n        # Run with some basic unroll and vectorize scheduling.\n        sch = tvm.tir.Schedule(memcopy_operator(size))\n        vtcm_block_a = sch.get_block(\"A_global.vtcm\")\n        v_block = sch.get_loops(vtcm_block_a)\n        _, vio_a, vii_a = sch.split(v_block[0], factors=[None, unroll_split, vector_split])\n        sch.unroll(vio_a)\n        sch.vectorize(vii_a)\n        vectorize_gbps = evaluate(hexagon_session, sch, size)\n\n        # Run with some basic unroll and vectorize scheduling and parallelization.\n        sch = tvm.tir.Schedule(memcopy_operator(size))\n        vtcm_block_a = sch.get_block(\"A_global.vtcm\")\n        v_block = sch.get_loops(vtcm_block_a)\n        vbo_a, _, vio_a, vii_a = sch.split(\n            v_block[0], factors=[outer_split, None, unroll_split, vector_split]\n        )\n        sch.unroll(vio_a)\n        sch.vectorize(vii_a)\n        sch.parallel(vbo_a)\n        parallel_gbps = evaluate(hexagon_session, sch, size)\n\n        # Run using a single dma copy to transfer the data.\n        sch = tvm.tir.Schedule(single_dma_operator(size))\n        single_dma_gbps = evaluate(hexagon_session, sch, size)\n\n        mbs = round(size / MB, 2)\n        print(\n            TEST_OUTPUT_TEMPLATE.format(\n                mbs, base_gpbs, vectorize_gbps, parallel_gbps, single_dma_gbps\n            )\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/test_wo_qnn_canonicalization.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"No QNN canonicalization tests.\"\"\"\n\nimport numpy as np\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.contrib.hexagon.pytest_plugin import HEXAGON_AOT_LLVM_TARGET\nfrom tvm.relay.backend import Executor\n\n\n@tvm.testing.requires_hexagon\ndef test_no_qnn_pass():\n    \"\"\"No QNN pass test.\"\"\"\n    x = relay.var(\"x\", shape=(4, 8), dtype=\"float32\")\n    op0 = relay.qnn.op.quantize(x, relay.const(2.0), relay.const(10), out_dtype=\"uint8\")\n    op1 = relay.qnn.op.dequantize(op0, relay.const(0.5), relay.const(5))\n    mod = tvm.IRModule.from_expr(op1)\n\n    target_hexagon = tvm.target.hexagon(\"v68\")\n    # Default compilation flow\n    with tvm.transform.PassContext(opt_level=3):\n        opt_mod_1, _ = relay.optimize(mod, tvm.target.Target(target_hexagon, host=target_hexagon))\n\n    # Disable QNN legalization and canonicalization passes\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"qnn.Legalize\"]):\n        opt_mod_2, _ = relay.optimize(mod, tvm.target.Target(target_hexagon, host=target_hexagon))\n\n    # Check that QNN ops are absent with default compilation flow.\n    assert \"qnn.quantize\" not in opt_mod_1.astext(show_meta_data=False)\n    assert \"qnn.dequantize\" not in opt_mod_1.astext(show_meta_data=False)\n\n    # Check that QNN ops are present without \"qnn.Legalize\" passes.\n    assert \"qnn.quantize\" in opt_mod_2.astext(show_meta_data=False)\n    assert \"qnn.dequantize\" in opt_mod_2.astext(show_meta_data=False)\n\n\ndef execute(executor, data_np, weight_np, bias_np=None):\n    executor.set_input(\"data\", data_np)\n    executor.set_input(\"weight\", weight_np)\n    if bias_np is not None:\n        executor.set_input(\"bias\", bias_np)\n    executor.run()\n    return executor.get_output(0)\n\n\n@tvm.testing.requires_hexagon\ndef test_qnn_conv2d_rq(hexagon_session: Session):\n    \"\"\"QNN conv2d test.\"\"\"\n    data_shape = [1, 8, 32, 32]\n    weight_shape = [16, 8, 3, 3]\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    op0 = relay.qnn.op.quantize(data, relay.const(0.078), relay.const(0), out_dtype=\"int8\")\n    op1 = relay.qnn.op.quantize(weight, relay.const(0.07), relay.const(0), out_dtype=\"int8\")\n    op2 = relay.qnn.op.conv2d(\n        op0,\n        op1,\n        input_zero_point=relay.const(0),\n        kernel_zero_point=relay.const(0),\n        input_scale=relay.const(0.078),\n        kernel_scale=relay.const(0.07),\n        padding=[0, 0, 0, 0],\n        channels=16,\n        kernel_size=[3, 3],\n    )\n    op5 = relay.qnn.op.requantize(\n        op2,\n        input_scale=relay.const(0.05),\n        input_zero_point=relay.const(0),\n        output_scale=relay.const(0.21),\n        output_zero_point=relay.const(61),\n        out_dtype=\"int8\",\n    )\n    relay_mod = tvm.IRModule.from_expr(op5)\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    executor = Executor(\"aot\")\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"qnn.Legalize\"]):\n        hexagon_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(HEXAGON_AOT_LLVM_TARGET, host=HEXAGON_AOT_LLVM_TARGET),\n            executor=executor,\n        )\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            executor=executor,\n        )\n\n    data_np = np.random.rand(*data_shape) - 0.5\n    weight_np = np.random.rand(*weight_shape) - 0.5\n\n    hx_m = hexagon_session.get_executor_from_factory(hexagon_lowered)\n    hexagon_output = execute(hx_m, data_np, weight_np)\n\n    dev = tvm.cpu(0)\n    llvm_m = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](dev))\n    llvm_out = execute(llvm_m, data_np, weight_np)\n\n    np.testing.assert_equal(hexagon_output.numpy(), llvm_out.numpy())\n\n\n@tvm.testing.requires_hexagon\ndef test_qnn_dense_bias_rq(hexagon_session: Session):\n    \"\"\"QNN dense with bias test.\"\"\"\n    data_shape = [8, 8]\n    weight_shape = [16, 8]\n    bias_shape = [16]\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n    op0 = relay.qnn.op.quantize(data, relay.const(0.08), relay.const(0), out_dtype=\"int8\")\n    op1 = relay.qnn.op.quantize(weight, relay.const(0.07), relay.const(0), out_dtype=\"int8\")\n    op2 = relay.qnn.op.dense(\n        op0,\n        op1,\n        input_zero_point=relay.const(0),\n        kernel_zero_point=relay.const(0),\n        input_scale=relay.const(0.08),\n        kernel_scale=relay.const(0.07),\n        units=None,\n    )\n    op3 = relay.qnn.op.quantize(bias, relay.const(0.5), relay.const(0), out_dtype=\"int32\")\n    op4 = relay.nn.bias_add(op2, op3)\n    op5 = relay.qnn.op.requantize(\n        op4,\n        input_scale=relay.const(0.05),\n        input_zero_point=relay.const(0),\n        output_scale=relay.const(0.212),\n        output_zero_point=relay.const(10),\n        out_dtype=\"int8\",\n    )\n    relay_mod = tvm.IRModule.from_expr(op5)\n\n    target_llvm = tvm.target.Target(\"llvm\")\n    executor = Executor(\"aot\")\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"qnn.Legalize\"]):\n        hexagon_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(HEXAGON_AOT_LLVM_TARGET, host=HEXAGON_AOT_LLVM_TARGET),\n            executor=executor,\n        )\n\n    with tvm.transform.PassContext(opt_level=3):\n        llvm_lowered = tvm.relay.build(\n            relay_mod,\n            tvm.target.Target(target_llvm, host=target_llvm),\n            executor=executor,\n        )\n\n    data_np = np.random.rand(*data_shape) - 0.5\n    weight_np = np.random.rand(*weight_shape) - 0.5\n    bias_np = np.random.rand(*bias_shape)\n\n    hx_m = hexagon_session.get_executor_from_factory(hexagon_lowered)\n    hexagon_output = execute(hx_m, data_np, weight_np, bias_np)\n\n    dev = tvm.cpu(0)\n    llvm_m = tvm.runtime.executor.AotModule(llvm_lowered[\"default\"](dev))\n    llvm_out = execute(llvm_m, data_np, weight_np, bias_np)\n\n    np.testing.assert_equal(hexagon_output.numpy(), llvm_out.numpy())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Hexagon TOPI tests \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Hexagon TOPI Slice OP tests \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_argmax_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Tests for Hexagon slice argmax op \"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport tvm.topi.hexagon.slice_ops as sl\nimport tvm.contrib.hexagon\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\n\nclass TestArgMaxSlice:\n    \"\"\"Argmax Slice Op Tests\"\"\"\n\n    (\n        input_shape,\n        input_layout,\n        output_layout,\n        dtype,\n        in_axis,\n        in_axis_sep,\n        out_axis_sep,\n    ) = tvm.testing.parameters(\n        ((1, 64, 64, 32), \"nhwc-8h2w32c2w-2d\", \"nhw-32h16w-2d\", \"float16\", [3], [4], [3]),\n        ((3, 32, 16, 32), \"nhwc-8h2w32c2w-2d\", \"nhw-32h16w-2d\", \"float16\", [3], [4], [3]),\n        ((1, 32, 32, 64), \"nhwc-8h2w32c2w-2d\", \"nhw-32h16w-2d\", \"float16\", [3], [4], [3]),\n        ((1, 64, 64, 32), \"nhwc-8h8w32c-2d\", \"nhw-32h16w-2d\", \"int8\", [3], [4], [3]),\n        ((3, 32, 16, 32), \"nhwc-8h8w32c-2d\", \"nhw-32h16w-2d\", \"int8\", [3], [4], [3]),\n        ((1, 32, 32, 64), \"nhwc-8h8w32c-2d\", \"nhw-32h16w-2d\", \"int8\", [3], [4], [3]),\n    )\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape, dtype):\n        return np.random.uniform(size=input_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, input_layout):\n        return transform_numpy(input_np, \"nhwc\", input_layout)\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np, in_axis):\n        ref_np = np.argmax(input_np, *in_axis).astype(\"int32\")\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_expected_output_np(self, expected_output_np, output_layout):\n        return transform_numpy(expected_output_np, \"nhw\", output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_argmax_slice(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        in_axis,\n        transformed_input_np,\n        transformed_expected_output_np,\n        in_axis_sep,\n        out_axis_sep,\n        hexagon_session,\n        working_scope,\n    ):\n        \"\"\"Top level testing function for argmax\"\"\"\n        argmax_input = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n        output = sl.argmax.argmax_compute(argmax_input, in_axis)\n        argmax_func = te.create_prim_func([argmax_input, output])\n        tir_s = sl.argmax_schedule(argmax_func, input_layout, output_layout)\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=in_axis_sep,\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=out_axis_sep,\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            tir_irm = tvm.lower(tir_s.mod, [argmax_input, output], name=\"argmax\")\n            runtime_module = tvm.build(\n                tir_irm, [argmax_input, output], target=get_hexagon_target(\"v69\"), name=\"argmax\"\n            )\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_expected_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_avg_pool2d_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nfrom typing import *\n\nfrom tvm import te\nimport tvm.testing\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.hexagon.slice_ops as sl\nimport tvm.topi.hexagon.qnn as qn\nfrom tvm.contrib.hexagon import allocate_hexagon_array\nfrom ...infrastructure import (\n    transform_numpy,\n    quantize_np,\n    get_hexagon_target,\n)\nfrom ...pytest_util import (\n    get_multitest_ids,\n    create_populated_numpy_ndarray,\n    TensorContentRandom,\n)\n\ninput_layout = tvm.testing.parameter(\n    \"nhwc-8h2w32c2w-2d\",\n)\n\ndtype = tvm.testing.parameter(\"float16\", \"uint8\")\n\n\n@tvm.testing.fixture\ndef output_layout(output_shape, dtype):\n    o_b, o_h, o_w, o_c = output_shape\n    if dtype == \"float16\":\n        if o_h == 1 and o_w == 1:\n            return \"n11c-1024c-2d\"\n        else:\n            assert o_h % 8 == 0 and o_w % 4 == 0, \"Invalid output shape\"\n            return \"nhwc-8h2w32c2w-2d\"\n    elif dtype == \"int8\" or \"uint8\":\n        if o_h == 1 and o_w == 1:\n            return \"n11c-2048c-2d\"\n        else:\n            assert o_h % 8 == 0 and o_w % 8 == 0, \"Invalid output shape\"\n            return \"nhwc-8h8w32c-2d\"\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef input_np(input_shape, dtype: str, input_tensor_populator):\n    if dtype == \"uint8\":\n        dtype = \"float32\"  # Use \"float32\" input which will be quantized later\n    return create_populated_numpy_ndarray(input_shape, dtype, input_tensor_populator)\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, output_layout, dtype):\n    if dtype == \"float16\":\n        return transform_numpy(expected_output_np, \"nhwc\", output_layout)\n    elif dtype in (\"uint8\", \"int8\"):\n        quant_arr, scale, zero_point = quantize_np(expected_output_np, dtype)\n        return [transform_numpy(quant_arr, \"nhwc\", output_layout), scale, zero_point]\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef transformed_input_np_padded(input_np_padded, input_layout, dtype):\n    if dtype == \"float16\":\n        return transform_numpy(input_np_padded, \"nhwc\", input_layout)\n    elif dtype in (\"uint8\", \"int8\"):\n        quant_arr, scale, zero_point = quantize_np(input_np_padded, dtype)\n        return [transform_numpy(quant_arr, \"nhwc\", input_layout), scale, zero_point]\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\nclass TestAvgPool2dSlice:\n    _param_descs = [\n        \"out_shape\",  # output_shape\n        \"kernel\",  # kernel\n        \"stride\",  # stride\n        \"dil\",  # dilation\n        \"pad\",  # padding\n        \"ceil\",  # ceil_mode\n        \"cnt_padded\",  # count_include_pad\n        None,  # input_tensor_populator\n    ]\n\n    _multitest_params = [\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 16, 16, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [8, 8],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test non-one stride and dilation\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 3],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 2],\n            [2, 2],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 2],\n            [2, 3],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test non-zero padding\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [1, 1, 1, 1],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [1, 2, 3, 4],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [1, 2, 3, 4],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [3, 2],\n            [2, 3],\n            [1, 2, 3, 4],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test n11c-1024c-2d layout which will require input and output to have different layout\n        (\n            [1, 1, 1, 2048],\n            [8, 8],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [6, 6],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [3, 3],\n            [2, 2],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [4, 4],\n            [2, 2],\n            [2, 3],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n    ]\n\n    _param_ids = get_multitest_ids(_multitest_params, _param_descs)\n\n    # NOTE: input_layout is always assumed to be \"nhwc-8h2w32c2w-2d\"\n    (\n        output_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        ceil_mode,\n        count_include_pad,\n        input_tensor_populator,\n    ) = tvm.testing.parameters(*_multitest_params, ids=_param_ids)\n\n    @tvm.testing.fixture\n    def expected_output_np(\n        self,\n        input_np,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        ceil_mode,\n        count_include_pad,\n    ):\n        pad_before = padding[:2]\n        pad_after = padding[2:]\n        ref_np = tvm.topi.testing.poolnd_python(\n            input_np,\n            kernel,\n            stride,\n            dilation,\n            pad_before,\n            pad_after,\n            \"avg\",  # pool_type\n            count_include_pad,\n            False,  # ceil_mode,\n            layout=\"NHWC\",\n        )\n        return ref_np\n\n    @tvm.testing.fixture\n    def input_shape(self, output_shape, kernel, padding, stride, dilation, output_layout):\n        # Input shape without any padding; 'ceil' is being ignored from calculation:\n        o_b, o_h, o_w, o_c = output_shape\n        d_h, d_w = dilation\n        s_h, s_w = stride\n        k_h, k_w = kernel\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h, pad_after_w = padding[2:]\n\n        if output_layout == \"n11c-1024c-2d\":\n            assert (\n                pad_before_w == 0 and pad_after_w == 0 and pad_before_h == 0 and pad_after_h == 0\n            ), \"Padding must be zero for n11c-1024c-2d layout\"\n            assert o_h == 1 and o_w == 1, \"Output height and width must be 1\"\n\n        in_h = (o_h - 1) * s_h + d_h * (k_h - 1) + 1 - pad_before_h - pad_after_h\n        in_w = (o_w - 1) * s_w + d_w * (k_w - 1) + 1 - pad_before_w - pad_after_w\n\n        return [o_b, in_h, in_w, o_c]\n\n    @tvm.testing.fixture\n    def input_shape_padded(self, input_shape, padding, output_layout, dtype):\n        # Input shape is adjusted to account for 'padding'. Also, due to the physical\n        # layout of the buffer, height and width are adjusted so that they are a\n        # multiple of the buffer size dictated by the layout.\n        # NOTE: For float16, the input layout is always assumed to be nhwc-8h2w32c2w-2d and\n        # for int8/uint8, it's nhwc-8h8w32c-2d.\n        # For both nhwc-8h2w32c2w-2d and nhwc-8h8w32c-2d, the height should be a multiple\n        # of 8. However, the width should be a multiple of 4 for the first case and 8 for\n        # the second case.\n\n        height_mult = 8\n        if dtype == \"float16\":\n            width_mult = 4  # input layout : nhwc-8h2w32c2w-2d\n        elif dtype in (\"uint8\", \"int8\"):\n            width_mult = 8  # input layout : nhwc-8h8w32c-2d\n        else:\n            raise RuntimeError(f\"Unsupport dtype '{dtype}'\")\n\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h, pad_after_w = padding[2:]\n        padded_input_height = (\n            (input_shape[1] + pad_before_h + pad_after_h + height_mult - 1) // height_mult\n        ) * height_mult\n        padded_input_width = (\n            (input_shape[2] + pad_before_w + pad_after_w + width_mult - 1) // width_mult\n        ) * width_mult\n        return [input_shape[0], padded_input_height, padded_input_width, input_shape[3]]\n\n    @tvm.testing.fixture\n    def input_np_padded(self, input_np, input_shape, input_shape_padded, padding):\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h = input_shape_padded[1] - input_shape[1] - pad_before_h\n        pad_after_w = input_shape_padded[2] - input_shape[2] - pad_before_w\n        input_padded = np.pad(\n            input_np,\n            ((0, 0), (pad_before_h, pad_after_h), (pad_before_w, pad_after_w), (0, 0)),\n            \"constant\",\n        )\n        return input_padded\n\n    @tvm.testing.fixture\n    def schedule_args(\n        self,\n        stride,\n        kernel,\n        dtype,\n        dilation,\n        input_layout,\n        output_layout,\n        output_shape,\n        input_shape_padded,\n        transformed_input_np_padded,\n        transformed_expected_output_np,\n    ):\n        \"\"\"\n        Construct schedule args based on dtype\n        \"\"\"\n        A = te.placeholder(input_shape_padded, name=\"A\", dtype=dtype)\n\n        if dtype == \"float16\":\n            M = sl.avg_pool2d_compute(A, kernel, stride, dilation, output_shape)\n            tir_schedule = sl.avg_pool2d_schedule(M, A, output_layout, input_layout)\n        elif dtype in (\"uint8\", \"int8\"):\n            in_data, in_scale, in_zero_point = transformed_input_np_padded\n            _, out_scale, out_zero_point = transformed_expected_output_np\n            M = qn.qnn_avg_pool2d_compute(\n                A,\n                kernel,\n                stride,\n                dilation,\n                output_shape,\n                dtype,\n                in_zero_point,\n                in_scale,\n                out_zero_point,\n                out_scale,\n            )\n            tir_schedule = qn.qnn_avg_pool2d_schedule(M, A, output_layout, input_layout)\n\n        return [tir_schedule.mod, [A, M]]\n\n    @tvm.testing.requires_hexagon\n    def test_avg_pool2d_slice(\n        self,\n        dtype,\n        output_layout,\n        output_shape,\n        transformed_input_np_padded,\n        transformed_expected_output_np,\n        schedule_args,\n        hexagon_session: Session,\n    ):\n        in_data = transformed_input_np_padded\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(\n                *schedule_args,\n                get_hexagon_target(\"v69\"),\n                name=\"avg_pool2d\",\n            )\n\n        input_axis_separator = [4]\n        if output_layout in (\n            \"nhwc-8h2w32c2w-2d\",\n            \"nhwc-8h8w32c-2d\",\n            \"n11c-1024c-2d\",\n            \"n11c-2048c-2d\",\n        ):\n            output_axis_separator = [4]\n        else:\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n\n        if dtype == \"float16\":\n            in_data_np = transformed_input_np_padded\n            out_data_np = transformed_expected_output_np\n        elif dtype in (\"uint8\", \"int8\"):\n            in_data_np, _, _ = transformed_input_np_padded\n            out_data_np, _, _ = transformed_expected_output_np\n        else:\n            raise RuntimeError(f\"Unsupport dtype '{dtype}'\")\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=in_data_np,\n            axis_separators=input_axis_separator,\n            mem_scope=\"global.vtcm\",\n        )\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            out_data_np.shape,\n            dtype,\n            axis_separators=output_axis_separator,\n            mem_scope=\"global.vtcm\",\n        )\n\n        mod = hexagon_session.load_module(func)\n\n        mod(input_arr, output_arr)\n        b, h, w, c = output_shape\n        if output_layout == \"nhwc-8h2w32c2w-2d\":\n            output_np = output_arr.numpy().reshape([b, h // 8, w // 4, c // 32, 8, 2, 32, 2])\n        elif output_layout == \"nhwc-8h8w32c-2d\":\n            output_np = output_arr.numpy().reshape([b, h // 8, w // 8, c // 32, 8, 8, 32])\n        elif output_layout == \"n11c-2048c-2d\":\n            output_np = output_arr.numpy().reshape([b, 1, 1, c // 2048, 2048])\n        elif output_layout == \"n11c-1024c-2d\":\n            output_np = output_arr.numpy().reshape([b, 1, 1, c // 1024, 1024])\n        else:\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n        if dtype == \"float16\":\n            np.testing.assert_allclose(output_np, out_data_np, rtol=1e-3, atol=1e-3)\n        else:\n            np.testing.assert_allclose(output_np, out_data_np, rtol=1, atol=1)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_cast_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Tests for Hexagon slice cast ops \"\"\"\nimport pytest\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport tvm.topi.hexagon.slice_ops as sl\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\n\nclass TestCastF16F32Slice2d:\n    \"\"\"\n    For testing Cast F16  to F32 Slice ops\n    \"\"\"\n\n    input_shape, orig_layout, input_layout, output_layout, axis_sep = tvm.testing.parameters(\n        ((1, 16, 12, 64), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 64, 64, 32), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 16, 12, 64), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-4h2w32c2w-2d\", [4]),\n        ((1, 64, 64, 32), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-4h2w32c2w-2d\", [4]),\n        ((1, 1024), \"nc\", \"nc-1024c-2d\", \"nc-1024c-2d\", [2]),\n        ((1, 1024), \"nc\", \"nc-1024c-2d\", \"nc-512c-2d\", [2]),\n    )\n    dtype = tvm.testing.parameter(\"float16\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape, dtype):\n        return np.random.uniform(size=input_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, orig_layout, input_layout):\n        return transform_numpy(input_np, orig_layout, input_layout)\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np):\n        ref_np = input_np.astype(\"float32\")\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_expected_output_np(self, expected_output_np, orig_layout, output_layout):\n        return transform_numpy(expected_output_np, orig_layout, output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_cast_fp16_fp32_slice(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        transformed_input_np,\n        transformed_expected_output_np,\n        axis_sep,\n        hexagon_session,\n        working_scope,\n    ):\n        \"\"\"\n        Top level testing function for cast fp16 to fp32\n        \"\"\"\n        if hexagon_session.is_simulator():\n            pytest.skip(msg=\"Due to https://github.com/apache/tvm/issues/11957\")\n\n        cast_input = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n        cast_output = sl.cast_f16_f32_compute(cast_input)\n        cast_func = te.create_prim_func([cast_input, cast_output])\n        tir_s = sl.cast_f16_f32_schedule(cast_func, input_layout, output_layout)\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            tir_irm = tvm.lower(tir_s.mod, [cast_input, cast_output], name=\"cast_f16_f32\")\n            runtime_module = tvm.build(\n                tir_irm, target=get_hexagon_target(\"v69\"), name=\"cast_f16_f32\"\n            )\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_expected_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nclass TestCastF32F16Slice2d:\n    \"\"\"\n    For testing Cast F32 to F16 Slice ops\n    \"\"\"\n\n    (input_shape, orig_layout, input_layout, output_layout, axis_sep,) = tvm.testing.parameters(\n        ((1, 16, 12, 64), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 64, 64, 32), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 16, 12, 64), \"nhwc\", \"nhwc-4h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 64, 64, 32), \"nhwc\", \"nhwc-4h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 1024), \"nc\", \"nc-1024c-2d\", \"nc-1024c-2d\", [2]),\n        ((1, 1024), \"nc\", \"nc-512c-2d\", \"nc-1024c-2d\", [2]),\n    )\n    dtype = tvm.testing.parameter(\"float32\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape, dtype):\n        return np.random.uniform(size=input_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, orig_layout, input_layout):\n        return transform_numpy(input_np, orig_layout, input_layout)\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np):\n        ref_np = input_np.astype(\"float16\")\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_expected_output_np(self, expected_output_np, orig_layout, output_layout):\n        return transform_numpy(expected_output_np, orig_layout, output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_cast_fp32_fp16_slice(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        transformed_input_np,\n        transformed_expected_output_np,\n        axis_sep,\n        hexagon_session,\n        working_scope,\n    ):\n        \"\"\"\n        Top level testing function for cast fp32 to fp16\n        \"\"\"\n        if hexagon_session.is_simulator():\n            pytest.skip(msg=\"Due to https://github.com/apache/tvm/issues/11957\")\n\n        cast_input = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n        cast_output = sl.cast_f32_f16_compute(cast_input)\n        cast_func = te.create_prim_func([cast_input, cast_output])\n        tir_s = sl.cast_f32_f16_schedule(cast_func, input_layout, output_layout)\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            tir_irm = tvm.lower(tir_s.mod, [cast_input, cast_output], name=\"cast_f32_f16\")\n            runtime_module = tvm.build(\n                tir_irm, target=get_hexagon_target(\"v69\"), name=\"cast_f32_f16\"\n            )\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_expected_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_clip_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# pylint: disable=invalid-name\n\nimport numpy as np\n\nfrom tvm import te\nimport tvm.testing\nimport tvm.topi.hexagon.slice_ops as sl\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\ninput_layout = tvm.testing.parameter(\n    \"nhwc-8h2w32c2w-2d\",\n)\n\n\n@tvm.testing.fixture\ndef input_np(input_shape, dtype):\n    return np.random.random(input_shape).astype(dtype)\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, output_layout):\n    return transform_numpy(expected_output_np, \"nhwc\", output_layout)\n\n\n@tvm.testing.fixture\ndef transformed_input_np(input_np, input_layout):\n    return transform_numpy(input_np, \"nhwc\", input_layout)\n\n\nclass TestClipSlice:\n    input_shape, output_shape, A_min, A_max, output_layout, dtype = tvm.testing.parameters(\n        ([1, 8, 4, 32], [1, 8, 4, 32], 0.1, 0.5, \"nhwc-8h2w32c2w-2d\", \"float16\")\n    )\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np, A_min, A_max):\n        ref_np = np.clip(input_np, A_min, A_max)\n        return ref_np\n\n    @tvm.testing.requires_hexagon\n    def test_clip_slice(\n        self,\n        input_shape,\n        output_shape,\n        input_np,\n        input_layout,\n        output_layout,\n        dtype,\n        A_min,\n        A_max,\n        transformed_input_np,\n        transformed_expected_output_np,\n        hexagon_session,\n    ):\n        # establish target and input placeholder\n        A = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n\n        # get the compute function and schedule\n        M = sl.clip_compute(A, A_min, A_max)\n\n        # Assume layout is nhwc-8h2w32c2w-2d\n        tir_schedule = sl.clip_schedule(M, A, output_layout, input_layout)\n\n        # build the function\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(\n                tir_schedule.mod,\n                target=get_hexagon_target(\"v69\"),\n                name=\"clip\",\n            )\n\n        # allocate input and output nd arrays\n        axis_separators = [4]\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            dtype=dtype,\n            axis_separators=axis_separators,\n            mem_scope=\"global.vtcm\",\n        )\n\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            transformed_expected_output_np.shape,\n            dtype=dtype,\n            axis_separators=axis_separators,\n            mem_scope=\"global.vtcm\",\n        )\n\n        # execute\n        mod = hexagon_session.load_module(func)\n        mod(input_arr, output_arr)\n\n        # convert output nd array to numpy array\n        output_np = output_arr.numpy()\n        b, h, w, c = output_shape\n        reshaped_output_np = np.reshape(output_np, [b, h // 8, w // 4, c // 32, 8, 2, 32, 2])\n\n        # test results\n        np.testing.assert_allclose(\n            reshaped_output_np, transformed_expected_output_np, rtol=1e-3, atol=1e-3\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_conv2d_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long, redefined-outer-name\n\n\"\"\"Test conv2d slice op for hexagon\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.topi.hexagon.slice_ops.conv2d import conv2d_compute, conv2d_schedule\nfrom tvm.topi.testing import conv2d_nhwc_python\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\ninput_layout = tvm.testing.parameter(\n    \"nhwc-8h2w32c2w-2d\",\n)\n\noutput_layout = tvm.testing.parameter(\n    \"nhwc-8h2w32c2w-2d\",\n)\n\nweights_layout = tvm.testing.parameter(\"iohw-16i32o2i-1d\")\n\n\n@tvm.testing.fixture\ndef input_np(in_shape, dtype):\n    return np.random.uniform(size=in_shape).astype(dtype)\n\n\n@tvm.testing.fixture\ndef weights_np(filt_shape, dtype):\n    return (np.random.uniform(size=filt_shape)).astype(dtype)\n\n\n@tvm.testing.fixture\ndef dilated_filt_shape(filt_shape, dilation):\n    \"\"\"Compute the dilated filter shape when dilation > 1\"\"\"\n    filt_height, filt_width, in_channel, out_channel = filt_shape\n    dilation_height, dilation_width = dilation\n    if dilation_height == 1 and dilation_width == 1:\n        return filt_shape\n    dilated_height, dilated_width = (\n        dilation_height * (filt_height - 1) + 1,\n        dilation_width * (filt_width - 1) + 1,\n    )\n    return dilated_height, dilated_width, in_channel, out_channel\n\n\n@tvm.testing.fixture\ndef dilated_weights_np(weights_np, dilation, dilated_filt_shape):\n    \"\"\"Get dilated weights from original weights for testing\"\"\"\n    filt_height, filt_width, in_channels, out_channels = weights_np.shape\n    dilation_height, dilation_width = dilation\n    if dilation_height == 1 and dilation_width == 1:\n        return weights_np\n    dilated_height, dilated_width = dilated_filt_shape[0], dilated_filt_shape[1]\n    dilated_weights = np.zeros(dilated_filt_shape, dtype=\"float16\")\n    for in_channel in range(in_channels):\n        for out_channel in range(out_channels):\n            for dilation_i, height_i in zip(\n                range(0, dilated_height, dilation_height), range(filt_height)\n            ):\n                for dilation_j, width_j in zip(\n                    range(0, dilated_width, dilation_width), range(filt_width)\n                ):\n                    dilated_weights[dilation_i, dilation_j, in_channel, out_channel] = weights_np[\n                        height_i, width_j, in_channel, out_channel\n                    ]\n\n    return dilated_weights\n\n\n@tvm.testing.fixture\ndef input_np_padded(input_np, in_shape, padded_in_shape):\n    pad_height = padded_in_shape[1] - in_shape[1]\n    pad_width = padded_in_shape[2] - in_shape[2]\n    pad_channel = padded_in_shape[3] - in_shape[3]\n    input_padded = np.pad(\n        input_np, ((0, 0), (0, pad_height), (0, pad_width), (0, pad_channel)), \"constant\"\n    )\n    return input_padded\n\n\n@tvm.testing.fixture\ndef padded_filt_shape(filt_shape):\n    filt_height, filt_width, in_channels, out_channels = filt_shape\n    in_channels = ((in_channels + 31) // 32) * 32\n    out_channels = ((out_channels + 31) // 32) * 32\n    return filt_height, filt_width, in_channels, out_channels\n\n\n@tvm.testing.fixture\ndef weights_np_padded(weights_np, filt_shape, padded_filt_shape):\n    pad_in_channels = padded_filt_shape[2] - filt_shape[2]\n    pad_out_channels = padded_filt_shape[3] - filt_shape[3]\n    filt_padded = np.pad(weights_np, ((0, 0), (0, 0), (0, pad_in_channels), (0, pad_out_channels)))\n    return filt_padded\n\n\n@tvm.testing.fixture\ndef weights_np_transformed(weights_np_padded):\n    height, width, in_channel, out_channel = weights_np_padded.shape\n    weights_np_reverse_width = weights_np_padded[:, ::-1, :, :]\n    transformed_weights_np = weights_np_reverse_width.reshape(\n        [height, width, in_channel // 32, 16, 2, out_channel // 32, 32]\n    ).transpose(2, 5, 0, 1, 3, 6, 4)\n    return transformed_weights_np\n\n\ndef generate_test_config(test_params):\n    \"\"\"Utility function to generate test config with meaningful ids\"\"\"\n    test_config = {}\n\n    dims = lambda vals: \"x\".join(map(str, vals))\n\n    for param in test_params:\n        in_shape, filt_shape, stride, dilation = param\n        test_name = f\"nhwc{dims(in_shape)}-hwio{dims(filt_shape)}-stride{dims(stride)}-dilation{dims(dilation)}\"\n        test_config[test_name] = param\n\n    return test_config\n\n\nclass TestConv2dSlice:\n    \"\"\"Test class that defines the conv2d slice test\"\"\"\n\n    test_params = [\n        [\n            (1, 10, 6, 32),\n            (3, 3, 32, 32),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 18, 10, 32),\n            (3, 3, 32, 32),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 10, 6, 64),\n            (3, 3, 64, 64),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 12, 8, 4),\n            (3, 3, 4, 32),\n            (1, 1),\n            (2, 2),\n        ],\n        [\n            (1, 12, 8, 32),\n            (5, 5, 32, 32),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 16, 12, 32),\n            (5, 5, 32, 32),\n            (1, 1),\n            (2, 2),\n        ],\n        [\n            (1, 13, 9, 32),\n            (6, 6, 32, 32),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 18, 10, 32),\n            (3, 3, 32, 32),\n            (2, 2),\n            (1, 1),\n        ],\n        [\n            (1, 20, 12, 32),\n            (5, 5, 32, 32),\n            (2, 2),\n            (1, 1),\n        ],\n        [\n            (1, 22, 14, 32),\n            (7, 7, 32, 32),\n            (2, 2),\n            (1, 1),\n        ],\n        [\n            (1, 28, 20, 32),\n            (7, 7, 32, 32),\n            (2, 2),\n            (2, 2),\n        ],\n        [\n            (1, 10, 4, 4),\n            (3, 1, 4, 32),\n            (1, 1),\n            (1, 1),\n        ],\n        [\n            (1, 18, 8, 4),\n            (3, 1, 4, 32),\n            (2, 2),\n            (1, 1),\n        ],\n        [\n            (1, 20, 8, 4),\n            (3, 1, 4, 32),\n            (2, 2),\n            (2, 2),\n        ],\n    ]\n\n    test_config = generate_test_config(test_params)\n\n    in_shape, filt_shape, stride, dilation = tvm.testing.parameters(\n        *test_config.values(), ids=test_config.keys()\n    )\n    dtype = tvm.testing.parameter(\"float16\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def padded_in_shape(self, in_shape):\n        in_batch, in_height, in_width, in_channel = in_shape\n        in_height = ((in_height + 7) // 8) * 8\n        in_width = ((in_width + 3) // 4) * 4\n        in_channel = ((in_channel + 31) // 32) * 32\n        return in_batch, in_height, in_width, in_channel\n\n    @tvm.testing.fixture\n    def out_shape(self, in_shape, dilated_filt_shape, stride):\n        in_batch, in_height, in_width, _ = in_shape\n        filt_height, filt_width, _, num_filt = dilated_filt_shape\n        out_height = (in_height - filt_height) // stride[0] + 1\n        out_width = (in_width - filt_width) // stride[1] + 1\n        out_channel = num_filt\n        return in_batch, out_height, out_width, out_channel\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np, dilated_weights_np, stride):\n        ref_np = conv2d_nhwc_python(\n            input_np.astype(\"float32\"), dilated_weights_np.astype(\"float32\"), stride, padding=0\n        ).astype(\"float16\")\n        return ref_np\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d(\n        self,\n        padded_in_shape,\n        padded_filt_shape,\n        stride,\n        dilation,\n        dtype,\n        out_shape,\n        input_layout,\n        weights_layout,\n        output_layout,\n        input_np_padded,\n        weights_np_transformed,\n        expected_output_np,\n        working_scope,\n        hexagon_session,\n    ):\n        \"\"\"Main test function that tests the conv2d slice op\"\"\"\n        input_tensor = tvm.te.placeholder(padded_in_shape, name=\"InputTensor\", dtype=dtype)\n        weights = tvm.te.placeholder(padded_filt_shape, name=\"Weights\", dtype=dtype)\n        output_name = \"output\"\n\n        output_tensor = conv2d_compute(\n            input_tensor, weights, out_shape, stride, dilation, dtype, output_name\n        )\n\n        tir_schedule = conv2d_schedule(\n            output_tensor,\n            [input_tensor, weights],\n            input_layout,\n            weights_layout,\n            output_layout,\n            output_name,\n        )\n\n        func_name = f\"fconv2d_{dtype}\"\n        with tvm.transform.PassContext(opt_level=3):\n            runtime_module = tvm.build(\n                tir_schedule.mod,\n                target=get_hexagon_target(\"v69\"),\n                name=func_name,\n            )\n\n        input_np_transformed = transform_numpy(input_np_padded, \"nhwc\", input_layout)\n        output_np_transformed = transform_numpy(expected_output_np, \"nhwc\", output_layout)\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=input_np_transformed,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n\n        weights_arr = allocate_hexagon_array(\n            hexagon_session.device, data=weights_np_transformed, mem_scope=working_scope\n        )\n\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=output_np_transformed.shape,\n            dtype=output_np_transformed.dtype,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n\n        mod = hexagon_session.load_module(runtime_module)\n        mod(input_arr, weights_arr, output_arr)\n        output_np = output_arr.numpy()\n        np.testing.assert_allclose(output_np, output_np_transformed, atol=1.0, rtol=0.05)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_depthwise_conv2d_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-variable, unused-argument, disable=line-too-long, redefined-outer-name\n\n\"\"\"Test depthwise_conv2d slice op for hexagon.\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.hexagon.qnn as qn\nfrom tvm.topi.testing import depthwise_conv2d_python_nhwc\nfrom tvm.topi.hexagon.slice_ops.dwconv2d import dwconv2d_compute, dwconv2d_schedule\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, quantize_np\n\n\n@tvm.testing.fixture\ndef input_np(in_shape, dtype, low, high):\n    if dtype in (\"uint8\"):\n        return np.random.uniform(low=low, high=high, size=in_shape).astype(\"float32\")\n    if dtype in (\"int8\"):\n        return np.random.uniform(low=-low, high=high, size=in_shape).astype(\"float32\")\n    return np.random.uniform(size=in_shape).astype(dtype)\n\n\n@tvm.testing.fixture\ndef input_np_padded(input_np, in_shape, padded_in_shape):\n    pad_height = padded_in_shape[1] - in_shape[1]\n    pad_width = padded_in_shape[2] - in_shape[2]\n    pad_channel = padded_in_shape[3] - in_shape[3]\n    input_padded = np.pad(\n        input_np, ((0, 0), (0, pad_height), (0, pad_width), (0, pad_channel)), \"constant\"\n    )\n    return input_padded\n\n\n@tvm.testing.fixture\ndef in_out_layout(dtype):\n    if dtype == \"float16\":\n        return \"nhwc-8h2w32c2w-2d\"\n    elif dtype in (\"uint8\", \"int8\"):\n        return \"nhwc-8h8w32c-2d\"\n    else:\n        raise RuntimeError(f\"Unsupported quantized data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef expected_output_np(input_np, dilated_weights_np, stride, dtype):\n    dilated_weights_np_t = dilated_weights_np.transpose(0, 1, 3, 2)\n    ref_type = dtype\n    if dtype in (\"uint8\", \"int8\"):\n        # for quantized versions, return float32 output\n        ref_type = \"float32\"\n    ref_np = depthwise_conv2d_python_nhwc(\n        input_np.astype(\"float32\"), dilated_weights_np_t.astype(\"float32\"), stride, padding=0\n    ).astype(ref_type)\n    return ref_np\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, in_out_layout, dtype):\n    if dtype == \"float16\":\n        return transform_numpy(expected_output_np, \"nhwc\", in_out_layout)\n    elif dtype in (\"uint8\", \"int8\"):\n        quant_arr, scale, zero_point = quantize_np(expected_output_np, dtype)\n        return [transform_numpy(quant_arr, \"nhwc\", in_out_layout), scale, zero_point]\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef transformed_input_np_padded(input_np_padded, in_out_layout, dtype):\n    if dtype == \"float16\":\n        return transform_numpy(input_np_padded, \"nhwc\", in_out_layout)\n    if dtype in (\"uint8\", \"int8\"):\n        quant_arr, scale, zero_point = quantize_np(input_np_padded, dtype)\n        return [transform_numpy(quant_arr, \"nhwc\", in_out_layout), scale, zero_point]\n    raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef weights_np(filt_shape, dtype):\n    if dtype == \"float16\":\n        return np.random.uniform(size=filt_shape).astype(dtype)\n    elif dtype in (\"uint8\", \"int8\"):\n        weight_arr = np.random.uniform(low=-5, high=5, size=filt_shape).astype(\"float32\")\n        return weight_arr\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\n@tvm.testing.fixture\ndef dilated_filt_shape(filt_shape, dilation):\n    \"\"\"Compute the dilated filter shape when dilation > 1\"\"\"\n    filt_height, filt_width, in_channel, out_channel = filt_shape\n    dilation_height, dilation_width = dilation\n    if dilation_height == 1 and dilation_width == 1:\n        return filt_shape\n    dilated_height = dilation_height * (filt_height - 1) + 1\n    dilated_width = dilation_width * (filt_width - 1) + 1\n    return dilated_height, dilated_width, in_channel, out_channel\n\n\n@tvm.testing.fixture\ndef dilated_weights_np(weights_np, dilation, dilated_filt_shape, dtype):\n    \"\"\"Get dilated weights from original weights for testing\"\"\"\n    if dtype in [\"int8\", \"uint8\"]:\n        dtype = \"float32\"\n    filt_height, filt_width, in_channels, out_channels = weights_np.shape\n    dilated_weights = np.zeros(dilated_filt_shape)\n    dilation_height, dilation_width = dilation\n    if dilation_height == 1 and dilation_width == 1:\n        return weights_np\n    dilated_height, dilated_width = dilated_filt_shape[0], dilated_filt_shape[1]\n    for in_channel in range(in_channels):\n        for out_channel in range(out_channels):\n            for dilation_i, height_i in zip(\n                range(0, dilated_height, dilation_height), range(filt_height)\n            ):\n                for dilation_j, width_j in zip(\n                    range(0, dilated_width, dilation_width), range(filt_width)\n                ):\n                    dilated_weights[dilation_i, dilation_j, in_channel, out_channel] = weights_np[\n                        height_i, width_j, in_channel, out_channel\n                    ]\n    return dilated_weights\n\n\n@tvm.testing.fixture\ndef transformed_weights_np(weights_np, dtype):\n    height, width, in_channel, out_channel = weights_np.shape\n    t = weights_np.reshape([height, width, in_channel, out_channel // 32, 32]).transpose(\n        3, 0, 1, 2, 4\n    )\n    if dtype == \"float16\":\n        return t\n    if dtype in (\"uint8\", \"int8\"):\n        quant_arr, scale, zero_point = quantize_np(t, dtype)\n        return [quant_arr, scale, zero_point]\n    raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\ndef generate_test_config(test_params):\n    \"\"\"Utility function to generate test config with meaningful ids\"\"\"\n    test_config = {}\n\n    dims = lambda vals: \"x\".join(map(str, vals))\n\n    for param in test_params:\n        in_shape, filt_shape, stride, dilation = param[:4]\n        test_name = f\"nhwc{dims(in_shape)}-hwio{dims(filt_shape)}-stride{dims(stride)}-dilation{dims(dilation)}\"\n        test_config[test_name] = param\n\n    return test_config\n\n\nclass Testdwconv2dSlice:\n    \"\"\"Test class that defines the dwconv2d slice test\"\"\"\n\n    test_params = [\n        [(1, 10, 10, 32), (3, 3, 1, 32), (1, 1), (1, 1), 0.0, 10.0],\n        [(1, 10, 10, 64), (3, 3, 1, 64), (1, 1), (1, 1), 0.0, 10.0],\n        [(1, 12, 12, 32), (5, 5, 1, 32), (1, 1), (1, 1), 0.0, 20.0],\n        [(1, 16, 16, 32), (5, 5, 1, 32), (1, 1), (2, 2), 0.0, 1.0],\n        [(1, 18, 10, 32), (3, 3, 1, 32), (1, 1), (1, 1), 0.0, 10.0],\n        [(1, 18, 18, 32), (3, 3, 1, 32), (2, 2), (1, 1), 0.0, 10.0],\n        [(1, 18, 10, 96), (3, 3, 1, 96), (1, 1), (1, 1), 0.0, 10.0],\n        [(1, 21, 21, 32), (7, 7, 1, 32), (2, 2), (1, 1), 0.0, 10.0],\n        [(1, 28, 28, 32), (7, 7, 1, 32), (2, 2), (2, 2), 0.0, 10.0],\n        [(1, 28, 28, 96), (7, 7, 1, 96), (2, 2), (2, 2), 0.0, 10.0],\n        [(1, 10, 16, 32), (3, 1, 1, 32), (1, 1), (1, 1), 0.0, 10.0],\n    ]\n\n    test_config = generate_test_config(test_params)\n\n    in_shape, filt_shape, stride, dilation, low, high = tvm.testing.parameters(\n        *test_config.values(), ids=test_config.keys()\n    )\n    dtype = tvm.testing.parameter(\"float16\", \"uint8\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n    weights_layout = tvm.testing.parameter(\"ohwi32o-1d\")\n\n    @tvm.testing.fixture\n    def padded_in_shape(self, in_shape, dtype):\n        \"\"\"Padding the input shape according to layout\"\"\"\n        # NOTE: For float16, the input layout is always assumed to be nhwc-8h2w32c2w-2d and\n        # for int8/uint8, it's nhwc-8h8w32c-2d.\n        # For both nhwc-8h2w32c2w-2d and nhwc-8h8w32c-2d, the height should be a multiple\n        # of 8. However, the width should be a multiple of 4 for the first case and 8 for\n        # the second case.\n        in_batch, in_height, in_width, in_channel = in_shape\n        in_height = ((in_height + 7) // 8) * 8\n\n        if dtype == \"float16\":\n            in_width = ((in_width + 3) // 4) * 4\n        elif dtype in (\"uint8\", \"int8\"):\n            in_width = ((in_width + 7) // 8) * 8\n\n        in_channel = ((in_channel + 31) // 32) * 32\n\n        return in_batch, in_height, in_width, in_channel\n\n    @tvm.testing.fixture\n    def out_shape(self, in_shape, dilated_filt_shape, stride):\n        in_batch, in_height, in_width, _ = in_shape\n        filt_height, filt_width, _, num_filt = dilated_filt_shape\n        out_height = (in_height - filt_height) // stride[0] + 1\n        out_width = (in_width - filt_width) // stride[1] + 1\n        out_channel = num_filt\n        return in_batch, out_height, out_width, out_channel\n\n    @tvm.testing.requires_hexagon\n    def test_dwconv2d(\n        self,\n        dtype,\n        in_out_layout,\n        weights_layout,\n        padded_in_shape,\n        weights_np,\n        filt_shape,\n        stride,\n        dilation,\n        out_shape,\n        input_np,\n        input_np_padded,\n        transformed_weights_np,\n        expected_output_np,\n        target,\n        working_scope,\n        transformed_input_np_padded,\n        transformed_expected_output_np,\n        hexagon_session,\n    ):\n        \"\"\"Main test function that tests the dwconv2d slice op\"\"\"\n        input_tensor = tvm.te.placeholder(padded_in_shape, name=\"InputTensor\", dtype=dtype)\n        weights = tvm.te.placeholder(filt_shape, name=\"Weights\", dtype=dtype)\n\n        target_hexagon = tvm.target.hexagon(\"v69\")\n        target = tvm.target.Target(target_hexagon, host=target_hexagon)\n        # Construct compute and schedule based on dtype\n        if dtype in (\"uint8\", \"int8\"):\n            in_data_np, activation_scale, activation_zero_point = transformed_input_np_padded\n            (\n                weights_data_np,\n                weight_scale,\n                weight_zero_point,\n            ) = transformed_weights_np\n            out_data_np, output_scale, output_zero_point = transformed_expected_output_np\n\n            output_tensor = qn.qdepthwise_conv2d_compute(\n                input_tensor,\n                weights,\n                out_shape,\n                stride,\n                dilation,\n                dtype,\n                activation_zero_point,\n                activation_scale,\n                weight_zero_point,\n                weight_scale,\n                output_zero_point,\n                output_scale,\n            )\n\n            tir_schedule = qn.qdepthwise_conv2d_schedule(\n                output_tensor, [input_tensor, weights], in_out_layout, weights_layout\n            )\n\n        elif dtype == \"float16\":\n            in_data_np = transformed_input_np_padded\n            out_data_np = transformed_expected_output_np\n            weights_data_np = transformed_weights_np\n            output_tensor = dwconv2d_compute(\n                input_tensor, weights, out_shape, stride, dilation, dtype\n            )\n\n            tir_schedule = dwconv2d_schedule(\n                output_tensor, [input_tensor, weights], in_out_layout, weights_layout\n            )\n        else:\n            raise RuntimeError(f\"Unsupport dtype '{dtype}'\")\n\n        func_name = \"depthwise_conv2d_slice\"\n        with tvm.transform.PassContext(opt_level=3):\n            runtime_module = tvm.build(\n                tir_schedule.mod,\n                [input_tensor, output_tensor],\n                target=target,\n                name=func_name,\n            )\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=in_data_np,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n\n        weights_arr = allocate_hexagon_array(\n            hexagon_session.device, data=weights_data_np, mem_scope=working_scope\n        )\n\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            out_data_np.shape,\n            dtype=dtype,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n\n        mod = hexagon_session.load_module(runtime_module)\n        mod(input_arr, weights_arr, output_arr)\n        n, h, w, c = out_shape\n\n        if dtype in (\"uint8\", \"int8\"):\n            output_np = output_arr.numpy().reshape([n, h // 8, w // 8, c // 32, 8, 8, 32])\n            np.testing.assert_allclose(output_np, out_data_np, atol=3, rtol=0.02)\n        elif dtype == \"float16\":\n            output_np = output_arr.numpy()\n            np.testing.assert_allclose(output_np, out_data_np, atol=0.01, rtol=0.01)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_dequantize_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\" Tests for Hexagon dequantize \"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.topi.hexagon import qnn\nfrom tvm.contrib.hexagon import allocate_hexagon_array\nfrom ...infrastructure import (\n    transform_numpy,\n    quantize_np,\n    get_hexagon_target,\n)\n\n\nclass TestDequantizeSlice2d:\n    \"\"\"\n    For testing Dequantize Slice ops\n    \"\"\"\n\n    input_shape, orig_layout, input_layout, output_layout, axis_sep, dtype = tvm.testing.parameters(\n        ((1, 16, 64, 128), \"nhwc\", \"nhwc-8h8w32c-2d\", \"nhwc-4h2w32c2w-2d\", [4], \"int8\"),\n        ((1, 16, 64, 128), \"nhwc\", \"nhwc-8h8w32c-2d\", \"nhwc-4h2w32c2w-2d\", [4], \"uint8\"),\n        ((1, 8, 8, 32), \"nhwc\", \"nhwc-8h8w32c-2d\", \"nhwc-4h2w32c2w-2d\", [4], \"int8\"),\n        ((1, 8, 8, 32), \"nhwc\", \"nhwc-8h8w32c-2d\", \"nhwc-4h2w32c2w-2d\", [4], \"uint8\"),\n        ((1, 2048), \"nc\", \"nc-2048c-2d\", \"nc-512c-2d\", [2], \"int8\"),\n        ((1, 2048), \"nc\", \"nc-2048c-2d\", \"nc-512c-2d\", [2], \"uint8\"),\n    )\n\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape):\n        arr_np = np.random.random(size=input_shape).astype(\"float32\")\n        return arr_np\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, orig_layout, input_layout, dtype):\n        quant_arr, scale, zero_point = quantize_np(input_np, dtype)\n        return [transform_numpy(quant_arr, orig_layout, input_layout), scale, zero_point]\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np, dtype):\n        quant_np, scale, zero_point = quantize_np(input_np, dtype)\n        ref_np = (scale * (quant_np.astype(\"int32\") - zero_point)).astype(\"float32\")\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_expected_output_np(self, expected_output_np, orig_layout, output_layout):\n        return transform_numpy(expected_output_np, orig_layout, output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_dequant_qnn(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        transformed_input_np,\n        transformed_expected_output_np,\n        axis_sep,\n        hexagon_session,\n        working_scope,\n    ):\n        \"\"\"\n        Top level testing function for dequantize\n        \"\"\"\n\n        dequant_input = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n\n        in_data_np, in_scale, in_zero_pt = transformed_input_np\n\n        dequant_output = qnn.dequantize_compute(dequant_input, in_scale, in_zero_pt)\n\n        tir_s = qnn.dequantize_schedule(dequant_input, dequant_output, input_layout, output_layout)\n\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=in_data_np,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            tir_irm = tvm.lower(tir_s.mod, [dequant_input, dequant_output], name=\"dequantize\")\n            runtime_module = tvm.build(tir_irm, target=get_hexagon_target(\"v69\"), name=\"dequantize\")\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_expected_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_max_pool2d_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nfrom typing import *\n\nfrom tvm import te\nimport tvm.testing\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.hexagon.slice_ops as sl\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\nfrom ...pytest_util import (\n    get_multitest_ids,\n    create_populated_numpy_ndarray,\n    TensorContentRandom,\n)\n\n\n@tvm.testing.fixture\ndef input_np(input_shape, dtype: str, input_tensor_populator):\n    return create_populated_numpy_ndarray(input_shape, dtype, input_tensor_populator)\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, output_layout):\n    return transform_numpy(expected_output_np, \"nhwc\", output_layout)\n\n\n@tvm.testing.fixture\ndef transformed_input_np_padded(input_np_padded, input_layout):\n    return transform_numpy(input_np_padded, \"nhwc\", input_layout)\n\n\n(input_layout, dtype) = tvm.testing.parameters(\n    (\"nhwc-8h2w32c2w-2d\", \"float16\"),\n    (\"nhwc-8h8w32c-2d\", \"uint8\"),\n)\n\n\n@tvm.testing.fixture\ndef output_layout(output_shape, dtype):\n    o_b, o_h, o_w, o_c = output_shape\n    if dtype == \"float16\":\n        if o_h == 1 and o_w == 1:\n            return \"n11c-1024c-2d\"\n        else:\n            assert o_h % 8 == 0 and o_w % 4 == 0, \"Invalid output shape\"\n            return \"nhwc-8h2w32c2w-2d\"\n    elif dtype == \"int8\" or \"uint8\":\n        if o_h == 1 and o_w == 1:\n            return \"n11c-2048c-2d\"\n        else:\n            assert o_h % 8 == 0 and o_w % 8 == 0, \"Invalid output shape\"\n            return \"nhwc-8h8w32c-2d\"\n    else:\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\n\n\nclass TestmaxPool2dSlice:\n    _param_descs = [\n        \"out_shape\",  # output_shape\n        \"kernel\",  # kernel\n        \"stride\",  # stride\n        \"dil\",  # dilation\n        \"pad\",  # padding\n        \"ceil\",  # ceil_mode\n        \"cnt_padded\",  # count_include_pad\n        None,  # input_tensor_populator\n    ]\n\n    _multitest_params = [\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 16, 16, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [8, 8],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test non-one stride and dilation\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 3],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 2],\n            [2, 2],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [2, 2],\n            [2, 3],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test non-zero padding\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [1, 1, 1, 1],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 8, 8, 32],\n            [3, 3],\n            [1, 1],\n            [1, 1],\n            [1, 2, 3, 4],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        # Test n11c-1024c-2d layout which will require input and output to have different layout\n        (\n            [1, 1, 1, 2048],\n            [8, 8],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [6, 6],\n            [1, 1],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [3, 3],\n            [2, 2],\n            [1, 1],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n        (\n            [1, 1, 1, 2048],\n            [4, 4],\n            [2, 2],\n            [2, 3],\n            [0, 0, 0, 0],\n            False,\n            True,\n            TensorContentRandom(),\n        ),\n    ]\n\n    _param_ids = get_multitest_ids(_multitest_params, _param_descs)\n\n    # NOTE: input_layout is always assumed to be \"nhwc-8h2w32c2w-2d\" for float16\n    # and \"nhwc-8h8w32c-2d\" for uint8\n    (\n        output_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        ceil_mode,\n        count_include_pad,\n        input_tensor_populator,\n    ) = tvm.testing.parameters(*_multitest_params, ids=_param_ids)\n\n    @tvm.testing.fixture\n    def expected_output_np(\n        self,\n        input_np,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        ceil_mode,\n        count_include_pad,\n    ):\n        pad_before = padding[:2]\n        pad_after = padding[2:]\n        ref_np = tvm.topi.testing.poolnd_python(\n            input_np,\n            kernel,\n            stride,\n            dilation,\n            pad_before,\n            pad_after,\n            \"max\",  # pool_type\n            count_include_pad,\n            False,  # ceil_mode,\n            layout=\"NHWC\",\n        )\n        return ref_np\n\n    @tvm.testing.fixture\n    def input_shape(self, output_shape, kernel, padding, stride, dilation, output_layout):\n        # Input shape without any padding; 'ceil' is being ignored from calculation:\n        o_b, o_h, o_w, o_c = output_shape\n        d_h, d_w = dilation\n        s_h, s_w = stride\n        k_h, k_w = kernel\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h, pad_after_w = padding[2:]\n\n        if output_layout == \"n11c-1024c-2d\":\n            assert (\n                pad_before_w == 0 and pad_after_w == 0 and pad_before_h == 0 and pad_after_h == 0\n            ), \"Padding must be zero for n11c-1024c-2d layout\"\n            assert o_h == 1 and o_w == 1, \"Output height and width must be 1\"\n\n        in_h = (o_h - 1) * s_h + d_h * (k_h - 1) + 1 - pad_before_h - pad_after_h\n        in_w = (o_w - 1) * s_w + d_w * (k_w - 1) + 1 - pad_before_w - pad_after_w\n\n        return [o_b, in_h, in_w, o_c]\n\n    @tvm.testing.fixture\n    def input_shape_padded(self, dtype, input_shape, padding, output_layout):\n        # Input shape is adjusted to account for 'padding'. Also, due to the physical\n        # layout of the buffer, height and width are adjusted so that they are a\n        # multiple of 8 and 4 respectively.\n        # NOTE: For float16, the input layout is always assumed to be nhwc-8h2w32c2w-2d and\n        # for int8/uint8, it's nhwc-8h8w32c-2d.\n        # For both nhwc-8h2w32c2w-2d and nhwc-8h8w32c-2d, the height should be a multiple\n        # of 8. However, the width should be a multiple of 4 for the first case and 8 for\n        # the second case.\n\n        height_mult = 8\n        if dtype == \"float16\":\n            width_mult = 4  # input layout : nhwc-8h2w32c2w-2d\n        elif dtype in (\"uint8\", \"int8\"):\n            width_mult = 8  # input layout : nhwc-8h8w32c-2d\n        else:\n            raise RuntimeError(f\"Unsupport dtype '{dtype}'\")\n\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h, pad_after_w = padding[2:]\n        padded_input_height = (\n            (input_shape[1] + pad_before_h + pad_after_h + height_mult - 1) // height_mult\n        ) * height_mult\n        padded_input_width = (\n            (input_shape[2] + pad_before_w + pad_after_w + width_mult - 1) // width_mult\n        ) * width_mult\n        return [input_shape[0], padded_input_height, padded_input_width, input_shape[3]]\n\n    @tvm.testing.fixture\n    def input_np_padded(self, input_np, input_shape, input_shape_padded, padding):\n        pad_before_h, pad_before_w = padding[:2]\n        pad_after_h = input_shape_padded[1] - input_shape[1] - pad_before_h\n        pad_after_w = input_shape_padded[2] - input_shape[2] - pad_before_w\n\n        input_padded = np.pad(\n            input_np,\n            ((0, 0), (pad_before_h, pad_after_h), (pad_before_w, pad_after_w), (0, 0)),\n            \"constant\",\n        )\n        return input_padded\n\n    @tvm.testing.requires_hexagon\n    def test_max_pool2d_slice(\n        self,\n        stride,\n        kernel,\n        dtype,\n        dilation,\n        padding,\n        ceil_mode,  # only needed for manually obtaining the test id string\n        input_tensor_populator,  # only needed for manually obtaining the test id string\n        count_include_pad,\n        input_layout,\n        output_layout,\n        output_shape,\n        input_shape,\n        input_shape_padded,\n        input_np,\n        input_np_padded,\n        transformed_input_np_padded,\n        transformed_expected_output_np,\n        expected_output_np,\n        hexagon_session: Session,\n    ):\n        A = te.placeholder(input_shape_padded, name=\"A\", dtype=dtype)\n\n        M = sl.max_pool2d_compute(A, output_shape, kernel, stride, dilation)\n\n        # tir schedule\n        tir_schedule = sl.max_pool2d_STIR_schedule(M, A, output_layout, input_layout)\n        sch = tir_schedule.mod\n\n        input_axis_separator = [4]\n        if output_layout in (\n            \"nhwc-8h2w32c2w-2d\",\n            \"nhwc-8h8w32c-2d\",\n            \"n11c-1024c-2d\",\n            \"n11c-2048c-2d\",\n        ):\n            output_axis_separator = [4]\n        else:\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(\n                sch,\n                [A, M],\n                get_hexagon_target(\"v69\"),\n                name=\"max_pool2d\",\n            )\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np_padded,\n            axis_separators=input_axis_separator,\n            mem_scope=\"global.vtcm\",\n        )\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            transformed_expected_output_np.shape,\n            dtype,\n            axis_separators=output_axis_separator,\n            mem_scope=\"global.vtcm\",\n        )\n\n        mod = hexagon_session.load_module(func)\n        mod(input_arr, output_arr)\n        b, h, w, c = output_shape\n        if output_layout == \"nhwc-8h2w32c2w-2d\":\n            output_np = output_arr.numpy().reshape([b, h // 8, w // 4, c // 32, 8, 2, 32, 2])\n        elif output_layout == \"nhwc-8h8w32c-2d\":\n            output_np = output_arr.numpy().reshape([b, h // 8, w // 8, c // 32, 8, 8, 32])\n        elif output_layout == \"n11c-2048c-2d\":\n            output_np = output_arr.numpy().reshape([b, 1, 1, c // 2048, 2048])\n        elif output_layout == \"n11c-1024c-2d\":\n            output_np = output_arr.numpy().reshape([b, 1, 1, c // 1024, 1024])\n        else:\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n\n        if dtype == \"float16\":\n            np.testing.assert_allclose(\n                output_np, transformed_expected_output_np, rtol=1e-3, atol=1e-3\n            )\n        elif dtype == \"uint8\":\n            np.testing.assert_allclose(output_np, transformed_expected_output_np, atol=1)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_relu_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.topi.hexagon.slice_ops.relu import relu_compute, relu_stir_schedule\nfrom tvm import te\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\n\n@tvm.testing.fixture\ndef input_np(in_shape, dtype):\n    return np.random.uniform(size=in_shape).astype(dtype)\n\n\n@tvm.testing.fixture\ndef ref_output_np(input_np):\n    output_np = input_np * (input_np > 0)\n    return output_np\n\n\n@tvm.testing.fixture\ndef transformed_input_np(input_np, input_layout):\n    return transform_numpy(input_np, \"nhwc\", input_layout)\n\n\n@tvm.testing.fixture\ndef transformed_ref_output_np(ref_output_np, output_layout):\n    return transform_numpy(ref_output_np, \"nhwc\", output_layout)\n\n\nclass BaseRelu:\n    in_shape = tvm.testing.parameter(\n        (1, 8, 4, 32),\n        (1, 16, 4, 32),\n        (1, 16, 8, 32),\n        (1, 16, 8, 64),\n        (2, 8, 4, 32),\n        (2, 16, 4, 32),\n        (2, 16, 8, 32),\n        (2, 16, 8, 64),\n    )\n    dtype = tvm.testing.parameter(\"float16\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n    input_layout = tvm.testing.parameter(\"nhwc-8h2w32c2w-2d\")\n    output_layout = tvm.testing.parameter(\"nhwc-8h2w32c2w-2d\")\n\n\nclass TestReluSlice(BaseRelu):\n    @tvm.testing.requires_hexagon\n    def test_relu(\n        self,\n        in_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        transformed_input_np,\n        transformed_ref_output_np,\n        working_scope,\n        hexagon_session,\n    ):\n        InputTensor = te.placeholder(in_shape, name=\"InputTensor\", dtype=dtype)\n\n        OutputTensor = relu_compute(InputTensor)\n\n        tir_s = relu_stir_schedule(InputTensor, OutputTensor, input_layout, output_layout)\n\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_ref_output_np.shape,\n            dtype=transformed_ref_output_np.dtype,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n\n        func_name = \"relu\"\n        with tvm.transform.PassContext(opt_level=3):\n            runtime_module = tvm.build(tir_s.mod, target=get_hexagon_target(\"v69\"), name=func_name)\n\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_ref_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_softmax_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.topi.testing import softmax_python\nimport tvm.topi.hexagon.slice_ops as sl\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\n\ndef transform_numpy(arr_np, layout):\n\n    if layout in [\"nc-512c-2d\"]:\n        N, C = arr_np.shape\n        return arr_np.reshape([N, C // 512, 512])\n    raise RuntimeError(f\"Unexpected layout '{layout}'\")\n\n\n@tvm.testing.fixture\ndef input_np(input_shape, dtype):\n    return (np.random.uniform(size=input_shape)).astype(dtype)\n\n\n@tvm.testing.fixture\ndef transformed_expected_output_np(expected_output_np, output_layout):\n    return transform_numpy(expected_output_np, output_layout)\n\n\n@tvm.testing.fixture\ndef transformed_input_np(input_np, input_layout):\n    return transform_numpy(input_np, input_layout)\n\n\nclass Basesoftmax2d:\n\n    input_shape, input_layout, output_layout, axis_sep = tvm.testing.parameters(\n        ((1, 1024), \"nc-512c-2d\", \"nc-512c-2d\", [2])\n    )\n    dtype = tvm.testing.parameter(\"float32\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n\nclass TestSoftmax2d(Basesoftmax2d):\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np):\n        if len(input_np.shape) == 2:\n            ref_np_2d = softmax_python(input_np)\n            return ref_np_2d\n        raise RuntimeError(f\"Unexpected input shape '{input_np.shape}'\")\n\n    @tvm.testing.requires_hexagon\n    def test_softmax_f32(\n        self,\n        dtype,\n        input_layout,\n        output_layout,\n        input_shape,\n        input_np,\n        transformed_input_np,\n        transformed_expected_output_np,\n        expected_output_np,\n        working_scope,\n        axis_sep,\n        hexagon_session,\n    ):\n        target_hexagon = tvm.target.hexagon(\n            \"v69\",\n            llvm_options=\"--disable-loop-unrolling-pass\",\n        )\n        A = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n\n        O = sl.softmax_compute(A)\n\n        if input_layout == \"nc-512c-2d\":\n            tir_s = sl.softmax_stir_schedule(O, A, output_layout, input_layout)\n            sch = tir_s.mod\n        else:\n            raise RuntimeError(f\"Unexpected input layout '{input_layout}'\")\n\n        with tvm.transform.PassContext(\n            opt_level=3,\n            config={\n                \"tir.LoopPartition\": {\"partition_const_loop\": True},\n            },\n        ):\n\n            func = tvm.build(\n                sch,\n                [A, O],\n                tvm.target.Target(target_hexagon, host=target_hexagon),\n                name=\"softmax_slice\",\n            )\n\n        input_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n\n        output_arr = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n\n        mod = hexagon_session.load_module(func)\n        mod(input_arr, output_arr)\n\n        n, c = input_np.shape\n        output_np = output_arr.numpy().reshape(1, c // 512, 512)\n\n        np.testing.assert_allclose(output_np, transformed_expected_output_np, rtol=1e-4, atol=1e-4)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/slice_op/test_tanh_slice.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test for Hexagon slice tanh op \"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport tvm.topi.hexagon.slice_ops as sl\nimport tvm.contrib.hexagon\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ...infrastructure import transform_numpy, get_hexagon_target\n\n# pylint: disable=invalid-name\n\n\nclass TestTanhSlice:\n    \"\"\"For Testing Tanh fp16 op\"\"\"\n\n    input_shape, orig_layout, input_layout, output_layout, axis_sep = tvm.testing.parameters(\n        ((1, 8, 4, 32), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 16, 12, 64), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n        ((1, 64, 64, 32), \"nhwc\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", [4]),\n    )\n    dtype = tvm.testing.parameter(\"float16\")\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape, dtype):\n        return np.random.uniform(size=input_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, orig_layout, input_layout):\n        return transform_numpy(input_np, orig_layout, input_layout)\n\n    @tvm.testing.fixture\n    def expected_output_np(self, input_np):\n        ref_np = np.tanh(input_np)\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_expected_output_np(self, expected_output_np, orig_layout, output_layout):\n        return transform_numpy(expected_output_np, orig_layout, output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_tanh(\n        self,\n        input_shape,\n        dtype,\n        input_layout,\n        output_layout,\n        transformed_input_np,\n        transformed_expected_output_np,\n        axis_sep,\n        hexagon_session,\n        working_scope,\n    ):\n        \"\"\"Top Level testing function for tanh fp16 op\"\"\"\n\n        A = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n        M = sl.tanh_te_compute(A)\n        tanhf16_func = te.create_prim_func([A, M])\n        tir_s = sl.tanhf16_schedule(tanhf16_func, input_layout, output_layout)\n        A_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        M_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_expected_output_np.shape,\n            dtype=transformed_expected_output_np.dtype,\n            axis_separators=axis_sep,\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            tir_irm = tvm.lower(tir_s.mod, [A, M], name=\"tanhf16\")\n            runtime_module = tvm.build(tir_irm, target=get_hexagon_target(\"v69\"), name=\"tanhf16\")\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(A_data, M_data)\n        output_np = M_data.numpy()\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_expected_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_add_subtract_multiply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n\"\"\"Test code for Add, Subtract and Multiply.\"\"\"\r\nimport numpy as np\r\n\r\nimport tvm\r\nfrom tvm import te\r\nimport tvm.topi.hexagon.slice_ops as sl\r\nimport tvm.topi.hexagon.qnn as qn\r\nfrom tvm.contrib.hexagon import allocate_hexagon_array\r\nfrom ..infrastructure import (\r\n    transform_numpy,\r\n    quantize_np,\r\n    get_hexagon_target,\r\n)\r\n\r\nZERO_POINT_A_VAL = None\r\nSCALE_A_VAL = None\r\n\r\nZERO_POINT_B_VAL = None\r\nSCALE_B_VAL = None\r\n\r\nZERO_POINT_M_VAL = None\r\nSCALE_M_VAL = None\r\n\r\n\r\ndef hexagon_wrapper_allocation(\r\n    device,\r\n    layout,\r\n    axis_separators,\r\n    tensor_shape=None,\r\n    data_original=None,\r\n    transformed_data=None,\r\n    dtype=None,\r\n):\r\n    \"\"\"Input layout can either be nhwc-8h2w32c2w-2d or nhwc\"\"\"\r\n    if layout in [\"nhwc-8h2w32c2w-2d\", \"nhwc-8h8w32c-2d\"]:\r\n        data_nd = allocate_hexagon_array(\r\n            device,\r\n            tensor_shape=tensor_shape,\r\n            data=transformed_data,\r\n            dtype=dtype,\r\n            axis_separators=axis_separators,\r\n            mem_scope=\"global.vtcm\",\r\n        )\r\n    elif layout == \"nhwc\":\r\n        data_nd = allocate_hexagon_array(\r\n            device,\r\n            data=data_original,\r\n        )\r\n    return data_nd\r\n\r\n\r\nclass TestAddSubtractMultiplyBroadcast2d:\r\n    \"\"\"Test Add, Subtract and Multiply class.\"\"\"\r\n\r\n    (\r\n        input_shape_a,\r\n        input_shape_b,\r\n        input_a_layout,\r\n        input_b_layout,\r\n        output_layout,\r\n        dtype,\r\n    ) = tvm.testing.parameters(\r\n        # no broadcast needed - short input\r\n        (\r\n            [1, 8, 4, 32],\r\n            [1, 8, 4, 32],\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        # no broadcast needed - large input\r\n        (\r\n            [1, 56, 64, 128],\r\n            [1, 56, 64, 128],\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        # one input needs broadcast\r\n        (\r\n            [1, 56, 64, 128],\r\n            [1, 1, 64, 1],\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        # Both input needs broadcast\r\n        (\r\n            [1, 56, 1, 128],\r\n            [1, 1, 64, 1],\r\n            \"nhwc\",\r\n            \"nhwc\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        # One axis in one input needs broadcast\r\n        (\r\n            [1, 56, 20, 128],\r\n            [1, 56, 20, 1],\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        # broadcast all axes in one input\r\n        (\r\n            [1, 48, 56, 32],\r\n            [1, 1, 1, 1],\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"float16\",\r\n        ),\r\n        (\r\n            [1, 48, 32, 64],\r\n            [1, 48, 32, 64],\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast axis 2 in one input\r\n        (\r\n            [1, 48, 32, 64],\r\n            [1, 48, 1, 64],\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast axis 1 in one input\r\n        (\r\n            [1, 48, 32, 64],\r\n            [1, 1, 32, 64],\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast axis 3 in one input\r\n        (\r\n            [1, 8, 8, 32],\r\n            [1, 8, 8, 1],\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast both inputs\r\n        (\r\n            [1, 56, 1, 128],\r\n            [1, 1, 64, 1],\r\n            \"nhwc\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast both inputs\r\n        (\r\n            [1, 48, 1, 1],\r\n            [1, 1, 32, 32],\r\n            \"nhwc\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast both inputs\r\n        (\r\n            [1, 48, 1, 32],\r\n            [1, 1, 32, 1],\r\n            \"nhwc\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n        # broadcast all axes in one input\r\n        (\r\n            [1, 48, 56, 32],\r\n            [1, 1, 1, 1],\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"nhwc\",\r\n            \"nhwc-8h8w32c-2d\",\r\n            \"uint8\",\r\n        ),\r\n    )\r\n\r\n    op_name = tvm.testing.parameter(\"add\", \"subtract\", \"multiply\")\r\n\r\n    @tvm.testing.fixture\r\n    def expected_output_np(self, input_np_a, input_np_b, op_name):\r\n        \"\"\"Generate expected output.\"\"\"\r\n        if op_name == \"add\":\r\n            out_ref = np.add(input_np_a, input_np_b)\r\n        elif op_name == \"subtract\":\r\n            out_ref = np.subtract(input_np_a, input_np_b)\r\n        elif op_name == \"multiply\":\r\n            out_ref = np.multiply(input_np_a, input_np_b)\r\n        return out_ref\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_expected_output_np(self, expected_output_np, output_layout, dtype):\r\n        \"\"\"Generate expected output.\"\"\"\r\n        if dtype == \"float16\":\r\n            return transform_numpy(expected_output_np, \"nhwc\", output_layout)\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            global ZERO_POINT_M_VAL, SCALE_M_VAL\r\n            out_ref_quantized, SCALE_M_VAL, ZERO_POINT_M_VAL = quantize_np(\r\n                expected_output_np, dtype\r\n            )\r\n            return transform_numpy(out_ref_quantized, \"nhwc\", output_layout)\r\n\r\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\r\n\r\n    @tvm.testing.fixture\r\n    def input_np_a(self, input_shape_a, dtype):\r\n        \"\"\"Generate numpy input for variable a.\"\"\"\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            dtype = \"float32\"\r\n        return np.random.random(input_shape_a).astype(dtype)\r\n\r\n    @tvm.testing.fixture\r\n    def input_np_b(self, input_shape_b, dtype):\r\n        \"\"\"Generate numpy input for variable b.\"\"\"\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            dtype = \"float32\"\r\n        return np.random.random(input_shape_b).astype(dtype)\r\n\r\n    @tvm.testing.fixture\r\n    def quantize_input_np_a(self, input_np_a, dtype):\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            global ZERO_POINT_A_VAL, SCALE_A_VAL\r\n            input_np_a_quantized, SCALE_A_VAL, ZERO_POINT_A_VAL = quantize_np(input_np_a, dtype)\r\n            return input_np_a_quantized\r\n        return None\r\n\r\n    @tvm.testing.fixture\r\n    def quantize_input_np_b(self, input_np_b, dtype):\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            global ZERO_POINT_B_VAL, SCALE_B_VAL\r\n            input_np_b_quantized, SCALE_B_VAL, ZERO_POINT_B_VAL = quantize_np(input_np_b, dtype)\r\n            return input_np_b_quantized\r\n        return None\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_input_np_a(self, input_np_a, quantize_input_np_a, input_a_layout, dtype):\r\n        if dtype == \"float16\":\r\n            return transform_numpy(input_np_a, \"nhwc\", input_a_layout)\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            return transform_numpy(quantize_input_np_a, \"nhwc\", input_a_layout)\r\n\r\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_input_np_b(self, input_np_b, quantize_input_np_b, input_b_layout, dtype):\r\n        if dtype == \"float16\":\r\n            return transform_numpy(input_np_b, \"nhwc\", input_b_layout)\r\n        if dtype in [\"uint8\", \"int8\"]:\r\n            return transform_numpy(quantize_input_np_b, \"nhwc\", input_b_layout)\r\n\r\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\r\n\r\n    @tvm.testing.requires_hexagon\r\n    def test_transform(\r\n        self,\r\n        dtype,\r\n        input_shape_a,\r\n        input_shape_b,\r\n        input_np_a,\r\n        input_np_b,\r\n        quantize_input_np_a,\r\n        quantize_input_np_b,\r\n        transformed_input_np_a,\r\n        transformed_input_np_b,\r\n        expected_output_np,\r\n        transformed_expected_output_np,\r\n        hexagon_session,\r\n        output_layout,\r\n        input_a_layout,\r\n        input_b_layout,\r\n        op_name,\r\n    ):\r\n        \"\"\"Test transform.\"\"\"\r\n        output_shape = expected_output_np.shape\r\n        a_tensor = te.placeholder(input_shape_a, name=\"a_tensor\", dtype=dtype)\r\n        b_tensor = te.placeholder(input_shape_b, name=\"b_tensor\", dtype=dtype)\r\n        if dtype == \"float16\":\r\n            if op_name == \"add\":\r\n                m_tensor = sl.add_broadcast_compute(a_tensor, b_tensor)\r\n            elif op_name == \"subtract\":\r\n                m_tensor = sl.subtract_broadcast_compute(a_tensor, b_tensor)\r\n            elif op_name == \"multiply\":\r\n                m_tensor = sl.multiply_broadcast_compute(a_tensor, b_tensor)\r\n            tir_schedule = sl.tir_broadcast_schedule(\r\n                m_tensor, a_tensor, b_tensor, output_layout, input_a_layout, input_b_layout, op_name\r\n            )\r\n        elif dtype in [\"uint8\", \"int8\"]:\r\n            args = [\r\n                a_tensor,\r\n                b_tensor,\r\n                output_shape,\r\n                ZERO_POINT_A_VAL,\r\n                SCALE_A_VAL,\r\n                ZERO_POINT_B_VAL,\r\n                SCALE_B_VAL,\r\n                ZERO_POINT_M_VAL,\r\n                SCALE_M_VAL,\r\n                dtype,\r\n            ]\r\n            if op_name == \"add\":\r\n                m_tensor = qn.qadd_broadcast_compute(*args)\r\n            elif op_name == \"subtract\":\r\n                m_tensor = qn.qsubtract_broadcast_compute(*args)\r\n            elif op_name == \"multiply\":\r\n                m_tensor = qn.qmultiply_broadcast_compute(*args)\r\n            tir_schedule = qn.tir_schedule_quant(\r\n                m_tensor, a_tensor, b_tensor, output_layout, input_a_layout, input_b_layout\r\n            )\r\n\r\n        sch = tir_schedule.mod\r\n\r\n        input_axis_separator = [4]\r\n        if output_layout in (\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h8w32c-2d\",\r\n        ):\r\n            output_axis_separator = [4]\r\n        else:\r\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\r\n\r\n        with tvm.transform.PassContext(opt_level=3):\r\n            func = tvm.build(\r\n                sch,\r\n                [a_tensor, b_tensor, m_tensor],\r\n                get_hexagon_target(\"v69\"),\r\n                name=\"slice_op_with_transform\",\r\n            )\r\n\r\n        if dtype == \"float16\":\r\n            in_data_np_a = input_np_a\r\n            in_data_np_b = input_np_b\r\n        elif dtype in [\"int8\", \"uint8\"]:\r\n            in_data_np_a = quantize_input_np_a\r\n            in_data_np_b = quantize_input_np_b\r\n        else:\r\n            raise RuntimeError(f\"Unsupport dtype '{dtype}'\")\r\n\r\n        a_data_nd = hexagon_wrapper_allocation(\r\n            hexagon_session.device,\r\n            layout=input_a_layout,\r\n            data_original=in_data_np_a,\r\n            transformed_data=transformed_input_np_a,\r\n            axis_separators=input_axis_separator,\r\n        )\r\n        b_data_nd = hexagon_wrapper_allocation(\r\n            hexagon_session.device,\r\n            layout=input_b_layout,\r\n            data_original=in_data_np_b,\r\n            transformed_data=transformed_input_np_b,\r\n            axis_separators=input_axis_separator,\r\n        )\r\n        m_data_nd = hexagon_wrapper_allocation(\r\n            hexagon_session.device,\r\n            layout=output_layout,\r\n            tensor_shape=transformed_expected_output_np.shape,\r\n            axis_separators=output_axis_separator,\r\n            dtype=dtype,\r\n        )\r\n\r\n        mod = hexagon_session.load_module(func)\r\n        mod(a_data_nd, b_data_nd, m_data_nd)\r\n\r\n        batch, height, width, channel = output_shape\r\n        # convert nd to np and reshape to fixed chunk size layout\r\n        if output_layout == \"nhwc-8h2w32c2w-2d\":\r\n            m_data_np = m_data_nd.numpy().reshape(\r\n                [batch, height // 8, width // 4, channel // 32, 8, 2, 32, 2]\r\n            )\r\n        elif output_layout == \"nhwc-8h8w32c-2d\":\r\n            m_data_np = m_data_nd.numpy().reshape(\r\n                [batch, height // 8, width // 8, channel // 32, 8, 8, 32]\r\n            )\r\n\r\n        if dtype == \"float16\":\r\n            np.testing.assert_allclose(\r\n                transformed_expected_output_np, m_data_np, rtol=1e-3, atol=1e-3\r\n            )\r\n        elif dtype in [\"int8\", \"uint8\"]:\r\n            np.testing.assert_allclose(transformed_expected_output_np, m_data_np, rtol=1, atol=1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    tvm.testing.main()\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for matmul\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass TestMatMulFloat:\n    \"\"\"Test MatMul Float class.\"\"\"\n\n    x_batch, y_batch, m_size, n_size, k_size = tvm.testing.parameters(\n        (1, 1, 16, 16, 32),\n        (5, 5, 16, 16, 32),\n        (5, 5, 16, 20, 32),\n        (30, 30, 16, 20, 32),\n        # Test batch broadcasting.\n        (1, 5, 16, 16, 32),\n        (5, 1, 16, 16, 32),\n    )\n\n    dtype = tvm.testing.parameter(\n        \"float32\",\n        \"float16\",\n    )\n\n    # TODO(mehrdadh): add dynamic testing\n    @tvm.testing.requires_hexagon\n    def test_batch_matmul(\n        self, hexagon_session: Session, x_batch, y_batch, m_size, n_size, k_size, dtype\n    ):\n        \"\"\"Test batch MatMul.\"\"\"\n        if dtype == \"float16\":\n            pytest.xfail(\"float16 is not supported.\")\n\n        x = te.placeholder((x_batch, m_size, k_size), name=\"x\")\n        y = te.placeholder((y_batch, n_size, k_size), name=\"y\")\n\n        def get_ref_data():\n            a_np = np.random.uniform(size=(x_batch, m_size, k_size)).astype(dtype)\n            b_np = np.random.uniform(size=(y_batch, n_size, k_size)).astype(dtype)\n            c_np = tvm.topi.testing.batch_matmul(a_np, b_np)\n            return (a_np, b_np, c_np)\n\n        # get the test data\n        a_np, b_np, c_np = get_ref_data()\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fcompute = topi.nn.batch_matmul\n            fschedule = topi.hexagon.schedule_batch_matmul\n            out = fcompute(x, y)\n            s = fschedule([out])\n            out_shape = out.shape\n\n        func = tvm.build(\n            s,\n            [x, y, out],\n            get_hexagon_target(\"v68\"),\n            name=\"batch_matmul\",\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(out_shape), dtype=dtype), dev)\n        mod[\"batch_matmul\"](a, b, c)\n\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\nclass TestMatMulInt8:\n    \"\"\"Test MatMul INT8 class.\"\"\"\n\n    x_batch, y_batch, m_size, n_size, k_size = tvm.testing.parameters(\n        (1, 1, 2, 3, 1),\n        (1, 1, 16, 24, 32),\n        (5, 5, 24, 16, 32),\n        (30, 30, 16, 20, 32),\n        (1, 5, 16, 16, 32),\n        (5, 1, 16, 16, 32),\n    )\n\n    dtype = tvm.testing.parameter(\n        \"float32\",\n        \"float16\",\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_batch_matmul_int8(\n        self, hexagon_session: Session, x_batch, y_batch, m_size, n_size, k_size\n    ):\n        \"\"\"Test batch matmul INT8.\"\"\"\n        dtype = \"int8\"\n        out_dtype = \"int8\"\n        assert x_batch == y_batch or x_batch == 1 or y_batch == 1\n        x = te.placeholder((x_batch, m_size, k_size), name=\"x\", dtype=dtype)\n        y = te.placeholder((y_batch, n_size, k_size), name=\"y\", dtype=dtype)\n\n        def get_ref_data():\n            a_np = np.random.randint(low=-128, high=127, size=(x_batch, m_size, k_size)).astype(\n                dtype\n            )\n            b_np = np.random.randint(low=-128, high=127, size=(y_batch, n_size, k_size)).astype(\n                dtype\n            )\n            c_np = tvm.topi.testing.batch_matmul(a_np, b_np, out_dtype=out_dtype)\n            return (a_np, b_np, c_np)\n\n        # get the test data\n        a_np, b_np, c_np = get_ref_data()\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fcompute = topi.nn.batch_matmul\n            fschedule = topi.hexagon.schedule_batch_matmul\n            out = fcompute(x, y)\n            s = fschedule([out])\n\n        func = tvm.build(\n            s,\n            [x, y, out],\n            get_hexagon_target(\"v68\"),\n            name=\"batch_matmul_int8\",\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(out.shape), dtype=out_dtype), dev)\n        mod[\"batch_matmul_int8\"](a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_conv2d_fp16_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test conv2d HVX intrinsic implementation\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.contrib.hexagon\nfrom tvm.topi.testing import conv2d_nhwc_python\n\nfrom ..infrastructure import get_hexagon_target\n\n\ndef build_conv2d(target):\n    \"\"\"Build and the return the conv2d module that calls the intrinsic implementation\"\"\"\n    act_n, act_h, act_w, act_c = (\n        tvm.te.var(\"act_n\"),\n        tvm.te.var(\"act_h\"),\n        tvm.te.var(\"act_w\"),\n        tvm.te.var(\"act_c\"),\n    )\n    filt_h, filt_w, filt_o = tvm.te.var(\"filt_h\"), tvm.te.var(\"fw\"), tvm.te.var(\"filt_o\")\n    off_l, off_t = tvm.te.var(\"off_l\"), tvm.te.var(\"off_t\")\n    stride_h, stride_w = tvm.te.var(\"stride_h\"), tvm.te.var(\"stride_w\")\n\n    act_flat = tvm.te.placeholder(\n        shape=(act_n, act_h, act_w, act_c), dtype=\"float16\", name=\"act_flat\"\n    )\n    wgt_flat = tvm.te.placeholder(\n        shape=(filt_h, filt_w, act_c, filt_o), dtype=\"float16\", name=\"wgt_flat\"\n    )\n\n    out_flat = tvm.te.extern(\n        shape=(act_n, (act_h - filt_h) // stride_h + 1, (act_w - filt_w) // stride_w + 1, filt_o),\n        inputs=[act_flat, wgt_flat],\n        fcompute=lambda ins, outs: tvm.tir.call_cpacked(\n            \"conv2d_packed_fp16\",  # Function from TVM runtime\n            ins[0],\n            ins[1],\n            off_t,\n            off_l,\n            stride_h,\n            stride_w,\n            outs[0],\n            tvm.runtime.const(0),  # resource_handle (unused)\n        ),\n        dtype=\"float16\",\n    )\n\n    s = tvm.te.create_schedule(out_flat.op)\n\n    func_name = \"extern_conv\"\n    with tvm.transform.PassContext(opt_level=3):\n        module = tvm.build(\n            s,\n            [act_flat, wgt_flat, off_t, off_l, stride_h, stride_w, out_flat],\n            target=target,\n            name=func_name,\n        )\n\n    return module\n\n\ndef gen_config(params):\n    \"\"\"Utility function to generate useful ids for shape_parameters\"\"\"\n\n    dims = lambda vals: \"x\".join(map(str, vals))\n\n    config = {}\n    for param in params:\n        act_shape, wgt_shape, inp_stride = param\n        name = f\"nhwc{dims(act_shape)}-hwio{dims(wgt_shape)}-stride{dims(inp_stride)}\"\n        config[name] = param\n\n    return config\n\n\nclass TestConv2dIntrin:\n    \"\"\"Test Conv2d Intrin class\"\"\"\n\n    shape_parameters = [\n        (\n            (1, 8, 4, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 10, 14, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 14, 6, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 14, 6, 3),\n            (3, 3, 3, 64),\n            (1, 1),\n        ),\n        (\n            (1, 14, 6, 3),\n            (5, 5, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 8, 8, 3),\n            (2, 2, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 14, 6, 64),\n            (3, 3, 64, 3),\n            (1, 1),\n        ),\n        (\n            (1, 4, 4, 40),\n            (3, 3, 40, 3),\n            (1, 1),\n        ),\n        (\n            (1, 4, 4, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 5, 5, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 6, 6, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 7, 7, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 8, 8, 3),\n            (3, 3, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 8, 8, 3),\n            (5, 5, 3, 3),\n            (1, 1),\n        ),\n        (\n            (1, 8, 8, 64),\n            (2, 2, 64, 64),\n            (1, 1),\n        ),\n        (\n            (1, 8, 4, 3),\n            (3, 3, 3, 3),\n            (2, 2),\n        ),\n        (\n            (1, 14, 6, 3),\n            (3, 3, 3, 64),\n            (2, 2),\n        ),\n        (\n            (1, 14, 6, 3),\n            (5, 5, 3, 3),\n            (2, 2),\n        ),\n        (\n            (1, 8, 8, 3),\n            (2, 2, 3, 3),\n            (2, 2),\n        ),\n    ]\n\n    config = gen_config(shape_parameters)\n    act_shape, wgt_shape, inp_stride = tvm.testing.parameters(*config.values(), ids=config.keys())\n    inp_offset = tvm.testing.parameter((0, 0), ids=[\"offset0x0\"])\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d(self, act_shape, wgt_shape, inp_stride, inp_offset, hexagon_session):\n        \"\"\"Test conv2d intrinsic implementation\"\"\"\n        assert act_shape[3] == wgt_shape[2]\n\n        # Currently, input offset does not affect the output shape\n        def get_out_shape(ash, wsh, inp_stride):\n            assert ash[3] == wsh[2]\n            osh = (\n                ash[0],\n                (ash[1] - wsh[0]) // inp_stride[0] + 1,\n                (ash[2] - wsh[1]) // inp_stride[1] + 1,\n                wsh[3],\n            )\n            assert tvm.tir.all([x > 0 for x in osh])\n            return osh\n\n        act = np.random.rand(*act_shape).astype(\"float16\")\n        wgt = np.random.rand(*wgt_shape).astype(\"float16\")\n\n        module = build_conv2d(get_hexagon_target(\"v68\"))\n\n        mod = hexagon_session.load_module(module)\n        output = tvm.nd.array(\n            np.zeros(get_out_shape(act_shape, wgt_shape, inp_stride), dtype=\"float16\"),\n            device=hexagon_session.device,\n        )\n        mod(\n            tvm.nd.array(act, device=hexagon_session.device),\n            tvm.nd.array(wgt, device=hexagon_session.device),\n            inp_offset[0],  # off_t\n            inp_offset[1],  # off_l\n            inp_stride[0],  # stride_height\n            inp_stride[1],  # stride_width\n            output,\n        )\n\n        out = output.numpy()\n\n        # Generate reference output and compare:\n        ref_out = conv2d_nhwc_python(\n            act.astype(\"float32\"), wgt.astype(\"float32\"), stride=inp_stride, padding=\"VALID\"\n        ).astype(\"float16\")\n\n        tvm.testing.assert_allclose(out, ref_out, rtol=5e-2, atol=5e-2)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_conv2d_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for convolution.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass BaseConv2DTests:\n    \"\"\"Conv2D test class.\"\"\"\n\n    add_bias = tvm.testing.parameter(False)\n    apply_relu = tvm.testing.parameter(False)\n    dilation = tvm.testing.parameter(1)\n    batch = tvm.testing.parameter(1)\n    dtype = tvm.testing.parameter(\"float32\")\n\n    random_seed = tvm.testing.parameter(0)\n\n    @tvm.testing.fixture\n    def input_shape(self, batch, in_channel, in_size):\n        return (batch, in_channel, in_size, in_size)\n\n    @tvm.testing.fixture\n    def weight_shape(self, num_filter, in_channel, kernel):\n        return (num_filter, in_channel, kernel, kernel)\n\n    @tvm.testing.fixture\n    def bias_shape(self, num_filter):\n        return (num_filter, 1, 1)\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(\n        self,\n        random_seed,\n        input_shape,\n        weight_shape,\n        bias_shape,\n        dtype,\n        stride,\n        padding,\n        dilation,\n        add_bias,\n        apply_relu,\n    ):\n        \"\"\"Generate reference data.\"\"\"\n        np.random.seed(random_seed)\n\n        # scipy.signal.convolve2d does not support float16 data types, and\n        # the python fallback is too slow for general use.  Computing\n        # ref_data in float32 will have fewer rounding errors than the TVM\n        # float16 compute, but those vary based on schedule anyways.\n        conv_dtype = \"float32\" if dtype == \"float16\" else dtype\n\n        a_np = np.random.uniform(size=input_shape).astype(dtype)\n        w_np = np.random.uniform(size=weight_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(\n            a_np.astype(conv_dtype), dw_np.astype(conv_dtype), stride, padding\n        ).astype(dtype)\n\n        if add_bias:\n            c_np = c_np + b_np\n        if apply_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d_nchw(\n        self,\n        hexagon_session: Session,\n        batch,\n        in_channel,\n        in_size,\n        num_filter,\n        kernel,\n        stride,\n        padding,\n        dtype,\n        ref_data,\n        dilation,\n        add_bias,\n        apply_relu,\n    ):\n        \"\"\"Test Conv2d NCHW.\"\"\"\n\n        pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n        padding_sum = pad_top + pad_left + pad_bottom + pad_right\n\n        a_np, w_np, b_np, c_np = ref_data\n\n        a_tensor = te.placeholder(a_np.shape, name=\"a_tensor\", dtype=dtype)\n        w_tensor = te.placeholder(w_np.shape, name=\"w_tensor\", dtype=dtype)\n        bias = te.placeholder(b_np.shape, name=\"bias\", dtype=dtype)\n\n        if \"int\" in dtype:\n            tol = {\"atol\": 0, \"rtol\": 0}\n        elif dtype == \"float32\":\n            tol = {\"rtol\": 1e-4, \"atol\": 2e-4}\n        elif dtype == \"float16\":\n            # a_tensor summation in float16 with a single accumulator very\n            # quickly runs into large rounding errors.  At some point,\n            # this tolerance should be schedule-dependent for to avoid\n            # false negatives.\n            num_values_summed = in_channel * kernel * kernel\n            gap_size = np.nextafter(c_np.max(), np.inf, dtype=c_np.dtype) - c_np.max()\n            tol = {\"rtol\": 1e-3, \"atol\": num_values_summed * gap_size / 2}\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fcompute = topi.nn.conv2d_nchw\n            fschedule = topi.hexagon.schedule_conv2d_nchw\n            c_tensor = fcompute(\n                a_tensor, w_tensor, (stride, stride), padding, (dilation, dilation), dtype\n            )\n            if add_bias:\n                c_tensor = topi.add(c_tensor, bias)\n            if apply_relu:\n                c_tensor = topi.nn.relu(c_tensor)\n            s = fschedule([c_tensor])\n\n        func_name = \"conv2d_{}_{}_{}_{}_{}_{}_{}_{}_{}\".format(\n            dtype,\n            batch,\n            in_channel,\n            in_size,\n            num_filter,\n            kernel,\n            stride,\n            padding_sum,\n            dilation,\n        )\n        func = tvm.build(\n            s,\n            [a_tensor, w_tensor, bias, c_tensor],\n            get_hexagon_target(\"v68\"),\n            name=func_name,\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a_data = tvm.nd.array(a_np, dev)\n        weight = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n\n        c = tvm.nd.array(np.zeros(get_const_tuple(c_tensor.shape), dtype=c_tensor.dtype), dev)\n        mod[func_name](a_data, weight, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, **tol)\n\n\nclass TestBatchSize(BaseConv2DTests):\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (32, 28, 32, 3, 1, 1),\n    )\n    batch = tvm.testing.parameter(1, 4, 9)\n\n\nclass TestBiasRelu(BaseConv2DTests):\n    apply_relu = tvm.testing.parameter(True, False, ids=[\"relu\", \"no_relu\"])\n    add_bias = tvm.testing.parameter(True, False, ids=[\"bias\", \"no_bias\"])\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (64, 56, 64, 3, 1, 1),\n        (64, 8, 64, 3, 1, (1, 2, 2, 1)),\n        (64, 8, 64, 5, 2, (1, 3)),\n        (64, 8, 64, 3, 1, \"VALID\"),\n        (32, 8, 32, 24, 1, \"SAME\"),\n    )\n\n\nclass TestResNet18Workloads(BaseConv2DTests):\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (3, 224, 64, 7, 2, 3),\n        (64, 56, 64, 3, 1, 1),\n        (64, 56, 64, 1, 1, 0),\n        (64, 56, 32, 3, 2, 1),\n        (64, 56, 32, 1, 2, 0),\n        (64, 28, 32, 3, 1, 1),\n    )\n\n\nclass TestMobilenet(BaseConv2DTests):\n    batch, in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (1, 32, 112, 32, 3, 1, 1),\n    )\n\n\nclass TestWeirdWorkloads(BaseConv2DTests):\n    batch, in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (2, 2, 2, 2, 2, 2, 2),\n        (3, 3, 3, 3, 3, 3, 3),\n        (4, 4, 4, 4, 4, 4, 4),\n        (5, 5, 5, 5, 5, 5, 5),\n        (6, 6, 6, 6, 6, 6, 6),\n        (1, 1, 1, 1, 1, 1, 1),\n        (2, 13, 71, 59, 3, 1, 1),\n    )\n\n\nclass TestAsymmetricPadding(BaseConv2DTests):\n    dilation = tvm.testing.parameter(1, 2)\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (3, 35, 64, 7, 2, (0, 0, 1, 1)),\n        (64, 8, 128, 3, 1, (3, 3, 2, 2)),\n        (64, 8, 64, 1, 1, (1, 2, 2, 1)),\n        (64, 17, 48, 1, 1, (1, 2)),\n        (64, 8, 64, 3, 1, (3, 1)),\n        (128, 8, 96, 3, 1, (0, 2)),\n        (64, 35, 64, 3, 1, (1, 2)),\n        (64, 8, 64, 1, 1, \"VALID\"),\n        (388, 8, 64, 3, 1, \"VALID\"),\n        (64, 10, 48, 3, 1, \"VALID\"),\n        (64, 19, 64, 1, 1, \"SAME\"),\n        (64, 5, 32, 2, 1, \"SAME\"),\n        (32, 8, 32, 3, 1, \"SAME\"),\n        (64, 8, 64, 3, 1, (1, 2, 2, 1)),\n        (64, 8, 64, 5, 2, (1, 3)),\n        (64, 8, 64, 3, 1, \"VALID\"),\n        (32, 8, 32, 24, 1, \"SAME\"),\n        (32, 35, 64, 7, 2, (0, 0, 2, 2)),\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_conv2d_nhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for convolution.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass BaseConv2DTests:\n    \"\"\"Test Conv2D base class.\"\"\"\n\n    dtype = tvm.testing.parameter(\"float32\")\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(\n        self, dtype, batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation\n    ):\n        \"\"\"Generate reference data.\"\"\"\n        in_height = in_width = in_size\n        a_shape = (batch, in_height, in_width, in_channel)\n        w_shape = (kernel, kernel, in_channel, num_filter)\n\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        return a_np, w_np, b_np\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d_nhwc(\n        self,\n        hexagon_session: Session,\n        ref_data,\n        batch,\n        in_channel,\n        in_size,\n        num_filter,\n        kernel,\n        dtype,\n        stride,\n        padding,\n        dilation,\n    ):\n        \"\"\"Test Conv2D NHWC.\"\"\"\n        a_np, w_np, b_np = ref_data\n\n        a_tensor = te.placeholder(a_np.shape, name=\"a_tensor\", dtype=dtype)\n        w_tensor = te.placeholder(w_np.shape, name=\"w_tensor\", dtype=dtype)\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fcompute = topi.nn.conv2d_nhwc\n            fschedule = topi.hexagon.schedule_conv2d_nhwc\n            b_tensor = fcompute(a_tensor, w_tensor, stride, padding, dilation, dtype)\n            s = fschedule([b_tensor])\n\n        func_name = \"conv2d_{}_{}_{}_{}_{}_{}_{}_{}_{}\".format(\n            dtype,\n            batch,\n            in_channel,\n            in_size,\n            num_filter,\n            kernel,\n            stride,\n            padding,\n            dilation,\n        )\n        func = tvm.build(\n            s, [a_tensor, w_tensor, b_tensor], get_hexagon_target(\"v68\"), name=func_name\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a_data = tvm.nd.array(a_np, dev)\n        weight = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(b_tensor.shape), dtype=b_tensor.dtype), dev)\n\n        mod[func_name](a_data, weight, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nclass TestConv2dNHWC(BaseConv2DTests):\n    (\n        batch,\n        in_channel,\n        in_size,\n        num_filter,\n        kernel,\n        stride,\n        padding,\n        dilation,\n    ) = tvm.testing.parameters(\n        (1, 64, 32, 64, 3, 1, \"SAME\", 1),\n        (4, 32, 16, 32, 5, 2, \"SAME\", 1),\n        (1, 64, 32, 64, 3, 1, \"VALID\", 1),\n        (4, 32, 16, 32, 5, 2, \"VALID\", 1),\n        (1, 32, 16, 64, 3, 2, (0, 0, 1, 1), 1),\n        (1, 32, 16, 64, 3, 2, (1, 1, 2, 2), 1),\n        (1, 32, 16, 32, 5, 2, (3, 3, 2, 2), 1),\n        (1, 32, 16, 64, 3, 2, (0, 1, 2, 3), 1),\n        (1, 64, 32, 64, 3, 1, \"SAME\", 2),\n        (1, 64, 32, 64, 3, 1, (1, 1, 2, 2), 2),\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for transposed convolution.\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n# TODO Should add kernal to tvm.testing.fixture\n\n\nclass BaseConv2DTransposeTests:\n    \"\"\"Conv2D transpose base class.\"\"\"\n\n    random_seed = tvm.testing.parameter(0)\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d(\n        self,\n        hexagon_session: Session,\n        batch,\n        in_channel,\n        in_size,\n        num_filter,\n        stride,\n        padding,\n        output_padding,\n        random_seed,\n    ):\n        \"\"\"Test conv2D.\"\"\"\n        in_height, in_width = in_size\n        kernel_height, kernel_width = (1, 1)\n        stride_height, stride_width = stride\n        pad_top, pad_left, pad_bottom, pad_right = padding\n\n        a_tensor = te.placeholder((batch, in_channel, in_height, in_width), name=\"a_tensor\")\n        w_tensor = te.placeholder(\n            (in_channel, num_filter, kernel_height, kernel_width), name=\"w_tensor\"\n        )\n\n        a_shape = get_const_tuple(a_tensor.shape)\n        w_shape = get_const_tuple(w_tensor.shape)\n        dtype = a_tensor.dtype\n\n        def get_ref_data():\n\n            np.random.seed(random_seed)\n            a_np = np.random.uniform(size=a_shape).astype(dtype)\n            w_np = np.random.uniform(size=w_shape).astype(dtype)\n            b_np = tvm.topi.testing.conv2d_transpose_nchw_python(\n                a_np, w_np, stride, padding, output_padding\n            )\n            c_np = np.maximum(b_np, 0)\n            return a_np, w_np, b_np, c_np\n\n        a_np, w_np, b_np, c_np = get_ref_data()\n\n        fcompute_args = (\n            a_tensor,\n            w_tensor,\n            [stride_height, stride_width],\n            [pad_top, pad_left, pad_bottom, pad_right],\n            a_tensor.dtype,\n            output_padding,\n        )\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fcompute = topi.nn.conv2d_transpose_nchw\n            fschedule = topi.hexagon.schedule_conv2d_transpose_nchw\n            b_tensor = fcompute(*fcompute_args)\n            c_tensor = topi.nn.relu(b_tensor)\n            schedule_1 = fschedule([b_tensor])\n            schedule_2 = fschedule([c_tensor])\n\n            dev = hexagon_session.device\n\n            a_data = tvm.nd.array(a_np, dev)\n            weight = tvm.nd.array(w_np, dev)\n            b = tvm.nd.array(np.zeros(get_const_tuple(b_tensor.shape), dtype=b_tensor.dtype), dev)\n            c = tvm.nd.array(np.zeros(get_const_tuple(c_tensor.shape), dtype=c_tensor.dtype), dev)\n\n            func1 = tvm.build(schedule_1, [a_tensor, w_tensor, b_tensor], get_hexagon_target(\"v68\"))\n            func2 = tvm.build(schedule_2, [a_tensor, w_tensor, c_tensor], get_hexagon_target(\"v68\"))\n\n            mod1 = hexagon_session.load_module(func1)\n            mod2 = hexagon_session.load_module(func2)\n\n            mod1(a_data, weight, b)\n            mod2(a_data, weight, c)\n            tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n            tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\nclass TestConv2DTranspose(BaseConv2DTransposeTests):\n    \"\"\"Test Conv2D transpose class.\"\"\"\n\n    (batch, in_channel, in_size, num_filter, stride) = tvm.testing.parameters(\n        (1, 3, (224, 224), 1, (1, 1)),\n        (1, 8, (224, 224), 1, (1, 1)),\n        (1, 512, (8, 1), 128, (31, 1)),\n        (1, 32, (8192, 1), 1, (1, 1)),\n    )\n\n    padding = tvm.testing.parameter((0, 0, 0, 0))\n    output_padding = tvm.testing.parameter((0, 0))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for dense\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass TestDense:\n    \"\"\"Dense test class.\"\"\"\n\n    random_seed = tvm.testing.parameter(0)\n\n    use_bias = tvm.testing.parameter(True, False)\n\n    # batch_size more than 8 would break\n    batch_size = tvm.testing.parameter(1, 2, 8)\n\n    in_dim, out_dim = tvm.testing.parameters((1024, 1000))\n\n    in_dtype, out_dtype = tvm.testing.parameters(\n        (\"float32\", \"float32\"),\n        (\"float16\", \"float32\"),\n        (\"int8\", \"int32\"),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def dense_ref_data(\n        self, random_seed, batch_size, in_dim, out_dim, use_bias, in_dtype, out_dtype\n    ):\n        \"\"\"Generate reference data.\"\"\"\n        np.random.seed(random_seed)\n\n        if \"float\" in in_dtype:\n            a_np = np.random.uniform(size=(batch_size, in_dim)).astype(in_dtype)\n            b_np = np.random.uniform(size=(out_dim, in_dim)).astype(in_dtype)\n            c_np = np.random.uniform(size=(out_dim,)).astype(out_dtype)\n        elif in_dtype == \"int8\":\n            a_np = np.random.randint(low=-128, high=127, size=(batch_size, in_dim)).astype(in_dtype)\n            b_np = np.random.randint(low=-128, high=127, size=(out_dim, in_dim)).astype(in_dtype)\n            c_np = np.random.randint(low=-128, high=127, size=(out_dim,)).astype(out_dtype)\n        else:\n            raise ValueError(\"No method to generate test data for data type '{}'\".format(in_dtype))\n\n        matmul = np.dot(a_np.astype(out_dtype), b_np.T.astype(out_dtype))\n\n        if use_bias:\n            matmul += c_np\n\n        d_np = np.maximum(matmul, 0)\n        return (a_np, b_np, c_np, d_np)\n\n    @tvm.testing.requires_hexagon\n    def test_dense(\n        self,\n        hexagon_session: Session,\n        batch_size,\n        in_dim,\n        out_dim,\n        use_bias,\n        in_dtype,\n        out_dtype,\n        dense_ref_data,\n    ):\n        \"\"\"Test dense.\"\"\"\n        if in_dtype == \"float16\":\n            pytest.xfail(\"float16 is not supported.\")\n\n        if \"int\" in in_dtype:\n            tol = {\"atol\": 0, \"rtol\": 0}\n        elif in_dtype == \"float32\":\n            tol = {\"rtol\": 1e-5, \"atol\": 1e-5}\n\n        a_tensor = te.placeholder((batch_size, in_dim), name=\"a_tensor\", dtype=in_dtype)\n        b_tensor = te.placeholder((out_dim, in_dim), name=\"b_tensor\", dtype=in_dtype)\n        c_tensor = te.placeholder((out_dim,), name=\"c_tensor\", dtype=out_dtype)\n\n        a_np, b_np, c_np, d_np = dense_ref_data\n\n        fcompute = topi.nn.dense\n        fschedule = topi.hexagon.schedule_dense\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            d_tensor = fcompute(a_tensor, b_tensor, c_tensor if use_bias else None, out_dtype)\n            d_tensor = topi.nn.relu(d_tensor)\n            schedule = fschedule([d_tensor])\n\n        func = tvm.build(\n            schedule,\n            [a_tensor, b_tensor, c_tensor, d_tensor],\n            get_hexagon_target(\"v68\"),\n            name=\"dense\",\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a_data = tvm.nd.array(a_np, dev)\n        b_data = tvm.nd.array(b_np, dev)\n        c_data = tvm.nd.array(c_np, dev)\n        d_data = tvm.nd.array(np.zeros(get_const_tuple(d_tensor.shape), dtype=out_dtype), dev)\n        mod[\"dense\"](a_data, b_data, c_data, d_data)\n        tvm.testing.assert_allclose(d_data.numpy(), d_np, **tol)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long, redefined-outer-name\n\n\"\"\"Test depth_to_space slice op for hexagon\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nimport tvm.testing\nfrom tvm.topi.hexagon.slice_ops.depth_to_space import d2s_compute, d2s_schedule\nfrom tvm.topi.testing import depth_to_space_python\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ..infrastructure import transform_numpy, get_hexagon_target\n\n\nclass TestD2SSlice:\n    \"\"\"Test class that defines the Depth to Space slice test\"\"\"\n\n    d2s_fp16_tests = (\n        ((1, 8, 8, 256), 2, \"CDR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 8, 8, 1024), 4, \"CDR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 16, 16, 256), 2, \"CDR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 16, 16, 1024), 4, \"CDR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 8, 8, 256), 2, \"DCR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 8, 8, 1024), 4, \"DCR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 16, 16, 256), 2, \"DCR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n        ((1, 16, 16, 1024), 4, \"DCR\", \"float16\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\"),\n    )\n\n    d2s_uint8_tests = (\n        ((1, 8, 8, 256), 2, \"CDR\", \"uint8\", \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\"),\n        ((1, 8, 8, 1024), 4, \"CDR\", \"uint8\", \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\"),\n        ((1, 8, 8, 256), 2, \"DCR\", \"uint8\", \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\"),\n        ((1, 8, 8, 1024), 4, \"DCR\", \"uint8\", \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\"),\n    )\n\n    (input_shape, block_size, mode, dtype, input_layout, output_layout,) = tvm.testing.parameters(\n        *d2s_fp16_tests,\n        *d2s_uint8_tests,\n    )\n\n    working_scope = tvm.testing.parameter(\"global.vtcm\")\n\n    @tvm.testing.fixture\n    def input_np(self, input_shape, dtype):\n        return np.random.uniform(size=input_shape).astype(dtype)\n\n    @tvm.testing.fixture\n    def transformed_input_np(self, input_np, input_layout):\n        return transform_numpy(input_np, \"nhwc\", input_layout)\n\n    @tvm.testing.fixture\n    def ref_output_np(self, input_np, block_size, mode):\n        a_np = np.transpose(input_np, axes=[0, 3, 1, 2])\n        ref_np = depth_to_space_python(a_np, block_size, mode=mode)\n        ref_np = np.transpose(ref_np, axes=[0, 2, 3, 1])\n        return ref_np\n\n    @tvm.testing.fixture\n    def transformed_ref_output_np(self, ref_output_np, output_layout):\n        return transform_numpy(ref_output_np, \"nhwc\", output_layout)\n\n    @tvm.testing.requires_hexagon\n    def test_d2s_slice(\n        self,\n        input_shape,\n        block_size,\n        mode,\n        dtype,\n        input_layout,\n        output_layout,\n        hexagon_session,\n        working_scope,\n        transformed_input_np,\n        transformed_ref_output_np,\n    ):\n        \"\"\"Top level testing function for depth to space\"\"\"\n        input_tensor = te.placeholder(input_shape, name=\"input_tensor\", dtype=dtype)\n\n        output = d2s_compute(input_tensor, block_size, \"NHWC\", mode)\n\n        tir_s = d2s_schedule(input_tensor, output, input_layout, output_layout)\n\n        input_data = allocate_hexagon_array(\n            hexagon_session.device,\n            data=transformed_input_np,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n        output_data = allocate_hexagon_array(\n            hexagon_session.device,\n            tensor_shape=transformed_ref_output_np.shape,\n            dtype=transformed_ref_output_np.dtype,\n            axis_separators=[4],\n            mem_scope=working_scope,\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            runtime_module = tvm.build(\n                tir_s.mod,\n                [input_tensor, output],\n                target=get_hexagon_target(\"v69\"),\n                name=\"depth_to_space\",\n            )\n        mod = hexagon_session.load_module(runtime_module)\n\n        mod(input_data, output_data)\n        output_np = output_data.numpy()\n\n        tvm.testing.assert_allclose(\n            output_np,\n            transformed_ref_output_np,\n            1e-3,\n            1e-3,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Depthwise Conv2D Tests.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass BaseDepthwiseConv2D:\n    \"\"\"Provides the test_conv2d test function, to be used by other test classes.\n\n    Test parameter sets are split out into different classes for\n    readability (e.g. used for mobilenet), and for restrictions\n    (e.g. implemented only for llvm).\n    \"\"\"\n\n    random_seed = tvm.testing.parameter(0)\n\n    in_dtype, out_dtype = tvm.testing.parameters(\n        (\"float32\", \"float32\"),\n    )\n\n    @tvm.testing.fixture\n    def input_shape(self, layout, batch, in_channel, in_size, filter_shape):\n        \"\"\"Returns input shape.\"\"\"\n        if layout == \"NCHW\":\n            return (batch, in_channel, in_size, in_size)\n        elif layout == \"NHWC\":\n            return (batch, in_size, in_size, in_channel)\n        elif layout == \"NCHWc\":\n            oc_block = filter_shape[-1]\n            ic_block = next(bn for bn in range(oc_block, 0, -1) if in_channel % bn == 0)\n            return (batch, in_channel // ic_block, in_size, in_size, ic_block)\n        else:\n            raise RuntimeError(f\"Not supported layout {layout}\")\n\n    @tvm.testing.fixture\n    def filter_shape(self, layout, in_channel, channel_multiplier, kernel):\n        \"\"\"Returns filter shape.\"\"\"\n        filter_channel = in_channel\n        if layout == \"NCHW\":\n            return (filter_channel, channel_multiplier, kernel, kernel)\n        elif layout == \"NHWC\":\n            return (kernel, kernel, filter_channel, channel_multiplier)\n        elif layout == \"NCHWc\":\n            out_channel = in_channel * channel_multiplier\n            # For testing the functionality, we choose an arbitrary block\n            # size that can divide out_channel, regardless of the\n            # performance.\n            oc_block = next(bn for bn in range(16, 0, -1) if out_channel % bn == 0)\n            return (out_channel // oc_block, 1, kernel, kernel, 1, oc_block)\n        else:\n            raise RuntimeError(f\"Not supported layout {layout}\")\n\n    @tvm.testing.fixture\n    def scale_shape(self, layout, in_channel, channel_multiplier, filter_shape):\n        \"\"\"Returns scale shape.\"\"\"\n        out_channel = in_channel * channel_multiplier\n\n        if layout in (\"NCHW\", \"NHWC\"):\n            return (out_channel,)\n\n        if layout == \"NCHWc\":\n            oc_block = filter_shape[-1]\n            return (out_channel // oc_block, oc_block)\n\n        raise ValueError(\"Unknown layout {}\".format(layout))\n\n    @tvm.testing.fixture\n    def shift_shape(self, scale_shape):\n        \"\"\"Returns shift shape.\"\"\"\n        return scale_shape\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(\n        self,\n        random_seed,\n        in_dtype,\n        out_dtype,\n        layout,\n        input_shape,\n        filter_shape,\n        dilation,\n        stride,\n        padding,\n        scale_shape,\n        shift_shape,\n        use_scale_shift,\n        apply_relu,\n    ):\n        \"\"\"Generate reference data.\"\"\"\n        np.random.seed(random_seed)\n\n        # scipy.signal.convolve2d does not support float16 data types, and\n        # the python fallback is too slow for general use.  Computing\n        # ref_data in float32 will have fewer rounding errors than the TVM\n        # float16 compute, but those vary based on schedule anyways.\n        conv_dtype = \"float32\" if in_dtype == \"float16\" else in_dtype\n\n        input_np = np.random.uniform(size=input_shape).astype(in_dtype)\n        filter_np = np.random.uniform(size=filter_shape).astype(in_dtype)\n        scale_np = np.random.uniform(size=scale_shape).astype(out_dtype)\n        shift_np = np.random.uniform(size=shift_shape).astype(out_dtype)\n        if layout == \"NCHW\":\n            np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nchw\n            dilation = (1, 1, dilation, dilation)\n            reshape = (1, -1, 1, 1)\n        elif layout == \"NHWC\":\n            np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nhwc\n            dilation = (dilation, dilation, 1, 1)\n            reshape = (1, 1, 1, -1)\n        elif layout == \"NCHWc\":\n            np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nchwc\n            dilation = (1, 1, dilation, dilation, 1, 1)\n            reshape = (1, scale_shape[0], 1, 1, scale_shape[1])\n\n        dilated_filter_np = tvm.topi.testing.dilate_python(filter_np, dilation)\n        output_np = np_depthwise_conv2d(\n            input_np.astype(conv_dtype), dilated_filter_np.astype(conv_dtype), stride, padding\n        ).astype(out_dtype)\n\n        if use_scale_shift:\n            output_np = output_np * scale_np.reshape(reshape) + shift_np.reshape(reshape)\n        if apply_relu:\n            output_np = np.maximum(output_np, 0)\n\n        return (\n            input_np,\n            filter_np,\n            scale_np,\n            shift_np,\n            output_np,\n        )\n\n    @tvm.testing.requires_hexagon\n    def test_conv2d(\n        self,\n        hexagon_session: Session,\n        in_dtype,\n        out_dtype,\n        layout,\n        input_shape,\n        filter_shape,\n        scale_shape,\n        shift_shape,\n        use_scale_shift,\n        apply_relu,\n        kernel,\n        stride,\n        padding,\n        dilation,\n        ref_data,\n    ):\n        \"\"\"Test conv2D.\"\"\"\n        # Transform the padding argument from 'str' to 'tuple' to\n        # match the \"workload\" tuple in TopHub.  Which padding_args to\n        # use for each layout chosen to reproduce previous behavior.\n        if dilation == 1:\n            padding_args = get_pad_tuple(padding, (kernel, kernel))\n            padding_args_i = [0, 1, 2, 3] if layout == \"NCHW\" else [0, 1]\n            padding_args = [padding_args[i] for i in padding_args_i]\n        else:\n            padding_args = padding\n\n        # placeholder\n        input_tensor = te.placeholder(input_shape, name=\"input_tensor\", dtype=in_dtype)\n        filter_tensor = te.placeholder(filter_shape, name=\"filter_tensor\", dtype=in_dtype)\n        scale = te.placeholder(scale_shape, name=\"scale\", dtype=out_dtype)\n        shift = te.placeholder(shift_shape, name=\"shift\", dtype=out_dtype)\n\n        if layout == \"NCHW\":\n            topi_scale_shift = topi.nn.scale_shift_nchw\n            fcompute_args = (input_tensor, filter_tensor, stride, padding_args, dilation, out_dtype)\n\n        elif layout == \"NHWC\":\n            topi_scale_shift = topi.nn.scale_shift_nhwc\n            fcompute_args = (input_tensor, filter_tensor, stride, padding_args, dilation, out_dtype)\n\n        elif layout == \"NCHWc\":\n            topi_scale_shift = topi.nn.scale_shift_nchwc\n            in_layout = \"NCHW{}c\".format(input_shape[-1])\n            out_layout = \"NCHW{}c\".format(filter_shape[-1])\n            fcompute_args = (\n                input_tensor,\n                filter_tensor,\n                stride,\n                padding,\n                dilation,\n                in_layout,\n                out_layout,\n                out_dtype,\n            )\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            # Declare, build schedule\n            if layout == \"NCHW\":\n                fcompute = topi.nn.depthwise_conv2d_nchw\n                fschedule = topi.hexagon.schedule_depthwise_conv2d_nchw\n            elif layout == \"NHWC\":\n                fcompute = topi.nn.depthwise_conv2d_nhwc\n                fschedule = topi.hexagon.schedule_depthwise_conv2d_nhwc\n            c_tensor = fcompute(*fcompute_args)\n            if use_scale_shift:\n                c_tensor = topi_scale_shift(c_tensor, scale, shift)\n            if apply_relu:\n                c_tensor = topi.nn.relu(c_tensor)\n\n            schedule = fschedule([c_tensor])\n\n            # Build and run\n            f = tvm.build(\n                schedule,\n                [input_tensor, filter_tensor, scale, shift, c_tensor],\n                get_hexagon_target(\"v68\"),\n            )\n            mod = hexagon_session.load_module(f)\n\n            input_np, filter_np, scale_np, shift_np, output_np = ref_data\n\n            dev = hexagon_session.device\n            input_tvm = tvm.nd.array(input_np, dev)\n            filter_tvm = tvm.nd.array(filter_np, dev)\n            scale_tvm = tvm.nd.array(scale_np, dev)\n            shift_tvm = tvm.nd.array(shift_np, dev)\n            output_tvm = tvm.nd.array(\n                np.zeros(shape=get_const_tuple(c_tensor.shape), dtype=c_tensor.dtype),\n                dev,\n            )\n\n            mod(input_tvm, filter_tvm, scale_tvm, shift_tvm, output_tvm)\n\n            tol = {\"rtol\": 1e-4, \"atol\": 1e-5}\n            tvm.testing.assert_allclose(output_np, output_tvm.numpy(), **tol)\n\n\nclass TestDepthwiseConv2DMobilenetWorkloads(BaseDepthwiseConv2D):\n    \"\"\"Extra tests to verify functionality for workloads used by mobilenet.\"\"\"\n\n    layout = tvm.testing.parameter(\"NCHW\", \"NHWC\")\n    use_scale_shift = tvm.testing.parameter(False, ids=[\"no_scale_shift\"])\n    apply_relu = tvm.testing.parameter(False, ids=[\"no_relu\"])\n\n    batch = tvm.testing.parameter(1)\n    channel_multiplier = tvm.testing.parameter(1)\n    kernel = tvm.testing.parameter(3)\n    padding = tvm.testing.parameter(\"SAME\")\n    dilation = tvm.testing.parameter(1)\n\n    in_channel, in_size, stride = tvm.testing.parameters(\n        (32, 112, 1),\n        (64, 112, 2),\n        (128, 56, 1),\n        (128, 56, 2),\n        (256, 28, 1),\n    )\n\n\nclass TestDepthwiseConv2D(BaseDepthwiseConv2D):\n    \"\"\"Test depthwise conv2D class.\"\"\"\n\n    layout = tvm.testing.parameter(\"NCHW\", \"NHWC\")\n    use_scale_shift = tvm.testing.parameter(True, False, ids=[\"with_scale_shift\", \"no_scale_shift\"])\n    apply_relu = tvm.testing.parameter(True, False, ids=[\"with_relu\", \"no_relu\"])\n\n    (batch, in_channel, in_size, channel_multiplier, kernel, stride) = tvm.testing.parameters(\n        (1, 64, 32, 1, 3, 1),\n        (1, 128, 64, 2, 5, 2),\n    )\n    padding = tvm.testing.parameter(\"VALID\")\n    dilation = tvm.testing.parameter(1)\n\n\n# TODO(hexagon-team): add TestDepthwiseConv2D_NCHWc test.\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_pad.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for reduce\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm import te, topi\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\n@tvm.testing.requires_hexagon\ndef test_nn_pad(hexagon_session: Session):\n    \"\"\"Test nn pad.\"\"\"\n    dtype = \"uint8\"\n    in_shape = (1, 56, 56, 32)\n\n    data_in = np.ones(in_shape).astype(dtype)\n\n    a_tensor = te.placeholder(shape=in_shape, name=\"a_tensor\", dtype=dtype)\n\n    c_tensor = topi.nn.pad(a_tensor, [0, 1, 1, 0], [0, 1, 1, 0], pad_value=0)\n\n    with tvm.target.Target(get_hexagon_target(\"v68\")):\n        fschedule = topi.hexagon.schedule_pad\n        s = fschedule(c_tensor)\n\n    func = tvm.build(s, [a_tensor, c_tensor], get_hexagon_target(\"v68\"), name=\"pad\")\n    mod = hexagon_session.load_module(func)\n\n    dev = hexagon_session.device\n    a = tvm.nd.array(data_in, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(c_tensor.shape), dtype=c_tensor.dtype), dev)\n    mod[\"pad\"](a, b)\n\n    # Reference numpy pad output\n    ref_out = np.pad(data_in, pad_width=((0, 0), (1, 1), (1, 1), (0, 0)))\n\n    tvm.testing.assert_allclose(b.numpy(), ref_out)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for pooling\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n\nclass TestAdaptivePool:\n    \"\"\"Adaptive pool test class.\"\"\"\n\n    dshape, out_size, pool_type, layout = tvm.testing.parameters(\n        ((1, 3, 112, 112), (1, 1), \"max\", \"NCHW\"),\n        ((1, 3, 112, 112), (1, 1), \"avg\", \"NCHW\"),\n        ((1, 14, 56, 78), (34, 13), \"max\", \"NCHW\"),\n        ((1, 5, 46, 97), (4, 96), \"avg\", \"NCHW\"),\n        ((1, 112, 112, 3), (1, 1), \"max\", \"NHWC\"),\n        ((1, 5, 46, 97), (4, 96), \"avg\", \"NHWC\"),\n        ((1, 16, 32, 32, 32), (1, 1, 1), \"max\", \"NCDHW\"),\n        ((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", \"NCDHW\"),\n        ((1, 16, 32, 32, 32), (2, 2, 2), \"avg\", \"NCDHW\"),\n        (\n            (1, 16, 64, 32, 32),\n            (7, 8, 9),\n            \"avg\",\n            \"NCDHW\",\n        ),\n        (\n            (1, 16, 64, 32, 32),\n            (8, 16, 16),\n            \"avg\",\n            \"NCDHW\",\n        ),\n        ((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", \"NDHWC\"),\n        ((1, 16, 32, 32, 32), (2, 2, 2), \"max\", \"NDHWC\"),\n        ((1, 16, 32, 32, 32), (2, 4, 4), \"max\", \"NDHWC\"),\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_adaptive_pool(self, hexagon_session: Session, dshape, out_size, pool_type, layout):\n        \"\"\"Test adaptive pool.\"\"\"\n        dtype = \"float32\"\n        np_data = np.random.uniform(low=0, high=255, size=dshape).astype(dtype)\n        np_out = tvm.topi.testing.adaptive_pool(np_data, out_size, pool_type, layout)\n        oshape = np_out.shape\n\n        data = te.placeholder(dshape, name=\"data\", dtype=dtype)\n        if len(out_size) == 2:\n            out = topi.nn.adaptive_pool(data, out_size, pool_type, layout)\n        else:\n            assert len(out_size) == 3\n            out = topi.nn.adaptive_pool3d(data, out_size, pool_type, layout)\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fschedule = topi.hexagon.schedule_adaptive_pool\n            s = fschedule(out)\n\n        func = tvm.build(\n            s,\n            [data, out],\n            get_hexagon_target(\"v68\"),\n            name=\"adaptive-pool\",\n        )\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a = tvm.nd.array(np_data, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(oshape), dtype=out.dtype), dev)\n        mod[\"adaptive-pool\"](a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), np_out, rtol=4e-5, atol=1e-6)\n\n\ndef verify_poolnd(\n    hexagon_session,\n    n,\n    input_shape,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode,\n    count_include_pad=True,\n    layout=\"NCW\",\n):\n    \"\"\"Pool test verification.\"\"\"\n    a_tensor = te.placeholder(input_shape, name=\"a_tensor\")\n\n    if n == 1:\n        b_tensor = topi.nn.pool1d(\n            a_tensor,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    elif n == 2:\n        b_tensor = topi.nn.pool2d(\n            a_tensor,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    elif n == 3:\n        b_tensor = topi.nn.pool3d(\n            a_tensor,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    else:\n        raise ValueError(f\"PoolND only supports n=1, 2, 3 got n={n}\")\n\n    b_tensor = topi.nn.relu(b_tensor)\n    dtype = a_tensor.dtype\n    output_shape = [int(i) for i in b_tensor.shape]\n\n    input_np = np.random.uniform(low=0.001, size=input_shape).astype(dtype)\n\n    padding_before = padding[:n]\n    padding_after = padding[n:]\n    ref_np = tvm.topi.testing.poolnd_python(\n        input_np,\n        kernel,\n        stride,\n        dilation,\n        padding_before,\n        padding_after,\n        pool_type,\n        count_include_pad,\n        ceil_mode,\n        layout=layout,\n    )\n\n    np.testing.assert_equal(tuple(output_shape), tuple(ref_np.shape))\n\n    with tvm.target.Target(get_hexagon_target(\"v68\")):\n        fschedule = topi.hexagon.schedule_pool\n        s = fschedule(b_tensor, layout)\n\n    func = tvm.build(s, [a_tensor, b_tensor], get_hexagon_target(\"v68\"), name=\"pool\")\n    mod = hexagon_session.load_module(func)\n\n    dev = hexagon_session.device\n    a = tvm.nd.array(input_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(b_tensor.shape), dtype=dtype), dev)\n    mod[\"pool\"](a, b)\n\n    tvm.testing.assert_allclose(b.numpy(), ref_np, rtol=1e-5)\n\n\nclass TestPool1D:\n    \"\"\"Pool1D test class.\"\"\"\n\n    (\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ) = tvm.testing.parameters(\n        ([1, 16, 32], [2], [2], [1], [0, 0], \"avg\", False, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [1, 2], \"avg\", False, True, \"NCW\"),\n        ([1, 16, 32], [2], [2], [1], [1, 2], \"avg\", False, False, \"NCW\"),\n        ([1, 16, 31], [4], [4], [1], [3, 3], \"avg\", False, False, \"NCW\"),\n        ([1, 16, 31], [4], [4], [1], [0, 0], \"avg\", False, False, \"NCW\"),\n        ([1, 16, 32], [2], [2], [1], [0, 0], \"max\", False, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [2, 1], \"max\", False, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [2, 1], \"max\", True, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [2, 5], \"avg\", False, True, \"NCW\"),\n        ([1, 16, 32], [2], [2], [1], [0, 3], \"avg\", False, False, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [1, 4], \"max\", False, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [1], [3, 0], \"max\", True, True, \"NCW\"),\n        # Test non-1 dilations\n        ([1, 16, 31], [3], [3], [2], [2, 5], \"avg\", False, True, \"NCW\"),\n        ([1, 16, 32], [2], [2], [3], [0, 3], \"avg\", False, False, \"NCW\"),\n        ([1, 16, 31], [3], [3], [2], [1, 4], \"max\", False, True, \"NCW\"),\n        ([1, 16, 31], [3], [3], [3], [3, 0], \"max\", True, True, \"NCW\"),\n        # Test Channel last\n        ([1, 32, 16], [2], [2], [1], [0, 0], \"avg\", False, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [1, 2], \"avg\", False, True, \"NWC\"),\n        ([1, 32, 16], [2], [2], [1], [1, 2], \"avg\", False, False, \"NWC\"),\n        ([1, 31, 16], [4], [4], [1], [3, 3], \"avg\", False, False, \"NWC\"),\n        ([1, 31, 16], [4], [4], [1], [0, 0], \"avg\", False, False, \"NWC\"),\n        ([1, 32, 16], [2], [2], [1], [0, 0], \"max\", False, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [2, 1], \"max\", False, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [2, 1], \"max\", True, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [2, 5], \"avg\", False, True, \"NWC\"),\n        ([1, 31, 16], [2], [2], [1], [0, 3], \"avg\", False, False, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [1, 4], \"max\", False, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [1], [3, 0], \"max\", True, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [2], [2, 5], \"avg\", False, True, \"NWC\"),\n        ([1, 32, 16], [2], [2], [3], [0, 3], \"avg\", False, False, \"NWC\"),\n        ([1, 31, 16], [3], [3], [2], [1, 4], \"max\", False, True, \"NWC\"),\n        ([1, 31, 16], [3], [3], [3], [3, 0], \"max\", True, True, \"NWC\"),\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_pool1d(\n        self,\n        hexagon_session: Session,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ):\n        \"\"\"Test Pool1D.\"\"\"\n        verify_poolnd(\n            hexagon_session,\n            1,\n            input_shape,\n            kernel,\n            stride,\n            dilation,\n            padding,\n            pool_type,\n            ceil_mode,\n            count_include_pad,\n            layout,\n        )\n\n\nclass TestPool2D:\n    \"\"\"Pool2D test class.\"\"\"\n\n    (\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ) = tvm.testing.parameters(\n        ([1, 16, 32, 32], [2, 2], [2, 2], [1, 1], [0, 0, 0, 0], \"avg\", False, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [1, 2, 1, 2], \"avg\", False, True, \"NCHW\"),\n        ([1, 16, 32, 32], [2, 2], [2, 2], [1, 1], [1, 2, 1, 2], \"avg\", False, False, \"NCHW\"),\n        ([1, 16, 31, 31], [4, 4], [4, 4], [1, 1], [3, 3, 3, 3], \"avg\", False, False, \"NCHW\"),\n        ([1, 16, 31, 31], [4, 4], [4, 4], [1, 1], [0, 0, 0, 0], \"avg\", False, False, \"NCHW\"),\n        ([1, 16, 32, 32], [2, 3], [2, 2], [1, 1], [0, 0, 0, 0], \"max\", False, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", False, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", True, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 0, 3], \"avg\", False, True, \"NCHW\"),\n        ([1, 16, 32, 32], [2, 3], [2, 2], [1, 1], [0, 3, 2, 1], \"avg\", False, False, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [1, 0, 3, 2], \"max\", False, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [3, 2, 1, 0], \"max\", True, True, \"NCHW\"),\n        # Test non-1 dilations\n        ([1, 16, 31, 31], [3, 3], [3, 3], [2, 1], [2, 1, 0, 3], \"avg\", False, True, \"NCHW\"),\n        ([1, 16, 32, 32], [2, 3], [2, 2], [2, 3], [0, 3, 2, 1], \"avg\", False, False, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [3, 3], [1, 0, 3, 2], \"max\", False, True, \"NCHW\"),\n        ([1, 16, 31, 31], [3, 3], [3, 3], [2, 2], [3, 2, 1, 0], \"max\", True, True, \"NCHW\"),\n        # Test channel last\n        ([1, 32, 32, 16], [2, 2], [2, 2], [1, 1], [0, 0, 0, 0], \"avg\", False, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [1, 2, 1, 2], \"avg\", False, True, \"NHWC\"),\n        ([1, 32, 32, 16], [2, 2], [2, 2], [1, 1], [1, 2, 1, 2], \"avg\", False, False, \"NHWC\"),\n        ([1, 31, 31, 16], [4, 4], [4, 4], [1, 1], [3, 3, 3, 3], \"avg\", False, False, \"NHWC\"),\n        ([1, 31, 31, 16], [4, 4], [4, 4], [1, 1], [0, 0, 0, 0], \"avg\", False, False, \"NHWC\"),\n        ([1, 32, 32, 16], [2, 3], [2, 2], [1, 1], [0, 0, 0, 0], \"max\", False, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", False, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", True, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 0, 3], \"avg\", False, True, \"NHWC\"),\n        ([1, 32, 32, 16], [2, 3], [2, 2], [1, 1], [0, 3, 2, 1], \"avg\", False, False, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [1, 0, 3, 2], \"max\", False, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [3, 2, 1, 0], \"max\", True, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [2, 1], [2, 1, 0, 3], \"avg\", False, True, \"NHWC\"),\n        ([1, 32, 32, 16], [2, 3], [2, 2], [2, 3], [0, 3, 2, 1], \"avg\", False, False, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [3, 3], [1, 0, 3, 2], \"max\", False, True, \"NHWC\"),\n        ([1, 31, 31, 16], [3, 3], [3, 3], [2, 2], [3, 2, 1, 0], \"max\", True, True, \"NHWC\"),\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_pool2d(\n        self,\n        hexagon_session: Session,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ):\n        \"\"\"Test Pool2D.\"\"\"\n        verify_poolnd(\n            hexagon_session,\n            2,\n            input_shape,\n            kernel,\n            stride,\n            dilation,\n            padding,\n            pool_type,\n            ceil_mode,\n            count_include_pad,\n            layout,\n        )\n\n\nclass TestPool3D:\n    \"\"\"Pool3D test class.\"\"\"\n\n    (\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ) = tvm.testing.parameters(\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"avg\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [1, 1, 2, 2, 2, 1],\n            \"avg\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [1, 1, 2, 2, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [4, 4, 4],\n            [4, 4, 4],\n            [1, 1, 1],\n            [3, 3, 3, 3, 3, 3],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [4, 4, 4],\n            [4, 4, 4],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"max\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 2, 1, 1, 1, 2],\n            \"max\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 2, 1, 1, 1, 2],\n            \"max\",\n            True,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 1, 0, 5, 4, 3],\n            \"avg\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 5, 4, 3, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [1, 0, 5, 4, 3, 2],\n            \"max\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [3, 2, 1, 0, 5, 4],\n            \"max\",\n            True,\n            True,\n            \"NCDHW\",\n        ),\n        # Test non-1 dilation\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 1, 0, 5, 4, 3],\n            \"avg\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [2, 2, 2],\n            [0, 5, 4, 3, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 1, 3],\n            [1, 0, 5, 4, 3, 2],\n            \"max\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 2, 3],\n            [3, 2, 1, 0, 5, 4],\n            \"max\",\n            True,\n            True,\n            \"NCDHW\",\n        ),\n        # Test channel last layouts\n        (\n            [1, 32, 32, 32, 16],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"avg\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [1, 1, 2, 2, 2, 1],\n            \"avg\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 32, 32, 32, 16],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [1, 1, 2, 2, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [4, 4, 4],\n            [4, 4, 4],\n            [1, 1, 1],\n            [3, 3, 3, 3, 3, 3],\n            \"avg\",\n            False,\n            False,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [4, 4, 4],\n            [4, 4, 4],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"avg\",\n            False,\n            False,\n            \"NDHWC\",\n        ),\n        (\n            [1, 32, 32, 32, 16],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 0, 0, 0, 0, 0],\n            \"max\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 2, 1, 1, 1, 2],\n            \"max\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 2, 1, 1, 1, 2],\n            \"max\",\n            True,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [2, 1, 0, 5, 4, 3],\n            \"avg\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 32, 32, 32, 16],\n            [2, 2, 2],\n            [2, 2, 2],\n            [1, 1, 1],\n            [0, 5, 4, 3, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [1, 0, 5, 4, 3, 2],\n            \"max\",\n            False,\n            True,\n            \"NDHWC\",\n        ),\n        (\n            [1, 31, 31, 31, 16],\n            [3, 3, 3],\n            [3, 3, 3],\n            [1, 1, 1],\n            [3, 2, 1, 0, 5, 4],\n            \"max\",\n            True,\n            True,\n            \"NDHWC\",\n        ),\n        # Test non-1 dilation\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 1, 0, 5, 4, 3],\n            \"avg\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 32, 32, 32],\n            [2, 2, 2],\n            [2, 2, 2],\n            [2, 2, 2],\n            [0, 5, 4, 3, 2, 1],\n            \"avg\",\n            False,\n            False,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 1, 3],\n            [1, 0, 5, 4, 3, 2],\n            \"max\",\n            False,\n            True,\n            \"NCDHW\",\n        ),\n        (\n            [1, 16, 31, 31, 31],\n            [3, 3, 3],\n            [3, 3, 3],\n            [2, 2, 3],\n            [3, 2, 1, 0, 5, 4],\n            \"max\",\n            True,\n            True,\n            \"NCDHW\",\n        ),\n    )\n\n    @tvm.testing.requires_hexagon\n    def test_pool3d(\n        self,\n        hexagon_session: Session,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        count_include_pad,\n        layout,\n    ):\n        \"\"\"Test Pool3D.\"\"\"\n        verify_poolnd(\n            hexagon_session,\n            3,\n            input_shape,\n            kernel,\n            stride,\n            dilation,\n            padding,\n            pool_type,\n            ceil_mode,\n            count_include_pad,\n            layout,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n\"\"\"TIR quantize schedule tests.\"\"\"\r\nimport numpy as np\r\n\r\nimport tvm\r\nfrom tvm import te\r\nimport tvm.topi.hexagon.qnn as s1\r\nfrom tvm.contrib.hexagon import allocate_hexagon_array\r\nfrom ..infrastructure import (\r\n    transform_numpy,\r\n    quantize_np,\r\n    get_hexagon_target,\r\n)\r\n\r\nQUANTIZE_SCALE = None\r\nQUANTIZE_ZERO_POINT = None\r\n\r\n\r\nclass TestQuantize:\r\n    \"\"\"Test quantize class.\"\"\"\r\n\r\n    @tvm.testing.fixture\r\n    def expected_output_np(self, input_np, output_dtype):\r\n        global QUANTIZE_SCALE, QUANTIZE_ZERO_POINT\r\n        quant_np, QUANTIZE_SCALE, QUANTIZE_ZERO_POINT = quantize_np(input_np, output_dtype)\r\n        return quant_np\r\n\r\n    @tvm.testing.fixture\r\n    def input_np(self, input_shape, input_dtype):\r\n        return np.random.random(input_shape).astype(input_dtype)\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_input_np(self, input_np, input_crouton_layout):\r\n        return transform_numpy(input_np, \"nhwc\", input_crouton_layout)\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_expected_output_np(self, expected_output_np, output_layout):\r\n        return transform_numpy(expected_output_np, \"nhwc\", output_layout)\r\n\r\n    input_crouton_layout, output_layout, input_dtype = tvm.testing.parameters(\r\n        (\"nhwc-4h2w32c2w-2d\", \"nhwc-8h8w32c-2d\", \"float32\"),\r\n    )\r\n\r\n    output_dtype = tvm.testing.parameter(\"uint8\", \"int8\")\r\n\r\n    input_shape = tvm.testing.parameter(\r\n        (1, 8, 8, 32), (1, 16, 16, 32), (1, 16, 16, 128), (1, 64, 64, 64)\r\n    )\r\n\r\n    @tvm.testing.requires_hexagon\r\n    def test_quantize(\r\n        self,\r\n        input_dtype,\r\n        output_dtype,\r\n        transformed_input_np,\r\n        input_shape,\r\n        expected_output_np,\r\n        transformed_expected_output_np,\r\n        input_crouton_layout,\r\n        output_layout,\r\n        hexagon_session,\r\n    ):\r\n        \"\"\"Test quantize.\"\"\"\r\n        a_tensor = te.placeholder(input_shape, name=\"a_tensor\", dtype=input_dtype)\r\n\r\n        m_tensor = s1.quantize_compute(a_tensor, QUANTIZE_SCALE, QUANTIZE_ZERO_POINT, output_dtype)\r\n\r\n        tir_schedule = s1.tir_quantize_schedule(\r\n            m_tensor, a_tensor, input_crouton_layout, output_layout\r\n        )\r\n\r\n        sch = tir_schedule.mod\r\n\r\n        input_axis_separator = [4]\r\n        output_axis_separator = [4]\r\n\r\n        with tvm.transform.PassContext(opt_level=3):\r\n            func = tvm.build(\r\n                sch,\r\n                [a_tensor, m_tensor],\r\n                get_hexagon_target(\"v69\"),\r\n                name=\"quantize\",\r\n            )\r\n\r\n        a_data_nd = allocate_hexagon_array(\r\n            hexagon_session.device,\r\n            data=transformed_input_np,\r\n            dtype=input_dtype,\r\n            axis_separators=input_axis_separator,\r\n            mem_scope=\"global.vtcm\",\r\n        )\r\n\r\n        m_data_nd = allocate_hexagon_array(\r\n            hexagon_session.device,\r\n            tensor_shape=transformed_expected_output_np.shape,\r\n            dtype=output_dtype,\r\n            axis_separators=output_axis_separator,\r\n            mem_scope=\"global.vtcm\",\r\n        )\r\n\r\n        mod = hexagon_session.load_module(func)\r\n        mod(a_data_nd, m_data_nd)\r\n\r\n        b, h, weight, c = expected_output_np.shape\r\n\r\n        # convert nd to np and reshape to fixed chunk size layout\r\n        m_data_np = m_data_nd.numpy().reshape([b, h // 8, weight // 8, c // 32, 8, 8, 32])\r\n\r\n        np.testing.assert_allclose(transformed_expected_output_np, m_data_np, atol=1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    tvm.testing.main()\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for reduce\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\n\nfrom ..infrastructure import get_hexagon_target\n\n\ndef _my_npy_argmax(arr, axis, keepdims):\n    if not keepdims:\n        return arr.argmax(axis=axis)\n    else:\n        if axis is None:\n            out_shape = [1 for _ in arr.shape]\n        else:\n            out_shape = list(arr.shape)\n            out_shape[axis] = 1\n\n        return arr.argmax(axis=axis).reshape(out_shape)\n\n\ndef _my_npy_argmin(arr, axis, keepdims):\n    if not keepdims:\n        return arr.argmin(axis=axis)\n    else:\n        if axis is None:\n            out_shape = [1 for _ in arr.shape]\n        else:\n            out_shape = list(arr.shape)\n            out_shape[axis] = 1\n        return arr.argmin(axis=axis).reshape(out_shape)\n\n\nclass TestReduce:\n    \"\"\"Test reduce class.\"\"\"\n\n    in_shape, axis, keepdims, reduce_type, dtype = tvm.testing.parameters(\n        ((32,), 0, False, \"argmax\", \"float32\"),\n        ((32, 24, 32, 24), (1, 2, 3), True, \"sum\", \"float32\"),\n        ((2, 3), None, True, \"all\", \"bool\"),\n        ((32, 24 * 32 * 24), (1,), False, \"max\", \"float32\"),\n        ((32, 128, 24), None, True, \"sum\", \"float32\"),\n        ((32, 128, 24), None, True, \"all\", \"bool\"),\n        ((32, 24, 32, 24), (0, 2), False, \"min\", \"float32\"),\n        ((32, 128), 1, True, \"argmax\", \"float32\"),\n        ((32, 24, 32, 24), 2, False, \"argmin\", \"float32\"),\n        ((31, 21, 15), None, True, \"argmax\", \"float32\"),\n        ((31, 21, 15), None, False, \"sum\", \"float32\"),\n        ((2, 3), None, True, \"any\", \"bool\"),\n        ((32, 128, 24), None, True, \"any\", \"bool\"),\n        ((1, 4, 7), 1, True, \"any\", \"bool\"),\n        ((32, 24, 32, 24), 2, False, \"any\", \"bool\"),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(self, in_shape, axis, keepdims, reduce_type, dtype):\n        \"\"\"Generate test reference data.\"\"\"\n        if dtype == \"bool\":\n            in_npy_map = in_npy = np.random.choice([True, False], size=in_shape)\n        else:\n            in_npy = np.random.uniform(-1, 1, size=in_shape).astype(dtype)\n            in_npy_map = np.sqrt(np.exp(in_npy)).astype(dtype)\n\n        if reduce_type == \"sum\":\n            out_npy = in_npy_map.sum(axis=axis, keepdims=keepdims)\n        elif reduce_type == \"all\" and dtype == \"bool\":\n            out_npy = in_npy_map.all(axis=axis, keepdims=keepdims)\n        elif reduce_type == \"any\" and dtype == \"bool\":\n            out_npy = in_npy_map.any(axis=axis, keepdims=keepdims)\n        elif reduce_type == \"max\":\n            out_npy = in_npy_map.max(axis=axis, keepdims=keepdims)\n        elif reduce_type == \"min\":\n            out_npy = in_npy_map.min(axis=axis, keepdims=keepdims)\n        elif reduce_type == \"argmax\":\n            out_npy = _my_npy_argmax(in_npy_map, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"argmin\":\n            out_npy = _my_npy_argmin(in_npy_map, axis=axis, keepdims=keepdims)\n        else:\n            raise NotImplementedError\n\n        return in_npy, in_npy_map, out_npy\n\n    @tvm.testing.requires_hexagon\n    def test_reduce_map(\n        self, hexagon_session: Session, ref_data, in_shape, axis, keepdims, reduce_type, dtype\n    ):\n        \"\"\"Test reduce map.\"\"\"\n        in_npy, in_npy_map, out_npy = ref_data\n\n        # Build the logic and compile the function\n        a_tensor = te.placeholder(shape=in_shape, name=\"a_tensor\", dtype=dtype)\n        a1_tensor = topi.sqrt(topi.exp(a_tensor))\n        out_dtype = dtype\n        if reduce_type == \"sum\":\n            b_tensor = topi.sum(a1_tensor, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"all\":\n            b_tensor = topi.all(a_tensor, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"any\":\n            b_tensor = topi.any(a_tensor, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"max\":\n            b_tensor = topi.max(a1_tensor, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"min\":\n            b_tensor = topi.min(a1_tensor, axis=axis, keepdims=keepdims)\n        elif reduce_type == \"argmax\":\n            b_tensor = topi.argmax(a1_tensor, axis=axis, keepdims=keepdims)\n            out_dtype = \"int32\"\n        elif reduce_type == \"argmin\":\n            b_tensor = topi.argmin(a1_tensor, axis=axis, keepdims=keepdims)\n            out_dtype = \"int32\"\n        else:\n            raise NotImplementedError\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fschedule = topi.hexagon.schedule_reduce\n            s = fschedule(b_tensor)\n\n        func = tvm.build(s, [a_tensor, b_tensor], get_hexagon_target(\"v68\"), name=reduce_type)\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        data_tvm = tvm.nd.array(in_npy, device=dev)\n        out_tvm = tvm.nd.empty(shape=out_npy.shape, device=dev, dtype=out_dtype)\n\n        mod[reduce_type](data_tvm, out_tvm)\n\n        if reduce_type in [\"argmax\", \"argmin\"]:\n            out_tvm_indices = out_tvm.numpy()\n            if keepdims:\n                out_tvm_indices = np.take(out_tvm_indices, indices=0, axis=axis)\n            if axis is None:\n                out_tvm_val = in_npy_map.ravel()[out_tvm_indices]\n            else:\n                other_indices = tuple(np.indices(in_shape[0:axis] + in_shape[(axis + 1) :]))\n                sel_indices = other_indices[0:axis] + (out_tvm_indices,) + other_indices[axis:]\n                out_tvm_val = in_npy_map[sel_indices]\n            if reduce_type == \"argmax\":\n                tvm.testing.assert_allclose(out_tvm_val, in_npy_map.max(axis=axis), 1e-3, 1e-3)\n            elif reduce_type == \"argmin\":\n                tvm.testing.assert_allclose(out_tvm_val, in_npy_map.min(axis=axis), 1e-3, 1e-3)\n        else:\n            tvm.testing.assert_allclose(out_tvm.numpy(), out_npy, 1e-3, 1e-3)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_reshape.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test reshape class.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.hexagon.slice_ops as sl\nfrom tvm import te\nfrom tvm.contrib.hexagon import allocate_hexagon_array\n\nfrom ..infrastructure import transform_numpy, get_hexagon_target\n\nBATCH_FLATTEN_FP16_TESTS = (\n    ([1, 1, 1, 2048], [1, 2048], \"nhwc-1024c-2d\", \"nc-1024-2d\", \"float16\"),\n    ([1, 2, 4, 2048], [1, 2 * 4 * 2048], \"nhwc-1024c-2d\", \"nc-1024-2d\", \"float16\"),\n    ([1, 8, 8, 1024], [1, 8 * 8 * 1024], \"nhwc-1024c-2d\", \"nc-1024-2d\", \"float16\"),\n    ([2, 4, 8, 1024], [2, 4 * 8 * 1024], \"nhwc-1024c-2d\", \"nc-1024-2d\", \"float16\"),\n)\n\nBATCH_FLATTEN_UINT8_TESTS = (\n    ([1, 1, 1, 2048], [1, 2048], \"nhwc-2048c-2d\", \"nc-2048-2d\", \"uint8\"),\n    ([1, 2, 4, 2048], [1, 2 * 4 * 2048], \"nhwc-2048c-2d\", \"nc-2048-2d\", \"uint8\"),\n)\n\n\ndef reshape_helper(\n    func,\n    fcompute,\n    fschedule,\n    data_type,\n    input_shape,\n    input_layout,\n    output_shape,\n    output_layout,\n    hexagon_session,\n):\n    \"\"\"Reshape helper function.\"\"\"\n\n    a_tensor = te.placeholder(input_shape, name=\"a_tensor\", dtype=data_type)\n    if func == \"reshape\":\n        d_tesnsor = fcompute(a_tensor, output_shape)\n    elif func == \"batch_flatten\":\n        d_tesnsor = fcompute(a_tensor)\n    else:\n        raise RuntimeError(f\"Unexpected func'{func}'\")\n    tir_s = fschedule(\n        d_tesnsor,\n        a_tensor,\n        output_layout,\n        input_layout,\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        runtime_module = tvm.build(tir_s.mod, target=get_hexagon_target(\"v69\"), name=func)\n\n    mod = hexagon_session.load_module(runtime_module)\n\n    a_numpy = (np.random.uniform(-10, 10, input_shape)).astype(data_type)\n    ref = np.reshape(a_numpy, output_shape)\n\n    input_np_transformed = transform_numpy(a_numpy, \"nhwc\", input_layout)\n    ref_np_transformed = transform_numpy(ref, \"nhwc\", output_layout)\n    input_axis_sep = [4]\n    if output_layout in [\"nhwc-8h2w32c2w-2d\", \"nhwc-8h8w32c-2d\"]:\n        output_axis_sep = [4]\n    elif output_layout in [\"nc-1024-2d\", \"nc-2048-2d\"]:\n        output_axis_sep = [2]\n    else:\n        raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\n\n    a_tvm = allocate_hexagon_array(\n        hexagon_session.device,\n        data=input_np_transformed,\n        axis_separators=input_axis_sep,\n        mem_scope=\"global.vtcm\",\n    )\n    output = allocate_hexagon_array(\n        hexagon_session.device,\n        ref_np_transformed.shape,\n        data_type,\n        axis_separators=output_axis_sep,\n        mem_scope=\"global.vtcm\",\n    )\n\n    mod(a_tvm, output)\n    np.testing.assert_allclose(output.numpy(), ref_np_transformed, atol=1e-07, rtol=0)\n\n\nclass BaseTestBatchFlatten:\n    \"\"\"Test batch flatten class.\"\"\"\n\n    (input_shape, output_shape, input_layout, output_layout, data_type,) = tvm.testing.parameters(\n        *BATCH_FLATTEN_FP16_TESTS,\n        *BATCH_FLATTEN_UINT8_TESTS,\n    )\n\n\nclass TestBatchFlatten(BaseTestBatchFlatten):\n    \"\"\"Test batch flatten class.\"\"\"\n\n    @tvm.testing.requires_hexagon\n    def test_batch_flatten(\n        self,\n        data_type,\n        input_shape,\n        input_layout,\n        output_shape,\n        output_layout,\n        hexagon_session,\n    ):\n        \"\"\"Test batch flatten.\"\"\"\n        reshape_helper(\n            \"batch_flatten\",\n            sl.batch_flatten_compute,\n            sl.batch_flatten_stir_schedule,\n            data_type,\n            input_shape,\n            input_layout,\n            output_shape,\n            output_layout,\n            hexagon_session,\n        )\n\n\nclass BaseTestReshape(BaseTestBatchFlatten):\n    \"\"\"Test reshape base class.\"\"\"\n\n    reshape_fp16_tests = (\n        ([1, 8, 4, 64], [1, 8, 8, 32], \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", \"float16\"),\n        ([1, 16, 8, 128], [1, 16, 16, 64], \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", \"float16\"),\n    )\n\n    reshape_uint8_tests = (\n        ([1, 8, 8, 128], [1, 8, 16, 64], \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\", \"uint8\"),\n        ([1, 16, 64, 128], [1, 16, 128, 64], \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\", \"uint8\"),\n    )\n\n    (input_shape, output_shape, input_layout, output_layout, data_type,) = tvm.testing.parameters(\n        *BATCH_FLATTEN_FP16_TESTS,\n        *BATCH_FLATTEN_UINT8_TESTS,\n        *reshape_fp16_tests,\n        *reshape_uint8_tests,\n    )\n\n\nclass TestReshape(BaseTestReshape):\n    \"\"\"Test reshape class.\"\"\"\n\n    @tvm.testing.requires_hexagon\n    def test_reshape(\n        self,\n        data_type,\n        input_shape,\n        input_layout,\n        output_shape,\n        output_layout,\n        hexagon_session,\n    ):\n        \"\"\"Test reshape.\"\"\"\n        reshape_helper(\n            \"reshape\",\n            sl.reshape_compute,\n            sl.reshape_stir_schedule,\n            data_type,\n            input_shape,\n            input_layout,\n            output_shape,\n            output_layout,\n            hexagon_session,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_resize2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements.  See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership.  The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License.  You may obtain a copy of the License at\r\n#\r\n#   http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied.  See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n\"\"\"Resize 2D tesst.\r\n\"\"\"\r\nimport numpy as np\r\n\r\nimport tvm\r\nfrom tvm import te\r\nfrom tvm.topi.testing import resize2d_python\r\nimport tvm.topi.hexagon as s1\r\nfrom tvm.contrib.hexagon import allocate_hexagon_array\r\n\r\nfrom ..infrastructure import transform_numpy, get_hexagon_target\r\n\r\n\r\nclass TestResize2d:\r\n    \"\"\"Test resize 2D class.\"\"\"\r\n\r\n    (batch, channel, in_height, in_width, out_height, out_width,) = tvm.testing.parameters(\r\n        (\r\n            1,\r\n            32,\r\n            8,\r\n            8,\r\n            16,\r\n            16,\r\n        ),\r\n        (\r\n            1,\r\n            32,\r\n            48,\r\n            48,\r\n            8,\r\n            8,\r\n        ),\r\n    )\r\n\r\n    (layout, input_crouton_layout, output_layout, dtype,) = tvm.testing.parameters(\r\n        (\"NHWC\", \"nhwc-8h2w32c2w-2d\", \"nhwc-8h2w32c2w-2d\", \"float16\"),\r\n        (\"NHWC\", \"nhwc-8h8w32c-2d\", \"nhwc-8h8w32c-2d\", \"uint8\"),\r\n    )\r\n\r\n    coord_trans = tvm.testing.parameter(\"asymmetric\", \"align_corners\", \"half_pixel\")\r\n    method = tvm.testing.parameter(\"nearest_neighbor\", \"linear\")\r\n\r\n    @tvm.testing.fixture\r\n    def expected_output_np(\r\n        self,\r\n        input_np,\r\n        in_height,\r\n        in_width,\r\n        out_height,\r\n        out_width,\r\n        layout,\r\n        method,\r\n        coord_trans,\r\n    ):\r\n        \"\"\"Generate expected output.\"\"\"\r\n        scale_h = out_height / in_height\r\n        scale_w = out_width / in_width\r\n\r\n        return resize2d_python(input_np, (scale_h, scale_w), layout, method, coord_trans)\r\n\r\n    @tvm.testing.fixture\r\n    def input_np(self, input_shape, dtype):\r\n        if dtype == \"float16\":\r\n            return np.random.random(input_shape).astype(dtype)\r\n        if dtype == \"uint8\":\r\n            return np.random.randint(0, 255, input_shape).astype(dtype)\r\n        if dtype == \"int8\":\r\n            return np.random.randint(-128, 127, input_shape).astype(dtype)\r\n        raise RuntimeError(f\"dtype {dtype} is not valid.\")\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_input_np(self, input_np, layout, input_crouton_layout, dtype):\r\n        if dtype in [\"float16\", \"uint8\", \"int8\"]:\r\n            return transform_numpy(input_np, layout.lower(), input_crouton_layout)\r\n\r\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\r\n\r\n    @tvm.testing.fixture\r\n    def transformed_expected_output_np(self, expected_output_np, layout, output_layout, dtype):\r\n        if dtype in [\"float16\", \"uint8\", \"int8\"]:\r\n            return transform_numpy(expected_output_np, layout.lower(), output_layout)\r\n\r\n        raise RuntimeError(f\"Unsupported data type '{dtype}'\")\r\n\r\n    @tvm.testing.fixture\r\n    def input_shape(self, batch, channel, in_height, in_width):\r\n        return (batch, in_height, in_width, channel)\r\n\r\n    @tvm.testing.fixture\r\n    def output_shape(self, batch, channel, out_height, out_width):\r\n        return (batch, out_height, out_width, channel)\r\n\r\n    @tvm.testing.requires_hexagon\r\n    def test_resize2d(\r\n        self,\r\n        dtype,\r\n        input_np,\r\n        transformed_input_np,\r\n        input_shape,\r\n        output_shape,\r\n        expected_output_np,\r\n        transformed_expected_output_np,\r\n        layout,\r\n        input_crouton_layout,\r\n        output_layout,\r\n        coord_trans,\r\n        method,\r\n        hexagon_session,\r\n    ):\r\n        \"\"\"Test resize 2D.\"\"\"\r\n        a_tensor = te.placeholder(input_shape, name=\"a_tensor\", dtype=dtype)\r\n\r\n        m_tensor = s1.resize2d_compute(\r\n            a_tensor,\r\n            [0.0] * 4,\r\n            (output_shape[1], output_shape[2]),\r\n            layout=layout,\r\n            coordinate_transformation_mode=coord_trans,\r\n            method=method,\r\n            out_dtype=dtype,\r\n        )\r\n\r\n        tir_schedule = s1.tir_resize2d_schedule(\r\n            m_tensor, a_tensor, input_crouton_layout, output_layout\r\n        )\r\n\r\n        sch = tir_schedule.mod\r\n\r\n        input_axis_separator = [4]\r\n        if output_layout in (\r\n            \"nhwc-8h2w32c2w-2d\",\r\n            \"nhwc-8h8w32c-2d\",\r\n        ):\r\n            output_axis_separator = [4]\r\n        else:\r\n            raise RuntimeError(f\"Unexpected layout '{output_layout}'\")\r\n\r\n        with tvm.transform.PassContext(opt_level=3):\r\n            func = tvm.build(\r\n                sch,\r\n                [a_tensor, m_tensor],\r\n                get_hexagon_target(\"v69\"),\r\n                name=\"resize2d\",\r\n            )\r\n\r\n        a_data_nd = allocate_hexagon_array(\r\n            hexagon_session.device,\r\n            data=transformed_input_np,\r\n            dtype=dtype,\r\n            axis_separators=input_axis_separator,\r\n            mem_scope=\"global.vtcm\",\r\n        )\r\n\r\n        m_data_nd = allocate_hexagon_array(\r\n            hexagon_session.device,\r\n            transformed_expected_output_np.shape,\r\n            dtype=dtype,\r\n            axis_separators=output_axis_separator,\r\n            mem_scope=\"global.vtcm\",\r\n        )\r\n\r\n        mod = hexagon_session.load_module(func)\r\n        mod(a_data_nd, m_data_nd)\r\n\r\n        batch_size, height, width, channel = output_shape\r\n        # convert nd to np and reshape to fixed chunk size layout\r\n        if output_layout == \"nhwc-8h2w32c2w-2d\":\r\n            m_data_np = m_data_nd.numpy().reshape(\r\n                [batch_size, height // 8, width // 4, channel // 32, 8, 2, 32, 2]\r\n            )\r\n        elif output_layout == \"nhwc-8h8w32c-2d\":\r\n            m_data_np = m_data_nd.numpy().reshape(\r\n                [batch_size, height // 8, width // 8, channel // 32, 8, 8, 32]\r\n            )\r\n\r\n        if dtype == \"float16\":\r\n            np.testing.assert_allclose(\r\n                transformed_expected_output_np, m_data_np, rtol=1e-3, atol=1e-3\r\n            )\r\n        elif dtype in [\"int8\", \"uint8\"]:\r\n            np.testing.assert_allclose(transformed_expected_output_np, m_data_np, rtol=1, atol=1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    tvm.testing.main()\r\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_hexagon/topi/test_softmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for softmax\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib.hexagon.session import Session\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ..infrastructure import get_hexagon_target\n\n# TODO(mehrdadh): add log_softmax to config\nOPERATOR_CONFIGS = {\n    \"softmax\": {\n        \"topi\": topi.nn.softmax,\n        \"ref\": tvm.topi.testing.softmax_python,\n        \"dimensions\": [2, 4],\n    },\n}\n\n\nclass TestSoftmax:\n    \"\"\"Softmax test class.\"\"\"\n\n    dtype = tvm.testing.parameter(\n        \"float16\",\n        \"float32\",\n    )\n\n    # TODO(mehrdadh): larger size like (1, 16, 256, 256)\n    # would fail due to TVM_HEXAGON_RPC_BUFF_SIZE_BYTES\n    shape = tvm.testing.parameter((32, 10), (3, 4), (1, 16, 32, 32))\n\n    @tvm.testing.fixture\n    def softmax_operation(self, shape) -> tuple:\n        \"\"\"Returns the operation name and shape.\"\"\"\n        for name, config in OPERATOR_CONFIGS.items():\n            if len(shape) in config[\"dimensions\"]:\n                return name\n            else:\n                raise ValueError(f\"Shape {shape} is not supported.\")\n\n    @tvm.testing.requires_hexagon\n    def test_softmax(self, hexagon_session: Session, dtype, shape, softmax_operation):\n        \"\"\"Test softmax.\"\"\"\n        if dtype == \"float16\":\n            pytest.xfail(\"float16 is not supported.\")\n\n        a_tensor = te.placeholder(shape, dtype=dtype, name=\"a_tensor\")\n\n        topi_op = OPERATOR_CONFIGS[softmax_operation][\"topi\"]\n        b_tensor = topi_op(a_tensor, axis=1)\n\n        def get_ref_data(shape):\n            ref_func = tvm.topi.testing.softmax_python\n            a_np = np.random.uniform(size=shape).astype(dtype)\n\n            if len(shape) == 2:\n                b_np = ref_func(a_np)\n            elif len(shape) == 4:\n                _, c, height, width = a_np.shape\n                a_np_2d = a_np.transpose(0, 2, 3, 1).reshape(height * width, c)\n                b_np_2d = tvm.topi.testing.softmax_python(a_np_2d)\n                b_np = b_np_2d.reshape(1, height, width, c).transpose(0, 3, 1, 2)\n\n            return a_np, b_np\n\n        # get the test data\n        a_np, b_np = get_ref_data(shape)\n\n        with tvm.target.Target(get_hexagon_target(\"v68\")):\n            fschedule = topi.hexagon.schedule_softmax\n            s = fschedule(b_tensor)\n\n        func = tvm.build(s, [a_tensor, b_tensor], get_hexagon_target(\"v68\"), name=\"softmax\")\n        mod = hexagon_session.load_module(func)\n\n        dev = hexagon_session.device\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(b_tensor.shape), dtype=b_tensor.dtype), dev)\n        mod[\"softmax\"](a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_libtorch_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm.relay\nfrom tvm.relay.op.contrib import torchop\nfrom tvm.testing import requires_libtorch\n\nimport_torch_error = None\n\ntry:\n    import torch\nexcept ImportError as e:\n    torch = None\n    import_torch_error = str(e)\n\n\n@pytest.mark.skipif(torch is None, reason=f\"PyTorch is not available: {import_torch_error}\")\n@requires_libtorch\ndef test_backend():\n    @torch.jit.script\n    def script_fn(x, y):\n        res = x * y\n        return res\n\n    for torch_dt, dt in (\n        (torch.int32, \"int32\"),\n        (torch.float32, \"float32\"),\n        (torch.float64, \"float64\"),\n    ):\n        x2 = tvm.relay.var(\"x\", shape=[1, 2], dtype=dt)\n        y2 = tvm.relay.var(\"y\", shape=[2, 2], dtype=dt)\n\n        x3 = tvm.relay.var(\"x\", shape=[1, 3], dtype=dt)\n        y3 = tvm.relay.var(\"y\", shape=[3, 3], dtype=dt)\n\n        test_body = tvm.relay.sum(torchop(script_fn, x2, y2)) + tvm.relay.sum(\n            torchop(script_fn, x3, y3)\n        )\n        test_fn = tvm.relay.Function([x2, y2, x3, y3], test_body)\n        mod = tvm.IRModule({\"main\": test_fn})\n\n        tvm.relay.transform.InferType()(mod)\n\n        # mod = tvm.relay.transform.AnnotateTarget(\"target.torch\")(mod)\n        mod = tvm.relay.transform.MergeCompilerRegions()(mod)\n        mod = tvm.relay.transform.PartitionGraph()(mod)\n        mod = tvm.relay.transform.InferType()(mod)\n\n        target = \"llvm\"\n        with tvm.transform.PassContext(opt_level=3):\n            lib = tvm.relay.build(mod, target, params={})\n\n        ctx = tvm.cpu(0)\n        rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](ctx))\n\n        # int does not have randn, so we cast...\n        x2t = torch.randn(1, 2).to(dtype=torch_dt)\n        y2t = torch.randn(2, 2).to(dtype=torch_dt)\n        x3t = torch.randn(1, 3).to(dtype=torch_dt)\n        y3t = torch.randn(3, 3).to(dtype=torch_dt)\n        # Set inputs\n        rt_mod.set_input(0, x2t)\n        rt_mod.set_input(1, y2t)\n        rt_mod.set_input(2, x3t)\n        rt_mod.set_input(3, y3t)\n        # Execute\n        rt_mod.run()\n        # Get outputs\n        tvm_output = rt_mod.get_output(0).numpy()\n        expected = (script_fn(x2t, y2t).sum() + script_fn(x3t, y3t).sum()).numpy()\n        print(tvm_output.dtype)\n        print(expected.dtype)\n        tvm.testing.assert_allclose(tvm_output, expected)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_miopen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.contrib import miopen\nimport numpy as np\nimport pytest\n\n\nrequires_miopen = pytest.mark.skipif(\n    tvm.get_global_func(\"tvm.contrib.miopen.conv2d.setup\", True) is None,\n    reason=\"MIOpen is not enabled\",\n)\n\n\n@tvm.testing.requires_rocm\n@requires_miopen\ndef test_conv2d():\n    in_channel = 3\n    out_channel = 64\n    filter_h = 3\n    filter_w = 3\n    pad_h = 1\n    pad_w = 1\n    stride_h = 1\n    stride_w = 1\n    dilation_h = 1\n    dilation_w = 1\n\n    xshape = [1, in_channel, 128, 128]\n    wshape = (out_channel, in_channel, filter_h, filter_w)\n\n    X = te.placeholder(xshape, name=\"X\")\n    W = te.placeholder(wshape, name=\"W\")\n    Y = miopen.conv2d_forward(\n        X, W, stride_h, stride_w, pad_h, pad_w, dilation_h, dilation_w, conv_mode=0, data_type=1\n    )\n\n    yshape = [x.value for x in Y.shape]\n    from tvm import topi\n\n    s = te.create_schedule(Y.op)\n\n    def verify():\n        dev = tvm.rocm(0)\n        f = tvm.build(s, [X, W, Y], \"rocm --host=llvm\", name=\"conv2d\")\n        x = tvm.nd.array(np.random.uniform(-1, 1, xshape).astype(np.float32), dev)\n        w = tvm.nd.array(np.random.uniform(-1, 1, wshape).astype(np.float32), dev)\n        y = tvm.nd.array(np.random.uniform(-1, 1, yshape).astype(np.float32), dev)\n        f(x, w, y)\n\n        Y_ref = topi.nn.conv2d_nchw(\n            X, W, (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w)\n        )\n        s_ref = te.create_schedule(Y_ref.op)\n        f_ref = tvm.build(s_ref, [X, W, Y_ref], \"rocm --host=llvm\")\n        y_ref = tvm.nd.array(np.random.uniform(-1, 1, yshape).astype(np.float32), dev)\n        f_ref(x, w, y_ref)\n        print(\"Max abs diff:\", np.max(np.abs(y.numpy() - y_ref.numpy())))\n        tvm.testing.assert_allclose(y.numpy(), y_ref.numpy(), atol=1e-3)\n\n    verify()\n\n\ndef verify_softmax(shape, axis, dtype=\"float32\", log_softmax=False):\n    miopen_op = miopen.log_softmax if log_softmax else miopen.softmax\n    testing_op = (\n        tvm.topi.testing.log_softmax_python if log_softmax else tvm.topi.testing.softmax_python\n    )\n\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = miopen_op(A, axis)\n    s = te.create_schedule([B.op])\n\n    dev = tvm.rocm(0)\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    b_np = testing_op(a_np)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    f = tvm.build(s, [A, B], target=\"rocm --host=llvm\", name=\"softmax\")\n    f(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3)\n\n\ndef verify_softmax_4d(shape, dtype=\"float32\", log_softmax=False):\n    miopen_op = miopen.log_softmax if log_softmax else miopen.softmax\n    testing_op = (\n        tvm.topi.testing.log_softmax_python if log_softmax else tvm.topi.testing.softmax_python\n    )\n\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = miopen_op(A, axis=1)\n    s = te.create_schedule([B.op])\n\n    dev = tvm.rocm(0)\n    n, c, h, w = shape\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    b_np = testing_op(a_np.transpose(0, 2, 3, 1).reshape(h * w, c))\n    b_np = b_np.reshape(n, h, w, c).transpose(0, 3, 1, 2)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    f = tvm.build(s, [A, B], target=\"rocm --host=llvm\", name=\"softmax\")\n    f(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3)\n\n\n@tvm.testing.requires_rocm\n@requires_miopen\ndef test_softmax():\n    verify_softmax((32, 10), -1)\n    verify_softmax((3, 4), -1)\n    verify_softmax_4d((1, 16, 256, 256))\n    verify_softmax_4d((1, 16, 256, 256))\n\n    verify_softmax((32, 10), -1, log_softmax=True)\n    verify_softmax((3, 4), -1, log_softmax=True)\n    verify_softmax_4d((1, 16, 256, 256), log_softmax=True)\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_mps.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import mps\n\n\n@tvm.testing.requires_metal\ndef test_matmul():\n    n = 1024\n    l = 128\n    m = 256\n    A = te.placeholder((n, l), name=\"A\")\n    B = te.placeholder((l, m), name=\"B\")\n    C = mps.matmul(A, B)\n    D = te.compute(C.shape, lambda *i: C(*i) + 1.0)\n    s = te.create_schedule(D.op)\n    yo, xo = D.op.axis\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    by, ty = s[D].split(yo, factor=16)\n    bx, tx = s[D].split(xo, factor=16)\n    s[D].bind(by, block_y)\n    s[D].bind(bx, block_x)\n    s[D].bind(ty, thread_y)\n    s[D].bind(tx, thread_x)\n\n    def verify(A, B, D, s, target=\"metal\"):\n        if not tvm.get_global_func(\"tvm.contrib.mps.matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.metal(0)\n        f = tvm.build(s, [A, B, D], \"metal\")\n        a = tvm.nd.array(np.random.uniform(size=(n, l)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(l, m)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), np.dot(a.numpy(), b.numpy()) + 1, rtol=1e-5)\n\n    verify(A, B, D, s)\n\n\n@tvm.testing.requires_metal\ndef test_conv2d():\n    n = 1\n    h = 14\n    w = 14\n    ci = 2\n    co = 4\n    kh = 3\n    kw = 3\n    stride = 2\n    A = te.placeholder((n, h, w, ci), name=\"x\")\n    B = te.placeholder((co, kh, kw, ci), name=\"w\")\n    C = mps.conv2d(A, B, \"SAME\", 2)\n    s1 = te.create_schedule(C.op)\n\n    def verify(A, B, C, target=\"llvm\"):\n        if not tvm.get_global_func(\"tvm.contrib.mps.conv2d\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.metal(0)\n        f = tvm.build(s1, [A, B, C], \"metal\")\n        a = tvm.nd.array(np.random.uniform(size=(n, h, w, ci)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(co, kh, kw, ci)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((n, h // stride, w // stride, co), dtype=C.dtype), dev)\n        f(a, b, c)\n        # print(c.numpy())\n        # print(c.shape)\n\n    verify(A, B, C, s1)\n\n\nif __name__ == \"__main__\":\n    # test_matmul()\n    test_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_mxnet_bridge.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\ndef mxnet_check():\n    \"\"\"This is a simple test function for MXNet bridge\n\n    It is not included as pytests, because of its dependency on mxnet\n\n    User can directly run this script to verify correctness.\n    \"\"\"\n    import mxnet as mx\n    from tvm import topi\n    import tvm\n    from tvm import te\n    import numpy as np\n    from tvm.contrib.mxnet import to_mxnet_func\n\n    # build a TVM function through topi\n    n = 20\n    shape = (20,)\n    scale = te.var(\"scale\", dtype=\"float32\")\n    x = te.placeholder(shape)\n    y = te.placeholder(shape)\n    z = topi.broadcast_add(x, y)\n    zz = te.compute(shape, lambda *i: z(*i) * scale)\n\n    target = tvm.target.cuda()\n\n    # build the function\n    with target:\n        s = topi.generic.schedule_injective(zz)\n        f = tvm.build(s, [x, y, zz, scale])\n\n    # get a mxnet version\n    mxf = to_mxnet_func(f, const_loc=[0, 1])\n\n    dev = mx.gpu(0)\n    xx = mx.nd.uniform(shape=shape, device=dev)\n    yy = mx.nd.uniform(shape=shape, device=dev)\n    zz = mx.nd.empty(shape=shape, device=dev)\n\n    # invoke myf: this runs in mxnet engine\n    mxf(xx, yy, zz, 10.0)\n    mxf(xx, yy, zz, 10.0)\n\n    tvm.testing.assert_allclose(zz.numpy(), (xx.numpy() + yy.numpy()) * 10)\n\n\nif __name__ == \"__main__\":\n    mxnet_check()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_nnpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nimport scipy.signal\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.contrib import nnpack\nimport pytest\n\n\n@tvm.testing.requires_llvm\ndef test_fully_connected_inference():\n    n = 1024\n    l = 128\n    m = 235\n    bias = te.var(\"bias\", dtype=\"float32\")\n    A = te.placeholder((l,), name=\"A\")\n    B = te.placeholder((m, l), name=\"B\")\n    C = nnpack.fully_connected_inference(A, B)\n    D = te.compute(C.shape, lambda i: C[i] + bias, name=\"D\")\n    s = te.create_schedule(D.op)\n\n    def verify(target=\"llvm\"):\n        if not tvm.get_global_func(\"tvm.contrib.nnpack.fully_connected_inference\", True):\n            pytest.skip(\"extern function is not available\")\n        if not nnpack.is_available():\n            pytest.skip(\"nnpack is not available\")\n\n        dev = tvm.cpu(0)\n        f = tvm.build(s, [A, B, D, bias], target)\n        a = tvm.nd.array(np.random.uniform(size=(l)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(m, l)).astype(B.dtype), dev)\n        d = tvm.nd.array(np.zeros((m,), dtype=D.dtype), dev)\n        bb = 10.0\n        f(a, b, d, bb)\n        tvm.testing.assert_allclose(d.numpy(), np.dot(a.numpy(), b.numpy().T) + bb, rtol=1e-5)\n\n    verify()\n\n\ndef np_conv(na, nw, padding, stride=1):\n    batch, in_channel, in_height, in_width = na.shape\n    _, num_filter, kernel_h, kernel_w = nw.shape\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w))\n    pad_h = pad_top + pad_bottom\n    pad_w = pad_left + pad_right\n\n    out_channel = num_filter\n    out_height = (in_height - kernel_h + pad_h) // stride_h + 1\n    out_width = (in_width - kernel_w + pad_w) // stride_w + 1\n    nb = np.zeros((batch, out_channel, out_height, out_width))\n    for n in range(batch):\n        for f in range(out_channel):\n            for c in range(in_channel):\n                if pad_h > 0 or pad_w > 0:\n                    apad = np.zeros((in_height + pad_h, in_width + pad_w))\n                    apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = na[n, c]\n                else:\n                    apad = na[n, c]\n                out = scipy.signal.convolve2d(apad, np.rot90(np.rot90(nw[f, c])), mode=\"valid\")\n                nb[n, f] += out[::stride, ::stride]\n    return nb\n\n\n@tvm.testing.requires_llvm\ndef test_convolution_inference():\n    BATCH = 8\n    IH = 48\n    IW = 48\n    IC = 16\n    OC = 16\n    K = 3\n    PAD = 1\n    STRIDE = 1\n\n    OH = (IH + 2 * PAD - K) + 1\n    OW = (IW + 2 * PAD - K) + 1\n    dshape = (BATCH, IC, IH, IW)\n    kshape = (OC, IC, K, K)\n    bshape = (OC,)\n    oshape = (BATCH, OC, OH, OW)\n\n    data = te.placeholder(dshape, name=\"data\")\n    kernel = te.placeholder(kshape, name=\"kernel\")\n    bias = te.placeholder(bshape, name=\"bias\")\n\n    def verify(target=\"llvm\", algorithm=nnpack.ConvolutionAlgorithm.AUTO, with_bias=True):\n        if not tvm.get_global_func(\"tvm.contrib.nnpack.fully_connected_inference\", True):\n            pytest.skip(\"extern function is not available\")\n        if not nnpack.is_available():\n            pytest.skip(\"nnpack is not available\")\n\n        dev = tvm.cpu(0)\n        output = nnpack.convolution_inference(\n            data,\n            kernel,\n            bias if with_bias else None,\n            [PAD, PAD, PAD, PAD],\n            [STRIDE, STRIDE],\n            algorithm=algorithm,\n        )\n        s = te.create_schedule(output.op)\n\n        f = tvm.build(s, [data, kernel, bias, output], target)\n\n        na = np.random.uniform(size=dshape).astype(data.dtype)\n        nb = np.random.uniform(size=kshape).astype(kernel.dtype)\n        nc = np.zeros(bshape, dtype=bias.dtype)\n        ta = tvm.nd.array(na, dev)\n        tb = tvm.nd.array(nb, dev)\n        tc = tvm.nd.array(nc, dev)\n        td = tvm.nd.array(np.zeros(oshape, dtype=output.dtype), dev)\n        f(ta, tb, tc, td)\n        nd = np_conv(np.reshape(na, (BATCH, IC, IH, IW)), nb, PAD, STRIDE) + nc.reshape(\n            1, bshape[0], 1, 1\n        )\n        tvm.testing.assert_allclose(td.numpy(), nd.reshape(BATCH, IC, IH, IW), rtol=1e-5)\n\n    for algorithm in [\n        nnpack.ConvolutionAlgorithm.AUTO,\n        nnpack.ConvolutionAlgorithm.FFT_8x8,\n        nnpack.ConvolutionAlgorithm.FFT_16x16,\n        nnpack.ConvolutionAlgorithm.WT_8x8,\n        nnpack.ConvolutionAlgorithm.IMPLICIT_GEMM,\n        nnpack.ConvolutionAlgorithm.WT_8x8_FP16,\n    ]:\n        for with_bias in [True, False]:\n            verify(algorithm=algorithm, with_bias=with_bias)\n\n\n@tvm.testing.requires_llvm\ndef test_convolution_inference_without_weight_transform():\n    BATCH = 6\n    IH = 48\n    IW = 48\n    IC = 16\n    OC = 16\n    K = 3\n    PAD = 1\n    STRIDE = 1\n\n    OH = (IH + 2 * PAD - K) + 1\n    OW = (IW + 2 * PAD - K) + 1\n    dshape = (BATCH, IC, IH, IW)\n    kshape = (OC, IC, K, K)\n    bshape = (OC,)\n    oshape = (BATCH, OC, OH, OW)\n\n    data = te.placeholder(dshape, name=\"data\")\n    kernel = te.placeholder(kshape, name=\"kernel\")\n    bias = te.placeholder(bshape, name=\"bias\")\n\n    def verify(target=\"llvm\", algorithm=nnpack.ConvolutionAlgorithm.AUTO, with_bias=True):\n        if not tvm.get_global_func(\"tvm.contrib.nnpack.fully_connected_inference\", True):\n            pytest.skip(\"extern function is not available\")\n        if not nnpack.is_available():\n            pytest.skip(\"nnpack is not available\")\n\n        dev = tvm.cpu(0)\n        transformed_kernel = nnpack.convolution_inference_weight_transform(\n            kernel, algorithm=algorithm\n        )\n        output = nnpack.convolution_inference_without_weight_transform(\n            data,\n            transformed_kernel,\n            bias if with_bias else None,\n            [PAD, PAD, PAD, PAD],\n            [STRIDE, STRIDE],\n            algorithm=algorithm,\n        )\n\n        s = te.create_schedule(output.op)\n\n        f = tvm.build(s, [data, kernel, bias, output], target)\n\n        na = np.random.uniform(size=dshape).astype(data.dtype)\n        nb = np.random.uniform(size=kshape).astype(kernel.dtype)\n        nc = (\n            np.random.uniform(size=bshape).astype(bias.dtype)\n            if with_bias\n            else np.zeros(bshape, dtype=bias.dtype)\n        )\n        ta = tvm.nd.array(na, dev)\n        tb = tvm.nd.array(nb, dev)\n        tc = tvm.nd.array(nc, dev)\n        td = tvm.nd.array(np.zeros(oshape, dtype=output.dtype), dev)\n        f(ta, tb, tc, td)\n        nd = np_conv(np.reshape(na, (BATCH, IC, IH, IW)), nb, PAD, STRIDE) + nc.reshape(\n            1, bshape[0], 1, 1\n        )\n        tvm.testing.assert_allclose(td.numpy(), nd.reshape(BATCH, IC, IH, IW), rtol=1e-5)\n\n    for algorithm in [nnpack.ConvolutionAlgorithm.WT_8x8]:\n        for with_bias in [True, False]:\n            verify(algorithm=algorithm, with_bias=with_bias)\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_onnx.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Relay to ONNX serialization test cases\"\"\"\nimport pytest\n\npytest.importorskip(\"onnx\")\npytest.importorskip(\"onnxruntime\")\n\nimport numpy as np\nimport onnxruntime as rt\n\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.target.onnx import to_onnx\nfrom tvm.relay.testing import run_infer_type\n\n\ndef func_to_onnx(func, name):\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    onnx_model = to_onnx(mod, {}, name, path=None)\n    return onnx_model.SerializeToString()\n\n\ndef run_onnx(onnx_model, input_data):\n    sess = rt.InferenceSession(onnx_model)\n    input_names = {}\n    for input, data in zip(sess.get_inputs(), input_data):\n        input_names[input.name] = data\n    output_names = [out.name for out in sess.get_outputs()]\n    res = sess.run(output_names, input_names)\n    return res\n\n\ndef run_relay(func, data_tuple, is_dyn=False):\n    target = \"llvm\"\n    dev = tvm.device(\"llvm\", 0)\n    kind = \"graph\" if not is_dyn else \"vm\"\n    relay_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(*data_tuple)\n\n    result = []\n    relay_res = relay_res if isinstance(relay_res, list) else [relay_res]\n    for res in relay_res:\n        result.append(res.numpy())\n\n    return result\n\n\ndef verify_results(relay_func, indata, test_name, rtol=1e-7, atol=0, is_dyn=False):\n    relay_results = run_relay(relay_func, indata, is_dyn)\n    onnx_results = run_onnx(func_to_onnx(relay_func, test_name), indata)\n\n    for relay_res, onnx_res in zip(relay_results, onnx_results):\n        np.testing.assert_allclose(relay_res, onnx_res, rtol=rtol, atol=atol)\n\n\ndef test_add():\n    dtype = \"float32\"\n    t1 = relay.TensorType((5, 10, 5))\n    t2 = relay.TensorType((5, 10, 5))\n    x = relay.var(\"x\", t1, dtype=dtype)\n    y = relay.var(\"y\", t2, dtype=dtype)\n    z = relay.add(x, y)\n    func = relay.Function([x, y], z)\n\n    x_data = np.random.rand(5, 10, 5).astype(dtype)\n    y_data = np.random.rand(5, 10, 5).astype(dtype)\n\n    verify_results(func, [x_data, y_data], \"test_add\")\n\n\ndef test_bias_add():\n    for dtype in [\"float16\", \"float32\"]:\n        xshape = (10, 2, 3, 4)\n        bshape = (2,)\n        rtol = 1e-2 if dtype == \"float16\" else 1e-5\n        x = relay.var(\"x\", shape=xshape, dtype=dtype)\n        bias = relay.var(\"bias\", shape=bshape, dtype=dtype)\n        z = relay.nn.bias_add(x, bias)\n        func = relay.Function([x, bias], z)\n\n        x_data = np.random.uniform(size=xshape).astype(dtype)\n        y_data = np.random.uniform(size=bshape).astype(dtype)\n\n        verify_results(func, [x_data, y_data], \"test_bias_add\", rtol=rtol)\n\n\ndef test_conv2d():\n    def verify_conv2d(\n        dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs\n    ):\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=dtype)\n        y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs)\n        func = relay.Function([x, w], y)\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        verify_results(func, [data, kernel], \"test_conv2d\", rtol=1e-5, atol=1e-5, is_dyn=True)\n\n    dshape = (1, 32, 18, 18)\n    kshape = (32, 1, 3, 3)\n    verify_conv2d(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=32, groups=32, kernel_size=(3, 3)\n    )\n\n    dshape = (1, 32, 18, 18)\n    kshape = (32, 4, 3, 3)\n    verify_conv2d(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=32, groups=8, kernel_size=(3, 3)\n    )\n\n    # also group conv2d\n    dshape = (1, 32, 18, 18)\n    kshape = (64, 1, 3, 3)\n    verify_conv2d(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=64, groups=32, kernel_size=(3, 3)\n    )\n\n    # normal conv2d\n    dshape = (1, 3, 224, 224)\n    kshape = (10, 3, 3, 3)\n    verify_conv2d(\"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3))\n\n    dshape = (1, 3, 224, 224)\n    kshape = (10, 3, 3, 3)\n    verify_conv2d(\"float32\", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3))\n\n    dshape = (1, 3, 18, 18)\n    kshape = (10, 3, 3, 3)\n    verify_conv2d(\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=10,\n        kernel_size=(3, 3),\n        dilation=(3, 3),\n    )\n\n    dshape = (1, 3, 18, 18)\n    kshape = (10, 3, 2, 2)\n    verify_conv2d(\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(2, 2),\n        channels=10,\n        kernel_size=(2, 2),\n        dilation=(1, 1),\n    )\n\n    dshape = (1, 3, 18, 18)\n    kshape = (10, 3, 4, 4)\n    verify_conv2d(\"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4))\n\n    dshape = (1, 3, 18, 18)\n    kshape = (10, 3, 4, 4)\n    verify_conv2d(\"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4))\n\n\ndef test_conv2d_transpose():\n    \"\"\"Conv2d_Transpose unit tests.\"\"\"\n\n    def verify_conv2d_transpose(\n        dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs\n    ):\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=dtype)\n        y = relay.nn.conv2d_transpose(\n            x, w, padding=padding, dilation=dilation, groups=groups, **attrs\n        )\n        func = relay.Function([x, w], y)\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        verify_results(func, [data, kernel], \"test_conv2d_transpose\", rtol=1e-5, atol=1e-5)\n\n    dshape = (1, 3, 224, 224)\n    kshape = (3, 10, 3, 3)\n    verify_conv2d_transpose(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3)\n    )\n\n    dshape = (1, 3, 224, 224)\n    kshape = (3, 10, 3, 3)\n    verify_conv2d_transpose(\n        \"float32\", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3)\n    )\n\n    dshape = (1, 3, 18, 18)\n    kshape = (3, 10, 2, 2)\n    verify_conv2d_transpose(\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(2, 2),\n        channels=10,\n        kernel_size=(2, 2),\n        dilation=(1, 1),\n    )\n\n    dshape = (1, 3, 18, 18)\n    kshape = (3, 10, 4, 4)\n    verify_conv2d_transpose(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)\n    )\n\n    dshape = (1, 3, 18, 18)\n    kshape = (3, 10, 4, 4)\n    verify_conv2d_transpose(\n        \"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)\n    )\n\n\ndef test_reshape():\n    def verify_reshape(shape, newshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.reshape(x, newshape=newshape)\n\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_reshape\", rtol=1e-5, atol=1e-5)\n\n    verify_reshape((2, 3, 4), tuple(np.array([4, 2, 3], dtype=np.int64)))\n    verify_reshape((2, 3, 4), tuple(np.array([2, 0, 0], dtype=np.int64)))\n    verify_reshape((2, 3, 4), tuple(np.array([0, -1], dtype=np.int64)))\n    verify_reshape((2, 3, 4), tuple(np.array([-1, 0], dtype=np.int64)))\n\n\ndef test_transpose():\n    def verify_reshape(shape, newshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.transpose(x, newshape)\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_transpose\", rtol=1e-5, atol=1e-5)\n\n    verify_reshape((1, 2, 3, 4), (0, 2, 3, 1))\n    verify_reshape((1, 2, 3, 4), (0, 3, 2, 1))\n\n\ndef test_dense():\n    def verify_dense(d_shape, w_shape):\n        data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType(w_shape, \"float32\"))\n        func = relay.Function([data, weight], relay.nn.dense(data, weight))\n        x_data = np.random.uniform(size=d_shape).astype(\"float32\")\n        w_data = np.random.uniform(size=w_shape).astype(\"float32\")\n        verify_results(func, [x_data, w_data], \"test_dense\", rtol=1e-5, atol=1e-5)\n\n    verify_dense((1, 8), (16, 8))\n    verify_dense((1, 4), (3, 4))\n\n\ndef test_max_pool():\n    def verify_max_pool(x_shape, pool_size, strides, padding, ceil_mode):\n        x = relay.var(\"x\", relay.TensorType(x_shape, \"float32\"))\n        y = tvm.relay.nn.max_pool2d(\n            x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode\n        )\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=x_shape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_max_pool\", rtol=1e-5, atol=1e-5)\n\n    verify_max_pool(\n        (1, 4, 16, 16), pool_size=(2, 2), strides=(2, 2), padding=(0, 0), ceil_mode=False\n    )\n\n\ndef test_batch_flatten():\n    def verify_test_batch_flatten(d_shape):\n        data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n        func = relay.Function([data], relay.nn.batch_flatten(data))\n        x_data = np.random.uniform(size=d_shape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_batch_flatten\", rtol=1e-5, atol=1e-5)\n\n    verify_test_batch_flatten((1, 2, 3, 4))\n    verify_test_batch_flatten((1, 8))\n\n\ndef test_batch_norm():\n    def verify_batch_norm(axis=1):\n        for dtype in [\"float16\", \"float32\"]:\n            data = relay.var(\"data\", relay.TensorType((2, 4, 4, 1), dtype))\n            gamma_shape = (data.type_annotation.shape[axis].value,)\n            beta = relay.var(\"beta\", relay.TensorType(gamma_shape, dtype))\n            gamma = relay.var(\"gamma\", relay.TensorType(gamma_shape, dtype))\n            moving_mean = relay.var(\"moving_mean\", relay.TensorType(gamma_shape, dtype))\n            moving_var = relay.var(\"moving_var\", relay.TensorType(gamma_shape, dtype))\n            y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var, axis=axis)\n            func = relay.Function([data, gamma, beta, moving_mean, moving_var], y[0])\n\n            x_data = np.random.uniform(size=(2, 4, 4, 1)).astype(dtype)\n            beta = np.random.uniform(size=gamma_shape).astype(dtype)\n            gamma = np.random.uniform(size=gamma_shape).astype(dtype)\n            moving_mean = np.random.uniform(size=gamma_shape).astype(dtype)\n            moving_var = np.random.uniform(size=gamma_shape).astype(dtype)\n            verify_results(\n                func,\n                [x_data, gamma, beta, moving_mean, moving_var],\n                \"test_batch_norm\",\n                rtol=1e-1,\n                atol=1e-1,\n            )\n\n    verify_batch_norm(axis=1)\n    verify_batch_norm(axis=3)\n\n\ndef test_pad():\n    \"\"\"Pad unit test.\"\"\"\n\n    def verify_pad():\n        dshape = (4, 10, 7, 7)\n        x = relay.var(\"x\", shape=dshape, dtype=\"int32\")\n        y = relay.nn.pad(x, ((1, 1), (2, 2), (3, 3), (4, 4)))\n        func = relay.Function([x], y)\n        func = run_infer_type(func)\n        x_data = np.random.randint(low=-255, high=255, size=dshape).astype(np.int32)\n        verify_results(func, [x_data], \"test_pad\", rtol=1e-5, atol=1e-5)\n\n    verify_pad()\n\n\ndef test_sofmax():\n    def verify_sofmax():\n        for dtype in [\"float32\"]:\n            shape = (10, 4)\n            x = relay.var(\"x\", shape=shape, dtype=dtype)\n            y = relay.nn.softmax(x, axis=1)\n            func = relay.Function([x], y)\n            x_data = np.random.uniform(size=shape).astype(dtype)\n            verify_results(func, [x_data], \"test_softmax\", rtol=1e-5, atol=1e-5)\n\n    verify_sofmax()\n\n\ndef test_squeeze():\n    def verify_squeeze(shape, dtype, axis):\n        x = relay.var(\"x\", relay.TensorType(shape, dtype))\n        z = relay.squeeze(x, axis=axis)\n        func = relay.Function([x], z)\n        x_data = np.random.random_sample(shape).astype(dtype)\n        verify_results(func, [x_data], \"test_squeeze\", rtol=1e-5, atol=1e-5)\n\n    verify_squeeze((1, 3, 2, 5), \"float32\", None)\n    verify_squeeze(\n        (1, 3, 1),\n        \"float32\",\n        [\n            2,\n        ],\n    )\n    verify_squeeze((1, 2, 1, 2, 1), \"float32\", [0, 2])\n\n\ndef test_mean():\n    def verify_mean(data_shape, axis, exclude, keepdims):\n        dtype = \"float32\"\n        x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n        y = relay.mean(x, axis, keepdims, exclude)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=data_shape).astype(dtype)\n        verify_results(func, [x_data], \"test_mean\", rtol=1e-5, atol=1e-5)\n\n    verify_mean((1, 2), 0, False, False)\n    verify_mean((1, 2), 0, True, False)\n    verify_mean((1, 2), 0, True, True)\n    verify_mean((1, 2), 1, True, True)\n    verify_mean((3, 2, 1), 1, False, True)\n\n\ndef test_split():\n    def verify_split(dshape, indices_or_sections, axis=None):\n        dtype = \"float32\"\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, \"float32\"))\n        y = relay.split(x, indices_or_sections, axis=axis)\n        func = relay.Function([x], y.astuple())\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n\n        verify_results(func, [x_data], \"test_split\", rtol=1e-5, atol=1e-5)\n\n    verify_split((5, 5, 2, 2), 5, axis=1)\n    verify_split((5, 5, 2, 2), 5, axis=0)\n    verify_split((5, 5, 2, 2), [1, 3, 4], axis=0)\n    verify_split((5, 5, 2, 2), [1, 3, 4], axis=1)\n\n\ndef test_concatenate():\n    def verify_concatenate(shapes, axis, dtype=\"float32\"):\n        in_vars = []\n        in_data = []\n        for i, shape in enumerate(shapes):\n            in_vars.append(relay.var(\"x\" + str(i), relay.ty.TensorType(shape, dtype)))\n            in_data.append(np.random.uniform(size=shape).astype(dtype))\n\n        out_tensor = relay.concatenate(in_vars, axis)\n        func = relay.Function(in_vars, out_tensor)\n        verify_results(func, in_data, \"test_concatenate\", rtol=1e-5, atol=1e-5)\n\n    verify_concatenate([(2,), (2,), (2,)], -1)\n    verify_concatenate([(2, 3, 4), (2, 2, 4), (2, 5, 4)], 1)\n    verify_concatenate([(1, 2, 4), (1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 1)], -1)\n    verify_concatenate([(5, 6, 7, 3), (16, 6, 7, 3), (12, 6, 7, 3), (8, 6, 7, 3), (2, 6, 7, 3)], 0)\n    verify_concatenate([(1, 14400), (1, 2400), (1, 640), (1, 240)], 1)\n\n\ndef test_strided_slice():\n    def verify_strided_slice(dshape, begin, end, strides, mode):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        if mode == \"size\":\n            strides = None\n        z = relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=mode)\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_strided_slice\", rtol=1e-5, atol=1e-5)\n\n    for mode in [\"end\", \"size\"]:\n        verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 2, 3], None, mode)\n        verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -1, 3], [1, 2], mode)\n        verify_strided_slice(\n            (3, 4, 3),\n            [\n                1,\n            ],\n            [4, -3],\n            None,\n            mode,\n        )\n        verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], mode)\n        verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, -3], [2, 1, 1], mode)\n        verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], mode)\n        verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2], mode)\n        verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], mode)\n\n        verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, mode)\n        verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4], None, mode)\n        verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], None, mode)\n        verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], [1, 1, 2], mode)\n\n\ndef test_cmp_type():\n    for op, ref in ((relay.greater, np.greater), (relay.less, np.less), (relay.equal, np.equal)):\n        x_shape = (10, 4)\n        y_shape = (5, 10, 1)\n        t1 = relay.TensorType(x_shape)\n        t2 = relay.TensorType(y_shape)\n        x = relay.var(\"x\", t1)\n        y = relay.var(\"y\", t2)\n        z = op(x, y)\n        x_data = np.random.rand(*x_shape).astype(t1.dtype)\n        y_data = np.random.rand(*y_shape).astype(t2.dtype)\n        func = relay.Function([x, y], z)\n        verify_results(func, [x_data, y_data], \"test_cmp_type\", rtol=1e-5, atol=1e-5)\n\n\ndef test_unary_identity():\n    for dtype in [\"int16\", \"float32\", \"float64\"]:\n        for op, ref in [(relay.zeros_like, np.zeros_like), (relay.ones_like, np.ones_like)]:\n            shape = (8, 9, 4)\n            x = relay.var(\"x\", relay.TensorType(shape, dtype))\n            y = op(x)\n            func = relay.Function(\n                [\n                    x,\n                ],\n                y,\n            )\n            x_data = np.random.rand(*shape).astype(dtype)\n            verify_results(func, [x_data], \"test_cmp_type\", rtol=1e-5, atol=1e-5)\n\n\ndef test_binary_op():\n    def check_binary_op(opfunc, dtype):\n        t1 = relay.TensorType((5, 10, 5))\n        t2 = relay.TensorType((5, 10, 5))\n        x = relay.var(\"x\", t1, dtype=dtype)\n        y = relay.var(\"y\", t2, dtype=dtype)\n        z = opfunc(x, y)\n        x_data = np.random.rand(5, 10, 5).astype(dtype)\n        y_data = np.random.rand(5, 10, 5).astype(dtype)\n        func = relay.Function([x, y], z)\n        verify_results(func, [x_data, y_data], \"test_binary_op\", rtol=1e-5, atol=1e-5)\n\n    for opfunc, ref in [\n        (relay.add, np.add),\n        (relay.subtract, np.subtract),\n        (relay.multiply, np.multiply),\n        (relay.divide, np.divide),\n    ]:\n        for dtype in [\"float32\"]:\n            check_binary_op(opfunc, dtype)\n\n\ndef test_tuple_types():\n    def verify_tuple_types(dshape, indices_or_sections, axis=None, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.split(x, indices_or_sections, axis=axis)\n        z = relay.concatenate(y, axis=axis)\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_tuple_types\", rtol=1e-5, atol=1e-5)\n\n        split_z = relay.split(z, indices_or_sections, axis=axis)\n        func = relay.Function([x], split_z.astuple())\n        verify_results(func, [x_data], \"test_tuple_types\", rtol=1e-5, atol=1e-5)\n\n        out = relay.Tuple([y[0] + y[1], y[0] - y[1]])\n        func = relay.Function([x], out)\n        verify_results(func, [x_data], \"test_tuple_types\", rtol=1e-5, atol=1e-5)\n\n        z = relay.concatenate(out, axis=axis)\n        func = relay.Function([x], z)\n        verify_results(func, [x_data], \"test_tuple_types\", rtol=1e-5, atol=1e-5)\n\n    verify_tuple_types((5, 5, 2, 2), 5, axis=1)\n    verify_tuple_types((5, 5, 2, 2), 5, axis=0)\n    verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=0)\n    verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=1)\n\n\ndef test_layout_transform():\n    def verify_layout_transform(dshape, src_layout, dst_layout, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.layout_transform(x, src_layout, dst_layout)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_layout_transform\", rtol=1e-5, atol=1e-5)\n\n    verify_layout_transform((1, 3, 8, 8), \"NCHW\", \"NHWC\")\n    verify_layout_transform((1, 8, 8, 3), \"NHWC\", \"NCHW\")\n\n\ndef test_clip():\n    def verify_clip(dshape, a_min, a_max, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.clip(x, a_min, a_max)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_clip\", rtol=1e-5, atol=1e-5)\n\n    verify_clip((5, 5, 2, 5), 0, 0.2)\n    verify_clip((5, 5, 2, 5), 0.2, 0.5)\n\n\ndef test_expand_dims():\n    def verify_expand_dims(dshape, axis, num_newaxis, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.expand_dims(x, axis, num_newaxis)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_expand_dims\", rtol=1e-5, atol=1e-5)\n\n    verify_expand_dims((1, 1001), 0, 2)\n    verify_expand_dims((1, 1, 1001), 2, 2)\n\n\ndef test_lrn():\n    \"\"\"LRN unit test.\"\"\"\n\n    def verify_lrn(xshape, size, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(xshape, dtype))\n        y = relay.nn.lrn(x, size=size, axis=1, alpha=1.0, beta=1.0, bias=1.0)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=xshape).astype(dtype)\n        verify_results(func, [x_data], \"test_lrn\", rtol=1e-5, atol=1e-5)\n\n    isize = [(1, 1, 480, 640), (1, 3, 224, 224)]\n    sizes = [1, 3]\n    for i in isize:\n        for s in sizes:\n            verify_lrn(i, s)\n\n\ndef test_sigmoid():\n    \"\"\"Sigmoid unit test.\"\"\"\n\n    def verify_sigmoid(dshape, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.sigmoid(x)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_sigmoid\", rtol=1e-4, atol=1e-4)\n\n    isize = [(1, 3, 480, 640), (1, 3, 224, 224)]\n\n    for i in isize:\n        verify_sigmoid(i)\n\n\ndef test_copy():\n    \"\"\"Copy unit test.\"\"\"\n\n    def verify_copy(dshape, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.copy(x)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_copy\", rtol=1e-4, atol=1e-4)\n\n    isize = [(1, 3, 480, 640), (1, 3, 224, 224)]\n\n    for i in isize:\n        verify_copy(i)\n\n\ndef test_round():\n    \"\"\"Round unit test.\"\"\"\n\n    def verify_round(dshape, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.round(x)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_round\", rtol=1e-4, atol=1e-4)\n\n    isize = [(1, 3, 480, 640), (1, 3, 224, 224)]\n\n    for i in isize:\n        verify_round(i)\n\n\ndef test_cast():\n    \"\"\"Cast unit test.\"\"\"\n\n    def verify_cast(dshape, dtype):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, \"float32\"))\n        y = relay.cast(x, dtype)\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        verify_results(func, [x_data], \"test_cast\", rtol=1e-4, atol=1e-4)\n\n    isize = [(1, 3, 480, 640), (1, 3, 224, 224)]\n    out_dtypes = [\"int8\", \"int16\", \"uint8\", \"uint16\"]\n\n    for i in isize:\n        for o_dtype in out_dtypes:\n            verify_cast(i, o_dtype)\n\n\n@pytest.mark.xfail(reason=\"Known failing test. See issue #12567.\")\ndef test_resize():\n    \"\"\"Resize unit test.\"\"\"\n\n    def verify_resize(dshape, outsize, method, coord_trans, rounding_method, dtype=\"float32\"):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        y = relay.image.resize2d(\n            x,\n            outsize,\n            None,\n            layout=\"NCHW\",\n            method=method,\n            coordinate_transformation_mode=coord_trans,\n            rounding_method=rounding_method,\n        )\n        func = relay.Function([x], y)\n        x_data = np.random.uniform(size=dshape).astype(dtype)\n        verify_results(func, [x_data], \"test_resize\", rtol=1e-4, atol=1e-4)\n\n    method = [\"nearest_neighbor\", \"linear\", \"cubic\"]\n    coord_trans = [\"half_pixel\", \"align_corners\", \"asymmetric\"]\n    rounding_method = [\"round\", \"floor\", \"ceil\"]\n\n    isize = (1, 3, 480, 640)\n\n    # Downsample\n    osize = (240, 320)\n    for i in method:\n        for j in coord_trans:\n            for k in rounding_method:\n                if (i == \"nearest_neighbor\" and j == \"align_corners\") or (\n                    i == \"cubic\" and j in [\"half_pixel\", \"align_corners\"]\n                ):\n                    continue\n                verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k)\n\n    # Upsample\n    osize = (960, 1280)\n    for i in method:\n        for j in coord_trans:\n            for k in rounding_method:\n                if (i == \"nearest_neighbor\" and j == \"align_corners\") or (i == \"cubic\"):\n                    continue\n                verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k)\n\n\ndef test_dyn():\n    \"\"\"Dynamic unit test.\"\"\"\n\n    def verify_dyn_bcast(lhs_shape, rhs_shape, dtype):\n        lhs_dyn_shape = tuple(relay.Any() for i in range(len(lhs_shape)))\n        rhs_dyn_shape = tuple(relay.Any() for i in range(len(rhs_shape)))\n        x = relay.var(\"x\", shape=lhs_dyn_shape, dtype=dtype)\n        y = relay.var(\"y\", shape=rhs_dyn_shape, dtype=dtype)\n        z = relay.add(x, y)\n        func = relay.Function([x, y], z)\n        lhs_data = np.random.uniform(size=lhs_shape).astype(dtype)\n        rhs_data = np.random.uniform(size=rhs_shape).astype(dtype)\n        verify_results(\n            func, [lhs_data, rhs_data], \"test_dyn_bcast\", rtol=1e-5, atol=1e-5, is_dyn=True\n        )\n\n    verify_dyn_bcast((1, 3, 32, 1), (1, 3, 1, 3), \"float32\")\n    verify_dyn_bcast((1, 13), (4, 3, 5, 1), \"float32\")\n\n\nif __name__ == \"__main__\":\n    test_add()\n    test_bias_add()\n    test_conv2d()\n    test_conv2d_transpose()\n    test_reshape()\n    test_transpose()\n    test_dense()\n    test_max_pool()\n    test_batch_flatten()\n    test_batch_norm()\n    test_pad()\n    test_mean()\n    test_split()\n    test_concatenate()\n    test_sofmax()\n    test_squeeze()\n    test_strided_slice()\n    test_cmp_type()\n    test_binary_op()\n    test_tuple_types()\n    test_layout_transform()\n    test_clip()\n    test_expand_dims()\n    test_lrn()\n    test_sigmoid()\n    test_copy()\n    test_round()\n    test_cast()\n    test_resize()\n    test_dyn()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_onnx_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Relay to ONNX target test cases\"\"\"\nimport pytest\n\npytest.importorskip(\"onnx\")\npytest.importorskip(\"onnxruntime\")\n\nfrom collections import OrderedDict\nimport numpy as np\nimport onnxruntime as rt\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib.target.onnx import to_onnx\nimport tvm.relay.testing\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.ir import IRModule\nfrom tvm.relay import transform\n\n\ndef func_to_onnx(mod, params, name):\n    onnx_model = to_onnx(mod, params, name, path=None)\n    return onnx_model.SerializeToString()\n\n\ndef run_onnx(mod, params, name, input_data):\n    onnx_model = func_to_onnx(mod, params, name)\n    sess = rt.InferenceSession(onnx_model)\n    input_names = {}\n    for input, data in zip(sess.get_inputs(), input_data):\n        input_names[input.name] = data\n    output_names = [output.name for output in sess.get_outputs()]\n    res = sess.run(output_names, input_names)\n    return res[0]\n\n\ndef get_data(in_data_shapes, dtype=\"float32\"):\n    in_data = OrderedDict()\n    for name, shape in in_data_shapes.items():\n        in_data[name] = np.random.uniform(size=shape).astype(dtype)\n    return in_data\n\n\ndef run_relay(mod, params, in_data):\n    target = \"llvm\"\n    dev = tvm.device(\"llvm\", 0)\n    in_data = [tvm.nd.array(value) for value in in_data.values()]\n    return (\n        relay.create_executor(\"graph\", mod, device=dev, target=target)\n        .evaluate()(*in_data, **params)\n        .numpy()\n    )\n\n\ndef _verify_results(mod, params, in_data):\n    a = run_relay(mod, params, in_data)\n    b = run_onnx(mod, params, \"test_resent\", in_data.values())\n    np.testing.assert_allclose(a, b, rtol=1e-7, atol=1e-7)\n\n\ndef test_resnet():\n    num_class = 1000\n    in_data_shapes = OrderedDict({\"data\": (1, 3, 224, 224)})\n    in_data = get_data(in_data_shapes, dtype=\"float32\")\n    for n in [18, 34, 50, 101]:\n        mod, params = tvm.relay.testing.resnet.get_workload(1, num_class, num_layers=n)\n        _verify_results(mod, params, in_data)\n\n\ndef test_squeezenet():\n    in_data_shapes = OrderedDict({\"data\": (1, 3, 224, 224)})\n    in_data = get_data(in_data_shapes, dtype=\"float32\")\n    for version in [\"1.0\", \"1.1\"]:\n        mod, params = tvm.relay.testing.squeezenet.get_workload(1, version=version)\n        _verify_results(mod, params, in_data)\n\n\n@pytest.mark.skip(\"USE_TARGET_ONNX should be ON\")\ndef test_partition():\n    in_1 = relay.var(\"in_1\", shape=(10, 10), dtype=\"float32\")\n    in_2 = relay.var(\"in_2\", shape=(10, 10), dtype=\"float32\")\n    in_3 = relay.var(\"in_3\", shape=(10, 10), dtype=\"float32\")\n    in_4 = relay.var(\"in_4\", shape=(10, 10), dtype=\"float32\")\n    in_5 = relay.var(\"in_5\", shape=(10, 10), dtype=\"float32\")\n    in_6 = relay.var(\"in_6\", shape=(10, 10), dtype=\"float32\")\n    in_7 = relay.var(\"in_7\", shape=(10, 10), dtype=\"float32\")\n    in_8 = relay.var(\"in_8\", shape=(10, 10), dtype=\"float32\")\n    in_9 = relay.var(\"in_9\", shape=(10, 10), dtype=\"float32\")\n    in_10 = relay.var(\"in_10\", shape=(10, 10), dtype=\"float32\")\n\n    begin0 = compiler_begin(in_1, \"onnx\")\n    begin1 = compiler_begin(in_2, \"onnx\")\n    begin2 = compiler_begin(in_3, \"onnx\")\n    begin3 = compiler_begin(in_4, \"onnx\")\n    node0 = relay.add(begin0, begin1)\n    node1 = relay.add(begin2, begin3)\n    end0 = compiler_end(node0, \"onnx\")\n    end1 = compiler_end(node1, \"onnx\")\n    begin4 = compiler_begin(end0, \"onnx\")\n    begin5 = compiler_begin(end1, \"onnx\")\n    node2 = relay.add(begin4, begin5)\n    end2 = compiler_end(node2, \"onnx\")\n\n    dbegin0 = compiler_begin(in_5, \"default\")\n    dbegin1 = compiler_begin(in_6, \"default\")\n    node3 = relay.subtract(dbegin0, dbegin1)\n    dbegin2 = compiler_begin(in_7, \"default\")\n    dend1 = compiler_end(node3, \"default\")\n    dbegin3 = compiler_begin(dend1, \"default\")\n    node4 = relay.subtract(dbegin2, dbegin3)\n    dend2 = compiler_end(node4, \"default\")\n\n    begin6 = compiler_begin(end2, \"onnx\")\n    begin7 = compiler_begin(dend2, \"onnx\")\n    node5 = relay.add(begin6, begin7)\n    end3 = compiler_end(node5, \"onnx\")\n    end4 = compiler_end(node5, \"onnx\")\n    dbegin4 = compiler_begin(in_8, \"default\")\n    dbegin5 = compiler_begin(end3, \"default\")\n    node6 = relay.subtract(dbegin4, dbegin5)\n    begin8 = compiler_begin(in_9, \"onnx\")\n    begin9 = compiler_begin(end4, \"onnx\")\n    node7 = relay.multiply(begin8, begin9)\n    end5 = compiler_end(node7, \"onnx\")\n\n    dend3 = compiler_end(node6, \"default\")\n    begin10 = compiler_begin(dend3, \"onnx\")\n    begin11 = compiler_begin(end5, \"onnx\")\n    node8 = relay.add(begin10, begin11)\n    end6 = compiler_end(node8, \"onnx\")\n    begin12 = compiler_begin(in_10, \"onnx\")\n    begin13 = compiler_begin(end6, \"onnx\")\n    node9 = relay.add(begin12, begin13)\n    end7 = compiler_end(node9, \"onnx\")\n\n    func = relay.Function([in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9, in_10], end7)\n\n    target = \"llvm\"\n    mod = IRModule.from_expr(func)\n    mod = transform.PartitionGraph()(mod)\n\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"FuseOps\"]):\n        graph_json, mod1, params = relay.build(mod, target)\n\n    assert mod1.type_key == \"metadata\"\n    assert mod1.imported_modules[0].type_key == \"llvm\"\n    assert mod1.imported_modules[0].get_source()\n    assert mod1.imported_modules[1].type_key == \"onnx\"\n    assert mod1.imported_modules[1].get_source()\n\n\nif __name__ == \"__main__\":\n    test_resnet()\n    test_squeezenet()\n    # test_partition needs USE_TARGET_ONNX to be ON\n    test_partition()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_opencl/test_run_gtests.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import rpc\n\n\n# use pytest -sv to observe gtest output\n# use --gtest_args to pass arguments to gtest\n# for example to run all \"foo\" tests twice and observe gtest output run\n# pytest -sv <this file> --gtests_args=\"--gtest_filter=*foo* --gtest_repeat=2\"\n@tvm.testing.requires_opencl\n@pytest.mark.skipif(tvm.testing.utils.IS_IN_CI, reason=\"failed due to nvidia libOpencl in the CI\")\ndef test_run_gtests(gtest_args):\n    if (\n        \"TVM_TRACKER_HOST\" in os.environ\n        and \"TVM_TRACKER_PORT\" in os.environ\n        and \"TVM_TRACKER_KEY\" in os.environ\n    ):\n        rpc_tracker_host = os.environ[\"TVM_TRACKER_HOST\"]\n        rpc_tracker_port = os.environ[\"TVM_TRACKER_PORT\"]\n        rpc_tracker_port = int(rpc_tracker_port)\n        rpc_key = os.environ[\"TVM_TRACKER_KEY\"]\n        tracker = rpc.connect_tracker(rpc_tracker_host, rpc_tracker_port)\n        rpc_connection = tracker.request(rpc_key, priority=0, session_timeout=600)\n    else:\n        rpc_connection = rpc.LocalSession()\n\n    try:\n        func = rpc_connection.get_function(\"opencl.run_gtests\")\n    except:\n        print(\n            \"This test requires TVM Runtime to be built with a OpenCL gtest version using OpenCL API cmake flag -DUSE_OPENCL_GTEST=/path/to/opencl/googletest/gtest\"\n        )\n        raise\n\n    gtest_error_code = func(gtest_args)\n    np.testing.assert_equal(gtest_error_code, 0)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_popen_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test PopenPoolExecutor.\"\"\"\nimport pytest\nimport os\nimport psutil\nimport time\nfrom tvm.contrib.popen_pool import PopenWorker, PopenPoolExecutor\nfrom tvm.testing import (\n    identity_after,\n    terminate_self,\n    initializer,\n    after_initializer,\n    register_ffi,\n    call_py_ffi,\n    call_cpp_ffi,\n    call_cpp_py_ffi,\n    fast_summation,\n    slow_summation,\n    timeout_job,\n)\n\n\ndef test_popen_worker():\n    proc = PopenWorker()\n\n    with pytest.raises(TimeoutError):\n        proc.send(identity_after, [1, 100], timeout=0.01)\n        proc.recv()\n\n    with pytest.raises(ChildProcessError):\n        proc.send(terminate_self)\n        proc.recv()\n\n    proc.send(identity_after, [2, 0])\n    assert proc.recv() == 2\n\n    proc.send(identity_after, [4, 0.0001])\n    assert proc.recv() == 4\n\n\ndef test_popen_worker_reuses():\n    proc = PopenWorker(maximum_uses=None)\n\n    proc.send(os.getpid)\n    initial_pid = proc.recv()\n\n    proc.send(os.getpid)\n    assert proc.recv() == initial_pid\n\n\ndef test_popen_worker_recycles():\n    proc = PopenWorker(maximum_uses=2)\n\n    proc.send(os.getpid)\n    initial_pid = proc.recv()\n    assert psutil.pid_exists(initial_pid)\n\n    proc.send(os.getpid)\n    assert proc.recv() == initial_pid\n    assert psutil.pid_exists(initial_pid)\n\n    proc.send(os.getpid)\n    assert proc.recv() != initial_pid\n    assert not psutil.pid_exists(initial_pid)\n\n\ndef test_popen_pool_executor():\n    import tvm\n\n    pool = PopenPoolExecutor(max_workers=2, timeout=0.01)\n    value1 = pool.submit(identity_after, 1, 100)\n    value2 = pool.submit(terminate_self)\n    value3 = pool.submit(identity_after, 3, 0)\n    value4 = pool.submit(tvm.runtime.String, \"xyz\")\n\n    with pytest.raises(TimeoutError):\n        value1.result()\n\n    with pytest.raises(ChildProcessError):\n        value2.result()\n\n    assert value3.result() == 3\n    value = value4.result()\n    assert isinstance(value, tvm.runtime.String)\n    assert value == \"xyz\"\n\n    pool = PopenPoolExecutor(max_workers=4, timeout=None)\n    values = pool.map_with_error_catching(lambda x: x, range(100))\n\n    for idx, val in enumerate(values):\n        assert val.value == idx\n\n\ndef test_popen_initializer():\n    initargs = [1, 2, 3]\n    proc = PopenWorker(initializer=initializer, initargs=initargs)\n    proc.send(after_initializer)\n    test_global_state_1, test_global_state_2, test_global_state_3 = proc.recv()\n    assert test_global_state_1 == initargs[0]\n    assert test_global_state_2 == initargs[1]\n    assert test_global_state_3 == initargs[2]\n\n\ndef test_popen_worker_recycles_with_initializer():\n    initargs = [1, 2, 3]\n    proc = PopenWorker(initializer=initializer, initargs=initargs, maximum_uses=3)\n\n    proc.send(os.getpid)\n    initial_pid = proc.recv()\n\n    proc.send(after_initializer)\n    assert list(proc.recv()) == initargs\n\n    proc.send(os.getpid)\n    assert proc.recv() == initial_pid\n\n    # The process should be recycled with this send.\n    proc.send(os.getpid)\n    assert proc.recv() != initial_pid\n\n    # But the initializer should've run this time as well.\n    proc.send(after_initializer)\n    assert list(proc.recv()) == initargs\n\n\ndef test_popen_ffi():\n    proc = PopenWorker(register_ffi)\n\n    # call python function via ffi\n    initargs = [0]\n    proc.send(call_py_ffi, initargs)\n    assert proc.recv() == initargs[0]\n\n    # call cpp function via ffi\n    initargs = [1]\n    proc.send(call_cpp_ffi, initargs)\n    assert proc.recv() == initargs[0]\n\n    # call python function from cpp function via ffi\n    initargs = [2]\n    proc.send(call_cpp_py_ffi, initargs)\n    assert proc.recv() == initargs[0]\n\n\ndef test_popen_pool_executor_timeout():\n    timeout = 0.5\n\n    pool = PopenPoolExecutor(timeout=timeout)\n\n    f1 = pool.submit(timeout_job, timeout)\n    while not f1.done():\n        pass\n    try:\n        res = f1.result()\n    except Exception as ex:\n        assert isinstance(ex, TimeoutError)\n\n\ndef test_popen_pool_executor_recycles():\n    pool = PopenPoolExecutor(max_workers=1, timeout=None, maximum_process_uses=2)\n\n    initial_pid = pool.submit(os.getpid).result()\n    assert initial_pid == pool.submit(os.getpid).result()\n    assert initial_pid != pool.submit(os.getpid).result()\n\n\nif __name__ == \"__main__\":\n    test_popen_worker()\n    test_popen_worker_recycles()\n    test_popen_pool_executor()\n    test_popen_initializer()\n    test_popen_worker_recycles_with_initializer()\n    test_popen_ffi()\n    test_popen_pool_executor_timeout()\n    test_popen_pool_executor_recycles()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_random.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import random\nfrom tvm import rpc\nimport tvm.testing\n\n\ndef test_randint():\n    m = 10240\n    n = 10240\n    A = random.randint(-127, 128, size=(m, n), dtype=\"int32\")\n    s = te.create_schedule(A.op)\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(\"tvm.contrib.random.randint\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        f = tvm.build(s, [A], target)\n        a = tvm.nd.array(np.zeros((m, n), dtype=A.dtype), dev)\n        f(a)\n        na = a.numpy()\n        assert abs(np.mean(na)) < 0.3\n        assert np.min(na) == -127\n        assert np.max(na) == 127\n\n    verify()\n\n\ndef test_uniform():\n    m = 10240\n    n = 10240\n    A = random.uniform(0, 1, size=(m, n))\n    s = te.create_schedule(A.op)\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(\"tvm.contrib.random.uniform\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        f = tvm.build(s, [A], target)\n        a = tvm.nd.array(np.zeros((m, n), dtype=A.dtype), dev)\n        f(a)\n        na = a.numpy()\n        assert abs(np.mean(na) - 0.5) < 1e-1\n        assert abs(np.min(na) - 0.0) < 1e-3\n        assert abs(np.max(na) - 1.0) < 1e-3\n\n    verify()\n\n\ndef test_normal():\n    m = 10240\n    n = 10240\n    A = random.normal(3, 4, size=(m, n))\n    s = te.create_schedule(A.op)\n\n    def verify(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(\"tvm.contrib.random.normal\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.cpu(0)\n        f = tvm.build(s, [A], target)\n        a = tvm.nd.array(np.zeros((m, n), dtype=A.dtype), dev)\n        f(a)\n        na = a.numpy()\n        assert abs(np.mean(na) - 3) < 1e-1\n        assert abs(np.std(na) - 4) < 1e-2\n\n    verify()\n\n\n@tvm.testing.uses_gpu\ndef test_random_fill():\n    def test_local(dev, dtype):\n        if not tvm.get_global_func(\"tvm.contrib.random.random_fill\", True):\n            print(\"skip because extern function is not available\")\n            return\n        value = tvm.nd.empty((512, 512), dtype, dev)\n        random_fill = tvm.get_global_func(\"tvm.contrib.random.random_fill\")\n        random_fill(value)\n\n        assert np.count_nonzero(value.numpy()) == 512 * 512\n\n        # make sure arithmentic doesn't overflow too\n        np_values = value.numpy()\n        assert np.isfinite(np_values * np_values + np_values).any()\n\n    def test_rpc(dtype):\n        if not tvm.get_global_func(\"tvm.contrib.random.random_fill\", True):\n            print(\"skip because extern function is not available\")\n            return\n        if not tvm.testing.device_enabled(\"rpc\") or not tvm.runtime.enabled(\"llvm\"):\n            return\n\n        np_ones = np.ones((512, 512), dtype=dtype)\n\n        def check_remote(server):\n            remote = rpc.connect(server.host, server.port)\n            value = tvm.nd.empty((512, 512), dtype, remote.cpu())\n            random_fill = remote.get_function(\"tvm.contrib.random.random_fill\")\n            random_fill(value)\n\n            assert np.count_nonzero(value.numpy()) == 512 * 512\n\n            # make sure arithmentic doesn't overflow too\n            np_values = value.numpy()\n            assert np.isfinite(np_values * np_values + np_values).any()\n\n        check_remote(rpc.Server(\"127.0.0.1\"))\n\n    for dtype in [\n        \"bool\",\n        \"int4\",\n        \"int8\",\n        \"uint8\",\n        \"int16\",\n        \"uint16\",\n        \"int32\",\n        \"int32\",\n        \"int64\",\n        \"uint64\",\n        \"float16\",\n        \"float32\",\n        \"float64\",\n    ]:\n        for _, dev in tvm.testing.enabled_targets():\n            test_local(dev, dtype)\n        test_rpc(dtype)\n\n\nif __name__ == \"__main__\":\n    test_randint()\n    test_uniform()\n    test_normal()\n    test_random_fill()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_rocblas.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nimport tvm.topi.testing\nimport tvm.testing\nfrom tvm.contrib import rocblas\n\n\n@tvm.testing.requires_rocm\ndef test_matmul():\n    n = 1024\n    l = 128\n    m = 235\n    A = te.placeholder((n, l), name=\"A\")\n    B = te.placeholder((l, m), name=\"B\")\n    C = rocblas.matmul(A, B)\n    s = te.create_schedule(C.op)\n\n    def verify(target=\"rocm\"):\n        if not tvm.get_global_func(\"tvm.contrib.rocblas.matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.rocm(0)\n        f = tvm.build(s, [A, B, C], target)\n        a = tvm.nd.array(np.random.uniform(size=(n, l)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(l, m)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), np.dot(a.numpy(), b.numpy()), rtol=1e-5)\n\n    verify()\n\n\ndef verify_batch_matmul(batch, m, k, n, lib, transa=False, transb=False, dtype=\"float32\"):\n    ashape = (batch, k, m) if transa else (batch, m, k)\n    bshape = (batch, n, k) if transb else (batch, k, n)\n    A = te.placeholder(ashape, name=\"A\", dtype=dtype)\n    B = te.placeholder(bshape, name=\"B\", dtype=dtype)\n    C = lib.batch_matmul(A, B, transa, transb)\n    s = te.create_schedule(C.op)\n\n    def get_numpy(a, b, transa, transb):\n        if transa:\n            a = a.transpose(0, 2, 1)\n        if not transb:\n            b = b.transpose(0, 2, 1)\n        return tvm.topi.testing.batch_matmul(a, b)\n\n    def verify(target=\"rocm\"):\n        if not tvm.testing.device_enabled(target):\n            print(\"skip because %s is not enabled...\" % target)\n            return\n        if not tvm.get_global_func(lib.__name__ + \".batch_matmul\", True):\n            print(\"skip because extern function is not available\")\n            return\n        dev = tvm.rocm(0)\n        f = tvm.build(s, [A, B, C], target)\n        a = tvm.nd.array(np.random.uniform(size=ashape).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=bshape).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((batch, m, n), dtype=C.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(\n            c.numpy(), get_numpy(a.numpy(), b.numpy(), transa, transb), rtol=1e-5\n        )\n\n    verify()\n\n\n@tvm.testing.requires_rocm\ndef test_batch_matmul():\n    verify_batch_matmul(128, 64, 512, 512, rocblas, transa=False, transb=False)\n    verify_batch_matmul(128, 64, 512, 512, rocblas, transa=False, transb=True)\n    verify_batch_matmul(128, 64, 512, 512, rocblas, transa=True, transb=False)\n    verify_batch_matmul(128, 64, 512, 512, rocblas, transa=True, transb=True)\n    verify_batch_matmul(128, 512, 512, 64, rocblas, transa=False, transb=False)\n    verify_batch_matmul(128, 512, 512, 64, rocblas, transa=False, transb=True)\n    verify_batch_matmul(128, 512, 512, 64, rocblas, transa=True, transb=False)\n    verify_batch_matmul(128, 512, 512, 64, rocblas, transa=True, transb=True)\n    verify_batch_matmul(128, 512, 64, 512, rocblas, transa=False, transb=False)\n    verify_batch_matmul(128, 512, 64, 512, rocblas, transa=False, transb=True)\n    verify_batch_matmul(128, 512, 64, 512, rocblas, transa=True, transb=False)\n    verify_batch_matmul(128, 512, 64, 512, rocblas, transa=True, transb=True)\n    verify_batch_matmul(128, 64, 128, 128, rocblas, transa=False, transb=False)\n    verify_batch_matmul(128, 64, 128, 128, rocblas, transa=False, transb=True)\n    verify_batch_matmul(128, 64, 128, 128, rocblas, transa=True, transb=False)\n    verify_batch_matmul(128, 64, 128, 128, rocblas, transa=True, transb=True)\n    verify_batch_matmul(128, 128, 128, 64, rocblas, transa=False, transb=False)\n    verify_batch_matmul(128, 128, 128, 64, rocblas, transa=False, transb=True)\n    verify_batch_matmul(128, 128, 128, 64, rocblas, transa=True, transb=False)\n    verify_batch_matmul(128, 128, 128, 64, rocblas, transa=True, transb=True)\n\n\nif __name__ == \"__main__\":\n    test_matmul()\n    test_batch_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_rpc_proxy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport logging\nimport numpy as np\nimport time\nimport multiprocessing\nfrom tvm import rpc\n\n\ndef rpc_proxy_check():\n    \"\"\"This is a simple test function for RPC Proxy\n\n    It is not included as pytests, because:\n    - It depends on tornado\n    - It relies on the fact that Proxy starts before client and server connects,\n      which is often the case but not always\n\n    User can directly run this script to verify correctness.\n    \"\"\"\n\n    try:\n        from tvm.rpc import proxy\n\n        web_port = 8888\n        prox = proxy.Proxy(\"127.0.0.1\", web_port=web_port)\n\n        def check():\n            if not tvm.runtime.enabled(\"rpc\"):\n                return\n\n            server = multiprocessing.Process(\n                target=proxy.websocket_proxy_server, args=(\"ws://localhost:%d/ws\" % web_port, \"x1\")\n            )\n            # Need to make sure that the connection start after proxy comes up\n            time.sleep(0.1)\n            server.deamon = True\n            server.start()\n            client = rpc.connect(prox.host, prox.port, key=\"x1\")\n            f1 = client.get_function(\"testing.echo\")\n            assert f1(10) == 10\n            assert f1(\"xyz\") == \"xyz\"\n\n        check()\n    except ImportError:\n        print(\"Skipping because tornado is not avaliable...\")\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n    rpc_proxy_check()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_rpc_server_device.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"iOS RPC Server tests.\"\"\"\n# pylint: disable=invalid-name, no-value-for-parameter, missing-function-docstring, import-error\nimport sys\nimport multiprocessing\nimport pytest\nimport numpy as np\n\nimport tvm.testing\nimport tvm.relay.testing\nfrom tvm import te\nfrom tvm import rpc\nfrom tvm import relay, auto_scheduler\nfrom tvm.contrib import utils, xcode, graph_executor\nfrom tvm.autotvm.measure import request_remote\nfrom tvm.auto_scheduler.measure_record import load_records\nfrom tvm.auto_scheduler.measure import MeasureErrorNo\nfrom tvm.auto_scheduler.utils import call_func_with_timeout\nfrom tvm.contrib.popen_pool import PopenWorker, StatusKind\nfrom tvm.rpc import tracker, proxy, server_ios_launcher\n\n\nHOST_URL = \"0.0.0.0\"\nHOST_PORT = 9190\nDEVICE_KEY = \"ios_mobile_device\"\n\n\nTEMPORARY_DIRECTORY = utils.tempdir()\nARCH = \"x86_64\"\nSDK = \"iphonesimulator\"\nDSO_NAME = \"lib.dylib\"\nDTYPE = \"float32\"\n\n\nnp.random.seed(0)\n\n\nios_rpc_bundle_description_required = pytest.mark.skipif(\n    not server_ios_launcher.ServerIOSLauncher.is_compatible_environment(),\n    reason=\"To run this test, you need to set environment variables required in ServerIOSLauncher.\",\n)\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef setup_and_teardown_actions():\n    \"\"\"Setup and teardown actions for pytest.\"\"\"\n\n    # No setup actions\n    yield\n    # Teardown actions:\n    server_ios_launcher.ServerIOSLauncher.shutdown_booted_devices()\n\n\ndef setup_rpc_standalone_configuration(f):\n    \"\"\"\n    Host  --  RPC server\n    \"\"\"\n\n    def wrapper():\n        with server_ios_launcher.ServerIOSContextManager(\n            mode=server_ios_launcher.RPCServerMode.standalone.value,\n            host=HOST_URL,\n            port=HOST_PORT,\n            key=DEVICE_KEY,\n        ) as ios_server:\n            f(host=ios_server.host, port=ios_server.port)\n\n    return wrapper\n\n\ndef setup_rpc_proxy_configuration(f):\n    \"\"\"\n    Host -- Proxy -- RPC server\n    \"\"\"\n\n    def wrapper():\n        proxy_server = proxy.Proxy(host=HOST_URL, port=HOST_PORT)\n        with server_ios_launcher.ServerIOSContextManager(\n            mode=server_ios_launcher.RPCServerMode.proxy.value,\n            host=proxy_server.host,\n            port=proxy_server.port,\n            key=DEVICE_KEY,\n        ):\n            f(host=proxy_server.host, port=proxy_server.port)\n        proxy_server.terminate()\n\n    return wrapper\n\n\ndef setup_rpc_tracker_configuration(f):\n    \"\"\"\n         tracker\n         /     \\\n    Host   --   RPC server\n    \"\"\"\n\n    def wrapper():\n        tracker_server = tracker.Tracker(host=HOST_URL, port=HOST_PORT, silent=True)\n        with server_ios_launcher.ServerIOSContextManager(\n            mode=server_ios_launcher.RPCServerMode.tracker.value,\n            host=tracker_server.host,\n            port=tracker_server.port,\n            key=DEVICE_KEY,\n        ):\n            f(host=tracker_server.host, port=tracker_server.port)\n        tracker_server.terminate()\n\n    return wrapper\n\n\ndef setup_rpc_tracker_via_proxy_configuration(f):\n    \"\"\"\n         tracker\n         /     \\\n    Host   --   Proxy -- RPC server\n    \"\"\"\n\n    def wrapper():\n        tracker_server = tracker.Tracker(host=HOST_URL, port=HOST_PORT, silent=True)\n        proxy_server_tracker = proxy.Proxy(\n            host=HOST_URL, port=8888, tracker_addr=(tracker_server.host, tracker_server.port)\n        )\n        with server_ios_launcher.ServerIOSContextManager(\n            mode=server_ios_launcher.RPCServerMode.proxy.value,\n            host=proxy_server_tracker.host,\n            port=proxy_server_tracker.port,\n            key=DEVICE_KEY,\n        ):\n            f(host=tracker_server.host, port=tracker_server.port)\n        proxy_server_tracker.terminate()\n        tracker_server.terminate()\n\n    return wrapper\n\n\ndef wrapper_for_call_function_with_timeout(timeout, func, args=(), kwargs=None):\n    \"\"\"Wrapper for call_func_with_timeout.\"\"\"\n\n    def wrapper(*_args, **_kwargs):\n        \"\"\"\n        This wrapper is needed because the cloudpicle\n        cannot serialize objects that contain pointers (RPCSession)\n        \"\"\"\n        func(*_args, **_kwargs)\n        return StatusKind.COMPLETE\n\n    worker = PopenWorker()\n    ret = call_func_with_timeout(worker, timeout=timeout, func=wrapper, args=args, kwargs=kwargs)\n    if isinstance(ret, Exception):\n        raise ret\n    return ret\n\n\ndef try_create_remote_session(session_factory, args=(), kwargs=None):\n    \"\"\"Deadlock-safe RPC Session creation.\"\"\"\n\n    try:\n        successful_attempt = True\n        results = []\n        for _ in range(2):\n            ret = wrapper_for_call_function_with_timeout(\n                timeout=10, func=session_factory, args=args, kwargs=kwargs\n            )\n            results.append(ret)\n        if not np.all(np.array(results) == StatusKind.COMPLETE):\n            raise ValueError(\"One or more sessions ended incorrectly.\")\n    except Exception as e:  # pylint: disable=broad-except\n        successful_attempt = False\n        print(e)\n    return successful_attempt\n\n\ndef ios_create_dylib(output, objects, **kwargs):  # pylint: disable=unused-argument\n    xcode.create_dylib(output, objects, arch=ARCH, sdk=SDK)\n\n\nios_create_dylib.output_format = \"dylib\"\n\n\ndef export_lib(lib):\n    \"\"\"Export lib to temporary directory.\"\"\"\n\n    path_dso = TEMPORARY_DIRECTORY.relpath(DSO_NAME)\n    lib.export_library(path_dso, fcompile=ios_create_dylib)\n    return path_dso\n\n\ndef get_add_relay_module(a_numpy, b_numpy):\n    \"\"\"Get simple relay module that add two tensors.\"\"\"\n\n    a = relay.var(\"a\", shape=a_numpy.shape, dtype=DTYPE)\n    b = relay.var(\"b\", shape=b_numpy.shape, dtype=DTYPE)\n    params = {}\n    out = tvm.IRModule.from_expr(relay.add(a, b))\n    return out, params\n\n\ndef get_add_module(target):\n    \"\"\"Get simple module that add two tensors.\"\"\"\n\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n    return tvm.build(s, [A, B, C], target=target, target_host=target, name=\"simple_add\")\n\n\n@pytest.mark.dependency()\n@ios_rpc_bundle_description_required\n@setup_rpc_standalone_configuration\ndef test_rpc_standalone(host, port):\n    status_ok = try_create_remote_session(session_factory=rpc.connect, args=(host, port))\n    assert status_ok\n\n\n@pytest.mark.dependency()\n@ios_rpc_bundle_description_required\n@setup_rpc_proxy_configuration\ndef test_rpc_proxy(host, port):\n    status_ok = try_create_remote_session(\n        session_factory=rpc.connect, args=(host, port, DEVICE_KEY)\n    )\n    assert status_ok\n\n\n@pytest.mark.dependency()\n@ios_rpc_bundle_description_required\n@setup_rpc_tracker_configuration\ndef test_rpc_tracker(host, port):\n    status_ok = try_create_remote_session(\n        session_factory=request_remote, args=(DEVICE_KEY, host, port)\n    )\n    assert status_ok\n\n\n@pytest.mark.dependency()\n@ios_rpc_bundle_description_required\n@setup_rpc_tracker_via_proxy_configuration\ndef test_rpc_tracker_via_proxy(host, port):\n    status_ok = try_create_remote_session(\n        session_factory=request_remote, args=(DEVICE_KEY, host, port)\n    )\n    assert status_ok\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_standalone\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_standalone_configuration\ndef test_can_call_remote_function_with_rpc_standalone(host, port):\n    remote_session = rpc.connect(host, port)\n    f = remote_session.get_function(\"runtime.GetFFIString\")\n    assert f(\"hello\") == \"hello\"\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_proxy\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_proxy_configuration\ndef test_can_call_remote_function_with_rpc_proxy(host, port):\n    remote_session = rpc.connect(host, port, key=DEVICE_KEY)\n    f = remote_session.get_function(\"runtime.GetFFIString\")\n    assert f(\"hello\") == \"hello\"\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_tracker\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_tracker_configuration\ndef test_can_call_remote_function_with_rpc_tracker(host, port):\n    remote_session = request_remote(DEVICE_KEY, host, port)\n    f = remote_session.get_function(\"runtime.GetFFIString\")\n    assert f(\"hello\") == \"hello\"\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_tracker_via_proxy\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_tracker_via_proxy_configuration\ndef test_can_call_remote_function_with_rpc_tracker_via_proxy(host, port):\n    remote_session = request_remote(DEVICE_KEY, host, port)\n    f = remote_session.get_function(\"runtime.GetFFIString\")\n    assert f(\"hello\") == \"hello\"\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_standalone\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_standalone_configuration\ndef test_basic_functionality_of_rpc_session(host, port):\n    remote_session = rpc.connect(host, port)\n    device = remote_session.cpu(0)\n\n    target = tvm.target.Target(target=f\"llvm -mtriple={ARCH}-apple-darwin\")\n    lib = get_add_module(target)\n    path_dso = export_lib(lib)\n\n    # Check correct upload\n    remote_session.upload(path_dso)\n\n    # Check correct download\n    downloaded_lib = remote_session.download(DSO_NAME)\n    with open(path_dso, \"rb\") as source_lib_file:\n        assert downloaded_lib == bytearray(\n            source_lib_file.read()\n        ), \"The downloaded module does not match the loaded module\"\n\n    # Check correct remote computing\n    lib = remote_session.load_module(DSO_NAME)\n    n = 100\n    a = tvm.nd.array(np.random.uniform(size=n).astype(DTYPE), device)\n    b = tvm.nd.array(np.random.uniform(size=n).astype(DTYPE), device)\n    c = tvm.nd.array(np.zeros(n, dtype=DTYPE), device)\n    lib(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    # Check correct remove\n    remote_session.remove(DSO_NAME)\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_standalone\"])\n@pytest.mark.xfail(reason=\"Not implemented functionality\")\n@ios_rpc_bundle_description_required\n@setup_rpc_standalone_configuration\ndef test_cleanup_workspace_after_session_end(host, port):\n    # Arrange\n    remote_session = rpc.connect(host, port)\n    target = tvm.target.Target(target=f\"llvm -mtriple={ARCH}-apple-darwin\")\n    lib = get_add_module(target)\n    path_dso = export_lib(lib)\n    remote_session.upload(path_dso)\n\n    # Act\n    del remote_session\n    remote_session = rpc.connect(host, port)\n    try:\n        remote_session.download(DSO_NAME)\n        status_ok = False\n    except Exception as _:  # pylint: disable=broad-except\n        status_ok = True\n\n    # Assert\n    assert status_ok, \"Workspace not cleared after RPC Session termination.\"\n\n\n@pytest.mark.dependency(depends=[\"test_rpc_standalone\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_standalone_configuration\ndef test_graph_executor_remote_run(host, port):\n    remote_session = rpc.connect(host, port)\n    target = tvm.target.Target(target=f\"llvm -mtriple={ARCH}-apple-darwin\")\n    device = remote_session.cpu(0)\n\n    size = 100\n    a = np.random.uniform(size=size).astype(DTYPE)\n    b = np.random.uniform(size=size).astype(DTYPE)\n    mod, params = get_add_relay_module(a, b)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, target_host=target, params=params)\n\n    path_dso = export_lib(lib)\n    remote_session.upload(path_dso)\n    lib = remote_session.load_module(DSO_NAME)\n\n    gen_module = graph_executor.GraphModule(lib[\"default\"](device))\n\n    # Check set input\n    gen_module.set_input(\"a\", tvm.nd.array(a))\n    gen_module.set_input(\"b\", tvm.nd.array(b))\n    tvm.testing.assert_allclose(gen_module.get_input(0).numpy(), a)\n    tvm.testing.assert_allclose(gen_module.get_input(1).numpy(), b)\n\n    # Check run\n    gen_module.run()\n    out = gen_module.get_output(0)\n    tvm.testing.assert_allclose(out.numpy(), a + b)\n\n\n@pytest.mark.xfail(\n    strict=False, reason=\"flaky test (see https://github.com/apache/tvm/issues/9824)\"\n)\n@pytest.mark.dependency(depends=[\"test_rpc_tracker\"])\n@ios_rpc_bundle_description_required\n@setup_rpc_tracker_configuration\ndef test_check_auto_schedule_tuning(host, port):  # pylint: disable=too-many-locals\n    log_file = TEMPORARY_DIRECTORY.relpath(\"ios_tuning_stat.log\")\n    target = tvm.target.Target(target=f\"llvm -mtriple={ARCH}-apple-darwin\")\n    mod, params = relay.testing.mlp.get_workload(batch_size=4, image_shape=(1, 4, 4))\n\n    try:\n        status_ok = True\n        measure_runner = auto_scheduler.RPCRunner(\n            DEVICE_KEY,\n            host,\n            port,\n            min_repeat_ms=1,\n            timeout=10,\n            n_parallel=multiprocessing.cpu_count(),\n        )\n        builder = auto_scheduler.LocalBuilder(timeout=10, build_func=ios_create_dylib)\n        tune_option = auto_scheduler.TuningOptions(\n            builder=builder,\n            num_measure_trials=2,\n            num_measures_per_round=1,\n            runner=measure_runner,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n            verbose=0,\n        )\n\n        tasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n        tasks, task_weights = tasks[:2], task_weights[:2]\n        tuner = auto_scheduler.TaskScheduler(tasks, task_weights)\n        tuner.tune(tune_option, search_policy=\"sketch.random\")\n\n        # Check tuning log\n        tuning_statistic = list(load_records(log_file))\n        for _, measure_result in tuning_statistic:\n            if measure_result.error_no != MeasureErrorNo.NO_ERROR:\n                raise ValueError(\n                    f\"Error for MeasureResult. Error code: {measure_result.error_no},\"\n                    f\" for details see MeasureErrorNO.\"\n                )\n\n    except Exception as e:  # pylint: disable=broad-except\n        status_ok = False\n        print(e)\n\n    assert status_ok, \"Tuning failed, see logs.\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_rpc_tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport logging\nimport numpy as np\nimport time\nimport multiprocessing\nfrom tvm import rpc\n\n\ndef check_server_drop():\n    \"\"\"test when server drops\"\"\"\n    try:\n        from tvm.rpc import tracker, proxy, base\n        from tvm.rpc.base import TrackerCode\n\n        @tvm.register_func(\"rpc.test2.addone\")\n        def addone(x):\n            return x + 1\n\n        def _put(tclient, value):\n            base.sendjson(tclient._sock, value)\n            base.recvjson(tclient._sock)\n\n        tserver = tracker.Tracker(\"127.0.0.1\", 8888)\n        tproxy = proxy.Proxy(\"127.0.0.1\", 8881, tracker_addr=(\"127.0.0.1\", tserver.port))\n        tclient = rpc.connect_tracker(\"127.0.0.1\", tserver.port)\n\n        server0 = rpc.Server(\n            \"127.0.0.1\", port=9099, tracker_addr=(\"127.0.0.1\", tserver.port), key=\"abc\"\n        )\n        server1 = rpc.Server(\n            \"127.0.0.1\", port=9099, tracker_addr=(\"127.0.0.1\", tserver.port), key=\"xyz\"\n        )\n        server2 = rpc.Server(\"127.0.0.1\", tproxy.port, is_proxy=True, key=\"xyz\")\n        server3 = rpc.Server(\"127.0.0.1\", tproxy.port, is_proxy=True, key=\"xyz1\")\n\n        # Fault tolerence to un-handled requested value\n        _put(tclient, [TrackerCode.REQUEST, \"abc\", \"\", 1])\n        _put(tclient, [TrackerCode.REQUEST, \"xyz1\", \"\", 1])\n\n        # Fault tolerence to stale worker value\n        _put(tclient, [TrackerCode.PUT, \"xyz\", (server1.port, \"abc\")])\n        _put(tclient, [TrackerCode.PUT, \"xyz\", (server1.port, \"abcxxx\")])\n        _put(tclient, [TrackerCode.PUT, \"xyz\", (tproxy.port, \"abcxxx11\")])\n\n        # Fault tolerence server timeout\n        def check_timeout(timeout, sleeptime):\n            def myfunc(remote):\n                time.sleep(sleeptime)\n                f1 = remote.get_function(\"rpc.test2.addone\")\n                assert f1(10) == 11\n\n            try:\n                tclient.request_and_run(\"xyz\", myfunc, session_timeout=timeout)\n            except RuntimeError:\n                pass\n            print(tclient.text_summary())\n            try:\n                remote = tclient.request(\"xyz\", priority=0, session_timeout=timeout)\n                remote2 = tclient.request(\"xyz\", session_timeout=timeout)\n                time.sleep(sleeptime)\n                f1 = remote.get_function(\"rpc.test2.addone\")\n                assert f1(10) == 11\n                f1 = remote2.get_function(\"rpc.test2.addone\")\n                assert f1(10) == 11\n\n            except tvm.error.TVMError as e:\n                pass\n            remote3 = tclient.request(\"abc\")\n            f1 = remote3.get_function(\"rpc.test2.addone\")\n            remote3 = tclient.request(\"xyz1\")\n            f1 = remote3.get_function(\"rpc.test2.addone\")\n            assert f1(10) == 11\n\n        check_timeout(0.01, 0.1)\n        check_timeout(2, 0)\n        tserver.terminate()\n        server0.terminate()\n        server1.terminate()\n        server2.terminate()\n        server3.terminate()\n        tproxy.terminate()\n    except ImportError:\n        print(\"Skip because tornado is not available\")\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n    check_server_drop()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_sort.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.topi.cuda import sort_by_key\nimport numpy as np\n\n\ndef test_sort():\n    n = 2\n    l = 5\n    m = 3\n    data = te.placeholder((n, l, m), name=\"data\")\n    sort_num = te.placeholder((n, m), name=\"sort_num\", dtype=\"int32\")\n    axis = 1\n    is_ascend = False\n    out = te.extern(\n        data.shape,\n        [data, sort_num],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.sort.argsort_nms\", ins[0], ins[1], outs[0], axis, is_ascend\n        ),\n        dtype=\"int32\",\n        name=\"sort_tensor\",\n    )\n    input = [\n        [[1, 2, 3], [2, 4.5, 3.5], [1.1, 0.5, 1], [3.2, -5, 0.5], [1.5, 0, 0]],\n        [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]],\n    ]\n    sort_num_input = [[1, 2, 3], [4, 5, 5]]\n    sorted_index = [\n        [[0, 1, 1], [1, 0, 0], [2, 2, 2], [3, 3, 3], [4, 4, 4]],\n        [[3, 4, 4], [2, 3, 3], [1, 2, 2], [0, 1, 1], [4, 0, 0]],\n    ]\n\n    dev = tvm.cpu(0)\n    target = \"llvm\"\n    s = te.create_schedule(out.op)\n    f = tvm.build(s, [data, sort_num, out], target)\n    a = tvm.nd.array(np.array(input).astype(data.dtype), dev)\n    b = tvm.nd.array(np.array(sort_num_input).astype(sort_num.dtype), dev)\n    c = tvm.nd.array(np.zeros(a.shape, dtype=out.dtype), dev)\n    f(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), np.array(sorted_index).astype(out.dtype), rtol=1e-5)\n\n\ndef test_sort_np():\n    dshape = (1, 2, 3, 4, 5, 6)\n    axis = 4\n    reduced_shape = (1, 2, 3, 4, 6)\n    is_ascend = True\n    data = te.placeholder(dshape, name=\"data\")\n    sort_num = te.placeholder(reduced_shape, name=\"sort_num\", dtype=\"int32\")\n    out = te.extern(\n        data.shape,\n        [data, sort_num],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.sort.argsort_nms\", ins[0], ins[1], outs[0], axis, is_ascend\n        ),\n        dtype=\"int32\",\n        name=\"sort_tensor\",\n    )\n\n    dev = tvm.cpu(0)\n    target = \"llvm\"\n    s = te.create_schedule(out.op)\n    f = tvm.build(s, [data, sort_num, out], target)\n\n    np_data = np.random.uniform(size=dshape)\n    np_out = np.argsort(np_data, axis=axis)\n    sort_num_input = np.full(reduced_shape, dshape[axis])\n    a = tvm.nd.array(np.array(np_data).astype(data.dtype), dev)\n    b = tvm.nd.array(np.array(sort_num_input).astype(sort_num.dtype), dev)\n    c = tvm.nd.array(np.zeros(a.shape, dtype=out.dtype), dev)\n    f(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), np_out, rtol=1e-5)\n\n\ndef test_sort_by_key_gpu():\n    size = 6\n    keys = te.placeholder((size,), name=\"keys\", dtype=\"int32\")\n    values = te.placeholder((size,), name=\"values\", dtype=\"int32\")\n\n    for target in [\"cuda\", \"nvptx\", \"opencl\", \"rocm\"]:\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            continue\n\n        with tvm.target.Target(target):\n            keys_out, values_out = sort_by_key(keys, values)\n            dev = tvm.device(target)\n            s = te.create_schedule([keys_out.op, values_out.op])\n            f = tvm.build(s, [keys, values, keys_out, values_out], target)\n\n            keys_np = np.array([1, 4, 2, 8, 2, 7], np.int32)\n            values_np = np.random.randint(0, 10, size=(size,)).astype(np.int32)\n            keys_np_out = np.zeros(keys_np.shape, np.int32)\n            values_np_out = np.zeros(values_np.shape, np.int32)\n            keys_in = tvm.nd.array(keys_np, dev)\n            values_in = tvm.nd.array(values_np, dev)\n            keys_out = tvm.nd.array(keys_np_out, dev)\n            values_out = tvm.nd.array(values_np_out, dev)\n            f(keys_in, values_in, keys_out, values_out)\n\n            ref_keys_out = np.sort(keys_np)\n            ref_values_out = np.array([values_np[i] for i in np.argsort(keys_np)])\n            tvm.testing.assert_allclose(keys_out.numpy(), ref_keys_out, rtol=1e-5)\n            tvm.testing.assert_allclose(values_out.numpy(), ref_values_out, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_sort()\n    test_sort_np()\n    test_sort_by_key_gpu()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport tvm.contrib.sparse as tvmsp\nimport tvm.runtime.ndarray as _nd\nimport numpy as np\nfrom collections import namedtuple\n\n\ndef test_static_tensor():\n    dtype = \"float32\"\n    stype = \"csr\"\n    target = \"llvm\"\n    dev = tvm.device(target, 0)\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = tvmsp.placeholder(shape=(m, n), name=\"A\", dtype=dtype)\n    assert A.stype == \"csr\"\n    n = 3\n    a = np.maximum(np.random.uniform(size=(n, n)).astype(dtype) - 0.6, 0.0)\n    a = tvmsp.array(a, dev)\n    A.data = te.placeholder(a.data.shape, dtype, name=\"A_data\")\n    Ab = tvm.tir.decl_buffer(a.data.shape, dtype, name=\"A_data\")\n    binds = {A.data: Ab}\n    C = te.compute(A.data.shape, lambda i: A.data[i] * 2.0, tag=\"cs_scatter\")\n    s = te.create_schedule(C.op)\n    f = tvm.build(s, [A.data, C], target, binds=binds)\n    c = tvmsp.array(np.zeros((n, n), dtype), dev)\n    c.data = tvm.nd.empty(a.data.shape, dtype)\n    c.indices = a.indices\n    c.indptr = a.indptr\n    f(a.data, c.data)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() * 2.0, rtol=1e-5)\n\n\ndef test_dynamic_tensor():\n    dtype = \"float32\"\n    stype = \"csr\"\n    target = \"llvm\"\n    dev = tvm.device(target, 0)\n    nr, nc, n = te.size_var(\"nr\"), te.size_var(\"nc\"), te.size_var(\"n\")\n    A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, name=\"A\", dtype=dtype)\n    assert A.stype == \"csr\"\n    C = te.compute(A.data.shape, lambda i: A.data[i] * 2.0, tag=\"cs_scatter\")\n    s = te.create_schedule(C.op)\n    _nr, _nc = 3, 5\n    a = np.maximum(np.random.uniform(size=(_nr, _nc)).astype(dtype) - 0.6, 0.0)\n    a = tvmsp.array(a, dev)\n    assert a.data.dtype == a.dtype\n    Ab = namedtuple(\"CSRBuffer\", [\"data\", \"indices\", \"indptr\"])\n    Ab.data = tvm.tir.decl_buffer(a.data.shape, a.data.dtype, name=\"A_data\")\n    Ab.indices = tvm.tir.decl_buffer(a.data.shape, a.data.dtype, name=\"A_indices\")\n    binds = {A.data: Ab.data, A.indices: Ab.indices}\n    f = tvm.build(s, [nr, A.data, C], target, binds=binds)\n    c = tvmsp.array(np.zeros((_nr, _nc), dtype), dev)\n    c.data = tvm.nd.empty(a.data.shape, dtype)\n    c.indices = a.indices\n    c.indptr = a.indptr\n    f(a.data.shape[0], a.data, c.data)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() * 2.0, rtol=1e-5)\n\n\ndef test_sparse_array_tuple():\n    dtype, itype = \"float32\", \"int32\"\n    stype = \"csr\"\n    target = \"llvm\"\n    dev = tvm.device(target, 0)\n    nr, nc, n = te.size_var(\"nr\"), te.size_var(\"nc\"), te.size_var(\"n\")\n    A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, name=\"A\", dtype=dtype)\n    assert A.stype == \"csr\"\n    C = te.compute(A.data.shape, lambda i: A.data[i] * 2.0, tag=\"cs_scatter\")\n    s = te.create_schedule(C.op)\n    _nr, _nc = 3, 5\n    a = np.maximum(np.random.uniform(size=(_nr, _nc)).astype(dtype) - 0.6, 0.0)\n    # convert to sparse array tuple\n    source_array = a\n    ridx, cidx = np.nonzero(source_array)\n    data = source_array[ridx, cidx]\n    a_data = _nd.array(data, dev)\n    indices = np.nonzero(source_array)[1].astype(itype)\n    a_indices = _nd.array(indices, dev)\n    indptr = [0] + np.apply_along_axis(np.count_nonzero, axis=1, arr=source_array).tolist()\n    indptr = np.cumsum(np.array(indptr, itype)).astype(itype)\n    a_indptr = _nd.array(indptr, dev)\n    a_init = (a_data, a_indices, a_indptr)\n    # construct tvm sparse array with tuple\n    a = tvmsp.array(a_init, shape=source_array.shape, device=dev)\n    assert a.data.dtype == a.dtype\n    Ab = namedtuple(\"CSRBuffer\", [\"data\", \"indices\", \"indptr\"])\n    Ab.data = tvm.tir.decl_buffer(a.data.shape, a.data.dtype, name=\"A_data\")\n    Ab.indices = tvm.tir.decl_buffer(a.data.shape, a.data.dtype, name=\"A_indices\")\n    binds = {A.data: Ab.data, A.indices: Ab.indices}\n    f = tvm.build(s, [nr, A.data, C], target, binds=binds)\n    c = tvmsp.array(np.zeros((_nr, _nc), dtype), dev)\n    c.data = tvm.nd.empty(a.data.shape, dtype)\n    c.indices = a.indices\n    c.indptr = a.indptr\n    f(a.data.shape[0], a.data, c.data)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() * 2.0, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_static_tensor()\n    test_dynamic_tensor()\n    test_sparse_array_tuple()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_tachikoma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport itertools\nimport numpy as np\nimport sys\nimport subprocess\nimport math\nimport collections\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\nfrom tvm.relay.op.contrib import tachikoma\nimport tvm.testing\n\n\nhas_tachikoma_codegen = pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.tachikoma\", True), reason=\"Tachikoma codegen not available\"\n)\n\nrun_module = tvm.testing.parameter(\n    pytest.param(False, marks=[has_tachikoma_codegen, *tvm.testing.requires_llvm.marks()]),\n    pytest.param(True, marks=[has_tachikoma_codegen, *tvm.testing.requires_llvm.marks()]),\n    ids=[\"compile\", \"run\"],\n)\n\n_bf16_supported = None\n\n\ndef bf16_supported():\n    global _bf16_supported\n    if _bf16_supported is None:\n        _bf16_supported = False\n        if sys.platform.startswith(\"darwin\"):\n            cpu_info = subprocess.check_output(\"sysctl -a\", shell=True).strip().decode()\n            for line in cpu_info.split(\"\\n\"):\n                if line.startswith(\"hw.optional.avx512f\"):\n                    _bf16_supported = bool(int(line.split(\":\", 1)[1]))\n        elif sys.platform.startswith(\"linux\"):\n            _bf16_supported = \"avx512\" in open(\"/proc/cpuinfo\", \"r\").read()\n    return _bf16_supported\n\n\ndef partition_for_tachikoma(mod, params=None, alter_layout=True, prune_subgraphs=True):\n    \"\"\"Partition the graph greedily offloading supported operators to Tachikoma.\n    Parameters\n    ----------\n    mod : Module\n        The module to run passes on.\n    params : Optional[Dict[str, NDArray]]\n        Constant input parameters.\n    Returns\n    -------\n    mod : Module\n        Annotated and partitioned module.\n    \"\"\"\n    if params:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", tachikoma.legalize_group_conv):\n        with TempOpAttr(\"nn.conv2d_transpose\", \"FTVMLegalize\", tachikoma.legalize_group_conv):\n            seq = tvm.transform.Sequential(\n                [\n                    transform.CanonicalizeOps(),\n                    transform.InferType(),\n                    transform.SimplifyInference(),\n                    transform.FoldConstant(),\n                    transform.FoldScaleAxis(),\n                    # fold consecutive add ops to simplify pattern `conv2d-bias_add-bn-relu`\n                    transform.SimplifyExpr(),\n                    transform.FoldConstant(),\n                    # alter group conv /conv_transpose layout to `GOIHW` / `GIOHW`\n                    transform.Legalize(),\n                    transform.FoldConstant(),\n                ]\n            )\n            with tvm.transform.PassContext(opt_level=3):\n                mod = seq(mod)\n    if alter_layout:\n        with TempOpAttr(\"nn.conv1d\", \"FTVMAlterOpLayout\", tachikoma.alter_conv):\n            with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", tachikoma.alter_conv):\n                with TempOpAttr(\"nn.conv3d\", \"FTVMAlterOpLayout\", tachikoma.alter_conv):\n                    with TempOpAttr(\n                        \"nn.conv2d_transpose\", \"FTVMAlterOpLayout\", tachikoma.alter_conv_transpose\n                    ):\n                        with TempOpAttr(\n                            \"nn.conv3d_transpose\", \"FTVMAlterOpLayout\", tachikoma.alter_conv_transpose\n                        ):\n                            alter_layout_seq = tvm.transform.Sequential(\n                                [\n                                    transform.AlterOpLayout(),\n                                    transform.FoldConstant(),\n                                ]\n                            )\n                            with tvm.transform.PassContext(opt_level=3):\n                                mod = alter_layout_seq(mod)\n\n    mod = tachikoma.rewrite_layer_norm(mod)\n    mod = tachikoma.rewrite_dense_bias_gelu_reshape_last(mod)\n    mod = tachikoma.legalize_qnn_for_tachikoma(mod)\n\n    byoc_seq = tvm.transform.Sequential(\n        [\n            transform.MergeComposite(tachikoma.pattern_table()),\n            transform.AnnotateTarget(\"tachikoma\"),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3):\n        mod = byoc_seq(mod)\n        if prune_subgraphs:\n            mod = tachikoma.prune_tachikoma_subgraphs(mod)\n    return mod\n\n\ndef vmobj_to_list(o):\n    if isinstance(o, tvm.nd.NDArray):\n        o_np = o.numpy()\n        if o_np.dtype == np.uint16:\n            o_np = np.left_shift(o_np.astype(\"uint32\"), 16).view(\"<f4\")\n        return [o_np]\n    elif isinstance(o, tvm.runtime.container.ADT) or isinstance(o, list):\n        return [vmobj_to_list(f) for f in o]\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef assert_result_dict_holds(result_dict):\n    for k1, k2 in itertools.combinations(result_dict, 2):\n        res1 = vmobj_to_list(result_dict[k1])\n        res2 = vmobj_to_list(result_dict[k2])\n        for r1, r2 in zip(res1, res2):\n            if \"bf16\" in k1 or \"bf16\" in k2:\n                np.testing.assert_array_almost_equal(r1, r2, decimal=1)\n            else:\n                tvm.testing.assert_allclose(r1, r2, rtol=1e-3, atol=1e-3)\n\n\ndef check_tachikoma_used(mod, subgraph_num=None):\n    num_tachikoma_subgraphs = sum([1 if \"tachikoma\" in gv.name_hint else 0 for gv in mod.get_global_vars()])\n    if subgraph_num:\n        assert num_tachikoma_subgraphs == subgraph_num\n    else:\n        assert num_tachikoma_subgraphs >= 1\n\n\ndef run_and_verify(mod, input, params, target, run_module, subgraph_num=None, test_bf16=True):\n    dev = tvm.cpu()\n    result_dict = dict()\n    for mode in [\"graph\", \"vm\"]:\n        configs = [\n            (False, False, False),\n            (True, False, False),\n            (True, True, False),\n        ]\n        if test_bf16 and bf16_supported():\n            configs += [(True, False, True), (True, True, True)]\n\n        for use_tachikoma, alter_layout, use_bf16 in configs:\n            result_key = (\n                mode\n                + (\"_tachikoma\" if use_tachikoma else \"\")\n                + (\"_layout\" if alter_layout else \"\")\n                + (\"_bf16\" if use_bf16 else \"_fp32\")\n            )\n            processed_mod = mod\n            if use_bf16:\n                processed_mod = relay.transform.ToMixedPrecision(\"bfloat16\")(processed_mod)\n                if tvm.ir.structural_equal(processed_mod, mod):\n                    print(\"can not convert to bfloat16, skipping...\")\n                    continue\n            if use_tachikoma:\n                processed_mod = partition_for_tachikoma(processed_mod, params, alter_layout)\n                check_tachikoma_used(processed_mod)\n            with tvm.transform.PassContext(opt_level=3):\n                func = relay.create_executor(\n                    mode, mod=processed_mod, device=dev, target=target\n                ).evaluate()\n            if run_module:\n                if isinstance(input, dict):\n                    result_dict[result_key] = func(**input, **params)\n                else:\n                    result_dict[result_key] = func(input, **params)\n\n    if run_module:\n        assert_result_dict_holds(result_dict)\n\n\ndef run_and_verify_func(\n    config, run_module, subgraph_num=None, target=\"llvm\", dtype=\"float32\", test_bf16=True\n):\n    \"\"\"Test a Relay func by compiling, running, and comparing TVM and Tachikoma outputs.\n    Parameters\n    ----------\n    config : Tuple[relay.Function, Dict[str, NDArray], List[str]]\n        A tuple containing 1) The function to test, 2) A dictionary of var names to input shapes and\n        3) A list of which vars should be considered params.\n    run_module: bool\n        If True, the built module will be run after being compiled.\n    \"\"\"\n    f, input_shapes, is_param = config\n    params = {x: np.random.uniform(-1, 1, input_shapes[x]).astype(dtype) for x in is_param}\n    input_dict = {\n        k: np.random.uniform(-1, 1, v).astype(dtype)\n        for k, v in input_shapes.items()\n        if k not in is_param\n    }\n    run_and_verify(\n        f,\n        input_dict,\n        params,\n        subgraph_num=subgraph_num,\n        target=target,\n        run_module=run_module,\n        test_bf16=test_bf16,\n    )\n\n\ndef add_activation(activation, out, dic, param_lst):\n    if activation == \"relu\":\n        return relay.nn.relu(out), dic, param_lst\n    elif activation == \"tanh\":\n        return relay.tanh(out), dic, param_lst\n    elif activation == \"sigmoid\":\n        return relay.sigmoid(out), dic, param_lst\n    elif activation == \"clip\":\n        return relay.clip(out, 0.0, 6.0), dic, param_lst\n    elif activation == \"swish\":\n        sig_out = relay.sigmoid(out)\n        out = relay.multiply(out, sig_out)\n        return out, dic, param_lst\n    elif activation == \"gelu\":\n        out = gelu_helper(out)\n        return out, dic, param_lst\n    elif activation == \"mish\":\n        exp = relay.exp(out)\n        add = relay.add(exp, relay.const(1.0))\n        log = relay.log(add)\n        tanh = relay.tanh(log)\n        out = relay.multiply(out, tanh)\n        return out, dic, param_lst\n    else:\n        return out, dic, param_lst\n\n\ndef get_conv1d(\n    x_shape=((1, 3, 224)),\n    k_shape=(16, 3, 3),\n    groups=1,\n    padding=(1, 1),\n    strides=(1),\n    dilation=(1),\n    channels=None,\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv1d(\n        x,\n        kernel,\n        kernel_size=k_shape[2:3],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        channels=k_shape[0],\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv1d_bias(x_shape=(1, 3, 224), k_shape=(10, 3, 3), activation=None, dtype=\"float32\"):\n    conv, dic, param_lst = get_conv1d(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv1d_bias_bn_relu(x_shape=(1, 3, 224), k_shape=(10, 3, 3), dtype=\"float32\"):\n    conv1d_bias, dic, param_lst = get_conv1d_bias(x_shape, k_shape, dtype=dtype)\n    beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n    moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n    conv1d_bias_bn, _, _ = relay.nn.batch_norm(\n        conv1d_bias,\n        gamma=gamma,\n        beta=beta,\n        moving_mean=moving_mean,\n        moving_var=moving_var,\n        axis=1,\n        center=True,\n        scale=True,\n        epsilon=1e-5,\n    )\n    return relay.nn.relu(conv1d_bias_bn), dic, param_lst\n\n\ndef get_conv2d(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(16, 32, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    dilation=(1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv2d(\n        x,\n        kernel,\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        channels=k_shape[0],\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_transpose(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(32, 16, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.conv2d_transpose(\n        x,\n        kernel,\n        channels=k_shape[1] * groups,\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_weights_const(\n    x_shape=(1, 32, 8, 8),\n    k_shape=(16, 32, 3, 3),\n    groups=1,\n    padding=(0, 0),\n    strides=(1, 1),\n    dilation=(1, 1),\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv2d(\n        x,\n        kernel,\n        channels=k_shape[0],\n        kernel_size=k_shape[2:4],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n    )\n    dic = {\"x\": x_shape}\n    param_lst = []\n    return out, dic, param_lst\n\n\ndef get_conv2d_bias(\n    x_shape=(1, 32, 8, 8), k_shape=(16, 32, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv2d_weights_const(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_transpose_bias(\n    x_shape=(1, 32, 8, 8), k_shape=(32, 16, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv2d_transpose(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[1],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[1],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv2d_bias_bn_relu(x_shape=(1, 32, 8, 8), k_shape=(16, 32, 3, 3), dtype=\"float32\"):\n    conv2d_bias, dic, param_lst = get_conv2d_bias(x_shape, k_shape, dtype=dtype)\n    beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n    moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n    moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n    conv2d_bias_bn, _, _ = relay.nn.batch_norm(\n        conv2d_bias,\n        gamma=gamma,\n        beta=beta,\n        moving_mean=moving_mean,\n        moving_var=moving_var,\n        axis=1,\n        center=True,\n        scale=True,\n        epsilon=1e-5,\n    )\n    return relay.nn.relu(conv2d_bias_bn), dic, param_lst\n\n\ndef get_layer_norm(x_shape=(1, 49, 64), dtype=\"float32\"):\n    dic = {\"input\": x_shape}\n    param_lst = []\n    input = relay.var(\"input\", shape=x_shape)\n    beta = relay.const(np.zeros(x_shape[2]).astype(dtype))\n    gamma = relay.const(np.ones(x_shape[2]).astype(dtype))\n    out = relay.nn.layer_norm(input, gamma=gamma, beta=beta)\n    return out, dic, param_lst\n\n\ndef get_conv2d_bias_sum_relu(x_shape=(1, 32, 8, 8), k_shape=(16, 32, 3, 3), dtype=\"float32\"):\n    conv2d_bias, dic, param_lst = get_conv2d_bias(x_shape, k_shape, dtype=dtype)\n    sum_data = relay.const(np.random.randint(x_shape).astype(dtype))\n    conv2d_bias_sum = relay.add(sum_data, conv2d_bias)\n    return relay.nn.relu(conv2d_bias_sum), dic, param_lst\n\n\ndef get_conv3d(\n    x_shape=(1, 32, 8, 8, 8),\n    k_shape=(16, 32, 3, 3, 3),\n    groups=1,\n    padding=(0, 0, 0),\n    strides=(1, 1, 1),\n    dilation=(1, 1, 1),\n    activation=None,\n    dtype=\"float32\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv3d(\n        x,\n        kernel,\n        channels=k_shape[0],\n        kernel_size=k_shape[2:],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_transpose(\n    x_shape=(1, 32, 8, 8, 8),\n    k_shape=(32, 16, 3, 3, 3),\n    groups=1,\n    padding=(0, 0, 0),\n    strides=(1, 1, 1),\n    output_padding=(0, 0, 0),\n    activation=None,\n    dtype=\"float32\",\n    data_layout=\"NCDHW\",\n    kernel_layout=\"OIDHW\",\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n    out = relay.nn.conv3d_transpose(\n        x,\n        kernel,\n        channels=k_shape[1],\n        kernel_size=k_shape[2:5],\n        groups=groups,\n        padding=padding,\n        strides=strides,\n        output_padding=output_padding,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_bias(\n    x_shape=(1, 32, 8, 8, 8), k_shape=(16, 32, 3, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv3d(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef get_conv3d_transpose_bias(\n    x_shape=(1, 32, 8, 8, 8), k_shape=(32, 16, 3, 3, 3), activation=None, dtype=\"float32\"\n):\n    conv, dic, param_lst = get_conv3d_transpose(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=(k_shape[1],), dtype=dtype)\n    out = relay.nn.bias_add(conv, bias)\n    dic[\"bias\"] = (k_shape[1],)\n    param_lst += [\"bias\"]\n    return add_activation(activation, out, dic, param_lst)\n\n\ndef gelu_helper(data):\n    const1 = relay.const(math.sqrt(2.0))\n    const2 = relay.const(1.0)\n    const3 = relay.const(0.5)\n    divisor = relay.op.divide(data, const1)\n    val_erf = relay.op.erf(divisor)\n    added_erf = relay.op.add(val_erf, const2)\n    mul1 = relay.op.multiply(data, added_erf)\n    out = relay.op.multiply(mul1, const3)\n    return out\n\n\ndef get_dense(\n    x_shape=(1, 16), k_shape=(32, 16), activation=None, has_reshape=False, dtype=\"float32\"\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.dense(x, kernel, units=k_shape[0])\n    # out = relay.nn.dense(x, kernel, units=None)\n    if has_reshape:\n        out = relay.reshape(out, newshape=(1, x_shape[0], k_shape[0]))\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n\n    if activation == \"gelu\":\n        out = gelu_helper(out)\n    return out, dic, param_lst\n\n\ndef get_bmm(\n    x_shape=(1, 16, 8), k_shape=(1, 4, 8), dtype=\"float32\", transpose_a=False, transpose_b=True\n):\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtype)\n    out = relay.nn.batch_matmul(\n        x, kernel, out_dtype=dtype, transpose_a=transpose_a, transpose_b=transpose_b\n    )\n    dic = {\"x\": x_shape, \"kernel\": k_shape}\n    param_lst = [\"kernel\"]\n    return out, dic, param_lst\n\n\ndef test_bmm(run_module, dtype=\"float32\"):\n    x_shape = (1, 2, 4)\n    k_shape = (1, 3, 4)\n\n    dense, dic, param_lst = get_bmm(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    k_shape_t = (1, 4, 3)\n    dense, dic, param_lst = get_bmm(x_shape, k_shape_t, dtype=dtype, transpose_b=False)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef get_dense_bias(\n    x_shape=(1, 16),\n    k_shape=(32, 16),\n    activation=None,\n    has_reshape=False,\n    use_add=False,\n    dtype=\"float32\",\n):\n    dense, dic, param_lst = get_dense(\n        x_shape=x_shape, k_shape=k_shape, has_reshape=has_reshape, dtype=dtype\n    )\n    bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n    if use_add:\n        out = relay.add(dense, bias)\n    else:\n        out = relay.nn.bias_add(dense, bias)\n    dic[\"bias\"] = (k_shape[0],)\n    param_lst += [\"bias\"]\n\n    if activation == \"gelu\":\n        out = gelu_helper(out)\n    return out, dic, param_lst\n\n\ndef test_tachikoma_not_compatible(run_module, target=\"llvm\", dtype=\"float32\"):\n    xshape = (1, 32, 14, 14)\n    x_data = np.random.uniform(-1, 1, xshape).astype(dtype)\n\n    x = relay.var(\"x\", shape=(xshape), dtype=dtype)\n    y = relay.add(x, x)\n    z = relay.cast(relay.cast(y, \"int32\"), \"float32\")\n    out = relay.nn.relu(z)\n    f = relay.Function([x], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = partition_for_tachikoma(mod)\n    for mode in [\"graph\", \"vm\"]:\n        with tvm.transform.PassContext(opt_level=3):\n            func = relay.create_executor(mode, mod=mod, device=tvm.cpu(0), target=target).evaluate()\n            if run_module:\n                results = func(x_data)\n\n\ndef test_multiple_outputs(run_module, dtype=\"float32\"):\n    def get_graph():\n        x = relay.var(\"x\", shape=(1, 3), dtype=dtype)\n        y = relay.var(\"y\", shape=(1, 3), dtype=dtype)\n        z = relay.add(x, y)\n        w = relay.add(z, y)\n        out = relay.Tuple((z, w))\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": (1, 3), \"y\": (1, 3)}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, dtype=dtype)\n\n\ndef test_elementwise(run_module, dtype=\"float32\"):\n    def get_graph(op, x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = op(x)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    for op in [\n        relay.abs,\n        relay.exp,\n        relay.log,\n        relay.sqrt,\n        relay.nn.relu,\n        relay.tanh,\n        relay.sigmoid,\n    ]:\n        run_and_verify_func(get_graph(op), run_module=run_module)\n\n\ndef test_clip(run_module, dtype=\"float32\"):\n    def get_graph(x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.clip(x, a_min=-0.2, a_max=0.4)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_leaky_relu(run_module, dtype=\"float32\"):\n    def get_graph(x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.nn.leaky_relu(x, alpha=0.1)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_softmax(run_module, dtype=\"float32\"):\n    def get_graph(x_shape, axis):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.nn.softmax(x, axis=axis)\n        f = tvm.IRModule.from_expr(out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph((1, 1000), axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 1000), axis=-1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 3, 4), axis=-2), run_module=run_module)\n    run_and_verify_func(get_graph((1, 3, 4), axis=1), run_module=run_module)\n\n\ndef test_conv1d(run_module, dtype=\"float32\"):\n    conv1d, dic, param_lst = get_conv1d(channels=16, dtype=dtype)\n    conv1d = tvm.IRModule.from_expr(conv1d)\n    config = conv1d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    x_shape = (1, 32, 224)\n    k_shape = (16, 32, 3)\n    conv1d_bias, dic, param_lst = get_conv1d(x_shape, k_shape, dtype=dtype)\n    conv1d_bias = tvm.IRModule.from_expr(conv1d_bias)\n    config = conv1d_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv1d_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 3, 224)\n    k_shape = (16, 3, 3)\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\"]\n    for a in activation_lst:\n        conv1d, dic, param_lst = get_conv1d(x_shape, k_shape, activation=a, dtype=dtype)\n        conv1d = tvm.IRModule.from_expr(conv1d)\n        config = conv1d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv1d_bias, dic, param_lst = get_conv1d_bias(x_shape, k_shape, activation=a, dtype=dtype)\n        conv1d_bias = tvm.IRModule.from_expr(conv1d_bias)\n        config = conv1d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    for k_shape, groups in [((16, 32, 3, 3), 1), ((32, 1, 3, 3), 32), ((32, 2, 3, 3), 16)]:\n        for padding in [(0, 0), (1, 1)]:\n            for strides in [(1, 1), (2, 2)]:\n                for dilation in [(1, 1), (2, 2)]:\n                    conv2d, dic, param_lst = get_conv2d(\n                        x_shape=x_shape,\n                        k_shape=k_shape,\n                        groups=groups,\n                        padding=padding,\n                        strides=strides,\n                        dilation=dilation,\n                        dtype=dtype,\n                    )\n                    conv2d = tvm.IRModule.from_expr(conv2d)\n                    config = conv2d, dic, param_lst\n                    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_weights_const(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n    conv2d, dic, param_lst = get_conv2d_weights_const(x_shape, k_shape, dtype=dtype)\n    conv2d = tvm.IRModule.from_expr(conv2d)\n    config = conv2d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    x_shape = (1, 3, 8, 8)\n    k_shape = (16, 3, 3, 3)\n    conv2d, dic, param_lst = get_conv2d_weights_const(x_shape, k_shape, dtype=dtype)\n    conv2d = tvm.IRModule.from_expr(conv2d)\n    config = conv2d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv2d, dic, param_lst = get_conv2d(x_shape, k_shape, activation=a, dtype=dtype)\n        conv2d = tvm.IRModule.from_expr(conv2d)\n        config = conv2d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv2d_bias, dic, param_lst = get_conv2d_bias(x_shape, k_shape, activation=a, dtype=dtype)\n        conv2d_bias = tvm.IRModule.from_expr(conv2d_bias)\n        config = conv2d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv2d_bias_bn_relu, dic, param_lst = get_conv2d_bias_bn_relu(x_shape, k_shape, dtype=dtype)\n    conv2d_bias_bn_relu = tvm.IRModule.from_expr(conv2d_bias_bn_relu)\n    config = conv2d_bias_bn_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv2d_bias_bn_relu, dic, param_lst = get_conv2d_bias_bn_relu(x_shape, k_shape, dtype=dtype)\n    conv2d_bias_bn_relu = tvm.IRModule.from_expr(conv2d_bias_bn_relu)\n    config = conv2d_bias_bn_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_bias_sum_relu(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    k_shape = (16, 32, 3, 3)\n\n    def get_conv2d_bn_sum_relu(x_shape, k_shape, sum_shape, dtype=\"float32\"):\n        out, dic, param_lst = get_conv2d_bias(x_shape=x_shape, k_shape=k_shape, dtype=dtype)\n        beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n        gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n        moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n        moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n        out, _, _ = relay.nn.batch_norm(\n            out,\n            gamma=gamma,\n            beta=beta,\n            moving_mean=moving_mean,\n            moving_var=moving_var,\n            axis=1,\n            center=True,\n            scale=True,\n            epsilon=1e-5,\n        )\n        sum_data = relay.var(\"data1\", shape=sum_shape, dtype=dtype)\n        out = relay.add(out, sum_data)\n        dic[\"data1\"] = sum_shape\n        param_lst += [\"data1\"]\n        return relay.nn.relu(out), dic, param_lst\n\n    conv2d_bn_sum_relu, dic, param_lst = get_conv2d_bn_sum_relu(\n        x_shape, k_shape, sum_shape=(1, 16, 6, 6), dtype=dtype\n    )\n    conv2d_bn_sum_relu = tvm.IRModule.from_expr(conv2d_bn_sum_relu)\n    config = conv2d_bn_sum_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv2d_bn_sum_relu, dic, param_lst = get_conv2d_bn_sum_relu(\n        x_shape, k_shape, sum_shape=(1, 16, 1, 1), dtype=dtype\n    )\n    conv2d_bn_sum_relu = tvm.IRModule.from_expr(conv2d_bn_sum_relu)\n    config = conv2d_bn_sum_relu, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_transpose(run_module, dtype=\"float32\"):\n    x_shape = (1, 32, 8, 8)\n    for k_shape, groups in [((32, 16, 3, 3), 1), ((32, 1, 3, 3), 32), ((32, 4, 3, 3), 16)]:\n        for padding in [(0, 0), (1, 1)]:\n            for strides in [(1, 1), (2, 2)]:\n                conv2d_transpose, dic, param_lst = get_conv2d_transpose(\n                    x_shape=x_shape,\n                    k_shape=k_shape,\n                    groups=groups,\n                    padding=padding,\n                    strides=strides,\n                    dtype=dtype,\n                )\n                conv2d_transpose = tvm.IRModule.from_expr(conv2d_transpose)\n                config = conv2d_transpose, dic, param_lst\n                run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv2d_transpose_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv2d, dic, param_lst = get_conv2d_transpose(activation=a, dtype=dtype)\n        conv2d = tvm.IRModule.from_expr(conv2d)\n        config = conv2d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv2d_bias, dic, param_lst = get_conv2d_transpose_bias(activation=a, dtype=dtype)\n        conv2d_bias = tvm.IRModule.from_expr(conv2d_bias)\n        config = conv2d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d(run_module, dtype=\"float32\"):\n    conv3d, dic, param_lst = get_conv3d(dtype=dtype)\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d, dic, param_lst = get_conv3d(padding=(0, 0, 0, 1, 1, 1), dtype=dtype)\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d, dic, param_lst = get_conv3d(\n        x_shape=(1, 3, 8, 8, 8), k_shape=(16, 3, 3, 3, 3), dtype=dtype\n    )\n    conv3d = tvm.IRModule.from_expr(conv3d)\n    config = conv3d, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv3d, dic, param_lst = get_conv3d(activation=a, dtype=dtype)\n        conv3d = tvm.IRModule.from_expr(conv3d)\n        config = conv3d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv3d_bias, dic, param_lst = get_conv3d_bias(activation=a, dtype=dtype)\n        conv3d_bias = tvm.IRModule.from_expr(conv3d_bias)\n        config = conv3d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_transpose(run_module, dtype=\"float32\"):\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(dtype=dtype)\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(strides=(2, 2, 2), dtype=dtype)\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    conv3d_transpose, dic, param_lst = get_conv3d_transpose(\n        strides=(2, 2, 2), output_padding=(1, 1, 1), dtype=dtype\n    )\n    conv3d_transpose = tvm.IRModule.from_expr(conv3d_transpose)\n    config = conv3d_transpose, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_conv3d_transpose_pattern(run_module, dtype=\"float32\"):\n    activation_lst = [None, \"relu\", \"tanh\", \"sigmoid\", \"clip\", \"swish\", \"gelu\", \"mish\"]\n    for a in activation_lst:\n        conv3d, dic, param_lst = get_conv3d_transpose(activation=a, dtype=dtype)\n        conv3d = tvm.IRModule.from_expr(conv3d)\n        config = conv3d, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n        conv3d_bias, dic, param_lst = get_conv3d_transpose_bias(activation=a, dtype=dtype)\n        conv3d_bias = tvm.IRModule.from_expr(conv3d_bias)\n        config = conv3d_bias, dic, param_lst\n        run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_dense(run_module, dtype=\"float32\"):\n    x_shape = (1, 16)\n    k_shape = (32, 16)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape=(1, 16), dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, activation=\"gelu\", dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_dense_pattern(run_module, dtype=\"float32\"):\n    x_shape = (1, 16)\n    k_shape = (32, 16)\n\n    dense, dic, param_lst = get_dense(x_shape, k_shape, dtype=dtype)\n    dense = tvm.IRModule.from_expr(dense)\n    config = dense, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense_bias, dic, param_lst = get_dense_bias(x_shape, k_shape, dtype=dtype)\n    dense_bias = tvm.IRModule.from_expr(dense_bias)\n    config = dense_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n    dense_bias, dic, param_lst = get_dense_bias(x_shape, k_shape, activation=\"gelu\", dtype=dtype)\n    dense_bias = tvm.IRModule.from_expr(dense_bias)\n    config = dense_bias, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_pool2d(run_module, dtype=\"float32\"):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 32, 32),\n        pool_size=(2, 2),\n        strides=(2, 2),\n        padding=(0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n            )\n        out = tvm.IRModule.from_expr(out)\n        return out, {\"x\": x_shape}, []\n\n    for pool_size in [(2, 2), (3, 3)]:\n        for strides in [(1, 1), (2, 2)]:\n            for padding in [(0, 0), (1, 1), (0, 0, 1, 1)]:\n                for ceil_mode in [False]:\n                    # Skip \"the padding size is larger than or equal to the filter size for exclusive-counting pooling\"\n                    if pool_size == (2, 2) and padding == (0, 0, 1, 1):\n                        continue\n                    for count_include_pad in [False, True]:\n                        # Skip \"inclusive-counted blended or average pooling is not supported in combination with asymmetric padding\"\n                        if count_include_pad and (padding == (0, 0, 1, 1) or strides == (2, 2)):\n                            continue\n                        run_and_verify_func(\n                            get_graph(\n                                relay.nn.avg_pool2d,\n                                pool_size=pool_size,\n                                strides=strides,\n                                padding=padding,\n                                ceil_mode=ceil_mode,\n                                count_include_pad=count_include_pad,\n                            ),\n                            run_module=run_module,\n                        )\n                    run_and_verify_func(\n                        get_graph(\n                            relay.nn.max_pool2d,\n                            pool_size=pool_size,\n                            strides=strides,\n                            padding=padding,\n                            ceil_mode=ceil_mode,\n                        ),\n                        run_module=run_module,\n                    )\n\n\ndef test_global_avg_pooling2d(run_module, dtype=\"float32\"):\n    x_shape = (1, 3, 32, 32)\n    x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n    out = relay.nn.global_avg_pool2d(x)\n    out = tvm.IRModule.from_expr(out)\n    config = out, {\"x\": x_shape}, []\n    run_and_verify_func(config, run_module=run_module)\n\n\ndef test_pool3d(run_module, dtype=\"float32\"):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 8, 32, 32),\n        pool_size=(2, 2, 2),\n        strides=(2, 2, 2),\n        padding=(0, 0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n        dtype=\"float32\",\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n            )\n        out = tvm.IRModule.from_expr(out)\n        return out, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(relay.nn.avg_pool3d), run_module=run_module)\n    run_and_verify_func(get_graph(relay.nn.max_pool3d), run_module=run_module)\n    run_and_verify_func(\n        get_graph(relay.nn.max_pool3d, padding=(0, 0, 0, 1, 1, 1)), run_module=run_module\n    )\n    run_and_verify_func(get_graph(relay.nn.max_pool3d, strides=(1, 1, 1)), run_module=run_module)\n\n\ndef test_prune_tachikoma_subgraph(run_module):\n    \"\"\"In this test, OP \"add\" should be offloaded from tachikoma codegen.\"\"\"\n\n    def get_graph():\n        x1 = relay.var(\"x1\", shape=(1, 32, 56, 56))\n        x2 = relay.var(\"x2\", shape=(1, 32, 56, 56))\n        bias = relay.var(\"bias\", shape=(32,))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        y = relay.nn.conv2d(\n            x1,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.nn.bias_add(y, bias)\n        y = relay.nn.relu(y)\n        y = relay.nn.global_max_pool2d(y)\n        y = relay.add(y, x2)\n        dic = {\n            \"x1\": (1, 32, 56, 56),\n            \"x2\": (1, 32, 56, 56),\n            \"weight\": (32, 32, 3, 3),\n            \"bias\": (32,),\n        }\n        param_lst = [\"weight\", \"bias\"]\n        out = tvm.IRModule.from_expr(y)\n        return out, dic, param_lst\n\n    run_and_verify_func(get_graph(), subgraph_num=1, run_module=run_module, test_bf16=False)\n\n\ndef test_layer_norm(run_module, dtype=\"float32\"):\n    x_shape = (1, 49, 64)\n\n    ln, dic, param_lst = get_layer_norm(x_shape, dtype=dtype)\n    ln = tvm.IRModule.from_expr(ln)\n    config = ln, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_rewrite_dense_bias_gelu_reshape_last(run_module, dtype=\"float32\"):\n    def get_graph(act=None):\n        x_shape = (1, 16)\n        k_shape = (32, 16)\n\n        dense_bias, dic, param_lst = get_dense_bias(\n            x_shape, k_shape, activation=act, has_reshape=True, use_add=True, dtype=dtype\n        )\n        dense_bias = tvm.IRModule.from_expr(dense_bias)\n        processed_dense_bias = partition_for_tachikoma(\n            dense_bias, params=None, alter_layout=False, prune_subgraphs=False\n        )\n        check_tachikoma_used(processed_dense_bias, 1)\n\n        return dense_bias, dic, param_lst\n\n    run_and_verify_func(\n        get_graph(\"gelu\"), subgraph_num=1, run_module=run_module, dtype=dtype, test_bf16=False\n    )\n    run_and_verify_func(\n        get_graph(), subgraph_num=1, run_module=run_module, dtype=dtype, test_bf16=False\n    )\n\n\ndef test_resnetv1_rewrite(run_module, dtype=\"float32\"):\n    def get_graph():\n        data_shape = (1, 256, 56, 56)\n        w_shapes = [\n            (64, 256, 1, 1),\n            (64, 64, 3, 3),\n            (256, 64, 1, 1),\n            (128, 256, 1, 1),\n            (128, 128, 3, 3),\n            (512, 128, 1, 1),\n            (512, 256, 1, 1),\n        ]\n        x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n        wights = [relay.const(np.random.randint(0, 1, w).astype(dtype)) for w in w_shapes]\n        biases = [relay.const(np.random.randint(0, 1, w[0]).astype(dtype)) for w in w_shapes]\n\n        conv1 = relay.nn.conv2d(\n            x,\n            wights[0],\n            channels=w_shapes[0][0],\n            kernel_size=w_shapes[0][2:4],\n            padding=(w_shapes[0][2] // 2, w_shapes[0][3] // 2),\n        )\n        conv1 = relay.nn.bias_add(conv1, biases[0])\n        conv1 = relay.nn.relu(conv1)\n\n        conv2 = relay.nn.conv2d(\n            conv1,\n            wights[1],\n            channels=w_shapes[1][0],\n            kernel_size=w_shapes[1][2:4],\n            padding=(w_shapes[1][2] // 2, w_shapes[1][3] // 2),\n        )\n        conv2 = relay.nn.bias_add(conv2, biases[1])\n        conv2 = relay.nn.relu(conv2)\n\n        conv3 = relay.nn.conv2d(\n            conv2,\n            wights[2],\n            channels=w_shapes[2][0],\n            kernel_size=w_shapes[2][2:4],\n            padding=(w_shapes[2][2] // 2, w_shapes[2][3] // 2),\n        )\n        conv3 = relay.nn.bias_add(conv3, biases[2])\n        conv3 = relay.add(conv3, x)\n        conv3 = relay.nn.relu(conv3)\n\n        left_conv4 = relay.nn.conv2d(\n            conv3,\n            wights[3],\n            channels=w_shapes[3][0],\n            strides=(2, 2),\n            kernel_size=w_shapes[3][2:4],\n            padding=(w_shapes[3][2] // 2, w_shapes[3][3] // 2),\n        )\n        left_conv4 = relay.nn.bias_add(left_conv4, biases[3])\n        left_conv4 = relay.nn.relu(left_conv4)\n\n        left_conv5 = relay.nn.conv2d(\n            left_conv4,\n            wights[4],\n            channels=w_shapes[4][0],\n            kernel_size=w_shapes[4][2:4],\n            padding=(w_shapes[4][2] // 2, w_shapes[4][3] // 2),\n        )\n        left_conv5 = relay.nn.bias_add(left_conv5, biases[4])\n        left_conv5 = relay.nn.relu(left_conv5)\n\n        left_conv6 = relay.nn.conv2d(\n            left_conv5,\n            wights[5],\n            channels=w_shapes[5][0],\n            kernel_size=w_shapes[5][2:4],\n            padding=(w_shapes[5][2] // 2, w_shapes[5][3] // 2),\n        )\n        left_conv6 = relay.nn.bias_add(left_conv6, biases[5])\n\n        right_conv7 = relay.nn.conv2d(\n            conv3,\n            wights[6],\n            channels=w_shapes[6][0],\n            strides=(2, 2),\n            kernel_size=w_shapes[6][2:4],\n            padding=(w_shapes[6][2] // 2, w_shapes[6][3] // 2),\n        )\n        right_conv7 = relay.nn.bias_add(right_conv7, biases[6])\n\n        out = relay.add(left_conv6, right_conv7)\n        out = relay.nn.relu(out)\n\n        dic = {\"x\": data_shape}\n        param_lst = []\n        return out, dic, param_lst\n\n    net, dic, param_lst = get_graph()\n    net = tvm.IRModule.from_expr(net)\n    config = net, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef test_fuse_pad_avg_pool(run_module, dtype=\"float32\"):\n    def get_graph():\n        data_shape = (1, 768, 17, 17)\n        x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n        out = relay.nn.pad(x, pad_width=[[0, 0], [0, 0], [1, 1], [1, 1]])\n        out = relay.nn.avg_pool2d(out, pool_size=[3, 3])\n        dic = {\"x\": data_shape}\n        param_lst = []\n        return out, dic, param_lst\n\n    net, dic, param_lst = get_graph()\n    net = tvm.IRModule.from_expr(net)\n    config = net, dic, param_lst\n    run_and_verify_func(config, run_module=run_module, dtype=dtype)\n\n\ndef permute_shape(shape, l_from=\"\", l_to=\"\"):\n    res_shape = []\n    for label in l_to:\n        pos = l_from.find(label)\n        res_shape.append(shape[pos])\n\n    return res_shape\n\n\ndef expand_dim(shape, rank=0):\n    assert len(shape) == 1\n    return shape + [1] * (rank - 1)\n\n\ndef filler_uni(low=0, high=1):\n    def filler_func(shape):\n        return np.random.uniform(low, high, shape)\n\n    return filler_func\n\n\nclass QnnBuilder:\n    def __init__(self, qnn_profile=None):\n        self._args = {}\n        self._args_op = []\n        self._qp = qnn_profile\n\n    def arg(self, shape=[], dtype=\"float32\", filler=filler_uni(), is_const=True):\n        if isinstance(filler, (int, float)):\n            value = np.full(shape, filler).astype(dtype)\n        else:\n            value = filler(shape).astype(dtype)\n\n        if is_const:\n            res = relay.const(value, dtype=dtype)\n        else:\n            name = f\"in_{len(self._args)}\"\n            res = relay.var(name, shape=shape, dtype=dtype)\n            self._args[name] = value\n            self._args_op.append(res)\n\n        return res\n\n    def make_zp(self, mean_val, num_ch=1, dispersion=0.2):\n        if num_ch == 1:\n            return self.arg(shape=[], dtype=\"int32\", filler=mean_val)\n        else:\n            low = int(mean_val * (1 - dispersion))\n            high = int(mean_val * (1 + dispersion))\n            return self.arg(shape=[num_ch], dtype=\"int32\", filler=filler_uni(low, high))\n\n    def make_scl(self, mean_val, num_ch=1, dispersion=0.2):\n        if num_ch == 1:\n            return self.arg(shape=[], dtype=\"float32\", filler=mean_val)\n        else:\n            low = mean_val * (1 - dispersion)\n            high = mean_val * (1 + dispersion)\n            return self.arg(shape=[num_ch], dtype=\"float32\", filler=filler_uni(low, high))\n\n    def make_zp_and_scl(self, name, num_ch=1, dispersion=0.2):\n        is_per_channel = getattr(self._qp, f\"{name}_pc\")\n        zp_val = getattr(self._qp, f\"{name}_zp\")\n        scl_val = getattr(self._qp, f\"{name}_scl\")\n\n        zp = self.make_zp(zp_val, num_ch if is_per_channel else 1, dispersion)\n        scl = self.make_scl(scl_val, num_ch if is_per_channel else 1, dispersion)\n        return zp, scl\n\n    def finalize(self, op):\n        func = relay.Function(self._args_op, op)\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        return mod, self._args\n\n\ndef check_fully_annotated(mod, desired_compiler):\n    matched_ops = []\n    other_ops = []\n\n    def _visit(node):\n        if isinstance(node, tvm.relay.Call):\n            op = node.op\n            if isinstance(op, relay.GlobalVar):\n                func = mod[op]\n                if \"Compiler\" in func.attrs and func.attrs[\"Compiler\"] == desired_compiler:\n                    matched_ops.append(op)\n                    return\n            else:\n                other_ops.append(op)\n\n    tvm.relay.analysis.post_order_visit(mod[\"main\"].body, _visit)\n\n    assert len(other_ops) == 0 and len(matched_ops) != 0, \"Model is not fully Tachikoma compiled\"\n\n\ndef check_result(\n    mod,\n    ref_mod,\n    map_inputs,\n    tol=1e-5,\n    target=\"llvm\",\n    device=tvm.cpu(),\n    params=None,\n    ref_result=None,\n    atol=None,\n    desired_compiler=\"tachikoma\",\n):\n    if atol is None:\n        atol = tol\n\n    if desired_compiler is not None:\n        check_fully_annotated(mod, desired_compiler)\n\n    if ref_result is None:\n        # Run the reference result\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            ref_lib = relay.build(ref_mod, target=target, params=params)\n        ref_rt_mod = tvm.contrib.graph_executor.GraphModule(ref_lib[\"default\"](device))\n\n        for name, data in map_inputs.items():\n            ref_rt_mod.set_input(name, data)\n        ref_rt_mod.run()\n        out = ref_rt_mod.get_output(0)\n        ref_result = out.numpy()\n\n    def check_vm_result():\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            exe = relay.vm.compile(mod, target=target, params=params)\n        code, lib = exe.save()\n        exe = tvm.runtime.vm.Executable.load_exec(code, lib)\n        vm = tvm.runtime.vm.VirtualMachine(exe, device)\n        output = vm.run(**map_inputs)\n        tvm.testing.assert_allclose(output.numpy(), ref_result, rtol=tol, atol=atol)\n\n    def check_graph_executor_result():\n        relay.backend.te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target, params=params)\n        rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](device))\n\n        rt_mod.run(**map_inputs)\n        output = rt_mod.get_output(0)\n        tvm.testing.assert_allclose(output.numpy(), ref_result, rtol=tol, atol=atol)\n\n    check_vm_result()\n    check_graph_executor_result()\n\n\nConvProfile = collections.namedtuple(\n    \"ConvProfile\",\n    [\n        \"SHAPE\",\n        \"KER\",\n        \"STR\",\n        \"PAD\",\n        \"DEL\",\n        \"OC\",\n        \"GR\",\n        \"D_LAYOUT\",\n        \"K_LAYOUT\",\n    ],\n)\nbase_conv = ConvProfile(\n    SHAPE=[1, 8, 5, 5],\n    KER=[3, 3],\n    STR=[1, 1],\n    PAD=[1, 1],\n    DEL=[1, 1],\n    OC=16,\n    GR=1,\n    D_LAYOUT=\"NCHW\",\n    K_LAYOUT=\"OIHW\",\n)\nbase_conv_nhwc = base_conv._replace(D_LAYOUT=\"NHWC\", K_LAYOUT=\"HWIO\")\nbase_conv_dilated = base_conv._replace(PAD=[2, 2], DEL=[2, 2])\nbase_conv_no_pad = base_conv._replace(PAD=[0, 0])\nbase_conv_no_pad_nhwc = base_conv_no_pad._replace(D_LAYOUT=\"NHWC\", K_LAYOUT=\"HWIO\")\nbase_conv_group_no_pad = base_conv_no_pad._replace(GR=2)\nbase_conv_dw_no_pad = base_conv_no_pad._replace(SHAPE=[1, 16, 5, 5], GR=16)\n\n\nDenseProfile = collections.namedtuple(\"DenseProfile\", [\"N\", \"IC\", \"OC\"])\nbase_dense_profile = DenseProfile(N=2, IC=10, OC=16)\n\nArgConstConfig = collections.namedtuple(\"ArgConstConfig\", [\"Data\", \"Weights\", \"Bias\", \"Sum\"])\nacp_regular = ArgConstConfig(Data=False, Weights=True, Bias=True, Sum=None)\nacp_no_bias = ArgConstConfig(Data=False, Weights=True, Bias=None, Sum=None)\nacp_with_sum = ArgConstConfig(Data=False, Weights=True, Bias=True, Sum=False)\nacp_no_bias_with_sum = ArgConstConfig(Data=False, Weights=True, Bias=None, Sum=False)\n\nQuantizationConfig = collections.namedtuple(\n    \"QuantizationConfig\",\n    [\n        \"d_zp\",\n        \"d_scl\",\n        \"d_pc\",\n        \"k_zp\",\n        \"k_scl\",\n        \"k_pc\",\n        \"rq_zp\",\n        \"rq_scl\",\n        \"rq_pc\",\n        \"sum_zp\",\n        \"sum_scl\",\n        \"sum_pc\",\n        \"o_zp\",\n        \"o_scl\",\n        \"o_pc\",\n    ],\n)\n\nqp_regular = QuantizationConfig(\n    d_zp=0,\n    d_scl=0.2,\n    d_pc=False,\n    k_zp=0,\n    k_scl=0.1,\n    k_pc=False,\n    rq_zp=30,\n    rq_scl=0.2,\n    rq_pc=False,\n    sum_zp=15,\n    sum_scl=0.3,\n    sum_pc=False,\n    o_zp=5,\n    o_scl=0.2,\n    o_pc=False,\n)\nqp_asymmetric_data = qp_regular._replace(\n    d_zp=3, rq_zp=10, rq_scl=0.1, sum_zp=15, sum_scl=0.3, o_zp=4\n)\n\nqnn_conv_profiles = tvm.testing.parameter(\n    by_dict={\n        #  Pattern qnn.conv2d + qnn.requantize\n        \"Base\": (base_conv, acp_regular, qp_regular),\n        \"NHWC\": (base_conv_nhwc, acp_regular, qp_regular),\n        #  Asymmetric input. NOTE: No pad! Input ZP is not compatible with padding\n        \"Group\": (base_conv_group_no_pad, acp_regular, qp_asymmetric_data),\n        \"DW\": (base_conv_dw_no_pad, acp_regular, qp_asymmetric_data),\n        \"NoBias\": (base_conv, acp_no_bias, qp_regular),\n        \"AsymmetricInput\": (base_conv_no_pad, acp_regular, qp_asymmetric_data),\n        \"AsymmetricInput_NHWC\": (base_conv_no_pad_nhwc, acp_regular, qp_asymmetric_data),\n        #  Pattern Conv2d + Requantize + Sum\n        \"WithSum\": (base_conv_no_pad, acp_with_sum, qp_asymmetric_data),\n        \"WithSum_NHWC\": (base_conv_no_pad_nhwc, acp_with_sum, qp_asymmetric_data),\n        \"WithSum_NoBias\": (base_conv_no_pad, acp_no_bias_with_sum, qp_asymmetric_data),\n    }\n)\n\n\n@has_tachikoma_codegen\ndef test_qnn_conv2d(qnn_conv_profiles):\n    def generate_model(p, c, q):\n        np.random.seed(0)\n\n        N, IC, IH, IW = p.SHAPE\n        d_shape = p.SHAPE\n        w_shape = [p.OC, IC, *p.KER]\n        b_shape = [p.OC]\n        s_shape = [\n            p.SHAPE[0],\n            p.OC,\n            (IH + 2 * p.PAD[0] - (p.KER[0] - 1) * p.DEL[0] - 1) // p.STR[0] + 1,\n            (IW + 2 * p.PAD[1] - (p.KER[1] - 1) * p.DEL[1] - 1) // p.STR[1] + 1,\n        ]\n\n        if p.GR != 1:\n            w_shape[1] //= p.GR\n\n        d_shape = permute_shape(d_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        s_shape = permute_shape(s_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        w_shape = permute_shape(w_shape, l_from=\"OIHW\", l_to=p.K_LAYOUT)\n\n        c_dim = p.D_LAYOUT.find(\"C\")\n        b_shape = expand_dim(b_shape, rank=len(p.D_LAYOUT) - c_dim)\n\n        bld = QnnBuilder(qnn_profile=q)\n\n        # Start build a test graph\n        data = bld.arg(shape=d_shape, dtype=\"uint8\", is_const=c.Data, filler=filler_uni(0, 20))\n        d_zp, d_scl = bld.make_zp_and_scl(\"d\", IC)\n\n        # Convolution\n        wgh = bld.arg(shape=w_shape, dtype=\"int8\", is_const=c.Weights, filler=filler_uni(-20, 20))\n        w_zp, w_scl = bld.make_zp_and_scl(\"k\")\n\n        op = tvm.relay.qnn.op.conv2d(\n            data,\n            wgh,\n            d_zp,\n            w_zp,\n            d_scl,\n            w_scl,\n            kernel_size=p.KER,\n            padding=p.PAD,\n            strides=p.STR,\n            dilation=p.DEL,\n            groups=p.GR,\n            channels=p.OC,\n            out_dtype=\"int32\",\n            data_layout=p.D_LAYOUT,\n            kernel_layout=p.K_LAYOUT,\n        )\n        # Optional bias\n        if c.Bias is not None:\n            bias = bld.arg(\n                shape=b_shape, dtype=\"int32\", is_const=c.Bias, filler=filler_uni(-50, 50)\n            )\n            op = tvm.relay.add(op, bias)\n\n        # Re-quantization\n        rq_in_zp = bld.make_zp(0)\n        rq_in_scl = bld.make_scl(q.d_scl * q.k_scl)  # in real cases that should be a vector\n        rq_out_zp, rq_out_scl = bld.make_zp_and_scl(\"rq\")\n\n        op = tvm.relay.qnn.op.requantize(\n            op, rq_in_scl, rq_in_zp, rq_out_scl, rq_out_zp, out_dtype=\"int32\"\n        )\n        op = tvm.relay.clip(\n            op, a_min=0.0, a_max=255.0\n        )  # pytorch frontend specific, I guess it's redundant\n        op = tvm.relay.cast(op, dtype=\"uint8\")\n\n        # Optional sum (ResNet like)\n        if c.Sum is not None:\n            sum_in = bld.arg(dtype=\"uint8\", shape=s_shape, filler=filler_uni(0, 10), is_const=c.Sum)\n\n            lhs_zp, lhs_scl = bld.make_zp_and_scl(\"rq\")\n            rhs_zp, rhs_scl = bld.make_zp_and_scl(\"sum\")\n            out_zp, out_scl = bld.make_zp_and_scl(\"o\")\n\n            op = tvm.relay.qnn.op.add(op, sum_in, lhs_scl, lhs_zp, rhs_scl, rhs_zp, out_scl, out_zp)\n            op = tvm.relay.clip(op, a_min=0.0, a_max=255.0)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p, quant_p = qnn_conv_profiles\n    ref_mod, args = generate_model(conv_p, arg_p, quant_p)\n    mod = partition_for_tachikoma(ref_mod)\n\n    # atol=1 means int values should match with +-1 quantum value tolerance\n    check_result(mod, ref_mod, args, tol=1e-10, atol=1, desired_compiler=\"tachikoma\")\n\n\nconv_profiles = tvm.testing.parameter(\n    by_dict={\n        \"Base\": (base_conv, acp_regular),\n        \"NHWC\": (base_conv_nhwc, acp_regular),\n        \"Group\": (base_conv_group_no_pad, acp_regular),\n        \"DW\": (base_conv_dw_no_pad, acp_regular),\n        \"Dilated\": (base_conv_dilated, acp_regular),\n    }\n)\n\n\n@has_tachikoma_codegen\ndef test_conv2d_plus(conv_profiles):\n    def generate_model(p, c):\n        np.random.seed(0)\n\n        N, IC, IH, IW = p.SHAPE\n        d_shape = p.SHAPE\n        w_shape = [p.OC, IC, *p.KER]\n        b_shape = [p.OC]\n        s_shape = [\n            p.SHAPE[0],\n            p.OC,\n            (IH + 2 * p.PAD[0] - (p.KER[0] - 1) * p.DEL[0] - 1) // p.STR[0] + 1,\n            (IW + 2 * p.PAD[1] - (p.KER[1] - 1) * p.DEL[1] - 1) // p.STR[1] + 1,\n        ]\n\n        if p.GR != 1:\n            w_shape[1] //= p.GR\n\n        d_shape = permute_shape(d_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        s_shape = permute_shape(s_shape, l_from=\"NCHW\", l_to=p.D_LAYOUT)\n        w_shape = permute_shape(w_shape, l_from=\"OIHW\", l_to=p.K_LAYOUT)\n\n        c_dim = p.D_LAYOUT.find(\"C\")\n        # b_shape = expand_dim(b_shape, rank=len(p.D_LAYOUT) - c_dim)\n\n        bld = QnnBuilder()\n\n        op = bld.arg(shape=d_shape, dtype=\"float32\", is_const=c.Data)\n        wgh = bld.arg(shape=w_shape, dtype=\"float32\", is_const=c.Weights)\n        op = tvm.relay.nn.conv2d(\n            op,\n            wgh,\n            kernel_size=p.KER,\n            padding=p.PAD,\n            strides=p.STR,\n            dilation=p.DEL,\n            groups=p.GR,\n            channels=p.OC,\n            out_dtype=\"float32\",\n            data_layout=p.D_LAYOUT,\n            kernel_layout=p.K_LAYOUT,\n        )\n\n        if c.Bias is not None:\n            bias = bld.arg(shape=b_shape, dtype=\"float32\", is_const=c.Bias)\n            op = tvm.relay.nn.bias_add(op, bias, axis=c_dim)\n\n        if c.Sum is not None:\n            sum_in = bld.arg(shape=s_shape, dtype=\"float32\", is_const=c.Sum)\n            op = tvm.relay.op.add(op, sum_in)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p = conv_profiles\n    ref_mod, args = generate_model(conv_p, arg_p)\n    mod = partition_for_tachikoma(ref_mod, alter_layout=False)\n    check_result(mod, ref_mod, args, tol=1e-5, desired_compiler=\"tachikoma\")\n\n\nqnn_dense_profiles = tvm.testing.parameter(\n    by_dict={\n        #  Pattern Dense + Requantize\n        \"Base\": (base_dense_profile, acp_regular, qp_regular),\n        \"AsymmetricInput\": (base_dense_profile, acp_regular, qp_asymmetric_data),\n        #  Pattern Dense + Requantize + Sum\n        \"AsymmetricInput_Sum\": (base_dense_profile, acp_with_sum, qp_asymmetric_data),\n    }\n)\n\n\n@has_tachikoma_codegen\ndef test_qnn_dense(qnn_dense_profiles):\n    def generate_model(p, c, q):\n        np.random.seed(0)\n\n        d_shape = [p.N, p.IC]\n        w_shape = [p.OC, p.IC]\n        b_shape = [p.OC]\n        s_shape = [p.N, p.OC]\n\n        bld = QnnBuilder(qnn_profile=q)\n\n        # Start build a test graph\n        data = bld.arg(shape=d_shape, dtype=\"uint8\", is_const=c.Data, filler=filler_uni(0, 20))\n        d_zp, d_scl = bld.make_zp_and_scl(\"d\", p.IC)\n\n        # Convolution\n        wgh = bld.arg(shape=w_shape, dtype=\"int8\", is_const=c.Weights, filler=filler_uni(-20, 20))\n        w_zp, w_scl = bld.make_zp_and_scl(\"k\")\n\n        op = tvm.relay.qnn.op.dense(\n            data, wgh, d_zp, w_zp, d_scl, w_scl, units=p.OC, out_dtype=\"int32\"\n        )\n        # Optional bias\n        if c.Bias is not None:\n            bias = bld.arg(\n                shape=b_shape, dtype=\"int32\", is_const=c.Bias, filler=filler_uni(-50, 50)\n            )\n            op = tvm.relay.add(op, bias)\n\n        # Re-quantization\n        rq_in_zp = bld.make_zp(0)\n        rq_in_scl = bld.make_scl(q.d_scl * q.k_scl)  # in real cases that should be a vector\n        rq_out_zp, rq_out_scl = bld.make_zp_and_scl(\"rq\")\n\n        op = tvm.relay.qnn.op.requantize(\n            op, rq_in_scl, rq_in_zp, rq_out_scl, rq_out_zp, out_dtype=\"int32\"\n        )\n        op = tvm.relay.clip(\n            op, a_min=0.0, a_max=255.0\n        )  # pytorch frontend specific, I guess it's redundant\n        op = tvm.relay.cast(op, dtype=\"uint8\")\n\n        # Optional sum (ResNet like)\n        if c.Sum is not None:\n            sum_in = bld.arg(dtype=\"uint8\", shape=s_shape, filler=filler_uni(0, 10), is_const=c.Sum)\n\n            lhs_zp, lhs_scl = bld.make_zp_and_scl(\"rq\")\n            rhs_zp, rhs_scl = bld.make_zp_and_scl(\"sum\")\n            out_zp, out_scl = bld.make_zp_and_scl(\"o\")\n\n            op = tvm.relay.qnn.op.add(op, sum_in, lhs_scl, lhs_zp, rhs_scl, rhs_zp, out_scl, out_zp)\n            op = tvm.relay.clip(op, a_min=0.0, a_max=255.0)\n\n        return bld.finalize(op)\n\n    conv_p, arg_p, quant_p = qnn_dense_profiles\n    ref_mod, args = generate_model(conv_p, arg_p, quant_p)\n    mod = partition_for_tachikoma(ref_mod)\n\n    # atol=1 means int values should match with +-1 quantum value tolerance\n    check_result(mod, ref_mod, args, tol=1e-10, atol=1, desired_compiler=\"tachikoma\")\n\n\ndense_profiles = tvm.testing.parameter(\n    by_dict={\n        \"Base\": (base_dense_profile, acp_regular),\n        \"WithSum\": (base_dense_profile, acp_with_sum),\n    }\n)\n\n\n@has_tachikoma_codegen\ndef test_dense_plus(dense_profiles):\n    def generate_model(p, c):\n        np.random.seed(0)\n\n        d_shape = [p.N, p.IC]\n        w_shape = [p.OC, p.IC]\n        b_shape = [p.OC]\n        s_shape = [p.N, p.OC]\n\n        c_dim = 1\n\n        bld = QnnBuilder()\n\n        op = bld.arg(shape=d_shape, dtype=\"float32\", is_const=c.Data)\n        wgh = bld.arg(shape=w_shape, dtype=\"float32\", is_const=c.Weights)\n        op = tvm.relay.nn.dense(op, wgh, out_dtype=\"float32\")\n\n        if c.Bias is not None:\n            bias = bld.arg(shape=b_shape, dtype=\"float32\", is_const=c.Bias)\n            op = tvm.relay.nn.bias_add(op, bias, axis=c_dim)\n\n        if c.Sum is not None:\n            sum_in = bld.arg(shape=s_shape, dtype=\"float32\", is_const=c.Sum)\n            op = tvm.relay.op.add(op, sum_in)\n\n        return bld.finalize(op)\n\n    dense_p, arg_p = dense_profiles\n    ref_mod, args = generate_model(dense_p, arg_p)\n    mod = partition_for_tachikoma(ref_mod)\n    check_result(mod, ref_mod, args, tol=1e-5, desired_compiler=\"tachikoma\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_tedd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport re\n\nfrom tvm import te\nfrom tvm import topi\n\n\ndef findany(pattern, str):\n    matches = re.findall(pattern, str)\n    assert len(matches) > 0, \"Pattern not found.\\nPattern: \" + pattern + \"\\nString:  \" + str\n\n\ndef checkdependency():\n    import pkg_resources\n\n    return not {\"graphviz\", \"ipython\"} - {pkg.key for pkg in pkg_resources.working_set}\n\n\ndef test_dfg():\n    A = te.placeholder((1024, 4096), dtype=\"float32\", name=\"A\")\n    B = topi.nn.softmax(A)\n    # confirm lower works\n    s = te.create_schedule([B.op])\n\n    def verify():\n        from tvm.contrib import tedd\n\n        str = tedd.viz_dataflow_graph(s, False, \"\", True)\n        # Check all edges are available\n        findany(r\"digraph \\\"Dataflow Graph\\\"\", str)\n        findany(r\"Stage_0:O_0 -> Tensor_0_0\", str)\n        findany(r\"Tensor_0_0 -> Stage_1:I_0\", str)\n        findany(r\"Stage_1:O_0 -> Tensor_1_0\", str)\n        findany(r\"Tensor_0_0 -> Stage_2:I_0\", str)\n        findany(r\"Tensor_1_0 -> Stage_2:I_1\", str)\n        findany(r\"Stage_2:O_0 -> Tensor_2_0\", str)\n        findany(r\"Tensor_2_0 -> Stage_3:I_0\", str)\n        findany(r\"Stage_3:O_0 -> Tensor_3_0\", str)\n        findany(r\"Tensor_2_0 -> Stage_4:I_0\", str)\n        findany(r\"Tensor_3_0 -> Stage_4:I_1\", str)\n        findany(r\"Stage_4:O_0 -> Tensor_4_0\", str)\n\n    if checkdependency():\n        verify()\n\n\ndef test_itervar_relationship_graph():\n    n = te.var(\"n\")\n    m = te.var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"k\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n\n    s = te.create_schedule(B.op)\n    s[B].split(B.op.reduce_axis[0], factor=16)\n\n    def verify():\n        from tvm.contrib import tedd\n\n        str = tedd.viz_itervar_relationship_graph(s, False, \"\", True)\n        findany(r\"digraph \\\"IterVar Relationship Graph\\\"\", str)\n        findany(r\"subgraph cluster_legend\", str)\n        # Check subgraphs for stages\n        findany(r\"subgraph cluster_Stage_0\", str)\n        findany(r\"subgraph cluster_Stage_1\", str)\n        # Check itervars and their types\n        findany(r\"\\(kDataPar\\)\\<br/\\>range\\(min=0, ext=n\\)\", str)\n        findany(r\"\\(kCommReduce\\)\\<br/\\>range\\(min=0, ext=m\\)\", str)\n        # Check the split node\n        findany(r\"Split_Relation_1_0 +.+\\>Split\", str)\n        # Check all edges to/from the split node\n        findany(r\"IterVar_1_1:itervar -> Split_Relation_1_0:Input\", str)\n        findany(r\"Split_Relation_1_0:Outer -> IterVar_1_2:itervar\", str)\n        findany(r\"Split_Relation_1_0:Inner -> IterVar_1_3:itervar\", str)\n\n    if checkdependency():\n        verify()\n\n\ndef test_schedule_tree():\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    n = te.var(\"n\")\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((n, m, l), name=\"A\")\n    B = te.compute((n, m, l), lambda bi, bj, bk: A[bi, bj, bk] + 1, name=\"B\")\n    r = te.reduce_axis((0, m), \"r\")\n    C = te.compute(\n        (\n            n,\n            m,\n        ),\n        lambda ci, cj: te.sum(B[ci, cj, r], axis=r),\n        name=\"C\",\n    )\n    s = te.create_schedule(C.op)\n    s.cache_read(A, \"shared\", [B])\n    s[B].vectorize(B.op.axis[-1])\n    s[C].reorder(C.op.reduce_axis[0], C.op.axis[0])\n    _, ki = s[C].split(C.op.reduce_axis[0], factor=16)\n    Cr = s.rfactor(C, ki)\n    s[Cr].compute_at(s[C], s[C].op.axis[-1])\n    s[C].bind(s[C].op.axis[0], block_x)\n    s[C].bind(s[C].op.axis[1], thread_x)\n\n    def verify():\n        from tvm.contrib import tedd\n\n        str = tedd.viz_schedule_tree(s, False, \"\", True)\n        findany(r\"digraph \\\"Schedule Tree\\\"\", str)\n        findany(r\"subgraph cluster_legend\", str)\n        # Check the A_shared stage, including memory scope, itervars,\n        # and compute\n        findany(\n            r\"Stage_1.*A\\.shared<br/>Scope: shared.+>0.+>\"\n            r\"ax0.*\\(kDataPar\\).+>1.+ax1.*\\(kDataPar\\).+>2.+>ax2.*\\(kDataPar\\).+>\"\n            r\"\\[A[\\[\\(]ax0, ax1, ax2[\\)\\]]\\]\",\n            str,\n        )\n        # Check itervars of types different from KDataPar\n        findany(r\"bk.*\\(kVectorized\\)\", str)\n        findany(r\"r.outer.*\\(kCommReduce\\)\", str)\n        findany(r\"label=ROOT\", str)\n        # Check the compute_at edge\n        findany(r\"Stage_1.*\\[color\\=\\\"\\#000000\\\"\\]\", str)\n\n    if checkdependency():\n        verify()\n\n\nif __name__ == \"__main__\":\n    test_dfg()\n    test_itervar_relationship_graph()\n    test_schedule_tree()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_tensorrt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport pytest\nimport itertools\nimport logging\nfrom typing import Tuple\n\ntry:\n    # See issue #9362.\n    import torch\nexcept:\n    pass\n\nimport tvm\nimport tvm.testing\nimport tvm.relay.testing\n\nfrom tvm import relay\nfrom tvm.relay import Any, GlobalVar\nfrom tvm.relay.expr_functor import ExprVisitor\nfrom tvm.contrib.download import download\nfrom tvm.relay.op.contrib import tensorrt\n\nSUPPORTED_DTYPES = [\"float16\", \"float32\"]\n\nhas_tensorrt_codegen = pytest.mark.skipif(\n    not tensorrt.is_tensorrt_compiler_enabled(), reason=\"TensorRT codegen not available\"\n)\n\n# CAUTION: Currently always false in CI since adds tens of minutes to test time and depends\n# on TensorRT installation. See https://github.com/apache/tvm/issues/11765\nhas_tensorrt_runtime = pytest.mark.skipif(\n    not tensorrt.is_tensorrt_runtime_enabled(), reason=\"TensorRT runtime not available\"\n)\n\nrun_module = tvm.testing.parameter(\n    pytest.param(False, marks=[has_tensorrt_codegen, *tvm.testing.requires_cuda.marks()]),\n    pytest.param(\n        True, marks=[has_tensorrt_runtime, has_tensorrt_codegen, *tvm.testing.requires_cuda.marks()]\n    ),\n    ids=[\"compile\", \"run\"],\n)\n\n\ndef vmobj_to_list(o):\n    if isinstance(o, tvm.nd.NDArray):\n        return [o.numpy()]\n    elif isinstance(o, tvm.runtime.container.ADT) or isinstance(o, list):\n        return [vmobj_to_list(f) for f in o]\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef assert_result_dict_holds(result_dict, dtype=\"float16\"):\n    for k1, k2 in itertools.combinations(result_dict, 2):\n        res1 = vmobj_to_list(result_dict[k1])\n        res2 = vmobj_to_list(result_dict[k2])\n        for r1, r2 in zip(res1, res2):\n            if dtype == \"float16\":\n                tvm.testing.assert_allclose(r1, r2, rtol=1e-1, atol=1e-1)\n            else:\n                tvm.testing.assert_allclose(r1, r2, rtol=1e-3, atol=5e-3)\n\n\ndef set_outer_func_attr(func, compile_name, symbol_name):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compile_name)\n    func = func.with_attr(\"global_symbol\", symbol_name)\n    return func\n\n\ndef set_inner_func_attr(func, pattern_name, composite_name):\n    func = func.with_attr(\"PartitionedFromPattern\", pattern_name)\n    func = func.with_attr(\"Composite\", composite_name)\n    return func\n\n\ndef run_and_verify_func(config, target=\"cuda\", run_module=True, data_type=\"float32\"):\n    \"\"\"Test a Relay func by compiling, running, and comparing TVM and TRT outputs.\n\n    Parameters\n    ----------\n    config : Tuple[relay.Function, Dict[str, NDArray], List[str]]\n        A tuple containing 1) The function to test, 2) A dictionary of var names to input shapes and\n        3) A list of which vars should be considered params.\n\n    run_module: bool\n\n        If True, the built module will be run after being compiled.\n\n    data_type: str\n        Check between single and double floating precision\n    \"\"\"\n    np.random.seed(42)\n    f, input_shapes, is_param = config\n    params = {\n        x: np.random.uniform(-1, 1, input_shapes[x]).astype(dtype=data_type) for x in is_param\n    }\n    input_dict = {\n        k: np.random.uniform(-1, 1, v).astype(dtype=data_type)\n        for k, v in input_shapes.items()\n        if k not in is_param\n    }\n    dev = tvm.device(target)\n\n    result_dict = dict()\n    for mode in [\"vm\", \"graph\"]:\n        for use_trt in [True, False]:\n            mod = tvm.IRModule()\n            mod[\"main\"] = f\n            result_key = mode + (\"_trt\" if use_trt else \"\")\n            if use_trt:\n                use_fp16 = data_type == \"float16\"\n                trt_target = tvm.target.Target(f\"tensorrt -use_fp16={use_fp16}\")\n                mod = relay.transform.InferType()(mod)\n                mod = tensorrt.partition_for_tensorrt(mod, params=params, target=trt_target)\n                with tvm.transform.PassContext(opt_level=3):\n                    func = relay.create_executor(\n                        mode, mod=mod, device=dev, target=[target, trt_target]\n                    ).evaluate()\n            else:\n                mod = relay.transform.InferType()(mod)\n                with tvm.transform.PassContext(opt_level=3):\n                    func = relay.create_executor(\n                        mode, mod=mod, device=dev, target=target\n                    ).evaluate()\n\n            if run_module:\n                result_dict[result_key] = func(**input_dict, **params)\n\n            if run_module:\n                assert_result_dict_holds(result_dict, data_type)\n\n\ndef test_tensorrt_simple(run_module):\n    for dtype in SUPPORTED_DTYPES:\n        xshape = (1, 3, 2, 2)\n        yshape = (1, 3, 1, 1)\n        zshape = (1, 1, 1, 1)\n        x = relay.var(\"x\", shape=(xshape), dtype=dtype)\n        y = relay.var(\"y\", shape=(yshape), dtype=dtype)\n        z = relay.var(\"z\", shape=(zshape), dtype=dtype)\n        w = z * (x + y)\n        out = relay.nn.relu(w)\n        f = relay.Function([x, y, z], out)\n        x_data = np.random.uniform(-1, 1, xshape).astype(dtype)\n        y_data = np.random.uniform(-1, 1, yshape).astype(dtype)\n        z_data = np.random.uniform(-1, 1, zshape).astype(dtype)\n\n        result_dict = dict()\n        for mode in [\"vm\", \"graph\"]:\n            for use_trt in [False, True]:\n                mod = tvm.IRModule()\n                mod[\"main\"] = f\n                result_key = mode + (\"_trt\" if use_trt else \"\")\n                if use_trt:\n                    mod = relay.transform.InferType()(mod)\n                    mod = tensorrt.partition_for_tensorrt(mod)\n                    with tvm.transform.PassContext(opt_level=3):\n                        func = relay.create_executor(\n                            mode, mod=mod, device=tvm.cuda(0), target=\"cuda\"\n                        ).evaluate()\n                else:\n                    mod = relay.transform.InferType()(mod)\n                    with tvm.transform.PassContext(opt_level=3):\n                        func = relay.create_executor(\n                            mode, mod=mod, device=tvm.cuda(0), target=\"cuda\"\n                        ).evaluate()\n                if run_module:\n                    result_dict[result_key] = func(x_data, y_data, z_data)\n\n        if run_module:\n            assert_result_dict_holds(result_dict)\n\n\ndef test_tensorrt_simple_cpu_io(run_module):\n    def get_graph():\n        dtype = \"float32\"\n        x_shape = (1, 3, 2, 2)\n        y_shape = (1, 3, 1, 1)\n        z_shape = (1, 1, 1, 1)\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        y = relay.var(\"y\", shape=(y_shape), dtype=dtype)\n        z = relay.var(\"z\", shape=(z_shape), dtype=dtype)\n        w = z * (x + y)\n        out = relay.nn.relu(w)\n        f = relay.Function([x, y, z], out)\n        return f, {\"x\": x_shape, \"y\": y_shape, \"z\": z_shape}, [\"y\"]\n\n    run_and_verify_func(get_graph(), target=\"llvm\", run_module=run_module)\n\n\ndef test_tensorrt_not_compatible(run_module):\n    dtype = \"float32\"\n    xshape = (1, 32, 14, 14)\n    x_data = np.random.uniform(-1, 1, xshape).astype(dtype)\n\n    x = relay.var(\"x\", shape=(xshape), dtype=dtype)\n    y = relay.add(x, x)\n    z = relay.cast(relay.cast(y, \"int32\"), \"float32\")\n    out = relay.nn.relu(z)\n    f = relay.Function([x], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = tensorrt.partition_for_tensorrt(mod)\n    for mode in [\"graph\", \"vm\"]:\n        with tvm.transform.PassContext(opt_level=3):\n            func = relay.create_executor(\n                mode, mod=mod, device=tvm.cuda(0), target=\"cuda\"\n            ).evaluate()\n            if run_module:\n                results = func(x_data)\n\n\ndef test_conv1d(run_module):\n    def get_graph(\n        x_shape=((1, 3, 224)),\n        k_shape=(10, 3, 3),\n        groups=1,\n        padding=(1, 1),\n        strides=(1),\n        dilation=(1),\n        channels=None,\n        d_type=\"float16\",\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=d_type)\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=d_type)\n        out = relay.nn.conv1d(\n            x,\n            kernel,\n            kernel_size=k_shape[2:3],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n            dilation=dilation,\n            channels=channels,\n            out_dtype=\"float16\",\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    for d_type in [\"float16\"]:\n        run_and_verify_func(\n            get_graph(channels=10, d_type=d_type), run_module=run_module, data_type=d_type\n        )\n\n\ndef test_conv2d(run_module):\n    def get_graph(\n        x_shape=(1, 32, 8, 8),\n        k_shape=(16, 32, 3, 3),\n        groups=1,\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        channels=None,\n        data_type=\"float16\",\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=data_type)\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=data_type)\n        out = relay.nn.conv2d(\n            x,\n            kernel,\n            kernel_size=k_shape[2:4],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n            dilation=dilation,\n            channels=channels,\n            out_dtype=data_type,\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    for k_shape, groups in [((16, 32, 3, 3), 1), ((32, 1, 3, 3), 32)]:\n        for padding in [(0, 0), (1, 1)]:\n            for strides in [(1, 1), (2, 2)]:\n                for dilation in [(1, 1), (2, 2)]:\n                    run_and_verify_func(\n                        get_graph(\n                            k_shape=k_shape,\n                            groups=groups,\n                            padding=padding,\n                            strides=strides,\n                            dilation=dilation,\n                        ),\n                        run_module=run_module,\n                        data_type=\"float16\",\n                    )\n    run_and_verify_func(\n        get_graph(\n            (1, 3, 16, 16), (3, 8, 7, 7), 3, [2, 2, 3, 3], [2, 2], [1, 1], 24, data_type=\"float16\"\n        ),\n        run_module=run_module,\n        data_type=\"float16\",\n    )\n\n    run_and_verify_func(\n        get_graph((1, 3, 16, 16), (1, 3, 1, 1), channels=1, data_type=\"float32\"),\n        run_module=run_module,\n        data_type=\"float32\",\n    )\n\n\ndef test_conv2d_nhwc(run_module):\n    def get_graph(x_shape=(1, 8, 8, 32), k_shape=(3, 3, 32, 16)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=\"float32\")\n        out = relay.nn.conv2d(\n            x, kernel, channels=16, kernel_size=(3, 3), data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_conv2d_weights_const(run_module):\n    def get_graph(\n        x_shape=(1, 32, 8, 8),\n        k_shape=(16, 32, 3, 3),\n        groups=1,\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_type=\"float16\",\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=data_type)\n        kernel = relay.const(np.ones(k_shape).astype(dtype=data_type))\n        out = relay.nn.conv2d(\n            x,\n            kernel,\n            channels=k_shape[0],\n            kernel_size=k_shape[2:4],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n            dilation=dilation,\n        )\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for tp in [\"float16\"]:\n        run_and_verify_func(get_graph(data_type=tp), run_module=run_module, data_type=tp)\n\n\ndef test_conv2d_weights_transposed(run_module):\n    def get_graph(x_shape=(1, 32, 9, 9), k_shape=(3, 3, 32, 16), order=(3, 2, 0, 1)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=\"float32\")\n        kernel_t = relay.transpose(kernel, order)\n        # Conv2d requires constant weights in TensorRT, so the weights should be transposed by\n        # FoldConstant.\n        out = relay.nn.conv2d(x, kernel_t, channels=k_shape[order[0]], kernel_size=(3, 3))\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_dense(run_module):\n    def get_graph(x_shape=(1, 16), k_shape=(32, 16), dtp=\"float16\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtp)\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=dtp)\n        # Dense requires constant weights in TensorRT, so the weights are transposed by us.\n        out = relay.nn.dense(x, kernel, units=k_shape[0])\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    for tp in [\"float32\"]:\n        run_and_verify_func(get_graph(dtp=tp), run_module=run_module, data_type=tp)\n        run_and_verify_func(get_graph(k_shape=(1, 16), dtp=tp), run_module=run_module, data_type=tp)\n\n\ndef test_batch_matmul(run_module):\n    def get_graph(x_shape=(12, 128, 64), y_shape=(12, 128, 64), transa=False, transb=True):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        y = relay.var(\"y\", shape=(y_shape), dtype=\"float32\")\n        out = relay.nn.batch_matmul(x, y, transpose_a=transa, transpose_b=transb)\n        f = relay.Function([x, y], out)\n        return f, {\"x\": x_shape, \"y\": y_shape}, []\n\n    run_and_verify_func(\n        get_graph(x_shape=(12, 64, 128), y_shape=(12, 128, 64), transa=True, transb=True),\n        run_module=run_module,\n    )\n    run_and_verify_func(\n        get_graph(x_shape=(12, 64, 128), y_shape=(12, 64, 128), transa=True, transb=False),\n        run_module=run_module,\n    )\n    run_and_verify_func(\n        get_graph(x_shape=(12, 128, 64), y_shape=(12, 128, 64), transa=False, transb=True),\n        run_module=run_module,\n    )\n    run_and_verify_func(\n        get_graph(x_shape=(12, 128, 64), y_shape=(12, 64, 128), transa=False, transb=False),\n        run_module=run_module,\n    )\n\n\ndef test_bias_add(run_module):\n    def get_graph(x_shape=(1, 16), channels=16):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=(channels,), dtype=\"float32\")\n        out = relay.nn.bias_add(x, bias)\n        f = relay.Function([x, bias], out)\n        return f, {\"x\": x_shape, \"bias\": (channels,)}, [\"bias\"]\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n    run_and_verify_func(get_graph((1, 6, 3, 4), 6), run_module=run_module)\n\n\ndef test_pool2d(run_module):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 32, 32),\n        pool_size=(2, 2),\n        strides=(2, 2),\n        padding=(0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for pool_size in [(2, 2), (3, 3)]:\n        for strides in [(1, 1), (2, 2)]:\n            for padding in [(0, 0), (1, 1), (0, 0, 1, 1)]:\n                for ceil_mode in [False, True]:\n                    # Skip \"the padding size is larger than or equal to the filter size for exclusive-counting pooling\"\n                    if pool_size == (2, 2) and padding == (0, 0, 1, 1):\n                        continue\n                    for count_include_pad in [False, True]:\n                        # Skip \"inclusive-counted blended or average pooling is not supported in combination with asymmetric padding\"\n                        if count_include_pad and (padding == (0, 0, 1, 1) or strides == (2, 2)):\n                            continue\n                        run_and_verify_func(\n                            get_graph(\n                                relay.nn.avg_pool2d,\n                                pool_size=pool_size,\n                                strides=strides,\n                                padding=padding,\n                                ceil_mode=ceil_mode,\n                                count_include_pad=count_include_pad,\n                            ),\n                            run_module=run_module,\n                        )\n                    run_and_verify_func(\n                        get_graph(\n                            relay.nn.max_pool2d,\n                            pool_size=pool_size,\n                            strides=strides,\n                            padding=padding,\n                            ceil_mode=ceil_mode,\n                        ),\n                        run_module=run_module,\n                    )\n\n\ndef test_global_pool2d(run_module):\n    def get_graph(op, x_shape=(1, 3, 32, 32)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = op(x)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(relay.nn.global_max_pool2d), run_module=run_module)\n    run_and_verify_func(get_graph(relay.nn.global_avg_pool2d), run_module=run_module)\n\n\ndef test_batch_flatten(run_module):\n    def get_graph(x_shape=(1, 3, 4, 6), data_type=\"float16\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=data_type)\n        out = relay.nn.batch_flatten(x)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for dtp in [\"float16\", \"float32\"]:\n        run_and_verify_func(get_graph(data_type=dtp), run_module=run_module, data_type=dtp)\n\n\ndef test_expand_dims(run_module):\n    def get_graph(x_shape=(1, 3), axis=1, num_newaxis=1):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = relay.expand_dims(x, axis, num_newaxis)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n\n\ndef test_squeeze(run_module):\n    def get_graph(x_shape, axis, dtype):\n        x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n        out = relay.squeeze(x, axis=axis)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for dtype in SUPPORTED_DTYPES:\n        run_and_verify_func(\n            get_graph((1, 5, 1, 1), (2, 3), dtype=dtype), run_module=run_module, data_type=dtype\n        )\n        run_and_verify_func(\n            get_graph((1, 3, 1), (-1,), dtype=dtype), run_module=run_module, data_type=dtype\n        )\n\n\ndef test_concatenate(run_module):\n    def get_graph(input_shapes, axis):\n        concat_inputs = []\n        shapes_dict = {}\n        for i in range(len(input_shapes)):\n            name = \"input_{}\".format(i)\n            concat_inputs.append(relay.var(name, shape=(input_shapes[i]), dtype=\"float32\"))\n            shapes_dict[name] = input_shapes[i]\n        out = relay.concatenate(concat_inputs, axis)\n        f = relay.Function(concat_inputs, out)\n        return f, shapes_dict, []\n\n    run_and_verify_func(get_graph([(1, 2, 6, 6), (1, 3, 6, 6)], axis=1), run_module=run_module)\n\n\ndef test_split(run_module):\n    def get_graph(x_shape, indices_or_sections, axis):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = relay.split(x, indices_or_sections=indices_or_sections, axis=axis)\n        f = relay.Function([x], out.astuple())\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph((1, 16), indices_or_sections=2, axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 16), indices_or_sections=4, axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 16), indices_or_sections=[8], axis=1), run_module=run_module)\n    run_and_verify_func(\n        get_graph((1, 16), indices_or_sections=[2, 3, 6, 10, 14], axis=1), run_module=run_module\n    )\n\n\ndef test_conv2d_transpose(run_module):\n    def get_graph(\n        x_shape=(1, 32, 8, 8), k_shape=(32, 16, 3, 3), groups=1, padding=(0, 0), strides=(1, 1)\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=\"float32\")\n        out = relay.nn.conv2d_transpose(\n            x,\n            kernel,\n            channels=k_shape[1],\n            kernel_size=k_shape[2:4],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    for padding in [(0, 0), (1, 1)]:\n        for strides in [(1, 1), (2, 2)]:\n            run_and_verify_func(get_graph(padding=padding, strides=strides), run_module=run_module)\n\n\ndef test_reshape(run_module):\n    def get_graph(x_shape, new_shape):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        out = relay.reshape(x, new_shape)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(\n        get_graph((1, 1, 1, 10), (-1, 10)), run_module=run_module, data_type=\"float16\"\n    )\n    run_and_verify_func(\n        get_graph((1, 10, 2, 3), (1, -1)), run_module=run_module, data_type=\"float16\"\n    )\n    run_and_verify_func(get_graph((1, 1, 2, 3), (1, 6)), run_module=run_module, data_type=\"float16\")\n\n\nclass AreOpsOnGraph(ExprVisitor):\n    \"\"\"\n    Visits the Graph recursively and checks if it contains ops in the op_list\n    \"\"\"\n\n    def __init__(self, op_list):\n        ExprVisitor.__init__(self)\n        self.op_list = op_list\n        self.on_graph = False\n\n    def visit_call(self, call):\n        if isinstance(call.op, tvm.tir.op.Op):\n            if str(call.op) in self.op_list:\n                self.on_graph = True\n\n        return super().visit_call(call)\n\n    def are_ops_on_graph(self, subgraph) -> bool:\n        \"\"\"\n        This function recursively visits the graph and checks if op_list ops are ongraph\"\n        \"\"\"\n        self.visit(subgraph)\n        return self.on_graph\n\n\ndef are_ops_on_trt(mod, op_list):\n    op_on_trt = False\n    op_on_tvm = False\n    for subgraph in mod.get_global_vars():\n        name = subgraph.name_hint\n        if mod[name].attrs and mod[name].attrs[\"Compiler\"] == \"tensorrt\":\n            op_on_trt |= AreOpsOnGraph(op_list).are_ops_on_graph(mod[name].body)\n        else:\n            op_on_tvm |= AreOpsOnGraph(op_list).are_ops_on_graph(mod[name].body)\n\n    return op_on_trt and not op_on_tvm\n\n\ndef test_dynamic_reshape(run_module):\n    def test_run(x_data_list, x_shape, new_shape, should_offload_to_trt):\n        result_arr = [{} for _ in range(len(x_data_list))]\n        for use_trt in [True, False]:\n            x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n            out = relay.reshape(x, new_shape)\n            f = relay.Function([x], out)\n            mod = tvm.IRModule()\n            mod[\"main\"] = f\n            if use_trt:\n                logging.info(\"Before partitioning:\\n%s\", mod)\n                mod = tensorrt.partition_for_tensorrt(mod)\n                logging.info(\"After partitioning:\\n%s\", mod)\n                assert are_ops_on_trt(mod, op_list=[\"reshape\"]) == should_offload_to_trt\n            if run_module:\n                with relay.build_config(opt_level=3):\n                    func = relay.create_executor(\n                        \"vm\", mod=mod, device=tvm.cpu(0), target=\"llvm\"\n                    ).evaluate()\n\n                for i, x_data in enumerate(x_data_list):\n                    result_arr[i][use_trt] = func(x_data)\n\n        if run_module:\n            for i in range(len(x_data_list)):\n                assert_result_dict_holds(result_arr[i])\n\n    dim_values = [1, 1, 0, 2, 3, 0, 1, 3, 2]\n    x_shape = (relay.Any(), 3, 2, 3)\n    x_data_list = [\n        np.ones([dim_value] + list(x_shape)[1:]).astype(\"float32\") for dim_value in dim_values\n    ]\n    new_shape = (-1, 3, 2, 3)\n    should_offload_to_trt = True\n    test_run(x_data_list, x_shape, new_shape, should_offload_to_trt)\n\n    dim_values = [1, 1, 0, 2, 3, 0, 1, 3, 2]\n    x_shape = (relay.Any(), 3, 2, 3)\n    x_data_list = [\n        np.ones([dim_value] + list(x_shape)[1:]).astype(\"float32\") for dim_value in dim_values\n    ]\n    new_shape = (-1, 1, 2, 3)\n    should_offload_to_trt = False\n    test_run(x_data_list, x_shape, new_shape, should_offload_to_trt)\n\n    dim_values = [1, 1, 0, 2, 3, 0, 1, 3, 2]\n    x_shape = (1, relay.Any(), 2, 3)\n    x_data_list = [\n        np.ones(list(x_shape[:1]) + [dim_value] + list(x_shape)[2:]).astype(\"float32\")\n        for dim_value in dim_values\n    ]\n    new_shape = (1, -1, 2, 3)\n    should_offload_to_trt = False\n    test_run(x_data_list, x_shape, new_shape, should_offload_to_trt)\n\n\ndef test_transpose(run_module):\n    def get_graph(x_shape, order):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = relay.transpose(x, order)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph((1, 16, 7, 7), [0, 2, 3, 1]), run_module=run_module)\n    run_and_verify_func(get_graph((1, 7, 7, 16), [0, 3, 1, 2]), run_module=run_module)\n\n\ndef test_float_const(run_module):\n    def get_graph(x_shape=(1, 16)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        beta = relay.const(1, dtype=\"float32\")\n        out = relay.multiply(x, beta)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, data_type=\"float32\")\n\n\ndef test_float_const16(run_module):\n    def get_graph(x_shape=(1, 16)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        beta = relay.const(1, dtype=\"float16\")\n        out = relay.multiply(x, beta)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, data_type=\"float16\")\n\n\ndef test_pad(run_module):\n    def get_graph(x_shape, pad_width):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = relay.nn.pad(x, pad_width=pad_width)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(\n        get_graph((1, 8, 16, 16), [[0, 0], [0, 0], [0, 0], [0, 0]]), run_module=run_module\n    )\n    run_and_verify_func(\n        get_graph((1, 8, 16, 16), [[0, 0], [0, 0], [1, 1], [1, 1]]), run_module=run_module\n    )\n    run_and_verify_func(\n        get_graph((1, 8, 16, 16), [[0, 0], [0, 0], [0, 1], [2, 0]]), run_module=run_module\n    )\n    run_and_verify_func(\n        get_graph((1, 8, 3, 16, 16), [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]),\n        run_module=run_module,\n    )\n\n\ndef test_add(run_module):\n    def get_graph(x_shape):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        y = relay.var(\"y\", shape=(x_shape), dtype=\"float16\")\n        out = relay.add(x, y)\n        f = relay.Function([x, y], out)\n        return f, {\"x\": x_shape, \"y\": x_shape}, []\n\n    run_and_verify_func(get_graph((1, 1000)), run_module=run_module, data_type=\"float16\")\n\n\ndef test_softmax(run_module):\n    def get_graph(x_shape, axis, data_type=\"float32\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=data_type)\n        out = relay.nn.softmax(x, axis=axis)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(\n        get_graph((1, 1000), axis=1, data_type=\"float32\"),\n        run_module=run_module,\n        data_type=\"float32\",\n    )\n    run_and_verify_func(\n        get_graph((1, 1000), axis=-1, data_type=\"float32\"),\n        run_module=run_module,\n        data_type=\"float32\",\n    )\n    run_and_verify_func(\n        get_graph((1, 3, 4), axis=-2, data_type=\"float16\"),\n        run_module=run_module,\n        data_type=\"float16\",\n    )\n    run_and_verify_func(\n        get_graph((1, 3, 4), axis=1, data_type=\"float16\"),\n        run_module=run_module,\n        data_type=\"float16\",\n    )\n\n\ndef test_batch_norm(run_module):\n    def get_graph(x_shape, param_shape, axis=1, epsilon=1e-5):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        beta = relay.var(\"beta\", shape=(param_shape), dtype=\"float32\")\n        gamma = relay.var(\"gamma\", shape=(param_shape), dtype=\"float32\")\n        moving_mean = relay.var(\"moving_mean\", shape=(param_shape), dtype=\"float32\")\n        moving_var = relay.var(\"moving_var\", shape=(param_shape), dtype=\"float32\")\n        out, _, _ = relay.nn.batch_norm(\n            x,\n            gamma=gamma,\n            beta=beta,\n            moving_mean=moving_mean,\n            moving_var=moving_var,\n            axis=axis,\n            center=True,\n            scale=True,\n            epsilon=epsilon,\n        )\n        f = relay.Function([x, gamma, beta, moving_mean, moving_var], out)\n        return (\n            f,\n            {\n                \"x\": x_shape,\n                \"beta\": param_shape,\n                \"gamma\": param_shape,\n                \"moving_mean\": param_shape,\n                \"moving_var\": param_shape,\n            },\n            [\"beta\", \"gamma\", \"moving_mean\", \"moving_var\"],\n        )\n\n    run_and_verify_func(get_graph((1, 64, 56, 56), (64,)), run_module=run_module)\n    run_and_verify_func(\n        get_graph((1, 56, 56, 64), (64,), axis=3, epsilon=1.001e-05), run_module=run_module\n    )\n    run_and_verify_func(get_graph((1, 4, 8, 4), (8,), axis=2), run_module=run_module)\n    run_and_verify_func(get_graph((1, 8, 4, 4, 4), (8,), axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 4, 8, 4, 4), (8,), axis=2), run_module=run_module)\n    run_and_verify_func(get_graph((1, 4, 4, 4, 8), (8,), axis=4), run_module=run_module)\n    run_and_verify_func(get_graph((1, 8), (8,), axis=1), run_module=run_module)\n    run_and_verify_func(get_graph((1, 3, 8), (8,), axis=2), run_module=run_module)\n\n\ndef test_layer_norm(run_module):\n    def get_graph(x_shape, param_shape, axis=1, epsilon=1e-5):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        gamma = relay.var(\"gamma\", shape=(param_shape), dtype=\"float32\")\n        beta = relay.var(\"beta\", shape=(param_shape), dtype=\"float32\")\n        out = relay.nn.layer_norm(\n            x, gamma=gamma, beta=beta, axis=axis, epsilon=epsilon, center=True, scale=True\n        )\n        f = relay.Function([x, gamma, beta], out)\n        return (f, {\"x\": x_shape, \"beta\": param_shape, \"gamma\": param_shape}, [\"beta\", \"gamma\"])\n\n    run_and_verify_func(get_graph((1, 32, 8, 8), (32,)), run_module=run_module)\n    run_and_verify_func(\n        get_graph((1, 8, 8, 32), (32,), axis=3, epsilon=1.001e-05), run_module=run_module\n    )\n    run_and_verify_func(get_graph((1, 8), (8,), axis=1), run_module=run_module)\n\n\ndef test_unary(run_module):\n    def get_graph(op, x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        out = op(x)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for op in [\n        relay.nn.relu,\n        relay.sigmoid,\n        relay.tanh,\n        relay.exp,\n        relay.log,\n        relay.sqrt,\n        relay.abs,\n        relay.negative,\n        relay.sin,\n        relay.cos,\n        relay.atan,\n        relay.ceil,\n        relay.floor,\n        relay.erf,\n    ]:\n        run_and_verify_func(get_graph(op), run_module=run_module)\n\n\ndef test_clip(run_module):\n    def get_graph(x_shape=(1, 8, 3, 3)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        out = relay.clip(x, a_min=-0.2, a_max=0.4)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, data_type=\"float16\")\n\n\ndef test_relu(run_module):\n    def get_graph(x_shape=(1, 8, 3, 4)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        out = relay.nn.relu(x)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, data_type=\"float16\")\n\n\ndef test_leaky_relu(run_module):\n    def get_graph(x_shape=(1, 8, 3, 4)):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float16\")\n        out = relay.nn.leaky_relu(x, alpha=0.1)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(), run_module=run_module, data_type=\"float16\")\n\n\ndef test_binary(run_module):\n    def get_graph(op, x_shape, y_shape, y_is_const=False, d_type=\"float16\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=d_type)\n        if y_is_const:\n            y = relay.const(np.ones(y_shape).astype(d_type))\n            out = op(x, y)\n            f = relay.Function([x], out)\n            return f, {\"x\": x_shape}, []\n        y = relay.var(\"y\", shape=(y_shape), dtype=d_type)\n        out = op(x, y)\n        f = relay.Function([x, y], out)\n        return f, {\"x\": x_shape, \"y\": y_shape}, []\n\n    for op in [relay.add, relay.subtract, relay.multiply, relay.divide, relay.power]:\n        for d_type in SUPPORTED_DTYPES:\n            for y_is_const in [True, False]:\n                run_and_verify_func(\n                    get_graph(op, (1, 8, 3, 3), (1, 8, 3, 3), y_is_const, d_type),\n                    run_module=run_module,\n                    data_type=d_type,\n                )\n                run_and_verify_func(\n                    get_graph(op, (1, 8, 1, 3), (1, 8, 3, 1), y_is_const, d_type),\n                    run_module=run_module,\n                    data_type=d_type,\n                )\n                run_and_verify_func(\n                    get_graph(op, (1, 10), (10,), y_is_const, d_type),\n                    run_module=run_module,\n                    data_type=d_type,\n                )\n                run_and_verify_func(\n                    get_graph(op, (1, 1, 1, 10), (10,), y_is_const, d_type),\n                    run_module=run_module,\n                    data_type=d_type,\n                )\n                run_and_verify_func(\n                    get_graph(op, (1, 1, 1), (3,), y_is_const, d_type),\n                    run_module=run_module,\n                    data_type=d_type,\n                )\n\n\ndef test_reduce(run_module):\n    def get_graph(op, x_shape=(1, 2, 3, 4), axis=(2, 3), keepdims=False, d_type=\"float32\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=d_type)\n        out = op(x, axis=axis, keepdims=keepdims)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for type in SUPPORTED_DTYPES:\n        for op in [relay.sum, relay.prod, relay.max, relay.min, relay.mean]:\n            for keepdims in [True, False]:\n                run_and_verify_func(\n                    get_graph(op, axis=(1), keepdims=keepdims, d_type=type),\n                    run_module=run_module,\n                    data_type=type,\n                )\n                run_and_verify_func(\n                    get_graph(op, axis=(2, 3), keepdims=keepdims, d_type=type),\n                    run_module=run_module,\n                    data_type=type,\n                )\n                run_and_verify_func(\n                    get_graph(op, axis=(1, 2), keepdims=keepdims, d_type=type),\n                    run_module=run_module,\n                    data_type=type,\n                )\n                run_and_verify_func(\n                    get_graph(op, axis=(1, 2, 3), keepdims=keepdims, d_type=type),\n                    run_module=run_module,\n                    data_type=type,\n                )\n\n\ndef test_strided_slice(run_module):\n    def get_graph(x_shape, begin, end, strides=None, slice_mode=\"size\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        if strides:\n            out = relay.strided_slice(x, begin, end, strides, slice_mode=slice_mode)\n        else:\n            out = relay.strided_slice(x, begin, end, slice_mode=slice_mode)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for slice_mode in [\"size\", \"end\"]:\n        run_and_verify_func(\n            get_graph((1, 3, 6, 7), (0, 0, 0, 0), (1, 1, 6, 7), slice_mode=slice_mode),\n            run_module=run_module,\n        )\n        run_and_verify_func(\n            get_graph((1, 3, 6, 7), [0, 1, 0, 0], [1, 2, 6, 6], slice_mode=slice_mode),\n            run_module=run_module,\n        )\n        run_and_verify_func(\n            get_graph((2, 3, 6, 7), [0, 0, 0, 0], [-1, -1, -1, -1], slice_mode=slice_mode),\n            run_module=run_module,\n        )\n        run_and_verify_func(\n            get_graph((2, 3, 6, 7), [0, 1, 0, 0], [-1, -1, -1, -1], slice_mode=slice_mode),\n            run_module=run_module,\n        )\n        run_and_verify_func(\n            get_graph((1, 6), [0, 1], [1, 3], slice_mode=slice_mode), run_module=run_module\n        )\n\n\ndef test_adaptive_pool2d(run_module):\n    def get_graph(op, x_shape=(1, 3, 32, 32), out_size=(1, 1), data_type=\"float16\"):\n        x = relay.var(\"x\", shape=(x_shape), dtype=data_type)\n        out = op(x, out_size)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    for type in SUPPORTED_DTYPES:\n        run_and_verify_func(\n            get_graph(relay.nn.adaptive_max_pool2d, data_type=type),\n            run_module=run_module,\n            data_type=type,\n        )\n        run_and_verify_func(\n            get_graph(relay.nn.adaptive_avg_pool2d, data_type=type),\n            run_module=run_module,\n            data_type=type,\n        )\n\n\ndef test_multiple_outputs(run_module):\n    def get_graph(d_type=\"float16\"):\n        x = relay.var(\"x\", shape=(1, 3), dtype=d_type)\n        y = relay.var(\"y\", shape=(1, 3), dtype=d_type)\n        z = relay.add(x, y)\n        w = relay.add(z, y)\n        out = relay.Tuple((z, w))\n        f = relay.Function([x, y], out)\n        return f, {\"x\": (1, 3), \"y\": (1, 3)}, []\n\n    for type in SUPPORTED_DTYPES:\n        run_and_verify_func(get_graph(d_type=type), run_module=run_module, data_type=type)\n\n\n@pytest.mark.skip(reason=(\"Fails assert_allclose. See https://github.com/apache/tvm/issues/11765\"))\ndef test_conv3d(run_module):\n    def get_graph(\n        x_shape=(1, 24, 8, 8, 8),\n        k_shape=(16, 24, 3, 3, 3),\n        groups=1,\n        padding=(0, 0, 0),\n        strides=(1, 1, 1),\n        dilation=(1, 1, 1),\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=\"float32\")\n        out = relay.nn.conv3d(\n            x,\n            kernel,\n            channels=k_shape[0],\n            kernel_size=k_shape[2:],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n            dilation=dilation,\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n    run_and_verify_func(get_graph(padding=(0, 0, 0, 1, 1, 1)), run_module=run_module)\n\n\ndef test_pool3d(run_module):\n    def get_graph(\n        op,\n        x_shape=(1, 3, 8, 32, 32),\n        pool_size=(2, 2, 2),\n        strides=(2, 2, 2),\n        padding=(0, 0, 0),\n        ceil_mode=False,\n        count_include_pad=None,\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        if count_include_pad is not None:\n            out = op(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                ceil_mode=ceil_mode,\n                count_include_pad=count_include_pad,\n            )\n        else:\n            out = op(x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode)\n        f = relay.Function([x], out)\n        return f, {\"x\": x_shape}, []\n\n    run_and_verify_func(get_graph(relay.nn.avg_pool3d), run_module=run_module)\n    run_and_verify_func(get_graph(relay.nn.max_pool3d), run_module=run_module)\n    run_and_verify_func(\n        get_graph(relay.nn.max_pool3d, padding=(0, 0, 0, 1, 1, 1)), run_module=run_module\n    )\n    run_and_verify_func(get_graph(relay.nn.max_pool3d, strides=(1, 1, 1)), run_module=run_module)\n\n\ndef test_conv3d_transpose(run_module):\n    def get_graph(\n        x_shape=(1, 32, 8, 8, 8),\n        k_shape=(32, 16, 3, 3, 3),\n        groups=1,\n        padding=(0, 0, 0),\n        strides=(1, 1, 1),\n        output_padding=(0, 0, 0),\n    ):\n        x = relay.var(\"x\", shape=(x_shape), dtype=\"float32\")\n        kernel = relay.var(\"kernel\", shape=(k_shape), dtype=\"float32\")\n        out = relay.nn.conv3d_transpose(\n            x,\n            kernel,\n            channels=k_shape[1],\n            kernel_size=k_shape[2:5],\n            groups=groups,\n            padding=padding,\n            strides=strides,\n            output_padding=output_padding,\n        )\n        f = relay.Function([x, kernel], out)\n        return f, {\"x\": x_shape, \"kernel\": k_shape}, [\"kernel\"]\n\n    run_and_verify_func(get_graph(), run_module=run_module)\n    run_and_verify_func(get_graph(strides=(2, 2, 2)), run_module=run_module)\n    run_and_verify_func(\n        get_graph(strides=(2, 2, 2), output_padding=(1, 1, 1)), run_module=run_module\n    )\n\n\n@has_tensorrt_codegen\ndef test_dynamic_offload():\n    \"\"\"\n    This test checks for proper dynamic offloading of relay graphs. An addition between\n    the outputs of two conv2d's is performed, one of them having all static args whereas\n    the other has a arg with dynamic shape. It is expected for the TRT partitioner to\n    offload the conv2d with dynamic arg to TVM while running the other in TRT.\n    \"\"\"\n\n    data_shape = (1, 32, 8, 8)\n    k_shape = (1, 32, 3, 3)\n\n    x = relay.var(\"x\", shape=(data_shape[0], data_shape[1], Any(), Any()), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(data_shape), dtype=\"float32\")\n    kernel = relay.const(np.random.rand(*k_shape).astype(\"float32\"))\n\n    def get_expected():\n        # Create a nested TRT function that matches the expected output\n        mod = tvm.IRModule()\n        outer_var = relay.var(\"tensorrt_0_i0\", shape=(data_shape), dtype=\"float32\")\n        inner_var = relay.var(\"FunctionVar_0_0\", shape=(data_shape), dtype=\"float32\")\n        inner_body = relay.nn.conv2d(\n            inner_var, kernel, channels=k_shape[0], kernel_size=k_shape[2:4]\n        )\n        inner_func = relay.Function([inner_var], inner_body)\n        inner_func = set_inner_func_attr(inner_func, \"nn.conv2d_\", \"tensorrt.nn.conv2d\")\n        outer_body = inner_func(outer_var)\n        outer_func = relay.Function([outer_var], outer_body)\n        outer_func = set_outer_func_attr(outer_func, \"tensorrt\", \"tvmgen_default_tensorrt_main_0\")\n        gv = GlobalVar(\"tvmgen_default_tensorrt_main_0\")\n        mod[gv] = outer_func\n        mod = relay.transform.InferType()(mod)\n\n        # Create the main function\n        out1 = relay.nn.conv2d(x, kernel, channels=k_shape[0], kernel_size=k_shape[2:4])\n        out = relay.add(out1, gv(y))\n        f = relay.Function([x, y], out)\n        mod[\"main\"] = f\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    # Create relay function that will be offloaded to TRT\n    out1 = relay.nn.conv2d(x, kernel, channels=k_shape[0], kernel_size=k_shape[2:4])\n    out2 = relay.nn.conv2d(y, kernel, channels=k_shape[0], kernel_size=k_shape[2:4])\n    out = relay.add(out1, out2)\n    f = relay.Function([x, y], out)\n\n    # Pass the function to TRT compilation\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = relay.transform.InferType()(mod)\n    mod_trt = tensorrt.partition_for_tensorrt(mod)\n\n    # Get the expected relay graph and compare\n    mod_exp = get_expected()\n    tvm.ir.assert_structural_equal(mod_trt, mod_exp, map_free_vars=True)\n\n\ndef test_tensorrt_dynamic_batch(run_module):\n    batches_to_test = [1, 1, 0, 2, 3, 0, 1, 3, 2]\n    x_shape = (relay.Any(), 1, 8, 8)\n    x_data = np.ones([max(batches_to_test)] + list(x_shape)[1:]).astype(\"float32\")\n    result_arr = [{} for _ in range(len(batches_to_test))]\n    for use_trt in [True, False]:\n        x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n        out = relay.nn.relu(x)\n        f = relay.Function([x], out)\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n        if use_trt:\n            mod = tensorrt.partition_for_tensorrt(mod)\n\n        if run_module:\n            with relay.build_config(opt_level=3):\n                func = relay.create_executor(\n                    \"vm\", mod=mod, device=tvm.cpu(0), target=\"llvm\"\n                ).evaluate()\n            for i, batch_size in enumerate(batches_to_test):\n                result_arr[i][use_trt] = func(x_data[:batch_size, ...])\n\n    if run_module:\n        for i in range(len(batches_to_test)):\n            assert_result_dict_holds(result_arr[i])\n\n\ndef test_tensorrt_dynamic_batch_conv(run_module):\n    batches_to_test = [1, 5, 1, 0, 2, 3, 0, 1, 3, 2]\n    x_shape = (relay.Any(), 32, 8, 8)\n    x_data = np.ones([max(batches_to_test)] + list(x_shape)[1:]).astype(\"float32\")\n    k_shape = (16, 32, 3, 3)\n    params = {\"kernel\": np.random.uniform(-1, 1, k_shape).astype(\"float32\")}\n    for use_implicit_batch in [True, False]:\n        result_arr = [{\"cuda\": {}, \"llvm\": {}} for _ in range(len(batches_to_test))]\n        for use_trt in [True, False]:\n            x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n            kernel = relay.var(\"kernel\", shape=k_shape, dtype=\"float32\")\n            out = relay.nn.conv2d(x, kernel, channels=16, kernel_size=(3, 3), groups=1)\n            f = relay.Function([x, kernel], out)\n            mod = tvm.IRModule()\n            mod[\"main\"] = f\n            trt_target = tvm.target.Target(f\"tensorrt -use_implicit_batch={use_implicit_batch}\")\n            if use_trt:\n                mod = tensorrt.partition_for_tensorrt(mod, params=params, target=trt_target)\n            if run_module:\n                for target in [\"llvm\", \"cuda\"]:\n                    targets = [target]\n                    if use_trt:\n                        targets.append(trt_target)\n                    with tvm.transform.PassContext(opt_level=3):\n                        func = relay.create_executor(\n                            \"vm\", mod=mod, device=tvm.device(target), target=targets\n                        ).evaluate()\n                    for i, batch_size in enumerate(batches_to_test):\n                        result_arr[i][target][use_trt] = func(x_data[:batch_size, ...], **params)\n        if run_module:\n            for i in range(len(batches_to_test)):\n                for target in [\"llvm\", \"cuda\"]:\n                    assert_result_dict_holds(result_arr[i][target])\n\n\ndef test_maskrcnn_resnet50(run_module) -> None:\n    \"\"\"\n    This function tests the working of pytorch maskrcnn with resnet50 as backbone with\n    VM and VM + TRT. Since the order of compiled model outputs is a bit different from\n    original pytorch model, it uses a custom logic for comparison check.\n    \"\"\"\n    import torch\n    import torchvision\n\n    def convert_traced_model_to_vm_trt(\n        traced_module: torch.jit.TopLevelTracedModule, np_sample_input: np.ndarray, target: str\n    ) -> tvm.runtime.vm.Executable:\n        \"\"\"\n        This function converts a traced pytorch model to VM + TRT.\n        \"\"\"\n        input_shape = np_sample_input.shape\n        input_name = \"input0\"\n        shape_list = [(input_name, input_shape)]\n        mod, params = relay.frontend.from_pytorch(traced_module, shape_list)\n        trt_target = tvm.target.Target(\"tensorrt -remove_no_mac_subgraphs=True\")\n        mod = tensorrt.partition_for_tensorrt(mod, params=params, target=trt_target)\n        targets = [target, trt_target]\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"FoldScaleAxis\"]):\n            vm_trt_exec = relay.vm.compile(mod, target=targets, params=params)\n\n        return vm_trt_exec\n\n    class TraceWrapper(torch.nn.Module):\n        \"\"\"\n        This class is a wrapper over the torch module to convert the outputs into traceable form\n        \"\"\"\n\n        def __init__(self, model: torch.nn.Module) -> None:\n            super().__init__()\n            self.model = model\n\n        def forward(\n            self, inp: torch.Tensor\n        ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n            out = self.model(inp)\n            return out[0][\"boxes\"], out[0][\"scores\"], out[0][\"labels\"], out[0][\"masks\"]\n\n    def get_traced_maskrcnn_model(np_sample_input: np.ndarray) -> torch.jit.TopLevelTracedModule:\n        \"\"\"\n        This function takes a sample input and returns the traced maskrcnn model\n        \"\"\"\n        model_func = torchvision.models.detection.maskrcnn_resnet50_fpn\n        model = TraceWrapper(model_func(pretrained=True))\n        model.eval()\n        inp = torch.Tensor(np.random.uniform(0.0, 250.0, size=np_sample_input.shape))\n\n        with torch.no_grad():\n            out = model(inp)\n            traced_module = torch.jit.trace(model, inp)\n            traced_module.eval()\n\n        return traced_module\n\n    def get_maskrcnn_input(in_size: int) -> np.ndarray:\n        \"\"\"\n        This function gets a real image with multiple objects of interest and returns it.\n        \"\"\"\n        input_shape = (1, 3, in_size, in_size)\n        img_path = \"test_street_small.jpg\"\n        img_url = \"https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/detection/street_small.jpg\"\n        download(img_url, img_path)\n        import cv2\n\n        img = cv2.imread(img_path).astype(\"float32\")\n        img = cv2.resize(img, (in_size, in_size))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        img = np.transpose(img / 255.0, [2, 0, 1])\n        img = np.expand_dims(img, axis=0)\n\n        return img\n\n    in_size = 300\n    np_sample_input = get_maskrcnn_input(in_size)\n    traced_module = get_traced_maskrcnn_model(np_sample_input)\n    vm_trt_exec = convert_traced_model_to_vm_trt(traced_module, np_sample_input, target=\"llvm\")\n\n    if run_module:\n        dev = tvm.cpu()\n        vm = tvm.runtime.vm.VirtualMachine(vm_trt_exec, dev)\n        vm.set_input(\"main\", **{\"input0\": np_sample_input})\n        tvm_res = vm.run()\n\n        # Descending sort by scores and get the high confidence indices. In this example 9 is chosen,\n        # because this image has 9 boxes over 0.9 confidence\n        num_high_confidence_boxes = 9\n        tvm_indices = np.argsort(-1 * tvm_res[1].numpy())[:num_high_confidence_boxes]\n\n        with torch.no_grad():\n            out = traced_module(torch.Tensor(np_sample_input))\n            # Descending sort by scores and get the high confidence indices\n            pt_indices = np.argsort(-1 * out[1].numpy())[:num_high_confidence_boxes]\n\n        # [Box Tol, Score Tol, Label Tol, Mask Tol]\n        tol = [1e-1, 5e-3, 1e-5, 4e-1]\n        # Because of certain ops, there are certain minor differences in TVM outputs and PT outputs,\n        # This means that the tolerance can't be 1e-4 or 1e-5 throughout. The ideal way to get around\n        # this is to test it on an entire dataset and compare mAP with the original model.\n        # However, since that is not practically possible on CI, the following compromise is made.\n        # These tolerances are chosen based on their impact or lack thereof to the mAP score, e.g:\n        # 0.1 pixel difference of a box in a 300X300 image wont make any change.\n        for i, tol_val in zip(range(4), tol):\n            np.testing.assert_allclose(\n                tvm_res[i].numpy()[tvm_indices],\n                out[i].numpy()[pt_indices],\n                rtol=tol_val,\n                atol=tol_val,\n            )\n\n\ndef test_empty_subgraph(run_module):\n    x_shape = (1, 3, 5)\n    mod = tvm.IRModule()\n    # Empty tensorrt subgraph.\n    var1 = relay.var(\"tensorrt_0_i0\", shape=(x_shape), dtype=\"float32\")\n    f1 = GlobalVar(\"tensorrt_0\")\n    func = relay.Function([var1], var1)\n    func = set_outer_func_attr(func, \"tensorrt\", \"tvmgen_default_tensorrt_0\")\n    mod[f1] = func\n    mod = relay.transform.InferType()(mod)\n\n    # Create the main function\n    x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n    out = f1(relay.nn.relu(x))\n    f = relay.Function([x], out)\n    mod[\"main\"] = f\n\n    x_data = np.random.uniform(-1, 1, x_shape).astype(\"float32\")\n    for mode in [\"graph\", \"vm\"]:\n        with tvm.transform.PassContext(opt_level=3):\n            func = relay.create_executor(\n                mode, mod=mod, device=tvm.cuda(0), target=\"cuda\"\n            ).evaluate()\n            if run_module:\n                results = func(x_data)\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_tensorrt_int8_exp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport os\nimport numpy as np\n\ntry:\n    # See issue #9362.\n    import torch\nexcept:\n    pass\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.op.contrib.tensorrt import partition_for_tensorrt\nfrom tvm.relay.op.contrib import tensorrt\n\n\ndef skip_codegen_test():\n    \"\"\"Skip test if TensorRT and CUDA codegen are not present\"\"\"\n    if not tvm.runtime.enabled(\"cuda\") or not tvm.cuda(0).exist:\n        print(\"Skip because CUDA is not enabled.\")\n        return True\n    if not tensorrt.is_tensorrt_compiler_enabled():\n        print(\"Skip because TensorRT compiler is not available.\")\n        return True\n    print(\"TensorRT compiler is available!\")\n    return False\n\n\ndef skip_runtime_test():\n    if not tvm.runtime.enabled(\"cuda\") or not tvm.cuda(0).exist:\n        print(\"Skip because CUDA is not enabled.\")\n        return True\n    if not tensorrt.is_tensorrt_runtime_enabled():\n        print(\"Skip because TensorRT runtime is not available.\")\n        return True\n    print(\"TensorRT runtime is available!\")\n    return False\n\n\ndef test_trt_int8():\n    \"\"\"\n    This Function is used to use tensorrt int8 to compile a resnet34 model,\n    and compare cosine distance between the output of the original model and trt int8 tvm output\n\n    \"\"\"\n    if skip_codegen_test() or skip_runtime_test():\n        return\n\n    try:\n        from PIL import Image\n        from scipy.spatial import distance\n    except:\n        print(\"please install scipy and Image python packages\")\n        return\n\n    try:\n        import torch\n        import torchvision\n        from torchvision import transforms\n    except:\n        print(\"please install pytorch python package\")\n        return\n\n    os.environ[\"TVM_TENSORRT_USE_INT8\"] = \"1\"\n    os.environ[\"TENSORRT_NUM_CALI_INT8\"] = \"10\"\n    model_name = \"resnet34\"\n    model = getattr(torchvision.models, model_name)(pretrained=True)\n    model = model.eval()\n\n    # We grab the TorchScripted model via tracing\n    input_shape = [1, 3, 224, 224]\n    input_data = torch.randn(input_shape)\n    scripted_model = torch.jit.trace(model, input_data).eval()\n\n    img_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\n    img_path = download_testdata(img_url, \"cat.png\", module=\"data\")\n    img = Image.open(img_path).resize((224, 224))\n    my_preprocess = transforms.Compose(\n        [\n            transforms.Resize(256),\n            transforms.CenterCrop(224),\n            transforms.ToTensor(),\n            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n        ]\n    )\n    img = my_preprocess(img)\n    img = np.expand_dims(img, 0)\n\n    input_name = \"input0\"\n    shape_list = [(input_name, img.shape)]\n    mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n\n    # compile the model\n    target = \"cuda\"\n    dev = tvm.cuda()\n    mod = partition_for_tensorrt(mod, params)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, params=params)\n\n    gen_module = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    num_cali_int8 = int(os.environ[\"TENSORRT_NUM_CALI_INT8\"])\n    if num_cali_int8 != 0:\n        print(\"start calibrating data ... \")\n        for i in range(num_cali_int8):\n            tvm_data = tvm.nd.array(img)\n            gen_module.set_input(input_name, tvm_data)\n            gen_module.run(data=tvm_data)\n        print(\"finished calibrating data ... \")\n\n    # get output of tvm model\n    print(\"rebuild engine and test to run ... \")\n    tvm_data = tvm.nd.array(img)\n    gen_module.set_input(input_name, tvm_data)\n    gen_module.run(data=tvm_data)\n    out = gen_module.get_output(0)\n\n    # check output of tvm and output of pytorch model are equal\n    torch_data = torch.from_numpy(img)\n    model = scripted_model.eval()\n    torch_output = model(torch_data)\n\n    cosine_distance_res = distance.cosine(out.numpy(), torch_output.detach().cpu().numpy())\n    assert cosine_distance_res <= 0.01\n\n    # Evaluate\n    print(\"Evaluate inference time cost...\")\n    ftimer = gen_module.module.time_evaluator(\"run\", dev, repeat=10, min_repeat_ms=500)\n    prof_res = np.array(ftimer().results) * 1e3  # convert to millisecond\n    message = \"Mean inference time (std dev): %.2f ms (%.2f ms)\" % (\n        np.mean(prof_res),\n        np.std(prof_res),\n    )\n    print(message)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_tflite_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.contrib import utils, tflite_runtime\n\n\ndef _create_tflite_model():\n    if not tvm.runtime.enabled(\"tflite\"):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n    if not tvm.get_global_func(\"tvm.tflite_runtime.create\", True):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n\n    try:\n        import tensorflow as tf\n    except ImportError:\n        print(\"skip because tensorflow not installed...\")\n        return\n\n    root = tf.Module()\n    root.const = tf.constant([1.0, 2.0], tf.float32)\n    root.f = tf.function(lambda x: root.const * x)\n\n    input_signature = tf.TensorSpec(\n        shape=[\n            2,\n        ],\n        dtype=tf.float32,\n    )\n    concrete_func = root.f.get_concrete_function(input_signature)\n    converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n    tflite_model = converter.convert()\n    return tflite_model\n\n\n@pytest.mark.skip(\"skip because accessing output tensor is flakey\")\ndef test_local():\n    if not tvm.runtime.enabled(\"tflite\"):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n    if not tvm.get_global_func(\"tvm.tflite_runtime.create\", True):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n\n    try:\n        import tensorflow as tf\n    except ImportError:\n        print(\"skip because tensorflow not installed...\")\n        return\n\n    tflite_fname = \"model.tflite\"\n    tflite_model = _create_tflite_model()\n    temp = utils.tempdir()\n    tflite_model_path = temp.relpath(tflite_fname)\n    open(tflite_model_path, \"wb\").write(tflite_model)\n\n    # inference via tflite interpreter python apis\n    interpreter = tf.lite.Interpreter(model_path=tflite_model_path)\n    interpreter.allocate_tensors()\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    input_shape = input_details[0][\"shape\"]\n    tflite_input = np.array(np.random.random_sample(input_shape), dtype=np.float32)\n    interpreter.set_tensor(input_details[0][\"index\"], tflite_input)\n    interpreter.invoke()\n    tflite_output = interpreter.get_tensor(output_details[0][\"index\"])\n\n    # inference via tvm tflite runtime\n    with open(tflite_model_path, \"rb\") as model_fin:\n        runtime = tflite_runtime.create(model_fin.read(), tvm.cpu(0))\n        runtime.set_input(0, tvm.nd.array(tflite_input))\n        runtime.invoke()\n        out = runtime.get_output(0)\n        np.testing.assert_equal(out.numpy(), tflite_output)\n\n\ndef test_remote():\n    if not tvm.runtime.enabled(\"tflite\"):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n    if not tvm.get_global_func(\"tvm.tflite_runtime.create\", True):\n        print(\"skip because tflite runtime is not enabled...\")\n        return\n\n    try:\n        import tensorflow as tf\n    except ImportError:\n        print(\"skip because tensorflow not installed...\")\n        return\n\n    tflite_fname = \"model.tflite\"\n    tflite_model = _create_tflite_model()\n    temp = utils.tempdir()\n    tflite_model_path = temp.relpath(tflite_fname)\n    open(tflite_model_path, \"wb\").write(tflite_model)\n\n    # inference via tflite interpreter python apis\n    interpreter = tf.lite.Interpreter(model_path=tflite_model_path)\n    interpreter.allocate_tensors()\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    input_shape = input_details[0][\"shape\"]\n    tflite_input = np.array(np.random.random_sample(input_shape), dtype=np.float32)\n    interpreter.set_tensor(input_details[0][\"index\"], tflite_input)\n    interpreter.invoke()\n    tflite_output = interpreter.get_tensor(output_details[0][\"index\"])\n\n    # inference via remote tvm tflite runtime\n    def check_remote(server):\n        remote = rpc.connect(server.host, server.port)\n        a = remote.upload(tflite_model_path)\n\n        with open(tflite_model_path, \"rb\") as model_fin:\n            runtime = tflite_runtime.create(model_fin.read(), remote.cpu(0))\n            runtime.set_input(0, tvm.nd.array(tflite_input, remote.cpu(0)))\n            runtime.invoke()\n            out = runtime.get_output(0)\n            np.testing.assert_equal(out.numpy(), tflite_output)\n\n    check_remote(rpc.Server(\"127.0.0.1\"))\n\n\nif __name__ == \"__main__\":\n    test_local()\n    test_remote()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_thrust.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.topi.cuda import stable_sort_by_key_thrust\nfrom tvm.topi.cuda.scan import exclusive_scan, scan_thrust, schedule_scan\nfrom tvm.contrib.thrust import can_use_thrust, can_use_rocthrust\nimport numpy as np\n\n\nthrust_check_func = {\"cuda\": can_use_thrust, \"rocm\": can_use_rocthrust}\n\n\ndef test_stable_sort_by_key():\n    size = 6\n    keys = te.placeholder((size,), name=\"keys\", dtype=\"int32\")\n    values = te.placeholder((size,), name=\"values\", dtype=\"int32\")\n\n    keys_out, values_out = stable_sort_by_key_thrust(keys, values)\n\n    for target in [\"cuda\", \"rocm\"]:\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            continue\n\n        with tvm.target.Target(target + \" -libs=thrust\") as tgt:\n            if not thrust_check_func[target](tgt, \"tvm.contrib.thrust.stable_sort_by_key\"):\n                print(\"skip because thrust is not enabled...\")\n                return\n\n            dev = tvm.device(target, 0)\n            s = te.create_schedule([keys_out.op, values_out.op])\n            f = tvm.build(s, [keys, values, keys_out, values_out], target)\n\n            keys_np = np.array([1, 4, 2, 8, 2, 7], np.int32)\n            values_np = np.random.randint(0, 10, size=(size,)).astype(np.int32)\n            keys_np_out = np.zeros(keys_np.shape, np.int32)\n            values_np_out = np.zeros(values_np.shape, np.int32)\n            keys_in = tvm.nd.array(keys_np, dev)\n            values_in = tvm.nd.array(values_np, dev)\n            keys_out = tvm.nd.array(keys_np_out, dev)\n            values_out = tvm.nd.array(values_np_out, dev)\n            f(keys_in, values_in, keys_out, values_out)\n\n            ref_keys_out = np.sort(keys_np)\n            ref_values_out = np.array([values_np[i] for i in np.argsort(keys_np)])\n            tvm.testing.assert_allclose(keys_out.numpy(), ref_keys_out, rtol=1e-5)\n            tvm.testing.assert_allclose(values_out.numpy(), ref_values_out, rtol=1e-5)\n\n\ndef test_exclusive_scan():\n    for target in [\"cuda\", \"rocm\"]:\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            continue\n\n        with tvm.target.Target(target + \" -libs=thrust\") as tgt:\n            if not thrust_check_func[target](tgt, \"tvm.contrib.thrust.sum_scan\"):\n                print(\"skip because thrust is not enabled...\")\n                return\n\n            for ishape in [(10,), (10, 10), (10, 10, 10)]:\n                values = te.placeholder(ishape, name=\"values\", dtype=\"int32\")\n\n                scan, reduction = exclusive_scan(values, return_reduction=True)\n                s = schedule_scan([scan, reduction])\n\n                dev = tvm.device(target, 0)\n                f = tvm.build(s, [values, scan, reduction], target)\n\n                values_np = np.random.randint(0, 10, size=ishape).astype(np.int32)\n                values_np_out = np.zeros(values_np.shape, np.int32)\n\n                if len(ishape) == 1:\n                    reduction_shape = ()\n                else:\n                    reduction_shape = ishape[:-1]\n\n                reduction_np_out = np.zeros(reduction_shape, np.int32)\n\n                values_in = tvm.nd.array(values_np, dev)\n                values_out = tvm.nd.array(values_np_out, dev)\n                reduction_out = tvm.nd.array(reduction_np_out, dev)\n                f(values_in, values_out, reduction_out)\n\n                ref_values_out = np.cumsum(values_np, axis=-1, dtype=\"int32\") - values_np\n                tvm.testing.assert_allclose(values_out.numpy(), ref_values_out, rtol=1e-5)\n                ref_reduction_out = np.sum(values_np, axis=-1)\n                tvm.testing.assert_allclose(reduction_out.numpy(), ref_reduction_out, rtol=1e-5)\n\n\ndef test_inclusive_scan():\n    out_dtype = \"int64\"\n\n    for target in [\"cuda\", \"rocm\"]:\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            continue\n\n        with tvm.target.Target(target + \" -libs=thrust\") as tgt:\n            if not thrust_check_func[target](tgt, \"tvm.contrib.thrust.sum_scan\"):\n                print(\"skip because thrust is not enabled...\")\n                return\n\n            for ishape in [(10,), (10, 10)]:\n                values = te.placeholder(ishape, name=\"values\", dtype=\"int32\")\n\n                scan = scan_thrust(values, out_dtype, exclusive=False)\n                s = tvm.te.create_schedule([scan.op])\n\n                dev = tvm.device(target, 0)\n                f = tvm.build(s, [values, scan], target)\n\n                values_np = np.random.randint(0, 10, size=ishape).astype(np.int32)\n                values_np_out = np.zeros(values_np.shape, out_dtype)\n                values_in = tvm.nd.array(values_np, dev)\n                values_out = tvm.nd.array(values_np_out, dev)\n                f(values_in, values_out)\n\n                ref_values_out = np.cumsum(values_np, axis=-1, dtype=out_dtype)\n                tvm.testing.assert_allclose(values_out.numpy(), ref_values_out, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_stable_sort_by_key()\n    test_exclusive_scan()\n    test_inclusive_scan()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_partition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm\nimport tvm.relay as relay\n\nfrom tvm.relay.backend.contrib.uma.api import UMAPartitioner\nfrom tvm.relay.op.contrib.register import get_pattern_table\nfrom tvm.relay.testing import resnet, mlp\nfrom tvm.relay.backend.contrib.uma import uma_available\n\n\npytestmark = pytest.mark.skipif(not uma_available(), reason=\"UMA not available\")\n\n\ndef test_partition_table():\n    partitioner = UMAPartitioner(\"test_partition\")\n    assert get_pattern_table(\"test_partition\") is None\n\n    partitioner.register()\n\n    assert get_pattern_table(\"test_partition\") is not None\n\n\n@pytest.mark.parametrize(\n    \"workload,backend,merge\",\n    [\n        (\"resnet\", \"dnnl\", False),\n        (\"resnet\", \"dnnl\", True),\n        (\"mlp\", \"dnnl\", False),\n        (\"mlp\", \"dnnl\", True),\n        (\"resnet\", \"cutlass\", False),\n        (\"resnet\", \"cutlass\", True),\n        (\"mlp\", \"cutlass\", False),\n        (\"mlp\", \"cutlass\", True),\n    ],\n)\ndef test_existing_pattern_tables(workload, backend, merge):\n    \"\"\"Tests that uma partitioner creates the same partitions than default BYOC partitioning\"\"\"\n    partitioner = UMAPartitioner(backend, merge)\n    pattern_table = get_pattern_table(backend)\n\n    for entry in pattern_table:\n        partitioner.add_pattern(*entry)\n\n    if workload == \"resnet\":\n        net = resnet.get_net(1, 10)\n    elif workload == \"mlp\":\n        net = mlp.get_net(1, 10)\n    else:\n        assert False, f\"don't know how to find workload for {workload}\"\n\n    mod = tvm.ir.IRModule()\n    mod[\"main\"] = net\n\n    partitioner.register()\n    partitioned_mod = partitioner.partition(mod)\n\n    def partition_default(mod):\n        \"\"\"partitions using default BYOC flow\"\"\"\n\n        sequence = [\n            relay.transform.MergeComposite(pattern_table),\n            relay.transform.AnnotateTarget(backend),\n        ]\n\n        if merge:\n            sequence.append(relay.transform.MergeCompilerRegions())\n\n        sequence.append(relay.transform.PartitionGraph())\n        sequential = tvm.transform.Sequential(sequence)\n\n        return sequential(mod)\n\n    default_partitioned_mod = partition_default(mod)\n\n    assert len(partitioned_mod.functions) == len(default_partitioned_mod.functions)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom typing import Union\n\nimport pytest\nimport tvm\nfrom tests.python.contrib.test_uma.test_uma_vanilla_accelerator import VanillaAcceleratorBackend\nfrom tvm.relay.backend.contrib.uma import uma_available\n\npytestmark = pytest.mark.skipif(not uma_available(), reason=\"UMA not available\")\n\n\n@pytest.mark.parametrize(\n    \"target_name,target_attrs,target_args\",\n    [\n        (\"my_hwa\", {}, {}),\n        (\n            \"my_hwa2\",\n            {\n                \"local_memory_size\": 128 * 1024,\n                \"variant\": \"version1\",\n            },\n            {\"local_memory_size\": 256 * 1024, \"variant\": \"version2\"},\n        ),\n    ],\n)\ndef test_uma_target(target_name, target_attrs, target_args):\n    registration_func = tvm.get_global_func(\"relay.backend.contrib.uma.RegisterTarget\")\n    registration_func(target_name, target_attrs)\n\n    # Test Defaults\n    my_target = tvm.target.Target(target_name)\n\n    assert str(my_target.kind) == target_name\n\n    for attr in target_attrs.keys():\n        assert my_target.attrs[attr] == target_attrs[attr]\n\n    # Test with parameters overwritten\n    args = \" \".join((f\"--{k}={v}\" for k, v in target_args.items()))\n    my_target = tvm.target.Target(f\"{target_name} {args}\")\n\n    for attr in target_args.keys():\n        assert my_target.attrs[attr] == target_args[attr]\n\n\n@pytest.mark.parametrize(\n    \"attr_name, target_attr\",\n    [\n        (\"float_attr\", 3.14),\n        (\"none_attr\", None),\n    ],\n)\ndef test_invalid_attr_option(attr_name: str, target_attr: Union[str, int, bool, float, None]):\n    if target_attr is None:\n        # None cannot be caught as TVMError, as it causes a SIGKILL, therefore it must be prevented to be\n        # entered into relay.backend.contrib.uma.RegisterTarget at Python level.\n        with pytest.raises(ValueError):\n            uma_backend = VanillaAcceleratorBackend()\n            uma_backend._target_attrs = {attr_name: target_attr}\n            uma_backend.register()\n    else:\n        registration_func = tvm.get_global_func(\"relay.backend.contrib.uma.RegisterTarget\")\n        target_name = f\"{attr_name}_{target_attr}\"\n        target_attr = {attr_name: target_attr}\n        with pytest.raises(tvm.TVMError, match=r\"Only String, Integer, or Bool are supported. .*\"):\n            registration_func(target_name, target_attr)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_uma_lowering_with_umalower.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport pathlib\n\nimport tvm\nfrom tests.python.contrib.test_uma.test_uma_utils import _create_schedule, _generate_io_arrays\nfrom tvm import topi\nfrom apps.uma._template.passes import MyAiHwConv2dPass\nimport tvm.testing\nfrom tvm import te\nfrom tvm.relay.backend.contrib.uma.api.lower import UMALower\nfrom tvm.relay.backend.contrib.uma.api.utils import PassPhase\nfrom tvm.relay.backend.contrib.uma import uma_available\n\n\npytestmark = pytest.mark.skipif(not uma_available(), reason=\"UMA not available\")\n\n\ndef _conv2d_te_definition(shapes: dict) -> list:\n    n, w, h, ci, kw, kh, co = (\n        shapes[\"n\"],\n        shapes[\"w\"],\n        shapes[\"h\"],\n        shapes[\"ci\"],\n        shapes[\"kw\"],\n        shapes[\"kh\"],\n        shapes[\"co\"],\n    )\n    ifmap = te.placeholder((n, ci, w, h), dtype=\"float32\", name=\"ifmap\")\n    weights = te.placeholder((co, ci, kw, kh), dtype=\"float32\", name=\"weights\")\n    result = topi.nn.conv2d_nchw(ifmap, weights, stride=1, padding=[kw // 2, kh // 2], dilation=1)\n    return [ifmap, weights, result]\n\n\ndef _pepare_conv2d_schedule(shapes, use_external_conv2d_impl=True):\n    placeholders = _conv2d_te_definition(shapes)\n\n    apps_path = (\n        pathlib.Path(str(__file__)).parent.parent.parent.parent.parent.joinpath(\"apps\").absolute()\n    )\n    conv2d_file = apps_path / \"uma\" / \"_template\" / \"conv2dnchw.cc\"\n\n    with conv2d_file.open() as f:\n        sch_tir = _create_schedule(\n            placeholders, f, use_external_conv2d_impl=use_external_conv2d_impl\n        )\n    return placeholders, sch_tir\n\n\ndef _run_external_conv2d(dut_io_arrays, conv2d_shapes, target):\n    # Run conv2d with external function\n    placeholders, schedule = _pepare_conv2d_schedule(conv2d_shapes)\n\n    uma_lower = UMALower(\"lower_test\")\n    uma_lower._tir_passes.append((PassPhase.TIR_PHASE_0, MyAiHwConv2dPass()))\n    with tvm.transform.PassContext():\n        tir_mod = uma_lower._lower_stir_to_nstir(schedule.mod[\"main\"])\n\n    ifmap_data, weight_data, result_data = dut_io_arrays\n\n    llvm_conv2d_mod = tvm.build(tir_mod, placeholders, target=target, name=\"test_external_conv2d\")\n    llvm_conv2d_mod(ifmap_data, weight_data, result_data)\n\n\ndef _run_reference_conv2d(reference_io_arrays, conv2d_shapes, target):\n    placeholders, schedule = _pepare_conv2d_schedule(conv2d_shapes)\n    ref_mod = tvm.build(schedule.mod, placeholders, target=target, name=\"test_reference_conv2d\")\n    ifmap, weights, result = reference_io_arrays\n    ref_mod(ifmap, weights, result)\n\n\ndef _prepare_io_arrays(conv2d_shapes, dev):\n    dut_io_arrays = _generate_io_arrays(conv2d_shapes, dev)\n    _, _, ref_result = _generate_io_arrays(conv2d_shapes, dev)\n    reference_io_arrays = [dut_io_arrays[0], dut_io_arrays[1], ref_result]\n    return dut_io_arrays, reference_io_arrays\n\n\n@pytest.mark.parametrize(\n    \"n, w, h, ci, kw, kh, co\",\n    [\n        (1, 224, 224, 3, 3, 3, 4),\n        (1, 224, 224, 3, 5, 5, 4),\n        (1, 224, 224, 3, 7, 7, 4),\n        (1, 224, 320, 3, 7, 7, 4),\n        (1, 224, 224, 3, 7, 7, 4),\n    ],\n)\ndef test_lower_with_uma(n, w, h, ci, kw, kh, co):\n    target = tvm.target.Target(target=\"llvm\", host=\"llvm\")\n    dev = tvm.device(target.kind.name, 0)\n    conv2d_shapes = dict(n=n, w=w, h=h, ci=ci, kw=kw, kh=kh, co=co)\n\n    dut_io_arrays, reference_io_arrays = _prepare_io_arrays(conv2d_shapes, dev)\n\n    _run_external_conv2d(dut_io_arrays, conv2d_shapes, target)\n    _run_reference_conv2d(reference_io_arrays, conv2d_shapes, target)\n\n    # compare results\n    dut_results = dut_io_arrays[2].numpy()\n    ref_results = reference_io_arrays[2].numpy()\n    tvm.testing.assert_allclose(dut_results, ref_results, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_uma_pipeline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\npytest.importorskip(\"tflite\")\npytest.importorskip(\"tensorflow\")\n\nimport os\nimport tensorflow as tf\nfrom tvm.micro.testing.aot_test_utils import AOT_DEFAULT_RUNNER\nfrom tvm.relay import transform, testing\nfrom tvm.testing.aot import (\n    AOTTestModel,\n    AOTTestRunner,\n    generate_ref_data,\n    compile_and_run,\n    create_relay_module_and_inputs_from_tflite_file,\n)\n\nimport tvm\nfrom test_uma_vanilla_accelerator import VanillaAcceleratorBackend\nfrom tvm import relay\nimport numpy as np\nfrom collections import OrderedDict\n\nfrom tvm.relay.backend.contrib.uma.api.utils import uma_available\n\npytestmark = pytest.mark.skipif(not uma_available(), reason=\"UMA not available\")\n\n\n@pytest.mark.parametrize(\n    \"interface_api,use_unpacked_api,test_runner,groups,weight_shape\",\n    [(\"c\", True, AOT_DEFAULT_RUNNER, 1, 32)],\n)\ndef test_conv2d(interface_api, use_unpacked_api, test_runner, groups, weight_shape):\n    \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n    mod, inputs, output_list, test_runner = create_conv2d(groups, test_runner, weight_shape)\n\n    uma_backend = VanillaAcceleratorBackend()\n    uma_backend.register()\n    mod = uma_backend.partition(mod)\n    target = tvm.target.Target(\"vanilla_accelerator\", host=tvm.target.Target(\"c\"))\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n        target=target,\n    )\n\n\ndef create_conv2d(groups=1, test_runner=AOT_DEFAULT_RUNNER, weight_shape=32):\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, weight_shape, 3, 3)\n    pass_config = {\"tir.usmp.enable\": True}\n    test_runner = AOTTestRunner(\n        makefile=test_runner.makefile,\n        prologue=test_runner.prologue,\n        epilogue=test_runner.epilogue,\n        includes=test_runner.includes,\n        parameters=test_runner.parameters,\n        pass_config=pass_config,\n    )\n    data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight0 = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=groups)\n    main_f = relay.Function([data0, weight0], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = main_f\n    mod = transform.InferType()(mod)\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, wshape).astype(dtype)\n    inputs = OrderedDict([(\"data\", i_data), (\"weight\", w1_data)])\n    output_list = generate_ref_data(mod, inputs)\n    return mod, inputs, output_list, test_runner\n\n\ndef _generate_runtime_data(input_shapes: dict, output_shapes: dict) -> [OrderedDict, OrderedDict]:\n    assert len(input_shapes) == 1\n    assert len(output_shapes) == 1\n\n    iname = list(input_shapes.keys())[0]\n    oname = list(output_shapes.keys())[0]\n    ishape = input_shapes[iname]\n    oshape = output_shapes[oname]\n    i_data = np.random.uniform(0, 1, ishape).astype(\"float32\")\n    o_data = np.random.uniform(0, 1, oshape).astype(\"float32\")\n    oname = \"output\"  # name set by relay.build in executor_codegen_metadata.outputs\n    inputs = OrderedDict([(iname, i_data)])\n    outputs = OrderedDict([(oname, o_data)])\n    return inputs, outputs\n\n\ndef test_mobilenet():\n    \"\"\"Full network test with Mobilenet\"\"\"\n    use_unpacked_api = True\n    interface_api = \"c\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    mod, params = testing.mobilenet.get_workload(batch_size=1)\n\n    uma_backend = VanillaAcceleratorBackend()\n    uma_backend.register()\n    target = tvm.target.Target(\"vanilla_accelerator\", host=tvm.target.Target(\"c\"))\n    target_c = tvm.target.Target(\"c\")\n\n    data_shape = [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n    data = np.random.uniform(size=data_shape).astype(\"float32\")\n    input_list = {\"data\": data}\n    output_list = generate_ref_data(mod, input_list, params)\n    mod = uma_backend.partition(mod)\n    aot_test_model = AOTTestModel(module=mod, inputs=input_list, outputs=output_list, params=params)\n\n    compile_and_run(\n        aot_test_model,\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n        workspace_byte_alignment=1,\n        debug_calculated_workspaces=False,\n        target=[target_c, target],\n    )\n\n\ndef test_tflite_model():\n    \"\"\"\n    End-to-end test of TF-Lite file using UMA\n    \"\"\"\n    tflite_file = \"/tmp/model.tflite\"\n    if os.path.exists(tflite_file):\n        os.remove(tflite_file)\n    generate_tflite_file(tflite_file)\n\n    pytest.importorskip(\"tflite\")\n\n    interpreter = tf.lite.Interpreter(model_path=tflite_file)\n    tf_model_details = interpreter.get_input_details()\n    mod, _, params = create_relay_module_and_inputs_from_tflite_file(\n        tflite_file, bind_params_by_name=False\n    )\n\n    uma_backend = VanillaAcceleratorBackend()\n    uma_backend.register()\n    target = tvm.target.Target(\"vanilla_accelerator\", host=tvm.target.Target(\"c\"))\n    target_c = tvm.target.Target(\"c\")\n\n    # Generation of test input and output\n    data_shape = [int(x) for x in mod[\"main\"].params[0].type_annotation.shape]\n    data = np.random.uniform(size=data_shape).astype(\"float32\")\n    input_list = {str(tf_model_details[0][\"name\"]): data}\n    output_list = generate_ref_data(mod, input_list, params)\n\n    # UMA partitioning (needs to be done after generate_ref_data)\n    mod = uma_backend.partition(mod)\n\n    aot_test_model = AOTTestModel(module=mod, inputs=input_list, outputs=output_list, params=params)\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": \"greedy_by_size\"}\n    )\n\n    compile_and_run(\n        aot_test_model,\n        test_runner,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        workspace_byte_alignment=1,\n        debug_calculated_workspaces=False,\n        target=[target_c, target],\n    )\n\n\ndef generate_tflite_file(tflite_filename):\n    mnist = tf.keras.datasets.mnist\n    (x_train, y_train), (x_test, y_test) = mnist.load_data()\n    x_train, x_test = x_train / 255.0, x_test / 255.0\n    x_train, x_test = x_train.reshape(-1, 28, 28, 1), x_test.reshape(-1, 28, 28, 1)\n    tf_model = tf.keras.models.Sequential(\n        [\n            tf.keras.Input(shape=(28, 28, 1)),\n            tf.keras.layers.Conv2D(4, (3, 3), padding=\"same\", activation=\"relu\"),\n            tf.keras.layers.Flatten(input_shape=(28, 28)),\n            tf.keras.layers.Dense(32, activation=\"relu\"),\n            tf.keras.layers.Dropout(0.2),\n            tf.keras.layers.Dense(10),\n        ]\n    )\n    output = tf_model(x_train[:1])\n    output = output.numpy()\n    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n    loss(y_train[:1], output).numpy()\n    tf_model.compile(metrics=[\"accuracy\"], optimizer=\"adam\", loss=loss)\n    tf_model.fit(x_train, y_train, epochs=1)\n\n    tflite_converter = tf.lite.TFLiteConverter.from_keras_model(tf_model)\n    tflite_model = tflite_converter.convert()\n    with open(tflite_filename, \"wb\") as f:\n        f.write(tflite_model)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_uma_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport io\n\nimport tvm\nfrom tvm import topi, IRModule\nimport numpy as np\nfrom tvm.contrib import utils, clang\nimport tvm.testing\nfrom tvm import te\nfrom typing import Union\n\n\ndef _create_schedule(\n    placeholder: list,\n    c_code: Union[str, io.TextIOWrapper] = \"\",\n    use_external_conv2d_impl: bool = True,\n):\n    # How to do the same with TE\n    # Add pragma TE\n    # s = te.create_schedule(result.op)\n    # axis = result.op.axis\n    # s[result].pragma(axis[0], \"import_llvm\", c_to_llvm())\n    # with tvm.transform.PassContext(config={\"tir.add_lower_pass\": [(1, my_ai_hw_conv2d_pass)]}):\n    #     mod = tvm.lower(s, [ifmap, weights, result], simple_mode=True)\n    #\n    # llvm_mod = tvm.build(mod, [ifmap, weights, result], target=target, name=\"test_external_conv2d\")\n    # llvm_mod(ifmap_data, weight_data, result_data)\n    if isinstance(c_code, io.TextIOWrapper):\n        c_code_str = c_code.read()\n    elif isinstance(c_code, str):\n        c_code_str = c_code\n    else:\n        raise TypeError()\n\n    assert (\n        use_external_conv2d_impl\n        and c_code_str != \"\"\n        or not use_external_conv2d_impl\n        and c_code_str == \"\"\n    )\n\n    def _c_to_llvm(c_code: str) -> str:\n        temp = utils.tempdir()\n        ll_path = temp.relpath(\"conv2d.ll\")\n        ll_code = clang.create_llvm([c_code], output=ll_path)\n        return ll_code\n\n    func_tir = te.create_prim_func(placeholder)\n    ir_module_from_te = IRModule({\"main\": func_tir})\n    sch_tir = tvm.tir.Schedule(ir_module_from_te)\n    if use_external_conv2d_impl:\n        conv2d_b = sch_tir.get_block(\"conv2d_nchw\")\n        conv2d_l = sch_tir.get_loops(conv2d_b)\n        sch_tir.annotate(conv2d_l[0], \"pragma_import_llvm\", _c_to_llvm(c_code_str))\n    return sch_tir\n\n\ndef _generate_io_arrays(shapes: dict, dev):\n    n, w, h, ci, kw, kh, co = (\n        shapes[\"n\"],\n        shapes[\"w\"],\n        shapes[\"h\"],\n        shapes[\"ci\"],\n        shapes[\"kw\"],\n        shapes[\"kh\"],\n        shapes[\"co\"],\n    )\n\n    ifmap_data = tvm.nd.array(np.random.uniform(size=(n, ci, w, h)).astype(\"float32\"), dev)\n    weight_data = tvm.nd.array(np.random.uniform(size=(co, ci, kh, kw)).astype(\"float32\"), dev)\n    result_data = tvm.nd.array(np.zeros((n, co, w, h)).astype(\"float32\"), dev)\n    return ifmap_data, weight_data, result_data\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_uma/test_uma_vanilla_accelerator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"UMA testcase for the vanilla_accelerator accelerator\"\"\"\nimport pytest\n\nfrom tvm.relay.backend.contrib.uma.api.utils import PassPhase\nfrom tvm.relay.backend.contrib.uma.backend import UMABackend\nfrom apps.uma._template.passes import (\n    MyAiHwConv2dPass as VanillaAcceleratorConv2dPass,\n)\nfrom apps.uma._template.codegen import gen_includes\n\nfrom apps.uma._template.patterns import conv2d_pattern, dense_pattern\nfrom tvm.relay.backend.contrib.uma import uma_available\n\npytestmark = pytest.mark.skipif(not uma_available(), reason=\"UMA not available\")\n\n\nclass VanillaAcceleratorBackend(UMABackend):\n    \"\"\"UMA backend for the VanillaAccelerator accelerator.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n\n        #######################################################################\n        # Relay to Relay function registration\n        #######################################################################\n        self._register_pattern(\"conv2d\", conv2d_pattern())\n        self._register_pattern(\"dense\", dense_pattern())\n\n        #######################################################################\n        # Relay to TIR function registration\n        #######################################################################\n        self._register_tir_pass(PassPhase.TIR_PHASE_0, VanillaAcceleratorConv2dPass())\n\n        #######################################################################\n        # TIR to runtime function registration\n        #######################################################################\n        self._register_codegen(fmt=\"c\", includes=gen_includes)\n\n    @property\n    def target_name(self):\n        return \"vanilla_accelerator\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for functions in tvm/python/tvm/contrib/util.py.\"\"\"\n\nimport datetime\nimport os\nimport shutil\nfrom tvm.contrib import utils\n\n\ndef validate_debug_dir_path(temp_dir, expected_basename):\n    dirname, basename = os.path.split(temp_dir.temp_dir)\n    assert basename == expected_basename, \"unexpected basename: %s\" % (basename,)\n\n    parent_dir = os.path.basename(dirname)\n    create_time = datetime.datetime.strptime(parent_dir.split(\"___\", 1)[0], \"%Y-%m-%dT%H-%M-%S\")\n    assert abs(datetime.datetime.now() - create_time) < datetime.timedelta(seconds=60)\n\n\ndef test_tempdir():\n    assert utils.TempDirectory._KEEP_FOR_DEBUG == False, \"don't submit with KEEP_FOR_DEBUG == True\"\n\n    temp_dir = utils.tempdir()\n    assert os.path.exists(temp_dir.temp_dir)\n\n    old_debug_mode = utils.TempDirectory._KEEP_FOR_DEBUG\n    old_tempdirs = utils.TempDirectory.TEMPDIRS\n    try:\n        for temp_dir_number in range(0, 3):\n            with utils.TempDirectory.set_keep_for_debug():\n                debug_temp_dir = utils.tempdir()\n                try:\n                    validate_debug_dir_path(debug_temp_dir, \"0000\" + str(temp_dir_number))\n                finally:\n                    shutil.rmtree(debug_temp_dir.temp_dir)\n\n        with utils.TempDirectory.set_keep_for_debug():\n            # Create 2 temp_dir within the same session.\n            debug_temp_dir = utils.tempdir()\n            try:\n                validate_debug_dir_path(debug_temp_dir, \"00003\")\n            finally:\n                shutil.rmtree(debug_temp_dir.temp_dir)\n\n            debug_temp_dir = utils.tempdir()\n            try:\n                validate_debug_dir_path(debug_temp_dir, \"00004\")\n            finally:\n                shutil.rmtree(debug_temp_dir.temp_dir)\n\n            with utils.TempDirectory.set_keep_for_debug(False):\n                debug_temp_dir = utils.tempdir()  # This one should get deleted.\n\n                # Simulate atexit hook\n                utils.TempDirectory.remove_tempdirs()\n\n                # Calling twice should be a no-op.\n                utils.TempDirectory.remove_tempdirs()\n\n                # Creating a new TempDirectory should fail now\n                try:\n                    utils.tempdir()\n                    assert False, \"creation should fail\"\n                except utils.DirectoryCreatedPastAtExit:\n                    pass\n\n    finally:\n        utils.TempDirectory.DEBUG_MODE = old_debug_mode\n        utils.TempDirectory.TEMPDIRS = old_tempdirs\n\n\nif __name__ == \"__main__\":\n    test_tempdir()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_verilator/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Infrastructure and tests for Verilator codegen \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_verilator/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Verilator utility functions\"\"\"\n\nimport os\nimport sys\nimport subprocess as sp\nimport json\n\nimport tvm\nfrom tvm import relay\nimport tvm.relay.testing\nfrom tvm import runtime\nfrom tvm.relay import transform\n\n\ndef _register_verilator_op(op_name, supported=True):\n    \"\"\"The helper function to indicate that a given operator can be supported by Verilator.\n\n    Paramters\n    ---------\n    op_name : Str\n        The name of operator that will be registered.\n\n    Returns\n    -------\n    f : callable\n        A function that returns if the operator is supported by DNNL.\n    \"\"\"\n\n    @tvm.ir.register_op_attr(op_name, \"target.verilator\")\n    def _func_wrapper(expr):\n        return supported\n\n    return _func_wrapper\n\n\n_register_verilator_op(\"add\")\n_register_verilator_op(\"nn.bias_add\")\n\n\ndef skip_test():\n    \"\"\"Skip test if it requires the Verilator codegen and it's not present.\"\"\"\n    if not tvm.get_global_func(\"relay.ext.verilator\", True):\n        print(\"Skip test because Verilator codegen is not available.\")\n        return True\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        return True\n    return False\n\n\ndef clear_stats():\n    \"\"\"Clear profiler statistics.\"\"\"\n    f = tvm.get_global_func(\"verilator.profiler_clear\", True)\n    if f:\n        f()\n\n\ndef stats():\n    \"\"\"Get profiler statistics.\"\"\"\n\n    x = tvm.get_global_func(\"verilator.profiler_status\")()\n    return json.loads(x)\n\n\ndef offload(mod):\n    \"\"\"Offload ops based on the registered ops\n\n    Paramters\n    ---------\n    mod : Module\n        The input module.\n\n    Returns\n    -------\n    mod : Module\n        The output module with offloaded ops.\n    \"\"\"\n\n    backend = \"verilator\"\n    mod = transform.AnnotateTarget([backend])(mod)\n    mod = transform.PartitionGraph()(mod)\n    return mod\n\n\ndef verilator_app_path():\n    \"\"\"Create verilator hardware app path.\"\"\"\n\n    cur_dir = os.path.dirname(os.path.realpath(__file__))\n    return os.path.join(\n        cur_dir,\n        \"..\",\n        \"..\",\n        \"..\",\n        \"..\",\n        \"3rdparty\",\n        \"vta-hw\",\n        \"apps\",\n        \"verilator\",\n        \"add\",\n    )\n\n\ndef compile_hardware(lanes):\n    \"\"\"Compile hardware into shared library\n\n    Paramters\n    ---------\n    lanes : Int\n        The number of vector lanes.\n\n    Returns\n    -------\n    path : Str\n        The path of the shared library.\n    \"\"\"\n    lib_name = \"libverilator_{}\".format(lanes)\n    lib_name_ext = \"{}.so\".format(lib_name)\n    lib = os.path.join(verilator_app_path(), lib_name_ext)\n    if not os.path.isfile(lib):\n        opt_lib_name = \"LIB_NAME={}\".format(lib_name)\n        opt_lanes = \"LANES={}\".format(lanes)\n        cmd = []\n        cmd.append(\"make\")\n        cmd.append(\"--directory\")\n        cmd.append(verilator_app_path())\n        cmd.append(opt_lib_name)\n        cmd.append(opt_lanes)\n        sp.run(cmd, check=True, stdout=sp.DEVNULL)\n    return lib\n\n\ndef compiler_opts(lib):\n    \"\"\"Create compiler options\n\n    Paramters\n    ---------\n    lib : Str\n        The path of the hardware shared library.\n\n    Returns\n    -------\n    opts : Dict\n        The compiler options.\n    \"\"\"\n    opts = {\n        \"lib_path\": lib,\n        \"profiler_enable\": True,\n        \"profiler_cycle_counter_id\": 0,\n    }\n    return opts\n\n\ndef run_module(inp, mod, params=None, opts=None):\n    \"\"\"Compile Relay module and hardware library\n\n    Paramters\n    ---------\n    inp : Data\n        The input data.\n\n    mod : Module\n        The relay module.\n\n    params : Parameters\n        The model Parameters.\n\n    opts : Dict\n        The compiler\n\n    Returns\n    -------\n    out : Data\n        The output data.\n    \"\"\"\n\n    with tvm.transform.PassContext(opt_level=3, config={\"relay.ext.verilator.options\": opts}):\n        lib = relay.vm.compile(mod, target=\"llvm\", params=params)\n    code, lib = lib.save()\n    exe = runtime.vm.Executable.load_exec(code, lib)\n    vm = runtime.vm.VirtualMachine(exe, tvm.cpu())\n    out = vm.run(**inp)\n    return out\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_verilator/test_mobilenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te, relay, transform\nfrom tvm.contrib.download import download_testdata\nfrom tvm.contrib import graph_executor as runtime\n\nimport os\nimport pytest\nfrom PIL import Image\nimport numpy as np\n\nfrom test_verilator.infrastructure import (\n    skip_test,\n    compile_hardware,\n    compiler_opts,\n    offload,\n    clear_stats,\n    stats,\n)\n\n\ndef extract(path):\n    \"\"\"Extract a tgz or gz file.\n\n    Paramters\n    ---------\n    path : Str\n        The path of the compressed file.\n    \"\"\"\n    import tarfile\n\n    if path.endswith(\"tgz\") or path.endswith(\"gz\"):\n        dir_path = os.path.dirname(path)\n        tar = tarfile.open(path)\n        tar.extractall(path=dir_path)\n        tar.close()\n    else:\n        raise RuntimeError(\"Could not decompress the file: \" + path)\n\n\ndef get_real_image(im_height, im_width):\n    \"\"\"Get a real image.\n\n    Paramters\n    ---------\n    im_height : Int\n        The image height.\n\n    im_width : Int\n        The image width.\n\n    Returns\n    -------\n    data: Data\n        The image array.\n    \"\"\"\n    repo_base = \"https://github.com/dmlc/web-data/raw/master/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    x = np.array(image).astype(\"uint8\")\n    data = np.reshape(x, (1, im_height, im_width, 3))\n    return data\n\n\ndef get_mobilenet_model():\n    \"\"\"Return mobilenet model.\"\"\"\n    model_url = \"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\"\n    model_path = download_testdata(\n        model_url, \"mobilenet_v1_1.0_224_quant.tgz\", module=[\"tf\", \"official\"]\n    )\n    model_dir = os.path.dirname(model_path)\n    extract(model_path)\n    tflite_model_file = os.path.join(model_dir, \"mobilenet_v1_1.0_224_quant.tflite\")\n    tflite_model_buf = open(tflite_model_file, \"rb\").read()\n    try:\n        import tflite\n\n        return tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite.Model\n\n        return tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\n\ndef get_input_tensor_name():\n    \"\"\"Return input name.\"\"\"\n    return \"input\"\n\n\ndef compile_model_to_relay(model):\n    \"\"\"Compile model to relay.\n\n    Paramters\n    ---------\n    model : Model\n        The input model.\n\n    Returns\n    -------\n    mod: Module\n        The relay module.\n\n    params: Parameters\n        The model parameters.\n    \"\"\"\n    input_tensor = get_input_tensor_name()\n    input_shape = (1, 224, 224, 3)\n    input_dtype = \"uint8\"\n    mod, params = relay.frontend.from_tflite(\n        model,\n        shape_dict={input_tensor: input_shape},\n        dtype_dict={input_tensor: input_dtype},\n    )\n    return mod, params\n\n\ndef run_model(mod, params=None, opts=None):\n    \"\"\"Run model.\n\n    Paramters\n    ---------\n    mod: Module\n        The relay module.\n\n    params: Parameters\n        The model parameters.\n\n    opts: Dict\n        The compiler options.\n\n    Returns\n    -------\n    out: Data\n        The output data.\n    \"\"\"\n    with transform.PassContext(opt_level=3, config={\"relay.ext.verilator.options\": opts}):\n        lib = relay.build(mod, target=\"llvm\", params=params)\n    module = runtime.GraphModule(lib[\"default\"](tvm.cpu()))\n    image_data = get_real_image(224, 224)\n    input_tensor = get_input_tensor_name()\n    module.set_input(input_tensor, image_data)\n    module.run()\n    out = module.get_output(0).numpy()\n    return out\n\n\ndef get_labels():\n    \"\"\"Return labels.\"\"\"\n    label_file_url = \"\".join(\n        [\n            \"https://raw.githubusercontent.com/\",\n            \"tensorflow/tensorflow/master/tensorflow/lite/java/demo/\",\n            \"app/src/main/assets/\",\n            \"labels_mobilenet_quant_v1_224.txt\",\n        ]\n    )\n    label_file = \"labels_mobilenet_quant_v1_224.txt\"\n    label_path = download_testdata(label_file_url, label_file, module=\"data\")\n    # List of 1001 classes\n    with open(label_path) as f:\n        labels = f.readlines()\n    return labels\n\n\ndef check_result(res):\n    \"\"\"Check prediction.\"\"\"\n    labels = get_labels()\n    predictions = np.squeeze(res)\n    prediction = np.argmax(predictions)\n    # 387 is the elephant\n    assert prediction == 387\n\n\ndef print_test_info(lanes, cycles):\n    \"\"\"Print test info\n\n    Paramters\n    ---------\n    lanes : Int\n        The number of vector lanes.\n\n    cycles : Int\n        The number of cycles.\n    \"\"\"\n    print(\n        \"[mobilenet] vector-lanes:{} number of cycles:{} spent in nn.bias_add\".format(lanes, cycles)\n    )\n\n\ndef is_tflite_available():\n    \"\"\"Skip test if tensorflow-lite is not installed.\"\"\"\n    try:\n        import tflite\n\n        return True\n    except:\n        return False\n\n\n@pytest.mark.skipif(skip_test(), reason=\"Skip because Verilator codegen is not available\")\ndef tmobilenet(lanes):\n    \"\"\"Mobilenet test template.\n    Paramters\n    ---------\n    lanes : Int\n        The number of vector lanes.\n    \"\"\"\n    if skip_test():\n        return\n    if not is_tflite_available():\n        return\n    model = get_mobilenet_model()\n    mod, params = compile_model_to_relay(model)\n    mod = offload(mod)\n    lib = compile_hardware(lanes)\n    opts = compiler_opts(lib)\n    clear_stats()\n    res = run_model(mod, params, opts)\n    values = stats()\n    check_result(res)\n    print_test_info(lanes, values[\"cycle_counter\"])\n\n\ndef test_mobilenet():\n    \"\"\"Mobilenet tests.\"\"\"\n    tmobilenet(4)\n    tmobilenet(32)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_verilator/test_verilator_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Verilator codegen tests\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nimport pytest\n\nfrom test_verilator.infrastructure import (\n    skip_test,\n    compile_hardware,\n    compiler_opts,\n    run_module,\n    offload,\n    clear_stats,\n    stats,\n)\n\n\ndef create_module_add(shape, dtype):\n    \"\"\"Create add module.\n\n    Paramters\n    ---------\n    shape : Tuple\n        The shape tuple.\n\n    dtype : Str\n        The data type.\n\n    Returns\n    -------\n    mod: Module\n        The relay module.\n    \"\"\"\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    y = relay.var(\"y\", shape=shape, dtype=dtype)\n    z = relay.add(x, y)\n    f = relay.Function([x, y], z)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    return mod\n\n\ndef create_module_bias_add(xshape, yshape, dtype):\n    \"\"\"Create bias_add module.\n\n    Paramters\n    ---------\n    xshape : Tuple\n        The x shape tuple.\n\n    yshape : Tuple\n        The y shape tuple.\n\n    dtype : Str\n        The data type.\n\n    Returns\n    -------\n    mod: Module\n        The relay module.\n    \"\"\"\n    x = relay.var(\"x\", shape=xshape, dtype=dtype)\n    y = relay.var(\"y\", shape=yshape, dtype=dtype)\n    z = relay.nn.bias_add(x, y, axis=3)\n    f = relay.Function([x, y], z)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    return mod\n\n\ndef run_and_check(xshape, yshape, dtype, mod, opts):\n    \"\"\"Run and check values.\n\n    Paramters\n    ---------\n    xshape : Tuple\n        The x shape tuple.\n\n    yshape : Tuple\n        The y shape tuple.\n\n    dtype : Str\n        The data type.\n\n    mod: Module\n        The relay module.\n\n    opts: Dict\n        The compiler options.\n\n    Returns\n    -------\n    cycles: Int\n        The number of cycles.\n    \"\"\"\n    x_data = np.random.randint(5, size=xshape, dtype=dtype)\n    y_data = np.random.randint(5, size=yshape, dtype=dtype)\n    ref = x_data + y_data\n    inp = {\"x\": x_data, \"y\": y_data}\n    clear_stats()\n    out = run_module(inp, mod, params=None, opts=opts)\n    values = stats()\n    tvm.testing.assert_allclose(out.numpy(), ref, rtol=1e-5, atol=1e-5)\n    return values[\"cycle_counter\"]\n\n\ndef print_test_info(test, lanes, cycles):\n    \"\"\"Print counter\n\n    Paramters\n    ---------\n    test : Str\n        The name of the test.\n\n    lanes : Int\n        The number of vector lanes.\n\n    cycles : Int\n        The number of cycles.\n    \"\"\"\n    print(\"test:{} vector-lanes:{} number of cycles:{}\".format(test, lanes, cycles))\n\n\n@pytest.mark.skipif(skip_test(), reason=\"Skip because Verilator codegen is not available\")\ndef tadd(lanes):\n    \"\"\"Print counter\n\n    Paramters\n    ---------\n    lanes : Int\n        The number of vector lanes.\n    \"\"\"\n    if skip_test():\n        return\n    dtype = \"int32\"\n    shape = (8, 4)\n    mod = create_module_add(shape, dtype)\n    mod = offload(mod)\n    lib = compile_hardware(lanes)\n    opts = compiler_opts(lib)\n    cycles = run_and_check(shape, shape, dtype, mod, opts)\n    print_test_info(\"add\", lanes, cycles)\n\n\n@pytest.mark.skipif(skip_test(), reason=\"Skip because Verilator codegen is not available\")\ndef tbias(lanes):\n    \"\"\"Print counter\n\n    Paramters\n    ---------\n    lanes : Int\n        The number of vector lanes.\n    \"\"\"\n    if skip_test():\n        return\n    dtype = \"int32\"\n    xshape = (1, 112, 112, 32)\n    yshape = (32,)\n    mod = create_module_bias_add(xshape, yshape, dtype)\n    mod = offload(mod)\n    lib = compile_hardware(lanes)\n    opts = compiler_opts(lib)\n    cycles = run_and_check(xshape, yshape, dtype, mod, opts)\n    print_test_info(\"nn.bias_add\", lanes, cycles)\n\n\ndef test_add():\n    \"\"\"add tests.\"\"\"\n    tadd(1)\n    tadd(4)\n\n\ndef test_bias_add():\n    \"\"\"bias_add tests.\"\"\"\n    tbias(1)\n    tbias(32)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_vitis_ai/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Infrastructure and tests for Vitis-AI codegen \"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_vitis_ai/infrastructure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, W0611, C0413\n\n\"\"\"Expose Vitis-AI test functions to the Python frontend\"\"\"\n\nimport sys\nimport numpy as np\n\nimport pytest\n\npytest.importorskip(\"pyxir\")\nimport pyxir.contrib.target.DPUCZDX8G\n\nimport tvm\nfrom tvm import relay\nfrom tvm import runtime\nfrom tvm.relay import transform\nfrom tvm.relay.op.contrib.vitis_ai import partition_for_vitis_ai\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.contrib.target import vitis_ai\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib import utils\n\n\ndef get_cpu_op_count(mod):\n    \"\"\"Traverse graph counting ops offloaded to TVM.\"\"\"\n\n    class Counter(tvm.relay.ExprVisitor):\n        def __init__(self):\n            super().__init__()\n            self.count = 0\n\n        def visit_call(self, call):\n            if isinstance(call.op, tvm.ir.Op):\n                self.count += 1\n\n            super().visit_call(call)\n\n    c = Counter()\n    c.visit(mod[\"main\"])\n    return c.count\n\n\ndef build_module(\n    mod,\n    target,\n    dpu_target=\"DPUCADF8H\",\n    params=None,\n    enable_vitis_ai=True,\n    tvm_ops=0,\n    vitis_ai_partitions=1,\n):\n    \"\"\"Build module for Vitis-AI codegen.\"\"\"\n    if isinstance(mod, tvm.relay.expr.Call):\n        mod = tvm.IRModule.from_expr(mod)\n    if params is None:\n        params = {}\n\n    with tvm.transform.PassContext(\n        opt_level=3, config={\"relay.ext.vitis_ai.options.target\": dpu_target}\n    ):\n        if enable_vitis_ai:\n            mod = partition_for_vitis_ai(mod, params, dpu_target)\n            tvm_op_count = get_cpu_op_count(mod)\n            assert tvm_op_count == tvm_ops, \"Got {} TVM operators, expected {}\".format(\n                tvm_op_count, tvm_ops\n            )\n            partition_count = 0\n            for global_var in mod.get_global_vars():\n                if \"vitis_ai\" in global_var.name_hint:\n                    partition_count += 1\n\n            assert (\n                vitis_ai_partitions == partition_count\n            ), \"Got {} Vitis-AI partitions, expected {}\".format(\n                partition_count, vitis_ai_partitions\n            )\n        relay.backend.te_compiler.get().clear()\n        return relay.build(mod, target, params=params)\n\n\ndef update_lib(lib, cross_compile=None):\n    tmp_path = utils.tempdir()\n    lib_name = \"lib.so\"\n    lib_path = tmp_path.relpath(lib_name)\n    if cross_compile:\n        lib.export_library(lib_path, cc=cross_compile)\n    else:\n        lib.export_library(lib_path)\n    lib = runtime.load_module(lib_path)\n    return lib\n\n\ndef extract_vitis_ai_modules(module):\n    \"\"\"Get the Vits-AI runtime module from llvm module.\"\"\"\n    return list(\n        filter(lambda mod: mod.type_key == \"VitisAIRuntime\", module.get_lib().imported_modules)\n    )\n\n\ndef verify_codegen(\n    module, num_vitis_ai_modules=1, params=None, target=\"llvm\", tvm_ops=0, dpu_target=\"DPUCADX8G\"\n):\n    \"\"\"Check Vitis-AI codegen against a known good output.\"\"\"\n    module = build_module(\n        module,\n        target,\n        params=params,\n        dpu_target=dpu_target,\n        tvm_ops=tvm_ops,\n        vitis_ai_partitions=num_vitis_ai_modules,\n    )\n    vitis_ai_modules = extract_vitis_ai_modules(module)\n\n    assert len(vitis_ai_modules) == num_vitis_ai_modules, (\n        f\"The number of Vitis-AI modules produced ({len(vitis_ai_modules)}) does not \"\n        f\"match the expected value ({num_vitis_ai_modules}).\"\n    )\n\n\ndef verify_result(\n    mod,\n    map_inputs,\n    out_shape,\n    result,\n    tol=1e-5,\n    target=\"llvm\",\n    device=tvm.cpu(),\n    params=None,\n    dpu_target=\"DPUCADX8G\",\n    tvm_ops=0,\n):\n    \"\"\"To check the result between reference and byoc vitis-ai flow\"\"\"\n\n    lib = build_module(mod, target, params=params, dpu_target=dpu_target, tvm_ops=tvm_ops)\n    lib = update_lib(lib)\n    rt_mod = graph_executor.GraphModule(lib[\"default\"](tvm.cpu()))\n\n    for name, data in map_inputs.items():\n        rt_mod.set_input(name, data)\n    rt_mod.set_input(**params)\n    rt_mod.run()\n\n    out_shapes = out_shape if isinstance(out_shape, list) else [out_shape]\n    results = result if isinstance(result, list) else [result]\n\n    for idx, shape in enumerate(out_shapes):\n        out = tvm.nd.empty(shape, device=device)\n        out = rt_mod.get_output(idx, out)\n        tvm.testing.assert_allclose(out.numpy(), results[idx], rtol=tol, atol=tol)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_vitis_ai/test_vitis_ai_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, W0611, C0413\n\n\"\"\"Vitis-AI codegen tests\"\"\"\n\nimport sys\n\nimport numpy as np\nimport pytest\n\npytest.importorskip(\"pyxir\")\nimport pyxir.contrib.target.DPUCADF8H\nimport pyxir.contrib.target.DPUCAHX8H\nimport pyxir.contrib.target.DPUCAHX8L\nimport pyxir.contrib.target.DPUCVDX8G\nimport pyxir.contrib.target.DPUCVDX8H\nimport pyxir.contrib.target.DPUCZDX8G\nimport tvm\nfrom tvm import relay\nfrom tvm.testing import requires_vitis_ai\nfrom tvm.contrib.target import vitis_ai\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.contrib.vitis_ai import annotation\n\nfrom .infrastructure import verify_codegen\n\n\ndef set_func_attr(func, compile_name, symbol_name):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compile_name)\n    func = func.with_attr(\"global_symbol\", symbol_name)\n    return func\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_conv2d(dpu_target):\n    \"\"\"Test conv2d operator for Vitis AI DPU targets\"\"\"\n\n    x = relay.var(\"x\", shape=(1, 3, 224, 224))\n    w = relay.const(np.zeros((16, 3, 3, 3), dtype=\"float32\"))\n    y = relay.nn.conv2d(x, w, strides=[2, 2], padding=[1, 1, 1, 1], kernel_size=[3, 3])\n    func = relay.Function([x], y)\n    params = {}\n    params[\"w\"] = np.random.rand(16, 3, 3, 3).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, params=params, dpu_target=dpu_target, tvm_ops=2)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\"dpu_target\", [\"DPUCAHX8L\", \"DPUCZDX8G-zcu104\"])\ndef test_depthwise_conv(dpu_target):\n    \"\"\"Test depthwise_conv operator for Vitis-AI DPUCZDX8G-zcu104 target\"\"\"\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, 1, 3, 3)\n    data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n    weights = relay.var(\"weights\", shape=(wshape), dtype=dtype)\n    depthwise_conv2d = relay.nn.conv2d(data, weights, kernel_size=(3, 3), padding=(1, 1), groups=32)\n    func = relay.Function([data, weights], depthwise_conv2d)\n    params = {}\n    params[\"weights\"] = np.random.randn(32, 1, 3, 3).astype(dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, params=params, dpu_target=dpu_target, tvm_ops=2)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_bias_add(dpu_target):\n    \"\"\"Test bias_add operator for Vitis AI DPU targets\"\"\"\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n    bias = relay.var(\"bias\", relay.TensorType((32,), dtype))\n    out = relay.nn.bias_add(data, bias)\n    func = relay.Function([data, bias], out)\n    params = {}\n    params[\"bias\"] = np.random.randn(32).astype(dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, params=params, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_relu(dpu_target):\n    \"\"\"Test relu operator for Vitis AI DPU targets\"\"\"\n\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.relu(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target, num_vitis_ai_modules=0, tvm_ops=1)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_batchnorm(dpu_target):\n    \"\"\"Test batchnorm operator for Vitis AI DPU targets\"\"\"\n\n    data = relay.var(\"data\", shape=(1, 16, 112, 112))\n    bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n    bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n    bn_mmean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n    bn_mvar = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n    bn_output = relay.nn.batch_norm(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n    func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output[0])\n    params = {}\n    params[\"bn_gamma\"] = np.random.rand(16).astype(\"float32\")\n    params[\"bn_beta\"] = np.random.rand(16).astype(\"float32\")\n    params[\"bn_mean\"] = np.random.rand(16).astype(\"float32\")\n    params[\"bn_var\"] = np.random.rand(16).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, params=params, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_add(dpu_target):\n    \"\"\"Test add operator for Vitis AI DPU targets\"\"\"\n\n    shape = (10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = x + x\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_global_avg_pool2d(dpu_target):\n    \"\"\"Test global_avg_pool2d operator for Vitis AI DPU targets\"\"\"\n\n    shape = (10, 10, 7, 7)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.global_avg_pool2d(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_avg_pool2d(dpu_target):\n    \"\"\"Test avg_pool2d for operator Vitis AI DPU targets\"\"\"\n\n    shape = (10, 10, 10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.avg_pool2d(x, pool_size=(3, 3))\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_max_pool2d(dpu_target):\n    \"\"\"Test max_pool2d for operator Vitis AI DPU targets\"\"\"\n\n    shape = (64, 512, 10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.max_pool2d(x, pool_size=(3, 3))\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_global_max_pool2d(dpu_target):\n    \"\"\"Test global_maxpool2d operator for Vitis AI DPU targets\"\"\"\n\n    shape = (1, 512, 7, 7)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.global_max_pool2d(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_upsampling(dpu_target):\n    \"\"\"Test upsampling operator for Vitis AI DPU targets\"\"\"\n\n    shape = (64, 512, 10, 10)\n    x = relay.var(\"x\", shape=shape)\n    y = relay.nn.upsampling(x, scale_h=2, scale_w=2)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, dpu_target=dpu_target)\n\n\n@pytest.mark.skip(\n    reason=\"I and O used to be mixed up in kernel layouts in TVM.\"\n    \"This is fixed, but vitis needs to adopt the new convention.\"\n    \"To change, simply remove this line:\"\n    \"https://github.com/Xilinx/pyxir/blob/bef661d6d77adcdbd2cf4163f2cf3a1d31d40406/\"\n    \"python/pyxir/frontend/tvm/relay_tools/relay_l2_convolution.py#L380\"\n)\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_conv2d_transpose(dpu_target):\n    \"\"\"Test conv2d_transpose operator for Vitis AI DPU targets\"\"\"\n\n    dshape = (1, 3, 18, 18)\n    kshape = (3, 10, 3, 3)\n    x = relay.var(\"x\", shape=dshape)\n    w = relay.const(np.zeros(kshape, dtype=\"float32\"))\n    y = relay.nn.conv2d_transpose(\n        x,\n        w,\n        channels=10,\n        kernel_size=(3, 3),\n        strides=(1, 1),\n        padding=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n    )\n    func = relay.Function([x], y)\n    params = {}\n    dtype = \"float32\"\n    params[\"w\"] = np.random.uniform(size=kshape).astype(dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    verify_codegen(mod, params=params, dpu_target=dpu_target)\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\n    \"dpu_target\",\n    [\"DPUCADF8H\", \"DPUCAHX8H-u50\", \"DPUCAHX8L\", \"DPUCVDX8H\", \"DPUCVDX8G\", \"DPUCZDX8G-zcu104\"],\n)\ndef test_annotate(dpu_target):\n    \"\"\"Test annotation operator for Vitis AI DPU targets\"\"\"\n\n    def partition(dpu_target):\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        conv = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n        bn_output = relay.nn.batch_norm(conv, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n\n        func = relay.Function(\n            [data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output.astuple()\n        )\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n        params = {}\n        params[\"weight\"] = np.random.rand(16, 3, 3, 3).astype(\"float32\")\n        params[\"bn_gamma\"] = np.random.rand(16).astype(\"float32\")\n        params[\"bn_beta\"] = np.random.rand(16).astype(\"float32\")\n        params[\"bn_mean\"] = np.random.rand(16).astype(\"float32\")\n        params[\"bn_var\"] = np.random.rand(16).astype(\"float32\")\n        mod = annotation(mod, params, dpu_target)\n\n        opt_pass = tvm.transform.Sequential(\n            [\n                transform.MergeCompilerRegions(),\n                transform.PartitionGraph(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3):\n            mod = opt_pass(mod)\n        return mod\n\n    def expected():\n        # function variables for conv2d\n        data0 = relay.var(\"data0\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight0 = relay.var(\"weight0\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        conv = relay.nn.conv2d(\n            data=data0, weight=weight0, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n\n        # function variables for batch_norm\n        bn_gamma0 = relay.var(\"bn_gamma0\", relay.TensorType((16,), \"float32\"))\n        bn_beta0 = relay.var(\"bn_beta0\", relay.TensorType((16,), \"float32\"))\n        bn_mmean0 = relay.var(\"bn_mean0\", relay.TensorType((16,), \"float32\"))\n        bn_mvar0 = relay.var(\"bn_var0\", relay.TensorType((16,), \"float32\"))\n        bn = relay.nn.batch_norm(conv, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0)\n        func0 = relay.Function(\n            [data0, weight0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0], bn.astuple()\n        )\n        func0 = set_func_attr(func0, \"vitis_ai\", \"tvmgen_default_vitis_ai_main_0\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_vitis_ai_main_0\")\n        mod = tvm.IRModule()\n        mod[gv0] = func0\n        mod = relay.transform.InferType()(mod)\n\n        # main function\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n        call0 = gv0(data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        mod[\"main\"] = relay.Function([data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], call0)\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    partitioned_mod = partition(dpu_target)\n\n    ref_mod = expected()\n\n    assert tvm.ir.structural_equal(partitioned_mod, ref_mod, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        sys.exit(0)\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/contrib/test_vitis_ai/test_vitis_ai_runtime_cpu_part.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name, W0611, C0413\n\n\"\"\"Vitis-AI runtime test for CPU only part\n\nThis test verifies as much as possible whether the a model can be correctly offloaded\nand executed for Vitis-AI acceleration. This entails:\n    - Annotating and partitioning model for Vitis-AI acceleration\n    - Building a Vitis-AI PyXIR runtime module with on-the-fly quantization enabled\n    - Run first iteration of on-the-fly quantization flow. This will always be run\n      on CPU as the first N (parameter) will be used for collecting calibration data\n      for quantization.\n\nNOTE This is not a full end-to-end test as we need the full Vitis-AI docker environment\nand access to an FPGA instance for that. This test verifies the Vitis-AI flow as much as\npossible without requiring access to dedicated docker environment and/or hardware setup.\nNOTE Quantization is not being tested (we need to be inside Vitis-AI docker environment\nfor that) buth the internal representation used for quantization is being generated and\nfunctionally tested (CPU).\n\"\"\"\n\nimport sys\nimport numpy as np\n\nimport pytest\n\npytest.importorskip(\"pyxir\")\nimport pyxir.contrib.target.DPUCADF8H\nimport pyxir.contrib.target.DPUCVDX8H\nimport pyxir.contrib.target.DPUCZDX8G\n\nimport tvm\nimport tvm.relay.testing\nfrom tvm import relay\nfrom tvm.testing import requires_vitis_ai\n\nfrom .infrastructure import verify_result\n\n\n@requires_vitis_ai\n@pytest.mark.parametrize(\"dpu_target\", [\"DPUCADF8H\", \"DPUCVDX8H\", \"DPUCZDX8G-zcu104\"])\ndef test_extern_vitis_ai_resnet18(dpu_target):\n    \"\"\"Test first part of Vitis AI on-the-fly quantization runtime with ResNet 18 model\"\"\"\n\n    dtype = \"float32\"\n    ishape = (1, 3, 224, 224)\n    mod, params = relay.testing.resnet.get_workload(num_layers=18, batch_size=1)\n    ref_mod, params = relay.testing.resnet.get_workload(num_layers=18, batch_size=1)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n        i_data, **params\n    )\n\n    verify_result(\n        mod,\n        {\"data\": i_data},\n        (1, 1000),\n        ref_res.numpy(),\n        tol=1e-5,\n        params=params,\n        dpu_target=dpu_target,\n        tvm_ops=7,\n    )\n\n\nif __name__ == \"__main__\":\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        sys.exit(0)\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/conftest.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport pytest\nimport tarfile\nimport textwrap\n\nimport numpy as np\n\nfrom PIL import Image\n\nimport tvm\nfrom tvm import relay\nfrom tvm.driver import tvmc\n\nfrom tvm.contrib.download import download_testdata\n\n# Support functions\n\n\ndef download_and_untar(model_url, model_sub_path, temp_dir):\n    model_tar_name = os.path.basename(model_url)\n    model_path = download_testdata(model_url, model_tar_name, module=[\"tvmc\"])\n\n    if model_path.endswith(\"tgz\") or model_path.endswith(\"gz\") or model_path.endswith(\"tar\"):\n        tar = tarfile.open(model_path)\n        tar.extractall(path=temp_dir)\n        tar.close()\n\n    return os.path.join(temp_dir, model_sub_path)\n\n\n# PyTest fixtures\n\n\n@pytest.fixture(scope=\"session\")\ndef tflite_mobilenet_v1_1_quant(tmpdir_factory):\n    base_url = \"https://storage.googleapis.com/download.tensorflow.org/models\"\n    model_url = \"mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\"\n    model_file = download_and_untar(\n        \"{}/{}\".format(base_url, model_url),\n        \"mobilenet_v1_1.0_224_quant.tflite\",\n        temp_dir=tmpdir_factory.mktemp(\"data\"),\n    )\n\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef pb_mobilenet_v1_1_quant(tmpdir_factory):\n    base_url = \"https://storage.googleapis.com/download.tensorflow.org/models\"\n    model_url = \"mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz\"\n    model_file = download_and_untar(\n        \"{}/{}\".format(base_url, model_url),\n        \"mobilenet_v1_1.0_224_frozen.pb\",\n        temp_dir=tmpdir_factory.mktemp(\"data\"),\n    )\n\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef keras_resnet50(tmpdir_factory):\n    try:\n        from tensorflow.keras.applications.resnet50 import ResNet50\n    except ImportError:\n        # not all environments provide TensorFlow, so skip this fixture\n        # if that is that case.\n        return \"\"\n\n    model_file_name = \"{}/{}\".format(tmpdir_factory.mktemp(\"data\"), \"resnet50.h5\")\n    model = ResNet50(include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000)\n    model.save(model_file_name)\n\n    return model_file_name\n\n\n@pytest.fixture(scope=\"session\")\ndef keras_simple(tmpdir_factory):\n    try:\n        from tensorflow import keras\n    except ImportError:\n        # not all environments provide TensorFlow, so skip this fixture\n        # if that is that case.\n        return \"\"\n\n    model_file_name = \"{}/{}\".format(tmpdir_factory.mktemp(\"data\"), \"simple_conv.h5\")\n    model = keras.Sequential(\n        [\n            keras.layers.InputLayer(input_shape=[32, 32, 3], batch_size=1),\n            keras.layers.Conv2D(8, kernel_size=(3, 3)),\n            keras.layers.Flatten(),\n            keras.layers.Dense(64),\n        ]\n    )\n    model.save(model_file_name)\n\n    return model_file_name\n\n\n@pytest.fixture(scope=\"session\")\ndef pytorch_resnet18(tmpdir_factory):\n    try:\n        import torch\n        import torchvision.models as models\n    except ImportError:\n        # Not all environments provide Pytorch, so skip if that's the case.\n        return \"\"\n    model = models.resnet18()\n    model_file_name = \"{}/{}\".format(tmpdir_factory.mktemp(\"data\"), \"resnet18.pth\")\n    # Trace model into torchscript.\n    traced_cpu = torch.jit.trace(model, torch.randn(1, 3, 224, 224))\n    torch.jit.save(traced_cpu, model_file_name)\n\n    return model_file_name\n\n\n@pytest.fixture(scope=\"session\")\ndef pytorch_mobilenetv2_quantized(tmpdir_factory):\n    try:\n        import torch\n        import torchvision.models as models\n    except ImportError:\n        # Not all environments provide Pytorch, so skip if that's the case.\n        return \"\"\n    model = models.quantization.mobilenet_v2(quantize=True)\n    model_file_name = \"{}/{}\".format(tmpdir_factory.mktemp(\"data\"), \"mobilenet_v2_quantized.pth\")\n    # Trace model into torchscript.\n    traced_cpu = torch.jit.trace(model, torch.randn(1, 3, 224, 224))\n    torch.jit.save(traced_cpu, model_file_name)\n\n    return model_file_name\n\n\n@pytest.fixture(scope=\"session\")\ndef onnx_resnet50():\n    base_url = \"https://github.com/onnx/models/raw/bd206494e8b6a27b25e5cf7199dbcdbfe9d05d1c/vision/classification/resnet/model\"\n    file_to_download = \"resnet50-v2-7.onnx\"\n    model_file = download_testdata(\n        \"{}/{}\".format(base_url, file_to_download), file_to_download, module=[\"tvmc\"]\n    )\n\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef paddle_resnet50(tmpdir_factory):\n    base_url = \"https://bj.bcebos.com/x2paddle/models\"\n    model_url = \"paddle_resnet50.tar\"\n    model_file = download_and_untar(\n        \"{}/{}\".format(base_url, model_url),\n        \"paddle_resnet50/model.pdmodel\",\n        temp_dir=tmpdir_factory.mktemp(\"data\"),\n    )\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef onnx_mnist():\n    base_url = \"https://github.com/onnx/models/raw/bd206494e8b6a27b25e5cf7199dbcdbfe9d05d1c/vision/classification/mnist/model\"\n    file_to_download = \"mnist-1.onnx\"\n    model_file = download_testdata(\n        \"{}/{}\".format(base_url, file_to_download), file_to_download, module=[\"tvmc\"]\n    )\n\n    return model_file\n\n\n@pytest.fixture\ndef tflite_compile_model(tmpdir_factory):\n    \"\"\"Support function that returns a TFLite compiled module\"\"\"\n\n    def model_compiler(model_file, **overrides):\n        package_path = tmpdir_factory.mktemp(\"data\").join(\"mock.tar\")\n        tvmc_model = tvmc.frontends.load_model(model_file)\n        args = {\"target\": \"llvm\", **overrides}\n        return tvmc.compiler.compile_model(tvmc_model, package_path=package_path, **args)\n\n    # Returns a TVMCPackage\n    return model_compiler\n\n\n@pytest.fixture\ndef relay_compile_model(tmpdir_factory):\n    \"\"\"Support function that returns a TFLite compiled module\"\"\"\n\n    def model_compiler(model_file, shape_dict, **overrides):\n        package_path = tmpdir_factory.mktemp(\"data\").join(\"mock.tar\")\n        tvmc_model = tvmc.frontends.load_model(\n            model_file, model_format=\"relay\", shape_dict=shape_dict\n        )\n        args = {\"target\": \"llvm\", **overrides}\n        return tvmc.compiler.compile_model(tvmc_model, package_path=package_path, **args)\n\n    # Returns a TVMCPackage\n    return model_compiler\n\n\n@pytest.fixture(scope=\"session\")\ndef imagenet_cat(tmpdir_factory):\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    cat_file_name = \"imagenet_cat.npz\"\n\n    cat_url = \"https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true\"\n    image_path = download_testdata(cat_url, \"inputs\", module=[\"tvmc\"])\n    resized_image = Image.open(image_path).resize((224, 224))\n    image_data = np.asarray(resized_image).astype(\"float32\")\n    image_data = np.expand_dims(image_data, axis=0)\n\n    cat_file_full_path = os.path.join(tmpdir_name, cat_file_name)\n    np.savez(cat_file_full_path, input=image_data)\n\n    return cat_file_full_path\n\n\n@pytest.fixture(scope=\"session\")\ndef tflite_mobilenet_v1_0_25_128(tmpdir_factory):\n    base_url = \"https://storage.googleapis.com/download.tensorflow.org/models\"\n    model_url = \"mobilenet_v1_2018_02_22/mobilenet_v1_0.25_128.tgz\"\n    model_file = download_and_untar(\n        \"{}/{}\".format(base_url, model_url),\n        \"mobilenet_v1_0.25_128.tflite\",\n        temp_dir=tmpdir_factory.mktemp(\"data\"),\n    )\n\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef tflite_cnn_s_quantized(tmpdir_factory):\n    base_url = \"https://github.com/ARM-software/ML-zoo/raw/master/models/keyword_spotting/cnn_small/tflite_int8/\"\n    file_to_download = \"cnn_s_quantized.tflite\"\n    model_file = download_testdata(\n        \"{}/{}\".format(base_url, file_to_download), file_to_download, module=[\"tvmc\"]\n    )\n    return model_file\n\n\n@pytest.fixture(scope=\"session\")\ndef relay_text_conv2d(tmpdir_factory):\n    file_path = os.path.join(tmpdir_factory.mktemp(\"model\"), \"relay.txt\")\n\n    RELAY_MODEL = textwrap.dedent(\n        \"\"\"\\\n        #[version = \"0.0.5\"]\n        def @main(%data : Tensor[(1, 3, 64, 64), uint8], %weight : Tensor[(3, 3, 5, 5), int8]) {\n            %1 = nn.conv2d(\n                 %data,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %2 = cast(nn.max_pool2d(%1, pool_size=[3, 3]), dtype=\"int8\");\n            %3 = nn.conv2d(\n                 %2,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %4 = nn.max_pool2d(%3, pool_size=[3, 3]);\n            %4\n        }\n    \"\"\"\n    )\n\n    with open(file_path, \"w\") as relay_text:\n        relay_text.write(RELAY_MODEL)\n    return file_path\n\n\n@pytest.fixture(scope=\"session\")\ndef relay_conv2d():\n    \"\"\"\n    Simple conv2d Relay implementation.\n    \"\"\"\n    dtype = \"float32\"\n\n    x = relay.var(\"x\", shape=(1, 4, 2, 2), dtype=dtype)\n    weight = relay.const(np.random.uniform(size=(2, 4, 2, 2)), dtype=dtype)\n    x = relay.nn.conv2d(x, weight)\n    func = relay.Function(relay.analysis.free_vars(x), x)\n    return tvm.IRModule.from_expr(func)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_autoscheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport platform\nimport pytest\nimport os\n\nfrom os import path\n\nfrom tvm import auto_scheduler\nfrom tvm.driver import tvmc\n\n\ndef _get_tasks(model):\n    tvmc_model = tvmc.frontends.load_model(model)\n    tasks, weights = tvmc.autotuner.autoscheduler_get_tuning_tasks(\n        tvmc_model.mod, tvmc_model.params, \"llvm\"\n    )\n    return (tasks, weights)\n\n\ndef _autoscheduler_test_helper(model, tmpdir_name, early_stopping=1, prior_records=None):\n    tvmc_model = tvmc.frontends.load_model(model)\n    log_file = os.path.join(tmpdir_name, \"autoscheduler.json\")\n\n    hardware_params = auto_scheduler.HardwareParams(num_cores=4, target=\"llvm\")\n\n    tvmc.tune(\n        tvmc_model,\n        target=\"llvm\",\n        tuning_records=log_file,\n        prior_records=prior_records,\n        early_stopping=early_stopping,\n        enable_autoscheduler=True,\n        trials=2,\n        hardware_params=hardware_params,\n    )\n\n    # testing whether the log file was produced\n    assert path.exists(log_file), \"autoscheduler log file should exist\"\n\n    with auto_scheduler.ApplyHistoryBest(log_file) as best:\n        assert isinstance(\n            best, auto_scheduler.dispatcher.ApplyHistoryBest\n        ), \"unable to load the best results of tuning\"\n\n    return log_file\n\n\ndef test_get_tuning_tasks(keras_simple):\n    pytest.importorskip(\"tensorflow\")\n\n    tasks, weights = _get_tasks(keras_simple)\n    expected_task_type = auto_scheduler.SearchTask\n\n    assert type(tasks) is list\n    assert len(tasks) > 0\n    assert all([type(x) is expected_task_type for x in tasks]) is True\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tune_tasks(keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _autoscheduler_test_helper(keras_simple, tmpdir_name)\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tune_tasks__tuning_records(keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    output_log_phase_1 = _autoscheduler_test_helper(keras_simple, tmpdir_name)\n\n    # Exercises transfer learning by making sure a previous log exists\n    _autoscheduler_test_helper(keras_simple, tmpdir_name, prior_records=output_log_phase_1)\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tune_tasks__no_early_stopping(keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _autoscheduler_test_helper(keras_simple, tmpdir_name, early_stopping=None)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_autotuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport platform\nimport pytest\nimport os\n\nfrom unittest import mock\n\nfrom os import path\nfrom pathlib import Path\n\nimport tvm\nfrom tvm import autotvm\nfrom tvm.driver import tvmc\n\n\ndef _get_tasks(model):\n    tvmc_model = tvmc.frontends.load_model(model)\n    return tvmc.autotuner.autotvm_get_tuning_tasks(tvmc_model.mod, tvmc_model.params, \"llvm\")\n\n\ndef _get_measure_options():\n    return autotvm.measure_option(\n        builder=autotvm.LocalBuilder(build_func=\"default\"), runner=\"local\"\n    )\n\n\ndef _tuner_test_helper(model, tuner_name, tmpdir_name, early_stopping=1, prior_records=None):\n    tvmc_model = tvmc.frontends.load_model(model)\n    log_file = os.path.join(tmpdir_name, \"log_{}.txt\".format(tuner_name))\n\n    tvmc.tune(\n        tvmc_model,\n        target=\"llvm\",\n        tuning_records=log_file,\n        prior_records=prior_records,\n        tuner=tuner_name,\n        trials=4,\n        early_stopping=early_stopping,\n    )\n\n    # testing whether the log file was produced\n    assert path.exists(log_file), \"tuning log file should exist\"\n\n    with autotvm.apply_history_best(log_file) as best:\n        assert isinstance(\n            best, autotvm.task.dispatcher.ApplyHistoryBest\n        ), \"unable to load the best results of tuning\"\n\n    return log_file\n\n\ndef test_get_tuning_tasks(onnx_mnist):\n    pytest.importorskip(\"onnx\")\n\n    sut = _get_tasks(onnx_mnist)\n    expected_task_type = autotvm.task.Task\n\n    assert type(sut) is list\n    assert len(sut) > 0\n    assert all([type(x) is expected_task_type for x in sut]) is True\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tune_tasks__tuner__xgb(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"xgb\", tmpdir_name)\n\n\ndef test_tune_tasks__tuner__xgb_knob(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"xgb_knob\", tmpdir_name)\n\n\ndef test_tune_tasks__tuner__ga(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"ga\", tmpdir_name)\n\n\ndef test_tune_tasks__tuner__random(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"random\", tmpdir_name)\n\n\ndef test_tune_tasks__tuner__gridsearch(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"gridsearch\", tmpdir_name)\n\n\ndef test_tune_tasks__tuner__gridsearch__tuning_records(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    output_log_phase_1 = _tuner_test_helper(onnx_mnist, \"gridsearch\", tmpdir_name)\n\n    # Exercises transfer learning by making sure a previous log exists\n    _tuner_test_helper(onnx_mnist, \"gridsearch\", tmpdir_name, prior_records=output_log_phase_1)\n\n\ndef test_tune_tasks__tuner__ga__empty_tasks(tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    log_file = os.path.join(tmpdir_name, \"log_{}.txt\".format(\"ga\"))\n\n    tvmc.autotuner.tune_tasks(\n        tasks=[],\n        log_file=log_file,\n        measure_option=_get_measure_options(),\n        tuner=\"ga\",\n        trials=1,\n        early_stopping=1,\n    )\n\n\ndef test_tune_tasks__tuner__xgb__no_early_stopping(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"xgb\", tmpdir_name, early_stopping=None)\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tune_tasks__tuner__xgb__no_tuning_records(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"xgb\", tmpdir_name, prior_records=None)\n\n\ndef test_tune_tasks__invalid_tuner(onnx_mnist, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tasks = _get_tasks(onnx_mnist)\n    log_file = os.path.join(tmpdir_factory.mktemp(\"data\"), \"log2.txt\")\n\n    with pytest.raises(tvmc.TVMCException):\n        tvmc.autotuner.tune_tasks(tasks, log_file, _get_measure_options(), \"invalid_tuner\", 1, 1)\n\n\n@mock.patch(\"tvm.driver.tvmc.autotuner.auto_scheduler.HardwareParams\", return_value=None)\n@mock.patch(\"tvm.driver.tvmc.autotuner.tune_model\", return_value=None)\n@mock.patch(\"tvm.driver.tvmc.frontends.load_model\", return_value=None)\ndef test_tune_rpc_tracker_parsing(mock_load_model, mock_tune_model, mock_auto_scheduler):\n    cli_args = mock.MagicMock()\n    cli_args.rpc_tracker = \"10.0.0.1:9999\"\n    # FILE is not used but it's set to a valid value here to avoid it being set\n    # by mock to a MagicMock class, which won't pass the checks for valid FILE.\n    fake_input_file = \"./fake_input_file.tflite\"\n    Path(fake_input_file).touch()\n    cli_args.FILE = fake_input_file\n\n    tvmc.autotuner.drive_tune(cli_args)\n\n    os.remove(fake_input_file)\n\n    mock_tune_model.assert_called_once()\n\n    # inspect the mock call, to search for specific arguments\n    _, _, kwargs = mock_tune_model.mock_calls[0]\n    assert \"hostname\" in kwargs\n    assert \"10.0.0.1\" == kwargs[\"hostname\"]\n    assert \"port\" in kwargs\n    assert 9999 == kwargs[\"port\"]\n\n\n@mock.patch(\"tvm.transform.PassContext\", return_value=tvm.transform.PassContext())\ndef test_autotune_pass_context(mock_pc, onnx_mnist, tmpdir_factory):\n    \"\"\"\n    Check that the pass context while tuning is as expected.\n    \"\"\"\n    pytest.importorskip(\"onnx\")\n\n    tmpdir_name = tmpdir_factory.mktemp(\"data\")\n    _tuner_test_helper(onnx_mnist, \"gridsearch\", tmpdir_name)\n\n    # AutoTVM overrides the pass context later in the pipeline to disable AlterOpLayout\n    assert mock_pc.call_count == 2\n    assert mock_pc.call_args_list[0][1][\"opt_level\"] == 3\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_command_line.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport platform\nimport pytest\nimport shutil\n\nfrom pytest_lazyfixture import lazy_fixture\nfrom unittest import mock\n\nimport tvm\nfrom tvm.driver.tvmc.main import _main\nfrom tvm.driver.tvmc.model import TVMCException\nfrom tvm.driver.tvmc import compiler\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tvmc_cl_workflow(keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n\n    tmpdir = tmpdir_factory.mktemp(\"data\")\n\n    # Test model tuning\n    log_path = os.path.join(tmpdir, \"keras-autotuner_records.json\")\n    tuning_str = (\n        f\"tvmc tune --target llvm --output {log_path} \"\n        f\"--trials 2 --enable-autoscheduler {keras_simple}\"\n    )\n    tuning_args = tuning_str.split(\" \")[1:]\n    _main(tuning_args)\n    assert os.path.exists(log_path)\n\n    # Test model compilation\n    package_path = os.path.join(tmpdir, \"keras-tvm.tar\")\n    compile_str = (\n        f\"tvmc compile --target llvm --tuning-records {log_path} \"\n        f\"--output {package_path} {keras_simple}\"\n    )\n    compile_args = compile_str.split(\" \")[1:]\n    _main(compile_args)\n    assert os.path.exists(package_path)\n\n    # Test running the model\n    output_path = os.path.join(tmpdir, \"predictions.npz\")\n    run_str = f\"tvmc run --end-to-end --outputs {output_path} {package_path}\"\n    run_args = run_str.split(\" \")[1:]\n    _main(run_args)\n    assert os.path.exists(output_path)\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_tvmc_cl_workflow_json_config(keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n    tune_config_file = \"tune_config_test\"\n    tmpdir = tmpdir_factory.mktemp(\"data\")\n\n    # Test model tuning\n    log_path = os.path.join(tmpdir, \"keras-autotuner_records.json\")\n    tuning_str = (\n        f\"tvmc tune --config {tune_config_file} --output {log_path} \"\n        f\"--enable-autoscheduler {keras_simple}\"\n    )\n    tuning_args = tuning_str.split(\" \")[1:]\n    _main(tuning_args)\n    assert os.path.exists(log_path)\n\n    # Test model compilation\n    package_path = os.path.join(tmpdir, \"keras-tvm.tar\")\n    compile_str = (\n        f\"tvmc compile --tuning-records {log_path} \" f\"--output {package_path} {keras_simple}\"\n    )\n    compile_args = compile_str.split(\" \")[1:]\n    _main(compile_args)\n    assert os.path.exists(package_path)\n\n    # Test running the model\n    output_path = os.path.join(tmpdir, \"predictions.npz\")\n    run_str = f\"tvmc run --outputs {output_path} {package_path}\"\n    run_args = run_str.split(\" \")[1:]\n    _main(run_args)\n    assert os.path.exists(output_path)\n\n\n@pytest.fixture\ndef missing_file():\n    missing_file_name = \"missing_file_as_invalid_input.tfite\"\n    return missing_file_name\n\n\n@pytest.fixture\ndef broken_symlink(tmp_path):\n    broken_symlink = \"broken_symlink_as_invalid_input.tflite\"\n    os.symlink(\"non_existing_file\", tmp_path / broken_symlink)\n    yield broken_symlink\n    os.unlink(tmp_path / broken_symlink)\n\n\n@pytest.fixture\ndef fake_directory(tmp_path):\n    dir_as_invalid = \"dir_as_invalid_input.tflite\"\n    os.mkdir(tmp_path / dir_as_invalid)\n    yield dir_as_invalid\n    shutil.rmtree(tmp_path / dir_as_invalid)\n\n\n@pytest.mark.parametrize(\n    \"invalid_input\",\n    [lazy_fixture(\"missing_file\"), lazy_fixture(\"broken_symlink\"), lazy_fixture(\"fake_directory\")],\n)\ndef test_tvmc_compile_file_check(capsys, invalid_input):\n    compile_cmd = f\"tvmc compile --target 'c' {invalid_input}\"\n    run_arg = compile_cmd.split(\" \")[1:]\n\n    _main(run_arg)\n\n    captured = capsys.readouterr()\n    expected_err = (\n        f\"Error: Input file '{invalid_input}' doesn't exist, \"\n        \"is a broken symbolic link, or a directory.\\n\"\n    )\n    on_assert_error = f\"'tvmc compile' failed to check invalid FILE: {invalid_input}\"\n    assert captured.err == expected_err, on_assert_error\n\n\n@pytest.mark.parametrize(\n    \"invalid_input\",\n    [lazy_fixture(\"missing_file\"), lazy_fixture(\"broken_symlink\"), lazy_fixture(\"fake_directory\")],\n)\ndef test_tvmc_tune_file_check(capsys, invalid_input):\n    tune_cmd = f\"tvmc tune --target 'llvm' --output output.json {invalid_input}\"\n    run_arg = tune_cmd.split(\" \")[1:]\n\n    _main(run_arg)\n\n    captured = capsys.readouterr()\n    expected_err = (\n        f\"Error: Input file '{invalid_input}' doesn't exist, \"\n        \"is a broken symbolic link, or a directory.\\n\"\n    )\n    on_assert_error = f\"'tvmc tune' failed to check invalid FILE: {invalid_input}\"\n    assert captured.err == expected_err, on_assert_error\n\n\n@mock.patch(\"tvm.relay.build\", side_effect=tvm.relay.build)\n@mock.patch(\"tvm.driver.tvmc.model.TVMCPackage.__init__\", return_value=None)\ndef test_tvmc_workspace_pools_check(mock_pkg, mock_relay, keras_simple, tmpdir_factory):\n    pytest.importorskip(\"tensorflow\")\n    tmpdir = tmpdir_factory.mktemp(\"data\")\n\n    # Test model compilation\n    package_path = os.path.join(tmpdir, \"keras-tvm.tar\")\n    compile_str = (\n        f\"tvmc compile --target=llvm --workspace-pools=sram \"\n        f\"--workspace-pools-targets=sram:llvm \"\n        f\"--output={package_path} {keras_simple}\"\n    )\n    compile_args = compile_str.split(\" \")[1:]\n    _main(compile_args)\n    assert os.path.exists(package_path)\n    assert mock_relay.call_count == 1\n    assert mock_relay.call_args_list[0][1][\"workspace_memory_pools\"].pools[0].pool_name == \"sram\"\n\n\n@pytest.fixture\ndef paddle_model(paddle_resnet50):\n    # If we can't import \"paddle\" module, skip testing paddle as the input model.\n    if pytest.importorskip(\"paddle\", reason=\"'paddle' module not installed\"):\n        return paddle_resnet50\n\n\n@pytest.mark.parametrize(\n    \"model\",\n    [\n        lazy_fixture(\"paddle_model\"),\n    ],\n)\n# compile_model() can take too long and is tested elsewhere, hence it's mocked below\n@mock.patch.object(compiler, \"compile_model\")\n# @mock.patch.object(compiler, \"compile_model\")\ndef test_tvmc_compile_input_model(mock_compile_model, tmpdir_factory, model):\n\n    output_dir = tmpdir_factory.mktemp(\"output\")\n    output_file = output_dir / \"model.tar\"\n\n    compile_cmd = (\n        f\"tvmc compile --target 'llvm' {model} --model-format paddle --output {output_file}\"\n    )\n    run_arg = compile_cmd.split(\" \")[1:]\n\n    _main(run_arg)\n\n    mock_compile_model.assert_called_once()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport re\nimport shutil\nimport tarfile\nfrom os import path\n\nfrom unittest import mock\nimport pytest\n\nimport tvm\nfrom tvm.ir.memory_pools import WorkspacePoolInfo, WorkspaceMemoryPools\nfrom tvm.target import Target\nimport tvm.testing\nfrom tvm.relay.op.contrib.ethosn import ethosn_available\nfrom tvm.relay.backend import Runtime, Executor\n\nfrom tvm.contrib.target.vitis_ai import vitis_ai_available\n\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc.model import TVMCPackage\n\nfrom tvm.contrib import utils\n\n\ndef test_save_dumps(tmpdir_factory):\n    tmpdir = tmpdir_factory.mktemp(\"data\")\n    dump_formats = {\"relay\": \"fake relay\", \"ll\": \"fake llvm\", \"asm\": \"fake asm\"}\n    tvmc.compiler.save_dumps(\"fake_module\", dump_formats, dump_root=tmpdir)\n\n    assert path.exists(\"{}/{}\".format(tmpdir, \"fake_module.ll\"))\n    assert path.exists(\"{}/{}\".format(tmpdir, \"fake_module.asm\"))\n    assert path.exists(\"{}/{}\".format(tmpdir, \"fake_module.relay\"))\n\n\n# End to end tests for compilation\n\n\ndef verify_tvmc_package(tvmc_package, dumps_path, use_vm=False):\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert os.path.exists(dumps_path)\n    assert type(tvmc_package.lib_path) is str\n\n    if use_vm:\n        assert tvmc_package.graph is None\n        assert tvmc_package.params is None\n    else:\n        assert type(tvmc_package.graph) is str\n        assert type(tvmc_package.params) is bytearray\n\n\ndef verify_compile_tflite_module(model, shape_dict=None, use_vm=False):\n    pytest.importorskip(\"tflite\")\n    tvmc_model = tvmc.load(model, shape_dict=shape_dict)\n    tvmc_package = tvmc.compile(\n        tvmc_model, target=\"llvm\", dump_code=\"ll\", desired_layout=\"NCHW\", use_vm=use_vm\n    )\n    dumps_path = tvmc_package.package_path + \".ll\"\n    verify_tvmc_package(tvmc_package, dumps_path, use_vm=use_vm)\n\n\n@pytest.mark.parametrize(\"use_vm\", [True, False])\ndef test_compile_tflite_module(use_vm, tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer tflite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n    # Check default compilation.\n    verify_compile_tflite_module(tflite_mobilenet_v1_1_quant)\n    # Check with manual shape override\n    shape_string = \"input:[1,224,224,3]\"\n    shape_dict = tvmc.shape_parser.parse_shape_string(shape_string)\n    verify_compile_tflite_module(tflite_mobilenet_v1_1_quant, shape_dict, use_vm=use_vm)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_aarch64_tflite_module(tflite_mobilenet_v1_1_quant):\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr='+neon'\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_options_aarch64_tflite_module(tflite_mobilenet_v1_1_quant):\n    pytest.importorskip(\"tflite\")\n\n    fake_sysroot_dir = utils.tempdir().relpath(\"\")\n\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr='+neon'\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n        cross_options=\"--sysroot=\" + fake_sysroot_dir,\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\ndef test_compile_keras__save_module(keras_resnet50, tmpdir_factory):\n    # some CI environments wont offer tensorflow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    expected_temp_dir = tmpdir_factory.mktemp(\"saved_output\")\n    expected_file_name = \"saved.tar\"\n    module_file = os.path.join(expected_temp_dir, expected_file_name)\n\n    tvmc_model = tvmc.load(keras_resnet50)\n    tvmc.compile(tvmc_model, target=\"llvm\", dump_code=\"ll\", package_path=module_file)\n\n    assert os.path.exists(module_file), \"output file {0} should exist\".format(module_file)\n\n    # Test that we can load back in a module.\n    tvmc_package = TVMCPackage(package_path=module_file)\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.params) is bytearray\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_aarch64_keras_module(keras_resnet50):\n    # some CI environments wont offer tensorflow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    tvmc_model = tvmc.load(keras_resnet50)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr='+neon'\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_options_aarch64_keras_module(keras_resnet50):\n    # some CI environments wont offer tensorflow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    fake_sysroot_dir = utils.tempdir().relpath(\"\")\n\n    tvmc_model = tvmc.load(keras_resnet50)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr='+neon'\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n        cross_options=\"--sysroot=\" + fake_sysroot_dir,\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\ndef verify_compile_onnx_module(model, shape_dict=None, use_vm=False):\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n    tvmc_model = tvmc.load(model, shape_dict=shape_dict)\n    tvmc_package = tvmc.compile(tvmc_model, target=\"llvm\", dump_code=\"ll\", use_vm=use_vm)\n    dumps_path = tvmc_package.package_path + \".ll\"\n    verify_tvmc_package(tvmc_package, dumps_path, use_vm=use_vm)\n\n\n@pytest.mark.parametrize(\"use_vm\", [True, False])\ndef test_compile_onnx_module(use_vm, onnx_resnet50):\n    # Test default compilation\n    verify_compile_onnx_module(onnx_resnet50)\n    # Test with manual shape dict\n    shape_string = \"data:[1,3,200,200]\"\n    shape_dict = tvmc.shape_parser.parse_shape_string(shape_string)\n    verify_compile_onnx_module(onnx_resnet50, shape_dict, use_vm=use_vm)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_aarch64_onnx_module(onnx_resnet50):\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    tvmc_model = tvmc.load(onnx_resnet50)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+neon\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_options_aarch64_onnx_module(onnx_resnet50):\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    fake_sysroot_dir = utils.tempdir().relpath(\"\")\n\n    tvmc_model = tvmc.load(onnx_resnet50)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+neon\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n        cross_options=\"--sysroot=\" + fake_sysroot_dir,\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\ndef verify_compile_paddle_module(model, shape_dict=None):\n    pytest.importorskip(\"paddle\")\n    tvmc_model = tvmc.load(model, \"paddle\", shape_dict=shape_dict)\n    tvmc_package = tvmc.compile(tvmc_model, target=\"llvm\", dump_code=\"ll\", desired_layout=\"NCHW\")\n    dumps_path = tvmc_package.package_path + \".ll\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\ndef test_compile_paddle_module(paddle_resnet50):\n    # some CI environments wont offer Paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n    # Check default compilation.\n    verify_compile_paddle_module(paddle_resnet50)\n    # Check with manual shape override\n    shape_string = \"inputs:[1,3,224,224]\"\n    shape_dict = tvmc.shape_parser.parse_shape_string(shape_string)\n    verify_compile_paddle_module(paddle_resnet50, shape_dict)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_aarch64_paddle_module(paddle_resnet50):\n    # some CI environments wont offer paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n\n    tvmc_model = tvmc.load(paddle_resnet50, \"paddle\")\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+neon\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n# This test will be skipped if the AArch64 cross-compilation toolchain is not installed.\n@pytest.mark.skipif(\n    not shutil.which(\"aarch64-linux-gnu-gcc\"), reason=\"cross-compilation toolchain not installed\"\n)\ndef test_cross_compile_options_aarch64_paddle_module(paddle_resnet50):\n    # some CI environments wont offer paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n\n    fake_sysroot_dir = utils.tempdir().relpath(\"\")\n\n    tvmc_model = tvmc.load(paddle_resnet50, \"paddle\")\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+neon\",\n        dump_code=\"asm\",\n        cross=\"aarch64-linux-gnu-gcc\",\n        cross_options=\"--sysroot=\" + fake_sysroot_dir,\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n@tvm.testing.requires_opencl\ndef test_compile_opencl(tflite_mobilenet_v1_0_25_128):\n    pytest.importorskip(\"tflite\")\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_0_25_128)\n    tvmc_package = tvmc.compile(\n        tvmc_model,\n        target=\"opencl -host=llvm\",\n        desired_layout=\"NCHW\",\n        dump_code=\"asm\",\n    )\n    dumps_path = tvmc_package.package_path + \".asm\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n@tvm.testing.requires_cmsisnn\ndef test_compile_tflite_module_with_external_codegen_cmsisnn(\n    tmpdir_factory, tflite_cnn_s_quantized\n):\n    pytest.importorskip(\"tflite\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    tvmc_model = tvmc.load(tflite_cnn_s_quantized)\n\n    output_file_name = f\"{output_dir}/file.tar\"\n\n    tvmc.compiler.compile_model(\n        tvmc_model,\n        target=f\"cmsis-nn, c -mcpu=cortex-m55\",\n        runtime=Runtime(\"crt\", {\"system-lib\": True}),\n        executor=Executor(\"aot\"),\n        output_format=\"mlf\",\n        package_path=output_file_name,\n        pass_context_configs=[\"tir.disable_vectorize=true\"],\n    )\n\n    # check whether an MLF package was created\n    assert os.path.exists(output_file_name)\n\n    # check whether the expected number of C sources are in the tarfile\n    with tarfile.open(output_file_name) as mlf_package:\n        c_source_files = [\n            name\n            for name in mlf_package.getnames()\n            if re.match(r\"\\./codegen/host/src/\\D+\\d+\\.c\", name)\n        ]\n        assert len(c_source_files) == 4\n\n\n@tvm.testing.requires_ethosn\ndef test_compile_tflite_module_with_external_codegen_ethos_n78(tflite_mobilenet_v1_1_quant):\n    pytest.importorskip(\"tflite\")\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    tvmc_package = tvmc.compile(tvmc_model, target=\"ethos-n -variant=n78, llvm\", dump_code=\"relay\")\n    dumps_path = tvmc_package.package_path + \".relay\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\n@tvm.testing.requires_vitis_ai\ndef test_compile_tflite_module_with_external_codegen_vitis_ai(tflite_mobilenet_v1_1_quant):\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    tvmc_package = tvmc.compiler.compile_model(\n        tvmc_model,\n        target=\"vitis-ai -dpu=DPUCZDX8G-zcu104 -export_runtime_module=vitis_ai.rtmod, llvm\",\n        dump_code=\"relay\",\n    )\n    dumps_path = tvmc_package.package_path + \".relay\"\n\n    # check for output types\n    assert type(tvmc_package) is TVMCPackage\n    assert type(tvmc_package.graph) is str\n    assert type(tvmc_package.lib_path) is str\n    assert type(tvmc_package.params) is bytearray\n    assert os.path.exists(dumps_path)\n\n\ndef test_compile_tflite_module_with_external_codegen_ethosu(\n    tmpdir_factory, tflite_mobilenet_v1_1_quant\n):\n    pytest.importorskip(\"tflite\")\n    pytest.importorskip(\"ethosu.vela\")\n    ACCEL_TYPES = [\"ethos-u55-256\", \"ethos-u55-128\", \"ethos-u55-64\", \"ethos-u55-32\"]\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n\n    for accel_type in ACCEL_TYPES:\n        output_file_name = f\"{output_dir}/file_{accel_type}.tar\"\n\n        tvmc.compiler.compile_model(\n            tvmc_model,\n            target=f\"ethos-u -accelerator_config={accel_type}, c -mcpu=cortex-m55\",\n            runtime=Runtime(\"crt\"),\n            executor=Executor(\"aot\", {\"unpacked-api\": True}),\n            output_format=\"mlf\",\n            package_path=output_file_name,\n            pass_context_configs=[\"tir.disable_vectorize=true\"],\n        )\n\n        # check whether an MLF package was created\n        assert os.path.exists(output_file_name)\n\n        # check whether the expected number of C sources are in the tarfile\n        with tarfile.open(output_file_name) as mlf_package:\n            c_source_files = [\n                name\n                for name in mlf_package.getnames()\n                if re.match(r\"\\./codegen/host/src/\\D+\\d+\\.c\", name)\n            ]\n            # The number of c_source_files depends on the number of fused subgraphs that\n            # get offloaded to the NPU, e.g. conv2d->depthwise_conv2d->conv2d gets offloaded\n            # as a single subgraph if both of these operators are supported by the NPU.\n            # Currently there are three source files for CPU execution and one offload graph\n            assert len(c_source_files) == 4\n\n\n@mock.patch(\"tvm.relay.build\")\n@mock.patch(\"tvm.driver.tvmc.composite_target.get_codegen_by_target\")\n@mock.patch(\"tvm.driver.tvmc.load\")\n@mock.patch(\"tvm.transform.PassContext\")\n@mock.patch(\"tvm.driver.tvmc.model.TVMCPackage.__init__\", return_value=None)\ndef test_compile_check_configs_composite_target(mock_pkg, mock_pc, mock_fe, mock_ct, mock_relay):\n    mock_codegen = {}\n    mock_codegen[\"config_key\"] = \"relay.ext.mock.options\"\n    mock_codegen[\"pass_pipeline\"] = lambda *args, **kwargs: None\n\n    mock_fe.return_value = mock.MagicMock()\n    mock_ct.return_value = mock_codegen\n    mock_relay.return_value = mock.MagicMock()\n\n    tvmc_model = tvmc.load(\"no_file_needed\")\n    tvmc.compile(tvmc_model, target=\"mockcodegen -testopt=value, llvm\")\n\n    assert mock_pc.call_count == 1\n    codegen_compile_context = mock.call(\n        config={\"relay.ext.mock.options\": {\"testopt\": \"value\"}},\n        opt_level=3,\n        disabled_pass=None,\n        instruments=None,\n    )\n    mock_pc.assert_has_calls(\n        [\n            codegen_compile_context,\n            codegen_compile_context.__enter__(),\n            codegen_compile_context.__exit__(None, None, None),\n        ]\n    )\n\n\ndef test_compile_tflite_module_with_mod_name(tmpdir_factory, tflite_cnn_s_quantized):\n    pytest.importorskip(\"tflite\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    tvmc_model = tvmc.load(tflite_cnn_s_quantized)\n\n    output_file_name = f\"{output_dir}/file.tar\"\n\n    tvmc.compiler.compile_model(\n        tvmc_model,\n        target=f\"c -mcpu=cortex-m55\",\n        runtime=Runtime(\"crt\", {\"system-lib\": True}),\n        executor=Executor(\"aot\"),\n        output_format=\"mlf\",\n        package_path=output_file_name,\n        pass_context_configs=[\"tir.disable_vectorize=true\"],\n        mod_name=\"classify\",\n    )\n\n    # check that an MLF package was created\n    assert os.path.exists(output_file_name)\n\n    with tarfile.open(output_file_name) as mlf_package:\n        # check that the C source files have been named classify_lib*.c\n        c_source_files = [\n            name\n            for name in mlf_package.getnames()\n            if re.match(r\"\\./codegen/host/src/classify_lib\\d+\\.c\", name)\n        ]\n        assert len(c_source_files) > 0\n\n        # check that \"default\" doesn't occur in any of the C source files\n        # check that function names are of the form \"tvmgen_classify_*\"\n        for file_name in c_source_files:\n            with mlf_package.extractfile(file_name) as f:\n                content = f.read()\n                assert b\"default\" not in content\n                assert b\"tvmgen_classify_\" in content\n\n        # check that tvmgen_classify_run() function exists\n        with mlf_package.extractfile(\"./codegen/host/src/classify_lib0.c\") as f:\n            content = f.read()\n            assert b\"tvmgen_classify_run(\" in content\n\n\n@tvm.testing.requires_cmsisnn\ndef test_compile_tflite_module_with_mod_name_and_cmsisnn(tmpdir_factory, tflite_cnn_s_quantized):\n    pytest.importorskip(\"tflite\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    tvmc_model = tvmc.load(tflite_cnn_s_quantized)\n\n    output_file_name = f\"{output_dir}/file.tar\"\n\n    tvmc.compiler.compile_model(\n        tvmc_model,\n        target=f\"cmsis-nn, c -mcpu=cortex-m55\",\n        runtime=Runtime(\"crt\", {\"system-lib\": True}),\n        executor=Executor(\"aot\"),\n        output_format=\"mlf\",\n        package_path=output_file_name,\n        pass_context_configs=[\"tir.disable_vectorize=true\"],\n        mod_name=\"classify\",\n    )\n\n    # check that an MLF package was created\n    assert os.path.exists(output_file_name)\n\n    with tarfile.open(output_file_name) as mlf_package:\n        # check that the C source files have been named classify_lib*.c\n        c_source_files = [\n            name\n            for name in mlf_package.getnames()\n            if re.match(r\"\\./codegen/host/src/classify_lib\\d+\\.c\", name)\n        ]\n        assert len(c_source_files) > 0\n\n        # check that \"default\" doesn't occur in any of the C source files\n        # check that function names are of the form \"tvmgen_classify_*\"\n        for file_name in c_source_files:\n            with mlf_package.extractfile(file_name) as f:\n                content = f.read()\n                assert b\"default\" not in content\n                assert b\"tvmgen_classify_\" in content\n\n        # check that tvmgen_classify_run() function exists\n        with mlf_package.extractfile(\"./codegen/host/src/classify_lib0.c\") as f:\n            content = f.read()\n            assert b\"tvmgen_classify_run(\" in content\n\n        # check that CMSIS-NN function names are of the form \"tvmgen_classify_cmsis_nn_main_*\"\n        with mlf_package.extractfile(\"./codegen/host/src/classify_lib2.c\") as f:\n            content = f.read()\n            assert b\"tvmgen_classify_cmsis_nn_main_\" in content\n\n\ndef test_compile_tflite_module_with_mod_name_and_ethosu(\n    tmpdir_factory, tflite_mobilenet_v1_1_quant\n):\n    pytest.importorskip(\"tflite\")\n    pytest.importorskip(\"ethosu.vela\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    output_file_name = f\"{output_dir}/file.tar\"\n\n    tvmc.compiler.compile_model(\n        tvmc_model,\n        target=f\"ethos-u -accelerator_config=ethos-u55-256, c -mcpu=cortex-m55\",\n        runtime=Runtime(\"crt\"),\n        executor=Executor(\"aot\", {\"unpacked-api\": True}),\n        output_format=\"mlf\",\n        package_path=output_file_name,\n        pass_context_configs=[\"tir.disable_vectorize=true\"],\n        mod_name=\"classify\",\n    )\n\n    # check that an MLF package was created\n    assert os.path.exists(output_file_name)\n\n    with tarfile.open(output_file_name) as mlf_package:\n        # check that the C source files have been named classify_lib*.c\n        c_source_files = [\n            name\n            for name in mlf_package.getnames()\n            if re.match(r\"\\./codegen/host/src/classify_lib\\d+\\.c\", name)\n        ]\n        assert len(c_source_files) > 0\n\n        # check that \"default\" doesn't occur in any of the C source files\n        # check that function names are of the form \"tvmgen_classify_*\"\n        for file_name in c_source_files:\n            with mlf_package.extractfile(file_name) as f:\n                content = f.read()\n                assert b\"default\" not in content\n                assert b\"tvmgen_classify_\" in content\n\n        # check that tvmgen_classify_run() function exists\n        with mlf_package.extractfile(\"./codegen/host/src/classify_lib0.c\") as f:\n            content = f.read()\n            assert b\"tvmgen_classify_run(\" in content\n\n        # check that microNPU function names are of the form \"tvmgen_classify_ethos_u_main_*\"\n        with mlf_package.extractfile(\"./codegen/host/src/classify_lib2.c\") as f:\n            content = f.read()\n            assert b\"tvmgen_classify_ethos_u_main_\" in content\n\n\n@mock.patch(\"tvm.relay.build\")\n@mock.patch(\"tvm.driver.tvmc.load\")\n@mock.patch(\"tvm.driver.tvmc.model.TVMCPackage.__init__\", return_value=None)\ndef test_compile_check_workspace_pools(mock_pkg, mock_fe, mock_relay):\n    mock_fe.return_value = mock.MagicMock()\n    mock_relay.return_value = mock.MagicMock()\n    memory_pools = WorkspaceMemoryPools(\n        [WorkspacePoolInfo(pool_name=\"sram\", targets=[Target(\"llvm\")])]\n    )\n    tvmc_model = tvmc.load(\"no_file_needed\")\n    tvmc.compile(\n        tvmc_model,\n        target=\"llvm,c\",\n        workspace_pools=memory_pools,\n    )\n\n    assert mock_relay.call_count == 1\n    assert mock_relay.call_args_list[0][1][\"workspace_memory_pools\"] == memory_pools\n\n\ndef test_compile_check_pass_instrument(keras_resnet50):\n    pytest.importorskip(\"tensorflow\")\n\n    @tvm.instrument.pass_instrument\n    class PassesCounter:\n        def __init__(self):\n            self.run_before_count = 0\n            self.run_after_count = 0\n\n        def run_before_pass(self, mod, info):\n            self.run_before_count = self.run_before_count + 1\n\n        def run_after_pass(self, mod, info):\n            self.run_after_count = self.run_after_count + 1\n\n    passes_counter = PassesCounter()\n    tvmc_model = tvmc.load(keras_resnet50)\n    tvmc.compile(tvmc_model, target=\"llvm\", instruments=[passes_counter])\n    assert passes_counter.run_after_count > 0\n    assert passes_counter.run_after_count == passes_counter.run_before_count\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_composite_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport os\nimport shutil\n\nfrom inspect import isfunction\nfrom os import path\n\nimport pytest\n\nimport tvm\n\nfrom tvm.driver import tvmc\n\nfrom tvm.driver.tvmc import TVMCException\n\n\ndef test_get_codegen_names():\n    names = tvmc.composite_target.get_codegen_names()\n\n    assert \"ethos-n\" in names\n    assert \"vitis-ai\" in names\n    assert len(names) > 0\n\n\ndef test_valid_codegen():\n    codegen = tvmc.composite_target.get_codegen_by_target(\"compute-library\")\n\n    assert codegen is not None\n    assert codegen[\"pass_pipeline\"] is not None\n\n\ndef test_invalid_codegen():\n    with pytest.raises(TVMCException):\n        _ = tvmc.composite_target.get_codegen_by_target(\"invalid\")\n\n\ndef test_all_codegens_contain_pass_pipeline():\n    for name in tvmc.composite_target.get_codegen_names():\n        codegen = tvmc.composite_target.get_codegen_by_target(name)\n        assert \"pass_pipeline\" in codegen, f\"{name} does not contain a pass_pipeline\"\n        assert isfunction(codegen[\"pass_pipeline\"])\n\n\ndef test_all_pass_pipelines_are_functions():\n    for name in tvmc.composite_target.get_codegen_names():\n        codegen = tvmc.composite_target.get_codegen_by_target(name)\n        assert isfunction(codegen[\"pass_pipeline\"]), f\"pass_pipeline for {name} is not a function\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_frontends.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport platform\nimport pytest\nimport builtins\nimport importlib\n\nimport tvm\nfrom unittest import mock\nfrom tvm.ir.module import IRModule\n\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc import TVMCException, TVMCImportError\nfrom tvm.driver.tvmc.model import TVMCModel\n\n\norig_import = importlib.import_module\n\n\ndef mock_error_on_name(name):\n    def mock_imports(module_name, package=None):\n        if module_name == name:\n            raise ImportError()\n        return orig_import(module_name, package)\n\n    return mock_imports\n\n\ndef test_get_frontends_contains_only_strings():\n    sut = tvmc.frontends.get_frontend_names()\n    assert all([type(x) is str for x in sut]) is True\n\n\ndef test_get_frontend_by_name_valid():\n    # some CI environments wont offer TensorFlow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    sut = tvmc.frontends.get_frontend_by_name(\"keras\")\n    assert type(sut) is tvmc.frontends.KerasFrontend\n\n\ndef test_get_frontend_by_name_invalid():\n    with pytest.raises(TVMCException):\n        tvmc.frontends.get_frontend_by_name(\"unsupported_thing\")\n\n\ndef test_guess_frontend_tflite():\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.tflite\")\n    assert type(sut) is tvmc.frontends.TFLiteFrontend\n\n\ndef test_guess_frontend_onnx():\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.onnx\")\n    assert type(sut) is tvmc.frontends.OnnxFrontend\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_guess_frontend_pytorch():\n    # some CI environments wont offer pytorch, so skip in case it is not present\n    pytest.importorskip(\"torch\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.pth\")\n    assert type(sut) is tvmc.frontends.PyTorchFrontend\n\n\ndef test_guess_frontend_keras():\n    # some CI environments wont offer TensorFlow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.h5\")\n    assert type(sut) is tvmc.frontends.KerasFrontend\n\n\ndef test_guess_frontend_tensorflow():\n    # some CI environments wont offer TensorFlow, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.pb\")\n    assert type(sut) is tvmc.frontends.TensorflowFrontend\n\n\ndef test_guess_frontend_paddle():\n    # some CI environments wont offer Paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n\n    sut = tvmc.frontends.guess_frontend(\"a_model.pdmodel\")\n    assert type(sut) is tvmc.frontends.PaddleFrontend\n\n\ndef test_guess_frontend_relay():\n\n    sut = tvmc.frontends.guess_frontend(\"relay.relay\")\n    assert type(sut) is tvmc.frontends.RelayFrontend\n\n\ndef test_guess_frontend_invalid():\n    with pytest.raises(TVMCException):\n        tvmc.frontends.guess_frontend(\"not/a/file.txt\")\n\n\ndef test_load_model__invalid_path__no_language():\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    with pytest.raises(FileNotFoundError):\n        tvmc.load(\"not/a/file.tflite\")\n\n\ndef test_load_model__invalid_path__with_language():\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    with pytest.raises(FileNotFoundError):\n        tvmc.load(\"not/a/file.txt\", model_format=\"onnx\")\n\n\ndef test_load_model__tflite(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.load(tflite_mobilenet_v1_1_quant)\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n    # check whether one known value is part of the params dict\n    assert \"_param_1\" in tvmc_model.params.keys()\n\n\n@pytest.mark.parametrize(\"load_model_kwargs\", [{}, {\"layout\": \"NCHW\"}])\ndef test_load_model__keras(keras_resnet50, load_model_kwargs):\n    # some CI environments wont offer TensorFlow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    tvmc_model = tvmc.frontends.load_model(keras_resnet50, **load_model_kwargs)\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n    ## check whether one known value is part of the params dict\n    assert \"_param_1\" in tvmc_model.params.keys()\n\n\ndef verify_load_model__onnx(model, **kwargs):\n    tvmc_model = tvmc.frontends.load_model(model, **kwargs)\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n    return tvmc_model\n\n\ndef test_load_model__onnx(onnx_resnet50):\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n    tvmc_model = verify_load_model__onnx(onnx_resnet50, freeze_params=False)\n    # check whether one known value is part of the params dict\n    assert \"resnetv24_batchnorm0_gamma\" in tvmc_model.params.keys()\n    tvmc_model = verify_load_model__onnx(onnx_resnet50, freeze_params=True)\n    # check that the parameter dict is empty, implying that they have been folded into constants\n    assert tvmc_model.params == {}\n\n\ndef test_load_model__pb(pb_mobilenet_v1_1_quant):\n    # some CI environments wont offer TensorFlow, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    tvmc_model = tvmc.load(pb_mobilenet_v1_1_quant)\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n    # check whether one known value is part of the params dict\n    assert \"MobilenetV1/Conv2d_0/weights\" in tvmc_model.params.keys()\n\n\ndef test_load_model__paddle(paddle_resnet50):\n    # some CI environments wont offer Paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n\n    tvmc_model = tvmc.load(paddle_resnet50, model_format=\"paddle\")\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n\n\ndef test_load_model__relay(relay_text_conv2d):\n    tvmc_model = tvmc.load(relay_text_conv2d, model_format=\"relay\")\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n\n\ndef test_load_model___wrong_language__to_keras(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer TensorFlow/Keras, so skip in case it is not present\n    pytest.importorskip(\"tensorflow\")\n\n    with pytest.raises(OSError):\n        tvmc.load(tflite_mobilenet_v1_1_quant, model_format=\"keras\")\n\n\ndef test_load_model___wrong_language__to_tflite(keras_resnet50):\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    with pytest.raises(TVMCException):\n        tvmc.frontends.load_model(keras_resnet50, model_format=\"tflite\")\n\n\ndef test_load_model___wrong_language__to_onnx(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer onnx, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    from google.protobuf.message import DecodeError\n\n    with pytest.raises(DecodeError):\n        tvmc.load(tflite_mobilenet_v1_1_quant, model_format=\"onnx\")\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_load_model__pth(pytorch_resnet18):\n    # some CI environments wont offer torch, so skip in case it is not present\n    pytest.importorskip(\"torch\")\n    pytest.importorskip(\"torchvision\")\n\n    tvmc_model = tvmc.load(pytorch_resnet18, shape_dict={\"input\": [1, 3, 224, 224]})\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n    # check whether one known value is part of the params dict\n    assert \"layer1.0.conv1.weight\" in tvmc_model.params.keys()\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_load_quantized_model__pth(pytorch_mobilenetv2_quantized):\n    # some CI environments wont offer torch, so skip in case it is not present\n    pytest.importorskip(\"torch\")\n    pytest.importorskip(\"torchvision\")\n\n    tvmc_model = tvmc.load(pytorch_mobilenetv2_quantized, shape_dict={\"input\": [1, 3, 224, 224]})\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_model.mod) is IRModule\n    assert type(tvmc_model.params) is dict\n\n    # checking weights remain quantized and are not float32\n    for p in tvmc_model.params.values():\n        assert p.dtype in [\"int8\", \"uint8\", \"int32\"]  # int32 for bias\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_load_model___wrong_language__to_pytorch(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer pytorch, so skip in case it is not present\n    pytest.importorskip(\"torch\")\n\n    with pytest.raises(RuntimeError) as e:\n        tvmc.load(\n            tflite_mobilenet_v1_1_quant,\n            model_format=\"pytorch\",\n            shape_dict={\"input\": [1, 3, 224, 224]},\n        )\n\n\ndef test_compile_tflite_module_nhwc_to_nchw(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.frontends.load_model(tflite_mobilenet_v1_1_quant)\n    before = tvmc_model.mod\n\n    expected_layout = \"NCHW\"\n    with tvm.transform.PassContext(opt_level=3):\n        after = tvmc.transform.convert_graph_layout(before, expected_layout)\n\n    layout_transform_calls = []\n\n    def _is_layout_transform(node):\n        if isinstance(node, tvm.relay.expr.Call):\n            layout_transform_calls.append(\n                node.op.name == \"layout_transform\"\n                and node.attrs.src_layout == \"NHWC\"\n                and node.attrs.dst_layout == \"NCHW\"\n            )\n\n    tvm.relay.analysis.post_order_visit(after[\"main\"], _is_layout_transform)\n\n    assert any(layout_transform_calls), \"Expected 'layout_transform NHWC->NCHW' not found\"\n\n\ndef test_compile_onnx_module_nchw_to_nhwc(onnx_resnet50):\n    # some CI environments wont offer ONNX, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    tvmc_model = tvmc.frontends.load_model(onnx_resnet50)\n    before = tvmc_model.mod\n\n    expected_layout = \"NHWC\"\n    with tvm.transform.PassContext(opt_level=3):\n        after = tvmc.transform.convert_graph_layout(before, expected_layout)\n\n    layout_transform_calls = []\n\n    def _is_layout_transform(node):\n        if isinstance(node, tvm.relay.expr.Call):\n            layout_transform_calls.append(\n                node.op.name == \"layout_transform\"\n                and node.attrs.src_layout == \"NCHW\"\n                and node.attrs.dst_layout == \"NHWC\"\n            )\n\n    tvm.relay.analysis.post_order_visit(after[\"main\"], _is_layout_transform)\n\n    assert any(layout_transform_calls), \"Expected 'layout_transform NCWH->NHWC' not found\"\n\n\ndef test_compile_paddle_module_nchw_to_nhwc(paddle_resnet50):\n    # some CI environments wont offer Paddle, so skip in case it is not present\n    pytest.importorskip(\"paddle\")\n\n    tvmc_model = tvmc.frontends.load_model(paddle_resnet50, \"paddle\")\n    before = tvmc_model.mod\n\n    expected_layout = \"NHWC\"\n    with tvm.transform.PassContext(opt_level=3):\n        after = tvmc.transform.convert_graph_layout(before, expected_layout)\n\n    layout_transform_calls = []\n\n    def _is_layout_transform(node):\n        if isinstance(node, tvm.relay.expr.Call):\n            layout_transform_calls.append(\n                node.op.name == \"layout_transform\"\n                and node.attrs.src_layout == \"NCHW\"\n                and node.attrs.dst_layout == \"NHWC\"\n            )\n\n    tvm.relay.analysis.post_order_visit(after[\"main\"], _is_layout_transform)\n\n    assert any(layout_transform_calls), \"Expected 'layout_transform NCWH->NHWC' not found\"\n\n\ndef test_compile_tflite_module__same_layout__nhwc_to_nhwc(tflite_mobilenet_v1_1_quant):\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.frontends.load_model(tflite_mobilenet_v1_1_quant)\n    before = tvmc_model.mod\n\n    expected_layout = \"NHWC\"\n\n    with tvm.transform.PassContext(opt_level=3):\n        after = tvmc.transform.convert_graph_layout(before, expected_layout)\n\n    layout_transform_calls = []\n\n    def _is_layout_transform(node):\n        if isinstance(node, tvm.relay.expr.Call):\n            layout_transform_calls.append(\n                node.op.name == \"layout_transform\"\n                and node.attrs.src_layout == \"NHWC\"\n                and node.attrs.dst_layout == \"NHWC\"\n            )\n\n    tvm.relay.analysis.post_order_visit(after[\"main\"], _is_layout_transform)\n\n    assert not any(layout_transform_calls), \"Unexpected 'layout_transform' call\"\n\n\ndef test_compile_onnx_module__same_layout__nchw_to_nchw(onnx_resnet50):\n    # some CI environments wont offer ONNX, so skip in case it is not present\n    pytest.importorskip(\"onnx\")\n\n    tvmc_model = tvmc.frontends.load_model(onnx_resnet50)\n    before = tvmc_model.mod\n\n    expected_layout = \"NCHW\"\n\n    with tvm.transform.PassContext(opt_level=3):\n        after = tvmc.transform.convert_graph_layout(before, expected_layout)\n\n    layout_transform_calls = []\n\n    def _is_layout_transform(node):\n        if isinstance(node, tvm.relay.expr.Call):\n            layout_transform_calls.append(\n                node.op.name == \"layout_transform\"\n                and node.attrs.src_layout == \"NCHW\"\n                and node.attrs.dst_layout == \"NCHW\"\n            )\n\n    tvm.relay.analysis.post_order_visit(after[\"main\"], _is_layout_transform)\n\n    assert not any(layout_transform_calls), \"Unexpected 'layout_transform' call\"\n\n\ndef test_import_keras_friendly_message(keras_resnet50, monkeypatch):\n    # keras is part of tensorflow\n    monkeypatch.setattr(\"importlib.import_module\", mock_error_on_name(\"tensorflow\"))\n\n    with pytest.raises(TVMCImportError, match=\"tensorflow\") as e:\n        _ = tvmc.frontends.load_model(keras_resnet50, model_format=\"keras\")\n\n\ndef test_import_onnx_friendly_message(onnx_resnet50, monkeypatch):\n    monkeypatch.setattr(\"importlib.import_module\", mock_error_on_name(\"onnx\"))\n\n    with pytest.raises(TVMCImportError, match=\"onnx\") as e:\n        _ = tvmc.frontends.load_model(onnx_resnet50, model_format=\"onnx\")\n\n\ndef test_import_tensorflow_friendly_message(pb_mobilenet_v1_1_quant, monkeypatch):\n    monkeypatch.setattr(\"importlib.import_module\", mock_error_on_name(\"tensorflow\"))\n\n    with pytest.raises(TVMCImportError, match=\"tensorflow\") as e:\n        _ = tvmc.frontends.load_model(pb_mobilenet_v1_1_quant, model_format=\"pb\")\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\ndef test_import_torch_friendly_message(pytorch_resnet18, monkeypatch):\n    monkeypatch.setattr(\"importlib.import_module\", mock_error_on_name(\"torch\"))\n\n    with pytest.raises(TVMCImportError, match=\"torch\") as e:\n        _ = tvmc.frontends.load_model(pytorch_resnet18, model_format=\"pytorch\")\n\n\ndef test_import_tflite_friendly_message(tflite_mobilenet_v1_1_quant, monkeypatch):\n    monkeypatch.setattr(\"importlib.import_module\", mock_error_on_name(\"tflite.Model\"))\n\n    with pytest.raises(TVMCImportError, match=\"tflite.Model\") as e:\n        _ = tvmc.frontends.load_model(tflite_mobilenet_v1_1_quant, model_format=\"tflite\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_mlf.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport os\nimport shlex\nimport sys\n\nimport tvm\nimport tvm.testing\nfrom tvm.autotvm.measure.executor import Executor\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc.main import _main\nfrom tvm.driver.tvmc.model import TVMCPackage, TVMCException\nfrom tvm.relay import backend\n\n\ndef test_tvmc_cl_compile_run_mlf(tflite_mobilenet_v1_1_quant, tmpdir_factory):\n    target = \"c\"\n    executor = \"aot\"\n    pass_configs = [\"tir.disable_vectorize=1\"]\n    pytest.importorskip(\"tflite\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    input_model = tflite_mobilenet_v1_1_quant\n    output_file = os.path.join(output_dir, \"mock.tar\")\n\n    # Compile the input model and generate a Model Library Format (MLF) archive.\n    pass_config_args = \" \".join([f\"--pass-config {pass_config}\" for pass_config in pass_configs])\n    tvmc_cmd = f\"tvmc compile {input_model} --target={target} --executor={executor} {pass_config_args} --output {output_file} --output-format mlf\"\n    tvmc_args = shlex.split(tvmc_cmd)[1:]\n    _main(tvmc_args)\n    assert os.path.exists(output_file), \"Could not find the exported MLF archive.\"\n\n    # Run the MLF archive. It must fail since it's only supported on micro targets.\n    tvmc_cmd = f\"tvmc run {output_file}\"\n    tvmc_args = tvmc_cmd.split(\" \")[1:]\n    exit_code = _main(tvmc_args)\n    on_error = \"Trying to run a MLF archive must fail because it's only supported on micro targets.\"\n    assert exit_code != 0, on_error\n\n\ndef test_tvmc_export_package_mlf(tflite_mobilenet_v1_1_quant, tmpdir_factory):\n    pytest.importorskip(\"tflite\")\n\n    tvmc_model = tvmc.frontends.load_model(tflite_mobilenet_v1_1_quant)\n    mod, params = tvmc_model.mod, tvmc_model.params\n\n    graph_module = tvm.relay.build(mod, target=\"llvm\", params=params)\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    output_file = os.path.join(output_dir, \"mock.tar\")\n\n    # Try to export MLF with no cross compiler set. No exception must be thrown.\n    tvmc_model.export_package(\n        executor_factory=graph_module,\n        package_path=output_file,\n        cross=None,\n        output_format=\"mlf\",\n    )\n    assert os.path.exists(output_file), \"Could not find the exported MLF archive.\"\n\n    # Try to export a MLF whilst also specifying a cross compiler. Since\n    # that's not supported it must throw a TVMCException and report the\n    # reason accordingly.\n    with pytest.raises(TVMCException) as exp:\n        tvmc_model.export_package(\n            executor_factory=graph_module,\n            package_path=output_file,\n            cross=\"cc\",\n            output_format=\"mlf\",\n        )\n    expected_reason = \"Specifying the MLF output and a cross compiler is not supported.\"\n    on_error = \"A TVMCException was caught but its reason is not the expected one.\"\n    assert str(exp.value) == expected_reason, on_error\n\n\ndef test_tvmc_import_package_project_dir(tflite_mobilenet_v1_1_quant, tflite_compile_model):\n    pytest.importorskip(\"tflite\")\n\n    # Generate a MLF archive.\n    compiled_model_mlf_tvmc_package = tflite_compile_model(\n        tflite_mobilenet_v1_1_quant, output_format=\"mlf\"\n    )\n\n    # Import the MLF archive setting 'project_dir'. It must succeed.\n    mlf_archive_path = compiled_model_mlf_tvmc_package.package_path\n    tvmc_package = TVMCPackage(mlf_archive_path, project_dir=\"/tmp/foobar\")\n    assert tvmc_package.type == \"mlf\", \"Can't load the MLF archive passing the project directory!\"\n\n    # Generate a Classic archive.\n    compiled_model_classic_tvmc_package = tflite_compile_model(tflite_mobilenet_v1_1_quant)\n\n    # Import the Classic archive setting 'project_dir'.\n    # It must fail since setting 'project_dir' is only support when importing a MLF archive.\n    classic_archive_path = compiled_model_classic_tvmc_package.package_path\n    with pytest.raises(TVMCException) as exp:\n        tvmc_package = TVMCPackage(classic_archive_path, project_dir=\"/tmp/foobar\")\n\n    expected_reason = \"Setting 'project_dir' is only allowed when importing a MLF.!\"\n    on_error = \"A TVMCException was caught but its reason is not the expected one.\"\n    assert str(exp.value) == expected_reason, on_error\n\n\ndef test_tvmc_import_package_mlf_graph(tflite_mobilenet_v1_1_quant, tflite_compile_model):\n    pytest.importorskip(\"tflite\")\n\n    tflite_compiled_model_mlf = tflite_compile_model(\n        tflite_mobilenet_v1_1_quant, output_format=\"mlf\"\n    )\n\n    # Compile and export a model to a MLF archive so it can be imported.\n    exported_tvmc_package = tflite_compiled_model_mlf\n    archive_path = exported_tvmc_package.package_path\n\n    # Import the MLF archive. TVMCPackage constructor will call import_package method.\n    tvmc_package = TVMCPackage(archive_path)\n\n    assert tvmc_package.lib_name is None, \".lib_name must not be set in the MLF archive.\"\n    assert tvmc_package.lib_path is None, \".lib_path must not be set in the MLF archive.\"\n    assert (\n        tvmc_package.graph is not None\n    ), \".graph must be set in the MLF archive for Graph executor.\"\n    assert tvmc_package.params is not None, \".params must be set in the MLF archive.\"\n    assert tvmc_package.type == \"mlf\", \".type must be set to 'mlf' in the MLF format.\"\n\n\ndef test_tvmc_import_package_mlf_aot(tflite_mobilenet_v1_1_quant, tflite_compile_model):\n    pytest.importorskip(\"tflite\")\n\n    tflite_compiled_model_mlf = tflite_compile_model(\n        tflite_mobilenet_v1_1_quant,\n        target=\"c\",\n        executor=backend.Executor(\"aot\"),\n        output_format=\"mlf\",\n        pass_context_configs=[\"tir.disable_vectorize=1\"],\n    )\n\n    # Compile and export a model to a MLF archive so it can be imported.\n    exported_tvmc_package = tflite_compiled_model_mlf\n    archive_path = exported_tvmc_package.package_path\n\n    # Import the MLF archive. TVMCPackage constructor will call import_package method.\n    tvmc_package = TVMCPackage(archive_path)\n\n    assert tvmc_package.lib_name is None, \".lib_name must not be set in the MLF archive.\"\n    assert tvmc_package.lib_path is None, \".lib_path must not be set in the MLF archive.\"\n    assert tvmc_package.graph is None, \".graph must not be set in the MLF archive for AOT executor.\"\n    assert tvmc_package.params is not None, \".params must be set in the MLF archive.\"\n    assert tvmc_package.type == \"mlf\", \".type must be set to 'mlf' in the MLF format.\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport platform\nimport pytest\nimport os\nimport numpy as np\n\nfrom os import path\n\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc.model import TVMCModel, TVMCPackage, TVMCResult\nfrom tvm.runtime.module import BenchmarkResult\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\n@pytest.mark.parametrize(\"use_vm\", [True, False])\ndef test_tvmc_workflow(use_vm, keras_simple):\n    pytest.importorskip(\"tensorflow\")\n    import tensorflow as tf\n\n    # Reset so the input name remains consistent across unit test runs\n    tf.keras.backend.clear_session()\n\n    tvmc_model = tvmc.load(keras_simple)\n    tuning_records = tvmc.tune(tvmc_model, target=\"llvm\", enable_autoscheduler=True, trials=2)\n    tvmc_package = tvmc.compile(\n        tvmc_model, tuning_records=tuning_records, target=\"llvm\", use_vm=use_vm\n    )\n    input_dict = {\"input_1\": np.random.uniform(size=(1, 32, 32, 3)).astype(\"float32\")}\n\n    result = tvmc.run(\n        tvmc_package, device=\"cpu\", end_to_end=True, benchmark=True, inputs=input_dict\n    )\n    assert type(tvmc_model) is TVMCModel\n    assert type(tvmc_package) is TVMCPackage\n    assert type(result) is TVMCResult\n    assert path.exists(tuning_records)\n    assert type(result.outputs) is dict\n    assert type(result.times) is BenchmarkResult\n    assert \"output_0\" in result.outputs.keys()\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n)\n@pytest.mark.parametrize(\"use_vm\", [True, False])\ndef test_save_load_model(use_vm, keras_simple, tmpdir_factory):\n    pytest.importorskip(\"onnx\")\n\n    tmpdir = tmpdir_factory.mktemp(\"data\")\n    tvmc_model = tvmc.load(keras_simple)\n\n    # Create tuning artifacts\n    tvmc.tune(tvmc_model, target=\"llvm\", trials=2)\n\n    # Create package artifacts\n    tvmc.compile(tvmc_model, target=\"llvm\", use_vm=use_vm)\n\n    # Save the model to disk\n    model_path = os.path.join(tmpdir, \"saved_model.tar\")\n    tvmc_model.save(model_path)\n\n    # Load the model into a new TVMCModel\n    new_tvmc_model = TVMCModel(model_path=model_path)\n\n    # Check that the two models match.\n    assert str(new_tvmc_model.mod) == str(tvmc_model.mod)\n    # Check that tuning records and the compiled package are recoverable.\n    assert path.exists(new_tvmc_model.default_package_path())\n    assert path.exists(new_tvmc_model.default_tuning_records_path())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_parse_config_file.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport os\nimport shlex\n\nimport tvm\nfrom tvm.driver.tvmc.main import _main\nfrom tvm.driver.tvmc.config_options import convert_config_json_to_cli, get_configs_json_dir\n\n\ndef test_parse_json_config_file_one_target():\n    tokens = convert_config_json_to_cli(\n        {\"targets\": [{\"kind\": \"llvm\"}], \"output\": \"resnet50-v2-7-autotuner_records.json\"}\n    )\n    expected_tokens = [{\"target\": \"llvm\"}, {\"output\": \"resnet50-v2-7-autotuner_records.json\"}]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_parse_json_config_file_multipile_targets():\n    tokens = convert_config_json_to_cli(\n        {\n            \"targets\": [{\"kind\": \"llvm\"}, {\"kind\": \"c\", \"mcpu\": \"cortex-m55\"}],\n            \"tuning-records\": \"resnet50-v2-7-autotuner_records.json\",\n            \"pass-config\": {\"tir.disable_vectorizer\": \"1\"},\n        }\n    )\n    expected_tokens = [\n        {\"target_c_mcpu\": \"cortex-m55\"},\n        {\"target\": \"llvm, c\"},\n        {\"tuning_records\": \"resnet50-v2-7-autotuner_records.json\"},\n        {\"pass_config\": [\"tir.disable_vectorizer=1\"]},\n    ]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_parse_json_config_file_executor():\n    tokens = convert_config_json_to_cli(\n        {\n            \"executor\": {\"kind\": \"aot\", \"interface-api\": \"c\"},\n            \"inputs\": \"imagenet_cat.npz\",\n            \"max-local-memory-per-block\": \"4\",\n            \"repeat\": \"100\",\n        }\n    )\n    expected_tokens = [\n        {\"executor\": \"aot\"},\n        {\"executor_aot_interface_api\": \"c\"},\n        {\"inputs\": \"imagenet_cat.npz\"},\n        {\"max_local_memory_per_block\": \"4\"},\n        {\"repeat\": \"100\"},\n    ]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_parse_json_config_file_target_and_executor():\n    tokens = convert_config_json_to_cli(\n        {\n            \"targets\": [\n                {\"kind\": \"ethos-u -accelerator_config=ethos-u55-256\"},\n                {\"kind\": \"c\", \"mcpu\": \"cortex-m55\"},\n                {\"kind\": \"cmsis-nn\"},\n            ],\n            \"executor\": {\"kind\": \"aot\", \"interface-api\": \"c\", \"unpacked-api\": \"1\"},\n            \"inputs\": \"imagenet_cat.npz\",\n            \"max-local-memory-per-block\": \"4\",\n            \"repeat\": \"100\",\n        }\n    )\n    expected_tokens = [\n        {\"target_c_mcpu\": \"cortex-m55\"},\n        {\"target\": \"ethos-u -accelerator_config=ethos-u55-256, c, cmsis-nn\"},\n        {\"executor\": \"aot\"},\n        {\"executor_aot_interface_api\": \"c\"},\n        {\"executor_aot_unpacked_api\": \"1\"},\n        {\"inputs\": \"imagenet_cat.npz\"},\n        {\"max_local_memory_per_block\": \"4\"},\n        {\"repeat\": \"100\"},\n    ]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_parse_json_config_file_runtime():\n    tokens = convert_config_json_to_cli(\n        {\n            \"targets\": [\n                {\"kind\": \"cmsis-nn\", \"from_device\": \"1\"},\n                {\"kind\": \"c\", \"mcpu\": \"cortex-m55\"},\n            ],\n            \"runtime\": {\"kind\": \"crt\"},\n            \"inputs\": \"imagenet_cat.npz\",\n            \"output\": \"predictions.npz\",\n            \"pass-config\": {\"tir.disable_vectorize\": \"1\", \"relay.backend.use_auto_scheduler\": \"0\"},\n        }\n    )\n    expected_tokens = [\n        {\"target_cmsis-nn_from_device\": \"1\"},\n        {\"target_c_mcpu\": \"cortex-m55\"},\n        {\"target\": \"cmsis-nn, c\"},\n        {\"runtime\": \"crt\"},\n        {\"inputs\": \"imagenet_cat.npz\"},\n        {\"output\": \"predictions.npz\"},\n        {\"pass_config\": [\"tir.disable_vectorize=1\", \"relay.backend.use_auto_scheduler=0\"]},\n    ]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\n@tvm.testing.requires_cmsisnn\ndef test_tvmc_cl_compile_run_config_file(tflite_mobilenet_v1_1_quant, tmpdir_factory):\n    compile_config_file = \"compile_config_test.json\"\n    pytest.importorskip(\"tflite\")\n\n    output_dir = tmpdir_factory.mktemp(\"mlf\")\n    input_model = tflite_mobilenet_v1_1_quant\n    output_file = os.path.join(output_dir, \"mock.tar\")\n\n    # Compile the input model and generate a Model Library Format (MLF) archive.\n    tvmc_cmd = (\n        f\"tvmc compile --config {compile_config_file} {input_model} --output {output_file} \"\n        f\"--output-format mlf\"\n    )\n    tvmc_args = shlex.split(tvmc_cmd)[1:]\n    _main(tvmc_args)\n    assert os.path.exists(output_file), \"Could not find the exported MLF archive.\"\n\n    # Run the MLF archive. It must fail since it's only supported on micro targets.\n    tvmc_cmd = f\"tvmc run {output_file}\"\n    tvmc_args = tvmc_cmd.split(\" \")[1:]\n    exit_code = _main(tvmc_args)\n    on_error = \"Trying to run a MLF archive must fail because it's only supported on micro targets.\"\n    assert exit_code != 0, on_error\n\n\ndef test_tvmc_get_configs_json_dir(tmpdir_factory, monkeypatch):\n    # Reset global state\n    monkeypatch.setattr(tvm.driver.tvmc.config_options, \"CONFIGS_JSON_DIR\", None)\n\n    # Get default directory for reference\n    default_dir = get_configs_json_dir()\n\n    # Set custom dir which does not exist -> ignore\n    monkeypatch.setattr(tvm.driver.tvmc.config_options, \"CONFIGS_JSON_DIR\", None)\n    monkeypatch.setenv(\"TVM_CONFIGS_JSON_DIR\", \"not_a_directory\")\n    result = get_configs_json_dir()\n    assert_msg = \"Non-existant directory passed via TVM_CONFIGS_JSON_DIR should be ignored.\"\n    assert result == default_dir, assert_msg\n\n    # Set custom dir which does exist\n    monkeypatch.setattr(tvm.driver.tvmc.config_options, \"CONFIGS_JSON_DIR\", None)\n    configs_dir = tmpdir_factory.mktemp(\"configs\")\n    monkeypatch.setenv(\"TVM_CONFIGS_JSON_DIR\", str(configs_dir))\n    result = get_configs_json_dir()\n    assert_msg = (\n        \"Custom value passed via TVM_CONFIGS_JSON_DIR should be used instead of default one.\"\n    )\n    assert result != default_dir and result is not None, assert_msg\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_pass_config.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nfrom unittest import mock\n\nfrom tvm.contrib.target.vitis_ai import vitis_ai_available\n\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.driver.tvmc.pass_config import parse_configs\nfrom tvm.tir.transform import PrimFuncPass\nfrom tvm.ir.transform import Sequential\n\n\ndef test_config_invalid_format():\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"relay.backend.use_auto_scheduler.missing.value\"])\n\n\ndef test_config_missing_from_tvm():\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"relay.backend.use_auto_scheduler.missing.value=1234\"])\n\n\ndef test_config_unsupported_tvmc_config():\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"tir.LoopPartition=value\"])\n\n\ndef test_config_empty():\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"\"])\n\n\ndef test_config_valid_config_bool():\n    configs = parse_configs([\"relay.backend.use_auto_scheduler=true\"])\n\n    assert len(configs) == 1\n    assert \"relay.backend.use_auto_scheduler\" in configs.keys()\n    assert configs[\"relay.backend.use_auto_scheduler\"] == True\n\n\n@pytest.mark.skipif(\n    not vitis_ai_available(),\n    reason=\"--target vitis-ai is not available. TVM built with 'USE_VITIS_AI OFF'\",\n)\ndef test_config_valid_multiple_configs():\n    configs = parse_configs(\n        [\n            \"relay.backend.use_auto_scheduler=false\",\n            \"tir.detect_global_barrier=10\",\n            \"relay.ext.vitis_ai.options.build_dir=mystring\",\n        ]\n    )\n\n    assert len(configs) == 3\n    assert \"relay.backend.use_auto_scheduler\" in configs.keys()\n    assert configs[\"relay.backend.use_auto_scheduler\"] == False\n    assert \"tir.detect_global_barrier\" in configs.keys()\n    assert configs[\"tir.detect_global_barrier\"] == 10\n    assert \"relay.ext.vitis_ai.options.build_dir\" in configs.keys()\n    assert configs[\"relay.ext.vitis_ai.options.build_dir\"] == \"mystring\"\n\n\ndef test_add_lower_pass_multi_built_in_pass():\n    configs = parse_configs(\n        [\n            \"tir.add_lower_pass=1,tir.transform.UnrollLoop\",\n            \"tir.add_lower_pass=1,tir.transform.HoistIfThenElse,2,tir.transform.LoopPartition\",\n        ]\n    )\n\n    assert len(configs[\"tir.add_lower_pass\"]) == 3\n    # opt_level: 1, pass: tir.transform.UnrollLoop\n    assert configs[\"tir.add_lower_pass\"][0][0] == 1\n    assert isinstance(configs[\"tir.add_lower_pass\"][0][1], PrimFuncPass)\n    # opt_level: 1, pass: tir.transform.HoistIfThenElse\n    assert configs[\"tir.add_lower_pass\"][1][0] == 1\n    assert isinstance(configs[\"tir.add_lower_pass\"][1][1], Sequential)\n    assert configs[\"tir.add_lower_pass\"][1][1].pass_info.name == \"tir.HoistIfThenElse\"\n    # opt_level: 2, pass: tir.transform.LoopPartition\n    assert configs[\"tir.add_lower_pass\"][2][0] == 2\n    assert isinstance(configs[\"tir.add_lower_pass\"][2][1], PrimFuncPass)\n\n\ndef test_add_lower_pass_multi_external_pass():\n    fake_pass_1 = mock.MagicMock()\n    fake_pass_2 = mock.MagicMock()\n    fake_pass_3 = mock.MagicMock()\n    with mock.patch.dict(\n        \"sys.modules\",\n        {\"fake_module\": fake_pass_1, \"fake_module\": fake_pass_2, \"fake_module\": fake_pass_3},\n    ):\n        configs = parse_configs(\n            [\n                \"tir.add_lower_pass=1,fake_module.fake_pass_1,2,fake_module.fake_pass2\",\n                \"tir.add_lower_pass=3,fake_module.fake_pass_3\",\n            ]\n        )\n        assert len(configs[\"tir.add_lower_pass\"]) == 3\n        # opt_level: 1, pass: fake_module.fake_pass_1\n        assert configs[\"tir.add_lower_pass\"][0][0] == 1\n        # opt_level: 2, pass: fake_module.fake_pass_2\n        assert configs[\"tir.add_lower_pass\"][1][0] == 2\n        # opt_level: 3, pass: fake_module.fake_pass_3\n        assert configs[\"tir.add_lower_pass\"][2][0] == 3\n\n\ndef test_add_lower_pass_multi_mix_pass():\n    fake_pass_1 = mock.MagicMock()\n    fake_pass_2 = mock.MagicMock()\n    with mock.patch.dict(\"sys.modules\", {\"fake_module\": fake_pass_1, \"fake_module\": fake_pass_2}):\n        configs = parse_configs(\n            [\n                \"tir.add_lower_pass=1,fake_module.fake_pass_1,1,tir.transform.UnrollLoop\",\n                \"tir.add_lower_pass=2,fake_module.fake_pass_2,2,tir.transform.LoopPartition\",\n            ]\n        )\n        assert len(configs[\"tir.add_lower_pass\"]) == 4\n        # opt_level: 1, pass: fake_module.fake_pass_1\n        assert configs[\"tir.add_lower_pass\"][0][0] == 1\n        # opt_level: 1, pass: tir.transform.UnrollLoop\n        assert configs[\"tir.add_lower_pass\"][1][0] == 1\n        assert isinstance(configs[\"tir.add_lower_pass\"][1][1], PrimFuncPass)\n        # opt_level: 2, pass: fake_module.fake_pass_2\n        assert configs[\"tir.add_lower_pass\"][2][0] == 2\n        # opt_level: 2, pass: tir.transform.LoopPartition\n        assert configs[\"tir.add_lower_pass\"][3][0] == 2\n        assert isinstance(configs[\"tir.add_lower_pass\"][3][1], PrimFuncPass)\n\n\ndef test_add_lower_pass_invalid_format():\n    # wrong format\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"tir.add_lower_pass=tir.transform.UnrollLoop,1\"])\n    # missing pass name\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"tir.add_lower_pass=1,tir.transform.UnrollLoop,3\"])\n    # wrong opt level\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"tir.add_lower_pass=a,tir.transform.UnrollLoop\"])\n    # fake module\n    with pytest.raises(ModuleNotFoundError):\n        _ = parse_configs(\n            [\"tir.add_lower_pass=1,tir.transform.UnrollLoop,2,path.to.module.fake_func\"]\n        )\n    # real module and fake func\n    with pytest.raises(TVMCException):\n        _ = parse_configs([\"tir.add_lower_pass=1,tir.transform.UnrollLoop,2,tvm.tir.fake_func\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_pass_list.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport pytest\nfrom tvm.driver.tvmc.pass_list import parse_pass_list_str\n\n\ndef test_parse_pass_list_str():\n    assert [\"\"] == parse_pass_list_str(\"\")\n    assert [\"FoldScaleAxis\", \"FuseOps\"] == parse_pass_list_str(\"FoldScaleAxis,FuseOps\")\n\n    with pytest.raises(argparse.ArgumentTypeError) as ate:\n        parse_pass_list_str(\"MyYobaPass,MySuperYobaPass,FuseOps\")\n\n    assert \"MyYobaPass\" in str(ate.value)\n    assert \"MySuperYobaPass\" in str(ate.value)\n    assert \"FuseOps\" in str(ate.value)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_registry_options.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\n\nimport pytest\n\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.driver.tvmc.registry import generate_registry_args, reconstruct_registry_entity\nfrom tvm.relay.backend import Executor\n\n\ndef test_registry_to_argparse():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor)\n    parsed, _ = parser.parse_known_args([\"--executor=aot\", \"--executor-aot-interface-api=c\"])\n\n    assert parsed.executor == \"aot\"\n    assert parsed.executor_aot_interface_api == \"c\"\n\n\ndef test_registry_to_argparse_default():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor, \"aot\")\n    parsed, _ = parser.parse_known_args([])\n\n    assert parsed.executor == \"aot\"\n\n\ndef test_mapping_registered_args():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor)\n    parsed, _ = parser.parse_known_args([\"--executor=aot\", \"--executor-aot-interface-api=c\"])\n    entity = reconstruct_registry_entity(parsed, Executor)\n\n    assert isinstance(entity, Executor)\n    assert \"interface-api\" in entity\n    assert entity[\"interface-api\"] == \"c\"\n\n\ndef test_mapping_registered_args_no_match_for_name():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor)\n    parsed, _ = parser.parse_known_args([\"--executor=woof\"])\n\n    with pytest.raises(TVMCException, match='Executor \"woof\" is not defined'):\n        reconstruct_registry_entity(parsed, Executor)\n\n\ndef test_mapping_registered_args_no_arg():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor)\n    parsed, _ = parser.parse_known_args([])\n\n    assert reconstruct_registry_entity(parsed, Executor) == None\n\n\ndef test_mapping_registered_args_mismatch_for_arg():\n    parser = argparse.ArgumentParser()\n    generate_registry_args(parser, Executor)\n    parsed, _ = parser.parse_known_args([\"--executor=aot\", \"--executor-graph-link-params=1\"])\n\n    with pytest.raises(\n        TVMCException,\n        match=\"Passed --executor-graph-link-params but did not specify graph executor\",\n    ):\n        reconstruct_registry_entity(parsed, Executor)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport numpy as np\n\nfrom tvm import rpc\nfrom tvm.driver import tvmc\nfrom tvm.driver.tvmc.model import TVMCResult\nfrom tvm.driver.tvmc.result_utils import get_top_results\nfrom tvm.runtime.module import BenchmarkResult\n\n\ndef test_generate_tensor_data_zeros():\n    expected_shape = (2, 3)\n    expected_dtype = \"uint8\"\n    sut = tvmc.runner.generate_tensor_data(expected_shape, expected_dtype, \"zeros\")\n\n    assert sut.shape == (2, 3)\n\n\ndef test_generate_tensor_data_ones():\n    expected_shape = (224, 224)\n    expected_dtype = \"uint8\"\n    sut = tvmc.runner.generate_tensor_data(expected_shape, expected_dtype, \"ones\")\n\n    assert sut.shape == (224, 224)\n\n\ndef test_generate_tensor_data_random():\n    expected_shape = (2, 3)\n    expected_dtype = \"uint8\"\n    sut = tvmc.runner.generate_tensor_data(expected_shape, expected_dtype, \"random\")\n\n    assert sut.shape == (2, 3)\n\n\ndef test_generate_tensor_data__type_unknown():\n    with pytest.raises(tvmc.TVMCException) as e:\n        tvmc.runner.generate_tensor_data((2, 3), \"float32\", \"whatever\")\n\n\ndef test_format_times__contains_header():\n    fake_result = TVMCResult(outputs=None, times=BenchmarkResult([0.6, 1.2, 0.12, 0.42]))\n    sut = fake_result.format_times()\n    assert \"std (ms)\" in sut\n\n\ndef test_get_top_results_keep_results():\n    fake_outputs = {\"output_0\": np.array([[1, 2, 3, 4], [5, 6, 7, 8]])}\n    fake_result = TVMCResult(outputs=fake_outputs, times=None)\n    number_of_results_wanted = 3\n    sut = get_top_results(fake_result, number_of_results_wanted)\n\n    expected_number_of_lines = 2\n    assert len(sut) == expected_number_of_lines\n\n    expected_number_of_results_per_line = 3\n    assert len(sut[0]) == expected_number_of_results_per_line\n    assert len(sut[1]) == expected_number_of_results_per_line\n\n\n@pytest.mark.parametrize(\"use_vm\", [True, False])\ndef test_run_tflite_module__with_profile__valid_input(\n    use_vm, tflite_mobilenet_v1_1_quant, tflite_compile_model, imagenet_cat\n):\n    # some CI environments wont offer TFLite, so skip in case it is not present\n    pytest.importorskip(\"tflite\")\n\n    inputs = np.load(imagenet_cat)\n    input_dict = {\"input\": inputs[\"input\"].astype(\"uint8\")}\n\n    tflite_compiled_model = tflite_compile_model(tflite_mobilenet_v1_1_quant, use_vm=use_vm)\n    result = tvmc.run(\n        tflite_compiled_model,\n        inputs=input_dict,\n        benchmark=True,\n        hostname=None,\n        device=\"cpu\",\n        profile=True,\n    )\n\n    # collect the top 5 results\n    top_5_results = get_top_results(result, 5)\n    top_5_ids = top_5_results[0]\n\n    # IDs were collected from this reference:\n    # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/\n    # java/demo/app/src/main/assets/labels_mobilenet_quant_v1_224.txt\n    tiger_cat_mobilenet_id = 283\n\n    assert (\n        tiger_cat_mobilenet_id in top_5_ids\n    ), \"tiger cat is expected in the top-5 for mobilenet v1\"\n    assert isinstance(result.outputs, dict)\n    assert isinstance(result.times, BenchmarkResult)\n    assert \"output_0\" in result.outputs.keys()\n\n\ndef test_run_tflite_module_with_rpc(\n    tflite_mobilenet_v1_1_quant, tflite_compile_model, imagenet_cat\n):\n    \"\"\"\n    Test to check that TVMC run is functional when it is being used in\n    conjunction with an RPC server.\n    \"\"\"\n    pytest.importorskip(\"tflite\")\n\n    inputs = np.load(imagenet_cat)\n    input_dict = {\"input\": inputs[\"input\"].astype(\"uint8\")}\n\n    tflite_compiled_model = tflite_compile_model(tflite_mobilenet_v1_1_quant)\n\n    server = rpc.Server(\"127.0.0.1\", 9099)\n    result = tvmc.run(\n        tflite_compiled_model,\n        inputs=input_dict,\n        hostname=server.host,\n        port=server.port,\n        device=\"cpu\",\n    )\n\n    top_5_results = get_top_results(result, 5)\n    top_5_ids = top_5_results[0]\n\n    # IDs were collected from this reference:\n    # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/\n    # java/demo/app/src/main/assets/labels_mobilenet_quant_v1_224.txt\n    tiger_cat_mobilenet_id = 283\n\n    assert (\n        tiger_cat_mobilenet_id in top_5_ids\n    ), \"tiger cat is expected in the top-5 for mobilenet v1\"\n    assert isinstance(result.outputs, dict)\n    assert \"output_0\" in result.outputs.keys()\n\n\n@pytest.mark.parametrize(\"use_vm\", [True, False])\n@pytest.mark.parametrize(\n    \"benchmark,repeat,number,expected_len\", [(False, 1, 1, 0), (True, 1, 1, 1), (True, 3, 2, 3)]\n)\ndef test_run_relay_module__benchmarking(\n    use_vm,\n    benchmark,\n    repeat,\n    number,\n    expected_len,\n    relay_text_conv2d,\n    relay_compile_model,\n):\n    \"\"\"Check the length of the results from benchmarking is what is expected by expected_len.\"\"\"\n    shape_dict = {\"data\": (1, 3, 64, 64), \"weight\": (3, 3, 5, 5)}\n    input_dict = {\n        \"data\": np.random.randint(low=0, high=10, size=shape_dict[\"data\"], dtype=\"uint8\"),\n        \"weight\": np.random.randint(low=0, high=10, size=shape_dict[\"weight\"], dtype=\"int8\"),\n    }\n\n    tflite_compiled_model = relay_compile_model(\n        relay_text_conv2d, shape_dict=shape_dict, use_vm=use_vm\n    )\n    result = tvmc.run(\n        tflite_compiled_model,\n        inputs=input_dict,\n        hostname=None,\n        device=\"cpu\",\n        benchmark=benchmark,\n        repeat=repeat,\n        number=number,\n    )\n\n    # When no benchmarking is used, an empty list is used to\n    # represent an absence of results.\n    if isinstance(result.times, list):\n        assert len(result.times) == expected_len\n    else:\n        assert len(result.times.results) == expected_len\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_shape_parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\n\nimport pytest\n\nfrom tvm.driver.tvmc.shape_parser import parse_shape_string\n\n\ndef test_shape_parser():\n    # Check that a valid input is parsed correctly\n    shape_string = \"input:[10,10,10]\"\n    shape_dict = parse_shape_string(shape_string)\n    assert shape_dict == {\"input\": [10, 10, 10]}\n\n\ndef test_alternate_syntax():\n    shape_string = \"input:0:[10,10,10] input2:[20,20,20,20]\"\n    shape_dict = parse_shape_string(shape_string)\n    assert shape_dict == {\"input:0\": [10, 10, 10], \"input2\": [20, 20, 20, 20]}\n\n\n@pytest.mark.parametrize(\n    \"shape_string\",\n    [\n        \"input:[10,10,10] input2:[20,20,20,20]\",\n        \"input: [10, 10, 10] input2: [20, 20, 20, 20]\",\n        \"input:[10,10,10],input2:[20,20,20,20]\",\n    ],\n)\ndef test_alternate_syntaxes(shape_string):\n    shape_dict = parse_shape_string(shape_string)\n    assert shape_dict == {\"input\": [10, 10, 10], \"input2\": [20, 20, 20, 20]}\n\n\ndef test_negative_dimensions():\n    # Check that negative dimensions parse to Any correctly.\n    shape_string = \"input:[-1,3,224,224]\"\n    shape_dict = parse_shape_string(shape_string)\n    # Convert to strings to allow comparison with Any.\n    assert str(shape_dict) == \"{'input': [?, 3, 224, 224]}\"\n\n\ndef test_multiple_valid_gpu_inputs():\n    # Check that multiple valid gpu inputs are parsed correctly.\n    shape_string = \"gpu_0/data_0:[1, -1,224,224] gpu_1/data_1:[7, 7]\"\n    shape_dict = parse_shape_string(shape_string)\n    expected = \"{'gpu_0/data_0': [1, ?, 224, 224], 'gpu_1/data_1': [7, 7]}\"\n    assert str(shape_dict) == expected\n\n\ndef test_invalid_pattern():\n    shape_string = \"input:[a,10]\"\n    with pytest.raises(argparse.ArgumentTypeError):\n        parse_shape_string(shape_string)\n\n\ndef test_invalid_separators():\n    shape_string = \"input:5,10 input2:10,10\"\n    with pytest.raises(argparse.ArgumentTypeError):\n        parse_shape_string(shape_string)\n\n\ndef test_invalid_colon():\n    shape_string = \"gpu_0/data_0:5,10 :test:10,10\"\n    with pytest.raises(argparse.ArgumentTypeError):\n        parse_shape_string(shape_string)\n\n\n@pytest.mark.parametrize(\n    \"shape_string\",\n    [\n        \"gpu_0/data_0:5,10 /:10,10\",\n        \"gpu_0/data_0:5,10 data/:10,10\",\n        \"gpu_0/data_0:5,10 /data:10,10\",\n        \"gpu_0/invalid/data_0:5,10 data_1:10,10\",\n    ],\n)\ndef test_invalid_slashes(shape_string):\n    with pytest.raises(argparse.ArgumentTypeError):\n        parse_shape_string(shape_string)\n\n\ndef test_dot():\n    # Check dot in input name\n    shape_string = \"input.1:[10,10,10]\"\n    shape_dict = parse_shape_string(shape_string)\n    assert shape_dict == {\"input.1\": [10, 10, 10]}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport tvm.testing\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.driver.tvmc.target import target_from_cli, tokenize_target, parse_target\n\n\ndef test_target_from_cli__error_duplicate():\n    with pytest.raises(TVMCException):\n        _ = target_from_cli(\"llvm, llvm\")\n\n\ndef test_target_invalid_more_than_two_tvm_targets():\n    with pytest.raises(TVMCException):\n        _ = target_from_cli(\"cuda, opencl, llvm\")\n\n\ndef test_target_from_cli__error_target_not_found():\n    with pytest.raises(TVMCException):\n        _ = target_from_cli(\"invalidtarget\")\n\n\ndef test_target_two_tvm_targets():\n    tvm_target, extra_targets = target_from_cli(\n        \"opencl -device=mali, llvm -mtriple=aarch64-linux-gnu\"\n    )\n\n    assert \"opencl\" in str(tvm_target)\n    assert \"llvm\" in str(tvm_target.host)\n\n    # No extra targets\n    assert 0 == len(extra_targets)\n\n\ndef test_tokenize_target_with_opts():\n    tokens = tokenize_target(\"foo -opt1=value1 --flag, bar -opt2=value2\")\n    expected_tokens = [\"foo\", \"-opt1=value1\", \"--flag\", \",\", \"bar\", \"-opt2=value2\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_tokenize_target_with_plus_sign():\n    tokens = tokenize_target(\"foo -opt1=+value1 --flag, bar -opt2=test,+v\")\n    expected_tokens = [\"foo\", \"-opt1=+value1\", \"--flag\", \",\", \"bar\", \"-opt2=test,+v\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_tokenize_target_with_commas():\n    tokens = tokenize_target(\"foo -opt1=v,a,l,u,e,1 --flag\")\n    expected_tokens = [\"foo\", \"-opt1=v,a,l,u,e,1\", \"--flag\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_tokenize_target_with_commas_and_single_quotes():\n    tokens = tokenize_target(\"foo -opt1='v, a, l, u, e', bar\")\n    expected_tokens = [\"foo\", \"-opt1='v, a, l, u, e'\", \",\", \"bar\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_tokenize_target_with_commas_and_double_quotes():\n    tokens = tokenize_target('foo -opt1=\"v, a, l, u, e\", bar')\n    expected_tokens = [\"foo\", '-opt1=\"v, a, l, u, e\"', \",\", \"bar\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_tokenize_target_with_dashes():\n    tokens = tokenize_target(\"foo-bar1 -opt-1=t-e-s-t, baz\")\n    expected_tokens = [\"foo-bar1\", \"-opt-1=t-e-s-t\", \",\", \"baz\"]\n\n    assert len(tokens) == len(expected_tokens)\n    assert tokens == expected_tokens\n\n\ndef test_parse_single_target_with_opts():\n    targets = parse_target(\"llvm -device=arm_cpu -mattr=+fp\")\n\n    assert len(targets) == 1\n    assert \"device\" in targets[0][\"opts\"]\n    assert \"mattr\" in targets[0][\"opts\"]\n\n\ndef test_parse_multiple_target():\n    targets = parse_target(\"compute-library, llvm -device=arm_cpu\")\n\n    assert len(targets) == 2\n    assert \"compute-library\" == targets[0][\"name\"]\n    assert \"llvm\" == targets[1][\"name\"]\n\n\ndef test_parse_hybrid_target():\n    \"\"\"Hybrid Target and external codegen\"\"\"\n    targets = parse_target(\"cmsis-nn -accelerator_config=ethos-u55-256, llvm -device=arm_cpu\")\n\n    assert len(targets) == 2\n    assert \"cmsis-nn\" == targets[0][\"name\"]\n    assert not targets[0][\"is_tvm_target\"]\n    assert \"llvm\" == targets[1][\"name\"]\n    assert targets[1][\"is_tvm_target\"]\n\n\ndef test_parse_multiple_hybrid_target():\n    \"\"\"Hybrid Target and multiple external codegen\"\"\"\n    targets = parse_target(\"ethos-u,cmsis-nn,c\")\n\n    assert len(targets) == 3\n    assert \"ethos-u\" == targets[0][\"name\"]\n    assert not targets[0][\"is_tvm_target\"]\n    assert \"cmsis-nn\" == targets[1][\"name\"]\n    assert not targets[1][\"is_tvm_target\"]\n    assert \"c\" == targets[2][\"name\"]\n    assert targets[2][\"is_tvm_target\"]\n\n\ndef test_parse_quotes_and_separators_on_options():\n    targets_no_quote = parse_target(\"foo -option1=+v1.0x,+value,+bar\")\n    targets_single_quote = parse_target(\"foo -option1='+v1.0x,+value'\")\n    targets_double_quote = parse_target('foo -option1=\"+v1.0x,+value\"')\n\n    assert len(targets_no_quote) == 1\n    assert \"+v1.0x,+value,+bar\" == targets_no_quote[0][\"opts\"][\"option1\"]\n\n    assert len(targets_single_quote) == 1\n    assert \"+v1.0x,+value\" == targets_single_quote[0][\"opts\"][\"option1\"]\n\n    assert len(targets_double_quote) == 1\n    assert \"+v1.0x,+value\" == targets_double_quote[0][\"opts\"][\"option1\"]\n\n\ndef test_parse_multiple_target_with_opts_ethos_n78():\n    targets = parse_target(\"ethos-n -myopt=value, llvm -device=arm_cpu\")\n\n    assert len(targets) == 2\n    assert \"ethos-n\" == targets[0][\"name\"]\n    assert \"myopt\" in targets[0][\"opts\"]\n    assert \"value\" == targets[0][\"opts\"][\"myopt\"]\n    assert \"llvm\" == targets[1][\"name\"]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_target_options.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\n\nimport pytest\n\nimport tvm\nfrom tvm.driver.tvmc import TVMCException\nfrom tvm.driver.tvmc.target import generate_target_args, reconstruct_target_args, target_from_cli\n\n\ndef test_target_to_argparse():\n    parser = argparse.ArgumentParser()\n    generate_target_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\"--target=llvm\", \"--target-llvm-mattr=+fp,+mve\", \"--target-llvm-mcpu=cortex-m3\"]\n    )\n    assert parsed.target == \"llvm\"\n    assert parsed.target_llvm_mcpu == \"cortex-m3\"\n    assert parsed.target_llvm_mattr == \"+fp,+mve\"\n\n\n@tvm.testing.requires_cmsisnn\ndef test_target_to_argparse_known_codegen():\n    parser = argparse.ArgumentParser()\n    generate_target_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--target=cmsis-nn,llvm\",\n            \"--target-cmsis-nn-mcpu=cortex-m3\",\n            \"--target-llvm-mattr=+fp,+mve\",\n            \"--target-llvm-mcpu=cortex-m3\",\n        ]\n    )\n    assert parsed.target == \"cmsis-nn,llvm\"\n    assert parsed.target_llvm_mcpu == \"cortex-m3\"\n    assert parsed.target_llvm_mattr == \"+fp,+mve\"\n    assert parsed.target_cmsis_nn_mcpu == \"cortex-m3\"\n\n\ndef test_mapping_target_args():\n    parser = argparse.ArgumentParser()\n    generate_target_args(parser)\n    parsed, _ = parser.parse_known_args([\"--target=llvm\", \"--target-llvm-mcpu=cortex-m3\"])\n    assert reconstruct_target_args(parsed) == {\"llvm\": {\"mcpu\": \"cortex-m3\"}}\n\n\n@tvm.testing.requires_cmsisnn\ndef test_include_known_codegen():\n    parser = argparse.ArgumentParser()\n    generate_target_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\"--target=cmsis-nn,c\", \"--target-cmsis-nn-mcpu=cortex-m55\", \"--target-c-mcpu=cortex-m55\"]\n    )\n    assert reconstruct_target_args(parsed) == {\n        \"c\": {\"mcpu\": \"cortex-m55\"},\n        \"cmsis-nn\": {\"mcpu\": \"cortex-m55\"},\n    }\n\n\ndef test_skip_target_from_codegen():\n    parser = argparse.ArgumentParser()\n    generate_target_args(parser)\n    parsed, left = parser.parse_known_args(\n        [\"--target=cmsis-nn, c\", \"--target-cmsis-nn-from_device=1\", \"--target-c-mcpu=cortex-m55\"]\n    )\n    assert left == [\"--target-cmsis-nn-from_device=1\"]\n    assert reconstruct_target_args(parsed) == {\"c\": {\"mcpu\": \"cortex-m55\"}}\n\n\ndef test_target_recombobulation_single():\n    tvm_target, _ = target_from_cli(\"llvm\", {\"llvm\": {\"mcpu\": \"cortex-m3\"}})\n\n    assert str(tvm_target) == \"llvm -keys=arm_cpu,cpu -mcpu=cortex-m3\"\n\n\ndef test_target_recombobulation_many():\n    tvm_target, _ = target_from_cli(\n        \"opencl -device=mali, llvm -mtriple=aarch64-linux-gnu\",\n        {\"llvm\": {\"mcpu\": \"cortex-m3\"}, \"opencl\": {\"max_num_threads\": 404}},\n    )\n\n    assert \"-max_num_threads=404\" in str(tvm_target)\n    assert \"-device=mali\" in str(tvm_target)\n    assert \"-mtriple=aarch64-linux-gnu\" in str(tvm_target.host)\n    assert \"-mcpu=cortex-m3\" in str(tvm_target.host)\n\n\ndef test_target_recombobulation_codegen():\n    tvm_target, extras = target_from_cli(\n        \"cmsis-nn, c -mcpu=cortex-m55\",\n        {\"cmsis-nn\": {\"mcpu\": \"cortex-m55\"}},\n    )\n\n    assert \"-mcpu=cortex-m55\" in str(tvm_target)\n    assert len(extras) == 1\n    assert extras[0][\"name\"] == \"cmsis-nn\"\n    assert extras[0][\"opts\"] == {\"mcpu\": \"cortex-m55\"}\n\n\ndef test_error_if_target_missing():\n    with pytest.raises(\n        TVMCException,\n        match=\"Passed --target-opencl-max_num_threads but did not specify opencl target\",\n    ):\n        target_from_cli(\n            \"llvm\",\n            {\"opencl\": {\"max_num_threads\": 404}},\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_tracker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom tvm.driver.tvmc.tracker import tracker_host_port_from_cli\n\n\ndef test_tracker_host_port_from_cli__hostname_port():\n    input_str = \"1.2.3.4:9090\"\n    expected_host = \"1.2.3.4\"\n    expected_port = 9090\n\n    actual_host, actual_port = tracker_host_port_from_cli(input_str)\n\n    assert expected_host == actual_host\n    assert expected_port == actual_port\n\n\ndef test_tracker_host_port_from_cli__hostname_port__empty():\n    input_str = \"\"\n\n    actual_host, actual_port = tracker_host_port_from_cli(input_str)\n\n    assert actual_host is None\n    assert actual_port is None\n\n\ndef test_tracker_host_port_from_cli__only_hostname__default_port_is_9090():\n    input_str = \"1.2.3.4\"\n    expected_host = \"1.2.3.4\"\n    expected_port = 9090\n\n    actual_host, actual_port = tracker_host_port_from_cli(input_str)\n\n    assert expected_host == actual_host\n    assert expected_port == actual_port\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom unittest.mock import MagicMock\n\nimport tvm\nfrom tvm import relay\nfrom tvm.ir.instrument import pass_instrument\nfrom tvm.driver.tvmc.transform import convert_graph_layout\n\n\ndef test_layout_transform_fold_constant(relay_conv2d):\n    \"\"\"\n    Test layout is correctly transformed and constant folding is applied.\n    \"\"\"\n    desired_layout = \"NHWC\"\n\n    @pass_instrument\n    class CollectPassNames:\n        def __init__(self):\n            self.names = []\n\n        def run_after_pass(self, _, info):\n            self.names.append(info.name)\n\n    pass_names = CollectPassNames()\n    with tvm.transform.PassContext(opt_level=3, instruments=[pass_names]):\n        convert_graph_layout(relay_conv2d, desired_layout)\n\n    names = pass_names.names\n    assert \"ConvertLayout\" in names\n    assert \"FoldConstant\" in names\n    assert names.index(\"ConvertLayout\") < names.index(\"FoldConstant\")\n\n\ndef test_layout_transform_convert_layout_pass_args(relay_conv2d, monkeypatch):\n    \"\"\"\n    Check the convert layout desired layouts arugment is what is expected when\n    a desired layout is provided.\n    \"\"\"\n    desired_layout = \"NHWC\"\n\n    mock_convert_layout = MagicMock()\n    mock_convert_layout.return_value = relay.transform.ConvertLayout({})\n    monkeypatch.setattr(relay.transform, \"ConvertLayout\", mock_convert_layout)\n\n    with tvm.transform.PassContext(opt_level=3):\n        convert_graph_layout(relay_conv2d, desired_layout)\n\n    mock_convert_layout.assert_called_once_with(\n        {\n            \"nn.conv2d\": [\"NHWC\", \"default\"],\n            \"nn.conv2d_transpose\": [\"NHWC\", \"default\"],\n            \"qnn.conv2d\": [\"NHWC\", \"default\"],\n        }\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/driver/tvmc/test_workspace_pools.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport argparse\n\nimport tvm\nfrom tvm.driver.tvmc.workspace_pools import (\n    generate_workspace_pools_args,\n    workspace_pools_recombobulate,\n)\nfrom tvm.target import Target\nfrom tvm.driver.tvmc import TVMCException\n\n\ndef test_workspace_pools_argparse():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, unparsed = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram,flash\",\n            \"--workspace-pools-targets=sram:c,llvm\",\n            \"--workspace-pools-targets=flash:c\",\n            \"--workspace-pools-size-hint-bytes=sram:400\",\n            \"--workspace-pools-size-hint-bytes=sram:500\",\n            \"--workspace-pools-clock-frequency-hz=sram:500\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=sram:200\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=sram:100\",\n            \"--workspace-pools-read-latency-cycles=sram:50\",\n            \"--workspace-pools-read-latency-cycles=flash:30\",\n            \"--workspace-pools-write-latency-cycles=sram:9001\",\n            \"--workspace-pools-target-burst-bytes=sram:c:2\",\n            \"--workspace-pools-is-internal=sram:0\",\n        ]\n    )\n\n    assert parsed.workspace_pools == \"sram,flash\"\n    assert parsed.workspace_pools_targets == [\"sram:c,llvm\", \"flash:c\"]\n    assert parsed.workspace_pools_size_hint_bytes == [\"sram:400\", \"sram:500\"]\n    assert parsed.workspace_pools_clock_frequency_hz == [\"sram:500\"]\n    assert parsed.workspace_pools_read_bandwidth_bytes_per_cycle == [\"sram:200\"]\n    assert parsed.workspace_pools_write_bandwidth_bytes_per_cycle == [\"sram:100\"]\n    assert parsed.workspace_pools_read_latency_cycles == [\"sram:50\", \"flash:30\"]\n    assert parsed.workspace_pools_write_latency_cycles == [\"sram:9001\"]\n    assert parsed.workspace_pools_target_burst_bytes == [\"sram:c:2\"]\n\n    assert unparsed == [\"--workspace-pools-is-internal=sram:0\"]\n\n\ndef test_workspace_pools_recombobulate_empty():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args([])\n\n    targets = [Target(\"llvm\")]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert memory_pools is None\n\n\ndef test_workspace_pools_recombobulate():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:llvm\",\n            \"--workspace-pools-size-hint-bytes=sram:400\",\n            \"--workspace-pools-clock-frequency-hz=sram:500\",\n        ]\n    )\n\n    targets = [Target(\"llvm\")]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 1\n    assert memory_pools.pools[0].pool_name == \"sram\"\n    assert memory_pools.pools[0].size_hint_bytes == 400\n    assert memory_pools.pools[0].clock_frequency_hz == 500\n\n\ndef test_workspace_pools_defaults():\n    parser = argparse.ArgumentParser()\n    targets = [Target(\"llvm\")]\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:llvm\",\n        ]\n    )\n\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 1\n    assert memory_pools.pools[0].pool_name == \"sram\"\n    assert memory_pools.pools[0].size_hint_bytes == -1\n    assert memory_pools.pools[0].clock_frequency_hz == -1\n    assert memory_pools.pools[0].read_bandwidth_bytes_per_cycle == -1\n    assert memory_pools.pools[0].write_bandwidth_bytes_per_cycle == -1\n    assert memory_pools.pools[0].read_latency_cycles == 0\n    assert memory_pools.pools[0].write_latency_cycles == 0\n    assert len(memory_pools.pools[0].target_burst_bytes) == 0\n\n\ndef test_workspace_pools_recombobulate_multi_fields():\n    parser = argparse.ArgumentParser()\n    targets = [Target(\"c\")]\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-size-hint-bytes=sram:400\",\n            \"--workspace-pools-clock-frequency-hz=sram:500\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=sram:200\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=sram:100\",\n            \"--workspace-pools-read-latency-cycles=sram:50\",\n            \"--workspace-pools-write-latency-cycles=sram:9001\",\n            \"--workspace-pools-target-burst-bytes=sram:c:2\",\n        ]\n    )\n\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 1\n    assert memory_pools.pools[0].pool_name == \"sram\"\n    assert memory_pools.pools[0].size_hint_bytes == 400\n    assert memory_pools.pools[0].clock_frequency_hz == 500\n    assert memory_pools.pools[0].read_bandwidth_bytes_per_cycle == 200\n    assert memory_pools.pools[0].write_bandwidth_bytes_per_cycle == 100\n    assert memory_pools.pools[0].read_latency_cycles == 50\n    assert memory_pools.pools[0].write_latency_cycles == 9001\n    assert len(memory_pools.pools[0].target_burst_bytes) == 1\n    assert memory_pools.pools[0].target_burst_bytes[targets[0]] == 2\n\n\ndef test_workspace_pools_recombobulate_multi_fields_variant():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=flash\",\n            \"--workspace-pools-targets=flash:c\",\n            \"--workspace-pools-size-hint-bytes=flash:2048\",\n            \"--workspace-pools-clock-frequency-hz=flash:2000000\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=flash:4\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=flash:1\",\n            \"--workspace-pools-read-latency-cycles=flash:2000\",\n            \"--workspace-pools-write-latency-cycles=flash:1000\",\n            \"--workspace-pools-target-burst-bytes=flash:c:4\",\n        ]\n    )\n\n    targets = [Target(\"c\")]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 1\n    assert memory_pools.pools[0].pool_name == \"flash\"\n    assert memory_pools.pools[0].size_hint_bytes == 2048\n    assert memory_pools.pools[0].clock_frequency_hz == 2000000\n    assert memory_pools.pools[0].read_bandwidth_bytes_per_cycle == 4\n    assert memory_pools.pools[0].write_bandwidth_bytes_per_cycle == 1\n    assert memory_pools.pools[0].read_latency_cycles == 2000\n    assert memory_pools.pools[0].write_latency_cycles == 1000\n    assert len(memory_pools.pools[0].target_burst_bytes) == 1\n    assert memory_pools.pools[0].target_burst_bytes[targets[0]] == 4\n\n\ndef test_workspace_pools_recombobulate_multi_fields_multi_pools():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram,flash\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-targets=flash:c\",\n            \"--workspace-pools-size-hint-bytes=sram:1024\",\n            \"--workspace-pools-size-hint-bytes=flash:2048\",\n            \"--workspace-pools-clock-frequency-hz=sram:4000000\",\n            \"--workspace-pools-clock-frequency-hz=flash:2000000\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=sram:8\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=flash:4\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=sram:4\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=flash:1\",\n            \"--workspace-pools-read-latency-cycles=sram:250\",\n            \"--workspace-pools-read-latency-cycles=flash:2000\",\n            \"--workspace-pools-write-latency-cycles=sram:500\",\n            \"--workspace-pools-write-latency-cycles=flash:1000\",\n            \"--workspace-pools-target-burst-bytes=sram:c:8\",\n            \"--workspace-pools-target-burst-bytes=flash:c:4\",\n        ]\n    )\n\n    targets = [Target(\"c\")]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 2\n\n    assert memory_pools.pools[0].pool_name == \"sram\"\n    assert memory_pools.pools[0].size_hint_bytes == 1024\n    assert memory_pools.pools[0].clock_frequency_hz == 4000000\n    assert memory_pools.pools[0].read_bandwidth_bytes_per_cycle == 8\n    assert memory_pools.pools[0].write_bandwidth_bytes_per_cycle == 4\n    assert memory_pools.pools[0].read_latency_cycles == 250\n    assert memory_pools.pools[0].write_latency_cycles == 500\n    assert len(memory_pools.pools[0].target_burst_bytes) == 1\n    assert memory_pools.pools[0].target_burst_bytes[targets[0]] == 8\n\n    assert memory_pools.pools[1].pool_name == \"flash\"\n    assert memory_pools.pools[1].size_hint_bytes == 2048\n    assert memory_pools.pools[1].clock_frequency_hz == 2000000\n    assert memory_pools.pools[1].read_bandwidth_bytes_per_cycle == 4\n    assert memory_pools.pools[1].write_bandwidth_bytes_per_cycle == 1\n    assert memory_pools.pools[1].read_latency_cycles == 2000\n    assert memory_pools.pools[1].write_latency_cycles == 1000\n    assert len(memory_pools.pools[1].target_burst_bytes) == 1\n    assert memory_pools.pools[1].target_burst_bytes[targets[0]] == 4\n\n\ndef test_workspace_pools_recombobulate_multi_fields_ordering():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram,flash\",\n            \"--workspace-pools-targets=flash:c\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-size-hint-bytes=flash:2048\",\n            \"--workspace-pools-size-hint-bytes=sram:1024\",\n            \"--workspace-pools-clock-frequency-hz=sram:4000000\",\n            \"--workspace-pools-clock-frequency-hz=flash:2000000\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=sram:8\",\n            \"--workspace-pools-read-bandwidth-bytes-per-cycle=flash:4\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=sram:4\",\n            \"--workspace-pools-write-bandwidth-bytes-per-cycle=flash:1\",\n            \"--workspace-pools-read-latency-cycles=sram:250\",\n            \"--workspace-pools-read-latency-cycles=flash:2000\",\n            \"--workspace-pools-write-latency-cycles=flash:1000\",\n            \"--workspace-pools-write-latency-cycles=sram:500\",\n            \"--workspace-pools-target-burst-bytes=sram:c:8\",\n            \"--workspace-pools-target-burst-bytes=flash:c:4\",\n        ]\n    )\n\n    targets = [Target(\"c\")]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n    assert len(memory_pools.pools) == 2\n\n    assert memory_pools.pools[0].pool_name == \"sram\"\n    assert memory_pools.pools[0].size_hint_bytes == 1024\n    assert memory_pools.pools[0].write_latency_cycles == 500\n\n    assert memory_pools.pools[1].pool_name == \"flash\"\n    assert memory_pools.pools[1].size_hint_bytes == 2048\n    assert memory_pools.pools[1].write_latency_cycles == 1000\n\n\ndef test_workspace_pools_recombobulate_multi_target():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:c,llvm\",\n            \"--workspace-pools-target-burst-bytes=sram:c:8\",\n            \"--workspace-pools-target-burst-bytes=sram:llvm:4\",\n        ]\n    )\n\n    c_target = Target(\"c\")\n    llvm_target = Target(\"llvm\")\n    extra_targets = []\n\n    targets = [c_target, llvm_target]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, extra_targets)\n\n    assert len(memory_pools.pools) == 1\n\n    assert len(memory_pools.pools[0].target_burst_bytes) == 2\n    assert memory_pools.pools[0].target_burst_bytes[c_target] == 8\n    assert memory_pools.pools[0].target_burst_bytes[llvm_target] == 4\n\n\ndef test_workspace_pools_recombobulate_no_target_burst_bytes():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-target-burst-bytes=sram:c:8\",\n        ]\n    )\n\n    c_target = Target(\"c\")\n    targets = [c_target]\n\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n\n    assert len(memory_pools.pools) == 1\n    assert len(memory_pools.pools[0].target_burst_bytes) == 1\n    assert memory_pools.pools[0].target_burst_bytes[c_target] == 8\n\n\ndef test_workspace_pools_recombobulate_missing_target():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n        ]\n    )\n\n    c_target = Target(\"c\")\n    with pytest.raises(TVMCException):\n        workspace_pools_recombobulate(parsed, [c_target], _)\n\n\ndef test_workspace_pools_recombobulate_multi_target_multi_pool():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:c,llvm\",\n            \"--workspace-pools-target-burst-bytes=sram:c:8\",\n            \"--workspace-pools-target-burst-bytes=sram:llvm:4\",\n        ]\n    )\n\n    c_target = Target(\"c\")\n    llvm_target = Target(\"llvm\")\n\n    targets = [c_target, llvm_target]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n\n    assert len(memory_pools.pools) == 1\n\n    assert len(memory_pools.pools[0].target_burst_bytes) == 2\n    assert memory_pools.pools[0].target_burst_bytes[llvm_target] == 4\n    assert memory_pools.pools[0].target_burst_bytes[c_target] == 8\n\n\ndef test_workspace_pools_recombobulate_parameter_overrides():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-size-hint-bytes=sram:800\",\n            \"--workspace-pools-size-hint-bytes=sram:400\",\n            \"--workspace-pools-clock-frequency-hz=sram:4000000\",\n            \"--workspace-pools-clock-frequency-hz=sram:3600000\",\n        ]\n    )\n\n    c_target = Target(\"c\")\n\n    targets = [c_target]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n\n    assert len(memory_pools.pools) == 1\n\n    assert memory_pools.pools[0].size_hint_bytes == 400\n    assert memory_pools.pools[0].clock_frequency_hz == 3600000\n\n\ndef test_workspace_pools_recombobulate_single_pool_overrides():\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args(\n        [\n            \"--workspace-pools=sram,flash\",\n            \"--workspace-pools-targets=sram:c\",\n            \"--workspace-pools-targets=flash:c\",\n            \"--workspace-pools-targets=sram:c,llvm\",  # Override on one pool\n            \"--workspace-pools-size-hint-bytes=sram:800\",\n            \"--workspace-pools-size-hint-bytes=flash:1200\",\n            \"--workspace-pools-size-hint-bytes=sram:400\",  # Override on one pool\n        ]\n    )\n\n    c_target = Target(\"c\")\n    llvm_target = Target(\"llvm\")\n\n    targets = [c_target, llvm_target]\n    memory_pools = workspace_pools_recombobulate(parsed, targets, _)\n\n    assert len(memory_pools.pools) == 2\n\n    assert memory_pools.pools[0].size_hint_bytes == 400\n    assert memory_pools.pools[1].size_hint_bytes == 1200\n\n    assert len(memory_pools.pools[0].targets) == 2\n    assert len(memory_pools.pools[1].targets) == 1\n\n\n@tvm.testing.requires_ethosn\ndef test_workspace_pools_recombobulate_ext_codegen():\n    \"\"\"No error should occur when using an external code generator without an attached Target\"\"\"\n\n    parser = argparse.ArgumentParser()\n    generate_workspace_pools_args(parser)\n    parsed, _ = parser.parse_known_args([])\n\n    targets = [Target(\"llvm\")]\n    extra_targets = [{\"raw\": \"ethos-n\"}]\n\n    memory_pools = workspace_pools_recombobulate(parsed, targets, extra_targets)\n    assert memory_pools is None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/caffe/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, unspecified-encoding\n\"\"\"\nCaffe testcases\n====================\nThis article is a test script to test Caffe operator with Relay.\n\"\"\"\nimport os\nimport logging\nimport numpy as np\nimport pytest\n\nfrom google.protobuf import text_format\nimport caffe\nfrom caffe import layers as L, params as P\nfrom caffe.proto import caffe_pb2 as pb\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.download import download_testdata\n\nos.environ[\"GLOG_minloglevel\"] = \"2\"\n\nlogging.basicConfig(level=logging.ERROR)\n\nCURRENT_DIR = os.path.join(os.path.expanduser(\"~\"), \".tvm_test_data\", \"caffe_test\")\n\n#######################################################################\n# Generic functions for TVM & Caffe\n# ------------------------------------------\n\n\ndef _create_dir(d_path):\n    \"\"\"If the directory is not existed, create it\"\"\"\n    if not (os.path.exists(d_path) and os.path.isdir(d_path)):\n        os.makedirs(d_path)\n\n\ndef _list_to_str(ll):\n    \"\"\"Convert list or tuple to str, separated by underline.\"\"\"\n    if isinstance(ll, (tuple, list)):\n        tmp = [str(i) for i in ll]\n        res = \"_\".join(tmp)\n    return res\n\n\ndef _gen_filename_str(op_name, data_shape, *args, **kwargs):\n    \"\"\"Combining the filename according to the op_name, shape and other args.\"\"\"\n    file_dir = os.path.join(CURRENT_DIR, op_name)\n    _create_dir(file_dir)\n    res = op_name + \"_\"\n    shape_str = _list_to_str(list(data_shape))\n    res += shape_str\n    for arg in args:\n        if isinstance(arg, (tuple, list)):\n            res += \"_\" + _list_to_str(arg)\n        elif isinstance(arg, (int, float, str)):\n            res += \"_\" + str(arg)\n    for _, v in kwargs.items():\n        if isinstance(v, (tuple, list)):\n            res += \"_\" + _list_to_str(v)\n        elif isinstance(v, (int, float, str)):\n            res += \"_\" + str(v)\n    res = res.replace(\".\", \"_\")\n    res = res.replace(\"-\", \"_\")\n    proto_file = os.path.join(file_dir, res + \".prototxt\")\n    blob_file = os.path.join(file_dir, res + \".caffemodel\")\n    solver_file = os.path.join(file_dir, res + \"_solver.prototxt\")\n\n    return (proto_file, blob_file, solver_file)\n\n\ndef _save_prototxt(n_netspec, f_path):\n    \"\"\"Generate .prototxt file according to caffe.NetSpec\"\"\"\n    s = n_netspec.to_proto()\n    with open(f_path, \"w\") as f:\n        f.write(str(s))\n\n\ndef _save_solver(solver_file, proto_file, blob_file):\n    \"\"\"Define a solver proto, you can change the configs.\"\"\"\n    blob_file_prefix = blob_file.split(\".caffemodel\")[0]\n    s = pb.SolverParameter()\n    s.train_net = proto_file\n    s.base_lr = 0.01\n    s.momentum = 0.9\n    s.weight_decay = 0.0005\n    s.lr_policy = \"inv\"\n    s.gamma = 0.0001\n    s.power = 0.75\n    s.display = 1\n    s.max_iter = 100000\n    s.snapshot = 100000\n    s.snapshot_prefix = blob_file_prefix\n\n    with open(solver_file, \"w\") as f:\n        f.write(str(s))\n\n\ndef _save_caffemodel(solver_file, blob_file):\n    \"\"\"Generate .caffemodel file.\"\"\"\n    solver = caffe.SGDSolver(solver_file)\n    solver.net.save(blob_file)\n\n\ndef _gen_model_files(n_netspec, proto_file, blob_file, solver_file):\n    _save_prototxt(n_netspec, proto_file)\n    _save_solver(solver_file, proto_file, blob_file)\n    _save_caffemodel(solver_file, blob_file)\n\n\ndef _siso_op(data, func, *args, **kwargs):\n    \"\"\"Create single input and single output Caffe op\"\"\"\n    n = caffe.NetSpec()\n    n.data = L.Input(input_param={\"shape\": {\"dim\": list(data.shape)}})\n    n.output = func(n.data, *args, **kwargs)\n    return n\n\n\ndef _miso_op(data_list, func, *args, **kwargs):\n    \"\"\"Create multi input and single output Caffe op\"\"\"\n    n = caffe.NetSpec()\n    if not isinstance(data_list, (tuple, list)):\n        raise TypeError(f\"Need tuple or list but get {type(data_list)}\")\n    input_list = []\n    for idx, data in enumerate(data_list):\n        n[\"data\" + str(idx)] = L.Input(input_param={\"shape\": {\"dim\": list(data.shape)}})\n        input_list.append(n[\"data\" + str(idx)])\n    n.output = func(*input_list, *args, **kwargs)\n    return n\n\n\ndef _simo_op(data, func, *args, **kwargs):\n    \"\"\"Create single input and multi output Caffe op\"\"\"\n    n = caffe.NetSpec()\n    n.data = L.Input(input_param={\"shape\": {\"dim\": list(data.shape)}})\n    output_list = func(n.data, *args, **kwargs)\n    for idx, out in enumerate(output_list):\n        n[\"output\" + str(idx)] = out\n    return n\n\n\ndef _run_caffe(data, proto_file, blob_file):\n    \"\"\"Run caffe model by Caffe according to .caffemodel and .prototxt\"\"\"\n    net = caffe.Net(proto_file, blob_file, caffe.TEST)\n    if isinstance(data, (list, tuple)):\n        for idx, d in enumerate(data):\n            net.blobs[\"data\" + str(idx)].data[...] = d\n    else:\n        net.blobs[\"data\"].data[...] = data\n    out = net.forward()\n\n    caffe_output = []\n    for i in range(len(out.keys())):\n        if \"output\" + str(i) not in out.keys():\n            caffe_output.clear()\n            return list(out.values())\n        caffe_output.append(out[\"output\" + str(i)])\n    return caffe_output\n\n\ndef _run_tvm(data, proto_file, blob_file):\n    \"\"\"Run caffe model by TVM according to .caffemodel and .prototxt\"\"\"\n    init_net = pb.NetParameter()\n    predict_net = pb.NetParameter()\n\n    # load model\n    with open(proto_file, \"r\") as f:\n        text_format.Merge(f.read(), predict_net)\n    # load blob\n    with open(blob_file, \"rb\") as f:\n        init_net.ParseFromString(f.read())\n\n    shape_dict = {}\n    dtype_dict = {}\n    if isinstance(data, (tuple, list)):\n        for idx, d in enumerate(data):\n            shape_dict[\"data\" + str(idx)] = d.shape\n            dtype_dict[\"data\" + str(idx)] = \"float32\"\n    else:\n        shape_dict = {\"data\": data.shape}\n        dtype_dict = {\"data\": \"float32\"}\n\n    mod, params = relay.frontend.from_caffe(init_net, predict_net, shape_dict, dtype_dict)\n\n    target = \"llvm\"\n\n    dev = tvm.cpu(0)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, params=params)\n    dtype = \"float32\"\n    m = graph_executor.GraphModule(lib[\"default\"](dev))\n    if isinstance(data, (tuple, list)):\n        for idx, d in enumerate(data):\n            m.set_input(\"data\" + str(idx), tvm.nd.array(d.astype(dtype)))\n    else:\n        m.set_input(\"data\", tvm.nd.array(data.astype(dtype)))\n    # execute\n    m.run()\n    tvm_output = []\n    # get outputs\n    for i in range(m.get_num_outputs()):\n        tvm_output.append(m.get_output(i).numpy())\n    return tvm_output\n\n\ndef _compare_caffe_tvm(caffe_out, tvm_out, is_network=False):\n    for i, _ in enumerate(caffe_out):\n        if is_network:\n            caffe_out[i] = caffe_out[i][:1]\n        tvm.testing.assert_allclose(caffe_out[i], tvm_out[i], rtol=1e-5, atol=1e-5)\n\n\ndef _test_op(data, func_op, op_name, **kwargs):\n    \"\"\"Single op testing pipline.\"\"\"\n    shape_list = []\n    if isinstance(data, (list, tuple)):\n        n = _miso_op(data, func_op, **kwargs)\n        for d in data:\n            shape_list.extend(list(d.shape))\n    else:\n        output_num = 1\n        if \"ntop\" in kwargs:\n            output_num = kwargs[\"ntop\"]\n        if output_num == 1:\n            n = _siso_op(data, func_op, **kwargs)\n        else:\n            n = _simo_op(data, func_op, **kwargs)\n        shape_list = list(data.shape)\n\n    # obtain the .caffemodel file and .prototxt file\n    (proto_file, blob_file, solver_file) = _gen_filename_str(op_name, shape_list, **kwargs)\n    _gen_model_files(n, proto_file, blob_file, solver_file)\n    # run model in Caffe\n    caffe_out = _run_caffe(data, proto_file, blob_file)\n    # run model in TVM\n    tvm_out = _run_tvm(data, proto_file, blob_file)\n    _compare_caffe_tvm(caffe_out, tvm_out)\n\n\ndef _test_network(data, proto_file, blob_file):\n    # run model in Caffe\n    caffe_out = _run_caffe(data, proto_file, blob_file)\n    # run model in TVM\n    tvm_out = _run_tvm(data, proto_file, blob_file)\n    _compare_caffe_tvm(caffe_out, tvm_out, is_network=True)\n\n\n#######################################################################\n# BatchNorm\n# -----------\n\n\ndef _test_batchnorm(data, moving_average_fraction=0.999, eps=1e-5):\n    \"\"\"One iteration of BatchNorm\"\"\"\n    _test_op(\n        data, L.BatchNorm, \"BatchNorm\", moving_average_fraction=moving_average_fraction, eps=eps\n    )\n\n\ndef test_forward_BatchNorm():\n    \"\"\"BatchNorm\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_batchnorm(data)\n    _test_batchnorm(data, moving_average_fraction=0.88, eps=1e-4)\n\n\n#######################################################################\n# Concat\n# -----------\n\n\ndef _test_concat(data_list, axis=1):\n    \"\"\"One iteration of Concat\"\"\"\n    _test_op(data_list, L.Concat, \"Concat\", axis=axis)\n\n\ndef test_forward_Concat():\n    \"\"\"Concat\"\"\"\n    _test_concat([np.random.rand(1, 3, 10, 10), np.random.rand(1, 2, 10, 10)], axis=1)\n    _test_concat([np.random.rand(3, 10, 10), np.random.rand(2, 10, 10)], axis=0)\n    _test_concat([np.random.rand(3, 10), np.random.rand(2, 10)], axis=0)\n\n\n#######################################################################\n# Convolution\n# -----------\n\n\ndef _test_convolution(data, **kwargs):\n    \"\"\"One iteration of Convolution\"\"\"\n    _test_op(data, L.Convolution, \"Convolution\", **kwargs)\n\n\ndef test_forward_Convolution():\n    \"\"\"Convolution\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_convolution(\n        data,\n        num_output=20,\n        bias_term=True,\n        pad=0,\n        kernel_size=3,\n        stride=2,\n        dilation=1,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_convolution(\n        data,\n        num_output=20,\n        bias_term=False,\n        pad=[1, 2],\n        kernel_size=3,\n        stride=2,\n        dilation=1,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_convolution(\n        data,\n        num_output=20,\n        bias_term=True,\n        pad=[1, 2],\n        kernel_size=[3, 5],\n        stride=[2, 1],\n        dilation=[1, 2],\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_convolution(\n        np.random.rand(1, 2, 10, 10).astype(np.float32),\n        num_output=20,\n        bias_term=True,\n        pad=[1, 2],\n        kernel_size=[3, 5],\n        stride=[2, 1],\n        dilation=[1, 2],\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n        group=2,\n    )\n    _test_convolution(\n        data,\n        num_output=20,\n        bias_term=True,\n        pad_h=1,\n        pad_w=2,\n        kernel_h=3,\n        kernel_w=5,\n        stride_h=2,\n        stride_w=1,\n        dilation=[1, 2],\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n\n\n#######################################################################\n# Crop\n# -----------\n\n\ndef _test_crop(data, **kwargs):\n    \"\"\"One iteration of Crop\"\"\"\n    _test_op(data, L.Crop, \"Crop\", **kwargs)\n\n\ndef test_forward_Crop():\n    \"\"\"Crop\"\"\"\n    _test_crop([np.random.rand(10, 10, 120, 120), np.random.rand(10, 5, 50, 60)])\n    _test_crop([np.random.rand(10, 10, 120, 120), np.random.rand(10, 5, 50, 60)], axis=1)\n    _test_crop([np.random.rand(10, 10, 120, 120), np.random.rand(10, 5, 50, 60)], axis=1, offset=2)\n    _test_crop(\n        [np.random.rand(10, 10, 120, 120), np.random.rand(10, 5, 50, 60)], axis=1, offset=[1, 2, 4]\n    )\n    _test_crop(\n        [np.random.rand(10, 10, 120, 120), np.random.rand(10, 5, 50, 60)], axis=2, offset=[2, 4]\n    )\n    _test_crop([np.random.rand(10, 120, 120), np.random.rand(5, 50, 60)], axis=1, offset=[2, 4])\n    _test_crop([np.random.rand(120, 120), np.random.rand(50, 60)], axis=0, offset=[2, 4])\n\n\n#######################################################################\n# Deconvolution\n# -----------\n\n\ndef _test_deconvolution(data, **kwargs):\n    \"\"\"One iteration of Deconvolution\"\"\"\n    _test_op(data, L.Deconvolution, \"Deconvolution\", **kwargs)\n\n\ndef test_forward_Deconvolution():\n    \"\"\"Deconvolution\"\"\"\n    data = np.random.rand(1, 16, 32, 32).astype(np.float32)\n    _test_deconvolution(\n        data,\n        convolution_param=dict(\n            num_output=20,\n            bias_term=True,\n            pad=0,\n            kernel_size=3,\n            stride=2,\n            dilation=1,\n            weight_filler=dict(type=\"xavier\"),\n            bias_filler=dict(type=\"xavier\"),\n        ),\n    )\n    _test_deconvolution(\n        data,\n        convolution_param=dict(\n            num_output=20,\n            bias_term=False,\n            pad=[1, 2],\n            kernel_size=3,\n            stride=2,\n            dilation=1,\n            weight_filler=dict(type=\"xavier\"),\n            bias_filler=dict(type=\"xavier\"),\n        ),\n    )\n    _test_deconvolution(\n        data,\n        convolution_param=dict(\n            num_output=20,\n            bias_term=True,\n            pad_h=1,\n            pad_w=2,\n            kernel_h=3,\n            kernel_w=5,\n            stride_h=2,\n            stride_w=1,\n            dilation=1,\n            weight_filler=dict(type=\"xavier\"),\n            bias_filler=dict(type=\"xavier\"),\n        ),\n    )\n    _test_deconvolution(\n        data,\n        convolution_param=dict(\n            num_output=16,\n            bias_term=False,\n            pad=0,\n            kernel_size=2,\n            stride=2,\n            dilation=1,\n            group=16,\n            weight_filler=dict(type=\"xavier\"),\n            bias_filler=dict(type=\"xavier\"),\n        ),\n    )\n    data = np.random.rand(1, 100, 32, 32).astype(np.float32)\n    _test_deconvolution(\n        data,\n        convolution_param=dict(\n            num_output=100,\n            bias_term=False,\n            pad=0,\n            kernel_size=2,\n            stride=2,\n            dilation=1,\n            group=100,\n            weight_filler=dict(type=\"xavier\"),\n            bias_filler=dict(type=\"xavier\"),\n        ),\n    )\n\n\n#######################################################################\n# Dropout\n# -----------\n\n\ndef _test_dropout(data, **kwargs):\n    \"\"\"One iteration of Dropout\"\"\"\n    _test_op(data, L.Dropout, \"Dropout\", **kwargs)\n\n\ndef test_forward_Dropout():\n    \"\"\"Dropout\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_dropout(data)\n    _test_dropout(data, dropout_ratio=0.7)\n\n\n#######################################################################\n# Eltwise\n# -----------\n\n\ndef _test_eltwise(data_list, **kwargs):\n    \"\"\"One iteration of Eltwise\"\"\"\n    _test_op(data_list, L.Eltwise, \"Eltwise\", **kwargs)\n\n\ndef test_forward_Eltwise():\n    \"\"\"Eltwise\"\"\"\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=0,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=1,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=2,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=1,\n        coeff=[0.5, 1],\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=0,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=1,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=2,\n    )\n    _test_eltwise(\n        [\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n            np.random.rand(1, 3, 10, 11).astype(np.float32),\n        ],\n        operation=1,\n        coeff=[0.5, 1, 0.2, 1.8, 3.1, 0.1],\n    )\n\n\n#######################################################################\n# Flatten\n# -----------\n\n\ndef _test_flatten(data, axis=1):\n    \"\"\"One iteration of Flatten\"\"\"\n    _test_op(data, L.Flatten, \"Flatten\", axis=axis)\n\n\ndef test_forward_Flatten():\n    \"\"\"Flatten\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_flatten(data)\n    _test_flatten(data, axis=1)\n\n\n#######################################################################\n# Flatten\n# -----------\n\n\ndef _test_inner_product(data, **kwargs):\n    \"\"\"One iteration of InnerProduct\"\"\"\n    _test_op(data, L.InnerProduct, \"InnerProduct\", **kwargs)\n\n\ndef test_forward_InnerProduct():\n    \"\"\"InnerProduct\"\"\"\n    data = np.random.rand(1, 3, 10, 10)\n    _test_inner_product(data, num_output=20, bias_term=False, weight_filler=dict(type=\"xavier\"))\n    _test_inner_product(\n        data,\n        num_output=20,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_inner_product(\n        np.random.rand(20, 10).astype(np.float32),\n        num_output=30,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n\n\n#######################################################################\n# LRN\n# -----------\n\n\ndef _test_lrn(data, local_size=5, alpha=1.0, beta=0.75, k=1.0):\n    \"\"\"One iteration of LRN\"\"\"\n    _test_op(data, L.LRN, \"LRN\", local_size=local_size, alpha=alpha, beta=beta, k=k)\n\n\ndef test_forward_LRN():\n    \"\"\"LRN\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_lrn(data)\n    _test_lrn(data, local_size=3)\n    _test_lrn(data, local_size=3, alpha=2.0)\n    _test_lrn(\n        data,\n        local_size=3,\n        alpha=2.0,\n        beta=0.5,\n    )\n    _test_lrn(data, local_size=3, alpha=2.0, beta=0.5, k=2.0)\n\n\n#######################################################################\n# Permute\n# -------\n\n\ndef _test_permute(data, **kwargs):\n    \"\"\"One iteration of Permute.\"\"\"\n    _test_op(data, L.Permute, \"Permute\", **kwargs)\n\n\ndef test_forward_Permute():\n    \"\"\"Permute\"\"\"\n    data = np.random.rand(2, 3, 4).astype(np.float32)\n    _test_permute(data, permute_param={\"order\": [0, 1, 2]})\n    _test_permute(data, permute_param={\"order\": [0, 2, 1]})\n    _test_permute(data, permute_param={\"order\": [1, 0, 2]})\n    _test_permute(data, permute_param={\"order\": [1, 2, 0]})\n    _test_permute(data, permute_param={\"order\": [2, 0, 1]})\n    _test_permute(data, permute_param={\"order\": [2, 1, 0]})\n\n\n#######################################################################\n# Pooling\n# -----------\n\n\ndef _test_pooling(data, **kwargs):\n    \"\"\"One iteration of Pooling.\"\"\"\n    _test_op(data, L.Pooling, \"Pooling\", **kwargs)\n\n\ndef test_forward_Pooling():\n    \"\"\"Pooing\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    # MAX Pooling\n    _test_pooling(data, kernel_size=2, stride=2, pad=0, pool=P.Pooling.MAX)\n    _test_pooling(\n        data, kernel_h=2, kernel_w=3, stride_h=2, stride_w=1, pad_h=1, pad_w=2, pool=P.Pooling.MAX\n    )\n    _test_pooling(data, pool=P.Pooling.MAX, global_pooling=True)\n\n    # AVE Pooing\n    _test_pooling(data, kernel_size=2, stride=2, pad=0, pool=P.Pooling.AVE)\n    _test_pooling(\n        data, kernel_h=2, kernel_w=3, stride_h=2, stride_w=1, pad_h=1, pad_w=2, pool=P.Pooling.AVE\n    )\n    _test_pooling(data, pool=P.Pooling.AVE, global_pooling=True)\n\n\n#######################################################################\n# Power\n# -----\ndef _test_power(data, **kwargs):\n    \"\"\"One iteration of Power.\"\"\"\n    _test_op(data, L.Power, \"Power\", **kwargs)\n\n\ndef test_forward_Power():\n    \"\"\"Power\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_power(data, power_param={\"power\": 0.37, \"scale\": 0.83, \"shift\": -2.4})\n    _test_power(data, power_param={\"power\": 0.37, \"scale\": 0.83, \"shift\": 0.0})\n    _test_power(data, power_param={\"power\": 0.0, \"scale\": 0.83, \"shift\": -2.4})\n    _test_power(data, power_param={\"power\": 1.0, \"scale\": 0.83, \"shift\": -2.4})\n    _test_power(data, power_param={\"power\": 2.0, \"scale\": 0.34, \"shift\": -2.4})\n    _test_power(data, power_param={\"power\": 1.0, \"scale\": 1.0, \"shift\": 0.0})\n\n\n#######################################################################\n# PReLU\n# -----------\n\n\ndef _test_prelu(data, **kwargs):\n    \"\"\"One iteration of PReLU.\"\"\"\n    _test_op(data, L.PReLU, \"PReLU\", **kwargs)\n\n\ndef test_forward_PReLU():\n    \"\"\"PReLU\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_prelu(data, filler=dict(type=\"constant\", value=0.5))\n    _test_prelu(data)\n    _test_prelu(np.random.rand(10, 20).astype(np.float32))\n\n\n#######################################################################\n# ReLU\n# -----------\n\n\ndef _test_relu(data, **kwargs):\n    \"\"\"One iteration of ReLU.\"\"\"\n    _test_op(data, L.ReLU, \"ReLU\", **kwargs)\n\n\ndef test_forward_ReLU():\n    \"\"\"ReLU\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_relu(data)\n    _test_relu(np.random.rand(10, 20).astype(np.float32))\n\n\n#######################################################################\n# Reshape\n# -----------\n\n\ndef _test_reshape(data, **kwargs):\n    \"\"\"One iteration of Reshape.\"\"\"\n    _test_op(data, L.Reshape, \"Reshape\", **kwargs)\n\n\ndef test_forward_Reshape():\n    \"\"\"Reshape\"\"\"\n    data = np.random.rand(1, 8, 6).astype(np.float32)\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [4, 3, 4]}})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [2, 0, 3]}})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [2, 0, -1]}})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [0, -1]}})\n\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [2, 3]}, \"axis\": 2})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [4, 3, 4]}, \"axis\": 1})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [4, 3, 4]}, \"axis\": -3})\n\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [2, 4]}, \"axis\": 1, \"num_axes\": 1})\n    _test_reshape(data, reshape_param={\"shape\": {\"dim\": [3, 16]}, \"axis\": 1, \"num_axes\": 2})\n\n\n#######################################################################\n# Scale\n# -----------\n\n\ndef _test_scale(data, **kwargs):\n    \"\"\"One iteration of Scale.\"\"\"\n    _test_op(data, L.Scale, \"Scale\", **kwargs)\n\n\ndef test_forward_Scale():\n    \"\"\"Scale\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_scale(data, filler=dict(type=\"xavier\"))\n    _test_scale(data, filler=dict(type=\"xavier\"), bias_term=True, bias_filler=dict(type=\"xavier\"))\n\n\n#######################################################################\n# Sigmoid\n# -----------\n\n\ndef _test_sigmoid(data, **kwargs):\n    \"\"\"One iteration of Sigmoid.\"\"\"\n    _test_op(data, L.Sigmoid, \"Sigmoid\", **kwargs)\n\n\ndef test_forward_Sigmoid():\n    \"\"\"Sigmoid\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_sigmoid(data)\n\n\n#######################################################################\n# Slice\n# -----------\n\n\ndef _test_slice(data, **kwargs):\n    \"\"\"One iteration of Slice\"\"\"\n    _test_op(data, L.Slice, \"Slice\", **kwargs)\n\n\ndef test_forward_Slice():\n    \"\"\"Slice\"\"\"\n    data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n    _test_slice(data, ntop=2, slice_param=dict(axis=1, slice_point=[1]))\n    _test_slice(data, ntop=2, slice_param=dict(axis=-1, slice_point=[1]))\n    _test_slice(data, ntop=3, slice_param=dict(axis=2, slice_point=[1, 6]))\n    _test_slice(data, ntop=3)\n\n\n#######################################################################\n# Softmax\n# -----------\n\n\ndef _test_softmax(data, **kwargs):\n    \"\"\"One iteration of Softmax\"\"\"\n    _test_op(data, L.Softmax, \"Softmax\", **kwargs)\n\n\ndef test_forward_Softmax():\n    \"\"\"Softmax\"\"\"\n    _test_softmax(np.random.rand(1, 3, 10, 10).astype(np.float32))\n    _test_softmax(np.random.rand(1, 3, 10, 10).astype(np.float32), axis=2)\n    _test_softmax(np.random.rand(10, 10).astype(np.float32), axis=0)\n    _test_softmax(np.random.rand(2, 10, 10).astype(np.float32), axis=1)\n\n\n#######################################################################\n# TanH\n# -----------\n\n\ndef _test_tanh(data, **kwargs):\n    \"\"\"One iteration of TanH\"\"\"\n    _test_op(data, L.TanH, \"TanH\", **kwargs)\n\n\ndef test_forward_TanH():\n    \"\"\"TanH\"\"\"\n    _test_tanh(np.random.rand(1, 3, 10, 10).astype(np.float32))\n    _test_tanh(np.random.rand(3, 10, 10).astype(np.float32))\n    _test_tanh(np.random.rand(10, 10).astype(np.float32))\n    _test_tanh(np.random.rand(10).astype(np.float32))\n\n\n#######################################################################\n# Reduction\n# -----------\n\n\ndef _test_reduction(data, **kwargs):\n    \"\"\"One iteration of Reduction\"\"\"\n    _test_op(data, L.Reduction, \"Reduction\", **kwargs)\n\n\ndef test_forward_Reduction():\n    \"\"\"Reduction\"\"\"\n    reduction_op = {\"SUM\": 1, \"ASUM\": 2, \"SUMSQ\": 3, \"MEAN\": 4}\n    _test_reduction(np.random.rand(10).astype(np.float32), operation=reduction_op[\"SUM\"], axis=0)\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32), operation=reduction_op[\"SUM\"], axis=3\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32), operation=reduction_op[\"SUM\"], axis=1\n    )\n    _test_reduction(\n        np.random.rand(10).astype(np.float32), operation=reduction_op[\"SUM\"], axis=0, coeff=0.5\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32),\n        operation=reduction_op[\"SUM\"],\n        axis=3,\n        coeff=5.0,\n    )\n    _test_reduction(np.random.rand(10).astype(np.float32), operation=reduction_op[\"ASUM\"])\n    _test_reduction(\n        np.random.rand(10, 20).astype(np.float32), operation=reduction_op[\"ASUM\"], axis=1\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32), operation=reduction_op[\"ASUM\"], axis=3\n    )\n    _test_reduction(\n        np.random.rand(10).astype(np.float32), operation=reduction_op[\"ASUM\"], axis=0, coeff=0.0\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30).astype(np.float32),\n        operation=reduction_op[\"ASUM\"],\n        axis=2,\n        coeff=7.0,\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40, 10).astype(np.float32),\n        operation=reduction_op[\"ASUM\"],\n        axis=3,\n        coeff=1.0,\n    )\n    _test_reduction(np.random.rand(10).astype(np.float32), operation=reduction_op[\"SUMSQ\"], axis=0)\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32), operation=reduction_op[\"SUMSQ\"], axis=3\n    )\n    _test_reduction(\n        np.random.rand(10).astype(np.float32), operation=reduction_op[\"SUMSQ\"], axis=0, coeff=0.0\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40, 50).astype(np.float32),\n        operation=reduction_op[\"SUMSQ\"],\n        axis=4,\n        coeff=2.0,\n    )\n    _test_reduction(np.random.rand(10).astype(np.float32), operation=reduction_op[\"MEAN\"], axis=0)\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32), operation=reduction_op[\"MEAN\"], axis=3\n    )\n    _test_reduction(\n        np.random.rand(10).astype(np.float32), operation=reduction_op[\"MEAN\"], axis=0, coeff=0.0\n    )\n    _test_reduction(\n        np.random.rand(10, 20, 30, 40).astype(np.float32),\n        operation=reduction_op[\"MEAN\"],\n        axis=3,\n        coeff=2.0,\n    )\n\n\n#######################################################################\n# Embed\n# -----------\n\n\ndef _test_embed(data, **kwargs):\n    \"\"\"One iteration of Embed\"\"\"\n    _test_op(data, L.Embed, \"Embed\", **kwargs)\n\n\ndef test_forward_Embed():\n    \"\"\"Embed\"\"\"\n    k = 20\n    data = list(i for i in range(k))\n    np.random.shuffle(data)\n    # dimension is 1\n    data = np.asarray(data)\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=False,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    # dimension is 2\n    data = np.reshape(data, [4, 5])\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=False,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    # dimension is 3\n    data = np.reshape(data, [2, 2, 5])\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=False,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    # dimension is 4\n    data = np.reshape(data, [2, 2, 5, 1])\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=True,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n    _test_embed(\n        data,\n        num_output=30,\n        input_dim=k,\n        bias_term=False,\n        weight_filler=dict(type=\"xavier\"),\n        bias_filler=dict(type=\"xavier\"),\n    )\n\n\n#######################################################################\n# Mobilenetv2\n# -----------\n\n\ndef _test_mobilenetv2(data):\n    \"\"\"One iteration of Mobilenetv2\"\"\"\n    mean_val = np.array([103.939, 116.779, 123.68], dtype=np.float32)\n    mean_val = np.reshape(mean_val, (1, 3, 1, 1))\n    mean_val = np.tile(mean_val, (1, 1, 224, 224))\n    data_process = data - mean_val\n    data_process = data_process / 58.8\n    data_process = data_process.astype(np.float32)\n\n    proto_file_url = (\n        \"https://github.com/shicai/MobileNet-Caffe/raw/master/mobilenet_v2_deploy.prototxt\"\n    )\n    blob_file_url = (\n        \"https://github.com/shicai/MobileNet-Caffe/blob/master/mobilenet_v2.caffemodel?raw=true\"\n    )\n    proto_file = download_testdata(proto_file_url, \"mobilenetv2.prototxt\", module=\"model\")\n    blob_file = download_testdata(blob_file_url, \"mobilenetv2.caffemodel\", module=\"model\")\n    _test_network(data_process, proto_file, blob_file)\n\n\ndef test_forward_Mobilenetv2():\n    \"\"\"Mobilenetv2\"\"\"\n    data = np.random.randint(0, 256, size=(1, 3, 224, 224)).astype(np.float32)\n    _test_mobilenetv2(data)\n\n\n#######################################################################\n# Alexnet\n# -----------\n\n\ndef _test_alexnet(data):\n    \"\"\"One iteration of Alexnet\"\"\"\n    mean_val = np.array([103.939, 116.779, 123.68], dtype=np.float32)\n    mean_val = np.reshape(mean_val, (1, 3, 1, 1))\n    mean_val = np.tile(mean_val, (1, 1, 227, 227))\n    data_process = data - mean_val\n    data_process = data_process.astype(np.float32)\n\n    proto_file_url = (\n        \"https://github.com/BVLC/caffe/raw/master/models/\" + \"bvlc_alexnet/deploy.prototxt\"\n    )\n    blob_file_url = \"http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel\"\n    proto_file = download_testdata(proto_file_url, \"alexnet.prototxt\", module=\"model\")\n    blob_file = download_testdata(blob_file_url, \"alexnet.caffemodel\", module=\"model\")\n    _test_network(data_process, proto_file, blob_file)\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/13227\")\ndef test_forward_Alexnet():\n    \"\"\"Alexnet\"\"\"\n    data = np.random.randint(0, 256, size=(1, 3, 227, 227)).astype(np.float32)\n    _test_alexnet(data)\n\n\n#######################################################################\n# Resnet50\n# -----------\n\n\ndef _test_resnet50(data):\n    \"\"\"One iteration of Resnet50\"\"\"\n    mean_val = np.array([103.939, 116.779, 123.68], dtype=np.float32)\n    mean_val = np.reshape(mean_val, (1, 3, 1, 1))\n    mean_val = np.tile(mean_val, (1, 1, 224, 224))\n    data_process = data - mean_val\n    data_process = data_process.astype(np.float32)\n\n    proto_file_url = (\n        \"https://github.com/fernchen/CaffeModels/raw/master/resnet/ResNet-50-deploy.prototxt\"\n    )\n    blob_file_url = (\n        \"https://github.com/fernchen/CaffeModels/raw/master/resnet/ResNet-50-model.caffemodel\"\n    )\n\n    proto_file = download_testdata(proto_file_url, \"resnet50.prototxt\", module=\"model\")\n    blob_file = download_testdata(blob_file_url, \"resnet50.caffemodel\", module=\"model\")\n\n    _test_network(data_process, proto_file, blob_file)\n\n\ndef test_forward_Resnet50():\n    \"\"\"Resnet50\"\"\"\n    data = np.random.randint(0, 256, size=(1, 3, 224, 224)).astype(np.float32)\n    _test_resnet50(data)\n\n\n#######################################################################\n# Inceptionv4\n# -----------\n\n\ndef _test_inceptionv1(data):\n    \"\"\"One iteration of Inceptionv4\"\"\"\n    mean_val = np.array([103.939, 116.779, 123.68], dtype=np.float32)\n    mean_val = np.reshape(mean_val, (1, 3, 1, 1))\n    mean_val = np.tile(mean_val, (1, 1, 224, 224))\n    data_process = data - mean_val\n    data_process = data_process / 58.8\n    data_process = data_process.astype(np.float32)\n\n    proto_file_url = (\n        \"https://github.com/BVLC/caffe/raw/master/models\" + \"/bvlc_googlenet/deploy.prototxt\"\n    )\n    blob_file_url = \"http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel\"\n    proto_file = download_testdata(proto_file_url, \"inceptionv1.prototxt\", module=\"model\")\n    blob_file = download_testdata(blob_file_url, \"inceptionv1.caffemodel\", module=\"model\")\n    _test_network(data_process, proto_file, blob_file)\n\n\n@pytest.mark.skip(reason=\"See issue https://github.com/apache/tvm/issues/13227\")\ndef test_forward_Inceptionv1():\n    \"\"\"Inceptionv4\"\"\"\n    data = np.random.randint(0, 256, size=(1, 3, 224, 224)).astype(np.float32)\n    _test_inceptionv1(data)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/caffe2/model_zoo/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Store for caffe2 examples and common models.\"\"\"\nfrom __future__ import absolute_import as _abs\nimport os\nimport sys\nimport importlib\nfrom caffe2.python.models.download import ModelDownloader\nfrom . import squeezenet\n\nmodels = [\n    \"squeezenet\",\n    \"resnet50\",\n    \"vgg19\",\n]\n\nmf = ModelDownloader()\n\n\nclass Model:\n    def __init__(self, model_name):\n        self.init_net, self.predict_net, self.value_info = mf.get_c2_model(model_name)\n\n\nfor model in models:\n    try:\n        locals()[\"c2_\" + model] = importlib.import_module(\"caffe2.python.models.\" + model)\n    except ImportError:\n        locals()[\"c2_\" + model] = Model(model)\n\n# squeezenet\ndef relay_squeezenet():\n    return squeezenet.get_workload()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/caffe2/model_zoo/squeezenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# coding: utf-8\n# pylint: disable=unused-argument\n\n\"\"\"\nSymbol of SqueezeNet\n\nReference:\nIandola, Forrest N., et al.\n\"Squeezenet: Alexnet-level accuracy with 50x fewer parameters and< 0.5 mb model size.\" (2016).\n\"\"\"\n\nfrom tvm import relay\nfrom tvm.relay.testing import create_workload\n\n# Helpers\ndef _make_fire(net, squeeze_channels, expand1x1_channels, expand3x3_channels, prefix=\"\"):\n    net = _make_fire_conv(net, squeeze_channels, 1, 0, f\"{prefix}/squeeze1x1\")\n\n    left = _make_fire_conv(net, expand1x1_channels, 1, 0, f\"{prefix}/expand1x1\")\n    right = _make_fire_conv(net, expand3x3_channels, 3, 1, f\"{prefix}/expand3x3\")\n    # NOTE : Assume NCHW layout here\n    net = relay.concatenate((left, right), axis=1)\n    return net\n\n\ndef _make_fire_conv(net, channels, kernel_size, padding=0, prefix=\"\"):\n    net = relay.nn.conv2d(\n        net,\n        relay.var(f\"{prefix}_weight\"),\n        channels=channels,\n        kernel_size=(kernel_size, kernel_size),\n        padding=(padding, padding),\n    )\n    net = relay.nn.bias_add(net, relay.var(f\"{prefix}_bias\"))\n    net = relay.nn.relu(net)\n    return net\n\n\n# Net\ndef get_net(batch_size, image_shape, num_classes, dtype):\n    \"\"\"Get symbol of SqueezeNet\n\n    Parameters\n    ----------\n    batch_size : int\n        The batch size used in the model\n\n    image_shape : tuple\n        The input image shape\n\n    num_classes: int\n        The number of classification results\n\n    dtype : str\n        The data type\n\n    \"\"\"\n    data_shape = (batch_size,) + image_shape\n    net = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    net = relay.nn.conv2d(\n        net,\n        relay.var(\"conv1_weight\"),\n        channels=64,\n        kernel_size=(3, 3),\n        strides=(2, 2),\n        padding=(0, 0),\n    )\n    net = relay.nn.bias_add(net, relay.var(\"conv1_bias\"))\n    net = relay.nn.relu(net)\n    net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n    net = _make_fire(net, 16, 64, 64, \"fire2\")\n    net = _make_fire(net, 16, 64, 64, \"fire3\")\n    net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n    net = _make_fire(net, 32, 128, 128, \"fire4\")\n    net = _make_fire(net, 32, 128, 128, \"fire5\")\n    net = relay.nn.max_pool2d(net, pool_size=(3, 3), strides=(2, 2))\n    net = _make_fire(net, 48, 192, 192, \"fire6\")\n    net = _make_fire(net, 48, 192, 192, \"fire7\")\n    net = _make_fire(net, 64, 256, 256, \"fire8\")\n    net = _make_fire(net, 64, 256, 256, \"fire9\")\n    net = relay.nn.dropout(net, rate=0.5)\n    net = relay.nn.conv2d(net, relay.var(\"conv10_weight\"), channels=num_classes, kernel_size=(1, 1))\n    net = relay.nn.bias_add(net, relay.var(\"conv10_bias\"))\n    net = relay.nn.relu(net)\n    net = relay.nn.global_avg_pool2d(net)\n    net = relay.nn.softmax(net, axis=1)\n    args = relay.analysis.free_vars(net)\n    return relay.Function(args, net)\n\n\ndef get_workload(batch_size=1, image_shape=(3, 224, 224), num_classes=1000, dtype=\"float32\"):\n    \"\"\"Get benchmark workload for SqueezeNet\n\n    Parameters\n    ----------\n    batch_size : int, optional\n        The batch size used in the model\n\n    num_classes : int, optional\n        Number of classes\n\n    image_shape : tuple, optional\n        The input image shape\n\n    dtype : str, optional\n        The data type\n\n    Returns\n    -------\n    net : relay.Function\n        The computational graph\n\n    params : dict of str to NDArray\n        The parameters.\n    \"\"\"\n\n    net = get_net(batch_size, image_shape, num_classes, dtype)\n    return create_workload(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/caffe2/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCaffe2 testcases\n====================\nThis article is a test script to test Caffe2 operator with Relay.\n\"\"\"\nfrom collections import namedtuple\nimport numpy as np\n\nfrom caffe2.python import workspace, core\nfrom caffe2.proto import caffe2_pb2\nfrom model_zoo import c2_squeezenet, c2_resnet50, c2_vgg19\nimport tvm\nfrom tvm.contrib import graph_executor\nfrom tvm import relay\n\nimport tvm.testing\n\n\ndef get_tvm_output(model, input_data, target, device, output_shape, output_dtype=\"float32\"):\n    \"\"\"Generic function to execute and get tvm output\"\"\"\n    # supporting multiple inputs in caffe2 in a bit tricky,\n    # because the input names can appear at the beginning or end of model.predict_net.external_input\n    assert isinstance(input_data, np.ndarray)\n\n    # here we use the first input blob to the first op to get the input name\n    input_names = model.predict_net.op[0].input[0]\n    shape_dict = {input_names: input_data.shape}\n    dtype_dict = {input_names: input_data.dtype}\n    mod, params = relay.frontend.from_caffe2(\n        model.init_net, model.predict_net, shape_dict, dtype_dict\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target, params=params)\n\n    m = graph_executor.GraphModule(lib[\"default\"](device))\n\n    # set inputs\n    m.set_input(input_names, tvm.nd.array(input_data.astype(input_data.dtype)))\n\n    # execute\n    m.run()\n\n    # get outputs\n    if isinstance(output_shape, list) and isinstance(output_dtype, list):\n        tvm_output_list = []\n        for i, s in enumerate(output_shape):\n            tvm_output = m.get_output(i, tvm.nd.empty((s), output_dtype[i]))\n            tvm_output_list.append(tvm_output.numpy())\n        return tvm_output_list\n    else:\n        tvm_output = m.get_output(0, tvm.nd.empty((output_shape), output_dtype))\n        return tvm_output.numpy()\n\n\ndef get_caffe2_output(model, x, dtype=\"float32\"):\n    workspace.RunNetOnce(model.init_net)\n\n    input_blob = model.predict_net.op[0].input[0]\n    workspace.FeedBlob(input_blob, x.astype(dtype))\n    workspace.RunNetOnce(model.predict_net)\n\n    output_blob = model.predict_net.external_output[0]\n    c2_output = workspace.FetchBlob(output_blob)\n    return c2_output\n\n\ndef verify_caffe2_forward_impl(model, data_shape, out_shape):\n    dtype = \"float32\"\n    data = np.random.uniform(size=data_shape).astype(dtype)\n    c2_out = get_caffe2_output(model, data, dtype)\n    for target, dev in tvm.testing.enabled_targets():\n        tvm_out = get_tvm_output(model, data, target, dev, out_shape, dtype)\n        tvm.testing.assert_allclose(c2_out, tvm_out, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_squeezenet1_1():\n    verify_caffe2_forward_impl(c2_squeezenet, (1, 3, 224, 224), (1, 1000, 1, 1))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_resnet50():\n    verify_caffe2_forward_impl(c2_resnet50, (1, 3, 224, 224), (1, 1000))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_vgg19():\n    verify_caffe2_forward_impl(c2_vgg19, (1, 3, 224, 224), (1, 1000))\n\n\nModel = namedtuple(\"Model\", [\"init_net\", \"predict_net\"])\n\n\n@tvm.testing.uses_gpu\ndef test_elementwise_add():\n    \"\"\"Elewise_add\"\"\"\n    data_shape = (1, 16, 9, 9)\n    init_net = caffe2_pb2.NetDef()\n    init_net.name = \"test_init_net\"\n    init_net.external_output[:] = [\"A\", \"B\"]\n    init_net.op.extend(\n        [\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"A\"],\n                shape=data_shape,\n                values=np.random.uniform(size=data_shape).flatten().tolist(),\n            ),\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"B\"],\n                shape=data_shape,\n                values=np.random.uniform(size=data_shape).flatten().tolist(),\n            ),\n        ]\n    )\n\n    predict_net = caffe2_pb2.NetDef()\n    predict_net.name = \"test_predict_net\"\n    predict_net.external_input[:] = [\"A\", \"B\"]\n    predict_net.external_output[:] = [\"C\"]\n    predict_net.op.extend(\n        [\n            core.CreateOperator(\n                \"Add\",\n                [\"A\", \"B\"],\n                [\"C\"],\n            )\n        ]\n    )\n\n    model = Model(init_net, predict_net)\n    verify_caffe2_forward_impl(model, data_shape, data_shape)\n\n\n@tvm.testing.uses_gpu\ndef test_elementwise_add_with_broadcast():\n    \"\"\"Elewise_add_with_broadcast\"\"\"\n    data_shape = (1, 16, 9, 9)\n    init_net = caffe2_pb2.NetDef()\n    init_net.name = \"test_init_net\"\n    init_net.external_output[:] = [\"A\", \"B\"]\n    init_net.op.extend(\n        [\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"A\"],\n                shape=data_shape,\n                values=np.random.uniform(size=data_shape).flatten().tolist(),\n            ),\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"B\"],\n                shape=(1,),\n                values=np.random.uniform(size=1).flatten().tolist(),\n            ),\n        ]\n    )\n\n    predict_net = caffe2_pb2.NetDef()\n    predict_net.name = \"test_predict_net\"\n    predict_net.external_input[:] = [\"A\", \"B\"]\n    predict_net.external_output[:] = [\"C\"]\n    predict_net.op.extend(\n        [\n            core.CreateOperator(\n                \"Add\",\n                [\"A\", \"B\"],\n                [\"C\"],\n                broadcast=1,\n            )\n        ]\n    )\n\n    model = Model(init_net, predict_net)\n    verify_caffe2_forward_impl(model, data_shape, data_shape)\n\n\n@tvm.testing.uses_gpu\ndef test_normalize_yuv():\n    \"\"\"Normalize_yuv\"\"\"\n    data_shape = (1, 3, 96, 96)\n    init_net = caffe2_pb2.NetDef()\n    init_net.name = \"test_init_net\"\n    init_net.external_output[:] = [\"A\", \"mean\", \"std\"]\n    init_net.op.extend(\n        [\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"A\"],\n                shape=data_shape,\n                values=np.random.uniform(size=data_shape).flatten().tolist(),\n            ),\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"mean\"],\n                shape=(\n                    1,\n                    3,\n                ),\n                values=np.random.uniform(size=3).flatten().tolist(),\n            ),\n            core.CreateOperator(\n                \"GivenTensorFill\",\n                [],\n                [\"std\"],\n                shape=(\n                    1,\n                    3,\n                ),\n                values=np.random.uniform(size=3).flatten().tolist(),\n            ),\n        ]\n    )\n\n    predict_net = caffe2_pb2.NetDef()\n    predict_net.name = \"test_predict_net\"\n    predict_net.external_input[:] = [\"A\", \"mean\", \"std\"]\n    predict_net.external_output[:] = [\"C\"]\n    predict_net.op.extend(\n        [\n            core.CreateOperator(\n                \"NormalizePlanarYUV\",\n                [\"A\", \"mean\", \"std\"],\n                [\"C\"],\n            )\n        ]\n    )\n\n    model = Model(init_net, predict_net)\n    verify_caffe2_forward_impl(model, data_shape, data_shape)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/caffe2/test_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test graph equality of caffe2 models.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom model_zoo import c2_squeezenet, relay_squeezenet\n\n\ndef compare_graph(lhs_mod, rhs_mod):\n    lhs_mod = transform.InferType()(lhs_mod)\n    rhs_mod = transform.InferType()(rhs_mod)\n    assert tvm.ir.structural_equal(lhs_mod[\"main\"], rhs_mod[\"main\"])\n\n\ndef test_squeeze_net():\n    shape_dict = {\"data\": (1, 3, 224, 224)}\n    dtype_dict = {\"data\": \"float32\"}\n    mod, _, = relay.frontend.from_caffe2(\n        c2_squeezenet.init_net, c2_squeezenet.predict_net, shape_dict, dtype_dict\n    )\n    relay_mod, _ = relay_squeezenet()\n    compare_graph(mod, relay_mod)\n\n\nif __name__ == \"__main__\":\n    test_squeeze_net()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/coreml/model_zoo/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"coreml model zoo for testing purposes.\"\"\"\nimport os\nfrom PIL import Image\nimport numpy as np\nfrom tvm.contrib.download import download_testdata\n\n\ndef get_mobilenet():\n    url = \"https://docs-assets.developer.apple.com/coreml/models/MobileNet.mlmodel\"\n    dst = \"mobilenet.mlmodel\"\n    real_dst = download_testdata(url, dst, module=\"coreml\")\n    return os.path.abspath(real_dst)\n\n\ndef get_resnet50():\n    url = \"https://docs-assets.developer.apple.com/coreml/models/Resnet50.mlmodel\"\n    dst = \"resnet50.mlmodel\"\n    real_dst = download_testdata(url, dst, module=\"coreml\")\n    return os.path.abspath(real_dst)\n\n\ndef get_cat_image():\n    \"\"\"Get cat image\"\"\"\n    url = (\n        \"https://gist.githubusercontent.com/zhreshold/\"\n        + \"bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png\"\n    )\n    dst = \"cat.png\"\n    real_dst = download_testdata(url, dst, module=\"data\")\n    img = Image.open(real_dst).resize((224, 224))\n    # CoreML's standard model image format is BGR\n    img_bgr = np.array(img)[:, :, ::-1]\n    img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :]\n    return np.asarray(img)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/coreml/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nCoreML testcases\n====================\nThis article is a test script to test CoreML operator with Relay.\n\"\"\"\nfrom os import path\nfrom enum import Enum\nimport tempfile\nimport numpy as np\n\nimport tvm\nimport tvm.topi.testing\nimport tvm.testing\nfrom tvm.contrib import graph_executor\nfrom tvm.topi.testing import conv2d_nchw_python\nfrom tvm import relay\nimport model_zoo\n\nimport coremltools as cm\nfrom coremltools.models.neural_network import NeuralNetworkBuilder\nfrom coremltools.models import datatypes\nfrom tensorflow import keras\n\n\ndef get_tvm_output(\n    func, x, params, target, device, out_shape=(1, 1000), input_name=\"image\", dtype=\"float32\"\n):\n    \"\"\"Generic function to execute and get tvm output\"\"\"\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(func, target, params=params)\n    m = graph_executor.GraphModule(lib[\"default\"](device))\n    # set inputs\n    m.set_input(input_name, tvm.nd.array(x.astype(dtype)))\n    m.run()\n    # get outputs\n    out = m.get_output(0, tvm.nd.empty(out_shape, dtype))\n    return out.numpy()\n\n\ndef run_model_checkonly(model_file, model_name=\"\", input_name=\"image\"):\n    model = cm.models.MLModel(model_file)\n    x = model_zoo.get_cat_image()\n    shape_dict = {input_name: x.shape}\n    # Some Relay passes change operators on the fly. Ensuring that we generate\n    # new graph for each target.\n    for target, dev in tvm.testing.enabled_targets():\n        mod, params = relay.frontend.from_coreml(model, shape_dict)\n        tvm_output = get_tvm_output(mod[\"main\"], x, params, target, dev)\n        print(target, dev, model_name, \"prediction id: \", np.argmax(tvm_output.flat))\n\n\n@tvm.testing.uses_gpu\ndef test_mobilenet_checkonly():\n    model_file = model_zoo.get_mobilenet()\n    run_model_checkonly(model_file, \"mobilenet\")\n\n\n@tvm.testing.uses_gpu\ndef test_resnet50_checkonly():\n    model_file = model_zoo.get_resnet50()\n    run_model_checkonly(model_file, \"resnet50\")\n\n\ndef run_tvm_graph(\n    coreml_model, target, device, input_data, input_name, output_shape, output_dtype=\"float32\"\n):\n    \"\"\"Generic function to compile on relay and execute on tvm\"\"\"\n    if isinstance(input_data, list):\n        shape_dict = {}\n        dtype_dict = {}\n        for i, inp in enumerate(input_name):\n            shape_dict[inp] = input_data[i].shape\n            dtype_dict[inp] = input_data[i].dtype\n    else:\n        shape_dict = {input_name: input_data.shape}\n        dtype_dict = {input_name: input_data.dtype}\n\n    mod, params = relay.frontend.from_coreml(coreml_model, shape_dict)\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target, params=params)\n\n    m = graph_executor.GraphModule(lib[\"default\"](device))\n    # set inputs\n    if isinstance(input_data, list):\n        for i, inp in enumerate(input_name):\n            m.set_input(inp, tvm.nd.array(input_data[i].astype(input_data[i].dtype)))\n    else:\n        m.set_input(input_name, tvm.nd.array(input_data.astype(input_data.dtype)))\n\n    # execute\n    m.run()\n    # get outputs\n    if isinstance(output_shape, list) and isinstance(output_dtype, list):\n        tvm_output_list = []\n        for i, s in enumerate(output_shape):\n            tvm_output = m.get_output(i, tvm.nd.empty((s), output_dtype[i]))\n            tvm_output_list.append(tvm_output.numpy())\n        return tvm_output_list\n    else:\n        if not output_shape:\n            tvm_output = m.get_output(0)\n        else:\n            tvm_output = m.get_output(0, tvm.nd.empty((output_shape), output_dtype))\n        return tvm_output.numpy()\n\n\ndef verify_add_layer_params(input_dim, alpha=2):\n    \"\"\"Verify add layer params\"\"\"\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n\n    b_np = np.add(a_np1, a_np2) + alpha\n    inputs = [(\"input1\", datatypes.Array(*input_dim)), (\"input2\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"Add\", alpha=alpha, input_names=[\"input1\", \"input2\"], output_name=\"output\", mode=\"ADD\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np1, a_np2], [\"input1\", \"input2\"], b_np.shape, dtype\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_add_layer_params():\n    verify_add_layer_params((1, 2, 2), 0)\n    verify_add_layer_params((1, 2, 2), 1)\n    verify_add_layer_params((1, 3, 3), 2)\n\n\ndef verify_multiply_layer_params(input_dim, alpha):\n    \"\"\"Verify multiply layer params\"\"\"\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n\n    b_np = np.multiply(a_np1, a_np2) * alpha\n    inputs = [(\"input1\", datatypes.Array(*input_dim)), (\"input2\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"Mul\",\n        alpha=alpha,\n        input_names=[\"input1\", \"input2\"],\n        output_name=\"output\",\n        mode=\"MULTIPLY\",\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np1, a_np2], [\"input1\", \"input2\"], b_np.shape, dtype\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_multiply_layer_params():\n    verify_multiply_layer_params((1, 2, 2), 0)\n    verify_multiply_layer_params((1, 2, 2), 1)\n    verify_multiply_layer_params((1, 3, 3), 2)\n\n\ndef verify_concat_layer_params(input1_dim, input2_dim):\n    \"\"\"Verify concat layer params\"\"\"\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input1_dim).astype(dtype)\n    a_np2 = np.random.uniform(size=input2_dim).astype(dtype)\n\n    b_np = np.concatenate((a_np1, a_np2), axis=1)\n    inputs = [(\"input1\", datatypes.Array(*input1_dim)), (\"input2\", datatypes.Array(*input2_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]  # pylint:disable=not-an-iterable\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"Concate\", input_names=[\"input1\", \"input2\"], output_name=\"output\", mode=\"CONCAT\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np1, a_np2], [\"input1\", \"input2\"], b_np.shape, dtype\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_concat_layer_params():\n    verify_concat_layer_params((1, 1, 2, 2), (1, 2, 2, 2))\n    verify_concat_layer_params((1, 2, 4, 4), (1, 3, 4, 4))\n\n\ndef _verify_upsample_layer_params(input_dim, scale, mode):\n    dtype = \"float32\"\n\n    a_np = np.full(input_dim, 1, dtype=dtype)\n\n    if mode == \"NN\":\n        method = \"nearest_neighbor\"\n        coord_trans = \"asymmetric\"\n    else:\n        method = \"linear\"\n        coord_trans = \"align_corners\"\n\n    b_np = tvm.topi.testing.resize2d_python(a_np, (scale, scale), \"NCHW\", method, coord_trans)\n\n    input_data = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(input_data, output)\n    builder.add_upsample(\n        name=\"Upsample\",\n        scaling_factor_h=scale,\n        scaling_factor_w=scale,\n        mode=mode,\n        input_name=\"input\",\n        output_name=\"output\",\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, a_np, \"input\", b_np.shape, dtype)\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_upsample_layer_params():\n    \"\"\"Upsample Layer Params\"\"\"\n    _verify_upsample_layer_params((1, 16, 32, 32), 2, \"NN\")\n    _verify_upsample_layer_params((1, 4, 6, 6), 3, \"BILINEAR\")\n\n\ndef _verify_l2_normalize(input_dim, eps):\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    b_np = tvm.topi.testing.l2_normalize_python(a_np, eps, 1)\n\n    input_data = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(input_data, output)\n    builder.add_l2_normalize(name=\"L2\", epsilon=eps, input_name=\"input\", output_name=\"output\")\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, a_np, \"input\", b_np.shape, dtype)\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_l2_normalize():\n    _verify_l2_normalize((1, 3, 20, 20), 0.001)\n\n\ndef _verify_lrn(input_dim, size, bias, alpha, beta):\n    dtype = \"float32\"\n    axis = 1\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    b_np = tvm.topi.testing.lrn_python(a_np, size, axis, bias, alpha, beta)\n\n    input_data = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(input_data, output)\n    builder.add_lrn(\n        name=\"LRN\",\n        input_name=\"input\",\n        output_name=\"output\",\n        alpha=alpha,\n        beta=beta,\n        k=bias,\n        local_size=size,\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, a_np, \"input\", b_np.shape, dtype)\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_lrn():\n    _verify_lrn((1, 3, 10, 20), 3, 1.0, 1.0, 0.5)\n\n\ndef _verify_average(input_dim1, input_dim2, axis=0):\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input_dim1).astype(dtype)\n    a_np2 = np.random.uniform(size=input_dim2).astype(dtype)\n\n    b_np = np.mean((a_np1, a_np2), axis=axis)\n\n    inputs = [(\"input1\", datatypes.Array(*input_dim1)), (\"input2\", datatypes.Array(*input_dim2))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"MEAN\", input_names=[\"input1\", \"input2\"], output_name=\"output\", mode=\"AVE\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np1, a_np2], [\"input1\", \"input2\"], b_np.shape, dtype\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_average():\n    _verify_average((1, 3, 20, 20), (1, 3, 20, 20))\n    _verify_average((3, 20, 20), (1, 3, 20, 20))\n    _verify_average((20, 20), (1, 3, 20, 20))\n\n\ndef _verify_max(input_dim):\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n    b_np = np.max((a_np1, a_np2, a_np3), axis=0)\n\n    inputs = [\n        (\"input1\", datatypes.Array(*input_dim)),\n        (\"input2\", datatypes.Array(*input_dim)),\n        (\"input3\", datatypes.Array(*input_dim)),\n    ]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"Max\", input_names=[\"input1\", \"input2\", \"input3\"], output_name=\"output\", mode=\"MAX\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model,\n            target,\n            dev,\n            [a_np1, a_np2, a_np3],\n            [\"input1\", \"input2\", \"input3\"],\n            b_np.shape,\n            dtype,\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_max():\n    _verify_max((1, 3, 20, 20))\n    _verify_max((20, 20))\n\n\ndef _verify_min(input_dim):\n    dtype = \"float32\"\n\n    a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n    a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n    b_np = np.min((a_np1, a_np2, a_np3), axis=0)\n\n    inputs = [\n        (\"input1\", datatypes.Array(*input_dim)),\n        (\"input2\", datatypes.Array(*input_dim)),\n        (\"input3\", datatypes.Array(*input_dim)),\n    ]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_elementwise(\n        name=\"Min\", input_names=[\"input1\", \"input2\", \"input3\"], output_name=\"output\", mode=\"MIN\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model,\n            target,\n            dev,\n            [a_np1, a_np2, a_np3],\n            [\"input1\", \"input2\", \"input3\"],\n            b_np.shape,\n            dtype,\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_min():\n    _verify_min((1, 3, 20, 20))\n    _verify_min((20, 20))\n\n\ndef verify_unary_sqrt(input_dim):\n    \"\"\"Verify unary sqrt\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = np.sqrt(a_np)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(name=\"sqrt\", input_name=\"input\", output_name=\"output\", mode=\"sqrt\")\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_rsqrt(input_dim, epsilon=0):\n    \"\"\"Verify unary rsqrt\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = 1 / np.sqrt(a_np + epsilon)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(\n        name=\"rsqrt\", input_name=\"input\", output_name=\"output\", mode=\"rsqrt\", epsilon=epsilon\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_inverse(input_dim, epsilon=0):\n    \"\"\"Verify unary inverse\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = 1 / (a_np + epsilon)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(\n        name=\"inverse\", input_name=\"input\", output_name=\"output\", mode=\"inverse\", epsilon=epsilon\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_power(input_dim, alpha):\n    \"\"\"Verify unary power\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = np.power(a_np, alpha)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(\n        name=\"power\", input_name=\"input\", output_name=\"output\", mode=\"power\", alpha=alpha\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_exp(input_dim):\n    \"\"\"Verify unary exp\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = np.exp(a_np)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(name=\"exp\", input_name=\"input\", output_name=\"output\", mode=\"exp\")\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_log(input_dim):\n    \"\"\"Verify unary log\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    ref_val = np.log(a_np)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(name=\"log\", input_name=\"input\", output_name=\"output\", mode=\"log\")\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_abs(input_dim):\n    \"\"\"Verify unary abs\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)\n    ref_val = np.abs(a_np)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(name=\"abs\", input_name=\"input\", output_name=\"output\", mode=\"abs\")\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef verify_unary_threshold(input_dim, alpha):\n    \"\"\"Verify unary threshold\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)\n    ref_val = np.maximum(a_np, alpha)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_unary(\n        name=\"threshold\", input_name=\"input\", output_name=\"output\", mode=\"threshold\", alpha=alpha\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_unary():\n    \"\"\"All unary\"\"\"\n    verify_unary_sqrt((1, 3, 20, 20))\n    verify_unary_rsqrt((1, 3, 20, 20))\n    verify_unary_rsqrt((1, 3, 20, 20), epsilon=1e-6)\n    verify_unary_inverse((1, 3, 20, 20))\n    verify_unary_inverse((1, 3, 20, 20), epsilon=1e-6)\n    verify_unary_power((1, 3, 20, 20), alpha=0.5)\n    verify_unary_power((1, 3, 20, 20), alpha=4)\n    verify_unary_exp((1, 3, 20, 20))\n    verify_unary_log((1, 3, 20, 20))\n    verify_unary_abs((1, 3, 20, 20))\n    verify_unary_threshold((1, 3, 20, 20), alpha=-6.0)\n    verify_unary_threshold((1, 3, 20, 20), alpha=5.0)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reduce():\n    \"\"\"Reduce\"\"\"\n\n    class ReduceAxis(Enum):\n        # pylint: disable=invalid-name\n        CHW = 0\n        HW = 1\n        C = 2\n        H = 3\n        W = 4\n\n    def _verify_reduce(input_dim, mode, axis, ref_func, dtype=\"float32\"):\n        print(input_dim, mode, axis)\n        a_np = np.random.uniform(size=input_dim).astype(dtype)\n\n        # translate to axis from coreml format\n        if axis == ReduceAxis.CHW:\n            np_axis = (-3, -2, -1)\n        elif axis == ReduceAxis.HW:\n            np_axis = (-2, -1)\n        elif axis == ReduceAxis.C:\n            np_axis = -3\n        elif axis == ReduceAxis.H:\n            np_axis = -2\n        elif axis == ReduceAxis.W:\n            np_axis = -1\n\n        if ref_func is np.argmax:\n            ref_val = np.expand_dims(ref_func(a_np, np_axis), np_axis).astype(dtype)\n        else:\n            ref_val = ref_func(a_np, np_axis, keepdims=True)\n\n        inputs = [(\"input\", datatypes.Array(*input_dim))]\n        output = [(\"output\", datatypes.Array(*ref_val.shape))]\n        builder = NeuralNetworkBuilder(inputs, output)\n        builder.add_reduce(\n            name=mode, input_name=\"input\", output_name=\"output\", axis=axis.name, mode=mode\n        )\n\n        model = cm.models.MLModel(builder.spec)\n        for target, dev in tvm.testing.enabled_targets():\n            out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n            tvm.testing.assert_allclose(out, ref_val, rtol=1e-5, atol=1e-5)\n\n    dshapes = [[10, 10], [1, 10, 10], [1, 3, 10, 10]]\n    for dshape in dshapes:\n        for axis in ReduceAxis:\n            if len(dshape) < 3 and axis in [ReduceAxis.CHW, ReduceAxis.C]:\n                # input must have rank at least 3\n                continue\n            _verify_reduce(dshape, \"sum\", axis, np.sum)\n            _verify_reduce(dshape, \"avg\", axis, np.mean)\n            _verify_reduce(dshape, \"prod\", axis, np.prod)\n            _verify_reduce(dshape, \"min\", axis, np.min)\n            _verify_reduce(dshape, \"max\", axis, np.max)\n            if axis in [ReduceAxis.C, ReduceAxis.H, ReduceAxis.W]:\n                # For mode ArgMax, axis must be [-1] or [-2] or [-3]\n                _verify_reduce(dshape, \"argmax\", axis, np.argmax, dtype=\"int32\")\n\n\ndef verify_reshape(input_dim, target_shape, mode):\n    \"\"\"Reshape\"\"\"\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)\n    ref_val = np.reshape(a_np, target_shape)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*ref_val.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_reshape(\n        name=\"reshape\",\n        input_name=\"input\",\n        output_name=\"output\",\n        target_shape=target_shape,\n        mode=mode,\n    )\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input\"], ref_val.shape, dtype)\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef test_forward_reshape():\n    for mode in [0, 1]:\n        verify_reshape((20,), (1, 2, 2, 5), mode)\n        verify_reshape((1, 3, 20, 20), (1, 12, 10, 10), mode)\n\n\ndef _verify_split(input_dim, out_nums):\n    dtype = \"float32\"\n\n    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)\n    ref_val = np.split(a_np, out_nums, axis=-3)\n\n    inputs = [(\"input\", datatypes.Array(*input_dim))]\n\n    output_names = []\n    outputs = []\n    output_shapes = []\n    for i, out in enumerate(ref_val):\n        output_name = \"output\" + str(i)\n        output_names = output_names + [output_name]\n        outputs = outputs + [(output_name, datatypes.Array(*out.shape))]\n        output_shapes = output_shapes + [out.shape]\n\n    builder = NeuralNetworkBuilder(inputs, outputs)\n    builder.add_split(name=\"split\", input_name=\"input\", output_names=output_names)\n\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np], [\"input\"], output_shapes, [dtype] * len(output_shapes)\n        )\n        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)\n\n\ndef test_forward_split():\n    \"\"\"Split\"\"\"\n    _verify_split(\n        (\n            1,\n            4,\n            4,\n            4,\n        ),\n        2,\n    )\n    _verify_split(\n        (\n            1,\n            3,\n            30,\n            20,\n        ),\n        3,\n    )\n\n\ndef verify_image_scaler(input_dim, blue_bias=0.0, green_bias=0.0, red_bias=0.0, image_scale=1.0):\n    \"\"\"Verify image scaler\"\"\"\n    dtype = \"float32\"\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    # make sure it is valid image format CHW.\n    assert len(a_np.shape) == 3 and a_np.shape[0] == 3\n    b_np = np.zeros(a_np.shape, dtype=dtype)\n    b_np[0, :, :] = image_scale * a_np[0, :, :] + blue_bias\n    b_np[1, :, :] = image_scale * a_np[1, :, :] + green_bias\n    b_np[2, :, :] = image_scale * a_np[2, :, :] + red_bias\n    b_np = np.add(a_np, b_np)\n    inputs = [(\"input1\", datatypes.Array(*input_dim)), (\"input2\", datatypes.Array(*input_dim))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.set_pre_processing_parameters(\n        image_input_names=[\"input1\"],\n        is_bgr=True,\n        blue_bias=blue_bias,\n        green_bias=green_bias,\n        red_bias=red_bias,\n        image_scale=image_scale,\n    )\n    # add one add layer to make CoreML model format valid\n    # add layer has been tested before.\n    builder.add_elementwise(\n        name=\"add\", input_names=[\"input1\", \"input2\"], output_name=\"output\", alpha=0, mode=\"ADD\"\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(\n            model, target, dev, [a_np, a_np], [\"input1\", \"input2\"], b_np.shape, dtype\n        )\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_image_scaler():\n    verify_image_scaler((3, 224, 224), image_scale=0.17)\n    verify_image_scaler(\n        (3, 224, 224),\n        blue_bias=-1.7669800519943237,\n        green_bias=-1.985260009765625,\n        red_bias=-2.102560043334961,\n        image_scale=0.379,\n    )\n\n\ndef verify_convolution(input_dim, filter_, padding):\n    \"\"\"Verify convolution\"\"\"\n    dtype = \"float32\"\n    _, c, h, width = input_dim\n    out_c, _, kernel_h, kernel_w = filter_\n    a_np = np.random.uniform(size=input_dim).astype(dtype)\n    w_np = np.random.uniform(size=(out_c, c, kernel_h, kernel_w)).astype(dtype)\n    w_np_cm = np.transpose(w_np, axes=(2, 3, 1, 0))\n    b_np = conv2d_nchw_python(a_np, w_np, [1, 1], padding)\n    inputs = [(\"input1\", datatypes.Array(c, h, width))]\n    output = [(\"output\", datatypes.Array(*b_np.shape))]  # pylint:disable=not-an-iterable\n    builder = NeuralNetworkBuilder(inputs, output)\n    builder.add_convolution(\n        name=\"conv\",\n        kernel_channels=3,\n        output_channels=out_c,\n        height=kernel_h,\n        width=kernel_w,\n        stride_height=1,\n        stride_width=1,\n        border_mode=padding.lower(),\n        groups=1,\n        W=w_np_cm,\n        b=None,\n        has_bias=False,\n        is_deconv=False,\n        input_name=\"input1\",\n        output_name=\"output\",\n    )\n    model = cm.models.MLModel(builder.spec)\n    for target, dev in tvm.testing.enabled_targets():\n        out = run_tvm_graph(model, target, dev, [a_np], [\"input1\"], output_shape=None)\n        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_convolution():\n    verify_convolution((1, 3, 224, 224), filter_=(32, 3, 3, 3), padding=\"VALID\")\n    verify_convolution((1, 3, 224, 224), filter_=(32, 3, 3, 3), padding=\"SAME\")\n\n\ndef test_can_build_keras_to_coreml_to_relay():\n    \"\"\"Test multiple conversion paths and importing from a saved file.\"\"\"\n    model = keras.models.Sequential()\n    model.add(\n        keras.layers.Conv2D(\n            filters=6,\n            kernel_size=(1, 1),\n            activation=\"relu\",\n            padding=\"same\",\n            input_shape=(3, 3, 1),\n            data_format=\"channels_first\",\n        )\n    )\n\n    with tempfile.TemporaryDirectory() as tmpdir:\n        kmodel_fn = path.join(tmpdir, \"c1mdl.h5\")\n        model.save(kmodel_fn)\n\n        mdl = cm.convert(kmodel_fn)\n        model_file = path.join(tmpdir, \"c1.mlmodel\")\n        mdl.save(model_file)\n\n        mdl = cm.models.MLModel(model_file)\n        desc = mdl.get_spec().description\n        iname = desc.input[0].name\n        ishape = desc.input[0].type.multiArrayType.shape\n        shape_dict = {}\n        for i in mdl.get_spec().description.input:\n            iname = i.name\n            ishape = i.type.multiArrayType.shape\n            shape_dict[iname] = ishape\n        mod, params = relay.frontend.from_coreml(mdl, shape_dict)\n\n        with tvm.transform.PassContext(opt_level=3):\n            relay.build(mod, \"llvm\", params=params)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/darknet/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"\nTest Darknet Models\n===================\nThis article is a test script to test darknet models with Relay.\nAll the required models and libraries will be downloaded from the internet\nby the script.\n\"\"\"\nfrom cffi import FFI\nimport numpy as np\nimport tvm\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.download import download_testdata\n\nfrom tvm.relay.testing.darknet import LAYERTYPE\nfrom tvm.relay.testing.darknet import __darknetffi__\nfrom tvm.relay.frontend.darknet import ACTIVATION\nfrom tvm import relay\n\nREPO_URL = \"https://github.com/dmlc/web-data/blob/main/darknet/\"\nDARKNET_LIB = \"libdarknet2.0.so\"\nDARKNETLIB_URL = REPO_URL + \"lib/\" + DARKNET_LIB + \"?raw=true\"\nLIB = __darknetffi__.dlopen(download_testdata(DARKNETLIB_URL, DARKNET_LIB, module=\"darknet\"))\n\nDARKNET_TEST_IMAGE_NAME = \"dog.jpg\"\nDARKNET_TEST_IMAGE_URL = REPO_URL + \"data/\" + DARKNET_TEST_IMAGE_NAME + \"?raw=true\"\nDARKNET_TEST_IMAGE_PATH = download_testdata(\n    DARKNET_TEST_IMAGE_URL, DARKNET_TEST_IMAGE_NAME, module=\"data\"\n)\n\n\ndef astext(program, unify_free_vars=False):\n    \"\"\"check that program is parsable in text format\"\"\"\n    text = program.astext()\n    if isinstance(program, relay.Expr):\n        roundtrip_program = tvm.parser.parse_expr(text)\n    else:\n        roundtrip_program = tvm.parser.fromtext(text)\n\n    tvm.ir.assert_structural_equal(roundtrip_program, program, map_free_vars=True)\n\n\ndef _read_memory_buffer(shape, data, dtype=\"float32\"):\n    length = 1\n    for x in shape:\n        length *= x\n    data_np = np.zeros(length, dtype=dtype)\n    for i in range(length):\n        data_np[i] = data[i]\n    return data_np.reshape(shape)\n\n\ndef _get_tvm_output(net, data, build_dtype=\"float32\", states=None):\n    \"\"\"Compute TVM output\"\"\"\n    dtype = \"float32\"\n    mod, params = relay.frontend.from_darknet(net, data.shape, dtype)\n    # verify that from_darknet creates a valid, parsable relay program\n    mod = relay.transform.InferType()(mod)\n    astext(mod)\n\n    target = \"llvm\"\n    lib = relay.build(mod, target, params=params)\n\n    # Execute on TVM\n    dev = tvm.cpu(0)\n    m = graph_executor.GraphModule(lib[\"default\"](dev))\n    # set inputs\n    m.set_input(\"data\", tvm.nd.array(data.astype(dtype)))\n    if states:\n        for name in states.keys():\n            m.set_input(name, tvm.nd.array(states[name].astype(dtype)))\n    m.run()\n    # get outputs\n    tvm_out = []\n    for i in range(m.get_num_outputs()):\n        tvm_out.append(m.get_output(i).numpy())\n    return tvm_out\n\n\ndef _load_net(cfg_url, cfg_name, weights_url, weights_name):\n    cfg_path = download_testdata(cfg_url, cfg_name, module=\"darknet\")\n    weights_path = download_testdata(weights_url, weights_name, module=\"darknet\")\n    net = LIB.load_network(cfg_path.encode(\"utf-8\"), weights_path.encode(\"utf-8\"), 0)\n    return net\n\n\ndef verify_darknet_frontend(net, build_dtype=\"float32\"):\n    \"\"\"Test network with given input image on both darknet and tvm\"\"\"\n\n    def get_darknet_output(net, img):\n        LIB.network_predict_image(net, img)\n        out = []\n        for i in range(net.n):\n            layer = net.layers[i]\n            if layer.type == LAYERTYPE.REGION:\n                attributes = np.array(\n                    [\n                        layer.n,\n                        layer.out_c,\n                        layer.out_h,\n                        layer.out_w,\n                        layer.classes,\n                        layer.coords,\n                        layer.background,\n                    ],\n                    dtype=np.int32,\n                )\n                out.insert(0, attributes)\n                out.insert(0, _read_memory_buffer((layer.n * 2,), layer.biases))\n                layer_outshape = (layer.batch, layer.out_c, layer.out_h, layer.out_w)\n                out.insert(0, _read_memory_buffer(layer_outshape, layer.output))\n            elif layer.type == LAYERTYPE.YOLO:\n                attributes = np.array(\n                    [layer.n, layer.out_c, layer.out_h, layer.out_w, layer.classes, layer.total],\n                    dtype=np.int32,\n                )\n                out.insert(0, attributes)\n                out.insert(0, _read_memory_buffer((layer.total * 2,), layer.biases))\n                out.insert(0, _read_memory_buffer((layer.n,), layer.mask, dtype=\"int32\"))\n                layer_outshape = (layer.batch, layer.out_c, layer.out_h, layer.out_w)\n                out.insert(0, _read_memory_buffer(layer_outshape, layer.output))\n            elif i == net.n - 1:\n                if layer.type == LAYERTYPE.CONNECTED:\n                    darknet_outshape = (layer.batch, layer.out_c)\n                elif layer.type in [LAYERTYPE.SOFTMAX]:\n                    darknet_outshape = (layer.batch, layer.outputs)\n                else:\n                    darknet_outshape = (layer.batch, layer.out_c, layer.out_h, layer.out_w)\n                out.insert(0, _read_memory_buffer(darknet_outshape, layer.output))\n        return out\n\n    dtype = \"float32\"\n\n    img = LIB.letterbox_image(\n        LIB.load_image_color(DARKNET_TEST_IMAGE_PATH.encode(\"utf-8\"), 0, 0), net.w, net.h\n    )\n    darknet_output = get_darknet_output(net, img)\n    batch_size = 1\n    data = np.empty([batch_size, img.c, img.h, img.w], dtype)\n    i = 0\n    for c in range(img.c):\n        for h in range(img.h):\n            for k in range(img.w):\n                data[0][c][h][k] = img.data[i]\n                i = i + 1\n\n    tvm_out = _get_tvm_output(net, data, build_dtype)\n    for tvm_outs, darknet_out in zip(tvm_out, darknet_output):\n        tvm.testing.assert_allclose(darknet_out, tvm_outs, rtol=1e-3, atol=1e-3)\n\n\ndef _test_rnn_network(net, states):\n    \"\"\"Test network with given input data on both darknet and tvm\"\"\"\n\n    def get_darknet_network_predict(net, data):\n        return LIB.network_predict(net, data)\n\n    ffi = FFI()\n    np_arr = np.zeros([1, net.inputs], dtype=\"float32\")\n    np_arr[0, 2] = 1\n    cffi_arr = ffi.cast(\"float*\", np_arr.ctypes.data)\n    tvm_out = _get_tvm_output(net, np_arr, states=states)[0]\n    darknet_output = get_darknet_network_predict(net, cffi_arr)\n    darknet_out = np.zeros(net.outputs, dtype=\"float32\")\n    for i in range(net.outputs):\n        darknet_out[i] = darknet_output[i]\n    last_layer = net.layers[net.n - 1]\n    darknet_outshape = (last_layer.batch, last_layer.outputs)\n    darknet_out = darknet_out.reshape(darknet_outshape)\n    tvm.testing.assert_allclose(darknet_out, tvm_out, rtol=1e-4, atol=1e-4)\n\n\ndef test_forward_extraction():\n    \"\"\"test extraction model\"\"\"\n    model_name = \"extraction\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_alexnet():\n    \"\"\"test alexnet model\"\"\"\n    model_name = \"alexnet\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_resnet50():\n    \"\"\"test resnet50 model\"\"\"\n    model_name = \"resnet50\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_resnext50():\n    \"\"\"test resnet50 model\"\"\"\n    model_name = \"resnext50\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_yolov2():\n    \"\"\"test yolov2 model\"\"\"\n    model_name = \"yolov2\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    build_dtype = {}\n    verify_darknet_frontend(net, build_dtype)\n    LIB.free_network(net)\n\n\ndef test_forward_yolov3():\n    \"\"\"test yolov3 model\"\"\"\n    model_name = \"yolov3\"\n    cfg_name = model_name + \".cfg\"\n    weights_name = model_name + \".weights\"\n    cfg_url = \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + cfg_name + \"?raw=true\"\n    weights_url = \"http://pjreddie.com/media/files/\" + weights_name + \"?raw=true\"\n    net = _load_net(cfg_url, cfg_name, weights_url, weights_name)\n    build_dtype = {}\n    verify_darknet_frontend(net, build_dtype)\n    LIB.free_network(net)\n\n\ndef test_forward_convolutional():\n    \"\"\"test convolutional layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_convolutional_layer(1, 224, 224, 3, 32, 1, 3, 2, 0, 1, 0, 0, 0, 0)\n    net.layers[0] = layer\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_dense():\n    \"\"\"test fully connected layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_connected_layer(1, 75, 20, 1, 0, 0)\n    net.layers[0] = layer\n    net.w = net.h = 5\n    LIB.resize_network(net, 5, 5)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_dense_batchnorm():\n    \"\"\"test fully connected layer with batchnorm\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_connected_layer(1, 12, 2, 1, 1, 0)\n    for i in range(5):\n        layer.rolling_mean[i] = np.random.rand(1)\n        layer.rolling_variance[i] = np.random.rand(1) + 0.5\n        layer.scales[i] = np.random.rand(1)\n    net.layers[0] = layer\n    net.w = net.h = 2\n    LIB.resize_network(net, 2, 2)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_maxpooling():\n    \"\"\"test maxpooling layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_maxpool_layer(1, 224, 224, 3, 2, 2, 0)\n    net.layers[0] = layer\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_avgpooling():\n    \"\"\"test avgerage pooling layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_avgpool_layer(1, 224, 224, 3)\n    net.layers[0] = layer\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_conv_batch_norm():\n    \"\"\"test batch normalization layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_convolutional_layer(1, 224, 224, 3, 32, 1, 3, 2, 0, 1, 1, 0, 0, 0)\n    for i in range(32):\n        layer.rolling_mean[i] = np.random.rand(1)\n        layer.rolling_variance[i] = np.random.rand(1) + 0.5\n    net.layers[0] = layer\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_shortcut():\n    \"\"\"test shortcut layer\"\"\"\n    net = LIB.make_network(3)\n    layer_1 = LIB.make_convolutional_layer(1, 224, 224, 3, 32, 1, 3, 2, 0, 1, 0, 0, 0, 0)\n    layer_2 = LIB.make_convolutional_layer(1, 111, 111, 32, 32, 1, 1, 1, 0, 1, 0, 0, 0, 0)\n    layer_3 = LIB.make_shortcut_layer(1, 0, 111, 111, 32, 111, 111, 32)\n    layer_3.activation = ACTIVATION.RELU\n    layer_3.alpha = 1\n    layer_3.beta = 1\n    net.layers[0] = layer_1\n    net.layers[1] = layer_2\n    net.layers[2] = layer_3\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_reorg():\n    \"\"\"test reorg layer\"\"\"\n    net = LIB.make_network(2)\n    layer_1 = LIB.make_convolutional_layer(1, 222, 222, 3, 32, 1, 3, 2, 0, 1, 0, 0, 0, 0)\n    layer_2 = LIB.make_reorg_layer(1, 110, 110, 32, 2, 0, 0, 0)\n    net.layers[0] = layer_1\n    net.layers[1] = layer_2\n    net.w = net.h = 222\n    LIB.resize_network(net, 222, 222)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_region():\n    \"\"\"test region layer\"\"\"\n    net = LIB.make_network(2)\n    layer_1 = LIB.make_convolutional_layer(1, 19, 19, 3, 425, 1, 1, 1, 0, 1, 0, 0, 0, 0)\n    layer_2 = LIB.make_region_layer(1, 19, 19, 5, 80, 4)\n    layer_2.softmax = 1\n    net.layers[0] = layer_1\n    net.layers[1] = layer_2\n    net.w = net.h = 19\n    LIB.resize_network(net, 19, 19)\n    build_dtype = {}\n    verify_darknet_frontend(net, build_dtype)\n    LIB.free_network(net)\n\n\ndef test_forward_yolo_op():\n    \"\"\"test yolo layer\"\"\"\n    net = LIB.make_network(2)\n    layer_1 = LIB.make_convolutional_layer(1, 224, 224, 3, 14, 1, 3, 2, 0, 1, 0, 0, 0, 0)\n    layer_2 = LIB.make_yolo_layer(1, 111, 111, 2, 9, __darknetffi__.NULL, 2)\n    net.layers[0] = layer_1\n    net.layers[1] = layer_2\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    build_dtype = {}\n    verify_darknet_frontend(net, build_dtype)\n    LIB.free_network(net)\n\n\ndef test_forward_upsample():\n    \"\"\"test upsample layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_upsample_layer(1, 19, 19, 3, 3)\n    layer.scale = 1\n    net.layers[0] = layer\n    net.w = net.h = 19\n    LIB.resize_network(net, 19, 19)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_l2normalize():\n    \"\"\"test l2 normalization layer\"\"\"\n    net = LIB.make_network(1)\n    layer = LIB.make_l2norm_layer(1, 224 * 224 * 3)\n    layer.c = layer.out_c = 3\n    layer.h = layer.out_h = 224\n    layer.w = layer.out_w = 224\n    net.layers[0] = layer\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_elu():\n    \"\"\"test elu activation layer\"\"\"\n    net = LIB.make_network(1)\n    layer_1 = LIB.make_convolutional_layer(1, 224, 224, 3, 32, 1, 3, 2, 0, 1, 0, 0, 0, 0)\n    layer_1.activation = ACTIVATION.ELU\n    net.layers[0] = layer_1\n    net.w = net.h = 224\n    LIB.resize_network(net, 224, 224)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_softmax():\n    \"\"\"test softmax layer\"\"\"\n    net = LIB.make_network(1)\n    layer_1 = LIB.make_softmax_layer(1, 75, 1)\n    layer_1.temperature = 1\n    net.layers[0] = layer_1\n    net.w = net.h = 5\n    LIB.resize_network(net, net.w, net.h)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_softmax_temperature():\n    \"\"\"test softmax layer\"\"\"\n    net = LIB.make_network(1)\n    layer_1 = LIB.make_softmax_layer(1, 75, 1)\n    layer_1.temperature = 0.8\n    net.layers[0] = layer_1\n    net.w = net.h = 5\n    LIB.resize_network(net, net.w, net.h)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_activation_logistic():\n    \"\"\"test logistic activation layer\"\"\"\n    net = LIB.make_network(1)\n    batch = 1\n    h = 224\n    width = 224\n    c = 3\n    n = 32\n    groups = 1\n    size = 3\n    stride = 2\n    padding = 0\n    activation = ACTIVATION.LOGISTIC\n    batch_normalize = 0\n    binary = 0\n    xnor = 0\n    adam = 0\n    layer_1 = LIB.make_convolutional_layer(\n        batch,\n        h,\n        width,\n        c,\n        n,\n        groups,\n        size,\n        stride,\n        padding,\n        activation,\n        batch_normalize,\n        binary,\n        xnor,\n        adam,\n    )\n    net.layers[0] = layer_1\n    net.w = width\n    net.h = h\n    LIB.resize_network(net, net.w, net.h)\n    verify_darknet_frontend(net)\n    LIB.free_network(net)\n\n\ndef test_forward_rnn():\n    \"\"\"test RNN layer\"\"\"\n    net = LIB.make_network(1)\n    batch = 1\n    inputs = 4\n    outputs = 4\n    steps = 1\n    activation = ACTIVATION.RELU\n    batch_normalize = 0\n    adam = 0\n    layer_1 = LIB.make_rnn_layer(batch, inputs, outputs, steps, activation, batch_normalize, adam)\n    net.layers[0] = layer_1\n    net.inputs = inputs\n    net.outputs = outputs\n    net.w = net.h = 0\n    LIB.resize_network(net, net.w, net.h)\n    states = {\"rnn0_state\": np.zeros([1, net.inputs])}\n    _test_rnn_network(net, states)\n    LIB.free_network(net)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/keras/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for various models and operators\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nimport tvm.testing\n\ntry:\n    import tensorflow.compat.v1 as tf\nexcept ImportError:\n    import tensorflow as tf\n\nfrom tensorflow import keras as tf_keras\n\n# prevent Keras from using up all gpu memory\nimport keras\n\nif tf.executing_eagerly():\n    GPUS = tf.config.experimental.list_physical_devices(\"GPU\")\n    for gpu in GPUS:\n        tf.config.experimental.set_memory_growth(gpu, True)\nelse:\n    from keras.backend.tensorflow_backend import set_session\n\n    CONFIG = tf.ConfigProto()\n    CONFIG.gpu_options.per_process_gpu_memory_fraction = 0.5\n    set_session(tf.Session(config=CONFIG))\n\n\ndef pytest_generate_tests(metafunc):\n    \"\"\"\n    This function generates the list of tests for pytest, based\n    on scenarios that will change the parameters in which the\n    tests use to run.\n    https://docs.pytest.org/en/latest/example/parametrize.html\n    \"\"\"\n    idlist = []\n    argvalues = []\n    for scenario in metafunc.cls.scenarios:\n        idlist.append(scenario[0])\n        items = scenario[1].items()\n        argnames = [x[0] for x in items]\n        argvalues.append([x[1] for x in items])\n    metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n\n# Scenarios:\n# - classic keras, using keras from \"import keras\"\n# - tensorflow keras, using keras from \"from tensorflow import keras as tf_keras\"\nUSING_CALSSIC_KERAS = (\"keras\", {\"keras_mod\": keras})\nUSING_TENSORFLOW_KERAS = (\"tf_keras\", {\"keras_mod\": tf_keras})\n\n\ndef verify_keras_frontend(keras_model, need_transpose=True, layout=\"NCHW\"):\n    \"\"\"Generic function to generate and compare Keras and TVM output\"\"\"\n    # Keras frontend currently supports tensorflow backend only.\n    assert keras.backend.backend() == \"tensorflow\"\n\n    if layout != \"NCHW\":\n        need_transpose = False\n\n    in_shapes = []\n    for layer in keras_model._input_layers:\n        if tf.executing_eagerly():\n            in_shapes.append(tuple(dim if dim is not None else 1 for dim in layer.input.shape))\n        else:\n            in_shapes.append(\n                tuple(dim.value if dim.value is not None else 1 for dim in layer.input.shape)\n            )\n\n    def get_keras_output(in_data):\n        return keras_model.predict(in_data)\n\n    def get_tvm_output(in_data, target, dev, dtype=\"float32\"):\n        shape_dict = {name: x.shape for (name, x) in zip(keras_model.input_names, in_data)}\n        mod, params = relay.frontend.from_keras(keras_model, shape_dict, layout=layout)\n        with tvm.transform.PassContext(opt_level=2):\n            lib = relay.build(mod, target, params=params)\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        for name, x in zip(keras_model.input_names, in_data):\n            m.set_input(name, tvm.nd.array(x.astype(dtype)))\n        m.run()\n        return [m.get_output(i).numpy() for i in range(m.get_num_outputs())]\n\n    def to_channels_first(arr):\n        return arr.transpose([0, -1] + list(range(1, arr.ndim - 1)))\n\n    def to_channels_last(arr):\n        return arr.transpose([0] + list(range(2, arr.ndim)) + [1])\n\n    in_data = [np.random.uniform(size=shape, low=-1.0, high=1.0) for shape in in_shapes]\n    keras_out = get_keras_output(in_data)\n    keras_out = keras_out if isinstance(keras_out, list) else [keras_out]\n    for target, dev in tvm.testing.enabled_targets():\n        inputs = [to_channels_first(x) for x in in_data] if need_transpose else in_data\n        tvm_out = get_tvm_output(inputs, target, dev)\n        for kout, tout in zip(keras_out, tvm_out):\n            if need_transpose:\n                tout = to_channels_last(tout)\n            tvm.testing.assert_allclose(kout, tout, rtol=1e-5, atol=1e-5)\n\n\ndef get_mobilenet(keras_mod):\n    if hasattr(keras_mod.applications, \"MobileNet\"):\n        # Keras 2.4.x and older\n        mobilenet_mod = keras_mod.applications.MobileNet\n    else:\n        # Keras 2.6.x and newer\n        mobilenet_mod = keras_mod.applications.mobilenet.MobileNet\n\n    return mobilenet_mod\n\n\n@tvm.testing.uses_gpu\nclass TestKeras:\n    \"\"\"Keras test\"\"\"\n\n    scenarios = [USING_CALSSIC_KERAS, USING_TENSORFLOW_KERAS]\n\n    def test_forward_merge(self, keras_mod):\n        \"\"\"test_forward_merge\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        conv2d_x = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n        conv2d_y = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(conv2d_x)\n        conv2d_z = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(conv2d_y)\n        merge_funcs = [\n            keras_mod.layers.Add(),\n            keras_mod.layers.Subtract(),\n            keras_mod.layers.Multiply(),\n            keras_mod.layers.Maximum(),\n            keras_mod.layers.Minimum(),\n            keras_mod.layers.Average(),\n            keras_mod.layers.Concatenate(),\n        ]\n        for merge_func in merge_funcs:\n            class_name = type(merge_func).__name__\n            if class_name in (\"Subtract\", \"Dot\"):\n                out = merge_func([conv2d_x, conv2d_y])\n            else:\n                out = merge_func([conv2d_x, conv2d_y, conv2d_z])\n            keras_model = keras_mod.models.Model(data, out)\n            verify_keras_frontend(keras_model)\n\n    def test_forward_merge_dot(self, keras_mod):\n        \"\"\"test_forward_merge_dot\"\"\"\n        data1 = keras_mod.layers.Input(shape=(2, 2))\n        data2 = keras_mod.layers.Input(shape=(2, 2))\n        merge_funcs = [\n            keras_mod.layers.Dot(axes=[1, 2]),\n            keras_mod.layers.Dot(axes=[2, 1]),\n            keras_mod.layers.Dot(axes=[1, 1]),\n            keras_mod.layers.Dot(axes=[2, 2]),\n            keras_mod.layers.Dot(axes=1),\n            keras_mod.layers.Dot(axes=2),\n        ]\n        for merge_func in merge_funcs:\n            out = merge_func([data1, data2])\n            keras_model = keras_mod.models.Model([data1, data2], out)\n            verify_keras_frontend(keras_model)\n\n    def test_forward_activations(self, keras_mod):\n        \"\"\"test_forward_activations\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        act_funcs = [\n            keras_mod.layers.Activation(\"softmax\"),\n            keras_mod.layers.Softmax(),\n            keras_mod.layers.Softmax(axis=-1),\n            keras_mod.layers.Softmax(axis=1),\n            keras_mod.layers.Softmax(axis=2),\n            keras_mod.layers.Softmax(axis=3),\n            keras_mod.layers.Activation(\"softplus\"),\n            keras_mod.layers.Activation(\"relu\"),\n            keras_mod.layers.Activation(\"softsign\"),\n            keras_mod.layers.Activation(\"hard_sigmoid\"),\n            keras_mod.layers.Activation(\"sigmoid\"),\n            keras_mod.layers.Activation(\"tanh\"),\n            keras_mod.layers.Activation(\"linear\"),\n            keras_mod.layers.Activation(\"selu\"),\n            keras_mod.layers.ReLU(),\n            keras_mod.layers.ReLU(max_value=6.0),\n            keras_mod.layers.ReLU(max_value=6.0, threshold=0.0),\n            keras_mod.layers.ReLU(max_value=6.0, threshold=1.0),\n            keras_mod.layers.ReLU(max_value=6.0, threshold=1.0, negative_slope=0.0),\n            keras_mod.layers.ReLU(max_value=6.0, threshold=1.0, negative_slope=0.5),\n            keras_mod.layers.ReLU(max_value=6.0, threshold=1.0, negative_slope=1.0),\n            keras_mod.layers.LeakyReLU(alpha=0.3),\n            keras_mod.layers.PReLU(weights=np.random.rand(1, 32, 32, 3)),\n            keras_mod.layers.ELU(alpha=0.5),\n            keras_mod.layers.ThresholdedReLU(theta=0.5),\n        ]\n        for act_func in act_funcs:\n            x = act_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model)\n            verify_keras_frontend(keras_model, need_transpose=False, layout=\"NHWC\")\n\n    def test_forward_dense(self, keras_mod):\n        \"\"\"test_forward_dense\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 1))\n        x = keras_mod.layers.Flatten()(data)\n        x = keras_mod.layers.Dropout(0.5)(x)\n        x = keras_mod.layers.Dense(10, activation=\"relu\", kernel_initializer=\"uniform\")(x)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n        # RNN dense\n        data = keras_mod.layers.Input(shape=(1, 32))\n        x = keras_mod.layers.Dense(32, activation=\"relu\", kernel_initializer=\"uniform\")(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_permute(self, keras_mod):\n        data = keras_mod.layers.Input(shape=(2, 3, 4))\n        x = keras_mod.layers.Permute([2, 3, 1])(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_sequential(self, keras_mod):\n        \"\"\"test_forward_sequential\"\"\"\n        keras_model = keras_mod.models.Sequential(\n            [\n                keras_mod.layers.Dense(16, input_dim=32, activation=\"relu\"),\n                keras_mod.layers.Dropout(0.5),\n                keras_mod.layers.Dense(8, activation=\"relu\"),\n                keras_mod.layers.Dropout(0.5),\n                keras_mod.layers.Dense(1, activation=\"sigmoid\"),\n            ]\n        )\n        verify_keras_frontend(keras_model)\n\n    def test_forward_pool(self, keras_mod):\n        data = keras_mod.layers.Input(shape=(32, 32, 1))\n        # maxpool\n        x = keras_mod.layers.MaxPooling2D((3, 3), strides=(1, 1), padding=\"same\")(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n        # avgpool\n        y = keras_mod.layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(data)\n        keras_model = keras_mod.models.Model(data, y)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_conv1d(self, keras_mod):\n        \"\"\"test_forward_conv1d\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 3))\n        conv_funcs = [\n            keras_mod.layers.Conv1D(filters=10, kernel_size=(3,), strides=(2,), padding=\"same\"),\n            keras_mod.layers.Conv1D(\n                filters=10, kernel_size=(3,), dilation_rate=(2,), padding=\"same\"\n            ),\n            keras_mod.layers.Conv1D(filters=1, kernel_size=(3,), padding=\"valid\", use_bias=False),\n            keras_mod.layers.Conv1D(filters=10, kernel_size=(2,), padding=\"valid\"),\n            # Enable when relay conv1dtranspose handles NWC\n            # keras.layers.Conv1DTranspose(filters=10, kernel_size=(3), padding=\"valid\"),\n        ]\n        for conv_func in conv_funcs:\n            x = conv_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NWC\")\n\n    def test_forward_conv(self, keras_mod):\n        \"\"\"test_forward_conv\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        conv_funcs = [\n            keras_mod.layers.Conv2D(filters=10, kernel_size=(3, 3), strides=(2, 2), padding=\"same\"),\n            keras_mod.layers.Conv2D(\n                filters=10, kernel_size=(3, 3), dilation_rate=(2, 2), padding=\"same\"\n            ),\n            keras_mod.layers.Conv2D(filters=1, kernel_size=(3, 3), padding=\"same\"),\n            keras_mod.layers.DepthwiseConv2D(kernel_size=(3, 3), padding=\"same\"),\n            keras_mod.layers.Conv2DTranspose(filters=10, kernel_size=(3, 3), padding=\"valid\"),\n            keras_mod.layers.SeparableConv2D(filters=10, kernel_size=(3, 3), padding=\"same\"),\n        ]\n        for conv_func in conv_funcs:\n            x = conv_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model)\n\n    def test_forward_batch_norm(self, keras_mod):\n        \"\"\"test_forward_batch_norm\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        batch_norm_funcs = [\n            keras_mod.layers.BatchNormalization(\n                axis=-1,\n                momentum=0.99,\n                epsilon=0.001,\n                center=True,\n                scale=False,\n                beta_initializer=\"zeros\",\n                gamma_initializer=\"ones\",\n                moving_mean_initializer=\"zeros\",\n                moving_variance_initializer=\"ones\",\n            ),\n            keras_mod.layers.BatchNormalization(\n                axis=-1,\n                momentum=0.99,\n                epsilon=0.001,\n                center=True,\n                scale=True,\n                beta_initializer=\"zeros\",\n                gamma_initializer=\"ones\",\n                moving_mean_initializer=\"zeros\",\n                moving_variance_initializer=\"ones\",\n            ),\n            keras_mod.layers.BatchNormalization(\n                axis=-1,\n                momentum=0.99,\n                epsilon=0.001,\n                center=False,\n                scale=True,\n                beta_initializer=\"zeros\",\n                gamma_initializer=\"ones\",\n                moving_mean_initializer=\"zeros\",\n                moving_variance_initializer=\"ones\",\n            ),\n            keras_mod.layers.BatchNormalization(\n                axis=-1,\n                momentum=0.99,\n                epsilon=0.001,\n                center=False,\n                scale=False,\n                beta_initializer=\"zeros\",\n                gamma_initializer=\"ones\",\n                moving_mean_initializer=\"zeros\",\n                moving_variance_initializer=\"ones\",\n            ),\n        ]\n        for batch_norm_func in batch_norm_funcs:\n            x = batch_norm_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_upsample(self, keras_mod, interpolation=\"nearest\"):\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.UpSampling2D(size=(3, 3), interpolation=interpolation)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_reshape(self, keras_mod):\n        \"\"\"test_forward_reshape\"\"\"\n        # input_shape len is 3, target_shape len is 3\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.Reshape(target_shape=(16, 64, 3))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n        # input_shape len is 3, target_shape len is 2\n        data = keras_mod.layers.Input(shape=(32, 8, 3))\n        x = keras_mod.layers.Reshape(target_shape=(256, 3))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n        # input_shape len is 2, target_shape len is 3\n        data = keras_mod.layers.Input(shape=(256, 3))\n        x = keras_mod.layers.Reshape(target_shape=(8, 32, 3))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n        # input_shape len is 2, target_shape len is 1\n        data = keras_mod.layers.Input(shape=(2, 8))\n        x = keras_mod.layers.Reshape(target_shape=(16,))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n        # input_shape len is 1, target_shape len is 2\n        data = keras_mod.layers.Input(shape=(16,))\n        x = keras_mod.layers.Reshape(target_shape=(4, 4))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n        # input_shape len is 2, target_shape len is 2\n        data = keras_mod.layers.Input(shape=(2, 8))\n        x = keras_mod.layers.Reshape(target_shape=(4, 4))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n        # \"non-square\" target shape\n        data = keras_mod.layers.Input(shape=(15,))\n        x = keras_mod.layers.Reshape(target_shape=(5, 3))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n        # modify channel dim\n        data = keras_mod.layers.Input(shape=(3, 2, 4))\n        x = keras_mod.layers.Reshape(target_shape=(3, 8))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_crop(self, keras_mod):\n        \"\"\"test_forward_crop\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.Cropping2D(cropping=((1, 1), (1, 1)))(data)\n        x = keras_mod.layers.Cropping2D(cropping=(1, 1))(x)\n        x = keras_mod.layers.Cropping2D(cropping=1)(x)\n        x = keras_mod.layers.Cropping2D(cropping=((0, 1), (1, 0)))(x)\n        x = keras_mod.layers.Cropping2D(cropping=(1, 0))(x)\n        x = keras_mod.layers.Cropping2D(cropping=0)(x)\n        x = keras_mod.layers.Add()([x, x])\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_multi_inputs(self, keras_mod):\n        data1 = keras_mod.layers.Input(shape=(32, 32, 3))\n        data2 = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data1)\n        y = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data2)\n        average_z = keras_mod.layers.Average()([x, y])\n        out = keras_mod.layers.GlobalAveragePooling2D()(average_z)\n        keras_model = keras_mod.models.Model([data1, data2], out)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_multi_outputs(self, keras_mod):\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n        x = keras_mod.layers.GlobalAveragePooling2D()(x)\n        y = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n        y = keras_mod.layers.GlobalAveragePooling2D()(y)\n        keras_model = keras_mod.models.Model(data, [x, y])\n        verify_keras_frontend(keras_model)\n\n    def test_forward_reuse_layers(self, keras_mod):\n        \"\"\"test_forward_reuse_layers\"\"\"\n        # reuse conv2d\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        conv2d = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")\n        x = conv2d(data)\n        y = conv2d(data)\n        add_z = keras_mod.layers.Add()([x, y])\n        out = keras_mod.layers.GlobalAveragePooling2D()(add_z)\n        keras_model = keras_mod.models.Model(data, out)\n        verify_keras_frontend(keras_model)\n        # reuse add\n        data = keras_mod.layers.Input(shape=(32, 32, 3))\n        x = keras_mod.layers.Conv2D(8, (3, 3), padding=\"same\")(data)\n        add = keras_mod.layers.Add()\n        x = add([x, x])\n        x = add([x, x])\n        out = keras_mod.layers.GlobalAveragePooling2D()(x)\n        keras_model = keras_mod.models.Model(data, out)\n        verify_keras_frontend(keras_model)\n\n    def test_forward_lstm(self, keras_mod):\n        \"\"\"test_forward_lstm\"\"\"\n        data = keras_mod.layers.Input(shape=(10, 32))\n        rnn_funcs = [\n            keras_mod.layers.LSTM(16),\n            keras_mod.layers.LSTM(16, return_sequences=True),\n            keras_mod.layers.LSTM(16, return_sequences=True, use_bias=False),\n        ]\n        for rnn_func in rnn_funcs:\n            x = rnn_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_rnn(self, keras_mod):\n        \"\"\"test_forward_rnn\"\"\"\n        data = keras_mod.layers.Input(shape=(1, 32))\n        rnn_funcs = [\n            keras_mod.layers.LSTM(\n                units=16, return_state=False, recurrent_activation=\"sigmoid\", activation=\"tanh\"\n            ),\n            keras_mod.layers.LSTM(\n                units=16,\n                return_state=False,\n                recurrent_activation=\"sigmoid\",\n                activation=\"tanh\",\n                use_bias=False,\n            ),\n            keras_mod.layers.SimpleRNN(units=16, return_state=False, activation=\"tanh\"),\n            keras_mod.layers.SimpleRNN(\n                units=16, return_state=False, activation=\"tanh\", use_bias=False\n            ),\n            keras_mod.layers.GRU(\n                units=16,\n                return_state=False,\n                recurrent_activation=\"sigmoid\",\n                activation=\"tanh\",\n                reset_after=False,\n            ),\n            keras_mod.layers.GRU(\n                units=16,\n                return_state=False,\n                recurrent_activation=\"sigmoid\",\n                activation=\"tanh\",\n                reset_after=False,\n                use_bias=False,\n            ),\n        ]\n        for rnn_func in rnn_funcs:\n            x = rnn_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_vgg16(self, keras_mod, layout=\"NCHW\"):\n        \"\"\"test_forward_vgg16\"\"\"\n        if hasattr(keras_mod.applications, \"VGG16\"):\n            # Keras 2.4.x and older\n            vgg16_mod = keras_mod.applications.VGG16\n        else:\n            # Keras 2.6.x and newer\n            vgg16_mod = keras_mod.applications.vgg16.VGG16\n\n        keras_model = vgg16_mod(\n            include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000\n        )\n        verify_keras_frontend(keras_model, layout=layout)\n\n    def test_forward_xception(self, keras_mod, layout=\"NCHW\"):\n        \"\"\"test_forward_vgg16\"\"\"\n        if hasattr(keras_mod.applications, \"Xception\"):\n            # Keras 2.4.x and older\n            xception_mod = keras_mod.applications.Xception\n        else:\n            # Keras 2.6.x and newer\n            xception_mod = keras_mod.applications.xception.Xception\n\n        keras_model = xception_mod(\n            include_top=True, weights=\"imagenet\", input_shape=(299, 299, 3), classes=1000\n        )\n        verify_keras_frontend(keras_model, layout=layout)\n\n    def test_forward_resnet50(self, keras_mod, layout=\"NCHW\"):\n        \"\"\"test_forward_resnet50\"\"\"\n        if hasattr(keras_mod.applications, \"ResNet50\"):\n            # Keras 2.4.x and older\n            resnet50_mod = keras_mod.applications.ResNet50\n        else:\n            # Keras 2.6.x and newer\n            resnet50_mod = keras_mod.applications.resnet.ResNet50\n\n        keras_model = resnet50_mod(\n            include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000\n        )\n        verify_keras_frontend(keras_model, layout=layout)\n\n    def test_forward_mobilenet(self, keras_mod, layout=\"NCHW\"):\n        mobilenet_mod = get_mobilenet(keras_mod)\n\n        keras_model = mobilenet_mod(\n            include_top=True, weights=\"imagenet\", input_shape=(224, 224, 3), classes=1000\n        )\n        verify_keras_frontend(keras_model, layout=layout)\n\n    def test_forward_conv3d(self, keras_mod):\n        \"\"\"test_forward_conv3d\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 3))\n        conv_funcs = [\n            keras_mod.layers.Conv3D(\n                filters=10, kernel_size=(3, 3, 3), strides=(2, 2, 2), padding=\"same\"\n            ),\n            keras_mod.layers.Conv3D(\n                filters=10, kernel_size=(3, 3, 3), dilation_rate=(2, 2, 2), padding=\"same\"\n            ),\n            keras_mod.layers.Conv3D(\n                filters=1, kernel_size=(3, 3, 3), padding=\"valid\", use_bias=False\n            ),\n            keras_mod.layers.Conv3D(filters=10, kernel_size=(2, 2, 2), padding=\"valid\"),\n        ]\n        for conv_func in conv_funcs:\n            x = conv_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_conv3d_transpose(self, keras_mod):\n        \"\"\"test_forward_conv3d_transpose\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 3))\n        conv_funcs = [\n            keras_mod.layers.Conv3DTranspose(\n                filters=10, kernel_size=(3, 3, 3), strides=(2, 2, 2), padding=\"same\"\n            ),\n            keras_mod.layers.Conv3DTranspose(\n                filters=10, kernel_size=(1, 1, 1), dilation_rate=(1, 1, 1), padding=\"same\"\n            ),\n            keras_mod.layers.Conv3DTranspose(\n                filters=1, kernel_size=(3, 3, 3), padding=\"valid\", use_bias=False\n            ),\n            keras_mod.layers.Conv3DTranspose(filters=10, kernel_size=(2, 2, 2), padding=\"valid\"),\n        ]\n        for conv_func in conv_funcs:\n            x = conv_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_pool3d(self, keras_mod):\n        \"\"\"test_forward_pool3d\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 1))\n        pool_funcs = [  # maxpool\n            keras_mod.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding=\"same\"),\n            keras_mod.layers.MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2), padding=\"valid\"),\n            # avgpool\n            keras_mod.layers.AveragePooling3D(\n                pool_size=(3, 3, 3), strides=(2, 2, 2), padding=\"same\"\n            ),\n            keras_mod.layers.AveragePooling3D(\n                pool_size=(2, 2, 2), strides=(1, 1, 1), padding=\"valid\"\n            ),\n        ]\n        for pool_func in pool_funcs:\n            x = pool_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_upsample3d(self, keras_mod):\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 3))\n        x = keras_mod.layers.UpSampling3D(size=(2, 3, 4))(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_zero_padding3d(self, keras_mod):\n        \"\"\"test_forward_zero_padding3d\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 3))\n        pad_funcs = [  # Integer\n            keras_mod.layers.ZeroPadding3D(padding=2),\n            # tuple of 3 ints\n            keras_mod.layers.ZeroPadding3D(padding=(1, 2, 3)),\n            # tuple of 3 tuples of 2 ints\n            keras_mod.layers.ZeroPadding3D(padding=((1, 1), (2, 2), (2, 2))),\n            # tuple of 3 tuples of 2 ints different values\n            keras_mod.layers.ZeroPadding3D(padding=((1, 2), (2, 3), (3, 2))),\n        ]\n        for pad_func in pad_funcs:\n            x = pad_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_embedding(self, keras_mod):\n        \"\"\"test_forward_embedding\"\"\"\n        data = keras_mod.layers.Input(shape=(2, 4), dtype=\"int32\")\n        x = keras_mod.layers.Embedding(10, 3)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n        data = keras_mod.layers.Input(shape=(2, 3, 4), dtype=\"int32\")\n        x = keras_mod.layers.Embedding(4, 5)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n        data = keras_mod.layers.Input(shape=(6, 2, 3, 4), dtype=\"int32\")\n        x = keras_mod.layers.Embedding(4, 5)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_repeat_vector(self, keras_mod):\n        \"\"\"test_forward_repeat_vector\"\"\"\n        data = keras_mod.layers.Input(shape=(5,), dtype=\"float32\")\n        x = keras_mod.layers.Dense(6)(data)\n        x = keras_mod.layers.RepeatVector(2)(x)\n\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n        data = keras_mod.layers.Input(shape=(10,), dtype=\"float32\")\n        x = keras_mod.layers.RepeatVector(3)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n        data = keras_mod.layers.Input(shape=(4,), dtype=\"float32\")\n        x = keras_mod.layers.RepeatVector(1)(data)\n        keras_model = keras_mod.models.Model(data, x)\n        verify_keras_frontend(keras_model, need_transpose=False)\n\n    def test_forward_global_pool3d(self, keras_mod):\n        \"\"\"test_forward_zero_padding3d\"\"\"\n        data = keras_mod.layers.Input(shape=(32, 32, 32, 1))\n        pool_funcs = [  # global maxpool\n            keras_mod.layers.GlobalMaxPooling3D(),\n            # global avgpool\n            keras_mod.layers.GlobalAveragePooling3D(),\n        ]\n        for pool_func in pool_funcs:\n            x = pool_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NDHWC\")\n\n    def test_forward_nested_layers(self, keras_mod):\n        \"\"\"test_forward_nested_layers\"\"\"\n        mobilenet_mod = get_mobilenet(keras_mod)\n\n        sub_model = mobilenet_mod(include_top=False, weights=\"imagenet\", input_shape=(224, 224, 3))\n        keras_model = keras_mod.Sequential(\n            [\n                sub_model,\n                keras_mod.layers.GlobalAveragePooling2D(),\n                keras_mod.layers.Dense(1024, activation=\"relu\"),\n                keras_mod.layers.Dense(2, activation=\"sigmoid\"),\n            ]\n        )\n        verify_keras_frontend(keras_model)\n\n    def test_forward_l2_normalize(self, keras_mod):\n        \"\"\"test_forward_l2_normalize\"\"\"\n        data = keras_mod.layers.Input(shape=(16, 12, 8))\n        k_backend = keras_mod.backend\n        l2_funcs = [\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, axis=-2)),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(x=v, axis=-1)),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(axis=1, x=v)),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, 2)),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, axis=3)),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, axis=(2, 3))),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, (1, 2))),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, axis=[-2, -1])),\n            keras_mod.layers.Lambda(lambda v: k_backend.l2_normalize(v, [-3, -2])),\n        ]\n        for l2_func in l2_funcs:\n            x = l2_func(data)\n            keras_model = keras_mod.models.Model(data, x)\n            verify_keras_frontend(keras_model, layout=\"NCHW\")\n            verify_keras_frontend(keras_model, layout=\"NHWC\")\n\n    def test_forward_time_distributed(self, keras_mod):\n        \"\"\"test_forward_time_distributed\"\"\"\n        conv2d_inputs = keras_mod.Input(shape=(10, 128, 128, 3))\n        conv_2d_layer = keras_mod.layers.Conv2D(64, (3, 3))\n        conv2d_model = keras_mod.models.Model(\n            conv2d_inputs, keras_mod.layers.TimeDistributed(conv_2d_layer)(conv2d_inputs)\n        )\n        verify_keras_frontend(conv2d_model, layout=\"NDHWC\")\n\n        dense_inputs = keras_mod.Input(shape=(5, 1))\n        dense_layer = keras_mod.layers.Dense(1)\n        dense_model = keras_mod.models.Model(\n            dense_inputs, keras_mod.layers.TimeDistributed(dense_layer)(dense_inputs)\n        )\n        verify_keras_frontend(dense_model, need_transpose=False)\n\n\nif __name__ == \"__main__\":\n    for k in [keras, tf_keras]:\n        sut = TestKeras()\n        sut.test_forward_merge_dot(keras_mod=k)\n        sut.test_forward_merge(keras_mod=k)\n        sut.test_forward_activations(keras_mod=k)\n        sut.test_forward_dense(keras_mod=k)\n        sut.test_forward_permute(keras_mod=k)\n        sut.test_forward_sequential(keras_mod=k)\n        sut.test_forward_pool(keras_mod=k)\n        sut.test_forward_conv(keras_mod=k)\n        sut.test_forward_conv1d(keras_mod=k)\n        sut.test_forward_batch_norm(keras_mod=k)\n        sut.test_forward_upsample(keras_mod=k, interpolation=\"nearest\")\n        sut.test_forward_upsample(keras_mod=k, interpolation=\"bilinear\")\n        sut.test_forward_reshape(keras_mod=k)\n        sut.test_forward_crop(keras_mod=k)\n        sut.test_forward_multi_inputs(keras_mod=k)\n        sut.test_forward_multi_outputs(keras_mod=k)\n        sut.test_forward_reuse_layers(keras_mod=k)\n        sut.test_forward_lstm(keras_mod=k)\n        sut.test_forward_rnn(keras_mod=k)\n        sut.test_forward_vgg16(keras_mod=k)\n        sut.test_forward_vgg16(keras_mod=k, layout=\"NHWC\")\n        sut.test_forward_xception(keras_mod=k)\n        sut.test_forward_resnet50(keras_mod=k)\n        sut.test_forward_resnet50(keras_mod=k, layout=\"NHWC\")\n        sut.test_forward_mobilenet(keras_mod=k)\n        sut.test_forward_mobilenet(keras_mod=k, layout=\"NHWC\")\n        sut.test_forward_conv3d(keras_mod=k)\n        sut.test_forward_conv3d_transpose(keras_mod=k)\n        sut.test_forward_pool3d(keras_mod=k)\n        sut.test_forward_global_pool3d(keras_mod=k)\n        sut.test_forward_upsample3d(keras_mod=k)\n        sut.test_forward_zero_padding3d(keras_mod=k)\n        sut.test_forward_embedding(keras_mod=k)\n        sut.test_forward_repeat_vector(keras_mod=k)\n        sut.test_forward_l2_normalize(keras_mod=k)\n        sut.test_forward_time_distributed(keras_mod=k)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"MXNet model zoo for testing purposes.\"\"\"\nfrom __future__ import absolute_import\nfrom . import mlp, vgg, resnet, dqn, inception_v3, squeezenet, dcgan\nimport tvm.relay.testing\n\n# mlp\ndef mx_mlp():\n    num_class = 10\n    return mlp.get_symbol(num_class)\n\n\ndef relay_mlp():\n    num_class = 10\n    return tvm.relay.testing.mlp.get_workload(1, num_class)[0]\n\n\n# vgg\ndef mx_vgg(num_layers):\n    num_class = 1000\n    return vgg.get_symbol(num_class, num_layers)\n\n\ndef relay_vgg(num_layers):\n    num_class = 1000\n    return tvm.relay.testing.vgg.get_workload(1, num_class, num_layers=num_layers)[0]\n\n\n# resnet\ndef mx_resnet(num_layers):\n    num_class = 1000\n    return resnet.get_symbol(num_class, num_layers, \"3,224,224\")\n\n\ndef relay_resnet(num_layers):\n    num_class = 1000\n    return tvm.relay.testing.resnet.get_workload(1, num_class, num_layers=num_layers)[0]\n\n\n# dqn\nmx_dqn = dqn.get_symbol\n\n\ndef relay_dqn():\n    return tvm.relay.testing.dqn.get_workload(1)[0]\n\n\n# squeezenet\ndef mx_squeezenet(version):\n    return squeezenet.get_symbol(version=version)\n\n\ndef relay_squeezenet(version):\n    return tvm.relay.testing.squeezenet.get_workload(1, version=version)[0]\n\n\n# inception\nmx_inception_v3 = inception_v3.get_symbol\n\n\ndef relay_inception_v3():\n    return tvm.relay.testing.inception_v3.get_workload(1)[0]\n\n\n# dcgan generator\nmx_dcgan = dcgan.get_symbol\n\n\ndef relay_dcgan(batch_size):\n    return tvm.relay.testing.dcgan.get_workload(batch_size=batch_size)[0]\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/dcgan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"\nThe MXNet symbol of DCGAN generator\n\nAdopted from:\nhttps://github.com/tqchen/mxnet-gan/blob/main/mxgan/generator.py\n\nReference:\nRadford, Alec, Luke Metz, and Soumith Chintala.\n\"Unsupervised representation learning with deep convolutional generative adversarial networks.\"\narXiv preprint arXiv:1511.06434 (2015).\n\"\"\"\n\nimport mxnet as mx\n\n\ndef deconv2d(data, ishape, oshape, kshape, name, stride=(2, 2)):\n    \"\"\"a deconv layer that enlarges the feature map\"\"\"\n    target_shape = (oshape[-2], oshape[-1])\n    pad_y = (kshape[0] - 1) // 2\n    pad_x = (kshape[1] - 1) // 2\n    adj_y = (target_shape[0] + 2 * pad_y - kshape[0]) % stride[0]\n    adj_x = (target_shape[1] + 2 * pad_x - kshape[1]) % stride[1]\n\n    net = mx.sym.Deconvolution(\n        data,\n        kernel=kshape,\n        stride=stride,\n        pad=(pad_y, pad_x),\n        adj=(adj_y, adj_x),\n        num_filter=oshape[0],\n        no_bias=True,\n        name=name,\n    )\n    return net\n\n\ndef deconv2d_bn_relu(data, prefix, **kwargs):\n    \"\"\"a block of deconv + batch norm + relu\"\"\"\n    eps = 1e-5 + 1e-12\n\n    net = deconv2d(data, name=\"%s_deconv\" % prefix, **kwargs)\n    net = mx.sym.BatchNorm(net, eps=eps, name=\"%s_bn\" % prefix)\n    net = mx.sym.Activation(net, name=\"%s_act\" % prefix, act_type=\"relu\")\n    return net\n\n\ndef get_symbol(oshape=(3, 64, 64), ngf=128, code=None):\n    \"\"\"get symbol of dcgan generator\"\"\"\n    assert oshape[-1] == 64, \"Only support 64x64 image\"\n    assert oshape[-2] == 64, \"Only support 64x64 image\"\n\n    code = mx.sym.Variable(\"data\") if code is None else code\n    net = mx.sym.FullyConnected(\n        code, name=\"g1\", num_hidden=ngf * 8 * 4 * 4, no_bias=True, flatten=False\n    )\n    net = mx.sym.Activation(net, act_type=\"relu\")\n    # 4 x 4\n    net = mx.sym.reshape(net, shape=(-1, ngf * 8, 4, 4))\n    # 8 x 8\n    net = deconv2d_bn_relu(\n        net, ishape=(ngf * 8, 4, 4), oshape=(ngf * 4, 8, 8), kshape=(4, 4), prefix=\"g2\"\n    )\n    # 16x16\n    net = deconv2d_bn_relu(\n        net, ishape=(ngf * 4, 8, 8), oshape=(ngf * 2, 16, 16), kshape=(4, 4), prefix=\"g3\"\n    )\n    # 32x32\n    net = deconv2d_bn_relu(\n        net, ishape=(ngf * 2, 16, 16), oshape=(ngf, 32, 32), kshape=(4, 4), prefix=\"g4\"\n    )\n    # 64x64\n    net = deconv2d(net, ishape=(ngf, 32, 32), oshape=oshape[-3:], kshape=(4, 4), name=\"g5_deconv\")\n    net = mx.sym.Activation(net, act_type=\"tanh\")\n    return net\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/dqn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThe mxnet symbol of Nature DQN\n\nReference:\nMnih, Volodymyr, et al.\n\"Human-level control through deep reinforcement learning.\"\nNature 518.7540 (2015): 529.\n\"\"\"\n\nimport mxnet as mx\n\n\ndef get_symbol(num_action=18):\n    data = mx.sym.Variable(name=\"data\")\n    net = mx.sym.Convolution(data, kernel=(8, 8), stride=(4, 4), num_filter=32, name=\"conv1\")\n    net = mx.sym.Activation(net, act_type=\"relu\", name=\"relu1\")\n    net = mx.sym.Convolution(net, kernel=(4, 4), stride=(2, 2), num_filter=64, name=\"conv2\")\n    net = mx.sym.Activation(net, act_type=\"relu\", name=\"relu2\")\n    net = mx.sym.Convolution(net, kernel=(3, 3), stride=(1, 1), num_filter=64, name=\"conv3\")\n    net = mx.sym.Activation(net, act_type=\"relu\", name=\"relu3\")\n    net = mx.sym.FullyConnected(net, num_hidden=512, name=\"fc4\")\n    net = mx.sym.Activation(net, act_type=\"relu\", name=\"relu4\")\n    net = mx.sym.FullyConnected(net, num_hidden=num_action, name=\"fc5\", flatten=False)\n\n    return net\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/inception_v3.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nInception V3, suitable for images with around 299 x 299\n\nReference:\nSzegedy, Christian, et al. \"Rethinking the Inception Architecture for Computer Vision.\" arXiv preprint arXiv:1512.00567 (2015).\n\nAdopted from https://github.com/apache/incubator-mxnet/blob/master/\n             example/image-classification/symbols/inception-v3.py\n\"\"\"\nimport mxnet as mx\nimport numpy as np\n\n\ndef Conv(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), name=None, suffix=\"\"):\n    conv = mx.sym.Convolution(\n        data=data,\n        num_filter=num_filter,\n        kernel=kernel,\n        stride=stride,\n        pad=pad,\n        no_bias=True,\n        name=\"%s%s_conv2d\" % (name, suffix),\n    )\n    bn = mx.sym.BatchNorm(data=conv, eps=2e-5, name=\"%s%s_batchnorm\" % (name, suffix))\n    act = mx.sym.Activation(data=bn, act_type=\"relu\", name=\"%s%s_relu\" % (name, suffix))\n    return act\n\n\ndef Inception7A(\n    data, num_1x1, num_3x3_red, num_3x3_1, num_3x3_2, num_5x5_red, num_5x5, pool, proj, name\n):\n    tower_1x1 = Conv(data, num_1x1, name=(\"%s_conv\" % name))\n    tower_5x5 = Conv(data, num_5x5_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_5x5 = Conv(\n        tower_5x5, num_5x5, kernel=(5, 5), pad=(2, 2), name=(\"%s_tower\" % name), suffix=\"_conv_1\"\n    )\n    tower_3x3 = Conv(data, num_3x3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\")\n    tower_3x3 = Conv(\n        tower_3x3,\n        num_3x3_1,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_3x3 = Conv(\n        tower_3x3,\n        num_3x3_2,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    pooling = mx.sym.Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    cproj = Conv(pooling, proj, name=(\"%s_tower_2\" % name), suffix=\"_conv\")\n    concat = mx.sym.Concat(\n        *[tower_1x1, tower_5x5, tower_3x3, cproj], name=\"ch_concat_%s_chconcat\" % name\n    )\n    return concat\n\n\n# First Downsample\ndef Inception7B(data, num_3x3, num_d3x3_red, num_d3x3_1, num_d3x3_2, pool, name):\n    tower_3x3 = Conv(\n        data, num_3x3, kernel=(3, 3), pad=(0, 0), stride=(2, 2), name=(\"%s_conv\" % name)\n    )\n    tower_d3x3 = Conv(data, num_d3x3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d3x3 = Conv(\n        tower_d3x3,\n        num_d3x3_1,\n        kernel=(3, 3),\n        pad=(1, 1),\n        stride=(1, 1),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d3x3 = Conv(\n        tower_d3x3,\n        num_d3x3_2,\n        kernel=(3, 3),\n        pad=(0, 0),\n        stride=(2, 2),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_2\",\n    )\n    pooling = mx.sym.Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(2, 2),\n        pad=(0, 0),\n        pool_type=\"max\",\n        name=(\"max_pool_%s_pool\" % name),\n    )\n    concat = mx.sym.Concat(*[tower_3x3, tower_d3x3, pooling], name=\"ch_concat_%s_chconcat\" % name)\n    return concat\n\n\ndef Inception7C(\n    data,\n    num_1x1,\n    num_d7_red,\n    num_d7_1,\n    num_d7_2,\n    num_q7_red,\n    num_q7_1,\n    num_q7_2,\n    num_q7_3,\n    num_q7_4,\n    pool,\n    proj,\n    name,\n):\n    tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=(\"%s_conv\" % name))\n    tower_d7 = Conv(data=data, num_filter=num_d7_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d7 = Conv(\n        data=tower_d7,\n        num_filter=num_d7_1,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7 = Conv(\n        data=tower_d7,\n        num_filter=num_d7_2,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_q7 = Conv(data=data, num_filter=num_q7_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\")\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_1,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_2,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_3,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_3\",\n    )\n    tower_q7 = Conv(\n        data=tower_q7,\n        num_filter=num_q7_4,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_4\",\n    )\n    pooling = mx.sym.Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    cproj = Conv(\n        data=pooling, num_filter=proj, kernel=(1, 1), name=(\"%s_tower_2\" % name), suffix=\"_conv\"\n    )\n    # concat\n    concat = mx.sym.Concat(\n        *[tower_1x1, tower_d7, tower_q7, cproj], name=\"ch_concat_%s_chconcat\" % name\n    )\n    return concat\n\n\ndef Inception7D(\n    data, num_3x3_red, num_3x3, num_d7_3x3_red, num_d7_1, num_d7_2, num_d7_3x3, pool, name\n):\n    tower_3x3 = Conv(data=data, num_filter=num_3x3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_3x3 = Conv(\n        data=tower_3x3,\n        num_filter=num_3x3,\n        kernel=(3, 3),\n        pad=(0, 0),\n        stride=(2, 2),\n        name=(\"%s_tower\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7_3x3 = Conv(\n        data=data, num_filter=num_d7_3x3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\"\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_1,\n        kernel=(1, 7),\n        pad=(0, 3),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_2,\n        kernel=(7, 1),\n        pad=(3, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_2\",\n    )\n    tower_d7_3x3 = Conv(\n        data=tower_d7_3x3,\n        num_filter=num_d7_3x3,\n        kernel=(3, 3),\n        stride=(2, 2),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_3\",\n    )\n    pooling = mx.sym.Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(2, 2),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    # concat\n    concat = mx.sym.Concat(*[tower_3x3, tower_d7_3x3, pooling], name=\"ch_concat_%s_chconcat\" % name)\n    return concat\n\n\ndef Inception7E(\n    data,\n    num_1x1,\n    num_d3_red,\n    num_d3_1,\n    num_d3_2,\n    num_3x3_d3_red,\n    num_3x3,\n    num_3x3_d3_1,\n    num_3x3_d3_2,\n    pool,\n    proj,\n    name,\n):\n    tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=(\"%s_conv\" % name))\n    tower_d3 = Conv(data=data, num_filter=num_d3_red, name=(\"%s_tower\" % name), suffix=\"_conv\")\n    tower_d3_a = Conv(\n        data=tower_d3,\n        num_filter=num_d3_1,\n        kernel=(1, 3),\n        pad=(0, 1),\n        name=(\"%s_tower\" % name),\n        suffix=\"_mixed_conv\",\n    )\n    tower_d3_b = Conv(\n        data=tower_d3,\n        num_filter=num_d3_2,\n        kernel=(3, 1),\n        pad=(1, 0),\n        name=(\"%s_tower\" % name),\n        suffix=\"_mixed_conv_1\",\n    )\n    tower_3x3_d3 = Conv(\n        data=data, num_filter=num_3x3_d3_red, name=(\"%s_tower_1\" % name), suffix=\"_conv\"\n    )\n    tower_3x3_d3 = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3,\n        kernel=(3, 3),\n        pad=(1, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_conv_1\",\n    )\n    tower_3x3_d3_a = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3_d3_1,\n        kernel=(1, 3),\n        pad=(0, 1),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_mixed_conv\",\n    )\n    tower_3x3_d3_b = Conv(\n        data=tower_3x3_d3,\n        num_filter=num_3x3_d3_2,\n        kernel=(3, 1),\n        pad=(1, 0),\n        name=(\"%s_tower_1\" % name),\n        suffix=\"_mixed_conv_1\",\n    )\n    pooling = mx.sym.Pooling(\n        data=data,\n        kernel=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        pool_type=pool,\n        name=(\"%s_pool_%s_pool\" % (pool, name)),\n    )\n    cproj = Conv(\n        data=pooling, num_filter=proj, kernel=(1, 1), name=(\"%s_tower_2\" % name), suffix=\"_conv\"\n    )\n    # concat\n    concat = mx.sym.Concat(\n        *[tower_1x1, tower_d3_a, tower_d3_b, tower_3x3_d3_a, tower_3x3_d3_b, cproj],\n        name=\"ch_concat_%s_chconcat\" % name,\n    )\n    return concat\n\n\ndef get_symbol(num_classes=1000, **kwargs):\n    data = mx.sym.Variable(name=\"data\")\n    # stage 1\n    conv = Conv(data, 32, kernel=(3, 3), stride=(2, 2), name=\"conv\")\n    conv_1 = Conv(conv, 32, kernel=(3, 3), name=\"conv_1\")\n    conv_2 = Conv(conv_1, 64, kernel=(3, 3), pad=(1, 1), name=\"conv_2\")\n    pool = mx.sym.Pooling(data=conv_2, kernel=(3, 3), stride=(2, 2), pool_type=\"max\", name=\"pool\")\n    # stage 2\n    conv_3 = Conv(pool, 80, kernel=(1, 1), name=\"conv_3\")\n    conv_4 = Conv(conv_3, 192, kernel=(3, 3), name=\"conv_4\")\n    pool1 = mx.sym.Pooling(data=conv_4, kernel=(3, 3), stride=(2, 2), pool_type=\"max\", name=\"pool1\")\n\n    # # stage 3\n    in3a = Inception7A(pool1, 64, 64, 96, 96, 48, 64, \"avg\", 32, \"mixed\")\n    in3b = Inception7A(in3a, 64, 64, 96, 96, 48, 64, \"avg\", 64, \"mixed_1\")\n    in3c = Inception7A(in3b, 64, 64, 96, 96, 48, 64, \"avg\", 64, \"mixed_2\")\n    in3d = Inception7B(in3c, 384, 64, 96, 96, \"max\", \"mixed_3\")\n    # stage 4\n    in4a = Inception7C(in3d, 192, 128, 128, 192, 128, 128, 128, 128, 192, \"avg\", 192, \"mixed_4\")\n    in4b = Inception7C(in4a, 192, 160, 160, 192, 160, 160, 160, 160, 192, \"avg\", 192, \"mixed_5\")\n    in4c = Inception7C(in4b, 192, 160, 160, 192, 160, 160, 160, 160, 192, \"avg\", 192, \"mixed_6\")\n    in4d = Inception7C(in4c, 192, 192, 192, 192, 192, 192, 192, 192, 192, \"avg\", 192, \"mixed_7\")\n    in4e = Inception7D(in4d, 192, 320, 192, 192, 192, 192, \"max\", \"mixed_8\")\n    # stage 5\n    in5a = Inception7E(in4e, 320, 384, 384, 384, 448, 384, 384, 384, \"avg\", 192, \"mixed_9\")\n    in5b = Inception7E(in5a, 320, 384, 384, 384, 448, 384, 384, 384, \"max\", 192, \"mixed_10\")\n    # pool\n    pool = mx.sym.Pooling(\n        data=in5b, kernel=(8, 8), stride=(1, 1), pool_type=\"avg\", name=\"global_pool\"\n    )\n    flatten = mx.sym.Flatten(data=pool, name=\"flatten\")\n    fc1 = mx.sym.FullyConnected(data=flatten, num_hidden=num_classes, name=\"fc1\", flatten=False)\n    softmax = mx.sym.SoftmaxOutput(data=fc1, name=\"softmax\")\n    return softmax\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/mlp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\na simple multilayer perceptron\n\"\"\"\nimport mxnet as mx\n\n\ndef get_symbol(num_classes=10, **kwargs):\n    data = mx.symbol.Variable(\"data\")\n    data = mx.sym.Flatten(data=data)\n    try:\n        fc1 = mx.symbol.FullyConnected(data=data, name=\"fc1\", num_hidden=128, flatten=False)\n        act1 = mx.symbol.Activation(data=fc1, name=\"relu1\", act_type=\"relu\")\n        fc2 = mx.symbol.FullyConnected(data=act1, name=\"fc2\", num_hidden=64, flatten=False)\n        act2 = mx.symbol.Activation(data=fc2, name=\"relu2\", act_type=\"relu\")\n        fc3 = mx.symbol.FullyConnected(data=act2, name=\"fc3\", num_hidden=num_classes, flatten=False)\n        mlp = mx.symbol.softmax(data=fc3, name=\"softmax\")\n    except:\n        fc1 = mx.symbol.FullyConnected(data=data, name=\"fc1\", num_hidden=128)\n        act1 = mx.symbol.Activation(data=fc1, name=\"relu1\", act_type=\"relu\")\n        fc2 = mx.symbol.FullyConnected(data=act1, name=\"fc2\", num_hidden=64)\n        act2 = mx.symbol.Activation(data=fc2, name=\"relu2\", act_type=\"relu\")\n        fc3 = mx.symbol.FullyConnected(data=act2, name=\"fc3\", num_hidden=num_classes)\n        mlp = mx.symbol.softmax(data=fc3, name=\"softmax\")\n    return mlp\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/resnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nAdapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py\nOriginal author Wei Wu\n\nImplemented the following paper:\n\nKaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. \"Identity Mappings in Deep Residual Networks\"\n\"\"\"\nimport mxnet as mx\nimport numpy as np\n\n\ndef residual_unit(\n    data,\n    num_filter,\n    stride,\n    dim_match,\n    name,\n    bottle_neck=True,\n    bn_mom=0.9,\n    workspace=256,\n    memonger=False,\n):\n    \"\"\"Return ResNet Unit symbol for building ResNet\n    Parameters\n    ----------\n    data : str\n        Input data\n    num_filter : int\n        Number of output channels\n    bnf : int\n        Bottle neck channels factor with regard to num_filter\n    stride : tuple\n        Stride used in convolution\n    dim_match : Boolean\n        True means channel number between input and output is the same, otherwise means differ\n    name : str\n        Base name of the operators\n    workspace : int\n        Workspace used in convolution operator\n    \"\"\"\n    if bottle_neck:\n        bn1 = mx.sym.BatchNorm(\n            data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + \"_bn1\"\n        )\n        act1 = mx.sym.Activation(data=bn1, act_type=\"relu\", name=name + \"_relu1\")\n        conv1 = mx.sym.Convolution(\n            data=act1,\n            num_filter=int(num_filter * 0.25),\n            kernel=(1, 1),\n            stride=stride,\n            pad=(0, 0),\n            no_bias=True,\n            workspace=workspace,\n            name=name + \"_conv1\",\n        )\n        bn2 = mx.sym.BatchNorm(\n            data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + \"_bn2\"\n        )\n        act2 = mx.sym.Activation(data=bn2, act_type=\"relu\", name=name + \"_relu2\")\n        conv2 = mx.sym.Convolution(\n            data=act2,\n            num_filter=int(num_filter * 0.25),\n            kernel=(3, 3),\n            stride=(1, 1),\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + \"_conv2\",\n        )\n        bn3 = mx.sym.BatchNorm(\n            data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + \"_bn3\"\n        )\n        act3 = mx.sym.Activation(data=bn3, act_type=\"relu\", name=name + \"_relu3\")\n        conv3 = mx.sym.Convolution(\n            data=act3,\n            num_filter=num_filter,\n            kernel=(1, 1),\n            stride=(1, 1),\n            pad=(0, 0),\n            no_bias=True,\n            workspace=workspace,\n            name=name + \"_conv3\",\n        )\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = mx.sym.Convolution(\n                data=act1,\n                num_filter=num_filter,\n                kernel=(1, 1),\n                stride=stride,\n                no_bias=True,\n                workspace=workspace,\n                name=name + \"_sc\",\n            )\n        if memonger:\n            shortcut._set_attr(mirror_stage=\"True\")\n        return conv3 + shortcut\n    else:\n        bn1 = mx.sym.BatchNorm(\n            data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + \"_bn1\"\n        )\n        act1 = mx.sym.Activation(data=bn1, act_type=\"relu\", name=name + \"_relu1\")\n        conv1 = mx.sym.Convolution(\n            data=act1,\n            num_filter=num_filter,\n            kernel=(3, 3),\n            stride=stride,\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + \"_conv1\",\n        )\n        bn2 = mx.sym.BatchNorm(\n            data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + \"_bn2\"\n        )\n        act2 = mx.sym.Activation(data=bn2, act_type=\"relu\", name=name + \"_relu2\")\n        conv2 = mx.sym.Convolution(\n            data=act2,\n            num_filter=num_filter,\n            kernel=(3, 3),\n            stride=(1, 1),\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + \"_conv2\",\n        )\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = mx.sym.Convolution(\n                data=act1,\n                num_filter=num_filter,\n                kernel=(1, 1),\n                stride=stride,\n                no_bias=True,\n                workspace=workspace,\n                name=name + \"_sc\",\n            )\n        if memonger:\n            shortcut._set_attr(mirror_stage=\"True\")\n        return conv2 + shortcut\n\n\ndef resnet(\n    units,\n    num_stages,\n    filter_list,\n    num_classes,\n    image_shape,\n    bottle_neck=True,\n    bn_mom=0.9,\n    workspace=256,\n    dtype=\"float32\",\n    memonger=False,\n):\n    \"\"\"Return ResNet symbol of\n    Parameters\n    ----------\n    units : list\n        Number of units in each stage\n    num_stages : int\n        Number of stage\n    filter_list : list\n        Channel size of each stage\n    num_classes : int\n        Output size of symbol\n    dataset : str\n        Dataset type, only cifar10 and imagenet supports\n    workspace : int\n        Workspace used in convolution operator\n    dtype : str\n        Precision (float32 or float16)\n    \"\"\"\n    num_unit = len(units)\n    assert num_unit == num_stages\n    data = mx.sym.Variable(name=\"data\")\n    if dtype == \"float32\":\n        # data = mx.sym.identity(data=data, name='id')\n        data = data\n    else:\n        if dtype == \"float16\":\n            data = mx.sym.Cast(data=data, dtype=np.float16)\n    data = mx.sym.BatchNorm(data=data, fix_gamma=True, eps=2e-5, momentum=bn_mom, name=\"bn_data\")\n    (nchannel, height, width) = image_shape\n    if height <= 32:  # such as cifar10\n        body = mx.sym.Convolution(\n            data=data,\n            num_filter=filter_list[0],\n            kernel=(3, 3),\n            stride=(1, 1),\n            pad=(1, 1),\n            no_bias=True,\n            name=\"conv0\",\n            workspace=workspace,\n        )\n    else:  # often expected to be 224 such as imagenet\n        body = mx.sym.Convolution(\n            data=data,\n            num_filter=filter_list[0],\n            kernel=(7, 7),\n            stride=(2, 2),\n            pad=(3, 3),\n            no_bias=True,\n            name=\"conv0\",\n            workspace=workspace,\n        )\n        body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=\"bn0\")\n        body = mx.sym.Activation(data=body, act_type=\"relu\", name=\"relu0\")\n        body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2, 2), pad=(1, 1), pool_type=\"max\")\n\n    for i in range(num_stages):\n        body = residual_unit(\n            body,\n            filter_list[i + 1],\n            (1 if i == 0 else 2, 1 if i == 0 else 2),\n            False,\n            name=\"stage%d_unit%d\" % (i + 1, 1),\n            bottle_neck=bottle_neck,\n            workspace=workspace,\n            memonger=memonger,\n        )\n        for j in range(units[i] - 1):\n            body = residual_unit(\n                body,\n                filter_list[i + 1],\n                (1, 1),\n                True,\n                name=\"stage%d_unit%d\" % (i + 1, j + 2),\n                bottle_neck=bottle_neck,\n                workspace=workspace,\n                memonger=memonger,\n            )\n    bn1 = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=\"bn1\")\n    relu1 = mx.sym.Activation(data=bn1, act_type=\"relu\", name=\"relu1\")\n    # Although kernel is not used here when global_pool=True, we should put one\n    pool1 = mx.sym.Pooling(\n        data=relu1, global_pool=True, kernel=(7, 7), pool_type=\"avg\", name=\"pool1\"\n    )\n    flat = mx.sym.Flatten(data=pool1)\n    try:\n        fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name=\"fc1\", flatten=False)\n    except:\n        fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name=\"fc1\")\n    if dtype == \"float16\":\n        fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)\n    return mx.sym.softmax(data=fc1, name=\"softmax\")\n\n\ndef get_symbol(num_classes, num_layers, image_shape, conv_workspace=256, dtype=\"float32\", **kwargs):\n    \"\"\"\n    Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py\n    Original author Wei Wu\n    \"\"\"\n    image_shape = [int(l) for l in image_shape.split(\",\")]\n    (nchannel, height, width) = image_shape\n    if height <= 28:\n        num_stages = 3\n        if (num_layers - 2) % 9 == 0 and num_layers >= 164:\n            per_unit = [(num_layers - 2) // 9]\n            filter_list = [16, 64, 128, 256]\n            bottle_neck = True\n        elif (num_layers - 2) % 6 == 0 and num_layers < 164:\n            per_unit = [(num_layers - 2) // 6]\n            filter_list = [16, 16, 32, 64]\n            bottle_neck = False\n        else:\n            raise ValueError(\n                \"no experiments done on num_layers {}, you can do it yourself\".format(num_layers)\n            )\n        units = per_unit * num_stages\n    else:\n        if num_layers >= 50:\n            filter_list = [64, 256, 512, 1024, 2048]\n            bottle_neck = True\n        else:\n            filter_list = [64, 64, 128, 256, 512]\n            bottle_neck = False\n        num_stages = 4\n        if num_layers == 18:\n            units = [2, 2, 2, 2]\n        elif num_layers == 34:\n            units = [3, 4, 6, 3]\n        elif num_layers == 50:\n            units = [3, 4, 6, 3]\n        elif num_layers == 101:\n            units = [3, 4, 23, 3]\n        elif num_layers == 152:\n            units = [3, 8, 36, 3]\n        elif num_layers == 200:\n            units = [3, 24, 36, 3]\n        elif num_layers == 269:\n            units = [3, 30, 48, 8]\n        else:\n            raise ValueError(\n                \"no experiments done on num_layers {}, you can do it yourself\".format(num_layers)\n            )\n\n    return resnet(\n        units=units,\n        num_stages=num_stages,\n        filter_list=filter_list,\n        num_classes=num_classes,\n        image_shape=image_shape,\n        bottle_neck=bottle_neck,\n        workspace=conv_workspace,\n        dtype=dtype,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/squeezenet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nSymbol of SqueezeNet\n\nReference:\nIandola, Forrest N., et al.\n\"Squeezenet: Alexnet-level accuracy with 50x fewer parameters and< 0.5 mb model size.\" (2016).\n\"\"\"\n\nimport mxnet as mx\n\n# Helpers\ndef _make_fire(net, squeeze_channels, expand1x1_channels, expand3x3_channels):\n    net = _make_fire_conv(net, squeeze_channels, 1, 0)\n\n    left = _make_fire_conv(net, expand1x1_channels, 1, 0)\n    right = _make_fire_conv(net, expand3x3_channels, 3, 1)\n    # NOTE : Assume NCHW layout here\n    net = mx.sym.concat(left, right, dim=1)\n\n    return net\n\n\ndef _make_fire_conv(net, channels, kernel_size, padding=0):\n    net = mx.sym.Convolution(\n        net, num_filter=channels, kernel=(kernel_size, kernel_size), pad=(padding, padding)\n    )\n    net = mx.sym.Activation(net, act_type=\"relu\")\n    return net\n\n\n# Net\ndef get_symbol(num_classes=1000, version=\"1.0\", **kwargs):\n    \"\"\"Get symbol of SqueezeNet\n\n    Parameters\n    ----------\n    num_classes: int\n        The number of classification results\n\n    version : str, optional\n        \"1.0\" or \"1.1\" of SqueezeNet\n    \"\"\"\n    assert version in [\n        \"1.0\",\n        \"1.1\",\n    ], \"Unsupported SqueezeNet version {version}:\" \"1.0 or 1.1 expected\".format(version=version)\n    net = mx.sym.Variable(\"data\")\n    if version == \"1.0\":\n        net = mx.sym.Convolution(net, num_filter=96, kernel=(7, 7), stride=(2, 2), pad=(3, 3))\n        net = mx.sym.Activation(net, act_type=\"relu\")\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 16, 64, 64)\n        net = _make_fire(net, 16, 64, 64)\n        net = _make_fire(net, 32, 128, 128)\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 32, 128, 128)\n        net = _make_fire(net, 48, 192, 192)\n        net = _make_fire(net, 48, 192, 192)\n        net = _make_fire(net, 64, 256, 256)\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 64, 256, 256)\n    else:\n        net = mx.sym.Convolution(net, num_filter=64, kernel=(3, 3), stride=(2, 2), pad=(1, 1))\n        net = mx.sym.Activation(net, act_type=\"relu\")\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 16, 64, 64)\n        net = _make_fire(net, 16, 64, 64)\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 32, 128, 128)\n        net = _make_fire(net, 32, 128, 128)\n        net = mx.sym.Pooling(data=net, kernel=(3, 3), pool_type=\"max\", stride=(2, 2))\n        net = _make_fire(net, 48, 192, 192)\n        net = _make_fire(net, 48, 192, 192)\n        net = _make_fire(net, 64, 256, 256)\n        net = _make_fire(net, 64, 256, 256)\n    net = mx.sym.Dropout(net, p=0.5)\n    net = mx.sym.Convolution(net, num_filter=num_classes, kernel=(1, 1))\n    net = mx.sym.Activation(net, act_type=\"relu\")\n    net = mx.sym.Pooling(data=net, global_pool=True, kernel=(13, 13), pool_type=\"avg\")\n    net = mx.sym.flatten(net)\n    return mx.sym.softmax(net)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/model_zoo/vgg.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"References:\n\nSimonyan, Karen, and Andrew Zisserman. \"Very deep convolutional networks for\nlarge-scale image recognition.\" arXiv preprint arXiv:1409.1556 (2014).\n\"\"\"\n\nimport mxnet as mx\nimport numpy as np\n\n\ndef get_feature(internel_layer, layers, filters, batch_norm=False, **kwargs):\n    for i, num in enumerate(layers):\n        for j in range(num):\n            internel_layer = mx.sym.Convolution(\n                data=internel_layer,\n                kernel=(3, 3),\n                pad=(1, 1),\n                num_filter=filters[i],\n                name=\"conv%s_%s\" % (i + 1, j + 1),\n            )\n            if batch_norm:\n                internel_layer = mx.symbol.BatchNorm(\n                    data=internel_layer, name=\"bn%s_%s\" % (i + 1, j + 1)\n                )\n            internel_layer = mx.sym.Activation(\n                data=internel_layer, act_type=\"relu\", name=\"relu%s_%s\" % (i + 1, j + 1)\n            )\n        internel_layer = mx.sym.Pooling(\n            data=internel_layer,\n            pool_type=\"max\",\n            kernel=(2, 2),\n            stride=(2, 2),\n            name=\"pool%s\" % (i + 1),\n        )\n    return internel_layer\n\n\ndef get_classifier(input_data, num_classes, **kwargs):\n    flatten = mx.sym.Flatten(data=input_data, name=\"flatten\")\n    try:\n        fc6 = mx.sym.FullyConnected(data=flatten, num_hidden=4096, name=\"fc6\", flatten=False)\n        relu6 = mx.sym.Activation(data=fc6, act_type=\"relu\", name=\"relu6\")\n        drop6 = mx.sym.Dropout(data=relu6, p=0.5, name=\"drop6\")\n        fc7 = mx.sym.FullyConnected(data=drop6, num_hidden=4096, name=\"fc7\", flatten=False)\n        relu7 = mx.sym.Activation(data=fc7, act_type=\"relu\", name=\"relu7\")\n        drop7 = mx.sym.Dropout(data=relu7, p=0.5, name=\"drop7\")\n        fc8 = mx.sym.FullyConnected(data=drop7, num_hidden=num_classes, name=\"fc8\", flatten=False)\n    except:\n        fc6 = mx.sym.FullyConnected(data=flatten, num_hidden=4096, name=\"fc6\")\n        relu6 = mx.sym.Activation(data=fc6, act_type=\"relu\", name=\"relu6\")\n        drop6 = mx.sym.Dropout(data=relu6, p=0.5, name=\"drop6\")\n        fc7 = mx.sym.FullyConnected(data=drop6, num_hidden=4096, name=\"fc7\")\n        relu7 = mx.sym.Activation(data=fc7, act_type=\"relu\", name=\"relu7\")\n        drop7 = mx.sym.Dropout(data=relu7, p=0.5, name=\"drop7\")\n        fc8 = mx.sym.FullyConnected(data=drop7, num_hidden=num_classes, name=\"fc8\")\n    return fc8\n\n\ndef get_symbol(num_classes, num_layers=11, batch_norm=False, dtype=\"float32\", **kwargs):\n    \"\"\"\n    Parameters\n    ----------\n    num_classes : int, default 1000\n        Number of classification classes.\n    num_layers : int\n        Number of layers for the variant of densenet. Options are 11, 13, 16, 19.\n    batch_norm : bool, default False\n        Use batch normalization.\n    dtype: str, float32 or float16\n        Data precision.\n    \"\"\"\n    vgg_spec = {\n        11: ([1, 1, 2, 2, 2], [64, 128, 256, 512, 512]),\n        13: ([2, 2, 2, 2, 2], [64, 128, 256, 512, 512]),\n        16: ([2, 2, 3, 3, 3], [64, 128, 256, 512, 512]),\n        19: ([2, 2, 4, 4, 4], [64, 128, 256, 512, 512]),\n    }\n    if num_layers not in vgg_spec:\n        raise ValueError(\n            \"Invalide num_layers {}. Possible choices are 11,13,16,19.\".format(num_layers)\n        )\n    layers, filters = vgg_spec[num_layers]\n    data = mx.sym.Variable(name=\"data\")\n    if dtype == \"float16\":\n        data = mx.sym.Cast(data=data, dtype=np.float16)\n    feature = get_feature(data, layers, filters, batch_norm)\n    classifier = get_classifier(feature, num_classes)\n    if dtype == \"float16\":\n        classifier = mx.sym.Cast(data=classifier, dtype=np.float32)\n    symbol = mx.sym.softmax(data=classifier, name=\"softmax\")\n    return symbol\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport operator\nimport random\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay, te\nfrom tvm.contrib import graph_executor\n\nimport model_zoo\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet.gluon.model_zoo import vision\n\n\ndef verify_mxnet_frontend_impl(\n    mx_symbol,\n    data_shape=(1, 3, 224, 224),\n    out_shape=(1, 1000),\n    gluon_impl=False,\n    name=None,\n    dtype=\"float32\",\n):\n    \"\"\"Use name different from test to avoid pytest picking it up\"\"\"\n    if gluon_impl:\n\n        def get_gluon_output(name, x):\n            net = vision.get_model(name)\n            net.collect_params().initialize(mx.init.Xavier())\n            net_sym = gluon.nn.SymbolBlock(\n                outputs=net(mx.sym.var(\"data\")),\n                inputs=mx.sym.var(\"data\"),\n                params=net.collect_params(),\n            )\n            out = net_sym(mx.nd.array(x.astype(dtype))).asnumpy()\n            return out, net_sym\n\n    else:\n\n        def get_mxnet_output(symbol, x, dtype=\"float32\"):\n            from collections import namedtuple\n\n            Batch = namedtuple(\"Batch\", [\"data\"])\n            mod = mx.mod.Module(symbol, label_names=None)\n            mod.bind(data_shapes=[(\"data\", x.shape)], for_training=False)\n            mod.init_params()\n            mod.forward(Batch([mx.nd.array(x.astype(dtype))]))\n            out = mod.get_outputs()[0].asnumpy()\n            args, auxs = mod.get_params()\n            return out, args, auxs\n\n    def get_tvm_output(symbol, x, args, auxs, target, dev, dtype=\"float32\"):\n        shape_dict = {\"data\": x.shape}\n        if gluon_impl:\n            mod, params = relay.frontend.from_mxnet(symbol, shape_dict)\n        else:\n            mod, params = relay.frontend.from_mxnet(\n                symbol, shape_dict, arg_params=args, aux_params=auxs\n            )\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target, params=params)\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        # set inputs\n        m.set_input(\"data\", tvm.nd.array(x.astype(dtype)))\n        m.run()\n        # get outputs\n        out = m.get_output(0, tvm.nd.empty(out_shape, dtype))\n        return out.numpy()\n\n    # random input\n    x = np.random.uniform(size=data_shape)\n    if gluon_impl:\n        gluon_out, gluon_sym = get_gluon_output(name, x)\n        for target, dev in tvm.testing.enabled_targets():\n            tvm_out = get_tvm_output(gluon_sym, x, None, None, target, dev, dtype)\n            tvm.testing.assert_allclose(gluon_out, tvm_out, rtol=1e-5, atol=1e-5)\n    else:\n        mx_out, args, auxs = get_mxnet_output(mx_symbol, x, dtype)\n        assert \"data\" not in args\n        for target, dev in tvm.testing.enabled_targets():\n            tvm_out = get_tvm_output(mx_symbol, x, args, auxs, target, dev, dtype)\n            tvm.testing.assert_allclose(mx_out, tvm_out, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_mlp():\n    mlp = model_zoo.mx_mlp()\n    verify_mxnet_frontend_impl(mlp, data_shape=(1, 1, 28, 28), out_shape=(1, 10))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_vgg():\n    for n in [11]:\n        mx_sym = model_zoo.mx_vgg(n)\n        verify_mxnet_frontend_impl(mx_sym)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_resnet():\n    for n in [18]:\n        mx_sym = model_zoo.mx_resnet(18)\n        verify_mxnet_frontend_impl(mx_sym)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_leaky_relu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.LeakyReLU(data)\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n    mx_sym = mx.sym.LeakyReLU(data, act_type=\"leaky\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_elu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.LeakyReLU(data, act_type=\"elu\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_rrelu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.LeakyReLU(data, act_type=\"rrelu\", lower_bound=0.3, upper_bound=0.7)\n    verify_mxnet_frontend_impl(mx_sym[0], (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_prelu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.LeakyReLU(data, act_type=\"prelu\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gelu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.LeakyReLU(data, act_type=\"gelu\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_softrelu():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.Activation(data, act_type=\"softrelu\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_fc_flatten():\n    # test flatten=True option in mxnet 0.11.1\n    data = mx.sym.var(\"data\")\n    try:\n        mx_sym = mx.sym.FullyConnected(data, num_hidden=100, flatten=True)\n        verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 100))\n        mx_sym = mx.sym.FullyConnected(mx.sym.Flatten(data), num_hidden=100, flatten=False)\n        verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 100))\n    except:\n        pass\n\n\n@tvm.testing.uses_gpu\ndef test_forward_clip():\n    data = mx.sym.var(\"data\")\n    data = mx.sym.concat(data, -data, dim=1)  # negative part explicitly\n    mx_sym = mx.sym.clip(data, a_min=0, a_max=1)\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_split():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.split(data, axis=1, num_outputs=4, squeeze_axis=False)\n    verify_mxnet_frontend_impl(mx_sym, (1, 4, 2, 1), (1, 1, 2, 1))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_split_squeeze():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.split(data, axis=1, num_outputs=4, squeeze_axis=True)\n    verify_mxnet_frontend_impl(mx_sym, (1, 4, 2, 1), (1, 2, 1))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_expand_dims():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.expand_dims(data, axis=1)\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 1, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pooling():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.Pooling(data, kernel=(3, 3), pad=(1, 1), pool_type=\"avg\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8), (1, 20, 8, 8))\n\n    mx_sym = mx.sym.Pooling(data, kernel=(3, 3), pad=(1, 1), pool_type=\"max\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8), (1, 20, 8, 8))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pooling3d():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.Pooling(data, kernel=(3, 3, 3), pad=(1, 1, 1), pool_type=\"avg\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8, 8), (1, 20, 8, 8, 8))\n\n    mx_sym = mx.sym.Pooling(data, kernel=(3, 3, 3), pad=(1, 1, 1), pool_type=\"max\")\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8, 8), (1, 20, 8, 8, 8))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_adaptive_pooling():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.contrib.AdaptiveAvgPooling2D(data, output_size=(1,))\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8), (1, 20, 1, 1))\n\n    mx_sym = mx.sym.contrib.AdaptiveAvgPooling2D(data, output_size=(3, 3))\n    verify_mxnet_frontend_impl(mx_sym, (1, 20, 8, 8), (1, 20, 3, 3))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_lrn():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.LRN(data, alpha=2, beta=2, knorm=1, nsize=5)\n    verify_mxnet_frontend_impl(mx_sym, (1, 10, 24, 24), (1, 10, 24, 24))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_ones():\n    data = mx.sym.var(\"data\")\n    ones = mx.sym.ones(shape=(2, 3, 4), dtype=\"float32\")\n    mx_sym = mx.sym.elemwise_add(data, ones)\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_zeros():\n    data = mx.sym.var(\"data\")\n    zeros = mx.sym.zeros(shape=(2, 3, 4), dtype=\"float32\")\n    mx_sym = mx.sym.elemwise_add(data, zeros)\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_ones_like():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.ones_like(data, dtype=\"float32\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_make_loss():\n    data = mx.sym.var(\"data\")\n    ones = mx.sym.ones(shape=(2, 3, 4), dtype=\"float32\")\n    mx_sym = mx.sym.make_loss((data - ones) ** 2 / 2, dtype=\"float32\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_zeros_like():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.zeros_like(data, dtype=\"float32\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4), (2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argmax():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.argmax(data, axis=1)\n    verify_mxnet_frontend_impl(mx_sym, (5, 3), (5,))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argmin():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.argmin(data, axis=0)\n    verify_mxnet_frontend_impl(mx_sym, (5, 4), (4,))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.slice(data, begin=(0, 1), end=(2, 4))\n    verify_mxnet_frontend_impl(mx_sym, (3, 4), (2, 3))\n    mx_sym = mx.sym.slice(data, begin=(-1, 1), end=(-3, 4), step=(-1, 2))\n    verify_mxnet_frontend_impl(mx_sym, (3, 4), (2, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_where():\n    cond = mx.sym.var(\"cond\")\n    x = mx.sym.var(\"x\")\n    y = mx.sym.var(\"y\")\n    dshape = (2, 2)\n    dtype = \"float32\"\n    mx_sym = mx.sym.where(cond, x, y)\n    np_cond = np.array([[0, 1], [-1, 0]]).astype(dtype)\n    np_x = np.random.uniform(size=dshape).astype(dtype)\n    np_y = np.random.uniform(size=dshape).astype(dtype)\n    mx_cond = mx.nd.array(np_cond)\n    mx_x = mx.nd.array(np_x)\n    mx_y = mx.nd.array(np_y)\n    shapes = {\"cond\": dshape, \"x\": dshape, \"y\": dshape}\n    mod = mx.mod.Module(mx_sym, label_names=None, data_names=[\"cond\", \"x\", \"y\"])\n    mod.bind(data_shapes=shapes.items(), for_training=False)\n    mod.init_params()\n    args, auxs = mod.get_params()\n    mx_out = mx.nd.where(mx_cond, mx_x, mx_y).asnumpy()\n\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, args, auxs)\n    for target, dev in tvm.testing.enabled_targets():\n        for kind in [\"graph\", \"debug\"]:\n            op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                np_cond, np_x, np_y\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), mx_out)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_arange():\n    def _mx_symbol(F, start, stop, step):\n        if start is None and step is None:\n            sym = F.arange(stop)\n        elif start is None:\n            sym = F.arange(stop, step=step)\n        elif step is None:\n            sym = F.arange(start, stop)\n        else:\n            sym = F.arange(start, stop, step)\n        return sym\n\n    def verify(start, stop, step):\n        ref_res = _mx_symbol(mx.nd, start, stop, step)\n        mx_sym = _mx_symbol(mx.sym, start, stop, step)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(\n                    kind, mod=mod, device=dev, target=target\n                ).evaluate()()\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify(0, 20, None)\n    verify(0, 20, 2)\n    verify(1, 20, None)\n    verify(1, 20, 2)\n    verify(1, 20, 1.5)\n    verify(1, 20.5, None)\n    verify(1, 20, 3)\n    verify(20, 1, -1)\n    verify(20, 1, -1.5)\n\n\ndef _mx_symbol(F, op_name, inputs):\n    op = getattr(F, op_name)\n    return op(*inputs)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_broadcast_ops():\n    for op in [\n        \"broadcast_add\",\n        \"broadcast_plus\",\n        \"broadcast_sub\",\n        \"broadcast_minus\",\n        \"broadcast_mul\",\n        \"broadcast_div\",\n        \"broadcast_mod\",\n        \"broadcast_maximum\",\n        \"broadcast_minimum\",\n        \"broadcast_equal\",\n        \"broadcast_not_equal\",\n        \"broadcast_greater\",\n        \"broadcast_greater_equal\",\n        \"broadcast_lesser\",\n        \"broadcast_lesser_equal\",\n        \"broadcast_power\",\n        \"broadcast_logical_or\",\n        \"broadcast_logical_and\",\n        \"broadcast_logical_xor\",\n    ]:\n        a_shape = (3, 4, 5)\n        b_shape = (4, 5)\n        if op == \"broadcast_mod\":\n            dtype = \"int32\"\n            a_np = np.random.randint(1, 100, size=a_shape).astype(dtype)\n            b_np = np.random.randint(1, 100, size=b_shape).astype(dtype)\n        else:\n            dtype = \"float32\"\n            a_np = np.random.uniform(size=a_shape).astype(dtype)\n            b_np = np.random.uniform(size=b_shape).astype(dtype)\n        mx_sym = _mx_symbol(mx.sym, op, [mx.sym.var(\"a\"), mx.sym.var(\"b\")])\n        ref_res = _mx_symbol(mx.nd, op, [mx.nd.array(a_np), mx.nd.array(b_np)])\n        shapes = {\"a\": a_shape, \"b\": b_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np, b_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_elemwise_ops():\n    for op in [\n        \"elemwise_add\",\n        \"elemwise_sub\",\n        \"elemwise_mul\",\n        \"elemwise_div\",\n        \"maximum\",\n        \"minimum\",\n        operator.lt,\n        operator.le,\n        operator.eq,\n        operator.ne,\n        operator.gt,\n        operator.ge,\n    ]:\n        shape = (3, 4, 5)\n        dtype = \"float32\"\n        a_np = np.random.uniform(size=shape).astype(dtype)\n        b_np = np.random.uniform(size=shape).astype(dtype)\n        if type(op) == str:\n            mx_sym = _mx_symbol(mx.sym, op, [mx.sym.var(\"a\"), mx.sym.var(\"b\")])\n            ref_res = _mx_symbol(mx.nd, op, [mx.nd.array(a_np), mx.nd.array(b_np)])\n        else:\n            mx_sym = op(mx.sym.var(\"a\"), mx.sym.var(\"b\"))\n            ref_res = op(mx.nd.array(a_np), mx.nd.array(b_np))\n        shapes = {\"a\": shape, \"b\": shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np, b_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_softmin():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.softmin(data)\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 3, 100, 100))\n\n    mx_sym = mx.sym.softmin(data, axis=2)\n    verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 3, 100, 100))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_unary_ops():\n    for op in [\n        \"abs\",\n        \"sqrt\",\n        \"ceil\",\n        \"floor\",\n        \"round\",\n        \"reciprocal\",\n        \"trunc\",\n        \"softsign\",\n        \"hard_sigmoid\",\n        \"cos\",\n        \"sin\",\n        \"tan\",\n        \"cosh\",\n        \"sinh\",\n        \"tanh\",\n        \"arccos\",\n        \"arcsin\",\n        \"arctan\",\n        \"arccosh\",\n        \"arcsinh\",\n        \"arctanh\",\n    ]:\n        shape = (1, 3, 4, 5)\n        dtype = \"float32\"\n        a_np = np.random.uniform(size=shape).astype(dtype)\n        mx_sym = _mx_symbol(mx.sym, op, [mx.sym.var(\"a\")])\n        ref_res = _mx_symbol(mx.nd, op, [mx.nd.array(a_np)])\n        shapes = {\"a\": shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_scalar_ops():\n    for op in [\n        operator.add,\n        operator.sub,\n        operator.mul,\n        operator.truediv,\n        operator.pow,\n        operator.lt,\n        operator.le,\n        operator.eq,\n        operator.ne,\n        operator.gt,\n        operator.ge,\n    ]:\n        dtype = \"float32\"\n        a_shape = (3, 4, 5)\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        b_scalar = 2.3\n        mx_sym = op(mx.sym.var(\"a\"), b_scalar)\n        ref_res = op(mx.nd.array(a_np), b_scalar)\n        shapes = {\"a\": a_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n    for op in [\"maximum\", \"minimum\"]:\n        dtype = \"float32\"\n        a_shape = (3, 4, 5)\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        b_scalar = 2.3\n        mx_sym = _mx_symbol(mx.sym, op, [mx.sym.var(\"a\"), b_scalar])\n        ref_res = _mx_symbol(mx.nd, op, [mx.nd.array(a_np), b_scalar])\n        shapes = {\"a\": a_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice_axis():\n    def verify(shape, axis, begin, end):\n        data_np = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.slice_axis(mx.nd.array(data_np), axis, begin, end)\n        mx_sym = mx.sym.slice_axis(mx.sym.var(\"data\"), axis, begin, end)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((3, 4), 0, 1, 2)\n    verify((3, 4), 0, 1, None)\n    verify((3, 4), 1, 0, 2)\n    verify((3, 4), 1, -3, -1)\n    verify((3, 4), -1, -3, -1)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice_like():\n    def verify(x_shape, y_shape, axes):\n        x_np = np.random.uniform(size=x_shape).astype(\"float32\")\n        y_np = np.random.uniform(size=y_shape).astype(\"float32\")\n        if axes is None:\n            ref_res = mx.nd.slice_like(mx.nd.array(x_np), mx.nd.array(y_np))\n            mx_sym = mx.sym.slice_like(mx.sym.var(\"x\"), mx.sym.var(\"y\"))\n        else:\n            ref_res = mx.nd.slice_like(mx.nd.array(x_np), mx.nd.array(y_np), axes=axes)\n            mx_sym = mx.sym.slice_like(mx.sym.var(\"x\"), mx.sym.var(\"y\"), axes=axes)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": x_shape, \"y\": y_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np, y_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((3, 4), (2, 3), None)\n    verify((3, 4), (2, 3), (0, 1))\n    verify((3, 4), (2, 3), (0))\n    verify((3, 4), (2, 3), (-1))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_sequence_reverse():\n    def verify(shape, seq_lengths, use_seq_lengths, seq_axis):\n        data_np = np.random.uniform(size=shape).astype(\"float32\")\n\n        ref_res_args = [mx.nd.array(data_np), None, use_seq_lengths, seq_axis]\n        mx_sym_args = [mx.sym.var(\"data\"), None, use_seq_lengths, seq_axis]\n        from_mxnet_args = [{\"data\": shape}, {\"data\": \"float32\"}]\n        in_data = [data_np]\n\n        if use_seq_lengths and seq_lengths:\n            seq_lengths_np = np.array(seq_lengths).astype(\"int32\")\n            ref_res_args[1] = mx.nd.array(seq_lengths_np)\n            mx_sym_args[1] = mx.sym.var(\"seq_lengths\")\n            from_mxnet_args[0].update({\"seq_lengths\": seq_lengths_np.shape})\n            from_mxnet_args[1].update({\"seq_lengths\": \"int32\"})\n            in_data.append(seq_lengths_np)\n\n        ref_res = mx.nd.SequenceReverse(*ref_res_args)\n        mx_sym = mx.sym.SequenceReverse(*mx_sym_args)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, *from_mxnet_args)\n\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    *in_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((3, 4), [1, 2, 3, 1], True, 0)\n    verify((3, 4), None, False, 0)\n    verify((3, 5, 5, 6), [1, 2, 3, 1, 3], True, 0)\n    # MXNet accepts axis value as 0 only\n    # verify((3, 4, 5, 6), None, False, 2)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_l2_normalize():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.L2Normalization(data, mode=\"channel\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4, 5), (2, 3, 4, 5))\n\n    mx_sym = mx.sym.L2Normalization(data, mode=\"instance\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4, 5), (2, 3, 4, 5))\n\n    mx_sym = mx.sym.L2Normalization(data, mode=\"spatial\")\n    verify_mxnet_frontend_impl(mx_sym, (2, 3, 4, 5), (2, 3, 4, 5))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logistic_regression_output():\n    data_shape = (1, 10)\n    dtype = \"float32\"\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    label_np = np.random.uniform(size=data_shape).astype(dtype)\n    mx_sym = mx.symbol.LogisticRegressionOutput(mx.sym.var(\"data\"), mx.sym.var(\"label\"))\n    ref_res = mx.nd.LogisticRegressionOutput(mx.nd.array(data_np), mx.nd.array(label_np))\n    shapes = {\"data\": data_shape}\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n    for target, dev in tvm.testing.enabled_targets():\n        for kind in [\"graph\", \"debug\"]:\n            op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                data_np\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dot():\n    def verify(a_shape, b_shape, transpose_b=False):\n        dtype = \"float32\"\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        b_np = np.random.uniform(size=b_shape).astype(dtype)\n        mx_sym = mx.symbol.dot(mx.sym.var(\"a\"), mx.sym.var(\"b\"), transpose_b=transpose_b)\n        ref_res = mx.nd.dot(mx.nd.array(a_np), mx.nd.array(b_np), transpose_b=transpose_b)\n        shapes = {\"a\": a_shape, \"b\": b_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np, b_np\n                )\n                tvm.testing.assert_allclose(\n                    op_res.numpy(), ref_res.asnumpy(), rtol=1e-05, atol=1e-05\n                )\n\n    verify((1, 256), (256, 1))\n    verify((1, 256), (1, 256), transpose_b=True)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_shape_array():\n    def verify(shape):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.shape_array(mx.nd.array(x_np))\n        mx_sym = mx.sym.shape_array(mx.sym.var(\"x\"))\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1,))\n    verify((3, 4, 5))\n    verify((3, 4, 5, 6))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_squeeze():\n    def verify(shape, axis):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        if axis is None:\n            ref_res = mx.nd.squeeze(mx.nd.array(x_np))\n            mx_sym = mx.sym.squeeze(mx.sym.var(\"x\"))\n        else:\n            ref_res = mx.nd.squeeze(mx.nd.array(x_np), axis=axis)\n            mx_sym = mx.sym.squeeze(mx.sym.var(\"x\"), axis=axis)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1, 3, 1), None)\n    verify((1, 3, 1), 0)\n    verify((1, 3, 1), 2)\n    verify((1, 3, 1), (0, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_broadcast_axis():\n    def verify(shape, axis, size):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        for op in [\"broadcast_axis\", \"broadcast_axes\"]:\n            mx_sym = _mx_symbol(mx.sym, op, [mx.sym.var(\"x\"), axis, size])\n            ref_res = _mx_symbol(mx.nd, op, [mx.nd.array(x_np), axis, size])\n            mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n            for target, dev in tvm.testing.enabled_targets():\n                for kind in [\"graph\", \"debug\"]:\n                    op_res = relay.create_executor(\n                        kind, mod=mod, device=dev, target=target\n                    ).evaluate()(x_np)\n                    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1, 2, 1), 2, 3)\n    verify((1, 2, 1), (0, 2), (2, 3))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_broadcast_to():\n    def verify(input_shape, shape):\n        x_np = np.random.uniform(size=input_shape).astype(\"float32\")\n        ref_res = mx.nd.broadcast_to(mx.nd.array(x_np), shape=shape)\n        mx_sym = mx.sym.broadcast_to(mx.sym.var(\"x\"), shape=shape)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": input_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1, 2, 3), (3, 2, 3))\n    verify((4, 1, 32, 32), (4, 8, 32, 32))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_broadcast_like():\n    def verify(input_shape, like_shape):\n        x_np = np.random.uniform(size=input_shape).astype(\"float32\")\n        y_np = np.random.uniform(size=like_shape).astype(\"float32\")\n        ref_res = mx.nd.broadcast_like(mx.nd.array(x_np), mx.nd.array(y_np))\n        mx_sym = mx.sym.broadcast_like(mx.sym.var(\"x\"), mx.sym.var(\"y\"))\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": input_shape, \"y\": like_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np, y_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1, 2, 3), (3, 2, 3))\n    verify((4, 1, 32, 32), (4, 8, 32, 32))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logical_not():\n    a_shape = (3, 4, 5)\n    dtype = \"float32\"\n    a_np = np.random.uniform(size=a_shape).astype(dtype)\n    mx_sym = mx.sym.logical_not(mx.sym.var(\"a\"))\n    ref_res = mx.nd.logical_not(mx.nd.array(a_np))\n    shapes = {\"a\": a_shape}\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n    for target, dev in tvm.testing.enabled_targets():\n        for kind in [\"graph\", \"debug\"]:\n            op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                a_np\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_full():\n    def verify(val, shape, dtype):\n        dev = mx.cpu()\n        ref_res = mx.nd.full(shape, val, dtype=dtype)\n        mx_sym = mx.sym.full(shape, val, dtype=dtype)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {})\n        for target, dev in tvm.testing.enabled_targets():\n            # Skip testing graph executor because this op will be optimized out\n            # by constant folding.\n            for kind in [\"debug\"]:\n                op_res = relay.create_executor(\n                    kind, mod=mod, device=dev, target=target\n                ).evaluate()()\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify(2, (3, 4), \"float32\")\n    verify(2, (3, 4), \"int32\")\n    verify(3.5, (1, 3, 4), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_embedding():\n    def verify(data_shape, weight_shape):\n        in_dim, out_dim = weight_shape\n        x_np = np.random.randint(0, weight_shape[0], size=data_shape).astype(\"float32\")\n        w_np = np.random.uniform(size=weight_shape).astype(\"float32\")\n        ref_res = mx.nd.Embedding(\n            mx.nd.array(x_np), mx.nd.array(w_np), input_dim=in_dim, output_dim=out_dim\n        )\n        mx_sym = mx.sym.Embedding(\n            mx.sym.var(\"x\"), mx.sym.var(\"w\"), input_dim=in_dim, output_dim=out_dim\n        )\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": data_shape, \"w\": weight_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x=x_np, w=w_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((2, 2), (4, 5))\n    verify((2, 3, 4), (4, 5))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_smooth_l1():\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.smooth_l1(data)\n    verify_mxnet_frontend_impl(mx_sym, (3, 4), (3, 4))\n    mx_sym = mx.sym.smooth_l1(data, scalar=1.0)\n    verify_mxnet_frontend_impl(mx_sym, (3, 4), (3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_take():\n    def verify(shape, indices_src, axis, mode=\"clip\"):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        indices_np = np.array(indices_src, dtype=\"float32\")\n        ref_res = mx.nd.take(mx.nd.array(x_np), mx.nd.array(indices_np), axis, mode)\n        mx_sym = mx.sym.take(mx.sym.var(\"x\"), mx.sym.var(\"y\"), axis, mode)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape, \"y\": indices_np.shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np, indices_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((2, 2), [[[1, 0], [0, 1]]], 0)\n    verify((2, 2), [[[1, 0], [0, 1]]], 1)\n    verify((4, 3, 5, 6), [[2, 1, 0, 0]], -2)\n    verify((3, 4), [-1, 5], 0)\n    verify((3, 4), [-1, 5], 0, mode=\"wrap\")\n    verify((3, 4), [-1, 5], 1)\n    verify((3, 4), [-1, 5], 1, mode=\"wrap\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gather_nd():\n    def verify(xshape, yshape, y_data, error=False):\n        x_data = np.random.uniform(size=xshape).astype(\"float32\")\n        ref_res = mx.nd.gather_nd(mx.nd.array(x_data), mx.nd.array(y_data))\n        mx_sym = mx.sym.gather_nd(mx.sym.var(\"x_data\"), mx.sym.var(\"y_data\"))\n        mod, _ = relay.frontend.from_mxnet(\n            mx_sym, {\"x_data\": xshape, \"y_data\": yshape}, {\"x_data\": \"float32\", \"y_data\": \"int32\"}\n        )\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_data, y_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((2, 2), (2, 3), [[1, 1, 0], [0, 1, 0]])\n    verify((2, 2, 2), (2, 2), [[0, 1], [1, 0]])\n    verify((3, 2, 2), (2, 2), [[0, 1], [1, 0]])\n    verify((3, 2), (2, 2, 3), [[[0, 1, 2], [2, 0, 1]], [[0, 0, 0], [1, 1, 1]]])\n    verify((1, 4), (1, 1), [[0]])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_bilinear_resize():\n    # add tests including scale_height and scale_width when mxnet is updated to version 1.5\n    data = mx.sym.var(\"data\")\n    mx_sym = mx.sym.contrib.BilinearResize2D(data, height=5, width=10)\n    verify_mxnet_frontend_impl(mx_sym, (1, 2, 3, 4), (1, 2, 5, 10))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_grid_generator():\n    def verify(shape, transform_type, target_shape):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.GridGenerator(mx.nd.array(x), transform_type, target_shape)\n        mx_sym = mx.sym.GridGenerator(mx.sym.var(\"x\"), transform_type, target_shape)\n        shape_dict = {\"x\": x.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5, atol=1e-5)\n\n    verify((4, 6), \"affine\", (16, 32))\n    verify((4, 2, 16, 16), \"warp\", None)\n    verify((1, 2, 16, 16), \"warp\", None)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_bilinear_sampler():\n    def verify(data_shape, grid_shape):\n        data = np.random.uniform(size=data_shape).astype(\"float32\")\n        grid = np.random.uniform(low=-1.5, high=1.5, size=grid_shape).astype(\"float32\")\n        ref_res = mx.nd.BilinearSampler(mx.nd.array(data), mx.nd.array(grid))\n        mx_sym = mx.sym.BilinearSampler(mx.sym.var(\"data\"), mx.sym.var(\"grid\"))\n        shape_dict = {\"data\": data.shape, \"grid\": grid.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data, grid\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5, atol=1e-5)\n\n    verify((4, 4, 16, 32), (4, 2, 8, 8))\n    verify((4, 4, 16, 32), (4, 2, 32, 32))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_rnn_layer():\n    def verify(\n        mode,\n        seq_len,\n        input_size,\n        hidden_size,\n        num_layers,\n        batch=1,\n        init_states=True,\n        bidirectional=False,\n    ):\n        if mode == \"rnn\":\n            layer = gluon.rnn.RNN(hidden_size, num_layers, bidirectional=bidirectional)\n        elif mode == \"gru\":\n            layer = gluon.rnn.GRU(hidden_size, num_layers, bidirectional=bidirectional)\n        else:  # mode == \"lstm\"\n            layer = gluon.rnn.LSTM(hidden_size, num_layers, bidirectional=bidirectional)\n        num_states = 2 if mode == \"lstm\" else 1\n        layer.initialize()\n        layer.hybridize()\n\n        dtype = \"float32\"\n        directions = 2 if bidirectional else 1\n        data_np = np.random.uniform(size=(seq_len, batch, input_size)).astype(dtype)\n        data_mx = mx.nd.array(data_np)\n\n        if init_states:\n            shape_dict = {\"data0\": data_np.shape}\n            inputs = {\"data0\": data_np}\n            state_shape = (num_layers * directions, batch, hidden_size)\n            states_np = []\n            states_mx = []\n            for i in range(num_states):\n                s = np.random.uniform(size=state_shape).astype(dtype)\n                states_np.append(s)\n                states_mx.append(mx.nd.array(s))\n                shape_dict[\"data%s\" % (i + 1)] = s.shape\n                inputs[\"data%s\" % (i + 1)] = s\n            mx_out, mx_states = layer(data_mx, states_mx)\n            mx_res = [mx_out] + mx_states\n        else:\n            shape_dict = {\"data\": data_np.shape}\n            inputs = {\"data\": data_np}\n            mx_res = layer(data_mx)\n\n        mx_sym = layer._cached_graph[1]\n        mx_params = {}\n        for name, param in layer.collect_params().items():\n            mx_params[name] = param._reduce()\n\n        mod, params = relay.frontend.from_mxnet(mx_sym, shape=shape_dict, arg_params=mx_params)\n        for target, dev in tvm.testing.enabled_targets():\n            # only test graph executor because debug runtime is too slow\n            for kind in [\"graph\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    **inputs, **params\n                )\n                if init_states:\n                    assert len(op_res) == len(mx_res)\n                    for i, val in enumerate(op_res):\n                        tvm.testing.assert_allclose(val.numpy(), mx_res[i].asnumpy(), rtol=1e-3)\n                else:\n                    tvm.testing.assert_allclose(op_res.numpy(), mx_res.asnumpy(), rtol=1e-3)\n\n    for mode in [\"rnn\", \"gru\", \"lstm\"]:\n        verify(mode, 1, 64, 64, 1)\n        verify(mode, 10, 64, 64, 2)\n        verify(mode, 10, 64, 32, 2)\n        verify(mode, 10, 64, 32, 2, batch=2)\n        verify(mode, 10, 32, 64, 1, bidirectional=True)\n        # The following two codeblocks need to be fixed for mxnet 1.5\n        # verify(mode, 10, 64, 64, 3, init_states=False)\n        # verify(mode, 10, 64, 64, 3, batch=2, bidirectional=True, init_states=False)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_Crop():\n    def verify(xshape, yshape, offset=None):\n        x_data = np.random.uniform(size=xshape).astype(\"float32\")\n        y_data = np.random.uniform(size=yshape).astype(\"float32\")\n        if offset is None:\n            mx_sym = mx.sym.Crop(mx.sym.var(\"x\"), mx.sym.var(\"y\"))\n            ref_res = mx.nd.Crop(mx.nd.array(x_data), mx.nd.array(y_data))\n        else:\n            mx_sym = mx.sym.Crop(mx.sym.var(\"x\"), mx.sym.var(\"y\"), offset=offset)\n            ref_res = mx.nd.Crop(mx.nd.array(x_data), mx.nd.array(y_data), offset=offset)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": xshape, \"y\": yshape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                func = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()\n                if offset is None or offset == (0, 0):\n                    op_res = func(x_data, y_data)\n                else:\n                    op_res = func(x_data)\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((1, 3, 40, 40), (1, 3, 20, 20))\n    verify((1, 3, 40, 40), (1, 3, 20, 20), (0, 0))\n    verify((1, 3, 40, 40), (1, 3, 20, 20), (10, 10))\n    verify((5, 32, 40, 40), (5, 32, 25, 25))\n    verify((5, 32, 40, 40), (5, 32, 25, 25), (5, 5))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argsort():\n    def verify(shape, axis, is_ascend, dtype=\"float32\"):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.argsort(mx.nd.array(x_np), axis=axis, is_ascend=is_ascend, dtype=dtype)\n        mx_sym = mx.sym.argsort(mx.sym.var(\"x\"), axis=axis, is_ascend=is_ascend, dtype=dtype)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((2, 3, 4), axis=0, is_ascend=False)\n    verify((1, 4, 6), axis=1, is_ascend=True)\n    verify((3, 5, 6), axis=-3, is_ascend=False, dtype=\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_topk():\n    def verify(shape, k, axis, ret_type, is_ascend=None, dtype=\"float32\"):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        if is_ascend is None:\n            ref_res = mx.nd.topk(mx.nd.array(x_np), k=k, axis=axis, ret_typ=ret_type, dtype=dtype)\n            mx_sym = mx.sym.topk(mx.sym.var(\"x\"), k=k, axis=axis, ret_typ=ret_type, dtype=dtype)\n        else:\n            ref_res = mx.nd.topk(\n                mx.nd.array(x_np),\n                k=k,\n                axis=axis,\n                ret_typ=ret_type,\n                is_ascend=is_ascend,\n                dtype=dtype,\n            )\n            mx_sym = mx.sym.topk(\n                mx.sym.var(\"x\"), k=k, axis=axis, ret_typ=ret_type, is_ascend=is_ascend, dtype=dtype\n            )\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                if isinstance(ref_res, list):\n                    assert len(op_res) == len(ref_res)\n                    for i, t in enumerate(op_res):\n                        tvm.testing.assert_allclose(t.numpy(), ref_res[i].asnumpy())\n                else:\n                    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((3, 4), k=1, axis=0, ret_type=\"both\")\n    verify((3, 4), k=1, axis=-1, ret_type=\"indices\")\n    verify((3, 5, 6), k=2, axis=2, ret_type=\"value\", is_ascend=False)\n    verify((3, 5, 6), k=2, axis=1, ret_type=\"value\", is_ascend=True)\n    verify((3, 5, 6), k=0, axis=2, ret_type=\"both\", dtype=\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_sequence_mask():\n    def verify(shape, use_sequence_length, value, axis, dtype, itype):\n        data_np = np.random.uniform(size=shape).astype(dtype)\n        valid_length_np = np.random.randint(0, shape[axis], size=shape[1 - axis]).astype(itype)\n        if use_sequence_length:\n            ref_res = mx.nd.SequenceMask(\n                mx.nd.array(data_np, dtype=dtype),\n                sequence_length=mx.nd.array(valid_length_np, dtype=itype),\n                use_sequence_length=use_sequence_length,\n                value=value,\n                axis=axis,\n            )\n            mx_sym = mx.sym.SequenceMask(\n                mx.sym.var(\"data\"),\n                sequence_length=mx.sym.var(\"valid_length\"),\n                use_sequence_length=use_sequence_length,\n                value=value,\n                axis=axis,\n            )\n            mod, _ = relay.frontend.from_mxnet(\n                mx_sym,\n                {\"data\": shape, \"valid_length\": valid_length_np.shape},\n                dtype={\"data\": dtype, \"valid_length\": itype},\n            )\n        else:\n            ref_res = mx.nd.SequenceMask(\n                mx.nd.array(data_np, dtype=dtype),\n                use_sequence_length=use_sequence_length,\n                value=value,\n                axis=axis,\n            )\n            mx_sym = mx.sym.SequenceMask(\n                mx.sym.var(\"data\"), use_sequence_length=use_sequence_length, value=value, axis=axis\n            )\n            mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": shape}, dtype={\"data\": dtype})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                if use_sequence_length is False and kind == \"graph\":\n                    # Disable the test for 'graph' when it's identity.\n                    continue\n                func = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()\n                if use_sequence_length:\n                    op_res = func(data_np, valid_length_np)\n                else:\n                    op_res = func(data_np)\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((5, 10), True, 0.0, 0, \"float32\", \"float32\")\n    verify((5, 4, 3), True, 1.0, 1, \"float32\", \"float32\")\n    verify((5, 4, 3), False, 1.0, 1, \"float64\", \"float64\")\n    verify((5, 4, 3, 2), True, 1.0, 0, \"float32\", \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_contrib_div_sqrt_dim():\n    def verify(shape):\n        x_np = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.contrib.div_sqrt_dim(mx.nd.array(x_np))\n        mx_sym = mx.sym.contrib.div_sqrt_dim(mx.sym.var(\"x\"))\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"x\": shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify((3, 4))\n    verify((3, 4, 5))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_batch_norm():\n    def verify(shape, axis=1, fix_gamma=False):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        gamma = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        beta = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        moving_mean = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        moving_var = np.abs(np.random.uniform(size=(shape[axis])).astype(\"float32\")) + 0.5\n        ref_res = mx.nd.BatchNorm(\n            mx.nd.array(x),\n            mx.nd.array(gamma),\n            mx.nd.array(beta),\n            mx.nd.array(moving_mean),\n            mx.nd.array(moving_var),\n            axis=axis,\n            use_global_stats=True,\n            fix_gamma=fix_gamma,\n        )\n        mx_sym = mx.sym.BatchNorm(\n            mx.sym.var(\"x\"),\n            mx.sym.var(\"gamma\"),\n            mx.sym.var(\"beta\"),\n            mx.sym.var(\"mean\"),\n            mx.sym.var(\"var\"),\n            axis=axis,\n            use_global_stats=True,\n            fix_gamma=fix_gamma,\n        )\n\n        shape_dict = {\n            \"x\": x.shape,\n            \"gamma\": gamma.shape,\n            \"beta\": beta.shape,\n            \"mean\": moving_mean.shape,\n            \"var\": moving_var.shape,\n        }\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        # print(mod)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, gamma, beta, moving_mean, moving_var\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3)\n\n    verify((2, 3, 4, 5))\n    verify((2, 3, 4, 5), axis=0)\n    verify((2, 3, 4, 5), axis=-1)\n    verify((2, 3, 4, 5), fix_gamma=True)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_instance_norm():\n    def verify(shape, axis=1, epsilon=1e-5):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        gamma = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        beta = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        ref_res = mx.nd.InstanceNorm(mx.nd.array(x), mx.nd.array(gamma), mx.nd.array(beta), epsilon)\n        mx_sym = mx.sym.InstanceNorm(\n            mx.sym.var(\"x\"), mx.sym.var(\"gamma\"), mx.sym.var(\"beta\"), epsilon\n        )\n        shape_dict = {\"x\": x.shape, \"gamma\": gamma.shape, \"beta\": beta.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, gamma, beta\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=2e-5, atol=1e-5)\n\n    verify((2, 3, 4, 5))\n    verify((32, 64, 80, 64))\n    verify((8, 6, 5))\n    verify((8, 7, 6, 5, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_layer_norm():\n    def verify(shape, axis=-1):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        gamma = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        beta = np.random.uniform(size=(shape[axis])).astype(\"float32\")\n        ref_res = mx.nd.LayerNorm(mx.nd.array(x), mx.nd.array(gamma), mx.nd.array(beta), axis=axis)\n        mx_sym = mx.sym.LayerNorm(\n            mx.sym.var(\"x\"), mx.sym.var(\"gamma\"), mx.sym.var(\"beta\"), axis=axis\n        )\n        shape_dict = {\"x\": x.shape, \"gamma\": gamma.shape, \"beta\": beta.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, gamma, beta\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((2, 5))\n    verify((2, 5), axis=0)\n    verify((2, 5, 6))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_group_norm():\n    def verify(shape, num_groups=1):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        gamma = np.random.uniform(size=(shape[1])).astype(\"float32\")\n        beta = np.random.uniform(size=(shape[1])).astype(\"float32\")\n        ref_res = mx.nd.GroupNorm(\n            data=mx.nd.array(x),\n            gamma=mx.nd.array(gamma),\n            beta=mx.nd.array(beta),\n            num_groups=num_groups,\n        )\n        mx_sym = mx.sym.GroupNorm(\n            mx.sym.var(\"x\"), mx.sym.var(\"gamma\"), mx.sym.var(\"beta\"), num_groups=num_groups\n        )\n        shape_dict = {\"x\": x.shape, \"gamma\": gamma.shape, \"beta\": beta.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, gamma, beta\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((1, 4, 2), num_groups=4)\n    # TODO(trevmorr): MXNet GroupNorm implementation is bugged for cases when num_groups != num_channels\n    # https://github.com/apache/incubator-mxnet/pull/18199\n    # verify((1, 4, 2, 3), num_groups=2)\n    # verify((1, 4, 2, 3))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_one_hot():\n    def verify(indices_shape, depth, on_value, off_value, dtype):\n        x = np.random.randint(0, 5, size=indices_shape)\n        ref_res = mx.nd.one_hot(mx.nd.array(x), depth, on_value, off_value, dtype)\n        mx_sym = mx.sym.one_hot(mx.sym.var(\"x\"), depth, on_value, off_value, dtype)\n        shape_dict = {\"x\": x.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x.astype(\"float32\")\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((3,), 3, 1, 0, \"int32\")\n    verify((3,), 3, 1.0, 0.0, \"float32\")\n    verify((2, 2), 5, 2, -2, \"int32\")\n    verify((2, 2), 5, 0.5, -0.5, \"float32\")\n    verify((3, 2, 4, 5), 6, 1, 0, \"int32\")\n    verify((3, 2, 4, 5), 6, 1.0, 0.0, \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pad():\n    def verify(data_shape, out_shape, mode, pad_width, constant_value=0.0):\n        data = mx.sym.var(\"data\")\n        mx_sym = mx.sym.pad(data, mode=mode, pad_width=pad_width, constant_value=constant_value)\n        verify_mxnet_frontend_impl(mx_sym, data_shape=data_shape, out_shape=out_shape)\n\n    verify(\n        data_shape=(1, 1, 3, 5),\n        out_shape=(1, 1, 6, 12),\n        mode=\"constant\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4),\n    )\n    verify(\n        data_shape=(1, 1, 3, 5),\n        out_shape=(1, 1, 6, 12),\n        mode=\"constant\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4),\n        constant_value=3.0,\n    )\n    verify(\n        data_shape=(1, 1, 3, 5),\n        out_shape=(1, 1, 6, 12),\n        mode=\"edge\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4),\n    )\n    verify(\n        data_shape=(1, 1, 3, 5),\n        out_shape=(1, 1, 6, 12),\n        mode=\"reflect\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4),\n    )\n    verify(\n        data_shape=(1, 1, 3, 5, 7),\n        out_shape=(1, 1, 6, 12, 18),\n        mode=\"constant\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4, 5, 6),\n    )\n    verify(\n        data_shape=(1, 1, 3, 5, 7),\n        out_shape=(1, 1, 6, 12, 18),\n        mode=\"constant\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4, 5, 6),\n        constant_value=3.0,\n    )\n    verify(\n        data_shape=(1, 1, 3, 5, 7),\n        out_shape=(1, 1, 6, 12, 18),\n        mode=\"edge\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4, 5, 6),\n    )\n    verify(\n        data_shape=(1, 1, 3, 5, 7),\n        out_shape=(1, 1, 6, 12, 18),\n        mode=\"reflect\",\n        pad_width=(0, 0, 0, 0, 1, 2, 3, 4, 5, 6),\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice():\n    def verify(data_shape, out_shape, begin, end):\n        data = mx.sym.var(\"data\")\n        mx_sym = mx.sym.slice(data, begin=begin, end=end)\n        verify_mxnet_frontend_impl(mx_sym, data_shape=data_shape, out_shape=out_shape)\n\n    verify(data_shape=(1, 1, 10), out_shape=(1, 1, 8), begin=(0, 0, 2), end=(1, 1, 10))\n    verify(\n        data_shape=(1, 1, 10), out_shape=(1, 1, 8), begin=(None, None, 2), end=(None, None, None)\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_convolution():\n    def verify(data_shape, kernel_size, stride, pad, num_filter, is_depthwise=False):\n        if is_depthwise:\n            groups = data_shape[1]\n            weight_shape = (\n                data_shape[1],\n                num_filter // groups,\n            ) + kernel_size\n        else:\n            groups = 1\n            weight_shape = (\n                num_filter,\n                data_shape[1],\n            ) + kernel_size\n        x = np.random.uniform(size=data_shape).astype(\"float32\")\n        weight = np.random.uniform(size=weight_shape).astype(\"float32\")\n        bias = np.random.uniform(size=num_filter).astype(\"float32\")\n        ref_res = mx.nd.Convolution(\n            data=mx.nd.array(x),\n            weight=mx.nd.array(weight),\n            bias=mx.nd.array(bias),\n            kernel=kernel_size,\n            stride=stride,\n            pad=pad,\n            num_filter=num_filter,\n            num_group=groups,\n        )\n        mx_sym = mx.sym.Convolution(\n            mx.sym.var(\"x\"),\n            mx.sym.var(\"weight\"),\n            mx.sym.var(\"bias\"),\n            kernel=kernel_size,\n            stride=stride,\n            pad=pad,\n            num_filter=num_filter,\n            num_group=groups,\n        )\n        shape_dict = {\"x\": x.shape, \"weight\": weight.shape, \"bias\": bias.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, weight, bias\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3)\n\n    verify(data_shape=(1, 1, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(20, 1, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(1, 8, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(20, 8, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(1, 1, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(20, 1, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(1, 8, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(20, 8, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(\n        data_shape=(1, 8, 32, 32),\n        kernel_size=(3, 3),\n        stride=(1, 1),\n        pad=(1, 1),\n        num_filter=8,\n        is_depthwise=True,\n    )\n    verify(\n        data_shape=(1, 1, 16, 16, 16),\n        kernel_size=(3, 3, 3),\n        stride=(1, 1, 1),\n        pad=(1, 1, 1),\n        num_filter=2,\n    )\n    verify(\n        data_shape=(20, 1, 16, 16, 16),\n        kernel_size=(3, 3, 3),\n        stride=(1, 1, 1),\n        pad=(1, 1, 1),\n        num_filter=2,\n    )\n    verify(\n        data_shape=(1, 8, 16, 16, 16),\n        kernel_size=(3, 3, 3),\n        stride=(2, 2, 2),\n        pad=(1, 1, 1),\n        num_filter=2,\n    )\n    verify(\n        data_shape=(20, 8, 16, 16, 16),\n        kernel_size=(3, 3, 3),\n        stride=(1, 1, 1),\n        pad=(1, 1, 1),\n        num_filter=2,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_deconvolution():\n    def verify(data_shape, kernel_size, stride, pad, num_filter):\n        weight_shape = (data_shape[1], num_filter) + kernel_size\n        x = np.random.uniform(size=data_shape).astype(\"float32\")\n        weight = np.random.uniform(size=weight_shape).astype(\"float32\")\n        bias = np.random.uniform(size=num_filter).astype(\"float32\")\n        ref_res = mx.nd.Deconvolution(\n            data=mx.nd.array(x),\n            weight=mx.nd.array(weight),\n            bias=mx.nd.array(bias),\n            kernel=kernel_size,\n            stride=stride,\n            pad=pad,\n            num_filter=num_filter,\n            no_bias=False,\n        )\n        mx_sym = mx.sym.Deconvolution(\n            mx.sym.var(\"x\"),\n            mx.sym.var(\"weight\"),\n            mx.sym.var(\"bias\"),\n            kernel=kernel_size,\n            stride=stride,\n            pad=pad,\n            num_filter=num_filter,\n            no_bias=False,\n        )\n        shape_dict = {\"x\": x.shape, \"weight\": weight.shape, \"bias\": bias.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x, weight, bias\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify(data_shape=(1, 1, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(20, 1, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(1, 8, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(20, 8, 1024 * 16), kernel_size=(17,), stride=(2,), pad=(8,), num_filter=4)\n    verify(data_shape=(1, 1, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(20, 1, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(1, 8, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n    verify(data_shape=(20, 8, 32, 32), kernel_size=(3, 3), stride=(1, 1), pad=(1, 1), num_filter=2)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_cond():\n    def verify(a_np, b_np):\n        a_nd, b_nd = mx.nd.array(a_np), mx.nd.array(b_np)\n        pred = a_nd * b_nd < 5\n        then_func = lambda: (a_nd + 5) * (b_nd + 5)\n        else_func = lambda: (a_nd - 5) * (b_nd - 5)\n        ref_res = mx.nd.contrib.cond(pred, then_func, else_func)\n\n        a_sym, b_sym = mx.sym.var(\"a\"), mx.sym.var(\"b\")\n        pred = a_sym * b_sym < 5\n        then_func = lambda: (a_sym + 5) * (b_sym + 5)\n        else_func = lambda: (a_sym - 5) * (b_sym - 5)\n        mx_sym = mx.sym.contrib.cond(pred, then_func, else_func)\n\n        shape_dict = {\"a\": a_np.shape, \"b\": b_np.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"debug\", \"vm\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np, b_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3)\n\n    verify(np.asarray([1.0], \"float32\"), np.asarray([2.0], \"float32\"))\n    verify(np.asarray([4.0], \"float32\"), np.asarray([3.0], \"float32\"))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_amp_cast():\n    def verify(from_dtype, to_dtype):\n        from_np = np.random.uniform(size=(1, 3, 18)).astype(from_dtype)\n        x_var = mx.sym.var(\"x\", dtype=from_dtype)\n        mx_sym = mx.sym.amp_cast(x_var, dtype=to_dtype)\n        shape_dict = {\"x\": (1, 3, 18)}\n        dtype_dict = {\"x\": from_dtype}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict, dtype_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"vm\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    from_np\n                )\n                assert op_res.dtype == to_dtype, op_res.dtype\n                tvm.testing.assert_allclose(op_res.numpy(), from_np.astype(to_dtype))\n\n    verify(\"float32\", \"float16\")\n    verify(\"float16\", \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_amp_multicast():\n    def verify(dtypes, cast_narrow, expected_dtype):\n        x_nps = [np.random.uniform(size=(1, 3, 18)).astype(dtype) for dtype in dtypes]\n        x_vars = [mx.sym.var(str(i), dtype=dtype) for i, dtype in enumerate(dtypes)]\n        mx_sym = mx.sym.amp_multicast(*x_vars, cast_narrow=cast_narrow, num_outputs=len(dtypes))\n        shape_dict = {}\n        dtype_dict = {}\n        for i, dtype in enumerate(dtypes):\n            shape_dict[str(i)] = (1, 3, 18)\n            dtype_dict[str(i)] = dtype\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict, dtype_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"vm\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    *x_nps\n                )\n                for i, res in enumerate(op_res):\n                    assert res.dtype == expected_dtype, res.dtype\n                    tvm.testing.assert_allclose(res.numpy(), x_nps[i].astype(expected_dtype))\n\n    verify([\"float32\", \"float16\"], False, \"float32\")\n    verify([\"float32\", \"float16\"], True, \"float16\")\n    verify([\"float32\", \"float32\"], False, \"float32\")\n    verify([\"float32\", \"float32\"], True, \"float32\")\n    verify([\"float16\", \"float16\"], False, \"float16\")\n    verify([\"float16\", \"float16\"], True, \"float16\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_unravel_index():\n    def verify(x, shape, dtype):\n        a_np = np.array(x).astype(dtype)\n        mx_sym = _mx_symbol(mx.sym, \"unravel_index\", [mx.sym.var(\"a\"), shape])\n        ref_res = _mx_symbol(mx.nd, \"unravel_index\", [mx.nd.array(a_np), shape])\n        shapes = {\"a\": a_np.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shapes, dtype)\n\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"vm\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    a_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    for dtype in [\"int32\", \"int64\"]:\n        verify([0, 1, 2, 3], [2, 2], dtype)\n        verify([144, 13, 45], [6, 7, 10, 2], dtype)\n        verify([456], [6, 7, 10, 2], dtype)\n\n    # In below example, 5 is out of bound for array of size 4.\n    # MXNet implementation provides different result than TVM\n    # TVM implementation is inline with Tensorflow\n    # Ideally error should be thrown just like Numpy\n    # verify([0, 1, 2, 5], [2, 2], dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_swap_axis():\n    def _verify_swap_axis(in_shape, out_shape, dim1, dim2):\n        data = mx.sym.var(\"data\")\n        mx_sym = mx.sym.swapaxes(data, dim1, dim2)\n        verify_mxnet_frontend_impl(mx_sym, in_shape, out_shape)\n\n    _verify_swap_axis((4, 5), (5, 4), 0, 1)\n    _verify_swap_axis((2, 4, 4, 5), (2, 5, 4, 4), 1, 3)\n    # MXNet errors out when dim1 == dim2\n    # _verify_swap_axis((4, 5), (5, 4), 0, 0)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_depth_to_space():\n    def verify(shape, blocksize=2):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.depth_to_space(mx.nd.array(x), blocksize)\n        mx_sym = mx.sym.depth_to_space(mx.sym.var(\"x\"), blocksize)\n        shape_dict = {\n            \"x\": x.shape,\n        }\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((1, 18, 3, 3), 3)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_space_to_depth():\n    def verify(shape, blocksize=2):\n        x = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = mx.nd.space_to_depth(mx.nd.array(x), blocksize)\n        mx_sym = mx.sym.space_to_depth(mx.sym.var(\"x\"), blocksize)\n        shape_dict = {\n            \"x\": x.shape,\n        }\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    x\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((1, 1, 9, 9), 3)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_correlation():\n    def verify(data_shape, kernel_size, max_displacement, stride1, stride2, pad_size, is_multiply):\n        data1 = np.random.uniform(size=data_shape).astype(\"float32\")\n        data2 = np.random.uniform(size=data_shape).astype(\"float32\")\n        ref_res = mx.nd.Correlation(\n            data1=mx.nd.array(data1),\n            data2=mx.nd.array(data2),\n            kernel_size=kernel_size,\n            max_displacement=max_displacement,\n            stride1=stride1,\n            stride2=stride2,\n            pad_size=pad_size,\n            is_multiply=is_multiply,\n        )\n        mx_sym = mx.sym.Correlation(\n            data1=mx.sym.var(\"data1\"),\n            data2=mx.sym.var(\"data2\"),\n            kernel_size=kernel_size,\n            max_displacement=max_displacement,\n            stride1=stride1,\n            stride2=stride2,\n            pad_size=pad_size,\n            is_multiply=is_multiply,\n        )\n        shape_dict = {\"data1\": data1.shape, \"data2\": data2.shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data1, data2\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify(\n        (1, 3, 10, 10),\n        kernel_size=1,\n        max_displacement=4,\n        stride1=1,\n        stride2=1,\n        pad_size=4,\n        is_multiply=False,\n    )\n    verify(\n        (5, 1, 15, 15),\n        kernel_size=1,\n        max_displacement=5,\n        stride1=1,\n        stride2=1,\n        pad_size=5,\n        is_multiply=False,\n    )\n    verify(\n        (5, 1, 15, 15),\n        kernel_size=1,\n        max_displacement=5,\n        stride1=1,\n        stride2=1,\n        pad_size=5,\n        is_multiply=True,\n    )\n    verify(\n        (5, 1, 15, 15),\n        kernel_size=1,\n        max_displacement=10,\n        stride1=1,\n        stride2=2,\n        pad_size=10,\n        is_multiply=True,\n    )\n    verify(\n        (5, 1, 4, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=1,\n        stride2=1,\n        pad_size=2,\n        is_multiply=True,\n    )\n    verify(\n        (5, 1, 4, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=2,\n        stride2=1,\n        pad_size=2,\n        is_multiply=True,\n    )\n    verify(\n        (5, 1, 4, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=2,\n        stride2=1,\n        pad_size=2,\n        is_multiply=False,\n    )\n    verify(\n        (5, 1, 6, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=2,\n        stride2=1,\n        pad_size=2,\n        is_multiply=False,\n    )\n    verify(\n        (5, 1, 11, 11),\n        kernel_size=5,\n        max_displacement=1,\n        stride1=1,\n        stride2=1,\n        pad_size=2,\n        is_multiply=False,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_arange_like():\n    def verify(data_shape, start=None, step=None, axis=None):\n        attrs = {}\n        if start is not None:\n            attrs[\"start\"] = start\n        if step is not None:\n            attrs[\"step\"] = step\n        if axis is not None:\n            attrs[\"axis\"] = axis\n        data = mx.sym.var(\"data\")\n        data_np = np.random.uniform(size=data_shape).astype(\"float32\")\n        ref_res = mx.nd.contrib.arange_like(mx.nd.array(data_np), **attrs)\n\n        mx_sym = mx.sym.contrib.arange_like(data, **attrs)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\"]:\n                op_res = relay.create_executor(\n                    kind, mod=mod, device=dev, target=target\n                ).evaluate()()\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy())\n\n    verify(data_shape=(3,), start=0.0, step=1.0)\n    verify(data_shape=(3, 4, 5), start=0.0, step=1.0)\n    verify(data_shape=(3, 4, 5), start=0.0, step=1.0, axis=-1)\n    verify(data_shape=(3, 4, 5), start=2.0, step=3.0, axis=1)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_interleaved_matmul_selfatt_qk():\n    def verify(batch, seq_length, num_heads, head_dim):\n        data_shape = (seq_length, batch, num_heads * head_dim * 3)\n        data = mx.sym.var(\"data\")\n        data_np = np.random.uniform(size=data_shape).astype(\"float32\")\n        ref_res = mx.nd.contrib.interleaved_matmul_selfatt_qk(mx.nd.array(data_np), heads=num_heads)\n\n        mx_sym = mx.sym.contrib.interleaved_matmul_selfatt_qk(data, heads=num_heads)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n    verify(1, 10, 3, 16)\n    verify(3, 10, 6, 8)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_interleaved_matmul_selfatt_valatt():\n    def verify(batch, seq_length, num_heads, head_dim):\n        data_shape = (seq_length, batch, num_heads * head_dim * 3)\n        weight_shape = (batch * num_heads, seq_length, seq_length)\n        data = mx.sym.var(\"data\")\n        weight = mx.sym.var(\"weight\")\n        data_np = np.random.uniform(size=data_shape).astype(\"float32\")\n        weight_np = np.random.uniform(size=weight_shape).astype(\"float32\")\n        ref_res = mx.nd.contrib.interleaved_matmul_selfatt_valatt(\n            mx.nd.array(data_np), mx.nd.array(weight_np), heads=num_heads\n        )\n\n        mx_sym = mx.sym.contrib.interleaved_matmul_selfatt_valatt(data, weight, heads=num_heads)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape, \"weight\": weight_shape})\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data=data_np, weight=weight_np\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n    verify(1, 10, 4, 16)\n    verify(3, 10, 6, 8)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_box_nms():\n    def verify(\n        data_shape,\n        overlap_thresh=0.5,\n        valid_thresh=0,\n        topk=1,\n        coord_start=2,\n        score_index=1,\n        id_index=0,\n        force_suppress=False,\n        in_format=\"corner\",\n    ):\n        dtype = \"float32\"\n        data = np.random.uniform(low=0, high=1, size=data_shape).astype(dtype)\n        ref_res = mx.nd.contrib.box_nms(\n            mx.nd.array(data),\n            overlap_thresh=overlap_thresh,\n            valid_thresh=valid_thresh,\n            topk=topk,\n            coord_start=coord_start,\n            score_index=score_index,\n            id_index=id_index,\n            force_suppress=force_suppress,\n            background_id=-1,\n            in_format=in_format,\n            out_format=in_format,\n        )\n        mx_sym = mx.sym.contrib.box_nms(\n            mx.sym.var(\"data\"),\n            overlap_thresh=overlap_thresh,\n            valid_thresh=valid_thresh,\n            topk=topk,\n            coord_start=coord_start,\n            score_index=score_index,\n            id_index=id_index,\n            force_suppress=force_suppress,\n            background_id=-1,\n            in_format=in_format,\n            out_format=in_format,\n        )\n        shape_dict = {\"data\": data_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            if tvm.contrib.thrust.can_use_thrust(\n                tvm.target.Target(target + \" -libs=thrust\"), \"tvm.contrib.thrust.sort\"\n            ):\n                target += \" -libs=thrust\"\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((1, 10, 6))\n    # No valid boxes\n    verify((1, 10, 6), valid_thresh=1)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_box_decode():\n    def verify(data_shape, anchor_shape, stds=[1, 1, 1, 1], clip=-1, in_format=\"corner\"):\n        dtype = \"float32\"\n        data = np.random.uniform(low=-2, high=2, size=data_shape).astype(dtype)\n        anchors = np.random.uniform(low=-2, high=2, size=anchor_shape).astype(dtype)\n        ref_res = mx.nd.contrib.box_decode(\n            mx.nd.array(data),\n            mx.nd.array(anchors),\n            stds[0],\n            stds[1],\n            stds[2],\n            stds[3],\n            clip,\n            in_format,\n        )\n        mx_sym = mx.sym.contrib.box_decode(\n            mx.sym.var(\"data\"),\n            mx.sym.var(\"anchors\"),\n            stds[0],\n            stds[1],\n            stds[2],\n            stds[3],\n            clip,\n            in_format,\n        )\n        shape_dict = {\"data\": data_shape, \"anchors\": anchor_shape}\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    data, anchors\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((1, 10, 4), (1, 10, 4))\n    verify((4, 10, 4), (1, 10, 4))\n    verify((1, 10, 4), (1, 10, 4), stds=[2, 3, 0.5, 1.5])\n    verify((1, 10, 4), (1, 10, 4), clip=1)\n    verify((1, 10, 4), (1, 10, 4), in_format=\"center\")\n\n\n@tvm.testing.uses_gpu\ndef test_forward_softmax():\n    def verify(data_shape, axis, use_length, length):\n        dtype = \"float32\"\n        x = np.random.uniform(low=-100, high=100, size=data_shape).astype(dtype)\n        if use_length:\n            ref_res = mx.nd.softmax(\n                data=mx.nd.array(x),\n                length=mx.nd.array(length, dtype=\"int32\"),\n                axis=axis,\n                use_length=use_length,\n            )\n            mx_sym = mx.symbol.softmax(\n                data=mx.sym.var(\"data\"),\n                length=mx.sym.var(\"length\"),\n                axis=axis,\n                use_length=use_length,\n            )\n            shape_dict = {\"data\": data_shape, \"length\": (length.shape)}\n            dtype_dict = {\"data\": dtype, \"length\": \"int32\"}\n            mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict, dtype_dict)\n        else:\n            ref_res = mx.nd.softmax(data=mx.nd.array(x), axis=axis)\n            mx_sym = mx.symbol.softmax(data=mx.sym.var(\"data\"), axis=axis)\n            shape_dict = {\"data\": data_shape}\n            mod, _ = relay.frontend.from_mxnet(mx_sym, shape_dict)\n\n        for target, dev in tvm.testing.enabled_targets():\n            for kind in [\"graph\", \"debug\"]:\n                func = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()\n                if use_length:\n                    op_res = func(x, length)\n                else:\n                    op_res = func(x)\n\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-3, atol=1e-5)\n\n    verify((2, 3, 5), -1, False, None)\n    verify((2, 3, 5), 2, False, None)\n    verify((2, 3), -1, True, np.array([2, 1]).astype(\"int32\"))\n    verify((2, 3, 4), -1, True, np.array([[3, 4, 2], [2, 1, 1]]).astype(\"int32\"))\n    verify((2, 3, 4), 2, True, np.array([[3, 4, 2], [1, 2, 1]]).astype(\"int32\"))\n\n\n@pytest.mark.skipif(not hasattr(mx.sym.np, \"pad\"), reason=\"mx.sym.np.pad hasn't been publish yet\")\n@pytest.mark.parametrize(\n    \"data_shape, pad_width\",\n    [\n        ((1, 1, 3, 5), ((0, 0), (0, 0), (1, 2), (3, 4))),\n        ((1, 1, 3, 5, 7), ((0, 0), (0, 0), (1, 2), (3, 4), (5, 6))),\n    ],\n)\n@pytest.mark.parametrize(\"mode\", [\"constant\", \"edge\", \"reflect\"])\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\"])\n@pytest.mark.parametrize(\"constant_value\", [0.0, 3.0])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_pad(data_shape, pad_width, mode, dtype, constant_value, target, dev, kind):\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    data = mx.sym.var(\"data\")\n    if mode == \"constant\":\n        ref_res = np.pad(data_np, mode=mode, pad_width=pad_width, constant_values=constant_value)\n        mx_sym = mx.sym.np.pad(\n            data.as_np_ndarray(), mode=mode, pad_width=pad_width, constant_values=constant_value\n        )\n    else:\n        ref_res = np.pad(data_np, mode=mode, pad_width=pad_width)\n        mx_sym = mx.sym.np.pad(data.as_np_ndarray(), mode=mode, pad_width=pad_width)\n    mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@pytest.mark.skipif(\n    not hasattr(mx.sym.np, \"pad\"), reason=\"test'll abort with Mxnet 1.x, skip for now\"\n)\n@pytest.mark.parametrize(\"data_shape\", [(2, 2, 2), (2, 7, 2)])\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@pytest.mark.parametrize(\"axes\", [(1, 0, 2), None])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_transpose(data_shape, axes, dtype, target, dev, kind):\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    data = mx.sym.var(\"data\")\n    ref_res = mx.np.transpose(mx.np.array(data_np), axes=axes)\n    mx_sym = mx.sym.np.transpose(data.as_np_ndarray(), axes=axes)\n    mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"data_shape1, data_shape2, axis\",\n    [\n        ((2, 2), (2, 2), 1),\n        ((2, 4), (2, 3), 1),\n        ((1, 3, 2), (1, 3, 5), 2),\n        ((1, 3, 3), (1, 3, 3), 1),\n        ((1, 3), (1, 3), 0),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_concatenate(data_shape1, data_shape2, axis, dtype, target, dev, kind):\n    data_np1 = np.random.uniform(size=data_shape1).astype(dtype)\n    data_np2 = np.random.uniform(size=data_shape2).astype(dtype)\n    data1 = mx.sym.var(\"data1\")\n    data2 = mx.sym.var(\"data2\")\n    ref_res = mx.np.concatenate([mx.np.array(data_np1), mx.np.array(data_np2)], axis=axis)\n    mx_sym = mx.sym.np.concatenate([data1.as_np_ndarray(), data2.as_np_ndarray()], axis=axis)\n    mod, _ = relay.frontend.from_mxnet(\n        mx_sym, shape={\"data1\": data_shape1, \"data2\": data_shape2}, dtype=dtype\n    )\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n        data_np1, data_np2\n    )\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"data_shape1, data_shape2, axis\",\n    [\n        ((3,), (3,), 0),\n        ((3,), (3,), -1),\n        ((1, 3, 2), (1, 3, 2), 2),\n        ((1, 3, 3), (1, 3, 3), 1),\n        ((1, 3), (1, 3), 0),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_stack(data_shape1, data_shape2, axis, dtype, target, dev, kind):\n    data_np1 = np.random.uniform(size=data_shape1).astype(dtype)\n    data_np2 = np.random.uniform(size=data_shape2).astype(dtype)\n    data1 = mx.sym.var(\"data1\")\n    data2 = mx.sym.var(\"data2\")\n    ref_res = mx.np.stack([mx.np.array(data_np1), mx.np.array(data_np2)], axis=axis)\n    mx_sym = mx.sym.np.stack([data1.as_np_ndarray(), data2.as_np_ndarray()], axis=axis)\n    mod, _ = relay.frontend.from_mxnet(\n        mx_sym, shape={\"data1\": data_shape1, \"data2\": data_shape2}, dtype=dtype\n    )\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n        data_np1, data_np2\n    )\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\"data_shape\", [(2, 2, 2), (2, 7, 2), (2, 2, 2, 1, 2, 3, 1), (1, 8)])\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_np_copy(data_shape, dtype, target, dev, kind):\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    data = mx.sym.var(\"data\")\n    ref_res = mx.np.copy(mx.np.array(data_np))\n    mx_sym = mx.sym.np.copy(data.as_np_ndarray())\n    mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\n@pytest.mark.parametrize(\n    \"data_shape,out_shape,reverse\",\n    [\n        ((2, 3, 8), (-2, -2, 2, -1), False),\n        ((8, 3, 3, 3, 4, 4), (-6, 2, -1, -4), False),\n        ((8, 3, 3, 3, 4, 4), (-5, -4), False),\n        ((1, 8, 3, 3, 3, 4, 4), (-3, -5, -4), False),\n        ((8, 1, 3, 4), (-2, -3, -1), False),\n        ((8, 3, 3, 3, 3, 8), (-4, -5), True),\n        ((8, 3, 2, 4, 8), (-4, -1, 2, -6), True),\n        ((3, 2, 4, 8, 1, 1), (-4, -1, 2, -6, -5, -3), True),\n        ((2, 4, 1, 8), (-4, -3, -1, 2, -6), True),\n    ],\n)\ndef test_forward_npx_reshape(data_shape, out_shape, dtype, target, reverse, dev, kind):\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    data = mx.sym.var(\"data\")\n    ref_res = mx.npx.reshape(mx.np.array(data_np), newshape=out_shape, reverse=reverse)\n    mx_sym = mx.sym.npx.reshape(data.as_np_ndarray(), newshape=out_shape, reverse=reverse)\n    mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"data_shape\", [(2, 2, 2), (2, 7, 2), (2, 2, 2, 1, 2, 3, 1), (1, 8), (2, 2), (1, 3)]\n)\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_binary(data_shape, dtype, target, dev, kind):\n    ref_ops = [mx.np.power, mx.np.multiply, mx.np.add, mx.np.subtract, mx.np.less]\n    mx_ops = [\n        mx.sym.np.power,\n        mx.sym.np.multiply,\n        mx.sym.np.add,\n        mx.sym.np.subtract,\n        mx.sym.np.less,\n    ]\n    for i in range(len(ref_ops)):\n        ref_op = ref_ops[i]\n        mx_op = mx_ops[i]\n        # mx.np.power only support float type\n        if ref_op == mx.np.power and dtype not in [\"float64\", \"float32\"]:\n            continue\n        data_np1 = np.random.uniform(size=data_shape).astype(dtype)\n        data_np2 = np.random.uniform(size=data_shape).astype(dtype)\n        data1 = mx.sym.var(\"lhs\")\n        data2 = mx.sym.var(\"rhs\")\n        ref_res = ref_op(mx.np.array(data_np1), mx.np.array(data_np2))\n        mx_sym = mx_op(data1.as_np_ndarray(), data2.as_np_ndarray())\n        mod, _ = relay.frontend.from_mxnet(\n            mx_sym, shape={\"lhs\": data_shape, \"rhs\": data_shape}, dtype=dtype\n        )\n        op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n            data_np1, data_np2\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"data_shape\", [(2, 2, 2), (2, 7, 2), (2, 2, 2, 1, 2, 3, 1), (1, 8), (2, 2), (1, 3)]\n)\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"scalar\", [1.0, 2.0, 3.0, 4.0])\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_binary_scalar(data_shape, dtype, scalar, target, dev, kind):\n    ref_ops = [mx.np.power, mx.np.multiply, mx.np.add, mx.np.subtract, mx.np.true_divide]\n    mx_ops = [\n        mx.sym.np.power,\n        mx.sym.np.multiply,\n        mx.sym.np.add,\n        mx.sym.np.subtract,\n        mx.sym.np.true_divide,\n    ]\n    for i in range(len(ref_ops)):\n        ref_op = ref_ops[i]\n        mx_op = mx_ops[i]\n        # mx.np.power only support float type\n        if ref_op == mx.np.power and dtype not in [\"float64\", \"float32\"]:\n            continue\n        data_np1 = np.random.uniform(size=data_shape).astype(dtype)\n        data1 = mx.sym.var(\"lhs\")\n        ref_res = ref_op(mx.np.array(data_np1), scalar)\n        mx_sym = mx_op(data1.as_np_ndarray(), scalar)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape={\"lhs\": data_shape}, dtype=dtype)\n        op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n            data_np1\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"data_shape\", [(2, 2, 2), (2, 7, 2), (2, 2, 2, 1, 2, 3, 1), (1, 8), (2, 2), (1, 3)]\n)\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_tanh(data_shape, dtype, target, dev, kind):\n    data_np1 = np.random.uniform(size=data_shape).astype(dtype)\n    data1 = mx.sym.var(\"data\")\n    ref_res = mx.np.tanh(mx.np.array(data_np1))\n    mx_sym = mx.sym.np.tanh(data1.as_np_ndarray())\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shape={\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np1)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.skipif(not hasattr(mx.np, \"where\"), reason=\"mx.np.where hasn't been publish yet\")\n@pytest.mark.parametrize(\n    \"data_shape,cond_shape\",\n    [[(2, 2, 2), (2, 2, 2)], [(2, 7, 2), (7, 2)], [(2, 2), (1, 2)], [(1, 3), (3, 3)]],\n)\n@pytest.mark.parametrize(\"data_dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@pytest.mark.parametrize(\"cond_dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@pytest.mark.parametrize(\"scalar\", [1.0, 2.0])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\ndef test_forward_npi_where_rscalar(\n    data_shape, cond_shape, data_dtype, cond_dtype, scalar, target, dev, kind\n):\n    if data_dtype == \"bool\":\n        scalar = scalar == 0.0\n    cond_np = np.random.uniform(size=cond_shape).astype(cond_dtype)\n    data_np = np.random.uniform(size=data_shape).astype(data_dtype)\n    cond = mx.sym.var(\"condition\")\n    data = mx.sym.var(\"x\")\n    ref_res = mx.np.where(mx.np.array(cond_np), mx.np.array(data_np), scalar)\n    mx_sym = mx.sym.np.where(cond.as_np_ndarray(), data.as_np_ndarray(), scalar)\n    dtypeDic = {}\n    dtypeDic[\"condition\"] = cond_dtype\n    dtypeDic[\"x\"] = data_dtype\n    mod, _ = relay.frontend.from_mxnet(\n        mx_sym, shape={\"condition\": cond_shape, \"x\": data_shape}, dtype=dtypeDic\n    )\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n        cond_np, data_np\n    )\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res.asnumpy(), rtol=1e-5)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float64\", \"float32\", \"int64\", \"int32\", \"bool\"])\n@tvm.testing.parametrize_targets\n@pytest.mark.parametrize(\"kind\", [\"graph\", \"vm\", \"debug\"])\n@pytest.mark.parametrize(\n    \"data_shape, axis, indices_or_sections, squeeze_axis\",\n    [\n        ((3, 2, 1), 1, 2, False),\n        ((3, 2, 1), 0, 3, False),\n        ((3, 2, 1), 0, 3, True),\n        ((3, 2, 1), 0, (1, 2), False),\n    ],\n)\ndef test_forward_split_v2(\n    data_shape, axis, dtype, indices_or_sections, squeeze_axis, target, dev, kind\n):\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    data = mx.sym.var(\"data\")\n    ref_res = mx.ndarray.split_v2(\n        mx.nd.array(data_np), indices_or_sections, axis=axis, squeeze_axis=squeeze_axis\n    )\n    mx_sym = mx.sym.split_v2(\n        data.as_nd_ndarray(), indices_or_sections, axis=axis, squeeze_axis=squeeze_axis\n    )\n    mod, _ = relay.frontend.from_mxnet(mx_sym, {\"data\": data_shape}, dtype=dtype)\n    op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(data_np)\n    op_res_ = []\n    for arr in op_res:\n        op_res_.append(arr.numpy().tolist())\n    ref_res_ = []\n    for arr in ref_res:\n        ref_res_.append(arr.asnumpy().tolist())\n    tvm.testing.assert_allclose(op_res_, ref_res_, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    pytest.main([\"test_forward.py\"])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/test_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport mxnet as mx\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\nimport model_zoo\n\n\ndef compare_graph(lhs_mod, rhs_mod):\n    lhs_mod = transform.InferType()(lhs_mod)\n    rhs_mod = transform.InferType()(rhs_mod)\n    assert tvm.ir.structural_equal(lhs_mod[\"main\"], rhs_mod[\"main\"])\n\n\ndef test_mlp():\n    shape = {\"data\": (1, 1, 28, 28)}\n    mx_fun = model_zoo.mx_mlp()\n    mod, _ = relay.frontend.from_mxnet(mx_fun, shape=shape)\n    relay_fun = model_zoo.relay_mlp()\n    compare_graph(mod, relay_fun)\n\n\ndef test_vgg():\n    shape = {\"data\": (1, 3, 224, 224)}\n    for n in [11, 13, 16, 19]:\n        mx_sym = model_zoo.mx_vgg(n)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape=shape)\n        relay_mod = model_zoo.relay_vgg(n)\n        compare_graph(mod, relay_mod)\n\n\ndef test_resnet():\n    shape = {\"data\": (1, 3, 224, 224)}\n    for n in [18, 34, 50, 101]:\n        mx_sym = model_zoo.mx_resnet(n)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape=shape)\n        relay_mod = model_zoo.relay_resnet(n)\n        compare_graph(mod, relay_mod)\n\n\ndef test_squeezenet():\n    shape = {\"data\": (1, 3, 224, 224)}\n    for version in [\"1.0\", \"1.1\"]:\n        mx_sym = model_zoo.mx_squeezenet(version)\n        mod, _ = relay.frontend.from_mxnet(mx_sym, shape)\n        relay_mod = model_zoo.relay_squeezenet(version)\n        compare_graph(mod, relay_mod)\n\n\ndef test_inception_v3():\n    shape = {\"data\": (1, 3, 299, 299)}\n    mx_sym = model_zoo.mx_inception_v3()\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shape)\n    relay_mod = model_zoo.relay_inception_v3()\n    compare_graph(mod, relay_mod)\n\n\ndef test_dqn():\n    shape = {\"data\": (1, 4, 84, 84)}\n    mx_sym = model_zoo.mx_dqn()\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shape)\n    relay_mod = model_zoo.relay_dqn()\n    compare_graph(mod, relay_mod)\n\n\ndef test_dcgan():\n    shape = {\"data\": (2, 100)}\n    mx_sym = model_zoo.mx_dcgan()\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shape)\n    relay_mod = model_zoo.relay_dcgan(batch_size=2)\n    compare_graph(mod, relay_mod)\n\n\ndef test_multi_outputs():\n    xshape = (10, 27)\n    yshape = (10, 9)\n\n    def mx_compose(F, **kwargs):\n        x = F.sym.Variable(\"x\")\n        y = F.sym.Variable(\"y\")\n        z = F.sym.split(x, **kwargs)\n        return F.sym.broadcast_sub(F.sym.broadcast_add(z[0], z[2]), y)\n\n    def relay_compose(F, **kwargs):\n        x = F.var(\"x\", shape=xshape)\n        y = F.var(\"y\", shape=yshape)\n        z = F.split(x, **kwargs)\n        z = F.subtract(F.add(z[0], z[2]), y)\n        func = relay.Function(relay.analysis.free_vars(z), z)\n        return tvm.IRModule.from_expr(func)\n\n    mx_sym = mx_compose(mx, num_outputs=3, axis=1)\n    mod, _ = relay.frontend.from_mxnet(mx_sym, shape={\"x\": xshape, \"y\": yshape})\n    relay_mod = relay_compose(relay, indices_or_sections=3, axis=1)\n    compare_graph(mod, relay_mod)\n\n\nif __name__ == \"__main__\":\n    test_mlp()\n    test_resnet()\n    test_vgg()\n    test_multi_outputs()\n    test_dqn()\n    test_dcgan()\n    test_squeezenet()\n    test_inception_v3()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/mxnet/test_qnn_ops_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.frontend.mxnet_qnn_op_utils import (\n    dequantize_mxnet_min_max,\n    quantize_mxnet_min_max,\n    get_mkldnn_int8_scale,\n    get_mkldnn_uint8_scale,\n    quantize_conv_bias_mkldnn_from_var,\n)\n\n\ndef test_mkldnn_dequantize():\n    def dequantize_test_driver(in_dtype, quant_args, in_data, verify_output_data):\n        shape = in_data.shape\n        input_data = relay.var(\"input_data\", shape=shape, dtype=in_dtype)\n        min_range = quant_args[\"min_range\"]\n        max_range = quant_args[\"max_range\"]\n        dequantized_output = dequantize_mxnet_min_max(\n            input_data, min_range=min_range, max_range=max_range, in_dtype=in_dtype\n        )\n        mod = relay.Function(relay.analysis.free_vars(dequantized_output), dequantized_output)\n        mod = tvm.IRModule.from_expr(mod)\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(mod, \"llvm\", params=None)\n            rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            rt_mod.set_input(input_data=in_data)\n            rt_mod.set_input(**params)\n            rt_mod.run()\n            res = rt_mod.get_output(0).numpy()\n            assert np.allclose(res, verify_output_data)\n            assert res.dtype == np.float32\n\n    def test_uint8_to_float32():\n        data = np.array([0, 1, 2, 3, 4, 251, 252, 253, 254, 255]).astype(\"uint8\").reshape((2, 5))\n        output = (\n            np.array(\n                [\n                    0.0,\n                    0.25048923,\n                    0.50097847,\n                    0.7514677,\n                    1.0019569,\n                    62.8728,\n                    63.123287,\n                    63.373775,\n                    63.624268,\n                    63.874756,\n                ]\n            )\n            .astype(\"float32\")\n            .reshape((2, 5))\n        )\n        quant_args = {\"min_range\": -63.5, \"max_range\": 64}\n        dequantize_test_driver(\n            in_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output\n        )\n\n    def test_int8_to_float32():\n        data = (\n            np.array([-126, -125, -124, -123, -122, 123, 124, 125, 126, 127])\n            .astype(\"int8\")\n            .reshape((2, 5))\n        )\n        output = (\n            np.array(\n                [\n                    -63.247063,\n                    -62.745102,\n                    -62.24314,\n                    -61.74118,\n                    -61.23922,\n                    61.74118,\n                    62.24314,\n                    62.745102,\n                    63.247063,\n                    63.749023,\n                ]\n            )\n            .astype(\"float32\")\n            .reshape((2, 5))\n        )\n        dequantize_args = {\"min_range\": -63.5, \"max_range\": 64}\n        dequantize_test_driver(\n            in_dtype=\"int8\", quant_args=dequantize_args, in_data=data, verify_output_data=output\n        )\n\n    test_uint8_to_float32()\n    test_int8_to_float32()\n\n\ndef test_mkldnn_quantize():\n    def quantize_test_driver(out_dtype, quant_args, in_data, verify_output_data):\n        shape = in_data.shape\n        input_data = relay.var(\"input_data\", shape=shape, dtype=\"float32\")\n        min_range = quant_args[\"min_range\"]\n        max_range = quant_args[\"max_range\"]\n        quantized_output, _, _ = quantize_mxnet_min_max(\n            input_data, min_range=min_range, max_range=max_range, out_dtype=out_dtype\n        )\n        mod = relay.Function(relay.analysis.free_vars(quantized_output), quantized_output)\n        mod = tvm.IRModule.from_expr(mod)\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(mod, \"llvm\", params=None)\n            rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            rt_mod.set_input(input_data=in_data)\n            rt_mod.set_input(**params)\n            rt_mod.run()\n            res = rt_mod.get_output(0).numpy()\n            assert np.allclose(res, verify_output_data)\n            assert res.dtype == verify_output_data.dtype\n\n    def test_float32_to_uint8():\n        data = (\n            np.array(\n                [\n                    0.0,\n                    0.25048923,\n                    0.50097847,\n                    0.7514677,\n                    1.0019569,\n                    62.8728,\n                    63.123287,\n                    63.373775,\n                    63.624268,\n                    63.874756,\n                ]\n            )\n            .astype(\"float32\")\n            .reshape((2, 5))\n        )\n        output = np.array([0, 1, 2, 3, 4, 251, 252, 253, 254, 255]).astype(\"uint8\").reshape((2, 5))\n\n        quant_args = {\"min_range\": -63.5, \"max_range\": 64}\n        quantize_test_driver(\n            out_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output\n        )\n\n    def test_float32_to_int8():\n        data = (\n            np.array(\n                [\n                    -63.247063,\n                    -62.745102,\n                    -62.24314,\n                    -61.74118,\n                    -61.23922,\n                    61.74118,\n                    62.24314,\n                    62.745102,\n                    63.247063,\n                    63.749023,\n                ]\n            )\n            .astype(\"float32\")\n            .reshape((2, 5))\n        )\n        output = (\n            np.array([-126, -125, -124, -123, -122, 123, 124, 125, 126, 127])\n            .astype(\"int8\")\n            .reshape((2, 5))\n        )\n\n        quant_args = {\"min_range\": -63.5, \"max_range\": 64}\n        quantize_test_driver(\n            out_dtype=\"int8\", quant_args=quant_args, in_data=data, verify_output_data=output\n        )\n\n    test_float32_to_uint8()\n    test_float32_to_int8()\n\n\ndef test_get_mkldnn_int8_scale():\n    range_min = -3.904039\n    range_max = 3.904039\n    expected = 0.03061991354976495\n    output = get_mkldnn_int8_scale(range_max=range_max, range_min=range_min)\n    assert np.allclose(output, expected)\n\n\ndef test_get_mkldnn_uint8_scale():\n    range_min = 0.0\n    range_max = 55.77269\n    expected = 0.21828841189047482\n    output = get_mkldnn_uint8_scale(range_max=range_max, range_min=range_min)\n    assert np.allclose(output, expected)\n\n\ndef test_quantize_conv_bias_mkldnn_from_var():\n    bias_var = relay.var(\"bias\", shape=(3,), dtype=\"float32\")\n    bias_scale = tvm.nd.array(np.array([0.5, 0.6, 0.7]))\n    output = quantize_conv_bias_mkldnn_from_var(bias_var, bias_scale)\n    assert isinstance(output, tvm.relay.expr.Call)\n    attrs = output.attrs\n    assert attrs.axis == 0\n    assert attrs.out_dtype == \"int32\"\n    assert output.op.name == \"qnn.quantize\"\n    assert output.args[1].data == bias_scale\n\n\nif __name__ == \"__main__\":\n    test_mkldnn_dequantize()\n    test_mkldnn_quantize()\n    test_get_mkldnn_int8_scale()\n    test_get_mkldnn_uint8_scale()\n    test_quantize_conv_bias_mkldnn_from_var()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/oneflow/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=arguments-differ, unused-argument\n\"\"\"Unit tests for various models and operators\"\"\"\nimport os\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\n\nimport oneflow as flow\n\nMODEL_HOME = \"test_model\"\n\n\ndef mkdir(path):\n    # init\n    path = path.strip()\n    path = path.rstrip(\"\\\\\")\n\n    if not os.path.exists(path):\n        os.makedirs(path)\n    else:\n        print(f\"{path} is already here\")\n\n\ndef rmdir(path):\n    for root, dirs, files in os.walk(path, topdown=False):\n        for name in files:\n            os.remove(os.path.join(root, name))\n        for name in dirs:\n            os.rmdir(os.path.join(root, name))\n    os.removedirs(path)\n\n\ndef assert_shape(out1, out2):\n    if out1.shape != out2.shape:\n        msg = \"Output shapes {} and {} don't match\"\n        raise AssertionError(msg.format(out1.shape, out2.shape))\n\n\nclass OneFlowGraph(flow.nn.Graph):\n    def __init__(self, module):\n        super().__init__()\n        self.m = module\n\n    def build(self, x):\n        out = self.m(x)\n        return out\n\n\nclass OneFlowGraphV2(flow.nn.Graph):\n    def __init__(self, module):\n        super().__init__()\n        self.m = module\n\n    def build(self, input_1, input_2, input_3):\n        out = self.m(input_1, input_2, input_3)\n        return out\n\n\nclass OneFlowGraphV3(flow.nn.Graph):\n    def __init__(self, module):\n        super().__init__()\n        self.m = module\n\n    def build(self, input_1, input_2):\n        out = self.m(input_1, input_2)\n        return out\n\n\ndef get_oneflow_output(model, inputs):\n    flow_output = model(inputs)\n    return flow_output.numpy()\n\n\ndef get_oneflow_concat_output(model, input1, input2, input3):\n    flow_output = model(input1, input2, input3).numpy()\n    return flow_output\n\n\ndef get_oneflow_elementwise_output(model, input1, input2):\n    return model(input1, input2).numpy()\n\n\ndef get_tvm_output(graph, model_path, inputs: flow.tensor, target=\"llvm\", dtype=\"float32\"):\n    \"\"\"Generic function to execute and get tvm output\"\"\"\n    inputs_numpy = inputs.numpy()\n    if target == \"llvm\":\n        device = tvm.cpu(0)\n    elif target == \"cuda\":\n        device = tvm.cuda(0)\n\n    mod, params = relay.frontend.from_oneflow(graph, model_path)\n    with tvm.transform.PassContext(opt_level=10):\n        intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n    tvm_output = intrp.evaluate()(tvm.nd.array(inputs_numpy.astype(dtype)), **params).numpy()\n    return tvm_output\n\n\ndef get_tvm_concat_output(\n    graph,\n    model_path,\n    input1: flow.tensor,\n    input2: flow.tensor,\n    input3: flow.tensor,\n    target=\"llvm\",\n    dtype=\"float32\",\n):\n    \"\"\"Generic function to execute and get tvm concat output\"\"\"\n    input1_numpy = input1.numpy()\n    input2_numpy = input2.numpy()\n    input3_numpy = input3.numpy()\n    if target == \"llvm\":\n        device = tvm.cpu(0)\n    elif target == \"cuda\":\n        device = tvm.cuda(0)\n\n    mod, params = relay.frontend.from_oneflow(graph, model_path)\n    with tvm.transform.PassContext(opt_level=10):\n        intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n    tvm_output = intrp.evaluate()(\n        tvm.nd.array(input1_numpy.astype(dtype)),\n        tvm.nd.array(input2_numpy.astype(dtype)),\n        tvm.nd.array(input3_numpy.astype(dtype)),\n        **params,\n    ).numpy()\n    return tvm_output\n\n\ndef get_tvm_elementwise_output(\n    graph,\n    model_path,\n    input1: flow.tensor,\n    input2: flow.tensor,\n    target=\"llvm\",\n    dtype=\"float32\",\n):\n    \"\"\"Generic function to execute and get tvm elementwise output\"\"\"\n    input1_numpy = input1.numpy()\n    input2_numpy = input2.numpy()\n    if target == \"llvm\":\n        device = tvm.cpu(0)\n    elif target == \"cuda\":\n        device = tvm.cuda(0)\n\n    mod, params = relay.frontend.from_oneflow(graph, model_path)\n    with tvm.transform.PassContext(opt_level=10):\n        intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n    tvm_output = intrp.evaluate()(\n        tvm.nd.array(input1_numpy.astype(dtype)),\n        tvm.nd.array(input2_numpy.astype(dtype)),\n        **params,\n    ).numpy()\n    return tvm_output\n\n\ndef verify_conv(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 224, 224),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_conv\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_pool(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 224, 224),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_pool\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_normalization(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 224, 224),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_normalization\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    # write params\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_upsample(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 50, 50),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_upsample\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_convtran(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 50, 50),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_convtran\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_activation(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(10, 10),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_activation\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_math(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(100, 1),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"verify_math\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_matmul(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs1=flow.tensor(np.random.randn(2, 5), dtype=flow.float32),\n    inputs2=flow.tensor(np.random.randn(5, 2), dtype=flow.float32),\n    device=\"llvm\",\n):\n    \"\"\"verify_matmul\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs1 = inputs1.to(device)\n        inputs2 = inputs2.to(device)\n\n    graph = OneFlowGraphV3(model)\n    graph._compile(inputs1, inputs2)\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_elementwise_output(graph, inputs1, inputs2)\n    out_tvm = get_tvm_elementwise_output(graph, MODEL_HOME, inputs1, inputs2, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_concat(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs1=flow.tensor(np.random.randn(2, 5, 5, 4), dtype=flow.float32),\n    inputs2=flow.tensor(np.random.randn(2, 5, 5, 2), dtype=flow.float32),\n    inputs3=flow.tensor(np.random.randn(2, 5, 5, 3), dtype=flow.float32),\n    device=\"llvm\",\n):\n    \"\"\"verify_concat\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs1 = inputs1.to(device)\n        inputs2 = inputs2.to(device)\n        inputs3 = inputs3.to(device)\n\n    graph = OneFlowGraphV2(model)\n    graph._compile(inputs1, inputs2, inputs3)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_concat_output(graph, inputs1, inputs2, inputs3)\n    out_tvm = get_tvm_concat_output(graph, MODEL_HOME, inputs1, inputs2, inputs3, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\n# defs/nn\n@tvm.testing.uses_gpu\ndef test_conv2d():\n    \"\"\"Conv2d\"\"\"\n\n    class Conv2dModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = flow.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)\n\n        def forward(self, x):\n            x = self.conv(x)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model = Conv2dModel()\n    model.eval()\n\n    for device in [\"llvm\"]:\n        verify_conv(model, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_pool2d():\n    \"\"\"Pool2d\"\"\"\n\n    class MaxPool2dModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.pool = flow.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        def forward(self, x):\n            x = self.pool(x)\n            return x\n\n    class AvgPool2dModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.pool = flow.nn.AvgPool2d(kernel_size=3, stride=2, padding=1)\n\n        def forward(self, x):\n            x = self.pool(x)\n            return x\n\n    class AdaptiveAvgPool2dModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.pool = flow.nn.AdaptiveAvgPool2d((None, 7))\n\n        def forward(self, x):\n            x = self.pool(x)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model1 = MaxPool2dModel().eval()\n    model2 = AvgPool2dModel().eval()\n    model3 = AdaptiveAvgPool2dModel().eval()\n\n    for device in [\"llvm\"]:\n        verify_pool(model1, device=device)\n        verify_pool(model2, device=device)\n        verify_pool(model3, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_normalization():\n    \"\"\"Normalization\"\"\"\n\n    class BatchNorm2dModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.normalization = flow.nn.BatchNorm2d(3)\n\n        def forward(self, x):\n            x = self.normalization(x)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model = BatchNorm2dModel().eval()\n\n    for device in [\"llvm\"]:\n        verify_normalization(model, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_upsample():\n    \"\"\"Upsample\"\"\"\n\n    class UpsampleModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.upsample = flow.nn.Upsample(scale_factor=2.0, mode=\"nearest\")\n\n        def forward(self, x):\n            x = self.upsample(x)\n            return x\n\n    class UpsampleBiliModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.upsample = flow.nn.UpsamplingBilinear2d(scale_factor=2.0)\n\n        def forward(self, x):\n            x = self.upsample(x)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model1 = UpsampleModel().eval()\n    model2 = UpsampleBiliModel().eval()\n\n    for device in [\"llvm\"]:\n        verify_upsample(model1, device=device)\n        verify_upsample(model2, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_convtran():\n    \"\"\"ConvTran\"\"\"\n\n    class ConvTranModel(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.convtran = flow.nn.ConvTranspose2d(3, 4, (3, 5), stride=(2, 1), padding=(4, 2))\n\n        def forward(self, x):\n            x = self.convtran(x)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model = ConvTranModel().eval()\n\n    for device in [\"llvm\"]:\n        verify_convtran(model, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_activation():\n    \"\"\"Activation\"\"\"\n\n    class Softmax(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.Softmax()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class Softplus(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.Softplus()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class Softsign(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.Softsign()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class Tanh(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.Tanh()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class ReLU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.ReLU()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class ReLU6(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.ReLU6()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class PReLU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.PReLU()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class SELU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.SELU()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class SiLU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.SiLU()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class LeakyReLU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.LeakyReLU(0.1)\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class GELU(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.GELU()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class HardTanh(flow.nn.Module):\n        def __init__(self):\n            super().__init__()\n            self.active = flow.nn.Hardtanh()\n\n        def forward(self, x):\n            x = self.active(x)\n            return x\n\n    class TensorSoftmax(flow.nn.Module):\n        def forward(self, x):\n            x = x.softmax(dim=-1)\n            return x\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    model1 = Softmax().eval()\n    model2 = Softplus().eval()  # pylint: disable=unused-variable\n    model3 = Softsign().eval()\n    model4 = Tanh().eval()\n    model5 = ReLU().eval()\n    model6 = ReLU6().eval()\n    model7 = PReLU().eval()\n    model8 = SELU().eval()\n    model9 = SiLU().eval()\n    model10 = LeakyReLU().eval()\n    model11 = GELU().eval()\n    model12 = HardTanh().eval()\n    model13 = TensorSoftmax().eval()\n\n    for device in [\"llvm\"]:\n        verify_activation(model1, device=device)\n        # verify_activation(model2, device=device) # NO PASS\n        verify_activation(model3, device=device)\n        verify_activation(model4, device=device)\n        verify_activation(model5, device=device)\n        verify_activation(model6, device=device)\n        verify_activation(model7, device=device)\n        verify_activation(model8, device=device)\n        verify_activation(model9, device=device)\n        verify_activation(model10, device=device)\n        verify_activation(model11, device=device)\n        verify_activation(model12, device=device)\n        verify_activation(\n            model13,\n            device=device,\n            inputs=flow.tensor(np.random.rand(1, 12, 197, 197).astype(np.float32)),\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_math():\n    \"\"\"Math\"\"\"\n\n    class Sigmoid(flow.nn.Module):\n        def forward(self, x):\n            return flow.sigmoid(x)\n\n    class Sign(flow.nn.Module):\n        def forward(self, x):\n            return flow.sign(x)\n\n    class Reciprocal(flow.nn.Module):\n        def forward(self, x):\n            return flow.reciprocal(x)\n\n    class Pow(flow.nn.Module):\n        def forward(self, x):\n            return flow.pow(x, 2.0)\n\n    class Log(flow.nn.Module):\n        def forward(self, x):\n            return flow.log(x)\n\n    class Log2(flow.nn.Module):\n        def forward(self, x):\n            return flow.log1p(x)\n\n    class Exp(flow.nn.Module):\n        def forward(self, x):\n            return flow.exp(x)\n\n    class Exp2(flow.nn.Module):\n        def forward(self, x):\n            return flow.expm1(x)\n\n    class Variance(flow.nn.Module):\n        def forward(self, x):\n            return flow.var(x, 1, unbiased=False, keepdim=True)\n\n    model1 = Sigmoid().eval()\n    model2 = Sign().eval()\n    model3 = Log().eval()\n    model4 = Log2().eval()\n    model5 = Exp().eval()\n    model6 = Exp2().eval()\n    model7 = Reciprocal().eval()\n    model8 = Pow().eval()\n    model9 = Variance().eval()\n\n    for device in [\"llvm\"]:\n        verify_math(model1, device=device)\n        verify_math(model2, device=device)\n        verify_math(model3, device=device)\n        verify_math(model4, device=device)\n        verify_math(model5, device=device)\n        verify_math(model6, device=device)\n        verify_math(model7, device=device)\n        verify_math(model8, device=device)\n        verify_math(model9, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_slice():\n    \"\"\"Slice\"\"\"\n\n    class Slice(flow.nn.Module):\n        def forward(self, x):\n            tup_list = [[None, None, None], [0, 5, 2], [0, 6, 3]]\n            out = flow.slice(x, slice_tup_list=tup_list)\n            return out\n\n    model = Slice().eval()\n\n    for device in [\"llvm\"]:\n        verify_math(\n            model, device=device, inputs=flow.tensor(np.random.randn(3, 6, 9).astype(np.float32))\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_concat():\n    \"\"\"Concat\"\"\"\n\n    class Concat(flow.nn.Module):\n        def forward(self, input_1, input_2, input_3):\n            out = flow.cat([input_1, input_2, input_3], dim=-1)\n            return out\n\n    model = Concat().eval()\n\n    for device in [\"llvm\"]:\n        verify_concat(model, device=device)\n\n\n@tvm.testing.uses_gpu\ndef test_add_constant():\n    \"\"\"ConstantAdd\"\"\"\n\n    class ConstantAdd(flow.nn.Module):\n        def forward(self, x):\n            out = flow.add(1.0, x)\n            return out\n\n    model = ConstantAdd().eval()\n\n    for device in [\"llvm\"]:\n        verify_math(\n            model, device=device, inputs=flow.tensor(np.random.randn(3, 6, 9).astype(np.float32))\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_logical():\n    class LogicalGreater(flow.nn.Module):\n        def forward(self, x):\n            return x > 1.0\n\n    model1 = LogicalGreater().eval()\n\n    for device in [\"llvm\"]:\n        verify_math(\n            model1, device=device, inputs=flow.tensor(np.random.randn(3, 6, 9).astype(np.float32))\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_expand():\n    class Expand(flow.nn.Module):\n        def forward(self, x):\n            return x.expand(2, -1, -1)\n\n    model1 = Expand().eval()\n\n    for device in [\"llvm\"]:\n        verify_math(\n            model1, device=device, inputs=flow.tensor(np.random.randn(1, 6, 9).astype(np.float32))\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_matmul():\n    \"\"\"MatMul\"\"\"\n\n    class MatMul(flow.nn.Module):\n        def forward(self, x, y):\n            return flow._C.matmul(x, y)\n\n    class MatMulTranspose(flow.nn.Module):\n        def forward(self, x, y):\n            return flow._C.matmul(x, y, transpose_b=True)\n\n    class BatchMatMul(flow.nn.Module):\n        def forward(self, x, y):\n            return flow._C.batch_matmul(x, y)\n\n    class BroadCastMatMul(flow.nn.Module):\n        def forward(self, x, y):\n            return flow._C.matmul(x, y)\n\n    model1 = MatMul().eval()\n    model2 = MatMulTranspose().eval()\n    model3 = BatchMatMul().eval()\n    model4 = BroadCastMatMul().eval()\n\n    for device in [\"llvm\"]:\n        verify_matmul(\n            model1,\n            device=device,\n            inputs1=flow.tensor(np.random.randn(2, 3).astype(np.float32)),\n            inputs2=flow.tensor(np.random.randn(3, 3).astype(np.float32)),\n        )\n        verify_matmul(\n            model2,\n            device=device,\n            inputs1=flow.tensor(np.random.randn(1, 2).astype(np.float32)),\n            inputs2=flow.tensor(np.random.randn(3, 2).astype(np.float32)),\n        )\n        verify_matmul(\n            model3,\n            device=device,\n            inputs1=flow.tensor(np.random.randn(2, 1, 2).astype(np.float32)),\n            inputs2=flow.tensor(np.random.randn(2, 2, 3).astype(np.float32)),\n        )\n        verify_matmul(\n            model4,\n            device=device,\n            inputs1=flow.tensor(np.random.randn(3, 8, 8, 16).astype(np.float32)),\n            inputs2=flow.tensor(np.random.randn(16, 8).astype(np.float32)),\n        )\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n    test_pool2d()\n    test_normalization()\n    test_upsample()\n    test_convtran()\n    test_activation()\n    test_math()\n    test_slice()\n    test_concat()\n    test_add_constant()\n    test_logical()\n    test_expand()\n    test_matmul()\n    rmdir(\"log\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/oneflow/test_vision_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name\n# pylint: disable=arguments-differ, unused-argument\n\"\"\"Unit tests for various models and operators\"\"\"\nimport os\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\n\nimport oneflow as flow\nfrom flowvision.models.alexnet import alexnet\nfrom flowvision.models.squeezenet import squeezenet1_0\nfrom flowvision.models.shufflenet_v2 import shufflenet_v2_x0_5\nfrom flowvision.models.mobilenet import mobilenet_v2\nfrom flowvision.models.ghostnet import ghostnet\nfrom flowvision.models.vision_transformer import vit_base_patch16_224\n\nMODEL_HOME = \"test_model\"\n\n\ndef mkdir(path):\n    # init\n    path = path.strip()\n    path = path.rstrip(\"\\\\\")\n\n    if not os.path.exists(path):\n        os.makedirs(path)\n    else:\n        print(f\"{path} is already here\")\n\n\ndef rmdir(path):\n    for root, dirs, files in os.walk(path, topdown=False):\n        for name in files:\n            os.remove(os.path.join(root, name))\n        for name in dirs:\n            os.rmdir(os.path.join(root, name))\n    os.removedirs(path)\n\n\ndef assert_shape(out1, out2):\n    if out1.shape != out2.shape:\n        msg = \"Output shapes {} and {} don't match\"\n        raise AssertionError(msg.format(out1.shape, out2.shape))\n\n\nclass OneFlowGraph(flow.nn.Graph):\n    def __init__(self, module):\n        super().__init__()\n        self.m = module\n\n    def build(self, x):\n        out = self.m(x)\n        return out\n\n\ndef get_oneflow_output(model, inputs):\n    flow_output = model(inputs)\n    return flow_output.numpy()\n\n\ndef get_tvm_output(graph, model_path, inputs: flow.tensor, target=\"llvm\", dtype=\"float32\"):\n    \"\"\"Generic function to execute and get tvm output\"\"\"\n    inputs_numpy = inputs.numpy()\n    if target == \"llvm\":\n        device = tvm.cpu(0)\n    elif target == \"cuda\":\n        device = tvm.cuda(0)\n\n    mod, params = relay.frontend.from_oneflow(graph, model_path)\n    with tvm.transform.PassContext(opt_level=10):\n        intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n    tvm_output = intrp.evaluate()(tvm.nd.array(inputs_numpy.astype(dtype)), **params).numpy()\n    return tvm_output\n\n\ndef verify_model(\n    model,\n    name=\"\",\n    rtol=1e-5,\n    atol=1e-5,\n    inputs=flow.tensor(\n        np.random.rand(1, 3, 224, 224),\n        dtype=flow.float32,\n    ),\n    device=\"llvm\",\n):\n    \"\"\"Generic function to generate and compare oneflow and TVM output\"\"\"\n    if device == \"cuda\":\n        model.to(device)\n        inputs = inputs.to(device)\n\n    graph = OneFlowGraph(model)\n    graph._compile(inputs)\n\n    mkdir(MODEL_HOME)\n    flow.save(model.state_dict(), MODEL_HOME)\n\n    out_flow = get_oneflow_output(graph, inputs)\n    out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n    rmdir(MODEL_HOME)\n\n    assert_shape(out_flow, out_tvm)\n    tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\n@tvm.testing.uses_gpu\ndef test_vision_models():\n    \"\"\"Vision models test\"\"\"\n\n    if os.path.exists(MODEL_HOME):\n        rmdir(MODEL_HOME)\n\n    vision_alexnet = alexnet().eval()\n    vision_squeezenet = squeezenet1_0().eval()\n    vision_shufflenet = shufflenet_v2_x0_5().eval()\n    vision_mobilenetv2 = mobilenet_v2().eval()\n    vision_ghostnet = ghostnet().eval()\n    vision_vit = vit_base_patch16_224().eval()\n\n    for device in [\"llvm\"]:\n        verify_model(vision_alexnet, device=device)\n        verify_model(vision_squeezenet, device=device)\n        verify_model(vision_shufflenet, device=device)\n        verify_model(vision_mobilenetv2, device=device)\n        verify_model(vision_ghostnet, device=device)\n        verify_model(vision_vit, device=device)\n\n\nif __name__ == \"__main__\":\n    test_vision_models()\n    rmdir(\"log\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/onnx/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"\nONNX testcases\n================\nThis article is a test script to test ONNX operator with Relay.\n\"\"\"\nimport glob\nimport os\nimport platform\nimport re\nimport copy\nimport tempfile\nimport pytest\nimport scipy\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\nimport onnx\nimport onnxruntime.backend\nfrom onnx import TensorProto, helper, mapping, numpy_helper\nfrom onnxruntime.quantization import CalibrationDataReader, quantize_static\n\nimport torch\nimport torchvision\nfrom torch.nn import Linear, Module, Sequential\n\n\ndef get_input_data_shape_dict(graph_def, input_data):\n    \"\"\"Get input data shape\"\"\"\n    if isinstance(input_data, list):\n        input_names = {}\n        shape_dict = {}\n        for i, _ in enumerate(input_data):\n            input_names[i] = graph_def.graph.input[i].name\n            input_ = input_data[i]\n\n            if input_ is None or not hasattr(input_, \"shape\") or input_.shape == ():\n                # Skip adding input shape data when the input data is None;\n                # This is to enable optional arguments for onnx operators.\n                continue\n\n            elif isinstance(input_, list):\n                shape_dict[input_names[i]] = (len(input_),)\n\n            else:\n                shape_dict[input_names[i]] = input_.shape\n\n    else:\n        input_names = graph_def.graph.input[0].name\n        shape_dict = {input_names: input_data.shape}\n\n    return input_names, shape_dict\n\n\ndef get_tvm_output_with_vm(\n    graph_def,\n    input_data,\n    target,\n    dev,\n    opset=None,\n    freeze_params=False,\n    convert_config=None,\n):\n    \"\"\"Generic function to execute and get tvm output with vm executor\"\"\"\n    if not isinstance(input_data, list):\n        input_data = [input_data]\n    _, shape_dict = get_input_data_shape_dict(graph_def, input_data)\n    mod, params = relay.frontend.from_onnx(\n        graph_def,\n        shape_dict,\n        opset=opset,\n        freeze_params=freeze_params,\n        convert_config=convert_config,\n    )\n\n    result = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(\n        *input_data, **params\n    )\n    if isinstance(result, tvm.runtime.NDArray):\n        return result.numpy()\n    return [r.numpy() for r in result]\n\n\ndef get_tvm_output(\n    graph_def,\n    input_data,\n    target,\n    dev,\n    output_shape=None,\n    output_dtype=\"float32\",\n    opset=None,\n    opt_level=1,\n    convert_config=None,\n):\n    \"\"\"Generic function to execute and get tvm output\"\"\"\n    # TODO: Resolve the issues and remove the following lines\n    input_names, shape_dict = get_input_data_shape_dict(graph_def, input_data)\n\n    mod, params = relay.frontend.from_onnx(\n        graph_def, shape_dict, opset=opset, convert_config=convert_config\n    )\n\n    with tvm.transform.PassContext(opt_level=opt_level):\n        graph, lib, params = relay.build(mod, target, params=params)\n\n    m = graph_executor.create(graph, lib, dev)\n    # set inputs\n    if isinstance(input_data, list):\n        for i, _ in enumerate(input_names):\n            # Its possible for some onnx inputs to not be needed in the tvm\n            # module, confirm its present before setting.\n            # pylint: disable=unnecessary-list-index-lookup\n            m.set_input(input_names[i], tvm.nd.array(input_data[i].astype(input_data[i].dtype)))\n    else:\n        m.set_input(input_names, tvm.nd.array(input_data.astype(input_data.dtype)))\n\n    m.set_input(**params)\n    # execute\n    m.run()\n    # get outputs\n    if isinstance(output_shape, list):\n        tvm_output_list = []\n        for i, _ in enumerate(output_shape):\n            tvm_output = m.get_output(i)\n            tvm_output_list.append(tvm_output.numpy())\n        return tvm_output_list\n    else:\n        tvm_output = m.get_output(0)\n        return tvm_output.numpy()\n\n\ndef get_onnxruntime_output(model, inputs):\n    \"\"\"Generic function to generate onnxruntime output\"\"\"\n    rep = onnxruntime.backend.prepare(model.SerializeToString(), \"CPU\")\n    if isinstance(inputs, list) and len(inputs) == 1:\n        inp = inputs[0]\n    else:\n        inp = inputs\n    output = rep.run(inp)\n    # Unpack output if there's only a single value.\n    if len(output) == 1:\n        output = output[0]\n    return output\n\n\ndef verify_with_ort_with_inputs(\n    model,\n    inputs,\n    out_shape=None,\n    target=None,\n    dev=None,\n    use_vm=False,\n    opset=None,\n    freeze_params=False,\n    dtype=\"float32\",\n    rtol=1e-5,\n    atol=1e-5,\n    apply_softmax=False,\n    opt_level=1,\n    convert_config=None,\n):\n    \"\"\"verify_with_ort_with_inputs\"\"\"\n    if opset is not None:\n        model.opset_import[0].version = opset\n\n    ort_out = get_onnxruntime_output(model, inputs)\n    if use_vm:\n        tvm_out = get_tvm_output_with_vm(\n            model,\n            inputs,\n            target,\n            dev,\n            opset=opset,\n            freeze_params=freeze_params,\n            convert_config=convert_config,\n        )\n    else:\n        tvm_out = get_tvm_output(\n            model,\n            inputs,\n            target,\n            dev,\n            out_shape,\n            dtype,\n            opset=opset,\n            opt_level=opt_level,\n            convert_config=convert_config,\n        )\n\n    if not isinstance(tvm_out, list):\n        tvm_out = [tvm_out]\n    if not isinstance(ort_out, list):\n        ort_out = [ort_out]\n    for tvm_val, ort_val in zip(tvm_out, ort_out):\n        if apply_softmax:\n            ort_val = scipy.special.softmax(ort_val)\n            tvm_val = scipy.special.softmax(tvm_val)\n        tvm.testing.assert_allclose(ort_val, tvm_val, rtol=rtol, atol=atol)\n        assert ort_val.dtype == tvm_val.dtype\n\n\ndef verify_with_ort(\n    model,\n    input_shapes,\n    out_shape=None,\n    target=None,\n    dev=None,\n    use_vm=False,\n    opset=None,\n    freeze_params=False,\n    dtype=\"float32\",\n    rtol=1e-5,\n    atol=1e-5,\n):\n    \"\"\"verify_with_ort\"\"\"\n    inputs = [np.random.uniform(size=ishape).astype(dtype) for ishape in input_shapes]\n    verify_with_ort_with_inputs(\n        model,\n        inputs,\n        out_shape=out_shape,\n        target=target,\n        dev=dev,\n        use_vm=use_vm,\n        opset=opset,\n        freeze_params=freeze_params,\n        dtype=dtype,\n        rtol=rtol,\n        atol=atol,\n    )\n\n\ndef quantize_and_verify_with_ort(\n    onnx_model, input_names, input_shapes, target, dev, rtol=1e-5, atol=1e-5\n):\n    \"\"\"quantize_and_verify_with_ort\"\"\"\n    input_arrays = [np.random.random(shape).astype(\"float32\") for shape in input_shapes]\n\n    class RandomDataReader(CalibrationDataReader):\n        # pylint: disable=missing-class-docstring\n        def __init__(self, n=10):\n            input_dict = dict(zip(input_names, input_shapes))\n            self.data = iter(\n                [\n                    {\n                        name: np.random.random(shape).astype(\"float32\")\n                        for name, shape in input_dict.items()\n                    }\n                    for _ in range(n)\n                ]\n            )\n\n        def get_next(self):\n            return next(self.data, None)\n\n    t_dir = tvm.contrib.utils.tempdir()\n    model_fp32 = os.path.join(t_dir.temp_dir, \"model.onnx\")\n    onnx.save_model(onnx_model, model_fp32)\n    model_quant = os.path.join(t_dir.temp_dir, \"model.quant.onnx\")\n    _ = quantize_static(  # pylint: disable=assignment-from-no-return\n        model_fp32, model_quant, RandomDataReader()\n    )\n    # opt_level=1 will cause error with qnn lowering\n    model = onnx.load(model_quant)\n    verify_with_ort_with_inputs(\n        model, input_arrays, opt_level=2, target=target, dev=dev, use_vm=True, rtol=rtol, atol=atol\n    )\n\n\ndef make_constant_node(name, data_type, dims, vals):\n    return helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[name],\n        value=helper.make_tensor(name=name, data_type=data_type, dims=dims, vals=vals),\n    )\n\n\ndef is_version_greater_than(ver):\n    return \"\".join(re.findall(r\"(\\d+\\.)(\\d+\\.)(\\d)\", onnx.__version__)[0]) > \"\".join(\n        re.findall(r\"(\\d+\\.)(\\d+\\.)(\\d)\", ver)[0]\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_reshape(target, dev):\n    \"\"\"test_reshape\"\"\"\n    in_shape = (4, 3, 3, 4)\n    ref_shape = (6, 2, 4, 3)\n\n    ref_array = np.array(ref_shape)\n    ref_node = onnx.helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[\"ref_in\"],\n        value=onnx.helper.make_tensor(\n            name=\"const_tensor\",\n            data_type=onnx.TensorProto.INT32,\n            dims=ref_array.shape,\n            vals=ref_array.flatten().astype(int),\n        ),\n    )\n    reshape_node = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out\"])\n\n    graph = helper.make_graph(\n        [ref_node, reshape_node],\n        \"reshape_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"reshape_test\")\n\n    x = np.random.uniform(size=in_shape).astype(\"int32\")\n    tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"float32\")\n    tvm.testing.assert_allclose(ref_shape, tvm_out.shape)\n\n\n@tvm.testing.parametrize_targets\ndef test_double_reshape(target, dev):\n    \"\"\"test_double_reshape\"\"\"\n    in_shape = (4, 3, 3, 4)\n    ref_shape = (6, 2, 4, 3)\n\n    ref_array = np.array(ref_shape)\n    ref_node = onnx.helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[\"ref_in\"],\n        value=onnx.helper.make_tensor(\n            name=\"const_tensor\",\n            data_type=onnx.TensorProto.INT32,\n            dims=ref_array.shape,\n            vals=ref_array.flatten().astype(int),\n        ),\n    )\n    reshape_node1 = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out1\"])\n    reshape_node2 = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out2\"])\n    add_node = helper.make_node(\"Add\", [\"out1\", \"out2\"], [\"out\"])\n\n    graph = helper.make_graph(\n        [ref_node, reshape_node1, reshape_node2, add_node],\n        \"reshape_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"reshape_test\")\n\n    x = np.random.uniform(size=in_shape).astype(\"int32\")\n    tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"float32\")\n    tvm.testing.assert_allclose(ref_shape, tvm_out.shape)\n\n\n@tvm.testing.parametrize_targets\ndef test_expand(target, dev):\n    \"\"\"test_expand\"\"\"\n\n    def _test_expand(name, data, shape, ref_data, dtype=\"int32\"):\n        shape_array = np.array(shape)\n        if dtype == \"int32\":\n            shape_node = onnx.helper.make_node(\n                \"Constant\",\n                inputs=[],\n                outputs=[\"shape\"],\n                value=onnx.helper.make_tensor(\n                    name=\"const_tensor\",\n                    data_type=onnx.TensorProto.INT32,\n                    dims=shape_array.shape,\n                    vals=shape_array.flatten().astype(\"int32\"),\n                ),\n            )\n        elif dtype == \"int64\":\n            shape_node = onnx.helper.make_node(\n                \"Constant\",\n                inputs=[],\n                outputs=[\"shape\"],\n                value=onnx.helper.make_tensor(\n                    name=\"const_tensor\",\n                    data_type=onnx.TensorProto.INT64,\n                    dims=shape_array.shape,\n                    vals=shape_array.flatten().astype(\"int64\"),\n                ),\n            )\n        else:\n            raise TypeError(\"Invalid dtype\")\n        expand_node = helper.make_node(\"Expand\", [\"in\", \"shape\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [shape_node, expand_node],\n            \"expand_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(data.shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_data.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=name)\n\n        tvm_out = get_tvm_output_with_vm(model, data, target, dev, freeze_params=True)\n        tvm.testing.assert_allclose(ref_data, tvm_out)\n\n    in_shape = (3, 1)\n    shape = (3, 4)\n    data = np.random.uniform(size=in_shape).astype(np.float32)\n    ref_data = np.tile(data, 4)\n    _test_expand(\"expand_with_dim_unchanged_test\", data, shape, ref_data, \"int32\")\n    _test_expand(\"expand_with_dim_unchanged_test\", data, shape, ref_data, \"int64\")\n\n    in_shape = (3, 1)\n    shape = (2, 1, 6)\n    data = np.random.uniform(size=in_shape).astype(np.float32)\n    ref_data = data * np.ones(shape, dtype=np.float32)\n    _test_expand(\"expand_larger_target_shape_test\", data, shape, ref_data, \"int32\")\n    _test_expand(\"expand_larger_target_shape_test\", data, shape, ref_data, \"int64\")\n\n    in_shape = (1, 1)\n    shape = (3,)\n    data = np.random.uniform(size=in_shape).astype(np.float32)\n    ref_data = data * np.ones(shape, dtype=np.float32)\n    _test_expand(\"expand_smaller_target_shape_test\", data, shape, ref_data, \"int32\")\n    _test_expand(\"expand_smaller_target_shape_test\", data, shape, ref_data, \"int64\")\n\n\n@tvm.testing.parametrize_targets\ndef test_depth_to_space(target, dev):\n    \"\"\"test_depth_to_space\"\"\"\n\n    def verify_depth_to_space(inshape, outshape, mode, block_size):\n        node = onnx.helper.make_node(\n            \"DepthToSpace\", inputs=[\"x\"], outputs=[\"y\"], blocksize=block_size\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"depth_to_space_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"depth_to_space_test\")\n\n        verify_with_ort(model, [inshape], [outshape], target, dev)\n\n    # current onnx.checker use OpSet-1 version of DepthToSpace, which doesn't have a mode argument.\n    # TO-DO, we can add mode argument to test CRD mode and DCR mode\n    # in the future when we update to a newer onnx version.\n    verify_depth_to_space((1, 8, 2, 3), (1, 2, 4, 6), mode=\"CRD\", block_size=2)\n\n\n@tvm.testing.parametrize_targets\ndef test_space_to_depth(target, dev):\n    \"\"\"test_space_to_depth\"\"\"\n\n    def verify_space_to_depth(inshape, outshape, block_size):\n        node = onnx.helper.make_node(\n            \"SpaceToDepth\", inputs=[\"x\"], outputs=[\"y\"], blocksize=block_size\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"space_to_depth_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"space_to_depth_test\")\n\n        verify_with_ort(model, [inshape], [outshape], target, dev)\n\n    verify_space_to_depth((1, 1, 4, 6), (1, 4, 2, 3), 2)\n\n\n@tvm.testing.parametrize_targets\ndef test_shape(target, dev):\n    \"\"\"test_shape\"\"\"\n    in_shape = (4, 3, 3, 4)\n    ref_shape = (6, 2, 4, 3)\n\n    ref_array = np.array(ref_shape)\n    ref_node = onnx.helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[\"ref_in\"],\n        value=onnx.helper.make_tensor(\n            name=\"const_tensor\",\n            data_type=onnx.TensorProto.INT32,\n            dims=ref_array.shape,\n            vals=ref_array.flatten().astype(int),\n        ),\n    )\n    reshape_node = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out\"])\n\n    shape_node = helper.make_node(\"Shape\", [\"out\"], [\"final_out\"])\n\n    graph = helper.make_graph(\n        [ref_node, reshape_node, shape_node],\n        \"shape_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"final_out\", TensorProto.FLOAT, list(ref_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"shape_test\")\n\n    x = np.random.uniform(size=in_shape).astype(\"int32\")\n    tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"int32\")\n    tvm.testing.assert_allclose(ref_shape, tvm_out)\n\n\n@tvm.testing.parametrize_targets\ndef test_power(target, dev):\n    \"\"\"test_power\"\"\"\n\n    def _test_power_iteration(x_shape, y_shape):\n        if isinstance(y_shape, int):\n            y_shape = [y_shape]\n\n        x = np.random.uniform(size=x_shape).astype(np.float32)\n        y = np.random.uniform(size=y_shape).astype(np.float32)\n\n        np_res = np.power(x, y).astype(np.float32)\n\n        res = helper.make_node(\"Pow\", [\"x\", \"y\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [res],\n            \"power_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(np_res.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"power_test\")\n\n        tvm_out = get_tvm_output(model, [x, y], target, dev, np_res.shape)\n        tvm.testing.assert_allclose(np_res, tvm_out, rtol=1e-5, atol=1e-5)\n\n    _test_power_iteration((1, 3), (1))\n    _test_power_iteration((2, 3), (2, 3))\n    _test_power_iteration((2, 3), (1, 3))\n\n\n@tvm.testing.parametrize_targets\ndef test_range(target, dev):\n    \"\"\"test_range\"\"\"\n\n    def verify_range(start, limit, delta, dtype):\n        dtype_map = {\n            \"float32\": TensorProto.FLOAT,\n            \"int32\": TensorProto.INT32,\n            \"int64\": TensorProto.INT64,\n        }\n        dtype_onnx = dtype_map[dtype]\n        y = helper.make_node(\"Range\", [\"start\", \"limit\", \"delta\"], [\"output\"])\n        graph = helper.make_graph(\n            [y],\n            \"range_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"start\", dtype_onnx, []),\n                helper.make_tensor_value_info(\"limit\", dtype_onnx, []),\n                helper.make_tensor_value_info(\"delta\", dtype_onnx, []),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"output\", dtype_onnx, np.arange(start, limit, delta).shape\n                )\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"range_test\")\n        inputs = [np.array(x).astype(dtype) for x in [start, limit, delta]]\n        verify_with_ort_with_inputs(model, inputs, target=target, dev=dev, use_vm=True)\n\n    for t in [\"float32\", \"int32\", \"int64\"]:\n        verify_range(0, 10, 1, t)\n        verify_range(2, 8, 2, t)\n        verify_range(-3, 6, 4, t)\n        verify_range(-2, -7, -1, t)\n\n\n@tvm.testing.parametrize_targets\ndef test_squeeze(target, dev):\n    \"\"\"test_squeeze\"\"\"\n\n    def test_squeeze_once(in_shape, out_shape, axes=None):\n        y = helper.make_node(\"Squeeze\", [\"in\"], [\"out\"], axes=axes)\n\n        graph = helper.make_graph(\n            [y],\n            \"squeeze_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"squeeze_test\")\n        x = np.random.uniform(size=in_shape).astype(\"float32\")\n        verify_with_ort_with_inputs(model, [x], [out_shape], target=target, dev=dev, opset=11)\n\n    test_squeeze_once((1, 3, 1, 3, 1, 1), (3, 3), [0, 2, 4, 5])\n    test_squeeze_once((1, 3, 1, 3, 1, 1), (3, 3))  # empty axis.\n    test_squeeze_once((), ())  # scalar testing.\n\n\n@tvm.testing.parametrize_targets\ndef test_flatten(target, dev):\n    \"\"\"test_flatten\"\"\"\n\n    def verify_flatten(in_shape, axis, ref_shape):\n        flatten_node = helper.make_node(\"Flatten\", [\"in\"], [\"out\"], axis=axis)\n\n        graph = helper.make_graph(\n            [flatten_node],\n            \"flatten_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"flatten_test\")\n        verify_with_ort(model, [in_shape], target=target, dev=dev)\n\n    verify_flatten((1, 3, 4, 4), 1, (1, 48))\n    verify_flatten((1,), 1, (1, 1))\n\n\n@tvm.testing.parametrize_targets\ndef test_unsqueeze(target, dev):\n    \"\"\"test_unsqueeze\"\"\"\n    in_shape = (3, 3)\n    axis = (0, 3, 4)\n    out_shape = (1, 3, 3, 1, 1)\n    y = helper.make_node(\"Unsqueeze\", [\"in\"], [\"out\"], axes=list(axis))\n\n    graph = helper.make_graph(\n        [y],\n        \"squeeze_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"squeeze_test\")\n    verify_with_ort(model, [in_shape], target=target, dev=dev, opset=11)\n\n\n@tvm.testing.parametrize_targets\ndef test_gather(target, dev):\n    \"\"\"test_gather\"\"\"\n\n    def verify_gather(in_shape, indices, axis, dtype):\n        x = np.random.uniform(size=in_shape).astype(dtype)\n        indices = np.array(indices, dtype=\"int64\")\n        out_np = np.take(x, indices, axis=axis)\n\n        y = helper.make_node(\"Gather\", [\"in\", \"indices\"], [\"out\"], axis=axis)\n\n        graph = helper.make_graph(\n            [y],\n            \"gather_test\",\n            inputs=[\n                helper.make_tensor_value_info(\n                    \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(in_shape)\n                ),\n                helper.make_tensor_value_info(\"indices\", TensorProto.INT64, list(indices.shape)),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(out_np.shape)\n                )\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"gather_test\")\n        verify_with_ort_with_inputs(model, [x, indices], target=target, dev=dev, dtype=dtype)\n\n    verify_gather((4,), [1], 0, \"int32\")\n    verify_gather((1, 4), [0], 0, \"int32\")\n    verify_gather((4,), [[[1, 0], [0, 1]]], 0, \"float32\")\n    verify_gather((2, 2), [[[1, 0], [0, 1]]], 1, \"int32\")\n    verify_gather((3, 3, 3), [[[1, 0]]], -1, \"int32\")\n    verify_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, \"float32\")\n\n\n@tvm.testing.parametrize_targets\ndef test_dynamic_gather(target, dev):\n    \"\"\"test_dynamic_gather\"\"\"\n    dtype = \"float32\"\n    in_shape = [2, 2]\n    indices = 1\n    axis = 1\n    x = np.random.uniform(size=in_shape).astype(dtype)\n    indices = np.array(indices, dtype=\"int64\")\n    out_np = np.take(x, indices, axis=axis)\n\n    indices = helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[\"indices\"],\n        value=onnx.helper.make_tensor(\n            name=\"const_indices\",\n            data_type=onnx.TensorProto.INT64,\n            dims=[],\n            vals=[1],\n        ),\n    )\n    y = helper.make_node(\"Gather\", [\"in\", \"indices\"], [\"out\"], axis=axis)\n\n    graph = helper.make_graph(\n        [indices, y],\n        \"gather_test\",\n        inputs=[\n            helper.make_tensor_value_info(\n                \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], [\"?\", \"?\"]\n            ),\n        ],\n        outputs=[\n            helper.make_tensor_value_info(\n                \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], [\"?\"] * len(out_np.shape)\n            )\n        ],\n    )\n    model = helper.make_model(graph, producer_name=\"dynamic_gather_test\")\n\n    mod, params = relay.frontend.from_onnx(model)\n\n    result = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(x, **params)\n    tvm.testing.assert_allclose(out_np, result.numpy(), rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.parametrize_targets\ndef test_gatherelements(target, dev):\n    \"\"\"test_gatherelements\"\"\"\n\n    def verify_gatherelements(in_shape, indices, axis):\n        x = np.random.uniform(size=in_shape).astype(\"float32\")\n        indices = np.array(indices, dtype=\"int32\")\n\n        y = helper.make_node(\"GatherElements\", [\"data\", \"indices\"], [\"output\"], axis=axis)\n        graph = helper.make_graph(\n            [y],\n            \"gather_elements_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(in_shape)),\n                helper.make_tensor_value_info(\"indices\", TensorProto.INT32, list(indices.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(in_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"gather_elements_test\")\n\n        verify_with_ort_with_inputs(model, [x, indices], target=target, dev=dev)\n\n    verify_gatherelements((4,), [3, 0, 2, 1], 0)\n    verify_gatherelements((2, 2), [[1, 0], [0, 1]], 0)\n    verify_gatherelements((2, 2), [[0, 0], [1, 0]], 1)\n    verify_gatherelements((2, 2), [[1, 0], [0, 1]], 1)\n\n    indices = [\n        [[1, 0, 0], [1, 0, 1], [0, 1, 1]],\n        [[1, 1, 1], [1, 2, 1], [1, 0, 1]],\n        [[1, 2, 1], [1, 2, 1], [1, 2, 1]],\n    ]\n\n    verify_gatherelements((3, 3, 3), indices, 2)\n\n\n@tvm.testing.parametrize_targets\ndef test_scatter(target, dev):\n    \"\"\"test_scatter\"\"\"\n\n    def verify_scatter(in_shape, indices, axis):\n        x = np.random.uniform(size=in_shape).astype(\"float32\")\n        indices = np.array(indices, dtype=\"int32\")\n        updates = np.random.uniform(size=indices.shape).astype(\"float32\")\n\n        y = helper.make_node(\n            \"ScatterElements\", [\"data\", \"indices\", \"updates\"], [\"output\"], axis=axis\n        )\n\n        graph = helper.make_graph(\n            [y],\n            \"scatter_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(in_shape)),\n                helper.make_tensor_value_info(\"indices\", TensorProto.INT32, list(indices.shape)),\n                helper.make_tensor_value_info(\"updates\", TensorProto.FLOAT, list(indices.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(in_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"scatter_test\")\n        verify_with_ort_with_inputs(model, [x, indices, updates], target=target, dev=dev)\n\n    verify_scatter((4,), [1], 0)\n    verify_scatter((1, 4), [[0]], 0)\n    verify_scatter((4,), [2, 3], 0)\n    verify_scatter((2, 2), [[1, 0], [0, 1]], 1)\n    verify_scatter((3, 3, 3), [[[-1, -3]]], -1)\n    verify_scatter((4, 3, 5, 6), [[[[2, 1, 0, 0]]]], 0)\n\n\n@tvm.testing.parametrize_targets\ndef test_slice(target, dev):\n    \"\"\"test_slice\"\"\"\n\n    def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None):\n        if axes:\n            y = helper.make_node(\"Slice\", [\"in\"], [\"out\"], axes=axes, starts=starts, ends=ends)\n        else:\n            y = helper.make_node(\"Slice\", [\"in\"], [\"out\"], starts=starts, ends=ends)\n\n        graph = helper.make_graph(\n            [y],\n            \"slice_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"slice_test\")\n        verify_with_ort_with_inputs(\n            model, [indata], [outdata.shape], opset=1, target=target, dev=dev\n        )\n\n    def _test_slice_iteration_v10(indata, outdata, **attrs):\n        starts = attrs[\"starts\"]\n        ends = attrs[\"ends\"]\n        axes = None if \"axes\" not in attrs else attrs[\"axes\"]\n        steps = None if \"steps\" not in attrs else attrs[\"steps\"]\n        starts = np.asarray(starts)\n        ends = np.asarray(ends)\n        inputs = [\n            helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(indata.shape)),\n            helper.make_tensor_value_info(\"starts\", TensorProto.INT64, list(starts.shape)),\n            helper.make_tensor_value_info(\"ends\", TensorProto.INT64, list(ends.shape)),\n        ]\n        initializer = [\n            helper.make_tensor(\"starts\", TensorProto.INT64, list(starts.shape), starts),\n            helper.make_tensor(\"ends\", TensorProto.INT64, list(ends.shape), ends),\n        ]\n        nodes = []\n\n        if \"add_noop_to_input_attrs\" in attrs:\n\n            def add_noop_to_input_attr(attr_name, attr):\n                output_name = attr_name + \"_output\"\n\n                ref_shape = list(np.array(attr).shape)\n                ref_shape.insert(0, 1)\n                ref_shape = tuple(ref_shape)\n                ref_array = np.array(ref_shape)\n                ref_node = onnx.helper.make_node(\n                    \"Constant\",\n                    inputs=[],\n                    outputs=[\"ref_in_\" + attr_name],\n                    value=onnx.helper.make_tensor(\n                        name=\"const_tensor__1_\" + attr_name,\n                        data_type=onnx.TensorProto.INT64,\n                        dims=ref_array.shape,\n                        vals=ref_array.flatten().astype(int),\n                    ),\n                )\n                in_shape = np.array(attr).shape\n                in_array = np.array(in_shape)\n                ref_node2 = onnx.helper.make_node(\n                    \"Constant\",\n                    inputs=[],\n                    outputs=[\"input_shape_\" + attr_name],\n                    value=onnx.helper.make_tensor(\n                        name=\"const_tensor__2_\" + attr_name,\n                        data_type=onnx.TensorProto.INT64,\n                        dims=in_array.shape,\n                        vals=in_array.flatten().astype(int),\n                    ),\n                )\n\n                reshape1_node = helper.make_node(\n                    \"Reshape\", [attr_name, \"ref_in_\" + attr_name], [\"reshape_\" + attr_name]\n                )\n                reshape2_node = helper.make_node(\n                    \"Reshape\", [\"reshape_\" + attr_name, \"input_shape_\" + attr_name], [output_name]\n                )\n                return [ref_node, ref_node2, reshape1_node, reshape2_node]\n\n        slice_inputs = []\n        for attr_name in [\"starts\", \"ends\", \"axes\", \"steps\"]:\n            if attr_name not in attrs:\n                continue\n            if \"add_noop_to_input_attrs\" in attrs and attr_name in attrs[\"add_noop_to_input_attrs\"]:\n                nodes.extend(add_noop_to_input_attr(attr_name, attrs[attr_name]))\n                slice_inputs.append(attr_name + \"_output\")\n            else:\n                slice_inputs.append(attr_name)\n\n        if axes:\n            axes = np.asarray(axes)\n            inputs.append(\n                helper.make_tensor_value_info(\"axes\", TensorProto.INT64, list(axes.shape))\n            )\n            initializer.append(\n                helper.make_tensor(\"axes\", TensorProto.INT64, list(axes.shape), axes)\n            )\n\n        if steps:\n            assert axes is not None and len(axes) == len(steps)\n            steps = np.asarray(steps)\n            inputs.append(\n                helper.make_tensor_value_info(\"steps\", TensorProto.INT64, list(axes.shape))\n            )\n            initializer.append(\n                helper.make_tensor(\"steps\", TensorProto.INT64, list(steps.shape), steps)\n            )\n\n        y = helper.make_node(\"Slice\", [\"data\", *slice_inputs], [\"out\"])\n\n        nodes.append(y)\n        graph = helper.make_graph(\n            nodes,\n            \"slice_test\",\n            inputs=inputs,\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n            initializer=initializer,\n        )\n        model = helper.make_model(graph, producer_name=\"slice_test\")\n        verify_with_ort_with_inputs(\n            model, [indata], opset=10, freeze_params=True, use_vm=True, target=target, dev=dev\n        )\n\n    x = np.random.randn(20, 10, 5).astype(np.float32)\n    _test_slice_iteration_v1(x, x[0:3, 0:10], starts=(0, 0), ends=(3, 10), axes=(0, 1))\n    _test_slice_iteration_v1(x, x[0:3, 0:10], starts=(0, 0), ends=(10, 3), axes=(1, 0))\n    _test_slice_iteration_v1(x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4))\n    _test_slice_iteration_v1(x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,))\n    _test_slice_iteration_v1(x, x[:, 0:-1], starts=(0,), ends=(-1,), axes=(1,))\n    _test_slice_iteration_v10(x, x[0:3, 0:10], starts=(0, 0), ends=(3, 10), axes=(0, 1))\n    _test_slice_iteration_v10(x, x[0:3, 0:10], starts=(0, 0), ends=(10, 3), axes=(1, 0))\n    _test_slice_iteration_v10(x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4))\n    _test_slice_iteration_v10(x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,))\n    _test_slice_iteration_v10(x, x[:, 0:-1], starts=(0,), ends=(-1,), axes=(1,))\n    _test_slice_iteration_v10(x, x[:, 0:-1], starts=(0,), ends=(-1,), axes=(-1,))\n    _test_slice_iteration_v10(\n        x,\n        x[0:3, 0:10],\n        starts=(0, 0),\n        ends=(3, 10),\n        axes=(0, 1),\n        add_noop_to_input_attrs=[\"starts\"],\n    )\n    _test_slice_iteration_v10(\n        x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4), add_noop_to_input_attrs=[\"ends\"]\n    )\n    _test_slice_iteration_v10(\n        x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,), add_noop_to_input_attrs=[\"axes\"]\n    )\n    _test_slice_iteration_v10(\n        x,\n        x[:, 0:-1],\n        starts=(0,),\n        ends=(-1,),\n        axes=(1,),\n        add_noop_to_input_attrs=[\"starts\", \"ends\"],\n    )\n    _test_slice_iteration_v10(\n        x,\n        x[0:3, 0:10],\n        starts=(0, 0),\n        ends=(3, 10),\n        axes=(0, 1),\n        add_noop_to_input_attrs=[\"ends\", \"axes\"],\n    )\n    _test_slice_iteration_v10(\n        x,\n        x[:, :, 3:4],\n        starts=(0, 0, 3),\n        ends=(20, 10, 4),\n        add_noop_to_input_attrs=[\"starts\", \"axes\"],\n    )\n    _test_slice_iteration_v10(\n        x,\n        x[:, 1:1000],\n        starts=(1,),\n        ends=(1000,),\n        axes=(1,),\n        add_noop_to_input_attrs=[\"starts\", \"ends\", \"axes\"],\n    )\n    x = np.random.randn(1, 1, 1, 128).astype(np.float32)\n    _test_slice_iteration_v10(\n        x, x, starts=(0, 0), ends=(9223372036854775807, 9223372036854775807), axes=(0, 3)\n    )\n\n    x = np.random.randn(4, 4).astype(np.float32)\n    _test_slice_iteration_v10(\n        x, x[:, 1::2], starts=(1,), ends=(9223372036854775807,), axes=(1,), steps=(2,)\n    )\n    _test_slice_iteration_v10(\n        x,\n        x[0::1, 1::2],\n        starts=(0, 1),\n        ends=(4, 4),\n        axes=(0, 1),\n        steps=(1, 2),\n    )\n\n\ndef _test_onnx_op_elementwise(\n    target, dev, inshape, outfunc, npargs, dtype, opname, kwargs, opset=None, verify=True\n):\n    indata = np.random.uniform(-1, 1, size=inshape).astype(dtype)\n    outdata = outfunc(indata, **npargs)\n\n    y = helper.make_node(opname, [\"in\"], [\"out\"], **kwargs)\n\n    ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n\n    graph = helper.make_graph(\n        [y],\n        opname + \"_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", ONNX_DTYPE, list(indata.shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, list(outdata.shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=opname + \"_test\")\n    if verify:\n        verify_with_ort_with_inputs(\n            model, [indata], [outdata.shape], opset=opset, dtype=dtype, target=target, dev=dev\n        )\n    else:\n        get_tvm_output(\n            model,\n            [indata],\n            target,\n            dev,\n            [outdata.shape],\n            dtype,\n            opset=opset,\n            opt_level=3,\n        )\n\n\n@tvm.testing.parametrize_targets\ndef test_floor(target, dev):\n    _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.floor, {}, \"float32\", \"Floor\", {})\n\n\n@tvm.testing.parametrize_targets\ndef test_ceil(target, dev):\n    _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.ceil, {}, \"float32\", \"Ceil\", {})\n\n\n@tvm.testing.parametrize_targets\ndef test_clip(target, dev):\n    \"\"\"test_clip\"\"\"\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        np.clip,\n        {\"a_min\": -1.0, \"a_max\": 1.0},\n        \"float32\",\n        \"Clip\",\n        {\"min\": -1.0, \"max\": 1.0},\n        opset=6,\n    )\n\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        np.clip,\n        {\"a_min\": -np.inf, \"a_max\": 1.0},\n        \"float32\",\n        \"Clip\",\n        {\"max\": 1.0},\n        opset=6,\n    )\n\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        np.clip,\n        {\"a_min\": -1.0, \"a_max\": np.inf},\n        \"float32\",\n        \"Clip\",\n        {\"min\": -1.0},\n        opset=6,\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_clip_min_max_as_inputs(target, dev):\n    \"\"\"test_clip_min_max_as_inputs\"\"\"\n    input_shape = (2, 4, 5, 6)\n    nodes = [\n        make_constant_node(\"min\", onnx.TensorProto.FLOAT, (), [0.0]),\n        make_constant_node(\"max\", onnx.TensorProto.FLOAT, (), [6.0]),\n    ]\n    input_names = [\"in\", \"min\", \"max\"]\n    nodes.append(helper.make_node(\"Clip\", inputs=input_names, outputs=[\"out\"]))\n    graph = helper.make_graph(\n        nodes,\n        \"clip_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(input_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_shape))],\n    )\n    model = helper.make_model(graph, producer_name=\"clip_test\")\n\n    verify_with_ort(model, [input_shape], out_shape=[input_shape], target=target, dev=dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_round(target, dev):\n    _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.round, {}, \"float32\", \"Round\", {})\n    _test_onnx_op_elementwise(\n        target, dev, (2, 4, 5, 6), np.round, {}, \"float64\", \"Round\", {}, verify=False\n    )  # TODO: enable verification once ORT supports float64\n\n\ndef _test_finite_ops(target, dev, inshape, outfunc, npargs, dtype, opname, kwargs):\n    indata = np.random.choice(a=[np.nan, np.inf, -np.inf, 0.5, 1.0, 0], size=inshape).astype(dtype)\n\n    outdata = outfunc(indata, **npargs)\n    y = helper.make_node(opname, [\"in\"], [\"out\"], **kwargs)\n\n    graph = helper.make_graph(\n        [y],\n        opname + \"_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=opname + \"_test\")\n    verify_with_ort_with_inputs(\n        model, [indata], [outdata.shape], dtype=dtype, target=target, dev=dev\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_isinf(target, dev):\n    _test_finite_ops(target, dev, (2, 4, 5, 6), np.isinf, {}, \"float32\", \"IsInf\", {})\n\n\n@tvm.testing.parametrize_targets\ndef test_isnan(target, dev):\n    \"\"\"test_isnan\"\"\"\n    _test_finite_ops(target, dev, (2, 4, 5, 6), np.isnan, {}, \"float32\", \"IsNaN\", {})\n\n\n@tvm.testing.parametrize_targets\ndef test_gather_nd(target, dev):\n    \"\"\"test_gather_nd\"\"\"\n\n    def verify_gather_nd(in_shape, indices, out_shape, dtype=\"float32\", batch_dims=0, opset=11):\n        x = np.random.uniform(size=in_shape).astype(dtype)\n        indices = np.array(indices, dtype=\"int64\")\n\n        y = helper.make_node(\"GatherND\", [\"in\", \"indices\"], [\"out\"])\n\n        if opset >= 12:\n            batch_dims_attr = helper.make_attribute(\"batch_dims\", batch_dims)\n            y.attribute.append(batch_dims_attr)\n\n        graph = helper.make_graph(\n            [y],\n            \"gather_test\",\n            inputs=[\n                helper.make_tensor_value_info(\n                    \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(in_shape)\n                ),\n                helper.make_tensor_value_info(\"indices\", TensorProto.INT64, list(indices.shape)),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(out_shape)\n                )\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"gather_test\")\n        verify_with_ort_with_inputs(\n            model, [x, indices], [out_shape], opset=opset, target=target, dev=dev\n        )\n\n    verify_gather_nd([2, 2], [[0, 0], [1, 1]], [2], \"int32\")\n    verify_gather_nd([2, 2], [[1], [0]], [2, 2])\n    verify_gather_nd([2, 2, 2], [[0, 1], [1, 0]], [2, 2])\n    verify_gather_nd([2, 2, 2], [[[0, 1]], [[1, 0]]], [2, 1, 2])\n\n    if is_version_greater_than(\"1.6.0\"):\n        verify_gather_nd([2, 2, 2], [[1], [0]], [2, 2], batch_dims=1, opset=12)\n        verify_gather_nd(\n            (3, 2, 2, 3, 4),\n            np.random.randint(low=0, high=2, size=(3, 2, 3), dtype=\"int64\"),\n            (3, 2),\n            batch_dims=2,\n            opset=12,\n        )\n\n\n@tvm.testing.parametrize_targets\ndef test_onehot(target, dev):\n    \"\"\"test_onehot\"\"\"\n    indices_shape = [10]\n    indices_array = np.random.randint(low=0, high=9, size=indices_shape, dtype=\"int32\")\n    depth = 10\n    values = np.asarray([0, 1]).astype(\"int32\")\n    out_np = np.eye(depth)[indices_array.reshape(-1)]\n\n    onehot_node = helper.make_node(\"OneHot\", [\"indices\", \"depth\", \"values\"], [\"out\"])\n\n    graph = helper.make_graph(\n        [onehot_node],\n        \"onehot_test\",\n        inputs=[\n            helper.make_tensor_value_info(\"indices\", TensorProto.INT32, indices_shape),\n            helper.make_tensor_value_info(\"depth\", TensorProto.INT32, [1]),\n            helper.make_tensor_value_info(\"values\", TensorProto.INT32, values.shape),\n        ],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.INT32, out_np.shape)],\n    )\n\n    model = helper.make_model(graph, producer_name=\"onehot_test\")\n\n    # TODO(jwfromm): Replace test against np with test against onnxrt once we update versions.\n    tvm_out = get_tvm_output_with_vm(\n        model, [indices_array, np.array([depth]).astype(\"int32\"), values], target, dev\n    )\n    tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.parametrize_targets\ndef test_gemm(target, dev):\n    \"\"\"test_gemm\"\"\"\n\n    def verify_gemm(a_shape, b_shape, c_shape=None, freeze_params=False, dtype=\"float32\"):\n        out_shape = [a_shape[0], b_shape[1]]\n        a_array = np.random.uniform(size=a_shape).astype(dtype)\n        b_array = np.random.uniform(size=b_shape).astype(dtype)\n        input_names = [\"a\", \"b\"]\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        input_nodes = [\n            helper.make_tensor_value_info(\"a\", ONNX_DTYPE, list(a_shape)),\n            helper.make_tensor_value_info(\"b\", ONNX_DTYPE, list(b_shape)),\n        ]\n        input_values = [a_array, b_array]\n        if c_shape is not None:\n            c_array = np.random.uniform(size=c_shape).astype(dtype)\n            input_names.append(\"c\")\n            input_nodes.append(helper.make_tensor_value_info(\"c\", ONNX_DTYPE, list(c_shape)))\n            input_values.append(c_array)\n\n        gemm_node = helper.make_node(\"Gemm\", input_names, [\"out\"])\n\n        graph = helper.make_graph(\n            [gemm_node],\n            \"gemm_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"gemm_test\")\n        atol = 1e-5\n        rtol = 1e-5\n        if dtype == \"float16\":\n            atol = 1e-3\n            rtol = 1e-3\n        verify_with_ort_with_inputs(\n            model,\n            input_values,\n            freeze_params=freeze_params,\n            dtype=dtype,\n            atol=atol,\n            rtol=rtol,\n            target=target,\n            dev=dev,\n        )\n\n    verify_gemm(a_shape=(4, 3), b_shape=(3, 4))\n    verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,))\n    verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,), freeze_params=True)\n    verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,), freeze_params=True, dtype=\"float16\")\n\n\n@tvm.testing.parametrize_targets\ndef test_matmul(target, dev):\n    \"\"\"test_matmul\"\"\"\n\n    def test_one_matmul(a_shape, b_shape):\n        if len(a_shape) == 1:\n            out_shape = [b_shape[1]]\n        else:\n            out_shape = [a_shape[0], b_shape[1]]\n\n        a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n        b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n\n        mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [mul_node],\n            \"matmul_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n                helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"matmul_test\")\n        verify_with_ort_with_inputs(model, [a_array, b_array], target=target, dev=dev)\n\n    test_one_matmul((4, 3), (3, 4))\n    test_one_matmul((3,), (3, 1))\n\n\n@tvm.testing.parametrize_targets\ndef test_batch_matmul(target, dev):\n    \"\"\"test_batch_matmul\"\"\"\n\n    def verify_batch_matmul(a_shape, b_shape, out_shape, convert_config=None):\n        a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n        b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n\n        mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [mul_node],\n            \"matmul_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n                helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, out_shape)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"matmul_test\")\n        verify_with_ort_with_inputs(\n            model,\n            [a_array, b_array],\n            use_vm=True,\n            target=target,\n            dev=dev,\n            convert_config=convert_config,\n        )\n\n    verify_batch_matmul((2, 3, 4, 3), (2, 3, 3, 4), (2, 3, 4, 4))\n    verify_batch_matmul((2, 4, 3), (3, 4), (2, 4, 4))\n    verify_batch_matmul((2, 3, 4, 3), (3, 4), (2, 3, 4, 4))\n    # Test implicit broadcasting.\n    verify_batch_matmul((4, 3), (2, 3, 4), (2, 4, 4))\n    verify_batch_matmul((2, 4, 3), (1, 3, 4), (2, 4, 4))\n    verify_batch_matmul((1, 4, 3), (2, 3, 4), (2, 4, 4))\n    verify_batch_matmul((4, 32, 16), (16, 32), (4, 32, 32))\n    verify_batch_matmul((4, 32, 16, 32), (32, 16), (4, 32, 16, 16))\n    verify_batch_matmul((4, 32, 16, 32), (1, 32, 32, 16), (4, 32, 16, 16))\n    verify_batch_matmul((4, 1, 16, 32), (1, 32, 32, 16), (4, 32, 16, 16))\n    # Test transb=False\n    verify_batch_matmul(\n        (2, 3, 4, 3),\n        (2, 3, 3, 4),\n        (2, 3, 4, 4),\n        convert_config={\"use_nt_batch_matmul\": False},\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_use_nt_batch_matmul(target, dev):\n    \"\"\"test_use_nt_batch_matmul\"\"\"\n    a_shape = (2, 3, 4)\n    b_shape = (2, 4, 3)\n    out_shape = [2, 3, 3]\n    a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n    b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n\n    for use_nt_batch_matmul in [True, False]:\n        mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [mul_node],\n            \"matmul_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n                helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"matmul_test\")\n        _, shape_dict = get_input_data_shape_dict(model, [a_array, b_array])\n\n        mod, _ = relay.frontend.from_onnx(\n            model, shape_dict, convert_config={\"use_nt_batch_matmul\": use_nt_batch_matmul}\n        )\n        has_transpose_op = \"transpose\" in str(mod)\n        # use_nt_batch_matmul implies, TVM converts qualified onnx `matmul`\n        # to `transpose(weight) + nn.batch_matmul_NT`, otherwise to `nn.batch_matmul`\n        assert has_transpose_op == use_nt_batch_matmul\n\n\n@tvm.testing.parametrize_targets\ndef test_matmulinteger16(target, dev):\n    \"\"\"test_matmulinteger16\"\"\"\n\n    def verify_matmulinteger16(a_shape, b_shape, out_shape):\n        a_dtype = \"int16\"\n        b_dtype = \"int16\"\n        low = np.iinfo(np.int16).min\n        high = np.iinfo(np.int16).max\n\n        a_proto = TensorProto.INT16\n        b_proto = TensorProto.INT16\n        out_proto = TensorProto.INT32\n        a_array = np.random.randint(low, high, size=a_shape).astype(a_dtype)\n        b_array = np.random.randint(low, high, size=b_shape).astype(b_dtype)\n\n        mul_node = helper.make_node(\"MatMulInteger16\", [\"a\", \"b\"], [\"out\"], domain=\"com.microsoft\")\n\n        graph = helper.make_graph(\n            [mul_node],\n            \"matmuli16_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a\", a_proto, list(a_shape)),\n                helper.make_tensor_value_info(\"b\", b_proto, list(b_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", out_proto, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"matmuli16_test\")\n        verify_with_ort_with_inputs(model, [a_array, b_array], target=target, dev=dev)\n\n    # 2D computation to verify matmul op\n    verify_matmulinteger16((4, 3), (3, 4), (4, 4))\n    verify_matmulinteger16((5, 7), (7, 8), (5, 8))\n    # Verify 3D matmul using batch_matmul op\n    verify_matmulinteger16((2, 4, 3), (1, 3, 4), (2, 4, 4))\n    verify_matmulinteger16((1, 4, 3), (2, 3, 4), (2, 4, 4))\n    # Test implicit broadcasting\n    verify_matmulinteger16((2, 3, 5, 3), (2, 3, 3, 5), (2, 3, 5, 5))\n    verify_matmulinteger16((2, 7, 3), (3, 7), (2, 7, 7))\n    verify_matmulinteger16((2, 3, 4, 3), (3, 4), (2, 3, 4, 4))\n\n\ndef verify_simple_dynamic_model(a_shape, b_shape, target, dev):\n    \"\"\"verify_simple_dynamic_model\"\"\"\n\n    def verify_model(model, a_shape, b_shape):\n        a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n        b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n        # matmul\n        out_np = np.matmul(a_array, b_array)\n        # relu\n        out_np[out_np < 0] = 0\n\n        tvm_out = model(a_array, b_array).numpy()\n        tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)\n\n    mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n    relu_node = helper.make_node(\"Relu\", [\"out\"], [\"relu\"])\n\n    a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n    b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n    # matmul\n    out_np = np.matmul(a_array, b_array)\n\n    graph = helper.make_graph(\n        [mul_node, relu_node],\n        \"matmul_test\",\n        inputs=[\n            helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n            helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n        ],\n        outputs=[helper.make_tensor_value_info(\"relu\", TensorProto.FLOAT, list(out_np.shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"matmul_test\")\n\n    a_anys = [relay.Any()] * len(a_shape)\n    b_anys = [relay.Any()] * len(b_shape)\n\n    mod, _ = relay.frontend.from_onnx(model, {\"a\": a_anys, \"b\": b_anys})\n    model = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()\n    verify_model(model, a_shape, b_shape)\n    verify_model(model, [a * 2 for a in a_shape], [b * 2 for b in b_shape])\n    verify_model(model, [a * 3 for a in a_shape], [b * 3 for b in b_shape])\n\n\n# TODO(mbrookhart, electriclilies): Add CUDA as a target once batch matmul is fixed\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_batch_matmul_dynamic_model(target, dev):\n    verify_simple_dynamic_model((2, 3, 4, 3), (2, 3, 3, 4), target, dev)\n    verify_simple_dynamic_model((2, 4, 3), (3, 4), target, dev)\n    verify_simple_dynamic_model((2, 3, 4, 3), (3, 4), target, dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_lrn(target, dev):\n    \"\"\"test_lrn\"\"\"\n\n    def verify_lrn(shape, nsize, dtype, alpha=None, beta=None, bias=None):\n        in_array = np.random.uniform(size=shape).astype(dtype)\n\n        if alpha is None and beta is None and bias is None:\n            alpha = 0.0001\n            beta = 0.75\n            bias = 1.0\n            node = onnx.helper.make_node(\"LRN\", inputs=[\"in\"], outputs=[\"out\"], size=nsize)\n        else:\n            node = onnx.helper.make_node(\n                \"LRN\", inputs=[\"in\"], outputs=[\"out\"], alpha=alpha, beta=beta, bias=bias, size=nsize\n            )\n\n        graph = helper.make_graph(\n            [node],\n            \"lrn_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"lrn_test\")\n        verify_with_ort_with_inputs(model, [in_array], target=target, dev=dev)\n\n    verify_lrn((5, 5, 5, 5), 3, \"float32\")\n    verify_lrn((5, 5, 5, 5), 3, \"float32\", alpha=0.0002, beta=0.5, bias=2.0)\n\n\n@tvm.testing.parametrize_targets\ndef test_instance_norm(target, dev):\n    \"\"\"test_instance_norm\"\"\"\n\n    def verify_instance_norm(shape, axis=1):\n        x = np.random.randn(*shape).astype(np.float32)\n        gamma = np.random.randn(shape[1]).astype(np.float32)\n        beta = np.random.randn(shape[1]).astype(np.float32)\n        epsilon = 1e-5\n\n        node = onnx.helper.make_node(\n            \"InstanceNormalization\",\n            inputs=[\"x\", \"gamma\", \"beta\"],\n            outputs=[\"y\"],\n            epsilon=epsilon,\n        )\n        graph = helper.make_graph(\n            [node],\n            \"instance_norm_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(shape)),\n                helper.make_tensor_value_info(\"gamma\", TensorProto.FLOAT, (shape[1],)),\n                helper.make_tensor_value_info(\"beta\", TensorProto.FLOAT, (shape[1],)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"instance_norm_test\")\n        verify_with_ort_with_inputs(\n            model, [x, gamma, beta], out_shape=[shape], target=target, dev=dev\n        )\n\n    verify_instance_norm((2, 3, 4, 5))\n    verify_instance_norm((32, 64, 80, 64))\n    verify_instance_norm((8, 6, 5))\n    verify_instance_norm((8, 7, 6, 5, 4))\n\n\n@tvm.testing.parametrize_targets\ndef test_upsample_nearest(target, dev):\n    \"\"\"test_upsample_nearest\"\"\"\n    scale = 2\n    in_shape = (1, 1, 3, 3)\n    out_shape = (1, 1, 3 * scale, 3 * scale)\n    y = helper.make_node(\"Upsample\", [\"in\"], [\"out\"], mode=\"nearest\", scales=[1.0, 1.0, 2.0, 2.0])\n\n    in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n    graph = helper.make_graph(\n        [y],\n        \"upsample_nearest_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"upsample_nearest_test\")\n    verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_upsample3d_nearest(target, dev):\n    \"\"\"test_upsample3d_nearest\"\"\"\n    scale = 2\n    in_shape = (1, 1, 3, 3, 3)\n    out_shape = (1, 1, 3 * scale, 3 * scale, 3 * scale)\n    y = helper.make_node(\n        \"Upsample\", [\"in\"], [\"out\"], mode=\"nearest\", scales=[1.0, 1.0, 2.0, 2.0, 2.0]\n    )\n\n    in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n    graph = helper.make_graph(\n        [y],\n        \"upsample_nearest_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"upsample_nearest_test\")\n    # Upsample is deprecated after opset 9\n    verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_upsample_bilinear(target, dev):\n    \"\"\"test_upsample_bilinear\"\"\"\n    scale = 2\n    in_shape = (1, 1, 3, 3)\n    out_shape = (1, 1, 3 * scale, 3 * scale)\n    y = helper.make_node(\"Upsample\", [\"in\"], [\"out\"], mode=\"linear\", scales=[1.0, 1.0, 2.0, 2.0])\n\n    in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n    graph = helper.make_graph(\n        [y],\n        \"upsample_bilinear_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"upsample_bilinear_test\")\n    verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_upsample3d_trilinear(target, dev):\n    \"\"\"test_upsample3d_trilinear\"\"\"\n    scale = 2\n    in_shape = (1, 1, 3, 3, 3)\n    out_shape = (1, 1, 3 * scale, 3 * scale, 3 * scale)\n    y = helper.make_node(\"Upsample\", [\"in\", \"scales\"], [\"out\"], mode=\"linear\")\n    scales = [1.0, 1.0, 2.0, 2.0, 2.0]\n    in_array = np.random.uniform(size=in_shape).astype(np.float32)\n    out_array = tvm.topi.testing.resize3d_python(\n        in_array,\n        (scale, scale, scale),\n        \"NCDHW\",\n        \"linear\",\n        coordinate_transformation_mode=\"asymmetric\",\n    )\n\n    ref_array = np.array(scales)\n    ref_node = helper.make_node(\n        \"Constant\",\n        inputs=[],\n        outputs=[\"scales\"],\n        value=onnx.helper.make_tensor(\n            name=\"const_tensor\",\n            data_type=TensorProto.FLOAT,\n            dims=ref_array.shape,\n            vals=ref_array.flatten().astype(float),\n        ),\n    )\n\n    graph = helper.make_graph(\n        [ref_node, y],\n        \"upsample_trilinear_test\",\n        inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n        outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"upsample_trilinear_test\")\n    # TODO(jwfromm): Trilinear upsampling not supported in 1.0.0 onnxruntime.\n    # Replace topi comparison with verify_with_ort once we update.\n    tvm_out = get_tvm_output(model, in_array, target, dev, out_shape, \"float32\")\n    tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5)\n\n\n# TODO: Fix softmax with dynamic input on cuda and enable this test\n@tvm.testing.known_failing_targets(\"cuda\")\n@tvm.testing.parametrize_targets\ndef test_softmax(target, dev):\n    \"\"\"test_softmax\"\"\"\n\n    def verify_softmax(inshape, axis, opset=None, dynamic=False):\n        opname = \"Softmax\"\n        outshape = inshape\n        node_list = []\n        input_node_list = [helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(inshape))]\n        output_node_list = [helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outshape))]\n        input_list = [np.random.uniform(size=inshape).astype(np.float32)]\n        softmax_inputs = [\"in\"]\n\n        if dynamic:\n            input_node_list.append(\n                helper.make_tensor_value_info(\"shape\", TensorProto.INT64, [len(inshape)])\n            )\n            input_list.append(np.asarray(inshape))\n            reshape_node = helper.make_node(\"Reshape\", [\"in\", \"shape\"], [\"dynamic_in\"])\n            softmax_inputs[0] = \"dynamic_in\"\n            node_list += [reshape_node]\n\n        y = helper.make_node(opname, softmax_inputs, [\"out\"])\n        if axis is not None:\n            axis_attr = helper.make_attribute(\"axis\", axis)\n            y.attribute.append(axis_attr)\n        node_list.append(y)\n\n        graph = helper.make_graph(\n            node_list,\n            opname + \"_test\",\n            inputs=input_node_list,\n            outputs=output_node_list,\n        )\n\n        model = helper.make_model(graph, producer_name=opname + \"_test\")\n        verify_with_ort_with_inputs(\n            model, input_list, use_vm=True, opset=opset, target=target, dev=dev\n        )\n\n    verify_softmax((1, 10), None)\n    verify_softmax((1, 10), 1)\n    verify_softmax((1, 2, 3, 10), 0)\n    verify_softmax((1, 2, 3, 10), 2)\n    verify_softmax((1, 2, 3, 4, 10), 3)\n    verify_softmax((1, 2, 3, 4, 10), 4)\n    verify_softmax((1, 10), -1, dynamic=True)\n    verify_softmax((1, 2, 3, 10), -1, dynamic=True)\n    verify_softmax((1, 10), -1, opset=8, dynamic=True)\n    verify_softmax((1, 2, 3, 10), -1, opset=8, dynamic=True)\n\n\n@tvm.testing.parametrize_targets\ndef test_forward_min(target, dev):\n    \"\"\"test_forward_min\"\"\"\n\n    def verify_min(input_dim):\n        dtype = \"float32\"\n\n        a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n        min_node = helper.make_node(\"Min\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [min_node],\n            \"Min_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"Min_test\")\n        verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n    verify_min((1, 3, 20, 20))\n    verify_min((20, 20))\n\n\n@tvm.testing.parametrize_targets\ndef test_forward_max(target, dev):\n    \"\"\"test_forward_max\"\"\"\n\n    def verify_max(input_dim):\n        dtype = \"float32\"\n\n        a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n        max_node = helper.make_node(\"Max\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [max_node],\n            \"Max_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"Max_test\")\n        verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n    verify_max((1, 3, 20, 20))\n    verify_max((20, 20))\n\n\n@tvm.testing.parametrize_targets\ndef test_forward_mean(target, dev):\n    \"\"\"test_forward_mean\"\"\"\n\n    def verify_mean(input_dim):\n        dtype = \"float32\"\n\n        a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n        a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n        mean_node = helper.make_node(\"Mean\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n        graph = helper.make_graph(\n            [mean_node],\n            \"Mean_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n                helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"Mean_test\")\n        verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n    verify_mean((1, 3, 20, 20))\n    verify_mean((20, 20))\n\n\n@tvm.testing.parametrize_targets\ndef test_forward_hardsigmoid(target, dev):\n    \"\"\"test_forward_hardsigmoid\"\"\"\n\n    def verify_hardsigmoid(input_dim, alpha, beta):\n        dtype = \"float32\"\n\n        a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n\n        hardsigmoid_node = helper.make_node(\n            \"HardSigmoid\", [\"a_np1\"], [\"out\"], alpha=alpha, beta=beta\n        )\n\n        graph = helper.make_graph(\n            [hardsigmoid_node],\n            \"HardSigmoid_test\",\n            inputs=[helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"HardSigmoid_test\")\n        verify_with_ort_with_inputs(model, [a_np1], target=target, dev=dev)\n\n    verify_hardsigmoid((1, 3, 20, 20), 0.5, 0.6)\n    verify_hardsigmoid((20, 20), 0.3, 0.4)\n\n\n# TODO (mbrookhart, electriclilies) Fix argmin on GPU and enable this test\n@tvm.testing.known_failing_targets(\"cuda\")\n@tvm.testing.parametrize_targets\ndef test_forward_arg_min_max(target, dev):\n    \"\"\"test_forward_arg_min_max\"\"\"\n\n    def verify_argreduce(input_dim, op_name, axis=None, keepdims=None):\n        a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32)\n        out_shape = list(a_np1.shape)\n        def_axis = axis if axis is not None else 0\n        if keepdims == 1 or keepdims is None:\n            out_shape[def_axis] = 1\n        else:\n            out_shape.pop(def_axis)\n\n        node = onnx.helper.make_node(op_name, inputs=[\"a_np1\"], outputs=[\"out\"])\n\n        if keepdims is not None:\n            keepdims_attr = helper.make_attribute(\"keepdims\", keepdims)\n            node.attribute.append(keepdims_attr)\n        if axis is not None:\n            axis_attr = helper.make_attribute(\"axis\", axis)\n            node.attribute.append(axis_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"argreduce_test\",\n            inputs=[helper.make_tensor_value_info(\"a_np1\", TensorProto.INT32, list(a_np1.shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.INT64, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"argreduce_test\")\n        verify_with_ort_with_inputs(model, [a_np1], target=target, dev=dev)\n\n    # Verify argmin and argmax\n    verify_argreduce([3, 4, 4], \"ArgMin\")\n    verify_argreduce([3, 4, 4], \"ArgMax\")\n    verify_argreduce([3, 4, 4], \"ArgMin\", axis=1)\n    verify_argreduce([3, 4, 4], \"ArgMax\", axis=0)\n    verify_argreduce([3, 4, 4], \"ArgMin\", keepdims=0)\n    verify_argreduce([3, 4, 4], \"ArgMax\", keepdims=1)\n    for axis in [None, 0, 1, 2]:\n        for keepdims in [None, True, False]:\n            verify_argreduce([3, 4, 4], \"ArgMin\", axis, keepdims)\n            verify_argreduce([3, 4, 4], \"ArgMax\", axis, keepdims)\n\n\n@tvm.testing.parametrize_targets\ndef test_constantofshape(target, dev):\n    \"\"\"test_constantofshape\"\"\"\n\n    def verify_constantofshape(input_dim, value, dtype):\n        fill_node = helper.make_node(\n            \"ConstantOfShape\",\n            [\"input\"],\n            [\"output\"],\n            value=helper.make_tensor(\n                \"value\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], (1,), (value,)\n            ),\n        )\n\n        inputs = [helper.make_tensor_value_info(\"input\", TensorProto.INT64, [len(input_dim)])]\n\n        graph = helper.make_graph(\n            [fill_node],\n            \"fill_test\",\n            inputs,\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"output\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], input_dim\n                )\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"fill_test\")\n        input_np = np.array(input_dim).astype(\"int64\")\n        verify_with_ort_with_inputs(model, [input_np], use_vm=True, target=target, dev=dev)\n\n    verify_constantofshape((2, 3, 4, 5), 10, \"float32\")\n    verify_constantofshape((3, 3), 0, \"int32\")\n    verify_constantofshape((1, 2, 3), -1, \"float32\")\n\n\n@tvm.testing.parametrize_targets\ndef test_pad(target, dev):\n    \"\"\"test_pad\"\"\"\n\n    def verify_pad(indata, pads, mode=\"constant\", value=0.0):\n        indata = np.array(indata).astype(np.float32)\n        #  numpy expect result\n        len_dim = len(pads) // 2\n        np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]\n        #  onnx graph\n        if mode in [\"edge\", \"reflect\"]:\n            outdata = np.pad(indata, pad_width=np_pads, mode=mode)\n            node = helper.make_node(\n                \"Pad\",\n                inputs=[\"input\"],\n                outputs=[\"output\"],\n                mode=mode,\n                pads=pads,\n            )\n        else:\n            outdata = np.pad(indata, pad_width=np_pads, mode=\"constant\", constant_values=value)\n            node = helper.make_node(\n                \"Pad\", inputs=[\"input\"], outputs=[\"output\"], mode=\"constant\", pads=pads, value=value\n            )\n        graph = helper.make_graph(\n            [node],\n            \"pad_test\",\n            inputs=[helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape))],\n            outputs=[\n                helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"pad_test\")\n        verify_with_ort_with_inputs(\n            model, [indata], [outdata.shape], dtype=\"float32\", opset=2, target=target, dev=dev\n        )\n\n    def verify_pad_v11(indata, pads, mode=\"constant\", value=0.0):\n        indata = np.array(indata).astype(np.float32)\n        #  numpy expect result\n        len_dim = len(pads) // 2\n        np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]\n        pads = np.array(pads)\n        #  onnx graph\n        if mode in [\"edge\", \"reflect\"]:\n            inputs = [indata]\n            outdata = np.pad(indata, pad_width=np_pads, mode=mode)\n            node = helper.make_node(\"Pad\", inputs=[\"input\", \"pads\"], outputs=[\"output\"], mode=mode)\n            graph = helper.make_graph(\n                [node],\n                \"pad_test\",\n                inputs=[\n                    helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n                    helper.make_tensor_value_info(\"pads\", TensorProto.INT64, (len(pads),)),\n                ],\n                initializer=[helper.make_tensor(\"pads\", TensorProto.INT64, (len(pads),), pads)],\n                outputs=[\n                    helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n                ],\n            )\n        else:\n            inputs = [indata]\n            outdata = np.pad(indata, pad_width=np_pads, mode=\"constant\", constant_values=value)\n            node = helper.make_node(\n                \"Pad\",\n                inputs=[\"input\", \"pads\", \"constant_value\"],\n                outputs=[\"output\"],\n                mode=\"constant\",\n            )\n            graph = helper.make_graph(\n                [node],\n                \"pad_test\",\n                inputs=[\n                    helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n                    helper.make_tensor_value_info(\"pads\", TensorProto.INT64, (len(pads),)),\n                    helper.make_tensor_value_info(\"constant_value\", TensorProto.FLOAT, (1,)),\n                ],\n                initializer=[\n                    helper.make_tensor(\"pads\", TensorProto.INT64, (len(pads),), pads),\n                    helper.make_tensor(\"constant_value\", TensorProto.FLOAT, (1,), [value]),\n                ],\n                outputs=[\n                    helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n                ],\n            )\n        model = helper.make_model(graph, producer_name=\"pad_test\")\n        verify_with_ort_with_inputs(model, inputs, opset=11, use_vm=True, target=target, dev=dev)\n\n    verify_pad(np.random.randn(2, 2).astype(np.float32), [0, 1, 0, 0], \"constant\", 0.0)\n    verify_pad(np.random.randn(2, 3).astype(np.float32), [1, 0, 0, 1], \"constant\", 0.0)\n    verify_pad(np.random.randn(3, 2).astype(np.float32), [0, 0, 1, 0], \"constant\", 5.0)\n    verify_pad(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"edge\")\n    verify_pad(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"reflect\")\n\n    verify_pad_v11(np.random.randn(2, 2).astype(np.float32), [0, 1, 0, 0], \"constant\", 0.0)\n    verify_pad_v11(np.random.randn(2, 3).astype(np.float32), [1, 0, 0, 1], \"constant\", 0.0)\n    verify_pad_v11(np.random.randn(3, 2).astype(np.float32), [0, 0, 1, 0], \"constant\", 5.0)\n    verify_pad_v11(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"edge\")\n    verify_pad_v11(\n        np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"reflect\"\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_all_reduce_funcs(target, dev):\n    \"\"\"test_all_reduce_funcs\"\"\"\n\n    def verify_reduce_func(func, data, axis, keepdims):\n        inshape = data.shape\n        outshape = np.sum(data, axis=axis, keepdims=keepdims == 1).shape\n\n        if axis:\n            node = onnx.helper.make_node(\n                func, inputs=[\"x\"], outputs=[\"y\"], axes=axis, keepdims=keepdims\n            )\n        else:\n            node = onnx.helper.make_node(func, inputs=[\"x\"], outputs=[\"y\"], keepdims=keepdims)\n\n        graph = helper.make_graph(\n            [node],\n            \"reduce_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"reduce_test\")\n\n        verify_with_ort_with_inputs(\n            model,\n            [data],\n            [outshape],\n            opset=11,\n            target=target,\n            dev=dev,\n            rtol=1e-4,\n            atol=1e-4,\n        )\n\n    funcs = [\n        \"ReduceMax\",\n        \"ReduceMean\",\n        \"ReduceMin\",\n        \"ReduceProd\",\n        \"ReduceSum\",\n        \"ReduceSumSquare\",\n        \"ReduceLogSum\",\n        \"ReduceLogSumExp\",\n        \"ReduceL1\",\n        \"ReduceL2\",\n    ]\n\n    for func in funcs:\n        verify_reduce_func(func, np.array(1.0).astype(np.float32), axis=None, keepdims=False)\n\n        for keepdims in [True, False]:\n            verify_reduce_func(\n                func, np.random.randn(3, 2, 2).astype(np.float32), axis=None, keepdims=keepdims\n            )\n\n            verify_reduce_func(\n                func, np.random.randn(3, 2, 3).astype(np.float32), axis=None, keepdims=keepdims\n            )\n\n            verify_reduce_func(\n                func, np.random.randn(3, 3, 3).astype(np.float32), axis=(1,), keepdims=keepdims\n            )\n\n            verify_reduce_func(\n                func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1, 2), keepdims=keepdims\n            )\n\n            verify_reduce_func(\n                func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1,), keepdims=keepdims\n            )\n\n            verify_reduce_func(\n                func, np.random.randn(1, 3, 4, 1).astype(np.float32), axis=(1,), keepdims=keepdims\n            )\n\n\n@tvm.testing.parametrize_targets\ndef test_split(target, dev):\n    \"\"\"test_split\"\"\"\n\n    def verify_split(indata, outdatas, split, axis=0, pass_split=True, opset=11):\n        indata = np.array(indata).astype(np.float32)\n        outdatas = [np.array(o).astype(np.float32) for o in outdatas]\n        inputs = [helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape))]\n        input_names = [\"input\"]\n        initializer = []\n\n        if split:\n            split_index = range(len(split))\n        else:\n            split_index = range(len(outdatas))\n\n        if pass_split:\n            if opset >= 13:\n                input_names.append(\"split\")\n                np_split = np.array(split).astype(np.int64)\n                inputs.append(\n                    helper.make_tensor_value_info(\"split\", TensorProto.INT64, list(np_split.shape))\n                )\n                # TODO(mbrookhart): Support dynamic split, edit this test case to remove split from\n                # the initializer and add it back to the input data\n                indata = [indata]  # , np_split]\n                initializer.append(\n                    helper.make_tensor(\"split\", TensorProto.INT64, list(np_split.shape), np_split)\n                )\n        node = helper.make_node(\n            \"Split\",\n            inputs=input_names,\n            outputs=[f\"output_{i}\" for i in range(len(split_index))],\n            axis=axis,\n        )\n\n        if pass_split and opset < 13:\n            split_attr = helper.make_attribute(\"split\", split)\n            node.attribute.append(split_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"split_test\",\n            inputs=inputs,\n            initializer=initializer,\n            outputs=[\n                helper.make_tensor_value_info(\n                    f\"output_{i}\", TensorProto.FLOAT, list(outdatas[i].shape)\n                )\n                for i in range(len(split_index))\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"split_test\")\n        verify_with_ort_with_inputs(\n            model,\n            indata,\n            out_shape=list(range(len(split_index))),\n            opset=opset,\n            target=target,\n            dev=dev,\n            use_vm=True,\n            freeze_params=(opset >= 13),\n        )\n\n    # 1D\n    verify_split([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [2, 2, 2], 0)\n    verify_split(\n        [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [2, 2, 2], 0, False\n    )\n    verify_split([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0], [4.0, 5.0, 6.0]], [2, 1, 3], 0)\n    verify_split(\n        [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0], [4.0, 5.0, 6.0]], [2, 1, 3], 0, opset=13\n    )\n    # 2D\n    verify_split(\n        [[1.0, 2.0, 3.0, 4.0], [7.0, 8.0, 9.0, 10.0]],\n        [[[1.0, 2.0], [7.0, 8.0]], [[3.0, 4.0], [9.0, 10.0]]],\n        [2, 2],\n        1,\n    )\n    verify_split(\n        [[1.0, 2.0, 3.0, 4.0], [7.0, 8.0, 9.0, 10.0]],\n        [[[1.0, 2.0], [7.0, 8.0]], [[3.0, 4.0], [9.0, 10.0]]],\n        [2, 2],\n        1,\n        opset=13,\n    )\n    # Split evenly (unstack)\n    verify_split([1, 2, 3], [[1], [2], [3]], False, 0, False)\n    # Split a single value to a single value\n    verify_split([1], [[1]], [1], pass_split=True)\n    # Test that the default case modifies nothing when split list has length one\n    verify_split([[1.0, 2.0]], [[1.0, 2.0]], [2], 1)\n    verify_split([[1.0, 2.0]], [[1.0, 2.0]], [1], 0)\n\n\n@tvm.testing.parametrize_targets\ndef test_binary_ops(target, dev):\n    \"\"\"test_binary_ops\"\"\"\n    in_shape = (1, 2, 3, 3)\n    dtype = \"float32\"\n    out_shape = in_shape\n\n    def verify_binary_ops(op, x, y, out_type=\"float32\"):\n        out = helper.make_node(op, [\"in1\", \"in2\"], [\"out\"])\n        graph = helper.make_graph(\n            [out],\n            \"_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"in1\", TensorProto.FLOAT, x.shape),\n                helper.make_tensor_value_info(\"in2\", TensorProto.FLOAT, y.shape),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(out_type)], list(out_shape)\n                )\n            ],\n        )\n        model = helper.make_model(graph, producer_name=\"_test\")\n        verify_with_ort_with_inputs(model, [x, y], target=target, dev=dev)\n\n    x = np.random.uniform(size=in_shape).astype(dtype)\n    y = np.random.uniform(size=in_shape).astype(dtype)\n    z_array = np.random.uniform(size=(3,)).astype(dtype)\n    verify_binary_ops(\"Add\", x, y)\n    verify_binary_ops(\"Add\", x, z_array)\n    verify_binary_ops(\"Sub\", x, y)\n    verify_binary_ops(\"Sub\", x, z_array)\n    verify_binary_ops(\"Mul\", x, y)\n    verify_binary_ops(\"Mul\", x, z_array)\n    verify_binary_ops(\"Div\", x, y)\n    verify_binary_ops(\"Div\", x, z_array)\n    verify_binary_ops(\"Sum\", x, y)\n    verify_binary_ops(\"Sum\", x, z_array)\n    verify_binary_ops(\"Greater\", x, y, \"bool\")\n    verify_binary_ops(\"Greater\", x, z_array, \"bool\")\n    verify_binary_ops(\"GreaterOrEqual\", x, y, \"bool\")\n    verify_binary_ops(\"GreaterOrEqual\", x, z_array, \"bool\")\n    verify_binary_ops(\"Less\", x, y, \"bool\")\n    verify_binary_ops(\"Less\", x, z_array, \"bool\")\n    verify_binary_ops(\"LessOrEqual\", x, y, \"bool\")\n    verify_binary_ops(\"LessOrEqual\", x, z_array, \"bool\")\n    verify_binary_ops(\"Equal\", x, y, \"bool\")\n    verify_binary_ops(\"Equal\", x, z_array, \"bool\")\n\n\n@tvm.testing.parametrize_targets\ndef test_unary_ops(target, dev):\n    \"\"\"test_unary_ops\"\"\"\n    in_shape = (1, 2, 3, 3)\n    _ = \"float32\"\n    out_shape = in_shape\n\n    def verify_unary_ops(op, x, rtol=1e-5, atol=1e-5, dtype=\"float32\"):\n        x = x.astype(dtype)\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        out = helper.make_node(op, [\"in1\"], [\"out\"])\n        graph = helper.make_graph(\n            [out],\n            \"_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"in1\", ONNX_DTYPE, list(in_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, list(out_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"_test\")\n        verify_with_ort_with_inputs(model, [x], rtol=rtol, atol=atol, target=target, dev=dev)\n\n    x = np.random.uniform(size=in_shape)\n    verify_unary_ops(\"Neg\", x)\n    verify_unary_ops(\"Abs\", x)\n    verify_unary_ops(\"Reciprocal\", x)\n    verify_unary_ops(\"Reciprocal\", x, dtype=\"float16\")\n    verify_unary_ops(\"Sqrt\", x)\n    verify_unary_ops(\"Relu\", x)\n    verify_unary_ops(\"Exp\", x)\n    verify_unary_ops(\"Log\", x)\n    verify_unary_ops(\"Log\", x)\n    verify_unary_ops(\"Acos\", x)\n    verify_unary_ops(\"Acosh\", x)\n    verify_unary_ops(\"Asin\", x)\n    verify_unary_ops(\"Asinh\", x)\n    verify_unary_ops(\"Atan\", x)\n    verify_unary_ops(\"Atanh\", x)\n    verify_unary_ops(\"Cos\", x)\n    verify_unary_ops(\"Cosh\", x)\n    verify_unary_ops(\"Sin\", x)\n    verify_unary_ops(\"Sinh\", x)\n    verify_unary_ops(\"Tan\", x)\n    verify_unary_ops(\"Tanh\", x)\n    verify_unary_ops(\"Sigmoid\", x)\n    verify_unary_ops(\"Softsign\", x)\n\n\n@tvm.testing.parametrize_targets\ndef test_leaky_relu(target, dev):\n    def leaky_relu_x(x, alpha):\n        return np.where(x >= 0, x, x * alpha)\n\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        leaky_relu_x,\n        {\"alpha\": 0.25},\n        \"float32\",\n        \"LeakyRelu\",\n        {\"alpha\": 0.25},\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_elu(target, dev):\n    def elu_x(x, alpha):\n        return np.where(x > 0, x, alpha * (np.exp(x) - 1.0))\n\n    _test_onnx_op_elementwise(\n        target, dev, (2, 4, 5, 6), elu_x, {\"alpha\": 0.25}, \"float32\", \"Elu\", {\"alpha\": 0.25}\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_selu(target, dev):\n    def selu_x(x, alpha, gamma):\n        return gamma * np.where(x > 0, x, alpha * (np.exp(x) - 1.0))\n\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        selu_x,\n        {\"alpha\": 0.25, \"gamma\": 0.3},\n        \"float32\",\n        \"Selu\",\n        {\"alpha\": 0.25, \"gamma\": 0.3},\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_prelu(target, dev):\n    \"\"\"test_prelu\"\"\"\n\n    def verify_prelu(x_shape, a_shape):\n        node = helper.make_node(\"PRelu\", inputs=[\"X\", \"slope\"], outputs=[\"Y\"])\n\n        graph = helper.make_graph(\n            [node],\n            \"prelu_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"slope\", TensorProto.FLOAT, list(a_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(x_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"prelu_test\")\n\n        verify_with_ort(\n            model,\n            [x_shape, a_shape],\n            out_shape=[list(x_shape)],\n            use_vm=True,\n            target=target,\n            dev=dev,\n        )\n\n    verify_prelu([3, 4, 5, 6], [1, 4, 1, 1])\n    verify_prelu([1, 8, 5, 6], [1, 8, 1, 1])\n    verify_prelu([2, 12, 16, 16], [1, 12, 1, 1])\n    verify_prelu([2, 12, 16, 16], [1])  # Test alpha broadcasting.\n    verify_prelu([3, 1], [3, 1])  # Test non NCHW workload.\n\n\n@tvm.testing.parametrize_targets\ndef test_thresholded_relu(target, dev):\n    def thresholded_relu_x(x, alpha):\n        out_np = np.clip(x, alpha, np.inf)\n        out_np[out_np == alpha] = 0\n        return out_np\n\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (2, 4, 5, 6),\n        thresholded_relu_x,\n        {\"alpha\": 0.25},\n        \"float32\",\n        \"ThresholdedRelu\",\n        {\"alpha\": 0.25},\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_logsoftmax(target, dev):\n    _test_onnx_op_elementwise(\n        target,\n        dev,\n        (1, 4),\n        tvm.topi.testing.log_softmax_python,\n        {},\n        \"float32\",\n        \"LogSoftmax\",\n        {\"axis\": 1},\n    )\n\n\ndef check_torch_conversion(model, input_size, target, dev):\n    dummy_input = torch.randn(*input_size)\n    file_name = f\"{model.__name__}.onnx\"\n    # Set verbose=True for more output\n    torch.onnx.export(model(), dummy_input, file_name, export_params=True, verbose=False)\n    onnx_model = onnx.load(file_name)\n    input_data = np.random.uniform(size=input_size).astype(\"float32\")\n    verify_with_ort_with_inputs(\n        onnx_model, [input_data], apply_softmax=True, target=target, dev=dev\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_resnet(target, dev):\n    check_torch_conversion(torchvision.models.resnet18, (1, 3, 224, 224), target, dev)\n    # check_torch_conversion(torchvision.models.resnet101, (1,3,224,224))\n\n\n# def test_alexnet():\n# Torch's ONNX export does not support the adaptive pooling used by AlexNet?\n# check_torch_conversion(torchvision.models.alexnet, (1,3,224,224))\n\n# Torch's ONNX export does not support the adaptive pooling used by vgg16?\n# def test_vgg16():\n#     check_torch_conversion(torchvision.models.vgg16, (1,3,224,224))\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_squeezenet():\n#     # Torch's ONNX export does not support the max pooling used by Squezenet\n#     check_torch_conversion(torchvision.models.squeezenet1_0, (1,3,224,224))\n\n\n@tvm.testing.parametrize_targets\ndef test_densenet(target, dev):\n    check_torch_conversion(torchvision.models.densenet161, (1, 3, 224, 224), target, dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_inception(target, dev):\n    check_torch_conversion(torchvision.models.inception_v3, (1, 3, 224, 224), target, dev)\n\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_googlenet():\n#     check_torch_conversion(torchvision.models.googlenet, (1,3,224,224))\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_shufflenetv2():\n#     check_torch_conversion(torchvision.models.shufflenetv2, (1,3,224,224))\n\n\n@tvm.testing.parametrize_targets\ndef test_sign(target, dev):\n    def sign_x(x):\n        return np.sign(x)\n\n    _test_onnx_op_elementwise(target, dev, (3, 4, 5, 6), sign_x, {}, \"float32\", \"Sign\", {})\n\n\n@tvm.testing.parametrize_targets\ndef test_not(target, dev):\n    \"\"\"test_not\"\"\"\n\n    def verify_not(indata, dtype):\n        x = indata.astype(dtype)\n\n        node = helper.make_node(\n            \"Not\",\n            inputs=[\"in\"],\n            outputs=[\"out\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"not_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.BOOL, list(x.shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(x.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"not_test\")\n        verify_with_ort_with_inputs(model, [x], target=target, dev=dev)\n\n    # 2d\n    verify_not(indata=(np.random.randn(3, 4) > 0), dtype=bool)\n    # 3d\n    verify_not(indata=(np.random.randn(3, 4, 5) > 0), dtype=bool)\n    # 4d\n    verify_not(indata=(np.random.randn(3, 4, 5, 6) > 0), dtype=bool)\n\n\n@tvm.testing.parametrize_targets\ndef test_and(target, dev):\n    \"\"\"test_and\"\"\"\n\n    def verify_and(indata, dtype):\n        x = indata[0].astype(dtype)\n        y = indata[1].astype(dtype)\n        outdata = np.logical_and(x, y)\n\n        node = helper.make_node(\n            \"And\",\n            inputs=[\"in1\", \"in2\"],\n            outputs=[\"out\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"and_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"in1\", TensorProto.BOOL, list(x.shape)),\n                helper.make_tensor_value_info(\"in2\", TensorProto.BOOL, list(y.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"and_test\")\n        verify_with_ort_with_inputs(model, [x, y], [outdata.shape], target=target, dev=dev)\n\n    # 2d\n    x = np.random.randn(3, 4) > 0\n    y = np.random.randn(3, 4) > 0\n    verify_and(indata=[x, y], dtype=bool)\n\n    # 3d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(3, 4, 5) > 0\n    verify_and(indata=[x, y], dtype=bool)\n\n    # 4d\n    x = np.random.randn(3, 4, 5, 6) > 0\n    y = np.random.randn(3, 4, 5, 6) > 0\n    verify_and(indata=[x, y], dtype=bool)\n\n    # 3d vs 1d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(5) > 0\n    verify_and(indata=[x, y], dtype=bool)\n\n    # 3d vs 2d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(4, 5) > 0\n    verify_and(indata=[x, y], dtype=bool)\n\n\n@tvm.testing.parametrize_targets\ndef test_tile(target, dev):\n    \"\"\"test_tile\"\"\"\n\n    def verify_tile_v6(indata, repeats, outdata):\n        node = helper.make_node(\"Tile\", inputs=[\"input\", \"repeats\"], outputs=[\"out\"])\n        graph = helper.make_graph(\n            [node],\n            \"tile_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n                helper.make_tensor_value_info(\"repeats\", TensorProto.INT64, list(repeats.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"tile_test\")\n        verify_with_ort_with_inputs(\n            model, [indata, repeats], use_vm=True, opset=6, target=target, dev=dev\n        )\n\n    x = np.random.rand(2, 3, 4, 5).astype(np.float32)\n    repeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n    z_array = np.tile(x, repeats)\n    verify_tile_v6(x, repeats, z_array)\n\n\n@tvm.testing.parametrize_targets\ndef test_erf(target, dev):\n    \"\"\"test_erf\"\"\"\n\n    def verify_erf(indata, outdata):\n        node = helper.make_node(\"Erf\", inputs=[\"in\"], outputs=[\"out\"])\n        graph = helper.make_graph(\n            [node],\n            \"erf_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"erf_test\")\n        verify_with_ort_with_inputs(model, [indata], [outdata.shape], target=target, dev=dev)\n\n    x = np.random.rand(2, 3, 4, 6).astype(np.float32)\n    z_array = scipy.special.erf(x)\n    verify_erf(x, z_array)\n\n\n@tvm.testing.parametrize_targets\ndef test_where(target, dev):\n    \"\"\"test_where\"\"\"\n\n    def verify_where(condition, x, y, dtype, outdata, dynamic=False):\n        node_list = []\n        where_inputs = [\"condition\", \"x\", \"y\"]\n        if dynamic:\n            shape_node = helper.make_node(\"Shape\", [\"x\"], [\"shape\"])\n            reshape_node = helper.make_node(\"Reshape\", [\"x\", \"shape\"], [\"X\"])\n            where_inputs[1] = \"X\"\n            node_list += [shape_node, reshape_node]\n        node = helper.make_node(\"Where\", inputs=where_inputs, outputs=[\"out\"])\n        node_list.append(node)\n        graph = helper.make_graph(\n            node_list,\n            \"where_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"condition\", TensorProto.BOOL, list(condition.shape)),\n                helper.make_tensor_value_info(\"x\", dtype, list(x.shape)),\n                helper.make_tensor_value_info(\"y\", dtype, list(y.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", dtype, list(outdata.shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"where_test\")\n        verify_with_ort_with_inputs(\n            model, [condition, x, y], [outdata.shape], use_vm=True, target=target, dev=dev\n        )\n\n    condition = np.array([[1, 0], [1, 1]], dtype=bool)\n    x = np.array([[1, 2], [3, 4]], dtype=np.int64)\n    y = np.array([[9, 8], [7, 6]], dtype=np.int64)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.INT64, outdata)\n\n    x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n    y = np.array([[9, 8], [7, 6]], dtype=np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n    x = np.array(1, dtype=np.float32)\n    y = np.array([2], dtype=np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n    x = np.array([2], dtype=np.float32)\n    y = np.array(1, dtype=np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n    condition = np.array(1, dtype=bool)\n    x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n    y = np.array([[5, 6], [7, 8]], dtype=np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n    x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n    y = np.array([[1], [7]], dtype=np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata, dynamic=True)\n\n    condition = np.random.uniform(size=(3, 1)) < 0.5\n    x = np.random.uniform(size=2).astype(np.float32)\n    y = np.random.uniform(size=2).astype(np.float32)\n    outdata = np.where(condition, x, y)\n    verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n\n@tvm.testing.parametrize_targets\ndef test_or(target, dev):\n    \"\"\"test_or\"\"\"\n\n    def verify_or(indata, dtype):\n        x = indata[0].astype(dtype)\n        y = indata[1].astype(dtype)\n        outdata = np.logical_or(x, y)\n\n        node = helper.make_node(\n            \"Or\",\n            inputs=[\"in1\", \"in2\"],\n            outputs=[\"out\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"or_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"in1\", TensorProto.BOOL, list(x.shape)),\n                helper.make_tensor_value_info(\"in2\", TensorProto.BOOL, list(y.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"or_test\")\n        verify_with_ort_with_inputs(model, [x, y], [outdata.shape], target=target, dev=dev)\n\n    # 2d\n    x = np.random.randn(3, 4) > 0\n    y = np.random.randn(3, 4) > 0\n    verify_or(indata=[x, y], dtype=bool)\n\n    # 3d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(3, 4, 5) > 0\n    verify_or(indata=[x, y], dtype=bool)\n\n    # 4d\n    x = np.random.randn(3, 4, 5, 6) > 0\n    y = np.random.randn(3, 4, 5, 6) > 0\n    verify_or(indata=[x, y], dtype=bool)\n\n    # 3d vs 1d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(5) > 0\n    verify_or(indata=[x, y], dtype=bool)\n\n    # 3d vs 2d\n    x = np.random.randn(3, 4, 5) > 0\n    y = np.random.randn(4, 5) > 0\n    verify_or(indata=[x, y], dtype=bool)\n\n\n@tvm.testing.parametrize_targets\ndef test_batch_norm(target, dev):\n    \"\"\"test_batch_norm\"\"\"\n\n    def verify_batch_norm(in_shape):\n        batchnorm = onnx.helper.make_node(\n            \"BatchNormalization\", inputs=[\"x\", \"scale\", \"B\", \"mean\", \"var\"], outputs=[\"Y\"]\n        )\n\n        graph = helper.make_graph(\n            [batchnorm],\n            \"batchnorm_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(in_shape)),\n                helper.make_tensor_value_info(\"scale\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"mean\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"var\", TensorProto.FLOAT, [in_shape[1]]),\n            ],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(in_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"batchnorm_test\")\n        # X, scale, b, mean, var\n        inshapes = [in_shape, in_shape[1], in_shape[1], in_shape[1], in_shape[1]]\n        verify_with_ort(model, inshapes, out_shape=[in_shape], target=target, dev=dev)\n\n    verify_batch_norm([1, 3, 224, 224])\n    verify_batch_norm([1, 3, 24, 24])\n    verify_batch_norm([16, 3, 24, 24])\n    verify_batch_norm([16, 16, 24, 24])\n    verify_batch_norm([16, 16, 10, 10])\n\n\n@tvm.testing.parametrize_targets\ndef test_batch_norm_dynamic_subgraph(target, dev):\n    \"\"\"test_batch_norm_dynamic_subgraph\"\"\"\n\n    def verify_batch_norm_dynamic_subgraph(in_shape, o_shape):\n\n        batchnorm = onnx.helper.make_node(\n            \"BatchNormalization\", inputs=[\"x\", \"scale\", \"B\", \"mean\", \"var\"], outputs=[\"Y\"]\n        )\n\n        shape_node = helper.make_node(\"Shape\", [\"Y\"], [\"shape\"])\n        reshape_node = helper.make_node(\"Reshape\", [\"in\", \"shape\"], [\"out\"])\n        graph = helper.make_graph(\n            [batchnorm, shape_node, reshape_node],\n            \"batchnorm_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(in_shape)),\n                helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(o_shape)),\n                helper.make_tensor_value_info(\"scale\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"mean\", TensorProto.FLOAT, [in_shape[1]]),\n                helper.make_tensor_value_info(\"var\", TensorProto.FLOAT, [in_shape[1]]),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(in_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"batchnorm_test\")\n\n        # X, inp, scale, b, mean, var\n        inshapes = [in_shape, o_shape, in_shape[1], in_shape[1], in_shape[1], in_shape[1]]\n        verify_with_ort(model, inshapes, out_shape=[in_shape], use_vm=True, target=target, dev=dev)\n\n    verify_batch_norm_dynamic_subgraph([16, 16, 10, 10], [160, 160])\n\n\n@tvm.testing.parametrize_targets\ndef test_conv(target, dev):\n    \"\"\"test_conv\"\"\"\n\n    def verify_conv(\n        x_shape,\n        w_shape,\n        y_shape,\n        padding,\n        kernel_shape,\n        strides,\n        dilations,\n        group=1,\n        auto_pad=\"NOTSET\",\n        unset_pad=False,\n    ):\n        if unset_pad:\n            node = helper.make_node(\n                \"Conv\",\n                inputs=[\"x\", \"W\"],\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                # Default values for other attributes:\n                strides=strides,\n                dilations=dilations,\n                group=group,\n            )\n        elif padding is None:\n            ## autopadding with unset default attributes\n            kwargs = {}\n            if not all(list(s == 1 for s in strides)):\n                kwargs[\"strides\"] = strides\n            if not all(list(d == 1 for d in dilations)):\n                kwargs[\"dilations\"] = dilations\n\n            node = helper.make_node(\n                \"Conv\",\n                inputs=[\"x\", \"W\"],\n                outputs=[\"y\"],\n                # Default values for other attributes:\n                auto_pad=auto_pad,\n                group=group,\n                **kwargs,\n            )\n        else:\n            node = helper.make_node(\n                \"Conv\",\n                inputs=[\"x\", \"W\"],\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                # Default values for other attributes:\n                strides=strides,\n                dilations=dilations,\n                group=group,\n                pads=padding,\n            )\n\n        graph = helper.make_graph(\n            [node],\n            \"conv_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"conv_test\")\n\n        verify_with_ort(\n            model,\n            [x_shape, w_shape],\n            [y_shape],\n            use_vm=True,\n            target=target,\n            dev=dev,\n        )\n\n    def repeat(num, dims):\n        return tuple(num for _ in range(dims))\n\n    for dims in [1, 2, 3]:\n        # Convolution with padding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(5, dims),\n            2 * repeat(1, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n        )\n        # Convolution with asymmetric padding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(4, dims),\n            repeat(0, dims) + repeat(1, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n        )\n        # Convolution without padding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(3, dims),\n            2 * repeat(0, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n        )\n        # Convolution with autopadding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(5, dims),\n            None,\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            auto_pad=\"SAME_UPPER\",\n        )\n        # Convolution with valid autopadding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(3, dims),\n            None,\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            auto_pad=\"VALID\",\n        )\n        # Convolution with unset padding\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(3, dims),\n            2 * repeat(0, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            True,\n        )\n        # Convolution with non uniform stride\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(3, dims),\n            None,\n            repeat(3, dims),\n            repeat(2, dims),\n            repeat(1, dims),\n            auto_pad=\"SAME_UPPER\",\n        )\n        # Convolution with dilation\n        verify_conv(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            (1, 1) + repeat(5, dims),\n            2 * repeat(2, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(2, dims),\n        )\n\n    # TODO(jwfromm): Merge with other tests once group_conv3d is supported.\n    for dims in [1, 2, 3]:\n        # Group Convolution\n        verify_conv(\n            (1, 8) + repeat(5, dims),\n            (8, 1) + repeat(3, dims),\n            (1, 8) + repeat(5, dims),\n            2 * repeat(1, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            group=8,\n        )\n\n        verify_conv(\n            (1, 12) + repeat(5, dims),\n            (30, 4) + repeat(3, dims),\n            (1, 30) + repeat(5, dims),\n            2 * repeat(1, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            group=3,\n        )\n\n\n@tvm.testing.parametrize_targets\ndef test_convtranspose(target, dev):\n    \"\"\"test_convtranspose\"\"\"\n\n    def verify_convtranspose_with_output_shape(\n        x_shape,\n        w_shape,\n        output_shape,\n        kernel_shape,\n        strides,\n        dilations,\n        auto_pad=\"SAME_UPPER\",\n        group=1,\n    ):\n        node = helper.make_node(\n            \"ConvTranspose\",\n            inputs=[\"x\", \"W\"],\n            outputs=[\"y\"],\n            kernel_shape=kernel_shape,\n            # Default values for other attributes:\n            strides=strides,\n            dilations=dilations,\n            output_shape=output_shape,\n            auto_pad=auto_pad,\n        )\n\n        if group is not None:\n            group_attr = helper.make_attribute(\"group\", group)\n            node.attribute.append(group_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"ConvTranspose_with_output_shape_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, [1, 1] + list(output_shape))\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"convtranspose_output_shape_test\")\n\n        verify_with_ort(model, [x_shape, w_shape], use_vm=True, target=target, dev=dev)\n\n    def verify_convtranspose_with_padding(\n        x_shape,\n        w_shape,\n        padding,\n        kernel_shape,\n        strides,\n        dilations,\n        auto_pad=\"NOTSET\",\n        unset_pad=False,\n        group=1,\n    ):\n        node = helper.make_node(\n            \"ConvTranspose\",\n            inputs=[\"x\", \"W\"],\n            outputs=[\"y\"],\n            kernel_shape=kernel_shape,\n            # Default values for other attributes:\n            strides=strides,\n            dilations=dilations,\n        )\n        if not unset_pad:\n            if padding is None:\n                pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n            else:\n                pad_attr = helper.make_attribute(\"pads\", padding)\n            node.attribute.append(pad_attr)\n\n        if group is not None:\n            group_attr = helper.make_attribute(\"group\", group)\n            node.attribute.append(group_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"convtranspose_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, [\"?\"] * len(x_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"convtranspose_pad_test\")\n\n        verify_with_ort(model, [x_shape, w_shape], use_vm=True, target=target, dev=dev)\n\n    def verify_convtranspose(x_shape, w_shape, y_shape, p, group=1):\n        node = onnx.helper.make_node(\n            \"ConvTranspose\",\n            inputs=[\"x\", \"W\"],\n            outputs=[\"y\"],\n            strides=[3, 2],\n            kernel_shape=[3, 3],\n            pads=p,\n        )\n\n        if group is not None:\n            group_attr = helper.make_attribute(\"group\", group)\n            node.attribute.append(group_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"verify_convtranspose_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"convtranspose_test\")\n        verify_with_ort(model, [x_shape, w_shape], y_shape, opset=11, target=target, dev=dev)\n\n    # Convolution Transpose with padding\n    # (1, 1, 3, 3) input tensor\n    # (1, 2, 3, 3) tensor for convolution weights\n    # (1, 2, 7, 3) output tensor\n    # [1, 2, 1, 2] list for pads\n    verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2])\n    # Test undefined groups.\n    verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2], group=None)\n\n    if \"llvm\" in target:\n        # GPU does not support groups != 1 for convtranspose, so only test llvm\n        # Test depthwise-convolution\n        verify_convtranspose((1, 10, 3, 3), (10, 1, 3, 3), (1, 10, 7, 3), [1, 2, 1, 2], group=10)\n\n        # Test grouped-convolution\n        verify_convtranspose((1, 10, 3, 3), (10, 1, 3, 3), (1, 5, 7, 3), [1, 2, 1, 2], group=5)\n\n    def repeat(num, dims):\n        return tuple(num for _ in range(dims))\n\n    # Once onnxruntime update is complete\n    for dims in [1, 2, 3]:\n        # Convolution with padding\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            2 * repeat(1, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n        )\n        # Convolution without padding\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            2 * repeat(0, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n        )\n        # Convolution with unset padding\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            2 * repeat(0, dims),\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            True,\n        )\n        # Convolution with autopadding\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            None,\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            auto_pad=\"SAME_UPPER\",\n        )\n        # Convolution with valid autopadding\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            None,\n            repeat(3, dims),\n            repeat(1, dims),\n            repeat(1, dims),\n            auto_pad=\"VALID\",\n        )\n        # Convolution with non uniform stride\n        verify_convtranspose_with_padding(\n            (1, 1) + repeat(5, dims),\n            (1, 1) + repeat(3, dims),\n            None,\n            repeat(3, dims),\n            repeat(2, dims),\n            repeat(1, dims),\n            auto_pad=\"SAME_UPPER\",\n        )\n        # Convolution with dilation\n        # TODO(mbrookhart): Relay doesn't currently support convtranspose with dilation\n        # verify_convtranspose_with_padding(\n        #     (1, 1) + repeat(5, D),\n        #     (1, 1) + repeat(3, D),\n        #     2 * repeat(2, D),\n        #     repeat(3, D),\n        #     repeat(1, D),\n        #     repeat(2, D),\n        # )\n\n    # Convolution with output_shape\n    for dims in [1, 2, 3]:\n        for num in range(60, 66):\n            verify_convtranspose_with_output_shape(\n                (1, 1) + repeat(32, dims),\n                (1, 1) + repeat(4, dims),\n                repeat(num, dims),\n                repeat(4, dims),\n                repeat(2, dims),\n                repeat(1, dims),\n            )\n\n            verify_convtranspose_with_output_shape(\n                (1, 1) + repeat(32, dims),\n                (1, 1) + repeat(4, dims),\n                repeat(num, dims),\n                repeat(4, dims),\n                repeat(2, dims),\n                repeat(1, dims),\n                auto_pad=\"SAME_LOWER\",\n            )\n\n\n@tvm.testing.parametrize_targets\ndef test_unsqueeze_constant(target, dev):\n    \"\"\"test_unsqueeze_constant\"\"\"\n\n    class Flatten(Module):\n        def forward(self, input_):\n            return input_.view(input_.size(0), -1)\n\n    with tempfile.NamedTemporaryFile() as f:\n        file_name = f.name\n        input_size = (1, 16, 32, 32)\n        dummy_input = torch.randn(*input_size)\n        layer = Sequential(Flatten(), Linear(16 * 32 * 32, 64))\n        torch.onnx.export(layer, dummy_input, file_name, export_params=True)\n\n        onnx_model = onnx.load(file_name)\n        relay.frontend.from_onnx(onnx_model, {\"onnx::Reshape_0\": input_size})\n\n\n@tvm.testing.parametrize_targets\ndef test_pooling(target, dev):\n    \"\"\"test_pooling\"\"\"\n\n    def verify_pooling(x_shape, kernel_shape, strides, pads, out_shape, mode, auto_pad=\"NOTSET\"):\n        _ = np.random.uniform(size=x_shape).astype(\"float32\")\n\n        if mode == \"max\":\n            node_type = \"MaxPool\"\n        elif mode == \"average\":\n            node_type = \"AveragePool\"\n        else:\n            raise ValueError(f\"Pool method {mode} is not supported.\")\n\n        pool_node = helper.make_node(\n            node_type, inputs=[\"x\"], outputs=[\"y\"], kernel_shape=kernel_shape, strides=strides\n        )\n\n        if pads is None:\n            pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n        else:\n            pad_attr = helper.make_attribute(\"pads\", pads)\n        pool_node.attribute.append(pad_attr)\n\n        if mode == \"max\":\n            storage_attr = helper.make_attribute(\"storage_order\", 0)\n            pool_node.attribute.append(storage_attr)\n\n        graph = helper.make_graph(\n            [pool_node],\n            \"pooling_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"pooling_test\")\n        verify_with_ort(\n            model,\n            [x_shape],\n            [out_shape],\n            use_vm=False,\n            target=target,\n            dev=dev,\n        )\n\n    for mode in [\"max\", \"average\"]:\n        # Pool1D\n        verify_pooling(\n            x_shape=[1, 1, 32],\n            kernel_shape=[3],\n            strides=[1],\n            pads=[1, 1],\n            out_shape=[1, 1, 32],\n            mode=mode,\n        )\n        # Pool2D\n        verify_pooling(\n            x_shape=[1, 1, 32, 32],\n            kernel_shape=[3, 3],\n            strides=[1, 1],\n            pads=[1, 1, 1, 1],\n            out_shape=[1, 1, 32, 32],\n            mode=mode,\n        )\n\n        # Pool1D with stride\n        verify_pooling(\n            x_shape=[1, 1, 32],\n            kernel_shape=[3],\n            strides=[2],\n            pads=[1, 1],\n            out_shape=[1, 1, 16],\n            mode=mode,\n        )\n        # Pool2D with stride\n        verify_pooling(\n            x_shape=[1, 1, 32, 32],\n            kernel_shape=[3, 3],\n            strides=[2, 2],\n            pads=[1, 1, 1, 1],\n            out_shape=[1, 1, 16, 16],\n            mode=mode,\n        )\n\n        # Pool1D with stride and autopadding\n        verify_pooling(\n            x_shape=[1, 1, 32],\n            kernel_shape=[3],\n            strides=[2],\n            pads=None,\n            out_shape=[1, 1, 16],\n            mode=mode,\n            auto_pad=\"SAME_UPPER\",\n        )\n        # Pool2D with stride and autopadding\n        verify_pooling(\n            x_shape=[1, 1, 32, 32],\n            kernel_shape=[3, 3],\n            strides=[2, 2],\n            pads=None,\n            out_shape=[1, 1, 16, 16],\n            mode=mode,\n            auto_pad=\"SAME_UPPER\",\n        )\n\n        # Pool3D with stride\n        verify_pooling(\n            x_shape=[1, 1, 32, 32, 32],\n            kernel_shape=[3, 3, 3],\n            strides=[2, 2, 2],\n            pads=[1, 1, 1, 1, 1, 1],\n            out_shape=[1, 1, 16, 16, 16],\n            mode=mode,\n        )\n\n        # Pool3D with stride and autopadding\n        verify_pooling(\n            x_shape=[1, 1, 32, 32, 32],\n            kernel_shape=[3, 3, 3],\n            strides=[2, 2, 2],\n            pads=None,\n            out_shape=[1, 1, 16, 16, 16],\n            mode=mode,\n            auto_pad=\"SAME_UPPER\",\n        )\n\n\n@tvm.testing.parametrize_targets\ndef test_global_pooling(target, dev):\n    \"\"\"test_global_pooling\"\"\"\n\n    def verify_global_pooling(x_shape, mode):\n        out_shape = x_shape[:2] + [1] * (len(x_shape) - 2)\n\n        if mode == \"max\":\n            node_type = \"GlobalMaxPool\"\n        elif mode == \"average\":\n            node_type = \"GlobalAveragePool\"\n        else:\n            raise ValueError(f\"Pool method {mode} is not supported.\")\n\n        pool_node = helper.make_node(node_type, inputs=[\"x\"], outputs=[\"y\"])\n\n        graph = helper.make_graph(\n            [pool_node],\n            \"global_pooling_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"global_pooling_test\")\n        verify_with_ort(\n            model,\n            [x_shape],\n            [out_shape],\n            use_vm=False,\n            target=target,\n            dev=dev,\n        )\n\n    # Test each pooling mode across all N-D inputs.\n    for mode in [\"average\", \"max\"]:\n        # 1D Pooling (NCW)\n        verify_global_pooling([1, 8, 8], mode)\n        verify_global_pooling([4, 1, 4], mode)\n        # 2D Pooling (NCHW)\n        verify_global_pooling([1, 8, 8, 8], mode)\n        verify_global_pooling([4, 1, 6, 4], mode)\n        # 3D Pooling (NCDHW)\n        verify_global_pooling([1, 8, 6, 8, 8], mode)\n        verify_global_pooling([4, 1, 2, 6, 4], mode)\n\n\n@pytest.mark.skip(\"flaky\")\n@tvm.testing.parametrize_targets\ndef test_qlinear_average_pool(target, dev):\n    \"\"\"test_qlinear_average_pool\"\"\"\n\n    def verify_qlinear_average_pool(\n        x_shape, kernel_shape, strides, pads, out_shape, auto_pad=\"NOTSET\"\n    ):\n        input_nodes = [\n            helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape)),\n        ]\n\n        output_nodes = [\n            helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(out_shape)),\n        ]\n\n        input_names = [\"X\"]\n\n        node = helper.make_node(\n            \"AveragePool\",\n            inputs=input_names,\n            outputs=[\"Y\"],\n            kernel_shape=kernel_shape,\n            strides=strides,\n        )\n\n        if pads is None:\n            pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n        else:\n            pad_attr = helper.make_attribute(\"pads\", pads)\n        node.attribute.append(pad_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"qlinear_average_pool_test\",\n            inputs=input_nodes,\n            outputs=output_nodes,\n        )\n\n        model = helper.make_model(graph, producer_name=\"qlinear_average_pool_Test\")\n        quantize_and_verify_with_ort(model, input_names, [x_shape], target, dev)\n\n    # Pool1D\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32],\n        kernel_shape=[3],\n        strides=[1],\n        pads=[1, 1],\n        out_shape=[1, 1, 32],\n    )\n    # Pool2D\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        strides=[1, 1],\n        pads=[1, 1, 1, 1],\n        out_shape=[1, 1, 32, 32],\n    )\n\n    # Pool1D with stride\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32],\n        kernel_shape=[3],\n        strides=[2],\n        pads=[1, 1],\n        out_shape=[1, 1, 16],\n    )\n    # Pool2D with stride\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        strides=[2, 2],\n        pads=[1, 1, 1, 1],\n        out_shape=[1, 1, 16, 16],\n    )\n\n    # Pool1D with stride and autopadding\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32],\n        kernel_shape=[3],\n        strides=[2],\n        pads=None,\n        out_shape=[1, 1, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Pool2D with stride and autopadding\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        strides=[2, 2],\n        pads=None,\n        out_shape=[1, 1, 16, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n\n    # Pool3D with stride\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32, 32, 32],\n        kernel_shape=[3, 3, 3],\n        strides=[2, 2, 2],\n        pads=[1, 1, 1, 1, 1, 1],\n        out_shape=[1, 1, 16, 16, 16],\n    )\n\n    # Pool3D with stride and autopadding\n    verify_qlinear_average_pool(\n        x_shape=[1, 1, 32, 32, 32],\n        kernel_shape=[3, 3, 3],\n        strides=[2, 2, 2],\n        pads=None,\n        out_shape=[1, 1, 16, 16, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_qlinear_global_average_pool(target, dev):\n    \"\"\"test_qlinear_global_average_pool\"\"\"\n\n    def verify_qlinear_global_average_pool(x_shape):\n        out_shape = x_shape[:2] + [1] * (len(x_shape) - 2)\n\n        node_type = \"GlobalAveragePool\"\n\n        input_names = [\"X\"]\n\n        pool_node = helper.make_node(node_type, inputs=input_names, outputs=[\"Y\"])\n\n        graph = helper.make_graph(\n            [pool_node],\n            \"qlinear_global_average_pool_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape))],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"qlinear_global_average_pool_test\")\n        quantize_and_verify_with_ort(model, input_names, [x_shape], target, dev)\n\n    # 1D Pooling (NCW)\n    verify_qlinear_global_average_pool([1, 8, 8])\n    verify_qlinear_global_average_pool([4, 1, 4])\n\n    # 2D Pooling (NCHW)\n    verify_qlinear_global_average_pool([1, 8, 8, 8])\n    verify_qlinear_global_average_pool([4, 1, 6, 4])\n\n    # 3D Pooling (NCDHW)\n    verify_qlinear_global_average_pool([1, 8, 6, 8, 8])\n    verify_qlinear_global_average_pool([4, 1, 2, 6, 4])\n\n\n@tvm.testing.parametrize_targets\ndef test_mod(target, dev):\n    \"\"\"test_mod\"\"\"\n\n    def verify_mod(x_shape, y_shape, fmod, out_shape, dtype=\"float32\"):\n        x_np = np.random.uniform(-100.0, 100.0, x_shape).astype(dtype)\n        y_np = np.random.uniform(-100.0, 100.0, y_shape).astype(dtype)\n        y_np = np.where(y_np == 0, 1, y_np)  # remove 0's to avoid division by zero error\n\n        mod_node = helper.make_node(\"Mod\", inputs=[\"x\", \"y\"], outputs=[\"z\"], fmod=fmod)\n\n        onnx_dtype = TensorProto.FLOAT if dtype == \"float32\" else TensorProto.INT32\n        graph = helper.make_graph(\n            [mod_node],\n            \"mod_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", onnx_dtype, list(x_shape)),\n                helper.make_tensor_value_info(\"y\", onnx_dtype, list(y_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"z\", onnx_dtype, list(out_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"mod_test\")\n        verify_with_ort_with_inputs(model, [x_np, y_np], [out_shape], target=target, dev=dev)\n\n    # Mod\n    verify_mod(\n        x_shape=[1, 32, 32], y_shape=[1, 1, 32], fmod=0, out_shape=(1, 32, 32), dtype=\"int32\"\n    )\n    verify_mod(\n        x_shape=[1, 32, 32, 32],\n        y_shape=[1, 32, 32, 32],\n        fmod=0,\n        out_shape=(1, 32, 32, 32),\n        dtype=\"int32\",\n    )\n\n    # fmod\n    verify_mod(\n        x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=1, out_shape=(1, 32, 32), dtype=\"int32\"\n    )\n    verify_mod(x_shape=[1, 1, 32, 32], y_shape=[1, 32, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n    verify_mod(x_shape=[1, 32, 32, 32], y_shape=[1, 1, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n    verify_mod(\n        x_shape=[1, 32, 32, 32],\n        y_shape=[1, 32, 32, 32],\n        fmod=1,\n        out_shape=(1, 32, 32, 32),\n        dtype=\"int32\",\n    )\n    verify_mod(x_shape=[1, 32, 32, 32], y_shape=[1, 32, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n\n\n@tvm.testing.parametrize_targets\ndef test_xor(target, dev):\n    \"\"\"test_xor\"\"\"\n\n    def verify_xor(x_shape, y_shape):\n        x_np = np.random.choice(a=[False, True], size=x_shape).astype(\"bool\")\n        y_np = np.random.choice(a=[False, True], size=y_shape).astype(\"bool\")\n\n        np_out = np.logical_xor(x_np, y_np)\n        out_shape = np_out.shape\n\n        xor_node = helper.make_node(\"Xor\", inputs=[\"x\", \"y\"], outputs=[\"z\"])\n\n        onnx_dtype = TensorProto.BOOL\n        graph = helper.make_graph(\n            [xor_node],\n            \"xor_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", onnx_dtype, list(x_shape)),\n                helper.make_tensor_value_info(\"y\", onnx_dtype, list(y_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"z\", onnx_dtype, list(out_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"xor_test\")\n        verify_with_ort_with_inputs(model, [x_np, y_np], [out_shape], target=target, dev=dev)\n\n    # XOR\n    verify_xor(x_shape=[1, 32, 32], y_shape=[1, 32, 32])\n\n    # Xor broadcast\n    verify_xor(x_shape=[1, 32, 32], y_shape=[1, 1, 32])\n\n\n@tvm.testing.parametrize_targets\ndef test_max_roi_pool(target, dev):\n    \"\"\"test_max_roi_pool\"\"\"\n\n    def verify_max_roi_pool(x_shape, rois_shape, pooled_shape, spatial_scale, out_shape):\n        if spatial_scale is None:\n            pool_node = helper.make_node(\n                \"MaxRoiPool\", inputs=[\"x\", \"rois\"], outputs=[\"y\"], pooled_shape=pooled_shape\n            )\n        else:\n            pool_node = helper.make_node(\n                \"MaxRoiPool\",\n                inputs=[\"x\", \"rois\"],\n                outputs=[\"y\"],\n                pooled_shape=pooled_shape,\n                spatial_scale=spatial_scale,\n            )\n\n        graph = helper.make_graph(\n            [pool_node],\n            \"pool_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n                helper.make_tensor_value_info(\"rois\", TensorProto.FLOAT, list(rois_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"pool_test\")\n        verify_with_ort(model, [x_shape, rois_shape], [out_shape], target=target, dev=dev)\n\n    verify_max_roi_pool(\n        x_shape=[1, 3, 6, 6],\n        rois_shape=[3, 5],\n        pooled_shape=[1, 1],\n        spatial_scale=None,\n        out_shape=[3, 3, 1, 1],\n    )\n\n    verify_max_roi_pool(\n        x_shape=[1, 3, 10, 10],\n        rois_shape=[4, 5],\n        pooled_shape=[2, 2],\n        spatial_scale=2.0,\n        out_shape=[4, 3, 2, 2],\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_lppool(target, dev):\n    \"\"\"test_lppool\"\"\"\n\n    def verify_lppool(x_shape, kernel_shape, p, strides, pads, out_shape, auto_pad=\"NOTSET\"):\n        kwargs = {}\n        if p is not None:\n            kwargs[\"p\"] = p\n        if pads is None:\n            pool_node = helper.make_node(\n                \"LpPool\",\n                inputs=[\"x\"],\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                auto_pad=auto_pad,\n                strides=strides,\n                **kwargs,\n            )\n        else:\n            pool_node = helper.make_node(\n                \"LpPool\",\n                inputs=[\"x\"],\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                pads=pads,\n                strides=strides,\n                **kwargs,\n            )\n\n        graph = helper.make_graph(\n            [pool_node],\n            \"lppool_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"lppool_test\")\n        verify_with_ort(\n            model,\n            [x_shape],\n            [out_shape],\n            use_vm=True,\n            target=target,\n            dev=dev,\n        )\n\n    # Pool1D\n    verify_lppool(\n        x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[1], pads=[1, 1], out_shape=[1, 1, 32]\n    )\n\n    # Pool2D\n    verify_lppool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        p=2,\n        strides=[1, 1],\n        pads=[1, 1, 1, 1],\n        out_shape=[1, 1, 32, 32],\n    )\n\n    # Pool1D with stride\n    verify_lppool(\n        x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=[1, 1], out_shape=[1, 1, 16]\n    )\n\n    # Pool2D with stride\n    verify_lppool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        p=2,\n        strides=[2, 2],\n        pads=[1, 1, 1, 1],\n        out_shape=[1, 1, 16, 16],\n    )\n\n    # Pool1D with stride and autopadding\n    verify_lppool(\n        x_shape=[1, 1, 32],\n        kernel_shape=[3],\n        p=2,\n        strides=[2],\n        pads=None,\n        out_shape=[1, 1, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n\n    # Pool2D with stride and autopadding\n    verify_lppool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        p=2,\n        strides=[2, 2],\n        pads=None,\n        out_shape=[1, 1, 16, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n\n    # Pool3D with stride\n    verify_lppool(\n        x_shape=[1, 1, 32, 32, 32],\n        kernel_shape=[3, 3, 3],\n        p=2,\n        strides=[2, 2, 2],\n        pads=[1, 1, 1, 1, 1, 1],\n        out_shape=[1, 1, 16, 16, 16],\n    )\n\n    # Pool3D with stride and autopadding\n    verify_lppool(\n        x_shape=[1, 1, 32, 32, 32],\n        kernel_shape=[3, 3, 3],\n        p=2,\n        strides=[2, 2, 2],\n        pads=None,\n        out_shape=[1, 1, 16, 16, 16],\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Pool2D with empty p\n    verify_lppool(\n        x_shape=[1, 1, 32, 32],\n        kernel_shape=[3, 3],\n        p=None,\n        strides=[1, 1],\n        pads=[1, 1, 1, 1],\n        out_shape=[1, 1, 32, 32],\n    )\n\n\ndef verify_global_lppool(x_shape, p, out_shape, target, dev):\n    \"\"\"verify_global_lppool\"\"\"\n    pool_node = helper.make_node(\n        \"GlobalLpPool\",\n        inputs=[\"x\"],\n        outputs=[\"y\"],\n        p=p,\n    )\n\n    graph = helper.make_graph(\n        [pool_node],\n        \"global_lppool_test\",\n        inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n        outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n    )\n\n    model = helper.make_model(graph, producer_name=\"global_lppool_test\")\n    verify_with_ort(model, [x_shape], out_shape, use_vm=True, target=target, dev=dev)\n\n\n@tvm.testing.parametrize_targets\ndef test_global_lppool(target, dev):\n    \"\"\"test_global_lppool\"\"\"\n    # LpPool1D\n    verify_global_lppool(x_shape=[1, 15, 16], p=2, out_shape=[1, 15, 1], target=target, dev=dev)\n\n    # LpPool2D\n    verify_global_lppool(\n        x_shape=[1, 15, 32, 32], p=2, out_shape=[1, 15, 1, 1], target=target, dev=dev\n    )\n\n    # LpPool2D\n    verify_global_lppool(\n        x_shape=[1, 15, 32, 32], p=3, out_shape=[1, 15, 1, 1], target=target, dev=dev\n    )\n\n    # LpPool3D\n    verify_global_lppool(\n        x_shape=[1, 15, 3, 32, 32], p=2, out_shape=[1, 15, 1, 1, 1], target=target, dev=dev\n    )\n\n\ndef verify_rnn(\n    seq_length,\n    batch_size,\n    input_size,\n    hidden_size,\n    rnn_type=\"LSTM\",\n    use_bias=False,\n    activations=None,\n    alphas=None,\n    betas=None,\n    use_initial_state=False,\n    use_peep=False,\n    linear_before_reset=False,\n    directions=1,\n    layout=0,\n    rtol=1e-5,\n    atol=1e-5,\n    target=None,\n    dev=None,\n):\n    \"\"\"verify_rnn\"\"\"\n    if rnn_type == \"RNN\":\n        multiplier = 1\n    elif rnn_type == \"LSTM\":\n        multiplier = 4\n    elif rnn_type == \"GRU\":\n        multiplier = 3\n    else:\n        raise NotImplementedError(f\"{rnn_type} RNNs not yet supported.\")\n\n    if directions not in [1, 2]:\n        raise ValueError(f\"Direction should be either 1 or 2 (for bidirectional LSTMs)\")\n\n    def get_inputs():\n        input_names = []\n        input_values = []\n        input_tensors = []\n\n        def register(np_arr, name, shape=None):\n            input_values.append(np_arr)\n            input_names.append(name)\n\n            # Map of numpy dtypes to the protobuf equivalent\n            dtype_map = {\n                \"float32\": TensorProto.FLOAT,\n                \"int32\": TensorProto.INT32,\n                \"int8\": TensorProto.INT8,\n            }\n\n            if np_arr.dtype.name not in dtype_map:\n                raise ValueError(f\"Unknown dtype we don't know how to handle {np.dtype.name}\")\n            if shape is None:\n                shape = list(np_arr.shape)\n            proto_type = dtype_map[np_arr.dtype.name]\n            input_tensors.append(helper.make_tensor_value_info(name, proto_type, shape))\n\n        if layout == 1:\n            x_np = np.random.uniform(size=(batch_size, seq_length, input_size)).astype(\"float32\")\n        else:\n            x_np = np.random.uniform(size=(seq_length, batch_size, input_size)).astype(\"float32\")\n        w_np = np.random.uniform(size=(directions, multiplier * hidden_size, input_size)).astype(\n            \"float32\"\n        )\n        r_np = np.random.uniform(size=(directions, multiplier * hidden_size, hidden_size)).astype(\n            \"float32\"\n        )\n        register(x_np, \"X\")\n        register(w_np, \"W\")\n        register(r_np, \"R\")\n\n        if use_bias:\n            b_np = np.random.uniform(size=(directions, multiplier * 2 * hidden_size)).astype(\n                \"float32\"\n            )\n            register(b_np, \"B\")\n\n        if use_initial_state:\n            assert use_bias is True, \"Initial states must have bias specified.\"\n            sequence_np = np.repeat(seq_length, batch_size).astype(\"int32\")\n            register(sequence_np, \"sequence_lens\")\n\n            if layout == 1:\n                initial_h_np = np.random.uniform(size=(batch_size, directions, hidden_size)).astype(\n                    \"float32\"\n                )\n            else:\n                initial_h_np = np.random.uniform(size=(directions, batch_size, hidden_size)).astype(\n                    \"float32\"\n                )\n            register(initial_h_np, \"initial_h\")\n\n            if rnn_type == \"LSTM\":\n                if layout == 1:\n                    initial_c_np = np.random.uniform(\n                        size=(batch_size, directions, hidden_size)\n                    ).astype(\"float32\")\n                else:\n                    initial_c_np = np.random.uniform(\n                        size=(directions, batch_size, hidden_size)\n                    ).astype(\"float32\")\n                register(initial_c_np, \"initial_c\")\n\n        if use_peep and rnn_type == \"LSTM\":\n            assert use_initial_state is True, \"Peepholes require initial state to be specified.\"\n            p_np = np.random.uniform(size=(directions, 3 * hidden_size)).astype(\"float32\")\n            register(p_np, \"P\")\n\n        return input_names, input_tensors, input_values\n\n    input_names, input_tensors, input_values = get_inputs()\n\n    def get_outputs():\n        output_names = []\n        graph_outputs = []\n        output_shapes = []\n\n        def register(name, shape, proto_type):\n            output_names.append(name)\n            graph_outputs.append(helper.make_tensor_value_info(name, proto_type, list(shape)))\n            output_shapes.append(list(shape))\n\n        if layout == 1:\n            register(\"Y\", [directions, seq_length, batch_size, hidden_size], TensorProto.FLOAT)\n            register(\"Y_h\", [batch_size, directions, hidden_size], TensorProto.FLOAT)\n        else:\n            register(\"Y\", [seq_length, directions, batch_size, hidden_size], TensorProto.FLOAT)\n            register(\"Y_h\", [directions, batch_size, hidden_size], TensorProto.FLOAT)\n\n        if rnn_type == \"LSTM\":\n            if layout == 1:\n                register(\"Y_c\", [batch_size, directions, hidden_size], TensorProto.FLOAT)\n            else:\n                register(\"Y_c\", [directions, batch_size, hidden_size], TensorProto.FLOAT)\n\n        return output_names, graph_outputs, output_shapes\n\n    output_names, graph_outputs, output_shapes = get_outputs()\n\n    rnn_node = helper.make_node(\n        rnn_type, inputs=input_names, outputs=output_names, hidden_size=hidden_size\n    )\n    if activations is not None:\n        activations_attr = helper.make_attribute(\"activations\", activations)\n        rnn_node.attribute.append(activations_attr)\n    if directions == 2:\n        direction_attr = helper.make_attribute(\"direction\", \"bidirectional\")\n        rnn_node.attribute.append(direction_attr)\n    if alphas is not None:\n        alphas_attr = helper.make_attribute(\"activation_alpha\", alphas)\n        rnn_node.attribute.append(alphas_attr)\n    if betas is not None:\n        betas_attr = helper.make_attribute(\"activation_beta\", betas)\n        rnn_node.attribute.append(betas_attr)\n    if linear_before_reset and rnn_type == \"GRU\":\n        lbr_attr = helper.make_attribute(\"linear_before_reset\", 1)\n        rnn_node.attribute.append(lbr_attr)\n    if layout == 1:\n        layout_attr = helper.make_attribute(\"layout\", 1)\n        rnn_node.attribute.append(layout_attr)\n\n    graph = helper.make_graph([rnn_node], \"rnn_test\", inputs=input_tensors, outputs=graph_outputs)\n\n    model = helper.make_model(graph, producer_name=\"rnn_test\")\n\n    verify_with_ort_with_inputs(\n        model, input_values, output_shapes, atol=atol, rtol=rtol, target=target, dev=dev\n    )\n\n\ndef verify_rnn_helper(target, dev, rnn_type):\n    num_activations = 1\n    if rnn_type == \"GRU\":\n        num_activations = 2\n    elif rnn_type == \"LSTM\":\n        num_activations = 3\n\n    for directions in [1, 2]:\n        # No bias.\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=16,\n            hidden_size=32,\n            use_bias=False,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # large batch.\n        verify_rnn(\n            seq_length=4,\n            batch_size=8,\n            input_size=16,\n            hidden_size=32,\n            use_bias=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # Non power of two.\n        verify_rnn(\n            seq_length=3,\n            batch_size=3,\n            input_size=16,\n            hidden_size=40,\n            use_bias=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # Long sequence.\n        verify_rnn(\n            seq_length=8,\n            batch_size=1,\n            input_size=16,\n            hidden_size=32,\n            use_bias=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # Large hidden.\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=16,\n            hidden_size=128,\n            use_bias=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # Large input.\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=64,\n            hidden_size=32,\n            use_bias=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n\n        # Different activation testing.\n        # Default value hardsigmoid.\n        # TODO: onnxruntime <= v1.12.0 has wrong default value of all activation functions\n        if rnn_type != \"RNN\":\n            activations = [\"HardSigmoid\", \"Tanh\", \"Tanh\"][0:num_activations] * directions\n            verify_rnn(\n                seq_length=2,\n                batch_size=1,\n                input_size=16,\n                hidden_size=32,\n                use_bias=False,\n                activations=activations,\n                rnn_type=rnn_type,\n                directions=directions,\n                target=target,\n                dev=dev,\n            )\n        # Multiple parametrized activations.\n        activations = [\"HardSigmoid\", \"LeakyRelu\", \"Tanh\"][0:num_activations] * directions\n        alphas = [2.0, 0.5, 0.0][0:num_activations] * directions\n        betas = [0.3, 0.0, 0.0][0:num_activations] * directions\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=16,\n            hidden_size=32,\n            use_bias=False,\n            activations=activations,\n            alphas=alphas,\n            betas=betas,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n        # All parametrized with new Affine activation.\n        activations = [\"Affine\", \"LeakyRelu\", \"HardSigmoid\"][0:num_activations] * directions\n        alphas = [0.8, 2.0, 0.5][0:num_activations] * directions\n        betas = [0.0, 0.3, 0.0][0:num_activations] * directions\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=16,\n            hidden_size=32,\n            use_bias=False,\n            activations=activations,\n            alphas=alphas,\n            betas=betas,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n\n        # Testing with initial state\n        verify_rnn(\n            seq_length=2,\n            batch_size=1,\n            input_size=16,\n            hidden_size=32,\n            use_bias=True,\n            use_initial_state=True,\n            rnn_type=rnn_type,\n            directions=directions,\n            target=target,\n            dev=dev,\n        )\n\n        # Testing layout\n        # TODO: onnxruntime <= 1.12.0 doesn't support layout == 1\n        # verify_rnn(\n        #     seq_length=2,\n        #     batch_size=1,\n        #     input_size=16,\n        #     hidden_size=32,\n        #     use_bias=True,\n        #     rnn_type=\"RNN\",\n        #     directions=directions,\n        #     layout=1,\n        #     target=target,\n        #     dev=dev,\n        # )\n\n        # Testing with peepholes\n        if rnn_type == \"LSTM\":\n            verify_rnn(\n                seq_length=2,\n                batch_size=1,\n                input_size=16,\n                hidden_size=32,\n                use_bias=True,\n                use_initial_state=True,\n                use_peep=True,\n                rnn_type=\"LSTM\",\n                directions=directions,\n                target=target,\n                dev=dev,\n            )\n\n\n@tvm.testing.parametrize_targets\ndef test_rnn(target, dev):\n    verify_rnn_helper(target, dev, \"RNN\")\n\n\n@tvm.testing.parametrize_targets\ndef test_lstm(target, dev):\n    verify_rnn_helper(target, dev, \"LSTM\")\n\n\n@tvm.testing.parametrize_targets\ndef test_gru(target, dev):\n    verify_rnn_helper(target, dev, \"GRU\")\n\n\n@tvm.testing.parametrize_targets\ndef test_resize(target, dev):\n    \"\"\"test_resize\"\"\"\n\n    def verify(ishape, oshape, scales, mode, coord_trans=\"asymmetric\", alpha=0.5, exclude=False):\n        nodes = [\n            make_constant_node(\"roi\", onnx.TensorProto.FLOAT, (0,), []),\n            make_constant_node(\"scales\", onnx.TensorProto.FLOAT, (len(scales),), scales),\n        ]\n        input_names = [\"X\", \"roi\", \"scales\"]\n\n        if oshape != []:\n            nodes.append(\n                make_constant_node(\"sizes\", onnx.TensorProto.INT64, (len(oshape),), oshape)\n            )\n            input_names.append(\"sizes\")\n        nodes.append(\n            helper.make_node(\n                \"Resize\",\n                inputs=input_names,\n                outputs=[\"Y\"],\n                mode=mode,\n                coordinate_transformation_mode=coord_trans,\n                cubic_coeff_a=alpha,\n                exclude_outside=exclude,\n            )\n        )\n\n        if oshape == []:\n            oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)]\n        graph = helper.make_graph(\n            nodes,\n            \"resize_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, ishape)],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, oshape)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"resize_test\")\n\n        verify_with_ort(\n            model,\n            [ishape],\n            [oshape],\n            use_vm=True,\n            opset=11,\n            freeze_params=True,\n            target=target,\n            dev=dev,\n        )\n\n    for ndim in [1, 2, 3]:\n        method = \"nearest\"\n        for coord_trans in [\"asymmetric\", \"align_corners\", \"half_pixel\"]:\n            # upsampling\n            verify([1, 16] + [32] * ndim, [1, 16] + [64] * ndim, [], method, coord_trans)\n            # downsampling\n            verify([1, 16] + [32] * ndim, [1, 16] + [16] * ndim, [], method, coord_trans)\n            # scales are specified instead of sizes\n            verify([1, 16] + [32] * ndim, [], [1, 1] + [0.5] * ndim, method, coord_trans)\n            verify([1, 16] + [32] * ndim, [], [1, 1] + [2] * ndim, method, coord_trans)\n\n        method = \"linear\"\n        # upsampling\n        verify([1, 16] + [32] * ndim, [1, 16] + [64] * ndim, [], method)\n        # downsampling\n        verify([1, 16] + [32] * ndim, [1, 16] + [16] * ndim, [], method)\n        # scales are specified instead of sizes\n        verify([1, 16] + [32] * ndim, [], [1, 1] + [0.5] * ndim, method)\n        verify([1, 16] + [32] * ndim, [], [1, 1] + [2] * ndim, method)\n\n        if ndim == 2:\n            # ONNX Runtime only supports cubic interpolation for 2D images\n            method = \"cubic\"\n            for alpha in [0.5, 0.75]:\n                for exclude in [True, False]:\n                    # upsampling\n                    verify(\n                        [1, 16] + [32] * ndim,\n                        [1, 16] + [64] * ndim,\n                        [],\n                        method,\n                        alpha=alpha,\n                        exclude=exclude,\n                    )\n                    # downsampling\n                    verify(\n                        [1, 16] + [32] * ndim,\n                        [1, 16] + [16] * ndim,\n                        [],\n                        method,\n                        alpha=alpha,\n                        exclude=exclude,\n                    )\n                    # scales are specified instead of sizes\n                    verify(\n                        [1, 16] + [32] * ndim,\n                        [],\n                        [1, 1] + [0.5] * ndim,\n                        method,\n                        alpha=alpha,\n                        exclude=exclude,\n                    )\n                    verify(\n                        [1, 16] + [32] * ndim,\n                        [],\n                        [1, 1] + [2] * ndim,\n                        method,\n                        alpha=alpha,\n                        exclude=exclude,\n                    )\n\n    def verify_opset_10(ishape, scales, mode):\n        nodes = [\n            make_constant_node(\"scales\", onnx.TensorProto.FLOAT, (len(scales),), scales),\n        ]\n        input_names = [\"X\", \"scales\"]\n        nodes.append(\n            helper.make_node(\n                \"Resize\",\n                inputs=input_names,\n                outputs=[\"Y\"],\n                mode=mode,\n            )\n        )\n\n        oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)]\n        graph = helper.make_graph(\n            nodes,\n            \"resize_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, ishape)],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, oshape)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"resize_test\")\n        verify_with_ort(\n            model,\n            [ishape],\n            [oshape],\n            use_vm=True,\n            freeze_params=True,\n            opset=10,\n            target=target,\n            dev=dev,\n        )\n\n    verify_opset_10([1, 16, 32, 32], [1, 1, 2, 2], \"nearest\")\n    verify_opset_10([1, 16, 32, 32], [1, 1, 0.5, 0.5], \"linear\")\n\n\n@tvm.testing.parametrize_targets\ndef test_nonzero(target, dev):\n    \"\"\"test_nonzero\"\"\"\n\n    def verify_nonzero(indata, outdata, dtype):\n        node = helper.make_node(\n            \"NonZero\",\n            inputs=[\"X\"],\n            outputs=[\"Y\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"nonzero_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.INT64, list(indata.shape))],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, list(outdata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"nonzero_test\")\n\n        verify_with_ort_with_inputs(\n            model, [indata], dtype=\"int64\", use_vm=True, opset=9, target=target, dev=dev\n        )\n\n    input_data = np.array([[1, 0], [1, 1]], dtype=np.int64)\n    result = np.array((np.nonzero(input_data)))  # expected output [[0, 1, 1], [0, 0, 1]]\n    verify_nonzero(input_data, result, dtype=np.int64)\n\n    input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64)\n    result = np.array((np.nonzero(input_data)))  # expected output [[0, 1, 2, 2], [0, 1, 0, 1]]\n    verify_nonzero(input_data, result, dtype=np.int64)\n\n\n@tvm.testing.parametrize_targets\ndef test_topk(target, dev):\n    \"\"\"test_topk\"\"\"\n\n    def verify_topk(input_dims, k, axis=-1):\n        output_dims = list(input_dims)\n        output_dims[axis] = k\n\n        node = helper.make_node(\"TopK\", inputs=[\"X\", \"K\"], outputs=[\"Values\", \"Indices\"], axis=axis)\n\n        graph = helper.make_graph(\n            [node],\n            \"topk_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(input_dims)),\n                helper.make_tensor_value_info(\n                    \"K\",\n                    TensorProto.INT64,\n                    [\n                        1,\n                    ],\n                ),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\"Values\", TensorProto.FLOAT, output_dims),\n                helper.make_tensor_value_info(\"Indices\", TensorProto.INT64, output_dims),\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"topk_test\")\n\n        indata = np.random.uniform(-10, 10, input_dims).astype(np.float32)\n        verify_with_ort_with_inputs(\n            model, [indata, np.array([k])], use_vm=True, target=target, dev=dev\n        )\n\n    for n in [12, 32]:\n        for shape in [[n], [n, n], [n, n, n]]:\n            for k in [1, 5, 10]:\n                verify_topk(shape, k)\n\n        verify_topk([n, n, n], 5, 0)\n        verify_topk([n, n, n], 5, 1)\n        verify_topk([n, n, n], 5, 2)\n\n\n@tvm.testing.parametrize_targets\ndef test_roi_align(target, dev):\n    \"\"\"test_roi_align\"\"\"\n\n    def verify_roi_align(\n        input_dims,\n        num_roi,\n        output_height,\n        output_width,\n        sampling_ratio=0,\n        spatial_scale=1.0,\n        mode=\"avg\",\n    ):\n        output_dims = [num_roi, input_dims[1], output_height, output_width]\n\n        node = helper.make_node(\n            \"RoiAlign\",\n            coordinate_transformation_mode=\"output_half_pixel\",\n            inputs=[\"X\", \"rois\", \"batch_indices\"],\n            outputs=[\"Y\"],\n            mode=mode,\n            output_height=output_height,\n            output_width=output_width,\n            sampling_ratio=sampling_ratio,\n            spatial_scale=spatial_scale,\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"roialign_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(input_dims)),\n                helper.make_tensor_value_info(\"rois\", TensorProto.FLOAT, [num_roi, 4]),\n                helper.make_tensor_value_info(\n                    \"batch_indices\",\n                    TensorProto.INT64,\n                    [\n                        num_roi,\n                    ],\n                ),\n            ],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, output_dims)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"roialign_test\")\n\n        np_data = np.random.uniform(size=input_dims).astype(\"float32\")\n        np_rois = np.random.uniform(size=[num_roi, 4]).astype(\"float32\") * input_dims[2]\n        np_batch_indices = np.random.randint(low=0, high=input_dims[0], size=num_roi)\n\n        verify_with_ort_with_inputs(\n            model,\n            [np_data, np_rois, np_batch_indices],\n            out_shape=[output_dims],\n            target=target,\n            dev=dev,\n        )\n\n    verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((4, 4, 16, 32), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((1, 8, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((1, 4, 8, 8), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((1, 4, 16, 16), 16, 5, 7, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((1, 4, 16, 12), 8, 7, 3, sampling_ratio=0, spatial_scale=1.0)\n    verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=0.5)\n    verify_roi_align((3, 4, 12, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.5)\n    verify_roi_align((5, 4, 16, 14), 32, 7, 7, sampling_ratio=1, spatial_scale=1.0)\n    verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=2, spatial_scale=1.0)\n\n    # ONNX implementation of roi_align with max mode is incorrect, so we don't compare outputs here.\n\n\n@tvm.testing.parametrize_targets\ndef test_non_max_suppression(target, dev):\n    \"\"\"test_non_max_suppression\"\"\"\n\n    def verify_nms(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, output_dims\n    ):\n        input_names = [\"boxes\", \"scores\", \"max_output_boxes_per_class\", \"iou_threshold\"]\n        input_nodes = [\n            helper.make_tensor_value_info(\"boxes\", TensorProto.FLOAT, boxes.shape),\n            helper.make_tensor_value_info(\"scores\", TensorProto.FLOAT, scores.shape),\n            helper.make_tensor_value_info(\n                \"max_output_boxes_per_class\", TensorProto.INT64, max_output_boxes_per_class.shape\n            ),\n            helper.make_tensor_value_info(\"iou_threshold\", TensorProto.FLOAT, iou_threshold.shape),\n        ]\n        inputs = [boxes, scores, max_output_boxes_per_class, iou_threshold]\n        if score_threshold is not None:\n            input_names.append(\"score_threshold\")\n            input_nodes.append(\n                helper.make_tensor_value_info(\n                    \"score_threshold\", TensorProto.FLOAT, score_threshold.shape\n                )\n            )\n            inputs.append(score_threshold)\n        node = helper.make_node(\n            \"NonMaxSuppression\",\n            inputs=input_names,\n            outputs=[\"Y\"],\n            center_point_box=0,\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"nms_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, output_dims)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"nms_test\")\n\n        verify_with_ort_with_inputs(model, inputs, use_vm=True, target=target, dev=dev)\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.0, 0.0, 0.5, 0.5],\n                [0.5, 0.5, 0.9, 0.9],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.5, 0.5, 0.95, 0.95],\n                [0.5, 0.5, 0.96, 0.96],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n        ]\n    ).astype(\"float32\")\n\n    scores = np.array(\n        [\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n        ]\n    ).astype(\"float32\")\n    max_output_boxes_per_class = np.array(2).astype(\"int64\")\n    iou_threshold = np.array(0.8).astype(\"float32\")\n    output_dims = [8, 3]\n    verify_nms(boxes, scores, max_output_boxes_per_class, iou_threshold, None, output_dims)\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 1.0, 1.0],\n                [0.0, 0.1, 1.0, 1.1],\n                [0.0, -0.1, 1.0, 0.9],\n                [0.0, 10.0, 1.0, 11.0],\n                [0.0, 10.1, 1.0, 11.1],\n                [0.0, 100.0, 1.0, 101.0],\n            ]\n        ]\n    ).astype(np.float32)\n    scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\n    max_output_boxes_per_class = np.array([3]).astype(np.int64)\n    iou_threshold = np.array([0.5]).astype(np.float32)\n    score_threshold = np.array([0.4]).astype(np.float32)\n    output_dims = [2, 3]\n    verify_nms(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, output_dims\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_loop(target, dev):\n    \"\"\"test_loop\"\"\"\n\n    def verify_cond_loop():\n        y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [1])\n        y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [1])\n        scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [1])\n        cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n        cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n        iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n        y = np.array([-2]).astype(np.float32)\n\n        five_const_node = helper.make_node(\n            \"Constant\",\n            inputs=[],\n            outputs=[\"five\"],\n            value=helper.make_tensor(\n                name=\"const_tensor_five\", data_type=TensorProto.FLOAT, dims=(), vals=[5]\n            ),\n        )\n\n        iter_cast_node = helper.make_node(\n            \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n        )\n\n        y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n        less_node = helper.make_node(\"Less\", inputs=[\"y_out\", \"five\"], outputs=[\"cond_less\"])\n\n        squeeze_node = helper.make_node(\"Squeeze\", inputs=[\"cond_less\"], outputs=[\"cond_squeeze\"])\n\n        cond_cast_node = helper.make_node(\n            \"Cast\", inputs=[\"cond_squeeze\"], outputs=[\"cond_out\"], to=onnx.TensorProto.BOOL\n        )\n\n        scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n        loop_body = helper.make_graph(\n            [\n                five_const_node,\n                iter_cast_node,\n                y_add_node,\n                less_node,\n                squeeze_node,\n                cond_cast_node,\n                scan_identity_node,\n            ],\n            \"loop_body\",\n            [iter_count, cond_in, y_in],\n            [cond_out, y_out, scan_out],\n        )\n\n        loop_node = helper.make_node(\n            \"Loop\",\n            inputs=[\"trip_count\", \"cond\", \"y\"],\n            outputs=[\"res_y\", \"res_scan\"],\n            body=loop_body,\n        )\n\n        trip_count = np.array(5).astype(np.int64)\n        _ = np.array([13]).astype(np.float32)\n        cond = np.array(1).astype(bool)\n        loop_graph = onnx.helper.make_graph(\n            [loop_node],\n            \"loop_outer\",\n            inputs=[\n                onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n                onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n                onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, [1]),\n            ],\n            outputs=[\n                onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, [1]),\n                onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, [5, 1]),\n            ],\n        )\n        loop_model = onnx.helper.make_model(loop_graph)\n\n        # Set a high trip count so that condition trips first.\n        trip_count = np.array(40).astype(np.int64)\n        cond = np.array(1).astype(bool)\n        input_vals = [trip_count, cond, y]\n        verify_with_ort_with_inputs(\n            loop_model,\n            input_vals,\n            use_vm=True,\n            freeze_params=True,\n            opset=11,\n            target=target,\n            dev=dev,\n        )\n\n    def verify_count_loop():\n        y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [])\n        y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [])\n        scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [])\n        cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n        cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n        iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n        y = np.array(-2).astype(np.float32)\n\n        iter_cast_node = helper.make_node(\n            \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n        )\n\n        y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n        identity_node = helper.make_node(\"Identity\", inputs=[\"cond_in\"], outputs=[\"cond_out\"])\n\n        scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n        loop_body = helper.make_graph(\n            [identity_node, iter_cast_node, y_add_node, scan_identity_node],\n            \"loop_body\",\n            [iter_count, cond_in, y_in],\n            [cond_out, y_out, scan_out],\n        )\n\n        loop_node = helper.make_node(\n            \"Loop\",\n            inputs=[\"trip_count\", \"cond\", \"y\"],\n            outputs=[\"res_y\", \"res_scan\"],\n            body=loop_body,\n        )\n\n        trip_count = np.array(5).astype(np.int64)\n        _ = np.array([13]).astype(np.float32)\n        cond = np.array(1).astype(bool)\n        loop_graph = onnx.helper.make_graph(\n            [loop_node],\n            \"loop_outer\",\n            inputs=[\n                onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n                onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n                onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, []),\n            ],\n            outputs=[\n                onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, []),\n                onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, [5]),\n            ],\n        )\n        loop_model = onnx.helper.make_model(loop_graph)\n\n        trip_count = np.array(5).astype(np.int64)\n        cond = np.array(1).astype(bool)\n        input_vals = [trip_count, cond, y]\n        verify_with_ort_with_inputs(\n            loop_model,\n            input_vals,\n            use_vm=True,\n            freeze_params=True,\n            opset=11,\n            target=target,\n            dev=dev,\n        )\n\n    def verify_tensor_loop(shapeless_output=False):\n        y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [3, 3, 3, 3])\n        y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [3, 3, 3, 3])\n        scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [3, 3, 3, 3])\n        cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n        cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n        iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n        y = np.random.normal(size=[3, 3, 3, 3]).astype(np.float32)\n\n        iter_cast_node = helper.make_node(\n            \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n        )\n\n        y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n        identity_node = helper.make_node(\"Identity\", inputs=[\"cond_in\"], outputs=[\"cond_out\"])\n\n        scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n        loop_body = helper.make_graph(\n            [identity_node, iter_cast_node, y_add_node, scan_identity_node],\n            \"loop_body\",\n            [iter_count, cond_in, y_in],\n            [cond_out, y_out, scan_out],\n        )\n\n        loop_node = helper.make_node(\n            \"Loop\",\n            inputs=[\"trip_count\", \"cond\", \"y\"],\n            outputs=[\"res_y\", \"res_scan\"],\n            body=loop_body,\n        )\n\n        trip_count = np.array(5).astype(np.int64)\n        cond = np.array(1).astype(bool)\n\n        # Allow testing of malformed nodes since pytorch likes to create these.\n        if shapeless_output:\n            scan_shape = None\n        else:\n            scan_shape = [5, 3, 3, 3, 3]\n\n        loop_graph = onnx.helper.make_graph(\n            [loop_node],\n            \"loop_outer\",\n            inputs=[\n                onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n                onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n                onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, [3, 3, 3, 3]),\n            ],\n            outputs=[\n                onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, [3, 3, 3, 3]),\n                onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, scan_shape),\n            ],\n        )\n        loop_model = onnx.helper.make_model(loop_graph)\n\n        trip_count = np.array(5).astype(np.int64)\n        cond = np.array(1).astype(bool)\n        input_vals = [trip_count, cond, y]\n        verify_with_ort_with_inputs(\n            loop_model,\n            input_vals,\n            use_vm=True,\n            freeze_params=True,\n            opset=11,\n            target=target,\n            dev=dev,\n        )\n\n    # Test a loop that exits once a condition is met.\n    verify_cond_loop()\n    # Test a loop that exits after a fixed number of iterations with scalar outputs.\n    verify_count_loop()\n    # Test a loop that uses an array output.\n    verify_tensor_loop()\n    # Test a loop that is malformed and has no output shape defined.\n    verify_tensor_loop(shapeless_output=True)\n\n\n@tvm.testing.parametrize_targets\ndef test_if(target, dev):\n    \"\"\"test_if\"\"\"\n\n    def verify_if(cond_array, num_outputs):\n        # Given a bool scalar input cond.\n        # return constant tensor x if cond is True, otherwise return constant tensor y.\n\n        def append_constant_nodes(nodes, outputs, expected, name):\n            outputs.append(onnx.helper.make_tensor_value_info(name, onnx.TensorProto.FLOAT, [5]))\n\n            expected.append(np.random.randn(5).astype(\"float32\"))\n\n            nodes.append(\n                onnx.helper.make_node(\n                    \"Constant\",\n                    inputs=[],\n                    outputs=[name],\n                    value=numpy_helper.from_array(expected[-1]),\n                )\n            )\n\n        if_outputs = []\n        graph_outputs = []\n\n        then_nodes, then_outs, then_expected = [], [], []\n        else_nodes, else_outs, else_expected = [], [], []\n\n        for i in range(num_outputs):\n            append_constant_nodes(then_nodes, then_outs, then_expected, f\"then_out{i}\")\n            append_constant_nodes(else_nodes, else_outs, else_expected, f\"else_out{i}\")\n\n            if_outputs.append(f\"res{i}\")\n            graph_outputs.append(\n                onnx.helper.make_tensor_value_info(f\"res{i}\", onnx.TensorProto.FLOAT, [5]),\n            )\n\n        then_body = onnx.helper.make_graph(then_nodes, \"then_body\", [], then_outs)\n        else_body = onnx.helper.make_graph(else_nodes, \"else_body\", [], else_outs)\n\n        if_node = onnx.helper.make_node(\n            \"If\", inputs=[\"cond\"], outputs=if_outputs, then_branch=then_body, else_branch=else_body\n        )\n\n        if_graph = onnx.helper.make_graph(\n            [if_node],\n            \"if_outer\",\n            inputs=[\n                onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n            ],\n            outputs=graph_outputs,\n        )\n\n        if_model = onnx.helper.make_model(if_graph)\n        if cond_array:\n            cond = np.array([1]).astype(\"bool\")\n        else:\n            cond = np.array(1).astype(\"bool\")\n        correct_out = then_expected if cond else else_expected\n\n        # TODO(jwfromm): Onnxruntime 1.0.0 is buggy with If statements. Replace this with\n        # verify_with_ort once we update versions.\n        tvm_out = get_tvm_output_with_vm(if_model, [cond], target, dev, freeze_params=True)\n        if not isinstance(tvm_out, list):\n            tvm_out = [tvm_out]\n        for i, _ in enumerate(tvm_out):\n            tvm.testing.assert_allclose(\n                correct_out[i],\n                tvm_out[i],  # pylint: disable=unnecessary-list-index-lookup\n                rtol=1e-05,\n                atol=1e-05,\n            )\n\n    # Confirm that if works with cond as an array or scalar.\n    verify_if(cond_array=False, num_outputs=1)\n    verify_if(cond_array=False, num_outputs=2)\n    verify_if(cond_array=True, num_outputs=1)\n    verify_if(cond_array=True, num_outputs=2)\n\n\n@tvm.testing.parametrize_targets\ndef test_size(target, dev):\n    \"\"\"test_size\"\"\"\n\n    def verify_size(indata):\n        node = helper.make_node(\n            \"Size\",\n            inputs=[\"X\"],\n            outputs=[\"Y\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"size_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.INT64, list(indata.shape))],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, [])],\n        )\n\n        model = helper.make_model(graph, producer_name=\"size_test\")\n\n        verify_with_ort_with_inputs(\n            model, [indata], dtype=\"int64\", use_vm=True, opset=11, target=target, dev=dev\n        )\n\n    input_data = np.array([[1, 0], [1, 1]], dtype=np.int64)\n    verify_size(input_data)\n\n    input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64)\n    verify_size(input_data)\n\n\n@tvm.testing.parametrize_targets\ndef test_maxunpool(target, dev):\n    \"\"\"test_maxunpool\"\"\"\n\n    def verify_maxunpool(data, indices, kernel_shape, strides, output_shape=None, pads=None):\n        input_names = [\"xT\", \"xI\"]\n        input_info = [\n            helper.make_tensor_value_info(\"xT\", TensorProto.FLOAT, list(data.shape)),\n            helper.make_tensor_value_info(\"xI\", TensorProto.INT64, list(indices.shape)),\n        ]\n        input_values = [data, indices]\n        if output_shape is not None:\n            input_names.append(\"output_shape\")\n            input_info.append(\n                helper.make_tensor_value_info(\n                    \"output_shape\", TensorProto.INT64, list(output_shape.shape)\n                )\n            )\n            input_values.append(output_shape)\n        else:\n            # Compute expected output shape\n            output_shape = np.asarray(([1, 1] + list(strides))) * np.asarray(list(data.shape))\n            output_shape += np.asarray(([0, 0] + list(kernel_shape))) - np.asarray(\n                ([0, 0] + list(strides))\n            )\n            if pads is not None:\n                output_shape -= np.asarray(\n                    [0, 0] + list(np.sum(np.reshape(list(pads), [-1, 2]), axis=-1))\n                )\n        output_shape = [int(i) for i in output_shape]\n\n        node = helper.make_node(\n            \"MaxUnpool\", inputs=input_names, outputs=[\"y\"], kernel_shape=kernel_shape\n        )\n\n        if pads is not None:\n            pad_attr = helper.make_attribute(\"pads\", pads)\n            node.attribute.append(pad_attr)\n\n        if strides is not None:\n            strides_attr = helper.make_attribute(\"strides\", strides)\n            node.attribute.append(strides_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"maxunpool_test\",\n            inputs=input_info,\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, output_shape)],\n        )\n\n        model = helper.make_model(graph, producer_name=\"size_test\")\n\n        verify_with_ort_with_inputs(\n            model, input_values, use_vm=True, opset=11, target=target, dev=dev\n        )\n\n    # Basic test\n    x_t = np.array([[[[5, 6], [7, 8]]]], dtype=np.float32)\n    x_i = np.array([[[[0, 7], [13, 15]]]], dtype=np.int64)\n    verify_maxunpool(x_t, x_i, [2, 2], strides=[2, 2])\n    # Small stride\n    verify_maxunpool(x_t, x_i, [2, 2], strides=[1, 1])\n    # Big kernel\n    verify_maxunpool(x_t, x_i, [3, 3], strides=[2, 2])\n    # With output shape\n    output_shape = np.array((1, 1, 5, 5), dtype=np.int64)\n    verify_maxunpool(x_t, x_i, [2, 2], strides=[2, 2], output_shape=output_shape)\n    # With explicit reverse padding\n    pads = np.asarray([1, 1, 1, 1]).astype(np.int64)\n    verify_maxunpool(x_t, x_i, [2, 2], strides=[2, 2], pads=pads)\n\n\n@tvm.testing.parametrize_targets\ndef test_softplus(target, dev):\n    \"\"\"test_softplus\"\"\"\n\n    def verify_softplus(indata):\n        node = helper.make_node(\n            \"Softplus\",\n            inputs=[\"X\"],\n            outputs=[\"Y\"],\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"softplus_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(indata.shape))],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(indata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"softplus_test\")\n\n        verify_with_ort_with_inputs(\n            model, [indata], dtype=\"float32\", use_vm=True, opset=11, target=target, dev=dev\n        )\n\n    # Simple case with all signs.\n    input_data = np.array([[-1, 0, 1]], dtype=np.float32)\n    verify_softplus(input_data)\n    # More fancy case.\n    input_data = np.random.randn(1, 32, 32, 3).astype(\"float32\")\n    verify_softplus(input_data)\n\n\n@tvm.testing.parametrize_targets\ndef test_cumsum(target, dev):\n    \"\"\"test_cumsum\"\"\"\n\n    def verify_cumsum(indata, axis, exclusive=0, reverse=0, dtype=\"float32\"):\n        cumsum_node = onnx.helper.make_node(\n            \"CumSum\",\n            inputs=[\"X\", \"axis\"],\n            outputs=[\"Y\"],\n        )\n        if exclusive != 0:\n            exclusive_attr = helper.make_attribute(\"exclusive\", exclusive)\n            cumsum_node.attribute.append(exclusive_attr)\n        if reverse != 0:\n            reverse_attr = helper.make_attribute(\"reverse\", reverse)\n            cumsum_node.attribute.append(reverse_attr)\n        nodes = [\n            make_constant_node(\"axis\", onnx.TensorProto.INT32, [1], [axis]),\n            cumsum_node,\n        ]\n        if dtype == \"float32\":\n            tensor_type = TensorProto.FLOAT\n        else:\n            tensor_type = TensorProto.INT32\n            dtype = \"int32\"\n\n        graph = helper.make_graph(\n            nodes,\n            \"cumsum_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"X\", tensor_type, list(indata.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"Y\", tensor_type, list(indata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"cumsum_test\")\n\n        verify_with_ort_with_inputs(\n            model, [indata], dtype=dtype, use_vm=True, opset=11, target=target, dev=dev\n        )\n\n    data = (\n        np.array(\n            [\n                1.0,\n                2.0,\n                3.0,\n                4.0,\n                5.0,\n                6.0,\n                7.0,\n                8.0,\n                9.0,\n                10.0,\n                11.0,\n                12.0,\n            ]\n        )\n        .astype(np.float32)\n        .reshape((3, 4))\n    )\n\n    verify_cumsum(data, 0)\n    verify_cumsum(data, 1)\n    verify_cumsum(data, 0, 1, 0)\n    verify_cumsum(data, 1, 1, 0)\n    verify_cumsum(data, 0, 0, 1)\n    verify_cumsum(data, 1, 0, 1)\n    verify_cumsum(data, 1, 1, 1)\n    data = np.random.randn(1, 32, 32, 3).astype(\"float32\")\n    verify_cumsum(data, 1)\n    data = np.random.randn(1, 32, 32, 3).astype(\"int32\")\n    verify_cumsum(data, 0, dtype=\"int32\")\n    verify_cumsum(data, 1, dtype=\"int32\")\n    verify_cumsum(data, 0, 1, 0, dtype=\"int32\")\n    verify_cumsum(data, 1, 1, 0, dtype=\"int32\")\n    verify_cumsum(data, 0, 0, 1, dtype=\"int32\")\n    verify_cumsum(data, 1, 0, 1, dtype=\"int32\")\n    verify_cumsum(data, 1, 1, 1, dtype=\"int32\")\n\n\n@tvm.testing.parametrize_targets\ndef test_eyelike(target, dev):\n    \"\"\"test_eyelike\"\"\"\n\n    def verify_eyelike(indata, dynamic=False):\n        node_list = []\n        eyelike_inputs = [\"X\"]\n        input_node_list = [\n            helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(indata.shape))\n        ]\n        input_list = [indata]\n\n        if dynamic:\n            input_node_list.append(\n                helper.make_tensor_value_info(\"shape\", TensorProto.INT64, [len(indata.shape)])\n            )\n            input_list.append(np.asarray(indata.shape))\n            reshape_node = helper.make_node(\"Reshape\", [\"X\", \"shape\"], [\"X_dyn\"])\n            eyelike_inputs[0] = \"X_dyn\"\n            node_list += [reshape_node]\n\n        node = helper.make_node(\n            \"EyeLike\",\n            inputs=eyelike_inputs,\n            outputs=[\"Y\"],\n        )\n        node_list.append(node)\n\n        graph = helper.make_graph(\n            node_list,\n            \"eyelike_test\",\n            inputs=input_node_list,\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(indata.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"eyelike_test\")\n        verify_with_ort_with_inputs(\n            model, input_list, dtype=\"float32\", opset=9, target=target, dev=dev, use_vm=True\n        )\n\n    input_data = np.zeros((5, 5), dtype=np.float32)\n    verify_eyelike(input_data)\n    verify_eyelike(input_data, True)\n\n\n# The following parametrized tests loads the tests that ONNX ships as\n# serialized ONNX files, inputs, and outputs. The goal of this test\n# is to ensure the ONNX importer is in line with the ONNX specification.\n# To allow these tests to run in CI before all pass, a number of tests\n# that are not yet supported are skipped.\n\nonnx_test_node_dir = os.path.join(os.path.dirname(onnx.__file__), \"backend\", \"test\", \"data\", \"node\")\n\nonnx_test_folders = sorted(\n    dirname\n    for dirname in os.listdir(onnx_test_node_dir)\n    if dirname.startswith(\"test\") and os.path.isdir(os.path.join(onnx_test_node_dir, dirname))\n)\n\nunsupported_onnx_tests = [\n    \"test_batchnorm_epsilon_training_mode\",\n    \"test_batchnorm_example_training_mode\",\n    \"test_bernoulli\",\n    \"test_bernoulli_expanded\",\n    \"test_bernoulli_double\",\n    \"test_bernoulli_double_expanded\",\n    \"test_bernoulli_seed\",\n    \"test_bernoulli_seed_expanded\",\n    \"test_blackmanwindow\",\n    \"test_blackmanwindow_expanded\",\n    \"test_blackmanwindow_symmetric\",\n    \"test_blackmanwindow_symmetric_expanded\",\n    # the follow cast and castlike cases have lowering issues\n    \"test_cast_FLOAT_to_STRING\",\n    \"test_cast_STRING_to_FLOAT\",\n    \"test_castlike_FLOAT_to_STRING\",\n    \"test_castlike_FLOAT_to_STRING_expanded\",\n    \"test_castlike_STRING_to_FLOAT\",\n    \"test_castlike_STRING_to_FLOAT_expanded\",\n    # the following cast and castlike cases segfault\n    \"test_cast_DOUBLE_to_FLOAT16\",\n    \"test_castlike_DOUBLE_to_FLOAT16\",\n    \"test_castlike_DOUBLE_to_FLOAT16_expanded\",\n    \"test_convtranspose_autopad_same\",\n    \"test_convtranspose_dilations\",\n    \"test_cumsum_1d\",\n    \"test_cumsum_1d_exclusive\",\n    \"test_cumsum_1d_reverse\",\n    \"test_cumsum_1d_reverse_exclusive\",\n    \"test_cumsum_2d_axis_0\",\n    \"test_cumsum_2d_axis_1\",\n    \"test_cumsum_2d_negative_axis\",\n    \"test_det_2d\",\n    \"test_det_nd\",\n    \"test_dft\",\n    \"test_dft_axis\",\n    \"test_dft_inverse\",\n    \"test_dropout_default\",\n    \"test_dropout_default_mask\",\n    \"test_dropout_default_mask_ratio\",\n    \"test_dropout_default_ratio\",\n    \"test_gru_batchwise\",\n    \"test_hammingwindow\",\n    \"test_hammingwindow_expanded\",\n    \"test_hammingwindow_symmetric\",\n    \"test_hammingwindow_symmetric_expanded\",\n    \"test_hannwindow\",\n    \"test_hannwindow_expanded\",\n    \"test_hannwindow_symmetric\",\n    \"test_hannwindow_symmetric_expanded\",\n    \"test_identity_opt\",\n    \"test_identity_sequence\",\n    \"test_if_opt\",\n    \"test_if_seq\",\n    \"test_loop13_seq\",\n    \"test_loop16_seq_none\",\n    \"test_lstm_batchwise\",\n    \"test_maxpool_with_argmax_2d_precomputed_pads\",\n    \"test_maxpool_with_argmax_2d_precomputed_strides\",\n    \"test_maxunpool_export_with_output_shape\",\n    \"test_melweightmatrix\",\n    # This test fails llvm with a lowering error:\n    \"test_nllloss_NCd1d2d3_none_no_weight_negative_ii_expanded\",\n    \"test_qlinearmatmul_3D\",\n    \"test_range_float_type_positive_delta_expanded\",\n    \"test_range_int32_type_negative_delta_expanded\",\n    \"test_reduce_sum_do_not_keepdims_example\",\n    \"test_reduce_sum_do_not_keepdims_random\",\n    \"test_reduce_sum_keepdims_example\",\n    \"test_reduce_sum_keepdims_random\",\n    \"test_reduce_sum_negative_axes_keepdims_example\",\n    \"test_reduce_sum_negative_axes_keepdims_random\",\n    \"test_roialign_aligned_true\",\n    \"test_scatter_elements_with_duplicate_indices\",\n    \"test_scatternd_add\",\n    \"test_scatternd_multiply\",\n    \"test_sequence_insert_at_back\",\n    \"test_sequence_insert_at_front\",\n    \"test_sequence_map_add_1_sequence_1_tensor\",\n    \"test_sequence_map_add_1_sequence_1_tensor_expanded\",\n    \"test_sequence_map_add_2_sequences\",\n    \"test_sequence_map_add_2_sequences_expanded\",\n    \"test_sequence_map_extract_shapes\",\n    \"test_sequence_map_extract_shapes_expanded\",\n    \"test_sequence_map_identity_1_sequence\",\n    \"test_sequence_map_identity_1_sequence_1_tensor\",\n    \"test_sequence_map_identity_1_sequence_1_tensor_expanded\",\n    \"test_sequence_map_identity_1_sequence_expanded\",\n    \"test_sequence_map_identity_2_sequences\",\n    \"test_sequence_map_identity_2_sequences_expanded\",\n    \"test_simple_rnn_batchwise\",\n    \"test_simple_rnn_defaults\",\n    \"test_simple_rnn_with_initial_bias\",\n    \"test_split_variable_parts_1d\",\n    \"test_split_variable_parts_2d\",\n    \"test_split_variable_parts_default_axis\",\n    \"test_split_zero_size_splits\",\n    \"test_stft\",\n    \"test_stft_with_window\",\n    \"test_strnormalizer_export_monday_casesensintive_lower\",\n    \"test_strnormalizer_export_monday_casesensintive_nochangecase\",\n    \"test_strnormalizer_export_monday_casesensintive_upper\",\n    \"test_strnormalizer_export_monday_empty_output\",\n    \"test_strnormalizer_export_monday_insensintive_upper_twodim\",\n    \"test_strnormalizer_nostopwords_nochangecase\",\n    \"test_tfidfvectorizer_tf_batch_onlybigrams_skip0\",\n    \"test_tfidfvectorizer_tf_batch_onlybigrams_skip5\",\n    \"test_tfidfvectorizer_tf_batch_uniandbigrams_skip5\",\n    \"test_tfidfvectorizer_tf_only_bigrams_skip0\",\n    \"test_tfidfvectorizer_tf_onlybigrams_levelempty\",\n    \"test_tfidfvectorizer_tf_onlybigrams_skip5\",\n    \"test_tfidfvectorizer_tf_uniandbigrams_skip5\",\n    \"test_training_dropout\",\n    \"test_training_dropout_default\",\n    \"test_training_dropout_default_mask\",\n    \"test_training_dropout_mask\",\n    \"test_training_dropout_zero_ratio\",\n    \"test_training_dropout_zero_ratio_mask\",\n    \"test_tril_zero\",\n    \"test_triu_zero\",\n    \"test_unique_sorted_with_axis\",\n    \"test_unique_sorted_with_axis_3d\",\n    \"test_unique_sorted_with_negative_axis\",\n    \"test_upsample_nearest\",\n]\n\n\ntarget_skips = {\n    \"cuda\": [\n        \"test_range_float_type_positive_delta_expanded\",\n        \"test_range_int32_type_positive_delta_expanded\",\n        \"test_mod_mixed_sign_float16\",\n        \"test_qlinearconv\",\n        \"test_qlinearmatmul\",\n        \"test_resize_upsample_sizes_nearest\",\n    ]\n}\n\n\ndef _load_proto(proto_filename, target_list, model_type_proto):\n    with open(proto_filename, \"rb\") as fin:\n        protobuf_content = fin.read()\n        if model_type_proto.HasField(\"sequence_type\"):\n            sequence = onnx.SequenceProto()\n            sequence.ParseFromString(protobuf_content)\n            target_list.append(numpy_helper.to_list(sequence))\n        elif model_type_proto.HasField(\"tensor_type\"):\n            tensor = onnx.TensorProto()\n            tensor.ParseFromString(protobuf_content)\n            target_list.append(numpy_helper.to_array(tensor))\n        elif model_type_proto.HasField(\"optional_type\"):\n            optional = onnx.OptionalProto()\n            optional.ParseFromString(protobuf_content)\n            target_list.append(numpy_helper.to_optional(optional))\n        else:\n            raise ValueError(\n                \"Loading proto of that specific type (Map/Sparse Tensor) is currently not supported\"\n            )\n\n\n@pytest.mark.parametrize(\"onnx_test\", onnx_test_folders)\n@tvm.testing.parametrize_targets\ndef test_onnx_nodes(target, dev, onnx_test):\n    \"\"\"test_onnx_nodes\"\"\"\n    if platform.machine() == \"aarch64\" and onnx_test == \"test_resize_upsample_sizes_nearest\":\n        pytest.skip(\"Currently failing on AArch64\")\n\n    target_kind = tvm.target.Target(target).kind.name\n\n    if onnx_test in unsupported_onnx_tests:\n        pytest.skip(f\"Onnx test '{onnx_test}' not yet supported by TVM\")\n\n    target_specific_skips = target_skips.get(target_kind, [])\n    if onnx_test in target_specific_skips:\n        pytest.skip(f\"Onnx test '{onnx_test}' not yet supported by TVM on {target_kind} targets\")\n\n    test_dir = os.path.join(onnx_test_node_dir, onnx_test)\n\n    atol = 1e-5\n    rtol = 1e-5\n    if \"roialign\" in test_dir:\n        # for some reason the ONNX test crops the\n        # roialign results to 4 decimal places\n        atol = 1e-4\n\n    if \"to_BFLOAT16\" in test_dir:\n        # the tolerance here is for the comparison in uint16 space, but is not as significant\n        # of a delta in bfloat16 space because it's representing the mantissa being off by 1\n        atol = 1\n\n    if \"_sce_\" in test_dir:\n        # complicated loss functions like SoftmaxCrossEntropy can have minor variations\n        # in accuracy depending on implementation\n        atol = 1e-4\n\n    if \"bicubic\" in test_dir:\n        # satisfies onnx precision for bicubic interpolation\n        atol = 1e-4\n\n    model = onnx.load(os.path.join(test_dir, \"model.onnx\"))\n    for test_data_dir in glob.glob(os.path.join(test_dir, \"test_data_set*\")):\n        inputs = []\n        n_inputs = len(glob.glob(os.path.join(test_data_dir, \"input_*.pb\")))\n        for i in range(n_inputs):\n            input_file = os.path.join(test_data_dir, f\"input_{i}.pb\")\n            _load_proto(input_file, inputs, model.graph.input[i].type)\n\n        outputs = []\n        n_outputs = len(glob.glob(os.path.join(test_data_dir, \"output_*.pb\")))\n        for i in range(n_outputs):\n            output_file = os.path.join(test_data_dir, f\"output_{i}.pb\")\n            _load_proto(output_file, outputs, model.graph.output[i].type)\n\n    tvm_val = get_tvm_output_with_vm(model, inputs, target, dev)\n    if len(outputs) == 1:\n        tvm.testing.assert_allclose(outputs[0], tvm_val, rtol=rtol, atol=atol)\n    else:\n        for output, val in zip(outputs, tvm_val):\n            tvm.testing.assert_allclose(output, val, rtol=rtol, atol=atol)\n\n\ndef test_wrong_input():\n    \"\"\"test_wrong_input\"\"\"\n    node = helper.make_node(\n        \"Softplus\",\n        inputs=[\"X\"],\n        outputs=[\"Y\"],\n    )\n\n    graph = helper.make_graph(\n        [node],\n        \"softplus_test\",\n        inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list([5]))],\n        outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list([5]))],\n    )\n    model = helper.make_model(graph, producer_name=\"softplus_test\")\n\n    # Check that the graph can import correctly with proper shape definitions.\n    correct_shape_dict = {\"X\": [5]}\n    relay.frontend.from_onnx(model, shape=correct_shape_dict)\n\n    # Check that an assertion is triggered when an input not in the graph is provided.\n    wrong_shape_dict = {\"Z\": [5]}\n    with pytest.raises(AssertionError):\n        relay.frontend.from_onnx(model, shape=wrong_shape_dict)\n\n\n@tvm.testing.parametrize_targets\ndef test_aten(target, dev):\n    \"\"\"test_aten\"\"\"\n    torch.set_grad_enabled(False)\n\n    def _convert_to_onnx(model, inputs):\n        file_name = \"aten_model.onnx\"\n        torch.onnx.export(\n            model,\n            inputs,\n            file_name,\n            export_params=True,\n            verbose=False,\n            opset_version=10,\n            operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN,\n        )\n        onnx_model = onnx.load(file_name)\n        return onnx_model\n\n    def verify_embedding_bag(num_embedding, embedding_dim, data_shape, num_bags=None):\n        dummy_data = torch.randint(0, num_embedding - 1, data_shape)\n        tvm_inputs = [dummy_data.numpy()]\n        model = torch.nn.EmbeddingBag(num_embedding, embedding_dim)\n        onnx_model = _convert_to_onnx(model, dummy_data)\n        torch_out = model(dummy_data)\n        tvm_out = get_tvm_output_with_vm(\n            onnx_model,\n            tvm_inputs,\n            freeze_params=True,\n            target=target,\n            dev=dev,\n        )\n        tvm.testing.assert_allclose(torch_out.numpy(), tvm_out, atol=5e-7)\n\n    verify_embedding_bag(10, 3, [2, 10])\n    verify_embedding_bag(32, 2, [3, 3])\n\n\n@tvm.testing.parametrize_targets\ndef test_index_put(target, dev):\n    \"\"\"test_index_put\"\"\"\n\n    class IndexPutModel(torch.nn.Module):\n        def __init__(self, indices, values, accumulate):\n            super().__init__()\n            self.indices = indices\n            self.values = values\n            self.accumulate = accumulate\n\n        def forward(self, x):\n            return x.index_put(self.indices, self.values, self.accumulate)\n\n    def _convert_to_onnx(model, dummy_data):\n        file_name = \"aten_model.onnx\"\n        torch.onnx.export(\n            model,\n            dummy_data,\n            file_name,\n            export_params=True,\n            verbose=False,\n            opset_version=11,\n            operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK,\n        )\n        onnx_model = onnx.load(file_name)\n        return onnx_model\n\n    def verify_index_put(data_shape, indices, accumulate):\n        dummy_data = torch.ones(data_shape)\n        tvm_inputs = [dummy_data.numpy()]\n        values = torch.rand(indices[0].size())\n        model = IndexPutModel(indices, values, accumulate)\n        onnx_model = _convert_to_onnx(model, dummy_data)\n        torch_out = model(dummy_data)\n\n        tvm_out = get_tvm_output_with_vm(onnx_model, tvm_inputs, target, dev, freeze_params=True)\n        tvm.testing.assert_allclose(torch_out.numpy(), tvm_out)\n\n    shape = (3, 5)\n    xidx = torch.tensor([0, 1, 2, 2])\n    yidx = torch.tensor([0, 1, 3, 4])\n    verify_index_put(shape, [xidx, yidx], True)\n\n    shape = (3, 5, 3)\n    xidx = torch.tensor([0, 1, 2, 2, 0])\n    yidx = torch.tensor([0, 1, 3, 4, 0])\n    zidx = torch.tensor([0, 1, 1, 2, 0])\n    verify_index_put(shape, [xidx, yidx, zidx], False)\n\n    def verify_index_put_slice(data_shape, value_shape, accumulate):\n        dummy_data = torch.ones(data_shape)\n        tvm_inputs = [dummy_data.numpy()]\n        indices = []\n        index_shape = [1] * len(value_shape)\n        index_shape[0] = -1\n        for _, v_shape in enumerate(value_shape):\n            indices.append(torch.arange(0, v_shape).reshape(tuple(index_shape)))\n            index_shape.pop()\n        values = torch.rand(value_shape)\n\n        model = IndexPutModel(indices, values, accumulate)\n        onnx_model = _convert_to_onnx(model, dummy_data)\n        torch_out = model(dummy_data)\n\n        tvm_out = get_tvm_output_with_vm(onnx_model, tvm_inputs, target, dev, freeze_params=True)\n        tvm.testing.assert_allclose(torch_out.numpy(), tvm_out)\n\n    verify_index_put_slice((3, 3), (2, 2), False)\n    verify_index_put_slice((2, 3, 4), (1, 2, 3), True)\n    verify_index_put_slice((2, 3, 4, 5), (1, 2, 3, 1), False)\n\n\n@tvm.testing.parametrize_targets\ndef test_reverse_sequence(target, dev):\n    \"\"\"test_reverse_sequence\"\"\"\n\n    def verify_reverse_sequence(x, sequence_lens, batch_axis, time_axis):\n        node = onnx.helper.make_node(\n            \"ReverseSequence\",\n            inputs=[\"x\", \"sequence_lens\"],\n            outputs=[\"y\"],\n            time_axis=time_axis,\n            batch_axis=batch_axis,\n        )\n\n        graph = helper.make_graph(\n            [node],\n            \"reverse_sequence_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x.shape)),\n                helper.make_tensor_value_info(\n                    \"sequence_lens\", TensorProto.INT64, list(sequence_lens.shape)\n                ),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(x.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=\"reverse_sequence_test\")\n        verify_with_ort_with_inputs(model, [x, sequence_lens], [x.shape], target=target, dev=dev)\n\n    x = np.array(\n        [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]],\n        dtype=np.float32,\n    )\n    sequence_lens = np.array([1, 2, 3, 4], dtype=np.int64)\n    verify_reverse_sequence(x, sequence_lens, 0, 1)\n\n    sequence_lens = np.array([4, 3, 2, 1], dtype=np.int64)\n    verify_reverse_sequence(x, sequence_lens, 1, 0)\n\n\n@pytest.mark.parametrize(\"op_name\", [\"Gelu\", \"FastGelu\"], scope=\"session\")\n@pytest.mark.parametrize(\"data_type\", [\"float16\", \"float32\"], scope=\"session\")\n@tvm.testing.parametrize_targets\ndef test_gelu(target, dev, data_type, op_name):\n    \"\"\"test_gelu\"\"\"\n    dtype = np.dtype(data_type)\n    tensor_type = mapping.NP_TYPE_TO_TENSOR_TYPE[dtype]\n    absolute_tolerance = 1e-3 if data_type == \"float16\" else 1e-5\n\n    def verify_gelu(x):\n        node = onnx.helper.make_node(\n            op_name,\n            inputs=[\"x\"],\n            outputs=[\"y\"],\n            domain=\"com.microsoft\",\n        )\n\n        graph = helper.make_graph(\n            [node],\n            f\"{op_name}_test\",\n            inputs=[helper.make_tensor_value_info(\"x\", tensor_type, list(x.shape))],\n            outputs=[helper.make_tensor_value_info(\"y\", tensor_type, list(x.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=f\"{op_name}_test\")\n        verify_with_ort_with_inputs(\n            model, [x], [x.shape], atol=absolute_tolerance, dtype=data_type, target=target, dev=dev\n        )\n\n    x = np.array([-1.0, 0, 1.0, 100.0, -100.0, 1000.0, -1000.0], dtype=dtype)\n    verify_gelu(x)\n    x = np.array([[1, 2], [3, 4]], dtype=dtype)\n    verify_gelu(x)\n\n\n@pytest.mark.parametrize(\"op_name\", [\"BiasGelu\", \"FastGelu\"], scope=\"session\")\n@pytest.mark.parametrize(\"data_type\", [\"float16\", \"float32\"], scope=\"session\")\n@tvm.testing.parametrize_targets\ndef test_biasgelu(target, dev, data_type, op_name):\n    \"\"\"test_biasgelu\"\"\"\n    dtype = np.dtype(data_type)\n    tensor_type = mapping.NP_TYPE_TO_TENSOR_TYPE[dtype]\n    absolute_tolerance = 1e-3 if data_type == \"float16\" else 1e-5\n\n    def verify_biasgelu(x, bias):\n        node = onnx.helper.make_node(\n            op_name,\n            inputs=[\"x\", \"bias\"],\n            outputs=[\"y\"],\n            domain=\"com.microsoft\",\n        )\n\n        graph = helper.make_graph(\n            [node],\n            f\"{op_name}_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"x\", tensor_type, list(x.shape)),\n                helper.make_tensor_value_info(\"bias\", tensor_type, list(bias.shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"y\", tensor_type, list(x.shape))],\n        )\n\n        model = helper.make_model(graph, producer_name=f\"{op_name}_test\")\n        verify_with_ort_with_inputs(\n            model,\n            [x, bias],\n            [x.shape],\n            atol=absolute_tolerance,\n            dtype=data_type,\n            target=target,\n            dev=dev,\n        )\n\n    x = np.array([-1.0, 0, 1.0, 100.0, -100.0, 1000.0, -1000.0], dtype=dtype)\n    bias = np.repeat(2.0, 7).astype(dtype)\n    verify_biasgelu(x, bias)\n\n    x = np.array([[1, 2], [3, 4]], dtype=dtype)\n    bias = np.array([0.3, 4.0], dtype=dtype)\n    verify_biasgelu(x, bias)\n\n\n@tvm.testing.parametrize_targets\ndef test_embedlayernormalization(target, dev):\n    \"\"\"test_embedlayernormalization\"\"\"\n\n    def verify_embedlayernormalization(\n        input_ids,\n        segment_ids,\n        word_embedding,\n        position_embedding,\n        segment_embedding,\n        gamma,\n        beta,\n    ):\n        node = onnx.helper.make_node(\n            \"EmbedLayerNormalization\",\n            inputs=[\n                \"input_ids\",\n                \"\" if segment_ids is None else \"segment_ids\",\n                \"word_embedding\",\n                \"position_embedding\",\n                \"\" if segment_embedding is None else \"segment_embedding\",\n                \"gamma\",\n                \"beta\",\n            ],\n            outputs=[\"output\", \"mask_index\"],\n            domain=\"com.microsoft\",\n        )\n\n        node.attribute.append(onnx.helper.make_attribute(\"epsilon\", 1e-4))\n\n        segment_ids_shape = [] if segment_ids is None else segment_ids.shape\n        segment_embedding_shape = [] if segment_embedding is None else segment_embedding.shape\n\n        graph = helper.make_graph(\n            [node],\n            \"embedlayernormalization_test\",\n            inputs=[\n                helper.make_tensor_value_info(\n                    \"input_ids\", TensorProto.INT32, list(input_ids.shape)\n                ),\n                helper.make_tensor_value_info(\"segment_ids\", TensorProto.INT32, segment_ids_shape),\n                helper.make_tensor_value_info(\n                    \"word_embedding\", TensorProto.FLOAT, list(word_embedding.shape)\n                ),\n                helper.make_tensor_value_info(\n                    \"position_embedding\", TensorProto.FLOAT, list(position_embedding.shape)\n                ),\n                helper.make_tensor_value_info(\n                    \"segment_embedding\", TensorProto.FLOAT, segment_embedding_shape\n                ),\n                helper.make_tensor_value_info(\"gamma\", TensorProto.FLOAT, list(gamma.shape)),\n                helper.make_tensor_value_info(\"beta\", TensorProto.FLOAT, list(beta.shape)),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\n                    \"output\", TensorProto.FLOAT, list((batch_size, sequence_length, hidden_size))\n                ),\n                helper.make_tensor_value_info(\"mask_index\", TensorProto.INT32, [batch_size]),\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"embedlayernormalization_test\")\n\n        # TODO(@anwang2009): onnxruntime v1.9.0 requires empty list for optional argument,\n        # but v1.10.0+ requires None instead.\n        verify_with_ort_with_inputs(\n            model,\n            [\n                input_ids,\n                np.empty(0, dtype=\"int32\") if segment_ids is None else segment_ids,\n                word_embedding,\n                position_embedding,\n                np.empty(0, dtype=\"float32\") if segment_embedding is None else segment_embedding,\n                gamma,\n                beta,\n            ],\n            [\n                (batch_size, sequence_length, hidden_size),\n                batch_size,\n            ],\n            target=target,\n            dev=dev,\n            rtol=1e-4,\n            atol=1e-4,\n        )\n\n    hidden_size = 384\n    batch_size = 4\n    sequence_length = 3\n    vocab_size = 5\n\n    input_ids = np.full((batch_size, sequence_length), 3).astype(\"int32\")\n    segment_ids = np.zeros((batch_size, sequence_length)).astype(\"int32\")\n    word_embedding = np.full((vocab_size, hidden_size), 1).astype(\"float32\")\n    position_embedding = np.full((sequence_length, hidden_size), 2).astype(\"float32\")\n    segment_embedding = np.full((vocab_size, hidden_size), 3).astype(\"float32\")\n\n    gamma = np.random.uniform(0.5, 0.7, hidden_size).astype(\"float32\")\n    beta = np.random.randn(hidden_size).astype(\"float32\") * 0.1\n\n    verify_embedlayernormalization(\n        input_ids, segment_ids, word_embedding, position_embedding, segment_embedding, gamma, beta\n    )\n\n    # Test with undefined segment embedding\n    verify_embedlayernormalization(\n        input_ids, None, word_embedding, position_embedding, None, gamma, beta\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_attention(target, dev):\n    \"\"\"test_attention\"\"\"\n\n    def verify_attention(input_, weight, bias, mask_index, num_heads):\n        node = onnx.helper.make_node(\n            \"Attention\",\n            inputs=[\"input\", \"weight\", \"bias\", \"mask_index\"],\n            outputs=[\"output\", \"present\"],\n            domain=\"com.microsoft\",\n            num_heads=num_heads,\n        )\n\n        present_output_shape = (2, batch_size, num_heads, sequence_length, head_size)\n\n        graph = helper.make_graph(\n            [node],\n            \"attention_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(input_.shape)),\n                helper.make_tensor_value_info(\"weight\", TensorProto.FLOAT, list(weight.shape)),\n                helper.make_tensor_value_info(\"bias\", TensorProto.FLOAT, list(bias.shape)),\n                helper.make_tensor_value_info(\n                    \"mask_index\", TensorProto.INT32, list(mask_index.shape)\n                ),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(input_.shape)),\n                helper.make_tensor_value_info(\n                    \"present\", TensorProto.FLOAT, list(present_output_shape)\n                ),\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"attention_test\")\n\n        # \"present\" output should be nullptr when the \"past\" input isn't included,\n        # but ort requires an output shape to be specified?\n        verify_with_ort_with_inputs(\n            model,\n            [input_, weight, bias, mask_index],\n            [input_.shape, present_output_shape],\n            target=target,\n            dev=dev,\n            rtol=1e-4,\n            atol=1e-4,\n        )\n\n    hidden_size = 384\n    batch_size = 4\n    sequence_length = 4\n    num_heads = 12\n    head_size = 32\n\n    dtype = \"float32\"\n    input_array = np.random.random((batch_size, sequence_length, hidden_size)).astype(dtype)\n    weight = np.random.normal(size=(hidden_size, 3 * hidden_size)).astype(dtype) * 0.1\n    bias = np.random.randn(3 * hidden_size).astype(dtype)\n    mask_index = np.full((batch_size, sequence_length), 1).astype(\"int32\")\n\n    verify_attention(input_array, weight, bias, mask_index, num_heads)\n\n\n@tvm.testing.parametrize_targets\ndef test_skiplayernormalization(target, dev):\n    \"\"\"test_skiplayernormalization\"\"\"\n\n    def verify_skiplayernormalization(input_, skip, gamma, beta, bias):\n        node = onnx.helper.make_node(\n            \"SkipLayerNormalization\",\n            inputs=[\"input\", \"skip\", \"gamma\", \"beta\", \"bias\"],\n            outputs=[\"output\"],\n            domain=\"com.microsoft\",\n        )\n\n        node.attribute.append(onnx.helper.make_attribute(\"epsilon\", 1e-4))\n\n        graph = helper.make_graph(\n            [node],\n            \"skiplayernormalization_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(input_.shape)),\n                helper.make_tensor_value_info(\"skip\", TensorProto.FLOAT, list(skip.shape)),\n                helper.make_tensor_value_info(\"gamma\", TensorProto.FLOAT, list(gamma.shape)),\n                helper.make_tensor_value_info(\"beta\", TensorProto.FLOAT, list(beta.shape)),\n                helper.make_tensor_value_info(\"bias\", TensorProto.FLOAT, list(bias.shape)),\n            ],\n            outputs=[\n                helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(input_.shape)),\n            ],\n        )\n\n        model = helper.make_model(graph, producer_name=\"skiplayernormalization_test\")\n        verify_with_ort_with_inputs(\n            model, [input_, skip, gamma, beta, bias], [input_.shape], target=target, dev=dev\n        )\n\n    hidden_size = 384\n    batch_size = 4\n    sequence_length = 4\n\n    dtype = \"float32\"\n    input_array = np.random.random((batch_size, sequence_length, hidden_size)).astype(dtype)\n    skip = np.random.random((batch_size, sequence_length, hidden_size)).astype(dtype)\n    gamma = np.random.uniform(0.5, 0.7, hidden_size).astype(dtype)\n    beta = np.random.randn(hidden_size).astype(dtype) * 0.1\n    bias = np.random.randn(hidden_size).astype(dtype)\n\n    verify_skiplayernormalization(input_array, skip, gamma, beta, bias)\n\n\n@tvm.testing.known_failing_targets(\"cuda\")\n@tvm.testing.parametrize_targets\ndef test_qlinearconv(target, dev):\n    \"\"\"test_qlinearconv\"\"\"\n\n    def verify_qlinearconv(\n        x_shape,\n        w_shape,\n        y_shape,\n        padding,\n        kernel_shape,\n        strides,\n        dilations,\n        auto_pad=\"NOTSET\",\n        bias=False,\n        per_channel_quantization=False,\n    ):\n\n        x_array = np.random.randint(low=0, high=255, size=x_shape).astype(\"uint8\")\n        w_array = np.random.uniform(low=0, high=255, size=w_shape).astype(\"uint8\")\n\n        initializer = [\n            helper.make_tensor(\"x_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n            helper.make_tensor(\"x_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]),\n            helper.make_tensor(\"y_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n            helper.make_tensor(\"y_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]),\n        ]\n\n        input_nodes = [\n            helper.make_tensor_value_info(\"x\", TensorProto.UINT8, list(x_shape)),\n            helper.make_tensor_value_info(\"w\", TensorProto.UINT8, list(w_shape)),\n        ]\n        input_names = [\n            \"x\",\n            \"x_scale\",\n            \"x_zero_point\",\n            \"w\",\n            \"w_scale\",\n            \"w_zero_point\",\n            \"y_scale\",\n            \"y_zero_point\",\n        ]\n        input_values = [x_array, w_array]\n\n        if per_channel_quantization:\n            w_scale_array = np.random.random(w_shape[0]).astype(\"float32\")\n            w_zero_point_array = np.random.randint(0, 255, size=w_shape[0]).astype(\"uint8\")\n\n            initializer.append(\n                helper.make_tensor(\"w_scale\", TensorProto.FLOAT, [w_shape[0]], w_scale_array)\n            )\n            initializer.append(\n                helper.make_tensor(\n                    \"w_zero_point\", TensorProto.UINT8, [w_shape[0]], w_zero_point_array\n                )\n            )\n        else:\n            initializer.append(\n                helper.make_tensor(\"w_scale\", TensorProto.FLOAT, (), [np.random.rand()])\n            )\n            initializer.append(\n                helper.make_tensor(\n                    \"w_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]\n                )\n            )\n\n        if bias is True:\n            b_shape = w_shape[0:1]\n            b_array = np.random.randint(low=0, high=65536, size=b_shape).astype(\"int32\")\n            input_nodes.append(helper.make_tensor_value_info(\"B\", TensorProto.INT32, list(b_shape)))\n            input_names.append(\"B\")\n            input_values.append(b_array)\n\n        if padding is None:\n            ## autopadding with unset default attributes\n            kwargs = {}\n            if not all(list(s == 1 for s in strides)):\n                kwargs[\"strides\"] = strides\n            if not all(list(d == 1 for d in dilations)):\n                kwargs[\"dilations\"] = dilations\n\n            node = helper.make_node(\n                \"QLinearConv\",\n                inputs=input_names,\n                outputs=[\"y\"],\n                # Default values for other attributes:\n                auto_pad=auto_pad,\n                **kwargs,\n            )\n        else:\n            node = helper.make_node(\n                \"QLinearConv\",\n                inputs=input_names,\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                # Default values for other attributes:\n                strides=strides,\n                dilations=dilations,\n                # groups=1\n                pads=padding,\n            )\n\n        graph = helper.make_graph(\n            [node],\n            \"conv_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.UINT8, list(y_shape))],\n            initializer=initializer,\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearconv_test\")\n        # opt_level=1 will cause error\n        verify_with_ort_with_inputs(model, input_values, opt_level=2, target=target, dev=dev)\n\n    def repeat(num, dims):\n        return tuple(num for _ in range(dims))\n\n    # only support QLinearConv2d because only support qnn.conv2d\n    dims = 2\n\n    # Convolution with padding\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        2 * repeat(1, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n\n    # Convolution with bias\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        2 * repeat(1, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        bias=True,\n    )\n\n    # Convolution with asymmetric padding\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(4, dims),\n        repeat(0, dims) + repeat(1, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n    # Convolution without padding\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        2 * repeat(0, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n    # Convolution with autopadding\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        None,\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Convolution with valid autopadding\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        None,\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        auto_pad=\"VALID\",\n    )\n    # Convolution with non uniform stride\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        None,\n        repeat(3, dims),\n        repeat(2, dims),\n        repeat(1, dims),\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Convolution with dilation\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        2 * repeat(2, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(2, dims),\n    )\n    # Convolution with per channel quantization\n    verify_qlinearconv(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        None,\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        per_channel_quantization=True,\n    )\n\n\n# TODO(vvchernov): fix problem with quantization on cuda\n@tvm.testing.known_failing_targets(\"cuda\")\n@tvm.testing.parametrize_targets\ndef test_qlinearmatmul(target, dev):\n    \"\"\"test_qlinearmatmul\"\"\"\n\n    def verify_qlinearmatmul(\n        x_shape,\n        w_shape,\n        y_shape,\n        x_dtype=\"uint8\",\n        w_dtype=\"uint8\",\n    ):\n        def get_randint_numpy_scalar(dtype=\"uint8\"):\n            if dtype == \"uint8\":\n                return np.random.randint(0, 255)\n            else:  # \"int8\"\n                return np.random.randint(-128, 127)\n\n        if x_dtype == \"uint8\":\n            x_array = np.random.randint(low=0, high=255, size=x_shape).astype(\"uint8\")\n        else:  # \"int8\"\n            x_array = np.random.randint(low=-128, high=127, size=x_shape).astype(\"int8\")\n        if w_dtype == \"uint8\":\n            w_array = np.random.uniform(low=0, high=255, size=w_shape).astype(\"uint8\")\n        else:  # \"int8\"\n            w_array = np.random.uniform(low=-128, high=127, size=w_shape).astype(\"int8\")\n\n        x_proto_type = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(x_dtype)]\n        w_proto_type = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(w_dtype)]\n\n        y_dtype = \"int8\"\n        if x_dtype == \"uint8\" and w_dtype == \"uint8\":\n            y_dtype = \"uint8\"\n        y_proto_type = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(y_dtype)]\n\n        initializer = [\n            helper.make_tensor(\"x_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n            # TODO: 0 value for int8?\n            helper.make_tensor(\n                \"x_zero_point\", x_proto_type, (), [get_randint_numpy_scalar(x_dtype)]\n            ),\n            helper.make_tensor(\"w_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n            # TODO: 0 value for int8?\n            helper.make_tensor(\n                \"w_zero_point\", w_proto_type, (), [get_randint_numpy_scalar(w_dtype)]\n            ),\n            helper.make_tensor(\"y_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n            helper.make_tensor(\n                \"y_zero_point\", y_proto_type, (), [get_randint_numpy_scalar(y_dtype)]\n            ),\n        ]\n\n        input_nodes = [\n            helper.make_tensor_value_info(\"x\", x_proto_type, list(x_shape)),\n            helper.make_tensor_value_info(\"w\", w_proto_type, list(w_shape)),\n        ]\n        input_names = [\n            \"x\",\n            \"x_scale\",\n            \"x_zero_point\",\n            \"w\",\n            \"w_scale\",\n            \"w_zero_point\",\n            \"y_scale\",\n            \"y_zero_point\",\n        ]\n        input_values = [x_array, w_array]\n\n        node = helper.make_node(\n            \"QLinearMatMul\",\n            inputs=input_names,\n            outputs=[\"y\"],\n        )\n\n        y_proto_type = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(\"int8\")]\n        if x_dtype == \"uint8\" and w_dtype == \"uint8\":\n            y_proto_type = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(\"uint8\")]\n\n        graph = helper.make_graph(\n            [node],\n            \"qmatmul_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"y\", y_proto_type, list(y_shape))],\n            initializer=initializer,\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearmatmul_test\")\n        # opt_level=1 will cause error\n        verify_with_ort_with_inputs(model, input_values, opt_level=2, target=target, dev=dev)\n\n    # Default matmul both ranks = 2 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    verify_qlinearmatmul((2, 3), (3, 2), (2, 2))\n\n    # Default matmul both ranks = 2 (x_dtype = \"int8\", w_dtype = \"int8\")\n    verify_qlinearmatmul((2, 3), (3, 2), (2, 2), \"int8\", \"int8\")\n\n    # TODO(vvchernov): problems on ONNX Runtime side and type check (onnx.py:L4763) on TVM side\n    # Default matmul both ranks = 2 (x_dtype = \"uint8\", w_dtype = \"int8\")\n    # verify_qlinearmatmul((2, 3), (3, 2), (2, 2), \"uint8\", \"int8\")\n\n    # TODO(vvchernov): problems on ONNX Runtime side and type check (onnx.py:L4763) on TVM side\n    # Default matmul both ranks = 2 (x_dtype = \"int8\", w_dtype = \"uint8\")\n    # verify_qlinearmatmul((2, 3), (3, 2), (2, 2), \"int8\", \"uint8\")\n\n    # Reduced matmul: x_ranks = 1, w_rank = 2 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    verify_qlinearmatmul((3,), (3, 2), (2,))\n\n    # Special case matmul: x_ranks = 3, w_rank = 2 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    verify_qlinearmatmul((2, 3, 4), (4, 3), (2, 3, 3))\n\n    # GPT2-style matmul both ranks = 4 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    verify_qlinearmatmul((2, 4, 3, 3), (2, 4, 3, 3), (2, 4, 3, 3))\n\n    # Asymetric matmul: x_ranks = 4, w_rank = 3 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    verify_qlinearmatmul((2, 4, 3, 3), (4, 3, 3), (2, 4, 3, 3))\n\n    # Asymetric matmul: x_ranks = 2, w_rank = 3 (x_dtype = \"uint8\", w_dtype = \"uint8\")\n    # verify_qlinearmatmul((3, 3), (4, 3, 3), (4, 3, 3))\n\n\n@tvm.testing.parametrize_targets\ndef test_qlinearconcat(target, dev):\n    \"\"\"test_qlinearconcat\"\"\"\n\n    def verify_qlinearconcat(shapes, out_shape, axis=None):\n        input_names = []\n        input_values = []\n        input_nodes = []\n        for i, shape in enumerate(shapes):\n            tensor_name = chr(ord(\"a\") + i)\n            node = helper.make_tensor_value_info(tensor_name, TensorProto.FLOAT, list(shape))\n\n            input_names.append(tensor_name)\n            input_values.append(np.random.random(shape).astype(\"float32\"))\n            input_nodes.append(node)\n\n        node = helper.make_node(\"Concat\", input_names, [\"C\"])\n        if axis is not None:\n            axis_attr = helper.make_attribute(\"axis\", axis)\n            node.attribute.append(axis_attr)\n        graph = helper.make_graph(\n            [node],\n            \"qlinearconcat_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(out_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearconcat_test\")\n        quantize_and_verify_with_ort(model, input_names, shapes, target, dev)\n\n    verify_qlinearconcat([[2, 1], [2, 1]], [4, 1], 0)\n    verify_qlinearconcat([[2, 1], [2, 1]], [2, 2], 1)\n    verify_qlinearconcat([[1, 2], [2, 2], [3, 2]], [6, 2], 0)\n\n\n@tvm.testing.parametrize_targets\ndef test_qlinearadd(target, dev):\n    \"\"\"test_qlinearadd\"\"\"\n\n    def verify_qlinearadd(a_shape, b_shape, c_shape):\n\n        _ = np.random.random(a_shape).astype(\"float32\")\n        _ = np.random.random(b_shape).astype(\"float32\")\n\n        input_nodes = [\n            helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n            helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n        ]\n        input_names = [\n            \"a\",\n            \"b\",\n        ]\n\n        node = helper.make_node(\"Add\", [\"a\", \"b\"], [\"C\"])\n        graph = helper.make_graph(\n            [node],\n            \"qlinearadd_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(c_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearadd_test\")\n        quantize_and_verify_with_ort(model, input_names, [a_shape, b_shape], target, dev)\n\n    verify_qlinearadd([4, 2], [4, 2], [4, 2])\n    verify_qlinearadd([4, 2], [2], [4, 2])\n    verify_qlinearadd([5, 1, 7], [2, 7], [5, 2, 7])\n\n\n@tvm.testing.parametrize_targets\ndef test_qlinearmul(target, dev):\n    \"\"\"test_qlinearmul\"\"\"\n\n    def verify_qlinearmul(a_shape, b_shape, c_shape):\n\n        _ = np.random.random(a_shape).astype(\"float32\")\n        _ = np.random.random(b_shape).astype(\"float32\")\n\n        input_nodes = [\n            helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n            helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n        ]\n        input_names = [\n            \"a\",\n            \"b\",\n        ]\n\n        node = helper.make_node(\"Mul\", input_names, [\"C\"])\n        graph = helper.make_graph(\n            [node],\n            \"qlinearmul_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(c_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearmul_test\")\n        quantize_and_verify_with_ort(model, input_names, [a_shape, b_shape], target, dev)\n\n    verify_qlinearmul([7], [7], [7])\n    verify_qlinearmul([4, 2], [4, 2], [4, 2])\n    verify_qlinearmul([4, 2], [2], [4, 2])\n    verify_qlinearmul([5, 1, 7], [2, 7], [5, 2, 7])\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/11375\")\n@tvm.testing.parametrize_targets\ndef test_qlinearleakyrelu(target, dev):\n    \"\"\"test_qlinearleakyrelu\"\"\"\n\n    def verify_qlinearleakyrelu(inshape, kwargs):\n\n        in_array = np.random.random(inshape).astype(\"float32\")\n        node = helper.make_node(\"LeakyRelu\", [\"X\"], [\"Y\"], **kwargs)\n\n        graph = helper.make_graph(\n            [node],\n            \"qlinearRelu_test\",\n            inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(in_array.shape))],\n            outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(in_array.shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearRelu_test\")\n        args = (model, [\"X\"], [in_array.shape], target, dev)\n        if dev == \"cuda\":\n            quantize_and_verify_with_ort(*args, rtol=1e-2, atol=1e-2)\n        else:\n            quantize_and_verify_with_ort(*args)\n\n    verify_qlinearleakyrelu([2, 4, 5, 6], {\"alpha\": 0.25})\n    verify_qlinearleakyrelu([6, 5, 6, 7], {\"alpha\": 0.35})\n    verify_qlinearleakyrelu([5, 1, 4, 6], {\"alpha\": 0.65})\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/11375\")\n@tvm.testing.parametrize_targets\ndef test_qlinearsigmoid(target, dev):\n    \"\"\"test_qlinearsigmoid\"\"\"\n\n    def verify_qlinearsigmoid(a_shape):\n\n        _ = np.random.random(a_shape).astype(\"float32\")\n\n        input_nodes = [helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape))]\n\n        node = helper.make_node(\"Sigmoid\", [\"a\"], [\"B\"])\n        graph = helper.make_graph(\n            [node],\n            \"qlinearsigmoid_test\",\n            inputs=input_nodes,\n            outputs=[helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, list(a_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"qlinearsigmoid_test\")\n        quantize_and_verify_with_ort(model, [\"a\"], [a_shape], target, dev)\n\n    verify_qlinearsigmoid([4, 2])\n    verify_qlinearsigmoid([5])\n    verify_qlinearsigmoid([3, 4, 5])\n    verify_qlinearsigmoid([])\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_random_uniform(target, dev):\n    \"\"\"test_random_uniform\"\"\"\n\n    def get_random_uniform(shape, dtype=\"float32\", high=1.0, low=0.0, seed=None):\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        node = helper.make_node(\n            \"RandomUniform\", [], [\"out\"], shape=shape, dtype=ONNX_DTYPE, high=high, low=low\n        )\n        if seed is not None:\n            seed_attr = helper.make_attribute(\"seed\", seed)\n            node.attribute.append(seed_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"random_uniform_test\",\n            inputs=[],\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, shape)],\n        )\n        model = helper.make_model(graph, producer_name=\"random_uniform_test\")\n        return get_tvm_output_with_vm(model, [], target=target, dev=dev)\n\n    # Check that function runs and produces proper shape.\n    vals = get_random_uniform([10], dtype=\"float32\")\n    assert list(vals.shape) == [10]\n    assert vals.dtype == \"float32\"\n\n    # Test N-D tensor generation.\n    vals = get_random_uniform([1, 3, 100, 100], dtype=\"float32\")\n    assert list(vals.shape) == [1, 3, 100, 100]\n\n    # Check that bounds aren't exceeded.\n    vals = get_random_uniform(shape=[100], high=100.0, low=-100.0)\n    assert list(vals.shape) == [100]\n    assert all(vals >= -100) and all(vals <= 100)\n\n    # Check that a fixed seed produces the same values when run twice.\n    vals_1 = get_random_uniform(shape=[10], seed=1)\n    vals_2 = get_random_uniform(shape=[10], seed=1)\n    assert all(vals_1 == vals_2)\n\n    # Test against an expected output with a fixed seed.\n    real = get_random_uniform(shape=[10], seed=5.0)\n    expected = np.asarray(\n        [\n            0.043976,\n            0.96656,\n            0.292199,\n            0.904297,\n            0.25167,\n            0.521778,\n            0.778985,\n            0.085463,\n            0.939846,\n            0.194201,\n        ]\n    )\n    tvm.testing.assert_allclose(real, expected, rtol=1e-5)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_random_uniform_like(target, dev):\n    \"\"\"test_random_uniform_like\"\"\"\n\n    def get_random_uniform_like(input_, shape, dtype=None, high=1.0, low=0.0, seed=None):\n        node = helper.make_node(\"RandomUniformLike\", [\"in\"], [\"out\"], high=high, low=low)\n        if seed is not None:\n            seed_attr = helper.make_attribute(\"seed\", seed)\n            node.attribute.append(seed_attr)\n\n        ONNX_DTYPE = None\n        if dtype is not None:\n            ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n            dtype_attr = helper.make_attribute(\"dtype\", ONNX_DTYPE)\n            node.attribute.append(dtype_attr)\n        else:\n            dtype = input_.dtype\n            ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n\n        graph = helper.make_graph(\n            [node],\n            \"random_uniform_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", ONNX_DTYPE, shape)],\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, shape)],\n        )\n        model = helper.make_model(graph, producer_name=\"random_uniform_like_test\")\n        return get_tvm_output_with_vm(model, [input_], target=target, dev=dev)\n\n    # Check that function runs and produces proper shape and dtype.\n    shape = [10]\n    input_array = np.random.random(shape).astype(\"float32\")\n    vals = get_random_uniform_like(input_array, shape, dtype=\"float32\")\n    assert list(vals.shape) == [10]\n    assert vals.dtype == \"float32\"\n\n    # Test N-D tensor generation.\n    shape = [1, 3, 100, 100]\n    input_array = np.random.random(shape).astype(\"float32\")\n    vals = get_random_uniform_like(input_array, shape, dtype=\"float64\")\n    assert list(vals.shape) == shape\n    assert vals.dtype == \"float64\"\n\n    # Check that bounds aren't exceeded.\n    shape = [100]\n    input_array = np.random.random(shape).astype(\"float64\")\n    vals = get_random_uniform_like(input_array, shape, high=100.0, low=-100.0)\n    assert list(vals.shape) == shape\n    assert all(vals >= -100) and all(vals <= 100)\n\n    # Test against an expected output with a fixed seed.\n    shape = [10]\n    input_array = np.random.random(shape).astype(\"float32\")\n    real = get_random_uniform_like(input_array, shape=[10], seed=5.0)\n    expected = np.asarray(\n        [\n            0.043976,\n            0.96656,\n            0.292199,\n            0.904297,\n            0.25167,\n            0.521778,\n            0.778985,\n            0.085463,\n            0.939846,\n            0.194201,\n        ]\n    )\n    tvm.testing.assert_allclose(real, expected, rtol=1e-5)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_random_normal(target, dev):\n    \"\"\"test_random_normal\"\"\"\n\n    def get_random_normal(shape, dtype=\"float32\", scale=1.0, mean=0.0, seed=None):\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        node = helper.make_node(\n            \"RandomNormal\", [], [\"out\"], shape=shape, dtype=ONNX_DTYPE, scale=scale, mean=mean\n        )\n        if seed is not None:\n            seed_attr = helper.make_attribute(\"seed\", seed)\n            node.attribute.append(seed_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"random_normal_test\",\n            inputs=[],\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, shape)],\n        )\n        model = helper.make_model(graph, producer_name=\"random_normal_test\")\n        return get_tvm_output_with_vm(model, [], target=target, dev=dev)\n\n    # Test N-D tensor generation.\n    vals = get_random_normal([1, 3, 100, 100], dtype=\"float32\")\n    assert list(vals.shape) == [1, 3, 100, 100]\n    tvm.testing.assert_allclose(vals.mean(), 0.0, rtol=0.1, atol=0.1)\n    tvm.testing.assert_allclose(np.std(vals), 1.0, rtol=0.1, atol=0.1)\n\n    # Test mean=2.0 scale=10.0\n    vals = get_random_normal([1, 3, 100, 100], mean=2.0, scale=10.0, dtype=\"float32\")\n    assert list(vals.shape) == [1, 3, 100, 100]\n    tvm.testing.assert_allclose(vals.mean(), 2.0, rtol=0.1, atol=0.1)\n    tvm.testing.assert_allclose(np.std(vals), 10.0, rtol=0.1, atol=0.1)\n\n    # Check that a fixed seed produces the same values when run twice.\n    vals_1 = get_random_normal(shape=[10], seed=1.0)\n    vals_2 = get_random_normal(shape=[10], seed=1.0)\n    assert all(vals_1 == vals_2)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_random_normal_like(target, dev):\n    \"\"\"test_random_normal_like\"\"\"\n\n    def get_random_normal_like(input_, shape, dtype=\"float32\", scale=1.0, mean=0.0, seed=None):\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        node = helper.make_node(\n            \"RandomNormalLike\", [\"in\"], [\"out\"], dtype=ONNX_DTYPE, scale=scale, mean=mean\n        )\n        if seed is not None:\n            seed_attr = helper.make_attribute(\"seed\", seed)\n            node.attribute.append(seed_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"random_normal_like_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", ONNX_DTYPE, shape)],\n            outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, shape)],\n        )\n        model = helper.make_model(graph, producer_name=\"random_normal_like_test\")\n        return get_tvm_output_with_vm(model, [input_], target=target, dev=dev)\n\n    # Test N-D tensor generation.\n    shape = [1, 3, 100, 100]\n    input_array = np.random.random(shape).astype(\"float32\")\n    vals = get_random_normal_like(input_array, [1, 3, 100, 100], dtype=\"float32\")\n    assert list(vals.shape) == [1, 3, 100, 100]\n    tvm.testing.assert_allclose(vals.mean(), 0.0, rtol=0.1, atol=0.1)\n    tvm.testing.assert_allclose(np.std(vals), 1.0, rtol=0.1, atol=0.1)\n\n    # Test mean=2.0 scale=10.0\n    shape = [1, 3, 100, 100]\n    input_array = np.random.random(shape).astype(\"float32\")\n    vals = get_random_normal_like(\n        input_array, [1, 3, 100, 100], mean=2.0, scale=10.0, dtype=\"float32\"\n    )\n    assert list(vals.shape) == [1, 3, 100, 100]\n    tvm.testing.assert_allclose(vals.mean(), 2.0, rtol=0.1, atol=0.1)\n    tvm.testing.assert_allclose(np.std(vals), 10.0, rtol=0.1, atol=0.1)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_multinomial(target, dev):\n    def get_multinomial(input, shape, sample_size, seed=None):\n        IN_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(\"float32\")]\n        OUT_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(\"int32\")]\n        node = helper.make_node(\"Multinomial\", [\"in\"], [\"out\"], sample_size=sample_size)\n        if seed is not None:\n            seed_attr = helper.make_attribute(\"seed\", seed)\n            node.attribute.append(seed_attr)\n\n        graph = helper.make_graph(\n            [node],\n            \"multinomial_test\",\n            inputs=[helper.make_tensor_value_info(\"in\", IN_DTYPE, shape)],\n            outputs=[helper.make_tensor_value_info(\"out\", OUT_DTYPE, shape)],\n        )\n        model = helper.make_model(graph, producer_name=\"multinomial_test\")\n        return get_tvm_output_with_vm(model, [input], target=target, dev=dev)\n\n    # Test N-D tensor generation.\n    shape = [3]\n    sample_size = 2\n    probs = np.random.random(shape).astype(\"float32\")\n    indices = get_multinomial(probs, shape, sample_size)\n    # Since specific values are random, we'll check that the output shape is\n    # correct and the values chosen are all valid indices.\n    assert list(indices.shape) == [sample_size]\n    assert np.max(indices) < shape[-1]\n\n    # Test 2d multinomial\n    shape = [10, 5]\n    sample_size = 4\n    probs = np.random.random(shape).astype(\"float32\")\n    indices = get_multinomial(probs, shape, sample_size)\n    assert list(indices.shape) == [10, sample_size]\n    assert np.max(indices) < shape[-1]\n\n\n@tvm.testing.parametrize_targets\ndef test_convinteger(target, dev):\n    \"\"\"test_convinteger\"\"\"\n\n    def verify_convinteger(\n        x_shape,\n        w_shape,\n        y_shape,\n        padding,\n        kernel_shape,\n        strides,\n        dilations,\n        auto_pad=\"NOTSET\",\n        dtype=\"uint8\",\n    ):\n        x_array = np.random.randint(low=0, high=255, size=x_shape).astype(dtype)\n        w_array = np.random.uniform(low=0, high=255, size=w_shape).astype(dtype)\n        x_zero_point_array = np.random.randint(0, 255, size=[1]).astype(dtype)\n        w_zero_point_array = np.random.randint(0, 255, size=[1]).astype(dtype)\n\n        ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n        input_nodes = [\n            helper.make_tensor_value_info(\"x\", ONNX_DTYPE, list(x_shape)),\n            helper.make_tensor_value_info(\"w\", ONNX_DTYPE, list(w_shape)),\n        ]\n        initializer = [\n            helper.make_tensor(\"x_zero_point\", ONNX_DTYPE, [], x_zero_point_array),\n            helper.make_tensor(\"w_zero_point\", ONNX_DTYPE, [], w_zero_point_array),\n        ]\n        input_names = [\"x\", \"w\", \"x_zero_point\", \"w_zero_point\"]\n        input_values = [x_array, w_array]\n\n        if padding is None:\n            ## autopadding with unset default attributes\n            kwargs = {}\n            if not all(list(s == 1 for s in strides)):\n                kwargs[\"strides\"] = strides\n            if not all(list(d == 1 for d in dilations)):\n                kwargs[\"dilations\"] = dilations\n\n            node = helper.make_node(\n                \"ConvInteger\",\n                inputs=input_names,\n                outputs=[\"y\"],\n                # Default values for other attributes:\n                auto_pad=auto_pad,\n                **kwargs,\n            )\n        else:\n            node = helper.make_node(\n                \"ConvInteger\",\n                inputs=input_names,\n                outputs=[\"y\"],\n                kernel_shape=kernel_shape,\n                # Default values for other attributes:\n                strides=strides,\n                dilations=dilations,\n                # groups=1\n                pads=padding,\n            )\n\n        graph = helper.make_graph(\n            [node],\n            \"convinteger_test\",\n            inputs=input_nodes,\n            initializer=initializer,\n            outputs=[helper.make_tensor_value_info(\"y\", TensorProto.INT32, list(y_shape))],\n        )\n        model = helper.make_model(graph, producer_name=\"convinteger_test\")\n        # opt_level=1 will cause error\n        verify_with_ort_with_inputs(model, input_values, target=target, dev=dev, opt_level=2)\n\n    def repeat(num, dims):\n        return tuple(num for _ in range(dims))\n\n    # only support 2D ConvInteger because we only support qnn.conv2d for now.\n    dims = 2\n\n    # Convolution with padding\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        2 * repeat(1, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n\n    # Convolution with asymmetric padding\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(4, dims),\n        repeat(0, dims) + repeat(1, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n    # Convolution without padding\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        2 * repeat(0, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n    )\n    # Convolution with autopadding\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        None,\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Convolution with valid autopadding\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        None,\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(1, dims),\n        auto_pad=\"VALID\",\n    )\n    # Convolution with non uniform stride\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(3, dims),\n        None,\n        repeat(3, dims),\n        repeat(2, dims),\n        repeat(1, dims),\n        auto_pad=\"SAME_UPPER\",\n    )\n    # Convolution with dilation\n    verify_convinteger(\n        (1, 1) + repeat(5, dims),\n        (1, 1) + repeat(3, dims),\n        (1, 1) + repeat(5, dims),\n        2 * repeat(2, dims),\n        repeat(3, dims),\n        repeat(1, dims),\n        repeat(2, dims),\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_scan(target, dev):\n    \"\"\"test_scan\"\"\"\n\n    def verify_scan(\n        input_shapes,\n        output_shapes,\n        num_scan_inputs,\n        scan_input_axes,\n        scan_input_directions,\n        scan_output_axes,\n        scan_output_directions,\n        opset,\n    ):\n\n        body_input_shapes = copy.deepcopy(input_shapes)\n        num_state_inputs = len(input_shapes) - num_scan_inputs\n\n        if opset == 8:\n            for i in range(len(input_shapes)):\n                body_input_shapes[i].pop(0)\n            for i in range(num_state_inputs, len(input_shapes)):\n                body_input_shapes[i].pop(0)\n        else:\n            for i in range(num_state_inputs, len(input_shapes)):\n                body_input_shapes[i].pop(scan_input_axes[i - num_state_inputs])\n\n        initial0 = onnx.helper.make_tensor_value_info(\n            \"initial0\", onnx.TensorProto.FLOAT, body_input_shapes[0]\n        )\n        initial1 = onnx.helper.make_tensor_value_info(\n            \"initial1\", onnx.TensorProto.FLOAT, body_input_shapes[1]\n        )\n        input0 = onnx.helper.make_tensor_value_info(\n            \"input0\", onnx.TensorProto.FLOAT, body_input_shapes[2]\n        )\n        input1 = onnx.helper.make_tensor_value_info(\n            \"input1\", onnx.TensorProto.FLOAT, body_input_shapes[3]\n        )\n        input2 = onnx.helper.make_tensor_value_info(\n            \"input2\", onnx.TensorProto.FLOAT, body_input_shapes[4]\n        )\n        state0 = onnx.helper.make_tensor_value_info(\n            \"state0\", onnx.TensorProto.FLOAT, body_input_shapes[0]\n        )\n        scan_out0 = onnx.helper.make_tensor_value_info(\n            \"scan_out0\", onnx.TensorProto.FLOAT, body_input_shapes[0]\n        )\n        state1 = onnx.helper.make_tensor_value_info(\n            \"state1\", onnx.TensorProto.FLOAT, body_input_shapes[1]\n        )\n        scan_out1 = onnx.helper.make_tensor_value_info(\n            \"scan_out1\", onnx.TensorProto.FLOAT, body_input_shapes[1]\n        )\n        add_node = onnx.helper.make_node(\n            \"Add\",\n            inputs=[\"initial0\", \"input0\"],\n            outputs=[\"state0\"],\n        )\n        id_node_0 = onnx.helper.make_node(\n            \"Identity\",\n            inputs=[\"state0\"],\n            outputs=[\"scan_out0\"],\n        )\n        matmul_node = onnx.helper.make_node(\n            \"MatMul\",\n            inputs=[\"input1\", \"input2\"],\n            outputs=[\"matmul_out\"],\n        )\n        sub_node = onnx.helper.make_node(\n            \"Sub\",\n            inputs=[\"initial1\", \"matmul_out\"],\n            outputs=[\"state1\"],\n        )\n        id_node_1 = onnx.helper.make_node(\n            \"Identity\",\n            inputs=[\"state1\"],\n            outputs=[\"scan_out1\"],\n        )\n        scan_body = onnx.helper.make_graph(\n            [add_node, id_node_0, matmul_node, sub_node, id_node_1],\n            \"scan_body\",\n            [initial0, initial1, input0, input1, input2],\n            [state0, state1, scan_out0, scan_out1],\n        )\n        # create scan op node\n        scan_node = None\n        if opset == 8:\n            scan_node = onnx.helper.make_node(\n                \"Scan\",\n                inputs=[\"\", \"init0\", \"init1\", \"in0\", \"in1\", \"in2\"],\n                outputs=[\"s0\", \"s1\", \"scan0\", \"scan1\"],\n                num_scan_inputs=num_scan_inputs,\n                body=scan_body,\n            )\n        else:\n            scan_node = onnx.helper.make_node(\n                \"Scan\",\n                inputs=[\"init0\", \"init1\", \"in0\", \"in1\", \"in2\"],\n                outputs=[\"s0\", \"s1\", \"scan0\", \"scan1\"],\n                num_scan_inputs=num_scan_inputs,\n                body=scan_body,\n                scan_input_axes=scan_input_axes,\n                scan_input_directions=scan_input_directions,\n                scan_output_axes=scan_output_axes,\n                scan_output_directions=scan_output_directions,\n            )\n        input_info = [\n            helper.make_tensor_value_info(\"init0\", TensorProto.FLOAT, input_shapes[0]),\n            helper.make_tensor_value_info(\"init1\", TensorProto.FLOAT, input_shapes[1]),\n            helper.make_tensor_value_info(\"in0\", TensorProto.FLOAT, input_shapes[2]),\n            helper.make_tensor_value_info(\"in1\", TensorProto.FLOAT, input_shapes[3]),\n            helper.make_tensor_value_info(\"in2\", TensorProto.FLOAT, input_shapes[4]),\n        ]\n        out_info = [\n            helper.make_tensor_value_info(\"s0\", TensorProto.FLOAT, output_shapes[0]),\n            helper.make_tensor_value_info(\"s1\", TensorProto.FLOAT, output_shapes[1]),\n            helper.make_tensor_value_info(\"scan0\", TensorProto.FLOAT, output_shapes[2]),\n            helper.make_tensor_value_info(\"scan1\", TensorProto.FLOAT, output_shapes[3]),\n        ]\n        graph = helper.make_graph(\n            nodes=[scan_node],\n            name=\"scan_test\",\n            inputs=input_info,\n            outputs=out_info,\n        )\n        model = onnx.helper.make_model(graph, producer_name=\"scan-test\")\n        init0 = np.random.uniform(low=0, high=255, size=input_shapes[0]).astype(np.float32)\n        init1 = np.random.uniform(low=0, high=255, size=input_shapes[1]).astype(np.float32)\n        in0 = np.random.uniform(low=0, high=255, size=input_shapes[2]).astype(np.float32)\n        in1 = np.random.uniform(low=0, high=255, size=input_shapes[3]).astype(np.float32)\n        in2 = np.random.uniform(low=0, high=255, size=input_shapes[4]).astype(np.float32)\n        input_values = [init0, init1, in0, in1, in2]\n\n        verify_with_ort_with_inputs(\n            model,\n            input_values,\n            target=target,\n            dev=dev,\n            opt_level=2,\n            use_vm=True,\n            opset=opset,\n        )\n\n    # opset 8\n    input_shapes = [[2, 6, 7, 8], [2, 3, 3], [2, 5, 6, 7, 8], [2, 5, 3, 4], [2, 5, 4, 3]]\n    output_shapes = [[2, 6, 7, 8], [2, 3, 3], [2, 5, 6, 7, 8], [2, 5, 3, 3]]\n    # input_shapes, output_shapes, num_scan_inputs, scan_input_axes, scan_input_directions,\n    # scan_output_axes, scan_output_directions, opset\n    verify_scan(input_shapes, output_shapes, 3, [0] * 3, [0] * 3, [0] * 2, [0] * 2, 8)\n    # opset 9\n    input_shapes = [[6, 7, 8], [3, 3], [5, 6, 7, 8], [5, 3, 4], [5, 4, 3]]\n    output_shapes = [[6, 7, 8], [3, 3], [5, 6, 7, 8], [5, 3, 3]]\n    verify_scan(input_shapes, output_shapes, 3, [0] * 3, [0] * 3, [0] * 2, [0] * 2, 9)\n\n    input_shapes = [[6, 7, 8], [3, 3], [5, 6, 7, 8], [3, 4, 5], [4, 5, 3]]\n    output_shapes = [[6, 7, 8], [3, 3], [6, 5, 7, 8], [3, 5, 3]]\n    verify_scan(input_shapes, output_shapes, 3, [0, 2, 1], [1] * 3, [1] * 2, [1] * 2, 9)\n    # Negative axes\n    input_shapes = [[6, 7, 8], [3, 3], [5, 6, 7, 8], [3, 4, 5], [4, 5, 3]]\n    output_shapes = [[6, 7, 8], [3, 3], [6, 5, 7, 8], [3, 5, 3]]\n    verify_scan(input_shapes, output_shapes, 3, [-4, -1, -2], [1] * 3, [-3, -2], [1] * 2, 9)\n\n\n@tvm.testing.parametrize_targets\ndef test_linear_regressor(target, dev):\n    \"\"\"test_linear_regressor\"\"\"\n\n    def verify_linear_regressor(a_shape, c_shape, i_shape, targets=1, batch=1):\n        a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n        out_shape = (batch, targets)\n\n        coefficients = np.random.uniform(size=c_shape).astype(\"float32\")\n        intercepts = np.random.uniform(size=i_shape).astype(\"float32\")\n\n        mul_node = helper.make_node(\n            \"LinearRegressor\",\n            [\"a\"],\n            [\"out\"],\n            coefficients=coefficients,\n            intercepts=intercepts,\n            targets=targets,\n            domain=\"ai.onnx.ml\",\n        )\n\n        graph = helper.make_graph(\n            [mul_node],\n            \"LinearRegressor_test\",\n            inputs=[\n                helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n            ],\n            outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, out_shape)],\n        )\n        model = helper.make_model(\n            graph,\n            producer_name=\"LinearRegressor_test\",\n            opset_imports=[\n                onnx.helper.make_opsetid(\"ai.onnx.ml\", 1),\n            ],\n        )\n        verify_with_ort_with_inputs(model, [a_array], target=target, dev=dev)\n\n    verify_linear_regressor((1, 3), (3), (1))\n    verify_linear_regressor((2, 10), (10), (1), batch=2)\n    verify_linear_regressor((1, 3), (30), (10), targets=10)\n    verify_linear_regressor((10, 3), (30), (10), targets=10, batch=10)\n    verify_linear_regressor((1, 4), (3), (1))\n\n\n@tvm.testing.parametrize_targets\ndef test_sequence(target, dev):\n    \"\"\"test_sequence\"\"\"\n\n    def verify_sequence_ops(tensor_shape, num_tensors, axis=0, position=None, new_axis=None):\n        tensor_shape = list(tensor_shape)\n        tensor_values = []\n        for i in range(num_tensors):\n            tensor_values.append(np.random.uniform(size=tensor_shape).astype(\"float32\"))\n\n        # Create an input for each tensor.\n        input_tensor_names = []\n        for i in range(num_tensors):\n            name = f\"input_tensor_{i}\"\n            input_tensor_names.append(name)\n\n        # Test creating a tensor sequence.\n        construct_node = helper.make_node(\n            \"SequenceConstruct\",\n            inputs=input_tensor_names,\n            outputs=[\"sequence\"],\n        )\n\n        insert_inputs = [\"sequence\", input_tensor_names[0]]\n        position_node = None\n        if position is not None:\n            insert_inputs.append(\"position\")\n            position_node = make_constant_node(\"position\", TensorProto.INT32, (), [position])\n\n        # Test sequence insertion.\n        insert_node = helper.make_node(\n            \"SequenceInsert\", inputs=insert_inputs, outputs=[\"inserted_sequence\"]\n        )\n\n        # Test sequence concatenation.\n        concat_node = helper.make_node(\n            \"ConcatFromSequence\", inputs=[\"inserted_sequence\"], outputs=[\"output\"], axis=axis\n        )\n\n        if new_axis is not None:\n            new_axis_attr = helper.make_attribute(\"new_axis\", new_axis)\n            concat_node.attribute.append(new_axis_attr)\n\n        # Create input and output tensors.\n        graph_inputs = []\n        for name in input_tensor_names:\n            input_tensor = helper.make_tensor_value_info(name, TensorProto.FLOAT, tensor_shape)\n            graph_inputs.append(input_tensor)\n\n        # Construct output tensor.\n        output_shape = tensor_shape\n        if new_axis is not None:\n            output_shape.insert(axis, 1)\n            output_shape[axis] = num_tensors + 1\n        else:\n            output_shape[axis] = (num_tensors + 1) * output_shape[axis]\n        graph_outputs = [helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, output_shape)]\n\n        graph_nodes = []\n        if position_node is not None:\n            graph_nodes.append(position_node)\n        graph_nodes += [construct_node, insert_node, concat_node]\n\n        graph = helper.make_graph(\n            graph_nodes,\n            \"Sequence_test\",\n            inputs=graph_inputs,\n            outputs=graph_outputs,\n        )\n        model = helper.make_model(\n            graph,\n            producer_name=\"Sequence_test\",\n        )\n\n        verify_with_ort_with_inputs(model, tensor_values, target=target, dev=dev)\n\n    verify_sequence_ops((10, 3), 2)\n    verify_sequence_ops((3, 3, 3, 3), 4, position=3)\n    verify_sequence_ops((3, 3, 3, 3), 4, axis=2)\n    verify_sequence_ops((3, 3, 3, 3), 4, axis=2, new_axis=1)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/paddlepaddle/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nfrom pathlib import Path\nimport shutil\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nimport pytest\n\nimport paddle\n\npaddle.disable_signal_handler()\nimport paddle.nn as nn\n\nPADDLE_TEST_DATA_ROOT_PATH = Path(Path(\"~\").expanduser(), \".tvm_test_data\", \"paddle\")\nPADDLE_TEST_DATA_ROOT_PATH.mkdir(parents=True, exist_ok=True)\ncached_program = list()\n\n\ndef assert_shapes_match(tru, est):\n    if tru.shape != est.shape:\n        msg = \"Output shapes {} and {} don't match\"\n        raise AssertionError(msg.format(tru.shape, est.shape))\n\n\ndef get_paddle_model(func, input_spec):\n    global PADDLE_TEST_DATA_ROOT_PATH\n    global cached_program\n    model_path = Path(PADDLE_TEST_DATA_ROOT_PATH, \"model\")\n\n    paddle.jit.save(func, str(model_path), input_spec=input_spec)\n    baseline_model = paddle.jit.load(str(model_path))\n    if len(cached_program) >= 4:\n        cached_program = list()\n    cached_program.append(baseline_model._get_program_holder())\n\n    shutil.rmtree(str(PADDLE_TEST_DATA_ROOT_PATH))\n    return baseline_model\n\n\ndef verify_model(func, input_data, rtol=1e-5, atol=1e-5):\n    if not (isinstance(input_data, (tuple, list))):\n        input_data = [input_data]\n\n    input_spec = []\n    input_names = []\n    input_shape_dict = {}\n    compiled_input = {}\n    for idx, data in enumerate(input_data):\n        input_name = \"input{}\".format(idx)\n        input_spec.append(\n            paddle.static.InputSpec(dtype=data.dtype, shape=data.shape, name=input_name)\n        )\n        input_names.append(input_name)\n        input_shape_dict[input_name] = data.shape\n        if isinstance(data, np.ndarray):\n            compiled_input[input_name] = data\n        else:\n            compiled_input[input_name] = data.numpy()\n\n    baseline_model = get_paddle_model(func, input_spec)\n    baseline_outputs = baseline_model(*[input[:] for input in input_data])\n\n    # get paddle outputs\n    if isinstance(baseline_outputs, (tuple, list)):\n        baseline_outputs = tuple(out.numpy() for out in baseline_outputs)\n    else:\n        baseline_outputs = (baseline_outputs.numpy(),)\n\n    mod, params = relay.frontend.from_paddle(baseline_model, input_shape_dict)\n    compiled_names = []\n    for arg in mod[\"main\"].params:\n        assert arg.name_hint in input_names or arg.name_hint in params\n        if arg.name_hint in input_names:\n            compiled_names.append(arg.name_hint)\n\n    with tvm.transform.PassContext(opt_level=3):\n        for target, dev in tvm.testing.enabled_targets():\n            lib = relay.build(mod, target=target, params=params)\n            gmod = graph_executor.GraphModule(lib[\"default\"](dev))\n            for name in compiled_names:\n                gmod.set_input(name, compiled_input[name])\n            gmod.run()\n\n            for i, baseline_output in enumerate(baseline_outputs):\n                compiled_output = gmod.get_output(i).numpy()\n\n                assert_shapes_match(baseline_output, compiled_output)\n                tvm.testing.assert_allclose(baseline_output, compiled_output, rtol=rtol, atol=atol)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_add_subtract():\n    input_shape = [10]\n\n    @paddle.jit.to_static\n    def add_subtract(inputs):\n        return paddle.subtract(paddle.add(inputs, inputs), inputs)\n\n    @paddle.jit.to_static\n    def add_subtract2(inputs):\n        return inputs + 1 - 2\n\n    @paddle.jit.to_static\n    def add_subtract3(inputs1, inputs2):\n        ones = paddle.ones([10], dtype=\"float32\")\n        return inputs1 + ones - inputs2\n\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(add_subtract, input_data)\n    verify_model(add_subtract2, input_data)\n    input_data2 = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(add_subtract3, [input_data, input_data2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_addmm():\n    class Addmm(nn.Layer):\n        def __init__(self, alpha=1.0, beta=1.0):\n            super(Addmm, self).__init__()\n            self.alpha = alpha\n            self.beta = beta\n\n        @paddle.jit.to_static\n        def forward(self, inputs, x, y):\n            return paddle.addmm(inputs, x, y, self.alpha, self.beta)\n\n    input_shapes = [[10, 10], [1, 1], [7, 1]]\n    x_shapes = [[10, 3], [5, 6], [7, 7]]\n    y_shapes = [[3, 10], [6, 2], [7, 3]]\n    input_shapes = [[10, 10]]\n    x_shapes = [[10, 3]]\n    y_shapes = [[3, 10]]\n\n    for i in range(len(input_shapes)):\n        input_data = paddle.rand(input_shapes[i], dtype=\"float32\")\n        x_data = paddle.rand(x_shapes[i], dtype=\"float32\")\n        y_data = paddle.rand(y_shapes[i], dtype=\"float32\")\n        verify_model(Addmm(), input_data=[input_data, x_data, y_data])\n        verify_model(Addmm(0.5, 0.3), input_data=[input_data, x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_arg_max_min():\n    class ArgMax(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.argmax(inputs)\n\n    class ArgMax1(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmax(axis=1)\n\n    class ArgMax2(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmax(axis=1, keepdim=False)\n\n    class ArgMax3(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmax(axis=2, keepdim=True)\n\n    class ArgMin(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.argmin(inputs)\n\n    class ArgMin1(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmin(axis=1)\n\n    class ArgMin2(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmax(axis=1, keepdim=False)\n\n    class ArgMin3(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return inputs.argmin(axis=2, keepdim=True)\n\n    input_shapes = [[256], [5, 28], [10, 5, 4], [1, 3, 8, 8]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(ArgMax(), input_data=input_data)\n        verify_model(ArgMin(), input_data=input_data)\n    for input_shape in input_shapes[1:]:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(ArgMax1(), input_data=input_data)\n        verify_model(ArgMax2(), input_data=input_data)\n        verify_model(ArgMin1(), input_data=input_data)\n        verify_model(ArgMin2(), input_data=input_data)\n    for input_shape in input_shapes[2:]:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(ArgMax3(), input_data=input_data)\n        verify_model(ArgMin3(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argsort():\n    class ArgSort1(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.argsort(inputs)\n\n    class ArgSort2(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.argsort(inputs, axis=0, descending=True)\n\n    class ArgSort3(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.argsort(inputs, axis=-1, descending=True)\n\n    input_shapes = [[256], [10, 20], [10, 5, 3], [1, 3, 5, 5]]\n    for input_shape in input_shapes:\n        # Avoid duplicate elements in the array which will bring\n        # different results with different sort algorithms\n        np.random.seed(13)\n        np_data = np.random.choice(range(-5000, 5000), np.prod(input_shape), replace=False)\n        input_data = paddle.to_tensor(np_data.reshape(input_shape).astype(\"int64\"))\n        verify_model(ArgSort1(), [input_data])\n        verify_model(ArgSort2(), [input_data])\n        verify_model(ArgSort3(), [input_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_assign():\n    @paddle.jit.to_static\n    def assign(inputs):\n        return paddle.assign(inputs)\n\n    @paddle.jit.to_static\n    def assign_value(inputs):\n        x = paddle.to_tensor(np.array([3]).astype(\"float32\"))\n        return inputs + x\n\n    input_shape = [2, 3]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(\n        assign,\n        [\n            input_data,\n        ],\n    )\n    input_data2 = np.random.randint(100, size=input_shape)\n    verify_model(\n        assign,\n        [\n            input_data2,\n        ],\n    )\n    verify_model(assign_value, [input_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_batch_norm():\n    class BatchNorm1D(nn.Layer):\n        def __init__(self):\n            super(BatchNorm1D, self).__init__()\n            self.batch_norm = nn.BatchNorm1D(2)\n\n        @paddle.jit.to_static\n        def forward(self, input_data):\n            return self.batch_norm(input_data)\n\n    class BatchNorm2D(nn.Layer):\n        def __init__(self):\n            super(BatchNorm2D, self).__init__()\n            self.batch_norm = nn.BatchNorm2D(2)\n\n        @paddle.jit.to_static\n        def forward(self, input_data):\n            return self.batch_norm(input_data)\n\n    class BatchNorm3D(nn.Layer):\n        def __init__(self):\n            super(BatchNorm3D, self).__init__()\n            self.batch_norm = nn.BatchNorm3D(2)\n\n        @paddle.jit.to_static\n        def forward(self, input_data):\n            return self.batch_norm(input_data)\n\n    input_data = paddle.rand((2, 2, 3), dtype=\"float32\")\n    verify_model(BatchNorm1D(), input_data=input_data)\n    input_data = paddle.rand((2, 2, 2, 3), dtype=\"float32\")\n    verify_model(BatchNorm2D(), input_data=input_data)\n    input_data = paddle.rand((2, 2, 2, 2, 3), dtype=\"float32\")\n    verify_model(BatchNorm3D(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_bmm():\n    class Bmm(nn.Layer):\n        def __init__(self):\n            super(Bmm, self).__init__()\n\n        @paddle.jit.to_static\n        def forward(self, x, y):\n            return paddle.bmm(x, y)\n\n    x_shapes = [[10, 3, 4], [5, 6, 2], [1, 7, 7]]\n    y_shapes = [[10, 4, 5], [5, 2, 7], [1, 7, 3]]\n    for i in range(len(x_shapes)):\n        x_data = paddle.rand(x_shapes[i], dtype=\"float32\")\n        y_data = paddle.rand(y_shapes[i], dtype=\"float32\")\n        verify_model(Bmm(), input_data=[x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_cast():\n    @paddle.jit.to_static\n    def cast1(inputs, dtype=\"uint8\"):\n        return paddle.cast(inputs, dtype)\n\n    @paddle.jit.to_static\n    def cast2(inputs, dtype=\"int64\"):\n        return inputs.cast(dtype)\n\n    input_shape = [2, 3]\n    input_data = paddle.rand(input_shape, dtype=\"float32\") * 100\n    verify_model(\n        cast1,\n        [\n            input_data,\n        ],\n    )\n    verify_model(\n        cast2,\n        [\n            input_data,\n        ],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_check_tensor():\n    class IsFinite(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.cast(paddle.isfinite(inputs), \"int32\")\n\n    class IsNan(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.cast(paddle.isnan(inputs), \"int32\")\n\n    class IsInf(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.cast(paddle.isinf(inputs), \"int32\")\n\n    input_shapes = [[32], [8, 32], [2, 5, 20], [2, 3, 8, 8], [2, 2, 3, 6, 6]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(IsFinite(), input_data=input_data)\n        verify_model(IsNan(), input_data=input_data)\n        verify_model(IsInf(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_clip():\n    class Clip1(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.clip(inputs, min=0.3, max=0.55)\n\n    class Clip2(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs, max_value):\n            return paddle.clip(inputs, max=max_value)\n\n    class Clip3(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs, min_value):\n            return paddle.clip(inputs, min=min_value)\n\n    class Clip4(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs, min_value, max_value):\n            return paddle.clip(inputs, min=min_value, max=max_value)\n\n    input_data = paddle.rand((2, 2, 2, 3), dtype=\"float32\")\n    max_value = paddle.to_tensor([0.55])\n    min_value = paddle.to_tensor([0.3])\n    verify_model(Clip1(), input_data)\n    verify_model(Clip2(), [input_data, max_value])\n    verify_model(Clip3(), [input_data, min_value])\n    verify_model(Clip4(), [input_data, min_value, max_value])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_concat_unsqueeze():\n    @paddle.jit.to_static\n    def concat_unsqueeze1(inputs):\n        return paddle.concat([inputs[:, 0].unsqueeze(1), inputs[:, 1].unsqueeze(1)], axis=1)\n\n    @paddle.jit.to_static\n    def concat_unsqueeze2(inputs):\n        a = (inputs[:, :, 0] + 2) * 7\n        b = (inputs[:, :, 1] + 3) * 11\n        c = (inputs[:, :, 2] + 5) * 13\n        return paddle.concat([paddle.unsqueeze(t, axis=2) for t in [a, b, c]], axis=2)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(concat_unsqueeze1, input_data=input_data)\n    verify_model(concat_unsqueeze2, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_cumsum():\n    @paddle.jit.to_static\n    def cusum1(inputs):\n        return paddle.cumsum(inputs)\n\n    @paddle.jit.to_static\n    def cusum2(inputs):\n        return paddle.cumsum(inputs, axis=0)\n\n    @paddle.jit.to_static\n    def cusum3(inputs):\n        return paddle.cumsum(inputs, axis=1)\n\n    input_data = paddle.randint(0, 100, (10, 10), dtype=paddle.int32)\n    verify_model(cusum1, [input_data])\n    verify_model(cusum1, [input_data.astype(paddle.int64)])\n    verify_model(\n        cusum2,\n        [\n            input_data,\n        ],\n    )\n    verify_model(\n        cusum3,\n        [\n            input_data,\n        ],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_conv():\n    class Conv2D1(nn.Layer):\n        def __init__(self, stride=1, padding=0, dilation=1, groups=1, padding_mode=\"zeros\"):\n            super(Conv2D1, self).__init__()\n            self.conv = nn.Conv2D(\n                3,\n                6,\n                3,\n                stride=stride,\n                padding=padding,\n                dilation=dilation,\n                groups=groups,\n                padding_mode=padding_mode,\n            )\n            self.softmax = nn.Softmax()\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.softmax(self.conv(inputs))\n\n    input_shapes = [[1, 3, 10, 10], [1, 3, 12, 12]]\n\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Conv2D1(), input_data=input_data)\n        verify_model(Conv2D1(stride=2, padding=\"VALID\", dilation=3), input_data=input_data)\n        verify_model(Conv2D1(stride=2, padding=\"SAME\", dilation=3), input_data=input_data)\n        verify_model(\n            Conv2D1(stride=2, padding=3, dilation=3, padding_mode=\"replicate\"),\n            input_data=input_data,\n        )\n        verify_model(Conv2D1(stride=2, padding=\"SAME\", dilation=2, groups=3), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_conv_transpose():\n    class Conv2DTranspose(nn.Layer):\n        def __init__(self, stride=1, padding=0, dilation=1, groups=1, padding_mode=\"zeros\"):\n            super(Conv2DTranspose, self).__init__()\n            self.conv = nn.Conv2DTranspose(\n                6,\n                3,\n                3,\n                stride=stride,\n                padding=padding,\n                dilation=dilation,\n                groups=groups,\n            )\n            self.softmax = nn.Softmax()\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.softmax(self.conv(inputs))\n\n    input_shapes = [[1, 6, 10, 10], [2, 6, 8, 8]]\n\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Conv2DTranspose(), input_data=input_data)\n        verify_model(Conv2DTranspose(stride=2, padding=\"VALID\"), input_data=input_data)\n        verify_model(Conv2DTranspose(stride=2, padding=\"SAME\", dilation=1), input_data=input_data)\n        verify_model(Conv2DTranspose(stride=2, padding=3), input_data=input_data)\n        verify_model(Conv2DTranspose(stride=3, padding=\"SAME\", groups=1), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dot():\n    class Dot(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, x, y):\n            return paddle.dot(x, y)\n\n    input_shapes = [[128], [8, 24]]\n    for input_shape in input_shapes:\n        x_data = paddle.rand(input_shape, dtype=\"float32\")\n        y_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Dot(), input_data=[x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dropout():\n    @paddle.jit.to_static\n    def dropout(inputs):\n        return nn.functional.dropout(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(dropout, input_data=input_data[0, 0])\n    verify_model(dropout, input_data=input_data)\n\n\ndef test_forward_elemwise():\n    class ElemwiseAPI(nn.Layer):\n        def __init__(self, api_name):\n            super(ElemwiseAPI, self).__init__()\n            self.api_name_ = api_name\n            for candidate in (paddle, paddle.nn.functional):\n                self.func = getattr(candidate, api_name, None)\n                if self.func:\n                    break\n\n        @paddle.jit.to_static\n        def forward(self, input1, input2):\n            y = self.func(input1, input2)\n            if \"equal\" in self.api_name_ or \"than\" in self.api_name_:\n                # for compare operation, cast boolean result to int32\n                y = paddle.cast(y, \"int32\")\n            return y\n\n    api_list = [\n        \"equal\",\n        \"floor_divide\",\n        \"greater_equal\",\n        \"greater_than\",\n        \"less_equal\",\n        \"less_than\",\n        \"maximum\",\n        \"minimum\",\n        \"pow\",\n    ]\n    x_shapes = [[128], [8, 20], [4, 20, 3], [2, 3, 8, 8], [2, 3, 3, 9, 9]]\n    y_shapes = [[1], [8, 20], [4, 1, 1], [2, 3, 8, 8], [2, 3, 3, 9, 1]]\n    for x_shape, y_shape in zip(x_shapes, y_shapes):\n        x_data = paddle.randint(1, 10, x_shape, dtype=\"int32\")\n        y_data = paddle.randint(1, 10, y_shape, dtype=\"int32\")\n        for api_name in api_list:\n            if api_name == \"pow\":\n                # only support float for pow\n                x_data = x_data.astype(\"float32\")\n                y_data = y_data.astype(\"float32\")\n            verify_model(ElemwiseAPI(api_name), [x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_expand():\n    @paddle.jit.to_static\n    def expand1(inputs):\n        return paddle.expand(inputs, shape=[2, 128])\n\n    @paddle.jit.to_static\n    def expand2(inputs):\n        return paddle.expand(inputs, shape=[2, 1, 4, 16])\n\n    @paddle.jit.to_static\n    def expand3(inputs):\n        return paddle.expand(inputs, shape=[2, 1, 3, 7, 7])\n\n    @paddle.jit.to_static\n    def expand4(inputs):\n        shape = paddle.to_tensor(np.array([2, 128]).astype(\"int32\"))\n        return paddle.expand(inputs, shape=shape)\n\n    @paddle.jit.to_static\n    def expand5(inputs):\n        shape = paddle.to_tensor(np.array([2, 1, 4, 16]).astype(\"int32\"))\n        return paddle.expand(inputs, shape=shape)\n\n    @paddle.jit.to_static\n    def expand6(inputs):\n        shape = paddle.to_tensor(np.array([2, 1, 3, 7, 7]).astype(\"int32\"))\n        return paddle.expand(inputs, shape=shape)\n\n    data = paddle.rand([128], dtype=\"float32\")\n    verify_model(expand1, input_data=[data])\n    verify_model(expand4, input_data=[data])\n    data = paddle.rand([4, 16], dtype=\"float32\")\n    verify_model(expand2, input_data=[data])\n    verify_model(expand5, input_data=[data])\n    data = paddle.rand([1, 3, 7, 7], dtype=\"float32\")\n    verify_model(expand3, input_data=[data])\n    verify_model(expand6, input_data=[data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_expand_as():\n    class ExpandAs(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, x, y):\n            z = paddle.expand_as(x, y)\n            z += y\n            return z\n\n    x_shapes = [[1], [8, 128], [8, 1, 1], [2, 3, 229, 229], [2, 3, 3, 224, 1]]\n    y_shapes = [[128], [8, 128], [8, 200, 300], [2, 3, 229, 229], [2, 3, 3, 224, 224]]\n    for x_shape, y_shape in zip(x_shapes, y_shapes):\n        x_data = paddle.rand(x_shape, dtype=\"float32\")\n        y_data = paddle.rand(y_shape, dtype=\"float32\")\n        verify_model(ExpandAs(), [x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_flatten():\n    class Flatten(nn.Layer):\n        def __init__(self, start_axis=0, stop_axis=-1):\n            super(Flatten, self).__init__()\n            self.start_axis = start_axis\n            self.stop_axis = stop_axis\n\n        @paddle.jit.to_static\n        def forward(self, x):\n            return paddle.flatten(x, start_axis=self.start_axis, stop_axis=self.stop_axis)\n\n    input_data = paddle.rand([2, 3, 4, 5, 2], dtype=\"float32\")\n    verify_model(Flatten(), input_data=input_data)\n    verify_model(Flatten(2), input_data=input_data)\n    verify_model(Flatten(2, -2), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gather():\n    class Gather(nn.Layer):\n        def __init__(self, axis=None):\n            super(Gather, self).__init__()\n            self.axis = axis\n\n        @paddle.jit.to_static\n        def forward(self, x, index):\n            return paddle.gather(x, index, axis=self.axis)\n\n    x_shapes = [[20, 10], [10, 10, 8]]\n    index = paddle.to_tensor(np.array([1, 3, 5]).astype(\"int64\"))\n    for x_shape in x_shapes:\n        x_data = paddle.rand(x_shape, dtype=\"float32\")\n        verify_model(Gather(), [x_data, index])\n        verify_model(Gather(axis=0), [x_data, index])\n        verify_model(Gather(axis=1), [x_data, index])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gather_nd():\n    class GatherNd(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, x, index):\n            return paddle.gather_nd(x, index)\n\n    x_shapes = [[20], [8, 8], [4, 5, 6], [3, 4, 3, 5]]\n    y_shapes = [[2, 1], [2], [1, 2, 3], [3]]\n    for x_shape, y_shape in zip(x_shapes, y_shapes):\n        x_data = paddle.rand(x_shape, dtype=\"float32\")\n        y_data = paddle.randint(low=0, high=3, shape=y_shape, dtype=\"int64\")\n        verify_model(GatherNd(), [x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_group_norm():\n    class GroupNorm(nn.Layer):\n        def __init__(self, channels, groups):\n            super(GroupNorm, self).__init__()\n            self.group_norm = paddle.nn.GroupNorm(num_channels=channels, num_groups=groups)\n\n        def forward(self, inputs):\n            return self.group_norm(inputs)\n\n    input_shapes = [[1, 4, 6, 6], [2, 2, 4, 7], [2, 8, 1, 1]]\n    for input_shape in input_shapes:\n        num_channels = input_shape[1]\n        input_data = paddle.uniform(input_shape)\n        verify_model(GroupNorm(num_channels, 1), input_data, rtol=1e-4, atol=1e-4)\n        verify_model(GroupNorm(num_channels, 2), input_data, rtol=1e-4, atol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_scatter():\n    class Scatter(nn.Layer):\n        def __init__(self, overwrite=True):\n            super(Scatter, self).__init__()\n            self.overwrite = overwrite\n\n        @paddle.jit.to_static\n        def forward(self, x, index, updates):\n            return paddle.scatter(x, index, updates, overwrite=self.overwrite)\n\n    x_shapes = [[10], [4, 5], [6, 4, 5], [4, 5, 6, 4]]\n    index_shapes = [[10], [4], [6], [4]]\n    for x_shape, index_shape in zip(x_shapes, index_shapes):\n        x_data = paddle.rand(x_shape, dtype=\"float32\")\n        updates = paddle.rand(x_shape, dtype=\"float32\") + 1.0\n        index = paddle.randint(low=0, high=3, shape=index_shape)\n        verify_model(Scatter(), [x_data, index, updates])\n        verify_model(Scatter(False), [x_data, index, updates])\n\n\ndef test_forward_scatter_nd():\n    @paddle.jit.to_static\n    def scatter_nd(index, updates):\n        shape = [3, 5, 9, 10]\n        return paddle.scatter_nd(index, updates, shape)\n\n    @paddle.jit.to_static\n    def scatter_nd_add(x, index, updates):\n        return paddle.scatter_nd_add(x, index, updates)\n\n    index_data = np.array([[1, 1], [0, 1], [1, 3]]).astype(np.int64)\n    index = paddle.to_tensor(index_data)\n    updates = paddle.rand(shape=[3, 9, 10], dtype=\"float32\")\n    verify_model(scatter_nd, [index, updates])\n    x = paddle.rand(shape=[3, 5, 4, 9, 10], dtype=\"float32\")\n    updates = paddle.rand(shape=[3, 2, 9, 10], dtype=\"float32\")\n    index = paddle.randint(0, 3, shape=[3, 2, 3])\n    verify_model(scatter_nd_add, [x, index, updates])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_shape_full():\n    @paddle.jit.to_static\n    def full1(inputs):\n        return paddle.full(paddle.shape(inputs), 3.14)\n\n    @paddle.jit.to_static\n    def full2(inputs):\n        return paddle.full(paddle.shape(inputs), 1.0, dtype=inputs.dtype)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(full1, input_data=[input_data])\n    verify_model(full2, input_data=[input_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_split():\n    class Split(nn.Layer):\n        def __init__(\n            self, axis=None, num_or_sections=None, axis_is_tensor=False, num_is_tensor=False\n        ):\n            super(Split, self).__init__()\n            self.axis = axis\n            self.num_or_sections = num_or_sections\n            self.axis_is_tensor = axis_is_tensor\n            self.num_is_tensor = num_is_tensor\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            axis = self.axis\n            if self.axis_is_tensor:\n                axis = paddle.to_tensor(axis, dtype=\"int32\")\n            num_or_sections = self.num_or_sections\n            if self.num_is_tensor:\n                new_num_or_sections = []\n                for i in num_or_sections:\n                    if isinstance(i, list):\n                        i = paddle.to_tensor(i, dtype=\"int32\")\n                    new_num_or_sections.append(i)\n                num_or_sections = new_num_or_sections\n            return paddle.split(inputs, num_or_sections=num_or_sections, axis=axis)\n\n    input_shape = [3, 6, 2]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(Split(axis=1, num_or_sections=3), input_data=input_data)\n    verify_model(\n        Split(axis=[1], num_or_sections=[2, 3, 1], axis_is_tensor=True), input_data=input_data\n    )\n    verify_model(\n        Split(axis=1, num_or_sections=[2, -1, [3]], num_is_tensor=True), input_data=input_data\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_squeeze():\n    class Squeeze(nn.Layer):\n        def __init__(self, axis=None):\n            super(Squeeze, self).__init__()\n            self.axis = axis\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return paddle.squeeze(inputs, axis=self.axis)\n\n    input_shapes = [[1, 1, 3, 1, 5], [5, 1, 6]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Squeeze(axis=None), input_data=input_data)\n        verify_model(Squeeze(axis=1), input_data=input_data)\n    input_data = paddle.rand([1], dtype=\"float32\")\n    verify_model(Squeeze(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_ones_like():\n    @paddle.jit.to_static\n    def ones_like1(inputs):\n        return paddle.ones_like(inputs)\n\n    @paddle.jit.to_static\n    def ones_like2(inputs):\n        return paddle.ones_like(inputs, dtype=\"int32\")\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(ones_like1, input_data=input_data)\n    verify_model(ones_like2, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gelu():\n    @paddle.jit.to_static\n    def gelu(inputs):\n        return nn.functional.gelu(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(gelu, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_hard_sigmoid():\n    @paddle.jit.to_static\n    def hard_sigmoid(inputs):\n        return nn.functional.hardsigmoid(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(hard_sigmoid, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_hard_swish():\n    @paddle.jit.to_static\n    def hard_swish(inputs):\n        return nn.functional.hardswish(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(hard_swish, input_data=input_data)\n\n\ndef test_forward_instance_norm():\n    class InstanceNorm(nn.Layer):\n        def __init__(self, num_features, epsilon=1e-05):\n            super(InstanceNorm, self).__init__()\n            self.instance_norm = paddle.nn.InstanceNorm2D(\n                num_features=num_features, epsilon=epsilon\n            )\n\n        def forward(self, inputs):\n            return self.instance_norm(inputs)\n\n    input_shapes = [[2, 2, 2, 3], [1, 3, 5, 5]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(InstanceNorm(input_shape[1]), input_data)\n        verify_model(InstanceNorm(input_shape[1], 1e-03), input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_interpolate():\n    class Interpolate(nn.Layer):\n        def __init__(\n            self,\n            mode=\"nearest\",\n            align_corners=False,\n            align_mode=0,\n            data_format=\"NCHW\",\n            use_scale=False,\n            use_list=False,\n            use_const=False,\n            use_scaler=False,\n        ):\n            super(Interpolate, self).__init__()\n            self.mode = mode\n            self.align_corners = align_corners\n            self.align_mode = align_mode\n            self.data_format = data_format\n            self.use_scale = use_scale\n            self.use_list = use_list\n            self.use_const = use_const\n            self.use_scaler = use_scaler\n\n        @paddle.jit.to_static\n        def forward(self, x):\n            size = np.array([15, 19]).astype(\"int32\")\n            scale = np.array([2.0, 1.0]).astype(\"float32\")\n            if not self.use_list and not self.use_const:\n                size = paddle.to_tensor(size)\n                scale = paddle.to_tensor(scale)\n            elif not self.use_const:\n                size0 = paddle.to_tensor(size[0:1])\n                size = [size0, int(size[1])]\n            elif not self.use_scaler:\n                size = size.tolist()\n                scale = scale.tolist()\n            else:\n                size = list(size)\n                h, w = paddle.rand(size).shape  # add decrease_axis\n                size = [h, w]\n            if not self.use_scale:\n                return paddle.nn.functional.interpolate(\n                    x,\n                    size=size,\n                    mode=self.mode,\n                    align_corners=self.align_corners,\n                    align_mode=self.align_mode,\n                    data_format=self.data_format,\n                )\n            else:\n                return paddle.nn.functional.interpolate(\n                    x,\n                    scale_factor=scale,\n                    mode=self.mode,\n                    align_corners=self.align_corners,\n                    align_mode=self.align_mode,\n                    data_format=self.data_format,\n                )\n\n    input_data = paddle.rand([1, 2, 8, 12]).astype(\"float32\")\n    verify_model(Interpolate(), input_data)\n    verify_model(Interpolate(use_list=True), input_data)\n    verify_model(Interpolate(use_scale=True, use_const=True), input_data)\n    verify_model(Interpolate(use_const=True, use_scaler=True), input_data)\n    verify_model(Interpolate(\"bilinear\", use_scale=True), input_data)\n    verify_model(Interpolate(\"bilinear\", use_scale=True, align_corners=True), input_data)\n    verify_model(\n        Interpolate(\n            \"bilinear\",\n            use_scale=True,\n            align_corners=True,\n            align_mode=1,\n            data_format=\"NHWC\",\n            use_const=True,\n        ),\n        input_data,\n    )\n    verify_model(\n        Interpolate(\"bicubic\", use_scale=True, align_corners=True, align_mode=1), input_data\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_layer_norm():\n    @paddle.jit.to_static\n    def layer_norm(inputs, weight, bias):\n        return nn.functional.layer_norm(inputs, inputs.shape[-1], weight=weight, bias=bias)\n\n    class LayerNorm(nn.Layer):\n        def __init__(self):\n            super(LayerNorm, self).__init__()\n            data_shape = [10]\n            self.layer_norm = nn.LayerNorm(data_shape)\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.layer_norm(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    weight = paddle.rand([10], dtype=\"float32\")\n    bias = paddle.rand([10], dtype=\"float32\")\n    verify_model(layer_norm, input_data=[input_data, weight, bias])\n    verify_model(LayerNorm(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_leaky_relu():\n    @paddle.jit.to_static\n    def leaky_relu(inputs):\n        return nn.functional.leaky_relu(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(leaky_relu, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logical_api():\n    class LogicalAPI(nn.Layer):\n        def __init__(self, api_name):\n            super(LogicalAPI, self).__init__()\n            for candidate in (paddle, paddle.nn.functional):\n                self.func = getattr(candidate, api_name, None)\n                if self.func:\n                    break\n\n        @paddle.jit.to_static\n        def forward(self, x, y):\n            out = paddle.to_tensor([True, True, True])\n            z = self.func(x, y, out=out)\n            return paddle.cast(z, \"int32\")\n\n    x_shapes = [[128], [8, 20], [4, 20, 3], [2, 3, 8, 8], [2, 3, 3, 9, 9]]\n    y_shapes = [[1], [8, 20], [4, 1, 1], [2, 3, 8, 8], [2, 3, 3, 9, 1]]\n    for x_shape, y_shape in zip(x_shapes, y_shapes):\n        x_data = paddle.randint(0, 2, x_shape).astype(\"bool\")\n        y_data = paddle.randint(0, 2, y_shape).astype(\"bool\")\n        verify_model(LogicalAPI(\"logical_and\"), [x_data, y_data])\n        verify_model(LogicalAPI(\"logical_or\"), [x_data, y_data])\n        verify_model(LogicalAPI(\"logical_xor\"), [x_data, y_data])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logical_not():\n    class LogicalNot(nn.Layer):\n        def __init__(self):\n            super(LogicalNot, self).__init__()\n\n        @paddle.jit.to_static\n        def forward(self, x):\n            return paddle.logical_not(x).astype(\"int32\")\n\n    input_shapes = [[128], [8, 20], [4, 20, 3], [2, 3, 8, 8], [2, 3, 3, 9, 9]]\n    for input_shape in input_shapes:\n        input_data = paddle.randint(-2, 2, input_shape).astype(\"bool\")\n        verify_model(LogicalNot(), input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_look_up():\n    @paddle.jit.to_static\n    def look_up(inputs, weight):\n        return nn.functional.embedding(inputs, weight)\n\n    class LookUp(nn.Layer):\n        def __init__(self):\n            super(LookUp, self).__init__()\n            self.embedding = paddle.nn.Embedding(10, 4, sparse=True)\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.embedding(inputs)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.randint(0, 10, input_shape, dtype=\"int32\")\n    weight = paddle.rand([10, 4], dtype=\"float32\")\n    verify_model(look_up, input_data=[input_data, weight])\n    verify_model(LookUp(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_multiply():\n    @paddle.jit.to_static\n    def multiply1(inputs):\n        return inputs * inputs\n\n    @paddle.jit.to_static\n    def multiply2(inputs):\n        return inputs * 1.0 / 2.0\n\n    @paddle.jit.to_static\n    def multiply3(inputs, inputs2):\n        ones = paddle.ones([10], dtype=\"float32\")\n        return inputs * ones / inputs2\n\n    input_shape = [10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(multiply1, input_data=input_data)\n    verify_model(multiply2, input_data=input_data)\n    input_data2 = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(multiply3, input_data=[input_data, input_data2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_matmul():\n    class MatMul1(nn.Layer):\n        def forward(self, input1, input2):\n            return paddle.matmul(input1, input2)\n\n    # matrix x vector\n    input_data1 = paddle.randn((3, 4), dtype=\"float32\")\n    input_data2 = paddle.randn((4,), dtype=\"float32\")\n    verify_model(MatMul1(), input_data=[input_data1, input_data2])\n\n    # matrix x matrix\n    input_data1 = paddle.randn((5, 4), dtype=\"float32\")\n    input_data2 = paddle.randn((4, 5), dtype=\"float32\")\n    verify_model(MatMul1(), input_data=[input_data1, input_data2])\n\n    # batched matrix x batched matrix\n    input_data1 = paddle.randn((10, 3, 4), dtype=\"float32\")\n    input_data2 = paddle.randn((10, 4, 5), dtype=\"float32\")\n    verify_model(MatMul1(), input_data=[input_data1, input_data2])\n\n    # batched matrix x broadcasted matrix\n    input_data1 = paddle.randn((10, 3, 4), dtype=\"float32\")\n    input_data2 = paddle.randn((4, 5), dtype=\"float32\")\n    verify_model(MatMul1(), input_data=[input_data1, input_data2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pool2d():\n    class Pool2D1(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return nn.functional.avg_pool2d(inputs, kernel_size=2, stride=2, padding=0)\n\n    class Pool2D2(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return nn.functional.adaptive_avg_pool2d(inputs, output_size=[3, 3])\n\n    class Pool2D3(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return nn.functional.avg_pool2d(\n                inputs,\n                kernel_size=3,\n                stride=1,\n                padding=[1, 1],\n                exclusive=False,\n                divisor_override=2.5,\n            )\n\n    input_shapes = [[1, 2, 8, 8], [1, 3, 10, 10]]\n    for input_shape in input_shapes:\n        input_data = paddle.uniform(shape=input_shape, dtype=\"float32\", min=-1, max=1)\n        verify_model(Pool2D1(), input_data=input_data)\n        verify_model(Pool2D2(), input_data=input_data)\n        verify_model(Pool2D3(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pad1d():\n    class Pad1D(nn.Layer):\n        def __init__(self, padding=0, mode=\"constant\", value=0.0, data_format=\"NCL\"):\n            super(Pad1D, self).__init__()\n            self.pad1d = paddle.nn.Pad1D(padding, mode=mode, value=value, data_format=data_format)\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.pad1d(inputs)\n\n    input_shapes = [[1, 2, 5], [2, 5, 9]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Pad1D(padding=2), input_data=input_data)\n        verify_model(Pad1D(padding=[1, 2], data_format=\"NLC\"), input_data=input_data)\n        verify_model(Pad1D(padding=[0, 2], value=0.3), input_data=input_data)\n        verify_model(Pad1D(padding=[2, 2], mode=\"reflect\"), input_data=input_data)\n        verify_model(Pad1D(padding=3, mode=\"replicate\"), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pad2d():\n    class Pad2D(nn.Layer):\n        def __init__(self, padding=0, mode=\"constant\", value=0.0, data_format=\"NCHW\"):\n            super(Pad2D, self).__init__()\n            self.pad2d = paddle.nn.Pad2D(padding, mode=mode, value=value, data_format=data_format)\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.pad2d(inputs)\n\n    input_shapes = [[1, 2, 5, 5], [2, 2, 5, 9]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Pad2D(padding=2), input_data=input_data)\n        verify_model(Pad2D(padding=[1, 2, 0, 2], data_format=\"NHWC\"), input_data=input_data)\n        verify_model(Pad2D(padding=[1, 2, 0, 2], value=0.3), input_data=input_data)\n        verify_model(Pad2D(padding=[1, 2, 0, 2], mode=\"reflect\"), input_data=input_data)\n        verify_model(Pad2D(padding=3, mode=\"replicate\"), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pad3d():\n    class Pad3D(nn.Layer):\n        def __init__(self, padding=0, mode=\"constant\", value=0.0, data_format=\"NCDHW\"):\n            super(Pad3D, self).__init__()\n            self.pad3d = paddle.nn.Pad3D(padding, mode=mode, value=value, data_format=data_format)\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.pad3d(inputs)\n\n    input_shapes = [[1, 2, 2, 5, 5], [1, 2, 2, 5, 9]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(Pad3D(padding=2), input_data=input_data)\n        verify_model(Pad3D(padding=[1, 2, 0, 2, 1, 1], data_format=\"NDHWC\"), input_data=input_data)\n        verify_model(Pad3D(padding=[1, 2, 0, 2, 1, 1], value=0.3), input_data=input_data)\n        verify_model(Pad3D(padding=[1, 2, 0, 2, 1, 1], mode=\"reflect\"), input_data=input_data)\n        verify_model(Pad3D(padding=3, mode=\"replicate\"), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_transpose():\n    class Transpose(nn.Layer):\n        def __init__(self, perm):\n            super(Transpose, self).__init__()\n            self.perm = perm\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            inputs = inputs + inputs.size()\n            return paddle.transpose(inputs, perm=self.perm)\n\n    input_data = paddle.rand([1, 3, 5, 4, 3], dtype=\"float32\")\n    verify_model(Transpose([0, 1, 2, 3, 4]), input_data=input_data)\n    verify_model(Transpose([4, 3, 2, 0, 1]), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reduce():\n    class Reduce(nn.Layer):\n        def __init__(self, op_name, axis=None, keepdim=False):\n            super(Reduce, self).__init__()\n            self.op_name = op_name\n            self.axis = axis\n            self.keepdim = keepdim\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            result = getattr(paddle, self.op_name)(inputs, axis=self.axis, keepdim=self.keepdim)\n            result = result.astype(\"float32\")\n            return result\n\n    input_shapes = [[1, 2, 2, 5, 5], [2, 3, 4], [4, 20], [2, 3, 30, 30]]\n    for input_shape in input_shapes:\n        input_data = paddle.uniform(min=-3, max=3, shape=input_shape, dtype=\"float32\")\n        verify_model(Reduce(\"all\"), input_data=input_data.astype(\"bool\"))\n        verify_model(Reduce(\"any\", 1), input_data=input_data.astype(\"bool\"))\n        verify_model(Reduce(\"max\", 0, True), input_data=input_data)\n        verify_model(Reduce(\"min\", 1, True), input_data=input_data)\n        verify_model(Reduce(\"prod\", 0), input_data=input_data)\n        verify_model(Reduce(\"sum\", 0, True), input_data=input_data)\n        verify_model(Reduce(\"mean\", -1, True), input_data=input_data)\n        # logsumexp only supports tensor with rank less than 5\n        if len(input_shape) < 5:\n            verify_model(Reduce(\"logsumexp\", -1, True), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reshape():\n    @paddle.jit.to_static\n    def reshape1(inputs, x):\n        new_shape = paddle.shape(x)\n        return paddle.reshape(inputs, new_shape)\n\n    @paddle.jit.to_static\n    def reshape2(inputs):\n        return inputs.reshape([-1])\n\n    @paddle.jit.to_static\n    def reshape3(inputs):\n        data_shape = inputs.shape\n        return inputs.reshape([data_shape[0] * data_shape[1], data_shape[2]])\n\n    @paddle.jit.to_static\n    def reshape4(inputs, x):\n        new_shape = paddle.shape(x)\n        return paddle.reshape(inputs, [new_shape[2], 2, -1])\n\n    input_shape = [2, 1, 10, 1, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    input_data2 = paddle.randn([2, 1, 10, 10])\n    verify_model(reshape1, input_data=[input_data, input_data2])\n    verify_model(reshape2, input_data=input_data)\n    verify_model(reshape3, input_data=paddle.randn((2, 3, 4)))\n    verify_model(reshape4, input_data=[input_data, input_data2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_scale():\n    @paddle.jit.to_static\n    def scale1(inputs):\n        return paddle.scale(inputs, scale=2.0, bias=1.0)\n\n    @paddle.jit.to_static\n    def scale2(inputs):\n        return paddle.scale(inputs, scale=3, bias=2.1, act=\"gelu\")\n\n    input_data = paddle.randn(shape=[2, 3], dtype=\"float32\")\n    verify_model(\n        scale1,\n        input_data=[\n            input_data,\n        ],\n    )\n    verify_model(scale2, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice():\n    @paddle.jit.to_static\n    def slice1(inputs):\n        return inputs[:, :, :, :3]\n\n    @paddle.jit.to_static\n    def slice2(inputs):\n        return inputs[0, :, :-3, :]\n\n    @paddle.jit.to_static\n    def slice3(inputs):\n        return inputs[0::2, 0::2] + inputs[1::2, 1::2]\n\n    @paddle.jit.to_static\n    def slice4(inputs):\n        x0 = paddle.to_tensor([2]) - paddle.to_tensor([1])\n        x1 = paddle.to_tensor([3]) + paddle.to_tensor([1])\n        return inputs[:, x0:, 1:x1, :]\n\n    input_shape = [1, 3, 10, 10]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(\n        slice1,\n        input_data=[\n            input_data,\n        ],\n    )\n    verify_model(slice2, input_data=input_data)\n    verify_model(slice3, input_data=paddle.randn((4, 4)))\n    verify_model(slice4, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef run_math_api(func):\n    api_name = func.__name__.split(\"_\")[-1]\n    print(\"func_name:\", api_name)\n\n    class MathAPI(nn.Layer):\n        def __init__(self, api_name):\n            super(MathAPI, self).__init__()\n            for candidate in (paddle, paddle.nn.functional):\n                self.func = getattr(candidate, api_name, None)\n                if self.func:\n                    break\n\n        @paddle.jit.to_static\n        def forward(self, inputs):\n            return self.func(inputs)\n\n    input_shapes = [[128], [2, 100], [10, 2, 5], [7, 3, 4, 1]]\n    for input_shape in input_shapes:\n        input_data = paddle.rand(input_shape, dtype=\"float32\")\n        if api_name in [\"log\", \"log2\", \"log10\", \"reciprocal\", \"sqrt\", \"rsqrt\"]:\n            # avoid illegal input, all elements should be positive\n            input_data = paddle.uniform(input_shape, min=0.01, max=0.99)\n        verify_model(MathAPI(api_name), input_data=input_data)\n\n\n@run_math_api\ndef test_forward_abs():\n    pass\n\n\n@run_math_api\ndef test_forward_acos():\n    pass\n\n\n@run_math_api\ndef test_forward_abs():\n    pass\n\n\n@run_math_api\ndef test_forward_atan():\n    pass\n\n\n@run_math_api\ndef test_forward_ceil():\n    pass\n\n\n@run_math_api\ndef test_forward_cos():\n    pass\n\n\n@run_math_api\ndef test_forward_cosh():\n    pass\n\n\n@run_math_api\ndef test_forward_elu():\n    pass\n\n\n@run_math_api\ndef test_forward_erf():\n    pass\n\n\n@run_math_api\ndef test_forward_exp():\n    pass\n\n\n@run_math_api\ndef test_forward_floor():\n    pass\n\n\n@run_math_api\ndef test_forward_hardshrink():\n    pass\n\n\n@run_math_api\ndef test_forward_hardtanh():\n    pass\n\n\n@run_math_api\ndef test_forward_log_sigmoid():\n    pass\n\n\n@run_math_api\ndef test_forward_log_softmax():\n    pass\n\n\n@run_math_api\ndef test_forward_log():\n    pass\n\n\n@run_math_api\ndef test_forward_log2():\n    pass\n\n\n@run_math_api\ndef test_forward_log10():\n    pass\n\n\n@run_math_api\ndef test_forward_log1p():\n    pass\n\n\n@run_math_api\ndef test_forward_reciprocal():\n    pass\n\n\n@run_math_api\ndef test_forward_relu():\n    pass\n\n\n@run_math_api\ndef test_forward_round():\n    pass\n\n\n@run_math_api\ndef test_forward_rsqrt():\n    pass\n\n\n@run_math_api\ndef test_forward_selu():\n    pass\n\n\n@run_math_api\ndef test_forward_sigmoid():\n    pass\n\n\n@run_math_api\ndef test_forward_sign():\n    pass\n\n\n@run_math_api\ndef test_forward_sin():\n    pass\n\n\n@run_math_api\ndef test_forward_softplus():\n    pass\n\n\n@run_math_api\ndef test_forward_sqrt():\n    pass\n\n\n@run_math_api\ndef test_forward_square():\n    pass\n\n\n@run_math_api\ndef test_forward_sin():\n    pass\n\n\n@run_math_api\ndef test_forward_softsign():\n    pass\n\n\n@run_math_api\ndef test_forward_sqrt():\n    pass\n\n\n@run_math_api\ndef test_forward_square():\n    pass\n\n\n@run_math_api\ndef test_forward_swish():\n    pass\n\n\n@run_math_api\ndef test_forward_tan():\n    pass\n\n\n@run_math_api\ndef test_forward_tanh():\n    pass\n\n\n@tvm.testing.uses_gpu\ndef test_forward_meshgrid():\n    @paddle.jit.to_static\n    def t(x, y, z):\n        return paddle.meshgrid(x, y, z)\n\n    x = paddle.randint(low=0, high=100, shape=[2])\n    y = paddle.randint(low=0, high=100, shape=[3])\n    z = paddle.randint(low=0, high=100, shape=[5])\n    verify_model(t, [x, y, z])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_mv():\n    class Mv(nn.Layer):\n        def forward(self, input1, input2):\n            return paddle.mv(input1, input2)\n\n    # matrix x vector\n    input_data1 = paddle.randn((3, 4), dtype=\"float32\")\n    input_data2 = paddle.randn((4,), dtype=\"float32\")\n    verify_model(Mv(), input_data=[input_data1, input_data2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pixel_shuffle():\n    class PixelShuffle(nn.Layer):\n        def __init__(self, upscale_factor):\n            super(PixelShuffle, self).__init__()\n            self.pixel_shuffle = paddle.nn.PixelShuffle(upscale_factor)\n\n        @paddle.jit.to_static\n        def forward(self, x):\n            return self.pixel_shuffle(x)\n\n    input_shapes = [[1, 4, 3, 3], [2, 8, 2, 5]]\n    for input_shape in input_shapes:\n        x = paddle.rand(input_shape, dtype=\"float32\")\n        verify_model(PixelShuffle(2), x)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_prelu():\n    class PRelu(nn.Layer):\n        @paddle.jit.to_static\n        def forward(self, x, w):\n            return paddle.nn.functional.prelu(x, w)\n\n    x = paddle.normal(shape=[4, 3, 5, 5])\n    w = paddle.to_tensor(\n        np.array(\n            [\n                0.25,\n            ]\n        ).astype(\"float32\")\n    )\n    verify_model(PRelu(), [x, w])\n    w2 = paddle.to_tensor(np.array([0.25, 0.5, 0.8]).astype(\"float32\"))\n    verify_model(PRelu(), [x, w2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_arange():\n    @paddle.jit.to_static\n    def arange(inputs):\n        return paddle.arange(paddle.shape(inputs)[0], 9, 2.0)\n\n    @paddle.jit.to_static\n    def arange1(inputs):\n        return inputs + paddle.arange(0, 10.0, 8, dtype=\"float32\")\n\n    input_shape = [2, 2]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n    verify_model(arange, input_data)\n    verify_model(arange1, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_rnn():\n    class RNN(nn.Layer):\n        def __init__(self, api_name, input_size, hidden_size, num_layers, direction=\"forward\"):\n            super(RNN, self).__init__()\n            rnn_func = getattr(paddle.nn, api_name, None)\n            self.rnn = rnn_func(input_size, hidden_size, num_layers, direction=direction)\n\n        @paddle.jit.to_static\n        def forward(self, inputs, prev_h):\n            y, h = self.rnn(inputs, prev_h)\n            return y\n\n    input_size, hidden_size, num_layers = 8, 16, 2\n    input_shape = [4, 5, 8]\n    input_data = paddle.rand(input_shape, dtype=\"float32\")\n\n    for api_name in (\"SimpleRNN\", \"GRU\"):\n        prev_h = paddle.rand([4, 4, 16], dtype=\"float32\")\n        verify_model(\n            RNN(api_name, input_size, hidden_size, num_layers, direction=\"bidirectional\"),\n            input_data=[input_data, prev_h],\n        )\n        prev_h = paddle.rand([2, 4, 16], dtype=\"float32\")\n        verify_model(\n            RNN(api_name, input_size, hidden_size, num_layers), input_data=[input_data, prev_h]\n        )\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/qnn_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Tests on quantized torch model conversion \"\"\"\nimport os\n\nfrom PIL import Image\n\nimport numpy as np\n\nimport torch\nfrom torch import nn\nfrom torch.quantization import (\n    QuantStub,\n    DeQuantStub,\n    fuse_modules,\n    QuantWrapper,\n    prepare_qat,\n    get_default_qat_qconfig,\n)\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.frontend.pytorch_utils import is_version_greater_than\nfrom tvm.contrib.download import download_testdata\nfrom tvm.relay.op.contrib.register import register_pattern_table, get_pattern_table\n\n\ndef torch_version_check():\n    from packaging import version\n\n    return version.parse(torch.__version__) > version.parse(\"1.4.0\")\n\n\ndef get_tvm_runtime(script_module, input_name, ishape, keep_quantized_weight=False, target=\"llvm\"):\n    input_shapes = [(input_name, ishape)]\n    mod, params = relay.frontend.from_pytorch(\n        script_module, input_shapes, keep_quantized_weight=keep_quantized_weight\n    )\n\n    if keep_quantized_weight:\n        for p in params.values():\n            assert p.dtype in [\"int8\", \"int32\"]\n\n    with tvm.transform.PassContext(opt_level=3):\n        # test on only cpu for now, torch cannot run quant models on cuda\n        # also not to make CI too slow\n        lib = relay.build(mod, target=target, params=params)\n\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](tvm.device(target, 0)))\n    return runtime\n\n\ndef get_qconfig(per_channel):\n    from torch.quantization.observer import MovingAverageMinMaxObserver\n    from torch.quantization.observer import default_weight_observer\n\n    if per_channel:\n        return torch.quantization.get_default_qconfig(\"fbgemm\")\n    else:\n        act = MovingAverageMinMaxObserver.with_args(reduce_range=False)\n        return torch.quantization.QConfig(activation=act, weight=default_weight_observer)\n\n\ndef quantize_model(model, inp, per_channel=False):\n    model.fuse_model()\n    model.qconfig = get_qconfig(per_channel)\n    torch.quantization.prepare(model, inplace=True)\n    model(inp)\n    torch.quantization.convert(model, inplace=True)\n\n\nclass ConvBn(nn.Module):\n    def __init__(self, with_relu=False):\n        super().__init__()\n        layers = [nn.Conv2d(3, 32, 3, bias=True), nn.BatchNorm2d(32)]\n        if with_relu:\n            layers.append(nn.ReLU())\n        self.conv = nn.Sequential(*layers)\n        self.quant_wrap = QuantWrapper(self.conv)\n        self.with_relu = with_relu\n\n    def forward(self, x):\n        return self.quant_wrap(x)\n\n    def fuse_model(self):\n        indices = [\"0\", \"1\"]\n        if self.with_relu:\n            indices.append(\"2\")\n        fuse_modules(self.conv, indices, inplace=True)\n\n\nclass ConvTranspose(nn.Module):\n    def __init__(self):\n        super().__init__()\n        layers = [nn.ConvTranspose2d(3, 32, 3, bias=True)]\n        self.conv = nn.Sequential(*layers)\n        self.quant_wrap = QuantWrapper(self.conv)\n\n    def forward(self, x):\n        return self.quant_wrap(x)\n\n    def fuse_model(self):\n        pass\n\n\nclass Linear(nn.Module):\n    def __init__(self, with_relu=False):\n        super().__init__()\n        layers = [nn.Linear(16, 32)]\n        if with_relu:\n            layers.append(nn.ReLU())\n        self.fc = nn.Sequential(*layers)\n        self.quant_wrap = QuantWrapper(self.fc)\n        self.with_relu = with_relu\n\n    def forward(self, x):\n        return self.quant_wrap(x)\n\n    def fuse_model(self):\n        if self.with_relu:\n            fuse_modules(self.fc, [\"0\", \"1\"], inplace=True)\n\n\nclass ReLU(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.relu = QuantWrapper(nn.ReLU())\n\n    def forward(self, x):\n        return self.relu(x)\n\n    def fuse_model(self):\n        pass\n\n\nclass LeakyReLU(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.leaky_relu = QuantWrapper(nn.LeakyReLU())\n\n    def forward(self, x):\n        return self.leaky_relu(x)\n\n    def fuse_model(self):\n        pass\n\n\n# Mobilenet V3 related modules\nclass Hsigmoid(nn.Module):\n    def __init__(self, add_stub=False):\n        super().__init__()\n        self.quant = QuantStub()\n        self.dequant = DeQuantStub()\n        self.add_stub = add_stub\n        self.hsigmoid = nn.Hardsigmoid()\n\n    def forward(self, x):\n        if self.add_stub:\n            x = self.quant(x)\n        x = self.hsigmoid(x)\n        if self.add_stub:\n            x = self.dequant(x)\n        return x\n\n    def fuse_model(self):\n        pass\n\n\nclass Hswish(nn.Module):\n    def __init__(self, add_stub=False):\n        super().__init__()\n        self.hswish = QuantWrapper(nn.Hardswish())\n\n    def forward(self, x):\n        return self.hswish(x)\n\n    def fuse_model(self):\n        pass\n\n\nclass SqueezeExcite(nn.Module):\n    def __init__(self, channel, reduction=4, add_stub=False):\n        super(SqueezeExcite, self).__init__()\n        self.avg_pool = nn.AdaptiveAvgPool2d(1)\n        self.fc = nn.Sequential(\n            nn.Linear(channel, channel // reduction, bias=False),\n            nn.ReLU(inplace=True),\n            nn.Linear(channel // reduction, channel, bias=False),\n            Hsigmoid(add_stub=False),\n        )\n        self.fmul = nn.quantized.FloatFunctional()\n        self.quant = QuantStub()\n        self.dequant = DeQuantStub()\n        self.add_stub = add_stub\n\n    def forward(self, x):\n        b, c, _, _ = x.size()\n        if self.add_stub:\n            x = self.quant(x)\n        y = self.avg_pool(x).view(b, c)\n        y = self.fc(y).view(b, c, 1, 1)\n        out = self.fmul.mul(x, y.expand_as(x))\n        if self.add_stub:\n            return self.dequant(out)\n        else:\n            return out\n\n    def fuse_model(self):\n        fuse_modules(self.fc, [\"0\", \"1\"], inplace=True)\n\n\n# test on quantized::mul_scalar with negative scale\nclass MulScalarNegative(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.float_op = nn.quantized.FloatFunctional()\n        self.quant = QuantStub()\n        self.dequant = DeQuantStub()\n\n    def forward(self, x):\n        x = self.quant(x)\n        mul = self.float_op.mul_scalar(x, -0.3)\n        return self.dequant(mul)\n\n    def fuse_model(self):\n        pass\n\n\nclass UpsamplingBilinear(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.quant = QuantStub()\n        self.dequant = DeQuantStub()\n\n    def forward(self, x):\n        x = self.quant(x)\n        upsample = nn.functional.interpolate(x, scale_factor=2, mode=\"bilinear\", align_corners=True)\n        return self.dequant(upsample)\n\n    def fuse_model(self):\n        pass\n\n\nclass AvgPool2d(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.pool = QuantWrapper(nn.AvgPool2d(kernel_size=2))\n\n    def forward(self, x):\n        return self.pool(x)\n\n    def fuse_model(self):\n        pass\n\n\nclass AdaptiveAvgPool2d(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.pool = QuantWrapper(nn.AdaptiveAvgPool2d((1, 1)))\n\n    def forward(self, x):\n        return self.pool(x)\n\n    def fuse_model(self):\n        pass\n\n\ndef test_quantized_modules():\n    imagenet_ishape = (1, 3, 224, 224)\n\n    qmodules = [\n        (\"relu\", imagenet_ishape, ReLU(), False),\n        (\"upsample bilinear\", (1, 3, 64, 64), UpsamplingBilinear(), False),\n        (\"avgpool\", imagenet_ishape, AvgPool2d(), False),\n    ]\n\n    for per_channel in [False, True]:\n        if per_channel:\n            postfix = \", per_channel\"\n        else:\n            postfix = \"\"\n\n        qmodules += [\n            (\"conv_bn\" + postfix, imagenet_ishape, ConvBn(), per_channel),\n            (\"conv_bn_relu\" + postfix, imagenet_ishape, ConvBn(with_relu=True), per_channel),\n            (\"linear\" + postfix, (16, 16), Linear(), per_channel),\n            (\"linear_relu\" + postfix, (16, 16), Linear(with_relu=True), per_channel),\n            (\"conv_transpose\", imagenet_ishape, ConvTranspose(), False),\n            (\"hsigmoid\", imagenet_ishape, Hsigmoid(add_stub=True), False),\n            (\"hswish\", imagenet_ishape, Hswish(), False),\n            (\"semodule\", (1, 16, 64, 64), SqueezeExcite(16, add_stub=True), False),\n            (\"semodule, per_channel\", (1, 16, 64, 64), SqueezeExcite(16, add_stub=True), True),\n            (\"mul_scalar negative\", imagenet_ishape, MulScalarNegative(), False),\n            (\"leaky_relu\", imagenet_ishape, LeakyReLU(), False),\n        ]\n\n    for (module_name, ishape, raw_module, per_channel) in qmodules:\n        raw_module.eval()\n        inp = torch.rand(ishape)\n\n        # quantized conv_transpose2d is supported only with qnnpack engine before torch v1.8.0.\n        if module_name == \"conv_transpose\" and not is_version_greater_than(\"1.7.1\"):\n            prev_engine = torch.backends.quantized.engine\n            torch.backends.quantized.engine = \"qnnpack\"\n            quantize_model(raw_module, inp, per_channel=per_channel)\n            torch.backends.quantized.engine = prev_engine\n        else:\n            quantize_model(raw_module, inp, per_channel=per_channel)\n\n        script_module = torch.jit.trace(raw_module, inp).eval()\n\n        with torch.no_grad():\n            pt_result = script_module(inp.clone()).numpy()\n\n        input_name = \"input\"\n        runtime = get_tvm_runtime(script_module, input_name, ishape)\n        runtime.set_input(input_name, inp.numpy().copy())\n        runtime.run()\n        tvm_result = runtime.get_output(0).numpy()\n\n        max_abs_diff = np.max(np.abs(tvm_result - pt_result))\n        mean_abs_diff = np.mean(np.abs(tvm_result - pt_result))\n        num_identical = np.sum(tvm_result == pt_result)\n        match_ratio = num_identical / float(np.prod(tvm_result.shape))\n\n        print(module_name, max_abs_diff, mean_abs_diff, match_ratio)\n\n        if \"linear\" in module_name and tvm.get_global_func(\"tvm.contrib.cublas.matmul\", True):\n            runtime = get_tvm_runtime(script_module, input_name, ishape, target=\"cuda -libs=cublas\")\n            runtime.set_input(input_name, inp.numpy().copy())\n            runtime.run()\n            cublas_result = runtime.get_output(0).numpy()\n            # It is generally safe to enable this assertion, but disabled for CI\n            # tvm.testing.assert_allclose(cublas_result, pt_result, atol=1e-5, rtol=1e-5)\n            print(np.max(np.abs(cublas_result - pt_result)))\n\n        # sample outputs\n        \"\"\"\n        relu 0.0039215684 2.6052087e-08 0.9999933567176871\n        leaky_relu 0.0 0.0 1.0\n        upsample bilinear 0.0 0.0 1.0\n        conv_bn 0.22062653 0.011478779 0.6909348115006899\n        conv_bn_relu 0.3700896 0.010921672 0.7489366477964451\n        linear 0.15987062 0.009231662 0.794921875\n        linear_relu 0.14180502 0.0053220326 0.8828125\n        conv_transpose 0.0033792555 4.4658788e-07 0.9998678439971806\n        conv_bn, per_channel 0.01654929 2.9486866e-06 0.9998218235127019\n        conv_bn_relu, per_channel 0.009089053 1.4926576e-06 0.9998357732732732\n        linear, per_channel 0.0 0.0 1.0\n        linear_relu, per_channel 0.0 0.0 1.0\n        hsigmoid 0.002614379 0.00020525524 0.9214896896258503\n        hswish 0.0026143193 1.7367661e-08 0.9999933567176871\n        hswish, per_channel 0.0 0.0 1.0\n        semodule, per_channel 0.0039885044 0.0008620687 0.7838592529296875\n        mul_scalar negative 0.0011764616 7.815566e-09 0.9999933567176871\n        \"\"\"\n\n        # we cannot make any guarantee on how close the raw output is to torch\n        # tvm.testing.assert_allclose(tvm_result, pt_result, rtol=1e-1, atol=1e-1)\n\n\ndef test_quantized_imagenet():\n    def get_transform():\n        import torchvision.transforms as transforms\n\n        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n        return transforms.Compose(\n            [transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize]\n        )\n\n    def get_real_image(im_height, im_width):\n        repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n        img_name = \"elephant-299.jpg\"\n        image_url = os.path.join(repo_base, img_name)\n        img_path = download_testdata(image_url, img_name, module=\"data\")\n        return Image.open(img_path).resize((im_height, im_width))\n\n    def get_imagenet_input():\n        im = get_real_image(224, 224)\n        preprocess = get_transform()\n        pt_tensor = preprocess(im)\n        return np.expand_dims(pt_tensor.numpy(), 0)\n\n    from torchvision.models.quantization import resnet as qresnet\n    from torchvision.models.quantization import mobilenet as qmobilenet\n    from torchvision.models.quantization import inception as qinception\n    from torchvision.models.quantization import googlenet as qgooglenet\n    from torchvision.models.quantization import mobilenet_v3_large as qmobilenet_v3_large\n\n    per_channel = True\n    qmodels = [\n        (\"resnet18\", qresnet.resnet18(pretrained=True), per_channel),\n        (\"mobilenet_v2\", qmobilenet.mobilenet_v2(pretrained=True), per_channel),\n        (\"inception_v3\", qinception.inception_v3(pretrained=True), per_channel),\n        # tracing quantized googlenet broken as of v1.6\n        # (\"googlenet\", qgooglenet(pretrained=True), per_channel),\n        # As of v1.10, quantized mobilenet v3 has a weird segfault issue\n        # during make_conv_packed_param\n        # See https://ci.tlcpack.ai/blue/organizations/jenkins/tvm/detail/ci-docker-staging/192\n        # (\"mobilenet_v3_large\", qmobilenet_v3_large(pretrained=True, quantize=True).eval(), True)\n    ]\n\n    results = []\n\n    for (model_name, raw_model, per_channel) in qmodels:\n        raw_model.eval()\n\n        if per_channel:\n            model_name += \", per channel quantization\"\n        else:\n            model_name += \", per tensor quantization\"\n\n        inp = get_imagenet_input()\n        pt_inp = torch.from_numpy(inp)\n\n        if \"mobilenet_v3_large\" not in model_name:\n            # mv3 was qat-ed, quantize=True option above makes it already quantized\n            quantize_model(raw_model, pt_inp, per_channel=per_channel)\n\n        script_module = torch.jit.trace(raw_model, pt_inp).eval()\n\n        with torch.no_grad():\n            pt_result = script_module(pt_inp).numpy()\n\n        input_name = \"image\"\n        runtime = get_tvm_runtime(script_module, input_name, (1, 3, 224, 224))\n        runtime.set_input(input_name, inp)\n        runtime.run()\n\n        tvm_result = runtime.get_output(0).numpy()\n\n        results.append((model_name, pt_result[0], tvm_result[0]))\n\n    for (model_name, pt_result, tvm_result) in results:\n        max_abs_diff = np.max(np.abs(tvm_result - pt_result))\n        mean_abs_diff = np.mean(np.abs(tvm_result - pt_result))\n        num_identical = np.sum(tvm_result == pt_result)\n        pt_top3_labels = np.argsort(pt_result)[::-1][:3]\n        tvm_top3_labels = np.argsort(tvm_result)[::-1][:3]\n\n        print(\"\\nModel name: %s\" % model_name)\n        print(\"PyTorch top3 label:\", pt_top3_labels)\n        print(\"TVM top3 label:\", tvm_top3_labels)\n        print(\"max abs diff:\", max_abs_diff)\n        print(\"mean abs_diff:\", mean_abs_diff)\n        print(\"%d in 1000 raw outputs identical.\" % num_identical)\n\n        assert set(pt_top3_labels) == set(tvm_top3_labels)\n\n        # sample outputs\n        \"\"\"\n        Model name: resnet18, per tensor quantization\n        PyTorch top3 label: [386 101 385]\n        TVM top3 label: [386 101 385]\n        max abs diff: 0.65681696\n        mean abs_diff: 0.14055882\n        236 in 1000 raw outputs identical.\n\n        Model name: mobilenet_v2, per tensor quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 2.1262953\n        mean abs_diff: 0.41025686\n        101 in 1000 raw outputs identical.\n\n        Model name: inception_v3, per tensor quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 0.9994669\n        mean abs_diff: 0.098697364\n        272 in 1000 raw outputs identical.\n\n        Model name: googlenet, per tensor quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 0.28248847\n        mean abs_diff: 0.0634469\n        274 in 1000 raw outputs identical.\n\n        Model name: resnet18, per channel quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 0.65908074\n        mean abs_diff: 0.1274223\n        469 in 1000 raw outputs identical.\n\n        Model name: mobilenet_v2, per channel quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 0.71120834\n        mean abs_diff: 0.15883648\n        423 in 1000 raw outputs identical.\n\n        Model name: inception_v3, per channel quantization\n        PyTorch top3 label: [386 101 385]\n        TVM top3 label: [386 101 385]\n        max abs diff: 1.3372154\n        mean abs_diff: 0.1225224\n        401 in 1000 raw outputs identical.\n\n        Model name: googlenet, per channel quantization\n        PyTorch top3 label: [101 386 385]\n        TVM top3 label: [101 386 385]\n        max abs diff: 0.34015465\n        mean abs_diff: 0.054197952\n        558 in 1000 raw outputs identical.\n        \"\"\"\n\n\ndef test_serialized_modules():\n    ishape = (1, 16, 64, 64)\n    raw_module = AdaptiveAvgPool2d().eval()\n    inp = torch.rand(ishape)\n\n    quantize_model(raw_module, inp)\n    script_module = torch.jit.trace(raw_module, inp).eval()\n\n    fname = \"tmp.pt\"\n    torch.jit.save(script_module, fname)\n    loaded = torch.jit.load(fname)\n    os.remove(fname)\n\n    with torch.no_grad():\n        pt_result = loaded(inp.clone()).numpy()\n\n    input_name = \"input\"\n    runtime = get_tvm_runtime(loaded, input_name, ishape)\n    runtime.set_input(input_name, inp.numpy().copy())\n    runtime.run()\n    tvm_result = runtime.get_output(0).numpy()\n\n    # with 0.5ish results, 1e-2 is relative accuracy close to 2**-6.\n    # for simple layers like here this should be achievable\n    # with 8 bit quantization\n    # we only require 90% match just to be sure\n    num_identical = np.sum(np.abs(tvm_result - pt_result) < 1e-2)\n    match_ratio = num_identical / float(np.prod(tvm_result.shape))\n    assert match_ratio > 0.90\n\n\ndef test_quantize_dynamic():\n    # A wrapper is required for quantize_dynamic to work correctly\n    class LinearWrapper(nn.Module):\n        def __init__(self, in_dim, hidden_dim):\n            super().__init__()\n            self.linear = nn.Linear(in_dim, hidden_dim)\n\n        def forward(self, inp):\n            return self.linear(inp)\n\n    torch.manual_seed(0)\n    mod = LinearWrapper(16, 32)\n\n    for qconfig in [\n        torch.quantization.per_channel_dynamic_qconfig,\n        torch.quantization.default_dynamic_qconfig,\n    ]:\n        for ishape in [(16, 16), (10, 16, 16)]:\n            qspec = {nn.Linear: qconfig}\n            qmod = torch.quantization.quantize_dynamic(mod, qconfig_spec=qspec, dtype=torch.qint8)\n\n            inp = torch.randn(*ishape)\n            script_module = torch.jit.trace(qmod, inp).eval()\n\n            with torch.no_grad():\n                pt_result = script_module(inp.clone()).numpy()\n\n            input_name = \"input\"\n            runtime = get_tvm_runtime(script_module, \"input\", inp.shape)\n            runtime.set_input(input_name, inp.numpy().copy())\n            runtime.run()\n            tvm_result = runtime.get_output(0).numpy()\n\n            # Only compare with the PyTorch result for version v1.6 or newer\n            # Have seen a strange accuracy problem from PyTorch 1.4 and 1.5\n            # Even with the manual random seed set, the same PyTorch\n            # version can outputs slightly different results depending on an environment.\n            # Outputs from v1.6 seem reliable. TVM's outputs are always the same\n            if is_version_greater_than(\"1.5.1\"):\n                tvm.testing.assert_allclose(tvm_result, pt_result, rtol=1e-4, atol=1e-4)\n\n\ndef make_qnn_add_pattern():\n    from tvm.relay.dataflow_pattern import wildcard, is_op\n\n    lhs = wildcard()\n    rhs = wildcard()\n    lhs_scale = wildcard()\n    lhs_zero_point = wildcard()\n    rhs_scale = wildcard()\n    rhs_zero_point = wildcard()\n    output_scale = wildcard()\n    output_zero_point = wildcard()\n    qadd = is_op(\"qnn.add\")(\n        lhs,\n        rhs,\n        lhs_scale,\n        lhs_zero_point,\n        rhs_scale,\n        rhs_zero_point,\n        output_scale,\n        output_zero_point,\n    )\n    return qadd.optional(is_op(\"clip\"))\n\n\n@register_pattern_table(\"test_table\")\ndef pattern_table():\n    return [\n        (\"qnn_add\", make_qnn_add_pattern()),\n    ]\n\n\ndef run_qnn_mergecomposite(script_module, input_name, ishape):\n    input_shapes = [(input_name, ishape)]\n    mod, params = relay.frontend.from_pytorch(script_module, input_shapes)\n    pattern_table = get_pattern_table(\"test_table\")\n    with tvm.transform.PassContext(opt_level=3):\n        pass_list = [\n            tvm.relay.transform.SimplifyInference(),\n            tvm.relay.transform.MergeComposite(pattern_table),\n        ]\n        composite_partition = tvm.transform.Sequential(pass_list)\n        partitioned = composite_partition(mod)\n\n\ndef test_qnn_mergecomposite():\n    from torchvision.models.quantization import resnet as qresnet\n\n    model = qresnet.resnet18(pretrained=True)\n    model.eval()\n\n    inp = torch.zeros((1, 3, 224, 224))\n    model.fuse_model()\n    model.qconfig = torch.quantization.get_default_qconfig(\"fbgemm\")\n    torch.quantization.prepare(model, inplace=True)\n    model(inp)\n    torch.quantization.convert(model, inplace=True)\n    script_module = torch.jit.trace(model, inp).eval()\n\n    input_name = \"image\"\n    run_qnn_mergecomposite(script_module, input_name, inp.shape)\n\n\ndef test_keep_quantized_weight():\n    qmodules = []\n\n    for per_channel in [False, True]:\n        qmodules += [\n            ((1, 3, 224, 224), ConvBn(), per_channel),\n            ((16, 16), Linear(), per_channel),\n        ]\n\n    for (ishape, raw_module, per_channel) in qmodules:\n        raw_module.eval()\n        inp = torch.rand(ishape)\n\n        quantize_model(raw_module, inp, per_channel=per_channel)\n        script_module = torch.jit.trace(raw_module, inp).eval()\n\n        input_name = \"input\"\n\n        runtime = get_tvm_runtime(script_module, input_name, ishape, keep_quantized_weight=False)\n        runtime.set_input(input_name, inp.numpy().copy())\n        runtime.run()\n        tvm_result = runtime.get_output(0).numpy()\n\n        runtime_int8_weight = get_tvm_runtime(\n            script_module, input_name, ishape, keep_quantized_weight=True\n        )\n        runtime_int8_weight.set_input(input_name, inp.numpy().copy())\n        runtime_int8_weight.run()\n        tvm_result_int8_weight = runtime_int8_weight.get_output(0).numpy()\n\n        tvm.testing.assert_allclose(tvm_result, tvm_result_int8_weight)\n\n\ndef test_tuple_lowered():\n    # See the following discuss thread for details\n    # https://discuss.tvm.apache.org/t/bug-frontend-pytorch-relay-ir-is-inconsistent-with-that-of-the-original-model/12010\n\n    class ConvBnRelu(nn.Module):\n        def __init__(self, inp, oup, kernel_size=3, stride=1, padding=1, bias=True, groups=1):\n            super(ConvBnRelu, self).__init__()\n            if groups > 1:\n                self.conv = nn.Conv2d(\n                    inp, inp, kernel_size, stride, padding, bias=bias, groups=groups\n                )\n                self.bn = nn.BatchNorm2d(inp)\n            else:\n                self.conv = nn.Conv2d(\n                    inp, oup, kernel_size, stride, padding, bias=bias, groups=groups\n                )\n                self.bn = nn.BatchNorm2d(oup)\n            self.relu = nn.ReLU(inplace=True)\n\n        def forward(self, inputs):\n            x = self.conv(inputs)\n            x = self.bn(x)\n            x = self.relu(x)\n            return x\n\n    def conv_bn(inp, oup, stride=1, width_multiplier=1):\n        return ConvBnRelu(inp, oup, kernel_size=3, stride=stride, padding=1, bias=False)\n\n    def conv_dw(inp, oup, stride, width_multiplier=1, padding=1):\n        dw_block = nn.Sequential()\n        depth_wise = ConvBnRelu(\n            inp, oup, kernel_size=3, stride=stride, padding=padding, bias=False, groups=inp\n        )\n        point_wise = ConvBnRelu(inp, oup, kernel_size=1, stride=1, padding=0, bias=False)\n\n        dw_block.add_module(\"depth_wise\", depth_wise)\n        dw_block.add_module(\"point_wise\", point_wise)\n\n        return dw_block\n\n    class Backbone(nn.Module):\n        def __init__(self, width_multiplier=1):\n            super(Backbone, self).__init__()\n            self.width_multiplier = width_multiplier\n            self.conv1 = conv_bn(3, 16, 2, self.width_multiplier)\n            self.conv2 = conv_dw(16, 32, 1, self.width_multiplier)\n\n        def forward(self, inputs):\n            x1 = self.conv1(inputs)\n            x2 = self.conv2(x1)\n            return [x1, x2]\n\n    class QuantizableBackbone(nn.Module):\n        def __init__(self, inputsize=(128, 128)):\n            super(QuantizableBackbone, self).__init__()\n            self.quant = QuantStub()\n            self.dequant = DeQuantStub()\n            self.backbone = Backbone()\n\n        def fuse_model(self):\n            fuse_modules_qat = getattr(torch.ao.quantization, \"fuse_modules_qat\", fuse_modules)\n            for idx, m in enumerate(self.modules()):\n                if type(m) == ConvBnRelu:\n                    fuse_modules_qat(m, [\"conv\", \"bn\", \"relu\"], inplace=True)\n\n        def forward(self, input):\n            input = self.quant(input)\n            y0, y1 = self.backbone(input)\n            y0 = self.dequant(y0)\n            y1 = self.dequant(y1)\n            return y0, y1\n\n    fp32_input = torch.randn(1, 3, 128, 128)\n    model = QuantizableBackbone()\n    model.train()\n    model.fuse_model()\n    model.qconfig = get_default_qat_qconfig(\"qnnpack\")\n\n    prepare_qat(model, inplace=True)\n\n    model.eval()\n    model(fp32_input)\n\n    model_int8 = torch.quantization.convert(model, inplace=True)\n    script_module = torch.jit.trace(model_int8, fp32_input).eval()\n\n    input_infos = [(\"input\", (fp32_input.shape, \"float32\"))]\n    mod, _ = relay.frontend.from_pytorch(script_module, input_infos)\n    output = mod[\"main\"].body\n\n    assert isinstance(output, relay.Tuple) and len(output) == 2\n    dq1, dq2 = output\n    assert str(dq1.op) == \"qnn.dequantize\" and str(dq2.op) == \"qnn.dequantize\"\n    scale1 = dq1.args[1].data.numpy().item()\n    scale2 = dq2.args[1].data.numpy().item()\n    assert scale1 != scale2\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument\n\"\"\"Unit tests for various models and operators\"\"\"\nimport os\nimport platform\nimport sys\n\nfrom packaging import version as package_version\n\nimport pytest\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.nvcc import have_fp16\nfrom tvm.contrib import cudnn\n\nimport torch\nfrom torch.nn import Module\nfrom torch.nn import functional as F\nimport torchvision\n\nsys.setrecursionlimit(10000)\nif torch.cuda.is_available():\n    torch.backends.cuda.matmul.allow_tf32 = False\n    torch.backends.cudnn.allow_tf32 = False\n\n\ndef list_ops(expr):\n    \"\"\"list_ops\"\"\"\n\n    class OpLister(tvm.relay.ExprVisitor):\n        \"\"\"OpLister inherits from ExprVisitor\"\"\"\n\n        def visit_op(self, op):\n            if op not in self.node_set:\n                self.node_list.append(op)\n            return super().visit_op(op)\n\n        def list_nodes(self, expr):\n            self.node_set = {}\n            self.node_list = []\n            self.visit(expr)\n            return self.node_list\n\n    return OpLister().list_nodes(expr)\n\n\ndef assert_shapes_match(tru, est):\n    \"\"\"Verfiy whether the shapes are equal\"\"\"\n    if tru.shape != est.shape:\n        msg = \"Output shapes {} and {} don't match\"\n        raise AssertionError(msg.format(tru.shape, est.shape))\n\n\ndef load_torchvision(model_name):\n    \"\"\"Given a model name, returns a Torchvision model in eval mode as well\n    as an example input.\"\"\"\n    with torch.no_grad():\n        if model_name.startswith(\"inception\"):\n            height = width = 299\n            mean = [0.5, 0.5, 0.5]\n            std = [0.5, 0.5, 0.5]\n        else:\n            height = width = 224\n            mean = [0.485, 0.456, 0.406]\n            std = [0.229, 0.224, 0.225]\n        input_shape = [1, 3, height, width]\n        input_data = torch.randn(input_shape).float()\n        for channel in range(3):\n            input_data[:, channel] -= mean[channel]\n            input_data[:, channel] /= std[channel]\n\n        if model_name.startswith(\"googlenet\"):\n            model = getattr(torchvision.models, model_name)(pretrained=True, aux_logits=True)\n        else:\n            model = getattr(torchvision.models, model_name)(pretrained=True)\n        model = model.float().eval()\n        return model, [input_data]\n\n\ndef load_pretrainedmodels(model_name):\n    \"\"\"Given a model name, returns a pretrainedmodels.pytorch model in eval\n    mode as well as an example input.\"\"\"\n    # pylint: disable=import-outside-toplevel\n    import pretrainedmodels  # https://github.com/Cadene/pretrained-models.pytorch\n\n    model = getattr(pretrainedmodels, model_name)().float().eval()\n    input_shape = [1, *model.input_size]\n    input_data = torch.rand(input_shape).float() * 256\n    for channel in range(3):\n        input_data[:, channel] -= model.mean[channel]\n        input_data[:, channel] /= model.std[channel]\n    return model, [input_data]\n\n\ndef load_model(model_name):\n    \"\"\"Given a model name, returns a model as well as an example input.\"\"\"\n    if hasattr(torchvision.models, model_name):\n        return load_torchvision(model_name)\n    # pylint: disable=import-outside-toplevel\n    try:\n        import pretrainedmodels\n\n        if hasattr(pretrainedmodels, model_name):\n            return load_pretrainedmodels(model_name)\n    except ModuleNotFoundError as e:\n        raise ModuleNotFoundError(\"Please install pretrainedmodels.pytorch\") from e\n    raise RuntimeError(\"Model not supported\")\n\n\ndef verify_model(\n    model_name,\n    input_data=None,\n    custom_convert_map=None,\n    rtol=1e-5,\n    atol=1e-5,\n    expected_ops=None,\n    kind=\"graph\",\n    check_correctness=True,\n    cpu_only=False,\n):\n    \"\"\"Assert that the output of a compiled model matches with that of its\n    baseline.\"\"\"\n    input_data = [] if input_data is None else input_data\n    custom_convert_map = custom_convert_map or {}\n    expected_ops = expected_ops or []\n    if isinstance(model_name, str):\n        baseline_model, baseline_input = load_model(model_name)\n    elif isinstance(input_data, list):\n        baseline_model = model_name\n        baseline_input = input_data\n    elif isinstance(input_data, torch.Tensor) or not input_data.shape:\n        baseline_model = model_name\n        baseline_input = [input_data]\n    else:\n        assert False, \"Unexpected input format\"\n    if torch.cuda.is_available():\n        if isinstance(baseline_model, torch.nn.Module):\n            baseline_model = baseline_model.cuda()\n        baseline_input = [inp.cuda() for inp in baseline_input]\n\n    with torch.no_grad():\n        baseline_outputs = baseline_model(*[input.clone() for input in baseline_input])\n\n    if isinstance(baseline_outputs, tuple):\n        baseline_outputs = tuple(out.cpu().numpy() for out in baseline_outputs)\n    else:\n        baseline_outputs = (baseline_outputs.cpu().numpy(),)\n\n    trace = torch.jit.trace(baseline_model, [input.clone() for input in baseline_input])\n    if isinstance(baseline_model, torch.nn.Module):\n        trace = trace.float().eval()\n\n        if torch.cuda.is_available():\n            trace = trace.cuda()\n        else:\n            trace = trace.cpu()\n\n    input_names = [f\"input{idx}\" for idx, _ in enumerate(baseline_input)]\n    input_shapes = list(zip(input_names, [inp.shape for inp in baseline_input]))\n    mod, params = relay.frontend.from_pytorch(trace, input_shapes, custom_convert_map)\n    for arg in mod[\"main\"].params[: len(input_names)]:\n        assert arg.name_hint in input_names\n    compiled_input = dict(zip(input_names, [inp.clone().cpu().numpy() for inp in baseline_input]))\n\n    targets = [\"llvm\"]\n    if not cpu_only:\n        targets.append(\"cuda\")\n\n    with tvm.transform.PassContext(opt_level=3):\n        for target in targets:\n            if not tvm.runtime.enabled(target):\n                continue\n            dev = tvm.device(target, 0)\n            exe = relay.create_executor(\n                kind, mod=mod, params=params, device=dev, target=target\n            ).evaluate()\n            result = exe(**compiled_input)\n            if not isinstance(result, list):\n                result = [result]\n\n            for i, baseline_output in enumerate(baseline_outputs):\n                output = result[i].numpy()\n\n                assert_shapes_match(baseline_output, output)\n                if check_correctness:\n                    tvm.testing.assert_allclose(baseline_output, output, rtol=rtol, atol=atol)\n\n    if expected_ops:\n\n        def visit(op):\n            if isinstance(op, tvm.ir.op.Op):\n                if op.name in expected_ops:\n                    expected_ops.remove(op.name)\n\n        tvm.relay.analysis.post_order_visit(mod[\"main\"].body, visit)\n\n        if expected_ops:\n            msg = \"TVM Relay do not contain expected ops {}\"\n            raise AssertionError(msg.format(expected_ops))\n\n    del model_name\n    del baseline_model\n    if torch.cuda.is_available():\n        torch.cuda.empty_cache()\n\n\ndef verify_model_with_input(\n    test_func,\n    input_data,\n    *,\n    input_dict=None,\n    custom_convert_map=None,\n    rtol=1e-5,\n    atol=1e-5,\n    assert_shape_only=False,\n):\n    \"\"\"Generic function to generate and compare Pytorch and TVM output\"\"\"\n    input_dict = input_dict or {}\n    custom_convert_map = custom_convert_map or {}\n    baseline_outputs = test_func(*input_data)\n    trace = torch.jit.trace(test_func, [input.clone() for input in input_data])\n    input_names = [f\"input{idx}\" for idx, _ in enumerate(input_data)]\n    input_shapes = list(zip(input_names, [inp.shape for inp in input_data]))\n    mod, params = relay.frontend.from_pytorch(trace, input_shapes, custom_convert_map)\n    with tvm.transform.PassContext(opt_level=3):\n        for target in [\"llvm\", \"cuda\"]:\n            if not tvm.runtime.enabled(target):\n                continue\n            dev = tvm.device(target, 0)\n            lib = relay.build(mod, target=target, params=params)\n            relay_model = graph_executor.GraphModule(lib[\"default\"](dev))\n            for name, value in input_dict.items():\n                relay_model.set_input(name, value)\n            relay_model.run()\n\n            compiled_output = relay_model.get_output(0).numpy()\n            assert_shapes_match(baseline_outputs, compiled_output)\n            if assert_shape_only is False:\n                tvm.testing.assert_allclose(baseline_outputs, compiled_output, rtol=rtol, atol=atol)\n\n\n# Single operator tests\n@tvm.testing.uses_gpu\ndef test_forward_pixel_shuffle():\n    \"\"\"test_forward_pixel_shuffle\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 144, 16, 16]\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.PixelShuffle(2).float().eval(), input_data=input_data)\n    verify_model(torch.nn.PixelShuffle(3).float().eval(), input_data=input_data)\n    verify_model(torch.nn.PixelShuffle(4).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_add():\n    \"\"\"test_forward_add\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n\n    class Add1(Module):\n        def forward(self, *args):\n            return args[0] + args[0]\n\n    class Add2(Module):\n        def forward(self, *args):\n            return args[0] + 1\n\n    class Add3(Module):\n        def forward(self, *args):\n            ones = torch.ones(input_shape, dtype=torch.float)\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] + ones\n\n    class Add4(Module):\n        def forward(self, *args):\n            ones = torch.ones([], dtype=torch.float)\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] + ones\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Add1().float().eval(), input_data=input_data)\n    verify_model(Add2().float().eval(), input_data=input_data)\n    verify_model(Add3().float().eval(), input_data=input_data)\n    verify_model(Add4().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_subtract():\n    \"\"\"test_forward_subtract\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n\n    class Subtract1(Module):\n        def forward(self, *args):\n            return args[0] - args[0]\n\n    class Subtract2(Module):\n        def forward(self, *args):\n            return args[0] - 1\n\n    class Subtract3(Module):\n        def forward(self, *args):\n            ones = torch.ones(input_shape)\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] - ones\n\n    class Subtract4(Module):\n        def forward(self, *args):\n            ones = torch.ones([])\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] - ones\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Subtract1().float().eval(), input_data=input_data)\n    verify_model(Subtract2().float().eval(), input_data=input_data)\n    verify_model(Subtract3().float().eval(), input_data=input_data)\n    verify_model(Subtract4().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_multiply():\n    \"\"\"test_forward_multiply\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n\n    class Multiply1(Module):\n        def forward(self, *args):\n            return args[0] * args[0]\n\n    class Multiply2(Module):\n        def forward(self, *args):\n            return args[0] * 1.0\n\n    class Multiply3(Module):\n        def forward(self, *args):\n            ones = torch.ones(input_shape)\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] * ones\n\n    class Multiply4(Module):\n        def forward(self, *args):\n            ones = torch.ones([])\n            if torch.cuda.is_available():\n                ones = ones.cuda()\n            return args[0] * ones\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Multiply1().float().eval(), input_data=input_data)\n    verify_model(Multiply2().float().eval(), input_data=input_data)\n    verify_model(Multiply3().float().eval(), input_data=input_data)\n    verify_model(Multiply4().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_min_max():\n    \"\"\"test_min_max\"\"\"\n\n    class Max(Module):\n        def forward(self, inp):\n            return torch.max(inp)\n\n    class Min(Module):\n        def forward(self, inp):\n            return torch.min(inp)\n\n    class Max2(Module):\n        def forward(self, inp):\n            out, _ = torch.max(inp, 1, keepdim=True)\n            return out\n\n    class Min2(Module):\n        def forward(self, inp):\n            out, _ = torch.min(inp, 0, keepdim=False)\n            return out\n\n    class Max3(Module):\n        def forward(self, lhs, rhs):\n            return torch.max(lhs, rhs)\n\n    class Min3(Module):\n        def forward(self, lhs, rhs):\n            return torch.min(lhs, rhs)\n\n    class Max4(Module):\n        def forward(self, inp):\n            out = torch.amax(inp, (1, 2), keepdim=True)\n            return out\n\n    class Min4(Module):\n        def forward(self, inp):\n            out = torch.amin(inp, (0, 3), keepdim=False)\n            return out\n\n    input_data = [torch.rand((10, 10, 10, 10)), torch.rand((10, 10, 10, 10))]\n\n    verify_model(Max(), input_data=input_data[0])\n    verify_model(Min(), input_data=input_data[0])\n    verify_model(Max2(), input_data=input_data[0])\n    verify_model(Min2(), input_data=input_data[0])\n    verify_model(Max3(), input_data=input_data)\n    verify_model(Min3(), input_data=input_data)\n    verify_model(Max4(), input_data=input_data[0])\n    verify_model(Min4(), input_data=input_data[0])\n\n\n@tvm.testing.uses_gpu\ndef test_minimum_maximum():\n    \"\"\"test_minimum_maximum\"\"\"\n\n    class Maximum(Module):\n        def forward(self, lhs, rhs):\n            return torch.maximum(lhs, rhs)\n\n    class Minimum(Module):\n        def forward(self, lhs, rhs):\n            return torch.minimum(lhs, rhs)\n\n    input_data = [torch.rand((10, 10, 10, 10)), torch.rand((10, 10, 10, 10))]\n\n    verify_model(Maximum(), input_data=input_data)\n    verify_model(Minimum(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reciprocal():\n    \"\"\"test_forward_reciprocal\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [2, 1, 10, 1, 10]\n\n    class Reciprocal1(Module):\n        def forward(self, *args):\n            return args[0].reciprocal()\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Reciprocal1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_repeat():\n    \"\"\"test_forward_repeat\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3]\n\n    class Repeat1(Module):\n        def forward(self, *args):\n            return args[0].repeat(1, 1)\n\n    class Repeat2(Module):\n        def forward(self, *args):\n            return args[0].repeat(4, 2)\n\n    class Repeat3(Module):\n        def forward(self, *args):\n            return args[0].repeat(4, 2, 1)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Repeat1().float().eval(), input_data=input_data)\n    verify_model(Repeat2().float().eval(), input_data=input_data)\n    verify_model(Repeat3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_repeat_interleave():\n    \"\"\"test_forward_repeat_interleave\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [2, 2, 3]\n\n    class RepeatInterleave1(Module):\n        def forward(self, *args):\n            return args[0].repeat_interleave(2)\n\n    class RepeatInterleave2(Module):\n        def forward(self, *args):\n            return args[0].repeat_interleave(3, dim=0)\n\n    class RepeatInterleave3(Module):\n        def forward(self, *args):\n            return args[0].repeat_interleave(2, dim=1)\n\n    class RepeatInterleave4(Module):\n        def forward(self, *args):\n            return args[0].repeat_interleave(4, dim=2)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(RepeatInterleave1().float().eval(), input_data=input_data)\n    verify_model(RepeatInterleave2().float().eval(), input_data=input_data)\n    verify_model(RepeatInterleave3().float().eval(), input_data=input_data)\n    verify_model(RepeatInterleave4().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_unsqueeze():\n    \"\"\"test_forward_unsqueeze\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10, 10]\n\n    class Unsqueeze1(Module):\n        def forward(self, *args):\n            return args[0].unsqueeze(2)\n\n    class Unsqueeze2(Module):\n        def forward(self, *args):\n            _ = args[0].unsqueeze_(2)\n            # Check whether operations after inplace unsqueeze works as expected\n            y = args[0].squeeze(2)\n            return torch.add(y, y)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Unsqueeze1().float().eval(), input_data=input_data)\n    verify_model(Unsqueeze2().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_squeeze():\n    \"\"\"test_forward_squeeze\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [2, 1, 10, 1, 10]\n\n    class Squeeze1(Module):\n        def forward(self, *args):\n            return args[0].squeeze()\n\n    class Squeeze2(Module):\n        def forward(self, *args):\n            return args[0].squeeze(1)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Squeeze1().float().eval(), input_data=input_data)\n    verify_model(Squeeze2().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_arange():\n    \"\"\"test_forward_arange\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Arange1(Module):\n        def forward(self, *args):\n            return torch.arange(5)\n\n    class Arange2(Module):\n        def forward(self, *args):\n            return torch.arange(2.5)\n\n    class Arange3(Module):\n        def forward(self, *args):\n            return torch.arange(1, 4)\n\n    class Arange4(Module):\n        def forward(self, *args):\n            return torch.arange(1, 2.5, 0.5)\n\n    class Arange5(Module):\n        def forward(self, *args):\n            return torch.arange(1, 2, 1, dtype=torch.int32)\n\n    class Arange6(Module):\n        def forward(self, *args):\n            return torch.arange(start=1, end=6, step=2)\n\n    class Arange7(Module):\n        def forward(self, *args):\n            return torch.arange(1, 4, dtype=torch.float32)\n\n    class Arange8(Module):\n        def forward(self, *args):\n            return torch.arange(1, 2, 1, dtype=torch.int16)\n\n    class Arange9(Module):\n        def forward(self, *args):\n            end = torch.add(torch.tensor(4), 1)\n            return torch.arange(end) + torch.ones((5,), dtype=torch.int64)\n\n    class Arange10(Module):\n        def forward(self, *args):\n            end = torch.add(torch.tensor(4.0), torch.tensor(1.0))\n            return torch.arange(end) + torch.ones((5,), dtype=torch.float)\n\n    class Arange11(Module):\n        def forward(self, *args):\n            start = torch.add(torch.tensor(1), 1)\n            end = torch.add(torch.tensor(4), 1)\n            step = torch.add(torch.tensor(2), 1)\n            out = torch.arange(start, end, step)\n            return out + torch.ones((3,), dtype=torch.int64)\n\n    class Arange12(Module):\n        def forward(self, *args):\n            start = torch.add(torch.tensor(1), 1)\n            end = torch.add(torch.tensor(4), 1)\n            step = torch.add(torch.tensor(2.5), torch.tensor(4.1))\n            out = torch.arange(start, end, step)\n            return out + torch.ones((3,), dtype=torch.float)\n\n    verify_model(Arange1().float().eval())\n    verify_model(Arange2().float().eval())\n    verify_model(Arange3().float().eval())\n    verify_model(Arange4().float().eval())\n    verify_model(Arange5().float().eval())\n    verify_model(Arange6().float().eval())\n    verify_model(Arange7().float().eval())\n    verify_model(Arange8().float().eval())\n    verify_model(Arange9().float().eval())\n    verify_model(Arange10().float().eval())\n    verify_model(Arange11().float().eval())\n    verify_model(Arange12().float().eval())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_mesh_grid():\n    \"\"\"test_forward_mesh_grid\"\"\"\n    torch.set_grad_enabled(False)\n\n    class MeshGrid1(Module):\n        def forward(self, *args):\n            x = torch.tensor([1, 2, 3])\n            y = torch.tensor([4, 5, 6])\n            grid_x, grid_y = torch.meshgrid([x, y])\n            return grid_x, grid_y\n\n    class MeshGrid2(Module):\n        def forward(self, *args):\n            x = torch.tensor([1, 2, 3], dtype=torch.float32)\n            y = torch.add(torch.tensor(5, dtype=torch.float32), 1)\n            grid_x, grid_y = torch.meshgrid([x, y])\n            return grid_x, grid_y\n\n    verify_model(MeshGrid1().float().eval())\n    verify_model(MeshGrid2().float().eval())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_abs():\n    \"\"\"test_forward_abs\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [2, 1, 10, 1, 10]\n\n    class Abs1(Module):\n        def forward(self, *args):\n            return args[0].abs()\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Abs1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_concatenate():\n    \"\"\"test_forward_concatenate\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Concatenate1(Module):\n        def forward(self, *args):\n            return torch.cat([args[0][:, 0].unsqueeze(1), args[0][:, 1].unsqueeze(1)], 1)\n\n    class Concatenate2(Module):\n        def forward(self, *args):\n            a = (args[0][:, :, 0] + 2) * 7\n            b = (args[0][:, :, 1] + 3) * 11\n            c = (args[0][:, :, 2] + 5) * 13\n            return torch.cat([t.unsqueeze(2) for t in [a, b, c]], 2)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Concatenate1().float().eval(), input_data=input_data)\n    verify_model(Concatenate2().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_relu():\n    \"\"\"test_forward_relu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.ReLU().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_relu6():\n    \"\"\"test_forward_relu6\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.ReLU6().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_prelu():\n    \"\"\"test_forward_prelu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.PReLU(num_parameters=3).eval(), input_data=input_data)\n    # Test when input channel > 1 and num parameters = 1\n    verify_model(torch.nn.PReLU(num_parameters=1).eval(), input_data=input_data)\n    # Test when input dims < 2\n    verify_model(torch.nn.PReLU(num_parameters=1).eval(), input_data=torch.randn(2))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_leakyrelu():\n    \"\"\"test_forward_leakyrelu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.LeakyReLU().eval(), input_data=input_data)\n    verify_model(torch.nn.LeakyReLU(negative_slope=0.05).eval(), input_data=input_data)\n    verify_model(torch.nn.LeakyReLU(negative_slope=1.0, inplace=True).eval(), input_data=input_data)\n    verify_model(\n        torch.nn.LeakyReLU(negative_slope=1.25, inplace=True).eval(), input_data=input_data\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_elu():\n    \"\"\"test_forward_elu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.randn(input_shape).float()\n    verify_model(torch.nn.ELU().eval(), input_data=input_data)\n    verify_model(torch.nn.ELU(alpha=0.3).eval(), input_data=input_data)\n    verify_model(torch.nn.ELU(alpha=1.0).eval(), input_data=input_data)\n    verify_model(torch.nn.ELU(alpha=1.3).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_celu():\n    \"\"\"test_forward_celu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.CELU().eval(), input_data=input_data)\n    verify_model(torch.nn.CELU(alpha=0.3).eval(), input_data=input_data)\n    verify_model(torch.nn.CELU(alpha=1.0).eval(), input_data=input_data)\n    verify_model(torch.nn.CELU(alpha=1.3).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gelu():\n    \"\"\"test_forward_gelu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.GELU().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_selu():\n    \"\"\"test_forward_selu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.SELU().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_silu():\n    \"\"\"test_forward_silu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.SiLU().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_glu():\n    \"\"\"test_forward_glu\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.GLU().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_softplus():\n    \"\"\"test_forward_softplus\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Softplus().eval(), input_data=input_data)\n    verify_model(torch.nn.Softplus(beta=1.5, threshold=20).eval(), input_data=input_data)\n    verify_model(torch.nn.Softplus(beta=5, threshold=10).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_softsign():\n    \"\"\"test_forward_softsign\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Softsign().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_log_sigmoid():\n    \"\"\"test_forward_log_sigmoid\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10, 10]\n    input_data = torch.rand(input_shape).float()\n    input_data_overflow = torch.tensor([-300.0, -100.0]).float()\n    verify_model(torch.nn.LogSigmoid().eval(), input_data=input_data)\n    verify_model(torch.nn.LogSigmoid().eval(), input_data=input_data_overflow)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_adaptive_avgpool():\n    \"\"\"test_forward_adaptive_avgpool\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.AdaptiveAvgPool2d([1, 1]).eval(), input_data=input_data)\n    verify_model(torch.nn.AdaptiveAvgPool2d([10, 10]).eval(), input_data=input_data)\n\n    input_data = torch.rand([1, 3, 10]).float()\n    verify_model(torch.nn.AdaptiveAvgPool1d([1]).eval(), input_data=input_data)\n    verify_model(torch.nn.AdaptiveAvgPool1d([5]).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_adaptive_maxpool():\n    \"\"\"test_forward_adaptive_maxpool\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.AdaptiveMaxPool2d([1, 1]).eval(), input_data=input_data)\n    verify_model(torch.nn.AdaptiveMaxPool2d([10, 10]).eval(), input_data=input_data)\n\n    input_data = torch.rand([1, 3, 10]).float()\n    verify_model(torch.nn.AdaptiveMaxPool1d([1]).eval(), input_data=input_data)\n    verify_model(torch.nn.AdaptiveMaxPool1d([5]).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_maxpool2d():\n    \"\"\"test_forward_maxpool2d\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n\n    verify_model(torch.nn.MaxPool2d(kernel_size=[1, 1]).eval(), input_data)\n    verify_model(torch.nn.MaxPool2d(kernel_size=[2, 2], dilation=[2, 3]).eval(), input_data)\n    verify_model(torch.nn.MaxPool2d(kernel_size=[10, 10]).eval(), input_data)\n    verify_model(torch.nn.MaxPool2d(kernel_size=[4, 4], padding=2, stride=2).eval(), input_data)\n\n    # A functional variant (default strides = None case)\n    class MaxPool2D(Module):\n        def forward(self, *args):\n            return torch.nn.functional.max_pool2d(args[0], kernel_size=[10, 10])\n\n    verify_model(MaxPool2D(), input_data=input_data)\n\n    class MaxPool2DWithIndices(Module):\n        def __init__(self):\n            super().__init__()\n            self.pool = torch.nn.MaxPool2d(kernel_size=[1, 1], return_indices=True)\n\n        def forward(self, *args):\n            output, _ = self.pool(args[0])\n            return output\n\n    class MaxPool2DWithIntStrides(Module):\n        def forward(self, *args):\n            # Makes kernel_size and strides a Relay expr to test converting back to int\n            x_shape = args[0].shape\n            # kernel_size = [torch.tensor(x_shape[1]).int(), torch.tensor(x_shape[1]).int()]\n            strides = [torch.tensor(x_shape[0]).int(), torch.tensor(x_shape[0]).int()]\n            return torch.nn.functional.max_pool2d(args[0], kernel_size=[4, 4], stride=strides)\n\n    verify_model(MaxPool2DWithIndices().float().eval(), input_data=input_data)\n    verify_model(MaxPool2DWithIntStrides().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_maxpool1d():\n    \"\"\"test_forward_maxpool1d\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10]\n    input_data = torch.rand(input_shape).float()\n\n    verify_model(torch.nn.MaxPool1d(kernel_size=1).eval(), input_data)\n    verify_model(torch.nn.MaxPool1d(kernel_size=2, dilation=[1]).eval(), input_data)\n    verify_model(torch.nn.MaxPool1d(kernel_size=10).eval(), input_data)\n    verify_model(torch.nn.MaxPool1d(kernel_size=4, padding=2, stride=2).eval(), input_data)\n\n    # A functional variant (default strides = None case)\n    class MaxPool1D(Module):\n        def forward(self, *args):\n            return torch.nn.functional.max_pool1d(args[0], kernel_size=10)\n\n    verify_model(MaxPool1D(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_maxpool3d():\n    \"\"\"test_forward_maxpool3d\"\"\"\n    torch.set_grad_enabled(False)\n    for input_shape in [(1, 3, 10, 10, 10), (3, 10, 10, 10)]:\n        input_data = torch.rand(input_shape).float()\n\n        verify_model(torch.nn.MaxPool3d(kernel_size=[1, 1, 1]).eval(), input_data)\n        verify_model(\n            torch.nn.MaxPool3d(kernel_size=[2, 2, 2], dilation=[1, 2, 3]).eval(), input_data\n        )\n        verify_model(torch.nn.MaxPool3d(kernel_size=[10, 10, 10]).eval(), input_data)\n        verify_model(\n            torch.nn.MaxPool3d(kernel_size=[4, 4, 4], padding=2, stride=2).eval(), input_data\n        )\n\n    # A functional variant (default strides = None case)\n    class MaxPool3D(Module):\n        def forward(self, *args):\n            return torch.nn.functional.max_pool3d(args[0], kernel_size=[10, 10, 10])\n\n    verify_model(MaxPool3D(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_split():\n    \"\"\"test_forward_split\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [4, 10]\n\n    class Split(Module):\n        def __init__(self, split_size_or_sections, dim):\n            super().__init__()\n            self.split_size_or_sections = split_size_or_sections\n            self.dim = dim\n\n        def forward(self, *args):\n            return torch.split(args[0], self.split_size_or_sections, self.dim)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Split(2, 0).float().eval(), input_data=input_data)\n    verify_model(Split(3, 1).float().eval(), input_data=input_data)\n    verify_model(Split(4, 1).float().eval(), input_data=input_data)\n    verify_model(Split([2, 3, 5], 1).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_tensor_split():\n    \"\"\"test_forward_tensor_split\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [4, 10]\n\n    class Tensor_Split(Module):\n        def __init__(self, split_size_or_sections, dim):\n            super().__init__()\n            self.split_size_or_sections = split_size_or_sections\n            self.dim = dim\n\n        def forward(self, *args):\n            return torch.tensor_split(args[0], self.split_size_or_sections, self.dim)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Tensor_Split(2, 0).float().eval(), input_data=input_data)\n    verify_model(Tensor_Split(torch.tensor(3), 1).float().eval(), input_data=input_data)\n    verify_model(Tensor_Split([2, 3, 5], 1).float().eval(), input_data=input_data)\n    verify_model(Tensor_Split((2, 3, 5), 1).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_avgpool1d():\n    \"\"\"test_forward_avgpool1d\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10]\n\n    class AvgPool1D2(Module):\n        def forward(self, *args):\n            return torch.nn.functional.avg_pool1d(args[0], kernel_size=[10])\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.AvgPool1d(kernel_size=[10]).eval(), input_data=input_data)\n    verify_model(AvgPool1D2().float().eval(), input_data=input_data)\n    verify_model(\n        torch.nn.AvgPool1d(kernel_size=[5], stride=2, padding=2).eval(), input_data=input_data\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_avgpool2d():\n    \"\"\"test_forward_avgpool2d\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class AvgPool2D2(Module):\n        def forward(self, *args):\n            return torch.nn.functional.avg_pool2d(args[0], kernel_size=[10, 10])\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.AvgPool2d(kernel_size=[10, 10]).eval(), input_data=input_data)\n    verify_model(AvgPool2D2().float().eval(), input_data=input_data)\n    verify_model(\n        torch.nn.AvgPool2d(kernel_size=5, stride=2, padding=2).eval(), input_data=input_data\n    )\n\n    input_shape = [1, 1, 1, 9]\n    input_data = torch.rand(input_shape).float()\n    verify_model(\n        torch.nn.AvgPool2d(\n            kernel_size=[1, 2], stride=[1, 2], ceil_mode=True, count_include_pad=True\n        ).eval(),\n        input_data=input_data,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_avgpool3d():\n    \"\"\"test_forward_avgpool3d\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10, 10]\n\n    class AvgPool3D1(Module):\n        def forward(self, *args):\n            return torch.nn.functional.avg_pool3d(args[0], kernel_size=[10, 10, 10])\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.AvgPool3d(kernel_size=[10, 10, 10]).eval(), input_data=input_data)\n    verify_model(AvgPool3D1().float().eval(), input_data=input_data)\n    verify_model(\n        torch.nn.AvgPool3d(kernel_size=5, stride=2, padding=2).eval(), input_data=input_data\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_hardtanh():\n    \"\"\"test_forward_hardtanh\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Hardtanh().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_conv():\n    \"\"\"test_forward_conv\"\"\"\n    torch.set_grad_enabled(False)\n    conv1d_input_shape = [1, 3, 10]\n    conv2d_input_shape = [1, 3, 10, 10]\n\n    class Conv2D1(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv2d(3, 6, 7, bias=True)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    class Conv2D2(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv2d(3, 6, 7, bias=False)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    class Conv2D3(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv2d(3, 6, 7, groups=3, bias=False)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    class Conv1D1(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv1d(3, 6, 7)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    class Conv1D2(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv1d(3, 6, 7, bias=False)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    class Conv1D3(Module):\n        def __init__(self):\n            super().__init__()\n            self.conv = torch.nn.Conv1d(3, 6, 7, groups=3, bias=False)\n            self.softmax = torch.nn.Softmax()\n\n        def forward(self, *args):\n            return self.softmax(self.conv(args[0]))\n\n    conv2d_input_data = torch.rand(conv2d_input_shape).float()\n    verify_model(Conv2D1().float().eval(), input_data=conv2d_input_data)\n    verify_model(Conv2D2().float().eval(), input_data=conv2d_input_data)\n    # depth wise conv with channel mult 2\n    verify_model(Conv2D3().float().eval(), input_data=conv2d_input_data)\n    # group conv\n    verify_model(\n        torch.nn.Conv2d(8, 8, kernel_size=(3, 3), stride=(1, 1), groups=2).eval(),\n        input_data=torch.randn((1, 8, 16, 16)),\n    )\n\n    conv1d_input_data = torch.rand(conv1d_input_shape).float()\n    verify_model(Conv1D1().float().eval(), input_data=conv1d_input_data)\n    verify_model(Conv1D2().float().eval(), input_data=conv1d_input_data)\n    verify_model(Conv1D3().float().eval(), input_data=conv1d_input_data)\n\n\n@tvm.testing.uses_gpu\n@pytest.mark.parametrize(\"in_channels\", [3], ids=lambda x: \"in_channels=\" + str(x))\n@pytest.mark.parametrize(\"out_channels\", [5], ids=lambda x: \"out_channels=\" + str(x))\n@pytest.mark.parametrize(\"kernel_size\", [3], ids=lambda x: \"kernel_size=\" + str(x))\n@pytest.mark.parametrize(\"output_padding\", [0, 1, 2], ids=lambda x: \"output_padding=\" + str(x))\n@pytest.mark.parametrize(\"groups\", [1], ids=lambda x: \"groups=\" + str(x))\n@pytest.mark.parametrize(\"bias\", [True, False], ids=lambda x: \"bias=\" + str(x))\ndef test_forward_conv_transpose(\n    in_channels, out_channels, kernel_size, output_padding, bias, groups\n):\n    \"\"\"test_forward_conv_transpose\"\"\"\n    # Note we do not test with groups  > 1 because that is not supported\n    # in tvm for conv transpose operations\n\n    # Output padding must be smaller than either stride or dilation so we\n    # opt to make the stride 1 + output padding\n    stride = output_padding + 1\n\n    # Conv 3D Transpose Tests\n    conv3d_input_shape = [1, in_channels, 16, 16, 16]\n    conv3d_input_data = torch.rand(conv3d_input_shape).float()\n    conv3d_transpose = torch.nn.ConvTranspose3d(\n        in_channels=in_channels,\n        out_channels=out_channels,\n        kernel_size=kernel_size,\n        stride=stride,\n        output_padding=output_padding,\n        groups=groups,\n        bias=bias,\n    ).eval()\n    verify_model(conv3d_transpose, conv3d_input_data)\n\n    # Conv 2D Transpose Tests\n    conv2d_input_shape = [1, in_channels, 128, 256]\n    conv2d_input_data = torch.rand(conv2d_input_shape).float()\n    conv2d_transpose = torch.nn.ConvTranspose2d(\n        in_channels=in_channels,\n        out_channels=out_channels,\n        kernel_size=kernel_size,\n        stride=stride,\n        output_padding=output_padding,\n        groups=groups,\n        bias=bias,\n    ).eval()\n    verify_model(conv2d_transpose, conv2d_input_data)\n\n    # # Conv 1D Transpose Tests\n    conv1d_input_shape = [1, in_channels, 10]\n    conv1d_input_data = torch.rand(conv1d_input_shape).float()\n    conv1d_transpose = torch.nn.ConvTranspose1d(\n        in_channels=in_channels,\n        out_channels=out_channels,\n        kernel_size=kernel_size,\n        stride=stride,\n        output_padding=output_padding,\n        groups=groups,\n        bias=bias,\n    ).eval()\n    verify_model(conv1d_transpose, conv1d_input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_conv2d_transpose_group():\n    \"\"\"test_forward_conv2d_transpose_group\"\"\"\n    # https://github.com/apache/tvm/issues/10223\n\n    class ModulatedConvTranspose2D(torch.nn.Module):\n        \"\"\"ModulatedConvTranspose2D module\"\"\"\n\n        def forward(self, x, w, s):\n            \"\"\"forward\"\"\"\n            B, C, H, W = x.shape\n            I, O, KH, KW = w.shape\n\n            # weight is different for each input in batch (this is why we want grouped conv\n            # transpose)\n            w = w.unsqueeze(0) * s.reshape(B, 1, 1, 1, 1)\n            w = w.reshape(B * I, O, KH, KW)\n            x = x.reshape(1, B * C, H, W)\n            x = torch.nn.functional.conv_transpose2d(\n                x, w, stride=(2, 2), padding=(1, 1), output_padding=(1, 1), groups=B\n            )\n            return x.reshape(B, O, H * 2, W * 2)\n\n    b, c, h, w, k = 4, 512, 8, 16, 3\n    inputs = torch.rand(b, c, h, w)\n    weights = torch.rand(c, c // 2, k, k)\n    styles = torch.rand(b)\n\n    # cuda not supported for group > 1 conv2d_transpose\n    targets = [\"llvm\"]\n\n    if cudnn.exists():\n        targets.append(\"cuda -libs=cudnn\")\n\n    verify_trace_model(ModulatedConvTranspose2D().eval(), [inputs, weights, styles], targets)\n\n\ndef test_forward_deform_conv():\n    \"\"\"test_forward_deform_conv\"\"\"\n    torch.set_grad_enabled(False)\n\n    def test_run(\n        batch_size,\n        in_channels,\n        out_channels,\n        in_height,\n        in_width,\n        out_height,\n        out_width,\n        offset_groups,\n        kh,\n        kw,\n        groups,\n    ):\n        input_shape = [batch_size, in_channels, in_height, in_width]\n        offset_shape = [batch_size, 2 * offset_groups * kh * kw, out_height, out_width]\n        weight_shape = [out_channels, in_channels // groups, kh, kw]\n        input_data = torch.rand(input_shape)\n        offset_data = torch.rand(offset_shape)\n        weight_data = torch.rand(weight_shape)\n\n        class DeformConv2D(Module):\n            def forward(self, *args):\n                return torchvision.ops.deform_conv2d(args[0], args[1], args[2])\n\n        verify_model(\n            DeformConv2D().float().eval(),\n            input_data=[input_data, offset_data, weight_data],\n            rtol=1e-4,\n            atol=1e-4,\n        )\n\n    batch_size = 4\n    in_channels, out_channels = 4, 6\n    in_height, in_width = 10, 10\n    out_height, out_width = 8, 8\n    offset_groups = 2\n    kh, kw = 3, 3\n    groups = 1\n\n    test_run(\n        batch_size,\n        in_channels,\n        out_channels,\n        in_height,\n        in_width,\n        out_height,\n        out_width,\n        offset_groups,\n        kh,\n        kw,\n        groups,\n    )\n\n    batch_size = 5\n    in_channels, out_channels = 4, 6\n    in_height, in_width = 10, 10\n    out_height, out_width = 8, 8\n    offset_groups = 1\n    kh, kw = 3, 3\n    groups = 1\n\n    test_run(\n        batch_size,\n        in_channels,\n        out_channels,\n        in_height,\n        in_width,\n        out_height,\n        out_width,\n        offset_groups,\n        kh,\n        kw,\n        groups,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_threshold():\n    \"\"\"test_forward_threshold\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Threshold(0, 0).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_contiguous():\n    \"\"\"test_forward_contiguous\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n\n    class Contiguous1(Module):\n        def forward(self, *args):\n            return args[0].contiguous()\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Contiguous1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_batchnorm():\n    \"\"\"test_forward_batchnorm\"\"\"\n\n    def init_weight(m):\n        torch.nn.init.normal_(m.weight, 0, 0.01)\n        torch.nn.init.normal_(m.bias)\n\n    inp_2d = torch.rand((1, 16, 10, 10))\n    inp_3d = torch.rand((1, 16, 10, 10, 10))\n\n    for bn, inp in [(torch.nn.BatchNorm2d(16), inp_2d), (torch.nn.BatchNorm3d(16), inp_3d)]:\n        init_weight(bn.eval())\n        verify_model(bn.eval(), input_data=inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_instancenorm():\n    \"\"\"test_forward_instancenorm\"\"\"\n    inp_2d = torch.rand((1, 16, 10, 10))\n    inp_3d = torch.rand((1, 16, 10, 10, 10))\n\n    for ins_norm, inp in [\n        (torch.nn.InstanceNorm2d(16), inp_2d),\n        (torch.nn.InstanceNorm3d(16), inp_3d),\n    ]:\n        verify_model(ins_norm.eval(), input_data=inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_layernorm():\n    \"\"\"test_forward_layernorm\"\"\"\n\n    def init_weight(m):\n        torch.nn.init.normal_(m.weight, 0, 0.01)\n        torch.nn.init.normal_(m.bias, 0.02)\n\n    inp_2d = torch.rand((1, 16, 10, 10))\n    inp_3d = torch.rand((1, 16, 10, 10, 10))\n    for ln, inp in [(torch.nn.LayerNorm(10), inp_2d), (torch.nn.LayerNorm(10), inp_3d)]:\n        init_weight(ln.eval())\n        verify_model(ln.eval(), input_data=inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_groupnorm():\n    \"\"\"test_forward_groupnorm\"\"\"\n    input_shape = [10, 6, 5, 5]\n    input_data = torch.rand(input_shape).float()\n\n    # Separate 6 channels into 3 groups\n    verify_model(torch.nn.GroupNorm(3, 6).eval(), input_data=input_data)\n\n    # Put all 6 channels into a single group (equivalent with LayerNorm)\n    verify_model(torch.nn.GroupNorm(1, 6).eval(), input_data=input_data)\n\n    # Separate 6 channels into 6 groups (equivalent with InstanceNorm)\n    verify_model(torch.nn.GroupNorm(6, 6).eval(), input_data=input_data)\n\n    input_shape = [1, 10, 4, 7]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.GroupNorm(1, 10).eval(), input_data=input_data)\n    verify_model(torch.nn.GroupNorm(2, 10).eval(), input_data=input_data)\n    verify_model(torch.nn.GroupNorm(5, 10).eval(), input_data=input_data)\n    verify_model(torch.nn.GroupNorm(10, 10).eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reshape():\n    \"\"\"test_forward_reshape\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [2, 1, 10, 1, 10]\n    new_shape = [2, 1, 10, 10]\n\n    class Reshape1(Module):\n        def forward(self, *args):\n            return args[0].reshape(new_shape)\n\n    class Reshape2(Module):\n        def forward(self, *args):\n            return args[0].reshape([-1])\n\n    class Reshape3(torch.nn.Module):\n        def forward(self, x):\n            x_shape = x.shape\n            return x.reshape((x_shape[0] * x_shape[1], x_shape[2]))\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Reshape1(), input_data=input_data)\n    verify_model(Reshape2(), input_data=input_data)\n    verify_model(Reshape3(), input_data=torch.randn(2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reshape_as():\n    \"\"\"test_forward_reshape_as\"\"\"\n\n    def test_func(input_tensor, other_tensor):\n        return input_tensor.reshape_as(other_tensor)\n\n    input_data = [torch.rand([2, 1, 10, 1, 10]), torch.rand([2, 1, 10, 10])]\n\n    verify_model_with_input(test_func, input_data, input_dict={\"input0\": input_data[0]})\n\n\n@tvm.testing.uses_gpu\ndef test_flatten():\n    \"\"\"test_flatten\"\"\"\n\n    def _test_flatten(start_dim, end_dim):\n        return lambda inp: torch.flatten(inp, start_dim, end_dim)\n\n    inp = torch.rand((3, 5, 2, 2))\n\n    # [3, 5, 2, 2] -> [60]\n    verify_model(_test_flatten(0, -1), inp)\n    verify_model(_test_flatten(0, 3), inp)\n    verify_model(_test_flatten(-4, 3), inp)\n    verify_model(_test_flatten(-4, -1), inp)\n\n    # [3, 5, 2, 2] -> [3, 5, 2, 2]\n    verify_model(_test_flatten(3, -1), inp)\n    verify_model(_test_flatten(-1, -1), inp)\n    verify_model(_test_flatten(0, -4), inp)\n    verify_model(_test_flatten(-4, -4), inp)\n\n    # [3, 5, 2, 2] -> [3, 10, 2]\n    verify_model(_test_flatten(1, 2), inp)\n    verify_model(_test_flatten(1, -2), inp)\n    verify_model(_test_flatten(-3, 2), inp)\n    verify_model(_test_flatten(-3, -2), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_transpose():\n    \"\"\"test_forward_transpose\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Transpose1(Module):\n        def forward(self, *args):\n            return args[0].transpose(2, 3)\n\n    class Transpose2(Module):\n        def forward(self, *args):\n            return args[0].transpose(-2, -1)\n\n    class Transpose3(Module):\n        def forward(self, *args):\n            return args[0].permute(0, 2, 3, 1)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Transpose1().float().eval(), input_data=input_data)\n    verify_model(Transpose2().float().eval(), input_data=input_data)\n    verify_model(Transpose3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_numpy_T():\n    \"\"\"test_forward_numpy_T\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    def test_fn(x):\n        return x.T\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(test_fn, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_size():\n    \"\"\"test_forward_size\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3]\n\n    class Size1(Module):\n        def forward(self, *args):\n            return float(args[0].size(0)) * args[0]\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Size1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_type_as():\n    \"\"\"test_type_as\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3]\n\n    def _create_module(dtype):\n        class TypeAs(Module):\n            def forward(self, *args):\n                expected_type_tensor = torch.zeros(1, 3, dtype=dtype)\n                return args[0].type_as(expected_type_tensor)\n\n        return TypeAs()\n\n    input_data = torch.randn(input_shape).float()\n    verify_model(_create_module(torch.float64), input_data=input_data)\n    verify_model(_create_module(torch.float32), input_data=input_data)\n    verify_model(_create_module(torch.int64), input_data=input_data)\n    verify_model(_create_module(torch.int32), input_data=input_data)\n    verify_model(_create_module(torch.int16), input_data=input_data)\n    verify_model(_create_module(torch.int8), input_data=input_data)\n\n    if torch.cuda.is_available():\n        check_fp16 = False\n        try:\n            # Only check half precision on supported hardwares.\n            if have_fp16(tvm.cuda(0).compute_version):\n                check_fp16 = True\n        # pylint: disable=broad-except\n        except Exception:\n            # If GPU is not enabled in TVM, skip the fp16 test.\n            pass\n\n        # Temporary disable fp16 test\n        check_fp16 = False\n\n        if check_fp16:\n            verify_model(_create_module(torch.float16), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_view():\n    \"\"\"test_forward_view\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class View1(Module):\n        def forward(self, *args):\n            return args[0].view((1, 3 * 10 * 10))\n\n    class View2(Module):\n        def forward(self, *args):\n            return args[0].view(args[0].shape[0], -1)\n\n    class View3(Module):\n        def forward(self, *args):\n            d1 = torch.tensor(3) * torch.tensor(10) * torch.tensor(10)\n            return args[0].view(args[0].shape[0], d1)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(View1().float().eval(), input_data=input_data)\n    verify_model(View2().float().eval(), input_data=input_data)\n    verify_model(View3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_select():\n    \"\"\"test_forward_select\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [5, 3, 10, 10]\n\n    class Select1(Module):\n        def forward(self, *args):\n            return args[0].select(1, 1)\n\n    class IndexedSelect(Module):\n        def __init__(self, inp, dim):\n            super().__init__()\n            self.inp = inp\n            self.dim = dim\n            if torch.cuda.is_available():\n                self.inp = self.inp.cuda()\n\n        def forward(self, index):\n            return torch.index_select(self.inp, self.dim, index)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Select1().float().eval(), input_data=input_data)\n\n    # test negative indexing\n    verify_model(lambda x: x[-1], input_data=input_data)\n\n    x = torch.randn(3, 4)\n    indices = torch.tensor([0, 2])\n    verify_model(IndexedSelect(x, 0).eval(), input_data=indices)\n    verify_model(IndexedSelect(x, 1).eval(), input_data=indices)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_clone():\n    \"\"\"test_forward_clone\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [10]\n\n    class Clone1(Module):\n        def forward(self, *args):\n            return args[0].clone()\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Clone1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_gather():\n    \"\"\"test_forward_gather\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Gather1(Module):\n        def forward(self, *args):\n            return torch.gather(args[0], 0, args[1])\n\n    class Gather2(Module):\n        def forward(self, *args):\n            return torch.gather(args[0], 1, args[1])\n\n    class Gather3(Module):\n        def forward(self, *args):\n            return torch.gather(args[0], 2, args[1])\n\n    input_data = torch.rand((4,)).float()\n    index = torch.tensor([1])\n    verify_model(Gather1().float().eval(), input_data=[input_data, index])\n\n    input_data = torch.rand((2, 2)).float()\n    index = torch.tensor([[1, 0], [0, 1]])\n    verify_model(Gather1().float().eval(), input_data=[input_data, index])\n\n    input_data = torch.tensor([[1, 2], [3, 4]])\n    index = torch.tensor([[0, 0], [1, 0]])\n    verify_model(Gather2().float().eval(), input_data=[input_data, index])\n\n    input_data = torch.rand((2, 2)).float()\n    index = torch.tensor([[1, 0], [0, 1]])\n    verify_model(Gather2().float().eval(), input_data=[input_data, index])\n\n    input_data = torch.rand((3, 3, 3)).float()\n    index = torch.tensor(\n        [\n            [[1, 0, 0], [1, 0, 1], [0, 1, 1]],\n            [[1, 1, 1], [1, 2, 1], [1, 0, 1]],\n            [[1, 2, 1], [1, 2, 1], [1, 2, 1]],\n        ]\n    )\n    verify_model(Gather3().float().eval(), input_data=[input_data, index])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logsoftmax():\n    \"\"\"test_forward_logsoftmax\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class LogSoftmax1(Module):\n        def forward(self, *args):\n            return torch.nn.LogSoftmax(dim=1)(args[0][0, 0])\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(LogSoftmax1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_norm():\n    \"\"\"test_forward_norm\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Norm1(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(\"inf\"), dim=None, keepdim=False)\n\n    class Norm2(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(\"-inf\"), dim=None, keepdim=False)\n\n    class Norm3(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(\"-inf\"), dim=None, keepdim=True)\n\n    class Norm4(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(\"inf\"), dim=(1, 2), keepdim=False)\n\n    class Norm5(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(\"inf\"), dim=(1), keepdim=True)\n\n    class Norm6(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(0.5), dim=(1), keepdim=True)\n\n    class Norm7(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(1), dim=None, keepdim=False)\n\n    class Norm8(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(2.0), dim=(1), keepdim=True)\n\n    class Norm9(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(-0.5), dim=(1, 2), keepdim=True)\n\n    class Norm10(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=float(-2), dim=(1), keepdim=False)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Norm1().float().eval(), input_data=input_data)\n    verify_model(Norm2().float().eval(), input_data=input_data)\n    verify_model(Norm3().float().eval(), input_data=input_data)\n    verify_model(Norm4().float().eval(), input_data=input_data)\n    verify_model(Norm5().float().eval(), input_data=input_data)\n    verify_model(Norm6().float().eval(), input_data=input_data)\n    verify_model(Norm7().float().eval(), input_data=input_data)\n    verify_model(Norm8().float().eval(), input_data=input_data)\n    verify_model(Norm9().float().eval(), input_data=input_data)\n    verify_model(Norm10().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_frobenius_norm():\n    \"\"\"test_forward_frobenius_norm\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class FroNorm1(Module):\n        def forward(self, *args):\n            return torch.norm(args[0])\n\n    class FroNorm2(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=\"fro\", dim=None, keepdim=True)\n\n    class FroNorm3(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], p=\"fro\", dim=(1), keepdim=True)\n\n    class FroNorm4(Module):\n        def forward(self, *args):\n            return torch.norm(args[0], dim=None, keepdim=False)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(FroNorm1().float().eval(), input_data=input_data)\n    verify_model(FroNorm2().float().eval(), input_data=input_data)\n    verify_model(FroNorm3().float().eval(), input_data=input_data)\n    verify_model(FroNorm4().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_sigmoid():\n    \"\"\"test_forward_sigmoid\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Sigmoid().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dense():\n    \"\"\"test_forward_dense\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Dense1(Module):\n        def __init__(self):\n            super().__init__()\n            self.linear = torch.nn.Linear(10, 7, bias=True)\n\n        def forward(self, *args):\n            return self.linear(args[0][0, 0])\n\n    class Dense2(Module):\n        def __init__(self):\n            super().__init__()\n            self.linear = torch.nn.Linear(10, 7, bias=False)\n\n        def forward(self, *args):\n            return self.linear(args[0][0, 0])\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Dense1().float().eval(), input_data=input_data)\n    verify_model(Dense2().float().eval(), input_data=input_data)\n\n    trace = torch.jit.trace(Dense1(), [input_data])\n    mod, _ = relay.frontend.from_pytorch(\n        trace,\n        [(\"input\", input_shape)],\n    )\n    assert not any(list(op.name == \"multiply\" for op in list_ops(mod[\"main\"])))\n\n\n@tvm.testing.uses_gpu\ndef test_forward_linear():\n    \"\"\"test_forward_linear\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Linear(Module):\n        def forward(self, inputs, weight, bias):\n            return F.linear(inputs, weight, bias)\n\n    class LinearNoBias(Module):\n        def forward(self, inputs, weight):\n            return F.linear(inputs, weight)\n\n    class LinearNested(torch.nn.Module):\n        def forward(self, x, y, z):\n            return F.linear(x, F.linear(y, z))\n\n    input2d = torch.rand([2, 2]).float()\n    input3d = torch.rand([4, 3, 2]).float()\n    weight1d = torch.rand([2]).float()\n    weight2d = torch.rand([2, 2]).float()\n    weight3x2 = torch.rand([3, 2]).float()\n    bias1d = torch.rand([2]).float()\n    bias2d = torch.rand([2, 2]).float()\n    # 2D input, 2D weight, 1D bias\n    verify_model(Linear(), input_data=[input2d, weight2d, bias1d])\n    # 2D input, 2D weight, 2D bias\n    verify_model(Linear(), input_data=[input2d, weight2d, bias2d])\n    # 2D input, 2D weight, no bias\n    verify_model(LinearNoBias(), input_data=[input2d, weight2d])\n    verify_model(LinearNoBias(), input_data=[input2d, weight3x2])\n    # 2D input, 1D weight, 1D bias is not supported by torch.linear()\n    # 2D input, 1D weight, no bias\n    verify_model(LinearNoBias(), input_data=[input2d, weight1d])\n    # 3D input, 2D weight, no bias\n    verify_model(LinearNoBias(), input_data=[input3d, weight3x2])\n    # 3D input, 2D weight, 1D bias\n    verify_model(Linear(), input_data=[input3d, weight2d, bias1d])\n\n    verify_model(LinearNested(), input_data=[torch.randn(10, 10) for _ in range(3)])\n\n    # TODO: Add the following cases when matmul(1D, _) is supported by TVM\n    # 1D input, 2D weight, 1D bias\n    # 1D input, 2D weight, no bias\n    # 1D input, 1D weight, scalar bias\n    # 1D input, 1D weight, no bias\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dropout():\n    \"\"\"test_forward_dropout\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(torch.nn.Dropout(p=0.5).eval(), input_data=input_data[0, 0])\n    verify_model(torch.nn.Dropout2d(p=0.5).eval(), input_data=input_data[0])\n    verify_model(torch.nn.Dropout3d(p=0.5).eval(), input_data=input_data)\n    verify_model(torch.nn.AlphaDropout(p=0.5).eval(), input_data=input_data[0, 0])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_slice():\n    \"\"\"test_forward_slice\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Slice1(Module):\n        def forward(self, *args):\n            return args[0][:, :, :, :3]\n\n    class Slice2(Module):\n        def forward(self, *args):\n            return args[0][0, :, :-3, :]\n\n    class Slice3(Module):\n        def forward(self, *args):\n            x0 = torch.tensor(2) - torch.tensor(1)\n            x1 = torch.tensor(3) + torch.tensor(1)\n            return args[0][:, x0:, 1:x1, :]\n\n    class SliceWithStride(torch.nn.Module):\n        def forward(self, x):\n            return x[..., 0::2] + x[..., 1::2]\n\n    class SliceWithStride2(torch.nn.Module):\n        def forward(self, x):\n            return x[0::2, 0::2] + x[1::2, 1::2]\n\n    class DynamicLengthSlice(torch.nn.Module):\n        def forward(self, values, length):\n            return values[0:length]\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Slice1(), input_data=input_data)\n    verify_model(Slice2(), input_data=input_data)\n    verify_model(Slice3(), input_data=input_data)\n    verify_model(SliceWithStride(), input_data=torch.randn(1, 4))\n    verify_model(SliceWithStride2(), input_data=torch.randn(4, 4))\n\n    inp = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n    slice_len = torch.tensor(2)\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(DynamicLengthSlice(), [inp, slice_len], targets)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_narrow():\n    \"\"\"test_forward_narrow\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [3, 3]\n\n    class Narrow1(Module):\n        def forward(self, *args):\n            return torch.narrow(args[0], 0, 0, 2)\n\n    class Narrow2(Module):\n        def forward(self, *args):\n            return torch.narrow(args[0], 1, 1, 2)\n\n    class Narrow3(Module):\n        def forward(self, *args):\n            begin = torch.tensor(2) - torch.tensor(1)\n            length = torch.tensor(1) * torch.tensor(2)\n            return torch.narrow(args[0], 1, begin, length)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Narrow1(), input_data=input_data)\n    verify_model(Narrow2(), input_data=input_data)\n    verify_model(Narrow3(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_mean():\n    \"\"\"test_forward_mean\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Mean1(Module):\n        def forward(self, *args):\n            return args[0].mean(2)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Mean1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_expand():\n    \"\"\"test_forward_expand\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Expand1(Module):\n        def forward(self, *args):\n            return args[0].expand((3, -1, -1, -1))\n\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(Expand1().float().eval(), input_data=input_data)\n\n    class Expand2(Module):\n        def forward(self, *args):\n            return args[0].expand((3, 3, 3, 1))\n\n    input_shape = [3, 1]\n    input_data = torch.rand(input_shape).float()\n    verify_model(Expand2().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_broadcast_tensors():\n    \"\"\"test_forward_broadcast_tensors\"\"\"\n    torch.set_grad_enabled(False)\n\n    class BroadCastTensors1(Module):\n        def forward(self, x, y):\n            return torch.broadcast_tensors(x, y)\n\n    x = torch.arange(3).view(1, 1, 3)\n    y = torch.arange(2).view(1, 2, 1)\n    verify_model(BroadCastTensors1().float().eval(), input_data=[x, y])\n\n    class BroadCastTensors2(Module):\n        def forward(self, x, y, z):\n            return torch.broadcast_tensors(x, y, z)\n\n    x = torch.arange(3).view(1, 1, 3)\n    y = torch.arange(2).view(1, 2, 1)\n    z = torch.arange(4).view(4, 1, 1)\n    verify_model(BroadCastTensors2().float().eval(), input_data=[x, y, z])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pow():\n    \"\"\"test_forward_pow\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Pow1(Module):\n        def forward(self, *args):\n            return args[0] ** 2\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Pow1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_chunk():\n    \"\"\"test_forward_chunk\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 14, 14]\n\n    class Chunk1(Module):\n        def forward(self, *args):\n            chunks = args[0].chunk(7, 2)\n            return torch.cat(chunks, 2)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Chunk1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_upsample():\n    \"\"\"test_upsample\"\"\"\n\n    class Upsample(Module):\n        def __init__(self, size=None, scale=None, mode=\"nearest\", align_corners=None):\n            super().__init__()\n            self.size = size\n            self.scale = scale\n            self.mode = mode\n            self.align_corners = align_corners\n\n        def forward(self, x):\n            return torch.nn.functional.interpolate(\n                x,\n                size=self.size,\n                scale_factor=self.scale,\n                mode=self.mode,\n                align_corners=self.align_corners,\n            )\n\n    inp = torch.rand((1, 3, 32, 32))\n    verify_model(Upsample(size=(64, 64), mode=\"nearest\"), inp)\n    verify_model(Upsample(scale=2, mode=\"nearest\"), inp)\n    verify_model(Upsample(size=(50, 50), mode=\"nearest\"), inp)\n    verify_model(Upsample(size=(64, 64), mode=\"bilinear\", align_corners=True), inp)\n    verify_model(Upsample(scale=2, mode=\"bilinear\", align_corners=True), inp)\n    verify_model(Upsample(size=(50, 50), mode=\"bilinear\", align_corners=True), inp)\n    verify_model(Upsample(size=(64, 64), mode=\"bicubic\", align_corners=True), inp)\n    verify_model(Upsample(scale=2, mode=\"bicubic\", align_corners=True), inp)\n    verify_model(Upsample(size=(50, 50), mode=\"bicubic\", align_corners=True), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_to():\n    \"\"\"test for aten::to(...)\"\"\"\n\n    class ToCPU(Module):\n        def forward(self, x):\n            return x.to(\"cpu\")\n\n    class ToFloat(Module):\n        def forward(self, x):\n            return x.float()\n\n    class ToInt(Module):\n        def forward(self, x):\n            return x.int()\n\n    class ToLong(Module):\n        def forward(self, x):\n            return x.long()\n\n    class ToDouble(Module):\n        def forward(self, x):\n            return x.double()\n\n    class ToFloat16(Module):\n        def forward(self, x):\n            return x.to(torch.float16)\n\n    verify_model(ToCPU().eval(), torch.rand((1, 3, 32, 32)))\n    verify_model(ToFloat().eval(), torch.zeros((1, 3, 32, 32), dtype=torch.int))\n    verify_model(ToFloat().eval(), torch.tensor(2, dtype=torch.int))\n    verify_model(ToInt().eval(), torch.zeros((1, 3, 32, 32)))\n    verify_model(ToInt().eval(), torch.tensor(0.8))\n    verify_model(ToLong().eval(), torch.tensor(0.8))\n    verify_model(ToDouble().eval(), torch.tensor(0.8))\n    verify_model(ToFloat16().eval(), torch.tensor(2, dtype=torch.float32))\n    verify_model(ToFloat16().eval(), torch.zeros((1, 3, 32, 32), dtype=torch.int))\n\n\n@tvm.testing.uses_gpu\ndef test_adaptive_pool3d():\n    \"\"\"test_adaptive_pool3d\"\"\"\n    for ishape in [(1, 32, 16, 16, 16), (1, 32, 9, 15, 15), (1, 32, 13, 7, 7)]:\n        inp = torch.rand(ishape)\n        verify_model(torch.nn.AdaptiveMaxPool3d((1, 1, 1)).eval(), inp)\n        verify_model(torch.nn.AdaptiveMaxPool3d((2, 2, 2)).eval(), inp)\n        verify_model(torch.nn.AdaptiveAvgPool3d((1, 1, 1)).eval(), inp)\n        verify_model(torch.nn.AdaptiveAvgPool3d((2, 2, 2)).eval(), inp)\n        verify_model(torch.nn.AdaptiveAvgPool3d((4, 8, 8)).eval(), inp)\n        verify_model(torch.nn.AdaptiveMaxPool3d((7, 8, 9)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_functional_pad():\n    \"\"\"test_forward_functional_pad\"\"\"\n    torch.set_grad_enabled(False)\n    pad = (0, 0)\n\n    class Pad1(Module):\n        def forward(self, *args):\n            return torch.nn.functional.pad(args[0], pad, \"constant\", 0)\n\n    input_data = torch.rand((3, 3, 4, 2))\n    pad = (1, 1)\n    verify_model(Pad1().float().eval(), input_data=input_data)\n\n    pad = (1, 1, 2, 2)\n    verify_model(Pad1().float().eval(), input_data=input_data)\n\n    pad = (0, 1, 2, 1, 3, 3)\n    verify_model(Pad1().float().eval(), input_data=input_data)\n\n    class Pad2(Module):\n        def forward(self, *args):\n            return torch.nn.functional.pad(args[0], pad, \"constant\", 1)\n\n    input_data = torch.rand((3, 3, 4, 2))\n    pad = (1, 1)\n    verify_model(Pad2().float().eval(), input_data=input_data)\n\n    pad = (1, 1, 2, 2)\n    verify_model(Pad2().float().eval(), input_data=input_data)\n\n    pad = (0, 1, 2, 1, 3, 3)\n    verify_model(Pad2().float().eval(), input_data=input_data)\n\n    class Pad3(Module):\n        def forward(self, *args):\n            return torch.nn.functional.pad(args[0], pad, \"constant\", 1.0)\n\n    input_data = torch.rand((3, 3, 4, 2))\n    pad = (1, 1)\n    verify_model(Pad3().float().eval(), input_data=input_data)\n\n    pad = (1, 1, 2, 2)\n    verify_model(Pad3().float().eval(), input_data=input_data)\n\n    pad = (0, 1, 2, 1, 3, 3)\n    verify_model(Pad3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_zero_pad2d():\n    \"\"\"test_forward_zero_pad2d\"\"\"\n    inp = torch.rand((1, 1, 3, 3))\n    verify_model(torch.nn.ZeroPad2d(2).eval(), inp)\n    verify_model(torch.nn.ZeroPad2d((1, 1, 2, 0)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_constant_pad1d():\n    \"\"\"test_forward_constant_pad1d\"\"\"\n    inp = torch.rand((1, 2, 4))\n    verify_model(torch.nn.ConstantPad1d(2, 3.5).eval(), inp)\n\n    inp = torch.rand((1, 2, 3))\n    verify_model(torch.nn.ConstantPad1d((3, 1), 3.5).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_constant_pad2d():\n    \"\"\"test_forward_constant_pad2d\"\"\"\n    inp = torch.rand((1, 2, 2, 2))\n    verify_model(torch.nn.ConstantPad2d(2, 3.5).eval(), inp)\n    verify_model(torch.nn.ConstantPad2d((3, 0, 2, 1), 3.5).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_constant_pad3d():\n    \"\"\"test_forward_constant_pad3d\"\"\"\n    inp = torch.rand((1, 3, 2, 2, 2))\n    verify_model(torch.nn.ConstantPad3d(3, 3.5).eval(), inp)\n    verify_model(torch.nn.ConstantPad3d((3, 4, 5, 6, 0, 1), 3.5).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reflection_pad1d():\n    \"\"\"test_forward_reflection_pad1d\"\"\"\n    inp = torch.rand((1, 2, 4))\n    verify_model(torch.nn.ReflectionPad1d(2).eval(), inp)\n    verify_model(torch.nn.ReflectionPad1d((3, 1)).eval(), inp)\n\n    inp = torch.rand((2, 4, 5))\n    verify_model(torch.nn.ReflectionPad1d((2, 3)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reflection_pad2d():\n    \"\"\"test_forward_reflection_pad2d\"\"\"\n    inp = torch.rand((1, 1, 3, 3))\n    verify_model(torch.nn.ReflectionPad2d(2).eval(), inp)\n    verify_model(torch.nn.ReflectionPad2d((1, 1, 2, 0)).eval(), inp)\n\n    inp = torch.rand((2, 4, 5, 6))\n    verify_model(torch.nn.ReflectionPad2d((1, 3, 2, 4)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_replication_pad1d():\n    \"\"\"test_forward_replication_pad1d\"\"\"\n    inp = torch.rand((1, 2, 4))\n    verify_model(torch.nn.ReplicationPad1d(2).eval(), inp)\n    verify_model(torch.nn.ReplicationPad1d((3, 1)).eval(), inp)\n\n    inp = torch.rand((2, 4, 5))\n    verify_model(torch.nn.ReplicationPad1d((2, 3)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_replication_pad2d():\n    \"\"\"test_forward_replication_pad2d\"\"\"\n    inp = torch.rand((1, 1, 3, 3))\n    verify_model(torch.nn.ReplicationPad2d(2).eval(), inp)\n    verify_model(torch.nn.ReplicationPad2d((1, 1, 2, 0)).eval(), inp)\n\n    inp = torch.rand((2, 4, 5, 6))\n    verify_model(torch.nn.ReplicationPad2d((1, 3, 2, 4)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_replication_pad3d():\n    \"\"\"test_forward_replication_pad3d\"\"\"\n    inp = torch.rand((1, 1, 3, 3, 3))\n    verify_model(torch.nn.ReplicationPad3d(3).eval(), inp)\n    verify_model(torch.nn.ReplicationPad3d((1, 1, 2, 2, 1, 1)).eval(), inp)\n\n    inp = torch.rand((7, 5, 4, 5, 6))\n    verify_model(torch.nn.ReplicationPad3d((2, 3, 2, 5, 1, 4)).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_upsample3d():\n    \"\"\"test_forward_upsample3d\"\"\"\n    inp = torch.arange(1, 9, dtype=torch.float32).view(1, 1, 2, 2, 2)\n    verify_model(torch.nn.Upsample(scale_factor=2, mode=\"nearest\").eval(), inp)\n    verify_model(torch.nn.Upsample(scale_factor=2, mode=\"trilinear\").eval(), inp)\n    verify_model(\n        torch.nn.Upsample(scale_factor=2, mode=\"trilinear\", align_corners=True).eval(), inp\n    )\n\n\ndef test_forward_nms():\n    \"\"\"dynamic Non-Maximum Suppression\"\"\"\n    torch.set_grad_enabled(False)\n\n    class NonMaxSupression(Module):\n        def __init__(self, iou_thres):\n            super().__init__()\n            self.iou_threshold = iou_thres\n\n        def forward(self, *args):\n            return torchvision.ops.nms(args[0], args[1], self.iou_threshold)\n\n    # Generate random input data\n    def _gen_rand_inputs(num_boxes):\n        box_len = 4\n        boxes = torch.rand(num_boxes, box_len, dtype=torch.float) * 0.5\n        boxes[:, 2] += boxes[:, 0]\n        boxes[:, 3] += boxes[:, 1]\n        scores = np.linspace(0, 1, num=num_boxes).astype(\"float32\")\n        np.random.shuffle(scores)\n        return boxes, torch.from_numpy(scores)\n\n    targets = [\"llvm\", \"cuda\"]\n\n    for num_boxes, iou_thres in [(10, 0.3), (100, 0.5), (500, 0.9)]:\n        in_boxes, in_scores = _gen_rand_inputs(num_boxes)\n        verify_trace_model(NonMaxSupression(iou_thres), [in_boxes, in_scores], targets)\n\n\ndef test_forward_roi_align():\n    \"\"\"ROI align\"\"\"\n    torch.set_grad_enabled(False)\n\n    class ROIAlign(Module):\n        def __init__(self, output_sizes, spatial_scale=1.0, sampling_ratio=-1):\n            super().__init__()\n            self.spatial_scale = spatial_scale\n            self.sampling_ratio = sampling_ratio\n            self.output_sizes = output_sizes\n\n        def forward(self, *args):\n            return torchvision.ops.roi_align(\n                args[0],\n                args[1],\n                self.output_sizes,\n                self.spatial_scale,\n                self.sampling_ratio,\n            )\n\n    in_data = torch.Tensor(np.random.uniform(size=(1, 8, 100, 100)))\n    in_boxes = torch.Tensor(np.random.uniform(0.0, 100.0, size=(35, 4)))\n    in_batch = torch.zeros((35, 1), dtype=torch.float)\n    in_boxes = torch.cat([in_batch, in_boxes], dim=1)\n\n    verify_model(ROIAlign(7), [in_data, in_boxes])\n    verify_model(ROIAlign((10, 10), 0.7, 5), [in_data, in_boxes])\n    verify_model(ROIAlign(15, 0.9, 3), [in_data, in_boxes])\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d():\n    \"\"\"test_conv3d\"\"\"\n    for ishape in [(1, 32, 16, 16, 16), (1, 32, 9, 15, 15), (1, 32, 13, 7, 7)]:\n        inp = torch.rand(ishape)\n        verify_model(torch.nn.Conv3d(32, 16, (3, 3, 3), padding=(1, 1, 1)).eval(), inp)\n        verify_model(torch.nn.Conv3d(32, 16, (5, 5, 5), padding=(2, 2, 2)).eval(), inp)\n        verify_model(torch.nn.Conv3d(32, 16, kernel_size=1).eval(), inp)\n        # downsample\n        verify_model(torch.nn.Conv3d(32, 16, kernel_size=1, stride=2).eval(), inp)\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_transpose():\n    \"\"\"test_conv3d_transpose\"\"\"\n    for ishape in [(1, 8, 10, 5, 10), (1, 8, 5, 8, 8), (1, 8, 13, 7, 7)]:\n        inp = torch.rand(ishape)\n        verify_model(\n            torch.nn.ConvTranspose3d(\n                in_channels=8, out_channels=33, kernel_size=3, stride=2\n            ).eval(),\n            inp,\n        )\n        verify_model(\n            torch.nn.ConvTranspose3d(\n                in_channels=8,\n                out_channels=20,\n                kernel_size=(3, 5, 2),\n                stride=(2, 1, 1),\n                padding=(0, 4, 2),\n            ).eval(),\n            inp,\n        )\n        verify_model(\n            torch.nn.ConvTranspose3d(in_channels=8, out_channels=20, kernel_size=1).eval(), inp\n        )\n        verify_model(\n            torch.nn.ConvTranspose3d(in_channels=8, out_channels=5, kernel_size=1, stride=2).eval(),\n            inp,\n        )\n\n\n# Model tests\n@tvm.testing.uses_gpu\ndef test_resnet18():\n    \"\"\"test_resnet18\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"resnet18\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_squeezenet1_0():\n    \"\"\"test_squeezenet1_0\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"squeezenet1_0\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_squeezenet1_1():\n    \"\"\"test_squeezenet1_1\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"squeezenet1_1\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_densenet121():\n    \"\"\"test_densenet121\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"densenet121\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_inception_v3():\n    \"\"\"test_inception_v3\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"inception_v3\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_googlenet():\n    \"\"\"test_googlenet\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"googlenet\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_mnasnet0_5():\n    \"\"\"test_mnasnet0_5\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"mnasnet0_5\", atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_mobilenet_v2():\n    \"\"\"test_mobilenet_v2\"\"\"\n    torch.set_grad_enabled(False)\n    verify_model(\"mobilenet_v2\", atol=1e-4, rtol=1e-4)\n\n\n# pylint: disable=pointless-string-statement\n\"\"\"\n#TODO: Fix VGG and AlexNet issues (probably due to pooling)\n@tvm.testing.uses_gpu\ndef test_alexnet():\n    torch.set_grad_enabled(False)\n    verify_model(\"alexnet\")\n\n@tvm.testing.uses_gpu\ndef test_vgg11():\n    torch.set_grad_enabled(False)\n    verify_model(\"vgg11\")\n\n@tvm.testing.uses_gpu\ndef test_vgg11_bn():\n    torch.set_grad_enabled(False)\n    verify_model(\"vgg11_bn\")\n\"\"\"\n\n\n@tvm.testing.uses_gpu\ndef test_custom_conversion_map():\n    \"\"\"test_custom_conversion_map\"\"\"\n\n    def get_roi_align():\n        pool_size = 5\n        n_channels = 2 * (pool_size**2)\n        x = torch.rand(2, n_channels, 10, 10)\n        rois = torch.tensor(\n            [\n                [0, 0, 0, 9, 9],  # format is (xyxy)\n                [0, 0, 5, 4, 9],\n                [0, 5, 5, 9, 9],\n                [1, 0, 0, 9, 9],\n            ],\n            dtype=torch.float,\n        )\n        roi_align = torchvision.ops.RoIAlign(pool_size, spatial_scale=1, sampling_ratio=-1)\n        return roi_align.eval(), [x, rois]\n\n    def convert_roi_align():\n        def _impl(inputs, input_types):\n            spatial_scale = inputs[2]\n            pooled_size = (inputs[3], inputs[4])\n            sampling_ratio = inputs[5]\n            return relay.op.vision.roi_align(\n                inputs[0], inputs[1], pooled_size, spatial_scale, sampling_ratio\n            )\n\n        return _impl\n\n    custom_map = {\"torchvision::roi_align\": convert_roi_align()}\n    model, inputs = get_roi_align()\n\n    verify_model(model, inputs, custom_map)\n\n\n@tvm.testing.uses_gpu\ndef test_segmentation_models():\n    \"\"\"test_segmentation_models\"\"\"\n\n    class SegmentationModelWrapper(Module):\n        def __init__(self, model):\n            super().__init__()\n            self.model = model\n\n        def forward(self, inp):\n            out = self.model(inp)\n            return out[\"out\"]\n\n    fcn = torchvision.models.segmentation.fcn_resnet101(pretrained=True)\n    deeplab = torchvision.models.segmentation.deeplabv3_resnet101(pretrained=True)\n\n    inp = [torch.rand((1, 3, 300, 300), dtype=torch.float)]\n\n    verify_model(SegmentationModelWrapper(fcn.eval()), inp, atol=1e-4, rtol=1e-4)\n    verify_model(SegmentationModelWrapper(deeplab.eval()), inp, atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_3d_models():\n    \"\"\"test_3d_models\"\"\"\n    input_shape = (1, 3, 4, 56, 56)\n    resnet3d = torchvision.models.video.r3d_18(pretrained=True).eval()\n    verify_model(resnet3d, [torch.rand(input_shape)], atol=1e-4, rtol=1e-4)\n\n\ndef _get_default_vm_targets():\n    \"\"\"Get default vm targets\"\"\"\n    return [\"llvm\", \"cuda\"]\n\n\ndef verify_script_model(pt_model, ishapes, targets, idtype=None):\n    \"\"\"verify_script_model\"\"\"\n    script_module = torch.jit.script(pt_model)\n\n    verify_model_vm(script_module, ishapes, idtype=idtype, targets=targets)\n\n\ndef verify_trace_model(pt_model, idata, targets):\n    \"\"\"verify_trace_model\"\"\"\n    traced_model = torch.jit.trace(pt_model, idata)\n    ishapes = [data.shape for data in idata]\n    verify_model_vm(traced_model, ishapes, idata=idata, targets=targets)\n\n\ndef convert_pt_to_tvm_type(idtype):\n    \"\"\"Accepts a pytorch dtype and returns string TVM dtype.\"\"\"\n    # TVM does not support PyTorch complex dtypes\n    if idtype == torch.float64:\n        curr_dtype = \"float64\"\n    elif idtype == torch.float32:\n        curr_dtype = \"float32\"\n    elif idtype == torch.float16:\n        curr_dtype = \"float16\"\n    elif idtype == torch.bfloat16:\n        curr_dtype = \"bfloat16\"\n    elif idtype == torch.int64:\n        curr_dtype = \"int64\"\n    elif idtype == torch.int32:\n        curr_dtype = \"int32\"\n    elif idtype == torch.int16:\n        curr_dtype = \"int16\"\n    elif idtype == torch.int8:\n        curr_dtype = \"int8\"\n    elif idtype == torch.uint8:\n        curr_dtype = \"uint8\"\n    elif idtype == torch.bool:\n        curr_dtype = \"bool\"\n    else:\n        raise NotImplementedError(f\"Unsupported dtype: {idtype}\")\n    return curr_dtype\n\n\ndef verify_model_vm(input_model, ishapes, idtype=None, idata=None, targets=None):\n    \"\"\"verify_model_vm\"\"\"\n    targets = targets or [\"llvm\"]\n    if not idtype:\n        idtype = torch.float\n\n    input_names = [f\"i{idx}\" for idx, _ in enumerate(ishapes)]\n    tvm_dtype = convert_pt_to_tvm_type(idtype)\n    input_dtypes = [tvm_dtype] * len(input_names)\n    input_shapes = list(zip(input_names, list(zip(ishapes, input_dtypes))))\n\n    if idata:\n        input_data = idata\n    # If no input_data provided, generate random data of specified dtype\n    else:\n        if idtype == torch.bool:\n            input_data = [\n                torch.Tensor.bool(torch.randint(low=0, high=2, size=shape)) for shape in ishapes\n            ]\n        # Torch dtype can be float, complex, int, or Bool. Complex not supported,\n        # so if not float or Bool, dtype must be int!\n        elif not idtype.is_floating_point:\n            input_data = [\n                torch.randint(low=0, high=10, size=shape, dtype=idtype) for shape in ishapes\n            ]\n        else:\n            input_data = [torch.randn(shape, dtype=idtype) for shape in ishapes]\n\n    # Compile via VM\n    mod, params = relay.frontend.from_pytorch(input_model, input_shapes)\n\n    for tgt in targets:\n        if not tvm.testing.device_enabled(tgt):\n            continue\n        print(\"Running on target\", tgt)\n\n        dev = tvm.device(tgt, 0)\n\n        evaluator = relay.create_executor(\"vm\", mod=mod, device=dev, target=tgt).evaluate()\n\n        # Inference\n        for name, inp in zip(input_names, input_data):\n            params[name] = inp.numpy()\n        vm_res = evaluator(**params)\n\n        # Baseline result\n        with torch.no_grad():\n            pt_result = input_model(*input_data)\n\n        # Verify the accuracy\n        if isinstance(pt_result, tuple):\n            # handle multiple outputs\n            for i, pt_result in enumerate(pt_result):\n                tvm_res = vm_res[i].numpy()\n                tvm.testing.assert_allclose(tvm_res, pt_result.numpy(), rtol=1e-5, atol=1e-5)\n        elif not isinstance(pt_result, torch.Tensor):\n            tvm_res = vm_res.numpy().item()\n            assert pt_result == tvm_res\n        else:\n            tvm.testing.assert_allclose(vm_res.numpy(), pt_result.numpy(), rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_control_flow():\n    \"\"\"test_control_flow\"\"\"\n\n    class SimpleIf(torch.nn.Module):\n        \"\"\"SimpleIf module\"\"\"\n\n        def __init__(self, N, M):\n            super().__init__()\n            self.weight = torch.nn.Parameter(torch.rand(N, M))\n\n        def forward(self, inp):\n            if inp.sum() > 0.0:\n                output = self.weight + inp\n            else:\n                output = self.weight - inp\n            return output\n\n    class NestedIf(torch.nn.Module):\n        \"\"\"NestedIf module\"\"\"\n\n        def __init__(self, N, M):\n            super().__init__()\n            self.weight = torch.nn.Parameter(torch.rand(N, M))\n\n        def forward(self, inp):\n            \"\"\"forward\"\"\"\n            if inp.sum() > 0.0:\n                if inp.mean() > 0.0:\n                    output = self.weight + inp\n                else:\n                    output = self.weight - inp\n            else:\n                if inp.mean() >= 0.0:\n                    output = self.weight * inp\n                else:\n                    output = self.weight / inp\n\n            return output\n\n    class ScalarLoop(torch.nn.Module):\n        \"\"\"ScalarLoop module\"\"\"\n\n        def forward(self, inp):\n            \"\"\"forward\"\"\"\n            a = 0\n            for i in range(inp.size(0)):\n                b = i * i\n                b = b + 1\n                a += b\n            if a != 0:\n                a += 1\n            else:\n                a += 2\n            return a\n\n    class SimpleLoop(torch.nn.Module):\n        def forward(self, inp):\n            a = inp\n            for _ in range(inp.size(0)):\n                b = a * 2.0\n                c = a + b\n                a += c\n            return a\n\n    class LoopWithIf(torch.nn.Module):\n        \"\"\"LoopWithIf module\"\"\"\n\n        def forward(self, inp):\n            a = inp\n            for _ in range(inp.size(0)):\n                b = a * 2.0\n                b = a + b\n                if b.sum() > 0.0:\n                    a += b\n                else:\n                    a -= b\n            return a\n\n    class NestedLoop(torch.nn.Module):\n        def forward(self, inp):\n            a = inp\n            for i in range(inp.size(0)):\n                b = a * float(i)\n                for j in range(inp.size(1)):\n                    a += b * float(j)\n            return a\n\n    class SimpleScalarWhileLoop(torch.nn.Module):\n        \"\"\"SimpleScalarWhileLoop module\"\"\"\n\n        def forward(self, inp):\n            \"\"\"forward\"\"\"\n            a = 1\n            i = 0\n            while i <= inp.size(0):\n                a += i\n                i += 2\n            i = 0\n            # also test constant init cond\n            while i < 10:\n                a += i\n                i += 3\n            return a\n\n    class SimpleWhileLoop(torch.nn.Module):\n        def forward(self, inp):\n            a = inp\n            i = 0\n            while i < inp.size(0):\n                a += a * float(i) * 2.0\n                i += 1\n            return a\n\n    models = [\n        SimpleIf(10, 20),\n        NestedIf(10, 20),\n        ScalarLoop(),\n        SimpleLoop(),\n        LoopWithIf(),\n        SimpleScalarWhileLoop(),\n        SimpleWhileLoop(),\n        NestedLoop(),\n    ]\n\n    for pt_model in models:\n        verify_script_model(pt_model.eval(), [(10, 20)], _get_default_vm_targets())\n\n\n@tvm.testing.uses_gpu\ndef test_simple_rnn():\n    \"\"\"test_simple_rnn\"\"\"\n    # The mixed tracing and scripting example from\n    # https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html#mixing-scripting-and-tracing\n    class DecisionGate(torch.nn.Module):\n        def forward(self, x):\n            if x.sum() > 0:\n                return x\n            else:\n                return -x\n\n    class Cell(torch.nn.Module):\n        def __init__(self, dg):\n            super().__init__()\n            self.dg = dg\n            self.linear = torch.nn.Linear(4, 4)\n\n        def forward(self, x, h):\n            new_h = torch.tanh(self.dg(self.linear(x)) + h)\n            return new_h, new_h\n\n    class RNNLoop(torch.nn.Module):\n        \"\"\"Pytorch RNNLoop module\"\"\"\n\n        def __init__(self):\n            super().__init__()\n            x = torch.rand(10, 4, dtype=torch.float)\n            h = torch.rand(10, 4, dtype=torch.float)\n            self.cell = torch.jit.trace(Cell(DecisionGate()), (x, h))\n\n        def forward(self, xs):\n            h = torch.zeros(10, 4, dtype=torch.float)\n            y = torch.zeros(10, 4, dtype=torch.float)\n            for i in range(xs.size(0)):\n                y, h = self.cell(xs[i], h)\n            return y\n\n    verify_script_model(RNNLoop().eval(), [(10, 10, 4)], _get_default_vm_targets())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reduce_sum():\n    \"\"\"test_forward_reduce_sum\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class ReduceSum1(Module):\n        def forward(self, *args):\n            return args[0].sum(1)\n\n    class ReduceSum2(Module):\n        def forward(self, *args):\n            return args[0].sum(dim=1, keepdim=False)\n\n    class ReduceSum3(Module):\n        def forward(self, *args):\n            return args[0].sum(dim=2, keepdim=True)\n\n    class ReduceSum4(Module):\n        def forward(self, *args):\n            return args[0].sum(dim=(2, 3), keepdim=True)\n\n    class ReduceSum5(Module):\n        def forward(self, *args):\n            return args[0].sum(dim=(2, 3), keepdim=False)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(ReduceSum1().float().eval(), input_data=input_data)\n    verify_model(ReduceSum2().float().eval(), input_data=input_data)\n    verify_model(ReduceSum3().float().eval(), input_data=input_data)\n    verify_model(ReduceSum4().float().eval(), input_data=input_data)\n    verify_model(ReduceSum5().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_reduce_prod():\n    \"\"\"test_forward_reduce_prod\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class ReduceProd1(Module):\n        def forward(self, *args):\n            return args[0].prod(1)\n\n    class ReduceProd2(Module):\n        def forward(self, *args):\n            return args[0].prod(dim=1, keepdim=False)\n\n    class ReduceProd3(Module):\n        def forward(self, *args):\n            return args[0].prod(dim=2, keepdim=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(ReduceProd1().float().eval(), input_data=input_data)\n    verify_model(ReduceProd2().float().eval(), input_data=input_data)\n    verify_model(ReduceProd3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argmin():\n    \"\"\"test_forward_argmin\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class ArgMin1(Module):\n        def forward(self, *args):\n            return args[0].argmin(1)\n\n    class ArgMin2(Module):\n        def forward(self, *args):\n            return args[0].argmin(dim=1, keepdim=False)\n\n    class ArgMin3(Module):\n        def forward(self, *args):\n            return args[0].argmin(dim=2, keepdim=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(ArgMin1().float().eval(), input_data=input_data)\n    verify_model(ArgMin2().float().eval(), input_data=input_data)\n    verify_model(ArgMin3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_argmax():\n    \"\"\"test_forward_argmax\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class ArgMax1(Module):\n        def forward(self, *args):\n            return args[0].argmax(1)\n\n    class ArgMax2(Module):\n        def forward(self, *args):\n            return args[0].argmax(dim=1, keepdim=False)\n\n    class ArgMax3(Module):\n        def forward(self, *args):\n            return args[0].argmax(dim=2, keepdim=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(ArgMax1().float().eval(), input_data=input_data)\n    verify_model(ArgMax2().float().eval(), input_data=input_data)\n    verify_model(ArgMax3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_std():\n    \"\"\"test_forward_std\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Std1(Module):\n        def forward(self, *args):\n            return args[0].std(1, unbiased=False)\n\n    class Std2(Module):\n        def forward(self, *args):\n            return args[0].std(dim=1, keepdim=False, unbiased=False)\n\n    class Std3(Module):\n        def forward(self, *args):\n            return args[0].std(dim=2, keepdim=True, unbiased=False)\n\n    class Std4(Module):\n        def forward(self, *args):\n            return args[0].std(dim=(2, 3), keepdim=True, unbiased=False)\n\n    class Std5(Module):\n        def forward(self, *args):\n            return args[0].std(dim=(2, 3), keepdim=False, unbiased=False)\n\n    class Std6(Module):\n        def forward(self, *args):\n            return args[0].std(unbiased=False)\n\n    class Std7(Module):\n        def forward(self, *args):\n            return args[0].std(dim=1, keepdim=False, unbiased=True)\n\n    class Std8(Module):\n        def forward(self, *args):\n            return args[0].std(dim=(2, 3), keepdim=True, unbiased=True)\n\n    class Std9(Module):\n        def forward(self, *args):\n            return args[0].std(unbiased=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Std1().float().eval(), input_data=input_data)\n    verify_model(Std2().float().eval(), input_data=input_data)\n    verify_model(Std3().float().eval(), input_data=input_data)\n    verify_model(Std4().float().eval(), input_data=input_data)\n    verify_model(Std5().float().eval(), input_data=input_data)\n    verify_model(Std6().float().eval(), input_data=input_data)\n    verify_model(Std7().float().eval(), input_data=input_data)\n    verify_model(Std8().float().eval(), input_data=input_data)\n    verify_model(Std9().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_var_mean():\n    \"\"\"test_forward_var_mean\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class VarMean1(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], 1, unbiased=False)\n\n    class VarMean2(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=1, keepdim=False, unbiased=False)\n\n    class VarMean3(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=2, keepdim=True, unbiased=False)\n\n    class VarMean4(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=(2, 3), keepdim=True, unbiased=False)\n\n    class VarMean5(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=(2, 3), keepdim=False, unbiased=False)\n\n    class VarMean6(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], unbiased=False)\n\n    class VarMean7(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=1, keepdim=False, unbiased=True)\n\n    class VarMean8(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], dim=(2, 3), keepdim=True, unbiased=True)\n\n    class VarMean9(Module):\n        def forward(self, *args):\n            return torch.var_mean(args[0], unbiased=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(VarMean1().float().eval(), input_data=input_data)\n    verify_model(VarMean2().float().eval(), input_data=input_data)\n    verify_model(VarMean3().float().eval(), input_data=input_data)\n    verify_model(VarMean4().float().eval(), input_data=input_data)\n    verify_model(VarMean5().float().eval(), input_data=input_data)\n    verify_model(VarMean6().float().eval(), input_data=input_data)\n    verify_model(VarMean7().float().eval(), input_data=input_data)\n    verify_model(VarMean8().float().eval(), input_data=input_data)\n    verify_model(VarMean9().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_variance():\n    \"\"\"test_forward_variance\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Variance1(Module):\n        def forward(self, *args):\n            return args[0].var(1, unbiased=False)\n\n    class Variance2(Module):\n        def forward(self, *args):\n            return args[0].var(dim=1, keepdim=False, unbiased=False)\n\n    class Variance3(Module):\n        def forward(self, *args):\n            return args[0].var(dim=2, keepdim=True, unbiased=False)\n\n    class Variance4(Module):\n        def forward(self, *args):\n            return args[0].var(dim=(2, 3), keepdim=True, unbiased=False)\n\n    class Variance5(Module):\n        def forward(self, *args):\n            return args[0].var(dim=(2, 3), keepdim=False, unbiased=False)\n\n    class Variance6(Module):\n        def forward(self, *args):\n            return args[0].var(unbiased=False)\n\n    class Variance7(Module):\n        def forward(self, *args):\n            return args[0].var(dim=1, keepdim=False, unbiased=True)\n\n    class Variance8(Module):\n        def forward(self, *args):\n            return args[0].var(dim=(2, 3), keepdim=True, unbiased=True)\n\n    class Variance9(Module):\n        def forward(self, *args):\n            return args[0].var(unbiased=True)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Variance1().float().eval(), input_data=input_data)\n    verify_model(Variance2().float().eval(), input_data=input_data)\n    verify_model(Variance3().float().eval(), input_data=input_data)\n    verify_model(Variance4().float().eval(), input_data=input_data)\n    verify_model(Variance5().float().eval(), input_data=input_data)\n    verify_model(Variance6().float().eval(), input_data=input_data)\n    verify_model(Variance7().float().eval(), input_data=input_data)\n    verify_model(Variance8().float().eval(), input_data=input_data)\n    verify_model(Variance9().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_rsub():\n    \"\"\"test_forward_rsub\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Rsub1(Module):\n        def forward(self, *args):\n            return torch.rsub(args[0], args[1])\n\n    class Rsub2(Module):\n        def forward(self, *args):\n            return torch.rsub(args[0], args[1], alpha=0.5)\n\n    d1 = torch.rand([1, 3]).float()\n    d2 = torch.rand([1, 3]).float()\n    d3 = torch.rand([1, 3]).int()\n    verify_model(Rsub1().float().eval(), input_data=[d1, d2])\n    verify_model(Rsub1().float().eval(), input_data=[d1, d3])\n    verify_model(Rsub2().float().eval(), input_data=[d1, d2])\n    verify_model(Rsub2().float().eval(), input_data=[d1, d3])\n\n    d1 = torch.rand([1, 3]).half()\n    d2 = torch.rand([1, 3]).half()\n    verify_model(Rsub1().half().eval(), input_data=[d1, d2])\n    verify_model(Rsub1().half().eval(), input_data=[d1, d3])\n    verify_model(Rsub2().half().eval(), input_data=[d1, d2])\n    verify_model(Rsub2().half().eval(), input_data=[d1, d3])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_embedding():\n    \"\"\"test_forward_embedding\"\"\"\n    torch.set_grad_enabled(False)\n\n    input_data = torch.randint(0, 10, [2, 4]).long()\n    verify_model(torch.nn.Embedding(10, 3).float().eval(), input_data=input_data)\n\n    input_data = torch.randint(0, 4, [2, 3, 4]).long()\n    verify_model(torch.nn.Embedding(4, 5, sparse=False).float().eval(), input_data=input_data)\n\n    input_data = torch.randint(0, 4, [2, 3, 4]).long()\n    verify_model(torch.nn.Embedding(4, 5, sparse=True).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_onehot():\n    \"\"\"test_forward_onehot\"\"\"\n    torch.set_grad_enabled(False)\n\n    class OneHot1(Module):\n        def forward(self, *args):\n            return torch.nn.functional.one_hot(args[0], num_classes=3)\n\n    class OneHot2(Module):\n        def forward(self, *args):\n            return torch.nn.functional.one_hot(args[0], num_classes=5)\n\n    input_data = torch.arange(0, 5) % 3\n    verify_model(OneHot1().float().eval(), input_data=input_data)\n\n    input_data = torch.arange(0, 5) % 4\n    verify_model(OneHot2().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_isfinite():\n    \"\"\"test_forward_isfinite\"\"\"\n    torch.set_grad_enabled(False)\n\n    class IsFinite1(Module):\n        def forward(self, *args):\n            return torch.isfinite(args[0])\n\n    input_data = torch.tensor([1, float(\"inf\"), 2, float(\"-inf\"), float(\"nan\")]).float()\n    verify_model(IsFinite1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_isnan():\n    \"\"\"test_forward_isnan\"\"\"\n    torch.set_grad_enabled(False)\n\n    class IsNan1(Module):\n        def forward(self, *args):\n            return torch.isnan(args[0])\n\n    input_data = torch.tensor([1, float(\"inf\"), 2, float(\"-inf\"), float(\"nan\")]).float()\n    verify_model(IsNan1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_isinf():\n    \"\"\"test_forward_isinf\"\"\"\n    torch.set_grad_enabled(False)\n\n    class IsInf1(Module):\n        def forward(self, *args):\n            return torch.isinf(args[0])\n\n    input_data = torch.tensor([1, float(\"inf\"), 2, float(\"-inf\"), float(\"nan\")]).float()\n    verify_model(IsInf1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_clamp():\n    \"\"\"test_forward_clamp\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class Clamp1(Module):\n        def forward(self, *args):\n            return torch.clamp(args[0], min=-0.5, max=0.5)\n\n    class Clamp2(Module):\n        def forward(self, *args):\n            return torch.clamp(args[0], min=-0.3)\n\n    class Clamp3(Module):\n        def forward(self, *args):\n            return torch.clamp(args[0], max=1.0)\n\n    class Clamp_MinExpr_MaxConstant(Module):\n        def forward(self, *args):\n            h, w = args[0].shape[2:]\n            amin = h / 100.0\n            return torch.clamp(args[0], min=amin, max=w)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Clamp1().float().eval(), input_data=input_data)\n    verify_model(Clamp2().float().eval(), input_data=input_data)\n    verify_model(Clamp3().float().eval(), input_data=input_data)\n    verify_model(Clamp_MinExpr_MaxConstant().float().eval(), input_data=input_data)\n\n    verify_model(lambda inp: torch.clamp_min(inp, 0.5), input_data)\n    inp_uint8 = torch.randint(low=0, high=256, size=(100, 100), dtype=torch.uint8)\n    verify_model(lambda inp: torch.clamp_max(inp, 125), inp_uint8)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_clamp_():\n    \"\"\"test_forward_clamp_\"\"\"\n    torch.set_grad_enabled(False)\n\n    class ClampInPlace(Module):\n        def __init__(self, i_min, i_max):\n            super().__init__()\n            self.min = i_min\n            self.max = i_max\n\n        def forward(self, *args):\n            return torch.clamp_(args[0], self.min, self.max)\n\n    for ishape, i_min, i_max in (([4, 8], 0.1, 0.9), ([7, 6], 0.2, 0.5)):\n        input_data = torch.rand(ishape).float()\n        verify_model(ClampInPlace(i_min, i_max).float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_ones():\n    \"\"\"test_forward_ones\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Ones1(Module):\n        def forward(self, *args):\n            return torch.ones(2, 3)\n\n    verify_model(Ones1().float().eval(), input_data=[])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_ones_like():\n    \"\"\"test_forward_ones_like\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class OnesLike1(Module):\n        def forward(self, *args):\n            return torch.ones_like(args[0])\n\n    class OnesLike2(Module):\n        def forward(self, *args):\n            return torch.ones_like(args[0], dtype=torch.int8)\n\n    class OnesLike3(Module):\n        def forward(self, *args):\n            return torch.ones_like(args[0], dtype=torch.float)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(OnesLike1().float().eval(), input_data=input_data)\n    verify_model(OnesLike2().float().eval(), input_data=input_data)\n    verify_model(OnesLike3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_new_ones():\n    \"\"\"test_forward_new_ones\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    def test_func(input_tensor):\n        return input_tensor.new_ones([3, 10, 10])\n\n    verify_model_with_input(test_func, [torch.rand(input_shape).float()])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_zeros():\n    \"\"\"test_forward_zeros\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Zeros1(Module):\n        def forward(self, *args):\n            return torch.zeros(2, 3)\n\n    verify_model(Zeros1().float().eval(), input_data=[])\n\n\ndef test_forward_zero_():\n    def test_func(x):\n        return x.zero_()\n\n    verify_model_with_input(test_func, [torch.rand([1, 3, 10, 10]).float()])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_zeros_like():\n    \"\"\"test_forward_zeros_like\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class ZerosLike1(Module):\n        def forward(self, *args):\n            return torch.zeros_like(args[0])\n\n    class ZerosLike2(Module):\n        def forward(self, *args):\n            return torch.zeros_like(args[0], dtype=torch.int32)\n\n    class ZerosLike3(Module):\n        def forward(self, *args):\n            return torch.zeros_like(args[0], dtype=torch.float)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(ZerosLike1().float().eval(), input_data=input_data)\n    verify_model(ZerosLike2().float().eval(), input_data=input_data)\n    verify_model(ZerosLike3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_full():\n    \"\"\"test_forward_full\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Full1(Module):\n        def forward(self, *args):\n            return torch.full((2, 3), 3.14)\n\n    class Full2(Module):\n        def forward(self, *args):\n            return torch.full((1, 2, 3), 1.0, dtype=torch.int32)\n\n    verify_model(Full1().float().eval(), input_data=[])\n    verify_model(Full2().float().eval(), input_data=[])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_full_like():\n    \"\"\"test_forward_full_like\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    class FullLike1(Module):\n        def forward(self, *args):\n            return torch.full_like(args[0], 3.14)\n\n    class FullLike2(Module):\n        def forward(self, *args):\n            return torch.full_like(args[0], 22.22, dtype=torch.int32)\n\n    class FullLike3(Module):\n        def forward(self, *args):\n            return torch.full_like(args[0], 1.4, dtype=torch.float)\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(FullLike1().float().eval(), input_data=input_data)\n    verify_model(FullLike2().float().eval(), input_data=input_data)\n    verify_model(FullLike3().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_new_full():\n    \"\"\"test_forward_new_full\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    def test_func(input_tensor):\n        return input_tensor.new_full([2, 3], 1)\n\n    verify_model_with_input(test_func, [torch.rand(input_shape).float()])\n\n\ndef test_forward_fill_():\n    def test_func(x):\n        return x.fill_(3)\n\n    verify_model_with_input(test_func, [torch.rand([1, 3, 10, 10]).float()])\n\n\ndef test_forward_fill_with_div():\n    \"\"\"test_forward_fill_with_div\"\"\"\n\n    def test_func(x):\n        y = torch.div(torch.tensor(6.0), torch.tensor(2.0))\n        return x.fill_(y)\n\n    verify_model_with_input(test_func, [torch.rand([1, 3, 10, 10]).float()])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_linspace():\n    \"\"\"test_forward_linspace\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Linspace1(Module):\n        def forward(self, *args):\n            return torch.linspace(5, 10, steps=100)\n\n    class Linspace2(Module):\n        def forward(self, *args):\n            return torch.linspace(-10, 10, steps=5)\n\n    class Linspace3(Module):\n        def forward(self, *args):\n            return torch.linspace(start=-10, end=10, steps=5)\n\n    class Linspace4(Module):\n        def forward(self, *args):\n            return torch.linspace(start=-10, end=10, steps=1)\n\n    class Linspace5(Module):\n        def forward(self, *args):\n            return torch.linspace(1, 2, 1, dtype=torch.int32)\n\n    class Linspace6(Module):\n        def forward(self, *args):\n            return torch.linspace(start=1, end=6, steps=2)\n\n    class Linspace7(Module):\n        def forward(self, *args):\n            return torch.linspace(1, 4, steps=100, dtype=torch.float32)\n\n    class Linspace8(Module):\n        def forward(self, *args):\n            return torch.linspace(1, 2, 1, dtype=torch.int16)\n\n    verify_model(Linspace1().float().eval())\n    verify_model(Linspace2().float().eval())\n    verify_model(Linspace3().float().eval())\n    verify_model(Linspace4().float().eval())\n    verify_model(Linspace5().float().eval())\n    verify_model(Linspace6().float().eval())\n    verify_model(Linspace7().float().eval())\n    verify_model(Linspace8().float().eval())\n\n\n@tvm.testing.uses_gpu\ndef test_forward_take():\n    \"\"\"test_forward_take\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Take1(Module):\n        def forward(self, *args):\n            indices = torch.tensor([[0, 0], [1, 0]])\n            if torch.cuda.is_available():\n                indices = indices.cuda()\n            return torch.take(args[0], indices)\n\n    class Take2(Module):\n        def forward(self, *args):\n            return torch.take(args[0], args[1])\n\n    input_data = torch.tensor([[1, 2], [3, 4]])\n    verify_model(Take1().float().eval(), input_data=input_data)\n    indices = torch.tensor([[0, 0], [1, 0]])\n    verify_model(Take2().float().eval(), input_data=[input_data, indices])\n    indices = torch.tensor([0, -1])\n    verify_model(Take2().float().eval(), input_data=[input_data, indices])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_topk():\n    \"\"\"test_forward_topk\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Topk1(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3)\n\n    class Topk2(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3, dim=-2)\n\n    class Topk3(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3, dim=3)\n\n    class Topk4(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3, largest=True)\n\n    class Topk5(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3, largest=False)\n\n    class Topk6(Module):\n        def forward(self, *args):\n            return torch.topk(args[0], k=3, sorted=True)\n\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(Topk1().float().eval(), input_data=input_data)\n    verify_model(Topk2().float().eval(), input_data=input_data)\n    verify_model(Topk3().float().eval(), input_data=input_data)\n    verify_model(Topk4().float().eval(), input_data=input_data)\n    verify_model(Topk5().float().eval(), input_data=input_data)\n    verify_model(Topk6().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logical_not():\n    \"\"\"test_forward_logical_not\"\"\"\n    torch.set_grad_enabled(False)\n\n    class LogicalNot1(Module):\n        def forward(self, *args):\n            return torch.logical_not(args[0])\n\n    input_data = torch.tensor([True, False])\n    verify_model(LogicalNot1().float().eval(), input_data=input_data)\n\n    input_data = torch.tensor([0, 1, -10], dtype=torch.int8)\n    verify_model(LogicalNot1().float().eval(), input_data=input_data)\n\n    input_data = torch.tensor([0.0, 1.5, -10.0], dtype=torch.double)\n    verify_model(LogicalNot1().float().eval(), input_data=input_data)\n\n    input_data = torch.tensor([0.0, 1.0, -10.0], dtype=torch.int32)\n    verify_model(LogicalNot1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_bitwise_not():\n    \"\"\"test_forward_bitwise_not\"\"\"\n    torch.set_grad_enabled(False)\n\n    class BitwiseNot1(Module):\n        def forward(self, *args):\n            return torch.bitwise_not(args[0])\n\n    input_data = torch.tensor([0, 1, -10], dtype=torch.int8)\n    verify_model(BitwiseNot1().float().eval(), input_data=input_data)\n\n    input_data = torch.tensor([0.0, 1.0, -10.0], dtype=torch.int32)\n    verify_model(BitwiseNot1().float().eval(), input_data=input_data)\n\n    input_data = torch.tensor([True, False])\n    verify_model(BitwiseNot1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_bitwise_xor():\n    \"\"\"test_forward_bitwise_xor\"\"\"\n    torch.set_grad_enabled(False)\n\n    class BitwiseXor1(Module):\n        def forward(self, *args):\n            return torch.bitwise_xor(args[0], args[1])\n\n    class BitwiseXor2(Module):\n        def forward(self, *args):\n            rhs = torch.tensor([1, 0, 3], dtype=torch.int8)\n            if torch.cuda.is_available():\n                rhs = rhs.cuda()\n            return torch.bitwise_xor(args[0], rhs)\n\n    lhs = torch.tensor([-1, -2, 3], dtype=torch.int8)\n    rhs = torch.tensor([1, 0, 3], dtype=torch.int8)\n    verify_model(BitwiseXor1().float().eval(), input_data=[lhs, rhs])\n\n    lhs = torch.tensor([True, True, False])\n    rhs = torch.tensor([False, True, False])\n    verify_model(BitwiseXor1().float().eval(), input_data=[lhs, rhs])\n\n    lhs = torch.tensor([-1, -2, 3], dtype=torch.int8)\n    verify_model(BitwiseXor2().float().eval(), input_data=[lhs])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_logical_xor():\n    \"\"\"test_forward_logical_xor\"\"\"\n    torch.set_grad_enabled(False)\n\n    class LogicalXor1(Module):\n        def forward(self, *args):\n            return torch.logical_xor(args[0], args[1])\n\n    class LogicalXor2(Module):\n        def forward(self, *args):\n            rhs = torch.tensor([1, 0, 3], dtype=torch.int8)\n            if torch.cuda.is_available():\n                rhs = rhs.cuda()\n            return torch.logical_xor(args[0], rhs)\n\n    lhs = torch.tensor([-1, -2, 3], dtype=torch.int8)\n    rhs = torch.tensor([1, 0, 3], dtype=torch.int8)\n    verify_model(LogicalXor1().float().eval(), input_data=[lhs, rhs])\n\n    lhs = torch.tensor([True, True, False])\n    rhs = torch.tensor([False, True, False])\n    verify_model(LogicalXor1().float().eval(), input_data=[lhs, rhs])\n\n    lhs = torch.tensor([-1, -2, 3], dtype=torch.int8)\n    verify_model(LogicalXor2().float().eval(), input_data=[lhs])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_unary():\n    \"\"\"test_forward_unary\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Sqrt1(Module):\n        def forward(self, *args):\n            return torch.sqrt(args[0])\n\n    class RSqrt1(Module):\n        def forward(self, *args):\n            return torch.rsqrt(args[0])\n\n    class Ceil1(Module):\n        def forward(self, *args):\n            return torch.ceil(args[0])\n\n    class Floor1(Module):\n        def forward(self, *args):\n            return torch.floor(args[0])\n\n    class Round1(Module):\n        def forward(self, *args):\n            return torch.round(args[0])\n\n    class Cos1(Module):\n        def forward(self, *args):\n            return torch.cos(args[0])\n\n    class Sin1(Module):\n        def forward(self, *args):\n            return torch.sin(args[0])\n\n    class Tan1(Module):\n        def forward(self, *args):\n            return torch.tan(args[0])\n\n    class Tanh1(Module):\n        def forward(self, *args):\n            return torch.tanh(args[0])\n\n    class Acos1(Module):\n        def forward(self, *args):\n            return torch.acos(args[0])\n\n    class Asin1(Module):\n        def forward(self, *args):\n            return torch.asin(args[0])\n\n    class Atan1(Module):\n        def forward(self, *args):\n            return torch.atan(args[0])\n\n    class Log1(Module):\n        def forward(self, *args):\n            return torch.log(args[0])\n\n    class Exp1(Module):\n        def forward(self, *args):\n            return torch.exp(args[0])\n\n    class Erf1(Module):\n        def forward(self, *args):\n            return torch.erf(args[0])\n\n    class Trunc1(Module):\n        def forward(self, *args):\n            return torch.trunc(args[0])\n\n    class Sign1(Module):\n        def forward(self, *args):\n            return torch.sign(args[0])\n\n    class Neg1(Module):\n        def forward(self, *args):\n            return torch.neg(args[0])\n\n    class Sinh1(Module):\n        def forward(self, *args):\n            return torch.sinh(args[0])\n\n    class Cosh1(Module):\n        def forward(self, *args):\n            return torch.cosh(args[0])\n\n    class Log2_1(Module):\n        def forward(self, *args):\n            return torch.log2(args[0])\n\n    class Log10_1(Module):\n        def forward(self, *args):\n            return torch.log10(args[0])\n\n    class Log1p_1(Module):\n        def forward(self, *args):\n            return torch.log1p(args[0])\n\n    class Square(Module):\n        def forward(self, *args):\n            return torch.square(args[0])\n\n    input_shape = [1, 3, 10, 10]\n    input_data = torch.rand(input_shape).float()\n    verify_model(Square().float().eval(), input_data=input_data)\n    verify_model(Sqrt1().float().eval(), input_data=input_data)\n    verify_model(RSqrt1().float().eval(), input_data=input_data)\n    verify_model(Ceil1().float().eval(), input_data=input_data)\n    verify_model(Floor1().float().eval(), input_data=input_data)\n    verify_model(Round1().float().eval(), input_data=input_data)\n    verify_model(Cos1().float().eval(), input_data=input_data)\n    verify_model(Cosh1().float().eval(), input_data=input_data)\n    verify_model(Sin1().float().eval(), input_data=input_data)\n    verify_model(Sinh1().float().eval(), input_data=input_data)\n    verify_model(Tan1().float().eval(), input_data=input_data)\n    verify_model(Tanh1().float().eval(), input_data=input_data)\n    verify_model(Acos1().float().eval(), input_data=input_data)\n    verify_model(Asin1().float().eval(), input_data=input_data)\n    verify_model(Atan1().float().eval(), input_data=input_data)\n    verify_model(Log1().float().eval(), input_data=input_data)\n    verify_model(Log2_1().float().eval(), input_data=input_data)\n    verify_model(Log10_1().float().eval(), input_data=input_data)\n    verify_model(Log1p_1().float().eval(), input_data=input_data)\n    verify_model(Exp1().float().eval(), input_data=input_data)\n    verify_model(Erf1().float().eval(), input_data=input_data)\n    verify_model(Trunc1().float().eval(), input_data=input_data)\n    verify_model(Sign1().float().eval(), input_data=input_data)\n    verify_model(Neg1().float().eval(), input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_tril():\n    \"\"\"test_forward_tril\"\"\"\n    torch.set_grad_enabled(False)\n\n    def test_func(input_data):\n        return torch.tril(input_data)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func, input_data=input_data)\n\n    def test_func1(input_data):\n        return torch.tril(input_data, 1)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func1, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func1, input_data=input_data)\n\n    def test_func2(input_data):\n        return torch.tril(input_data, -1)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func2, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func2, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_triu():\n    \"\"\"test_forward_triu\"\"\"\n    torch.set_grad_enabled(False)\n\n    def test_func(input_data):\n        return torch.triu(input_data)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func, input_data=input_data)\n\n    def test_func1(input_data):\n        return torch.triu(input_data, 1)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func1, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func1, input_data=input_data)\n\n    def test_func2(input_data):\n        return torch.triu(input_data, -1)\n\n    input_data = torch.rand([3, 3]).float()\n    verify_model(test_func2, input_data=input_data)\n    input_data = torch.rand([1, 3, 10, 10]).float()\n    verify_model(test_func2, input_data=input_data)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_where():\n    \"\"\"test_forward_where\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Where1(Module):\n        def forward(self, *args):\n            y = torch.ones([3, 2])\n            if torch.cuda.is_available():\n                y = y.cuda()\n            return torch.where(args[0] > 0, args[0], y)\n\n    class Where2(Module):\n        def forward(self, *args):\n            return torch.where(args[0] > 0, args[0], args[1])\n\n    class Where3(Module):\n        def forward(self, *args):\n            return torch.where(args[0])[0]\n\n    x = torch.rand([3, 2]).float()\n    verify_model(Where1(), input_data=[x])\n    y = torch.rand([3, 2])\n    verify_model(Where2(), input_data=[x, y])\n\n    # a single argument variant, equivalent to torch.nonzero(..., as_tuple=True)\n    inp = torch.rand([10])\n    inp[3:8] = 0\n    verify_trace_model(Where3(), [inp], [\"llvm\"])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_addcdiv():\n    \"\"\"test_forward_addcdiv\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Addcdiv1(Module):\n        def forward(self, *args):\n            t1 = torch.ones([3, 1])\n            t2 = torch.ones([1, 3])\n            if torch.cuda.is_available():\n                t1 = t1.cuda()\n                t2 = t2.cuda()\n            return torch.addcdiv(args[0], 0.1, t1, t2)\n\n    class Addcdiv2(Module):\n        def forward(self, *args):\n            return torch.addcdiv(args[0], 0.5, args[1], args[2])\n\n    input_data = torch.rand([1, 3]).float()\n    verify_model(Addcdiv1().float().eval(), input_data=input_data)\n    t1 = torch.rand([3, 1]).float()\n    t2 = torch.rand([1, 3]).float()\n    verify_model(Addcdiv2().float().eval(), input_data=[input_data, t1, t2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_addcmul():\n    \"\"\"test_forward_addcmul\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Addcmul1(Module):\n        def forward(self, *args):\n            t1 = torch.ones([3, 1])\n            t2 = torch.ones([1, 3])\n            if torch.cuda.is_available():\n                t1 = t1.cuda()\n                t2 = t2.cuda()\n            return torch.addcmul(args[0], 0.1, t1, t2)\n\n    class Addcmul2(Module):\n        def forward(self, *args):\n            return torch.addcmul(args[0], 0.5, args[1], args[2])\n\n    input_data = torch.rand([1, 3]).float()\n    verify_model(Addcmul1().float().eval(), input_data=input_data)\n    t1 = torch.rand([3, 1]).float()\n    t2 = torch.rand([1, 3]).float()\n    verify_model(Addcmul2().float().eval(), input_data=[input_data, t1, t2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_true_divide():\n    \"\"\"test_forward_true_divide\"\"\"\n    if package_version.parse(torch.__version__) < package_version.parse(\"1.5.0\"):\n        return\n    torch.set_grad_enabled(False)\n\n    class TrueDivide(Module):\n        def forward(self, *args):\n            return torch.true_divide(args[0], args[1])\n\n    dividend = torch.rand([5, 3]).float()\n    # divisor could be either tensor or scalar\n    divisor_tensor = torch.rand([5, 3]).float() + 0.5\n    divisor_scalar = torch.tensor(1.0, dtype=torch.float32)\n    verify_model(\n        TrueDivide().float().eval(), input_data=[dividend, divisor_tensor], atol=1e-4, rtol=1e-4\n    )\n    verify_model(\n        TrueDivide().float().eval(), input_data=[dividend, divisor_scalar], atol=1e-4, rtol=1e-4\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_is_floating_point():\n    \"\"\"test_forward_is_floating_point\"\"\"\n    torch.set_grad_enabled(False)\n\n    class IsFloatingPoint(Module):\n        def forward(self, arg):\n            # `torch.jit.trace` cannot accept something that outputs\n            # a Bool, so `torch.jit.script` will be used instead\n            return torch.is_floating_point(arg)\n\n    targets = _get_default_vm_targets()\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.float64)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.float32)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.float16)\n    # todo(dvisnty): Run the test for bfloat16 when full bfloat16 support is implemented\n    # verify_script_model(IsFloatingPoint(), [(1,1)], targets, idtype=torch.bfloat16)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.int64)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.int32)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.int16)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.int8)\n    verify_script_model(IsFloatingPoint(), [(1, 1)], targets, idtype=torch.uint8)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_traced_function():\n    \"\"\"test_forward_traced_function\"\"\"\n\n    def fn(t1, t2):\n        return t1 + t2\n\n    tensor1 = torch.randn(3, 4)\n    tensor2 = torch.randn(3, 4)\n    verify_model(fn, input_data=[tensor1, tensor2])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_dtypes():\n    \"\"\"test_forward_dtypes\"\"\"\n\n    def fn(t1, t2):\n        return 2.5 * t1 + t2\n\n    for dt in [torch.int32, torch.int64, torch.double]:\n        tensor1 = torch.randn(3, 4).to(dtype=dt)\n        tensor2 = torch.randn(3, 4).to(dtype=dt)\n        verify_model(fn, input_data=[tensor1, tensor2])\n\n    class ModuleWithIntParameters(Module):\n        def __init__(self, arr):\n            super().__init__()\n            self.param = torch.nn.Parameter(torch.LongTensor(arr), requires_grad=False)\n\n        def forward(self, x):\n            return x.long() + self.param\n\n    shape = (10, 10)\n    param = torch.ones(shape, dtype=torch.long)\n    inp = torch.ones(shape, dtype=torch.int)\n    verify_model(ModuleWithIntParameters(param), input_data=inp)\n\n\n@tvm.testing.uses_gpu\ndef test_weight_names():\n    tm = torch.jit.trace(torch.nn.Linear(3, 4), [torch.randn(2, 3)])\n    _, params = relay.frontend.from_pytorch(tm, [(\"input\", (2, 3))])\n    assert set(params.keys()) == set(n for n, _ in tm.named_parameters())\n\n\n@tvm.testing.uses_gpu\ndef test_duplicate_weight_use():\n    \"\"\"test_duplicate_weight_use\"\"\"\n    # The test cases doesn't make any sense as a neural network,\n    # the issue popped up in shared input/output embeddings of bert,\n    # but this is quicker\n    class Test(Module):\n        def __init__(self):\n            super().__init__()\n            self.lin = torch.nn.Linear(5, 3)\n\n        def forward(self, x):\n            x = self.lin(x)\n            x = x @ self.lin.weight\n            return x\n\n    verify_model(Test(), input_data=[torch.randn(5, 5)])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_matmul():\n    \"\"\"test_forward_matmul\"\"\"\n    torch.set_grad_enabled(False)\n\n    class MatMul1(Module):\n        def forward(self, *args):\n            return torch.matmul(args[0], args[1])\n\n    # matrix x vector\n    tensor1 = torch.randn(3, 4)\n    tensor2 = torch.randn(4)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2])\n\n    # vector x matrix\n    tensor1 = torch.randn(4)\n    tensor2 = torch.randn(4, 3)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2])\n\n    # matrix x matrix\n    tensor1 = torch.randn(10, 4)\n    tensor2 = torch.randn(4, 10)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2], expected_ops=[\"nn.dense\"])\n\n    # batched matrix x batched matrix\n    tensor1 = torch.randn(10, 3, 4)\n    tensor2 = torch.randn(10, 4, 5)\n    verify_model(\n        MatMul1().float().eval(), input_data=[tensor1, tensor2], expected_ops=[\"nn.batch_matmul\"]\n    )\n\n    # batched matrix x broadcasted matrix\n    tensor1 = torch.randn(10, 3, 4)\n    tensor2 = torch.randn(4, 5)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2], expected_ops=[\"nn.dense\"])\n\n    # broadcasted matrix x batched matrix\n    tensor1 = torch.randn(10, 4)\n    tensor2 = torch.randn(3, 4, 5)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2], expected_ops=[\"nn.dense\"])\n\n    # batched matrix x batched matrix\n    tensor1 = torch.randn(1, 12, 14, 64)\n    tensor2 = torch.randn(1, 12, 64, 14)\n    verify_model(MatMul1().float().eval(), input_data=[tensor1, tensor2])\n\n\ndef test_forward_index():\n    \"\"\"test_forward_index\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [3, 4, 5, 6]\n\n    class Index0(Module):\n        def forward(self, x):\n            return x[[0, 1], [0, 2], :2, 4]\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Index0().eval(), input_data=input_data)\n\n    class Index1(Module):\n        def forward(self, x):\n            return x[[0], [1, 2, 3, 0], [3, 1, 2, 2], [4, 2, 1, 0]]\n\n    input_data = torch.rand(input_shape).float()\n    verify_model(Index1().eval(), input_data=input_data)\n\n    def test_fn_bool_mask():\n        return lambda data, mask: data[0, mask]\n\n    data = torch.tensor([[1, 2, 3], [4, 5, 6]])\n    mask = torch.tensor([True, True, False])\n\n    verify_trace_model(test_fn_bool_mask(), [data, mask], [\"llvm\", \"cuda\"])\n\n\ndef test_logsumexp():\n    \"\"\"test_logsumexp\"\"\"\n\n    class Logsumexp(Module):\n        def __init__(self, dim, keepdim=False):\n            super().__init__()\n            self.dim = dim\n            self.keepdim = keepdim\n\n        def forward(self, x):\n            return torch.logsumexp(x, self.dim, self.keepdim)\n\n    input_shape = (100, 100)\n    input_data = torch.rand(input_shape)\n\n    verify_model(Logsumexp(0), input_data=input_data)\n    verify_model(Logsumexp(0, keepdim=True), input_data=input_data)\n    # Also test on double\n    verify_model(Logsumexp(1, keepdim=True), input_data=input_data.double())\n\n\ndef test_stack():\n    \"\"\"test_stack\"\"\"\n\n    class Stack(torch.nn.Module):\n        def __init__(self, axis=0):\n            super().__init__()\n            self.axis = axis\n\n        def forward(self, x):\n            return torch.stack((x, x), dim=self.axis)\n\n    inp = torch.randn(8, 8, 8)\n    verify_model(Stack(), input_data=inp)\n    verify_model(Stack(axis=-1), input_data=inp)\n    verify_model(Stack(axis=3), input_data=inp)\n    verify_model(Stack(axis=-4), input_data=inp)\n\n\ndef test_stack_dynamic():\n    \"\"\"test_stack_dynamic\"\"\"\n\n    class Stack(torch.nn.Module):\n        def forward(self, x):\n            tensor_list = []\n            for i in range(x.size(0)):\n                # this is a workaround to avoid generating impure aten::append op\n                tensor_list += [x[i]]\n            # relay tensor array only supports stacking on the first axis\n            return torch.stack(tensor_list, dim=0)\n\n    verify_script_model(Stack(), [(8, 8, 8)], _get_default_vm_targets())\n\n\ndef test_forward_unbind():\n    \"\"\"test_forward_unbind\"\"\"\n\n    class Unbind(torch.nn.Module):\n        def __init__(self, axis=0):\n            super().__init__()\n            self.axis = axis\n\n        def forward(self, x):\n            return torch.unbind(x, self.axis)\n\n    inp = torch.randn(8, 8, 8)\n    verify_model(Unbind(0), input_data=inp)\n    verify_model(Unbind(1), input_data=inp)\n    verify_model(Unbind(2), input_data=inp)\n\n\ndef test_forward_nonzero():\n    \"\"\"test_forward_nonzero\"\"\"\n\n    class Nonzero(Module):\n        def __init__(self, as_tuple=False):\n            super().__init__()\n            self.as_tuple = as_tuple\n\n        def forward(self, data):\n            return torch.nonzero(data, as_tuple=self.as_tuple)\n\n    inp = torch.Tensor(np.array([[0, 1, 0], [2, 0, 9], [-1, -1, 0]]).astype(\"float32\"))\n    verify_trace_model(Nonzero(), [inp], [\"llvm\"])\n\n\ndef test_forward_scatter():\n    \"\"\"test_forward_scatter\"\"\"\n    # integer cannot be traced\n    def test_fn_scatter(dim):\n        return lambda data, index, src: torch.scatter(data, dim=dim, index=index, src=src)\n\n    def test_fn_scatter_add(dim):\n        return lambda data, index, src: torch.scatter_add(data, dim=dim, index=index, src=src)\n\n    in_data = torch.zeros(3, 5)\n    in_index = torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]])\n    in_src = torch.rand(2, 5)\n\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(test_fn_scatter(0), [in_data, in_index, in_src], targets)\n    verify_trace_model(test_fn_scatter_add(0), [in_data, in_index, in_src], targets)\n\n    in_data = torch.zeros(2, 4)\n    in_index = torch.tensor([[2], [3]])\n    in_src = torch.rand(2, 1)\n\n    verify_trace_model(test_fn_scatter(1), [in_data, in_index, in_src], targets)\n    verify_trace_model(test_fn_scatter_add(1), [in_data, in_index, in_src], targets)\n\n\ndef test_forward_index_put():\n    \"\"\"test_forward_index_put\"\"\"\n    # torch.index_put for 2D tensor and default accumulate (False)\n    def test_fn_index_put2():\n        return lambda data, xidx, yidx, values: torch.index_put(\n            data, indices=[xidx, yidx], values=values\n        )\n\n    # torch.index_put for 3D tensor and accumulate=True\n    def test_fn_index_put3a():\n        return lambda data, xidx, yidx, zidx, values: torch.index_put(\n            data, indices=[xidx, yidx, zidx], values=values, accumulate=True\n        )\n\n    shape = (3, 5)\n    in_data = torch.zeros(shape)\n    xidx = torch.tensor([0, 1, 2, 2])\n    yidx = torch.tensor([0, 1, 3, 4])\n    values = torch.tensor([2.0, 4.0, 7.0, 9.0])\n\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(test_fn_index_put2(), [in_data, xidx, yidx, values], targets)\n\n    shape = (3, 5, 3)\n    in_data = torch.zeros(shape)\n    xidx = torch.tensor([0, 1, 2, 2, 0])\n    yidx = torch.tensor([0, 1, 3, 4, 0])\n    zidx = torch.tensor([0, 1, 1, 2, 0])\n    values = torch.tensor([2.0, 4.0, 7.0, 9.0, 1.0])\n\n    verify_trace_model(test_fn_index_put3a(), [in_data, xidx, yidx, zidx, values], targets)\n\n\ndef test_numel():\n    \"\"\"test_numel\"\"\"\n\n    class Numel(Module):\n        def forward(self, data):\n            return torch.tensor(torch.numel(data))\n\n    targets = _get_default_vm_targets()\n    verify_script_model(Numel(), [(1,)], targets)\n    verify_script_model(Numel(), [(3, 5)], targets)\n    verify_script_model(Numel(), [(3, 5, 8)], targets)\n\n\ndef test_empty():\n    \"\"\"Test for aten::empty\"\"\"\n\n    def test_func():\n        return torch.empty([1, 3, 10, 10])\n\n    verify_model_with_input(test_func, [], assert_shape_only=True)\n\n\ndef test_empty_like():\n    \"\"\"Test for aten::empty_like\"\"\"\n\n    def test_func(data):\n        return torch.empty_like(data)\n\n    verify_model_with_input(test_func, [torch.rand([1, 3, 10, 10]).float()], assert_shape_only=True)\n\n\n@tvm.testing.uses_gpu\ndef test_new_empty():\n    \"\"\"test_forward_new_ones\"\"\"\n    torch.set_grad_enabled(False)\n    input_shape = [1, 3, 10, 10]\n\n    def test_func(input_tensor):\n        return input_tensor.new_empty([3, 10, 10])\n\n    verify_model_with_input(test_func, [torch.rand(input_shape).float()], assert_shape_only=True)\n\n    def test_func1(input_tensor):\n        return input_tensor.new_empty([3, 10, 10], dtype=torch.int32)\n\n    verify_model_with_input(test_func1, [torch.rand(input_shape).float()], assert_shape_only=True)\n\n\ndef test_randn():\n    \"\"\"Test for aten::randn\"\"\"\n\n    def test_func():\n        return torch.randn([1, 3, 10, 10])\n\n    verify_model_with_input(test_func, [], assert_shape_only=True)\n\n    def test_func1():\n        return torch.randn(1, 3, 10, 10)\n\n    verify_model_with_input(test_func1, [], assert_shape_only=True)\n\n\ndef test_forward_pretrained_bert_base_uncased():\n    ######################################################################\n    # This is an example how to run BERT models using TVM\n    # ---------------------------------------------------\n    \"\"\"\n    Refer the bert example given in https://pypi.org/project/pytorch-pretrained-bert\n\n    # To get started, pretrained bert package needs to be installed as prerequisite.\n\n    .. code-block:: bash\n\n        # install bert package\n        pip install pytorch_pretrained_bert==0.6.2 --user\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n    try:\n        from pytorch_pretrained_bert import BertForMaskedLM, BertTokenizer\n    except ImportError:\n        print(\"Torch pretrained bert package must be installed to run this script.\")\n        return\n\n    ######################################################################\n    # Load the tokenizer and tokenize the input\n    # -----------------------------------------\n\n    # Load pre-trained model tokenizer (vocabulary)\n    tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n\n    # Tokenized input\n    text = \"[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]\"\n    tokenized_text = tokenizer.tokenize(text)\n\n    # Mask a token that we will try to predict back with `BertForMaskedLM`\n    masked_index = 8\n    tokenized_text[masked_index] = \"[MASK]\"\n    assert tokenized_text == [\n        \"[CLS]\",\n        \"who\",\n        \"was\",\n        \"jim\",\n        \"henson\",\n        \"?\",\n        \"[SEP]\",\n        \"jim\",\n        \"[MASK]\",\n        \"was\",\n        \"a\",\n        \"puppet\",\n        \"##eer\",\n        \"[SEP]\",\n    ]\n\n    # Convert token to vocabulary indices\n    indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n    # Define sentence A and B indices associated to 1st and 2nd sentences (see paper)\n    segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]\n\n    # Convert inputs to PyTorch tensors\n    tokens_tensor = torch.tensor([indexed_tokens])\n    segments_tensors = torch.tensor([segments_ids])\n\n    ######################################################################\n    # Load a pretrained PyTorch model bert-base-uncased\n    # -------------------------------------------------\n\n    # Bert Model with a language modeling\n    model = BertForMaskedLM.from_pretrained(\"bert-base-uncased\")\n    model.eval()\n\n    ######################################################################\n    # Predict all tokens with pytorch\n    # -------------------------------\n\n    with torch.no_grad():\n        torch_preds = model(tokens_tensor, segments_tensors)\n\n    ######################################################################\n    # Make TorchScripted model via jit trace\n    # --------------------------------------\n\n    scripted_model = torch.jit.trace(model, (tokens_tensor, segments_tensors)).eval()\n\n    ######################################################################\n    # Import the graph to Relay\n    # -------------------------\n    # Convert PyTorch graph to Relay graph. The input name can be arbitrary.\n\n    input_1 = \"input_ids\"\n    input_2 = \"input.2\"\n    shape_list = [(input_1, list(tokens_tensor.shape)), (input_2, list(segments_tensors.shape))]\n\n    mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n\n    ######################################################################\n    # Compile the model with relay\n    # ----------------------------\n\n    target = \"llvm\"\n    with tvm.transform.PassContext(opt_level=3):\n        relay_graph, relay_lib, relay_params = relay.build(mod, target=target, params=params)\n\n    ######################################################################\n    # Execute on TVM\n    # --------------\n\n    dev = tvm.device(target, 0)\n    relay_model = graph_executor.create(relay_graph, relay_lib, dev)\n    relay_model.set_input(**relay_params)\n    relay_model.set_input(input_1, tokens_tensor)\n    relay_model.set_input(input_2, segments_tensors)\n    relay_model.run()\n    compiled_output = relay_model.get_output(0).numpy()\n\n    ######################################################################\n    # Validate the outputs\n    # --------------------\n    # Compare the torch and tvm outputs\n\n    tvm.testing.assert_allclose(torch_preds, compiled_output, rtol=1e-3, atol=1e-3)\n\n    ######################################################################\n    # Process the output\n    # ------------------\n    # Process the model output to token.\n\n    # Torch output to token\n    torch_pred_idx = torch.argmax(torch_preds[0, masked_index]).item()\n    torch_pred_token = tokenizer.convert_ids_to_tokens([torch_pred_idx])[0]\n\n    # TVM output to token\n    tvm_pred_idx = compiled_output[0, masked_index].argmax()\n    tvm_pred_token = tokenizer.convert_ids_to_tokens([tvm_pred_idx])[0]\n\n    assert torch_pred_idx == tvm_pred_idx\n    assert torch_pred_token == tvm_pred_token\n\n    # Print the outputs\n    print(f\"Torch top-1 id: {torch_pred_idx}, token: {torch_pred_idx}\")\n    print(f\"TVM   top-1 id: {tvm_pred_idx}, token: {tvm_pred_token}\")\n\n\n@pytest.mark.skipif(\n    platform.machine() == \"aarch64\",\n    reason=\"Currently failing on AArch64\",\n)\ndef test_convert_torch_script_with_input_types():\n    \"\"\"test_convert_torch_script_with_input_types\"\"\"\n\n    def model_fn(x, y):\n        x = x.to(dtype=torch.int32)\n        y = x + y\n        return y\n\n    ishape = (4, 5)\n    input_x = torch.rand(ishape, dtype=torch.float32)\n    input_y = torch.randint(low=0, high=100, size=ishape, dtype=torch.int32)\n    inputs = [input_x, input_y]\n    script_module = torch.jit.trace(model_fn, inputs)\n\n    fname = \"tmp.pt\"\n    torch.jit.save(script_module, fname)\n    loaded = torch.jit.load(fname)\n    os.remove(fname)\n\n    verify_model(loaded.eval(), input_data=inputs)\n\n    def expected(x_shape, y_shape):\n        # use a fixed order of args so alpha equal check can pass\n        x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n        y = relay.var(\"y\", shape=y_shape, dtype=\"int32\")\n        args = [x, y]\n        x1 = relay.cast(x, \"int32\")\n        y1 = relay.add(x1, y)\n        mod = tvm.IRModule.from_expr(relay.Function(args, y1))\n        return mod[\"main\"]\n\n    input_infos = [(\"input0\", (ishape, \"float\")), (\"input1\", (ishape, \"int\"))]\n    mod, _ = relay.frontend.from_pytorch(loaded, input_infos)\n\n    expected_mod = expected(ishape, ishape)\n\n    assert tvm.ir.structural_equal(expected_mod, mod[\"main\"], map_free_vars=True)\n\n\ndef test_bincount():\n    \"\"\"test_bincount\"\"\"\n\n    def test_fn(x, weights=None):\n        return torch.bincount(x, weights=weights)\n\n    inp = torch.randint(0, 100, (10000,), dtype=torch.int64)\n    weights = torch.linspace(0, 100, steps=10000)\n\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(test_fn, [inp], targets)\n    verify_trace_model(test_fn, [inp, weights], targets)\n\n\ndef test_hard_swish():\n    \"\"\"test_hard_swish\"\"\"\n    examples = [torch.rand(8).float(), torch.rand(8, 10).float(), torch.rand(1, 1, 10).float()]\n    for input_data in examples:\n        verify_model(torch.nn.Hardswish().eval(), input_data=input_data)\n        verify_model(torch.nn.Hardswish(inplace=True).eval(), input_data=input_data)\n\n\ndef test_hard_sigmoid():\n    \"\"\"test_hard_sigmoid\"\"\"\n    examples = [torch.rand(8).float(), torch.rand(8, 10).float(), torch.rand(1, 1, 10).float()]\n    for input_data in examples:\n        verify_model(torch.nn.Hardsigmoid().eval(), input_data=input_data)\n        verify_model(torch.nn.Hardsigmoid(inplace=True).eval(), input_data=input_data)\n\n\ndef test_cumsum():\n    \"\"\"test_cumsum\"\"\"\n\n    def test_fn(dim, dtype=None):\n        return lambda x: torch.cumsum(x, dim=dim, dtype=dtype)\n\n    inp = torch.randint(0, 100, (10000,), dtype=torch.int32)\n    verify_model(test_fn(0), [inp])\n    verify_model(test_fn(0), [inp.to(torch.int64)])\n    verify_model(test_fn(0, dtype=torch.int64), [inp.to(torch.int64)])\n\n    inp = torch.randn((100, 100), dtype=torch.float32)\n    verify_model(test_fn(dim=0, dtype=torch.float64), [inp])\n    verify_model(test_fn(dim=1), [inp])\n\n    inp = torch.randn((100, 100), dtype=torch.float32) > 0.5\n    verify_model(test_fn(dim=0, dtype=torch.int32), [inp])\n\n\ndef test_masked_fill():\n    \"\"\"test_transformer\"\"\"\n\n    def test_fn(x, mask):\n        return torch.masked_fill(x, mask, 0.0)\n\n    inp = torch.randn(100, 100)\n    verify_model(test_fn, [inp, inp > 0.5])\n    verify_model(test_fn, [inp.to(torch.float64), inp > 0.5])\n\n\ndef test_transformer():\n    \"\"\"test_transformer\"\"\"\n    model = torch.nn.Transformer(d_model=256, nhead=8, num_encoder_layers=6, num_decoder_layers=6)\n    model = model.eval()\n    src = torch.rand((10, 32, 256))\n    tgt = torch.rand((20, 32, 256))\n    verify_model(model.eval(), input_data=[src, tgt])\n\n\ndef test_argsort():\n    \"\"\"test_argsort\"\"\"\n\n    def test_fn(dim, descending):\n        return lambda x: torch.argsort(x, dim=dim, descending=descending)\n\n    inp = torch.randn(100)\n    verify_model(test_fn(0, True), [inp])\n    verify_model(test_fn(0, False), [inp])\n\n    inp = torch.randn(100, 100)\n    verify_model(test_fn(0, True), [inp])\n    verify_model(test_fn(0, False), [inp])\n    verify_model(test_fn(1, True), [inp])\n    verify_model(test_fn(1, False), [inp])\n\n\ndef test_sort():\n    \"\"\"test_sort\"\"\"\n\n    def test_fn(dim, descending):\n        return lambda x: torch.sort(x, dim=dim, descending=descending)\n\n    inp = torch.randn(100)\n    verify_model(test_fn(0, True), [inp])\n    verify_model(test_fn(-1, False), [inp])\n\n    inp = torch.randn(100, 100)\n    verify_model(test_fn(0, True), [inp])\n    verify_model(test_fn(-2, False), [inp])\n    verify_model(test_fn(1, True), [inp])\n    verify_model(test_fn(-1, False), [inp])\n\n\ndef test_logical_and():\n    \"\"\"test_logical_and\"\"\"\n\n    def test_fn(x, y):\n        return torch.logical_and(x, y)\n\n    a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)\n    b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)\n    verify_model(test_fn, [a, b])\n\n    a = torch.tensor([True, False, True])\n    b = torch.tensor([True, False, False])\n    verify_model(test_fn, [a, b])\n\n\ndef test_masked_select():\n    \"\"\"test_masked_select\"\"\"\n\n    def test_fn(x, mask):\n        return torch.masked_select(x, mask)\n\n    for shape in [(10,), (3, 4), (16, 32, 64)]:\n        x = torch.randn(*shape)\n        mask = x.ge(0.5)\n        verify_trace_model(test_fn, [x, mask], [\"llvm\", \"cuda\"])\n\n\ndef test_unique():\n    \"\"\"test_unique\"\"\"\n\n    def test_fn(is_sorted, return_inverse, return_counts):\n        return lambda x: torch.unique(x, is_sorted, return_inverse, return_counts)\n\n    in_data = torch.randint(0, 20, (10,), dtype=torch.int32)\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(test_fn(True, True, True), [in_data], targets)\n    verify_trace_model(test_fn(True, False, True), [in_data], targets)\n    verify_trace_model(test_fn(True, True, False), [in_data], targets)\n    verify_trace_model(test_fn(True, False, True), [in_data], targets)\n    in_data = torch.randint(0, 20, (20,), dtype=torch.int64)\n    verify_trace_model(test_fn(True, True, True), [in_data], targets)\n    verify_trace_model(test_fn(True, False, True), [in_data], targets)\n    verify_trace_model(test_fn(True, True, False), [in_data], targets)\n    verify_trace_model(test_fn(True, False, True), [in_data], targets)\n\n\ndef test_forward_nll_loss():\n    \"\"\"test_forward_nll_loss\"\"\"\n    torch.set_grad_enabled(False)\n    N, C = 10, 3\n    predictions = torch.rand((N, C)).float()\n    targets = torch.randint(0, 3, (N,))\n    weights = torch.tensor([1, 2, 3]).float()\n    verify_model(torch.nn.NLLLoss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(weight=weights).eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(ignore_index=1).eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n    # multidimension nll loss (aten::nll_loss2d)\n    d1, d2 = 2, 3\n    predictions = torch.rand((N, C, d1, d2)).float()\n    targets = torch.randint(0, 3, (N, d1, d2))\n    verify_model(torch.nn.NLLLoss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(weight=weights).eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(ignore_index=1).eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.NLLLoss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n\ndef test_cross_entropy_loss():\n    \"\"\"test_cross_entropy_loss\"\"\"\n    torch.set_grad_enabled(False)\n    N, C = 10, 3\n    # class indices\n    predictions = torch.rand((N, C)).float()\n    targets = torch.randint(0, 3, (N,))\n    weights = torch.tensor([1, 2, 3]).float()\n    verify_model(torch.nn.CrossEntropyLoss().eval(), input_data=[predictions, targets])\n    verify_model(\n        torch.nn.CrossEntropyLoss(weight=weights).eval(), input_data=[predictions, targets]\n    )\n\n    # class probabilities\n    predictions = torch.randn(N, C).float()\n    targets = torch.randn(N, C)\n    verify_model(torch.nn.CrossEntropyLoss().eval(), input_data=[predictions, targets])\n\n\ndef test_forward_l1_loss():\n    \"\"\"test_forward_l1_loss\"\"\"\n    torch.set_grad_enabled(False)\n    N, C = 10, 3\n    predictions = torch.rand((N, C)).float()\n    targets = torch.rand((N, C)).float()\n    verify_model(torch.nn.L1Loss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.L1Loss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.L1Loss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n    # multidimension l1 loss\n    d1, d2 = 2, 3\n    predictions = torch.rand((N, C, d1, d2)).float()\n    targets = torch.rand((N, C, d1, d2)).float()\n    verify_model(torch.nn.L1Loss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.L1Loss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.L1Loss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n\ndef test_forward_mse_loss():\n    \"\"\"test_forward_mse_loss\"\"\"\n    torch.set_grad_enabled(False)\n    N, C = 10, 3\n    predictions = torch.rand((N, C)).float()\n    targets = torch.rand((N, C)).float()\n    verify_model(torch.nn.MSELoss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.MSELoss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.MSELoss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n    # multidimension mse loss\n    d1, d2 = 2, 3\n    predictions = torch.rand((N, C, d1, d2)).float()\n    targets = torch.rand((N, C, d1, d2)).float()\n    verify_model(torch.nn.MSELoss().eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.MSELoss(reduction=\"sum\").eval(), input_data=[predictions, targets])\n    verify_model(torch.nn.MSELoss(reduction=\"none\").eval(), input_data=[predictions, targets])\n\n\n@tvm.testing.uses_gpu\ndef test_forward_flip():\n    \"\"\"Test for aten::flip\"\"\"\n    torch.set_grad_enabled(False)\n\n    class Flip(Module):\n        def __init__(self, axis=0):\n            super().__init__()\n            self.axis = axis\n\n        def forward(self, x):\n            return x.flip([self.axis])\n\n    input_t = torch.randn(2, 3, 4)\n    verify_model(Flip(axis=0), input_data=input_t)\n    verify_model(Flip(axis=1), input_data=input_t)\n    verify_model(Flip(axis=2), input_data=input_t)\n    verify_model(Flip(axis=-1), input_data=input_t)\n\n\ndef test_annotate_span():\n    \"\"\"test_annotate_span\"\"\"\n    model = torchvision.models.resnet18().eval()\n    inp = torch.randn([1, 3, 224, 224])\n    trace = torch.jit.trace(model, inp).eval()\n    mod, _ = relay.frontend.from_pytorch(\n        trace, [(\"input\", inp.shape)], use_parser_friendly_name=True\n    )\n    relay.transform.AnnotateSpans()(mod)\n\n\n@tvm.testing.uses_gpu\ndef test_all_any():\n    \"\"\"test_all_any\"\"\"\n\n    def test_fn(f, dim=None, keepdim=False):\n        return lambda x: f(x, dim=dim, keepdim=keepdim)\n\n    def test_fn_no_arg(f):\n        return lambda x: f(x)  # pylint: disable=unnecessary-lambda\n\n    for f in [torch.all, torch.any]:\n        verify_model(test_fn(f, 0), [torch.rand(1, 2).bool()])\n        verify_model(test_fn(f, 0), [torch.arange(0, 3).to(torch.uint8)])\n        verify_model(test_fn(f, 1), [torch.rand(4, 2).bool()])\n        verify_model(test_fn(f, 0, keepdim=True), [torch.rand(4, 2).bool()])\n        verify_model(test_fn_no_arg(f), [torch.rand(1, 2).bool()])\n        verify_model(test_fn_no_arg(f), [torch.arange(0, 3).to(torch.uint8)])\n\n\n@tvm.testing.uses_gpu\ndef test_searchsorted():\n    \"\"\"test_searchsorted\"\"\"\n\n    def test_fn(out_int32=False, right=False):\n        return lambda x, y: torch.searchsorted(x, y, out_int32=out_int32, right=right)\n\n    sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]])\n    values = torch.tensor([[3, 6, 9], [3, 6, 9]])\n    verify_model(test_fn(), [sorted_sequence, values])\n    verify_model(test_fn(out_int32=True), [sorted_sequence[0], values[0]])\n    verify_model(test_fn(right=True), [sorted_sequence, values])\n\n    sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9])\n    values = torch.tensor([[3, 6, 9], [4, 2, 7]])\n    verify_model(test_fn(), [sorted_sequence_1d, values])\n\n    verify_model(test_fn(), [sorted_sequence_1d, torch.tensor(6)])\n\n\n@tvm.testing.uses_gpu\ndef test_bucketize():\n    \"\"\"test_bucketize\"\"\"\n\n    def test_fn(out_int32=False, right=False):\n        return lambda x, y: torch.bucketize(x, y, out_int32=out_int32, right=right)\n\n    boundaries = torch.tensor([1, 3, 5, 7, 9])\n    values = torch.tensor([3, 6, 9])\n\n    verify_model(test_fn(), [values, boundaries])\n    verify_model(test_fn(out_int32=True, right=True), [values, boundaries])\n\n\n@tvm.testing.uses_gpu\ndef test_roll():\n    \"\"\"Test for aten::roll\"\"\"\n\n    def test_fn(shifts, dims):\n        return lambda x: torch.roll(x, shifts, dims)\n\n    x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2)\n    verify_model(test_fn(1, 0), [x])\n    verify_model(test_fn(-1, 0), [x])\n    verify_model(test_fn(shifts=(2, 1), dims=(0, 1)), [x])\n\n\n@tvm.testing.uses_gpu\ndef test_einsum():\n    \"\"\"test_einsum\"\"\"\n\n    def test_fn(equation):\n        return lambda *x: torch.einsum(equation, *x)\n\n    x = torch.ones([2, 3])\n    y = torch.ones([3, 4])\n    z = torch.ones([4, 5])\n    verify_model(test_fn(\"ij,jk\"), [x, y])\n    verify_model(test_fn(\"ij,jk,km->im\"), [x, y, z])\n\n\ndef test_stft():\n    \"\"\"test_stft\"\"\"\n\n    def test_fn(n_fft, hop_length, win_length, center, pad_mode, normalized, onesided):\n        return lambda input, window=None: torch.stft(\n            input=input,\n            n_fft=n_fft,\n            hop_length=hop_length,\n            win_length=win_length,\n            window=window,\n            center=center,\n            pad_mode=pad_mode,\n            normalized=normalized,\n            onesided=onesided,\n        )\n\n    input_t = torch.rand([1, 12]).float()\n    window = torch.tensor([2, 3, 4], dtype=torch.int32)\n    targets = [\"llvm\", \"cuda\"]\n    verify_trace_model(test_fn(3, 3, 3, False, \"constant\", False, True), [input_t, window], targets)\n    verify_trace_model(test_fn(3, 3, 3, True, \"constant\", False, True), [input_t, window], targets)\n    verify_trace_model(test_fn(3, 3, 3, False, \"reflect\", False, True), [input_t, window], targets)\n    verify_trace_model(test_fn(3, 3, 3, True, \"reflect\", False, True), [input_t, window], targets)\n    verify_trace_model(test_fn(3, 3, 3, True, \"reflect\", True, True), [input_t, window], targets)\n    verify_trace_model(test_fn(3, 3, 3, True, \"reflect\", False, False), [input_t, window], targets)\n    input_t = torch.rand([2, 12]).float()\n    window = torch.tensor([2, 3, 4], dtype=torch.int32)\n    verify_trace_model(test_fn(3, 3, 3, False, \"reflect\", False, True), [input_t, window], targets)\n    window = torch.tensor([1, 3], dtype=torch.int32)\n    verify_trace_model(test_fn(2, 1, 2, False, \"reflect\", False, True), [input_t, window], targets)\n    verify_trace_model(test_fn(2, 1, 2, False, \"reflect\", False, True), [input_t], targets)\n\n\n@tvm.testing.uses_gpu\ndef test_dot():\n    \"\"\"Test for aten::dot\"\"\"\n\n    def test_fn(x):\n        return x.dot(x)\n\n    x = torch.randn([4])\n    verify_model(test_fn, [x])\n\n\n@tvm.testing.uses_gpu\ndef test_mv():\n    \"\"\"Test for aten::mv\"\"\"\n\n    def test_fn(m, v):\n        return m.mv(v)\n\n    verify_model(test_fn, [torch.randn(4, 4), torch.randn(4)])\n    verify_model(test_fn, [torch.randn(2, 2), torch.randn(2)])\n    verify_model(test_fn, [torch.randn(3, 8), torch.randn(8)])\n\n\ndef test_grid_sample():\n    \"\"\"test_grid_sample\"\"\"\n\n    class Grid_sample(Module):\n        def __init__(self, method, padding_mode, align_corners):\n            super().__init__()\n            self._method = method\n            self._padding_mode = padding_mode\n            self._align_corners = align_corners\n\n        def forward(self, x, y):\n            return torch.nn.functional.grid_sample(\n                input=x,\n                grid=y,\n                mode=self._method,\n                padding_mode=self._padding_mode,\n                align_corners=self._align_corners,\n            )\n\n    methods = [\"nearest\", \"bilinear\", \"bicubic\"]\n    padding_modes = [\"zeros\", \"border\", \"reflection\"]\n    align_corners = [True, False]\n\n    data_2D = torch.rand([4, 4, 8, 8]).float()\n    grid_2D = torch.rand([4, 16, 16, 2]).float()\n    # choosing smaller sizes to be testable on weaker GPUs\n    data_3D = torch.rand([4, 4, 4, 4, 4]).float()\n    grid_3D = torch.rand([4, 8, 8, 8, 3]).float()\n\n    for _method in methods:\n        for _padding in padding_modes:\n            for _align in align_corners:\n                # ATTENTION:\n                #   \"nearest\" + \"reflection\" result may be different with pytorch on cpu device,\n                #   because pytorch's cpu result is different with gpu result,\n                #   and gpu result used here as baseline in tvm topi.image.grid_sample.\n                model = Grid_sample(_method, _padding, _align)\n                verify_model(model, input_data=[data_2D, grid_2D])\n\n                # 3D \"bicubic\"(tricubic) is not supported in pytorch\n                if _method != \"bicubic\":\n                    verify_model(model, input_data=[data_3D, grid_3D])\n\n\ndef test_list_tuple():\n    \"\"\"test compilation error for a Python list followed by a prim::TupleConstruct.\"\"\"\n\n    class List_tuple(Module):\n        \"\"\"List_tuple\"\"\"\n\n        def forward(self, x):\n            \"\"\"forward\"\"\"\n            merged = []\n            mask_list = []\n            for i in range(3):\n                w0 = torch.sigmoid(x)\n                merged.append((w0, w0))\n                mask_list.append(x)\n\n            for i in range(3):\n                merged[i] = merged[i][0] + merged[i][1]\n            return mask_list[2], merged\n\n    x = torch.rand([4, 4, 16, 32]).float()\n    script_module = torch.jit.trace(List_tuple(), x, strict=False).eval()\n    relay.frontend.from_pytorch(script_module, [(\"x\", x.shape)])\n\n\n# pylint: disable=unnecessary-dunder-call\n@tvm.testing.uses_gpu\ndef test_binary_bitwise():\n    \"\"\"Test for binary bitwise\"\"\"\n\n    def test_ior(x, y):\n        return x.__ior__(y)\n\n    def test_iand(x, y):\n        return x.__iand__(y)\n\n    def test_ixor(x, y):\n        return x.__ixor__(y)\n\n    x = torch.tensor([7, 49, 16, 1, 2, 3], dtype=torch.uint8)\n    y = torch.tensor([39, 128, 99, 228, 63, 17], dtype=torch.uint8)\n\n    for test_fn in [test_ior, test_iand, test_ixor]:\n        verify_model(test_fn, [x, y])\n\n\n@tvm.testing.uses_gpu\ndef test_shift():\n    \"\"\"Test for aten::__lshift__, aten::__rshift__\"\"\"\n\n    def test_lshift(x, y):\n        return x << y\n\n    def test_rshift(x, y):\n        return x >> y\n\n    x = torch.tensor([39, 128, 99, 228, 63, 17], dtype=torch.int32)\n    y = torch.tensor([3, 2, 7, 4, 5, 9], dtype=torch.int32)\n\n    for test_fn in [test_lshift, test_rshift]:\n        verify_model(test_fn, [x, y])\n\n\n@tvm.testing.uses_gpu\ndef test_mod():\n    \"\"\"Test for aten::fmod\"\"\"\n\n    def test_fmod(x, y):\n        return torch.fmod(x, y)\n\n    def test_remainder(x, y):\n        return torch.remainder(x, y)\n\n    for test_fn in [test_fmod, test_remainder]:\n        verify_model(test_fn, [torch.tensor([-3.0, -2, -1, 1, 2, 3]), torch.tensor(2)])\n        verify_model(test_fn, [torch.tensor([1, 2, 3, 4, 5]), torch.tensor(-1.5)])\n\n\ndef test_softmax_fuse():\n    \"\"\"test_softmax_fuse\"\"\"\n    # https://github.com/apache/tvm/issues/12001\n    class Model(torch.nn.Module):\n        \"\"\"Pytorch model module\"\"\"\n\n        def __init__(self, nchwc_post_op=False) -> None:\n            super().__init__()\n            self.conv = torch.nn.Conv2d(3, 3, (1, 1), 1)\n            self.nchwc_post_op = nchwc_post_op\n\n        @torch.no_grad()\n        def forward(self, x):\n            \"\"\"forward\"\"\"\n            t0a = self.conv(x)\n            t0b = torch.floor(x)\n            t2b = torch.softmax(t0a, dim=2)\n\n            if self.nchwc_post_op:\n                t3a = t0a - t0b\n                t4a = t2b - t0b\n                t6a = t3a + t4a\n                return t6a\n\n            return t2b + 1\n\n    sh = [3, 3, 10, 1]\n    inp = torch.ones(*sh, dtype=torch.float32)\n\n    for model in [Model(nchwc_post_op=False).eval(), Model(nchwc_post_op=True).eval()]:\n        output_torch = model(inp).numpy()\n\n        mod, params = relay.frontend.from_pytorch(torch.jit.trace(model, inp), [(\"inp0\", sh)])\n\n        with tvm.transform.PassContext(opt_level=4):\n            out = (\n                relay.create_executor(\"graph\", mod, params=params)\n                .evaluate()(inp0=inp.numpy())\n                .numpy()\n            )\n\n        tvm.testing.assert_allclose(out, output_torch, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_lerp():\n    \"\"\"test_lerp\"\"\"\n\n    def test_fn(x, y, w):\n        return torch.lerp(x, y, w)\n\n    input_shape = [16]\n    x = torch.rand(input_shape).float()\n    y = torch.rand(input_shape).float()\n    w = torch.rand(input_shape).float()\n\n    # weight can be tensor or scalar\n    verify_model(test_fn, [x, y, w])\n    verify_model(test_fn, [x, y, w[0]])\n\n\ndef test_trilu():\n    def _test_trilu(op, diagonal):\n        return lambda inp: op(inp, diagonal)\n\n    for op in [torch.triu, torch.tril]:\n        verify_model(_test_trilu(op, 0), [torch.rand(size=[3, 3])])\n        verify_model(_test_trilu(op, 1), [torch.rand(size=[6, 6])])\n        verify_model(_test_trilu(op, -2), [torch.rand(size=[6, 6])])\n\n\ndef test_multinomial():\n    def _test_multinomial(num_samples):\n        return lambda inp: torch.multinomial(inp, num_samples=num_samples, replacement=True)\n\n    # Dont check output since it's random. Instead we'll just make sure shapes are right.\n    verify_model(\n        _test_multinomial(2), [torch.rand(size=[3]).float()], cpu_only=True, check_correctness=False\n    )\n    verify_model(\n        _test_multinomial(1),\n        [torch.rand(size=[4, 5]).float()],\n        cpu_only=True,\n        check_correctness=False,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/test_fx_quant.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Tests on fx-quantized torch model conversion \"\"\"\nimport torch\nimport torchvision\nimport numpy as np\nfrom torch.quantization import get_default_qconfig\nfrom torch.quantization.quantize_fx import prepare_fx, convert_fx\nfrom torchvision.models.efficientnet import efficientnet_b4\nfrom torchvision.models.resnet import resnet50\nfrom tvm import relay\n\n\ndef quantize(model):\n    qconfig = get_default_qconfig(\"fbgemm\")\n    qconfig_dict = {\"\": qconfig}\n    return convert_fx(prepare_fx(model, qconfig_dict))\n\n\ndef quantize_and_build(model, in_size):\n    inp = torch.rand(1, 3, in_size, in_size)\n    input_name = \"inp\"\n    qmodel = quantize(model)\n\n    with torch.no_grad():\n        script_module = torch.jit.trace(qmodel, inp)\n        mod, _ = relay.frontend.from_pytorch(script_module, [(input_name, inp.shape)])\n        mod = relay.transform.InferType()(mod)\n\n        # Make sure that the model is quantized\n        assert \"qnn.conv2d\" in mod.astext(show_meta_data=False)\n\n        # Skip building since it is slow on CI\n        # relay.build(mod, params=params, target=\"llvm\")\n\n\ndef test_ssd_vgg():\n    class TraceWrapper(torch.nn.Module):\n        def __init__(self, model):\n            super().__init__()\n            self.model = model\n\n        def forward(self, inp):\n            features = self.model.backbone(inp)\n            features = list(features.values())\n            out = self.model.head(features)\n            return out[\"bbox_regression\"], out[\"cls_logits\"]\n\n    model_func = torchvision.models.detection.ssd300_vgg16\n    model = TraceWrapper(model_func(num_classes=50, pretrained_backbone=True)).eval()\n    quantize_and_build(model, 300)\n\n\ndef test_deeplab_v3():\n    class TraceWrapper(torch.nn.Module):\n        def __init__(self, model):\n            super().__init__()\n            self.model = model\n\n        def forward(self, inp):\n            out = self.model(inp)\n            return out[\"out\"]\n\n    deeplabv3 = torchvision.models.segmentation.deeplabv3_mobilenet_v3_large(pretrained=True)\n    model = TraceWrapper(deeplabv3.eval()).eval()\n    quantize_and_build(model, 300)\n\n\ndef test_imagenet():\n    for model_func in [resnet50, efficientnet_b4]:\n        quantize_and_build(model_func(pretrained=True).eval(), 224)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/test_lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Tests on torch lstm model conversion \"\"\"\n# originally from https://github.com/pytorch/pytorch/blob/master/benchmarks/fastrnns/custom_lstms.py\n# described in https://pytorch.org/blog/optimizing-cuda-rnn-with-torchscript/\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import Parameter\nimport torch.jit as jit\nfrom typing import List, Tuple\nfrom torch import Tensor\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.frontend.pytorch import from_pytorch\nfrom tvm.relay.prelude import Prelude\nfrom tvm.runtime.container import ADT, tuple_object\n\n\nclass LayerNormLSTMCell(jit.ScriptModule):\n    def __init__(self, input_size, hidden_size):\n        super().__init__()\n        self.input_size = input_size\n        self.hidden_size = hidden_size\n        self.weight_ih = Parameter(torch.randn(4 * hidden_size, input_size))\n        self.weight_hh = Parameter(torch.randn(4 * hidden_size, hidden_size))\n\n        ln = nn.LayerNorm\n\n        self.layernorm_i = ln(4 * hidden_size)\n        self.layernorm_h = ln(4 * hidden_size)\n        self.layernorm_c = ln(hidden_size)\n\n    @jit.script_method\n    def forward(self, input, state):\n        # type: (Tensor, Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tuple[Tensor, Tensor]]\n        hx, cx = state\n        igates = self.layernorm_i(torch.mm(input, self.weight_ih.t()))\n        hgates = self.layernorm_h(torch.mm(hx, self.weight_hh.t()))\n        gates = igates + hgates\n        ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n        ingate = torch.sigmoid(ingate)\n        forgetgate = torch.sigmoid(forgetgate)\n        cellgate = torch.tanh(cellgate)\n        outgate = torch.sigmoid(outgate)\n\n        cy = self.layernorm_c((forgetgate * cx) + (ingate * cellgate))\n        hy = outgate * torch.tanh(cy)\n\n        return hy, (hy, cy)\n\n\nclass LSTMLayer(jit.ScriptModule):\n    def __init__(self, cell, *cell_args):\n        super().__init__()\n        self.cell = cell(*cell_args)\n\n    @jit.script_method\n    def forward(self, input, state):\n        # type: (Tensor, Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tuple[Tensor, Tensor]]\n        outputs = []\n        for i in range(input.size(0)):\n            out, state = self.cell(input[i], state)\n            outputs += [out]\n        return torch.stack(outputs), state\n\n\nclass ReverseLSTMLayer(jit.ScriptModule):\n    def __init__(self, cell, *cell_args):\n        super(ReverseLSTMLayer, self).__init__()\n        self.cell = cell(*cell_args)\n\n    @jit.script_method\n    def forward(self, inputs, state):\n        # type: (Tensor, Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tuple[Tensor, Tensor]]\n        outputs = jit.annotate(List[Tensor], [])\n        seq_len = inputs.size(0)\n        for i in range(seq_len):\n            out, state = self.cell(inputs[seq_len - i - 1], state)\n            # workaround for the lack of list rev support\n            outputs = [out] + outputs\n        return torch.stack(outputs), state\n\n\nclass BidirLSTMLayer(jit.ScriptModule):\n    __constants__ = [\"directions\"]\n\n    def __init__(self, cell, *cell_args):\n        super(BidirLSTMLayer, self).__init__()\n        self.directions = nn.ModuleList(\n            [\n                LSTMLayer(cell, *cell_args),\n                ReverseLSTMLayer(cell, *cell_args),\n            ]\n        )\n\n    @jit.script_method\n    def forward(self, input, states):\n        # type: (Tensor, List[Tuple[Tensor, Tensor]]) -> Tuple[Tensor, List[Tuple[Tensor, Tensor]]]\n        # List[LSTMState]: [forward LSTMState, backward LSTMState]\n        outputs = jit.annotate(List[Tensor], [])\n        output_states = jit.annotate(List[Tuple[Tensor, Tensor]], [])\n        for (i, direction) in enumerate(self.directions):\n            state = states[i]\n            out, out_state = direction(input, state)\n            outputs += [out]\n            output_states += [out_state]\n        # tensor array concat assumes axis == 0 for now\n        # return torch.cat(outputs, -1), output_states\n        return torch.cat(outputs, 0), output_states\n\n\ndef init_stacked_lstm(num_layers, layer, first_layer_args, other_layer_args):\n    layers = [layer(*first_layer_args)] + [layer(*other_layer_args) for _ in range(num_layers - 1)]\n    return nn.ModuleList(layers)\n\n\nclass StackedLSTM(jit.ScriptModule):\n    __constants__ = [\"layers\"]  # Necessary for iterating through self.layers\n\n    def __init__(self, num_layers, layer, first_layer_args, other_layer_args):\n        super().__init__()\n        self.layers = init_stacked_lstm(num_layers, layer, first_layer_args, other_layer_args)\n\n    @jit.script_method\n    def forward(self, input, states):\n        # type: (Tensor, List[Tuple[Tensor, Tensor]]) -> Tuple[Tensor, List[Tuple[Tensor, Tensor]]]\n        # List[LSTMState]: One state per layer\n        output_states = jit.annotate(List[Tuple[Tensor, Tensor]], [])\n        output = input\n        for (i, rnn_layer) in enumerate(self.layers):\n            state = states[i]\n            output, out_state = rnn_layer(output, state)\n            output_states += [out_state]\n        return output, output_states\n\n\nclass StackedBidirLSTM(jit.ScriptModule):\n    __constants__ = [\"layers\"]  # Necessary for iterating through self.layers\n\n    def __init__(self, num_layers, layer, first_layer_args, other_layer_args):\n        super(StackedBidirLSTM, self).__init__()\n        self.layers = init_stacked_lstm(num_layers, layer, first_layer_args, other_layer_args)\n\n    @jit.script_method\n    def forward(self, input, states):\n        # type: (Tensor, List[List[Tuple[Tensor, Tensor]]]) -> Tuple[Tensor, List[List[Tuple[Tensor, Tensor]]]]\n        # List[List[LSTMState]]: The outer list is for layers,\n        #                        inner list is for directions.\n        output_states = jit.annotate(List[List[Tuple[Tensor, Tensor]]], [])\n        output = input\n        for (i, rnn_layer) in enumerate(self.layers):\n            state = states[i]\n            output, out_state = rnn_layer(output, state)\n            output_states += [out_state]\n        return output, output_states\n\n\ndef lstm(input_size, hidden_size):\n    return LSTMLayer(LayerNormLSTMCell, input_size, hidden_size)\n\n\ndef stacked_lstm(input_size, hidden_size, num_layers):\n    return StackedLSTM(\n        num_layers,\n        LSTMLayer,\n        first_layer_args=[LayerNormLSTMCell, input_size, hidden_size],\n        other_layer_args=[LayerNormLSTMCell, hidden_size, hidden_size],\n    )\n\n\ndef bidir_lstm(input_size, hidden_size):\n    return BidirLSTMLayer(LayerNormLSTMCell, input_size, hidden_size)\n\n\ndef stacked_bidir_lstm(input_size, hidden_size, num_layers):\n    return StackedBidirLSTM(\n        num_layers,\n        BidirLSTMLayer,\n        first_layer_args=[LayerNormLSTMCell, input_size, hidden_size],\n        other_layer_args=[LayerNormLSTMCell, hidden_size, hidden_size],\n    )\n\n\ndef vmobj_to_list(o, dtype=\"float32\"):\n    if isinstance(o, tvm.nd.NDArray):\n        return [o]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(f, dtype))\n        return result\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef assert_equal(tvm_result, torch_result):\n    if isinstance(torch_result, (tuple, list)):\n        assert isinstance(tvm_result, list)\n        for tvm_res, pt_res in zip(tvm_result, torch_result):\n            assert_equal(tvm_res, pt_res)\n    elif isinstance(torch_result, torch.Tensor):\n        tvm.testing.assert_allclose(tvm_result.numpy(), torch_result.numpy(), rtol=1e-4, atol=1e-4)\n\n\ndef run_and_compare(mod, params, pt_result, target, device):\n    exec_res = relay.create_executor(\"vm\", mod=mod, device=device, target=target).evaluate()(\n        **params\n    )\n\n    def flatten(nested):\n        res = []\n        for r in nested:\n            if isinstance(r, torch.Tensor):\n                res.append(r)\n            else:\n                res.extend(flatten(r))\n        return res\n\n    if isinstance(exec_res, tvm.runtime.container.ADT):\n        assert not isinstance(pt_result, torch.Tensor)\n        tvm_res = vmobj_to_list(exec_res)\n        torch_res = flatten(pt_result)\n    else:\n        tvm_res = exec_res\n        torch_res = pt_result\n\n    assert_equal(tvm_res, torch_res)\n\n\ndef convert_list_to_vmobj(py_lst):\n    def wrap_nd_array(arr):\n        return tvm.nd.array(arr, device=tvm.cpu(0))\n\n    mod = tvm.IRModule()\n    prelude = Prelude(mod)\n    list, cons, nil = mod.get_type(\"List\")\n    adt_lst = ADT(nil.tag, [])\n    for elem in reversed(py_lst):\n        if isinstance(elem, np.ndarray):\n            vmobj = wrap_nd_array(elem)\n        elif isinstance(elem, tuple):\n            vmobj = tuple_object([wrap_nd_array(e) for e in elem])\n        elif isinstance(elem, list):\n            vmobj = convert_list_to_vmobj(elem)\n        adt_lst = ADT(cons.tag, [vmobj, adt_lst])\n    return adt_lst\n\n\n@tvm.testing.uses_gpu\ndef test_custom_lstm():\n    input_name = \"input\"\n    states_name = \"states\"\n    seq_len = 5\n    batch = 2\n    input_size = 3\n    hidden_size = 4\n    num_layers = 3\n    state_tensor_shape = (batch, hidden_size)\n\n    torch.manual_seed(1)\n\n    inp = torch.randn(seq_len, batch, input_size)\n\n    input_shapes = [\n        (input_name, (seq_len, batch, input_size)),\n        (states_name, (state_tensor_shape, state_tensor_shape)),\n    ]\n\n    input_shapes_stacked = [\n        (input_name, (seq_len, batch, input_size)),\n        (\n            states_name,\n            [(state_tensor_shape, state_tensor_shape), (state_tensor_shape, state_tensor_shape)],\n        ),\n    ]\n\n    input_shapes_stacked_bidir = [\n        (input_name, (seq_len, batch, input_size)),\n        (\n            states_name,\n            [\n                [(state_tensor_shape, state_tensor_shape) for _ in range(2)]\n                for _ in range(num_layers)\n            ],\n        ),\n    ]\n\n    states = [\n        (torch.randn(state_tensor_shape), torch.randn(state_tensor_shape))\n        for _ in range(num_layers)\n    ]\n\n    bidir_states = [\n        (torch.randn(state_tensor_shape), torch.randn(state_tensor_shape)) for _ in range(2)\n    ]\n\n    stacked_bidir_states = [\n        [(torch.randn(state_tensor_shape), torch.randn(state_tensor_shape)) for _ in range(2)]\n        for _ in range(num_layers)\n    ]\n\n    models = [\n        (\"lstm\", lstm(input_size, hidden_size).eval(), states[0], input_shapes),\n        (\n            \"stacked\",\n            stacked_lstm(input_size, hidden_size, num_layers).eval(),\n            states,\n            input_shapes_stacked,\n        ),\n        (\"bidir\", bidir_lstm(input_size, hidden_size).eval(), bidir_states, input_shapes_stacked),\n        # TODO(masahi): stacked bidir seems to have a rare accuracy issue\n        # (\n        #     \"stacked_bidir\",\n        #     stacked_bidir_lstm(input_size, hidden_size, num_layers).eval(),\n        #     stacked_bidir_states,\n        #     input_shapes_stacked_bidir,\n        # ),\n    ]\n\n    for (name, raw_model, states, input_shapes) in models:\n        script_module = torch.jit.script(raw_model)\n        mod, params = from_pytorch(script_module, input_shapes)\n\n        with torch.no_grad():\n            pt_result = raw_model(inp.clone(), states)\n\n        params[input_name] = inp.numpy()\n\n        if isinstance(states, tuple):\n            states_np = tuple(st.numpy() for st in states)\n        elif isinstance(states, list) and isinstance(states[0], torch.Tensor):\n            states_np = [st.numpy() for st in states]\n        elif isinstance(states, list) and isinstance(states[0], tuple):\n            states_np = [tuple(st.numpy() for st in states[i]) for i in range(len(states))]\n        elif isinstance(states, list) and isinstance(states[0], list):\n            states_np = [\n                [tuple(st.numpy() for st in states) for states in states[layer]]\n                for layer in range(num_layers)\n            ]\n        else:\n            assert False\n\n        if isinstance(states_np, list):\n            params[states_name] = convert_list_to_vmobj(states_np)\n        else:\n            params[states_name] = states_np\n\n        for tgt, dev in tvm.testing.enabled_targets():\n            print(\"Running %s on target %s\" % (name, tgt))\n            run_and_compare(mod, params, pt_result, target=tgt, device=dev)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/test_object_detection.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument\n\"\"\"Test torch vision fasterrcnn and maskrcnn models\"\"\"\nimport numpy as np\nimport cv2\n\nimport torch\nimport torchvision\n\nimport tvm\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.relay.frontend.pytorch_utils import (\n    rewrite_nms_to_batched_nms,\n    rewrite_batched_nms_with_max_out_size,\n    rewrite_scatter_to_gather,\n)\nfrom tvm.contrib.download import download\n\nin_size = 300\n\n\ndef process_image(img):\n    img = cv2.imread(img).astype(\"float32\")\n    img = cv2.resize(img, (in_size, in_size))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = torch.from_numpy(img / 255.0).permute(2, 0, 1).float()\n    img = torch.unsqueeze(img, axis=0)\n\n    return img\n\n\ndef do_trace(model, inp, in_size=in_size):\n    model_trace = torch.jit.trace(model, inp)\n    model_trace.eval()\n    return model_trace\n\n\ndef dict_to_tuple(out_dict):\n    if \"masks\" in out_dict.keys():\n        return out_dict[\"boxes\"], out_dict[\"scores\"], out_dict[\"labels\"], out_dict[\"masks\"]\n    return out_dict[\"boxes\"], out_dict[\"scores\"], out_dict[\"labels\"]\n\n\nclass TraceWrapper(torch.nn.Module):\n    def __init__(self, model):\n        super().__init__()\n        self.model = model\n\n    def forward(self, inp):\n        out = self.model(inp)\n        return dict_to_tuple(out[0])\n\n\ndef generate_jit_model(index):\n    model_funcs = [\n        torchvision.models.detection.fasterrcnn_resnet50_fpn,\n        torchvision.models.detection.maskrcnn_resnet50_fpn,\n    ]\n\n    model_func = model_funcs[index]\n    model = TraceWrapper(model_func(pretrained=True, rpn_pre_nms_top_n_test=1000))\n\n    model.eval()\n    inp = torch.Tensor(np.random.uniform(0.0, 250.0, size=(1, 3, in_size, in_size)))\n\n    with torch.no_grad():\n        out = model(inp)\n\n        script_module = do_trace(model, inp)\n        script_out = script_module(inp)\n\n        assert len(out[0]) > 0 and len(script_out[0]) > 0\n        return script_module\n\n\ndef test_detection_models():\n    img = \"test_street_small.jpg\"\n    img_url = (\n        \"https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/detection/street_small.jpg\"\n    )\n    download(img_url, img)\n\n    input_shape = (1, 3, in_size, in_size)\n\n    input_name = \"input0\"\n    shape_list = [(input_name, input_shape)]\n\n    scripted_model = generate_jit_model(1)\n    mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)\n\n    data = process_image(img)\n    data_np = data.detach().numpy()\n\n    with torch.no_grad():\n        pt_res = scripted_model(data)\n\n    def compile_and_run_vm(mod, params, data_np, target):\n        with tvm.transform.PassContext(opt_level=3):\n            vm_exec = relay.vm.compile(mod, target=target, params=params)\n\n        dev = tvm.device(target, 0)\n        vm = VirtualMachine(vm_exec, dev)\n        vm.set_input(\"main\", **{input_name: data_np})\n        return vm.run()\n\n    for target in [\"llvm\"]:\n        tvm_res = compile_and_run_vm(mod, params, data_np, target)\n\n        # Bounding boxes\n        tvm.testing.assert_allclose(\n            pt_res[0].cpu().numpy(), tvm_res[0].numpy(), rtol=1e-5, atol=1e-5\n        )\n        # Scores\n        tvm.testing.assert_allclose(\n            pt_res[1].cpu().numpy(), tvm_res[1].numpy(), rtol=1e-5, atol=1e-5\n        )\n        # Class ids\n        np.testing.assert_equal(pt_res[2].cpu().numpy(), tvm_res[2].numpy())\n\n        score_threshold = 0.9\n        print(\"Num boxes:\", pt_res[0].cpu().numpy().shape[0])\n        print(\"Num valid boxes:\", np.sum(pt_res[1].cpu().numpy() >= score_threshold))\n\n    before = mod[\"main\"]\n    mod = rewrite_nms_to_batched_nms(mod)\n    after = mod[\"main\"]\n    assert not tvm.ir.structural_equal(after, before)\n\n    # TODO(masahi): It seems this rewrite causes flaky segfaults on CI\n    # See https://github.com/apache/tvm/issues/7363\n    # before = mod[\"main\"]\n    # mod = rewrite_batched_nms_with_max_out_size(mod)\n    # after = mod[\"main\"]\n    # assert not tvm.ir.structural_equal(after, before)\n\n    before = mod[\"main\"]\n    mod = rewrite_scatter_to_gather(mod, 4)  # num_scales is 4 for maskrcnn_resnet50_fpn\n    after = mod[\"main\"]\n    assert not tvm.ir.structural_equal(after, before)\n\n    tvm_res_after_rewrite = compile_and_run_vm(mod, params, data_np, \"llvm\")\n\n    # Results should be equivalent after rewriting\n    for res1, res2 in zip(tvm_res, tvm_res_after_rewrite):\n        tvm.testing.assert_allclose(res1.numpy(), res2.numpy())\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/pytorch/test_rnns.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport torch\nimport tvm\nimport tvm.testing\nimport onnx\nimport io\nimport sys\n\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\nfrom torch import nn\n\n## LSTM parameters\nlstm_feature_size = 16\nlstm_hidden_size = 32\nlstm_projection_size = 20\n\n## GRU parameters\ngru_feature_size = 8\ngru_hidden_size = 16\n\nnum_layers = 2\nseqs_length = 2\nbatch_size = 2\n\n##RNN parameters\nrnn_feature_size = 8\nrnn_hidden_size = 16\n\n\nclass RNN_Model(nn.Module):\n    \"\"\"\n    It is base class for RNN layer classes.\n    It contains some common fields and methods for child classes.\n    \"\"\"\n\n    def __init__(\n        self,\n    ):\n        super().__init__()\n\n        # model is defined in child class\n        self.model = None\n\n    def forward(self, input, hidden_init=None):\n        \"\"\"\n        Computes the output tensor after input inference along RNN layer.\n\n        :param input: batch of data as a tensor of shape (seqs_length, batch_size, feature_size) or (batch_size, seqs_length, feature_size) if self.batch_first = True\n        :param hidden_init: initial hidden state(s) of the RNN as a tensor(s) of shape (num_layers, batch_size, hidden_size). Will default to a tensor of zeros if None.\n        :return: the output tensor of shape (batch_size, hidden_size)\n        \"\"\"\n        if self.model is None:\n            raise NotImplementedError(\"self.model must be defined in subclasses!\")\n        out, _ = self.model(input, hidden_init)\n\n        return out\n\n    def gen_rnd_weights(self):\n        \"\"\"\n        Generate random weigths for the model\n        \"\"\"\n        if self.model is None:\n            raise NotImplementedError(\"self.model must be defined in subclasses!\")\n        with torch.no_grad():\n            for weight_group in self.model.all_weights:\n                for weight in weight_group:\n                    weight.data = torch.rand(weight.shape)\n\n    def get_dummy_inputs(self):\n        raise NotImplementedError(\"subclasses must override get_dummy_inputs()!\")\n\n    def get_input_names(self):\n        raise NotImplementedError(\"subclasses must override get_input_names()!\")\n\n    def get_shape_desc(self, frontend_type):\n        raise NotImplementedError(\"subclasses must override get_shape_desc(frontend_type)!\")\n\n    def get_tvm_inputs(self, dtype):\n        raise NotImplementedError(\"subclasses must override get_tvm_inputs(dtype)!\")\n\n\nclass RNN_Model_Impl(RNN_Model):\n    def __init__(\n        self,\n        seq_len=seqs_length,\n        batch_size=batch_size,\n        feature_size=rnn_feature_size,\n        hidden_size=rnn_hidden_size,\n        batch_first=False,\n        layer_num=1,\n        bidirectional=False,\n        use_bias=True,\n        rnd_weights_init=False,\n        nonlinearity=\"tanh\",\n        dropout=0.0,\n    ):\n        super().__init__()\n        # Shapes\n        self.shape = [seq_len, batch_size, feature_size]\n        if batch_first:\n            self.shape = [batch_size, seq_len, feature_size]\n        layers_num = 2 * layer_num if bidirectional else layer_num\n        self.h0_shape = [layers_num, batch_size, hidden_size]\n        # Dummy inputs\n        self.dummy_inputs = (torch.rand(self.shape), torch.zeros(self.h0_shape))\n\n        self.model = nn.RNN(\n            input_size=feature_size,\n            hidden_size=hidden_size,\n            num_layers=layer_num,\n            nonlinearity=nonlinearity,\n            bias=use_bias,\n            batch_first=batch_first,\n            dropout=dropout,\n            bidirectional=bidirectional,\n        )\n\n        if rnd_weights_init:\n            self.gen_rnd_weights()\n\n    def gen_rnd_weights(self):\n        super().gen_rnd_weights()\n\n    def get_dummy_inputs(self):\n        return self.dummy_inputs\n\n    def get_input_names(self):\n        return [\"input\", \"h0\"]\n\n    def get_shape_desc(self, frontend_type):\n        shape_desc = None\n        if frontend_type == \"pt\":  # PyTorch\n            shape_desc = [(\"input\", self.shape)]\n        elif frontend_type == \"onnx\":  # ONNX\n            shape_desc = {\n                \"input\": self.shape,\n                \"h0\": self.h0_shape,\n            }\n        return shape_desc\n\n    def get_tvm_inputs(self, dtype):\n        return {\n            \"input\": tvm.nd.array(self.dummy_inputs[0].numpy().astype(dtype)),\n            \"h0\": tvm.nd.array(self.dummy_inputs[1].numpy().astype(dtype)),\n        }\n\n\nclass GRU_Model(RNN_Model):\n    def __init__(\n        self,\n        seq_len=seqs_length,\n        batch_size=batch_size,\n        feature_size=gru_feature_size,\n        hidden_size=gru_hidden_size,\n        batch_first=False,\n        layer_num=1,\n        bidirectional=False,\n        use_bias=True,\n        rnd_weights_init=False,\n    ):\n        super().__init__()\n\n        # Shapes\n        self.shape = [seq_len, batch_size, feature_size]\n        if batch_first:\n            self.shape = [batch_size, seq_len, feature_size]\n        layers_num = 2 * layer_num if bidirectional else layer_num\n        self.h0_shape = [layers_num, batch_size, hidden_size]\n        # Dummy inputs\n        self.dummy_inputs = (torch.rand(self.shape), torch.zeros(self.h0_shape))\n\n        self.model = nn.GRU(\n            input_size=feature_size,\n            hidden_size=hidden_size,\n            num_layers=layer_num,\n            bidirectional=bidirectional,\n            batch_first=batch_first,\n            bias=use_bias,\n        )\n\n        if rnd_weights_init:\n            self.gen_rnd_weights()\n\n    def gen_rnd_weights(self):\n        \"\"\"\n        Generate random weigths for the model with biases\n        For first uni- and bidirectional weights group:\n            Wi (3*hidden_size, feature_size)\n            Wh (3*hidden_size, hidden_size)\n            Bi (3*hidden_size)\n            Bh (3*hidden_size)\n        For other weights group:\n            Wi (3*hidden_size, hidden_size)\n            Wh (3*hidden_size, hidden_size)\n            Bi (3*hidden_size)\n            Bh (3*hidden_size)\n        For generation of random weigths for the model without biases the Bi and Bh weights are skipped\n        \"\"\"\n        super().gen_rnd_weights()\n\n    def get_dummy_inputs(self):\n        return self.dummy_inputs\n\n    def get_input_names(self):\n        return [\"input\", \"h0\"]\n\n    def get_shape_desc(self, frontend_type):\n        shape_desc = None\n        if frontend_type == \"pt\":  # PyTorch\n            shape_desc = [(\"input\", self.shape)]\n        elif frontend_type == \"onnx\":  # ONNX\n            shape_desc = {\n                \"input\": self.shape,\n                \"h0\": self.h0_shape,\n            }\n        return shape_desc\n\n    def get_tvm_inputs(self, dtype):\n        return {\n            \"input\": tvm.nd.array(self.dummy_inputs[0].numpy().astype(dtype)),\n            \"h0\": tvm.nd.array(self.dummy_inputs[1].numpy().astype(dtype)),\n        }\n\n\ndef check_torch_version_for_proj_in_lstm():\n    \"\"\"\n    proj_size parameter is supported in torch.nn.LSTM layer started from 1.8.0 torch version\n    \"\"\"\n    me = False\n\n    version = torch.__version__\n    major, minor, micro = version.split(\".\")\n\n    if int(major) > 1:\n        me = True\n    elif int(major) == 1:\n        if int(minor) >= 8:\n            me = True\n\n    return me\n\n\nclass LSTM_Model(RNN_Model):\n    def __init__(\n        self,\n        seq_len=seqs_length,\n        batch_size=batch_size,\n        feature_size=lstm_feature_size,\n        hidden_size=lstm_hidden_size,\n        batch_first=False,\n        layer_num=1,\n        bidirectional=False,\n        proj_size=0,\n        use_bias=True,\n        rnd_weights_init=False,\n    ):\n        super().__init__()\n\n        # Shapes\n        self.shape = [seq_len, batch_size, feature_size]\n        if batch_first:\n            self.shape = [batch_size, seq_len, feature_size]\n        layers_num = 2 * layer_num if bidirectional else layer_num\n        self.h0_shape = [layers_num, batch_size, hidden_size]\n        if proj_size > 0:\n            self.h0_shape = [layers_num, batch_size, proj_size]\n        self.c0_shape = [layers_num, batch_size, hidden_size]\n        # Dummy inputs\n        self.dummy_inputs = (\n            torch.rand(self.shape),\n            (torch.zeros(self.h0_shape), torch.zeros(self.c0_shape)),\n        )\n\n        if check_torch_version_for_proj_in_lstm():\n            self.model = nn.LSTM(\n                input_size=lstm_feature_size,\n                hidden_size=lstm_hidden_size,\n                num_layers=layer_num,\n                bidirectional=bidirectional,\n                proj_size=proj_size,\n                batch_first=batch_first,\n                bias=use_bias,\n            )\n        else:\n            if proj_size > 0:\n                print(\n                    \"WARNING: projection is not supported for torch version less than 1.8.0! \",\n                    \"LSTM was constructed without projection!\",\n                )\n                # sys.exit()\n            self.model = nn.LSTM(\n                input_size=lstm_feature_size,\n                hidden_size=lstm_hidden_size,\n                num_layers=layer_num,\n                bidirectional=bidirectional,\n                batch_first=batch_first,\n                bias=use_bias,\n            )\n\n        if rnd_weights_init:\n            self.gen_rnd_weights()\n\n    def gen_rnd_weights(self):\n        \"\"\"\n        Generate random weigths for the model with biases\n        Without projection:\n            For first weights group:\n                Wi (4*lstm_hidden_size, lstm_feature_size)\n                Wh (4*lstm_hidden_size, lstm_hidden_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n            For first bidirectional weights group:\n                Wi (4*lstm_hidden_size, lstm_feature_size)\n                Wh (4*lstm_hidden_size, lstm_hidden_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n            For other weights group:\n                Wi (4*lstm_hidden_size, lstm_hidden_size)\n                Wh (4*lstm_hidden_size, lstm_hidden_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n        With projection:\n            For first weights group:\n                Wi (4*lstm_hidden_size, lstm_feature_size)\n                Wh (4*lstm_hidden_size, proj_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n                P  (proj_size, lstm_hidden_size)\n            For first bidirectional weights group:\n                Wi (4*lstm_hidden_size, lstm_feature_size)\n                Wh (4*lstm_hidden_size, proj_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n                P  (proj_size, lstm_hidden_size)\n            For other weights group:\n                Wi (4*lstm_hidden_size, proj_size * num_directions)\n                Wh (4*lstm_hidden_size, proj_size)\n                Bi (4*lstm_hidden_size)\n                Bh (4*lstm_hidden_size)\n                P  (proj_size, lstm_hidden_size)\n        For generation of random weigths for the model without biases Bi and Bh are skipped\n        \"\"\"\n        super().gen_rnd_weights()\n\n    def get_dummy_inputs(self):\n        return self.dummy_inputs\n\n    def get_input_names(self):\n        return [\"input\", \"h0\", \"c0\"]\n\n    def get_shape_desc(self, frontend_type):\n        shape_desc = None\n        if frontend_type == \"pt\":  # PyTorch\n            shape_desc = [(\"input\", self.shape)]\n        elif frontend_type == \"onnx\":  # ONNX\n            shape_desc = {\n                \"input\": self.shape,\n                \"h0\": self.h0_shape,\n                \"c0\": self.c0_shape,\n            }\n        return shape_desc\n\n    def get_tvm_inputs(self, dtype):\n        return {\n            \"input\": tvm.nd.array(self.dummy_inputs[0].numpy().astype(dtype)),\n            \"h0\": tvm.nd.array(self.dummy_inputs[1][0].numpy().astype(dtype)),\n            \"c0\": tvm.nd.array(self.dummy_inputs[1][1].numpy().astype(dtype)),\n        }\n\n\ndef compare(input, gold_data, rtol=1e-5, atol=1e-5):\n    tvm.testing.assert_allclose(input, gold_data, rtol=rtol, atol=atol)\n\n\ndef check_rnn(rnn_type, rnn_mod, target=tvm.target.Target(\"llvm -mcpu=core-avx2\"), dev=tvm.cpu(0)):\n    def get_model(\n        rnn_type,\n        rnn_mod,\n        args,\n    ):\n        # Fill args\n        if \"b\" in rnn_mod:\n            args[\"bidirectional\"] = True\n        if \"s\" in rnn_mod:\n            args[\"layer_num\"] = num_layers\n        if \"tanh\" in rnn_mod:\n            args[\"nonlinearity\"] = \"tanh\"\n        if \"relu\" in rnn_mod:\n            args[\"nonlinearity\"] = \"relu\"\n\n        if rnn_type == \"GRU\":\n            RNN_Model_selector = GRU_Model\n        elif rnn_type == \"LSTM\":\n            RNN_Model_selector = LSTM_Model\n            if \"p\" in rnn_mod:\n                args[\"proj_size\"] = lstm_projection_size\n        elif rnn_type == \"RNN\":\n            RNN_Model_selector = RNN_Model_Impl\n\n        return RNN_Model_selector(**args)\n\n    def get_onnx_model(model):\n        onnx_io = io.BytesIO()\n        with torch.no_grad():\n            input_names = model.get_input_names()\n            inputs = model.get_dummy_inputs()\n\n            # default export (without dynamic input)\n            torch.onnx.export(model, inputs, onnx_io, input_names=input_names)\n\n        onnx_io.seek(0, 0)\n        return onnx.load_model(onnx_io)\n\n    model = None\n    dtype = \"float32\"\n    device = torch.device(\"cpu\")\n    for batch_first in (True, False):\n        for use_bias in (True, False):\n            for rnd_weights in [True]:  # (True, False):\n                model_inputs = {\n                    \"batch_first\": batch_first,\n                    \"use_bias\": use_bias,\n                    \"rnd_weights_init\": rnd_weights,\n                }\n                model = get_model(rnn_type, rnn_mod, model_inputs)\n                model.to(device)\n                model.eval()\n\n                # Get golden output from original model\n                dummy_inputs = model.get_dummy_inputs()\n                golden_output = model.forward(dummy_inputs[0].to(device)).detach().cpu().numpy()\n\n                tvm_output = None\n                for format in [\"pt\"]:  # [\"pt\", \"onnx\"]:\n                    shape_desc = model.get_shape_desc(format)\n                    if format == \"pt\":\n                        # Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.\n                        traced_script_module = torch.jit.trace(model, dummy_inputs[0]).eval()\n\n                        # Import model to Relay\n                        mod, params = relay.frontend.from_pytorch(traced_script_module, shape_desc)\n                    elif format == \"onnx\":\n                        try:\n                            onnx_model = get_onnx_model(model)\n                        except:\n                            print(\n                                \"WARNING: torch.onnx.export does not support conversion LSTM with projection \"\n                                \"from pytorch! TODO: waiting for the support and correct test after that.\"\n                            )\n                            continue\n\n                        # Import model to Relay\n                        mod, params = relay.frontend.from_onnx(onnx_model, shape_desc)\n\n                    # Model compilation by tvm\n                    with tvm.transform.PassContext(opt_level=3):\n                        lib = relay.build(mod, target=target, params=params)\n\n                    # Inference of the model with given input data\n                    m = graph_executor.GraphModule(lib[\"default\"](dev))\n\n                    # Set inputs\n                    tvm_inputs = model.get_tvm_inputs(dtype)\n                    m.set_input(**tvm_inputs)\n                    # Execute\n                    m.run()\n                    # Get outputs (converted to numpy array)\n                    tvm_output = m.get_output(0).numpy()\n\n                    compare(tvm_output, golden_output)\n\n\n@tvm.testing.uses_gpu\ndef test_rnns():\n    for target, dev in tvm.testing.enabled_targets():\n        # RNN types: GRU, LSTM\n        # GRU modifications: unidirectional, stacked, bidirectional, stacked bidirectional\n        for mod_type in [\"uni\", \"s\", \"b\", \"sb\"]:\n            check_rnn(\"GRU\", mod_type, target, dev)\n        # LSTM modifications: unidirectional, stacked, bidirectional, stacked bidirectional,\n        # and all these types with projection (\"p\", \"sp\", \"bp\", \"sbp\")\n        # The latter are skiped for test acceleration\n        for mod_type in [\"uni\", \"s\", \"b\", \"sb\"]:\n            check_rnn(\"LSTM\", mod_type, target, dev)\n\n        for mod_type in [\"uni\", \"s\", \"b\", \"sb\", \"tanh\", \"relu\"]:\n            check_rnn(\"RNN\", mod_type, target, dev)\n\n\nif __name__ == \"__main__\":\n    test_rnns()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow/test_bn_dynamic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nBatchNorm without given mean and variance given testcases\n====================\nThis is a test script to test fused_batch_norm operators\nin TensorFlow frontend when mean and variance are not given.\n\"\"\"\nimport tvm\nimport tvm.testing\nimport numpy as np\n\ntry:\n    import tensorflow.compat.v1 as tf\n\n    tf.disable_v2_behavior()\nexcept ImportError:\n    import tensorflow as tf\nfrom tvm import relay\nfrom tensorflow.python.framework import graph_util\n\n\ndef verify_fused_batch_norm(shape):\n    g = tf.Graph()\n    with g.as_default():\n        input_tensor = tf.placeholder(tf.float32, shape=shape, name=\"input\")\n        alpha = tf.constant(\n            np.random.rand(\n                shape[-1],\n            ),\n            dtype=tf.float32,\n            name=\"alpha\",\n        )\n        beta = tf.constant(\n            np.random.rand(\n                shape[-1],\n            ),\n            dtype=tf.float32,\n            name=\"beta\",\n        )\n        bn = tf.nn.fused_batch_norm(x=input_tensor, offset=beta, scale=alpha, name=\"bn\")\n        out = tf.identity(bn[0], name=\"output\")\n    data = np.random.rand(*shape)\n    with tf.Session(graph=out.graph) as sess:\n        sess.run([tf.global_variables_initializer()])\n        tf_out = sess.run(out, feed_dict={input_tensor: data})\n        constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, [\"output\"])\n\n    for device in [\"llvm\"]:\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            continue\n        mod, params = relay.frontend.from_tensorflow(constant_graph, outputs=[\"output\"])\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(mod, target=device, params=params)\n        from tvm.contrib import graph_executor\n\n        m = graph_executor.create(graph, lib, dev)\n        m.set_input(**params)\n        m.set_input(\"input\", data)\n        m.run()\n        tvm_out = m.get_output(0)\n        tvm.testing.assert_allclose(\n            tvm_out.numpy(), tf_out.astype(tvm_out.dtype), atol=1e-3, rtol=1e-3\n        )\n\n\ndef test_fused_batch_norm():\n    verify_fused_batch_norm(shape=(1, 12, 12, 32))\n    verify_fused_batch_norm(shape=(1, 24, 24, 64))\n    verify_fused_batch_norm(shape=(1, 64, 64, 128))\n    verify_fused_batch_norm(shape=(8, 12, 12, 32))\n    verify_fused_batch_norm(shape=(16, 12, 12, 32))\n    verify_fused_batch_norm(shape=(32, 12, 12, 32))\n\n\nif __name__ == \"__main__\":\n    test_fused_batch_norm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow/test_control_flow.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for converting TensorFlow control flow op to Relay.\"\"\"\nimport pytest\n\ntry:\n    import tensorflow.compat.v1 as tf\n\n    tf.disable_v2_behavior()\nexcept ImportError:\n    import tensorflow as tf\nfrom tensorflow.python.ops import control_flow_ops\nimport numpy as np\nfrom tvm import nd\nfrom tvm import relay\nfrom tvm.relay.frontend.tensorflow import from_tensorflow\n\n\ndef check_equal(graph, tf_out, input_map=None):\n    mod, params = from_tensorflow(graph.as_graph_def(add_shapes=True))\n    if input_map is not None:\n        params.update(input_map)\n    relay_out = relay.create_executor(\"vm\", mod=mod).evaluate()(**params)\n    if isinstance(relay_out, nd.NDArray):\n        np.testing.assert_allclose(tf_out, relay_out.numpy())\n    else:\n        if not isinstance(tf_out, (list, tuple)):\n            tf_out = [tf_out]\n        for x, y in zip(tf_out, [r.numpy() for r in relay_out]):\n            np.testing.assert_allclose(x, y)\n\n\ndef test_vanilla_loop():\n    graph = tf.Graph()\n    with graph.as_default():\n        i = tf.constant(0, name=\"while/constant\")\n\n        def c(i):\n            return tf.less(i, 10)\n\n        def b(i):\n            return tf.add(i, 1)\n\n        r = tf.while_loop(c, b, [i])\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n        check_equal(graph, tf_out)\n\n\ndef test_callnode_loop_vars():\n    graph = tf.Graph()\n    with graph.as_default():\n        i = tf.add(tf.constant(0), 1)\n\n        def c(i):\n            return tf.less(i, 10)\n\n        def b(i):\n            return tf.add(i, 1)\n\n        r = tf.while_loop(c, b, [i])\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n        check_equal(graph, tf_out)\n\n\ndef test_loop_2_vars():\n    graph = tf.Graph()\n    with graph.as_default():\n        i0 = tf.constant(0)\n        j0 = tf.ones([2, 2])\n\n        def c(i, j):\n            return i < 10\n\n        def b(i, j):\n            return [tf.add(i, 1), j]\n\n        i1, i2 = tf.while_loop(c, b, loop_vars=[i0, j0])\n        i1 += tf.constant(1337)\n\n        with tf.Session() as sess:\n            tf_out = sess.run(i1)\n\n    check_equal(graph, tf_out)\n\n\ndef test_loop_3_vars():\n    graph = tf.Graph()\n    with graph.as_default():\n        i0 = tf.constant(1)\n        j0 = tf.constant(2)\n        k0 = tf.constant(4)\n\n        def c(i, j, k):\n            return i < 10\n\n        def b(i, j, k):\n            return [i + 1, j * k, k + i]\n\n        r = tf.while_loop(c, b, loop_vars=[i0, j0, k0])\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_loop_conditions():\n    graph = tf.Graph()\n    with graph.as_default():\n        i = tf.constant(1)\n        j = tf.constant(1)\n        k = tf.constant(5)\n\n        def c(i, j, k):\n            return tf.equal(\n                tf.not_equal(tf.less(i + j, 10), tf.less(j * k, 100)), tf.greater_equal(k, i + j)\n            )\n\n        def b(i, j, k):\n            return [i + j, j + k, k + 1]\n\n        r = tf.while_loop(c, b, loop_vars=[i, j, k])\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\n@pytest.mark.skip\ndef test_loop_bodies():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def body(x):\n            a = tf.constant(np.array([[5, 6], [7, 8]]), dtype=tf.int32)\n            b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)\n            c = a + b\n            return tf.nn.relu(x + c)\n\n        def condition(x):\n            return tf.reduce_sum(x) < 100\n\n        x = tf.constant(0, shape=[2, 2])\n        r = tf.while_loop(condition, body, [x])\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_nested_loop():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def body(x):\n            def nest_body(c):\n                return tf.multiply(c, 2)\n\n            def cd(c):\n                return tf.less(c, 10)\n\n            c = tf.constant(2)\n            res = tf.while_loop(cd, nest_body, loop_vars=[c])\n            return tf.nn.relu(x + res)\n\n        def condition(x):\n            return tf.greater(x, 100)\n\n        x = tf.constant(3)\n        r = tf.while_loop(condition, body, loop_vars=[x])\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_vanilla_cond():\n    graph = tf.Graph()\n    with graph.as_default():\n        i = tf.constant(1)\n        j = tf.constant(4)\n\n        def f1():\n            return tf.multiply(1, 17)\n\n        def f2():\n            return tf.add(4, 23)\n\n        r = tf.cond(tf.less(i, j), f1, f2)\n\n    with tf.Session(graph=graph) as sess:\n        tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_multiple_cond_vars():\n    graph = tf.Graph()\n    with graph.as_default():\n        x1 = tf.constant(7)\n        x2 = tf.constant(12)\n        z = tf.constant(20)\n        r = tf.cond(tf.less(tf.add(x1, x2), 10), lambda: tf.add(10, 2), lambda: tf.square(5))\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_cond_fn_parameters():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def fn1(x, y):\n            return tf.multiply(5, 6)\n\n        def fn2(x, y):\n            return tf.add(3, 4)\n\n        i = tf.constant(1)\n        j = tf.constant(2)\n        k = tf.constant(3)\n        r = tf.cond(tf.less(i, j), lambda: fn1(i, k), lambda: fn2(j, k))\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={i: 1, j: 2, k: 3})\n\n    check_equal(graph, tf_out)\n\n\ndef test_nested_cond():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def fn1(a, b):\n            def nest_fn1():\n                return tf.add(1, 2)\n\n            def nest_fn2():\n                return tf.subtract(10, 5)\n\n            res = tf.cond(tf.less(1, 2), nest_fn1, nest_fn2)\n            return tf.multiply(tf.add(87, res), 10)\n\n        def fn2(a, b):\n            return tf.add(10, 10)\n\n        x = tf.constant(5)\n        y = tf.constant(6)\n        z = tf.constant(7)\n        pred = tf.less(x, y)\n        r = tf.cond(pred, lambda: fn1(x, y), lambda: fn2(y, z))\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={x: 1, y: 2, z: 3, pred: True})\n\n    check_equal(graph, tf_out)\n\n\ndef test_loop_in_cond():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def fn1(a, b):\n            i = tf.constant(0)\n\n            def cd(i):\n                return tf.less(i, 10)\n\n            def bd(i):\n                return tf.add(i, 1)\n\n            res = tf.while_loop(cd, bd, [i])\n            return tf.multiply(tf.add(20, res), 10)\n\n        def fn2(a, b):\n            return tf.add(10, 20)\n\n        x = tf.constant(7)\n        y = tf.constant(20)\n        z = tf.constant(10)\n        pred = tf.less(x, y)\n        r = tf.cond(pred, lambda: fn1(x, y), lambda: fn2(y, z))\n\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={x: 1, y: 2, z: 3, pred: True})\n\n    check_equal(graph, tf_out)\n\n\ndef test_cond_in_loop():\n    graph = tf.Graph()\n    with graph.as_default():\n\n        def body(x):\n            x = tf.constant(7)\n            z = tf.constant(20)\n            res = tf.cond(tf.less(x, 10), lambda: tf.add(10, 20), lambda: tf.square(10))\n            return tf.multiply(res, x)\n\n        x = tf.constant(21)\n\n        def condition(x):\n            return tf.less(x, 100)\n\n        r = tf.while_loop(condition, body, loop_vars=[x])\n        with tf.Session() as sess:\n            tf_out = sess.run(r)\n\n    check_equal(graph, tf_out)\n\n\ndef test_vanilla_loop_bound():\n    graph = tf.Graph()\n    with graph.as_default():\n        dshape = (2, 10)\n        dtype = \"float32\"\n        dname = \"data\"\n        np_data = np.random.uniform(size=dshape).astype(dtype)\n        data = tf.placeholder(shape=dshape, dtype=dtype, name=dname)\n        x = tf.slice(data, [1, 4], [1, 4])\n        outer = x + 5.0\n\n        def body(x, y):\n            res = tf.cond(tf.less(y, 10), lambda: tf.add(10.0, 20.0), lambda: tf.square(10.0))\n            z = tf.constant(7)\n            res = tf.cond(tf.less(z, 10), lambda: res * 5, lambda: res + 10)\n            return tf.multiply(res, x * outer), y + 1\n\n        y = tf.constant(0)\n\n        def condition(x, y):\n            return tf.less(y, 20)\n\n        r = tf.while_loop(condition, body, loop_vars=[x, y])\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={\"%s:0\" % dname: np_data})\n\n    check_equal(graph, tf_out, {dname: np_data})\n\n\ndef test_nested_loop_bound():\n    graph = tf.Graph()\n    with graph.as_default():\n        dshape = (2, 10)\n        dtype = \"float32\"\n        dname = \"data\"\n        np_data = np.random.uniform(size=dshape).astype(dtype)\n        data = tf.placeholder(shape=dshape, dtype=dtype, name=dname)\n        x = tf.slice(data, [1, 4], [1, 4])\n        outer = x + 5.0\n\n        def body(x, y):\n            res = tf.cond(tf.less(y, 10), lambda: tf.add(10.0, 20.0), lambda: tf.square(10.0))\n\n            def nested_body(nx, ny):\n                return nx + 1, res + 2.0\n\n            def nested_cond(nx, ny):\n                return tf.less(nx, 15)\n\n            nx = tf.constant(0)\n            ny = tf.constant(0.0)\n            nested_res = tf.while_loop(nested_cond, nested_body, loop_vars=[nx, ny])\n            res = res + nested_res[1]\n            z = tf.constant(7)\n            res = tf.cond(tf.less(z, 10), lambda: res * 5, lambda: res + 10)\n            return tf.multiply(res, x * outer), y + 1\n\n        y = tf.constant(0)\n\n        def condition(x, y):\n            return tf.less(y, 20)\n\n        r = tf.while_loop(condition, body, loop_vars=[x, y])\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={\"%s:0\" % dname: np_data})\n\n    check_equal(graph, tf_out, {dname: np_data})\n\n\ndef test_switch():\n    graph = tf.Graph()\n\n    with graph.as_default():\n        data_np = np.random.uniform(0, 5, size=(2, 4, 5, 1)).astype(\"float32\")\n        dname = \"data\"\n        flag_name = \"flag\"\n        data = tf.placeholder(shape=data_np.shape, dtype=data_np.dtype, name=dname)\n        split = tf.split(data, 2, axis=0)\n        flag = tf.placeholder(shape={}, dtype=tf.bool, name=flag_name)\n        output_false, output_true = control_flow_ops.switch(split[1], flag)\n        with tf.Session() as sess:\n            tf_out = sess.run(output_false, feed_dict={data.name: data_np, flag.name: False})\n\n    check_equal(graph, tf_out, {dname: data_np, flag_name: False})\n\n\ndef test_loop_tuple_input():\n    graph = tf.Graph()\n\n    with graph.as_default():\n        data_np = np.random.uniform(0, 5, size=(2, 4, 5, 1)).astype(\"float32\")\n        dname = \"data\"\n        data = tf.placeholder(shape=data_np.shape, dtype=data_np.dtype, name=dname)\n        split = tf.split(data, 2, axis=0)\n\n        def body(x, y):\n            return x + 2, y + 1\n\n        start = tf.constant(0)\n\n        def condition(x, y):\n            return tf.less(y, 20)\n\n        r = tf.while_loop(condition, body, loop_vars=[split[1], start])\n        with tf.Session() as sess:\n            tf_out = sess.run(r, feed_dict={data.name: data_np})\n\n    check_equal(graph, tf_out, {dname: data_np})\n\n\nif __name__ == \"__main__\":\n    # tf.while_loop\n    test_vanilla_loop()\n    test_loop_2_vars()\n    test_loop_3_vars()\n    test_loop_conditions()\n    # TODO(@jroesch): Need to fix memory alloc to support closure\n    # test_loop_bodies()\n    test_callnode_loop_vars()\n\n    # tf.cond\n    test_vanilla_cond()\n    test_multiple_cond_vars()\n    test_cond_fn_parameters()\n\n    # nested cases\n    test_nested_loop()\n    test_nested_cond()\n    test_loop_in_cond()\n    test_cond_in_loop()\n    test_vanilla_loop_bound()\n    test_nested_loop_bound()\n\n    test_switch()\n    test_loop_tuple_input()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow/test_debugging.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for converting TensorFlow debugging ops to Relay.\"\"\"\ntry:\n    import tensorflow.compat.v1 as tf\n\n    tf.disable_v2_behavior()\nexcept ImportError:\n    import tensorflow as tf\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay.frontend.tensorflow import from_tensorflow\n\n\ndef run_relay(graph, shape_dict=None, *vars):\n    mod, params = from_tensorflow(graph.as_graph_def(add_shapes=True), shape=shape_dict)\n    return relay.create_executor(\"debug\", mod=mod).evaluate()(*vars)\n\n\ndef test_assert_true():\n    g = tf.Graph()\n    shape = (1, 2)\n    with g.as_default():\n        x = tf.placeholder(tf.float32, shape=shape, name=\"input\")\n        assert_op = tf.Assert(tf.reduce_all(tf.less_equal(x, x)), [\"it failed\"])\n\n        with tf.Session() as sess:\n            x_value = np.random.rand(*shape)\n            assert sess.run(assert_op, feed_dict={x: x_value}) is None\n\n        # In TVM, tf.assert is converted to a no-op which is actually a 0,\n        # though it should probably be none or an empty tuple.\n        #\n        # ToDo: It appears that the frontend converter gets confused here and\n        # entirely eliminates all operands from main(). Likely because x <= x\n        # is always true, so the placeholder can be eliminated. But TF doesn't\n        # do that, it's happening in Relay, and that optimization shouldn't\n        # affect the arity of the main function. We should have to pass in\n        # x_value here.\n        np.testing.assert_allclose(0, run_relay(g, {\"input\": shape}).numpy())\n\n\ndef test_assert_true_var_capture():\n    g = tf.Graph()\n    with g.as_default():\n        x = tf.placeholder(tf.float32, shape=())\n\n        # It turns out that tf.assert() creates a large and complex subgraph if\n        # you capture a variable as part of the error message. So we need to\n        # test that, too.\n        assert_op = tf.Assert(tf.less_equal(x, x), [\"it failed\", x])\n\n        with tf.Session() as sess:\n            x_value = np.random.rand()\n            assert sess.run(assert_op, feed_dict={x: x_value}) is None\n\n        # TODO: The frontend converter notes the output of\n        # the graph as a boolean, which is not correct - as you can see above,\n        # TF believes that the value of this graph is None.\n        np.testing.assert_allclose(True, run_relay(g, None, x_value).numpy())\n\n\ndef test_assert_false():\n    g = tf.Graph()\n    with g.as_default():\n        assert_op = tf.Assert(tf.constant(False), [\"it failed\"])\n\n        with tf.Session() as sess:\n            try:\n                print(sess.run(assert_op))\n                assert False  # TF should have thrown an exception\n            except tf.errors.InvalidArgumentError as e:\n                assert \"it failed\" in e.message\n\n        # In TVM, tf.assert is converted to a no-op which is actually a 0,\n        # though it should probably be none or an empty tuple. For the same\n        # reason, there should not be an error here, even though the assertion\n        # argument is false.\n        np.testing.assert_allclose(0, run_relay(g).numpy())\n\n\nif __name__ == \"__main__\":\n    test_assert_true()\n    test_assert_true_var_capture()\n    test_assert_false()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument\n\"\"\"\nTensorflow testcases\n====================\nThis article is a test script to test tensorflow operator with Relay.\n\"\"\"\nfrom __future__ import print_function\nfrom distutils.version import LooseVersion\n\nimport threading\nimport platform\nimport os.path\nfrom packaging import version as package_version\nimport numpy as np\nimport pytest\n\nfrom PIL import Image\nfrom tvm import relay\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.relay.frontend.tensorflow import from_tensorflow\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib import utils\n\nimport tvm\nimport tvm.relay.testing.tf as tf_testing\nimport tvm.testing\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import gen_functional_ops\nfrom tensorflow.python.client import device_lib\n\ntry:\n    import tensorflow.compat.v1 as tf\n\n    tf.disable_v2_behavior()\nexcept ImportError:\n    import tensorflow as tf\n\n# Only allow TF to run on half the GPU RAM to save the other half\n# For TVM\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\ngpu_sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\ngpu_sess.close()\n\n\n#######################################################################\n# Generic run functions for TVM & tensorflow\n# ------------------------------------------\n\n\ndef convert_to_list(x):\n    if not isinstance(x, list):\n        x = [x]\n    return x\n\n\ntf_dtypes = {\n    \"float32\": tf.float32,\n    \"float16\": tf.float16,\n    \"float64\": tf.float64,\n    \"int32\": tf.int32,\n    \"uint8\": tf.uint8,\n    \"int8\": tf.int8,\n    \"int16\": tf.int16,\n    \"uint16\": tf.uint16,\n    \"int64\": tf.int64,\n}\n\n\ndef vmobj_to_list(o):\n    \"\"\"Converts TVM objects returned by VM execution to Python List.\"\"\"\n    if isinstance(o, tvm.nd.NDArray):\n        return [o.numpy()]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(f))\n        return result\n    elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):\n        if o.constructor.name_hint == \"Cons\":\n            tl = vmobj_to_list(o.fields[1])\n            hd = vmobj_to_list(o.fields[0])\n            hd.extend(tl)\n            return hd\n        elif o.constructor.name_hint == \"Nil\":\n            return []\n        elif \"tensor_nil\" in o.constructor.name_hint:\n            return [0]\n        elif \"tensor\" in o.constructor.name_hint:\n            return [o.fields[0].numpy()]\n        else:\n            raise RuntimeError(f\"Unknown object type: {o.constructor.name_hint}\")\n    else:\n        raise RuntimeError(f\"Unknown object type: {type(o)}\")\n\n\ndef run_tvm_graph(\n    graph_def,\n    input_data,\n    input_node,\n    num_output=1,\n    target=\"llvm\",\n    out_names=None,\n    opt_level=3,\n    mode=\"graph_executor\",\n    cuda_layout=\"NCHW\",\n    layout=None,\n    disabled_pass=None,\n    ignore_in_shape=False,\n    serialize=False,\n    convert_config=None,\n):\n    \"\"\"Generic function to compile on relay and execute on tvm\"\"\"\n    input_data = convert_to_list(input_data)\n    input_node = convert_to_list(input_node)\n    if target == \"cuda\":\n        layout = cuda_layout\n    target_host = None\n    if ignore_in_shape:\n        shape_dict = None\n    else:\n        shape_dict = {\n            e: i.shape if hasattr(i, \"shape\") else () for e, i in zip(input_node, input_data)\n        }\n    mod, params = relay.frontend.from_tensorflow(\n        graph_def,\n        layout=layout,\n        shape=shape_dict,\n        outputs=out_names,\n        convert_config=convert_config,\n    )\n\n    dev = tvm.device(target, 0)\n    if mode == \"debug\":\n        inputs = []\n        for param in mod[\"main\"].params:\n            found = False\n            for i, n in enumerate(input_node):\n                if n == param.name_hint:\n                    found = True\n                    inputs.append(tvm.nd.array(input_data[i]))\n                    break\n            # Interpreter doesn't bind constants, so still need to find in params\n            if not found:\n                inputs.append(tvm.nd.array(params[param.name_hint]))\n        result = relay.create_executor(mode, mod=mod, device=tvm.cpu(), target=\"llvm\").evaluate()(\n            *inputs\n        )\n        return vmobj_to_list(result)\n    elif mode == \"vm\":\n        with tvm.transform.PassContext(opt_level=opt_level, disabled_pass=disabled_pass):\n            mod = relay.transform.InferType()(mod)\n            vm_exec = relay.vm.compile(mod, target=\"llvm\", params=params)\n        if serialize:\n            code, lib = vm_exec.save()\n            vm_exec = tvm.runtime.vm.Executable.load_exec(code, lib)\n        vm = VirtualMachine(vm_exec, tvm.cpu())\n        inputs = {}\n        for e, i in zip(input_node, input_data):\n            inputs[e] = tvm.nd.array(i)\n        result = vm.invoke(\"main\", **inputs)\n        return vmobj_to_list(result)\n    else:\n        with tvm.transform.PassContext(opt_level=opt_level, disabled_pass=disabled_pass):\n            target = tvm.target.Target(target, target_host)\n            graph, lib, params = relay.build(mod, target=target, params=params)\n\n        m = graph_executor.create(graph, lib, dev)\n        # set inputs\n        for e, i in zip(input_node, input_data):\n            if e != \"\":\n                m.set_input(e, tvm.nd.array(i))\n\n        m.set_input(**params)\n        # execute\n        m.run()\n        # get outputs\n        assert out_names is None or num_output == len(\n            out_names\n        ), f\"out_names: {out_names} num_output: {num_output}\"\n        tvm_output_list = [m.get_output(i).numpy() for i in range(num_output)]\n        return tvm_output_list\n\n\ndef run_tf_graph(sess, input_data, input_node, output_node):\n    \"\"\"Generic function to execute tensorflow\"\"\"\n    input_data = convert_to_list(input_data)\n    input_node = convert_to_list(input_node)\n    output_node = convert_to_list(output_node)\n\n    tensor = [sess.graph.get_tensor_by_name(output_name) for output_name in output_node]\n\n    input_dict = {e: input_data[i] for i, e in enumerate(input_node)}\n    if len(input_node) == 1 and input_node[0] == \"\":\n        output_data = sess.run(tensor)\n    else:\n        output_data = sess.run(tensor, input_dict)\n    return output_data\n\n\ndef compare_tf_with_tvm(\n    in_data,\n    in_name,\n    out_name,\n    init_global_variables=False,\n    no_gpu=False,\n    opt_level=3,\n    mode=\"graph_executor\",\n    cuda_layout=\"NCHW\",\n    add_shapes_to_graph_def=True,\n    targets=None,\n    ignore_in_shape=False,\n    convert_config=None,\n):\n    \"\"\"Generic function to generate and compare tensorflow and TVM output\"\"\"\n\n    def name_without_num(name):\n        return name.split(\":\")[0] if \":\" in name else name\n\n    out_name = convert_to_list(out_name)\n    out_node = [name_without_num(name) for name in out_name]\n\n    in_data = convert_to_list(in_data)\n    in_name = convert_to_list(in_name)\n    in_node = [name_without_num(name) for name in in_name]\n    with tf.Session() as sess:\n        if init_global_variables:\n            sess.run(variables.global_variables_initializer())\n        final_graph_def = (\n            tf_testing.AddShapesToGraphDef(sess, out_node)\n            if add_shapes_to_graph_def\n            else tf.get_default_graph().as_graph_def()\n        )\n\n        tf_output = run_tf_graph(sess, in_data, in_name, out_name)\n\n        devices = targets if targets else [\"llvm\", \"cuda\"]\n\n        for device in devices:\n            _ = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(f\"Skip because {device} is not enabled\")\n                continue\n            if no_gpu and device == \"cuda\":\n                continue\n            if \"cublas\" in device and not tvm.get_global_func(\"tvm.contrib.cublas.matmul\", True):\n                print(f\"Skip because cublas is not enabled: {device}\")\n                continue\n\n            tvm_output = run_tvm_graph(\n                final_graph_def,\n                in_data,\n                in_node,\n                target=device,\n                out_names=out_name,\n                num_output=len(out_name),\n                opt_level=opt_level,\n                mode=mode,\n                cuda_layout=cuda_layout,\n                ignore_in_shape=ignore_in_shape,\n                convert_config=convert_config,\n            )\n            # since the names from tensorflow and relay runs are not exactly same,\n            # first len(tf_output) will be compared\n            for i, tf_out in enumerate(tf_output):\n                if not isinstance(tf_out, np.ndarray):\n                    assert len(tvm_output[i].shape) == 0  # pylint: disable=len-as-condition\n                tvm.testing.assert_allclose(tf_out, tvm_output[i], atol=1e-5, rtol=1e-5)\n\n        sess.close()\n\n\ndef is_gpu_available():\n    \"\"\"Verify gpu is available\"\"\"\n    local_device_protos = device_lib.list_local_devices()\n    gpu_list = [x.name for x in local_device_protos if x.device_type == \"GPU\"]\n    if gpu_list:\n        print(\"Tensorflow GPU:\", gpu_list)\n        return True\n    else:\n        return False\n\n\n#######################################################################\n# Pooling\n# -------\n\n\ndef _test_pooling_iteration(input_shape, **kwargs):\n    \"\"\"One iteration of pool operation with given shapes and attributes\"\"\"\n\n    x = -np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=\"float32\")\n        nn_ops.pool(in_data, **kwargs)\n\n        if kwargs[\"pooling_type\"] == \"MAX\":\n            out_name = \"max_pool:0\"\n        else:\n            out_name = \"avg_pool:0\"\n\n        compare_tf_with_tvm(x, \"Placeholder:0\", out_name)\n\n\ndef _test_pooling(input_shape, **kwargs):\n    _test_pooling_iteration(input_shape, **kwargs)\n\n    if is_gpu_available():\n        if len(input_shape) == 4:\n            input_shape = [input_shape[ii] for ii in (0, 3, 1, 2)]\n            if isinstance(kwargs[\"padding\"], list):\n                kwargs[\"padding\"] = [kwargs[\"padding\"][ii] for ii in (0, 3, 1, 2)]\n            kwargs[\"data_format\"] = \"NCHW\"\n            _test_pooling_iteration(input_shape, **kwargs)\n\n\ndef _test_pooling_dynamic(input_shape, np_shape, **kwargs):\n    \"\"\"Pooling with dynamic height and width dimensions.\"\"\"\n    x = -np.arange(np.prod(np_shape), dtype=np.float32).reshape(np_shape) - 1\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=\"float32\")\n        nn_ops.pool(in_data, **kwargs)\n\n        if kwargs[\"pooling_type\"] == \"MAX\":\n            out_name = \"max_pool:0\"\n        else:\n            out_name = \"avg_pool:0\"\n\n        compare_tf_with_tvm(x, \"Placeholder:0\", out_name, mode=\"vm\", ignore_in_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_forward_pooling():\n    \"\"\"Pooling\"\"\"\n    # TensorFlow only supports NDHWC for max_pool3d on CPU\n    for pool_type in [\"AVG\", \"MAX\"]:\n        # NDHWC is the default layout for max_pool3d and avg_pool3d in TensorFlow\n        _test_pooling(\n            input_shape=[1, 3, 32, 32, 32],\n            window_shape=[2, 2, 2],\n            padding=\"VALID\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1, 1],\n            strides=[2, 2, 2],\n        )\n\n        _test_pooling(\n            input_shape=[1, 3, 32, 32, 32],\n            window_shape=[1, 1, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1, 1],\n            strides=[1, 1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[1, 3, 32, 32, 32],\n            window_shape=[2, 2, 2],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1, 1],\n            strides=[2, 2, 2],\n        )\n\n        _test_pooling_dynamic(\n            input_shape=[1, None, None, 3],\n            np_shape=[1, 32, 32, 3],\n            window_shape=[2, 2],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        # test cases for max_pool3d & avg_pool3d with layout NCDHW\n        # TensorFlow pool3d  doesn't support NCDHW on cpu\n        if is_gpu_available():\n            _test_pooling(\n                input_shape=[1, 3, 32, 32, 32],\n                window_shape=[1, 1, 1],\n                padding=\"SAME\",\n                pooling_type=pool_type,\n                dilation_rate=[1, 1, 1],\n                strides=[1, 1, 1],\n                data_format=\"NCDHW\",\n            )\n\n            _test_pooling(\n                input_shape=[1, 3, 32, 32, 32],\n                window_shape=[2, 2, 2],\n                padding=\"VALID\",\n                pooling_type=pool_type,\n                dilation_rate=[1, 1, 1],\n                strides=[2, 2, 2],\n                data_format=\"NCDHW\",\n            )\n\n        _test_pooling(\n            input_shape=[2, 9, 10, 2],\n            window_shape=[1, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 10, 9, 2],\n            window_shape=[1, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 9, 10, 2],\n            window_shape=[2, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 10, 9, 2],\n            window_shape=[2, 3],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[2, 1],\n        )\n\n        # Tests involving SpaceToBatchND\n        _test_pooling(\n            input_shape=[1, 1, 2, 1],\n            window_shape=[1, 1],\n            padding=\"VALID\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 2],\n        )\n\n        _test_pooling(\n            input_shape=[1, 2, 1],\n            window_shape=[1],\n            padding=\"VALID\",\n            pooling_type=pool_type,\n            dilation_rate=[2],\n        )\n    # Explicit padding\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.4.1\"):\n        _test_pooling(\n            input_shape=[2, 9, 10, 2],\n            window_shape=[4, 4],\n            padding=[[0, 0], [0, 1], [2, 3], [0, 0]],\n            pooling_type=\"MAX\",\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n\n#######################################################################\n# Convolution\n# -----------\n\n\ndef _test_convolution(\n    opname,\n    tensor_in_sizes,\n    filter_in_sizes,\n    dilations,\n    strides,\n    padding,\n    data_format,\n    deconv_output_shape=None,\n    add_shapes_to_graph_def=True,\n):\n    \"\"\"One iteration of convolution with given shapes and attributes\"\"\"\n    deconv_output_shape = deconv_output_shape or []\n    total_size_1 = np.prod(tensor_in_sizes)\n    total_size_2 = np.prod(filter_in_sizes)\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n    filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\")\n        in_filter = constant_op.constant(filter_array, shape=filter_in_sizes, dtype=\"float32\")\n        if data_format == \"NHWC\":\n            strides = [1] + strides + [1]\n            dilations = [1] + dilations + [1]\n        else:\n            strides = [1, 1] + strides\n            dilations = [1, 1] + dilations\n\n        if opname == \"conv\":\n            nn_ops.conv2d(\n                in_data,\n                in_filter,\n                strides=strides,\n                dilations=dilations,\n                padding=padding,\n                data_format=data_format,\n            )\n\n            compare_tf_with_tvm(\n                np.reshape(data_array, tensor_in_sizes).astype(\"float32\"),\n                \"Placeholder:0\",\n                \"Conv2D:0\",\n                add_shapes_to_graph_def=add_shapes_to_graph_def,\n            )\n        elif opname == \"conv_transpose\":\n            nn_ops.conv2d_transpose(\n                in_data,\n                in_filter,\n                output_shape=deconv_output_shape,\n                strides=strides,\n                padding=padding,\n                data_format=data_format,\n            )\n\n            compare_tf_with_tvm(\n                np.reshape(data_array, tensor_in_sizes).astype(\"float32\"),\n                \"Placeholder:0\",\n                \"conv2d_transpose:0\",\n                add_shapes_to_graph_def=add_shapes_to_graph_def,\n            )\n        else:\n            nn_ops.depthwise_conv2d_native(\n                in_data,\n                in_filter,\n                strides=strides,\n                dilations=dilations,\n                padding=padding,\n                data_format=data_format,\n            )\n\n            compare_tf_with_tvm(\n                np.reshape(data_array, tensor_in_sizes).astype(\"float32\"),\n                \"Placeholder:0\",\n                \"DepthwiseConv2dNative:0\",\n                add_shapes_to_graph_def=add_shapes_to_graph_def,\n            )\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/10275\")\n@tvm.testing.uses_gpu\ndef test_forward_convolution():\n    \"\"\"Convolution\"\"\"\n    if is_gpu_available():\n        _test_convolution(\"conv\", [4, 176, 8, 8], [1, 1, 176, 32], [1, 1], [1, 1], \"SAME\", \"NCHW\")\n        _test_convolution(\"conv\", [4, 19, 17, 17], [3, 3, 19, 19], [1, 1], [2, 2], \"VALID\", \"NCHW\")\n        _test_convolution(\"conv\", [4, 124, 17, 17], [1, 1, 124, 19], [1, 1], [1, 1], \"SAME\", \"NCHW\")\n        _test_convolution(\"conv\", [4, 12, 17, 17], [3, 3, 12, 32], [1, 1], [2, 2], \"VALID\", \"NCHW\")\n        _test_convolution(\n            \"depthwise\", [4, 176, 8, 8], [1, 1, 176, 1], [1, 1], [1, 1], \"SAME\", \"NCHW\"\n        )\n        _test_convolution(\n            \"depthwise\", [4, 19, 17, 17], [3, 3, 19, 1], [1, 1], [2, 2], \"VALID\", \"NCHW\"\n        )\n        _test_convolution(\n            \"depthwise\", [4, 124, 17, 17], [1, 1, 124, 1], [1, 1], [1, 1], \"SAME\", \"NCHW\"\n        )\n        _test_convolution(\n            \"depthwise\", [4, 12, 17, 17], [3, 3, 12, 1], [1, 1], [2, 2], \"VALID\", \"NCHW\"\n        )\n        _test_convolution(\n            \"depthwise\", [4, 12, 17, 17], [3, 3, 12, 2], [1, 1], [2, 2], \"VALID\", \"NCHW\"\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [1, 1, 176, 32],\n            [1, 1],\n            [1, 1],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 8, 8],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [2, 2, 176, 32],\n            [1, 1],\n            [1, 1],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 8, 8],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [2, 2, 176, 32],\n            [1, 1],\n            [2, 2],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 15, 15],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [3, 3, 176, 32],\n            [1, 1],\n            [1, 1],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 8, 8],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [3, 3, 176, 32],\n            [1, 1],\n            [2, 2],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 15, 15],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [3, 3, 176, 32],\n            [1, 1],\n            [2, 2],\n            \"SAME\",\n            \"NCHW\",\n            [4, 176, 16, 16],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 19, 8, 8],\n            [3, 3, 19, 19],\n            [1, 1],\n            [2, 2],\n            \"VALID\",\n            \"NCHW\",\n            [4, 19, 17, 17],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 19, 17, 17],\n            [1, 1, 124, 19],\n            [1, 1],\n            [1, 1],\n            \"SAME\",\n            \"NCHW\",\n            [4, 124, 17, 17],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 19, 17, 17],\n            [3, 3, 124, 19],\n            [1, 1],\n            [1, 1],\n            \"SAME\",\n            \"NCHW\",\n            [4, 124, 17, 17],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [3, 3, 12, 32],\n            [1, 1],\n            [2, 2],\n            \"VALID\",\n            \"NCHW\",\n            [4, 12, 17, 17],\n        )\n        # kernel 2x2, strides (2,2)\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 19, 8, 8],\n            [2, 2, 19, 19],\n            [1, 1],\n            [2, 2],\n            \"VALID\",\n            \"NCHW\",\n            [4, 19, 16, 16],\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 32, 8, 8],\n            [2, 2, 12, 32],\n            [1, 1],\n            [2, 2],\n            \"VALID\",\n            \"NCHW\",\n            [4, 12, 16, 16],\n        )\n        # output channel is 1\n        _test_convolution(\n            \"conv_transpose\",\n            [1, 19, 8, 8],\n            [1, 1, 1, 19],\n            [1, 1],\n            [1, 1],\n            \"VALID\",\n            \"NCHW\",\n            [1, 1, 8, 8],\n        )\n\n    _test_convolution(\"conv\", [4, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], \"SAME\", \"NHWC\")\n    _test_convolution(\"conv\", [4, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], \"VALID\", \"NHWC\")\n    _test_convolution(\"conv\", [4, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], \"SAME\", \"NHWC\")\n    _test_convolution(\"conv\", [4, 17, 17, 12], [3, 3, 12, 32], [1, 1], [2, 2], \"VALID\", \"NHWC\")\n    _test_convolution(\n        \"conv\",\n        [4, 17, 17, 12],\n        [3, 3, 12, 32],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        add_shapes_to_graph_def=False,\n    )\n    _test_convolution(\"depthwise\", [4, 8, 8, 176], [1, 1, 176, 1], [1, 1], [1, 1], \"SAME\", \"NHWC\")\n    _test_convolution(\"depthwise\", [4, 17, 17, 19], [3, 3, 19, 1], [1, 1], [2, 2], \"VALID\", \"NHWC\")\n    _test_convolution(\"depthwise\", [4, 17, 17, 124], [1, 1, 124, 1], [1, 1], [1, 1], \"SAME\", \"NHWC\")\n    _test_convolution(\"depthwise\", [4, 17, 17, 12], [3, 3, 12, 1], [1, 1], [2, 2], \"VALID\", \"NHWC\")\n    _test_convolution(\"depthwise\", [4, 17, 17, 12], [3, 3, 12, 2], [1, 1], [2, 2], \"VALID\", \"NHWC\")\n    _test_convolution(\n        \"depthwise\",\n        [4, 17, 17, 12],\n        [3, 3, 12, 2],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        add_shapes_to_graph_def=False,\n    )\n\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [1, 1, 176, 32],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 8, 8, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [2, 2, 176, 32],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 8, 8, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [2, 2, 176, 32],\n        [1, 1],\n        [2, 2],\n        \"SAME\",\n        \"NHWC\",\n        [4, 15, 15, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [3, 3, 176, 32],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 8, 8, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [3, 3, 176, 32],\n        [1, 1],\n        [2, 2],\n        \"SAME\",\n        \"NHWC\",\n        [4, 15, 15, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [3, 3, 176, 32],\n        [1, 1],\n        [2, 2],\n        \"SAME\",\n        \"NHWC\",\n        [4, 16, 16, 176],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 19],\n        [3, 3, 19, 19],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        [4, 17, 17, 19],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 17, 17, 19],\n        [1, 1, 124, 19],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 17, 17, 124],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 17, 17, 19],\n        [3, 3, 124, 19],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 17, 17, 124],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [3, 3, 12, 32],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        [4, 17, 17, 12],\n    )\n    # kernel 2x2, strides (2,2)\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 19],\n        [2, 2, 19, 19],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        [4, 16, 16, 19],\n    )\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [2, 2, 12, 32],\n        [1, 1],\n        [2, 2],\n        \"VALID\",\n        \"NHWC\",\n        [4, 16, 16, 12],\n    )\n    # output channel is 1\n    _test_convolution(\n        \"conv_transpose\",\n        [1, 8, 8, 19],\n        [1, 1, 1, 19],\n        [1, 1],\n        [1, 1],\n        \"VALID\",\n        \"NHWC\",\n        [1, 8, 8, 1],\n    )\n    # Test without adding shapes to graph def\n    _test_convolution(\n        \"conv_transpose\",\n        [4, 8, 8, 32],\n        [1, 1, 176, 32],\n        [1, 1],\n        [1, 1],\n        \"SAME\",\n        \"NHWC\",\n        [4, 8, 8, 176],\n        add_shapes_to_graph_def=False,\n    )\n    # Explicit padding\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.4.1\"):\n        _test_convolution(\n            \"conv\",\n            [4, 8, 8, 16],\n            [1, 1, 16, 32],\n            [1, 1],\n            [1, 1],\n            [[0, 0], [2, 3], [0, 1], [0, 0]],\n            \"NHWC\",\n        )\n        _test_convolution(\n            \"depthwise\",\n            [4, 8, 8, 16],\n            [1, 1, 16, 1],\n            [1, 1],\n            [1, 1],\n            [[0, 0], [2, 3], [0, 1], [0, 0]],\n            \"NHWC\",\n        )\n        _test_convolution(\n            \"conv_transpose\",\n            [4, 8, 8, 32],\n            [3, 3, 176, 32],\n            [1, 1],\n            [2, 2],\n            [[0, 0], [1, 0], [1, 0], [0, 0]],\n            \"NHWC\",\n            [4, 16, 16, 176],\n        )\n\n\n#######################################################################\n# Convolution3D\n# -------------\n\n\ndef _test_convolution3d(\n    opname,\n    tensor_in_sizes,\n    filter_in_sizes,\n    dilations,\n    strides,\n    padding,\n    data_format,\n    deconv_output_shape=None,\n    add_shapes_to_graph_def=True,\n):\n    \"\"\"One iteration of 3D convolution with given shapes and attributes\"\"\"\n    deconv_output_shape = deconv_output_shape or []\n    total_size_1 = np.prod(tensor_in_sizes)\n    total_size_2 = np.prod(filter_in_sizes)\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n    filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\")\n        in_filter = constant_op.constant(filter_array, shape=filter_in_sizes, dtype=\"float32\")\n        if data_format == \"NDHWC\":\n            strides = [1] + strides + [1]\n            dilations = [1] + dilations + [1]\n        else:\n            strides = [1, 1] + strides\n            dilations = [1, 1] + dilations\n\n        if opname == \"conv\":\n            nn_ops.conv3d(\n                in_data,\n                in_filter,\n                strides=strides,\n                dilations=dilations,\n                padding=padding,\n                data_format=data_format,\n            )\n\n            compare_tf_with_tvm(\n                np.reshape(data_array, tensor_in_sizes).astype(\"float32\"),\n                \"Placeholder:0\",\n                \"Conv3D:0\",\n                cuda_layout=\"NCDHW\",\n                add_shapes_to_graph_def=add_shapes_to_graph_def,\n            )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_convolution3d():\n    \"\"\"Convolution3d\"\"\"\n    if is_gpu_available():\n        _test_convolution3d(\n            \"conv\", [4, 176, 8, 8, 8], [1, 1, 1, 176, 32], [1, 1, 1], [1, 1, 1], \"SAME\", \"NCDHW\"\n        )\n        _test_convolution3d(\n            \"conv\", [4, 19, 17, 17, 17], [3, 3, 3, 19, 19], [1, 1, 1], [2, 2, 2], \"VALID\", \"NCDHW\"\n        )\n        _test_convolution3d(\n            \"conv\", [4, 124, 17, 17, 17], [1, 1, 1, 124, 19], [1, 1, 1], [1, 1, 1], \"SAME\", \"NCDHW\"\n        )\n        _test_convolution3d(\n            \"conv\", [4, 12, 17, 17, 17], [3, 3, 3, 12, 32], [1, 1, 1], [2, 2, 2], \"VALID\", \"NCDHW\"\n        )\n    _test_convolution3d(\n        \"conv\", [4, 8, 8, 8, 176], [1, 1, 1, 176, 32], [1, 1, 1], [1, 1, 1], \"SAME\", \"NDHWC\"\n    )\n    _test_convolution3d(\n        \"conv\", [4, 17, 17, 17, 19], [3, 3, 3, 19, 19], [1, 1, 1], [2, 2, 2], \"VALID\", \"NDHWC\"\n    )\n    _test_convolution3d(\n        \"conv\", [4, 17, 17, 17, 124], [1, 1, 1, 124, 19], [1, 1, 1], [1, 1, 1], \"SAME\", \"NDHWC\"\n    )\n    _test_convolution3d(\n        \"conv\", [4, 17, 17, 17, 12], [3, 3, 3, 12, 32], [1, 1, 1], [2, 2, 2], \"VALID\", \"NDHWC\"\n    )\n    # Test without adding shapes to graph def\n    _test_convolution3d(\n        \"conv\",\n        [4, 17, 17, 17, 12],\n        [3, 3, 3, 12, 32],\n        [1, 1, 1],\n        [2, 2, 2],\n        \"VALID\",\n        \"NDHWC\",\n        add_shapes_to_graph_def=False,\n    )\n\n\n#######################################################################\n# Convolution3D Transpose\n# -----------------------\n\n\ndef _test_convolution3d_transpose(\n    data_shape,\n    filter_shape,\n    strides,\n    padding,\n    output_shape,\n    data_format=\"NCDHW\",\n    add_shapes_to_graph_def=True,\n):\n    \"\"\"One iteration of 3D convolution transpose with given shapes and attributes\"\"\"\n\n    dtype = \"float32\"\n    data_array = np.random.uniform(size=data_shape).astype(dtype)\n    filter_array = np.random.uniform(size=filter_shape).astype(dtype)\n    if data_format == \"NDHWC\":\n        strides = [1] + strides + [1]\n    else:\n        strides = [1, 1] + strides\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data_shape, dtype=dtype)\n        in_filter = constant_op.constant(filter_array, shape=filter_shape, dtype=dtype)\n\n        nn_ops.conv3d_transpose(\n            in_data,\n            in_filter,\n            output_shape=output_shape,\n            strides=strides,\n            padding=padding,\n            data_format=data_format,\n        )\n\n        compare_tf_with_tvm(\n            data_array,\n            \"Placeholder:0\",\n            \"conv3d_transpose:0\",\n            cuda_layout=\"NDHWC\",\n            add_shapes_to_graph_def=add_shapes_to_graph_def,\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_convolution3d_transpose():\n    \"\"\"Convolution3d transpose\"\"\"\n    if is_gpu_available():\n        _test_convolution3d_transpose(\n            data_shape=[1, 10, 8, 8, 8],\n            filter_shape=[1, 1, 1, 6, 10],\n            strides=[1, 1, 1],\n            padding=\"VALID\",\n            output_shape=[1, 6, 8, 8, 8],\n        )\n\n        _test_convolution3d_transpose(\n            data_shape=[4, 9, 8, 8, 8],\n            filter_shape=[1, 1, 1, 6, 9],\n            strides=[1, 1, 1],\n            padding=\"VALID\",\n            output_shape=[4, 6, 8, 8, 8],\n        )\n\n        _test_convolution3d_transpose(\n            data_shape=[1, 3, 8, 8, 8],\n            filter_shape=[1, 1, 1, 6, 3],\n            strides=[2, 2, 2],\n            padding=\"SAME\",\n            output_shape=[1, 6, 15, 15, 15],\n        )\n\n        _test_convolution3d_transpose(\n            data_shape=[1, 16, 8, 8, 8],\n            filter_shape=[3, 3, 3, 6, 16],\n            strides=[3, 3, 3],\n            padding=\"VALID\",\n            output_shape=[1, 6, 24, 24, 24],\n        )\n\n    _test_convolution3d_transpose(\n        data_shape=[1, 8, 8, 8, 10],\n        filter_shape=[1, 1, 1, 6, 10],\n        strides=[1, 1, 1],\n        padding=\"VALID\",\n        output_shape=[1, 8, 8, 8, 6],\n        data_format=\"NDHWC\",\n    )\n\n    _test_convolution3d_transpose(\n        data_shape=[4, 8, 8, 8, 9],\n        filter_shape=[1, 1, 1, 6, 9],\n        strides=[1, 1, 1],\n        padding=\"VALID\",\n        output_shape=[4, 8, 8, 8, 6],\n        data_format=\"NDHWC\",\n    )\n\n    _test_convolution3d_transpose(\n        data_shape=[1, 8, 8, 8, 3],\n        filter_shape=[1, 1, 1, 6, 3],\n        strides=[2, 2, 2],\n        padding=\"SAME\",\n        output_shape=[1, 15, 15, 15, 6],\n        data_format=\"NDHWC\",\n    )\n\n    _test_convolution3d_transpose(\n        data_shape=[1, 8, 8, 8, 16],\n        filter_shape=[3, 3, 3, 6, 16],\n        strides=[3, 3, 3],\n        padding=\"VALID\",\n        output_shape=[1, 24, 24, 24, 6],\n        data_format=\"NDHWC\",\n    )\n\n    # Test without adding shapes to graph def\n    _test_convolution3d_transpose(\n        data_shape=[1, 8, 8, 8, 16],\n        filter_shape=[3, 3, 3, 6, 16],\n        strides=[3, 3, 3],\n        padding=\"VALID\",\n        output_shape=[1, 24, 24, 24, 6],\n        data_format=\"NDHWC\",\n        add_shapes_to_graph_def=False,\n    )\n\n\n#######################################################################\n# BiasAdd\n# -----------\n\n\ndef _test_biasadd(tensor_in_sizes, data_format):\n    \"\"\"One iteration of biasadd with given shapes and attributes\"\"\"\n\n    total_size_1 = 1\n    for s in tensor_in_sizes:\n        total_size_1 *= s\n    tensor_bias_sizes = [tensor_in_sizes[1]] if data_format == \"NCHW\" else [tensor_in_sizes[3]]\n    total_size_2 = tensor_bias_sizes[0]\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n    bias_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\")\n        in_bias = constant_op.constant(bias_array, shape=tensor_bias_sizes, dtype=\"float32\")\n        nn_ops.bias_add(in_data, in_bias, data_format=data_format)\n\n        compare_tf_with_tvm(\n            np.reshape(data_array, tensor_in_sizes).astype(\"float32\"), \"Placeholder:0\", \"BiasAdd:0\"\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_forward_biasadd():\n    \"\"\"Bias add\"\"\"\n    if is_gpu_available():\n        _test_biasadd([4, 176, 8, 8], \"NCHW\")\n        _test_biasadd([1, 100, 1, 1], \"NCHW\")\n        _test_biasadd([4, 19, 17, 17], \"NCHW\")\n        _test_biasadd([4, 124, 3, 3], \"NCHW\")\n\n    _test_biasadd([4, 8, 8, 176], \"NHWC\")\n    _test_biasadd([1, 1, 1, 100], \"NHWC\")\n    _test_biasadd([4, 17, 17, 19], \"NHWC\")\n    _test_biasadd([4, 3, 3, 124], \"NHWC\")\n\n\ndef _test_forward_where(input_shape):\n    with tf.Graph().as_default():\n        dtype = tf.float32\n        t = tf.constant(\n            np.random.choice([0, 1, -2, 3, -1, 0.1, -0.2], size=input_shape).astype(dtype.name)\n        )\n        out = tf.where(t)\n        compare_tf_with_tvm([], [], out.name, mode=\"debug\")\n        compare_tf_with_tvm([], [], out.name, mode=\"vm\")\n\n\ndef test_forward_argwhere():\n    _test_forward_where((5,))\n    _test_forward_where((5, 5))\n    _test_forward_where((5, 5, 5))\n    _test_forward_where((5, 5, 5, 5))\n    _test_forward_where((5, 5, 5, 5, 5))\n\n\n#######################################################################\n# SpaceToBatchND\n# --------------\n\n\ndef _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype=\"int32\"):\n    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)\n\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(shape=input_shape, dtype=dtype)\n        out = tf.space_to_batch_nd(in_data, block_shape, paddings)\n\n        compare_tf_with_tvm(data, in_data.name, out.name)\n\n\ndef _test_space_to_batch_nd_infer_paddings(input_shape, block_shape, dtype=\"int32\"):\n    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)\n    padding_np = np.array([0, 1]).astype(np.int32).reshape((1, 2))\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(shape=input_shape, dtype=dtype)\n        const1 = tf.constant(padding_np, dtype=tf.int32)\n        # make paddings an input to tf.transpose, but not an input to the graph,\n        # so it can be extracted with infer_value_simulated\n        paddings = tf.reverse(const1, axis=[-1])\n        out = tf.space_to_batch_nd(in_data, block_shape, paddings)\n        compare_tf_with_tvm(data, in_data.name, out.name)\n\n\ndef test_forward_space_to_batch_nd():\n    \"\"\"SpaceToBatchNd\"\"\"\n    # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/space-to-batch-n-d\n    _test_space_to_batch_nd(input_shape=[1, 2, 2, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(input_shape=[1, 2, 2, 3], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(input_shape=[1, 4, 4, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(\n        input_shape=[2, 2, 4, 1], block_shape=[2, 2], paddings=[[0, 0], [2, 0]], dtype=\"int64\"\n    )\n\n    # pylint: disable=line-too-long\n    # https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/spacetobatch_op_test.py\n    _test_space_to_batch_nd(input_shape=[2, 3], block_shape=[2], paddings=[[1, 0]], dtype=\"float32\")\n\n    _test_space_to_batch_nd(\n        input_shape=[2, 3, 2], block_shape=[2], paddings=[[1, 0]], dtype=\"float64\"\n    )\n\n    _test_space_to_batch_nd_infer_paddings(input_shape=[2, 3, 2], block_shape=[2])\n\n\n#######################################################################\n# BatchToSpaceND\n# --------------\n\n\ndef _test_batch_to_space_nd(input_shape, block_shape, crops, dtype=\"int32\"):\n    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)\n\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(shape=input_shape, dtype=dtype)\n        out = tf.batch_to_space_nd(in_data, block_shape, crops)\n\n        compare_tf_with_tvm(data, in_data.name, out.name)\n\n\ndef test_forward_batch_to_space_nd():\n    \"\"\"BatchToSpaceNd\"\"\"\n    # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d\n    _test_batch_to_space_nd(input_shape=[4, 1, 1, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(input_shape=[4, 1, 1, 3], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(input_shape=[4, 2, 2, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(\n        input_shape=[8, 1, 3, 1], block_shape=[2, 2], crops=[[0, 0], [2, 0]], dtype=\"int64\"\n    )\n\n    # pylint: disable=line-too-long\n    # https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/batchtospace_op_test.py\n    _test_batch_to_space_nd(\n        input_shape=[18, 2, 1, 2], block_shape=[2, 3], crops=[[1, 1], [0, 0]], dtype=\"float32\"\n    )\n\n    _test_batch_to_space_nd(\n        input_shape=[20, 5, 8, 7], block_shape=[2, 2], crops=[[1, 1], [1, 1]], dtype=\"float64\"\n    )\n\n\n#######################################################################\n# Reshape\n# -------\n\n\ndef _test_reshape(data, out_shape):\n    \"\"\"One iteration of reshape operation with given data and out shape\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        array_ops.reshape(in_data, out_shape)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"Reshape:0\")\n\n\ndef _test_reshape_with_call():\n    \"\"\"relay.expr.Call as shape\"\"\"\n    data = np.zeros((6, 4, 2))\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out_shape = tf.constant([1, 2, 3], dtype=\"int32\")\n        out_shape = tf.multiply(out_shape, 2)\n        array_ops.reshape(in_data, out_shape)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"Reshape:0\")\n\n\ndef _test_reshape_like(data, shape_like):\n    \"\"\"A special case for reshape.\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        in_shape_like = array_ops.placeholder(shape=shape_like.shape, dtype=data.dtype)\n        out_shape = array_ops.shape(in_shape_like)\n        array_ops.reshape(in_data, out_shape)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"Reshape:0\")\n\n\ndef _test_reshape_symbolic(data, a_data, b_data):\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        a = array_ops.placeholder(shape=a_data.shape, dtype=a_data.dtype)\n        b = array_ops.placeholder(shape=b_data.shape, dtype=b_data.dtype)\n        newshape = tf.add(a, b)\n        out = array_ops.reshape(in_data, newshape)\n\n        for mode in [\"debug\", \"vm\"]:\n            compare_tf_with_tvm(\n                [data, a_data, b_data], [in_data.name, a.name, b.name], out.name, mode=mode\n            )\n\n\ndef test_forward_reshape():\n    \"\"\"Reshape\"\"\"\n    _test_reshape(np.arange(6.0), [2, 3])\n    _test_reshape(np.arange(6), [-1, 2])\n    _test_reshape(np.arange(6), [3, -1])\n    _test_reshape(np.arange(6), [-1])\n    _test_reshape_with_call()\n    _test_reshape_like(np.zeros((3, 6)), np.zeros((9, 2)))\n    _test_reshape_symbolic(np.arange(6.0), np.array([2, 0]), np.array([0, 3]))\n    _test_reshape_symbolic(np.arange(6), np.array([-1, 0]), np.array([0, 2]))\n    _test_reshape_symbolic(np.arange(6), np.array([3, 0]), np.array([3, -1]))\n    _test_reshape_symbolic(np.arange(6), np.array([0]), np.array([-1]))\n\n\n#######################################################################\n# DepthToSpace\n# ------------\n\n\ndef _test_depthtospace(data, block_size):\n    \"\"\"One iteration of depth_to_space operation with given data and block size\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        array_ops.depth_to_space(in_data, block_size)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"DepthToSpace:0\")\n\n\ndef test_forward_depthtospace():\n    _test_depthtospace(np.random.normal(size=[1, 32, 32, 4]), 2)\n    _test_depthtospace(np.random.normal(size=[1, 16, 8, 32]), 4)\n\n\n#######################################################################\n# SpaceToDepth\n# ------------\n\n\ndef _test_spacetodepth(data, block_size):\n    \"\"\"One iteration of space_to_depth operation with given data and block size\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        array_ops.space_to_depth(in_data, block_size)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"SpaceToDepth:0\")\n\n\ndef test_forward_spacetodepth():\n    _test_spacetodepth(np.random.normal(size=[1, 32, 32, 4]), 2)\n    _test_spacetodepth(np.random.normal(size=[1, 16, 8, 32]), 4)\n\n\n#######################################################################\n# Squeeze\n# -------\n\n\ndef _test_squeeze(data, squeeze_dims=None):\n    \"\"\"One iteration of squeeze\"\"\"\n\n    if squeeze_dims is None:\n        squeeze_dims = []\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n        if squeeze_dims:\n            array_ops.squeeze(in_data, squeeze_dims)\n        else:\n            array_ops.squeeze(in_data)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"Squeeze:0\")\n\n\ndef test_forward_squeeze():\n    \"\"\"Squeeze\"\"\"\n\n    # Nothing to squeeze.\n    _test_squeeze(np.arange(2).reshape((2)))\n    _test_squeeze(np.arange(6).reshape((2, 3)))\n\n    # Squeeze the middle element away.\n    _test_squeeze(np.arange(4).reshape((2, 1, 2)))\n\n    # Squeeze on both ends.\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)))\n\n    # Positive squeeze dim index.\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0])\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [2, 4])\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0, 4, 2])\n\n    # Negative squeeze dim index.\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-1])\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5])\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5, -1])\n\n\n#######################################################################\n# TensorArray\n# -----------\ndef test_tensor_array_write_read():\n    \"\"\"Tensor array write read\"\"\"\n\n    def run(dtype_str, infer_shape, element_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            np_data = np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str)\n            _ = [np_data, np_data]\n            t1 = tf.constant(np_data, dtype=dtype)\n            t2 = tf.constant(np_data, dtype=dtype)\n            ta1 = tf.TensorArray(\n                dtype=dtype, size=2, infer_shape=infer_shape, element_shape=element_shape\n            )\n            ta2 = ta1.write(0, t1)\n            ta3 = ta2.write(1, t2)\n            _ = ta3.read(0)\n            _ = tf.get_default_graph()\n            compare_tf_with_tvm([], [], \"TensorArrayReadV3:0\", mode=\"vm\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, False, None)\n        run(dtype, False, tf.TensorShape([None, 2]))\n        run(dtype, True, None)\n\n\ndef test_tensor_array_scatter():\n    \"\"\"Tensor array scatter\"\"\"\n\n    def run(dtype_str, infer_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            if infer_shape:\n                element_shape = tf.TensorShape([tf.Dimension(None)])\n            else:\n                element_shape = None\n            ta0 = _construct_scatter(dtype, dtype_str, element_shape, infer_shape, 3)\n            _ = ta0.read(0)\n            _ = ta0.read(1)\n            _ = ta0.read(2)\n            ta1 = _construct_scatter(dtype, dtype_str, element_shape, infer_shape, 4)\n            out4 = ta1.read(0)\n            _ = tf.get_default_graph()\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3:0\"], mode=\"vm\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_1:0\"], mode=\"vm\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_2:0\"], mode=\"vm\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_2:0\", out4.name], mode=\"vm\")\n\n    def _construct_scatter(dtype, dtype_str, element_shape, infer_shape, size):\n        arr = [[float(i)] for i in range(size)]  # pylint: disable=unnecessary-comprehension\n        indices_arr = list(range(size - 1, -1, -1))\n\n        t = tf.constant(np.array(arr).astype(dtype_str), dtype=dtype)\n        indices = tf.constant(indices_arr)\n        ta1 = tf.TensorArray(\n            dtype=dtype, size=size, infer_shape=infer_shape, element_shape=element_shape\n        )\n        ta2 = ta1.scatter(indices, t)\n        return ta2\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, False)\n        run(dtype, True)\n\n\ndef test_tensor_array_gather():\n    \"\"\"tensor array gather\"\"\"\n\n    def run(dtype_str, infer_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            t = tf.constant(np.array([[1.0], [2.0], [3.0]]).astype(dtype_str))\n            scatter_indices = tf.constant([2, 1, 0])\n            gather_indices = tf.constant([1, 2])\n            ta1 = tf.TensorArray(dtype=dtype, size=3, infer_shape=infer_shape)\n            ta2 = ta1.scatter(scatter_indices, t)\n            _ = ta2.gather(gather_indices)\n            _ = tf.get_default_graph()\n            compare_tf_with_tvm([], [], [\"TensorArrayGatherV3:0\"], mode=\"vm\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, True)\n\n\ndef test_tensor_array_split():\n    \"\"\"tensor array split\"\"\"\n\n    def run(dtype_str, infer_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            t = tf.constant(\n                np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(\n                    dtype_str\n                ),\n                dtype=dtype,\n            )\n            split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)\n            ta1 = tf.TensorArray(dtype=dtype, size=4, infer_shape=infer_shape)\n            ta2 = ta1.split(t, split_length)\n            _ = ta2.read(0)\n            _ = ta2.read(1)\n            _ = ta2.read(2)\n            _ = ta2.read(3)\n            _ = tf.get_default_graph()\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3:0\"], mode=\"debug\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_1:0\"], mode=\"debug\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_2:0\"], mode=\"debug\")\n            compare_tf_with_tvm([], [], [\"TensorArrayReadV3_3:0\"], mode=\"debug\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, False)\n        run(dtype, True)\n\n\ndef test_tensor_array_concat():\n    \"\"\"Tensor array concat\"\"\"\n\n    def run(dtype_str, infer_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            t = tf.constant(\n                np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(\n                    dtype_str\n                ),\n                dtype=dtype,\n            )\n            split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)\n            ta1 = tf.TensorArray(dtype=dtype, size=4, infer_shape=infer_shape)\n            ta2 = ta1.split(t, split_length)\n            t = ta2.concat()\n            _ = tf.identity(t)\n            compare_tf_with_tvm([], [], [\"Identity:0\"], mode=\"debug\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, False)\n        run(dtype, True)\n\n\ndef test_tensor_array_size():\n    \"\"\"Tensor array size\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n        pytest.skip(\"Needs fixing for tflite >= 1.15.0\")\n\n    def run(dtype_str, infer_shape):\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            np_data = np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str)\n            _ = [np_data, np_data]\n            t1 = tf.constant(np_data, dtype=dtype)\n            t2 = tf.constant(np_data, dtype=dtype)\n            ta1 = tf.TensorArray(dtype=dtype, size=2, infer_shape=infer_shape)\n            ta2 = ta1.write(0, t1)\n            ta3 = ta2.write(1, t2)\n            _ = ta3.size()\n            _ = tf.get_default_graph()\n            compare_tf_with_tvm([], [], \"TensorArraySizeV3:0\", mode=\"debug\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, False)\n        run(dtype, True)\n\n\ndef test_tensor_array_stack():\n    \"\"\"Tensor array stack\"\"\"\n\n    def run(dtype_str, infer_shape):\n        if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n            pytest.skip(\"Needs fixing for tflite >= 1.15.0\")\n\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            t = tf.constant(np.array([[1.0], [2.0], [3.0]]).astype(dtype_str))\n            scatter_indices = tf.constant([2, 1, 0])\n            ta1 = tf.TensorArray(dtype=dtype, size=3, infer_shape=infer_shape)\n            ta2 = ta1.scatter(scatter_indices, t)\n            t1 = ta2.stack()\n            print(t1)\n            _ = tf.get_default_graph()\n\n            compare_tf_with_tvm([], [], [\"TensorArrayStack/TensorArrayGatherV3:0\"], mode=\"vm\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, True)\n\n\ndef test_tensor_array_unstack():\n    \"\"\"Tensor array unstack\"\"\"\n\n    def run(dtype_str, input_shape, infer_shape):\n        if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n            pytest.skip(\"Needs fixing for tflite >= 1.15.0\")\n\n        with tf.Graph().as_default():\n            dtype = tf_dtypes[dtype_str]\n            t = tf.constant(np.random.choice([0, 1, 2, 3], size=input_shape).astype(dtype.name))\n            ta1 = tf.TensorArray(dtype=dtype, infer_shape=infer_shape, size=input_shape[0])\n            ta2 = ta1.unstack(t)\n            _ = ta2.size()\n            _ = ta2.read(0)\n            compare_tf_with_tvm([], [], \"TensorArraySizeV3:0\", mode=\"debug\")\n            compare_tf_with_tvm([], [], \"TensorArrayReadV3:0\", mode=\"debug\")\n\n    for dtype in [\"float32\", \"int8\"]:\n        run(dtype, (5,), False)\n        run(dtype, (5, 5), True)\n        run(dtype, (5, 5, 5), False)\n        run(dtype, (5, 5, 5, 5), True)\n\n\n#######################################################################\n# ConcatV2\n# --------\n\n\ndef _test_concat_v2(shape1, shape2, dim):\n    \"\"\"One iteration of ConcatV2\"\"\"\n\n    with tf.Graph().as_default():\n        dtype = \"float32\"\n        in1 = tf.placeholder(shape=shape1, dtype=dtype, name=\"in1\")\n        in2 = tf.placeholder(shape=shape2, dtype=dtype, name=\"in2\")\n        array_ops.concat_v2([in1, in2], dim)\n\n        np_data1 = np.random.uniform(size=shape1).astype(dtype)\n        np_data2 = np.random.uniform(size=shape2).astype(dtype)\n\n        compare_tf_with_tvm([np_data1, np_data2], [\"in1:0\", \"in2:0\"], \"ConcatV2:0\")\n\n\ndef test_forward_concat_v2():\n    if tf.__version__ < LooseVersion(\"1.4.1\"):\n        return\n\n    _test_concat_v2([2, 3], [2, 3], 0)\n    _test_concat_v2([10, 3, 5], [2, 3, 5], 0)\n    _test_concat_v2([2, 3], [2, 3], 1)\n    _test_concat_v2([5, 8], [5, 4], 1)\n    _test_concat_v2([2, 8, 5], [2, 8, 6], -1)\n\n\n#######################################################################\n# Sigmoid\n# -------\n\n\ndef _test_sigmoid(data):\n    \"\"\"One iteration of sigmoid\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        _ = math_ops.sigmoid(in_data)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"Sigmoid:0\")\n\n\ndef test_forward_sigmoid():\n    \"\"\"Sigmoid\"\"\"\n\n    _test_sigmoid(np.random.uniform(size=(3, 4, 4, 3)).astype(\"float32\"))\n\n\n#######################################################################\n# Argmin/Argmax\n# -------------\n\n\ndef _test_argx(func, data, **kwargs):\n\n    with tf.Graph().as_default():\n        inp = array_ops.placeholder(shape=data.shape, dtype=data.dtype, name=\"c0\")\n        func(inp, name=\"argx0\", **kwargs)\n        compare_tf_with_tvm(data, \"c0:0\", \"argx0:0\")\n\n\ndef test_forward_argminmax():\n    for output_type in [tf.int64, tf.int32]:\n        for axis in [None, 0, 1, 2]:\n            data = np.random.uniform(size=(8, 4, 9)).astype(\"float32\")\n            _test_argx(tf.argmax, data=data, axis=axis, output_type=output_type)\n            _test_argx(tf.argmin, data=data, axis=axis, output_type=output_type)\n\n\n#######################################################################\n# Variable\n# --------\n\n\ndef _test_variable(data):\n    \"\"\"One iteration of a variable\"\"\"\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        input_op = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        input_tensor = array_ops.reshape(input_op, data.shape)\n\n        size = input_tensor.shape.dims[1]\n        with variable_scope.variable_scope(\"linear\", reuse=None):\n            w = variable_scope.get_variable(\"w\", shape=[size, size], dtype=input_tensor.dtype)\n        math_ops.matmul(input_tensor, w)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"MatMul:0\", init_global_variables=True)\n\n\ndef test_forward_variable():\n    \"\"\"Variable type op test\"\"\"\n    _test_variable(np.random.uniform(size=(32, 100)).astype(\"float32\"))\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\ndef test_read_variable_op(target, dev):\n    \"\"\"Read Variable op test\"\"\"\n\n    tf.reset_default_graph()\n    data = np.random.uniform(size=(32, 100)).astype(\"float32\")\n    input_tensor = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n    size = input_tensor.shape.dims[1]\n    var_data = np.random.uniform(-5, 5, size=[size, size]).astype(np.float32)\n    input_var = tf.Variable(var_data, name=\"var1\", use_resource=True)\n    math_ops.matmul(input_tensor, input_var)\n\n    out_name = [\"MatMul:0\"]\n    out_node = [\"MatMul\"]\n    in_name = [\"Placeholder:0\"]\n    in_node = [\"Placeholder\"]\n    in_data = [data]\n\n    with tf.Session() as sess:\n        sess.run(variables.global_variables_initializer())\n\n        final_graph_def = sess.graph.as_graph_def(add_shapes=True)\n        tf_output = run_tf_graph(sess, in_data, in_name, out_name)\n\n        shape_dict = {e: i.shape for e, i in zip(in_name, in_data)}\n        with pytest.raises(Exception) as execinfo:\n            _, _ = relay.frontend.from_tensorflow(\n                final_graph_def, layout=None, shape=shape_dict, outputs=None\n            )\n\n        assert execinfo.value.args[0].startswith(\"Graph is not frozen. Provide a frozen graph\")\n\n        # Now convert the variables to constant and run inference on the converted graph\n        final_graph_def = tf.graph_util.convert_variables_to_constants(\n            sess,\n            sess.graph.as_graph_def(add_shapes=True),\n            out_node,\n        )\n\n        tvm_output = run_tvm_graph(\n            final_graph_def,\n            in_data,\n            in_node,\n            target=target,\n            out_names=out_name,\n            num_output=len(out_name),\n        )\n        for i, tf_out in enumerate(tf_output):\n            tvm.testing.assert_allclose(tf_out, tvm_output[i], atol=1e-4, rtol=1e-5)\n\n        sess.close()\n\n\n#######################################################################\n# MatMul, BatchMatMul, BatchMatMulV2\n# ----------------------------------\n\n\ndef _test_matmul(i, j, k, dtype, outer=None):\n    \"\"\"One iteration of matmul\"\"\"\n\n    A_shape_init = [i, j]\n    B_shape_init = [j, k]\n\n    for transpose_a in [False, True]:\n        for transpose_b in [False, True]:\n            outer = outer or []\n            A_shape = outer + (A_shape_init[::-1] if transpose_a else A_shape_init)\n            B_shape = outer + (B_shape_init[::-1] if transpose_b else B_shape_init)\n\n            with tf.Graph().as_default():\n                A = tf.placeholder(shape=A_shape, dtype=dtype, name=\"A\")\n                B = tf.placeholder(shape=B_shape, dtype=dtype, name=\"B\")\n                result = tf.matmul(A, B, transpose_a=transpose_a, transpose_b=transpose_b)\n\n                A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)\n                B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)\n                compare_tf_with_tvm(\n                    [A_np, B_np], [A.name, B.name], result.name, convert_config={\"use_dense\": True}\n                )\n                compare_tf_with_tvm(\n                    [A_np, B_np], [A.name, B.name], result.name, convert_config={\"use_dense\": False}\n                )\n\n\ndef test_forward_matmul():\n    \"\"\"MatMul op test\"\"\"\n    _test_matmul(1, 3, 6, \"int32\")\n    _test_matmul(5, 3, 1, \"float64\")\n\n\ndef _test_batch_matmul(A_shape, B_shape, dtype, adjoint_a=False, adjoint_b=False):\n\n    with tf.Graph().as_default():\n        A = tf.placeholder(shape=A_shape, dtype=dtype, name=\"A\")\n        B = tf.placeholder(shape=B_shape, dtype=dtype, name=\"B\")\n        result = tf.matmul(A, B, adjoint_a=adjoint_a, adjoint_b=adjoint_b, name=\"batchmatmul\")\n\n        A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)\n        B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)\n        compare_tf_with_tvm(\n            [A_np, B_np],\n            [A.name, B.name],\n            result.name,\n            convert_config={\"use_nt_batch_matmul\": True},\n        )\n        compare_tf_with_tvm(\n            [A_np, B_np],\n            [A.name, B.name],\n            result.name,\n            convert_config={\"use_nt_batch_matmul\": False},\n        )\n\n\ndef _test_batch_matmul_dynamic(\n    A_shape, B_shape, A_np_shape, B_np_shape, dtype, adjoint_a=False, adjoint_b=False\n):\n    with tf.Graph().as_default():\n        A = tf.placeholder(shape=A_shape, dtype=dtype, name=\"A\")\n        B = tf.placeholder(shape=B_shape, dtype=dtype, name=\"B\")\n        result = tf.matmul(A, B, adjoint_a=adjoint_a, adjoint_b=adjoint_b, name=\"batchmatmul\")\n\n        A_np = np.random.uniform(high=5.0, size=A_np_shape).astype(dtype)\n        B_np = np.random.uniform(high=5.0, size=B_np_shape).astype(dtype)\n        # for now, in TOPI, only llvm & cublas's implementation support dynamic shape\n        # TODO add more backends support in TOPI\n        compare_tf_with_tvm(\n            [A_np, B_np],\n            [A.name, B.name],\n            result.name,\n            mode=\"vm\",\n            targets=[\"llvm\", \"cuda -libs=cublas\"],\n            convert_config={\"use_nt_batch_matmul\": True},\n        )\n        compare_tf_with_tvm(\n            [A_np, B_np],\n            [A.name, B.name],\n            result.name,\n            mode=\"vm\",\n            targets=[\"llvm\", \"cuda -libs=cublas\"],\n            convert_config={\"use_nt_batch_matmul\": False},\n        )\n\n\ndef test_forward_batch_matmul():\n    \"\"\"TF op BatchMatMul, BatchMatMulV2 test\"\"\"\n    _test_batch_matmul((3, 5, 4), (3, 4, 5), \"int32\")\n    _test_batch_matmul((3, 5, 4), (3, 4, 5), \"float32\", True, True)\n    _test_batch_matmul((3, 5, 4), (3, 5, 4), \"int32\", True, False)\n    _test_batch_matmul((3, 5, 4), (3, 5, 4), \"float32\", False, True)\n    _test_batch_matmul((2, 3, 4, 5, 6), (2, 3, 4, 6, 5), \"int32\")\n    _test_batch_matmul((1, 2, 3, 4, 5, 6), (1, 2, 3, 4, 6, 5), \"float32\", True, True)\n    _test_batch_matmul((3, 4, 5, 6), (3, 4, 5, 6), \"int32\", True, False)\n    _test_batch_matmul((2, 3, 4, 2, 3, 4, 5, 6), (2, 3, 4, 2, 3, 4, 5, 6), \"float32\", False, True)\n    _test_batch_matmul((1, 8, 64, 2), (2, 1), \"float32\", False, False)\n    _test_batch_matmul((1, 8, 8, 64), (64, 1), \"float32\", False, False)\n    _test_batch_matmul((1, 8, 64), (64, 1), \"float32\", False, False)\n\n\ndef test_forward_batch_matmul_dynamic():\n    \"\"\"Dynamic batch matmul\"\"\"\n    _test_batch_matmul_dynamic((None, 5, 4), (None, 4, 5), (3, 5, 4), (3, 4, 5), \"int32\")\n    _test_batch_matmul_dynamic(\n        (None, 5, 4), (None, 4, 5), (3, 5, 4), (3, 4, 5), \"float32\", True, True\n    )\n    _test_batch_matmul_dynamic(\n        (None, 5, 4), (None, 5, 4), (3, 5, 4), (3, 5, 4), \"int32\", True, False\n    )\n    _test_batch_matmul_dynamic(\n        (None, 5, 4), (None, 5, 4), (3, 5, 4), (3, 5, 4), \"float32\", False, True\n    )\n    _test_batch_matmul_dynamic(\n        (None, 4, 5, 6), (None, 4, 6, 5), (3, 4, 5, 6), (3, 4, 6, 5), \"float32\"\n    )\n    _test_batch_matmul_dynamic(\n        (None, None, 5, 6), (None, None, 6, 5), (3, 4, 5, 6), (3, 4, 6, 5), \"float32\"\n    )\n    _test_batch_matmul_dynamic(\n        (None, None, None, 5, 6),\n        (None, None, None, 6, 5),\n        (2, 3, 4, 5, 6),\n        (2, 3, 4, 6, 5),\n        \"float32\",\n    )\n    _test_batch_matmul_dynamic(\n        (None, None, None, 5, 6),\n        (6, None),\n        (2, 3, 4, 5, 6),\n        (6, 1),\n        \"float32\",\n    )\n    _test_batch_matmul_dynamic(\n        (None, 5, 6),\n        (6, None),\n        (24, 5, 6),\n        (6, 1),\n        \"float32\",\n    )\n\n\n#######################################################################\n# SparseTensorDenseMatMul\n# ----------------------------------\n\n\ndef _test_sparse_dense_matmul(indices, values, A_inp_shape, B_inp_shape, dtype, flip=False):\n    \"\"\"One iteration of sparse_dense_matmul\"\"\"\n\n    for adjoint_a in [False, True]:\n        for adjoint_b in [False, True]:\n            A_shape = A_inp_shape[::-1] if adjoint_a else A_inp_shape\n            B_shape = B_inp_shape[::-1] if adjoint_b else B_inp_shape\n\n            with tf.Graph().as_default():\n                A_sp = tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=A_shape)\n                B = tf.placeholder(shape=B_shape, dtype=dtype, name=\"B\")\n\n                if flip:\n                    result = tf.sparse.sparse_dense_matmul(\n                        B, A_sp, adjoint_a=adjoint_b, adjoint_b=adjoint_a\n                    )\n                else:\n                    result = tf.sparse.sparse_dense_matmul(\n                        A_sp, B, adjoint_a=adjoint_a, adjoint_b=adjoint_b\n                    )\n\n                B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)\n\n                compare_tf_with_tvm([B_np], [B.name], result.name)\n\n\ndef test_forward_sparse_dense_matmul():\n    \"\"\"sparse_dense_matmul op test\"\"\"\n    ###################################################################\n    #\n    # In order to create a SparseTensor, it requires 3 input as below:\n    #    SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n    #\n    # Above Sparse can be represented in Dense as below :\n    #    [[1, 0, 0, 0]\n    #     [0, 0, 2, 0]\n    #     [0, 0, 0, 0]]\n    #\n    # ------------------------------------------------------------------\n\n    _test_sparse_dense_matmul([[0, 0], [1, 2]], [4.0, 8.0], [3, 4], [4, 3], \"float32\")\n    _test_sparse_dense_matmul([[0, 0], [1, 2]], [4.0, 8.0], [3, 3], [3, 3], \"float32\")\n    _test_sparse_dense_matmul([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], [5, 5], \"float32\")\n    _test_sparse_dense_matmul([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [7, 9], [9, 5], \"float32\")\n    _test_sparse_dense_matmul([[0, 0], [1, 2]], [4.0, 8.0], [4, 3], [3, 4], \"float32\", True)\n    _test_sparse_dense_matmul([[0, 0], [1, 2]], [4.0, 8.0], [3, 3], [3, 3], \"float32\", True)\n    _test_sparse_dense_matmul(\n        [[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], [5, 5], \"float32\", True\n    )\n    _test_sparse_dense_matmul(\n        [[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [9, 5], [7, 9], \"float32\", True\n    )\n\n\n#######################################################################\n# SparseFillEmptyRows\n# ------------\n\n\ndef _test_sparse_fill_empty_rows(indices_np, values_np, dense_shape_np, default_value_int, use_dyn):\n    with tf.Graph().as_default():\n        if use_dyn:\n            indices = tf.placeholder(shape=(None, None), dtype=indices_np.dtype, name=\"indices\")\n            values = tf.placeholder(shape=(None), dtype=values_np.dtype, name=\"values\")\n            dense_shape = tf.placeholder(\n                shape=(None), dtype=dense_shape_np.dtype, name=\"dense_shape\"\n            )\n        else:\n            indices = tf.placeholder(shape=indices_np.shape, dtype=indices_np.dtype, name=\"indices\")\n            values = tf.placeholder(shape=values_np.shape, dtype=values_np.dtype, name=\"values\")\n            dense_shape = tf.placeholder(\n                shape=dense_shape_np.shape, dtype=dense_shape_np.dtype, name=\"dense_shape\"\n            )\n\n        default_value = tf.placeholder(shape=(), dtype=values_np.dtype, name=\"default_value\")\n        sp_input = tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=dense_shape)\n        _ = tf.sparse.fill_empty_rows(sp_input, default_value, name=\"sparse_fill_empty_rows\")\n        compare_tf_with_tvm(\n            [indices_np, values_np, dense_shape_np, default_value_int],\n            [indices.name, values.name, dense_shape.name, default_value.name],\n            [\n                \"sparse_fill_empty_rows/SparseFillEmptyRows:0\",\n                \"sparse_fill_empty_rows/SparseFillEmptyRows:1\",\n                \"sparse_fill_empty_rows/SparseFillEmptyRows:2\",\n            ],\n            mode=\"vm\",\n        )\n\n\n@pytest.mark.parametrize(\n    \"sparse_indices_np, sparse_values_np, dense_shape_np, default_value_int\",\n    [\n        (\n            np.array([[1, 1], [0, 3], [0, 1], [2, 0], [3, 1]], dtype=np.int64),\n            np.array([1, 2, 3, 4, 5], dtype=np.int64),\n            np.array([5, 6], dtype=np.int64),\n            10,\n        ),\n        (\n            np.array([[1, 1], [0, 3], [2, 0], [3, 1]], dtype=np.int64),\n            np.array([1, 2, 3, 4], dtype=np.int64),\n            np.array([5, 6], dtype=np.int64),\n            10,\n        ),\n        (\n            np.array([[0, 1], [0, 3], [2, 0], [3, 1]], dtype=np.int64),\n            np.array([1, 2, 3, 4], dtype=np.int64),\n            np.array([5, 6], dtype=np.int64),\n            10,\n        ),\n        (\n            np.array([[1, 1, 1], [1, 3, 1], [2, 0, 5], [3, 1, 6]], dtype=np.int64),\n            np.array([1, 2, 3, 4], dtype=np.int64),\n            np.array([7, 7, 7], dtype=np.int64),\n            5,\n        ),\n        (\n            np.array([[1], [2]], dtype=np.int64),\n            np.array([7, 8], dtype=np.int64),\n            np.array([5], dtype=np.int64),\n            4,\n        ),\n        (\n            np.ones((0, 1), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([5], dtype=np.int64),\n            4,\n        ),\n        (\n            np.ones((0, 3), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([9, 3, 7], dtype=np.int64),\n            100,\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"use_dyn\", [True, False])\ndef test_forward_sparse_fill_empty_rows(\n    sparse_indices_np, sparse_values_np, dense_shape_np, default_value_int, use_dyn\n):\n    \"\"\"sparse_fill_empty_rows op test\"\"\"\n    ###################################################################\n    #\n    # In order to create a SparseTensor, it requires 3 input as below:\n    #    SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n    #\n    # Above Sparse can be represented in Dense as below :\n    #    [[1, 0, 0, 0]\n    #     [0, 0, 2, 0]\n    #     [0, 0, 0, 0]]\n    #\n    # ------------------------------------------------------------------\n    _test_sparse_fill_empty_rows(\n        sparse_indices_np, sparse_values_np, dense_shape_np, default_value_int, use_dyn\n    )\n\n\n#######################################################################\n# SparseReshape\n# ------------\n\n\ndef _test_sparse_reshape(indices_np, values_np, prev_shape_np, new_shape_np, use_dyn=False):\n    with tf.Graph().as_default():\n        if use_dyn:\n            indices = tf.placeholder(shape=(None, None), dtype=indices_np.dtype, name=\"indices\")\n            values = tf.placeholder(shape=(None), dtype=values_np.dtype, name=\"values\")\n            prev_shape = tf.placeholder(shape=(None), dtype=prev_shape_np.dtype, name=\"prev_shape\")\n            new_shape = tf.placeholder(shape=(None), dtype=new_shape_np.dtype, name=\"new_shape\")\n        else:\n            indices = tf.placeholder(shape=indices_np.shape, dtype=indices_np.dtype, name=\"indices\")\n            values = tf.placeholder(shape=values_np.shape, dtype=values_np.dtype, name=\"values\")\n            prev_shape = tf.placeholder(\n                shape=prev_shape_np.shape, dtype=prev_shape_np.dtype, name=\"prev_shape\"\n            )\n            new_shape = tf.placeholder(\n                shape=new_shape_np.shape, dtype=new_shape_np.dtype, name=\"new_shape\"\n            )\n        sp_input = tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=prev_shape)\n\n        _ = tf.sparse.reshape(sp_input, new_shape, name=\"sparse_reshape\")\n        compare_tf_with_tvm(\n            [indices_np, values_np, prev_shape_np, new_shape_np],\n            [indices.name, values.name, prev_shape.name, new_shape.name],\n            [\"sparse_reshape:0\", \"sparse_reshape:1\", \"sparse_reshape/Identity:0\"],\n            mode=\"vm\",\n        )\n\n\n@pytest.mark.parametrize(\n    \"sparse_indices_np, sparse_values_np, prev_shape_np, new_shape_np\",\n    [\n        (\n            np.ones((0, 1), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([4], dtype=np.int64),\n            np.array([2, -1], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 1), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([4], dtype=np.int64),\n            np.array([2, 2], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 2), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([3, 6], dtype=np.int64),\n            np.array([-1, 2], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([2, 3, 6], dtype=np.int64),\n            np.array([-1, 9], dtype=np.int64),\n        ),\n        (\n            np.array(\n                [\n                    [0, 0, 0, 0, 0],\n                    [0, 0, 1, 2, 3],\n                    [0, 1, 0, 3, 5],\n                    [1, 0, 0, 4, 6],\n                    [1, 2, 3, 6, 8],\n                ],\n                dtype=np.int64,\n            ),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([2, 3, 6, 7, 9], dtype=np.int64),\n            np.array([9, -1, 7], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 0], [0, 1], [3, 4], [4, 3], [7, 3]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([9, 4], dtype=np.int64),\n            np.array([-1], dtype=np.int64),\n        ),\n        (\n            np.array([[0], [5], [10], [20], [24]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([25], dtype=np.int64),\n            np.array([5, 5], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n            np.array([500, -1], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n            np.array([250, 40], dtype=np.int64),\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"use_dyn\", [True, False])\ndef test_forward_sparse_reshape(\n    sparse_indices_np, sparse_values_np, prev_shape_np, new_shape_np, use_dyn\n):\n    \"\"\"sparse_reshape op test\"\"\"\n    ###################################################################\n    #\n    # In order to create a SparseTensor, it requires 3 input as below:\n    #    SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n    #\n    # Above Sparse can be represented in Dense as below :\n    #    [[1, 0, 0, 0]\n    #     [0, 0, 2, 0]\n    #     [0, 0, 0, 0]]\n    #\n    # ------------------------------------------------------------------\n    _test_sparse_reshape(sparse_indices_np, sparse_values_np, prev_shape_np, new_shape_np, use_dyn)\n\n\n#######################################################################\n# Sparse Segment Variants\n# ------------\n\n\ndef _test_sparse_segment_variant(\n    tf_op, data_np, indices_np, segment_ids_np, num_segments, use_dyn=False\n):\n    with tf.Graph().as_default():\n        if use_dyn:\n            data = tf.placeholder(\n                shape=[None for _ in data_np.shape], dtype=data_np.dtype, name=\"data\"\n            )\n            indices = tf.placeholder(shape=[None], dtype=indices_np.dtype, name=\"indices\")\n            segment_ids = tf.placeholder(\n                shape=(None), dtype=segment_ids_np.dtype, name=\"segment_ids\"\n            )\n        else:\n            data = tf.placeholder(shape=data_np.shape, dtype=data_np.dtype, name=\"data\")\n            indices = tf.placeholder(shape=indices_np.shape, dtype=indices_np.dtype, name=\"indices\")\n            segment_ids = tf.placeholder(\n                shape=segment_ids_np.shape, dtype=segment_ids_np.dtype, name=\"segment_ids\"\n            )\n\n        _ = tf_op(\n            data, indices, segment_ids, num_segments=num_segments, name=\"sparse_segment_variant\"\n        )\n        compare_tf_with_tvm(\n            [data_np, indices_np, segment_ids_np],\n            [data.name, indices.name, segment_ids.name],\n            [\"sparse_segment_variant:0\"],\n            mode=\"vm\",\n        )\n\n\n@pytest.mark.parametrize(\n    \"data_np, indices_np, segment_ids_np, num_segments\",\n    [\n        (\n            np.array([5, 1, 7, 2, 3, 4], dtype=np.float32),\n            np.array([0, 3, 4], dtype=np.int32),\n            np.array([0, 1, 1], dtype=np.int32),\n            None,\n        ),\n        (\n            np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float64),\n            np.array([0, 1], dtype=np.int32),\n            np.array([0, 2], dtype=np.int32),\n            4,\n        ),\n        (\n            np.random.random((6, 4, 5)),\n            np.array([0, 2, 4, 3, 1], dtype=np.int32),\n            np.array([0, 0, 1, 5, 5], dtype=np.int32),\n            100,\n        ),\n        (\n            np.random.random((6, 4, 5)),\n            np.array([0, 2, 4, 3, 1], dtype=np.int32),\n            np.array([0, 0, 1, 5, 5], dtype=np.int32),\n            None,\n        ),\n        (\n            np.array([[[1, 7]], [[3, 8]], [[2, 9]]], dtype=np.float64),\n            np.array([0, 1, 2], dtype=np.int32),\n            np.array([0, 0, 1], dtype=np.int32),\n            None,\n        ),\n        (\n            np.random.random((9, 4, 5, 7)),\n            np.array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32),\n            np.array([0, 0, 1, 3, 5, 6, 7, 7, 8], dtype=np.int32),\n            9,\n        ),\n        (\n            np.random.random((9, 4, 5, 7)),\n            np.array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32),\n            np.array([0, 0, 1, 3, 5, 6, 7, 7, 8], dtype=np.int32),\n            None,\n        ),\n        (\n            np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float64),\n            np.array([0, 1], dtype=np.int32),\n            np.array([0, 2], dtype=np.int32),\n            None,\n        ),\n        (\n            np.random.random((9, 4, 5, 7)),\n            np.array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32),\n            np.array([0, 0, 1, 3, 5, 5, 5, 5, 5], dtype=np.int32),\n            6,\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"use_dyn\", [True, False])\n@pytest.mark.parametrize(\n    \"tf_op\",\n    [\n        tf.sparse.segment_sum,\n        tf.sparse.segment_sqrt_n,\n        tf.sparse.segment_mean,\n    ],\n)\ndef test_forward_sparse_segment_sum_variants(\n    tf_op,\n    data_np,\n    indices_np,\n    segment_ids_np,\n    num_segments,\n    use_dyn,\n):\n    \"\"\"sparse segment sum variants tests\"\"\"\n    _test_sparse_segment_variant(tf_op, data_np, indices_np, segment_ids_np, num_segments, use_dyn)\n\n\n#######################################################################\n# Math SegmentSum\n# ------------\n\n\ndef _test_math_segment_sum(data_np, segment_ids_np, use_dyn=False):\n    with tf.Graph().as_default():\n        if use_dyn:\n            data = tf.placeholder(\n                shape=[None for _ in data_np.shape], dtype=data_np.dtype, name=\"data\"\n            )\n            segment_ids = tf.placeholder(\n                shape=(None), dtype=segment_ids_np.dtype, name=\"segment_ids\"\n            )\n        else:\n            data = tf.placeholder(shape=data_np.shape, dtype=data_np.dtype, name=\"data\")\n            segment_ids = tf.placeholder(\n                shape=segment_ids_np.shape, dtype=segment_ids_np.dtype, name=\"segment_ids\"\n            )\n\n        _ = tf.math.segment_sum(data, segment_ids, name=\"segment_sum\")\n        compare_tf_with_tvm(\n            [data_np, segment_ids_np],\n            [data.name, segment_ids.name],\n            [\"segment_sum:0\"],\n            mode=\"vm\",\n        )\n\n\n@pytest.mark.parametrize(\n    \"data_np, segment_ids_np\",\n    [\n        (\n            np.array([5, 1, 7, 2, 3, 4], dtype=np.float32),\n            np.array([0, 0, 0, 1, 1, 1], dtype=np.int32),\n        ),\n        (\n            np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float64),\n            np.array([0, 0, 1], dtype=np.int32),\n        ),\n        (\n            np.random.random((6, 4, 5)),\n            np.array([0, 0, 1, 2, 2, 3], dtype=np.int64),\n        ),\n        (\n            np.array([[[1, 7]], [[3, 8]], [[2, 9]]], dtype=np.float32),\n            np.array([0, 0, 1], dtype=np.int32),\n        ),\n        (\n            np.random.random((9, 4, 5, 7)),\n            np.array([0, 0, 0, 1, 2, 3, 4, 4, 5], dtype=np.int64),\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"use_dyn\", [True, False])\ndef test_forward_math_segment_sum(data_np, segment_ids_np, use_dyn):\n    \"\"\"math segment sum test\"\"\"\n    _test_math_segment_sum(data_np, segment_ids_np, use_dyn)\n\n\n# tensorflow.compat.v1.sparse_to_dense\n# ---------------\ndef _test_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape):\n    with tf.Graph().as_default():\n        indices = tf.placeholder(\n            shape=sparse_indices.shape, dtype=str(sparse_indices.dtype), name=\"indices\"\n        )\n        values = tf.placeholder(\n            shape=sparse_values.shape, dtype=str(sparse_values.dtype), name=\"values\"\n        )\n        oshape = tf.constant(output_shape, shape=output_shape.shape, dtype=str(output_shape.dtype))\n\n        # Output shape depends on a dynamic input, use VM.\n        if default_value is None:\n            output = tf.sparse_to_dense(indices, oshape, values)\n            compare_tf_with_tvm(\n                [sparse_indices, sparse_values], [\"indices:0\", \"values:0\"], output.name, mode=\"vm\"\n            )\n        else:\n            dv = tf.placeholder(shape=(), dtype=str(default_value.dtype), name=\"default_value\")\n            output = tf.sparse_to_dense(indices, oshape, values, dv)\n            compare_tf_with_tvm(\n                [sparse_indices, sparse_values, default_value],\n                [\"indices:0\", \"values:0\", \"default_value:0\"],\n                output.name,\n                mode=\"vm\",\n            )\n\n\ndef test_forward_sparse_to_dense():\n    \"\"\"Sparse to dense\"\"\"\n    # scalar\n    _test_sparse_to_dense(\n        sparse_indices=np.int32(1),\n        sparse_values=np.int32(3),\n        default_value=np.int32(0),\n        output_shape=np.array([5]).astype(\"int32\"),\n    )\n\n    # vector\n    _test_sparse_to_dense(\n        sparse_indices=np.array([0, 1, 4]).astype(\"int32\"),\n        sparse_values=np.array([3, 3, 3]).astype(\"int32\"),\n        default_value=np.int32(0),\n        output_shape=np.array([5]).astype(\"int32\"),\n    )\n\n    # vector nXd\n    _test_sparse_to_dense(\n        sparse_indices=np.array([[0, 0], [1, 2]]).astype(\"int32\"),\n        sparse_values=np.array([1, 2]).astype(\"int32\"),\n        default_value=np.int32(0),\n        output_shape=np.array([3, 4]).astype(\"int32\"),\n    )\n\n    _test_sparse_to_dense(\n        sparse_indices=np.array([[0, 0, 0], [1, 2, 3]]).astype(\"int32\"),\n        sparse_values=np.array([1, 2]).astype(\"int32\"),\n        default_value=np.int32(4),\n        output_shape=np.array([2, 3, 4]).astype(\"int32\"),\n    )\n\n    # floats\n    _test_sparse_to_dense(\n        sparse_indices=np.array([0, 1, 4]).astype(\"int32\"),\n        sparse_values=np.array([3.1, 3.1, 3.1]).astype(\"float32\"),\n        default_value=np.float32(3.5),\n        output_shape=np.array([5]).astype(\"int32\"),\n    )\n\n    # default value not specified\n    _test_sparse_to_dense(\n        sparse_indices=np.array([0, 1, 4]).astype(\"int32\"),\n        sparse_values=np.array([3.1, 3.1, 3.1]).astype(\"float32\"),\n        default_value=None,\n        output_shape=np.array([5]).astype(\"int32\"),\n    )\n\n\n#######################################################################\n# tensorflow.sparse.to_dense\n# ---------------\ndef _test_sparse_to_dense_v2(indices, values, A_shape, dtype, default_value=None):\n    with tf.Graph().as_default():\n        A_sp = tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=A_shape)\n\n        result = tf.sparse.to_dense(A_sp, default_value=default_value)\n\n        # The output shape depends on a dynamic input, use VM.\n        compare_tf_with_tvm([], [], result.name, mode=\"vm\")\n\n\ndef test_forward_sparse_to_dense_v2():\n    _test_sparse_to_dense_v2([[1]], [3.0], [5], \"float32\")\n    _test_sparse_to_dense_v2([[1]], [3.0], [5], \"float32\", 0.3)\n    _test_sparse_to_dense_v2([[0, 0], [1, 2]], [4.0, 8.0], [3, 4], \"float32\")\n    _test_sparse_to_dense_v2([[0, 0], [1, 2]], [4.0, 8.0], [3, 4], \"float32\", 1.3)\n    _test_sparse_to_dense_v2([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], \"float32\")\n    _test_sparse_to_dense_v2([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], \"float32\", 1.9)\n\n\n#######################################################################\n# tensorflow.sparse.add\n# ----------------------------------\n\n\ndef _test_sparse_add(indices, values, A_shape, B_shape, dtype, flip=False):\n    \"\"\"One iteration of tf.sparse.add\"\"\"\n\n    # TODO(ANSHUMAN87): support cuda\n    # TODO(ANSHUMAN87): support both sparse input case\n\n    with tf.Graph().as_default():\n        A_sp = tf.sparse.SparseTensor(\n            indices=indices, values=np.array(values).astype(dtype), dense_shape=A_shape\n        )\n        B = tf.placeholder(shape=B_shape, dtype=dtype, name=\"B\")\n\n        # TODO(ANSHUMAN87): support user input threashold values\n        if flip:\n            if package_version.parse(tf.VERSION) < package_version.parse(\"1.13.0\"):\n                result = tf.sparse.add(B, A_sp, thresh=0)\n            else:\n                result = tf.sparse.add(B, A_sp, threshold=0)\n        else:\n            if package_version.parse(tf.VERSION) < package_version.parse(\"1.13.0\"):\n                result = tf.sparse.add(A_sp, B, thresh=0)\n            else:\n                result = tf.sparse.add(A_sp, B, threshold=0)\n\n        B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)\n\n        compare_tf_with_tvm([B_np], [B.name], result.name, no_gpu=True)\n\n\ndef test_sparse_add():\n    \"\"\"sparse.add op test\"\"\"\n    ###################################################################\n    #\n    # In order to create a SparseTensor, it requires 3 input as below:\n    #    SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n    #\n    # Above Sparse can be represented in Dense as below :\n    #    [[1, 0, 0, 0]\n    #     [0, 0, 2, 0]\n    #     [0, 0, 0, 0]]\n    #\n    # ------------------------------------------------------------------\n    for dtype_inp in [\"float32\", \"float64\", \"int32\"]:\n        _test_sparse_add([[0, 0], [1, 2]], [4.0, 8.0], [3, 4], [3, 4], dtype_inp)\n        _test_sparse_add([[0, 0], [1, 2]], [4.0, 8.0], [3, 4], [3, 4], dtype_inp, True)\n        _test_sparse_add([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], [5, 5], dtype_inp)\n        _test_sparse_add([[0, 0], [1, 3], [4, 3]], [3.0, 6.0, 9.0], [5, 5], [5, 5], dtype_inp, True)\n\n\n#######################################################################\n# StridedSlice\n# ------------\n\n\ndef _test_stridedslice(\n    ip_shape,\n    begin,\n    end,\n    stride,\n    dtype,\n    begin_mask=0,\n    end_mask=0,\n    new_axis_mask=0,\n    shrink_axis_mask=0,\n    ellipsis_mask=0,\n):\n    \"\"\"One iteration of a Stridedslice\"\"\"\n\n    tf.reset_default_graph()\n    np_data = np.random.uniform(size=ip_shape).astype(dtype)\n    with tf.Graph().as_default():\n        if len(ip_shape) == 0:  # pylint: disable=len-as-condition\n            in_data = tf.constant(np_data, dtype)\n        else:\n            in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        tf.strided_slice(\n            in_data,\n            begin,\n            end,\n            stride,\n            begin_mask=begin_mask,\n            end_mask=end_mask,\n            new_axis_mask=new_axis_mask,\n            shrink_axis_mask=shrink_axis_mask,\n            ellipsis_mask=ellipsis_mask,\n            name=\"strided_slice\",\n        )\n        if len(ip_shape) == 0:  # pylint: disable=len-as-condition\n            compare_tf_with_tvm(None, \"\", \"strided_slice:0\")\n        else:\n            compare_tf_with_tvm(np_data, \"in_data:0\", \"strided_slice:0\")\n\n\ndef test_forward_stridedslice():\n    \"\"\"test StridedSlice\"\"\"\n\n    _test_stridedslice([], [0], [0], [1], \"float32\", new_axis_mask=1)\n    _test_stridedslice([2], [1], [1], [1], \"float32\", shrink_axis_mask=1)\n    _test_stridedslice([4], [-1], [0], [1], \"float32\", shrink_axis_mask=1)\n    _test_stridedslice([2, 1], [0], [1], [1], \"float32\", shrink_axis_mask=1)\n    _test_stridedslice([2, 3, 4], [-2], [0], [1], \"float32\", shrink_axis_mask=8)\n    _test_stridedslice([2, 3, 4], [0], [1], [1], \"float32\", shrink_axis_mask=8)\n    _test_stridedslice([3, 4, 3], [1, -1, 0], [4, -5, 3], [2, -1, 1], \"float32\")\n    _test_stridedslice([3, 4, 3], [1, 0], [4, 3], [2, 1], \"float32\", ellipsis_mask=8)\n    _test_stridedslice([3, 4, 3], [1, 0], [4, 2], [2, 1], \"float32\", ellipsis_mask=2)\n    _test_stridedslice([3, 4, 5, 3], [1, 0], [4, 2], [2, 1], \"float32\", ellipsis_mask=2)\n    _test_stridedslice([3, 4, 5, 3], [1, 0, 1], [4, 2, 2], [2, 1, 1], \"float32\", ellipsis_mask=2)\n    _test_stridedslice([3, 4, 3], [1, 1, 0], [4, 4, 2], [2, 1, 1], \"float32\", new_axis_mask=5)\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 1], [4, 4, 1], [2, 1, 1], \"float32\", ellipsis_mask=2, new_axis_mask=4\n    )\n    _test_stridedslice(\n        [6, 4, 5], [1, 1, 1], [6, 3, 4], [2, 1, 1], \"float32\", ellipsis_mask=2, new_axis_mask=5\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 2], [4, 4, 3], [2, 1, 1], \"float32\", ellipsis_mask=4, new_axis_mask=2\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 2], [4, 4, 3], [2, 1, 1], \"float32\", ellipsis_mask=2, new_axis_mask=3\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 0], [4, 4, 1], [2, 1, 1], \"float32\", ellipsis_mask=2, new_axis_mask=3\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 2], [4, 4, 3], [2, 1, 1], \"float32\", ellipsis_mask=2, new_axis_mask=2\n    )\n    _test_stridedslice((3, 4), [1, 0], [4, 4], [1, 1], \"float32\", shrink_axis_mask=2)\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 0], [4, 4, 3], [2, 1, 1], \"float32\", shrink_axis_mask=2, new_axis_mask=2\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 0], [4, 4, 3], [2, 1, 1], \"float32\", shrink_axis_mask=1, new_axis_mask=2\n    )\n    _test_stridedslice(\n        [3, 4, 3], [1, 1, 0], [4, 4, 3], [2, 1, 1], \"float32\", shrink_axis_mask=2, new_axis_mask=1\n    )\n    _test_stridedslice(\n        [3, 4, 5, 4, 5, 6], [0, 0], [2, 3], [1, 1], \"float32\", shrink_axis_mask=5, new_axis_mask=1\n    )\n    _test_stridedslice(\n        [3, 4, 5, 4, 5, 6],\n        [0, 0, 1, 2, 1],\n        [2, 3, 4, 5, 3],\n        [1, 1, 2, 2, 1],\n        \"float32\",\n        shrink_axis_mask=5,\n        new_axis_mask=1,\n        ellipsis_mask=2,\n        begin_mask=8,\n        end_mask=8,\n    )\n    _test_stridedslice(\n        [3, 4, 5, 4, 5, 6],\n        [0, 0, 1, 2, 1],\n        [2, 3, 4, 5, 3],\n        [1, 1, 2, 2, 1],\n        \"float32\",\n        shrink_axis_mask=8,\n        new_axis_mask=1,\n        ellipsis_mask=2,\n        begin_mask=5,\n        end_mask=5,\n    )\n    _test_stridedslice(\n        [3, 4, 5, 4, 5, 6],\n        [0, 0, 1, 2, 1],\n        [2, 3, 4, 5, 3],\n        [1, 1, 2, 2, 1],\n        \"float32\",\n        shrink_axis_mask=16,\n        new_axis_mask=1,\n        ellipsis_mask=2,\n        begin_mask=5,\n        end_mask=5,\n    )\n    _test_stridedslice(\n        [3, 4, 5, 4, 5, 6],\n        [1, 2, 0, -3],\n        [4, 5, 3, 3],\n        [2, 2, 1, 1],\n        \"float32\",\n        shrink_axis_mask=8,\n        new_axis_mask=1,\n        ellipsis_mask=2,\n        begin_mask=5,\n        end_mask=8,\n    )\n    _test_stridedslice(\n        [1, 13, 13, 3, 2],\n        [0, 0],\n        [1, 1],\n        [1, -1],\n        \"float32\",\n        ellipsis_mask=1,\n        begin_mask=2,\n        end_mask=2,\n    )\n\n\n#######################################################################\n# FloorDiv, RealDiv\n# -----------------\ndef _test_forward_divide(ip_shape, dtype):\n    np_numer = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)\n    np_denomin = np.random.uniform(1, 100, size=ip_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        numerator = tf.placeholder(dtype, ip_shape, name=\"numer\")\n        denominator = tf.placeholder(dtype, ip_shape, name=\"denomin\")\n        tf.math.divide(numerator, denominator, name=\"RealDiv\")\n        compare_tf_with_tvm([np_numer, np_denomin], [\"numer:0\", \"denomin:0\"], \"RealDiv:0\")\n\n\ndef _test_forward_floordiv(ip_shape, dtype):\n    np_numer = np.random.uniform(1, 100, size=ip_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        numerator = tf.placeholder(dtype, ip_shape, name=\"numer\")\n        tf.math.floordiv(numerator, tf.constant(5, dtype=dtype), name=\"FloorDiv\")\n        compare_tf_with_tvm([np_numer], [\"numer:0\"], \"FloorDiv:0\")\n\n\ndef test_forward_divide():\n    \"\"\"test FloorDiv, RealDiv\"\"\"\n    _test_forward_divide((4,), \"int32\")\n    _test_forward_divide((4, 3, 7), \"float32\")\n    _test_forward_floordiv((4, 3, 7), \"float32\")\n    _test_forward_floordiv((4, 3, 7), \"int32\")\n\n\n#######################################################################\n# FloorMod\n# --------\ndef _test_forward_floormod(in_shape, if_shape, dtype):\n    np_numer = np.random.uniform(1, 100, size=in_shape).astype(dtype)\n    np_factor = np.random.uniform(1, 100, size=if_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        numerator = tf.placeholder(dtype, in_shape, name=\"numer\")\n        factor = tf.placeholder(dtype, if_shape, name=\"factor\")\n        tf.floormod(numerator, factor, name=\"FloorMod\")\n        compare_tf_with_tvm([np_numer, np_factor], [\"numer:0\", \"factor:0\"], \"FloorMod:0\")\n\n\ndef test_forward_floormod():\n    \"\"\"test FloorMod\"\"\"\n    _test_forward_floormod((10,), (10,), \"float32\")\n    _test_forward_floormod((8, 2), (1,), \"float32\")\n    _test_forward_floormod((4, 3, 7), (4, 3, 7), \"float32\")\n    _test_forward_floormod((4, 3, 7), (4, 3, 7), \"int32\")\n\n\n#######################################################################\n# TruncateMod\n# -----------\ndef _test_forward_truncatemod(ip_shape, dtype):\n    np_data_1 = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)\n    np_data_2 = np.random.uniform(1, 10, size=ip_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data_1 = tf.placeholder(dtype, ip_shape, name=\"in_data_1\")\n        in_data_2 = tf.placeholder(dtype, ip_shape, name=\"in_data_2\")\n        tf.truncatemod(in_data_1, in_data_2, name=\"truncatemod\")\n        compare_tf_with_tvm([np_data_1, np_data_2], [\"in_data_1:0\", \"in_data_2:0\"], \"truncatemod:0\")\n\n\ndef test_forward_truncatemod():\n    \"\"\"test TruncateMod\"\"\"\n    _test_forward_truncatemod((4, 3, 7), \"int32\")\n\n\n#######################################################################\n# Gather, GatherV2\n# --------------------------\n\n\ndef _test_gather(ip_shape, indice_shape, indice_value, axis, batch_dims, dtype):\n    \"\"\"One iteration of a GatherV2\"\"\"\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        indices = tf.placeholder(\"int32\", indice_shape, name=\"indices\")\n        out = tf.gather(in_data, indices, axis=axis, batch_dims=batch_dims)\n        np_data = np.random.uniform(1, 10, size=ip_shape).astype(dtype)\n\n        def _fill_indices(indice_value):\n            indices = np.array(ip_shape, dtype=dtype)\n            if isinstance(indice_value, int):\n                indices = np.array([indice_value], dtype=\"int32\")\n            else:\n                indices = np.asarray(indice_value, dtype=\"int32\")\n            return indices\n\n        np_indices = _fill_indices(indice_value)\n        compare_tf_with_tvm([np_data, np_indices], [\"in_data:0\", \"indices:0\"], out.name)\n\n\ndef test_forward_gather():\n    \"\"\"test Gather/GatherV2 layer\"\"\"\n    _test_gather((4,), (1,), 1, 0, 1, \"int32\")\n    _test_gather((4,), (1,), 1, 0, 0, \"float32\")\n    _test_gather((1, 4), (1,), [0], 0, 0, \"int32\")\n    _test_gather((4,), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 0, \"float32\")\n    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 0, \"int32\")\n    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 1, 0, \"int32\")\n    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 0, \"float32\")\n    _test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 0, 0, \"int32\")\n    _test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 2, 0, \"int32\")\n    _test_gather((4, 3, 5, 6), (1, 4), [[2, 1, 0, 0]], 0, 0, \"float32\")\n    _test_gather((2, 2), (2, 2), [[0, 0], [0, 0]], 1, 1, \"float32\")\n    _test_gather(\n        (2, 2, 3, 6), (2, 2, 3), [[[1, 1, 0], [0, 0, 1]], [[0, 1, 0], [1, 0, 1]]], 2, 2, \"float32\"\n    )\n    _test_gather(\n        (2, 2, 3, 6), (2, 2, 3), [[[1, 1, 0], [0, 0, 1]], [[0, 1, 0], [1, 0, 1]]], 3, 1, \"float32\"\n    )\n    _test_gather(\n        (2, 2, 3, 6), (2, 2, 3), [[[1, 1, 0], [0, 0, 1]], [[0, 1, 0], [1, 0, 1]]], 3, 2, \"float32\"\n    )\n    _test_gather(\n        (2, 2, 3, 6), (2, 2, 3), [[[1, 1, 0], [0, 0, 1]], [[0, 1, 0], [1, 0, 1]]], 3, 0, \"float32\"\n    )\n\n\n#######################################################################\n# GatherND\n# --------------------------\n\n\ndef _test_gather_nd(ip_shape, indice_value, dtype):\n    \"\"\"test operator GatherNd\"\"\"\n    np_data = np.random.uniform(1, 100, size=ip_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        tf.gather_nd(in_data, indices=indice_value, name=\"gather_nd\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"gather_nd:0\")\n\n\ndef test_forward_gather_nd():\n    \"\"\"test operator GatherNd\"\"\"\n    _test_gather_nd((2, 2), [[0, 0], [1, 1]], \"float32\")\n    _test_gather_nd((2, 2, 2), [[1, 0, 0], [0, 0, 0]], \"float32\")\n    _test_gather_nd((4,), [1], \"float32\")\n    _test_gather_nd((4,), [1], \"int32\")\n    _test_gather_nd((1, 4), [0, 3], \"int32\")\n    _test_gather_nd((2, 2), [[[1, 0], [0, 1]]], \"int32\")\n    _test_gather_nd((2, 2), [[[1, 0], [0, 1]]], \"float32\")\n    _test_gather_nd((3, 3, 3), [[[1, 0]]], \"int32\")\n    _test_gather_nd((3, 3, 3), [[[1, 0]]], \"int32\")\n    _test_gather_nd((4, 3, 5, 6), [[2, 1, 0, 0]], \"float32\")\n    _test_gather_nd((3, 3, 3), [[[2, 1]]], \"int32\")\n\n\n#######################################################################\n# BiasAdd\n# -------\ndef test_forward_bias_add():\n    \"\"\"test Op BiasAdd\"\"\"\n\n    def check_bias_add(lh_shpae, rh_shape, dtype):\n        tf.reset_default_graph()\n        lh_data = np.random.uniform(size=lh_shpae).astype(dtype)\n        rh_data = np.random.uniform(size=rh_shape).astype(dtype)\n        with tf.Graph().as_default():\n            lft_data = tf.placeholder(dtype, name=\"lft_data\")\n            rgt_data = tf.placeholder(dtype, name=\"rgt_data\")\n            tf.nn.bias_add(lft_data, rgt_data, name=\"BiasAdd\")\n            compare_tf_with_tvm([lh_data, rh_data], [\"lft_data:0\", \"rgt_data:0\"], \"BiasAdd:0\")\n\n    check_bias_add((10, 8, 16, 32), (32,), dtype=\"int32\")\n    check_bias_add((10, 20), (20,), dtype=\"float32\")\n\n\n#######################################################################\n# Split\n# -----\n\n\ndef _test_split(in_shape, axis, num_or_size_splits, dtype):\n    \"\"\"One iteration of a Split\"\"\"\n    np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        _ = len(num_or_size_splits) if isinstance(num_or_size_splits, list) else num_or_size_splits\n        split = tf.split(in_data, num_or_size_splits, axis=axis)\n        relu = [tf.nn.relu(i) for i in split]\n\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], [n.name for n in relu])\n\n    # and now test together with concat\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        splitted = tf.split(in_data, num_or_size_splits, axis=axis)\n        concat = tf.concat(splitted, axis)\n        compare_tf_with_tvm([np_data], \"in_data:0\", concat.name)\n\n\ndef test_forward_split():\n    \"\"\"test split layer\"\"\"\n    # rank 1\n    _test_split((3,), 0, 1, \"float32\")\n    _test_split((3,), 0, 3, \"float32\")\n    _test_split((6,), 0, 3, \"float32\")\n    # rank 2\n    _test_split((6, 2), 0, 3, \"float32\")\n    _test_split((2, 6), 1, 6, \"float32\")\n    # rank 3\n    _test_split((6, 2, 4), 0, 2, \"int32\")\n    _test_split((2, 6, 4), 1, 3, \"float32\")\n    _test_split((2, 4, 6), 2, 1, \"float32\")\n    # rank 4\n    _test_split((6, 1, 3, 5), 0, 3, \"float32\")\n    _test_split((1, 6, 3, 5), 1, 3, \"float32\")\n    _test_split((1, 3, 6, 5), 2, 3, \"float32\")\n    _test_split((1, 3, 5, 6), 3, 3, \"float32\")\n    # split along negative axis\n    _test_split((6, 1, 3, 5), -4, 3, \"float32\")\n    _test_split((1, 6, 3, 5), -3, 3, \"float32\")\n    _test_split((1, 3, 6, 5), -2, 3, \"float32\")\n    _test_split((1, 3, 5, 6), -1, 3, \"float32\")\n    # size_splits list\n    _test_split((6,), 0, [1, 2, 3], \"int32\")\n    _test_split((3, 6, 4), -2, [1, 4, 1], \"float32\")\n\n\n######################################################################\n# TopKV2\n# ------\n\n\ndef _test_forward_top_k_v2(in_shape, k):\n    np_data = np.random.uniform(-100, 100, size=in_shape).astype(\"float32\")\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(\"float32\", in_shape, name=\"in_data\")\n        tf.math.top_k(in_data, k, name=\"TopK\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"TopK:0\")\n\n\ndef test_forward_top_k_v2():\n    _test_forward_top_k_v2((3,), 1)\n    _test_forward_top_k_v2((3,), 3)\n    _test_forward_top_k_v2((3, 5, 7), 3)\n    _test_forward_top_k_v2((3, 5, 7), 3)\n\n\n#######################################################################\n# Unstack\n# -------\n\n\ndef _test_unstack(ip_shape, axis, dtype):\n    np_data = np.random.uniform(-5, 5, size=ip_shape).astype(dtype)\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        unstack = tf.unstack(in_data, axis=axis)\n\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], [n.name for n in unstack])\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        tf.stack(tf.unstack(in_data, axis=axis), axis=axis)\n\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"stack:0\")\n\n\ndef test_forward_unstack():\n    \"\"\"test unstack layer\"\"\"\n    _test_unstack((6,), 0, \"int32\")\n    _test_unstack((2, 6), 1, \"float64\")\n    # negative axis\n    _test_unstack((1, 4), -1, \"int32\")\n    _test_unstack((3, 6, 4), -2, \"float32\")\n\n\n#######################################################################\n# Tile\n# ----\n\n\ndef _test_tile(in_shape, multiples, dtype):\n    np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        tf.tile(in_data, multiples=multiples, name=\"tile\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"tile:0\")\n\n\ndef test_forward_tile():\n    \"\"\"test Tile\"\"\"\n    _test_tile((2,), (3,), \"int32\")\n    _test_tile((2, 2), (2, 3), \"float32\")\n    _test_tile((2, 4, 6), (6, 7, 8), \"float64\")\n\n\n#######################################################################\n# ClipByValue\n# -----------\n\n\ndef _test_forward_clip_by_value(ip_shape, clip_value_min, clip_value_max, dtype):\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        tf.clip_by_value(in_data, clip_value_min, clip_value_max, name=\"ClipByValue\")\n        np_data = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"ClipByValue:0\")\n\n\ndef test_forward_clip_by_value():\n    \"\"\"test ClipByValue op\"\"\"\n    if tf.__version__ < LooseVersion(\"1.9\"):\n        _test_forward_clip_by_value((4,), 0.1, 5.0, \"float32\")\n        _test_forward_clip_by_value((4, 4), 1, 5, \"int32\")\n\n\n#######################################################################\n# Multi Input to graph\n# --------------------\n\n\ndef test_forward_multi_input():\n    \"\"\"Multi Input\"\"\"\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in1\")\n        in2 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in2\")\n        in3 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in3\")\n        in4 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in4\")\n\n        out1 = tf.add(in1, in2, name=\"out1\")\n        out2 = tf.subtract(in3, in4, name=\"out2\")\n        _ = tf.multiply(out1, out2, name=\"out\")\n        in_data = np.arange(9, dtype=\"int32\").reshape([3, 3])\n\n        compare_tf_with_tvm(\n            [in_data, in_data, in_data, in_data], [\"in1:0\", \"in2:0\", \"in3:0\", \"in4:0\"], \"out:0\"\n        )\n\n\n#######################################################################\n# Multi Output to Graph\n# ---------------------\n\n\ndef test_forward_multi_output():\n    \"\"\"Multi Output\"\"\"\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in1\")\n        in2 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in2\")\n        in3 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in3\")\n        in4 = tf.placeholder(tf.int32, shape=[3, 3], name=\"in4\")\n\n        _ = tf.add(in1, in2, name=\"out1\")\n        _ = tf.subtract(in3, in4, name=\"out2\")\n        in_data = np.arange(9, dtype=\"int32\").reshape([3, 3])\n        in_data = [in_data] * 4\n        in_name = [\"in1:0\", \"in2:0\", \"in3:0\", \"in4:0\"]\n        out_name = [\"out1:0\", \"out2:0\"]\n        out_node = [out.strip(\":0\") for out in out_name]\n        in_node = [inp.strip(\":0\") for inp in in_name]\n\n        with tf.Session() as sess:\n            final_graph_def = tf.graph_util.convert_variables_to_constants(\n                sess,\n                sess.graph.as_graph_def(add_shapes=True),\n                out_node,\n            )\n            tf_output = run_tf_graph(sess, in_data, in_name, out_name)\n            tvm_output = run_tvm_graph(\n                final_graph_def, in_data, in_node, target=\"llvm\", out_names=out_node, num_output=2\n            )\n            for i, tf_out in enumerate(tf_output):\n                tvm.testing.assert_allclose(tf_out, tvm_output[i], atol=1e-5, rtol=1e-5)\n\n\n#######################################################################\n# Resize Bilinear, Nearest_Neighbor\n# ---------------------------------\n\n\ndef _test_resize_bilinear(in_shape, to_shape, align_corners):\n    \"\"\"One iteration of resize bilinear\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    shape_data = np.array(to_shape).astype(\"int32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        shape_data = constant_op.constant(\n            shape_data, shape=shape_data.shape, dtype=shape_data.dtype\n        )\n        tf.image.resize_bilinear(in_data, shape_data, align_corners=align_corners)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"ResizeBilinear:0\")\n\n\ndef _test_resize_bilinear_from_tensor(in_shape, align_corners):\n    \"\"\"One iteration of resize bilinear with non-constant output shape, requires\n    value inference to get proper output shape.\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(\n            shape=[in_shape[0], None, None, in_shape[3]], dtype=data.dtype\n        )\n        to_shape = tf.shape(in_data)[1:3]\n        tf.image.resize_bilinear(in_data, to_shape, align_corners=align_corners)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"ResizeBilinear:0\")\n\n\ndef _test_resize_nearest_neighbor(in_shape, to_shape):\n    \"\"\"One iteration of resize nearest neighbor\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    shape_data = np.array(to_shape).astype(\"int32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        shape_data = constant_op.constant(\n            shape_data, shape=shape_data.shape, dtype=shape_data.dtype\n        )\n        tf.image.resize_nearest_neighbor(in_data, shape_data, name=\"resize_nearest_neighbor\")\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"resize_nearest_neighbor:0\")\n\n\ndef _test_resize_nearest_neighbor_dynamic_shape(in_shape, scale):\n    \"\"\"One iteration of resize nearest neighbor for graph with dynamic input shape\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=None, dtype=data.dtype)\n        # multiply input shape by scale factor\n        new_shape = tf.shape(in_data)[1:3] * tf.constant(scale, dtype=tf.int32)\n        tf.image.resize_nearest_neighbor(in_data, new_shape, name=\"resize_nearest_neighbor\")\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"resize_nearest_neighbor:0\")\n\n\ndef test_forward_resize():\n    \"\"\"Resize Bilinear, Nearest_Neighbor\"\"\"\n    # TF default layout is NHWC\n    _test_resize_bilinear((4, 32, 32, 3), [50, 50], False)\n    _test_resize_bilinear((6, 32, 32, 3), [20, 20], True)\n    _test_resize_bilinear_from_tensor((4, 32, 32, 3), False)\n    _test_resize_bilinear_from_tensor((6, 50, 50, 3), True)\n    _test_resize_nearest_neighbor((6, 32, 32, 3), [20, 20])\n    _test_resize_nearest_neighbor_dynamic_shape((1, 16, 16, 3), scale=[2, 2])\n\n\n#######################################################################\n# BroadcastArgs\n# -----------\n\n\ndef _test_broadcast_args(in_shape_1, in_shape_2):\n    \"\"\"One iteration of broadcast_args\"\"\"\n\n    shape_1 = np.array(in_shape_1).astype(\"int32\")\n    shape_2 = np.array(in_shape_2).astype(\"int32\")\n\n    with tf.Graph().as_default():\n        shape_1 = constant_op.constant(shape_1, shape=shape_1.shape, dtype=shape_1.dtype)\n        shape_2 = constant_op.constant(shape_2, shape=shape_2.shape, dtype=shape_2.dtype)\n        tf.raw_ops.BroadcastArgs(s0=shape_1, s1=shape_2)\n\n        compare_tf_with_tvm(None, \"\", \"BroadcastArgs:0\", opt_level=0)\n\n\ndef test_forward_broadcast_args():\n    \"\"\"Resize Bilinear\"\"\"\n\n    _test_broadcast_args((4, 1, 32, 32), [4, 8, 32, 32])\n    _test_broadcast_args((6, 32, 32, 1), [6, 32, 32, 16])\n    _test_broadcast_args((32, 32, 16), [6, 32, 32, 16])\n\n\n#######################################################################\n# BroadcastTo\n# -----------\n\n\ndef _test_broadcast_to(in_shape, to_shape):\n    \"\"\"One iteration of broadcast_to\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    shape_data = np.array(to_shape).astype(\"int32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        shape_data = constant_op.constant(\n            shape_data, shape=shape_data.shape, dtype=shape_data.dtype\n        )\n        tf.broadcast_to(in_data, shape_data)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"BroadcastTo:0\", opt_level=0)\n\n\ndef _test_broadcast_to_from_tensor(in_shape):\n    \"\"\"One iteration of broadcast_to with unknown shape at graph build\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=[None], dtype=data.dtype)\n\n        shape_data = tf.multiply(tf.shape(in_data), 32)\n        tf.broadcast_to(in_data, shape_data)\n\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"BroadcastTo:0\")\n\n\ndef test_forward_broadcast_to():\n    \"\"\"Resize Bilinear\"\"\"\n\n    _test_broadcast_to((4, 1, 32, 32), [4, 8, 32, 32])\n    _test_broadcast_to((6, 32, 32, 1), [6, 32, 32, 16])\n    _test_broadcast_to_from_tensor((1))\n\n\n#######################################################################\n# Fill\n# ----\n\n\ndef _test_fill(in_shape):\n    \"\"\"Use the fill op to create a tensor of ones with non-constant shape.\"\"\"\n\n    with tf.Graph().as_default():\n        tf.ones(shape=in_shape, dtype=\"float32\")\n        compare_tf_with_tvm(in_shape, [], \"ones:0\", opt_level=1)\n\n\ndef _test_fill_from_tensor(in_shape):\n    \"\"\"Use the fill op to create a tensor of ones with non-constant shape.\n    Some extra ops need to be added here to prevent the graph from\n    being fully constant and folded away.\"\"\"\n\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(\n            shape=[in_shape[0], in_shape[1], None, None], dtype=data.dtype\n        )\n\n        x = tf.ones(shape=2 * tf.shape(in_data), dtype=data.dtype)\n        _ = tf.math.add(in_data, tf.reduce_mean(x), name=\"out1\")\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"out1:0\")\n\n\ndef _test_fill_symbolic_inputs(in_shape_data, in_value_data, dtype):\n    with tf.Graph().as_default():\n        in_shape = tf.placeholder(shape=[in_shape_data.shape[0]], dtype=in_shape_data.dtype)\n        in_value = tf.placeholder(shape=(), dtype=dtype)\n        out = tf.fill(in_shape, in_value)\n        for mode in [\"debug\", \"vm\"]:\n            compare_tf_with_tvm(\n                [in_shape_data, in_value_data], [in_shape.name, in_value.name], out.name, mode=mode\n            )\n\n\ndef test_forward_fill():\n    \"\"\"Resize Bilinear\"\"\"\n\n    _test_fill((32))\n    _test_fill((6, 32, 64, 64))\n    _test_fill_from_tensor((6, 32, 64, 64))\n    _test_fill_symbolic_inputs(np.array((2,)), np.int32(9), tf.int32)\n    _test_fill_symbolic_inputs(np.array((2, 3)), 9, tf.int64)\n    _test_fill_symbolic_inputs(np.array((2, 3, 4)), np.float32(9.0), tf.float32)\n\n\n#######################################################################\n# Crop to bounding box\n# --------------------\n\n\ndef _test_crop(in_shape, off_h, off_w, tar_h, tar_w):\n    \"\"\"Crop to bounding box\"\"\"\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        tf.image.crop_to_bounding_box(in_data, off_h, off_w, tar_h, tar_w)\n        compare_tf_with_tvm(data, \"Placeholder:0\", \"crop_to_bounding_box/Slice:0\")\n\n\ndef test_forward_crop():\n    \"\"\"Crop to bounding box\"\"\"\n    _test_crop((1, 224, 224, 3), 20, 20, 120, 120)\n\n\n#######################################################################\n# CropAndResize\n# -------------\n\n\ndef _test_forward_crop_and_resize(\n    img_shape,\n    boxes,\n    box_idx,\n    crop_size,\n    extrapolation_value=0.0,\n    method=\"bilinear\",\n    dtype=\"float32\",\n):\n    image = np.random.uniform(0, 10, size=img_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(dtype, image.shape, name=\"in_data\")\n        tf.image.crop_and_resize(\n            in_data,\n            boxes=boxes,\n            box_ind=box_idx,\n            crop_size=crop_size,\n            method=method,\n            extrapolation_value=extrapolation_value,\n            name=\"crop_and_resize\",\n        )\n        compare_tf_with_tvm([image], [\"in_data:0\"], \"crop_and_resize:0\")\n\n\ndef test_forward_crop_and_resize():\n    \"\"\"CropAndResize\"\"\"\n    _test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3])\n    _test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3], 0.2)\n    _test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3], 0.2, \"nearest\")\n    _test_forward_crop_and_resize([1, 11, 11, 3], [[0.3, 0.3, 1, 1]], [0], [21, 21])\n    _test_forward_crop_and_resize([1, 41, 41, 3], [[0.2, 0.4, 0.8, 0.8]], [0], [21, 11])\n    _test_forward_crop_and_resize([1, 100, 100, 3], [[0, 0, 0.9, 0.9]], [0], [30, 30])\n    _test_forward_crop_and_resize([1, 249, 249, 3], [[0, 0, 1, 1]], [0], [9, 9])\n    _test_forward_crop_and_resize([1, 201, 301, 3], [[0.2, 0.3, 0.7, 0.8]], [0], [51, 51])\n    _test_forward_crop_and_resize(\n        img_shape=[10, 11, 11, 3],\n        boxes=[[0, 0, 0.9, 0.9], [0.2, 0.2, 0.8, 0.8]],\n        box_idx=[0, 1],\n        crop_size=[5, 5],\n    )\n\n    if platform.machine() == \"aarch64\":\n        pytest.skip(\"Currently failing on AArch64\")\n    _test_forward_crop_and_resize([1, 224, 224, 3], [[0.1, 0.2, 1, 1]], [0], [9, 9])\n    _test_forward_crop_and_resize(\n        img_shape=[20, 576, 576, 3],\n        boxes=[[0, 0, 1, 1], [0, 0, 0.8, 0.8], [0.1, 0.2, 0.9, 1], [0.2, 0, 1, 1]],\n        box_idx=[1, 0, 2, 3],\n        crop_size=[24, 24],\n        extrapolation_value=0.3,\n    )\n    _test_forward_crop_and_resize(\n        img_shape=[20, 229, 229, 3],\n        boxes=[[0, 0, 0.9, 0.9], [0.3, 0.3, 1, 1], [0.2, 0.1, 0.7, 0.8], [0, 0, 1, 1]],\n        box_idx=[3, 0, 2, 1],\n        crop_size=[58, 58],\n        extrapolation_value=0.2,\n        method=\"nearest\",\n    )\n\n\n#######################################################################\n# Non Max Suppression\n# -------------------\ndef _test_forward_nms_v3(\n    bx_shape, score_shape, iou_threshold, score_threshold, out_size, dtype=\"float32\"\n):\n    boxes = np.random.uniform(0, 10, size=bx_shape).astype(dtype)\n    scores = np.random.uniform(size=score_shape).astype(dtype)\n    max_output_size = np.int32(out_size)\n    tf.reset_default_graph()\n    in_data_1 = tf.placeholder(dtype, boxes.shape, name=\"in_data_1\")\n    in_data_2 = tf.placeholder(dtype, scores.shape, name=\"in_data_2\")\n    in_data_3 = tf.placeholder(tf.int32, name=\"in_data_3\")\n    tf.image.non_max_suppression(\n        boxes=in_data_1,\n        scores=in_data_2,\n        max_output_size=in_data_3,\n        iou_threshold=iou_threshold,\n        score_threshold=score_threshold,\n        name=\"nms\",\n    )\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        \"nms/NonMaxSuppressionV3:0\",\n        mode=\"vm\",\n    )\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        \"nms/NonMaxSuppressionV3:0\",\n        mode=\"debug\",\n    )\n\n\ndef _test_forward_nms_v4(\n    bx_shape, score_shape, iou_threshold, score_threshold, out_size, dtype=\"float32\"\n):\n    boxes = np.random.uniform(0, 10, size=bx_shape).astype(dtype)\n    scores = np.random.uniform(size=score_shape).astype(dtype)\n    max_output_size = np.int32(out_size)\n    tf.reset_default_graph()\n    in_data_1 = tf.placeholder(dtype, boxes.shape, name=\"in_data_1\")\n    in_data_2 = tf.placeholder(dtype, scores.shape, name=\"in_data_2\")\n    in_data_3 = tf.placeholder(tf.int32, name=\"in_data_3\")\n    indices_padded, num_valid = tf.image.non_max_suppression_padded(\n        boxes=in_data_1,\n        scores=in_data_2,\n        max_output_size=in_data_3,\n        iou_threshold=iou_threshold,\n        score_threshold=score_threshold,\n        name=\"nms\",\n        pad_to_max_output_size=True,\n    )\n    num_valid = tf.reshape(num_valid, shape=(-1,))\n    indices_padded = tf.reshape(indices_padded, shape=(-1,))\n    tf.slice(indices_padded, tf.constant([0]), num_valid, name=\"SlicedIndices\")\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        [\"nms/NonMaxSuppressionV4:1\", \"SlicedIndices:0\"],\n        mode=\"vm\",\n    )\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        [\"nms/NonMaxSuppressionV4:1\", \"SlicedIndices:0\"],\n        mode=\"debug\",\n    )\n\n\ndef _test_forward_nms_v5(\n    bx_shape, score_shape, iou_threshold, score_threshold, out_size, dtype=\"float32\"\n):\n    boxes = np.random.uniform(0, 10, size=bx_shape).astype(dtype)\n    scores = np.random.uniform(size=score_shape).astype(dtype)\n    max_output_size = np.int32(out_size)\n    tf.reset_default_graph()\n    in_data_1 = tf.placeholder(dtype, boxes.shape, name=\"in_data_1\")\n    in_data_2 = tf.placeholder(dtype, scores.shape, name=\"in_data_2\")\n    in_data_3 = tf.placeholder(tf.int32, name=\"in_data_3\")\n    tf.image.non_max_suppression_with_scores(\n        boxes=in_data_1,\n        scores=in_data_2,\n        max_output_size=in_data_3,\n        iou_threshold=iou_threshold,\n        score_threshold=score_threshold,\n        name=\"nms\",\n    )\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        [\"nms/NonMaxSuppressionV5:0\", \"nms/NonMaxSuppressionV5:1\"],\n        mode=\"vm\",\n    )\n\n\ndef test_forward_nms():\n    \"\"\"NonMaxSuppressionV3,5\"\"\"\n    for _test_forward_nms in [_test_forward_nms_v3, _test_forward_nms_v5]:\n        _test_forward_nms((5, 4), (5,), 0.7, 0.5, 5)\n        _test_forward_nms((20, 4), (20,), 0.5, 0.6, 10)\n        _test_forward_nms((1000, 4), (1000,), 0.3, 0.7, 1000)\n        _test_forward_nms((2000, 4), (2000,), 0.4, 0.6, 7)\n\n\ndef _test_forward_combined_nms(\n    bx_shape,\n    score_shape,\n    iou_threshold,\n    score_threshold,\n    out_size,\n    total_size,\n    clip_boxes=False,\n    dtype=\"float32\",\n):\n    def get_random_scores(size, dtype):\n        size1d = np.prod(size)\n        scores = np.linspace(0, 1, num=size1d)\n        np.random.shuffle(scores)\n        return scores.reshape(size).astype(dtype)\n\n    boxes = np.random.uniform(-1, 2, size=bx_shape).astype(dtype)\n    scores = get_random_scores(score_shape, dtype)\n    max_output_size = np.int32(out_size)\n    tf.reset_default_graph()\n    in_data_1 = tf.placeholder(dtype, boxes.shape, name=\"in_data_1\")\n    in_data_2 = tf.placeholder(dtype, scores.shape, name=\"in_data_2\")\n    in_data_3 = tf.placeholder(tf.int32, name=\"in_data_3\")\n    tf.image.combined_non_max_suppression(\n        boxes=in_data_1,\n        scores=in_data_2,\n        max_output_size_per_class=in_data_3,\n        max_total_size=total_size,\n        iou_threshold=iou_threshold,\n        score_threshold=score_threshold,\n        pad_per_class=False,\n        clip_boxes=clip_boxes,\n        name=\"nms\",\n    )\n    compare_tf_with_tvm(\n        [boxes, scores, max_output_size],\n        [\"in_data_1:0\", \"in_data_2:0\", \"in_data_3:0\"],\n        [\n            \"nms/CombinedNonMaxSuppression:0\",\n            \"nms/CombinedNonMaxSuppression:1\",\n            \"nms/CombinedNonMaxSuppression:2\",\n            \"nms/CombinedNonMaxSuppression:3\",\n        ],\n    )\n\n\ndef test_forward_combined_nms():\n    \"\"\"CombinedNonMaxSuppression\"\"\"\n    _test_forward_combined_nms((1, 64, 1, 4), (1, 64, 1), 0.7, 0.5, 64, 64)\n    _test_forward_combined_nms((1, 32, 1, 4), (1, 32, 1), 0.7, 0.5, 10, 64)\n    _test_forward_combined_nms((1, 32, 1, 4), (1, 32, 2), 0.7, 0.5, 32, 64)\n    _test_forward_combined_nms((1, 64, 1, 4), (1, 64, 20), 0.7, 0.5, 64, 10)\n    # This workload seems flaky on CI.\n    # See https://github.com/apache/tvm/issues/8140\n    # _test_forward_combined_nms((1, 64, 20, 4), (1, 64, 20), 0.7, 0.5, 64, 64, clip_boxes=True)\n    _test_forward_combined_nms((2, 200, 1, 4), (2, 200, 1), 0.4, 0.6, 100, 100)\n    _test_forward_combined_nms((2, 200, 1, 4), (2, 200, 10), 0.4, 0.2, 150, 1000)\n\n\n#######################################################################\n# LSTM\n# ----\n\n\ndef _test_lstm_cell(batch_size, num_hidden, num_layers, forget_bias, dtype):\n    \"\"\"One iteration of a LSTM cell\"\"\"\n\n    tf.reset_default_graph()\n    input_size = num_hidden\n    input_data = np.full((batch_size, input_size), 1.0, dtype=dtype)\n    in_state_c = np.full((batch_size, num_hidden), 0.1, dtype=dtype)\n    in_state_h = np.full((batch_size, num_hidden), 0.1, dtype=dtype)\n\n    def _get_tensorflow_output():\n        with tf.Session() as sess:\n            with variable_scope.variable_scope(\n                \"root\", initializer=init_ops.constant_initializer(0.5)\n            ):\n                m0 = tf.placeholder(dtype, [batch_size, num_hidden], name=\"m0\")\n                m1 = tf.placeholder(dtype, [batch_size, num_hidden], name=\"m1\")\n                x = tf.placeholder(shape=(batch_size, input_size), dtype=dtype, name=\"input\")\n                g, ((out_m0, out_m1)) = tensorflow.contrib.rnn.LSTMBlockCell(\n                    num_hidden, forget_bias=forget_bias\n                )(x, (m0, m1))\n                sess.run([variables.global_variables_initializer()])\n                res = sess.run(\n                    [g, out_m0, out_m1],\n                    {\n                        x.name: np.array([[1.0, 1.0]]),\n                        m0.name: in_state_c,\n                        m1.name: in_state_h,\n                    },\n                )\n            graph_def = sess.graph.as_graph_def(add_shapes=True)\n            final_graph_def = graph_util.convert_variables_to_constants(\n                sess, graph_def, [\"root/lstm_cell/LSTMBlockCell\"]\n            )\n\n            return final_graph_def, res\n\n    graph_def, tf_out = _get_tensorflow_output()\n    tvm_output = run_tvm_graph(\n        graph_def,\n        [input_data, in_state_c, in_state_h],\n        [\"root/input\", \"root/m0\", \"root/m1\"],\n        num_output=7,\n    )\n    assert isinstance(tvm_output, list)\n\n    tvm.testing.assert_allclose(tf_out[0], tvm_output[6], rtol=1e-3, atol=1e-3)\n    tvm.testing.assert_allclose(tf_out[1], tvm_output[1], rtol=1e-3, atol=1e-3)\n\n\ndef test_forward_lstm():\n    \"\"\"test LSTM block cell\"\"\"\n    if package_version.parse(tf.VERSION) < package_version.parse(\"2.0.0\"):\n        # in 2.0, tf.contrib.rnn.LSTMBlockCell is removed\n        _test_lstm_cell(1, 2, 1, 0.5, \"float32\")\n\n\n#######################################################################\n# Pack\n# ---\ndef _test_pack(axis, shape, **kwargs):\n\n    a = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n    b = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n\n    with tf.Graph().as_default():\n        tf_a = array_ops.placeholder(shape=shape, dtype=\"float32\", name=\"pl_a\")\n        tf_b = array_ops.placeholder(shape=shape, dtype=\"float32\", name=\"pl_b\")\n        tf_c = tf.stack([tf_a, tf_b], axis=axis, **kwargs)\n        assert tf_c.op.op_def.name == \"Pack\", \"tf.stack() is expected to produce 'Pack' operation\"\n\n        compare_tf_with_tvm([a, b], [\"pl_a:0\", \"pl_b:0\"], \"stack:0\")\n\n\ndef test_forward_pack():\n    for axis in range(-3, 3):\n        _test_pack(axis, [3, 2, 1])\n    for axis in range(-1, 1):\n        _test_pack(axis, [3])\n    _test_pack(0, [])\n\n\n#######################################################################\n# Unpack\n# ------\ndef _test_forward_unpack(in_shape, axis, dtype):\n    \"\"\"test operator Unpack\"\"\"\n    np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        tf.unstack(in_data, axis=axis, name=\"Unpack\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"Unpack:0\")\n\n\ndef test_forward_unpack():\n    _test_forward_unpack((3,), 0, \"int32\")\n    _test_forward_unpack((3,), -1, \"int16\")\n    _test_forward_unpack((21, 23, 3), 2, \"float32\")\n\n\n#######################################################################\n# Range\n# -----\n\n\ndef test_forward_range():\n    \"\"\"test operator Range\"\"\"\n    for dtype in [tf.int32, tf.int64]:\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            tf.range(1, 18, 3, name=\"range\", dtype=dtype)\n            compare_tf_with_tvm([], [], \"range:0\")\n\n    # test type assignment for operator Range\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        tf.range(1, 256 + 1, 1, dtype=tf.float32)\n        compare_tf_with_tvm([], [], \"range:0\")\n\n\n#######################################################################\n# Einsum\n# -----\n\n\ndef _test_einsum(equation, dtype, *shape_of_input_tensors):\n    \"\"\"Test Einsum Op\"\"\"\n\n    with tf.Graph().as_default():\n        inputs_placeholders = []\n        input_data = []\n        for idx, shape in enumerate(shape_of_input_tensors):\n            input_name = f\"input_{idx}\"\n            inputs_placeholders.append(tf.placeholder(shape=shape, dtype=dtype, name=input_name))\n            input_data.append(np.random.normal(size=shape).astype(dtype))\n\n        result = tf.einsum(equation, *inputs_placeholders)\n\n        compare_tf_with_tvm(input_data, [ph.name for ph in inputs_placeholders], result.name)\n\n\ndef test_forward_einsum():\n    for dtype in [\"float32\"]:\n        _test_einsum(\"ij,jk->ik\", dtype, [2, 3], [3, 5])  # Matmul\n        _test_einsum(\"ij,jk\", dtype, [2, 3], [3, 5])  # Matmul\n        _test_einsum(\"i,i->\", dtype, [2], [2])  # Dot product\n        _test_einsum(\"i,j->ij\", dtype, [3], [5])  # Outer produce\n        _test_einsum(\"ij->ji\", dtype, [2, 3])  # Transpose\n        _test_einsum(\"ii->i\", dtype, [3, 3])  # Diag\n        _test_einsum(\"ii\", dtype, [3, 3])  # Trace of a square matrix\n        _test_einsum(\"bij,bjk->bik\", dtype, [7, 5, 3], [7, 3, 2])  # Batch matmul\n\n\n#######################################################################\n# Pad\n# ---\n\n\ndef _test_pad(input_shape, paddings, mode, **kwargs):\n    \"\"\"One iteration of pad operation with given shape\"\"\"\n\n    x = np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape)\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=\"float32\")\n        pad_values = constant_op.constant(paddings)\n        _ = tf.pad(in_data, paddings=pad_values, mode=mode, **kwargs)\n\n        if mode == \"CONSTANT\":\n            if \"constant_values\" in kwargs:\n                out_name = \"PadV2:0\"\n            else:\n                out_name = \"Pad:0\"\n        else:\n            out_name = \"MirrorPad:0\"\n\n        compare_tf_with_tvm(x, \"Placeholder:0\", out_name)\n\n\ndef test_forward_pad():\n    \"\"\"Pad\"\"\"\n    _test_pad((2, 3), [[1, 1], [2, 2]], mode=\"CONSTANT\")\n    _test_pad((2, 3), [[1, 1], [2, 2]], mode=\"CONSTANT\", constant_values=1.0)\n    _test_pad((2, 3), [[1, 1], [2, 2]], mode=\"SYMMETRIC\")\n    _test_pad((2, 3), [[1, 1], [2, 2]], mode=\"REFLECT\")\n\n\n#######################################################################\n# Logical operators\n# --------------------\n\n\ndef test_logical_and():\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in1\")\n        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in2\")\n        _ = tf.logical_and(in1, in2, name=\"out\")\n        in_data1 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        in_data2 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        compare_tf_with_tvm([in_data1, in_data2], [\"in1:0\", \"in2:0\"], \"out:0\")\n\n\ndef test_logical_or():\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in1\")\n        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in2\")\n        _ = tf.logical_or(in1, in2, name=\"out\")\n        in_data1 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        in_data2 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        compare_tf_with_tvm([in_data1, in_data2], [\"in1:0\", \"in2:0\"], \"out:0\")\n\n\ndef test_logical_xor():\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in1\")\n        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in2\")\n        _ = tf.logical_xor(in1, in2, name=\"out\")\n        in_data1 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        in_data2 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        compare_tf_with_tvm([in_data1, in_data2], [\"in1:0\", \"in2:0\"], \"out:0\")\n\n\ndef test_logical_not():\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name=\"in1\")\n        _ = tf.logical_not(in1, name=\"out\")\n        in_data1 = np.random.choice(a=[False, True], size=(1, 4, 4, 3)).astype(\"bool\")\n        compare_tf_with_tvm(in_data1, \"in1:0\", \"out:0\")\n\n\ndef test_forward_logical():\n    test_logical_and()\n    test_logical_or()\n    test_logical_xor()\n    test_logical_not()\n\n\n#######################################################################\n# Where, Select, SelectV2\n# -------------\ndef test_forward_where():\n    \"\"\"Where: return elements depending on conditions\"\"\"\n    with tf.Graph().as_default():\n        with tf.Session() as _:\n            input1 = tf.placeholder(tf.int32, shape=[1, 4, 4, 3], name=\"input1\")\n            input2 = tf.placeholder(tf.int32, shape=[1, 4, 4, 3], name=\"input2\")\n            mask = input1 > input2\n            tf.where(mask, input1 + 1, input2 * 2)\n            in_data1 = np.random.uniform(0, 10, size=(1, 4, 4, 3)).astype(\"uint32\")\n            in_data2 = np.random.uniform(0, 10, size=(1, 4, 4, 3)).astype(\"uint32\")\n            compare_tf_with_tvm([in_data1, in_data2], [\"input1:0\", \"input2:0\"], \"Select:0\")\n\n\n#######################################################################\n# Inception V3\n# ------------\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/10275\")\ndef test_forward_inception_v3():\n    \"\"\"test inception V3 model\"\"\"\n    with tf.Graph().as_default():\n        graph_def = tf_testing.get_workload(\n            \"InceptionV3/inception_v3_2016_08_28_frozen-with_shapes.pb\"\n        )\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        data = np.random.uniform(size=(1, 299, 299, 3)).astype(\"float32\")\n\n        with tf.Session() as sess:\n            tf_output = run_tf_graph(sess, data, \"input:0\", \"InceptionV3/Predictions/Reshape_1:0\")\n            tvm_output = run_tvm_graph(graph_def, data, \"input\")\n            tvm.testing.assert_allclose(tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)\n\n\n#######################################################################\n# Inception V1\n# ------------\n\n\ndef test_forward_inception_v1():\n    \"\"\"test inception V1 model\"\"\"\n    with tf.Graph().as_default():\n        graph_def = tf_testing.get_workload(\"InceptionV1/classify_image_graph_def-with_shapes.pb\")\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        # Build an image from random data.\n        img_array = np.random.uniform(size=(1, 600, 600, 3)).astype(\"uint8\")\n        img = Image.frombuffer(\"RGB\", (600, 600), img_array.tostring(), \"raw\", \"RGB\", 0, 1)\n        temp = utils.tempdir()\n        img_path = temp.relpath(\"tf-test.jpg\")\n        img.save(img_path)\n\n        if not tf.gfile.Exists(os.path.join(img_path)):\n            tf.logging.fatal(\"File does not exist %s\", img_path)\n        data = tf.gfile.FastGFile(os.path.join(img_path), \"rb\").read()\n\n        temp.remove()\n\n        # Extract tensorflow decoded image frame for tvm input\n        with tf.Session() as sess:\n            tvm_data = run_tf_graph(sess, data, \"DecodeJpeg/contents:0\", \"DecodeJpeg:0\")\n\n        with tf.Session() as sess:\n            tf_output = run_tf_graph(sess, data, \"DecodeJpeg/contents:0\", \"softmax:0\")\n            tvm_output = run_tvm_graph(graph_def, tvm_data, \"DecodeJpeg/contents\")\n            tvm.testing.assert_allclose(tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)\n\n\n#######################################################################\n# Mobilenet\n# ---------\n\n\ndef test_forward_mobilenet():\n    \"\"\"test mobilenet model\"\"\"\n    # MobilenetV2\n    with tf.Graph().as_default():\n        graph_def = tf_testing.get_workload(\n            \"https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.4_224.tgz\",\n            \"mobilenet_v2_1.4_224_frozen.pb\",\n        )\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n        out_node = \"MobilenetV2/Predictions/Reshape_1\"\n\n        with tf.Session() as sess:\n            # Add shapes to the graph.\n            graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)\n            tf_output = run_tf_graph(sess, data, \"input:0\", out_node + \":0\")\n            tvm_output = run_tvm_graph(graph_def, data, \"input\")\n            tvm.testing.assert_allclose(\n                np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]), rtol=1e-5, atol=1e-5\n            )\n\n\n#######################################################################\n# ResnetV2\n# --------\n\n\n@tvm.testing.requires_gpu\ndef test_forward_resnetv2():\n    \"\"\"test resnet model\"\"\"\n    if is_gpu_available():\n        with tf.Graph().as_default():\n            graph_def = tf_testing.get_workload(\n                \"ResnetV2/resnet-20180601_resnet_v2_imagenet-shapes.pb\"\n            )\n            # Call the utility to import the graph definition into default graph.\n            graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n            data = np.random.uniform(size=(128, 224, 224, 3)).astype(\"float32\")\n            out_node = \"ArgMax\"\n\n            with tf.Session() as sess:\n                tf_output = run_tf_graph(sess, data, \"input_tensor:0\", out_node + \":0\")\n                for device in [\"llvm\", \"cuda\"]:\n                    _ = tvm.device(device, 0)\n                    if not tvm.testing.device_enabled(device):\n                        print(f\"Skip because {device} is not enabled\")\n                        continue\n                    tvm_output = run_tvm_graph(\n                        graph_def, data, \"input_tensor\", len(tf_output), target=device\n                    )\n                    tvm.testing.assert_allclose(\n                        np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]), rtol=1e-5, atol=1e-5\n                    )\n\n\n#######################################################################\n# SSD\n# ---\n\n\ndef _test_ssd_impl():\n    \"\"\"Test SSD with backbone MobileNet V1\"\"\"\n    with tf.Graph().as_default():\n        graph_def = tf_testing.get_workload(\n            \"object_detection/ssd_mobilenet_v1_ppn_shared_\"\n            \"box_predictor_300x300_coco14_sync_2018_07_03.pb\"\n        )\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        data = np.random.uniform(0.0, 255.0, size=(1, 512, 512, 3)).astype(\"uint8\")\n        in_node = \"image_tensor\"\n        out_node = [\"detection_boxes\", \"detection_scores\", \"detection_classes\"]\n\n        with tf.Session() as sess:\n            tf_output = run_tf_graph(\n                sess, data, f\"{in_node}:0\", [f\"{oname}:0\" for oname in out_node]\n            )\n            # TODO(kevinthesun): enable gpu test when VM heterogeneous execution is ready.\n            for device in [\"llvm\"]:\n                _ = tvm.device(device, 0)\n                if not tvm.testing.device_enabled(device):\n                    print(f\"Skip because {device} is not enabled\")\n                    continue\n                tvm_output = run_tvm_graph(\n                    graph_def,\n                    data,\n                    in_node,\n                    len(out_node),\n                    target=device,\n                    layout=\"NCHW\",\n                    out_names=out_node,\n                    mode=\"vm\",\n                    disabled_pass=[\"FoldScaleAxis\"],\n                    serialize=True,\n                )\n                for i in range(len(out_node)):\n                    tvm.testing.assert_allclose(tvm_output[i], tf_output[i], rtol=1e-3, atol=1e-3)\n\n\n@pytest.mark.skip(\n    reason=\"Use of threading module here hides errors, see https://github.com/apache/tvm/pull/10231\"\n)\ndef test_forward_ssd():\n    run_thread = threading.Thread(target=_test_ssd_impl, args=())\n    old_stack_size = threading.stack_size(100 * 1024 * 1024)\n    run_thread.start()\n    run_thread.join()\n    threading.stack_size(old_stack_size)\n\n\n#######################################################################\n# Placeholder\n# -----------\n\n\ndef test_forward_placeholder():\n    \"\"\"test a simple pb with Placeholder node in the end of GraphDef\"\"\"\n    with tf.Graph().as_default():\n        graph_def = tf_testing.get_workload(\"Custom/placeholder.pb\")\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n\n        data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n        out_node = \"mul\"\n\n        with tf.Session() as sess:\n            # Add shapes to the graph.\n            graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)\n            tf_output = run_tf_graph(sess, data, \"Placeholder:0\", out_node + \":0\")\n            tvm_output = run_tvm_graph(graph_def, data, \"Placeholder\")\n            tvm.testing.assert_allclose(\n                np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]), rtol=1e-5, atol=1e-5\n            )\n\n\n#######################################################################\n# PTB\n# ---\ntry:\n    # Load contrib for running ptb model in tf version before 2.0\n    import tensorflow.contrib\nexcept ImportError:\n    pass\n\n\ndef test_forward_ptb():\n    \"\"\"test ptb model\"\"\"\n    config = tf_testing.get_config()\n    num_steps = config.num_steps\n    num_hidden = config.hidden_size\n    num_layers = config.num_layers\n    batch_size = config.batch_size\n    vocab_size = config.vocab_size\n    out_sample_shape = (batch_size, vocab_size)\n    out_state_shape = (batch_size, num_hidden)\n    # Sample input\n    inpt = \"we have no useful information on\"\n    cnt_sample = 20\n\n    def _pretty_print(items, is_char_model, id2word):\n        if not is_char_model:\n            return \" \".join([id2word[x] for x in items])\n        else:\n            return \"\".join([id2word[x] for x in items]).replace(\"_\", \" \")\n\n    def _get_tvm_graph_module(graph_def):\n        # Cell inputs 'c and 'h' consist of all layers values\n        shape_dict = {\"Model/Placeholder\": (batch_size, num_steps)}\n\n        mod, params = relay.frontend.from_tensorflow(\n            graph_def,\n            shape=shape_dict,\n            outputs=[\n                \"Model/Softmax:0\",\n                \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell:1\",\n                \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell:6\",\n                \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_1:1\",\n                \"Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_1:6\",\n            ],\n        )\n\n        target = \"llvm\"\n        with tvm.transform.PassContext(opt_level=0):\n            graph, lib, params = relay.build(mod, target, params=params)\n\n        dev = tvm.cpu(0)\n        return params, graph_executor.create(graph, lib, dev)\n\n    def _do_tvm_sample(model, data, in_states, params, num_samples):\n        \"\"\"Sampled from the model\"\"\"\n        samples = []\n        state = in_states\n        sample = None\n\n        def _get_sample(data, state):\n            input_data = np.full((batch_size, num_steps), data, dtype=\"int32\")\n\n            model.set_input(\"Model/Placeholder\", tvm.nd.array(input_data.astype(\"int32\")))\n            model.set_input(\n                \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros\",\n                tvm.nd.array(state[0].astype(\"float32\")),\n            )\n            model.set_input(\n                \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState/zeros_1\",\n                tvm.nd.array(state[1].astype(\"float32\")),\n            )\n            model.set_input(\n                \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros\",\n                tvm.nd.array(state[2].astype(\"float32\")),\n            )\n            model.set_input(\n                \"Model/MultiRNNCellZeroState/LSTMBlockCellZeroState_1/zeros_1\",\n                tvm.nd.array(state[3].astype(\"float32\")),\n            )\n            model.set_input(**params)\n            model.run()\n            tvm_output = model.get_output(0, tvm.nd.empty(out_sample_shape, \"float32\")).numpy()\n\n            state_output = []\n            for i in range(4):\n                state_output.append(\n                    model.get_output(i + 1, tvm.nd.empty(out_state_shape, \"float32\")).numpy()\n                )\n            sample = tf_testing.pick_from_weight(tvm_output[0])\n\n            return sample, state_output\n\n        for x in data:\n            sample, state = _get_sample(x, state)\n\n        if sample is not None:\n            samples.append(sample)\n        else:\n            samples.append(0)\n\n        k = 1\n        while k < num_samples:\n            sample, state = _get_sample(samples[-1], state)\n            samples.append(sample)\n            k += 1\n        return samples, state\n\n    with tf.Graph().as_default():\n        word_to_id, id_to_word, graph_def = tf_testing.get_workload_ptb()\n        vocab_size = len(word_to_id)\n        # Call the utility to import the graph definition into default graph.\n        graph_def = tf_testing.ProcessGraphDefParam(graph_def)\n        sess = tf.Session()\n\n    # TVM graph module creation\n    params, m = _get_tvm_graph_module(graph_def)\n\n    # Create 10 predicted statments of 20 words\n    cnt_stm = 0\n    while cnt_stm < 10:\n        cnt_stm += 1\n        in_state = [np.full((batch_size, num_hidden), 0, dtype=\"float32\")] * 2 * num_layers\n        seed_for_sample = inpt.split()\n        tvm_samples, _ = _do_tvm_sample(\n            m, [word_to_id[word] for word in seed_for_sample], in_state, params, cnt_sample\n        )\n        tvm_sample_str = _pretty_print(tvm_samples, False, id_to_word)\n        tf_samples, _ = tf_testing.do_tf_sample(\n            sess, [word_to_id[word] for word in seed_for_sample], in_state, cnt_sample\n        )\n        tf_sample_str = _pretty_print(tf_samples, False, id_to_word)\n        inpt = tvm_sample_str\n        tvm.testing.assert_allclose(tf_samples, tvm_samples, rtol=1e-5, atol=1e-5)\n        assert tvm_sample_str == tf_sample_str\n\n\n#######################################################################\n# LRN (Local Response Normalization)\n# ----------------------------------\n\n\ndef _test_lrn(ishape, size, axis, bias, alpha, beta):\n    \"\"\"testing local response normalization\"\"\"\n    lrn_depth_radius = size / 2\n\n    inp_array = np.random.uniform(size=ishape).astype(np.float32)\n\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype, name=\"lrn0_data\")\n        nn_ops.local_response_normalization(\n            in1, name=\"lrn\", depth_radius=lrn_depth_radius, bias=bias, alpha=alpha, beta=beta\n        )\n\n        compare_tf_with_tvm(inp_array, \"lrn0_data:0\", \"lrn:0\")\n\n\ndef test_forward_lrn():\n    _test_lrn((1, 3, 20, 20), 3, 1, 1.0, 1.0, 0.5)\n\n\n#######################################################################\n# l2_normalize\n# ------------\n\n\ndef _test_l2_normalize(ishape, eps, axis):\n    \"\"\"testing l2 normalize (uses max, sum, square, sqrt frontend operators)\"\"\"\n\n    inp_array = np.random.uniform(size=ishape).astype(np.float32)\n\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        nn.l2_normalize(in1, axis=axis, epsilon=eps, name=None, dim=None)\n\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"l2_normalize:0\")\n\n\ndef test_forward_l2_normalize():\n    _test_l2_normalize((1, 3, 20, 20), 0.001, (0,))\n\n\n#######################################################################\n# transpose\n# ---------\n\n\ndef _test_forward_transpose(ishape, axes=None):\n    data = np.random.uniform(size=ishape).astype(np.float32)\n\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=data.shape, dtype=data.dtype, name=\"transpose_data\")\n\n        if axes is None:\n            tf.transpose(in1)\n        else:\n            tf.transpose(in1, perm=axes)\n\n        compare_tf_with_tvm(data, \"transpose_data:0\", \"transpose:0\")\n\n\ndef _test_forward_tranapose_axes_input(ishape, axes):\n    data = np.random.uniform(size=ishape).astype(np.float32)\n    axes_np = np.array(axes).astype(np.int32)\n\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=data.shape, dtype=data.dtype, name=\"transpose_data\")\n\n        const1 = tf.constant(axes_np, dtype=tf.int32)\n\n        # make axes an input to tf.transpose, but not an input to the graph,\n        # so it can be extracted with infer_value_simulated\n        axes = tf.reverse(const1, axis=[-1])\n        tf.transpose(in1, axes)\n\n        compare_tf_with_tvm([data], [\"transpose_data:0\"], \"transpose:0\")\n\n\ndef test_forward_transpose():\n    _test_forward_transpose((2, 3, 4), (1, 2, 0))\n    _test_forward_transpose((2, 3, 4))\n    _test_forward_transpose((7, 8, 8, 10))\n    _test_forward_transpose((2, 3, 4), (1, 2, 0))\n    _test_forward_transpose((2, 3, 4), (0, 1, 2))\n    _test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2))\n    _test_forward_tranapose_axes_input((2, 3, 4), (1, 2, 0))\n    _test_forward_tranapose_axes_input((2, 3, 4, 5), (3, 0, 1, 2))\n\n\ndef _test_forward_slice_operation_input(input_value, begin_value, size_value):\n    input_data = np.array(input_value, dtype=np.float32)\n    with tf.Graph().as_default():\n        input_tensor = tf.placeholder(shape=input_data.shape, dtype=input_data.dtype, name=\"input\")\n        tf.slice(input_tensor, begin_value, size_value, name=\"slice_output\")\n        compare_tf_with_tvm([input_data], [\"input:0\"], \"slice_output:0\")\n\n\ndef test_forward_slice():\n    _test_forward_slice_operation_input([1, 1], [0], [2])\n    _test_forward_slice_operation_input([0, 1, 2, 3], [3], [-1])\n    _test_forward_slice_operation_input(\n        [[0, 1, 2, 3], [4, 5, 6, 7]], begin_value=[0, 1], size_value=[-1, -1]\n    )\n\n\ndef test_forward_ceil():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        tf.ceil(in1)\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Ceil:0\")\n\n\ndef test_forward_floor():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        tf.floor(in1)\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Floor:0\")\n\n\ndef test_forward_relu():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    for mode in [\"graph_executor\", \"vm\"]:\n        with tf.Graph().as_default():\n            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n            tf.nn.relu(in1)\n            compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Relu:0\", mode=mode)\n\n\ndef test_forward_leaky_relu():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    for mode in [\"graph_executor\", \"vm\"]:\n        with tf.Graph().as_default():\n            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n            tf.nn.leaky_relu(in1, alpha=0.4)\n            compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"LeakyRelu:0\", mode=mode)\n\n\ndef test_forward_elu():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        tf.nn.elu(in1)\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Elu:0\")\n\n\ndef test_forward_selu():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        tf.nn.selu(in1)\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Selu:0\")\n\n\ndef test_forward_tanh():\n    ishape = (1, 3, 10, 10)\n    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n        tf.nn.tanh(in1)\n        compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Tanh:0\")\n\n\n#######################################################################\n# Softmax\n# -------\ndef test_forward_softmax():\n    \"\"\"test operator Softmax\"\"\"\n\n    def check_softmax(in_shape, axis, dtype):\n        np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n            tf.nn.softmax(in_data, axis=axis, name=\"Softmax\")\n            compare_tf_with_tvm([np_data], [\"in_data:0\"], \"Softmax:0\")\n\n    check_softmax((2, 3, 5), 2, \"float32\")\n    check_softmax((2, 3, 5), -1, \"float32\")\n\n\n#######################################################################\n# Tensor\n# ------\n\n\ndef test_forward_round():\n    \"\"\"test Round\"\"\"\n    np_data = np.random.uniform(-10, 10, size=(5, 7)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (5, 7), name=\"in_data\")\n        tf.round(in_data, name=\"round\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"round:0\")\n\n\ndef test_forward_abs():\n    \"\"\"test operator Abs\"\"\"\n    np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (9, 11), name=\"in_data\")\n        tf.math.abs(in_data, name=\"abs\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"abs:0\")\n\n\ndef _test_forward_zeros_like(in_shape, dtype):\n    np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        tf.zeros_like(in_data, name=\"zeros_like\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"zeros_like:0\")\n\n\ndef test_forward_zeros_like():\n    if tf.__version__ < LooseVersion(\"1.2\"):\n        _test_forward_zeros_like((2, 3), \"int32\")\n        _test_forward_zeros_like((2, 3, 5), \"int8\")\n        _test_forward_zeros_like((2, 3, 5, 7), \"uint16\")\n        _test_forward_zeros_like((2, 3, 11), \"float32\")\n        _test_forward_zeros_like((2, 3, 11), \"float64\")\n\n\ndef test_forward_squared_difference():\n    ishape = (1, 3, 10, 14)\n    inp_array_a = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    inp_array_b = np.random.uniform(-5, 5, size=ishape).astype(np.float32)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array_a.shape, dtype=inp_array_a.dtype, name=\"in1\")\n        in2 = tf.placeholder(shape=inp_array_b.shape, dtype=inp_array_b.dtype, name=\"in2\")\n        out = tf.math.squared_difference(in1, in2)\n        compare_tf_with_tvm([inp_array_a, inp_array_b], [in1.name, in2.name], out.name)\n\n\ndef _test_forward_reverse_v2(in_shape, axis, dtype):\n    np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, in_shape, name=\"in_data\")\n        tf.reverse(in_data, axis=[axis], name=\"reverse\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"reverse:0\")\n\n\ndef test_forward_reverse_v2():\n    \"\"\"test ReverseV2\"\"\"\n    _test_forward_reverse_v2((2, 3), 0, \"int32\")\n    _test_forward_reverse_v2((2, 3, 5), 2, \"float32\")\n    _test_forward_reverse_v2((2, 3, 5, 7), 1, \"float32\")\n    _test_forward_reverse_v2((2, 3, 5), -1, \"float64\")\n    _test_forward_reverse_v2((2, 3, 5), -3, \"float64\")\n\n\ndef test_forward_sign():\n    \"\"\"test Sign\"\"\"\n    np_data = np.random.uniform(-10, 10, size=(5, 7, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (5, 7, 11), name=\"in_data\")\n        tf.sign(in_data, name=\"sign\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"sign:0\")\n\n\ndef test_forward_square():\n    \"\"\"test operator Square\"\"\"\n    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (2, 3, 5), name=\"in_data\")\n        tf.square(in_data, name=\"square\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"square:0\")\n\n\ndef test_forward_pow_exp():\n    \"\"\"test Pow and Exp\"\"\"\n    np_in1 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)\n    np_in2 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(tf.float32, (5, 7, 11), name=\"in1\")\n        in2 = tf.placeholder(tf.float32, (5, 7, 11), name=\"in2\")\n        _ = tf.pow(in1, in2, name=\"pow\")\n        _ = tf.exp(in1, name=\"exp\")\n        compare_tf_with_tvm([np_in1, np_in2], [\"in1:0\", \"in2:0\"], \"pow:0\")\n        compare_tf_with_tvm([np_in1], [\"in1:0\"], \"exp:0\")\n\n\ndef test_forward_unary():\n    \"\"\"Unary\"\"\"\n\n    def _test_forward_unary(op, a_min=1, a_max=5, dtype=np.float32):\n        \"\"\"test unary operators\"\"\"\n        np_data = np.random.uniform(a_min, a_max, size=(2, 3, 5)).astype(dtype)\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            in_data = tf.placeholder(dtype, (2, 3, 5), name=\"in_data\")\n            out = op(in_data)\n            compare_tf_with_tvm([np_data], [\"in_data:0\"], out.name)\n\n    _test_forward_unary(tf.acos, -1, 1)\n    _test_forward_unary(tf.asin, -1, 1)\n    _test_forward_unary(tf.atanh, -1, 1)\n    _test_forward_unary(tf.sinh)\n    _test_forward_unary(tf.cosh)\n    _test_forward_unary(tf.acosh)\n    _test_forward_unary(tf.asinh)\n    _test_forward_unary(tf.atan)\n    _test_forward_unary(tf.sin)\n    _test_forward_unary(tf.cos)\n    _test_forward_unary(tf.tan)\n    _test_forward_unary(tf.tanh)\n    _test_forward_unary(tf.erf)\n    _test_forward_unary(tf.log)\n    _test_forward_unary(tf.log1p)\n\n\ndef test_forward_atan2():\n    \"\"\"test operator tan\"\"\"\n    tf.disable_eager_execution()\n    np_data_1 = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)\n    np_data_2 = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)\n    tf.reset_default_graph()\n    in_data_1 = tf.placeholder(tf.float32, (2, 3, 5), name=\"in_data_1\")\n    in_data_2 = tf.placeholder(tf.float32, (2, 3, 5), name=\"in_data_2\")\n    tf.atan2(in_data_1, in_data_2, name=\"atan2\")\n    compare_tf_with_tvm([np_data_1, np_data_2], [\"in_data_1:0\", \"in_data_2:0\"], \"atan2:0\")\n\n\ndef test_forward_expm1():\n    \"\"\"test operator expm1\"\"\"\n\n    def _test_forward_expm1(shape):\n        tf.disable_eager_execution()\n        np_data = np.random.uniform(1, 10, size=shape).astype(np.float32)\n        tf.reset_default_graph()\n        in_data = tf.placeholder(tf.float32, shape, name=\"in_data\")\n        tf.expm1(in_data, name=\"expm1\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"expm1:0\")\n\n    _test_forward_expm1([1, 100])\n    _test_forward_expm1([1, 10, 10])\n    _test_forward_expm1([2, 5, 2, 5])\n\n\ndef test_forward_softsign():\n    \"\"\"test operator softsign\"\"\"\n\n    def _test_forward_softsign(shape):\n        tf.disable_eager_execution()\n        np_data = np.random.uniform(1, 100, size=shape).astype(np.float32)\n        tf.reset_default_graph()\n        in_data = tf.placeholder(tf.float32, shape, name=\"in_data\")\n        tf.nn.softsign(in_data, name=\"softsign\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"softsign:0\")\n\n    _test_forward_softsign([1, 100])\n    _test_forward_softsign([1, 10, 10])\n    _test_forward_softsign([2, 5, 2, 5])\n\n\ndef test_forward_rint():\n    \"\"\"test operator rint\"\"\"\n\n    def _test_forward_rint(shape):\n        tf.disable_eager_execution()\n        np_data = np.random.uniform(-100, 100, size=shape).astype(np.float32)\n        tf.reset_default_graph()\n        in_data = tf.placeholder(tf.float32, shape, name=\"in_data\")\n        tf.math.rint(in_data, name=\"rint\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"rint:0\")\n\n    _test_forward_rint([100])\n    _test_forward_rint([1, 100])\n    _test_forward_rint([1, 10, 10])\n    _test_forward_rint([2, 5, 2, 5])\n\n\ndef test_forward_negative():\n    \"\"\"test tf operator Neg\"\"\"\n    np_data = np.random.uniform(-100, 255, size=(224, 224, 3)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (224, 224, 3), name=\"in_data\")\n        tf.negative(in_data, name=\"negative\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"negative:0\")\n\n\ndef test_forward_log_softmax():\n    \"\"\"test operator LogSoftmax\"\"\"\n    np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (9, 11), name=\"in_data\")\n        tf.math.log_softmax(in_data, name=\"LogSoftmax\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"LogSoftmax:0\")\n\n\ndef test_forward_softplus():\n    \"\"\"test operator Softplus\"\"\"\n    np_data = np.random.uniform(1, 10, size=(2, 3, 5)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (2, 3, 5), name=\"in_data\")\n        tf.nn.softplus(in_data, name=\"softplus\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"softplus:0\")\n\n\ndef test_forward_rsqrt():\n    \"\"\"test Rsqrt\"\"\"\n    np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (5, 7, 11), name=\"in_data\")\n        tf.rsqrt(in_data, name=\"rsqrt\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"rsqrt:0\")\n\n\ndef test_forward_sqrt():\n    \"\"\"test Sqrt\"\"\"\n    np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, (5, 7, 11), name=\"in_data\")\n        tf.sqrt(in_data, name=\"sqrt\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"sqrt:0\")\n\n\ndef _test_forward_right_shift(in_shape, dtype):\n    \"\"\"test operator RightShift\"\"\"\n    lh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)\n    rh_data = np.random.randint(1, 8, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        lft_data = tf.placeholder(dtype, in_shape, name=\"lft_data\")\n        rgt_data = tf.placeholder(dtype, in_shape, name=\"rgt_data\")\n        tf.bitwise.right_shift(lft_data, rgt_data, name=\"RightShift\")\n        compare_tf_with_tvm([lh_data, rh_data], [\"lft_data:0\", \"rgt_data:0\"], \"RightShift:0\")\n\n\ndef test_forward_right_shift():\n    _test_forward_right_shift((7,), \"int32\")\n    _test_forward_right_shift((3, 11), \"int16\")\n\n\ndef _test_forward_left_shift(in_shape, dtype):\n    \"\"\"test operator LeftShift\"\"\"\n    lh_data = np.random.randint(100, 1000000, size=in_shape).astype(dtype)\n    rh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        lft_data = tf.placeholder(dtype, in_shape, name=\"lft_data\")\n        rgt_data = tf.placeholder(dtype, in_shape, name=\"rgt_data\")\n        tf.bitwise.left_shift(lft_data, rgt_data, name=\"LeftShift\")\n        compare_tf_with_tvm([lh_data, rh_data], [\"lft_data:0\", \"rgt_data:0\"], \"LeftShift:0\")\n\n\ndef test_forward_left_shift():\n    _test_forward_left_shift((10,), \"int32\")\n    _test_forward_left_shift((224, 224, 3), \"int16\")\n\n\n#######################################################################\n# Mean\n# ----\n\n\ndef test_forward_mean():\n    \"\"\"Mean\"\"\"\n\n    def check_mean(ishape, **kwargs):\n        inp_array = np.random.uniform(size=ishape).astype(np.float32)\n        with tf.Graph().as_default():\n            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)\n            tf.keras.backend.mean(in1, **kwargs)\n            compare_tf_with_tvm(inp_array, \"Placeholder:0\", \"Mean:0\", no_gpu=True)\n\n    check_mean((10, 8, 16, 32))\n    check_mean((10, 8, 16, 32), axis=(2, 3))\n    check_mean((10, 8, 16, 32), axis=(1, 2), keepdims=True)\n\n\n#######################################################################\n# Size\n# ----\n\n\ndef test_forward_size():\n    \"\"\"Size\"\"\"\n\n    def check_size(ishape):\n        np_input = np.random.uniform(size=ishape).astype(np.float32)\n\n        # if all dimensions are constant, TF will optimize away size operator into constant\n        tf_input_shape = list(np_input.shape)\n        tf_input_shape[0] = None\n\n        with tf.Graph().as_default():\n            tf_input = tf.placeholder(shape=tf_input_shape, dtype=np_input.dtype, name=\"input\")\n            tf.size(tf_input, name=\"size\")\n            compare_tf_with_tvm([np_input], [\"input:0\"], \"size:0\")\n\n    check_size((10, 8, 16, 32))\n    check_size((10,))\n\n\n#######################################################################\n# All, Any, Max, Min, Prod, variance, std, logsumexp, euclidean_norm\n# ------------------------------------------------------------------\n\n\ndef test_forward_reduce():\n    \"\"\"Reduce\"\"\"\n\n    def _check_op(tf_op, ishape, axis, keepdims, dtype=\"float32\"):\n        tf.reset_default_graph()\n        if dtype == \"bool\":\n            np_data = np.random.choice([True, False], size=ishape)\n        else:\n            np_data = np.random.uniform(size=ishape).astype(dtype)\n        if tf_op == tf.math.reduce_prod:\n            axis = 1\n            np_data = np_data.reshape(1, -1)\n        with tf.Graph().as_default():\n            in_data = tf.placeholder(dtype, name=\"in_data\")\n            reduce_op = tf_op(in_data, axis=axis, keepdims=keepdims, name=\"reduce_std\")\n            compare_tf_with_tvm([np_data], [\"in_data:0\"], reduce_op.name)\n\n    def _test_math_op(op, d_types=None):\n        d_types = d_types or [\"int32\", \"float32\"]\n        for dtype in d_types:\n            _check_op(op, (3, 10), axis=(-1), keepdims=False, dtype=dtype)\n            _check_op(op, (8, 16, 32), axis=(-1), keepdims=False, dtype=dtype)\n            _check_op(op, (1, 8, 8, 3), axis=(2, 3), keepdims=True, dtype=dtype)\n            _check_op(op, (2, 3, 10, 10), axis=(1, 2), keepdims=True, dtype=dtype)\n\n    _test_math_op(tf.math.reduce_all, d_types=[\"bool\"])\n    _test_math_op(tf.math.reduce_any, d_types=[\"bool\"])\n    _test_math_op(tf.math.reduce_max)\n    _test_math_op(tf.math.reduce_min)\n    _test_math_op(tf.math.reduce_prod)\n    _test_math_op(tf.math.reduce_variance, d_types=[\"float32\"])\n    _test_math_op(tf.math.reduce_std, d_types=[\"float32\"])\n    _test_math_op(tf.math.reduce_logsumexp, d_types=[\"float32\"])\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n        _test_math_op(tf.math.reduce_euclidean_norm)\n\n\n#######################################################################\n# All, Max, Min\n# ------------------------------------------------------------------\n\n\ndef test_forward_raw_reduce():\n    \"\"\"Raw reduce\"\"\"\n\n    def _check_op(tf_op, ishape, axis, keepdims, range_axis=False, dtype=\"float32\"):\n        tf.reset_default_graph()\n        if dtype == \"bool\":\n            np_data = np.random.choice([True, False], size=ishape)\n        else:\n            np_data = np.random.uniform(size=ishape).astype(dtype)\n        if tf_op == tf.math.reduce_prod:\n            axis = 1\n            np_data = np_data.reshape(1, -1)\n        with tf.Graph().as_default():\n            if range_axis:\n                axis = tf.range(axis[0], axis[1], axis[2], name=\"range\", dtype=\"int32\")\n            in_data = tf.placeholder(dtype, name=\"in_data\")\n            reduce_op = tf_op(input=in_data, axis=axis, keep_dims=keepdims, name=\"reduce_std\")\n            compare_tf_with_tvm([np_data], [\"in_data:0\"], reduce_op.name)\n\n    def _test_raw_reduce_op(op, d_types=None):\n        d_types = d_types or [\"int32\", \"float32\"]\n        for dtype in d_types:\n            _check_op(op, (3, 10), axis=(-1), keepdims=False, dtype=dtype)\n            _check_op(op, (8, 16, 32), axis=(-1), keepdims=False, dtype=dtype)\n            _check_op(op, (1, 8, 8, 3), axis=(2, 3), keepdims=True, dtype=dtype)\n            _check_op(op, (2, 3, 10, 10), axis=(1, 2), keepdims=True, dtype=dtype)\n            _check_op(op, (1, 8, 8, 3), axis=(2, 4, 1), keepdims=True, range_axis=True, dtype=dtype)\n            _check_op(\n                op, (2, 3, 10, 10), axis=(1, 3, 1), keepdims=True, range_axis=True, dtype=dtype\n            )\n\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.4.1\"):\n        _test_raw_reduce_op(tf.raw_ops.All, d_types=[\"bool\"])\n        _test_raw_reduce_op(tf.raw_ops.Max)\n        _test_raw_reduce_op(tf.raw_ops.Min)\n\n\n#######################################################################\n# Relational operators\n# --------------------\n\n\ndef _test_forward_rel_op(data, func):\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=data[0].shape, dtype=data[0].dtype, name=\"in1\")\n        in2 = tf.placeholder(shape=data[1].shape, dtype=data[1].dtype, name=\"in2\")\n        op = func(in1, in2, name=\"op\")\n        _ = tf.cast(op, tf.int32, name=\"out1\")\n        compare_tf_with_tvm([data[0], data[1]], [\"in1:0\", \"in2:0\"], \"out1:0\")\n\n\ndef test_forward_rel_ops():\n    t1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n    t2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])\n    _test_forward_rel_op([t1, t2], math_ops.less)\n    _test_forward_rel_op([t1, t2], math_ops.greater)\n    _test_forward_rel_op([t1, t2], math_ops.less_equal)\n    _test_forward_rel_op([t1, t2], math_ops.greater_equal)\n    _test_forward_rel_op([t1, t2], math_ops.equal)\n    _test_forward_rel_op([t1, t2], math_ops.not_equal)\n\n\n#######################################################################\n# ExpandDims\n# ----------\n\n\ndef _test_forward_expand_dims(data, axis):\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=data.shape, dtype=data.dtype, name=\"in1\")\n        out = tf.expand_dims(in1, axis)\n        compare_tf_with_tvm([data], [in1.name], out.name)\n\n\ndef test_forward_expand_dims():\n    _test_forward_expand_dims(np.int32(1), 0)\n    _test_forward_expand_dims(np.array([1]), 0)\n    _test_forward_expand_dims(np.array([1]), -1)\n    _test_forward_expand_dims(np.array([[1], [2]]), 0)\n    _test_forward_expand_dims(np.array([[1], [2]]), 1)\n    _test_forward_expand_dims(np.array([[1], [2]]), -1)\n\n\n#######################################################################\n# Maximum, Minimum\n# ----------------\ndef test_forward_maximum():\n    \"\"\"test Op Maximum\"\"\"\n\n    def check_maximum(lh_shape, rh_shape, dtype):\n        tf.reset_default_graph()\n        lh_data = np.random.uniform(size=lh_shape).astype(dtype)\n        rh_data = np.random.uniform(size=rh_shape).astype(dtype)\n        with tf.Graph().as_default():\n            lft_data = tf.placeholder(dtype, name=\"lft_data\")\n            rgt_data = tf.placeholder(dtype, name=\"rgt_data\")\n            tf.math.maximum(lft_data, rgt_data, name=\"maximum\")\n            compare_tf_with_tvm([lh_data, rh_data], [\"lft_data:0\", \"rgt_data:0\"], \"maximum:0\")\n\n    check_maximum((10, 8, 16, 32), (1,), dtype=\"int32\")\n    check_maximum((10, 8, 16, 32), (10, 8, 16, 32), dtype=\"float32\")\n\n\ndef test_forward_minimum():\n    \"\"\"test Op Minimum\"\"\"\n\n    def check_minimum(lh_shape, rh_shape, dtype):\n        tf.reset_default_graph()\n        lh_data = np.random.uniform(size=lh_shape).astype(dtype)\n        rh_data = np.random.uniform(size=rh_shape).astype(dtype)\n        with tf.Graph().as_default():\n            lft_data = tf.placeholder(dtype, name=\"lft_data\")\n            rgt_data = tf.placeholder(dtype, name=\"rgt_data\")\n            tf.math.minimum(lft_data, rgt_data, name=\"minimum\")\n            compare_tf_with_tvm([lh_data, rh_data], [\"lft_data:0\", \"rgt_data:0\"], \"minimum:0\")\n\n    check_minimum((10, 8, 16, 32), (1,), dtype=\"int32\")\n    check_minimum((10, 8, 16, 32), (10, 8, 16, 32), dtype=\"float32\")\n\n\n#######################################################################\n# PlaceholderWithDefault\n# ----------------------\ndef test_placeholder():\n    \"\"\"Placeholder\"\"\"\n    with tf.Graph().as_default():\n        in_data1 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)\n        var1 = tf.Variable(in_data1, name=\"in1\")\n        var2 = array_ops.placeholder_with_default(var1, None, name=\"place1\")\n\n        in_data2 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)\n        place1 = array_ops.placeholder(shape=in_data1.shape, dtype=in_data1.dtype, name=\"in2\")\n\n        out1 = tf.math.add(var1, var2, name=\"out1\")\n        _ = tf.math.add(out1, place1, name=\"out2\")\n\n        compare_tf_with_tvm(\n            [in_data1, in_data2], [\"place1:0\", \"in2:0\"], \"out2:0\", init_global_variables=True\n        )\n\n\n#######################################################################\n# OneHot\n# ----------------------\n\n\ndef _test_forward_one_hot(indices_shape, depth, on_value, off_value, axis, out_dtype):\n    inp_array1 = np.random.randint(0, 5, size=indices_shape)\n    with tf.Graph().as_default():\n        in1 = tf.placeholder(shape=inp_array1.shape, dtype=inp_array1.dtype)\n        out = tf.one_hot(in1, depth, on_value, off_value, axis, dtype=out_dtype)\n        compare_tf_with_tvm(inp_array1, in1.name, out.name)\n\n\ndef test_forward_one_hot():\n    _test_forward_one_hot((3,), 3, 1, 0, -1, \"int32\")\n    _test_forward_one_hot((3,), 3, 1.0, 0.0, -1, \"float32\")\n    _test_forward_one_hot((2, 2), 5, 2, -2, 0, \"int32\")\n    _test_forward_one_hot((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    _test_forward_one_hot((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n    _test_forward_one_hot((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\n#######################################################################\n# AddN\n# ----------------------\n\n\ndef _test_forward_add_n(inputs):\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        temp = []\n        for each in inputs:\n            temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))\n        output = tf.add_n(temp)\n        compare_tf_with_tvm(list(inputs), [each.name for each in temp], output.name)\n\n\ndef test_forward_add_n():\n    \"\"\"Add n\"\"\"\n    x = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n    y = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n    z = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n    m, n, o = x.astype(np.float32), y.astype(np.float32), z.astype(np.float32)\n    in0 = x\n    in1 = [x, y]\n    in2 = (x, y, z)\n    in3 = m\n    in4 = [m, n]\n    in5 = (m, n, o)\n    _test_forward_add_n(in0)\n    _test_forward_add_n(in1)\n    _test_forward_add_n(in2)\n    _test_forward_add_n(in3)\n    _test_forward_add_n(in4)\n    _test_forward_add_n(in5)\n\n\n#######################################################################\n# Sharing params case\n# ----------------------\n\n\ndef test_sharing_node():\n    \"\"\"Test the sharing params case.\"\"\"\n    np_data = np.random.uniform(size=(2, 2, 2)).astype(\"float32\")\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(tf.float32, shape=(2, 2, 2), name=\"in_data\")\n        axis = tf.constant([-1], dtype=tf.int32, name=\"axis\")\n        mean0 = tf.reduce_mean(in_data, axis=axis, keepdims=False, name=\"mean0\")\n        mean1 = tf.reduce_mean(in_data, axis=axis, keepdims=False, name=\"mean1\")\n        _ = tf.add(mean0, mean1, name=\"out\")\n        compare_tf_with_tvm([np_data], [\"in_data:0\"], \"out:0\")\n\n\n#######################################################################\n# Unravel Index\n# ----------------------\ndef _test_forward_unravel_index(inputs):\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        temp = []\n        for each in inputs:\n            temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))\n        output = tf.unravel_index(temp[0], temp[1])\n        compare_tf_with_tvm(list(inputs), [each.name for each in temp], output.name)\n\n\ndef _test_forward_unravel_index_scalar(x, y, dtype=\"int32\"):\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        indices_1 = constant_op.constant(x, dtype=dtype)\n        dims_1 = constant_op.constant(y, dtype=dtype)\n        out_1 = array_ops.unravel_index(indices_1, dims_1)\n        compare_tf_with_tvm([], [], out_1.name)\n\n\ndef test_forward_unravel_index():\n    \"\"\"Unravel index\"\"\"\n    x = np.array([0, 1, 2, 3])\n    y = np.array([2, 2])\n    _test_forward_unravel_index([x, y])\n\n    x = np.array([0, 1, 2, 5])\n    y = np.array([2, 3])\n    _test_forward_unravel_index([x, y])\n\n    x = np.array([0, 1, 2, 5])\n    y = np.array([6])\n    _test_forward_unravel_index([x, y])\n\n    x = np.array([102, 300, 16])\n    y = np.array([10, 10, 9, 6])\n    _test_forward_unravel_index([x, y])\n\n    x = np.array([100])\n    y = np.array([10, 10, 9, 6])\n    _test_forward_unravel_index([x, y])\n\n    # Test scalar input\n    _test_forward_unravel_index_scalar(13, [1, 4, 5, 2])\n\n\n#######################################################################\n# Dilation2d\n# ----------------------\ndef _test_dilation2d(tensor_in_sizes, filter_in_sizes, strides, dilations, padding):\n    \"\"\"One iteration of dilation2d with given shapes and attributes\"\"\"\n\n    total_size_1 = np.prod(tensor_in_sizes)\n    total_size_2 = np.prod(filter_in_sizes)\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n    filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\")\n        in_filter = constant_op.constant(filter_array, shape=filter_in_sizes, dtype=\"float32\")\n\n        nn_ops.dilation2d(in_data, in_filter, strides=strides, rates=dilations, padding=padding)\n\n        compare_tf_with_tvm(\n            np.reshape(data_array, tensor_in_sizes).astype(\"float32\"),\n            \"Placeholder:0\",\n            \"Dilation2D:0\",\n            no_gpu=True,\n        )\n\n\ndef test_forward_dilation():\n    \"\"\"Dilation2d\"\"\"\n    _test_dilation2d([1, 18, 18, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], \"VALID\")\n    _test_dilation2d([1, 15, 15, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], \"SAME\")\n    _test_dilation2d([1, 5, 5, 1], [2, 2, 1], [1, 1, 1, 1], [1, 1, 1, 1], \"VALID\")\n    _test_dilation2d([1, 5, 5, 1], [3, 3, 1], [1, 1, 1, 1], [1, 2, 2, 1], \"VALID\")\n    _test_dilation2d([1, 5, 5, 3], [3, 3, 3], [1, 1, 1, 1], [1, 1, 1, 1], \"SAME\")\n    _test_dilation2d([1, 28, 28, 3], [5, 5, 3], [1, 2, 2, 1], [1, 1, 1, 1], \"VALID\")\n    _test_dilation2d([1, 224, 224, 10], [8, 8, 10], [1, 1, 1, 1], [1, 1, 1, 1], \"VALID\")\n    _test_dilation2d([1, 18, 18, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], \"SAME\")\n    _test_dilation2d([1, 15, 15, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], \"VALID\")\n    _test_dilation2d([1, 5, 5, 1], [7, 2, 1], [1, 3, 1, 1], [1, 1, 1, 1], \"SAME\")\n    _test_dilation2d([1, 5, 5, 1], [3, 4, 1], [1, 2, 1, 1], [1, 2, 2, 1], \"SAME\")\n    _test_dilation2d([1, 5, 5, 3], [3, 3, 3], [1, 1, 4, 1], [1, 1, 1, 1], \"VALID\")\n    _test_dilation2d([1, 28, 28, 3], [5, 6, 3], [1, 1, 2, 1], [1, 1, 1, 1], \"SAME\")\n    _test_dilation2d([1, 224, 224, 10], [8, 8, 10], [1, 3, 1, 1], [1, 1, 1, 1], \"SAME\")\n    _test_dilation2d([1, 3, 3, 1], [2, 2, 1], [1, 1, 1, 1], [1, 2, 2, 1], \"SAME\")\n    _test_dilation2d([1, 3, 3, 1], [2, 2, 1], [1, 1, 1, 1], [1, 1, 2, 1], \"VALID\")\n\n\ndef _test_identityn(data_np_list):\n    with tf.Graph().as_default():\n        data_tensors = []\n        data_tensors_name = []\n        for index, data_np in enumerate(data_np_list):\n            tensor_name = f\"data_{index}\"\n            data_tensors_name.append(tensor_name + \":0\")\n            data_tensors.append(\n                tf.placeholder(shape=data_np.shape, dtype=str(data_np.dtype), name=tensor_name)\n            )\n\n        output = tf.identity_n(data_tensors)\n        output_names = [out.name for out in output]\n        compare_tf_with_tvm(\n            data_np_list,\n            data_tensors_name,\n            output_names,\n        )\n\n\n@pytest.mark.parametrize(\n    \"data_np_list\",\n    [\n        (\n            [\n                np.array([[1, 1], [0, 3], [0, 1], [2, 0], [3, 1]], dtype=np.int64),\n                np.array([1, 2, 3, 4, 5], dtype=np.int64),\n                np.array([5, 6], dtype=np.int64),\n            ]\n        ),\n        (\n            [\n                np.array([[1, 1], [0, 3], [2, 0], [3, 1]], dtype=np.int64),\n                np.array([1, 2, 3, 4], dtype=np.int64),\n                np.array([5, 6], dtype=np.int64),\n                np.array([True, False, True]),\n            ]\n        ),\n        (\n            [\n                np.array([]),\n                np.array([[]]),\n            ]\n        ),\n    ],\n)\ndef test_forward_identityn(data_np_list):\n    \"\"\"Identityn\"\"\"\n    _test_identityn(data_np_list)\n\n\n#######################################################################\n# infinity ops\n# ------------\ndef _verify_infiniteness_ops(tf_op, name):\n    \"\"\"test operator infinity ops\"\"\"\n\n    # Only float types are allowed in Tensorflow for isfinite and isinf\n    # float16 is failing on cuda\n    tf_dtypes = [\"float32\", \"float64\"]  # pylint: disable=redefined-outer-name\n    for tf_dtype in tf_dtypes:\n        shape = (8, 8)\n        data = np.random.uniform(size=shape).astype(tf_dtype)\n        data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.infty\n        data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.nan\n\n        tf.reset_default_graph()\n        in_data = tf.placeholder(tf_dtype, shape, name=\"in_data\")\n        tf_op(in_data, name=name)\n        compare_tf_with_tvm([data], [\"in_data:0\"], f\"{name}:0\")\n\n\ndef test_forward_isinf():\n    _verify_infiniteness_ops(tf.is_inf, \"isinf\")\n\n\ndef test_forward_isfinite():\n    _verify_infiniteness_ops(tf.is_finite, \"isfinite\")\n\n\ndef test_forward_isnan():\n    _verify_infiniteness_ops(tf.is_nan, \"isnan\")\n\n\ndef _test_spop_placeholder_without_shape_info():\n    with tf.Graph().as_default():\n\n        @function.Defun(*[tf.int32] * 2)\n        def Forward(x, y):\n            print(x.name)\n            print(y.name)\n            b = tf.add(x, y)\n            return b\n\n        pl1 = tf.placeholder(tf.int32, name=\"pl1\")\n        pl2 = tf.placeholder(tf.int32, name=\"pl2\")\n        pl3 = tf.placeholder(tf.int32, name=\"pl3\")\n        data = np.array([[-1, 1], [2, -2]], dtype=np.int32)\n        data2 = np.array([[-2, 3], [4, -6]], dtype=np.int32)\n        data3 = np.array([[-2, 3], [4, -6]], dtype=np.int32)\n        z1 = gen_functional_ops.StatefulPartitionedCall(args=[pl1, pl2], Tout=[tf.int32], f=Forward)\n        z2 = z1 + pl3\n        compare_tf_with_tvm(\n            [data, data2, data3],\n            [\"pl1:0\", \"pl2:0\", \"pl3:0\"],\n            [\"StatefulPartitionedCall:0\", z2.name],\n            mode=\"vm\",\n            init_global_variables=True,\n        )\n\n\ndef _test_spop_placeholder_with_shape_and_default_value():\n    with tf.Graph().as_default():\n        data = np.ones([1], dtype=int).astype(np.int32)\n        dataVar = tf.Variable(data, shape=data.shape)\n        pl1 = array_ops.placeholder_with_default(dataVar, shape=data.shape, name=\"pl1\")\n        tpl = tf.convert_to_tensor(pl1, dtype=tf.int32)\n\n        @function.Defun(*[tf.int32])\n        def pl_with_default(pl):\n            return tf.expand_dims(tf.multiply(pl, pl), 0)\n\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[tpl], Tout=[tf.int32], f=pl_with_default\n        )\n        compare_tf_with_tvm(\n            data, [\"pl1:0\"], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_placeholder_numpy_arange_feed():\n    with tf.Graph().as_default():\n        t1 = tf.placeholder(tf.int32, (3, 3, 3), \"t1\")\n        t1_data = np.arange(27, dtype=np.int32).reshape((3, 3, 3))\n        t2 = tf.placeholder(tf.int32, (3, 3, 3), \"t2\")\n        t2_data = np.arange(27, dtype=np.int32).reshape((3, 3, 3))\n\n        @tf.function\n        def add(x, y):\n            return tf.add(x, y, \"add_t1_t2\")\n\n        t3 = add(t1, t2)\n        compare_tf_with_tvm(\n            [t1_data, t2_data], [\"t1:0\", \"t2:0\"], [t3.name], mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_placeholder_numpy_array_feed():\n    with tf.Graph().as_default():\n        t1_data = np.array([[-1, 1, 3], [2, -2, 4], [2, -3, 14]], dtype=np.int32)\n        t2_data = np.array([[-2, 1, 2], [12, -2, 14], [12, -3, 4]], dtype=np.int32)\n        t1 = tf.placeholder(tf.int32, name=\"t1\")\n        t2 = tf.placeholder(tf.int32, name=\"t2\")\n\n        @tf.function\n        def add(x, y):\n            return tf.add(x, y, \"add_t1_t2\")\n\n        t3 = add(t1, t2)\n        compare_tf_with_tvm(\n            [t1_data, t2_data], [\"t1:0\", \"t2:0\"], [t3.name], mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_function_invocation_basic():\n    with tf.Graph().as_default():\n\n        def fun1(a):\n            return tf.multiply(a, a)\n\n        def fun2(b):\n            return tf.multiply(b, 10)\n\n        @tf.function\n        def fun3(x, y):\n            x = fun2(x)\n            y = fun1(y)\n            z = tf.add(x, y)\n            return z\n\n        t3 = fun3(tf.constant(10.5), tf.constant(20.4))\n\n        compare_tf_with_tvm([], [], [t3.name], mode=\"vm\", init_global_variables=True)\n\n\ndef _test_spop_function_invocation_nested():\n    with tf.Graph().as_default():\n        t1 = tf.placeholder(tf.int32, (3, 3, 3), name=\"t1\")\n        t1_data = np.arange(27, dtype=np.int32).reshape((3, 3, 3))\n        t2 = tf.placeholder(tf.int32, name=\"t2\")\n        t2_data = np.arange(27, dtype=np.int32).reshape((3, 3, 3))\n\n        @tf.function\n        def myfunc(x, y):\n            return tf.add(x, y, \"myfunc\")\n\n        @tf.function\n        def myfunc2(x, y):\n            z = myfunc(x, y)\n            l = myfunc(z, y)\n            m = myfunc(l, z)\n            return tf.add(l, m, \"myfunc2\")\n\n        res1 = myfunc(t1, t2)\n        res2 = myfunc2(res1, t1)\n\n        compare_tf_with_tvm(\n            [t1_data, t2_data], [\"t1:0\", \"t2:0\"], [res2.name], mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_function_invocation_no_autograph():\n    with tf.Graph().as_default():\n\n        @tf.function(autograph=False)\n        def fun1(a):\n            return tf.multiply(a, a)\n\n        @tf.function(autograph=False)\n        def fun2(b):\n            return tf.multiply(b, 10)\n\n        @tf.function\n        def fun3(x, y):\n            x = fun2(x)\n            y = fun1(y)\n            z = tf.add(x, y)\n            return z\n\n        t3 = fun3(tf.constant(10.5), tf.constant(20.4))\n\n        compare_tf_with_tvm([], [], [t3.name], mode=\"vm\", init_global_variables=True)\n\n\ndef _test_spop_function_invocation_defun():\n    with tf.Graph().as_default():\n\n        def fun1(a):\n            return tf.multiply(a, a)\n\n        def fun2(b):\n            return tf.multiply(b, b)\n\n        @function.Defun(dtypes.float32, dtypes.float32, func_name=\"Fun3\")\n        def fun3(x, y):\n            x = fun2(x)\n            y = fun1(y)\n            z = tf.add(x, y)\n            return z\n\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[tf.constant(10.5), tf.constant(20.4)],\n            Tout=[dtypes.float32],\n            f=fun3,\n            name=\"SpopFnInvocation\",\n        )\n        compare_tf_with_tvm([], [], \"SpopFnInvocation:0\", mode=\"vm\", init_global_variables=True)\n\n\ndef _test_spop_arithmetic():\n    with tf.Graph().as_default():\n\n        @function.Defun(*[dtypes.int32] * 3)\n        def arithmetic(m, x, c):\n            z = tf.add(tf.multiply(m, x), c)\n            return z\n\n        m = tf.constant(10)\n        x = tf.constant(20)\n        c = tf.constant(2)\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[m, x, c], Tout=[tf.int32], f=arithmetic\n        )\n\n        compare_tf_with_tvm(\n            [], [], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_control_flow():\n    with tf.Graph().as_default():\n\n        @function.Defun(*[dtypes.float32] * 2)\n        def Body1(x, y):\n            with ops.device(\"/job:localhost/replica:0/task:0/device:CPU:0\"):\n                z = math_ops.multiply(x, y)\n                i = 0\n                while i < 10:\n                    i += 1\n                    if i == 5:\n                        continue\n                    z = math_ops.multiply(x, y * i)\n            return z\n\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[constant_op.constant(32.0), constant_op.constant(100.0)],\n            Tout=[dtypes.float32],\n            f=Body1,\n        )\n        compare_tf_with_tvm(\n            [], [], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_variables():\n    with tf.Graph().as_default():\n        const1 = tf.constant(10)\n        const2 = tf.constant(20)\n        var1 = tf.Variable(const1, dtype=tf.int32)\n        var2 = tf.Variable(const2, dtype=tf.int32)\n\n        @function.Defun(tf.int32, tf.int32)\n        def Forward(x, y):\n            return tf.multiply(x, y)\n\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[var1, var2], Tout=[tf.int32], f=Forward\n        )\n        compare_tf_with_tvm(\n            [], [], \"StatefulPartitionedCall:0\", init_global_variables=True, mode=\"vm\"\n        )\n\n\ndef _test_spop_constants():\n    with tf.Graph().as_default():\n\n        @function.Defun(*[dtypes.int32] * 2)\n        def constantsFn(x, y):\n            vv = tf.constant([2, 3, 4], name=\"vv\")\n            z = tf.add(vv + x, y)\n            return z\n\n        a = tf.constant(20000, name=\"a\")\n        b = tf.constant(40000, name=\"b\")\n        _ = gen_functional_ops.StatefulPartitionedCall(args=[a, b], Tout=[tf.int32], f=constantsFn)\n\n        compare_tf_with_tvm(\n            [], [], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n        )\n\n\ndef _test_spop_stateful():\n    # This test case is to test that TVM rejects any TF stateful operations\n    # (including Resource Variables) except StatefulPartitionedCall/PartitionedCall\n    # (as these two operators can still be used as container graphs to execute\n    # \"stateless\" operations internally.\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n\n        @tf.function\n        def FunctionWithStatefulOp_One(i):\n            b = tf.random.uniform(shape=[2, 4], maxval=10, dtype=tf.float32, seed=10)\n            y = tf.multiply(b, i)\n            return y\n\n        @tf.function\n        def FunctionWithStatefulOp(m, n):\n            a = tf.random.uniform(shape=[2, 4], maxval=10, dtype=tf.float32, seed=10)\n            x = tf.multiply(a, m)\n            y = FunctionWithStatefulOp_One(n)\n            z = tf.multiply(x, y)\n            return z\n\n        op = FunctionWithStatefulOp(constant_op.constant(1.0), constant_op.constant(2.0))\n        with pytest.raises(Exception) as execinfo:\n            compare_tf_with_tvm([], [], [op.name], init_global_variables=True, mode=\"vm\")\n        assert execinfo.value.args[0].startswith(\"The following operators are not implemented\")\n\n\ndef _test_spop_device_assignment():\n    # This test case is to test that TVM rejects inconsistent device assignment\n    # while using StatefulPartitionedCall/PartitionedCall operators which in case of TVM will\n    # be used as container graphs to internally execute \"stateless\" operations.\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n\n        def fun1(a):\n            with ops.device(\"/GPU:0\"):\n                return tf.multiply(a, a)\n\n        def fun2(b):\n            with ops.device(\"/job:localhost/replica:0/task:0/device:CPU:1\"):\n                return tf.multiply(b, b)\n\n        @function.Defun(dtypes.float32, dtypes.float32, func_name=\"Fun3\")\n        def fun3(x, y):\n            with ops.device(\"/CPU:0\"):\n                x = fun2(x)\n            with ops.device(\"/job:localhost/replica:0/task:0/device:CPU:2\"):\n                y = fun1(y)\n            with ops.device(\"/job:localhost/replica:0/task:0/device:CPU:3\"):\n                z = tf.add(x, y)\n                return z\n\n        _ = gen_functional_ops.StatefulPartitionedCall(\n            args=[tf.constant(10.5), tf.constant(20.4)], Tout=[dtypes.float32], f=fun3\n        )\n        with pytest.raises(Exception) as execinfo:\n            compare_tf_with_tvm(\n                [], [], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n            )\n        assert execinfo.value.args[0].startswith(\"Found inconsistent Device assignment\")\n\n\ndef _test_spop_resource_variables():\n    # This test case is to test that TVM rejects any graph containing\n    # resource variables with StatefulPartitionedOp.\n\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n\n        const1 = tf.constant(10)\n        const2 = tf.constant(20)\n        var1 = tf.Variable(const1, dtype=tf.int32, use_resource=True)\n        var2 = tf.Variable(const2, dtype=tf.int32, use_resource=True)\n\n        @tf.function\n        def resourceVariablesTest(x, y):\n            return tf.multiply(x, y)\n\n        _ = resourceVariablesTest(var1, var2)\n        with pytest.raises(Exception) as execinfo:\n            compare_tf_with_tvm(\n                [], [], \"StatefulPartitionedCall:0\", mode=\"vm\", init_global_variables=True\n            )\n        # pylint: disable=implicit-str-concat\n        assert execinfo.value.args[0].startswith(\"Graph is not frozen.\" \" Provide a frozen graph\")\n\n\ndef test_forward_spop():\n    \"\"\"Spop\"\"\"\n    _test_spop_stateful()\n    _test_spop_device_assignment()\n    # tensorflow version upgrade support\n    # This test is expected to fail in TF version >= 2.6\n    # as the generated graph will be considered frozen, hence\n    # not passing the criteria for the test below.\n    if tf.__version__ < LooseVersion(\"2.6.1\"):\n        _test_spop_resource_variables()\n\n    # Placeholder test cases\n    _test_spop_placeholder_without_shape_info()\n    _test_spop_placeholder_with_shape_and_default_value()\n    _test_spop_placeholder_numpy_arange_feed()\n    _test_spop_placeholder_numpy_array_feed()\n\n    # Function Invocation test cases\n    _test_spop_function_invocation_basic()\n    _test_spop_function_invocation_nested()\n    _test_spop_function_invocation_no_autograph()\n    _test_spop_function_invocation_defun()\n\n    # Test cases for various other TF constructs\n    _test_spop_arithmetic()\n    _test_spop_control_flow()\n    _test_spop_variables()\n    _test_spop_constants()\n\n\n#######################################################################\n# Dynamic input shape\n# -------------------\ndef test_forward_dynamic_input_shape():\n    \"\"\"Dynamic input shape\"\"\"\n    tf.reset_default_graph()\n\n    with tf.Graph().as_default():\n        data = tf.placeholder(tf.float32, name=\"data\", shape=(None,))\n        _ = data + 1\n        np_data = np.random.uniform(size=(2,)).astype(\"float32\")\n        out_name = \"add\"\n\n        with tf.Session() as sess:\n            graph_def = tf_testing.AddShapesToGraphDef(sess, out_name)\n            tf_output = run_tf_graph(sess, np_data, \"data:0\", [f\"{out_name}:0\"])\n            # TODO(kevinthesun): enable gpu test when VM heterogeneous execution is ready.\n            for device in [\"llvm\"]:\n                _ = tvm.device(device, 0)\n                if not tvm.testing.device_enabled(device):\n                    print(f\"Skip because {device} is not enabled\")\n                    continue\n                tvm_output = run_tvm_graph(\n                    graph_def,\n                    np_data,\n                    [\"data\"],\n                    1,\n                    target=device,\n                    layout=\"NCHW\",\n                    out_names=[out_name],\n                    mode=\"vm\",\n                    ignore_in_shape=True,\n                )\n                tvm.testing.assert_allclose(tvm_output[0], tf_output[0], rtol=1e-5, atol=1e-5)\n\n\ndef test_forward_dynmaic_rnn_lstmblockcell():\n    \"\"\"Dynmaic rnn lstmblockcell\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.0.0\"):\n        return\n\n    total_series_length = 50000\n    truncated_backprop_length = 15\n    state_size = 4\n    echo_step = 3\n    batch_size = 5\n    num_layers = 5\n\n    def generateData():\n        x = np.array(np.random.choice(2, total_series_length, p=[0.5, 0.5]))\n        y = np.roll(x, echo_step)\n        y[0:echo_step] = 0\n\n        x = x.reshape((batch_size, -1))  # The first index changing slowest, subseries as rows\n        y = y.reshape((batch_size, -1))\n\n        return (x, y)\n\n    batchX_placeholder = tf.placeholder(tf.float32, [batch_size, truncated_backprop_length])\n\n    init_state = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])\n\n    state_per_layer_list = tf.unstack(init_state, axis=0)\n    rnn_tuple_state = tuple(\n        list(\n            tf.nn.rnn_cell.LSTMStateTuple(\n                state_per_layer_list[idx][0], state_per_layer_list[idx][1]\n            )\n            for idx in range(num_layers)\n        )\n    )\n\n    # Forward passes\n    def lstm_cell():\n        return tensorflow.contrib.rnn.LSTMBlockCell(state_size)\n\n    cell = tf.nn.rnn_cell.MultiRNNCell(\n        [lstm_cell() for _ in range(num_layers)], state_is_tuple=True\n    )\n    states_series, current_state = tf.nn.dynamic_rnn(\n        cell, tf.expand_dims(batchX_placeholder, -1), initial_state=rnn_tuple_state\n    )\n\n    with tf.Session() as sess:\n        sess.run(tf.global_variables_initializer())\n        x, _ = generateData()\n        _current_state = np.zeros((num_layers, 2, batch_size, state_size))\n\n        start_idx = 0\n        end_idx = start_idx + truncated_backprop_length\n\n        batchX = x[:, start_idx:end_idx]\n\n        # Save current state for TVM\n        current_state_tvm = _current_state\n\n        _current_state, _states_series = sess.run(\n            [current_state, states_series],\n            feed_dict={batchX_placeholder: batchX, init_state: _current_state},\n        )\n\n        # Organize results and corresponding names\n        tf_output = [_states_series]\n\n        for c in _current_state:\n            tf_output.append(c.c)\n            tf_output.append(c.h)\n\n        name = [states_series.name.split(\":\")[0]]\n\n        for t in current_state:\n            name.append(t.c.name.split(\":\")[0])\n            name.append(t.h.name.split(\":\")[0])\n\n        graph_def = sess.graph.as_graph_def(add_shapes=True)\n\n        final_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, name)\n\n        _ = run_tvm_graph(\n            final_graph_def,\n            [batchX.astype(\"float32\"), current_state_tvm.astype(\"float32\")],\n            [\"Placeholder\", \"Placeholder_1\"],\n            out_names=name,\n            num_output=len(name),\n            mode=\"vm\",\n            disabled_pass=[\"FoldScaleAxis\"],\n        )\n\n        # Compare result\n        for _, tf_out in enumerate(tf_output):\n            tvm.testing.assert_allclose(tf_out, tf_out, atol=1e-5, rtol=1e-5)\n\n\n#######################################################################\n# Unique\n# ------------\n\n\ndef _test_unique(n, dtype, is_dyn):\n    tf.reset_default_graph()\n    np_data = np.random.randint(100, size=n).astype(dtype)\n    with tf.Graph().as_default():\n        if is_dyn:\n            in_data = tf.placeholder(dtype, [n], name=\"in_data\")\n        else:\n            in_data = tf.constant(np_data, dtype, name=\"in_data\")\n        tf.unique(in_data)\n        if is_dyn:\n            compare_tf_with_tvm(np_data, \"in_data:0\", [\"Unique:0\", \"Unique:1\"], mode=\"vm\")\n        else:\n            compare_tf_with_tvm(np_data, \"\", [\"Unique:0\", \"Unique:1\"], mode=\"vm\")\n\n\ndef test_forward_unique():\n    \"\"\"test Unique\"\"\"\n\n    for dtype in [\"int32\", \"int64\"]:\n        for is_dyn in [False, True]:\n            _test_unique(50, dtype, is_dyn)\n            _test_unique(100, dtype, is_dyn)\n\n\n#######################################################################\n# Unique with counts\n# ------------\n\n\ndef _test_unique_with_counts(n, dtype, is_dyn):\n    tf.reset_default_graph()\n    np_data = np.random.randint(100, size=n).astype(dtype)\n    with tf.Graph().as_default():\n        if is_dyn:\n            in_data = tf.placeholder(dtype, [n], name=\"in_data\")\n        else:\n            in_data = tf.constant(np_data, dtype, name=\"in_data\")\n        tf.unique_with_counts(in_data)\n        if is_dyn:\n            compare_tf_with_tvm(\n                np_data,\n                \"in_data:0\",\n                [\"UniqueWithCounts:0\", \"UniqueWithCounts:1\", \"UniqueWithCounts:2\"],\n                mode=\"vm\",\n            )\n        else:\n            compare_tf_with_tvm(\n                np_data,\n                \"\",\n                [\"UniqueWithCounts:0\", \"UniqueWithCounts:1\", \"UniqueWithCounts:2\"],\n                mode=\"vm\",\n            )\n\n\ndef test_forward_unique_with_counts():\n    \"\"\"test UniqueWithCounts\"\"\"\n\n    for dtype in [\"int32\", \"int64\"]:\n        for is_dyn in [False, True]:\n            _test_unique_with_counts(10, dtype, is_dyn)\n            _test_unique_with_counts(20, dtype, is_dyn)\n\n\n#######################################################################\n# check graph ir for nn.moments\n# ------------\n\n\ndef test_moments():\n    \"\"\"NN.moments\"\"\"\n    g = tf.Graph()\n    shape = [4, 176, 8, 8]\n    dtype = \"float32\"\n    with g.as_default():\n        A = tf.placeholder(shape=shape, dtype=dtype, name=\"A\")\n        _ = tf.placeholder(shape=shape, dtype=dtype, name=\"B\")\n        mean, variance = tf.nn.moments(A, [1], keep_dims=True)\n        _ = (A - mean) / tf.sqrt(variance + 0.0005)\n\n    mod, _ = from_tensorflow(g.as_graph_def(add_shapes=True))\n    program = \"\"\"\n    def @main(%A: Tensor[(4, 176, 8, 8), float32]) {\n        %527 = mean(%A, axis=[1], keepdims=True) /* moments/mean */;\n        %528 = subtract(%A, %527) /* sub */;\n        %529 = subtract(%A, %527);\n        %530 = multiply(%529, %529) /* moments/SquaredDifference */;\n        %531 = mean(%530, axis=[1], keepdims=True) /* moments/variance */;\n        %532 = add(%531, 0.0005f) /* add */;\n        %533 = sqrt(%532) /* Sqrt */;\n        divide(%528, %533) /* truediv */\n    }\n    \"\"\"\n    mod_golden = tvm.parser.parse('#[version = \"0.0.5\"]\\n' + program)\n    tvm.ir.assert_structural_equal(mod[\"main\"].body, mod_golden[\"main\"].body, map_free_vars=True)\n\n\n#######################################################################\n# invert_permutation\n# --------------------\n\n\ndef test_invert_permutation():\n    \"\"\"test InvertPermutation\"\"\"\n    tf.reset_default_graph()\n\n    input_shape = [6]\n    x = np.array([3, 4, 0, 2, 1, 5]).astype(\"int32\")\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(shape=input_shape, dtype=\"int32\")\n        tf.invert_permutation(in_data)\n        out_name = \"InvertPermutation:0\"\n        compare_tf_with_tvm(x, \"Placeholder:0\", out_name, no_gpu=False)\n\n\n#######################################################################\n# Bincount\n# ----\n\n\ndef _test_bincount(in_shape, size, weights):\n    with tf.Graph().as_default():\n        inputs = []\n        data = []\n        inputs.append(tf.placeholder(shape=in_shape, dtype=\"int32\", name=\"input0\"))\n        data.append(np.random.uniform(0, size, size=in_shape).astype(\"int32\"))\n        inputs.append(tf.placeholder(shape=(), dtype=\"int32\", name=\"size\"))\n        data.append(np.array(size, \"int32\"))\n        if weights:\n            inputs.append(tf.placeholder(shape=in_shape, dtype=\"float32\", name=\"weights\"))\n            data.append(np.reshape(weights, in_shape).astype(\"float32\"))\n        else:\n            inputs.append(tf.placeholder(shape=(0,), dtype=\"float32\", name=\"weights\"))\n            data.append(np.array([], \"float32\"))\n        result = tf.raw_ops.Bincount(arr=data[0], size=data[1], weights=data[2])\n        compare_tf_with_tvm(data, [a.name for a in inputs], result.name, mode=\"vm\")\n\n\ndef test_forward_bincount():\n    \"\"\"Test Bincount Op\"\"\"\n    # 2D input\n    _test_bincount((3, 10), 20, [1.0] * 30)\n    _test_bincount((3, 10), 20, [1.5] * 30)\n    _test_bincount((3, 10), 20, None)\n    # 1D input\n    _test_bincount((10,), 20, [1.0] * 10)\n    _test_bincount((10,), 20, [1.5] * 10)\n    _test_bincount((10,), 20, None)\n\n\n#######################################################################\n# DenseBincount\n# ----\n\n\ndef _test_dense_bincount(in_shape, size, weights, binary_output):\n    with tf.Graph().as_default():\n        inputs = []\n        data = []\n        inputs.append(tf.placeholder(shape=in_shape, dtype=\"int32\", name=\"input0\"))\n        data.append(np.random.uniform(0, size, size=in_shape).astype(\"int32\"))\n        inputs.append(tf.placeholder(shape=(), dtype=\"int32\", name=\"size\"))\n        data.append(np.array(size, \"int32\"))\n        if weights:\n            inputs.append(tf.placeholder(shape=in_shape, dtype=\"float32\", name=\"weights\"))\n            data.append(np.reshape(weights, in_shape).astype(\"float32\"))\n        else:\n            inputs.append(tf.placeholder(shape=(0,), dtype=\"float32\", name=\"weights\"))\n            data.append(np.array([], \"float32\"))\n        result = tf.raw_ops.DenseBincount(\n            input=data[0],\n            size=data[1],\n            weights=data[2],\n            binary_output=binary_output,\n        )\n        compare_tf_with_tvm(data, [a.name for a in inputs], result.name, mode=\"vm\")\n\n\ndef test_forward_dense_bincount():\n    \"\"\"Test DenseBincount Op\"\"\"\n    for binary_output in [False, True]:\n        # 2D input\n        _test_dense_bincount((3, 10), 20, [1.0] * 30, binary_output)\n        _test_dense_bincount((3, 10), 20, [1.5] * 30, binary_output)\n        _test_dense_bincount((3, 10), 20, None, binary_output)\n        # 1D input\n        _test_dense_bincount((10,), 20, [1.0] * 10, binary_output)\n        _test_dense_bincount((10,), 20, [1.5] * 10, binary_output)\n        _test_dense_bincount((10,), 20, None, binary_output)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow/test_no_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for converting TensorFlow debugging ops to Relay.\"\"\"\ntry:\n    import tensorflow.compat.v1 as tf\n\n    tf.disable_v2_behavior()\nexcept ImportError:\n    import tensorflow as tf\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay.frontend.tensorflow import from_tensorflow\n\n\ndef run_relay(graph):\n    mod, params = from_tensorflow(graph.as_graph_def(add_shapes=True))\n    return relay.create_executor(\"debug\", mod=mod).evaluate()(**params)\n\n\ndef test_no_op():\n    g = tf.Graph()\n    with g.as_default():\n        no_op = tf.no_op()\n        with tf.Session() as sess:\n            # In TF, the type of a no-op is None.\n            assert sess.run(no_op) is None\n\n        # In TVM, no-op is currently translated to 0, though it should\n        # probably be none or an empty tuple.\n        np.testing.assert_allclose(0, run_relay(g).numpy())\n\n\nif __name__ == \"__main__\":\n    test_no_op()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow2/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n# pylint: disable=import-outside-toplevel, redefined-builtin\n\"\"\"TF2 to relay converter test utilities\"\"\"\n\nimport tvm\nfrom tvm import relay\n\nfrom tvm.runtime.vm import VirtualMachine\nimport tvm.contrib.graph_executor as runtime\nfrom tvm.relay.frontend.tensorflow2 import from_tensorflow\nimport tvm.testing\nfrom tvm.relay.testing.tf import vmobj_to_list as vmobj_to_list\n\nimport tensorflow as tf\nfrom tensorflow.python.eager.def_function import Function\n\n\ndef run_tf_code(func, input_):\n    if type(func) is Function:\n        f_out = func(input_)\n        if isinstance(f_out, (list, tuple)):\n            np_out = [x.numpy() for x in f_out]\n        else:\n            np_out = [f_out.numpy()]\n    else:\n        f_out = func(tf.constant(input_))\n        if type(f_out) is dict:\n            np_out = [f_out[k].numpy() for k in sorted(f_out.keys())]\n        elif type(f_out) is list:\n            np_out = [x.numpy() for x in f_out]\n        else:\n            np_out = f_out.numpy()\n    return np_out\n\n\ndef compile_graph_executor(mod, params, target=\"llvm\", target_host=\"llvm\", opt_level=3):\n    with tvm.transform.PassContext(opt_level):\n        lib = relay.build(mod, target=tvm.target.Target(target, host=target_host), params=params)\n    return lib\n\n\ndef compile_vm(mod, params, target=\"llvm\", target_host=\"llvm\", opt_level=3, disabled_pass=None):\n    with tvm.transform.PassContext(opt_level, disabled_pass=disabled_pass):\n        vm_exec = relay.vm.compile(\n            mod, target=tvm.target.Target(target, host=target_host), params=params\n        )\n    return vm_exec\n\n\ndef run_vm(vm_exec, input_, ctx=tvm.cpu(0)):\n    vm = VirtualMachine(vm_exec, ctx)\n    _out = vm.invoke(\"main\", input_)\n    return vmobj_to_list(_out)\n\n\ndef run_graph_executor(lib, input_, ctx=tvm.cpu(0)):\n    mod = runtime.GraphModule(lib[\"default\"](ctx))\n    mod.set_input(0, input_)\n    mod.run()\n    return [mod.get_output(i).numpy() for i in range(mod.get_num_outputs())]\n\n\ndef compare_tf_tvm(gdef, input_, output_, runtime=\"vm\", output_tensors=None):\n    \"\"\"compare tf and tvm execution for the same input.\n\n    Parameters\n    ----------\n    gdef: TF2 graph def extracted to be fed into from_tensorflow parser.\n    (https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)\n\n    input_: a single numpy array object\n\n    output_: the expected output from TF to match TVM output with\n\n    runtime: choose TVM runtime; either \"vm\" for VirtualMachine or \"graph\" for GraphExecutor\n\n    output_tensors : List of output tensor names (Optional)\n            if not specified then the last node is assumed as graph output.\n    \"\"\"\n    mod, params = from_tensorflow(gdef, outputs=output_tensors)\n    if runtime == \"vm\":\n        exec_ = compile_vm(mod, params)\n        tvm_out = run_vm(exec_, input_)\n    elif runtime == \"graph\":\n        lib = compile_graph_executor(mod, params)\n        tvm_out = run_graph_executor(lib, input_)\n    else:\n        raise RuntimeError(\"Runtime input not supported: %s\" % runtime)\n\n    tvm.testing.assert_allclose(output_, tvm_out, atol=1e-5)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow2/test_functional_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n# pylint: disable=import-outside-toplevel, redefined-builtin\n\"\"\"TF2 to relay converter test: tests basic examples\"\"\"\n\nimport tempfile\nimport tensorflow as tf\nimport numpy as np\nimport pytest\nfrom common import compare_tf_tvm\nfrom common import run_tf_code\n\n\ndef _function_graph(TestClass):\n    f = TestClass().func\n    gdef = f.get_concrete_function().graph.as_graph_def()\n    gdef_ops = list(set([n.op for n in gdef.node]))\n    input_ = TestClass().get_input()\n    output = run_tf_code(f, input_)\n    return gdef, input_, output\n\n\ndef _model_graph(TestClass):\n    model = TestClass()\n    with tempfile.TemporaryDirectory() as model_path:\n        tf.saved_model.save(model, model_path)\n        imported = tf.saved_model.load(model_path)\n\n    f = imported.signatures[\"serving_default\"]\n    gdef = f.graph.as_graph_def(add_shapes=True)\n\n    input_ = model.get_input()\n    output = run_tf_code(f, input_)\n    return gdef, input_, output\n\n\ndef run_func_graph(TestClass, runtime=\"vm\", outputs=None):\n    compare_tf_tvm(*_function_graph(TestClass), runtime=runtime, output_tensors=outputs)\n\n\ndef run_model_graph(TestClass, outputs=None):\n    compare_tf_tvm(*_model_graph(TestClass), runtime=\"vm\", output_tensors=outputs)\n\n\ndef run_all(TestClass):\n    run_model_graph(TestClass)\n    for runtime_ in [\"vm\", \"graph\"]:\n        run_func_graph(TestClass, runtime=runtime_)\n\n\ndef test_add_one():\n    class AddOne(tf.Module):\n        \"\"\"simple function to test x=x+1; scalar as input\"\"\"\n\n        def get_input(self):\n            return np.array(1.0, dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(), dtype=tf.float32)])\n        def func(self, x):\n            return x + 1\n\n    run_all(AddOne)\n\n\ndef test_add_one_2d():\n    class AddOne2D(tf.Module):\n        \"\"\"2D array as input\"\"\"\n\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            return x + 1\n\n    run_all(AddOne2D)\n\n\ndef test_add_one_2d_constant():\n    class AddOne2DConstant(tf.Module):\n        \"\"\"2D array as input with 2D constant as well; 2D constant stored in params after convert\"\"\"\n\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            return x + np.ones((2, 2), dtype=\"float32\")\n\n    run_all(AddOne2DConstant)\n\n\ndef test_sub_one_2d_constant():\n    class SubOne2DConstant(tf.Module):\n        \"\"\"2D array as input with 2D constant as well; 2D constant stored in params after convert\"\"\"\n\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            return x - np.ones((2, 2), dtype=\"float32\")\n\n    run_all(SubOne2DConstant)\n\n\ndef test_mul_one_2d_constant():\n    class MulOne2DConstant(tf.Module):\n        \"\"\"2D array as input with 2D constant as well; 2D constant stored in params after convert\"\"\"\n\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            return x * np.ones((2, 2), dtype=\"float32\")\n\n    run_all(MulOne2DConstant)\n\n\ndef test_div_one_2d_constant():\n    class DivOne2DConstant(tf.Module):\n        \"\"\"2D array as input with 2D constant as well; 2D constant stored in params after convert\"\"\"\n\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            return x / np.ones((2, 2), dtype=\"float32\")\n\n    run_all(DivOne2DConstant)\n\n\ndef test_strided_slice():\n    class StridedSlice(tf.Module):\n        def get_input(self):\n            return np.ones((3, 2, 3), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(3, 2, 3), dtype=tf.float32)])\n        def func(self, x):\n            return tf.strided_slice(x, [1, 0, 0], [2, 1, 3], [1, 1, 1])\n\n    run_all(StridedSlice)\n\n\ndef test_split():\n    class Split(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b, c = tf.split(x, 3, axis=1)\n            return tf.raw_ops.Pack(values=[a, b, c], axis=1)\n\n    run_all(Split)\n\n\ndef test_shape():\n    class Shape(tf.Module):\n        def get_input(self):\n            return np.ones((3, 2, 3), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(3, 2, 3), dtype=tf.float32)])\n        def func(self, x):\n            a = tf.ones_like(tf.raw_ops.Shape(input=x), dtype=tf.float32)\n            return a + x\n\n    run_all(Shape)\n\n\ndef test_pack():\n    class Pack(tf.Module):\n        def get_input(self):\n            return np.ones((2, 3), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 3), dtype=tf.float32)])\n        def func(self, x):\n            return tf.raw_ops.Pack(values=[x, x], axis=0)\n\n    run_all(Pack)\n\n\ndef test_max():\n    class Maximum(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b = tf.split(x, 2, axis=1)\n            return tf.math.maximum(a, b, name=None)\n\n    run_all(Maximum)\n\n\ndef test_less():\n    class Less(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b = tf.split(x, 2, axis=1)\n            return tf.math.less(a, b, name=None)\n\n    run_all(Less)\n\n\ndef test_equal():\n    class Equal(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b = tf.split(x, 2, axis=1)\n            return tf.math.equal(a, b, name=None)\n\n    run_all(Equal)\n\n\ndef test_cast():\n    class Cast(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.cast(x, tf.int32)\n\n    run_all(Cast)\n\n\ndef test_expand_dims():\n    class ExpandDims(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.expand_dims(x, axis=2)\n\n    run_all(ExpandDims)\n\n\ndef test_transpose():\n    class Transpose(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            x = tf.expand_dims(x, axis=2)\n            return tf.transpose(x, perm=[0, 2, 1])\n\n    run_all(Transpose)\n\n\ndef test_reshape():\n    class Reshape(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.reshape(x, (1, 2, 15))\n\n    run_all(Reshape)\n\n\ndef test_tanh():\n    class Tanh(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.math.tanh(x)\n\n    run_all(Tanh)\n\n\ndef test_sigmoid():\n    class Sigmoid(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.math.sigmoid(x)\n\n    run_all(Sigmoid)\n\n\ndef test_relu():\n    class Relu(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.nn.relu(x)\n\n    run_all(Relu)\n\n\ndef test_floor():\n    class Floor(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            return tf.math.floor(x)\n\n    run_all(Floor)\n\n\ndef test_floor_mod():\n    class FloorMod(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b = tf.split(x, 2, axis=1)\n            return tf.math.floormod(a, b)\n\n    run_all(FloorMod)\n\n\ndef test_concat_v2():\n    class ConcatV2(tf.Module):\n        def get_input(self):\n            return np.ones((1, 30), dtype=np.float32)\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1, 30), dtype=tf.float32)])\n        def func(self, x):\n            a, b, c = tf.split(x, 3, axis=1)\n            axis = tf.add(tf.constant(1, dtype=\"int32\"), tf.constant(0, dtype=\"int32\"))\n            return tf.raw_ops.ConcatV2(values=[a, b, c], axis=axis)\n\n    run_all(ConcatV2)\n\n\ndef test_multi_output():\n    class MultiOutput(tf.Module):\n        def get_input(self):\n            return np.ones((2, 2), dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n        def func(self, x):\n            y = 2 * x\n            return x, y\n\n    run_func_graph(MultiOutput, runtime=\"vm\", outputs=[\"Identity:output:0\", \"Identity_1:output:0\"])\n    run_func_graph(\n        MultiOutput, runtime=\"graph\", outputs=[\"Identity:output:0\", \"Identity_1:output:0\"]\n    )\n    run_model_graph(MultiOutput, outputs=[\"Identity:output:0\"])\n\n\ndef test_if():\n    def create_if_class(_condition=True):\n        class If(tf.Module):\n            def get_input(self):\n                return np.ones((2, 2), dtype=\"float32\")\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n            def func(self, x):\n                @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n                def double(x):\n                    return 2 * x\n\n                @tf.function(input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)])\n                def triple(x):\n                    return 3 * x\n\n                output = tf.raw_ops.If(\n                    cond=_condition,\n                    input=[x],\n                    Tout=[tf.float32],\n                    output_shapes=[(2, 2)],\n                    then_branch=double.get_concrete_function(),\n                    else_branch=triple.get_concrete_function(),\n                )\n                return output[0]\n\n        return If\n\n    for cond in [True, False]:\n        if_class = create_if_class(_condition=cond)\n        run_func_graph(if_class, runtime=\"vm\")\n        run_model_graph(if_class)\n\n\ndef test_stateless_while():\n    class StatelessWhile(tf.Module):\n        def get_input(self):\n            return np.array([6], dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1,), dtype=tf.float32)])\n        def func(self, x):\n            i = tf.constant(3.0)\n            cond = lambda i: tf.less(i, x)\n            body = lambda i: (tf.add(i, 2),)\n            r = tf.while_loop(cond, body, [i])\n            return r[0]\n\n    run_func_graph(StatelessWhile, runtime=\"vm\")\n    run_model_graph(StatelessWhile)\n\n\ndef test_stateless_while_2var():\n    class StatelessWhile2Var(tf.Module):\n        def get_input(self):\n            return np.array([20], dtype=\"float32\")\n\n        @tf.function(input_signature=[tf.TensorSpec(shape=(1,), dtype=tf.float32)])\n        def func(self, x):\n            i = tf.constant(3.0)\n            j = tf.constant(5.0)\n            cond = lambda i, j: tf.less(i + j, x)\n            body = lambda i, j: (tf.add(i, 2), tf.add(j, 3))\n            r = tf.while_loop(cond, body, [i, j])\n            return r\n\n    run_func_graph(\n        StatelessWhile2Var, runtime=\"vm\", outputs=[\"Identity:output:0\", \"Identity_1:output:0\"]\n    )\n    run_model_graph(StatelessWhile2Var, outputs=[\"Identity:output:0\"])\n\n\ndef test_tensorlist():\n    def run_test(elem_shape):\n        class TensorList(tf.Module):\n            def get_input(self):\n                in_tens = np.ones((2, 3), dtype=\"float32\")\n                in_tens[1, :] = np.zeros((3,), dtype=\"float32\")\n                return in_tens\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(2, 3), dtype=tf.float32)])\n            def func(self, x):\n                dtype = tf.float32\n                tl = tf.raw_ops.TensorListReserve(\n                    element_shape=elem_shape, num_elements=2, element_dtype=dtype\n                )\n                tl = tf.raw_ops.TensorListSetItem(input_handle=tl, index=0, item=x[0, :])\n                tl = tf.raw_ops.TensorListSetItem(input_handle=tl, index=1, item=x[1, :])\n                output = tf.raw_ops.TensorListGetItem(\n                    input_handle=tl, index=0, element_shape=elem_shape, element_dtype=dtype\n                )\n                return output\n\n        run_model_graph(TensorList)\n        run_func_graph(TensorList, runtime=\"vm\")\n\n    run_test((3,))\n    run_test((-1,))\n\n\ndef test_tensorlist_stack():\n    def run_test(elem_shape):\n        class TensorListStack(tf.Module):\n            def get_input(self):\n                in_tens = np.ones((2, 3), dtype=\"float32\")\n                in_tens[1] = np.zeros((3,), dtype=\"float32\")\n                return in_tens\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(2, 3), dtype=tf.float32)])\n            def func(self, x):\n                dtype = tf.float32\n                tl = tf.raw_ops.TensorListReserve(\n                    element_shape=elem_shape, num_elements=2, element_dtype=dtype\n                )\n                tl = tf.raw_ops.TensorListFromTensor(tensor=x, element_shape=elem_shape)\n                output = tf.raw_ops.TensorListStack(\n                    input_handle=tl, element_shape=elem_shape, element_dtype=dtype\n                )\n                return output\n\n        run_model_graph(TensorListStack)\n        run_func_graph(TensorListStack, runtime=\"vm\")\n\n    run_test((3,))\n    run_test((-1,))\n\n\ndef test_tensorlist_2d():\n    def run_test(elem_shape):\n        class TensorList2D(tf.Module):\n            def get_input(self):\n                in_tens = np.ones((2, 3, 4), dtype=\"float32\")\n                in_tens[1, :, :] = np.zeros((3, 4), dtype=\"float32\")\n                return in_tens\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(2, 3, 4), dtype=tf.float32)])\n            def func(self, x):\n                dtype = tf.float32\n                tl = tf.raw_ops.TensorListReserve(\n                    element_shape=elem_shape, num_elements=2, element_dtype=dtype\n                )\n                tl = tf.raw_ops.TensorListSetItem(input_handle=tl, index=0, item=x[0, :, :])\n                tl = tf.raw_ops.TensorListSetItem(input_handle=tl, index=1, item=x[1, :, :])\n                output = tf.raw_ops.TensorListGetItem(\n                    input_handle=tl, index=0, element_shape=elem_shape, element_dtype=dtype\n                )\n                return output\n\n        run_model_graph(TensorList2D)\n        run_func_graph(TensorList2D, runtime=\"vm\")\n\n    run_test((3, 4))\n    run_test((-1, -1))\n\n\ndef test_tensorlist_stack_2d():\n    def run_test(elem_shape):\n        class TensorListStack2D(tf.Module):\n            def get_input(self):\n                in_tens = np.ones((2, 3, 4), dtype=\"float32\")\n                in_tens[1, :, :] = np.zeros((3, 4), dtype=\"float32\")\n                return in_tens\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(2, 3, 4), dtype=tf.float32)])\n            def func(self, x):\n                dtype = tf.float32\n                tl = tf.raw_ops.TensorListReserve(\n                    element_shape=elem_shape, num_elements=2, element_dtype=dtype\n                )\n                tl = tf.raw_ops.TensorListFromTensor(tensor=x, element_shape=elem_shape)\n                output = tf.raw_ops.TensorListStack(\n                    input_handle=tl, element_shape=elem_shape, element_dtype=dtype\n                )\n                return output\n\n        run_model_graph(TensorListStack2D)\n        run_func_graph(TensorListStack2D, runtime=\"vm\")\n\n    run_test((3, 4))\n    run_test((-1, -1))\n\n\ndef test_tensorlist_stack_unpack():\n    def run_test(elem_shape):\n        class TensorListStack2D(tf.Module):\n            def get_input(self):\n                in_tens = np.ones((1, 3, 4), dtype=\"float32\")\n                return in_tens\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=(1, 3, 4), dtype=tf.float32)])\n            def func(self, x):\n                dtype = tf.float32\n                tl = tf.raw_ops.TensorListReserve(\n                    element_shape=elem_shape, num_elements=1, element_dtype=dtype\n                )\n                tl = tf.raw_ops.TensorListSetItem(input_handle=tl, index=0, item=x[0, :, :])\n                output = tf.raw_ops.TensorListStack(\n                    input_handle=tl, element_shape=elem_shape, element_dtype=dtype, num_elements=1\n                )\n                output = tf.raw_ops.Unpack(value=output, num=1, axis=0)\n                return output\n\n        run_model_graph(TensorListStack2D)\n        run_func_graph(TensorListStack2D, runtime=\"vm\")\n\n    run_test((3, 4))\n    run_test((-1, -1))\n\n\ndef test_bincount_1d():\n    def run_test(weights, minlength, maxlength, axis, binary_output):\n        class Bincount1D(tf.Module):\n            def get_input(self):\n                return np.random.uniform(low=0, high=maxlength, size=(100,)).astype(\"int32\")\n\n            @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.int32)])\n            def func(self, x):\n                return tf.math.bincount(\n                    x,\n                    weights=weights,\n                    minlength=minlength,\n                    maxlength=maxlength,\n                    axis=axis,\n                    binary_output=binary_output,\n                )\n\n        run_model_graph(Bincount1D)\n        run_func_graph(Bincount1D, runtime=\"vm\")\n\n    for axis in [None, 0, -1]:\n        run_test(weights=None, minlength=20, maxlength=20, axis=axis, binary_output=False)\n        run_test(weights=None, minlength=20, maxlength=20, axis=axis, binary_output=True)\n\n    # weights and axis=None need operator UnsortedSegmentSum to be implemented. Skip axis=None\n    weights = np.random.uniform(low=0.2, high=5, size=(100,)).astype(\"float32\")\n    for axis in [0, -1]:\n        run_test(weights=weights, minlength=20, maxlength=20, axis=axis, binary_output=False)\n\n\ndef test_bincount_2d():\n    def run_test(weights, minlength, maxlength, axis, binary_output):\n        class Bincount2D(tf.Module):\n            def get_input(self):\n                return np.random.uniform(low=0, high=maxlength, size=(3, 100)).astype(\"int32\")\n\n            @tf.function(input_signature=[tf.TensorSpec([None, None], tf.int32)])\n            def func(self, x):\n                return tf.math.bincount(\n                    x,\n                    weights=weights,\n                    minlength=minlength,\n                    maxlength=maxlength,\n                    axis=axis,\n                    binary_output=binary_output,\n                )\n\n        run_model_graph(Bincount2D)\n        run_func_graph(Bincount2D, runtime=\"vm\")\n\n    for axis in [None, 0, -1]:\n        run_test(weights=None, minlength=20, maxlength=20, axis=axis, binary_output=False)\n        run_test(weights=None, minlength=20, maxlength=20, axis=axis, binary_output=True)\n\n    # weights and axis=None need operator UnsortedSegmentSum to be implemented. Skip axis=None\n    weights = np.random.uniform(low=0.2, high=5, size=(3, 100)).astype(\"float32\")\n    for axis in [0, -1]:\n        run_test(weights=weights, minlength=20, maxlength=20, axis=axis, binary_output=False)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tensorflow2/test_sequential_models.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n# pylint: disable=import-outside-toplevel, redefined-builtin\n\"\"\"TF2 to relay converter test: testing models built with tf.keras.Sequential()\"\"\"\n\nimport tempfile\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2\n\nfrom common import compare_tf_tvm\nfrom common import run_tf_code\n\n\ndef run_sequential_model(model_fn, input_shape):\n    def get_input(shape):\n        _input = np.random.uniform(0, 1, shape).astype(dtype=\"float32\")\n        return _input\n\n    def save_and_reload(_model):\n        with tempfile.TemporaryDirectory() as model_path:\n            tf.saved_model.save(_model, model_path)\n            loaded = tf.saved_model.load(model_path)\n            func = loaded.signatures[\"serving_default\"]\n            frozen_func = convert_variables_to_constants_v2(func)\n        return frozen_func\n\n    def model_graph(model, input_shape):\n        _input = get_input(input_shape)\n        f = save_and_reload(model(input_shape))\n        _output = run_tf_code(f, _input)\n        gdef = f.graph.as_graph_def(add_shapes=True)\n        return gdef, _input, _output\n\n    compare_tf_tvm(*model_graph(model_fn, input_shape), runtime=\"vm\")\n\n\ndef test_dense_model():\n    def dense_model(input_shape, num_units=128):\n        return tf.keras.Sequential(\n            [tf.keras.layers.Flatten(input_shape=input_shape[1:]), tf.keras.layers.Dense(num_units)]\n        )\n\n    run_sequential_model(dense_model, input_shape=(1, 28, 28))\n\n\ndef test_mnist_model():\n    def mnist_model(input_shape):\n        return tf.keras.Sequential(\n            [\n                tf.keras.layers.Flatten(input_shape=input_shape[1:]),\n                tf.keras.layers.Dense(128, activation=\"relu\"),\n                tf.keras.layers.Dense(10),\n            ]\n        )\n\n    run_sequential_model(mnist_model, input_shape=(1, 28, 28))\n\n\ndef test_conv2d_model():\n    def conv2d_model(input_shape, kernel=(3, 3), filters=16):\n        model = tf.keras.Sequential(\n            [\n                tf.keras.layers.Input(shape=input_shape[1:], batch_size=1),\n                tf.keras.layers.Conv2D(filters, kernel),\n            ]\n        )\n        return model\n\n    run_sequential_model(conv2d_model, input_shape=(1, 32, 32, 3))\n\n\ndef test_maxpool_model():\n    def maxpool_model(input_shape, pool_size=(2, 2)):\n        model = tf.keras.Sequential(\n            [tf.keras.layers.MaxPool2D(pool_size=pool_size, input_shape=input_shape[1:])]\n        )\n        return model\n\n    run_sequential_model(maxpool_model, input_shape=(1, 32, 32, 3))\n\n\ndef test_maxpool_batchnorm_model():\n    def maxpool_batchnorm_model(input_shape, pool_size=(2, 2)):\n        model = tf.keras.Sequential(\n            [\n                tf.keras.layers.MaxPool2D(pool_size=pool_size, input_shape=input_shape[1:]),\n                tf.keras.layers.BatchNormalization(),\n            ]\n        )\n        return model\n\n    run_sequential_model(maxpool_batchnorm_model, input_shape=(1, 32, 32, 3))\n\n\ndef test_tensorlist_stack_model():\n    def tensorlist_stack_model(input_shape):\n        class TensorArrayStackLayer(tf.keras.layers.Layer):\n            def __init__(self):\n                super().__init__()\n\n            def call(self, inputs):\n                inputs = tf.squeeze(inputs)\n                outputs = tf.TensorArray(\n                    tf.float32,\n                    size=inputs.shape[0],\n                    infer_shape=False,\n                    element_shape=inputs.shape[1:],\n                )\n                outputs = outputs.unstack(inputs)\n\n                return outputs.stack()\n\n        input_shape = (3, 32)\n        model = tf.keras.Sequential(\n            [tf.keras.layers.Input(shape=input_shape, batch_size=1), TensorArrayStackLayer()]\n        )\n        return model\n\n    run_sequential_model(tensorlist_stack_model, input_shape=(3, 32))\n\n\ndef test_tensorlist_read_model():\n    def tensorlist_read_model(input_shape):\n        class TensorArrayReadLayer(tf.keras.layers.Layer):\n            def __init__(self):\n                super().__init__()\n\n            def call(self, inputs):\n                inputs = tf.squeeze(inputs)\n                outputs = tf.TensorArray(\n                    tf.float32,\n                    size=inputs.shape[0],\n                    infer_shape=False,\n                    element_shape=inputs.shape[1:],\n                )\n                for i in range(inputs.shape[0]):\n                    outputs = outputs.write(i, inputs[i, :])\n\n                return outputs.read(0)\n\n        input_shape = (3, 32)\n        model = tf.keras.Sequential(\n            [tf.keras.layers.Input(shape=input_shape, batch_size=1), TensorArrayReadLayer()]\n        )\n        return model\n\n    run_sequential_model(tensorlist_read_model, input_shape=(3, 32))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/test_common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.relay.frontend.common import StrAttrsDict\n\n\ndef test_key_is_present():\n    attrs = StrAttrsDict({\"a\": 1})\n    assert attrs.has_attr(\"a\")\n\n\ndef test_key_is_not_present():\n    attrs = StrAttrsDict({\"a\": 1})\n    assert not attrs.has_attr(\"b\")\n\n\nif __name__ == \"__main__\":\n    test_key_is_present()\n    test_key_is_present()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/frontend/tflite/test_forward.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, import-outside-toplevel, inconsistent-return-statements\n\"\"\"\nTFLite testcases\n================\nThis article is a test script to test TFLite operator with Relay.\n\"\"\"\nfrom __future__ import print_function\nfrom functools import partial\nfrom distutils.version import LooseVersion\n\nimport os\nimport tempfile\nfrom packaging import version as package_version\nimport pytest\nimport numpy as np\n\nfrom PIL import Image\n\nimport tvm\nimport tvm.relay.testing.tf as tf_testing\nfrom tvm.contrib.download import download_testdata\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tflite.BuiltinOperator import BuiltinOperator\n\n\ntry:\n    import tensorflow.compat.v1 as tf\n\n    # tensorflow.python.framework.ops module itself is not part of\n    # TensorFlow's public API: the precise contents of that module\n    # may vary from one version to the next\n    import tensorflow.compat.v1 as ops\nexcept ImportError:\n    import tensorflow as tf\n    import tensorflow as ops\nfrom tensorflow.python.framework import constant_op\n\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import image_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import nn_impl\nfrom tensorflow.python.ops import variables\n\ntry:\n    from tensorflow import lite as interpreter_wrapper\nexcept ImportError:\n    from tensorflow.contrib import lite as interpreter_wrapper\n\n\n#######################################################################\n# Generic run functions for TVM & TFLite\n# --------------------------------------\ndef convert_to_list(x):\n    if not isinstance(x, list):\n        x = [x]\n    return x\n\n\n#######################################################################\n# Get a real image for e2e testing\n# --------------------------------\ndef get_real_image(im_height, im_width, quantized=True):\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    x = np.array(image).astype(\"uint8\") if quantized else np.array(image).astype(\"float32\")\n    data = np.reshape(x, (1, im_height, im_width, 3))\n    return data\n\n\ndef pre_processed_image(height, width):\n    \"\"\"Image preprocessed\"\"\"\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/\"\n    img_name = \"elephant-299.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = tf.io.read_file(img_path)\n    image = tf.image.decode_jpeg(image, channels=3)\n    with tf.name_scope(\"eval_image\"):\n        if image.dtype != tf.float32:\n            image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n        image = tf.image.central_crop(image, central_fraction=0.875)\n    # Resize the image to the specified height and width.\n    image = tf.image.resize(image, [height, width], align_corners=False)\n    image = tf.expand_dims(image, axis=0)\n    return image\n\n\ndef get_real_image_object_detection(im_height, im_width):\n    repo_base = \"https://github.com/dmlc/web-data/raw/main/gluoncv/detection/\"\n    img_name = \"street_small.jpg\"\n    image_url = os.path.join(repo_base, img_name)\n    img_path = download_testdata(image_url, img_name, module=\"data\")\n    image = Image.open(img_path).resize((im_height, im_width))\n    x = np.array(image).astype(\"uint8\")\n    data = np.reshape(x, (1, im_height, im_width, 3))\n    return data\n\n\ndef vmobj_to_list(obj):\n    \"\"\"Converts TVM objects returned by VM execution to Python List.\"\"\"\n    if isinstance(obj, tvm.nd.NDArray):\n        return [obj.numpy().tolist()]\n    elif isinstance(obj, tvm.runtime.container.ADT):\n        result = []\n        for f in obj:\n            result.extend(vmobj_to_list(f))\n        return result\n    elif isinstance(obj, tvm.relay.backend.interpreter.ConstructorValue):\n        if obj.constructor.name_hint == \"Cons\":\n            t_l = vmobj_to_list(obj.fields[1])\n            h_d = vmobj_to_list(obj.fields[0])\n            h_d.extend(t_l)\n            return h_d\n        elif obj.constructor.name_hint == \"Nil\":\n            return []\n        elif \"tensor_nil\" in obj.constructor.name_hint:\n            return [0]\n        elif \"tensor\" in obj.constructor.name_hint:\n            return [obj.fields[0].numpy()]\n        else:\n            raise RuntimeError(f\"Unknown object type: {obj.constructor.name_hint}\")\n    else:\n        raise RuntimeError(f\"Unknown object type: {type(obj)}\")\n\n\ndef _quantize_keras_model(\n    keras_model,\n    representative_data_gen,\n    is_float_input=False,\n    is_float_output=False,\n    int_quant_dtype=tf.int8,\n):\n    \"\"\"Utility function to quantize a Keras model using TFLite converter.\"\"\"\n    converter = interpreter_wrapper.TFLiteConverter.from_keras_model(keras_model)\n    if int_quant_dtype == tf.int8:\n        converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n        converter.representative_dataset = representative_data_gen\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        inference_dtype = tf.uint8\n    elif int_quant_dtype == tf.int16:\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_data_gen\n        converter.target_spec.supported_ops = [\n            tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8\n        ]\n        inference_dtype = tf.uint16\n    else:\n        raise RuntimeError(\n            f\"Invalid quantized dtype {int_quant_dtype}. Supported types: int8, int16.\"\n        )\n\n    # NOTE: If representative dataset is provided, and inference input type is not set,\n    #       then converter will self add quant & dequant Op accordingly.\n    if not is_float_input:\n        converter.inference_input_type = inference_dtype\n    if not is_float_output:\n        converter.inference_output_type = inference_dtype\n\n    return converter.convert()\n\n\ndef run_tvm_graph(\n    tflite_model_buf,\n    input_data,\n    input_node,\n    num_output=1,\n    target=\"llvm\",\n    out_names=None,\n    mode=\"graph_executor\",\n    op_converter=relay.frontend.tflite.OperatorConverter,\n):\n    \"\"\"Generic function to compile on relay and execute on tvm\"\"\"\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n    except AttributeError:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n    except ImportError as exc:\n        raise ImportError(\"The tflite package must be installed\") from exc\n\n    input_data = convert_to_list(input_data)\n    input_node = convert_to_list(input_node)\n\n    shape_dict = {}\n    dtype_dict = {}\n    for i, node in enumerate(input_node):\n        shape_dict[node] = input_data[i].shape\n        dtype_dict[node] = input_data[i].dtype.name\n\n    mod, params = relay.frontend.from_tflite(\n        tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict, op_converter=op_converter\n    )\n\n    if mode in [\"debug\", \"vm\"]:\n        inputs = []\n        for param in mod[\"main\"].params:\n            found = False\n            for i, n in enumerate(input_node):\n                if n == param.name_hint:\n                    found = True\n                    inputs.append(tvm.nd.array(input_data[i]))\n                    break\n            # Interpreter doesn't bind constants, so still need to find in params\n            if not found:\n                inputs.append(tvm.nd.array(params[param.name_hint]))\n        result = relay.create_executor(mode, mod=mod, device=tvm.cpu(), target=\"llvm\").evaluate()(\n            *inputs\n        )\n        return vmobj_to_list(result)\n    else:\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target, params=params)\n\n        dev = tvm.device(target, 0)\n\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        # set inputs\n        for i, node in enumerate(input_node):\n            m.set_input(node, tvm.nd.array(input_data[i].astype(input_data[i].dtype)))\n        # execute\n        m.run()\n        # get outputs\n        assert out_names is None or num_output == len(\n            out_names\n        ), f\"out_names: {out_names} num_output: {num_output}\"\n        tvm_output_list = []\n        for i in range(0, num_output):\n            tvm_output = m.get_output(i)\n            tvm_output_list.append(tvm_output.numpy())\n        return tvm_output_list\n\n\ndef run_tflite_graph(tflite_model_buf, input_data):\n    \"\"\"Generic function to execute TFLite\"\"\"\n    input_data = convert_to_list(input_data)\n\n    interpreter = interpreter_wrapper.Interpreter(model_content=tflite_model_buf)\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    for i, input_detail in enumerate(input_details):\n        interpreter.resize_tensor_input(input_detail[\"index\"], input_data[i].shape)\n    interpreter.allocate_tensors()\n\n    # set input\n    assert len(input_data) == len(input_details)\n    for i, input_detail in enumerate(input_details):\n        interpreter.set_tensor(input_detail[\"index\"], input_data[i])\n\n    # Run\n    interpreter.invoke()\n\n    # get output\n    tflite_output = []\n    for _, output_detail in enumerate(output_details):\n        tflite_output.append(interpreter.get_tensor(output_detail[\"index\"]))\n\n    return tflite_output\n\n\ndef compare_tflite_with_tvm(\n    in_data,\n    in_name,\n    input_tensors,\n    output_tensors,\n    init_global_variables=False,\n    out_names=None,\n    quantized=False,\n    input_range=None,\n    mode=\"graph_executor\",\n    experimental_new_converter=False,\n    fp16_quantized=False,\n    int_quant_dtype=tf.int8,\n):\n    \"\"\"Generic function to generate and compare TFLite and TVM output\"\"\"\n    in_data = convert_to_list(in_data)\n    in_name = convert_to_list(in_name)\n    out_names = convert_to_list(out_names)\n    in_node = [0] * len(in_name)\n    for i, _ in enumerate(in_name):\n        in_node[i] = in_name[i].split(\":\")[0] if \":\" in in_name[i] else in_name[i]\n\n    with tf.Session() as sess:\n        if init_global_variables:\n            sess.run(variables.global_variables_initializer())\n        # convert to tflite model\n        converter = tf.lite.TFLiteConverter.from_session(sess, input_tensors, output_tensors)\n        converter.experimental_new_converter = experimental_new_converter\n        if quantized:\n            if int_quant_dtype == tf.int16:\n                converter.optimizations = [tf.lite.Optimize.DEFAULT]\n                converter.target_spec.supported_ops = [\n                    tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8\n                ]\n            else:\n                # default to int8 quantization\n                converter.inference_type = tf.lite.constants.QUANTIZED_UINT8\n\n            input_arrays = converter.get_input_arrays()\n            input_stats = {}\n            # calculate the mean and quantization scale for every input tensor,\n            # with respect to its fp32 input range, defined in fake_quant.\n            # s = 255/(fmax-fmin);  m = -fmin*s (the zero point)\n            for i in input_arrays:\n                try:\n                    quant_scale = 255 / (input_range[i][1] - input_range[i][0])\n                except ZeroDivisionError:\n                    print(\"Min and max of the input range for tensor \" + i + \" can't be equal\")\n                mean = -input_range[i][0] * quant_scale\n                input_stats[i] = (mean, quant_scale)\n            converter.quantized_input_stats = input_stats\n        elif fp16_quantized:\n            converter.optimizations = [tf.lite.Optimize.DEFAULT]\n            converter.target_spec.supported_types = [tf.float16]\n\n        tflite_model_buffer = converter.convert()\n        tflite_output = run_tflite_graph(tflite_model_buffer, in_data)\n\n        for device in [\"llvm\"]:\n            _ = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(f\"Skip because {device} is not enabled\")\n                continue\n\n            tvm_output = run_tvm_graph(\n                tflite_model_buffer,\n                in_data,\n                in_node,\n                target=device,\n                num_output=len(out_names),\n                out_names=out_names,\n                mode=mode,\n            )\n            # WARNING: the results could well be random values clipped to 0 or 255 because of badly\n            # tuned output range for the specific operator. While adding test ensure that we aren't\n            # getting only clipped values in output tensors that still pass the assertion.\n            # For reference see _test_elemwise_qnn_out_range()\n            if quantized and not fp16_quantized:\n                for i, _ in enumerate(tflite_output):\n                    # allow absolute tolerance of 1 in the quantized results\n                    tvm.testing.assert_allclose(\n                        tflite_output[i],  # pylint: disable=unnecessary-list-index-lookup\n                        tvm_output[i],\n                        atol=1,\n                        rtol=1e-5,\n                    )\n            else:\n                for i, _ in enumerate(tflite_output):\n                    tvm.testing.assert_allclose(\n                        tflite_output[i],  # pylint: disable=unnecessary-list-index-lookup\n                        tvm_output[i],\n                        atol=1e-5,\n                        rtol=1e-5,\n                    )\n\n\ndef with_fused_activation_function(input_tensor, fn_name):\n    \"\"\"Fused activation function\"\"\"\n    if fn_name is None or fn_name == \"NONE\":\n        return input_tensor\n    if fn_name == \"RELU\":\n        return nn_ops.relu(input_tensor)\n    if fn_name == \"RELU6\":\n        return nn_ops.relu6(input_tensor)\n    if fn_name == \"RELU_N1_TO_1\":\n        return math_ops.maximum(-1, math_ops.minimum(input_tensor, 1))\n    if fn_name == \"TANH\":\n        return math_ops.tanh(input_tensor)\n    raise AssertionError(f\"Unknown fused_activation_function {fn_name}\")\n\n\ndef _test_split(in_shape, axis, num_splits, dtype):\n    \"\"\"internal split tester taking as parameters in_shape, number of tensors to split into\n    and dtype (data type)\"\"\"\n\n    np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=in_shape, dtype=dtype, name=\"in_data\")\n        out = array_ops.split(in_data, num_splits, axis=axis)\n        num_splits = len(num_splits) if isinstance(num_splits, list) else num_splits\n        out_names = [\"out_\" + str(n) + \":0\" for n in range(num_splits)]\n        compare_tflite_with_tvm([np_data], [\"in_data\"], [in_data], out, out_names=out_names)\n\n\ndef test_forward_split():\n    \"\"\"test split layer\"\"\"\n    # rank 1\n    _test_split((3,), 0, 1, \"float32\")\n    _test_split((3,), 0, 3, \"float32\")\n    _test_split((6,), 0, 3, \"float32\")\n    # rank 2\n    _test_split((6, 2), 0, 3, \"float32\")\n    _test_split((2, 6), 1, 6, \"float32\")\n    # rank 3\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_split((6, 2, 4), 0, 2, \"int32\")\n\n    _test_split((2, 6, 4), 1, 3, \"float32\")\n    _test_split((2, 4, 6), 2, 1, \"float32\")\n    # rank 4\n    _test_split((6, 1, 3, 5), 0, 3, \"float32\")\n    _test_split((1, 6, 3, 5), 1, 3, \"float32\")\n    _test_split((1, 3, 6, 5), 2, 3, \"float32\")\n    _test_split((1, 3, 5, 6), 3, 3, \"float32\")\n    # split along negative axis\n    _test_split((6, 1, 3, 5), -4, 3, \"float32\")\n    _test_split((1, 6, 3, 5), -3, 3, \"float32\")\n    _test_split((1, 3, 6, 5), -2, 3, \"float32\")\n    _test_split((1, 3, 5, 6), -1, 3, \"float32\")\n    # size_splits split\n    _test_split((6,), 0, [1, 2, 3], \"float32\")\n    _test_split((3, 6, 4), -2, [1, 4, 1], \"float32\")\n\n\n#######################################################################\n# slice\n# -----\n\n\ndef _test_slice(data, begin, size):\n    \"\"\"One iteration of SLICE\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = array_ops.slice(in_data, begin, size)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_slice():\n    \"\"\"SLICE\"\"\"\n    _test_slice(np.arange(4, dtype=np.float32).reshape((4,)), begin=[0], size=[2])\n    _test_slice(np.arange(18, dtype=np.int32).reshape((3, 2, 3)), begin=[1, 0, 0], size=[1, 1, 3])\n    # tflite 1.13 outputs nonsense values if size[i] == -1\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_slice(np.arange(8, dtype=np.int32).reshape((2, 4)), begin=[0, 1], size=[-1, -1])\n        _test_slice(np.arange(5, dtype=np.int32).reshape((5,)), begin=[4], size=[-1])\n\n\n#######################################################################\n# Topk\n# ----\ndef _test_topk(in_shape, k=1):\n    \"\"\"One iteration of TOPK\"\"\"\n    data = np.random.uniform(size=in_shape).astype(\"float32\")\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = nn_ops.top_k(in_data, k, name=\"TopK\")\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out[0]])\n\n\ndef test_forward_topk():\n    \"\"\"TOPK\"\"\"\n    _test_topk((3,), 1)\n    _test_topk((3,), 3)\n    _test_topk((3, 5, 7), 3)\n    _test_topk((3, 5, 7), 3)\n\n\n#######################################################################\n# Gather\n# ------\n\n\ndef _test_gather(dshape, indices, axis, dtype, quantized=False, oob=False, wrap_idx=False):\n    \"\"\"One iteration of Gather\"\"\"\n    indices = np.asarray(indices).astype(\"int32\")\n    data = np.random.uniform(1, 10, size=dshape)\n    data = data.astype(np.uint8) if quantized else data.astype(dtype)\n    with tf.Graph().as_default():\n        if wrap_idx:\n            in_name = \"in_indices\"\n            indices_expr = array_ops.placeholder(\n                shape=indices.shape, dtype=indices.dtype, name=in_name\n            )\n            in_tensor_name = [in_name + \":0\"]\n            in_indices = [indices_expr]\n        else:\n            indices_expr = indices\n            indices = []\n            in_tensor_name = []\n            in_indices = []\n\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype, name=\"in_data\")\n        if axis:\n            out = array_ops.gather(in_data, indices_expr, axis=axis)\n        else:\n            out = array_ops.gather(in_data, indices_expr)  # tflite conversion fails for None axis\n        input_range = {\"in_data\": (-100, 100)} if quantized else None\n        try:\n            compare_tflite_with_tvm(\n                [data] + indices,\n                [\"in_data:0\"] + in_tensor_name,\n                [in_data] + in_indices,\n                [out],\n                quantized=quantized,\n                input_range=input_range,\n            )\n        except ValueError as exc:\n            if not oob:\n                raise exc\n        except Exception as exc:\n            raise exc\n\n\ndef test_forward_gather():\n    \"\"\"GATHER\"\"\"\n    for quantized in [False, True]:\n        for wrap_idx in [False, True]:\n            _test_gather((4,), [1], 0, \"float32\", quantized, wrap_idx)\n            _test_gather((4,), [1], None, \"int32\", quantized, wrap_idx)\n            _test_gather((1, 4), [0], 0, \"int32\", quantized, wrap_idx)\n            _test_gather((4,), [[[1, 0], [0, 1]]], 0, \"float32\", quantized, wrap_idx)\n            _test_gather((2, 2), [[[1, 0], [0, 1]]], 1, \"int32\", quantized, wrap_idx)\n            _test_gather((2, 2), [[[1, 0], [0, 1]]], None, \"float32\", quantized, wrap_idx)\n            _test_gather((3, 3, 3), [[[1, 0]]], 0, \"int32\", quantized, wrap_idx)\n            _test_gather((3, 3, 3), [[[1, 0]]], 2, \"int32\", quantized, wrap_idx)\n            _test_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, \"float32\", quantized, wrap_idx)\n            _test_gather((3, 3, 3), [[[2, 1]]], -1, \"int32\", quantized, wrap_idx)\n        # Out of boundary error cannot be tested with wrapped index\n        _test_gather((4,), [16], 0, \"float32\", quantized, oob=True)\n        _test_gather((1, 3, 3), [12], 0, \"int32\", quantized, oob=True)\n        _test_gather((1, 3, 3), [20], 1, \"float32\", quantized, oob=True)\n        _test_gather((1, 3, 3), [20, 20], 2, \"float32\", quantized, oob=True)\n\n\n#######################################################################\n# Gather_ND\n# ---------\n\n\ndef _test_gather_nd(data, indices):\n    \"\"\"One iteration of GATHER_ND\"\"\"\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(shape=data.shape, dtype=data.dtype, name=\"data\")\n        indices_data = tf.placeholder(shape=indices.shape, dtype=indices.dtype, name=\"indices\")\n        out = tf.gather_nd(in_data, indices_data)\n\n        compare_tflite_with_tvm(\n            [data, indices], [\"data:0\", \"indices:0\"], [in_data, indices_data], [out]\n        )\n\n\ndef test_forward_gather_nd():\n    \"\"\"GATHER_ND\"\"\"\n    _test_gather_nd(\n        np.array([[[1.2, 2.0], [3.1, 4.1]], [[5.1, 6.1], [7.1, 8.1]]]).astype(\"float32\"),\n        np.asarray([[0, 1], [1, 0]]).astype(\"int32\"),\n    )\n    _test_gather_nd(\n        np.reshape(np.arange(30), [5, 6]).astype(\"int32\"), np.asarray([[1, 2]]).astype(\"int32\")\n    )\n    _test_gather_nd(\n        np.reshape(np.arange(12), [2, 3, 2]).astype(\"int32\"),\n        np.asarray([[[0, 0], [0, 1]], [[1, 0], [1, 1]]]).astype(\"int32\"),\n    )\n    _test_gather_nd(\n        np.reshape(np.arange(4), [4]).astype(\"float32\"), np.asarray([1]).astype(\"int32\")\n    )\n    _test_gather_nd(\n        np.reshape(np.arange(4), [1, 4]).astype(\"float32\"), np.asarray([0]).astype(\"int32\")\n    )\n    _test_gather_nd(\n        np.reshape(np.arange(4), [1, 4]).astype(\"float32\"), np.asarray([0, 3]).astype(\"int32\")\n    )\n\n\n#######################################################################\n# StridedSlice\n# ------------\n\n\ndef _test_stridedslice(\n    ip_shape,\n    begin,\n    end,\n    stride,\n    dtype,\n    begin_mask=0,\n    end_mask=0,\n    new_axis_mask=0,\n    shrink_axis_mask=0,\n    ellipsis_mask=0,\n    quantized=False,\n):\n    \"\"\"One iteration of a Stridedslice\"\"\"\n    data = np.random.uniform(size=ip_shape).astype(dtype)\n    data = data.astype(np.uint8) if quantized else data.astype(dtype)\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype, ip_shape, name=\"in_data\")\n        out = array_ops.strided_slice(\n            in_data,\n            begin,\n            end,\n            stride,\n            begin_mask=begin_mask,\n            end_mask=end_mask,\n            new_axis_mask=new_axis_mask,\n            shrink_axis_mask=shrink_axis_mask,\n            ellipsis_mask=ellipsis_mask,\n        )\n        input_range = {\"in_data\": (-100, 100)} if quantized else None\n        compare_tflite_with_tvm(\n            [data], [\"in_data:0\"], [in_data], [out], quantized=quantized, input_range=input_range\n        )\n\n\ndef test_forward_stridedslice():\n    \"\"\"test StridedSlice\"\"\"\n    for quantized in [False, True]:\n        _test_stridedslice(\n            (1, 3, 3),\n            [0, 0, 0],\n            [3, 3, 3],\n            [1, 1, 1],\n            \"float32\",\n            shrink_axis_mask=7,\n            quantized=quantized,\n        )\n        _test_stridedslice(\n            (1, 3, 3),\n            [0, 0, 0],\n            [3, 3, 3],\n            [1, 1, 1],\n            \"float32\",\n            shrink_axis_mask=5,\n            quantized=quantized,\n        )\n        _test_stridedslice((2), [1], [1], [1], \"float32\", shrink_axis_mask=1, quantized=quantized)\n        _test_stridedslice(\n            (3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], \"float32\", quantized=quantized\n        )\n        _test_stridedslice(\n            (3, 4), [1, 0], [4, 4], [1, 1], \"float32\", shrink_axis_mask=0, quantized=quantized\n        )\n        _test_stridedslice(\n            (4, 4), [1, 0], [4, 4], [1, 1], \"float32\", shrink_axis_mask=2, quantized=quantized\n        )\n        _test_stridedslice(\n            (3, 4), [-1, 0], [0, 3], [1, 1], \"float32\", shrink_axis_mask=1, quantized=quantized\n        )\n\n\n#######################################################################\n# transpose\n# ---------\n\n\ndef _test_forward_transpose(ishape, axes=()):\n    data = np.random.uniform(size=ishape).astype(np.float32)\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n        if not axes:\n            out = array_ops.transpose(in_data)\n        else:\n            out = array_ops.transpose(in_data, axes)\n\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_transpose():\n    _test_forward_transpose((2, 2))\n    _test_forward_transpose((2, 3, 4))\n    _test_forward_transpose((7, 8, 8, 10))\n    _test_forward_transpose((2, 3, 4), (1, 2, 0))\n    _test_forward_transpose((2, 3, 4), (0, 1, 2))\n    _test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2))\n    _test_forward_transpose((2, 3, 4, 5), ())\n\n\n#######################################################################\n# Cast\n# ----\n\n\ndef _test_cast(data, cast_dtype, use_mlir=False):\n    \"\"\"One iteration of CAST\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = math_ops.cast(in_data, cast_dtype)\n        compare_tflite_with_tvm(\n            data, \"Placeholder:0\", [in_data], [out], experimental_new_converter=use_mlir\n        )\n\n\ndef test_forward_cast():\n    \"\"\"CAST\"\"\"\n    for use_mlir in [False, True]:\n        _test_cast(\n            np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.int32, use_mlir=use_mlir\n        )\n        _test_cast(\n            np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.uint8, use_mlir=use_mlir\n        )\n        _test_cast(\n            np.arange(6.0, dtype=np.int32).reshape((1, 6)), cast_dtype=tf.int64, use_mlir=use_mlir\n        )\n\n\n#######################################################################\n# Batch Mat Mul\n# ----\ndef _test_batch_matmul(a_shape, b_shape, dtype, adjoint_a=False, adjoint_b=False):\n    with tf.Graph().as_default():\n        a = array_ops.placeholder(shape=a_shape, dtype=dtype, name=\"A\")\n        b = array_ops.placeholder(shape=b_shape, dtype=dtype, name=\"B\")\n        result = math_ops.matmul(a, b, adjoint_a=adjoint_a, adjoint_b=adjoint_b, name=\"batchmatmul\")\n\n        a_np = np.random.uniform(high=5.0, size=a_shape).astype(dtype)\n        b_np = np.random.uniform(high=5.0, size=b_shape).astype(dtype)\n        compare_tflite_with_tvm([a_np, b_np], [a.name, b.name], [a, b], [result])\n\n\ndef test_forward_batch_matmul():\n    \"\"\"BATCH_MAT_MUL\"\"\"\n    _test_batch_matmul((3, 5, 4), (3, 4, 5), \"float32\")\n    _test_batch_matmul((3, 5, 4), (3, 4, 5), \"float32\", True, True)\n    _test_batch_matmul((3, 5, 4), (3, 5, 4), \"float32\", True, False)\n    _test_batch_matmul((3, 5, 4), (3, 5, 4), \"float32\", False, True)\n    _test_batch_matmul((2, 3, 4, 5, 6), (2, 3, 4, 6, 5), \"float32\")\n\n\n#######################################################################\n# Tile\n# ----\n\n\ndef _test_forward_tile(in_shape, reps, dtype):\n    data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n        out = array_ops.tile(in_data, reps)\n\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_tile():\n    _test_forward_tile((2,), (3,), \"int32\")\n    _test_forward_tile((2, 2), (2, 3), \"float32\")\n\n\n######################################################################\n# BatchToSpaceND\n# --------------\n\n\ndef _test_batch_to_space_nd(input_shape, block_shape, crops, dtype=\"int32\"):\n    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=dtype)\n\n        out = array_ops.batch_to_space_nd(in_data, block_shape, crops)\n\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_batch_to_space_nd():\n    # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d\n    _test_batch_to_space_nd(input_shape=[4, 1, 1, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(input_shape=[4, 1, 1, 3], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(input_shape=[4, 2, 2, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]])\n\n    _test_batch_to_space_nd(input_shape=[4, 3, 3, 1], block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n\n######################################################################\n# SpaceToBatchND\n# --------------\n\n\ndef _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype=\"int32\"):\n    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=dtype)\n\n        out = array_ops.space_to_batch_nd(in_data, block_shape, paddings)\n\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_space_to_batch_nd():\n    # test cases: https://www.tensorflow.org/api_docs/python/tf/space_to_batch_nd\n    _test_space_to_batch_nd(input_shape=[1, 2, 2, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(input_shape=[1, 2, 2, 3], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(input_shape=[1, 4, 4, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]])\n\n    _test_space_to_batch_nd(input_shape=[2, 2, 4, 1], block_shape=[2, 2], paddings=[[0, 0], [2, 0]])\n\n\n#######################################################################\n# Pooling\n# -------\ndef _test_pooling_iteration(input_shape, **kwargs):\n    \"\"\"One iteration of pool operation with given shapes and attributes\"\"\"\n\n    x = -np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=input_shape, dtype=\"float32\")\n        out = nn_ops.pool(in_data, **kwargs)\n\n        compare_tflite_with_tvm(x, \"Placeholder:0\", [in_data], [out])\n\n\ndef _test_pooling(input_shape, **kwargs):\n    _test_pooling_iteration(input_shape, **kwargs)\n\n\ndef test_forward_pooling():\n    \"\"\"Pooling\"\"\"\n\n    for pool_type in [\"AVG\", \"MAX\"]:\n        _test_pooling(\n            input_shape=[2, 9, 10, 2],\n            window_shape=[1, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 10, 9, 2],\n            window_shape=[1, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 9, 10, 2],\n            window_shape=[2, 1],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[1, 1],\n        )\n\n        _test_pooling(\n            input_shape=[2, 10, 9, 2],\n            window_shape=[2, 3],\n            padding=\"SAME\",\n            pooling_type=pool_type,\n            dilation_rate=[1, 1],\n            strides=[2, 1],\n        )\n\n\ndef _test_l2_pool2d(input_shape, ksize, strides, padding, data_format, fused_func_name=None):\n    x = np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1\n\n    with tf.Graph().as_default():\n        in_data = tf.placeholder(dtype=tf.float32, name=\"input\", shape=input_shape)\n        out = tf.sqrt(\n            tf.nn.avg_pool(\n                tf.square(in_data),\n                ksize=ksize,\n                strides=strides,\n                padding=padding,\n                data_format=data_format,\n            )\n        )\n        out = with_fused_activation_function(out, fused_func_name)\n\n        compare_tflite_with_tvm(x, \"input\", [in_data], [out])\n\n\ndef test_forward_l2_pool2d():\n    _test_l2_pool2d([1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], \"SAME\", \"NHWC\", \"RELU6\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 1, 1, 1], [1, 1, 1, 1], \"SAME\", \"NHWC\", \"RELU6\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 2, 1, 1], [1, 1, 1, 1], \"SAME\", \"NHWC\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 2, 1, 1], [1, 1, 2, 1], \"SAME\", \"NHWC\")\n    _test_l2_pool2d([1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], \"VALID\", \"NHWC\", \"RELU\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 1, 1, 1], [1, 1, 1, 1], \"VALID\", \"NHWC\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 2, 1, 1], [1, 1, 1, 1], \"VALID\", \"NHWC\")\n    _test_l2_pool2d([2, 9, 10, 2], [1, 2, 1, 1], [1, 1, 2, 1], \"VALID\", \"NHWC\", \"RELU6\")\n\n\n#######################################################################\n# Convolution\n# -----------\n\n\ndef _test_tflite2_quantized_convolution(\n    input_shape, kernel_shape, filters, padding=\"valid\", data_format=None, int_quant_dtype=tf.int8\n):\n    \"\"\"One iteration of TFLite2 quantized convolution with given shapes and attributes\"\"\"\n    data_format = \"channels_last\" if data_format == \"NHWC\" else \"channels_first\"\n    data = np.random.uniform(0, 1, input_shape).astype(\"float32\")\n    _ = np.random.uniform(0, 1, kernel_shape).astype(\"float32\")\n\n    data_in = tf.keras.layers.Input(shape=data.shape[1:])\n    conv = tf.keras.layers.Conv2D(\n        filters=filters,\n        kernel_size=(kernel_shape[0], kernel_shape[1]),\n        activation=tf.nn.relu,\n        padding=padding,\n        data_format=data_format,\n    )(data_in)\n    keras_model = tf.keras.models.Model(data_in, conv)\n\n    # To create quantized values with dynamic range of activations, needs representative dataset\n    def representative_data_gen():\n        for _ in range(1):\n            yield [data]\n\n    tflite_model_quant = _quantize_keras_model(\n        keras_model,\n        representative_data_gen,\n        is_float_input=True,\n        is_float_output=True,\n        int_quant_dtype=int_quant_dtype,\n    )\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_quant, 0)\n    except AttributeError:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_quant, 0)\n    except ImportError as exc:\n        raise ImportError(\"The tflite package must be installed\") from exc\n\n    subgraph = tflite_model.Subgraphs(0)\n    model_input = subgraph.InputsAsNumpy()\n    input_node = subgraph.Tensors(model_input).Name().decode(\"utf-8\")\n\n    tflite_output = run_tflite_graph(tflite_model_quant, data)\n    if tf.__version__ < LooseVersion(\"2.9\"):\n        input_node = data_in.name.replace(\":0\", \"\")\n    else:\n        input_node = \"serving_default_\" + data_in.name + \":0\"\n    tvm_output = run_tvm_graph(tflite_model_quant, data, input_node)\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-2, atol=1e-2\n    )\n\n\ndef test_forward_quantized_convolution():\n    \"\"\"Quantized convolution\"\"\"\n    for int_quant_dtype in [tf.int8, tf.int16]:\n        _test_tflite2_quantized_convolution(\n            (1, 28, 28, 1),\n            (1, 1),\n            12,\n            data_format=\"NHWC\",\n            int_quant_dtype=int_quant_dtype,\n        )\n\n        _test_tflite2_quantized_convolution(\n            (1, 1, 28, 28),\n            (1, 1),\n            12,\n            data_format=\"NCWH\",\n            int_quant_dtype=int_quant_dtype,\n        )\n\n\ndef test_forward_quantized_depthwise_convolution():\n    for int_quant_dtype in [tf.int8, tf.int16]:\n        _test_tflite2_quantized_depthwise_convolution(\n            [1, 8, 8, 128], [1, 1, 128, 1], [1, 1], [1, 1], \"SAME\", \"NHWC\", 1, int_quant_dtype\n        )\n        _test_tflite2_quantized_depthwise_convolution(\n            [1, 17, 17, 12], [3, 3, 12, 1], [1, 1], [2, 2], \"VALID\", \"NHWC\", 1, int_quant_dtype\n        )\n        _test_tflite2_quantized_depthwise_convolution(\n            [1, 24, 24, 3], [7, 7, 3, 8], [1, 1], [2, 2], \"SAME\", \"NHWC\", 8, int_quant_dtype\n        )\n\n\ndef _test_tflite2_quantized_depthwise_convolution(\n    input_shape,\n    kernel_shape,\n    dilations,\n    strides,\n    padding,\n    data_format,\n    depth_multiplier,\n    int_quant_dtype=tf.int8,\n):\n    \"\"\"One iteration of TFLite2 quantized depthwise convolution with given shapes and attributes\"\"\"\n\n    data_format = \"channels_last\" if data_format == \"NHWC\" else \"channels_first\"\n    data = np.random.uniform(0, 1, input_shape).astype(\"float32\")\n    kernel = np.random.uniform(0, 1, kernel_shape).astype(\"float32\")\n\n    data_in = tf.keras.layers.Input(shape=data.shape[1:])\n    conv = tf.keras.layers.DepthwiseConv2D(\n        kernel_size=(kernel_shape[0], kernel_shape[1]),\n        strides=strides,\n        padding=padding,\n        data_format=data_format,\n        activation=\"relu\",\n        use_bias=False,\n        depth_multiplier=depth_multiplier,\n    )(data_in)\n    keras_model = tf.keras.models.Model(data_in, conv)\n    keras_model.layers[1].set_weights([kernel])\n\n    # To create quantized values with dynamic range of activations, needs representative dataset\n    def representative_data_gen():\n        for _ in range(1):\n            yield [data]\n\n    tflite_model_quant = _quantize_keras_model(\n        keras_model,\n        representative_data_gen,\n        is_float_input=True,\n        is_float_output=True,\n        int_quant_dtype=int_quant_dtype,\n    )\n\n    # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n    try:\n        import tflite.Model\n\n        tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_quant, 0)\n    except AttributeError:\n        import tflite\n\n        tflite_model = tflite.Model.GetRootAsModel(tflite_model_quant, 0)\n    except ImportError as exc:\n        raise ImportError(\"The tflite package must be installed\") from exc\n\n    subgraph = tflite_model.Subgraphs(0)\n    model_input = subgraph.InputsAsNumpy()\n    input_node = subgraph.Tensors(model_input).Name().decode(\"utf-8\")\n\n    tflite_output = run_tflite_graph(tflite_model_quant, data)\n    tvm_output = run_tvm_graph(tflite_model_quant, data, input_node)\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-2, atol=1e-2\n    )\n\n\ndef _test_convolution(\n    tensor_in_sizes,\n    filter_in_sizes,\n    dilations,\n    strides,\n    padding,\n    data_format,\n    is_depthwise=False,\n    quantized=False,\n    fp16_quantized=False,\n):\n    \"\"\"One iteration of convolution with given shapes and attributes\"\"\"\n\n    total_size_1 = 1\n    total_size_2 = 1\n    for s in tensor_in_sizes:\n        total_size_1 *= s\n    for s in filter_in_sizes:\n        total_size_2 *= s\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    if quantized:\n        data_array = np.random.uniform(0, 255, tensor_in_sizes).astype(\"uint8\")\n        filter_array = np.random.uniform(0, 255, filter_in_sizes).astype(\"uint8\")\n    else:\n        data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n        filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\", name=\"in_data\")\n        in_filter = constant_op.constant(\n            filter_array, shape=filter_in_sizes, dtype=\"float32\", name=\"in_filter\"\n        )\n        strides = [1] + strides + [1]\n        dilations = [1] + dilations + [1]\n\n        if is_depthwise:\n            out = nn_ops.depthwise_conv2d_native(\n                in_data, in_filter, strides=strides, padding=padding, data_format=data_format\n            )\n        else:\n            out = nn_ops.conv2d(\n                in_data, in_filter, strides=strides, padding=padding, data_format=data_format\n            )\n\n        if quantized and not fp16_quantized:\n            if is_depthwise:\n                # Quantized the inputs and feed them to the convolution\n                inq_data = tf.quantization.fake_quant_with_min_max_args(\n                    in_data, min=-100, max=100, name=\"inq_data\"\n                )\n                inq_filter = tf.quantization.fake_quant_with_min_max_args(\n                    in_filter, min=-100, max=100, name=\"inq_filter\"\n                )\n                out = nn_ops.depthwise_conv2d_native(\n                    inq_data, inq_filter, strides=strides, padding=padding, data_format=data_format\n                )\n                out = tf.quantization.fake_quant_with_min_max_args(\n                    out, min=-200, max=200, name=\"out\"\n                )\n\n                # Set the input quantization range\n                input_range = {\"in_data\": (-100, 100)} if quantized else None\n\n                # Compare\n                compare_tflite_with_tvm(\n                    data_array,\n                    \"in_data\",\n                    [in_data],\n                    [out],\n                    quantized=quantized,\n                    input_range=input_range,\n                    experimental_new_converter=True,\n                )\n            else:\n                # Quantized the inputs and feed them to the convolution\n                inq_data = tf.quantization.fake_quant_with_min_max_args(\n                    in_data, min=-100, max=100, name=\"inq_data\"\n                )\n                inq_filter = tf.quantization.fake_quant_with_min_max_args(\n                    in_filter, min=-100, max=100, name=\"inq_filter\"\n                )\n                out = nn_ops.conv2d(\n                    inq_data, inq_filter, strides=strides, padding=padding, data_format=data_format\n                )\n                out = tf.quantization.fake_quant_with_min_max_args(\n                    out, min=-200, max=200, name=\"out\"\n                )\n\n                # Set the input quantization range\n                input_range = {\"in_data\": (-100, 100)} if quantized else None\n\n                # Compare\n                compare_tflite_with_tvm(\n                    data_array,\n                    \"in_data\",\n                    [in_data],\n                    [out],\n                    quantized=quantized,\n                    input_range=input_range,\n                    experimental_new_converter=True,\n                )\n        else:\n            data_array = np.reshape(data_array, tensor_in_sizes).astype(\"float32\")\n            compare_tflite_with_tvm(data_array, \"in_data\", [in_data], [out])\n\n\ndef test_forward_convolution():\n    \"\"\"Convolution\"\"\"\n    for quantized in [False, True]:\n        for fp16_quantized in [False, True]:\n            _test_convolution(\n                [4, 8, 8, 176],\n                [1, 1, 176, 32],\n                [1, 1],\n                [1, 1],\n                \"SAME\",\n                \"NHWC\",\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 19],\n                [3, 3, 19, 19],\n                [1, 1],\n                [2, 2],\n                \"VALID\",\n                \"NHWC\",\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 124],\n                [1, 1, 124, 19],\n                [1, 1],\n                [1, 1],\n                \"SAME\",\n                \"NHWC\",\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 12],\n                [3, 3, 12, 32],\n                [1, 1],\n                [2, 2],\n                \"VALID\",\n                \"NHWC\",\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n\n            # depthwise convolution\n            _test_convolution(\n                [4, 8, 8, 176],\n                [1, 1, 176, 1],\n                [1, 1],\n                [1, 1],\n                \"SAME\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 19],\n                [3, 3, 19, 1],\n                [1, 1],\n                [2, 2],\n                \"VALID\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 124],\n                [1, 1, 124, 1],\n                [1, 1],\n                [1, 1],\n                \"SAME\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 12],\n                [3, 3, 12, 1],\n                [1, 1],\n                [2, 2],\n                \"VALID\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            _test_convolution(\n                [4, 17, 17, 12],\n                [3, 3, 12, 2],\n                [1, 1],\n                [2, 2],\n                \"VALID\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n            # depthwise convolution with single input channel\n            _test_convolution(\n                [1, 76, 64, 1],\n                [9, 5, 1, 96],\n                [1, 1],\n                [1, 1],\n                \"SAME\",\n                \"NHWC\",\n                True,\n                quantized=quantized,\n                fp16_quantized=fp16_quantized,\n            )\n\n    # TFLite2 quantized convolution testing\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.3.0\"):\n        _test_convolution(\n            [1, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], \"SAME\", \"NHWC\", quantized=True\n        )\n        _test_convolution(\n            [1, 17, 17, 12], [3, 3, 12, 32], [1, 1], [2, 2], \"VALID\", \"NHWC\", quantized=True\n        )\n        _test_convolution(\n            [1, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], \"VALID\", \"NHWC\", quantized=True\n        )\n        _test_convolution(\n            [1, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], \"SAME\", \"NHWC\", quantized=True\n        )\n\n\n#######################################################################\n# Transpose Convolution\n# ---------------------\n\n\ndef _test_transpose_conv(\n    tensor_in_sizes,\n    filter_in_sizes,\n    output_shape,\n    strides,\n    padding,\n    quantized=False,\n    fp16_quantized=False,\n):\n    \"\"\"One iteration of transpose convolution with given shapes and attributes\"\"\"\n\n    total_size_1 = 1\n    total_size_2 = 1\n    for s in tensor_in_sizes:\n        total_size_1 *= s\n    for s in filter_in_sizes:\n        total_size_2 *= s\n\n    with tf.Graph().as_default():\n        if quantized and not fp16_quantized:\n            # Initializes the input tensor with array containing incrementing\n            # numbers from 1.\n            data_array = [max(f, 255) for f in range(1, total_size_1 + 1)]\n            filter_array = [max(f, 255) for f in range(1, total_size_2 + 1)]\n            data_array = np.reshape(data_array, tensor_in_sizes).astype(\"uint8\")\n            filter_array = np.reshape(filter_array, filter_in_sizes).astype(\"uint8\")\n\n            in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\", name=\"in_data\")\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-100, max=100, name=\"q_data\"\n            )\n            input_range = {\"q_data\": (-100, 100)}\n\n            in_filter = constant_op.constant(\n                filter_array, shape=filter_in_sizes, dtype=\"float32\", name=\"in_filter\"\n            )\n            inq_filter = tf.quantization.fake_quant_with_min_max_args(\n                in_filter, min=-100, max=100, name=\"q_filter\"\n            )\n\n            strides = [1] + strides + [1]\n\n            out = nn_ops.conv2d_transpose(\n                inq_data, inq_filter, output_shape=output_shape, strides=strides, padding=padding\n            )\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-100, max=100, name=\"out\")\n            compare_tflite_with_tvm(\n                [data_array], [\"q_data\"], [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            # Initializes the input tensor with array containing incrementing\n            # numbers from 1.\n            data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]\n            filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]\n\n            in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype=\"float32\", name=\"in_data\")\n            in_filter = constant_op.constant(\n                filter_array, shape=filter_in_sizes, dtype=\"float32\", name=\"in_filter\"\n            )\n            strides = [1] + strides + [1]\n            # in_filter layout is HWOI\n            out = nn_ops.conv2d_transpose(\n                in_data, in_filter, output_shape=output_shape, strides=strides, padding=padding\n            )\n            data_array = np.reshape(data_array, tensor_in_sizes).astype(\"float32\")\n            compare_tflite_with_tvm(\n                [data_array], [\"in_data\"], [in_data], [out], fp16_quantized=fp16_quantized\n            )\n\n\ndef test_forward_transpose_conv():\n    \"\"\"Transpose convolution\"\"\"\n    for quantized in [True, False]:\n        for fp16_quantized in [True, False]:\n            # odd size input, padding VALID\n            _test_transpose_conv(\n                [1, 5, 6, 16],\n                [2, 2, 16, 16],\n                [1, 10, 12, 16],\n                [2, 2],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            # odd size input, padding SAME\n            _test_transpose_conv(\n                [1, 5, 6, 16],\n                [2, 2, 16, 16],\n                [1, 10, 12, 16],\n                [2, 2],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            # kernel 3x3, padding VALID\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [3, 3, 5, 16],\n                [4, 34, 34, 5],\n                [1, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [3, 3, 5, 16],\n                [1, 65, 65, 5],\n                [2, 2],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [3, 3, 5, 16],\n                [1, 65, 34, 5],\n                [2, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n\n            # kernel 3x3, padding SAME\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [3, 3, 5, 16],\n                [4, 32, 32, 5],\n                [1, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [3, 3, 5, 16],\n                [1, 64, 64, 5],\n                [2, 2],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [3, 3, 5, 16],\n                [1, 64, 32, 5],\n                [2, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n\n            # kernel 2x2, padding VALID\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [2, 2, 5, 16],\n                [4, 33, 33, 5],\n                [1, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [2, 2, 5, 16],\n                [1, 64, 64, 5],\n                [2, 2],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [2, 2, 5, 16],\n                [1, 64, 33, 5],\n                [2, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n\n            # kernel 2x2, padding SAME\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [2, 2, 5, 16],\n                [4, 32, 32, 5],\n                [1, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [2, 2, 5, 16],\n                [1, 64, 64, 5],\n                [2, 2],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [2, 2, 5, 16],\n                [1, 64, 32, 5],\n                [2, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n\n            # kernel 1x1, padding VALID\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [1, 1, 5, 16],\n                [4, 32, 32, 5],\n                [1, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [1, 1, 5, 16],\n                [1, 63, 63, 5],\n                [2, 2],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [1, 1, 5, 16],\n                [1, 63, 32, 5],\n                [2, 1],\n                \"VALID\",\n                quantized,\n                fp16_quantized,\n            )\n\n            # kernel 1x1, padding SAME\n            _test_transpose_conv(\n                [4, 32, 32, 16],\n                [1, 1, 5, 16],\n                [4, 32, 32, 5],\n                [1, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [1, 1, 5, 16],\n                [1, 63, 63, 5],\n                [2, 2],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n            _test_transpose_conv(\n                [1, 32, 32, 16],\n                [1, 1, 5, 16],\n                [1, 63, 32, 5],\n                [2, 1],\n                \"SAME\",\n                quantized,\n                fp16_quantized,\n            )\n\n\n#######################################################################\n# Reshape\n# -------\n\n\ndef _test_reshape(data, out_shape, wrap_shape, quantized=False):\n    \"\"\"One iteration of reshape operation with given data and out shape\"\"\"\n    if quantized:\n        with tf.Graph().as_default():\n            in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in\")\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-100, max=100, name=\"inq_0\"\n            )\n\n            input_range = {\"inq_0\": (-100, 100)}\n            out_shape = out_shape if not wrap_shape else np.array(out_shape, dtype=np.int32)\n\n            in_shape = (\n                out_shape\n                if not wrap_shape\n                else array_ops.placeholder(\n                    shape=out_shape.shape, dtype=out_shape.dtype, name=\"Newshape\"\n                )\n            )\n\n            out = array_ops.reshape(inq_data, in_shape)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-200, max=200, name=\"out\")\n            compare_tflite_with_tvm(\n                [data, out_shape] if wrap_shape else [data],\n                [\"inq_0:0\", \"Newshape:0\"] if wrap_shape else [\"inq_0:0\"],\n                [inq_data, in_shape] if wrap_shape else [inq_data],\n                [out],\n                quantized=True,\n                input_range=input_range,\n                mode=\"vm\",\n            )\n    else:\n        # Test with tensor and constant\n        with tf.Graph().as_default():\n            in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n            out_shape = out_shape if not wrap_shape else np.array(out_shape, dtype=np.int32)\n\n            in_shape = (\n                out_shape\n                if not wrap_shape\n                else array_ops.placeholder(\n                    shape=out_shape.shape, dtype=out_shape.dtype, name=\"Newshape\"\n                )\n            )\n\n            out = array_ops.reshape(in_data, in_shape)\n\n            compare_tflite_with_tvm(\n                [data, out_shape] if wrap_shape else [data],\n                [\"Placeholder:0\", \"Newshape:0\"] if wrap_shape else [\"Placeholder:0\"],\n                [in_data, in_shape] if wrap_shape else [in_data],\n                [out],\n                mode=\"vm\",\n            )\n\n\ndef test_forward_reshape():\n    for wrap in [True, False]:\n        _test_reshape(np.arange(6.0, dtype=np.float32), [2, 3], wrap)\n        _test_reshape(np.arange(6), [-1, 2], wrap)\n        _test_reshape(np.arange(6), [3, -1], wrap)\n        _test_reshape(np.arange(6), [-1], wrap)\n\n    _test_reshape(np.arange(6, dtype=np.uint8), [2, 3], False, True)\n    _test_reshape(np.arange(6, dtype=np.uint8), [-1, 2], False, True)\n\n\n#######################################################################\n# Resize\n# ------\n\n\ndef _test_resize(\n    tf_resize_op, images_data, size_data, align_corners, half_pixel_centers, quantized=False\n):\n    \"\"\"One iteration of Resize\"\"\"\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        images_tensor = array_ops.placeholder(shape=images_data.shape, dtype=\"float32\", name=\"in\")\n        size = ops.convert_to_tensor(size_data, dtype=size_data.dtype)\n\n        if quantized:\n            images_tensor_q = tf.quantization.fake_quant_with_min_max_args(\n                images_tensor, min=-3, max=2, name=\"in\"\n            )\n            input_range = {\"in\": (-3, 2)}\n            out_tensor = tf_resize_op(\n                images=images_tensor_q,\n                size=size,\n                align_corners=align_corners,\n                half_pixel_centers=half_pixel_centers,\n            )\n            out_tensor = tf.quantization.fake_quant_with_min_max_args(\n                out_tensor, min=-3, max=2, name=\"out_tensor\"\n            )\n\n            compare_tflite_with_tvm(\n                [images_data],\n                [\"in:0\"],\n                [images_tensor],\n                [out_tensor],\n                quantized=True,\n                input_range=input_range,\n            )\n        else:\n            out_tensor = tf_resize_op(\n                images=images_tensor,\n                size=size,\n                align_corners=align_corners,\n                half_pixel_centers=half_pixel_centers,\n            )\n            compare_tflite_with_tvm([images_data], [\"in:0\"], [images_tensor], [out_tensor])\n\n\ndef test_all_resize():\n    \"\"\"Resize\"\"\"\n    images_data = np.random.uniform(0, 255, (1, 16, 16, 3))\n    images_data_float32 = images_data.astype(np.float32)\n    images_data_uint8 = images_data.astype(np.uint8)\n    size_data = np.array([8, 8]).astype(\"int32\")\n    ### RESIZE_BILINEAR\n    _test_resize(\n        tf.image.resize_bilinear,\n        images_data_float32,\n        size_data,\n        align_corners=False,\n        half_pixel_centers=False,\n        quantized=False,\n    )\n    _test_resize(\n        tf.image.resize_bilinear,\n        images_data_float32,\n        size_data,\n        align_corners=True,\n        half_pixel_centers=False,\n        quantized=False,\n    )\n    _test_resize(\n        tf.image.resize_bilinear,\n        images_data_uint8,\n        size_data,\n        align_corners=False,\n        half_pixel_centers=False,\n        quantized=True,\n    )\n    _test_resize(\n        tf.image.resize_bilinear,\n        images_data_uint8,\n        size_data,\n        align_corners=True,\n        half_pixel_centers=False,\n        quantized=True,\n    )\n    _test_resize(\n        tf.image.resize_bilinear,\n        images_data_uint8,\n        size_data,\n        align_corners=False,\n        half_pixel_centers=True,\n        quantized=True,\n    )\n    ### RESIZE_NEAREST_NEIGHBOR (was added in v1.13)\n    # According to topi resize.h\n    # Align corners not supported for nearest neighbour\n\n    if \"RESIZE_NEAREST_NEIGHBOR\" in dir(BuiltinOperator()):\n        _test_resize(\n            tf.image.resize_nearest_neighbor,\n            images_data_float32,\n            size_data,\n            align_corners=False,\n            half_pixel_centers=False,\n        )\n        _test_resize(\n            tf.image.resize_nearest_neighbor,\n            images_data_float32,\n            size_data,\n            align_corners=True,\n            half_pixel_centers=False,\n        )\n        _test_resize(\n            tf.image.resize_nearest_neighbor,\n            images_data_float32,\n            size_data,\n            align_corners=False,\n            half_pixel_centers=True,\n        )\n\n\n#######################################################################\n# Range\n# -----\ndef _test_range(start, limit, delta):\n    # tflite 1.13 convert method does not accept empty shapes\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            start_scalar, limit_scalar, delta_scalar = (\n                tf.placeholder(dtype=start.dtype, shape=(), name=\"start\"),\n                tf.placeholder(dtype=limit.dtype, shape=(), name=\"limit\"),\n                tf.placeholder(dtype=delta.dtype, shape=(), name=\"delta\"),\n            )\n\n            out = tf.range(start_scalar, limit_scalar, delta_scalar, name=\"range\")\n\n            compare_tflite_with_tvm(\n                [start, limit, delta],\n                [\"start\", \"limit\", \"delta\"],\n                [start_scalar, limit_scalar, delta_scalar],\n                [out],\n                mode=\"vm\",\n                quantized=False,\n            )\n\n\ndef _test_range_default():\n    # tflite 1.13 convert method does not accept empty shapes\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            inputs = [\n                tf.placeholder(dtype=tf.int32, shape=(), name=\"p1\"),\n                tf.placeholder(dtype=tf.int32, shape=(), name=\"p2\"),\n            ]\n            outputs = [\n                tf.range(start=inputs[0], limit=inputs[1]),  # use default delta\n                tf.range(\n                    start=inputs[1]\n                ),  # use start as limit with 0 as the first item in the range\n            ]\n\n            compare_tflite_with_tvm(\n                [np.int32(1), np.int32(18)], [\"p1\", \"p2\"], inputs, outputs, mode=\"vm\"\n            )\n\n\ndef test_forward_range():\n    _test_range(np.int32(1), np.int32(18), np.int32(3))\n    _test_range(np.int32(1), np.int32(18), np.float32(3.1))  # increment is of type float\n    _test_range(np.float32(1.0), np.int32(18), np.int32(3.1))  # start is of type float\n    _test_range_default()\n\n\n#######################################################################\n# Shape\n# -----\n\n\ndef _test_shape(dtype):\n    # tflite 1.13 convert method does not accept empty shapes\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        tf.reset_default_graph()\n        with tf.Graph().as_default():\n            data = np.array([1, 18, 3], dtype=np.int32)\n            start = tf.placeholder(dtype=tf.int32, shape=[], name=\"start\")\n            limit = tf.placeholder(dtype=tf.int32, shape=[], name=\"limit\")\n            delta = tf.placeholder(dtype=tf.int32, shape=[], name=\"delta\")\n            tf_range = tf.range(start, limit, delta, tf.int32, name=\"range\")\n            out = tf.shape(tf_range, out_type=dtype)\n            out = tf.add(out, tf.constant([1], dtype=dtype))\n            compare_tflite_with_tvm(\n                list(np.nditer(data)),\n                [\"start\", \"limit\", \"delta\"],\n                [start, limit, delta],\n                [out],\n                mode=\"vm\",\n            )\n\n\ndef test_forward_shape():\n    _test_shape(tf.int32)\n    _test_shape(tf.int64)\n\n\n#######################################################################\n# Concatenation\n# -------------\n\n\ndef _test_concatenation(data, axis):\n    \"\"\"One iteration of concatenation\"\"\"\n\n    assert len(data) >= 1\n\n    with tf.Graph().as_default():\n        in_data = [\n            array_ops.placeholder(shape=tensor.shape, dtype=tensor.dtype, name=f\"in_{idx}\")\n            for idx, tensor in enumerate(data)\n        ]\n        out = array_ops.concat(in_data, axis)\n        name = [f\"in_{idx}:0\" for idx in range(len(data))]\n\n        compare_tflite_with_tvm(data, name, in_data, [out])\n\n\ndef test_forward_concatenation():\n\n    _test_concatenation([np.arange(6).reshape((1, 2, 1, 3)), np.arange(6).reshape((1, 2, 1, 3))], 1)\n\n    _test_concatenation([np.arange(6).reshape((3, 2)), np.arange(6).reshape((3, 2))], 1)\n\n    _test_concatenation(\n        [\n            np.arange(6).reshape((2, 1, 1, 3)),\n            np.arange(6).reshape((2, 1, 1, 3)),\n            np.arange(6).reshape((2, 1, 1, 3)),\n        ],\n        1,\n    )\n\n\n#######################################################################\n# Unary elemwise\n# --------------\n\n\ndef _test_unary_elemwise(math_op, data, quantized, quant_range=(-6, 6), int_quant_dtype=tf.int8):\n    \"\"\"One iteration of unary elemwise\"\"\"\n    if quantized:\n        with tf.Graph().as_default():\n            quant_min, quant_max = quant_range\n            in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=quant_min, max=quant_max, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (quant_min, quant_max)}\n            out = math_op(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(\n                out, min=quant_min, max=quant_max, name=\"out\"\n            )\n            compare_tflite_with_tvm(\n                data,\n                \"inq_0:0\",\n                [inq_data],\n                [out],\n                quantized=True,\n                input_range=input_range,\n                experimental_new_converter=True,\n                int_quant_dtype=int_quant_dtype,\n            )\n    else:\n        with tf.Graph().as_default():\n            in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype, name=\"in\")\n            out = math_op(in_data)\n            compare_tflite_with_tvm(data, [\"in:0\"], [in_data], [out])\n\n\ndef _unary_elewise_create_model(math_op, data, offset=0, int_quant_dtype=tf.int8):\n    class Model(tf.Module):\n        @tf.function\n        def tf_function(self, x):\n            op = math_op(x)\n            return op\n\n    if int_quant_dtype in (tf.int8, tf.uint8):\n        _ = \"int8\"\n    elif int_quant_dtype in (tf.int16, tf.uint16):\n        _ = \"int16\"\n    else:\n        raise Exception(f\"Unsupported dtype '{int_quant_dtype}' for unary elementwise test.\")\n\n    model = Model()\n\n    # Save the model\n    export_dir = tempfile.gettempdir() + \"/tf_model\"\n    tf.saved_model.save(\n        model,\n        export_dir,\n        signatures=model.tf_function.get_concrete_function(\n            tf.TensorSpec(data.shape, tf.float32, name=\"input\")\n        ),\n    )\n\n    # Convert the model\n    def representative_dataset():\n        for _ in range(100):\n            tmp_data = np.random.rand(*tuple(data.shape))\n            yield [tmp_data.astype(np.float32) * 2 - offset]\n\n    converter = tf.lite.TFLiteConverter.from_saved_model(export_dir)\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    converter.representative_dataset = representative_dataset\n\n    if int_quant_dtype in (tf.int16, tf.uint16):\n        converter.target_spec.supported_ops = [\n            tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8\n        ]\n    else:\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n\n    converter.inference_input_type = int_quant_dtype\n    converter.inference_output_type = int_quant_dtype\n\n    tflite_model = converter.convert()\n    return tflite_model\n\n\n#######################################################################\n# Abs\n# ----\n\n\ndef _test_abs(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of abs\"\"\"\n    if quantized:\n        tflite_model_quant = _unary_elewise_create_model(\n            tf.math.abs, data, offset=1, int_quant_dtype=int_quant_dtype\n        )\n        tflite_output = run_tflite_graph(tflite_model_quant, data)\n\n        # TFLite 2.6.x upgrade support\n        if tf.__version__ < LooseVersion(\"2.6.1\"):\n            in_node = [\"serving_default_input_int8\"]\n        elif tf.__version__ < LooseVersion(\"2.9\"):\n            in_node = (\n                [\"serving_default_input_int16\"] if int_quant_dtype == tf.int16 else [\"tfl.quantize\"]\n            )\n        else:\n            in_node = \"serving_default_input\"\n\n        tvm_output = run_tvm_graph(tflite_model_quant, data, in_node)\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-2\n        )\n    else:\n        return _test_unary_elemwise(math_ops.abs, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Rsqrt\n# ----\n\n\ndef _test_rsqrt(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of rsqrt\"\"\"\n\n    # tensorflow version upgrade support\n    if tf.__version__ < LooseVersion(\"2.6.1\") or not quantized:\n        return _test_unary_elemwise(\n            math_ops.rsqrt, data, quantized, quant_range=[1, 6], int_quant_dtype=int_quant_dtype\n        )\n    else:\n        tflite_model_quant = _unary_elewise_create_model(\n            tf.math.rsqrt, data, int_quant_dtype=int_quant_dtype\n        )\n        tflite_output = run_tflite_graph(tflite_model_quant, data)\n        if tf.__version__ < LooseVersion(\"2.9\"):\n            in_node = [\"tfl.quantize\"]\n        else:\n            in_node = \"serving_default_input\"\n        tvm_output = run_tvm_graph(tflite_model_quant, data, in_node)\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-2\n        )\n\n\n#######################################################################\n# Ceil\n# ----\n\n\ndef _test_ceil(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of ceil\"\"\"\n    return _test_unary_elemwise(math_ops.ceil, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Floor\n# -----\n\n\ndef _test_floor(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of floor\"\"\"\n    return _test_unary_elemwise(math_ops.floor, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Round\n# -----\n\n\ndef _test_round(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of round\"\"\"\n    return _test_unary_elemwise(math_ops.round, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Exp\n# ---\n\n\ndef _test_exp(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of exp\"\"\"\n    return _test_unary_elemwise(math_ops.exp, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Log\n# ---\n\n\ndef _test_log(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of log\"\"\"\n    return _test_unary_elemwise(\n        math_ops.log, data, quantized, quant_range=[1, 6], int_quant_dtype=int_quant_dtype\n    )\n\n\n#######################################################################\n# Sin\n# ---\n\n\ndef _test_sin(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of sin\"\"\"\n    return _test_unary_elemwise(math_ops.sin, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Cos\n# ---\n\n\ndef _test_cos(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of cos\"\"\"\n    if quantized:\n        tflite_model_quant = _unary_elewise_create_model(\n            tf.math.cos, data, int_quant_dtype=int_quant_dtype\n        )\n        tflite_output = run_tflite_graph(tflite_model_quant, data)\n        if tf.__version__ < LooseVersion(\"2.9\"):\n            in_node = [\"tfl.quantize\"]\n        else:\n            in_node = \"serving_default_input\"\n        tvm_output = run_tvm_graph(tflite_model_quant, data, in_node)\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-2\n        )\n    else:\n        return _test_unary_elemwise(math_ops.cos, data, quantized)\n\n\n#######################################################################\n# Tan\n# ---\n\n\ndef _test_tan(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of tan\"\"\"\n    return _test_unary_elemwise(math_ops.tan, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Square\n# ------\n\n\ndef _test_square(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of square\"\"\"\n    return _test_unary_elemwise(math_ops.square, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Neg\n# ------\n\n\ndef _test_neg(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of neg\"\"\"\n    return _test_unary_elemwise(math_ops.neg, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\n#######################################################################\n# Sqrt\n# ------\n\n\ndef _test_sqrt(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of sqrt\"\"\"\n    return _test_unary_elemwise(\n        math_ops.sqrt, data, quantized, quant_range=[1, 6], int_quant_dtype=int_quant_dtype\n    )\n\n\n#######################################################################\n# Elu\n# ---\n\n\ndef _test_elu(data, quantized, int_quant_dtype=tf.int8):\n    \"\"\"One iteration of elu\"\"\"\n    return _test_unary_elemwise(nn_ops.elu, data, quantized, int_quant_dtype=int_quant_dtype)\n\n\ndef _test_forward_unary_elemwise(test_op, int_quant_dtype=None, quantized=True, negative=True):\n    # input data\n    in_data, inq_data = [], []\n\n    np_dtype = int_quant_dtype.as_numpy_dtype if int_quant_dtype else np.uint8\n\n    # quantized input data\n    if quantized:\n        inq_data.append(np.arange(1, 240, 40, dtype=np_dtype))\n        inq_data.append(np.arange(1, 240, 40, dtype=np_dtype).reshape((2, 1, 3)))\n        if int_quant_dtype == np.int8:\n            inq_data.append(np.arange(-128, 127, 45, dtype=np.int8))\n\n    for data in inq_data:\n        test_op(data, quantized=True, int_quant_dtype=int_quant_dtype)\n\n    # normal input data\n    if negative:\n        in_data.append(np.arange(-2.0, 4.0, dtype=np.float32))\n        in_data.append(np.arange(-2.0, 4.0, dtype=np.float32).reshape((2, 1, 3)))\n    else:\n        in_data.append(np.arange(1.0, 7.0, dtype=np.float32))\n        in_data.append(np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)))\n\n    for data in in_data:\n        test_op(data, quantized=False, int_quant_dtype=int_quant_dtype)\n\n\ndef test_all_unary_elemwise():\n    \"\"\"All unary elemwise\"\"\"\n    _test_forward_unary_elemwise(_test_abs, int_quant_dtype=tf.int8)\n    _test_forward_unary_elemwise(_test_abs, int_quant_dtype=tf.int16)\n    _test_forward_unary_elemwise(_test_floor)\n    _test_forward_unary_elemwise(_test_exp)\n    _test_forward_unary_elemwise(_test_log, negative=False)\n    _test_forward_unary_elemwise(_test_square)\n    _test_forward_unary_elemwise(_test_sin)\n    _test_forward_unary_elemwise(_test_neg)\n    _test_forward_unary_elemwise(_test_sqrt, negative=False)\n    # tensorflow version upgrade support\n    if tf.__version__ < LooseVersion(\"2.6.1\"):\n        _test_forward_unary_elemwise(_test_rsqrt, negative=False, int_quant_dtype=tf.uint8)\n    else:\n        _test_forward_unary_elemwise(_test_rsqrt, negative=False, int_quant_dtype=tf.int8)\n    # ceil and cos come with TFLite 1.14.0.post1 fbs schema\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_forward_unary_elemwise(_test_ceil)\n        if tf.__version__ < LooseVersion(\"2.6.1\"):\n            _test_forward_unary_elemwise(_test_cos, quantized=False)\n        else:\n            _test_forward_unary_elemwise(_test_cos, int_quant_dtype=tf.int8)\n        _test_forward_unary_elemwise(_test_round)\n        # This fails with TF and Tflite 1.15.2, this could not have been tested\n        # in CI or anywhere else. The failure mode is that we see a backtrace\n        # from the converter that we need to provide a custom Tan operator\n        # implementation.\n        # _test_forward_unary_elemwise(_test_tan)\n        _test_forward_unary_elemwise(_test_elu, quantized=False)\n\n\n#######################################################################\n# Element-wise\n# ------------\n\n\ndef _test_elemwise(\n    math_op,\n    data,\n    fused_activation_function=None,\n    quantized=False,\n    qnn_op=None,\n    same_qnn_params=False,\n    comparison_op=False,\n):\n    \"\"\"One iteration of elemwise\"\"\"\n\n    assert len(data) == 2\n\n    def __test_elemwise(in_data):\n        assert len(in_data) == 2\n        if quantized:\n            # set the fp32 output range with respect to the operation\n            out_min, out_max = _test_elemwise_qnn_out_range(qnn_op)\n            inq0_min, inq0_max = (-100, 100)\n            inq1_min, inq1_max = (-50, 50)\n\n            # if requested use same quantization parameters provided by _test_elemwise_qnn_out_range\n            if same_qnn_params:\n                inq0_min, inq0_max = (out_min, out_max)\n                inq1_min, inq1_max = (out_min, out_max)\n\n            # fake_quant will keep the tensors in float32 until the conversion in the session\n            inq_data = [\n                tf.quantization.fake_quant_with_min_max_args(\n                    in_data[0], min=out_min, max=out_max, name=\"inq_0\"\n                )\n                if in_data[0] is not None\n                else tf.quantization.fake_quant_with_min_max_args(\n                    data[0], min=out_min, max=out_max, name=\"const_tensor0\"\n                ),\n                tf.quantization.fake_quant_with_min_max_args(\n                    in_data[1], min=out_min, max=out_max, name=\"inq_1\"\n                )\n                if in_data[1] is not None\n                else tf.quantization.fake_quant_with_min_max_args(\n                    data[1], min=out_min, max=out_max, name=\"const_tensor1\"\n                ),\n            ]\n\n            input_range = {\n                x[1][0]: x[1][1]\n                for x in zip(\n                    in_data, ((\"inq_0\", (inq0_min, inq0_max)), (\"inq_1\", (inq1_min, inq1_max)))\n                )\n                if x[0] is not None\n            }\n\n            if comparison_op:\n                out = math_op(inq_data[0], inq_data[1])\n                out = with_fused_activation_function(out, fused_activation_function)\n\n                compare_tflite_with_tvm(\n                    [x[1] for x in zip(in_data, data) if x[0] is not None],\n                    [x + \":0\" for x in input_range.keys()],\n                    [x[1] for x in zip(in_data, inq_data) if x[0] is not None],\n                    [out],\n                    quantized=True,\n                    input_range=input_range,\n                    experimental_new_converter=same_qnn_params,\n                )\n            else:\n                out = math_op(inq_data[0], inq_data[1])\n                out = with_fused_activation_function(out, fused_activation_function)\n                out = tf.quantization.fake_quant_with_min_max_args(\n                    out, min=out_min, max=out_max, name=\"out\"\n                )\n\n                # Note same_qnn_params uses experimental_new_converter as toco failed\n                compare_tflite_with_tvm(\n                    [x[1] for x in zip(in_data, data) if x[0] is not None],\n                    [x + \":0\" for x in input_range.keys()],\n                    [x[1] for x in zip(in_data, inq_data) if x[0] is not None],\n                    [out],\n                    quantized=True,\n                    input_range=input_range,\n                    experimental_new_converter=same_qnn_params,\n                )\n        else:\n            out = math_op(\n                in_data[0]\n                if in_data[0] is not None\n                else ops.convert_to_tensor(data[0], dtype=data[0].dtype),\n                in_data[1]\n                if in_data[1] is not None\n                else ops.convert_to_tensor(data[1], dtype=data[1].dtype),\n            )\n            out = with_fused_activation_function(out, fused_activation_function)\n            compare_tflite_with_tvm(\n                [x[1] for x in zip(in_data, data) if x[0] is not None],\n                [x[1] for x in zip(in_data, (\"in_0:0\", \"in_1:0\")) if x[0] is not None],\n                [x for x in in_data if x is not None],\n                [out],\n            )\n\n    # Test with two tensors\n    with tf.Graph().as_default():\n        __test_elemwise(\n            in_data=[\n                array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in_0\"),\n                array_ops.placeholder(shape=data[1].shape, dtype=\"float32\", name=\"in_1\"),\n            ]\n        )\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        __test_elemwise(\n            in_data=[array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in_0\"), None]\n        )\n    # Test with constant and tensor\n    with tf.Graph().as_default():\n        __test_elemwise(\n            in_data=[None, array_ops.placeholder(shape=data[1].shape, dtype=\"float32\", name=\"in_1\")]\n        )\n\n\n#######################################################################\n# Add\n# ---\n\n\ndef _test_add(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of add\"\"\"\n    return _test_elemwise(math_ops.add, data, fused_activation_function, quantized, qnn_op)\n\n\n#######################################################################\n# Subtract\n# --------\n\n\ndef _test_sub(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of subtract\"\"\"\n    return _test_elemwise(math_ops.subtract, data, fused_activation_function, quantized, qnn_op)\n\n\n#######################################################################\n# Mul\n# ---\n\n\ndef _test_mul(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of mul\"\"\"\n    return _test_elemwise(math_ops.multiply, data, fused_activation_function, quantized, qnn_op)\n\n\n#######################################################################\n# Divide\n# ------\n\n\ndef _test_div(data, fused_activation_function=None):\n    \"\"\"One iteration of divide\"\"\"\n    return _test_elemwise(math_ops.divide, data, fused_activation_function)\n\n\n#######################################################################\n# Power\n# -----\n\n\ndef _test_pow(data):\n    \"\"\"One iteration of power\"\"\"\n    return _test_elemwise(math_ops.pow, data)\n\n\n#######################################################################\n# Maximum\n# -------\n\n\ndef _test_maximum(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of maximum\"\"\"\n    return _test_elemwise(\n        math_ops.maximum, data, fused_activation_function, quantized, qnn_op, same_qnn_params=True\n    )\n\n\n#######################################################################\n# Minimum\n# -------\n\n\ndef _test_minimum(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of minimum\"\"\"\n    return _test_elemwise(\n        math_ops.minimum, data, fused_activation_function, quantized, qnn_op, same_qnn_params=True\n    )\n\n\n#######################################################################\n# Greater\n# -------\n\n\ndef _test_greater(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of greater\"\"\"\n    return _test_elemwise(\n        math_ops.greater,\n        data,\n        fused_activation_function,\n        quantized,\n        qnn_op,\n        same_qnn_params=True,\n        comparison_op=True,\n    )\n\n\n#######################################################################\n# Greater_equal\n# -------------\n\n\ndef _test_greater_equal(data):\n    \"\"\"One iteration of greater_equal\"\"\"\n    return _test_elemwise(math_ops.greater_equal, data)\n\n\n#######################################################################\n# Less\n# ----\n\n\ndef _test_less(data):\n    \"\"\"One iteration of less\"\"\"\n    return _test_elemwise(math_ops.less, data)\n\n\n#######################################################################\n# Less_equal\n# ----------\n\n\ndef _test_less_equal(data):\n    \"\"\"One iteration of less_equal\"\"\"\n    return _test_elemwise(math_ops.less_equal, data)\n\n\n#######################################################################\n# Equal\n# -----\n\n\ndef _test_equal(data, fused_activation_function=None, quantized=False, qnn_op=None):\n    \"\"\"One iteration of equal\"\"\"\n    return _test_elemwise(\n        math_ops.equal,\n        data,\n        fused_activation_function,\n        quantized,\n        qnn_op,\n        same_qnn_params=True,\n        comparison_op=True,\n    )\n\n\n#######################################################################\n# Not_equal\n# ---------\n\n\ndef _test_not_equal(data):\n    \"\"\"One iteration of not_equal\"\"\"\n    return _test_elemwise(math_ops.not_equal, data)\n\n\n#######################################################################\n# Squared_difference\n# ------------------\n\n\ndef _test_squared_difference(data):\n    \"\"\"One iteration of squared difference\"\"\"\n    return _test_elemwise(math_ops.squared_difference, data)\n\n\n#######################################################################\n# Floor_divide\n# ------------\n\n\ndef _test_floor_divide(data):\n    \"\"\"One iteration of floor_div\"\"\"\n    return _test_elemwise(math_ops.floordiv, data)\n\n\n#######################################################################\n# Floor_mod\n# ---------\n\n\ndef _test_floor_mod(data):\n    \"\"\"One iteration of floor_mod\"\"\"\n    return _test_elemwise(math_ops.floormod, data)\n\n\ndef _test_forward_elemwise(testop):\n    \"\"\"Elewise\"\"\"\n    testop(\n        [\n            np.arange(6.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n        ]\n    )\n    testop(\n        [\n            np.arange(6.0, dtype=np.float32).reshape((2, 1, 3)),\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)),\n        ]\n    )\n    testop(\n        [\n            np.arange(3.0, dtype=np.float32).reshape((1, 3)),\n            np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3)),\n        ]\n    )\n\n\ndef _test_forward_elemwise_quantized(testop):\n    testop(\n        [\n            np.array(np.random.uniform(0, 255, (3, 6)), dtype=np.uint8),\n            np.array(np.random.uniform(0, 255, (3, 6)), dtype=np.uint8),\n        ],\n        quantized=True,\n        qnn_op=testop,\n    )\n\n\ndef _test_elemwise_qnn_out_range(qnn_op):\n    # set the fake_quant output range with respect to the input tensors float32 range\n    qnn_out_range = {\n        _test_add: (-150, 150),\n        _test_sub: (-150, 150),\n        _test_mul: (-5e3, 5e3),\n        _test_maximum: (-112, 111),\n        _test_minimum: (-128, 127),\n        _test_equal: (-150, 150),\n        _test_greater: (-150, 150),\n    }\n\n    return qnn_out_range[qnn_op]\n\n\ndef test_all_elemwise():\n    \"\"\"All_elewise\"\"\"\n    _test_forward_elemwise(_test_add)\n    _test_forward_elemwise_quantized(_test_add)\n    _test_forward_elemwise(partial(_test_add, fused_activation_function=\"RELU\"))\n    # this is broken with tf upgrade 1.15.2 and hits a segfault that needs\n    # further investigation.\n    # _test_forward_elemwise(partial(_test_add, fused_activation_function=\"RELU6\"))\n    _test_forward_elemwise(_test_sub)\n    _test_forward_elemwise_quantized(_test_sub)\n    _test_forward_elemwise(partial(_test_sub, fused_activation_function=\"RELU\"))\n    _test_forward_elemwise(partial(_test_sub, fused_activation_function=\"RELU6\"))\n    _test_forward_elemwise(_test_mul)\n    _test_forward_elemwise_quantized(_test_mul)\n    _test_forward_elemwise(partial(_test_mul, fused_activation_function=\"RELU\"))\n    _test_forward_elemwise(partial(_test_mul, fused_activation_function=\"RELU6\"))\n    _test_forward_elemwise(_test_div)\n    _test_forward_elemwise(partial(_test_div, fused_activation_function=\"RELU\"))\n    _test_forward_elemwise(partial(_test_div, fused_activation_function=\"RELU6\"))\n    _test_forward_elemwise(_test_pow)\n    _test_forward_elemwise(_test_maximum)\n    _test_forward_elemwise_quantized(_test_maximum)\n    _test_forward_elemwise(_test_minimum)\n    _test_forward_elemwise_quantized(_test_minimum)\n    _test_forward_elemwise(_test_greater)\n    _test_forward_elemwise_quantized(_test_greater)\n    _test_forward_elemwise(_test_squared_difference)\n    _test_forward_elemwise(_test_greater_equal)\n    _test_forward_elemwise(_test_less)\n    _test_forward_elemwise(_test_less_equal)\n    _test_forward_elemwise(_test_equal)\n    _test_forward_elemwise_quantized(_test_equal)\n    _test_forward_elemwise(_test_not_equal)\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_forward_elemwise(_test_floor_divide)\n        _test_forward_elemwise(_test_floor_mod)\n\n\n#######################################################################\n# AddN\n# ----\n\n\ndef _test_forward_add_n(inputs):\n    tf.reset_default_graph()\n    with tf.Graph().as_default():\n        temp = []\n        for each in inputs:\n            temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))\n        output = tf.add_n(temp)\n        compare_tflite_with_tvm(\n            list(inputs),\n            [each.name for each in temp],\n            list(temp),\n            [output],\n        )\n\n\ndef test_forward_add_n():\n    \"\"\"Add n\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        x = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n        y = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n        z_1 = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)\n        x_1, x_2, z_2 = x.astype(np.float32), y.astype(np.float32), z_1.astype(np.float32)\n        in0 = x\n        in1 = [x, y]\n        in2 = (x, y, z_1)\n        in3 = x_1\n        in4 = [x_1, x_2]\n        in5 = (x_1, x_2, z_2)\n        _test_forward_add_n(in0)\n        _test_forward_add_n(in1)\n        _test_forward_add_n(in2)\n        _test_forward_add_n(in3)\n        _test_forward_add_n(in4)\n        _test_forward_add_n(in5)\n\n\n#######################################################################\n# Logical operators\n# -----------------\n\n\ndef _test_logical_binary(logical_bin_op, data):\n\n    with tf.Graph().as_default():\n        in_data = [\n            array_ops.placeholder(shape=data[0].shape, dtype=\"bool\", name=\"in_0\"),\n            array_ops.placeholder(shape=data[1].shape, dtype=\"bool\", name=\"in_1\"),\n        ]\n        if logical_bin_op is math_ops.logical_not:\n            out = math_ops.logical_or(in_data[0], in_data[1], name=\"out1\")\n            out = logical_bin_op(out, name=\"out\")\n        else:\n            out = logical_bin_op(in_data[0], in_data[1], name=\"out\")\n\n        compare_tflite_with_tvm(data, [\"in_0:0\", \"in_1:0\"], in_data, [out])\n\n\ndef _test_forward_logical_and(data):\n    \"\"\"One iteration of logical and\"\"\"\n    return _test_logical_binary(math_ops.logical_and, data)\n\n\ndef _test_forward_logical_or(data):\n    \"\"\"One iteration of logical or\"\"\"\n    return _test_logical_binary(math_ops.logical_or, data)\n\n\ndef _test_forward_logical_not(data):\n    \"\"\"One iteration of logical not\"\"\"\n    return _test_logical_binary(math_ops.logical_not, data)\n\n\ndef test_all_logical():\n    data = [\n        np.random.choice(a=[False, True], size=(2, 3, 4)).astype(\"bool\"),\n        np.random.choice(a=[False, True], size=(2, 3, 4)).astype(\"bool\"),\n    ]\n    # boolean dtype is not supported by older versions than TFLite 1.15.0\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n        _test_forward_logical_and(data)\n        _test_forward_logical_or(data)\n        _test_forward_logical_not(data)\n\n\n#######################################################################\n# Zeros like\n# ----------\n\n\ndef _test_zeros_like(data):\n    \"\"\"One iteration of ZEROS LIKE\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = gen_array_ops.zeros_like(in_data)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_zeros_like():\n    \"\"\"ZEROS LIKE\"\"\"\n    _test_zeros_like(np.arange(6.0, dtype=np.float32).reshape((1, 6)))\n\n\n#######################################################################\n# Fill\n# ----\n\n\ndef _test_fill(dims, value_data, value_dtype):\n    \"\"\"Use the fill op to create a tensor of value_data with constant dims.\"\"\"\n\n    value_data = np.array(value_data, dtype=value_dtype)\n    # TF 1.13 TFLite convert method does not accept empty shapes\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        with tf.Graph().as_default():\n            value = array_ops.placeholder(dtype=value_dtype, name=\"value\", shape=[])\n            out = tf.fill(dims, value)\n            compare_tflite_with_tvm([value_data], [\"value\"], [value], [out])\n\n    with tf.Graph().as_default():\n        input1 = array_ops.placeholder(dtype=value_dtype, name=\"input1\", shape=dims)\n        # Fill op gets converted to static tensor during conversion\n        out = tf.fill(dims, value_data)\n        out1 = tf.add(out, input1)\n        input1_data = np.random.uniform(0, 5, size=dims).astype(value_dtype)\n        compare_tflite_with_tvm([input1_data], [\"input1\"], [input1], [out1])\n\n\ndef test_forward_fill():\n    \"\"\"Test FILL op\"\"\"\n\n    _test_fill((1, 2, 2, 4), 5, \"int32\")\n    _test_fill((1, 2, 2, 4), 5, \"float32\")\n    _test_fill((5,), 5, \"int32\")\n\n\n#######################################################################\n# Reduce\n# ------\n\n\ndef _test_reduce(math_op, data, keep_dims=None):\n    \"\"\"One iteration of reduce\"\"\"\n\n    assert len(data) == 2\n\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name=\"in\")\n        out = math_op(in_data, data[1], keep_dims)\n        compare_tflite_with_tvm([data[0]], [\"in:0\"], [in_data], [out])\n\n\ndef _test_reduce_quantize(math_op, data, keep_dims=None):\n    \"\"\"One iteration of reduce\"\"\"\n\n    assert len(data) == 2\n\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        in_data = [array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in\")]\n        inq_data = [\n            tf.quantization.fake_quant_with_min_max_args(\n                in_data[0], min=-100, max=100, name=\"inq_0\"\n            )\n        ]\n        input_range = {\"inq_0\": (-100, 100)}\n        out = math_op(inq_data, data[1], keep_dims)\n        out = tf.quantization.fake_quant_with_min_max_args(out, min=-200, max=200, name=\"out\")\n        compare_tflite_with_tvm(\n            [data[0]], [\"inq_0:0\"], [inq_data[0]], [out], quantized=True, input_range=input_range\n        )\n\n\n#######################################################################\n# Reduce_min\n# ----------\n\n\ndef _test_reduce_min(data, keep_dims=None):\n    \"\"\"One iteration of reduce_min\"\"\"\n    return _test_reduce(math_ops.reduce_min, data, keep_dims)\n\n\n#######################################################################\n# Reduce_max\n# ----------\n\n\ndef _test_reduce_max(data, keep_dims=None):\n    \"\"\"One iteration of reduce_max\"\"\"\n    return _test_reduce(math_ops.reduce_max, data, keep_dims)\n\n\n#######################################################################\n# Reduce_mean\n# -----------\n\n\ndef _test_reduce_mean(data, keep_dims=None, quantized=False):\n    \"\"\"One iteration of reduce_mean\"\"\"\n    if quantized:\n        return _test_reduce_quantize(math_ops.reduce_mean, data, keep_dims)\n    else:\n        return _test_reduce(math_ops.reduce_mean, data, keep_dims)\n\n\n#######################################################################\n# Reduce_prod\n# -----------\n\n\ndef _test_reduce_prod(data, keep_dims=None):\n    \"\"\"One iteration of reduce_prod\"\"\"\n    return _test_reduce(math_ops.reduce_prod, data, keep_dims)\n\n\n#######################################################################\n# Reduce_sum\n# -----------\n\n\ndef _test_reduce_sum(data, keep_dims=None):\n    \"\"\"One iteration of reduce_sum\"\"\"\n    return _test_reduce(math_ops.reduce_sum, data, keep_dims)\n\n\n#######################################################################\n# Reduce_any\n# ----------\n\n\ndef _test_reduce_any(data, keep_dims=None):\n    \"\"\"One iteration of reduce_any\"\"\"\n    return _test_reduce(math_ops.reduce_any, data, keep_dims)\n\n\ndef _test_forward_reduce(testop, dtype=\"float32\"):\n    \"\"\"Reduce\"\"\"\n    if dtype == \"bool\":\n        data0 = [np.random.choice(a=[False, True], size=(16, 16, 16, 16)).astype(dtype), None]\n        data1 = [\n            np.random.choice(a=[False, True], size=(16, 16, 16, 16)).astype(dtype),\n            np.array(1, dtype=np.int32),\n        ]\n        data2 = [\n            np.random.choice(a=[False, True], size=(16, 16, 16, 16)).astype(dtype),\n            np.array([1, 2], dtype=np.int32),\n        ]\n    else:\n        data0 = [np.random.rand(16, 16, 16, 16).astype(dtype), None]\n        data1 = [np.random.rand(16, 16, 16, 16).astype(dtype), np.array(1, dtype=np.int32)]\n        data2 = [np.random.rand(16, 16, 16, 16).astype(dtype), np.array([1, 2], dtype=np.int32)]\n\n    for data in [data0, data1, data2]:\n        testop(data)\n        testop(data, keep_dims=False)\n        testop(data, keep_dims=True)\n\n\ndef _test_forward_reduce_quantized(testop):\n    data0 = [\n        np.array(np.random.uniform(0, 255, (3, 6)), dtype=np.uint8),\n        np.array([1, 2], dtype=np.int32),\n    ]\n    testop(data0, quantized=True)\n    testop(data0, keep_dims=False, quantized=True)\n    testop(data0, keep_dims=True, quantized=True)\n\n\ndef test_all_reduce():\n    _test_forward_reduce(_test_reduce_min)\n    _test_forward_reduce(_test_reduce_max)\n    _test_forward_reduce(_test_reduce_mean)\n    _test_forward_reduce_quantized(_test_reduce_mean)\n    _test_forward_reduce(_test_reduce_prod)\n    _test_forward_reduce(_test_reduce_sum)\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n        _test_forward_reduce(_test_reduce_any, dtype=\"bool\")\n\n\n#######################################################################\n# Arg_min_max\n# -----------\n\n\ndef _test_arg_min_max(math_op, data, axis, quantized=False):\n    \"\"\"One iteration of arg_min_max\"\"\"\n\n    with tf.Graph().as_default():\n        t_name = \"in\"\n        in_data = array_ops.placeholder(shape=data.shape, dtype=np.float32, name=t_name)\n        input_range = None\n        qmin, qmax = -100, 102\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=qmin, max=qmax, name=\"q\" + t_name\n            )\n            input_range = {inq_data.name.split(\":\")[0]: (qmin, qmax)}\n            out = math_op(input=inq_data, axis=axis)\n            compare_tflite_with_tvm(\n                [data], [inq_data.name], [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = math_op(input=in_data, axis=axis)\n            compare_tflite_with_tvm([data], [in_data.name], [in_data], [out])\n\n\ndef test_forward_arg_min_max():\n    \"\"\"Arg min max\"\"\"\n    # test quantized\n    for data in [np.array(np.random.uniform(-100, 100, (3, 4)), dtype=np.uint8)]:\n        # There is no quantized version of ArgMin\n        for axis in [None, 0, 1, -1]:\n            _test_arg_min_max(math_ops.argmax, data, axis, True)\n\n    for data in [np.array(np.random.uniform(-100, 100, (3, 4)), dtype=np.float32)]:\n        for axis in [None, 0, 1, -1]:\n            _test_arg_min_max(math_ops.argmax, data, axis)\n            _test_arg_min_max(math_ops.argmin, data, axis)\n\n\n#######################################################################\n# Select, Where\n# -------------\n\n\ndef test_forward_select():\n    \"\"\"Select\"\"\"\n    with tf.Graph().as_default():\n        with tf.Session() as _:\n            input1 = tf.placeholder(tf.int32, shape=[1, 4, 4, 3], name=\"input1\")\n            input2 = tf.placeholder(tf.int32, shape=[1, 4, 4, 3], name=\"input2\")\n            mask = input1 > input2\n            out = tf.where(mask, input1 + 1, input2 * 2)\n            in_data1 = np.random.uniform(0, 10, size=(1, 4, 4, 3)).astype(\"int32\")\n            in_data2 = np.random.uniform(0, 10, size=(1, 4, 4, 3)).astype(\"int32\")\n\n            compare_tflite_with_tvm(\n                [in_data1, in_data2], [\"input1:0\", \"input2:0\"], [input1, input2], [out]\n            )\n\n\n@pytest.mark.parametrize(\"quant_bits\", [2, 4, 8, 16])\n@pytest.mark.parametrize(\n    \"value, min_value, max_value\",\n    [[-10.11, -6, 6], [-3.55, -6, 6], [0, -6, 6], [3.55, -6, 6], [10.11, -6, 6]],\n)\ndef test_forward_fake_quant(value, min_value, max_value, quant_bits):\n    \"\"\"Fake quant\"\"\"\n    with tf.Graph().as_default():\n        with tf.Session() as _:\n            input_placeholder = tf.placeholder(tf.float32, shape=[1], name=\"input\")\n            out = tf.quantization.fake_quant_with_min_max_args(\n                input_placeholder, min=min_value, max=max_value, num_bits=quant_bits, name=None\n            )\n\n            in_data = np.float32(value)\n            compare_tflite_with_tvm([in_data], [\"input:0\"], [input_placeholder], [out])\n\n\n# Squeeze\n# -------\n\n\ndef _test_squeeze(data, squeeze_dims=None):\n    \"\"\"One iteration of squeeze\"\"\"\n\n    if squeeze_dims is None:\n        squeeze_dims = []\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n\n        if squeeze_dims:\n            out = array_ops.squeeze(in_data, squeeze_dims)\n        else:\n            out = array_ops.squeeze(in_data)\n\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_squeeze():\n    \"\"\"Squeeze\"\"\"\n    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3)), [0, 2])\n    _test_squeeze(np.arange(6).reshape((2, 1, 3, 1)), [1, 3])\n\n\n#######################################################################\n# Quantize/DeQuantize\n# -------------------\n\n\ndef _test_quantize_dequantize(data):\n    \"\"\"One iteration of quantize and dequantize\"\"\"\n\n    # Keras model to force TFLite converter to insert 2 TFLite quantize ops.\n    # First TFLite quantize op converts float32 tensor to int8 tensor - Qnn quantize.\n    # Second TFLite quantize op converts int8 tensor to int8 tensor - Qnn requantize.\n    data_in = tf.keras.layers.Input(shape=data.shape[1:])\n    relu = tf.keras.layers.ReLU()(data_in)\n    add = tf.keras.layers.Add()([data_in, relu])\n    concat = tf.keras.layers.Concatenate(axis=0)([relu, add])\n    keras_model = tf.keras.models.Model(inputs=data_in, outputs=concat)\n\n    # To create quantized values with dynamic range of activations, needs representative dataset\n    def representative_data_gen():\n        for _ in range(1):\n            yield [data]\n\n    tflite_model_quant = _quantize_keras_model(keras_model, representative_data_gen, True, True)\n\n    tflite_output = run_tflite_graph(tflite_model_quant, data)\n    if tf.__version__ < LooseVersion(\"2.9\"):\n        in_node = data_in.name.split(\":\")[0]\n    else:\n        in_node = \"serving_default_\" + data_in.name + \":0\"\n    tvm_output = run_tvm_graph(tflite_model_quant, data, in_node)\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-2\n    )\n\n\ndef _test_quantize_dequantize_const(data):\n    \"\"\"One iteration of quantize and dequantize\"\"\"\n\n    # Keras model to force TFLite converter to insert 2 TFLite quantize ops.\n    # First TFLite quantize op converts float32 tensor to int8 tensor - Qnn quantize.\n    # Second TFLite quantize op converts int8 tensor to int8 tensor - Qnn requantize.\n    data_in = tf.keras.layers.Input(shape=data.shape[1:])\n    relu = tf.keras.layers.ReLU()(data_in)\n    add = tf.keras.layers.Add()([data, relu])\n    concat = tf.keras.layers.Concatenate(axis=0)([relu, add])\n    keras_model = tf.keras.models.Model(inputs=data_in, outputs=concat)\n\n    # To create quantized values with dynamic range of activations, needs representative dataset\n    def representative_data_gen():\n        for _ in range(1):\n            yield [data]\n\n    tflite_model_quant = _quantize_keras_model(keras_model, representative_data_gen, True, True)\n\n    tflite_output = run_tflite_graph(tflite_model_quant, data)\n    if tf.__version__ < LooseVersion(\"2.9\"):\n        in_node = data_in.name.split(\":\")[0]\n    else:\n        in_node = \"serving_default_\" + data_in.name + \":0\"\n    tvm_output = run_tvm_graph(tflite_model_quant, data, in_node)\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-2\n    )\n\n\ndef test_forward_quantize_dequantize():\n    \"\"\"Quantize Dequantize\"\"\"\n    data = np.random.uniform(0, 1, (1, 4, 4, 3)).astype(\"float32\")\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.1.0\"):\n        _test_quantize_dequantize(data)\n        _test_quantize_dequantize_const(data)\n\n\n#######################################################################\n# Pad\n# ---\n\n\ndef _test_pad(data, mode=\"CONSTANT\", quantized=False):\n    \"\"\"One iteration of PAD\"\"\"\n\n    assert len(data) == 2\n\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        in_data = [array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in\")]\n\n        if quantized:\n            # fake_quant will keep the tensors in float32 until the conversion in the session\n            input_range = {\"inq_0\": (-100, 100)}\n            inq_data = [\n                tf.quantization.fake_quant_with_min_max_args(\n                    in_data[0], min=-100, max=100, name=\"inq_0\"\n                )\n            ]\n            out = array_ops.pad(\n                inq_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype), mode=mode\n            )\n            compare_tflite_with_tvm(\n                [data[0]], [\"inq_0:0\"], inq_data, [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = array_ops.pad(\n                in_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype), mode=mode\n            )\n            compare_tflite_with_tvm([data[0]], [\"in:0\"], in_data, [out])\n\n\ndef test_forward_pad():\n    \"\"\"Pad\"\"\"\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)),\n            np.array([[2, 2], [1, 1], [1, 1]], dtype=np.int32),\n        ]\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        mode=\"REFLECT\",\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        mode=\"SYMMETRIC\",\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int64),\n        ],\n        mode=\"REFLECT\",\n    )\n    _test_pad(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int64),\n        ],\n        mode=\"SYMMETRIC\",\n    )\n    _test_pad(\n        [\n            np.arange(0, 256, dtype=np.uint8).reshape((1, 256)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        quantized=True,\n    )\n\n\n#######################################################################\n# PADV2\n# -----\n\n\ndef _test_padv2(data, mode=\"CONSTANT\", quantized=False):\n    \"\"\"One iteration of PADV2\"\"\"\n\n    assert len(data) == 2 or len(data) == 3\n\n    with_constant_values = len(data) == 3\n\n    # Test with tensor and constant\n    with tf.Graph().as_default():\n        in_data = [array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in\")]\n\n        if quantized:\n            # fake_quant will keep the tensors in float32 until the conversion in the session\n            input_range = {\"inq_0\": (-100, 100)}\n            inq_data = [\n                tf.quantization.fake_quant_with_min_max_args(\n                    in_data[0], min=-100, max=100, name=\"inq_0\"\n                )\n            ]\n            if with_constant_values:\n                in_constant_values = constant_op.constant(\n                    data[2], shape=data[2].shape, dtype=\"float32\", name=\"in_constant_values\"\n                )\n                inq_constant_values = tf.quantization.fake_quant_with_min_max_args(\n                    in_constant_values, min=-100, max=100, name=\"inq_constant_values\"\n                )\n                out = array_ops.pad_v2(\n                    inq_data[0],\n                    ops.convert_to_tensor(data[1], dtype=data[1].dtype),\n                    constant_values=inq_constant_values,\n                    mode=mode,\n                )\n                out = tf.quantization.fake_quant_with_min_max_args(\n                    out, min=-100, max=100, name=\"out\"\n                )\n            else:\n                out = array_ops.pad_v2(\n                    inq_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype), mode=mode\n                )\n            compare_tflite_with_tvm(\n                [data[0]], [\"inq_0:0\"], inq_data, [out], quantized=True, input_range=input_range\n            )\n        else:\n            if with_constant_values:\n                out = array_ops.pad_v2(\n                    in_data[0],\n                    ops.convert_to_tensor(data[1], dtype=data[1].dtype),\n                    constant_values=ops.convert_to_tensor(data[2], dtype=data[2].dtype),\n                    mode=mode,\n                )\n            else:\n                out = array_ops.pad_v2(\n                    in_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype), mode=mode\n                )\n            compare_tflite_with_tvm([data[0]], [\"in:0\"], in_data, [out])\n\n\ndef test_forward_padv2():\n    \"\"\"PADV2\"\"\"\n    # Tests without Constant_values\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)),\n            np.array([[2, 2], [1, 1], [1, 1]], dtype=np.int32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        mode=\"REFLECT\",\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        mode=\"SYMMETRIC\",\n    )\n    _test_padv2(\n        [\n            np.arange(0, 256, dtype=np.uint8).reshape((1, 256)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n        ],\n        quantized=True,\n    )\n\n    # Tests with Constant_values\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32),\n            np.array([2], dtype=np.float32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)),\n            np.array([[2, 2], [1, 1], [1, 1]], dtype=np.int32),\n            np.array([1], dtype=np.float32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n            np.array([-1], dtype=np.float32),\n        ]\n    )\n    _test_padv2(\n        [\n            np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3)),\n            np.array([[1, 1], [2, 2]], dtype=np.int32),\n            np.array([2], dtype=np.float32),\n        ]\n    )\n    # NOTE: In versions > 2.1.0, there is a bug in Tensorflow package for this scenario.\n    #       Hence, it is disabled temporarily for TF version > 2.1.0 .\n    if package_version.parse(tf.VERSION) <= package_version.parse(\"2.1.0\"):\n        _test_padv2(\n            [\n                np.arange(0, 256, dtype=np.uint8).reshape((1, 256)),\n                np.array([[1, 1], [2, 2]], dtype=np.int32),\n                np.array([2], dtype=np.float32),\n            ],\n            quantized=True,\n        )\n\n    # Constant Values input can be scalar\n    _test_padv2(\n        [\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32),\n            np.float32(2),\n        ]\n    )\n    # NOTE: In versions > 2.1.0, there is a bug in Tensorflow package for this scenario.\n    #       Hence, it is disabled temporarily for TF versions > 2.1.0.\n    if package_version.parse(tf.VERSION) <= package_version.parse(\"2.1.0\"):\n        _test_padv2(\n            [\n                np.arange(0, 256, dtype=np.uint8).reshape((1, 256)),\n                np.array([[1, 1], [2, 2]], dtype=np.int32),\n                np.uint8(10),\n            ],\n            quantized=True,\n        )\n\n\n#######################################################################\n# EXPAND_DIMS\n# -----------\n\n\ndef _test_expand_dims(input_shape, input_type, axis, quantized=False):\n    \"\"\"One iteration of EXPAND_DIMS\"\"\"\n    with tf.Graph().as_default():\n        axis = ops.convert_to_tensor(axis, dtype=axis.dtype)\n\n        if quantized:\n            # ignoring input_type as quantized requires uint8\n            input_array = np.random.uniform(0, 256, input_shape).astype(\"uint8\")\n            in_input = tf.placeholder(dtype=\"float32\", shape=input_array.shape, name=\"input\")\n\n            input_range = {\"q_input\": (-100, 100)}\n            inq_input = tf.quantization.fake_quant_with_min_max_args(\n                in_input, min=-100, max=100, name=\"q_input\"\n            )\n\n            out = array_ops.expand_dims(inq_input, axis=axis)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-100, max=100, name=\"out\")\n\n            compare_tflite_with_tvm(\n                [input_array],\n                [\"q_input\"],\n                [inq_input],\n                [out],\n                quantized=True,\n                input_range=input_range,\n            )\n        else:\n            input_array = np.random.uniform(-100, 100, input_shape).astype(input_type)\n            in_input = tf.placeholder(\n                dtype=input_array.dtype, shape=input_array.shape, name=\"input\"\n            )\n\n            out = array_ops.expand_dims(in_input, axis=axis)\n\n            compare_tflite_with_tvm([input_array], [\"input\"], [in_input], [out])\n\n\ndef test_forward_expand_dims():\n    \"\"\"EXPAND_DIMS\"\"\"\n    for quantized in [False, True]:\n        _test_expand_dims((6, 2, 7, 5), \"float32\", np.int32(0), quantized=quantized)\n        _test_expand_dims((1, 2, 3), \"int32\", np.int32(-2), quantized=quantized)\n        _test_expand_dims((2, 4, 5), \"float32\", np.array([1], dtype=np.int32), quantized=quantized)\n\n\n#######################################################################\n# ONE_HOT\n# -------\n\n\ndef _test_one_hot(indices, depth, on_value, off_value, axis=None):\n    \"\"\"One iteration of One_Hot\"\"\"\n    with tf.Graph().as_default():\n        in_indices = tf.placeholder(dtype=indices.dtype, shape=indices.shape, name=\"indices\")\n        in_depth = ops.convert_to_tensor(depth, dtype=depth.dtype)\n        in_on_value = tf.placeholder(dtype=on_value.dtype, shape=on_value.shape, name=\"on_value\")\n        in_off_value = tf.placeholder(\n            dtype=off_value.dtype, shape=off_value.shape, name=\"off_value\"\n        )\n        if axis is not None:\n            out = array_ops.one_hot(in_indices, in_depth, in_on_value, in_off_value, axis=axis)\n        else:\n            out = array_ops.one_hot(in_indices, in_depth, in_on_value, in_off_value)\n        compare_tflite_with_tvm(\n            [indices, on_value, off_value],\n            [\"indices\", \"on_value\", \"off_value\"],\n            [in_indices, in_on_value, in_off_value],\n            [out],\n        )\n\n\ndef test_forward_one_hot():\n    \"\"\"One_Hot\"\"\"\n    _test_one_hot(np.int32(2), np.int32(8), np.int32(1), np.int32(0))\n    _test_one_hot(np.int32(4), np.int32(8), np.float32(1), np.float32(0))\n    _test_one_hot(np.array([1, 2, 3], dtype=np.int32), np.int32(8), np.int32(3), np.int32(-1))\n    _test_one_hot(\n        np.array([1, 2, 3], dtype=np.int32), np.int32(8), np.int32(3), np.int32(-1), axis=0\n    )\n\n\n#######################################################################\n# Pack\n# ----\n\n\ndef _test_pack(data, is_var, axis, quantized=False):\n    \"\"\"One iteration of pack\"\"\"\n\n    assert len(data) >= 1\n    assert len(data) == len(is_var)\n    if quantized:\n        with tf.Graph().as_default():\n            in_data = [\n                array_ops.placeholder(shape=d.shape, dtype=\"float32\", name=\"in_\" + str(idx))\n                if is_var[idx]\n                else constant_op.constant(\n                    d, shape=d.shape, dtype=\"float32\", name=\"in_constant_\" + str(idx)\n                )\n                for idx, d in enumerate(data)\n            ]\n            inq_data = [\n                tf.quantization.fake_quant_with_min_max_args(\n                    i_data, min=-100, max=100, name=f\"inq_{idx}\"\n                )\n                for idx, i_data in enumerate(in_data)\n            ]\n            input_range = {}\n            for i in range(len(data)):\n                input_range[f\"inq_{i}\"] = (-100, 100)\n\n            out = array_ops.pack(inq_data, axis=axis)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-100, max=100, name=\"out\")\n            name = [f\"inq_{idx}:0\" for idx in range(len(data))]\n            compare_tflite_with_tvm(\n                data, name, inq_data, [out], quantized=True, input_range=input_range\n            )\n    else:\n        with tf.Graph().as_default():\n            in_data = [\n                array_ops.placeholder(shape=d.shape, dtype=d.dtype, name=\"in_\" + str(idx))\n                if is_var[idx]\n                else constant_op.constant(\n                    d, shape=d.shape, dtype=d.dtype, name=\"in_constant_\" + str(idx)\n                )\n                for idx, d in enumerate(data)\n            ]\n\n            out = array_ops.pack(in_data, axis=axis)\n            name = [_.name for _ in in_data]\n            compare_tflite_with_tvm(data, name, in_data, [out], experimental_new_converter=True)\n\n\ndef test_forward_pack():\n    \"\"\"Pack\"\"\"\n    _test_pack([np.int32(1), np.int32(5)], [False, False], 0)\n    _test_pack([np.array([1, 4]), np.array([2, 5]), np.array([3, 6])], [True, False, False], 0)\n    _test_pack(\n        [np.arange(6).reshape((1, 2, 1, 3)), np.arange(6).reshape((1, 2, 1, 3))], [True, True], 1\n    )\n\n    _test_pack([np.arange(6).reshape((3, 2)), np.arange(6).reshape((3, 2))], [True, True], 1)\n\n    _test_pack(\n        [\n            np.arange(6).reshape((2, 1, 1, 3)),\n            np.arange(6).reshape((2, 1, 1, 3)),\n            np.arange(6).reshape((2, 1, 1, 3)),\n        ],\n        [True, True, True],\n        1,\n    )\n\n    _test_pack(\n        [\n            np.arange(6, dtype=np.uint8).reshape((2, 1, 1, 3)),\n            np.arange(6, dtype=np.uint8).reshape((2, 1, 1, 3)),\n            np.arange(6, dtype=np.uint8).reshape((2, 1, 1, 3)),\n        ],\n        [True, True, True],\n        1,\n        quantized=True,\n    )\n\n\n#######################################################################\n# Unpack\n# ------\n\n\ndef _test_unpack(data, axis, num_unpacks):\n    \"\"\"One iteration of UNPACK\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = gen_array_ops.unpack(in_data, num=num_unpacks, axis=axis, name=\"unpack\")\n        out_names = [\"out_\" + str(n) + \":0\" for n in range(num_unpacks)]\n        compare_tflite_with_tvm([data], \"Placeholder:0\", [in_data], out, out_names=out_names)\n\n\ndef test_forward_unpack():\n    \"\"\"UNPACK\"\"\"\n    _test_unpack(np.array(np.random.uniform(0, 5, (3, 1)), dtype=np.int32), axis=1, num_unpacks=1)\n    _test_unpack(np.array(np.random.uniform(0, 5, (3, 4)), dtype=np.float32), axis=0, num_unpacks=3)\n    _test_unpack(\n        np.array(np.random.uniform(0, 5, (3, 1, 2)), dtype=np.float32), axis=0, num_unpacks=3\n    )\n    # tflite 1.13 doesn't accept negative axis\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_unpack(\n            np.array(np.random.uniform(0, 5, (3, 6)), dtype=np.int32), axis=-2, num_unpacks=3\n        )\n        _test_unpack(\n            np.array(np.random.uniform(0, 5, (2, 3, 4)), dtype=np.int32), axis=-3, num_unpacks=2\n        )\n\n\n#######################################################################\n# Local response normalization\n# ----------------------------\n\n\ndef _test_local_response_normalization(data, depth_radius, bias, alpha, beta):\n    \"\"\"One iteration of LOCAL_RESPONSE_NORMALIZATION\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n        out = nn_ops.local_response_normalization(\n            in_data, depth_radius=depth_radius, bias=bias, alpha=alpha, beta=beta\n        )\n        compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_local_response_normalization():\n    \"\"\"LOCAL_RESPONSE_NORMALIZATION\"\"\"\n    data = np.random.uniform(size=(1, 6, 4, 3)).astype(\"float32\")\n    # LOCAL_RESPONSE_NORMALIZATION come with TFLite >= 1.14.0 fbs schema\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_local_response_normalization(data, depth_radius=5, bias=1, alpha=1, beta=0.5)\n\n\n#######################################################################\n# L2 normalization\n# ----------------\n\n\ndef _test_l2_normalization(data, axis, fused_activation_function=None):\n    \"\"\"One iteration of L2_NORMALIZATION\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = nn_impl.l2_normalize(in_data, axis)\n        out = with_fused_activation_function(out, fused_activation_function)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_l2_normalization():\n    \"\"\"L2_NORMALIZATION\"\"\"\n    data = np.random.uniform(size=(3, 6, 4)).astype(\"float32\")\n    _test_l2_normalization(data, axis=2)\n    _test_l2_normalization(data, axis=2, fused_activation_function=\"RELU\")\n\n\n#######################################################################\n# Logistic\n# --------\n\n\ndef _test_logistic(data, quantized=False):\n    \"\"\"One iteration of LOGISTIC\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-5, max=5, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-5, 5)}\n            out = math_ops.sigmoid(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=0, max=1, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = math_ops.sigmoid(in_data)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_logistic():\n    \"\"\"LOGISTIC\"\"\"\n    _test_logistic(np.arange(6.0, dtype=np.float32).reshape((1, 6)))\n    _test_logistic(np.random.uniform(0, 255, (3, 6)).astype(np.uint8), quantized=True)\n\n\n#######################################################################\n# Softmax\n# -------\n\n\ndef _test_softmax(data):\n    \"\"\"One iteration of softmax\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = nn_ops.softmax(in_data)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_softmax():\n    \"\"\"Softmax\"\"\"\n    _test_softmax(np.arange(6.0, dtype=np.float32).reshape((1, 6)))\n    _test_softmax(np.arange(6.0, dtype=np.float32).reshape((1, 2, 3)))\n\n\n######################################################################\n# Log_softmax\n# -----------\n\n\ndef _test_log_softmax(data, quantized=False):\n    \"\"\"One iteration of log_softmax\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-10, max=10, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-10, 10)}\n            # tflite log_softmax supports only the case when axis is not specified\n            out = nn_ops.log_softmax(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-20, max=0, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = nn_ops.log_softmax(in_data)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_log_softmax():\n    \"\"\"Log_softmax\"\"\"\n    _test_log_softmax(np.random.uniform(-10, 10, size=(3, 6)).astype(np.float32))\n    _test_log_softmax(np.random.uniform(0, 255, (3, 6)).astype(np.uint8), quantized=True)\n\n\n#######################################################################\n# Tanh\n# ----\n\n\ndef _test_tanh(data, quantized=False):\n    \"\"\"One iteration of TANH\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-3, max=3, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-3, 3)}\n            out = math_ops.tanh(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-1, max=1, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = math_ops.tanh(in_data)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_tanh():\n    \"\"\"TANH\"\"\"\n    _test_tanh(np.arange(6.0, dtype=np.float32).reshape((1, 6)), quantized=False)\n    _test_tanh(np.arange(0, 256, 30, dtype=np.uint8), quantized=True)\n\n\n#######################################################################\n# ReLu\n# ----\n\n\ndef _test_relu(data, quantized=False):\n    \"\"\"One iteration of ReLU\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-10, max=10, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-10, 10)}\n            out = nn_ops.relu(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=0, max=6, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = nn_ops.relu(in_data)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_relu():\n    \"\"\"ReLU\"\"\"\n    _test_relu(np.arange(6.0, dtype=np.float32).reshape((1, 6)))\n    _test_relu(np.random.uniform(0, 255, (3, 6)).astype(np.uint8), quantized=True)\n\n\n#######################################################################\n# ReLU6\n# -----\n\n\ndef _test_relu6(data, quantized=False):\n    \"\"\"One iteration of ReLU6\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-10, max=10, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-10, 10)}\n            out = nn_ops.relu6(inq_data)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=0, max=6, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = nn_ops.relu6(in_data)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_relu6():\n    \"\"\"ReLU6\"\"\"\n    _test_relu6(np.random.uniform(-10, 10, size=(3, 6)).astype(np.float32))\n    _test_relu6(np.random.uniform(0, 255, (3, 6)).astype(np.uint8), quantized=True)\n\n\n#######################################################################\n# Leaky_ReLU\n# ----------\n\n\ndef _test_leaky_relu(data, alpha, quantized=False):\n    \"\"\"One iteration of Leaky_ReLU\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-3, max=2, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-3, 2)}\n            out = nn_ops.leaky_relu(inq_data, alpha)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-3, max=2, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = nn_ops.leaky_relu(in_data, alpha)\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_leaky_relu():\n    \"\"\"Leaky_ReLU\"\"\"\n    _test_leaky_relu(np.random.uniform(-5, 5, (1, 6)).astype(np.float32), alpha=0.2)\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_leaky_relu(\n            np.random.uniform(0, 255, (2, 3)).astype(np.uint8), alpha=0.3, quantized=True\n        )\n\n\n#######################################################################\n# ReLU_n1_to_1\n# ------------\n\n\ndef _test_relu_n1_to_1(data, quantized=False):\n    \"\"\"One iteration of ReLU_n1_to_1\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=\"float32\", name=\"in_0\")\n\n        if quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-3, max=3, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-3, 3)}\n            # There is no such tf operation.\n            # The specific pattern will be replaced into RELU_N1_TO_1 by tflite\n            out = math_ops.maximum(-1.0, math_ops.minimum(inq_data, 1.0))\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-1, max=1, name=\"out\")\n            compare_tflite_with_tvm(\n                data, \"inq_0:0\", [inq_data], [out], quantized=True, input_range=input_range\n            )\n        else:\n            out = math_ops.maximum(-1.0, math_ops.minimum(in_data, 1.0))\n            compare_tflite_with_tvm(data, \"in_0:0\", [in_data], [out])\n\n\ndef test_forward_relu_n1_to_1():\n    \"\"\"ReLU_n1_to_1\"\"\"\n    _test_relu_n1_to_1(np.random.uniform(-3, 3, (1, 6)).astype(np.float32))\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_relu_n1_to_1(np.random.uniform(0, 255, (3, 6)).astype(np.uint8), quantized=True)\n\n\n#######################################################################\n# PReLU\n# -----\n\n\ndef _test_prelu(data, alpha):\n    \"\"\"One iteration of PReLU\"\"\"\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        # This specific pattern will be replaced into PRelu by tflite\n        out = nn_ops.relu(in_data) + (-alpha * nn_ops.relu(-in_data))\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_prelu():\n    \"\"\"PReLU\"\"\"\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((3,), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((1, 3), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((1, 1, 3), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((1, 1, 1, 3), 0.2, dtype=\"float32\"),\n    )\n    #\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((32, 3), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((32, 32, 3), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 32, 3)).astype(\"float32\"),\n        np.full((1, 32, 1, 3), 0.2, dtype=\"float32\"),\n    )\n    #\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 1, 3)).astype(\"float32\"),\n        np.full((3,), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(1, 32, 3)).astype(\"float32\"),\n        np.full((32, 3), 0.2, dtype=\"float32\"),\n    )\n    _test_prelu(\n        np.random.uniform(-5, 5, size=(32, 3)).astype(\"float32\"), np.full((3), 0.2, dtype=\"float32\")\n    )\n\n\n#######################################################################\n# DepthToSpace\n# ------------\n\n\ndef _test_depthtospace(data, block_size):\n    \"\"\"One iteration of depth_to_space operation with given data and block size\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = array_ops.depth_to_space(in_data, block_size)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_depthtospace():\n    # DEPTH_TO_SPACE comes with TFLite >= 1.15.0 fbs schema\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.15.0\"):\n        _test_depthtospace(np.random.normal(size=[1, 32, 32, 4]).astype(\"float32\"), 2)\n        _test_depthtospace(np.random.normal(size=[1, 16, 8, 32]).astype(\"float32\"), 4)\n\n\n#######################################################################\n# SpaceToDepth\n# ------------\n\n\ndef _test_spacetodepth(data, block_size):\n    \"\"\"One iteration of space_to_depth operation with given data and block size\"\"\"\n\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)\n        out = array_ops.space_to_depth(in_data, block_size)\n        compare_tflite_with_tvm(data, \"Placeholder:0\", [in_data], [out])\n\n\ndef test_forward_spacetodepth():\n    _test_spacetodepth(np.random.normal(size=[1, 32, 32, 4]).astype(\"float32\"), 2)\n    _test_spacetodepth(np.random.normal(size=[1, 16, 8, 32]).astype(\"float32\"), 4)\n\n\n#######################################################################\n# ReverseSequence\n# ---------------\n\n\ndef _test_reverse_sequence(shape, dtype, seq_lengths, batch_axis, seq_axis):\n    \"\"\"One iteration of reverse_sequence operation with given data and attributes\"\"\"\n\n    data = np.random.uniform(0, 100, size=shape).astype(dtype)\n    with tf.Graph().as_default():\n        in_data = array_ops.placeholder(dtype=dtype, name=\"input\", shape=shape)\n        out = tf.reverse_sequence(\n            in_data, seq_lengths=seq_lengths, batch_axis=batch_axis, seq_axis=seq_axis\n        )\n\n        compare_tflite_with_tvm(data, \"input\", [in_data], [out])\n\n\ndef test_forward_reverse_sequence():\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        _test_reverse_sequence([4, 3], \"float32\", [3, 2, 1], 1, 0)\n        _test_reverse_sequence([4, 3], \"float32\", [3, 2, 1, 3], 0, 1)\n        _test_reverse_sequence([2, 3, 3, 3], \"float32\", [2, 3, 2], 2, 1)\n        _test_reverse_sequence([2, 4, 6, 4, 5], \"float32\", [5, 3], 0, 2)\n        _test_reverse_sequence([2, 4, 6, 4, 5], \"float32\", [5, 3, 1, 4], 3, 2)\n\n\n#######################################################################\n# Sparse To Dense\n# ---------------\ndef _test_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape):\n    # tflite 1.13 convert method does not accept empty shapes\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"1.14.0\"):\n        with tf.Graph().as_default():\n            indices = tf.placeholder(\n                shape=sparse_indices.shape, dtype=str(sparse_indices.dtype), name=\"indices\"\n            )\n            values = tf.placeholder(\n                shape=sparse_values.shape, dtype=str(sparse_values.dtype), name=\"values\"\n            )\n            oshape = tf.constant(\n                output_shape, shape=output_shape.shape, dtype=str(output_shape.dtype)\n            )\n\n            if default_value is None:\n                output = tf.sparse_to_dense(indices, oshape, values)\n                compare_tflite_with_tvm(\n                    [sparse_indices, sparse_values],\n                    [\"indices\", \"values\"],\n                    [indices, values],\n                    [output],\n                )\n            else:\n                dv_placeholder = tf.placeholder(\n                    shape=(), dtype=str(default_value.dtype), name=\"default_value\"\n                )\n                output = tf.sparse_to_dense(indices, oshape, values, dv_placeholder)\n                compare_tflite_with_tvm(\n                    [sparse_indices, sparse_values, default_value],\n                    [\"indices\", \"values\", \"default_value\"],\n                    [indices, values, dv_placeholder],\n                    [output],\n                )\n\n\ndef test_forward_sparse_to_dense():\n    \"\"\"\n    Works in tvm/topi/tensorflow. But tflite converter breaks this test case\n    _test_sparse_to_dense(\n        np.int32(1),\n        np.int32(3),\n        np.int32(0),\n        np.array([5]).astype(\"int32\")\n    )\n    \"\"\"\n    # vector\n    _test_sparse_to_dense(\n        np.array([0, 1, 4]).astype(\"int32\"),\n        np.array([3, 3, 3]).astype(\"int32\"),\n        np.int32(0),\n        np.array([5]).astype(\"int32\"),\n    )\n    # vector nXd\n    _test_sparse_to_dense(\n        np.array([[0, 0], [1, 2]]).astype(\"int32\"),\n        np.array([1, 2]).astype(\"int32\"),\n        np.int32(0),\n        np.array([3, 4]).astype(\"int32\"),\n    )\n    _test_sparse_to_dense(\n        np.array([[0, 0, 0], [1, 2, 3]]).astype(\"int32\"),\n        np.array([1, 2]).astype(\"int32\"),\n        np.int32(4),\n        np.array([2, 3, 4]).astype(\"int32\"),\n    )\n    # floats\n    _test_sparse_to_dense(\n        np.array([0, 1, 4]).astype(\"int32\"),\n        np.array([3.1, 3.1, 3.1]).astype(\"float32\"),\n        np.float32(3.5),\n        np.array([5]).astype(\"int32\"),\n    )\n    # default value not specified\n    _test_sparse_to_dense(\n        np.array([0, 1, 4]).astype(\"int32\"),\n        np.array([3.1, 3.1, 3.1]).astype(\"float32\"),\n        None,\n        np.array([5]).astype(\"int32\"),\n    )\n\n\n#######################################################################\n# Fully Connected\n# ---------------\ndef _test_fully_connected(\n    tensor_in_sizes,\n    const_input,\n    filter_in_sizes,\n    bias_in_size=None,\n    quantized=False,\n    fp16_quantized=False,\n):\n    \"\"\"One iteration of fully connected\"\"\"\n\n    total_size_1 = np.prod(tensor_in_sizes)\n    total_size_2 = np.prod(filter_in_sizes)\n\n    assert (\n        int(total_size_1 / tensor_in_sizes[0]) == filter_in_sizes[0]\n    ), \"input size and filter size are mismatched\"\n\n    # Initializes the input tensor with array containing incrementing\n    # numbers from 1.\n    data_array = np.arange(\n        1, total_size_1 + 1, dtype=np.uint8 if quantized and not fp16_quantized else np.float32\n    )\n    filter_array = np.arange(\n        1, total_size_2 + 1, dtype=np.uint8 if quantized and not fp16_quantized else np.float32\n    )\n    in_name = \"input\"\n\n    with tf.Graph().as_default():\n        in_data = (\n            constant_op.constant(data_array, shape=tensor_in_sizes, dtype=np.float32, name=in_name)\n            if const_input\n            else array_ops.placeholder(shape=tensor_in_sizes, dtype=np.float32, name=in_name)\n        )\n\n        in_filter = constant_op.constant(filter_array, shape=filter_in_sizes, dtype=np.float32)\n        data_array = np.reshape(data_array, tensor_in_sizes)\n\n        # if we have bias\n        if bias_in_size:\n            assert bias_in_size[0] == filter_in_sizes[1], \"bias and filter size are mismatched\"\n            bias_array = np.arange(\n                1, bias_in_size[0] + 1, dtype=np.uint8 if quantized else np.float32\n            )\n            in_bias = constant_op.constant(bias_array, shape=bias_in_size, dtype=np.float32)\n\n        if quantized and not fp16_quantized:\n            inq_data = tf.quantization.fake_quant_with_min_max_args(\n                in_data, min=-100, max=100, name=\"inq_0\"\n            )\n            input_range = {\"inq_0\": (-100, 100)}\n            inq_filter = tf.quantization.fake_quant_with_min_max_args(\n                in_filter, min=-100, max=100, name=\"inq_1\"\n            )\n            input_range = {\"inq_0\": (-100, 100), \"inq_1\": (-100, 100)}\n            # reshape N H W C into N H*W*C\n            inq_data_reshape = array_ops.reshape(inq_data, [tensor_in_sizes[0], -1])\n            out = math_ops.mat_mul(inq_data_reshape, inq_filter)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-100, max=100, name=\"out\")\n\n            # if we have bias\n            if bias_in_size:\n                out = nn_ops.bias_add(out, in_bias)\n\n            compare_tflite_with_tvm(\n                data_array,\n                inq_data.name,\n                [inq_data],\n                [out],\n                quantized=True,\n                input_range=input_range,\n                experimental_new_converter=True,\n            )\n        else:\n            # reshape N H W C into N H*W*C\n            in_data_reshape = array_ops.reshape(in_data, [tensor_in_sizes[0], -1])\n            out = math_ops.mat_mul(in_data_reshape, in_filter)\n            # TODO : Need to construct a fc op with (keep_num_dims == True)\n\n            # if we have bias\n            if bias_in_size:\n                out = nn_ops.bias_add(out, in_bias)\n\n            compare_tflite_with_tvm(\n                data_array,\n                in_data.name,\n                [in_data],\n                [out],\n                experimental_new_converter=True,\n                fp16_quantized=fp16_quantized,\n            )\n\n\ndef test_forward_fully_connected():\n    \"\"\"Fully Connected\"\"\"\n    for input_shape, weight_shape, bias_shape in [\n        ([1, 4], [4, 4], None),\n        ([1, 4], [4, 4], [4]),\n        ([1, 1, 1, 5], [5, 5], None),\n        ([1, 1, 10], [10, 103], None),\n        ([1, 1, 1, 150], [150, 100], None),\n        ([1, 1, 1, 150], [150, 100], None),\n        ([1, 1, 1, 150], [150, 100], [100]),\n        ([5, 1, 1, 150], [150, 100], None),\n        ([5, 1, 1, 150], [150, 100], [100]),\n    ]:\n        for const_input in [False, True]:\n            for quantized in [False, True]:\n                for fp16_quantized in [False, True]:\n                    _test_fully_connected(\n                        input_shape,\n                        const_input,\n                        weight_shape,\n                        bias_shape,\n                        quantized,\n                        fp16_quantized,\n                    )\n\n\n#######################################################################\n# REVERSE_V2\n# ----------\n\n\ndef _test_reverse_v2(input_shape, axis, dtype):\n    \"\"\"One iteration of REVERSE_V2\"\"\"\n    with tf.Graph().as_default():\n        input_array = np.random.randint(0, 100, size=input_shape).astype(dtype)\n        in_input = tf.placeholder(dtype=input_array.dtype, shape=input_array.shape, name=\"input\")\n        in_axis = ops.convert_to_tensor(axis, dtype=axis.dtype)\n\n        out = array_ops.reverse(in_input, in_axis)\n\n        compare_tflite_with_tvm([input_array], [\"input\"], [in_input], [out])\n\n\ndef test_forward_reverse_v2():\n    \"\"\"REVERSE_V2\"\"\"\n    for dtype in [\"float32\", \"int32\"]:\n        _test_reverse_v2((5), np.array([0], dtype=\"int32\"), dtype)\n        _test_reverse_v2((5, 6, 4, 2), np.array([2], dtype=\"int32\"), dtype)\n\n\n#######################################################################\n# MATRIX_SET_DIAG\n# ---------------\n\n\ndef _test_matrix_set_diag(input_shape, input_type, quantized=False):\n    \"\"\"One iteration of MATRIX_SET_DIAG\"\"\"\n    with tf.Graph().as_default():\n        diagonal_shape = list(input_shape[:-2])\n        diagonal_shape.append(min(input_shape[-2], input_shape[-1]))\n\n        if quantized:\n            # ignoring input_type as quantized requires uint8\n            input_array = np.random.uniform(0, 256, input_shape).astype(\"uint8\")\n            in_input = tf.placeholder(dtype=\"float32\", shape=input_array.shape, name=\"input\")\n            inq_input = tf.quantization.fake_quant_with_min_max_args(\n                in_input, min=-100, max=100, name=\"q_input\"\n            )\n\n            diagonal = np.random.uniform(0, 256, diagonal_shape).astype(\"uint8\")\n            in_diagonal = tf.placeholder(dtype=\"float32\", shape=diagonal.shape, name=\"diagonal\")\n            inq_diagonal = tf.quantization.fake_quant_with_min_max_args(\n                in_diagonal, min=-100, max=100, name=\"q_diagonal\"\n            )\n\n            input_range = {\"q_input\": (-100, 100), \"q_diagonal\": (-100, 100)}\n\n            out = array_ops.matrix_set_diag(inq_input, inq_diagonal)\n            out = tf.quantization.fake_quant_with_min_max_args(out, min=-100, max=100, name=\"out\")\n\n            compare_tflite_with_tvm(\n                [input_array, diagonal],\n                [\"q_input\", \"q_diagonal\"],\n                [inq_input, inq_diagonal],\n                [out],\n                quantized=True,\n                input_range=input_range,\n            )\n        else:\n            input_array = np.random.uniform(0, 100, input_shape).astype(input_type)\n            diagonal = np.random.uniform(0, 100, diagonal_shape).astype(input_type)\n\n            in_input = tf.placeholder(\n                dtype=input_array.dtype, shape=input_array.shape, name=\"input\"\n            )\n            in_diagonal = tf.placeholder(\n                dtype=diagonal.dtype, shape=diagonal.shape, name=\"diagonal\"\n            )\n\n            out = array_ops.matrix_set_diag(in_input, in_diagonal)\n\n            compare_tflite_with_tvm(\n                [input_array, diagonal], [\"input\", \"diagonal\"], [in_input, in_diagonal], [out]\n            )\n\n\ndef test_forward_matrix_set_diag():\n    \"\"\"MATRIX_SET_DIAG\"\"\"\n    for dtype in [np.float32, np.int32]:\n        _test_matrix_set_diag((4, 4), dtype)\n        _test_matrix_set_diag((5, 4, 3, 4), dtype)\n        _test_matrix_set_diag((4, 4, 2), dtype)\n\n    _test_matrix_set_diag((4, 4), np.uint8, quantized=True)\n    _test_matrix_set_diag((5, 4, 3, 4), np.uint8, quantized=True)\n    _test_matrix_set_diag((4, 4, 2), np.uint8, quantized=True)\n\n\n#######################################################################\n# MATRIX_DIAG\n# -----------\n\n\ndef _test_matrix_diag(diagonal_shape, dtype):\n    \"\"\"One iteration of MATRIX_DIAG\"\"\"\n    with tf.Graph().as_default():\n        diagonal = np.random.uniform(0, 100, diagonal_shape).astype(dtype)\n        in_diagonal = tf.placeholder(dtype=diagonal.dtype, shape=diagonal.shape, name=\"diagonal\")\n\n        out = array_ops.matrix_diag(in_diagonal)\n\n        compare_tflite_with_tvm(\n            [diagonal], [\"diagonal\"], [in_diagonal], [out], experimental_new_converter=True\n        )\n\n\ndef test_forward_matrix_diag():\n    \"\"\"MATRIX_DIAG\"\"\"\n    for dtype in [np.float32, np.int32]:\n        _test_matrix_diag((4), dtype)\n        _test_matrix_diag((5, 4, 3), dtype)\n        _test_matrix_diag((2, 3), dtype)\n\n\n#######################################################################\n# Custom Operators\n# ----------------\n\n\ndef _test_detection_postprocess(tf_model_file, box_encodings_size, class_predictions_size):\n    \"\"\"One iteration of detection postProcess with given model and shapes\"\"\"\n    converter = tf.lite.TFLiteConverter.from_frozen_graph(\n        tf_model_file,\n        input_arrays=[\"raw_outputs/box_encodings\", \"raw_outputs/class_predictions\"],\n        output_arrays=[\n            \"TFLite_Detection_PostProcess\",\n            \"TFLite_Detection_PostProcess:1\",\n            \"TFLite_Detection_PostProcess:2\",\n            \"TFLite_Detection_PostProcess:3\",\n        ],\n        input_shapes={\n            \"raw_outputs/box_encodings\": box_encodings_size,\n            \"raw_outputs/class_predictions\": class_predictions_size,\n        },\n    )\n    converter.allow_custom_ops = True\n    converter.inference_type = tf.lite.constants.FLOAT\n    tflite_model = converter.convert()\n    np.random.seed(0)\n    box_encodings = np.random.uniform(size=box_encodings_size).astype(\"float32\")\n    class_predictions = np.random.uniform(size=class_predictions_size).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model, [box_encodings, class_predictions])\n    tvm_output = run_tvm_graph(\n        tflite_model,\n        [box_encodings, class_predictions],\n        [\"raw_outputs/box_encodings\", \"raw_outputs/class_predictions\"],\n        num_output=4,\n    )\n\n    # Check all output shapes are equal\n    assert all(\n        list(\n            tvm_tensor.shape == tflite_tensor.shape\n            for (tvm_tensor, tflite_tensor) in zip(tvm_output, tflite_output)\n        )\n    )\n\n    # Check valid count is the same\n    assert tvm_output[3] == tflite_output[3]\n    valid_count = tvm_output[3][0]\n\n    # For boxes that do not have any detections, TFLite puts random values. Therefore, we compare\n    # tflite and tvm tensors for only valid boxes.\n    for i in range(0, valid_count):\n        # Check bounding box co-ords\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[0][0][i]),\n            np.squeeze(tflite_output[0][0][i]),\n            rtol=1e-5,\n            atol=1e-5,\n        )\n\n        # Check the class\n        # Stricter check to ensure class remains same\n        np.testing.assert_equal(np.squeeze(tvm_output[1][0][i]), np.squeeze(tflite_output[1][0][i]))\n\n        # Check the score\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[2][0][i]),\n            np.squeeze(tflite_output[2][0][i]),\n            rtol=1e-5,\n            atol=1e-5,\n        )\n\n\ndef test_detection_postprocess():\n    \"\"\"Detection PostProcess\"\"\"\n    box_encodings_size = (1, 1917, 4)\n    class_predictions_size = (1, 1917, 91)\n    tf_model_file = tf_testing.get_workload_official(\n        \"http://download.tensorflow.org/models/object_detection/\"\n        \"ssd_mobilenet_v2_quantized_300x300_coco_2019_01_03.tar.gz\",\n        \"ssd_mobilenet_v2_quantized_300x300_coco_2019_01_03/tflite_graph.pb\",\n    )\n    _test_detection_postprocess(tf_model_file, box_encodings_size, class_predictions_size)\n\n    box_encodings_size = (1, 2034, 4)\n    class_predictions_size = (1, 2034, 91)\n    tf_model_file = download_testdata(\n        \"https://github.com/czh978/models_for_tvm_test/raw/main/tflite_graph_with_postprocess.pb\",\n        \"tflite_graph_with_postprocess.pb\",\n    )\n    _test_detection_postprocess(tf_model_file, box_encodings_size, class_predictions_size)\n\n\n#######################################################################\n# Custom Converter\n# ----------------\n\n\ndef test_custom_op_converter():\n    \"\"\"Test case for user-defined operator converter in TFLite frontend\"\"\"\n\n    class DummyOperatorConverter(relay.frontend.tflite.OperatorConverter):\n        \"\"\"Operator Converter for converting TFLite ops to relay ops\"\"\"\n\n        def __init__(self, model, subgraph, exp_tab):\n            super().__init__(model, subgraph, exp_tab)\n            self.allow_custom_ops = True\n\n            convert_map_overwrite = {\"SUB\": self.convert_sub_dummy}\n\n            self.convert_map.update(convert_map_overwrite)\n\n        def convert_sub_dummy(self, op):\n            \"\"\"Convert TFLite SUB\"\"\"\n            input_tensors = self.get_input_tensors(op)\n            assert len(input_tensors) == 2, \"input tensors length should be 2\"\n\n            lhs_tensor = input_tensors[0]\n            rhs_tensor = input_tensors[1]\n\n            lhs_expr = self.get_expr(lhs_tensor.tensor_idx)\n            rhs_expr = self.get_expr(rhs_tensor.tensor_idx)\n\n            temp_expr = relay.op.negative(rhs_expr)\n            out = relay.op.add(lhs_expr, temp_expr)\n\n            return out\n\n    with tf.Graph().as_default():\n        # Generate TFLite model for single addition\n        data = [\n            np.arange(6.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n            np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)),\n        ]\n        in_data = [\n            array_ops.placeholder(shape=data[0].shape, dtype=\"float32\", name=\"in_0\"),\n            array_ops.placeholder(shape=data[1].shape, dtype=\"float32\", name=\"in_1\"),\n        ]\n        out = math_ops.subtract(in_data[0], in_data[1])\n        in_name = [x[1] for x in zip(in_data, (\"in_0:0\", \"in_1:0\"))]\n        input_tensors = in_data\n        output_tensors = [out]\n        in_node = [0] * len(in_name)\n        for i, _ in enumerate(in_name):\n            in_node[i] = in_name[i].split(\":\")[0]\n\n        with tf.Session() as sess:\n            converter = tf.lite.TFLiteConverter.from_session(sess, input_tensors, output_tensors)\n            tflite_model_buf = converter.convert()\n    in_data = [x[1] for x in zip(in_data, data)]\n    tvm_output_orig = run_tvm_graph(tflite_model_buf, in_data, in_node)\n    tvm_output_dummy = run_tvm_graph(\n        tflite_model_buf, in_data, in_node, op_converter=DummyOperatorConverter\n    )\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output_orig[0]), np.squeeze(tvm_output_dummy[0]), rtol=1e-5, atol=1e-5\n    )\n\n\n#######################################################################\n# Mobilenet\n# ---------\n\n\ndef test_forward_mobilenet_v1():\n    \"\"\"Test the Mobilenet V1 TF Lite model.\"\"\"\n    # MobilenetV1\n    tflite_model_file = tf_testing.get_workload_official(\n        \"http://download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz\",\n        \"mobilenet_v1_1.0_224.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\ndef test_forward_mobilenet_v2():\n    \"\"\"Test the Mobilenet V2 TF Lite model.\"\"\"\n    # MobilenetV2\n    tflite_model_file = tf_testing.get_workload_official(\n        \"http://download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224.tgz\",\n        \"mobilenet_v2_1.0_224.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\n#######################################################################\n# Mobilenet V3\n# ------------\n\n\ndef test_forward_mobilenet_v3():\n    \"\"\"Test the Mobilenet V3 TF Lite model.\"\"\"\n    # In MobilenetV3, some ops are not supported before tf 1.15 fbs schema\n    if package_version.parse(tf.VERSION) < package_version.parse(\"1.15.0\"):\n        return\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/mobilenet_v3/checkpoints/v3-large_224_1.0_float.tgz\",\n        \"v3-large_224_1.0_float/v3-large_224_1.0_float.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\n#######################################################################\n# Mobilenet V1 Sparse\n# -----------------\n\n\ndef test_forward_sparse_mobilenet_v1():\n    \"\"\"Test the Sparse version of Mobilenet V1 TF Lite model.\"\"\"\n    # MobilenetV1\n    tflite_model_file = download_testdata(\n        \"https://storage.googleapis.com/fast-convnets/tflite-models/mbv1_140_90_12b4_720.tflite\",\n        \"mbv1_140_90_12b4_720.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"float_image_input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\n#######################################################################\n# Mobilenet V2 Sparse\n# -----------------\n\n\ndef test_forward_sparse_mobilenet_v2():\n    \"\"\"Test the Sparse version of Mobilenet V2 TF Lite model.\"\"\"\n    # MobilenetV1\n    tflite_model_file = download_testdata(\n        \"https://storage.googleapis.com/fast-convnets/tflite-models/mbv2_200_85_11-16b2_744.tflite\",\n        \"mbv2_200_85_11-16b2_744.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 224, 224, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"float_image_input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\n#######################################################################\n# Inception\n# ---------\n\n\ndef test_forward_inception_v3_net():\n    \"\"\"Test the Inception V3 TF Lite model.\"\"\"\n    # InceptionV3\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/\"\n        \"upload_20180427/inception_v3_2018_04_27.tgz\",\n        \"inception_v3.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 299, 299, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\ndef test_forward_inception_v4_net():\n    \"\"\"Test the Inception V4 TF Lite model.\"\"\"\n    # InceptionV4\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n        \"tflite/model_zoo/upload_20180427/\"\n        \"inception_v4_2018_04_27.tgz\",\n        \"inception_v4.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 299, 299, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\ndef test_forward_inception_v4_net_batched():\n    \"\"\"Test the Inception V4 TF Lite model.\"\"\"\n    # InceptionV4\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n        \"tflite/model_zoo/upload_20180427/\"\n        \"inception_v4_2018_04_27.tgz\",\n        \"inception_v4.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(4, 299, 299, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm.testing.assert_allclose(\n        np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5\n    )\n\n\ndef test_forward_qnn_inception_v1_net():\n    \"\"\"Test the Quantized TFLite Inception model.\"\"\"\n    # InceptionV1\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n        \"inception_v1_224_quant_20181026.tgz\",\n        \"inception_v1_224_quant.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    data = get_real_image(224, 224)\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_qnn_mobilenet_v1_net():\n    \"\"\"Test the Quantized TFLite Mobilenet V1 model.\"\"\"\n    # MobilenetV1\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/\"\n        \"mobilenet_v1_1.0_224_quant.tgz\",\n        \"mobilenet_v1_1.0_224_quant.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    data = get_real_image(224, 224)\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_qnn_mobilenet_v2_net():\n    \"\"\"Test the Quantized TFLite Mobilenet V2 model.\"\"\"\n    # MobilenetV2\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/\"\n        \"mobilenet_v2_1.0_224_quant.tgz\",\n        \"mobilenet_v2_1.0_224_quant.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    data = get_real_image(224, 224)\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\n#######################################################################\n# Mobilenet V3 Quantized\n# ----------------------\n\n\ndef test_forward_qnn_mobilenet_v3_net():\n    \"\"\"Test the Quantized TFLite Mobilenet V3 model.\"\"\"\n    # In MobilenetV3, some ops are not supported before tf 1.15 fbs schema\n    if package_version.parse(tf.VERSION) < package_version.parse(\"1.15.0\"):\n        pytest.skip(\"Unsupported in tflite < 1.15.0\")\n    else:\n        pytest.skip(\"This segfaults with tensorflow 1.15.2 and above\")\n\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/mobilenet_v3/checkpoints/v3-large_224_1.0_uint8.tgz\",\n        \"v3-large_224_1.0_uint8/v3-large_224_1.0_uint8.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    data = get_real_image(224, 224)\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_tflite2_qnn_resnet50():\n    \"\"\"Test the Quantized TFLite version 2.1.0 Resnet50 model.\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.1.0\"):\n        tflite_model_file = download_testdata(\n            \"https://raw.githubusercontent.com/dmlc/web-data/main/tensorflow/models/Quantized/\"\n            \"resnet_50_quantized.tflite\",\n            \"resnet_50_quantized.tflite\",\n        )\n        with open(tflite_model_file, \"rb\") as f:\n            tflite_model_buf = f.read()\n\n        data = pre_processed_image(224, 224)\n\n        tflite_output = run_tflite_graph(tflite_model_buf, data)\n        tflite_predictions = np.squeeze(tflite_output)\n        tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n        tvm_output = run_tvm_graph(tflite_model_buf, np.array(data), \"input_1\")\n        tvm_predictions = np.squeeze(tvm_output)\n        tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n        tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_tflite2_qnn_inception_v1():\n    \"\"\"Test the Quantized TFLite version 2.1.0 Inception V1 model.\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.1.0\"):\n        tflite_model_file = download_testdata(\n            \"https://raw.githubusercontent.com/dmlc/web-data/main/tensorflow/models/Quantized/\"\n            \"inception_v1_quantized.tflite\",\n            \"inception_v1_quantized.tflite\",\n        )\n        with open(tflite_model_file, \"rb\") as f:\n            tflite_model_buf = f.read()\n\n        data = pre_processed_image(224, 224)\n\n        tflite_output = run_tflite_graph(tflite_model_buf, data)\n        tflite_predictions = np.squeeze(tflite_output)\n        tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n        tvm_output = run_tvm_graph(tflite_model_buf, np.array(data), \"input_1\")\n        tvm_predictions = np.squeeze(tvm_output)\n        tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n        tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_tflite2_qnn_mobilenet_v2():\n    \"\"\"Test the Quantized TFLite version 2.1.0 Mobilenet V2 model.\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.1.0\"):\n        tflite_model_file = download_testdata(\n            \"https://raw.githubusercontent.com/dmlc/web-data/main/tensorflow/models/Quantized/\"\n            \"mobilenet_v2_quantized.tflite\",\n            \"mobilenet_v2_quantized.tflite\",\n        )\n        with open(tflite_model_file, \"rb\") as f:\n            tflite_model_buf = f.read()\n\n        data = pre_processed_image(224, 224)\n\n        tflite_output = run_tflite_graph(tflite_model_buf, data)\n        tflite_predictions = np.squeeze(tflite_output)\n        tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n        tvm_output = run_tvm_graph(tflite_model_buf, np.array(data), \"input_1\")\n        tvm_predictions = np.squeeze(tvm_output)\n        tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n        tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_tflite_float16():\n    \"\"\"Test float16 quantized model\"\"\"\n    # MobilenetV2\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_02_22/\"\n        \"mobilenet_v1_0.25_128.tgz\",\n        \"mobilenet_v1_0.25_128_frozen.pb\",\n    )\n\n    converter = tf.lite.TFLiteConverter.from_frozen_graph(\n        tflite_model_file, [\"input\"], [\"MobilenetV1/Predictions/Reshape_1\"]\n    )\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    converter.target_spec.supported_types = [tf.float16]\n    tflite_model_buf = converter.convert()\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    data = get_real_image(128, 128, quantized=False)\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\ndef test_forward_mobilenet_int16():\n    \"\"\"Test int16 quantized model\"\"\"\n    # MobilenetV2\n    model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_02_22/\"\n        \"mobilenet_v1_0.25_128.tgz\",\n        \"mobilenet_v1_0.25_128_frozen.pb\",\n    )\n\n    # Test image. Checking the labels because the requantize implementation is different between\n    # TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via\n    # labels. Also, giving a real image, instead of random inputs.\n    #\n    # According to TFLite documentation, despite the quantization being done to make this model\n    # use int16 types, inputs and outputs are kept float32 by default.\n    # https://www.tensorflow.org/lite/performance/post_training_integer_quant_16x8\n    data = get_real_image(128, 128, quantized=False)\n\n    converter = tf.lite.TFLiteConverter.from_frozen_graph(\n        model_file, [\"input\"], [\"MobilenetV1/Predictions/Reshape_1\"]\n    )\n\n    def representative_dataset():\n        for _ in range(1):\n            yield [data]\n\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    converter.target_spec.supported_ops = [\n        tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8\n    ]\n    converter.representative_dataset = representative_dataset\n    tflite_model_buf = converter.convert()\n\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tflite_predictions = np.squeeze(tflite_output)\n    tflite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input\")\n    tvm_predictions = np.squeeze(tvm_output)\n    tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]\n    tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)\n\n\n#######################################################################\n# Unidirectional Sequence LSTM\n# ---------------------\ndef test_forward_unidirectional_sequence_lstm():\n    \"\"\"Test the UnidirectionalSequenceLSTM TFLite\"\"\"\n    if package_version.parse(tf.VERSION) >= package_version.parse(\"2.1.0\"):\n        tflite_model_file = download_testdata(\n            \"https://github.com/SebastianBoblestETAS/nn_models/blob/\"\n            \"ce49c5de64889493161ca4194a20e0fd5eb707e6/lstm_1_in_3_out_2_ts_4.tflite?raw=true\",\n            \"lstm_1_in_3_out_2_ts_4.tflite\",\n        )\n        with open(tflite_model_file, \"rb\") as f:\n            tflite_model_buf = f.read()\n\n        data = np.array(\n            [\n                [\n                    [0.5488135, 0.71518934, 0.60276335],\n                    [0.5448832, 0.4236548, 0.6458941],\n                    [0.4375872, 0.891773, 0.96366274],\n                    [0.3834415, 0.79172504, 0.5288949],\n                ]\n            ],\n            dtype=\"float32\",\n        )\n\n        tflite_output = run_tflite_graph(tflite_model_buf, data)\n        tvm_output = run_tvm_graph(tflite_model_buf, data, \"serving_default_input_1:0\")\n        tvm.testing.assert_allclose(tflite_output, tvm_output)\n\n\n#######################################################################\n# Quantized SSD Mobilenet\n# -----------------------\n\n\ndef test_forward_qnn_coco_ssd_mobilenet_v1():\n    \"\"\"Test the quantized Coco SSD Mobilenet V1 TF Lite model.\"\"\"\n    pytest.skip(\n        \"LLVM bug - getExtendedVectorNumElements - \"\n        + \"https://discuss.tvm.apache.org/t/segfault-in-llvm/3567. The workaround is to use a \"\n        + \"specific target, for example, llvm -mpcu=core-avx2\"\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/models/tflite/\"\n        \"coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip\",\n        \"detect.tflite\",\n    )\n\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    data = get_real_image_object_detection(300, 300)\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(\n        tflite_model_buf, data, \"normalized_input_image_tensor\", num_output=4\n    )\n\n    # Check all output shapes are equal\n    assert all(\n        list(\n            tvm_tensor.shape == tflite_tensor.shape\n            for (tvm_tensor, tflite_tensor) in zip(tvm_output, tflite_output)\n        )\n    )\n\n    # Check valid count is the same\n    assert tvm_output[3] == tflite_output[3]\n    valid_count = tvm_output[3][0]\n\n    # For boxes that do not have any detections, TFLite puts random values. Therefore, we compare\n    # tflite and tvm tensors for only valid boxes.\n    for i in range(0, valid_count):\n        # We compare the bounding boxes whose prediction score is above 60%. This is typical in end\n        # to end application where a low prediction score is discarded. This is also needed because\n        # multiple low score bounding boxes can have same score and TFlite and TVM can have\n        # different orderings for same score bounding boxes. Another reason for minor differences in\n        # low score bounding boxes is the difference between TVM and TFLite for requantize operator.\n        if tvm_output[2][0][i] > 0.6:\n            # Check bounding box co-ords. The tolerances have to be adjusted, from 1e-5 to 1e-2,\n            # because of differences between for requantiize operator in TFLite and TVM.\n            tvm.testing.assert_allclose(\n                np.squeeze(tvm_output[0][0][i]),\n                np.squeeze(tflite_output[0][0][i]),\n                rtol=1e-2,\n                atol=1e-2,\n            )\n\n            # Check the class\n            # Stricter check to ensure class remains same\n            np.testing.assert_equal(\n                np.squeeze(tvm_output[1][0][i]), np.squeeze(tflite_output[1][0][i])\n            )\n\n            # Check the score\n            tvm.testing.assert_allclose(\n                np.squeeze(tvm_output[2][0][i]),\n                np.squeeze(tflite_output[2][0][i]),\n                rtol=1e-5,\n                atol=1e-5,\n            )\n\n\n#######################################################################\n# SSD Mobilenet\n# -------------\n\n\ndef test_forward_coco_ssd_mobilenet_v1():\n    \"\"\"Test the FP32 Coco SSD Mobilenet V1 TF Lite model.\"\"\"\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://raw.githubusercontent.com/dmlc/web-data/main/tensorflow/models/object_detection/\"\n        \"ssd_mobilenet_v1_coco_2018_01_28.tgz\",\n        \"ssd_mobilenet_v1_coco_2018_01_28.tflite\",\n    )\n\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n\n    np.random.seed(0)\n    data = np.random.uniform(size=(1, 300, 300, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(\n        tflite_model_buf, data, \"normalized_input_image_tensor\", num_output=4\n    )\n\n    # Check all output shapes are equal\n    assert all(\n        list(\n            tvm_tensor.shape == tflite_tensor.shape\n            for (tvm_tensor, tflite_tensor) in zip(tvm_output, tflite_output)\n        )\n    )\n\n    # Check valid count is the same\n    assert tvm_output[3] == tflite_output[3]\n    valid_count = tvm_output[3][0]\n\n    # For boxes that do not have any detections, TFLite puts random values. Therefore, we compare\n    # tflite and tvm tensors for only valid boxes.\n    for i in range(0, valid_count):\n        # Check bounding box co-ords\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[0][0][i]),\n            np.squeeze(tflite_output[0][0][i]),\n            rtol=1e-5,\n            atol=1e-5,\n        )\n        # Check the class\n        np.testing.assert_equal(np.squeeze(tvm_output[1][0][i]), np.squeeze(tflite_output[1][0][i]))\n\n        # Check the score\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[2][0][i]),\n            np.squeeze(tflite_output[2][0][i]),\n            rtol=1e-5,\n            atol=1e-5,\n        )\n\n\n#######################################################################\n# MediaPipe\n# -------------\ndef test_forward_mediapipe_hand_landmark():\n    \"\"\"Test MediaPipe 2D hand landmark TF Lite model.\"\"\"\n    # MediaPipe 2D hand landmark TF\n    tflite_model_file = download_testdata(\n        \"https://github.com/google/mediapipe/raw/v0.7.4/mediapipe/models/hand_landmark.tflite\",\n        \"hand_landmark.tflite\",\n    )\n    with open(tflite_model_file, \"rb\") as f:\n        tflite_model_buf = f.read()\n    data = np.random.uniform(size=(1, 256, 256, 3)).astype(\"float32\")\n    tflite_output = run_tflite_graph(tflite_model_buf, data)\n    tvm_output = run_tvm_graph(tflite_model_buf, data, \"input_1\", num_output=2)\n    for i in range(2):\n        tvm.testing.assert_allclose(\n            np.squeeze(tvm_output[i]), np.squeeze(tflite_output[i]), rtol=1e-5, atol=1e-5\n        )\n\n\n#######################################################################\n# Test check for Tensorflow \"dynamic range quantization\" optimization\n# --------------\ndef test_prevent_tensorflow_dynamic_range():\n    \"\"\"\n    Should prevent running \"dynamic range quantization\" optimized TFLite graph\n    \"\"\"\n    data_array = np.random.randint(0, 2, (1, 1024, 1024)).astype(dtype=np.float32)\n    filter_array = np.random.randint(0, 2, (1024, 1024)).astype(dtype=np.float32)\n    data_in = tf.keras.layers.Input(shape=data_array.shape[1:])\n    dense = tf.keras.layers.Dense(units=filter_array.shape[-1], use_bias=False)(data_in)\n    keras_model = tf.keras.models.Model(data_in, dense)\n    keras_model.layers[1].set_weights([filter_array])\n\n    converter = interpreter_wrapper.TFLiteConverter.from_keras_model(keras_model)\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    tflite_model = converter.convert()\n    with pytest.raises(tvm.error.OpNotImplemented):\n        _ = run_tvm_graph(tflite_model, data_array, data_in.name.replace(\":0\", \"\"))\n\n\ndef _test_nms_v5(\n    bx_shape, score_shape, iou_threshold, score_threshold, max_output_size, dtype=\"float32\"\n):\n    \"\"\"One iteration of nms_v5 with given attributes\"\"\"\n    boxes = np.random.uniform(0, 10, size=bx_shape).astype(dtype)\n    scores = np.random.uniform(size=score_shape).astype(dtype)\n\n    tf.reset_default_graph()\n    tf.compat.v1.disable_eager_execution()\n    in_data_1 = array_ops.placeholder(dtype, boxes.shape, name=\"in_data_1\")\n    in_data_2 = array_ops.placeholder(dtype, scores.shape, name=\"in_data_2\")\n    out = image_ops.non_max_suppression_with_scores(\n        boxes=in_data_1,\n        scores=in_data_2,\n        max_output_size=max_output_size,\n        iou_threshold=iou_threshold,\n        score_threshold=score_threshold,\n        name=\"nms\",\n    )\n\n    compare_tflite_with_tvm(\n        [boxes, scores],\n        [\"in_data_1:0\", \"in_data_2:0\"],\n        [in_data_1, in_data_2],\n        [out[0], out[1]],\n        out_names=[out[0].name, out[1].name],\n        experimental_new_converter=True,\n    )\n\n\ndef test_forward_nms_v5():\n    \"\"\"test nms_v5\"\"\"\n    _test_nms_v5((10000, 4), (10000,), 0.5, 0.4, 100)\n    _test_nms_v5((1000, 4), (1000,), 0.7, 0.3, 50)\n\n\n#######################################################################\n# Main\n# ----\nif __name__ == \"__main__\":\n    # BatchToSpaceND\n    test_forward_batch_to_space_nd()\n\n    # SpaceToBatchND\n    test_forward_space_to_batch_nd()\n\n    # Split\n    test_forward_split()\n\n    # Transpose\n    test_forward_transpose()\n\n    # Cast\n    test_forward_cast()\n\n    # BatchMatMul\n    test_forward_batch_matmul()\n\n    # Tile\n    test_forward_tile()\n\n    # Query\n    test_forward_shape()\n\n    # Transforms\n    test_forward_concatenation()\n    test_forward_pad()\n    test_forward_pack()\n    test_forward_unpack()\n    test_forward_reshape()\n    test_all_resize()\n    test_forward_range()\n    test_forward_squeeze()\n    test_forward_slice()\n    test_forward_topk()\n    test_forward_gather()\n    test_forward_gather_nd()\n    test_forward_stridedslice()\n    test_forward_depthtospace()\n    test_forward_spacetodepth()\n    test_forward_reverse_sequence()\n    test_forward_sparse_to_dense()\n    test_forward_select()\n    test_forward_quantize_dequantize()\n    test_forward_arg_min_max()\n    test_forward_expand_dims()\n    test_forward_reverse_v2()\n    test_forward_matrix_set_diag()\n    test_forward_matrix_diag()\n\n    # NN\n    test_forward_convolution()\n    test_forward_transpose_conv()\n    test_forward_logistic()\n    test_forward_pooling()\n    test_forward_l2_pool2d()\n    test_forward_softmax()\n    test_forward_tanh()\n    test_forward_relu()\n    test_forward_relu6()\n    test_forward_leaky_relu()\n    test_forward_relu_n1_to_1()\n    test_forward_log_softmax()\n    test_forward_fully_connected()\n    test_forward_l2_normalization()\n    test_forward_local_response_normalization()\n    test_forward_prelu()\n    test_forward_unidirectional_sequence_lstm()\n\n    # Elemwise\n    test_all_elemwise()\n    test_forward_add_n()\n\n    # Unary elemwise\n    test_all_unary_elemwise()\n    # Zeros Like\n    test_forward_zeros_like()\n\n    # Fill\n    test_forward_fill()\n\n    # Reduce\n    test_all_reduce()\n\n    # Logical\n    test_all_logical()\n\n    # Detection_PostProcess\n    test_detection_postprocess()\n\n    # NonMaxSuppressionV5\n    test_forward_nms_v5()\n\n    # Overwrite Converter\n    test_custom_op_converter()\n\n    # End to End\n    test_forward_mobilenet_v1()\n    test_forward_mobilenet_v2()\n    test_forward_mobilenet_v3()\n    test_forward_inception_v3_net()\n    test_forward_inception_v4_net()\n    test_forward_inception_v4_net_batched()\n    test_forward_coco_ssd_mobilenet_v1()\n    test_forward_mediapipe_hand_landmark()\n\n    # End to End Sparse models\n    test_forward_sparse_mobilenet_v1()\n    test_forward_sparse_mobilenet_v2()\n\n    # End to End quantized\n    test_forward_qnn_inception_v1_net()\n    test_forward_qnn_mobilenet_v1_net()\n    test_forward_qnn_mobilenet_v2_net()\n    # This also fails with a segmentation fault in my run\n    # with Tflite 1.15.2\n    test_forward_qnn_mobilenet_v3_net()\n    test_forward_qnn_coco_ssd_mobilenet_v1()\n\n    # TFLite 2.1.0 quantized tests\n    test_forward_quantized_convolution()\n    test_forward_quantized_depthwise_convolution()\n    test_forward_tflite2_qnn_resnet50()\n    test_forward_tflite2_qnn_inception_v1()\n    test_forward_tflite2_qnn_mobilenet_v2()\n\n    test_forward_tflite_float16()\n\n    test_forward_tflite_int16()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Infrastructure and tests for e2e integration tests.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_arm_mprofile_dsp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test arm mprofile dsp.\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import AOT_CORSTONE300_RUNNER\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_nhwc, kernel_size, num_filter, strides, padding, dilation\",\n    [\n        ((1, 32, 32, 1), (3, 3), 12, 1, 0, 1),\n        ((1, 32, 10, 3), (3, 3), 16, 1, 0, 1),\n        ((1, 49, 10, 1), (10, 4), 64, (2, 1), (4, 1, 5, 1), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n        # bug https://github.com/apache/tvm/issues/9226\n        ((1, 49, 10, 1), (10, 4), 64, (2, 2), (4, 1, 5, 1), 1),\n        # from Visual Wake Word model\n        ((1, 96, 96, 3), (3, 3), 8, (2, 2), (0, 0, 1, 1), 1),\n        # from Image Classification model (one of the MLPerfTiny models)\n        ((1, 16, 16, 32), (1, 1), 64, (2, 2), 0, 1),\n        ((4, 16, 16, 8), (5, 5), 8, 2, (0, 4, 4, 0), 1),\n        ((4, 16, 16, 8), (5, 5), 16, 2, (0, 4, 4, 0), 1),\n        ((4, 16, 16, 8), (5, 5), 8, 2, 0, 1),\n        ((4, 16, 16, 8), (5, 5), 16, 2, 0, 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (0, 0, 1, 1), 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (1, 1, 2, 2), 1),\n        ((1, 16, 16, 8), (5, 5), 16, 2, (3, 3, 2, 2), 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (0, 1, 2, 3), 1),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"int16\"])\ndef test_conv2d(data_shape_nhwc, kernel_size, num_filter, strides, padding, dilation, dtype):\n    \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n    ishape = data_shape_nhwc\n    wshape = (*kernel_size, data_shape_nhwc[-1], num_filter)\n\n    weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n    weight0 = relay.const(weight_data)\n    out0 = relay.op.nn.conv2d(\n        input0,\n        weight0,\n        kernel_size=kernel_size,\n        strides=strides,\n        padding=padding,\n        dilation=(dilation, dilation),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"int32\",\n        out_layout=\"NHWC\",\n    )\n    ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n    input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n    weight1 = relay.const(np.moveaxis(weight_data, 2, -1))\n    out1 = relay.op.nn.conv2d(\n        input1,\n        weight1,\n        kernel_size=kernel_size,\n        strides=strides,\n        padding=padding,\n        dilation=(dilation, dilation),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n        out_layout=\"NHWC\",\n    )\n    mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n    inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n    output_list = generate_ref_data(ref_mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_nwc, kernel_size, num_filter, strides, padding\",\n    [\n        ((1, 32, 12), 3, 16, 1, 0),\n        ((3, 12, 10), 4, 24, 1, 0),\n        ((1, 7, 7), 3, 5, 1, 0),\n        ((1, 10, 2), 4, 4, 2, (1, 1)),\n        ((1, 20, 2), 4, 4, 2, (0, 1)),\n        ((1, 16, 4), 1, 12, 1, (1, 0)),\n        ((1, 24, 16), 1, 32, 3, (2, 2)),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"int16\"])\ndef test_conv1d(data_shape_nwc, kernel_size, num_filter, strides, padding, dtype):\n    \"\"\"Test a subgraph with a single conv1d operator.\"\"\"\n    ishape = data_shape_nwc\n    wshape = (kernel_size, data_shape_nwc[-1], num_filter)\n\n    weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n    weight0 = relay.const(weight_data)\n    out0 = relay.op.nn.conv1d(\n        input0,\n        weight0,\n        strides=strides,\n        padding=padding,\n        data_layout=\"NWC\",\n        kernel_layout=\"WIO\",\n        out_dtype=\"int32\",\n        out_layout=\"NWC\",\n    )\n    ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n    input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n    weight1 = relay.const(np.moveaxis(weight_data, 1, -1))\n    out1 = relay.op.nn.conv1d(\n        input1,\n        weight1,\n        strides=strides,\n        padding=padding,\n        data_layout=\"NWC\",\n        kernel_layout=\"WOI\",\n        out_dtype=\"int32\",\n        out_layout=\"NWC\",\n    )\n    mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n    inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n    output_list = generate_ref_data(ref_mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"dim_m, dim_k, dim_n\",\n    [\n        (1, 32, 64),\n        (3, 12, 10),\n    ],\n)\ndef test_dense(dim_m, dim_k, dim_n):\n    \"\"\"Test a subgraph with a single dense operator.\"\"\"\n    ishape = (dim_m, dim_k)\n    wshape = (dim_n, dim_k)\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, \"int8\"))\n    dense_f = relay.op.nn.batch_flatten(input0)\n    weight0 = relay.const(np.random.randint(low=-10, high=10, size=wshape, dtype=\"int8\"))\n    out = relay.op.nn.dense(dense_f, weight0, out_dtype=\"int32\")\n\n    mod = tvm.IRModule.from_expr(relay.Function([input0], out))\n    inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=\"int8\")}\n    output_list = generate_ref_data(mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_nhwc, pool_size, strides, padding\",\n    [\n        ((1, 32, 32, 1), (3, 3), 1, 0),\n        ((1, 32, 20, 4), (3, 3), (2, 2), 0),\n    ],\n)\ndef test_maxpool_2d(data_shape_nhwc, pool_size, strides, padding):\n    \"\"\"Test a subgraph with a single maxpool_2d operator.\"\"\"\n\n    ishape = data_shape_nhwc\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, \"int8\"))\n    out = relay.op.nn.max_pool2d(input0, pool_size, layout=\"NHWC\", strides=strides, padding=padding)\n\n    mod = tvm.IRModule.from_expr(relay.Function([input0], out))\n    inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=\"int8\")}\n    output_list = generate_ref_data(mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_nwc, pool_size, strides, padding\",\n    [\n        ((1, 32, 1), 3, 1, 0),\n        ((1, 20, 4), 3, 2, 0),\n    ],\n)\ndef test_maxpool_1d(data_shape_nwc, pool_size, strides, padding):\n    \"\"\"Test a subgraph with a single maxpool_1d operator.\"\"\"\n    ishape = data_shape_nwc\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, \"int8\"))\n    out = relay.op.nn.max_pool1d(input0, pool_size, layout=\"NWC\", strides=strides, padding=padding)\n\n    mod = tvm.IRModule.from_expr(relay.Function([input0], out))\n    inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=\"int8\")}\n    output_list = generate_ref_data(mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_nchw, pool_size, strides, padding\",\n    [\n        ((1, 1, 32, 32), (3, 3), 1, 0),\n        ((1, 4, 32, 20), (3, 3), (2, 2), 0),\n    ],\n)\ndef test_avgpool_2d(data_shape_nchw, pool_size, strides, padding):\n    \"\"\"Test a subgraph with a single avgpool_2d operator.\"\"\"\n\n    ishape = data_shape_nchw\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, \"int32\"))\n    out0 = relay.nn.avg_pool2d(input0, pool_size, layout=\"NCHW\", strides=strides, padding=padding)\n    ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n    input1 = relay.var(\"input\", relay.TensorType(ishape, \"int16\"))\n    out1 = relay.op.nn.avg_pool2d(\n        input1, pool_size, layout=\"NCHW\", strides=strides, padding=padding\n    )\n    mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n    input_data = np.random.randint(low=-128, high=127, size=ishape, dtype=\"int32\")\n    inputs = {\"input\": input_data}\n    output_list = generate_ref_data(ref_mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(\n            module=mod, inputs={\"input\": input_data.astype(dtype=\"int16\")}, outputs=output_list\n        ),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\n@tvm.testing.requires_corstone300\n@pytest.mark.parametrize(\n    \"data_shape_ncw, pool_size, strides, padding\",\n    [\n        ((1, 1, 32), 3, 1, 0),\n        ((1, 4, 20), 3, 2, 2),\n    ],\n)\ndef test_avgpool_1d(data_shape_ncw, pool_size, strides, padding):\n    \"\"\"Test a subgraph with a single avgpool_1d operator.\"\"\"\n\n    ishape = data_shape_ncw\n\n    input0 = relay.var(\"input\", relay.TensorType(ishape, \"int32\"))\n    out0 = relay.op.nn.avg_pool1d(input0, pool_size, layout=\"NCW\", strides=strides, padding=padding)\n    ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n    input1 = relay.var(\"input\", relay.TensorType(ishape, \"int16\"))\n    out1 = relay.op.nn.avg_pool1d(input1, pool_size, layout=\"NCW\", strides=strides, padding=padding)\n    mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n    input_data = np.random.randint(low=-10, high=10, size=ishape, dtype=\"int32\")\n    inputs = {\"input\": input_data}\n    output_list = generate_ref_data(ref_mod, inputs)\n\n    compile_and_run(\n        AOTTestModel(\n            module=mod, inputs={\"input\": input_data.astype(dtype=\"int16\")}, outputs=output_list\n        ),\n        runner=AOT_CORSTONE300_RUNNER,\n        interface_api=\"c\",\n        use_unpacked_api=True,\n        target_opts={\n            \"-keys\": \"arm_cpu\",\n            \"-mcpu\": \"cortex-m7\",\n        },\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_auto_tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Integration test for MetaSchedule's auto tensorization.\"\"\"\nimport tempfile\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.meta_schedule.testing import relay_workload\nfrom tvm.meta_schedule.testing.tlcbench import load_quantized_bert_base\nfrom tvm.tir.tensor_intrin.arm_cpu import DP4A_INTRIN\nfrom tvm.tir.tensor_intrin.rocm import AMDGPU_SDOT4_INTRIN\nfrom tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN\n\nSCH_RULES_FOR_VNNI = [\n    ms.schedule_rule.ApplyCustomRule(),\n    ms.schedule_rule.AutoInline(\n        into_producer=False,\n        into_consumer=True,\n        inline_const_tensor=True,\n        disallow_if_then_else=True,\n        require_injective=True,\n        require_ordered=True,\n        disallow_op=[\"tir.exp\"],\n    ),\n    ms.schedule_rule.AddRFactor(max_jobs_per_core=16, max_innermost_factor=64),\n    ms.schedule_rule.MultiLevelTilingWithIntrin(\n        VNNI_INTRIN,\n        structure=\"SSRSRS\",\n        tile_binds=None,\n        max_innermost_factor=64,\n        vector_load_lens=None,\n        reuse_read=None,\n        reuse_write=ms.schedule_rule.ReuseType(\n            req=\"may\",\n            levels=[1, 2],\n            scope=\"global\",\n        ),\n    ),\n    ms.schedule_rule.MultiLevelTiling(\n        structure=\"SSRSRS\",\n        tile_binds=None,\n        max_innermost_factor=64,\n        vector_load_lens=None,\n        reuse_read=None,\n        reuse_write=ms.schedule_rule.ReuseType(\n            req=\"may\",\n            levels=[1, 2],\n            scope=\"global\",\n        ),\n    ),\n    ms.schedule_rule.ParallelizeVectorizeUnroll(\n        max_jobs_per_core=16,\n        max_vectorize_extent=64,\n        unroll_max_steps=[0, 16, 64, 512],\n        unroll_explicit=True,\n    ),\n    ms.schedule_rule.RandomComputeLocation(),\n]\n\n\ndef _get_sch_rules_for_dp4a(intrin):\n    return [\n        ms.schedule_rule.MultiLevelTilingWithIntrin(\n            intrin,\n            structure=\"SSSRRSRS\",\n            tile_binds=[\"blockIdx.x\", \"vthread.x\", \"threadIdx.x\"],\n            max_innermost_factor=64,\n            vector_load_lens=[1, 2, 3, 4],\n            reuse_read=ms.schedule_rule.ReuseType(\n                req=\"must\",\n                levels=[4],\n                scope=\"shared\",\n            ),\n            reuse_write=ms.schedule_rule.ReuseType(\n                req=\"must\",\n                levels=[3],\n                scope=\"local\",\n            ),\n        ),\n        ms.schedule_rule.AutoInline(\n            into_producer=True,\n            into_consumer=True,\n            inline_const_tensor=True,\n            disallow_if_then_else=False,\n            require_injective=False,\n            require_ordered=False,\n            disallow_op=None,\n        ),\n        ms.schedule_rule.CrossThreadReduction(thread_extents=[4, 8, 16, 32, 64, 128, 256, 512]),\n        ms.schedule_rule.ParallelizeVectorizeUnroll(\n            max_jobs_per_core=-1,  # disable parallelize\n            max_vectorize_extent=-1,  # disable vectorize\n            unroll_max_steps=[0, 16, 64, 512, 1024],\n            unroll_explicit=True,\n        ),\n    ]\n\n\nSCH_RULES_FOR_DP4A = _get_sch_rules_for_dp4a(DP4A_INTRIN)\nSCH_RULES_FOR_SDOT4 = _get_sch_rules_for_dp4a(AMDGPU_SDOT4_INTRIN)\n\nPOSTPROCS_FOR_VNNI = [\n    ms.postproc.DisallowDynamicLoop(),\n    ms.postproc.RewriteParallelVectorizeUnroll(),\n    ms.postproc.RewriteReductionBlock(),\n    ms.postproc.RewriteTensorize(vectorize_init_loop=True),\n]\n\nPOSTPROCS_FOR_DP4A = [\n    ms.postproc.DisallowDynamicLoop(),\n    ms.postproc.RewriteCooperativeFetch(),\n    ms.postproc.RewriteUnboundBlock(),\n    ms.postproc.RewriteParallelVectorizeUnroll(),\n    ms.postproc.RewriteReductionBlock(),\n    ms.postproc.RewriteTensorize(),\n    ms.postproc.VerifyGPUCode(),\n]\n\n\ndef tune_and_test(relay_mod, data_np, weight_np, op_name, target, sch_rules, postprocs):\n    \"\"\"Test tuning.\"\"\"\n    tgt = \"cuda\" if \"nvidia\" in target else target\n    dev = tvm.device(tgt, 0)\n    ref = (\n        relay.create_executor(\"vm\", mod=relay_mod, device=dev, target=tgt)\n        .evaluate()(*[data_np, weight_np])\n        .numpy()\n    )\n    params = {\"weight\": weight_np}\n    tune_tasks = list(\n        filter(\n            lambda task: op_name in task.task_name,\n            ms.relay_integration.extract_tasks(relay_mod, target, params),\n        )\n    )\n    with tempfile.TemporaryDirectory() as work_dir:\n        tasks, task_weights = ms.relay_integration.extracted_tasks_to_tune_contexts(\n            extracted_tasks=tune_tasks,\n            work_dir=work_dir,\n            space=ms.space_generator.PostOrderApply(\n                sch_rules=sch_rules,\n                postprocs=postprocs,\n            ),\n        )\n        database = ms.tune.tune_tasks(\n            tasks=tasks,\n            task_weights=task_weights,\n            work_dir=work_dir,\n            max_trials_global=32,\n        )\n    with database, tvm.transform.PassContext(\n        opt_level=3,\n        config={\"relay.backend.use_meta_schedule\": True},\n    ):\n        lib = relay.build(relay_mod, target=target, params=params)\n\n    if \"cascadelake\" in target:\n        asm = lib.lib.get_source(\"asm\")\n        assert \"vpdpbusd\" in asm\n\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n    out = runtime.get_output(0).numpy()\n    np.testing.assert_equal(out, ref)\n\n\ndef _test_dense(data_dtype, sch_rules, postprocs, target):\n    dim_m, dim_n, dim_k = 1024, 1024, 1024\n    data_shape = (dim_m, dim_k)\n    weight_shape = (dim_n, dim_k)\n\n    weight_dtype = \"int8\"\n    out_dtype = \"int32\"\n\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=weight_dtype)\n    dense = relay.nn.dense(data, weight, out_dtype=out_dtype)\n\n    relay_mod = tvm.IRModule.from_expr(dense)\n\n    data_np = np.random.uniform(1, 10, size=data_shape).astype(data_dtype)\n    weight_np = np.random.uniform(1, 10, size=weight_shape).astype(weight_dtype)\n\n    tune_and_test(relay_mod, data_np, weight_np, \"dense\", target, sch_rules, postprocs)\n\n\ndef _test_conv2d(data_dtype, sch_rules, postprocs, target):\n    d_shape = (1, 64, 56, 56)\n    w_shape = (64, 64, 3, 3)\n\n    weight_dtype = \"int8\"\n    out_dtype = \"int32\"\n\n    data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=w_shape, dtype=weight_dtype)\n    out_channel = w_shape[0]\n    conv2d = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=(1, 1),\n        strides=(1, 1),\n        out_dtype=out_dtype,\n    )\n\n    relay_mod = tvm.IRModule.from_expr(conv2d)\n\n    data_np = np.random.uniform(1, 10, d_shape).astype(data_dtype)\n    weight_np = np.random.uniform(1, 10, size=w_shape).astype(\"int8\")\n\n    tune_and_test(relay_mod, data_np, weight_np, \"conv2d\", target, sch_rules, postprocs)\n\n\ndef _test_bert_int8(relay_mod, params, input_info, target, sch_rules, postprocs):\n    relay_mod = relay.transform.FastMath()(relay_mod)\n    tune_tasks = [\n        task\n        for task in ms.relay_integration.extract_tasks(relay_mod, target, params)\n        if \"dense\" in task.task_name or \"batch_matmul\" in task.task_name\n    ]\n    with tempfile.TemporaryDirectory() as work_dir:\n        tasks, task_weights = ms.relay_integration.extracted_tasks_to_tune_contexts(\n            extracted_tasks=tune_tasks,\n            work_dir=work_dir,\n            space=ms.space_generator.PostOrderApply(\n                sch_rules=sch_rules,\n                postprocs=postprocs,\n            ),\n        )\n        database = ms.tune.tune_tasks(\n            tasks=tasks,\n            task_weights=task_weights,\n            work_dir=work_dir,\n            max_trials_per_task=32,\n            max_trials_global=20000,\n        )\n    with database, tvm.transform.PassContext(\n        opt_level=3,\n        config={\"relay.backend.use_meta_schedule\": True},\n    ):\n        lib = relay.build(relay_mod, target=target, params=params)\n\n    dev = tvm.device(\"cuda\" if \"nvidia\" in target else target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    inputs = []\n    for name, shape in input_info:\n        arr = np.random.uniform(1, 10, size=shape).astype(\"int64\")\n        runtime.set_input(name, arr)\n        inputs.append(arr)\n    print(runtime.benchmark(dev, number=1, repeat=50).mean)\n\n\n@tvm.testing.requires_cascadelake\ndef test_vnni_dense():\n    _test_dense(\n        \"uint8\", SCH_RULES_FOR_VNNI, POSTPROCS_FOR_VNNI, \"llvm -mcpu=cascadelake -num-cores 4\"\n    )\n\n\n@pytest.mark.skip(\"Only tested locally on sm_86 (for cuda) which is not supported by CI\")\n@tvm.testing.requires_gpu\ndef test_dp4a_dense():\n    _test_dense(\"int8\", SCH_RULES_FOR_DP4A, POSTPROCS_FOR_DP4A, \"nvidia/geforce-rtx-3070\")\n    # Uncomment to test on vulkan or rocm target\n    # _test_dense(\n    #     \"int8\", SCH_RULES_FOR_DP4A, POSTPROCS_FOR_DP4A, \"vulkan -from_device=0\"\n    # )\n    # _test_dense(\n    #     \"int8\", SCH_RULES_FOR_SDOT4, POSTPROCS_FOR_DP4A, \"rocm\"\n    # )\n\n\n@tvm.testing.requires_cascadelake\ndef test_vnni_conv2d():\n    _test_conv2d(\n        \"uint8\", SCH_RULES_FOR_VNNI, POSTPROCS_FOR_VNNI, \"llvm -mcpu=cascadelake -num-cores 4\"\n    )\n\n\n@pytest.mark.skip(\"Only tested locally on sm_86 (for cuda) which is not supported by CI\")\n@tvm.testing.requires_gpu\ndef test_dp4a_conv2d():\n    _test_conv2d(\"int8\", SCH_RULES_FOR_DP4A, POSTPROCS_FOR_DP4A, \"nvidia/geforce-rtx-3070\")\n    # Uncomment to test on vulkan or rocm target\n    # _test_conv2d(\n    #     \"int8\", SCH_RULES_FOR_DP4A, POSTPROCS_FOR_DP4A, \"vulkan -from_device=0\"\n    # )\n    # _test_conv2d(\n    #     \"int8\", SCH_RULES_FOR_SDOT4, POSTPROCS_FOR_DP4A, \"rocm\"\n    # )\n\n\n@tvm.testing.requires_cascadelake\n@pytest.mark.skip_if(tvm.testing.IS_IN_CI, reason=\"Slow on CI\")\ndef test_vnni_bert_int8():\n    relay_mod, params, input_info = load_quantized_bert_base()\n    _test_bert_int8(\n        relay_mod,\n        params,\n        input_info,\n        \"llvm -mcpu=cascadelake -num-cores 4\",\n        SCH_RULES_FOR_VNNI,\n        POSTPROCS_FOR_VNNI,\n    )\n\n\n@tvm.testing.requires_gpu\n@pytest.mark.skip(\"Slow on CI\")\ndef test_dp4a_bert_int8():\n    relay_mod, params, input_info = load_quantized_bert_base()\n    _test_bert_int8(\n        relay_mod,\n        params,\n        input_info,\n        \"nvidia/geforce-rtx-3070\",\n        SCH_RULES_FOR_DP4A,\n        POSTPROCS_FOR_DP4A,\n    )\n    # Uncomment to test on vulkan or rocm target\n    # _test_bert_int8(\n    #     relay_mod,\n    #     params,\n    #     input_info,\n    #     \"vulkan -from_device=0\",\n    #     SCH_RULES_FOR_DP4A,\n    #     POSTPROCS_FOR_DP4A,\n    # )\n    # _test_bert_int8(\n    #     relay_mod,\n    #     params,\n    #     input_info,\n    #     \"rocm\",\n    #     SCH_RULES_FOR_SDOT4\n    #     POSTPROCS_FOR_DP4A,\n    # )\n\n\n@tvm.testing.requires_gpu\n@pytest.mark.skip(\"Slow on CI\")\n@pytest.mark.parametrize(\n    [\"model_name\", \"input_shape\"],\n    [(\"bert_base\", (8, 128)), (\"resnet_18\", (16, 3, 224, 224)), (\"resnet_50\", (16, 3, 224, 224))],\n)\ndef test_cuda_tensor_core(model_name, input_shape):\n    \"\"\"Integration tests of auto tensorization with CUDA tensor core\"\"\"\n    target = tvm.target.Target(\"nvidia/geforce-rtx-3070\")\n    dev = tvm.cuda()\n    if model_name.startswith(\"bert\"):\n        data = tvm.nd.array(np.random.randint(0, 30521, size=input_shape), dev)  # embedding size\n    else:\n        data = tvm.nd.array(np.random.randn(*input_shape).astype(\"float32\"), dev)\n    mod, params, (input_name, _, _) = relay_workload.get_network(model_name, input_shape)\n    seq = tvm.transform.Sequential(\n        [\n            relay.transform.ToMixedPrecision(),\n        ]\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n\n    def convert_layout(mod):\n        seq = tvm.transform.Sequential(\n            [relay.transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"OHWI\"]})]\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            mod = seq(mod)\n        return mod\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        with ms.Profiler() as profiler:\n            converted_mod = convert_layout(mod)\n            database = ms.relay_integration.tune_relay(\n                mod=converted_mod,\n                target=target,\n                work_dir=work_dir,\n                max_trials_global=3000,\n                params=params,\n            )\n            rt_mod1 = ms.relay_integration.compile_relay(\n                database=database,\n                mod=converted_mod,\n                target=target,\n                params=params,\n            )\n        print(profiler.table())\n\n        # Compile without MetaSchedule for correctness check\n        with tvm.transform.PassContext(opt_level=0):\n            rt_mod2 = relay.build(mod, target=target, params=params)\n\n        def get_output(data, lib):\n            module = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n            module.set_input(input_name, data)\n            module.run()\n            return module.get_output(0).numpy()\n\n        # Check correctness\n        actual_output = get_output(data, rt_mod1)\n        expected_output = get_output(data, rt_mod2)\n        assert np.allclose(actual_output, expected_output, rtol=1e-2, atol=2e-2)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_dot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test scheduling and running a dot product.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\n@tvm.testing.requires_llvm\ndef test_dot():\n    \"\"\"Test dot product.\"\"\"\n    arr_length = 12\n    arr_length_tvm = tvm.runtime.convert(arr_length)\n    placeholder_a = te.placeholder((arr_length_tvm,), name=\"A\")\n    placeholder_b = te.placeholder((arr_length_tvm,), name=\"B\")\n    reduce_axis_k = te.reduce_axis((0, arr_length_tvm), \"k\")\n    result_c = te.compute(\n        (),\n        lambda: te.sum(\n            placeholder_a[reduce_axis_k] * placeholder_b[reduce_axis_k], axis=reduce_axis_k\n        ),\n        name=\"C\",\n    )\n    schedule = te.create_schedule(result_c.op)\n\n    def verify(target):\n        f = tvm.driver.build(schedule, [placeholder_a, placeholder_b, result_c], target)\n        # verify\n        dev = tvm.cpu(0)\n        buff_a = tvm.nd.array(\n            np.random.uniform(size=(arr_length,)).astype(placeholder_a.dtype), dev\n        )\n        buff_b = tvm.nd.array(\n            np.random.uniform(size=(arr_length,)).astype(placeholder_b.dtype), dev\n        )\n        buff_c = tvm.nd.array(np.zeros((), dtype=result_c.dtype), dev)\n        f(buff_a, buff_b, buff_c)\n        tvm.testing.assert_allclose(\n            buff_c.numpy(), np.dot(buff_a.numpy(), buff_b.numpy()), rtol=1e-4\n        )\n\n    verify(\"llvm\")\n\n\nif __name__ == \"__main__\":\n    test_dot()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_ewise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test elementwise integration.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.contrib import nvcc\n\n\n@tvm.testing.requires_gpu\ndef test_exp():\n    \"\"\"Test scheduling and running exponent.\"\"\"\n    # graph\n    arr_length = 1024\n    arr_length_tvm = tvm.runtime.convert(arr_length)\n    placeholder_a = te.placeholder((arr_length_tvm,), name=\"A\")\n    placeholder_b = te.compute(placeholder_a.shape, lambda *i: te.exp(placeholder_a(*i)), name=\"B\")\n    schedule = te.create_schedule(placeholder_b.op)\n    # create iter var and assign them tags.\n    num_thread = 8\n    axis1, axis2 = schedule[placeholder_b].split(placeholder_b.op.axis[0], factor=num_thread)\n    schedule[placeholder_b].bind(axis1, te.thread_axis(\"blockIdx.x\"))\n    schedule[placeholder_b].bind(axis2, te.thread_axis(\"threadIdx.x\"))\n\n    # one line to build the function.\n    def check_device(device, host=\"stackvm\"):\n        if not tvm.testing.device_enabled(host):\n            return\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        fexp = tvm.build(schedule, [placeholder_a, placeholder_b], device, host, name=\"myexp\")\n        dev = tvm.device(device, 0)\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_a.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros(arr_length, dtype=placeholder_b.dtype), dev)\n        fexp(buff_a, buff_b)\n        tvm.testing.assert_allclose(buff_b.numpy(), np.exp(buff_a.numpy()), rtol=1e-5)\n\n    check_device(\"opencl -device=intel_graphics\")\n    check_device(\"cuda\", \"llvm\")\n    check_device(\"vulkan\")\n\n\n@tvm.testing.requires_gpu\ndef test_fmod():\n    \"\"\"Test scheduling and running fmod.\"\"\"\n    # graph\n    def run(dtype):\n        size_var_n = te.size_var(\"n\")\n        placeholder_a = te.placeholder((size_var_n,), name=\"A\", dtype=dtype)\n        placeholder_b = te.placeholder((size_var_n,), name=\"B\", dtype=dtype)\n        result_c = te.compute(\n            placeholder_a.shape, lambda *i: te.fmod(placeholder_a(*i), placeholder_b(*i)), name=\"C\"\n        )\n        schedule = te.create_schedule(result_c.op)\n        # create iter var and assign them tags.\n        num_thread = 8\n        axis0, axis1 = schedule[result_c].split(result_c.op.axis[0], factor=num_thread)\n\n        def check_device(device):\n            dev = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled..\" % device)\n                return\n            target = tvm.target.Target(device)\n            if \"cpu\" not in target.keys:\n                schedule[result_c].bind(axis0, te.thread_axis(\"blockIdx.x\"))\n                schedule[result_c].bind(axis1, te.thread_axis(\"threadIdx.x\"))\n            fmod = tvm.build(\n                schedule, [placeholder_a, placeholder_b, result_c], device, name=\"myfmod\"\n            )\n\n            # launch the kernel.\n            value_n = 1024\n            a_np = (np.random.uniform(size=value_n) * 256).astype(placeholder_a.dtype)\n            b_np = (np.random.uniform(size=value_n) * 256).astype(placeholder_b.dtype)\n\n            # \"fix\" the values in a and b to avoid the result being too small\n            b_np += (b_np < 2.0) * 2\n            a_np[np.abs(np.fmod(a_np, b_np)) < 1] += 1\n\n            buff_a = tvm.nd.array(a_np, dev)\n            buff_b = tvm.nd.array(b_np, dev)\n            buff_c = tvm.nd.array(np.zeros(value_n, dtype=result_c.dtype), dev)\n            ftimer = fmod.time_evaluator(fmod.entry_name, dev, number=1)\n            _ = ftimer(buff_a, buff_b, buff_c).mean\n            np.testing.assert_allclose(\n                buff_c.numpy(), np.mod(buff_a.numpy(), buff_b.numpy()), rtol=1e-5\n            )\n\n        check_device(\"cuda\")\n        check_device(\"opencl -device=intel_graphics\")\n        check_device(\"metal\")\n\n    run(\"float32\")\n\n\n@tvm.testing.requires_gpu\ndef test_multiple_cache_write():\n    \"\"\"Test multiple cache writes.\"\"\"\n    # graph\n    arr_length = 1024\n    arr_length_tvm = tvm.runtime.convert(arr_length)\n    placeholder_a0 = te.placeholder((arr_length_tvm,), name=\"A0\", dtype=\"float32\")\n    placeholder_a1 = te.placeholder((arr_length_tvm,), name=\"A1\", dtype=\"float32\")\n    result_b0, result_b1 = te.compute(\n        (arr_length_tvm,),\n        lambda *i: (\n            placeholder_a0(*i) + placeholder_a1(*i),\n            placeholder_a0(*i) * placeholder_a1(*i),\n        ),\n        name=\"B\",\n    )\n    result_c = te.compute((arr_length_tvm,), lambda *i: result_b0(*i) + result_b1(*i), name=\"C\")\n    schedule = te.create_schedule(result_c.op)\n    # create iter var and assign them tags.\n    num_thread = 8\n    cache_b0, _ = schedule.cache_write([result_b0, result_b1], \"local\")\n    axis0, axis1 = schedule[result_c].split(result_c.op.axis[0], factor=num_thread)\n    schedule[result_b0].compute_at(schedule[result_c], axis0)\n    schedule[cache_b0].compute_at(schedule[result_c], axis0)\n    schedule[result_c].bind(axis0, te.thread_axis(\"blockIdx.x\"))\n    schedule[result_c].bind(axis1, te.thread_axis(\"threadIdx.x\"))\n    # one line to build the function.\n    def check_device(device, host=\"stackvm\"):\n        if not tvm.testing.device_enabled(host):\n            return\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            return\n        func = tvm.build(\n            schedule,\n            [placeholder_a0, placeholder_a1, result_c],\n            device,\n            host,\n            name=\"multiple_cache_write\",\n        )\n        dev = tvm.device(device, 0)\n        # launch the kernel.\n        buff_a0 = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_a0.dtype), dev)\n        buff_a1 = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_a1.dtype), dev)\n        buff_c = tvm.nd.array(np.zeros(arr_length, dtype=result_c.dtype), dev)\n        func(buff_a0, buff_a1, buff_c)\n        tvm.testing.assert_allclose(\n            buff_c.numpy(),\n            buff_a0.numpy() + buff_a1.numpy() + (buff_a0.numpy() * buff_a1.numpy()),\n            rtol=1e-5,\n        )\n\n    check_device(\"cuda\", \"llvm\")\n    check_device(\"vulkan\")\n    check_device(\"opencl\")\n\n\ndef test_log_pow_llvm():\n    \"\"\"Test log pow using llvm to lower.\"\"\"\n    # graph\n    size_var_n = te.size_var(\"n\")\n    placeholder_a = te.placeholder((size_var_n,), name=\"A\")\n    result_b = te.compute(\n        placeholder_a.shape, lambda *i: te.power(te.log(placeholder_a(*i)), 2.0), name=\"B\"\n    )\n    schedule = te.create_schedule(result_b.op)\n    # create iter var and assign them tags.\n    schedule[result_b].split(result_b.op.axis[0], factor=32)\n    # one line to build the function.\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    flog = tvm.build(schedule, [placeholder_a, result_b], \"llvm\", name=\"mylog\")\n    dev = tvm.cpu(0)\n    # launch the kernel.\n    size_var_n = 1028\n    buff_a = tvm.nd.array(np.random.uniform(size=size_var_n).astype(placeholder_a.dtype), dev)\n    buff_b = tvm.nd.array(np.zeros(size_var_n, dtype=result_b.dtype), dev)\n    repeat = 10\n    ftimer = flog.time_evaluator(flog.entry_name, dev, number=1, repeat=repeat)\n    res = ftimer(buff_a, buff_b)\n    assert len(res.results) == repeat\n    tvm.testing.assert_allclose(buff_b.numpy(), np.power(np.log(buff_a.numpy()), 2.0), rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_popcount():\n    \"\"\"Test popcount.\"\"\"\n\n    def run(dtype):\n        # graph\n        arr_length = 1024\n        arr_length_tvm = tvm.runtime.convert(1024)\n        placeholder_a = te.placeholder((arr_length_tvm,), name=\"A\", dtype=dtype)\n        placeholder_b = te.compute(\n            placeholder_a.shape, lambda *i: tvm.tir.popcount(placeholder_a(*i)), name=\"B\"\n        )\n        schedule = te.create_schedule(placeholder_b.op)\n        # simple schedule\n        num_thread = 8\n        axis1, axis2 = schedule[placeholder_b].split(placeholder_b.op.axis[0], factor=num_thread)\n\n        def check_device(device):\n            dev = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled..\" % device)\n                return\n            target = tvm.target.Target(device)\n            if \"cpu\" not in target.keys:\n                schedule[placeholder_b].bind(axis1, te.thread_axis(\"blockIdx.x\"))\n                schedule[placeholder_b].bind(axis2, te.thread_axis(\"threadIdx.x\"))\n            func = tvm.build(schedule, [placeholder_a, placeholder_b], device)\n            # launch the kernel.\n            buff_a = tvm.nd.array(\n                np.random.randint(low=0, high=1000, size=arr_length, dtype=placeholder_a.dtype), dev\n            )\n            buff_b = tvm.nd.array(np.zeros(shape=arr_length, dtype=placeholder_b.dtype), dev)\n            func(buff_a, buff_b)\n            tvm.testing.assert_allclose(\n                buff_b.numpy(), list(map(lambda x: bin(x).count(\"1\"), buff_a.numpy())), rtol=1e-5\n            )\n\n        check_device(\"llvm\")\n        check_device(\"cuda\")\n        check_device(\"opencl\")\n        if dtype == \"uint32\":\n            check_device(\"metal\")\n            check_device(\"vulkan\")\n\n    run(\"uint32\")\n    run(\"uint64\")\n\n\n@tvm.testing.requires_gpu\ndef test_add():\n    \"\"\"Test addition.\"\"\"\n\n    def run(dtype):\n        # graph\n        size_var_n = te.size_var(\"n\")\n        placeholder_a = te.placeholder((size_var_n,), name=\"A\", dtype=dtype)\n        placeholder_b = te.placeholder((size_var_n,), name=\"B\", dtype=dtype)\n        result_c = te.compute(\n            placeholder_a.shape, lambda *i: placeholder_a(*i) + placeholder_b(*i), name=\"C\"\n        )\n        # schedule\n        schedule = te.create_schedule(result_c.op)\n        # create iter var and assign them tags.\n        num_thread = 16\n        axis_bx, axis_x = schedule[result_c].split(result_c.op.axis[0], factor=num_thread * 4)\n        axis_tx, axis_x = schedule[result_c].split(axis_x, nparts=num_thread)\n        _, axis_x = schedule[result_c].split(axis_x, factor=4)\n        schedule[result_c].bind(axis_bx, te.thread_axis(\"blockIdx.x\"))\n        schedule[result_c].bind(axis_tx, te.thread_axis(\"threadIdx.x\"))\n        schedule[result_c].vectorize(axis_x)\n\n        # one line to build the function.\n        def check_device(device):\n            dev = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled..\" % device)\n                return\n            fadd = tvm.build(\n                schedule, [placeholder_a, placeholder_b, result_c], device, name=\"myadd\"\n            )\n\n            # launch the kernel.\n            n = 1024\n            buff_a = tvm.nd.array(\n                (np.random.uniform(size=n) * 256).astype(placeholder_a.dtype), dev\n            )\n            buff_b = tvm.nd.array(\n                (np.random.uniform(size=n) * 256).astype(placeholder_b.dtype), dev\n            )\n            buff_c = tvm.nd.array(np.zeros(n, dtype=result_c.dtype), dev)\n            ftimer = fadd.time_evaluator(fadd.entry_name, dev, number=1)\n            _ = ftimer(buff_a, buff_b, buff_c).mean\n            tvm.testing.assert_allclose(buff_c.numpy(), buff_a.numpy() + buff_b.numpy(), rtol=1e-6)\n\n        check_device(\"opencl\")\n        check_device(\"cuda\")\n        if dtype == \"float32\":\n            check_device(\"metal\")\n            check_device(\"vulkan\")\n\n    run(\"float32\")\n    run(\"int32\")\n    run(\"int64\")\n    run(\"uint64\")\n\n\n@tvm.testing.requires_gpu\ndef try_warp_memory():\n    \"\"\"Test using warp memory\n    skip this in default test because it require higher arch\"\"\"\n    arr_size = 128\n    placeholder_a = te.placeholder((arr_size,), name=\"A\")\n    result_b = te.compute((arr_size,), lambda i: placeholder_a[i] + 3, name=\"B\")\n    warp_size = 32\n    schedule = te.create_schedule(result_b.op)\n    cache_read_aa = schedule.cache_read(placeholder_a, \"warp\", [result_b])\n    axis_x0, axis_xi = schedule[result_b].split(result_b.op.axis[0], warp_size * 2)\n    _, axis_xi1 = schedule[result_b].split(axis_xi, factor=warp_size)\n    thread_axis_tx = te.thread_axis(\"threadIdx.x\")\n    schedule[result_b].bind(axis_xi1, thread_axis_tx)\n    schedule[result_b].bind(axis_x0, te.thread_axis(\"blockIdx.x\"))\n    schedule[cache_read_aa].compute_at(schedule[result_b], axis_x0)\n    axis_x0, axis_xi = schedule[cache_read_aa].split(schedule[cache_read_aa].op.axis[0], warp_size)\n    schedule[cache_read_aa].bind(axis_xi, thread_axis_tx)\n\n    @tvm.register_func(\"tvm_callback_cuda_compile\", override=True)\n    def tvm_callback_cuda_compile(code):  # pylint: disable=unused-variable\n        ptx = nvcc.compile_cuda(code)\n        return ptx\n\n    # one line to build the function.\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        myfunc = tvm.build(schedule, [placeholder_a, result_b], device)\n        buff_a = tvm.nd.array(\n            (np.random.uniform(size=arr_size) * 256).astype(placeholder_a.dtype), dev\n        )\n        buff_b = tvm.nd.array(np.zeros(arr_size, dtype=result_b.dtype), dev)\n        myfunc(buff_a, buff_b)\n        tvm.testing.assert_allclose(buff_b.numpy(), buff_a.numpy() + 3, rtol=1e-6)\n\n    check_device(\"cuda\")\n\n\nif __name__ == \"__main__\":\n    test_exp()\n    try_warp_memory()\n    test_multiple_cache_write()\n    test_add()\n    test_log_pow_llvm()\n    test_popcount()\n    test_fmod()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_ewise_fpga.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test elementwise ops on fpga.\"\"\"\nimport os\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\nos.environ[\"XCL_EMULATION_MODE\"] = \"1\"\nos.environ[\"CL_CONTEXT_EMULATOR_DEVICE_INTELFPGA\"] = \"1\"\n\n\n@tvm.register_func\ndef tvm_callback_vhls_postproc(code):\n    \"\"\"Hook to inspect the Vivado HLS code before actually run it\"\"\"\n    print(code)\n    return code\n\n\ndef test_exp():\n    \"\"\"Test scheduling and running exp function.\"\"\"\n    # graph\n    arr_length = 1024\n    arr_length_tvm = tvm.runtime.convert(arr_length)\n    placeholder_b = te.placeholder((arr_length_tvm,), name=\"A\")\n    result_b = te.compute(placeholder_b.shape, lambda *i: te.exp(placeholder_b(*i)), name=\"B\")\n    schedule = te.create_schedule(result_b.op)\n    # create iter var and assign them tags.\n    axis1, _ = schedule[result_b].split(result_b.op.axis[0], nparts=1)\n    schedule[result_b].bind(axis1, te.thread_axis(\"pipeline\"))\n\n    # one line to build the function.\n    def check_device(device, host=\"llvm\"):\n        if not tvm.testing.device_enabled(device):\n            return\n        dev = tvm.device(device, 0)\n        fexp = tvm.build(schedule, [placeholder_b, result_b], device, host, name=\"myexp\")\n        dev = tvm.device(device, 0)\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_b.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros(arr_length, dtype=result_b.dtype), dev)\n        fexp(buff_a, buff_b)\n        tvm.testing.assert_allclose(buff_b.numpy(), np.exp(buff_a.numpy()), rtol=1e-5)\n\n    check_device(\"sdaccel\")\n    if \"AWS_PLATFORM\" in os.environ:\n        check_device(\"sdaccel -device=\" + os.environ.get(\"AWS_PLATFORM\"))\n\n    check_device(\"aocl_sw_emu\")\n\n\ndef test_multi_kernel():\n    \"\"\"Test scheduling with multiple computes.\"\"\"\n    # graph\n    arr_length = 1024\n    arr_length_tvm = tvm.runtime.convert(arr_length)\n    placeholder_a = te.placeholder((arr_length_tvm,), name=\"A\")\n    placeholder_b = te.placeholder((arr_length_tvm,), name=\"B\")\n    result_c = te.compute(\n        placeholder_a.shape, lambda *i: placeholder_a(*i) + placeholder_b(*i), name=\"C\"\n    )\n    result_d = te.compute(\n        placeholder_a.shape, lambda *i: placeholder_a(*i) + result_c(*i), name=\"D\"\n    )\n    schedule = te.create_schedule(result_d.op)\n    # create iter var and assign them tags.\n    axis1, _ = schedule[result_c].split(result_c.op.axis[0], nparts=1)\n    schedule[result_c].bind(axis1, te.thread_axis(\"pipeline\"))\n    axis1, _ = schedule[result_d].split(result_d.op.axis[0], nparts=1)\n    schedule[result_d].bind(axis1, te.thread_axis(\"pipeline\"))\n\n    # one line to build the function.\n    def check_device(device, host=\"llvm\"):\n        if not tvm.testing.device_enabled(device):\n            return\n        dev = tvm.device(device, 0)\n        fadd = tvm.build(\n            schedule, [placeholder_a, placeholder_b, result_c, result_d], device, host, name=\"myadd\"\n        )\n        dev = tvm.device(device, 0)\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_a.dtype), dev)\n        buff_b = tvm.nd.array(np.random.uniform(size=arr_length).astype(placeholder_b.dtype), dev)\n        buff_c = tvm.nd.array(np.random.uniform(size=arr_length).astype(result_c.dtype), dev)\n        buff_d = tvm.nd.array(np.random.uniform(size=arr_length).astype(result_d.dtype), dev)\n        fadd(buff_a, buff_b, buff_c, buff_d)\n        tvm.testing.assert_allclose(buff_d.numpy(), buff_a.numpy() * 2 + buff_b.numpy(), rtol=1e-5)\n\n    check_device(\"sdaccel\")\n    check_device(\"aocl_sw_emu\")\n\n\nif __name__ == \"__main__\":\n    test_exp()\n    test_multi_kernel()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test scheduling and running a gemm!\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\n@tvm.testing.requires_gpu\ndef test_gemm():\n    \"\"\"Test the gemm!\"\"\"\n    # graph\n    dim1_length = 1024\n    dim_n = tvm.runtime.convert(dim1_length)\n    dim_m = dim_n\n    dim_l = dim_n\n    placeholder_a = te.placeholder((dim_n, dim_l), name=\"A\")\n    placeholder_b = te.placeholder((dim_m, dim_l), name=\"B\")\n    axis_k = te.reduce_axis((0, dim_l), name=\"k\")\n    result_c = te.compute(\n        (dim_n, dim_m),\n        lambda ii, jj: te.sum(placeholder_a[ii, axis_k] * placeholder_b[jj, axis_k], axis=axis_k),\n        name=\"CC\",\n    )\n    # schedule\n    schedule = te.create_schedule(result_c.op)\n    scale = 8\n    num_thread = 8\n    block_factor = scale * num_thread\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n\n    cache_write = schedule.cache_write(result_c, \"local\")\n    cache_read_a = schedule.cache_read(placeholder_a, \"shared\", [cache_write])\n    cache_read_b = schedule.cache_read(placeholder_b, \"shared\", [cache_write])\n    axis_by, axis_yi = schedule[result_c].split(result_c.op.axis[0], factor=block_factor)\n    axis_bx, axis_xi = schedule[result_c].split(result_c.op.axis[1], factor=block_factor)\n    schedule[result_c].reorder(axis_by, axis_bx, axis_yi, axis_xi)\n    schedule[result_c].bind(axis_by, block_y)\n    schedule[result_c].bind(axis_bx, block_x)\n    axis_ty, axis_yi = schedule[result_c].split(axis_yi, nparts=num_thread)\n    axis_tx, axis_xi = schedule[result_c].split(axis_xi, nparts=num_thread)\n    schedule[result_c].reorder(axis_ty, axis_tx, axis_yi, axis_xi)\n    schedule[result_c].bind(axis_ty, thread_y)\n    schedule[result_c].bind(axis_tx, thread_x)\n    axis_yo, axis_xo = cache_write.op.axis\n    schedule[cache_write].reorder(axis_k, axis_yo, axis_xo)\n\n    schedule[cache_write].compute_at(schedule[result_c], axis_tx)\n    schedule[cache_read_a].compute_at(schedule[cache_write], axis_k)\n    schedule[cache_read_b].compute_at(schedule[cache_write], axis_k)\n    schedule[cache_read_a].double_buffer()\n    schedule[cache_read_b].double_buffer()\n    axis_ty, axis_xi = schedule[cache_read_a].split(\n        schedule[cache_read_a].op.axis[0], nparts=num_thread\n    )\n    axis_tx, axis_xi = schedule[cache_read_a].split(axis_xi, nparts=num_thread)\n    schedule[cache_read_a].bind(axis_ty, thread_y)\n    schedule[cache_read_a].bind(axis_tx, thread_x)\n\n    axis_ty, axis_xi = schedule[cache_read_b].split(\n        schedule[cache_read_b].op.axis[0], nparts=num_thread\n    )\n    axis_tx, axis_xi = schedule[cache_read_b].split(axis_xi, nparts=num_thread)\n    schedule[cache_read_b].bind(axis_ty, thread_y)\n    schedule[cache_read_b].bind(axis_tx, thread_x)\n\n    # lowering test\n    schedule = schedule.normalize()\n\n    # one line to build the function.\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n\n        with tvm.target.Target(device):\n            f = tvm.build(schedule, [placeholder_a, placeholder_b, result_c])\n\n        # launch the kernel.\n        num_n = dim1_length\n        num_m = num_n\n        num_l = num_n\n        a_np = np.random.uniform(size=(num_n, num_l)).astype(placeholder_a.dtype)\n        b_np = np.random.uniform(size=(num_m, num_l)).astype(placeholder_b.dtype)\n        buff_a = tvm.nd.array(a_np, dev)\n        buff_b = tvm.nd.array(b_np, dev)\n        buff_c = tvm.nd.array(np.zeros((num_n, num_m), dtype=result_c.dtype), dev)\n        ftimer = f.time_evaluator(f.entry_name, dev, number=1)\n        tcost = ftimer(buff_a, buff_b, buff_c).mean\n        print(\"%s: exec=%g sec/op\" % (dev, tcost))\n        tvm.testing.assert_allclose(buff_c.numpy(), np.dot(a_np, b_np.T), rtol=1e-5)\n\n    check_device(\"vulkan\")\n    check_device(\"nvptx -mcpu=sm_20\")\n    check_device(\"rocm\")\n    check_device(\"metal\")\n    check_device(\"opencl\")\n    check_device(\"cuda\")\n\n\nif __name__ == \"__main__\":\n    test_gemm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_legacy_tuning.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTest the tuner\n\"\"\"\nimport logging\nimport multiprocessing as mp\nimport textwrap\n\nimport tvm\nimport tvm.relay\nimport tvm.testing\nfrom tvm import autotvm, te\nfrom tvm.autotvm.measure import measure_methods\nfrom tvm.autotvm.tuner import RandomTuner\nfrom tvm.contrib import tar\nfrom tvm.ir.instrument import pass_instrument\nfrom tvm.ir.transform import PassContext\nfrom tvm.target import Target\nfrom tvm.tir.analysis import _ffi_api as _analysis_ffi_api\n\n\ndef setup_module():\n    \"\"\"Setup the module used for testing.\"\"\"\n\n    @autotvm.template(\"testing/conv2d_no_batching\")\n    def conv2d_no_batching(  # pylint: disable=unused-variable\n        batch_size, input_h, input_w, channels_in, channels_out, kernel_h, kernel_w\n    ):\n        \"\"\"An example template for testing\"\"\"\n        assert batch_size == 1, \"Only consider batch_size = 1 in this template\"\n\n        data = te.placeholder((batch_size, channels_in, input_h, input_w), name=\"data\")\n        kernel = te.placeholder((channels_out, channels_in, kernel_h, kernel_w), name=\"kernel\")\n\n        axis_rc = te.reduce_axis((0, channels_in), name=\"rc\")\n        axis_ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n        axis_rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n        conv = te.compute(\n            (batch_size, channels_out, input_h - kernel_h + 1, input_w - kernel_w + 1),\n            lambda nn, ff, yy, xx: te.sum(\n                data[nn, axis_rc, yy + axis_ry, xx + axis_rx]\n                * kernel[ff, axis_rc, axis_ry, axis_rx],\n                axis=[axis_rc, axis_ry, axis_rx],\n            ),\n            tag=\"conv2d_nchw\",\n        )\n\n        schedule = te.create_schedule([conv.op])\n\n        output = conv\n        cache_write_ol = schedule.cache_write(conv, \"local\")\n\n        # create cache stage\n        cache_read_aa = schedule.cache_read(data, \"shared\", [cache_write_ol])\n        cache_read_ww = schedule.cache_read(kernel, \"shared\", [cache_write_ol])\n        cache_read_al = schedule.cache_read(cache_read_aa, \"local\", [cache_write_ol])\n        cache_read_wl = schedule.cache_read(cache_read_ww, \"local\", [cache_write_ol])\n\n        # tile and bind spatial axes\n        axis_n, axis_f, axis_y, axis_x = schedule[output].op.axis\n        cfg = autotvm.get_config()\n        cfg.define_split(\"tile_f\", cfg.axis(axis_f), num_outputs=4)\n        cfg.define_split(\"tile_y\", cfg.axis(axis_y), num_outputs=4)\n        cfg.define_split(\"tile_x\", cfg.axis(axis_x), num_outputs=4)\n        axis_bf, axis_vf, axis_tf, axis_fi = cfg[\"tile_f\"].apply(schedule, output, axis_f)\n        axis_by, axis_vy, axis_ty, axis_yi = cfg[\"tile_y\"].apply(schedule, output, axis_y)\n        axis_bx, axis_vx, axis_tx, axis_xi = cfg[\"tile_x\"].apply(schedule, output, axis_x)\n        kernel_scope = axis_n  # this is the scope to attach global config inside this kernel\n\n        schedule[output].bind(axis_bf, te.thread_axis(\"blockIdx.z\"))\n        schedule[output].bind(axis_by, te.thread_axis(\"blockIdx.y\"))\n        schedule[output].bind(axis_bx, te.thread_axis(\"blockIdx.x\"))\n        schedule[output].bind(axis_vf, te.thread_axis(\"vthread\"))\n        schedule[output].bind(axis_vy, te.thread_axis(\"vthread\"))\n        schedule[output].bind(axis_vx, te.thread_axis(\"vthread\"))\n        schedule[output].bind(axis_tf, te.thread_axis(\"threadIdx.z\"))\n        schedule[output].bind(axis_ty, te.thread_axis(\"threadIdx.y\"))\n        schedule[output].bind(axis_tx, te.thread_axis(\"threadIdx.x\"))\n        schedule[output].reorder(\n            axis_n,\n            axis_bf,\n            axis_by,\n            axis_bx,\n            axis_vf,\n            axis_vy,\n            axis_vx,\n            axis_tf,\n            axis_ty,\n            axis_tx,\n            axis_fi,\n            axis_yi,\n            axis_xi,\n        )\n        schedule[cache_write_ol].compute_at(schedule[output], axis_tx)\n\n        # tile and bind reduction axes\n        axis_n, axis_f, axis_y, axis_x = schedule[cache_write_ol].op.axis\n        axis_rc, axis_ry, axis_rx = schedule[cache_write_ol].op.reduce_axis\n        cfg.define_split(\"tile_rc\", cfg.axis(axis_rc), num_outputs=3)\n        cfg.define_split(\"tile_ry\", cfg.axis(axis_ry), num_outputs=3)\n        cfg.define_split(\"tile_rx\", cfg.axis(axis_rx), num_outputs=3)\n        axis_rco, axis_rcm, axis_rci = cfg[\"tile_rc\"].apply(schedule, cache_write_ol, axis_rc)\n        axis_ryo, axis_rym, axis_ryi = cfg[\"tile_rx\"].apply(schedule, cache_write_ol, axis_ry)\n        axis_rxo, axis_rxm, axis_rxi = cfg[\"tile_ry\"].apply(schedule, cache_write_ol, axis_rx)\n        schedule[cache_write_ol].reorder(\n            axis_rco,\n            axis_ryo,\n            axis_rxo,\n            axis_rcm,\n            axis_rym,\n            axis_rxm,\n            axis_rci,\n            axis_ryi,\n            axis_rxi,\n            axis_n,\n            axis_f,\n            axis_y,\n            axis_x,\n        )\n\n        schedule[cache_read_aa].compute_at(schedule[cache_write_ol], axis_rxo)\n        schedule[cache_read_ww].compute_at(schedule[cache_write_ol], axis_rxo)\n        schedule[cache_read_al].compute_at(schedule[cache_write_ol], axis_rxm)\n        schedule[cache_read_wl].compute_at(schedule[cache_write_ol], axis_rxm)\n\n        # cooperative fetching\n        for load in [cache_read_aa, cache_read_ww]:\n            axis_n, axis_f, axis_y, axis_x = schedule[load].op.axis\n            fused = schedule[load].fuse(axis_n, axis_f, axis_y, axis_x)\n            axis_tz, fused = schedule[load].split(fused, nparts=cfg[\"tile_f\"].size[2])\n            axis_ty, fused = schedule[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n            axis_tx, fused = schedule[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n            schedule[load].bind(axis_tz, te.thread_axis(\"threadIdx.z\"))\n            schedule[load].bind(axis_ty, te.thread_axis(\"threadIdx.y\"))\n            schedule[load].bind(axis_tx, te.thread_axis(\"threadIdx.x\"))\n\n        # tune unroll\n        cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n        cfg.define_knob(\"unroll_explicit\", [0, 1])\n        schedule[output].pragma(\n            kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val\n        )\n        schedule[output].pragma(kernel_scope, \"unroll_explicit\", cfg[\"unroll_explicit\"].val)\n\n        return schedule, [data, kernel, conv]\n\n\ndef teardown_module():\n    \"\"\"Remove the module from the autotvm task tables.\"\"\"\n    # TODO(areusch): Tasks should not be registered into a global.\n    del autotvm.task.task.TASK_TABLE[\"testing/conv2d_no_batching\"]\n\n\ndef get_sample_task(target=tvm.target.cuda(), target_host=None):\n    \"\"\"return a sample task for testing\"\"\"\n    target, target_host = Target.canon_target_and_host(target, target_host)\n    task = autotvm.task.create(\n        \"testing/conv2d_no_batching\", args=(1, 7, 7, 512, 512, 3, 3), target=target\n    )\n    return task, target\n\n\ndef run_test_with_all_multiprocessing(func, *args, **kwargs):\n    \"\"\"Check all multiprocessing methods work for the tuning test.\n\n    In the past fork() had the most support at detriment to spawn() and forkserver().\n    As fork() is unavailable or unsafe on some platforms it is good to check all\n    available methods.\n    \"\"\"\n    for multiprocessing_method in mp.get_all_start_methods():\n        old_start_method = mp.get_start_method()\n        try:\n            mp.set_start_method(multiprocessing_method, force=True)\n            func(*args, **kwargs)\n        finally:\n            mp.set_start_method(old_start_method, force=True)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"opencl\")\ndef test_tuning_gpu(target):\n    \"\"\"Test gpu tuning.\"\"\"\n\n    def runner(target):\n        # init task\n        task, target = get_sample_task(target, None)\n        logging.info(\"task config space: %s\", task.config_space)\n\n        measure_option = autotvm.measure_option(autotvm.LocalBuilder(), autotvm.LocalRunner())\n\n        results = []\n\n        tuner = RandomTuner(task)\n        tuner.tune(\n            n_trial=20,\n            measure_option=measure_option,\n            callbacks=(lambda _tuner, _inputs, rs: results.extend(rs),),\n        )\n\n        assert len(results) == 20\n\n        successful_results = [\n            r\n            for r in results\n            if r.error_no == autotvm.MeasureErrorNo.NO_ERROR\n            # We filter records before building if we know they won't work ahead of time.\n            # We can't guarantee we get one good record so we count these as success too\n            or r.error_no == autotvm.MeasureErrorNo.INSTANTIATION_ERROR\n        ]\n        assert len(successful_results) > 0, f\"No successful tuning runs: {results!r}\"\n\n    run_test_with_all_multiprocessing(runner, target)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"opencl\")\ndef test_tuning_gpu_inherits_pass_context(target):\n    \"\"\"Autotvm tuner inherits PassContexts but also adds a gpu verification pass by default.\n\n    Test that using PassContext inherits passes properly but also runs gpu verification pass.\n    \"\"\"\n\n    @pass_instrument\n    class PassInstrumentChecker:\n        \"\"\"Pass Instrument that simply sees if it's been run.\"\"\"\n\n        def __init__(self):\n            self.has_been_run = False\n\n        def run_after_pass(self, *_):\n            self.has_been_run = True\n\n    class GPUVerifyPassMocked:\n        \"\"\"Context manager that mocks tir.analysis.verify_gpu_code meant\n        to verify the pass has been run. This is done by patching the ffi func handles.\"\"\"\n\n        FFI_FUNC_HANDLE = \"tir.analysis.verify_gpu_code\"\n        FUNC_NAME = \"verify_gpu_code\"\n\n        def __init__(self) -> None:\n            self.old_impl = tvm._ffi.get_global_func(self.FFI_FUNC_HANDLE)\n            self.has_been_run = False\n\n        def gpu_verify_pass_mocked(self):\n            \"\"\"Get the replacement for the gpu verification pass.\"\"\"\n\n            def _gpu_verify_pass_mocked(*args, **kwargs):\n                self.has_been_run = True\n                return self.old_impl(*args, **kwargs)\n\n            return _gpu_verify_pass_mocked\n\n        def __enter__(self):\n            tvm._ffi.register_func(\n                self.FFI_FUNC_HANDLE, self.gpu_verify_pass_mocked(), override=True\n            )\n\n            # Also overwrite the python bindings\n            setattr(\n                _analysis_ffi_api, self.FUNC_NAME, tvm._ffi.get_global_func(self.FFI_FUNC_HANDLE)\n            )\n\n        def __exit__(self, *args, **kwargs):\n            # Restore FFI status back to normal\n            tvm._ffi.register_func(self.FFI_FUNC_HANDLE, self.old_impl, override=True)\n            setattr(_analysis_ffi_api, self.FUNC_NAME, self.old_impl)\n\n    class OverwrittenBuildFunc(measure_methods._WrappedBuildFunc):\n        \"\"\"BuildFunc that mocks and patches as necessary to test proper passes are run.\"\"\"\n\n        def __call__(self, measure_input, tmp_dir, **kwargs):\n            instrument = PassInstrumentChecker()\n            mocked_pass_checker = GPUVerifyPassMocked()\n            with mocked_pass_checker:\n                with PassContext(instruments=[instrument]):\n                    regular_result = super().__call__(measure_input, tmp_dir, **kwargs)\n\n                    # Check instrument has been run, meaning context was inherited by builder\n                    assert instrument.has_been_run\n\n                    # But also check the gpu verification pass has been run\n                    # (which was not in the inherited ctx)\n                    assert mocked_pass_checker.has_been_run\n\n                    return regular_result\n\n    class MockedLocalBuilder(measure_methods.LocalBuilder):\n        \"\"\"As measure_methods.LocalBuilder but overwrites the PassContext for testing.\"\"\"\n\n        def __init__(\n            self,\n            timeout=10,\n            n_parallel=None,\n            build_kwargs=None,\n            build_func=\"default\",\n            do_fork=False,\n            runtime=None,\n        ):\n            # pylint: disable=too-many-function-args\n            super().__init__(timeout, n_parallel, build_kwargs, build_func, do_fork, runtime)\n\n            self.build_func = OverwrittenBuildFunc(tar.tar, runtime)\n\n    def runner(target):\n        task, target = get_sample_task(target, None)\n        logging.info(\"task config space: %s\", task.config_space)\n\n        # Note: we use the MockedLocalBuilder here instead of autotvm.LocalBuilder()\n        measure_option = autotvm.measure_option(MockedLocalBuilder(), autotvm.LocalRunner())\n\n        results = []\n\n        tuner = RandomTuner(task)\n        tuner.tune(\n            n_trial=1,\n            measure_option=measure_option,\n            callbacks=(lambda _tuner, _inputs, rs: results.extend(rs),),\n        )\n\n        assert len(results) == 1\n\n    run_test_with_all_multiprocessing(runner, target)\n\n\ndef test_tuning_cpu():\n    \"\"\"Test tuning on cpu.\"\"\"\n\n    def runner():\n        ir_mod = tvm.parser.fromtext(\n            textwrap.dedent(\n                \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a : Tensor[(1, 3, 32, 32), float32], %b : Tensor[(3, 3, 5, 5), float32]) {\n                nn.conv2d(%a, %b, data_layout=\"NCHW\", kernel_layout=\"OIHW\")\n            }\n            \"\"\"\n            )\n        )\n        tasks = autotvm.task.relay_integration.extract_from_program(\n            ir_mod, {}, tvm.target.create(\"llvm\")\n        )\n        assert len(tasks) == 1, f\"Extracted != 1 task from program: {tasks!r}\"\n\n        task = tasks[0]\n\n        measure_option = autotvm.measure_option(autotvm.LocalBuilder(), autotvm.LocalRunner())\n\n        results = []\n\n        tuner = RandomTuner(task)\n        tuner.tune(\n            n_trial=20,\n            measure_option=measure_option,\n            callbacks=(lambda _tuner, _inputs, rs: results.extend(rs),),\n        )\n\n        assert len(results) == 20\n\n        successful_results = [r for r in results if r.error_no == autotvm.MeasureErrorNo.NO_ERROR]\n        assert len(successful_results) > 0, f\"No successful tuning runs: {results!r}\"\n\n    run_test_with_all_multiprocessing(runner)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_lower.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test workload for lowering and build.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef tensorcore_gemm(handle_a: T.handle, handle_b: T.handle, handle_c: T.handle) -> None:\n    # pylint: disable=missing-function-docstring\n    # match buffer\n    match_buffer_a = T.match_buffer(handle_a, [1024, 1024], \"float16\")\n    match_buffer_b = T.match_buffer(handle_b, [1024, 1024], \"float16\")\n    match_buffer_c = T.match_buffer(handle_c, [1024, 1024], \"float32\")\n\n    # body\n    for block_idx_x in T.thread_binding(0, 16, \"blockIdx.x\"):\n        for block_idx_y in T.thread_binding(0, 8, \"blockIdx.y\"):\n            with T.block():\n                axis_bx, axis_by = T.axis.remap(\"SS\", [block_idx_x, block_idx_y])\n                shared_a = T.alloc_buffer([1024, 1024], \"float16\", scope=\"shared\")\n                shared_b = T.alloc_buffer([1024, 1024], \"float16\", scope=\"shared\")\n                wmma_a = T.alloc_buffer([1024, 1024], \"float16\", scope=\"wmma.matrix_a\")\n                wmma_b = T.alloc_buffer([1024, 1024], \"float16\", scope=\"wmma.matrix_b\")\n                wmma_c = T.alloc_buffer([1024, 1024], \"float32\", scope=\"wmma.accumulator\")\n\n                # pylint: disable=too-many-nested-blocks\n                for thread_ty in T.thread_binding(0, 2, \"threadIdx.y\"):\n                    for thread_tz in T.thread_binding(0, 2, \"threadIdx.z\"):\n                        for index_i, index_jj in T.grid(2, 4):\n                            with T.block():\n                                new_axis_vi = T.axis.S(64, axis_bx * 4 + thread_ty * 2 + index_i)\n                                new_axis_vj = T.axis.S(64, axis_by * 8 + thread_tz * 4 + index_jj)\n                                T.reads([])\n                                T.writes(\n                                    wmma_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ]\n                                )\n                                match_buffer_c0 = T.match_buffer(\n                                    wmma_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ],\n                                    (16, 16),\n                                    \"float32\",\n                                    strides=[16 * 4, 1],\n                                    scope=\"wmma.accumulator\",\n                                    offset_factor=1,\n                                )\n                                T.evaluate(\n                                    T.tvm_fill_fragment(\n                                        match_buffer_c0.data,\n                                        16,\n                                        16,\n                                        16,\n                                        index_i * 4 + index_jj,\n                                        T.float32(0),  # pylint: disable=not-callable\n                                        dtype=\"handle\",\n                                    )\n                                )\n\n                        for k_o in range(0, 32):\n                            # copy data from global to shared\n                            for thread_tx in T.thread_binding(0, 32, \"threadIdx.x\"):\n                                for index_i0, index_j0 in T.grid(1, 4):\n                                    for index_j1 in T.vectorized(0, 4):\n                                        with T.block():\n                                            new_axis_vi = T.axis.S(\n                                                1024,\n                                                axis_bx * 64\n                                                + thread_ty * 32\n                                                + thread_tx\n                                                + index_i0,\n                                            )\n                                            new_axis_vj = T.axis.S(\n                                                1024,\n                                                k_o * 32 + thread_tz * 16 + index_j0 * 4 + index_j1,\n                                            )\n                                            shared_a[new_axis_vi, new_axis_vj + 8] = match_buffer_a[\n                                                new_axis_vi, new_axis_vj\n                                            ]\n\n                                for index_i0, index_j0 in T.grid(2, 4):\n                                    for index_j1 in T.vectorized(0, 4):\n                                        with T.block():\n                                            new_axis_vi = T.axis.S(\n                                                1024,\n                                                axis_by * 128\n                                                + thread_ty * 64\n                                                + thread_tx * 2\n                                                + index_i0,\n                                            )\n                                            new_axis_vj = T.axis.S(\n                                                1024,\n                                                k_o * 32 + thread_tz * 16 + index_j0 * 4 + index_j1,\n                                            )\n                                            shared_b[new_axis_vi, new_axis_vj + 8] = match_buffer_b[\n                                                new_axis_vi, new_axis_vj\n                                            ]\n\n                            for k_i in range(0, 2):\n                                for index_i in range(0, 2):\n                                    with T.block():\n                                        new_axis_vi = T.axis.S(\n                                            64, axis_bx * 4 + thread_ty * 2 + index_i\n                                        )\n                                        axis_vk = T.axis.S(64, k_o * 2 + k_i)\n                                        T.reads(\n                                            shared_a[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16 + 8,\n                                            ]\n                                        )\n                                        T.writes(\n                                            wmma_a[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ]\n                                        )\n                                        stride0 = T.var(\"int32\")\n                                        stride1 = T.var(\"int32\")\n                                        match_buffer_a0 = T.match_buffer(\n                                            shared_a[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16 + 8,\n                                            ],\n                                            (16, 16 + 8),\n                                            \"float16\",\n                                            strides=[stride0, stride1],\n                                            scope=\"shared\",\n                                            offset_factor=1,\n                                        )\n                                        wmma_a0 = T.match_buffer(\n                                            wmma_a[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ],\n                                            (16, 16),\n                                            \"float16\",\n                                            strides=[16, 1],\n                                            scope=\"wmma.matrix_a\",\n                                            offset_factor=1,\n                                        )\n                                        T.evaluate(\n                                            T.tvm_load_matrix_sync(\n                                                wmma_a0.data,\n                                                16,\n                                                16,\n                                                16,\n                                                index_i,\n                                                T.tvm_access_ptr(\n                                                    T.type_annotation(dtype=\"float16\"),\n                                                    match_buffer_a0.data,\n                                                    match_buffer_a0.elem_offset + 8,\n                                                    match_buffer_a0.strides[0],\n                                                    1,\n                                                    dtype=\"handle\",\n                                                ),\n                                                match_buffer_a0.strides[0],\n                                                \"row_major\",\n                                                dtype=\"handle\",\n                                            )\n                                        )\n                                for index_jj in range(0, 4):\n                                    with T.block():\n                                        new_axis_vj = T.axis.S(\n                                            64, axis_by * 8 + thread_tz * 4 + index_jj\n                                        )\n                                        axis_vk = T.axis.S(64, k_o * 2 + k_i)\n                                        T.reads(\n                                            shared_b[\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16 + 8,\n                                            ]\n                                        )\n                                        T.writes(\n                                            wmma_b[\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ]\n                                        )\n                                        stride0 = T.var(\"int32\")\n                                        stride1 = T.var(\"int32\")\n                                        match_buffer_b0 = T.match_buffer(\n                                            shared_b[\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16 + 8,\n                                            ],\n                                            (16, 16 + 8),\n                                            \"float16\",\n                                            strides=[stride0, stride1],\n                                            scope=\"shared\",\n                                            offset_factor=1,\n                                        )\n                                        wmma_b0 = T.match_buffer(\n                                            wmma_b[\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ],\n                                            (16, 16),\n                                            \"float16\",\n                                            strides=[16, 1],\n                                            scope=\"wmma.matrix_b\",\n                                            offset_factor=1,\n                                        )\n                                        T.evaluate(\n                                            T.tvm_load_matrix_sync(\n                                                wmma_b0.data,\n                                                16,\n                                                16,\n                                                16,\n                                                index_jj,\n                                                T.tvm_access_ptr(\n                                                    T.type_annotation(dtype=\"float16\"),\n                                                    match_buffer_b0.data,\n                                                    match_buffer_b0.elem_offset + 8,\n                                                    match_buffer_b0.strides[0],\n                                                    1,\n                                                    dtype=\"handle\",\n                                                ),\n                                                match_buffer_b0.strides[0],\n                                                \"col_major\",\n                                                dtype=\"handle\",\n                                            )\n                                        )\n                                for index_i, index_jj in T.grid(2, 4):\n                                    with T.block():\n                                        new_axis_vi = T.axis.S(\n                                            64, axis_bx * 4 + thread_ty * 2 + index_i\n                                        )\n                                        new_axis_vj = T.axis.S(\n                                            64, axis_by * 8 + thread_tz * 4 + index_jj\n                                        )\n                                        axis_vk = T.axis.R(64, k_o * 2 + k_i)\n                                        T.reads(\n                                            [\n                                                wmma_a[\n                                                    new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                    axis_vk * 16 : axis_vk * 16 + 16,\n                                                ],\n                                                wmma_b[\n                                                    new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                    axis_vk * 16 : axis_vk * 16 + 16,\n                                                ],\n                                                wmma_c[\n                                                    new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                    new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                ],\n                                            ]\n                                        )\n                                        T.writes(\n                                            wmma_c[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                            ]\n                                        )\n                                        wmma_a1 = T.match_buffer(\n                                            wmma_a[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ],\n                                            (16, 16),\n                                            \"float16\",\n                                            strides=[16, 1],\n                                            scope=\"wmma.matrix_a\",\n                                            offset_factor=1,\n                                        )\n                                        wmma_b1 = T.match_buffer(\n                                            wmma_b[\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                                axis_vk * 16 : axis_vk * 16 + 16,\n                                            ],\n                                            (16, 16),\n                                            \"float16\",\n                                            strides=[16, 1],\n                                            scope=\"wmma.matrix_b\",\n                                            offset_factor=1,\n                                        )\n                                        wmma_c1 = T.match_buffer(\n                                            wmma_c[\n                                                new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                                new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                            ],\n                                            (16, 16),\n                                            \"float32\",\n                                            strides=[16 * 4, 1],\n                                            scope=\"wmma.accumulator\",\n                                            offset_factor=1,\n                                        )\n                                        T.evaluate(\n                                            T.tvm_mma_sync(\n                                                wmma_c1.data,\n                                                index_i * 4 + index_jj,\n                                                wmma_a1.data,\n                                                index_i,\n                                                wmma_b1.data,\n                                                index_jj,\n                                                wmma_c1.data,\n                                                index_i * 4 + index_jj,\n                                                dtype=\"handle\",\n                                            )\n                                        )\n                        for index_i, index_jj in T.grid(2, 4):\n                            with T.block():\n                                new_axis_vi = T.axis.S(64, axis_bx * 4 + thread_ty * 2 + index_i)\n                                new_axis_vj = T.axis.S(64, axis_by * 8 + thread_tz * 4 + index_jj)\n                                T.reads(\n                                    wmma_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ]\n                                )\n                                T.writes(\n                                    match_buffer_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ]\n                                )\n                                stride0 = T.var(\"int32\")\n                                stride1 = T.var(\"int32\")\n                                wmma_c2 = T.match_buffer(\n                                    wmma_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ],\n                                    (16, 16),\n                                    \"float32\",\n                                    strides=[16 * 4, 1],\n                                    scope=\"wmma.accumulator\",\n                                    offset_factor=1,\n                                )\n                                match_buffer_c1 = T.match_buffer(\n                                    match_buffer_c[\n                                        new_axis_vi * 16 : new_axis_vi * 16 + 16,\n                                        new_axis_vj * 16 : new_axis_vj * 16 + 16,\n                                    ],\n                                    (16, 16),\n                                    \"float32\",\n                                    strides=[stride0, stride1],\n                                    offset_factor=1,\n                                )\n                                T.evaluate(\n                                    T.tvm_store_matrix_sync(\n                                        wmma_c2.data,\n                                        16,\n                                        16,\n                                        16,\n                                        index_i * 4 + index_jj,\n                                        T.tvm_access_ptr(\n                                            T.type_annotation(dtype=\"float32\"),\n                                            match_buffer_c1.data,\n                                            match_buffer_c1.elem_offset,\n                                            match_buffer_c1.strides[0],\n                                            1,\n                                            dtype=\"handle\",\n                                        ),\n                                        match_buffer_c1.strides[0],\n                                        \"row_major\",\n                                        dtype=\"handle\",\n                                    )\n                                )\n\n\n@tvm.testing.requires_cuda\ndef test_gemm_tensorcore():\n    \"\"\"Test running gemm on tensorcore.\"\"\"\n    dev = tvm.device(\"cuda\", 0)\n    a_np = np.random.uniform(size=(1024, 1024)).astype(\"float16\")\n    b_np = np.random.uniform(size=(1024, 1024)).astype(\"float16\")\n    c_np = np.dot(a_np.astype(\"float32\"), b_np.T.astype(\"float32\"))\n    buff_a = tvm.nd.array(a_np, dev)\n    buff_b = tvm.nd.array(b_np, dev)\n    buff_c = tvm.nd.array(np.zeros((1024, 1024), dtype=\"float32\"), dev)\n    myfunc = tvm.build(tensorcore_gemm, target=\"cuda\", name=\"dense\")\n    myfunc(buff_a, buff_b, buff_c)\n    tvm.testing.assert_allclose(buff_c.numpy(), c_np, rtol=1e-3)\n\n    evaluator = myfunc.time_evaluator(myfunc.entry_name, dev, number=100)\n    time_elapsed = evaluator(buff_a, buff_b, buff_c).mean\n    num_flops = 2 * 1024 * 1024 * 1024\n    gflops = num_flops / (time_elapsed * 1e3) / 1e6\n    print(\"gemm with tensor core: %f ms\" % (time_elapsed * 1e3))\n    print(\"GFLOPS: %f\" % gflops)\n\n\nif __name__ == \"__main__\":\n    test_gemm_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test scheduling of reduction operations.\"\"\"\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import te, topi\nfrom tvm.driver.build_module import schedule_to_module\nimport tvm.testing\nimport tvm.topi.testing\n\n\n@tvm.testing.requires_gpu\ndef test_reduce_prims():\n    \"\"\"Test reduction operations.\"\"\"\n\n    def test_prim(reducer, np_reducer):\n        # graph\n        size_var_n = tvm.te.size_var(\"n\")\n        size_var_m = tvm.te.size_var(\"m\")\n        placeholder_a = te.placeholder((size_var_n, size_var_m), name=\"A\")\n        result_r = te.compute((size_var_n,), lambda i: tvm.tir.Select((i > 1), 1, 0), name=\"R\")\n        axis_k = te.reduce_axis((0, size_var_m))\n        result_b = te.compute(\n            (size_var_n,),\n            lambda i: reducer(placeholder_a[i, axis_k], axis=axis_k, where=(result_r[i] == 1)),\n            name=\"B\",\n        )\n        # schedule\n        schedule = te.create_schedule(result_b.op)\n        # create iter var and assign them tags.\n        num_thread = 1\n        axis_x0, axis_x1 = schedule[result_b].split(result_b.op.axis[0], factor=num_thread)\n        schedule[result_b].bind(axis_x0, te.thread_axis(\"blockIdx.x\"))\n        schedule[result_b].bind(axis_x1, te.thread_axis(\"threadIdx.x\"))\n        schedule[result_r].compute_inline()\n\n        # one line to build the function.\n        def check_device(device, host=\"llvm\"):\n            dev = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled..\" % device)\n                return\n            freduce = tvm.build(\n                schedule,\n                args=[placeholder_a, result_b],\n                target=tvm.target.Target(device, host),\n                name=\"myreduce\",\n            )\n            # launch the kernel.\n            num_n = 1028\n            num_m = 129\n            buff_x = tvm.nd.array(\n                np.random.uniform(size=(num_n, num_m)).astype(placeholder_a.dtype), dev\n            )\n            buff_y = tvm.nd.array(np.zeros(num_n, dtype=result_b.dtype), dev)\n            freduce(buff_x, buff_y)\n            npy = buff_y.numpy()\n            npy[:2] = 0\n            res = np_reducer(buff_x.numpy(), axis=1)\n            res[:2] = 0\n            tvm.testing.assert_allclose(npy, res, rtol=1e-4)\n\n        check_device(\"metal\")\n        check_device(\"vulkan\")\n        check_device(\"cuda\")\n        check_device(\"opencl\")\n        check_device(\"rocm\")\n\n    test_prim(te.sum, np.sum)\n    test_prim(tvm.te.min, np.amin)\n    test_prim(tvm.te.max, np.amax)\n\n\ndef test_init_imm():\n    \"\"\"Test initial values which are immutable in reduction ops.\"\"\"\n    num_n = 1027\n    arr_length = tvm.runtime.convert(num_n)\n    placeholder_a = te.placeholder((arr_length,), name=\"A\")\n    axis_k = te.reduce_axis((0, arr_length))\n    result_b = te.compute(\n        (), lambda: te.sum(placeholder_a[axis_k], axis=axis_k, init=10.0), name=\"B\"\n    )\n    # schedule\n    schedule_s = te.create_schedule(result_b.op)\n    # one line to build the function.\n    def check_target(target=\"llvm\"):\n        if not tvm.runtime.enabled(target):\n            return\n        dev = tvm.cpu(0)\n        fapi = tvm.lower(schedule_s, args=[placeholder_a, result_b])\n        fsum = tvm.build(fapi, target=target, name=\"mysum\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=(num_n,)).astype(placeholder_a.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros((), dtype=result_b.dtype), dev)\n        fsum(buff_a, buff_b)\n        res = 10.0 + np.sum(buff_a.numpy(), axis=0)\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target()\n\n\ndef test_init():\n    \"\"\"Test initializer which is non-const.\"\"\"\n    num_n = 1027\n    arr_length = tvm.runtime.convert(num_n)\n    placeholder_a = te.placeholder((arr_length, arr_length), name=\"A\")\n    placeholder_c = te.placeholder((arr_length, arr_length), name=\"C\")\n    placeholder_i = te.placeholder((arr_length, arr_length), name=\"I\")\n    axis_k = te.reduce_axis((0, arr_length))\n    result_b = te.compute(\n        (arr_length, arr_length),\n        lambda i, j: te.sum(\n            placeholder_a[i, axis_k] * placeholder_c[axis_k, j],\n            axis=axis_k,\n            init=placeholder_i[i, j],\n        ),\n        name=\"B\",\n    )\n\n    # schedule\n    schedule = te.create_schedule(result_b.op)\n    # one line to build the function.\n    def check_target(target=\"llvm\"):\n        if not tvm.runtime.enabled(target):\n            return\n        dev = tvm.cpu(0)\n        fapi = tvm.lower(schedule, args=[placeholder_a, placeholder_c, placeholder_i, result_b])\n        print(fapi)\n        mmult = tvm.build(fapi, target=target, name=\"mmult\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(\n            np.random.uniform(size=(num_n, num_n)).astype(placeholder_a.dtype), dev\n        )\n        buff_c = tvm.nd.array(\n            np.random.uniform(size=(num_n, num_n)).astype(placeholder_c.dtype), dev\n        )\n        buff_i = tvm.nd.array(np.random.uniform(size=(num_n, num_n)).astype(result_b.dtype), dev)\n        buf_b = tvm.nd.array(np.zeros((num_n, num_n), dtype=result_b.dtype), dev)\n        mmult(buff_a, buff_c, buff_i, buf_b)\n        res = buff_i.numpy() + np.matmul(buff_a.numpy(), buff_c.numpy())\n        tvm.testing.assert_allclose(buf_b.numpy(), res, rtol=1e-4)\n\n    check_target()\n\n\ndef test_rfactor():\n    \"\"\"Test rfactors.\"\"\"\n    num_n = 1027\n    arr_length = tvm.runtime.convert(num_n)\n    placeholder_a = te.placeholder((arr_length,), name=\"A\")\n    axis_k = te.reduce_axis((0, arr_length))\n    placeholder_b = te.compute((), lambda: te.sum(placeholder_a[axis_k], axis=axis_k), name=\"B\")\n    # schedule\n    schedule = te.create_schedule(placeholder_b.op)\n    axis_kf, _ = schedule[placeholder_b].split(axis_k, nparts=4)\n    rfactor_bf = schedule.rfactor(placeholder_b, axis_kf)\n    schedule[rfactor_bf].parallel(rfactor_bf.op.axis[0])\n    # one line to build the function.\n    def check_target(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            return\n        dev = tvm.cpu(0)\n        fapi = tvm.lower(schedule, args=[placeholder_a, placeholder_b])\n        fsum = tvm.build(fapi, target=target, name=\"mysum\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=(num_n,)).astype(placeholder_a.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros((), dtype=placeholder_b.dtype), dev)\n        fsum(buff_a, buff_b)\n        res = np.sum(buff_a.numpy(), axis=0)\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target()\n\n\ndef test_rfactor_init():\n    \"\"\"Test rfactors with constant inits.\"\"\"\n    num_n = 1027\n    arr_length = tvm.runtime.convert(num_n)\n    placeholder_a = te.placeholder((arr_length, arr_length), name=\"A\")\n    placeholder_c = te.placeholder((arr_length, arr_length), name=\"C\")\n    placeholder_i = te.placeholder((arr_length, arr_length), name=\"I\")\n    axis_k = te.reduce_axis((0, arr_length))\n    result_b = te.compute(\n        (arr_length, arr_length),\n        lambda i, j: te.sum(\n            placeholder_a[i, axis_k] * placeholder_c[axis_k, j],\n            axis=axis_k,\n            init=placeholder_i[i, j],\n        ),\n        name=\"B\",\n    )\n\n    # schedule\n    schedule = te.create_schedule(result_b.op)\n    axis_kf, _ = schedule[result_b].split(axis_k, nparts=4)\n    rfactor_bf = schedule.rfactor(result_b, axis_kf, 1)\n    schedule[rfactor_bf].parallel(rfactor_bf.op.axis[0])\n    # one line to build the function.\n    def check_target(target=\"llvm\"):\n        if not tvm.runtime.enabled(target):\n            return\n        dev = tvm.cpu(0)\n        fapi = tvm.lower(schedule, args=[placeholder_a, placeholder_c, placeholder_i, result_b])\n        print(fapi)\n        mmult = tvm.build(fapi, target=target, name=\"mmult\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(\n            np.random.uniform(size=(num_n, num_n)).astype(placeholder_a.dtype), dev\n        )\n        buff_c = tvm.nd.array(\n            np.random.uniform(size=(num_n, num_n)).astype(placeholder_c.dtype), dev\n        )\n        buff_i = tvm.nd.array(np.random.uniform(size=(num_n, num_n)).astype(result_b.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros((num_n, num_n), dtype=result_b.dtype), dev)\n        mmult(buff_a, buff_c, buff_i, buff_b)\n        res = buff_i.numpy() + np.matmul(buff_a.numpy(), buff_c.numpy())\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target()\n\n\ndef test_rfactor_factor_axis():\n    \"\"\"Test rfactors across axis.\"\"\"\n    num_n = 1027\n    arr_length = tvm.runtime.convert(num_n)\n    placeholder_a = te.placeholder((arr_length,), name=\"A\")\n    axis_k = te.reduce_axis((0, arr_length))\n    placeholder_b = te.compute((), lambda: te.sum(placeholder_a[axis_k], axis=axis_k), name=\"B\")\n    # schedule\n    schedule = te.create_schedule(placeholder_b.op)\n    axis_kf, _ = schedule[placeholder_b].split(axis_k, nparts=4)\n    rfactor_bf = schedule.rfactor(placeholder_b, axis_kf, 0)\n    schedule[rfactor_bf].parallel(rfactor_bf.op.axis[0])\n    # one line to build the function.\n    def check_target(target=\"llvm\"):\n        if not tvm.testing.device_enabled(target):\n            return\n        dev = tvm.cpu(0)\n        fapi = tvm.lower(schedule, args=[placeholder_a, placeholder_b])\n        fsum = tvm.build(fapi, target=target, name=\"mysum\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(np.random.uniform(size=(num_n,)).astype(placeholder_a.dtype), dev)\n        buff_b = tvm.nd.array(np.zeros((), dtype=placeholder_b.dtype), dev)\n        fsum(buff_a, buff_b)\n        res = np.sum(buff_a.numpy(), axis=0)\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target()\n\n\n@tvm.testing.requires_gpu\ndef test_rfactor_threads():\n    \"\"\"Test rfactors across threads.\"\"\"\n    num_n = 1027\n    num_m = 10\n    length_n = tvm.runtime.convert(num_n)\n    length_m = tvm.runtime.convert(num_m)\n    placeholder_a = te.placeholder((length_m, length_n), name=\"A\")\n    axis_k = te.reduce_axis((0, length_n))\n    nthread = 16\n    result_b = te.compute(\n        (length_m,),\n        lambda i: te.sum(placeholder_a[i, axis_k], axis=axis_k, where=(i > 1)),\n        name=\"B\",\n    )\n    # schedule\n    schedule = te.create_schedule(result_b.op)\n    _, axis_kf = schedule[result_b].split(axis_k, factor=nthread)\n    rfactor_bf = schedule.rfactor(result_b, axis_kf)\n    axis_bx, axis_ty = schedule[result_b].split(schedule[result_b].op.axis[0], factor=nthread)\n    schedule[result_b].bind(axis_bx, te.thread_axis(\"blockIdx.x\"))\n    schedule[result_b].bind(axis_ty, te.thread_axis(\"threadIdx.y\"))\n    axis_tx = schedule[result_b].op.reduce_axis[0]\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    schedule[result_b].bind(axis_tx, thread_x)\n    schedule[rfactor_bf].compute_at(schedule[result_b], axis_tx)\n    schedule[result_b].set_store_predicate(thread_x.var.equal(0))\n\n    # one line to build the function.\n    def check_target(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n\n        fapi = tvm.lower(schedule, args=[placeholder_a, result_b])\n        fsum = tvm.build(fapi, target=device, name=\"mysum\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(\n            np.random.uniform(size=(num_m, num_n)).astype(placeholder_a.dtype), dev\n        )\n        buff_b = tvm.nd.array(np.zeros(num_m, dtype=result_b.dtype), dev)\n        fsum(buff_a, buff_b)\n        res = np.sum(buff_a.numpy(), axis=1)\n        res[:2] = 0\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target(\"vulkan\")\n    check_target(\"cuda\")\n    check_target(\"metal\")\n    check_target(\"opencl\")\n    check_target(\"rocm\")\n\n\n@tvm.testing.requires_gpu\ndef test_rfactor_elemwise_threads():\n    \"\"\"Test rfactor elemwise threads.\"\"\"\n    num_n = 1025\n    num_m = 10\n    placeholder_a = te.placeholder((num_m, num_n), name=\"A\")\n    axis_k = te.reduce_axis((0, num_n))\n    nthread = 16\n    result_b = te.compute(\n        (num_m,), lambda i: te.sum(placeholder_a[i, axis_k], axis=axis_k), name=\"B\"\n    )\n    result_bb = te.compute((num_m,), lambda i: result_b[i] + 1, name=\"BB\")\n    result_c = te.compute((num_m,), lambda i: result_bb[i] + 1, name=\"C\")\n    # schedule\n    schedule = te.create_schedule(result_c.op)\n    schedule[result_bb].compute_inline()\n    axis_bx, axis_ty = schedule[result_c].split(schedule[result_c].op.axis[0], factor=nthread)\n    _, axis_kf = schedule[result_b].split(axis_k, factor=nthread)\n    rfactor_bf = schedule.rfactor(result_b, axis_kf)\n    schedule[result_b].compute_at(schedule[result_c], axis_ty)\n    schedule[result_c].bind(axis_bx, te.thread_axis(\"blockIdx.x\"))\n    schedule[result_c].bind(axis_ty, te.thread_axis(\"threadIdx.y\"))\n    axis_tx = schedule[result_b].op.reduce_axis[0]\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    schedule[result_b].bind(axis_tx, thread_x)\n    schedule[rfactor_bf].compute_at(schedule[result_b], axis_tx)\n    # Since thread_x is shared across reductions\n    # only one of them need to do write back\n    schedule[result_b].set_store_predicate(thread_x.var.equal(0))\n    schedule[result_c].set_store_predicate(thread_x.var.equal(0))\n\n    # one line to build the function.\n    def check_target(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        fapi = tvm.lower(schedule, args=[placeholder_a, result_c])\n        fsum = tvm.build(fapi, target=device, name=\"mysum\")\n        # launch the kernel.\n        buff_a = tvm.nd.array(\n            np.random.uniform(size=(num_m, num_n)).astype(placeholder_a.dtype), dev\n        )\n        buff_b = tvm.nd.array(np.zeros(num_m, dtype=result_b.dtype), dev)\n        fsum(buff_a, buff_b)\n        res = np.sum(buff_a.numpy(), axis=1) + 2\n        tvm.testing.assert_allclose(buff_b.numpy(), res, rtol=1e-4)\n\n    check_target(\"vulkan\")\n    check_target(\"cuda\")\n    check_target(\"metal\")\n    check_target(\"opencl\")\n    check_target(\"rocm\")\n\n\ndef test_argmax():\n    \"\"\"Test argmax.\"\"\"\n\n    def fcombine(tensor_x, tensor_y):\n        lhs = tvm.tir.Select((tensor_x[1] >= tensor_y[1]), tensor_x[0], tensor_y[0])\n        rhs = tvm.tir.Select((tensor_x[1] >= tensor_y[1]), tensor_x[1], tensor_y[1])\n        return lhs, rhs\n\n    def fidentity(tensor1, tensor2):\n        return tvm.tir.const(-1, tensor1), tvm.te.min_value(tensor2)\n\n    argmax = te.comm_reducer(fcombine, fidentity, name=\"argmax\")\n    size_var_m = te.size_var(\"m\")\n    size_var_n = te.size_var(\"n\")\n    idx = te.placeholder((size_var_m, size_var_n), name=\"idx\", dtype=\"int32\")\n    val = te.placeholder((size_var_m, size_var_n), name=\"val\", dtype=\"float32\")\n    axis_k = te.reduce_axis((0, size_var_n), \"k\")\n    result_t0, result_t1 = te.compute(\n        (size_var_m,), lambda i: argmax((idx[i, axis_k], val[i, axis_k]), axis=axis_k), name=\"T\"\n    )\n    schedule = te.create_schedule(result_t0.op)\n\n    def check_target():\n        device = \"cpu\"\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        dev = tvm.device(device, 0)\n        fapi = tvm.lower(schedule, args=[idx, val, result_t0, result_t1])\n        fargmax = tvm.build(fapi, target=\"llvm\", name=\"argmax\")\n\n        height = 12\n        width = 16\n        np_idx = np.repeat(np.arange(width, dtype=\"int32\").reshape(1, width), height, axis=0)\n        np_val = np.random.uniform(size=(height, width)).astype(\"float32\")\n        np_res = np.argmax(np_val, axis=1)\n\n        nd_idx = tvm.nd.array(np_idx, dev)\n        nd_val = tvm.nd.array(np_val, dev)\n        nd_res0 = tvm.nd.array(np.zeros(height, dtype=\"int32\"), dev)\n        nd_res1 = tvm.nd.array(np.zeros(height, dtype=\"float32\"), dev)\n        fargmax(nd_idx, nd_val, nd_res0, nd_res1)\n        tvm.testing.assert_allclose(np_res, nd_res0.numpy())\n\n    check_target()\n\n\n@tvm.testing.requires_gpu\ndef test_rfactor_argmax():\n    \"\"\"Test rfactor argmax\"\"\"\n\n    def fcombine(tensor0, tensor1):\n        lhs = tvm.tir.Select((tensor0[1] >= tensor1[1]), tensor0[0], tensor1[0])\n        rhs = tvm.tir.Select((tensor0[1] >= tensor1[1]), tensor0[1], tensor1[1])\n        return lhs, rhs\n\n    def fidentity(tensor0, tensor1):\n        return tvm.tir.const(-1, tensor0), tvm.te.min_value(tensor1)\n\n    argmax = te.comm_reducer(fcombine, fidentity, name=\"argmax\")\n\n    num_width = 1027\n    num_height = 10\n    width = tvm.runtime.convert(num_width)\n    height = tvm.runtime.convert(num_height)\n    placeholder_a0 = te.placeholder((height, width), name=\"A0\", dtype=\"int32\")\n    placeholder_a1 = te.placeholder((height, width), name=\"A1\", dtype=\"float32\")\n    axis_k = te.reduce_axis((0, width))\n    result_b0, result_b1 = te.compute(\n        (height,),\n        lambda i: argmax((placeholder_a0[i, axis_k], placeholder_a1[i, axis_k]), axis=axis_k),\n        name=\"B\",\n    )\n\n    # schedule\n    schedule = te.create_schedule(result_b0.op)\n    nthread = 16\n    _, axis_kf = schedule[result_b0].split(axis_k, factor=nthread)\n    rfactor_bf0, _ = schedule.rfactor(result_b0, axis_kf)\n    axis_bx, axis_ty = schedule[result_b0].split(schedule[result_b0].op.axis[0], factor=nthread)\n    schedule[result_b0].bind(axis_bx, te.thread_axis(\"blockIdx.x\"))\n    schedule[result_b0].bind(axis_ty, te.thread_axis(\"threadIdx.y\"))\n    axis_tx = schedule[result_b0].op.reduce_axis[0]\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    schedule[result_b0].bind(axis_tx, thread_x)\n    schedule[rfactor_bf0.op].compute_at(schedule[result_b0], axis_tx)\n    schedule[result_b0].set_store_predicate(thread_x.var.equal(0))\n\n    def check_target(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        fapi = tvm.lower(schedule, args=[placeholder_a0, placeholder_a1, result_b0, result_b1])\n        fargmax = tvm.build(fapi, target=device, name=\"argmax\")\n\n        np_idx = np.repeat(\n            np.arange(num_width, dtype=\"int32\").reshape(1, num_width), num_height, axis=0\n        )\n        np_val = np.random.uniform(size=(num_height, num_width)).astype(\"float32\")\n        np_res = np.argmax(np_val, axis=1)\n\n        nd_idx = tvm.nd.array(np_idx, dev)\n        nd_val = tvm.nd.array(np_val, dev)\n        nd_res0 = tvm.nd.array(np.zeros(num_height, dtype=\"int32\"), dev)\n        nd_res1 = tvm.nd.array(np.zeros(num_height, dtype=\"float32\"), dev)\n        fargmax(nd_idx, nd_val, nd_res0, nd_res1)\n        tvm.testing.assert_allclose(np_res, nd_res0.numpy())\n\n    check_target(\"cuda\")\n    check_target(\"vulkan\")\n    check_target(\"rocm\")\n\n\n@tvm.testing.requires_gpu\ndef test_warp_reduction1():\n    \"\"\"Test warp reductions.\"\"\"\n    nthx = 32\n    nthy = 4\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis((0, nthx), \"threadIdx.x\")\n    thread_y = te.thread_axis((0, nthy), \"threadIdx.y\")\n\n    def check_target(device, m, n):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n\n        # compute\n        placeholder_a = te.placeholder((m, n), name=\"A\")\n        axis_k = te.reduce_axis((0, n))\n        placeholder_b = te.compute(\n            (m,), lambda i: te.max(placeholder_a[i][axis_k], axis=axis_k), name=\"B\"\n        )\n        schedule = te.create_schedule(placeholder_b.op)\n\n        # schedule\n        axis_k = schedule[placeholder_b].op.reduce_axis[0]\n        axis_ko, _ = schedule[placeholder_b].split(axis_k, nparts=nthx)\n        schedule[placeholder_b].bind(axis_ko, thread_x)\n        axis_xo, axis_xi = schedule[placeholder_b].split(\n            schedule[placeholder_b].op.axis[0], factor=nthy\n        )\n        schedule[placeholder_b].bind(axis_xi, thread_y)\n        schedule[placeholder_b].bind(axis_xo, block_x)\n\n        tvm.lower(schedule, [placeholder_a, placeholder_b], simple_mode=True)\n\n        # validation\n        func = tvm.build(schedule, [placeholder_a, placeholder_b], device, name=\"warp_reduction\")\n        a_np = np.random.uniform(size=(m, n)).astype(placeholder_a.dtype)\n        b_np = np.zeros((m,), dtype=placeholder_a.dtype)\n        buff_a = tvm.nd.array(a_np, dev)\n        buff_b = tvm.nd.array(b_np, dev)\n        b_np = np.max(a_np, axis=1)\n        func(buff_a, buff_b)\n        tvm.testing.assert_allclose(buff_b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    check_target(\"cuda\", m=32, n=256)\n    check_target(\"cuda\", m=10, n=20)\n    check_target(\"rocm\", m=32, n=256)\n    check_target(\"rocm\", m=10, n=20)\n    # This is a bug in normal reduction.\n    # check_target(\"cuda\", m=10, n=37)\n\n\n@tvm.testing.requires_gpu\ndef test_warp_reduction2():\n    \"\"\"Test warp reductions.\"\"\"\n\n    def fcombine(tensor1, tensor2):\n        return tensor1[0] + tensor2[0], tensor1[1] * tensor2[1]\n\n    def fidentity(tensor1, tensor2):\n        return tvm.tir.const(0, tensor1), tvm.tir.const(1, tensor2)\n\n    add_mul_reducer = te.comm_reducer(fcombine, fidentity, name=\"add_mul_reducer\")\n\n    # compute\n    num_m = 16\n    num_n = 256\n    placeholder_a0 = te.placeholder((num_m, num_n), name=\"A0\", dtype=\"float32\")\n    placeholder_a1 = te.placeholder((num_m, num_n), name=\"Al\", dtype=\"float32\")\n    axis_k = te.reduce_axis((0, num_n), \"k\")\n    result0, result1 = te.compute(\n        (num_m,),\n        lambda i: add_mul_reducer(\n            (placeholder_a0[i, axis_k], placeholder_a1[i, axis_k]), axis=axis_k\n        ),\n        name=\"T\",\n    )\n\n    nthdx, nthdy = 32, 2\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis((0, nthdx), \"threadIdx.x\")\n    thread_y = te.thread_axis((0, nthdy), \"threadIdx.y\")\n\n    def check_target(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n\n        # schedule\n        schedule = te.create_schedule(result0.op)\n        axis_ko, _ = schedule[result0].split(axis_k, nparts=nthdx)\n        axis_xo, axis_xi = schedule[result0].split(schedule[result0].op.axis[0], factor=nthdy)\n        schedule[result0].bind(axis_ko, thread_x)\n        schedule[result0].bind(axis_xi, thread_y)\n        schedule[result0].bind(axis_xo, block_x)\n\n        # validation\n        dev = tvm.device(device, 0)\n        a0_np = np.random.uniform(size=(num_m, num_n)).astype(placeholder_a0.dtype)\n        a1_np = np.random.uniform(size=(num_m, num_n)).astype(placeholder_a1.dtype)\n        t0_np = np.zeros((num_m,), dtype=placeholder_a0.dtype)\n        t1_np = np.zeros((num_m,), dtype=placeholder_a1.dtype)\n        buff_a0 = tvm.nd.array(a0_np, dev)\n        buff_a1 = tvm.nd.array(a1_np, dev)\n        buff_t0 = tvm.nd.array(t0_np, dev)\n        buff_t1 = tvm.nd.array(t1_np, dev)\n        func = tvm.build(\n            schedule, [placeholder_a0, placeholder_a1, result0, result1], device, name=\"reduction\"\n        )\n        func(buff_a0, buff_a1, buff_t0, buff_t1)\n        t0_np = np.sum(a0_np, axis=1)\n        t1_np = np.product(a1_np, axis=1)\n        tvm.testing.assert_allclose(buff_t0.numpy(), t0_np, rtol=1e-3, atol=1e-3)\n        tvm.testing.assert_allclose(buff_t1.numpy(), t1_np, rtol=1e-3, atol=1e-3)\n\n    check_target(\"cuda\")\n    check_target(\"rocm\")\n\n\n@tvm.testing.requires_cuda\ndef test_reduce_storage_reuse():\n    \"\"\"Test reduction reuses storage.\"\"\"\n    target = tvm.target.Target(\"cuda\")\n\n    def run_passes(sch, args):\n        mod = schedule_to_module(sch, args)\n        mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", target))(mod)\n        return tvm.transform.Sequential(\n            [\n                tvm.tir.transform.StorageFlatten(64),\n                tvm.tir.transform.Simplify(),\n                tvm.tir.transform.StorageRewrite(),\n                tvm.tir.transform.LowerThreadAllreduce(),\n            ]\n        )(mod)\n\n    dev = tvm.device(target.kind.name, 0)\n    shape = (16, 16)\n\n    placeholder_a = te.placeholder(shape, dtype=\"float32\", name=\"A\")\n    placeholder_b = topi.nn.softmax(placeholder_a, axis=1) + 1.0\n\n    with tvm.target.Target(target):\n        schedule = topi.cuda.schedule_softmax(placeholder_b)\n\n    mod = run_passes(schedule, [placeholder_a, placeholder_b])\n\n    # Due to the storage rewrite pass, the reduction output storage reduce_temp0 can be reused as\n    # the storage of the next compute.\n\n    # Example:\n    # ...\n    # tir.tvm_thread_allreduce((uint32)1, normal_reduce_temp0[0], 1, reduce_temp0, threadIdx.x)\n    # if ((threadIdx.x < 16)) {\n    #   reduce_temp0[0] = (T_softmax_exp[threadIdx.x]/reduce_temp0[0])\n    # }\n    # ...\n\n    # The LowerThreadAllreduce pass should remap reduce_temp0 on the left hand side of the store\n    # above, as well as the load on the right hand side.\n\n    # Expected output:\n    # ...\n    # red_buf0[0] = tir.tvm_warp_shuffle(mask[0], red_buf0[0], 0, 32, 32)\n    # if ((threadIdx.x < 16)) {\n    #   red_buf0[0] = (T_softmax_exp[threadIdx.x]/red_buf0[0])\n    # }\n    # ...\n\n    def check_store_dst_remapped(op):\n        if isinstance(op, tvm.tir.Store):\n            assert op.buffer_var.name != \"reduce_temp0\"\n\n    tvm.tir.stmt_functor.post_order_visit(mod[\"main\"].body, check_store_dst_remapped)\n\n    inp = np.random.uniform(size=shape).astype(\"float32\")\n    ref = tvm.topi.testing.softmax_python(inp) + 1.0\n\n    func = tvm.build(schedule, [placeholder_a, placeholder_b], target)\n    buff_a = tvm.nd.array(inp, dev)\n    buff_b = tvm.nd.array(np.zeros(shape, dtype=placeholder_b.dtype), dev)\n    func(buff_a, buff_b)\n    tvm.testing.assert_allclose(buff_b.numpy(), ref, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_scan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test scheduling adn running scan operators.\"\"\"\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\n@tvm.testing.requires_gpu\ndef test_scan():\n    \"\"\"Test scan operators.\"\"\"\n    size_var_m = te.size_var(\"m\")\n    size_var_n = te.size_var(\"n\")\n    placeholder_x = te.placeholder((size_var_m, size_var_n), name=\"X\")\n    s_state = te.placeholder((size_var_m, size_var_n))\n    s_init = te.compute((1, size_var_n), lambda _, i: placeholder_x[0, i])\n    s_update = te.compute(\n        (size_var_m, size_var_n), lambda t, i: s_state[t - 1, i] + placeholder_x[t, i]\n    )\n    scan = tvm.te.scan(s_init, s_update, s_state)\n    # test scan + compute case\n    res = te.compute((size_var_m, size_var_n), lambda i, j: scan[i, j])\n\n    # schedule\n    schedule = te.create_schedule(res.op)\n    num_thread = 256\n    block_x = te.thread_axis(None, \"blockIdx.x\")\n    thread_x = te.thread_axis((0, num_thread), \"threadIdx.x\")\n    axis_xo, axis_xi = schedule[s_init].split(s_init.op.axis[1], factor=num_thread)\n    schedule[s_init].bind(axis_xo, block_x)\n    schedule[s_init].bind(axis_xi, thread_x)\n    axis_xo, axis_xi = schedule[s_update].split(s_update.op.axis[1], factor=num_thread)\n    schedule[s_update].bind(axis_xo, block_x)\n    schedule[s_update].bind(axis_xi, thread_x)\n    axis_xo, axis_xi = schedule[res].split(res.op.axis[1], factor=num_thread)\n    schedule[res].bind(axis_xo, block_x)\n    schedule[res].bind(axis_xi, thread_x)\n\n    # one line to build the function.\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled..\" % device)\n            return\n        fscan = tvm.build(schedule, [placeholder_x, res], device, name=\"myscan\")\n        # launch the kernel.\n        num_n = 1024\n        num_m = 10\n        a_np = np.random.uniform(size=(num_m, num_n)).astype(res.dtype)\n        buff_a = tvm.nd.array(a_np, dev)\n        buff_b = tvm.nd.array(np.zeros((num_m, num_n), dtype=res.dtype), dev)\n        fscan(buff_a, buff_b)\n        tvm.testing.assert_allclose(buff_b.numpy(), np.cumsum(a_np, axis=0))\n\n    check_device(\"vulkan\")\n    check_device(\"cuda\")\n    check_device(\"metal\")\n    check_device(\"opencl\")\n\n\nif __name__ == \"__main__\":\n    test_scan()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_tuning.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport logging\nimport tempfile\nfrom typing import List, Optional\n\nimport numpy as np  # type: ignore\nimport pytest\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.meta_schedule.testing.tune_utils import generate_input_data\nfrom tvm.target.target import Target\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\n\n\n@pytest.mark.skip(\"Integration test\")\n@pytest.mark.parametrize(\n    \"model_name, input_shape, data_type, target, layout\",\n    [\n        (\"resnet_18\", [1, 3, 224, 224], \"float32\", \"llvm --num-cores=12\", \"NHWC\"),\n        (\"resnet_18\", [1, 3, 224, 224], \"float32\", \"nvidia/geforce-rtx-3070\", \"NHWC\"),\n    ],\n)\ndef test_meta_schedule_tune_relay(\n    model_name: str,\n    input_shape: List[int],\n    data_type: str,\n    target: str,\n    layout: Optional[str],\n):\n    dev = tvm.cpu() if str(target).startswith(\"llvm\") else tvm.cuda()\n    data = generate_input_data(input_shape, data_type)\n\n    mod, params, (input_name, _, _) = get_network(\n        name=model_name,\n        input_shape=input_shape,\n        layout=layout,\n    )\n\n    target = Target(target)\n    with tempfile.TemporaryDirectory() as work_dir:\n        with ms.Profiler() as profiler:\n            database = ms.relay_integration.tune_relay(\n                mod=mod,\n                target=target,\n                params=params,\n                work_dir=work_dir,\n                max_trials_global=2048,\n            )\n            rt_mod1 = ms.relay_integration.compile_relay(\n                database=database,\n                mod=mod,\n                target=target,\n                params=params,\n            )\n        print(profiler.table())\n\n    def get_output(data, lib, dev):\n        module = graph_executor.GraphModule(lib[\"default\"](dev))\n        module.set_input(input_name, tvm.nd.array(data, device=dev))\n        module.run()\n        return module.get_output(0).numpy()\n\n    # Check correctness\n    actual_output = get_output(data, rt_mod1, dev)\n    print(\n        f\"{model_name} finished tuning and running on {Target(target).kind.name}. \"\n        \"Running baseline...\",\n        flush=True,\n    )\n\n    # Compile without meta-schedule for correctness check\n    baseline_target = \"llvm -num-cores=1\"\n    with tvm.transform.PassContext(opt_level=0):\n        rt_mod2 = relay.build(mod, target=baseline_target, params=params)\n\n    expected_output = get_output(data, rt_mod2, tvm.cpu())\n    print(\n        f\"Basline finished running on {Target(baseline_target).kind.name}. \"\n        \"Verifying correctness...\",\n        flush=True,\n    )\n\n    assert np.allclose(actual_output, expected_output, rtol=1e-4, atol=2e-4)\n    print(\n        f\"Correctness verified for {model_name} on {Target(target).kind.name}.\",\n        flush=True,\n    )\n\n\nif __name__ == \"\"\"__main__\"\"\":\n    test_meta_schedule_tune_relay(\n        \"resnet_18\", [1, 3, 224, 224], \"float32\", \"llvm --num-cores=12\", \"NHWC\"\n    )\n    test_meta_schedule_tune_relay(\n        \"resnet_18\", [1, 3, 224, 224], \"float32\", \"nvidia/geforce-rtx-3070\", None\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/integration/test_winograd_nnpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test winograd convolution using nnpack impl.\"\"\"\nimport numpy as np\nfrom pytest import skip\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import autotvm, te, topi\nfrom tvm.autotvm.task.space import FallbackConfigEntity\nfrom tvm.contrib import nnpack\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef verify_conv2d_nchw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    devices,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    \"\"\"Verify conv2d nchw workload.\"\"\"\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    placholder_a = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    placeholder_w = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(placholder_a.shape)\n    w_shape = get_const_tuple(placeholder_w.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = placholder_a.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_nchw.verify_conv2d_nchw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skipping %s becuase it is not enabled\" % device)\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            result_c = topi.nn.conv2d(\n                placholder_a,\n                placeholder_w,\n                stride,\n                padding,\n                dilation,\n                data_layout=\"NCHW\",\n                out_dtype=dtype,\n            )\n            if add_bias:\n                result_c = topi.add(result_c, bias)\n            if add_relu:\n                result_c = topi.nn.relu(result_c)\n            schedule = topi.generic.schedule_conv2d_nchw([result_c])\n\n        buff_a = tvm.nd.array(a_np, dev)\n        buff_w = tvm.nd.array(w_np, dev)\n        buff_b = tvm.nd.array(b_np, dev)\n        buff_c = tvm.nd.array(np.zeros(get_const_tuple(result_c.shape), dtype=result_c.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                schedule,\n                [placholder_a, placeholder_w, bias, result_c],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation),\n            )\n            func(buff_a, buff_w, buff_b, buff_c)\n        else:\n            func = tvm.build(\n                schedule,\n                [placholder_a, placeholder_w, result_c],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation),\n            )\n            func(buff_a, buff_w, buff_c)\n        tvm.testing.assert_allclose(buff_c.numpy(), c_np, rtol=1e-4)\n\n    for device in devices:\n        check_device(device)\n\n\nclass WinogradFallback(autotvm.FallbackContext):\n    \"\"\"Winograd fallbacks.\"\"\"\n\n    def _query_inside(self, target, workload):\n        key = (target, workload)\n        if key in self.memory:\n            return self.memory[key]\n        cfg = FallbackConfigEntity()\n        cfg.template_key = \"winograd_nnpack_fp32\"\n        self.memory[key] = cfg\n        return cfg\n\n\ndef test_conv2d_nchw():\n    \"\"\"Verify conv2d nchw winograd works.\"\"\"\n\n    if not tvm.get_global_func(\n        \"tvm.contrib.nnpack.convolution_inference_without_weight_transform\", True\n    ):\n        skip(\"extern function is not available\")\n\n    if not nnpack.is_available():\n        skip(\"nnpack is not available\")\n\n    devices = [\"llvm -device=arm_cpu\"]\n    autotvm.GLOBAL_SCOPE.silent = True\n    with WinogradFallback():\n        # resnet 18 workloads\n        verify_conv2d_nchw(1, 64, 56, 64, 3, 1, 1, devices=devices)\n        verify_conv2d_nchw(1, 128, 28, 128, 3, 1, 1, devices=devices)\n        verify_conv2d_nchw(1, 256, 14, 256, 3, 1, 1, devices=devices)\n        verify_conv2d_nchw(1, 512, 7, 512, 3, 1, 1, devices=devices)\n\n        # unet workloads\n        verify_conv2d_nchw(1, 3, 192, 12, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 4, 192, 12, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 12, 96, 24, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 24, 48, 48, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 48, 24, 96, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 96, 12, 180, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 180, 6, 220, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 220, 6, 180, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 180, 12, 96, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 96, 24, 48, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 48, 48, 24, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 24, 96, 12, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 12, 192, 1, 3, 1, 1, add_bias=True, devices=devices)\n\n        # relu, bias\n        verify_conv2d_nchw(1, 64, 56, 64, 3, 1, 1, add_bias=True, devices=devices)\n        verify_conv2d_nchw(1, 64, 56, 64, 3, 1, 1, add_relu=True, devices=devices)\n        verify_conv2d_nchw(1, 64, 56, 64, 3, 1, 1, add_relu=True, add_bias=True, devices=devices)\n\n        # werid workloads\n        verify_conv2d_nchw(1, 3, 3, 3, 3, 1, 1, devices=devices)\n        verify_conv2d_nchw(1, 13, 71, 59, 3, 1, 1, devices=devices)\n    autotvm.GLOBAL_SCOPE.silent = False\n\n\nif __name__ == \"__main__\":\n    import pytest\n\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/nightly/quantization/test_quantization_accuracy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom collections import namedtuple\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import quantize as qtz\nimport mxnet as mx\nfrom mxnet import gluon\nimport logging\nimport os\nimport tvm.testing\n\nlogging.basicConfig(level=logging.INFO)\n\nConfig = namedtuple(\n    \"Config\",\n    [\n        \"model\",\n        \"nbit_input\",\n        \"dtype_input\",\n        \"nbit_output\",\n        \"dtype_output\",\n        \"global_scale\",\n        \"expected_acc\",\n    ],\n)\n\n\ndef get_val_data(model_name, rec_val, batch_size, num_workers=4):\n    rec_val = os.path.expanduser(rec_val)\n    mean_rgb = [123.68, 116.779, 103.939]\n    std_rgb = [58.393, 57.12, 57.375]\n\n    def batch_fn(batch, ctx):\n        data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0)\n        label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)\n        return data, label\n\n    img_size = 299 if model_name == \"inceptionv3\" else 224\n    val_data = mx.io.ImageRecordIter(\n        path_imgrec=rec_val,\n        preprocess_threads=num_workers,\n        shuffle=False,\n        batch_size=batch_size,\n        resize=256,\n        data_shape=(3, img_size, img_size),\n        mean_r=mean_rgb[0],\n        mean_g=mean_rgb[1],\n        mean_b=mean_rgb[2],\n        std_r=std_rgb[0],\n        std_g=std_rgb[1],\n        std_b=std_rgb[2],\n    )\n    return val_data, batch_fn\n\n\ndef get_model(model_name, batch_size, qconfig, original=False):\n    gluon_model = gluon.model_zoo.vision.get_model(model_name, pretrained=True)\n    img_size = 299 if model_name == \"inceptionv3\" else 224\n    data_shape = (batch_size, 3, img_size, img_size)\n    mod, params = relay.frontend.from_mxnet(gluon_model, {\"data\": data_shape})\n\n    logging.debug(\"original\")\n    logging.debug(mod.astext(show_meta_data=False))\n    if original:\n        return mod, params\n\n    with qconfig:\n        logging.debug(\"current quantize config\")\n        logging.debug(qtz.current_qconfig())\n        qfunc = qtz.quantize(mod, params)\n        logging.debug(\"after quantize\")\n        logging.debug(qfunc.astext(show_meta_data=False))\n    return qfunc, params\n\n\ndef eval_acc(\n    model, params, dataset, batch_fn, target=tvm.target.cuda(), device=tvm.cuda(), log_interval=500\n):\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(model, target, params=params)\n    # create runtime module\n    m = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](device))\n\n    # setup evaluaiton metric\n    dataset.reset()\n    batch_size = dataset.batch_size\n    acc_top1 = mx.metric.Accuracy()\n    acc_top5 = mx.metric.TopKAccuracy(5)\n    acc_top1.reset()\n    acc_top5.reset()\n    # Execute\n    for i, batch in enumerate(dataset):\n        data, label = batch_fn(batch, [mx.cpu(0)])\n        m.set_input(\"data\", tvm.nd.array(data[0].asnumpy()))\n        m.run()\n        out_arr = m.get_output(0)\n        acc_top1.update(label, [mx.nd.array(out_arr.numpy())])\n        acc_top5.update(label, [mx.nd.array(out_arr.numpy())])\n\n        if not (i + 1) % log_interval:\n            _, top1 = acc_top1.get()\n            _, top5 = acc_top5.get()\n            nsamples = (i + 1) * batch_size\n            logging.info(\"[%d samples] validation: acc-top1=%f acc-top5=%f\", nsamples, top1, top5)\n    logging.info(\"[final] validation: acc-top1=%f acc-top5=%f\", top1, top5)\n    return top1\n\n\n@tvm.testing.requires_gpu\ndef test_quantize_acc(cfg, rec_val):\n    qconfig = qtz.qconfig(\n        skip_conv_layers=[0],\n        nbit_input=cfg.nbit_input,\n        nbit_weight=cfg.nbit_input,\n        global_scale=cfg.global_scale,\n        dtype_input=cfg.dtype_input,\n        dtype_weight=cfg.dtype_input,\n        dtype_activation=cfg.dtype_output,\n        debug_enabled_ops=None,\n    )\n\n    batch_size = 1\n    model, params = get_model(cfg.model, batch_size, qconfig)\n    val_data, batch_fn = get_val_data(cfg.model, rec_val=rec_val, batch_size=batch_size)\n\n    acc = eval_acc(model, params, val_data, batch_fn)\n    assert acc > cfg.expected_acc\n    return acc\n\n\nif __name__ == \"__main__\":\n    # TODO(for user): replace the line with the path to imagenet validation dataset\n    rec_val = \"/scratch/tqchen/imagenet/val.rec\"\n\n    results = []\n    configs = [\n        # TODO: need to fix accuracy and add AutoTVM log\n        Config(\n            \"mobilenetv2_1.0\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=4.0,\n            expected_acc=0.666,\n        ),\n        Config(\n            \"mobilenetv2_1.0\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=16,\n            dtype_output=\"int16\",\n            global_scale=4.0,\n            expected_acc=0.666,\n        ),\n        Config(\n            \"resnet18_v1\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=16,\n            dtype_output=\"int16\",\n            global_scale=8.0,\n            expected_acc=0.692,\n        ),\n        Config(\n            \"resnet18_v1\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=8.0,\n            expected_acc=0.692,\n        ),\n        Config(\n            \"resnet34_v1\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=8.0,\n            expected_acc=0.733,\n        ),\n        Config(\n            \"resnet50_v1\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=8.0,\n            expected_acc=0.747,\n        ),\n        Config(\n            \"resnet101_v1\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=8.0,\n            expected_acc=0.756,\n        ),\n    ]\n\n    for config in configs:\n        acc = test_quantize_acc(config, rec_val)\n        results.append((config, acc))\n    for res in results:\n        print(res)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/nightly/quantization/test_quantization_accuracy_for_vit.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport sys\nimport logging\n\nimport pytest\n\npytest.importorskip(\"onnx\")\n\nimport onnx\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import quantize as qtz\nimport tvm.testing\nfrom test_quantization_accuracy import Config, get_val_data, eval_acc\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef calibrate_dataset(model_name, rec_val, batch_size, calibration_samples):\n    val_data, _ = get_val_data(model_name, rec_val=rec_val, batch_size=batch_size)\n    val_data.reset()\n    for i, batch in enumerate(val_data):\n        if i * batch_size >= calibration_samples:\n            break\n        data = batch.data[0].asnumpy()\n        yield {\"data\": data}\n\n\ndef download_file(url_base, file_name):\n    if not os.path.exists(file_name) or not os.path.isfile(file_name):\n        import urllib.request as urllib2\n\n        url = \"{}/{}\".format(url_base, file_name)\n        try:\n            print(\"download from {}\".format(url))\n            if sys.version_info >= (3,):\n                urllib2.urlretrieve(url, file_name)\n            else:\n                f = urllib2.urlopen(url)\n                data = f.read()\n                with open(file_name, \"wb\") as code:\n                    code.write(data)\n        except Exception as err:\n            if os.path.exists(file_name):\n                os.remove(file_name)\n            raise Exception(\"download {} failed due to {}!\".format(file_name, repr(err)))\n\n\ndef get_onnx_model(model_name, batch_size, qconfig, original=False, dataset=None):\n    assert model_name == \"vit32\", \"Only support vit32 model!\"\n    base = \"https://github.com/TheGreatCold/tvm-vit/raw/d2aa1e60eef42e2fdedbd1e13aa85ac5faf0a7fc\"\n    logfile = \"gtx1660_vit_B32_224.log\"\n    onnx_path = \"vit_B32_224.onnx\"\n\n    download_file(base, logfile)\n    download_file(base, onnx_path)\n\n    onnx_graph = onnx.load(open(onnx_path, \"rb\"))\n    data_shape = (batch_size, 3, 224, 224)\n    mod, params = relay.frontend.from_onnx(onnx_graph, {\"data\": data_shape})\n\n    with tvm.transform.PassContext(opt_level=3):\n        qfunc = relay.quantize.prerequisite_optimize(mod, params=params)\n    logging.debug(\"original\")\n    logging.debug(qfunc.astext(show_meta_data=False))\n    if original:\n        return qfunc, params, logfile\n\n    with qconfig:\n        logging.debug(\"current quantize config\")\n        logging.debug(qtz.current_qconfig())\n\n        if dataset is not None:\n            with tvm.target.cuda():\n                with tvm.autotvm.apply_history_best(logfile):\n                    qfunc = qtz.quantize(qfunc, params, dataset=dataset)\n        else:\n            qfunc = qtz.quantize(qfunc, params)\n\n        logging.debug(\"after quantize\")\n        logging.debug(qfunc.astext(show_meta_data=False))\n    return qfunc, params, logfile\n\n\n@tvm.testing.requires_gpu\ndef test_onnx_quantize_acc(cfg, rec_val, batch_size=1, original=False):\n    qconfig = qtz.qconfig(\n        skip_conv_layers=[0],\n        skip_dense_layer=False,\n        nbit_input=cfg.nbit_input,\n        nbit_weight=cfg.nbit_input,\n        dtype_input=cfg.dtype_input,\n        dtype_weight=cfg.dtype_input,\n        dtype_activation=cfg.dtype_output,\n        debug_enabled_ops=None,\n        calibrate_mode=\"percentile\",\n        calibrate_chunk_by=8,\n    )\n\n    dataset = list(calibrate_dataset(cfg.model, rec_val, batch_size, 64))\n    model, params, logfile = get_onnx_model(\n        cfg.model, batch_size, qconfig, original=original, dataset=dataset\n    )\n    val_data, batch_fn = get_val_data(cfg.model, rec_val=rec_val, batch_size=batch_size)\n\n    with tvm.autotvm.apply_history_best(logfile):\n        acc = eval_acc(model, params, val_data, batch_fn, log_interval=1000)\n    assert acc > cfg.expected_acc\n    return acc\n\n\nif __name__ == \"__main__\":\n    # TODO(for user): replace the line with the path to imagenet validation dataset\n    rec_val = \"/scratch/tqchen/imagenet/val.rec\"\n\n    configs = [\n        Config(\n            \"vit32\",\n            nbit_input=8,\n            dtype_input=\"int8\",\n            nbit_output=32,\n            dtype_output=\"int32\",\n            global_scale=8.0,\n            expected_acc=0.727,\n        ),\n    ]\n\n    for config in configs:\n\n        # float32 model\n        acc = test_onnx_quantize_acc(config, rec_val, batch_size=1, original=True)\n        print(\"{}-float32: {}\".format(config.model, acc))\n\n        # int8 model\n        acc = test_onnx_quantize_acc(config, rec_val, batch_size=1, original=False)\n        print(\"{}-int8: {}\".format(config.model, acc))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_aot_create_executor_metadata.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long,missing-class-docstring,missing-module-docstring,missing-function-docstring,no-self-argument,unused-argument,invalid-name\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nfrom tvm.runtime.ndarray import array\nfrom tvm.relay.backend import Executor\nfrom tvm.relay.backend.aot import CreateExecutorMetadata\nfrom tvm.relay import TensorType\nfrom tvm.tir.usmp.utils import PoolAllocation\nfrom tvm.ir.memory_pools import AllocatedPoolInfo, ConstantPoolInfo, WorkspacePoolInfo, ConstantInfo\n\n\ndef _check_executor_metadata(executor_metadata, expected_metadata):\n    assert list(executor_metadata.inputs) == expected_metadata[\"inputs\"]\n    assert list(executor_metadata.input_tensor_types) == expected_metadata[\"input_tensor_types\"]\n    assert list(executor_metadata.outputs) == expected_metadata[\"outputs\"]\n    assert list(executor_metadata.output_tensor_types) == expected_metadata[\"output_tensor_types\"]\n    assert list(executor_metadata.pools) == expected_metadata[\"pools\"]\n    assert executor_metadata.devices == expected_metadata[\"devices\"]\n    assert executor_metadata.executor == expected_metadata[\"executor\"]\n    assert executor_metadata.mod_name == expected_metadata[\"mod_name\"]\n    assert executor_metadata.interface_api == expected_metadata[\"interface_api\"]\n    assert executor_metadata.unpacked_api == expected_metadata[\"unpacked_api\"]\n    assert executor_metadata.workspace_alignment == expected_metadata[\"workspace_alignment\"]\n    assert executor_metadata.constant_alignment == expected_metadata[\"constant_alignment\"]\n    assert set(executor_metadata.pool_inputs.keys()) == set(expected_metadata[\"pool_inputs\"].keys())\n    assert set(executor_metadata.io_pool_allocations.keys()) == set(\n        expected_metadata[\"io_pool_allocations\"].keys()\n    )\n\n\ndef test_create_executor_metadata_single_func():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(\n            a: T.handle, output: T.handle, workspace: T.Ptr[T.uint8], constants: T.Ptr[T.uint8]\n        ) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\": \"llvm\", \"tag\": \"\", \"keys\": [\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": [\"test_device\"]})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_1 = T.allocate([140], \"int8\", \"global.workspace\")\n            constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_1, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_1, constant_0, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    target = Module[\"__tvm_main__\"].attrs[\"target\"]\n    executor = Executor(\"aot\", {\"interface-api\": \"c\"})\n    workspace_pool_info = AllocatedPoolInfo(\n        WorkspacePoolInfo(\"sram\", [target]),\n        256,\n        3,\n    )\n    constant_pool_info = AllocatedPoolInfo(\n        ConstantPoolInfo(\n            \"flash\",\n            [target],\n            [ConstantInfo(\"a\", 0, array(np.array([0])))],\n        ),\n        512,\n        2,\n    )\n    io_pool_allocations = {\n        \"a\": PoolAllocation(WorkspacePoolInfo(\"sram\", [target]), 0),\n        \"output\": PoolAllocation(WorkspacePoolInfo(\"sram\", [target]), 0),\n    }\n    mod = Module.with_attr(\"io_tensor_pool_allocations\", io_pool_allocations)\n    mod[\"__tvm_main__\"] = mod[\"__tvm_main__\"].with_attr(\n        \"pool_args\",\n        [\n            constant_pool_info,\n            workspace_pool_info,\n        ],\n    )\n    f = mod[\"__tvm_main__\"]\n    expected_metadata = {\n        \"inputs\": [f.params[0]],\n        \"input_tensor_types\": [TensorType((5, 7), \"float32\")],\n        \"outputs\": [\"output\"],\n        \"output_tensor_types\": [TensorType((5, 7), \"float32\")],\n        \"pools\": f.params[2:],\n        \"devices\": f.attrs[\"devices\"],\n        \"executor\": \"aot\",\n        \"mod_name\": \"test_mod\",\n        \"interface_api\": \"c\",\n        \"unpacked_api\": False,\n        \"workspace_alignment\": 16,\n        \"constant_alignment\": 1,\n        \"pool_inputs\": {\n            f.params[2]: workspace_pool_info,\n            f.params[3]: constant_pool_info,\n        },\n        \"io_pool_allocations\": io_pool_allocations,\n    }\n\n    executor_metadata = CreateExecutorMetadata(mod, \"test_mod\", executor, 16, 1)\n\n    _check_executor_metadata(executor_metadata, expected_metadata)\n\n\ndef test_create_executor_metadata_no_usmp():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(\n            a: T.handle, output: T.handle\n        ) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\": \"llvm\", \"tag\": \"\", \"keys\": [\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": [\"test_device\"]})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_1 = T.allocate([140], \"int8\", \"global.workspace\")\n            constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_1, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_1, constant_0, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    executor = Executor(\"aot\", {\"interface-api\": \"c\"})\n    mod = Module\n    f = mod[\"__tvm_main__\"]\n    expected_metadata = {\n        \"inputs\": [f.params[0]],\n        \"input_tensor_types\": [TensorType((5, 7), \"float32\")],\n        \"outputs\": [\"output\"],\n        \"output_tensor_types\": [TensorType((5, 7), \"float32\")],\n        \"pools\": f.params[2:],\n        \"devices\": f.attrs[\"devices\"],\n        \"executor\": \"aot\",\n        \"mod_name\": \"test_mod\",\n        \"interface_api\": \"c\",\n        \"unpacked_api\": False,\n        \"workspace_alignment\": 16,\n        \"constant_alignment\": 1,\n        \"pool_inputs\": {},\n        \"io_pool_allocations\": {},\n    }\n\n    executor_metadata = CreateExecutorMetadata(mod, \"test_mod\", executor, 16, 1)\n\n    _check_executor_metadata(executor_metadata, expected_metadata)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_aot_create_function_metadata.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long,missing-class-docstring,missing-module-docstring,missing-function-docstring,no-self-argument,unused-argument,invalid-name\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nfrom tvm.runtime.ndarray import array\nfrom tvm.relay.backend.aot import CreateFunctionMetadata\nfrom tvm.ir.memory_pools import AllocatedPoolInfo, ConstantPoolInfo, WorkspacePoolInfo, ConstantInfo\n\n\ndef _check_function_metadata(function_metadata, expected_infos):\n    for symbol, expected_info in expected_infos.items():\n        func_info = function_metadata[symbol]\n        # Check workspace_sizes\n        key, value = func_info.workspace_sizes.items()[0]\n        assert str(key) == expected_info[\"target\"]\n        assert value == expected_info[\"workspace_sizes\"]\n        # Check io_sizes\n        key, value = func_info.io_sizes.items()[0]\n        assert str(key) == expected_info[\"target\"]\n        assert value == expected_info[\"io_sizes\"]\n        # Check constant_sizes\n        key, value = func_info.constant_sizes.items()[0]\n        assert str(key) == expected_info[\"target\"]\n        assert value == expected_info[\"constant_sizes\"]\n        # Check tir_primfuncs\n        key, value = func_info.tir_primfuncs.items()[0]\n        assert str(key) == expected_info[\"target\"]\n        tvm.ir.assert_structural_equal(value, expected_info[\"tir_primfuncs\"])\n\n\ndef test_create_function_metadata_workspace_allocate_only():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]})})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_1 = T.allocate([140], \"int8\", \"global.workspace\")\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_1, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_1, sid_2, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 432,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 0,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        }\n    }\n\n    function_metadata = CreateFunctionMetadata(Module, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\ndef test_create_function_metadata_constant_allocate_only():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"num_inputs\": 1, \"num_outputs\": 1})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, constant_0, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 0,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 140,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        }\n    }\n\n    function_metadata = CreateFunctionMetadata(Module, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\ndef test_create_function_metadata_constant_pool_only():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"num_inputs\": 1, \"num_outputs\": 1})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, a_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 0,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 256,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        }\n    }\n\n    target = Module[\"__tvm_main__\"].attrs[\"target\"]\n    mod = Module.with_attr(\n        \"pool_args\",\n        [\n            AllocatedPoolInfo(\n                ConstantPoolInfo(\n                    \"flash\",\n                    [target],\n                    [ConstantInfo(\"a\", 0, array(np.array([0])))],\n                ),\n                256,\n            ),\n        ],\n    )\n\n    function_metadata = CreateFunctionMetadata(mod, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\ndef test_create_function_metadata_workspace_pool_only():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"num_inputs\": 1, \"num_outputs\": 1})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, a_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 256,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 0,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        }\n    }\n\n    target = Module[\"__tvm_main__\"].attrs[\"target\"]\n    mod = Module.with_attr(\n        \"pool_args\",\n        [\n            AllocatedPoolInfo(\n                WorkspacePoolInfo(\"sram\", [target]),\n                256,\n            ),\n        ],\n    )\n\n    function_metadata = CreateFunctionMetadata(mod, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\ndef test_create_function_metadata_all_single_func():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]})})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n            sid_1 = T.allocate([140], \"int8\", \"global.workspace\")\n            constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_1, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_1, constant_0, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 688,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 652,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        }\n    }\n\n    target = Module[\"__tvm_main__\"].attrs[\"target\"]\n    mod = Module.with_attr(\n        \"pool_args\",\n        [\n            AllocatedPoolInfo(\n                ConstantPoolInfo(\n                    \"flash\",\n                    [target],\n                    [ConstantInfo(\"a\", 0, array(np.array([0])))],\n                ),\n                512,\n            ),\n            AllocatedPoolInfo(\n                WorkspacePoolInfo(\"sram\", [target]),\n                256,\n            ),\n        ],\n    )\n\n    function_metadata = CreateFunctionMetadata(mod, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\ndef test_create_function_metadata_workspace_multi_funcs():\n    # fmt: off\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def __tvm_main__(a: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"num_inputs\": 1, \"num_outputs\": 1})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, a_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n\n        @T.prim_func\n        def test_fused_add(a: T.handle, b: T.handle, output: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"test_mod_test_fused_add\", \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]})})\n            a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n            b_buffer = T.match_buffer(b, [5, 7], dtype=\"float32\", align=16)\n            output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n            # body\n            sid_0 = T.allocate([140], \"int8\", \"global.workspace\")\n            constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n            T.evaluate(T.tvm_call_cpacked(\"magic\", a_buffer.data, b_buffer.data, sid_0, constant_0, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    expected_infos = {\n        \"__tvm_main__\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 0,\n            \"io_sizes\": 280,\n            \"constant_sizes\": 0,\n            \"tir_primfuncs\": Module[\"__tvm_main__\"],\n        },\n        \"test_fused_add\": {\n            \"target\": \"llvm -keys=cpu \",\n            \"workspace_sizes\": 144,\n            \"io_sizes\": 420,\n            \"constant_sizes\": 140,\n            \"tir_primfuncs\": Module[\"test_fused_add\"],\n        },\n    }\n\n    function_metadata = CreateFunctionMetadata(Module, 16, 1)\n\n    _check_function_metadata(function_metadata, expected_infos)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_c_device_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"AOT with C Device API Tests\"\"\"\n\nimport re\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pytest\n\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.ir.module import IRModule\nfrom tvm.testing.aot import AOTTestModel, generate_ref_data, compile_models\nfrom tvm.micro.testing.aot_test_utils import AOT_DEFAULT_RUNNER\n\n\n@pytest.fixture(name=\"device_api_main_func\")\ndef fixture_device_api_main_func():\n    \"\"\"Test function generator which generates C Device API calls\"\"\"\n\n    # Ideally we should have a sample Target registered here\n    # but we're going to re-use this for now\n    pytest.importorskip(\"ethosu.vela\")\n\n    # pylint: disable=import-outside-toplevel\n    import tensorflow as tf\n    import tflite.Model\n\n    from tests.python.contrib.test_ethosu.infra import create_test_runner, generate_ref_data_tflite\n    from tvm.relay.op.contrib.ethosu import partition_for_ethosu\n\n    # pylint: enable=import-outside-toplevel\n\n    tf.config.run_functions_eagerly(True)\n\n    class Model(tf.Module):\n        @tf.function\n        def tf_function(self, x):\n            return tf.nn.max_pool(x, [1, 2], [1, 2], \"SAME\")\n\n    def representative_dataset():\n        for _ in range(100):\n            data = np.random.rand(1, 3, 4, 3)\n            yield [data.astype(np.float32)]\n\n    model = Model()\n    concrete_func = model.tf_function.get_concrete_function(\n        tf.TensorSpec([1, 3, 4, 3], dtype=tf.float32)\n    )\n\n    converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    converter.representative_dataset = representative_dataset\n    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n    converter.inference_input_type = tf.int8\n    converter.inference_output_type = tf.int8\n\n    tflite_graph = converter.convert()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n\n    relay_module, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"x\": [1, 3, 4, 3]},\n        dtype_dict={\"x\": \"int8\"},\n    )\n    mod = partition_for_ethosu(relay_module, params)\n\n    # Generate reference data\n    input_data, output_data = generate_ref_data_tflite(tflite_graph)\n\n    def compile_to_main_func(interface_api=\"c\", use_unpacked_api=True):\n        test_runner = create_test_runner()\n        compiled_models = compile_models(\n            models=AOTTestModel(\n                module=mod,\n                inputs=input_data,\n                outputs=output_data,\n            ),\n            interface_api=interface_api,\n            use_unpacked_api=use_unpacked_api,\n            workspace_byte_alignment=16,\n            pass_config=test_runner.pass_config,\n        )\n        main_ir_module = compiled_models[0].executor_factory.lowered_ir_mods.items()[0][1]\n        main_func = main_ir_module[\"__tvm_main__\"]\n        return main_func\n\n    return compile_to_main_func\n\n\n@pytest.fixture(name=\"non_device_api_main_func\")\ndef fixture_non_device_api_main_func():\n    \"\"\"Test function generator which does not generate C Device API calls\"\"\"\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    func = relay.Function([x, y], relay.multiply(x, y))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(1, 10).astype(\"float32\")\n\n    inputs = OrderedDict([(\"x\", x_data), (\"y\", y_data)])\n    output_list = generate_ref_data(func, inputs)\n\n    def compile_to_main_func(interface_api=\"c\", use_unpacked_api=True):\n        test_runner = AOT_DEFAULT_RUNNER\n        compiled_models = compile_models(\n            models=AOTTestModel(\n                module=IRModule.from_expr(func),\n                inputs=inputs,\n                outputs=output_list,\n            ),\n            interface_api=interface_api,\n            use_unpacked_api=use_unpacked_api,\n            workspace_byte_alignment=16,\n            pass_config=test_runner.pass_config,\n        )\n        main_ir_module = list(compiled_models[0].executor_factory.lowered_ir_mods.values())[0]\n        main_func = main_ir_module[\"__tvm_main__\"]\n        return main_func\n\n    return compile_to_main_func\n\n\ndef test_device_api_hooks_unpacked_api(device_api_main_func):\n    \"\"\"Check for Device API hooks with unpacked internal calls\"\"\"\n    main_func = device_api_main_func(interface_api=\"c\", use_unpacked_api=True)\n\n    # Activate Device\n    assert (\n        str(main_func.body[0])\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUActivate\",'\n        + \" device_context_ethos_u))\\n\"\n    )\n    # Open Device\n    print(\"main func\", repr(main_func.body))\n    assert (\n        str(main_func.body[1][0][0][0])\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUOpen\",'\n        + \" device_context_ethos_u))\\n\"\n    )\n    # Device Call\n    # We dont need to check exact input and output var names in this test.\n    # Hence, using a regex to cover any legal I/O name.\n    regex = re.compile(\n        r\"tir\\.tvm_check_return\\(\"\n        r\"0, -1, \"\n        r'tir\\.call_extern\\(\"tvmgen_default_ethos_u_main_0\", '\n        r\"\\w+, \\w+, device_context_ethos_u\\)\\)\"\n    )\n    assert regex.match(str(main_func.body[1][0][0][1]))\n    # Close Device\n    assert (\n        str(main_func.body[1][0][0][2])\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUClose\",'\n        + \" device_context_ethos_u))\\n\"\n    )\n    # Deactivate Device\n    assert (\n        str(str(main_func.body[2]))\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUDeactivate\",'\n        + \" device_context_ethos_u))\\n\"\n    )\n\n\n@pytest.mark.skip(\n    \"Skipping this test as this is incorrectly using Arm(R) Ethos(TM)-U NPU \"\n    \"with packed calling convention which is not supported by the NPU codegen's \"\n    \"TIR to Runtime Hook. We need to use a different target to test this feature\"\n)\ndef test_device_api_hooks_packed_api(device_api_main_func):\n    \"\"\"Check for Device API hooks with packed internal calls\"\"\"\n    main_func = device_api_main_func(interface_api=\"packed\", use_unpacked_api=False)\n\n    # Activate Device\n    assert (\n        str(main_func.body[0][0].value)\n        == \"@tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUActivate\",'\n        + \" device_context_ethos_u: handle,\"\n        + \" dtype=int32))\"\n    )\n    # Open Device\n    assert (\n        str(main_func.body[1].body.body[0][0][0].value)\n        == \"@tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUOpen\",'\n        + \" device_context_ethos_u: handle,\"\n        + \" dtype=int32))\"\n    )\n    # Device Call\n    assert (\n        str(main_func.body[1].body.body[0][0][1][0].value)\n        == \"@tir.tvm_call_cpacked(\"\n        + '\"tvmgen_default_ethos_u_main_0\",'\n        + \" input: handle, output: handle,\"\n        + \" device_context_ethos_u: handle,\"\n        + \" dtype=int32)\"\n    )\n    # Close Device\n    assert (\n        str(main_func.body[1].body.body[0][0][2].value)\n        == \"@tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUClose\",'\n        + \" device_context_ethos_u: handle,\"\n        + \" dtype=int32))\"\n    )\n    # Deactivate Device\n    assert (\n        str(main_func.body[2][0].value)\n        == \"@tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"TVMDeviceEthosUDeactivate\",'\n        + \" device_context_ethos_u: handle,\"\n        + \" dtype=int32))\"\n    )\n\n\ndef test_without_device_api_unpacked_api(non_device_api_main_func):\n    \"\"\"Test a graph without the Device API with the unpacked internal calls\"\"\"\n\n    main_func = non_device_api_main_func(interface_api=\"c\", use_unpacked_api=True)\n    assert (\n        str(main_func.body)\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"tvmgen_default_fused_multiply\",'\n        + \" x_buffer_var, y_buffer_var, output_buffer_var))\\n\"\n    )\n\n\ndef test_without_device_api_packed_api(non_device_api_main_func):\n    \"\"\"Test a graph without the Device API with the packed internal calls\"\"\"\n\n    main_func = non_device_api_main_func(interface_api=\"packed\", use_unpacked_api=False)\n\n    assert str(main_func.body) == (\n        'tir.tvm_call_cpacked(\"tvmgen_default_fused_multiply\", '\n        \"tir.tvm_stack_make_array(x_buffer_var, tir.tvm_stack_make_shape(10, 10), tir.reinterpret((uint64)0), (uint32)2, float32(0), 0), \"  # pylint: disable=line-too-long\n        \"tir.tvm_stack_make_array(y_buffer_var, tir.tvm_stack_make_shape(1, 10), tir.reinterpret((uint64)0), (uint32)2, float32(0), 0), \"  # pylint: disable=line-too-long\n        \"tir.tvm_stack_make_array(output_buffer_var, tir.tvm_stack_make_shape(10, 10), tir.reinterpret((uint64)0), (uint32)2, float32(0), 0), \"  # pylint: disable=line-too-long\n        \"tir.reinterpret((uint64)0))\\n\"\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_cpp_aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"AOT with C++ Runtime Tests\"\"\"\n\nimport re\nimport textwrap\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import IRModule\nfrom tvm import relay\nfrom tvm.relay import backend, testing\nfrom tvm.testing.aot import generate_ref_data\n\n\ndef test_error_c_interface():\n    \"\"\"Checks that an error occurs when using the packed API in combination with C interface\"\"\"\n\n    two = relay.add(relay.const(1), relay.const(1))\n    func = relay.Function([], two)\n\n    with pytest.raises(\n        tvm.TVMError,\n        match=re.escape(\n            'Need unpacked-api == false (got: 0) and interface-api == \"packed\" (got: c) when '\n            \"targeting c++ runtime\"\n        ),\n    ):\n        tvm.relay.build(\n            IRModule.from_expr(func),\n            target=\"llvm\",\n            executor=backend.Executor(\"aot\", {\"interface-api\": \"c\"}),\n        )\n\n\n@pytest.mark.parametrize(\"enable_usmp\", [True, False])\n@pytest.mark.parametrize(\"target_kind\", [\"c\", \"llvm\"])\ndef test_conv2d(enable_usmp, target_kind):\n    \"\"\"Tests compilation of convolutions\"\"\"\n    relay_model = textwrap.dedent(\n        \"\"\"\\\n        #[version = \"0.0.5\"]\n        def @main(%data : Tensor[(1, 3, 64, 64), uint8], %weight : Tensor[(3, 3, 5, 5), int8]) {\n            %1 = nn.conv2d(\n                 %data,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %2 = cast(nn.max_pool2d(%1, pool_size=[3, 3]), dtype=\"int8\");\n            %3 = nn.conv2d(\n                 %2,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %4 = nn.max_pool2d(%3, pool_size=[3, 3]);\n            %4\n        }\n    \"\"\"\n    )\n    ir_mod = tvm.parser.fromtext(relay_model)\n\n    main_func = ir_mod[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    weight_data = np.random.randint(1, 255, shape_dict[\"weight\"]).astype(type_dict[\"weight\"])\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n    params = {\"weight\": weight_data}\n    inputs = {\"data\": input_data}\n    ref_outputs = generate_ref_data(ir_mod, inputs, params)\n\n    with tvm.transform.PassContext(\n        opt_level=3,\n        config={\n            \"tir.disable_vectorize\": True,\n            \"tir.usmp.enable\": enable_usmp,\n        },\n    ):\n        mod = tvm.relay.build(\n            ir_mod,\n            params=params,\n            target=target_kind,\n            executor=backend.Executor(\"aot\", {\"interface-api\": \"packed\", \"unpacked-api\": False}),\n        )\n    temp_dir = tvm.contrib.utils.TempDirectory()\n    test_so_path = temp_dir / \"test.so\"\n    mod.export_library(test_so_path, cc=\"gcc\", options=[\"-std=c11\", \"-g3\", \"-O0\"])\n    loaded_mod = tvm.runtime.load_module(test_so_path)\n    runner = tvm.runtime.executor.AotModule(loaded_mod[\"default\"](tvm.cpu(0)))\n    runner.set_input(**inputs)\n    runner.run()\n    assert (runner.get_output(0).numpy() == list(ref_outputs.values())[0]).all()\n\n\n@pytest.mark.parametrize(\"enable_usmp\", [True, False])\n@pytest.mark.parametrize(\"target_kind\", [\"c\", \"llvm\"])\ndef test_mobilenet(enable_usmp: bool, target_kind: str):\n    \"\"\"Full network test with Mobilenet\"\"\"\n    ir_mod, params = testing.mobilenet.get_workload(batch_size=1)\n    data_shape = [int(x) for x in ir_mod[\"main\"].checked_type.arg_types[0].shape]\n    data = np.random.uniform(size=data_shape).astype(\"float32\")\n    inputs = {\"data\": data}\n    ref_outputs = generate_ref_data(ir_mod, inputs, params)\n\n    with tvm.transform.PassContext(\n        opt_level=3, config={\"tir.disable_vectorize\": True, \"tir.usmp.enable\": enable_usmp}\n    ):\n        mod = tvm.relay.build(\n            ir_mod,\n            params=params,\n            target=target_kind,\n            executor=backend.Executor(\"aot\", {\"interface-api\": \"packed\"}),\n        )\n\n    temp_dir = tvm.contrib.utils.TempDirectory()\n    test_so_path = temp_dir / \"test.so\"\n    mod.export_library(test_so_path, cc=\"c++\", options=[\"-std=gnu++17\", \"-g3\", \"-O0\"])\n    loaded_mod = tvm.runtime.load_module(test_so_path)\n    runner = tvm.runtime.executor.AotModule(loaded_mod[\"default\"](tvm.cpu(0)))\n    runner.set_input(**inputs)\n    runner.run()\n    assert (runner.get_output(0).asnumpy() == list(ref_outputs.values())[0]).all()\n\n\ndef test_module_list():\n    \"\"\"Checks the correct list of module names is generated\"\"\"\n    input_x = tvm.relay.var(\"x\", tvm.relay.TensorType([1], dtype=\"float32\"))\n    expr = tvm.relay.add(input_x, tvm.relay.Constant(tvm.nd.array(np.array([1], dtype=\"float32\"))))\n    mod = tvm.relay.build(\n        tvm.IRModule.from_expr(tvm.relay.Function([input_x], expr)),\n        target=\"c\",\n        executor=tvm.relay.backend.Executor(\"aot\", {\"interface-api\": \"packed\"}),\n        mod_name=\"unusual_module_name_fred\",\n    )\n    temp_dir = tvm.contrib.utils.TempDirectory()\n    test_so_path = temp_dir / \"test.so\"\n    mod.export_library(test_so_path, cc=\"gcc\", options=[\"-std=c11\"])\n    loaded_mod = tvm.runtime.load_module(test_so_path)\n    list_module_names = loaded_mod.get_function(\"list_module_names\")\n    names_expected = [\"unusual_module_name_fred\"]\n    assert list(sorted(names_expected)) == list(sorted(list_module_names()))\n\n\ndef test_create_executor():\n    x = tvm.relay.var(\"x\", tvm.relay.TensorType([1], dtype=\"float32\"))\n    expr = tvm.relay.add(x, tvm.relay.Constant(tvm.nd.array(np.array([1], dtype=\"float32\"))))\n    actual = relay.create_executor(\n        \"aot\", mod=tvm.IRModule.from_expr(tvm.relay.Function([x], expr)), target=\"c\"\n    ).evaluate()(np.array([2], dtype=\"float32\"))\n\n    np.isfinite(np.array([3], dtype=\"float32\"))\n\n    np.testing.assert_allclose(actual.numpy(), np.array([3], dtype=\"float32\"))\n\n\ndef test_pass_wrong_device_arg():\n    \"\"\"Ensure an error is generated if the incorrect number of devices are passed\"\"\"\n    x = tvm.relay.var(\"x\", tvm.relay.TensorType([1], dtype=\"float32\"))\n    expr = tvm.relay.add(x, tvm.relay.Constant(tvm.nd.array(np.array([1], dtype=\"float32\"))))\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(\n            tvm.IRModule.from_expr(tvm.relay.Function([x], expr)),\n            target=\"c\",\n            executor=backend.Executor(\"aot\", {\"interface-api\": \"packed\"}),\n        )\n\n    temp_dir = tvm.contrib.utils.TempDirectory()\n    test_so_path = temp_dir / \"test.so\"\n    mod.export_library(test_so_path, cc=\"gcc\", options=[\"-std=c11\", \"-g3\", \"-O0\"])\n    loaded_mod = tvm.runtime.load_module(test_so_path)\n\n    with pytest.raises(tvm.TVMError) as error:\n        tvm.runtime.executor.AotModule(loaded_mod[\"default\"](tvm.cpu(0), tvm.cpu(0)))\n\n        assert (\n            \"Check failed: devices_.size() == 1 (2 vs. 1) : Expect exactly 1 device passed.\"\n            in str(error.exception)\n        )\n    # TODO write asserts for # and type of device.\n\n\n@pytest.mark.parametrize(\"target_kind\", [\"c\", \"llvm\"])\n@pytest.mark.parametrize(\"input_name\", [\"input:0\", \"input@0\", \"input_0\"])\ndef test_aot_input_name_with_special_character(target_kind: str, input_name: str):\n    \"\"\"Test name transforms in AOT for input names with special characters.\"\"\"\n    dtype = \"float32\"\n    input_1 = relay.var(input_name, shape=(10, 5), dtype=dtype)\n    weight = relay.var(\"weight\", shape=(1, 5), dtype=dtype)\n    output = relay.add(input_1, weight)\n    func = relay.Function([input_1, weight], output)\n\n    input_data = np.random.rand(10, 5).astype(dtype)\n    weight_data = np.random.rand(1, 5).astype(dtype)\n    expected_output = input_data + weight_data\n    params = {\"weight\": weight_data}\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.relay.build(\n            tvm.IRModule.from_expr(func),\n            target=target_kind,\n            params=params,\n            executor=tvm.relay.backend.Executor(\"aot\", {\"interface-api\": \"packed\"}),\n        )\n    temp_dir = tvm.contrib.utils.TempDirectory()\n    test_so_path = temp_dir / \"test.so\"\n    mod.export_library(test_so_path, cc=\"c++\", options=[\"-std=gnu++17\", \"-g3\", \"-O0\"])\n    # test both original name and transformed name\n    for name in [\"input_0\", input_name]:\n        loaded_mod = tvm.runtime.load_module(test_so_path)\n        runner = tvm.runtime.executor.AotModule(loaded_mod[\"default\"](tvm.cpu(0)))\n        inputs = {name: input_data}\n        runner.set_input(**inputs)\n\n        input_ind = runner.get_input_index(name)\n        assert (runner.get_input(input_ind).asnumpy() == input_data).all()\n\n        runner.run()\n        assert (runner.get_output(0).asnumpy() == expected_output).all()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_crt_aot.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"AOT with C Runtime Tests\"\"\"\n\nfrom collections import OrderedDict\nimport re\nimport os\nimport tarfile\nimport pathlib\n\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay, TVMError\nfrom tvm.contrib import utils\nfrom tvm.ir.module import IRModule\nfrom tvm.relay import testing, transform\nfrom tvm.relay.testing import byoc\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.micro import model_library_format as mlf\nfrom tvm.micro import export_model_library_format\nfrom tvm.ir.instrument import pass_instrument\nfrom tvm.testing.aot import (\n    AOTTestModel,\n    generate_ref_data,\n    compile_and_run,\n    compile_models,\n    create_relay_module_and_inputs_from_tflite_file,\n)\nfrom tvm.micro.testing.aot_test_utils import AOT_DEFAULT_RUNNER, parametrize_aot_options\nfrom tvm.micro.testing.utils import get_conv2d_relay_module\n\n\ndef test_error_c_interface_with_packed_api():\n    \"\"\"Checks that an error occurs when using the packed API in combination with C interface\"\"\"\n    interface_api = \"c\"\n    use_unpacked_api = False\n    test_runner = AOT_DEFAULT_RUNNER\n\n    two = relay.add(relay.const(1), relay.const(1))\n    func = relay.Function([], two)\n\n    with pytest.raises(\n        tvm.TVMError,\n        match=re.escape(\n            'Either need interface_api == \"packed\" (got: c) or '\n            \"unpacked-api == true (got: 0) when targeting \"\n            \"c runtime\"\n        ),\n    ):\n        compile_and_run(\n            AOTTestModel(\n                module=IRModule.from_expr(func), inputs={}, outputs=generate_ref_data(func, {})\n            ),\n            test_runner,\n            interface_api,\n            use_unpacked_api,\n        )\n\n\n@parametrize_aot_options\ndef test_conv_with_params(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests compilation of convolution with parameters\"\"\"\n    mod = get_conv2d_relay_module()\n    main_func = mod[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    weight_data = np.ones(shape_dict[\"weight\"]).astype(type_dict[\"weight\"])\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n\n    params = {\"weight\": weight_data}\n    inputs = {\"data\": input_data}\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_add_with_params(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests compilation of add with parameters\"\"\"\n    input_x = relay.var(\"x\", shape=(1, 10))\n    input_y = relay.var(\"y\", shape=(1, 10))\n    input_z = relay.add(input_x, input_y)\n    func = relay.Function([input_x, input_y], input_z)\n\n    input_x_data = np.ones((1, 10)).astype(\"float32\")\n    input_y_data = np.random.uniform(size=(1, 10)).astype(\"float32\")\n\n    params = {\"x\": input_x_data}\n    inputs = {\"y\": input_y_data}\n    output_list = generate_ref_data(func, inputs, params)\n\n    compile_and_run(\n        AOTTestModel(\n            module=IRModule.from_expr(func),\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\n@pytest.mark.parametrize(\"groups,weight_shape\", [(1, 32), (32, 1)])\ndef test_conv2d(interface_api, use_unpacked_api, test_runner, groups, weight_shape):\n    \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, weight_shape, 3, 3)\n\n    data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight0 = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=groups)\n    main_f = relay.Function([data0, weight0], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = main_f\n    mod = transform.InferType()(mod)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, wshape).astype(dtype)\n\n    inputs = OrderedDict([(\"data\", i_data), (\"weight\", w1_data)])\n\n    output_list = generate_ref_data(mod, inputs)\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef test_packed_global_variables():\n    \"\"\"Check packed global variables in codegen output.\"\"\"\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, 32, 3, 3)\n    interface_api = \"packed\"\n    use_unpacked_api = False\n\n    data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight0 = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=1)\n    main_f = relay.Function([data0, weight0], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = main_f\n    mod = transform.InferType()(mod)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, wshape).astype(dtype)\n\n    inputs = OrderedDict([(\"data\", i_data), (\"weight\", w1_data)])\n\n    output_list = generate_ref_data(mod, inputs)\n    compiled_models_list = compile_models(\n        models=AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        workspace_byte_alignment=8,\n        enable_op_fusion=True,\n        pass_config=AOT_DEFAULT_RUNNER.pass_config,\n        use_runtime_executor=True,\n        target=tvm.target.Target(\"c\"),\n    )\n    compiled_model = compiled_models_list[0]\n\n    tmp_path = utils.tempdir()\n    base_path = tmp_path.temp_dir\n\n    model = compiled_model.model\n    tar_file = os.path.join(base_path, f\"{model.name}.tar\")\n    export_model_library_format(compiled_model.executor_factory, tar_file)\n    t = tarfile.open(tar_file)\n    t.extractall(base_path)\n\n    file_list = []\n    for path in (pathlib.Path(base_path) / \"codegen\" / \"host\" / \"src\").iterdir():\n        if path.is_file():\n            file_list.append(path)\n    assert len(file_list) > 0\n\n    for path in file_list:\n        with open(path, \"r\") as lib_f:\n            lib1 = lib_f.readlines()\n\n        tvmgen_names = []\n        tvmgen_funcs = []\n        for line in lib1:\n            for item in line.split(\" \"):\n                # Find all names starting with tvmgen_default\n                if item.startswith(\"tvmgen_default\"):\n                    # Collect any name starting with tvmgen_default\n                    tvmgen_names.append(item)\n                    # Collect all functions starting with tvmgen_default\n                    tvmgen_funcs += re.findall(r\"(?<=).*(?=\\()\", item)\n\n        # Check if any function name has a packed variable name in all\n        # items that start with tvmgen_default\n        for func in tvmgen_funcs:\n            assert f\"{func}_packed\" not in tvmgen_names\n\n\n@parametrize_aot_options\ndef test_concatenate(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests compilation of concatenate\"\"\"\n    dtype = \"float32\"\n    input_x = relay.var(\"x\", shape=(10, 5), dtype=dtype)\n    input_y = relay.var(\"y\", shape=(10, 5), dtype=dtype)\n    input_z = relay.var(\"z\", shape=(), dtype=dtype)\n    concat_inputs = relay.concatenate((input_x, input_y), axis=1)\n    func_output = relay.add(input_z, concat_inputs)\n    # Check result.\n    func = relay.Function([input_x, input_y, input_z], func_output)\n    x_data = np.random.rand(10, 5).astype(dtype)\n    y_data = np.random.rand(10, 5).astype(dtype)\n    t_data = np.random.uniform(size=()).astype(dtype)\n    inputs = OrderedDict([(\"x\", x_data), (\"y\", y_data), (\"z\", t_data)])\n\n    output_list = generate_ref_data(func, inputs)\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_nested_tuples(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests compilation of functions with nested tuple outputs\"\"\"\n    input_x = relay.var(\"x\", shape=(10,))\n    output_1 = input_x + relay.const(1.0)\n    output_2 = output_1 + relay.const(1.0)\n    output_3 = output_2 + relay.const(1.0)\n    output_4 = output_3 + relay.const(1.0)\n    full_output = relay.Tuple(\n        [output_1, relay.Tuple([relay.Tuple([output_2, output_3]), output_4])]\n    )\n    func = relay.Function([input_x], full_output)\n\n    x_data = np.random.uniform(size=(10,)).astype(np.float32)\n    inputs = {\"x\": x_data}\n    output_list = generate_ref_data(func, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_tuple_getitem(interface_api, use_unpacked_api, test_runner):\n    func = relay.Function([], relay.TupleGetItem(relay.Tuple([relay.const(1), relay.const(2)]), 0))\n    output_list = generate_ref_data(func, {})\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs={}, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_id(interface_api, use_unpacked_api, test_runner):\n    x = relay.var(\"x\", \"float32\")\n    ident = relay.Function([x], x)\n    one = np.array(1.0, \"float32\")\n    inputs = {\"x\": one}\n    output_list = generate_ref_data(ident, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(ident), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_add_const(interface_api, use_unpacked_api, test_runner):\n    two = relay.add(relay.const(1), relay.const(1))\n    func = relay.Function([], two)\n    output_list = generate_ref_data(func, {})\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs={}, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_multiply(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests compilation of multiply\"\"\"\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    func = relay.Function([x, y], relay.multiply(x, y))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(1, 10).astype(\"float32\")\n\n    inputs = OrderedDict([(\"x\", x_data), (\"y\", y_data)])\n    output_list = generate_ref_data(func, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_subtract(interface_api, use_unpacked_api, test_runner):\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sub = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n    func = relay.Function([i], sub, ret_type=relay.TensorType([], \"int32\"))\n    i_data = np.array(1, dtype=\"int32\")\n    inputs = {\"i\": i_data}\n    output_list = generate_ref_data(func, inputs)\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_tuple_output(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Tests getting items from tuples\"\"\"\n    x = relay.var(\"x\", shape=(6, 9))\n    y = relay.split(x, 3).astuple()\n    a = relay.TupleGetItem(y, 0)\n    b = relay.TupleGetItem(y, 1)\n    out = relay.Tuple([a, b])\n    func = relay.Function([x], out)\n    x_data = np.random.rand(6, 9).astype(\"float32\")\n    inputs = {\"x\": x_data}\n    output_list = generate_ref_data(func, inputs)\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@pytest.mark.parametrize(\n    [\"debug_calculated_workspaces\", \"workspace_byte_alignment\"], [(True, 1), (True, 16), (False, 1)]\n)\ndef test_mobilenet(debug_calculated_workspaces, workspace_byte_alignment):\n    \"\"\"Full network test with Mobilenet\"\"\"\n    use_unpacked_api = True\n    interface_api = \"c\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    # TODO(@Mousius) - Enable memory planning to take into account debug information\n    debugging_memory_overhead = 1024 * 1024\n\n    mod, params = testing.mobilenet.get_workload(batch_size=1)\n    data_shape = [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n    data = np.random.uniform(size=data_shape).astype(\"float32\")\n    inputs = {\"data\": data}\n    output_list = generate_ref_data(mod, inputs, params)\n    compile_and_run(\n        AOTTestModel(\n            module=mod,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n            extra_memory_in_bytes=debugging_memory_overhead,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n        workspace_byte_alignment=workspace_byte_alignment,\n        debug_calculated_workspaces=debug_calculated_workspaces,\n    )\n\n\n@pytest.mark.parametrize(\"merge_compiler_regions\", [False, True])\ndef test_byoc_microtvm(merge_compiler_regions):\n    \"\"\"\n    This is a simple test to check BYOC capabilities of AOT\n    with and without merging compiler regions to test for https://github.com/apache/tvm/issues/9036\n    \"\"\"\n    use_unpacked_api = False\n    interface_api = \"packed\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    input_x = relay.var(\"x\", shape=(10, 10))\n    input_w0 = relay.var(\"w0\", shape=(10, 10))\n    input_w1 = relay.var(\"w1\", shape=(10, 10))\n\n    # z0 = x + w0\n    marked_input_x = compiler_begin(input_x, \"ccompiler\")\n    marked_input_w0 = compiler_begin(input_w0, \"ccompiler\")\n    add_x_and_w0 = relay.add(marked_input_x, marked_input_w0)\n    end_inner_add = compiler_end(add_x_and_w0, \"ccompiler\")\n\n    # z1 = z0 + w1\n    marked_inner_add = compiler_begin(end_inner_add, \"ccompiler\")\n    marked_w1 = compiler_begin(input_w1, \"ccompiler\")\n    add_nested_and_w1 = relay.add(marked_inner_add, marked_w1)\n    end_outer_add = compiler_end(add_nested_and_w1, \"ccompiler\")\n\n    # z2 = z0 + z1\n    final_add = relay.add(end_inner_add, end_outer_add)\n\n    relay_func = relay.Function([input_x, input_w0, input_w1], final_add)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay_func\n\n    if merge_compiler_regions:\n        mod = transform.MergeCompilerRegions()(mod)\n\n    mod = transform.PartitionGraph(\"mod_name\")(mod)\n    mod = transform.InferType()(mod)\n\n    x_data = [(\"x\", np.random.rand(10, 10).astype(\"float32\"))]\n    w_data = [(\"w{}\".format(i), np.random.rand(10, 10).astype(\"float32\")) for i in range(2)]\n\n    map_inputs = OrderedDict(x_data + w_data)\n    output_list = generate_ref_data(mod, map_inputs)\n    compile_and_run(\n        AOTTestModel(name=\"my_mod\", module=mod, inputs=map_inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@pytest.mark.parametrize(\"merge_compiler_regions\", [False, True])\ndef test_byoc_microtvm_multiple_subgraphs(merge_compiler_regions):\n    \"\"\"This is a test case to check BYOC capabilities of AOT with multiple sub graphs\"\"\"\n    use_unpacked_api = False\n    interface_api = \"packed\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    input_x = relay.var(\"x\", shape=(10, 10))\n    input_w0 = relay.var(\"w0\", shape=(10, 10))\n    input_w1 = relay.var(\"w1\", shape=(10, 10))\n    input_w2 = relay.var(\"w2\", shape=(10, 10))\n    input_w3 = relay.var(\"w3\", shape=(10, 10))\n    input_w4 = relay.var(\"w4\", shape=(10, 10))\n    input_w5 = relay.var(\"w5\", shape=(10, 10))\n    input_w6 = relay.var(\"w6\", shape=(10, 10))\n    input_w7 = relay.var(\"w7\", shape=(10, 10))\n\n    # C compiler\n    ccompiler_add_1 = relay.add(input_x, input_w0)\n    ccompiler_sub_1 = relay.subtract(ccompiler_add_1, input_w1)\n    ccompiler_mul_1 = relay.multiply(ccompiler_sub_1, input_w2)\n\n    ccompiler_add_2 = relay.add(input_x, input_w3)\n    ccompiler_sub_2 = relay.subtract(ccompiler_add_2, input_w4)\n    ccompiler_mul_2 = relay.multiply(ccompiler_sub_2, input_w5)\n\n    # Other parts on TVM\n    tvm_add = relay.add(input_x, input_w6)\n    tvm_sub = relay.subtract(tvm_add, input_w7)\n\n    concat_outputs = relay.concatenate((ccompiler_mul_1, ccompiler_mul_2, tvm_sub), axis=0)\n    relay_func = relay.Function(\n        [input_x, input_w0, input_w1, input_w2, input_w3, input_w4, input_w5, input_w6, input_w7],\n        concat_outputs,\n    )\n    mod = tvm.IRModule()\n    ann = byoc.CcompilerAnnotator()\n    mod[\"main\"] = ann.visit(relay_func)\n\n    if merge_compiler_regions:\n        mod = transform.MergeCompilerRegions()(mod)\n\n    mod = tvm.relay.transform.PartitionGraph(\"mod_name\")(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    w_data = []\n    for _ in range(8):\n        w_data.append(np.random.rand(10, 10).astype(\"float32\"))\n\n    map_inputs = OrderedDict([(\"x\", x_data)] + [(\"w{}\".format(i), w_data[i]) for i in range(8)])\n    output_list = generate_ref_data(mod, map_inputs)\n    input_list = [map_inputs[\"x\"]]\n    input_list.extend([map_inputs[\"w{}\".format(i)] for i in range(8)])\n    compile_and_run(\n        AOTTestModel(name=\"my_mod\", module=mod, inputs=map_inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_add_name_mangling_with_params(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Checks name mangling works with parameters\"\"\"\n    input_x = relay.var(\"x\", shape=(1, 10))\n    input_y = relay.var(\"y\", shape=(1, 10))\n    func_add = relay.add(input_x, input_y)\n    relay_func = relay.Function([input_x, input_y], func_add)\n\n    x_in = np.ones((1, 10)).astype(\"float32\")\n    y_in = np.random.uniform(size=(1, 10)).astype(\"float32\")\n\n    params = {\"x\": x_in}\n    inputs = {\"y\": y_in}\n    output_list = generate_ref_data(relay_func, inputs, params)\n\n    compile_and_run(\n        AOTTestModel(\n            name=\"my_mod\",\n            module=relay_func,\n            inputs=inputs,\n            outputs=output_list,\n            params=params,\n        ),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_multiple_models(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Compiles multiple models to ensure both can be compiled into one output\"\"\"\n    # Identity model without params\n    x = relay.var(\"x\", \"float32\")\n    mod1 = relay.Function([x], x)\n    one = np.array(1.0, \"float32\")\n    inputs1 = {\"x\": one}\n    output_list1 = generate_ref_data(mod1, inputs1)\n    params1 = None\n\n    # Convolution model\n    mod2 = get_conv2d_relay_module()\n    main_func = mod2[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    weight_data = np.ones(shape_dict[\"weight\"]).astype(type_dict[\"weight\"])\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n\n    params2 = {\"weight\": weight_data}\n    inputs2 = {\"data\": input_data}\n    output_list2 = generate_ref_data(mod2, inputs2, params2)\n\n    compile_and_run(\n        [\n            AOTTestModel(\n                name=\"mod1\",\n                module=mod1,\n                inputs=inputs1,\n                outputs=output_list1,\n                params=params1,\n            ),\n            AOTTestModel(\n                name=\"mod2\",\n                module=mod2,\n                inputs=inputs2,\n                outputs=output_list2,\n                params=params2,\n            ),\n        ],\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef test_quant_mobilenet_tfl():\n    \"\"\"Since in AOT we pass directly the output buffer from the user,\n    in quantized networks sharing the output buffers is not possible.\n    This is because the output data type is int8 and the intermediate\n    buffer are int32 or int16. We use mobilenet quantized to stress this\n    situation and verify that the output buffer sharing is disabled in AOT.\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    tflite_model_file = tf_testing.get_workload_official(\n        \"https://storage.googleapis.com/download.tensorflow.org/\"\n        \"models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\",\n        \"mobilenet_v1_1.0_224_quant.tflite\",\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@parametrize_aot_options\ndef test_transpose(interface_api, use_unpacked_api, test_runner):\n    \"\"\"Test that non-inpleaceable operations (e.g., transpose) do not happen in-place.\"\"\"\n\n    dtype = \"float32\"\n    input_x = relay.var(\"x\", shape=(10, 5), dtype=dtype)\n    input_y = relay.var(\"y\", shape=(10, 5), dtype=dtype)\n    input_z = relay.var(\"z\", shape=(), dtype=dtype)\n    first_add = relay.add(input_x, input_y)\n    transpose_add = relay.transpose(first_add)\n    final_add = relay.add(transpose_add, input_z)\n    # Check result.\n    relay_func = relay.Function([input_x, input_y, input_z], final_add)\n    x_data = np.random.rand(10, 5).astype(dtype)\n    y_data = np.random.rand(10, 5).astype(dtype)\n    t_data = np.random.uniform(size=()).astype(dtype)\n\n    inputs = {\"x\": x_data, \"y\": y_data, \"z\": t_data}\n    output_list = generate_ref_data(relay_func, inputs)\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(relay_func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n        enable_op_fusion=False,\n    )\n\n\ndef test_name_sanitiser():\n    \"\"\"Test that input tensors with special characters in the name don't break compilation\"\"\"\n\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_DEFAULT_RUNNER\n\n    func = relay.var(\"input-x::2\", \"float32\")\n    ident = relay.Function([func], func)\n    one = np.array(1.0, \"float32\")\n    inputs = {\"input-x::2\": one}\n    output_list = generate_ref_data(ident, inputs)\n\n    compile_and_run(\n        AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n        enable_op_fusion=False,\n    )\n\n\ndef test_name_sanitiser_name_clash():\n    \"\"\"Test that 2 input tensors with names that clash once sanitized, generates an error\"\"\"\n\n    interface_api = \"c\"\n    use_unpacked_api = True\n    test_runner = AOT_DEFAULT_RUNNER\n\n    dtype = \"float32\"\n    input_non_clashing = relay.var(\"input::-1\", shape=(10, 5), dtype=dtype)\n    # Next 2 input tensor names will clash once sanitized.\n    input_clashing_1 = relay.var(\"input::-2\", shape=(10, 5), dtype=dtype)\n    input_clashing_2 = relay.var(\"input:--2\", shape=(), dtype=dtype)\n    inner_add = relay.add(input_non_clashing, input_clashing_1)\n    transpose_add = relay.transpose(inner_add)\n    final_add = relay.add(transpose_add, input_clashing_2)\n    # Check result.\n    func = relay.Function([input_non_clashing, input_clashing_1, input_clashing_2], final_add)\n    x_data = np.random.rand(10, 5).astype(dtype)\n    y_data = np.random.rand(10, 5).astype(dtype)\n    t_data = np.random.uniform(size=()).astype(dtype)\n\n    inputs = {\"input::-1\": x_data, \"input::-2\": y_data, \"input:--2\": t_data}\n    output_list = generate_ref_data(func, inputs)\n\n    with pytest.raises(TVMError, match=\"Sanitized input tensor name clash\"):\n        compile_and_run(\n            AOTTestModel(module=IRModule.from_expr(func), inputs=inputs, outputs=output_list),\n            test_runner,\n            interface_api,\n            use_unpacked_api,\n            enable_op_fusion=False,\n        )\n\n\ndef test_aot_codegen_backend_alloc_workspace_calls():\n    \"\"\"This test checks whether AoT lowering creates TVMBackendAllocWorkspace calls\"\"\"\n\n    # The %data and %weight shapes in the following primitive Relay should create\n    # small tensors that would get lowered to stack allocations in the CPU PrimFuncs.\n    # However, the AoT executor codegen should retain them as TVMBAW calls\n    # pylint: disable=line-too-long\n    relay_mod = tvm.parser.fromtext(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(1, 4, 4, 4), float32], %weight: Tensor[(4, 4, 3, 3), float32], src_layout=\"OIHW\", dst_layout=\"OIHW4i4o\") -> Tensor[(1, 4, 4, 4), float32] {\n        %0 = fn (%p02: Tensor[(1, 4, 4, 4), float32], Primitive=1, hash=\"9332b3872fb5292c\", src_layout=\"NCHW\", dst_layout=\"NCHW4c\") -> Tensor[(1, 1, 4, 4, 4), float32] {\n            layout_transform(%p02, src_layout=\"NCHW\", dst_layout=\"NCHW4c\") /* ty=Tensor[(1, 1, 4, 4, 4), float32] */\n        };\n        %1 = fn (%p03: Tensor[(4, 4, 3, 3), float32], Primitive=1, hash=\"9f0b2b8a24a4dab3\", src_layout=\"OIHW\", dst_layout=\"OIHW4i4o\") -> Tensor[(1, 1, 3, 3, 4, 4), float32] {\n            layout_transform(%p03, src_layout=\"OIHW\", dst_layout=\"OIHW4i4o\") /* ty=Tensor[(1, 1, 3, 3, 4, 4), float32] */\n        };\n        %2 = %0(%data) /* ty=Tensor[(1, 1, 4, 4, 4), float32] */;\n        %3 = %1(%weight) /* ty=Tensor[(1, 1, 3, 3, 4, 4), float32] */;\n        %4 = fn (%p01: Tensor[(1, 1, 4, 4, 4), float32], %p1: Tensor[(1, 1, 3, 3, 4, 4), float32], out_layout=\"NCHW4c\", kernel_layout=\"OIHW4i4o\", Primitive=1, data_layout=\"NCHW4c\") -> Tensor[(1, 1, 4, 4, 4), float32] {\n                                                                                                                                                                                                                                                      nn.contrib_conv2d_NCHWc(%p01, %p1, padding=[1, 1, 1, 1], channels=4, kernel_size=[3, 3], data_layout=\"NCHW4c\", kernel_layout=\"OIHW4i4o\", out_layout=\"NCHW4c\") /* ty=Tensor[(1, 1, 4, 4, 4), float32] */\n        };\n        %5 = %4(%2, %3) /* ty=Tensor[(1, 1, 4, 4, 4), float32] */;\n        %6 = fn (%p0: Tensor[(1, 1, 4, 4, 4), float32], Primitive=1, src_layout=\"NCHW4c\", dst_layout=\"NCHW\") -> Tensor[(1, 4, 4, 4), float32] {\n            layout_transform(%p0, src_layout=\"NCHW4c\", dst_layout=\"NCHW\") /* ty=Tensor[(1, 4, 4, 4), float32] */\n        };\n        %6(%5) /* ty=Tensor[(1, 4, 4, 4), float32] */\n        }\n        \"\"\"\n    )\n    # pylint: enable=line-too-long\n\n    compiled_test_mods = compile_models(\n        models=AOTTestModel(module=relay_mod, inputs=None, outputs=None),\n        interface_api=\"c\",\n        use_unpacked_api=True,\n    )\n    source = compiled_test_mods[0].executor_factory.lib.imported_modules[0].get_source()\n    # There should be three allocates created for three primitive relay function\n    # calls in the main for the above relay snippet.\n    assert source.count(\"TVMBackendAllocWorkspace\") == 3\n\n\n@pytest.mark.parametrize(\"constants_byte_alignment\", [8, 16, 32])\ndef test_constants_alignment(constants_byte_alignment):\n    \"\"\"Test that constants_byte_alignment correctly sets constants byte alignment\"\"\"\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    mod, params = testing.mobilenet.get_workload(batch_size=1)\n    data_shape = [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n    data = np.random.uniform(size=data_shape).astype(\"float32\")\n    inputs = {\"data\": data}\n    output_list = generate_ref_data(mod, inputs, params)\n    target = f\"c -constants-byte-alignment={constants_byte_alignment}\"\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api,\n        use_unpacked_api,\n        target=tvm.target.Target(target, host=target),\n    )\n    source = compiled_test_mods[0].executor_factory.lib.imported_modules[0].get_source()\n    assert f'__attribute__((section(\".rodata.tvm\"), aligned({constants_byte_alignment})))' in source\n\n\ndef test_output_tensor_names():\n    \"\"\"Test that the output names generated match those in the model\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    # pylint: disable=import-outside-toplevel\n    import tensorflow as tf\n    import tflite.Model\n\n    # pylint: enable=import-outside-toplevel\n\n    ifm_shape = (1, 299, 299, 3)\n    padding = \"VALID\"\n    strides = (1, 1)\n    dilation = (1, 1)\n    kernel_shape = (3, 2)\n\n    def create_tflite_graph_two_outs():\n        \"\"\"Create a model with 2 output tensors\"\"\"\n\n        class Model(tf.Module):\n            \"\"\"Simple TFLite test model\"\"\"\n\n            @tf.function\n            def tf_function(self, tf_input_x):\n                \"\"\"Single TFLite function with two convolutions\"\"\"\n                tf_strides = [1, strides[0], strides[1], 1]\n                filter_shape = [kernel_shape[0], kernel_shape[1], 3, 3]\n                filter1 = tf.constant(\n                    np.arange(np.prod(filter_shape)).reshape(filter_shape),\n                    dtype=tf.float32,\n                )\n                first_conv2d = tf.nn.conv2d(\n                    tf_input_x,\n                    filters=filter1,\n                    strides=tf_strides,\n                    padding=padding,\n                    dilations=dilation,\n                )\n                first_conv2d = tf.nn.relu(first_conv2d)\n\n                filter2 = tf.constant(\n                    1000 + np.arange(np.prod(filter_shape)).reshape(filter_shape),\n                    dtype=tf.float32,\n                )\n                second_conv2d = tf.nn.conv2d(\n                    tf_input_x,\n                    filters=filter2,\n                    strides=strides,\n                    padding=padding,\n                    data_format=\"NHWC\",\n                    dilations=dilation,\n                )\n                second_conv2d = tf.nn.relu(second_conv2d)\n                return first_conv2d, second_conv2d\n\n        model = Model()\n        concrete_func = model.tf_function.get_concrete_function(\n            tf.TensorSpec(ifm_shape, dtype=tf.float32)\n        )\n\n        # Convert the model\n        def representative_dataset():\n            for _ in range(100):\n                data = np.random.rand(*tuple(ifm_shape))\n                yield [data.astype(np.float32)]\n\n        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n        converter.optimizations = [tf.lite.Optimize.DEFAULT]\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8\n        converter.inference_output_type = tf.int8\n        tflite_model = converter.convert()\n        return tflite_model\n\n    tflite_graph = create_tflite_graph_two_outs()\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)\n    mod, params = relay.frontend.from_tflite(\n        tflite_model,\n        shape_dict={\"input\": ifm_shape},\n        dtype_dict={\"input\": \"int8\"},\n    )\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n    test_runner = AOT_DEFAULT_RUNNER\n\n    in_min, in_max = (-128, 127)\n    data = np.random.randint(in_min, high=in_max, size=ifm_shape, dtype=\"int8\")\n    input_name = mod[\"main\"].params[0].name_hint\n    inputs = {input_name: data}\n    output_list = generate_ref_data(mod, inputs, params)\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api,\n        use_unpacked_api,\n    )\n\n    # Check that the names of the output tensors occur in the source code\n    source = compiled_test_mods[0].executor_factory.lib.get_source()\n    for output_name in output_list.keys():\n        assert output_name in source\n\n\n@pytest.mark.parametrize(\n    \"workspace_byte_alignment,main_workspace_size\",\n    [\n        (8, 14880),\n        (16, 14880),\n        (256, 15616),\n    ],\n)\ndef test_workspace_calculation(workspace_byte_alignment, main_workspace_size):\n    \"\"\"Checks calculated workspace against known values\"\"\"\n    mod, params = tvm.relay.testing.synthetic.get_workload()\n    target = \"c\"\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": workspace_byte_alignment,\n        },\n    )\n    with tvm.transform.PassContext(\n        opt_level=3,\n        config={\n            \"tir.disable_vectorize\": True,\n        },\n    ):\n        lib = tvm.relay.build(mod, target, executor=executor, runtime=runtime, params=params)\n\n    mlf_memory_map = mlf._build_function_memory_map(lib.function_metadata)\n    assert mlf_memory_map[\"main\"][0][\"workspace_size_bytes\"] == main_workspace_size\n\n\n@tvm.testing.requires_package(\"tflite\")\n@tvm.testing.requires_cmsisnn\ndef test_workspace_calculation_cmsis_nn():\n    \"\"\"This tests cmsis_nn codegen for workspace calculation.\n    This is tested specially because cmsis-nn codegen creates\n    multiple PrimFuncs per offloaded relay function in a non\n    -hierarchical manner.\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    # pylint: disable=import-outside-toplevel\n    from tvm.relay.op.contrib import cmsisnn\n    from tvm.contrib.download import download_testdata\n\n    # pylint: enable=import-outside-toplevel\n\n    target = \"c\"\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": 16,\n            \"interface-api\": \"c\",\n            \"unpacked-api\": True,\n        },\n    )\n\n    base_url = (\n        \"https://github.com/ARM-software/ML-zoo/raw/\"\n        \"48a22ee22325d15d2371a6df24eb7d67e21dcc97\"\n        \"/models/keyword_spotting/cnn_small/tflite_int8\"\n    )\n    file_to_download = \"cnn_s_quantized.tflite\"\n    file_saved = \"cnn_s_quantized_15Dec2021.tflite\"\n    model_file = download_testdata(\"{}/{}\".format(base_url, file_to_download), file_saved)\n    mod, _, params = create_relay_module_and_inputs_from_tflite_file(model_file)\n    mod = cmsisnn.partition_for_cmsisnn(mod, params)\n    with tvm.transform.PassContext(\n        opt_level=3,\n        config={\n            \"tir.disable_vectorize\": True,\n        },\n    ):\n        lib = tvm.relay.build(mod, target, executor=executor, runtime=runtime, params=params)\n    mlf_memory_map = mlf._build_function_memory_map(lib.function_metadata)\n    assert mlf_memory_map[\"main\"][0][\"workspace_size_bytes\"] == 14256\n\n\ndef test_aot_codegen_checks_returns():\n    \"\"\"This test checks whether AoT lowering creates calls that check the return value correctly\"\"\"\n    input_x = relay.var(\"x\", shape=(1, 10))\n    input_y = relay.var(\"y\", shape=(1, 10))\n    func_add = relay.add(input_x, input_y)\n    func = relay.Function([input_x, input_y], func_add)\n\n    compiled_test_mods = compile_models(\n        models=AOTTestModel(module=IRModule.from_expr(func), inputs=None, outputs=None),\n        interface_api=\"c\",\n        use_unpacked_api=True,\n    )\n    source = compiled_test_mods[0].executor_factory.lib.imported_modules[0].get_source()\n\n    main_ir_module = compiled_test_mods[0].executor_factory.lowered_ir_mods.items()[0][1]\n    main_func = main_ir_module[\"__tvm_main__\"]\n\n    # Check operator call is wrapped properly\n    assert (\n        str(main_func.body[1])\n        == \"tir.tvm_check_return(0, -1, tir.call_extern(\"\n        + '\"tvmgen_default_fused_add\",'\n        + \" x_buffer_var, y_buffer_var, output_buffer_var))\\n\"\n    )\n    # TODO(Mousius) - Create a better place for C codegen tests\n    assert (\n        \"if (tvmgen_default_fused_add(x_buffer_var, y_buffer_var, output_buffer_var) != 0 ) return -1;\"  # pylint: disable=line-too-long\n        in source\n    )\n\n\ndef test_aot_uses_anf():\n    \"\"\"Checks that A-Normal Form is being used in the AOT lowering pipeline.\"\"\"\n    input_x = relay.var(\"x\", shape=(1, 10, 10, 10))\n    input_y = relay.var(\"y\", shape=(1, 10, 10, 10))\n    func_add = relay.add(input_x, input_y)\n    func = relay.Function([input_x, input_y], func_add)\n\n    @pass_instrument\n    class CheckANFRuns:\n        def __init__(self):\n            self.did_run_anf = False\n\n        def run_before_pass(self, _, info):\n            if info.name == \"ToANormalForm\":\n                self.did_run_anf = True\n            if info.name == \"LowerTE\":\n                assert self.did_run_anf, \"ToANormalForm pass should run before LowerTE.\"\n\n    check_run_anf = CheckANFRuns()\n\n    model = AOTTestModel(module=IRModule.from_expr(func), inputs=None, outputs=None)\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": 8,\n            \"interface-api\": \"c\",\n            \"unpacked-api\": True,\n        },\n    )\n    config = {\"tir.disable_vectorize\": True}\n\n    with tvm.transform.PassContext(opt_level=3, config=config, instruments=[check_run_anf]):\n        tvm.relay.build(\n            model.module,\n            tvm.target.Target(\"c\"),\n            executor=executor,\n            runtime=runtime,\n            workspace_memory_pools=None,\n            params=model.params,\n            mod_name=model.name,\n        )\n\n    assert check_run_anf.did_run_anf, \"Expected ToANormalForm pass to have run.\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_crt_aot_usmp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" This file contains test that use USMP + AoT using C runtime APIs\"\"\"\n\nfrom collections import OrderedDict\nimport re\n\nimport random\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import testing  # pylint: disable=W0611\nfrom tvm.relay import transform\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm import (\n    WorkspaceMemoryPools,\n    ConstantMemoryPools,\n    WorkspacePoolInfo,\n    ConstantPoolInfo,\n    PoolInfoProperties,\n)\nfrom tvm.micro import model_library_format as mlf\nfrom tvm.micro.testing.aot_test_utils import parametrize_aot_options\nfrom tvm.testing.aot import (\n    AOTTestModel,\n    AOTTestRunner,\n    generate_ref_data,\n    compile_and_run,\n    compile_models,\n    run_and_check,\n    create_relay_module_and_inputs_from_tflite_file,\n)\nfrom tvm.testing.usmp import is_tvm_backendallocworkspace_calls\n\n\ndef _check_for_no_tvm_backendallocworkspace_calls(mod: tvm.runtime.module):\n    assert (\n        is_tvm_backendallocworkspace_calls(mod) is False\n    ), \"This is failing because USMP was unable to plan for every tir.allocate node.\"\n\n\n# U1 test case\n@parametrize_aot_options\ndef test_synthetic(interface_api, use_unpacked_api, test_runner):\n    \"\"\"\n    Simple U1 usecase test\n    \"\"\"\n    mod, params = tvm.relay.testing.synthetic.get_workload()\n    main_func = mod[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n    params = {}\n    for name, _ in shape_dict.items():\n        if name != \"data\":\n            params[name] = np.ones(shape_dict[name]).astype(type_dict[name])\n\n    inputs = {\"data\": input_data}\n    output_list = generate_ref_data(mod, inputs, params)\n    config = (\n        {\n            \"tir.disable_vectorize\": True,\n            \"tir.disable_storage_rewrite\": True,\n            \"tir.usmp.enable\": True,\n            \"tir.usmp.algorithm\": \"greedy_by_conflicts\",\n        },\n    )\n\n    test_runner = AOTTestRunner(\n        makefile=test_runner.makefile,\n        prologue=test_runner.prologue,\n        epilogue=test_runner.epilogue,\n        includes=test_runner.includes,\n        parameters=test_runner.parameters,\n        pass_config={**test_runner.pass_config},\n    )\n    test_runner.pass_config.update(*config)\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"workspace_byte_alignment,constant_byte_alignment,\"\n    \"main_workspace_size,main_constant_size,usmp_algo\",\n    [\n        (8, 8, 14208, 948, \"greedy_by_conflicts\"),\n        (16, 8, 14208, 948, \"greedy_by_conflicts\"),\n        (256, 8, 14720, 948, \"greedy_by_conflicts\"),\n        (8, 16, 14208, 956, \"greedy_by_conflicts\"),\n        (16, 16, 14208, 956, \"greedy_by_conflicts\"),\n        (256, 16, 14720, 956, \"greedy_by_conflicts\"),\n        (8, 256, 14208, 1804, \"greedy_by_conflicts\"),\n        (16, 256, 14208, 1804, \"greedy_by_conflicts\"),\n        (256, 256, 14720, 1804, \"greedy_by_conflicts\"),\n        (8, 8, 18576, 948, \"greedy_by_size\"),\n        (16, 8, 18576, 948, \"greedy_by_size\"),\n        (256, 8, 19392, 948, \"greedy_by_size\"),\n        (8, 16, 18576, 956, \"greedy_by_size\"),\n        (16, 16, 18576, 956, \"greedy_by_size\"),\n        (256, 16, 19392, 956, \"greedy_by_size\"),\n        (8, 256, 18576, 1804, \"greedy_by_size\"),\n        (16, 256, 18576, 1804, \"greedy_by_size\"),\n        (256, 256, 19392, 1804, \"greedy_by_size\"),\n        (8, 8, 11424, 948, \"hill_climb\"),\n        (16, 8, 11424, 948, \"hill_climb\"),\n        (256, 8, 11920, 948, \"hill_climb\"),\n        (8, 16, 11424, 956, \"hill_climb\"),\n        (16, 16, 11424, 956, \"hill_climb\"),\n        (256, 16, 11920, 956, \"hill_climb\"),\n        (8, 256, 11424, 1804, \"hill_climb\"),\n        (16, 256, 11424, 1804, \"hill_climb\"),\n        (256, 256, 11920, 1804, \"hill_climb\"),\n    ],\n)\ndef test_memory_planning(\n    workspace_byte_alignment,\n    constant_byte_alignment,\n    main_workspace_size,\n    main_constant_size,\n    usmp_algo,\n):\n    \"\"\"Checks calculated workspace against known values\"\"\"\n    random.seed(0)\n    mod, params = tvm.relay.testing.synthetic.get_workload()\n    target = \"c\"\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"workspace-byte-alignment\": workspace_byte_alignment,\n            \"constant-byte-alignment\": constant_byte_alignment,\n        },\n    )\n    with tvm.transform.PassContext(\n        opt_level=3,\n        config={\n            \"tir.disable_vectorize\": True,\n            \"tir.disable_storage_rewrite\": True,\n            \"tir.usmp.enable\": True,\n            \"tir.usmp.algorithm\": usmp_algo,\n        },\n    ):\n        lib = tvm.relay.build(mod, target, executor=executor, runtime=runtime, params=params)\n    # The workspace_size dictionary will have an entry for both the 'primitive' and 'host'\n    # targets, though both are identical.\n    assert (\n        sum(lib.function_metadata[\"__tvm_main__\"].workspace_sizes.values()) == main_workspace_size\n    )\n    assert sum(lib.function_metadata[\"__tvm_main__\"].constant_sizes.values()) == main_constant_size\n\n\n@parametrize_aot_options\n@pytest.mark.parametrize(\"groups,weight_shape\", [(1, 32), (32, 1)])\ndef test_conv2d(interface_api, use_unpacked_api, test_runner, groups, weight_shape):\n    \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, weight_shape, 3, 3)\n    pass_config = {\"tir.usmp.enable\": True}\n    test_runner = AOTTestRunner(\n        makefile=test_runner.makefile,\n        prologue=test_runner.prologue,\n        epilogue=test_runner.epilogue,\n        includes=test_runner.includes,\n        parameters=test_runner.parameters,\n        pass_config=pass_config,\n    )\n\n    data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight0 = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=groups)\n    main_f = relay.Function([data0, weight0], out)\n    mod = tvm.IRModule()\n    mod[\"main\"] = main_f\n    mod = transform.InferType()(mod)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, wshape).astype(dtype)\n\n    inputs = OrderedDict([(\"data\", i_data), (\"weight\", w1_data)])\n\n    output_list = generate_ref_data(mod, inputs)\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n    compiled_test_mods = compile_models(\n        models=AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\"merge_compiler_regions\", [False, True])\ndef test_byoc_microtvm(merge_compiler_regions):\n    \"\"\"\n    This is a simple test to check BYOC capabilities of AOT\n    with and without merging compiler regions to test for https://github.com/apache/tvm/issues/9036\n    \"\"\"\n    use_unpacked_api = False\n    interface_api = \"packed\"\n    test_runner = AOTTestRunner(pass_config={\"tir.usmp.enable\": True})\n\n    input_x = relay.var(\"x\", shape=(10, 10))\n    input_w0 = relay.var(\"w0\", shape=(10, 10))\n    input_w1 = relay.var(\"w1\", shape=(10, 10))\n\n    # z0 = x + w0\n    marked_input_x = compiler_begin(input_x, \"ccompiler\")\n    marked_input_w0 = compiler_begin(input_w0, \"ccompiler\")\n    add_x_and_w0 = relay.add(marked_input_x, marked_input_w0)\n    end_inner_add = compiler_end(add_x_and_w0, \"ccompiler\")\n\n    # z1 = z0 + w1\n    marked_inner_add = compiler_begin(end_inner_add, \"ccompiler\")\n    marked_w1 = compiler_begin(input_w1, \"ccompiler\")\n    add_nested_and_w1 = relay.add(marked_inner_add, marked_w1)\n    end_outer_add = compiler_end(add_nested_and_w1, \"ccompiler\")\n\n    # z2 = z0 + z1\n    final_add = relay.add(end_inner_add, end_outer_add)\n\n    relay_func = relay.Function([input_x, input_w0, input_w1], final_add)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay_func\n\n    if merge_compiler_regions:\n        mod = transform.MergeCompilerRegions()(mod)\n\n    mod = transform.PartitionGraph(\"mod_name\")(mod)\n    mod = transform.InferType()(mod)\n\n    x_data = [(\"x\", np.random.rand(10, 10).astype(\"float32\"))]\n    w_data = [(\"w{}\".format(i), np.random.rand(10, 10).astype(\"float32\")) for i in range(2)]\n\n    map_inputs = OrderedDict(x_data + w_data)\n    output_list = generate_ref_data(mod, map_inputs)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(name=\"my_mod\", module=mod, inputs=map_inputs, outputs=output_list),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\nMOBILENET_V1_URL = (\n    \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n    + \"mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz\",\n    \"mobilenet_v1_1.0_224_quant.tflite\",\n)\nMOBILENET_V2_URL = (\n    \"https://storage.googleapis.com/download.tensorflow.org/models/\"\n    + \"tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz\",\n    \"mobilenet_v2_1.0_224_quant.tflite\",\n)\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo, workspace_size, constant_size\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\", 4845696, 8468008),\n        (MOBILENET_V1_URL, \"greedy_by_conflicts\", 4845696, 8468008),\n        (MOBILENET_V1_URL, \"hill_climb\", 3240064, 8468008),\n    ],\n)\ndef test_tflite_model_u1_usecase(model_url, usmp_algo, workspace_size, constant_size):\n    \"\"\"\n    This checks for ML models and the memory used by them\n    when using USMP with different algorithms\n    \"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo}\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    # Checking the workspace size reported in model library format\n    mlf_memory_map = mlf._build_function_memory_map(\n        compiled_test_mods[0].executor_factory.function_metadata\n    )\n    assert mlf_memory_map[\"main\"][0][\"workspace_size_bytes\"] == workspace_size\n    assert mlf_memory_map[\"main\"][0][\"constants_size_bytes\"] == constant_size\n    # That should match to workspace size that will be codegen'd to the entry point.\n    allocated_pool_info_size = sum(\n        [\n            _.allocated_size\n            for _ in list(\n                dict(\n                    compiled_test_mods[0].executor_factory.executor_codegen_metadata.pool_inputs\n                ).values()\n            )\n        ]\n    )\n    assert allocated_pool_info_size == workspace_size + constant_size\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\ndef _get_workspace_size_define_macro(pool_name: str, model_name=\"default\") -> str:\n    \"\"\"This function converts pool names to compiler generated\n    pool size macros\"\"\"\n\n    prefix = \"TVMGEN_\" + model_name.upper() + \"_\"\n    postfix = \"_WORKSPACE_POOL_SIZE\"\n    return prefix + pool_name.upper() + postfix\n\n\ndef _get_constant_size_define_macro(pool_name: str, model_name=\"default\") -> str:\n    \"\"\"This function converts pool names to compiler generated\n    pool size macros\"\"\"\n\n    prefix = \"TVMGEN_\" + model_name.upper() + \"_\"\n    postfix = \"_CONSTANT_POOL_SIZE\"\n    return prefix + pool_name.upper() + postfix\n\n\ndef _get_constant_data_define_macro(pool_name: str, model_name=\"default\") -> str:\n    \"\"\"This function converts pool names to compiler generated\n    pool data macros\"\"\"\n\n    prefix = \"TVMGEN_\" + model_name.upper() + \"_\"\n    postfix = \"_CONSTANT_POOL_DATA\"\n    return prefix + pool_name.upper() + postfix\n\n\ndef _add_module_prefix(suffix: str, model_name=\"default\") -> str:\n    \"\"\"A helper function create struct types\"\"\"\n    return \"tvmgen_\" + model_name + \"_\" + suffix\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\"),\n    ],\n)\ndef test_tflite_model_u3_usecase_single_external_pool(model_url, usmp_algo):\n    \"\"\"This checks for inference with USMP using external pool placed in the application\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    pool_name = \"my_memory_pool\"\n    target = tvm.target.Target(\"c\")\n    workspace_memory_pools = WorkspaceMemoryPools([WorkspacePoolInfo(pool_name, [target])])\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo},\n        prologue=f\"\"\"\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t {pool_name}[{_get_workspace_size_define_macro(pool_name)}];\n        \"\"\",\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_memory_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"usmp_algo\",\n    [(\"greedy_by_size\"), (\"hill_climb\")],\n)\ndef test_tflite_model_u3_usecase_conv2d_var_cons(usmp_algo):\n    \"\"\"This checks for inference using workspace and constant pools placed in the application\"\"\"\n\n    mod = tvm.parser.fromtext(\n        \"\"\"\\\n        #[version = \"0.0.5\"]\n        def @main(%data : Tensor[(1, 3, 64, 64), uint8], %weight : Tensor[(3, 3, 5, 5), int8]) {\n            %1 = nn.conv2d(\n                 %data,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %2 = cast(nn.max_pool2d(%1, pool_size=[3, 3]), dtype=\"int8\");\n            %3 = nn.conv2d(\n                 %2,\n                 %weight,\n                 padding=[2, 2],\n                 channels=3,\n                 kernel_size=[5, 5],\n                 data_layout=\"NCHW\",\n                 kernel_layout=\"OIHW\",\n                 out_dtype=\"int32\");\n            %4 = nn.max_pool2d(%3, pool_size=[3, 3]);\n            %4\n        }\n    \"\"\"\n    )\n\n    main_func = mod[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    weight_data = np.random.randint(1, 255, shape_dict[\"weight\"]).astype(type_dict[\"weight\"])\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n    params = {\"weight\": weight_data}\n    inputs = {\"data\": input_data}\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    target = tvm.target.Target(\"c\")\n    workspace_mem_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"my_memory_pool_1\", [target], PoolInfoProperties(size_hint_bytes=8500000)\n            ),\n        ]\n    )\n\n    constant_mem_pools = ConstantMemoryPools(\n        [\n            ConstantPoolInfo(\"my_const_pool_1\", [target], []),\n        ]\n    )\n\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo},\n        prologue=f\"\"\"\n        __attribute__((section(\".bss.noinit\"), aligned(TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)))\n        static uint8_t my_memory_pool_1[{_get_workspace_size_define_macro(\"my_memory_pool_1\")}];\n        __attribute__((section(\".rodata.tvm\"), aligned(TVM_RUNTIME_CONST_ALLOC_ALIGNMENT_BYTES)))\n        static uint8_t my_const_pool_1[{_get_constant_size_define_macro(\"my_const_pool_1\")}] = {{ {_get_constant_data_define_macro(\"my_const_pool_1\")} }};\n        \"\"\",\n    )\n\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_mem_pools,\n        constant_memory_pools=constant_mem_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\"),\n    ],\n)\ndef test_tflite_model_u3_usecase_var_cons_ext_pools(model_url, usmp_algo):\n    \"\"\"This checks for inference using one external workspace and one external constant\n    pools placed in the application\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    target = tvm.target.Target(\"c\")\n    workspace_mem_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"my_memory_pool_1\", [target], PoolInfoProperties(size_hint_bytes=8500000)\n            ),\n        ]\n    )\n\n    constant_mem_pools = ConstantMemoryPools(\n        [\n            ConstantPoolInfo(\"my_const_pool_1\", [target], []),\n        ]\n    )\n\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo},\n        prologue=f\"\"\"\n        __attribute__((section(\".bss.noinit\"), aligned(TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)))\n        static uint8_t my_memory_pool_1[{_get_workspace_size_define_macro(\"my_memory_pool_1\")}];\n        __attribute__((section(\".rodata.tvm\"), aligned(TVM_RUNTIME_CONST_ALLOC_ALIGNMENT_BYTES)))\n        static uint8_t my_const_pool_1[{_get_constant_size_define_macro(\"my_const_pool_1\")}] = {{ {_get_constant_data_define_macro(\"my_const_pool_1\")} }};\n        \"\"\",\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_mem_pools,\n        constant_memory_pools=constant_mem_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\"),\n    ],\n)\ndef test_tflite_model_u3_usecase_two_external_pools(model_url, usmp_algo):\n    \"\"\"This checks for inference using two external pools placed in the application\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    target = tvm.target.Target(\"c\")\n    workspace_memory_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"my_memory_pool_1\", [target], PoolInfoProperties(size_hint_bytes=2500000)\n            ),\n            WorkspacePoolInfo(\"my_memory_pool_2\", [target]),\n        ]\n    )\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo},\n        prologue=f\"\"\"\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t my_memory_pool_1[{_get_workspace_size_define_macro(\"my_memory_pool_1\")}];\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t my_memory_pool_2[{_get_workspace_size_define_macro(\"my_memory_pool_2\")}];\n        \"\"\",\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_memory_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"model_urls, usmp_algo\",\n    [\n        ((MOBILENET_V1_URL, MOBILENET_V2_URL), \"greedy_by_size\"),\n    ],\n)\ndef test_two_models_with_a_single_external_pool(model_urls, usmp_algo):\n    \"\"\"This checks for inference using a single large enough common pool\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    target = tvm.target.Target(\"c\")\n    workspace_memory_pools = WorkspaceMemoryPools([WorkspacePoolInfo(\"my_memory_pool\", [target])])\n    test_runner = AOTTestRunner(\n        pass_config={\"tir.usmp.enable\": True, \"tir.usmp.algorithm\": usmp_algo},\n        prologue=f\"\"\"\n        #define MAX(A, B) ((A > B) ? A : B)\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t my_memory_pool[MAX({_get_workspace_size_define_macro(\"my_memory_pool\", \"mod1\")},{_get_workspace_size_define_macro(\"my_memory_pool\", \"mod2\")})];\n        \"\"\",\n    )\n\n    tflite_model_file1 = tf_testing.get_workload_official(\n        model_urls[0][0],\n        model_urls[0][1],\n    )\n    mod1, inputs1, params1 = create_relay_module_and_inputs_from_tflite_file(tflite_model_file1)\n    output_list1 = generate_ref_data(mod1, inputs1, params1)\n\n    tflite_model_file2 = tf_testing.get_workload_official(\n        model_urls[1][0],\n        model_urls[1][1],\n    )\n    mod2, inputs2, params2 = create_relay_module_and_inputs_from_tflite_file(tflite_model_file2)\n    output_list2 = generate_ref_data(mod2, inputs2, params2)\n\n    compiled_test_mods = compile_models(\n        [\n            AOTTestModel(\n                name=\"mod1\", module=mod1, inputs=inputs1, outputs=output_list1, params=params1\n            ),\n            AOTTestModel(\n                name=\"mod2\", module=mod2, inputs=inputs2, outputs=output_list2, params=params2\n            ),\n        ],\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_memory_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n    )\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\"),\n    ],\n)\ndef test_tflite_model_u4_usecase_single_external_pool(model_url, usmp_algo):\n    \"\"\"This checks for inference with USMP using external pool placed in the application\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    pool_name = \"my_memory_pool\"\n    target = tvm.target.Target(\"c\")\n    workspace_memory_pools = WorkspaceMemoryPools([WorkspacePoolInfo(pool_name, [target])])\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    input_name, input_data = list(inputs.items())[0]\n    input_size_bytes = input_data.size * input_data.itemsize\n    test_runner = AOTTestRunner(\n        pass_config={\n            \"tir.usmp.enable\": True,\n            \"tir.usmp.algorithm\": usmp_algo,\n            \"tir.usmp.use_workspace_io\": True,\n        },\n        prologue=f\"\"\"\n        #include <string.h>\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t {pool_name}[{_get_workspace_size_define_macro(pool_name)}];\n        struct {_add_module_prefix(\"workspace_pools\")} {_add_module_prefix(\"workspace_pools\")} = {{\n            .{pool_name} = {pool_name}\n        }};\n        struct {_add_module_prefix(\"inputs\")} {_add_module_prefix(\"inputs\")} = {_add_module_prefix(\"map_inputs\")}(&{_add_module_prefix(\"workspace_pools\")});\n        memcpy({_add_module_prefix(\"inputs\")}.{input_name}, tvmgen_default_input_data_input, {input_size_bytes});\n        struct {_add_module_prefix(\"outputs\")} {_add_module_prefix(\"outputs\")} = {_add_module_prefix(\"map_outputs\")}(&{_add_module_prefix(\"workspace_pools\")});\n        \"\"\",\n    )\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_memory_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n        use_workspace_io=True,\n    )\n\n\n@pytest.mark.parametrize(\n    \"model_url, usmp_algo\",\n    [\n        (MOBILENET_V1_URL, \"greedy_by_size\"),\n    ],\n)\ndef test_tflite_model_u4_usecase_two_external_pools(model_url, usmp_algo):\n    \"\"\"This checks for inference with USMP using external pool placed in the application\"\"\"\n    pytest.importorskip(\"tflite\")\n\n    import tvm.relay.testing.tf as tf_testing  # pylint: disable=import-outside-toplevel\n\n    use_unpacked_api = True\n    interface_api = \"c\"\n\n    target = tvm.target.Target(\"c\")\n    workspace_memory_pools = WorkspaceMemoryPools(\n        [\n            WorkspacePoolInfo(\n                \"my_memory_pool_1\", [target], PoolInfoProperties(size_hint_bytes=2500000)\n            ),\n            WorkspacePoolInfo(\"my_memory_pool_2\", [target]),\n        ]\n    )\n\n    tflite_model_file = tf_testing.get_workload_official(\n        model_url[0],\n        model_url[1],\n    )\n    mod, inputs, params = create_relay_module_and_inputs_from_tflite_file(tflite_model_file)\n    output_list = generate_ref_data(mod, inputs, params)\n\n    input_name, input_data = list(inputs.items())[0]\n    input_size_bytes = input_data.size * input_data.itemsize\n    test_runner = AOTTestRunner(\n        pass_config={\n            \"tir.usmp.enable\": True,\n            \"tir.usmp.algorithm\": usmp_algo,\n            \"tir.usmp.use_workspace_io\": True,\n        },\n        prologue=f\"\"\"\n        #include <string.h>\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t my_memory_pool_1[{_get_workspace_size_define_macro(\"my_memory_pool_1\")}];\n        __attribute__((section(\".data.tvm\"), aligned(16)))\n        static uint8_t my_memory_pool_2[{_get_workspace_size_define_macro(\"my_memory_pool_2\")}];\n        struct {_add_module_prefix(\"workspace_pools\")} {_add_module_prefix(\"workspace_pools\")} = {{\n            .my_memory_pool_1 = my_memory_pool_1,\n            .my_memory_pool_2 = my_memory_pool_2,\n        }};\n        struct {_add_module_prefix(\"inputs\")} {_add_module_prefix(\"inputs\")} = {_add_module_prefix(\"map_inputs\")}(&{_add_module_prefix(\"workspace_pools\")});\n        memcpy({_add_module_prefix(\"inputs\")}.{input_name}, tvmgen_default_input_data_input, {input_size_bytes});\n        struct {_add_module_prefix(\"outputs\")} {_add_module_prefix(\"outputs\")} = {_add_module_prefix(\"map_outputs\")}(&{_add_module_prefix(\"workspace_pools\")});\n        \"\"\",\n    )\n\n    compiled_test_mods = compile_models(\n        AOTTestModel(module=mod, inputs=inputs, outputs=output_list, params=params),\n        interface_api=interface_api,\n        use_unpacked_api=use_unpacked_api,\n        pass_config=test_runner.pass_config,\n        workspace_memory_pools=workspace_memory_pools,\n        target=target,\n    )\n\n    for compiled_model in compiled_test_mods:\n        _check_for_no_tvm_backendallocworkspace_calls(compiled_model.executor_factory.lib)\n\n    run_and_check(\n        models=compiled_test_mods,\n        runner=test_runner,\n        interface_api=interface_api,\n        use_workspace_io=True,\n    )\n\n\ndef test_incompatible_interface_api_errors():\n    \"\"\"Ensures an error is thrown if not using the C interface API\"\"\"\n    mod, params = tvm.relay.testing.synthetic.get_workload()\n    target = \"c\"\n    runtime = Runtime(\"crt\")\n    executor = Executor(\n        \"aot\",\n        {\n            \"interface-api\": \"packed\",\n        },\n    )\n\n    with pytest.raises(\n        tvm.TVMError,\n        match=re.escape(\n            \"tir.usmp.use_workspace_io option is only compatible with interface_api c.\\n\"\n            \"Please use interface_api c to be able to enable tir.usmp.use_workspace_io\"\n        ),\n    ):\n        with tvm.transform.PassContext(\n            opt_level=3,\n            config={\"tir.usmp.enable\": True, \"tir.usmp.use_workspace_io\": True},\n        ):\n            tvm.relay.build(mod, target, executor=executor, runtime=runtime, params=params)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/aot/test_pass_aot_lower_main.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=line-too-long,missing-class-docstring,missing-module-docstring,missing-function-docstring,no-self-argument,unused-argument,invalid-name\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm.ir import assert_structural_equal\nfrom tvm.relay.backend.aot import AOTLowerMain, CallType\nfrom tvm.script import tir as T\n\n\ndef _make_const(dtype, shape):\n    return tvm.relay.const(np.zeros(shape).astype(dtype))\n\n\ndef _make_consts(dtype, shapes):\n    return [_make_const(dtype, shape) for shape in shapes]\n\n\ndef _plan_devices(mod):\n    host_target = tvm.target.Target(\"llvm\")\n    prim_target = tvm.target.Target(\"llvm\", host=host_target)\n    ctxt = tvm.transform.PassContext()\n    config = tvm.target.make_compilation_config(ctxt, prim_target)\n    mod = tvm.relay.transform.PlanDevices(config)(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n    return mod, config\n\n\ndef _assert_lowered_main(mod, main_func, call_type, print_script=False):\n    mod, config = _plan_devices(mod)\n    mod = AOTLowerMain(\"test_mod\", config, call_type)(mod)\n    if print_script:\n        print(mod[\"__tvm_main__\"].script())\n\n    assert_structural_equal(mod[\"__tvm_main__\"], main_func)\n\n\ndef test_single_call_cpacked():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,) /* ty=(Tensor[(5, 7), float32],) */;\n  call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_single_call_packed():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,) /* ty=(Tensor[(5, 7), float32],) */;\n  call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_check_return(0, -1, T.tvm_call_packed(\"test_fused_add\", a_buffer.data, output_buffer.data, dtype=\"int32\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.Packed)\n\n\ndef test_single_call_unpacked():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,) /* ty=(Tensor[(5, 7), float32],) */;\n  call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"test_fused_add\", a_buffer.data, output_buffer.data, dtype=\"int32\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.Unpacked)\n\n\ndef test_constant():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a, meta[relay.Constant][0]) /* ty=(Tensor[(5, 7), float32], Tensor[(5, 7), float32]) */;\n  call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n        init_meta_table={\"relay.Constant\": _make_consts(\"float32\", [(5, 7)])},\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"global_symbol\": \"test_mod___tvm_main__\", \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        constant_0 = T.allocate_const([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, 0, 0, 0], \"float32\", [5, 7])\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, constant_0, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\n# TODO(@mbaret) There seems to be a TVMScript round-trip bug causing this to fail\n@pytest.mark.xfail()\ndef test_copy_to_output():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %a\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        tmp_read = T.buffer_var(\"uint8\", \"\")\n        # buffer definition\n        tmp_read_1 = T.buffer_decl([T.uint64(140)], dtype=\"uint8\", data=tmp_read)\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        tmp_write: T.Ptr[T.uint8] = output_buffer.data\n        tmp_write_1 = T.buffer_decl([T.uint64(140)], dtype=\"uint8\", data=tmp_write)\n        for i in T.serial(140):\n            tmp_write_1[i] = T.let(tmp_read, a_buffer.data, tmp_read_1[i])\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_two_calls():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,) /* ty=(Tensor[(5, 7), float32],) */;\n  %1 = call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */;\n  %2 = (%1,) /* ty=(Tensor[(5, 7), float32],) */;\n  call_lowered(@test_fused_add, %2) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, sid_2, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", sid_2, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_tuple_output():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) { (%x, %x) }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> (Tensor[(5, 7), float32], Tensor[(5, 7), float32]) {\n  %0 = (%a,) /* ty=(Tensor[(5, 7), float32],) */;\n  call_lowered(@test_fused_add, %0) /* ty=(Tensor[(5, 7), float32], Tensor[(5, 7), float32]) */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output0: T.handle, output1: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output0, output1], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output0_buffer = T.match_buffer(output0, [5, 7], dtype=\"float32\", align=16)\n        output1_buffer = T.match_buffer(output1, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, output0_buffer.data, output1_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_tuple_intermediate():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add_0(%x: Tensor[(5, 7), float32]) -> (Tensor[(5, 7), float32], Tensor[(5, 7), float32]) { (%x, %x) }\ndef @test_fused_add_1(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,);\n  %1 = call_lowered(@test_fused_add_0, %0);\n  %2 = (%1.0, %1.1);\n  call_lowered(@test_fused_add_1, %2)\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n        sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_multi_input():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) { %x }\n\ndef @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a, %b) /* ty=(Tensor[(5, 7), float32], Tensor[(5, 7), float32]) */;\n  call_lowered(@test_fused_add, %0) /* ty=Tensor[(5, 7), float32] */\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, b: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a, b], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        b_buffer = T.match_buffer(b, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, b_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_let_binding():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,);\n  let %v1 = call_lowered(@test_fused_add, %0);\n  %v1\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_let_binding_branch():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add_0(%x: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] { %x }\ndef @test_fused_add_1(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,);\n  let %v0 = call_lowered(@test_fused_add_0, %0);\n  %1 = (%v0,);\n  let %v1 = call_lowered(@test_fused_add_0, %1);\n  %2 = (%v1,);\n  let %v2 = call_lowered(@test_fused_add_0, %2);\n  %3 = (%v1, %v2);\n  let %v3 = call_lowered(@test_fused_add_1, %3);\n  %v3\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": []})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        sid_3 = T.allocate([140], \"int8\", \"global.workspace\")\n        sid_2 = T.allocate([140], \"int8\", \"global.workspace\")\n        sid_1 = T.allocate([140], \"int8\", \"global.workspace\")\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", a_buffer.data, sid_1, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_1, sid_2, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_0\", sid_2, sid_3, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"test_fused_add_1\", sid_2, sid_3, output_buffer.data, T.reinterpret(T.uint64(0), dtype=\"handle\"), dtype=\"int32\"))\n    # fmt: on\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\ndef test_device_hooks():\n    mod = tvm.parser.parse(\n        \"\"\"\n#[version = \"0.0.5\"]\ndef @test_fused_add(%x: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] { %x }\n\ndef @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n  %0 = (%a,);\n  %1 = call_lowered(@test_fused_add, %0);\n  %2 = (%1,);\n  call_lowered(@test_fused_add, %2)\n}\n        \"\"\",\n    )\n\n    # fmt: off\n    @T.prim_func\n    def func(a: T.handle, output: T.handle, device_context_example_target_hook: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_mod___tvm_main__\", \"runner_function\": True, \"target\": T.target({\"kind\":\"llvm\", \"tag\":\"\", \"keys\":[\"cpu\"]}), \"input_vars\": [a], \"output_vars\": [output], \"devices\": [\"example_target_hook\"]})\n        a_buffer = T.match_buffer(a, [5, 7], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [5, 7], dtype=\"float32\", align=16)\n        # body\n        T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookActivate\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n        with T.allocate([140], \"int8\", \"global.workspace\") as sid_2:\n            T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookOpen\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", a_buffer.data, sid_2, device_context_example_target_hook, dtype=\"int32\"))\n            T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookClose\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookOpen\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n            T.evaluate(T.tvm_call_cpacked(\"test_fused_add\", sid_2, output_buffer.data, device_context_example_target_hook, dtype=\"int32\"))\n            T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookClose\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n        T.evaluate(T.tvm_check_return(0, -1, T.call_extern(\"TVMDeviceExampleTargetHookDeactivate\", device_context_example_target_hook, dtype=\"int32\"), dtype=\"int32\"))\n    # fmt: on\n\n    device_contexts = {}\n    for gv in mod.get_global_vars():\n        device_contexts[gv] = \"example_target_hook\"\n\n    mod = mod.with_attr(\"device_contexts\", device_contexts)\n\n    _assert_lowered_main(mod, func, CallType.CPacked)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/backend/test_pass_lower_te.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Exercises the LowerTE pass.\n\nimport tvm\nimport tvm.testing\nimport logging\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"test_pass_lower_te\")\nlogger.setLevel(logging.INFO)\n\n# Since the TE compiler needs a good refactor it has not been exposed as a 'standard' pass\n# in relay.transform. For testing grab it directly.\nLowerTE = tvm._ffi.get_global_func(\"relay.tec.LowerTE\")\n\n\ndef transform(mod):\n    logger.info(\"Starting module:\\n%s\", mod)\n    host_target = tvm.target.Target(\"llvm\")\n    prim_target = tvm.target.Target(\"llvm\", host=host_target)\n    ctxt = tvm.transform.PassContext()\n    config = tvm.target.make_compilation_config(ctxt, prim_target)\n    mod = tvm.relay.transform.PlanDevices(config)(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod = LowerTE(\"test\", config)(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n    logger.info(\"After LowerTE:\\n%s\", mod)\n    return mod\n\n\n# All attempts to use structural equalty tests against an expected IRModule parsed from\n# Relay text were thwarted by the difficulty of setting up the expected call_lower attributes\n# with the right GlobalVar instances. So the following assert structural correctness the hard way.\n\n\ndef test_lower_primitive():\n    input_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n          %0 = fn(%x : Tensor[(5, 7), float32], %y : Tensor[(5, 7), float32], Primitive=1) -> Tensor[(5, 7), float32] {\n            add(%x, %y)\n          };\n          %0(%a, %a)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        None,\n    )\n\n    actual_mod = transform(input_mod)\n\n    # Expected:\n    #   def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n    #     %0 = (%a, %a);\n    #     call_lowered(@test_fused_add, %0, metadata={relay_attrs={Primitive=1},all_prim_fn_vars=[@test_fused_add]})\n    #   }\n    #   def @test_fused_add = <lowered PrimFunc>\n\n    main = actual_mod[\"main\"]\n    call = main.body\n    assert call.op.name == \"call_lowered\"\n    assert len(call.args) == 2\n    assert call.args[0].name_hint == \"test_fused_add\"\n    assert len(call.args[1].fields) == 2\n    assert call.args[1].fields[0].name_hint == \"a\"\n    assert call.args[1].fields[1].name_hint == \"a\"\n    assert call.attrs.metadata[\"relay_attrs\"].Primitive == 1\n    assert len(call.attrs.metadata[\"all_prim_fn_vars\"]) == 1\n    assert call.attrs.metadata[\"all_prim_fn_vars\"][0].name_hint == \"test_fused_add\"\n\n    test_fused_add = actual_mod[\"test_fused_add\"]\n    assert isinstance(test_fused_add, tvm.tir.PrimFunc)\n\n\ndef test_lower_compiler():\n    @tvm._ffi.register_func(\"relay.ext.test_pass_lower_te\")\n    def relay_ext_test_pass_lower_te(func):\n        return None\n\n    input_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n          %0 = fn(%x : Tensor[(5, 7), float32], %y : Tensor[(5, 7), float32], Primitive=1, Compiler=\"test_pass_lower_te\", global_symbol=\"test_add\") -> Tensor[(5, 7), float32] {\n            add(%x, %y)\n          };\n          %0(%a, %a)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        None,\n    )\n\n    actual_mod = transform(input_mod)\n\n    # Expected:\n    #   def @main(%a : Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n    #     %0 = (%a, %a)\n    #     call_lowered(@test_add , %0, metadata={relay_attrs={Primitive=1, Compiler=\"test_pass_lower_te\", global_symbol=\"test_add\"}}, all_prim_fn_vars=[]})\n    #   }\n    #   def @test_add(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32], Extern=1) -> Tensor[(5, 7), float32] {\n    #     add(%x, %y)\n    #   }\n\n    main = actual_mod[\"main\"]\n    call = main.body\n    assert call.op.name == \"call_lowered\"\n    assert len(call.args) == 2\n    assert call.args[0].name_hint == \"test_add\"\n    assert len(call.args[1].fields) == 2\n    assert call.args[1].fields[0].name_hint == \"a\"\n    assert call.args[1].fields[1].name_hint == \"a\"\n    assert call.attrs.metadata[\"relay_attrs\"].Primitive == 1\n    assert call.attrs.metadata[\"relay_attrs\"].Compiler == \"test_pass_lower_te\"\n    assert call.attrs.metadata[\"relay_attrs\"].global_symbol == \"test_add\"\n    assert len(call.attrs.metadata[\"all_prim_fn_vars\"]) == 0\n\n    test_add = actual_mod[\"test_add\"]\n    assert isinstance(test_add, tvm.relay.Function)\n    assert test_add.attrs[\"Extern\"] == 1\n\n\ndef test_lower_extern():\n    input_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n          @my_add(%a, %a)\n        }\n        def @my_add(%x : Tensor[(5, 7), float32], %y : Tensor[(5, 7), float32], Extern=1) -> Tensor[(5, 7), float32] {\n          add(%x, %y)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        None,\n    )\n\n    actual_mod = transform(input_mod)\n\n    # Expected:\n    #   def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n    #     %0 = (%a, %a);\n    #     call_lowered(@my_add, %0, metadata={relay_attrs={Extern=1}}, all_prim_fn_vars=[]})\n    #   }\n    #   def @my_add(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32], Extern=1) -> Tensor[(5, 7), float32] {\n    #     add(%x, %y)\n    #   }\n\n    main = actual_mod[\"main\"]\n    call = main.body\n    assert call.op.name == \"call_lowered\"\n    assert len(call.args) == 2\n    assert call.args[0].name_hint == \"my_add\"\n    assert len(call.args[1].fields) == 2\n    assert call.args[1].fields[0].name_hint == \"a\"\n    assert call.args[1].fields[1].name_hint == \"a\"\n    assert call.attrs.metadata[\"relay_attrs\"].Extern == 1\n    assert len(call.attrs.metadata[\"all_prim_fn_vars\"]) == 0\n\n    test_add = actual_mod[\"my_add\"]\n    assert isinstance(test_add, tvm.relay.Function)\n    assert test_add.attrs[\"Extern\"] == 1\n\n\ndef test_lower_extern_with_dynamic_shape():\n    input_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(?, ?), float32] {\n          @my_dyn(%a, %a)\n        }\n        def @my_dyn(%x : Tensor[(5, 7), float32], %y : Tensor[(5, 7), float32], Extern=1) -> Tensor[(?, ?), float32] {\n          add(%x, %y)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        None,\n    )\n\n    actual_mod = transform(input_mod)\n\n    # Expected:\n    # def @main(%a: Tensor[(5, 7), float32]) -> Tensor[(?, ?), float32] {\n    #   %0 = (%a, %a);\n    #   call_lowered(@my_dyn, %0, metadata={prim_shape_fn_var='test_shape_func_add', relay_attrs={Extern=1}, prim_shape_fn_states=[2, 2], prim_shape_fn_num_inputs=2, all_prim_shape_fn_vars=['shape_func_add'], prim_shape_fn_num_outputs=1, all_prim_fn_vars=[]})\n    # }\n    # def @my_dyn(%x: Tensor[(5, 7), float32] , %y: Tensor[(5, 7), float32] , Extern=1) -> Tensor[(?, ?), float32] {\n    #   add(%x, %y)\n    # }\n    # def @test_shape_func_add = <shape PrimFunc>\n\n    main = actual_mod[\"main\"]\n    call = main.body\n    assert call.op.name == \"call_lowered\"\n    assert len(call.args) == 2\n    assert call.args[0].name_hint == \"my_dyn\"\n    assert len(call.args[1].fields) == 2\n    assert call.args[1].fields[0].name_hint == \"a\"\n    assert call.args[1].fields[1].name_hint == \"a\"\n    assert call.attrs.metadata[\"prim_shape_fn_var\"].name_hint == \"test_shape_func_add\"\n    assert call.attrs.metadata[\"relay_attrs\"].Extern == 1\n    assert len(call.attrs.metadata[\"prim_shape_fn_states\"]) == 2\n    assert call.attrs.metadata[\"prim_shape_fn_states\"][0] == 2\n    assert call.attrs.metadata[\"prim_shape_fn_states\"][1] == 2\n    assert call.attrs.metadata[\"prim_shape_fn_num_inputs\"] == 2\n    assert len(call.attrs.metadata[\"all_prim_shape_fn_vars\"]) == 1\n    assert call.attrs.metadata[\"all_prim_shape_fn_vars\"][0].name_hint == \"test_shape_func_add\"\n    assert call.attrs.metadata[\"prim_shape_fn_num_outputs\"] == 1\n    assert len(call.attrs.metadata[\"all_prim_fn_vars\"]) == 0\n\n    my_dyn = actual_mod[\"my_dyn\"]\n    assert isinstance(my_dyn, tvm.relay.Function)\n    assert my_dyn.attrs[\"Extern\"] == 1\n\n    shape_func_add = actual_mod[\"test_shape_func_add\"]\n    assert isinstance(shape_func_add, tvm.tir.PrimFunc)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/backend/test_pass_remove_standalone_reshapes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Exercises the RemoveStandaloneReshapes pass.\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.expr_functor import ExprMutator\nimport tvm.testing\nfrom tvm.script import tir as T\n\n\nHOST_DEVICE = tvm.device(\"cpu\")\nHOST_TARGET = tvm.target.Target(\"llvm\")\n\nCPU_DEVICE = tvm.device(\"cpu\")\nCPU_TARGET = tvm.target.Target(\"llvm\").with_host(HOST_TARGET)\n\nCPU = tvm.target.VirtualDevice(CPU_DEVICE, CPU_TARGET)  # device_type=1\n\n\nRemoveStandaloneReshapes = tvm._ffi.get_global_func(\"relay._transform.RemoveStandaloneReshapes\")\n\n\nclass MarkReshapeOnlyMutator(ExprMutator):\n    \"\"\"A pass for marking call_lowered as ReshapeOnly where reshapes exist unfused\"\"\"\n\n    def __init__(self):\n        ExprMutator.__init__(self)\n\n    def visit_call(self, call):\n        if isinstance(call.args[0], tvm.ir.GlobalVar) and \"reshape\" in call.args[0].name_hint:\n            # attrs = {\"relay_attrs\" : {\"relay.reshape_only\" : 1}}\n            dict_attrs = tvm.ir.make_node(\"DictAttrs\", **{\"relay.reshape_only\": 1})\n            attrs = tvm.ir.make_node(\n                \"relay.attrs.CallLoweredAttrs\", **{\"metadata\": {\"relay_attrs\": dict_attrs}}\n            )\n            return relay.Call(call.op, call.args, attrs)\n        return super().visit_call(call)\n\n\n# Reshape should not be removed if its the first layer in the network\ndef test_first_reshape():\n    mod = tvm.ir.IRModule()\n\n    @T.prim_func\n    def reshape_primfunc(a: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        D = T.match_buffer(d, [128, 128])\n\n        for i, j in T.grid(128, 128):\n            D[i, j] = A[i, j]\n\n    metatable = {\"VirtualDevice\": [CPU]}\n    reshape_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n\n    reshape_gv = relay.GlobalVar(\"reshape\", type_annot=reshape_ty)\n    mod[reshape_gv] = reshape_primfunc\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  virtual_device=meta[VirtualDevice][0]) {\n          %1 = call_lowered(@reshape, (%x,) );\n          let %x_14: Tensor[(128, 128), float32] = on_device(%1, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n          %x_14\n        }\n        \"\"\",\n        \"from_string\",\n        mod,\n        metatable,\n    )\n\n    mod[\"main\"] = MarkReshapeOnlyMutator().visit(mod[\"main\"])\n    mod = RemoveStandaloneReshapes()(mod)\n    reshapes_present = any([\"reshape\" in gv.name_hint for gv in mod.get_global_vars()])\n    assert reshapes_present, \"Reshape should have been removed.\"\n    return\n\n\n# When reshape layer is the last one in the network\ndef test_last_reshape():\n    mod = tvm.ir.IRModule()\n\n    @T.prim_func\n    def mul_primfunc(a: T.handle, b: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        B = T.match_buffer(b, [128, 128])\n        D = T.match_buffer(d, [128, 128])\n\n        for i, j, k in T.grid(128, 128, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                D[vi, vj] = A[vi, vk] * B[vj, vk]\n\n    @T.prim_func\n    def reshape_primfunc(a: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        D = T.match_buffer(d, [128, 128])\n\n        for i, j in T.grid(128, 128):\n            D[i, j] = A[i, j]\n\n    metatable = {\"VirtualDevice\": [CPU]}\n    mul_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n\n    mul_gv = relay.GlobalVar(\"multiply\", type_annot=mul_ty)\n    mod[mul_gv] = mul_primfunc\n    reshape_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n\n    reshape_gv = relay.GlobalVar(\"reshape\", type_annot=reshape_ty)\n    mod[reshape_gv] = reshape_primfunc\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  %z {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  virtual_device=meta[VirtualDevice][0]) {\n          %0 = call_lowered(@multiply, (%x, %y, %z));\n          let %x_12: Tensor[(128, 128), float32] = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n          %1 = call_lowered(@reshape, (%x_12,) );\n          let %x_14: Tensor[(128, 128), float32] = on_device(%1, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n          %x_14\n        }\n        \"\"\",\n        \"from_string\",\n        mod,\n        metatable,\n    )\n\n    # Expected main:\n    ##[version = \"0.0.5\"]\n    # def @main(%x /* ty=Tensor[(128, 128), float32] */) -> Tensor[(128, 128), float32] {\n    #  %0 = (%x, %y, %z);\n    #  %1 = call_lowered(@multiply, %0);\n    #  let %x_12: Tensor[(128, 128), float32] = on_device(%1, constrain_result=True);\n    #  let %x_14: Tensor[(128, 128), float32] = on_device(%1, constrain_result=True);\n    #  %x_14\n    # }\n\n    mod[\"main\"] = MarkReshapeOnlyMutator().visit(mod[\"main\"])\n    mod = RemoveStandaloneReshapes()(mod)\n    reshapes_present = any([\"reshape\" in gv.name_hint for gv in mod.get_global_vars()])\n    assert not reshapes_present, \"Reshape should have been removed.\"\n    return\n\n\n# When reshape layer is not marked as reshape_only\ndef test_fused_reshape():\n    mod = tvm.ir.IRModule()\n\n    @T.prim_func\n    def mul_primfunc(a: T.handle, b: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        B = T.match_buffer(b, [128, 128])\n        D = T.match_buffer(d, [128, 128])\n\n        for i, j, k in T.grid(128, 128, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                D[vi, vj] = A[vi, vk] * B[vj, vk]\n\n    @T.prim_func\n    def fused_reshape_primfunc(a: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        D = T.match_buffer(d, [128, 128])\n\n        for i, j in T.grid(128, 128):\n            D[i, j] = A[i, j]\n\n    metatable = {\"VirtualDevice\": [CPU]}\n    mul_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n\n    mul_gv = relay.GlobalVar(\"multiply\", type_annot=mul_ty)\n    mod[mul_gv] = mul_primfunc\n    reshape_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n\n    reshape_gv = relay.GlobalVar(\"fused_reshape\", type_annot=reshape_ty)\n    mod[reshape_gv] = fused_reshape_primfunc\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  %z {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                  virtual_device=meta[VirtualDevice][0]) {\n          %0 = call_lowered(@multiply, (%x, %y, %z));\n          let %x_12: Tensor[(128, 128), float32] = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n          %1 = call_lowered(@fused_reshape, (%x_12,) );\n          let %x_14: Tensor[(128, 128), float32] = on_device(%1, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n          %x_14\n        }\n        \"\"\",\n        \"from_string\",\n        mod,\n        metatable,\n    )\n\n    # Expected main:\n    ##[version = \"0.0.5\"]\n    # def @main(%x /* ty=Tensor[(128, 128), float32] */) -> Tensor[(128, 128), float32] {\n    #  %0 = (%x, %y, %z);\n    #  %1 = call_lowered(@multiply, %0);\n    #  let %x_12: Tensor[(128, 128), float32] = on_device(%1, constrain_result=True);\n    #  let %x_14: Tensor[(128, 128), float32] = on_device(%1, constrain_result=True);\n    #  %x_14\n    # }\n\n    mod = RemoveStandaloneReshapes()(mod)\n    reshapes_present = any([\"reshape\" in gv.name_hint for gv in mod.get_global_vars()])\n    assert reshapes_present, \"Reshape should have been removed.\"\n    return\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/benchmarking/benchmark_vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Benchmarking Relay VM using models from MXNet.\"\"\"\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import graph_executor\nfrom tvm import relay\nfrom tvm.runtime import container\nfrom tvm.runtime import vm as vm_rt\nfrom tvm.relay import testing\nfrom tvm.relay import vm\n\n\ndef benchmark_execution(\n    mod,\n    params,\n    measure=True,\n    data_shape=(1, 3, 224, 224),\n    out_shape=(1, 1000),\n    dtype=\"float32\",\n    model=\"unknown\",\n):\n    def get_graph_executor_output(\n        mod, data, params, target, dev, dtype=\"float32\", number=2, repeat=20\n    ):\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target, params=params)\n\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        # set inputs\n        m.set_input(\"data\", data)\n        m.run()\n        out = m.get_output(0, tvm.nd.empty(out_shape, dtype))\n\n        if measure:\n            print(\"Evaluate graph executor inference cost of {} on \" \"{}\".format(model, repr(dev)))\n            ftimer = m.module.time_evaluator(\"run\", dev, number=1, repeat=20)\n            # Measure in millisecond.\n            prof_res = np.array(ftimer().results) * 1000\n            print(\n                \"Mean graph executor inference time (std dev): %.2f ms (%.2f ms)\"\n                % (np.mean(prof_res), np.std(prof_res))\n            )\n\n        return out.numpy()\n\n    def get_vm_output(mod, data, params, target, dev, dtype=\"float32\", number=2, repeat=20):\n        with tvm.transform.PassContext(opt_level=3):\n            exe = vm.compile(mod, target, params=params)\n            rly_vm = vm_rt.VirtualMachine(exe, dev)\n            result = rly_vm.run(data)\n\n        if measure:\n            print(\"Evaluate vm inference cost of {} on {}\".format(model, repr(dev)))\n            ftimer = rly_vm.module.time_evaluator(\"invoke\", dev, number=number, repeat=repeat)\n            # Measure in millisecond.\n            prof_res = np.array(ftimer(\"main\", data).results) * 1000\n            print(\n                \"Mean vm inference time (std dev): %.2f ms (%.2f ms)\"\n                % (np.mean(prof_res), np.std(prof_res))\n            )\n\n        return result.numpy().astype(dtype)\n\n    # random input\n    data = np.random.uniform(size=data_shape).astype(dtype)\n\n    for target, dev in testing.enabled_targets():\n        tvm_out = get_graph_executor_output(\n            mod, tvm.nd.array(data.astype(dtype)), params, target, dev, dtype\n        )\n        vm_out = get_vm_output(mod, tvm.nd.array(data.astype(dtype)), params, target, dev, dtype)\n        tvm.testing.assert_allclose(vm_out, tvm_out, rtol=1e-5, atol=1e-5)\n\n\ndef test_mlp():\n    image_shape = (1, 1, 28, 28)\n    mod, params = testing.mlp.get_workload(1)\n    benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 10), model=\"mlp\")\n\n\ndef test_vgg():\n    for n in [11, 16]:\n        mod, params = testing.vgg.get_workload(1, num_layers=n)\n        model = \"vgg\" + str(n)\n        benchmark_execution(mod, params, model=model)\n\n\ndef test_resnet():\n    for n in [18, 50]:\n        mod, params = testing.resnet.get_workload(batch_size=1, num_layers=n)\n        model = \"resnet\" + str(n)\n        benchmark_execution(mod, params, model=model)\n\n\ndef test_squeezenet():\n    for version in [\"1.0\", \"1.1\"]:\n        mod, params = testing.squeezenet.get_workload(version=version)\n        model = \"squeezenet\" + version\n        benchmark_execution(mod, params, model=model)\n\n\ndef test_inception_v3():\n    image_shape = (3, 299, 299)\n    mod, params = testing.inception_v3.get_workload(image_shape=image_shape)\n    benchmark_execution(mod, params, data_shape=(1, 3, 299, 299), model=\"inception_v3\")\n\n\ndef test_dqn():\n    image_shape = (1, 4, 84, 84)\n    mod, params = testing.dqn.get_workload(batch_size=1, image_shape=image_shape)\n    benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 18))\n\n\ndef test_dcgan():\n    image_shape = (1, 100)\n    mod, params = testing.dcgan.get_workload(batch_size=1)\n    benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 3, 64, 64))\n\n\ndef test_mobilenet():\n    mod, params = testing.mobilenet.get_workload(batch_size=1)\n    benchmark_execution(mod, params, model=\"mobilenet\")\n\n\n# TODO: enable when the low building performance (several minutes) fixed.\ndef test_mobilenet_nhwc():\n    image_shape = (1, 224, 224, 3)\n    mod, params = testing.mobilenet.get_workload(\n        batch_size=1, image_shape=image_shape[1:], layout=\"NHWC\"\n    )\n    benchmark_execution(mod, params, measure=False, data_shape=image_shape)\n\n\ndef test_densenet():\n    mod, params = testing.densenet.get_workload(batch_size=1)\n    benchmark_execution(mod, params, model=\"densenet\")\n\n\nif __name__ == \"__main__\":\n    test_resnet()\n    test_vgg()\n    test_squeezenet()\n    test_mobilenet()\n    test_densenet()\n    test_inception_v3()\n    test_mlp()\n    test_dqn()\n    test_dcgan()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/collage/demo_collage_partitioner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Compares Collage with various other baselines.\"\"\"\n\n# CAUTION: Requires some changes in python/tvm/autotvm/task/dispatcher.py\n# so that AutoTVM tuning records can be cached between runs and between\n# models. See https://github.com/mbs-octoml/mbs-tvm/tree/mbs-collage-hacks.\n\nimport tvm\nimport logging\nimport tempfile\nimport os\nimport shutil\n\nimport menangerie\n\n# The following are necessary to force global functions or pattern tables to be registered\nfrom tvm.relay.op.contrib.cutlass import partition_for_cutlass\nfrom tvm.contrib.cutlass import num_cutlass_partitions\nfrom tvm.relay.op.contrib.cublas import partition_for_cublas\nfrom tvm.relay.op.contrib.cudnn import partition_for_cudnn\n\nlogging.basicConfig(level=logging.INFO)\n\n\n########### Configuration ###########\n\n###\n### Rename to match your hardware, eg ..._vt100...\n###\nTUNING_LOG = \"/home/mbs/collage_autotvm_rtx3070.tuninglog\"\n\n###\n### If true, runs final model under nvprof\n###\nPROFILE = True\n\n###\n### If true, run all models\n###\nALL_MODELS = False\n\n###\n### If true, run all configurations\n###\nALL_CONFIGS = False\n\n###\n### How aggressively to look for candidates?\n###\nTVM_MAX_DEPTH = 8\nBYOC_MAX_DEPTH = 8\n\n###\n### AutoTVM tuning parameters.\n###\nAUTOTVM_NUM_TRIALS = 2000\nAUTOTVM_EARLY_STOPPING = 600\nTIMEOUT = 10\nMEASURE_NUMBER = tvm.relay.collage.MEASURE_NUMBER\nMEASURE_REPEAT = tvm.relay.collage.MEASURE_REPEAT\nWARMUP_MIN_REPEAT_MS = tvm.relay.collage.WARMUP_MIN_REPEAT_MS\n\nHOST = tvm.target.Target(\"llvm\")\nCUDA = tvm.target.Target(\"cuda\", HOST)\n\n########### Runtime ###########\n\n# Code to run a model. The actual call to 'run' is appended at compile time.\n# We invoke the model as a sub-process so that we can wrap profiling tools around it.\nrunner_template = f\"\"\"\nimport tvm\nimport tvm.runtime.vm\nimport numpy as np\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nMEASURE_NUMBER = {MEASURE_NUMBER}\nMEASURE_REPEAT = {MEASURE_REPEAT}\nWARMUP_MIN_REPEAT_MS = {WARMUP_MIN_REPEAT_MS}\n\ndef arg_for(shape, dtype, device):\n    return tvm.nd.array(\n        np.random.rand(*shape).astype(dtype), device=device)\n\ndef vm_estimate_seconds(device, vm, args):\n    vm.benchmark(device, repeat=1, number=1, min_repeat_ms=WARMUP_MIN_REPEAT_MS, **args)\n    return vm.benchmark(device, repeat=MEASURE_REPEAT, number=MEASURE_NUMBER, min_repeat_ms=0,\n                        **args)\n\n\ndef run(label, name, device, lib_path, code_path, input_shapes, input_dtypes):\n    logging.info(f\"Loading compiled code for {{name}} generated by {{label}} from {{lib_path}} and {{code_path}}...\")\n    loaded_lib = tvm.runtime.load_module(lib_path)\n    loaded_code = bytearray(open(code_path, \"rb\").read())\n    loaded_exe = tvm.runtime.vm.Executable.load_exec(loaded_code, loaded_lib)\n    vm = tvm.runtime.vm.VirtualMachine(loaded_exe, device)\n    args = {{\n        input_name: arg_for(input_shapes[input_name], input_dtypes[input_name], device)\n        for input_name in input_shapes.keys()\n    }}\n    logging.info(f\"Benchmarking for {{name}} generated by {{label}}...\")\n    profile = vm_estimate_seconds(device, vm, args)\n    logging.info(f\"Benchmarked for {{name}} generated by {{label}}: {{profile}}\")\n    logging.info(f\"RESULT: {{label}} | {{name}} | {{profile.median * 1e3}}ms\")\n\nif __name__ == \"__main__\":\n\"\"\"\n\n########### AutoTVM tuning helpers ###########\n\n\ndef extract_autotvm_tasks(mod, target):\n    \"\"\"Returns TVM kernels to tune for mod and target.\"\"\"\n    return tvm.autotvm.task.extract_from_program(mod, target=target, params=None)\n\n\ndef optional_tuning_records(log_filename):\n    \"\"\"Returns existing tuning records, if any.\"\"\"\n    if log_filename == \"\" or not os.path.exists(log_filename):\n        return tvm.autotvm.task.FallbackContext()\n    else:\n        return tvm.autotvm.task.ApplyHistoryBest(log_filename)\n\n\ndef is_already_tuned(task, log_filename):\n    \"\"\"Returns True if we already have a tuning record for task in turning logs in log_filename\"\"\"\n    if not os.path.exists(log_filename):\n        return False\n\n    dispatch_context = tvm.autotvm.task.ApplyHistoryBest(log_filename)\n    return dispatch_context.contains(task.target, task.workload)\n\n\ndef tune_autotvm_tasks(tasks, log_filename):\n    \"\"\"Appends to log_filename the best strategies for tasks\"\"\"\n    if len(tasks) == 0:\n        return\n\n    measure_option = tvm.autotvm.measure_option(\n        builder=tvm.autotvm.LocalBuilder(timeout=TIMEOUT),\n        runner=tvm.autotvm.LocalRunner(\n            number=MEASURE_NUMBER, repeat=MEASURE_REPEAT, timeout=TIMEOUT, min_repeat_ms=0\n        ),\n    )\n\n    logging.info(\n        f\"Using autotvm tuning for {len(tasks)} tasks with {AUTOTVM_NUM_TRIALS} trials, logging to {log_filename}\"\n    )\n\n    # create tmp log file, starting with contents from existing log file\n    tmp_log_filename = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_filename):\n        os.remove(tmp_log_filename)\n    if os.path.exists(log_filename):\n        logging.info(f\"Copying existing log {log_filename} to {tmp_log_filename}\")\n        shutil.copy(log_filename, tmp_log_filename)\n\n    for i, task in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n        logging.info(f\"Considering task {task.name} {prefix}\")\n        if is_already_tuned(task, tmp_log_filename):\n            logging.info(f\"Re-using existing record for {task.name}\")\n            continue\n\n        logging.info(f\"Using autotvm to tune {task.name}\")\n        tuner_obj = tvm.autotvm.tuner.XGBTuner(task, loss_type=\"rank\")\n        if os.path.exists(tmp_log_filename):\n            tuner_obj.load_history(tvm.autotvm.record.load_from_file(tmp_log_filename))\n\n        # do tuning\n        n_trial = min(AUTOTVM_NUM_TRIALS, len(task.config_space))\n        tuner_obj.tune(\n            n_trial=n_trial,\n            early_stopping=AUTOTVM_EARLY_STOPPING,\n            measure_option=measure_option,\n            callbacks=[\n                tvm.autotvm.callback.progress_bar(n_trial, prefix=prefix),\n                tvm.autotvm.callback.log_to_file(tmp_log_filename),\n            ],\n        )\n\n    # pick best records and copy back to main log file\n    tvm.autotvm.record.pick_best(tmp_log_filename, log_filename)\n    os.remove(tmp_log_filename)\n\n    logging.info(\"Done with autotvm tuning\")\n\n\ndef autotvm_tune_module(mod, target, log_filename):\n    if log_filename == \"\":\n        logging.info(\"Not tuning with autotvm since disabled\")\n        return\n    # Extract and tune any TVM kernels. BYOC partitions will have no tasks extracted.\n    logging.info(\"Extracting tasks from overall module\")\n    tasks = extract_autotvm_tasks(mod, target)\n    logging.info(f\"Auto-tuning {len(tasks)} tasks from overall module\")\n    tune_autotvm_tasks(tasks, log_filename)\n\n\n########### Drivers ###########\n\n\ndef compile_and_benchmark(label, model, targets, dev, tmp_dir):\n    \"\"\"Compile model for target and run it with profiling.\"\"\"\n    logging.info(f\"Compiling {model['name']} using {label} with {targets}...\")\n    exe = tvm.relay.vm.compile(model[\"mod\"], target=targets, params=model[\"params\"])\n    lib_path = os.path.join(tmp_dir, \"lib.so\")\n    code_path = os.path.join(tmp_dir, \"code.ro\")\n    code, lib = exe.save()\n    logging.info(f\"Saving VM code to {code_path}...\")\n    with open(code_path, \"wb\") as fo:\n        fo.write(code)\n    logging.info(f\"Exporting library to {lib_path}...\")\n    lib.export_library(lib_path, workspace_dir=tmp_dir, cc=\"nvcc\")\n    runner = f\"{runner_template}    run('{label}', '{model['name']}', tvm.device({dev.device_type}), '{lib_path}', '{code_path}', {model['input_shapes']}, {model['input_dtypes']})\\n\"\n    runner_path = os.path.join(tmp_dir, \"runner.py\")\n    logging.info(f\"Saving runner to {runner_path}...\")\n    with open(runner_path, \"w\") as fo:\n        fo.write(runner)\n\n    logging.info(f\"Invoking runner...\")\n    if PROFILE:\n        profile_path = os.path.join(tmp_dir, \"profile.txt\")\n        os.system(f\"nsys nvprof -o {profile_path} python3 {runner_path}\")\n    else:\n        os.system(f\"python3 {runner_path}\")\n\n\ndef collage(model):\n    \"\"\"Run the Collage partitioner for a set of CUDA-related targets and profile the result\"\"\"\n    logging.info(f\"collage | {model['name']}\")\n    logging.info(\"-------------- BEGIN ORIGINAL --------------\")\n    logging.info(model[\"mod\"])\n    logging.info(\"-------------- END ORIGINAL ----------------\")\n    autotvm_tune_module(model[\"mod\"], CUDA, TUNING_LOG)\n    with optional_tuning_records(TUNING_LOG):\n        targets = []\n        targets.append(CUDA)\n        use_fp16 = model[\"main_dtype\"] == \"float16\"\n        targets.append(\n            tvm.target.Target(f\"tensorrt -use_implicit_batch=False -use_fp16={use_fp16}\", HOST)\n        )\n        tmp_dir = tempfile.mkdtemp()\n        targets.append(tvm.target.Target(f\"cutlass -tmp_dir={tmp_dir}\", HOST))\n        targets.append(tvm.target.Target(\"cublas\", HOST))\n        targets.append(tvm.target.Target(\"cudnn\", HOST))\n        config = {\n            \"relay.collage.tvm_max_depth\": TVM_MAX_DEPTH,\n            \"relay.collage.byoc_max_depth\": BYOC_MAX_DEPTH,\n        }\n        logging.info(f\"Using PassContext(config={config}\")\n        ctxt = tvm.transform.PassContext(config=config)\n        config = tvm.target.make_compilation_config(ctxt, targets)\n        with ctxt:\n            mod = model[\"mod\"]\n            mod = tvm.relay.transform.CapturePostDfsIndexInSpans()(mod)\n            logging.info(\"-------------- BEGIN INDEXED --------------\")\n            logging.info(mod)\n            logging.info(\"-------------- END INDEXED ----------------\")\n            mod = tvm.relay.transform.CollagePartition(config)(mod)\n            partitioned_model = model.copy()\n            partitioned_model[\"mod\"] = mod\n            logging.info(\"-------------- BEGIN PARTITIONED --------------\")\n            logging.info(partitioned_model[\"mod\"])\n            logging.info(\"-------------- END PARTITIONED ----------------\")\n            dev = tvm.device(CUDA.get_target_device_type())\n            compile_and_benchmark(\"collage\", partitioned_model, targets, dev, tmp_dir)\n\n\ndef just_tensorrt(model):\n    \"\"\"Run partition_for_tensorrt, complete the compilation with TVM, and profile the result.\"\"\"\n    logging.info(f\"just_tensorrt | {model['name']}\")\n    logging.info(\"-------------- BEGIN ORIGINAL --------------\")\n    logging.info(model[\"mod\"])\n    logging.info(\"-------------- END ORIGINAL ----------------\")\n    tmp_dir = tempfile.mkdtemp()\n    autotvm_tune_module(model[\"mod\"], CUDA, TUNING_LOG)\n    with optional_tuning_records(TUNING_LOG):\n        logging.info(\"Partitioning for TensorRT...\")\n        use_fp16 = model[\"main_dtype\"] == \"float16\"\n        trt_target = tvm.target.Target(\n            f\"tensorrt -use_implicit_batch=False -use_fp16={use_fp16}\", HOST\n        )\n        mod = tvm.relay.op.contrib.partition_for_tensorrt(\n            mod=model[\"mod\"], params=model[\"params\"], target=trt_target\n        )\n        partitioned_model = model.copy()\n        partitioned_model[\"mod\"] = mod\n        logging.info(\"-------------- BEGIN PARTITIONED --------------\")\n        logging.info(partitioned_model[\"mod\"])\n        logging.info(\"-------------- END PARTITIONED ----------------\")\n        targets = []\n        targets.append(CUDA)\n        targets.append(trt_target)\n        dev = tvm.device(CUDA.get_target_device_type())\n        compile_and_benchmark(\"just_tensorrt\", partitioned_model, targets, dev, tmp_dir)\n\n\ndef just_cutlass(model):\n    \"\"\"Run partition_for_cutlass, complete the compilation with TVM, and profile the result.\"\"\"\n    logging.info(f\"just_cutlass | {model['name']}\")\n    logging.info(\"-------------- BEGIN ORIGINAL --------------\")\n    logging.info(model[\"mod\"])\n    logging.info(\"-------------- END ORIGINAL ----------------\")\n    tmp_dir = tempfile.mkdtemp()\n    autotvm_tune_module(model[\"mod\"], CUDA, TUNING_LOG)\n    with optional_tuning_records(TUNING_LOG):\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            logging.info(\"Partitioning for CUTLASS...\")\n            mod = tvm.relay.op.contrib.partition_for_cutlass(model[\"mod\"], model[\"params\"])\n            partitioned_model = model.copy()\n            partitioned_model[\"mod\"] = mod\n            logging.info(\"-------------- BEGIN PARTITIONED --------------\")\n            logging.info(partitioned_model[\"mod\"])\n            logging.info(\"-------------- END PARTITIONED ----------------\")\n            targets = []\n            targets.append(CUDA)\n            targets.append(tvm.target.Target(f\"cutlass -tmp_dir={tmp_dir}\", HOST))\n            dev = tvm.device(CUDA.get_target_device_type())\n            compile_and_benchmark(\"just_cutlass\", partitioned_model, targets, dev, tmp_dir)\n\n\ndef just_tvm(model):\n    \"\"\"Compile and profile using vanilla TVM.\"\"\"\n    logging.info(f\"just_tvm | {model['name']}\")\n    logging.info(\"-------------- BEGIN ORIGINAL --------------\")\n    logging.info(model[\"mod\"])\n    logging.info(\"-------------- END ORIGINAL ----------------\")\n    tmp_dir = tempfile.mkdtemp()\n    autotvm_tune_module(model[\"mod\"], CUDA, TUNING_LOG)\n    with optional_tuning_records(TUNING_LOG):\n        dev = tvm.device(CUDA.get_target_device_type())\n        compile_and_benchmark(\"just_tvm\", model, CUDA, dev, tmp_dir)\n\n\ndef tvm_with_libs(model):\n    \"\"\"As for just_tvm, but use the existing -libs mechanism to enable standard CUDA libs.\"\"\"\n    logging.info(f\"tvm_with_libs | {model['name']}\")\n    logging.info(\"-------------- BEGIN ORIGINAL --------------\")\n    logging.info(model[\"mod\"])\n    logging.info(\"-------------- END ORIGINAL ----------------\")\n    tmp_dir = tempfile.mkdtemp()\n    cuda_target = tvm.target.Target(\"cuda -libs=cudnn,cublas\", HOST)\n    autotvm_tune_module(model[\"mod\"], cuda_target, TUNING_LOG)\n    with optional_tuning_records(TUNING_LOG):\n        dev = tvm.device(cuda_target.get_target_device_type())\n        compile_and_benchmark(\"tvm_with_libs\", model, cuda_target, dev, tmp_dir)\n\n\n########### Runners ###########\n\n\ndef run_all():\n    \"\"\"Run the whole test suite.\"\"\"\n    make_models = []\n    make_models.append(menangerie.resnext50_32x4d)\n    if ALL_MODELS:\n        make_models.append(menangerie.resnext50_32x4d_16)\n        make_models.append(menangerie.gpt2_16)\n        make_models.append(menangerie.gpt2)\n        make_models.append(menangerie.mobilenet_16)\n        make_models.append(menangerie.mobilenet)\n        make_models.append(menangerie.resnet50_16)\n        make_models.append(menangerie.resnet50)\n    run_models = []\n    if ALL_CONFIGS:\n        run_models.append(just_tensorrt)\n        run_models.append(just_tvm)\n        run_models.append(tvm_with_libs)\n    run_models.append(collage)\n    for make_model in make_models:\n        model = make_model()\n        for run_model in run_models:\n            run_model(model)\n\n\ndef run_mini():\n    \"\"\"Run Collage on a tiny GPT2 extract.\"\"\"\n    collage(menangerie.gpt2_16_for_cutlass_extract())\n\n\nif __name__ == \"__main__\":\n    # run_all()\n    run_mini()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/collage/menangerie.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A collection of Relay models for exercising Collage.\"\"\"\n\nimport tvm\nimport onnx\nimport numpy as np\nimport logging\nimport tvm.contrib.target.onnx\n\nMODEL_PREFIX = \"/home/mbs/gauntlet/models/\"\nMNIST = {\n    \"name\": \"mnist\",\n    \"filename\": \"mnist-8.onnx\",\n    \"input_shapes\": {\"Input3\": [1, 1, 28, 28]},\n    \"input_dtypes\": {\"Input3\": \"float32\"},\n    \"main_dtype\": \"float32\",\n}\nGPT2 = {\n    \"name\": \"gpt2\",\n    \"filename\": \"gpt2.onnx\",\n    \"input_shapes\": {\"input1\": [1, 50, 32]},\n    \"input_dtypes\": {\"input1\": \"int64\"},\n    \"main_dtype\": \"float32\",\n}\nRESNET50V2 = {\n    \"name\": \"resnet50\",\n    \"filename\": \"resnet50-v2-7.onnx\",\n    \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n    \"input_dtypes\": {\"data\": \"float32\"},\n    \"main_dtype\": \"float32\",\n}\nMOBILENETV2 = {\n    \"name\": \"mobilenet\",\n    \"filename\": \"mobilenetv2-1.0.onnx\",\n    \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n    \"input_dtypes\": {\"data\": \"float32\"},\n    \"main_dtype\": \"float32\",\n}\n# Note that resnext50_32_4d below was extracted directly from the pytorch model and not from any onnx file.\nRESNEXT50_32_4d = {\n    \"name\": \"resnext50_32_4d\",\n    \"filename\": \"resnext50_32x4d.onnx\",\n    \"input_shapes\": {\"x\": [1, 64, 56, 56]},\n    \"input_dtypes\": {\"x\": \"float32\"},\n    \"main_dtype\": \"float32\",\n}\n\n\ndef make_const(dtype, shape):\n    return tvm.relay.const(np.random.rand(*shape).astype(dtype))\n\n\ndef make_consts(dtype, shapes):\n    return [make_const(dtype, shape) for shape in shapes]\n\n\ndef mnist_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (8, 1, 5, 5),  # 0\n            (8, 1, 1),  # 1\n            (16, 8, 5, 5),  # 2\n            (16, 1, 1),  # 3\n            (10, 256),  # 4\n            (1, 10),  # 5\n        ],\n    )\n\n\ndef mnist():\n    metatable = {\"relay.Constant\": mnist_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1, 1, 28, 28), float32]) -> Tensor[(1, 10), float32] {\n          %0 = nn.pad(%x, 0f, pad_width=[[0, 0], [0, 0], [2, 2], [2, 2]]);\n          %1 = nn.conv2d(%0, meta[relay.Constant][0], padding=[0, 0, 0, 0], channels=8, kernel_size=[5, 5]);\n          %2 = add(%1, meta[relay.Constant][1]);\n          %3 = nn.relu(%2);\n          %4 = nn.max_pool2d(%3, pool_size=[2, 2], strides=[2, 2], padding=[0, 0, 0, 0]);\n          %5 = nn.pad(%4, 0f, pad_width=[[0, 0], [0, 0], [2, 2], [2, 2]]);\n          %6 = nn.conv2d(%5, meta[relay.Constant][2], padding=[0, 0, 0, 0], channels=16, kernel_size=[5, 5]);\n          %7 = add(%6, meta[relay.Constant][3]);\n          %8 = nn.relu(%7);\n          %9 = nn.max_pool2d(%8, pool_size=[3, 3], strides=[3, 3], padding=[0, 0, 0, 0]);\n          %10 = reshape(%9, newshape=[1, 256]);\n          %11 = nn.dense(%10, meta[relay.Constant][4], units=None, out_dtype=\"float32\");\n          add(%11, meta[relay.Constant][5])\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"mnist\",\n        \"input_shapes\": {\"x\": [1, 1, 28, 28]},\n        \"input_dtypes\": {\"x\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef gpt2_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (50257, 768),  # 0\n            (1, 32, 768),  # 1\n            (768,),  # 2\n            (768,),  # 3\n            (2304, 768),  # 4\n            (2304,),  # 5\n            (1, 1, 32, 32),  # 6\n            (1, 1, 32, 32),  # 7\n            (768, 768),  # 8\n            (768,),  # 9\n            (768,),  # 10\n            (768,),  # 11\n            (3072, 768),  # 12\n            (3072,),  # 13\n            (768, 3072),  # 14\n            (768,),  # 15\n            (768,),  # 16\n            (768,),  # 17\n            (2304, 768),  # 18\n            (2304,),  # 19\n            (1, 1, 32, 32),  # 20\n            (1, 1, 32, 32),  # 21\n            (768, 768),  # 22\n            (768,),  # 23\n            (768,),  # 24\n            (768,),  # 25\n            (3072, 768),  # 26\n            (3072,),  # 27\n            (768, 3072),  # 28\n            (768,),  # 29\n            (768,),  # 30\n            (768,),  # 31\n            (2304, 768),  # 32\n            (2304,),  # 33\n            (1, 1, 32, 32),  # 34\n            (1, 1, 32, 32),  # 35\n            (768, 768),  # 36\n            (768,),  # 37\n            (768,),  # 38\n            (768,),  # 39\n            (3072, 768),  # 40\n            (3072,),  # 41\n            (768, 3072),  # 42\n            (768,),  # 43\n            (768,),  # 44\n            (768,),  # 45\n            (2304, 768),  # 46\n            (2304,),  # 47\n            (1, 1, 32, 32),  # 48\n            (1, 1, 32, 32),  # 49\n            (768, 768),  # 50\n            (768,),  # 51\n            (768,),  # 52\n            (768,),  # 53\n            (3072, 768),  # 54\n            (3072,),  # 55\n            (768, 3072),  # 56\n            (768,),  # 57\n            (768,),  # 58\n            (768,),  # 59\n            (2304, 768),  # 60\n            (2304,),  # 61\n            (1, 1, 32, 32),  # 62\n            (1, 1, 32, 32),  # 63\n            (768, 768),  # 64\n            (768,),  # 65\n            (768,),  # 66\n            (768,),  # 67\n            (3072, 768),  # 68\n            (3072,),  # 69\n            (768, 3072),  # 70\n            (768,),  # 71\n            (768,),  # 72\n            (768,),  # 73\n            (2304, 768),  # 74\n            (2304,),  # 75\n            (1, 1, 32, 32),  # 76\n            (1, 1, 32, 32),  # 77\n            (768, 768),  # 78\n            (768,),  # 79\n            (768,),  # 80\n            (768,),  # 81\n            (3072, 768),  # 82\n            (3072,),  # 83\n            (768, 3072),  # 84\n            (768,),  # 85\n            (768,),  # 86\n            (768,),  # 87\n            (2304, 768),  # 88\n            (2304,),  # 89\n            (1, 1, 32, 32),  # 90\n            (1, 1, 32, 32),  # 91\n            (768, 768),  # 92\n            (768,),  # 93\n            (768,),  # 94\n            (768,),  # 95\n            (3072, 768),  # 96\n            (3072,),  # 97\n            (768, 3072),  # 98\n            (768,),  # 99\n            (768,),  # 100\n            (768,),  # 101\n            (2304, 768),  # 102\n            (2304,),  # 103\n            (1, 1, 32, 32),  # 104\n            (1, 1, 32, 32),  # 105\n            (768, 768),  # 106\n            (768,),  # 107\n            (768,),  # 108\n            (768,),  # 109\n            (3072, 768),  # 110\n            (3072,),  # 111\n            (768, 3072),  # 112\n            (768,),  # 113\n            (768,),  # 114\n            (768,),  # 115\n            (2304, 768),  # 116\n            (2304,),  # 117\n            (1, 1, 32, 32),  # 118\n            (1, 1, 32, 32),  # 119\n            (768, 768),  # 120\n            (768,),  # 121\n            (768,),  # 122\n            (768,),  # 123\n            (3072, 768),  # 124\n            (3072,),  # 125\n            (768, 3072),  # 126\n            (768,),  # 127\n            (768,),  # 128\n            (768,),  # 129\n            (2304, 768),  # 130\n            (2304,),  # 131\n            (1, 1, 32, 32),  # 132\n            (1, 1, 32, 32),  # 133\n            (768, 768),  # 134\n            (768,),  # 135\n            (768,),  # 136\n            (768,),  # 137\n            (3072, 768),  # 138\n            (3072,),  # 139\n            (768, 3072),  # 140\n            (768,),  # 141\n            (768,),  # 142\n            (768,),  # 143\n            (2304, 768),  # 144\n            (2304,),  # 145\n            (1, 1, 32, 32),  # 146\n            (1, 1, 32, 32),  # 147\n            (768, 768),  # 148\n            (768,),  # 149\n            (768,),  # 150\n            (768,),  # 151\n            (3072, 768),  # 152\n            (3072,),  # 153\n            (768, 3072),  # 154\n            (768,),  # 155\n            (768,),  # 156\n            (768,),  # 157\n            (2304, 768),  # 158\n            (2304,),  # 159\n            (1, 1, 32, 32),  # 160\n            (1, 1, 32, 32),  # 161\n            (768, 768),  # 162\n            (768,),  # 163\n            (768,),  # 164\n            (768,),  # 165\n            (3072, 768),  # 166\n            (3072,),  # 167\n            (768, 3072),  # 168\n            (768,),  # 169\n            (768,),  # 170\n            (768,),  # 171\n        ],\n    )\n\n\ndef gpt2():\n    metatable = {\"relay.Constant\": gpt2_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1, 50, 32), int64]) -> (Tensor[(1, 50, 32, 768), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32],\n                                                      Tensor[(2, 50, 12, 32, 64), float32]) {\n          %0 = reshape(%x, newshape=[-1, 32]);\n          %1 = less(%0, 0i64);\n          %2 = add(%0, 50257i64);\n          %3 = where(%1, %2, %0);\n          %4 = take(meta[relay.Constant][0], %3, axis=0);\n          %5 = add(%4, meta[relay.Constant][1]);\n          %6 = mean(%5, axis=[-1], keepdims=True);\n          %7 = subtract(%5, %6);\n          %8 = power(%7, 2f);\n          %9 = mean(%8, axis=[-1], keepdims=True);\n          %10 = add(%9, 1e-05f);\n          %11 = sqrt(%10);\n          %12 = divide(%7, %11);\n          %13 = multiply(%12, meta[relay.Constant][2]);\n          %14 = add(%13, meta[relay.Constant][3]);\n          %15 = reshape(%14, newshape=[-1, 768]);\n          %16 = nn.dense(%15, meta[relay.Constant][4], units=2304);\n          %17 = add(%16, meta[relay.Constant][5]);\n          %18 = reshape(%17, newshape=[50, 32, 2304]);\n          %19 = split(%18, indices_or_sections=[768, 1536], axis=2);\n          %20 = %19.0;\n          %21 = reshape(%20, newshape=[50, 32, 12, 64]);\n          %22 = transpose(%21, axes=[0, 2, 1, 3]);\n          %23 = %19.1;\n          %24 = reshape(%23, newshape=[50, 32, 12, 64]);\n          %25 = transpose(%24, axes=[0, 2, 3, 1]);\n          %26 = reshape(%25, newshape=[-1, 64, 32]);\n          %27 = reshape(%22, newshape=[-1, 32, 64]);\n          %28 = transpose(%26, axes=[0, 2, 1]);\n          %29 = nn.batch_matmul(%27, %28, out_dtype=\"float32\", transpose_b=True);\n          %30 = reshape(%29, newshape=[50, 12, 32, 32]);\n          %31 = divide(%30, 8f);\n          %32 = multiply(%31, meta[relay.Constant][6]);\n          %33 = subtract(%32, meta[relay.Constant][7]);\n          %34 = nn.softmax(%33, axis=3);\n          %35 = %19.2;\n          %36 = reshape(%35, newshape=[50, 32, 12, 64]);\n          %37 = transpose(%36, axes=[0, 2, 1, 3]);\n          %38 = reshape(%37, newshape=[-1, 32, 64]);\n          %39 = reshape(%34, newshape=[-1, 32, 32]);\n          %40 = transpose(%38, axes=[0, 2, 1]);\n          %41 = nn.batch_matmul(%39, %40, out_dtype=\"float32\", transpose_b=True);\n          %42 = reshape(%41, newshape=[50, 12, 32, 64]);\n          %43 = transpose(%42, axes=[0, 2, 1, 3]);\n          %44 = reshape(%43, newshape=[50, 32, 768]);\n          %45 = reshape(%44, newshape=[-1, 768]);\n          %46 = nn.dense(%45, meta[relay.Constant][8], units=768);\n          %47 = add(%46, meta[relay.Constant][9]);\n          %48 = reshape(%47, newshape=[50, 32, 768]);\n          %49 = add(%5, %48);\n          %50 = mean(%49, axis=[-1], keepdims=True);\n          %51 = subtract(%49, %50);\n          %52 = power(%51, 2f);\n          %53 = mean(%52, axis=[-1], keepdims=True);\n          %54 = add(%53, 1e-05f);\n          %55 = sqrt(%54);\n          %56 = divide(%51, %55);\n          %57 = multiply(%56, meta[relay.Constant][10]);\n          %58 = add(%57, meta[relay.Constant][11]);\n          %59 = reshape(%58, newshape=[-1, 768]);\n          %60 = nn.dense(%59, meta[relay.Constant][12], units=3072);\n          %61 = add(%60, meta[relay.Constant][13]);\n          %62 = reshape(%61, newshape=[50, 32, 3072]);\n          %63 = power(%62, 3f);\n          %64 = multiply(%63, 0.044715f);\n          %65 = add(%62, %64);\n          %66 = multiply(%65, 0.797885f);\n          %67 = tanh(%66);\n          %68 = multiply(%62, 0.5f);\n          %69 = add(%67, 1f);\n          %70 = multiply(%68, %69);\n          %71 = reshape(%70, newshape=[-1, 3072]);\n          %72 = nn.dense(%71, meta[relay.Constant][14], units=768);\n          %73 = add(%72, meta[relay.Constant][15]);\n          %74 = reshape(%73, newshape=[50, 32, 768]);\n          %75 = add(%49, %74);\n          %76 = mean(%75, axis=[-1], keepdims=True);\n          %77 = subtract(%75, %76);\n          %78 = power(%77, 2f);\n          %79 = mean(%78, axis=[-1], keepdims=True);\n          %80 = add(%79, 1e-05f);\n          %81 = sqrt(%80);\n          %82 = divide(%77, %81);\n          %83 = multiply(%82, meta[relay.Constant][16]);\n          %84 = add(%83, meta[relay.Constant][17]);\n          %85 = reshape(%84, newshape=[-1, 768]);\n          %86 = nn.dense(%85, meta[relay.Constant][18], units=2304);\n          %87 = add(%86, meta[relay.Constant][19]);\n          %88 = reshape(%87, newshape=[50, 32, 2304]);\n          %89 = split(%88, indices_or_sections=[768, 1536], axis=2);\n          %90 = %89.0;\n          %91 = reshape(%90, newshape=[50, 32, 12, 64]);\n          %92 = transpose(%91, axes=[0, 2, 1, 3]);\n          %93 = %89.1;\n          %94 = reshape(%93, newshape=[50, 32, 12, 64]);\n          %95 = transpose(%94, axes=[0, 2, 3, 1]);\n          %96 = reshape(%95, newshape=[-1, 64, 32]);\n          %97 = reshape(%92, newshape=[-1, 32, 64]);\n          %98 = transpose(%96, axes=[0, 2, 1]);\n          %99 = nn.batch_matmul(%97, %98, out_dtype=\"float32\", transpose_b=True);\n          %100 = reshape(%99, newshape=[50, 12, 32, 32]);\n          %101 = divide(%100, 8f);\n          %102 = multiply(%101, meta[relay.Constant][20]);\n          %103 = subtract(%102, meta[relay.Constant][21]);\n          %104 = nn.softmax(%103, axis=3);\n          %105 = %89.2;\n          %106 = reshape(%105, newshape=[50, 32, 12, 64]);\n          %107 = transpose(%106, axes=[0, 2, 1, 3]);\n          %108 = reshape(%107, newshape=[-1, 32, 64]);\n          %109 = reshape(%104, newshape=[-1, 32, 32]);\n          %110 = transpose(%108, axes=[0, 2, 1]);\n          %111 = nn.batch_matmul(%109, %110, out_dtype=\"float32\", transpose_b=True);\n          %112 = reshape(%111, newshape=[50, 12, 32, 64]);\n          %113 = transpose(%112, axes=[0, 2, 1, 3]);\n          %114 = reshape(%113, newshape=[50, 32, 768]);\n          %115 = reshape(%114, newshape=[-1, 768]);\n          %116 = nn.dense(%115, meta[relay.Constant][22], units=768);\n          %117 = add(%116, meta[relay.Constant][23]);\n          %118 = reshape(%117, newshape=[50, 32, 768]);\n          %119 = add(%75, %118);\n          %120 = mean(%119, axis=[-1], keepdims=True);\n          %121 = subtract(%119, %120);\n          %122 = power(%121, 2f);\n          %123 = mean(%122, axis=[-1], keepdims=True);\n          %124 = add(%123, 1e-05f);\n          %125 = sqrt(%124);\n          %126 = divide(%121, %125);\n          %127 = multiply(%126, meta[relay.Constant][24]);\n          %128 = add(%127, meta[relay.Constant][25]);\n          %129 = reshape(%128, newshape=[-1, 768]);\n          %130 = nn.dense(%129, meta[relay.Constant][26], units=3072);\n          %131 = add(%130, meta[relay.Constant][27]);\n          %132 = reshape(%131, newshape=[50, 32, 3072]);\n          %133 = power(%132, 3f);\n          %134 = multiply(%133, 0.044715f);\n          %135 = add(%132, %134);\n          %136 = multiply(%135, 0.797885f);\n          %137 = tanh(%136);\n          %138 = multiply(%132, 0.5f);\n          %139 = add(%137, 1f);\n          %140 = multiply(%138, %139);\n          %141 = reshape(%140, newshape=[-1, 3072]);\n          %142 = nn.dense(%141, meta[relay.Constant][28], units=768);\n          %143 = add(%142, meta[relay.Constant][29]);\n          %144 = reshape(%143, newshape=[50, 32, 768]);\n          %145 = add(%119, %144);\n          %146 = mean(%145, axis=[-1], keepdims=True);\n          %147 = subtract(%145, %146);\n          %148 = power(%147, 2f);\n          %149 = mean(%148, axis=[-1], keepdims=True);\n          %150 = add(%149, 1e-05f);\n          %151 = sqrt(%150);\n          %152 = divide(%147, %151);\n          %153 = multiply(%152, meta[relay.Constant][30]);\n          %154 = add(%153, meta[relay.Constant][31]);\n          %155 = reshape(%154, newshape=[-1, 768]);\n          %156 = nn.dense(%155, meta[relay.Constant][32], units=2304);\n          %157 = add(%156, meta[relay.Constant][33]);\n          %158 = reshape(%157, newshape=[50, 32, 2304]);\n          %159 = split(%158, indices_or_sections=[768, 1536], axis=2);\n          %160 = %159.0;\n          %161 = reshape(%160, newshape=[50, 32, 12, 64]);\n          %162 = transpose(%161, axes=[0, 2, 1, 3]);\n          %163 = %159.1;\n          %164 = reshape(%163, newshape=[50, 32, 12, 64]);\n          %165 = transpose(%164, axes=[0, 2, 3, 1]);\n          %166 = reshape(%165, newshape=[-1, 64, 32]);\n          %167 = reshape(%162, newshape=[-1, 32, 64]);\n          %168 = transpose(%166, axes=[0, 2, 1]);\n          %169 = nn.batch_matmul(%167, %168, out_dtype=\"float32\", transpose_b=True);\n          %170 = reshape(%169, newshape=[50, 12, 32, 32]);\n          %171 = divide(%170, 8f);\n          %172 = multiply(%171, meta[relay.Constant][34]);\n          %173 = subtract(%172, meta[relay.Constant][35]);\n          %174 = nn.softmax(%173, axis=3);\n          %175 = %159.2;\n          %176 = reshape(%175, newshape=[50, 32, 12, 64]);\n          %177 = transpose(%176, axes=[0, 2, 1, 3]);\n          %178 = reshape(%177, newshape=[-1, 32, 64]);\n          %179 = reshape(%174, newshape=[-1, 32, 32]);\n          %180 = transpose(%178, axes=[0, 2, 1]);\n          %181 = nn.batch_matmul(%179, %180, out_dtype=\"float32\", transpose_b=True);\n          %182 = reshape(%181, newshape=[50, 12, 32, 64]);\n          %183 = transpose(%182, axes=[0, 2, 1, 3]);\n          %184 = reshape(%183, newshape=[50, 32, 768]);\n          %185 = reshape(%184, newshape=[-1, 768]);\n          %186 = nn.dense(%185, meta[relay.Constant][36], units=768);\n          %187 = add(%186, meta[relay.Constant][37]);\n          %188 = reshape(%187, newshape=[50, 32, 768]);\n          %189 = add(%145, %188);\n          %190 = mean(%189, axis=[-1], keepdims=True);\n          %191 = subtract(%189, %190);\n          %192 = power(%191, 2f);\n          %193 = mean(%192, axis=[-1], keepdims=True);\n          %194 = add(%193, 1e-05f);\n          %195 = sqrt(%194);\n          %196 = divide(%191, %195);\n          %197 = multiply(%196, meta[relay.Constant][38]);\n          %198 = add(%197, meta[relay.Constant][39]);\n          %199 = reshape(%198, newshape=[-1, 768]);\n          %200 = nn.dense(%199, meta[relay.Constant][40], units=3072);\n          %201 = add(%200, meta[relay.Constant][41]);\n          %202 = reshape(%201, newshape=[50, 32, 3072]);\n          %203 = power(%202, 3f);\n          %204 = multiply(%203, 0.044715f);\n          %205 = add(%202, %204);\n          %206 = multiply(%205, 0.797885f);\n          %207 = tanh(%206);\n          %208 = multiply(%202, 0.5f);\n          %209 = add(%207, 1f);\n          %210 = multiply(%208, %209);\n          %211 = reshape(%210, newshape=[-1, 3072]);\n          %212 = nn.dense(%211, meta[relay.Constant][42], units=768);\n          %213 = add(%212, meta[relay.Constant][43]);\n          %214 = reshape(%213, newshape=[50, 32, 768]);\n          %215 = add(%189, %214);\n          %216 = mean(%215, axis=[-1], keepdims=True);\n          %217 = subtract(%215, %216);\n          %218 = power(%217, 2f);\n          %219 = mean(%218, axis=[-1], keepdims=True);\n          %220 = add(%219, 1e-05f);\n          %221 = sqrt(%220);\n          %222 = divide(%217, %221);\n          %223 = multiply(%222, meta[relay.Constant][44]);\n          %224 = add(%223, meta[relay.Constant][45]);\n          %225 = reshape(%224, newshape=[-1, 768]);\n          %226 = nn.dense(%225, meta[relay.Constant][46], units=2304);\n          %227 = add(%226, meta[relay.Constant][47]);\n          %228 = reshape(%227, newshape=[50, 32, 2304]);\n          %229 = split(%228, indices_or_sections=[768, 1536], axis=2);\n          %230 = %229.0;\n          %231 = reshape(%230, newshape=[50, 32, 12, 64]);\n          %232 = transpose(%231, axes=[0, 2, 1, 3]);\n          %233 = %229.1;\n          %234 = reshape(%233, newshape=[50, 32, 12, 64]);\n          %235 = transpose(%234, axes=[0, 2, 3, 1]);\n          %236 = reshape(%235, newshape=[-1, 64, 32]);\n          %237 = reshape(%232, newshape=[-1, 32, 64]);\n          %238 = transpose(%236, axes=[0, 2, 1]);\n          %239 = nn.batch_matmul(%237, %238, out_dtype=\"float32\", transpose_b=True);\n          %240 = reshape(%239, newshape=[50, 12, 32, 32]);\n          %241 = divide(%240, 8f);\n          %242 = multiply(%241, meta[relay.Constant][48]);\n          %243 = subtract(%242, meta[relay.Constant][49]);\n          %244 = nn.softmax(%243, axis=3);\n          %245 = %229.2;\n          %246 = reshape(%245, newshape=[50, 32, 12, 64]);\n          %247 = transpose(%246, axes=[0, 2, 1, 3]);\n          %248 = reshape(%247, newshape=[-1, 32, 64]);\n          %249 = reshape(%244, newshape=[-1, 32, 32]);\n          %250 = transpose(%248, axes=[0, 2, 1]);\n          %251 = nn.batch_matmul(%249, %250, out_dtype=\"float32\", transpose_b=True);\n          %252 = reshape(%251, newshape=[50, 12, 32, 64]);\n          %253 = transpose(%252, axes=[0, 2, 1, 3]);\n          %254 = reshape(%253, newshape=[50, 32, 768]);\n          %255 = reshape(%254, newshape=[-1, 768]);\n          %256 = nn.dense(%255, meta[relay.Constant][50], units=768);\n          %257 = add(%256, meta[relay.Constant][51]);\n          %258 = reshape(%257, newshape=[50, 32, 768]);\n          %259 = add(%215, %258);\n          %260 = mean(%259, axis=[-1], keepdims=True);\n          %261 = subtract(%259, %260);\n          %262 = power(%261, 2f);\n          %263 = mean(%262, axis=[-1], keepdims=True);\n          %264 = add(%263, 1e-05f);\n          %265 = sqrt(%264);\n          %266 = divide(%261, %265);\n          %267 = multiply(%266, meta[relay.Constant][52]);\n          %268 = add(%267, meta[relay.Constant][53]);\n          %269 = reshape(%268, newshape=[-1, 768]);\n          %270 = nn.dense(%269, meta[relay.Constant][54], units=3072);\n          %271 = add(%270, meta[relay.Constant][55]);\n          %272 = reshape(%271, newshape=[50, 32, 3072]);\n          %273 = power(%272, 3f);\n          %274 = multiply(%273, 0.044715f);\n          %275 = add(%272, %274);\n          %276 = multiply(%275, 0.797885f);\n          %277 = tanh(%276);\n          %278 = multiply(%272, 0.5f);\n          %279 = add(%277, 1f);\n          %280 = multiply(%278, %279);\n          %281 = reshape(%280, newshape=[-1, 3072]);\n          %282 = nn.dense(%281, meta[relay.Constant][56], units=768);\n          %283 = add(%282, meta[relay.Constant][57]);\n          %284 = reshape(%283, newshape=[50, 32, 768]);\n          %285 = add(%259, %284);\n          %286 = mean(%285, axis=[-1], keepdims=True);\n          %287 = subtract(%285, %286);\n          %288 = power(%287, 2f);\n          %289 = mean(%288, axis=[-1], keepdims=True);\n          %290 = add(%289, 1e-05f);\n          %291 = sqrt(%290);\n          %292 = divide(%287, %291);\n          %293 = multiply(%292, meta[relay.Constant][58]);\n          %294 = add(%293, meta[relay.Constant][59]);\n          %295 = reshape(%294, newshape=[-1, 768]);\n          %296 = nn.dense(%295, meta[relay.Constant][60], units=2304);\n          %297 = add(%296, meta[relay.Constant][61]);\n          %298 = reshape(%297, newshape=[50, 32, 2304]);\n          %299 = split(%298, indices_or_sections=[768, 1536], axis=2);\n          %300 = %299.0;\n          %301 = reshape(%300, newshape=[50, 32, 12, 64]);\n          %302 = transpose(%301, axes=[0, 2, 1, 3]);\n          %303 = %299.1;\n          %304 = reshape(%303, newshape=[50, 32, 12, 64]);\n          %305 = transpose(%304, axes=[0, 2, 3, 1]);\n          %306 = reshape(%305, newshape=[-1, 64, 32]);\n          %307 = reshape(%302, newshape=[-1, 32, 64]);\n          %308 = transpose(%306, axes=[0, 2, 1]);\n          %309 = nn.batch_matmul(%307, %308, out_dtype=\"float32\", transpose_b=True);\n          %310 = reshape(%309, newshape=[50, 12, 32, 32]);\n          %311 = divide(%310, 8f);\n          %312 = multiply(%311, meta[relay.Constant][62]);\n          %313 = subtract(%312, meta[relay.Constant][63]);\n          %314 = nn.softmax(%313, axis=3);\n          %315 = %299.2;\n          %316 = reshape(%315, newshape=[50, 32, 12, 64]);\n          %317 = transpose(%316, axes=[0, 2, 1, 3]);\n          %318 = reshape(%317, newshape=[-1, 32, 64]);\n          %319 = reshape(%314, newshape=[-1, 32, 32]);\n          %320 = transpose(%318, axes=[0, 2, 1]);\n          %321 = nn.batch_matmul(%319, %320, out_dtype=\"float32\", transpose_b=True);\n          %322 = reshape(%321, newshape=[50, 12, 32, 64]);\n          %323 = transpose(%322, axes=[0, 2, 1, 3]);\n          %324 = reshape(%323, newshape=[50, 32, 768]);\n          %325 = reshape(%324, newshape=[-1, 768]);\n          %326 = nn.dense(%325, meta[relay.Constant][64], units=768);\n          %327 = add(%326, meta[relay.Constant][65]);\n          %328 = reshape(%327, newshape=[50, 32, 768]);\n          %329 = add(%285, %328);\n          %330 = mean(%329, axis=[-1], keepdims=True);\n          %331 = subtract(%329, %330);\n          %332 = power(%331, 2f);\n          %333 = mean(%332, axis=[-1], keepdims=True);\n          %334 = add(%333, 1e-05f);\n          %335 = sqrt(%334);\n          %336 = divide(%331, %335);\n          %337 = multiply(%336, meta[relay.Constant][66]);\n          %338 = add(%337, meta[relay.Constant][67]);\n          %339 = reshape(%338, newshape=[-1, 768]);\n          %340 = nn.dense(%339, meta[relay.Constant][68], units=3072);\n          %341 = add(%340, meta[relay.Constant][69]);\n          %342 = reshape(%341, newshape=[50, 32, 3072]);\n          %343 = power(%342, 3f);\n          %344 = multiply(%343, 0.044715f);\n          %345 = add(%342, %344);\n          %346 = multiply(%345, 0.797885f);\n          %347 = tanh(%346);\n          %348 = multiply(%342, 0.5f);\n          %349 = add(%347, 1f);\n          %350 = multiply(%348, %349);\n          %351 = reshape(%350, newshape=[-1, 3072]);\n          %352 = nn.dense(%351, meta[relay.Constant][70], units=768);\n          %353 = add(%352, meta[relay.Constant][71]);\n          %354 = reshape(%353, newshape=[50, 32, 768]);\n          %355 = add(%329, %354);\n          %356 = mean(%355, axis=[-1], keepdims=True);\n          %357 = subtract(%355, %356);\n          %358 = power(%357, 2f);\n          %359 = mean(%358, axis=[-1], keepdims=True);\n          %360 = add(%359, 1e-05f);\n          %361 = sqrt(%360);\n          %362 = divide(%357, %361);\n          %363 = multiply(%362, meta[relay.Constant][72]);\n          %364 = add(%363, meta[relay.Constant][73]);\n          %365 = reshape(%364, newshape=[-1, 768]);\n          %366 = nn.dense(%365, meta[relay.Constant][74], units=2304);\n          %367 = add(%366, meta[relay.Constant][75]);\n          %368 = reshape(%367, newshape=[50, 32, 2304]);\n          %369 = split(%368, indices_or_sections=[768, 1536], axis=2);\n          %370 = %369.0;\n          %371 = reshape(%370, newshape=[50, 32, 12, 64]);\n          %372 = transpose(%371, axes=[0, 2, 1, 3]);\n          %373 = %369.1;\n          %374 = reshape(%373, newshape=[50, 32, 12, 64]);\n          %375 = transpose(%374, axes=[0, 2, 3, 1]);\n          %376 = reshape(%375, newshape=[-1, 64, 32]);\n          %377 = reshape(%372, newshape=[-1, 32, 64]);\n          %378 = transpose(%376, axes=[0, 2, 1]);\n          %379 = nn.batch_matmul(%377, %378, out_dtype=\"float32\", transpose_b=True);\n          %380 = reshape(%379, newshape=[50, 12, 32, 32]);\n          %381 = divide(%380, 8f);\n          %382 = multiply(%381, meta[relay.Constant][76]);\n          %383 = subtract(%382, meta[relay.Constant][77]);\n          %384 = nn.softmax(%383, axis=3);\n          %385 = %369.2;\n          %386 = reshape(%385, newshape=[50, 32, 12, 64]);\n          %387 = transpose(%386, axes=[0, 2, 1, 3]);\n          %388 = reshape(%387, newshape=[-1, 32, 64]);\n          %389 = reshape(%384, newshape=[-1, 32, 32]);\n          %390 = transpose(%388, axes=[0, 2, 1]);\n          %391 = nn.batch_matmul(%389, %390, out_dtype=\"float32\", transpose_b=True);\n          %392 = reshape(%391, newshape=[50, 12, 32, 64]);\n          %393 = transpose(%392, axes=[0, 2, 1, 3]);\n          %394 = reshape(%393, newshape=[50, 32, 768]);\n          %395 = reshape(%394, newshape=[-1, 768]);\n          %396 = nn.dense(%395, meta[relay.Constant][78], units=768);\n          %397 = add(%396, meta[relay.Constant][79]);\n          %398 = reshape(%397, newshape=[50, 32, 768]);\n          %399 = add(%355, %398);\n          %400 = mean(%399, axis=[-1], keepdims=True);\n          %401 = subtract(%399, %400);\n          %402 = power(%401, 2f);\n          %403 = mean(%402, axis=[-1], keepdims=True);\n          %404 = add(%403, 1e-05f);\n          %405 = sqrt(%404);\n          %406 = divide(%401, %405);\n          %407 = multiply(%406, meta[relay.Constant][80]);\n          %408 = add(%407, meta[relay.Constant][81]);\n          %409 = reshape(%408, newshape=[-1, 768]);\n          %410 = nn.dense(%409, meta[relay.Constant][82], units=3072);\n          %411 = add(%410, meta[relay.Constant][83]);\n          %412 = reshape(%411, newshape=[50, 32, 3072]);\n          %413 = power(%412, 3f);\n          %414 = multiply(%413, 0.044715f);\n          %415 = add(%412, %414);\n          %416 = multiply(%415, 0.797885f);\n          %417 = tanh(%416);\n          %418 = multiply(%412, 0.5f);\n          %419 = add(%417, 1f);\n          %420 = multiply(%418, %419);\n          %421 = reshape(%420, newshape=[-1, 3072]);\n          %422 = nn.dense(%421, meta[relay.Constant][84], units=768);\n          %423 = add(%422, meta[relay.Constant][85]);\n          %424 = reshape(%423, newshape=[50, 32, 768]);\n          %425 = add(%399, %424);\n          %426 = mean(%425, axis=[-1], keepdims=True);\n          %427 = subtract(%425, %426);\n          %428 = power(%427, 2f);\n          %429 = mean(%428, axis=[-1], keepdims=True);\n          %430 = add(%429, 1e-05f);\n          %431 = sqrt(%430);\n          %432 = divide(%427, %431);\n          %433 = multiply(%432, meta[relay.Constant][86]);\n          %434 = add(%433, meta[relay.Constant][87]);\n          %435 = reshape(%434, newshape=[-1, 768]);\n          %436 = nn.dense(%435, meta[relay.Constant][88], units=2304);\n          %437 = add(%436, meta[relay.Constant][89]);\n          %438 = reshape(%437, newshape=[50, 32, 2304]);\n          %439 = split(%438, indices_or_sections=[768, 1536], axis=2);\n          %440 = %439.0;\n          %441 = reshape(%440, newshape=[50, 32, 12, 64]);\n          %442 = transpose(%441, axes=[0, 2, 1, 3]);\n          %443 = %439.1;\n          %444 = reshape(%443, newshape=[50, 32, 12, 64]);\n          %445 = transpose(%444, axes=[0, 2, 3, 1]);\n          %446 = reshape(%445, newshape=[-1, 64, 32]);\n          %447 = reshape(%442, newshape=[-1, 32, 64]);\n          %448 = transpose(%446, axes=[0, 2, 1]);\n          %449 = nn.batch_matmul(%447, %448, out_dtype=\"float32\", transpose_b=True);\n          %450 = reshape(%449, newshape=[50, 12, 32, 32]);\n          %451 = divide(%450, 8f);\n          %452 = multiply(%451, meta[relay.Constant][90]);\n          %453 = subtract(%452, meta[relay.Constant][91]);\n          %454 = nn.softmax(%453, axis=3);\n          %455 = %439.2;\n          %456 = reshape(%455, newshape=[50, 32, 12, 64]);\n          %457 = transpose(%456, axes=[0, 2, 1, 3]);\n          %458 = reshape(%457, newshape=[-1, 32, 64]);\n          %459 = reshape(%454, newshape=[-1, 32, 32]);\n          %460 = transpose(%458, axes=[0, 2, 1]);\n          %461 = nn.batch_matmul(%459, %460, out_dtype=\"float32\", transpose_b=True);\n          %462 = reshape(%461, newshape=[50, 12, 32, 64]);\n          %463 = transpose(%462, axes=[0, 2, 1, 3]);\n          %464 = reshape(%463, newshape=[50, 32, 768]);\n          %465 = reshape(%464, newshape=[-1, 768]);\n          %466 = nn.dense(%465, meta[relay.Constant][92], units=768);\n          %467 = add(%466, meta[relay.Constant][93]);\n          %468 = reshape(%467, newshape=[50, 32, 768]);\n          %469 = add(%425, %468);\n          %470 = mean(%469, axis=[-1], keepdims=True);\n          %471 = subtract(%469, %470);\n          %472 = power(%471, 2f);\n          %473 = mean(%472, axis=[-1], keepdims=True);\n          %474 = add(%473, 1e-05f);\n          %475 = sqrt(%474);\n          %476 = divide(%471, %475);\n          %477 = multiply(%476, meta[relay.Constant][94]);\n          %478 = add(%477, meta[relay.Constant][95]);\n          %479 = reshape(%478, newshape=[-1, 768]);\n          %480 = nn.dense(%479, meta[relay.Constant][96], units=3072);\n          %481 = add(%480, meta[relay.Constant][97]);\n          %482 = reshape(%481, newshape=[50, 32, 3072]);\n          %483 = power(%482, 3f);\n          %484 = multiply(%483, 0.044715f);\n          %485 = add(%482, %484);\n          %486 = multiply(%485, 0.797885f);\n          %487 = tanh(%486);\n          %488 = multiply(%482, 0.5f);\n          %489 = add(%487, 1f);\n          %490 = multiply(%488, %489);\n          %491 = reshape(%490, newshape=[-1, 3072]);\n          %492 = nn.dense(%491, meta[relay.Constant][98], units=768);\n          %493 = add(%492, meta[relay.Constant][99]);\n          %494 = reshape(%493, newshape=[50, 32, 768]);\n          %495 = add(%469, %494);\n          %496 = mean(%495, axis=[-1], keepdims=True);\n          %497 = subtract(%495, %496);\n          %498 = power(%497, 2f);\n          %499 = mean(%498, axis=[-1], keepdims=True);\n          %500 = add(%499, 1e-05f);\n          %501 = sqrt(%500);\n          %502 = divide(%497, %501);\n          %503 = multiply(%502, meta[relay.Constant][100]);\n          %504 = add(%503, meta[relay.Constant][101]);\n          %505 = reshape(%504, newshape=[-1, 768]);\n          %506 = nn.dense(%505, meta[relay.Constant][102], units=2304);\n          %507 = add(%506, meta[relay.Constant][103]);\n          %508 = reshape(%507, newshape=[50, 32, 2304]);\n          %509 = split(%508, indices_or_sections=[768, 1536], axis=2);\n          %510 = %509.0;\n          %511 = reshape(%510, newshape=[50, 32, 12, 64]);\n          %512 = transpose(%511, axes=[0, 2, 1, 3]);\n          %513 = %509.1;\n          %514 = reshape(%513, newshape=[50, 32, 12, 64]);\n          %515 = transpose(%514, axes=[0, 2, 3, 1]);\n          %516 = reshape(%515, newshape=[-1, 64, 32]);\n          %517 = reshape(%512, newshape=[-1, 32, 64]);\n          %518 = transpose(%516, axes=[0, 2, 1]);\n          %519 = nn.batch_matmul(%517, %518, out_dtype=\"float32\", transpose_b=True);\n          %520 = reshape(%519, newshape=[50, 12, 32, 32]);\n          %521 = divide(%520, 8f);\n          %522 = multiply(%521, meta[relay.Constant][104]);\n          %523 = subtract(%522, meta[relay.Constant][105]);\n          %524 = nn.softmax(%523, axis=3);\n          %525 = %509.2;\n          %526 = reshape(%525, newshape=[50, 32, 12, 64]);\n          %527 = transpose(%526, axes=[0, 2, 1, 3]);\n          %528 = reshape(%527, newshape=[-1, 32, 64]);\n          %529 = reshape(%524, newshape=[-1, 32, 32]);\n          %530 = transpose(%528, axes=[0, 2, 1]);\n          %531 = nn.batch_matmul(%529, %530, out_dtype=\"float32\", transpose_b=True);\n          %532 = reshape(%531, newshape=[50, 12, 32, 64]);\n          %533 = transpose(%532, axes=[0, 2, 1, 3]);\n          %534 = reshape(%533, newshape=[50, 32, 768]);\n          %535 = reshape(%534, newshape=[-1, 768]);\n          %536 = nn.dense(%535, meta[relay.Constant][106], units=768);\n          %537 = add(%536, meta[relay.Constant][107]);\n          %538 = reshape(%537, newshape=[50, 32, 768]);\n          %539 = add(%495, %538);\n          %540 = mean(%539, axis=[-1], keepdims=True);\n          %541 = subtract(%539, %540);\n          %542 = power(%541, 2f);\n          %543 = mean(%542, axis=[-1], keepdims=True);\n          %544 = add(%543, 1e-05f);\n          %545 = sqrt(%544);\n          %546 = divide(%541, %545);\n          %547 = multiply(%546, meta[relay.Constant][108]);\n          %548 = add(%547, meta[relay.Constant][109]);\n          %549 = reshape(%548, newshape=[-1, 768]);\n          %550 = nn.dense(%549, meta[relay.Constant][110], units=3072);\n          %551 = add(%550, meta[relay.Constant][111]);\n          %552 = reshape(%551, newshape=[50, 32, 3072]);\n          %553 = power(%552, 3f);\n          %554 = multiply(%553, 0.044715f);\n          %555 = add(%552, %554);\n          %556 = multiply(%555, 0.797885f);\n          %557 = tanh(%556);\n          %558 = multiply(%552, 0.5f);\n          %559 = add(%557, 1f);\n          %560 = multiply(%558, %559);\n          %561 = reshape(%560, newshape=[-1, 3072]);\n          %562 = nn.dense(%561, meta[relay.Constant][112], units=768);\n          %563 = add(%562, meta[relay.Constant][113]);\n          %564 = reshape(%563, newshape=[50, 32, 768]);\n          %565 = add(%539, %564);\n          %566 = mean(%565, axis=[-1], keepdims=True);\n          %567 = subtract(%565, %566);\n          %568 = power(%567, 2f);\n          %569 = mean(%568, axis=[-1], keepdims=True);\n          %570 = add(%569, 1e-05f);\n          %571 = sqrt(%570);\n          %572 = divide(%567, %571);\n          %573 = multiply(%572, meta[relay.Constant][114]);\n          %574 = add(%573, meta[relay.Constant][115]);\n          %575 = reshape(%574, newshape=[-1, 768]);\n          %576 = nn.dense(%575, meta[relay.Constant][116], units=2304);\n          %577 = add(%576, meta[relay.Constant][117]);\n          %578 = reshape(%577, newshape=[50, 32, 2304]);\n          %579 = split(%578, indices_or_sections=[768, 1536], axis=2);\n          %580 = %579.0;\n          %581 = reshape(%580, newshape=[50, 32, 12, 64]);\n          %582 = transpose(%581, axes=[0, 2, 1, 3]);\n          %583 = %579.1;\n          %584 = reshape(%583, newshape=[50, 32, 12, 64]);\n          %585 = transpose(%584, axes=[0, 2, 3, 1]);\n          %586 = reshape(%585, newshape=[-1, 64, 32]);\n          %587 = reshape(%582, newshape=[-1, 32, 64]);\n          %588 = transpose(%586, axes=[0, 2, 1]);\n          %589 = nn.batch_matmul(%587, %588, out_dtype=\"float32\", transpose_b=True);\n          %590 = reshape(%589, newshape=[50, 12, 32, 32]);\n          %591 = divide(%590, 8f);\n          %592 = multiply(%591, meta[relay.Constant][118]);\n          %593 = subtract(%592, meta[relay.Constant][119]);\n          %594 = nn.softmax(%593, axis=3);\n          %595 = %579.2;\n          %596 = reshape(%595, newshape=[50, 32, 12, 64]);\n          %597 = transpose(%596, axes=[0, 2, 1, 3]);\n          %598 = reshape(%597, newshape=[-1, 32, 64]);\n          %599 = reshape(%594, newshape=[-1, 32, 32]);\n          %600 = transpose(%598, axes=[0, 2, 1]);\n          %601 = nn.batch_matmul(%599, %600, out_dtype=\"float32\", transpose_b=True);\n          %602 = reshape(%601, newshape=[50, 12, 32, 64]);\n          %603 = transpose(%602, axes=[0, 2, 1, 3]);\n          %604 = reshape(%603, newshape=[50, 32, 768]);\n          %605 = reshape(%604, newshape=[-1, 768]);\n          %606 = nn.dense(%605, meta[relay.Constant][120], units=768);\n          %607 = add(%606, meta[relay.Constant][121]);\n          %608 = reshape(%607, newshape=[50, 32, 768]);\n          %609 = add(%565, %608);\n          %610 = mean(%609, axis=[-1], keepdims=True);\n          %611 = subtract(%609, %610);\n          %612 = power(%611, 2f);\n          %613 = mean(%612, axis=[-1], keepdims=True);\n          %614 = add(%613, 1e-05f);\n          %615 = sqrt(%614);\n          %616 = divide(%611, %615);\n          %617 = multiply(%616, meta[relay.Constant][122]);\n          %618 = add(%617, meta[relay.Constant][123]);\n          %619 = reshape(%618, newshape=[-1, 768]);\n          %620 = nn.dense(%619, meta[relay.Constant][124], units=3072);\n          %621 = add(%620, meta[relay.Constant][125]);\n          %622 = reshape(%621, newshape=[50, 32, 3072]);\n          %623 = power(%622, 3f);\n          %624 = multiply(%623, 0.044715f);\n          %625 = add(%622, %624);\n          %626 = multiply(%625, 0.797885f);\n          %627 = tanh(%626);\n          %628 = multiply(%622, 0.5f);\n          %629 = add(%627, 1f);\n          %630 = multiply(%628, %629);\n          %631 = reshape(%630, newshape=[-1, 3072]);\n          %632 = nn.dense(%631, meta[relay.Constant][126], units=768);\n          %633 = add(%632, meta[relay.Constant][127]);\n          %634 = reshape(%633, newshape=[50, 32, 768]);\n          %635 = add(%609, %634);\n          %636 = mean(%635, axis=[-1], keepdims=True);\n          %637 = subtract(%635, %636);\n          %638 = power(%637, 2f);\n          %639 = mean(%638, axis=[-1], keepdims=True);\n          %640 = add(%639, 1e-05f);\n          %641 = sqrt(%640);\n          %642 = divide(%637, %641);\n          %643 = multiply(%642, meta[relay.Constant][128]);\n          %644 = add(%643, meta[relay.Constant][129]);\n          %645 = reshape(%644, newshape=[-1, 768]);\n          %646 = nn.dense(%645, meta[relay.Constant][130], units=2304);\n          %647 = add(%646, meta[relay.Constant][131]);\n          %648 = reshape(%647, newshape=[50, 32, 2304]);\n          %649 = split(%648, indices_or_sections=[768, 1536], axis=2);\n          %650 = %649.0;\n          %651 = reshape(%650, newshape=[50, 32, 12, 64]);\n          %652 = transpose(%651, axes=[0, 2, 1, 3]);\n          %653 = %649.1;\n          %654 = reshape(%653, newshape=[50, 32, 12, 64]);\n          %655 = transpose(%654, axes=[0, 2, 3, 1]);\n          %656 = reshape(%655, newshape=[-1, 64, 32]);\n          %657 = reshape(%652, newshape=[-1, 32, 64]);\n          %658 = transpose(%656, axes=[0, 2, 1]);\n          %659 = nn.batch_matmul(%657, %658, out_dtype=\"float32\", transpose_b=True);\n          %660 = reshape(%659, newshape=[50, 12, 32, 32]);\n          %661 = divide(%660, 8f);\n          %662 = multiply(%661, meta[relay.Constant][132]);\n          %663 = subtract(%662, meta[relay.Constant][133]);\n          %664 = nn.softmax(%663, axis=3);\n          %665 = %649.2;\n          %666 = reshape(%665, newshape=[50, 32, 12, 64]);\n          %667 = transpose(%666, axes=[0, 2, 1, 3]);\n          %668 = reshape(%667, newshape=[-1, 32, 64]);\n          %669 = reshape(%664, newshape=[-1, 32, 32]);\n          %670 = transpose(%668, axes=[0, 2, 1]);\n          %671 = nn.batch_matmul(%669, %670, out_dtype=\"float32\", transpose_b=True);\n          %672 = reshape(%671, newshape=[50, 12, 32, 64]);\n          %673 = transpose(%672, axes=[0, 2, 1, 3]);\n          %674 = reshape(%673, newshape=[50, 32, 768]);\n          %675 = reshape(%674, newshape=[-1, 768]);\n          %676 = nn.dense(%675, meta[relay.Constant][134], units=768);\n          %677 = add(%676, meta[relay.Constant][135]);\n          %678 = reshape(%677, newshape=[50, 32, 768]);\n          %679 = add(%635, %678);\n          %680 = mean(%679, axis=[-1], keepdims=True);\n          %681 = subtract(%679, %680);\n          %682 = power(%681, 2f);\n          %683 = mean(%682, axis=[-1], keepdims=True);\n          %684 = add(%683, 1e-05f);\n          %685 = sqrt(%684);\n          %686 = divide(%681, %685);\n          %687 = multiply(%686, meta[relay.Constant][136]);\n          %688 = add(%687, meta[relay.Constant][137]);\n          %689 = reshape(%688, newshape=[-1, 768]);\n          %690 = nn.dense(%689, meta[relay.Constant][138], units=3072);\n          %691 = add(%690, meta[relay.Constant][139]);\n          %692 = reshape(%691, newshape=[50, 32, 3072]);\n          %693 = power(%692, 3f);\n          %694 = multiply(%693, 0.044715f);\n          %695 = add(%692, %694);\n          %696 = multiply(%695, 0.797885f);\n          %697 = tanh(%696);\n          %698 = multiply(%692, 0.5f);\n          %699 = add(%697, 1f);\n          %700 = multiply(%698, %699);\n          %701 = reshape(%700, newshape=[-1, 3072]);\n          %702 = nn.dense(%701, meta[relay.Constant][140], units=768);\n          %703 = add(%702, meta[relay.Constant][141]);\n          %704 = reshape(%703, newshape=[50, 32, 768]);\n          %705 = add(%679, %704);\n          %706 = mean(%705, axis=[-1], keepdims=True);\n          %707 = subtract(%705, %706);\n          %708 = power(%707, 2f);\n          %709 = mean(%708, axis=[-1], keepdims=True);\n          %710 = add(%709, 1e-05f);\n          %711 = sqrt(%710);\n          %712 = divide(%707, %711);\n          %713 = multiply(%712, meta[relay.Constant][142]);\n          %714 = add(%713, meta[relay.Constant][143]);\n          %715 = reshape(%714, newshape=[-1, 768]);\n          %716 = nn.dense(%715, meta[relay.Constant][144], units=2304);\n          %717 = add(%716, meta[relay.Constant][145]);\n          %718 = reshape(%717, newshape=[50, 32, 2304]);\n          %719 = split(%718, indices_or_sections=[768, 1536], axis=2);\n          %720 = %719.0;\n          %721 = reshape(%720, newshape=[50, 32, 12, 64]);\n          %722 = transpose(%721, axes=[0, 2, 1, 3]);\n          %723 = %719.1;\n          %724 = reshape(%723, newshape=[50, 32, 12, 64]);\n          %725 = transpose(%724, axes=[0, 2, 3, 1]);\n          %726 = reshape(%725, newshape=[-1, 64, 32]);\n          %727 = reshape(%722, newshape=[-1, 32, 64]);\n          %728 = transpose(%726, axes=[0, 2, 1]);\n          %729 = nn.batch_matmul(%727, %728, out_dtype=\"float32\", transpose_b=True);\n          %730 = reshape(%729, newshape=[50, 12, 32, 32]);\n          %731 = divide(%730, 8f);\n          %732 = multiply(%731, meta[relay.Constant][146]);\n          %733 = subtract(%732, meta[relay.Constant][147]);\n          %734 = nn.softmax(%733, axis=3);\n          %735 = %719.2;\n          %736 = reshape(%735, newshape=[50, 32, 12, 64]);\n          %737 = transpose(%736, axes=[0, 2, 1, 3]);\n          %738 = reshape(%737, newshape=[-1, 32, 64]);\n          %739 = reshape(%734, newshape=[-1, 32, 32]);\n          %740 = transpose(%738, axes=[0, 2, 1]);\n          %741 = nn.batch_matmul(%739, %740, out_dtype=\"float32\", transpose_b=True);\n          %742 = reshape(%741, newshape=[50, 12, 32, 64]);\n          %743 = transpose(%742, axes=[0, 2, 1, 3]);\n          %744 = reshape(%743, newshape=[50, 32, 768]);\n          %745 = reshape(%744, newshape=[-1, 768]);\n          %746 = nn.dense(%745, meta[relay.Constant][148], units=768);\n          %747 = add(%746, meta[relay.Constant][149]);\n          %748 = reshape(%747, newshape=[50, 32, 768]);\n          %749 = add(%705, %748);\n          %750 = mean(%749, axis=[-1], keepdims=True);\n          %751 = subtract(%749, %750);\n          %752 = power(%751, 2f);\n          %753 = mean(%752, axis=[-1], keepdims=True);\n          %754 = add(%753, 1e-05f);\n          %755 = sqrt(%754);\n          %756 = divide(%751, %755);\n          %757 = multiply(%756, meta[relay.Constant][150]);\n          %758 = add(%757, meta[relay.Constant][151]);\n          %759 = reshape(%758, newshape=[-1, 768]);\n          %760 = nn.dense(%759, meta[relay.Constant][152], units=3072);\n          %761 = add(%760, meta[relay.Constant][153]);\n          %762 = reshape(%761, newshape=[50, 32, 3072]);\n          %763 = power(%762, 3f);\n          %764 = multiply(%763, 0.044715f);\n          %765 = add(%762, %764);\n          %766 = multiply(%765, 0.797885f);\n          %767 = tanh(%766);\n          %768 = multiply(%762, 0.5f);\n          %769 = add(%767, 1f);\n          %770 = multiply(%768, %769);\n          %771 = reshape(%770, newshape=[-1, 3072]);\n          %772 = nn.dense(%771, meta[relay.Constant][154], units=768);\n          %773 = add(%772, meta[relay.Constant][155]);\n          %774 = reshape(%773, newshape=[50, 32, 768]);\n          %775 = add(%749, %774);\n          %776 = mean(%775, axis=[-1], keepdims=True);\n          %777 = subtract(%775, %776);\n          %778 = power(%777, 2f);\n          %779 = mean(%778, axis=[-1], keepdims=True);\n          %780 = add(%779, 1e-05f);\n          %781 = sqrt(%780);\n          %782 = divide(%777, %781);\n          %783 = multiply(%782, meta[relay.Constant][156]);\n          %784 = add(%783, meta[relay.Constant][157]);\n          %785 = reshape(%784, newshape=[-1, 768]);\n          %786 = nn.dense(%785, meta[relay.Constant][158], units=2304);\n          %787 = add(%786, meta[relay.Constant][159]);\n          %788 = reshape(%787, newshape=[50, 32, 2304]);\n          %789 = split(%788, indices_or_sections=[768, 1536], axis=2);\n          %790 = %789.0;\n          %791 = reshape(%790, newshape=[50, 32, 12, 64]);\n          %792 = transpose(%791, axes=[0, 2, 1, 3]);\n          %793 = %789.1;\n          %794 = reshape(%793, newshape=[50, 32, 12, 64]);\n          %795 = transpose(%794, axes=[0, 2, 3, 1]);\n          %796 = reshape(%795, newshape=[-1, 64, 32]);\n          %797 = reshape(%792, newshape=[-1, 32, 64]);\n          %798 = transpose(%796, axes=[0, 2, 1]);\n          %799 = nn.batch_matmul(%797, %798, out_dtype=\"float32\", transpose_b=True);\n          %800 = reshape(%799, newshape=[50, 12, 32, 32]);\n          %801 = divide(%800, 8f);\n          %802 = multiply(%801, meta[relay.Constant][160]);\n          %803 = subtract(%802, meta[relay.Constant][161]);\n          %804 = nn.softmax(%803, axis=3);\n          %805 = %789.2;\n          %806 = reshape(%805, newshape=[50, 32, 12, 64]);\n          %807 = transpose(%806, axes=[0, 2, 1, 3]);\n          %808 = reshape(%807, newshape=[-1, 32, 64]);\n          %809 = reshape(%804, newshape=[-1, 32, 32]);\n          %810 = transpose(%808, axes=[0, 2, 1]);\n          %811 = nn.batch_matmul(%809, %810, out_dtype=\"float32\", transpose_b=True);\n          %812 = reshape(%811, newshape=[50, 12, 32, 64]);\n          %813 = transpose(%812, axes=[0, 2, 1, 3]);\n          %814 = reshape(%813, newshape=[50, 32, 768]);\n          %815 = reshape(%814, newshape=[-1, 768]);\n          %816 = nn.dense(%815, meta[relay.Constant][162], units=768);\n          %817 = add(%816, meta[relay.Constant][163]);\n          %818 = reshape(%817, newshape=[50, 32, 768]);\n          %819 = add(%775, %818);\n          %820 = mean(%819, axis=[-1], keepdims=True);\n          %821 = subtract(%819, %820);\n          %822 = power(%821, 2f);\n          %823 = mean(%822, axis=[-1], keepdims=True);\n          %824 = add(%823, 1e-05f);\n          %825 = sqrt(%824);\n          %826 = divide(%821, %825);\n          %827 = multiply(%826, meta[relay.Constant][164]);\n          %828 = add(%827, meta[relay.Constant][165]);\n          %829 = reshape(%828, newshape=[-1, 768]);\n          %830 = nn.dense(%829, meta[relay.Constant][166], units=3072);\n          %831 = add(%830, meta[relay.Constant][167]);\n          %832 = reshape(%831, newshape=[50, 32, 3072]);\n          %833 = power(%832, 3f);\n          %834 = multiply(%833, 0.044715f);\n          %835 = add(%832, %834);\n          %836 = multiply(%835, 0.797885f);\n          %837 = tanh(%836);\n          %838 = multiply(%832, 0.5f);\n          %839 = add(%837, 1f);\n          %840 = multiply(%838, %839);\n          %841 = reshape(%840, newshape=[-1, 3072]);\n          %842 = nn.dense(%841, meta[relay.Constant][168], units=768);\n          %843 = add(%842, meta[relay.Constant][169]);\n          %844 = reshape(%843, newshape=[50, 32, 768]);\n          %845 = add(%819, %844);\n          %846 = mean(%845, axis=[-1], keepdims=True);\n          %847 = subtract(%845, %846);\n          %848 = power(%847, 2f);\n          %849 = mean(%848, axis=[-1], keepdims=True);\n          %850 = add(%849, 1e-05f);\n          %851 = sqrt(%850);\n          %852 = divide(%847, %851);\n          %853 = multiply(%852, meta[relay.Constant][170]);\n          %854 = add(%853, meta[relay.Constant][171]);\n          %855 = transpose(%24, axes=[0, 2, 1, 3]);\n          %856 = expand_dims(%855, axis=0);\n          %857 = expand_dims(%37, axis=0);\n          %858 = (%856, %857);\n          %859 = transpose(%94, axes=[0, 2, 1, 3]);\n          %860 = expand_dims(%859, axis=0);\n          %861 = expand_dims(%107, axis=0);\n          %862 = (%860, %861);\n          %863 = transpose(%164, axes=[0, 2, 1, 3]);\n          %864 = expand_dims(%863, axis=0);\n          %865 = expand_dims(%177, axis=0);\n          %866 = (%864, %865);\n          %867 = transpose(%234, axes=[0, 2, 1, 3]);\n          %868 = expand_dims(%867, axis=0);\n          %869 = expand_dims(%247, axis=0);\n          %870 = (%868, %869);\n          %871 = transpose(%304, axes=[0, 2, 1, 3]);\n          %872 = expand_dims(%871, axis=0);\n          %873 = expand_dims(%317, axis=0);\n          %874 = (%872, %873);\n          %875 = transpose(%374, axes=[0, 2, 1, 3]);\n          %876 = expand_dims(%875, axis=0);\n          %877 = expand_dims(%387, axis=0);\n          %878 = (%876, %877);\n          %879 = transpose(%444, axes=[0, 2, 1, 3]);\n          %880 = expand_dims(%879, axis=0);\n          %881 = expand_dims(%457, axis=0);\n          %882 = (%880, %881);\n          %883 = transpose(%514, axes=[0, 2, 1, 3]);\n          %884 = expand_dims(%883, axis=0);\n          %885 = expand_dims(%527, axis=0);\n          %886 = (%884, %885);\n          %887 = transpose(%584, axes=[0, 2, 1, 3]);\n          %888 = expand_dims(%887, axis=0);\n          %889 = expand_dims(%597, axis=0);\n          %890 = (%888, %889);\n          %891 = transpose(%654, axes=[0, 2, 1, 3]);\n          %892 = expand_dims(%891, axis=0);\n          %893 = expand_dims(%667, axis=0);\n          %894 = (%892, %893);\n          %895 = transpose(%724, axes=[0, 2, 1, 3]);\n          %896 = expand_dims(%895, axis=0);\n          %897 = expand_dims(%737, axis=0);\n          %898 = (%896, %897);\n          %899 = transpose(%794, axes=[0, 2, 1, 3]);\n          %900 = expand_dims(%899, axis=0);\n          %901 = expand_dims(%807, axis=0);\n          %902 = (%900, %901);\n          %903 = reshape(%854, newshape=[1, 50, 32, 768]);\n          %904 = concatenate(%858);\n          %905 = concatenate(%862);\n          %906 = concatenate(%866);\n          %907 = concatenate(%870);\n          %908 = concatenate(%874);\n          %909 = concatenate(%878);\n          %910 = concatenate(%882);\n          %911 = concatenate(%886);\n          %912 = concatenate(%890);\n          %913 = concatenate(%894);\n          %914 = concatenate(%898);\n          %915 = concatenate(%902);\n          (%903, %904, %905, %906, %907, %908, %909, %910, %911, %912, %913, %914, %915)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"gpt2\",\n        \"input_shapes\": {\"x\": [1, 50, 32]},\n        \"input_dtypes\": {\"x\": \"int64\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef gpt2_16():\n    metatable = {\"relay.Constant\": gpt2_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1, 50, 32), int64]) -> (Tensor[(1, 50, 32, 768), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16],\n                                                      Tensor[(2, 50, 12, 32, 64), float16]) {\n          %0 = reshape(%x, newshape=[-1, 32]);\n          %1 = less(%0, 0i64);\n          %2 = add(%0, 50257i64);\n          %3 = where(%1, %2, %0);\n          %4 = take(meta[relay.Constant][0], %3, axis=0);\n          %5 = add(%4, meta[relay.Constant][1]);\n          %6 = mean(%5, axis=[-1], keepdims=True);\n          %7 = subtract(%5, %6);\n          %8 = power(%7, 2f16);\n          %9 = mean(%8, axis=[-1], keepdims=True);\n          %10 = add(%9, 1e-05f16);\n          %11 = sqrt(%10);\n          %12 = divide(%7, %11);\n          %13 = multiply(%12, meta[relay.Constant][2]);\n          %14 = add(%13, meta[relay.Constant][3]);\n          %15 = reshape(%14, newshape=[-1, 768]);\n          %16 = nn.dense(%15, meta[relay.Constant][4], units=2304);\n          %17 = add(%16, meta[relay.Constant][5]);\n          %18 = reshape(%17, newshape=[50, 32, 2304]);\n          %19 = split(%18, indices_or_sections=[768, 1536], axis=2);\n          %20 = %19.0;\n          %21 = reshape(%20, newshape=[50, 32, 12, 64]);\n          %22 = transpose(%21, axes=[0, 2, 1, 3]);\n          %23 = %19.1;\n          %24 = reshape(%23, newshape=[50, 32, 12, 64]);\n          %25 = transpose(%24, axes=[0, 2, 3, 1]);\n          %26 = reshape(%25, newshape=[-1, 64, 32]);\n          %27 = reshape(%22, newshape=[-1, 32, 64]);\n          %28 = transpose(%26, axes=[0, 2, 1]);\n          %29 = nn.batch_matmul(%27, %28, out_dtype=\"float16\", transpose_b=True);\n          %30 = reshape(%29, newshape=[50, 12, 32, 32]);\n          %31 = divide(%30, 8f16);\n          %32 = multiply(%31, meta[relay.Constant][6]);\n          %33 = subtract(%32, meta[relay.Constant][7]);\n          %34 = nn.softmax(%33, axis=3);\n          %35 = %19.2;\n          %36 = reshape(%35, newshape=[50, 32, 12, 64]);\n          %37 = transpose(%36, axes=[0, 2, 1, 3]);\n          %38 = reshape(%37, newshape=[-1, 32, 64]);\n          %39 = reshape(%34, newshape=[-1, 32, 32]);\n          %40 = transpose(%38, axes=[0, 2, 1]);\n          %41 = nn.batch_matmul(%39, %40, out_dtype=\"float16\", transpose_b=True);\n          %42 = reshape(%41, newshape=[50, 12, 32, 64]);\n          %43 = transpose(%42, axes=[0, 2, 1, 3]);\n          %44 = reshape(%43, newshape=[50, 32, 768]);\n          %45 = reshape(%44, newshape=[-1, 768]);\n          %46 = nn.dense(%45, meta[relay.Constant][8], units=768);\n          %47 = add(%46, meta[relay.Constant][9]);\n          %48 = reshape(%47, newshape=[50, 32, 768]);\n          %49 = add(%5, %48);\n          %50 = mean(%49, axis=[-1], keepdims=True);\n          %51 = subtract(%49, %50);\n          %52 = power(%51, 2f16);\n          %53 = mean(%52, axis=[-1], keepdims=True);\n          %54 = add(%53, 1e-05f16);\n          %55 = sqrt(%54);\n          %56 = divide(%51, %55);\n          %57 = multiply(%56, meta[relay.Constant][10]);\n          %58 = add(%57, meta[relay.Constant][11]);\n          %59 = reshape(%58, newshape=[-1, 768]);\n          %60 = nn.dense(%59, meta[relay.Constant][12], units=3072);\n          %61 = add(%60, meta[relay.Constant][13]);\n          %62 = reshape(%61, newshape=[50, 32, 3072]);\n          %63 = power(%62, 3f16);\n          %64 = multiply(%63, 0.044715f16);\n          %65 = add(%62, %64);\n          %66 = multiply(%65, 0.797885f16);\n          %67 = tanh(%66);\n          %68 = multiply(%62, 0.5f16);\n          %69 = add(%67, 1f16);\n          %70 = multiply(%68, %69);\n          %71 = reshape(%70, newshape=[-1, 3072]);\n          %72 = nn.dense(%71, meta[relay.Constant][14], units=768);\n          %73 = add(%72, meta[relay.Constant][15]);\n          %74 = reshape(%73, newshape=[50, 32, 768]);\n          %75 = add(%49, %74);\n          %76 = mean(%75, axis=[-1], keepdims=True);\n          %77 = subtract(%75, %76);\n          %78 = power(%77, 2f16);\n          %79 = mean(%78, axis=[-1], keepdims=True);\n          %80 = add(%79, 1e-05f16);\n          %81 = sqrt(%80);\n          %82 = divide(%77, %81);\n          %83 = multiply(%82, meta[relay.Constant][16]);\n          %84 = add(%83, meta[relay.Constant][17]);\n          %85 = reshape(%84, newshape=[-1, 768]);\n          %86 = nn.dense(%85, meta[relay.Constant][18], units=2304);\n          %87 = add(%86, meta[relay.Constant][19]);\n          %88 = reshape(%87, newshape=[50, 32, 2304]);\n          %89 = split(%88, indices_or_sections=[768, 1536], axis=2);\n          %90 = %89.0;\n          %91 = reshape(%90, newshape=[50, 32, 12, 64]);\n          %92 = transpose(%91, axes=[0, 2, 1, 3]);\n          %93 = %89.1;\n          %94 = reshape(%93, newshape=[50, 32, 12, 64]);\n          %95 = transpose(%94, axes=[0, 2, 3, 1]);\n          %96 = reshape(%95, newshape=[-1, 64, 32]);\n          %97 = reshape(%92, newshape=[-1, 32, 64]);\n          %98 = transpose(%96, axes=[0, 2, 1]);\n          %99 = nn.batch_matmul(%97, %98, out_dtype=\"float16\", transpose_b=True);\n          %100 = reshape(%99, newshape=[50, 12, 32, 32]);\n          %101 = divide(%100, 8f16);\n          %102 = multiply(%101, meta[relay.Constant][20]);\n          %103 = subtract(%102, meta[relay.Constant][21]);\n          %104 = nn.softmax(%103, axis=3);\n          %105 = %89.2;\n          %106 = reshape(%105, newshape=[50, 32, 12, 64]);\n          %107 = transpose(%106, axes=[0, 2, 1, 3]);\n          %108 = reshape(%107, newshape=[-1, 32, 64]);\n          %109 = reshape(%104, newshape=[-1, 32, 32]);\n          %110 = transpose(%108, axes=[0, 2, 1]);\n          %111 = nn.batch_matmul(%109, %110, out_dtype=\"float16\", transpose_b=True);\n          %112 = reshape(%111, newshape=[50, 12, 32, 64]);\n          %113 = transpose(%112, axes=[0, 2, 1, 3]);\n          %114 = reshape(%113, newshape=[50, 32, 768]);\n          %115 = reshape(%114, newshape=[-1, 768]);\n          %116 = nn.dense(%115, meta[relay.Constant][22], units=768);\n          %117 = add(%116, meta[relay.Constant][23]);\n          %118 = reshape(%117, newshape=[50, 32, 768]);\n          %119 = add(%75, %118);\n          %120 = mean(%119, axis=[-1], keepdims=True);\n          %121 = subtract(%119, %120);\n          %122 = power(%121, 2f16);\n          %123 = mean(%122, axis=[-1], keepdims=True);\n          %124 = add(%123, 1e-05f16);\n          %125 = sqrt(%124);\n          %126 = divide(%121, %125);\n          %127 = multiply(%126, meta[relay.Constant][24]);\n          %128 = add(%127, meta[relay.Constant][25]);\n          %129 = reshape(%128, newshape=[-1, 768]);\n          %130 = nn.dense(%129, meta[relay.Constant][26], units=3072);\n          %131 = add(%130, meta[relay.Constant][27]);\n          %132 = reshape(%131, newshape=[50, 32, 3072]);\n          %133 = power(%132, 3f16);\n          %134 = multiply(%133, 0.044715f16);\n          %135 = add(%132, %134);\n          %136 = multiply(%135, 0.797885f16);\n          %137 = tanh(%136);\n          %138 = multiply(%132, 0.5f16);\n          %139 = add(%137, 1f16);\n          %140 = multiply(%138, %139);\n          %141 = reshape(%140, newshape=[-1, 3072]);\n          %142 = nn.dense(%141, meta[relay.Constant][28], units=768);\n          %143 = add(%142, meta[relay.Constant][29]);\n          %144 = reshape(%143, newshape=[50, 32, 768]);\n          %145 = add(%119, %144);\n          %146 = mean(%145, axis=[-1], keepdims=True);\n          %147 = subtract(%145, %146);\n          %148 = power(%147, 2f16);\n          %149 = mean(%148, axis=[-1], keepdims=True);\n          %150 = add(%149, 1e-05f16);\n          %151 = sqrt(%150);\n          %152 = divide(%147, %151);\n          %153 = multiply(%152, meta[relay.Constant][30]);\n          %154 = add(%153, meta[relay.Constant][31]);\n          %155 = reshape(%154, newshape=[-1, 768]);\n          %156 = nn.dense(%155, meta[relay.Constant][32], units=2304);\n          %157 = add(%156, meta[relay.Constant][33]);\n          %158 = reshape(%157, newshape=[50, 32, 2304]);\n          %159 = split(%158, indices_or_sections=[768, 1536], axis=2);\n          %160 = %159.0;\n          %161 = reshape(%160, newshape=[50, 32, 12, 64]);\n          %162 = transpose(%161, axes=[0, 2, 1, 3]);\n          %163 = %159.1;\n          %164 = reshape(%163, newshape=[50, 32, 12, 64]);\n          %165 = transpose(%164, axes=[0, 2, 3, 1]);\n          %166 = reshape(%165, newshape=[-1, 64, 32]);\n          %167 = reshape(%162, newshape=[-1, 32, 64]);\n          %168 = transpose(%166, axes=[0, 2, 1]);\n          %169 = nn.batch_matmul(%167, %168, out_dtype=\"float16\", transpose_b=True);\n          %170 = reshape(%169, newshape=[50, 12, 32, 32]);\n          %171 = divide(%170, 8f16);\n          %172 = multiply(%171, meta[relay.Constant][34]);\n          %173 = subtract(%172, meta[relay.Constant][35]);\n          %174 = nn.softmax(%173, axis=3);\n          %175 = %159.2;\n          %176 = reshape(%175, newshape=[50, 32, 12, 64]);\n          %177 = transpose(%176, axes=[0, 2, 1, 3]);\n          %178 = reshape(%177, newshape=[-1, 32, 64]);\n          %179 = reshape(%174, newshape=[-1, 32, 32]);\n          %180 = transpose(%178, axes=[0, 2, 1]);\n          %181 = nn.batch_matmul(%179, %180, out_dtype=\"float16\", transpose_b=True);\n          %182 = reshape(%181, newshape=[50, 12, 32, 64]);\n          %183 = transpose(%182, axes=[0, 2, 1, 3]);\n          %184 = reshape(%183, newshape=[50, 32, 768]);\n          %185 = reshape(%184, newshape=[-1, 768]);\n          %186 = nn.dense(%185, meta[relay.Constant][36], units=768);\n          %187 = add(%186, meta[relay.Constant][37]);\n          %188 = reshape(%187, newshape=[50, 32, 768]);\n          %189 = add(%145, %188);\n          %190 = mean(%189, axis=[-1], keepdims=True);\n          %191 = subtract(%189, %190);\n          %192 = power(%191, 2f16);\n          %193 = mean(%192, axis=[-1], keepdims=True);\n          %194 = add(%193, 1e-05f16);\n          %195 = sqrt(%194);\n          %196 = divide(%191, %195);\n          %197 = multiply(%196, meta[relay.Constant][38]);\n          %198 = add(%197, meta[relay.Constant][39]);\n          %199 = reshape(%198, newshape=[-1, 768]);\n          %200 = nn.dense(%199, meta[relay.Constant][40], units=3072);\n          %201 = add(%200, meta[relay.Constant][41]);\n          %202 = reshape(%201, newshape=[50, 32, 3072]);\n          %203 = power(%202, 3f16);\n          %204 = multiply(%203, 0.044715f16);\n          %205 = add(%202, %204);\n          %206 = multiply(%205, 0.797885f16);\n          %207 = tanh(%206);\n          %208 = multiply(%202, 0.5f16);\n          %209 = add(%207, 1f16);\n          %210 = multiply(%208, %209);\n          %211 = reshape(%210, newshape=[-1, 3072]);\n          %212 = nn.dense(%211, meta[relay.Constant][42], units=768);\n          %213 = add(%212, meta[relay.Constant][43]);\n          %214 = reshape(%213, newshape=[50, 32, 768]);\n          %215 = add(%189, %214);\n          %216 = mean(%215, axis=[-1], keepdims=True);\n          %217 = subtract(%215, %216);\n          %218 = power(%217, 2f16);\n          %219 = mean(%218, axis=[-1], keepdims=True);\n          %220 = add(%219, 1e-05f16);\n          %221 = sqrt(%220);\n          %222 = divide(%217, %221);\n          %223 = multiply(%222, meta[relay.Constant][44]);\n          %224 = add(%223, meta[relay.Constant][45]);\n          %225 = reshape(%224, newshape=[-1, 768]);\n          %226 = nn.dense(%225, meta[relay.Constant][46], units=2304);\n          %227 = add(%226, meta[relay.Constant][47]);\n          %228 = reshape(%227, newshape=[50, 32, 2304]);\n          %229 = split(%228, indices_or_sections=[768, 1536], axis=2);\n          %230 = %229.0;\n          %231 = reshape(%230, newshape=[50, 32, 12, 64]);\n          %232 = transpose(%231, axes=[0, 2, 1, 3]);\n          %233 = %229.1;\n          %234 = reshape(%233, newshape=[50, 32, 12, 64]);\n          %235 = transpose(%234, axes=[0, 2, 3, 1]);\n          %236 = reshape(%235, newshape=[-1, 64, 32]);\n          %237 = reshape(%232, newshape=[-1, 32, 64]);\n          %238 = transpose(%236, axes=[0, 2, 1]);\n          %239 = nn.batch_matmul(%237, %238, out_dtype=\"float16\", transpose_b=True);\n          %240 = reshape(%239, newshape=[50, 12, 32, 32]);\n          %241 = divide(%240, 8f16);\n          %242 = multiply(%241, meta[relay.Constant][48]);\n          %243 = subtract(%242, meta[relay.Constant][49]);\n          %244 = nn.softmax(%243, axis=3);\n          %245 = %229.2;\n          %246 = reshape(%245, newshape=[50, 32, 12, 64]);\n          %247 = transpose(%246, axes=[0, 2, 1, 3]);\n          %248 = reshape(%247, newshape=[-1, 32, 64]);\n          %249 = reshape(%244, newshape=[-1, 32, 32]);\n          %250 = transpose(%248, axes=[0, 2, 1]);\n          %251 = nn.batch_matmul(%249, %250, out_dtype=\"float16\", transpose_b=True);\n          %252 = reshape(%251, newshape=[50, 12, 32, 64]);\n          %253 = transpose(%252, axes=[0, 2, 1, 3]);\n          %254 = reshape(%253, newshape=[50, 32, 768]);\n          %255 = reshape(%254, newshape=[-1, 768]);\n          %256 = nn.dense(%255, meta[relay.Constant][50], units=768);\n          %257 = add(%256, meta[relay.Constant][51]);\n          %258 = reshape(%257, newshape=[50, 32, 768]);\n          %259 = add(%215, %258);\n          %260 = mean(%259, axis=[-1], keepdims=True);\n          %261 = subtract(%259, %260);\n          %262 = power(%261, 2f16);\n          %263 = mean(%262, axis=[-1], keepdims=True);\n          %264 = add(%263, 1e-05f16);\n          %265 = sqrt(%264);\n          %266 = divide(%261, %265);\n          %267 = multiply(%266, meta[relay.Constant][52]);\n          %268 = add(%267, meta[relay.Constant][53]);\n          %269 = reshape(%268, newshape=[-1, 768]);\n          %270 = nn.dense(%269, meta[relay.Constant][54], units=3072);\n          %271 = add(%270, meta[relay.Constant][55]);\n          %272 = reshape(%271, newshape=[50, 32, 3072]);\n          %273 = power(%272, 3f16);\n          %274 = multiply(%273, 0.044715f16);\n          %275 = add(%272, %274);\n          %276 = multiply(%275, 0.797885f16);\n          %277 = tanh(%276);\n          %278 = multiply(%272, 0.5f16);\n          %279 = add(%277, 1f16);\n          %280 = multiply(%278, %279);\n          %281 = reshape(%280, newshape=[-1, 3072]);\n          %282 = nn.dense(%281, meta[relay.Constant][56], units=768);\n          %283 = add(%282, meta[relay.Constant][57]);\n          %284 = reshape(%283, newshape=[50, 32, 768]);\n          %285 = add(%259, %284);\n          %286 = mean(%285, axis=[-1], keepdims=True);\n          %287 = subtract(%285, %286);\n          %288 = power(%287, 2f16);\n          %289 = mean(%288, axis=[-1], keepdims=True);\n          %290 = add(%289, 1e-05f16);\n          %291 = sqrt(%290);\n          %292 = divide(%287, %291);\n          %293 = multiply(%292, meta[relay.Constant][58]);\n          %294 = add(%293, meta[relay.Constant][59]);\n          %295 = reshape(%294, newshape=[-1, 768]);\n          %296 = nn.dense(%295, meta[relay.Constant][60], units=2304);\n          %297 = add(%296, meta[relay.Constant][61]);\n          %298 = reshape(%297, newshape=[50, 32, 2304]);\n          %299 = split(%298, indices_or_sections=[768, 1536], axis=2);\n          %300 = %299.0;\n          %301 = reshape(%300, newshape=[50, 32, 12, 64]);\n          %302 = transpose(%301, axes=[0, 2, 1, 3]);\n          %303 = %299.1;\n          %304 = reshape(%303, newshape=[50, 32, 12, 64]);\n          %305 = transpose(%304, axes=[0, 2, 3, 1]);\n          %306 = reshape(%305, newshape=[-1, 64, 32]);\n          %307 = reshape(%302, newshape=[-1, 32, 64]);\n          %308 = transpose(%306, axes=[0, 2, 1]);\n          %309 = nn.batch_matmul(%307, %308, out_dtype=\"float16\", transpose_b=True);\n          %310 = reshape(%309, newshape=[50, 12, 32, 32]);\n          %311 = divide(%310, 8f16);\n          %312 = multiply(%311, meta[relay.Constant][62]);\n          %313 = subtract(%312, meta[relay.Constant][63]);\n          %314 = nn.softmax(%313, axis=3);\n          %315 = %299.2;\n          %316 = reshape(%315, newshape=[50, 32, 12, 64]);\n          %317 = transpose(%316, axes=[0, 2, 1, 3]);\n          %318 = reshape(%317, newshape=[-1, 32, 64]);\n          %319 = reshape(%314, newshape=[-1, 32, 32]);\n          %320 = transpose(%318, axes=[0, 2, 1]);\n          %321 = nn.batch_matmul(%319, %320, out_dtype=\"float16\", transpose_b=True);\n          %322 = reshape(%321, newshape=[50, 12, 32, 64]);\n          %323 = transpose(%322, axes=[0, 2, 1, 3]);\n          %324 = reshape(%323, newshape=[50, 32, 768]);\n          %325 = reshape(%324, newshape=[-1, 768]);\n          %326 = nn.dense(%325, meta[relay.Constant][64], units=768);\n          %327 = add(%326, meta[relay.Constant][65]);\n          %328 = reshape(%327, newshape=[50, 32, 768]);\n          %329 = add(%285, %328);\n          %330 = mean(%329, axis=[-1], keepdims=True);\n          %331 = subtract(%329, %330);\n          %332 = power(%331, 2f16);\n          %333 = mean(%332, axis=[-1], keepdims=True);\n          %334 = add(%333, 1e-05f16);\n          %335 = sqrt(%334);\n          %336 = divide(%331, %335);\n          %337 = multiply(%336, meta[relay.Constant][66]);\n          %338 = add(%337, meta[relay.Constant][67]);\n          %339 = reshape(%338, newshape=[-1, 768]);\n          %340 = nn.dense(%339, meta[relay.Constant][68], units=3072);\n          %341 = add(%340, meta[relay.Constant][69]);\n          %342 = reshape(%341, newshape=[50, 32, 3072]);\n          %343 = power(%342, 3f16);\n          %344 = multiply(%343, 0.044715f16);\n          %345 = add(%342, %344);\n          %346 = multiply(%345, 0.797885f16);\n          %347 = tanh(%346);\n          %348 = multiply(%342, 0.5f16);\n          %349 = add(%347, 1f16);\n          %350 = multiply(%348, %349);\n          %351 = reshape(%350, newshape=[-1, 3072]);\n          %352 = nn.dense(%351, meta[relay.Constant][70], units=768);\n          %353 = add(%352, meta[relay.Constant][71]);\n          %354 = reshape(%353, newshape=[50, 32, 768]);\n          %355 = add(%329, %354);\n          %356 = mean(%355, axis=[-1], keepdims=True);\n          %357 = subtract(%355, %356);\n          %358 = power(%357, 2f16);\n          %359 = mean(%358, axis=[-1], keepdims=True);\n          %360 = add(%359, 1e-05f16);\n          %361 = sqrt(%360);\n          %362 = divide(%357, %361);\n          %363 = multiply(%362, meta[relay.Constant][72]);\n          %364 = add(%363, meta[relay.Constant][73]);\n          %365 = reshape(%364, newshape=[-1, 768]);\n          %366 = nn.dense(%365, meta[relay.Constant][74], units=2304);\n          %367 = add(%366, meta[relay.Constant][75]);\n          %368 = reshape(%367, newshape=[50, 32, 2304]);\n          %369 = split(%368, indices_or_sections=[768, 1536], axis=2);\n          %370 = %369.0;\n          %371 = reshape(%370, newshape=[50, 32, 12, 64]);\n          %372 = transpose(%371, axes=[0, 2, 1, 3]);\n          %373 = %369.1;\n          %374 = reshape(%373, newshape=[50, 32, 12, 64]);\n          %375 = transpose(%374, axes=[0, 2, 3, 1]);\n          %376 = reshape(%375, newshape=[-1, 64, 32]);\n          %377 = reshape(%372, newshape=[-1, 32, 64]);\n          %378 = transpose(%376, axes=[0, 2, 1]);\n          %379 = nn.batch_matmul(%377, %378, out_dtype=\"float16\", transpose_b=True);\n          %380 = reshape(%379, newshape=[50, 12, 32, 32]);\n          %381 = divide(%380, 8f16);\n          %382 = multiply(%381, meta[relay.Constant][76]);\n          %383 = subtract(%382, meta[relay.Constant][77]);\n          %384 = nn.softmax(%383, axis=3);\n          %385 = %369.2;\n          %386 = reshape(%385, newshape=[50, 32, 12, 64]);\n          %387 = transpose(%386, axes=[0, 2, 1, 3]);\n          %388 = reshape(%387, newshape=[-1, 32, 64]);\n          %389 = reshape(%384, newshape=[-1, 32, 32]);\n          %390 = transpose(%388, axes=[0, 2, 1]);\n          %391 = nn.batch_matmul(%389, %390, out_dtype=\"float16\", transpose_b=True);\n          %392 = reshape(%391, newshape=[50, 12, 32, 64]);\n          %393 = transpose(%392, axes=[0, 2, 1, 3]);\n          %394 = reshape(%393, newshape=[50, 32, 768]);\n          %395 = reshape(%394, newshape=[-1, 768]);\n          %396 = nn.dense(%395, meta[relay.Constant][78], units=768);\n          %397 = add(%396, meta[relay.Constant][79]);\n          %398 = reshape(%397, newshape=[50, 32, 768]);\n          %399 = add(%355, %398);\n          %400 = mean(%399, axis=[-1], keepdims=True);\n          %401 = subtract(%399, %400);\n          %402 = power(%401, 2f16);\n          %403 = mean(%402, axis=[-1], keepdims=True);\n          %404 = add(%403, 1e-05f16);\n          %405 = sqrt(%404);\n          %406 = divide(%401, %405);\n          %407 = multiply(%406, meta[relay.Constant][80]);\n          %408 = add(%407, meta[relay.Constant][81]);\n          %409 = reshape(%408, newshape=[-1, 768]);\n          %410 = nn.dense(%409, meta[relay.Constant][82], units=3072);\n          %411 = add(%410, meta[relay.Constant][83]);\n          %412 = reshape(%411, newshape=[50, 32, 3072]);\n          %413 = power(%412, 3f16);\n          %414 = multiply(%413, 0.044715f16);\n          %415 = add(%412, %414);\n          %416 = multiply(%415, 0.797885f16);\n          %417 = tanh(%416);\n          %418 = multiply(%412, 0.5f16);\n          %419 = add(%417, 1f16);\n          %420 = multiply(%418, %419);\n          %421 = reshape(%420, newshape=[-1, 3072]);\n          %422 = nn.dense(%421, meta[relay.Constant][84], units=768);\n          %423 = add(%422, meta[relay.Constant][85]);\n          %424 = reshape(%423, newshape=[50, 32, 768]);\n          %425 = add(%399, %424);\n          %426 = mean(%425, axis=[-1], keepdims=True);\n          %427 = subtract(%425, %426);\n          %428 = power(%427, 2f16);\n          %429 = mean(%428, axis=[-1], keepdims=True);\n          %430 = add(%429, 1e-05f16);\n          %431 = sqrt(%430);\n          %432 = divide(%427, %431);\n          %433 = multiply(%432, meta[relay.Constant][86]);\n          %434 = add(%433, meta[relay.Constant][87]);\n          %435 = reshape(%434, newshape=[-1, 768]);\n          %436 = nn.dense(%435, meta[relay.Constant][88], units=2304);\n          %437 = add(%436, meta[relay.Constant][89]);\n          %438 = reshape(%437, newshape=[50, 32, 2304]);\n          %439 = split(%438, indices_or_sections=[768, 1536], axis=2);\n          %440 = %439.0;\n          %441 = reshape(%440, newshape=[50, 32, 12, 64]);\n          %442 = transpose(%441, axes=[0, 2, 1, 3]);\n          %443 = %439.1;\n          %444 = reshape(%443, newshape=[50, 32, 12, 64]);\n          %445 = transpose(%444, axes=[0, 2, 3, 1]);\n          %446 = reshape(%445, newshape=[-1, 64, 32]);\n          %447 = reshape(%442, newshape=[-1, 32, 64]);\n          %448 = transpose(%446, axes=[0, 2, 1]);\n          %449 = nn.batch_matmul(%447, %448, out_dtype=\"float16\", transpose_b=True);\n          %450 = reshape(%449, newshape=[50, 12, 32, 32]);\n          %451 = divide(%450, 8f16);\n          %452 = multiply(%451, meta[relay.Constant][90]);\n          %453 = subtract(%452, meta[relay.Constant][91]);\n          %454 = nn.softmax(%453, axis=3);\n          %455 = %439.2;\n          %456 = reshape(%455, newshape=[50, 32, 12, 64]);\n          %457 = transpose(%456, axes=[0, 2, 1, 3]);\n          %458 = reshape(%457, newshape=[-1, 32, 64]);\n          %459 = reshape(%454, newshape=[-1, 32, 32]);\n          %460 = transpose(%458, axes=[0, 2, 1]);\n          %461 = nn.batch_matmul(%459, %460, out_dtype=\"float16\", transpose_b=True);\n          %462 = reshape(%461, newshape=[50, 12, 32, 64]);\n          %463 = transpose(%462, axes=[0, 2, 1, 3]);\n          %464 = reshape(%463, newshape=[50, 32, 768]);\n          %465 = reshape(%464, newshape=[-1, 768]);\n          %466 = nn.dense(%465, meta[relay.Constant][92], units=768);\n          %467 = add(%466, meta[relay.Constant][93]);\n          %468 = reshape(%467, newshape=[50, 32, 768]);\n          %469 = add(%425, %468);\n          %470 = mean(%469, axis=[-1], keepdims=True);\n          %471 = subtract(%469, %470);\n          %472 = power(%471, 2f16);\n          %473 = mean(%472, axis=[-1], keepdims=True);\n          %474 = add(%473, 1e-05f16);\n          %475 = sqrt(%474);\n          %476 = divide(%471, %475);\n          %477 = multiply(%476, meta[relay.Constant][94]);\n          %478 = add(%477, meta[relay.Constant][95]);\n          %479 = reshape(%478, newshape=[-1, 768]);\n          %480 = nn.dense(%479, meta[relay.Constant][96], units=3072);\n          %481 = add(%480, meta[relay.Constant][97]);\n          %482 = reshape(%481, newshape=[50, 32, 3072]);\n          %483 = power(%482, 3f16);\n          %484 = multiply(%483, 0.044715f16);\n          %485 = add(%482, %484);\n          %486 = multiply(%485, 0.797885f16);\n          %487 = tanh(%486);\n          %488 = multiply(%482, 0.5f16);\n          %489 = add(%487, 1f16);\n          %490 = multiply(%488, %489);\n          %491 = reshape(%490, newshape=[-1, 3072]);\n          %492 = nn.dense(%491, meta[relay.Constant][98], units=768);\n          %493 = add(%492, meta[relay.Constant][99]);\n          %494 = reshape(%493, newshape=[50, 32, 768]);\n          %495 = add(%469, %494);\n          %496 = mean(%495, axis=[-1], keepdims=True);\n          %497 = subtract(%495, %496);\n          %498 = power(%497, 2f16);\n          %499 = mean(%498, axis=[-1], keepdims=True);\n          %500 = add(%499, 1e-05f16);\n          %501 = sqrt(%500);\n          %502 = divide(%497, %501);\n          %503 = multiply(%502, meta[relay.Constant][100]);\n          %504 = add(%503, meta[relay.Constant][101]);\n          %505 = reshape(%504, newshape=[-1, 768]);\n          %506 = nn.dense(%505, meta[relay.Constant][102], units=2304);\n          %507 = add(%506, meta[relay.Constant][103]);\n          %508 = reshape(%507, newshape=[50, 32, 2304]);\n          %509 = split(%508, indices_or_sections=[768, 1536], axis=2);\n          %510 = %509.0;\n          %511 = reshape(%510, newshape=[50, 32, 12, 64]);\n          %512 = transpose(%511, axes=[0, 2, 1, 3]);\n          %513 = %509.1;\n          %514 = reshape(%513, newshape=[50, 32, 12, 64]);\n          %515 = transpose(%514, axes=[0, 2, 3, 1]);\n          %516 = reshape(%515, newshape=[-1, 64, 32]);\n          %517 = reshape(%512, newshape=[-1, 32, 64]);\n          %518 = transpose(%516, axes=[0, 2, 1]);\n          %519 = nn.batch_matmul(%517, %518, out_dtype=\"float16\", transpose_b=True);\n          %520 = reshape(%519, newshape=[50, 12, 32, 32]);\n          %521 = divide(%520, 8f16);\n          %522 = multiply(%521, meta[relay.Constant][104]);\n          %523 = subtract(%522, meta[relay.Constant][105]);\n          %524 = nn.softmax(%523, axis=3);\n          %525 = %509.2;\n          %526 = reshape(%525, newshape=[50, 32, 12, 64]);\n          %527 = transpose(%526, axes=[0, 2, 1, 3]);\n          %528 = reshape(%527, newshape=[-1, 32, 64]);\n          %529 = reshape(%524, newshape=[-1, 32, 32]);\n          %530 = transpose(%528, axes=[0, 2, 1]);\n          %531 = nn.batch_matmul(%529, %530, out_dtype=\"float16\", transpose_b=True);\n          %532 = reshape(%531, newshape=[50, 12, 32, 64]);\n          %533 = transpose(%532, axes=[0, 2, 1, 3]);\n          %534 = reshape(%533, newshape=[50, 32, 768]);\n          %535 = reshape(%534, newshape=[-1, 768]);\n          %536 = nn.dense(%535, meta[relay.Constant][106], units=768);\n          %537 = add(%536, meta[relay.Constant][107]);\n          %538 = reshape(%537, newshape=[50, 32, 768]);\n          %539 = add(%495, %538);\n          %540 = mean(%539, axis=[-1], keepdims=True);\n          %541 = subtract(%539, %540);\n          %542 = power(%541, 2f16);\n          %543 = mean(%542, axis=[-1], keepdims=True);\n          %544 = add(%543, 1e-05f16);\n          %545 = sqrt(%544);\n          %546 = divide(%541, %545);\n          %547 = multiply(%546, meta[relay.Constant][108]);\n          %548 = add(%547, meta[relay.Constant][109]);\n          %549 = reshape(%548, newshape=[-1, 768]);\n          %550 = nn.dense(%549, meta[relay.Constant][110], units=3072);\n          %551 = add(%550, meta[relay.Constant][111]);\n          %552 = reshape(%551, newshape=[50, 32, 3072]);\n          %553 = power(%552, 3f16);\n          %554 = multiply(%553, 0.044715f16);\n          %555 = add(%552, %554);\n          %556 = multiply(%555, 0.797885f16);\n          %557 = tanh(%556);\n          %558 = multiply(%552, 0.5f16);\n          %559 = add(%557, 1f16);\n          %560 = multiply(%558, %559);\n          %561 = reshape(%560, newshape=[-1, 3072]);\n          %562 = nn.dense(%561, meta[relay.Constant][112], units=768);\n          %563 = add(%562, meta[relay.Constant][113]);\n          %564 = reshape(%563, newshape=[50, 32, 768]);\n          %565 = add(%539, %564);\n          %566 = mean(%565, axis=[-1], keepdims=True);\n          %567 = subtract(%565, %566);\n          %568 = power(%567, 2f16);\n          %569 = mean(%568, axis=[-1], keepdims=True);\n          %570 = add(%569, 1e-05f16);\n          %571 = sqrt(%570);\n          %572 = divide(%567, %571);\n          %573 = multiply(%572, meta[relay.Constant][114]);\n          %574 = add(%573, meta[relay.Constant][115]);\n          %575 = reshape(%574, newshape=[-1, 768]);\n          %576 = nn.dense(%575, meta[relay.Constant][116], units=2304);\n          %577 = add(%576, meta[relay.Constant][117]);\n          %578 = reshape(%577, newshape=[50, 32, 2304]);\n          %579 = split(%578, indices_or_sections=[768, 1536], axis=2);\n          %580 = %579.0;\n          %581 = reshape(%580, newshape=[50, 32, 12, 64]);\n          %582 = transpose(%581, axes=[0, 2, 1, 3]);\n          %583 = %579.1;\n          %584 = reshape(%583, newshape=[50, 32, 12, 64]);\n          %585 = transpose(%584, axes=[0, 2, 3, 1]);\n          %586 = reshape(%585, newshape=[-1, 64, 32]);\n          %587 = reshape(%582, newshape=[-1, 32, 64]);\n          %588 = transpose(%586, axes=[0, 2, 1]);\n          %589 = nn.batch_matmul(%587, %588, out_dtype=\"float16\", transpose_b=True);\n          %590 = reshape(%589, newshape=[50, 12, 32, 32]);\n          %591 = divide(%590, 8f16);\n          %592 = multiply(%591, meta[relay.Constant][118]);\n          %593 = subtract(%592, meta[relay.Constant][119]);\n          %594 = nn.softmax(%593, axis=3);\n          %595 = %579.2;\n          %596 = reshape(%595, newshape=[50, 32, 12, 64]);\n          %597 = transpose(%596, axes=[0, 2, 1, 3]);\n          %598 = reshape(%597, newshape=[-1, 32, 64]);\n          %599 = reshape(%594, newshape=[-1, 32, 32]);\n          %600 = transpose(%598, axes=[0, 2, 1]);\n          %601 = nn.batch_matmul(%599, %600, out_dtype=\"float16\", transpose_b=True);\n          %602 = reshape(%601, newshape=[50, 12, 32, 64]);\n          %603 = transpose(%602, axes=[0, 2, 1, 3]);\n          %604 = reshape(%603, newshape=[50, 32, 768]);\n          %605 = reshape(%604, newshape=[-1, 768]);\n          %606 = nn.dense(%605, meta[relay.Constant][120], units=768);\n          %607 = add(%606, meta[relay.Constant][121]);\n          %608 = reshape(%607, newshape=[50, 32, 768]);\n          %609 = add(%565, %608);\n          %610 = mean(%609, axis=[-1], keepdims=True);\n          %611 = subtract(%609, %610);\n          %612 = power(%611, 2f16);\n          %613 = mean(%612, axis=[-1], keepdims=True);\n          %614 = add(%613, 1e-05f16);\n          %615 = sqrt(%614);\n          %616 = divide(%611, %615);\n          %617 = multiply(%616, meta[relay.Constant][122]);\n          %618 = add(%617, meta[relay.Constant][123]);\n          %619 = reshape(%618, newshape=[-1, 768]);\n          %620 = nn.dense(%619, meta[relay.Constant][124], units=3072);\n          %621 = add(%620, meta[relay.Constant][125]);\n          %622 = reshape(%621, newshape=[50, 32, 3072]);\n          %623 = power(%622, 3f16);\n          %624 = multiply(%623, 0.044715f16);\n          %625 = add(%622, %624);\n          %626 = multiply(%625, 0.797885f16);\n          %627 = tanh(%626);\n          %628 = multiply(%622, 0.5f16);\n          %629 = add(%627, 1f16);\n          %630 = multiply(%628, %629);\n          %631 = reshape(%630, newshape=[-1, 3072]);\n          %632 = nn.dense(%631, meta[relay.Constant][126], units=768);\n          %633 = add(%632, meta[relay.Constant][127]);\n          %634 = reshape(%633, newshape=[50, 32, 768]);\n          %635 = add(%609, %634);\n          %636 = mean(%635, axis=[-1], keepdims=True);\n          %637 = subtract(%635, %636);\n          %638 = power(%637, 2f16);\n          %639 = mean(%638, axis=[-1], keepdims=True);\n          %640 = add(%639, 1e-05f16);\n          %641 = sqrt(%640);\n          %642 = divide(%637, %641);\n          %643 = multiply(%642, meta[relay.Constant][128]);\n          %644 = add(%643, meta[relay.Constant][129]);\n          %645 = reshape(%644, newshape=[-1, 768]);\n          %646 = nn.dense(%645, meta[relay.Constant][130], units=2304);\n          %647 = add(%646, meta[relay.Constant][131]);\n          %648 = reshape(%647, newshape=[50, 32, 2304]);\n          %649 = split(%648, indices_or_sections=[768, 1536], axis=2);\n          %650 = %649.0;\n          %651 = reshape(%650, newshape=[50, 32, 12, 64]);\n          %652 = transpose(%651, axes=[0, 2, 1, 3]);\n          %653 = %649.1;\n          %654 = reshape(%653, newshape=[50, 32, 12, 64]);\n          %655 = transpose(%654, axes=[0, 2, 3, 1]);\n          %656 = reshape(%655, newshape=[-1, 64, 32]);\n          %657 = reshape(%652, newshape=[-1, 32, 64]);\n          %658 = transpose(%656, axes=[0, 2, 1]);\n          %659 = nn.batch_matmul(%657, %658, out_dtype=\"float16\", transpose_b=True);\n          %660 = reshape(%659, newshape=[50, 12, 32, 32]);\n          %661 = divide(%660, 8f16);\n          %662 = multiply(%661, meta[relay.Constant][132]);\n          %663 = subtract(%662, meta[relay.Constant][133]);\n          %664 = nn.softmax(%663, axis=3);\n          %665 = %649.2;\n          %666 = reshape(%665, newshape=[50, 32, 12, 64]);\n          %667 = transpose(%666, axes=[0, 2, 1, 3]);\n          %668 = reshape(%667, newshape=[-1, 32, 64]);\n          %669 = reshape(%664, newshape=[-1, 32, 32]);\n          %670 = transpose(%668, axes=[0, 2, 1]);\n          %671 = nn.batch_matmul(%669, %670, out_dtype=\"float16\", transpose_b=True);\n          %672 = reshape(%671, newshape=[50, 12, 32, 64]);\n          %673 = transpose(%672, axes=[0, 2, 1, 3]);\n          %674 = reshape(%673, newshape=[50, 32, 768]);\n          %675 = reshape(%674, newshape=[-1, 768]);\n          %676 = nn.dense(%675, meta[relay.Constant][134], units=768);\n          %677 = add(%676, meta[relay.Constant][135]);\n          %678 = reshape(%677, newshape=[50, 32, 768]);\n          %679 = add(%635, %678);\n          %680 = mean(%679, axis=[-1], keepdims=True);\n          %681 = subtract(%679, %680);\n          %682 = power(%681, 2f16);\n          %683 = mean(%682, axis=[-1], keepdims=True);\n          %684 = add(%683, 1e-05f16);\n          %685 = sqrt(%684);\n          %686 = divide(%681, %685);\n          %687 = multiply(%686, meta[relay.Constant][136]);\n          %688 = add(%687, meta[relay.Constant][137]);\n          %689 = reshape(%688, newshape=[-1, 768]);\n          %690 = nn.dense(%689, meta[relay.Constant][138], units=3072);\n          %691 = add(%690, meta[relay.Constant][139]);\n          %692 = reshape(%691, newshape=[50, 32, 3072]);\n          %693 = power(%692, 3f16);\n          %694 = multiply(%693, 0.044715f16);\n          %695 = add(%692, %694);\n          %696 = multiply(%695, 0.797885f16);\n          %697 = tanh(%696);\n          %698 = multiply(%692, 0.5f16);\n          %699 = add(%697, 1f16);\n          %700 = multiply(%698, %699);\n          %701 = reshape(%700, newshape=[-1, 3072]);\n          %702 = nn.dense(%701, meta[relay.Constant][140], units=768);\n          %703 = add(%702, meta[relay.Constant][141]);\n          %704 = reshape(%703, newshape=[50, 32, 768]);\n          %705 = add(%679, %704);\n          %706 = mean(%705, axis=[-1], keepdims=True);\n          %707 = subtract(%705, %706);\n          %708 = power(%707, 2f16);\n          %709 = mean(%708, axis=[-1], keepdims=True);\n          %710 = add(%709, 1e-05f16);\n          %711 = sqrt(%710);\n          %712 = divide(%707, %711);\n          %713 = multiply(%712, meta[relay.Constant][142]);\n          %714 = add(%713, meta[relay.Constant][143]);\n          %715 = reshape(%714, newshape=[-1, 768]);\n          %716 = nn.dense(%715, meta[relay.Constant][144], units=2304);\n          %717 = add(%716, meta[relay.Constant][145]);\n          %718 = reshape(%717, newshape=[50, 32, 2304]);\n          %719 = split(%718, indices_or_sections=[768, 1536], axis=2);\n          %720 = %719.0;\n          %721 = reshape(%720, newshape=[50, 32, 12, 64]);\n          %722 = transpose(%721, axes=[0, 2, 1, 3]);\n          %723 = %719.1;\n          %724 = reshape(%723, newshape=[50, 32, 12, 64]);\n          %725 = transpose(%724, axes=[0, 2, 3, 1]);\n          %726 = reshape(%725, newshape=[-1, 64, 32]);\n          %727 = reshape(%722, newshape=[-1, 32, 64]);\n          %728 = transpose(%726, axes=[0, 2, 1]);\n          %729 = nn.batch_matmul(%727, %728, out_dtype=\"float16\", transpose_b=True);\n          %730 = reshape(%729, newshape=[50, 12, 32, 32]);\n          %731 = divide(%730, 8f16);\n          %732 = multiply(%731, meta[relay.Constant][146]);\n          %733 = subtract(%732, meta[relay.Constant][147]);\n          %734 = nn.softmax(%733, axis=3);\n          %735 = %719.2;\n          %736 = reshape(%735, newshape=[50, 32, 12, 64]);\n          %737 = transpose(%736, axes=[0, 2, 1, 3]);\n          %738 = reshape(%737, newshape=[-1, 32, 64]);\n          %739 = reshape(%734, newshape=[-1, 32, 32]);\n          %740 = transpose(%738, axes=[0, 2, 1]);\n          %741 = nn.batch_matmul(%739, %740, out_dtype=\"float16\", transpose_b=True);\n          %742 = reshape(%741, newshape=[50, 12, 32, 64]);\n          %743 = transpose(%742, axes=[0, 2, 1, 3]);\n          %744 = reshape(%743, newshape=[50, 32, 768]);\n          %745 = reshape(%744, newshape=[-1, 768]);\n          %746 = nn.dense(%745, meta[relay.Constant][148], units=768);\n          %747 = add(%746, meta[relay.Constant][149]);\n          %748 = reshape(%747, newshape=[50, 32, 768]);\n          %749 = add(%705, %748);\n          %750 = mean(%749, axis=[-1], keepdims=True);\n          %751 = subtract(%749, %750);\n          %752 = power(%751, 2f16);\n          %753 = mean(%752, axis=[-1], keepdims=True);\n          %754 = add(%753, 1e-05f16);\n          %755 = sqrt(%754);\n          %756 = divide(%751, %755);\n          %757 = multiply(%756, meta[relay.Constant][150]);\n          %758 = add(%757, meta[relay.Constant][151]);\n          %759 = reshape(%758, newshape=[-1, 768]);\n          %760 = nn.dense(%759, meta[relay.Constant][152], units=3072);\n          %761 = add(%760, meta[relay.Constant][153]);\n          %762 = reshape(%761, newshape=[50, 32, 3072]);\n          %763 = power(%762, 3f16);\n          %764 = multiply(%763, 0.044715f16);\n          %765 = add(%762, %764);\n          %766 = multiply(%765, 0.797885f16);\n          %767 = tanh(%766);\n          %768 = multiply(%762, 0.5f16);\n          %769 = add(%767, 1f16);\n          %770 = multiply(%768, %769);\n          %771 = reshape(%770, newshape=[-1, 3072]);\n          %772 = nn.dense(%771, meta[relay.Constant][154], units=768);\n          %773 = add(%772, meta[relay.Constant][155]);\n          %774 = reshape(%773, newshape=[50, 32, 768]);\n          %775 = add(%749, %774);\n          %776 = mean(%775, axis=[-1], keepdims=True);\n          %777 = subtract(%775, %776);\n          %778 = power(%777, 2f16);\n          %779 = mean(%778, axis=[-1], keepdims=True);\n          %780 = add(%779, 1e-05f16);\n          %781 = sqrt(%780);\n          %782 = divide(%777, %781);\n          %783 = multiply(%782, meta[relay.Constant][156]);\n          %784 = add(%783, meta[relay.Constant][157]);\n          %785 = reshape(%784, newshape=[-1, 768]);\n          %786 = nn.dense(%785, meta[relay.Constant][158], units=2304);\n          %787 = add(%786, meta[relay.Constant][159]);\n          %788 = reshape(%787, newshape=[50, 32, 2304]);\n          %789 = split(%788, indices_or_sections=[768, 1536], axis=2);\n          %790 = %789.0;\n          %791 = reshape(%790, newshape=[50, 32, 12, 64]);\n          %792 = transpose(%791, axes=[0, 2, 1, 3]);\n          %793 = %789.1;\n          %794 = reshape(%793, newshape=[50, 32, 12, 64]);\n          %795 = transpose(%794, axes=[0, 2, 3, 1]);\n          %796 = reshape(%795, newshape=[-1, 64, 32]);\n          %797 = reshape(%792, newshape=[-1, 32, 64]);\n          %798 = transpose(%796, axes=[0, 2, 1]);\n          %799 = nn.batch_matmul(%797, %798, out_dtype=\"float16\", transpose_b=True);\n          %800 = reshape(%799, newshape=[50, 12, 32, 32]);\n          %801 = divide(%800, 8f16);\n          %802 = multiply(%801, meta[relay.Constant][160]);\n          %803 = subtract(%802, meta[relay.Constant][161]);\n          %804 = nn.softmax(%803, axis=3);\n          %805 = %789.2;\n          %806 = reshape(%805, newshape=[50, 32, 12, 64]);\n          %807 = transpose(%806, axes=[0, 2, 1, 3]);\n          %808 = reshape(%807, newshape=[-1, 32, 64]);\n          %809 = reshape(%804, newshape=[-1, 32, 32]);\n          %810 = transpose(%808, axes=[0, 2, 1]);\n          %811 = nn.batch_matmul(%809, %810, out_dtype=\"float16\", transpose_b=True);\n          %812 = reshape(%811, newshape=[50, 12, 32, 64]);\n          %813 = transpose(%812, axes=[0, 2, 1, 3]);\n          %814 = reshape(%813, newshape=[50, 32, 768]);\n          %815 = reshape(%814, newshape=[-1, 768]);\n          %816 = nn.dense(%815, meta[relay.Constant][162], units=768);\n          %817 = add(%816, meta[relay.Constant][163]);\n          %818 = reshape(%817, newshape=[50, 32, 768]);\n          %819 = add(%775, %818);\n          %820 = mean(%819, axis=[-1], keepdims=True);\n          %821 = subtract(%819, %820);\n          %822 = power(%821, 2f16);\n          %823 = mean(%822, axis=[-1], keepdims=True);\n          %824 = add(%823, 1e-05f16);\n          %825 = sqrt(%824);\n          %826 = divide(%821, %825);\n          %827 = multiply(%826, meta[relay.Constant][164]);\n          %828 = add(%827, meta[relay.Constant][165]);\n          %829 = reshape(%828, newshape=[-1, 768]);\n          %830 = nn.dense(%829, meta[relay.Constant][166], units=3072);\n          %831 = add(%830, meta[relay.Constant][167]);\n          %832 = reshape(%831, newshape=[50, 32, 3072]);\n          %833 = power(%832, 3f16);\n          %834 = multiply(%833, 0.044715f16);\n          %835 = add(%832, %834);\n          %836 = multiply(%835, 0.797885f16);\n          %837 = tanh(%836);\n          %838 = multiply(%832, 0.5f16);\n          %839 = add(%837, 1f16);\n          %840 = multiply(%838, %839);\n          %841 = reshape(%840, newshape=[-1, 3072]);\n          %842 = nn.dense(%841, meta[relay.Constant][168], units=768);\n          %843 = add(%842, meta[relay.Constant][169]);\n          %844 = reshape(%843, newshape=[50, 32, 768]);\n          %845 = add(%819, %844);\n          %846 = mean(%845, axis=[-1], keepdims=True);\n          %847 = subtract(%845, %846);\n          %848 = power(%847, 2f16);\n          %849 = mean(%848, axis=[-1], keepdims=True);\n          %850 = add(%849, 1e-05f16);\n          %851 = sqrt(%850);\n          %852 = divide(%847, %851);\n          %853 = multiply(%852, meta[relay.Constant][170]);\n          %854 = add(%853, meta[relay.Constant][171]);\n          %855 = transpose(%24, axes=[0, 2, 1, 3]);\n          %856 = expand_dims(%855, axis=0);\n          %857 = expand_dims(%37, axis=0);\n          %858 = (%856, %857);\n          %859 = transpose(%94, axes=[0, 2, 1, 3]);\n          %860 = expand_dims(%859, axis=0);\n          %861 = expand_dims(%107, axis=0);\n          %862 = (%860, %861);\n          %863 = transpose(%164, axes=[0, 2, 1, 3]);\n          %864 = expand_dims(%863, axis=0);\n          %865 = expand_dims(%177, axis=0);\n          %866 = (%864, %865);\n          %867 = transpose(%234, axes=[0, 2, 1, 3]);\n          %868 = expand_dims(%867, axis=0);\n          %869 = expand_dims(%247, axis=0);\n          %870 = (%868, %869);\n          %871 = transpose(%304, axes=[0, 2, 1, 3]);\n          %872 = expand_dims(%871, axis=0);\n          %873 = expand_dims(%317, axis=0);\n          %874 = (%872, %873);\n          %875 = transpose(%374, axes=[0, 2, 1, 3]);\n          %876 = expand_dims(%875, axis=0);\n          %877 = expand_dims(%387, axis=0);\n          %878 = (%876, %877);\n          %879 = transpose(%444, axes=[0, 2, 1, 3]);\n          %880 = expand_dims(%879, axis=0);\n          %881 = expand_dims(%457, axis=0);\n          %882 = (%880, %881);\n          %883 = transpose(%514, axes=[0, 2, 1, 3]);\n          %884 = expand_dims(%883, axis=0);\n          %885 = expand_dims(%527, axis=0);\n          %886 = (%884, %885);\n          %887 = transpose(%584, axes=[0, 2, 1, 3]);\n          %888 = expand_dims(%887, axis=0);\n          %889 = expand_dims(%597, axis=0);\n          %890 = (%888, %889);\n          %891 = transpose(%654, axes=[0, 2, 1, 3]);\n          %892 = expand_dims(%891, axis=0);\n          %893 = expand_dims(%667, axis=0);\n          %894 = (%892, %893);\n          %895 = transpose(%724, axes=[0, 2, 1, 3]);\n          %896 = expand_dims(%895, axis=0);\n          %897 = expand_dims(%737, axis=0);\n          %898 = (%896, %897);\n          %899 = transpose(%794, axes=[0, 2, 1, 3]);\n          %900 = expand_dims(%899, axis=0);\n          %901 = expand_dims(%807, axis=0);\n          %902 = (%900, %901);\n          %903 = reshape(%854, newshape=[1, 50, 32, 768]);\n          %904 = concatenate(%858);\n          %905 = concatenate(%862);\n          %906 = concatenate(%866);\n          %907 = concatenate(%870);\n          %908 = concatenate(%874);\n          %909 = concatenate(%878);\n          %910 = concatenate(%882);\n          %911 = concatenate(%886);\n          %912 = concatenate(%890);\n          %913 = concatenate(%894);\n          %914 = concatenate(%898);\n          %915 = concatenate(%902);\n          (%903, %904, %905, %906, %907, %908, %909, %910, %911, %912, %913, %914, %915)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"gpt2_16\",\n        \"input_shapes\": {\"x\": [1, 50, 32]},\n        \"input_dtypes\": {\"x\": \"int64\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef gpt2_extract_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (768, 768),  # 0\n            (768,),  # 1\n            (768,),  # 2\n            (768,),  # 3\n            (3072, 768),  # 4\n            (3072,),  # 5\n            (1, 32, 768),  # 6\n        ],\n    )\n\n\ndef gpt2_extract():\n    metatable = {\"relay.Constant\": gpt2_extract_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1600, 768), float32]) -> Tensor[(50, 32, 3072), float32] {\n            %46 = nn.dense(%x, meta[relay.Constant][0], units=768);\n            %47 = add(%46, meta[relay.Constant][1]);\n            %48 = reshape(%47, newshape=[50, 32, 768]);\n            %49 = add(meta[relay.Constant][6], %48);\n            %50 = mean(%49, axis=[-1], keepdims=True);\n            %51 = subtract(%49, %50);\n            %52 = power(%51, 2f);\n            %53 = mean(%52, axis=[-1], keepdims=True);\n            %54 = add(%53, 1e-05f);\n            %55 = sqrt(%54);\n            %56 = divide(%51, %55);\n            %57 = multiply(%56, meta[relay.Constant][2]);\n            %58 = add(%57, meta[relay.Constant][3]);\n            %59 = reshape(%58, newshape=[-1, 768]);\n            %60 = nn.dense(%59, meta[relay.Constant][4], units=3072);\n            %61 = add(%60, meta[relay.Constant][5]);\n            %62 = reshape(%61, newshape=[50, 32, 3072]);\n            %63 = power(%62, 3f);\n            %64 = multiply(%63, 0.044715f);\n            %65 = add(%62, %64);\n            %66 = multiply(%65, 0.797885f);\n            %67 = tanh(%66);\n            %68 = multiply(%62, 0.5f);\n            %69 = add(%67, 1f);\n            %70 = multiply(%68, %69);\n            %70\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"input_shapes\": {\"x\": [1600, 768]},\n        \"input_dtypes\": {\"x\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef gpt2_extract_16():\n    metatable = {\"relay.Constant\": gpt2_extract_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1600, 768), float16]) -> Tensor[(50, 32, 3072), float16] {\n            %46 = nn.dense(%x, meta[relay.Constant][0], units=768);\n            %47 = add(%46, meta[relay.Constant][1]);\n            %48 = reshape(%47, newshape=[50, 32, 768]);\n            %49 = add(meta[relay.Constant][6], %48);\n            %50 = mean(%49, axis=[-1], keepdims=True);\n            %51 = subtract(%49, %50);\n            %52 = power(%51, 2f16);\n            %53 = mean(%52, axis=[-1], keepdims=True);\n            %54 = add(%53, 1e-05f16);\n            %55 = sqrt(%54);\n            %56 = divide(%51, %55);\n            %57 = multiply(%56, meta[relay.Constant][2]);\n            %58 = add(%57, meta[relay.Constant][3]);\n            %59 = reshape(%58, newshape=[-1, 768]);\n            %60 = nn.dense(%59, meta[relay.Constant][4], units=3072);\n            %61 = add(%60, meta[relay.Constant][5]);\n            %62 = reshape(%61, newshape=[50, 32, 3072]);\n            %63 = power(%62, 3f16);\n            %64 = multiply(%63, 0.044715f16);\n            %65 = add(%62, %64);\n            %66 = multiply(%65, 0.797885f16);\n            %67 = tanh(%66);\n            %68 = multiply(%62, 0.5f16);\n            %69 = add(%67, 1f16);\n            %70 = multiply(%68, %69);\n            %70\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"gpt2_extract_16\",\n        \"input_shapes\": {\"x\": [1600, 768]},\n        \"input_dtypes\": {\"x\": \"float16\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef gpt2_16_for_cutlass_extract_consts(dtype):\n    return make_consts(\n        \"float16\",\n        [\n            (2304, 768),  # 0\n            (2304,),  # 1\n            (600, 32, 64),  # 2\n            (600, 32, 32),  # 3\n        ],\n    )\n\n\ndef gpt2_16_for_cutlass_extract():\n    metatable = {\"relay.Constant\": gpt2_16_for_cutlass_extract_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0: Tensor[(1600, 768), float16],\n                  %x3: Tensor[(600, 32, 64), float16])\n            -> (Tensor[(1600, 2304), float16], Tensor[(1200, 32, 32), float16]) {\n          %0 = nn.dense(%x0, meta[relay.Constant][0], units=2304);\n          %1 = add(%0, meta[relay.Constant][1]);\n          %2 = nn.batch_matmul(%x3, meta[relay.Constant][2], out_dtype=\"float16\", transpose_b=True);\n          %3 = (%2, meta[relay.Constant][3]);\n          %4 = concatenate(%3);\n          (%1, %4)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"gpt2_16_for_cutlass_extract\",\n        \"input_shapes\": {\"x0\": (1600, 768), \"x3\": (600, 32, 64)},\n        \"input_dtypes\": {\"x0\": \"float16\", \"x3\": \"float16\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef resnet50_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (3,),  # 0\n            (3,),  # 1\n            (3,),  # 2\n            (3,),  # 3\n            (64, 3, 7, 7),  # 4\n            (64,),  # 5\n            (64,),  # 6\n            (64,),  # 7\n            (64,),  # 8\n            (64,),  # 9\n            (64,),  # 10\n            (64,),  # 11\n            (64,),  # 12\n            (64, 64, 1, 1),  # 13\n            (64,),  # 14\n            (64,),  # 15\n            (64,),  # 16\n            (64,),  # 17\n            (64, 64, 3, 3),  # 18\n            (64,),  # 19\n            (64,),  # 20\n            (64,),  # 21\n            (64,),  # 22\n            (256, 64, 1, 1),  # 23\n            (256, 64, 1, 1),  # 24\n            (256,),  # 25\n            (256,),  # 26\n            (256,),  # 27\n            (256,),  # 28\n            (64, 256, 1, 1),  # 29\n            (64,),  # 30\n            (64,),  # 31\n            (64,),  # 32\n            (64,),  # 33\n            (64, 64, 3, 3),  # 34\n            (64,),  # 35\n            (64,),  # 36\n            (64,),  # 37\n            (64,),  # 38\n            (256, 64, 1, 1),  # 39\n            (256,),  # 40\n            (256,),  # 41\n            (256,),  # 42\n            (256,),  # 43\n            (64, 256, 1, 1),  # 44\n            (64,),  # 45\n            (64,),  # 46\n            (64,),  # 47\n            (64,),  # 48\n            (64, 64, 3, 3),  # 49\n            (64,),  # 50\n            (64,),  # 51\n            (64,),  # 52\n            (64,),  # 53\n            (256, 64, 1, 1),  # 54\n            (256,),  # 55\n            (256,),  # 56\n            (256,),  # 57\n            (256,),  # 58\n            (128, 256, 1, 1),  # 59\n            (128,),  # 60\n            (128,),  # 61\n            (128,),  # 62\n            (128,),  # 63\n            (128, 128, 3, 3),  # 64\n            (128,),  # 65\n            (128,),  # 66\n            (128,),  # 67\n            (128,),  # 68\n            (512, 128, 1, 1),  # 69\n            (512, 256, 1, 1),  # 70\n            (512,),  # 71\n            (512,),  # 72\n            (512,),  # 73\n            (512,),  # 74\n            (128, 512, 1, 1),  # 75\n            (128,),  # 76\n            (128,),  # 77\n            (128,),  # 78\n            (128,),  # 79\n            (128, 128, 3, 3),  # 80\n            (128,),  # 81\n            (128,),  # 82\n            (128,),  # 83\n            (128,),  # 84\n            (512, 128, 1, 1),  # 85\n            (512,),  # 86\n            (512,),  # 87\n            (512,),  # 88\n            (512,),  # 89\n            (128, 512, 1, 1),  # 90\n            (128,),  # 91\n            (128,),  # 92\n            (128,),  # 93\n            (128,),  # 94\n            (128, 128, 3, 3),  # 95\n            (128,),  # 96\n            (128,),  # 97\n            (128,),  # 98\n            (128,),  # 99\n            (512, 128, 1, 1),  # 100\n            (512,),  # 101\n            (512,),  # 102\n            (512,),  # 103\n            (512,),  # 104\n            (128, 512, 1, 1),  # 105\n            (128,),  # 106\n            (128,),  # 107\n            (128,),  # 108\n            (128,),  # 109\n            (128, 128, 3, 3),  # 110\n            (128,),  # 111\n            (128,),  # 112\n            (128,),  # 113\n            (128,),  # 114\n            (512, 128, 1, 1),  # 115\n            (512,),  # 116\n            (512,),  # 117\n            (512,),  # 118\n            (512,),  # 119\n            (256, 512, 1, 1),  # 120\n            (256,),  # 121\n            (256,),  # 122\n            (256,),  # 123\n            (256,),  # 124\n            (256, 256, 3, 3),  # 125\n            (256,),  # 126\n            (256,),  # 127\n            (256,),  # 128\n            (256,),  # 129\n            (1024, 256, 1, 1),  # 130\n            (1024, 512, 1, 1),  # 131\n            (1024,),  # 132\n            (1024,),  # 133\n            (1024,),  # 134\n            (1024,),  # 135\n            (256, 1024, 1, 1),  # 136\n            (256,),  # 137\n            (256,),  # 138\n            (256,),  # 139\n            (256,),  # 140\n            (256, 256, 3, 3),  # 141\n            (256,),  # 142\n            (256,),  # 143\n            (256,),  # 144\n            (256,),  # 145\n            (1024, 256, 1, 1),  # 146\n            (1024,),  # 147\n            (1024,),  # 148\n            (1024,),  # 149\n            (1024,),  # 150\n            (256, 1024, 1, 1),  # 151\n            (256,),  # 152\n            (256,),  # 153\n            (256,),  # 154\n            (256,),  # 155\n            (256, 256, 3, 3),  # 156\n            (256,),  # 157\n            (256,),  # 158\n            (256,),  # 159\n            (256,),  # 160\n            (1024, 256, 1, 1),  # 161\n            (1024,),  # 162\n            (1024,),  # 163\n            (1024,),  # 164\n            (1024,),  # 165\n            (256, 1024, 1, 1),  # 166\n            (256,),  # 167\n            (256,),  # 168\n            (256,),  # 169\n            (256,),  # 170\n            (256, 256, 3, 3),  # 171\n            (256,),  # 172\n            (256,),  # 173\n            (256,),  # 174\n            (256,),  # 175\n            (1024, 256, 1, 1),  # 176\n            (1024,),  # 177\n            (1024,),  # 178\n            (1024,),  # 179\n            (1024,),  # 180\n            (256, 1024, 1, 1),  # 181\n            (256,),  # 182\n            (256,),  # 183\n            (256,),  # 184\n            (256,),  # 185\n            (256, 256, 3, 3),  # 186\n            (256,),  # 187\n            (256,),  # 188\n            (256,),  # 189\n            (256,),  # 190\n            (1024, 256, 1, 1),  # 191\n            (1024,),  # 192\n            (1024,),  # 193\n            (1024,),  # 194\n            (1024,),  # 195\n            (256, 1024, 1, 1),  # 196\n            (256,),  # 197\n            (256,),  # 198\n            (256,),  # 199\n            (256,),  # 200\n            (256, 256, 3, 3),  # 201\n            (256,),  # 202\n            (256,),  # 203\n            (256,),  # 204\n            (256,),  # 205\n            (1024, 256, 1, 1),  # 206\n            (1024,),  # 207\n            (1024,),  # 208\n            (1024,),  # 209\n            (1024,),  # 210\n            (512, 1024, 1, 1),  # 211\n            (512,),  # 212\n            (512,),  # 213\n            (512,),  # 214\n            (512,),  # 215\n            (512, 512, 3, 3),  # 216\n            (512,),  # 217\n            (512,),  # 218\n            (512,),  # 219\n            (512,),  # 220\n            (2048, 512, 1, 1),  # 221\n            (2048, 1024, 1, 1),  # 222\n            (2048,),  # 223\n            (2048,),  # 224\n            (2048,),  # 225\n            (2048,),  # 226\n            (512, 2048, 1, 1),  # 227\n            (512,),  # 228\n            (512,),  # 229\n            (512,),  # 230\n            (512,),  # 231\n            (512, 512, 3, 3),  # 232\n            (512,),  # 233\n            (512,),  # 234\n            (512,),  # 235\n            (512,),  # 236\n            (2048, 512, 1, 1),  # 237\n            (2048,),  # 238\n            (2048,),  # 239\n            (2048,),  # 240\n            (2048,),  # 241\n            (512, 2048, 1, 1),  # 242\n            (512,),  # 243\n            (512,),  # 244\n            (512,),  # 245\n            (512,),  # 246\n            (512, 512, 3, 3),  # 247\n            (512,),  # 248\n            (512,),  # 249\n            (512,),  # 250\n            (512,),  # 251\n            (2048, 512, 1, 1),  # 252\n            (2048,),  # 253\n            (2048,),  # 254\n            (2048,),  # 255\n            (2048,),  # 256\n            (1000, 2048),  # 257\n            (1000,),  # 258\n        ],\n    )\n\n\ndef resnet50():\n    metatable = {\"relay.Constant\": resnet50_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(1, 3, 224, 224), float32]) -> Tensor[(1, 1000), float32] {\n          %0 = nn.batch_norm(%data, meta[relay.Constant][0], meta[relay.Constant][1], meta[relay.Constant][2], meta[relay.Constant][3]);\n          %1 = %0.0;\n          %2 = nn.conv2d(%1, meta[relay.Constant][4], strides=[2, 2], padding=[3, 3, 3, 3], channels=64, kernel_size=[7, 7]);\n          %3 = nn.batch_norm(%2, meta[relay.Constant][5], meta[relay.Constant][6], meta[relay.Constant][7], meta[relay.Constant][8]);\n          %4 = %3.0;\n          %5 = nn.relu(%4);\n          %6 = nn.max_pool2d(%5, pool_size=[3, 3], strides=[2, 2], padding=[1, 1, 1, 1]);\n          %7 = nn.batch_norm(%6, meta[relay.Constant][9], meta[relay.Constant][10], meta[relay.Constant][11], meta[relay.Constant][12]);\n          %8 = %7.0;\n          %9 = nn.relu(%8);\n          %10 = nn.conv2d(%9, meta[relay.Constant][13], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %11 = nn.batch_norm(%10, meta[relay.Constant][14], meta[relay.Constant][15], meta[relay.Constant][16], meta[relay.Constant][17]);\n          %12 = %11.0;\n          %13 = nn.relu(%12);\n          %14 = nn.conv2d(%13, meta[relay.Constant][18], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %15 = nn.batch_norm(%14, meta[relay.Constant][19], meta[relay.Constant][20], meta[relay.Constant][21], meta[relay.Constant][22]);\n          %16 = %15.0;\n          %17 = nn.relu(%16);\n          %18 = nn.conv2d(%17, meta[relay.Constant][23], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %19 = nn.conv2d(%9, meta[relay.Constant][24], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %20 = add(%18, %19);\n          %21 = nn.batch_norm(%20, meta[relay.Constant][25], meta[relay.Constant][26], meta[relay.Constant][27], meta[relay.Constant][28]);\n          %22 = %21.0;\n          %23 = nn.relu(%22);\n          %24 = nn.conv2d(%23, meta[relay.Constant][29], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %25 = nn.batch_norm(%24, meta[relay.Constant][30], meta[relay.Constant][31], meta[relay.Constant][32], meta[relay.Constant][33]);\n          %26 = %25.0;\n          %27 = nn.relu(%26);\n          %28 = nn.conv2d(%27, meta[relay.Constant][34], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %29 = nn.batch_norm(%28, meta[relay.Constant][35], meta[relay.Constant][36], meta[relay.Constant][37], meta[relay.Constant][38]);\n          %30 = %29.0;\n          %31 = nn.relu(%30);\n          %32 = nn.conv2d(%31, meta[relay.Constant][39], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %33 = add(%32, %20);\n          %34 = nn.batch_norm(%33, meta[relay.Constant][40], meta[relay.Constant][41], meta[relay.Constant][42], meta[relay.Constant][43]);\n          %35 = %34.0;\n          %36 = nn.relu(%35);\n          %37 = nn.conv2d(%36, meta[relay.Constant][44], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %38 = nn.batch_norm(%37, meta[relay.Constant][45], meta[relay.Constant][46], meta[relay.Constant][47], meta[relay.Constant][48]);\n          %39 = %38.0;\n          %40 = nn.relu(%39);\n          %41 = nn.conv2d(%40, meta[relay.Constant][49], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %42 = nn.batch_norm(%41, meta[relay.Constant][50], meta[relay.Constant][51], meta[relay.Constant][52], meta[relay.Constant][53]);\n          %43 = %42.0;\n          %44 = nn.relu(%43);\n          %45 = nn.conv2d(%44, meta[relay.Constant][54], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %46 = add(%45, %33);\n          %47 = nn.batch_norm(%46, meta[relay.Constant][55], meta[relay.Constant][56], meta[relay.Constant][57], meta[relay.Constant][58]);\n          %48 = %47.0;\n          %49 = nn.relu(%48);\n          %50 = nn.conv2d(%49, meta[relay.Constant][59], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %51 = nn.batch_norm(%50, meta[relay.Constant][60], meta[relay.Constant][61], meta[relay.Constant][62], meta[relay.Constant][63]);\n          %52 = %51.0;\n          %53 = nn.relu(%52);\n          %54 = nn.conv2d(%53, meta[relay.Constant][64], strides=[2, 2], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %55 = nn.batch_norm(%54, meta[relay.Constant][65], meta[relay.Constant][66], meta[relay.Constant][67], meta[relay.Constant][68]);\n          %56 = %55.0;\n          %57 = nn.relu(%56);\n          %58 = nn.conv2d(%57, meta[relay.Constant][69], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %59 = nn.conv2d(%49, meta[relay.Constant][70], strides=[2, 2], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %60 = add(%58, %59);\n          %61 = nn.batch_norm(%60, meta[relay.Constant][71], meta[relay.Constant][72], meta[relay.Constant][73], meta[relay.Constant][74]);\n          %62 = %61.0;\n          %63 = nn.relu(%62);\n          %64 = nn.conv2d(%63, meta[relay.Constant][75], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %65 = nn.batch_norm(%64, meta[relay.Constant][76], meta[relay.Constant][77], meta[relay.Constant][78], meta[relay.Constant][79]);\n          %66 = %65.0;\n          %67 = nn.relu(%66);\n          %68 = nn.conv2d(%67, meta[relay.Constant][80], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %69 = nn.batch_norm(%68, meta[relay.Constant][81], meta[relay.Constant][82], meta[relay.Constant][83], meta[relay.Constant][84]);\n          %70 = %69.0;\n          %71 = nn.relu(%70);\n          %72 = nn.conv2d(%71, meta[relay.Constant][85], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %73 = add(%72, %60);\n          %74 = nn.batch_norm(%73, meta[relay.Constant][86], meta[relay.Constant][87], meta[relay.Constant][88], meta[relay.Constant][89]);\n          %75 = %74.0;\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][90], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %78 = nn.batch_norm(%77, meta[relay.Constant][91], meta[relay.Constant][92], meta[relay.Constant][93], meta[relay.Constant][94]);\n          %79 = %78.0;\n          %80 = nn.relu(%79);\n          %81 = nn.conv2d(%80, meta[relay.Constant][95], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %82 = nn.batch_norm(%81, meta[relay.Constant][96], meta[relay.Constant][97], meta[relay.Constant][98], meta[relay.Constant][99]);\n          %83 = %82.0;\n          %84 = nn.relu(%83);\n          %85 = nn.conv2d(%84, meta[relay.Constant][100], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %86 = add(%85, %73);\n          %87 = nn.batch_norm(%86, meta[relay.Constant][101], meta[relay.Constant][102], meta[relay.Constant][103], meta[relay.Constant][104]);\n          %88 = %87.0;\n          %89 = nn.relu(%88);\n          %90 = nn.conv2d(%89, meta[relay.Constant][105], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %91 = nn.batch_norm(%90, meta[relay.Constant][106], meta[relay.Constant][107], meta[relay.Constant][108], meta[relay.Constant][109]);\n          %92 = %91.0;\n          %93 = nn.relu(%92);\n          %94 = nn.conv2d(%93, meta[relay.Constant][110], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %95 = nn.batch_norm(%94, meta[relay.Constant][111], meta[relay.Constant][112], meta[relay.Constant][113], meta[relay.Constant][114]);\n          %96 = %95.0;\n          %97 = nn.relu(%96);\n          %98 = nn.conv2d(%97, meta[relay.Constant][115], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %99 = add(%98, %86);\n          %100 = nn.batch_norm(%99, meta[relay.Constant][116], meta[relay.Constant][117], meta[relay.Constant][118], meta[relay.Constant][119]);\n          %101 = %100.0;\n          %102 = nn.relu(%101);\n          %103 = nn.conv2d(%102, meta[relay.Constant][120], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %104 = nn.batch_norm(%103, meta[relay.Constant][121], meta[relay.Constant][122], meta[relay.Constant][123], meta[relay.Constant][124]);\n          %105 = %104.0;\n          %106 = nn.relu(%105);\n          %107 = nn.conv2d(%106, meta[relay.Constant][125], strides=[2, 2], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %108 = nn.batch_norm(%107, meta[relay.Constant][126], meta[relay.Constant][127], meta[relay.Constant][128], meta[relay.Constant][129]);\n          %109 = %108.0;\n          %110 = nn.relu(%109);\n          %111 = nn.conv2d(%110, meta[relay.Constant][130], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %112 = nn.conv2d(%102, meta[relay.Constant][131], strides=[2, 2], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %113 = add(%111, %112);\n          %114 = nn.batch_norm(%113, meta[relay.Constant][132], meta[relay.Constant][133], meta[relay.Constant][134], meta[relay.Constant][135]);\n          %115 = %114.0;\n          %116 = nn.relu(%115);\n          %117 = nn.conv2d(%116, meta[relay.Constant][136], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %118 = nn.batch_norm(%117, meta[relay.Constant][137], meta[relay.Constant][138], meta[relay.Constant][139], meta[relay.Constant][140]);\n          %119 = %118.0;\n          %120 = nn.relu(%119);\n          %121 = nn.conv2d(%120, meta[relay.Constant][141], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %122 = nn.batch_norm(%121, meta[relay.Constant][142], meta[relay.Constant][143], meta[relay.Constant][144], meta[relay.Constant][145]);\n          %123 = %122.0;\n          %124 = nn.relu(%123);\n          %125 = nn.conv2d(%124, meta[relay.Constant][146], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %126 = add(%125, %113);\n          %127 = nn.batch_norm(%126, meta[relay.Constant][147], meta[relay.Constant][148], meta[relay.Constant][149], meta[relay.Constant][150]);\n          %128 = %127.0;\n          %129 = nn.relu(%128);\n          %130 = nn.conv2d(%129, meta[relay.Constant][151], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %131 = nn.batch_norm(%130, meta[relay.Constant][152], meta[relay.Constant][153], meta[relay.Constant][154], meta[relay.Constant][155]);\n          %132 = %131.0;\n          %133 = nn.relu(%132);\n          %134 = nn.conv2d(%133, meta[relay.Constant][156], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %135 = nn.batch_norm(%134, meta[relay.Constant][157], meta[relay.Constant][158], meta[relay.Constant][159], meta[relay.Constant][160]);\n          %136 = %135.0;\n          %137 = nn.relu(%136);\n          %138 = nn.conv2d(%137, meta[relay.Constant][161], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %139 = add(%138, %126);\n          %140 = nn.batch_norm(%139, meta[relay.Constant][162], meta[relay.Constant][163], meta[relay.Constant][164], meta[relay.Constant][165]);\n          %141 = %140.0;\n          %142 = nn.relu(%141);\n          %143 = nn.conv2d(%142, meta[relay.Constant][166], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %144 = nn.batch_norm(%143, meta[relay.Constant][167], meta[relay.Constant][168], meta[relay.Constant][169], meta[relay.Constant][170]);\n          %145 = %144.0;\n          %146 = nn.relu(%145);\n          %147 = nn.conv2d(%146, meta[relay.Constant][171], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %148 = nn.batch_norm(%147, meta[relay.Constant][172], meta[relay.Constant][173], meta[relay.Constant][174], meta[relay.Constant][175]);\n          %149 = %148.0;\n          %150 = nn.relu(%149);\n          %151 = nn.conv2d(%150, meta[relay.Constant][176], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %152 = add(%151, %139);\n          %153 = nn.batch_norm(%152, meta[relay.Constant][177], meta[relay.Constant][178], meta[relay.Constant][179], meta[relay.Constant][180]);\n          %154 = %153.0;\n          %155 = nn.relu(%154);\n          %156 = nn.conv2d(%155, meta[relay.Constant][181], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %157 = nn.batch_norm(%156, meta[relay.Constant][182], meta[relay.Constant][183], meta[relay.Constant][184], meta[relay.Constant][185]);\n          %158 = %157.0;\n          %159 = nn.relu(%158);\n          %160 = nn.conv2d(%159, meta[relay.Constant][186], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %161 = nn.batch_norm(%160, meta[relay.Constant][187], meta[relay.Constant][188], meta[relay.Constant][189], meta[relay.Constant][190]);\n          %162 = %161.0;\n          %163 = nn.relu(%162);\n          %164 = nn.conv2d(%163, meta[relay.Constant][191], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %165 = add(%164, %152);\n          %166 = nn.batch_norm(%165, meta[relay.Constant][192], meta[relay.Constant][193], meta[relay.Constant][194], meta[relay.Constant][195]);\n          %167 = %166.0;\n          %168 = nn.relu(%167);\n          %169 = nn.conv2d(%168, meta[relay.Constant][196], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %170 = nn.batch_norm(%169, meta[relay.Constant][197], meta[relay.Constant][198], meta[relay.Constant][199], meta[relay.Constant][200]);\n          %171 = %170.0;\n          %172 = nn.relu(%171);\n          %173 = nn.conv2d(%172, meta[relay.Constant][201], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %174 = nn.batch_norm(%173, meta[relay.Constant][202], meta[relay.Constant][203], meta[relay.Constant][204], meta[relay.Constant][205]);\n          %175 = %174.0;\n          %176 = nn.relu(%175);\n          %177 = nn.conv2d(%176, meta[relay.Constant][206], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %178 = add(%177, %165);\n          %179 = nn.batch_norm(%178, meta[relay.Constant][207], meta[relay.Constant][208], meta[relay.Constant][209], meta[relay.Constant][210]);\n          %180 = %179.0;\n          %181 = nn.relu(%180);\n          %182 = nn.conv2d(%181, meta[relay.Constant][211], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %183 = nn.batch_norm(%182, meta[relay.Constant][212], meta[relay.Constant][213], meta[relay.Constant][214], meta[relay.Constant][215]);\n          %184 = %183.0;\n          %185 = nn.relu(%184);\n          %186 = nn.conv2d(%185, meta[relay.Constant][216], strides=[2, 2], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %187 = nn.batch_norm(%186, meta[relay.Constant][217], meta[relay.Constant][218], meta[relay.Constant][219], meta[relay.Constant][220]);\n          %188 = %187.0;\n          %189 = nn.relu(%188);\n          %190 = nn.conv2d(%189, meta[relay.Constant][221], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %191 = nn.conv2d(%181, meta[relay.Constant][222], strides=[2, 2], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %192 = add(%190, %191);\n          %193 = nn.batch_norm(%192, meta[relay.Constant][223], meta[relay.Constant][224], meta[relay.Constant][225], meta[relay.Constant][226]);\n          %194 = %193.0;\n          %195 = nn.relu(%194);\n          %196 = nn.conv2d(%195, meta[relay.Constant][227], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %197 = nn.batch_norm(%196, meta[relay.Constant][228], meta[relay.Constant][229], meta[relay.Constant][230], meta[relay.Constant][231]);\n          %198 = %197.0;\n          %199 = nn.relu(%198);\n          %200 = nn.conv2d(%199, meta[relay.Constant][232], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %201 = nn.batch_norm(%200, meta[relay.Constant][233], meta[relay.Constant][234], meta[relay.Constant][235], meta[relay.Constant][236]);\n          %202 = %201.0;\n          %203 = nn.relu(%202);\n          %204 = nn.conv2d(%203, meta[relay.Constant][237], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %205 = add(%204, %192);\n          %206 = nn.batch_norm(%205, meta[relay.Constant][238], meta[relay.Constant][239], meta[relay.Constant][240], meta[relay.Constant][241]);\n          %207 = %206.0;\n          %208 = nn.relu(%207);\n          %209 = nn.conv2d(%208, meta[relay.Constant][242], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %210 = nn.batch_norm(%209, meta[relay.Constant][243], meta[relay.Constant][244], meta[relay.Constant][245], meta[relay.Constant][246]);\n          %211 = %210.0;\n          %212 = nn.relu(%211);\n          %213 = nn.conv2d(%212, meta[relay.Constant][247], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %214 = nn.batch_norm(%213, meta[relay.Constant][248], meta[relay.Constant][249], meta[relay.Constant][250], meta[relay.Constant][251]);\n          %215 = %214.0;\n          %216 = nn.relu(%215);\n          %217 = nn.conv2d(%216, meta[relay.Constant][252], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %218 = add(%217, %205);\n          %219 = nn.batch_norm(%218, meta[relay.Constant][253], meta[relay.Constant][254], meta[relay.Constant][255], meta[relay.Constant][256]);\n          %220 = %219.0;\n          %221 = nn.relu(%220);\n          %222 = nn.global_avg_pool2d(%221);\n          %223 = reshape(%222, newshape=[0, -1]);\n          %224 = nn.dense(%223, meta[relay.Constant][257], units=1000);\n          add(%224, meta[relay.Constant][258])\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"resnet50\",\n        \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n        \"input_dtypes\": {\"data\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef resnet50_16():\n    metatable = {\"relay.Constant\": resnet50_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(1, 3, 224, 224), float16]) -> Tensor[(1, 1000), float16] {\n          %0 = nn.batch_norm(%data, meta[relay.Constant][0], meta[relay.Constant][1], meta[relay.Constant][2], meta[relay.Constant][3]);\n          %1 = %0.0;\n          %2 = nn.conv2d(%1, meta[relay.Constant][4], strides=[2, 2], padding=[3, 3, 3, 3], channels=64, kernel_size=[7, 7]);\n          %3 = nn.batch_norm(%2, meta[relay.Constant][5], meta[relay.Constant][6], meta[relay.Constant][7], meta[relay.Constant][8]);\n          %4 = %3.0;\n          %5 = nn.relu(%4);\n          %6 = nn.max_pool2d(%5, pool_size=[3, 3], strides=[2, 2], padding=[1, 1, 1, 1]);\n          %7 = nn.batch_norm(%6, meta[relay.Constant][9], meta[relay.Constant][10], meta[relay.Constant][11], meta[relay.Constant][12]);\n          %8 = %7.0;\n          %9 = nn.relu(%8);\n          %10 = nn.conv2d(%9, meta[relay.Constant][13], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %11 = nn.batch_norm(%10, meta[relay.Constant][14], meta[relay.Constant][15], meta[relay.Constant][16], meta[relay.Constant][17]);\n          %12 = %11.0;\n          %13 = nn.relu(%12);\n          %14 = nn.conv2d(%13, meta[relay.Constant][18], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %15 = nn.batch_norm(%14, meta[relay.Constant][19], meta[relay.Constant][20], meta[relay.Constant][21], meta[relay.Constant][22]);\n          %16 = %15.0;\n          %17 = nn.relu(%16);\n          %18 = nn.conv2d(%17, meta[relay.Constant][23], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %19 = nn.conv2d(%9, meta[relay.Constant][24], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %20 = add(%18, %19);\n          %21 = nn.batch_norm(%20, meta[relay.Constant][25], meta[relay.Constant][26], meta[relay.Constant][27], meta[relay.Constant][28]);\n          %22 = %21.0;\n          %23 = nn.relu(%22);\n          %24 = nn.conv2d(%23, meta[relay.Constant][29], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %25 = nn.batch_norm(%24, meta[relay.Constant][30], meta[relay.Constant][31], meta[relay.Constant][32], meta[relay.Constant][33]);\n          %26 = %25.0;\n          %27 = nn.relu(%26);\n          %28 = nn.conv2d(%27, meta[relay.Constant][34], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %29 = nn.batch_norm(%28, meta[relay.Constant][35], meta[relay.Constant][36], meta[relay.Constant][37], meta[relay.Constant][38]);\n          %30 = %29.0;\n          %31 = nn.relu(%30);\n          %32 = nn.conv2d(%31, meta[relay.Constant][39], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %33 = add(%32, %20);\n          %34 = nn.batch_norm(%33, meta[relay.Constant][40], meta[relay.Constant][41], meta[relay.Constant][42], meta[relay.Constant][43]);\n          %35 = %34.0;\n          %36 = nn.relu(%35);\n          %37 = nn.conv2d(%36, meta[relay.Constant][44], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %38 = nn.batch_norm(%37, meta[relay.Constant][45], meta[relay.Constant][46], meta[relay.Constant][47], meta[relay.Constant][48]);\n          %39 = %38.0;\n          %40 = nn.relu(%39);\n          %41 = nn.conv2d(%40, meta[relay.Constant][49], padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n          %42 = nn.batch_norm(%41, meta[relay.Constant][50], meta[relay.Constant][51], meta[relay.Constant][52], meta[relay.Constant][53]);\n          %43 = %42.0;\n          %44 = nn.relu(%43);\n          %45 = nn.conv2d(%44, meta[relay.Constant][54], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %46 = add(%45, %33);\n          %47 = nn.batch_norm(%46, meta[relay.Constant][55], meta[relay.Constant][56], meta[relay.Constant][57], meta[relay.Constant][58]);\n          %48 = %47.0;\n          %49 = nn.relu(%48);\n          %50 = nn.conv2d(%49, meta[relay.Constant][59], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %51 = nn.batch_norm(%50, meta[relay.Constant][60], meta[relay.Constant][61], meta[relay.Constant][62], meta[relay.Constant][63]);\n          %52 = %51.0;\n          %53 = nn.relu(%52);\n          %54 = nn.conv2d(%53, meta[relay.Constant][64], strides=[2, 2], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %55 = nn.batch_norm(%54, meta[relay.Constant][65], meta[relay.Constant][66], meta[relay.Constant][67], meta[relay.Constant][68]);\n          %56 = %55.0;\n          %57 = nn.relu(%56);\n          %58 = nn.conv2d(%57, meta[relay.Constant][69], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %59 = nn.conv2d(%49, meta[relay.Constant][70], strides=[2, 2], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %60 = add(%58, %59);\n          %61 = nn.batch_norm(%60, meta[relay.Constant][71], meta[relay.Constant][72], meta[relay.Constant][73], meta[relay.Constant][74]);\n          %62 = %61.0;\n          %63 = nn.relu(%62);\n          %64 = nn.conv2d(%63, meta[relay.Constant][75], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %65 = nn.batch_norm(%64, meta[relay.Constant][76], meta[relay.Constant][77], meta[relay.Constant][78], meta[relay.Constant][79]);\n          %66 = %65.0;\n          %67 = nn.relu(%66);\n          %68 = nn.conv2d(%67, meta[relay.Constant][80], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %69 = nn.batch_norm(%68, meta[relay.Constant][81], meta[relay.Constant][82], meta[relay.Constant][83], meta[relay.Constant][84]);\n          %70 = %69.0;\n          %71 = nn.relu(%70);\n          %72 = nn.conv2d(%71, meta[relay.Constant][85], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %73 = add(%72, %60);\n          %74 = nn.batch_norm(%73, meta[relay.Constant][86], meta[relay.Constant][87], meta[relay.Constant][88], meta[relay.Constant][89]);\n          %75 = %74.0;\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][90], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %78 = nn.batch_norm(%77, meta[relay.Constant][91], meta[relay.Constant][92], meta[relay.Constant][93], meta[relay.Constant][94]);\n          %79 = %78.0;\n          %80 = nn.relu(%79);\n          %81 = nn.conv2d(%80, meta[relay.Constant][95], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %82 = nn.batch_norm(%81, meta[relay.Constant][96], meta[relay.Constant][97], meta[relay.Constant][98], meta[relay.Constant][99]);\n          %83 = %82.0;\n          %84 = nn.relu(%83);\n          %85 = nn.conv2d(%84, meta[relay.Constant][100], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %86 = add(%85, %73);\n          %87 = nn.batch_norm(%86, meta[relay.Constant][101], meta[relay.Constant][102], meta[relay.Constant][103], meta[relay.Constant][104]);\n          %88 = %87.0;\n          %89 = nn.relu(%88);\n          %90 = nn.conv2d(%89, meta[relay.Constant][105], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %91 = nn.batch_norm(%90, meta[relay.Constant][106], meta[relay.Constant][107], meta[relay.Constant][108], meta[relay.Constant][109]);\n          %92 = %91.0;\n          %93 = nn.relu(%92);\n          %94 = nn.conv2d(%93, meta[relay.Constant][110], padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3]);\n          %95 = nn.batch_norm(%94, meta[relay.Constant][111], meta[relay.Constant][112], meta[relay.Constant][113], meta[relay.Constant][114]);\n          %96 = %95.0;\n          %97 = nn.relu(%96);\n          %98 = nn.conv2d(%97, meta[relay.Constant][115], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %99 = add(%98, %86);\n          %100 = nn.batch_norm(%99, meta[relay.Constant][116], meta[relay.Constant][117], meta[relay.Constant][118], meta[relay.Constant][119]);\n          %101 = %100.0;\n          %102 = nn.relu(%101);\n          %103 = nn.conv2d(%102, meta[relay.Constant][120], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %104 = nn.batch_norm(%103, meta[relay.Constant][121], meta[relay.Constant][122], meta[relay.Constant][123], meta[relay.Constant][124]);\n          %105 = %104.0;\n          %106 = nn.relu(%105);\n          %107 = nn.conv2d(%106, meta[relay.Constant][125], strides=[2, 2], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %108 = nn.batch_norm(%107, meta[relay.Constant][126], meta[relay.Constant][127], meta[relay.Constant][128], meta[relay.Constant][129]);\n          %109 = %108.0;\n          %110 = nn.relu(%109);\n          %111 = nn.conv2d(%110, meta[relay.Constant][130], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %112 = nn.conv2d(%102, meta[relay.Constant][131], strides=[2, 2], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %113 = add(%111, %112);\n          %114 = nn.batch_norm(%113, meta[relay.Constant][132], meta[relay.Constant][133], meta[relay.Constant][134], meta[relay.Constant][135]);\n          %115 = %114.0;\n          %116 = nn.relu(%115);\n          %117 = nn.conv2d(%116, meta[relay.Constant][136], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %118 = nn.batch_norm(%117, meta[relay.Constant][137], meta[relay.Constant][138], meta[relay.Constant][139], meta[relay.Constant][140]);\n          %119 = %118.0;\n          %120 = nn.relu(%119);\n          %121 = nn.conv2d(%120, meta[relay.Constant][141], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %122 = nn.batch_norm(%121, meta[relay.Constant][142], meta[relay.Constant][143], meta[relay.Constant][144], meta[relay.Constant][145]);\n          %123 = %122.0;\n          %124 = nn.relu(%123);\n          %125 = nn.conv2d(%124, meta[relay.Constant][146], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %126 = add(%125, %113);\n          %127 = nn.batch_norm(%126, meta[relay.Constant][147], meta[relay.Constant][148], meta[relay.Constant][149], meta[relay.Constant][150]);\n          %128 = %127.0;\n          %129 = nn.relu(%128);\n          %130 = nn.conv2d(%129, meta[relay.Constant][151], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %131 = nn.batch_norm(%130, meta[relay.Constant][152], meta[relay.Constant][153], meta[relay.Constant][154], meta[relay.Constant][155]);\n          %132 = %131.0;\n          %133 = nn.relu(%132);\n          %134 = nn.conv2d(%133, meta[relay.Constant][156], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %135 = nn.batch_norm(%134, meta[relay.Constant][157], meta[relay.Constant][158], meta[relay.Constant][159], meta[relay.Constant][160]);\n          %136 = %135.0;\n          %137 = nn.relu(%136);\n          %138 = nn.conv2d(%137, meta[relay.Constant][161], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %139 = add(%138, %126);\n          %140 = nn.batch_norm(%139, meta[relay.Constant][162], meta[relay.Constant][163], meta[relay.Constant][164], meta[relay.Constant][165]);\n          %141 = %140.0;\n          %142 = nn.relu(%141);\n          %143 = nn.conv2d(%142, meta[relay.Constant][166], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %144 = nn.batch_norm(%143, meta[relay.Constant][167], meta[relay.Constant][168], meta[relay.Constant][169], meta[relay.Constant][170]);\n          %145 = %144.0;\n          %146 = nn.relu(%145);\n          %147 = nn.conv2d(%146, meta[relay.Constant][171], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %148 = nn.batch_norm(%147, meta[relay.Constant][172], meta[relay.Constant][173], meta[relay.Constant][174], meta[relay.Constant][175]);\n          %149 = %148.0;\n          %150 = nn.relu(%149);\n          %151 = nn.conv2d(%150, meta[relay.Constant][176], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %152 = add(%151, %139);\n          %153 = nn.batch_norm(%152, meta[relay.Constant][177], meta[relay.Constant][178], meta[relay.Constant][179], meta[relay.Constant][180]);\n          %154 = %153.0;\n          %155 = nn.relu(%154);\n          %156 = nn.conv2d(%155, meta[relay.Constant][181], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %157 = nn.batch_norm(%156, meta[relay.Constant][182], meta[relay.Constant][183], meta[relay.Constant][184], meta[relay.Constant][185]);\n          %158 = %157.0;\n          %159 = nn.relu(%158);\n          %160 = nn.conv2d(%159, meta[relay.Constant][186], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %161 = nn.batch_norm(%160, meta[relay.Constant][187], meta[relay.Constant][188], meta[relay.Constant][189], meta[relay.Constant][190]);\n          %162 = %161.0;\n          %163 = nn.relu(%162);\n          %164 = nn.conv2d(%163, meta[relay.Constant][191], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %165 = add(%164, %152);\n          %166 = nn.batch_norm(%165, meta[relay.Constant][192], meta[relay.Constant][193], meta[relay.Constant][194], meta[relay.Constant][195]);\n          %167 = %166.0;\n          %168 = nn.relu(%167);\n          %169 = nn.conv2d(%168, meta[relay.Constant][196], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %170 = nn.batch_norm(%169, meta[relay.Constant][197], meta[relay.Constant][198], meta[relay.Constant][199], meta[relay.Constant][200]);\n          %171 = %170.0;\n          %172 = nn.relu(%171);\n          %173 = nn.conv2d(%172, meta[relay.Constant][201], padding=[1, 1, 1, 1], channels=256, kernel_size=[3, 3]);\n          %174 = nn.batch_norm(%173, meta[relay.Constant][202], meta[relay.Constant][203], meta[relay.Constant][204], meta[relay.Constant][205]);\n          %175 = %174.0;\n          %176 = nn.relu(%175);\n          %177 = nn.conv2d(%176, meta[relay.Constant][206], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %178 = add(%177, %165);\n          %179 = nn.batch_norm(%178, meta[relay.Constant][207], meta[relay.Constant][208], meta[relay.Constant][209], meta[relay.Constant][210]);\n          %180 = %179.0;\n          %181 = nn.relu(%180);\n          %182 = nn.conv2d(%181, meta[relay.Constant][211], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %183 = nn.batch_norm(%182, meta[relay.Constant][212], meta[relay.Constant][213], meta[relay.Constant][214], meta[relay.Constant][215]);\n          %184 = %183.0;\n          %185 = nn.relu(%184);\n          %186 = nn.conv2d(%185, meta[relay.Constant][216], strides=[2, 2], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %187 = nn.batch_norm(%186, meta[relay.Constant][217], meta[relay.Constant][218], meta[relay.Constant][219], meta[relay.Constant][220]);\n          %188 = %187.0;\n          %189 = nn.relu(%188);\n          %190 = nn.conv2d(%189, meta[relay.Constant][221], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %191 = nn.conv2d(%181, meta[relay.Constant][222], strides=[2, 2], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %192 = add(%190, %191);\n          %193 = nn.batch_norm(%192, meta[relay.Constant][223], meta[relay.Constant][224], meta[relay.Constant][225], meta[relay.Constant][226]);\n          %194 = %193.0;\n          %195 = nn.relu(%194);\n          %196 = nn.conv2d(%195, meta[relay.Constant][227], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %197 = nn.batch_norm(%196, meta[relay.Constant][228], meta[relay.Constant][229], meta[relay.Constant][230], meta[relay.Constant][231]);\n          %198 = %197.0;\n          %199 = nn.relu(%198);\n          %200 = nn.conv2d(%199, meta[relay.Constant][232], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %201 = nn.batch_norm(%200, meta[relay.Constant][233], meta[relay.Constant][234], meta[relay.Constant][235], meta[relay.Constant][236]);\n          %202 = %201.0;\n          %203 = nn.relu(%202);\n          %204 = nn.conv2d(%203, meta[relay.Constant][237], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %205 = add(%204, %192);\n          %206 = nn.batch_norm(%205, meta[relay.Constant][238], meta[relay.Constant][239], meta[relay.Constant][240], meta[relay.Constant][241]);\n          %207 = %206.0;\n          %208 = nn.relu(%207);\n          %209 = nn.conv2d(%208, meta[relay.Constant][242], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %210 = nn.batch_norm(%209, meta[relay.Constant][243], meta[relay.Constant][244], meta[relay.Constant][245], meta[relay.Constant][246]);\n          %211 = %210.0;\n          %212 = nn.relu(%211);\n          %213 = nn.conv2d(%212, meta[relay.Constant][247], padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3]);\n          %214 = nn.batch_norm(%213, meta[relay.Constant][248], meta[relay.Constant][249], meta[relay.Constant][250], meta[relay.Constant][251]);\n          %215 = %214.0;\n          %216 = nn.relu(%215);\n          %217 = nn.conv2d(%216, meta[relay.Constant][252], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %218 = add(%217, %205);\n          %219 = nn.batch_norm(%218, meta[relay.Constant][253], meta[relay.Constant][254], meta[relay.Constant][255], meta[relay.Constant][256]);\n          %220 = %219.0;\n          %221 = nn.relu(%220);\n          %222 = nn.global_avg_pool2d(%221);\n          %223 = reshape(%222, newshape=[0, -1]);\n          %224 = nn.dense(%223, meta[relay.Constant][257], units=1000);\n          add(%224, meta[relay.Constant][258])\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"resnet50_16\",\n        \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n        \"input_dtypes\": {\"data\": \"float16\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef mobilenet_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (32, 3, 3, 3),  # 0\n            (32,),  # 1\n            (32,),  # 2\n            (32,),  # 3\n            (32,),  # 4\n            (32, 32, 1, 1),  # 5\n            (32,),  # 6\n            (32,),  # 7\n            (32,),  # 8\n            (32,),  # 9\n            (32, 1, 3, 3),  # 10\n            (32,),  # 11\n            (32,),  # 12\n            (32,),  # 13\n            (32,),  # 14\n            (16, 32, 1, 1),  # 15\n            (16,),  # 16\n            (16,),  # 17\n            (16,),  # 18\n            (16,),  # 19\n            (96, 16, 1, 1),  # 20\n            (96,),  # 21\n            (96,),  # 22\n            (96,),  # 23\n            (96,),  # 24\n            (96, 1, 3, 3),  # 25\n            (96,),  # 26\n            (96,),  # 27\n            (96,),  # 28\n            (96,),  # 29\n            (24, 96, 1, 1),  # 30\n            (24,),  # 31\n            (24,),  # 32\n            (24,),  # 33\n            (24,),  # 34\n            (144, 24, 1, 1),  # 35\n            (144,),  # 36\n            (144,),  # 37\n            (144,),  # 38\n            (144,),  # 39\n            (144, 1, 3, 3),  # 40\n            (144,),  # 41\n            (144,),  # 42\n            (144,),  # 43\n            (144,),  # 44\n            (24, 144, 1, 1),  # 45\n            (24,),  # 46\n            (24,),  # 47\n            (24,),  # 48\n            (24,),  # 49\n            (144, 24, 1, 1),  # 50\n            (144,),  # 51\n            (144,),  # 52\n            (144,),  # 53\n            (144,),  # 54\n            (144, 1, 3, 3),  # 55\n            (144,),  # 56\n            (144,),  # 57\n            (144,),  # 58\n            (144,),  # 59\n            (32, 144, 1, 1),  # 60\n            (32,),  # 61\n            (32,),  # 62\n            (32,),  # 63\n            (32,),  # 64\n            (192, 32, 1, 1),  # 65\n            (192,),  # 66\n            (192,),  # 67\n            (192,),  # 68\n            (192,),  # 69\n            (192, 1, 3, 3),  # 70\n            (192,),  # 71\n            (192,),  # 72\n            (192,),  # 73\n            (192,),  # 74\n            (32, 192, 1, 1),  # 75\n            (32,),  # 76\n            (32,),  # 77\n            (32,),  # 78\n            (32,),  # 79\n            (192, 32, 1, 1),  # 80\n            (192,),  # 81\n            (192,),  # 82\n            (192,),  # 83\n            (192,),  # 84\n            (192, 1, 3, 3),  # 85\n            (192,),  # 86\n            (192,),  # 87\n            (192,),  # 88\n            (192,),  # 89\n            (32, 192, 1, 1),  # 90\n            (32,),  # 91\n            (32,),  # 92\n            (32,),  # 93\n            (32,),  # 94\n            (192, 32, 1, 1),  # 95\n            (192,),  # 96\n            (192,),  # 97\n            (192,),  # 98\n            (192,),  # 99\n            (192, 1, 3, 3),  # 100\n            (192,),  # 101\n            (192,),  # 102\n            (192,),  # 103\n            (192,),  # 104\n            (64, 192, 1, 1),  # 105\n            (64,),  # 106\n            (64,),  # 107\n            (64,),  # 108\n            (64,),  # 109\n            (384, 64, 1, 1),  # 110\n            (384,),  # 111\n            (384,),  # 112\n            (384,),  # 113\n            (384,),  # 114\n            (384, 1, 3, 3),  # 115\n            (384,),  # 116\n            (384,),  # 117\n            (384,),  # 118\n            (384,),  # 119\n            (64, 384, 1, 1),  # 120\n            (64,),  # 121\n            (64,),  # 122\n            (64,),  # 123\n            (64,),  # 124\n            (384, 64, 1, 1),  # 125\n            (384,),  # 126\n            (384,),  # 127\n            (384,),  # 128\n            (384,),  # 129\n            (384, 1, 3, 3),  # 130\n            (384,),  # 131\n            (384,),  # 132\n            (384,),  # 133\n            (384,),  # 134\n            (64, 384, 1, 1),  # 135\n            (64,),  # 136\n            (64,),  # 137\n            (64,),  # 138\n            (64,),  # 139\n            (384, 64, 1, 1),  # 140\n            (384,),  # 141\n            (384,),  # 142\n            (384,),  # 143\n            (384,),  # 144\n            (384, 1, 3, 3),  # 145\n            (384,),  # 146\n            (384,),  # 147\n            (384,),  # 148\n            (384,),  # 149\n            (64, 384, 1, 1),  # 150\n            (64,),  # 151\n            (64,),  # 152\n            (64,),  # 153\n            (64,),  # 154\n            (384, 64, 1, 1),  # 155\n            (384,),  # 156\n            (384,),  # 157\n            (384,),  # 158\n            (384,),  # 159\n            (384, 1, 3, 3),  # 160\n            (384,),  # 161\n            (384,),  # 162\n            (384,),  # 163\n            (384,),  # 164\n            (96, 384, 1, 1),  # 165\n            (96,),  # 166\n            (96,),  # 167\n            (96,),  # 168\n            (96,),  # 169\n            (576, 96, 1, 1),  # 170\n            (576,),  # 171\n            (576,),  # 172\n            (576,),  # 173\n            (576,),  # 174\n            (576, 1, 3, 3),  # 175\n            (576,),  # 176\n            (576,),  # 177\n            (576,),  # 178\n            (576,),  # 179\n            (96, 576, 1, 1),  # 180\n            (96,),  # 181\n            (96,),  # 182\n            (96,),  # 183\n            (96,),  # 184\n            (576, 96, 1, 1),  # 185\n            (576,),  # 186\n            (576,),  # 187\n            (576,),  # 188\n            (576,),  # 189\n            (576, 1, 3, 3),  # 190\n            (576,),  # 191\n            (576,),  # 192\n            (576,),  # 193\n            (576,),  # 194\n            (96, 576, 1, 1),  # 195\n            (96,),  # 196\n            (96,),  # 197\n            (96,),  # 198\n            (96,),  # 199\n            (576, 96, 1, 1),  # 200\n            (576,),  # 201\n            (576,),  # 202\n            (576,),  # 203\n            (576,),  # 204\n            (576, 1, 3, 3),  # 205\n            (576,),  # 206\n            (576,),  # 207\n            (576,),  # 208\n            (576,),  # 209\n            (160, 576, 1, 1),  # 210\n            (160,),  # 211\n            (160,),  # 212\n            (160,),  # 213\n            (160,),  # 214\n            (960, 160, 1, 1),  # 215\n            (960,),  # 216\n            (960,),  # 217\n            (960,),  # 218\n            (960,),  # 219\n            (960, 1, 3, 3),  # 220\n            (960,),  # 221\n            (960,),  # 222\n            (960,),  # 223\n            (960,),  # 224\n            (160, 960, 1, 1),  # 225\n            (160,),  # 226\n            (160,),  # 227\n            (160,),  # 228\n            (160,),  # 229\n            (960, 160, 1, 1),  # 230\n            (960,),  # 231\n            (960,),  # 232\n            (960,),  # 233\n            (960,),  # 234\n            (960, 1, 3, 3),  # 235\n            (960,),  # 236\n            (960,),  # 237\n            (960,),  # 238\n            (960,),  # 239\n            (160, 960, 1, 1),  # 240\n            (160,),  # 241\n            (160,),  # 242\n            (160,),  # 243\n            (160,),  # 244\n            (960, 160, 1, 1),  # 245\n            (960,),  # 246\n            (960,),  # 247\n            (960,),  # 248\n            (960,),  # 249\n            (960, 1, 3, 3),  # 250\n            (960,),  # 251\n            (960,),  # 252\n            (960,),  # 253\n            (960,),  # 254\n            (320, 960, 1, 1),  # 255\n            (320,),  # 256\n            (320,),  # 257\n            (320,),  # 258\n            (320,),  # 259\n            (1280, 320, 1, 1),  # 260\n            (1280,),  # 261\n            (1280,),  # 262\n            (1280,),  # 263\n            (1280,),  # 264\n            (1000, 1280, 1, 1),  # 265\n        ],\n    )\n\n\ndef mobilenet():\n    metatable = {\"relay.Constant\": mobilenet_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(1, 3, 224, 224), float32]) -> Tensor[(1, 1000), float32] {\n          %0 = nn.conv2d(%data, meta[relay.Constant][0], strides=[2, 2], padding=[1, 1, 1, 1], channels=32, kernel_size=[3, 3]);\n          %1 = nn.batch_norm(%0, meta[relay.Constant][1], meta[relay.Constant][2], meta[relay.Constant][3], meta[relay.Constant][4]);\n          %2 = %1.0;\n          %3 = nn.relu(%2);\n          %4 = nn.conv2d(%3, meta[relay.Constant][5], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %5 = nn.batch_norm(%4, meta[relay.Constant][6], meta[relay.Constant][7], meta[relay.Constant][8], meta[relay.Constant][9]);\n          %6 = %5.0;\n          %7 = nn.relu(%6);\n          %8 = nn.conv2d(%7, meta[relay.Constant][10], padding=[1, 1, 1, 1], groups=32, channels=32, kernel_size=[3, 3]);\n          %9 = nn.batch_norm(%8, meta[relay.Constant][11], meta[relay.Constant][12], meta[relay.Constant][13], meta[relay.Constant][14]);\n          %10 = %9.0;\n          %11 = nn.relu(%10);\n          %12 = nn.conv2d(%11, meta[relay.Constant][15], padding=[0, 0, 0, 0], channels=16, kernel_size=[1, 1]);\n          %13 = nn.batch_norm(%12, meta[relay.Constant][16], meta[relay.Constant][17], meta[relay.Constant][18], meta[relay.Constant][19]);\n          %14 = %13.0;\n          %15 = nn.conv2d(%14, meta[relay.Constant][20], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %16 = nn.batch_norm(%15, meta[relay.Constant][21], meta[relay.Constant][22], meta[relay.Constant][23], meta[relay.Constant][24]);\n          %17 = %16.0;\n          %18 = nn.relu(%17);\n          %19 = nn.conv2d(%18, meta[relay.Constant][25], strides=[2, 2], padding=[1, 1, 1, 1], groups=96, channels=96, kernel_size=[3, 3]);\n          %20 = nn.batch_norm(%19, meta[relay.Constant][26], meta[relay.Constant][27], meta[relay.Constant][28], meta[relay.Constant][29]);\n          %21 = %20.0;\n          %22 = nn.relu(%21);\n          %23 = nn.conv2d(%22, meta[relay.Constant][30], padding=[0, 0, 0, 0], channels=24, kernel_size=[1, 1]);\n          %24 = nn.batch_norm(%23, meta[relay.Constant][31], meta[relay.Constant][32], meta[relay.Constant][33], meta[relay.Constant][34]);\n          %25 = %24.0;\n          %26 = nn.conv2d(%25, meta[relay.Constant][35], padding=[0, 0, 0, 0], channels=144, kernel_size=[1, 1]);\n          %27 = nn.batch_norm(%26, meta[relay.Constant][36], meta[relay.Constant][37], meta[relay.Constant][38], meta[relay.Constant][39]);\n          %28 = %27.0;\n          %29 = nn.relu(%28);\n          %30 = nn.conv2d(%29, meta[relay.Constant][40], padding=[1, 1, 1, 1], groups=144, channels=144, kernel_size=[3, 3]);\n          %31 = nn.batch_norm(%30, meta[relay.Constant][41], meta[relay.Constant][42], meta[relay.Constant][43], meta[relay.Constant][44]);\n          %32 = %31.0;\n          %33 = nn.relu(%32);\n          %34 = nn.conv2d(%33, meta[relay.Constant][45], padding=[0, 0, 0, 0], channels=24, kernel_size=[1, 1]);\n          %35 = nn.batch_norm(%34, meta[relay.Constant][46], meta[relay.Constant][47], meta[relay.Constant][48], meta[relay.Constant][49]);\n          %36 = %35.0;\n          %37 = add(%36, %25);\n          %38 = nn.conv2d(%37, meta[relay.Constant][50], padding=[0, 0, 0, 0], channels=144, kernel_size=[1, 1]);\n          %39 = nn.batch_norm(%38, meta[relay.Constant][51], meta[relay.Constant][52], meta[relay.Constant][53], meta[relay.Constant][54]);\n          %40 = %39.0;\n          %41 = nn.relu(%40);\n          %42 = nn.conv2d(%41, meta[relay.Constant][55], strides=[2, 2], padding=[1, 1, 1, 1], groups=144, channels=144, kernel_size=[3, 3]);\n          %43 = nn.batch_norm(%42, meta[relay.Constant][56], meta[relay.Constant][57], meta[relay.Constant][58], meta[relay.Constant][59]);\n          %44 = %43.0;\n          %45 = nn.relu(%44);\n          %46 = nn.conv2d(%45, meta[relay.Constant][60], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %47 = nn.batch_norm(%46, meta[relay.Constant][61], meta[relay.Constant][62], meta[relay.Constant][63], meta[relay.Constant][64]);\n          %48 = %47.0;\n          %49 = nn.conv2d(%48, meta[relay.Constant][65], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %50 = nn.batch_norm(%49, meta[relay.Constant][66], meta[relay.Constant][67], meta[relay.Constant][68], meta[relay.Constant][69]);\n          %51 = %50.0;\n          %52 = nn.relu(%51);\n          %53 = nn.conv2d(%52, meta[relay.Constant][70], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %54 = nn.batch_norm(%53, meta[relay.Constant][71], meta[relay.Constant][72], meta[relay.Constant][73], meta[relay.Constant][74]);\n          %55 = %54.0;\n          %56 = nn.relu(%55);\n          %57 = nn.conv2d(%56, meta[relay.Constant][75], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %58 = nn.batch_norm(%57, meta[relay.Constant][76], meta[relay.Constant][77], meta[relay.Constant][78], meta[relay.Constant][79]);\n          %59 = %58.0;\n          %60 = add(%59, %48);\n          %61 = nn.conv2d(%60, meta[relay.Constant][80], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %62 = nn.batch_norm(%61, meta[relay.Constant][81], meta[relay.Constant][82], meta[relay.Constant][83], meta[relay.Constant][84]);\n          %63 = %62.0;\n          %64 = nn.relu(%63);\n          %65 = nn.conv2d(%64, meta[relay.Constant][85], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %66 = nn.batch_norm(%65, meta[relay.Constant][86], meta[relay.Constant][87], meta[relay.Constant][88], meta[relay.Constant][89]);\n          %67 = %66.0;\n          %68 = nn.relu(%67);\n          %69 = nn.conv2d(%68, meta[relay.Constant][90], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %70 = nn.batch_norm(%69, meta[relay.Constant][91], meta[relay.Constant][92], meta[relay.Constant][93], meta[relay.Constant][94]);\n          %71 = %70.0;\n          %72 = add(%71, %60);\n          %73 = nn.conv2d(%72, meta[relay.Constant][95], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %74 = nn.batch_norm(%73, meta[relay.Constant][96], meta[relay.Constant][97], meta[relay.Constant][98], meta[relay.Constant][99]);\n          %75 = %74.0;\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][100], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %78 = nn.batch_norm(%77, meta[relay.Constant][101], meta[relay.Constant][102], meta[relay.Constant][103], meta[relay.Constant][104]);\n          %79 = %78.0;\n          %80 = nn.relu(%79);\n          %81 = nn.conv2d(%80, meta[relay.Constant][105], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %82 = nn.batch_norm(%81, meta[relay.Constant][106], meta[relay.Constant][107], meta[relay.Constant][108], meta[relay.Constant][109]);\n          %83 = %82.0;\n          %84 = nn.conv2d(%83, meta[relay.Constant][110], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %85 = nn.batch_norm(%84, meta[relay.Constant][111], meta[relay.Constant][112], meta[relay.Constant][113], meta[relay.Constant][114]);\n          %86 = %85.0;\n          %87 = nn.relu(%86);\n          %88 = nn.conv2d(%87, meta[relay.Constant][115], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %89 = nn.batch_norm(%88, meta[relay.Constant][116], meta[relay.Constant][117], meta[relay.Constant][118], meta[relay.Constant][119]);\n          %90 = %89.0;\n          %91 = nn.relu(%90);\n          %92 = nn.conv2d(%91, meta[relay.Constant][120], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %93 = nn.batch_norm(%92, meta[relay.Constant][121], meta[relay.Constant][122], meta[relay.Constant][123], meta[relay.Constant][124]);\n          %94 = %93.0;\n          %95 = add(%94, %83);\n          %96 = nn.conv2d(%95, meta[relay.Constant][125], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %97 = nn.batch_norm(%96, meta[relay.Constant][126], meta[relay.Constant][127], meta[relay.Constant][128], meta[relay.Constant][129]);\n          %98 = %97.0;\n          %99 = nn.relu(%98);\n          %100 = nn.conv2d(%99, meta[relay.Constant][130], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %101 = nn.batch_norm(%100, meta[relay.Constant][131], meta[relay.Constant][132], meta[relay.Constant][133], meta[relay.Constant][134]);\n          %102 = %101.0;\n          %103 = nn.relu(%102);\n          %104 = nn.conv2d(%103, meta[relay.Constant][135], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %105 = nn.batch_norm(%104, meta[relay.Constant][136], meta[relay.Constant][137], meta[relay.Constant][138], meta[relay.Constant][139]);\n          %106 = %105.0;\n          %107 = add(%106, %95);\n          %108 = nn.conv2d(%107, meta[relay.Constant][140], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %109 = nn.batch_norm(%108, meta[relay.Constant][141], meta[relay.Constant][142], meta[relay.Constant][143], meta[relay.Constant][144]);\n          %110 = %109.0;\n          %111 = nn.relu(%110);\n          %112 = nn.conv2d(%111, meta[relay.Constant][145], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %113 = nn.batch_norm(%112, meta[relay.Constant][146], meta[relay.Constant][147], meta[relay.Constant][148], meta[relay.Constant][149]);\n          %114 = %113.0;\n          %115 = nn.relu(%114);\n          %116 = nn.conv2d(%115, meta[relay.Constant][150], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %117 = nn.batch_norm(%116, meta[relay.Constant][151], meta[relay.Constant][152], meta[relay.Constant][153], meta[relay.Constant][154]);\n          %118 = %117.0;\n          %119 = add(%118, %107);\n          %120 = nn.conv2d(%119, meta[relay.Constant][155], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %121 = nn.batch_norm(%120, meta[relay.Constant][156], meta[relay.Constant][157], meta[relay.Constant][158], meta[relay.Constant][159]);\n          %122 = %121.0;\n          %123 = nn.relu(%122);\n          %124 = nn.conv2d(%123, meta[relay.Constant][160], strides=[2, 2], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %125 = nn.batch_norm(%124, meta[relay.Constant][161], meta[relay.Constant][162], meta[relay.Constant][163], meta[relay.Constant][164]);\n          %126 = %125.0;\n          %127 = nn.relu(%126);\n          %128 = nn.conv2d(%127, meta[relay.Constant][165], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %129 = nn.batch_norm(%128, meta[relay.Constant][166], meta[relay.Constant][167], meta[relay.Constant][168], meta[relay.Constant][169]);\n          %130 = %129.0;\n          %131 = nn.conv2d(%130, meta[relay.Constant][170], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %132 = nn.batch_norm(%131, meta[relay.Constant][171], meta[relay.Constant][172], meta[relay.Constant][173], meta[relay.Constant][174]);\n          %133 = %132.0;\n          %134 = nn.relu(%133);\n          %135 = nn.conv2d(%134, meta[relay.Constant][175], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %136 = nn.batch_norm(%135, meta[relay.Constant][176], meta[relay.Constant][177], meta[relay.Constant][178], meta[relay.Constant][179]);\n          %137 = %136.0;\n          %138 = nn.relu(%137);\n          %139 = nn.conv2d(%138, meta[relay.Constant][180], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %140 = nn.batch_norm(%139, meta[relay.Constant][181], meta[relay.Constant][182], meta[relay.Constant][183], meta[relay.Constant][184]);\n          %141 = %140.0;\n          %142 = add(%141, %130);\n          %143 = nn.conv2d(%142, meta[relay.Constant][185], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %144 = nn.batch_norm(%143, meta[relay.Constant][186], meta[relay.Constant][187], meta[relay.Constant][188], meta[relay.Constant][189]);\n          %145 = %144.0;\n          %146 = nn.relu(%145);\n          %147 = nn.conv2d(%146, meta[relay.Constant][190], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %148 = nn.batch_norm(%147, meta[relay.Constant][191], meta[relay.Constant][192], meta[relay.Constant][193], meta[relay.Constant][194]);\n          %149 = %148.0;\n          %150 = nn.relu(%149);\n          %151 = nn.conv2d(%150, meta[relay.Constant][195], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %152 = nn.batch_norm(%151, meta[relay.Constant][196], meta[relay.Constant][197], meta[relay.Constant][198], meta[relay.Constant][199]);\n          %153 = %152.0;\n          %154 = add(%153, %142);\n          %155 = nn.conv2d(%154, meta[relay.Constant][200], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %156 = nn.batch_norm(%155, meta[relay.Constant][201], meta[relay.Constant][202], meta[relay.Constant][203], meta[relay.Constant][204]);\n          %157 = %156.0;\n          %158 = nn.relu(%157);\n          %159 = nn.conv2d(%158, meta[relay.Constant][205], strides=[2, 2], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %160 = nn.batch_norm(%159, meta[relay.Constant][206], meta[relay.Constant][207], meta[relay.Constant][208], meta[relay.Constant][209]);\n          %161 = %160.0;\n          %162 = nn.relu(%161);\n          %163 = nn.conv2d(%162, meta[relay.Constant][210], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %164 = nn.batch_norm(%163, meta[relay.Constant][211], meta[relay.Constant][212], meta[relay.Constant][213], meta[relay.Constant][214]);\n          %165 = %164.0;\n          %166 = nn.conv2d(%165, meta[relay.Constant][215], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %167 = nn.batch_norm(%166, meta[relay.Constant][216], meta[relay.Constant][217], meta[relay.Constant][218], meta[relay.Constant][219]);\n          %168 = %167.0;\n          %169 = nn.relu(%168);\n          %170 = nn.conv2d(%169, meta[relay.Constant][220], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %171 = nn.batch_norm(%170, meta[relay.Constant][221], meta[relay.Constant][222], meta[relay.Constant][223], meta[relay.Constant][224]);\n          %172 = %171.0;\n          %173 = nn.relu(%172);\n          %174 = nn.conv2d(%173, meta[relay.Constant][225], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %175 = nn.batch_norm(%174, meta[relay.Constant][226], meta[relay.Constant][227], meta[relay.Constant][228], meta[relay.Constant][229]);\n          %176 = %175.0;\n          %177 = add(%176, %165);\n          %178 = nn.conv2d(%177, meta[relay.Constant][230], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %179 = nn.batch_norm(%178, meta[relay.Constant][231], meta[relay.Constant][232], meta[relay.Constant][233], meta[relay.Constant][234]);\n          %180 = %179.0;\n          %181 = nn.relu(%180);\n          %182 = nn.conv2d(%181, meta[relay.Constant][235], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %183 = nn.batch_norm(%182, meta[relay.Constant][236], meta[relay.Constant][237], meta[relay.Constant][238], meta[relay.Constant][239]);\n          %184 = %183.0;\n          %185 = nn.relu(%184);\n          %186 = nn.conv2d(%185, meta[relay.Constant][240], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %187 = nn.batch_norm(%186, meta[relay.Constant][241], meta[relay.Constant][242], meta[relay.Constant][243], meta[relay.Constant][244]);\n          %188 = %187.0;\n          %189 = add(%188, %177);\n          %190 = nn.conv2d(%189, meta[relay.Constant][245], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %191 = nn.batch_norm(%190, meta[relay.Constant][246], meta[relay.Constant][247], meta[relay.Constant][248], meta[relay.Constant][249]);\n          %192 = %191.0;\n          %193 = nn.relu(%192);\n          %194 = nn.conv2d(%193, meta[relay.Constant][250], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %195 = nn.batch_norm(%194, meta[relay.Constant][251], meta[relay.Constant][252], meta[relay.Constant][253], meta[relay.Constant][254]);\n          %196 = %195.0;\n          %197 = nn.relu(%196);\n          %198 = nn.conv2d(%197, meta[relay.Constant][255], padding=[0, 0, 0, 0], channels=320, kernel_size=[1, 1]);\n          %199 = nn.batch_norm(%198, meta[relay.Constant][256], meta[relay.Constant][257], meta[relay.Constant][258], meta[relay.Constant][259]);\n          %200 = %199.0;\n          %201 = nn.conv2d(%200, meta[relay.Constant][260], padding=[0, 0, 0, 0], channels=1280, kernel_size=[1, 1]);\n          %202 = nn.batch_norm(%201, meta[relay.Constant][261], meta[relay.Constant][262], meta[relay.Constant][263], meta[relay.Constant][264]);\n          %203 = %202.0;\n          %204 = nn.relu(%203);\n          %205 = nn.global_avg_pool2d(%204);\n          %206 = nn.conv2d(%205, meta[relay.Constant][265], padding=[0, 0, 0, 0], channels=1000, kernel_size=[1, 1]);\n          reshape(%206, newshape=[0, -1])\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"mobilenet\",\n        \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n        \"input_dtypes\": {\"data\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef mobilenet_16():\n    metatable = {\"relay.Constant\": mobilenet_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(1, 3, 224, 224), float16]) -> Tensor[(1, 1000), float16] {\n          %0 = nn.conv2d(%data, meta[relay.Constant][0], strides=[2, 2], padding=[1, 1, 1, 1], channels=32, kernel_size=[3, 3]);\n          %1 = nn.batch_norm(%0, meta[relay.Constant][1], meta[relay.Constant][2], meta[relay.Constant][3], meta[relay.Constant][4]);\n          %2 = %1.0;\n          %3 = nn.relu(%2);\n          %4 = nn.conv2d(%3, meta[relay.Constant][5], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %5 = nn.batch_norm(%4, meta[relay.Constant][6], meta[relay.Constant][7], meta[relay.Constant][8], meta[relay.Constant][9]);\n          %6 = %5.0;\n          %7 = nn.relu(%6);\n          %8 = nn.conv2d(%7, meta[relay.Constant][10], padding=[1, 1, 1, 1], groups=32, channels=32, kernel_size=[3, 3]);\n          %9 = nn.batch_norm(%8, meta[relay.Constant][11], meta[relay.Constant][12], meta[relay.Constant][13], meta[relay.Constant][14]);\n          %10 = %9.0;\n          %11 = nn.relu(%10);\n          %12 = nn.conv2d(%11, meta[relay.Constant][15], padding=[0, 0, 0, 0], channels=16, kernel_size=[1, 1]);\n          %13 = nn.batch_norm(%12, meta[relay.Constant][16], meta[relay.Constant][17], meta[relay.Constant][18], meta[relay.Constant][19]);\n          %14 = %13.0;\n          %15 = nn.conv2d(%14, meta[relay.Constant][20], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %16 = nn.batch_norm(%15, meta[relay.Constant][21], meta[relay.Constant][22], meta[relay.Constant][23], meta[relay.Constant][24]);\n          %17 = %16.0;\n          %18 = nn.relu(%17);\n          %19 = nn.conv2d(%18, meta[relay.Constant][25], strides=[2, 2], padding=[1, 1, 1, 1], groups=96, channels=96, kernel_size=[3, 3]);\n          %20 = nn.batch_norm(%19, meta[relay.Constant][26], meta[relay.Constant][27], meta[relay.Constant][28], meta[relay.Constant][29]);\n          %21 = %20.0;\n          %22 = nn.relu(%21);\n          %23 = nn.conv2d(%22, meta[relay.Constant][30], padding=[0, 0, 0, 0], channels=24, kernel_size=[1, 1]);\n          %24 = nn.batch_norm(%23, meta[relay.Constant][31], meta[relay.Constant][32], meta[relay.Constant][33], meta[relay.Constant][34]);\n          %25 = %24.0;\n          %26 = nn.conv2d(%25, meta[relay.Constant][35], padding=[0, 0, 0, 0], channels=144, kernel_size=[1, 1]);\n          %27 = nn.batch_norm(%26, meta[relay.Constant][36], meta[relay.Constant][37], meta[relay.Constant][38], meta[relay.Constant][39]);\n          %28 = %27.0;\n          %29 = nn.relu(%28);\n          %30 = nn.conv2d(%29, meta[relay.Constant][40], padding=[1, 1, 1, 1], groups=144, channels=144, kernel_size=[3, 3]);\n          %31 = nn.batch_norm(%30, meta[relay.Constant][41], meta[relay.Constant][42], meta[relay.Constant][43], meta[relay.Constant][44]);\n          %32 = %31.0;\n          %33 = nn.relu(%32);\n          %34 = nn.conv2d(%33, meta[relay.Constant][45], padding=[0, 0, 0, 0], channels=24, kernel_size=[1, 1]);\n          %35 = nn.batch_norm(%34, meta[relay.Constant][46], meta[relay.Constant][47], meta[relay.Constant][48], meta[relay.Constant][49]);\n          %36 = %35.0;\n          %37 = add(%36, %25);\n          %38 = nn.conv2d(%37, meta[relay.Constant][50], padding=[0, 0, 0, 0], channels=144, kernel_size=[1, 1]);\n          %39 = nn.batch_norm(%38, meta[relay.Constant][51], meta[relay.Constant][52], meta[relay.Constant][53], meta[relay.Constant][54]);\n          %40 = %39.0;\n          %41 = nn.relu(%40);\n          %42 = nn.conv2d(%41, meta[relay.Constant][55], strides=[2, 2], padding=[1, 1, 1, 1], groups=144, channels=144, kernel_size=[3, 3]);\n          %43 = nn.batch_norm(%42, meta[relay.Constant][56], meta[relay.Constant][57], meta[relay.Constant][58], meta[relay.Constant][59]);\n          %44 = %43.0;\n          %45 = nn.relu(%44);\n          %46 = nn.conv2d(%45, meta[relay.Constant][60], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %47 = nn.batch_norm(%46, meta[relay.Constant][61], meta[relay.Constant][62], meta[relay.Constant][63], meta[relay.Constant][64]);\n          %48 = %47.0;\n          %49 = nn.conv2d(%48, meta[relay.Constant][65], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %50 = nn.batch_norm(%49, meta[relay.Constant][66], meta[relay.Constant][67], meta[relay.Constant][68], meta[relay.Constant][69]);\n          %51 = %50.0;\n          %52 = nn.relu(%51);\n          %53 = nn.conv2d(%52, meta[relay.Constant][70], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %54 = nn.batch_norm(%53, meta[relay.Constant][71], meta[relay.Constant][72], meta[relay.Constant][73], meta[relay.Constant][74]);\n          %55 = %54.0;\n          %56 = nn.relu(%55);\n          %57 = nn.conv2d(%56, meta[relay.Constant][75], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %58 = nn.batch_norm(%57, meta[relay.Constant][76], meta[relay.Constant][77], meta[relay.Constant][78], meta[relay.Constant][79]);\n          %59 = %58.0;\n          %60 = add(%59, %48);\n          %61 = nn.conv2d(%60, meta[relay.Constant][80], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %62 = nn.batch_norm(%61, meta[relay.Constant][81], meta[relay.Constant][82], meta[relay.Constant][83], meta[relay.Constant][84]);\n          %63 = %62.0;\n          %64 = nn.relu(%63);\n          %65 = nn.conv2d(%64, meta[relay.Constant][85], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %66 = nn.batch_norm(%65, meta[relay.Constant][86], meta[relay.Constant][87], meta[relay.Constant][88], meta[relay.Constant][89]);\n          %67 = %66.0;\n          %68 = nn.relu(%67);\n          %69 = nn.conv2d(%68, meta[relay.Constant][90], padding=[0, 0, 0, 0], channels=32, kernel_size=[1, 1]);\n          %70 = nn.batch_norm(%69, meta[relay.Constant][91], meta[relay.Constant][92], meta[relay.Constant][93], meta[relay.Constant][94]);\n          %71 = %70.0;\n          %72 = add(%71, %60);\n          %73 = nn.conv2d(%72, meta[relay.Constant][95], padding=[0, 0, 0, 0], channels=192, kernel_size=[1, 1]);\n          %74 = nn.batch_norm(%73, meta[relay.Constant][96], meta[relay.Constant][97], meta[relay.Constant][98], meta[relay.Constant][99]);\n          %75 = %74.0;\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][100], padding=[1, 1, 1, 1], groups=192, channels=192, kernel_size=[3, 3]);\n          %78 = nn.batch_norm(%77, meta[relay.Constant][101], meta[relay.Constant][102], meta[relay.Constant][103], meta[relay.Constant][104]);\n          %79 = %78.0;\n          %80 = nn.relu(%79);\n          %81 = nn.conv2d(%80, meta[relay.Constant][105], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %82 = nn.batch_norm(%81, meta[relay.Constant][106], meta[relay.Constant][107], meta[relay.Constant][108], meta[relay.Constant][109]);\n          %83 = %82.0;\n          %84 = nn.conv2d(%83, meta[relay.Constant][110], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %85 = nn.batch_norm(%84, meta[relay.Constant][111], meta[relay.Constant][112], meta[relay.Constant][113], meta[relay.Constant][114]);\n          %86 = %85.0;\n          %87 = nn.relu(%86);\n          %88 = nn.conv2d(%87, meta[relay.Constant][115], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %89 = nn.batch_norm(%88, meta[relay.Constant][116], meta[relay.Constant][117], meta[relay.Constant][118], meta[relay.Constant][119]);\n          %90 = %89.0;\n          %91 = nn.relu(%90);\n          %92 = nn.conv2d(%91, meta[relay.Constant][120], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %93 = nn.batch_norm(%92, meta[relay.Constant][121], meta[relay.Constant][122], meta[relay.Constant][123], meta[relay.Constant][124]);\n          %94 = %93.0;\n          %95 = add(%94, %83);\n          %96 = nn.conv2d(%95, meta[relay.Constant][125], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %97 = nn.batch_norm(%96, meta[relay.Constant][126], meta[relay.Constant][127], meta[relay.Constant][128], meta[relay.Constant][129]);\n          %98 = %97.0;\n          %99 = nn.relu(%98);\n          %100 = nn.conv2d(%99, meta[relay.Constant][130], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %101 = nn.batch_norm(%100, meta[relay.Constant][131], meta[relay.Constant][132], meta[relay.Constant][133], meta[relay.Constant][134]);\n          %102 = %101.0;\n          %103 = nn.relu(%102);\n          %104 = nn.conv2d(%103, meta[relay.Constant][135], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %105 = nn.batch_norm(%104, meta[relay.Constant][136], meta[relay.Constant][137], meta[relay.Constant][138], meta[relay.Constant][139]);\n          %106 = %105.0;\n          %107 = add(%106, %95);\n          %108 = nn.conv2d(%107, meta[relay.Constant][140], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %109 = nn.batch_norm(%108, meta[relay.Constant][141], meta[relay.Constant][142], meta[relay.Constant][143], meta[relay.Constant][144]);\n          %110 = %109.0;\n          %111 = nn.relu(%110);\n          %112 = nn.conv2d(%111, meta[relay.Constant][145], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %113 = nn.batch_norm(%112, meta[relay.Constant][146], meta[relay.Constant][147], meta[relay.Constant][148], meta[relay.Constant][149]);\n          %114 = %113.0;\n          %115 = nn.relu(%114);\n          %116 = nn.conv2d(%115, meta[relay.Constant][150], padding=[0, 0, 0, 0], channels=64, kernel_size=[1, 1]);\n          %117 = nn.batch_norm(%116, meta[relay.Constant][151], meta[relay.Constant][152], meta[relay.Constant][153], meta[relay.Constant][154]);\n          %118 = %117.0;\n          %119 = add(%118, %107);\n          %120 = nn.conv2d(%119, meta[relay.Constant][155], padding=[0, 0, 0, 0], channels=384, kernel_size=[1, 1]);\n          %121 = nn.batch_norm(%120, meta[relay.Constant][156], meta[relay.Constant][157], meta[relay.Constant][158], meta[relay.Constant][159]);\n          %122 = %121.0;\n          %123 = nn.relu(%122);\n          %124 = nn.conv2d(%123, meta[relay.Constant][160], strides=[2, 2], padding=[1, 1, 1, 1], groups=384, channels=384, kernel_size=[3, 3]);\n          %125 = nn.batch_norm(%124, meta[relay.Constant][161], meta[relay.Constant][162], meta[relay.Constant][163], meta[relay.Constant][164]);\n          %126 = %125.0;\n          %127 = nn.relu(%126);\n          %128 = nn.conv2d(%127, meta[relay.Constant][165], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %129 = nn.batch_norm(%128, meta[relay.Constant][166], meta[relay.Constant][167], meta[relay.Constant][168], meta[relay.Constant][169]);\n          %130 = %129.0;\n          %131 = nn.conv2d(%130, meta[relay.Constant][170], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %132 = nn.batch_norm(%131, meta[relay.Constant][171], meta[relay.Constant][172], meta[relay.Constant][173], meta[relay.Constant][174]);\n          %133 = %132.0;\n          %134 = nn.relu(%133);\n          %135 = nn.conv2d(%134, meta[relay.Constant][175], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %136 = nn.batch_norm(%135, meta[relay.Constant][176], meta[relay.Constant][177], meta[relay.Constant][178], meta[relay.Constant][179]);\n          %137 = %136.0;\n          %138 = nn.relu(%137);\n          %139 = nn.conv2d(%138, meta[relay.Constant][180], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %140 = nn.batch_norm(%139, meta[relay.Constant][181], meta[relay.Constant][182], meta[relay.Constant][183], meta[relay.Constant][184]);\n          %141 = %140.0;\n          %142 = add(%141, %130);\n          %143 = nn.conv2d(%142, meta[relay.Constant][185], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %144 = nn.batch_norm(%143, meta[relay.Constant][186], meta[relay.Constant][187], meta[relay.Constant][188], meta[relay.Constant][189]);\n          %145 = %144.0;\n          %146 = nn.relu(%145);\n          %147 = nn.conv2d(%146, meta[relay.Constant][190], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %148 = nn.batch_norm(%147, meta[relay.Constant][191], meta[relay.Constant][192], meta[relay.Constant][193], meta[relay.Constant][194]);\n          %149 = %148.0;\n          %150 = nn.relu(%149);\n          %151 = nn.conv2d(%150, meta[relay.Constant][195], padding=[0, 0, 0, 0], channels=96, kernel_size=[1, 1]);\n          %152 = nn.batch_norm(%151, meta[relay.Constant][196], meta[relay.Constant][197], meta[relay.Constant][198], meta[relay.Constant][199]);\n          %153 = %152.0;\n          %154 = add(%153, %142);\n          %155 = nn.conv2d(%154, meta[relay.Constant][200], padding=[0, 0, 0, 0], channels=576, kernel_size=[1, 1]);\n          %156 = nn.batch_norm(%155, meta[relay.Constant][201], meta[relay.Constant][202], meta[relay.Constant][203], meta[relay.Constant][204]);\n          %157 = %156.0;\n          %158 = nn.relu(%157);\n          %159 = nn.conv2d(%158, meta[relay.Constant][205], strides=[2, 2], padding=[1, 1, 1, 1], groups=576, channels=576, kernel_size=[3, 3]);\n          %160 = nn.batch_norm(%159, meta[relay.Constant][206], meta[relay.Constant][207], meta[relay.Constant][208], meta[relay.Constant][209]);\n          %161 = %160.0;\n          %162 = nn.relu(%161);\n          %163 = nn.conv2d(%162, meta[relay.Constant][210], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %164 = nn.batch_norm(%163, meta[relay.Constant][211], meta[relay.Constant][212], meta[relay.Constant][213], meta[relay.Constant][214]);\n          %165 = %164.0;\n          %166 = nn.conv2d(%165, meta[relay.Constant][215], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %167 = nn.batch_norm(%166, meta[relay.Constant][216], meta[relay.Constant][217], meta[relay.Constant][218], meta[relay.Constant][219]);\n          %168 = %167.0;\n          %169 = nn.relu(%168);\n          %170 = nn.conv2d(%169, meta[relay.Constant][220], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %171 = nn.batch_norm(%170, meta[relay.Constant][221], meta[relay.Constant][222], meta[relay.Constant][223], meta[relay.Constant][224]);\n          %172 = %171.0;\n          %173 = nn.relu(%172);\n          %174 = nn.conv2d(%173, meta[relay.Constant][225], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %175 = nn.batch_norm(%174, meta[relay.Constant][226], meta[relay.Constant][227], meta[relay.Constant][228], meta[relay.Constant][229]);\n          %176 = %175.0;\n          %177 = add(%176, %165);\n          %178 = nn.conv2d(%177, meta[relay.Constant][230], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %179 = nn.batch_norm(%178, meta[relay.Constant][231], meta[relay.Constant][232], meta[relay.Constant][233], meta[relay.Constant][234]);\n          %180 = %179.0;\n          %181 = nn.relu(%180);\n          %182 = nn.conv2d(%181, meta[relay.Constant][235], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %183 = nn.batch_norm(%182, meta[relay.Constant][236], meta[relay.Constant][237], meta[relay.Constant][238], meta[relay.Constant][239]);\n          %184 = %183.0;\n          %185 = nn.relu(%184);\n          %186 = nn.conv2d(%185, meta[relay.Constant][240], padding=[0, 0, 0, 0], channels=160, kernel_size=[1, 1]);\n          %187 = nn.batch_norm(%186, meta[relay.Constant][241], meta[relay.Constant][242], meta[relay.Constant][243], meta[relay.Constant][244]);\n          %188 = %187.0;\n          %189 = add(%188, %177);\n          %190 = nn.conv2d(%189, meta[relay.Constant][245], padding=[0, 0, 0, 0], channels=960, kernel_size=[1, 1]);\n          %191 = nn.batch_norm(%190, meta[relay.Constant][246], meta[relay.Constant][247], meta[relay.Constant][248], meta[relay.Constant][249]);\n          %192 = %191.0;\n          %193 = nn.relu(%192);\n          %194 = nn.conv2d(%193, meta[relay.Constant][250], padding=[1, 1, 1, 1], groups=960, channels=960, kernel_size=[3, 3]);\n          %195 = nn.batch_norm(%194, meta[relay.Constant][251], meta[relay.Constant][252], meta[relay.Constant][253], meta[relay.Constant][254]);\n          %196 = %195.0;\n          %197 = nn.relu(%196);\n          %198 = nn.conv2d(%197, meta[relay.Constant][255], padding=[0, 0, 0, 0], channels=320, kernel_size=[1, 1]);\n          %199 = nn.batch_norm(%198, meta[relay.Constant][256], meta[relay.Constant][257], meta[relay.Constant][258], meta[relay.Constant][259]);\n          %200 = %199.0;\n          %201 = nn.conv2d(%200, meta[relay.Constant][260], padding=[0, 0, 0, 0], channels=1280, kernel_size=[1, 1]);\n          %202 = nn.batch_norm(%201, meta[relay.Constant][261], meta[relay.Constant][262], meta[relay.Constant][263], meta[relay.Constant][264]);\n          %203 = %202.0;\n          %204 = nn.relu(%203);\n          %205 = nn.global_avg_pool2d(%204);\n          %206 = nn.conv2d(%205, meta[relay.Constant][265], padding=[0, 0, 0, 0], channels=1000, kernel_size=[1, 1]);\n          reshape(%206, newshape=[0, -1])\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"mobilenet_16\",\n        \"input_shapes\": {\"data\": [1, 3, 224, 224]},\n        \"input_dtypes\": {\"data\": \"float16\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef batch_norm_extract():\n    consts = make_consts(\n        \"float32\",\n        [\n            (32,),  # 0\n            (32,),  # 1\n            (32,),  # 2\n            (32,),  # 3\n        ],\n    )\n    metatable = {\"relay.Constant\": consts}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%FunctionVar_0: Tensor[(1, 32, 112, 112), float32]) -> Tensor[(1, 32, 112, 112), float32] {\n          %3 = nn.batch_norm(%FunctionVar_0, meta[relay.Constant][0], meta[relay.Constant][1], meta[relay.Constant][2], meta[relay.Constant][3]);\n          %3.0\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"batch_norm_extract\",\n        \"input_shapes\": {\"FunctionVar_0\": [1, 32, 112, 112]},\n        \"input_dtypes\": {\"FunctionVar_0\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef resnext50_32x4d_consts(dtype):\n    return make_consts(\n        dtype,\n        [\n            (128, 64, 1, 1),  # 0\n            (128, 4, 3, 3),  # 1\n            (256, 128, 1, 1),  # 2\n            (256, 64, 1, 1),  # 3\n            (128, 256, 1, 1),  # 4\n            (128, 4, 3, 3),  # 5\n            (256, 128, 1, 1),  # 6\n            (128, 256, 1, 1),  # 7\n            (128, 4, 3, 3),  # 8\n            (256, 128, 1, 1),  # 9\n            (256, 256, 1, 1),  # 10\n            (256, 8, 3, 3),  # 11\n            (512, 256, 1, 1),  # 12\n            (512, 256, 1, 1),  # 13\n            (256, 512, 1, 1),  # 14\n            (256, 8, 3, 3),  # 15\n            (512, 256, 1, 1),  # 16\n            (256, 512, 1, 1),  # 17\n            (256, 8, 3, 3),  # 18\n            (512, 256, 1, 1),  # 19\n            (256, 512, 1, 1),  # 20\n            (256, 8, 3, 3),  # 21\n            (512, 256, 1, 1),  # 22\n            (512, 512, 1, 1),  # 23\n            (512, 16, 3, 3),  # 24\n            (1024, 512, 1, 1),  # 25\n            (1024, 512, 1, 1),  # 26\n            (512, 1024, 1, 1),  # 27\n            (512, 16, 3, 3),  # 28\n            (1024, 512, 1, 1),  # 29\n            (512, 1024, 1, 1),  # 30\n            (512, 16, 3, 3),  # 31\n            (1024, 512, 1, 1),  # 32\n            (512, 1024, 1, 1),  # 33\n            (512, 16, 3, 3),  # 34\n            (1024, 512, 1, 1),  # 35\n            (512, 1024, 1, 1),  # 36\n            (512, 16, 3, 3),  # 37\n            (1024, 512, 1, 1),  # 38\n            (512, 1024, 1, 1),  # 39\n            (512, 16, 3, 3),  # 40\n            (1024, 512, 1, 1),  # 41\n            (1024, 1024, 1, 1),  # 42\n            (1024, 32, 3, 3),  # 43\n            (2048, 1024, 1, 1),  # 44\n            (2048, 1024, 1, 1),  # 45\n            (1024, 2048, 1, 1),  # 46\n            (1024, 32, 3, 3),  # 47\n            (2048, 1024, 1, 1),  # 48\n            (1024, 2048, 1, 1),  # 49\n            (1024, 32, 3, 3),  # 50\n            (2048, 1024, 1, 1),  # 51\n        ],\n    )\n\n\ndef resnext50_32x4d():\n    metatable = {\"relay.Constant\": resnext50_32x4d_consts(\"float32\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1, 64, 56, 56), float32]) {\n          %0 = nn.conv2d(%x, meta[relay.Constant][0], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %1 = nn.relu(%0);\n          %2 = nn.conv2d(%1, meta[relay.Constant][1], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %3 = nn.relu(%2);\n          %4 = nn.conv2d(%3, meta[relay.Constant][2], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %5 = nn.conv2d(%x, meta[relay.Constant][3], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %6 = add(%4, %5);\n          %7 = nn.relu(%6);\n          %8 = nn.conv2d(%7, meta[relay.Constant][4], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %9 = nn.relu(%8);\n          %10 = nn.conv2d(%9, meta[relay.Constant][5], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %11 = nn.relu(%10);\n          %12 = nn.conv2d(%11, meta[relay.Constant][6], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %13 = add(%12, %7);\n          %14 = nn.relu(%13);\n          %15 = nn.conv2d(%14, meta[relay.Constant][7], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %16 = nn.relu(%15);\n          %17 = nn.conv2d(%16, meta[relay.Constant][8], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %18 = nn.relu(%17);\n          %19 = nn.conv2d(%18, meta[relay.Constant][9], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %20 = add(%19, %14);\n          %21 = nn.relu(%20);\n          %22 = nn.conv2d(%21, meta[relay.Constant][10], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %23 = nn.relu(%22);\n          %24 = nn.conv2d(%23, meta[relay.Constant][11], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %25 = nn.relu(%24);\n          %26 = nn.conv2d(%25, meta[relay.Constant][12], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %27 = nn.conv2d(%21, meta[relay.Constant][13], strides=[2, 2], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %28 = add(%26, %27);\n          %29 = nn.relu(%28);\n          %30 = nn.conv2d(%29, meta[relay.Constant][14], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %31 = nn.relu(%30);\n          %32 = nn.conv2d(%31, meta[relay.Constant][15], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %33 = nn.relu(%32);\n          %34 = nn.conv2d(%33, meta[relay.Constant][16], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %35 = add(%34, %29);\n          %36 = nn.relu(%35);\n          %37 = nn.conv2d(%36, meta[relay.Constant][17], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %38 = nn.relu(%37);\n          %39 = nn.conv2d(%38, meta[relay.Constant][18], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %40 = nn.relu(%39);\n          %41 = nn.conv2d(%40, meta[relay.Constant][19], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %42 = add(%41, %36);\n          %43 = nn.relu(%42);\n          %44 = nn.conv2d(%43, meta[relay.Constant][20], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %45 = nn.relu(%44);\n          %46 = nn.conv2d(%45, meta[relay.Constant][21], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %47 = nn.relu(%46);\n          %48 = nn.conv2d(%47, meta[relay.Constant][22], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %49 = add(%48, %43);\n          %50 = nn.relu(%49);\n          %51 = nn.conv2d(%50, meta[relay.Constant][23], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %52 = nn.relu(%51);\n          %53 = nn.conv2d(%52, meta[relay.Constant][24], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %54 = nn.relu(%53);\n          %55 = nn.conv2d(%54, meta[relay.Constant][25], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %56 = nn.conv2d(%50, meta[relay.Constant][26], strides=[2, 2], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %57 = add(%55, %56);\n          %58 = nn.relu(%57);\n          %59 = nn.conv2d(%58, meta[relay.Constant][27], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %60 = nn.relu(%59);\n          %61 = nn.conv2d(%60, meta[relay.Constant][28], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %62 = nn.relu(%61);\n          %63 = nn.conv2d(%62, meta[relay.Constant][29], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %64 = add(%63, %58);\n          %65 = nn.relu(%64);\n          %66 = nn.conv2d(%65, meta[relay.Constant][30], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %67 = nn.relu(%66);\n          %68 = nn.conv2d(%67, meta[relay.Constant][31], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %69 = nn.relu(%68);\n          %70 = nn.conv2d(%69, meta[relay.Constant][32], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %71 = add(%70, %65);\n          %72 = nn.relu(%71);\n          %73 = nn.conv2d(%72, meta[relay.Constant][33], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %74 = nn.relu(%73);\n          %75 = nn.conv2d(%74, meta[relay.Constant][34], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][35], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %78 = add(%77, %72);\n          %79 = nn.relu(%78);\n          %80 = nn.conv2d(%79, meta[relay.Constant][36], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %81 = nn.relu(%80);\n          %82 = nn.conv2d(%81, meta[relay.Constant][37], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %83 = nn.relu(%82);\n          %84 = nn.conv2d(%83, meta[relay.Constant][38], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %85 = add(%84, %79);\n          %86 = nn.relu(%85);\n          %87 = nn.conv2d(%86, meta[relay.Constant][39], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %88 = nn.relu(%87);\n          %89 = nn.conv2d(%88, meta[relay.Constant][40], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %90 = nn.relu(%89);\n          %91 = nn.conv2d(%90, meta[relay.Constant][41], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %92 = add(%91, %86);\n          %93 = nn.relu(%92);\n          %94 = nn.conv2d(%93, meta[relay.Constant][42], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %95 = nn.relu(%94);\n          %96 = nn.conv2d(%95, meta[relay.Constant][43], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %97 = nn.relu(%96);\n          %98 = nn.conv2d(%97, meta[relay.Constant][44], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %99 = nn.conv2d(%93, meta[relay.Constant][45], strides=[2, 2], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %100 = add(%98, %99);\n          %101 = nn.relu(%100);\n          %102 = nn.conv2d(%101, meta[relay.Constant][46], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %103 = nn.relu(%102);\n          %104 = nn.conv2d(%103, meta[relay.Constant][47], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %105 = nn.relu(%104);\n          %106 = nn.conv2d(%105, meta[relay.Constant][48], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %107 = add(%106, %101);\n          %108 = nn.relu(%107);\n          %109 = nn.conv2d(%108, meta[relay.Constant][49], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %110 = nn.relu(%109);\n          %111 = nn.conv2d(%110, meta[relay.Constant][50], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %112 = nn.relu(%111);\n          %113 = nn.conv2d(%112, meta[relay.Constant][51], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %114 = add(%113, %108);\n          nn.relu(%114)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"resnext50_32x4d\",\n        \"input_shapes\": {\"x\": [1, 64, 56, 56]},\n        \"input_dtypes\": {\"x\": \"float32\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float32\",\n    }\n\n\ndef resnext50_32x4d_16():\n    metatable = {\"relay.Constant\": resnext50_32x4d_consts(\"float16\")}\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(1, 64, 56, 56), float16]) {\n          %0 = nn.conv2d(%x, meta[relay.Constant][0], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %1 = nn.relu(%0);\n          %2 = nn.conv2d(%1, meta[relay.Constant][1], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %3 = nn.relu(%2);\n          %4 = nn.conv2d(%3, meta[relay.Constant][2], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %5 = nn.conv2d(%x, meta[relay.Constant][3], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %6 = add(%4, %5);\n          %7 = nn.relu(%6);\n          %8 = nn.conv2d(%7, meta[relay.Constant][4], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %9 = nn.relu(%8);\n          %10 = nn.conv2d(%9, meta[relay.Constant][5], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %11 = nn.relu(%10);\n          %12 = nn.conv2d(%11, meta[relay.Constant][6], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %13 = add(%12, %7);\n          %14 = nn.relu(%13);\n          %15 = nn.conv2d(%14, meta[relay.Constant][7], padding=[0, 0, 0, 0], channels=128, kernel_size=[1, 1]);\n          %16 = nn.relu(%15);\n          %17 = nn.conv2d(%16, meta[relay.Constant][8], padding=[1, 1, 1, 1], groups=32, channels=128, kernel_size=[3, 3]);\n          %18 = nn.relu(%17);\n          %19 = nn.conv2d(%18, meta[relay.Constant][9], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %20 = add(%19, %14);\n          %21 = nn.relu(%20);\n          %22 = nn.conv2d(%21, meta[relay.Constant][10], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %23 = nn.relu(%22);\n          %24 = nn.conv2d(%23, meta[relay.Constant][11], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %25 = nn.relu(%24);\n          %26 = nn.conv2d(%25, meta[relay.Constant][12], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %27 = nn.conv2d(%21, meta[relay.Constant][13], strides=[2, 2], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %28 = add(%26, %27);\n          %29 = nn.relu(%28);\n          %30 = nn.conv2d(%29, meta[relay.Constant][14], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %31 = nn.relu(%30);\n          %32 = nn.conv2d(%31, meta[relay.Constant][15], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %33 = nn.relu(%32);\n          %34 = nn.conv2d(%33, meta[relay.Constant][16], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %35 = add(%34, %29);\n          %36 = nn.relu(%35);\n          %37 = nn.conv2d(%36, meta[relay.Constant][17], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %38 = nn.relu(%37);\n          %39 = nn.conv2d(%38, meta[relay.Constant][18], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %40 = nn.relu(%39);\n          %41 = nn.conv2d(%40, meta[relay.Constant][19], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %42 = add(%41, %36);\n          %43 = nn.relu(%42);\n          %44 = nn.conv2d(%43, meta[relay.Constant][20], padding=[0, 0, 0, 0], channels=256, kernel_size=[1, 1]);\n          %45 = nn.relu(%44);\n          %46 = nn.conv2d(%45, meta[relay.Constant][21], padding=[1, 1, 1, 1], groups=32, channels=256, kernel_size=[3, 3]);\n          %47 = nn.relu(%46);\n          %48 = nn.conv2d(%47, meta[relay.Constant][22], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %49 = add(%48, %43);\n          %50 = nn.relu(%49);\n          %51 = nn.conv2d(%50, meta[relay.Constant][23], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %52 = nn.relu(%51);\n          %53 = nn.conv2d(%52, meta[relay.Constant][24], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %54 = nn.relu(%53);\n          %55 = nn.conv2d(%54, meta[relay.Constant][25], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %56 = nn.conv2d(%50, meta[relay.Constant][26], strides=[2, 2], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %57 = add(%55, %56);\n          %58 = nn.relu(%57);\n          %59 = nn.conv2d(%58, meta[relay.Constant][27], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %60 = nn.relu(%59);\n          %61 = nn.conv2d(%60, meta[relay.Constant][28], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %62 = nn.relu(%61);\n          %63 = nn.conv2d(%62, meta[relay.Constant][29], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %64 = add(%63, %58);\n          %65 = nn.relu(%64);\n          %66 = nn.conv2d(%65, meta[relay.Constant][30], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %67 = nn.relu(%66);\n          %68 = nn.conv2d(%67, meta[relay.Constant][31], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %69 = nn.relu(%68);\n          %70 = nn.conv2d(%69, meta[relay.Constant][32], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %71 = add(%70, %65);\n          %72 = nn.relu(%71);\n          %73 = nn.conv2d(%72, meta[relay.Constant][33], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %74 = nn.relu(%73);\n          %75 = nn.conv2d(%74, meta[relay.Constant][34], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %76 = nn.relu(%75);\n          %77 = nn.conv2d(%76, meta[relay.Constant][35], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %78 = add(%77, %72);\n          %79 = nn.relu(%78);\n          %80 = nn.conv2d(%79, meta[relay.Constant][36], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %81 = nn.relu(%80);\n          %82 = nn.conv2d(%81, meta[relay.Constant][37], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %83 = nn.relu(%82);\n          %84 = nn.conv2d(%83, meta[relay.Constant][38], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %85 = add(%84, %79);\n          %86 = nn.relu(%85);\n          %87 = nn.conv2d(%86, meta[relay.Constant][39], padding=[0, 0, 0, 0], channels=512, kernel_size=[1, 1]);\n          %88 = nn.relu(%87);\n          %89 = nn.conv2d(%88, meta[relay.Constant][40], padding=[1, 1, 1, 1], groups=32, channels=512, kernel_size=[3, 3]);\n          %90 = nn.relu(%89);\n          %91 = nn.conv2d(%90, meta[relay.Constant][41], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %92 = add(%91, %86);\n          %93 = nn.relu(%92);\n          %94 = nn.conv2d(%93, meta[relay.Constant][42], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %95 = nn.relu(%94);\n          %96 = nn.conv2d(%95, meta[relay.Constant][43], strides=[2, 2], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %97 = nn.relu(%96);\n          %98 = nn.conv2d(%97, meta[relay.Constant][44], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %99 = nn.conv2d(%93, meta[relay.Constant][45], strides=[2, 2], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %100 = add(%98, %99);\n          %101 = nn.relu(%100);\n          %102 = nn.conv2d(%101, meta[relay.Constant][46], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %103 = nn.relu(%102);\n          %104 = nn.conv2d(%103, meta[relay.Constant][47], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %105 = nn.relu(%104);\n          %106 = nn.conv2d(%105, meta[relay.Constant][48], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %107 = add(%106, %101);\n          %108 = nn.relu(%107);\n          %109 = nn.conv2d(%108, meta[relay.Constant][49], padding=[0, 0, 0, 0], channels=1024, kernel_size=[1, 1]);\n          %110 = nn.relu(%109);\n          %111 = nn.conv2d(%110, meta[relay.Constant][50], padding=[1, 1, 1, 1], groups=32, channels=1024, kernel_size=[3, 3]);\n          %112 = nn.relu(%111);\n          %113 = nn.conv2d(%112, meta[relay.Constant][51], padding=[0, 0, 0, 0], channels=2048, kernel_size=[1, 1]);\n          %114 = add(%113, %108);\n          nn.relu(%114)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    return {\n        \"name\": \"resnext50_32x4d_16\",\n        \"input_shapes\": {\"x\": [1, 64, 56, 56]},\n        \"input_dtypes\": {\"x\": \"float16\"},\n        \"mod\": mod,\n        \"params\": None,\n        \"main_dtype\": \"float16\",\n    }\n\n\ndef describe_onnx(name, filename):\n    \"\"\"Returns the description of the ONNX model at filename, which can be passed to from_onnx to actually load\n    the model. Note that ? (ie unknown) shape dimensions must be manually changed to concrete dimensions\n    which are consistent with the overall model.\"\"\"\n    onnx_model = onnx.load(MODEL_PREFIX + filename)\n    input_shapes = {}\n    input_dtypes = {}\n    initializer_names = [n.name for n in onnx_model.graph.initializer]\n    for input_info in onnx_model.graph.input:\n        if input_info.name not in initializer_names:\n            _, shape, dtype, _ = tvm.relay.frontend.onnx.get_info(input_info)\n            if dtype is None:\n                raise ValueError(f\"Unknown dtype on input '{input_info.name}' is not supported.\")\n            input_shapes.update({input_info.name: shape})\n            input_dtypes.update({input_info.name: dtype})\n    print(\n        f\"{{'name': '{name}', 'filename': '{filename}', 'input_shapes': {input_shapes}, 'input_dtypes': {input_dtypes}, 'main_dtype': 'float32'}}\"\n    )\n\n\ndef from_onnx(model):\n    logging.info(\"-------------------- BEGIN ONNX IMPORT --------------------\")\n\n    filename = MODEL_PREFIX + model[\"filename\"]\n    logging.info(f\"Loading ONNX model from {filename}\")\n\n    onnx_model = onnx.load(filename)\n    logging.info(f\"Loaded model from {filename}\")\n\n    mod, params = tvm.relay.frontend.from_onnx(\n        onnx_model, model[\"input_shapes\"], freeze_params=True\n    )\n    mod = tvm.relay.transform.InferType()(mod)\n    logging.info(\"-------------------- END ONNX IMPORT --------------------\")\n\n    logging.info(f\"Imported model:\\n{mod}\")\n    logging.info(f\"Params:\\n{params}\")\n\n    return {\n        \"name\": model[\"name\"],\n        \"input_shapes\": model[\"input_shapes\"],\n        \"input_dtypes\": model[\"input_dtypes\"],\n        \"mod\": mod,\n        \"params\": params,\n        \"main_dtype\": model[\"main_dtype\"],\n    }\n\n\ndef to_onnx(model):\n    logging.info(\"-------------------- BEGIN ONNX EXPORT --------------------\")\n    short_filename = model[\"name\"] + \".onnx\"\n    filename = MODEL_PREFIX + short_filename\n    logging.info(f\"Saving ONNX model to {filename}\")\n\n    params = model[\"params\"]\n    if params is None:\n        params = {}\n    tvm.contrib.target.onnx.to_onnx(model[\"mod\"], params, model[\"name\"], path=filename)\n    logging.info(\"-------------------- END ONNX EXPORT --------------------\")\n\n    return {\n        \"name\": model[\"name\"],\n        \"filename\": short_filename,\n        \"input_shapes\": model[\"input_shapes\"],\n        \"input_dtypes\": model[\"input_dtypes\"],\n        \"main_dtype\": model[\"main_dtype\"],\n    }\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/collage/test_sub_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport logging\nimport tvm.testing\n\nlogging.basicConfig(level=logging.INFO)\n\npartition_for_testing = tvm._ffi.get_global_func(\"relay.collage.PartitionForTesting\")\n\n\ndef print_with_indexes(mod):\n    mod = tvm.relay.transform.CapturePostDfsIndexInSpans()(mod)\n    print(mod)\n\n\ndef run(in_mod, expected_mod, max_outputs, allow_taps, compiler, map):\n    expected_mod = tvm.relay.transform.InferType()(expected_mod)\n\n    in_mod = tvm.relay.transform.InferType()(in_mod)\n    in_mod = tvm.relay.transform.CapturePostDfsIndexInSpans()(in_mod)\n\n    indexes = [i for l, iss in map.items() for i in iss]\n    labels = [l for l, iss in map.items() for i in iss]\n    actual_mod = partition_for_testing(max_outputs, allow_taps, compiler, indexes, labels)(in_mod)\n\n    if not tvm.ir.structural_equal(actual_mod, expected_mod, True):\n        # Print everything in full so we can see what's going on when things fail.\n        print(\"Input module:\")\n        print(in_mod)\n        print(\"Expected module:\")\n        print(expected_mod)\n        print(\"Actual module:\")\n        print(actual_mod)\n        # Assert again so as to see the actual disagreeing sub-expressions.\n        tvm.ir.assert_structural_equal(actual_mod, expected_mod, map_free_vars=True)\n\n\ndef test_single_op():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = add(%c, %d);   // node 7\n              subtract(%0, %1)\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = (fn(%x, %y, Compiler=\"foo\") { add(%x, %y) })(%c, %d);\n              subtract(%0, %1)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 1, False, \"foo\", {\"\": [7]})\n\n\ndef test_multi_output():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);   // node 6\n              %1 = add(%c, %d);   // node 7\n              subtract(%0, %1)\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = (fn(%w, %x, %y, %z, Compiler=\"foo\") { (add(%y, %z), add(%w, %x)) })(%c, %d, %a, %b);\n              %1 = %0.0;\n              %2 = %0.1;\n              subtract(%1, %2)\n            }\n        \"\"\"\n        )\n\n    # No rewrite since 2 outputs\n    run(input(), input(), 1, False, \"foo\", {\"\": [6, 7]})\n    # Rewrite\n    run(input(), expected(), 2, False, \"foo\", {\"\": [6, 7]})\n\n\ndef test_classic_conv2d_add_relu():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32],\n                      %c: Tensor[(5, 2, 28, 28), float32], %d: Tensor[(5, 2, 28, 28), float32]) {\n              %0 = nn.conv2d(%a, %b); // node 8\n              %1 = add(%0, %c);       // node 9\n              %2 = nn.relu(%1);       // node 10\n              subtract(%2, %d)\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32],\n                      %c: Tensor[(5, 2, 28, 28), float32], %d: Tensor[(5, 2, 28, 28), float32]) {\n              %2 = (fn(%x, %y, %z, Compiler=\"foo\") {\n                %0 = nn.conv2d(%x, %y);\n                %1 = add(%0, %z);\n                nn.relu(%1)\n              })(%a, %b, %c);\n              subtract(%2, %d)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 1, False, \"foo\", {\"\": [8, 9, 10]})\n\n\ndef test_diamond_single_output():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              %0 = nn.conv2d(%a, %b, padding=[0, 0, 0, 0]); // node 5\n              %1 = nn.relu(%0);                             // node 6\n              %2 = nn.relu(%1);                             // node 7\n              %3 = nn.leaky_relu(%0, alpha=0f);             // node 9\n              add(%2, %3)                                   // node 10\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              (fn (%x: Tensor[(5, 3, 32, 32), float32], %y: Tensor[(2, 3, 5, 5), float32], Compiler=\"foo\") {\n                %0 = nn.conv2d(%x, %y, padding=[0, 0, 0, 0]);\n                %1 = nn.relu(%0);\n                %2 = nn.relu(%1);\n                %3 = nn.leaky_relu(%0, alpha=0f);\n                add(%2, %3)\n              })(%a, %b)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 1, False, \"foo\", {\"\": [5, 6, 7, 9, 10]})\n\n\ndef test_diamond_multi_output():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              %0 = nn.conv2d(%a, %b, padding=[0, 0, 0, 0]); // node 5\n              %1 = nn.relu(%0);                             // node 6\n              %2 = nn.relu(%1);                             // node 7\n              %3 = nn.leaky_relu(%0, alpha=0f);             // node 9\n              add(%2, %3)\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              %4 = (fn (%x: Tensor[(5, 3, 32, 32), float32], %y: Tensor[(2, 3, 5, 5), float32], Compiler=\"foo\") {\n                %0 = nn.conv2d(%x, %y, padding=[0, 0, 0, 0]);\n                %1 = nn.relu(%0);\n                %2 = nn.relu(%1);\n                %3 = nn.leaky_relu(%0, alpha=0f);\n                (%2, %3)\n              })(%a, %b);\n              %5 = %4.0;\n              %6 = %4.1;\n              add(%5, %6)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 2, False, \"foo\", {\"\": [5, 6, 7, 9]})\n\n\ndef test_with_tap():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              %0 = nn.conv2d(%a, %b, padding=[0, 0, 0, 0]); // node 5\n              %1 = nn.relu(%0);                             // node 6\n              add(%1, %0)\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 3, 32, 32), float32], %b: Tensor[(2, 3, 5, 5), float32]) {\n              %2 = (fn (%x, %y, Compiler=\"foo\") {\n                %0 = nn.conv2d(%x, %y, padding=[0, 0, 0, 0]);\n                %1 = nn.relu(%0);\n                (%0, %1)\n              })(%a, %b);\n              %3 = %2.1;\n              %4 = %2.0;\n              add(%3, %4)\n            }\n        \"\"\"\n        )\n\n    # No rewrite since has tap\n    run(input(), input(), 2, False, \"foo\", {\"\": [5, 6]})\n    # Rewrite\n    run(input(), expected(), 2, True, \"foo\", {\"\": [5, 6]})\n\n\ndef test_no_cycles():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b); // node 3\n              %1 = add(%0, %b);\n              add(%1, %b)       // node 5\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) {\n              (fn(%x, %y, Compiler=\"foo\") {\n                %0 = add(%x, %y);\n                %1 = add(%0, %y);\n                add(%1, %y)\n              })(%a, %b)\n            }\n        \"\"\"\n        )\n\n    # No rewrite since would create cycle\n    run(input(), input(), 2, False, \"foo\", {\"\": [3, 5]})\n    # No cycle\n    run(input(), expected(), 2, False, \"foo\", {\"\": [3, 4, 5]})\n\n\ndef test_labels_direct_connection():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32]) {\n              %0 = nn.relu(%a);  // node 3\n              %1 = nn.relu(%0);  // node 4\n              %2 = nn.relu(%1);  // node 5\n              %3 = nn.relu(%1);  // node 6\n              %4 = add(%2, %3);  // node 7\n              %5 = nn.relu(%4);  // node 8\n              %6 = nn.relu(%4);  // node 9\n              %7 = add(%5, %6);  // node 10\n              nn.relu(%7)        // node 11\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32]) {\n              (fn(%aa: Tensor[(5, 7), float32], Compiler=\"foo\") {\n                %0 = nn.relu(%aa);\n                %4 = (fn(%y, Composite=\"a\") {\n                  %1 = nn.relu(%y);\n                  %2 = nn.relu(%1);\n                  %3 = nn.relu(%1);\n                  add(%2, %3)\n                })(%0);\n                %7 = (fn(%z, Composite=\"b\") {\n                  %5 = nn.relu(%z);\n                  %6 = nn.relu(%z);\n                  add(%5, %6)\n                })(%4);\n                nn.relu(%7)\n              })(%a)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 1, False, \"foo\", {\"\": [3, 11], \"a\": [4, 5, 6, 7], \"b\": [8, 9, 10]})\n\n\ndef test_labels_nested_tap():\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32]) {\n              %0 = nn.relu(%a);  // node 3\n              %1 = nn.relu(%0);  // node 4\n              %2 = nn.relu(%1);  // node 5\n              %3 = nn.relu(%1);  // node 6\n              %4 = add(%2, %3);  // node 7\n              %5 = nn.relu(%4);  // node 8\n              %6 = nn.relu(%4);  // node 9\n              %7 = add(%5, %6);  // node 10\n              add(%2, %7)        // node 11\n            }\n        \"\"\"\n        )\n\n    def expected():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32]) {\n              %0 = nn.relu(%a);\n              %9 = (fn(%x: Tensor[(5, 7), float32], Compiler=\"foo\") {\n                %5 = (fn(%y, Composite=\"a\") {\n                  %1 = nn.relu(%y);\n                  %2 = nn.relu(%1);\n                  %3 = nn.relu(%1);\n                  %4 = add(%2, %3);\n                  (%2, %4)\n                })(%x);\n                %8 = (fn(%z, Composite=\"b\") {\n                  %6 = nn.relu(%z);\n                  %7 = nn.relu(%z);\n                  add(%6, %7)\n                })(%5.1);\n                (%5.0, %8)\n              })(%0);\n              add(%9.0, %9.1)\n            }\n        \"\"\"\n        )\n\n    run(input(), expected(), 2, True, \"foo\", {\"a\": [4, 5, 6, 7], \"b\": [8, 9, 10]})\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level10.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nSupport level10 operator test cases.\n\n\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import run_infer_type\nimport tvm.topi.testing\nimport random\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"debug\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_to(executor_kind):\n    def verify_more_dynamic_broadcast_to(x_shape, out_shape):\n        rank = len(out_shape)\n        dtype = \"float32\"\n        shape_type = \"int64\"\n        reshape_shape = relay.Var(\"shape\", relay.ty.TensorType((len(x_shape),), shape_type))\n        broadcast_shape = relay.Var(\"shape\", relay.ty.TensorType((rank,), shape_type))\n        x = relay.Var(\"x\", relay.ty.TensorType((np.prod(x_shape),), dtype))\n        r = relay.reshape(x, reshape_shape)\n        z = relay.broadcast_to(r, broadcast_shape)\n\n        func = relay.Function([x, reshape_shape, broadcast_shape], z)\n\n        x = np.random.uniform(size=np.prod(x_shape)).astype(dtype)\n        ref_res = np.broadcast_to(np.reshape(x, x_shape), out_shape)\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate(func)(\n                x, np.array(x_shape).astype(shape_type), np.array(out_shape).astype(shape_type)\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_more_dynamic_broadcast_to((4, 3), (3, 4, 3))\n\n    def verify_broadcast_to(x_shape, out_shape):\n        rank = len(out_shape)\n        dtype = \"float32\"\n        shape_type = \"int64\"\n        dyn_shape = relay.Var(\"shape\", relay.ty.TensorType((rank,), shape_type))\n        x = relay.Var(\"x\", relay.ty.TensorType(x_shape, dtype))\n        z = relay.broadcast_to(x, dyn_shape)\n        zz = run_infer_type(z)\n\n        assert zz.checked_type == relay.ty.TensorType((relay.Any(),) * rank, dtype)\n\n        func = relay.Function([x, dyn_shape], z)\n\n        x = np.random.uniform(size=x_shape).astype(dtype)\n        ref_res = np.broadcast_to(x, out_shape)\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate(func)(x, np.array(out_shape).astype(shape_type))\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_broadcast_to((1,), (1, 1, 1))\n    verify_broadcast_to((1, 1), (4, 1, 1))\n    verify_broadcast_to((4, 1), (1, 4, 3))\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_broadcast_to(executor_kind):\n    dtype = \"uint8\"\n    rank = 3\n    shape_type = \"int64\"\n    dyn_shape = relay.Var(\"shape\", relay.ty.TensorType((rank,), shape_type))\n    x_shape = (1,)\n    x = relay.Var(\"x\", relay.ty.TensorType(x_shape, dtype))\n    z = relay.broadcast_to(x, dyn_shape)\n    zz = run_infer_type(z)\n\n    assert zz.checked_type == relay.ty.TensorType((relay.Any(),) * rank, dtype)\n\n    func = relay.Function([x, dyn_shape], z)\n\n    x = np.random.uniform(size=x_shape).astype(dtype)\n    dyn_shape = (1,) * rank\n    ref_res = np.broadcast_to(x, dyn_shape)\n    for target, dev in tvm.testing.enabled_targets():\n        mod = tvm.ir.IRModule.from_expr(func)\n        op_res = relay.create_executor(executor_kind, mod=mod, device=dev, target=target).evaluate(\n            func\n        )(x, np.array(dyn_shape).astype(shape_type))\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_one_hot(executor_kind):\n    def _get_oshape(indices_shape, depth, axis):\n        oshape = []\n        true_axis = len(indices_shape) if axis == -1 else axis\n        ndim = len(indices_shape) + 1\n        indices_index = 0\n        for i in range(0, ndim):\n            if i == true_axis:\n                oshape.append(depth)\n            else:\n                oshape.append(indices_shape[indices_index])\n                indices_index += 1\n\n        return oshape\n\n    def _verify(indices_shape, depth, on_value, off_value, axis, dtype):\n        indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n        depth_var = relay.var(\"depth\", relay.TensorType((), \"int32\"))\n        on_value_const = relay.const(on_value)\n        off_value_const = relay.const(off_value)\n        out = relay.one_hot(indices, on_value_const, off_value_const, depth_var, axis, dtype)\n        func = relay.Function([indices, depth_var], out)\n        indices_np = np.random.randint(0, depth, size=indices_shape).astype(\"int32\")\n        out_np = tvm.topi.testing.one_hot(indices_np, on_value, off_value, depth, axis, dtype)\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            out_relay = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate()(indices_np, np.array(depth).astype(\"int32\"))\n            tvm.testing.assert_allclose(out_relay.numpy(), out_np)\n\n    _verify((3,), 3, 1, 0, -1, \"int32\")\n    _verify((3,), 3, 1.0, 0.0, -1, \"float32\")\n    _verify((2, 2), 5, 2, -2, 0, \"int32\")\n    _verify((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    _verify((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n    _verify((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level2.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level2 dynamic operator test cases.\n\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm import te\nfrom tvm.relay.testing import enabled_targets\nimport random\nfrom test_dynamic_op_level3 import verify_func\nimport tvm.topi.testing\nfrom tvm.relay.testing import run_infer_type\n\nexecutor_kind = tvm.testing.parameter(\"debug\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_upsampling_run(executor_kind):\n    def verify_upsampling(dshape, scale_h, scale_w, layout, method, align_corners=False):\n\n        if layout == \"NCHW\":\n            (n, c, h, w) = dshape\n            x_data = np.random.uniform(size=(n, c, h, w)).astype(\"float32\")\n\n        elif layout == \"NHWC\":\n            (n, h, w, c) = dshape\n            x_data = np.random.uniform(size=(n, h, w, c)).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.resize2d_python(\n            x_data,\n            (scale_h, scale_w),\n            layout,\n            method[2:] if method[0:2] == \"bi\" else method,\n            \"align_corners\" if align_corners else \"asymmetric\",\n        )\n        x = relay.Var(\"x\", relay.TensorType(dshape, \"float32\"))\n        scale_h_var = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n        scale_w_var = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n\n        z = relay.nn.upsampling(\n            x, scale_h_var, scale_w_var, method=method, layout=layout, align_corners=align_corners\n        )\n        zz = run_infer_type(z)\n        func = relay.Function([x, scale_h_var, scale_w_var], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate()(\n                x_data, np.array(scale_h).astype(\"float32\"), np.array(scale_w).astype(\"float32\")\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4, atol=1e-6)\n\n    verify_upsampling((1, 16, 32, 32), 3, 2.0, \"NCHW\", \"nearest_neighbor\")\n    verify_upsampling((1, 16, 32, 32), 5, 2.0, \"NCHW\", \"bilinear\", True)\n    verify_upsampling((1, 16, 32, 32), 2.0, 6, \"NHWC\", \"nearest_neighbor\")\n    verify_upsampling((1, 16, 32, 32), 2.0, 2.0, \"NHWC\", \"bilinear\", True)\n\n\n# tests upsampling type inference with scale_h passed in as a constant and scale_w as a variable\n@tvm.testing.uses_gpu\ndef test_dyn_upsampling_infer_type_const():\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n\n    data = relay.var(\"data\", relay.TensorType((n, c, h, w), \"int8\"))\n    scale_w = relay.Var(\"scale_w\", relay.TensorType((), \"float32\"))\n\n    z = relay.nn.upsampling(data, 2.0, scale_w)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, relay.Any(), relay.Any()), \"int8\")\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_upsampling3d_run(executor_kind):\n    def verify_upsampling3d(\n        dshape, scale_d, scale_h, scale_w, layout, method, coord_trans=\"asymmetric\"\n    ):\n\n        if layout == \"NCDHW\":\n            (n, c, d, h, w) = dshape\n            x_data = np.random.uniform(size=(n, c, d, h, w)).astype(\"float32\")\n\n        elif layout == \"NDHWC\":\n            (n, d, h, w, c) = dshape\n            x_data = np.random.uniform(size=(n, d, h, w, c)).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.resize3d_python(\n            x_data,\n            (scale_d, scale_h, scale_w),\n            layout,\n            method[3:] if method[0:3] == \"tri\" else method,\n            coord_trans,\n        )\n\n        x = relay.Var(\"x\", relay.TensorType(dshape, \"float32\"))\n        scale_d_var = relay.var(\"scale_d\", relay.TensorType((), \"float32\"))\n        scale_h_var = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n        scale_w_var = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n\n        z = relay.nn.upsampling3d(\n            x,\n            scale_d_var,\n            scale_h_var,\n            scale_w_var,\n            method=method,\n            layout=layout,\n            coordinate_transformation_mode=coord_trans,\n        )\n        zz = run_infer_type(z)\n        func = relay.Function([x, scale_d_var, scale_h_var, scale_w_var], z)\n\n        for target, dev in enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate()(\n                x_data,\n                np.array(scale_d).astype(\"float32\"),\n                np.array(scale_h).astype(\"float32\"),\n                np.array(scale_w).astype(\"float32\"),\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4, atol=1e-6)\n\n    verify_upsampling3d((1, 1, 1, 1, 1), 2, 3, 4, \"NCDHW\", \"nearest_neighbor\")\n    verify_upsampling3d((1, 8, 16, 16, 16), 2.0, 3.0, 4.0, \"NCDHW\", \"nearest_neighbor\")\n    verify_upsampling3d((1, 8, 16, 16, 16), 2.0, 5.0, 1.0, \"NCDHW\", \"trilinear\", \"align_corners\")\n    verify_upsampling3d((1, 20, 3, 4, 16), 2.0, 2.0, 2.0, \"NDHWC\", \"nearest_neighbor\")\n    verify_upsampling3d((1, 8, 4, 16, 15), 2.0, 2.0, 2.0, \"NDHWC\", \"trilinear\", \"align_corners\")\n\n\n# tests upsampling type inference with scale_h passed in as a constant and scale_w as a variable\ndef test_dyn_upsampling3d_infer_type_const():\n    n, c, d, h, w = (\n        te.size_var(\"n\"),\n        te.size_var(\"c\"),\n        te.size_var(\"d\"),\n        te.size_var(\"h\"),\n        te.size_var(\"w\"),\n    )\n\n    data = relay.var(\"data\", relay.TensorType((n, c, d, h, w), \"int8\"))\n    scale_d = relay.Var(\"scale_h\", relay.TensorType((), \"float32\"))\n    scale_w = relay.Var(\"scale_w\", relay.TensorType((), \"float32\"))\n\n    z = relay.nn.upsampling3d(data, scale_d, 2.0, scale_w, layout=\"NCDHW\", method=\"trilinear\")\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType(\n        (n, c, relay.Any(), relay.Any(), relay.Any()), \"int8\"\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_pad(executor_kind):\n    def verify_pad(dshape, pad_width, pad_val, dtype):\n        x = relay.var(\"x\", relay.TensorType(dshape, dtype))\n        ndim = len(dshape)\n        pad_width_var = relay.var(\"pad_width_var\", relay.TensorType((ndim, 2), \"int64\"))\n        pad_val_var = relay.var(\"pad_val_var\", relay.TensorType((), dtype))\n        y = relay.nn.pad(x, pad_width_var, pad_val_var)\n        yy = run_infer_type(y)\n\n        assert yy.checked_type == relay.ty.TensorType((relay.Any(),) * ndim, dtype)\n        func = relay.Function([x, pad_width_var, pad_val_var], y)\n        data = np.random.uniform(size=dshape).astype(dtype)\n        ref_res = np.pad(data, pad_width, \"constant\", constant_values=(((pad_val,) * 2),) * ndim)\n        pad_width = np.array(pad_width).astype(\"int64\")\n\n        verify_func(\n            executor_kind, func, [data, pad_width, np.array(pad_val).astype(dtype)], ref_res\n        )\n\n    def verify_pad_default_fill(dshape, pad_width, dtype):\n        x = relay.var(\"x\", relay.TensorType(dshape, dtype))\n        ndim = len(dshape)\n        pad_width_var = relay.var(\"pad_width_var\", relay.TensorType((ndim, 2), \"int64\"))\n        y = relay.nn.pad(x, pad_width_var)\n        yy = run_infer_type(y)\n\n        assert yy.checked_type == relay.ty.TensorType((relay.Any(),) * ndim, dtype)\n        func = relay.Function([x, pad_width_var], y)\n        data = np.random.uniform(size=dshape).astype(dtype)\n        ref_res = np.pad(data, pad_width)\n        pad_width = np.array(pad_width).astype(\"int64\")\n\n        verify_func(executor_kind, func, [data, pad_width], ref_res)\n\n    verify_pad((4, 10, 7, 7), ((1, 1), (2, 2), (3, 3), (4, 4)), 2.0, \"int32\")\n    verify_pad((2, 7), ((1, 4), (2, 2)), 4.0, \"float64\")\n    verify_pad_default_fill((4, 10, 7, 7), ((1, 1), (2, 2), (3, 3), (4, 4)), \"float64\")\n    verify_pad_default_fill((2, 7), ((1, 4), (2, 2)), \"int32\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level3.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level3 operator test cases.\n\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay, te\nfrom tvm.relay.testing import check_grad, run_infer_type\n\nexecutor_kind = tvm.testing.parameter(\"debug\", \"vm\")\n\n\ndef verify_func(executor_kind, func, data, ref_res, target_device=tvm.testing.enabled_targets()):\n    assert isinstance(data, list)\n    for target, dev in target_device:\n        mod = tvm.ir.IRModule.from_expr(func)\n        op_res = relay.create_executor(\n            executor_kind, mod=mod, device=dev, target=target\n        ).evaluate()(*data)\n        if isinstance(op_res, tvm.runtime.container.ADT):\n            assert len(op_res) == len(\n                ref_res\n            ), \"Outputs from TVM and Python implementation must be equal \"\n            for op_result, ref_result in zip(op_res, ref_res):\n                tvm.testing.assert_allclose(op_result.numpy(), ref_result, rtol=1e-5)\n        else:\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n        relay.backend.te_compiler.get().clear()\n\n\ndef check_on_vm(target, dev, args, expected_result, mod):\n    \"\"\"\n    Check that evaluating `expr` applied to the arguments produces\n    `result` on Relay VM.\n    \"\"\"\n    rts_result = relay.create_executor(\"vm\", device=dev, target=target, mod=mod).evaluate()(*args)\n    tvm.testing.assert_allclose(expected_result, rts_result.numpy())\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_reshape(executor_kind):\n    def verify_reshape(shape, newshape, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType((len(newshape),), \"int64\"))\n        z = relay.reshape(x, y)\n\n        func = relay.Function([x, y], z)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        x_data = np.ones(shape).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n        check_grad(\n            run_infer_type(func),\n            inputs=[x_data, np.array(newshape).astype(\"int64\")],\n            test_inputs=[x_data],\n            eps=1e-3,\n        )\n        verify_func(executor_kind, func, [x_data, np.array(newshape).astype(\"int64\")], ref_res)\n\n    verify_reshape((2, 3, 4), (8, 3), (8, 3))\n    verify_reshape((4, 7), (2, 7, 2), (2, 7, 2))\n    verify_reshape((2, 3, 4), (4, 0, 2), (4, 3, 2))\n    verify_reshape((2, 3, 4), (2, 0, 0), (2, 3, 4))\n    verify_reshape((2, 3, 4), (0, -1), (2, 12))\n    verify_reshape((2, 3, 4), (-1, 0), (8, 3))\n    verify_reshape((2, 3, 4), (-3, 4), (6, 4))\n    verify_reshape((2, 3, 4, 5), (-3, -3), (6, 20))\n    verify_reshape((2, 3, 4), (0, -3), (2, 12))\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_shape_reshape(executor_kind):\n    def verify_reshape(shape, newshape, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(newshape, \"float32\"))\n        z = relay.reshape(x, relay.shape_of(y))\n\n        func = relay.Function([x, y], z)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=newshape).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n        check_grad(run_infer_type(func), inputs=[x_data, y_data], eps=1e-3)\n        verify_func(executor_kind, func, [x_data, y_data], ref_res)\n\n    verify_reshape((2, 3, 4), (8, 3), (8, 3))\n    verify_reshape((4, 7), (2, 7, 2), (2, 7, 2))\n\n\ndef test_squeeze(executor_kind):\n    def verify_squeeze(shape, dtype, axis):\n        x = relay.var(\"x\", relay.TensorType(shape, dtype))\n        assert axis is not None\n        np_axis = tuple(axis)\n        axis = relay.var(\"axis\", relay.TensorType([len(axis)], \"int64\"))\n        squeeze = relay.squeeze(x, axis=axis)\n        func = relay.Function([x, axis], squeeze)\n        x_data = np.random.random_sample(shape).astype(dtype)\n        ref_res = np.squeeze(x_data, axis=np_axis)\n        verify_func(executor_kind, func, [x_data, np.array(np_axis).astype(\"int64\")], ref_res)\n\n    verify_squeeze((1, 3, 1), \"float32\", [0])\n    verify_squeeze((1, 2, 1, 2, 1), \"float32\", [0, 2])\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_expand_dims(executor_kind):\n    def verify_expand_dims(\n        dshape, dtype, oshape, axis, num_newaxis, target_device=tvm.testing.enabled_targets()\n    ):\n        # Use 1 to avoid issues with invalid buffer sizes\n        x = relay.Var(\"x\", relay.TensorType(dshape, dtype))\n        y = relay.var(\"axis\", shape=[], dtype=\"int64\")\n        z = relay.expand_dims(x, axis=y, num_newaxis=num_newaxis)\n        func = relay.Function([x, y], z)\n\n        data_np = np.random.uniform(size=dshape).astype(dtype)\n        axis_np = np.array(axis).astype(\"int64\")\n        ref_res = data_np.reshape(oshape)\n        verify_func(executor_kind, func, [data_np, axis_np], ref_res, target_device=target_device)\n\n    for dtype in [\"float16\", \"float32\"]:\n        verify_expand_dims((2, 2), dtype, (2, 2, 1), 2, 1)\n        verify_expand_dims((2, 2), dtype, (2, 1, 2), 1, 1)\n        verify_expand_dims((2, 2), dtype, (1, 2, 2), 0, 1)\n\n        # TODO (AndrewZhaoLuo): investigate why runtimes in non-llvm are extremely slow\n        # for multiple new axis\n        llvm_target_only = [x for x in tvm.testing.enabled_targets() if \"llvm\" in x]\n        verify_expand_dims((2, 2), dtype, (2, 2, 1, 1), 2, 2, target_device=llvm_target_only)\n        verify_expand_dims((2, 2), dtype, (2, 1, 1, 1, 2), 1, 3, target_device=llvm_target_only)\n        verify_expand_dims((2, 2), dtype, (1, 1, 1, 1, 2, 2), 0, 4, target_device=llvm_target_only)\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_tile(executor_kind):\n    def verify_tile(dshape, reps):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        r = relay.var(\"reps\", relay.TensorType((len(reps),), \"float32\"))\n        z = relay.tile(x, r)\n\n        func = relay.Function([x, r], z)\n        x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n        ref_res = np.tile(x_data, reps=reps)\n        reps_data = np.array(reps).astype(\"float32\")\n        verify_func(executor_kind, func, [x_data, np.array(reps).astype(\"float32\")], ref_res)\n\n    verify_tile((2, 3, 4), (3, 2, 1))\n    verify_tile((2, 3, 4), (1, 2))\n    verify_tile((2, 3), (3, 2, 1))\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_zeros_ones(executor_kind):\n    def verify_zeros_ones(shape, dtype):\n        for op, ref in [(relay.zeros, np.zeros), (relay.ones, np.ones)]:\n            rank = len(shape)\n            dyn_shape = relay.Var(\"shape\", relay.ty.TensorType((rank,), \"int64\"))\n            y = op(dyn_shape, dtype)\n            yy = run_infer_type(y)\n            assert yy.checked_type == relay.ty.TensorType((relay.Any(),) * rank, dtype)\n\n            func = relay.Function([dyn_shape], y)\n            ref_res = ref(shape, dtype)\n            verify_func(\n                executor_kind, func, [np.array(shape).astype(\"int64\")], ref_res.astype(\"int64\")\n            )\n\n    verify_zeros_ones((1, 3), \"int64\")\n    verify_zeros_ones((8, 9, 1, 2), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_full(executor_kind):\n    def verify_full(fill_value, src_shape, dtype):\n        x = relay.var(\"x\", relay.scalar_type(dtype))\n        rank = len(src_shape)\n        dyn_src_shape = relay.var(\"dyn_scr_shape\", relay.ty.TensorType((rank,), \"int64\"))\n        z = relay.full(x, dyn_src_shape, dtype)\n        func = relay.Function([x, dyn_src_shape], z)\n        ref_res = np.full(src_shape, fill_value).astype(dtype)\n\n        verify_func(\n            executor_kind,\n            func,\n            [np.array(fill_value).astype(dtype), np.array(src_shape).astype(\"int64\")],\n            ref_res,\n        )\n\n    verify_full(4, (1, 3, 4, 4), \"int32\")\n    verify_full(4, (1, 3, 4, 4), \"int64\")\n    verify_full(4.0, (2, 50), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_sparse_to_dense(executor_kind):\n    def verify_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape, xpected):\n        sparse_indices_data = np.array(sparse_indices)\n        sparse_values_data = np.array(sparse_values)\n        default_value_data = np.array(default_value)\n        output_shape_data = np.array(output_shape)\n\n        a = relay.var(\n            \"a\", relay.TensorType(sparse_indices_data.shape, str(sparse_indices_data.dtype))\n        )\n        b = relay.var(\n            \"b\", relay.TensorType(sparse_values_data.shape, str(sparse_values_data.dtype))\n        )\n        output_shape_var = relay.var(\n            \"output_shape\", relay.TensorType(output_shape_data.shape, str(output_shape_data.dtype))\n        )\n        if default_value is None:\n            args = [a, b, output_shape_var]\n            d = relay.sparse_to_dense(a, output_shape_var, b)\n        else:\n            c = relay.var(\n                \"c\", relay.TensorType(default_value_data.shape, str(default_value_data.dtype))\n            )\n            args = [a, b, c, output_shape_var]\n            d = relay.sparse_to_dense(a, output_shape_var, b, c)\n\n        zz = run_infer_type(d)\n        assert len(zz.checked_type.shape) == len(output_shape)\n\n        func = relay.Function(args, d)\n\n        if default_value is None:\n            arguments = [sparse_indices_data, sparse_values_data, output_shape_data]\n        else:\n            arguments = [\n                sparse_indices_data,\n                sparse_values_data,\n                default_value_data,\n                output_shape_data,\n            ]\n\n        verify_func(executor_kind, func, arguments, xpected)\n\n    verify_sparse_to_dense(1, 3, 0, [5], [0, 3, 0, 0, 0])  # scalar\n    verify_sparse_to_dense([0, 1, 4], [3, 3, 3], 0, [5], [3, 3, 0, 0, 3])  # vector\n    verify_sparse_to_dense(\n        [[0, 0], [1, 2]], [1, 2], 0, [3, 4], [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]\n    )  # nXd\n    verify_sparse_to_dense(\n        [[0, 0, 0], [1, 2, 3]],\n        [1, 2],\n        4,\n        [2, 3, 4],\n        [[[1, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]], [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 2]]],\n    )  # nXd\n    verify_sparse_to_dense(\n        [0, 1, 4], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1]\n    )  # floats\n    # default value not specified\n    verify_sparse_to_dense(1, 3, None, [5], [0, 3, 0, 0, 0])\n\n\n@pytest.mark.parametrize(\n    \"sparse_indices, sparse_values, dense_shape, default_value\",\n    [\n        (\n            np.array([[0, 1], [0, 3], [2, 0], [3, 1]], dtype=np.int64),\n            np.array([1, 2, 3, 4], dtype=np.int64),\n            np.array([5, 6], dtype=np.int64),\n            np.array([10], dtype=np.int64),\n        ),\n        (\n            np.array([[1, 1, 1], [1, 3, 1], [2, 0, 5], [3, 1, 6]], dtype=np.int64),\n            np.array([1, 2, 3, 4], dtype=np.int64),\n            np.array([7, 7, 7], dtype=np.int64),\n            np.array([5], dtype=np.int64),\n        ),\n        (\n            np.array([[1], [2]], dtype=np.int64),\n            np.array([7, 8], dtype=np.int64),\n            np.array([5], dtype=np.int64),\n            np.array([4], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 1), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([5], dtype=np.int64),\n            np.array([4], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 3), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([9, 3, 7], dtype=np.int64),\n            np.array([100], dtype=np.int64),\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"dtype\", [np.int64, np.int32])\n@pytest.mark.parametrize(\"use_dyn\", [True, False])\ndef test_sparse_fill_empty_rows(\n    sparse_indices, sparse_values, dense_shape, default_value, dtype, use_dyn, executor_kind\n):\n    def ref_sparse_fill_empty_rows(\n        sparse_indices: np.ndarray,\n        sparse_values: np.ndarray,\n        dense_shape: np.ndarray,\n        default_value: np.ndarray,\n    ) -> None:\n        \"\"\"\n        This function calculates the expected output of sparse_fill_empty_rows operator given the\n        inputs.\n        \"\"\"\n\n        def check_add_rows(current_idx, limit_idx):\n            while current_idx < limit_idx:\n                new_sparse_indices.append([current_idx] + [0] * (num_cols - 1))\n                new_sparse_values.append(default_value[0])\n                empty_row_indicator[current_idx] = True\n                current_idx += 1\n\n            return current_idx\n\n        current_idx = 0\n        new_sparse_indices = []\n        new_sparse_values = []\n        empty_row_indicator = [False for _ in range(dense_shape[0])]\n        num_cols = sparse_indices.shape[1]\n        for sparse_row, sparse_value in zip(sparse_indices, sparse_values):\n            limit_idx = sparse_row[0]\n            current_idx = check_add_rows(current_idx, limit_idx)\n            new_sparse_indices.append(list(sparse_row))\n            new_sparse_values.append(sparse_value)\n            current_idx = limit_idx + 1\n\n        check_add_rows(current_idx, dense_shape[0])\n        return new_sparse_indices, new_sparse_values, empty_row_indicator\n\n    def verify_sparse_fill_empty_rows(\n        sparse_indices_np: np.ndarray,\n        sparse_values_np: np.ndarray,\n        dense_shape_np: np.ndarray,\n        default_value_np: np.ndarray,\n    ) -> None:\n        \"\"\"\n        This function verifies the relay output of sparse_fill_empty_rows with its expected output.\n        \"\"\"\n        if use_dyn:\n            sparse_indices = relay.var(\n                \"sparse_indices\",\n                shape=[relay.Any(), relay.Any()],\n                dtype=str(sparse_indices_np.dtype),\n            )\n            sparse_values = relay.var(\n                \"sparse_values\",\n                shape=[relay.Any()],\n                dtype=str(sparse_values_np.dtype),\n            )\n            dense_shape = relay.var(\n                \"dense_shape\",\n                shape=[relay.Any()],\n                dtype=str(dense_shape_np.dtype),\n            )\n            default_value = relay.var(\n                \"default_value\",\n                shape=[relay.Any()],\n                dtype=str(default_value_np.dtype),\n            )\n        else:\n            sparse_indices = relay.var(\n                \"sparse_indices\",\n                relay.TensorType(sparse_indices_np.shape, str(sparse_indices_np.dtype)),\n            )\n            sparse_values = relay.var(\n                \"sparse_values\",\n                relay.TensorType(sparse_values_np.shape, str(sparse_values_np.dtype)),\n            )\n            dense_shape = relay.var(\n                \"dense_shape\",\n                relay.TensorType(dense_shape_np.shape, str(dense_shape_np.dtype)),\n            )\n            default_value = relay.var(\n                \"default_value\",\n                relay.TensorType(default_value_np.shape, str(default_value_np.dtype)),\n            )\n        z = relay.sparse_fill_empty_rows(sparse_indices, sparse_values, dense_shape, default_value)\n        func = relay.Function([sparse_indices, sparse_values, dense_shape, default_value], z)\n        ref_res = ref_sparse_fill_empty_rows(\n            sparse_indices_np,\n            sparse_values_np,\n            dense_shape_np,\n            default_value_np,\n        )\n        (\n            new_sparse_indices_infer_type,\n            new_sparse_values_infer_type,\n            empty_row_indicator_infer_type,\n        ) = run_infer_type(z)\n\n        assert new_sparse_indices_infer_type.checked_type.dtype == sparse_indices_np.dtype\n        assert new_sparse_values_infer_type.checked_type.dtype == sparse_indices_np.dtype\n        assert empty_row_indicator_infer_type.checked_type.dtype == \"bool\"\n\n        verify_func(\n            executor_kind,\n            func,\n            [sparse_indices_np, sparse_values_np, dense_shape_np, default_value_np],\n            ref_res,\n            [(\"llvm\", tvm.cpu())],\n        )\n\n    verify_sparse_fill_empty_rows(\n        sparse_indices.astype(dtype),\n        sparse_values.astype(dtype),\n        dense_shape.astype(dtype),\n        default_value.astype(dtype),\n    )\n\n\ndef test_dyn_copy():\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n    mod = tvm.parser.fromtext(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(?, 3), int64]) -> Tensor[(?, 3), int64] {\n          copy(%x)\n        }\n        \"\"\"\n    )\n    x_data = np.random.rand(15, 3).astype(\"int64\")\n    expected = x_data\n    check_on_vm(target, dev, [x_data], expected, mod)\n\n\ndef test_dyn_copy_scalar():\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n    mod = tvm.parser.fromtext(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: int32, %y: Tensor[(?), int32]) -> Tensor[(?), int32] {\n          %0 = copy(%x);\n          %1 = expand_dims(%0, axis=0);\n          %2 = (%y, %1);\n          concatenate(%2)\n        }\n        \"\"\"\n    )\n    x_data = 3\n    y_data = np.random.rand(7).astype(\"int32\")\n    expected = np.concatenate((y_data, np.expand_dims(x_data, axis=0)))\n    check_on_vm(target, dev, [x_data, y_data], expected, mod)\n\n\ndef test_dyn_cast():\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n    mod = tvm.parser.fromtext(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x: Tensor[(?, 3), int64]) -> Tensor[(?, 3), int32] {\n          cast(%x, dtype=\"int32\")\n        }\n        \"\"\"\n    )\n    x_data = np.random.rand(15, 3).astype(\"int64\")\n    expected = x_data.astype(\"int32\")\n    check_on_vm(target, dev, [x_data], expected, mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level4.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\nimport tvm.topi.testing\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_strided_slice():\n    def verify(dshape, begin, end, strides, slice_mode=\"end\", test_ref=True, dtype=\"int32\"):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        ndim = len(dshape)\n        slice_dim = len(begin)\n        begin = begin if begin else [0] * ndim\n        end = end if end else list(dshape)[:slice_dim]\n        if strides:\n            if len(strides) == 1:\n                strides = strides * slice_dim\n        else:\n            strides = [1] * slice_dim\n\n        num_static_axes = len(dshape) - len(begin)\n\n        # target numpy result\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        ref_res = tvm.topi.testing.strided_slice_python(x_data, begin, end, strides, slice_mode)\n        data = [x_data, np.array(begin, dtype=dtype), np.array(end, dtype=dtype)]\n\n        begin = relay.var(\"begin\", shape=[len(begin)], dtype=dtype)\n        end = relay.var(\"end\", shape=[len(end)], dtype=dtype)\n        inputs = [x, begin, end]\n        if strides:\n            data.append(np.array(strides, dtype=dtype))\n            strides = relay.var(\"strides\", shape=[len(strides)], dtype=dtype)\n            inputs.append(strides)\n            z = relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=slice_mode)\n        else:\n            z = relay.strided_slice(x, begin=begin, end=end, slice_mode=slice_mode)\n        func = relay.Function(inputs, z)\n\n        func = run_infer_type(func)\n\n        if num_static_axes > 0:\n            oshape = run_infer_type(z).checked_type.shape\n            assert tuple(oshape[-num_static_axes:]) == dshape[-num_static_axes:]\n\n        if not test_ref:\n            return\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(\n                *data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    verify(\n        (1, 224, 224, 3),\n        [0, 20, 20, 0],\n        [1, 140, 140, 3],\n        [1, 1, 1, 1],\n        dtype=\"int64\",\n    )\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], dtype=\"int16\")\n    verify((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None)\n    verify((3, 4, 3), [1, 1, 0], [4, 1000, 3], None)\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 4], None)\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None)\n    verify((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1])\n    verify((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1])\n    verify((20, 10, 5), [20, 10, 4], [0, 0, 1], [-1, -3, -2])\n    verify((3, 4, 3), [1, 0, 0], [3, -1, 3], [1, 1, 1], slice_mode=\"size\", test_ref=False)\n    verify((3, 4, 3), [1, 0, 0], [-1, 2, 3], [1, 1, 1], slice_mode=\"size\", test_ref=True)\n\n    # Slicing along first few axes, where the rest of axes remain static\n    verify((3, 4, 3), [0], [2], None)\n    verify((3, 4, 3), [1], [4], [2])\n    verify((3, 4, 3), [1, 0], [4, 2], [2, 1])\n\n\nif __name__ == \"__main__\":\n    test_dynamic_strided_slice()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level5.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level5 operator test cases.\n\"\"\"\nimport math\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\nimport tvm.topi.testing\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"debug\", \"vm\")\n\n\ndef test_resize2d_infer_type():\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"int8\"))\n    size = relay.var(\"size\", relay.TensorType((2,), \"int8\"))\n    z = relay.image.resize2d(x, size)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, relay.Any(), relay.Any()), \"int8\")\n\n\n@tvm.testing.uses_gpu\ndef test_resize2d(executor_kind):\n    def verify_resize2d(dshape, scale, method, layout):\n        if layout == \"NHWC\":\n            size = (dshape[1] * scale, dshape[2] * scale)\n        else:\n            size = (dshape[2] * scale, dshape[3] * scale)\n        size = np.array(size).astype(\"int64\")\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        size_var = relay.var(\"size\", relay.TensorType((2,), \"int64\"))\n\n        coord_trans = \"asymmetric\" if method == \"nearest_neighbor\" else \"align_corners\"\n        z = relay.image.resize2d(\n            x, size_var, None, layout, method, coordinate_transformation_mode=coord_trans\n        )\n\n        zz = run_infer_type(z)\n        func = relay.Function([x, size_var], z)\n\n        ref_res = tvm.topi.testing.resize2d_python(\n            x_data, (scale, scale), layout, method, coord_trans\n        )\n\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate()(x_data, size)\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4, atol=1e-6)\n\n    for method in [\"linear\", \"nearest_neighbor\"]:\n        for layout in [\"NCHW\", \"NHWC\"]:\n            verify_resize2d((1, 4, 4, 4), 2, method, layout)\n            verify_resize2d((2, 8, 17, 20), 7, method, layout)\n\n\nif __name__ == \"__main__\":\n    test_resize2d_infer_type()\n    test_resize2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/dyn/test_dynamic_op_level6.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level6 operator test cases.\n\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"debug\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_topk(executor_kind):\n    def verify_topk(k, axis, ret_type, is_ascend, dtype):\n        shape = (20, 100)\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        k_var = relay.var(\"x\", relay.TensorType((1,), \"float32\"))\n        out = relay.topk(x, k_var, axis, ret_type, is_ascend, dtype)\n        if isinstance(out, relay.expr.TupleWrapper):\n            out = out.astuple()\n        func = relay.Function([x, k_var], out)\n\n        np_data = np.random.uniform(size=shape).astype(\"float32\")\n        if is_ascend:\n            np_indices = np.argsort(np_data, axis=axis)\n        else:\n            np_indices = np.argsort(-np_data, axis=axis)\n        kk = k if k >= 1 else shape[axis]\n        if axis == 0:\n            np_indices = np_indices[:kk, :]\n            np_values = np.zeros(np_indices.shape).astype(\"float32\")\n            for i in range(shape[1]):\n                np_values[:, i] = np_data[np_indices[:, i], i]\n        else:\n            np_indices = np_indices[:, :kk]\n            np_values = np.zeros(np_indices.shape).astype(\"float32\")\n            for i in range(shape[0]):\n                np_values[i, :] = np_data[i, np_indices[i, :]]\n        np_indices = np_indices.astype(dtype)\n\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\n                executor_kind, mod=mod, device=dev, target=target\n            ).evaluate()(np_data, np.array([k]).astype(\"float32\"))\n            if ret_type == \"both\":\n                tvm.testing.assert_allclose(op_res[0].numpy(), np_values)\n                tvm.testing.assert_allclose(op_res[1].numpy(), np_indices)\n            elif ret_type == \"values\":\n                tvm.testing.assert_allclose(op_res.numpy(), np_values)\n            else:\n                tvm.testing.assert_allclose(op_res.numpy(), np_indices)\n\n    np.random.seed(0)\n    for k in [0, 1, 5]:\n        for axis in [0, -1, 1]:\n            for ret_type in [\"both\", \"values\", \"indices\"]:\n                verify_topk(k, axis, ret_type, True, \"int64\")\n                verify_topk(k, axis, ret_type, False, \"float32\")\n\n\nif __name__ == \"__main__\":\n    test_dynamic_topk()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/op/annotation/test_annotation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for annotations.\"\"\"\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nimport pytest\n\n\ndef test_on_device_via_string():\n    x = relay.Var(\"x\")\n    call = relay.annotation.on_device(x, \"cuda\")\n    assert isinstance(call, relay.Call)\n    assert len(call.args) == 1\n    assert call.args[0] == x\n    assert call.attrs.virtual_device.device_type_int == 2  # ie kDLCUDA\n    assert call.attrs.virtual_device.virtual_device_id == 0\n    assert call.attrs.virtual_device.target is None\n    assert call.attrs.virtual_device.memory_scope == \"\"\n    assert call.attrs.constrain_body\n    assert not call.attrs.constrain_result\n\n\ndef test_on_device_via_device():\n    x = relay.Var(\"x\")\n    call = relay.annotation.on_device(x, tvm.device(\"cpu\"))\n    assert call.attrs.virtual_device.device_type_int == 1  # ie kDLCPU\n\n\ndef test_on_device_invalid_device():\n    x = relay.Var(\"x\")\n    pytest.raises(ValueError, lambda: relay.annotation.on_device(x, \"bogus\"))\n\n\ndef test_on_device_fixed():\n    x = relay.Var(\"x\")\n    call = relay.annotation.on_device(x, \"cuda\", constrain_result=True)\n    assert call.attrs.virtual_device.device_type_int == 2  # ie kDLCUDA\n    assert call.attrs.constrain_body\n    assert call.attrs.constrain_result\n\n\ndef test_on_device_free():\n    x = relay.Var(\"x\")\n    call = relay.annotation.on_device(x, \"cuda\", constrain_result=False, constrain_body=False)\n    assert call.attrs.virtual_device.device_type_int == -1  # ie kInvalidDeviceType\n    assert not call.attrs.constrain_body\n    assert not call.attrs.constrain_result\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/op/test_tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for tensor helpers.\"\"\"\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nimport pytest\n\n\ndef test_device_copy_via_string():\n    x = relay.var(\"x\")\n    call = relay.op.device_copy(x, \"cuda\", \"cpu\")\n    assert isinstance(call, relay.Call)\n    assert len(call.args) == 1\n    assert call.args[0] == x\n    assert call.attrs.src_virtual_device.device_type_int == 2  # ie kDLCUDA\n    assert call.attrs.src_virtual_device.virtual_device_id == 0\n    assert call.attrs.src_virtual_device.target is None\n    assert call.attrs.src_virtual_device.memory_scope == \"\"\n    assert call.attrs.dst_virtual_device.device_type_int == 1  # ie kDLCPU\n    assert call.attrs.dst_virtual_device.virtual_device_id == 0\n    assert call.attrs.dst_virtual_device.target is None\n    assert call.attrs.dst_virtual_device.memory_scope == \"\"\n\n\ndef test_device_copy_via_device():\n    x = relay.var(\"x\")\n    call = relay.op.device_copy(x, tvm.device(\"cuda\"), tvm.device(\"cpu\"))\n    assert isinstance(call, relay.Call)\n    assert len(call.args) == 1\n    assert call.args[0] == x\n    assert call.attrs.src_virtual_device.device_type_int == 2  # ie kDLCUDA\n    assert call.attrs.dst_virtual_device.device_type_int == 1  # ie kDLCPU\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/test_conv2d_nchw_texture.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport re\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import utils\nfrom utils.adreno_utils import gpu_preprocess, build_run_compare\nimport pytest\n\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_64x35x35_96x64x3x3_nopad(target, dtype):\n    input_shape = (1, 32, 42, 42)\n    filter_shape = (96, 32, 3, 3)\n    bias_shape = (1, 96, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=96,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_64x35x35_96x64x3x3_nopad_pass(target, dtype):\n    input_shape = (1, 32, 40, 40)\n    filter_shape = (96, 32, 2, 2)\n    bias_shape = (1, 96, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=96,\n        kernel_size=(2, 2),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_35_35_strides(target, dtype):\n    input_shape = (1, 48, 35, 35)\n    filter_shape = (64, 48, 5, 5)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[2, 2, 2, 2],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(5, 5),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_resnet50_v2_nchw_3c(target, dtype):\n    input_shape = (1, 3, 224, 224)\n    filter_shape = (64, 3, 7, 7)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[3, 3, 3, 3],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(7, 7),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_nchw_3c(target, dtype):\n    input_shape = (1, 3, 299, 299)\n    filter_shape = (64, 3, 3, 3)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_1x1_16c16spatial(target, dtype):\n    input_shape = (1, 16, 256, 256)\n    filter_shape = (32, 16, 4, 4)\n    bias_shape = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_4x4_16c16pad(target, dtype):\n    input_shape = (1, 32, 256, 256)\n    filter_shape = (32, 32, 4, 4)\n    bias_shape = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[3, 3, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_4x4x4_16c16pad(target, dtype):\n    input_shape = (1, 32, 256, 256)\n    filter_shape = (4, 32, 4, 4)\n    bias_shape = (1, 4, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[3, 3, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_yolov3_v2_nchw_3c(target, dtype):\n    input_shape = (1, 1024, 13, 13)\n    filter_shape = (255, 1024, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=255,\n        kernel_size=(1, 1),\n    )\n\n    mod = relay.Function([A, B], conv)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    params = {\n        \"weight\": tvm.nd.array(filter_data),\n    }\n\n    build_run_compare(mod, params, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_vgg16_winograd_4d(target, dtype):\n    input_shape = (1, 512, 28, 28)\n    filter_shape = (512, 512, 3, 3)\n    bias_shape = (1, 512, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        channels=512,\n        kernel_size=[3, 3],\n        out_dtype=dtype,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256\", \"conv2d_nchw_winograd.image2d\", [[\"TENSOR\", [1, 512, 28, 28], \"{dtype}\"], [\"TENSOR\", [512, 512, 3, 3], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 1591, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 4], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 2]], [\"tile_rc\", \"sp\", [-1, 8]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_winograd_conv(target, dtype):\n    input_shape = (1, 4, 3, 3)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    filter_shape3 = (8, 4, 3, 3)\n    bias_shape3 = (8,)\n    B3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n    D = relay.nn.conv2d(\n        A, B3, padding=[1, 1, 1, 1], channels=8, kernel_size=[3, 3], out_dtype=dtype\n    )\n\n    filter_shape4 = (8, 8, 3, 3)\n    bias_shape4 = (8,)\n    B4 = relay.var(\"weight4\", shape=filter_shape4, dtype=dtype)\n    D = relay.nn.conv2d(\n        D, B4, padding=[1, 1, 1, 1], channels=8, kernel_size=[3, 3], out_dtype=dtype\n    )\n    mod = relay.Function([A, B3, B4], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    bias_data3 = np.zeros(bias_shape3).astype(dtype)\n    filter_data4 = np.zeros(filter_shape4).astype(dtype)\n    bias_data4 = np.zeros(bias_shape4).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    initializer(\"bias\", bias_data3)\n    initializer(\"weight\", filter_data4)\n    initializer(\"bias\", bias_data4)\n    params1 = {\n        \"weight3\": tvm.nd.array(filter_data3),\n        \"weight4\": tvm.nd.array(filter_data4),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256\", \"conv2d_nchw_winograd.image2d\", [[\"TENSOR\", [1, 4, 3, 3], \"{dtype}\"], [\"TENSOR\", [8, 4, 3, 3], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 1591, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 4], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 2]], [\"tile_rc\", \"sp\", [-1, 8]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_residual_block(target, dtype):\n    \"\"\"\n    - some kind of residual block followed by convolution to have texture after residual block\n    - scalar data type verification which should be mapped to global memory scope\n        layout_transform (NCHW->NCHW4c)\n                  |                      <- buffer\n                conv2d (1)                  <- to get textures as output\n               /         \\\n            conv2d (2)    |\n                 \\       /\n                    add                     <- add should be fused into conv2d (2)\n                multiply to scalar          <- buffer to the input of multiply scalar value\n                    relu\n                     |                      <- texture in intermediate tensor\n                  conv2d (3)\n                   relu\n                     |                      <- buffer\n               layout_transform (NCHW4c->NCHW)\n    \"\"\"\n    input_shape = (1, 32, 40, 40)\n    filter_shape1 = (32, 32, 2, 2)\n    filter_shape2 = (32, 32, 1, 1)\n    filter_shape3 = (32, 32, 2, 2)\n    bias_shape1 = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    B1 = relay.var(\"bias1\", shape=bias_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    W3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n\n    conv1 = relay.nn.conv2d(\n        A,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    D = relay.op.add(conv1, B1)\n    D = relay.op.nn.relu(D)\n\n    conv2 = relay.nn.conv2d(\n        D,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n    D = relay.op.add(conv2, D)\n    D = D * relay.const(0.15, dtype)\n    D = relay.op.nn.relu(D)\n\n    conv3 = relay.nn.conv2d(\n        D,\n        W3,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    D = relay.op.nn.relu(conv3)\n\n    mod = relay.Function([A, W1, B1, W2, W3], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    bias_data1 = np.zeros(bias_shape1).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"bias\", bias_data1)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    initializer(\"weight\", filter_data2)\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    params1 = {\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"bias1\": tvm.nd.array(bias_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n        \"weight3\": tvm.nd.array(filter_data3),\n    }\n    if dtype == \"float16\":\n        static_memory_scope = [\n            \"global\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"global.texture-weight\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"global\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"\",\n            \"\",\n        ]\n    else:\n        static_memory_scope = [\n            \"global\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"global.texture-weight\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"global.texture\",\n            \"global.texture-weight\",\n            \"\",\n            \"\",\n        ]\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_concat(target, dtype):\n    \"\"\"\n        layout_transform (NCHW->NCHW4c)\n                  |                      <- buffer\n                conv2d (1)               <- to get textures as output\n               /         \\\n            conv2d (2)    conv2d (3)\n                 \\       /               <- concat does not support textures, there we should have buffers\n                concatenation\n                     |                   <- buffer\n               layout_transform (NCHW4c->NCHW)\n    \"\"\"\n    input_shape = (1, 32, 40, 40)\n    filter_shape1 = (96, 32, 2, 2)\n    filter_shape2 = (32, 96, 2, 2)\n    filter_shape3 = (5, 96, 2, 2)\n    bias_shape1 = (1, 96, 1, 1)\n    bias_shape2 = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    B1 = relay.var(\"bias1\", shape=bias_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    W3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n    B2 = relay.var(\"bias2\", shape=bias_shape2, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv1 = relay.nn.conv2d(\n        A,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=96,\n        kernel_size=(2, 2),\n    )\n    D = relay.op.add(conv1, B1)\n    D = relay.op.nn.relu(D)\n\n    conv2 = relay.nn.conv2d(\n        D,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    conv2 = relay.op.add(conv2, B2)\n    conv2 = relay.op.nn.relu(conv2)\n\n    conv3 = relay.nn.conv2d(\n        D,\n        W3,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=5,\n        kernel_size=(2, 2),\n    )\n\n    t = relay.Tuple([conv2, conv3])\n    c = relay.op.concatenate(t, axis=1)\n\n    mod = relay.Function([A, W1, B1, W2, B2, W3], c)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    bias_data1 = np.zeros(bias_shape1).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"bias\", bias_data1)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    bias_data2 = np.zeros(bias_shape2).astype(dtype)\n    initializer(\"weight\", filter_data2)\n    initializer(\"bias\", bias_data2)\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    params1 = {\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"bias1\": tvm.nd.array(bias_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n        \"bias2\": tvm.nd.array(bias_data2),\n        \"weight3\": tvm.nd.array(filter_data3),\n    }\n\n    static_memory_scope = [\n        \"\",\n        \"global\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"global\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ]\n\n    static_memory_scope = []\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_pooling_branching_texture_params(target, dtype):\n    \"\"\"\n    Verification of the pooling and many branches having textures\n                layout_transform (NCHW->NCHW4c)\n                         |                        <- buffer\n                      conv2d (0)                  <- to get textures\n                         |                        <- textures\n                     pooling\n               /           \\           \\          <- textures\n            conv2d (1)    conv2d (2)    conv2d (3)\n                \\             /           |\n                     add                  |       <- to have  the only one output, will be fused\n                      \\                  /\n                            add                  <- to have  the only one output, will be fused\n                             |                   <- buffer\n                    layout_transform (NCHW4c->NCHW)\n    \"\"\"\n    input_shape = (1, 32, 40, 40)\n    filter_shape0 = (32, 32, 1, 1)\n    filter_shape1 = (32, 32, 2, 2)\n    filter_shape2 = (32, 32, 1, 1)\n    filter_shape3 = (32, 32, 2, 2)\n    bias_shape1 = (1, 32, 1, 1)\n    # bias_shape2 = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W0 = relay.var(\"weight0\", shape=filter_shape0, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    B1 = relay.var(\"bias1\", shape=bias_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    W3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n\n    conv0 = relay.nn.conv2d(\n        A,\n        W0,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    pool = relay.nn.avg_pool2d(conv0, pool_size=(2, 2), strides=(2, 2))\n    conv1 = relay.nn.conv2d(\n        pool,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    conv1 = relay.op.add(conv1, B1)\n    conv1 = relay.op.nn.relu(conv1)\n\n    conv2 = relay.nn.conv2d(\n        pool,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    conv3 = relay.nn.conv2d(\n        pool,\n        W3,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 1, 1, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    conv3 = relay.op.nn.relu(conv3)\n    res = relay.op.add(conv1, conv2)\n    res = relay.op.add(res, conv3)\n\n    mod = relay.Function([A, W0, W1, B1, W2, W3], res)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data0 = np.zeros(filter_shape0).astype(dtype)\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    bias_data1 = np.zeros(bias_shape1).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"bias\", bias_data1)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    initializer(\"weight\", filter_data2)\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    params1 = {\n        \"weight0\": tvm.nd.array(filter_data0),\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"bias1\": tvm.nd.array(bias_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n        \"weight3\": tvm.nd.array(filter_data3),\n    }\n\n    static_memory_scope = [\n        \"global\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"\",\n        \"\",\n    ]\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_branching_texture_params(target, dtype):\n    \"\"\"\n    Verification of passing texture to several consumers markup of relay variables in\n    primary functions + on_device\n\n                layout_transform (NCHW->NCHW4c)\n                         |                      <- buffer\n                      conv2d (0)                <- to get textures\n             /           \\           \\          <- here should be textures and textures in params\n          conv2d (1)    conv2d (2)    conv2d (3)\n            \\             /           |\n                  add                 |         <- to have  the only one output\n                    \\                /\n                           add                  <- to have  the only one output\n                            |                   <- buffer\n                    layout_transform (NCHW4c->NCHW)\n    \"\"\"\n    input_shape = (1, 32, 40, 40)\n    filter_shape0 = (32, 32, 1, 1)\n    filter_shape1 = (32, 32, 2, 2)\n    filter_shape2 = (32, 32, 1, 1)\n    filter_shape3 = (32, 32, 2, 2)\n    bias_shape1 = (1, 32, 1, 1)\n    # bias_shape2 = (1, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W0 = relay.var(\"weight0\", shape=filter_shape0, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    B1 = relay.var(\"bias1\", shape=bias_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    W3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n\n    conv0 = relay.nn.conv2d(\n        A,\n        W0,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    conv1 = relay.nn.conv2d(\n        conv0,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    conv1 = relay.op.add(conv1, B1)\n    conv1 = relay.op.nn.relu(conv1)\n\n    conv2 = relay.nn.conv2d(\n        conv0,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    conv3 = relay.nn.conv2d(\n        conv0,\n        W3,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 1, 1, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(2, 2),\n    )\n    conv3 = relay.op.nn.relu(conv3)\n    res = relay.op.add(conv1, conv2)\n    res = relay.op.add(res, conv3)\n\n    mod = relay.Function([A, W0, W1, B1, W2, W3], res)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data0 = np.zeros(filter_shape0).astype(dtype)\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    bias_data1 = np.zeros(bias_shape1).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"bias\", bias_data1)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    initializer(\"weight\", filter_data2)\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    params1 = {\n        \"weight0\": tvm.nd.array(filter_data0),\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"bias1\": tvm.nd.array(bias_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n        \"weight3\": tvm.nd.array(filter_data3),\n    }\n\n    static_memory_scope = [\n        \"global\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"\",\n        \"\",\n    ]\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n# function repeat, params scope are different in reused functions\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_different_lowering_same_op(target, dtype):\n    \"\"\"\n    Use case for verification of caching compiled functions\n    Three convolutions following by each other in this case should be\n    compiled in three different entities and lowered differently because\n    they are differ in input param memory scopes and in output memory scope\n\n                layout_transform (NCHW->NCHW4c)\n                         |                      <- buffer\n                      conv2d (1)                <- buffer as input tensor and texture as output\n                         |                      <- texture\n                      conv2d (2)                <- texture as input and texture as output\n                         |                      <- texture\n                      conv2d (3)                <- texture as input and buffer as output\n                         |                      <- buffer\n                    layout_transform (NCHW4c->NCHW)\n    \"\"\"\n    input_shape = (1, 32, 40, 40)\n    filter_shape1 = (32, 32, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n\n    conv1 = relay.nn.conv2d(\n        A,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    conv2 = relay.nn.conv2d(\n        conv1,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    conv3 = relay.nn.conv2d(\n        conv2,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(1, 1),\n    )\n\n    mod = relay.Function([A, W1], conv3)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    params1 = {\n        \"weight1\": tvm.nd.array(filter_data1),\n    }\n\n    static_memory_scope = [\n        \"global\",\n        \"global.texture\",\n        \"global.texture-weight\",\n        \"global.texture\",\n        \"global.texture\",\n        \"\",\n        \"\",\n    ]\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_winograd_non_rect(target, dtype):\n    input_shape = (1, 771, 36, 64)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    filter_shape = (128, 771, 3, 3)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    D = relay.nn.conv2d(\n        A, B, padding=[1, 1, 1, 1], channels=128, kernel_size=[3, 3], out_dtype=dtype\n    )\n\n    mod = relay.Function([A, B], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256 -texture_spatial_limit=16384 -thread_warp_size=1\", \"conv2d_nchw_winograd.image2d\", [[\"TENSOR\", [1, 771, 36, 64], \"{dtype}\"], [\"TENSOR\", [128, 771, 3, 3], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 5399, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 16], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 8]], [\"tile_rc\", \"sp\", [-1, 193]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n\n\n# function repeat, params scope are different in reused functions\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_injective_nwo_inputs1(target, dtype):\n    \"\"\"\n    Use case for verification of stability of annotation primary functions\n    having several ops accepting data outside of Primary function\n    The visiting of ops during traversing of graph inside primary function\n    can depend on order of relay graph creation. Thus the annotation mechanism\n    should be reliable for graph traversal order\n    The current decision if Prim Function support textures or not depend on\n    *any* op accepting input of the function and if op support textures\n                                     Input\n                               /                   \\\n                layout_transform (NCHW->NCHW4c)    |\n                         |                        /\n                      conv2d (1)                 /\n                         |                      /\n                      conv2d (2)       mean    /\n                  /         \\                 /   <- Primary function several head ops\n             (1)add    (2)layout_transform    |\n                 |        (NCHW4c->NCHW)      |\n                 |           |      \\        /\n                 |           |       (3) add\n                 |           |         |\n    layout_transform          \\       /\n     (NCHW4c->NCHW)             \\    /\n                 \\                mul\n                  \\            /\n                        add\n\n    This test verifies a case when the latest op which is visited is (3) and does not\n    support textures, but there is (1) supporting textures, thus the whole func will\n    support textures\n    \"\"\"\n    input_shape = (1, 4, 40, 40)\n    filter_shape1 = (4, 4, 3, 3)\n    filter_shape2 = (4, 4, 3, 3)\n    filter_shape3 = (4, 4, 3, 3)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    mean = relay.mean(A, axis=1, keepdims=True)\n    conv1 = relay.nn.conv2d(\n        A,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(3, 3),\n    )\n\n    conv2 = relay.nn.conv2d(\n        conv1,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(3, 3),\n    )\n\n    ad3 = relay.op.add(conv1, conv2)\n    ad1 = relay.op.add(mean, conv1)\n    ad2 = relay.op.multiply(ad1, conv2)\n    ad4 = relay.op.add(ad3, ad2)\n\n    mod = relay.Function([A, W1, W2], ad4)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"weight\", filter_data2)\n    params1 = {\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n    }\n\n    static_memory_scope = [\n        \"global\",\n        \"global.texture\",\n        \"global.texture-nhwc\",\n        \"global.texture\",\n        \"global.texture-nhwc\",\n        \"global.texture\",\n        \"global\",\n        \"global\",\n    ]\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n\n\n# function repeat, params scope are different in reused functions\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_injective_nwo_inputs2(target, dtype):\n    \"\"\"\n    Use case for verification of stability of annotation primary functions\n    having several ops accepting data outside of Primary function\n    The visiting of ops during traversing of graph inside primary function\n    can depend on order of relay graph creation. Thus the annotation mechanism\n    should be reliable for graph traversal order\n    The current decision if Prim Function support textures or not depend on\n    *any* op accepting input of the function and if op support textures\n                                     Input\n                               /                   \\\n                layout_transform (NCHW->NCHW4c)    |\n                         |                        /\n                      conv2d (1)                 /\n                         |                      /\n                      conv2d (2)       mean    /\n                  /         \\                 /   <- Primary function several head ops\n             (1)add    (2)layout_transform    |\n                 |        (NCHW4c->NCHW)      |\n                 |           |      \\        /\n                 |           |       (3) add\n                 |           |         |\n    layout_transform          \\       /\n     (NCHW4c->NCHW)             \\    /\n                 \\                mul\n                  \\            /\n                        add\n\n    This test verifies a case when the latest op which is (1), it supports textures\n    an whole prim function is considered as a func working with textures\n    \"\"\"\n    input_shape = (1, 4, 40, 40)\n    filter_shape1 = (4, 4, 3, 3)\n    filter_shape2 = (4, 4, 3, 3)\n    filter_shape3 = (4, 4, 3, 3)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    W1 = relay.var(\"weight1\", shape=filter_shape1, dtype=dtype)\n    W2 = relay.var(\"weight2\", shape=filter_shape2, dtype=dtype)\n    mean = relay.mean(A, axis=1, keepdims=True)\n    conv1 = relay.nn.conv2d(\n        A,\n        W1,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(3, 3),\n    )\n\n    conv2 = relay.nn.conv2d(\n        conv1,\n        W2,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(3, 3),\n    )\n\n    ad3 = relay.op.add(conv1, conv2)\n    ad1 = relay.op.add(mean, conv1)\n    ad2 = relay.op.multiply(ad1, conv2)\n    ad4 = relay.op.add(ad2, ad3)\n\n    mod = relay.Function([A, W1, W2], ad4)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data1 = np.zeros(filter_shape1).astype(dtype)\n    filter_data2 = np.zeros(filter_shape2).astype(dtype)\n    initializer(\"weight\", filter_data1)\n    initializer(\"weight\", filter_data2)\n    params1 = {\n        \"weight1\": tvm.nd.array(filter_data1),\n        \"weight2\": tvm.nd.array(filter_data2),\n    }\n\n    static_memory_scope = [\n        \"global\",\n        \"global.texture\",\n        \"global.texture-nhwc\",\n        \"global.texture\",\n        \"global\",\n        \"global.texture-nhwc\",\n        \"global.texture\",\n        \"global\",\n    ]\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, static_memory_scope)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/test_conv2d_nhwc_texture.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport re\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import utils\nfrom utils.adreno_utils import gpu_preprocess, build_run_compare\nimport pytest\n\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_deeplabv3_1_257_257_32x1_1_32_16(target, dtype):\n    input_shape = (1, 257, 257, 32)\n    filter_shape = (1, 1, 32, 16)\n    bias_shape = (filter_shape[-1],)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=dtype,\n        channels=filter_shape[-1],\n        kernel_size=(1, 1),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_deeplabv3_1_257_257_32x1_1_32_16_with_padding(target, dtype):\n    input_shape = (1, 257, 257, 32)\n    filter_shape = (1, 1, 32, 16)\n    bias_shape = (filter_shape[-1],)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[3, 3, 3, 3],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=filter_shape[-1],\n        kernel_size=(1, 1),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_4_35_35_32x3_3_144_16(target, dtype):\n    input_shape = (4, 35, 35, 32)\n    filter_shape = (3, 3, 32, 16)\n    bias_shape = (filter_shape[-1],)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=dtype,\n        channels=filter_shape[-1],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_deeplabv3_1_513_513_3x3_3_3_32(target, dtype):\n    input_shape = (1, 513, 513, 3)\n    filter_shape = (3, 3, 3, 32)\n    bias_shape = (filter_shape[-1],)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=dtype,\n        channels=filter_shape[-1],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.ones(filter_shape).astype(dtype)\n    bias_data = np.ones(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_64x35x35_96x64x3x3_nopad(target, dtype):\n    input_shape = (1, 42, 42, 32)\n    filter_shape = (3, 3, 32, 96)\n    bias_shape = (1, 1, 1, 96)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=96,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_64x35x35_96x64x3x3_nopad_pass(target, dtype):\n    input_shape = (1, 40, 40, 32)\n    filter_shape = (2, 2, 32, 96)\n    bias_shape = (1, 1, 1, 96)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=96,\n        kernel_size=(2, 2),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_35_35_strides(target, dtype):\n    input_shape = (1, 35, 35, 48)\n    filter_shape = (5, 5, 48, 64)\n    bias_shape = (1, 1, 1, 64)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[2, 2, 2, 2],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(5, 5),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_resnet50_v2_nhwc_3c(target, dtype):\n    input_shape = (1, 224, 224, 3)\n    filter_shape = (7, 7, 3, 64)\n    bias_shape = (1, 1, 1, 64)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[3, 3, 3, 3],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(7, 7),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_inceptionv3_nhwc_3c(target, dtype):\n    input_shape = (1, 299, 299, 3)\n    filter_shape = (3, 3, 3, 64)\n    bias_shape = (1, 1, 1, 64)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_1x1_16c16spatial(target, dtype):\n    input_shape = (1, 128, 128, 16)\n    filter_shape = (4, 4, 16, 32)\n    bias_shape = (1, 1, 1, 32)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[0, 0, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_4x4_16c16pad(target, dtype):\n    input_shape = (1, 256, 256, 32)\n    filter_shape = (4, 4, 32, 32)\n    bias_shape = (1, 1, 1, 32)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[3, 3, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=32,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_4x4x4_16c16pad(target, dtype):\n    input_shape = (1, 256, 256, 32)\n    filter_shape = (4, 4, 32, 4)\n    bias_shape = (1, 1, 1, 4)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[3, 3, 0, 0],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=4,\n        kernel_size=(4, 4),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_yolov3_v2_nhwc_3c(target, dtype):\n    input_shape = (1, 13, 13, 1024)\n    filter_shape = (1, 1, 1024, 255)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[0, 0, 0, 0],\n        strides=[1, 1],\n        out_dtype=dtype,\n        channels=255,\n        kernel_size=(1, 1),\n    )\n\n    mod = relay.Function([A, B], conv)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    params = {\n        \"weight\": tvm.nd.array(filter_data),\n    }\n\n    build_run_compare(mod, params, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_vgg16_winograd_4d(target, dtype):\n    input_shape = (1, 28, 28, 512)\n    filter_shape = (3, 3, 512, 512)\n    bias_shape = (1, 1, 1, 512)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[1, 1, 1, 1],\n        channels=512,\n        kernel_size=[3, 3],\n        out_dtype=dtype,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(0)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256\", \"conv2d_nhwc_winograd.image2d\", [[\"TENSOR\", [1, 28, 28, 512], \"{dtype}\"], [\"TENSOR\", [3, 3, 512, 512], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 1591, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 4], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 2]], [\"tile_rc\", \"sp\", [-1, 8]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_winograd_conv(target, dtype):\n    input_shape = (1, 3, 3, 4)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    filter_shape3 = (3, 3, 4, 8)\n    bias_shape3 = (1, 1, 1, 8)\n    B3 = relay.var(\"weight3\", shape=filter_shape3, dtype=dtype)\n    D = relay.nn.conv2d(\n        A,\n        B3,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[1, 1, 1, 1],\n        channels=8,\n        kernel_size=[3, 3],\n        out_dtype=dtype,\n    )\n\n    filter_shape4 = (3, 3, 8, 8)\n    bias_shape4 = (1, 1, 1, 8)\n    B4 = relay.var(\"weight4\", shape=filter_shape4, dtype=dtype)\n    D = relay.nn.conv2d(\n        D,\n        B4,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[1, 1, 1, 1],\n        channels=8,\n        kernel_size=[3, 3],\n        out_dtype=dtype,\n    )\n    mod = relay.Function([A, B3, B4], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data3 = np.zeros(filter_shape3).astype(dtype)\n    bias_data3 = np.zeros(bias_shape3).astype(dtype)\n    filter_data4 = np.zeros(filter_shape4).astype(dtype)\n    bias_data4 = np.zeros(bias_shape4).astype(dtype)\n    initializer(\"weight\", filter_data3)\n    initializer(\"bias\", bias_data3)\n    initializer(\"weight\", filter_data4)\n    initializer(\"bias\", bias_data4)\n    params1 = {\n        \"weight3\": tvm.nd.array(filter_data3),\n        \"weight4\": tvm.nd.array(filter_data4),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256\", \"conv2d_nhwc_winograd.image2d\", [[\"TENSOR\", [1, 3, 3, 4], \"{dtype}\"], [\"TENSOR\", [3, 3, 4, 8], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 1591, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 4], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 2]], [\"tile_rc\", \"sp\", [-1, 8]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_conv2d_winograd_non_rect(target, dtype):\n    input_shape = (1, 36, 64, 771)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    filter_shape = (3, 3, 771, 128)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    D = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        padding=[1, 1, 1, 1],\n        channels=128,\n        kernel_size=[3, 3],\n        out_dtype=dtype,\n    )\n\n    mod = relay.Function([A, B], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n    }\n\n    temp = utils.tempdir()\n    stat_file = temp.relpath(\"stat.log\")\n    with open(stat_file, \"w\") as f:\n        f.write(\n            f'{{\"input\": [\"opencl -keys=adreno,opencl,gpu -device=adreno -max_num_threads=256 -texture_spatial_limit=16384 -thread_warp_size=1\", \"conv2d_nhwc_winograd.image2d\", [[\"TENSOR\", [1, 36, 64, 771], \"{dtype}\"], [\"TENSOR\", [3, 3, 771, 128], \"{dtype}\"], [1, 1], [1, 1, 1, 1], [1, 1], \"{dtype}\"], {{}}], \"config\": {{\"index\": 5399, \"code_hash\": null, \"entity\": [[\"auto_unroll_max_step\", \"ot\", 16], [\"tile_y\", \"sp\", [-1, 1, 32]], [\"tile_x\", \"sp\", [-1, 4, 8]], [\"tile_rc\", \"sp\", [-1, 193]]]}}, \"result\": [[0.0037244], 0, 7.06374192237854, 1653898629.7427933], \"version\": 0.2, \"tvm_version\": \"0.8.dev0\"}}\\n'\n        )\n    graph = build_run_compare(\n        mod, params1, {\"data\": input_shape}, dtype, target, stat_file=stat_file\n    )\n    matches = re.findall(\"winograd\", graph)\n    assert len(matches) > 0\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/test_depthwise_conv2d_nchw_texture.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom utils.adreno_utils import gpu_preprocess, build_run_compare\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_bias_nchwc(target, dtype):\n    input_shape = (1, 64, 112, 112)\n    filter_shape = (64, 1, 3, 3)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        groups=64,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_nchwc(target, dtype):\n    input_shape = (1, 64, 112, 112)\n    filter_shape = (64, 1, 3, 3)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        groups=64,\n        kernel_size=(3, 3),\n    )\n\n    mod = relay.Function([A, B], conv)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target, [], gpu_preprocess)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_bias_nchw(target, dtype):\n    input_shape = (1, 64, 112, 112)\n    filter_shape = (64, 1, 3, 3)\n    bias_shape = (1, 64, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=64,\n        groups=64,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_repack_bias_nchw(target, dtype):\n    input_shape = (1, 63, 112, 112)\n    filter_shape = (63, 1, 3, 3)\n    bias_shape = (1, 63, 1, 1)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    # C = relay.nn.relu(A)\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NCHW\",\n        kernel_layout=\"OIHW\",\n        padding=[1, 1, 1, 1],\n        strides=[2, 2],\n        out_dtype=dtype,\n        channels=63,\n        groups=63,\n        kernel_size=(3, 3),\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/test_depthwise_conv2d_nhwc_texture.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom utils.adreno_utils import build_run_compare\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_deeplabv3_1_129_129_144x3_3_144_1(target, dtype):\n    input_shape = (1, 129, 129, 144)\n    filter_shape = (3, 3, 144, 1)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    bias_shape = (filter_shape[2],)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=dtype,\n        groups=filter_shape[2],\n        channels=filter_shape[2],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    mod = relay.Function([A, B, bias], conv)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_deeplabv3_4_35_35_576x3_3_576_1(target, dtype):\n    input_shape = (4, 35, 35, 576)\n    filter_shape = (3, 3, 576, 1)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    bias_shape = (filter_shape[2],)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=dtype,\n        groups=filter_shape[2],\n        channels=filter_shape[2],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    mod = relay.Function([A, B, bias], conv)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_deeplabv3_1_129_129_144x3_3_144_1_with_padding(target, dtype):\n    input_shape = (1, 129, 129, 144)\n    filter_shape = (3, 3, 144, 1)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    bias_shape = (filter_shape[2],)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        padding=[3, 3, 3, 3],\n        strides=[2, 2],\n        out_dtype=dtype,\n        groups=filter_shape[2],\n        channels=filter_shape[2],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    # mod, params = relay.testing.init.create_workload(func)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.zeros(filter_shape).astype(dtype)\n    bias_data = np.zeros(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_1_513_513_7x3_3_7_1(target, dtype):\n    input_shape = (1, 513, 513, 7)\n    filter_shape = (3, 3, 7, 1)\n    bias_shape = (filter_shape[2],)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=dtype,\n        channels=filter_shape[2],\n        groups=filter_shape[2],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.ones(filter_shape).astype(dtype)\n    bias_data = np.ones(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_depthwise_conv2d_1_513_513_3x3_3_3_1(target, dtype):\n    input_shape = (1, 513, 513, 3)\n    filter_shape = (3, 3, 3, 1)\n    bias_shape = (filter_shape[2],)\n    kernel_size = (filter_shape[0], filter_shape[1])\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n    conv = relay.nn.conv2d(\n        A,\n        B,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=dtype,\n        channels=filter_shape[2],\n        groups=filter_shape[2],\n        kernel_size=kernel_size,\n    )\n    D = relay.op.add(conv, bias)\n    D = relay.op.nn.relu(D)\n\n    mod = relay.Function([A, B, bias], D)\n    np.random.seed(1)\n    initializer = relay.testing.init.Xavier()\n    filter_data = np.ones(filter_shape).astype(dtype)\n    bias_data = np.ones(bias_shape).astype(dtype)\n    initializer(\"weight\", filter_data)\n    initializer(\"bias\", bias_data)\n    params1 = {\n        \"weight\": tvm.nd.array(filter_data),\n        \"bias\": tvm.nd.array(bias_data),\n    }\n\n    build_run_compare(mod, params1, {\"data\": input_shape}, dtype, target)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/test_reduction_texture.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport re\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import utils\nfrom utils.adreno_utils import gpu_preprocess, build_run_compare\n\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_mean(target, dtype):\n    # NCHW\n    input_shape = (1, 3, 720, 1280)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    mean = relay.mean(A, axis=1, keepdims=True)\n    mod = relay.Function([A], mean)\n\n    build_run_compare(mod, {}, {\"data\": input_shape}, dtype, target)\n\n\n@tvm.testing.requires_opencl\n@tvm.testing.parametrize_targets(\"opencl -device=adreno\")\ndef test_argmax(target, dtype):\n    # NCHW\n    input_shape = (1, 3, 720, 1280)\n    A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n    argmax = relay.op.argmax(A, axis=[1])\n    mod = relay.Function([A], argmax)\n\n    build_run_compare(mod, {}, {\"data\": input_shape}, dtype, target)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/opencl_texture/utils/adreno_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utils for adreno compute/schedules\"\"\"\n\nimport os\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.relay import testing\nfrom tvm.relay.transform import recast\nfrom tvm.contrib import graph_runtime\nimport json\n\n\ndef get_cpu_reference(mod, params1, input_shape, inputs):\n    mod_fp32 = recast(mod, \"float32\", \"float32\", ops=[\"nn.conv2d\", \"add\", \"nn.relu\"])\n    with relay.build_config(opt_level=3):\n        graph, lib, params = relay.build(mod_fp32, \"llvm\", params=params1)\n    ctx = tvm.cpu()\n    m = graph_runtime.create(graph, lib, ctx)\n    if isinstance(input_shape, dict):\n        for key in input_shape:\n            m.set_input(key, inputs[-1])\n    else:\n        m.set_input(\"data\", inputs[-1])\n    m.set_input(**params)\n    m.run()\n    return [\n        m.get_output(0).asnumpy(),\n    ]\n\n\n# build module run with opencl and cpu, compare results\ndef build_run_compare(\n    tvm_mod,\n    params1,\n    input_shape,\n    dtype=\"float32\",\n    target=\"llvm\",\n    static_mem_scopes=[],\n    gpu_preprocess=None,\n    stat_file=None,\n):\n\n    if \"TVM_TRACKER_HOST\" in os.environ and \"TVM_TRACKER_PORT\" in os.environ:\n        rpc_tracker_host = os.environ[\"TVM_TRACKER_HOST\"]\n        rpc_tracker_port = os.environ[\"TVM_TRACKER_PORT\"]\n        run_on_host = 0\n        target_host = \"llvm -mtriple=arm64-linux-android\"\n        rpc_tracker_port = int(rpc_tracker_port)\n    else:\n        run_on_host = 1\n        target_host = \"llvm\"\n\n    if gpu_preprocess:\n        tvm_mod_nchwc = gpu_preprocess(tvm_mod)\n    else:\n        tvm_mod_nchwc = tvm_mod\n\n    if stat_file is not None:\n        with autotvm.apply_history_best(stat_file):\n            with tvm.transform.PassContext(opt_level=3):\n                graph, lib, params = relay.build(\n                    tvm_mod_nchwc, target_host=target_host, target=target, params=params1\n                )\n    else:\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(\n                tvm_mod_nchwc, target_host=target_host, target=target, params=params1\n            )\n\n    # verification that storage_scope has expected textures scopes\n    graph_json = json.loads(graph)\n    if \"storage_scope\" in graph_json[\"attrs\"]:\n        assert (\n            len(static_mem_scopes) == len(graph_json[\"attrs\"][\"storage_scope\"][1])\n            or len(static_mem_scopes) == 0\n        )\n    else:\n        assert len(static_mem_scopes) == 0\n\n    for i in range(0, len(static_mem_scopes)):\n        assert static_mem_scopes[i] == graph_json[\"attrs\"][\"storage_scope\"][1][i]\n\n    if run_on_host:\n        ctx = tvm.opencl()\n        m = graph_runtime.create(graph, lib, ctx)\n    else:\n        from tvm import rpc\n        from tvm.contrib import utils, ndk\n\n        rpc_key = \"android\"\n        tracker = rpc.connect_tracker(rpc_tracker_host, rpc_tracker_port)\n        remote = tracker.request(rpc_key, priority=0, session_timeout=600)\n        temp = utils.tempdir()\n        dso_binary = \"dev_lib_cl.so\"\n        dso_binary_path = temp.relpath(dso_binary)\n        ctx = remote.cl(0)\n        lib.export_library(dso_binary_path, ndk.create_shared)\n        remote.upload(dso_binary_path)\n        rlib = remote.load_module(dso_binary)\n        m = graph_runtime.create(graph, rlib, ctx)\n    m.set_input(**params)\n    inputs = []\n    if isinstance(input_shape, dict):\n        for key in input_shape:\n            inputs.append(np.random.normal(size=input_shape[key]).astype(dtype))\n            m.set_input(key, inputs[-1])\n    else:\n        inputs.append(np.random.normal(size=input_shape).astype(dtype))\n        m.set_input(\"data\", inputs[-1])\n    m.run()\n\n    ref_outputs = get_cpu_reference(tvm_mod, params1, input_shape, inputs)\n    for i, ref_output in enumerate(ref_outputs):\n        tvm_output = m.get_output(i)\n        output = tvm_output.asnumpy()\n        # for index, x in np.ndenumerate(ref_output):\n        #     if abs(output[index] - x) > 0.01:\n        #         print(index, output[index], x)\n\n        np.testing.assert_allclose(output, ref_output, rtol=1e-1, atol=1e-1)\n    return graph\n\n\ndef gpu_preprocess(tvm_mod):\n    layout_config = relay.transform.LayoutConfig()\n    desired_layouts = {\"nn.conv2d\": [\"NCHW4c\", \"OIHW4o\"]}\n    with layout_config:\n        seq = tvm.transform.Sequential([relay.transform.ConvertLayout(desired_layouts)])\n        with tvm.transform.PassContext(opt_level=3):\n            mod = tvm.IRModule.from_expr(tvm_mod)\n            tvm_mod_nchwc = seq(mod)\n            return tvm_mod_nchwc\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/qnn/test_canonicalizations.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom typing import Callable\n\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay.qnn.op import canonicalizations\n\n\nclass TestIntegerTableLookupTable:\n    \"\"\"Consists of tests testing functionality of creating lookup tables for integer operations.\"\"\"\n\n    def fake_identity_func_numpy(self, arr: np.ndarray):\n        return arr.astype(\"float32\")\n\n    def fake_identity_func_relay(\n        self,\n        floating_point_func: Callable[[np.ndarray], np.ndarray],\n        input_arg=None,\n        in_scale=relay.const(1.0, dtype=\"float32\"),\n        in_zero_point=relay.const(0, dtype=\"int32\"),\n        out_scale=relay.const(1.0, dtype=\"float32\"),\n        out_zero_point=relay.const(0, dtype=\"int32\"),\n        in_axis=-1,\n        out_axis=-1,\n        in_dtype=\"uint8\",\n        out_dtype=\"uint8\",\n    ):\n        if input_arg is None:\n            input_arg = relay.const(np.arange(0, 256, dtype=\"uint8\").view(in_dtype))\n\n        return (\n            canonicalizations.create_integer_lookup_op(\n                input_arg=input_arg,\n                floating_point_func=floating_point_func,\n                in_scale=in_scale,\n                in_zero_point=in_zero_point,\n                out_scale=out_scale,\n                out_zero_point=out_zero_point,\n                in_axis=in_axis,\n                out_axis=out_axis,\n                in_dtype=in_dtype,\n                out_dtype=out_dtype,\n            ),\n            input_arg.data.numpy(),\n        )\n\n    def dequantize_numpy(self, np_arr, np_scale=1.0, np_zero_point=0):\n        return (np_arr.astype(\"int32\") - np_zero_point) * np_scale\n\n    def run_function_test(\n        self,\n        in_scale: float,\n        in_zero_point: int,\n        out_scale: float,\n        out_zero_point: int,\n        in_dtype: str,\n        out_dtype: str,\n        floating_point_func: Callable[[np.ndarray], np.ndarray],\n        input_arg: relay.Expr = None,\n        rtol=1e-7,\n        atol=0,\n    ):\n        relay_lookup, input_arg = self.fake_identity_func_relay(\n            input_arg=input_arg,\n            floating_point_func=floating_point_func,\n            in_scale=relay.const(in_scale, \"float32\"),\n            in_zero_point=relay.const(in_zero_point, \"int32\"),\n            out_scale=relay.const(out_scale, \"float32\"),\n            out_zero_point=relay.const(out_zero_point, \"int32\"),\n            in_dtype=in_dtype,\n            out_dtype=out_dtype,\n        )\n        result = canonicalizations.run_const_expr(relay_lookup)\n        np.testing.assert_allclose(\n            floating_point_func(\n                self.dequantize_numpy(input_arg, np_scale=in_scale, np_zero_point=in_zero_point)\n            ),\n            self.dequantize_numpy(result, np_scale=out_scale, np_zero_point=out_zero_point),\n            atol=atol,\n            rtol=rtol,\n        )\n\n    \"\"\"Test mapping between different input/output dtypes\"\"\"\n\n    def test_int8_to_int8(self):\n        self.run_function_test(\n            in_scale=1.0,\n            in_zero_point=0,\n            out_scale=1.0,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=self.fake_identity_func_numpy,\n        )\n\n    def test_uint8_to_uint8(self):\n        self.run_function_test(\n            in_scale=1.0,\n            in_zero_point=128,\n            out_scale=1.0,\n            out_zero_point=128,\n            in_dtype=\"uint8\",\n            out_dtype=\"uint8\",\n            floating_point_func=self.fake_identity_func_numpy,\n        )\n\n    def test_int8_to_uint8(self):\n        self.run_function_test(\n            in_scale=1.0,\n            in_zero_point=0,\n            out_scale=1.0,\n            out_zero_point=128,\n            in_dtype=\"int8\",\n            out_dtype=\"uint8\",\n            floating_point_func=self.fake_identity_func_numpy,\n        )\n\n    def test_uint8_to_int8(self):\n        self.run_function_test(\n            in_scale=1.0,\n            in_zero_point=128,\n            out_scale=1.0,\n            out_zero_point=0,\n            in_dtype=\"uint8\",\n            out_dtype=\"int8\",\n            floating_point_func=self.fake_identity_func_numpy,\n        )\n\n    \"\"\"Test different input shapes\"\"\"\n\n    def test_keep_input_shapes(self):\n        # input in floating point ~[-2, 2], final output ~[0, 8]\n        self.run_function_test(\n            input_arg=relay.const(np.arange(-128, 128).astype(\"int8\").reshape([2, 2, 8, 8])),\n            in_scale=0.015,\n            in_zero_point=0,\n            out_scale=16 / 256,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=self.fake_identity_func_numpy,\n            atol=0.03,\n            rtol=0.01,\n        )\n        self.run_function_test(\n            input_arg=relay.const(np.arange(-128, 128).astype(\"int8\").reshape([2, 2, 64])),\n            in_scale=0.015,\n            in_zero_point=0,\n            out_scale=16 / 256,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=self.fake_identity_func_numpy,\n            atol=0.03,\n            rtol=0.01,\n        )\n        self.run_function_test(\n            input_arg=relay.const(np.arange(-128, 128).astype(\"int8\").reshape([2, 128])),\n            in_scale=0.015,\n            in_zero_point=0,\n            out_scale=16 / 256,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=self.fake_identity_func_numpy,\n            atol=0.03,\n            rtol=0.01,\n        )\n\n    \"\"\"Test mapping with different in/out qparams works.\"\"\"\n\n    def test_different_in_out_qparams(self):\n        self.run_function_test(\n            in_scale=1.0,\n            in_zero_point=128,\n            out_scale=1.0,\n            out_zero_point=128,\n            in_dtype=\"uint8\",\n            out_dtype=\"uint8\",\n            floating_point_func=self.fake_identity_func_numpy,\n            atol=1,  # numbers range from -128 -> 128 so not that big error\n            rtol=0,\n        )\n\n    \"\"\"Test some simple functions\"\"\"\n\n    def test_tanh(self):\n        # 1 / 64 in scale -- input range is ~ (-2, 2), tanh(+-2) ~= +-1\n        # 1 / 128 out_scale -- output range is ~(-1, 1)\n        self.run_function_test(\n            input_arg=relay.const(np.arange(-128, 128).astype(\"int8\")),\n            in_scale=1 / 64,\n            in_zero_point=0,\n            out_scale=1 / 128,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=np.tanh,\n            atol=0.01,\n            rtol=0.01,\n        )\n\n    def test_exp(self):\n        # input in floating point ~[-2, 2], final output ~[0, 8]\n        self.run_function_test(\n            input_arg=relay.const(np.arange(-128, 128).astype(\"int8\")),\n            in_scale=0.015,\n            in_zero_point=0,\n            out_scale=16 / 256,\n            out_zero_point=0,\n            in_dtype=\"int8\",\n            out_dtype=\"int8\",\n            floating_point_func=np.exp,\n            atol=0.03,\n            rtol=0.01,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_avg_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicPoolTests:\n    @tvm.testing.requires_corstone300\n    def test_pool(\n        self,\n        pool_type,\n        shape,\n        dtype,\n        pool_size,\n        strides,\n        padding,\n        dilation,\n        layout,\n        ceil_mode,\n        count_include_pad,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single pool operator.\"\"\"\n        ishape = shape\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n\n        out0 = getattr(relay.op.nn, pool_type)(\n            input0,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=layout,\n            out_layout=\"\",\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n        )\n\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        out1 = getattr(relay.op.nn, pool_type)(\n            input1,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=layout,\n            out_layout=\"\",\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestAvgPool1d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    (\n        shape,\n        pool_size,\n        strides,\n        padding,\n        dilation,\n        layout,\n        ceil_mode,\n        count_include_pad,\n    ) = tvm.testing.parameters(\n        ((3, 32, 27), (3,), (2,), 0, 1, \"NCW\", False, False),\n        ((3, 32, 27), (3,), (2,), 0, 1, \"NWC\", False, False),\n        ((3, 32, 27), (3,), (2,), 0, 1, \"NCW\", True, False),\n        ((3, 32, 27), (3,), (2,), 1, 1, \"NCW\", False, True),\n        ((1, 1, 32), 3, 1, 0, 1, \"NCW\", False, False),\n        ((1, 4, 20), 3, 2, 2, 1, \"NCW\", False, False),\n    )\n    pool_type = tvm.testing.parameter(\"avg_pool1d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nclass TestAvgPool2d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    (\n        shape,\n        pool_size,\n        strides,\n        padding,\n        dilation,\n        layout,\n        ceil_mode,\n        count_include_pad,\n    ) = tvm.testing.parameters(\n        ((3, 32, 27, 27), (3, 3), (2, 2), 0, 1, \"NCHW\", False, False),\n        ((3, 32, 27, 27), (3, 3), (2, 2), 0, 1, \"NHWC\", False, False),\n        ((2, 16, 27, 27), (3, 3), (2, 2), 0, 1, \"NCHW\", True, False),\n        ((2, 27, 27, 16), (3, 3), (2, 2), 0, 1, \"NHWC\", True, False),\n        ((2, 16, 27, 27), (3, 3), (2, 2), 0, 1, \"NCHW\", True, True),\n        ((1, 25, 5, 64), (25, 5), (25, 5), 0, 1, \"NHWC\", False, False),\n        ((1, 3, 3, 256), (3, 3), (3, 3), 0, 1, \"NHWC\", False, False),\n        ((1, 8, 8, 64), (8, 8), (8, 8), 0, 1, \"NHWC\", False, False),\n        ((1, 1, 32, 32), (3, 3), 1, 0, 1, \"NCHW\", False, False),\n        ((1, 4, 32, 20), (3, 3), (2, 2), 0, 1, \"NCHW\", False, False),\n    )\n    pool_type = tvm.testing.parameter(\"avg_pool2d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nclass TestAvgPool3d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    (\n        shape,\n        pool_size,\n        strides,\n        padding,\n        dilation,\n        layout,\n        ceil_mode,\n        count_include_pad,\n    ) = tvm.testing.parameters(\n        ((3, 4, 8, 27, 27), (3, 3, 3), 2, 0, 1, \"NCDHW\", False, False),\n    )\n    pool_type = tvm.testing.parameter(\"avg_pool3d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_conv1d_ncw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicConv1dTests:\n    @tvm.testing.requires_corstone300\n    def test_conv1d(\n        self,\n        data_shape,\n        kernel_size,\n        num_filter,\n        strides,\n        padding,\n        dilation,\n        dtype,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single conv1d_ncw operator.\"\"\"\n        ishape = data_shape\n        wshape = (num_filter, data_shape[1], kernel_size)\n\n        weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight0 = relay.const(weight_data)\n        out0 = relay.op.nn.conv1d(\n            input0,\n            weight0,\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=\"NCW\",\n            kernel_layout=\"OIW\",\n            out_dtype=\"int32\",\n            out_layout=\"NCW\",\n        )\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight1 = relay.const(weight_data)\n\n        out1 = relay.op.nn.conv1d(\n            input1,\n            weight1,\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=\"NCW\",\n            kernel_layout=\"OIW\",\n            out_dtype=\"int32\",\n            out_layout=\"NCW\",\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestConv1d_ncw(BasicConv1dTests):\n    \"\"\"This test is for conv1d_ncw.generic schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = tvm.testing.parameters(\n        ((4, 32, 16), 3, 12, 1, 0, 1),\n        ((4, 16, 32), 3, 12, 1, 0, 1),\n        ((1, 12, 32), 3, 16, 1, 0, 1),\n        ((3, 10, 12), 4, 24, 1, 0, 1),\n        ((1, 7, 7), 3, 5, 1, 0, 1),\n        ((1, 2, 10), 4, 4, 2, (1, 1), 1),\n        ((1, 2, 20), 4, 4, 2, (0, 1), 1),\n        ((1, 4, 16), 1, 12, 1, (1, 0), 1),\n        ((1, 16, 24), 1, 32, 3, (2, 2), 1),\n    )\n    dtype = tvm.testing.parameter(\"int8\", \"int16\")\n    data_layout = tvm.testing.parameter(\"NCW\")\n    schedule_name = tvm.testing.parameter(\"conv1d_ncw.generic\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_conv1d_nwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicConv1dTests:\n    @tvm.testing.requires_corstone300\n    def test_conv1d(\n        self,\n        data_shape,\n        kernel_size,\n        kernel_layout,\n        num_filter,\n        strides,\n        padding,\n        dilation,\n        dtype,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single conv1d_nwc operator.\"\"\"\n        ishape = data_shape\n        wshape = (kernel_size, data_shape[-1], num_filter)\n        weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight0 = relay.const(weight_data)\n        out0 = relay.op.nn.conv1d(\n            input0,\n            weight0,\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=\"NWC\",\n            kernel_layout=\"WIO\",\n            out_dtype=\"int32\",\n            out_layout=\"NWC\",\n        )\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n\n        if kernel_layout == \"WOI\":\n            weight1 = relay.const(np.moveaxis(weight_data, 1, -1))\n        else:\n            weight1 = relay.const(weight_data)\n\n        out1 = relay.op.nn.conv1d(\n            input1,\n            weight1,\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=\"NWC\",\n            kernel_layout=kernel_layout,\n            out_dtype=\"int32\",\n            out_layout=\"NWC\",\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestConv1d_dsp(BasicConv1dTests):\n    \"\"\"This test is for conv1d_dsp schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = tvm.testing.parameters(\n        ((4, 32, 16), 3, 12, 1, 0, 1),\n        ((4, 16, 32), 3, 12, 1, 0, 1),\n        ((4, 32, 16), 3, 12, 1, 0, 1),\n        ((1, 32, 12), 3, 16, 1, 0, 1),\n        # TODO: The following 4 tests fail due to https://github.com/apache/tvm/issues/11466\n        # ((3, 12, 10), 4, 24, 1, 0, 1),\n        # ((1, 7, 7), 3, 5, 1, 0, 1),\n        # ((1, 10, 2), 4, 4, 2, (1, 1), 1),\n        # ((1, 20, 2), 4, 4, 2, (0, 1), 1),\n        ((1, 16, 4), 1, 12, 1, (1, 0), 1),\n        ((1, 24, 16), 1, 32, 3, (2, 2), 1),\n    )\n    dtype = tvm.testing.parameter(\"int8\", \"int16\")\n    data_layout = tvm.testing.parameter(\"NWC\")\n    kernel_layout = tvm.testing.parameter(\"WOI\")\n    schedule_name = tvm.testing.parameter(\"conv1d_dsp\")\n\n\nclass TestConv1d_nwc(BasicConv1dTests):\n    \"\"\"This test is for conv1d_nwc.generic schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = tvm.testing.parameters(\n        ((4, 32, 16), 3, 12, 1, 0, 1),\n        ((4, 16, 32), 3, 12, 1, 0, 1),\n        ((4, 32, 16), 3, 12, 1, 0, 1),\n        ((1, 32, 12), 3, 16, 1, 0, 1),\n        ((3, 12, 10), 4, 24, 1, 0, 1),\n        ((1, 7, 7), 3, 5, 1, 0, 1),\n        ((1, 10, 2), 4, 4, 2, (1, 1), 1),\n        ((1, 20, 2), 4, 4, 2, (0, 1), 1),\n        ((1, 16, 4), 1, 12, 1, (1, 0), 1),\n        ((1, 24, 16), 1, 32, 3, (2, 2), 1),\n    )\n    dtype = tvm.testing.parameter(\"int8\", \"int16\")\n    data_layout = tvm.testing.parameter(\"NWC\")\n    kernel_layout = tvm.testing.parameter(\"WIO\")\n    schedule_name = tvm.testing.parameter(\"conv1d_nwc.generic\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for arm_cpu schedules for regular conv2d.\"\"\"\n\nfrom test_generalized_conv2d import GeneralizedConv2dTests\nfrom tvm.testing import fixture, main, parameter, parameters\n\n\nclass Conv2dTests(GeneralizedConv2dTests):\n    \"\"\"Helper for constructing regular Conv2ds. Always sets groups to 1. We set the reference\n    kernel layout here as we must pick something, but the x86 implementation supports several.\"\"\"\n\n    @fixture\n    def groups(self):\n        \"\"\"Using a fixture instead of a parameter stops Pytest from adding the (redundant) number of\n        groups to the name of each test.\"\"\"\n        return 1\n\n    def setup_method(self):\n        self.ref_kernel_layout = \"HWIO\"\n\n\nclass TestConv2d_NHWC_DSP(Conv2dTests):\n    \"\"\"This test is for conv2d_nhwc_dsp.arm_cpu schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        # TODO(mehrdadh): Fails due to https://github.com/apache/tvm/issues/11216\n        # ((1, 32, 32, 1), (3, 3), 12, 1, 0, 1),\n        # ((1, 32, 10, 3), (3, 3), 16, 1, 0, 1),\n        # ((1, 49, 10, 1), (10, 4), 64, (2, 1), (4, 1, 5, 1), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n        # from Keyword Spotting model from MLPerfTiny models\n        # TODO(mehrdad): Fails due to https://github.com/apache/tvm/issues/11216\n        # ((1, 49, 10, 1), (10, 4), 64, (2, 2), (4, 1, 5, 1), 1),\n        # from Visual Wake Word model from MLPerfTiny models\n        # TODO(mehrdadh): fails due to https://github.com/apache/tvm/issues/11216\n        # ((1, 96, 96, 3), (3, 3), 8, (2, 2), (0, 0, 1, 1), 1),\n        # from Image Classification model from MLPerfTiny models\n        ((1, 16, 16, 32), (1, 1), 64, (2, 2), 0, 1),\n        ((4, 16, 16, 8), (5, 5), 8, 2, (0, 4, 4, 0), 1),\n        ((4, 16, 16, 8), (5, 5), 16, 2, (0, 4, 4, 0), 1),\n        ((4, 16, 16, 8), (5, 5), 8, 2, 0, 1),\n        ((4, 16, 16, 8), (5, 5), 16, 2, 0, 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (0, 0, 1, 1), 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (1, 1, 2, 2), 1),\n        ((1, 16, 16, 8), (5, 5), 16, 2, (3, 3, 2, 2), 1),\n        ((1, 16, 16, 8), (3, 3), 16, 2, (0, 1, 2, 3), 1),\n    )\n    in_dtype = parameter(\"int8\", \"int16\")\n\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"HWOI\")\n    out_layout = parameter(\"NHWC\")\n    schedule_name = parameter(\"conv2d_nhwc_dsp.arm_cpu\")\n\n\nclass TestConv2d_NHWC_Spatial_Pack(Conv2dTests):\n    \"\"\"This test is for conv2d_nhwc_spatial_pack.arm_cpu schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        ((1, 32, 32, 1), (3, 3), 12, 1, 0, 1),\n        ((1, 32, 10, 3), (3, 3), 16, 1, 0, 1),\n        ((1, 49, 10, 1), (10, 4), 64, (2, 1), (4, 1, 5, 1), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n    )\n    in_dtype = parameter(\"int8\", \"int16\")\n\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"HWIO\")\n    out_layout = parameter(\"NHWC\")\n    schedule_name = parameter(\"conv2d_nhwc_spatial_pack.arm_cpu\")\n\n\nclass TestConv2d_Tensordot(Conv2dTests):\n    \"\"\"This test is for the regular conv2d schedule tensorized using tensordot.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding = parameters(\n        # Disabled because these kernels are not an integral number of words\n        # ((1, 32, 32, 1), (3, 3), 12, 1, 0),\n        # ((1, 32, 10, 3), (3, 3), 16, 1, 0),\n        # ((1, 96, 96, 3), (3, 3), 8, (2, 2), (0, 0, 1, 1)),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0)),\n        ((1, 16, 16, 32), (1, 1), 64, (2, 2), 0),\n        ((1, 49, 10, 1), (10, 4), 64, (2, 1), (4, 1, 5, 1)),\n        ((4, 16, 16, 16), (5, 5), 8, 2, 0),\n    )\n    dilation = parameter(1)\n    in_dtype = parameter(\"int8\", \"int16\", \"int32\")\n\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"OHWI\")\n    out_layout = parameter(\"NHWC\", \"NCHW\")\n    schedule_name = parameter(\"conv2d_nhwc_ohwi_dsp.arm_cpu\")\n\n\nclass TestConv2d_NCHW_Spatial_Pack(Conv2dTests):\n    \"\"\"This test is for conv2d_nchw_spatial_pack.arm_cpu schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation, in_dtype = parameters(\n        ((1, 32, 32, 16), (3, 3), 12, 1, 0, 1, \"int8\"),\n        ((1, 32, 32, 16), (3, 3), 12, 1, 0, 1, \"int16\"),\n        ((1, 16, 16, 32), (3, 3), 12, 1, 0, 1, \"int16\"),\n    )\n    data_layout = parameter(\"NCHW\")\n    kernel_layout = parameter(\"OIHW\")\n    out_layout = parameter(\"NCHW\")\n    schedule_name = parameter(\"conv2d_nchw_spatial_pack.arm_cpu\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_conv2d_NCHWc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicConv2dTests:\n    @tvm.testing.requires_corstone300\n    def test_conv2d_NCHWc(\n        self,\n        data_shape,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        num_filter,\n        strides,\n        padding,\n        dilation,\n        dtype,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single conv2d_NCHWc operator.\"\"\"\n        ishape = data_shape\n        wshape = (num_filter, data_shape[1], *kernel_size)\n        weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight0 = relay.const(weight_data)\n        out0 = relay.op.nn.contrib_conv2d_nchwc(\n            relay.layout_transform(input0, \"NCHW\", data_layout),\n            relay.layout_transform(weight0, \"OIHW\", kernel_layout),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            channels=num_filter,\n            out_dtype=\"\",\n            out_layout=\"\",\n        )\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight1 = relay.const(weight_data)\n        out1 = relay.op.nn.contrib_conv2d_nchwc(\n            relay.layout_transform(input1, \"NCHW\", data_layout),\n            relay.layout_transform(weight1, \"OIHW\", kernel_layout),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            channels=num_filter,\n            out_dtype=\"\",\n            out_layout=\"\",\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestConv2d_NCHWc(BasicConv2dTests):\n    \"\"\"This test is for conv2d_NCHWc.x86 schedule.\"\"\"\n\n    (\n        data_shape,\n        kernel_size,\n        num_filter,\n        strides,\n        padding,\n        dilation,\n        dtype,\n        kernel_layout,\n        data_layout,\n    ) = tvm.testing.parameters(\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int16\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int32\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW2i8o\", \"NCHW8c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int16\", \"OIHW2i8o\", \"NCHW8c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1), (1, 1), \"int32\", \"OIHW2i8o\", \"NCHW8c\"),\n        # ResNet18 workloads\n        # this test does not fit in corstone300 DCTM section.\n        # ((1, 3, 112, 112), (7, 7), 64, (2, 2), (3, 3), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 64, 28, 28), (3, 3), 64, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 64, 28, 28), (1, 1), 64, (1, 1), (0, 0), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 64, 28, 28), (3, 3), 128, (2, 2), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 64, 28, 28), (1, 1), 128, (2, 2), (0, 0), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 128, 14, 14), (3, 3), 128, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 128, 14, 14), (3, 3), 256, (2, 2), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 128, 14, 14), (1, 1), 256, (2, 2), (0, 0), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 256, 7, 7), (3, 3), 256, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 256, 7, 7), (3, 3), 512, (2, 2), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 256, 7, 7), (1, 1), 512, (2, 2), (0, 0), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n        ((1, 512, 3, 3), (3, 3), 512, (1, 1), (1, 1), (1, 1), \"int8\", \"OIHW4i4o\", \"NCHW4c\"),\n    )\n    schedule_name = tvm.testing.parameter(\"conv2d_NCHWc.x86\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_dense_dsp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicDenseTests:\n    @tvm.testing.requires_corstone300\n    def test_dense(self, shape, weight_shape, dtype, schedule_name, enable_bias):\n        \"\"\"Test a subgraph with a single dense operator.\"\"\"\n        ishape = shape\n        wshape = weight_shape\n        out_dtype = \"int32\"\n        units = weight_shape[0]\n        weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n        if enable_bias:\n            bias_data = np.random.randint(low=-10, high=10, size=(wshape[0]), dtype=out_dtype)\n\n        input = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight = relay.const(weight_data)\n        dense = relay.op.nn.dense(\n            input,\n            weight,\n            units=units,\n            out_dtype=out_dtype,\n        )\n        if enable_bias:\n            bias = relay.const(bias_data)\n            relay_op = relay.op.nn.bias_add(dense, bias)\n        else:\n            relay_op = dense\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input], relay_op))\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        mod = tvm.IRModule.from_expr(relay.Function([input], relay_op))\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestDense(BasicDenseTests):\n    \"\"\"This test is for dense_dsp schedule.\"\"\"\n\n    shape, weight_shape = tvm.testing.parameters(\n        ((8, 128), (32, 128)),\n        ((32, 32), (32, 32)),\n        ((1, 64), (1, 64)),\n        ((11, 2), (2, 2)),\n        ((1, 32), (64, 32)),\n        ((3, 12), (10, 12)),\n    )\n    dtype = tvm.testing.parameter(\"int8\", \"int16\")\n    schedule_name = tvm.testing.parameter(\"dense_dsp.arm_cpu\")\n    enable_bias = tvm.testing.parameter(False, True)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for arm_cpu schedules for depthwise_conv2d.\"\"\"\n\nfrom test_generalized_conv2d import GeneralizedConv2dTests\nfrom tvm.testing import fixture, main, parameter, parameters\n\n\nclass DepthwiseConv2dTests(GeneralizedConv2dTests):\n    \"\"\"Helper for constructing depthwise Conv2ds. Sets the reference kernel layout to what x86 code\n    supports.\"\"\"\n\n    @fixture\n    def groups(self, data_shape):\n        \"\"\"By definition, a depthwise_conv2d has a number of groups equal to the number of input\n        channels, so we don't need to specify the number of groups each time.\"\"\"\n        return data_shape[3]\n\n    def setup_method(self):\n        self.ref_kernel_layout = \"HWOI\"\n\n\nclass TestDepthwiseConv2d_NCHW_OIHW(DepthwiseConv2dTests):\n    \"\"\"This test is for depthwise_conv2d_nchw.arm_cpu schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 10, 3, 32), (3, 3), 32, 1, 0, 1),\n        ((1, 32, 16, 32), (3, 3), 32, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 16, 32), (3, 3), 32, 1, 0, 1),\n        ((1, 32, 16, 32), (3, 3), 32, 1, 0, 1),\n        ((1, 32, 16, 32), (3, 3), 32, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 16, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n    )\n\n    in_dtype = parameter(\"int8\", \"int16\")\n    data_layout = parameter(\"NCHW\")\n    kernel_layout = parameter(\"OIHW\")\n    out_layout = parameter(\"NCHW\")\n    schedule_name = parameter(\"depthwise_conv2d_nchw.arm_cpu\")\n\n\nclass TestDepthwiseConv2d_NHWC_HWOI(DepthwiseConv2dTests):\n    \"\"\"This test is for depthwise_conv2d_nhwc.generic schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 10, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 49, 10, 64), (10, 4), 64, (2, 1), (4, 1, 5, 1), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n    )\n\n    in_dtype = parameter(\"int8\", \"int16\")\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"HWOI\")\n    out_layout = parameter(\"NHWC\")\n    schedule_name = parameter(\"depthwise_conv2d_nhwc.generic\")\n\n\nclass TestDepthwiseConv2d_NHWC_HWOI_DSP(DepthwiseConv2dTests):\n    \"\"\"This test is for depthwise_conv2d_nhwc_dsp.arm_cpu schedule. The tests that are parameterized\n    by dtype work for both int8 and int16, while the others only work on the specified dtype.\"\"\"\n\n    in_dtype_parameterized_tests = [\n        # Depthwise_conv2d parameters from MobileNetV1 0.25x\n        ((1, 48, 48, 8), (3, 3), 8, (1, 1), 1),\n        ((1, 48, 48, 16), (3, 3), 16, (2, 2), (1, 1, 0, 0)),\n        ((1, 24, 24, 32), (3, 3), 32, (1, 1), 1),\n        ((1, 24, 24, 32), (3, 3), 32, (2, 2), (1, 1, 0, 0)),\n        ((1, 12, 12, 64), (3, 3), 64, (1, 1), 1),\n        ((1, 12, 12, 64), (3, 3), 64, (2, 2), (1, 1, 0, 0)),\n        ((1, 6, 6, 128), (3, 3), 128, (1, 1), 1),\n        ((1, 6, 6, 128), (3, 3), 128, (2, 2), (1, 1, 0, 0)),\n        ((1, 3, 3, 256), (3, 3), 256, (1, 1), 1),\n        # Asymmetric and larger kernels\n        ((1, 25, 5, 64), (3, 3), 64, (1, 1), 1),\n        ((1, 24, 24, 8), (5, 5), 8, (1, 1), 1),\n        ((1, 24, 24, 8), (3, 5), 8, (1, 1), 1),\n    ]\n\n    data_shape, kernel_size, num_filter, strides, padding, in_dtype = parameters(\n        # Make a copy of each parameterized test for int8 and one for int16\n        *map(lambda t: t + (\"int8\",), in_dtype_parameterized_tests),\n        *map(lambda t: t + (\"int16\",), in_dtype_parameterized_tests),\n        # Test the int16 implementation with channel numbers not divisible by four\n        ((1, 48, 48, 6), (3, 3), 6, (1, 1), 1, \"int16\"),\n    )\n    dilation = parameter(1)\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"HWOI\")\n    out_layout = parameter(\"NHWC\")\n    schedule_name = parameter(\"depthwise_conv2d_nhwc_dsp.arm_cpu\")\n\n\nclass TestDepthwiseConv2d_Tensordot(DepthwiseConv2dTests):\n    \"\"\"This test is for the depthwise_conv2d schedule tensorized using tensordot.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, in_dtype = parameters(\n        # Currently, our schedule requires kernel_w be divisible by the number of simd lanes given\n        # its dtype. This means 3x3 and 5x5 kernels do not work on int16 or int8 for now. If you had\n        # to, you could hack around this by padding the data and kernel.\n        ((1, 48, 48, 8), (3, 3), 8, (1, 1), 1, \"int32\"),\n        ((1, 48, 48, 16), (3, 3), 16, (2, 2), (1, 1, 0, 0), \"int32\"),\n        ((1, 24, 24, 32), (3, 3), 32, (1, 1), 1, \"int32\"),\n        ((1, 24, 24, 32), (3, 3), 32, (2, 2), (1, 1, 0, 0), \"int32\"),\n        ((1, 12, 12, 64), (3, 3), 64, (1, 1), 1, \"int32\"),\n        ((1, 12, 12, 64), (3, 3), 64, (2, 2), (1, 1, 0, 0), \"int32\"),\n        ((1, 6, 6, 128), (3, 3), 128, (1, 1), 1, \"int32\"),\n        ((1, 6, 6, 128), (3, 3), 128, (2, 2), (1, 1, 0, 0), \"int32\"),\n        ((1, 3, 3, 256), (3, 3), 256, (1, 1), 1, \"int32\"),\n        ((1, 25, 5, 64), (3, 3), 64, (1, 1), 1, \"int32\"),\n        ((1, 24, 24, 8), (5, 5), 8, (1, 1), 1, \"int32\"),\n        ((1, 24, 24, 8), (3, 5), 8, (1, 1), 1, \"int32\"),\n        # These \"evenly divisible\" kernels work on smaller dtypes.\n        ((1, 48, 48, 8), (3, 2), 8, 1, 0, \"int16\"),\n        ((1, 48, 48, 8), (4, 4), 8, 1, 0, \"int8\"),\n    )\n    dilation = parameter(1)\n\n    data_layout = parameter(\"NCHW\")\n    kernel_layout = parameter(\"OIHW\")\n    out_layout = parameter(\"NHWC\", \"NCHW\")\n    schedule_name = parameter(\"depthwise_conv2d_nchw_oihw_dsp.arm_cpu\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_depthwise_conv2d_NCHWc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicConv2dTests:\n    @tvm.testing.requires_corstone300\n    def test_depthwise_conv2d_NCHWc(\n        self,\n        data_shape,\n        kernel_size,\n        data_layout,\n        kernel_layout,\n        groups,\n        strides,\n        padding,\n        dilation,\n        dtype,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single depthwise_conv2d_nchwc operator.\"\"\"\n        ishape = data_shape\n        wshape = (data_shape[1], 1, *kernel_size)\n        weight_data = np.random.randint(low=-10, high=10, size=wshape, dtype=dtype)\n        groups = groups\n\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight0 = relay.const(weight_data)\n        out0 = relay.op.nn.contrib_depthwise_conv2d_nchwc(\n            relay.layout_transform(input0, \"NCHW\", data_layout),\n            relay.layout_transform(weight0, \"OIHW\", kernel_layout),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            groups=groups,\n            out_dtype=\"\",\n            out_layout=\"\",\n        )\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        weight1 = relay.const(weight_data)\n        out1 = relay.op.nn.contrib_depthwise_conv2d_nchwc(\n            relay.layout_transform(input1, \"NCHW\", data_layout),\n            relay.layout_transform(weight1, \"OIHW\", kernel_layout),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            dilation=dilation,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            groups=groups,\n            out_dtype=\"\",\n            out_layout=\"\",\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestDepthWiseConv2d_NCHWc(BasicConv2dTests):\n    \"\"\"This test is for depthwise_conv2d_NCHWc schedule.\"\"\"\n\n    (\n        data_shape,\n        kernel_size,\n        groups,\n        strides,\n        padding,\n        dilation,\n        kernel_layout,\n        data_layout,\n    ) = tvm.testing.parameters(\n        ((1, 16, 32, 32), (3, 3), 16, (1, 1), (1, 1, 1, 1), (1, 1), \"OIHW1i4o\", \"NCHW4c\"),\n        ((1, 16, 32, 32), (3, 3), 12, (1, 1), (1, 1, 1, 1), (1, 1), \"OIHW1i8o\", \"NCHW8c\"),\n    )\n    dtype = tvm.testing.parameter(\"int8\", \"int16\", \"int32\")\n    schedule_name = tvm.testing.parameter(\"depthwise_conv2d_NCHWc\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_generalized_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Helper class for testing variations of 2D convolution. Should be used by subclassing\n`GeneralizedConv2dTests`, and then setting the arguments using tvm.testing.parameter(s).\"\"\"\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import AOT_CORSTONE300_RUNNER\n\n\ndef _change_ndarray_layout(arr, src_layout, dst_layout):\n    \"\"\"Makes a copy of an ndarray, reshaping it to a new data layout.\n\n    Parameter\n    ---------\n    arr : numpy.ndarray\n        The ndarray to be reformatted.\n\n    src_layout : str\n        The current layout of the Relay constant. Must be alphabetic (e.g. NHWC\n        or OIHW, but not NCHW2c).\n\n    dst_layout : str\n        The desired layout of new the Relay constant. Must be alphabetic (e.g. NHWC\n        or OIHW, but not NCHW2c).\n\n    Returns\n    -------\n    dst_shape : numpy.ndarray\n        A copy of the ndarray with the new layout.\n    \"\"\"\n    assert src_layout.isalpha() and dst_layout.isalpha()\n    axis_order = [src_layout.index(c) for c in dst_layout]\n    return np.transpose(arr, axis_order)\n\n\nclass GeneralizedConv2dTests:\n    \"\"\"Superclass which can be used to test regular, depthwise, or grouped conv2D. Cannot be used\n    for 5D data formats (NCHWc and such) as written, but could be extended. Might also be worth\n    abstracting some of this logic into an even more general class that could be used for other\n    operators.\n\n    Note that data_shape should always be a tuple of length four indicating the data shape in NHWC\n    format (it will later be reshaped according to the given data_layout), and kernel_size should be\n    a length two tuple giving the height and width of the kernel.\n\n    This test (and other base Conv2dTests classes) are not run by Pytest, as their names do not\n    start with `Test`.\"\"\"\n\n    @tvm.testing.requires_corstone300\n    def test_conv2d(\n        self,\n        data_shape,\n        kernel_size,\n        num_filter,\n        in_dtype,\n        strides,\n        padding,\n        groups,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n\n        ref_input_data = np.random.randint(low=-128, high=127, size=data_shape, dtype=in_dtype)\n        ref_input_var = relay.var(\"input\", relay.TensorType(data_shape, in_dtype))  # NHWC layout\n        kernel_shape = (*kernel_size, data_shape[-1] // groups, num_filter)  # HWIO layout\n        ref_kernel_data = np.random.randint(low=-10, high=10, size=kernel_shape, dtype=in_dtype)\n\n        \"\"\"Our x86 depthwise implementation only supports HWOI with NHWC, so we need to change our\n        kernel layout to work around this. We can't just change the whole thing to HWIO or\n        something else, as then group conv2d would not work. Eventually, we should switch to using\n        TensorFlow to create the reference output so we can ensure our implementation is right.\n        See https://github.com/apache/tvm/issues/13137 for details.\"\"\"\n\n        ref_relay_op = relay.op.nn.conv2d(\n            ref_input_var,\n            relay.const(_change_ndarray_layout(ref_kernel_data, \"HWIO\", self.ref_kernel_layout)),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            groups=groups,\n            dilation=(dilation, dilation),\n            data_layout=\"NHWC\",\n            kernel_layout=self.ref_kernel_layout,\n            out_dtype=\"int32\",\n            out_layout=\"NHWC\",\n        )\n        ref_module = tvm.IRModule.from_expr(relay.Function([ref_input_var], ref_relay_op))\n        ref_outputs = generate_ref_data(ref_module, {\"input\": ref_input_data})\n\n        # Reshape output dictionary to match out_layout\n        assert len(ref_outputs) == 1\n        output_tensor_name, output_tensor = next(iter(ref_outputs.items()))\n        ref_outputs[output_tensor_name] = _change_ndarray_layout(output_tensor, \"NHWC\", out_layout)\n\n        test_input_data = _change_ndarray_layout(ref_input_data, \"NHWC\", data_layout)\n        test_input_var = relay.var(\"input\", relay.TensorType(test_input_data.shape, in_dtype))\n        test_kernel_data = _change_ndarray_layout(ref_kernel_data, \"HWIO\", kernel_layout)\n\n        test_relay_op = relay.op.nn.conv2d(\n            test_input_var,\n            relay.const(test_kernel_data),\n            kernel_size=kernel_size,\n            strides=strides,\n            padding=padding,\n            groups=groups,\n            dilation=(dilation, dilation),\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            out_dtype=\"int32\",\n            out_layout=out_layout,\n        )\n        test_function = relay.Function([test_input_var], test_relay_op)\n        test_model = AOTTestModel(\n            module=tvm.IRModule.from_expr(test_function),\n            inputs={\"input\": test_input_data},\n            outputs=ref_outputs,\n        )\n\n        compile_and_run(\n            test_model,\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for arm_cpu schedules for grouped conv2d.\"\"\"\n\nfrom test_generalized_conv2d import GeneralizedConv2dTests\nfrom tvm.testing import main, parameter, parameters\n\n\nclass GroupConv2dTests(GeneralizedConv2dTests):\n    \"\"\"Helper for constructing group Conv2ds. Sets the reference kernel layout to what x86 code\n    supports.\"\"\"\n\n    def setup_method(self):\n        self.ref_kernel_layout = \"HWIO\"\n\n\nclass TestGroupConv2d_NCHW_OIHW(GroupConv2dTests):\n    \"\"\"This test is for group_conv2d_nchw.arm_cpu schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        ((1, 32, 32, 16), (3, 3), 12, 1, 0, 1),\n        ((1, 32, 10, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 32, 1, (1, 1, 2, 2), 2),\n    )\n    groups = parameter(2, 4)\n    in_dtype = parameter(\"int8\", \"int16\")\n\n    data_layout = parameter(\"NCHW\")\n    kernel_layout = parameter(\"OIHW\")\n    out_layout = parameter(\"NCHW\")\n    schedule_name = parameter(\"group_conv2d_nchw.arm_cpu\")\n\n\nclass TestGroupConv2d_NHWC_HWIO(GroupConv2dTests):\n    \"\"\"This test is for group_conv2d_nhwc.generic schedule.\"\"\"\n\n    data_shape, kernel_size, num_filter, strides, padding, dilation = parameters(\n        ((1, 32, 32, 16), (3, 3), 12, 1, 0, 1),\n        ((1, 32, 10, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 49, 10, 16), (10, 4), 64, (2, 1), (4, 1, 5, 1), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, 0, 1),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (0, 2, 2, 0), 2),\n        ((1, 32, 32, 16), (3, 3), 16, 1, (1, 1, 2, 2), 2),\n    )\n    groups = parameter(2, 4)\n    in_dtype = parameter(\"int8\", \"int16\")\n\n    data_layout = parameter(\"NHWC\")\n    kernel_layout = parameter(\"HWIO\")\n    out_layout = parameter(\"NHWC\")\n    schedule_name = parameter(\"group_conv2d_nhwc.generic\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/strategy/arm_cpu/test_max_pool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.testing.aot import AOTTestModel, compile_and_run, generate_ref_data\nfrom tvm.micro.testing.aot_test_utils import (\n    AOT_CORSTONE300_RUNNER,\n)\n\n\nclass BasicPoolTests:\n    @tvm.testing.requires_corstone300\n    def test_pool(\n        self,\n        pool_type,\n        shape,\n        dtype,\n        pool_size,\n        strides,\n        padding,\n        dilation,\n        layout,\n        ceil_mode,\n        schedule_name,\n    ):\n        \"\"\"Test a subgraph with a single max_pool operator.\"\"\"\n        ishape = shape\n        input0 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n\n        out0 = getattr(relay.op.nn, pool_type)(\n            input0,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=layout,\n            out_layout=\"\",\n            ceil_mode=ceil_mode,\n        )\n\n        ref_mod = tvm.IRModule.from_expr(relay.Function([input0], out0))\n\n        input1 = relay.var(\"input\", relay.TensorType(ishape, dtype))\n        out1 = getattr(relay.op.nn, pool_type)(\n            input1,\n            pool_size=pool_size,\n            strides=strides,\n            dilation=dilation,\n            padding=padding,\n            layout=layout,\n            out_layout=\"\",\n            ceil_mode=ceil_mode,\n        )\n        mod = tvm.IRModule.from_expr(relay.Function([input1], out1))\n\n        inputs = {\"input\": np.random.randint(low=-128, high=127, size=ishape, dtype=dtype)}\n        output_list = generate_ref_data(ref_mod, inputs)\n\n        compile_and_run(\n            AOTTestModel(module=mod, inputs=inputs, outputs=output_list),\n            runner=AOT_CORSTONE300_RUNNER,\n            interface_api=\"c\",\n            use_unpacked_api=True,\n            target_opts={\n                \"-keys\": \"arm_cpu\",\n                \"-mcpu\": \"cortex-m7\",\n            },\n            schedule_name=schedule_name,\n        )\n\n\nclass TestMaxPool1d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    shape, pool_size, strides, padding, dilation, layout, ceil_mode = tvm.testing.parameters(\n        ((3, 32, 27), (3,), (2,), 0, 1, \"NCW\", True),\n        ((1, 32, 1), 3, 1, 0, 1, \"NWC\", False),\n        ((1, 20, 4), 3, 2, 0, 1, \"NWC\", False),\n    )\n    pool_type = tvm.testing.parameter(\"max_pool1d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nclass TestMaxPool2d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    shape, pool_size, strides, padding, dilation, layout, ceil_mode = tvm.testing.parameters(\n        ((2, 32, 27, 27), (3, 3), (2, 2), 0, 1, \"NCHW\", False),\n        ((2, 32, 27, 27), (3, 3), (2, 2), 0, 1, \"NCHW\", True),\n        ((1, 26, 26, 12), (2, 2), (2, 2), 0, 1, \"NHWC\", False),\n        ((1, 11, 11, 32), (2, 2), (2, 2), 0, 1, \"NHWC\", False),\n        ((1, 3, 3, 64), (2, 2), (2, 2), 0, 1, \"NHWC\", False),\n        ((1, 32, 32, 1), (3, 3), 1, 0, 1, \"NHWC\", False),\n        ((1, 32, 20, 4), (3, 3), (2, 2), 0, 1, \"NHWC\", False),\n        ((1, 32, 32, 1), (3, 3), 1, 0, 1, \"NHWC\", True),\n        ((1, 32, 20, 4), (3, 3), (2, 2), 0, 1, \"NHWC\", True),\n    )\n    pool_type = tvm.testing.parameter(\"max_pool2d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nclass TestMaxPool3d(BasicPoolTests):\n    \"\"\"This test is for pool.arm_cpu schedule.\"\"\"\n\n    shape, pool_size, strides, padding, dilation, layout, ceil_mode = tvm.testing.parameters(\n        ((3, 4, 8, 27, 27), (3, 3, 3), 2, 0, 1, \"NCDHW\", False),\n    )\n    pool_type = tvm.testing.parameter(\"max_pool3d\")\n    dtype = tvm.testing.parameter(\"int32\")\n    schedule_name = tvm.testing.parameter(\"pool.arm_cpu\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_adt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.relay.backend.interpreter import ConstructorValue\nfrom tvm.relay import create_executor\nfrom tvm.relay.prelude import Prelude, StaticTensorArrayOps\nfrom tvm.relay.testing import count as count_, make_nat_value, make_nat_expr\n\nimport numpy as np\n\nprelude = p = Prelude(tvm.IRModule({}))\np.mod.import_from_std(\"nat.rly\")\n\n\ndef count(e):\n    return count_(p, e)\n\n\ndev = tvm.device(\"llvm\", 0)\n\n\ndef eval(expr):\n    # CAUTION: These tests re-process the entire prelude for each test expression.\n    # Hoisting the create_executor won't improve that since preprocessing won't begin\n    # until the evaluate.\n    return create_executor(mod=prelude.mod, device=dev, target=\"llvm\").evaluate(expr)\n\n\nnat, z, s = prelude.mod.get_type(\"nat\")\n\ndouble = p.mod.get_global_var(\"nat_double\")\nadd = p.mod.get_global_var(\"nat_add\")\n\noptional, some, none = prelude.mod.get_type(\"Option\")\nrlist, cons, nil = prelude.mod.get_type(\"List\")\n\nhd = p.hd\ntl = p.tl\nnth = p.nth\nupdate = p.update\nlength = p.length\nmap = p.map\nfoldl = p.foldl\nfoldr = p.foldr\nfoldr1 = p.foldr1\nsum = p.sum\n\nconcat = p.concat\nfilter = p.filter\nzip = p.zip\nrev = p.rev\nunfoldl = p.unfoldl\nunfoldr = p.unfoldr\nmap_accumr = p.map_accumr\nmap_accuml = p.map_accuml\n\ntree, rose = prelude.mod.get_type(\"Tree\")\n\ntmap = p.tmap\nsize = p.size\n\ncompose = p.compose\niterate = p.iterate\n\n\ndef to_list(l):\n    assert isinstance(l, ConstructorValue)\n    val = l\n    ret = []\n    while True:\n        if val.tag == cons.tag:\n            ret.append(val.fields[0])\n            val = val.fields[1]\n        else:\n            assert val.tag == nil.tag\n            break\n    return ret\n\n\ndef tree_to_dict(t):\n    assert isinstance(t, ConstructorValue)\n    ret = {}\n    assert t.tag == rose.tag\n    ret[\"member\"] = t.fields[0]\n    ret[\"children\"] = []\n    for subtree in to_list(t.fields[1]):\n        l = tree_to_dict(subtree)\n        ret[\"children\"].append(l)\n    return ret\n\n\ndef vmobj_to_list(o, dtype=\"float32\"):\n    if isinstance(o, tvm.nd.NDArray):\n        return [o.numpy().tolist()]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        if len(o) == 0:\n            tensor_nil = p.get_var(\"tensor_nil\", dtype=dtype)\n            if tensor_nil.tag == o.tag:\n                return [0]\n            return []\n\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(f, dtype))\n        return result\n    elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):\n        if o.constructor.name_hint == \"Cons\":\n            tl = vmobj_to_list(o.fields[1], dtype)\n            hd = vmobj_to_list(o.fields[0], dtype)\n            hd.extend(tl)\n            return hd\n        elif o.constructor.name_hint == \"Nil\":\n            return []\n        elif \"tensor_nil\" in o.constructor.name_hint:\n            return [0]\n        elif \"tensor\" in o.constructor.name_hint:\n            return [o.fields[0].numpy()]\n        else:\n            raise RuntimeError(\"Unknown object type: %s\" % o.constructor.name_hint)\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\n# turns a scalar-valued relay tensor value into a python number\ndef get_scalar(tv):\n    return tv.numpy().item()\n\n\n# @tvm.testing.uses_gpu\ndef test_nat_value():\n    assert count(make_nat_value(p, 10)) == 10\n    assert count(eval(s(s(z())))) == 2\n\n\n@tvm.testing.uses_gpu\ndef test_nat_constructor():\n    func = relay.Function([], z())\n    test_z = relay.GlobalVar(\"test_z\")\n    test_sz = relay.GlobalVar(\"test_sz\")\n    prelude.mod[test_z] = func\n    func = relay.Function([], s(z()))\n    prelude.mod[test_sz] = func\n    ck_mod = relay.transform.InferType()(prelude.mod)\n    assert ck_mod[test_z].body.checked_type == nat()\n    assert ck_mod[test_sz].body.checked_type == nat()\n\n\n@tvm.testing.uses_gpu\ndef test_double():\n    assert prelude.mod[double].checked_type == relay.FuncType([nat()], nat())\n    res = eval(double(s(z())))\n    assert count(res) == 2\n\n\n@tvm.testing.uses_gpu\ndef test_add():\n    assert prelude.mod[add].checked_type == relay.FuncType([nat(), nat()], nat())\n    res = eval(add(s(z()), s(z())))\n    assert count(res) == 2\n\n\n@tvm.testing.uses_gpu\ndef test_list_constructor():\n    test_consz = relay.GlobalVar(\"test_consz\")\n    func = relay.Function([], cons(z(), nil()))\n    prelude.mod[test_consz] = func\n    ck_mod = relay.transform.InferType()(prelude.mod)\n    assert ck_mod[test_consz].body.checked_type == rlist(nat())\n\n\n@tvm.testing.uses_gpu\ndef test_hd_tl():\n    expected = list(range(10))\n    l = nil()\n    for i in reversed(expected):\n        l = cons(make_nat_expr(prelude, i), l)\n\n    got = []\n    for i in range(len(expected)):\n        got.append(count(eval(hd(l))))\n        l = tl(l)\n\n    assert got == expected\n\n\n@tvm.testing.uses_gpu\ndef test_nth():\n    expected = list(range(10))\n    l = nil()\n    for i in reversed(expected):\n        l = cons(relay.const(i), l)\n\n    for i in range(len(expected)):\n        nth = prelude.mod.get_global_var(\"nth\")\n        item = eval(nth(l, relay.const(i)))\n        assert get_scalar(item) == i\n\n\n@tvm.testing.uses_gpu\ndef test_update():\n    expected = list(range(10))\n    l = nil()\n    # create zero initialized list\n    for i in range(len(expected)):\n        l = cons(make_nat_expr(prelude, 0), l)\n\n    # set value\n    for i, v in enumerate(expected):\n        l = update(l, relay.const(i), make_nat_expr(prelude, v))\n\n    got = []\n    for i in range(len(expected)):\n        got.append(count(eval(nth(l, relay.const(i)))))\n\n    assert got == expected\n\n\n@tvm.testing.uses_gpu\ndef test_length():\n    a = relay.TypeVar(\"a\")\n    assert prelude.mod[length].checked_type == relay.FuncType(\n        [rlist(a)], relay.scalar_type(\"int32\"), [a]\n    )\n    res = eval(length(cons(z(), cons(z(), cons(z(), nil())))))\n    assert get_scalar(res) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_map():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    lhs = prelude.mod[map].checked_type\n    rhs = relay.FuncType([relay.FuncType([a], b), rlist(a)], rlist(b), [a, b])\n    assert lhs == rhs\n\n    x = relay.Var(\"x\")\n    add_one = relay.Function([x], s(x))\n    res = eval(map(add_one, cons(z(), cons(z(), nil()))))\n    ones = to_list(res)\n    assert len(ones) == 2\n    assert count(ones[0]) == 1 and count(ones[1]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_foldl():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n\n    lhs = prelude.mod[foldl].checked_type\n    rhs = relay.FuncType([relay.FuncType([a, b], a), a, rlist(b)], a, [a, b])\n    assert lhs == rhs\n\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    rev_dup = relay.Function([y, x], cons(x, cons(x, y)))\n    res = eval(\n        foldl(\n            rev_dup,\n            nil(),\n            cons(\n                make_nat_expr(prelude, 1),\n                cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n            ),\n        )\n    )\n    reversed = to_list(res)\n    assert len(reversed) == 6\n    assert count(reversed[0]) == 3 and count(reversed[1]) == 3\n    assert count(reversed[2]) == 2 and count(reversed[3]) == 2\n    assert count(reversed[4]) == 1 and count(reversed[5]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_foldr():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    lhs = prelude.mod[foldr].checked_type\n    rhs = relay.FuncType([relay.FuncType([a, b], b), b, rlist(a)], b, [a, b])\n    assert lhs == rhs\n\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    identity = relay.Function([x, y], cons(x, y))\n    res = eval(\n        foldr(\n            identity,\n            nil(),\n            cons(\n                make_nat_expr(prelude, 1),\n                cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n            ),\n        )\n    )\n    same = to_list(res)\n    assert len(same) == 3\n    assert count(same[0]) == 1 and count(same[1]) == 2 and count(same[2]) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_foldr1():\n    a = relay.TypeVar(\"a\")\n    lhs = prelude.mod[foldr1].checked_type\n    rhs = relay.FuncType([relay.FuncType([a, a], a), rlist(a)], a, [a])\n    assert lhs == rhs\n\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    f = relay.Function([x, y], add(x, y))\n    res = eval(\n        foldr1(\n            f,\n            cons(\n                make_nat_expr(prelude, 1),\n                cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n            ),\n        )\n    )\n\n    assert count(res) == 6\n\n\n@tvm.testing.uses_gpu\ndef test_sum():\n    assert prelude.mod[sum].checked_type == relay.FuncType(\n        [rlist(relay.scalar_type(\"int32\"))], relay.scalar_type(\"int32\")\n    )\n    res = eval(sum(cons(relay.const(1), cons(relay.const(2), nil()))))\n    assert get_scalar(res) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_concat():\n    a = relay.TypeVar(\"a\")\n    assert prelude.mod[concat].checked_type == relay.FuncType([rlist(a), rlist(a)], rlist(a), [a])\n\n    l1 = cons(make_nat_expr(prelude, 1), cons(make_nat_expr(prelude, 2), nil()))\n    l2 = cons(make_nat_expr(prelude, 3), cons(make_nat_expr(prelude, 4), nil()))\n    res = eval(concat(l1, l2))\n\n    catted = to_list(res)\n    assert len(catted) == 4\n    assert count(catted[0]) == 1\n    assert count(catted[1]) == 2\n    assert count(catted[2]) == 3\n    assert count(catted[3]) == 4\n\n\n@tvm.testing.uses_gpu\ndef test_filter():\n    a = relay.TypeVar(\"a\")\n    expected_type = relay.FuncType(\n        [relay.FuncType([a], relay.scalar_type(\"bool\")), rlist(a)], rlist(a), [a]\n    )\n    assert prelude.mod[filter].checked_type == expected_type\n\n    x = relay.Var(\"x\", nat())\n    greater_than_one = relay.Function(\n        [x],\n        relay.Match(\n            x,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(\n                        s, [relay.PatternConstructor(s, [relay.PatternWildcard()])]\n                    ),\n                    relay.const(True),\n                ),\n                relay.Clause(relay.PatternWildcard(), relay.const(False)),\n            ],\n        ),\n    )\n    res = eval(\n        filter(\n            greater_than_one,\n            cons(\n                make_nat_expr(prelude, 1),\n                cons(\n                    make_nat_expr(prelude, 1),\n                    cons(\n                        make_nat_expr(prelude, 3),\n                        cons(\n                            make_nat_expr(prelude, 1),\n                            cons(make_nat_expr(prelude, 5), cons(make_nat_expr(prelude, 1), nil())),\n                        ),\n                    ),\n                ),\n            ),\n        )\n    )\n    filtered = to_list(res)\n    assert len(filtered) == 2\n    assert count(filtered[0]) == 3\n    assert count(filtered[1]) == 5\n\n\n@tvm.testing.uses_gpu\ndef test_zip():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    expected_type = relay.FuncType([rlist(a), rlist(b)], rlist(relay.TupleType([a, b])), [a, b])\n    assert prelude.mod[zip].checked_type == expected_type\n\n    l1 = cons(\n        make_nat_expr(prelude, 1),\n        cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n    )\n    l2 = cons(nil(), cons(cons(nil(), nil()), cons(cons(nil(), cons(nil(), nil())), nil())))\n\n    res = eval(zip(l1, l2))\n    zipped = to_list(res)\n    assert len(zipped) == 3\n    assert count(zipped[0][0]) == 1\n    assert len(to_list(zipped[0][1])) == 0\n    assert count(zipped[1][0]) == 2\n    assert len(to_list(zipped[1][1])) == 1\n    assert count(zipped[2][0]) == 3\n    assert len(to_list(zipped[2][1])) == 2\n\n    # test truncation\n    l3 = cons(make_nat_expr(prelude, 4), cons(make_nat_expr(prelude, 5), nil()))\n    shorter_res = eval(zip(l3, l2))\n    truncated = to_list(shorter_res)\n    assert len(truncated) == 2\n    assert count(truncated[0][0]) == 4\n    assert len(to_list(truncated[0][1])) == 0\n    assert count(truncated[1][0]) == 5\n    assert len(to_list(truncated[1][1])) == 1\n\n    l4 = cons(nil(), nil())\n    shortest_res = eval(zip(l3, l4))\n    singleton = to_list(shortest_res)\n    assert len(singleton) == 1\n    assert count(singleton[0][0]) == 4\n    assert len(to_list(singleton[0][1])) == 0\n\n\n@tvm.testing.uses_gpu\ndef test_rev():\n    a = relay.TypeVar(\"a\")\n    assert prelude.mod[rev].checked_type == relay.FuncType([rlist(a)], rlist(a), [a])\n\n    res = eval(\n        rev(\n            cons(\n                make_nat_expr(prelude, 1),\n                cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n            )\n        )\n    )\n    reversed = to_list(res)\n\n    assert len(reversed) == 3\n    assert count(reversed[0]) == 3\n    assert count(reversed[1]) == 2\n    assert count(reversed[2]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_unfoldr():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    expected_type = relay.FuncType(\n        [relay.FuncType([a], optional(relay.TupleType([a, b]))), a], rlist(b), [a, b]\n    )\n\n    x = relay.Var(\"x\", nat())\n    n = relay.Var(\"n\", nat())\n    count_down = relay.Function(\n        [x],\n        relay.Match(\n            x,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(s, [relay.PatternVar(n)]), some(relay.Tuple([n, x]))\n                ),\n                relay.Clause(relay.PatternConstructor(z, []), none()),\n            ],\n        ),\n    )\n\n    res = eval(unfoldr(count_down, make_nat_expr(prelude, 3)))\n    unfolded = to_list(res)\n\n    assert len(unfolded) == 3\n    assert count(unfolded[0]) == 3\n    assert count(unfolded[1]) == 2\n    assert count(unfolded[2]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_unfoldl():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    expected_type = relay.FuncType(\n        [relay.FuncType([a], optional(relay.TupleType([a, b]))), a], rlist(b), [a, b]\n    )\n\n    x = relay.Var(\"x\", nat())\n    n = relay.Var(\"n\", nat())\n    count_down = relay.Function(\n        [x],\n        relay.Match(\n            x,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(s, [relay.PatternVar(n)]), some(relay.Tuple([n, x]))\n                ),\n                relay.Clause(relay.PatternConstructor(z, []), none()),\n            ],\n        ),\n    )\n\n    res = eval(unfoldl(count_down, make_nat_expr(prelude, 3)))\n    unfolded = to_list(res)\n\n    assert len(unfolded) == 3\n    assert count(unfolded[0]) == 1\n    assert count(unfolded[1]) == 2\n    assert count(unfolded[2]) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_map_accumr():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    c = relay.TypeVar(\"c\")\n    expected_type = relay.FuncType(\n        [relay.FuncType([a, b], relay.TupleType([a, c])), a, rlist(b)],\n        relay.TupleType([a, rlist(c)]),\n        [a, b, c],\n    )\n    assert prelude.mod[map_accumr].checked_type == expected_type\n\n    acc = relay.Var(\"acc\", nat())\n    x = relay.Var(\"x\", nat())\n    add_acc_to_each = relay.Function([acc, x], relay.Tuple([add(x, acc), add(x, acc)]))\n\n    vals = cons(\n        make_nat_expr(prelude, 1),\n        cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n    )\n    res = eval(map_accumr(add_acc_to_each, z(), vals))\n\n    sum = count(res[0])\n    new_vals = to_list(res[1])\n\n    assert sum == 6\n    assert len(new_vals) == 3\n    assert count(new_vals[0]) == 6\n    assert count(new_vals[1]) == 5\n    assert count(new_vals[2]) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_map_accuml():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    c = relay.TypeVar(\"c\")\n    expected_type = relay.FuncType(\n        [relay.FuncType([a, b], relay.TupleType([a, c])), a, rlist(b)],\n        relay.TupleType([a, rlist(c)]),\n        [a, b, c],\n    )\n    assert prelude.mod[map_accuml].checked_type == expected_type\n\n    acc = relay.Var(\"acc\", nat())\n    x = relay.Var(\"x\", nat())\n    add_to_acc = relay.Function([acc, x], relay.Tuple([add(x, acc), x]))\n\n    vals = cons(\n        make_nat_expr(prelude, 1),\n        cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n    )\n    res = eval(map_accuml(add_to_acc, z(), vals))\n\n    sum = count(res[0])\n    new_vals = to_list(res[1])\n\n    assert sum == 6\n    assert len(new_vals) == 3\n    assert count(new_vals[0]) == 3\n    assert count(new_vals[1]) == 2\n    assert count(new_vals[2]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_optional_matching():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    v = relay.Var(\"v\")\n    condense = relay.Function(\n        [x, y],\n        relay.Match(\n            x,\n            [\n                relay.Clause(relay.PatternConstructor(some, [relay.PatternVar(v)]), cons(v, y)),\n                relay.Clause(relay.PatternConstructor(none), y),\n            ],\n        ),\n    )\n\n    res = eval(\n        foldr(\n            condense,\n            nil(),\n            cons(\n                some(make_nat_expr(prelude, 3)),\n                cons(none(), cons(some(make_nat_expr(prelude, 1)), nil())),\n            ),\n        )\n    )\n\n    reduced = to_list(res)\n    assert len(reduced) == 2\n    assert count(reduced[0]) == 3\n    assert count(reduced[1]) == 1\n\n\n@tvm.testing.uses_gpu\ndef test_tmap():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    lhs = prelude.mod[tmap].checked_type\n    rhs = relay.FuncType([relay.FuncType([a], b), tree(a)], tree(b), [a, b])\n    assert lhs == rhs\n\n    x = relay.Var(\"x\")\n    add_one = relay.Function([x], s(x))\n    res = eval(tmap(add_one, rose(z(), cons(rose(z(), nil()), cons(rose(z(), nil()), nil())))))\n\n    tree_dict = tree_to_dict(res)\n    assert count(tree_dict[\"member\"]) == 1\n    assert len(tree_dict[\"children\"]) == 2\n    for subtree in tree_dict[\"children\"]:\n        assert count(subtree[\"member\"]) == 1\n        assert len(subtree[\"children\"]) == 0\n\n\n@tvm.testing.uses_gpu\ndef test_size():\n    a = relay.TypeVar(\"a\")\n    lhs = prelude.mod[size].checked_type\n    rhs = relay.FuncType([tree(a)], relay.scalar_type(\"int32\"), [a])\n    assert lhs == rhs\n\n    root = rose(z(), cons(rose(z(), nil()), cons(rose(z(), nil()), nil())))\n    t = rose(z(), cons(root, cons(root, cons(root, nil()))))\n    res = eval(size(t))\n    assert get_scalar(res) == 10\n\n\n@tvm.testing.uses_gpu\ndef test_wildcard_match_solo():\n    x = relay.Var(\"x\", nat())\n    copy = relay.Function([x], relay.Match(x, [relay.Clause(relay.PatternWildcard(), x)]), nat())\n\n    res = eval(copy(s(s(s(z())))))\n    assert count(res) == 3\n\n\n@tvm.testing.uses_gpu\ndef test_wildcard_match_order():\n    x = relay.Var(\"x\", rlist(nat()))\n    y = relay.Var(\"y\")\n    a = relay.Var(\"a\")\n    return_zero = relay.Function(\n        [x],\n        relay.Match(\n            x,\n            [\n                relay.Clause(relay.PatternWildcard(), z()),\n                relay.Clause(\n                    relay.PatternConstructor(cons, [relay.PatternVar(y), relay.PatternVar(a)]), y\n                ),\n                relay.Clause(relay.PatternConstructor(nil), s(z())),\n            ],\n        ),\n        nat(),\n    )\n\n    res = eval(return_zero(cons(s(z()), nil())))\n    # wildcard pattern is evaluated first\n    assert count(res) == 0\n\n\n@tvm.testing.uses_gpu\ndef test_nested_matches():\n    a = relay.TypeVar(\"a\")\n    # TODO(@jroesch): inference should be able to handle this one\n    x = relay.Var(\"x\", type_annotation=rlist(rlist(a)))\n    y = relay.Var(\"y\")\n    w = relay.Var(\"w\")\n    h = relay.Var(\"h\")\n    t = relay.Var(\"t\")\n    flatten = relay.GlobalVar(\"flatten\")\n\n    # flatten could be written using a fold, but this way has nested matches\n    inner_match = relay.Match(\n        y,\n        [\n            relay.Clause(relay.PatternConstructor(nil), flatten(w)),\n            relay.Clause(\n                relay.PatternConstructor(cons, [relay.PatternVar(h), relay.PatternVar(t)]),\n                cons(h, flatten(cons(t, w))),\n            ),\n        ],\n    )\n\n    prelude.mod[flatten] = relay.Function(\n        [x],\n        relay.Match(\n            x,\n            [\n                relay.Clause(relay.PatternConstructor(nil), nil()),\n                relay.Clause(\n                    relay.PatternConstructor(cons, [relay.PatternVar(y), relay.PatternVar(w)]),\n                    inner_match,\n                ),\n            ],\n        ),\n        rlist(a),\n        [a],\n    )\n\n    first_list = cons(\n        make_nat_expr(prelude, 1),\n        cons(make_nat_expr(prelude, 2), cons(make_nat_expr(prelude, 3), nil())),\n    )\n    second_list = cons(\n        make_nat_expr(prelude, 4),\n        cons(make_nat_expr(prelude, 5), cons(make_nat_expr(prelude, 6), nil())),\n    )\n    final_list = cons(first_list, cons(second_list, nil()))\n\n    res = eval(flatten(final_list))\n\n    flat = to_list(res)\n    assert len(flat) == 6\n    for i in range(6):\n        assert count(flat[i]) == i + 1\n\n\n@tvm.testing.uses_gpu\ndef test_match_full_var():\n    x = relay.Var(\"x\")\n    v = relay.Var(\"v\")\n    id_func = relay.Function([x], relay.Match(x, [relay.Clause(relay.PatternVar(v), v)]))\n\n    res1 = eval(id_func(nil()))\n    res2 = eval(id_func(cons(z(), cons(z(), nil()))))\n\n    empty = to_list(res1)\n    assert len(empty) == 0\n\n    zeroes = to_list(res2)\n    assert len(zeroes) == 2\n    assert count(zeroes[0]) == 0\n    assert count(zeroes[1]) == 0\n\n\n@tvm.testing.uses_gpu\ndef test_nested_pattern_match():\n    x = relay.Var(\"x\", rlist(nat()))\n    h1 = relay.Var(\"h1\")\n    h2 = relay.Var(\"h2\")\n    t = relay.Var(\"t\")\n    match = relay.Match(\n        x,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternVar(h1),\n                        relay.PatternConstructor(cons, [relay.PatternVar(h2), relay.PatternVar(t)]),\n                    ],\n                ),\n                h2,\n            ),\n            relay.Clause(relay.PatternWildcard(), z()),\n        ],\n    )\n    get_second = relay.Function([x], match)\n\n    res = eval(get_second(cons(s(z()), cons(s(s(z())), nil()))))\n\n    assert count(res) == 2\n\n\n@tvm.testing.uses_gpu\ndef test_compose():\n    n = relay.Var(\"n\")\n    inc = relay.Function([n], s(n))\n    x = relay.Var(\"x\")\n    res = eval(relay.Call(compose(inc, double), [s(s(z()))]))\n    assert count(res) == 5\n\n\n@tvm.testing.uses_gpu\ndef test_iterate():\n    expr = relay.Call(iterate(double, relay.const(2)), [make_nat_expr(prelude, 3)])\n    res = eval(relay.Function([], expr)())\n    assert count(res) == 12\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_basic_block_normal_form.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.analysis import check_basic_block_normal_form\n\n\ndef test_one_block():\n    x = relay.var(\"x\")\n    y = relay.add(x, x)\n    z = relay.add(x, y)\n    check_basic_block_normal_form(z)\n\n\ndef test_let():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    body = relay.Let(y, x, y)\n    check_basic_block_normal_form(body)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_if():\n    cond = relay.var(\"cond\", dtype=\"bool\", shape=())\n    shared = relay.var(\"shared\")\n    true_branch = shared\n    false_branch = relay.add(shared, shared)\n    body = relay.If(cond, true_branch, false_branch)\n    \"\"\"\n    The program below violates basic block normal form, as the scope of %shared\n    is ambiguous and should not be in that of true branch.\n\n    free_var %cond: bool\n    if (%cond) {\n      free_var %shared\n      %shared\n    } else {\n      add(%shared, %shared)\n    }\n    \"\"\"\n    check_basic_block_normal_form(body)\n\n\ndef test_valid_if():\n    cond = relay.var(\"cond\", dtype=\"bool\", shape=())\n    shared = relay.var(\"shared\")\n    true_branch = shared\n    false_branch = relay.add(shared, shared)\n    body = relay.If(cond, true_branch, false_branch)\n    shared_bound = relay.var(\"shared_bound\", shape=(1,), dtype=\"float32\")\n    body = relay.Let(shared, shared_bound, body)\n    \"\"\"\n    The program below uses let binding to control the scope of %shared, which\n    follows the basic block normal form.\n\n    free_var %shared_bound: Tensor[(1), float32]\n    let %shared = %shared_bound;\n    free_var %cond: bool\n    if (%cond) {\n      %shared\n    } else {\n      add(%shared, %shared)\n    }\n    \"\"\"\n    check_basic_block_normal_form(body)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_if2():\n    \"\"\"\n    fn (%x: float32) {\n      %0 = equal(%x, 2f);\n      if (%0) {\n        %1 = add(%x, 1f);\n        multiply(%1, 2f)\n      } else {\n        multiply(%1, 1f)\n      }\n    }\n    \"\"\"\n    x = relay.var(\"x\", shape=(), dtype=\"float32\")\n    one = relay.const(1, dtype=\"float32\")\n    two = relay.const(2, dtype=\"float32\")\n    v1 = relay.add(x, one)\n    v2 = relay.equal(x, two)\n    true_branch = relay.multiply(v1, two)\n    false_branch = relay.multiply(v1, one)\n    body = relay.If(v2, true_branch, false_branch)\n    func = relay.Function([x], body)\n    check_basic_block_normal_form(func)\n\n\ndef test_valid_if2():\n    \"\"\"\n    fn (%x: float32) {\n      let %v1 = add(%x, 1f);\n      %0 = equal(%x, 2f);\n      if (%0) {\n        multiply(%v1, 2f)\n      } else {\n        multiply(%v1, 1f)\n      }\n    }\n    \"\"\"\n    x = relay.var(\"x\", shape=(), dtype=\"float32\")\n    one = relay.const(1, dtype=\"float32\")\n    two = relay.const(2, dtype=\"float32\")\n    v1 = relay.var(\"v1\")\n    v2 = relay.equal(x, two)\n    true_branch = relay.multiply(v1, two)\n    false_branch = relay.multiply(v1, one)\n    body = relay.If(v2, true_branch, false_branch)\n    body = relay.Let(v1, relay.add(x, one), body)\n    func = relay.Function([x], body)\n    check_basic_block_normal_form(func)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_func():\n    x = relay.var(\"x\", shape=(1,), dtype=\"float32\")  # , a)\n    y = relay.var(\"y\", shape=(1,), dtype=\"float32\")  # , a)\n    z = relay.var(\"z\", shape=(1,), dtype=\"float32\")  # , a)\n    x2 = relay.add(x, x)\n    func_a = relay.Function([y], relay.add(x2, y))  # , a, [a])\n    func_b = relay.Function([z], relay.add(x2, z))  # , a, [a])\n    body = relay.Tuple([func_a, func_b])\n    body = relay.Function([x], body)\n    \"\"\"\n    fn (%x: Tensor[(1), float32]) {\n      %1 = fn (%y: Tensor[(1), float32]) {\n        %0 = add(%x, %x);\n        add(%0, %y)\n      };\n      %2 = fn (%z: Tensor[(1), float32]) {\n        add(%0, %z)\n      };\n      (%1, %2)\n    }\n    \"\"\"\n    check_basic_block_normal_form(body)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_higher_order_return():\n    x = relay.var(\"x\", shape=(1,), dtype=\"float32\")  # , a)\n    y = relay.var(\"y\", shape=(1,), dtype=\"float32\")  # , a)\n    z = relay.var(\"z\", shape=(1,), dtype=\"float32\")  # , a)\n    x2 = relay.add(x, x)\n    func_a = relay.Function([y], relay.add(x2, y))  # , a, [a])\n    func_b = relay.Function([z], relay.add(x2, z))  # , a, [a])\n    body = relay.Tuple([func_a, func_b])\n    body = relay.Function([x], body)\n    \"\"\"\n    fn (%x: Tensor[(1), float32]) {\n      %1 = fn (%y: Tensor[(1), float32]) {\n        %0 = add(%x, %x);\n        add(%0, %y)\n      };\n      %2 = fn (%z: Tensor[(1), float32]) {\n        add(%0, %z)\n      };\n      (%1, %2)\n    }\n    \"\"\"\n    check_basic_block_normal_form(body)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_higher_order_nested():\n    x = relay.var(\"x\", dtype=\"float32\", shape=(1,))\n    s = relay.var(\"s\", dtype=\"float32\", shape=(1,))\n    shared = relay.add(s, s)\n    func_true = relay.Function([x], relay.add(x, shared))\n    choice_t = relay.FuncType([], relay.scalar_type(\"bool\"))\n    f = relay.Var(\"f\", choice_t)\n    z = relay.Var(\"z\")\n    body = relay.If(f(), func_true, relay.Function([z], relay.add(z, shared)))\n    top = relay.Function([f, s], body)\n    \"\"\"\n    fn (%f: fn () -> bool, %s: Tensor[(1), float32]) {\n      %0 = %f();\n      if (%0) {\n        fn (%x: Tensor[(1), float32]) {\n          %1 = add(%s, %s);\n          add(%x, %1)\n        }\n      } else {\n        fn (%z) {\n          add(%z, %1)\n        }\n      }\n    }\n    \"\"\"\n    check_basic_block_normal_form(top)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_extract_fake_quantized_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test function extraction\"\"\"\nimport tvm\nfrom tvm import relay\n\n\ndef test_fake_quantize_conv():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    zero = relay.const(0)\n\n    op = relay.op.nn.conv2d(\n        relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n        relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n        kernel_size=[5, 5],\n    )\n    op = relay.qnn.op.quantize(op, relay.const(1.0), zero, out_dtype=\"int8\")\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"nn.conv2d\": 1}\n\n\ndef test_fake_quantize_dense():\n    x = relay.var(\"x\", shape=[128, 64], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[256, 64], dtype=\"int8\")\n    zero = relay.const(0)\n\n    op = relay.op.nn.dense(\n        relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n        relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n    )\n    op = relay.qnn.op.quantize(op, relay.const(1.0), zero, out_dtype=\"int8\")\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"nn.dense\": 1}\n\n\ndef test_fake_quantize_multiple_regions():\n    x = relay.var(\"x\", shape=[128, 64], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[256, 64], dtype=\"int8\")\n    zero = relay.const(0)\n\n    op = relay.op.nn.dense(\n        relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n        relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n    )\n    op = relay.qnn.op.quantize(op, relay.const(1.0), zero, out_dtype=\"int8\")\n\n    op = relay.qnn.op.dequantize(op, relay.const(2.0), relay.const(114))\n    op = relay.op.nn.relu(op)\n    op = relay.qnn.op.quantize(op, relay.const(1.0), zero, out_dtype=\"int8\")\n\n    w2 = relay.var(\"w2\", shape=[64, 256], dtype=\"int8\")\n    op = relay.op.nn.dense(\n        relay.qnn.op.dequantize(op, relay.const(1.0), zero),\n        relay.qnn.op.dequantize(w2, relay.const(0.5), zero),\n    )\n    op = relay.qnn.op.quantize(op, relay.const(1.0), zero, out_dtype=\"int8\")\n\n    # We expect to ignore this sigmoid op since it's just outside a fake\n    # quantized region\n    op = relay.op.sigmoid(op)\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"nn.dense\": 2, \"nn.relu\": 1}\n\n\ndef test_fake_quantize_maxpool():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.nn.max_pool2d(x, [3, 3])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"nn.max_pool2d\": 1}\n\n\ndef test_fake_quantize_transpose_reshape():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.transpose(x, [1, 0, 2, 3])\n    op = relay.op.reshape(op, [3, -1])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"transpose\": 1, \"reshape\": 1}\n\n\ndef test_fake_quantize_concat():\n    zero = relay.const(0)\n    inputs = []\n    for i in range(4):\n        inputs.append(\n            relay.qnn.op.dequantize(\n                relay.var(\"x%d\" % i, shape=[1, 4], dtype=\"int8\"), relay.const(i + 0.5), zero\n            )\n        )\n    concat = relay.op.concatenate(inputs, axis=1)\n    op = relay.qnn.op.quantize(concat, relay.const(3.5), zero)\n\n    mod = tvm.IRModule.from_expr(op)\n    fake_quantized_op_freqs = relay.analysis.list_fake_quantized_op_freqs(mod)\n\n    assert dict(fake_quantized_op_freqs) == {\"concatenate\": 1}\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_extract_fused_functions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test function extraction\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing.synthetic import get_workload\n\n\ndef get_conv_net():\n    \"\"\"This gets the net for a case described in fuse_ops.cc:\n\n            conv2d\n            /  |  \\\n           /   |   \\\n         op    op   op\n          \\    |    /\n           \\   |   /\n          elemwise add\n               |\n    \"\"\"\n    dshape = (1, 1, 5, 1)\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n\n    x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n    x2 = relay.nn.conv2d(y, relay.var(\"w3\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n    x3 = relay.nn.conv2d(y, relay.var(\"w4\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n\n    z = relay.add(x1, x2)\n    z = relay.add(x3, z)\n\n    return tvm.IRModule.from_expr(z)\n\n\ndef get_conv2d():\n    x = relay.var(\"x\", shape=(1, 56, 56, 64))\n    weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n    y = relay.nn.conv2d(\n        x,\n        weight1,\n        channels=32,\n        kernel_size=(3, 3),\n        padding=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    return tvm.IRModule.from_expr(y)\n\n\ndef test_extract_identity():\n    mod = get_conv2d()\n    items = relay.analysis.extract_fused_functions(mod)\n    assert len(items) == 1\n\n    mod[\"main\"] = mod[\"main\"].with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    tvm.ir.structural_equal(list(items.values())[0], mod[\"main\"])\n\n\ndef test_extract_conv_net():\n    mod = get_conv_net()\n    items = relay.analysis.extract_fused_functions(mod)\n    functions = list(items.values())\n    assert len(functions) == 2\n    x = functions[0]\n    y = functions[1]\n\n    def is_conv(func):\n        conv2d = relay.op.op.get(\"nn.conv2d\")\n        call_node = func.body\n        return call_node.op == conv2d\n\n    def is_conv_add(func):\n        add = relay.op.op.get(\"add\")\n        call_node = func.body\n        maybe_conv_module = tvm.IRModule.from_expr(call_node.args[0])\n        return call_node.op == add and is_conv(maybe_conv_module[\"main\"])\n\n    # Function traversal order isn't obvious, so checking both orders is more consistent\n    assert (is_conv(x) and is_conv_add(y)) or (is_conv_add(x) and is_conv(y))\n\n\ndef test_extract_resnet():\n    mod, _params = get_workload()\n    items = relay.analysis.extract_fused_functions(mod)\n    assert len(items) == 7\n\n\nif __name__ == \"__main__\":\n    test_extract_identity()\n    test_extract_conv_net()\n    test_extract_resnet()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_extract_intermediate_expr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test function extraction\"\"\"\nimport pytest\nimport tvm\nfrom tvm import relay\n\n\ndef get_conv_net():\n    \"\"\"This gets the net for:\n          conv2d\n          /  |\n         /   |\n    conv2d   |\n        \\    |\n         \\   |\n        elemwise add\n             |\n             |\n             |\n           split\n             |\n             |\n             |\n        elemwise add\n    \"\"\"\n    dshape = (1, 1, 5, 1)\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n    x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n\n    z = relay.add(y, x1)\n\n    tuple_out = relay.op.split(z, indices_or_sections=1, axis=0)\n\n    tuple_0_add = relay.add(tuple_out[0], relay.const(1, dtype=\"float32\"))\n\n    return tvm.IRModule.from_expr(tuple_0_add)\n\n\ndef get_conv2d():\n    x = relay.var(\"x\", shape=(1, 56, 56, 64))\n    weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n    y = relay.nn.conv2d(\n        x,\n        weight1,\n        channels=32,\n        kernel_size=(3, 3),\n        padding=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    return tvm.IRModule.from_expr(y)\n\n\ndef test_extract():\n    dshape = (1, 1, 5, 1)\n\n    def before():\n        return get_conv_net()\n\n    def expected_0():\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        return tvm.IRModule.from_expr(y)\n\n    def expected_1():\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        return tvm.IRModule.from_expr(x1)\n\n    def expected_2():\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        z = relay.add(y, x1)\n        return tvm.IRModule.from_expr(z)\n\n    def expected_3():\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        z = relay.add(y, x1)\n        tuple_out = relay.op.split(z, indices_or_sections=1, axis=0)\n        return tvm.IRModule.from_expr(tuple_out.astuple())\n\n    def expected_4():\n        # check tuple node\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n        z = relay.add(y, x1)\n        tuple_out = relay.op.split(z, indices_or_sections=1, axis=0)\n        return tvm.IRModule.from_expr(tuple_out[0])\n\n    assert tvm.ir.structural_equal(\n        relay.analysis.extract_intermdeiate_expr(before(), 0), expected_0()\n    )\n    assert tvm.ir.structural_equal(\n        relay.analysis.extract_intermdeiate_expr(before(), 1), expected_1()\n    )\n    assert tvm.ir.structural_equal(\n        relay.analysis.extract_intermdeiate_expr(before(), 2), expected_2()\n    )\n    assert tvm.ir.structural_equal(\n        (relay.analysis.extract_intermdeiate_expr(before(), 3)), expected_3()\n    )\n    assert tvm.ir.structural_equal(\n        relay.analysis.extract_intermdeiate_expr(before(), 4), expected_4()\n    )\n    assert tvm.ir.structural_equal(relay.analysis.extract_intermdeiate_expr(before(), 5), before())\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_extract_operators.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test function extraction\"\"\"\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing.resnet import get_workload\nfrom tvm.relay.testing import run_opt_pass\n\n\ndef get_conv_net():\n    \"\"\"This gets the net for:\n          conv2d\n          /  |\n         /   |\n    conv2d   |\n        \\    |\n         \\   |\n        elemwise add\n             |\n    \"\"\"\n    dshape = (1, 1, 5, 1)\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n    x1 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(3, 3), padding=(1, 1), channels=1)\n\n    z = relay.add(y, x1)\n\n    return tvm.IRModule.from_expr(z)\n\n\ndef get_conv2d():\n    x = relay.var(\"x\", shape=(1, 56, 56, 64))\n    weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n    y = relay.nn.conv2d(\n        x,\n        weight1,\n        channels=32,\n        kernel_size=(3, 3),\n        padding=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    return tvm.IRModule.from_expr(y)\n\n\ndef test_extract_identity():\n    mod = get_conv2d()\n    op_freqs = relay.analysis.list_op_freqs(mod)\n    assert len(op_freqs) == 1\n    assert op_freqs[\"nn.conv2d\"] == 1\n\n\ndef test_extract_conv_net():\n    mod = get_conv_net()\n    op_freqs = relay.analysis.list_op_freqs(mod)\n    assert len(op_freqs) == 2\n    assert op_freqs[\"add\"] == 1\n    assert op_freqs[\"nn.conv2d\"] == 2\n\n\ndef test_extract_fused():\n    mod = get_conv_net()\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.FuseOps(3)(mod)\n\n    op_freqs = relay.analysis.list_op_freqs(mod)\n    assert len(op_freqs) == 2\n    assert op_freqs[\"add\"] == 1\n    assert op_freqs[\"nn.conv2d\"] == 2\n\n\ndef test_extract_resnet():\n    mod, _params = get_workload()\n    expected_op_freqs = {\n        \"nn.batch_norm\": 19,\n        \"nn.conv2d\": 21,\n        \"nn.relu\": 18,\n        \"nn.max_pool2d\": 1,\n        \"add\": 8,\n        \"nn.global_avg_pool2d\": 1,\n        \"nn.batch_flatten\": 1,\n        \"nn.dense\": 1,\n        \"nn.bias_add\": 1,\n        \"nn.softmax\": 1,\n    }\n    op_freqs = relay.analysis.list_op_freqs(mod)\n    assert len(op_freqs) == len(expected_op_freqs)\n    assert all([op_freqs[op] == expected_op_freqs[op] for op in expected_op_freqs])\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import detect_feature, Feature\nfrom tvm.relay.transform import gradient\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.testing import run_infer_type\n\n\ndef test_prelude():\n    p = Prelude()\n    feats = detect_feature(p.mod)\n    assert feats == set(\n        [\n            Feature.fVar,\n            Feature.fGlobalVar,\n            Feature.fConstant,\n            Feature.fTuple,\n            Feature.fTupleGetItem,\n            Feature.fFunction,\n            Feature.fOp,\n            Feature.fCall,\n            Feature.fLet,\n            Feature.fIf,\n            Feature.fConstructor,\n            Feature.fMatch,\n        ]\n    )\n\n\ndef test_ad():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x + x)\n    func = run_infer_type(func)\n    mod = tvm.IRModule.from_expr(gradient(func))\n    mod = relay.transform.InferType()(mod)\n    back_func = mod[\"main\"]\n    feats = detect_feature(back_func)\n    assert feats == set(\n        [\n            Feature.fVar,\n            Feature.fTuple,\n            Feature.fTupleGetItem,\n            Feature.fFunction,\n            Feature.fOp,\n            Feature.fCall,\n            Feature.fLet,\n            Feature.fRefCreate,\n            Feature.fRefRead,\n            Feature.fRefWrite,\n        ]\n    )\n\n\nif __name__ == \"__main__\":\n    test_prelude()\n    test_ad()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_analysis_get_calibration_data.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\n\nimport tvm\nimport tvm.relay.testing\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.analysis import get_calibration_data\n\n\ndef check_data_size(mod, data):\n    assert len(data) == len(mod.functions) - 1\n    for key, value in mod.functions.items():\n        if key.name_hint != \"main\":\n            assert len(data[key][\"inputs\"]) == len(value.params)\n            if isinstance(value.body, relay.Tuple):\n                assert len(data[key][\"outputs\"]) == len(value.body.fields)\n            else:\n                assert len(data[key][\"outputs\"]) == 1\n\n\ndef test_simple_graph():\n    # A module with two subgraphs\n    mod = tvm.IRModule()\n\n    x0 = relay.var(\"x0\", shape=(8, 8))\n    y0 = relay.var(\"y0\", shape=(8, 8))\n    z0 = x0 + y0\n    z1 = x0 - y0\n    z2 = relay.Tuple((z0, z1))\n    f0 = relay.Function([x0, y0], z2)\n    f0 = f0.with_attr(\"Compiler\", \"test_graph\")\n    g0 = relay.GlobalVar(\"g0\")\n    mod[g0] = f0\n    mod = relay.transform.InferType()(mod)\n\n    x1 = relay.var(\"x1\", shape=(8, 8))\n    y1 = relay.var(\"y1\", shape=(8, 8))\n    z1 = x1 - y1\n    f1 = relay.Function([x1, y1], z1)\n    f1 = f1.with_attr(\"Compiler\", \"test_graph\")\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = f1\n    mod = relay.transform.InferType()(mod)\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    z = relay.var(\"z\", shape=(8, 8))\n    c0 = relay.Call(g0, [x, y])\n    c1 = relay.Call(g1, [relay.TupleGetItem(c0, 0), z])\n    fm = relay.Function([x, y, z], c1)\n    mod[\"main\"] = fm\n    mod = relay.transform.InferType()(mod)\n\n    x_data = np.random.rand(8, 8).astype(\"float32\")\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n    z_data = np.random.rand(8, 8).astype(\"float32\")\n    data = get_calibration_data(mod, {\"x\": x_data, \"y\": y_data, \"z\": z_data})\n\n    # Check the number and orders\n    check_data_size(mod, data)\n    tvm.testing.assert_allclose(data[g0][\"inputs\"][0].numpy(), x_data)\n    tvm.testing.assert_allclose(data[g0][\"inputs\"][1].numpy(), y_data)\n    tvm.testing.assert_allclose(data[g0][\"outputs\"][0].numpy(), x_data + y_data)\n    tvm.testing.assert_allclose(data[g0][\"outputs\"][1].numpy(), x_data - y_data)\n    tvm.testing.assert_allclose(data[g1][\"inputs\"][0].numpy(), x_data + y_data)\n    tvm.testing.assert_allclose(data[g1][\"inputs\"][1].numpy(), z_data)\n    tvm.testing.assert_allclose(data[g1][\"outputs\"][0].numpy(), x_data + y_data - z_data)\n\n\ndef test_mobilenet_dnnl():\n    if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 3, 224, 224)\n    mod, params = relay.testing.mobilenet.get_workload(batch_size=1, dtype=\"float32\")\n\n    mod = transform.AnnotateTarget([\"dnnl\"])(mod)\n    mod = transform.MergeCompilerRegions()(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    data = get_calibration_data(mod, {\"data\": i_data, **params})\n\n    # Check the number and orders\n    check_data_size(mod, data)\n\n\nif __name__ == \"__main__\":\n    test_simple_graph()\n    test_mobilenet_dnnl()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_annotated_regions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\n\n\ndef check_region(region_set, target, args, nodes, rets):\n    region = region_set.get_region(args[0])\n    assert region\n    assert target == region.target\n    assert set(args) == set(region.args)\n    assert set(nodes) == set(region.nodes)\n    assert set(rets) == set(region.rets)\n\n\ndef test_region_set_creator_diamond():\n    data = relay.var(\"data\", shape=(10, 10))\n    cb_1 = compiler_begin(data, \"test_target\")\n    O_1 = relay.abs(cb_1)\n    ce_1 = compiler_end(O_1, \"test_target\")\n    ce_2 = compiler_end(O_1, \"test_target\")\n    cb_2 = compiler_begin(ce_1, \"test_target\")\n    O_2 = relay.nn.relu(cb_2)\n    ce_3 = compiler_end(O_2, \"test_target\")\n    cb_d = compiler_begin(ce_2, \"default\")\n    X = relay.tanh(cb_d)\n    ce_d = compiler_end(X, \"default\")\n    cb_3 = compiler_begin(ce_3, \"test_target\")\n    cb_4 = compiler_begin(ce_d, \"test_target\")\n    O_3 = relay.add(cb_3, cb_4)\n    ce_4 = compiler_end(O_3, \"test_target\")\n    diamond = relay.Function([data], ce_4)\n\n    region_set = relay.analysis.AnnotatedRegionSet(\n        diamond, relay.op.get(\"annotation.compiler_begin\"), relay.op.get(\"annotation.compiler_end\")\n    )\n    assert len(region_set) == 4\n    check_region(\n        region_set,\n        \"test_target\",\n        [cb_1],\n        [cb_1, O_1, ce_1, ce_2],\n        [ce_1, ce_2],\n    )\n    check_region(\n        region_set,\n        \"test_target\",\n        [cb_2],\n        [cb_2, O_2, ce_3],\n        [ce_3],\n    )\n    check_region(\n        region_set,\n        \"default\",\n        [cb_d],\n        [cb_d, X, ce_d],\n        [ce_d],\n    )\n    check_region(\n        region_set,\n        \"test_target\",\n        [cb_3, cb_4],\n        [cb_3, cb_4, O_3, ce_4],\n        [ce_4],\n    )\n\n\ndef test_region_set_creator_merged():\n    data = relay.var(\"data\", shape=(10, 10))\n    cb_1 = compiler_begin(data, \"test_target\")\n    O_1 = relay.abs(cb_1)\n    ce_2 = compiler_end(O_1, \"test_target\")\n    O_2 = relay.nn.relu(O_1)\n    ce_3 = compiler_end(O_2, \"test_target\")\n    cb_d = compiler_begin(ce_2, \"default\")\n    X = relay.tanh(cb_d)\n    ce_d = compiler_end(X, \"default\")\n    cb_3 = compiler_begin(ce_3, \"test_target\")\n    cb_4 = compiler_begin(ce_d, \"test_target\")\n    O_3 = relay.add(cb_3, cb_4)\n    O_4 = relay.add(cb_3, cb_4)\n    O_5 = relay.Tuple([O_3, O_4])\n    ce_4 = compiler_end(O_5, \"test_target\")\n    merged = relay.Function([data], ce_4)\n\n    region_set = relay.analysis.AnnotatedRegionSet(\n        merged, relay.op.get(\"annotation.compiler_begin\"), relay.op.get(\"annotation.compiler_end\")\n    )\n    assert len(region_set) == 3\n    check_region(\n        region_set,\n        \"test_target\",\n        [cb_1],\n        [cb_1, O_1, O_2, ce_2, ce_3],\n        [ce_2, ce_3],\n    )\n    check_region(\n        region_set,\n        \"default\",\n        [cb_d],\n        [cb_d, X, ce_d],\n        [ce_d],\n    )\n    check_region(\n        region_set,\n        \"test_target\",\n        [cb_3, cb_4],\n        [cb_3, cb_4, O_3, O_4, O_5, ce_4],\n        [ce_4],\n    )\n\n\nif __name__ == \"__main__\":\n    test_region_set_creator_diamond()\n    test_region_set_creator_merged()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_any.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay, te\nfrom tvm.relay.loops import while_loop\nfrom tvm.relay.testing import run_infer_type as infer_type\nfrom tvm.topi.testing import searchsorted_ref\n\nfrom utils import ref_funcs\nfrom utils.assert_diagnostic import DiagnosticTesting\n\n\ndef int32(val):\n    return relay.const(val, \"int32\")\n\n\ndef any_dims(ndim):\n    shape = []\n    for _ in range(ndim):\n        shape.append(relay.Any())\n    return tuple(shape)\n\n\ndef check_result(\n    args,\n    mod,\n    expected,\n    flatten=False,\n    assert_shape=False,\n    only_vm=False,\n    targets=None,\n    disable_targets=None,\n):\n    if not isinstance(expected, list):\n        expected = [expected]\n    for kind in [\"debug\", \"vm\"]:\n        targets = targets or tvm.testing.enabled_targets()\n        for tgt, dev in targets:\n            if disable_targets and tgt in disable_targets:\n                continue\n            if kind == \"debug\" and (only_vm or dev.device_type != tvm.cpu().device_type):\n                continue\n            result = relay.create_executor(kind, mod=mod, device=dev, target=tgt).evaluate()(*args)\n            if isinstance(result, tvm.runtime.container.ADT):\n                result = [r.numpy() for r in result]\n            else:\n                result = [result.numpy()]\n\n            for r, e in zip(result, expected):\n                if assert_shape:\n                    assert r.shape == e, \"Shape mismatch: expect %s but got %s.\" % (\n                        str(e),\n                        str(r),\n                    )\n                else:\n                    if flatten:\n                        r = r.flatten()\n                        e = e.flatten()\n                    tvm.testing.assert_allclose(r, e, atol=2e-6)\n\n\ndef verify_any_broadcast(x_shape, y_shape, x_np_shape, y_np_shape, op, np_op):\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    y = relay.var(\"y\", shape=y_shape, dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], op(x, y))\n    x_np = np.random.uniform(size=x_np_shape).astype(dtype)\n    y_np = np.random.uniform(size=y_np_shape).astype(dtype)\n    res_np = np_op(x_np, y_np)\n    check_result([x_np, y_np], mod, res_np)\n\n\n@tvm.testing.uses_gpu\ndef test_any_broadcast():\n    # Test broadcast with 1s\n    verify_any_broadcast((relay.Any(),), (3, 2), (1,), (3, 2), relay.add, np.add)\n    verify_any_broadcast((relay.Any(), 2), (1, 2), (1, 2), (1, 2), relay.add, np.add)\n    verify_any_broadcast((relay.Any(), 2), (1, 2), (3, 2), (1, 2), relay.add, np.add)\n    verify_any_broadcast((relay.Any(), 2), (3, 2), (1, 2), (3, 2), relay.add, np.add)\n    verify_any_broadcast((relay.Any(), 2), (3, relay.Any()), (1, 2), (3, 1), relay.add, np.add)\n\n    # Test broadcast with values other than 1\n    verify_any_broadcast((relay.Any(),), (3, 2), (2,), (3, 2), relay.add, np.add)\n    verify_any_broadcast((relay.Any(), 2), (3, 2), (3, 2), (3, 2), relay.add, np.add)\n\n\ndef verify_any_elemwise(x_shape, x_np_shape, op, np_op):\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], op(x))\n    x_np = np.random.uniform(size=x_np_shape).astype(dtype)\n    res_np = np_op(x_np)\n    check_result([x_np], mod, res_np)\n\n\n@tvm.testing.uses_gpu\ndef test_any_elemwise():\n    verify_any_elemwise((relay.Any(),), (3,), relay.sqrt, np.sqrt)\n    verify_any_elemwise((relay.Any(), 2), (5, 2), relay.negative, np.negative)\n    verify_any_elemwise((relay.Any(), relay.Any()), (5, 4), relay.exp, np.exp)\n    verify_any_elemwise((relay.Any(),), (3,), relay.round, np.round)\n\n\n@tvm.testing.uses_gpu\ndef test_any_broadcast_fail():\n    # Test broadcast with incompatible values at runtime\n    def check_fail(x_shape, y_shape, x_np_shape, y_np_shape, op, np_op):\n        try:\n            verify_any_broadcast(x_shape, y_shape, x_np_shape, y_np_shape, op, np_op)\n        except tvm._ffi.base.TVMError:\n            pass\n        else:\n            assert False\n\n    check_fail((relay.Any(),), (3, 2), (1,), (4, 2), relay.add, np.add)\n    check_fail((relay.Any(), 2), (3, 2), (4, 2), (4, 2), relay.add, np.add)\n    check_fail((relay.Any(), 2), (3, relay.Any()), (1, 2), (4, 1), relay.add, np.add)\n    check_fail((relay.Any(), 2), (3, 3), (1, 3), (3, 3), relay.add, np.add)\n    check_fail((relay.Any(),), (3, 2), (2), (4, 2), relay.add, np.add)\n\n\ndef verify_any_full_like(x_shape, x_np_shape, relay_op, np_op, dtype=\"float32\"):\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], relay_op(x))\n    x_np = np.random.uniform(size=x_np_shape).astype(dtype)\n    res_np = np_op(x_np)\n    check_result([x_np], mod, res_np)\n\n\n@tvm.testing.uses_gpu\ndef test_any_full_like():\n    # zeros_like, ones_like\n    verify_any_full_like(any_dims(3), (2, 3, 5), relay.zeros_like, np.zeros_like, \"float32\")\n    verify_any_full_like(any_dims(3), (225, 115, 15), relay.zeros_like, np.zeros_like, \"float32\")\n    verify_any_full_like(\n        any_dims(5), (10, 11, 12, 13, 14), relay.zeros_like, np.zeros_like, \"int32\"\n    )\n    verify_any_full_like(any_dims(3), (2, 3, 5), relay.ones_like, np.ones_like, \"float32\")\n    verify_any_full_like(any_dims(3), (225, 115, 15), relay.ones_like, np.ones_like, \"float32\")\n    verify_any_full_like(any_dims(5), (10, 11, 12, 13, 14), relay.ones_like, np.ones_like, \"int32\")\n\n\ndef verify_any_full(x_np_shape, relay_op, np_op, dtype=\"float32\", value=None):\n    x = relay.var(\"x\", shape=(len(x_np_shape),), dtype=\"int32\")\n    mod = tvm.IRModule()\n    out = relay_op(x, dtype) if value is None else relay_op(relay.expr.const(value), x, dtype)\n    mod[\"main\"] = relay.Function([x], out)\n    res_np = np_op(x_np_shape) if value is None else np_op(x_np_shape, value)\n    x_np = np.array(x_np_shape).astype(\"int32\")\n    check_result([x_np], mod, res_np)\n\n\n@tvm.testing.uses_gpu\ndef test_any_full():\n    # zeros, ones, full\n    verify_any_full((2, 3, 5), relay.zeros, np.zeros, \"float32\")\n    verify_any_full((225, 115, 15), relay.zeros, np.zeros, \"float32\")\n    verify_any_full((10, 11, 12, 13, 14), relay.zeros, np.zeros, \"int32\")\n    verify_any_full((2, 3, 5), relay.ones, np.ones, \"float32\")\n    verify_any_full((225, 115, 15), relay.ones, np.ones, \"float32\")\n    verify_any_full((10, 11, 12, 13, 14), relay.ones, np.ones, \"int32\")\n    verify_any_full((10, 11, 12, 13, 14), relay.full, np.full, \"float32\", 2.0)\n    verify_any_full((1, 2, 3, 4), relay.full, np.full, \"int32\", -2)\n\n\n@tvm.testing.uses_gpu\ndef test_any_concat():\n    x = relay.var(\"x\", shape=(relay.Any(), 2), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(1, 2), dtype=\"float32\")\n    xx = x - relay.expr.const(3.0)\n    yy = y * relay.expr.const(5.0)\n    z = relay.op.concatenate([xx, yy], axis=0)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], z)\n    x_np = np.random.uniform(size=(3, 2)).astype(\"float32\")\n    y_np = np.random.uniform(size=(1, 2)).astype(\"float32\")\n    ref = np.concatenate([x_np - 3.0, y_np * 5.0], axis=0)\n    check_result([x_np, y_np], mod, ref)\n\n    num_inputs = 25\n    x = [relay.var(\"x\", shape=(relay.Any(),), dtype=\"float32\") for _ in range(num_inputs)]\n    z = relay.op.concatenate(x, axis=0)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function(x, z)\n    x_np = [np.random.uniform(size=(1,)).astype(\"float32\") for _ in range(num_inputs)]\n    ref = np.concatenate(x_np, axis=0)\n    check_result(x_np, mod, ref)\n\n    def test_oshape(in_vars, axis, oshape):\n        z = relay.op.concatenate(in_vars, axis=axis)\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function(in_vars, z)\n        typed_mod = relay.transform.InferType()(mod)\n        assert typed_mod[\"main\"].body.checked_type == relay.TensorType(oshape, dtype=\"float32\")\n\n    x = [relay.var(\"x\", shape=(relay.Any(), 3), dtype=\"float32\") for _ in range(3)]\n    x.append(relay.var(\"x\", shape=(relay.Any(), relay.Any()), dtype=\"float32\"))\n\n    test_oshape(x, 0, (relay.Any(), 3))\n    test_oshape(x, 1, (relay.Any(), relay.Any()))\n\n    # [(1, 3), (1, ?)] -> (2, ?)\n    x = [\n        relay.var(\"x\", shape=(1, 3), dtype=\"float32\"),\n        relay.var(\"x\", shape=(1, relay.Any()), dtype=\"float32\"),\n    ]\n    test_oshape(x, 0, (2, relay.Any()))\n    test_oshape(x, 1, (1, relay.Any()))\n\n\ndef verify_any_reshape(x_shape, newshape, x_np_shape, out_shape, variable_newshape=False):\n    x = relay.var(\"x\", shape=x_shape, dtype=\"float32\")\n    relu_x = relay.nn.relu(x)\n    data = np.random.uniform(size=x_np_shape).astype(\"float32\")\n    expected = data.reshape(out_shape)\n    params = [x]\n    args = [data]\n\n    if variable_newshape:\n        newshape_var = relay.var(\"newshape\", shape=(len(newshape),), dtype=\"int64\")\n        params.append(newshape_var)\n        args.append(np.array(newshape, dtype=\"int64\"))\n        newshape = newshape_var\n\n    y = relay.reshape(relu_x, newshape=newshape)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function(params, y)\n    check_result(args, mod, expected)\n\n\n@tvm.testing.uses_gpu\ndef test_any_reshape():\n    for variable_newshape in [False, True]:\n        # Variable newshape only supports that output rank is the same as newshape\n        verify_any_reshape(any_dims(3), (1, -1), (2, 3, 4), (1, 24), variable_newshape)\n        verify_any_reshape(any_dims(3), (0, -1), (2, 3, 4), (2, 12), variable_newshape)\n    verify_any_reshape(any_dims(3), (0, -2), (2, 3, 4), (2, 3, 4))\n    verify_any_reshape(any_dims(3), (-4, -1, 2, -3), (6, 3, 4), (3, 2, 12))\n    verify_any_reshape(any_dims(3), (-4, 2, -1, -2), (6, 3, 4), (2, 3, 3, 4))\n    verify_any_reshape(any_dims(3), (1, -1, 0), (2, 3, 4), (1, 6, 4))\n    verify_any_reshape(any_dims(3), (-1, 1, 0), (2, 3, 4), (6, 1, 4))\n\n\ndef verify_any_one_hot(indices_shape, indices_np_shape, depth, on_value, off_value, axis, dtype):\n    indices = relay.var(\"indices\", shape=indices_shape, dtype=\"int32\")\n    on_value_const = relay.const(on_value, dtype)\n    off_value_const = relay.const(off_value, dtype)\n    y = relay.one_hot(indices, on_value_const, off_value_const, depth, axis=axis, dtype=dtype)\n    params = [indices]\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function(params, y)\n\n    indices_npy = np.random.randint(0, depth, size=indices_np_shape).astype(\"int32\")\n    out_npy = tvm.topi.testing.one_hot(indices_npy, on_value, off_value, depth, axis, dtype)\n    args = [indices_npy]\n    check_result(args, mod, out_npy)\n\n\n@tvm.testing.uses_gpu\ndef test_any_one_hot():\n    verify_any_one_hot(any_dims(1), (3,), 3, 1, 0, -1, \"int32\")\n    verify_any_one_hot(any_dims(2), (2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    verify_any_one_hot(any_dims(4), (3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\ndef verify_any_argwhere(x_shape, x_np_shape, dtype=\"bool\"):\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    y = relay.argwhere(x)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y)\n    data = np.random.choice([0, 1, 2, 3], size=x_np_shape).astype(dtype)\n    expected = np.argwhere(data)\n    check_result([data], mod, expected, flatten=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_argwhere():\n    verify_any_argwhere(any_dims(1), (5,))\n    verify_any_argwhere(any_dims(2), (5, 5))\n    verify_any_argwhere(any_dims(2), (5, 5), \"int32\")\n    verify_any_argwhere(any_dims(2), (5, 5), \"int8\")\n    verify_any_argwhere(any_dims(3), (5, 5, 5))\n    verify_any_argwhere(any_dims(4), (5, 5, 5, 5))\n    verify_any_argwhere(any_dims(5), (5, 5, 5, 5, 5))\n    verify_any_argwhere(any_dims(1), (5,), \"int32\")\n    verify_any_argwhere(any_dims(3), (5, 5, 5), \"int32\")\n    verify_any_argwhere(any_dims(4), (5, 5, 5, 5), \"int32\")\n    verify_any_argwhere(any_dims(5), (5, 5, 5, 5, 5), \"int32\")\n    verify_any_argwhere(any_dims(1), (5,), \"int8\")\n    verify_any_argwhere(any_dims(3), (5, 5, 5), \"int8\")\n    verify_any_argwhere(any_dims(4), (5, 5, 5, 5), \"int8\")\n    verify_any_argwhere(any_dims(5), (5, 5, 5, 5, 5), \"int8\")\n\n\ndef verify_any_take(data_shape, indices_shape, axis, data_np_shape, indices_np_shape):\n    mod = tvm.IRModule()\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    indices = relay.var(\"indices\", shape=indices_shape, dtype=\"int32\")\n    y = relay.take(data, indices, axis=axis)\n    mod[\"main\"] = relay.Function([data, indices], y)\n    data_np = np.random.uniform(size=data_np_shape).astype(\"float32\")\n    if axis is None:\n        max_index = data_np.size\n    else:\n        max_index = data_np.shape[axis]\n    indices_np = np.random.randint(max_index, size=indices_np_shape).astype(\"int32\")\n    ref = np.take(data_np, indices_np, axis=axis)\n    check_result([data_np, indices_np], mod, ref)\n\n\n@tvm.testing.uses_gpu\ndef test_any_take():\n    verify_any_take(any_dims(2), (1,), 0, (4, 5), (1,))\n    verify_any_take(any_dims(2), (), 0, (4, 5), ())\n    verify_any_take(any_dims(2), (), None, (4, 5), ())\n    verify_any_take(any_dims(3), any_dims(2), 1, (3, 4, 5), (2, 3))\n    verify_any_take(any_dims(2), any_dims(3), None, (4, 5), (2, 3, 4))\n    verify_any_take(any_dims(2), any_dims(4), -1, (4, 5), (2, 3, 4, 5))\n\n\ndef verify_any_tile(dshape, reps, np_dshape, np_reps):\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=dshape, dtype=\"float32\")\n    y = relay.tile(x, reps=reps)\n    mod[\"main\"] = relay.Function([x], y)\n    x_data = np.random.uniform(size=np_dshape).astype(\"float32\")\n    ref_res = np.tile(x_data, reps=np_reps)\n    check_result([x_data], mod, ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_any_tile():\n    verify_any_tile(any_dims(3), (3, 2, 1), (2, 3, 4), (3, 2, 1))\n    verify_any_tile(any_dims(3), (1, 2), (2, 3, 4), (1, 2))\n    verify_any_tile(any_dims(2), (3, 2, 1), (2, 3), (3, 2, 1))\n    verify_any_tile(any_dims(3), (1,), (2, 3, 4), (1,))\n\n\n@tvm.testing.uses_gpu\ndef test_any_shape_of():\n    x = relay.var(\"x\", shape=any_dims(2), dtype=\"float32\")\n    y = relay.shape_of(x)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y)\n    data = np.random.uniform(size=(3, 4)).astype(\"float32\")\n    check_result([data], mod, np.array([3, 4]).astype(\"int64\"))\n\n    x = relay.var(\"x\", shape=any_dims(3), dtype=\"float32\")\n    y0 = relay.shape_of(x)\n    y1 = relay.take(y0, relay.const(1, \"int32\"))\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y1)\n    data = np.random.uniform(size=(2, 3, 4)).astype(\"float32\")\n    check_result([data], mod, np.array(3).astype(\"int64\"))\n\n\nclass TestAnyReduce:\n    config = {\n        \"argmax\": (relay.argmax, any_dims(3), None, False, False, (3, 4, 5), ()),\n        \"argmin\": (relay.argmin, any_dims(4), 1, False, True, (3, 4, 5, 6), (3, 1, 5, 6)),\n        \"all\": (relay.all, any_dims(3), (1, 2), True, False, (3, 4, 5), (4, 5)),\n        \"max\": (relay.max, any_dims(4), -1, True, True, (3, 4, 5, 6), (1, 1, 1, 6)),\n        \"min\": (relay.min, any_dims(3), (0, 1), False, False, (4, 5, 6), (6,)),\n        \"prod\": (relay.prod, any_dims(4), 2, True, True, (3, 4, 5, 6), (1, 1, 5, 1)),\n        \"mean\": (relay.mean, any_dims(2), 0, False, False, (1, 2), (2,)),\n        \"variance\": (relay.variance, any_dims(5), (2, 4), False, False, (3, 4, 5, 6, 7), (3, 4, 6)),\n    }\n\n    (\n        reduce_op,\n        data_shape,\n        axis,\n        exclude,\n        keepdims,\n        static_data_shape,\n        ref_out_shape,\n    ) = tvm.testing.parameters(*config.values(), ids=config.keys())\n\n    def test_any_reduce(\n        self,\n        target,\n        dev,\n        reduce_op,\n        data_shape,\n        axis,\n        exclude,\n        keepdims,\n        static_data_shape,\n        ref_out_shape,\n    ):\n        target = tvm.target.Target(target)\n        if target.kind.name == \"vulkan\" and reduce_op == relay.all:\n            pytest.xfail(\"Known failing test case for vulkan runtime\")\n\n        mod = tvm.IRModule()\n        dtype = \"bool\" if reduce_op == relay.all else \"float32\"\n        data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n        y = reduce_op(data, axis, keepdims, exclude)\n        mod[\"main\"] = relay.Function([data], y)\n        data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n        check_result([data_np], mod, ref_out_shape, assert_shape=True, targets=[(target, dev)])\n\n\ndef verify_any_layout_transform(\n    data_shape, src_layout, dst_layout, static_data_shape, ref_out_shape\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.layout_transform(data, src_layout, dst_layout)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_layout_transform():\n    verify_any_layout_transform(any_dims(4), \"NCHW\", \"NHWC\", (3, 4, 5, 6), (3, 5, 6, 4))\n    verify_any_layout_transform(\n        any_dims(5), \"NCHW16c\", \"NCHW2c\", (1, 2, 8, 8, 16), (1, 16, 8, 8, 2)\n    )\n    verify_any_layout_transform(any_dims(5), \"NCHW6n\", \"NHWC\", (3, 4, 5, 6, 6), (18, 5, 6, 4))\n    verify_any_layout_transform(any_dims(4), \"NCHW\", \"NCHW4c\", (3, 4, 5, 6), (3, 1, 5, 6, 4))\n    verify_any_layout_transform((16, 1), \"CH\", \"C4cH\", (16, 1), (4, 4, 1))\n\n\ndef verify_any_expand_dims(data_shape, axis, num_newaxis, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.expand_dims(data, axis=axis, num_newaxis=num_newaxis)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_expand_dims():\n    verify_any_expand_dims(any_dims(3), 1, 2, (1, 2, 3), (1, 1, 1, 2, 3))\n    verify_any_expand_dims(any_dims(3), -1, 2, (1, 2, 3), (1, 2, 3, 1, 1))\n\n\ndef verify_any_transpose(data_shape, axes, static_data_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.transpose(data, axes=axes)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_out = np.transpose(data_np, axes)\n    check_result([data_np], mod, ref_out)\n\n\n@tvm.testing.uses_gpu\ndef test_any_transpose():\n    verify_any_transpose(any_dims(3), (1, 0, 2), (10, 3, 2))\n    verify_any_transpose(any_dims(3), None, (2, 3, 4))\n    verify_any_transpose(any_dims(6), (0, 1, 3, 2, 5, 4), (11, 12, 2, 1, 9, 17))\n    verify_any_transpose(any_dims(2), (-1, 0), (3, 2))\n\n\ndef verify_any_squeeze(data_shape, axis, static_data_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.squeeze(data, axis=axis)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_out = np.squeeze(data_np, axis)\n    check_result([data_np], mod, ref_out)\n\n\n@tvm.testing.uses_gpu\ndef test_any_squeeze():\n    verify_any_squeeze((relay.Any(), relay.Any(), relay.Any()), (0,), (1, 9, 8))\n    verify_any_squeeze((1, relay.Any(), relay.Any()), (0,), (1, 9, 8))\n    verify_any_squeeze(\n        (1, relay.Any(), relay.Any(), 1, relay.Any(), relay.Any()), (0, 3), (1, 12, 2, 1, 9, 17)\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_any_reshape_like():\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=(relay.Any(), 3, 10), dtype=dtype)\n    shape_like = relay.var(\"data\", shape=(relay.Any(), 5, 6), dtype=dtype)\n    y = relay.reshape_like(data, shape_like)\n    mod[\"main\"] = relay.Function([data, shape_like], y)\n    data_np = np.random.uniform(size=(3, 3, 10)).astype(dtype)\n    shape_like_np = np.random.uniform(size=(3, 5, 6)).astype(dtype)\n    check_result([data_np, shape_like_np], mod, shape_like_np.shape, assert_shape=True)\n\n\ndef verify_any_conv2d(\n    data_shape,\n    kernel_shape,\n    strides,\n    padding,\n    dilation,\n    static_data_shape,\n    ref_out_shape,\n    data_layout=\"NCHW\",\n    kernel_layout=\"OIHW\",\n    use_cudnn=False,\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=dtype)\n    y = relay.nn.conv2d(\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        kernel_size=kernel_shape[2:4] if kernel_layout == \"OIHW\" else kernel_shape[0:2],\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    mod[\"main\"] = relay.Function([data, kernel], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    kernel_np = np.random.uniform(size=kernel_shape).astype(dtype)\n\n    targets = None\n    if use_cudnn and tvm.get_global_func(\"tvm.contrib.cudnn.conv2d.forward\", True):\n        targets = [(\"cuda -libs=cudnn\", tvm.cuda(0))]\n\n    check_result([data_np, kernel_np], mod, ref_out_shape, assert_shape=True, targets=targets)\n\n\n# TODO(@kevinthesun): Support dynamic input height and width.\n@tvm.testing.uses_gpu\ndef test_any_conv2d():\n    verify_any_conv2d(\n        (relay.Any(), 64, 224, 224),\n        (64, 64, 3, 3),\n        (1, 1),\n        (1, 1),\n        (1, 1),\n        (1, 64, 224, 224),\n        (1, 64, 224, 224),\n    )\n    verify_any_conv2d(\n        (relay.Any(), 64, 224, 224),\n        (64, 64, 3, 3),\n        (1, 1),\n        (1, 1),\n        (2, 2),\n        (2, 64, 224, 224),\n        (2, 64, 222, 222),\n    )\n    verify_any_conv2d(\n        (relay.Any(), 64, 224, 224),\n        (64, 64, 3, 3),\n        (1, 1),\n        (1, 1),\n        (1, 1),\n        (1, 64, 224, 224),\n        (1, 64, 224, 224),\n        use_cudnn=True,\n    )\n    verify_any_conv2d(\n        (relay.Any(), 224, 224, 64),\n        (3, 3, 64, 64),\n        (1, 1),\n        (1, 1),\n        (1, 1),\n        (1, 224, 224, 64),\n        (1, 224, 224, 64),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n    verify_any_conv2d(\n        (relay.Any(), 224, 224, 64),\n        (3, 3, 64, 64),\n        (1, 1),\n        (1, 1),\n        (2, 2),\n        (2, 224, 224, 64),\n        (2, 222, 222, 64),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n    )\n\n\nclass TestAnyConv2dNCHWc:\n    data_shape = tvm.testing.parameter((relay.Any(), 8, 224, 224, 8))\n    kernel_shape = tvm.testing.parameter((8, 8, 3, 3, 8, 8))\n    strides = tvm.testing.parameter((1, 1))\n    padding = tvm.testing.parameter((1, 1))\n    data_layout = tvm.testing.parameter(\"NCHW8c\")\n    kernel_layout = tvm.testing.parameter(\"OIHW8i8o\")\n    out_layout = tvm.testing.parameter(\"NCHW8c\")\n\n    dilation, static_data_shape, ref_out_shape = tvm.testing.parameters(\n        ((1, 1), (1, 8, 224, 224, 8), (1, 8, 224, 224, 8)),\n        ((2, 2), (2, 8, 224, 224, 8), (2, 8, 222, 222, 8)),\n    )\n\n    @tvm.testing.known_failing_targets(\"cuda\", \"vulkan\")\n    def test_any_conv2d_NCHWc(\n        self,\n        target,\n        dev,\n        data_shape,\n        kernel_shape,\n        strides,\n        padding,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_layout,\n        static_data_shape,\n        ref_out_shape,\n    ):\n        mod = tvm.IRModule()\n        dtype = \"float32\"\n        data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n        kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=dtype)\n        y = relay.nn.contrib_conv2d_nchwc(\n            data,\n            kernel,\n            strides,\n            padding,\n            dilation,\n            kernel_size=kernel_shape[2:4],\n            channels=kernel_shape[0] * kernel_shape[-1],\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            out_layout=out_layout,\n        )\n        mod[\"main\"] = relay.Function([data, kernel], y)\n        data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n        kernel_np = np.random.uniform(size=kernel_shape).astype(dtype)\n        check_result(\n            [data_np, kernel_np], mod, ref_out_shape, assert_shape=True, targets=[(target, dev)]\n        )\n\n\ndef verify_any_conv1d_transpose_ncw(\n    data_shape,\n    kernel_shape,\n    strides,\n    padding,\n    dilation,\n    groups,\n    static_data_shape,\n    ref_out_shape,\n    output_padding,\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=dtype)\n    y = relay.nn.conv1d_transpose(\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        groups,\n        kernel_size=kernel_shape[2:],\n        output_padding=output_padding,\n    )\n    mod[\"main\"] = relay.Function([data, kernel], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    kernel_np = np.random.uniform(size=kernel_shape).astype(dtype)\n    check_result([data_np, kernel_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_conv1d_transpose_ncw():\n    verify_any_conv1d_transpose_ncw(\n        (relay.Any(), 64, 224),\n        (64, 192, 3),\n        (1,),\n        (1,),\n        (1,),\n        1,\n        (2, 64, 224),\n        (2, 192, 224),\n        (0, 0),\n    )\n    verify_any_conv1d_transpose_ncw(\n        (relay.Any(), 32, 224),\n        (32, 64, 3),\n        (2,),\n        (1,),\n        (1,),\n        1,\n        (1, 32, 224),\n        (1, 64, 448),\n        (1, 1),\n    )\n\n\ndef verify_any_conv2d_transpose_nchw(\n    data_shape,\n    kernel_shape,\n    strides,\n    padding,\n    dilation,\n    groups,\n    static_data_shape,\n    ref_out_shape,\n    output_padding,\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=dtype)\n    y = relay.nn.conv2d_transpose(\n        data,\n        kernel,\n        strides,\n        padding,\n        dilation,\n        groups,\n        kernel_size=kernel_shape[2:4],\n        output_padding=output_padding,\n    )\n    mod[\"main\"] = relay.Function([data, kernel], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    kernel_np = np.random.uniform(size=kernel_shape).astype(dtype)\n    check_result([data_np, kernel_np], mod, ref_out_shape, assert_shape=True)\n\n\n# TODO(@kevinthesun): Support dynamic input height and width.\n@tvm.testing.uses_gpu\ndef test_any_conv2d_transpose_nchw():\n    verify_any_conv2d_transpose_nchw(\n        (relay.Any(), 64, 224, 224),\n        (64, 192, 3, 3),\n        (1, 1),\n        (1, 1),\n        (1, 1),\n        1,\n        (2, 64, 224, 224),\n        (2, 192, 224, 224),\n        (0, 0),\n    )\n    verify_any_conv2d_transpose_nchw(\n        (relay.Any(), 32, 224, 224),\n        (32, 64, 3, 3),\n        (2, 2),\n        (1, 1),\n        (1, 1),\n        1,\n        (1, 32, 224, 224),\n        (1, 64, 448, 448),\n        (1, 1),\n    )\n\n\ndef verify_any_pool2d(\n    pool_type,\n    data_shape,\n    pool_size,\n    strides,\n    dilation,\n    padding,\n    layout,\n    static_data_shape,\n    ref_out_shape,\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    pool_func = relay.nn.max_pool2d if pool_type == \"max\" else relay.nn.avg_pool2d\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = pool_func(data, pool_size, strides, dilation, padding, layout)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_pool2d():\n    verify_any_pool2d(\n        \"max\",\n        (relay.Any(), 3, relay.Any(), relay.Any()),\n        (3, 3),\n        (1, 1),\n        (1, 1),\n        (1, 1),\n        \"NCHW\",\n        (2, 3, 220, 220),\n        (2, 3, 220, 220),\n    )\n    verify_any_pool2d(\n        \"avg\",\n        (relay.Any(), relay.Any(), relay.Any(), 4),\n        (1, 1),\n        (2, 2),\n        (1, 1),\n        (0, 0),\n        \"NHWC\",\n        (3, 220, 220, 4),\n        (3, 110, 110, 4),\n    )\n    verify_any_pool2d(\n        \"max\",\n        (relay.Any(), 3, relay.Any(), relay.Any(), 4),\n        (3, 3),\n        (2, 2),\n        (1, 1),\n        (1, 1),\n        \"NCHW4c\",\n        (2, 3, 220, 220, 4),\n        (2, 3, 110, 110, 4),\n    )\n\n\ndef verify_any_global_pool2d(pool_type, data_shape, layout, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    pool_func = relay.nn.global_max_pool2d if pool_type == \"max\" else relay.nn.global_avg_pool2d\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = pool_func(data, layout)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_global_pool2d():\n    verify_any_global_pool2d(\n        \"max\", (relay.Any(), 3, relay.Any(), relay.Any()), \"NCHW\", (2, 3, 220, 220), (2, 3, 1, 1)\n    )\n    verify_any_global_pool2d(\n        \"avg\", (relay.Any(), relay.Any(), relay.Any(), 4), \"NHWC\", (3, 220, 220, 4), (3, 1, 1, 4)\n    )\n    verify_any_global_pool2d(\n        \"max\",\n        (relay.Any(), 3, relay.Any(), relay.Any(), 4),\n        \"NCHW4c\",\n        (2, 3, 220, 220, 4),\n        (2, 3, 1, 1, 4),\n    )\n\n\ndef verify_any_split(data_shape, indices_or_sections, axis, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.split(data, indices_or_sections, axis)\n    mod[\"main\"] = relay.Function([data], y.astuple())\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    for kind in [\"vm\"]:\n        result = relay.create_executor(kind, mod=mod, device=tvm.cpu(), target=\"llvm\").evaluate()(\n            data_np\n        )\n        for ret, ref_ret in zip(result, ref_out_shape):\n            assert ret.numpy().shape == ref_ret, \"Shape mismatch: expect %s but got %s.\" % (\n                str(ref_ret),\n                str(ret.numpy().shape),\n            )\n\n\n@tvm.testing.uses_gpu\ndef test_any_split():\n    verify_any_split((relay.Any(), 4), 2, -1, (9, 4), [(9, 2), (9, 2)])\n    verify_any_split((relay.Any(), 4), 2, 1, (9, 4), [(9, 2), (9, 2)])\n    verify_any_split((relay.Any(), relay.Any()), 2, 1, (9, 4), [(9, 2), (9, 2)])\n    verify_any_split((relay.Any(), 12), (1, 4, 8), 1, (7, 12), [(7, 1), (7, 3), (7, 4)])\n    verify_any_split((relay.Any(), relay.Any()), (1, 4, 8), 1, (7, 12), [(7, 1), (7, 3), (7, 4)])\n    verify_any_split((relay.Any(), 12), (8,), 1, (7, 12), [(7, 8), (7, 4)])\n    verify_any_split((relay.Any(), relay.Any()), (8,), 1, (7, 12), [(7, 8), (7, 4)])\n\n\n@tvm.testing.uses_gpu\ndef test_any_batch_flatten():\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=any_dims(3), dtype=dtype)\n    y = relay.nn.batch_flatten(data)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=(3, 3, 10)).astype(dtype)\n    ref_out_shape = (3, 30)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n# TODO(tvm-team) Fix dense schedule\n@tvm.testing.known_failing_targets(\"cuda\", \"vulkan\")\nclass TestAnyDense:\n    (\n        data_shape,\n        weight_shape,\n        units,\n        static_data_shape,\n        static_weight_shape,\n        ref_out_shape,\n    ) = tvm.testing.parameters(\n        (any_dims(2), any_dims(2), None, (4, 16), (8, 16), (4, 8)),\n        (any_dims(2), (50, relay.Any()), 50, (4, 40), (50, 40), (4, 50)),\n    )\n\n    @tvm.testing.known_failing_targets(\"cuda\", \"vulkan\")\n    def test_any_dense(\n        self,\n        target,\n        dev,\n        data_shape,\n        weight_shape,\n        units,\n        static_data_shape,\n        static_weight_shape,\n        ref_out_shape,\n    ):\n        mod = tvm.IRModule()\n        dtype = \"float32\"\n        data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=weight_shape, dtype=dtype)\n        y = relay.nn.dense(data, weight, units)\n        mod[\"main\"] = relay.Function([data, weight], y)\n        data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n        weight_np = np.random.uniform(size=static_weight_shape).astype(dtype)\n\n        check_result(\n            [data_np, weight_np], mod, ref_out_shape, assert_shape=True, targets=[(target, dev)]\n        )\n\n    @tvm.testing.parametrize_targets(\"cuda -libs=cublas\")\n    @tvm.testing.known_failing_targets(\"cuda\", \"vulkan\")\n    def test_any_dense_cublas(\n        self,\n        target,\n        dev,\n        data_shape,\n        weight_shape,\n        units,\n        static_data_shape,\n        static_weight_shape,\n        ref_out_shape,\n    ):\n\n        self.test_any_dense(\n            target,\n            dev,\n            data_shape,\n            weight_shape,\n            units,\n            static_data_shape,\n            static_weight_shape,\n            ref_out_shape,\n        )\n\n\nclass TestAnyBatchMatmul:\n    dtype = tvm.testing.parameter(\"float32\")\n    executor_kind = tvm.testing.parameter(\"vm\", \"debug\")\n\n    (x_shape, y_shape) = tvm.testing.parameters(\n        ((1, 16, 32), (1, 32, 16)),\n        ((5, 16, 32), (5, 32, 16)),\n        ((5, 16, 32), (5, 32, 20)),\n        ((30, 16, 32), (30, 32, 20)),\n    )\n\n    # any_x = tvm.testing.parameter(\"none\", \"batch\")\n    # any_y = tvm.testing.parameter(\"none\", \"batch\", \"all\")\n\n    any_x, any_y = tvm.testing.parameters(\n        (\"none\", \"batch\"), (\"none\", \"all\"), (\"batch\", \"none\"), (\"batch\", \"batch\"), (\"batch\", \"all\")\n    )\n\n    transpose_x = tvm.testing.parameter(True, False)\n    transpose_y = tvm.testing.parameter(True, False)\n\n    @tvm.testing.fixture\n    def x_var_shape(self, x_shape, any_x):\n        if any_x == \"none\":\n            return x_shape\n        elif any_x == \"batch\":\n            return tuple(relay.Any() if i == 0 else size for i, size in enumerate(x_shape))\n        elif any_x == \"all\":\n            return tuple(relay.Any() for _ in x_shape)\n\n    @tvm.testing.fixture\n    def y_var_shape(self, y_shape, any_y):\n        if any_y == \"none\":\n            return y_shape\n        elif any_y == \"batch\":\n            return tuple(relay.Any() if i == 0 else size for i, size in enumerate(y_shape))\n        elif any_y == \"all\":\n            return tuple(relay.Any() for _ in y_shape)\n\n    @tvm.testing.known_failing_targets(\"cuda\", \"vulkan\")\n    def test_any_batch_matmul(\n        self,\n        target,\n        dev,\n        x_shape,\n        y_shape,\n        any_x,\n        any_y,\n        x_var_shape,\n        y_var_shape,\n        transpose_x,\n        transpose_y,\n        executor_kind,\n        dtype,\n    ):\n        if transpose_x:\n            x_shape = (x_shape[0], x_shape[2], x_shape[1])\n            x_var_shape = (x_var_shape[0], x_var_shape[2], x_var_shape[1])\n\n        if transpose_y:\n            y_shape = (y_shape[0], y_shape[2], y_shape[1])\n            y_var_shape = (y_var_shape[0], y_var_shape[2], y_var_shape[1])\n\n        x = relay.var(\"x\", relay.TensorType(x_var_shape, dtype))\n        y = relay.var(\"y\", relay.TensorType(y_var_shape, dtype))\n        z = relay.nn.batch_matmul(x, y, transpose_a=transpose_x, transpose_b=transpose_y)\n\n        func = relay.Function([x, y], z)\n        x_np = np.random.uniform(size=x_shape).astype(dtype)\n        y_np = np.random.uniform(size=y_shape).astype(dtype)\n        z_np = tvm.topi.testing.batch_matmul(x_np, y_np, trans_x=transpose_x, trans_y=transpose_y)\n\n        mod = tvm.ir.IRModule.from_expr(func)\n        z = relay.create_executor(executor_kind, mod=mod, device=dev, target=target).evaluate()(\n            x_np, y_np\n        )\n        tvm.testing.assert_allclose(z.numpy(), z_np, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef verify_any_pad(data_shape, pad_width, static_data_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.nn.pad(data, pad_width)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_out = np.pad(data_np, pad_width)\n    check_result([data_np], mod, ref_out)\n\n\n@tvm.testing.uses_gpu\ndef test_any_pad():\n    verify_any_pad(any_dims(3), ((0, 0), (1, 1), (2, 2)), (1, 2, 3))\n    verify_any_pad(any_dims(4), ((1, 0), (1, 3), (0, 2), (9, 0)), (13, 11, 3, 1))\n\n\ndef verify_any_dilate(data_shape, strides, static_data_shape, dilation_value=None):\n    assert len(data_shape) == len(strides)\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    if dilation_value is None:\n        y = relay.nn.dilate(data, strides)\n    else:\n        y = relay.nn.dilate(data, strides, dilation_value)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_shape = tuple(\n        (static_data_shape[i] - 1) * strides[i] + 1 for i in range(len(static_data_shape))\n    )\n    if dilation_value is None:\n        dilation_value = 0.0\n    ref_out = np.ones(shape=ref_shape, dtype=dtype)\n    ref_out = dilation_value * ref_out\n    ref_out[tuple(slice(None, None, strides[i]) for i in range(len(data_shape)))] = data_np\n    check_result([data_np], mod, ref_out)\n\n\n@tvm.testing.uses_gpu\ndef test_any_dilate():\n    verify_any_dilate(any_dims(1), (1,), (1,))\n    verify_any_dilate(any_dims(1), (1,), (5,))\n    verify_any_dilate(any_dims(1), (5,), (5,))\n    verify_any_dilate(any_dims(3), (1, 1, 1), (1, 2, 3))\n    verify_any_dilate(any_dims(3), (1, 1, 2), (1, 2, 3))\n    verify_any_dilate(any_dims(3), (1, 1, 5), (1, 2, 3))\n    verify_any_dilate(any_dims(3), (3, 7, 5), (1, 2, 3))\n    verify_any_dilate(any_dims(4), (3, 7, 1, 5), (1, 2, 3, 4))\n    verify_any_dilate(any_dims(4), (3, 7, 1, 5), (1, 2, 3, 4), 1.0)\n\n\ndef verify_any_softmax(data_shape, axis, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.nn.softmax(data, axis)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_softmax():\n    verify_any_softmax(any_dims(3), -1, (1, 2, 3), (1, 2, 3))\n    verify_any_softmax(any_dims(4), 2, (13, 11, 3, 1), (13, 11, 3, 1))\n\n\ndef verify_any_relu(data_shape, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.nn.relu(data)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_relu():\n    verify_any_relu(any_dims(3), (1, 2, 3), (1, 2, 3))\n    verify_any_relu(any_dims(4), (13, 11, 3, 1), (13, 11, 3, 1))\n\n\ndef verify_any_prelu(data_shape, alpha, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    alpha = relay.const(np.array([alpha]), dtype=dtype)\n    y = relay.nn.prelu(data, alpha)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_prelu():\n    verify_any_prelu(any_dims(3), 1, (1, 2, 3), (1, 2, 3))\n    verify_any_prelu(any_dims(4), 2, (13, 11, 3, 1), (13, 11, 3, 1))\n\n\ndef verify_any_leaky_relu(data_shape, alpha, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.nn.leaky_relu(data, alpha)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_leaky_relu():\n    verify_any_leaky_relu(any_dims(3), 0.1, (1, 2, 3), (1, 2, 3))\n    verify_any_leaky_relu(any_dims(4), 0.2, (13, 11, 3, 1), (13, 11, 3, 1))\n\n\ndef verify_any_bias_add(data_shape, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    bias = relay.const(np.random.randn(1), dtype=dtype)\n    y = relay.nn.bias_add(data, bias)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_bias_add():\n    verify_any_bias_add(any_dims(3), (1, 2, 3), (1, 2, 3))\n    verify_any_bias_add(any_dims(4), (13, 11, 3, 1), (13, 11, 3, 1))\n\n\ndef verify_any_topk(data_shape, kval, np_dshape, dtype, ret_type=\"indices\", const_k=False):\n    mod = tvm.IRModule()\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    np_data = np.random.uniform(size=np_dshape).astype(dtype)\n    if const_k:\n        k = relay.const(kval)\n        args = [data]\n        in_vals = [np_data]\n    else:\n        k = relay.var(\"k\", shape=(), dtype=\"int32\")\n        args = [data, k]\n        in_vals = [np_data, kval]\n    out = relay.topk(data, k, ret_type=ret_type)\n    if ret_type == \"both\":\n        out = out[0]\n    mod[\"main\"] = relay.Function(args, out)\n\n    sorted = np.argsort(-np_data)\n    if len(np_dshape) == 2:\n        ref_out = sorted[:, 0:kval]\n    else:\n        ref_out = sorted[0:kval]\n\n    check_result(in_vals, mod, ref_out)\n\n\n@tvm.testing.uses_gpu\ndef test_any_topk():\n    verify_any_topk(any_dims(1), 5, (10,), \"float32\")\n    verify_any_topk(any_dims(2), 2, (6, 3), \"int32\")\n    verify_any_topk(any_dims(2), 3, (6, 3), \"float32\", const_k=True)\n    verify_any_topk(any_dims(1), 0, (0,), \"float32\", ret_type=\"both\")\n\n\ndef verify_any_get_valid_counts(num_anchor_real, dtype, targets=None):\n    mod = tvm.IRModule()\n    batch_size = 1\n    num_anchor = relay.Any()\n    data = relay.var(\"data\", shape=(batch_size, num_anchor, 5), dtype=dtype)\n    np_data = np.random.uniform(size=(batch_size, num_anchor_real, 5)).astype(dtype)\n\n    np_out1 = np.zeros(shape=(batch_size,))\n    np_out2 = np.zeros(shape=np_data.shape).astype(dtype)\n    np_out3 = np.zeros(shape=(batch_size, num_anchor_real))\n    score_threshold = 0.95\n\n    for i in range(batch_size):\n        np_out1[i] = 0\n        inter_idx = 0\n        for j in range(num_anchor_real):\n            score = np_data[i, j, 0]\n            if score > score_threshold:\n                for k in range(5):\n                    np_out2[i, inter_idx, k] = np_data[i, j, k]\n                np_out1[i] += 1\n                np_out3[i, inter_idx] = j\n                inter_idx += 1\n            if j >= np_out1[i]:\n                for k in range(5):\n                    np_out2[i, j, k] = -1.0\n                np_out3[i, j] = -1\n\n    z = relay.vision.get_valid_counts(data, score_threshold, 0, score_index=0)\n\n    mod[\"main\"] = relay.Function([data], z.astuple())\n\n    check_result([np_data], mod, [np_out1, np_out2, np_out3], targets=targets)\n\n\n@tvm.testing.uses_gpu\ndef test_any_get_valid_counts():\n    verify_any_get_valid_counts(10, \"float32\")\n    # opencl seems to have issues with empty size buffer\n    # Check failed: err_code == CL_SUCCESS == false: OpenCL Error,\n    # code=-61: CL_INVALID_BUFFER_SIZE\n    targets = []\n    for tgt, dev in tvm.testing.enabled_targets():\n        if \"opencl\" not in tgt:\n            targets.append((tgt, dev))\n    verify_any_get_valid_counts(0, \"float32\", targets=targets)\n\n\n@tvm.testing.uses_gpu\ndef test_fused_ops():\n    x = relay.var(\"x\", shape=(relay.Any(), relay.Any()), dtype=\"float32\")\n    y0 = x + relay.const(1.0, \"float32\")\n    y1 = y0 * relay.const(2.0, \"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y1)\n    data = np.random.uniform(size=(5, 4)).astype(\"float32\")\n    check_result([data], mod, (data + 1) * 2)\n\n\n@tvm.testing.uses_gpu\ndef test_arange_with_dynamic_shape():\n    # m, n, k = relay.ShapeVar('m'), relay.ShapeVar('n'), relay.ShapeVar('k')\n    m, n, k = relay.Any(), relay.Any(), relay.Any()\n    x = relay.var(\"x\", shape=(m, n, k), dtype=\"float32\")\n    y0 = relay.shape_of(x)\n    y1 = relay.take(y0, relay.const(0, \"int32\"))\n    y2 = relay.op.arange(y1, dtype=\"int32\")\n    y3 = y2 + relay.const(1, dtype=\"int32\")\n    data = np.random.rand(10, 5, 3).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y3)\n    check_result([data], mod, np.array(range(10)).astype(\"int32\") + 1)\n\n\ndef verify_any_random_strided_slice(\n    begin_shape,\n    end_shape,\n    strides_shape,\n    data_shape,\n    slice_mode=\"end\",\n    const_attrs=False,\n):\n    # Generate random numpy input data\n    np_begin = np.random.randint(2, size=begin_shape, dtype=\"int32\")\n    np_end = np.random.randint(5, 10, size=end_shape, dtype=\"int32\")\n    np_strides = np.random.randint(\n        1, 2 if slice_mode == \"size\" else 3, size=strides_shape, dtype=\"int32\"\n    )\n\n    verify_any_strided_slice(\n        np_begin, np_end, np_strides, data_shape, slice_mode=slice_mode, const_attrs=const_attrs\n    )\n\n\ndef verify_any_strided_slice(\n    np_begin,\n    np_end,\n    np_strides,\n    data_shape,\n    axes=None,\n    slice_mode=\"end\",\n    const_attrs=False,\n):\n    np_data = np.random.uniform(size=data_shape).astype(\"float32\")\n    # target numpy result\n    ref_res = tvm.topi.testing.strided_slice_python(\n        np_data, np_begin, np_end, np_strides, slice_mode, axes\n    )\n\n    # Relay Module\n    mod = tvm.IRModule()\n    data = relay.var(\"data\", shape=any_dims(len(data_shape)), dtype=\"float32\")\n    if const_attrs:\n        begin = relay.const(np_begin)\n        end = relay.const(np_end)\n        strides = relay.const(np_strides)\n        args = [data]\n        np_inputs = [np_data]\n    else:\n        begin = relay.var(\"begin\", shape=np_begin.shape, dtype=\"int32\")\n        end = relay.var(\"end\", shape=np_end.shape, dtype=\"int32\")\n        strides = relay.var(\"strides\", shape=np_strides.shape, dtype=\"int32\")\n        args = [data, begin, end, strides]\n        np_inputs = [np_data, np_begin, np_end, np_strides]\n\n    y = relay.strided_slice(\n        data, begin=begin, end=end, strides=strides, axes=axes, slice_mode=slice_mode\n    )\n    mod[\"main\"] = relay.Function(args, y)\n\n    check_result(np_inputs, mod, ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_any_strided_slice():\n    verify_any_random_strided_slice((2,), (2,), (2,), (15, 21))\n    verify_any_random_strided_slice((3,), (3,), (3,), (15, 17, 21))\n    verify_any_random_strided_slice((3,), (3,), (3,), (23, 29, 41))\n    verify_any_random_strided_slice((4,), (4,), (4,), (40, 50, 60, 70))\n    verify_any_random_strided_slice((3,), (3,), (3,), (15, 17, 21), slice_mode=\"size\")\n    verify_any_random_strided_slice((2,), (2,), (2,), (15, 21), const_attrs=True)\n\n    begin = np.array([0, 1000000]).astype(\"int32\")\n    end = np.array([1000000, -1000000]).astype(\"int32\")\n    strides = np.array([1, -1]).astype(\"int32\")\n    verify_any_strided_slice(begin, end, strides, (15, 21), const_attrs=False)\n    verify_any_strided_slice(begin, end, strides, (15, 21), const_attrs=True)\n    verify_any_strided_slice(begin, end, strides, (15, 17, 21), axes=[0, 2], const_attrs=True)\n\n\n@tvm.testing.uses_gpu\ndef test_recursive_concat():\n    \"\"\"\n    fn @concat_loop(%i: int32, %st: (any, 1)) -> (any, 1) {\n        if (%i < 10) {\n            let %i = reshape(cast(i, \"float32\"), newshape=(1, ))\n            let %new_st = concatenate((st, i), axis=0)\n            concat_loop(%i + 1, )\n        } else {\n            st\n        }\n    }\n    \"\"\"\n    # Initial Values.\n    i = relay.var(\"i\", shape=(), dtype=\"int32\")\n    st = relay.var(\"st\", shape=(relay.Any(), 1), dtype=\"int32\")\n\n    def _cond(i, st):\n        return relay.op.min(relay.op.less(i, int32(10)))\n\n    def _body(i, st):\n        i_vec = relay.op.reshape(i, (1, 1))\n        ret = relay.op.concatenate([st, i_vec], axis=0)\n        return i + int32(1), ret\n\n    loop = while_loop(_cond, [i, st], _body)\n    start = relay.var(\"start\", shape=(), dtype=\"int32\")\n    body = loop(start, relay.op.reshape(relay.const(0), newshape=(1, 1)))\n    func = relay.Function([start], relay.TupleGetItem(body, 1))\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    data = np.array(0.0, dtype=\"int32\")\n    ref = np.array([0] + list(range(10))).reshape((11, 1)).astype(\"int32\")\n    check_result([data], mod, ref)\n\n\n@tvm.testing.uses_gpu\ndef test_recursive_concat_with_wrong_annotation():\n    \"\"\"\n    v0.0.1\n    fn (%start: int32) {\n        %7 = {\n            let %while_loop = fn (%i: int32, %st: Tensor[(1, 1), int32]) {\n            %0 = less(%i, 10)\n            %1 = min(%0)\n            if (%1) {\n                %2 = add(%i, 1)\n                %3 = reshape(%i, newshape=[1, 1])\n                %4 = (%st, %3)\n                /* The result of concat should be 1,1 but it is 2, 1. */\n                %5 = concatenate(%4)\n                %while_loop(%2, %5)\n            } else {\n                (%i, %st)\n            }\n        }\n        %6 = reshape(0, newshape=[1, 1])\n        %while_loop(%start, %6)\n    }\n    %7.1\n    }\n    \"\"\"\n    # Initial Values.\n    i = relay.var(\"i\", shape=(), dtype=\"int32\")\n    st = relay.var(\"st\", shape=(1, 1), dtype=\"int32\")\n\n    def _cond(i, st):\n        return relay.op.min(relay.op.less(i, int32(10)))\n\n    def _body(i, st):\n        i_vec = relay.op.reshape(i, (1, 1))\n        ret = relay.op.concatenate([st, i_vec], axis=0)\n        return i + int32(1), ret\n\n    loop = while_loop(_cond, [i, st], _body)\n    start = relay.var(\"start\", shape=(), dtype=\"int32\")\n    body = loop(start, relay.op.reshape(relay.const(0), newshape=(1, 1)))\n    func = relay.Function([start], relay.TupleGetItem(body, 1))\n\n    with DiagnosticTesting() as diagnostics:\n        diagnostics.assert_message(\n            \"The Relay type checker is unable to show the following types match:\\n\"\n            \"  Tensor[(2, 1), int32]\\n\"\n            \"  Tensor[(1, 1), int32]\\n\"\n            \"In particular:\\n\"\n            \"  dimension 0 conflicts: 2 does not match 1.\"\n        )\n        func = infer_type(func)\n\n\n@tvm.testing.uses_gpu\ndef test_tuple_get_item():\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    static_data_shape = (9, 4)\n    data_shape = (relay.Any(), 4)\n    indices_or_sections = 2\n    axis = 1\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.split(data, indices_or_sections, axis)\n    y = relay.expr.TupleGetItem(y.astuple(), 0)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_out_shape = (9, 2)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_mixed_input_type():\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    static_data_shape = (9, 4)\n    data_shape = (relay.Any(), 4)\n    tensor_type = relay.TensorType(data_shape, dtype)\n    tuple_type = relay.TupleType([tensor_type, tensor_type])\n    data0 = relay.var(\"d0\", type_annotation=relay.TupleType([tuple_type, tensor_type]))\n    data1 = relay.var(\"d1\", shape=(relay.Any(), 4), dtype=dtype)\n    data_tuple = relay.expr.TupleWrapper(data0, 2)\n    nested_data_tuple = relay.expr.TupleWrapper(data_tuple[0], 2)\n    y = nested_data_tuple[1] * data_tuple[1] + data1\n    mod[\"main\"] = relay.Function([data0, data1], y)\n    data_np0 = np.random.uniform(size=static_data_shape).astype(dtype)\n    data_np1 = np.random.uniform(size=static_data_shape).astype(dtype)\n    ref_out_shape = (9, 4)\n    check_result(\n        [[[data_np0, data_np0], data_np0], data_np1],\n        mod,\n        ref_out_shape,\n        assert_shape=True,\n        only_vm=True,\n    )\n\n\ndef verify_any_crop_and_resize(\n    data_shape,\n    boxes_shape,\n    box_indices_shape,\n    crop_size,\n    layout,\n    static_boxes,\n    static_box_indices_shape,\n    ref_out_shape,\n):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    indices_dtype = \"int32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    boxes = relay.var(\"boxes\", shape=boxes_shape, dtype=dtype)\n    box_indices = relay.var(\"box_indices\", shape=box_indices_shape, dtype=indices_dtype)\n    y = relay.image.crop_and_resize(data, boxes, box_indices, crop_size, layout)\n    mod[\"main\"] = relay.Function([data, boxes, box_indices], y)\n    data_np = np.random.uniform(size=data_shape).astype(dtype)\n    boxes_np = np.random.uniform(size=static_boxes).astype(dtype)\n    box_indices_np = np.random.uniform(size=static_box_indices_shape).astype(indices_dtype)\n    check_result([data_np, boxes_np, box_indices_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_crop_and_resize():\n    verify_any_crop_and_resize(\n        data_shape=(1, 234, 234, 256),\n        boxes_shape=(relay.Any(), 4),\n        box_indices_shape=(relay.Any(),),\n        crop_size=(14, 14),\n        layout=\"NHWC\",\n        static_boxes=(128, 4),\n        static_box_indices_shape=(128,),\n        ref_out_shape=(128, 14, 14, 256),\n    )\n    verify_any_crop_and_resize(\n        data_shape=(1, 256, 234, 234),\n        boxes_shape=(relay.Any(), 4),\n        box_indices_shape=(relay.Any(),),\n        crop_size=(14, 14),\n        layout=\"NCHW\",\n        static_boxes=(128, 4),\n        static_box_indices_shape=(128,),\n        ref_out_shape=(128, 256, 14, 14),\n    )\n\n\ndef verify_any_mirror_pad(data_shape, pad_width, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.nn.mirror_pad(data, pad_width)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_mirror_pad():\n    verify_any_mirror_pad(\n        data_shape=(1, 256, 232, 232),\n        pad_width=((0, 0), (0, 0), (1, 1), (1, 1)),\n        static_data_shape=(1, 256, 232, 232),\n        ref_out_shape=(1, 256, 234, 234),\n    )\n\n\ndef verify_any_ndarray_size(data_np_shape):\n    v = relay.var(\"v\", shape=any_dims(len(data_np_shape)), dtype=\"float32\")\n    n = relay.ndarray_size(v, dtype=\"int32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([v], n)\n    np_data = np.zeros(data_np_shape, dtype=\"float32\")\n    ref_res = np.size(np_data)\n    check_result([np_data], mod, ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_any_ndarray_size():\n    verify_any_ndarray_size((2,))\n    verify_any_ndarray_size((2, 2))\n    verify_any_ndarray_size((1, 2, 3, 4))\n\n\ndef verify_any_resize2d(data_shape, scale, layout, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    if layout == \"NHWC\":\n        size = (data_shape[1] * scale, data_shape[2] * scale)\n    else:\n        size = (data_shape[2] * scale, data_shape[3] * scale)\n    y = relay.image.resize2d(data, size, None, layout)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_resize():\n    verify_any_resize2d(\n        data_shape=(relay.Any(), 4, 4, 4),\n        scale=2,\n        layout=\"NHWC\",\n        static_data_shape=(1, 4, 4, 4),\n        ref_out_shape=(1, 8, 8, 4),\n    )\n    verify_any_resize2d(\n        data_shape=(relay.Any(), 8, 17, 20),\n        scale=3,\n        layout=\"NCHW\",\n        static_data_shape=(2, 8, 17, 20),\n        ref_out_shape=(2, 8, 51, 60),\n    )\n\n\ndef verify_any_grid_sample(data_shape, grid_shape, static_data_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    grid = relay.var(\"grid\", shape=grid_shape, dtype=dtype)\n    y = relay.image.grid_sample(data, grid)\n    mod[\"main\"] = relay.Function([data, grid], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    grid_np = np.random.uniform(size=grid_shape).astype(dtype)\n    check_result([data_np, grid_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_grid_sample():\n    verify_any_grid_sample(\n        data_shape=(relay.Any(), 4, 16, 32),\n        grid_shape=(4, 2, 8, 8),\n        static_data_shape=(4, 4, 16, 32),\n        ref_out_shape=(4, 4, 8, 8),\n    )\n    verify_any_grid_sample(\n        data_shape=(relay.Any(), 4, 16, 32),\n        grid_shape=(4, 2, 32, 32),\n        static_data_shape=(4, 4, 16, 32),\n        ref_out_shape=(4, 4, 32, 32),\n    )\n\n\ndef verify_any_affine_grid(num_batch, static_num_batch, target_shape, ref_out_shape):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data_shape = (num_batch, 2, 3)\n    static_data_shape = (static_num_batch, 2, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.image.affine_grid(data, target_shape)\n    mod[\"main\"] = relay.Function([data], y)\n    data_np = np.random.uniform(size=static_data_shape).astype(dtype)\n    check_result([data_np], mod, ref_out_shape, assert_shape=True)\n\n\n@tvm.testing.uses_gpu\ndef test_any_affine_grid():\n    verify_any_affine_grid(\n        num_batch=relay.Any(),\n        static_num_batch=1,\n        target_shape=(16, 32),\n        ref_out_shape=(1, 2, 16, 32),\n    )\n    verify_any_affine_grid(\n        num_batch=relay.Any(),\n        static_num_batch=8,\n        target_shape=(32, 32),\n        ref_out_shape=(8, 2, 32, 32),\n    )\n\n\ndef test_any_consecutive_broadcast():\n    dtype = \"float32\"\n    data0 = relay.var(\"data0\", shape=any_dims(2), dtype=dtype)\n    data1 = relay.var(\"data1\", shape=any_dims(2), dtype=dtype)\n    data2 = relay.var(\"data2\", shape=any_dims(2), dtype=dtype)\n    data3 = relay.var(\"data3\", shape=any_dims(2), dtype=dtype)\n\n    out0 = data0 + data1\n    out1 = data0 * data1\n    out2 = out0 - out1\n\n    out3 = data2 + data3\n    out4 = data2 * data3\n    out5 = out3 - out4\n\n    out6 = out2 * out5\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([data0, data1, data2, data3], out6)\n\n    np_data0 = np.random.uniform(size=(1, 4)).astype(dtype)\n    np_data1 = np.random.uniform(size=(2, 4)).astype(dtype)\n    np_data2 = np.random.uniform(size=(1, 4)).astype(dtype)\n    np_data3 = np.random.uniform(size=(2, 4)).astype(dtype)\n    ref_res = ((np_data0 + np_data1) - (np_data0 * np_data1)) * (\n        (np_data2 + np_data3) - (np_data2 * np_data3)\n    )\n    check_result([np_data0, np_data1, np_data2, np_data3], mod, ref_res)\n\n\ndef test_reshape_concat():\n    dtype = \"float32\"\n    d0 = relay.var(\"d0\", shape=any_dims(2), dtype=dtype)\n    d1 = relay.var(\"d1\", shape=any_dims(3), dtype=dtype)\n    out = relay.op.concatenate([relay.op.reshape(d0, [-1]), relay.op.reshape(d1, [-1])], axis=0)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d0, d1], out)\n    np_data0 = np.random.uniform(size=(4, 5)).astype(dtype)\n    np_data1 = np.random.uniform(size=(2, 5, 2)).astype(dtype)\n    ref_res = np.concatenate([np.reshape(np_data0, [-1]), np.reshape(np_data1, [-1])], axis=0)\n    check_result([np_data0, np_data1], mod, ref_res)\n\n    d0 = relay.var(\"d0\", shape=any_dims(2), dtype=dtype)\n    d1 = relay.var(\"d1\", shape=any_dims(2), dtype=dtype)\n    s0 = relay.var(\"s0\", shape=any_dims(3), dtype=dtype)\n    s1 = relay.var(\"s1\", shape=any_dims(3), dtype=dtype)\n    out = relay.op.concatenate(\n        [relay.op.reshape_like(d0, s0), relay.op.reshape_like(d1, s1)], axis=0\n    )\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d0, d1, s0, s1], out)\n    np_data0 = np.random.uniform(size=(4, 5)).astype(dtype)\n    np_data1 = np.random.uniform(size=(8, 5)).astype(dtype)\n    np_shape_like0 = np.random.uniform(size=(2, 2, 5)).astype(dtype)\n    np_shape_like1 = np.random.uniform(size=(4, 2, 5)).astype(dtype)\n    ref_res = np.concatenate(\n        [np.reshape(np_data0, np_shape_like0.shape), np.reshape(np_data1, np_shape_like1.shape)],\n        axis=0,\n    )\n    check_result([np_data0, np_data1, np_shape_like0, np_shape_like1], mod, ref_res)\n\n\ndef test_any_adv_index():\n    data = relay.var(\"data\", shape=(5, relay.Any(), relay.Any()), dtype=\"float32\")\n    index0 = relay.var(\"index0\", shape=(1, relay.Any()), dtype=\"int64\")\n    index1 = relay.var(\"index1\", shape=(relay.Any(), 1), dtype=\"int64\")\n    out = relay.adv_index([data, index0, index1])\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([data, index0, index1], out)\n    np_data_shape = (5, 5, 10)\n    np_index0_shape = (1, 4)\n    np_index1_shape = (4, 1)\n    np_data = np.random.uniform(size=np_data_shape).astype(\"float32\")\n    np_index0 = np.random.uniform(0, np_data_shape[0], size=np_index0_shape).astype(\"int64\")\n    np_index1 = np.random.uniform(0, np_data_shape[0], size=np_index1_shape).astype(\"int64\")\n    ref_res = np_data[tuple([np_index0, np_index1])]\n    print(ref_res.shape)\n    check_result([np_data, np_index0, np_index1], mod, ref_res)\n\n\ndef verify_any_repeat(data_shape, np_dshape, repeats, axis):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n    y = relay.repeat(data, repeats, axis)\n    mod[\"main\"] = relay.Function([data], y)\n    np_data = np.random.uniform(size=np_dshape).astype(dtype)\n    ref_res = np.repeat(np_data, repeats, axis)\n    check_result([np_data], mod, ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_any_repeat():\n    verify_any_repeat(any_dims(2), (1, 2), 2, 0)\n    verify_any_repeat(any_dims(1), (3,), 3, -1)\n    verify_any_repeat(any_dims(4), (2, 1, 1, 4), 4, 2)\n\n\ndef verify_any_stack(data_shape, np_dshape, num_data, axis):\n    mod = tvm.IRModule()\n    dtype = \"float32\"\n    inputs = []\n    for i in range(num_data):\n        inputs.append(relay.var(\"data{}\".format(i), shape=data_shape, dtype=dtype))\n    y = relay.stack(inputs, axis)\n    mod[\"main\"] = relay.Function(inputs, y)\n    np_inputs = []\n    for _ in range(num_data):\n        np_inputs.append(np.random.uniform(size=np_dshape).astype(dtype))\n    ref_res = np.stack(np_inputs, axis)\n    check_result(np_inputs, mod, ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_any_stack():\n    verify_any_stack(any_dims(2), (1, 2), 3, 0)\n    verify_any_stack(any_dims(1), (3,), 4, -1)\n    verify_any_stack(any_dims(4), (2, 1, 1, 4), 2, 2)\n\n\ndef verify_any_where(\n    cond_shape, x_shape, y_shape, cond_np_shape, x_np_shape, y_np_shape, y_np_shape_invalid=None\n):\n    dtype = \"float32\"\n    cond = relay.var(\"cond\", shape=cond_shape, dtype=\"bool\")\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    y = relay.var(\"y\", shape=y_shape, dtype=dtype)\n    z = relay.where(cond, x, y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([cond, x, y], z)\n\n    cond_np = np.random.randn(*cond_np_shape) > 0\n    x_np = np.random.randn(*x_np_shape).astype(dtype)\n    y_np = np.random.randn(*y_np_shape).astype(dtype)\n    expected = np.where(cond_np, x_np, y_np)\n\n    check_result([cond_np, x_np, y_np], mod, expected)\n\n    # verify invalid broadcasting check\n    if y_np_shape_invalid:\n        y_np_bad = np.random.randn(*y_np_shape_invalid).astype(dtype)\n        try:\n            check_result([cond_np, x_np, y_np_bad], mod, expected)\n        except tvm.error.TVMError as e:\n            error_msg = str(e).split(\"\\n\")[-1]\n            assert \"Invalid broadcast shapes\" in error_msg\n\n\n@tvm.testing.uses_gpu\ndef test_any_where():\n    verify_any_where(any_dims(1), (5,), (5,), (5,), (5,), (5,))\n    verify_any_where(any_dims(1), any_dims(1), (5,), (5,), (5,), (5,))\n    verify_any_where(any_dims(1), any_dims(1), any_dims(1), (5,), (5,), (5,))\n    verify_any_where((5,), any_dims(1), any_dims(1), (5,), (5,), (5,))\n\n    # where with broadcast\n    verify_any_where(any_dims(1), any_dims(1), any_dims(1), (5,), (1,), (5,))\n    verify_any_where(any_dims(1), any_dims(2), any_dims(2), (5,), (5, 5), (5, 5))\n    verify_any_where(any_dims(1), any_dims(1), any_dims(2), (5,), (5,), (5, 5))\n    verify_any_where(\n        any_dims(2), any_dims(2), any_dims(2), (3, 4), (3, 1), (1, 4), y_np_shape_invalid=(2, 4)\n    )\n\n    # Test scalar where in a dynamically shaped graph\n    x = relay.var(\"x\", shape=any_dims(1), dtype=\"int64\")\n    y = relay.var(\"y\", shape=any_dims(2), dtype=\"float32\")\n\n    left = relay.take(x, relay.const(1, dtype=\"int32\")) + relay.const(4, \"int64\")\n    right = relay.const(4, \"int64\")\n    where = relay.where(relay.const(False, \"bool\"), left, right)\n    z = relay.take(y, where, axis=1)\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], z)\n\n    x_np = np.random.randn(2).astype(\"int64\")\n    y_np = np.random.randn(2, 6).astype(\"float32\")\n    expected = y_np[:, 4]\n\n    check_result([x_np, y_np], mod, expected)\n\n\n@tvm.testing.uses_gpu\ndef test_non_max_suppression():\n    x0 = relay.var(\"x0\", relay.ty.TensorType((1, relay.Any(), 6), \"float32\"))\n    x1 = relay.var(\"x1\", relay.ty.TensorType((1,), \"int32\"))\n    x2 = relay.var(\"x2\", relay.ty.TensorType((1, relay.Any()), \"int32\"))\n    x3 = relay.var(\"x3\", relay.ty.TensorType((), \"int32\"))\n    z = relay.vision.non_max_suppression(\n        x0,\n        x1,\n        x2,\n        x3,\n        iou_threshold=0.5,\n        force_suppress=True,\n        top_k=2,\n        return_indices=True,\n        invalid_to_bottom=False,\n    )\n    z = z.astuple()\n    func = relay.Function([x0, x1, x2, x3], z)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n\n    np_data = np.array(\n        [\n            [\n                [0, 0.8, 1, 20, 25, 45],\n                [1, 0.7, 30, 60, 50, 80],\n                [0, 0.4, 4, 21, 19, 40],\n                [2, 0.9, 35, 61, 52, 79],\n                [1, 0.5, 100, 60, 70, 110],\n            ]\n        ]\n    ).astype(\"float32\")\n    np_valid_count = np.array([4]).astype(\"int32\")\n    np_indices = np.array([[0, 1, 3, 4, -1]]).astype(\"int32\")\n    np_max_output_size = -1\n    np_indices_result = np.array([[4, 0, -1, -1, -1]])\n    np_valid_box_count = np.array([[2]]).astype(\"int32\")\n\n    check_result(\n        [np_data, np_valid_count, np_indices, np_max_output_size],\n        mod,\n        [np_indices_result, np_valid_box_count],\n        only_vm=False,\n    )\n\n    np_data = np.zeros((1, 0, 6)).astype(\"float32\")\n    np_valid_count = np.array([0]).astype(\"int32\")\n    np_indices = np.zeros((1, 0)).astype(\"int32\")\n    np_max_output_size = -1\n    np_indices_result = np.zeros((1, 0))\n    np_valid_box_count = np.array([[0]]).astype(\"int32\")\n\n    check_result(\n        [np_data, np_valid_count, np_indices, np_max_output_size],\n        mod,\n        [np_indices_result, np_valid_box_count],\n        only_vm=False,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_all_class_non_max_suppression():\n    def verify_all_class_non_max_suppression(\n        boxes_np,\n        scores_np,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        expected,\n        output_format=\"onnx\",\n    ):\n        batch_size = boxes_np.shape[0]\n        num_classes = scores_np.shape[1]\n        num_boxes = relay.Any()\n        boxes = relay.var(\"boxes\", relay.ty.TensorType((batch_size, num_boxes, 4), \"float32\"))\n        scores = relay.var(\n            \"scores\", relay.ty.TensorType((batch_size, num_classes, num_boxes), \"float32\")\n        )\n\n        nms_out = relay.vision.all_class_non_max_suppression(\n            boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, output_format\n        )\n\n        if output_format == \"onnx\":\n            three = relay.const(np.array([3]), dtype=\"int64\")\n            begin = relay.const(np.array([0, 0]), dtype=\"int64\")\n            end = relay.op.concatenate([nms_out[1], three], axis=0)\n            strides = relay.const(np.array([1, 1]), dtype=\"int64\")\n            out = relay.op.strided_slice(nms_out[0], begin, end, strides)\n            mod = tvm.IRModule()\n            mod[\"main\"] = relay.Function([boxes, scores], out)\n            check_result([boxes_np, scores_np], mod, [expected])\n        else:\n            out = nms_out.tuple_value\n            mod = tvm.IRModule()\n            mod[\"main\"] = relay.Function([boxes, scores], out)\n            check_result([boxes_np, scores_np], mod, expected)\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.5, 0.5, 0.4, 0.4],\n                [0.0, 0.0, 0.5, 0.5],\n                [0.5, 0.5, 0.9, 0.9],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n        ]\n    ).astype(\"float32\")\n\n    scores = np.array(\n        [\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.8, 0.2, 0.6, 0.3, 0.9]],\n        ]\n    ).astype(\"float32\")\n\n    max_output_boxes_per_class = 2\n    iou_threshold = 0.8\n    score_threshold = 0.4\n\n    expected = np.array([[0, 0, 4], [0, 0, 2], [0, 1, 4], [0, 1, 0]])\n\n    verify_all_class_non_max_suppression(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, expected\n    )\n\n    expected = [\n        np.array(\n            [[[0, 4], [0, 2], [1, 4], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]]\n        ),\n        np.array(\n            [\n                [\n                    0.9,\n                    0.6,\n                    0.9,\n                    0.8,\n                    0.0,\n                    0.0,\n                    0.0,\n                    0.0,\n                    0.0,\n                    0.0,\n                ]\n            ]\n        ),\n        np.array([4]),\n    ]\n\n    verify_all_class_non_max_suppression(\n        boxes,\n        scores,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        expected,\n        output_format=\"tensorflow\",\n    )\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 1.0, 1.0],\n                [0.0, 0.1, 0.9, 1.2],\n            ]\n        ]\n    ).astype(np.float32)\n    scores = np.array([[[0.2, 0.3], [0.3, 0.2]]]).astype(np.float32)\n    iou_threshold = 0.3\n    score_threshold = 0.15\n\n    expected = np.array([[0, 0, 1], [0, 1, 0]])\n\n    verify_all_class_non_max_suppression(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, expected\n    )\n\n    # zero box detection case\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 1.0, 1.0],\n            ]\n        ]\n    ).astype(np.float32)\n    scores = np.array([[[0.2]]]).astype(np.float32)\n    score_threshold = 0.4\n\n    expected = np.zeros((0, 3))\n\n    verify_all_class_non_max_suppression(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, expected\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_gather_nd():\n    def verify_gather_nd(data_shape, indices_shape, data_shape_np, indices_shape_np, batch_dims=0):\n        x = relay.var(\"x\", relay.TensorType(data_shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(indices_shape, \"int32\"))\n        z = relay.gather_nd(x, y, batch_dims=batch_dims, index_rank=indices_shape[0])\n\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x, y], z)\n\n        data_np = np.random.uniform(size=data_shape_np).astype(\"float32\")\n        indices_np = np.random.randint(low=0, high=2, size=indices_shape_np, dtype=\"int32\")\n\n        ref_res = ref_funcs.gather_nd(data_np, indices_np, batch_dims)\n        check_result([data_np, indices_np], mod, [ref_res])\n\n    verify_gather_nd((2, 2), (2, relay.Any()), (2, 2), (2, 3))\n    verify_gather_nd((relay.Any(), 2), (2, relay.Any()), (2, 2), (2, 3))\n    verify_gather_nd((relay.Any(), 2), (1, relay.Any()), (10, 2), (1, 10), 1)\n    verify_gather_nd(\n        (relay.Any(), 2, 2, 3, 4), (3, relay.Any(), relay.Any()), (3, 2, 2, 3, 4), (3, 3, 2), 2\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_scatter_nd():\n    def verify_scatter_nd(data_np, indices_np, updates_np, ref_res):\n        indices_shape = (2, relay.Any())\n        updates_shape = (relay.Any(),)\n        data = relay.var(\"data\", shape=data_np.shape, dtype=str(data_np.dtype))\n        indices = relay.var(\"indices\", relay.TensorType(indices_shape, str(indices_np.dtype)))\n        updates = relay.var(\"updates\", relay.TensorType(updates_shape, str(updates_np.dtype)))\n\n        out = relay.op.scatter_nd(data, indices, updates, \"add\")\n\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([data, indices, updates], out)\n\n        check_result([data_np, indices_np, updates_np], mod, [ref_res])\n\n    data = np.zeros((2, 2)).astype(\"int64\")\n    indices = np.array([[1, 1, 0], [0, 1, 0]])\n    updates = np.array([2, 3, 0])\n    out = np.array([[0, 0], [2, 3]])\n    verify_scatter_nd(data, indices, updates, out)\n\n\n@tvm.testing.uses_gpu\ndef test_gather():\n    def verify_gather(data_shape, indices_shape, data_shape_np, indices_shape_np, axis):\n        x = relay.var(\"x\", relay.TensorType(data_shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(indices_shape, \"int32\"))\n        z = relay.gather(x, axis, y)\n\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x, y], z)\n\n        data_np = np.random.uniform(size=data_shape_np).astype(\"float32\")\n        indices_np = np.random.randint(low=0, high=2, size=indices_shape_np, dtype=\"int32\")\n\n        ref_res = tvm.topi.testing.gather_python(data_np, axis, indices_np)\n        check_result([data_np, indices_np], mod, [ref_res])\n\n    verify_gather((relay.Any(),), (relay.Any(),), (10,), (10,), 0)\n    verify_gather((2, 2), (2, relay.Any()), (2, 2), (2, 3), 1)\n    verify_gather((relay.Any(), 2), (2, relay.Any()), (2, 2), (2, 3), 1)\n    verify_gather((relay.Any(), relay.Any()), (relay.Any(), relay.Any()), (2, 3), (1, 3), 0)\n\n\n@tvm.testing.uses_gpu\ndef test_searchsorted():\n    def verify_searchsorted(\n        sorted_sequence_shape, values_shape, sorted_sequence_shape_np, values_shape_np\n    ):\n        x = relay.var(\"x\", relay.TensorType(sorted_sequence_shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(values_shape, \"float32\"))\n        z = relay.searchsorted(x, y)\n\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x, y], z)\n\n        x_np = np.sort(np.random.uniform(size=sorted_sequence_shape_np).astype(\"float32\"), axis=-1)\n        y_np = np.random.uniform(size=values_shape_np).astype(\"float32\")\n\n        ref_res = searchsorted_ref(x_np, y_np, False, \"int32\")\n        check_result([x_np, y_np], mod, [ref_res])\n\n    for shape_np, values_shape_np in zip([(8, 9, 10), (10,), (11,)], [(8, 9, 20), (5,), (8, 9, 7)]):\n        sorted_sequence_shape = (relay.Any(),) * len(shape_np)\n        values_shape = (relay.Any(),) * len(values_shape_np)\n\n        verify_searchsorted(\n            sorted_sequence_shape,\n            values_shape,\n            shape_np,\n            values_shape_np,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_auto_scheduler_layout_rewrite_networks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test layout rewrite support for whole neural networks\"\"\"\nimport sys\nimport tempfile\nimport pytest\n\nimport numpy as np\n\nimport tvm\nfrom tvm import relay, auto_scheduler\nfrom tvm.contrib import graph_executor\nimport tvm.testing\n\n\ndef get_np_array(var, dtype):\n    return np.random.randn(*[int(x) for x in var.type_annotation.shape]).astype(dtype)\n\n\ndef get_relay_conv2d(\n    outc=32,\n    inc=32,\n    height=14,\n    width=14,\n    kh=3,\n    kw=3,\n    batch=1,\n    pad=0,\n    stride=1,\n    dilation=1,\n    layout=\"NHWC\",\n):\n    dtype = \"float32\"\n    if layout == \"NHWC\":\n        kernel_layout = \"HWIO\"\n        d = relay.var(\"data\", shape=(batch, height, width, inc), dtype=dtype)\n        w = relay.var(\"weight\", shape=(kh, kw, inc, outc), dtype=dtype)\n    elif layout == \"NCHW\":\n        kernel_layout = \"OIHW\"\n        d = relay.var(\"data\", shape=(batch, inc, height, width), dtype=dtype)\n        w = relay.var(\"weight\", shape=(outc, inc, kh, kw), dtype=dtype)\n\n    y = relay.nn.conv2d(\n        d,\n        w,\n        padding=pad,\n        kernel_size=(kh, kw),\n        strides=(stride, stride),\n        dilation=(dilation, dilation),\n        channels=outc,\n        groups=1,\n        data_layout=layout,\n        kernel_layout=kernel_layout,\n    )\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d, w], y)\n    data, weight = get_np_array(d, dtype), get_np_array(w, dtype)\n    return mod, data, weight\n\n\ndef get_relay_conv3d(\n    outc=8,\n    inc=8,\n    depth=8,\n    height=7,\n    width=7,\n    kd=1,\n    kh=1,\n    kw=1,\n    batch=1,\n    pad=0,\n    stride=1,\n    dilation=1,\n    layout=\"NDHWC\",\n):\n    dtype = \"float32\"\n    if layout == \"NDHWC\":\n        kernel_layout = \"DHWIO\"\n        d = relay.var(\"data\", shape=(batch, depth, height, width, inc), dtype=dtype)\n        w = relay.var(\"weight\", shape=(kd, kh, kw, inc, outc), dtype=dtype)\n    elif layout == \"NCDHW\":\n        kernel_layout = \"OIDHW\"\n        d = relay.var(\"data\", shape=(batch, inc, depth, height, width), dtype=dtype)\n        w = relay.var(\"weight\", shape=(outc, inc, kd, kh, kw), dtype=dtype)\n\n    y = relay.nn.conv3d(\n        d,\n        w,\n        padding=pad,\n        kernel_size=(kd, kh, kw),\n        strides=(stride, stride, stride),\n        dilation=(dilation, dilation, dilation),\n        channels=outc,\n        groups=1,\n        data_layout=layout,\n        kernel_layout=kernel_layout,\n    )\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d, w], y)\n    data, weight = get_np_array(d, dtype), get_np_array(w, dtype)\n    return mod, data, weight\n\n\ndef get_relay_dense(m=128, n=128, k=128):\n    dtype = \"float32\"\n    d = relay.var(\"data\", shape=(m, k), dtype=dtype)\n    w = relay.var(\"weight\", shape=(n, k), dtype=dtype)\n    y = relay.nn.dense(d, w)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d, w], y)\n    data, weight = get_np_array(d, dtype), get_np_array(w, dtype)\n    return mod, data, weight\n\n\ndef get_relay_batchmm(batch=4, m=128, n=128, k=128):\n    dtype = \"float32\"\n    d = relay.var(\"data\", shape=(batch, m, k), dtype=dtype)\n    w = relay.var(\"weight\", shape=(batch, n, k), dtype=dtype)\n    y = relay.nn.batch_matmul(d, w)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([d, w], y)\n    data, weight = get_np_array(d, dtype), get_np_array(w, dtype)\n    return mod, data, weight\n\n\ndef tune_and_check(mod, data, weight, target, dev):\n    # Extract tasks from a relay program\n    tasks, task_weights = auto_scheduler.extract_tasks(\n        mod, target=target, params={\"weight\": weight}\n    )\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        # Tune tasks\n        tuner = auto_scheduler.TaskScheduler(tasks, task_weights, callbacks=[])\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=1,\n            num_measures_per_round=1,\n            builder=auto_scheduler.LocalBuilder(timeout=60),\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        tuner.tune(tune_option, search_policy=\"sketch.random\")\n\n        # Compile\n        with auto_scheduler.ApplyHistoryBest(log_file):\n            with tvm.transform.PassContext(\n                opt_level=3,\n                config={\"relay.backend.use_auto_scheduler\": True},\n            ):\n                lib = relay.build(mod, target=target, params={\"weight\": weight})\n\n        # Compile without auto-scheduler for correctness check\n        with tvm.transform.PassContext(opt_level=0):\n            lib2 = relay.build(mod, target=target, params={\"weight\": weight})\n\n        def get_output(data, lib):\n            module = graph_executor.GraphModule(lib[\"default\"](dev))\n            module.set_input(\"data\", data)\n            module.run()\n\n            return module.get_output(0).numpy()\n\n        # Check correctness\n        actual_output = get_output(data, lib)\n        expected_output = get_output(data, lib2)\n\n        tvm.testing.assert_allclose(actual_output, expected_output, rtol=1e-4, atol=2e-4)\n\n\n# layout rewriting only works on CPU targets\n@tvm.testing.parametrize_targets(\"llvm\", \"llvm -device=arm_cpu\")\ndef test_conv2d(target, dev):\n    mod, data, weight = get_relay_conv2d(kh=1, kw=1)\n    tune_and_check(mod, data, weight, target, dev)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"llvm -device=arm_cpu\")\ndef test_conv2d_winograd(target, dev):\n    mod, data, weight = get_relay_conv2d(outc=128, kh=3, kw=3)\n    tune_and_check(mod, data, weight, target, dev)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"llvm -device=arm_cpu\")\ndef test_conv3d(target, dev):\n    mod, data, weight = get_relay_conv3d()\n    tune_and_check(mod, data, weight, target, dev)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"llvm -device=arm_cpu\")\ndef test_dense(target, dev):\n    mod, data, weight = get_relay_dense()\n    tune_and_check(mod, data, weight, target, dev)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"llvm -device=arm_cpu\")\ndef test_batch_matmul(target, dev):\n    mod, data, weight = get_relay_batchmm()\n    tune_and_check(mod, data, weight, target, dev)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_auto_scheduler_task_extraction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test task extraction for auto-scheduler\"\"\"\nimport json\nimport tempfile\n\nimport pytest\nimport tvm.relay.testing\nimport tvm.testing\nfrom tvm import _ffi as _ffi_api\nfrom tvm import auto_scheduler, relay\n\n\ndef get_network(name, batch_size=1, layout=\"NHWC\"):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n\n    # auto-scheduler prefer NHWC layout\n    if layout == \"NHWC\":\n        image_shape = (224, 224, 3)\n    elif layout == \"NCHW\":\n        image_shape = (3, 224, 224)\n    elif layout == \"NCDHW\":\n        image_shape = (3, 16, 224, 224)\n    elif layout == \"NDHWC\":\n        image_shape = (3, 224, 224, 16)\n    else:\n        raise ValueError(\"Invalid layout: \" + layout)\n\n    if name == \"resnet-18\":\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=18, batch_size=batch_size, layout=layout, image_shape=image_shape\n        )\n    elif name == \"resnet-50\":\n        mod, params = relay.testing.resnet.get_workload(\n            num_layers=50, batch_size=batch_size, layout=layout, image_shape=image_shape\n        )\n    elif name == \"winograd-test\":\n        input_shape = [1, 23, 40, 32]\n\n        data = relay.var(\"data\", shape=input_shape, dtype=\"float32\")\n        net = relay.testing.layers.conv2d(\n            data=data,\n            channels=128,\n            kernel_size=3,\n            strides=1,\n            padding=1,\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            name=\"\",\n        )\n        bias = relay.var(\"conv1_bias\")\n        net = relay.nn.bias_add(net, bias, 3)\n        net = relay.nn.relu(net)\n        mod, params = relay.testing.create_workload(net)\n    elif name == \"resnet3d-18\":\n        mod, params = relay.testing.resnet_3d.get_workload(\n            num_layers=18, batch_size=batch_size, layout=layout, image_shape=image_shape\n        )\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(\n            batch_size=batch_size, layout=layout, image_shape=image_shape\n        )\n    elif name == \"resnet3d-18\":\n        mod, params = relay.testing.resnet_3d.get_workload(\n            num_layers=18, batch_size=batch_size, layout=layout, image_shape=image_shape\n        )\n    elif name == \"dcgan\":\n        mod, params = relay.testing.dcgan.get_workload(batch_size=batch_size, layout=layout)\n    elif name == \"mlp\":\n        data = relay.var(\"data\", shape=(batch_size, 32))\n        fc1 = relay.nn.dense(data, relay.var(\"fc1_weight\"), units=32)\n        fc1 = relay.nn.bias_add(fc1, relay.var(\"fc1_bias\"), axis=-1)\n        act1 = relay.nn.relu(fc1)\n        fc2 = relay.nn.dense(act1, relay.var(\"fc2_weight\"), units=32)\n        fc2 = relay.nn.bias_add(fc2, relay.var(\"fc2_bias\"), axis=-1)\n        act2 = relay.nn.relu(fc2)\n        mlp = act2\n        args = relay.analysis.free_vars(act2)\n        mlp = relay.Function(args, mlp)\n        mod, params = relay.testing.init.create_workload(mlp)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params\n\n\n@tvm.testing.requires_cuda\n@pytest.mark.parametrize(\n    \"params\",\n    [\n        (\"mlp\", \"NHWC\", 1, 2),\n        (\"resnet-18\", \"NHWC\", 24, 25),\n        (\"resnet-18\", \"NCHW\", 24, 25),\n        (\"mobilenet\", \"NHWC\", 22, 30),\n        (\"mobilenet\", \"NCHW\", 22, 30),\n        (\"resnet3d-18\", \"NCDHW\", 23, 24),\n        (\"resnet3d-18\", \"NDHWC\", 23, 24),\n    ],\n)\ndef test_task_extraction_cuda(params):\n    target = tvm.target.Target(\"cuda\")\n    network, layout, expected_task, expected_weights = params\n\n    mod, params = get_network(network, layout=layout)\n    tasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n    for task, weight in zip(tasks, task_weights):\n        print(task.desc, task.workload_key, weight)\n\n    assert len(tasks) == expected_task\n    assert sum(task_weights) == expected_weights\n\n\n@pytest.mark.parametrize(\n    \"params\",\n    [\n        # Relay FuseOps puts two conv2ds to separate functions and results in two tasks.\n        (\"basic_func\", 2, False),\n        # Relay FuseOps will not break the primitive function and result in one task.\n        (\"fused_func\", 1, False),\n        # The Relay function without complex ops will not form a task by default.\n        (\"simple_func\", 0, False),\n        # Every Relay function becomes a task regardless what ops in its body.\n        (\"simple_func\", 1, True),\n        # The Relay function without any reduce op is considered as a simple task.\n        (\"shape_of_func\", 0, False),\n        (\"shape_of_func\", 1, True),\n        # The Relay function with dynamic shape inputs/outputs will not be extracted.\n        (\"dyn_shape_func\", 0, False),\n        # The Conv2D in the Relay function with control flow could still be a task.\n        # Also, two identical Conv2D should only be one task with weight=2.\n        (\"control_flow_func\", 1, False),\n        # The first function with unsupported op (NMS) will not be extracted.\n        (\"func_w_unsupported_op\", 1, True),\n    ],\n)\ndef test_task_extraction_cpu(params):\n    ishape = (1, 3, 224, 224)\n    w1shape = (32, 3, 3, 3)\n    w2shape = (32, 32, 3, 3)\n    dtype = \"float32\"\n    target = tvm.target.Target(\"llvm\")\n\n    def get_func():\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        weight2 = relay.var(\"weight2\", shape=(w2shape), dtype=dtype)\n\n        conv2d = relay.nn.conv2d(data, weight1, kernel_size=(3, 3), padding=(1, 1))\n        relu = relay.nn.relu(conv2d)\n        conv2d = relay.nn.conv2d(relu, weight2, kernel_size=(3, 3), padding=(1, 1))\n        out = relay.nn.relu(conv2d)\n        return relay.Function([data, weight1, weight2], out)\n\n    def get_fused_func():\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        weight2 = relay.var(\"weight2\", shape=(w2shape), dtype=dtype)\n\n        fused_func = get_func()\n\n        # Set to primitive to keep fuse_ops untouch.\n        fused_func = fused_func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        call = relay.Call(fused_func, [data, weight1, weight2])\n        return relay.Function([data, weight1, weight2], call)\n\n    def get_simple_func():\n        data = relay.var(\"data\", relay.TensorType((1, 2, 3), \"float32\"))\n        out = relay.image.affine_grid(data, (150, 150))\n        return relay.Function([data], out)\n\n    def get_shape_of_func():\n        data = relay.var(\"data\", shape=(relay.Any(), 28, 28), dtype=\"float32\")\n        out = relay.shape_of(data)\n        return relay.Function([data], out)\n\n    def get_func_with_dynamic_shape():\n        data = relay.var(\"data\", shape=(relay.Any(), 32), dtype=\"float32\")\n        out = relay.max(data)\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def get_func_with_control_flow():\n        data = relay.var(\"data\", shape=(1, 3, 224, 224))\n        weight = relay.var(\"weight\", shape=(3, 3, 3, 3))\n        eq1 = relay.var(\"e1\", shape=[], dtype=\"float32\")\n        eq2 = relay.var(\"e2\", shape=[], dtype=\"float32\")\n        eq = relay.equal(eq1, eq2)\n\n        true_branch = relay.zeros(shape=(1, 3, 224, 224), dtype=\"float32\")\n        false_branch = relay.nn.conv2d(data, weight, kernel_size=(3, 3), channels=3, padding=(1, 1))\n        false_branch = relay.nn.conv2d(\n            false_branch, weight, kernel_size=(3, 3), channels=3, padding=(1, 1)\n        )\n        ife = relay.If(eq, true_branch, false_branch)\n        out = relay.erf(ife)\n        return relay.Function([data, weight, eq1, eq2], out)\n\n    def get_func_with_unsupported_op():\n        def get_postproc_func():\n            data = relay.var(\"data\", shape=((1, 3, 6)), dtype=dtype)\n            out = relay.nn.relu(data)\n            func = relay.Function([data], out)\n            func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n            return func\n\n        cls_prob = relay.var(\"cls_prob\", relay.ty.TensorType((1, 3, 3), \"float32\"))\n        loc_pred = relay.var(\"loc_pred\", relay.ty.TensorType((1, 3 * 4), \"float32\"))\n        anchors = relay.var(\"anchors\", relay.ty.TensorType((1, 3, 4), \"float32\"))\n\n        mtl = relay.vision.multibox_transform_loc(\n            cls_prob=cls_prob, loc_pred=loc_pred, anchor=anchors\n        )\n        nms = relay.vision.non_max_suppression(mtl[0], mtl[1], mtl[0], return_indices=False)\n        out = relay.Call(get_postproc_func(), [nms])\n        return relay.Function([cls_prob, loc_pred, anchors], out)\n\n    func_map = {\n        \"basic_func\": get_func,\n        \"fused_func\": get_fused_func,\n        \"simple_func\": get_simple_func,\n        \"shape_of_func\": get_shape_of_func,\n        \"dyn_shape_func\": get_func_with_dynamic_shape,\n        \"control_flow_func\": get_func_with_control_flow,\n        \"func_w_unsupported_op\": get_func_with_unsupported_op,\n    }\n\n    def verify_task_extraction(func_name, expected_task, include_simple_tasks=False):\n        func = func_map[func_name]()\n        mod = tvm.IRModule.from_expr(func)\n        tasks, task_weights = auto_scheduler.extract_tasks(\n            mod[\"main\"], None, target, include_simple_tasks=include_simple_tasks\n        )\n\n        assert len(tasks) == expected_task\n        assert len(task_weights) == expected_task\n\n    verify_task_extraction(*params)\n\n\ndef test_dump_workload_to_dag_extract_tasks():\n    mod, _ = get_network(\"mobilenet\", layout=\"NHWC\")\n    with tempfile.NamedTemporaryFile() as f:\n        tasks, _ = auto_scheduler.extract_tasks(\n            mod[\"main\"], None, \"llvm\", include_simple_tasks=True, dump_workload_to_dag_log=f.name\n        )\n        expected = {task.workload_key: str(task.compute_dag) for task in tasks}\n        actual = json.load(f)\n        assert expected == actual\n\n\ndef test_custom_hash_func_extract_tasks():\n    @_ffi_api.register_func(\"auto_scheduler.compute_dag.hash_func\")\n    def counting_unique_hash(str_dag):\n        ret = counting_unique_hash.i\n        counting_unique_hash.i += 1\n        return ret\n\n    counting_unique_hash.i = 0\n\n    mod, _ = get_network(\"mobilenet\", layout=\"NHWC\")\n    tasks, _ = auto_scheduler.extract_tasks(mod[\"main\"], None, \"llvm\", include_simple_tasks=True)\n\n    hash_values = []\n    for task in tasks:\n        # task.workload_key should look like\n        # [43, [3, 3, 1024, 1], [1024], [3, 3, 1024, 1]] where the first int is the result of the hash\n        # Extract the hash and keep track of every hash\n        hash_value = int(task.workload_key[1:].split(\",\")[0])\n        hash_values.append(hash_value)\n\n    # All values are unique, and we know the min and max\n    # This is a sufficient condition to know that hashes in hash_values are an increasing list\n    # of hashes up to counting_unique_hash.i - 1\n    assert len(hash_values) == len(set(hash_values))\n    assert min(hash_values) == 0\n    assert max(hash_values) == counting_unique_hash.i - 1\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_auto_scheduler_tuning.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test end-to-end network tuning with auto-scheduler\"\"\"\nimport tempfile\n\nimport numpy as np\n\nfrom tvm import auto_scheduler, relay\nfrom tvm.contrib import graph_executor\nimport tvm.testing\n\nfrom test_auto_scheduler_task_extraction import get_network\n\n\ndef tune_network(network, target):\n    # Extract tasks\n    mod, params = get_network(network)\n    target = tvm.target.Target(target)\n    tasks, task_weights = auto_scheduler.extract_tasks(mod[\"main\"], params, target)\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        # Tuning\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext(timeout=60, device=0)\n        tuner = auto_scheduler.TaskScheduler(tasks, task_weights, callbacks=[])\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=100,\n            num_measures_per_round=2,\n            early_stopping=1,\n            runner=measure_ctx.runner,\n            builder=auto_scheduler.LocalBuilder(timeout=60),\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        tuner.tune(tune_option, search_policy=\"sketch.random\")\n        del measure_ctx\n\n        # Compile with the history best\n        with auto_scheduler.ApplyHistoryBest(log_file):\n            with tvm.transform.PassContext(\n                opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}\n            ):\n                lib = relay.build(mod, target=target, params=params)\n\n        # Also test that multiple log files can be loaded.\n        with auto_scheduler.ApplyHistoryBest([log_file, log_file]) as best:\n            assert isinstance(\n                best, auto_scheduler.dispatcher.ApplyHistoryBest\n            ), \"Unable to load multiple log files jointly.\"\n\n        # Confirm iterables can be directly loaded.\n        loaded_recs = auto_scheduler.dispatcher.load_records(log_file)\n        with auto_scheduler.ApplyHistoryBest(iter(loaded_recs)) as best:\n            assert isinstance(\n                best, auto_scheduler.dispatcher.ApplyHistoryBest\n            ), \"Unable to ingest logs from an interator.\"\n\n        # Sample a schedule when missing\n        with auto_scheduler.ApplyHistoryBestOrSample(None, num_measure=2):\n            with tvm.transform.PassContext(\n                opt_level=3, config={\"relay.backend.use_auto_scheduler\": True}\n            ):\n                lib2 = relay.build(mod, target=target, params=params)\n\n        # Compile without auto-scheduler and any other optimization for correctness check\n        with tvm.transform.PassContext(opt_level=0):\n            ref_lib = relay.build(mod, target=target, params=params)\n\n        # Check the correctness\n        def get_output(data, lib):\n            dev = tvm.cuda()\n            module = graph_executor.GraphModule(lib[\"default\"](dev))\n            module.set_input(\"data\", data)\n            module.run()\n            return module.get_output(0).numpy()\n\n        np.random.seed(0)\n        if network == \"mlp\":\n            data = np.random.uniform(size=(1, 32))\n        elif network == \"winograd-test\":\n            data = np.random.uniform(size=(1, 23, 40, 32))\n        else:\n            raise ValueError(\"Unknown network: \" + network)\n\n        actual_output1 = get_output(data, lib)\n        actual_output2 = get_output(data, lib2)\n        expected_output = get_output(data, ref_lib)\n\n        tvm.testing.assert_allclose(actual_output1, expected_output, rtol=1e-4, atol=1e-4)\n        tvm.testing.assert_allclose(actual_output2, expected_output, rtol=1e-4, atol=1e-4)\n\n\n@tvm.testing.requires_cuda\ndef test_tuning_cuda():\n    tune_network(\"mlp\", \"cuda\")\n    tune_network(\"winograd-test\", \"cuda\")\n\n\nif __name__ == \"__main__\":\n    test_tuning_cuda()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_autotvm_task_extraction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test task extraction for autotvm\"\"\"\nimport tvm.relay.testing\nfrom tvm import relay\nfrom tvm import autotvm\n\n\ndef get_network(name, batch_size):\n    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n    input_shape = (batch_size, 3, 224, 224)\n\n    if name == \"resnet-18\":\n        mod, params = relay.testing.resnet.get_workload(num_layers=18, batch_size=batch_size)\n    elif name == \"resnet3d-18\":\n        mod, params = relay.testing.resnet_3d.get_workload(num_layers=18, batch_size=batch_size)\n    elif name == \"mobilenet\":\n        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size)\n    elif name == \"dcgan\":\n        mod, params = relay.testing.dcgan.get_workload(batch_size=batch_size)\n        input_shape = (batch_size, 100)\n    else:\n        raise ValueError(\"Unsupported network: \" + name)\n\n    return mod, params, input_shape\n\n\ndef test_task_extraction():\n    target = \"llvm\"\n    mod_list = []\n    params_list = []\n    conv2d = relay.op.get(\"nn.conv2d\")\n    conv3d = relay.op.get(\"nn.conv3d\")\n    conv2d_transpose = relay.op.get(\"nn.conv2d_transpose\")\n    dense = relay.op.get(\"nn.dense\")\n\n    mod, params, _ = get_network(\"resnet-18\", batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(conv2d,)\n    )\n    assert len(tasks) == 12\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params, ops=(conv2d,))\n    assert len(tasks) == 12\n\n    mod, params, _ = get_network(\"resnet-18\", batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(dense,)\n    )\n    assert len(tasks) == 2\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params, ops=(dense,))\n    assert len(tasks) == 2\n\n    mod, params, _ = get_network(\"resnet-18\", batch_size=1)\n    mod_list.append(mod)\n    params_list.append(params)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(conv2d, dense)\n    )\n    assert len(tasks) == 14\n    tasks = autotvm.task.extract_from_program(\n        mod, target=target, params=params, ops=(conv2d, dense)\n    )\n    assert len(tasks) == 14\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params)\n    assert len(tasks) == 14\n\n    mod, params, _ = get_network(\"resnet3d-18\", batch_size=1)\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params, ops=(conv3d,))\n    assert len(tasks) == 12\n\n    mod, params, _ = get_network(\"mobilenet\", batch_size=1)\n    mod_list.append(mod)\n    params_list.append(params)\n    tasks = autotvm.task.extract_from_program(\n        mod, target=target, params=params, ops=(conv2d, dense)\n    )\n    assert len(tasks) == 21\n\n    mod, params, _ = get_network(\"dcgan\", batch_size=1)\n    tasks = autotvm.task.extract_from_program(\n        mod, target=target, params=params, ops=(conv2d_transpose,)\n    )\n    assert len(tasks) == 4\n\n    tasks = autotvm.task.extract_from_multiple_program(\n        mod_list, params_list, target=target, ops=(conv2d,)\n    )\n    assert len(tasks) == 31\n\n\ndef test_task_extraction_for_dense_int8_cuda():\n    target = \"cuda\"\n    dense = relay.op.get(\"nn.dense\")\n\n    def get_net(batch, in_dim, out_dim, dtype, out_dtype):\n        data = tvm.relay.var(\"data\", shape=[batch, in_dim], dtype=dtype)\n        weight = tvm.relay.var(\"weight\", shape=[out_dim, in_dim], dtype=dtype)\n        out = relay.nn.dense(data, weight, out_dtype=out_dtype)\n        mod, params = relay.testing.create_workload(out)\n        return mod, params\n\n    mod, params = get_net(1, 16, 32, \"float32\", \"float32\")\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params, ops=(dense,))\n    assert len(tasks) == 1 and tasks[0].name == \"dense_small_batch.gpu\"\n\n    mod, params = get_net(1, 16, 32, \"int8\", \"int32\")\n    tasks = autotvm.task.extract_from_program(mod, target=target, params=params, ops=(dense,))\n    assert len(tasks) == 1 and tasks[0].name == \"dense_int8.cuda\"\n\n\nif __name__ == \"__main__\":\n    test_task_extraction()\n    test_task_extraction_for_dense_int8_cuda()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_backend_graph_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nfrom unittest.mock import patch\n\nimport tvm\nimport json\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.op import add\nimport tvm.testing\nfrom tvm.relay.testing import mlp\nfrom tvm import rpc\nfrom tvm.contrib import utils\n\n# @tq, @jr should we put this in testing ns?\ndef check_rts(expr, args, expected_result, mod=None):\n    \"\"\"\n    Check that evaluating `expr` applied to the arguments produces\n    `result` on both the evaluator and TVM runtime.\n\n    Parameters\n    ----------\n    expr:\n        The expression to evaluate\n\n    args: list of Expr\n        The arguments to supply the expr.\n\n    expected_result:\n        The expected result of running the expression.\n    \"\"\"\n    eval_result = relay.create_executor(\"debug\", mod=mod).evaluate(expr)(*args)\n    rts_result = relay.create_executor(\"graph\", mod=mod).evaluate(expr)(*args)\n    tvm.testing.assert_allclose(eval_result.numpy(), rts_result.numpy())\n    tvm.testing.assert_allclose(eval_result.numpy(), expected_result)\n\n\ndef test_add_op_scalar():\n    \"\"\"\n    test_add_op_scalar:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    x = relay.var(\"x\", shape=())  # Default to float32\n    y = relay.var(\"y\", shape=())  # Default to float32\n    func = relay.Function([x, y], add(x, y))\n    x_y_data = [\n        (np.array(10.0, dtype=\"float32\"), np.array(1.0, dtype=\"float32\")),\n        (np.float32(10.0), np.float32(1.0)),\n        (10.0, 1.0),\n    ]\n    for (x_data, y_data) in x_y_data:\n        check_rts(func, [x_data, y_data], x_data + y_data)\n\n\ndef test_add_op_scalar_int():\n    \"\"\"\n    test_add_op_scalar_int:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    x = relay.var(\"x\", shape=(), dtype=\"int32\")\n    y = relay.var(\"y\", shape=(), dtype=\"int32\")\n    func = relay.Function([x, y], add(x, y))\n    x_y_data = [\n        (np.array(10.0, dtype=\"int32\"), np.array(1.0, dtype=\"int32\")),\n        (np.int32(10), np.int32(1)),\n        (10, 1),\n    ]\n    for (x_data, y_data) in x_y_data:\n        check_rts(func, [x_data, y_data], x_data + y_data)\n\n\ndef test_add_op_tensor():\n    \"\"\"\n    Program:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(10, 5))\n    func = relay.Function([x, y], add(x, y))\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(10, 5).astype(\"float32\")\n    check_rts(func, [x_data, y_data], x_data + y_data)\n\n\ndef test_add_op_broadcast():\n    \"\"\"\n    Program:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(1, 5))\n    func = relay.Function([x, y], add(x, y))\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(1, 5).astype(\"float32\")\n    check_rts(func, [x_data, y_data], x_data + y_data)\n\n\ndef test_with_params():\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(1, 5))\n    z = relay.add(x, y)\n    z = relay.exp(z)\n    func = relay.Function([x, y], z)\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(1, 5).astype(\"float32\")\n    params = {\"y\": y_data}\n    graph, lib, params = relay.build(tvm.IRModule.from_expr(func), \"llvm\", params=params)\n    mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n    mod.set_input(**params)\n    mod.set_input(x=x_data)\n    mod.run()\n    res = mod.get_output(0).numpy()\n    ref_res = np.exp(y_data + x_data)\n    tvm.testing.assert_allclose(res, ref_res, atol=1e-5, rtol=1e-5)\n\n\ndef test_plan_memory():\n    # it is sufficient to cycle through two memories.\n\n    x = relay.var(\"x\", shape=(10,))\n    y = relay.var(\"x\", shape=(1,))\n    y2 = relay.exp(y)\n    z = relay.add(x, y2)\n    z = relay.exp(z)\n    z = relay.exp(z)\n    z = relay.exp(z)\n    z = relay.exp(z)\n    z = relay.exp(z)\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.FuseOps(0)(mod)\n    func = mod[\"main\"]\n    mod = relay.transform.InferType()(mod)\n    memory_plan = relay.backend._backend.GraphPlanMemory(func)\n    storage_ids = set()\n    device_types = set()\n    storage_sizes = {}\n\n    for k, v in memory_plan.expr_to_storage_info.items():\n        for x in v.storage_ids:\n            storage_ids.add(x)\n            storage_sizes[x] = v.storage_sizes\n        for x in v.device_types:\n            device_types.add(x)\n\n    # Current rule requires vars have unique storage id\n    # because we don't do inplace, we will need another\n    # two alternating temporary space.\n    assert len(storage_ids) == 4, f\"found storage_ids: {storage_ids}\"\n    assert len(device_types) == 1\n    assert len(storage_sizes) == 4\n\n    # Check the specific size of each sid\n    assert (\n        storage_sizes[0][0] == 40\n        and storage_sizes[1][0] == 4\n        and storage_sizes[2][0] == 4\n        and storage_sizes[3][0] == 40\n    )\n\n\ndef test_plan_2d_memory():\n    \"\"\"Verification if GraphPlanMemory manages 2d memory reffered as\n    global.texture* memory scopes in json file.\"\"\"\n    global_virtual_device = tvm.target.VirtualDevice(memory_scope=\"global\")\n    texture_virtual_device = tvm.target.VirtualDevice(memory_scope=\"global.texture\")\n    metatable = {\n        \"VirtualDevice\": [\n            global_virtual_device,\n            texture_virtual_device,\n        ]\n    }\n\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data1: Tensor[(1, 32, 40, 40), float32],\n                  %data2: Tensor[(1, 32, 40, 40), float32]) {\n          %0 = fn (%a, Primitive=1) {\n            layout_transform(%a, src_layout=\"NCHW\", dst_layout=\"NCHW4c\")\n          };\n          %1 = %0(%data1);\n          %3 = %0(%data2);\n          %5 = fn (%a {virtual_device=meta[VirtualDevice][0]},  // global\n                   %b {virtual_device=meta[VirtualDevice][0]},  // global\n                   virtual_device=meta[VirtualDevice][1],       // texture\n                   Primitive=1) {\n            add(%a, %b)\n          };\n          %6 = %5(%1, %3);\n          %7 = fn (%a {virtual_device=meta[VirtualDevice][1]},  // texture\n                   %b {virtual_device=meta[VirtualDevice][0]},  // global\n                   virtual_device=meta[VirtualDevice][1],       // texture\n                   Primitive=1) {\n            add(%a, %b)\n          };\n          %8 = %7(%6, %3);\n          %9 = fn (%a {virtual_device=meta[VirtualDevice][1]},  // texture\n                   %b {virtual_device=meta[VirtualDevice][1]},  // texture\n                   virtual_device=meta[VirtualDevice][1],       // texture\n                   Primitive=1) {\n            add(%a, %b)\n          };\n          %10 = %9(%8, %6);\n          %11 = fn (%a,\n                    virtual_device=meta[VirtualDevice][0],      // global\n                    Primitive=1) {\n            layout_transform(%a, src_layout=\"NCHW4c\", dst_layout=\"NCHW\")\n          };\n          %11(%10)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n    GPU_DEVICE = tvm.device(\"cuda\")\n    HOST_TARGET = tvm.target.Target(\"llvm\")\n    GPU_TARGET = tvm.target.Target(\"cuda\").with_host(HOST_TARGET)\n    GPU = tvm.target.VirtualDevice(GPU_DEVICE, GPU_TARGET)  # device_type=2\n    CTXT = tvm.transform.PassContext(config={\"relay.fallback_device_type\": GPU.device_type_int})\n    config = tvm.target.make_compilation_config(CTXT, GPU_TARGET)\n    mod = relay.transform.InferType()(mod)\n    # PlanDevices should succeed.\n    mod = relay.transform.PlanDevices(config)(mod)\n\n    func = mod[\"main\"]\n    memory_plan = relay.backend._backend.GraphPlanMemory(func)\n    virtual_devices = {}\n\n    # We do not have execution ordered information, the only order that we can stick\n    # in this place - storage_id\n    # for above graph we know that\n    # We have\n    #  - 8 manageable storages for above graph\n    #  - 5 of them are buffers\n    #  - 3 of them are textures (2d storages)\n    #  - 1 of buffer will be reused, since we have storage id maped data, we will have 4th\n    #      storage id reuesed and hidden in virtual_devices map\n    #  - no textures are reused so far\n    for k, v in memory_plan.expr_to_storage_info.items():\n        virtual_devices[v.storage_ids[0]] = v.virtual_devices[0].memory_scope\n\n    # Check the scopes according to abvoce expectaions\n    assert (\n        virtual_devices[0] == \"global\"\n        and virtual_devices[1] == \"global\"\n        and virtual_devices[2] == \"global\"\n        and virtual_devices[3] == \"global\"\n        and virtual_devices[4] == \"global.texture\"\n        and virtual_devices[5] == \"global.texture\"\n        and virtual_devices[6] == \"global.texture\"\n    )\n\n\ndef test_reshape_nop():\n    # test that reshape can be turned into nop\n    x = relay.var(\"x\", shape=(10, 4))\n    xx = relay.abs(x)\n    y = relay.expand_dims(xx, axis=1)\n    t0 = relay.reshape(y, (1, 40))\n    t1 = relay.abs(y)\n\n    z0 = relay.reshape(t0, (2, 20))\n    z1 = relay.sqrt(t1)\n    z2 = relay.reshape(t1, (1, 40))\n\n    func = relay.Function([x], relay.Tuple([z0, z1, z2]))\n    x_data = np.random.rand(10, 4).astype(\"float32\")\n    graph = relay.build(tvm.IRModule.from_expr(func), \"llvm\")\n    graph_json_str = graph.get_graph_json()\n\n    graph_json = json.loads(graph_json_str)\n\n    # reshape must force sharing memory\n    storage_ids = graph_json[\"attrs\"][\"storage_id\"][1]\n    assert tuple(storage_ids) == (0, 1, 1, 2, 3, 2)\n    assert graph_json[\"nodes\"][2][\"attrs\"][\"func_name\"] == \"__nop\"\n    assert graph_json[\"nodes\"][5][\"attrs\"][\"func_name\"] == \"__nop\"\n\n    gmod = graph_executor.GraphModule(graph[\"default\"](tvm.cpu(0)))\n\n    gmod.set_input(x=x_data)\n    gmod.run()\n    z0_np = x_data.reshape(2, 20)\n    z1_np = np.sqrt(\n        np.abs(\n            x_data.reshape(\n                10,\n                1,\n                4,\n            )\n        )\n    )\n    z2_np = np.abs(x_data).reshape(1, 40)\n    tvm.testing.assert_allclose(gmod.get_output(0).numpy(), z0_np)\n    tvm.testing.assert_allclose(gmod.get_output(1).numpy(), z1_np)\n    tvm.testing.assert_allclose(gmod.get_output(2).numpy(), z2_np)\n\n\n@tvm.testing.uses_gpu\ndef test_gru_like():\n    def unit(rnn_dim):\n        X = relay.var(\"X\", shape=(1, rnn_dim))\n        W = relay.var(\"y\", shape=(3 * rnn_dim, rnn_dim))\n        matmul = relay.nn.dense(X, W)\n        splitted = relay.split(matmul, indices_or_sections=3, axis=1)\n        out = relay.sigmoid(splitted[0]) + relay.tanh(splitted[1]) * relay.exp(splitted[2])\n        return relay.Function([X, W], out)\n\n    def sigmoid(x):\n        return 1 / (1 + np.exp(-x))\n\n    def unit_numpy(X, W):\n        prod = np.dot(X, W.transpose())\n        splits = np.split(prod, indices_or_sections=3, axis=1)\n        return sigmoid(splits[0]) + np.tanh(splits[1]) * np.exp(splits[2])\n\n    dtype = \"float32\"\n    rnn_dim = 1000\n    x = np.random.rand(1, rnn_dim).astype(dtype)\n    y = np.random.rand(3 * rnn_dim, rnn_dim).astype(dtype) * 0.01 - 0.005\n    out_shape = (1, rnn_dim)\n    z = unit(rnn_dim)\n\n    for target, dev in tvm.testing.enabled_targets():\n        with tvm.transform.PassContext(opt_level=2):\n            graph, lib, params = relay.build(tvm.IRModule.from_expr(z), target)\n            m = graph_executor.create(graph, lib, dev)\n            m.set_input(\"X\", tvm.nd.array(x.astype(dtype)))\n            m.set_input(\"y\", tvm.nd.array(y.astype(dtype)))\n            m.set_input(**params)\n            m.run()\n            out = m.get_output(0, tvm.nd.empty(out_shape, dtype)).numpy()\n            ref = unit_numpy(x, y)\n            tvm.testing.assert_allclose(out, ref, rtol=1e-5, atol=1e-5)\n\n\ndef test_compile_nested_tuples():\n    x = relay.var(\"x\", shape=(10,))\n    x1 = x + relay.const(1.0)\n    x2 = x1 + relay.const(1.0)\n    x3 = x2 + relay.const(1.0)\n    x4 = x3 + relay.const(1.0)\n    out = relay.Tuple([x1, relay.Tuple([relay.Tuple([x2, x3]), x4])])\n    func = relay.Function([x], out)\n\n    graph, lib, _ = relay.build(tvm.IRModule.from_expr(func), \"llvm\")\n    mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n\n    x_data = np.random.uniform(size=(10,)).astype(np.float32)\n    mod.set_input(x=x_data)\n    mod.run()\n\n    assert mod.get_num_outputs() == 4\n\n    ref = x_data + 1\n    for i in range(mod.get_num_outputs()):\n        out = mod.get_output(i).numpy()\n        tvm.testing.assert_allclose(out, ref, rtol=1e-5, atol=1e-5)\n        ref = ref + 1\n\n\ndef test_compile_return_empty_tuple():\n    x = relay.var(\"x\", shape=[16], dtype=\"float32\")\n    mod = tvm.IRModule.from_expr(relay.Function([x], relay.Tuple([])))\n    graph, lib, _ = relay.build(mod, \"llvm\")\n    mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n    mod.run()\n\n\n@tvm.testing.uses_gpu\ndef test_compile_fused_identity_cast():\n    # a fused function that would optimized to identity\n    x = relay.var(\"x\", shape=[16], dtype=\"float32\")\n    y = relay.cast(x, \"float32\")\n    func1 = relay.Function([x], y).with_attr(\"Primitive\", 1)\n\n    # a fused function with param pass-through\n    x = relay.var(\"x\", shape=[16], dtype=\"float32\")\n    y = relay.add(x, relay.const(3.14, \"float32\"))\n    func2 = relay.Function([x], relay.Tuple([x, y])).with_attr(\"Primitive\", 1)\n\n    x_global = relay.var(\"xx\", shape=[16], dtype=\"float32\")\n    tup = func2(x_global)\n    y_global = func1(relay.TupleGetItem(tup, 0) + relay.TupleGetItem(tup, 1))\n\n    mod = tvm.IRModule.from_expr(relay.Function([x_global], y_global))\n    for target, device in tvm.testing.enabled_targets():\n        with tvm.transform.PassContext(opt_level=2):\n            graph, lib, _ = relay.build(mod, target=target)\n            executor = graph_executor.create(graph, lib, device=device)\n            executor.run()\n\n\ndef test_graph_executor_nested_tuples():\n    x, y, z, w = [relay.var(c, shape=(2, 3), dtype=\"float32\") for c in \"xyzw\"]\n    out = relay.Tuple([x, relay.Tuple([y, relay.Tuple([z, w])])])\n    func = relay.Function([x, y, z, w], out)\n\n    f = relay.create_executor(\n        kind=\"graph\", mod=tvm.IRModule.from_expr(func), device=tvm.cpu(0), target=\"llvm\"\n    ).evaluate()\n\n    data = [np.random.uniform(size=(2, 3)).astype(\"float32\") for _ in \"xyzw\"]\n    out = f(*data)\n    assert len(out) == 2\n    tvm.testing.assert_allclose(out[0].numpy(), data[0])\n    assert len(out[1]) == 2\n    tvm.testing.assert_allclose(out[1][0].numpy(), data[1])\n    assert len(out[1][1]) == 2\n    tvm.testing.assert_allclose(out[1][1][0].numpy(), data[2])\n    tvm.testing.assert_allclose(out[1][1][1].numpy(), data[3])\n\n\ndef test_graph_executor_api():\n    dname_0, dname_1 = \"data_0\", \"data_1\"\n    data_0, data_1 = [relay.var(c, shape=(1, 1), dtype=\"float32\") for c in [dname_0, dname_1]]\n    net = relay.add(data_0, data_1)\n    func = relay.Function((data_0, data_1), net)\n\n    lib = relay.build(tvm.IRModule.from_expr(func), \"llvm\")\n    mod = graph_executor.GraphModule(lib[\"default\"](tvm.cpu(0)))\n\n    assert mod.get_input_index(dname_1) == 1\n    assert mod.get_input_index(dname_0) == 0\n    assert mod.get_input_index(\"Invalid\") == -1\n\n    shape_dict, dtype_dict = mod.get_input_info()\n    assert isinstance(shape_dict, tvm.container.Map)\n    assert isinstance(dtype_dict, tvm.container.Map)\n    for data in [data_0, data_1]:\n        name = data.name_hint\n        ty = data.type_annotation\n        # verify shape\n        assert name in shape_dict\n        assert isinstance(shape_dict[name], tvm.runtime.container.ShapeTuple)\n        assert shape_dict[name] == tvm.runtime.container.ShapeTuple([i.value for i in ty.shape])\n        # verify dtype\n        assert name in dtype_dict\n        assert isinstance(dtype_dict[name], tvm.runtime.container.String)\n        assert dtype_dict[name] == ty.dtype\n\n\n@tvm.testing.requires_llvm\ndef test_benchmark():\n    mod, params = mlp.get_workload(1)\n    lib = relay.build(mod, target=\"llvm\", params=params)\n    exe = graph_executor.create(lib.get_graph_json(), lib.lib, tvm.cpu())\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"))\n    result = exe.benchmark(tvm.cpu(), data=data, func_name=\"run\", repeat=2, number=1)\n    assert result.mean == result.median\n    assert result.mean > 0\n    assert len(result.results) == 2\n\n    with patch.object(\n        tvm.runtime.module.Module,\n        \"time_evaluator\",\n        return_value=lambda: tvm.runtime.module.BenchmarkResult([1, 2, 2, 5]),\n    ) as method:\n        result = exe.benchmark(tvm.cpu(), data=data, func_name=\"run\", repeat=2, number=1)\n        assert result.mean == 2.5\n        assert result.median == 2.0\n        assert result.max == 5\n        assert result.min == 1\n        assert result.std == 1.5\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"llvm\")\ndef test_benchmark_end_to_end(dev, target):\n    mod, params = mlp.get_workload(1)\n    lib = relay.build(mod, target=target, params=params)\n    exe = graph_executor.create(lib.get_graph_json(), lib.lib, dev)\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"))\n    result = exe.benchmark(dev, data=data, func_name=\"run\", repeat=2, number=1, end_to_end=True)\n    assert result.mean > 0\n    assert len(result.results) == 2\n\n\n@tvm.testing.requires_cuda\ndef test_benchmark_end_to_end_rpc():\n    server = rpc.Server(\"127.0.0.1\")\n    remote = rpc.connect(server.host, server.port)\n\n    mod, params = mlp.get_workload(1)\n    lib = relay.build(mod, target=\"cuda\", params=params)\n\n    temp = utils.tempdir()\n    path = temp.relpath(\"library.so\")\n    lib.export_library(path)\n    remote.upload(path)\n    rlib = remote.load_module(\"library.so\")\n\n    dev = remote.device(\"cuda\")\n    exe = graph_executor.create(lib.get_graph_json(), rlib, dev)\n\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"), device=dev)\n    result = exe.benchmark(dev, data=data, func_name=\"run\", repeat=2, number=1, end_to_end=True)\n    assert result.mean > 0\n    assert len(result.results) == 2\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_backend_interpreter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import testing\nfrom tvm import nd\nfrom tvm import relay\nfrom tvm.runtime import container\nfrom tvm.relay.backend.interpreter import RefValue, ConstructorValue\nfrom tvm.relay.scope_builder import ScopeBuilder\n\n\ndef check_eval(expr, args, expected_result, mod=None, rtol=1e-07):\n    # TODO(tqchen) add more types once the schedule register is fixed.\n    for target in [\"llvm\"]:\n        dev = tvm.device(target, 0)\n        if not testing.device_enabled(target):\n            return\n        func = relay.create_executor(mod=mod, device=dev, target=target).evaluate(expr)\n        result = func if args is None else func(*args)\n        # use testing which also set atol\n        testing.assert_allclose(result.numpy(), expected_result, rtol=rtol)\n\n\ndef test_tuple_value():\n    tv = container.tuple_object([relay.const(1), relay.const(2), relay.const(3)])\n    np.testing.assert_allclose(tv[0].data.numpy(), 1)\n    np.testing.assert_allclose(tv[1].data.numpy(), 2)\n    np.testing.assert_allclose(tv[2].data.numpy(), 3)\n\n\ndef test_tuple_getitem():\n    two = relay.add(relay.const(1), relay.const(1))\n    func = relay.Function([], relay.TupleGetItem(relay.Tuple([relay.const(1), relay.const(2)]), 0))\n    check_eval(func, [], 1)\n\n\ndef test_id():\n    x = relay.var(\"x\", \"float32\")\n    ident = relay.Function([x], x)\n    one = np.array(1.0, \"float32\")\n    check_eval(ident, [one], one)\n\n\ndef test_add_const():\n    two = relay.add(relay.const(1), relay.const(1))\n    func = relay.Function([], two)\n    check_eval(func, [], 2)\n\n\ndef test_mul_param():\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    func = relay.Function([x, y], relay.multiply(x, y))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(1, 10).astype(\"float32\")\n    check_eval(func, [x_data, y_data], x_data * y_data)\n\n\ndef test_equal():\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    j = relay.var(\"i\", shape=[], dtype=\"int32\")\n    z = relay.equal(i, j)\n    func = relay.Function([i, j], z, ret_type=relay.TensorType([], \"bool\"))\n    i_data = relay.const(0, \"int32\")\n    j_data = relay.const(0, \"int32\")\n    check_eval(func, [i_data, j_data], True)\n\n\ndef test_subtract():\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sub = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n    func = relay.Function([i], sub, ret_type=relay.TensorType([], \"int32\"))\n    i_data = np.array(1, dtype=\"int32\")\n    check_eval(func, [i_data], 0)\n\n\ndef test_simple_loop():\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n        sb.ret(i)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n        rec_call = relay.Call(sum_up, [one_less])\n        sb.ret(relay.add(rec_call, i))\n    func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n    mod[sum_up] = func\n    i_data = np.array(10, dtype=\"int32\")\n    check_eval(sum_up, [i_data], sum(range(1, 11)), mod=mod)\n\n\ndef test_loop():\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    accum = relay.var(\"accum\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, \"int32\"))):\n        sb.ret(accum)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, \"int32\"))\n        new_accum = relay.add(accum, i)\n        sb.ret(relay.Call(sum_up, [one_less, new_accum]))\n    func = relay.Function([i, accum], sb.get())\n    mod[sum_up] = func\n    i_data = np.array(10, dtype=\"int32\")\n    accum_data = np.array(0, dtype=\"int32\")\n    check_eval(sum_up, [i_data, accum_data], sum(range(1, 11)), mod=mod)\n\n\ndef test_ref():\n    mod = tvm.IRModule()\n    three_with_ref = relay.GlobalVar(\"three_with_ref\")\n    i = relay.Var(\"i\")\n    iv = relay.Var(\"iv\")\n    u = relay.Var(\"u\")\n    uv = relay.Var(\"uv\")\n    body = relay.add(iv, uv)\n    body = relay.Let(uv, relay.RefRead(i), body)\n    body = relay.Let(u, relay.RefWrite(i, relay.const(2)), body)\n    body = relay.Let(iv, relay.RefRead(i), body)\n    body = relay.Let(i, relay.RefCreate(relay.const(1)), body)\n    mod[three_with_ref] = relay.Function([], body)\n    check_eval(three_with_ref, [], 3, mod=mod)\n\n\ndef test_binds():\n    x = relay.var(\"x\")\n    y = relay.add(x, x)\n    xx = np.ones((10, 20))\n    res = relay.create_executor().evaluate(y, binds={x: xx}).numpy()\n    testing.assert_allclose(xx + xx, res)\n\n\ndef test_kwargs_params():\n    x = relay.var(\"x\", shape=(1, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    z = relay.var(\"z\", shape=(1, 10))\n    f = relay.Function([x, y, z], x + y + z)\n    x_data = np.random.rand(1, 10).astype(\"float32\")\n    y_data = np.random.rand(1, 10).astype(\"float32\")\n    z_data = np.random.rand(1, 10).astype(\"float32\")\n    params = {\"y\": y_data, \"z\": z_data}\n    res = relay.create_executor().evaluate(f)(x_data, **params)\n    testing.assert_allclose(res.numpy(), x_data + y_data + z_data)\n\n\ndef test_function_taking_adt_ref_tuple():\n    mod = tvm.IRModule()\n    prelude = relay.prelude.Prelude(mod)\n    _, cons, nil = prelude.mod.get_type(\"List\")\n\n    nil_value = ConstructorValue(nil.tag, [], nil)\n    cons_value = ConstructorValue(\n        cons.tag,\n        [nd.array(np.random.rand(1, 10).astype(\"float32\")), nil_value],\n        cons,\n    )\n\n    ref_value = RefValue(nd.array(np.random.rand(1, 10).astype(\"float32\")))\n    tuple_value = container.tuple_object(\n        [nd.array(np.random.rand(1, 10).astype(\"float32\")) for _ in range(10)]\n    )\n\n    id_func = relay.create_executor(mod=mod).evaluate(prelude.id)\n\n    res_nil = id_func(nil_value)\n    assert res_nil.tag == nil_value.tag\n    assert len(res_nil.fields) == 0\n\n    res_cons = id_func(cons_value)\n    assert res_cons.tag == cons_value.tag\n    assert len(res_cons.fields) == len(cons_value.fields)\n    testing.assert_allclose(res_cons.fields[0].numpy(), cons_value.fields[0].numpy())\n    assert isinstance(res_cons.fields[1], ConstructorValue)\n    assert res_cons.fields[1].tag == nil.tag\n    assert len(res_cons.fields[1].fields) == 0\n\n    res_ref = id_func(ref_value)\n    testing.assert_allclose(res_ref.value.numpy(), ref_value.value.numpy())\n\n    res_tuple = id_func(tuple_value)\n    for i in range(10):\n        testing.assert_allclose(res_tuple[i].numpy(), tuple_value[i].numpy())\n\n\ndef test_tuple_passing():\n    x = relay.var(\n        \"x\",\n        type_annotation=relay.ty.TupleType(\n            [relay.ty.TensorType((), \"int64\"), relay.ty.TensorType((), \"int64\")]\n        ),\n    )\n\n    fn = relay.Function([x], relay.expr.TupleGetItem(x, 0))\n    mod = tvm.IRModule({})\n    gv = relay.GlobalVar(\"main\")\n    mod[gv] = fn\n    mod = relay.transform.InferType()(mod)\n\n    dev = tvm.cpu()\n    target = tvm.target.Target(\"llvm\")\n    f = relay.create_executor(mod=mod, device=dev, target=target).evaluate(gv)\n    # First use a Python tuple.\n    out = f((10, 8))\n    testing.assert_allclose(out.numpy(), np.array(10))\n    # Second use a tuple value.\n    value_tuple = container.tuple_object([nd.array(np.array(11)), nd.array(np.array(12))])\n    out = f(value_tuple)\n    testing.assert_allclose(out.numpy(), np.array(11))\n\n\ndef test_dynamic():\n    n = 3\n    m = 2\n    x = relay.Var(\"x\", relay.TensorType([relay.Any(), m], \"float32\"))\n    y = relay.Var(\"y\", relay.TensorType([relay.Any(), m], \"float32\"))\n    xx = x - relay.expr.const(3.0)\n    yy = y * relay.expr.const(5.0)\n    z = relay.op.concatenate([xx, yy], axis=0)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], z)\n    x_np = np.random.uniform(size=(n, m)).astype(\"float32\")\n    y_np = np.random.uniform(size=(n, m)).astype(\"float32\")\n    expected = np.concatenate([x_np - 3.0, y_np * 5.0], axis=0)\n    check_eval(None, [x_np, y_np], expected, mod)\n\n\ndef test_ref_global_from_expr():\n    n = 3\n    x = relay.Var(\"x\", relay.TensorType([n], \"float32\"))\n    y = relay.Var(\"y\", relay.TensorType([n], \"float32\"))\n    mod = tvm.IRModule()\n    mod[\"add\"] = relay.Function([x, y], relay.add(x, y))\n    x_np = np.random.uniform(size=(n,)).astype(\"float32\")\n    y_np = np.random.uniform(size=(n,)).astype(\"float32\")\n    expected = np.add(x_np, y_np)\n    expr = relay.Call(mod.get_global_var(\"add\"), [relay.const(x_np), relay.const(y_np)])\n    check_eval(expr, None, expected, mod)\n\n\ndef test_keyword_args():\n    n = 3\n    x = relay.Var(\"x\", relay.TensorType([n], \"float32\"))\n    y = relay.Var(\"y\", relay.TensorType([n], \"float32\"))\n    z = relay.add(x, y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], z)\n    x_np = np.random.uniform(size=(n,)).astype(\"float32\")\n    y_np = np.random.uniform(size=(n,)).astype(\"float32\")\n    expected = np.add(x_np, y_np)\n    actual = relay.create_executor(mod=mod).evaluate()(y=y_np, x=x_np)\n    testing.assert_allclose(actual.numpy(), expected)\n\n\n# TODO(mbs): Support? Would help reduce wasted work when we need to prepare\n# multiple functions w.r.t. the same module.\n@pytest.mark.skip(reason=\"closures are currently not directly Python callable\")\ndef test_functional_returns():\n    n = 3\n    x = relay.Var(\"x\", relay.TensorType([n], \"float32\"))\n    f = relay.Function([x], x)\n    t = relay.Tuple([f, f])\n    c = np.random.rand(n).astype(\"float32\")\n    result1, result2 = relay.create_executor().evaluate(t)\n    testing.assert_allclose(result1(c).numpy(), c)\n    testing.assert_allclose(result2(c).numpy(), c)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.target.target import Target\nfrom tvm.relay.backend import Runtime, Executor, graph_executor_codegen\n\n\n@pytest.mark.parametrize(\n    \"test_target,unsupported_config\",\n    [\n        [\"c\", \"-runtime=c\"],\n        [\"c\", \"-system-lib=1\"],\n        [\"c\", \"-executor=aot\"],\n        [\"c\", \"-interface-api=c\"],\n        [\"c\", \"-unpacked-api=1\"],\n        [\"c\", \"-link-params=1\"],\n    ],\n)\ndef test_deprecated_target_parameters(test_target, unsupported_config):\n    with pytest.raises(ValueError) as e_info:\n        Target(f\"{test_target} {unsupported_config}\")\n        assert f\"Cannot recognize '{unsupported_config}\" in str(e_info.execption)\n\n\ndef test_build_relay_graph_():\n    \"\"\"Test to build a simple relay graph by using APIs directly\"\"\"\n\n    def build_graph(mod, target):\n        target, target_host = tvm.target.Target.canon_target_and_host(target)\n        mod, _ = relay.optimize(mod, target)\n        grc = graph_executor_codegen.GraphExecutorCodegen(None, target)\n        _, lowered_funcs, _ = grc.codegen(mod, mod[\"main\"])\n        _ = relay.backend._backend.build(lowered_funcs, target)\n\n    def add(shape, dtype):\n        lhs = relay.var(\"A\", shape=shape, dtype=dtype)\n        rhs = relay.var(\"B\", shape=shape, dtype=dtype)\n        out = relay.add(lhs, rhs)\n        expr = relay.Function((lhs, rhs), out)\n        mod = tvm.IRModule.from_expr(expr)\n        return mod\n\n    build_graph(add((1, 8), \"float32\"), tvm.target.Target(\"llvm\"))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_call_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name\nimport pytest\nimport tvm\nfrom tvm import relay\n\n\ndef test_callgraph_construct():\n    mod = tvm.IRModule({})\n    x = relay.var(\"x\", shape=(2, 3))\n    y = relay.var(\"y\", shape=(2, 3))\n    mod[\"g1\"] = relay.Function([x, y], x + y)\n    call_graph = relay.analysis.CallGraph(mod)\n    assert \"g1\" in str(call_graph)\n    assert tvm.ir.structural_equal(mod, call_graph.module)\n\n\ndef test_print_element():\n    mod = tvm.IRModule({})\n    x0 = relay.var(\"x0\", shape=(2, 3))\n    y0 = relay.var(\"y0\", shape=(2, 3))\n    mod[\"g0\"] = relay.Function([x0, y0], x0 + y0)\n    x1 = relay.var(\"x1\", shape=(2, 3))\n    y1 = relay.var(\"y1\", shape=(2, 3))\n    mod[\"g1\"] = relay.Function([x1, y1], x1 - y1)\n    call_graph = relay.analysis.CallGraph(mod)\n\n    assert \"#refs = 0\" in str(call_graph.print_var(\"g0\"))\n    assert \"#refs = 0\" in str(call_graph.print_var(\"g1\"))\n\n\ndef test_global_call_count():\n    mod = tvm.IRModule({})\n    x0 = relay.var(\"x0\", shape=(2, 3))\n    y0 = relay.var(\"y0\", shape=(2, 3))\n    g0 = relay.GlobalVar(\"g0\")\n    mod[g0] = relay.Function([x0, y0], x0 + y0)\n    x1 = relay.var(\"x1\", shape=(2, 3))\n    y1 = relay.var(\"y1\", shape=(2, 3))\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = relay.Function([x1, y1], g0(x1, y1))\n    call_graph = relay.analysis.CallGraph(mod)\n\n    p0 = relay.var(\"p0\", shape=(2, 3))\n    p1 = relay.var(\"p1\", shape=(2, 3))\n    func = relay.Function([p0, p1], g0(p0, p1) * g1(p0, p1))\n    mod[\"main\"] = func\n    call_graph = relay.analysis.CallGraph(mod)\n\n    assert call_graph.global_call_count(g0) == 0\n    assert call_graph.global_call_count(g1) == 1\n    assert call_graph.global_call_count(\"main\") == 2\n\n\ndef test_ref_count():\n    mod = tvm.IRModule({})\n    x0 = relay.var(\"x0\", shape=(2, 3))\n    y0 = relay.var(\"y0\", shape=(2, 3))\n    g0 = relay.GlobalVar(\"g0\")\n    mod[g0] = relay.Function([x0, y0], x0 + y0)\n    x1 = relay.var(\"x1\", shape=(2, 3))\n    y1 = relay.var(\"y1\", shape=(2, 3))\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = relay.Function([x1, y1], x1 - y1)\n    call_graph = relay.analysis.CallGraph(mod)\n\n    p0 = relay.var(\"p0\", shape=(2, 3))\n    p1 = relay.var(\"p1\", shape=(2, 3))\n    func = relay.Function([p0, p1], g0(p0, p1) * g1(p0, p1))\n    mod[\"main\"] = func\n    call_graph = relay.analysis.CallGraph(mod)\n\n    assert call_graph.ref_count(g0) == 1\n    assert call_graph.ref_count(g1) == 1\n    assert call_graph.ref_count(\"main\") == 0\n\n\ndef test_nested_ref():\n    mod = tvm.IRModule({})\n    x0 = relay.var(\"x0\", shape=(2, 3))\n    y0 = relay.var(\"y0\", shape=(2, 3))\n    g0 = relay.GlobalVar(\"g0\")\n    mod[g0] = relay.Function([x0, y0], x0 + y0)\n    x1 = relay.var(\"x1\", shape=(2, 3))\n    y1 = relay.var(\"y1\", shape=(2, 3))\n    g1 = relay.GlobalVar(\"g1\")\n    mod[g1] = relay.Function([x1, y1], g0(x1, y1))\n    call_graph = relay.analysis.CallGraph(mod)\n\n    p0 = relay.var(\"p0\", shape=(2, 3))\n    p1 = relay.var(\"p1\", shape=(2, 3))\n    func = relay.Function([p0, p1], g0(p0, p1) * g1(p0, p1))\n    mod[\"main\"] = func\n    call_graph = relay.analysis.CallGraph(mod)\n\n    assert call_graph.ref_count(g0) == 2\n    assert call_graph.ref_count(g1) == 1\n    assert call_graph.ref_count(\"main\") == 0\n\n\ndef test_recursive_func():\n    mod = tvm.IRModule({})\n\n    x = relay.var(\"x\", shape=[], dtype=\"int32\")\n    fn0 = relay.Function([x], x)\n    gx = relay.GlobalVar(\"gx\")\n    mod[gx] = fn0\n\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sb = relay.ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n        sb.ret(i)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n        global_call = gx(i)\n        rec_call = relay.Call(sum_up, [one_less]) + global_call\n        sb.ret(relay.add(rec_call, i))\n    func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n    func = func.with_attr(\"Compiler\", \"a\")\n    mod[sum_up] = func\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n    call_graph = relay.analysis.CallGraph(mod)\n\n    assert call_graph.is_recursive(sum_up)\n    assert call_graph.ref_count(sum_up) == 2\n    assert call_graph.ref_count(gx) == 1\n    assert call_graph.ref_count(\"main\") == 0\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_change_batch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.testing import synthetic\nfrom tvm.relay import transform\n\n\ndef test_change_batch_synthetic():\n    net, params = synthetic.get_workload()\n    new_net = transform.ChangeBatch({net[\"main\"].params[0]: 0}, batch_size=123)(net)\n    assert new_net[\"main\"].checked_type.ret_type.shape[0] == 123\n\n\nif __name__ == \"__main__\":\n    test_change_batch_synthetic()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_cmp_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom tvm import relay\n\na = relay.Var(\"a\")\nb = relay.expr.const(1.0, dtype=\"float32\")\n\nc = a < b\nd = relay.less(a, b)\nassert c.astext() == d.astext()\n\nc = a > b\nd = relay.greater(a, b)\nassert c.astext() == d.astext()\n\nc = a >= b\nd = relay.greater_equal(a, b)\nassert c.astext() == d.astext()\n\nc = a <= b\nd = relay.less_equal(a, b)\nassert c.astext() == d.astext()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_const.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay.frontend.common import infer_type\nfrom tvm.relay import op as _op\n\n\ndef test_const_dtype():\n    strides = (1, 1)\n    np_array = np.array(strides).astype(\"int32\")\n    strides = _op.const(np_array, dtype=\"int64\")\n\n    # strides needs to be autoconverted to int64 on Windows\n    assert infer_type(strides).checked_type.dtype == np.dtype(np.int64)\n\n    a = tvm.nd.array(np.random.randint(0, high=255, size=(2, 3), dtype=\"uint8\"))\n    a = _op.const(a, dtype=\"uint8\")\n    aa = a.data.numpy()\n    assert aa.dtype == np.dtype(np.uint8)\n\n    b = _op.const(1, dtype=\"int8\")\n    bb = b.data.numpy()\n    assert bb.dtype == np.dtype(np.int8)\n\n    kshape = (3, 10, 3, 3)\n    w = relay.const(np.zeros(kshape, dtype=\"float32\"))\n    assert w.data.numpy().dtype == np.dtype(np.float32)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_cpp_build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay, runtime\nfrom tvm.contrib.nvcc import have_fp16\nimport tvm.testing\n\n\ndef test_basic_build():\n    tgt = \"llvm\"\n    dev = tvm.cpu()\n    # func\n    a = relay.var(\"a\", dtype=\"float32\", shape=(16, 8))\n    b = relay.var(\"b\", dtype=\"float32\", shape=(8, 8))\n    c = relay.var(\"c\", dtype=\"float32\", shape=(16, 8))\n    x = relay.nn.dense(a, b)\n    y = relay.nn.relu(x)\n    z = y + c\n    func = relay.Function([a, b, c], z)\n    A = tvm.nd.array(np.random.uniform(-1, 1, (16, 8)).astype(\"float32\"), device=dev)\n    B = tvm.nd.array(np.random.uniform(-1, 1, (8, 8)).astype(\"float32\"), device=dev)\n    C = tvm.nd.array(np.random.uniform(-1, 1, (16, 8)).astype(\"float32\"), device=dev)\n    params = {\"b\": B, \"c\": C}\n    # build\n    targets = {tvm.tir.IntImm(\"int32\", dev.device_type): tgt}\n    mod = tvm.IRModule.from_expr(func)\n    func_in_mod = mod[\"main\"]\n    assert mod[\"main\"] == func_in_mod, \"cannot compare function to itself\"\n\n    lib = relay.build(mod, targets, \"llvm\", params=params)\n    assert mod[\"main\"] == func_in_mod, \"relay.build changed module in-place\"\n\n    # test\n    rt = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    rt.set_input(\"a\", A)\n    rt.run()\n    out = rt.get_output(0)\n\n    np.testing.assert_allclose(\n        out.numpy(),\n        np.maximum(np.dot(A.numpy(), B.numpy().T), 0) + C.numpy(),\n        atol=1e-5,\n        rtol=1e-5,\n    )\n\n\n@tvm.testing.requires_cuda\ndef test_fp16_build():\n    dtype = \"float16\"\n\n    dev = tvm.cuda(0)\n    if dtype == \"float16\" and not have_fp16(dev.compute_version):\n        print(\"skip because gpu does not support fp16\")\n        return\n\n    x = relay.var(\"x\", dtype=dtype, shape=(4, 4))\n    y = relay.var(\"y\", dtype=dtype, shape=(4, 4))\n    z = x + y\n    func = relay.Function([x, y], z)\n    X = tvm.nd.array(np.random.uniform(-1, 1, (4, 4)).astype(dtype), device=dev)\n    Y = tvm.nd.array(np.random.uniform(-1, 1, (4, 4)).astype(dtype), device=dev)\n    params = {\n        \"x\": X,\n        \"y\": Y,\n    }\n\n    # build\n    g_json, mmod, params = relay.build(func, \"cuda\", params=params)\n\n    # test\n    rt = tvm.contrib.graph_executor.create(g_json, mmod, dev)\n    rt.load_params(runtime.save_param_dict(params))\n    rt.run()\n    out = rt.get_output(0)\n\n    np.testing.assert_allclose(out.numpy(), X.numpy() + Y.numpy(), atol=1e-5, rtol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_bf16_build():\n    data = relay.var(\"data\", shape=(1, 3, 224, 224), dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=(64, 3, 7, 7), dtype=\"float32\")\n    bn_gamma = relay.var(\"gamma\", shape=(64,), dtype=\"float32\")\n    bn_beta = relay.var(\"beta\", shape=(64,), dtype=\"float32\")\n    bn_mean = relay.var(\"mean\", shape=(64,), dtype=\"float32\")\n    bn_var = relay.var(\"var\", shape=(64,), dtype=\"float32\")\n    params = {\n        \"weight\": np.random.uniform(-1, 1, size=(64, 3, 7, 7)).astype(\"float32\"),\n        \"gamma\": np.random.uniform(-1, 1, size=(64,)).astype(\"float32\"),\n        \"beta\": np.random.uniform(-1, 1, size=(64,)).astype(\"float32\"),\n        \"mean\": np.random.uniform(-1, 1, size=(64,)).astype(\"float32\"),\n        \"var\": np.random.uniform(-1, 1, size=(64,)).astype(\"float32\"),\n    }\n    conv_bf16 = relay.nn.conv2d(\n        relay.cast(data, \"bfloat16\"),\n        relay.cast(weight, \"bfloat16\"),\n        strides=(2, 2),\n        padding=(3, 3, 3, 3),\n        channels=64,\n        kernel_size=(7, 7),\n        out_dtype=\"bfloat16\",\n    )\n    bn_bf16 = relay.nn.batch_norm(\n        conv_bf16,\n        relay.cast(bn_gamma, \"bfloat16\"),\n        relay.cast(bn_beta, \"bfloat16\"),\n        relay.cast(bn_mean, \"bfloat16\"),\n        relay.cast(bn_var, \"bfloat16\"),\n    )\n    relu_bf16 = relay.nn.relu(bn_bf16[0])\n    maxpool_bf16 = relay.nn.max_pool2d(relu_bf16, pool_size=(2, 2), strides=(2, 2))\n    avgpool_bf16 = relay.nn.avg_pool2d(maxpool_bf16, pool_size=(2, 2), strides=(2, 2))\n    flattened_bf16 = relay.nn.batch_flatten(avgpool_bf16)\n    softmax_bf16 = relay.nn.softmax(flattened_bf16)\n    mod_bf16 = tvm.IRModule.from_expr(softmax_bf16)\n    with tvm.transform.PassContext(opt_level=3):\n        relay.build(mod_bf16, target=\"llvm\", params=params)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\ndef test_fp16_conversion(target, dev):\n    if target == \"cuda\" and not have_fp16(dev.compute_version):\n        print(\"skip because gpu does not support fp16\")\n        return\n\n    n = 10\n\n    for (src, dst) in [(\"float32\", \"float16\"), (\"float16\", \"float32\")]:\n        x = relay.var(\"x\", relay.TensorType((n,), src))\n        y = x.astype(dst)\n        func = relay.Function([x], y)\n\n        # init input\n        X = tvm.nd.array(n * np.random.randn(n).astype(src) - n / 2)\n\n        # build\n        with tvm.transform.PassContext(opt_level=1):\n            g_json, mmod, params = relay.build(tvm.IRModule.from_expr(func), target)\n\n        # test\n        rt = tvm.contrib.graph_executor.create(g_json, mmod, dev)\n        rt.set_input(\"x\", X)\n        rt.run()\n        out = rt.get_output(0)\n\n        np.testing.assert_allclose(out.numpy(), X.numpy().astype(dst), atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_basic_build()\n    test_fp16_build()\n    test_fp16_conversion()\n    test_bf16_build()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_dataflow_pattern.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-wildcard-import\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.dataflow_pattern import *\nfrom tvm.relay.testing import run_opt_pass\n\n# NB: 1 corresponds to the C++ enum that specicfies this\n# we loose the type safety due to the Python/C++ calling\n# convention.\nK_ELEMWISE = 0\nK_BROADCAST = 1\n\n\n## NODE TESTS\ndef test_expr_pattern():\n    ep = is_expr(relay.var(\"x\", shape=(4, 1)))\n    assert isinstance(ep, ExprPattern)\n    assert isinstance(ep.expr, relay.Var)\n\n\ndef test_var_pattern():\n    v = is_var(\"x\")\n    assert isinstance(v, VarPattern)\n    assert v.name == \"x\"\n\n\ndef test_constant_pattern():\n    c = is_constant()\n    assert isinstance(c, ConstantPattern)\n\n\ndef test_wildcard_pattern():\n    wc = wildcard()\n    assert isinstance(wc, WildcardPattern)\n\n\ndef test_CallPattern():\n    wc1 = wildcard()\n    wc2 = wildcard()\n    c = is_op(\"add\")(wc1, wc2)\n    assert isinstance(c, CallPattern)\n    assert isinstance(c.args[0], WildcardPattern)\n    assert isinstance(c.args[1], WildcardPattern)\n\n\ndef test_FunctionPattern():\n    wc1 = wildcard()\n    wc2 = wildcard()\n    c = is_op(\"add\")(wc1, wc2)\n    f = FunctionPattern([wc1, wc2], c)\n    assert isinstance(f, FunctionPattern)\n    assert isinstance(f.params[0], WildcardPattern)\n    assert isinstance(f.params[1], WildcardPattern)\n    assert isinstance(f.body, CallPattern)\n    assert isinstance(f.body.args[0], WildcardPattern)\n    assert isinstance(f.body.args[1], WildcardPattern)\n\n\ndef test_TuplePattern():\n    wc1 = wildcard()\n    wc2 = wildcard()\n    t = is_tuple([wc1, wc2])\n    assert isinstance(t, TuplePattern)\n    assert isinstance(t.fields[0], WildcardPattern)\n    assert isinstance(t.fields[1], WildcardPattern)\n\n\ndef test_TupleGetItemPattern():\n    wc1 = wildcard()\n    wc2 = wildcard()\n    t = is_tuple([wc1, wc2])\n    tgi = is_tuple_get_item(t, 1)\n    assert isinstance(tgi, TupleGetItemPattern)\n    assert isinstance(tgi.tuple, TuplePattern)\n    assert isinstance(tgi.tuple.fields[0], WildcardPattern)\n    assert isinstance(tgi.tuple.fields[1], WildcardPattern)\n\n\ndef test_AltPattern():\n    is_add_or_sub = is_op(\"add\") | is_op(\"subtract\")\n    assert isinstance(is_add_or_sub, AltPattern)\n\n\ndef test_TypePattern():\n    ttype = relay.TensorType((10, 10), \"float32\")\n    ty_pat = has_type(ttype)\n    assert isinstance(ty_pat, TypePattern)\n    assert ty_pat.type == ttype\n\n\ndef test_DataTypePattern():\n    dtype = \"float16\"\n    pattern = has_dtype(dtype)\n    assert isinstance(pattern, DataTypePattern)\n    assert pattern.dtype == dtype\n\n\ndef test_ShapePattern():\n    shape = [10, 10]\n    pattern = has_shape(shape)\n    assert isinstance(pattern, ShapePattern)\n    assert tvm.ir.structural_equal(pattern.shape, shape)\n\n\ndef test_AttrPattern():\n    op = is_op(\"add\").has_attr({\"TOpPattern\": K_ELEMWISE})\n    assert isinstance(op, AttrPattern)\n    assert op.attrs[\"TOpPattern\"] == K_ELEMWISE\n\n\ndef test_IfPattern():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    pat = is_if(is_op(\"less\")(x, y), x, y)\n\n    assert isinstance(pat, IfPattern)\n    assert isinstance(pat.cond, CallPattern)\n    assert isinstance(pat.true_branch, VarPattern)\n    assert isinstance(pat.false_branch, VarPattern)\n\n\ndef test_LetPattern():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    let_var = is_var(\"let\")\n    pat = is_let(let_var, is_op(\"less\")(x, y), let_var)\n\n    assert isinstance(pat, LetPattern)\n    assert isinstance(pat.var, VarPattern)\n    assert isinstance(pat.value, CallPattern)\n    assert isinstance(pat.body, VarPattern)\n\n\n## MATCHER TESTS\n\n\ndef test_match_op():\n    assert is_op(\"add\").match(relay.op.op.get(\"add\"))\n\n\ndef test_no_match_op():\n    assert not is_op(\"add\").match(relay.op.op.get(\"subtract\"))\n\n\ndef test_match_op_or():\n    is_add_or_sub = is_op(\"add\") | is_op(\"subtract\")\n    assert is_add_or_sub.match(relay.op.op.get(\"add\"))\n    assert is_add_or_sub.match(relay.op.op.get(\"subtract\"))\n\n\ndef test_match_call_commutive():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"add\")(is_var(\"x\"), is_var(\"y\"))\n    assert add_pattern.match(x + y)\n    assert add_pattern.match(y + x)\n    mul_pattern = is_op(\"multiply\")(is_var(\"x\"), is_var(\"y\"))\n    assert mul_pattern.match(x * y)\n    assert mul_pattern.match(y * x)\n\n\ndef test_no_match_call_commutive():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"subtract\")(is_var(\"x\"), is_var(\"y\"))\n    assert add_pattern.match(x - y)\n    assert not add_pattern.match(y - x)\n    add_pattern = is_op(\"divide\")(is_var(\"x\"), is_var(\"y\"))\n    assert add_pattern.match(x / y)\n    assert not add_pattern.match(y / x)\n\n\ndef test_match_call():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"add\")(wildcard(), wildcard())\n    assert add_pattern.match(x + y)\n\n    # Match call with any number of inputs\n    call_pattern = wildcard()(None)\n    assert call_pattern.match(relay.op.nn.relu(x))\n    assert call_pattern.match(relay.op.add(x, y))\n\n\ndef test_no_match_call():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"add\")(wildcard(), wildcard())\n    assert not add_pattern.match(x - y)\n\n\ndef test_match_func():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    wc1 = wildcard()\n    wc2 = wildcard()\n    func_pattern = FunctionPattern([wc1, wc2], wc1 + wc2)\n    assert func_pattern.match(relay.Function([x, y], x + y))\n\n    # Match Function with any number of inputs\n    func_pattern = FunctionPattern(None, wildcard())\n    assert func_pattern.match(relay.Function([x], x))\n    assert func_pattern.match(relay.Function([x, y], x + y))\n\n\ndef test_no_match_func():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    wc1 = wildcard()\n    wc2 = wildcard()\n    func_pattern = FunctionPattern([wc1, wc2], wc1 + wc2)\n    assert not func_pattern.match(relay.Function([x, y], x - y))\n\n\ndef test_match_if():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    pat = is_if(is_op(\"less\")(x, y), x, y)\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    cond = x < y\n\n    assert pat.match(relay.expr.If(cond, x, y))\n\n\ndef test_no_match_if():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    pat = is_if(is_op(\"less\")(x, y), x, y)\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n\n    assert not pat.match(relay.expr.If(x > y, x, y))\n    assert not pat.match(relay.expr.If(x < y, y, x))\n\n\ndef test_match_let():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    let_var = is_var(\"let\")\n    pat = is_let(let_var, is_op(\"less\")(x, y), let_var)\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    lv = relay.var(\"let\")\n    cond = x < y\n    assert pat.match(relay.expr.Let(lv, cond, lv))\n\n\ndef test_no_match_let():\n    x = is_var(\"x\")\n    y = is_var(\"y\")\n    let_var = is_var(\"let\")\n    pat = is_let(let_var, is_op(\"less\")(x, y), let_var)\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    lv = relay.var(\"let\")\n\n    assert not pat.match(relay.expr.Let(lv, x > y, lv))\n    assert not pat.match(relay.expr.Let(lv, x < y, lv * x))\n\n\ndef test_match_option():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.conv2d\")(wildcard(), wildcard()).optional(\n            lambda x: is_op(\"nn.bias_add\")(x, wildcard())\n        )\n    )\n\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n    assert pattern.match(relu)\n\n    conv2d = relay.op.nn.conv2d(x, w)\n    bias_add = relay.op.nn.bias_add(conv2d, b)\n    relu = relay.op.nn.relu(bias_add)\n    assert pattern.match(relu)\n\n    pattern = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    pattern = pattern.optional(is_op(\"nn.relu\")).optional(is_op(\"tanh\"))\n\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n    tanh = relay.op.tanh(conv2d)\n    tanh2 = relay.op.tanh(relu)\n    relu2 = relay.op.nn.relu(tanh)\n    assert pattern.match(conv2d)\n    assert pattern.match(relu)\n    assert pattern.match(tanh)\n    assert pattern.match(tanh2)\n    assert not pattern.match(relu2)\n\n\ndef test_no_match_option():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.conv2d\")(wildcard(), wildcard()).optional(\n            lambda x: is_op(\"nn.bias_add\")(x, wildcard())\n        )\n    )\n\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.tanh(conv2d)\n    assert not pattern.match(relu)\n\n    conv2d = relay.op.nn.dense(x, w)\n    relu = relay.op.tanh(conv2d)\n    assert not pattern.match(relu)\n\n    conv2d = relay.op.nn.dense(x, w)\n    bias_add = relay.op.nn.bias_add(conv2d, b)\n    relu = relay.op.nn.relu(bias_add)\n    assert not pattern.match(relu)\n\n    conv2d = relay.op.nn.conv2d(x, w)\n    bias_add = conv2d + w\n    relu = relay.op.nn.relu(bias_add)\n    assert not pattern.match(relu)\n\n\ndef test_match_const():\n    conv2d = is_op(\"nn.conv2d\")(wildcard(), is_constant())\n    pattern = is_op(\"nn.bias_add\")(conv2d, wildcard())\n\n    x = relay.var(\"x\", shape=(1, 3, 224, 224))\n    w = relay.var(\"w\", shape=(3, 3, 3, 3))\n    b = relay.var(\"b\", shape=(3,))\n    conv2d = relay.op.nn.conv2d(x, w)\n    out = relay.op.nn.bias_add(conv2d, b)\n    func = relay.Function([x, w, b], out)\n    mod = tvm.IRModule.from_expr(func)\n\n    assert not pattern.match(mod[\"main\"].body)\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], {\"w\": tvm.nd.array(np.ones(shape=(3, 3, 3, 3)))})\n    assert pattern.match(mod[\"main\"].body)\n\n\ndef test_match_tuple():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.op.op.get(\"add\")\n    tuple_pattern = is_tuple((is_var(\"x\"), wildcard(), is_op(\"add\")))\n    assert tuple_pattern.match(relay.expr.Tuple((x, y, z)))\n\n    tuple_pattern = is_tuple((is_var(\"x\"), wildcard(), is_op(\"add\")))\n    tuple_get_item_pattern = is_tuple_get_item(tuple_pattern, 1)\n    assert tuple_get_item_pattern.match(relay.expr.TupleGetItem(relay.expr.Tuple((x, y, z)), 1))\n\n    tuple_get_item_pattern = is_tuple_get_item(tuple_pattern)  # Match any index\n    assert tuple_get_item_pattern.match(relay.expr.TupleGetItem(relay.expr.Tuple((x, y, z)), 0))\n    assert tuple_get_item_pattern.match(relay.expr.TupleGetItem(relay.expr.Tuple((x, y, z)), 1))\n    assert tuple_get_item_pattern.match(relay.expr.TupleGetItem(relay.expr.Tuple((x, y, z)), 2))\n\n    # Match tuple with any inputs\n    tuple_pattern = is_tuple(None)\n    concat_pattern = is_op(\"concatenate\")(tuple_pattern)\n    assert concat_pattern.match(relay.op.concatenate(relay.expr.Tuple((x,)), axis=0))\n    assert concat_pattern.match(relay.op.concatenate(relay.expr.Tuple((x, y)), axis=0))\n    assert concat_pattern.match(relay.op.concatenate(relay.expr.Tuple((x, y, z)), axis=0))\n\n\ndef test_no_match_tuple():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.op.op.get(\"add\")\n    tuple_pattern = is_tuple((is_var(\"x\"), wildcard(), is_op(\"add\"), wildcard()))\n    assert not tuple_pattern.match(relay.expr.Tuple((x, y, z)))\n\n    tuple_pattern = is_tuple((is_var(\"x\"), wildcard(), is_op(\"add\")))\n    tuple_get_item_pattern = is_tuple_get_item(tuple_pattern, 1)\n    assert not tuple_get_item_pattern.match(relay.expr.TupleGetItem(relay.expr.Tuple((x, y, z)), 2))\n\n\ndef test_match_type():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float32\")\n    ty_pat = has_type(relay.TensorType((10, 10), \"float32\"))\n    assert ty_pat.match(x)\n\n\ndef test_no_match_type():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"int32\")\n    ty_pat = has_type(relay.TensorType((10, 10), \"float32\"))\n    assert not ty_pat.match(x)\n\n\ndef test_match_dtype():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float32\")\n    ty_pat = has_dtype(\"float32\")\n    assert ty_pat.match(x)\n\n\ndef test_no_match_dtype():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"int32\")\n    ty_pat = has_dtype(\"float32\")\n    assert not ty_pat.match(x)\n\n\ndef test_match_shape():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float32\")\n    ty_pat = has_shape((10, 10))\n    assert ty_pat.match(x)\n\n\ndef test_no_match_shape():\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"int32\")\n    ty_pat = has_shape((10, 5))\n    assert not ty_pat.match(x)\n\n\ndef test_match_op_attr():\n    op = is_op(\"add\").has_attr({\"TOpPattern\": K_BROADCAST})\n    op_pat = op(wildcard(), wildcard())\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    assert op_pat.match(x + y)\n\n\ndef test_no_match_op_attr():\n    op = is_op(\"nn.dense\").has_attr({\"TOpPattern\": K_ELEMWISE})\n    op_pat = op(wildcard(), wildcard())\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    assert not op_pat.match(relay.op.nn.dense(x, y))\n    op = is_op(\"add\").has_attr({\"TOpPattern\": K_BROADCAST})\n    op_pat = op(wildcard(), wildcard())\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    assert not op_pat.match(x - y)\n    z = relay.var(\"z\")\n    assert not op_pat.match(relay.Let(z, x + y, z))\n\n\ndef test_match_func_attr():\n    pattern = wildcard().has_attr({\"Composite\": \"add\"})\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    f = relay.Function([x, y], x + y).with_attr(\"Composite\", \"add\")\n    assert pattern.match(f)\n\n\ndef test_no_match_func_attr():\n    pattern = wildcard().has_attr({\"Composite\": \"add\"})\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n\n    f = relay.Function([x, y], x + y).with_attr(\"RandomTest\", \"add\")\n    assert not pattern.match(f)\n    f = relay.Function([x, y], x + y).with_attr(\"Composite\", \"conv_bias\")\n    assert not pattern.match(f)\n\n\ndef test_match_call_attr():\n    # String attr\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard()).has_attr({\"data_layout\": \"NCHW\"})\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    assert is_conv2d.match(relay.op.nn.conv2d(x, y))\n\n    # Array attr\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard()).has_attr({\"kernel_size\": [3, 3]})\n    out = relay.op.nn.conv2d(x, y, kernel_size=[3, 3])\n    assert is_conv2d.match(out)\n\n    # non-operator call\n    attr_dict = {\"call_attr\": \"attr\"}\n    call_has_attr = wildcard()(wildcard()).has_attr(attr_dict)\n    call_attr = tvm.ir.make_node(\"DictAttrs\", **attr_dict)\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    assert call_has_attr.match(relay.Call(a, [b], attrs=call_attr))\n\n    # empty attrs should match anything\n    empty_attrs = tvm.ir.make_node(\"DictAttrs\", **{})\n    call_has_empty_attrs = wildcard()(wildcard()).has_attr({})\n    assert call_has_empty_attrs.match(relay.Call(a, [b], attrs=empty_attrs))\n    assert call_has_empty_attrs.match(relay.Call(a, [b], attrs=call_attr))\n\n\ndef test_no_match_call_attr():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard()).has_attr({\"data_layout\": \"NHWC\"})\n    assert not is_conv2d.match(relay.op.nn.conv2d(x, y))\n\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard()).has_attr({\"RandomAttr\": \"NCHW\"})\n    assert not is_conv2d.match(relay.op.nn.conv2d(x, y))\n\n    # Array attr\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard()).has_attr({\"kernel_size\": [3, 3]})\n    out = relay.op.nn.conv2d(x, y, kernel_size=[2, 1])\n    assert not is_conv2d.match(out)\n\n    # non-operator calls\n    call_has_attr = wildcard()(wildcard()).has_attr({\"call_attr\": \"attr\"})\n    wrong_key = tvm.ir.make_node(\"DictAttrs\", **{\"wrong\": \"attr\"})\n    wrong_value = tvm.ir.make_node(\"DictAttrs\", **{\"call_attr\": \"wrong\"})\n    empty_attrs = tvm.ir.make_node(\"DictAttrs\", **{})\n\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    # attrs left undefined\n    assert not call_has_attr.match(relay.Call(a, [b]))\n    # wrong attrs\n    assert not call_has_attr.match(relay.Call(a, [b], attrs=wrong_key))\n    assert not call_has_attr.match(relay.Call(a, [b], attrs=wrong_value))\n    assert not call_has_attr.match(relay.Call(a, [b], attrs=empty_attrs))\n\n\ndef test_match_call_attr_dtype():\n    is_cast = is_op(\"cast\")(wildcard()).has_attr({\"dtype\": \"float32\"})\n    x = relay.var(\"x\")\n    assert is_cast.match(relay.op.cast(x, \"float32\"))\n\n\ndef test_match_diamond():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    path1 = is_op(\"nn.relu\")(is_conv2d)\n    path2 = is_op(\"nn.leaky_relu\")(is_conv2d)\n    diamond = is_op(\"add\")(path1, path2)\n\n    # Expr\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert diamond.match(out)\n\n\ndef test_no_match_diamond():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    path1 = is_op(\"nn.relu\")(is_conv2d)\n    path2 = is_op(\"nn.leaky_relu\")(is_conv2d)\n    diamond = is_op(\"add\")(path1, path2)\n\n    # Expr\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n\n    # Check\n    assert not diamond.match(leaky_relu)\n    assert not diamond.match(relu)\n\n\ndef test_match_fake_diamond():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    path1 = is_op(\"nn.relu\")(is_conv2d)\n    path2 = is_op(\"nn.leaky_relu\")(is_conv2d)\n    diamond = is_op(\"add\")(path1, path2)\n\n    # Expr\n    input1 = relay.var(\"input1\")\n    weight1 = relay.var(\"weight1\")\n    conv2d1 = relay.op.nn.conv2d(input1, weight1)\n    inp2 = relay.var(\"input2\")\n    weight2 = relay.var(\"weight2\")\n    conv2d2 = relay.op.nn.conv2d(inp2, weight2)\n    relu = relay.op.nn.relu(conv2d1)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d2, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert not diamond.match(out)\n\n\ndef test_at_most_one_parent():\n    # Pattern\n    P = is_op(\"nn.conv2d\")(wildcard(), wildcard())  # 'parent'\n    I = is_op(\"nn.relu\")(wildcard())  # 'intermediate' ('path' in the code)\n    C = is_op(\"add\")(wildcard(), wildcard())  # 'child'\n    pattern = dominates(P, I, C)\n\n    #       n6(P)\n    #      /  \\\n    #     n7   \\\n    #    /      \\\n    #    n8(P)  n10(I)\n    #    \\      /\n    #    n9(I) /\n    #      \\  /\n    #      n11(C)\n\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    n6 = relay.op.nn.conv2d(x, w)  # matches P\n    n7 = relay.op.tanh(n6)  # does not match I\n    n8 = relay.op.nn.conv2d(n7, w)  # matches P\n    n9 = relay.op.nn.relu(n8)  # matches I\n    n10 = relay.op.nn.relu(n6)  # matches I\n    n11 = relay.add(n9, n10)  # matches C\n\n    # Does not match: Can't match the parent pattern P at both 8 and 6.\n    # Note that if we did allow P to be used twice the implementation would\n    # need to be changed to not 'jump over' n7.\n    assert not pattern.match(n11)\n\n\ndef test_match_dominator():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard())\n    reduction = is_op(\"add\")(wildcard(), wildcard())\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Classic Diamond\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert diamond.match(out)\n\n    # Deeper Branch\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    relu = relay.op.tanh(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert diamond.match(out)\n\n    # Single Branch\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    tanh = relay.op.tanh(relu)\n    out = relu + tanh\n\n    # Check\n    assert diamond.match(out)\n\n    # Fuzzy path/nested Diamond\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard()) | is_op(\n        \"add\"\n    )(wildcard(), wildcard())\n    reduction = is_op(\"add\")(wildcard(), wildcard())\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relu + relu\n    tanh = relay.op.tanh(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = tanh + leaky_relu\n\n    assert diamond.match(out)\n\n\ndef test_not_match_dominator():\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard())\n    reduction = is_op(\"add\")(wildcard(), wildcard())\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Fake Diamond\n    input1 = relay.var(\"input1\")\n    weight1 = relay.var(\"weight1\")\n    conv2d1 = relay.op.nn.conv2d(input1, weight1)\n    inp2 = relay.var(\"input2\")\n    weight2 = relay.var(\"weight2\")\n    conv2d2 = relay.op.nn.conv2d(inp2, weight2)\n    relu = relay.op.nn.relu(conv2d1)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d2, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert not diamond.match(out)\n\n    # Add op that doesn't match K_ELEMWISE\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relu + relu\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert not diamond.match(out)\n\n    # Relu on the input instead of the conv\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(inp)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert not diamond.match(out)\n\n    # No conv\n    inp = relay.var(\"input\")\n    relu = relay.op.nn.relu(inp)\n    relu = relay.op.nn.relu(relu)\n    tanh = relay.op.tanh(relu)\n    out = relu + tanh\n\n    # Check\n    assert not diamond.match(out)\n\n\ndef test_match_typed_dominator():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard()).has_dtype(\n        \"float32\"\n    )\n    reduction = is_op(\"add\")(wildcard(), wildcard()).has_shape([1, 3, 10, 10])\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Classic Diamond\n    inp = relay.var(\"input\", relay.TensorType((1, 3, 12, 12), \"float32\"))\n    weight = relay.var(\"weight\", relay.TensorType((3, 3, 3, 3), \"float32\"))\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Check\n    assert diamond.match(out)\n\n\ndef test_no_match_typed_dominator():\n    # Classic Diamond\n    inp = relay.var(\"input\", relay.TensorType((1, 3, 12, 12), \"float32\"))\n    weight = relay.var(\"weight\", relay.TensorType((3, 3, 3, 3), \"float32\"))\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard()).has_dtype(\n        \"float32\"\n    )\n    reduction = is_op(\"add\")(wildcard(), wildcard()).has_shape([1, 1, 10, 10])\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Check\n    assert not diamond.match(out)\n\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard()).has_dtype(\n        \"float16\"\n    )\n    reduction = is_op(\"add\")(wildcard(), wildcard()).has_shape([1, 3, 10, 10])\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Check\n    assert not diamond.match(out)\n\n\ndef test_rewrite():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"add\")(wildcard(), wildcard())\n    sub_pattern = is_op(\"subtract\")(wildcard(), wildcard())\n\n    class TestRewrite(DFPatternCallback):\n        def __init__(self):\n            super(TestRewrite, self).__init__()\n            self.pattern = add_pattern\n\n        def callback(self, pre, post, node_map):\n            return post.args[0] - post.args[1]\n\n    out = rewrite(TestRewrite(), x + y)\n    assert sub_pattern.match(out)\n\n\ndef test_rewrite_func():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    y = relay.var(\"y\")\n    add_pattern = is_op(\"add\")(wildcard(), wildcard())\n    sub_pattern = is_op(\"subtract\")(wildcard(), wildcard())\n\n    class TestRewrite(DFPatternCallback):\n        def __init__(self):\n            super(TestRewrite, self).__init__()\n            self.pattern = add_pattern\n\n        def callback(self, pre, post, node_map):\n            return post.args[0] - post.args[1]\n\n    inpf = relay.var(\"input\")\n    weightf = relay.var(\"weight\")\n    func = relay.Function(\n        [inpf, weightf], relay.op.nn.relu(relay.op.nn.conv2d(inpf, weightf)), attrs=None\n    )\n    out = rewrite(TestRewrite(), func(x, w) + y)\n    assert sub_pattern.match(out)\n\n\ndef test_rewrite_func_with_attr():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    f = relay.Function([x, y], x + y).with_attr(\"Composite\", \"add\")\n\n    a = relay.var(\"a\")\n    b = relay.var(\"b\")\n    c = relay.Call(f, [a, b])\n    c_abs = relay.abs(c)\n\n    class TestRewrite(DFPatternCallback):\n        def __init__(self):\n            super(TestRewrite, self).__init__()\n            self.pattern = wildcard().has_attr({\"Composite\": \"add\"})(wildcard(), wildcard())\n\n        def callback(self, pre, post, node_map):\n            return post.args[0] + post.args[1]\n\n    out = rewrite(TestRewrite(), c_abs)\n    inlined_add_pattern = is_op(\"abs\")(is_op(\"add\")(wildcard(), wildcard()))\n    assert inlined_add_pattern.match(out)\n\n\ndef test_nested_rewrite():\n    class PatternCallback(DFPatternCallback):\n        def __init__(self, pattern):\n            super(PatternCallback, self).__init__()\n            self.pattern = pattern\n\n        def callback(self, pre, post, node_map):\n            return post\n\n    def gen():\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n        y_add = relay.add(y, y)\n        n0 = relay.add(x, y_add)\n        n1 = relay.add(x, n0)\n        return relay.add(n1, n0)\n\n    def pattern():\n        a = wildcard()\n        b = wildcard()\n        n0 = is_op(\"add\")(a, b)\n        n1 = is_op(\"add\")(n0, a)\n        return is_op(\"add\")(n0, n1)\n\n    out = gen()\n    pat = pattern()\n    new_out = rewrite(PatternCallback(pat), out)\n\n    assert tvm.ir.structural_equal(out, new_out)\n\n\ndef test_not_fuse_multi_diamond():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    path1 = is_op(\"nn.relu\")(is_conv2d)\n    path2 = is_op(\"nn.leaky_relu\")(is_conv2d)\n    diamond = is_op(\"add\")(path1, path2)\n\n    # Expr\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n    out = out + conv2d\n    # Check\n    assert not diamond.match(out)\n\n\nclass BatchnormCallback(DFPatternCallback):\n    def __init__(self):\n        super(BatchnormCallback, self).__init__()\n        self.x = wildcard()\n        self.var = wildcard()\n        self.mean = wildcard()\n        self.beta = wildcard()\n        self.gamma = wildcard()\n        self.eps = is_constant()\n\n        self.pattern = (\n            self.gamma * (self.x - self.mean) / is_op(\"sqrt\")(self.var + self.eps) + self.beta\n        )\n\n    def callback(self, pre, post, node_map):\n        x = node_map[self.x][0]\n        var = node_map[self.var][0]\n        mean = node_map[self.mean][0]\n        beta = node_map[self.beta][0]\n        gamma = node_map[self.gamma][0]\n        eps = node_map[self.eps][0]\n        return relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=eps.data.numpy().item())[0]\n\n\ndef test_fuse_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n\n    BN = gamma * (x - mean) / relay.op.sqrt(var + relay.const(1e-5)) + beta\n\n    out = rewrite(BatchnormCallback(), BN)\n    assert tvm.ir.structural_equal(\n        out, relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)[0]\n    )\n\n\ndef test_no_fuse_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n\n    fake_BN = gamma * (x - mean) / relay.op.sqrt(var + relay.const(1e-5)) - beta\n\n    out = rewrite(BatchnormCallback(), fake_BN)\n    assert tvm.ir.structural_equal(out, fake_BN)\n\n\ndef test_fuse_double_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n\n    BN = gamma * (x - mean) / relay.op.sqrt(var + relay.const(1e-5)) + beta\n    BN2 = gamma * (BN - mean) / relay.op.sqrt(var + relay.const(1e-5)) + beta\n\n    out = rewrite(BatchnormCallback(), BN2)\n\n    bn = relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)[0]\n    bn2 = relay.op.nn.batch_norm(bn, gamma, beta, mean, var, epsilon=1e-5)[0]\n\n    assert tvm.ir.structural_equal(out, bn2)\n\n\ndef test_partial_fuse_double_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n\n    BN = gamma * (x - mean) / relay.op.sqrt(var + relay.const(1e-5)) - beta\n    BN2 = gamma * (BN - mean) / relay.op.sqrt(var + relay.const(1e-5)) + beta\n\n    out = rewrite(BatchnormCallback(), BN2)\n\n    bn2 = relay.op.nn.batch_norm(BN, gamma, beta, mean, var, epsilon=1e-5)[0]\n\n    assert tvm.ir.structural_equal(out, bn2)\n\n\ndef test_fuse_batchnorm_commutation():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n\n    # commute add\n    BN = beta + gamma * (x - mean) / relay.op.sqrt(var + relay.const(1e-5))\n    out = rewrite(BatchnormCallback(), BN)\n    assert tvm.ir.structural_equal(\n        out, relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)[0]\n    )\n\n    # associate divide/multiply\n    BN = (gamma * (x - mean)) / relay.op.sqrt(var + relay.const(1e-5)) + beta\n    out = rewrite(BatchnormCallback(), BN)\n    assert tvm.ir.structural_equal(\n        out, relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)[0]\n    )\n\n    # associate multiply/divide\n    BN = gamma * ((x - mean) / relay.op.sqrt(var + relay.const(1e-5))) + beta\n    out = rewrite(BatchnormCallback(), BN)\n    assert tvm.ir.structural_equal(\n        out, relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)[0]\n    )\n\n\ndef test_quadruple_rewrite_dominator():\n    class DominatorRemovalCallback(DFPatternCallback):\n        def __init__(self):\n            super(DominatorRemovalCallback, self).__init__()\n            self.inp = wildcard()\n            self.weight = wildcard()\n            is_conv2d = is_op(\"nn.conv2d\")(self.inp, self.weight)\n            is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(\n                wildcard()\n            ) | is_op(\"add\")(wildcard(), wildcard())\n            reduction = is_op(\"add\")(wildcard(), wildcard())\n            self.pattern = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n        def callback(self, pre, post, node_map):\n            inp = node_map[self.inp][0]\n            weight = node_map[self.weight][0]\n            return relay.op.nn.conv2d(inp, weight)\n\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n    # Classic Diamond\n    conv2d = relay.op.nn.conv2d(inp, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Deeper Branch\n    conv2d = relay.op.nn.conv2d(out, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    relu = relay.op.tanh(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = relu + leaky_relu\n\n    # Single Branch\n    conv2d = relay.op.nn.conv2d(out, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relay.op.nn.relu(relu)\n    tanh = relay.op.tanh(relu)\n    out = relu + tanh\n\n    # Fuzzy path/nested Diamond\n    conv2d = relay.op.nn.conv2d(out, weight)\n    relu = relay.op.nn.relu(conv2d)\n    relu = relu + relu\n    tanh = relay.op.tanh(relu)\n    leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n    out = tanh + leaky_relu\n    one = relay.op.nn.conv2d(inp, weight)\n    two = relay.op.nn.conv2d(one, weight)\n    three = relay.op.nn.conv2d(two, weight)\n    four = relay.op.nn.conv2d(three, weight)\n\n    assert tvm.ir.structural_equal(DominatorRemovalCallback().rewrite(out), four)\n\n\ndef algebraic_simplify(expr):\n    zero = is_expr(relay.const(0)) | is_expr(relay.const(0.0))\n    one = is_expr(relay.const(1)) | is_expr(relay.const(1.0))\n\n    class ElwiseNullCallback(DFPatternCallback):\n        def callback(self, pre, post, node_map):\n            return node_map[self.x][0]  # pylint: disable=no-member\n\n    class AddCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(AddCallback, self).__init__()\n            self.x = wildcard()\n            self.pattern = self.x + zero\n\n    class SubCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(SubCallback, self).__init__()\n            self.x = wildcard()\n            self.pattern = self.x - zero\n\n    class MulCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(MulCallback, self).__init__()\n            self.x = wildcard()\n            self.pattern = self.x * one\n\n    class DivCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(DivCallback, self).__init__()\n            self.x = wildcard()\n            self.pattern = self.x / one\n\n    class MulZeroCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(MulZeroCallback, self).__init__()\n            self.x = zero\n            self.pattern = self.x * wildcard()\n\n    class ZeroDivCallback(ElwiseNullCallback):\n        def __init__(self):\n            super(ZeroDivCallback, self).__init__()\n            self.x = zero\n            self.pattern = self.x / wildcard()\n\n    return rewrite(\n        [\n            AddCallback(),\n            SubCallback(),\n            MulCallback(),\n            DivCallback(),\n            MulZeroCallback(),\n            ZeroDivCallback(),\n        ],\n        expr,\n    )\n\n\ndef test_algebraic_simplify():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n\n    one = relay.const(1)\n    zero = relay.const(0)\n    onef = relay.const(1.0)\n    zerof = relay.const(0.0)\n\n    assert algebraic_simplify(x + zero) == x\n    assert algebraic_simplify(x + zerof) == x\n    assert algebraic_simplify(zero + x) == x\n    assert algebraic_simplify(zerof + x) == x\n\n    assert algebraic_simplify(x - zero) == x\n    assert algebraic_simplify(x - zerof) == x\n\n    assert algebraic_simplify(x * one) == x\n    assert algebraic_simplify(x * onef) == x\n    assert algebraic_simplify(one * x) == x\n    assert algebraic_simplify(onef * x) == x\n    assert algebraic_simplify(x * zero) == zero\n    assert algebraic_simplify(x * zerof) == zerof\n\n    assert algebraic_simplify(x / one) == x\n    assert algebraic_simplify(x / onef) == x\n    assert algebraic_simplify(zero / x) == zero\n    assert algebraic_simplify(zerof / x) == zerof\n\n    assert tvm.ir.structural_equal(\n        algebraic_simplify((x + zero * y) / one + (y * one) - zero / x), x + y\n    )\n\n\ndef test_double_partition():\n    # Pattern 1\n    conv2d_p = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    bias_add_p = is_op(\"nn.bias_add\")(conv2d_p, wildcard())\n    relu_p = is_op(\"nn.relu\")(bias_add_p)\n\n    # Graph\n    x = relay.var(\"input\")\n    w = relay.var(\"weight\")\n    b = relay.var(\"bias\")\n    w2 = relay.var(\"weight\")\n    b2 = relay.var(\"bias\")\n    conv2d = relay.op.nn.conv2d(x, w)\n    bias_add = relay.op.nn.bias_add(conv2d, b)\n    relu = relay.op.nn.relu(bias_add)\n    conv2d2 = relay.op.nn.conv2d(relu, w2)\n    bias_add2 = relay.op.nn.bias_add(conv2d2, b2)\n\n    partitioned = bias_add2\n    for pat, label in [(relu_p, \"conv_bias_relu\"), (bias_add_p, \"conv_bias\")]:\n        partitioned = pat.partition(partitioned, {\"Composite\": label})\n\n    inpf = relay.var(\"input\")\n    weightf = relay.var(\"weight\")\n    biasf = relay.var(\"bias\")\n    func0 = (\n        relay.Function(\n            [inpf, weightf, biasf],\n            relay.op.nn.relu(relay.op.nn.bias_add(relay.op.nn.conv2d(inpf, weightf), biasf)),\n        )\n        .with_attr(\"Composite\", \"conv_bias_relu\")\n        .with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\")\n    )\n    inpf = relay.var(\"input\")\n    weightf = relay.var(\"weight\")\n    biasf = relay.var(\"bias\")\n    func1 = (\n        relay.Function(\n            [inpf, weightf, biasf], relay.op.nn.bias_add(relay.op.nn.conv2d(inpf, weightf), biasf)\n        )\n        .with_attr(\"Composite\", \"conv_bias\")\n        .with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_\")\n    )\n\n    expected = func1(func0(x, w, b), w2, b2)\n    assert tvm.ir.structural_equal(partitioned, expected)\n\n\ndef test_partition_dominator():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard())\n    reduction = is_op(\"add\")(wildcard(), wildcard())\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    # Classic Diamond\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n\n    def generate_diamond(inp, weight):\n        conv2d = relay.op.nn.conv2d(inp, weight)\n        relu = relay.op.nn.relu(conv2d)\n        relu = relay.op.nn.relu(relu)\n        leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n        return relu + leaky_relu\n\n    out = generate_diamond(inp * inp, weight * weight)\n    # Check\n    partitioned = diamond.partition(out)\n\n    i = relay.Var(\"input\")\n    w = relay.Var(\"weight\")\n    f = relay.Function([i, w], generate_diamond(i, w)).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_nn.relu_nn.relu_nn.leaky_relu_add_\"\n    )\n    assert tvm.ir.structural_equal(partitioned, f(inp * inp, weight * weight))\n\n\ndef test_quadruple_partition_dominator():\n    # Pattern\n    is_conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    is_unary_elemwise = (wildcard().has_attr({\"TOpPattern\": K_ELEMWISE}))(wildcard()) | is_op(\n        \"add\"\n    )(wildcard(), wildcard())\n    reduction = is_op(\"add\")(wildcard(), wildcard())\n    diamond = dominates(is_conv2d, is_unary_elemwise, reduction)\n\n    inp = relay.var(\"input\")\n    weight = relay.var(\"weight\")\n\n    # Classic Diamond\n    def classic_diamond(inp, weight):\n        conv2d = relay.op.nn.conv2d(inp, weight)\n        relu = relay.op.nn.relu(conv2d)\n        relu = relay.op.nn.relu(relu)\n        leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n        return relu + leaky_relu\n\n    # Deeper Branch\n    def deeper_diamond(inp, weight):\n        conv2d = relay.op.nn.conv2d(inp, weight)\n        relu = relay.op.nn.relu(conv2d)\n        relu = relay.op.nn.relu(relu)\n        relu = relay.op.tanh(relu)\n        leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n        return relu + leaky_relu\n\n    # Single Branch\n    def single_branch(inp, weight):\n        conv2d = relay.op.nn.conv2d(inp, weight)\n        relu = relay.op.nn.relu(conv2d)\n        relu = relay.op.nn.relu(relu)\n        tanh = relay.op.tanh(relu)\n        return relu + tanh\n\n    # Fuzzy path/nested Diamond\n    def nested_diamond(inp, weight):\n        conv2d = relay.op.nn.conv2d(inp, weight)\n        relu = relay.op.nn.relu(conv2d)\n        relu = relu + relu\n        tanh = relay.op.tanh(relu)\n        leaky_relu = relay.op.nn.leaky_relu(conv2d, alpha=0)\n        return tanh + leaky_relu\n\n    partitioned = diamond.partition(\n        nested_diamond(\n            single_branch(deeper_diamond(classic_diamond(inp, weight), weight), weight), weight\n        )\n    )\n\n    functions = []\n    partition_names = [\n        \"nn.conv2d_nn.relu_nn.relu_nn.leaky_relu_add_\",\n        \"nn.conv2d_nn.relu_nn.relu_tanh_nn.leaky_relu_add_\",\n        \"nn.conv2d_nn.relu_nn.relu_tanh_add_\",\n        \"nn.conv2d_nn.relu_add_tanh_nn.leaky_relu_add_\",\n    ]\n    for i, f in enumerate([classic_diamond, deeper_diamond, single_branch, nested_diamond]):\n        inpf = relay.var(\"input\")\n        weightf = relay.var(\"weight\")\n        functions.append(\n            relay.Function([inpf, weightf], f(inpf, weightf)).with_attr(\n                \"PartitionedFromPattern\", partition_names[i]\n            )\n        )\n\n    reference = functions[3](\n        functions[2](functions[1](functions[0](inp, weight), weight), weight), weight\n    )\n    assert tvm.ir.structural_equal(partitioned, reference)\n\n\ndef get_BN(x, var, mean, beta, gamma, eps):\n    return gamma * (x - mean) / relay.op.sqrt(var + eps) + beta\n\n\ndef test_partition_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n    eps = relay.const(1e-5)\n    BN = get_BN(x, var, mean, beta, gamma, eps)\n\n    xf = relay.var(\"xf\")\n    varf = relay.var(\"varf\")\n    meanf = relay.var(\"meanf\")\n    betaf = relay.var(\"betaf\")\n    gammaf = relay.var(\"gammaf\")\n    # Put the arguments in toplogological order for the reference\n    f = relay.Function(\n        [gammaf, xf, meanf, varf, betaf], get_BN(xf, varf, meanf, betaf, gammaf, eps)\n    ).with_attr(\"PartitionedFromPattern\", \"subtract_multiply_add_sqrt_divide_add_\")\n\n    partitioned = BatchnormCallback().pattern.partition(BN)\n    reference = f(gamma, x, mean, var, beta)\n    assert tvm.ir.structural_equal(partitioned, reference)\n\n\ndef test_partition_double_batchnorm():\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n    eps = relay.const(1e-5)\n\n    BN = gamma * (x - mean) / relay.op.sqrt(var + eps) + beta\n    BN2 = gamma * (BN - mean) / relay.op.sqrt(var + eps) + beta\n\n    xf = relay.var(\"xf\")\n    varf = relay.var(\"varf\")\n    meanf = relay.var(\"meanf\")\n    betaf = relay.var(\"betaf\")\n    gammaf = relay.var(\"gammaf\")\n    f1 = relay.Function(\n        [gammaf, xf, meanf, varf, betaf], get_BN(xf, varf, meanf, betaf, gammaf, eps)\n    ).with_attr(\"PartitionedFromPattern\", \"subtract_multiply_add_sqrt_divide_add_\")\n    # The partitioner doesn't replace duplicates, so we use two copies of the function\n    xf2 = relay.var(\"xf2\")\n    varf2 = relay.var(\"varf2\")\n    meanf2 = relay.var(\"meanf2\")\n    betaf2 = relay.var(\"betaf2\")\n    gammaf2 = relay.var(\"gammaf2\")\n    f2 = relay.Function(\n        [gammaf2, xf2, meanf2, varf2, betaf2], get_BN(xf2, varf2, meanf2, betaf2, gammaf2, eps)\n    ).with_attr(\"PartitionedFromPattern\", \"subtract_multiply_add_sqrt_divide_add_\")\n\n    partitioned = BatchnormCallback().pattern.partition(BN2)\n    reference = f2(gamma, f1(gamma, x, mean, var, beta), mean, var, beta)\n    assert tvm.ir.structural_equal(partitioned, reference)\n\n\ndef test_overlappting_partitions():\n    x = wildcard()\n    gamma = wildcard()\n    beta = wildcard()\n    moving_mean = wildcard()\n    moving_var = wildcard()\n    bn_node = is_op(\"nn.batch_norm\")(x, gamma, beta, moving_mean, moving_var)\n    tuple_get_item_node = TupleGetItemPattern(bn_node, 0)\n\n    x = relay.var(\"x\")\n    var = relay.var(\"var\")\n    mean = relay.var(\"mean\")\n    beta = relay.var(\"beta\")\n    gamma = relay.var(\"gamma\")\n    BN = relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)\n    T1 = BN[0]\n    T2 = BN[0]\n    add = T1 + T2\n\n    assert tuple_get_item_node.partition(add) == add\n\n\ndef test_partition_overused():\n    pattern = is_op(\"nn.relu\")(is_op(\"nn.conv2d\")(wildcard(), wildcard()))\n\n    x = relay.var(\"input\")\n    w = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n    out = relu + conv2d\n\n    assert pattern.partition(out) == out\n\n\ndef test_partition_fuzzy_tuple():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = x + y\n    tuple_pattern = is_tuple(None)\n    concat_pattern = is_op(\"concatenate\")(tuple_pattern)\n\n    xp = relay.var(\"xp\")\n    yp = relay.var(\"yp\")\n    zp = relay.var(\"zp\")\n\n    def create_func(args, body):\n        return relay.Function(args, body).with_attr(\"PartitionedFromPattern\", \"Tuple_concatenate_\")\n\n    def concat(*args):\n        return relay.op.concatenate(relay.expr.Tuple(args), axis=0)\n\n    one = concat_pattern.partition(concat(x))\n    assert tvm.ir.structural_equal(one, create_func([xp], concat(xp))(x))\n    two = concat_pattern.partition(concat(x, y))\n    assert tvm.ir.structural_equal(two, create_func([xp, yp], concat(xp, yp))(x, y))\n    three = concat_pattern.partition(concat(x, y, z))\n    assert tvm.ir.structural_equal(three, create_func([xp, yp, zp], concat(xp, yp, zp))(x, y, z))\n\n\ndef test_partition_fuzzy_function_args():\n    func_pattern = FunctionPattern(None, wildcard() + wildcard())(None) + wildcard()\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.var(\"z\")\n    b = relay.var(\"b\")\n    xp = relay.var(\"xp\")\n    yp = relay.var(\"yp\")\n    zp = relay.var(\"zp\")\n\n    def create_func(call):\n        N = len(call.op.params)\n        new_params = [relay.var(str(i)) for i in range(N + 1)]\n        label = \"add_FunctionCall_add_\"\n        if N == 3:\n            label = \"add_\" + label\n        return relay.Function(\n            new_params, relay.Call(call.op, (new_params[0:-1])) + new_params[-1]\n        ).with_attr(\"PartitionedFromPattern\", label)(*([x, y, z][0:N] + [b]))\n\n    f1 = relay.Function([xp], xp + xp)(x)\n    one = func_pattern.partition(f1 + b)\n    assert tvm.ir.structural_equal(one, create_func(f1))\n    f2 = relay.Function([xp, yp], xp + yp)(x, y)\n    two = func_pattern.partition(f2 + b)\n    assert tvm.ir.structural_equal(two, create_func(f2))\n    f3 = relay.Function([xp, yp, zp], xp + yp + zp)(x, y, z)\n    three = func_pattern.partition(f3 + b)\n    assert tvm.ir.structural_equal(three, create_func(f3))\n\n\ndef test_partition_check():\n    pattern = is_op(\"nn.relu\")(is_op(\"nn.conv2d\")(is_var(\"input\"), wildcard()))\n\n    def check(pre):\n        return pre.args[0].attrs.data_layout == \"NCHW\"\n\n    x = relay.var(\"input\")\n    w = relay.var(\"weight\")\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n\n    xf = relay.var(\"input\")\n    wf = relay.var(\"weight\")\n    conv2df = relay.op.nn.conv2d(xf, wf)\n    reluf = relay.op.nn.relu(conv2df)\n    func = relay.Function([xf, wf], reluf).with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.relu_\")\n\n    reference = func(x, w)\n    partitioned = pattern.partition(relu, check=check)\n    assert tvm.ir.structural_equal(partitioned, reference)\n\n    conv2d = relay.op.nn.conv2d(x, w, data_layout=\"NHWC\")\n    relu = relay.op.nn.relu(conv2d)\n    assert relu == pattern.partition(relu, check=check)\n\n\ndef test_partition_check_types():\n    pattern = is_op(\"nn.relu\")(is_op(\"nn.conv2d\")(wildcard(), wildcard()))\n\n    def check(pre):\n        conv = pre.args[0]\n        return (conv.attrs.data_layout == \"NCHW\") and bool(conv.checked_type.shape[0] == 1)\n\n    x = relay.var(\"input\", shape=(1, 10, 10, 10))\n    w = relay.var(\"weight\", shape=(10, 10, 3, 3))\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n    relu = run_opt_pass(relu, relay.transform.InferType())\n\n    partitioned = pattern.partition(relu, check=check)\n    assert partitioned.op.attrs[\"PartitionedFromPattern\"] == \"nn.conv2d_nn.relu_\"\n\n    conv2d = relay.op.nn.conv2d(x, w, data_layout=\"NHWC\")\n    relu = relay.op.nn.relu(conv2d)\n    relu = run_opt_pass(relu, relay.transform.InferType())\n    assert relu == pattern.partition(relu, check=check)\n\n    x = relay.var(\"input\", shape=(2, 10, 10, 10))\n    w = relay.var(\"weight\", shape=(10, 10, 3, 3))\n    conv2d = relay.op.nn.conv2d(x, w)\n    relu = relay.op.nn.relu(conv2d)\n    relu = run_opt_pass(relu, relay.transform.InferType())\n    assert relu == pattern.partition(relu, check=check)\n\n\ndef conv_bias_relu(x, w, b):\n    conv2d = relay.op.nn.conv2d(x, w)\n    bias_add = relay.op.nn.bias_add(conv2d, b)\n    relu = relay.op.nn.relu(bias_add)\n    return relu\n\n\ndef test_partition_option():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n\n    conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    bias = conv2d.optional(lambda x: is_op(\"nn.bias_add\")(x, wildcard()))\n    pattern1 = is_op(\"nn.relu\")(bias)\n\n    conv2d = is_op(\"nn.conv2d\")(wildcard(), wildcard())\n    bias = is_op(\"nn.bias_add\")(conv2d, wildcard())\n    pattern2 = bias.optional(lambda x: is_op(\"nn.relu\")(x))\n\n    relu = conv_bias_relu(x, w, b)\n\n    xf = relay.var(\"x\")\n    wf = relay.var(\"w\")\n    bf = relay.var(\"b\")\n    func = relay.Function([xf, wf, bf], conv_bias_relu(xf, wf, bf)).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\"\n    )\n\n    assert pattern1.match(relu)\n    assert tvm.ir.structural_equal(func(x, w, b), pattern1.partition(relu))\n\n    assert pattern2.match(relu)\n    assert tvm.ir.structural_equal(func(x, w, b), pattern2.partition(relu))\n\n\ndef test_partition_function():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n\n    x1 = relay.var(\"x1\")\n    w1 = relay.var(\"w1\")\n\n    wc_x = wildcard()\n    wc_w = wildcard()\n    wc_b = wildcard()\n    wc_x1 = wildcard()\n    wc_w1 = wildcard()\n\n    func_pattern = FunctionPattern([wc_x1, wc_w1], is_op(\"nn.conv2d\")(wc_x1, wc_w1))\n    pattern = func_pattern(wc_x, wc_w) + wc_b\n\n    func = relay.Function([x1, w1], relay.nn.conv2d(x1, w1))\n    expr = func(x, w) + b + b\n\n    x2 = relay.var(\"x2\")\n    w2 = relay.var(\"w2\")\n    b2 = relay.var(\"b2\")\n    func2 = relay.Function([x2, w2, b2], func(x2, w2) + b2).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_FunctionCall_add_\"\n    )\n    expr2 = func2(x, w, b) + b\n    assert tvm.ir.structural_equal(pattern.partition(expr), expr2)\n\n\ndef test_partition_optional_function():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n\n    x1 = relay.var(\"x1\")\n    w1 = relay.var(\"w1\")\n\n    wc_x = wildcard()\n    wc_w = wildcard()\n    wc_x1 = wildcard()\n    wc_w1 = wildcard()\n\n    func_pattern0 = FunctionPattern(\n        [wc_x1, wc_w1], is_op(\"sigmoid\")(is_op(\"nn.conv2d\")(wc_x1, wc_w1))\n    )\n    func_pattern1 = FunctionPattern(\n        [wc_x1, wc_w1], is_op(\"nn.relu\")(is_op(\"nn.conv2d\")(wc_x1, wc_w1))\n    )\n    pattern = func_pattern0(wc_x, wc_w) | func_pattern1(wc_x, wc_w)\n\n    func = relay.Function([x1, w1], relay.nn.relu(relay.nn.conv2d(x1, w1)))\n    expr = func(x, w) + b\n\n    x2 = relay.var(\"x2\")\n    w2 = relay.var(\"w2\")\n    func2 = relay.Function([x2, w2], func(x2, w2)).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_nn.relu_FunctionCall_\"\n    )\n    expr2 = func2(x, w) + b\n    assert tvm.ir.structural_equal(pattern.partition(expr), expr2)\n\n\ndef test_rewrite_function_with_fuzzy_body():\n    \"\"\"Allow Rewriting a function with a fuzzy body via dominator analysis\"\"\"\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n\n    x1 = relay.var(\"x1\")\n    w1 = relay.var(\"w1\")\n\n    wc_x = wildcard()\n    wc_w = wildcard()\n    wc_b = wildcard()\n    wc_x1 = wildcard()\n    wc_w1 = wildcard()\n\n    func_pattern = FunctionPattern([wc_x1, wc_w1], wildcard())\n    pattern = func_pattern(wc_x, wc_w) + wc_b\n\n    func = relay.Function([x1, w1], relay.nn.conv2d(x1, w1))\n    expr = func(x, w) + b + b\n\n    class TestRewrite(DFPatternCallback):\n        def __init__(self):\n            super(TestRewrite, self).__init__()\n            self.pattern = pattern\n\n        def callback(self, pre, post, node_map):\n            return x + w\n\n    out = rewrite(TestRewrite(), expr)\n    assert tvm.ir.structural_equal(out, x + w + b)\n\n\ndef test_partition_function_with_fuzzy_body():\n    \"\"\"\n    Allow Rewriting a function with a fuzzy body via dominator analysis\n    \"\"\"\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    b = relay.var(\"b\")\n\n    x1 = relay.var(\"x1\")\n    w1 = relay.var(\"w1\")\n\n    wc_x = wildcard()\n    wc_w = wildcard()\n    wc_b = wildcard()\n    wc_x1 = wildcard()\n    wc_w1 = wildcard()\n\n    func_pattern = FunctionPattern([wc_x1, wc_w1], wildcard())\n    pattern = func_pattern(wc_x, wc_w) + wc_b\n\n    func = relay.Function([x1, w1], relay.nn.conv2d(x1, w1))\n    expr = func(x, w) + b + b\n\n    x2 = relay.var(\"x2\")\n    w2 = relay.var(\"w2\")\n    b2 = relay.var(\"b2\")\n    func2 = relay.Function([x2, w2, b2], func(x2, w2) + b2).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_FunctionCall_add_\"\n    )\n    expr2 = func2(x, w, b) + b\n    assert tvm.ir.structural_equal(pattern.partition(expr), expr2)\n\n\ndef test_match_match():\n    add_pattern = is_op(\"add\")(wildcard(), wildcard())\n\n    class TestRewrite(DFPatternCallback):\n        def __init__(self):\n            super(TestRewrite, self).__init__()\n            self.pattern = add_pattern\n\n        def callback(self, pre, post, node_map):\n            return post.args[0] - post.args[1]\n\n    mod = tvm.IRModule({})\n    tvm.relay.prelude.Prelude(mod)\n    # Apply rewrite on IR including relay.Match\n    out = rewrite(TestRewrite(), mod[\"tensor_concatenate_int64\"])\n    assert tvm.ir.structural_equal(mod[\"tensor_concatenate_int64\"], out)\n\n\ndef test_partition_constant_embedding():\n    x = relay.var(\"x\")\n    w = relay.var(\"w\")\n    wc = relay.const(1)\n    b = relay.var(\"b\")\n\n    xf = relay.var(\"x\")\n    wf = relay.var(\"w\")\n    bf = relay.var(\"b\")\n    embeded_func = relay.Function([xf, bf], conv_bias_relu(xf, wc, bf)).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\"\n    )\n    xf = relay.var(\"x\")\n    wf = relay.var(\"w\")\n    bf = relay.var(\"b\")\n    lifted_func = relay.Function([xf, wf, bf], conv_bias_relu(xf, wf, bf)).with_attr(\n        \"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\"\n    )\n    relu = conv_bias_relu(x, w, b)\n    reluc = conv_bias_relu(x, wc, b)\n\n    # Check lifting of wildcard matches\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), wildcard()), wildcard())\n    )\n    assert tvm.ir.structural_equal(lifted_func(x, w, b), pattern.partition(relu))\n    assert tvm.ir.structural_equal(lifted_func(x, wc, b), pattern.partition(reluc))\n\n    # Check lifting of input matches\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), is_var()), wildcard())\n    )\n    assert tvm.ir.structural_equal(lifted_func(x, w, b), pattern.partition(relu))\n    assert tvm.ir.structural_equal(reluc, pattern.partition(reluc))  # Constants are not Inputs\n\n    # Check embedding of constant matches\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), is_constant()), wildcard())\n    )\n    assert tvm.ir.structural_equal(relu, pattern.partition(relu))\n    assert tvm.ir.structural_equal(embeded_func(x, b), pattern.partition(reluc))\n\n    # Check embedding of constant ExprPatterns\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), is_expr(wc)), wildcard())\n    )\n    assert tvm.ir.structural_equal(relu, pattern.partition(relu))\n    assert tvm.ir.structural_equal(embeded_func(x, b), pattern.partition(reluc))\n\n    # Check lifting/embedding of Alt matches\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), is_var() | is_constant()), wildcard())\n    )\n    assert tvm.ir.structural_equal(lifted_func(x, w, b), pattern.partition(relu))\n    assert tvm.ir.structural_equal(embeded_func(x, b), pattern.partition(reluc))\n\n    # Check lifting/embedding of Alt matches with the other ordering\n    pattern = is_op(\"nn.relu\")(\n        is_op(\"nn.bias_add\")(is_op(\"nn.conv2d\")(wildcard(), is_constant() | is_var()), wildcard())\n    )\n    assert tvm.ir.structural_equal(lifted_func(x, w, b), pattern.partition(relu))\n    assert tvm.ir.structural_equal(embeded_func(x, b), pattern.partition(reluc))\n\n\ndef test_rewrite_once():\n    # This class recursively removes the arguments to concat until there is nothing left to concatenate.\n    class ConcatRewriter(DFPatternCallback):\n        def __init__(self, rewrite_once):\n            super().__init__(rewrite_once=rewrite_once)\n            self.pattern = is_op(\"concatenate\")(None)\n\n        def callback(self, pre, post, node_map):\n            concat_args = post.args[0]\n            # Remove the last argument\n            new_args = [concat_args[i] for i in range(len(concat_args) - 1)]\n            if new_args:\n                return relay.op.concatenate(relay.expr.Tuple(new_args), axis=0)\n            else:\n                return concat_args\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.var(\"z\")\n    concat = relay.op.concatenate(relay.expr.Tuple([x, y, z]), axis=0)\n\n    # Let the rewriter run recursively\n    out = rewrite(ConcatRewriter(False), concat)\n    expected = relay.expr.Tuple([x])\n    assert tvm.ir.structural_equal(out, expected)\n\n    # Run the rewriter once\n    out = rewrite(ConcatRewriter(True), concat)\n    expected = relay.op.concatenate(relay.expr.Tuple([x, y]), axis=0)\n    assert tvm.ir.structural_equal(out, expected)\n\n\ndef test_matched_outside_but_dominated():\n    \"\"\"In this example the pattern matches the nn.conv2d/add/multiply flow. Even though the\n    add output is consumed by the sigmoid, the sigmoid itself is dominated by the multiply.\n    So partitioning can proceed, all be it with a duplication of the add.\"\"\"\n    in_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(16, 16, 32, 32), float16], %weight: Tensor[(32, 16, 3, 3), float16], %bias: Tensor[(32), float32]) -> Tensor[(16, 32, 32, 32), float32] {\n          %0 = layout_transform(%data, src_layout=\"NCHW\", dst_layout=\"NHWC\");\n          %1 = layout_transform(%weight, src_layout=\"OIHW\", dst_layout=\"OHWI\");\n          %2 = expand_dims(%bias, axis=1, num_newaxis=2);\n          %3 = expand_dims(%2, axis=0);\n          %4 = nn.conv2d(%0, %1, padding=[1, 1, 1, 1], channels=32, kernel_size=[3, 3], data_layout=\"NHWC\", kernel_layout=\"OHWI\", out_dtype=\"float32\");\n          %5 = layout_transform(%3, src_layout=\"NCHW\", dst_layout=\"NHWC\");\n          %6 = add(%4, %5);\n          %7 = sigmoid(%6);\n          %8 = multiply(%6, %7);\n          layout_transform(%8, src_layout=\"NHWC\", dst_layout=\"NCHW\")\n        }\n        \"\"\"\n    )\n    expected_mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data: Tensor[(16, 16, 32, 32), float16], %weight: Tensor[(32, 16, 3, 3), float16], %bias: Tensor[(32), float32]) -> Tensor[(16, 32, 32, 32), float32] {\n          %2 = expand_dims(%bias, axis=1, num_newaxis=2);\n          %3 = expand_dims(%2, axis=0);\n          %4 = layout_transform(%data, src_layout=\"NCHW\", dst_layout=\"NHWC\");\n          %5 = layout_transform(%weight, src_layout=\"OIHW\", dst_layout=\"OHWI\");\n          %6 = nn.conv2d(%4, %5, padding=[1, 1, 1, 1], channels=32, kernel_size=[3, 3], data_layout=\"NHWC\", kernel_layout=\"OHWI\", out_dtype=\"float32\");\n          %7 = layout_transform(%3, src_layout=\"NCHW\", dst_layout=\"NHWC\");\n          %8 = add(%6, %7);\n          %9 = sigmoid(%8);\n          %10 = fn (%FunctionVar_0_0, %FunctionVar_0_1, %FunctionVar_0_2, %FunctionVar_0_3, PartitionedFromPattern=\"nn.conv2d_add_multiply_\") {\n            %0 = nn.conv2d(%FunctionVar_0_0, %FunctionVar_0_1, padding=[1, 1, 1, 1], channels=32, kernel_size=[3, 3], data_layout=\"NHWC\", kernel_layout=\"OHWI\", out_dtype=\"float32\");\n            %1 = add(%0, %FunctionVar_0_2);\n            multiply(%1, %FunctionVar_0_3)\n          };\n          %11 = %10(%4, %5, %7, %9);\n          layout_transform(%11, src_layout=\"NHWC\", dst_layout=\"NCHW\")\n        }\n        \"\"\"\n    )\n    pattern = is_op(\"multiply\")(\n        is_op(\"add\")(is_op(\"nn.conv2d\")(wildcard(), wildcard()), wildcard()), wildcard()\n    )\n    actual_mod = tvm.IRModule.from_expr(pattern.partition(in_mod[\"main\"]))\n    actual_mod = relay.transform.InferType()(actual_mod)\n    tvm.ir.assert_structural_equal(actual_mod, expected_mod)\n\n\ndef test_partition_parallel_branch_with_same_input():\n    \"\"\"In this example, conv2d's two consumer(add and multiply) on two different branches are\n    merged into one partition, make sure that the partitioned function has no redundant parameters\"\"\"\n    # Pattern\n    path1 = is_op(\"multiply\")(wildcard(), wildcard())\n    path2 = is_op(\"add\")(wildcard(), wildcard())\n    pattern = is_op(\"add\")(path1, path2)\n\n    i = relay.Var(\"input\")\n    w = relay.Var(\"weight\")\n    l = relay.Var(\"left\")\n    r = relay.Var(\"right\")\n\n    conv2d = relay.op.nn.conv2d(i, w)\n    branch1 = relay.multiply(l, conv2d)\n    branch2 = relay.add(conv2d, r)\n    add = relay.add(branch1, branch2)\n\n    lf = relay.Var(\"leftf\")\n    mf = relay.Var(\"midf\")\n    rf = relay.Var(\"rightf\")\n    f = relay.Function([lf, mf, rf], (lf * mf) + (mf + rf)).with_attr(\n        \"PartitionedFromPattern\", \"multiply_add_add_\"\n    )\n\n    partitioned = pattern.partition(add)\n    reference = f(l, conv2d, r)\n    assert tvm.ir.structural_equal(partitioned, reference)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_debug.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.relay import var, const, create_executor\nfrom tvm.relay.op import debug\n\n\n_test_debug_hit = False\n\n\ndef test_debug():\n    global _test_debug_hit\n    x = var(\"x\", shape=(), dtype=\"int32\")\n    _test_debug_hit = False\n\n    def did_exec(x):\n        global _test_debug_hit\n        _test_debug_hit = True\n\n    prog = debug(x, debug_func=did_exec)\n    result = create_executor().evaluate(prog, {x: const(1, \"int32\")})\n    assert _test_debug_hit\n    assert result.numpy() == 1\n\n\ndef test_debug_with_expr():\n    global _test_debug_hit\n    _test_debug_hit = False\n    x = var(\"x\", shape=(), dtype=\"int32\")\n    _test_debug_hit = False\n\n    def did_exec(x):\n        global _test_debug_hit\n        _test_debug_hit = True\n\n    prog = debug(x + x * x, debug_func=did_exec)\n    result = create_executor().evaluate(prog, {x: const(2, \"int32\")})\n    assert _test_debug_hit\n    assert result.numpy() == 6\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nfrom tvm import TVMError\nfrom tvm.relay.backend import Executor\n\n\ndef test_create_executor():\n    executor = Executor(\"aot\")\n    assert executor.name == \"aot\"\n\n\ndef test_create_executor_with_options():\n    executor = Executor(\"aot\", {\"interface-api\": \"c\"})\n    assert executor.name == \"aot\"\n    assert executor[\"interface-api\"] == \"c\"\n\n\ndef test_create_executor_with_default():\n    executor = Executor(\"graph\")\n    assert not executor[\"link-params\"]\n\n\ndef test_attr_check():\n    executor = Executor(\"aot\", {\"interface-api\": \"c\"})\n    assert \"woof\" not in executor\n    assert \"interface-api\" in executor\n\n\ndef test_create_executor_not_found():\n    with pytest.raises(TVMError, match='Executor \"woof\" is not defined'):\n        Executor(\"woof\", {})\n\n\ndef test_create_executor_attr_not_found():\n    with pytest.raises(TVMError, match='Attribute \"woof\" is not available on this Executor'):\n        Executor(\"aot\", {\"woof\": \"bark\"})\n\n\ndef test_create_executor_attr_type_incorrect():\n    with pytest.raises(\n        TVMError,\n        match='Attribute \"interface-api\" should have type \"runtime.String\"'\n        ' but instead found \"IntImm\"',\n    ):\n        Executor(\"aot\", {\"interface-api\": True})\n\n\ndef test_list_executors():\n    assert \"aot\" in Executor.list_registered()\n\n\n@pytest.mark.parametrize(\"executor\", [Executor(\"aot\").name, \"aot\"])\ndef test_list_executor_options(executor):\n    aot_options = Executor.list_registered_options(executor)\n    assert \"interface-api\" in aot_options\n    assert aot_options[\"interface-api\"] == \"runtime.String\"\n\n\ndef test_list_executor_options_not_found():\n    with pytest.raises(TVMError, match='Executor \"woof\" is not defined'):\n        Executor.list_registered_options(\"woof\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_expr_functor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import ExprFunctor, ExprMutator, ExprVisitor\n\n\ndef check_visit(expr):\n    try:\n        ef = ExprFunctor()\n        ef.visit(expr)\n        assert False\n    except NotImplementedError:\n        pass\n\n    ev = ExprVisitor()\n    ev.visit(expr)\n\n    em = ExprMutator()\n    assert em.visit(expr)\n\n\ndef test_constant():\n    check_visit(relay.const(1.0))\n\n\ndef test_tuple():\n    t = relay.Tuple([relay.var(\"x\", shape=())])\n    check_visit(t)\n\n\ndef test_var():\n    v = relay.var(\"x\", shape=())\n    check_visit(v)\n\n\ndef test_global():\n    v = relay.GlobalVar(\"f\")\n    check_visit(v)\n\n\ndef test_function():\n    x = relay.var(\"x\", shape=())\n    y = relay.var(\"y\", shape=())\n    params = [x, y]\n    body = x + y\n    ret_type = relay.TensorType(())\n    type_params = []\n    attrs = None  # How to build?\n    f = relay.Function(params, body, ret_type, type_params, attrs)\n    check_visit(f)\n\n\ndef test_call():\n    x = relay.var(\"x\", shape=())\n    y = relay.var(\"y\", shape=())\n    call = relay.op.add(x, y)\n    check_visit(call)\n\n\ndef test_let():\n    x = relay.var(\"x\", shape=())\n    value = relay.const(2.0)\n    body = x + x\n    l = relay.Let(x, value, body)\n    check_visit(l)\n\n\ndef test_ite():\n    cond = relay.var(\"x\", shape=(), dtype=\"bool\")\n    ite = relay.If(cond, cond, cond)\n    check_visit(ite)\n\n\ndef test_get_item():\n    t = relay.Tuple([relay.var(\"x\", shape=())])\n    t = relay.TupleGetItem(t, 0)\n    check_visit(t)\n\n\ndef test_ref_create():\n    r = relay.expr.RefCreate(relay.const(1.0))\n    check_visit(r)\n\n\ndef test_ref_read():\n    ref = relay.expr.RefCreate(relay.const(1.0))\n    r = relay.expr.RefRead(ref)\n    check_visit(r)\n\n\ndef test_ref_write():\n    ref = relay.expr.RefCreate(relay.const(1.0))\n    r = relay.expr.RefWrite(ref, relay.const(2.0))\n    check_visit(r)\n\n\ndef test_memo():\n    expr = relay.const(1)\n    for _ in range(100):\n        expr = expr + expr\n    check_visit(expr)\n\n\ndef test_match():\n    p = relay.prelude.Prelude()\n    check_visit(p.mod[p.map])\n\n\ndef test_match_completeness():\n    p = relay.prelude.Prelude()\n    _, _, nil = p.mod.get_type(\"List\")\n    for completeness in [True, False]:\n        match_expr = relay.adt.Match(nil, [], complete=completeness)\n        result_expr = ExprMutator().visit(match_expr)\n        # ensure the mutator doesn't mangle the completeness flag\n        assert result_expr.complete == completeness\n\n\nif __name__ == \"__main__\":\n    test_constant()\n    test_tuple()\n    test_var()\n    test_global()\n    test_function()\n    test_call()\n    test_let()\n    test_ite()\n    test_ref_create()\n    test_ref_read()\n    test_ref_write()\n    test_memo()\n    test_match()\n    test_match_completeness()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_external_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for graph partitioning.\"\"\"\n\nimport sys\nfrom collections import OrderedDict\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay, runtime\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom utils.external_codegen import (\n    update_lib,\n    set_external_func_attr,\n    parametrize_external_codegen_checks,\n    parametrize_external_json_codegen_checks,\n    check_graph_executor_result,\n    check_vm_result,\n)\n\n\n@parametrize_external_codegen_checks\ndef test_multi_node_subgraph(check_result):\n    x = relay.var(\"x\", shape=(10, 10))\n    w0 = relay.var(\"w0\", shape=(10, 10))\n    w1 = relay.var(\"w1\", shape=(10, 10))\n    w2 = relay.var(\"w2\", shape=(10, 10))\n    w3 = relay.var(\"w3\", shape=(10, 10))\n    w4 = relay.var(\"w4\", shape=(10, 10))\n    w5 = relay.var(\"w5\", shape=(10, 10))\n    w6 = relay.var(\"w6\", shape=(10, 10))\n    w7 = relay.var(\"w7\", shape=(10, 10))\n\n    # subgraph0\n    x0 = relay.var(\"x0\", shape=(10, 10))\n    w00 = relay.var(\"w00\", shape=(10, 10))\n    w01 = relay.var(\"w01\", shape=(10, 10))\n    w02 = relay.var(\"w02\", shape=(10, 10))\n    z00 = relay.add(x0, w00)\n    p00 = relay.subtract(z00, w01)\n    q00 = relay.multiply(p00, w02)\n    subgraph0 = relay.Function([x0, w00, w01, w02], q00)\n    subgraph0 = set_external_func_attr(subgraph0, \"ccompiler\", \"ccompiler_0\")\n    call0 = relay.Call(subgraph0, [x, w0, w1, w2])\n\n    # subgraph1\n    x1 = relay.var(\"x1\", shape=(10, 10))\n    w10 = relay.var(\"w10\", shape=(10, 10))\n    w11 = relay.var(\"w11\", shape=(10, 10))\n    w12 = relay.var(\"w12\", shape=(10, 10))\n    z10 = relay.add(x1, w10)\n    p10 = relay.subtract(z10, w11)\n    q10 = relay.multiply(p10, w12)\n    subgraph1 = relay.Function([x1, w10, w11, w12], q10)\n    subgraph1 = set_external_func_attr(subgraph1, \"ccompiler\", \"ccompiler_1\")\n    call1 = relay.Call(subgraph1, [x, w3, w4, w5])\n\n    # Other parts on TVM\n    z2 = relay.add(x, w6)\n    q2 = relay.subtract(z2, w7)\n\n    r = relay.concatenate((call0, call1, q2), axis=0)\n    f = relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = relay.transform.InferType()(mod)\n\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    w_data = []\n    for _ in range(8):\n        w_data.append(np.random.rand(10, 10).astype(\"float32\"))\n\n    map_inputs = OrderedDict([(\"x\", x_data)] + [(\"w{}\".format(i), w_data[i]) for i in range(8)])\n    check_result(\n        mod,\n        map_inputs,\n        (30, 10),\n        np.concatenate(\n            (\n                ((x_data + w_data[0]) - w_data[1]) * w_data[2],\n                ((x_data + w_data[3]) - w_data[4]) * w_data[5],\n                x_data + w_data[6] - w_data[7],\n            ),\n            axis=0,\n        ),\n    )\n\n\n@parametrize_external_codegen_checks\ndef test_extern_gcc_single_op(check_result):\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n\n    x0 = relay.var(\"x0\", shape=(8, 8))\n    y0 = relay.var(\"y0\", shape=(8, 8))\n    z = x0 + y0\n    f = relay.Function([x0, y0], z)\n    f = set_external_func_attr(f, \"ccompiler\", \"ccompiler_0\")\n    call = relay.Call(f, [x, y])\n    mod = tvm.IRModule.from_expr(call)\n    x_data = np.random.rand(8, 8).astype(\"float32\")\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (8, 8), x_data + y_data)\n\n\n@parametrize_external_codegen_checks\ndef test_extern_gcc_single_op_int(check_result):\n    x = relay.var(\"x\", shape=(8, 8), dtype=\"int32\")\n    y = relay.var(\"y\", shape=(8, 8), dtype=\"int32\")\n\n    x0 = relay.var(\"x0\", shape=(8, 8), dtype=\"int32\")\n    y0 = relay.var(\"y0\", shape=(8, 8), dtype=\"int32\")\n    z = x0 + y0\n    f = relay.Function([x0, y0], z)\n    f = set_external_func_attr(f, \"ccompiler\", \"ccompiler_0\")\n    call = relay.Call(f, [x, y])\n    mod = tvm.IRModule.from_expr(call)\n    x_data = np.random.rand(8, 8).astype(\"int32\")\n    y_data = np.random.rand(8, 8).astype(\"int32\")\n\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (8, 8), x_data + y_data)\n\n\n@parametrize_external_codegen_checks\ndef test_extern_gcc(check_result):\n    x = relay.var(\"x\", shape=(2, 2))\n    y = relay.var(\"y\", shape=(2, 2))\n\n    # subgraph for mul\n    x0 = relay.var(\"x0\", shape=(2, 2))\n    y0 = relay.var(\"y0\", shape=(2, 2))\n    mul = x0 * y0\n    mul = relay.Function([x0, y0], mul)\n    mul = set_external_func_attr(mul, \"ccompiler\", \"ccompiler_2\")\n    call_mul = relay.Call(mul, [y, y])\n\n    # subgraph for add\n    x1 = relay.var(\"x1\", shape=(2, 2))\n    y1 = relay.var(\"y1\", shape=(2, 2))\n    add = x1 + y1\n    add = relay.Function([x1, y1], add)\n    add = set_external_func_attr(add, \"ccompiler\", \"ccompiler_1\")\n    call_add = relay.Call(add, [x, x])\n\n    # subgraph for sub\n    x2 = relay.var(\"x2\", shape=(2, 2))\n    y2 = relay.var(\"y2\", shape=(2, 2))\n    sub = x2 - y2\n    sub = relay.Function([x2, y2], sub)\n    sub = set_external_func_attr(sub, \"ccompiler\", \"ccompiler_0\")\n    call_sub = relay.Call(sub, [call_mul, call_add])\n    mod = tvm.IRModule.from_expr(call_sub)\n\n    x_data = np.random.rand(2, 2).astype(\"float32\")\n    y_data = np.random.rand(2, 2).astype(\"float32\")\n\n    inputs = OrderedDict(\n        [\n            (\"y\", y_data),\n            (\"x\", x_data),\n        ]\n    )\n\n    check_result(mod, inputs, (2, 2), (y_data * y_data) - (x_data + x_data))\n\n\n# TODO(mbs): The check_aot_executor_result does not support the list-of-targets, mostly because\n# tvm.testing.aot.compile_and_run requires the target to be a kind name string, and\n# tvm.testing.aot.compile_models requires a single Target object. However, code outside of\n# tvm.testing.aot is ready for this more general form.\n@pytest.mark.parametrize(\"check_result\", [check_graph_executor_result, check_vm_result])\ndef test_extern_gcc_with_target_instance(check_result):\n    shape = (8, 8)\n    dtype = \"int32\"\n\n    def make_mod():\n        x0 = relay.var(\"x0\", shape=shape, dtype=dtype)\n        y0 = relay.var(\"y0\", shape=shape, dtype=dtype)\n        z = x0 + y0\n        f = relay.Function([x0, y0], z)\n        f = set_external_func_attr(f, \"ccompiler\", \"ccompiler_0\")\n        x = relay.var(\"x\", shape=shape, dtype=dtype)\n        y = relay.var(\"y\", shape=shape, dtype=dtype)\n        call = relay.Call(f, [x, y])\n        return tvm.IRModule.from_expr(call)\n\n    host_target = tvm.target.Target(\"llvm\")\n    generic_target = tvm.target.Target(\"llvm\", host=host_target)\n    # The header attribute is just whitespace, so compilation is as usual.\n    good_extern_codegen_target = tvm.target.Target(\n        {\"kind\": \"ccompiler\", \"header\": \"// Good\"}, host=host_target\n    )\n    # The header attribute is ill-formed, so compilation is expected to fail.\n    bogus_extern_codegen_target = tvm.target.Target(\n        {\"kind\": \"ccompiler\", \"header\": \"Bogus\"}, host=host_target\n    )\n\n    mod = make_mod()\n\n    x_data = np.random.rand(*shape).astype(dtype)\n    y_data = np.random.rand(*shape).astype(dtype)\n    expected_result = x_data + y_data\n    inputs = {\"x\": x_data, \"y\": y_data}\n\n    check_result(\n        mod, inputs, shape, expected_result, target=[generic_target, good_extern_codegen_target]\n    )\n\n    with pytest.raises(RuntimeError):\n        check_result(\n            mod,\n            inputs,\n            shape,\n            expected_result,\n            target=[generic_target, bogus_extern_codegen_target],\n        )\n\n\n@pytest.mark.skipif(sys.platform == \"win32\", reason=\"Skip test on Windows for now\")\n@pytest.mark.parametrize(\"check_result\", [check_graph_executor_result, check_vm_result])\ndef test_extern_gcc_consts(check_result):\n    shape = (8, 8)\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=shape)\n    y0_data = np.random.uniform(0, 1, shape).astype(dtype)\n\n    x0 = relay.var(\"x0\", shape=shape)\n    y0_const = relay.const(y0_data, dtype)\n    z = x0 + y0_const\n    f = relay.Function([x0], z)\n    f = set_external_func_attr(f, \"ccompiler\", \"ccompiler_0\")\n    call = relay.Call(f, [x])\n    mod = tvm.IRModule.from_expr(call)\n\n    # Note that while the VMCompiler get_params() will return all 'parameters' from both\n    # TVM and external codegen compiled code, the GraphExecutor.get_params() will return only\n    # those from non-external modules. So in the following we'll test by execution rather than\n    # test by inspection.\n    x_data = np.random.rand(*shape).astype(dtype)\n    inputs = {\"x\": x_data}\n    expected_result = x_data + y0_data\n    check_result(mod, inputs, shape, expected_result, target=\"llvm\")\n\n\n@pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.dnnl\", True),\n    reason=\"skip because DNNL codegen is not available\",\n)\n@parametrize_external_json_codegen_checks\ndef test_extern_dnnl_padding(check_result):\n    dtype = \"float32\"\n    ishape = (1, 1, 99, 12)\n    w1shape = (54, 1, 3, 3)\n    data0 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    weight0 = relay.var(\"weight0\", shape=(w1shape), dtype=dtype)\n    out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), strides=(2, 2), padding=(1, 0, 1, 1))\n    f = relay.Function([data0, weight0], out)\n    ref_mod = tvm.IRModule()\n    ref_mod[\"main\"] = f\n\n    data1 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    weight1 = relay.var(\"weight0\", shape=(w1shape), dtype=dtype)\n    f = set_external_func_attr(f, \"dnnl\", \"dnnl_0\")\n    call = relay.Call(f, [data1, weight1])\n    mod = tvm.IRModule.from_expr(call)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(\n        i_data, w_data\n    )\n    check_result(\n        mod, {\"data0\": i_data, \"weight0\": w_data}, (1, 54, 50, 6), ref_res.numpy(), tol=1e-5\n    )\n\n\n@pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.dnnl\", True),\n    reason=\"skip because DNNL codegen is not available\",\n)\n@parametrize_external_json_codegen_checks\ndef test_extern_dnnl(check_result):\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 1, 3, 3)\n    data0 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    weight0 = relay.var(\"weight0\", shape=(w1shape), dtype=dtype)\n\n    data1 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    weight1 = relay.var(\"weight0\", shape=(w1shape), dtype=dtype)\n    weight2 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n    depthwise_conv2d_1 = relay.nn.conv2d(\n        data1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n    )\n    depthwise_conv2d_2 = relay.nn.conv2d(\n        depthwise_conv2d_1, weight2, kernel_size=(3, 3), padding=(1, 1), groups=32\n    )\n    out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n    f = relay.Function([data1, weight1, weight2], out)\n    ref_mod = tvm.IRModule()\n    ref_mod[\"main\"] = f\n\n    f = set_external_func_attr(f, \"dnnl\", \"dnnl_0\")\n    call = relay.Call(f, [data0, weight0, weight0])\n    mod = tvm.IRModule.from_expr(call)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(\n        i_data, w_data, w_data\n    )\n    check_result(\n        mod, {\"data0\": i_data, \"weight0\": w_data}, (1, 32, 14, 14), ref_res.numpy(), tol=1e-5\n    )\n\n\n@pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.dnnl\", True),\n    reason=\"skip because DNNL codegen is not available\",\n)\n@parametrize_external_json_codegen_checks\ndef test_extern_dnnl_const(check_result):\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 1, 3, 3)\n    data0 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    w_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n    data1 = relay.var(\"data0\", shape=(ishape), dtype=dtype)\n    weight1 = relay.const(w_data, dtype=dtype)\n    weight2 = relay.const(w_data, dtype=dtype)\n    depthwise_conv2d_1 = relay.nn.conv2d(\n        data1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n    )\n    depthwise_conv2d_2 = relay.nn.conv2d(\n        depthwise_conv2d_1, weight2, kernel_size=(3, 3), padding=(1, 1), groups=32\n    )\n    out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n    f = relay.Function([data1], out)\n    ref_mod = tvm.IRModule()\n    ref_mod[\"main\"] = f\n\n    f = set_external_func_attr(f, \"dnnl\", \"dnnl_0\")\n    call = relay.Call(f, [data0])\n    mod = tvm.IRModule.from_expr(call)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(i_data)\n    check_result(mod, {\"data0\": i_data}, (1, 32, 14, 14), ref_res.numpy(), tol=1e-5)\n\n\ndef test_load_params_with_constants_in_ext_codegen():\n    # After binding params and partitioning graph_module.get_params()\n    # might contain parameters that are not an graph executor input but\n    # for example constants in external function.\n    y_in = np.ones((1,)).astype(\"float32\")\n    params = {\"y\": y_in}\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=(1, 10))\n    y = relay.var(\"y\", shape=(1,))\n    xcb = compiler_begin(x, \"ccompiler\")\n    ycb = compiler_begin(y, \"ccompiler\")\n    z = relay.add(xcb, ycb)\n    zce = compiler_end(z, \"ccompiler\")\n    mod[\"main\"] = relay.Function([x, y], zce)\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = relay.transform.PartitionGraph()(mod)\n\n    graph_module = relay.build(mod, target=\"llvm\", params=params)\n    # Params will be stored in metadata module.\n    assert len(graph_module.get_params()) == 0\n    lib = update_lib(graph_module.get_lib())\n    rt_mod = tvm.contrib.graph_executor.create(graph_module.get_graph_json(), lib, tvm.cpu(0))\n    rt_mod.load_params(runtime.save_param_dict(graph_module.get_params()))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_bind.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" test bind function.\"\"\"\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import TVMError\n\n\ndef test_bind_params():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.add(x, y)\n    f = relay.Function([x, y], z)\n    fbinded = relay.bind(f, {x: relay.const(1, \"float32\")})\n    fexpected = relay.Function([y], relay.add(relay.const(1, \"float32\"), y))\n    assert tvm.ir.structural_equal(fbinded, fexpected)\n\n    zbinded = relay.bind(z, {y: x})\n    zexpected = relay.add(x, x)\n    assert tvm.ir.structural_equal(zbinded, zexpected)\n\n\ndef test_bind_duplicated_params():\n    a = relay.var(\"a\", shape=(1,))\n    aa = relay.var(\"a\", shape=(1,))\n    s = a + aa\n    func = relay.Function([a, aa], s)\n\n    with pytest.raises(TVMError):\n        relay.build_module.bind_params_by_name(func, {\"a\": [1.0]})\n\n\nif __name__ == \"__main__\":\n    test_bind_params()\n    test_bind_duplicated_params()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for module functionality.\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.prelude import Prelude\n\n\ndef constructor_list(p):\n    list_ctors = p.mod.get_type(\"List\")\n    optional_ctors = p.mod.get_type(\"Option\")\n    nat_ctors = p.mod.get_type(\"nat\")\n    rose_ctors = p.mod.get_type(\"Tree\")\n    return list_ctors[1:] + optional_ctors[1:] + nat_ctors[1:] + rose_ctors[1:]\n\n\ndef adt_list(p):\n    list_ctors = p.mod.get_type(\"List\")\n    optional_ctors = p.mod.get_type(\"Option\")\n    nat_ctors = p.mod.get_type(\"nat\")\n    rose_ctors = p.mod.get_type(\"Tree\")\n    return list_ctors[:1] + optional_ctors[:1] + nat_ctors[:1] + rose_ctors[:1]\n\n\ndef test_constructor_tag_round_trip():\n    mod1 = tvm.IRModule()\n    p1 = Prelude(mod1)\n    p1.mod.import_from_std(\"nat.rly\")\n\n    mod2 = tvm.IRModule()\n    p2 = Prelude(mod2)\n    p2.mod.import_from_std(\"nat.rly\")\n\n    # ensure hashes match across modules\n    ctors1 = constructor_list(p1)\n    ctors2 = constructor_list(p2)\n\n    for i in range(len(ctors1)):\n        tag = ctors1[i].tag\n        ctor = mod2.get_constructor(tag)\n        assert ctor == ctors2[i]\n        assert ctor.name_hint == ctors1[i].name_hint\n\n\ndef test_constructor_tag_differences():\n    # ensure that if we have the type data for a given ADT, the tags\n    # for the constructors of the *same ADT* are simple offsets from\n    # each other\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n\n    adts = adt_list(p)\n    for adt in adts:\n        data = mod[adt]\n        for i in range(len(data.constructors) - 1):\n            ctor1 = data.constructors[i]\n            ctor2 = data.constructors[i + 1]\n            assert ctor2.tag - ctor1.tag == 1\n            # make sure there is something present at the MSB\n            assert ctor1.tag - i != 0\n            assert ctor2.tag - (i + 1) != 0\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_nodes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" test ir\"\"\"\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.tir.expr import *\nfrom tvm.relay import op\nimport numpy as np\n\n\ndef check_json_roundtrip(node):\n    json_str = tvm.ir.save_json(node)\n    back = tvm.ir.load_json(json_str)\n    assert tvm.ir.structural_equal(back, node, map_free_vars=True)\n\n\n# Span\ndef test_span():\n    span = relay.Span(None, 1, 2, 3, 4)\n    assert span.source_name == None\n    assert span.line == 1\n    assert span.end_line == 2\n    assert span.column == 3\n    assert span.end_column == 4\n    assert span.same_as(span)\n    assert span == span\n    assert isinstance(span, relay.base.Span)\n    str(span)\n\n    # span is not a node so we can't use graph_equal\n    # to test the round trip\n    back = tvm.ir.load_json(tvm.ir.save_json(span))\n    assert back.source_name == span.source_name\n    assert back.line == span.line\n    assert back.end_line == span.end_line\n    assert back.column == span.column\n    assert back.end_column == span.end_column\n\n\ndef test_constant():\n    arr = tvm.nd.array(10)\n    const = relay.Constant(arr)\n    assert const.data == arr\n    assert const.span == None\n    str(const)\n    check_json_roundtrip(const)\n\n\ndef test_tuple():\n    fields = tvm.runtime.convert([])\n    tup = relay.Tuple(fields)\n    assert tup.fields == fields\n    assert tup.span == None\n    str(tup)\n    check_json_roundtrip(tup)\n\n\ndef test_local_var():\n    name_hint = \"s\"\n    lv = relay.Var(name_hint)\n    assert lv.name_hint == name_hint\n    assert lv.type_annotation is None\n    # assert lv.span == None todo(@jroesch): what do we do about spans\n    str(lv)\n    check_json_roundtrip(lv)\n\n    t1 = relay.ty.TensorType((), \"float\")\n    lv = relay.Var(name_hint, t1)\n    assert lv.name_hint == name_hint\n    assert lv.type_annotation == t1\n\n\ndef test_global_var():\n    name_hint = \"g\"\n    gv = relay.GlobalVar(name_hint)\n    gv.name_hint == name_hint\n    # assert lv.span == None todo(@jroesch): what do we do about spans\n    str(gv)\n    check_json_roundtrip(gv)\n\n\ndef test_function():\n    param_names = [\"a\", \"b\", \"c\", \"d\"]\n    params = tvm.runtime.convert([relay.Var(n) for n in param_names])\n    ret_type = relay.TupleType(tvm.runtime.convert([]))\n    body = relay.Tuple(tvm.runtime.convert([]))\n    type_params = tvm.runtime.convert([])\n    fn = relay.Function(params, body, ret_type, type_params)\n    fn = fn.with_attr(\"test_attribute\", \"value\")\n    fn = fn.with_attr(\"test_attribute1\", \"value1\")\n    assert fn.params == params\n    assert fn.body == body\n    assert fn.type_params == type_params\n    assert fn.span == None\n    assert fn.attrs[\"test_attribute\"] == \"value\"\n    assert fn.attrs[\"test_attribute1\"] == \"value1\"\n    str(fn)\n    check_json_roundtrip(fn)\n\n\ndef test_function_attrs():\n    param_names = [\"a\", \"b\", \"c\", \"d\"]\n    params = tvm.runtime.convert([relay.var(n, shape=(5, 2)) for n in param_names])\n    ret_type = relay.TupleType(tvm.runtime.convert([]))\n    body = relay.Tuple(tvm.runtime.convert([]))\n    type_params = tvm.runtime.convert([])\n    fn = relay.Function(params, body, ret_type, type_params)\n    model_params = {}\n    for param in params[:1]:\n        cty = param.type_annotation\n        tensor = np.random.rand(*[int(sh) for sh in cty.shape]).astype(cty.dtype)\n        model_params[param] = relay.Constant(tvm.nd.array(tensor))\n\n    fn = fn.with_attr(\"__params__\", model_params)\n\n    assert fn.params == params\n    assert fn.body == body\n    assert fn.type_params == type_params\n    assert fn.span == None\n    str(fn)\n    check_json_roundtrip(fn)\n    json_str = tvm.ir.save_json(fn)\n    fn_after = tvm.ir.load_json(json_str)\n    model_params_after = fn_after.attrs[\"__params__\"]\n    after_keys = [item[0] for item in model_params_after.items()]\n    for key1, key2 in zip(model_params, after_keys):\n        assert key1.name_hint == key2.name_hint\n        p1 = model_params[key1]\n        p2 = model_params_after[key2]\n        np.testing.assert_allclose(p1.data.numpy(), p2.data.numpy())\n\n\ndef test_call():\n    op = relay.Var(\"f\")\n    arg_names = [\"a\", \"b\", \"c\", \"d\"]\n    args = tvm.runtime.convert([relay.Var(n) for n in arg_names])\n    call = relay.Call(op, args, None, None)\n    assert call.op == op\n    assert call.args == args\n    assert call.span == None\n    str(call)\n    check_json_roundtrip(call)\n\n\ndef test_let():\n    lv = relay.Var(\"x\")\n    ty = None\n    arr = tvm.nd.array(10)\n    value = relay.Constant(arr)\n    # I would prefer that the order of arguments\n    # matches syntax let x: t = v in b\n    let = relay.Let(lv, value, lv)\n    assert let.var == lv\n    assert let.value == value\n    assert let.body == lv\n    assert let.span == None\n    str(let)\n    check_json_roundtrip(let)\n\n\ndef test_if():\n    cond = relay.Var(\"cond\")\n    left = relay.Var(\"left\")\n    right = relay.Var(\"right\")\n    ife = relay.If(cond, left, right)\n    assert ife.cond == cond\n    assert ife.true_branch == left\n    assert ife.false_branch == right\n    assert ife.span == None\n    str(ife)\n    check_json_roundtrip(ife)\n\n\ndef test_tuple_get_item():\n    tup = relay.Var(\"tuple\")\n    get = relay.TupleGetItem(tup, 1)\n    assert get.tuple_value == tup\n    assert get.index == 1\n    str(get)\n    check_json_roundtrip(get)\n\n\ndef test_op():\n    add = op.op.get(\"add\")\n    check_json_roundtrip(add)\n\n\ndef test_conv2d_attrs():\n    data = relay.var(\"data\", shape=(1, 3, 224, 224))\n    param = relay.var(\"param\", shape=(64, 3, 7, 7))\n    out = op.nn.conv2d(data, param, strides=(2, 2), padding=(3, 3), channels=64, kernel_size=(7, 7))\n    check_json_roundtrip(out)\n\n\n# Commented due to weird memory allocation issue\n# def test_large_grpah():\n# Test large graphs to avoid stack overflow in serialize/deserialize\n#    size = int(1e5)\n#    var = [relay.var(\"var_\" + str(i), shape=(2, 3)) for i in range(size)]\n#    body = var[-1]\n#    for i in range(size, 1, -1):\n#        body = relay.Let(var[i - 1], op.add(var[i - 2], var[i - 2]), body)\n#    func = relay.Function([var[0]], body)\n#    check_json_roundtrip(func)\n\n\nif __name__ == \"__main__\":\n    test_span()\n    test_constant()\n    test_tuple()\n    test_local_var()\n    test_global_var()\n    test_function()\n    test_function_attrs()\n    test_call()\n    test_let()\n    test_if()\n    test_tuple_get_item()\n    test_op()\n    test_conv2d_attrs()\n    # Commented due to weird memory allocation issue\n    # test_large_grpah()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\nfrom tvm.relay.op import op as _op\n\n\ndef test_op_attr():\n    log_op = relay.op.get(\"log\")\n\n    @tvm.ir.register_op_attr(\"exp\", \"ftest\")\n    def test(x):\n        return x + 1\n\n    assert log_op.num_inputs == 1\n    assert log_op.get_attr(\"ftest\") is None\n    assert relay.op.get(\"exp\").get_attr(\"ftest\")(1) == 2\n\n\ndef test_op_reset_attr():\n    \"\"\"Tests reset_attr functionality.\"\"\"\n\n    def add1(x):\n        return x + 1\n\n    def add2(x):\n        return x + 2\n\n    # Register fadd1 and fadd2 attributes.\n    tvm.ir.register_op_attr(\"exp\", \"fadd1\", add1)\n    tvm.ir.register_op_attr(\"log\", \"fadd1\", add1)\n    tvm.ir.register_op_attr(\"log\", \"fadd2\", add2)\n\n    # Reset log fadd1 attr.\n    log_op = relay.op.get(\"log\")\n    log_op.reset_attr(\"fadd1\")\n\n    # Check that fadd1 attr is resetted.\n    assert log_op.get_attr(\"fadd1\") is None\n\n    # Check that fadd1 attr of other ops are intact.\n    assert relay.op.get(\"exp\").get_attr(\"fadd1\")(1) == 2\n\n    # Check that other attrs of the log op are intact.\n    assert relay.op.get(\"log\").get_attr(\"fadd2\")(1) == 3\n\n\ndef test_op_temp_attr():\n    \"\"\"Tests reset_attr functionality.\"\"\"\n\n    def add1(x):\n        return x + 1\n\n    def add2(x):\n        return x + 2\n\n    # Set original attr value is add1.\n    tvm.ir.register_op_attr(\"sqrt\", \"ftest\", add1)\n\n    with TempOpAttr(\"sqrt\", \"ftest\", add2):\n        # Check that the attr value is updated to add2.\n        assert relay.op.get(\"sqrt\").get_attr(\"ftest\")(1) == 3\n\n    # Check that the attr value is recovered to add1.\n    assert relay.op.get(\"sqrt\").get_attr(\"ftest\")(1) == 2\n\n\ndef test_op_level1():\n    x = relay.Var(\"x\")\n\n    for op_name in [\"log\", \"exp\", \"sqrt\", \"rsqrt\", \"tanh\"]:\n        y = getattr(relay, op_name)(x)\n        assert y.op.name == op_name\n        assert y.op.support_level == 1\n        assert y.args[0] == x\n\n\ndef test_op_level3():\n    x = relay.Var(\"x\")\n\n    for op_name in [\"ceil\", \"floor\", \"trunc\", \"round\", \"abs\", \"negative\"]:\n        y = getattr(relay, op_name)(x)\n        assert y.op.name == op_name\n        assert y.op.support_level == 3\n        assert y.args[0] == x\n\n\ndef test_op_register():\n    \"\"\"Tests register_op functionality.\"\"\"\n    op_name = \"custom_op\"\n\n    _op.register(op_name, r\"code(Add two tensor with inner broadcasting.)code\")\n    _op.get(op_name).set_num_inputs(2)\n    _op.get(op_name).add_argument(\"data_0\", \"Tensor\", \"The input data tensor.\")\n    _op.get(op_name).add_argument(\"data_1\", \"Tensor\", \"The input data tensor.\")\n    # call default relation functions\n    _op.get(op_name).add_type_rel(\"Identity\")\n    _op.get(op_name).set_support_level(1)\n    _op.register_pattern(op_name, _op.OpPattern.ELEMWISE)\n    _op.register_stateful(op_name, False)\n\n    assert _op.get(op_name).name == op_name\n    assert _op.get(op_name).num_inputs == 2\n    assert _op.get(op_name).get_attr(\"TOpPattern\") == _op.OpPattern.ELEMWISE\n    assert _op.get(op_name).get_attr(\"TOpIsStateful\") == False\n\n\nif __name__ == \"__main__\":\n    test_op_attr()\n    test_op_reset_attr()\n    test_op_temp_attr()\n    test_op_level1()\n    test_op_level3()\n    test_op_register()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_parser.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nimport tvm.relay.testing\nfrom numpy import isclose\nfrom typing import Union\n\nSEMVER = '#[version = \"0.0.5\"]\\n'\n\nBINARY_OPS = {\n    \"*\": relay.multiply,\n    \"/\": relay.divide,\n    \"+\": relay.add,\n    \"-\": relay.subtract,\n    \"<\": relay.less,\n    \">\": relay.greater,\n    \"<=\": relay.less_equal,\n    \">=\": relay.greater_equal,\n    \"==\": relay.equal,\n    \"!=\": relay.not_equal,\n}\n\nTYPES = {\n    \"int8\",\n    \"int16\",\n    \"int32\",\n    \"int64\",\n    \"uint8\",\n    \"uint16\",\n    \"uint32\",\n    \"uint64\",\n    \"float16\",\n    \"float32\",\n    \"float64\",\n    \"bool\",\n    \"int8x4\",\n    \"uint1x4\",\n    \"float16x4\",\n}\n\nLIST_DEFN = \"\"\"\ntype List[A] {\n    Cons(A, List[A]),\n    Nil,\n}\n\"\"\"\n\n\ndef assert_graph_equal(lhs, rhs):\n    tvm.ir.assert_structural_equal(lhs, rhs, map_free_vars=True)\n\n\ndef graph_equal(lhs, rhs):\n    return tvm.ir.structural_equal(lhs, rhs, map_free_vars=True)\n\n\ndef roundtrip_expr(expr):\n    text = tvm.relay.Expr.astext(expr, show_meta_data=False)\n    x = tvm.parser.parse_expr(text)\n    assert_graph_equal(x, expr)\n\n\n# Testing Utilities for expressions.\ndef roundtrip(expr):\n    x = tvm.parser.fromtext(expr.astext())\n    assert_graph_equal(x, expr)\n\n\ndef parse_text(code):\n    expr = tvm.parser.parse_expr(code)\n    roundtrip_expr(expr)\n    return expr\n\n\ndef parses_as(code, expr):\n    # type: (str, relay.Expr) -> bool\n    parsed = parse_text(code)\n    result = graph_equal(parsed, expr)\n    return result\n\n\n# Testing Utilities for full modules.\ndef parse_module(code):\n    mod = tvm.parser.parse(SEMVER + code)\n    roundtrip(mod)\n    return mod\n\n\ndef assert_parses_as(code, expr):\n    parsed = parse_text(code)\n    assert_graph_equal(parsed, expr)\n\n\ndef assert_parse_module_as(code, mod):\n    mod = tvm.relay.transform.InferType()(mod)\n    parsed = parse_module(code)\n    assert_graph_equal(parsed, mod)\n\n\ndef get_scalar(x):\n    # type: (relay.Constant) -> (Union[float, int, bool])\n    return x.data.numpy().item()\n\n\nint32 = relay.scalar_type(\"int32\")\n\n_ = relay.Var(\"_\")\nX = relay.Var(\"x\")\nY = relay.Var(\"y\")\nX_ANNO = relay.Var(\"x\", int32)\nY_ANNO = relay.Var(\"y\", int32)\n\nUNIT = relay.Tuple([])\n\n\ndef test_comments():\n    assert_parses_as(\n        \"\"\"\n        // This is a line comment!\n        ()\n        \"\"\",\n        UNIT,\n    )\n\n    assert_parses_as(\n        \"\"\"\n        /* This is a block comment!\n            This is still a block comment!\n        */\n        ()\n        \"\"\",\n        UNIT,\n    )\n\n    assert_parses_as(\n        \"\"\"\n        /* This is a block comment!\n           /*Block comment is recursive!*/\n        */\n        ()\n        \"\"\",\n        UNIT,\n    )\n\n\ndef test_int_literal():\n    assert isinstance(parse_text(\"1\"), relay.Constant)\n    assert isinstance(parse_text(\"1\").data, tvm.nd.NDArray)\n\n    assert get_scalar(parse_text(\"1\")) == 1\n    assert get_scalar(parse_text(\"10\")) == 10\n    assert get_scalar(parse_text(\"0\")) == 0\n    assert get_scalar(parse_text(\"-100\")) == -100\n    assert get_scalar(parse_text(\"-05\")) == -5\n    assert get_scalar(parse_text(\"9223372036854775807\")) == 9223372036854775807\n\n    assert get_scalar(parse_text(\"-42i\")) == -42\n    assert get_scalar(parse_text(\"-42i16\")) == -42\n    assert get_scalar(parse_text(\"-42i32\")) == -42\n    assert get_scalar(parse_text(\"-42i64\")) == -42\n\n    assert_parses_as(\"-42i16\", relay.const(-42, \"int16\"))\n    assert_parses_as(\"-42i32\", relay.const(-42, \"int32\"))\n    assert_parses_as(\"-42i\", relay.const(-42, \"int32\"))\n    assert_parses_as(\"-42\", relay.const(-42, \"int32\"))\n    assert_parses_as(\"-42i64\", relay.const(-42, \"int64\"))\n    assert_parses_as(\"2147483647\", relay.const(2147483647, \"int32\"))\n    assert_parses_as(\"2147483648\", relay.const(2147483648, \"int64\"))\n\n    with pytest.raises(tvm.error.DiagnosticError):\n        # Unrepresentable\n        parse_text(\"2147483648i32\")\n    with pytest.raises(tvm.error.DiagnosticError):\n        # Unrepresentable\n        parse_text(\"32768i16\")\n\n\ndef test_float_literal():\n    assert get_scalar(parse_text(\"1.0f\")) == 1.0\n    assert isclose(get_scalar(parse_text(\"1.56667f\")), 1.56667)\n    assert get_scalar(parse_text(\"0.0f\")) == 0.0\n    assert get_scalar(parse_text(\"-10.0f\")) == -10.0\n\n    # scientific notation\n    assert isclose(get_scalar(parse_text(\"1e-1f\")), 1e-1)\n    assert get_scalar(parse_text(\"1e+1f\")) == 1e1\n    assert isclose(get_scalar(parse_text(\"1E-1f\")), 1e-1)\n    assert get_scalar(parse_text(\"1E+1f\")) == 1e1\n    assert isclose(get_scalar(parse_text(\"1.0e-1f\")), 1.0e-1)\n    assert get_scalar(parse_text(\"1.0e+1f\")) == 1.0e1\n    assert isclose(get_scalar(parse_text(\"1.0E-1f\")), 1.0e-1)\n    assert get_scalar(parse_text(\"1.0E+1f\")) == 1.0e1\n\n    assert get_scalar(parse_text(\"3f16\")) == 3.0\n    assert get_scalar(parse_text(\"3f32\")) == 3.0\n\n    assert_parses_as(\"3f16\", relay.const(3.0, \"float16\"))\n    assert_parses_as(\"3f32\", relay.const(3.0, \"float32\"))\n    assert_parses_as(\"3f\", relay.const(3.0, \"float32\"))\n    assert_parses_as(\"3f64\", relay.const(3.0, \"float64\"))\n\n    with pytest.raises(tvm.error.DiagnosticError):\n        # Unrepresentable\n        parse_text(\"3.40283e+38f32\")\n    with pytest.raises(tvm.error.DiagnosticError):\n        # Unrepresentable\n        parse_text(\"65505f16\")\n\n\ndef test_bool_literal():\n    assert get_scalar(parse_text(\"True\")) == True\n    assert get_scalar(parse_text(\"False\")) == False\n\n    assert_parses_as(\"True\", relay.const(True, \"bool\"))\n\n\ndef test_negative():\n    # need to handle parsing non-literal operations\n    # assert isinstance(parse_text(\"let %x = 1; -%x\").body, relay.Call)\n    assert get_scalar(parse_text(\"--10\")) == 10\n    assert get_scalar(parse_text(\"---10\")) == -10\n\n\ndef test_bin_op():\n    for bin_op in BINARY_OPS.keys():\n        assert_parses_as(\n            \"1 {} 1\".format(bin_op), BINARY_OPS.get(bin_op)(relay.const(1), relay.const(1))\n        )\n\n\ndef test_parens():\n    assert graph_equal(parse_text(\"1 * 1 + 1\"), parse_text(\"(1 * 1) + 1\"))\n    assert not graph_equal(parse_text(\"1 * 1 + 1\"), parse_text(\"1 * (1 + 1)\"))\n\n\ndef test_op_assoc():\n    assert graph_equal(parse_text(\"1 * 1 + 1 < 1 == 1\"), parse_text(\"(((1 * 1) + 1) < 1) == 1\"))\n    assert graph_equal(parse_text(\"1 == 1 < 1 + 1 * 1\"), parse_text(\"1 == (1 < (1 + (1 * 1)))\"))\n\n\ndef test_vars():\n    # var\n    var = parse_text(\"let %foo = (); %foo\")\n    assert isinstance(var.body, relay.Var)\n    assert var.body.name_hint == \"foo\"\n\n    # global var\n    global_var = parse_text(\"@foo\")\n    assert isinstance(global_var, relay.GlobalVar)\n    assert global_var.name_hint == \"foo\"\n\n    # operator id\n    op = parse_text(\"add\")\n    assert isinstance(op, tvm.ir.Op)\n    assert op.name == \"add\"\n\n    # operator id with prefix\n    op = parse_text(\"nn.global_avg_pool2d\")\n    assert isinstance(op, tvm.ir.Op)\n    assert op.name == \"nn.global_avg_pool2d\"\n\n\ndef test_meta_ref():\n    with pytest.raises(tvm.error.DiagnosticError):\n        meta_op = parse_text(\"meta[type_key][1337]\")\n        assert meta_op.attrs.node_type_key == \"type_key\"\n        assert meta_op.attrs.node_index == 1337\n\n\ndef test_let():\n    assert_parses_as(\"let %x = 1; ()\", relay.Let(X, relay.const(1), UNIT))\n\n    assert_parses_as(\n        \"\"\"\n        let %x = 1;\n        let %y = 2;\n        ()\n        \"\"\",\n        relay.Let(X, relay.const(1), relay.Let(Y, relay.const(2), UNIT)),\n    )\n\n\ndef test_seq():\n    assert_parses_as(\"(); ()\", relay.Let(_, UNIT, UNIT))\n\n    assert_parses_as(\"let %_ = 1; ()\", relay.Let(X, relay.const(1), UNIT))\n\n\ndef test_graph():\n    code = \"%0 = (); %1 = 1; (%0, %0, %1)\"\n    assert_parses_as(code, relay.Tuple([UNIT, UNIT, relay.const(1)]))\n\n\ndef test_graph_single():\n    assert_parses_as(\"%1 = (); %1\", relay.Tuple([]))\n\n\ndef test_let_global_var():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\"let @x = 1; ()\")\n\n\ndef test_let_op():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\"let x = 1; ()\")\n\n\ndef test_tuple():\n    assert_parses_as(\"()\", relay.Tuple([]))\n\n    assert_parses_as(\"(0,)\", relay.Tuple([relay.const(0)]))\n\n    assert_parses_as(\"(0, 1)\", relay.Tuple([relay.const(0), relay.const(1)]))\n\n    assert_parses_as(\"(0, 1, 2)\", relay.Tuple([relay.const(0), relay.const(1), relay.const(2)]))\n\n\ndef test_tuple_proj():\n    x = relay.var(\"x\", shape=())\n    assert_parses_as(\n        \"free_var %x: float32; %x((%x,).0, %x)\",\n        relay.Call(x, [relay.TupleGetItem(relay.Tuple([x]), 0), x]),\n    )\n\n\ndef test_func():\n    # 0 args\n    assert_parses_as(\"fn () { 0 }\", relay.Function([], relay.const(0), None, []))\n\n    # 1 arg\n    assert_parses_as(\"fn (%x) { %x }\", relay.Function([X], X, None, []))\n\n    # 2 args\n    assert_parses_as(\"fn (%x, %y) { %x + %y }\", relay.Function([X, Y], relay.add(X, Y), None, []))\n\n    # annotations\n    assert_parses_as(\"fn (%x: int32) -> int32 { %x }\", relay.Function([X_ANNO], X_ANNO, int32, []))\n\n    # Refactor the attribute syntax and printing.\n    #\n    # # attributes\n    # assert_parses_as(\n    #     \"fn (n=5) { () }\",\n    #     relay.Function([], UNIT, None, None, tvm.ir.make_node(\"DictAttrs\", n=relay.const(5)))\n    # )\n\n\n# TODO(@jmp): Crashes if %x isn't annnotated.\ndef test_defn():\n    id_defn = parse_module(\n        \"\"\"\n        def @id(%x: int32) -> int32 {\n            %x\n        }\n        \"\"\"\n    )\n    assert isinstance(id_defn, tvm.IRModule)\n\n\ndef test_recursive_call():\n    id_defn = parse_module(\n        \"\"\"\n        def @id(%x: int32) -> int32 {\n            @id(%x)\n        }\n        \"\"\"\n    )\n    assert isinstance(id_defn, tvm.IRModule)\n\n\ndef test_ifelse():\n    assert_parses_as(\n        \"\"\"\n        if (True) {\n            0\n        } else {\n            1\n        }\n        \"\"\",\n        relay.If(relay.const(True), relay.const(0), relay.const(1)),\n    )\n\n\ndef test_ifelse_scope():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\n            \"\"\"\n            if (True) {\n                let %x = ();\n                ()\n            } else {\n                %x\n            }\n            \"\"\"\n        )\n\n\ndef test_ref():\n    program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%x: float32) {\n        %0 = ref(%x);\n        ref_write(%0, 1f);\n        ref_read(%0)\n    }\n    \"\"\"\n    tvm.parser.parse(program)\n\n\ndef test_call():\n    # select right function to call: simple ident case\n    id_func = relay.Var(\"id\")\n    assert_parses_as(\n        \"\"\"\n        let %id = fn (%x) { %x };\n        10 * %id(10)\n        \"\"\",\n        relay.Let(\n            id_func,\n            relay.Function([X], X, None, []),\n            relay.multiply(relay.const(10), relay.Call(id_func, [relay.const(10)])),\n        ),\n    )\n\n    # 0 args\n    constant = relay.Var(\"constant\")\n    assert_parses_as(\n        \"\"\"\n        let %constant = fn () { 0 };\n        %constant()\n        \"\"\",\n        relay.Let(\n            constant,\n            relay.Function([], relay.const(0), None, []),\n            relay.Call(constant, [], None, None),\n        ),\n    )\n\n    # 1 arg\n    id_var = relay.Var(\"id\")\n    assert_parses_as(\n        \"\"\"\n        let %id = fn (%x) { %x };\n        %id(1)\n        \"\"\",\n        relay.Let(\n            id_var,\n            relay.Function([X], X, None, []),\n            relay.Call(id_var, [relay.const(1)], None, None),\n        ),\n    )\n\n    # 2 args\n    multiply = relay.Var(\"multiply\")\n    assert_parses_as(\n        \"\"\"\n        let %multiply = fn (%x, %y) { %x * %y };\n        %multiply(0, 0)\n        \"\"\",\n        relay.Let(\n            multiply,\n            relay.Function([X, Y], relay.multiply(X, Y), None, []),\n            relay.Call(multiply, [relay.const(0), relay.const(0)], None, None),\n        ),\n    )\n\n    # anonymous function\n    assert_parses_as(\n        \"\"\"\n        (fn (%x) { %x })(0)\n        \"\"\",\n        relay.Call(relay.Function([X], X, None, []), [relay.const(0)], None, None),\n    )\n\n    # curried function\n    curried_mult = relay.Var(\"curried_mult\")\n    assert_parses_as(\n        \"\"\"\n        let %curried_mult =\n            fn (%x) {\n            fn (%y) {\n                %x * %y\n            }\n            };\n            %curried_mult(0);\n            %curried_mult(0)(0)\n        \"\"\",\n        relay.Let(\n            curried_mult,\n            relay.Function([X], relay.Function([Y], relay.multiply(X, Y), None, []), None, []),\n            relay.Let(\n                _,\n                relay.Call(curried_mult, [relay.const(0)], None, None),\n                relay.Call(\n                    relay.Call(curried_mult, [relay.const(0)], None, None),\n                    [relay.const(0)],\n                    None,\n                    None,\n                ),\n            ),\n        ),\n    )\n\n    # op\n    assert_parses_as(\"abs(1)\", relay.Call(relay.op.get(\"abs\"), [relay.const(1)], None, None))\n\n\n# Types\n\n\ndef test_incomplete_type():\n    assert_parses_as(\"let %_ : _ = (); ()\", relay.Let(_, UNIT, UNIT))\n\n\ndef test_builtin_types():\n    for builtin_type in TYPES:\n        parse_text(\"let %_ : {} = (); ()\".format(builtin_type))\n\n\ndef test_tensor_type():\n    assert_parses_as(\n        \"let %_ : Tensor[(), float32] = (); ()\",\n        relay.Let(relay.Var(\"_\", relay.TensorType((), \"float32\")), UNIT, UNIT),\n    )\n\n    assert_parses_as(\n        \"let %_ : Tensor[(1), float32] = (); ()\",\n        relay.Let(relay.Var(\"_\", relay.TensorType((1,), \"float32\")), UNIT, UNIT),\n    )\n\n    assert_parses_as(\n        \"let %_ : Tensor[(1, 1), float32] = (); ()\",\n        relay.Let(relay.Var(\"_\", relay.TensorType((1, 1), \"float32\")), UNIT, UNIT),\n    )\n\n    assert_parses_as(\n        \"let %_ : Tensor[(?, 1), float32] = (); ()\",\n        relay.Let(relay.Var(\"_\", relay.TensorType((tvm.tir.Any(), 1), \"float32\")), UNIT, UNIT),\n    )\n\n\ndef test_function_type():\n    assert_parses_as(\n        \"\"\"\n        let %_: fn () -> int32 = fn () -> int32 { 0 }; ()\n        \"\"\",\n        relay.Let(\n            relay.Var(\"_\", relay.FuncType([], int32, [], [])),\n            relay.Function([], relay.const(0), int32, []),\n            UNIT,\n        ),\n    )\n\n    assert_parses_as(\n        \"\"\"\n        let %_: fn (int32) -> int32 = fn (%x: int32) -> int32 { 0 }; ()\n        \"\"\",\n        relay.Let(\n            relay.Var(\"_\", relay.FuncType([int32], int32, [], [])),\n            relay.Function([relay.Var(\"x\", int32)], relay.const(0), int32, []),\n            UNIT,\n        ),\n    )\n\n    assert_parses_as(\n        \"\"\"\n        let %_: fn (int32, int32) -> int32 = fn (%x: int32, %y: int32) -> int32 { 0 }; ()\n        \"\"\",\n        relay.Let(\n            relay.Var(\"_\", relay.FuncType([int32, int32], int32, [], [])),\n            relay.Function(\n                [relay.Var(\"x\", int32), relay.Var(\"y\", int32)], relay.const(0), int32, []\n            ),\n            UNIT,\n        ),\n    )\n\n\ndef test_tuple_type():\n    assert_parses_as(\n        \"\"\"\n        let %_: () = (); ()\n        \"\"\",\n        relay.Let(relay.Var(\"_\", relay.TupleType([])), UNIT, UNIT),\n    )\n\n    assert_parses_as(\n        \"\"\"\n        let %_: (int32,) = (0,); ()\n        \"\"\",\n        relay.Let(relay.Var(\"_\", relay.TupleType([int32])), relay.Tuple([relay.const(0)]), UNIT),\n    )\n\n    assert_parses_as(\n        \"\"\"\n        let %_: (int32, int32) = (0, 1); ()\n        \"\"\",\n        relay.Let(\n            relay.Var(\"_\", relay.TupleType([int32, int32])),\n            relay.Tuple([relay.const(0), relay.const(1)]),\n            UNIT,\n        ),\n    )\n\n\ndef test_adt_defn():\n    mod = tvm.IRModule()\n\n    glob_typ_var = relay.GlobalTypeVar(\"Ayy\")\n    prog = relay.TypeData(glob_typ_var, [], [relay.Constructor(\"Nil\", [], glob_typ_var)])\n    mod[glob_typ_var] = prog\n    assert_parse_module_as(\n        \"\"\"\n        type Ayy { Nil }\n        \"\"\",\n        mod,\n    )\n\n\ndef test_adt_any():\n    code = \"\"\"\n    type my_dtype {\n        my_cons(Tensor[(?, 1), uint16]),\n    }\n    \"\"\"\n    mod = parse_module(code)\n    items = mod.type_definitions.items()\n    global_type_var, type_data = items[0]\n    assert global_type_var.name_hint == \"my_dtype\"\n    ctors = type_data.constructors\n    assert len(ctors) == 1\n    my_cons = ctors[0]\n    assert my_cons.name_hint == \"my_cons\"\n    ty_shape = my_cons.inputs[0].shape\n    assert isinstance(ty_shape[0], tvm.tir.Any)\n    assert ty_shape[1] == 1\n\n\ndef test_empty_adt_defn():\n    mod = tvm.IRModule()\n\n    glob_typ_var = relay.GlobalTypeVar(\"Ayy\")\n    prog = relay.TypeData(glob_typ_var, [], [])\n    mod[glob_typ_var] = prog\n    assert_parse_module_as(\n        \"\"\"\n        type Ayy { }\n        \"\"\",\n        mod,\n    )\n\n\ndef test_multiple_cons_defn():\n    mod = tvm.IRModule()\n\n    list_var = relay.GlobalTypeVar(\"List\")\n    typ_var = relay.TypeVar(\"A\")\n    prog = relay.TypeData(\n        list_var,\n        [typ_var],\n        [\n            relay.Constructor(\"Cons\", [typ_var, list_var(typ_var)], list_var),\n            relay.Constructor(\"Nil\", [], list_var),\n        ],\n    )\n    mod[list_var] = prog\n    assert_parse_module_as(LIST_DEFN, mod)\n\n\ndef test_multiple_type_param_defn():\n    glob_typ_var = relay.GlobalTypeVar(\"Either\")\n    typ_var_a = relay.TypeVar(\"A\")\n    typ_var_b = relay.TypeVar(\"B\")\n    prog = relay.TypeData(\n        glob_typ_var,\n        [typ_var_a, typ_var_b],\n        [\n            relay.Constructor(\"Left\", [typ_var_a], glob_typ_var),\n            relay.Constructor(\"Right\", [typ_var_b], glob_typ_var),\n        ],\n    )\n    mod = tvm.IRModule()\n    mod[glob_typ_var] = prog\n    assert_parse_module_as(\n        \"\"\"\n        type Either[A, B] {\n          Left(A),\n          Right(B),\n        }\n        \"\"\",\n        mod,\n    )\n\n\ndef test_match():\n    # pair each match keyword with whether it specifies a complete match or not\n    match_keywords = [(\"match\", True), (\"match?\", False)]\n    for (match_keyword, is_complete) in match_keywords:\n        mod = tvm.IRModule()\n\n        list_var = relay.GlobalTypeVar(\"List\")\n        typ_var = relay.TypeVar(\"A\")\n        cons_constructor = relay.Constructor(\"Cons\", [typ_var, list_var(typ_var)], list_var)\n        nil_constructor = relay.Constructor(\"Nil\", [], list_var)\n        list_def = relay.TypeData(list_var, [typ_var], [cons_constructor, nil_constructor])\n        mod[list_var] = list_def\n\n        length_var = relay.GlobalVar(\"length\")\n        typ_var = relay.TypeVar(\"A\")\n        input_type = list_var(typ_var)\n        input_var = relay.Var(\"xs\", input_type)\n        rest_var = relay.Var(\"rest\")\n        cons_case = relay.Let(\n            relay.var(\"\", type_annotation=None),\n            UNIT,\n            relay.add(relay.const(1), relay.Call(length_var, [rest_var])),\n        )\n        body = relay.Match(\n            input_var,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(\n                        cons_constructor, [relay.PatternWildcard(), relay.PatternVar(rest_var)]\n                    ),\n                    cons_case,\n                ),\n                relay.Clause(relay.PatternConstructor(nil_constructor, []), relay.const(0)),\n            ],\n            complete=is_complete,\n        )\n        length_func = relay.Function([input_var], body, int32, [typ_var])\n        mod[length_var] = length_func\n\n        assert_parse_module_as(\n            \"\"\"\n            %s\n\n            def @length[A](%%xs: List[A]) -> int32 {\n              %s (%%xs) {\n                Cons(_, %%rest : List[A]) => {\n                  ();\n                  1 + @length(%%rest)\n                },\n                Nil => 0,\n              }\n            }\n            \"\"\"\n            % (LIST_DEFN, match_keyword),\n            mod,\n        )\n\n\ndef test_adt_cons_expr():\n    mod = tvm.IRModule()\n\n    list_var = relay.GlobalTypeVar(\"List\")\n    typ_var = relay.TypeVar(\"A\")\n    cons_constructor = relay.Constructor(\"Cons\", [typ_var, list_var(typ_var)], list_var)\n    nil_constructor = relay.Constructor(\"Nil\", [], list_var)\n    list_def = relay.TypeData(list_var, [typ_var], [cons_constructor, nil_constructor])\n    mod[list_var] = list_def\n\n    make_singleton_var = relay.GlobalVar(\"make_singleton\")\n    input_var = relay.Var(\"x\", int32)\n    make_singleton_func = relay.Function(\n        [input_var], cons_constructor(input_var, nil_constructor()), list_var(int32)\n    )\n    mod[make_singleton_var] = make_singleton_func\n\n    assert_parse_module_as(\n        \"\"\"\n        %s\n\n        def @make_singleton(%%x: int32) -> List[int32] {\n          Cons(%%x, Nil)\n        }\n        \"\"\"\n        % LIST_DEFN,\n        mod,\n    )\n\n\ndef test_duplicate_adt_defn():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_module(\n            \"\"\"\n            %s\n\n            type List[A] {\n            Cons(A, List[A]),\n            Nil,\n            }\n            \"\"\"\n            % LIST_DEFN\n        )\n\n\ndef test_duplicate_adt_cons():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\n            \"\"\"\n            type Ayy { Lmao }\n            type Haha { Lmao }\n            \"\"\"\n        )\n\n\ndef test_duplicate_adt_cons_defn():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\n            \"\"\"\n            type Ayy { Lmao }\n            type Lmao { Ayy }\n            \"\"\"\n        )\n\n\ndef test_duplicate_global_var():\n    with pytest.raises(tvm.error.DiagnosticError):\n        parse_text(\n            \"\"\"\n            def @id[A](%x: A) -> A { x }\n            def @id[A](%x: A) -> A { x }\n            \"\"\"\n        )\n\n\ndef test_extern_adt_defn():\n    mod = tvm.IRModule()\n\n    extern_var = relay.GlobalTypeVar(\"T\")\n    typ_var = relay.TypeVar(\"A\")\n    extern_def = relay.TypeData(extern_var, [typ_var], [])\n    mod[extern_var] = extern_def\n\n    assert_parse_module_as(\n        \"\"\"\n        extern type T[A]\n        \"\"\",\n        mod,\n    )\n\n\ndef test_import_grad():\n    mod = tvm.IRModule()\n    mod.import_from_std(\"gradient.rly\")\n\n\ndef test_mlp():\n    mod, _ = relay.testing.mlp.get_workload(1)\n    text = mod.astext()\n    parsed_mod = tvm.parser.parse(text)\n    tvm.ir.assert_structural_equal(mod, parsed_mod)\n\n\ndef inline_params(mod, params):\n    main_fn = mod[\"main\"]\n    str_to_var = {}\n    for param in main_fn.params:\n        str_to_var[param.name_hint] = param\n\n    bind_map = {}\n    for param in params:\n        bind_map[str_to_var[param]] = relay.const(params[param])\n\n    body = relay.bind(main_fn.body, bind_map)\n    main_fn = relay.Function(relay.analysis.free_vars(body), body)\n    mod._add(\"main\", main_fn, True)\n    return mod\n\n\ndef test_mlp_inlined_params():\n    mod, params = relay.testing.mlp.get_workload(1)\n    mod = inline_params(mod, params)\n    mod = relay.transform.InferType()(mod)\n    text = mod.astext()\n    parsed_mod = tvm.parser.parse(text)\n    tvm.ir.assert_structural_equal(mod, parsed_mod)\n\n\ndef test_tuple_return_value():\n    program = \"\"\"\n    type Box[T] {\n        constructor(T)\n    }\n\n    def @example() {\n        %0 = ();\n        %1 = constructor(%0);\n        %2 = constructor(0f);\n        (%1, %2,)\n    }\n    \"\"\"\n    parse_module(program)\n\n\ndef test_parse_if_in_binding():\n    program = \"\"\"\n    def @example(%b: bool) {\n        %0 = if (%b) {\n            1\n        } else {\n            0\n        };\n        %0\n    }\n    \"\"\"\n    parse_module(program)\n\n\ndef test_op_string_attr():\n    call = parse_text(\n        \"\"\"\n        free_var %x: Tensor[(1, 32, 32, 3), float32];\n        free_var %y: Tensor[(1, 1, 3, 3), float32];\n        nn.conv2d(%x, %y, data_layout=\"NHWC\", kernel_layout=\"HWIO\")\n        \"\"\"\n    )\n\n    assert isinstance(call.op, tvm.ir.Op)\n    assert call.op.name == \"nn.conv2d\"\n    assert call.attrs.data_layout == \"NHWC\"\n    assert call.attrs.kernel_layout == \"HWIO\"\n\n\ndef test_load_prelude():\n    mod = tvm.IRModule()\n    mod.import_from_std(\"prelude.rly\")\n    tvm.parser.parse(mod.astext())\n\n\ndef test_call_attrs():\n    def get_func(shape, dtype):\n        x0 = relay.var(\"data\", shape=shape, dtype=dtype)\n        w0 = relay.var(\"weight\", shape=shape, dtype=dtype)\n        a = relay.nn.dense(x0, w0)\n        b = relay.nn.relu(a)\n        d = relay.add(b, relay.const(1.0, dtype=dtype))\n        return relay.Function([x0, w0], d)\n\n    # build relay graph\n    shape = (2, 4)\n    dtype = \"float32\"\n    sub_func = get_func(shape, dtype)\n    p0 = relay.var(\"p0\", shape=shape, dtype=dtype)\n    p1 = relay.var(\"p1\", shape=shape, dtype=dtype)\n    attr = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"func_call_attrs\")\n    call = relay.Call(sub_func, [p0, p1], attrs=attr)\n    func = relay.Function([p0, p1], call)\n\n    # build relay module\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    mod = tvm.relay.transform.InferType()(mod)\n\n    # assert equal\n    program = \"\"\"\n    def @main(%p0: Tensor[(2, 4), float32], %p1: Tensor[(2, 4), float32]) {\n    %2 = fn (%data: Tensor[(2, 4), float32], %weight: Tensor[(2, 4), float32]) {\n        %0 = nn.dense(%data, %weight, units=None);\n        %1 = nn.relu(%0);\n        add(%1, 1f)\n    };\n    %2(%p0, %p1, name=\"func_call_attrs\", attrs_type_key=\"attrs.TestAttrs\")\n    }\n    \"\"\"\n    parsed = parse_module(program)\n    assert_graph_equal(parsed, mod)\n\n\ndef test_tokenize_inf():\n    x = relay.var(\"x\", shape=(3, 4), dtype=\"float32\")\n    y = relay.clip(x, -np.inf, np.inf)\n\n    f = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(f)\n\n    mod = relay.transform.AnnotateSpans()(mod)\n\n\ndef test_func_attrs():\n    attrs = tvm.ir.make_node(\"DictAttrs\", **{\"Primitive\": 1, \"relay.reshape_only\": 1})\n    x = relay.var(\"x\", shape=(2, 3))\n    func = relay.Function([x], relay.reshape(x, (-1,)), attrs=attrs)\n    assert_parses_as(func.astext(), func)\n\n\ndef test_init_module_and_metatable():\n    init_metatable = {\"relay.Constant\": [relay.const(np.random.rand(2, 3), dtype=\"float32\")]}\n    init_module = tvm.parser.fromtext(\n        SEMVER\n        + \"\"\"\n            def @f(%y : Tensor[(2, 3), float32]) -> Tensor[(2, 3), float32] {\n              negative(%y)\n            }\n        \"\"\",\n    )\n    mod = tvm.parser.parse(\n        SEMVER\n        + \"\"\"\n            def @main(%x: Tensor[(2, 3), float32]) {\n              add(@f(%x), meta[relay.Constant][0])\n            }\n        \"\"\",\n        \"from_string\",\n        init_module,\n        init_metatable,\n    )\n    roundtrip(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_structural_equal_hash.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.testing import run_opt_pass\n\n\ndef consistent_equal(x, y, map_free_vars=False):\n    struct_equal0 = tvm.ir.structural_equal(x, y, map_free_vars)\n    struct_equal1 = tvm.ir.structural_equal(y, x, map_free_vars)\n\n    xhash = tvm.ir.structural_hash(x, map_free_vars)\n    yhash = tvm.ir.structural_hash(y, map_free_vars)\n\n    if struct_equal0 != struct_equal1:\n        raise ValueError(\n            \"Non-communicative {} vs {}, sequal0={}, sequal1={}\".format(\n                x, y, struct_equal0, struct_equal1\n            )\n        )\n\n    # NOTE: hash colision can happen but should be rare.\n    # we can confirm that hash colison doesn't happen for our testcases\n    if struct_equal0 != (xhash == yhash):\n        raise ValueError(\n            \"Inconsistent {} vs {}, sequal={}, xhash={}, yhash={}\".format(\n                x, y, struct_equal0, xhash, yhash\n            )\n        )\n    return struct_equal0\n\n\ndef test_tensor_type_sequal():\n    t1 = relay.TensorType((3, 4), \"float32\")\n    t2 = relay.TensorType((3, 4), \"float32\")\n    t3 = relay.TensorType((3, 4, 5), \"float32\")\n    assert t1 == t2\n    assert t1 != t3\n\n    t1 = relay.TensorType((), \"float32\")\n    t2 = relay.TensorType((), \"float32\")\n    assert t1 == t2\n\n\ndef test_incomplete_type_sequal():\n    t1 = relay.IncompleteType(relay.TypeKind.ShapeVar)\n    t2 = relay.IncompleteType(relay.TypeKind.Type)\n    t3 = relay.IncompleteType(relay.TypeKind.Type)\n\n    # only equal when there is pointer equality\n    assert t2 == t2\n    assert t1 == t1\n    assert t1 != t2\n    assert t2 != t3\n\n\ndef test_type_param_sequal():\n    t1 = relay.TypeVar(\"v1\", relay.TypeKind.Type)\n    t2 = relay.TypeVar(\"v2\", relay.TypeKind.ShapeVar)\n    t3 = relay.TypeVar(\"v3\", relay.TypeKind.Type)\n\n    # only pointer equality and eq_map allow equal params\n    assert t1 == t1\n    assert t2 == t2\n    assert t1 != t2  # different kind\n    assert t1 != t3  # not in eq_map\n\n    # function types are the only way to put type params\n    # in eq map\n    ft1 = relay.FuncType(\n        tvm.runtime.convert([]), t1, tvm.runtime.convert([t1]), tvm.runtime.convert([])\n    )\n    ft2 = relay.FuncType(\n        tvm.runtime.convert([]), t3, tvm.runtime.convert([t3]), tvm.runtime.convert([])\n    )\n    # actually an invalid type because t2 is wrong kind\n    ft3 = relay.FuncType(\n        tvm.runtime.convert([]), t2, tvm.runtime.convert([t2]), tvm.runtime.convert([])\n    )\n\n    assert ft1 == ft2\n    assert ft1 != ft3  # kinds still do not match\n\n\ndef test_func_type_sequal():\n    t1 = relay.TensorType((1, 2), \"float32\")\n    t2 = relay.TensorType((1, 2, 3), \"float32\")\n\n    tp1 = relay.TypeVar(\"v1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"v2\", relay.TypeKind.Type)\n    tp3 = relay.TypeVar(\"v3\", relay.TypeKind.ShapeVar)\n    tp4 = relay.TypeVar(\"v3\", relay.TypeKind.ShapeVar)\n\n    broadcast = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Broadcast\")\n    identity = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Identity\")\n\n    tr1 = relay.TypeRelation(broadcast, tvm.runtime.convert([tp1, tp3]), 1, None)\n    tr2 = relay.TypeRelation(broadcast, tvm.runtime.convert([tp2, tp4]), 1, None)\n    tr3 = relay.TypeRelation(identity, tvm.runtime.convert([tp1, tp3]), 1, None)\n\n    ft = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp1,\n        tvm.runtime.convert([tp1, tp3]),\n        tvm.runtime.convert([tr1]),\n    )\n    translate_vars = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp2,\n        tvm.runtime.convert([tp2, tp4]),\n        tvm.runtime.convert([tr2]),\n    )\n    assert ft == translate_vars\n\n    different_args = relay.FuncType(\n        tvm.runtime.convert([t1]), tp1, tvm.runtime.convert([tp1, tp3]), tvm.runtime.convert([tr1])\n    )\n    assert ft != different_args\n\n    different_order = relay.FuncType(\n        tvm.runtime.convert([t2, t1]),\n        tp1,\n        tvm.runtime.convert([tp1, tp3]),\n        tvm.runtime.convert([tr1]),\n    )\n    assert ft != different_order\n\n    no_rel = relay.FuncType(\n        tvm.runtime.convert([t1, t2]), tp1, tvm.runtime.convert([tp1, tp3]), tvm.runtime.convert([])\n    )\n    assert ft != no_rel\n\n    more_vars = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp2,\n        tvm.runtime.convert([tp1, tp2, tp3]),\n        tvm.runtime.convert([tr1]),\n    )\n    assert ft != more_vars\n\n    all_the_vars = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp1,\n        tvm.runtime.convert([tp1, tp2, tp3, tp4]),\n        tvm.runtime.convert([tr1, tr2]),\n    )\n    assert ft != all_the_vars\n\n    different_rel = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp1,\n        tvm.runtime.convert([tp1, tp3]),\n        tvm.runtime.convert([tr3]),\n    )\n    assert ft != different_rel\n\n    more_rels = relay.FuncType(\n        tvm.runtime.convert([t1, t2]),\n        tp1,\n        tvm.runtime.convert([tp1, tp3]),\n        tvm.runtime.convert([tr1, tr3]),\n    )\n    assert ft != more_rels\n\n\ndef test_tuple_type_sequal():\n    t1 = relay.TensorType((1, 2, 3), \"float32\")\n    t2 = relay.TensorType((1, 2, 3, 4), \"float32\")\n    tp1 = relay.TypeVar(\"v1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"v2\", relay.TypeKind.Type)\n\n    tup1 = relay.TupleType(tvm.runtime.convert([t1, t2, tp1]))\n    tup2 = relay.TupleType(tvm.runtime.convert([t1, t2, tp1]))\n    tup3 = relay.TupleType(tvm.runtime.convert([t2, t1, tp1]))\n    tup4 = relay.TupleType(tvm.runtime.convert([t1, t2, tp2]))\n\n    # as long as types are alpha-equal and in same order,\n    # tuples should be alpha-equal\n    assert tup1 == tup2\n    assert tup1 != tup3\n    assert tup1 != tup4\n\n\ndef test_type_relation_sequal():\n    t1 = relay.TensorType((1, 2), \"float32\")\n    t2 = relay.TensorType((1, 2, 3), \"float32\")\n    t3 = relay.TensorType((1, 2, 3, 4), \"float32\")\n\n    # functions are compared only by pointer equality so\n    # we need to be sure to use the same pointers\n    broadcast = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Broadcast\")\n    identity = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Identity\")\n\n    attr1 = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n    attr1_same = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n    attr2 = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4, 4))\n\n    tr = relay.TypeRelation(broadcast, tvm.runtime.convert([t1, t2]), 1, attr1)\n    same = relay.TypeRelation(broadcast, tvm.runtime.convert([t1, t2]), 1, attr1)\n    diff_func = relay.TypeRelation(identity, tvm.runtime.convert([t1, t2]), 1, attr1)\n    diff_order = relay.TypeRelation(broadcast, tvm.runtime.convert([t2, t1]), 1, attr1)\n    diff_args = relay.TypeRelation(broadcast, tvm.runtime.convert([t2, t3]), 1, attr1)\n    diff_attr = relay.TypeRelation(broadcast, tvm.runtime.convert([t1, t2]), 1, attr2)\n    same_attr = relay.TypeRelation(broadcast, tvm.runtime.convert([t1, t2]), 1, attr1_same)\n\n    bigger = relay.TypeRelation(identity, tvm.runtime.convert([t1, t3, t2]), 2, attr1)\n    diff_num_inputs = relay.TypeRelation(identity, tvm.runtime.convert([t1, t3, t2]), 1, attr2)\n\n    # func, number of args, input count, and order should be the same\n    assert tr == same\n    assert tr != diff_func\n    assert tr != diff_order\n    assert tr != diff_args\n    assert tr != diff_attr\n    assert tr == same_attr\n    assert tr != bigger\n\n    assert bigger != diff_num_inputs\n\n\ndef test_type_call_sequal():\n    h1 = relay.GlobalTypeVar(\"h1\")\n    h2 = relay.GlobalTypeVar(\"h2\")\n    t1 = relay.TensorType((1, 2), \"float32\")\n    t2 = relay.TensorType((1, 2, 3), \"float32\")\n    t3 = relay.TensorType((1, 2, 3, 4), \"float32\")\n    t4 = relay.TensorType((), \"float32\")\n\n    tc = relay.TypeCall(h1, [t1, t2, t3])\n    same = relay.TypeCall(h1, [t1, t2, t3])\n\n    different_func = relay.TypeCall(h2, [t1, t2, t3])\n    different_arg = relay.TypeCall(h1, [t1, t2, t4])\n    fewer_args = relay.TypeCall(h1, [t1, t2])\n    more_args = relay.TypeCall(h1, [t1, t2, t3, t4])\n    different_order_args = relay.TypeCall(h1, [t3, t2, t1])\n\n    assert tc == same\n    assert tc != different_func\n    assert tc != fewer_args\n    assert tc != more_args\n    assert tc != different_order_args\n\n\ndef test_constant_sequal():\n    x = relay.const(1)\n    y = relay.const(2)\n    assert consistent_equal(x, x)\n    assert not consistent_equal(x, y)\n    assert consistent_equal(x, relay.const(1))\n\n\ndef test_type_node_sequal():\n    v1 = relay.TypeVar(\"v1\", 6)\n    v2 = relay.TypeVar(\"v2\", 6)\n    assert not consistent_equal(v1, v2)\n\n    v1 = relay.TypeVar(\"v1\", 0)\n    v2 = relay.TypeVar(\"v2\", 6)\n    assert not consistent_equal(v1, v2)\n\n\ndef test_type_node_incompatible_sequal():\n    v1 = relay.TypeVar(\"v1\", 6)\n    v2 = relay.Var(\"v2\")\n    assert not consistent_equal(v1, v2)\n\n\ndef test_expr_node_incompatible_sequal():\n    v1 = relay.Var(\"v1\")\n    v2 = relay.PatternVar(relay.Var(\"v2\"))\n    assert not consistent_equal(v1, v2)\n\n\ndef test_var_sequal():\n    v1 = relay.Var(\"v1\")\n    v2 = relay.Var(\"v2\")\n\n    # normally only pointer equality\n    assert consistent_equal(v1, v1)\n    assert not consistent_equal(v1, v2)\n\n    # let node allows for setting the eq_map\n    l1 = relay.Let(v1, relay.const(1), v1)\n    l2 = relay.Let(v2, relay.const(1), v2)\n    l3 = relay.Let(v1, relay.const(1), v2)\n\n    assert consistent_equal(l1, l2)\n    assert not consistent_equal(l1, l3)\n\n    # type annotations\n    tt1 = relay.TensorType([], \"int32\")\n    tt2 = relay.TensorType([], \"int32\")\n    tt3 = relay.TensorType([], \"int64\")\n    v3 = relay.Var(\"v3\", tt1)\n    v4 = relay.Var(\"v4\", tt2)\n    v5 = relay.Var(\"v5\", tt3)\n\n    l4 = relay.Let(v3, relay.const(1), v3)\n    l5 = relay.Let(v4, relay.const(1), v4)\n    l6 = relay.Let(v5, relay.const(1), v5)\n\n    # same annotations\n    assert consistent_equal(l4, l5)\n    # different annotations\n    assert not consistent_equal(l4, l6)\n    # one null annotation\n    assert not consistent_equal(l1, l4)\n\n\ndef test_global_var_sequal():\n    v1 = relay.GlobalVar(\"v1\")\n    v2 = relay.GlobalVar(\"v2\")\n\n    # only pointer equality suffices (smoke test)\n    assert consistent_equal(v1, v1)\n    assert not consistent_equal(v1, v2)\n\n\ndef test_tuple_sequal():\n    v0 = relay.Var(\"v0\")\n    v1 = relay.Var(\"v1\")\n    v2 = relay.Var(\"v2\")\n\n    # unit value is a valid tuple\n    assert consistent_equal(relay.Tuple([]), relay.Tuple([]))\n\n    tup = relay.Tuple([v0, relay.const(2), relay.const(3), relay.Tuple([relay.const(4)])])\n    same = relay.Tuple([v0, relay.const(2), relay.const(3), relay.Tuple([relay.const(4)])])\n\n    assert consistent_equal(tup, same)\n\n    # use the eq_map\n\n    let_tup = relay.Let(v1, tup, v1)\n    let_mapped = relay.Let(\n        v2, relay.Tuple([v0, relay.const(2), relay.const(3), relay.Tuple([relay.const(4)])]), v2\n    )\n\n    assert consistent_equal(let_tup, let_mapped)\n\n    more_fields = relay.Tuple(\n        [v1, relay.const(2), relay.const(3), relay.Tuple([relay.const(4)]), v2]\n    )\n    assert not consistent_equal(tup, more_fields)\n\n    fewer_fields = relay.Tuple([v1, relay.const(2), relay.const(3)])\n    assert not consistent_equal(tup, fewer_fields)\n\n    different_end = relay.Tuple([v1, relay.const(2), relay.const(3), relay.Tuple([relay.const(5)])])\n    assert not consistent_equal(tup, different_end)\n\n    different_start = relay.Tuple(\n        [v2, relay.const(2), relay.const(3), relay.Tuple([relay.const(4)])]\n    )\n    assert not consistent_equal(tup, different_start)\n\n    longer_at_end = relay.Tuple(\n        [v1, relay.const(2), relay.const(3), relay.Tuple([relay.const(4), relay.const(5)])]\n    )\n    assert not consistent_equal(tup, longer_at_end)\n\n\ndef test_tuple_get_item_sequal():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    assert not consistent_equal(relay.TupleGetItem(x, 1), relay.TupleGetItem(y, 1))\n    assert not consistent_equal(relay.TupleGetItem(x, 1), relay.TupleGetItem(x, 2))\n    assert consistent_equal(relay.TupleGetItem(x, 1), relay.TupleGetItem(x, 1))\n\n\ndef test_function_attr():\n    x0 = relay.var(\"x0\", shape=(10, 10))\n    w00 = relay.var(\"w00\", shape=(10, 10))\n    w01 = relay.var(\"w01\", shape=(10, 10))\n    w02 = relay.var(\"w02\", shape=(10, 10))\n    z00 = relay.add(x0, w00)\n    p00 = relay.subtract(z00, w01)\n    q00 = relay.multiply(p00, w02)\n    func0 = relay.Function([x0, w00, w01, w02], q00)\n    func0 = func0.with_attr(\"FuncName\", \"a\")\n\n    x1 = relay.var(\"x1\", shape=(10, 10))\n    w10 = relay.var(\"w10\", shape=(10, 10))\n    w11 = relay.var(\"w11\", shape=(10, 10))\n    w12 = relay.var(\"w12\", shape=(10, 10))\n    z10 = relay.add(x1, w10)\n    p10 = relay.subtract(z10, w11)\n    q10 = relay.multiply(p10, w12)\n    func1 = relay.Function([x1, w10, w11, w12], q10)\n    func1 = func1.with_attr(\"FuncName\", \"b\")\n    assert not consistent_equal(func0, func1)\n\n\ndef test_function_sequal():\n    tt1 = relay.TensorType((1, 2, 3), \"float32\")\n    tt2 = relay.TensorType((4, 5, 6), \"int8\")\n    tt3 = relay.TupleType([tt1, tt2])\n\n    v1 = relay.Var(\"v1\", tt1)\n    v2 = relay.Var(\"v2\", tt2)\n    v3 = relay.Var(\"v3\", tt3)\n    v4 = relay.Var(\"v4\", tt2)\n    vret = relay.Constant(tvm.nd.array(np.ones(1)))\n\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.Type)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.ShapeVar)\n    tp4 = relay.TypeVar(\"tp4\", relay.TypeKind.ShapeVar)\n\n    basic_args = [relay.Var(\"v3\", tt1), relay.Var(\"v4\", tt2)]\n    basic_tps = [tp1, tp2]\n\n    func = relay.Function([v1, v2], v1, tt2, basic_tps)\n    mapped = relay.Function(basic_args, basic_args[0], tt2, basic_tps)\n    assert consistent_equal(func, mapped)\n\n    fewer_params = relay.Function([relay.Var(\"v4\", tt2)], v4, tt2, basic_tps)\n    assert not consistent_equal(func, fewer_params)\n\n    more_params = relay.Function(\n        [relay.Var(\"v3\", tt1), relay.Var(\"v4\", tt2), relay.Var(\"v2\", tt2)], v4, tt2, basic_tps\n    )\n    assert not consistent_equal(func, more_params)\n\n    params_unordered = relay.Function([v2, v1], v1, tt2, basic_tps)\n    assert not consistent_equal(func, params_unordered)\n\n    params_mismatch = relay.Function([v1, v3], v1, tt2, basic_tps)\n    assert not consistent_equal(func, params_mismatch)\n\n    # also would not typecheck\n    ret_type_mismatch = relay.Function(basic_args, v4, tt1, basic_tps)\n    assert not consistent_equal(func, ret_type_mismatch)\n\n    # also mis-typed\n    different_body = relay.Function(basic_args, v3, tt2, basic_tps)\n    assert not consistent_equal(func, different_body)\n\n    fewer_type_params = relay.Function(basic_args, v4, tt2, [tp1])\n    assert not consistent_equal(func, fewer_type_params)\n\n    more_type_params = relay.Function(basic_args, v4, tt2, [tp1, tp2, tp3])\n    assert not consistent_equal(func, more_type_params)\n\n    type_params_unordered = relay.Function(basic_args, v4, tt2, [tp2, tp1])\n    assert not consistent_equal(func, type_params_unordered)\n\n    different_type_params = relay.Function(basic_args, v4, tt2, [tp3, tp4])\n    assert not consistent_equal(func, different_type_params)\n\n    # a well-typed example that also differs in body, ret type, and type params\n    tupled_example = relay.Function(basic_args, relay.Tuple([v3, v4]), tt3)\n    assert not consistent_equal(func, tupled_example)\n\n    # nullable\n    no_ret_type = relay.Function(basic_args, v4, None, [tp1, tp2])\n    # both null\n    assert consistent_equal(no_ret_type, no_ret_type)\n    # one null\n    assert not consistent_equal(func, no_ret_type)\n    assert not consistent_equal(no_ret_type, func)\n\n\ndef test_call_sequal():\n    v1 = relay.Var(\"v1\")\n    v2 = relay.Var(\"v2\")\n\n    attr1 = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n    attr1_same = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n    attr2 = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4, 4))\n\n    tt1 = relay.TensorType((1, 2, 3), \"float32\")\n    tt2 = relay.TensorType((), \"int8\")\n\n    basic_args = [relay.const(1), relay.const(2), v2, relay.Tuple([])]\n\n    # manually writing out args to ensure that args does not rely on\n    # pointer equality\n    call = relay.Call(v1, [relay.const(1), relay.const(2), v2, relay.Tuple([])], attr1, [tt1])\n    same = relay.Call(v1, basic_args, attr1, [tt1])\n    assert consistent_equal(call, same)\n\n    different_fn = relay.Call(v2, basic_args, attr1, [tt1])\n    assert not consistent_equal(call, different_fn)\n\n    fewer_args = relay.Call(v1, [relay.const(1), relay.const(2), v2], attr1, [tt1])\n    assert not consistent_equal(call, fewer_args)\n\n    reordered_args = relay.Call(\n        v1, [relay.const(2), relay.const(1), relay.Tuple([]), v2], attr1, [tt1]\n    )\n    assert not consistent_equal(call, reordered_args)\n\n    different_args = relay.Call(v1, [relay.const(1), relay.const(2), relay.const(3)], attr1, [tt1])\n    assert not consistent_equal(call, different_args)\n\n    more_args = relay.Call(\n        v1,\n        [relay.const(1), relay.const(2), v2, relay.Tuple([]), relay.const(3), relay.const(4)],\n        attr1,\n        [tt1],\n    )\n    assert not consistent_equal(call, more_args)\n\n    different_attrs = relay.Call(v1, basic_args, attr2, [tt1])\n    assert not consistent_equal(call, different_attrs)\n\n    same_attrs = relay.Call(v1, basic_args, attr1_same, [tt1])\n    assert consistent_equal(call, same_attrs)\n\n    no_type_args = relay.Call(v1, basic_args, attr1)\n    assert not consistent_equal(call, no_type_args)\n\n    more_type_args = relay.Call(v1, basic_args, attr1, [tt1, tt2])\n    assert not consistent_equal(call, more_type_args)\n\n    different_type_arg = relay.Call(v1, basic_args, attr1, [tt2])\n    assert not consistent_equal(call, different_type_arg)\n\n\ndef test_let_sequal():\n    tt1 = relay.TensorType((), \"float32\")\n    tt2 = relay.TensorType((), \"int8\")\n    v1 = relay.Var(\"v1\")\n    v1_wtype = relay.Var(\"v1\", tt1)\n    v2 = relay.Var(\"v2\")\n    v3 = relay.Var(\"v3\")\n\n    let = relay.Let(v1, relay.const(2), v1)\n    mapped = relay.Let(v2, relay.const(2), v2)\n    assert consistent_equal(let, mapped)\n\n    mismatched_var = relay.Let(v2, relay.const(2), v3)\n    assert not consistent_equal(let, mismatched_var)\n\n    different_value = relay.Let(v2, relay.const(3), v2)\n    assert not consistent_equal(let, different_value)\n\n    different_body = relay.Let(v2, relay.const(3), relay.const(12))\n    assert not consistent_equal(let, different_body)\n\n    # specified types must match\n\n    let_with_type = relay.Let(v1_wtype, relay.const(2), v1_wtype)\n    same_type = relay.Let(v1_wtype, relay.const(2), v1_wtype)\n    assert consistent_equal(let_with_type, same_type)\n    assert not consistent_equal(let, let_with_type)\n    v2 = relay.Var(\"v1\", tt2)\n    different_type = relay.Let(v2, relay.const(2), v2)\n    assert not consistent_equal(let_with_type, different_type)\n\n\ndef test_if_sequal():\n    v1 = relay.Var(\"v1\")\n    v2 = relay.Var(\"v2\")\n\n    if_sample = relay.If(v1, relay.const(1), relay.Tuple([relay.const(2), relay.const(3)]))\n    same = relay.If(v1, relay.const(1), relay.Tuple([relay.const(2), relay.const(3)]))\n    assert consistent_equal(if_sample, same)\n\n    different_cond = relay.If(v2, relay.const(1), relay.Tuple([relay.const(2), relay.const(3)]))\n    assert not consistent_equal(if_sample, different_cond)\n\n    different_true = relay.If(v1, relay.const(2), relay.Tuple([relay.const(2), relay.const(3)]))\n    assert not consistent_equal(if_sample, different_true)\n\n    different_false = relay.If(v1, relay.const(1), relay.Tuple([]))\n    assert not consistent_equal(if_sample, different_false)\n\n\ndef test_constructor_sequal():\n    # smoke test: it should be pointer equality\n    mod = tvm.IRModule()\n    p = relay.prelude.Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n\n    assert consistent_equal(nil, nil)\n    assert consistent_equal(cons, cons)\n    assert not consistent_equal(nil, cons)\n\n\ndef test_match_sequal():\n    mod = tvm.IRModule()\n    p = relay.prelude.Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n    _, none, some = p.mod.get_type(\"Option\")\n\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    nil_case = relay.Clause(relay.PatternConstructor(nil), nil())\n    cons_case = relay.Clause(\n        relay.PatternConstructor(cons, [relay.PatternVar(x), relay.PatternVar(y)]), cons(x, y)\n    )\n\n    z = relay.Var(\"z\")\n    a = relay.Var(\"a\")\n    equivalent_cons = relay.Clause(\n        relay.PatternConstructor(cons, [relay.PatternVar(z), relay.PatternVar(a)]), cons(z, a)\n    )\n\n    data = cons(relay.const(1), cons(relay.const(2), nil()))\n\n    match = relay.Match(data, [nil_case, cons_case])\n    equivalent = relay.Match(data, [nil_case, equivalent_cons])\n    empty = relay.Match(data, [])\n    no_cons = relay.Match(data, [nil_case])\n    no_nil = relay.Match(data, [cons_case])\n    different_data = relay.Match(nil(), [nil_case, cons_case])\n    different_order = relay.Match(data, [cons_case, nil_case])\n    different_nil = relay.Match(\n        data, [relay.Clause(relay.PatternConstructor(nil), cons(nil(), nil())), cons_case]\n    )\n    different_cons = relay.Match(\n        data,\n        [\n            nil_case,\n            relay.Clause(\n                relay.PatternConstructor(cons, [relay.PatternWildcard(), relay.PatternWildcard()]),\n                nil(),\n            ),\n        ],\n    )\n    another_case = relay.Match(\n        data, [nil_case, cons_case, relay.Clause(relay.PatternWildcard(), nil())]\n    )\n    wrong_constructors = relay.Match(\n        data,\n        [\n            relay.Clause(relay.PatternConstructor(none), nil()),\n            relay.Clause(relay.PatternConstructor(some, [relay.PatternVar(x)]), cons(x, nil())),\n        ],\n    )\n\n    tvm.ir.assert_structural_equal(match, match)\n    assert consistent_equal(match, match)\n    assert consistent_equal(match, equivalent)\n    assert not consistent_equal(match, no_cons)\n    assert not consistent_equal(match, no_nil)\n    assert not consistent_equal(match, empty)\n    assert not consistent_equal(match, different_data)\n    assert not consistent_equal(match, different_order)\n    assert not consistent_equal(match, different_nil)\n    assert not consistent_equal(match, different_cons)\n    assert not consistent_equal(match, another_case)\n    assert not consistent_equal(match, wrong_constructors)\n\n\ndef test_op_sequal():\n    # only checks names\n    op1 = relay.op.get(\"add\")\n    op2 = relay.op.get(\"add\")\n    assert consistent_equal(op1, op2)\n\n    op3 = relay.op.get(\"take\")\n    assert not consistent_equal(op1, op3)\n\n\ndef test_graph_equal():\n    x = relay.var(\"x\")\n\n    y0 = relay.add(x, x)\n    z0 = relay.add(y0, y0)\n\n    y1 = relay.add(x, x)\n    z1 = relay.add(y1, y1)\n\n    z3 = relay.add(relay.add(x, x), relay.add(x, x))\n\n    assert consistent_equal(z0, z1)\n    assert consistent_equal(z0, z1)\n\n    # z3's dataflow format is different from z0\n    # z0 is computed from a common y0 node\n    # Relay view them as different programs\n    # Check the difference in the text format.\n    assert not consistent_equal(z0, z3)\n\n\ndef test_hash_unequal():\n    x1 = relay.var(\"x1\", shape=(10, 10), dtype=\"float32\")\n    y1 = relay.var(\"y1\", shape=(10, 10), dtype=\"float32\")\n    func1 = relay.Function([x1, y1], relay.add(x1, y1))\n\n    # func2 is exactly same structure with same variables shapes and dtypes\n    x2 = relay.var(\"x2\", shape=(10, 10), dtype=\"float32\")\n    y2 = relay.var(\"y2\", shape=(10, 10), dtype=\"float32\")\n    func2 = relay.Function([x2, y2], relay.add(x2, y2))\n\n    assert consistent_equal(func1, func2)\n\n    # func3 is same as func1 but with different var shapes\n    x3 = relay.var(\"x3\", shape=(20, 10), dtype=\"float32\")\n    y3 = relay.var(\"y3\", shape=(20, 10), dtype=\"float32\")\n    func3 = relay.Function([x3, y3], relay.add(x3, y3))\n\n    assert not consistent_equal(func1, func3)\n\n\ndef test_tuple_match():\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    clause = relay.Clause(relay.PatternTuple([relay.PatternVar(a), relay.PatternVar(b)]), a + b)\n    x = relay.Match(relay.Tuple([relay.const(1), relay.const(1)]), [clause])\n\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    clause = relay.Clause(relay.PatternTuple([relay.PatternVar(a), relay.PatternVar(b)]), a + b)\n    y = relay.Match(relay.Tuple([relay.const(1), relay.const(1)]), [clause])\n    assert consistent_equal(x, y)\n\n\ndef test_fn_attribute():\n    # create function that performs add\n    a = relay.var(\"a\", shape=(10, 10))\n    b = relay.var(\"b\", shape=(10, 10))\n    add = relay.add(a, b)\n    add_fn = relay.Function([a, b], add)\n    add_fn = run_opt_pass(add_fn, relay.transform.InferType())\n\n    # create function that performs add with test attribute\n    c = relay.var(\"c\", shape=(10, 10))\n    d = relay.var(\"d\", shape=(10, 10))\n    add_1 = relay.add(c, d)\n    add_1_fn = relay.Function([c, d], add_1)\n    add_1_fn = add_1_fn.with_attr(\"TestAttribute\", \"test\")\n    add_1_fn = run_opt_pass(add_1_fn, relay.transform.InferType())\n\n    assert not consistent_equal(add_1_fn, add_fn)\n    assert not consistent_equal(add_fn, add_1_fn)\n\n\ndef test_fn_vid_map():\n    def get_fn(with_vid):\n        x = relay.var(\"x\", shape=(10,), dtype=\"float32\")\n        f = relay.Function([x], x).with_attr(\"dict\", {x.vid: 1} if with_vid else {x: 1})\n        return f\n\n    assert consistent_equal(get_fn(True), get_fn(True))\n    assert consistent_equal(get_fn(False), get_fn(False))\n\n\ndef test_lets():\n    shape = (5, 5)\n\n    def func1():\n        sb = relay.ScopeBuilder()\n        p0 = relay.var(\"p0\", shape=shape)\n        p1 = relay.var(\"p1\", shape=shape)\n        a0 = sb.let(\"a0\", relay.add(p0, relay.const(1)))\n        a1 = sb.let(\"a1\", relay.add(p1, relay.const(1)))\n        a2 = sb.let(\"a2\", relay.add(a0, a1))\n        sb.ret(a2)\n        return relay.Function([p0, p1], sb.get())\n\n    def func2():\n        # Alpha conversion is structurally equal\n        sb = relay.ScopeBuilder()\n        p0 = relay.var(\"p0\", shape=shape)\n        p1 = relay.var(\"p1\", shape=shape)\n        a1 = sb.let(\"a1\", relay.add(p0, relay.const(1)))\n        a0 = sb.let(\"a0\", relay.add(p1, relay.const(1)))\n        a2 = sb.let(\"a2\", relay.add(a1, a0))\n        sb.ret(a2)\n        return relay.Function([p0, p1], sb.get())\n\n    def func3():\n        # But changing the order of bindings is not structurally equal\n        # (even though algebraically equal)\n        sb = relay.ScopeBuilder()\n        p0 = relay.var(\"p0\", shape=shape)\n        p1 = relay.var(\"p1\", shape=shape)\n        a1 = sb.let(\"a1\", relay.add(p1, relay.const(1)))\n        a0 = sb.let(\"a0\", relay.add(p0, relay.const(1)))\n        a2 = sb.let(\"a2\", relay.add(a1, a0))\n        sb.ret(a2)\n        return relay.Function([p0, p1], sb.get())\n\n    assert tvm.ir.structural_equal(func1(), func2())\n    assert not tvm.ir.structural_equal(func1(), func3())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_text_printer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import testing\nimport numpy as np\nfrom tvm.relay import Expr\nfrom tvm.relay.analysis import free_vars\nimport pytest\n\nDEBUG_PRINT = False\n\nSEMVER = '#[version = \"0.0.5\"]\\n'\n\n\ndef astext(program, unify_free_vars=False):\n    text = program.astext()\n\n    if isinstance(program, Expr):\n        roundtrip_program = tvm.parser.parse_expr(text)\n    else:\n        roundtrip_program = tvm.parser.fromtext(text)\n\n    tvm.ir.assert_structural_equal(roundtrip_program, program, map_free_vars=True)\n\n    return text\n\n\ndef show(text):\n    if DEBUG_PRINT:\n        print(\"---------------------------\")\n        print(text)\n\n\ndef assert_prints_as(expr, str):\n    assert astext(expr) == SEMVER + str\n\n\ndef test_scalars():\n    assert_prints_as(relay.const(42, \"int16\"), \"42i16\")\n    assert_prints_as(relay.const(42, \"int32\"), \"42\")\n    assert_prints_as(relay.const(42, \"int64\"), \"42i64\")\n    assert_prints_as(relay.const(3.0, \"float16\"), \"3f16\")\n    assert_prints_as(relay.const(3.0, \"float32\"), \"3f\")\n    assert_prints_as(relay.const(3.0, \"float64\"), \"3f64\")\n\n\ndef test_large_graph():\n    x = relay.var(\"x\", shape=(3, 2))\n    y = relay.var(\"y\")\n    one = relay.const(10e10, dtype=\"float32\")\n    z = relay.add(x, one)\n    for i in range(int(9e4)):\n        z = relay.add(z, one)\n    f = relay.Function([x, y], z)\n    show(astext(f))\n\n\ndef test_func():\n    x = relay.var(\"x\", shape=(3, 2))\n    y = relay.var(\"y\")\n    one = relay.const(10e10, dtype=\"float32\")\n    z = relay.add(x, one)\n    z = relay.add(z, z)\n    f = relay.Function([x, y], z)\n    show(astext(z))\n    show(astext(f))\n\n\ndef test_mod():\n    x = relay.var(\"x\", \"float32\")\n    y = relay.var(\"y\", \"float32\")\n    z = relay.add(x, y)\n    z = relay.add(z, z)\n    f = relay.Function([x, y], z)\n    mod = tvm.IRModule()\n    mod[\"myf\"] = f\n    mod = relay.transform.InferType()(mod)\n    text = astext(mod)\n    assert \"def @myf\" in text\n    assert \"def @myf\" in str(mod)\n    assert \"add(%0, %0) /* ty=float32 */\" in text\n    assert \"add(%0, %0) /* ty=float32 */\" in str(mod)\n    show(mod.astext(annotate=lambda x: str(x.checked_type.dtype) if type(x) == relay.Call else \"\"))\n    show(text)\n\n\ndef test_meta_data():\n    n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n    x = relay.var(\"x\", shape=(n, c, h, w))\n    w = relay.var(\"w\")\n    z = relay.nn.conv2d(x, w, kernel_size=(3, 3), padding=(1, 1), channels=2)\n    f = relay.Function([x, w], z)\n    text = astext(f, unify_free_vars=True)\n    text_no_meta = str(f)\n    assert \"channels=2\" in text\n    assert \"channels=2\" in text_no_meta\n    assert \"meta[tir.SizeVar][0]\" in text\n    assert \"meta[tir.SizeVar][0]\" in text_no_meta\n    assert \"type_key\" in text\n    assert \"type_key\" not in text_no_meta\n\n    text = astext(relay.const([1, 2, 3]))\n    assert \"meta[relay.Constant][0]\" in text\n\n\ndef test_call_attrs():\n    x = relay.var(\"x\")\n    # non default args\n    z = relay.nn.softmax(x, axis=2)\n    assert \"axis=2\" in astext(z)\n    # default args\n    z = relay.nn.softmax(x)\n    assert \"softmax(%x)\" in astext(z)\n    # non default args\n    z = relay.expand_dims(x, axis=2, num_newaxis=2)\n    assert \"num_newaxis=2\" in astext(z)\n\n\ndef test_let_if_scope():\n    x = relay.var(\"x\", \"float32\")\n    y = relay.var(\"y\", \"float32\")\n    cond = relay.var(\"cond\", \"bool\")\n\n    sb = relay.ScopeBuilder()\n    with sb.if_scope(cond):\n        v1 = sb.let(\"v\", relay.const(1, \"float32\"))\n        v2 = sb.let(\"v\", x)\n        sb.ret(relay.subtract(v1, v2))\n    with sb.else_scope():\n        v3 = relay.var(\"v\")\n        let2 = relay.Let(v3, y, v3)\n        sb.ret(relay.add(let2, let2))\n    result = sb.get()\n\n    f = relay.Function([x, y, cond], result)\n    text = astext(f)\n    assert text.count(\"{\") == 3\n    assert \"%cond: bool\" in text\n    show(astext(f))\n\n\ndef test_variable_name():\n    # avoid pure number even if the namehint is pure number\n    v1 = relay.var(\"1\")\n    assert \"%v1\" in astext(v1)\n\n\ndef test_mlp():\n    net, _ = tvm.relay.testing.mlp.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_resnet():\n    net, _ = tvm.relay.testing.resnet.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_mobilenet():\n    net, _ = tvm.relay.testing.mobilenet.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_dqn():\n    net, _ = tvm.relay.testing.dqn.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_dcgan():\n    net, _ = tvm.relay.testing.dcgan.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_lstm():\n    net, _ = tvm.relay.testing.lstm.get_workload(1, 1)\n    astext(net)\n\n    net, _ = tvm.relay.testing.lstm.get_workload(4, 4)\n    astext(net)\n\n\ndef test_inception_v3():\n    net, _ = tvm.relay.testing.inception_v3.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_squeezenet():\n    for version in [\"1.0\", \"1.1\"]:\n        net, _ = tvm.relay.testing.squeezenet.get_workload(batch_size=1, version=version)\n        astext(net)\n\n\ndef test_densenet():\n    net, _ = tvm.relay.testing.densenet.get_workload(batch_size=1)\n    astext(net)\n\n\ndef test_call_node_order():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    prog = relay.Call(\n        relay.Function([x], x), [relay.Call(relay.Function([y], y), [relay.const(1)])]\n    )\n    assert astext(prog) == SEMVER + (\n        \"%0 = fn (%y) {\\n\"\n        \"  %y\\n\"\n        \"};\\n\"\n        \"%1 = %0(1);\\n\"\n        \"%2 = fn (%x) {\\n\"\n        \"  %x\\n\"\n        \"};\\n\"\n        \"%2(%1)\"\n    )\n\n\ndef test_let_inlining():\n    tup = relay.Tuple([relay.const(0), relay.const(0)])\n    x = relay.var(\"x\")\n    assert astext(relay.Let(x, tup, tup)) == SEMVER + (\"%0 = (0, 0);\\n\" \"let %x = %0;\\n\" \"%0\")\n\n    assert astext(relay.Let(x, tup, x)) == SEMVER + (\"let %x = (0, 0);\\n\" \"%x\")\n\n\ndef test_zeros():\n    x = relay.op.zeros([], \"float32\")\n    astext(x)\n\n\ndef test_unapplied_constructor():\n    type_def_str = r\"\"\"\ntype List[A] {\n  Cons(A, List[A]),\n  Nil,\n}\n    \"\"\"\n    main_def_str = r\"\"\"\ndef @main[A]() -> fn (A, List[A]) -> List[A] {\n  Cons\n}\n    \"\"\"\n    mod = tvm.parser.parse(SEMVER + type_def_str + main_def_str)\n    mod_str = str(mod)\n    # ensure constructors are printed correctly in type definitions (with their\n    # signature) and as exprs (without their signature)\n    assert type_def_str.strip() in mod_str\n    assert main_def_str.strip() in mod_str\n\n\ndef test_null_attribute():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    z = relay.Function([x], y)\n    z = z.with_attr(\"TestAttribute\", None)\n    txt = astext(z)\n    assert \"TestAttribute=None\" in txt\n\n\ndef test_span():\n    x = relay.var(\"x\", shape=(3, 2))\n    y = relay.var(\"y\")\n    one = relay.const(10e10, dtype=\"float32\")\n    z = relay.add(x, one)\n    z = relay.Call(\n        z.op, z.args, z.attrs, z.type_args, relay.Span(relay.SourceName(\"Add0\"), 0, 0, 0, 0)\n    )\n    z = relay.add(z, z)\n    z = relay.Call(\n        z.op, z.args, z.attrs, z.type_args, relay.Span(relay.SourceName(\"Add1\"), 0, 0, 0, 0)\n    )\n    f = relay.Function([x, y], z)\n    txt = astext(f)\n    assert \"Add0\" in txt\n    assert \"Add1\" in txt\n\n\ndef test_optional_info():\n    c = relay.const(1)\n    call = relay.add(c, c)\n    m = tvm.IRModule.from_expr(call)\n    m = relay.transform.InferType()(m)\n    txt = astext(m)\n    assert txt.count(\"/* ty=int32 */\") == 3\n\n\ndef test_slash_in_identifier():\n    x = relay.var(\"base/x\")\n    y = relay.var(\"base/y\")\n    z = x + y\n    txt = astext(z)\n    assert \"base/x\" in txt\n    assert \"base/y\" in txt\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_ir_well_formed.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import well_formed\nfrom tvm.relay.prelude import Prelude\n\n\ndef test_let():\n    x = relay.Var(\"x\")\n    assert well_formed(x)\n    v = relay.Constant(tvm.nd.array(10))\n    ty = None\n    let = relay.Let(x, v, x)\n    assert well_formed(let)\n    assert not well_formed(relay.Let(x, v, let))\n    f = relay.Function([x], x, ty)\n    assert well_formed(f)\n    assert well_formed(relay.Let(relay.Var(\"y\"), f, relay.Let(relay.Var(\"z\"), f, v)))\n\n\ndef test_tuple():\n    x = relay.Var(\"x\")\n    assert well_formed(x)\n    v = relay.Constant(tvm.nd.array(10))\n    let = relay.Let(x, v, x)\n    assert well_formed(let)\n    assert well_formed(relay.Tuple([v, v]))\n    assert not well_formed(relay.Tuple([let, relay.Let(x, v, x)]))\n\n\ndef test_tuple_get_item():\n    t = relay.Var(\"t\")\n    assert well_formed(relay.TupleGetItem(t, 2))\n\n\ndef test_adt():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, none, some = p.mod.get_type(\"Option\")\n    x = relay.Var(\"x\")\n    some_case = relay.Clause(relay.PatternConstructor(some, [relay.PatternVar(x)]), x)\n    default_case = relay.Clause(relay.PatternVar(x), x)\n    m0 = relay.Match(none(), [default_case])\n    m1 = relay.Match(none(), [some_case, default_case])\n    assert well_formed(m0)\n    assert not well_formed(m1)\n\n\nif __name__ == \"__main__\":\n    test_let()\n    test_tuple()\n    test_tuple_get_item()\n    test_adt()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_json_compact.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import relay\nfrom tvm import te\nimport json\n\n\n# 0.6 BACKWARDS COMPATIBILITY TESTS\n\n\ndef test_type_var():\n    # type var in 0.6\n    nodes = [\n        {\"type_key\": \"\"},\n        {\"type_key\": \"relay.TypeVar\", \"attrs\": {\"kind\": \"0\", \"span\": \"0\", \"var\": \"2\"}},\n        {\"type_key\": \"Variable\", \"attrs\": {\"dtype\": \"int32\", \"name\": \"in0\"}},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.TypeVar)\n    assert tvar.name_hint == \"in0\"\n    nodes[1][\"type_key\"] = \"relay.GlobalTypeVar\"\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.GlobalTypeVar)\n    assert tvar.name_hint == \"in0\"\n\n\ndef test_var():\n    # type var in 0.6\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"relay.Var\",\n            \"attrs\": {\n                \"_checked_type_\": \"0\",\n                \"span\": \"0\",\n                \"type_annotation\": \"0\",\n                \"vid\": \"2\",\n            },\n        },\n        {\"type_key\": \"relay.Id\", \"attrs\": {\"name_hint\": \"a3\"}},\n        {\"type_key\": \"relay.TensorType\", \"attrs\": {\"dtype\": \"float32\", \"shape\": \"4\", \"span\": \"0\"}},\n        {\"type_key\": \"Array\", \"data\": [5, 6]},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"16\", \"span\": \"0\"}},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"8\", \"span\": \"0\"}},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, relay.Var)\n    assert tvar.name_hint == \"a3\"\n\n\ndef test_incomplete_type():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\"type_key\": \"relay.IncompleteType\", \"attrs\": {\"kind\": \"0\", \"span\": \"0\"}},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.IncompleteType)\n\n\ndef test_func_tuple_type():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"relay.FuncType\",\n            \"attrs\": {\n                \"arg_types\": \"2\",\n                \"ret_type\": \"3\",\n                \"span\": \"0\",\n                \"type_constraints\": \"6\",\n                \"type_params\": \"5\",\n            },\n        },\n        {\"type_key\": \"Array\"},\n        {\"type_key\": \"relay.TupleType\", \"attrs\": {\"fields\": \"4\", \"span\": \"0\"}},\n        {\"type_key\": \"Array\"},\n        {\"type_key\": \"Array\"},\n        {\"type_key\": \"Array\"},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.FuncType)\n\n\ndef test_global_var():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"relay.GlobalVar\",\n            \"attrs\": {\"_checked_type_\": \"0\", \"name_hint\": \"x\", \"span\": \"0\"},\n        },\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.GlobalVar)\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"GlobalVar\",\n            \"attrs\": {\"_checked_type_\": \"0\", \"name_hint\": \"x\", \"span\": \"0\"},\n        },\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    tvar = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(tvar, tvm.ir.GlobalVar)\n\n\ndef test_op():\n    nodes = [{\"type_key\": \"\"}, {\"type_key\": \"relay.Op\", \"global_key\": \"nn.conv2d\"}]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    op = tvm.ir.load_json(json.dumps(data))\n    assert op == relay.op.get(\"nn.conv2d\")\n\n\ndef test_tir_var():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\"type_key\": \"Variable\", \"attrs\": {\"dtype\": \"int32\", \"name\": \"x\", \"span\": \"0\"}},\n        {\"type_key\": \"SizeVar\", \"attrs\": {\"dtype\": \"int32\", \"name\": \"y\", \"span\": \"0\"}},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    x = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(x, tvm.tir.Var)\n    assert x.name == \"x\"\n    data[\"root\"] = 2\n    y = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(y, tvm.tir.SizeVar)\n    assert y.name == \"y\"\n\n\ndef test_str_map():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\"type_key\": \"StrMap\", \"keys\": [\"z\", \"x\"], \"data\": [2, 3]},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"2\", \"span\": \"0\"}},\n        {\"type_key\": \"Max\", \"attrs\": {\"a\": \"4\", \"b\": \"10\", \"dtype\": \"int32\", \"span\": \"0\"}},\n        {\"type_key\": \"Add\", \"attrs\": {\"a\": \"5\", \"b\": \"9\", \"dtype\": \"int32\", \"span\": \"0\"}},\n        {\"type_key\": \"Add\", \"attrs\": {\"a\": \"6\", \"b\": \"8\", \"dtype\": \"int32\", \"span\": \"0\"}},\n        {\n            \"type_key\": \"tir.Var\",\n            \"attrs\": {\"dtype\": \"int32\", \"name\": \"7\", \"type_annotation\": \"0\", \"span\": \"0\"},\n        },\n        {\"type_key\": \"runtime.String\", \"repr_str\": \"x\"},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"1\", \"span\": \"0\"}},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"2\", \"span\": \"0\"}},\n        {\"type_key\": \"IntImm\", \"attrs\": {\"dtype\": \"int32\", \"value\": \"100\", \"span\": \"0\"}},\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.6.0\"},\n        \"b64ndarrays\": [],\n    }\n    x = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(x, tvm.ir.container.Map)\n    assert len(x) == 2\n    assert \"x\" in x\n    assert \"z\" in x\n    assert bool(x[\"z\"] == 2)\n\n\n# 0.7 BACKWARDS COMPATIBILITY TESTS\n\n\ndef test_irmodule_attributes():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"IRModule\",\n            \"attrs\": {\n                \"functions\": \"0\",\n                \"global_type_var_map_\": \"0\",\n                \"global_var_map_\": \"0\",\n                \"source_map\": \"0\",\n                \"type_definitions\": \"0\",\n            },\n        },\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.7.0\"},\n        \"b64ndarrays\": [],\n    }\n    mod = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(mod, tvm.ir.IRModule)\n    # IRModule attributes should defualt to null\n    assert not mod.attrs\n\n\n# 0.8 BACKWARDS COMPATIBILITY TESTS\n\n\ndef test_virtual_device():\n    nodes = [\n        {\"type_key\": \"\"},\n        {\n            \"type_key\": \"relay.Function\",\n            \"attrs\": {\n                \"_checked_type_\": \"0\",\n                \"attrs\": \"0\",\n                \"body\": \"0\",\n                \"params\": \"0\",\n                \"ret_type\": \"0\",\n                \"span\": \"0\",\n                \"type_params\": \"0\",\n            },\n        },\n    ]\n    data = {\n        \"root\": 1,\n        \"nodes\": nodes,\n        \"attrs\": {\"tvm_version\": \"0.8.0\"},\n        \"b64ndarrays\": [],\n    }\n    func = tvm.ir.load_json(json.dumps(data))\n    assert isinstance(func, relay.Function)\n    assert not func.virtual_device_\n\n\nif __name__ == \"__main__\":\n    test_op()\n    test_type_var()\n    test_var()\n    test_incomplete_type()\n    test_func_tuple_type()\n    test_global_var()\n    test_tir_var()\n    test_str_map()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_json_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for JSON codegen and runtime.\"\"\"\nimport os\nimport sys\n\nimport numpy as np\n\nimport tvm\nimport tvm.relay.op as reg\nimport tvm.relay.testing\nfrom tvm import relay, runtime\nfrom tvm.contrib import utils\nfrom tvm.relay import transform\nfrom tvm.relay.backend import te_compiler\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.op.contrib.register import get_pattern_table\n\n\ndef set_func_attr(func, compile_name, symbol_name):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compile_name)\n    func = func.with_attr(\"global_symbol\", symbol_name)\n    return func\n\n\ndef check_result(\n    mod, ref_mod, map_inputs, out_shape, tol=1e-5, target=\"llvm\", device=tvm.cpu(), params=None\n):\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        return\n\n    # Run the reference result\n    te_compiler.get().clear()\n    with tvm.transform.PassContext(opt_level=3):\n        json, lib, param = relay.build(ref_mod, target=target, params=params)\n    rt_mod = tvm.contrib.graph_executor.create(json, lib, device)\n\n    for name, data in map_inputs.items():\n        rt_mod.set_input(name, data)\n    rt_mod.set_input(**param)\n    rt_mod.run()\n    out = tvm.nd.empty(out_shape, device=device)\n    out = rt_mod.get_output(0, out)\n    ref_result = out.numpy()\n\n    def check_vm_result():\n        te_compiler.get().clear()\n        with relay.build_config(opt_level=3):\n            exe = relay.vm.compile(mod, target=target, params=params)\n        code, lib = exe.save()\n        exe = runtime.vm.Executable.load_exec(code, lib)\n        vm = runtime.vm.VirtualMachine(exe, device)\n        out = vm.run(**map_inputs)\n        tvm.testing.assert_allclose(out.numpy(), ref_result, rtol=tol, atol=tol)\n\n    def check_graph_executor_result():\n        te_compiler.get().clear()\n        with relay.build_config(opt_level=3):\n            json, lib, param = relay.build(mod, target=target, params=params)\n        rt_mod = tvm.contrib.graph_executor.create(json, lib, device)\n\n        for name, data in map_inputs.items():\n            rt_mod.set_input(name, data)\n        rt_mod.set_input(**param)\n        rt_mod.run()\n        out = tvm.nd.empty(out_shape, device=device)\n        out = rt_mod.get_output(0, out)\n        tvm.testing.assert_allclose(out.numpy(), ref_result, rtol=tol, atol=tol)\n\n    check_vm_result()\n    check_graph_executor_result()\n\n\ndef test_conv2d():\n    \"\"\"Test a subgraph with a single conv2d operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    def conv2d_direct():\n        dtype = \"float32\"\n        ishape = (1, 1, 99, 12)\n        w1shape = (54, 1, 3, 3)\n\n        data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight0 = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        out = relay.nn.conv2d(\n            data0, weight0, kernel_size=(3, 3), strides=(2, 2), padding=(1, 0, 1, 1)\n        )\n\n        func = relay.Function([data0, weight0], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight = relay.var(\"weight\", shape=(w1shape), dtype=dtype)\n        main_f = relay.Function([data, weight], glb_var(data, weight))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight0 = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        out = relay.nn.conv2d(\n            data0, weight0, kernel_size=(3, 3), strides=(2, 2), padding=(1, 0, 1, 1)\n        )\n        main_f = relay.Function([data0, weight0], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n        w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n        return mod, ref_mod, {\"data\": i_data, \"weight\": w1_data}, (1, 54, 50, 6)\n\n    def group_conv2d():\n        dtype = \"float32\"\n        ishape = (1, 32, 14, 14)\n        w2shape = (32, 1, 3, 3)\n\n        data0 = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight0 = relay.var(\"weight\", shape=(w2shape), dtype=dtype)\n        out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=32)\n\n        func = relay.Function([data0, weight0], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight = relay.var(\"weight\", shape=(w2shape), dtype=dtype)\n        main_f = relay.Function([data, weight], glb_var(data, weight))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight0 = relay.var(\"weight\", shape=(w2shape), dtype=dtype)\n        out = relay.nn.conv2d(data0, weight0, kernel_size=(3, 3), padding=(1, 1), groups=32)\n        main_f = relay.Function([data0, weight0], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n        w_data = np.random.uniform(0, 1, w2shape).astype(dtype)\n\n        return mod, ref_mod, {\"data\": i_data, \"weight\": w_data}, (1, 32, 14, 14)\n\n    for mod, ref_mod, map_inputs, out_shape in [conv2d_direct(), group_conv2d()]:\n        check_result(mod, ref_mod, map_inputs, out_shape, tol=1e-5)\n\n\ndef test_add():\n    \"\"\"Test a subgraph with a single add operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    shape = (10, 10)\n\n    def gen_add():\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        out = relay.add(data0, data1)\n\n        func = relay.Function([data0, data1], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        main_f = relay.Function([data0, data1], glb_var(data0, data1))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        out = relay.add(data0, data1)\n        main_f = relay.Function([data0, data1], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        return mod, ref_mod\n\n    mod, ref_mod = gen_add()\n\n    data0 = np.random.uniform(0, 1, shape).astype(dtype)\n    data1 = np.random.uniform(0, 1, shape).astype(dtype)\n    check_result(mod, ref_mod, {\"data0\": data0, \"data1\": data1}, shape, tol=1e-5)\n\n\ndef test_multiply():\n    \"\"\"Test a subgraph with a single add operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    shape = (10, 10)\n\n    def gen_multiply():\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        out = relay.multiply(data0, data1)\n\n        func = relay.Function([data0, data1], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        main_f = relay.Function([data0, data1], glb_var(data0, data1))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        data1 = relay.var(\"data1\", shape=shape, dtype=dtype)\n        out = relay.multiply(data0, data1)\n        main_f = relay.Function([data0, data1], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        return mod, ref_mod\n\n    mod, ref_mod = gen_multiply()\n\n    data0 = np.random.uniform(0, 1, shape).astype(dtype)\n    data1 = np.random.uniform(0, 1, shape).astype(dtype)\n    check_result(mod, ref_mod, {\"data0\": data0, \"data1\": data1}, shape, tol=1e-5)\n\n\ndef test_relu():\n    \"\"\"Test a subgraph with a single ReLU operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    shape = (1, 32, 14, 14)\n\n    def gen_relu(shape):\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        out = relay.nn.relu(data0)\n\n        func = relay.Function([data0], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        main_f = relay.Function([data0], glb_var(data0))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data0 = relay.var(\"data0\", shape=shape, dtype=dtype)\n        out = relay.nn.relu(data0)\n        main_f = relay.Function([data0], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        return mod, ref_mod\n\n    def check(shape):\n        mod, ref_mod = gen_relu(shape)\n\n        data0 = np.random.uniform(-1, 1, shape).astype(dtype)\n        check_result(\n            mod,\n            ref_mod,\n            {\n                \"data0\": data0,\n            },\n            shape,\n            tol=1e-5,\n        )\n\n    check(shape=(1, 32, 14, 14))\n    check(shape=(1, 32))\n\n\ndef test_dense():\n    \"\"\"Test a subgraph with a single dense operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    a_shape = (1, 512)\n    b_shape = (1024, 512)\n\n    def gen_dense():\n        a = relay.var(\"A\", shape=a_shape, dtype=dtype)\n        b = relay.var(\"B\", shape=b_shape, dtype=dtype)\n        out = relay.nn.dense(a, b)\n\n        func = relay.Function([a, b], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        a = relay.var(\"A\", shape=a_shape, dtype=dtype)\n        b = relay.var(\"B\", shape=b_shape, dtype=dtype)\n        main_f = relay.Function([a, b], glb_var(a, b))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        a = relay.var(\"A\", shape=a_shape, dtype=dtype)\n        b = relay.var(\"B\", shape=b_shape, dtype=dtype)\n        out = relay.nn.dense(a, b)\n        main_f = relay.Function([a, b], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        return mod, ref_mod\n\n    mod, ref_mod = gen_dense()\n\n    data_a = np.random.uniform(0, 1, a_shape).astype(dtype)\n    data_b = np.random.uniform(0, 1, b_shape).astype(dtype)\n    check_result(mod, ref_mod, {\"A\": data_a, \"B\": data_b}, (1, 1024), tol=1e-5)\n\n\ndef test_bn():\n    \"\"\"Test a subgraph with a single batch_norm operator.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    d_shape = (1, 8)\n    c_shape = (8,)\n\n    def gen_bn():\n        data = relay.var(\"data\", shape=d_shape)\n        gamma = relay.var(\"gamma\", shape=c_shape)\n        beta = relay.var(\"beta\", shape=c_shape)\n        moving_mean = relay.var(\"moving_mean\", shape=c_shape)\n        moving_var = relay.var(\"moving_var\", shape=c_shape)\n        bn = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var)\n        out = bn[0]\n\n        func = relay.Function([data, gamma, beta, moving_mean, moving_var], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=d_shape)\n        gamma = relay.var(\"gamma\", shape=c_shape)\n        beta = relay.var(\"beta\", shape=c_shape)\n        moving_mean = relay.var(\"moving_mean\", shape=c_shape)\n        moving_var = relay.var(\"moving_var\", shape=c_shape)\n        main_f = relay.Function(\n            [data, gamma, beta, moving_mean, moving_var],\n            glb_var(data, gamma, beta, moving_mean, moving_var),\n        )\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=d_shape)\n        gamma = relay.var(\"gamma\", shape=c_shape)\n        beta = relay.var(\"beta\", shape=c_shape)\n        moving_mean = relay.var(\"moving_mean\", shape=c_shape)\n        moving_var = relay.var(\"moving_var\", shape=c_shape)\n        bn = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var)\n        out = bn[0]\n        main_f = relay.Function([data, gamma, beta, moving_mean, moving_var], out)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_f\n        ref_mod = transform.InferType()(ref_mod)\n\n        return mod, ref_mod\n\n    mod, ref_mod = gen_bn()\n\n    data = np.random.uniform(-1, 1, d_shape).astype(dtype)\n    gamma = np.random.uniform(-1, 1, c_shape).astype(dtype)\n    beta = np.random.uniform(-1, 1, c_shape).astype(dtype)\n    moving_mean = np.random.uniform(-1, 1, c_shape).astype(dtype)\n    moving_var = np.random.uniform(-1, 1, c_shape).astype(dtype)\n    check_result(\n        mod,\n        ref_mod,\n        {\n            \"data\": data,\n            \"gamma\": gamma,\n            \"beta\": beta,\n            \"moving_mean\": moving_mean,\n            \"moving_var\": moving_var,\n        },\n        d_shape,\n        tol=1e-5,\n    )\n\n\ndef test_multiple_ops():\n    \"\"\"Test a subgraph with multiple operators.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 32, 3, 3)\n    w2shape = (64, 32, 5, 5)\n\n    def get_net():\n        data = relay.var(\"data\", relay.TensorType(ishape, dtype))\n        w1 = relay.var(\"w1\", relay.TensorType(w1shape, dtype))\n        w2 = relay.var(\"w2\", relay.TensorType(w2shape, dtype))\n\n        layer = relay.nn.conv2d(data=data, weight=w1, kernel_size=(3, 3), padding=(1, 1))\n        layer = relay.nn.relu(layer)\n        layer = relay.nn.conv2d(data=layer, weight=w2, kernel_size=(5, 5), padding=(2, 2))\n        layer = relay.nn.relu(layer)\n\n        main_f = relay.Function([data, w1, w2], layer)\n        mod = tvm.IRModule()\n        mod[\"main\"] = main_f\n        return mod\n\n    def get_partitoned_mod(mod):\n        remove_bn_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        byoc_pass = tvm.transform.Sequential(\n            [\n                remove_bn_pass,\n                transform.AnnotateTarget(\"dnnl\"),\n                transform.MergeCompilerRegions(),\n                transform.PartitionGraph(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            return byoc_pass(mod)\n\n    ref_mod = get_net()\n    mod = get_partitoned_mod(ref_mod)\n\n    data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1 = np.random.uniform(0, 1, w1shape).astype(dtype)\n    w2 = np.random.uniform(0, 1, w2shape).astype(dtype)\n    check_result(\n        mod,\n        ref_mod,\n        {\n            \"data\": data,\n            \"w1\": w1,\n            \"w2\": w2,\n        },\n        (1, 64, 14, 14),\n        tol=1e-5,\n    )\n\n\ndef test_composite():\n    \"\"\"Test DNNL patterns and there composite functions.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n\n    def conv2d_relu():\n        ishape = (1, 32, 14, 14)\n        w1shape = (32, 32, 3, 3)\n\n        # Composite function\n        in_1 = relay.var(\"in_1\", shape=ishape, dtype=dtype)\n        in_2 = relay.var(\"in_2\", shape=w1shape, dtype=dtype)\n        conv2d = relay.nn.conv2d(in_1, in_2, kernel_size=(3, 3), padding=(1, 1))\n        relu = relay.nn.relu(conv2d)\n        func = relay.Function([in_1, in_2], relu)\n        func = func.with_attr(\"Composite\", \"dnnl.conv2d_relu\")\n        func = func.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.relu_\")\n\n        # Partition function\n        arg_1 = relay.var(\"arg_1\", shape=ishape, dtype=dtype)\n        arg_2 = relay.var(\"arg_2\", shape=w1shape, dtype=dtype)\n        call = relay.Call(func, [arg_1, arg_2])\n        p_func = relay.Function([arg_1, arg_2], call)\n        p_func = set_func_attr(p_func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = p_func\n        mod = transform.InferType()(mod)\n\n        # Main function\n        data = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        main_func = relay.Function([data, weight], glb_var(data, weight))\n        mod[\"main\"] = main_func\n        mod = transform.InferType()(mod)\n\n        # Reference module\n        data = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        conv2d = relay.nn.conv2d(data, weight, kernel_size=(3, 3), padding=(1, 1))\n        relu = relay.nn.relu(conv2d)\n        main_func = relay.Function([data, weight], relu)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_func\n        ref_mod = transform.InferType()(ref_mod)\n\n        i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n        w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n        return mod, ref_mod, {\"data\": i_data, \"weight\": w1_data}, (1, 32, 14, 14)\n\n    def conv2d_bias_relu():\n        ishape = (1, 32, 14, 14)\n        w1shape = (32, 32, 3, 3)\n        bshape = (32, 1, 1)\n\n        # Composite function\n        in_1 = relay.var(\"in_1\", shape=ishape, dtype=dtype)\n        in_2 = relay.var(\"in_2\", shape=w1shape, dtype=dtype)\n        in_3 = relay.var(\"in_3\", shape=bshape, dtype=dtype)\n        conv2d = relay.nn.conv2d(in_1, in_2, kernel_size=(3, 3), padding=(1, 1))\n        add = relay.add(conv2d, in_3)\n        relu = relay.nn.relu(add)\n        func = relay.Function([in_1, in_2, in_3], relu)\n        func = func.with_attr(\"Composite\", \"dnnl.conv2d_bias_relu\")\n        func = func.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_add_nn.relu_\")\n\n        # Partition function\n        arg_1 = relay.var(\"arg_1\", shape=ishape, dtype=dtype)\n        arg_2 = relay.var(\"arg_2\", shape=w1shape, dtype=dtype)\n        arg_3 = relay.var(\"arg_3\", shape=bshape, dtype=dtype)\n        call = relay.Call(func, [arg_1, arg_2, arg_3])\n        p_func = relay.Function([arg_1, arg_2, arg_3], call)\n        p_func = set_func_attr(p_func, \"dnnl\", \"tvmgen_default_dnnl_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = p_func\n        mod = transform.InferType()(mod)\n\n        # Main function\n        data = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        bias = relay.var(\"bias\", shape=bshape, dtype=dtype)\n        main_func = relay.Function([data, weight, bias], glb_var(data, weight, bias))\n        mod[\"main\"] = main_func\n        mod = transform.InferType()(mod)\n\n        # Reference module\n        data = relay.var(\"data\", shape=ishape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w1shape, dtype=dtype)\n        bias = relay.var(\"bias\", shape=bshape, dtype=dtype)\n        conv2d = relay.nn.conv2d(data, weight, kernel_size=(3, 3), padding=(1, 1))\n        add = relay.add(conv2d, bias)\n        relu = relay.nn.relu(add)\n        main_func = relay.Function([data, weight, bias], relu)\n        ref_mod = tvm.IRModule()\n        ref_mod[\"main\"] = main_func\n        ref_mod = transform.InferType()(ref_mod)\n\n        i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n        w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n        b_data = np.random.uniform(0, 1, bshape).astype(dtype)\n\n        return mod, ref_mod, {\"data\": i_data, \"weight\": w1_data, \"bias\": b_data}, (1, 32, 14, 14)\n\n    for mod, ref_mod, input_maps, out_shape in [conv2d_relu(), conv2d_bias_relu()]:\n        check_result(mod, ref_mod, input_maps, out_shape, tol=1e-5)\n\n\ndef test_constant():\n    \"\"\"Test the subgraph with (var, const, ...) arguments.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    wshape = (32, 32, 3, 3)\n\n    data = relay.var(\"data\", shape=ishape, dtype=dtype)\n    weight = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    bn_gamma = relay.var(\"bn_gamma\")\n    bn_beta = relay.var(\"bn_beta\")\n    bn_mmean = relay.var(\"bn_mean\")\n    bn_mvar = relay.var(\"bn_var\")\n\n    layer = relay.nn.conv2d(data=data, weight=weight, kernel_size=(3, 3), padding=(1, 1))\n    bn_output = relay.nn.batch_norm(layer, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n    out = bn_output[0]\n    out = relay.nn.relu(out)\n\n    func = relay.Function(relay.analysis.free_vars(out), out)\n    ref_mod, params = tvm.relay.testing.create_workload(func)\n    ref_mod[\"main\"] = bind_params_by_name(ref_mod[\"main\"], params)\n\n    remove_bn_pass = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.SimplifyInference(),\n            transform.FoldConstant(),\n            transform.FoldScaleAxis(),\n        ]\n    )\n\n    dnnl_patterns = get_pattern_table(\"dnnl\")\n    composite_partition = tvm.transform.Sequential(\n        [\n            transform.MergeComposite(dnnl_patterns),\n            transform.AnnotateTarget(\"dnnl\"),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n        ref_mod = remove_bn_pass(ref_mod)\n        mod = composite_partition(ref_mod)\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    check_result(mod, ref_mod, {\"data\": i_data}, (1, 32, 14, 14), tol=1e-5)\n\n\ndef test_partial_constant():\n    \"\"\"Test the subgraph with (const, var, const, var) arguments.\"\"\"\n    if not tvm.get_global_func(\"runtime.DNNLJSONRuntimeCreate\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (10, 10)\n\n    in_1 = relay.var(\"in_1\", shape=ishape, dtype=dtype)\n    in_2 = relay.var(\"in_2\", shape=ishape, dtype=dtype)\n    in_3 = relay.var(\"in_3\", shape=ishape, dtype=dtype)\n    in_4 = relay.var(\"in_4\", shape=ishape, dtype=dtype)\n\n    add1 = relay.add(in_1, in_2)\n    add2 = relay.add(add1, in_3)\n    add3 = relay.add(add2, in_3)\n    add4 = relay.add(add3, in_3)\n\n    func = relay.Function([in_1, in_2, in_3, in_4], add4)\n    ref_mod = tvm.IRModule.from_expr(func)\n    ref_mod = relay.transform.InferType()(ref_mod)\n\n    data1 = np.random.uniform(0, 1, ishape).astype(dtype)\n    data3 = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    params = {\n        \"in_1\": tvm.nd.array(data1, device=tvm.cpu(0)),\n        \"in_3\": tvm.nd.array(data3, device=tvm.cpu(0)),\n    }\n    ref_mod[\"main\"] = bind_params_by_name(ref_mod[\"main\"], params)\n\n    opt_pass = tvm.transform.Sequential(\n        [\n            transform.InferType(),\n            transform.SimplifyInference(),\n            transform.FoldConstant(),\n            transform.FoldScaleAxis(),\n            transform.AnnotateTarget(\"dnnl\"),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n        mod = opt_pass(ref_mod)\n\n    data2 = np.random.uniform(0, 1, ishape).astype(dtype)\n    data4 = np.random.uniform(0, 1, ishape).astype(dtype)\n    check_result(mod, ref_mod, {\"in_2\": data2, \"in_4\": data4}, (10, 10), tol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n    test_add()\n    test_multiply()\n    test_relu()\n    test_dense()\n    test_bn()\n    test_multiple_ops()\n    test_composite()\n    test_constant()\n    test_partial_constant()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_layer_count.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.relay.testing import resnet\nfrom tvm.relay.analysis import count_layers\n\n\ndef test_layer_count():\n    def verify(num_layers):\n        # Load a resnet with a known number of layers.\n        mod, _ = resnet.get_workload(num_layers=num_layers)\n        # Count the number of conv and dense layers.\n        count = count_layers(mod, valid_ops=[\"nn.conv2d\", \"nn.dense\"])\n        assert count == num_layers\n\n    verify(18)\n    verify(50)\n\n\nif __name__ == \"__main__\":\n    test_layer_count()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_memory_passes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\n\n\ndef check_memory_plan(func, check_fn):\n    # Build Module\n    mod = tvm.IRModule().from_expr(func)\n\n    # Convert arguments.\n    args = []\n    for param in func.params:\n        param = param.type_annotation\n        sh = [int(sh) for sh in param.shape]\n        data = np.random.rand(*sh).astype(param.dtype)\n        args.append(tvm.nd.array(data))\n\n    # TODO(mbs): Why does the executor need to be shared? Seems wrong.\n    ex = relay.create_executor(\"vm\", mod)\n\n    # Compute without memory planning.\n    no_plan_result = ex.evaluate()(*args)\n\n    # Compute with memory planning.\n    with tvm.transform.PassContext(opt_level=1, disabled_pass=[\"MemoryPlan\"]):\n        plan_result = ex.evaluate()(*args)\n\n    # Compute Python result.\n    py_res = check_fn(*[arg.numpy() for arg in args])\n\n    # First check that the two VM results agree.\n    np.testing.assert_allclose(no_plan_result.numpy(), plan_result.numpy())\n\n    # Finally check that the results match the Python result.\n    np.testing.assert_allclose(plan_result.numpy(), py_res)\n\n\ndef storage_type(mod):\n    return relay.TypeCall(mod.get_global_type_var(\"Storage\"), [])\n\n\ndef test_tyck_alloc_storage():\n    mod = tvm.IRModule()\n    mod.import_from_std(\"core.rly\")\n\n\ndef test_tyck_alloc_tensor():\n    mod = tvm.IRModule()\n    mod.import_from_std(\"core.rly\")\n    sto = relay.Var(\"x\", storage_type(mod))\n    sh = relay.const(np.array([1, 2]), dtype=\"int64\")\n    at = relay.op.memory.alloc_tensor(sto, relay.const(0, dtype=\"int64\"), sh)\n    mod[\"main\"] = relay.Function([sto], at)\n    relay.transform.InferType()(mod)\n\n\ndef check_add(x):\n    return x + x\n\n\ndef test_add():\n    x = relay.var(\"x\", shape=(2,))\n    z = x + x\n    func = relay.Function(\n        [\n            x,\n        ],\n        z,\n    )\n    check_memory_plan(func, check_add)\n\n\ndef check_add_sub(x, y):\n    z = x + x\n    return z - y\n\n\ndef test_add_sub():\n    x = relay.var(\"x\", shape=(10,))\n    y = relay.var(\"y\", shape=(10,))\n    z = x + x\n    z = z - y\n    func = relay.Function([x, y], z)\n    check_memory_plan(func, check_add_sub)\n\n\ndef check_no_fuse(x, y, w):\n    z = x + y\n    return np.matmul(z, np.transpose(w))\n\n\ndef test_no_fuse():\n    x = relay.var(\"x\", shape=(5, 1))\n    y = relay.var(\"y\", shape=(5, 1))\n    w = relay.var(\"w\", shape=(5, 1))\n    z = x + y\n    out = relay.op.nn.dense(z, w)\n    func = relay.Function([x, y, w], out)\n    check_memory_plan(func, check_no_fuse)\n\n\nif __name__ == \"__main__\":\n    test_tyck_alloc_tensor()\n    test_add()\n    test_add_sub()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_name_mangling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\n\nimport tvm\nimport tvm.testing\nimport tvm.relay as relay\nimport tvm.relay.backend.utils as utils\nimport pytest\n\n\ndef test_mangle_mod_name():\n    assert utils.mangle_module_name(\"default\") == \"tvmgen_default\"\n    assert utils.mangle_module_name(\"ccompiler\") == \"tvmgen_ccompiler\"\n    assert utils.mangle_module_name(\"1234\"), \"tvmgen_1234\"\n    assert utils.mangle_module_name(\"\"), \"tvmgen\"\n    assert utils.mangle_module_name(None), \"tvmgen\"\n\n    with pytest.raises(ValueError):\n        utils.mangle_module_name(\"\\u018e\")\n        utils.mangle_module_name(\"\\xf1\")\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_name_supply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\n\nfrom tvm import relay\nfrom tvm.ir import GlobalVar, structural_equal\nfrom tvm.ir.supply import NameSupply\nfrom tvm.ir.supply import GlobalVarSupply\n\n\ndef test_name_supply():\n    name_supply = NameSupply(\"prefix\")\n    name_supply.reserve_name(\"test\")\n\n    assert name_supply.contains_name(\"test\")\n    assert name_supply.fresh_name(\"test\") == \"prefix_test_1\"\n    assert name_supply.contains_name(\"test_1\")\n    assert not name_supply.contains_name(\"test_1\", False)\n    assert not name_supply.contains_name(\"test_2\")\n\n\ndef test_global_var_supply_from_none():\n    var_supply = GlobalVarSupply()\n    global_var = GlobalVar(\"test\")\n    var_supply.reserve_global(global_var)\n\n    assert structural_equal(var_supply.unique_global_for(\"test\"), global_var)\n    assert not structural_equal(var_supply.fresh_global(\"test\"), global_var)\n\n\ndef test_global_var_supply_from_name_supply():\n    name_supply = NameSupply(\"prefix\")\n    var_supply = GlobalVarSupply(name_supply)\n    global_var = GlobalVar(\"test\")\n    var_supply.reserve_global(global_var)\n\n    assert structural_equal(var_supply.unique_global_for(\"test\", False), global_var)\n    assert not structural_equal(var_supply.unique_global_for(\"test\"), global_var)\n\n\ndef test_global_var_supply_from_ir_mod():\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    mod = tvm.IRModule()\n    global_var = GlobalVar(\"test\")\n    mod[global_var] = relay.Function([x, y], relay.add(x, y))\n    var_supply = GlobalVarSupply(mod)\n\n    second_global_var = var_supply.fresh_global(\"test\", False)\n\n    assert structural_equal(var_supply.unique_global_for(\"test\", False), global_var)\n    assert not structural_equal(var_supply.unique_global_for(\"test\"), global_var)\n    assert not structural_equal(second_global_var, global_var)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_name_transforms.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\" you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nfrom tvm import TVMError\nfrom tvm.relay.backend.name_transforms import (\n    to_c_function_style,\n    to_c_variable_style,\n    to_c_constant_style,\n    prefix_name,\n    prefix_generated_name,\n)\nfrom tvm.runtime.name_transforms import sanitize_name\n\n\ndef test_to_c_function_style():\n    assert to_c_function_style(\"TVM_Woof\") == \"TVMWoof\"\n    assert to_c_function_style(\"TVM_woof\") == \"TVMWoof\"\n    assert to_c_function_style(\"TVM_woof_woof\") == \"TVMWoofWoof\"\n    assert to_c_function_style(\"TVMGen_woof_woof\") == \"TVMGenWoofWoof\"\n\n    # Incorrect prefix\n    with pytest.raises(TVMError, match=\"Function not TVM prefixed\"):\n        to_c_function_style(\"Cake_Bakery\")\n    with pytest.raises(TVMError, match=\"Function name is empty\"):\n        to_c_function_style(\"\")\n\n\ndef test_to_c_variable_style():\n    assert to_c_variable_style(\"TVM_Woof\") == \"tvm_woof\"\n    assert to_c_variable_style(\"TVM_woof\") == \"tvm_woof\"\n    assert to_c_variable_style(\"TVM_woof_Woof\") == \"tvm_woof_woof\"\n\n    # Incorrect prefix\n    with pytest.raises(TVMError, match=\"Variable not TVM prefixed\"):\n        to_c_variable_style(\"Cake_Bakery\")\n    with pytest.raises(TVMError, match=\"Variable name is empty\"):\n        to_c_variable_style(\"\")\n\n\ndef test_to_c_constant_style():\n    assert to_c_constant_style(\"TVM_Woof\") == \"TVM_WOOF\"\n    assert to_c_constant_style(\"TVM_woof\") == \"TVM_WOOF\"\n    assert to_c_constant_style(\"TVM_woof_Woof\") == \"TVM_WOOF_WOOF\"\n\n    with pytest.raises(TVMError, match=\"Constant not TVM prefixed\"):\n        to_c_constant_style(\"Cake_Bakery\")\n    with pytest.raises(TVMError):\n        to_c_constant_style(\"\")\n\n\ndef test_prefix_name():\n    assert prefix_name(\"Woof\") == \"TVM_Woof\"\n    assert prefix_name([\"Woof\"]) == \"TVM_Woof\"\n    assert prefix_name([\"woof\"]) == \"TVM_woof\"\n    assert prefix_name([\"woof\", \"moo\"]) == \"TVM_woof_moo\"\n\n    with pytest.raises(TVMError, match=\"Name is empty\"):\n        prefix_name(\"\")\n    with pytest.raises(TVMError, match=\"Name segments empty\"):\n        prefix_name([])\n    with pytest.raises(TVMError, match=\"Name segment is empty\"):\n        prefix_name([\"\"])\n\n\ndef test_prefix_generated_name():\n    assert prefix_generated_name(\"Woof\") == \"TVMGen_Woof\"\n    assert prefix_generated_name([\"Woof\"]) == \"TVMGen_Woof\"\n    assert prefix_generated_name([\"Woof\"]) == \"TVMGen_Woof\"\n    assert prefix_generated_name([\"woof\"]) == \"TVMGen_woof\"\n    assert prefix_generated_name([\"woof\", \"moo\"]) == \"TVMGen_woof_moo\"\n\n    with pytest.raises(TVMError, match=\"Name is empty\"):\n        prefix_generated_name(\"\")\n    with pytest.raises(TVMError, match=\"Name segments empty\"):\n        prefix_generated_name([])\n    with pytest.raises(TVMError, match=\"Name segment is empty\"):\n        prefix_generated_name([\"\"])\n\n\ndef test_sanitize_name():\n    assert sanitize_name(\"+_+ \") == \"____\"\n    assert sanitize_name(\"input+\") == \"input_\"\n    assert sanitize_name(\"input-\") == \"input_\"\n    assert sanitize_name(\"input++\") == \"input__\"\n    assert sanitize_name(\"woof:1\") == \"woof_1\"\n\n    with pytest.raises(TVMError, match=\"Name is empty\"):\n        sanitize_name(\"\")\n\n\ndef test_combined_logic():\n    assert (\n        to_c_function_style(prefix_name([\"Device\", \"target\", \"Invoke\"])) == \"TVMDeviceTargetInvoke\"\n    )\n    assert to_c_function_style(prefix_generated_name([\"model\", \"Run\"])) == \"TVMGenModelRun\"\n    assert to_c_variable_style(prefix_name([\"Device\", \"target\", \"t\"])) == \"tvm_device_target_t\"\n    assert (\n        to_c_variable_style(prefix_generated_name([\"model\", \"Devices\"])) == \"tvmgen_model_devices\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_fast_math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport scipy\nfrom scipy import special\nimport tvm\nimport tvm.testing\nimport tvm.relay as relay\nfrom tvm import topi\nfrom tvm import te\nfrom tvm.contrib import graph_executor\nfrom tvm.topi import testing\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\ndef test_fastmath(target, dev):\n    def test_apply(relay_op, name, f_numpy, low, high, step, dtype=\"float32\"):\n        a_np = np.arange(low, high, step).astype(dtype).reshape((1, -1))\n        b_np = f_numpy(a_np)\n\n        x = relay.var(\"x\", shape=a_np.shape, dtype=\"float32\")\n        y = relay_op(x)\n        func = relay.Function([x], y)\n        mod = tvm.IRModule.from_expr(func)\n\n        with tvm.transform.PassContext(opt_level=3, required_pass=[\"FastMath\"]):\n            graph, lib, params = relay.build(mod, target=target, params=None)\n\n        # Check that the op related to fast math have been convered to function in lib\n        func_name = \"tvmgen_default_fused_\" + name\n        # When there're multiple targets in tvm.testing.parametrize_targets, the function\n        # built will have a \"_1\" in function name\n        assert func_name in graph\n\n        m = graph_executor.create(graph, lib, dev)\n        # Set inputs\n        m.set_input(\"x\", tvm.nd.array(a_np, dev))\n        m.set_input(**params)\n        # Execute\n        m.run()\n        # Get outputs\n        tvm_output = m.get_output(0)\n        tvm.testing.assert_allclose(tvm_output.numpy(), b_np, rtol=1e-5, atol=1e-5)\n\n    test_apply(relay.exp, \"fast_exp\", np.exp, low=-88, high=88, step=0.01)\n    test_apply(relay.erf, \"fast_erf\", scipy.special.erf, low=-10, high=10, step=0.01)\n    test_apply(relay.tanh, \"fast_tanh\", np.tanh, low=-10, high=10, step=0.01)\n    test_apply(\n        relay.nn.fast_softmax,\n        \"nn_fast_softmax\",\n        tvm.topi.testing.softmax_python,\n        low=-10,\n        high=10,\n        step=0.01,\n    )\n\n\nif __name__ == \"__main__\":\n    test_fastmath()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_grad_level1.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\n\nfrom tvm import te, relay\nfrom tvm.relay.testing import check_grad, run_infer_type\nfrom tvm.relay.transform import gradient\n\nexecutor_kind = tvm.testing.parameter(\"debug\")\n\n\ndef sigmoid(x):\n    one = np.ones_like(x)\n    return one / (one + np.exp(-x))\n\n\ndef relu(x):\n    x_copy = np.copy(x)\n    np.maximum(x_copy, 0, x_copy)\n    return x_copy\n\n\nclass TestUnaryOp:\n    config = {\n        \"log\": (tvm.relay.log, lambda x, g: g * (1 / x)),\n        \"exp\": (tvm.relay.exp, lambda x, g: g * np.exp(x)),\n        \"sigmoid\": (tvm.relay.sigmoid, lambda x, g: g * sigmoid(x) * (1 - sigmoid(x))),\n        \"tanh\": (tvm.relay.tanh, lambda x, g: g * (1 - np.tanh(x) * np.tanh(x))),\n        \"sqrt\": (tvm.relay.sqrt, lambda x, g: g * 0.5 * np.power(x, -0.5)),\n        \"abs\": (tvm.relay.abs, lambda x, g: np.where(x < 0, -g, g)),\n        \"relu\": (relay.nn.relu, lambda x, g: np.where(x < 0, np.zeros_like(x), g)),\n        \"erf\": (tvm.relay.erf, lambda x, g: g * (2.0 / (np.pi ** (0.5)) * np.exp(-x * x))),\n        \"cos\": (tvm.relay.cos, lambda x, g: g * -1.0 * np.sin(x)),\n        \"sin\": (tvm.relay.sin, lambda x, g: g * np.cos(x)),\n        \"tan\": (tvm.relay.tan, lambda x, g: g * (1.0 / (np.cos(x) ** 2))),\n        \"atan\": (tvm.relay.atan, lambda x, g: g * (1 / (1 + np.power(x, 2.0)))),\n        \"log2\": (tvm.relay.log2, lambda x, g: g * (1 / (np.log(2) * x))),\n        \"log10\": (tvm.relay.log10, lambda x, g: g * (1 / (np.log(10) * x))),\n        \"cosh\": (tvm.relay.cosh, lambda x, g: g * (np.sinh(x))),\n        \"sinh\": (tvm.relay.sinh, lambda x, g: g * (np.cosh(x))),\n        \"asin\": (tvm.relay.asin, lambda x, g: g * (1.0 / (1.0 - x**2) ** (1.0 / 2.0))),\n        \"acos\": (tvm.relay.acos, lambda x, g: g * (-1.0 / (1.0 - x**2.0) ** (1.0 / 2.0))),\n        \"acosh\": (tvm.relay.acosh, lambda x, g: g * (1.0 / (x**2 - 1.0) ** (1.0 / 2.0))),\n        \"asinh\": (tvm.relay.asinh, lambda x, g: g * (1.0 / (x**2 + 1.0) ** (1.0 / 2.0))),\n        \"atanh\": (tvm.relay.atanh, lambda x, g: g * (-1.0 / (x**2 - 1.0))),\n    }\n\n    relay_op, ref_func = tvm.testing.parameters(*config.values(), ids=config.keys())\n    dtype = tvm.testing.parameter(\"float32\", \"float64\")\n    shape = tvm.testing.parameter((10, 4))\n\n    def test_op(self, target, dev, executor_kind, relay_op, ref_func, shape, dtype):\n\n        target = tvm.target.Target(target)\n        if target.kind.name == \"vulkan\":\n\n            known_breaks = {\n                \"float32\": [\n                    tvm.relay.erf,\n                    tvm.relay.tan,\n                    tvm.relay.atan,\n                    tvm.relay.log10,\n                    tvm.relay.cosh,\n                    tvm.relay.sinh,\n                    tvm.relay.asin,\n                    tvm.relay.acos,\n                    tvm.relay.acosh,\n                    tvm.relay.asinh,\n                    tvm.relay.atanh,\n                ],\n                \"float64\": [\n                    tvm.relay.log,\n                    tvm.relay.exp,\n                    tvm.relay.sigmoid,\n                    tvm.relay.tanh,\n                    tvm.relay.sqrt,\n                    tvm.relay.erf,\n                    tvm.relay.cos,\n                    tvm.relay.sin,\n                    tvm.relay.tan,\n                    tvm.relay.atan,\n                    tvm.relay.log2,\n                    tvm.relay.log10,\n                    tvm.relay.cosh,\n                    tvm.relay.sinh,\n                    tvm.relay.asin,\n                    tvm.relay.acos,\n                    tvm.relay.acosh,\n                    tvm.relay.asinh,\n                    tvm.relay.atanh,\n                ],\n            }\n\n            if relay_op in known_breaks[dtype]:\n                pytest.xfail(f\"{dtype} {relay_op.__name__} not yet supported on Vulkan runtime\")\n\n        tp = relay.TensorType(shape, dtype)\n        x = relay.var(\"x\", tp)\n        g = relay.var(\"g\", tp)\n        y = relay_op(x) * g\n\n        fwd_func = relay.Function([x, g], y)\n        fwd_func = run_infer_type(fwd_func)\n        bwd_func = run_infer_type(gradient(fwd_func))\n\n        data_in = np.random.rand(*shape).astype(dtype)\n        grad_in = np.random.rand(*shape).astype(dtype)\n        ref_grad_out = ref_func(data_in, grad_in)\n\n        op_res, (op_grad, _) = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(bwd_func)(data_in, grad_in)\n        np.testing.assert_allclose(op_grad.numpy(), ref_grad_out, rtol=0.01)\n\n\nclass TestBinaryOp:\n    config = {\n        \"add\": (relay.add, lambda x, y: [np.ones_like(x), np.ones_like(y)]),\n        \"subtract\": (relay.subtract, lambda x, y: [np.ones_like(x), -np.ones_like(y)]),\n        \"multiply\": (relay.multiply, lambda x, y: [y, x]),\n        \"divide\": (relay.divide, lambda x, y: [1 / y, -x / (y**2)]),\n    }\n\n    relay_op, ref_func = tvm.testing.parameters(*config.values(), ids=config.keys())\n    dtype = tvm.testing.parameter(\"float32\", \"float64\")\n    shape = tvm.testing.parameter((5, 10, 5))\n\n    def test_binary_op(self, target, dev, executor_kind, relay_op, ref_func, shape, dtype):\n        t = relay.TensorType(shape, dtype=dtype)\n        x = relay.var(\"x\", t)\n        y = relay.var(\"y\", t)\n        z = relay_op(x, y)\n\n        x_data = np.random.rand(*shape).astype(t.dtype)\n        y_data = np.random.rand(*shape).astype(t.dtype)\n        ref_grad0, ref_grad1 = ref_func(x_data, y_data)\n        fwd_func = relay.Function([x, y], z)\n        fwd_func = run_infer_type(fwd_func)\n        bwd_func = run_infer_type(gradient(fwd_func))\n\n        op_res, (op_grad0, op_grad1) = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(bwd_func)(x_data, y_data)\n        np.testing.assert_allclose(op_grad0.numpy(), ref_grad0, rtol=0.01)\n        np.testing.assert_allclose(op_grad1.numpy(), ref_grad1, rtol=0.01)\n\n\ndef test_softmax_grad(executor_kind, target, dev):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\":\n        pytest.xfail(\"Known failure on vulkan\")\n\n    data = relay.var(\"data\", relay.TensorType((1, 16), \"float64\"))\n    fwd_func = relay.Function([data], relay.nn.softmax(data))\n    check_grad(fwd_func, scale=1, target_devices=[(target, dev)], executor_kind=executor_kind)\n\n\ndef test_log_softmax_grad(executor_kind, target, dev):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\":\n        pytest.xfail(\"Known failure on vulkan\")\n\n    data = relay.var(\"data\", relay.TensorType((2, 16), \"float64\"))\n    fwd_func = relay.Function([data], relay.nn.log_softmax(data))\n    check_grad(fwd_func, scale=1, target_devices=[(target, dev)], executor_kind=executor_kind)\n\n\nclass TestBiasAddGrad:\n    d_shape, b_shape, axis = tvm.testing.parameters(\n        ((1, 16), (16,), 1),\n        ((1, 8, 2, 2), (8,), 1),\n        ((1, 2, 2, 8), (8,), 3),\n        ((4, 8), (8,), 1),\n    )\n\n    def test_bias_add(self, executor_kind, target, dev, d_shape, b_shape, axis):\n        data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n        bias = relay.var(\"bias\", relay.TensorType(b_shape, \"float32\"))\n        fwd_func = relay.Function([data, bias], relay.nn.bias_add(data, bias, axis=axis))\n        check_grad(fwd_func, target_devices=[(target, dev)], executor_kind=executor_kind)\n\n\ndef test_expand_dims_grad(executor_kind, target, dev):\n    data = relay.var(\"data\", shape=(2, 3), dtype=\"float64\")\n    fwd_func = relay.Function([data], relay.expand_dims(data, axis=1, num_newaxis=2))\n    check_grad(fwd_func, target_devices=[(target, dev)], executor_kind=executor_kind)\n\n\ndef test_concatenate_grad(executor_kind, target, dev):\n    x = relay.var(\"x\", shape=(2, 2, 5))\n    y = relay.var(\"y\", shape=(2, 1, 5))\n    z = relay.var(\"z\", shape=(2, 4, 5))\n    fwd_func = relay.Function([x, y, z], relay.concatenate([x, y, z], axis=1))\n    check_grad(fwd_func, target_devices=[(target, dev)], executor_kind=executor_kind)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_grad_level10.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\n\nfrom tvm import relay\nfrom tvm.relay.testing import check_grad\n\n\nindex_dtype = tvm.testing.parameter(\"int32\", \"int64\")\nval_dtype = tvm.testing.parameter(\"float32\", \"float64\")\nexecutor_kind = tvm.testing.parameter(\"debug\")\n\n\ndef test_cross_entropy_grad(executor_kind, target, dev, val_dtype):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\" and val_dtype == \"float64\":\n        # GLSL.std.450's Log implementation only takes 16/32-bit floats.\n        pytest.xfail(\"Known failing test case for vulkan runtime\")\n\n    x = relay.var(\"x\", shape=(2, 5), dtype=val_dtype)\n    y = relay.var(\"y\", shape=(2, 5), dtype=val_dtype)\n    check_grad(\n        relay.Function([x, y], relay.op.nn.cross_entropy(x, y)),\n        eps=0.01,\n        scale=0.1,\n        mean=1,\n        target_devices=[(target, dev)],\n        executor_kind=executor_kind,\n    )\n\n\ndef test_cross_entropy_with_logits_grad(executor_kind, target, dev, val_dtype):\n    x = relay.var(\"x\", shape=(2, 5), dtype=val_dtype)\n    y = relay.var(\"y\", shape=(2, 5), dtype=val_dtype)\n    check_grad(\n        relay.Function([x, y], relay.op.nn.cross_entropy_with_logits(x, y)),\n        eps=0.01,\n        scale=0.1,\n        mean=1,\n        target_devices=[(target, dev)],\n        executor_kind=executor_kind,\n    )\n\n\ndef test_checkpoint(executor_kind, target, dev):\n    inputs = [relay.var(\"x{}\".format(i), shape=(1,)) for i in range(4)]\n    output = relay.multiply(relay.add(inputs[0], inputs[1]), relay.add(inputs[2], inputs[3]))\n    check_grad(\n        relay.Function(inputs, relay.annotation.checkpoint(output)), executor_kind=executor_kind\n    )\n\n    scope = relay.ScopeBuilder()\n    out_tuple = scope.let(\n        \"out_tuple\",\n        relay.Tuple([relay.add(inputs[0], inputs[1]), relay.multiply(inputs[2], inputs[3])]),\n    )\n    scope.ret(\n        relay.subtract(\n            relay.annotation.checkpoint(relay.TupleGetItem(out_tuple, 0)),\n            relay.TupleGetItem(out_tuple, 1),\n        )\n    )\n    out_single = scope.get()\n    check_grad(\n        relay.Function(inputs, out_single),\n        target_devices=[(target, dev)],\n        executor_kind=executor_kind,\n    )\n\n\nclass TestBatchMatmulGrad:\n    a_shape, b_shape, transpose_a, transpose_b = tvm.testing.parameters(\n        ((2, 3, 5), (2, 5, 4), False, False),\n        ((2, 3, 5), (2, 4, 5), False, True),\n        ((2, 5, 3), (2, 5, 4), True, False),\n        ((2, 5, 3), (2, 4, 5), True, True),\n    )\n\n    def test_batch_matmul_grad(\n        self, executor_kind, target, dev, a_shape, b_shape, transpose_a, transpose_b\n    ):\n        tensor_a = relay.var(\"tensor_a\", relay.TensorType(a_shape, \"float32\"))\n        tensor_b = relay.var(\"tensor_b\", relay.TensorType(b_shape, \"float32\"))\n        check_grad(\n            relay.Function(\n                [tensor_a, tensor_b],\n                relay.op.nn.batch_matmul(\n                    tensor_a, tensor_b, transpose_a=transpose_a, transpose_b=transpose_b\n                ),\n            ),\n            target_devices=[(target, dev)],\n            executor_kind=executor_kind,\n        )\n\n\ndef test_reverse_reshape_grad(executor_kind, target, dev):\n    x = relay.var(\"x\", shape=(3, 4, 5), dtype=\"float64\")\n    check_grad(\n        relay.Function([x], relay.op.reverse_reshape(x, (-1, 0))),\n        target_devices=[(target, dev)],\n        executor_kind=executor_kind,\n    )\n\n\ndef test_one_hot_grad(executor_kind, target, dev, index_dtype, val_dtype):\n    indices_shape = (3, 4)\n    depth = 5\n    axis = -1\n\n    inputs = [\n        np.random.randint(depth, size=indices_shape, dtype=index_dtype),\n        np.array(np.random.randn() * 1e-5).astype(val_dtype),\n        np.array(np.random.randn() * 1e-5).astype(val_dtype),\n    ]\n    test_inputs = inputs[1:]\n\n    indices = relay.var(\"indices\", shape=indices_shape, dtype=index_dtype)\n    on_val = relay.var(\"on_val\", shape=tuple(), dtype=val_dtype)\n    off_val = relay.var(\"off_val\", shape=tuple(), dtype=val_dtype)\n    y = relay.one_hot(indices, on_val, off_val, depth, axis, val_dtype)\n    f = relay.Function([indices, on_val, off_val], y)\n\n    check_grad(\n        f,\n        inputs=inputs,\n        test_inputs=test_inputs,\n        target_devices=[(target, dev)],\n        executor_kind=executor_kind,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_grad_level2.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nfrom tvm import topi\nimport tvm.topi.testing\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.testing import check_grad, run_infer_type, run_opt_pass\nfrom tvm.relay.transform import gradient\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"debug\")\n\n\ndef verify_max_pool2d_grad(executor_kind, x_shape, pool_size, strides, padding, ceil_mode):\n    x = relay.var(\"x\", relay.TensorType(x_shape, \"float32\"))\n    y = tvm.relay.nn.max_pool2d(\n        x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode\n    )\n\n    fwd_func = relay.Function([x], y)\n    fwd_func = run_infer_type(fwd_func)\n    bwd_func = run_infer_type(gradient(fwd_func))\n\n    data = np.random.rand(*x_shape).astype(\"float32\")\n    ph, pw = padding\n    y_shape = topi.utils.get_const_tuple(fwd_func.ret_type.shape)\n    out_grad = np.ones(shape=y_shape)\n    ref_grad = tvm.topi.testing.pool_grad_nchw(\n        data,\n        out_grad,\n        pool_size=pool_size,\n        strides=strides,\n        padding=[ph, pw, ph, pw],\n        pool_type=\"max\",\n        ceil_mode=ceil_mode,\n    )\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res, (op_grad,) = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(bwd_func)(data)\n        np.testing.assert_allclose(op_grad.numpy(), ref_grad, rtol=0.01)\n\n\n@tvm.testing.uses_gpu\ndef test_max_pool2d_grad(executor_kind):\n    verify_max_pool2d_grad(\n        executor_kind,\n        (1, 4, 16, 16),\n        pool_size=(2, 2),\n        strides=(2, 2),\n        padding=(0, 0),\n        ceil_mode=False,\n    )\n    verify_max_pool2d_grad(\n        executor_kind,\n        (1, 4, 16, 16),\n        pool_size=(1, 1),\n        strides=(1, 1),\n        padding=(1, 1),\n        ceil_mode=False,\n    )\n\n\ndef verify_avg_pool2d_grad(\n    x_shape,\n    pool_size,\n    strides,\n    padding,\n    ceil_mode,\n    count_include_pad,\n    executor_kind,\n    dtype=\"float32\",\n):\n\n    for shape_dtype in [\"int32\", \"int64\"]:\n        x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in x_shape], dtype=dtype)\n        y = tvm.relay.nn.avg_pool2d(\n            x,\n            pool_size=pool_size,\n            strides=strides,\n            padding=padding,\n            ceil_mode=ceil_mode,\n            count_include_pad=count_include_pad,\n        )\n\n        fwd_func = relay.Function([x], y)\n        fwd_func = run_infer_type(fwd_func)\n        bwd_func = run_infer_type(gradient(fwd_func))\n\n        data = np.random.rand(*x_shape).astype(dtype)\n        ph, pw = padding\n        y_shape = topi.utils.get_const_tuple(fwd_func.ret_type.shape)\n        out_grad = np.ones(shape=y_shape)\n        ref_grad = tvm.topi.testing.pool_grad_nchw(\n            data,\n            out_grad,\n            pool_size=pool_size,\n            strides=strides,\n            padding=[ph, pw, ph, pw],\n            pool_type=\"avg\",\n            ceil_mode=ceil_mode,\n        )\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res, (op_grad,) = relay.create_executor(\n                executor_kind, device=dev, target=target\n            ).evaluate(bwd_func)(data)\n            np.testing.assert_allclose(op_grad.numpy(), ref_grad, rtol=0.01)\n\n\n@tvm.testing.uses_gpu\ndef test_avg_pool2d_grad(executor_kind):\n    verify_avg_pool2d_grad(\n        (1, 4, 16, 16),\n        pool_size=(2, 2),\n        strides=(2, 2),\n        padding=(0, 0),\n        ceil_mode=False,\n        count_include_pad=True,\n        executor_kind=executor_kind,\n    )\n    verify_avg_pool2d_grad(\n        (1, 4, 16, 16),\n        pool_size=(1, 1),\n        strides=(1, 1),\n        padding=(1, 1),\n        ceil_mode=False,\n        count_include_pad=False,\n        executor_kind=executor_kind,\n    )\n    verify_avg_pool2d_grad(\n        (1, 4, 16, 16),\n        pool_size=(1, 1),\n        strides=(1, 1),\n        padding=(1, 1),\n        ceil_mode=False,\n        count_include_pad=False,\n        executor_kind=executor_kind,\n        dtype=\"int32\",\n    )\n\n\ndef verify_global_avg_pool2d_grad(executor_kind, x_shape):\n    x = relay.var(\"x\", relay.TensorType(x_shape, \"float32\"))\n    y = tvm.relay.nn.global_avg_pool2d(x)\n\n    fwd_func = relay.Function([x], y)\n    fwd_func = run_infer_type(fwd_func)\n    bwd_func = run_infer_type(gradient(fwd_func))\n\n    data = np.random.rand(*x_shape).astype(\"float32\")\n    y_shape = topi.utils.get_const_tuple(fwd_func.ret_type.shape)\n    out_grad = np.ones(shape=y_shape)\n    ref_grad = tvm.topi.testing.pool_grad_nchw(\n        data,\n        out_grad,\n        pool_size=(x_shape[2], x_shape[3]),\n        strides=(1, 1),\n        padding=[0, 0, 0, 0],\n        pool_type=\"avg\",\n        ceil_mode=False,\n    )\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res, (op_grad,) = relay.create_executor(\n            executor_kind, device=dev, target=target\n        ).evaluate(bwd_func)(data)\n        np.testing.assert_allclose(op_grad.numpy(), ref_grad, rtol=0.01)\n\n\n@tvm.testing.uses_gpu\ndef test_global_avg_pool2d_grad(executor_kind):\n    verify_global_avg_pool2d_grad(executor_kind, (1, 4, 16, 16))\n    verify_global_avg_pool2d_grad(executor_kind, (1, 8, 8, 24))\n\n\ndef verify_conv2d_grad(\n    dshape, wshape, strides, padding, dilation, groups=1, mode=\"higher_order\", executor_kind=\"vm\"\n):\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=dshape, dtype=dtype)\n    weight = relay.var(\"weight\", shape=wshape, dtype=dtype)\n    conv = relay.nn.conv2d(\n        data,\n        weight,\n        strides=strides,\n        padding=padding,\n        dilation=dilation,\n        groups=groups,\n        out_dtype=dtype,\n    )\n    fwd_func = relay.Function([data, weight], conv)\n    check_grad(fwd_func, mode=mode, executor_kind=executor_kind)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_grad(executor_kind):\n    verify_conv2d_grad(\n        (1, 4, 16, 16), (16, 4, 3, 3), [1, 1], [1, 1], [1, 1], executor_kind=executor_kind\n    )\n    verify_conv2d_grad(\n        (1, 4, 16, 16), (16, 4, 1, 1), [1, 1], [0, 0], [1, 1], executor_kind=executor_kind\n    )\n    verify_conv2d_grad(\n        (1, 4, 16, 16), (16, 4, 1, 1), [2, 2], [0, 0], [1, 1], executor_kind=executor_kind\n    )\n    verify_conv2d_grad(\n        (1, 4, 16, 16),\n        (16, 4, 3, 3),\n        [1, 1],\n        [1, 1],\n        [1, 1],\n        mode=\"first_order\",\n        executor_kind=executor_kind,\n    )\n\n\ndef verify_dense_grad(d_shape, w_shape, executor_kind):\n    data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n    weight = relay.var(\"weight\", relay.TensorType(w_shape, \"float32\"))\n    fwd_func = relay.Function([data, weight], relay.nn.dense(data, weight))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_dense_grad(executor_kind):\n    verify_dense_grad((1, 8), (16, 8), executor_kind)\n    verify_dense_grad((1, 4), (3, 4), executor_kind)\n    verify_dense_grad((5, 4), (3, 4), executor_kind)\n\n\ndef verify_matmul_grad(a_shape, b_shape, transpose_a, transpose_b, executor_kind):\n    tensor_a = relay.var(\"tensor_a\", relay.TensorType(a_shape, \"float32\"))\n    tensor_b = relay.var(\"tensor_b\", relay.TensorType(b_shape, \"float32\"))\n    fwd_func = relay.Function(\n        [tensor_a, tensor_b],\n        relay.nn.matmul(tensor_a, tensor_b, transpose_a=transpose_a, transpose_b=transpose_b),\n    )\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_matmul_grad(executor_kind):\n    verify_matmul_grad((1, 8), (8, 16), False, False, executor_kind)\n    verify_matmul_grad((4, 1), (4, 3), True, False, executor_kind)\n    verify_matmul_grad((4, 5), (3, 4), True, True, executor_kind)\n\n\ndef verify_batch_flatten_grad(d_shape, executor_kind):\n    data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n    fwd_func = relay.Function([data], relay.nn.batch_flatten(data))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_batch_flatten_grad(executor_kind):\n    verify_batch_flatten_grad((1, 2, 3, 4), executor_kind)\n    verify_batch_flatten_grad((1, 8), executor_kind)\n\n\ndef verify_conv2d_backward_weight(\n    executor_kind, dy_shape, x_shape, kernel_size, stride, padding, groups=1, out_channels=None\n):\n    dtype = \"float32\"\n    dy = relay.var(\"dy\", shape=dy_shape, dtype=dtype)\n    x = relay.var(\"x\", shape=x_shape, dtype=dtype)\n    dw_func = relay.Function(\n        [dy, x],\n        relay.nn.conv2d_backward_weight(\n            dy,\n            x,\n            strides=stride,\n            padding=padding,\n            kernel_size=kernel_size,\n            groups=groups,\n            channels=out_channels,\n            out_dtype=dtype,\n        ),\n    )\n\n    dw_func_legalized = run_opt_pass(dw_func, relay.transform.Legalize())\n\n    for dw, target in [(dw_func_legalized, \"llvm\"), (dw_func, \"cuda -libs=cudnn\")]:\n        if \"cudnn\" in target and not tvm.contrib.cudnn.exists():\n            continue\n\n        dev = tvm.device(target, 0)\n        dy_np = np.random.randn(*dy_shape).astype(dtype)\n        x_np = np.random.randn(*x_shape).astype(dtype)\n\n        dw_np = (\n            relay.create_executor(executor_kind, device=dev, target=target)\n            .evaluate(dw)(dy_np, x_np)\n            .numpy()\n        )\n        ref_dw_np = tvm.topi.testing.conv2d_backward_weight_python(\n            dy_np, x_np, kernel_size, stride, padding, groups=groups, channels=out_channels\n        )\n\n        np.testing.assert_allclose(dw_np, ref_dw_np, rtol=1e-4, atol=1e-4)\n\n\ndef test_conv2d_backward_weight(executor_kind):\n    verify_conv2d_backward_weight(\n        executor_kind, (2, 8, 32, 32), (2, 4, 32, 32), (3, 3), (1, 1), (1, 1)\n    )\n    verify_conv2d_backward_weight(\n        executor_kind, (2, 16, 15, 15), (2, 3, 32, 32), (3, 3), (2, 2), (0, 0)\n    )\n    verify_conv2d_backward_weight(\n        executor_kind,\n        (1, 16, 32, 32),\n        (1, 16, 32, 32),\n        (3, 3),\n        (1, 1),\n        (1, 1),\n        groups=16,\n        out_channels=16,\n    )\n\n\ndef test_conv2d_backward_weight_infer_type():\n    # From https://github.com/apache/tvm/pull/10439\n    depthwise_conv_code = \"\"\"\n    fn (%input0: Tensor[(1, 3, 32, 32), float32], %v0_weight: Tensor[(3, 1, 3, 3), float32], %v0_bias: Tensor[(3), float32]) {\n      %0 = nn.conv2d(%input0, %v0_weight, padding=[1, 1, 1, 1], groups=3, channels=3, kernel_size=[3, 3]);\n      nn.bias_add(%0, %v0_bias)\n    }\n    \"\"\"\n\n    normal_conv_code = \"\"\"\n    fn (%input0: Tensor[(1, 3, 32, 32), float32], %v0_weight: Tensor[(3, 3, 3, 3), float32], %v0_bias: Tensor[(3), float32]) {\n      %0 = nn.conv2d(%input0, %v0_weight, padding=[1, 1, 1, 1], groups=1, channels=3, kernel_size=[3, 3]);\n      nn.bias_add(%0, %v0_bias)\n    }\n    \"\"\"\n\n    SEMVER = '#[version = \"0.0.5\"]\\n'\n\n    for code in [normal_conv_code, depthwise_conv_code]:\n        expr = tvm.parser.parse_expr(SEMVER + code)\n        fmod = tvm.IRModule.from_expr(expr)\n\n        mod = relay.transform.InferType()(fmod)\n        bwd_expr = relay.transform.gradient(mod[\"main\"], mode=\"first_order\")\n\n        bwd_mod = tvm.IRModule.from_expr(bwd_expr)\n        bwd_mod = relay.transform.InferType()(bwd_mod)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_grad_level3.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.testing import check_grad, run_infer_type, run_opt_pass, _np_randn_from_type\nfrom tvm.relay.transform import gradient\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"debug\")\n\n\n@tvm.testing.uses_gpu\ndef test_clip(executor_kind):\n    for dtype in (\"float32\", \"float64\"):\n        ref = lambda x: np.where(\n            x > 10.0, np.zeros_like(x), np.where(x < 1.0, np.zeros_like(x), np.ones_like(x))\n        )\n        x = relay.var(\"x\", relay.TensorType((10, 4), dtype))\n        y = tvm.relay.clip(x, 1.0, 10.0)\n\n        data = np.random.rand(10, 4).astype(dtype) * 11.0\n        ref_grad = ref(data)\n        fwd_func = relay.Function([x], y)\n        fwd_func = run_infer_type(fwd_func)\n        bwd_func = run_infer_type(gradient(fwd_func))\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res, (op_grad,) = relay.create_executor(\n                executor_kind, device=dev, target=target\n            ).evaluate(bwd_func)(data)\n            np.testing.assert_allclose(op_grad.numpy(), ref_grad, rtol=0.01)\n\n\ndef verify_transpose_grad(d_shape, axes=None, executor_kind=\"vm\"):\n    data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n    fwd_func = relay.Function([data], relay.transpose(data, axes=axes))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_transpose_grad(executor_kind):\n    verify_transpose_grad((1, 2, 3, 4), executor_kind=executor_kind)\n    verify_transpose_grad((1, 2, 3, 4), axes=(0, 2, 3, 1), executor_kind=executor_kind)\n\n\ndef test_negative_grad(executor_kind):\n    data = relay.var(\"data\", relay.TensorType((10, 4), \"float32\"))\n    fwd_func = relay.Function([data], relay.negative(data))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_cast_grad(executor_kind):\n    data = relay.var(\"data\", relay.TensorType((10, 4), \"float32\"))\n    fwd_func = relay.Function([data], relay.cast(data, \"float64\"))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_cast_like_grad(executor_kind):\n    data = relay.var(\"data\", shape=(10, 4), dtype=\"float32\")\n    like = relay.var(\"like\", shape=(1,), dtype=\"float64\")\n    fwd_func = relay.Function([data, like], relay.cast_like(data, like))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_copy_grad(executor_kind):\n    data = relay.var(\"data\", relay.TensorType((10, 4), \"float64\"))\n    fwd_func = relay.Function([data], relay.copy(data))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_take_grad(executor_kind):\n    data_dtype = relay.TensorType((3, 4, 5), \"float64\")\n    data = relay.var(\"data\", data_dtype)\n    indices = relay.var(\"indices\", relay.TensorType((relay.Any(),), \"int32\"))\n    inputs = [_np_randn_from_type(data_dtype, scale=1e-5), np.array([1, 2], dtype=\"int32\")]\n    test_inputs = [inputs[0]]\n\n    # take on axis\n    fwd_func = relay.Function([data, indices], relay.take(data, indices, axis=1))\n    check_grad(fwd_func, inputs=inputs, test_inputs=test_inputs, executor_kind=executor_kind)\n\n    # take on flattened\n    fwd_func = relay.Function([data, indices], relay.take(data, indices, axis=None))\n    check_grad(fwd_func, inputs=inputs, test_inputs=test_inputs, executor_kind=executor_kind)\n\n\ndef test_stack_grad(executor_kind):\n    args = [relay.var(c, shape=(2, 3, 4), dtype=\"float64\") for c in \"xyz\"]\n    fwd_func = relay.Function(args, relay.stack(args, axis=0))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_squeeze_grad(executor_kind):\n    data = relay.var(\"data\", shape=(2, 1, 1, 3, 4, 1), dtype=\"float64\")\n    fwd_func = relay.Function([data], relay.squeeze(data))\n    fwd_func_subset = relay.Function([data], relay.squeeze(data, axis=[1, -1]))\n    check_grad(fwd_func, executor_kind=executor_kind)\n    check_grad(fwd_func_subset, executor_kind=executor_kind)\n\n\ndef test_arange_grad(executor_kind):\n    # TODO: testing arange numerically is strange because two-sided approx can\n    #       produce different output shapes\n    dtype = \"float64\"\n    start = relay.var(\"start\", relay.TensorType((), dtype))\n    stop = relay.var(\"stop\", relay.TensorType((), dtype))\n    step = relay.var(\"step\", relay.TensorType((), dtype))\n    values = [np.array(v, dtype=dtype) for v in [2.5, 9.5, 1.8]]\n    fwd_func = relay.Function([start, stop, step], relay.arange(start, stop, step, dtype))\n    check_grad(fwd_func, inputs=values, executor_kind=executor_kind)\n\n\ndef test_gather_nd_grad(executor_kind):\n    data = relay.var(\"data\", relay.TensorType((2, 3), \"float64\"))\n    indices = relay.var(\"indices\", relay.TensorType((2, 4), \"int64\"))\n    fwd = relay.Function([data, indices], relay.gather_nd(data, indices))\n    data_np = np.random.rand(2, 3).astype(\"float64\")\n    indices_np = np.array([[0, 1, 1, 0], [0, 1, 0, 0]], dtype=\"int64\")\n    check_grad(\n        fwd, inputs=[data_np, indices_np], test_inputs=[data_np], executor_kind=executor_kind\n    )\n\n\ndef test_reshape_like_grad(executor_kind):\n    data = relay.var(\"data\", shape=(2, 3, 4), dtype=\"float32\")\n    shape_like = relay.var(\"shape_like\", shape=(6, 2, 2), dtype=\"float32\")\n    fwd_func = relay.Function([data, shape_like], relay.reshape_like(data, shape_like))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_zeros_ones_grad_const_ints():\n    # when shape is static (i.e. not an input), there is no gradient at all\n    static_ty = relay.TensorType([2, 3, 4], dtype=\"float32\")\n    expected_ty = relay.TupleType([static_ty, relay.TupleType([])])\n\n    for op in [relay.zeros, relay.ones]:\n        fwd_func = relay.Function([], op(static_ty.concrete_shape, static_ty.dtype))\n        bwd_func = run_infer_type(gradient(run_infer_type(fwd_func)))\n        tvm.ir.assert_structural_equal(bwd_func.ret_type, expected_ty)\n\n\ndef test_zeros_ones_grad_const_expr():\n    # when shape is static (i.e. not an input), there is no gradient at all\n    shape_const = relay.const(np.array([2, 3, 4]), dtype=\"int32\") * relay.const(1, dtype=\"int32\")\n    static_ty = relay.TensorType([2, 3, 4], dtype=\"float32\")\n    dyn_ty = relay.TensorType([relay.Any(), relay.Any(), relay.Any()], dtype=\"float32\")\n    expected_ty_static = relay.TupleType([static_ty, relay.TupleType([])])\n    expected_ty_dyn = relay.TupleType([dyn_ty, relay.TupleType([])])\n\n    for op in [relay.zeros, relay.ones]:\n        # with DynamicToStatic, the shape should be concretized\n        fwd_func = relay.Function([], op(shape_const, static_ty.dtype))\n        fwd_func = run_opt_pass(fwd_func, relay.transform.DynamicToStatic())\n        bwd_func = run_infer_type(gradient(run_infer_type(fwd_func)))\n        tvm.ir.assert_structural_equal(bwd_func.ret_type, expected_ty_static)\n\n        fwd_func = relay.Function([], op(shape_const, static_ty.dtype))\n        bwd_func = run_infer_type(gradient(run_infer_type(fwd_func)))\n        tvm.ir.assert_structural_equal(bwd_func.ret_type, expected_ty_dyn)\n\n\ndef test_zeros_ones_grad_dynamic(executor_kind):\n    rank = np.random.randint(low=1, high=5, dtype=\"int32\")\n    dyn_shape = np.random.randint(low=1, high=4, size=(rank,), dtype=\"int32\")\n    shape_data = relay.var(\"shape_data\", shape=(rank,), dtype=\"int32\")\n\n    for op, op_ref in [(relay.zeros, np.zeros), (relay.ones, np.ones)]:\n        fwd_func = relay.Function([shape_data], op(shape_data, dtype=\"float32\"))\n        bwd_func = run_infer_type(gradient(run_infer_type(fwd_func)))\n\n        for target, dev in tvm.testing.enabled_targets():\n            res, (grad,) = relay.create_executor(executor_kind, device=dev, target=target).evaluate(\n                bwd_func\n            )(dyn_shape)\n            tvm.testing.assert_allclose(res.numpy(), op_ref(dyn_shape, dtype=\"float32\"))\n            tvm.testing.assert_allclose(grad.numpy(), np.zeros((rank,), dtype=\"int32\"))\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_grad_level4.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport numpy as np\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.testing import check_grad, _np_randn_from_type\n\nexecutor_kind = tvm.testing.parameter(\"debug\")\n\n\ndef verify_reduction_grad(executor_kind, red_fn, d_shape, axis=None, keepdims=False, exclude=False):\n    data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n    fwd_func = relay.Function([data], red_fn(data, axis=axis, keepdims=keepdims, exclude=exclude))\n    check_grad(fwd_func, executor_kind=executor_kind)\n\n\ndef test_reduction_grad(executor_kind):\n    def _unbiased_variance(x, axis=None, keepdims=False, exclude=False):\n        return relay.variance(x, axis=axis, keepdims=keepdims, exclude=exclude, unbiased=True)\n\n    for op in (relay.sum, relay.variance, _unbiased_variance, relay.mean):\n        verify_reduction_grad(executor_kind, op, (4, 2))\n        verify_reduction_grad(executor_kind, op, (4, 2), axis=-1, keepdims=True)\n        verify_reduction_grad(executor_kind, op, (4, 2, 1), axis=(1, 2), exclude=True)\n        verify_reduction_grad(executor_kind, op, (4, 2, 1), axis=1)\n\n\ndef verify_max_grad(executor_kind, d_shape, axis=None, keepdims=False, exclude=False):\n    data = relay.var(\"data\", relay.TensorType(d_shape, \"float32\"))\n    fwd_func = relay.Function(\n        [data], relay.max(data, axis=axis, keepdims=keepdims, exclude=exclude)\n    )\n    check_grad(fwd_func, scale=1e-3, executor_kind=executor_kind)\n\n\ndef test_max_grad(executor_kind):\n    verify_max_grad(executor_kind, (10, 10), axis=None)\n    verify_max_grad(executor_kind, (10, 10), axis=-1)\n    verify_max_grad(executor_kind, (6, 3, 2), axis=(1, 2), keepdims=True)\n    verify_max_grad(executor_kind, (5, 4, 3), axis=(0, 2), exclude=True)\n\n\ndef test_where_grad(executor_kind):\n    cond_type = relay.TensorType((2, 3, 4), \"int32\")\n    lhs_type = relay.TensorType((1, 3, 4), \"float32\")\n    rhs_type = relay.TensorType((2, 1, 4), \"float32\")\n    inputs = [\n        np.random.randint(2, size=cond_type.concrete_shape, dtype=cond_type.dtype),\n        _np_randn_from_type(lhs_type, scale=1e-5),\n        _np_randn_from_type(rhs_type, scale=1e-5),\n    ]\n\n    cond = relay.var(\"cond\", type_annotation=cond_type)\n    lhs = relay.var(\"lhs\", type_annotation=lhs_type)\n    rhs = relay.var(\"rhs\", type_annotation=rhs_type)\n    fwd_func = relay.Function([cond, lhs, rhs], relay.where(cond, lhs, rhs))\n    check_grad(fwd_func, inputs=inputs, test_inputs=inputs[1:], executor_kind=executor_kind)\n\n\ndef test_less_equal_grad(executor_kind):\n    x_type = relay.TensorType((2, 3, 4), \"float32\")\n    y_type = relay.TensorType((3, 1), \"float32\")\n    # We need to generate inputs far apart to get correct numerical gradients\n    # (otherwise adding epsilon may change comparison result). The gradient\n    # should always be zero for both inputs.\n    inputs = [\n        np.random.choice([-1, 1], size=x_type.concrete_shape).astype(x_type.dtype),\n        np.random.choice([-2, 2], size=y_type.concrete_shape).astype(y_type.dtype),\n    ]\n\n    x = relay.var(\"x\", type_annotation=x_type)\n    y = relay.var(\"y\", type_annotation=y_type)\n    fwd_func = relay.Function([x, y], relay.less_equal(x, y))\n    check_grad(fwd_func, inputs=inputs, test_inputs=inputs, eps=1e-6, executor_kind=executor_kind)\n\n\ndef test_not_equal_grad(executor_kind):\n    x_type = relay.TensorType((2, 3, 4), \"float32\")\n    y_type = relay.TensorType((3, 1), \"float32\")\n    # We need to generate inputs far apart to get correct numerical gradients\n    # (otherwise adding epsilon may change comparison result). The gradient\n    # should always be zero for both inputs.\n    inputs = [\n        np.random.choice([-1, 1], size=x_type.concrete_shape).astype(x_type.dtype),\n        np.random.choice([-2, 2], size=y_type.concrete_shape).astype(y_type.dtype),\n    ]\n\n    x = relay.var(\"x\", type_annotation=x_type)\n    y = relay.var(\"y\", type_annotation=y_type)\n    fwd_func = relay.Function([x, y], relay.not_equal(x, y))\n    check_grad(fwd_func, inputs=inputs, test_inputs=inputs, eps=1e-6, executor_kind=executor_kind)\n\n\ndef test_strided_slice_grad(executor_kind):\n    def check(sh, dtype, begin, end, strides, slice_mode):\n        x = relay.var(\"x\", shape=sh, dtype=dtype)\n        f = relay.Function(\n            [x],\n            relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=slice_mode),\n        )\n        check_grad(f, executor_kind=executor_kind)\n\n    check((2, 3, 4), \"float32\", (0, 1, 0), (-1, -1, 1), (1, 1, 1), \"size\")\n    check((2, 3, 4), \"float32\", (0, 1, 0), (2, 3, 1), (1, 1, 1), \"end\")\n    # check that strides are properly ignored when using \"size\" mode\n    check((2, 3, 4), \"float32\", (0, 0, 0), (-1, -1, -1), (1, 1, 2), \"size\")\n    check((2, 3, 4), \"float32\", (0, 0, 0), (2, 3, 4), (1, 1, 2), \"end\")\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level1.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nimport scipy\nfrom tvm import relay\nimport pytest\nfrom tvm.relay.testing import run_infer_type\nimport tvm.topi.testing\nfrom tvm.contrib.nvcc import have_fp16\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\ndef sigmoid(x):\n    one = np.ones_like(x)\n    return one / (one + np.exp(-x))\n\n\ndef relu(x):\n    x_copy = np.copy(x)\n    np.maximum(x_copy, 0, x_copy)\n    return x_copy\n\n\ndef rsqrt(x):\n    one = np.ones_like(x)\n    return one / np.sqrt(x)\n\n\nclass TestUnaryOp:\n    # Tuple of (operator, reference op, supports fp16)\n    op_list = {\n        \"log\": (tvm.relay.log, np.log, True),\n        \"exp\": (tvm.relay.exp, np.exp, True),\n        \"erf\": (tvm.relay.erf, scipy.special.erf, True),\n        \"sqrt\": (tvm.relay.sqrt, np.sqrt, True),\n        \"rqsrt\": (tvm.relay.rsqrt, rsqrt, True),\n        \"sigmoid\": (tvm.relay.sigmoid, sigmoid, True),\n        \"tanh\": (tvm.relay.tanh, np.tanh, False),\n        \"relu\": (relay.nn.relu, relu, True),\n        \"cos\": (tvm.relay.cos, np.cos, True),\n        \"sin\": (tvm.relay.sin, np.sin, True),\n        \"tan\": (tvm.relay.tan, np.tan, False),\n        \"atan\": (tvm.relay.atan, np.arctan, False),\n        \"ceil\": (tvm.relay.ceil, np.ceil, True),\n        \"floor\": (tvm.relay.floor, np.floor, True),\n        \"trunc\": (tvm.relay.trunc, np.trunc, True),\n        \"round\": (tvm.relay.round, np.round, False),\n    }\n\n    dtype = tvm.testing.parameter(\"float16\", \"float32\")\n\n    relay_op, ref_func, supports_fp16 = tvm.testing.parameters(\n        *op_list.values(), ids=op_list.keys()\n    )\n\n    def test_unary_op(self, target, dev, relay_op, ref_func, supports_fp16, dtype):\n        target = tvm.target.Target(target)\n        if dtype == \"float16\":\n            if target.kind.name == \"cuda\":\n                if not have_fp16(tvm.cuda(0).compute_version):\n                    pytest.xfail(\n                        \"No float16 support on local cuda device (compute_version != 5.3 and < 6.0)\"\n                    )\n            elif target.kind.name == \"vulkan\" and not target.attrs.get(\"supports_float16\", False):\n                pytest.xfail(\"No float16 support on vulkan target (supports_float16=False)\")\n            elif not supports_fp16:\n                pytest.xfail(f\"No float16 support on {target.kind.name} target\")\n\n        if target.kind.name == \"vulkan\" and relay_op in [\n            tvm.relay.erf,\n            tvm.relay.tan,\n            tvm.relay.atan,\n        ]:\n            pytest.xfail(f\"Vulkan runtime doesn't yet support {relay_op}\")\n\n        shape = (10, 4)\n        dtype = dtype\n        tp = relay.TensorType(shape, dtype=dtype)\n        x = relay.var(\"x\", type_annotation=tp)\n        y = relay_op(x)\n        # test printer\n        assert (\"{}(%x)\".format(y.op.name)) in y.astext()\n        # test type inference\n        yy = run_infer_type(y)\n        assert yy.checked_type == tp\n\n        if ref_func is not None:\n            data = np.random.rand(*shape).astype(dtype)\n            ref_res = ref_func(data).astype(dtype)\n            func = relay.Function([x], y)\n            # use graph by execuor default for testing, as we need\n            # create function explicitly to avoid constant-folding.\n            op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n            tolerance = 1e-2 if dtype == \"float16\" else 1e-5\n            np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=tolerance)\n\n\n@tvm.testing.uses_gpu\ndef test_binary_op():\n    def inst(vars, sh):\n        return [vars.get(s, s) for s in sh]\n\n    def check_binary_op(opfunc, ref, dtype):\n        # TODO(@jroesch): this piece of code improperly uses type variables.\n        n = te.var(\"n\")\n        s1 = (5, n, 5)\n        s2 = (n, 1)\n        t1 = relay.TensorType(s1)\n        t2 = relay.TensorType(s2)\n        x = relay.var(\"x\", t1, dtype=dtype)\n        y = relay.var(\"y\", t2, dtype=dtype)\n        z = opfunc(x, y)\n        # test printer\n        assert (\"{}(%x, %y)\".format(z.op.name)) in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == t1\n\n        if ref is not None:\n            t1 = relay.TensorType((5, 10, 5))\n            t2 = relay.TensorType((5, 10, 5))\n            x = relay.var(\"x\", t1, dtype=dtype)\n            y = relay.var(\"y\", t2, dtype=dtype)\n            z = opfunc(x, y)\n            x_data = np.random.rand(5, 10, 5).astype(dtype)\n            y_data = np.random.rand(5, 10, 5).astype(dtype)\n            ref_res = ref(x_data, y_data)\n            func = relay.Function([x, y], z)\n\n            for target, dev in tvm.testing.enabled_targets():\n                # use graph by execuor default for testing, as we need\n                # create function explicitly to avoid constant-folding.\n                if (\n                    dtype == \"float16\"\n                    and target == \"cuda\"\n                    and not have_fp16(tvm.cuda(0).compute_version)\n                ):\n                    continue\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data, y_data\n                )\n                np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01, atol=1e-3)\n\n    for opfunc, ref in [\n        (relay.add, np.add),\n        (relay.subtract, np.subtract),\n        (relay.multiply, np.multiply),\n        (relay.divide, np.divide),\n        (relay.floor_divide, np.floor_divide),\n        (relay.floor_mod, np.fmod),\n    ]:\n        for dtype in [\"float16\", \"float32\"]:\n            check_binary_op(opfunc, ref, dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_expand_dims():\n    # based on topi test\n    def verify_expand_dims(dshape, dtype, oshape, axis, num_newaxis):\n        x = relay.Var(\"x\", relay.TensorType(dshape, dtype))\n        func = relay.Function([x], relay.expand_dims(x, axis, num_newaxis))\n        for target, dev in tvm.testing.enabled_targets():\n            if (\n                dtype == \"float16\"\n                and target == \"cuda\"\n                and not have_fp16(tvm.cuda(0).compute_version)\n            ):\n                continue\n            data = np.random.uniform(size=dshape).astype(dtype)\n            ref_res = data.reshape(oshape)\n            op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n            np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n    for dtype in [\"float16\", \"float32\"]:\n        verify_expand_dims((3, 10), dtype, (3, 10, 1, 1), 2, 2)\n        verify_expand_dims((3, 10), dtype, (1, 3, 10), -3, 1)\n\n\n@tvm.testing.uses_gpu\ndef test_bias_add():\n    for dtype in [\"float16\", \"float32\"]:\n        xshape = (10, 2, 3, 4)\n        bshape = (2,)\n        rtol = 1e-2 if dtype == \"float16\" else 1e-5\n        x = relay.var(\"x\", shape=xshape, dtype=dtype)\n        bias = relay.var(\"bias\", dtype=dtype)\n        z = relay.nn.bias_add(x, bias)\n        zz = run_infer_type(z)\n        assert \"axis=\" not in zz.astext()\n        assert zz.args[1].checked_type == relay.TensorType(bshape, dtype)\n\n        func = relay.Function([x, bias], z)\n        x_data = np.random.uniform(size=xshape).astype(dtype)\n        y_data = np.random.uniform(size=bshape).astype(dtype)\n        ref_res = x_data + y_data.reshape((2, 1, 1))\n        for target, dev in tvm.testing.enabled_targets():\n            if (\n                dtype == \"float16\"\n                and target == \"cuda\"\n                and not have_fp16(tvm.cuda(0).compute_version)\n            ):\n                continue\n            op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                x_data, y_data\n            )\n            np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=rtol)\n\n\ndef test_bias_add_type_failure():\n    def assert_failure(expr):\n        try:\n            run_infer_type(expr)\n        except tvm._ffi.base.TVMError:\n            return\n        else:\n            assert False\n\n    for axis in (0, -1, -3, 1):\n        assert_failure(relay.nn.bias_add(relay.const(1), relay.const(2), axis=axis))\n\n\ndef test_expand_dims_infer_type():\n    for dtype in [\"float16\", \"float32\"]:\n        n, t, d = te.size_var(\"n\"), te.size_var(\"t\"), 100\n        x = relay.var(\"x\", shape=(n, t, d), dtype=dtype)\n        y = relay.expand_dims(x, axis=2)\n        assert \"axis=2\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, t, 1, 100), dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_softmax():\n    for shape in [(10, 4), (10, 5, 4)]:\n        for dtype in [\"float16\", \"float32\"]:\n            # Softmax accuracy for float16 is poor\n            if dtype == \"float16\":\n                continue\n            x = relay.var(\"x\", shape=shape, dtype=dtype)\n            y = relay.nn.softmax(x, axis=1)\n            assert \"nn.softmax\" in y.astext()\n            yy = run_infer_type(y)\n            assert yy.checked_type == relay.TensorType(shape, dtype)\n            func = relay.Function([x], y)\n            x_data = np.random.uniform(size=shape).astype(dtype)\n            ref_res = tvm.topi.testing.softmax_python(x_data, axis=1)\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data\n                )\n                np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_log_softmax():\n    for shape in [(10, 4), (10, 5, 4)]:\n        for dtype in [\"float16\", \"float32\"]:\n            # Softmax accuracy for float16 is poor\n            if dtype == \"float16\":\n                continue\n            x = relay.var(\"x\", shape=shape, dtype=dtype)\n            y = relay.nn.log_softmax(x, axis=1)\n            assert \"nn.log_softmax\" in y.astext()\n            yy = run_infer_type(y)\n            assert yy.checked_type == relay.TensorType(shape, dtype)\n            func = relay.Function([x], y)\n            x_data = np.random.uniform(size=shape).astype(dtype)\n            ref_res = tvm.topi.testing.log_softmax_python(x_data, axis=1)\n            for target, dev in tvm.testing.enabled_targets():\n                if target == \"nvptx\":\n                    continue\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data\n                )\n                np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_concatenate(executor_kind):\n    for dtype in [\"float16\", \"float32\"]:\n        n, t, d = te.size_var(\"n\"), te.size_var(\"t\"), 100\n        x = relay.var(\"x\", shape=(n, t, d))\n        y = relay.var(\"y\", shape=(n, t, d))\n        z = relay.concatenate((x, y), axis=-1)\n        assert \"axis=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((n, t, 200))\n\n        x = relay.exp(x)\n        z = relay.concatenate((x, y), axis=2)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((n, t, 200))\n\n        z = relay.concatenate((x, y), axis=1)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((n, t + t, 100))\n\n        # check shape mismatches (the following case is expected to raise tvm._ffi.base.TVMError.\n        try:\n            x = relay.var(\"p1\", shape=(2, 5))\n            y = relay.var(\"p2\", shape=(2, 3))\n            c = relay.concatenate([x, y], axis=0)\n            func = relay.Function([x, y], c)\n            zz = run_infer_type(func)\n        except tvm._ffi.base.TVMError:\n            pass\n        else:\n            assert False\n\n        x = relay.var(\"x\", shape=(10, 5), dtype=dtype)\n        y = relay.var(\"y\", shape=(10, 5), dtype=dtype)\n        t = relay.var(\"z\", shape=(), dtype=dtype)\n        z = relay.concatenate((x, y), axis=1)\n        z = relay.add(z, t)\n        # Check result.\n        func = relay.Function([x, y, t], z)\n        x_data = np.random.rand(10, 5).astype(dtype)\n        y_data = np.random.rand(10, 5).astype(dtype)\n        t_data = np.random.uniform(size=()).astype(dtype)\n        ref_res = np.concatenate((x_data, y_data), axis=1) + t_data\n\n        for target, dev in tvm.testing.enabled_targets():\n            if (\n                dtype == \"float16\"\n                and target == \"cuda\"\n                and not have_fp16(tvm.cuda(0).compute_version)\n            ):\n                continue\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data, y_data, t_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\ndef test_dropout(executor_kind):\n    for dtype in [\"float16\", \"float32\"]:\n        n, t, d = te.size_var(\"n\"), te.size_var(\"t\"), te.size_var(\"d\")\n        input_ty = relay.TensorType((n, t, d), dtype)\n        x = relay.var(\"x\", input_ty)\n        y = relay.nn.dropout(x, rate=0.75)\n        assert \"rate=\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == input_ty\n\n    in_np = np.random.random([4, 5, 6]).astype(\"float32\")\n    x = relay.const(in_np)\n    y = relay.nn.dropout(x, rate=0.5)\n    func = relay.Function([], y)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)()\n        tvm.testing.assert_allclose(op_res.numpy(), in_np, rtol=0.01)\n\n\ndef test_batch_norm():\n    for dtype in [\"float16\", \"float32\"]:\n        # beta and gamma ignored\n        data = relay.var(\"data\", relay.TensorType((3, 2, 1), dtype))\n        beta = relay.var(\"beta\", relay.TensorType((2,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((2,), dtype))\n        moving_mean = relay.var(\"moving_mean\", relay.TensorType((2,), dtype))\n        moving_var = relay.var(\"moving_var\", relay.TensorType((2,), dtype))\n        y = relay.nn.batch_norm(\n            data, gamma, beta, moving_mean, moving_var, center=False, scale=False\n        )\n        yy = run_infer_type(y.astuple())\n        assert \"center=\" in yy.astext()\n        assert yy.checked_type == relay.ty.TupleType(\n            tvm.runtime.convert(\n                [\n                    relay.TensorType((3, 2, 1), dtype),\n                    relay.TensorType((2,), dtype),\n                    relay.TensorType((2,), dtype),\n                ]\n            )\n        )\n\n        # axis=1\n        beta = relay.var(\"beta\", relay.TensorType((3,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((3,), dtype))\n        moving_mean = relay.var(\"moving_mean\", relay.TensorType((3,), dtype))\n        moving_var = relay.var(\"moving_var\", relay.TensorType((3,), dtype))\n\n        y = relay.nn.batch_norm(\n            data, gamma, beta, moving_mean, moving_var, axis=0, center=False, scale=False\n        )\n        yy = run_infer_type(y.astuple())\n        assert yy.checked_type == relay.ty.TupleType(\n            tvm.runtime.convert(\n                [\n                    relay.ty.TensorType((3, 2, 1), dtype),\n                    relay.ty.TensorType((3,), dtype),\n                    relay.ty.TensorType((3,), dtype),\n                ]\n            )\n        )\n\n        # axis=-1\n        data = relay.var(\"data\", relay.TensorType((1, 2, 3), dtype))\n        beta = relay.var(\"beta\", relay.TensorType((3,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((3,), dtype))\n        moving_mean = relay.var(\"moving_mean\", relay.TensorType((3,), dtype))\n        moving_var = relay.var(\"moving_var\", relay.TensorType((3,), dtype))\n        y = relay.nn.batch_norm(\n            data, gamma, beta, moving_mean, moving_var, axis=-1, center=False, scale=False\n        )\n        yy = run_infer_type(y.astuple())\n        assert yy.checked_type == relay.ty.TupleType(\n            tvm.runtime.convert(\n                [\n                    relay.ty.TensorType((1, 2, 3), dtype),\n                    relay.ty.TensorType((3,), dtype),\n                    relay.ty.TensorType((3,), dtype),\n                ]\n            )\n        )\n\n\ndef do_concat_test(shapes, t_shape, dtype, axis, dev, target):\n    varsToConcat = []\n    inputData = []\n    pos = 0\n    for s in shapes:\n        varsToConcat.append(relay.var(\"x{}\".format(pos), shape=s))\n        inputData.append(np.random.rand(*s).astype(dtype))\n        pos += 1\n    t = relay.var(\"z\", shape=t_shape, dtype=dtype)\n    z = relay.concatenate(varsToConcat, axis=axis)\n    z = relay.add(z, t)\n    params = varsToConcat\n    params.append(t)\n    func = relay.Function(params, z)\n    t_data = np.random.uniform(low=-10, high=10, size=t_shape).astype(dtype)\n    ref_res = np.concatenate((tuple(inputData)), axis=axis) + t_data\n    mod = tvm.IRModule.from_expr(func)\n\n    executor = relay.create_executor(\"graph\", mod=mod, device=dev, target=target)\n    op_res1 = executor.evaluate()(*inputData, t_data)\n\n    tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=0.000001)\n    op_res2 = relay.create_executor(\"debug\", device=dev, target=target).evaluate(func)(\n        *inputData, t_data\n    )\n    tvm.testing.assert_allclose(op_res2.numpy(), ref_res, rtol=0.000001)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_concatenate1(target, dev):\n    np.random.seed(471)\n    maxNumDimensions = 6\n    shape = [4, 32, 16, 1, 31, 20, 21, 8, 28, 7]  # just randomly selected 10 numbers\n    for dtype in [\"float32\"]:\n        for dimsNum in range(1, maxNumDimensions):\n            np.random.shuffle(shape)\n            for axis in range(0, dimsNum):  # range should be (-dimsNum + 1, dimsNum)\n                numToConcat = np.random.uniform(low=2, high=10, size=(1)).astype(\"int64\")[0]\n                shapes = []\n                # the code below to normalize axes index. For some reasons tvm notifies about error if the axis is negative\n                normalizedAxis = axis\n                if axis < 0:\n                    normalizedAxis += dimsNum\n                finalSize = 0\n                for i in range(0, numToConcat):\n                    shp = tuple(shape[:dimsNum])\n                    finalSize += shape[(i % len(shape))]\n                    shapes.append(\n                        shp[:normalizedAxis]\n                        + tuple([shape[(i % len(shape))]])\n                        + shp[normalizedAxis + 1 :]\n                    )\n                t_shape = shp[:normalizedAxis] + tuple([finalSize]) + shp[normalizedAxis + 1 :]\n                do_concat_test(shapes, t_shape, dtype, axis, dev, target)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_concatenate2(target, dev):\n    # test to cover cases (1, .. , x, 1, .. , 1)\n    np.random.seed(13)\n    maxNumDimensions = 6\n    shape = [8, 3, 25, 33, 12, 29, 5, 11, 29, 11]  # just randomly selected 10 numbers\n    ind = 0\n    for dtype in [\"float32\"]:\n        for dimsNum in range(2, maxNumDimensions):\n            np.random.shuffle(shape)\n            for axis in range(-dimsNum + 1, dimsNum):  # range should be (-dimsNum + 1, dimsNum)\n                numToConcat = np.random.uniform(low=2, high=10, size=(1)).astype(\"int64\")[0]\n                shapes = []\n                # the code below to normalize axes index. For some reasons tvm notifies about error if the axis is negative\n                normalizedAxis = axis\n                if axis < 0:\n                    normalizedAxis += dimsNum\n                finalSize = 0\n                for i in range(0, numToConcat):\n                    axisVal = [1] * dimsNum\n                    axisVal[axis] = shape[(ind % len(shape))]\n                    ind += 1\n                    finalSize += axisVal[axis]\n                    shapes.append(tuple(axisVal))\n                temp = [1] * dimsNum\n                temp[axis] = finalSize\n                t_shape = tuple(temp)\n                do_concat_test(shapes, t_shape, dtype, axis, dev, target)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_concatenate3(target, dev):\n    np.random.seed(477)\n    for dtype in [\"float32\"]:\n        axis = -2\n        ending = 1\n        shapes = [[3, 2, 1, ending], [3, 2, 1, ending]]\n        t_shape = [3, 2, 2, ending]\n        do_concat_test(shapes, t_shape, dtype, axis, dev, target)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_concatenate4(target, dev):\n    np.random.seed(7)\n    x_shape = (2, 1)\n    x = relay.var(\"x\", shape=x_shape, dtype=\"int64\")\n    concat = relay.concatenate([x], axis=1)\n    f = relay.Function([x], concat)\n    x_val = np.array([[33], [13]], dtype=\"int64\")\n    graph = relay.create_executor(\"graph\", device=tvm.cpu(), target=\"llvm\")\n    op_res = graph.evaluate(f)(x_val)\n    ref_res = np.concatenate([x_val], axis=1)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.000001)\n\n\ndef test_batch_norm_fold_const():\n    axis = 1\n    dtype = \"float32\"\n    shape = [4, 5, 6]\n\n    data_np = np.random.random(shape).astype(dtype)\n    beta_np = np.random.random(shape[axis]).astype(dtype)\n    gamma_np = np.random.random(shape[axis]).astype(dtype)\n    moving_mean_np = np.random.random(shape[axis]).astype(dtype)\n    moving_var_np = np.random.random(shape[axis]).astype(dtype)\n\n    data = relay.var(\"data\", relay.TensorType(shape, dtype))\n    beta = relay.var(\"beta\", relay.TensorType((shape[1],), dtype))\n    gamma = relay.var(\"gamma\", relay.TensorType((shape[1],), dtype))\n    moving_mean = relay.var(\"moving_mean\", relay.TensorType((shape[1],), dtype))\n    moving_var = relay.var(\"moving_var\", relay.TensorType((shape[1],), dtype))\n    out = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var, axis=axis).astuple()\n    func = relay.Function([data, gamma, beta, moving_mean, moving_var], out)\n\n    out_const = relay.nn.batch_norm(\n        relay.const(data_np),\n        relay.const(gamma_np),\n        relay.const(beta_np),\n        relay.const(moving_mean_np),\n        relay.const(moving_var_np),\n        axis=axis,\n    ).astuple()\n    func_const = relay.Function([], out_const)\n\n    # Build the module with constants to have FoldConstant transform batch_norm.\n    mod_const = tvm.IRModule.from_expr(func_const)\n    mod_const = relay.transform.FoldConstant()(mod_const)\n\n    const_data_out = mod_const[\"main\"].body[0].data\n    const_moving_mean_out = mod_const[\"main\"].body[1].data\n    const_moving_var_out = mod_const[\"main\"].body[2].data\n\n    # Run the Relay func without constants. This will use SimplyInference instead.\n    vm_data_out, vm_moving_mean_out, vm_moving_var_out = relay.create_executor(\n        \"vm\", device=tvm.device(\"llvm\"), target=\"llvm\"\n    ).evaluate(func)(data_np, gamma_np, beta_np, moving_mean_np, moving_var_np)\n\n    tvm.testing.assert_allclose(const_data_out.numpy(), vm_data_out.numpy())\n    tvm.testing.assert_allclose(const_moving_mean_out.numpy(), vm_moving_mean_out.numpy())\n    tvm.testing.assert_allclose(const_moving_var_out.numpy(), vm_moving_var_out.numpy())\n\n\n@pytest.mark.xfail\ndef test_matmul_type_check():\n    dtype = \"float16\"\n    n, c, h, w = 2, 2, 2, 2\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n    # it should fail since it does not match with m(2)\n    mismatch_w = 3\n    w = relay.var(\"w\", relay.TensorType((mismatch_w, 2), dtype))\n    y = relay.nn.matmul(x, w)\n    yy = run_infer_type(y)\n\n\n@tvm.testing.uses_gpu\ndef test_matmul(executor_kind):\n    for dtype in [\"float16\", \"float32\"]:\n        # Matmul accuracy for float16 is poor\n        if dtype == \"float16\":\n            continue\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        w = relay.var(\"w\", relay.TensorType((2, w), dtype))\n        y = relay.nn.matmul(x, w, units=2, transpose_b=True)\n        assert \"units=2\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)\n\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), 2\n        x = relay.var(\"x\", relay.TensorType((n, c, w, h), dtype))\n        wh, ww = te.size_var(\"wh\"), te.size_var(\"ww\")\n        w = relay.var(\"w\", relay.TensorType((wh, ww), dtype))\n        y = relay.nn.matmul(x, w, transpose_a=True)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, ww), dtype)\n\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), 2\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        w = relay.var(\"w\", relay.IncompleteType())\n        y = relay.nn.matmul(x, w, units=2)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)\n\n        x = relay.var(\"x\", shape=(5, 10), dtype=dtype)\n        w = relay.var(\"w\", shape=(5, 2), dtype=dtype)\n        z = relay.nn.matmul(x, w, transpose_a=True)\n\n        # Check result.\n        func = relay.Function([x, w], z)\n        x_data = np.random.rand(5, 10).astype(dtype)\n        w_data = np.random.rand(5, 2).astype(dtype)\n        ref_res = np.dot(x_data.transpose(), w_data)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data, w_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@pytest.mark.xfail\ndef test_dense_type_check():\n    dtype = \"float16\"\n    n, c, h, w = 2, 2, 2, 2\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n    # it should fail since it does not match with m(2)\n    mismatch_w = 3\n    w = relay.var(\"w\", relay.TensorType((2, mismatch_w), dtype))\n    y = relay.nn.dense(x, w)\n    yy = run_infer_type(y)\n\n\n@tvm.testing.uses_gpu\ndef test_dense(executor_kind):\n    for dtype in [\"float16\", \"float32\"]:\n        # Dense accuracy for float16 is poor\n        if dtype == \"float16\":\n            continue\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        w = relay.var(\"w\", relay.TensorType((2, w), dtype))\n        y = relay.nn.dense(x, w, units=2)\n        assert \"units=2\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)\n\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), 2\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        wh, ww = te.size_var(\"wh\"), te.size_var(\"ww\")\n        w = relay.var(\"w\", relay.TensorType((ww, wh), dtype))\n        y = relay.nn.dense(x, w)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, ww), dtype)\n\n        # test dynamic shape in inner\n        m, k = 4, 2\n        x = relay.var(\"x\", relay.TensorType((m, k), dtype))\n        k, nw = relay.Any(), 6\n        w = relay.var(\"w\", relay.TensorType((k, n), dtype))\n        y = relay.nn.dense(x, w)\n        yy = run_infer_type(y)\n\n        n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), 2\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        w = relay.var(\"w\", relay.IncompleteType())\n        y = relay.nn.dense(x, w, units=2)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)\n\n        x = relay.var(\"x\", shape=(10, 5), dtype=dtype)\n        w = relay.var(\"w\", shape=(2, 5), dtype=dtype)\n        z = relay.nn.dense(x, w)\n\n        # Check result.\n        func = relay.Function([x, w], z)\n        x_data = np.random.rand(10, 5).astype(dtype)\n        w_data = np.random.rand(2, 5).astype(dtype)\n        ref_res = np.dot(x_data, w_data.T)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data, w_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_dense_same_args_compile():\n    for dtype in [\"float32\", \"int8\"]:\n        x = relay.var(\"x\", shape=(32, 64), dtype=dtype)\n        out_dtype = \"int32\" if dtype == \"int8\" else \"float32\"\n        f = relay.Function([x], relay.nn.dense(x, x, out_dtype=out_dtype))\n        m = tvm.IRModule.from_expr(f)\n\n        for target, _ in tvm.testing.enabled_targets():\n            tvm.relay.build(m, target=target)\n\n\ndef test_dense_dtype():\n    data_dtype = \"uint8\"\n    weight_dtype = \"int8\"\n    out_dtype = \"uint8\"\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), data_dtype))\n    w = relay.var(\"w\", relay.TensorType((2, w), weight_dtype))\n    y = relay.nn.dense(x, w, units=2, out_dtype=out_dtype)\n    assert \"units=2\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, h, 2), out_dtype)\n    assert run_infer_type(yy.args[0]).checked_type.dtype == \"uint8\"\n    assert run_infer_type(yy.args[1]).checked_type.dtype == \"int8\"\n\n\ndef test_bitserial_dense():\n    m, k = te.size_var(\"m\"), te.size_var(\"k\")\n    x = relay.var(\"x\", relay.TensorType((m, k), \"int16\"))\n    w = relay.var(\"w\", relay.TensorType((k, 32), \"int16\"))\n    y = relay.nn.bitserial_dense(x, w, units=32)\n    \"units=8\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((m, 32), \"int16\")\n\n\n@tvm.testing.requires_cascadelake\ndef test_dense_vnni():\n    data_shape = (32, 96)\n    weight_shape = (128, 96)\n\n    for data_dtype in [\"uint8\", \"int8\"]:\n        data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n        weight = relay.var(\"weight\", shape=weight_shape, dtype=\"int8\")\n        bias = relay.var(\"bias\", shape=(weight_shape[0],), dtype=\"int32\")\n        dense = relay.nn.dense(data, weight, out_dtype=\"int32\")\n        out = relay.nn.bias_add(dense, bias)\n        mod = tvm.IRModule.from_expr(out)\n\n        target = \"llvm -mcpu=cascadelake\"\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target)\n\n        asm = lib.lib.get_source(\"asm\")\n        assert \"vpdpbusd\" in asm\n\n        dev = tvm.device(target, 0)\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n        a = np.random.uniform(1, 10, size=data_shape).astype(data_dtype)\n        b = np.random.uniform(1, 10, size=weight_shape).astype(\"int8\")\n        c = np.random.uniform(1, 10, size=(weight_shape[0],)).astype(\"int32\")\n\n        runtime.set_input(\"data\", a)\n        runtime.set_input(\"weight\", b)\n        runtime.set_input(\"bias\", c)\n        runtime.run()\n\n        out = runtime.get_output(0).numpy()\n        ref = np.dot(a.astype(\"int32\"), b.transpose().astype(\"int32\")) + c\n\n        np.testing.assert_equal(out, ref)\n\n\n@pytest.mark.skip(\"Requires GFX10 AMDGPU\")\ndef test_dense_rocm_sdot4():\n    data_shape = (32, 96)\n    weight_shape = (128, 96)\n\n    data_dtype = \"int8\"\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"int8\")\n    bias = relay.var(\"bias\", shape=(weight_shape[0],), dtype=\"int32\")\n    dense = relay.nn.dense(data, weight, out_dtype=\"int32\")\n    out = relay.nn.bias_add(dense, bias)\n    mod = tvm.IRModule.from_expr(out)\n\n    target = \"rocm -mattr=+dotprod\"\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target)\n\n    asm = lib.lib.imported_modules[0].get_source(\"asm\")\n    assert \"v_dot4_i32_i8\" in asm\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    a = np.random.uniform(1, 10, size=data_shape).astype(data_dtype)\n    b = np.random.uniform(1, 10, size=weight_shape).astype(\"int8\")\n    c = np.random.uniform(1, 10, size=(weight_shape[0],)).astype(\"int32\")\n\n    runtime.set_input(\"data\", a)\n    runtime.set_input(\"weight\", b)\n    runtime.set_input(\"bias\", c)\n    runtime.run()\n\n    out = runtime.get_output(0).numpy()\n    ref = np.dot(a.astype(\"int32\"), b.transpose().astype(\"int32\")) + c\n\n    np.testing.assert_equal(out, ref)\n\n\ndef test_extern_concat_injective_fuse():\n    # This is a subgraph from MobileBERT, which crashes compilation if buffers created in te.extern(...)\n    # do not have their elem_offset explicitly set as a variable.\n\n    # fmt: off\n    mod = tvm.parser.fromtext(\n        \"\"\"\n       #[version = \"0.0.5\"]\n       def @main(%p0844: Tensor[(1, 384), int64], %p1652: Tensor[(2016, 128), float16]) {\n        %1331 = cast(%p0844, dtype=\"int32\");\n        %1332 = take(%p1652, %1331, axis=0);\n        %1333 = strided_slice(%1332, begin=[0, 1, 0], end=[1, 384, 128], strides=[1, 1, 1], axes=None);\n        %1334 = strided_slice(%1332, begin=[0, 0, 0], end=[1, -1, 128], strides=[1, 1, 1], axes=None);\n        %1335 = nn.pad(%1333, 0, pad_width=[[0, 0], [0, 1], [0, 0]]);\n        %1336 = nn.pad(%1334, 0, pad_width=[[0, 0], [1, 0], [0, 0]]);\n        %1337 = (%1335, %1332, %1336);\n        %1338 = concatenate(%1337, axis=2);\n        reshape(%1338, newshape=[-1, 384])\n      }\n    \"\"\"\n    )\n    # fmt: on\n\n    relay.build(mod, params={}, target=\"llvm\")\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level10.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level10 operator test cases.\n\"\"\"\nimport sys\nimport pytest\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay, te, topi\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_checkpoint(executor_kind):\n    dtype = \"float32\"\n    xs = [relay.var(\"x{}\".format(i), dtype) for i in range(4)]\n    f = relay.multiply(relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3]))\n    f_checkpoint = relay.annotation.checkpoint(f)\n\n    func, func_checkpoint = relay.Function(xs, f), relay.Function(xs, f_checkpoint)\n    f, f_checkpoint = run_infer_type(func), run_infer_type(func_checkpoint)\n    assert f.checked_type == f_checkpoint.checked_type\n\n    inputs = [np.random.uniform() for _ in range(len(xs))]\n    for target, dev in tvm.testing.enabled_targets():\n        f_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(f)(*inputs)\n        f_checkpoint_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(\n            f_checkpoint\n        )(*inputs)\n        tvm.testing.assert_allclose(f_res.numpy(), f_checkpoint_res.numpy(), 0, 0)\n\n\ndef test_checkpoint_alpha_equal():\n    xs = [relay.var(\"x{}\".format(i), relay.TensorType((1,), \"float32\")) for i in range(4)]\n    f = relay.Function(\n        xs,\n        relay.annotation.checkpoint(\n            relay.multiply(relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3]))\n        ),\n    )\n    df = transform.gradient(run_infer_type(f))\n\n    # run PE and DCE\n    with tvm.transform.PassContext(opt_level=3):\n        # The expected output assumes DCE can elide 'dead writes' to references. At the time this unit test was\n        # written DCE would elide all writes, which though unsound in general happens to work for this case. Preserve\n        # that legacy behaviour here using 'ignore_impurity=True'.\n        # TODO(mbs): Revisit once DCE supports dead reference writes.\n        passes = [\n            transform.PartialEvaluate(),\n            transform.DeadCodeElimination(inline_once=True, ignore_impurity=True),\n        ]\n        mod = tvm.transform.Sequential(passes)(tvm.IRModule.from_expr(df))\n        df = mod[\"main\"]\n\n    df_parsed = tvm.parser.parse_expr(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        fn (%x: Tensor[(1), float32], %y: Tensor[(1), float32],\n            %z: Tensor[(1), float32], %w: Tensor[(1), float32])\n            ->  (Tensor[(1), float32],\n                (Tensor[(1), float32], Tensor[(1), float32],\n                 Tensor[(1), float32], Tensor[(1), float32])) {\n            %0 = add(%x, %y);\n            %1 = add(%z, %w);\n            let %x1: Tensor[(1), float32] = multiply(%0, %1);\n            let %x2: Tensor[(1), float32] = ones_like(%x1);\n            let %x3: Tensor[(1), float32] = add(%x, %y);\n            let %x4: Tensor[(1), float32] = add(%z, %w);\n            %2 = zeros_like(%x3);\n            %3 = multiply(%x2, %x4);\n            %4 = collapse_sum_like(%3, %x3);\n            let %x5: Tensor[(1), float32] = add(%2, %4);\n            %5 = zeros_like(%x4);\n            %6 = multiply(%x2, %x3);\n            %7 = collapse_sum_like(%6, %x4);\n            let %x6: Tensor[(1), float32] = add(%5, %7);\n            %8 = zeros_like(%x);\n            %9 = collapse_sum_like(%x5, %x);\n            %10 = add(%8, %9);\n            %11 = zeros_like(%y);\n            %12 = collapse_sum_like(%x5, %y);\n            %13 = add(%11, %12);\n            %14 = zeros_like(%z);\n            %15 = collapse_sum_like(%x6, %z);\n            %16 = add(%14, %15);\n            %17 = zeros_like(%w);\n            %18 = collapse_sum_like(%x6, %w);\n            %19 = add(%17, %18);\n            %20 = (%10, %13, %16, %19);\n            (%x1, %20)\n        }\n        \"\"\"\n    )\n\n    tvm.ir.assert_structural_equal(df, df_parsed)\n\n\ndef test_checkpoint_alpha_equal_tuple():\n    xs = [relay.var(\"x{}\".format(i), relay.TensorType((1,), \"float32\")) for i in range(4)]\n    f = relay.Function(\n        xs,\n        relay.annotation.checkpoint(\n            relay.Tuple([relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3])])\n        ),\n    )\n    df = transform.gradient(run_infer_type(f))\n\n    # run PE and DCE\n    with tvm.transform.PassContext(opt_level=3):\n        # See comment in test_checkpoint_alpha_equal above.\n        # TODO(mbs): Revisit once DCE supports dead reference writes.\n        passes = [\n            transform.PartialEvaluate(),\n            transform.DeadCodeElimination(inline_once=True, ignore_impurity=True),\n        ]\n        mod = tvm.transform.Sequential(passes)(tvm.IRModule.from_expr(df))\n        df = mod[\"main\"]\n\n    df_parsed = tvm.parser.parse_expr(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        fn (%x: Tensor[(1), float32], %y: Tensor[(1), float32],\n            %z: Tensor[(1), float32], %w: Tensor[(1), float32])\n            -> ((Tensor[(1), float32], Tensor[(1), float32]),\n                (Tensor[(1), float32], Tensor[(1), float32],\n                 Tensor[(1), float32], Tensor[(1), float32])) {\n        let %x1: Tensor[(1), float32] = add(%x, %y) /* ty=Tensor[(1), float32] */;\n        let %x2: Tensor[(1), float32] = add(%z, %w) /* ty=Tensor[(1), float32] */;\n        let %x3: Tensor[(1), float32] = zeros_like(%x2) /* ty=Tensor[(1), float32] */;\n        let %x4: Tensor[(1), float32] = ones_like(%x1) /* ty=Tensor[(1), float32] */;\n        %0 = (%x1, %x2);\n        %1 = zeros_like(%x) /* ty=Tensor[(1), float32] */;\n        %2 = collapse_sum_like(%x4, %x) /* ty=Tensor[(1), float32] */;\n        %3 = add(%1, %2) /* ty=Tensor[(1), float32] */;\n        %4 = zeros_like(%y) /* ty=Tensor[(1), float32] */;\n        %5 = collapse_sum_like(%x4, %y) /* ty=Tensor[(1), float32] */;\n        %6 = add(%4, %5) /* ty=Tensor[(1), float32] */;\n        %7 = zeros_like(%z) /* ty=Tensor[(1), float32] */;\n        %8 = collapse_sum_like(%x3, %z) /* ty=Tensor[(1), float32] */;\n        %9 = add(%7, %8) /* ty=Tensor[(1), float32] */;\n        %10 = zeros_like(%w) /* ty=Tensor[(1), float32] */;\n        %11 = collapse_sum_like(%x3, %w) /* ty=Tensor[(1), float32] */;\n        %12 = add(%10, %11) /* ty=Tensor[(1), float32] */;\n        %13 = (%3, %6, %9, %12);\n        (%0, %13)\n        }\n        \"\"\"\n    )\n\n    tvm.ir.assert_structural_equal(df, df_parsed)\n\n\n@tvm.testing.uses_gpu\ndef test_collapse_sum_like(executor_kind):\n    shape = (3, 4, 5, 6)\n    shape_like = (4, 5, 6)\n    dtype = \"float32\"\n    x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n    y = relay.Var(\"y\", relay.ty.TensorType(shape_like, dtype))\n    z = relay.collapse_sum_like(x, y)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n    func = relay.Function([x, y], z)\n    x = np.random.uniform(size=shape).astype(dtype)\n    y = np.random.uniform(size=shape_like).astype(dtype)\n    ref_res = np.sum(x, 0)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x, y\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_collapse_sum_to(executor_kind):\n    shape = (3, 4, 5, 6)\n    shape_to = (4, 5, 6)\n    dtype = \"float32\"\n    x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n    z = relay.collapse_sum_to(x, shape_to)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.ty.TensorType(shape_to, dtype)\n\n    func = relay.Function([x], z)\n    x = np.random.uniform(size=shape).astype(dtype)\n    ref_res = np.sum(x, 0)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(x)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_to(executor_kind):\n    shape = (4, 1, 6)\n    shape_like = (3, 4, 5, 6)\n    dtype = \"float32\"\n    x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n    z = relay.broadcast_to(x, shape=shape_like)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n    func = relay.Function([x], z)\n    x = np.random.uniform(size=shape).astype(dtype)\n    ref_res = np.broadcast_to(x, shape_like)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(x)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_to_const_shape_int64(executor_kind):\n    shape_like = relay.const(np.array([1, 5]), dtype=\"int64\")\n    x = relay.var(\"x\", shape=(1,), dtype=\"int64\")\n    z = relay.broadcast_to(x, shape=shape_like)\n    z = relay.sum(z, axis=0)\n\n    f = relay.Function([x], z)\n\n    x = np.random.randint(10, size=(1,), dtype=\"int64\")\n    ref_res = np.broadcast_to(x, (5,))\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(f)(x)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\ndef test_broadcast_concat_shape_int64(executor_kind):\n    x_shape = (1, 2, 1, 1)\n    broadcast_shape = [1, 2, 2, 1]\n    x = relay.var(\"data\", relay.TensorType(x_shape, \"float32\"))\n    broadcast_to = relay.op.broadcast_to(x, relay.const(broadcast_shape, dtype=\"int64\"))\n    concate = relay.op.concatenate((broadcast_to,), axis=0)\n\n    f = relay.Function([x], concate)\n\n    x = np.zeros(x_shape).astype(\"float32\")\n    ref_res = np.concatenate((np.broadcast_to(x, broadcast_shape),), axis=0)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(f)(x)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\ndef test_broadcast_pool2d_shape_int64(executor_kind):\n    x_shape = (1, 3, 32, 32)\n    out_shape = (2, 3, 32, 32)\n    x = relay.var(\"data\", shape=x_shape, dtype=\"float32\")\n    broadcast_to = relay.broadcast_to(x, shape=relay.const([2, 3, 32, 32], dtype=\"int64\"))\n    pool2d = relay.nn.max_pool2d(broadcast_to, pool_size=(3, 3), padding=(1, 1, 1, 1))\n    sub = relay.subtract(broadcast_to, pool2d)\n\n    f = relay.Function([x], sub)\n    x = np.ones(x_shape).astype(\"float32\")\n    ref_res = np.zeros(out_shape).astype(\"float32\")\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(f)(x)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_to_like(executor_kind):\n    shape = (4, 1, 6)\n    shape_like = (3, 4, 5, 6)\n    dtype = \"float32\"\n    x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n    y = relay.Var(\"y\", relay.ty.TensorType(shape_like, dtype))\n    z = relay.broadcast_to_like(x, y)\n\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n    func = relay.Function([x, y], z)\n    x = np.random.uniform(size=shape).astype(dtype)\n    y = np.random.uniform(size=shape_like).astype(dtype)\n    ref_res = np.broadcast_to(x, shape_like)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x, y\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef np_slice_like(np_data, np_shape_like, axis=None):\n    begin_idx = [0 for _ in np_data.shape]\n    end_idx = list(np_data.shape)\n    if axis:\n        for i in axis:\n            if i < 0:\n                i = len(np_data.shape) + i\n            end_idx[i] = np_shape_like.shape[i]\n    else:\n        for i in range(len(np_data.shape)):\n            if i < len(np_shape_like.shape):\n                end_idx[i] = np_shape_like.shape[i]\n    slice_idx = []\n    for b, e in zip(begin_idx, end_idx):\n        slice_idx.append(slice(b, e))\n    np_result = np_data[tuple(slice_idx)]\n    return np_result\n\n\ndef verify_slice_like(executor_kind, data, slice_like, axes, output, dtype=\"float32\"):\n    x = relay.var(\"data\", relay.TensorType(data, dtype))\n    y = relay.var(\"slice_like\", relay.TensorType(slice_like, dtype))\n    z = relay.slice_like(x, y, axes)\n    zz = run_infer_type(z)\n    if axes:\n        assert \"axes\" in z.astext()\n    assert zz.checked_type == relay.ty.TensorType(output, dtype)\n\n    if all(isinstance(v, int) == 0 for v in data) or all(\n        isinstance(v, int) == 0 for v in slice_like\n    ):\n        return\n\n    func = relay.Function([x, y], z)\n    x_data = np.random.uniform(size=data).astype(dtype)\n    y_data = np.random.uniform(size=slice_like).astype(dtype)\n    ref_res = np_slice_like(x_data, y_data, axes)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, y_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_slice_like(executor_kind):\n    d1, d2, d3, d4 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\"), te.var(\"d4\")\n    verify_slice_like(\n        executor_kind, data=(d1, d2, d3), slice_like=(1, 2, 3), axes=None, output=(1, 2, 3)\n    )\n    verify_slice_like(\n        executor_kind, data=(1, 2, 3), slice_like=(d1, d2, d3), axes=None, output=(d1, d2, d3)\n    )\n    verify_slice_like(\n        executor_kind, data=(d2, d3, d4), slice_like=(d1, d2, d3), axes=(1, 2), output=(d2, d2, d3)\n    )\n    verify_slice_like(\n        executor_kind, data=(3, 4, 5), slice_like=(1, 2, 3), axes=None, output=(1, 2, 3)\n    )\n    verify_slice_like(executor_kind, data=(3, 4, 5), slice_like=(1, 2), axes=None, output=(1, 2, 5))\n    verify_slice_like(\n        executor_kind, data=(3, 4, 5), slice_like=(1, 2, 3), axes=(1, 2), output=(3, 2, 3)\n    )\n    verify_slice_like(\n        executor_kind, data=(3, 4, 5), slice_like=(1, 2, 3), axes=(-1, -3), output=(1, 4, 3)\n    )\n    verify_slice_like(\n        executor_kind,\n        data=(1, 3, 224, 224),\n        slice_like=(1, 3, 112, 112),\n        axes=(2, 3),\n        output=(1, 3, 112, 112),\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_reverse_reshape(executor_kind):\n    def verify_reverse_reshape(executor_kind, shape, newshape, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.reverse_reshape(x, newshape=newshape)\n        zz = run_infer_type(z)\n        assert \"newshape=\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_reverse_reshape(executor_kind, (2, 3, 4), (4, 0, 2), (4, 3, 2))\n    verify_reverse_reshape(executor_kind, (2, 3, 4), (2, 0, 0), (2, 3, 4))\n    verify_reverse_reshape(executor_kind, (2, 3, 4), (0, -1), (3, 8))\n    verify_reverse_reshape(executor_kind, (2, 3, 4), (-1, 0), (6, 4))\n    verify_reverse_reshape(executor_kind, (2, 3, 4), (0, -3), (2, 12))\n\n\ndef verify_batch_matmul_with_inputs(\n    executor_kind, x, y, x_np, y_np, out_shape, dtype=\"float32\", trans_x=False, trans_y=True\n):\n    z = relay.nn.batch_matmul(x, y, transpose_a=trans_x, transpose_b=trans_y)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.ty.TensorType(out_shape, dtype)\n\n    input_vars = relay.analysis.free_vars(z)\n    func = relay.Function(input_vars, z)\n    z_np = tvm.topi.testing.batch_matmul(x_np, y_np, trans_x=trans_x, trans_y=trans_y)\n\n    for target, dev in tvm.testing.enabled_targets():\n        if len(input_vars) == 2:\n            z = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_np, y_np\n            )\n        else:\n            z = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(x_np)\n        tvm.testing.assert_allclose(z.numpy(), z_np, rtol=1e-5, atol=1e-5)\n\n\ndef verify_batch_matmul(\n    executor_kind, x_shape, y_shape, out_shape, dtype=\"float32\", trans_x=False, trans_y=True\n):\n    x = relay.var(\"x\", relay.TensorType(x_shape, dtype))\n    y = relay.var(\"y\", relay.TensorType(y_shape, dtype))\n    x_np = np.random.uniform(size=x_shape).astype(dtype)\n    y_np = np.random.uniform(size=y_shape).astype(dtype)\n    verify_batch_matmul_with_inputs(\n        executor_kind, x, y, x_np, y_np, out_shape, dtype, trans_x, trans_y\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_batch_matmul(executor_kind):\n    b, m, n, k = te.size_var(\"b\"), te.size_var(\"m\"), te.size_var(\"n\"), te.size_var(\"k\")\n    x = relay.var(\"x\", relay.TensorType((b, m, k), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((b, n, k), \"float32\"))\n    z = relay.nn.batch_matmul(x, y)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((b, m, n), \"float32\")\n\n    verify_batch_matmul(\n        executor_kind, (1, 16, 32), (1, 16, 32), (1, 16, 16), trans_x=False, trans_y=True\n    )\n    verify_batch_matmul(\n        executor_kind, (5, 16, 32), (5, 16, 32), (5, 16, 16), trans_x=False, trans_y=True\n    )\n    verify_batch_matmul(\n        executor_kind, (5, 16, 32), (5, 20, 32), (5, 16, 20), trans_x=False, trans_y=True\n    )\n    verify_batch_matmul(\n        executor_kind, (30, 16, 32), (30, 20, 32), (30, 16, 20), trans_x=False, trans_y=True\n    )\n    verify_batch_matmul(\n        executor_kind, (1, 32, 16), (1, 16, 32), (1, 16, 16), trans_x=True, trans_y=True\n    )\n    verify_batch_matmul(\n        executor_kind, (5, 16, 32), (5, 32, 16), (5, 16, 16), trans_x=False, trans_y=False\n    )\n    verify_batch_matmul(\n        executor_kind, (5, 32, 16), (5, 32, 20), (5, 16, 20), trans_x=True, trans_y=False\n    )\n\n    x_np = np.random.randn(10, 27, 64).astype(\"float32\")\n    x = relay.var(\"x\", shape=x_np.shape)\n    verify_batch_matmul_with_inputs(executor_kind, x, x, x_np, x_np, (10, 27, 27))\n\n\n@tvm.testing.requires_cascadelake\ndef test_batch_matmul_vnni():\n    x_shape = (16, 32, 96)\n    y_shape = (16, 128, 96)\n    z_shape = (16, 32, 128)\n\n    for lhs_dtype in [\"uint8\", \"int8\"]:\n        x = relay.var(\"x\", shape=x_shape, dtype=lhs_dtype)\n        y = relay.var(\"y\", shape=y_shape, dtype=\"int8\")\n        z = relay.var(\"z\", shape=z_shape, dtype=\"int32\")\n        bmm = relay.nn.batch_matmul(x, y, out_dtype=\"int32\")\n        out = bmm + z\n        mod = tvm.IRModule.from_expr(out)\n\n        target = \"llvm -mcpu=cascadelake\"\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target)\n\n        asm = lib.lib.get_source(\"asm\")\n        assert \"vpdpbusd\" in asm\n\n        dev = tvm.device(target, 0)\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n        x_np = np.random.uniform(1, 10, size=x_shape).astype(lhs_dtype)\n        y_np = np.random.uniform(1, 10, size=y_shape).astype(\"int8\")\n        z_np = np.random.uniform(1, 10, size=z_shape).astype(\"int32\")\n\n        runtime.set_input(\"x\", x_np)\n        runtime.set_input(\"y\", y_np)\n        runtime.set_input(\"z\", z_np)\n        runtime.run()\n\n        out = runtime.get_output(0).numpy()\n        ref = tvm.topi.testing.batch_matmul(x_np, y_np, out_dtype=\"int32\") + z_np\n\n        np.testing.assert_equal(out, ref)\n\n\n@pytest.mark.skip(\"Requires GFX10 AMDGPU\")\ndef test_batch_matmul_rocm_sdot4():\n    x_shape = (16, 32, 96)\n    y_shape = (16, 128, 96)\n\n    lhs_dtype = \"int8\"\n    x = relay.var(\"x\", shape=x_shape, dtype=lhs_dtype)\n    y = relay.var(\"y\", shape=y_shape, dtype=\"int8\")\n    bmm = relay.nn.batch_matmul(x, y, out_dtype=\"int32\")\n\n    mod = tvm.IRModule.from_expr(bmm)\n\n    target = \"rocm -mattr=+dotprod\"\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target)\n\n    asm = lib.lib.imported_modules[0].get_source(\"asm\")\n    assert \"v_dot4_i32_i8\" in asm\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    x_np = np.random.uniform(1, 10, size=x_shape).astype(lhs_dtype)\n    y_np = np.random.uniform(1, 10, size=y_shape).astype(\"int8\")\n\n    runtime.set_input(\"x\", x_np)\n    runtime.set_input(\"y\", y_np)\n    runtime.run()\n\n    out = runtime.get_output(0).numpy()\n    ref = tvm.topi.testing.batch_matmul(x_np, y_np, out_dtype=\"int32\")\n\n    np.testing.assert_equal(out, ref)\n\n\n@tvm.testing.uses_gpu\ndef test_shape_of():\n    shape = (10, 5, 12)\n    x = relay.var(\"x\", shape=shape)\n    func = relay.Function([x], relay.op.shape_of(x))\n    func = run_infer_type(func)\n    x_data = np.random.rand(*shape).astype(\"float32\")\n    for target, dev in tvm.testing.enabled_targets():\n        # Because using graph executor, this op will be optimized after\n        # constant folding pass, here we only test with interpreter\n        for kind in [\"vm\"]:\n            op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x_data)\n            tvm.testing.assert_allclose(op_res.numpy(), np.array(shape).astype(\"int32\"))\n\n\n@tvm.testing.uses_gpu\ndef test_ndarray_size(executor_kind):\n    def verify_ndarray_size(shape):\n        x = relay.var(\"x\", shape=shape)\n        func = relay.Function([x], relay.op.ndarray_size(x))\n        func = run_infer_type(func)\n\n        x_data = np.random.uniform(size=shape).astype(\"float32\")\n        ref_res = np.size(x_data)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    verify_ndarray_size((2, 3, 5))\n    verify_ndarray_size((2, 3, 5, 7))\n\n\ndef verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc):\n    for shape_dtype in [\"int32\", \"int64\"]:\n        x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in dshape], dtype=dtype)\n        y = opfunc(x, out_size, layout)\n        func = relay.Function([x], y)\n\n        np_data = np.random.uniform(low=0, high=255, size=dshape).astype(dtype)\n        np_out = tvm.topi.testing.adaptive_pool(np_data, out_size, pool_type, layout)\n\n        for target, dev in tvm.testing.enabled_targets():\n            relay_out = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                np_data\n            )\n            tvm.testing.assert_allclose(relay_out.numpy(), np_out, rtol=1e-5, atol=1e-5)\n\n\ndef verify_adaptive_pool1d(dshape, out_size, pool_type, layout=\"NCW\", dtype=\"float32\"):\n    opfunc = relay.nn.adaptive_avg_pool1d if pool_type == \"avg\" else relay.nn.adaptive_max_pool1d\n    verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\ndef verify_adaptive_pool2d(dshape, out_size, pool_type, layout=\"NCHW\", dtype=\"float32\"):\n    opfunc = relay.nn.adaptive_avg_pool2d if pool_type == \"avg\" else relay.nn.adaptive_max_pool2d\n    verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\ndef verify_adaptive_pool3d(dshape, out_size, pool_type, layout=\"NCDHW\", dtype=\"float32\"):\n    opfunc = relay.nn.adaptive_avg_pool3d if pool_type == \"avg\" else relay.nn.adaptive_max_pool3d\n    verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\n@tvm.testing.uses_gpu\ndef test_adaptive_pool():\n    verify_adaptive_pool1d((1, 9, 224), (1), \"max\")\n    verify_adaptive_pool1d((1, 3, 224), (3), \"avg\")\n    verify_adaptive_pool1d((1, 3, 224), (3), \"avg\", dtype=\"int32\")\n    verify_adaptive_pool1d((1, 14, 78), (13), \"max\")\n    verify_adaptive_pool1d((1, 5, 97), (96), \"avg\")\n    verify_adaptive_pool1d((1, 224, 3), (1), \"max\", layout=\"NWC\")\n    verify_adaptive_pool1d((1, 3, 224), (3), \"avg\", layout=\"NWC\")\n    verify_adaptive_pool2d((1, 9, 224, 224), (1, 1), \"max\")\n    verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\")\n    verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\", dtype=\"int32\")\n    verify_adaptive_pool2d((1, 14, 56, 78), (34, 13), \"max\")\n    verify_adaptive_pool2d((1, 5, 46, 97), (4, 96), \"avg\")\n    verify_adaptive_pool2d((1, 224, 224, 3), (1, 1), \"max\", layout=\"NHWC\")\n    verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\", layout=\"NHWC\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"max\", layout=\"NCDHW\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NCDHW\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NDHWC\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NCDHW\", dtype=\"int32\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NDHWC\", dtype=\"int32\")\n    verify_adaptive_pool3d((1, 16, 32, 32, 32), (2, 4, 4), \"max\", layout=\"NDHWC\")\n\n\n@tvm.testing.uses_gpu\ndef test_sequence_mask(executor_kind):\n    def _verify(data_shape, mask_value, axis, dtype, itype):\n        max_length = data_shape[axis]\n        nbatch = data_shape[1 - axis]\n        data = relay.var(\"data\", relay.TensorType(data_shape, dtype))\n        valid_length = relay.var(\"valid_length\", relay.TensorType((nbatch,), itype))\n        out = relay.sequence_mask(data, valid_length, mask_value, axis)\n        checked = run_infer_type(out)\n        assert checked.checked_type == relay.ty.TensorType(data_shape, dtype)\n        func = relay.Function([data, valid_length], out)\n        data_np = np.random.uniform(size=data_shape).astype(dtype)\n        valid_length_np = np.random.randint(0, max_length, size=nbatch).astype(itype)\n        gt_out_np = tvm.topi.testing.sequence_mask(data_np, valid_length_np, mask_value, axis)\n\n        for target, dev in tvm.testing.enabled_targets():\n            out_relay = relay.create_executor(executor_kind, device=dev, target=target).evaluate(\n                func\n            )(data_np, valid_length_np)\n            tvm.testing.assert_allclose(out_relay.numpy(), gt_out_np)\n\n    _verify((5, 10), 0.0, 1, \"float32\", \"int32\")\n    _verify((2, 3, 5, 3), 0.0, 0, \"float32\", \"int64\")\n    _verify((5, 8, 3), 0.1, 1, \"float64\", \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_one_hot(executor_kind):\n    def _get_oshape(indices_shape, depth, axis):\n        oshape = []\n        true_axis = len(indices_shape) if axis == -1 else axis\n        ndim = len(indices_shape) + 1\n        indices_index = 0\n        for i in range(0, ndim):\n            if i == true_axis:\n                oshape.append(depth)\n            else:\n                oshape.append(indices_shape[indices_index])\n                indices_index += 1\n\n        return oshape\n\n    def _verify(indices_shape, depth, on_value, off_value, axis, dtype):\n        indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n        on_value_const = relay.const(on_value)\n        off_value_const = relay.const(off_value)\n        out = relay.one_hot(indices, on_value_const, off_value_const, depth, axis, dtype)\n        checked = run_infer_type(out)\n        assert checked.checked_type == relay.ty.TensorType(\n            _get_oshape(indices_shape, depth, axis), dtype\n        )\n        func = relay.Function([indices], out)\n        indices_np = np.random.randint(0, depth, size=indices_shape).astype(\"int32\")\n        out_np = tvm.topi.testing.one_hot(indices_np, on_value, off_value, depth, axis, dtype)\n\n        for target, dev in tvm.testing.enabled_targets():\n            out_relay = relay.create_executor(executor_kind, device=dev, target=target).evaluate(\n                func\n            )(indices_np)\n            tvm.testing.assert_allclose(out_relay.numpy(), out_np)\n\n    _verify((3,), 3, 1, 0, -1, \"int32\")\n    _verify((3,), 3, 1.0, 0.0, -1, \"float32\")\n    _verify((2, 2), 5, 2, -2, 0, \"int32\")\n    _verify((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    _verify((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n    _verify((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_matrix_set_diag(executor_kind):\n    def _verify(input_shape, diagonal_shape, dtype, k=0, align=\"RIGHT_LEFT\"):\n        input = relay.var(\"input\", relay.TensorType(input_shape, dtype))\n        diagonal = relay.var(\"diagonal\", relay.TensorType(diagonal_shape, dtype))\n        out = relay.matrix_set_diag(input, diagonal, k, align)\n\n        in_type = run_infer_type(input)\n        out_type = run_infer_type(out)\n        assert in_type.checked_type == out_type.checked_type\n\n        func = relay.Function([input, diagonal], out)\n        input_np = np.random.randint(-100, 100, size=input_shape).astype(dtype)\n        diagonal_np = np.random.randint(-100, 100, size=diagonal_shape).astype(dtype)\n        out_np = tvm.topi.testing.matrix_set_diag(input_np, diagonal_np, k, align)\n\n        for target, dev in tvm.testing.enabled_targets():\n            out_relay = relay.create_executor(executor_kind, device=dev, target=target).evaluate(\n                func\n            )(input_np, diagonal_np)\n            tvm.testing.assert_allclose(out_relay.numpy(), out_np)\n\n    _verify((2, 2), (2,), \"float32\")\n    _verify((4, 3, 3), (4, 3), \"int32\")\n    _verify((2, 3, 4), (2, 3), \"float32\", 1)\n    _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"LEFT_RIGHT\")\n    _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"LEFT_LEFT\")\n    _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"RIGHT_RIGHT\")\n\n\n@tvm.testing.parametrize_targets\ndef test_nll_loss(executor_kind, dev, target):\n    def _get_oshape(target_shape, reduction):\n        if reduction == \"none\":\n            return target_shape\n        else:\n            return []\n\n    def _verify(prediction_shape, reduction=\"mean\", ignore_index=-100, dtype=\"float32\"):\n        C = prediction_shape[1]\n        target_shape = prediction_shape[:1] + prediction_shape[2:]\n\n        predictions = relay.var(\"predictions\", relay.TensorType(prediction_shape, dtype))\n        targets = relay.var(\"targets\", relay.TensorType(target_shape, \"int32\"))\n        weights = relay.var(\"weights\", relay.TensorType((C,), dtype))\n        out = relay.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)\n        checked = run_infer_type(out)\n        assert checked.checked_type == relay.ty.TensorType(\n            _get_oshape(target_shape, reduction), dtype\n        )\n        func = relay.Function([predictions, targets, weights], out)\n        predictions_np = np.random.uniform(size=prediction_shape).astype(dtype)\n        targets_np = np.random.randint(0, C, target_shape).astype(\"int32\")\n        weights_np = np.random.uniform(size=(C,)).astype(dtype)\n        out_np = tvm.topi.testing.nll_loss(\n            predictions_np, targets_np, weights_np, reduction, ignore_index\n        )\n\n        out_relay = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            predictions_np, targets_np, weights_np\n        )\n        tvm.testing.assert_allclose(out_relay.numpy(), out_np, rtol=1e-6, atol=1e-6)\n\n    _verify((10, 5))\n    _verify((10, 5, 2, 2))\n    _verify((10, 5), reduction=\"sum\")\n    _verify((10, 5), reduction=\"none\")\n    _verify((10, 5), ignore_index=3)\n    _verify((10, 5), dtype=\"float64\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level2.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level2 operator test cases.\n\"\"\"\nimport sys\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import autotvm, relay, te\nfrom tvm.contrib import utils, cudnn\nfrom tvm.ir.module import IRModule\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\nfrom tvm.topi.cuda.conv3d_winograd import _infer_tile_size\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv1d_infer_type():\n    # symbolic in batch dimension\n    n, c, w = te.var(\"n\"), 10, 224\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, w), \"float32\"))\n    w = relay.var(\"w\")\n    y = relay.nn.conv1d(x, w, kernel_size=3, padding=(1, 1), channels=2)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 224), \"float32\")\n    assert yy.args[1].checked_type == relay.TensorType((2, 10, 3), \"float32\")\n\n    # infer by shape of w, mixed precision\n    n, c, w = te.var(\"n\"), 10, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, w), \"int8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3), \"int8\"))\n    y = relay.nn.conv1d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222), \"int32\")\n\n    # infer shape in case of different dtypes for input and weight.\n    n, c, w = te.var(\"n\"), 10, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, w), \"uint8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3), \"int8\"))\n    y = relay.nn.conv1d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222), \"int32\")\n\n    # Infer with NWC\n    n, c, w = 4, 32, 224\n    x = relay.var(\"x\", relay.TensorType((n, w, c), \"int8\"))\n    wt = relay.var(\"w\")\n    y = relay.nn.conv1d(\n        x, wt, kernel_size=3, padding=(1, 1), channels=16, data_layout=\"NWC\", out_dtype=\"int32\"\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, w, 16), \"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv1d_run():\n    def run_test_conv1d(\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        fref=None,\n        dilation=1,\n        except_targets=None,\n        **attrs,\n    ):\n        if except_targets is None:\n            except_targets = []\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", dtype=dtype)\n        y = relay.nn.conv1d(x, w, padding=padding, dilation=dilation, **attrs)\n        func = relay.Function([x, w], y)\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        ref_res = tvm.topi.testing.conv1d_ncw_python(\n            data.astype(out_dtype), kernel.astype(out_dtype), 1, padding, dilation\n        )\n\n        for target, dev in tvm.testing.enabled_targets():\n            if target in except_targets:\n                continue\n            dev = tvm.device(target, 0)\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                data, kernel\n            )\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    # normal conv1d\n    dshape = (1, 3, 224)\n    kshape = (10, 3, 3)\n    run_test_conv1d(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=3\n    )\n    # mixed precision\n    run_test_conv1d(\"int8\", \"int32\", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=3)\n    # dilated conv2d\n    dshape = (1, 3, 18)\n    kshape = (10, 3, 3)\n    run_test_conv1d(\n        \"float32\",\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=10,\n        kernel_size=3,\n        dilation=3,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_infer_type():\n    # symbolic in batch dimension\n    n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, h, w), \"float32\"))\n    w = relay.var(\"w\")\n    y = relay.nn.conv2d(x, w, kernel_size=(3, 3), padding=(1, 1), channels=2)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 224, 224), \"float32\")\n    assert yy.args[1].checked_type == relay.TensorType((2, 10, 3, 3), \"float32\")\n\n    # infer by shape of w, mixed precision\n    n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"int8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3, 3), \"int8\"))\n    y = relay.nn.conv2d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222, 222), \"int32\")\n\n    # infer shape in case of different dtypes for input and weight.\n    n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"uint8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3, 3), \"int8\"))\n    y = relay.nn.conv2d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222, 222), \"int32\")\n\n    # Infer with a different layout\n    n, c, h, w = 4, 32, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n // 4, c // 4, h, w, 4, 4), \"int8\"))\n    wt = relay.var(\"w\")\n    y = relay.nn.conv2d(\n        x,\n        wt,\n        kernel_size=(3, 3),\n        padding=(1, 1),\n        channels=16,\n        data_layout=\"NCHW4n4c\",\n        kernel_layout=\"OIHW4o4i\",\n        out_dtype=\"int32\",\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1, 4, 224, 224, 4, 4), \"int32\")\n    assert yy.args[1].checked_type == relay.TensorType((4, 8, 3, 3, 4, 4), \"int8\")\n\n    # Infer with NHWC\n    n, c, h, w = 4, 32, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, h, w, c), \"int8\"))\n    wt = relay.var(\"w\")\n    y = relay.nn.conv2d(\n        x,\n        wt,\n        kernel_size=(3, 3),\n        padding=(1, 1),\n        channels=16,\n        data_layout=\"NHWC\",\n        out_dtype=\"int32\",\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, h, w, 16), \"int32\")\n\n\nclass TestConv2D:\n    config = {\n        \"group1\": dict(\n            dtype=\"float32\",\n            out_dtype=\"float32\",\n            scale=1,\n            dshape=(1, 32, 18, 18),\n            kshape=(32, 4, 3, 3),\n            padding=(1, 1),\n            channels=32,\n            groups=8,\n            kernel_size=(3, 3),\n            dilation=(1, 1),\n        ),\n        \"group2\": dict(\n            dtype=\"float32\",\n            out_dtype=\"float32\",\n            scale=1,\n            dshape=(1, 32, 18, 18),\n            kshape=(64, 1, 3, 3),\n            padding=(1, 1),\n            channels=64,\n            groups=32,\n            kernel_size=(3, 3),\n            dilation=(1, 1),\n        ),\n        \"normal\": dict(\n            dtype=\"float32\",\n            out_dtype=\"float32\",\n            scale=1,\n            dshape=(1, 3, 224, 224),\n            kshape=(10, 3, 3, 3),\n            padding=(1, 1),\n            channels=10,\n            groups=1,\n            kernel_size=(3, 3),\n            dilation=(1, 1),\n        ),\n        \"mixed_precision_int8_int32_case1\": dict(\n            dtype=\"int8\",\n            out_dtype=\"int32\",\n            scale=1,\n            dshape=(1, 3, 224, 224),\n            kshape=(10, 3, 3, 3),\n            padding=(1, 1),\n            channels=10,\n            groups=1,\n            kernel_size=(3, 3),\n            dilation=(1, 1),\n        ),\n        \"mixed_precision_int8_int32_case2\": dict(\n            dtype=\"int8\",\n            out_dtype=\"int32\",\n            scale=1,\n            dshape=(1, 3, 224, 224),\n            kshape=(10, 3, 1, 3),\n            padding=(0, 1),\n            channels=10,\n            groups=1,\n            kernel_size=(1, 3),\n            dilation=(1, 1),\n        ),\n        \"dilated\": dict(\n            dtype=\"float32\",\n            out_dtype=\"float32\",\n            scale=1,\n            dshape=(1, 3, 18, 18),\n            kshape=(10, 3, 3, 3),\n            padding=(1, 1),\n            channels=10,\n            groups=1,\n            kernel_size=(3, 3),\n            dilation=(3, 3),\n        ),\n    }\n\n    # TODO(Lunderberg): Make a cleaner utility for this type of\n    # parametrization.  It would be much nicer to have the fixture\n    # name come from the dictionaries themselves, rather than needing\n    # to be re-packed into tuples.\n    (\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding,\n        channels,\n        groups,\n        kernel_size,\n        dilation,\n    ) = tvm.testing.parameters(\n        *[\n            [\n                d[p]\n                for p in [\n                    \"dtype\",\n                    \"out_dtype\",\n                    \"scale\",\n                    \"dshape\",\n                    \"kshape\",\n                    \"padding\",\n                    \"channels\",\n                    \"groups\",\n                    \"kernel_size\",\n                    \"dilation\",\n                ]\n            ]\n            for d in config.values()\n        ],\n        ids=config.keys(),\n    )\n\n    def test_run(\n        self,\n        target,\n        dev,\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding,\n        groups,\n        dilation,\n        channels,\n        kernel_size,\n    ):\n        target = tvm.target.Target(target)\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=dtype)\n        y = relay.nn.conv2d(\n            x,\n            w,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n            channels=channels,\n            kernel_size=kernel_size,\n        )\n        func = relay.Function([x, w], y)\n\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        dkernel = tvm.topi.testing.dilate_python(kernel, (1, 1) + dilation)\n\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        ref_res = tvm.topi.testing.conv2d_nchw_python(\n            data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding, groups=groups\n        )\n\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n            data, kernel\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-4, atol=1e-4)\n\n\ndef test_compile_depthwise_conv2d_arm_cpu():\n    dtype = \"float32\"\n    out_dtype = \"float32\"\n    scale = 1\n    dshape = (1, 512, 32, 32)\n    kshape = (512, 1, 3, 3)\n    padding = (1, 1)\n    channels = 512\n    groups = 512\n    kernel_size = (3, 3)\n    dilation = (1, 1)\n\n    x = relay.var(\"x\", shape=dshape, dtype=dtype)\n    w = relay.var(\"w\", shape=kshape, dtype=dtype)\n    y = relay.nn.conv2d(\n        x,\n        w,\n        padding=padding,\n        dilation=dilation,\n        groups=groups,\n        channels=channels,\n        kernel_size=kernel_size,\n    )\n    func = relay.Function([x, w], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n\n    test_schedule = '{\"i\": [\"llvm -device=arm_cpu\", \"depthwise_conv2d_nchw_spatial_pack.arm_cpu\", \\\n                    [[\"TENSOR\", [1, 512, 32, 32], \"float32\"], \\\n                    [\"TENSOR\", [512, 1, 3, 3], \"float32\"], \\\n                    [1, 1], [1, 1], [1, 1], \"float32\"], {}, \\\n                    [\"depthwise_conv2d_nchw_spatial_pack.arm_cpu\", [1, 512, 32, 32, \"float32\"], \\\n                    [512, 1, 3, 3, \"float32\"], [1, 1], [1, 1], [1, 1], \"float32\"], \\\n                    {\"i\": 743640, \"t\": \"\", \"c\": null, \\\n                    \"e\": [[\"tile_co\", \"sp\", [32, 16]], [\"tile_oh\", \"sp\", [8, 1]], \\\n                    [\"tile_ow\", \"sp\", [1, 8]], \\\n                    [\"reorder_0\", \"re\", [0, 1, 2, 3, 4, 5, 8, 6, 7]], \\\n                    [\"reorder_1\", \"re\", [0, 1, 2, 3, 6, 4, 5]], \\\n                    [\"ann_reduce\", \"an\", [\"unroll\", \"none\"]], \\\n                    [\"ann_spatial\", \"an\", [\"unroll\", \"unroll\", \"vec\"]], \\\n                    [\"data_pad_inline\", \"ot\", 4], [\"data_vec_inline\", \"ot\", 1], \\\n                    [\"conv_inline\", \"ot\", 0]]}], \"r\": [[0.0002933163], \\\n                    0, 3.1976189613342285, 1570811630.6058347], \"v\": 0.1}'\n    temp = utils.tempdir()\n    with open(temp.relpath(\"temp.log\"), \"w\") as log_file:\n        log_file.write(test_schedule)\n    with autotvm.apply_history_best(temp.relpath(\"temp.log\")):\n        with tvm.transform.PassContext(opt_level=3):\n            print(\"Compiling...\")\n            graph_json, mod, params = tvm.relay.build(mod, target=\"llvm -device=arm_cpu\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_winograd():\n    class WinogradFallback(autotvm.FallbackContext):\n        def _query_inside(self, target, workload):\n            key = (target, workload)\n            if key in self.memory:\n                return self.memory[key]\n            cfg = autotvm.task.space.FallbackConfigEntity()\n            cfg.is_fallback = False\n            cfg.cost = 0.1 if \"winograd\" in workload[0] else 1\n            cfg[\"tile_b\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_y\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_x\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_rc\"] = autotvm.task.space.SplitEntity([-1, 1])\n            cfg[\"auto_unroll_max_step\"] = autotvm.task.space.OtherOptionEntity(1500)\n            cfg[\"unroll_explicit\"] = autotvm.task.space.OtherOptionEntity(1)\n            self.memory[key] = cfg\n            return cfg\n\n    def run_test_conv2d_cuda(\n        dtype, out_dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs\n    ):\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=dtype)\n        y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs)\n        func = relay.Function([x, w], y)\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n        mod = relay.transform.InferType()(mod)\n\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        ref_res = tvm.topi.testing.conv2d_nchw_python(\n            data.astype(out_dtype), kernel.astype(out_dtype), 1, padding, groups=groups\n        )\n\n        with WinogradFallback(), tvm.transform.PassContext(opt_level=3):\n            for target, dev in tvm.testing.enabled_targets():\n                if target != \"cuda\":\n                    continue\n                dev = tvm.device(target, 0)\n                params = {\"w\": tvm.nd.array(kernel)}\n                graph, lib, params = relay.build_module.build(mod, target=target, params=params)\n                module = tvm.contrib.graph_executor.create(graph, lib, dev)\n                module.set_input(\"x\", tvm.nd.array(data))\n                module.set_input(**params)\n                module.run()\n                op_res1 = module.get_output(0)\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-3, atol=1e-3)\n\n    # normal winograd: stride 1, padding 1, kernel 3x3\n    dshape = (1, 80, 73, 73)\n    kshape = (192, 80, 3, 3)\n    run_test_conv2d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(1, 1), channels=192, kernel_size=(3, 3)\n    )\n    # extended winograd: stride 1, padding N, kernel 3x3\n    run_test_conv2d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(0, 0), channels=192, kernel_size=(3, 3)\n    )\n    run_test_conv2d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(2, 2), channels=192, kernel_size=(3, 3)\n    )\n    # extended winograd: stride 1, padding N, kernel NxN\n    kshape = (192, 80, 7, 7)\n    run_test_conv2d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(2, 2), channels=192, kernel_size=(7, 7)\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_infer_type():\n    # symbolic in batch dimension\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, d, h, w), \"float32\"))\n    w = relay.var(\"w\")\n    y = relay.nn.conv3d(x, w, kernel_size=(3, 3, 3), padding=(1, 1, 1), channels=2)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 224, 224, 224), \"float32\")\n    assert yy.args[1].checked_type == relay.TensorType((2, 10, 3, 3, 3), \"float32\")\n\n    # infer by shape of w, mixed precision\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"int8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3, 3, 3), \"int8\"))\n    y = relay.nn.conv3d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222, 222, 222), \"int32\")\n\n    # infer shape in case of different dtypes for input and weight.\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"uint8\"))\n    w = relay.var(\"w\", relay.TensorType((2, 10, 3, 3, 3), \"int8\"))\n    y = relay.nn.conv3d(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 222, 222, 222), \"int32\")\n\n    # Infer with NDHWC\n    n, c, d, h, w = 4, 32, 224, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, d, h, w, c), \"int8\"))\n    wt = relay.var(\"w\")\n    y = relay.nn.conv3d(\n        x,\n        wt,\n        kernel_size=(3, 3, 3),\n        padding=(1, 1, 1),\n        channels=16,\n        data_layout=\"NDHWC\",\n        out_dtype=\"int32\",\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, d, h, w, 16), \"int32\")\n\n    # Infer with groups\n    x = relay.var(\"x\", relay.TensorType((1, 16, 224, 224, 224), \"float32\"))\n    w = relay.var(\"w\", relay.TensorType((4, 4, 1, 1, 1), \"float32\"))\n    y = relay.nn.conv3d(x, w, groups=4, kernel_size=(1, 1, 1), channels=4)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1, 4, 224, 224, 224), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_run():\n    def run_test_conv3d(\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding=(1, 1, 1),\n        fref=None,\n        groups=1,\n        dilation=(1, 1, 1),\n        except_targets=None,\n        **attrs,\n    ):\n        if except_targets is None:\n            except_targets = []\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", dtype=dtype)\n        y = relay.nn.conv3d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs)\n        func = relay.Function([x, w], y)\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        dkernel = tvm.topi.testing.dilate_python(kernel, (1, 1) + dilation)\n        if fref is None:\n            ref_res = tvm.topi.testing.conv3d_ncdhw_python(\n                data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding, groups=groups\n            )\n        else:\n            ref_res = fref(data.astype(out_dtype), dkernel.astype(out_dtype))\n\n        for target, dev in tvm.testing.enabled_targets():\n            if target in except_targets:\n                continue\n            dev = tvm.device(target, 0)\n\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                data, kernel\n            )\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    # normal conv3d\n    dshape = (1, 3, 5, 224, 224)\n    kshape = (10, 3, 3, 3, 3)\n    run_test_conv3d(\n        \"float32\",\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1, 1),\n        channels=10,\n        kernel_size=(3, 3, 3),\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_ndhwc_run():\n    def run_test_conv3d(\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding=(1, 1, 1),\n        fref=None,\n        groups=1,\n        dilation=(1, 1, 1),\n        except_targets=None,\n        **attrs,\n    ):\n        if except_targets is None:\n            except_targets = []\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", dtype=dtype)\n        y = relay.nn.conv3d(\n            x,\n            w,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n            data_layout=\"NDHWC\",\n            kernel_layout=\"DHWIO\",\n            **attrs,\n        )\n        func = relay.Function([x, w], y)\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        dkernel = tvm.topi.testing.dilate_python(kernel, (1, 1) + dilation)\n        if fref is None:\n            ref_res = tvm.topi.testing.conv3d_ndhwc_python(\n                data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding\n            )\n        else:\n            ref_res = fref(data.astype(out_dtype), dkernel.astype(out_dtype))\n\n        for target, dev in tvm.testing.enabled_targets():\n            if target in except_targets:\n                continue\n            dev = tvm.device(target, 0)\n\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                data, kernel\n            )\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    # normal conv3d\n    dshape = (1, 5, 224, 224, 6)\n    kshape = (3, 3, 3, 6, 10)\n    run_test_conv3d(\n        \"float32\",\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1, 1),\n        channels=10,\n        kernel_size=(3, 3, 3),\n        except_targets=[\"cuda\"],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_winograd():\n    class WinogradFallback(autotvm.FallbackContext):\n        def _query_inside(self, target, workload):\n            key = (target, workload)\n            if key in self.memory:\n                return self.memory[key]\n            cfg = autotvm.task.space.FallbackConfigEntity()\n            cfg.is_fallback = False\n            cfg.cost = 0.1 if \"winograd\" in workload[0] else 1\n            cfg[\"tile_b\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_y\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_x\"] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])\n            cfg[\"tile_rc\"] = autotvm.task.space.SplitEntity([-1, 1])\n            cfg[\"auto_unroll_max_step\"] = autotvm.task.space.OtherOptionEntity(0)\n            cfg[\"unroll_explicit\"] = autotvm.task.space.OtherOptionEntity(1)\n            self.memory[key] = cfg\n            return cfg\n\n    def run_test_conv3d_cuda(\n        dtype,\n        out_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding=(1, 1, 1),\n        groups=1,\n        dilation=(1, 1, 1),\n        prepack=False,\n        **attrs,\n    ):\n\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=dtype)\n        if prepack:\n            tile_size = _infer_tile_size(np.zeros(shape=dshape), np.zeros(shape=kshape))\n            w_packed = relay.nn.contrib_conv3d_winograd_weight_transform(w, tile_size)\n\n            y = relay.nn.contrib_conv3d_winograd_without_weight_transform(\n                x,\n                w_packed,\n                tile_size,\n                padding=padding,\n                dilation=dilation,\n                groups=groups,\n                channels=kshape[0],\n                **attrs,\n            )\n        else:\n            y = relay.nn.conv3d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs)\n        func = relay.Function([x, w], y)\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n        mod = relay.transform.InferType()(mod)\n\n        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n        ref_res = tvm.topi.testing.conv3d_ncdhw_python(\n            data.astype(out_dtype), kernel.astype(out_dtype), 1, padding, groups=groups\n        )\n\n        with WinogradFallback(), tvm.transform.PassContext(opt_level=3):\n            for target, dev in tvm.testing.enabled_targets():\n                if target != \"cuda\":\n                    continue\n                dev = tvm.device(target, 0)\n                params = {\"w\": tvm.nd.array(kernel)}\n                graph, lib, params = relay.build_module.build(mod, target=target, params=params)\n                module = tvm.contrib.graph_executor.create(graph, lib, dev)\n                module.set_input(\"x\", tvm.nd.array(data))\n                module.set_input(**params)\n                module.run()\n                op_res1 = module.get_output(0)\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-3, atol=1e-3)\n\n    # normal winograd: stride 1, padding 1, kernel 3x3x3\n    dshape = (1, 32, 16, 16, 16)\n    kshape = (64, 32, 3, 3, 3)\n    run_test_conv3d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(1, 1, 1), kernel_size=(3, 3, 3)\n    )\n    # Without depth transform using 1x3x3 kernel.\n    kshape = (64, 32, 1, 3, 3)\n    run_test_conv3d_cuda(\n        \"float32\", \"float32\", 1, dshape, kshape, padding=(0, 1, 1), kernel_size=(1, 3, 3)\n    )\n\n    # extended winograd: stride 1, padding N, kernel NxNxN\n    dshape = (1, 61, 20, 20, 20)\n    kshape = (120, 61, 5, 5, 5)\n    run_test_conv3d_cuda(\n        \"float32\",\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(2, 2, 2),\n        channels=120,\n        kernel_size=(5, 5, 5),\n    )\n    # Without depth transform\n    kshape = (120, 61, 1, 5, 5)\n    run_test_conv3d_cuda(\n        \"float32\",\n        \"float32\",\n        1,\n        dshape,\n        kshape,\n        padding=(0, 2, 2),\n        channels=120,\n        kernel_size=(1, 5, 5),\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_transpose_infer_type():\n    # symbolic in batch dimension\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, d, h, w), \"float32\"))\n    w = relay.var(\"w\")\n    y = relay.nn.conv3d_transpose(x, w, kernel_size=(3, 3, 3), padding=(1, 1, 1), channels=2)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 2, 224, 224, 224), \"float32\")\n\n    assert yy.args[1].checked_type == relay.TensorType((10, 2, 3, 3, 3), \"float32\")\n\n    # infer by shape of w, mixed precision\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"int8\"))\n    w = relay.var(\"w\", relay.TensorType((10, 12, 3, 3, 3), \"int8\"))\n    y = relay.nn.conv3d_transpose(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 12, 226, 226, 226), \"int32\")\n\n    # infer shape in case of different dtypes for input and weight.\n    n, c, d, h, w = te.size_var(\"n\"), 10, 224, 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"uint8\"))\n    w = relay.var(\"w\", relay.TensorType((10, 12, 3, 3, 3), \"int8\"))\n    y = relay.nn.conv3d_transpose(x, w, out_dtype=\"int32\")\n    assert 'out_dtype=\"int32\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 12, 226, 226, 226), \"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_transpose_ncdhw_run():\n    dshape = (1, 3, 24, 24, 24)\n    kshape = (3, 4, 2, 2, 2)\n\n    x = relay.var(\"x\", shape=dshape)\n    w = relay.var(\"w\")\n    y = relay.nn.conv3d_transpose(\n        x, w, channels=4, kernel_size=(2, 2, 2), strides=(1, 1, 1), padding=(1, 1, 1)\n    )\n    func = relay.Function([x, w], y)\n    dtype = \"float32\"\n\n    data = np.random.uniform(size=dshape).astype(dtype)\n    kernel = np.random.uniform(size=kshape).astype(dtype)\n    ref_res = tvm.topi.testing.conv3d_transpose_ncdhw_python(data, kernel, 1, 1, 0)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n            data, kernel\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_transpose_infer_type():\n    # symbolic in batch dimension\n    n, c, h, w = te.size_var(\"n\"), 10, 10, 12\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    w = relay.var(\"w\", relay.IncompleteType())\n    y = relay.nn.conv2d_transpose(x, w, kernel_size=(3, 3), padding=(1, 1), channels=15)\n    assert \"channels=15\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 15, 10, 12), \"float32\")\n    assert yy.args[1].checked_type == relay.TensorType((10, 15, 3, 3), \"float32\")\n\n    # infer by shape of w, mixed precision\n    n, h, w, c = te.size_var(\"n\"), 10, 10, 12\n    x = relay.var(\"x\", relay.TensorType((n, h, w, c), \"float32\"))\n    w = relay.var(\"w\", relay.TensorType((12, 11, 5, 5), \"float32\"))\n    y = relay.nn.conv2d_transpose(x, w, output_padding=(1, 1), channels=11, data_layout=\"NHWC\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 15, 15, 11), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_transpose_nchw_run():\n    k_layouts = {\"OIHW\": (10, 3, 3, 3), \"IOHW\": (3, 10, 3, 3)}\n    output_padding = (1, 1)\n\n    for k_layout, kshape in k_layouts.items():\n        dshape = (1, 3, 18, 18)\n        x = relay.var(\"x\", shape=dshape)\n        w = relay.var(\"w\")\n        y = relay.nn.conv2d_transpose(\n            x,\n            w,\n            channels=10,\n            kernel_size=(3, 3),\n            strides=(2, 2),\n            padding=(1, 1),\n            output_padding=output_padding,\n            kernel_layout=k_layout,\n            data_layout=\"NCHW\",\n        )\n        func = relay.Function([x, w], y)\n        dtype = \"float32\"\n        data = np.random.uniform(size=dshape).astype(dtype)\n        kernel = np.random.uniform(size=kshape).astype(dtype)\n\n        if k_layout != \"IOHW\":\n            # Must be OIHW so switch\n            kernel_iohw = np.transpose(kernel, [1, 0, 2, 3])\n        else:\n            kernel_iohw = kernel\n\n        ref_res = tvm.topi.testing.conv2d_transpose_nchw_python(\n            data, kernel_iohw, 2, 1, output_padding\n        )\n\n        enabled_targets = tvm.testing.enabled_targets()\n\n        if cudnn.exists() and k_layout == \"IOHW\":\n            enabled_targets.append((\"cuda -libs=cudnn\", tvm.cuda(0)))\n\n        for target, dev in enabled_targets:\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                data, kernel\n            )\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_transpose_nhwc_run():\n    dshape_nhwc = (1, 18, 18, 3)\n    kshape_hwoi = (3, 3, 10, 3)\n    x = relay.var(\"x\", shape=dshape_nhwc)\n    w = relay.var(\"w\")\n\n    y = relay.nn.conv2d_transpose(\n        x,\n        w,\n        channels=10,\n        kernel_size=(3, 3),\n        strides=(2, 2),\n        padding=(1, 1),\n        output_padding=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    func = relay.Function([x, w], y)\n    dtype = \"float32\"\n    data = np.random.uniform(size=dshape_nhwc).astype(dtype)\n    kernel = np.random.uniform(size=kshape_hwoi).astype(dtype)\n\n    ref_res = tvm.topi.testing.conv2d_transpose_nhwc_python(\n        data, kernel, \"HWOI\", 2, 1, output_padding=(1, 1)\n    )\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n            data, kernel\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_transpose_nhwc_cudnn():\n    if not cudnn.exists():\n        return\n\n    dshape_nhwc = (1, 18, 18, 3)\n    kshape_ihwo = (3, 3, 3, 10)\n    x = relay.var(\"x\", shape=dshape_nhwc)\n    w = relay.var(\"w\", shape=kshape_ihwo)\n\n    y = relay.nn.conv2d_transpose(\n        x,\n        w,\n        channels=10,\n        kernel_size=(3, 3),\n        strides=(2, 2),\n        padding=(1, 1),\n        output_padding=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"IHWO\",\n    )\n    func = relay.Function([x, w], y)\n    dtype = \"float32\"\n    data = np.random.uniform(size=dshape_nhwc).astype(dtype)\n    kernel = np.random.uniform(size=kshape_ihwo).astype(dtype)\n\n    ref_res = tvm.topi.testing.conv2d_transpose_nhwc_python(\n        data, np.transpose(kernel, [1, 2, 3, 0]), \"HWOI\", 2, 1, output_padding=(1, 1)\n    )\n\n    target = \"cuda -libs=cudnn\"\n    dev = tvm.cuda(0)\n\n    op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data, kernel)\n    tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_conv1d_transpose_ncw_run():\n    dshape = (1, 3, 18)\n    kshape = (3, 10, 3)\n    oshape = (1, 10, 36)\n    x = relay.var(\"x\", shape=dshape)\n    w = relay.var(\"w\")\n    y = relay.nn.conv1d_transpose(\n        x, w, channels=10, kernel_size=(3,), strides=(2,), padding=(1,), output_padding=(1,)\n    )\n    func = relay.Function([x, w], y)\n    dtype = \"float32\"\n    data = np.random.uniform(size=dshape).astype(dtype)\n    kernel = np.random.uniform(size=kshape).astype(dtype)\n    ref_res = tvm.topi.testing.conv1d_transpose_ncw_python(data, kernel, 2, 1, output_padding=(1,))\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n            data, kernel\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling_infer_type():\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    scale = tvm.tir.const(2.0, \"float64\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.upsampling(x, scale_h=2, scale_w=2, layout=\"NCHW\", method=\"bilinear\")\n    'method=\"BINLINEAR\"' in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType(\n        (\n            n,\n            c,\n            tvm.tir.Cast(\"int32\", te.round(h * scale)),\n            tvm.tir.Cast(\"int32\", te.round(w * scale)),\n        ),\n        \"float32\",\n    )\n    n, c = te.size_var(\"n\"), te.size_var(\"c\")\n    x = relay.var(\"x\", relay.TensorType((n, c, 100, 200), \"float32\"))\n    y = relay.nn.upsampling(x, scale_h=2, scale_w=2, layout=\"NCHW\", method=\"bilinear\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, 200, 400), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling3d_infer_type():\n    n, c, d, h, w = (\n        te.size_var(\"n\"),\n        te.size_var(\"c\"),\n        te.size_var(\"d\"),\n        te.size_var(\"h\"),\n        te.size_var(\"w\"),\n    )\n    scale = tvm.tir.const(2.0, \"float64\")\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"float32\"))\n    y = relay.nn.upsampling3d(\n        x, scale_d=2, scale_h=2, scale_w=2, layout=\"NCDHW\", method=\"trilinear\"\n    )\n\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType(\n        (\n            n,\n            c,\n            tvm.tir.Cast(\"int32\", te.round(d * scale)),\n            tvm.tir.Cast(\"int32\", te.round(h * scale)),\n            tvm.tir.Cast(\"int32\", te.round(w * scale)),\n        ),\n        \"float32\",\n    )\n    n, c = te.size_var(\"n\"), te.size_var(\"c\")\n    x = relay.var(\"x\", relay.TensorType((n, c, 100, 100, 200), \"float32\"))\n    y = relay.nn.upsampling3d(\n        x, scale_d=2, scale_h=2, scale_w=2, layout=\"NCDHW\", method=\"trilinear\"\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, 200, 200, 400), \"float32\")\n\n\ndef _test_global_pool2d(opfunc, reffunc):\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), 224, 224\n    x = relay.var(\"x\", relay.TensorType((n, h, w, c), \"float32\"))\n    y = opfunc(x, layout=\"NHWC\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 1, 1, c), \"float32\")\n\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = opfunc(x)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, 1, 1), \"float32\")\n    # test execution\n    dtype = \"float32\"\n    dshape = (1, 1024, 7, 7)\n    x = relay.var(\"x\", shape=dshape)\n    y = opfunc(x)\n    func = relay.Function([x], y)\n    data = np.random.uniform(size=dshape).astype(dtype)\n    ref_res = reffunc(data, axis=(2, 3), keepdims=True)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_pool2d():\n    def _test_pool2d(opfunc, pool_type, pool_size=2, strides=2, dilation=1, padding=0):\n        n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n        y = opfunc(x, pool_size=(1, 1))\n        assert \"pool_size=\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, 10, 224, 224), \"float32\")\n        # test execution\n        dtype = \"float32\"\n        dshape = (1, 3, 28, 28)\n        x = relay.var(\"x\", shape=dshape)\n        y = opfunc(x, pool_size=pool_size, strides=strides, dilation=dilation, padding=padding)\n        func = relay.Function([x], y)\n        data = np.random.uniform(size=dshape).astype(dtype)\n        ref_res = tvm.topi.testing.poolnd_python(\n            data,\n            [pool_size, pool_size],\n            [strides, strides],\n            [dilation, dilation],\n            [padding, padding],\n            [padding, padding],\n            pool_type,\n            count_include_pad=False,\n            ceil_mode=False,\n        )\n        for target, dev in tvm.testing.enabled_targets():\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    def _test_pool2d_int(opfunc, reffunc, dtype):\n        n, c, h, w = te.size_var(\"n\"), 10, 224, 224\n        x = relay.var(\"x\", relay.TensorType((n, c, h, w), dtype))\n        y = opfunc(x, pool_size=(1, 1))\n        assert \"pool_size=\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, 10, 224, 224), dtype)\n        # test execution\n        dtype = \"int32\"\n        dshape = (1, 3, 28, 28)\n        for shape_dtype in [\"int32\", \"int64\"]:\n            x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in dshape], dtype=dtype)\n            y = opfunc(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n            func = relay.Function([x], y)\n            data = np.random.randint(low=-128, high=128, size=dshape)\n            ref_res = reffunc(data.reshape(1, 3, 14, 2, 14, 2), axis=(3, 5)).astype(dtype)\n            for target, dev in tvm.testing.enabled_targets():\n                op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    data\n                )\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_pool2d(relay.nn.max_pool2d, \"max\")\n    _test_pool2d(relay.nn.max_pool2d, \"max\", pool_size=2, strides=2, padding=0)\n    _test_pool2d(relay.nn.max_pool2d, \"max\", pool_size=2, strides=2, padding=0, dilation=2)\n    _test_pool2d(relay.nn.avg_pool2d, \"avg\")\n    _test_pool2d(relay.nn.avg_pool2d, \"avg\", pool_size=2, strides=2, padding=0)\n    _test_pool2d(relay.nn.avg_pool2d, \"avg\", pool_size=2, strides=2, padding=0, dilation=2)\n\n    _test_pool2d_int(relay.nn.avg_pool2d, np.mean, \"int32\")\n    _test_pool2d_int(relay.nn.avg_pool2d, np.mean, \"uint16\")\n    _test_global_pool2d(relay.nn.global_max_pool2d, np.max)\n    _test_global_pool2d(relay.nn.global_avg_pool2d, np.mean)\n\n\ndef _test_global_pool1d(opfunc, reffunc):\n    n, c, w = te.size_var(\"n\"), te.size_var(\"c\"), 224\n    x = relay.var(\"x\", relay.TensorType((n, w, c), \"float32\"))\n    y = opfunc(x, layout=\"NWC\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 1, c), \"float32\")\n\n    n, c, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, w), \"float32\"))\n    y = opfunc(x)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, 1), \"float32\")\n    # test execution\n    dtype = \"float32\"\n    dshape = (1, 1024, 7)\n    x = relay.var(\"x\", shape=dshape)\n    y = opfunc(x)\n    func = relay.Function([x], y)\n    data = np.random.uniform(size=dshape).astype(dtype)\n    ref_res = reffunc(data, axis=(2,), keepdims=True)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_pool1d():\n    def _test_pool1d(\n        opfunc, pool_type, pool_size=2, strides=2, dilation=1, padding=0, dtype=\"float32\"\n    ):\n        n, c, w = te.var(\"n\"), 10, 224\n        x = relay.var(\"x\", relay.TensorType((n, c, w), \"float32\"))\n        y = opfunc(x, pool_size=(1,))\n        assert \"pool_size=\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, 10, 224), \"float32\")\n        # test execution\n        dshape = (1, 3, 32)\n        for shape_dtype in [\"int32\", \"int64\"]:\n            x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in dshape], dtype=dtype)\n            pool_type = \"max\" if \"max\" in str(opfunc) else \"avg\"\n            y = opfunc(x, pool_size=pool_size, strides=strides, dilation=dilation, padding=padding)\n            func = relay.Function([x], y)\n            data = np.random.uniform(size=dshape).astype(dtype)\n            ref_res = tvm.topi.testing.poolnd_python(\n                data,\n                [pool_size],\n                [strides],\n                [dilation],\n                [padding],\n                [padding],\n                pool_type,\n                count_include_pad=False,\n                ceil_mode=False,\n            )\n            for target, dev in tvm.testing.enabled_targets():\n                op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    data\n                )\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_pool1d(relay.nn.max_pool1d, \"max\")\n    _test_pool1d(relay.nn.max_pool1d, \"max\", dtype=\"int32\")\n    _test_pool1d(relay.nn.max_pool1d, \"max\", pool_size=2, strides=2, padding=0)\n    _test_pool1d(relay.nn.max_pool1d, \"max\", pool_size=2, strides=2, padding=0, dilation=2)\n    _test_pool1d(relay.nn.avg_pool1d, \"avg\")\n    _test_pool1d(relay.nn.avg_pool1d, \"avg\", dtype=\"int32\")\n    _test_pool1d(relay.nn.avg_pool1d, \"avg\", pool_size=2, strides=2, padding=0)\n    _test_pool1d(relay.nn.avg_pool1d, \"avg\", pool_size=2, strides=2, padding=0, dilation=2)\n    _test_global_pool1d(relay.nn.global_max_pool1d, np.max)\n    _test_global_pool1d(relay.nn.global_avg_pool1d, np.mean)\n\n\n@tvm.testing.uses_gpu\ndef test_pool3d():\n    def _test_pool3d(\n        opfunc,\n        pool_type,\n        pool_size=2,\n        strides=2,\n        dilation=1,\n        padding=[0, 0, 0, 0, 0, 0],\n        dtype=\"float32\",\n    ):\n        n, c, d, h, w = te.size_var(\"n\"), 10, 5, 224, 224\n        x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"float32\"))\n        y = opfunc(x, pool_size=(1, 1, 1))\n        assert \"pool_size=\" in y.astext()\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((n, 10, 5, 224, 224), \"float32\")\n        # test execution\n        dtype = \"float32\"\n        dshape = (1, 3, 32, 32, 32)\n        for shape_dtype in [\"int32\", \"int64\"]:\n            x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in dshape], dtype=dtype)\n            pool_type = \"max\" if \"max\" in str(opfunc) else \"avg\"\n            y = opfunc(\n                x,\n                pool_size=pool_size,\n                strides=strides,\n                padding=padding,\n                dilation=dilation,\n            )\n            func = relay.Function([x], y)\n            data = np.random.uniform(size=dshape).astype(dtype)\n            ref_res = tvm.topi.testing.poolnd_python(\n                data,\n                [pool_size, pool_size, pool_size],\n                [strides, strides, strides],\n                [dilation, dilation, dilation],\n                padding[:3],\n                padding[3:],\n                pool_type,\n                count_include_pad=False,\n                ceil_mode=False,\n            )\n            for target, dev in tvm.testing.enabled_targets():\n                op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    data\n                )\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_pool3d(relay.nn.max_pool3d, \"max\")\n    _test_pool3d(relay.nn.max_pool3d, \"max\", dtype=\"int32\")\n    _test_pool3d(relay.nn.max_pool3d, \"max\", padding=(2, 0, 0, 2, 0, 0))\n    _test_pool3d(relay.nn.max_pool3d, \"max\", padding=(0, 3, 0, 0, 3, 0))\n    _test_pool3d(relay.nn.max_pool3d, \"max\", padding=(0, 0, 4, 0, 0, 4))\n    _test_pool3d(relay.nn.max_pool3d, \"max\", pool_size=2, strides=2)\n    _test_pool3d(relay.nn.max_pool3d, \"max\", pool_size=2, strides=2, dilation=2)\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\")\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", dtype=\"int32\")\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", padding=(2, 0, 0, 2, 0, 0))\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", padding=(0, 3, 0, 0, 3, 0))\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", padding=(0, 0, 4, 0, 0, 4))\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", pool_size=2, strides=2)\n    _test_pool3d(relay.nn.avg_pool3d, \"avg\", pool_size=2, strides=2, dilation=2)\n\n\n@tvm.testing.uses_gpu\ndef test_avg_pool2d_no_count_pad():\n    kh, kw = (4, 4)\n    sh, sw = (2, 2)\n    ph, pw = (2, 2)\n    n = 1\n    (ic, ih, iw) = (3, 28, 28)\n    (oc, oh, ow) = (3, 15, 15)\n    dshape = (n, ic, ih, iw)\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.avg_pool2d(\n        x, pool_size=(kh, kw), strides=(sw, sw), padding=(ph, pw), count_include_pad=False\n    )\n    func = relay.Function([x], y)\n    dtype = \"float32\"\n    a_np = np.random.uniform(low=0.001, size=(n, ic, ih, iw)).astype(dtype)\n    pad_np = np.zeros(shape=(n, ic, ih + 2 * ph, iw + 2 * pw)).astype(dtype)\n    no_zero = (range(n), range(ic), (range(ph, ih + ph)), (range(pw, iw + pw)))\n    pad_np[np.ix_(*no_zero)] = a_np\n    b_np = np.zeros(shape=(n, oc, oh, ow)).astype(dtype)\n    for i in range(oh):\n        for j in range(ow):\n            pad_count = np.sum(\n                pad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw] > 0, axis=(2, 3)\n            )\n            b_np[:, :, i, j] = np.sum(\n                pad_np[:, :, i * sh : i * sh + kh, j * sw : j * sw + kw], axis=(2, 3)\n            ) / np.maximum(pad_count, 1)\n    ref_res = np.maximum(b_np, 0.0)\n    data = a_np\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_flatten_infer_type(executor_kind):\n    d1, d2, d3, d4 = te.size_var(\"d1\"), te.size_var(\"d2\"), te.size_var(\"d3\"), te.size_var(\"d4\")\n    x = relay.var(\"x\", relay.TensorType((d1, d2, d3, d4), \"float32\"))\n    y = relay.nn.batch_flatten(x)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((d1, ((d2 * d3) * d4)), \"float32\")\n\n    x = relay.var(\"x\", relay.TensorType((3, 2, 4, 3), \"float32\"))\n    y = relay.nn.batch_flatten(x)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((3, 24), \"float32\")\n\n    x = relay.var(\"x\", relay.TensorType((d1, 2, d3, 3), \"float32\"))\n    y = relay.nn.batch_flatten(x)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((d1, ((2 * d3) * 3)), \"float32\")\n\n    shape = (1, 5, 10, 10)\n    o_shape = (1, 500)\n    dtype = \"float32\"\n    x = relay.var(\"x\", relay.TensorType(shape, dtype))\n    z = relay.nn.batch_flatten(x)\n    yy = run_infer_type(z)\n    assert yy.checked_type == relay.TensorType(o_shape, dtype)\n    func = relay.Function([x], z)\n    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)\n    ref_res = x_data.flatten().reshape(o_shape)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_pad_infer_type():\n    # entirely concrete cases\n    n, c, h, w = 1, 2, 3, 4\n    t = relay.var(\"t\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.pad(t, ((1, 1), (2, 2), (3, 3), (4, 4)))\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((3, 6, 9, 12), \"float32\")\n\n    n, c, h, w = 4, 6, 3, 5\n    t = relay.var(\"t\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.pad(t, ((-1, -1), (2, -2), (0, -3), (4, 4)), pad_mode=\"reflect\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((2, 6, 0, 13), \"float32\")\n\n    # some symbolic values\n    n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n    t = relay.var(\"t\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.pad(t, ((1, 1), (2, 2), (3, 3), (4, 4)))\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n + 2, 6, 9, w + 8), \"float32\")\n\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    t = relay.var(\"t\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.pad(t, ((-1, -1), (-2, -2), (1, -3), (4, 4)))\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n + (-2), c + (-4), h + (-2), w + 8), \"float32\")\n\n    # dealing with dynamic vals\n    n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n    t = relay.var(\"t\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.pad(\n        t, ((1, 1), (2, 2), (3, 3), (4, 4)), pad_value=relay.var(\"pad_value\", \"float32\")\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n + 2, 6, 9, w + 8), \"float32\")\n\n\ndef _get_numpy_pad(dshape, data, pad, pad_value=0):\n    mod_pad = []\n    for axis, (pad_x, pad_y) in enumerate(pad):\n        indices = range(dshape[axis])\n        if pad_x < 0:\n            indices = indices[abs(pad_x) :]\n            pad_x = 0\n        if pad_y < 0:\n            indices = indices[:pad_y]\n            pad_y = 0\n        data = np.take(data, indices, axis)\n        mod_pad.append((pad_x, pad_y))\n    return np.pad(data, tuple(mod_pad), \"constant\", constant_values=pad_value)\n\n\n@tvm.testing.uses_gpu\ndef test_pad_run():\n    def _test_run(dtype):\n        dshape_list = [(4, 10, 7, 7), (4, 6, 3, 5)]\n        pad_list = [((1, 1), (2, 2), (3, 3), (4, 4)), ((-1, -1), (2, -2), (0, -2), (4, 4))]\n\n        for dshape, pad in zip(dshape_list, pad_list):\n            x = relay.var(\"x\", shape=dshape)\n            y = relay.nn.pad(x, pad)\n            func = relay.Function([x], y)\n            data = np.random.uniform(size=dshape).astype(dtype)\n            ref_res = _get_numpy_pad(dshape, data, pad)\n            for target, dev in tvm.testing.enabled_targets():\n                op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    data\n                )\n                tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_run(\"float32\")\n    _test_run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_pad_run_dynamic_pad_value():\n    def _test_run(dtype):\n        dshape = (4, 6, 3, 5)\n        pad = ((-1, -1), (2, -2), (0, -2), (4, 4))\n\n        data = relay.var(\"data\", shape=dshape, dtype=dtype)\n        pad_value = relay.var(\"pad_value\", dtype)\n        pad_data = relay.nn.pad(data, pad, pad_value=pad_value)\n        f = relay.Function([data, pad_value], pad_data)\n\n        data_arr = np.random.uniform(-10, 10, size=dshape).astype(dtype)\n        pad_value_arr = 2.0\n        ref_res = _get_numpy_pad(dshape, data_arr, pad, pad_value=pad_value_arr)\n\n        for target, dev in tvm.testing.enabled_targets():\n            result = relay.create_executor(kind=\"graph\", device=dev, target=target).evaluate(f)(\n                data_arr, pad_value_arr\n            )\n            tvm.testing.assert_allclose(result.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_run(\"float32\")\n    _test_run(\"int32\")\n\n\n@tvm.testing.uses_gpu\n@pytest.mark.parametrize(\"dtype\", [\"float32\", \"float16\"])\ndef test_lrn(executor_kind, dtype):\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", shape=(n, c, h, w), dtype=dtype)\n    y = relay.nn.lrn(x, size=10, axis=2, bias=0.5, alpha=0.00001, beta=0.75)\n    \"alpha=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, h, w), dtype)\n\n    shape = (1, 5, 10, 10)\n    x = relay.var(\"x\", relay.TensorType(shape, dtype))\n    size = 5\n    axis = 1\n    bias = 0.5\n    alpha = 0.00001\n    beta = 0.75\n    z = relay.nn.lrn(x, size=size, axis=axis, bias=bias, alpha=alpha, beta=beta)\n    yy = run_infer_type(z)\n    assert yy.checked_type == relay.TensorType(shape, dtype)\n    func = relay.Function([x], z)\n    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)\n    ref_res = tvm.topi.testing.lrn_python(x_data, size, axis, bias, alpha, beta)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_l2_normalize(executor_kind):\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", shape=(n, c, h, w))\n    y = relay.nn.l2_normalize(x, eps=0.001, axis=[1])\n    \"axis=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, h, w))\n\n    shape = (1, 5, 10, 10)\n    dtype = \"float32\"\n    x = relay.var(\"x\", relay.TensorType(shape, dtype))\n    eps = 0.001\n    axis = 1\n    z = relay.nn.l2_normalize(x, eps=0.001, axis=[axis])\n    yy = run_infer_type(z)\n    assert yy.checked_type == relay.TensorType(shape, dtype)\n    func = relay.Function([x], z)\n    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)\n    ref_res = tvm.topi.testing.l2_normalize_python(x_data, eps, axis)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef batch_flatten(data):\n    shape = data.shape\n    target_dim = 1\n    for i in range(len(shape) - 1):\n        target_dim = target_dim * shape[i + 1]\n    return np.reshape(data, (shape[0], target_dim))\n\n\n@tvm.testing.uses_gpu\ndef test_batch_flatten():\n    t1 = relay.TensorType((5, 10, 5))\n    x = relay.Var(\"x\", t1)\n    func = relay.Function([x], relay.nn.batch_flatten(x))\n\n    data = np.random.rand(5, 10, 5).astype(t1.dtype)\n    ref_res = batch_flatten(data)\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\ndef _test_upsampling(layout, method, align_corners=False):\n    n, c, h, w = te.size_var(\"n\"), 16, 32, 32\n    scale_h = 2.0\n    scale_w = 2.0\n    dtype = \"float32\"\n\n    def get_shape():\n        if layout == \"NCHW\":\n            return (c, h, w), (c, int(round(h * scale_h)), int(round(w * scale_w)))\n        else:\n            return (h, w, c), (int(round(h * scale_h)), int(round(w * scale_w)), c)\n\n    ishape, oshape = get_shape()\n    x = relay.var(\"x\", relay.TensorType((n,) + ishape, dtype))\n    y = relay.nn.upsampling(\n        x,\n        scale_h=scale_h,\n        scale_w=scale_w,\n        layout=layout,\n        method=method,\n        align_corners=align_corners,\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n,) + oshape, dtype)\n    dshape = (1,) + ishape\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.upsampling(\n        x,\n        scale_h=scale_h,\n        scale_w=scale_w,\n        layout=layout,\n        method=method,\n        align_corners=align_corners,\n    )\n    func = relay.Function([x], y)\n\n    data = np.random.uniform(size=dshape).astype(dtype)\n    ref = tvm.topi.testing.resize2d_python(\n        data,\n        (scale_h, scale_w),\n        layout,\n        method[2:] if method[0:2] == \"bi\" else method,\n        \"align_corners\" if align_corners else \"asymmetric\",\n    )\n    for target, dev in tvm.testing.enabled_targets():\n        out = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        tvm.testing.assert_allclose(out.numpy(), ref, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling():\n    _test_upsampling(\"NCHW\", \"nearest_neighbor\")\n    _test_upsampling(\"NCHW\", \"bilinear\", True)\n    _test_upsampling(\"NHWC\", \"nearest_neighbor\")\n    _test_upsampling(\"NHWC\", \"bilinear\", True)\n\n\ndef _test_upsampling3d(layout, method, coordinate_transformation_mode=\"half_pixel\"):\n    n, c, d, h, w = te.size_var(\"n\"), 8, 16, 16, 16\n    scale_d = 2.0\n    scale_h = 2.0\n    scale_w = 2.0\n    dtype = \"float32\"\n\n    def get_shape():\n        if layout == \"NCDHW\":\n            return (c, d, h, w), (\n                c,\n                int(round(d * scale_d)),\n                int(round(h * scale_h)),\n                int(round(w * scale_w)),\n            )\n        else:\n            return (d, h, w, c), (\n                int(round(d * scale_d)),\n                int(round(h * scale_h)),\n                int(round(w * scale_w)),\n                c,\n            )\n\n    ishape, oshape = get_shape()\n    x = relay.var(\"x\", relay.TensorType((n,) + ishape, dtype))\n    y = relay.nn.upsampling3d(\n        x,\n        scale_d=scale_d,\n        scale_h=scale_h,\n        scale_w=scale_w,\n        layout=layout,\n        method=method,\n        coordinate_transformation_mode=coordinate_transformation_mode,\n    )\n\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n,) + oshape, dtype)\n    dshape = (1,) + ishape\n    x = relay.var(\"x\", shape=dshape)\n    y = relay.nn.upsampling3d(\n        x,\n        scale_d=scale_d,\n        scale_h=scale_h,\n        scale_w=scale_w,\n        layout=layout,\n        method=method,\n        coordinate_transformation_mode=coordinate_transformation_mode,\n    )\n    func = relay.Function([x], y)\n\n    data = np.random.uniform(size=dshape).astype(dtype)\n    ref = tvm.topi.testing.resize3d_python(\n        data,\n        (scale_d, scale_h, scale_w),\n        layout,\n        method[3:] if method[0:3] == \"tri\" else method,\n        coordinate_transformation_mode,\n    )\n    for target, dev in tvm.testing.enabled_targets():\n        out = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(data)\n        tvm.testing.assert_allclose(out.numpy(), ref, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling3d():\n    _test_upsampling3d(\"NCDHW\", \"nearest_neighbor\", \"asymmetric\")\n    _test_upsampling3d(\"NCDHW\", \"trilinear\", \"align_corners\")\n    _test_upsampling3d(\"NDHWC\", \"nearest_neighbor\", \"asymmetric\")\n    _test_upsampling3d(\"NDHWC\", \"trilinear\", \"align_corners\")\n\n\n@tvm.testing.requires_x86\n@pytest.mark.skipif(tvm.target.codegen.llvm_version_major() < 8, reason=\"Requires LLVM 8\")\nclass TestConv2DInt8Intrinsics:\n    supported_targets = [\n        \"llvm -mcpu=nehalem\",\n        \"llvm -mcpu=core-avx2\",\n        \"llvm -mcpu=skylake-avx512\",\n        \"llvm -mcpu=cascadelake\",\n    ]\n\n    unsupported_targets = [\n        \"llvm -mcpu=x86-64\",\n    ]\n\n    data_layout, kernel_layout = tvm.testing.parameters(\n        (\"NCHW\", \"OIHW\"),\n        # TODO(@anijain2305, @icemelon9): disable conv2d_int8 for NHWC data layout.\n        #   Re-enable this after adding conv2d_NCHWc_int8 support for NHWC.\n        # (\"NHWC\", \"HWIO\"),\n    )\n\n    input_channels, output_channels = tvm.testing.parameters(\n        # Sweep the input channels to check int8 robustness\n        # Input channels should be a multiple of 4 internally.\n        (1, 16),\n        (4, 16),\n        (6, 16),\n        # Sweep the output channels to check int8 robustness\n        # Output channels should be a multiple of 16 internally.\n        (8, 4),\n        (8, 16),\n        (8, 20),\n        # Check that both non-divisible oc and ic work\n        (17, 29),\n    )\n\n    @tvm.testing.fixture\n    def fast_int8_intrinsic(self, target):\n        if \"nehalem\" in target or \"core-avx2\" in target or \"skylake-avx512\" in target:\n            return \"pmaddubs\"\n        elif \"cascadelake\" in target:\n            return \"vpdpbusd\"\n        else:\n            assert False, \"Target should be Skylake or Cascadelake\"\n\n    @tvm.testing.fixture\n    def assembly(\n        self,\n        target,\n        dtypes,\n        input_channels,\n        output_channels,\n        data_layout,\n        kernel_layout,\n    ):\n        input_dtype, weight_dtype, output_dtype = dtypes\n\n        image_size = (64, 64)\n        kernel_size = (3, 3)\n        batch_size = 1\n\n        h, w = image_size\n\n        if data_layout == \"NCHW\":\n            data_shape = (batch_size, input_channels, *image_size)\n        elif data_layout == \"NHWC\":\n            data_shape = (batch_size, *image_size, input_channels)\n        else:\n            raise ValueError(f\"Unsupported data layout: {data_layout}\")\n        x = relay.var(\"x\", relay.TensorType(data_shape, input_dtype))\n\n        if kernel_layout == \"OIHW\":\n            kernel_shape = (output_channels, input_channels, *kernel_size)\n        elif kernel_layout == \"HWIO\":\n            kernel_shape = (*kernel_size, input_channels, output_channels)\n        else:\n            raise ValueError(\"Not supported\")\n        weight = relay.var(\"weight\", relay.TensorType(kernel_shape, weight_dtype))\n\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            kernel_size=kernel_size,\n            channels=output_channels,\n            padding=(0, 0, 0, 1),\n            dilation=(1, 1),\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n            out_dtype=output_dtype,\n        )\n\n        func = relay.Function([x, weight], y)\n\n        wdata = np.random.rand(*kernel_shape) * 10\n        parameters = {\"weight\": tvm.nd.array(wdata.astype(weight_dtype))}\n\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(func, target, params=parameters)\n\n        return lib.get_source(\"asm\")\n\n    # Ensure that code uses the fast int8 instructions when available.\n    @tvm.testing.parametrize_targets(*supported_targets)\n    @pytest.mark.parametrize(\n        \"dtypes\",\n        [\n            # compile conv2d for x86 (skylake, cascadelake) and test\n            # assembly contains *pmadd* instructions\n            (\"uint8\", \"int8\", \"int32\"),\n            # Check that int8 x int8 goes through legalization so that\n            # fast instructions can be picked up.\n            (\"int8\", \"int8\", \"int32\"),\n        ],\n    )\n    def test_uses_intrinsic(\n        self,\n        fast_int8_intrinsic,\n        assembly,\n    ):\n        assert fast_int8_intrinsic in assembly\n\n    # For datatypes that don't have HW support, ensure that code is\n    # generated without the fast int8 intrinsic.\n    @tvm.testing.parametrize_targets(*supported_targets)\n    @pytest.mark.parametrize(\"dtypes\", [(\"uint8\", \"uint8\", \"int32\")])\n    def test_no_intrinsic(\n        self,\n        fast_int8_intrinsic,\n        assembly,\n    ):\n        assert fast_int8_intrinsic not in assembly\n\n    # Check that a vectorized instruction is generated for older Intel\n    # generations, because we default to NCHWc layout.\n    @tvm.testing.parametrize_targets(*unsupported_targets)\n    @pytest.mark.parametrize(\"dtypes\", [(\"uint8\", \"int8\", \"int32\")])\n    def test_uses_vectorized_instruction(self, assembly):\n        assert \"pmulhw\" in assembly and \"paddd\" in assembly\n\n\n@tvm.testing.uses_gpu\ndef test_depthwise_conv2d_int8():\n    input_dtype = \"uint8\"\n    weight_dtype = \"int8\"\n    output_dtype = \"int32\"\n\n    data_shape = (1, 64, 56, 56)\n    x = relay.var(\"x\", relay.TensorType(data_shape, input_dtype))\n\n    kernel_shape = (64, 1, 3, 3)\n    weight = relay.var(\"weight\", relay.TensorType(kernel_shape, weight_dtype))\n\n    y = relay.nn.conv2d(\n        x,\n        weight,\n        kernel_size=(3, 3),\n        groups=64,\n        padding=(1, 1),\n        dilation=(1, 1),\n        out_dtype=output_dtype,\n    )\n    func = relay.Function([x, weight], y)\n    wdata = np.random.rand(*kernel_shape) * 10\n    parameters = {\"weight\": tvm.nd.array(wdata.astype(weight_dtype))}\n\n    targets = [\"llvm -mcpu=skylake-avx512\", \"llvm -mcpu=cascadelake\"]\n    llvm_version = tvm.target.codegen.llvm_version_major()\n    for target in targets:\n        if llvm_version >= 8:\n            with tvm.transform.PassContext(opt_level=3):\n                graph, lib, params = relay.build(func, target, params=parameters)\n\n\n@tvm.testing.uses_gpu\ndef test_bitserial_conv2d_infer_type():\n    # Basic shape test with ambiguous batch.\n    n, c, h, w = te.size_var(\"n\"), 32, 224, 224\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, h, w), \"int16\"))\n    w = relay.var(\"w\", relay.ty.TensorType((32, 32, 3, 3), \"int16\"))\n    y = relay.nn.bitserial_conv2d(x, w, kernel_size=(3, 3), padding=(0, 0), channels=32)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 32, 222, 222), \"int16\")\n\n\n@tvm.testing.uses_gpu\ndef test_bitpack_infer_type():\n    # Test axis packing shape inference.\n    o, i, h, w = 32, 32, 128, 128\n    x = relay.var(\"x\", relay.ty.TensorType((o, i, h, w), \"int16\"))\n    y = relay.nn.bitpack(x, bit_axis=4, pack_axis=1, pack_type=\"uint16\", bits=1)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((32, 2, 128, 128, 1), \"uint16\")\n\n\n# TODO(@jwfromm): Need to add bitserial_conv2d & bitpack run test cases\n\n\n@tvm.testing.uses_gpu\ndef test_correlation():\n    def _test_correlation(\n        data_shape,\n        kernel_size,\n        max_displacement,\n        stride1,\n        stride2,\n        padding,\n        is_multiply,\n        dtype=\"float32\",\n    ):\n        data1 = relay.var(\"data1\", relay.ty.TensorType(data_shape, dtype))\n        data2 = relay.var(\"data2\", relay.ty.TensorType(data_shape, dtype))\n        y = relay.nn.correlation(\n            data1,\n            data2,\n            kernel_size,\n            max_displacement,\n            stride1,\n            stride2,\n            padding,\n            is_multiply,\n            \"NCHW\",\n        )\n        yy = run_infer_type(y)\n        padded_height = data_shape[2] + 2 * padding\n        padded_width = data_shape[3] + 2 * padding\n        border_size = (kernel_size - 1) // 2 + max_displacement\n        displacement_radius = max_displacement // stride2\n        out_channel = ((2 * displacement_radius) + 1) ** 2\n        out_height = (padded_height - 2 * border_size + stride1 - 1) // stride1\n        out_width = (padded_width - 2 * border_size + stride1 - 1) // stride1\n        assert yy.checked_type == relay.TensorType(\n            (data_shape[0], out_channel, out_height, out_width), dtype\n        )\n        func = relay.Function([data1, data2], y)\n        data1_np = np.random.uniform(size=data_shape).astype(dtype)\n        data2_np = np.random.uniform(size=data_shape).astype(dtype)\n        ref_res = tvm.topi.testing.correlation_nchw_python(\n            data1_np,\n            data2_np,\n            kernel_size,\n            max_displacement,\n            stride1,\n            stride2,\n            padding,\n            is_multiply,\n        )\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                data1_np, data2_np\n            )\n            tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    _test_correlation(\n        (1, 3, 10, 10),\n        kernel_size=1,\n        max_displacement=4,\n        stride1=1,\n        stride2=1,\n        padding=4,\n        is_multiply=True,\n    )\n    _test_correlation(\n        (1, 3, 10, 10),\n        kernel_size=1,\n        max_displacement=5,\n        stride1=1,\n        stride2=1,\n        padding=5,\n        is_multiply=True,\n    )\n    _test_correlation(\n        (5, 1, 4, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=2,\n        stride2=1,\n        padding=2,\n        is_multiply=True,\n    )\n    _test_correlation(\n        (5, 1, 6, 4),\n        kernel_size=3,\n        max_displacement=1,\n        stride1=2,\n        stride2=2,\n        padding=2,\n        is_multiply=False,\n    )\n    _test_correlation(\n        (5, 1, 11, 11),\n        kernel_size=5,\n        max_displacement=1,\n        stride1=1,\n        stride2=1,\n        padding=2,\n        is_multiply=False,\n    )\n\n\n@pytest.mark.skip(\"Requires GFX10 AMDGPU\")\ndef test_conv2d_rocm_sdot4():\n    d_shape = (1, 64, 56, 56)\n    w_shape = (64, 64, 3, 3)\n    padding = (1, 1)\n    strides = (1, 1)\n    data_dtype = \"int8\"\n    weight_dtype = \"int8\"\n    out_dtype = \"int32\"\n\n    data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n    weight = relay.var(\"weight\", shape=w_shape, dtype=weight_dtype)\n    out_channel = w_shape[0]\n    conv2d = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=w_shape[2:],\n        channels=out_channel,\n        padding=padding,\n        strides=strides,\n        out_dtype=out_dtype,\n    )\n\n    mod = tvm.IRModule.from_expr(conv2d)\n\n    data_np = np.random.uniform(1, 10, d_shape).astype(\"int8\")\n    weight_np = np.random.uniform(1, 10, size=w_shape).astype(\"int8\")\n\n    target = \"rocm -mattr=+dotprod\"\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, target=target, params={\"weight\": weight_np})\n\n    asm = lib.lib.imported_modules[0].get_source(\"asm\")\n    assert \"v_dot4_i32_i8\" in asm\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n\n    out = runtime.get_output(0).numpy()\n\n    ref = tvm.topi.testing.conv2d_nchw_python(\n        data_np.astype(\"int32\"), weight_np.astype(\"int32\"), strides, padding\n    )\n\n    np.testing.assert_equal(out, ref)\n\n\ndef np_float2tvm_bf16(arr):\n    \"\"\"Convert a numpy array of float to a TVM array\n    of bf16\"\"\"\n    orig = arr.view(\"<u4\")\n    bias = np.bitwise_and(np.right_shift(orig, 16), 1) + 0x7FFF\n    nparr = np.right_shift(orig + bias, 16).astype(\"uint16\")\n    return tvm.nd.empty(nparr.shape, \"bfloat16\").copyfrom(nparr)\n\n\ndef np_bf162np_float(arr):\n    \"\"\"Convert a numpy array of bf16 (uint16) to a numpy array\n    of float\"\"\"\n    u32 = np.left_shift(arr.astype(\"uint32\"), 16)\n    return u32.view(\"<f4\")\n\n\n@tvm.testing.requires_x86\ndef test_conv2d_nchw_dnnl():\n    if not tvm.get_global_func(\"tvm.contrib.dnnl.conv2d\", allow_missing=True):\n        print(\n            \"skip because extern dnnl function is not available, \\\n                built with dnnl=ON\"\n        )\n        return\n    d_shape = (1, 64, 56, 56)\n    w_shape = (64, 64, 3, 3)\n    padding = (1, 1)\n    strides = (1, 1)\n\n    def get_subgraph(dtype):\n        data = relay.var(\"data\", shape=d_shape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w_shape, dtype=dtype)\n        out_channel = w_shape[0]\n        conv2d = relay.nn.conv2d(\n            data=data,\n            weight=weight,\n            kernel_size=w_shape[2:],\n            channels=out_channel,\n            padding=padding,\n            strides=strides,\n            out_dtype=dtype,\n        )\n        return conv2d\n\n    for t in [\"float32\", \"bfloat16\"]:\n        mod = tvm.IRModule.from_expr(get_subgraph(t))\n\n        data_np = np.random.uniform(1, 10, d_shape).astype(\"float32\")\n        weight_np = np.random.uniform(1, 10, size=w_shape).astype(\"float32\")\n        ref = tvm.topi.testing.conv2d_nchw_python(data_np, weight_np, strides, padding)\n\n        if t == \"bfloat16\":\n            data_np = np_float2tvm_bf16(data_np)\n            weight_np = np_float2tvm_bf16(weight_np)\n\n        target = \"llvm -mcpu=skylake-avx512 -libs=dnnl\"\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target, params={\"weight\": weight_np})\n\n        dev = tvm.device(target, 0)\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n        runtime.set_input(\"data\", data_np)\n        runtime.run()\n\n        out = runtime.get_output(0).numpy()\n\n        if t == \"bfloat16\":\n            out = np_bf162np_float(out)\n            np.testing.assert_allclose(out, ref, rtol=1e-2)\n        else:\n            np.testing.assert_allclose(out, ref, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.requires_x86\ndef test_conv2d_nhwc_dnnl():\n    if not tvm.get_global_func(\"tvm.contrib.dnnl.conv2d\", allow_missing=True):\n        print(\n            \"skip because extern dnnl function is not available, \\\n                built with dnnl=ON\"\n        )\n        return\n    d_shape = (1, 56, 56, 64)\n    w_shape = (3, 3, 64, 64)\n    padding = (1, 1)\n    strides = (1, 1)\n\n    def get_subgraph(dtype):\n        data = relay.var(\"data\", shape=d_shape, dtype=dtype)\n        weight = relay.var(\"weight\", shape=w_shape, dtype=dtype)\n        out_channel = w_shape[3]\n        conv2d = relay.nn.conv2d(\n            data=data,\n            weight=weight,\n            kernel_size=w_shape[:2],\n            channels=out_channel,\n            padding=padding,\n            strides=strides,\n            out_dtype=dtype,\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        return conv2d\n\n    for t in [\"float32\", \"bfloat16\"]:\n        mod = tvm.IRModule.from_expr(get_subgraph(t))\n\n        data_np = np.random.uniform(1, 10, d_shape).astype(\"float32\")\n        weight_np = np.random.uniform(1, 10, size=w_shape).astype(\"float32\")\n        ref = tvm.topi.testing.conv2d_nhwc_python(data_np, weight_np, strides, padding)\n\n        if t == \"bfloat16\":\n            data_np = np_float2tvm_bf16(data_np)\n            weight_np = np_float2tvm_bf16(weight_np)\n\n        target = \"llvm -mcpu=skylake-avx512 -libs=dnnl\"\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target=target, params={\"weight\": weight_np})\n\n        dev = tvm.device(target, 0)\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n        runtime.set_input(\"data\", data_np)\n        runtime.run()\n\n        out = runtime.get_output(0).numpy()\n\n        if t == \"bfloat16\":\n            out = np_bf162np_float(out)\n            np.testing.assert_allclose(out, ref, rtol=1e-2)\n        else:\n            np.testing.assert_allclose(out, ref, rtol=1e-5, atol=1e-5)\n\n\ndef _test_conv2d_int8_alter_dtype(data_dtype, target, dot_product_instr):\n    def get_conv2d_nchw(\n        d_shape,\n        w_shape,\n        data_dtype,\n    ):\n        out_dtype = \"int32\"\n        strides = (1, 1)\n        padding = (1, 1)\n        data = relay.var(\"data\", shape=d_shape, dtype=data_dtype)\n        weight = relay.var(\"weight\", shape=w_shape, dtype=\"int8\")\n        out_channel = w_shape[0]\n        return relay.nn.conv2d(\n            data=data,\n            weight=weight,\n            kernel_size=w_shape[2:],\n            channels=out_channel,\n            padding=padding,\n            strides=strides,\n            out_dtype=out_dtype,\n        )\n\n    I, O, H, W = 64, 64, 56, 56\n    kH = kW = 3\n\n    data_shape = (1, I, H, W)\n    weight_shape = (O, I, kH, kW)\n    bias_shape = (1, weight_shape[0], 1, 1)\n\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"int32\")\n    bias_np = np.random.randint(low=-127, high=128, size=bias_shape).astype(\"int32\")\n    weight_np = np.random.uniform(-128, 127, size=weight_shape).astype(\"int8\")\n\n    conv2d = get_conv2d_nchw(data_shape, weight_shape, data_dtype)\n    bias_add = relay.add(conv2d, bias)\n    mod = tvm.IRModule.from_expr(bias_add)\n\n    if data_dtype == \"uint8\":\n        data_np = np.random.uniform(0, 255, size=data_shape).astype(\"uint8\")\n    else:\n        data_np = np.random.uniform(-128, 127, size=data_shape).astype(\"int8\")\n\n    params = {\"weight\": weight_np, \"bias\": bias_np}\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight_np, bias_np])\n        .numpy()\n    )\n\n    dev = tvm.cpu(0)\n\n    with tvm.transform.PassContext(\n        opt_level=3,\n    ):\n        lib = relay.build(mod, target=target, params=params)\n\n    assert dot_product_instr in lib.lib.get_source(\"asm\")\n\n    rt_mod = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    rt_mod.set_input(\"data\", data_np)\n\n    rt_mod.run()\n\n    out = rt_mod.get_output(0).numpy()\n\n    np.testing.assert_equal(out, ref)\n\n\n@tvm.testing.requires_arm_dot\ndef test_conv2d_int8_alter_dtype_arm():\n    _test_conv2d_int8_alter_dtype(\n        \"uint8\", \"llvm -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\", \"sdot\"\n    )\n\n\n@tvm.testing.requires_cascadelake\ndef test_conv2d_int8_alter_dtype_vnni():\n    _test_conv2d_int8_alter_dtype(\"int8\", \"llvm -mcpu=cascadelake\", \"vpdpbusd\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level3.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level3 operator test cases.\n\"\"\"\nimport sys\nfrom typing import Callable, Optional\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay, te\nfrom tvm.error import TVMError\nfrom tvm.relay import create_executor, transform\nfrom tvm.relay.testing import check_grad, run_infer_type\n\nfrom utils import ref_funcs\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\nclass TestZerosOnes:\n    config = {\"zeros\": (relay.zeros, np.zeros), \"ones\": (relay.ones, np.ones)}\n    op, ref = tvm.testing.parameters(*config.values(), ids=config.keys())\n\n    def test_zeros_ones(self, op, ref):\n        y = op(shape=(124, 50), dtype=\"float64\")\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType((124, 50), \"float64\")\n        intrp_res = create_executor().evaluate(y).numpy()\n        np.testing.assert_allclose(intrp_res, ref((124, 50), \"float64\"))\n\n\nclass TestUnaryIdentity:\n    config = {\n        \"zeros_like\": (relay.zeros_like, np.zeros_like),\n        \"ones_like\": (relay.ones_like, np.ones_like),\n        \"ceil\": (relay.ceil, np.ceil),\n        \"floor\": (relay.floor, np.floor),\n        \"trunc\": (relay.trunc, np.trunc),\n        \"round\": (relay.round, np.round),\n        \"abs\": (relay.abs, np.abs),\n        \"copy\": (relay.copy, None),  # np.copy\n        \"negative\": (relay.negative, np.negative),\n        \"sign\": (relay.sign, np.sign),\n    }\n    op, ref = tvm.testing.parameters(*config.values(), ids=config.keys())\n\n    def test_unary_identity(self, op, ref):\n        shape = (8, 9, 4)\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = op(x)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType(shape, \"float32\")\n\n        if ref is not None:\n            data = np.random.rand(*shape).astype(\"float32\")\n            op_res = create_executor().evaluate(y, {x: relay.const(data)})\n            ref_res = ref(data)\n            np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\ndef test_cast():\n    x = relay.var(\"x\", relay.TensorType((8, 9, 4), \"float32\"))\n    y = x.astype(\"int32\")\n    yy = run_infer_type(y)\n    assert \"dtype=\" in yy.astext()\n    assert yy.checked_type == relay.TensorType((8, 9, 4), \"int32\")\n\n    x = relay.var(\"x\", relay.TensorType((8, 9, 4), \"float32\"))\n    y = relay.cast(x, \"int32\")\n    yy = run_infer_type(y)\n    assert \"dtype=\" in yy.astext()\n    assert yy.checked_type == relay.TensorType((8, 9, 4), \"int32\")\n\n\ndef test_sliding_window():\n    # Slide a window of shape (3, 4, 5) over the x tensor, beginning with\n    # dimension 1, which slides the window over the two subtensors of shape (3,\n    # 32, 32).\n    x = relay.var(\"x\", relay.TensorType((2, 3, 32, 32), \"float32\"))\n    y = relay.sliding_window(x, 1, [3, 4, 5], [1, 2, 3])\n\n    # The resulting shape still has batch size 2. Each dimension in (1, 15, 10)\n    # represents the locations where we were able to form a window; that is, we\n    # were able to place the window in one place along the dimension of length\n    # 3, 15 places along the dimension of length 32 (when striding by 2), and 10\n    # places along the second dimension of length 32 (when striding by 3). The\n    # remaining dimensions (3, 4, 5) represent the formed windows.\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((2, 1, 15, 10, 3, 4, 5), \"float32\")\n\n    data = np.random.rand(2, 3, 32, 32).astype(\"float32\")\n    intrp = create_executor()\n    result = intrp.evaluate(y, {x: relay.const(data)})\n    result_np = result.numpy()\n    assert result_np.shape == (2, 1, 15, 10, 3, 4, 5)\n    assert np.array_equal(result_np[0, 0, 0, 0, :, :, :], data[0, :, 0:4, 0:5])\n    assert np.array_equal(result_np[1, 0, 7, 3, :, :, :], data[1, :, 14:18, 9:14])\n    assert np.array_equal(result_np[1, 0, 14, 9, :, :, :], data[1, :, 28:32, 27:32])\n\n\ndef test_clip():\n    a = relay.var(\"a\", relay.TensorType((10, 4), \"float32\"))\n    y = relay.clip(a, 1.0, 4.0)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((10, 4), \"float32\")\n\n    data = np.random.rand(10, 4).astype(\"float32\")\n    op_res = create_executor().evaluate(y, {a: relay.const(data)})\n    ref_res = np.clip(data, 1.0, 4.0)\n    np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\ndef test_fixed_point_multiply():\n    # Test 23 * 1/16\n    # [m,s] = [0.5, -3] = frexp(1/16)\n    # M = 0.5*2^31 = 1073741824\n    # so M = 1073741824 and s = -3\n\n    a = relay.var(\"a\", relay.TensorType((10, 4), \"int32\"))\n    y = relay.fixed_point_multiply(a, 1073741824, -3)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((10, 4), \"int32\")\n\n    data = 23 * np.ones((10, 4)).astype(\"int32\")\n    op_res = create_executor().evaluate(y, {a: relay.const(data)})\n    ref_res = np.ones((10, 4)).astype(\"int32\")\n    np.testing.assert_allclose(op_res.numpy(), ref_res, atol=1)\n\n\ndef test_reinterpret():\n    a = relay.var(\"a\", relay.TensorType((1000, 4), \"float32\"))\n    y = relay.reinterpret(a, \"int32\")\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1000, 4), \"int32\")\n\n    data = np.random.randn(1000, 4).astype(\"float32\") * 1000\n    op_res = create_executor().evaluate(y, {a: relay.const(data)})\n    ref_res = data.view(\"int32\")\n    np.testing.assert_equal(op_res.numpy(), ref_res)\n\n\ndef test_approximate_transcendental():\n    def C(x):\n        return relay.expr.const(x, \"float32\")\n\n    def approx_exp(x):\n        # An approximation derived from Opus,\n        # https://github.com/xiph/opus/blob/c1c247/celt/mathops.h#L147-L165\n        x = relay.minimum(relay.maximum(x, C(-88.0)), C(88.0))\n        x = C(127.0) + x * C(1.44269504)\n        xf = relay.floor(x)\n        i = relay.cast(xf, \"int32\")\n        x = x - xf\n        Y = C(0.99992522) + x * (C(0.69583354) + x * (C(0.22606716) + x * C(0.078024523)))\n        exponent = relay.left_shift(i, relay.expr.const(23, \"int32\"))\n        exponent = relay.reinterpret(exponent, \"float32\")\n        return exponent * Y\n\n    def approximate_sigmoid(x):\n        y = approx_exp(x)\n        return y / (y + C(1.0))\n\n    def approximate_tanh(x):\n        x = x * C(2.0)\n        y = approx_exp(x)\n        return (y - C(1.0)) / (y + C(1.0))\n\n    a = relay.var(\"a\", relay.TensorType((1000,), \"float32\"))\n    y = approximate_sigmoid(a)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1000,), \"float32\")\n    data = np.linspace(-5, 5, 1000).astype(\"float32\")\n    op_res = create_executor().evaluate(y, {a: relay.const(data)})\n\n    def reference_sigmoid(x):\n        return np.exp(-np.logaddexp(0, -x))\n\n    np.testing.assert_allclose(op_res.numpy(), reference_sigmoid(data), atol=2e-5, rtol=1e-9)\n\n    y = approximate_tanh(a)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1000,), \"float32\")\n    data = np.linspace(-5, 5, 1000).astype(\"float32\")\n    op_res = create_executor().evaluate(y, {a: relay.const(data)})\n\n    def reference_tanh(x):\n        return np.tanh(x)\n\n    np.testing.assert_allclose(op_res.numpy(), reference_tanh(data), atol=4e-5, rtol=1e-9)\n\n\nclass TestSqueeze:\n    shape, dtype, axis = tvm.testing.parameters(\n        ((1, 3, 2, 5), \"float32\", None),\n        ((1, 3, 1), \"float32\", [0]),\n        ((1, 2, 1, 2, 1), \"float32\", [0, 2]),\n    )\n\n    def test_squeeze(self, shape, dtype, axis):\n        x = relay.var(\"x\", relay.TensorType(shape, dtype))\n        squeeze = relay.squeeze(x, axis=axis)\n\n        np_axis = tuple(axis) if axis is not None else None\n\n        data = np.random.random_sample(shape).astype(dtype)\n        op_res = create_executor().evaluate(squeeze, {x: relay.const(data)})\n        ref_res = np.squeeze(data, axis=np_axis)\n        np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\ndef test_transpose_infer_type():\n    n, t, d = te.size_var(\"n\"), te.size_var(\"t\"), 100\n    x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n    y = relay.transpose(x, axes=(1, 0, 2))\n    assert \"axes=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((t, n, 100), \"float32\")\n\n    y = relay.transpose(x)\n    assert \"axes=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((100, t, n), \"float32\")\n\n\ndef test_transpose(target, dev, executor_kind):\n    dshape = (2, 3, 4)\n    axes = (0, 2, 1)\n\n    x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n    z = relay.transpose(x, axes=axes)\n\n    func = relay.Function([x], z)\n    x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n    ref_res = np.transpose(x_data, axes=axes)\n\n    op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(x_data)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef test_squeeze_infer_type():\n    n, t, d = 1, 4, 1\n    x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n    y = relay.squeeze(x, axis=(2,))\n    assert \"axis=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1, 4), \"float32\")\n\n    n, t, d = 1, 4, 1\n    x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n    y = relay.squeeze(x)\n    assert \"axis=\" not in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((4,), \"float32\")\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_squeeze_bad_axes_infer_type():\n    n, t, d = 1, 4, 1\n    x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n    y = relay.squeeze(x, axis=(1,))\n    yy = run_infer_type(y)\n\n\ndef test_reshape_infer_type():\n    n, t, d1, d2 = 10, 20, 100, 20\n    x = relay.var(\"x\", relay.TensorType((n, t, d1, d2), \"float32\"))\n    y = relay.reshape(x, newshape=(n, t, 2000))\n    assert \"newshape=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, t, 2000), \"float32\")\n\n\nclass TestReshape:\n    shape, newshape, oshape = tvm.testing.parameters(\n        ((2, 3, 4), (8, 3), (8, 3)),\n        ((4, 7), (2, 7, 2), (2, 7, 2)),\n        ((2, 3, 4), (4, 0, 2), (4, 3, 2)),\n        ((2, 3, 4), (2, 0, 0), (2, 3, 4)),\n        ((2, 3, 4), (0, -1), (2, 12)),\n        ((2, 3, 4), (-1, 0), (8, 3)),\n        ((2, 3, 4), (2, -2), (2, 3, 4)),\n        ((2, 3, 4), (-2, 1, 1), (2, 3, 4, 1, 1)),\n        ((2, 3, 4), (-3, 4), (6, 4)),\n        ((2, 3, 4, 5), (-3, -3), (6, 20)),\n        ((2, 3, 4), (0, -3), (2, 12)),\n        ((2, 3, 4), (-3, -2), (6, 4)),\n        ((2, 3, 4), (-4, 1, 2, -2), (1, 2, 3, 4)),\n        ((2, 3, 4), (2, -4, -1, 3, -2), (2, 1, 3, 4)),\n        ((1,), (), ()),\n    )\n\n    def test_reshape(self, target, dev, executor_kind, shape, newshape, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.reshape(x, newshape=newshape)\n        zz = run_infer_type(z)\n        assert \"newshape=\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n        func = relay.Function([x], z)\n        check_grad(func)\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef test_reshape_fail():\n    with pytest.raises(TVMError) as reshape_err:\n        x = relay.var(\"x\", relay.TensorType([2, 3], \"float32\"))\n        z = relay.reshape(x, [7])\n        zz = run_infer_type(z)\n\n\ndef test_reshape_like_infer_type():\n    # concrete shape\n    x = relay.var(\"x\", relay.TensorType((1, 2, 3), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((1, 6), \"float32\"))\n    z = relay.reshape_like(x, y)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((1, 6), \"float32\")\n\n    # symbolic shape\n    n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((1, 8, 8), \"float32\"))\n    z = relay.reshape_like(x, y)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((1, 8, 8), \"float32\")\n\n    # partial reshaping\n    x = relay.var(\"x\", relay.TensorType((1, 2, 3, 4), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((1, 6, 5), \"float32\"))\n    z = relay.reshape_like(x, y, lhs_begin=1, lhs_end=3, rhs_begin=1, rhs_end=2)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((1, 6, 4), \"float32\")\n\n    x = relay.var(\"x\", relay.TensorType((1, 2, 3, 4), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((2, 3, 4, 1, 6), \"float32\"))\n    z = relay.reshape_like(x, y, rhs_end=3)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((2, 3, 4), \"float32\")\n    z = relay.reshape_like(x, y, rhs_begin=2)\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((4, 1, 6), \"float32\")\n\n    # symbolic partial reshaping\n    n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.var(\"y\", relay.TensorType((5, 6), \"float32\"))\n    z = relay.var(\"z\", relay.TensorType((4,), \"float32\"))\n    w = relay.reshape_like(x, y, lhs_end=3)\n    w = relay.reshape_like(w, z, lhs_begin=2)\n    w = run_infer_type(w)\n    assert w.checked_type == relay.TensorType((5, 6, 4), \"float32\")\n\n\nclass TestReshapeLike:\n    shape, oshape, shape_like, reshape_like_kwargs = tvm.testing.parameters(\n        ((2, 3, 4), (1, 8, 3), None, {}),\n        ((4, 7), (2, 7, 2), None, {}),\n        ((1, 2, 3, 4), (1, 6, 4), (1, 6, 5), dict(lhs_begin=1, lhs_end=3, rhs_begin=1, rhs_end=2)),\n    )\n\n    def test_reshape_like(\n        self, target, dev, executor_kind, shape, oshape, shape_like=None, reshape_like_kwargs={}\n    ):\n        if shape_like is None:\n            shape_like = oshape\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=shape_like).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"x\", relay.TensorType(shape_like, \"float32\"))\n        z = relay.reshape_like(x, y, **reshape_like_kwargs)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.ty.TensorType(ref_res.shape, \"float32\")\n\n        func = relay.Function([x, y], z)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, y_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestTakeInferType:\n    d1, d2, d3 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\")\n    d4, d5, d6 = te.var(\"d4\"), te.var(\"d5\"), te.var(\"d6\")\n    dshape, indices_shape, oshape, axis = tvm.testing.parameters(\n        ((d1,), (1,), (1,), 0),\n        ((4,), (d1, d2), (d1, d2), None),\n        ((3, 3, 3), (1, d2), (1, d2), None),\n        ((d1, d2), (d3, d4, d5), (d3, d4, d5, d2), 0),\n        ((d1, d2), (d3, d4, d5), (d1, d3, d4, d5), 1),\n        ((d1, d2, d3, d4), (d5, d6), (d1, d2, d5, d6, d4), -2),\n    )\n\n    def test_take(self, dshape, indices_shape, oshape, axis):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n        y = relay.take(x, indices, axis=axis)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType(oshape, \"float32\")\n\n\nclass TestTake:\n    src_shape, indices_src, axis, mode, indices_dtype = tvm.testing.parameters(\n        ((4,), [1], None, \"clip\", \"int32\"),\n        ((4,), [[0, 1, 2, 3]], None, \"clip\", \"int32\"),\n        ((3, 3, 3), [[11, 25]], None, \"clip\", \"int32\"),\n        ((4,), [[0, 1], [2, 3]], None, \"clip\", \"int32\"),\n        ((4,), [1], 0, \"clip\", \"int32\"),\n        ((2, 2), [[[1, 0], [0, 1]]], 0, \"clip\", \"int32\"),\n        ((2, 2), [[[1, 0], [0, 1]]], 1, \"clip\", \"int32\"),\n        ((4, 3, 5, 6), [[2, 1, 0, 0]], -2, \"clip\", \"int32\"),\n        ((3, 4), [-5, 20], None, \"clip\", \"int32\"),\n        ((3, 4), [-5, 20], None, \"wrap\", \"int32\"),\n        ((3, 4), [-1, 2], 0, \"clip\", \"int32\"),\n        ((3, 4), [-1, 2], 0, \"wrap\", \"int32\"),\n        ((3, 4), [-1, 2], 1, \"clip\", \"int32\"),\n        ((3, 4), [-1, 2], 1, \"wrap\", \"int32\"),\n        ((3, 3, 3), [[11, 25]], None, \"fast\", \"int32\"),\n        ((3, 4), [0, 2], 0, \"fast\", \"int32\"),\n        ((3, 4), [0, 2], 1, \"fast\", \"int32\"),\n        ((3, 4), [1, 2], 1, \"clip\", \"uint32\"),\n        ((3, 4), [1, 2], 1, \"wrap\", \"uint16\"),\n        ((3, 3, 3), [1, 2], None, \"fast\", \"uint16\"),\n        ((3, 4), [0, 2], 0, \"fast\", \"uint8\"),\n    )\n\n    # Incorrect numeric output in some cases on vulkan\n    @tvm.testing.known_failing_targets(\"vulkan\")\n    def test_take(\n        self, target, dev, executor_kind, src_shape, indices_src, axis, mode, indices_dtype\n    ):\n        src_dtype = \"float32\"\n        indices_src = np.array(indices_src, dtype=indices_dtype)\n        x = relay.var(\"x\", relay.TensorType(src_shape, src_dtype))\n        indices = relay.var(\"indices\", relay.TensorType(indices_src.shape, indices_dtype))\n        z = relay.take(x, indices, axis=axis, mode=mode)\n\n        func = relay.Function([x, indices], z)\n        x_data = np.random.uniform(low=-1, high=1, size=src_shape).astype(src_dtype)\n        np_mode = \"raise\" if mode == \"fast\" else mode\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, indices_src\n        )\n\n        # Old versions of numpy has take internally cast inside take which may violate\n        # safety rules. We have such version in i386 CI image.\n        indices_src = indices_src.astype(\"int32\")\n        ref_res = np.take(x_data, indices=indices_src, axis=axis, mode=np_mode)\n\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestSplitInferType:\n    idxd = tvm.tir.indexdiv\n\n    d1, d2, d3, d4 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\"), te.var(\"d4\")\n    axis = te.var(\"axis\")\n\n    dshape, indices_or_sections, ret_type, axis = tvm.testing.parameters(\n        (\n            (5, 5, 2, 2),\n            5,\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n                        relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n                        relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n                        relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n                        relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n                    ]\n                )\n            ),\n            1,\n        ),\n        (\n            (5, 5, 2, 2),\n            5,\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n                        relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n                        relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n                        relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n                        relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n                    ]\n                )\n            ),\n            0,\n        ),\n        (\n            (d1, d2, d3, d4),\n            4,\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n                        relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n                        relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n                        relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n                    ]\n                )\n            ),\n            2,\n        ),\n        (\n            (d1, d2, d3, d4),\n            2,\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((idxd(d1, 2), d2, d3, d4), \"float32\"),\n                        relay.ty.TensorType((idxd(d1, 2), d2, d3, d4), \"float32\"),\n                    ]\n                )\n            ),\n            0,\n        ),\n        (\n            (d1, d2, d3, d4),\n            (2, 4, 7),\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, 3, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, (d2 - 7), d3, d4), \"float32\"),\n                    ]\n                )\n            ),\n            1,\n        ),\n        (\n            (d1, d2, d3, d4),\n            tuple(np.array([2, 4, 7]).astype(np.int64)),\n            relay.ty.TupleType(\n                tvm.runtime.convert(\n                    [\n                        relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, 3, d3, d4), \"float32\"),\n                        relay.ty.TensorType((d1, (d2 - 7), d3, d4), \"float32\"),\n                    ]\n                )\n            ),\n            1,\n        ),\n    )\n\n    def test_split(self, dshape, indices_or_sections, ret_type, axis):\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, \"float32\"))\n        y = relay.split(x, indices_or_sections, axis=axis)\n        yy = run_infer_type(y.astuple())\n        assert yy.checked_type == ret_type\n\n\ndef test_full_infer_type():\n    # default settings: match input dtype\n    x = relay.var(\"x\", relay.TensorType((), \"int8\"))\n    y = relay.full(x, ())\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((), \"int8\")\n\n    # change the shape and dtype\n    x = relay.var(\"x\", relay.TensorType((), \"float32\"))\n    y = relay.full(x, (1, 2), \"int8\")\n    \"shape=\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1, 2), \"int8\")\n\n\nclass TestFull:\n    fill_value, arr_shape, dtype = tvm.testing.parameters(\n        (4, (1, 3, 4, 4), \"int32\"),\n        (4, (1, 3, 4, 4), \"int64\"),\n        (4.0, (1, 4), \"float32\"),\n    )\n\n    def test_full(self, target, dev, executor_kind, fill_value, arr_shape, dtype):\n        x = relay.var(\"x\", relay.scalar_type(dtype))\n        z = relay.full(x, arr_shape, dtype)\n        func = relay.Function([x], z)\n        ref_res = np.full(arr_shape, fill_value, dtype=dtype)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            np.array(fill_value, dtype)\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    def test_full_like(self, target, dev, executor_kind, arr_shape, fill_value, dtype):\n        x_data = np.random.uniform(low=-1, high=1, size=arr_shape).astype(dtype)\n        x = relay.var(\"x\", relay.TensorType(arr_shape, dtype))\n        y = relay.var(\"y\", relay.scalar_type(dtype))\n        z = relay.full_like(x, y)\n\n        func = relay.Function([x, y], z)\n        ref_res = np.full_like(x_data, fill_value)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, np.array(fill_value, dtype)\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef test_full_like_infer_type():\n    # concrete shape\n    base = relay.var(\"base\", relay.TensorType((1, 2, 3), \"float32\"))\n    fill = relay.var(\"fill\", relay.TensorType((), \"float32\"))\n    y = relay.full_like(base, fill)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((1, 2, 3), \"float32\")\n\n    # symbolic shape\n    n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n    base = relay.var(\"base\", relay.TensorType((n, c, h, w), \"float32\"))\n    fill = relay.var(\"fill\", relay.TensorType((), \"float32\"))\n    y = relay.full_like(base, fill)\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, h, w), \"float32\")\n\n\ndef test_infer_type_leaky_relu(target, dev, executor_kind):\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n    y = relay.nn.leaky_relu(x, alpha=0.1)\n    \"alpha=0.1\" in y.astext()\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, c, h, w), \"float32\")\n\n    shape = (1, 5, 10, 10)\n    dtype = \"float32\"\n    x = relay.var(\"x\", relay.TensorType(shape, dtype))\n    z = relay.nn.leaky_relu(x, alpha=0.1)\n    assert \"alpha=0.1\" in z.astext()\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType(shape, dtype)\n    func = relay.Function([x], z)\n    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)\n    ref_res = np.where(x_data > 0, x_data, x_data * 0.1)\n\n    op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(x_data)\n    tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestInferTypePrelu:\n    dtype = tvm.testing.parameter(\"float32\")\n\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    data, alpha, axis, output = tvm.testing.parameters(\n        ((n, c, h, w), (c,), 1, (n, c, h, w)),\n        ((n, h, w, c), (c,), 3, (n, h, w, c)),\n        ((n, c, h, w), None, 1, (n, c, h, w)),\n        ((n, h, w, c), None, 3, (n, h, w, c)),\n        ((1, 3, 2, 2), (3,), 1, (1, 3, 2, 2)),\n        ((1, 2, 2, 3), (3,), 3, (1, 2, 2, 3)),\n        ((1, 3, 2, 2), None, 1, (1, 3, 2, 2)),\n        ((1, 2, 2, 3), None, 3, (1, 2, 2, 3)),\n    )\n\n    def test_infer_type_prelu(self, target, dev, executor_kind, data, alpha, axis, output, dtype):\n        x = relay.var(\"data\", relay.TensorType(data, dtype))\n        if alpha:\n            y = relay.var(\"alpha\", relay.TensorType(alpha, dtype))\n        else:\n            y = relay.var(\"alpha\", relay.IncompleteType())\n        z = relay.nn.prelu(x, y, axis=axis)\n        zz = run_infer_type(z)\n        if axis != 1:\n            assert \"axis\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(output, dtype)\n        if not alpha:\n            axis = axis if axis else 1\n            alpha_shape = (data[axis],)\n            assert zz.args[1].checked_type == relay.TensorType(alpha_shape, \"float32\")\n\n        if all(isinstance(v, tvm.tir.Var) == 1 for v in data) or not alpha:\n            return\n\n        func = relay.Function([x, y], z)\n        x_data = np.random.uniform(low=-1, high=1, size=data).astype(dtype)\n        a_data = np.random.uniform(low=-1, high=1, size=alpha).astype(dtype)\n\n        if axis == 1:\n            ref_res = (x_data < 0) * (x_data * a_data.reshape(3, 1, 1)) + (x_data >= 0) * x_data\n        else:\n            ref_res = (x_data < 0) * (x_data * a_data.reshape(1, 1, 3)) + (x_data >= 0) * x_data\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, a_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestArange:\n    dtype = tvm.testing.parameter(\"float32\")\n\n    start, stop, step = tvm.testing.parameters(\n        (None, 20, None),\n        (None, 20, 2),\n        (1, 20, None),\n        (1, 20, 2),\n        # arange doesnt' support floating point right now, see type relation\n        # (1, 20, 1.5),\n        (1, 20.5, None),\n        (1, 20, 3),\n        (20, 1, -1),\n        # arange doesnt' support floating point right now, see type relation\n        # (20, 1, -1.5),\n    )\n\n    def test_arange(self, target, dev, executor_kind, start, stop, step, dtype):\n        if start is None and step is None:\n            x = relay.arange(relay.const(stop, dtype=dtype))\n            ref_res = np.arange(stop).astype(dtype)\n        elif start is None:\n            x = relay.arange(relay.const(stop, dtype=dtype), step=relay.const(step, dtype=dtype))\n            ref_res = np.arange(stop, step=step).astype(dtype)\n        elif step is None:\n            x = relay.arange(relay.const(start, dtype=dtype), relay.const(stop, dtype=dtype))\n            ref_res = np.arange(start, stop).astype(dtype)\n        else:\n            x = relay.arange(\n                relay.const(start, dtype=dtype),\n                relay.const(stop, dtype=dtype),\n                relay.const(step, dtype=dtype),\n            )\n            ref_res = np.arange(start, stop, step).astype(dtype)\n\n        func = relay.Function([], x)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)()\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestMeshgrid:\n    lengths, indexing = tvm.testing.parameters(\n        ([3, 5], \"ij\"),\n        ([4, 2], \"xy\"),\n        ([3, 5, 2], \"ij\"),\n        ([3, 1, 5], \"xy\"),\n        # Length 0 signifies scalar.\n        ([3, 5, 0], \"ij\"),\n    )\n\n    def test_meshgrid(self, target, dev, executor_kind, lengths, indexing=\"ij\"):\n        input_vars = []\n        input_data = []\n        for i, length in enumerate(lengths):\n            input_name = \"x_{}\".format(i)\n            if length == 0:\n                # Scalar\n                input_vars.append(relay.var(input_name, relay.scalar_type(\"float32\")))\n                input_data.append(np.array(1, \"float32\"))\n            else:\n                input_vars.append(relay.var(input_name, relay.TensorType((length,), \"float32\")))\n                input_data.append(np.arange(length).astype(\"float32\"))\n\n        z = relay.meshgrid(input_vars, indexing=indexing).astuple()\n        func = relay.Function(input_vars, z)\n        # Get ref\n        ref_res = np.meshgrid(*input_data, indexing=indexing)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            *input_data\n        )\n        assert len(op_res) == len(ref_res)\n        for i in range(len(op_res)):\n            tvm.testing.assert_allclose(op_res[i].numpy(), ref_res[i], rtol=1e-5)\n\n\nclass TestTile:\n    dshape, reps = tvm.testing.parameters(\n        ((2, 3, 4), (3, 2, 1)),\n        ((2, 3, 4), (1, 2)),\n        ((2, 3), (3, 2, 1)),\n    )\n\n    def test_tile(self, target, dev, executor_kind, dshape, reps):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.tile(x, reps=reps)\n\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n        ref_res = np.tile(x_data, reps=reps)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestRepeat:\n    dshape, repeats, axis = tvm.testing.parameters(\n        ((3,), 2, 0),\n        ((3, 10), 2, -1),\n        ((3, 2, 4), 3, 1),\n    )\n\n    def test_repeat(self, target, dev, executor_kind, dshape, repeats, axis):\n        x = relay.Var(\"x\", relay.TensorType(dshape, \"float32\"))\n        func = relay.Function([x], relay.repeat(x, repeats, axis))\n        data = np.random.uniform(size=dshape).astype(\"float32\")\n        ref_res = np.repeat(data, repeats, axis)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestStack:\n    dshapes, axis = tvm.testing.parameters(\n        ([(2,), (2,), (2,)], -1),\n        ([(2,), (2,), (2,)], 0),\n        ([(2, 2, 4), (2, 2, 4), (2, 2, 4)], 1),\n        ([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], -1),\n        ([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], 4),\n    )\n\n    expr_type = tvm.testing.parameter(\"tuple\", \"list\", \"tuple_expr\")\n\n    @tvm.testing.fixture\n    def ref_data(self, dshapes, axis):\n        np_in = [np.random.normal(size=shape).astype(\"float32\") for shape in dshapes]\n        np_out = np.stack(np_in, axis=axis)\n        return np_in, np_out\n\n    @tvm.testing.fixture\n    def input_expr(self, dshapes, axis, expr_type, ref_data):\n        input_vars = [relay.var(\"input\", relay.TensorType(shape, \"float32\")) for shape in dshapes]\n\n        if expr_type == \"tuple\":\n            input_expr = relay.Tuple(input_vars)\n\n        elif expr_type == \"list\":\n            input_expr = input_vars\n\n        elif expr_type == \"tuple_expr\":\n            # expression that evaluates to a tuple\n            # but is not a tuple literal\n            np_in, np_out = ref_data\n            x = relay.Var(\"x\")\n            input_expr = relay.Let(x, relay.Tuple([relay.const(inp) for inp in np_in]), x)\n\n        else:\n            raise ValueError(f\"Unknown expr_type '{expr_type}'\")\n\n        return input_expr\n\n    def test_stack(self, target, dev, executor_kind, input_expr, ref_data, axis):\n        z = relay.stack(input_expr, axis=axis)\n        inp_vars = relay.analysis.free_vars(z)\n        func = relay.Function(inp_vars, z)\n\n        np_in, np_out = ref_data\n        relay_args = np_in if inp_vars else []\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            *relay_args\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), np_out, rtol=1e-5)\n\n\nclass TestReverse:\n    dshape, axis = tvm.testing.parameters(\n        ((2, 3, 4), 1),\n        ((4, 7), 0),\n        ((2, 3, 4), -1),\n    )\n\n    def test_reverse(self, target, dev, executor_kind, dshape, axis):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.reverse(x, axis=axis)\n        zz = run_infer_type(z)\n\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n        ref_res = np.flip(x_data, axis)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef test_reverse_sequence(target, dev, executor_kind):\n    def verify_reverse_sequence(x_data, seq_lengths, batch_axis, seq_axis, ref_res):\n        seq_lengths_data = np.array(seq_lengths).astype(\"int32\")\n        x = relay.var(\"x\", relay.TensorType(x_data.shape, str(x_data.dtype)))\n        z = relay.reverse_sequence(x, relay.const(seq_lengths_data), seq_axis, batch_axis)\n        zz = run_infer_type(z)\n        assert zz.checked_type == x.type_annotation\n        func = relay.Function([x], z)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 5, 10, 15], [4, 1, 6, 11], [8, 9, 2, 7], [12, 13, 14, 3]]\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 1, 0, np.array(result))\n    verify_reverse_sequence(indata, [1, 2, 3, 4], -1, 0, np.array(result))\n    verify_reverse_sequence(\n        indata.astype(\"float32\"), [1, 2, 3, 4], 1, 0, np.array(result).astype(\"float32\")\n    )\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 1, 2, 3], [5, 4, 6, 7], [10, 9, 8, 11], [15, 14, 13, 12]]\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 0, 1, np.array(result))\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 0, -1, np.array(result))\n    verify_reverse_sequence(\n        indata.astype(\"float32\"), [1, 2, 3, 4], 0, 1, np.array(result).astype(\"float32\")\n    )\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [15, 14, 13, 12]]\n    verify_reverse_sequence(indata, [-1, 0, 1, 5], 0, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n    result = [\n        [\n            [[18, 19, 20], [21, 22, 23], [24, 25, 26]],\n            [[9, 10, 11], [12, 13, 14], [15, 16, 17]],\n            [[0, 1, 2], [3, 4, 5], [6, 7, 8]],\n        ],\n        [\n            [[45, 46, 47], [48, 49, 50], [51, 52, 53]],\n            [[36, 37, 38], [39, 40, 41], [42, 43, 44]],\n            [[27, 28, 29], [30, 31, 32], [33, 34, 35]],\n        ],\n    ]\n    verify_reverse_sequence(indata, [3, 3], 0, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n    result = [\n        [\n            [[9, 10, 11], [21, 22, 23], [15, 16, 17]],\n            [[0, 1, 2], [12, 13, 14], [6, 7, 8]],\n            [[18, 19, 20], [3, 4, 5], [24, 25, 26]],\n        ],\n        [\n            [[36, 37, 38], [48, 49, 50], [42, 43, 44]],\n            [[27, 28, 29], [39, 40, 41], [33, 34, 35]],\n            [[45, 46, 47], [30, 31, 32], [51, 52, 53]],\n        ],\n    ]\n    verify_reverse_sequence(indata, [2, 3, 2], 2, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = []\n    with pytest.raises(Exception) as execinfo:\n        verify_reverse_sequence(indata, [2, 3, 2, 4, 5], 1, 0, np.array(result))\n\n    assert (\n        \"For reverse_sequnece seq_lengths size should match with dimension of batch axis,\"\n        \" but got dimension of batch_axis = 4, and seq_length size = 5\" in execinfo.value.args[0]\n    )\n\n\ndef ref_scatter(data, indices, updates, axis=0):\n    idx = np.indices(indices.shape).reshape(indices.ndim, -1)\n\n    updated_idx = np.copy(idx)\n    indices = indices.reshape(-1)\n    for i in range(len(indices)):\n        updated_idx[axis, i] = indices[i]\n    scattered = np.copy(data)\n    scattered[tuple(updated_idx)] = updates[tuple(idx)]\n    return scattered\n\n\ndef test_scatter(target, dev, executor_kind):\n    def verify_scatter(dshape, ishape, axis=0, indices_dtype=\"int64\"):\n        d = relay.var(\"d\", relay.TensorType(dshape, \"float32\"))\n        i = relay.var(\"i\", relay.TensorType(ishape, indices_dtype))\n        u = relay.var(\"u\", relay.TensorType(ishape, \"float32\"))\n        z = relay.op.scatter(d, i, u, axis)\n\n        func = relay.Function([d, i, u], z)\n\n        data_np = np.random.uniform(size=dshape).astype(\"float32\")\n        updates_np = np.random.uniform(size=ishape).astype(\"float32\")\n        indices_np = np.random.randint(0, dshape[axis] - 1, ishape).astype(indices_dtype)\n\n        ref_res = ref_scatter(data_np, indices_np, updates_np, axis)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data_np, indices_np, updates_np\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_scatter((10,), (10,), 0)\n    verify_scatter((10, 5), (10, 5), -2)\n    verify_scatter((10, 5), (10, 5), -1)\n    verify_scatter((10, 5), (3, 5), 0)\n    verify_scatter((12, 4), (7, 2), 1)\n    verify_scatter((2, 3, 4), (1, 3, 4), 0)\n    verify_scatter((2, 3, 4), (2, 1, 4), 1)\n    verify_scatter((2, 3, 4), (2, 3, 1), 2)\n    verify_scatter((4, 2, 1), (1, 1, 1), 0)\n    verify_scatter((2, 3, 4, 5), (1, 3, 4, 5), 0)\n    verify_scatter((6, 3, 4, 5), (2, 3, 4, 5), 1)\n    verify_scatter((2, 3, 8, 5), (2, 3, 1, 1), 2)\n    verify_scatter((16, 16, 4, 5), (16, 16, 4, 5), 3)\n    verify_scatter((16, 16, 4, 5), (16, 16, 4, 5), 3, indices_dtype=\"uint32\")\n\n\nclass TestDynamicScatter:\n    dshape, ishape, axis = tvm.testing.parameters(\n        ((10,), (10,), 0),\n        ((10, 5), (10, 5), -2),\n        ((10, 5), (10, 5), -1),\n        ((10, 5), (3, 5), 0),\n        ((12, 4), (7, 2), 1),\n        ((2, 3, 4), (1, 3, 4), 0),\n        ((2, 3, 4), (2, 1, 4), 1),\n        ((2, 3, 4), (2, 3, 1), 2),\n        ((4, 2, 1), (1, 1, 1), 0),\n        ((2, 3, 4, 5), (1, 3, 4, 5), 0),\n        ((6, 3, 4, 5), (2, 3, 4, 5), 1),\n        ((2, 3, 8, 5), (2, 3, 1, 1), 2),\n        ((16, 16, 4, 5), (16, 16, 4, 5), 3),\n    )\n\n    @pytest.mark.parametrize(\"executor_kind\", [\"vm\"])\n    def test_dynamic_scatter(self, target, dev, executor_kind, dshape, ishape, axis):\n        d = relay.var(\"d\", relay.TensorType([relay.Any() for i in range(len(dshape))], \"float32\"))\n        i = relay.var(\"i\", relay.TensorType([relay.Any() for i in range(len(ishape))], \"int64\"))\n        u = relay.var(\"u\", relay.TensorType([relay.Any() for i in range(len(ishape))], \"float32\"))\n        z = relay.op.scatter(d, i, u, axis)\n\n        func = relay.Function([d, i, u], z)\n\n        data_np = np.random.uniform(size=dshape).astype(\"float32\")\n        updates_np = np.random.uniform(size=ishape).astype(\"float32\")\n        indices_np = np.random.randint(-dshape[axis], dshape[axis] - 1, ishape).astype(\"int64\")\n\n        ref_res = ref_scatter(data_np, indices_np, updates_np, axis)\n\n        mod = tvm.ir.IRModule.from_expr(func)\n        op_res = relay.create_executor(\n            executor_kind, mod=mod, device=dev, target=target\n        ).evaluate()(data_np, indices_np, updates_np)\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\nclass TestScatterAdd:\n    dshape, ishape, axis, dtype, indice_dtype = tvm.testing.parameters(\n        ((10,), (10,), 0, \"int32\", \"int64\"),\n        ((1000,), (1000,), 0, \"int32\", \"int64\"),\n        ((10, 5), (10, 5), -2, \"float32\", \"int64\"),\n        ((10, 5), (10, 5), -1, \"float32\", \"int64\"),\n        ((10, 5), (3, 5), 0, \"float32\", \"int64\"),\n        ((12, 4), (7, 2), 1, \"float32\", \"int64\"),\n        ((2, 3, 4), (1, 3, 4), 0, \"float32\", \"int64\"),\n        ((2, 3, 4), (2, 1, 4), 1, \"float32\", \"int64\"),\n        ((2, 3, 4), (2, 3, 1), 2, \"float32\", \"int64\"),\n        ((2, 3, 4, 5), (1, 3, 4, 5), 0, \"float32\", \"int64\"),\n        ((6, 3, 4, 5), (2, 3, 4, 5), 1, \"float32\", \"int64\"),\n        ((2, 3, 8, 5), (2, 3, 1, 1), 2, \"float32\", \"int64\"),\n        ((16, 16, 4, 5), (16, 16, 4, 5), 3, \"float32\", \"int64\"),\n        ((16, 16, 4, 5), (16, 16, 4, 5), 3, \"float32\", \"uint32\"),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(self, dshape, ishape, axis, dtype, indice_dtype):\n        data_np = np.random.uniform(size=dshape).astype(dtype)\n        updates_np = np.random.uniform(size=ishape).astype(dtype)\n        indices_np = np.random.randint(0, dshape[axis] - 1, ishape).astype(indice_dtype)\n\n        out_np = np.copy(data_np)\n        for index in np.ndindex(*indices_np.shape):\n            new_index = list(index)\n            new_index[axis] = indices_np[index]\n            out_np[tuple(new_index)] += updates_np[index]\n        return data_np, updates_np, indices_np, out_np\n\n    # Optimization can produce tir.atomic_add, not currently supported\n    # on vulkan runtime.\n    @tvm.testing.known_failing_targets(\"vulkan\")\n    def test_scatter_add(self, target, dev, ref_data, dshape, ishape, axis, dtype, indice_dtype):\n        d = relay.var(\"d\", relay.TensorType(shape=[relay.Any() for _ in dshape], dtype=dtype))\n        i = relay.var(\n            \"i\", relay.TensorType(shape=[relay.Any() for _ in ishape], dtype=indice_dtype)\n        )\n        u = relay.var(\"u\", relay.TensorType(shape=[relay.Any() for _ in ishape], dtype=dtype))\n        z = relay.op.scatter_add(d, i, u, axis)\n\n        func = relay.Function([d, i, u], z)\n\n        data_np, updates_np, indices_np, out_np = ref_data\n\n        verify_func(target, dev, func, [data_np, indices_np, updates_np], out_np)\n\n\n@pytest.mark.parametrize(\n    \"data, axis, indices, ref_res\",\n    [\n        ([[1, 2], [3, 4]], 1, [[0, 0], [1, 0]], [[1, 1], [4, 3]]),\n        ([[1, 2], [3, 4]], -1, [[0, 0], [1, 0]], [[1, 1], [4, 3]]),\n        (\n            [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]],\n            0,\n            [[[1, 0, 1], [1, 1, 0]]],\n            [[[6, 1, 8], [9, 10, 5]]],\n        ),\n        (\n            [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]],\n            -3,\n            [[[1, 0, 1], [1, 1, 0]]],\n            [[[6, 1, 8], [9, 10, 5]]],\n        ),\n        (\n            [\n                [\n                    [-0.2321, -0.2024, -1.7624],\n                    [-0.3829, -0.4246, 0.2448],\n                    [0.1822, 0.2360, -0.8965],\n                    [0.4497, -0.2224, 0.6103],\n                ],\n                [\n                    [0.0408, -0.7667, -0.4303],\n                    [-0.3216, 0.7489, -0.1502],\n                    [0.0144, -0.4699, -0.0064],\n                    [-0.0768, -1.6064, 1.3390],\n                ],\n            ],\n            1,\n            [[[2, 2, 0], [1, 0, 3]], [[3, 2, 0], [1, 0, 0]]],\n            [\n                [[0.1822, 0.2360, -1.7624], [-0.3829, -0.2024, 0.6103]],\n                [[-0.0768, -0.4699, -0.4303], [-0.3216, -0.7667, -0.4303]],\n            ],\n        ),\n        (\n            [\n                [\n                    [-0.2321, -0.2024, -1.7624],\n                    [-0.3829, -0.4246, 0.2448],\n                    [0.1822, 0.2360, -0.8965],\n                    [0.4497, -0.2224, 0.6103],\n                ],\n                [\n                    [0.0408, -0.7667, -0.4303],\n                    [-0.3216, 0.7489, -0.1502],\n                    [0.0144, -0.4699, -0.0064],\n                    [-0.0768, -1.6064, 1.3390],\n                ],\n            ],\n            -2,\n            [[[2, 2, 0], [1, 0, 3]], [[3, 2, 0], [1, 0, 0]]],\n            [\n                [[0.1822, 0.2360, -1.7624], [-0.3829, -0.2024, 0.6103]],\n                [[-0.0768, -0.4699, -0.4303], [-0.3216, -0.7667, -0.4303]],\n            ],\n        ),\n        (\n            [\n                [\n                    [-0.2321, -0.2024, -1.7624],\n                    [-0.3829, -0.4246, 0.2448],\n                    [0.1822, 0.2360, -0.8965],\n                    [0.4497, -0.2224, 0.6103],\n                ],\n                [\n                    [0.0408, -0.7667, -0.4303],\n                    [-0.3216, 0.7489, -0.1502],\n                    [0.0144, -0.4699, -0.0064],\n                    [-0.0768, -1.6064, 1.3390],\n                ],\n            ],\n            -2,\n            [[[2, 2, 0], [1, 0, 3]], [[3, 2, 0], [1, 0, 0]]],\n            [\n                [[0.1822, 0.2360, -1.7624], [-0.3829, -0.2024, 0.6103]],\n                [[-0.0768, -0.4699, -0.4303], [-0.3216, -0.7667, -0.4303]],\n            ],\n        ),\n        (\n            [\n                [\n                    [0.3050, 1.6986, 1.1034],\n                    [0.7020, -0.6960, -2.1818],\n                    [0.3116, -0.5773, -0.9912],\n                    [0.0835, -1.3915, -1.0720],\n                ],\n                [\n                    [0.1694, -0.6091, -0.6539],\n                    [-0.5234, -0.1218, 0.5084],\n                    [0.2374, -1.9537, -2.0078],\n                    [-0.5700, -1.0302, 0.1558],\n                ],\n            ],\n            2,\n            [\n                [[1, 1, 0, 1], [0, 0, 2, 2], [1, 2, 1, 2], [2, 2, 1, 0]],\n                [[0, 0, 1, 2], [2, 2, 1, 0], [1, 2, 0, 0], [0, 2, 0, 2]],\n            ],\n            [\n                [\n                    [1.6986, 1.6986, 0.3050, 1.6986],\n                    [0.7020, 0.7020, -2.1818, -2.1818],\n                    [-0.5773, -0.9912, -0.5773, -0.9912],\n                    [-1.0720, -1.0720, -1.3915, 0.0835],\n                ],\n                [\n                    [0.1694, 0.1694, -0.6091, -0.6539],\n                    [0.5084, 0.5084, -0.1218, -0.5234],\n                    [-1.9537, -2.0078, 0.2374, 0.2374],\n                    [-0.5700, 0.1558, -0.5700, 0.1558],\n                ],\n            ],\n        ),\n        (\n            [\n                [\n                    [0.3050, 1.6986, 1.1034],\n                    [0.7020, -0.6960, -2.1818],\n                    [0.3116, -0.5773, -0.9912],\n                    [0.0835, -1.3915, -1.0720],\n                ],\n                [\n                    [0.1694, -0.6091, -0.6539],\n                    [-0.5234, -0.1218, 0.5084],\n                    [0.2374, -1.9537, -2.0078],\n                    [-0.5700, -1.0302, 0.1558],\n                ],\n            ],\n            -1,\n            [\n                [[1, 1, 0, 1], [0, 0, 2, 2], [1, 2, 1, 2], [2, 2, 1, 0]],\n                [[0, 0, 1, 2], [2, 2, 1, 0], [1, 2, 0, 0], [0, 2, 0, 2]],\n            ],\n            [\n                [\n                    [1.6986, 1.6986, 0.3050, 1.6986],\n                    [0.7020, 0.7020, -2.1818, -2.1818],\n                    [-0.5773, -0.9912, -0.5773, -0.9912],\n                    [-1.0720, -1.0720, -1.3915, 0.0835],\n                ],\n                [\n                    [0.1694, 0.1694, -0.6091, -0.6539],\n                    [0.5084, 0.5084, -0.1218, -0.5234],\n                    [-1.9537, -2.0078, 0.2374, 0.2374],\n                    [-0.5700, 0.1558, -0.5700, 0.1558],\n                ],\n            ],\n        ),\n    ],\n)\ndef test_gather(target, dev, executor_kind, data, axis, indices, ref_res):\n    def verify_gather(data, axis, indices, ref_res):\n        data = np.asarray(data, dtype=\"float32\")\n        indices = np.asarray(indices, dtype=\"int32\")\n        ref_res = np.asarray(ref_res)\n        d = relay.var(\"x\", relay.TensorType(data.shape, \"float32\"))\n        i = relay.var(\"y\", relay.TensorType(indices.shape, \"int32\"))\n        z = relay.gather(d, axis, i)\n\n        func = relay.Function([d, i], z)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data, indices\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_gather(data, axis, indices, ref_res)\n\n\ndef test_gather_nd(target, dev, executor_kind):\n    def verify_gather_nd(xshape, yshape, y_data, batch_dims=0, indices_dtype=\"int32\"):\n        x = relay.var(\"x\", relay.TensorType(xshape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(yshape, indices_dtype))\n        z = relay.gather_nd(x, y, batch_dims)\n\n        func = relay.Function([x, y], z)\n\n        x_data = np.random.uniform(size=xshape).astype(\"float32\")\n\n        if y_data:\n            y_data = np.array(y_data, dtype=indices_dtype)\n        else:\n            y_data = np.random.randint(low=0, high=2, size=yshape, dtype=indices_dtype)\n\n        ref_res = ref_funcs.gather_nd(x_data, y_data, batch_dims)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, y_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_gather_nd((2, 2), (2, 3), [[1, 1, 0], [0, 1, 0]])\n    verify_gather_nd((2, 2, 2), (2, 2), [[0, 1], [1, 0]])\n    verify_gather_nd((3, 2, 2), (2, 2), [[0, 1], [1, 0]])\n    verify_gather_nd((3, 2), (2, 2, 3), [[[0, 1, 2], [2, 0, 1]], [[0, 0, 0], [1, 1, 1]]])\n\n    # Examples from tensorflow gather_nd doc\n    # https://www.tensorflow.org/api_docs/python/tf/gather_nd\n    verify_gather_nd((2, 2, 2), (1, 2), [[1, 0]], 1)\n    verify_gather_nd((2, 2, 2), (1, 2, 1), [[[1], [0]]], 1)\n    verify_gather_nd((2, 2, 2), (2, 2, 1), [[[1], [0]], [[0], [1]]], 1)\n\n    # Test cases from tensorflow gather_nd tests kernel_tests/array_ops_test.py\n    verify_gather_nd((2, 2, 2), (1, 2), None, 1)\n    verify_gather_nd((2, 2, 2), (2, 2), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (3, 2), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (2, 2), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (1, 2), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (3, 2, 1), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (2, 2, 2), None, 1)\n    verify_gather_nd((2, 2, 3, 2), (1, 2, 3), None, 1)\n\n    verify_gather_nd((3, 2, 2, 3, 4), (3, 3, 2), None, 2)\n    verify_gather_nd((3, 2, 2, 3, 4), (2, 3, 2), None, 2)\n    verify_gather_nd((3, 2, 2, 3, 4), (1, 3, 2), None, 2)\n    verify_gather_nd((3, 2, 2, 3, 4), (3, 3, 2, 1), None, 2)\n    verify_gather_nd((3, 2, 2, 3, 4), (2, 3, 2, 2), None, 2)\n    verify_gather_nd((3, 2, 2, 3, 4), (1, 3, 2, 3), None, 2)\n\n    verify_gather_nd((3, 2, 2, 3, 4), (1, 3, 2, 3), None, 2, indices_dtype=\"uint8\")\n    verify_gather_nd((2, 2, 2), (2, 2, 1), [[[1], [0]], [[0], [1]]], 1, indices_dtype=\"uint32\")\n\n\ndef _verify_infiniteness_ops(relay_op, ref_op, target=\"llvm\", dev=None):\n    for dtype in [\"float32\", \"float16\", \"float16\", \"int32\", \"int16\"]:\n        shape = (2, 8, 8)\n        x = relay.var(\"x\", relay.TensorType(shape, dtype))\n        y = relay_op(x)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.TensorType(shape, \"bool\")\n\n        data = np.random.uniform(size=shape).astype(dtype)\n        if dtype.startswith(\"float\"):\n            data.ravel()[\n                np.random.choice(data.size, int(data.size * 0.5), replace=False)\n            ] = np.infty\n            data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.nan\n\n        op_res = create_executor(target=target, device=dev).evaluate(y, {x: data})\n        ref_res = ref_op(data)\n        np.testing.assert_allclose(op_res.numpy(), ref_res, rtol=0.01)\n\n\n@tvm.testing.requires_gpu\ndef test_isfinite():\n    for target, dev in tvm.testing.enabled_targets():\n        if target not in [\"llvm\", \"cuda\"]:\n            continue\n        _verify_infiniteness_ops(relay.isfinite, np.isfinite, target=target, dev=dev)\n\n\n@tvm.testing.requires_gpu\ndef test_isinf():\n    for target, dev in tvm.testing.enabled_targets():\n        if target not in [\"llvm\", \"cuda\"]:\n            continue\n        _verify_infiniteness_ops(relay.isinf, np.isinf, target=target, dev=dev)\n\n\ndef test_unravel_index(target, dev, executor_kind):\n    def verify_unravel_index(indices, shape, dtype):\n        x_data = np.array(indices).astype(dtype)\n        y_data = np.array(shape).astype(dtype)\n        x = relay.var(\"x\", relay.TensorType(x_data.shape, dtype))\n        y = relay.var(\"y\", relay.TensorType(y_data.shape, dtype))\n\n        z = relay.unravel_index(x, y)\n        zz = run_infer_type(z)\n\n        if len(x_data.shape) == 1:\n            out_shape = [y_data.shape[0], x_data.shape[0]]\n        else:\n            out_shape = [y_data.shape[0]]\n        assert zz.checked_type == relay.ty.TensorType(out_shape, dtype)\n\n        func = relay.Function([x, y], z)\n        ref_res = np.unravel_index(x_data, y_data)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data, y_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    for dtype in [\"int64\", \"int32\"]:\n        verify_unravel_index([0, 1, 2, 3], [2, 2], dtype)\n        verify_unravel_index([144], [5, 5, 5, 2], dtype)\n        verify_unravel_index(144, [5, 5, 5, 2], dtype)\n        verify_unravel_index([100, 13, 5], [5, 5, 5, 2], dtype)\n\n        # In below example, 5 is out of bound for array of size 4.\n        # Numpy implementation throws error for it\n        # TVM implementation does not throw error instead it produces\n        # output which is inline with Tensorflow\n        # verify_unravel_index([0, 1, 2, 5], [2, 2], dtype)\n\n\ndef test_sparse_to_dense(target, dev, executor_kind):\n    def verify_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape, xpected):\n        sparse_indices_data = np.array(sparse_indices)\n        sparse_values_data = np.array(sparse_values)\n        default_value_data = np.array(default_value)\n\n        a = relay.var(\n            \"a\", relay.TensorType(sparse_indices_data.shape, str(sparse_indices_data.dtype))\n        )\n        b = relay.var(\n            \"b\", relay.TensorType(sparse_values_data.shape, str(sparse_values_data.dtype))\n        )\n        if default_value is None:\n            args = [a, b]\n            d = relay.sparse_to_dense(a, output_shape, b)\n        else:\n            c = relay.var(\n                \"c\", relay.TensorType(default_value_data.shape, str(default_value_data.dtype))\n            )\n            args = [a, b, c]\n            d = relay.sparse_to_dense(a, output_shape, b, c)\n\n        zz = run_infer_type(d)\n        assert zz.checked_type == relay.ty.TensorType(output_shape, str(sparse_values_data.dtype))\n\n        func = relay.Function(args, d)\n        f = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)\n        if default_value is None:\n            op_res = f(sparse_indices_data, sparse_values_data)\n        else:\n            op_res = f(sparse_indices_data, sparse_values_data, default_value_data)\n        tvm.testing.assert_allclose(op_res.numpy(), xpected, rtol=1e-5)\n\n    verify_sparse_to_dense(1, 3, 0, [5], [0, 3, 0, 0, 0])  # scalar\n    verify_sparse_to_dense([0, 1, 4], [3, 3, 3], 0, [5], [3, 3, 0, 0, 3])  # vector\n    verify_sparse_to_dense(\n        [[0, 0], [1, 2]], [1, 2], 0, [3, 4], [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]\n    )  # nXd\n    verify_sparse_to_dense(\n        [[0, 0, 0], [1, 2, 3]],\n        [1, 2],\n        4,\n        [2, 3, 4],\n        [[[1, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]], [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 2]]],\n    )  # nXd\n    verify_sparse_to_dense(\n        [0, 1, 4], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1]\n    )  # floats\n    # default value not specified\n    verify_sparse_to_dense(1, 3, None, [5], [0, 3, 0, 0, 0])\n\n    # negative test cases\n    # sparse indices should be ints\n    # verify_sparse_to_dense([[0.1, 1.1, 4.1], [0,2,4]], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n    # sparse_values should be 0d or 1d only\n    # verify_sparse_to_dense([[0, 1, 4], [0, 2, 4]], [[[3.1, 3.1, 3.1]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n    # sparse_indices should not be > 2d tensor\n    # verify_sparse_to_dense([[[[0, 1, 4], [0, 2, 4]]]], [[[[3.1, 3.1, 3.1]]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n\n\nclass TestSparseReshape:\n\n    sparse_indices_np, sparse_values_np, prev_shape_np, new_shape_np = tvm.testing.parameters(\n        (\n            np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]], dtype=np.int32),\n            np.array([7, 5, 6, 3, 9], dtype=np.int32),\n            np.array([2, 3, 6], dtype=np.int32),\n            np.array([9, -1], dtype=np.int32),\n        ),\n        (\n            np.array(\n                [[0, 0, 0, 0], [0, 0, 1, 2], [0, 1, 0, 3], [1, 0, 0, 4], [1, 2, 3, 6]],\n                dtype=np.int64,\n            ),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([2, 3, 6, 7], dtype=np.int64),\n            np.array([9, -1, 7], dtype=np.int64),\n        ),\n        (\n            np.array(\n                [\n                    [0, 0, 0, 0, 0],\n                    [0, 0, 1, 2, 3],\n                    [0, 1, 0, 3, 5],\n                    [1, 0, 0, 4, 6],\n                    [1, 2, 3, 6, 8],\n                ],\n                dtype=np.int64,\n            ),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([2, 3, 6, 7, 9], dtype=np.int64),\n            np.array([9, -1, 7], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 0], [0, 1], [3, 4], [4, 3], [7, 3]], dtype=np.int32),\n            np.array([7, 5, 6, 3, 9], dtype=np.int32),\n            np.array([9, 4], dtype=np.int32),\n            np.array([2, -1, 6], dtype=np.int32),\n        ),\n        (\n            np.array([[0, 0], [0, 1], [3, 4], [4, 3], [7, 3]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([9, 4], dtype=np.int64),\n            np.array([-1], dtype=np.int64),\n        ),\n        (\n            np.array([[0], [5], [10], [20], [24]], dtype=np.int32),\n            np.array([7, 5, 6, 3, 9], dtype=np.int32),\n            np.array([25], dtype=np.int32),\n            np.array([5, 5], dtype=np.int32),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int32),\n            np.array([7, 5, 6, 3, 9], dtype=np.int32),\n            np.array([500, 20], dtype=np.int32),\n            np.array([500, -1], dtype=np.int32),\n        ),\n        (\n            np.array([[0, 100], [200, 100], [300, 400], [50, 20], [400, 50]], dtype=np.int64),\n            np.array([7, 5, 6, 3, 9], dtype=np.int64),\n            np.array([500, 20], dtype=np.int64),\n            np.array([250, 40], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 1), dtype=np.int32),\n            np.array([], dtype=np.int32),\n            np.array([4], dtype=np.int32),\n            np.array([2, -1], dtype=np.int32),\n        ),\n        (\n            np.ones((0, 1), dtype=np.int64),\n            np.array([], dtype=np.int64),\n            np.array([4], dtype=np.int64),\n            np.array([2, 2], dtype=np.int64),\n        ),\n        (\n            np.ones((0, 2), dtype=np.int32),\n            np.array([], dtype=np.int32),\n            np.array([3, 6], dtype=np.int32),\n            np.array([-1, 2], dtype=np.int32),\n        ),\n    )\n\n    use_dyn = tvm.testing.parameter(True, False, ids=[\"dyn\", \"static\"])\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_res(\n        self,\n        sparse_indices_np: np.ndarray,\n        prev_shape_np: np.ndarray,\n        new_shape_np: np.ndarray,\n    ):\n        \"\"\"\n        This function calculates the expected output of sparseshape operator given the inputs.\n        \"\"\"\n\n        new_sparse_indices = np.ones(\n            (sparse_indices_np.shape[0], new_shape_np.shape[0]), dtype=sparse_indices_np.dtype\n        )\n        multipliers = np.ones(prev_shape_np.shape[0])\n        dividers = np.ones(new_shape_np.shape[0])\n        total_ele = np.prod(prev_shape_np)\n        division_total_ele = 1\n        for i in range(new_shape_np.shape[0]):\n            if new_shape_np[i] == -1:\n                continue\n            division_total_ele *= new_shape_np[i]\n        for i in range(prev_shape_np.shape[0] - 2, -1, -1):\n            multipliers[i] = prev_shape_np[i + 1] * multipliers[i + 1]\n\n        for i in range(len(new_shape_np)):\n            if new_shape_np[i] == -1:\n                new_shape_np[i] = total_ele // division_total_ele\n\n        if np.array_equal(prev_shape_np, new_shape_np):\n            return sparse_indices_np, prev_shape_np\n\n        for i in range(new_shape_np.shape[0] - 2, -1, -1):\n            dividers[i] = new_shape_np[i + 1] * dividers[i + 1]\n\n        for row_num, sparse_row in enumerate(sparse_indices_np):\n            flat_idx = 0\n            if len(sparse_indices_np.shape) != 1:\n                for i, ele in enumerate(sparse_row):\n                    flat_idx += sparse_row[i] * multipliers[i]\n            else:\n                flat_idx += sparse_row\n            if len(new_sparse_indices.shape) != 1:\n                for i in range(new_sparse_indices.shape[1]):\n                    new_sparse_indices[row_num][i] = flat_idx // dividers[i]\n                    flat_idx = flat_idx % dividers[i]\n            else:\n                new_sparse_indices[row_num] = flat_idx\n\n        return new_sparse_indices, new_shape_np\n\n    @tvm.testing.known_failing_targets(\"vulkan\")\n    def test_sparse_reshape(\n        self,\n        target,\n        dev,\n        ref_res,\n        sparse_indices_np,\n        sparse_values_np,\n        prev_shape_np,\n        new_shape_np,\n        use_dyn,\n    ):\n        if use_dyn:\n            sparse_indices = relay.var(\n                \"sparse_indices\",\n                shape=[relay.Any(), relay.Any()],\n                dtype=str(sparse_indices_np.dtype),\n            )\n            prev_shape = relay.var(\n                \"prev_shape\",\n                shape=[relay.Any()],\n                dtype=str(prev_shape_np.dtype),\n            )\n            new_shape = relay.var(\n                \"new_shape\",\n                shape=[relay.Any()],\n                dtype=str(new_shape_np.dtype),\n            )\n        else:\n            sparse_indices = relay.var(\n                \"sparse_indices\",\n                relay.TensorType(sparse_indices_np.shape, str(sparse_indices_np.dtype)),\n            )\n            prev_shape = relay.var(\n                \"prev_shape\", relay.TensorType(prev_shape_np.shape, str(prev_shape_np.dtype))\n            )\n            new_shape = relay.var(\n                \"new_shape\", relay.TensorType(new_shape_np.shape, str(new_shape_np.dtype))\n            )\n        z = relay.op.sparse_reshape(sparse_indices, prev_shape, new_shape).astuple()\n\n        func = relay.Function([sparse_indices, prev_shape, new_shape], z)\n\n        outputs = run_infer_type(z)\n        new_sparse_indices_infer_type, new_shape_infer_type = (\n            outputs.checked_type.fields[0].dtype,\n            outputs.checked_type.fields[1].dtype,\n        )\n\n        assert new_sparse_indices_infer_type == sparse_indices_np.dtype\n        assert new_shape_infer_type == new_shape_np.dtype\n        verify_func(\n            target,\n            dev,\n            func,\n            [sparse_indices_np, prev_shape_np, new_shape_np],\n            ref_res,\n        )\n\n\nclass TestSegmentSum:\n    data_np, segment_ids_np, num_segments = tvm.testing.parameters(\n        (\n            np.array([5, 1, 7, 2, 3, 4], dtype=np.float32),\n            np.array([0, 0, 1, 1, 0, 1], dtype=np.int32),\n            None,\n        ),\n        (\n            np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float64),\n            np.array([0, 0, 1], dtype=np.int32),\n            None,\n        ),\n        (\n            np.random.random((6, 4, 5)),\n            np.array([2, 0, 1, 0, 3, 2], dtype=np.int64),\n            None,\n        ),\n        (\n            np.array([[[1, 7]], [[3, 8]], [[2, 9]]], dtype=np.float32),\n            np.array([0, 0, 1], dtype=np.int32),\n            None,\n        ),\n        (\n            np.random.random((9, 4, 5, 7)),\n            np.array([5, 0, 1, 0, 3, 6, 8, 7, 7], dtype=np.int64),\n            9,\n        ),\n        (\n            np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float64),\n            np.array([0, 2], dtype=np.int32),\n            4,\n        ),\n        (\n            np.random.random((6, 4, 5)),\n            np.array([0, 0, 1, 5, 5], dtype=np.int32),\n            100,\n        ),\n    )\n\n    use_dyn = tvm.testing.parameter(True, False, ids=[\"dyn\", \"static\"])\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_res(\n        self,\n        data_np: np.ndarray,\n        segment_ids_np: np.ndarray,\n        num_segments: Optional[int],\n    ):\n        \"\"\"\n        This function calculates the expected output of segment_sum operator given the inputs.\n        \"\"\"\n        if not num_segments:\n            num_segments = np.unique(segment_ids_np).shape[0]\n\n        result = np.zeros((num_segments,) + data_np.shape[1:], data_np.dtype)\n        for i, index in enumerate(segment_ids_np):\n            result[index] += data_np[i]\n        return result\n\n    # Optimization can produce tir.atomic_add, not currently supported\n    # on vulkan runtime.\n    @tvm.testing.known_failing_targets(\"vulkan\")\n    def test_segment_sum(\n        self,\n        target,\n        dev,\n        ref_res: np.ndarray,\n        data_np: np.ndarray,\n        segment_ids_np: np.ndarray,\n        num_segments: Optional[int],\n        use_dyn: bool,\n    ):\n        \"\"\"\n        This function verifies the relay output of segment_sum with its expected output.\n        \"\"\"\n        if use_dyn:\n            data = relay.var(\n                \"data\",\n                shape=[relay.Any() for _ in data_np.shape],\n                dtype=str(data_np.dtype),\n            )\n            segment_ids = relay.var(\n                \"segment_ids\",\n                shape=[relay.Any()],\n                dtype=str(segment_ids_np.dtype),\n            )\n        else:\n            data = relay.var(\n                \"data\",\n                relay.TensorType(data_np.shape, str(data_np.dtype)),\n            )\n            segment_ids = relay.var(\n                \"segment_ids\", relay.TensorType(segment_ids_np.shape, str(segment_ids_np.dtype))\n            )\n        z = relay.op.segment_sum(data, segment_ids, num_segments)\n\n        func = relay.Function([data, segment_ids], z)\n        segment_sum_result = run_infer_type(z)\n        assert segment_sum_result.checked_type.dtype == data_np.dtype\n        verify_func(\n            target,\n            dev,\n            func,\n            [data_np, segment_ids_np],\n            ref_res,\n        )\n\n\ndef verify_func(target, dev, func, data, ref_res, rtol=1e-5, atol=1e-7, kinds=[\"vm\"]):\n    assert isinstance(data, list)\n    for kind in kinds:\n        mod = tvm.ir.IRModule.from_expr(func)\n        op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(*data)\n        if isinstance(op_res, tvm.runtime.container.ADT):\n            assert len(op_res) == len(\n                ref_res\n            ), \"Outputs from TVM and Python implementation must be equal \"\n            for op_result, ref_result in zip(op_res, ref_res):\n                tvm.testing.assert_allclose(op_result.numpy(), ref_result, rtol=rtol, atol=atol)\n        else:\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=rtol, atol=atol)\n        relay.backend.te_compiler.get().clear()\n\n\ndef test_adv_index(target, dev, executor_kind):\n    def verify_adv_index(data_shape, index_shapes):\n        dtype = \"float32\"\n        inputs = [relay.var(\"data\", relay.TensorType(data_shape, dtype))]\n        np_data = np.random.uniform(size=data_shape).astype(dtype)\n        np_indices = []\n        for i, index_shape in enumerate(index_shapes):\n            limit = data_shape[i]\n            np_indices.append(np.random.uniform(0, limit - 1, size=index_shape).astype(\"int64\"))\n            inputs.append(relay.var(\"index_{}\".format(i), relay.TensorType(index_shape, \"int64\")))\n        np_out = np_data[tuple(np_indices)]\n        np_args = [np_data] + np_indices\n        out = relay.op.adv_index(inputs)\n\n        func = relay.Function(inputs, out)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            *np_args\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), np_out, rtol=1e-5)\n\n    verify_adv_index((10, 5), [(3, 4), (3, 1)])\n    verify_adv_index((10, 5), [(1, 4), (3, 1)])\n    verify_adv_index(\n        (10, 5),\n        [\n            (2,),\n        ],\n    )\n    verify_adv_index((10, 5, 15), [(1, 2, 1), (1, 2, 7)])\n\n\n# Helper for testing binop functions\nscanops_supported = {\"cumsum\": relay.op.cumsum, \"cumprod\": relay.op.cumprod}\n\n\ndef run_binop_tests(\n    target,\n    dev,\n    executor_kind,\n    binop_type: str,\n    gt_func: Callable[..., np.array],\n    identity_value: int,\n):\n    def assert_relay_scanop(\n        data_np: np.array,\n        np_out: np.array,\n        axis: int = None,\n        out_dtype: str = None,\n        rtol: float = 1e-5,\n        atol: float = 1e-5,\n        exclusive: bool = False,\n    ):\n        inp = relay.var(\"data\", relay.TensorType(data_np.shape, str(data_np.dtype)))\n\n        if binop_type not in scanops_supported.keys():\n            raise ValueError(f\"Unknown function {binop_type}. Options: {scanops_supported.keys()}\")\n        out = scanops_supported[binop_type](inp, axis, out_dtype, exclusive=exclusive)\n        func = relay.Function([inp], out)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data_np\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), np_out, rtol=rtol, atol=atol)\n\n    data = np.array([2, 3, 0])\n    assert_relay_scanop(data, gt_func(data))\n    assert_relay_scanop(data, gt_func(data), out_dtype=\"int64\")\n\n    data = np.random.randn(10, 10)\n    assert_relay_scanop(data, gt_func(data))\n    assert_relay_scanop(data, gt_func(data, axis=0), axis=0)\n    assert_relay_scanop(data, gt_func(data, axis=1), axis=1)\n\n    data = np.random.randn(10, 5, 10).astype(\"float32\")\n    assert_relay_scanop(data, gt_func(data), rtol=1e-4, atol=1e-4)\n    assert_relay_scanop(data, gt_func(data, axis=0), axis=0, rtol=1e-4, atol=1e-4)\n    assert_relay_scanop(data, gt_func(data, axis=1), axis=1, rtol=1e-4, atol=1e-4)\n    assert_relay_scanop(data, gt_func(data, axis=-1), axis=-1, rtol=1e-4, atol=1e-4)\n\n    data = np.random.rand(10) > 0.5\n    data = data.astype(np.int32)\n    assert_relay_scanop(data, gt_func(data, dtype=np.int32))\n    assert_relay_scanop(data, gt_func(data, dtype=\"int64\"), out_dtype=\"int64\")\n\n    # Test exclusivity operations\n    data = np.random.randint(-100, 100, size=(10, 10)).astype(\"int64\")\n    expected_result = np.roll(gt_func(data), 1)\n    expected_result[0] = identity_value\n    assert_relay_scanop(data, expected_result, exclusive=True)\n\n    expected_result = np.roll(gt_func(data, axis=0), 1, axis=0)\n    expected_result[0, :] = identity_value\n    assert_relay_scanop(data, expected_result, exclusive=True, axis=0)\n\n    expected_result = np.roll(gt_func(data, axis=1), 1, axis=1)\n    expected_result[:, 0] = identity_value\n    assert_relay_scanop(data, expected_result, exclusive=True, axis=1)\n\n\n@tvm.testing.parametrize_targets\ndef test_cumsum(target, dev, executor_kind):\n    run_binop_tests(\n        target, dev, executor_kind, binop_type=\"cumsum\", gt_func=np.cumsum, identity_value=0\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_cumprod(target, dev, executor_kind):\n    run_binop_tests(\n        target, dev, executor_kind, binop_type=\"cumprod\", gt_func=np.cumprod, identity_value=1\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_scatter_nd(target, dev, executor_kind):\n    def test_scatter_nd_large_shape():\n        def before():\n            data = relay.const(np.zeros((1, 900, 300), dtype=\"float32\"), dtype=\"float32\")\n            indices = relay.const(np.ones((3, 1, 900, 300), dtype=\"int64\"), dtype=\"int64\")\n            update = relay.const(np.ones((1, 900, 300), dtype=\"float32\"), dtype=\"float32\")\n            b = relay.op.scatter_nd(data, indices, update)\n            return relay.Function(relay.analysis.free_vars(b), b)\n\n        passes = tvm.transform.Sequential(\n            [\n                relay.transform.InferType(),\n                relay.transform.FoldConstant(),\n            ]\n        )\n        before_mod = tvm.IRModule.from_expr(before())\n        with tvm.transform.PassContext(opt_level=3):\n            after_mod = passes(before_mod)\n\n    test_scatter_nd_large_shape()\n\n    def verify_scatter_nd(\n        data_np, indices_np, updates_np, ref_res, mode=\"add\", rtol=1e-5, atol=1e-5\n    ):\n        data = relay.var(\"data\", shape=data_np.shape, dtype=str(data_np.dtype))\n        indices = relay.var(\"indices\", shape=indices_np.shape, dtype=str(indices_np.dtype))\n        updates = relay.var(\"updates\", shape=updates_np.shape, dtype=str(updates_np.dtype))\n\n        out = relay.op.scatter_nd(data, indices, updates, mode)\n        func = relay.Function([data, indices, updates], out)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data_np, indices_np, updates_np\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=rtol, atol=atol)\n\n    def verify_scatter_nd_with_stack(\n        data_np, indices_np, updates_np, ref_res, mode=\"add\", rtol=1e-5, atol=1e-5\n    ):\n        data = relay.var(\"data\", shape=data_np.shape, dtype=str(data_np.dtype))\n        indices_vars = [\n            relay.var(\"ind%d\" % i, shape=v.shape, dtype=str(v.dtype))\n            for i, v in enumerate(indices_np)\n        ]\n        updates = relay.var(\"updates\", shape=updates_np.shape, dtype=str(updates_np.dtype))\n\n        # test if scatter_nd works in case indices are prepared by another Relay operator\n        indices = relay.op.stack(indices_vars, axis=0)\n        out = relay.op.scatter_nd(data, indices, updates, mode)\n        func = relay.Function(\n            [data, updates] + indices_vars,\n            out,\n        )\n\n        fargs = [data_np, updates_np]\n        for a in indices_np:\n            fargs.append(a)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            *fargs\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=rtol, atol=atol)\n\n    for indice_dtype in [\"uint8\", \"uint16\", \"uint32\"]:\n        data = np.zeros((2, 2)).astype(\"int64\")\n        indices = np.array([[1, 1, 0], [0, 1, 0]]).astype(indice_dtype)\n        updates = np.array([2, 3, 0])\n        out = np.array([[0, 0], [2, 3]])\n        verify_scatter_nd(data, indices, updates, out)\n        verify_scatter_nd_with_stack(data, indices, updates, out)\n\n        data = np.zeros((2, 2, 2, 2)).astype(\"int64\")\n        indices = np.array([[0, 1], [1, 1]]).astype(indice_dtype)\n        updates = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])\n        out = np.array([[[[0, 0], [0, 0]], [[1, 2], [3, 4]]], [[[0, 0], [0, 0]], [[5, 6], [7, 8]]]])\n        verify_scatter_nd(data, indices, updates, out)\n        verify_scatter_nd_with_stack(data, indices, updates, out)\n\n        indices = np.array([[1, 0, 0]]).astype(indice_dtype)\n        updates = np.reshape(np.arange(1560 * 3), (3, 1560)).astype(\"float32\")\n        shape = (2, 1560)\n        data = np.zeros(shape).astype(\"float32\")\n        out = data.copy()\n        out[1, :] += updates[0, :]\n        out[0, :] += updates[1, :]\n        out[0, :] += updates[2, :]\n        verify_scatter_nd(data, indices, updates, out, mode=\"add\")\n        verify_scatter_nd_with_stack(data, indices, updates, out)\n\n        for mode in [\"add\", \"update\"]:\n            indices = np.stack((np.random.randint(2, size=5), np.random.randint(7, size=5))).astype(\n                indice_dtype\n            )\n            updates = np.ones((5, 3)).astype(\"float64\")\n            shape = (2, 7, 3)\n            data = np.random.random(shape).astype(\"float64\")\n            out = data.copy()\n            for i in range(indices.shape[1]):\n                for j in range(updates.shape[1]):\n                    if mode == \"add\":\n                        out[indices[0, i], indices[1, i], j] += updates[i, j]\n                    elif mode == \"update\":\n                        out[indices[0, i], indices[1, i], j] = updates[i, j]\n            verify_scatter_nd(data, indices, updates, out, mode)\n            verify_scatter_nd_with_stack(data, indices, updates, out, mode)\n\n\ndef test_unique(target, dev):\n    def calc_numpy_unique(data, is_sorted=False):\n        uniq, index, inverse, counts = np.unique(\n            data, return_index=True, return_inverse=True, return_counts=True\n        )\n        num_uniq = np.array([len(uniq)]).astype(\"int32\")\n        if not is_sorted:\n            order = np.argsort(index)\n            reverse_order = np.argsort(order)\n            uniq = uniq[order].astype(data.dtype)\n            inverse = np.array([reverse_order[i] for i in inverse]).astype(\"int32\")\n            counts = counts[order].astype(\"int32\")\n            # In unsorted case, need to sort the index of first occurence\n            index = np.sort(index)\n        return [\n            uniq.astype(data.dtype),\n            index.astype(\"int32\"),\n            inverse.astype(\"int32\"),\n            num_uniq,\n            counts,\n        ]\n\n    def verify_unique(n, dtype, is_dyn=False, is_sorted=False, return_counts=False):\n        if is_dyn:\n            x = relay.var(\"x\", relay.TensorType([relay.Any()], dtype))\n        else:\n            x = relay.var(\"x\", relay.TensorType([n], dtype))\n        outs = relay.unique(x, is_sorted, return_counts)\n        outs = outs.astuple()\n        func = relay.Function([x], outs)\n        x_data = np.random.randint(50, size=n).astype(dtype)\n\n        if is_dyn:\n            backend = \"vm\"\n        else:\n            backend = \"graph\"\n\n        mod = tvm.ir.IRModule.from_expr(func)\n        tvm_res = relay.create_executor(backend, mod=mod, device=dev, target=target).evaluate()(\n            x_data\n        )  # unique, indices, inverse_indices, num_unique, (counts)\n        np_res = calc_numpy_unique(\n            x_data, is_sorted\n        )  # unique, indices, inverse_indices, num_unique, counts\n        num_unique = np_res[3][0]\n\n        # num_unique\n        assert num_unique == tvm_res[3].numpy()[0]\n        # unique\n        tvm.testing.assert_allclose(tvm_res[0].numpy()[:num_unique], np_res[0], rtol=1e-5)\n        # indices\n        tvm.testing.assert_allclose(tvm_res[1].numpy()[:num_unique], np_res[1], rtol=1e-5)\n        # inverse_indices\n        tvm.testing.assert_allclose(tvm_res[2].numpy(), np_res[2], rtol=1e-5)\n        # counts\n        if return_counts:\n            tvm.testing.assert_allclose(tvm_res[4].numpy()[:num_unique], np_res[4], rtol=1e-5)\n\n    for dtype in [\"int32\", \"int64\"]:\n        for i in range(8):\n            is_dyn, is_sorted, return_counts = bool(i & 1), bool(i & 2), bool(i & 4)\n            verify_unique(10, dtype, is_dyn, is_sorted, return_counts)\n\n\nclass TestSTFT:\n    (\n        data_np,\n        n_fft,\n        hop_length,\n        win_length,\n        window_np,\n        normalized,\n        onesided,\n    ) = tvm.testing.parameters(\n        (\n            np.array([[1, 2, 3, 4, 5, 6]], dtype=np.float32),\n            3,\n            3,\n            3,\n            np.array([4, 3, 2], dtype=np.int32),\n            False,\n            True,\n        ),\n        (\n            np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 5, 7, 8, 5, 6, 7, 3, 2]], dtype=np.float32),\n            2,\n            1,\n            2,\n            np.array([1, 3], dtype=np.int32),\n            False,\n            True,\n        ),\n        (\n            np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 5, 7, 8, 5, 6, 7, 3, 2]], dtype=np.float32),\n            2,\n            1,\n            2,\n            np.array([1, 3], dtype=np.int32),\n            True,\n            True,\n        ),\n        (\n            np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 5, 7, 8, 5, 6, 7, 3, 2]], dtype=np.float32),\n            2,\n            1,\n            2,\n            np.array([1, 3], dtype=np.int32),\n            False,\n            False,\n        ),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_res(\n        self,\n        data_np: np.ndarray,\n        n_fft: int,\n        hop_length: int,\n        win_length: int,\n        window_np,\n        normalized,\n        onesided,\n    ):\n        \"\"\"\n        This function calculates the expected output of segment_sum operator given the inputs.\n        \"\"\"\n\n        def pad_window(window_np, n_fft):\n            shape = window_np.shape[-1]\n            lpad = int((n_fft - shape) // 2)\n            lengths = [(0, 0)] * len(window_np.shape)\n            lengths[-1] = (lpad, int(n_fft - shape - lpad))\n            if lpad < 0:\n                print(\"ERROR Padding\")\n            return np.pad(window_np, lengths, mode=\"constant\")\n\n        import math\n\n        if not onesided:\n            n_rows = n_fft\n        else:\n            n_rows = n_fft // 2 + 1\n        if window_np is None:\n            window_np = np.ones(win_length, dtype=np.int32)\n        window_np = pad_window(window_np, n_fft)\n\n        n_cols = (data_np.shape[-1] - n_fft) // hop_length + 1\n        np_result = np.zeros((data_np.shape[0], n_rows, n_cols, 2))\n\n        for batch in range(data_np.shape[0]):\n            for w in range(n_rows):\n                for m in range(n_cols):\n                    for k in range(n_fft):\n                        np_result[batch][w][m][0] += (\n                            window_np[k]\n                            * data_np[batch][m * hop_length + k]\n                            * math.cos(2 * math.pi * w * k / n_fft)\n                        )\n                        np_result[batch][w][m][1] -= (\n                            window_np[k]\n                            * data_np[batch][m * hop_length + k]\n                            * math.sin(2 * math.pi * w * k / n_fft)\n                        )\n                    if normalized:\n                        np_result[batch][w][m][0] /= math.sqrt(n_fft)\n                        np_result[batch][w][m][1] /= math.sqrt(n_fft)\n        return np_result\n\n    use_dyn = tvm.testing.parameter(True, False, ids=[\"dyn\", \"static\"])\n\n    @tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\n    def test_stft(\n        self,\n        target,\n        dev,\n        ref_res: np.ndarray,\n        data_np: np.ndarray,\n        n_fft: int,\n        hop_length: int,\n        win_length: int,\n        window_np: np.ndarray,\n        normalized: bool,\n        onesided: bool,\n        use_dyn,\n    ):\n        if use_dyn:\n            data = relay.var(\n                \"data\",\n                relay.TensorType([relay.Any(), relay.Any()], str(data_np.dtype)),\n            )\n            window = relay.var(\n                \"window\",\n                relay.TensorType([relay.Any()], str(window_np.dtype)),\n            )\n            backends = [\"vm\"]\n        else:\n            data = relay.var(\n                \"data\",\n                relay.TensorType(data_np.shape, str(data_np.dtype)),\n            )\n            window = relay.var(\n                \"window\",\n                relay.TensorType(window_np.shape, str(window_np.dtype)),\n            )\n            backends = [\"graph\", \"vm\"]\n\n        z = relay.op.stft(data, n_fft, hop_length, win_length, window, normalized, onesided)\n        func = relay.Function([data, window], z)\n        verify_func(\n            target, dev, func, [data_np, window_np], ref_res, rtol=1e-3, atol=1e-3, kinds=backends\n        )\n\n\ndef test_trilu(target=\"llvm\", dev=tvm.cpu()):\n    def verify_trilu(data_shape, upper=True, k=0):\n        data = relay.var(\"data\", relay.TensorType(data_shape, \"float32\"))\n        y = relay.trilu(data, k, upper)\n        mod = tvm.ir.IRModule.from_expr(y)\n\n        data_np = np.random.normal(size=data_shape).astype(\"float32\")\n        tvm_res = (\n            relay.create_executor(\"graph\", mod=mod, device=dev, target=target)\n            .evaluate()(data_np)\n            .numpy()\n        )\n        if upper:\n            np_res = np.triu(data_np, k)\n        else:\n            np_res = np.tril(data_np, k)\n        tvm.testing.assert_allclose(tvm_res, np_res)\n\n    # Test upper and lower triangle\n    verify_trilu((3, 3), True, 0)\n    verify_trilu((3, 3), False, 0)\n    # Test larger matrices with offset.\n    verify_trilu((6, 6), True, 1)\n    verify_trilu((6, 6), False, 2)\n    verify_trilu((6, 6), False, -2)\n    # Test batch size\n    verify_trilu((8, 6, 6), False, -2)\n\n\ndef test_trilu_shape_i64():\n    data_x = np.ones((2, 1), dtype=\"int32\")\n\n    x = relay.var(\"x\", shape=[2, 1], dtype=\"float32\")\n    v0 = relay.broadcast_to(x, shape=relay.const([2, 1], dtype=\"int64\"))\n    v2 = relay.add(relay.const([[1.0]]), v0)\n    v3 = relay.trilu(v0, k=0)\n\n    f = relay.Function([x], relay.Tuple([v2, v3]))\n    tvm_res = relay.create_executor(\"graph\", device=tvm.cpu(), target=\"llvm\").evaluate(f)(data_x)\n\n    np_res = (\n        np.array([[2.0], [2.0]], dtype=np.float32),\n        np.array([[1.0], [0.0]], dtype=np.float32),\n    )\n\n    tvm.testing.assert_allclose(tvm_res[0].numpy(), np_res[0])\n    tvm.testing.assert_allclose(tvm_res[1].numpy(), np_res[1])\n\n\ndef test_trilu_reduce():\n    data_i0 = np.ones((2, 2), dtype=\"int32\")\n    k = 0\n\n    i0 = relay.var(\"i0\", shape=[2, 2], dtype=\"int32\")\n    i1 = relay.var(\"i1\", shape=(), dtype=\"int64\")\n    v0 = relay.trilu(i0, i1)\n    v1 = relay.argmin(v0, axis=[0])\n    f = relay.Function([i0, i1], v1)\n    tvm_res = (\n        relay.create_executor(\"graph\", device=tvm.cpu(), target=\"llvm\")\n        .evaluate(f)(data_i0, k)\n        .numpy()\n    )\n\n    np_res = np.triu(data_i0, k).argmin(axis=0)\n    tvm.testing.assert_allclose(tvm_res, np_res)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level4.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport numpy as np\nimport numpy.random\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay, te\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_binary_op():\n    def check_binary_op(opfunc, ref):\n        n = te.size_var(\"n\")\n        t1 = relay.TensorType((5, n, 5))\n        t2 = relay.TensorType((n, 1))\n        x = relay.var(\"x\", t1)\n        y = relay.var(\"y\", t2)\n        z = opfunc(x, y)\n        # test printer\n        assert (\"{}(%x, %y)\".format(z.op.name)) in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == t1\n\n        if ref is not None:\n            t1 = relay.TensorType((5, 10, 5))\n            t2 = relay.TensorType((5, 10, 5))\n            x = relay.var(\"x\", t1)\n            y = relay.var(\"y\", t2)\n            z = opfunc(x, y)\n            x_data = np.random.rand(5, 10, 5).astype(t1.dtype)\n            y_data = np.random.rand(5, 10, 5).astype(t2.dtype)\n            ref_res = ref(x_data, y_data)\n            func = relay.Function([x, y], z)\n\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data, y_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    for opfunc, ref in [(relay.power, np.power)]:\n        check_binary_op(opfunc, ref)\n\n\n@tvm.testing.uses_gpu\ndef test_cmp_type():\n    for op, ref in (\n        (relay.greater, np.greater),\n        (relay.greater_equal, np.greater_equal),\n        (relay.less, np.less),\n        (relay.less_equal, np.less_equal),\n        (relay.equal, np.equal),\n        (relay.not_equal, np.not_equal),\n    ):\n        x = relay.var(\"x\", relay.TensorType((10, 4), \"float32\"))\n        y = relay.var(\"y\", relay.TensorType((5, 10, 1), \"float32\"))\n        z = op(x, y)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((5, 10, 4), \"bool\")\n\n        if ref is not None:\n            x_shape = (10, 4)\n            y_shape = (5, 10, 1)\n            t1 = relay.TensorType(x_shape)\n            t2 = relay.TensorType(y_shape)\n            x = relay.var(\"x\", t1)\n            y = relay.var(\"y\", t2)\n            z = op(x, y)\n            x_data = np.random.rand(*x_shape).astype(t1.dtype)\n            y_data = np.random.rand(*y_shape).astype(t2.dtype)\n            ref_res = ref(x_data, y_data)\n            func = relay.Function([x, y], z)\n\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data, y_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_binary_int_broadcast_1():\n    for op, ref in [(relay.right_shift, np.right_shift), (relay.left_shift, np.left_shift)]:\n        x = relay.var(\"x\", relay.TensorType((10, 4), \"int32\"))\n        y = relay.var(\"y\", relay.TensorType((5, 10, 1), \"int32\"))\n        z = op(x, y)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((5, 10, 4), \"int32\")\n\n        if ref is not None:\n            x_shape = (10, 4)\n            y_shape = (5, 10, 1)\n            t1 = relay.TensorType(x_shape, \"int32\")\n            t2 = relay.TensorType(y_shape, \"int32\")\n            x_data = np.random.randint(1, 10000, size=(x_shape)).astype(t1.dtype)\n            y_data = np.random.randint(1, 31, size=(y_shape)).astype(t2.dtype)\n            func = relay.Function([x, y], z)\n            ref_res = ref(x_data, y_data)\n\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data, y_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_binary_int_broadcast_2():\n    for op, ref in [(relay.maximum, np.maximum), (relay.minimum, np.minimum), (relay.mod, np.mod)]:\n        x = relay.var(\"x\", relay.TensorType((10, 4), \"int32\"))\n        y = relay.var(\"y\", relay.TensorType((5, 10, 1), \"int32\"))\n        z = op(x, y)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType((5, 10, 4), \"int32\")\n\n        if ref is not None:\n            x_shape = (10, 4)\n            y_shape = (5, 10, 1)\n            t1 = relay.TensorType(x_shape, \"int32\")\n            t2 = relay.TensorType(y_shape, \"int32\")\n            x_data = np.random.randint(1, 10000, size=(x_shape)).astype(t1.dtype)\n            y_data = np.random.randint(1, 10000, size=(y_shape)).astype(t2.dtype)\n            func = relay.Function([x, y], z)\n            ref_res = ref(x_data, y_data)\n\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                    x_data, y_data\n                )\n                tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n\n@tvm.testing.uses_gpu\ndef test_where(executor_kind):\n    def run(func, inputs, ref_res):\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                *inputs\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    def verify(x_np, y_np, cond_np):\n        ref_res = np.where(cond_np, x_np, y_np)\n\n        args = []\n        args_np = []\n        vs = []\n\n        cond = relay.var(\"cond\", relay.TensorType(cond_np.shape, \"bool\"))\n\n        args.append(cond)\n        args_np.append(cond_np)\n\n        for v_name, v_np in [(\"x\", x_np), (\"y\", y_np)]:\n            if len(v_np.shape) == 0:\n                v = relay.const(v_np.item())\n            else:\n                v = relay.var(v_name, relay.TensorType(v_np.shape, dtype))\n                args.append(v)\n                args_np.append(v_np)\n            vs.append(v)\n\n        z = relay.where(cond, vs[0], vs[1])\n\n        func = relay.Function(args, z)\n\n        run(func, args_np, ref_res)\n\n    dtype = \"float32\"\n\n    x_np = np.random.uniform(size=(3, 4)).astype(dtype)\n    y_np = np.random.uniform(size=(3, 4)).astype(dtype)\n    cond_np = np.random.uniform(low=-1, high=1, size=(3, 4)) > 0\n\n    verify(x_np, y_np, cond_np)\n\n    x_np = np.array(1.0, dtype)\n    y_np = np.array(-1.0, dtype)\n    cond_np = np.array([1, 0, 1], dtype=bool)\n\n    verify(x_np, y_np, cond_np)\n\n    x_np = np.arange(10).astype(dtype)\n    y_np = 10 * x_np\n    cond_np = x_np < 5\n\n    verify(x_np, y_np, cond_np)\n\n    x_np = np.array([[1, 2], [3, 4]], dtype)\n    y_np = np.array([[5, 6], [7, 8]], dtype)\n    cond_np = np.array([[1], [0]], dtype=bool)\n\n    verify(x_np, y_np, cond_np)\n    verify(x_np, y_np, cond_np.T)\n\n    x_np = np.random.randn(1, 12, 8, 8).astype(dtype)\n    y_np = np.array(-1.0, dtype)\n    cond_np = np.random.randn(1, 1, 8, 8) > 0\n\n    verify(x_np, y_np, cond_np)\n\n    x_np, y_np = np.ogrid[:3, :4]\n    cond_np = np.where(x_np < y_np, x_np, 10 + y_np).astype(bool)\n\n    verify(x_np.astype(dtype), y_np.astype(dtype), cond_np)\n\n\ndef _with_keepdims(func):\n    def _wrapper(data, axis=None, keepdims=False):\n        if not keepdims:\n            return func(data, axis=axis)\n        else:\n            if axis is not None:\n                axis = axis if isinstance(axis, int) else axis[0]\n                out_shape = list(data.shape)\n                out_shape[axis] = 1\n            else:\n                out_shape = [1 for _ in range(len(data.shape))]\n            return func(data, axis=axis).reshape(out_shape)\n\n    return _wrapper\n\n\ndef _np_log_sum_exp(x, axis, keepdims=False):\n    max_x = np.max(x, axis=axis, keepdims=True)\n    x = np.log(np.sum(np.exp(x - max_x), axis=axis, keepdims=True))\n    x = x + max_x\n    if not keepdims:\n        x = np.squeeze(x, axis=axis)\n    return x\n\n\ndef _unbiased_relay_wrapper(f):\n    def _unbiased_func(x, axis=None, keepdims=False, exclude=False):\n        return f(x, axis=axis, keepdims=keepdims, exclude=exclude, unbiased=True)\n\n    return _unbiased_func\n\n\ndef _unbiased_np_wrapper(f):\n    def _unbiased_func(a, axis=None, dtype=None, keepdims=None):\n        return f(a, axis=axis, dtype=dtype, ddof=1, keepdims=keepdims)\n\n    return _unbiased_func\n\n\nclass TestReduceFunctions:\n    funcs = {\n        \"sum\": (relay.sum, np.sum),\n        \"max\": (relay.max, np.max),\n        \"min\": (relay.min, np.min),\n        \"mean\": (relay.mean, np.mean),\n        \"var\": (relay.variance, np.var),\n        \"unbiased_var\": (_unbiased_relay_wrapper(relay.variance), _unbiased_np_wrapper(np.var)),\n        \"std\": (relay.std, np.std),\n        \"unbiased_std\": (_unbiased_relay_wrapper(relay.std), _unbiased_np_wrapper(np.std)),\n        \"prod\": (relay.prod, np.prod),\n        \"all\": (relay.all, np.all),\n        \"any\": (relay.any, np.any),\n        \"logsumexp\": (relay.logsumexp, _np_log_sum_exp),\n        \"argmin\": (relay.argmin, _with_keepdims(np.argmin)),\n        \"argmax\": (relay.argmax, _with_keepdims(np.argmax)),\n    }\n    relay_func, ref_func = tvm.testing.parameters(\n        *funcs.values(),\n        ids=list(funcs),\n    )\n\n    d1, d2, d3, d4 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\"), te.var(\"d4\")\n\n    data, axis, keepdims, exclude, output = tvm.testing.parameters(\n        ((d1, d2, d3, d4), None, False, False, ()),\n        ((d1, d2, d3, d4), 2, True, False, (d1, d2, 1, d4)),\n        ((d1, d2, d3, d4), 0, True, False, (1, d2, d3, d4)),\n        ((d1, d2, d3), 1, True, False, (d1, 1, d3)),\n        ((d1, d2, d3), 0, True, False, (1, d2, d3)),\n        ((d1, d2, d3), None, True, False, (1, 1, 1)),\n        ((d1, d2, d3), (0, 1), True, False, (1, 1, d3)),\n        ((2, 3, 4), 1, True, False, (2, 1, 4)),\n        ((2, 3, 4), (1,), True, False, (2, 1, 4)),\n        ((2, 3, 4), -1, True, False, (2, 3, 1)),\n        ((2, 3, 4), (0, 1, 2), False, False, ()),\n        ((4, 4, 3), None, False, False, ()),\n        ((4, 4, 3), (0, 2), False, False, (4,)),\n        ((128, 24, 128), (0, 1), False, False, (128,)),\n        ((128, 24, 128), (0, 2), False, False, (24,)),\n        ((128, 24, 128), (0, 1), True, False, (1, 1, 128)),\n        ((128, 24, 128), (0, 2), True, False, (1, 24, 1)),\n    )\n\n    def test_reduce(\n        self,\n        target,\n        dev,\n        relay_func,\n        ref_func,\n        executor_kind,\n        data,\n        axis,\n        keepdims,\n        exclude,\n        output,\n    ):\n        dtype = \"bool\" if ref_func in [np.all, np.any] else \"float32\"\n        out_type = \"int32\" if relay_func in [relay.argmin, relay.argmax] else dtype\n\n        target = tvm.target.Target(target)\n        if target.kind.name == \"vulkan\" and dtype == \"bool\":\n            pytest.xfail(\"Known failing test on vulkan runtime\")\n\n        x = relay.var(\"x\", relay.TensorType(data, dtype))\n        if relay_func == relay.logsumexp:\n            z = relay_func(x, axis, keepdims)\n        else:\n            z = relay_func(x, axis, keepdims, exclude)\n        zz = run_infer_type(z)\n        if axis:\n            assert \"axis=\" in z.astext()\n        if keepdims:\n            assert \"keepdims=\" in z.astext()\n        if exclude:\n            assert \"exclude=\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(output, out_type)\n\n        if all(isinstance(v, tvm.tir.Var) == 1 for v in data):\n            return\n\n        func = relay.Function([x], z)\n        x_data = (\n            np.random.choice([True, False], size=data)\n            if ref_func in [np.all]\n            else np.random.uniform(size=data).astype(dtype)\n        )\n\n        if ref_func in [np.sum]:\n            ref_res = ref_func(x_data + 0, axis=axis, dtype=dtype, keepdims=keepdims)\n        elif ref_func in [np.max, np.min, np.mean, np.prod]:\n            ref_res = ref_func(x_data + 0, axis=axis, keepdims=keepdims)\n        else:  # argmin/argmax\n            if axis and not isinstance(axis, int) and len(axis) > 1:\n                return\n            ref_res = ref_func(x_data + 0, axis=axis, keepdims=keepdims)\n\n        op_res1 = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_argmin_argmax_get_last_elements():\n    def get_test_case(shape, gt_func, test_argmin=False):\n        total_ele = np.product(shape)\n        arr = np.zeros(total_ele)\n        target_value = -1 if test_argmin else 1\n        arr[: total_ele // 3] = target_value\n        np.random.shuffle(arr)\n        arr = arr.reshape(shape)\n        ans = gt_func(np.flip(arr))\n        return arr, len(arr) - ans - 1\n\n    funcs_and_gt_funcs = [(relay.argmax, np.argmax), (relay.argmin, np.argmin)]\n    lengths = [5, 10, 15]\n    for func, gt_func in funcs_and_gt_funcs:\n        for shape in lengths:\n            x_in = relay.var(\"x_in\", shape=[shape])\n            output = func(x_in, select_last_index=True)\n            arr, ans = get_test_case(shape, gt_func, test_argmin=func == relay.argmin)\n\n            mod = tvm.IRModule.from_expr(output)\n            for target, dev in tvm.testing.enabled_targets():\n                op_res = relay.create_executor(\n                    \"graph\", mod=mod, device=dev, target=target\n                ).evaluate()(arr)\n                assert op_res.numpy().item() == ans\n\n\ndef verify_mean_var_std(executor_kind, funcs, shape, axis, keepdims, dtype=\"float32\"):\n    test_func = funcs[0]\n    ref_func = funcs[1]\n\n    x = relay.var(\"x\", relay.TensorType(shape, dtype))\n    z = test_func(x, axis, keepdims)\n    func = relay.Function([x], z.astuple())\n    x_data = np.random.uniform(size=shape).astype(\"float32\")\n    ref_mean = np.mean(x_data, axis=axis, dtype=\"float32\", keepdims=keepdims).astype(dtype)\n    ref_res = ref_func(x_data, axis=axis, dtype=\"float32\", keepdims=keepdims).astype(dtype)\n\n    for target, dev in tvm.testing.enabled_targets():\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data.astype(dtype)\n        )\n        # FP16 is always a little less accurate.\n        if dtype == \"float16\":\n            rtol, atol = (1e-2, 1e-2)\n        else:\n            rtol, atol = (1e-5, 1e-5)\n        tvm.testing.assert_allclose(op_res[0].numpy(), ref_mean, rtol=rtol, atol=atol)\n        tvm.testing.assert_allclose(op_res[1].numpy(), ref_res, rtol=rtol, atol=atol)\n\n\n@tvm.testing.uses_gpu\ndef test_mean_var_std(executor_kind):\n    for func in [[relay.mean_variance, np.var], [relay.mean_std, np.std]]:\n        verify_mean_var_std(executor_kind, func, (2, 3, 4), 1, True)\n        verify_mean_var_std(executor_kind, func, (2, 3, 4), (1,), True)\n        verify_mean_var_std(executor_kind, func, (2, 3, 4), -1, True)\n        verify_mean_var_std(executor_kind, func, (2, 3, 4), (0, 1, 2), False)\n        verify_mean_var_std(executor_kind, func, (4, 4, 3), None, False)\n        verify_mean_var_std(executor_kind, func, (4, 4, 3), (0, 2), False)\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), (0, 1), False)\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), (0, 2), False)\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), (0, 1), True)\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), (0, 2), True)\n        # Test FP16 reduction with large indices.\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), (0, 2), True, \"float16\")\n        verify_mean_var_std(executor_kind, func, (128, 24, 128), None, False, \"float16\")\n\n\n@tvm.testing.uses_gpu\ndef test_strided_slice():\n    def verify(\n        dshape,\n        begin,\n        end,\n        strides,\n        output,\n        axes=None,\n        slice_mode=\"end\",\n        test_ref=True,\n        dtype=\"int32\",\n        unknown_dim_value=10,\n    ):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        ndim = len(dshape)\n        begin = begin if begin else [0] * ndim\n        end = end if end else list(dshape)\n\n        # Resolve unknown dimensions to create test case:\n        dshape = list(dshape)\n        for i, d in enumerate(dshape):\n            if not isinstance(d, int):\n                dshape[i] = unknown_dim_value\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.strided_slice_python(\n            x_data,\n            begin,\n            end,\n            strides,\n            slice_mode,\n            axes=axes,\n        )\n\n        if strides:\n            z = relay.strided_slice(\n                x, begin=begin, end=end, strides=strides, axes=axes, slice_mode=slice_mode\n            )\n        else:\n            z = relay.strided_slice(x, begin=begin, end=end, axes=axes, slice_mode=slice_mode)\n        func = relay.Function([x], z)\n\n        func = run_infer_type(func)\n        text = func.astext()\n        assert \"begin=\" in text\n        assert \"end=\" in text\n\n        if output:\n            assert func.body.checked_type == relay.ty.TensorType(output, \"float32\")\n\n        if not test_ref:\n            return\n        for target, dev in tvm.testing.enabled_targets():\n            # Need VM to run tests with non-static dimensions\n            op_res = relay.create_executor(\"vm\", device=dev, target=target).evaluate(func)(x_data)\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    verify((1, 3, 10, 10), [0, 0, 0, 0], [-1, 3, 10, 10], [1], (0, 3, 10, 10), dtype=\"int64\")\n    verify(\n        (1, 224, 224, 3),\n        [0, 20, 20, 0],\n        [1, 140, 140, 3],\n        [1, 1, 1, 1],\n        (1, 120, 120, 3),\n        dtype=\"int64\",\n    )\n\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], (1, 3, 3), dtype=\"int16\")\n    verify((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], (3, 1, 2))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], (1, 4, 3))\n    verify((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], (1, 2, 3))\n\n    # Test backwards slicing.\n    verify((3, 4, 3), [-1, -1, -1], [-5, -5, -5], [-1, -1, -1], (3, 4, 3))\n    # Test slicing with overlarge indices.\n    verify((3, 4, 3), [0, 0, 0], [np.iinfo(np.int32).max] * 3, [1, 1, 1], (3, 4, 3))\n    # Test slice mode.\n    verify(\n        (3, 4, 3), [1, 0, 0], [3, -1, 3], [1, 1, 1], (2, 4, 3), slice_mode=\"size\", test_ref=False\n    )\n\n    verify((3, 4, 3), [1, 0, 0], [-1, 2, 3], [1, 1, 1], (2, 2, 3), slice_mode=\"size\", test_ref=True)\n    verify((3, 4, 3), [1], [4], None, None, axes=[1])\n\n    # Test Any dims for simple cases\n    verify((3, relay.Any()), [0], [1], [1], None, axes=[1], unknown_dim_value=10)\n    verify((relay.Any(), 3), [0], [1], [1], None, axes=[1], unknown_dim_value=10)\n    verify(\n        (relay.Any(), relay.Any(), relay.Any()),\n        [0, 1, 2],\n        [5, 5, 5],\n        [1, 2, 1],\n        None,\n        unknown_dim_value=10,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_strided_slice():\n    def verify(\n        dshape,\n        begin,\n        end,\n        strides,\n        output,\n        axes=None,\n        ishape=None,\n        slice_mode=\"end\",\n        test_ref=True,\n        dtype=\"int32\",\n    ):\n        ndim = len(dshape)\n        begin = begin if begin else [0] * ndim\n        end = end if end else list(dshape)\n\n        # target numpy result\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        ref_res = tvm.topi.testing.strided_slice_python(\n            x_data, begin, end, strides, slice_mode, axes=axes\n        )\n\n        if ishape is None:\n            ishape = (relay.Any(),) * ndim\n\n        x = relay.var(\"x\", relay.TensorType(ishape, \"float32\"))\n        if strides:\n            z = relay.strided_slice(\n                x, begin=begin, end=end, strides=strides, axes=axes, slice_mode=slice_mode\n            )\n        else:\n            z = relay.strided_slice(x, begin=begin, end=end, axes=axes, slice_mode=slice_mode)\n        func = relay.Function([x], z)\n\n        func = run_infer_type(func)\n        text = func.astext()\n        assert \"begin=\" in text\n        assert \"end=\" in text\n\n        if not test_ref:\n            return\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    verify(\n        (1, 224, 224, 3),\n        [0, 20, 20, 0],\n        [1, 140, 140, 3],\n        [1, 1, 1, 1],\n        (1, 120, 120, 3),\n        dtype=\"int64\",\n    )\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], (1, 3, 3), dtype=\"int16\")\n    verify((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], (3, 1, 2))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 4], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], (1, 4, 3))\n    verify((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], (1, 2, 3))\n    verify(\n        (3, 4, 3), [1, 0, 0], [3, -1, 3], [1, 1, 1], (2, 4, 3), slice_mode=\"size\", test_ref=False\n    )\n    verify((3, 4, 3), [1, 0, 0], [-1, 2, 3], [1, 1, 1], (2, 2, 3), slice_mode=\"size\", test_ref=True)\n    verify(\n        (3, 4, 3, 2),\n        [1, 0],\n        [3, 1],\n        [1, 1],\n        None,\n        axes=[1, 3],\n        ishape=(relay.Any(), 4, relay.Any(), 2),\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_strided_set():\n    def verify(dshape, begin, end, strides, vshape, test_ref=True):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        v = relay.var(\"v\", relay.TensorType(vshape, \"float32\"))\n        begin_c = relay.const(begin, dtype=\"int32\")\n        end_c = relay.const(end, dtype=\"int32\")\n        if strides:\n            strides_c = relay.const(strides, dtype=\"int32\")\n            z = relay.strided_set(x, v, begin=begin_c, end=end_c, strides=strides_c)\n        else:\n            z = relay.strided_set(x, v, begin=begin_c, end=end_c)\n        func = relay.Function([x, v], z)\n        func = run_infer_type(func)\n        text = func.astext()\n        assert \"strided_set\" in text\n        print(text)\n        assert func.body.checked_type == relay.ty.TensorType(dshape, \"float32\")\n        if not test_ref:\n            return\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        v_data = np.random.uniform(size=vshape).astype(\"float32\")\n        ref_res = tvm.topi.testing.strided_set_python(x_data, v_data, begin, end, strides)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                x_data, v_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n    verify((3, 4, 16), [0, 0, 0], [4, -5, 4], [1, -1, 2], (3, 1, 2))\n    verify((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], (3, 1, 2))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], (1, 3, 3))\n    verify((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], (1, 4, 3))\n    verify((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2], (1, 2, 2))\n    verify((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], (1, 2, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1], [4, 4, 3], None, (2, 3, 3))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level5.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level5 operator test cases.\n\"\"\"\nimport math\nimport platform\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay, te\nfrom tvm.relay.testing import run_infer_type\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\ndef test_resize1d_infer_type():\n    n, c, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, w), \"int8\"))\n    tw = te.var(\"tw\")\n    z = relay.image.resize1d(x, (tw,))\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, tw), \"int8\")\n\n    x = relay.var(\"x\", relay.TensorType((n, c, w), \"int8\"))\n    z = relay.image.resize1d(x, (200,), None, \"NCW\", \"linear\", \"align_corners\")\n    assert \"size=\" in z.astext()\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, 200), \"int8\")\n\n\nclass TestResize1D:\n    interpolate_method = tvm.testing.parameter(\"nearest_neighbor\", \"linear\", \"cubic\")\n    coord_trans = tvm.testing.parameter(\"asymmetric\", \"align_corners\", \"half_pixel\")\n\n    layout = tvm.testing.parameter(\"NWC\", \"NCW\")\n    dshape, scale = tvm.testing.parameters(\n        ((1, 4, 4), 2),\n        ((2, 8, 17), 3),\n        ((2, 8, 17), 3),\n        ((3, 4, 5), 5),\n    )\n\n    def test_resize(\n        self, target, dev, executor_kind, dshape, scale, interpolate_method, layout, coord_trans\n    ):\n        target_kind = tvm.target.Target(target).kind.name\n        if (\n            target_kind == \"vulkan\"\n            and dshape == (3, 4, 5)\n            and scale == 5\n            and interpolate_method == \"nearest_neighbor\"\n            and coord_trans == \"align_corners\"\n        ):\n            pytest.xfail(\"Known failing case for these parameters\")\n\n        if layout == \"NWC\":\n            size = (dshape[1] * scale,)\n        else:\n            size = (dshape[2] * scale,)\n\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.resize1d_python(\n            x_data, (scale,), layout, interpolate_method, coord_trans\n        )\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.image.resize1d(\n            x, size, None, layout, interpolate_method, coordinate_transformation_mode=coord_trans\n        )\n        assert \"size=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-3, atol=1e-4)\n\n\ndef test_resize2d_infer_type():\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"int8\"))\n    th, tw = te.var(\"th\"), te.var(\"tw\")\n    z = relay.image.resize2d(x, (th, tw))\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, th, tw), \"int8\")\n\n    x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"int8\"))\n    z = relay.image.resize2d(x, (100, 200), None, \"NCHW\", \"linear\", \"align_corners\")\n    assert \"size=\" in z.astext()\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, 100, 200), \"int8\")\n\n\nclass TestResize2D:\n    interpolate_method = tvm.testing.parameter(\"nearest_neighbor\", \"linear\", \"cubic\")\n    coord_trans = tvm.testing.parameter(\"asymmetric\", \"align_corners\", \"half_pixel\")\n\n    layout = tvm.testing.parameter(\"NHWC\", \"NCHW\")\n\n    dshape, scale = tvm.testing.parameters(\n        ((1, 4, 4, 4), 2),\n        ((2, 8, 17, 20), 3),\n        ((2, 8, 17, 20), 3),\n        ((3, 4, 5, 6), 5),\n    )\n\n    def test_resize(\n        self, target, dev, executor_kind, dshape, scale, interpolate_method, layout, coord_trans\n    ):\n        target_kind = tvm.target.Target(target).kind.name\n        if (\n            target_kind == \"vulkan\"\n            and dshape == (3, 4, 5, 6)\n            and scale == 5\n            and interpolate_method == \"nearest_neighbor\"\n            and coord_trans == \"align_corners\"\n        ):\n            pytest.xfail(\"Known failing case for these parameters\")\n\n        if layout == \"NHWC\":\n            size = (dshape[1] * scale, dshape[2] * scale)\n        else:\n            size = (dshape[2] * scale, dshape[3] * scale)\n\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.resize2d_python(\n            x_data, (scale, scale), layout, interpolate_method, coord_trans\n        )\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.image.resize2d(\n            x, size, None, layout, interpolate_method, coordinate_transformation_mode=coord_trans\n        )\n        assert \"size=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-3, atol=1e-4)\n\n\ndef test_resize3d_infer_type():\n    n, c, d, h, w = (\n        te.size_var(\"n\"),\n        te.size_var(\"c\"),\n        te.size_var(\"d\"),\n        te.size_var(\"h\"),\n        te.size_var(\"w\"),\n    )\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"int8\"))\n    td, th, tw = te.var(\"td\"), te.var(\"th\"), te.var(\"tw\")\n    z = relay.image.resize3d(x, (td, th, tw))\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, td, th, tw), \"int8\")\n\n    x = relay.var(\"x\", relay.TensorType((n, c, d, h, w), \"int8\"))\n    z = relay.image.resize3d(x, (10, 10, 20), None, \"NCDHW\", \"linear\", \"align_corners\")\n    assert \"size=\" in z.astext()\n    zz = run_infer_type(z)\n    assert zz.checked_type == relay.TensorType((n, c, 10, 10, 20), \"int8\")\n\n\nclass TestResize3D:\n    interpolate_method = tvm.testing.parameter(\"nearest_neighbor\", \"linear\", \"cubic\")\n    coord_trans = tvm.testing.parameter(\"asymmetric\", \"align_corners\", \"half_pixel\")\n\n    layout = tvm.testing.parameter(\"NDHWC\", \"NCDHW\")\n\n    dshape, scale = tvm.testing.parameters(\n        ((1, 4, 4, 4, 4), 2),\n    )\n\n    def test_resize(\n        self, target, dev, executor_kind, dshape, scale, interpolate_method, layout, coord_trans\n    ):\n        if layout == \"NDHWC\":\n            size = (dshape[1] * scale, dshape[2] * scale, dshape[3] * scale)\n        else:\n            size = (dshape[2] * scale, dshape[3] * scale, dshape[4] * scale)\n\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        ref_res = tvm.topi.testing.resize3d_python(\n            x_data, (scale, scale, scale), layout, interpolate_method, coord_trans\n        )\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.image.resize3d(x, size, None, layout, interpolate_method, coord_trans)\n        assert \"size=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            x_data\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4, atol=1e-6)\n\n\nclass TestCropAndResize:\n    interpolate_method = tvm.testing.parameter(\"bilinear\", \"nearest_neighbor\")\n    layout = tvm.testing.parameter(\"NHWC\", \"NCHW\")\n\n    @pytest.mark.skipif(\n        platform.machine() == \"aarch64\",\n        reason=\"Currently failing on AArch64 - see https://github.com/apache/tvm/issues/10673\",\n    )\n    def test_crop_and_resize(self, target, dev, executor_kind, layout, interpolate_method):\n        target_kind = tvm.target.Target(target).kind.name\n        if (\n            target_kind == \"vulkan\"\n            and layout == \"NHWC\"\n            and interpolate_method == \"nearest_neighbor\"\n        ):\n            pytest.xfail(\"Known failing case for these parameters\")\n\n        extrapolation_value = 0.0\n\n        if layout == \"NHWC\":\n            img_shape = (10, 224, 224, 3)\n            boxes = np.array([[0.1, 0.2, 0.8, 0.7], [0.2, 0, 1, 0.6]]).astype(\"float32\")\n            box_indices = np.array([1, 0]).astype(\"int32\")\n            crop_size = np.array([20, 30]).astype(\"int32\")\n        elif layout == \"NCHW\":\n            img_shape = (5, 3, 255, 255)\n            boxes = np.array([[0, 0, 1, 1], [0.2, 0.1, 1, 0.9]]).astype(\"float32\")\n            box_indices = np.array([0, 1]).astype(\"int32\")\n            crop_size = np.array([30, 30]).astype(\"int32\")\n        else:\n            raise ValueError(f\"Unknown layout: {layout}\")\n\n        image_data = np.random.uniform(size=img_shape).astype(\"float32\")\n\n        ref_res = tvm.topi.testing.crop_and_resize_python(\n            image_data,\n            boxes,\n            box_indices,\n            crop_size,\n            layout,\n            interpolate_method,\n            extrapolation_value,\n        )\n\n        img = relay.var(\"img\", relay.TensorType(img_shape, \"float32\"))\n        bx = relay.var(\"bx\", relay.TensorType(boxes.shape, \"float32\"))\n        bx_idx = relay.var(\"bx_idx\", relay.TensorType(box_indices.shape, \"int32\"))\n\n        z = relay.image.crop_and_resize(\n            img, bx, bx_idx, list(crop_size), layout, interpolate_method, extrapolation_value\n        )\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([img, bx, bx_idx], z)\n\n        op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            image_data, boxes, box_indices\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-3, atol=1e-04)\n\n\n@tvm.testing.uses_gpu\ndef test_multibox_prior(executor_kind):\n    def get_ref_result(\n        dshape, sizes=(1.0,), ratios=(1.0,), steps=(-1.0, -1.0), offsets=(0.5, 0.5), clip=True\n    ):\n        in_height = dshape[2]\n        in_width = dshape[3]\n        num_sizes = len(sizes)\n        num_ratios = len(ratios)\n        size_ratio_concat = sizes + ratios\n        steps_h = steps[0] if steps[0] > 0 else 1.0 / in_height\n        steps_w = steps[1] if steps[1] > 0 else 1.0 / in_width\n        offset_h = offsets[0]\n        offset_w = offsets[1]\n\n        oshape = (1, in_height * in_width * (num_sizes + num_ratios - 1), 4)\n        dtype = \"float32\"\n        np_out = np.zeros(oshape).astype(dtype)\n\n        for i in range(in_height):\n            center_h = (i + offset_h) * steps_h\n            for j in range(in_width):\n                center_w = (j + offset_w) * steps_w\n                for k in range(num_sizes + num_ratios - 1):\n                    w = (\n                        size_ratio_concat[k] * in_height / in_width / 2.0\n                        if k < num_sizes\n                        else size_ratio_concat[0]\n                        * in_height\n                        / in_width\n                        * math.sqrt(size_ratio_concat[k + 1])\n                        / 2.0\n                    )\n                    h = (\n                        size_ratio_concat[k] / 2.0\n                        if k < num_sizes\n                        else size_ratio_concat[0] / math.sqrt(size_ratio_concat[k + 1]) / 2.0\n                    )\n                    count = (\n                        i * in_width * (num_sizes + num_ratios - 1)\n                        + j * (num_sizes + num_ratios - 1)\n                        + k\n                    )\n                    np_out[0][count][0] = center_w - w\n                    np_out[0][count][1] = center_h - h\n                    np_out[0][count][2] = center_w + w\n                    np_out[0][count][3] = center_h + h\n        if clip:\n            np_out = np.clip(np_out, 0, 1)\n\n        return np_out\n\n    def verify_multibox_prior(\n        x,\n        dshape,\n        ref_res,\n        sizes=(1.0,),\n        ratios=(1.0,),\n        steps=(-1.0, -1.0),\n        offsets=(0.5, 0.5),\n        clip=True,\n        check_size=False,\n        check_type_only=False,\n    ):\n\n        z = relay.vision.multibox_prior(x, sizes, ratios, steps, offsets, clip)\n        zz = run_infer_type(z)\n        if check_size:\n            assert \"sizes=\" in z.astext()\n        assert zz.checked_type == relay.TensorType(\n            (1, dshape[2] * dshape[3] * (len(sizes) + len(ratios) - 1), 4), \"float32\"\n        )\n\n        if check_type_only:\n            return\n\n        data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n        func = relay.Function([x], z)\n        func = run_infer_type(func)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    sizes = (0.3, 1.5, 0.7)\n    ratios = (1.3, 2.4)\n    steps = (2.0, 1.5)\n    offsets = (0.2, 0.3)\n    dshape = (1, 3, 56, 56)\n    ref_res = get_ref_result(dshape, sizes, ratios, steps, offsets)\n    x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n    verify_multibox_prior(x, dshape, ref_res, sizes, ratios, steps, offsets, check_size=True)\n    y = relay.var(\"y\", relay.TensorType((te.size_var(\"n\"), 3, 56, 56), \"float32\"))\n    verify_multibox_prior(\n        x, dshape, ref_res, sizes, ratios, steps, offsets, check_size=True, check_type_only=True\n    )\n\n    dshape = (1, 24, 32, 32)\n    ref_res = get_ref_result(dshape, clip=False)\n    x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n    verify_multibox_prior(x, dshape, ref_res, clip=False)\n    y = relay.var(\"y\", relay.TensorType((te.size_var(\"n\"), 24, 32, 32), \"float32\"))\n    verify_multibox_prior(x, dshape, ref_res, clip=False, check_type_only=True)\n\n\n@tvm.testing.uses_gpu\ndef test_get_valid_counts():\n    def verify_get_valid_counts(dshape, score_threshold, id_index, score_index):\n        dtype = \"float32\"\n        batch_size, num_anchor, elem_length = dshape\n        np_data = np.random.uniform(low=-2, high=2, size=dshape).astype(dtype)\n        np_out1 = np.zeros(shape=(batch_size,))\n        np_out2 = np.zeros(shape=dshape).astype(dtype)\n        np_out3 = np.zeros(shape=(batch_size, num_anchor))\n        for i in range(batch_size):\n            np_out1[i] = 0\n            inter_idx = 0\n            for j in range(num_anchor):\n                score = np_data[i, j, score_index]\n                if score > score_threshold and (id_index < 0 or np_data[i, j, id_index] >= 0):\n                    for k in range(elem_length):\n                        np_out2[i, inter_idx, k] = np_data[i, j, k]\n                    np_out1[i] += 1\n                    np_out3[i, inter_idx] = j\n                    inter_idx += 1\n                if j >= np_out1[i]:\n                    for k in range(elem_length):\n                        np_out2[i, j, k] = -1.0\n                    np_out3[i, j] = -1\n\n        x = relay.var(\"x\", relay.ty.TensorType(dshape, dtype))\n        z = relay.vision.get_valid_counts(x, score_threshold, id_index, score_index)\n        assert \"score_threshold\" in z.astext()\n        func = relay.Function([x], z.astuple())\n        func = run_infer_type(func)\n        for target, dev in tvm.testing.enabled_targets():\n            out = relay.create_executor(\"vm\", device=dev, target=target).evaluate(func)(np_data)\n\n            tvm.testing.assert_allclose(out[0].numpy(), np_out1, rtol=1e-3, atol=1e-04)\n            tvm.testing.assert_allclose(out[1].numpy(), np_out2, rtol=1e-3, atol=1e-04)\n            tvm.testing.assert_allclose(out[2].numpy(), np_out3, rtol=1e-3, atol=1e-04)\n\n    verify_get_valid_counts((1, 2500, 6), 0, 0, 1)\n    verify_get_valid_counts((1, 2500, 5), -1, -1, 0)\n    verify_get_valid_counts((3, 1000, 6), 0.55, 1, 0)\n    verify_get_valid_counts((16, 500, 5), 0.95, -1, 0)\n\n\n@tvm.testing.uses_gpu\ndef test_non_max_suppression(executor_kind):\n    def verify_nms(\n        x0_data,\n        x1_data,\n        x2_data,\n        x3_data,\n        dshape,\n        ref_res,\n        ref_indices_res,\n        iou_threshold=0.5,\n        force_suppress=False,\n        top_k=-1,\n        check_type_only=False,\n    ):\n        x0 = relay.var(\"x0\", relay.ty.TensorType(dshape, \"float32\"))\n        x1 = relay.var(\"x1\", relay.ty.TensorType((dshape[0],), \"int32\"))\n        x2 = relay.var(\"x2\", relay.ty.TensorType((dshape[0], dshape[1]), \"int32\"))\n        x3 = relay.var(\"x3\", relay.ty.TensorType((), \"int32\"))\n        z = relay.vision.non_max_suppression(\n            x0,\n            x1,\n            x2,\n            x3,\n            iou_threshold=iou_threshold,\n            force_suppress=force_suppress,\n            top_k=top_k,\n            return_indices=False,\n        )\n        z_indices = relay.vision.non_max_suppression(\n            x0,\n            x1,\n            x2,\n            x3,\n            iou_threshold=iou_threshold,\n            force_suppress=force_suppress,\n            top_k=top_k,\n            return_indices=True,\n        )\n        if isinstance(z_indices, relay.expr.TupleWrapper):\n            z_indices = z_indices.astuple()\n        zz = run_infer_type(z)\n        zz_indices = run_infer_type(z_indices)\n        assert zz.checked_type == relay.ty.TensorType(dshape, \"float32\")\n        assert zz_indices.checked_type == relay.ty.TupleType(\n            [\n                relay.ty.TensorType((dshape[0], dshape[1]), \"int32\"),\n                relay.ty.TensorType((dshape[0], 1), \"int32\"),\n            ]\n        )\n\n        if check_type_only:\n            return\n\n        func = relay.Function([x0, x1, x2, x3], z)\n        func = run_infer_type(func)\n        func_indices = relay.Function([x0, x1, x2, x3], z_indices)\n        func_indices = run_infer_type(func_indices)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x0_data, x1_data, x2_data, x3_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n            op_indices_res = relay.create_executor(\n                executor_kind, device=dev, target=target\n            ).evaluate(func_indices)(x0_data, x1_data, x2_data, x3_data)\n            tvm.testing.assert_allclose(op_indices_res[0].numpy(), ref_indices_res, rtol=1e-5)\n\n    np_data = np.array(\n        [\n            [\n                [0, 0.8, 1, 20, 25, 45],\n                [1, 0.7, 30, 60, 50, 80],\n                [0, 0.4, 4, 21, 19, 40],\n                [2, 0.9, 35, 61, 52, 79],\n                [1, 0.5, 100, 60, 70, 110],\n            ]\n        ]\n    ).astype(\"float32\")\n    np_valid_count = np.array([4]).astype(\"int32\")\n    np_indices = np.array([[0, 1, 3, 4, -1]]).astype(\"int32\")\n    np_max_output_size = -1\n\n    np_result = np.array(\n        [\n            [\n                [2, 0.9, 35, 61, 52, 79],\n                [0, 0.8, 1, 20, 25, 45],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n            ]\n        ]\n    )\n    np_indices_result = np.array([[4, 0, -1, -1, -1]])\n    num_anchors = 5\n\n    dshape = (te.size_var(\"n\"), num_anchors, 6)\n    verify_nms(\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_max_output_size,\n        dshape,\n        np_result,\n        np_indices_result,\n        force_suppress=True,\n        top_k=2,\n        check_type_only=True,\n    )\n    dshape = (1, num_anchors, 6)\n    verify_nms(\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_max_output_size,\n        dshape,\n        np_result,\n        np_indices_result,\n        force_suppress=True,\n        top_k=2,\n        check_type_only=False,\n    )\n\n    np_result = np.array(\n        [\n            [\n                [2, 0.9, 35, 61, 52, 79],\n                [0, 0.8, 1, 20, 25, 45],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n            ]\n        ]\n    )\n    np_indices_result = np.array([[4, 0, -1, -1, -1]])\n    np_max_output_size = 2\n    dshape = (te.size_var(\"n\"), num_anchors, 6)\n    verify_nms(\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_max_output_size,\n        dshape,\n        np_result,\n        np_indices_result,\n        check_type_only=True,\n    )\n    dshape = (1, num_anchors, 6)\n    verify_nms(\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_max_output_size,\n        dshape,\n        np_result,\n        np_indices_result,\n        top_k=2,\n    )\n\n    np_data = np.array(\n        [\n            [\n                [0, 0.8, 1, 20, 25, 45, 1, 2, 3, 4],\n                [1, 0.7, 30, 60, 50, 80, 5, 6, 7, 8],\n                [0, 0.4, 4, 21, 19, 40, 9, 10, 11, 12],\n                [2, 0.9, 35, 61, 52, 79, 13, 14, 15, 16],\n                [1, 0.5, 100, 60, 70, 110, 17, 18, 19, 20],\n            ]\n        ]\n    ).astype(\"float32\")\n    np_result = np.array(\n        [\n            [\n                [2, 0.9, 35, 61, 52, 79, 13, 14, 15, 16],\n                [0, 0.8, 1, 20, 25, 45, 1, 2, 3, 4],\n                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],\n            ]\n        ]\n    )\n    dshape = (1, 5, 10)\n    verify_nms(\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_max_output_size,\n        dshape,\n        np_result,\n        np_indices_result,\n        force_suppress=True,\n        top_k=2,\n        check_type_only=False,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_multibox_transform_loc(executor_kind):\n    def test_default_value():\n        num_anchors = 3\n        num_classes = 3\n\n        np_cls_prob = np.array([[[0.2, 0.5, 0.3], [0.25, 0.3, 0.45], [0.7, 0.1, 0.2]]]).astype(\n            \"float32\"\n        )\n        np_loc_preds = np.array(\n            [[0.1, -0.2, 0.3, 0.2, 0.2, 0.4, 0.5, -0.3, 0.7, -0.2, -0.4, -0.8]]\n        ).astype(\"float32\")\n        np_anchors = np.array(\n            [[[-0.1, -0.1, 0.1, 0.1], [-0.2, -0.2, 0.2, 0.2], [1.2, 1.2, 1.5, 1.5]]]\n        ).astype(\"float32\")\n\n        expected_np_out = np.array(\n            [\n                [\n                    [1, 0.69999999, 0, 0, 0.10818365, 0.10008108],\n                    [0, 0.44999999, 1, 1, 1, 1],\n                    [0, 0.30000001, 0, 0, 0.22903419, 0.20435292],\n                ]\n            ]\n        )\n\n        cls_prob = relay.var(\n            \"cls_prob\", relay.ty.TensorType((1, num_anchors, num_classes), \"float32\")\n        )\n        loc_pred = relay.var(\"loc_pred\", relay.ty.TensorType((1, num_anchors * 4), \"float32\"))\n        anchors = relay.var(\"anchors\", relay.ty.TensorType((1, num_anchors, 4), \"float32\"))\n\n        mtl = relay.vision.multibox_transform_loc(\n            cls_prob=cls_prob, loc_pred=loc_pred, anchor=anchors\n        )\n        ret = run_infer_type(mtl.astuple())\n        ref_type = relay.ty.TupleType(\n            tvm.runtime.convert(\n                [\n                    relay.ty.TensorType((1, num_anchors, 6), \"float32\"),\n                    relay.ty.TensorType((1,), \"int\"),\n                ]\n            )\n        )\n\n        assert ret.checked_type == ref_type\n\n        nms = relay.vision.non_max_suppression(mtl[0], mtl[1], mtl[0], return_indices=False)\n        func = relay.Function([cls_prob, loc_pred, anchors], nms)\n        func = run_infer_type(func)\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                np_cls_prob, np_loc_preds, np_anchors\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), expected_np_out, rtol=1e-5)\n\n    def test_threshold():\n        num_anchors = 5\n        num_classes = 5\n        n = te.size_var(\"n\")\n        cls_prob = relay.var(\n            \"cls_prob\", relay.ty.TensorType((n, num_anchors, num_classes), \"float32\")\n        )\n        loc_pred = relay.var(\"loc_pred\", relay.ty.TensorType((n, num_anchors * 4), \"float32\"))\n        anchors = relay.var(\"anchors\", relay.ty.TensorType((1, num_anchors, 4), \"float32\"))\n        threshold = 0.02\n        variances = (0.2, 0.2, 0.3, 0.3)\n\n        ret = relay.vision.multibox_transform_loc(\n            cls_prob=cls_prob,\n            loc_pred=loc_pred,\n            anchor=anchors,\n            threshold=threshold,\n            variances=variances,\n        )\n        ret = run_infer_type(ret.astuple())\n        ref_type = relay.ty.TupleType(\n            tvm.runtime.convert(\n                [\n                    relay.ty.TensorType((n, num_anchors, 6), \"float32\"),\n                    relay.ty.TensorType((n,), \"int\"),\n                ]\n            )\n        )\n        assert ret.checked_type == ref_type\n\n    test_default_value()\n    test_threshold()\n\n\n@tvm.testing.uses_gpu\ndef test_roi_align(executor_kind):\n    def verify_roi_align(\n        data_shape,\n        rois_shape,\n        channel,\n        in_size,\n        pooled_size,\n        spatial_scale,\n        sample_ratio,\n        mode,\n        layout,\n        ref_func,\n    ):\n        data = relay.var(\"data\", relay.ty.TensorType(data_shape, \"float32\"))\n        rois = relay.var(\"rois\", relay.ty.TensorType(rois_shape, \"float32\"))\n        z = relay.vision.roi_align(\n            data,\n            rois,\n            pooled_size=(pooled_size, pooled_size),\n            spatial_scale=spatial_scale,\n            sample_ratio=sample_ratio,\n            mode=mode,\n            layout=layout,\n        )\n        zz = run_infer_type(z)\n\n        num_roi = rois_shape[0]\n\n        if layout == \"NCHW\":\n            assert zz.checked_type == relay.ty.TensorType(\n                (num_roi, channel, pooled_size, pooled_size), \"float32\"\n            )\n        else:\n            assert zz.checked_type == relay.ty.TensorType(\n                (num_roi, pooled_size, pooled_size, channel), \"float32\"\n            )\n\n        func = relay.Function([data, rois], z)\n        func = run_infer_type(func)\n        np_data = np.random.uniform(size=data_shape).astype(\"float32\")\n        np_rois = np.random.uniform(size=rois_shape).astype(\"float32\") * in_size\n        np_rois[:, 0] = np.random.randint(low=0, high=data_shape[0], size=num_roi)\n        ref_res = ref_func(\n            np_data,\n            np_rois,\n            pooled_size=pooled_size,\n            spatial_scale=spatial_scale,\n            sample_ratio=sample_ratio,\n            mode=mode,\n        )\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                np_data, np_rois\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, atol=1e-6, rtol=1e-3)\n\n    def verify_roi_align_nchw(\n        data_shape, rois_shape, pooled_size, spatial_scale, sample_ratio, mode\n    ):\n        _, channel, in_size, _ = data_shape\n        return verify_roi_align(\n            data_shape,\n            rois_shape,\n            channel,\n            in_size,\n            pooled_size,\n            spatial_scale,\n            sample_ratio,\n            mode,\n            \"NCHW\",\n            tvm.topi.testing.roi_align_nchw_python,\n        )\n\n    def verify_roi_align_nhwc(\n        data_shape, rois_shape, pooled_size, spatial_scale, sample_ratio, mode\n    ):\n        _, in_size, _, channel = data_shape\n        return verify_roi_align(\n            data_shape,\n            rois_shape,\n            channel,\n            in_size,\n            pooled_size,\n            spatial_scale,\n            sample_ratio,\n            mode,\n            \"NHWC\",\n            tvm.topi.testing.roi_align_nhwc_python,\n        )\n\n    verify_roi_align_nchw(\n        (1, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=1.0, sample_ratio=-1, mode=\"avg\"\n    )\n    verify_roi_align_nchw(\n        (4, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=0.5, sample_ratio=2, mode=\"avg\"\n    )\n    verify_roi_align_nchw(\n        (1, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=1.0, sample_ratio=-1, mode=\"max\"\n    )\n    verify_roi_align_nchw(\n        (4, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=0.5, sample_ratio=2, mode=\"max\"\n    )\n    verify_roi_align_nhwc(\n        (1, 16, 16, 4), (32, 5), pooled_size=7, spatial_scale=1.0, sample_ratio=-1, mode=\"avg\"\n    )\n    verify_roi_align_nhwc(\n        (4, 16, 16, 4), (32, 5), pooled_size=7, spatial_scale=0.5, sample_ratio=2, mode=\"avg\"\n    )\n    verify_roi_align_nhwc(\n        (1, 16, 16, 4), (32, 5), pooled_size=7, spatial_scale=1.0, sample_ratio=-1, mode=\"max\"\n    )\n    verify_roi_align_nhwc(\n        (4, 16, 16, 4), (32, 5), pooled_size=7, spatial_scale=0.5, sample_ratio=2, mode=\"max\"\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_roi_pool(executor_kind):\n    def verify_roi_pool(data_shape, rois_shape, pooled_size, spatial_scale):\n        data = relay.var(\"data\", relay.ty.TensorType(data_shape, \"float32\"))\n        rois = relay.var(\"rois\", relay.ty.TensorType(rois_shape, \"float32\"))\n        z = relay.vision.roi_pool(\n            data,\n            rois,\n            pooled_size=(pooled_size, pooled_size),\n            spatial_scale=spatial_scale,\n            layout=\"NCHW\",\n        )\n        zz = run_infer_type(z)\n        batch, channel, in_size, _ = data_shape\n        num_roi = rois_shape[0]\n        assert zz.checked_type == relay.ty.TensorType(\n            (num_roi, channel, pooled_size, pooled_size), \"float32\"\n        )\n\n        func = relay.Function([data, rois], z)\n        func = run_infer_type(func)\n        np_data = np.random.uniform(size=data_shape).astype(\"float32\")\n        np_rois = np.random.uniform(size=rois_shape).astype(\"float32\") * in_size\n        np_rois[:, 0] = np.random.randint(low=0, high=batch, size=num_roi).astype(\"float32\")\n        ref_res = tvm.topi.testing.roi_pool_nchw_python(\n            np_data, np_rois, pooled_size=pooled_size, spatial_scale=spatial_scale\n        )\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                np_data, np_rois\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4)\n\n    verify_roi_pool((1, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=1.0)\n    verify_roi_pool((4, 4, 16, 16), (32, 5), pooled_size=7, spatial_scale=0.5)\n\n\n@tvm.testing.uses_gpu\ndef test_proposal(executor_kind):\n    def verify_proposal(np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs):\n        cls_prob = relay.var(\"cls_prob\", relay.ty.TensorType(np_cls_prob.shape, \"float32\"))\n        bbox_pred = relay.var(\"bbox_pred\", relay.ty.TensorType(np_bbox_pred.shape, \"float32\"))\n        im_info = relay.var(\"im_info\", relay.ty.TensorType(np_im_info.shape, \"float32\"))\n        z = relay.vision.proposal(cls_prob, bbox_pred, im_info, **attrs)\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.ty.TensorType(np_out.shape, \"float32\")\n\n        func = relay.Function([cls_prob, bbox_pred, im_info], z)\n        func = run_infer_type(func)\n        for target in [\"llvm\", \"cuda\"]:\n            if not tvm.testing.device_enabled(target):\n                print(\"Skip test because %s is not enabled.\" % target)\n                continue\n            dev = tvm.device(target, 0)\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                np_cls_prob, np_bbox_pred, np_im_info\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), np_out, rtol=1e-4)\n\n    attrs = {\n        \"scales\": (0.5,),\n        \"ratios\": (0.5,),\n        \"feature_stride\": 16,\n        \"iou_loss\": False,\n        \"rpn_min_size\": 16,\n        \"threshold\": 0.7,\n        \"rpn_pre_nms_top_n\": 200,\n        \"rpn_post_nms_top_n\": 4,\n    }\n\n    np_cls_prob = np.array(\n        [\n            [\n                [[0.3, 0.6, 0.2], [0.4, 0.7, 0.5], [0.1, 0.4, 0.3]],\n                [[0.7, 0.5, 0.3], [0.6, 0.4, 0.8], [0.9, 0.2, 0.5]],\n            ]\n        ],\n        dtype=\"float32\",\n    )\n    np_bbox_pred = np.array(\n        [\n            [\n                [[0.5, 1.0, 0.6], [0.8, 1.2, 2.0], [0.9, 1.0, 0.8]],\n                [[0.5, 1.0, 0.7], [0.8, 1.2, 1.6], [2.1, 1.5, 0.7]],\n                [[1.0, 0.5, 0.7], [1.5, 0.9, 1.6], [1.4, 1.5, 0.8]],\n                [[1.0, 0.5, 0.6], [1.5, 0.9, 2.0], [1.8, 1.0, 0.9]],\n            ]\n        ],\n        dtype=\"float32\",\n    )\n    np_im_info = np.array([[48.0, 48.0, 1.0]], dtype=\"float32\")\n    np_out = np.array(\n        [\n            [0.0, 0.0, 2.8451548, 28.38012, 18.154846],\n            [0.0, 0.0, 15.354933, 41.96971, 41.245064],\n            [0.0, 18.019852, 1.0538368, 51.98015, 25.946163],\n            [0.0, 27.320923, -1.266357, 55.0, 24.666357],\n        ],\n        dtype=\"float32\",\n    )\n\n    verify_proposal(np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs)\n\n    np_out = np.array(\n        [\n            [0.0, -5.25, -2.5, 21.75, 19.0],\n            [0.0, 11.25, -2.0, 37.25, 18.5],\n            [0.0, 26.849998, -2.3000002, 53.45, 18.6],\n            [0.0, -4.95, 13.799999, 22.25, 35.5],\n        ],\n        dtype=\"float32\",\n    )\n    attrs[\"iou_loss\"] = True\n    verify_proposal(np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs)\n\n\ndef test_yolo_reorg_infer_shape():\n    def verify_yolo_reorg(shape, stride, out_shape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.vision.yolo_reorg(x, stride=stride)\n        zz = run_infer_type(z)\n        assert \"stride=\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(out_shape, \"float32\")\n\n    n, c, h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n    idxd = tvm.tir.indexdiv\n    verify_yolo_reorg((n, c, 20, 20), 10, (n, c * 10 * 10, 2, 2))\n    verify_yolo_reorg((n, c, h, w), 2, (n, c * 2 * 2, idxd(h, 2), idxd(w, 2)))\n\n\n@tvm.testing.uses_gpu\ndef test_yolo_reorg(executor_kind):\n    def verify_yolo_reorg(shape, stride):\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        ref_res = tvm.topi.testing.reorg_python(x_data, stride)\n\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        z = relay.vision.yolo_reorg(x, stride=stride)\n        zz = run_infer_type(z)\n        assert \"stride=\" in z.astext()\n        assert zz.checked_type == relay.ty.TensorType(ref_res.shape, \"float32\")\n\n        func = relay.Function([x], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    verify_yolo_reorg((1, 100, 20, 20), 10)\n    verify_yolo_reorg((1, 4, 6, 6), 2)\n\n\nclass TestDeformableConv2D:\n    batch, in_channel, size, out_channel, deformable_groups = tvm.testing.parameters(\n        (1, 4, 16, 4, 4),\n        (2, 4, 16, 4, 1),\n    )\n    kernel_size = tvm.testing.parameter((3, 3))\n    groups = tvm.testing.parameter(1, 2)\n    layout = tvm.testing.parameter(\"NCHW\", \"NHWC\")\n    dtype = tvm.testing.parameter(\"float32\")\n\n    @tvm.testing.fixture\n    def data_shape(self, layout, batch, in_channel, size):\n        if layout == \"NCHW\":\n            return (batch, in_channel, size, size)\n        elif layout == \"NHWC\":\n            return (batch, size, size, in_channel)\n\n    @tvm.testing.fixture\n    def kernel_shape(self, layout, in_channel, out_channel, groups, kernel_size):\n        if layout == \"NCHW\":\n            return (out_channel, in_channel // groups, kernel_size[0], kernel_size[1])\n        elif layout == \"NHWC\":\n            return (kernel_size[0], kernel_size[1], in_channel // groups, out_channel)\n\n    @tvm.testing.fixture\n    def out_shape(self, layout, batch, out_channel, size):\n        if layout == \"NCHW\":\n            return (batch, out_channel, size, size)\n        elif layout == \"NHWC\":\n            return (batch, size, size, out_channel)\n\n    @tvm.testing.fixture\n    def offset_shape(self, layout, batch, kernel_size, deformable_groups, out_shape):\n        if layout == \"NCHW\":\n            return (\n                batch,\n                2 * kernel_size[0] * kernel_size[1] * deformable_groups,\n                out_shape[2],\n                out_shape[3],\n            )\n        elif layout == \"NHWC\":\n            return (\n                batch,\n                out_shape[1],\n                out_shape[2],\n                2 * kernel_size[0] * kernel_size[1] * deformable_groups,\n            )\n\n    @tvm.testing.fixture\n    def kernel_layout(self, layout):\n        return {\"NCHW\": \"OIHW\", \"NHWC\": \"HWIO\"}[layout]\n\n    @tvm.testing.fixture\n    def relay_setup(\n        self,\n        dtype,\n        data_shape,\n        layout,\n        kernel_layout,\n        kernel_size,\n        deformable_groups,\n        groups,\n        out_channel,\n    ):\n        data = relay.var(\"data\", shape=data_shape, dtype=dtype)\n        offset = relay.var(\"offset\", dtype=dtype)\n        kernel = relay.var(\"kernel\", dtype=dtype)\n        expr = relay.nn.deformable_conv2d(\n            data,\n            offset,\n            kernel,\n            strides=(1, 1),\n            padding=(1, 1),\n            dilation=(1, 1),\n            data_layout=layout,\n            kernel_layout=kernel_layout,\n            kernel_size=kernel_size,\n            deformable_groups=deformable_groups,\n            groups=groups,\n            channels=out_channel,\n        )\n        func = relay.Function([data, offset, kernel], expr)\n        return expr, func\n\n    def test_infer_type(self, relay_setup, out_shape, offset_shape, kernel_shape):\n        expr, func = relay_setup\n        yy = run_infer_type(expr)\n        assert yy.checked_type == relay.TensorType(out_shape), yy.checked_type\n        assert yy.args[1].checked_type == relay.TensorType(offset_shape), yy.args[1].checked_type\n        assert yy.args[2].checked_type == relay.TensorType(kernel_shape), yy.args[2].checked_type\n\n    # The reference python implementation only supports groups==1.\n    @pytest.mark.parametrize(\"groups\", [1])\n    def test_run(\n        self,\n        target,\n        dev,\n        dtype,\n        executor_kind,\n        data_shape,\n        offset_shape,\n        kernel_shape,\n        relay_setup,\n        deformable_groups,\n        groups,\n        layout,\n    ):\n        target = tvm.target.Target(target)\n        if layout == \"NHWC\" and target.kind.name != \"llvm\":\n            pytest.xfail(\"Can only run NHWC layout on llvm\")\n\n        expr, func = relay_setup\n        data = np.random.uniform(size=data_shape).astype(dtype)\n        offset = np.random.uniform(size=offset_shape).astype(dtype)\n        kernel = np.random.uniform(size=kernel_shape).astype(dtype)\n        if layout == \"NCHW\":\n            ref_res = tvm.topi.testing.deformable_conv2d_nchw_python(\n                data,\n                offset,\n                kernel,\n                stride=(1, 1),\n                padding=(1, 1),\n                dilation=(1, 1),\n                deformable_groups=deformable_groups,\n                groups=groups,\n            )\n        else:\n            ref_res = tvm.topi.testing.deformable_conv2d_nhwc_python(\n                data,\n                offset,\n                kernel,\n                stride=(1, 1),\n                padding=(1, 1),\n                dilation=(1, 1),\n                deformable_groups=deformable_groups,\n                groups=groups,\n            )\n\n        op_res1 = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n            data, offset, kernel\n        )\n        tvm.testing.assert_allclose(op_res1.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_depth_to_space(executor_kind):\n    def verify_depth_to_space(dshape, block_size, layout, mode):\n        if layout == \"NHWC\":\n            out_shape = [\n                dshape[0],\n                dshape[1] * block_size,\n                dshape[2] * block_size,\n                dshape[3] / (block_size * block_size),\n            ]\n        else:\n            out_shape = [\n                dshape[0],\n                dshape[1] / (block_size * block_size),\n                dshape[2] * block_size,\n                dshape[3] * block_size,\n            ]\n\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        if layout == \"NHWC\":\n            x_data = np.transpose(x_data, axes=[0, 3, 1, 2])\n        ref_res = tvm.topi.testing.depth_to_space_python(x_data, block_size, mode=mode)\n        if layout == \"NHWC\":\n            x_data = np.transpose(x_data, axes=[0, 2, 3, 1])\n            ref_res = np.transpose(ref_res, axes=[0, 2, 3, 1])\n\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.nn.depth_to_space(x, block_size, layout, mode)\n        assert \"block_size=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4)\n\n    for layout in [\"NHWC\", \"NCHW\"]:\n        for mode in [\"DCR\", \"CDR\"]:\n            verify_depth_to_space((1, 4, 4, 4), 2, layout, mode)\n\n\n@tvm.testing.uses_gpu\ndef test_space_to_depth(executor_kind):\n    def verify_space_to_depth(dshape, block_size, layout):\n        if layout == \"NHWC\":\n            out_shape = [\n                dshape[0],\n                dshape[1] / block_size,\n                dshape[2] / block_size,\n                dshape[3] * (block_size * block_size),\n            ]\n        else:\n            out_shape = [\n                dshape[0],\n                dshape[1] * (block_size * block_size),\n                dshape[2] / block_size,\n                dshape[3] / block_size,\n            ]\n\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        if layout == \"NHWC\":\n            x_data = np.transpose(x_data, axes=[0, 3, 1, 2])\n        ref_res = tvm.topi.testing.space_to_depth_python(x_data, block_size)\n        if layout == \"NHWC\":\n            x_data = np.transpose(x_data, axes=[0, 2, 3, 1])\n            ref_res = np.transpose(ref_res, axes=[0, 2, 3, 1])\n\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.nn.space_to_depth(x, block_size, layout)\n        assert \"block_size=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4)\n\n    for layout in [\"NHWC\", \"NCHW\"]:\n        verify_space_to_depth((1, 4, 4, 4), 2, layout)\n\n\ndef test_dilation2d_infer_type():\n    # symbolic in batch dimension\n    n, h, w, c = te.var(\"n\"), 224, 224, 10\n    x = relay.var(\"x\", relay.ty.TensorType((n, c, h, w), \"float32\"))\n    kc, kh, kw = 10, 8, 8\n    w = relay.var(\"w\", relay.ty.TensorType((kc, kw, kh), \"float32\"))\n    y = relay.image.dilation2d(\n        x,\n        w,\n        # kernel_size=(3, 3),\n        strides=[1, 1, 1, 1],\n        dilations=[1, 1, 1, 1],\n        padding=[0, 0, 0, 0],\n    )\n    yy = run_infer_type(y)\n    assert yy.checked_type == relay.TensorType((n, 10, 217, 217), \"float32\")\n\n\nclass TestDilation2DRun:\n    data_layout, kernel_layout = tvm.testing.parameters((\"NCHW\", \"IHW\"), (\"NHWC\", \"HWI\"))\n    dtype = tvm.testing.parameter(\"float32\")\n\n    config = tvm.testing.parameter(\n        dict(\n            image=[[[[0.1], [0.2]], [[0.3], [0.4]]]],\n            kernel=[[[0.4], [0.3]], [[0.1], [0.0]]],\n            out=[[[[0.5]]]],\n        ),\n        dict(\n            image=[[[[0.1], [0.2]], [[0.3], [0.4]]]],\n            kernel=[[[0.4], [0.3]], [[0.1], [0.0]]],\n            out=[[[[0.5], [0.6]], [[0.7], [0.8]]]],\n            padding=[0, 0, 1, 1],\n        ),\n        dict(\n            image=[[[[0.1, 0.2, 0.0], [0.2, 0.3, 0.1]], [[0.3, 0.4, 0.2], [0.4, 0.5, 0.3]]]],\n            kernel=[[[0.4, 0.5, 0.3], [0.3, 0.4, 0.2]], [[0.1, 0.2, 0.0], [0.0, 0.1, -0.1]]],\n            out=[[[[0.5, 0.7, 0.3], [0.6, 0.8, 0.4]], [[0.7, 0.9, 0.5], [0.8, 1.0, 0.6]]]],\n            padding=[0, 0, 1, 1],\n        ),\n        dict(\n            image=[[[[0.1], [0.2]], [[0.3], [0.4]]], [[[0.2], [0.3]], [[0.4], [0.5]]]],\n            kernel=[[[0.4], [0.3]], [[0.1], [0.0]]],\n            out=[[[[0.5], [0.6]], [[0.7], [0.8]]], [[[0.6], [0.7]], [[0.8], [0.9]]]],\n            padding=[0, 0, 1, 1],\n        ),\n        dict(\n            image=[[[[0.1], [0.2]], [[0.3], [0.4]]]],\n            kernel=[[[0.4], [0.3]]],\n            out=[[[[0.5]], [[0.7]]]],\n        ),\n        dict(\n            image=[[[[0.1], [0.2], [0.3]], [[0.4], [0.5], [0.6]], [[0.7], [0.8], [0.9]]]],\n            kernel=[[[0.4], [0.3]], [[0.1], [0.2]]],\n            out=[[[[0.7], [0.8], [0.6]], [[1.0], [1.1], [0.9]], [[0.8], [0.9], [0.9]]]],\n            padding=[1, 1],\n            dilations=[2, 2],\n        ),\n        dict(\n            image=[\n                [\n                    [[0.1], [0.2], [0.3], [0.4]],\n                    [[0.5], [0.6], [0.7], [0.8]],\n                    [[0.9], [1.0], [1.1], [1.2]],\n                ]\n            ],\n            kernel=[[[0.4], [0.3]], [[0.1], [0.2]]],\n            out=[[[[0.8], [1.0]], [[1.2], [1.4]]]],\n            strides=[1, 2],\n        ),\n    )\n\n    @tvm.testing.fixture\n    def test_case(self, config, data_layout, dtype):\n        indata = np.array(config[\"image\"], dtype=dtype)\n        kernel = np.array(config[\"kernel\"], dtype=dtype)\n        out = np.array(config[\"out\"], dtype=dtype)\n\n        if data_layout == \"NHWC\":\n            pass\n        elif data_layout == \"NCHW\":\n            indata = indata.transpose([0, 3, 1, 2])\n            kernel = kernel.transpose([2, 0, 1])\n            out = out.transpose([0, 3, 1, 2])\n        else:\n            raise ValueError(f\"Unsupported layout '{data_layout}'\")\n\n        return indata, kernel, out\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_dilation2d(\n        self,\n        target,\n        dev,\n        test_case,\n        dtype,\n        config,\n        data_layout,\n        kernel_layout,\n    ):\n        strides = config.get(\"strides\", [1, 1])\n        padding = config.get(\"padding\", [0, 0])\n        dilations = config.get(\"dilations\", [1, 1])\n\n        indata, kernel, out = test_case\n\n        x = relay.var(\"x\", shape=indata.shape, dtype=dtype)\n        w = relay.var(\"w\", shape=kernel.shape, dtype=dtype)\n        y = relay.image.dilation2d(\n            x,\n            w,\n            strides=strides,\n            dilations=dilations,\n            padding=padding,\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        func = relay.Function([x, w], y)\n\n        op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n            indata, kernel\n        )\n        tvm.testing.assert_allclose(op_res.numpy(), out, rtol=1e-5, atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_affine_grid(executor_kind):\n    def verify_affine_grid(num_batch, target_shape):\n        dtype = \"float32\"\n        data_shape = (num_batch, 2, 3)\n        data = relay.var(\"data\", relay.ty.TensorType(data_shape, dtype))\n        y = relay.image.affine_grid(data, target_shape)\n        yy = run_infer_type(y)\n        assert yy.checked_type == relay.ty.TensorType(\n            (num_batch, len(target_shape), *target_shape), dtype\n        )\n\n        func = relay.Function([data], y)\n        data_np = np.random.uniform(size=data_shape).astype(dtype)\n        ref_res = tvm.topi.testing.affine_grid_python(data_np, target_shape)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                data_np\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    verify_affine_grid(1, (16, 32))\n    verify_affine_grid(4, (16, 32))\n\n\n@tvm.testing.uses_gpu\ndef test_grid_sample(executor_kind):\n    def verify_grid_sample(\n        data_shape, grid_shape, method=\"bilinear\", padding_mode=\"zeros\", align_corners=True\n    ):\n        dtype = \"float32\"\n        data = relay.var(\"data\", relay.ty.TensorType(data_shape, dtype))\n        grid = relay.var(\"grid\", relay.ty.TensorType(grid_shape, dtype))\n\n        if len(data_shape) == 4:\n            layout = \"NCHW\"\n            batch, channel, _, _ = data_shape\n            _, _, out_height, out_width = grid_shape\n            tensor_type = relay.TensorType((batch, channel, out_height, out_width), dtype)\n        else:  # len(data_shape) == 5:\n            layout = \"NCDHW\"\n            batch, channel, _, _, _ = data_shape\n            _, _, out_depth, out_height, out_width = grid_shape\n            tensor_type = relay.TensorType(\n                (batch, channel, out_depth, out_height, out_width), dtype\n            )\n\n        y = relay.image.grid_sample(\n            data,\n            grid,\n            method=method,\n            layout=layout,\n            padding_mode=padding_mode,\n            align_corners=align_corners,\n        )\n        yy = run_infer_type(y)\n        assert yy.checked_type == tensor_type\n        func = relay.Function([data, grid], y)\n\n        data_np = np.random.uniform(size=data_shape).astype(dtype)\n        grid_np = np.random.uniform(size=grid_shape, low=-1.5, high=1.5).astype(dtype)\n        ref_res = tvm.topi.testing.grid_sample_python(\n            data_np, grid_np, method, layout, padding_mode, align_corners\n        )\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                data_np, grid_np\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5, atol=1e-5)\n\n    methods = [\"nearest\", \"bilinear\", \"bicubic\"]\n    padding_modes = [\"zeros\", \"border\", \"reflection\"]\n    align_corners = [True, False]\n\n    data_2D_shape = (4, 4, 8, 8)\n    grid_2D_shape = (4, 2, 16, 16)\n    # choosing smaller sizes to be testable on weaker GPUs\n    data_3D_shape = (4, 4, 4, 4, 4)\n    grid_3D_shape = (4, 3, 8, 8, 8)\n\n    for _method in methods:\n        for _padding in padding_modes:\n            for _align in align_corners:\n                verify_grid_sample(data_2D_shape, grid_2D_shape, _method, _padding, _align)\n\n                # 3D \"bicubic\"(tricubic) is not supported in pytorch\n                if _method != \"bicubic\":\n                    verify_grid_sample(data_3D_shape, grid_3D_shape, _method, _padding, _align)\n\n\n@tvm.testing.uses_gpu\ndef test_space_to_batch_nd(executor_kind):\n    def verify_space_to_batch_nd(dshape, block_shape, paddings):\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        pad_before, pad_after = map(list, zip(*paddings))\n        ref_res = tvm.topi.testing.space_to_batch_nd_python(\n            x_data, block_shape, pad_before, pad_after\n        )\n\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.nn.space_to_batch_nd(x, block_shape, paddings)\n        assert \"block_shape=\" in z.astext()\n        assert \"paddings=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4)\n\n    verify_space_to_batch_nd([3, 3, 2, 1], [3], [[0, 0]])\n    verify_space_to_batch_nd([2, 2, 4, 1], [2, 2], [[0, 0], [2, 0]])\n\n\n@tvm.testing.uses_gpu\ndef test_batch_to_space_nd(executor_kind):\n    def verify_batch_to_space_nd(dshape, block_shape, crops):\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        crop_begin_list, crop_end_list = map(list, zip(*crops))\n        ref_res = tvm.topi.testing.batch_to_space_nd_python(\n            x_data, block_shape, crop_begin_list, crop_end_list\n        )\n\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        z = relay.nn.batch_to_space_nd(x, block_shape, crops)\n        assert \"block_shape=\" in z.astext()\n        assert \"crops=\" in z.astext()\n        zz = run_infer_type(z)\n        assert zz.checked_type == relay.TensorType(ref_res.shape, \"float32\")\n        func = relay.Function([x], z)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-4)\n\n    verify_batch_to_space_nd([4, 1, 1, 3], [2, 2], [[0, 0], [0, 0]])\n    verify_batch_to_space_nd([8, 1, 3, 1], [2, 2], [[0, 0], [2, 0]])\n\n\n@tvm.testing.uses_gpu\ndef test_all_class_non_max_suppression(executor_kind):\n    def verify_all_class_non_max_suppression(\n        boxes_np,\n        scores_np,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        expected_indices,\n    ):\n        boxes = relay.var(\"boxes\", relay.ty.TensorType(boxes_np.shape, \"float32\"))\n        scores = relay.var(\"scores\", relay.ty.TensorType(scores_np.shape, \"float32\"))\n\n        out = relay.vision.all_class_non_max_suppression(\n            boxes,\n            scores,\n            max_output_boxes_per_class,\n            iou_threshold,\n            score_threshold,\n        )\n\n        func = relay.Function([boxes, scores], out.astuple())\n        func = run_infer_type(func)\n\n        for target, dev in tvm.testing.enabled_targets():\n            selected_indices, num_detections = relay.create_executor(\n                executor_kind, device=dev, target=target\n            ).evaluate(func)(boxes_np, scores_np)\n            tvm_res = selected_indices.numpy()[: num_detections.numpy()[0]]\n            np.testing.assert_equal(tvm_res, expected_indices)\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.0, 0.0, 0.5, 0.5],\n                [0.5, 0.5, 0.9, 0.9],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.5, 0.5, 0.95, 0.95],\n                [0.5, 0.5, 0.96, 0.96],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n        ]\n    ).astype(\"float32\")\n\n    scores = np.array(\n        [\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n        ]\n    ).astype(\"float32\")\n\n    max_output_boxes_per_class = 2\n    iou_threshold = 0.8\n    score_threshold = 0.0\n\n    expected = np.array(\n        [[0, 0, 4], [0, 0, 2], [0, 1, 4], [0, 1, 2], [1, 0, 4], [1, 0, 1], [1, 1, 4], [1, 1, 1]]\n    )\n\n    verify_all_class_non_max_suppression(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, expected\n    )\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 1.0, 1.0],\n                [0.0, 0.1, 1.0, 1.1],\n                [0.0, -0.1, 1.0, 0.9],\n                [0.0, 10.0, 1.0, 11.0],\n                [0.0, 10.1, 1.0, 11.1],\n                [0.0, 100.0, 1.0, 101.0],\n            ]\n        ]\n    ).astype(np.float32)\n    scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\n    max_output_boxes_per_class = 3\n    iou_threshold = 0.5\n    score_threshold = 0.4\n\n    expected = np.array([[0, 0, 3], [0, 0, 0]])\n\n    verify_all_class_non_max_suppression(\n        boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, expected\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_level6.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level6 operator test cases.\n\"\"\"\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.topi.testing import searchsorted_ref\nimport tvm.testing\n\nexecutor_kind = tvm.testing.parameter(\"graph\", \"vm\")\n\n\n@tvm.testing.uses_gpu\ndef test_sort():\n    def verify_sort(shape, axis, is_ascend, is_dyn=False, in_dtype=\"float32\"):\n        if is_dyn:\n            x = relay.var(\"x\", relay.TensorType([relay.Any()] * len(shape), in_dtype))\n        else:\n            x = relay.var(\"x\", relay.TensorType(shape, in_dtype))\n        z = relay.sort(x, axis=axis, is_ascend=is_ascend)\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(size=shape).astype(in_dtype)\n        if is_ascend:\n            ref_res = np.sort(x_data, axis=axis)\n        else:\n            ref_res = -np.sort(-x_data, axis=axis)\n\n        if is_dyn:\n            backend = \"vm\"\n        else:\n            backend = \"graph\"\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(backend, mod=mod, device=dev, target=target).evaluate()(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n    for is_dyn in [False, True]:\n        verify_sort((2, 3, 4), axis=0, is_ascend=False, is_dyn=is_dyn)\n        verify_sort((1, 4, 6), axis=1, is_ascend=True, is_dyn=is_dyn)\n        verify_sort((3, 5, 6), axis=-1, is_ascend=False, is_dyn=is_dyn)\n        verify_sort((3, 2000, 6), axis=1, is_ascend=False, is_dyn=is_dyn)\n        verify_sort((1, 122640), axis=1, is_ascend=False, is_dyn=is_dyn)\n        verify_sort((1, 122640), axis=1, is_ascend=False, is_dyn=is_dyn, in_dtype=\"float16\")\n\n\n@tvm.testing.uses_gpu\ndef test_argsort():\n    def verify_argsort(shape, axis, is_ascend, dtype, is_dyn=False, in_dtype=\"float32\"):\n        if is_dyn:\n            x = relay.var(\"x\", relay.TensorType([relay.Any()] * len(shape), in_dtype))\n        else:\n            x = relay.var(\"x\", relay.TensorType(shape, in_dtype))\n        z = relay.argsort(x, axis=axis, is_ascend=is_ascend, dtype=dtype)\n        func = relay.Function([x], z)\n        x_data = np.random.uniform(size=shape).astype(in_dtype)\n        if is_ascend:\n            ref_res = np.argsort(x_data, axis=axis, kind=\"stable\")\n        else:\n            ref_res = np.argsort(-x_data, axis=axis, kind=\"stable\")\n\n        if is_dyn:\n            backend = \"vm\"\n        else:\n            backend = \"graph\"\n        for target, dev in tvm.testing.enabled_targets():\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(backend, mod=mod, device=dev, target=target).evaluate()(\n                x_data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res.astype(dtype), rtol=1e-5)\n\n    for is_dyn in [False, True]:\n        for dtype in [\"int32\", \"int64\", \"float32\", \"float64\"]:\n            verify_argsort((2, 3, 4), axis=0, is_ascend=False, dtype=dtype, is_dyn=is_dyn)\n            verify_argsort((1, 4, 6), axis=1, is_ascend=True, dtype=dtype, is_dyn=is_dyn)\n        dtype = \"int32\"\n        verify_argsort((3, 5, 6), axis=-1, is_ascend=False, dtype=dtype, is_dyn=is_dyn)\n        verify_argsort((3, 6000, 6), axis=1, is_ascend=False, dtype=dtype, is_dyn=is_dyn)\n        verify_argsort((1000, 1, 1), axis=0, is_ascend=False, dtype=dtype, is_dyn=is_dyn)\n        verify_argsort((1, 122640), axis=1, is_ascend=False, dtype=dtype, is_dyn=is_dyn)\n        verify_argsort(\n            (1, 122640), axis=1, is_ascend=False, dtype=dtype, is_dyn=is_dyn, in_dtype=\"float16\"\n        )\n\n\n@tvm.testing.uses_gpu\ndef test_topk(executor_kind):\n    def verify_topk(k, axis, ret_type, is_ascend, dtype, in_dtype=\"float32\"):\n        shape = (20, 100)\n        x = relay.var(\"x\", relay.TensorType(shape, in_dtype))\n        out = relay.topk(x, k, axis, ret_type, is_ascend, dtype)\n        if isinstance(out, relay.expr.TupleWrapper):\n            out = out.astuple()\n        func = relay.Function([x], out)\n        np_data = np.random.uniform(size=shape).astype(in_dtype)\n        if is_ascend:\n            np_indices = np.argsort(np_data, axis=axis, kind=\"stable\")\n        else:\n            np_indices = np.argsort(-np_data, axis=axis, kind=\"stable\")\n        kk = k if k >= 1 else shape[axis]\n        if axis == 0:\n            np_indices = np_indices[:kk, :]\n            np_values = np.zeros(np_indices.shape).astype(in_dtype)\n            for i in range(shape[1]):\n                np_values[:, i] = np_data[np_indices[:, i], i]\n        else:\n            np_indices = np_indices[:, :kk]\n            np_values = np.zeros(np_indices.shape).astype(in_dtype)\n            for i in range(shape[0]):\n                np_values[i, :] = np_data[i, np_indices[i, :]]\n        np_indices = np_indices.astype(dtype)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(executor_kind, device=dev, target=target).evaluate(func)(\n                np_data\n            )\n            if ret_type == \"both\":\n                tvm.testing.assert_allclose(op_res[0].numpy(), np_values)\n                tvm.testing.assert_allclose(op_res[1].numpy(), np_indices)\n            elif ret_type == \"values\":\n                tvm.testing.assert_allclose(op_res.numpy(), np_values)\n            else:\n                tvm.testing.assert_allclose(op_res.numpy(), np_indices)\n\n    np.random.seed(0)\n    for k in [0, 1, 5]:\n        for axis in [0, -1, 1]:\n            for ret_type in [\"both\", \"values\", \"indices\"]:\n                verify_topk(k, axis, ret_type, True, \"int64\")\n                verify_topk(k, axis, ret_type, False, \"float32\")\n                verify_topk(k, axis, ret_type, False, \"int64\", \"float16\")\n\n\n@tvm.testing.uses_gpu\ndef test_searchsorted():\n    def verify_searchsorted(right, dtype):\n        shape = (8, 9, 10)\n        values_shape = shape[:-1] + (10,)\n        sorted_sequence = relay.var(\"sorted_sequence\", relay.TensorType(shape, \"float32\"))\n        values = relay.var(\"sorted_sequence\", relay.TensorType(values_shape, \"float32\"))\n        out = relay.searchsorted(sorted_sequence, values, right, dtype)\n        func = relay.Function([sorted_sequence, values], out)\n        sorted_sequence_np = np.sort(np.random.randn(*shape).astype(\"float32\"), axis=-1)\n        values_np = np.random.randn(*values_shape).astype(\"float32\")\n        np_indices = searchsorted_ref(sorted_sequence_np, values_np, right, dtype)\n\n        for target, dev in tvm.testing.enabled_targets():\n            op_res = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n                sorted_sequence_np, values_np\n            )\n            np.testing.assert_equal(op_res.numpy(), np_indices)\n\n    verify_searchsorted(False, \"int32\")\n    verify_searchsorted(True, \"int64\")\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_add.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\n\n\ndef test_tflite_same_io_qnn_params():\n    data_dtype = \"uint8\"\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.00784314, \"float32\"),\n        lhs_zero_point=relay.const(127, \"int32\"),\n        rhs_scale=relay.const(0.00784314, \"float32\"),\n        rhs_zero_point=relay.const(127, \"int32\"),\n        output_scale=relay.const(0.00784314, \"float32\"),\n        output_zero_point=relay.const(127, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_datas = [\n        np.array((140, 153, 165, 178)).reshape((1, 4)),\n        np.array((25, 153, 178, 216)).reshape((1, 4)),\n        np.array((25, 153, 216, 165)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((204, 178, 165, 140)).reshape((1, 4)),\n        np.array((204, 178, 191, 25)).reshape((1, 4)),\n        np.array((204, 178, 25, 191)).reshape((1, 4)),\n    ]\n    golden_outputs = [\n        np.array((217, 204, 203, 191)).reshape((1, 4)),\n        np.array((102, 204, 242, 114)).reshape((1, 4)),\n        np.array((102, 204, 114, 229)).reshape((1, 4)),\n    ]\n\n    for i in range(0, 3):\n        x_data = x_datas[i]\n        y_data = y_datas[i]\n        golden_output = golden_outputs[i]\n\n        op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n            x_data, y_data\n        )\n        np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_tflite_different_io_qnn_params():\n    data_dtype = \"uint8\"\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.0156863, \"float32\"),\n        lhs_zero_point=relay.const(127, \"int32\"),\n        rhs_scale=relay.const(0.0117647, \"float32\"),\n        rhs_zero_point=relay.const(85, \"int32\"),\n        output_scale=relay.const(0.0235294, \"float32\"),\n        output_zero_point=relay.const(128, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_datas = [\n        np.array((76, 140, 153, 172)).reshape((1, 4)),\n        np.array((133, 140, 146, 153)).reshape((1, 4)),\n        np.array((76, 140, 172, 146)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((136, 119, 128, 17)).reshape((1, 4)),\n        np.array((136, 119, 111, 94)).reshape((1, 4)),\n        np.array((136, 119, 17, 128)).reshape((1, 4)),\n    ]\n    golden_outputs = [\n        np.array((120, 154, 167, 124)).reshape((1, 4)),\n        np.array((158, 154, 154, 150)).reshape((1, 4)),\n        np.array((120, 154, 124, 163)).reshape((1, 4)),\n    ]\n\n    for i in range(0, 3):\n        x_data = x_datas[i]\n        y_data = y_datas[i]\n        golden_output = golden_outputs[i]\n\n        op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n            x_data, y_data\n        )\n        np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_saturation():\n    # Same params\n    data_dtype = \"uint8\"\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.125, \"float32\"),\n        lhs_zero_point=relay.const(0, \"int32\"),\n        rhs_scale=relay.const(0.125, \"float32\"),\n        rhs_zero_point=relay.const(0, \"int32\"),\n        output_scale=relay.const(0.125, \"float32\"),\n        output_zero_point=relay.const(0, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n    mod = relay.transform.InferType()(mod)\n\n    x_data = np.array((255, 1, 1, 0)).reshape((1, 4))\n    y_data = np.array((255, 255, 128, 0)).reshape((1, 4))\n    golden_output = np.array((255, 255, 129, 0)).reshape((1, 4))\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n    # Same params, different scale\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.125, \"float32\"),\n        lhs_zero_point=relay.const(0, \"int32\"),\n        rhs_scale=relay.const(0.125, \"float32\"),\n        rhs_zero_point=relay.const(0, \"int32\"),\n        output_scale=relay.const(0.25, \"float32\"),\n        output_zero_point=relay.const(0, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 1, 1, 0)).reshape((1, 4))\n    y_data = np.array((255, 255, 127, 0)).reshape((1, 4))\n    golden_output = np.array((255, 129, 65, 0)).reshape((1, 4))\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n    # Same io params, different output scale\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.125, \"float32\"),\n        lhs_zero_point=relay.const(0, \"int32\"),\n        rhs_scale=relay.const(0.125, \"float32\"),\n        rhs_zero_point=relay.const(0, \"int32\"),\n        output_scale=relay.const(0.25, \"float32\"),\n        output_zero_point=relay.const(0, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 1, 1, 0)).reshape((1, 4))\n    y_data = np.array((255, 255, 127, 0)).reshape((1, 4))\n    golden_output = np.array((255, 129, 65, 0)).reshape((1, 4))\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n    # All params different\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.5, \"float32\"),\n        lhs_zero_point=relay.const(0, \"int32\"),\n        rhs_scale=relay.const(0.25, \"float32\"),\n        rhs_zero_point=relay.const(0, \"int32\"),\n        output_scale=relay.const(0.125, \"float32\"),\n        output_zero_point=relay.const(0, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 0, 1, 0)).reshape((1, 4))\n    y_data = np.array((0, 128, 64, 0)).reshape((1, 4))\n    golden_output = np.array((255, 255, 132, 0)).reshape((1, 4))\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_ignore_channel_axis():\n    data_dtype = \"uint8\"\n\n    x = relay.var(\"x\", shape=(4,), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(4,), dtype=data_dtype)\n    z = relay.qnn.op.add(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(0.00784314, \"float32\"),\n        lhs_zero_point=relay.const(127, \"int32\"),\n        rhs_scale=relay.const(0.00784314, \"float32\"),\n        rhs_zero_point=relay.const(127, \"int32\"),\n        output_scale=relay.const(0.00784314, \"float32\"),\n        output_zero_point=relay.const(127, \"int32\"),\n        lhs_axis=1,\n        rhs_axis=1,\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n\n\nif __name__ == \"__main__\":\n    test_tflite_same_io_qnn_params()\n    test_tflite_different_io_qnn_params()\n    test_saturation()\n    test_ignore_channel_axis()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n# We use llvm target for testing functionality. `llvm` points to an older Intel\n# generation machine, that legalizes to a simple lowering. Therefore, the\n# legalization is overwritten such that it can be skipped and we use the\n# QNNCanonicalizeOps lowering for the testing.\ndef legalize_qnn_batch_matmul(attrs, inputs, types):\n    return None\n\n\ndef make_requantize_params(input_scale, output_scale, output_zero_point, out_dtype):\n    config = {\n        \"input_scale\": input_scale,\n        \"output_scale\": output_scale,\n        \"output_zero_point\": output_zero_point,\n        \"out_dtype\": out_dtype,\n    }\n    return config\n\n\ndef make_configuration(\n    quantized_x,\n    quantized_y,\n    dtype,\n    x_shape,\n    y_shape,\n    x_zero_point,\n    y_zero_point,\n    x_scale,\n    y_scale,\n    output,\n    out_dtype=\"int32\",\n    requantize=None,\n):\n    config = {\n        \"quantized_x\": quantized_x,\n        \"quantized_y\": quantized_y,\n        \"dtype\": dtype,\n        \"x_shape\": x_shape,\n        \"y_shape\": y_shape,\n        \"x_zero_point\": x_zero_point,\n        \"y_zero_point\": y_zero_point,\n        \"x_scale\": x_scale,\n        \"y_scale\": y_scale,\n        \"output\": output,\n        \"out_dtype\": out_dtype,\n        \"requantize\": requantize,\n    }\n    return config\n\n\ndef make_int_configuration(\n    xzero_point_zero=True,\n    yzero_point_zero=True,\n    requantize_output=False,\n    per_channel=False,\n    batch_size=1,\n):\n    x_shape, y_shape, output_shape = (batch_size, 4, 5), (batch_size, 3, 5), (batch_size, 4, 3)\n    if xzero_point_zero == True:\n        x_zero_point = 0\n    else:\n        x_zero_point = -123\n\n    if yzero_point_zero == True:\n        y_zero_point = 0\n    else:\n        y_zero_point = -123\n\n    in_dtype = \"int8\"\n    out_dtype = \"int32\" if not requantize_output else \"int8\"\n\n    quantized_x_np = (\n        np.array(\n            [\n                1,\n                3,\n                5,\n                7,\n                9,  # sum = 25\n                11,\n                13,\n                15,\n                -19,\n                -21,  # sum = -1\n                1,\n                3,\n                5,\n                7,\n                9,  # sum = 25\n                11,\n                13,\n                -17,\n                17,\n                -21,\n            ]\n        )[  # sum = 3\n            np.newaxis, np.newaxis, :\n        ]\n        .repeat(batch_size, axis=1)\n        .astype(in_dtype)\n        .reshape(x_shape)\n    )\n    quantized_y_np = (\n        np.array([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 1, 3, 5, 7, 9])[np.newaxis, np.newaxis, :]\n        .repeat(batch_size, axis=1)\n        .astype(in_dtype)\n        .reshape(y_shape)\n    )\n    x_scale = 0.5\n    y_scale = 0.5\n    output_scale = 2.0\n\n    if requantize_output:\n        assert xzero_point_zero is True\n        assert yzero_point_zero is True\n        output = np.array([20, 51, 20, -26, -27, -26, 20, 51, 20, -14, -10, -14])\n    elif xzero_point_zero is False and yzero_point_zero is False:\n        output = np.array(\n            [81960, 88360, 81960, 78400, 84540, 78400, 81960, 88360, 81960, 78984, 85164, 78984]\n        )\n    elif xzero_point_zero is True and yzero_point_zero is False:\n        output = np.array([3240, 3490, 3240, -320, -330, -320, 3240, 3490, 3240, 264, 294, 264])\n    elif xzero_point_zero is False and yzero_point_zero is True:\n        output = np.array([3240, 9640, 3240, 2878, 9018, 2878, 3240, 9640, 3240, 2970, 9150, 2970])\n    else:\n        output = np.array([165, 415, 165, -197, -207, -197, 165, 415, 165, -105, -75, -105])\n\n    requant_params = (\n        make_requantize_params(x_scale * y_scale, output_scale, -1, \"int8\")\n        if requantize_output\n        else None\n    )\n    # Outputs are for batch size 1, make batch size n version\n    output = (\n        output[np.newaxis, np.newaxis, :]\n        .repeat(batch_size, axis=1)\n        .astype(out_dtype)\n        .reshape(output_shape)\n    )\n    return make_configuration(\n        quantized_x=quantized_x_np,\n        quantized_y=quantized_y_np,\n        dtype=in_dtype,\n        x_shape=x_shape,\n        y_shape=y_shape,\n        x_zero_point=x_zero_point,\n        y_zero_point=y_zero_point,\n        x_scale=x_scale,\n        y_scale=y_scale,\n        output=output,\n        requantize=requant_params,\n    )\n\n\ndef qnn_batch_matmul_driver(test_configuration):\n    in_dtype = test_configuration[\"dtype\"]\n    out_dtype = test_configuration[\"out_dtype\"]\n    quantized_x_name = \"quantized_x\"\n    quantized_y_name = \"quantized_y\"\n    expected_out_dtype = test_configuration[\"out_dtype\"]\n    quantized_x = relay.var(quantized_x_name, shape=test_configuration[\"x_shape\"], dtype=in_dtype)\n    quantized_y = relay.var(quantized_y_name, shape=test_configuration[\"y_shape\"], dtype=in_dtype)\n    mod = relay.qnn.op.batch_matmul(\n        quantized_x,\n        quantized_y,\n        relay.const(test_configuration[\"x_zero_point\"], \"int32\"),\n        relay.const(test_configuration[\"y_zero_point\"], \"int32\"),\n        relay.const(test_configuration[\"x_scale\"], \"float32\"),\n        relay.const(test_configuration[\"y_scale\"], \"float32\"),\n    )\n    if test_configuration[\"requantize\"] is not None:\n        requantize_config = test_configuration[\"requantize\"]\n        mod = relay.qnn.op.requantize(\n            mod,\n            input_scale=relay.const(requantize_config[\"input_scale\"], \"float32\"),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(requantize_config[\"output_scale\"], \"float32\"),\n            output_zero_point=relay.const(requantize_config[\"output_zero_point\"], \"int32\"),\n            out_dtype=requantize_config[\"out_dtype\"],\n        )\n        expected_out_dtype = requantize_config[\"out_dtype\"]\n\n    mod = relay.Function(relay.analysis.free_vars(mod), mod)\n    mod = tvm.IRModule.from_expr(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    with tvm.transform.PassContext(opt_level=2):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n        mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n        mod.set_input(quantized_x_name, test_configuration[quantized_x_name])\n        mod.set_input(quantized_y_name, test_configuration[quantized_y_name])\n        mod.set_input(**params)\n        mod.run()\n        res = mod.get_output(0).numpy()\n        np.testing.assert_equal(res, test_configuration[\"output\"])\n        assert res.dtype == expected_out_dtype\n\n\ndef test_qnn_batch_matmul_xzp0_yzp0():\n    with TempOpAttr(\"qnn.batch_matmul\", \"FTVMQnnLegalize\", legalize_qnn_batch_matmul):\n        for batch_size in [1, 4, 7]:\n            int32_output_params = make_int_configuration(\n                xzero_point_zero=True, yzero_point_zero=True, batch_size=batch_size\n            )\n            qnn_batch_matmul_driver(int32_output_params)\n\n\ndef test_qnn_batch_matmul_xzp0():\n    with TempOpAttr(\"qnn.batch_matmul\", \"FTVMQnnLegalize\", legalize_qnn_batch_matmul):\n        for batch_size in [1, 4, 7]:\n            int32_output_params = make_int_configuration(\n                xzero_point_zero=True, yzero_point_zero=False, batch_size=batch_size\n            )\n            qnn_batch_matmul_driver(int32_output_params)\n\n\ndef test_qnn_batch_matmul_yzp0():\n    with TempOpAttr(\"qnn.batch_matmul\", \"FTVMQnnLegalize\", legalize_qnn_batch_matmul):\n\n        for batch_size in [1, 4, 7]:\n            int32_output_params = make_int_configuration(\n                xzero_point_zero=False, yzero_point_zero=True, batch_size=batch_size\n            )\n            qnn_batch_matmul_driver(int32_output_params)\n\n\ndef test_qnn_batch_matmul():\n    with TempOpAttr(\"qnn.batch_matmul\", \"FTVMQnnLegalize\", legalize_qnn_batch_matmul):\n        for batch_size in [1, 4, 7]:\n\n            int32_output_params = make_int_configuration(\n                xzero_point_zero=False, yzero_point_zero=False, batch_size=batch_size\n            )\n            qnn_batch_matmul_driver(int32_output_params)\n\n\ndef test_qnn_batch_matmul_with_requantized_output():\n    with TempOpAttr(\"qnn.dense\", \"FTVMQnnLegalize\", legalize_qnn_batch_matmul):\n        for batch_size in [1, 4, 7]:\n            int8_requantized_output_params = make_int_configuration(\n                requantize_output=True, batch_size=batch_size\n            )\n            qnn_batch_matmul_driver(int8_requantized_output_params)\n\n\nif __name__ == \"__main__\":\n    test_qnn_batch_matmul_xzp0_yzp0()\n    test_qnn_batch_matmul_xzp0()\n    test_qnn_batch_matmul_yzp0()\n    test_qnn_batch_matmul()\n    test_qnn_batch_matmul_with_requantized_output()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_concatenate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nimport tvm.topi.testing\n\n\ndef test_same_io_qnn_params():\n    data_dtype = \"int32\"\n    axis = 0\n    x_data = np.arange(-32, 32, 1).reshape(1, 64).astype(data_dtype)\n    y_data = np.arange(-64, 64, 2).reshape(1, 64).astype(data_dtype)\n    x_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    y_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    zero = relay.const(0, \"int32\")\n\n    x = relay.var(\"x\", shape=(1, 64), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 64), dtype=data_dtype)\n    z = relay.qnn.op.concatenate(\n        (x, y),\n        input_scales=(x_scale, y_scale),\n        input_zero_points=(zero, zero),\n        output_scale=y_scale,\n        output_zero_point=zero,\n        axis=axis,\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    golden_output = np.concatenate((x_data, y_data), axis=axis)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_different_io_qnn_params():\n    data_dtype = \"int32\"\n    axis = 0\n    x_data = np.arange(-32, 32, 1).reshape(1, 64).astype(data_dtype)\n    y_data = np.arange(-64, 64, 2).reshape(1, 64).astype(data_dtype)\n\n    x_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    y_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    x_zero_point = relay.const(3, \"int32\")\n    y_zero_point = relay.const(4, \"int32\")\n\n    x = relay.var(\"x\", shape=(1, 64), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 64), dtype=data_dtype)\n    z = relay.qnn.op.concatenate(\n        (x, y),\n        input_scales=(x_scale, y_scale),\n        input_zero_points=(x_zero_point, y_zero_point),\n        output_scale=y_scale,\n        output_zero_point=relay.const(1, \"int32\"),\n        axis=axis,\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    golden_output = np.concatenate((x_data - 2, y_data - 3), axis=axis)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_few_same_io_qnn_params():\n    data_dtype = \"int32\"\n    axis = 0\n    x_data = np.arange(-32, 32, 1).reshape(1, 64).astype(data_dtype)\n    y_data = np.arange(-64, 64, 2).reshape(1, 64).astype(data_dtype)\n\n    x_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    y_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    x_zero_point = relay.const(0, \"int32\")\n    y_zero_point = relay.const(1, \"int32\")\n\n    x = relay.var(\"x\", shape=(1, 64), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 64), dtype=data_dtype)\n    z = relay.qnn.op.concatenate(\n        (x, y),\n        input_scales=(x_scale, y_scale),\n        input_zero_points=(x_zero_point, y_zero_point),\n        output_scale=y_scale,\n        output_zero_point=relay.const(1, \"int32\"),\n        axis=axis,\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    golden_output = np.concatenate((x_data + 1, y_data), axis=axis)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_same_i_qnn_params():\n    data_dtype = \"int32\"\n    axis = 0\n    x_data = np.arange(-32, 32, 1).reshape(1, 64).astype(data_dtype)\n    y_data = np.arange(-64, 64, 2).reshape(1, 64).astype(data_dtype)\n\n    x_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    y_scale = relay.const((62 + 64) / (np.power(2, 32) - 1.0), \"float32\")\n    x_zero_point = relay.const(0, \"int32\")\n    y_zero_point = relay.const(0, \"int32\")\n\n    x = relay.var(\"x\", shape=(1, 64), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 64), dtype=data_dtype)\n    z = relay.qnn.op.concatenate(\n        (x, y),\n        input_scales=(x_scale, y_scale),\n        input_zero_points=(x_zero_point, y_zero_point),\n        output_scale=y_scale,\n        output_zero_point=relay.const(1, \"int32\"),\n        axis=axis,\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    golden_output = np.concatenate((x_data + 1, y_data + 1), axis=axis)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_call_input():\n    # This tests the case where the input to concatenate is not explicitly a\n    # tuple node but is instead a call node.\n    x_data = np.ones(shape=(64,)).astype(\"uint8\")\n\n    x = relay.var(\"x\", shape=(64,), dtype=\"uint8\")\n    x_scale = relay.const(1, \"float32\")\n    y_scale = relay.const(1, \"float32\")\n    x_zero_point = relay.const(0, \"int32\")\n    y_zero_point = relay.const(0, \"int32\")\n\n    tup = relay.split(x, 2, axis=0)\n    z = relay.qnn.op.concatenate(\n        tup,\n        input_scales=(x_scale, y_scale),\n        input_zero_points=(x_zero_point, y_zero_point),\n        output_scale=y_scale,\n        output_zero_point=relay.const(0, \"int32\"),\n        axis=0,\n    )\n    func = relay.Function([x], z)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(x_data)\n    np.testing.assert_equal(op_res.numpy(), x_data)\n\n\nif __name__ == \"__main__\":\n    test_call_input()\n    test_same_io_qnn_params()\n    test_different_io_qnn_params()\n    test_few_same_io_qnn_params()\n    test_same_i_qnn_params()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_conv2_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport tvm\nfrom tvm import relay, te\nfrom tvm.contrib import graph_executor\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\ndef get_ref_func(\n    data,\n    kernel,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    groups,\n    channels=None,\n):\n    casted_data = relay.op.cast(data, \"int32\")\n    casted_kernel = relay.op.cast(kernel, \"int32\")\n    shifted_data = relay.op.subtract(casted_data, relay.const(input_zero_point, \"int32\"))\n    shifted_kernel = relay.op.subtract(casted_kernel, relay.const(kernel_zero_point, \"int32\"))\n    func = relay.op.nn.conv2d_transpose(\n        shifted_data,\n        shifted_kernel,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        groups=groups,\n        channels=channels,\n        kernel_size=kernel_size,\n        out_dtype=out_dtype,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    func = relay.Function(relay.analysis.free_vars(func), func)\n    return func\n\n\ndef get_qnn_func(\n    data,\n    kernel,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    channels,\n    groups,\n):\n    func = relay.qnn.op.conv2d_transpose(\n        data,\n        kernel,\n        input_zero_point=relay.const(input_zero_point, \"int32\"),\n        kernel_zero_point=relay.const(kernel_zero_point, \"int32\"),\n        input_scale=relay.const(input_scale, \"float32\"),\n        kernel_scale=relay.const(kernel_scale, \"float32\"),\n        kernel_size=kernel_size,\n        strides=strides,\n        dilation=dilation,\n        padding=padding,\n        out_dtype=out_dtype,\n        groups=groups,\n        channels=channels,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    mod = relay.Function(relay.analysis.free_vars(func), func)\n    mod = tvm.IRModule.from_expr(mod)\n    return mod\n\n\ndef get_funcs(\n    data_shape,\n    data_dtype,\n    kernel_shape,\n    kernel_dtype,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    groups=1,\n    channels=None,\n):\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n\n    ref_func = get_ref_func(\n        data,\n        kernel,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        kernel_size,\n        padding,\n        strides,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_dtype,\n        groups,\n        channels,\n    )\n    ref_func = run_infer_type(ref_func)\n    ref_func = tvm.IRModule.from_expr(ref_func)\n    qnn_func = get_qnn_func(\n        data,\n        kernel,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        kernel_size,\n        padding,\n        strides,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_dtype,\n        channels,\n        groups,\n    )\n\n    return (ref_func, qnn_func)\n\n\ndef verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype):\n    def get_inputs(data_shape, data_dtype, kernel_shape, kernel_dtype):\n        # Keeping inputs multiple of 4 because of a bug in Average Pool2d\n        # https://discuss.tvm.apache.org/t/pool2d-gives-bad-output-for-integer-inputs/3377\n        low = -128\n        high = 127\n        if data_dtype == \"uint8\":\n            low = 0\n            high = 255\n        golden_data = np.random.randint(low=low, high=high, size=data_shape).astype(data_dtype)\n        low = -128\n        high = 127\n        if kernel_dtype == \"uint8\":\n            low = 0\n            high = 255\n        golden_weight = np.random.randint(low=low, high=high, size=kernel_shape).astype(\n            kernel_dtype\n        )\n        return (golden_data, golden_weight)\n\n    def get_output(func, golden_inputs):\n        with tvm.transform.PassContext(opt_level=2):\n            golden_data, golden_weight = golden_inputs\n            params = {\"kernel\": golden_weight}\n            libs = relay.build(func, \"llvm\", params=params)\n            mod = graph_executor.create(libs.graph_json, libs.lib, device=tvm.cpu(0))\n            mod.set_input(\"data\", golden_data)\n            mod.set_input(**libs.params)\n            mod.run()\n            res = mod.get_output(0).numpy()\n            return res\n\n    golden_inputs = get_inputs(data_shape, data_dtype, kernel_shape, kernel_dtype)\n    golden_output = get_output(ref_func, golden_inputs)\n    qnn_output = get_output(qnn_func, golden_inputs)\n    np.testing.assert_equal(qnn_output, golden_output)\n\n\ndef test_no_zero_point():\n    # uint8 input\n    data_shape = (2, 1, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (1, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=0,\n        kernel_zero_point=0,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # int8 input\n    data_shape = (2, 1, 2, 4)\n    data_dtype = \"int8\"\n    kernel_shape = (1, 3, 2, 2)\n    kernel_dtype = \"int8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=0,\n        kernel_zero_point=0,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_kernel_zero_point():\n    # uint8 input\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=0,\n        kernel_zero_point=1,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # int8 input\n    data_shape = (2, 1, 2, 4)\n    data_dtype = \"int8\"\n    kernel_shape = (1, 3, 2, 2)\n    kernel_dtype = \"int8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=0,\n        kernel_zero_point=5,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_input_zero_point():\n    # uint8 input\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=0,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # int8 input\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"int8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"int8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=0,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_both_zero_point():\n    # uint8 input\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # int8 input\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"int8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"int8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_different_dtype():\n    # uint8 input and int8 weight\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"int8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n        channels=kernel_shape[1],\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # int8 input and uint8 weight\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"int8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n        channels=kernel_shape[1],\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_layout():\n    # uint8 input\n    data_shape = (2, 2, 4, 4)  # NHWC\n    data_dtype = \"uint8\"\n    kernel_shape = (2, 2, 3, 4)  # HWOI\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    data_shape = (2, 2, 4, 3)  # NHWC\n    data_dtype = \"uint8\"\n    kernel_shape = (2, 2, 1, 3)  # HWOI\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=5,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_padding():\n    # uint8 input\n    data_shape = (1, 4, 2, 2)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=8,\n        kernel_zero_point=5,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(1, 1),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # Try different layout\n    data_shape = (2, 2, 4, 4)  # NHWC\n    data_dtype = \"uint8\"\n    kernel_shape = (2, 2, 3, 4)  # HWOI\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=8,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(1, 1),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n    # Try asymmetric padding\n    data_shape = (2, 8, 6, 4)  # NHWC\n    data_dtype = \"uint8\"\n    kernel_shape = (2, 2, 3, 4)  # HWOI\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=8,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(1, 1, 2, 2),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_const_folding():\n    data_shape = (2, 4, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (4, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n\n    golden_weight = np.random.randint(low=0, high=255, size=kernel_shape).astype(kernel_dtype)\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    kernel = relay.const(golden_weight)\n    qnn_func = get_qnn_func(\n        data,\n        kernel,\n        input_zero_point=8,\n        kernel_zero_point=3,\n        kernel_size=(2, 2),\n        input_scale=1.0,\n        kernel_scale=1.0,\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n        channels=kernel_shape[1],\n        groups=1,\n    )\n    folded_mod = transform.FoldConstant()(qnn_func)\n    folded_func = folded_mod[\"main\"]\n    assert \"reshape\" not in folded_func.astext()\n\n\ndef test_broadcast_layout():\n    # Test broadcast support for NHWC layout.\n    data_shape = (1, 229, 229, 3)  # NHWC\n    data_dtype = \"uint8\"\n    kernel_shape = (7, 7, 64, 3)  # HWOI\n    kernel_dtype = \"int8\"\n    _, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=8,\n        kernel_zero_point=3,\n        input_scale=1.0,\n        kernel_scale=1.0,\n        kernel_size=(7, 7),\n        padding=(1, 1),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n        out_dtype=\"int32\",\n    )\n    func = qnn_func[\"main\"].body\n    bias = relay.var(\"bias\", shape=(64,), dtype=\"int32\")\n    bias2 = relay.var(\"bias2\", shape=(1, 233, 233, 64), dtype=\"int32\")\n\n    # Check broadcast support on both lhs and rhs\n    func = relay.add(func, bias2)\n    func = relay.add(bias2, func)\n    func = relay.add(bias, func)\n    func = relay.add(func, bias)\n    func = relay.Function(relay.analysis.free_vars(func), func)\n    mod = tvm.IRModule.from_expr(func)\n    with tvm.transform.PassContext(opt_level=3):\n        libs = relay.build(mod, \"llvm -mcpu=skylake-avx512\")\n\n\ndef test_non_scalar_input_scale_zp():\n    data_shape = (2, 1, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (1, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    ref_func, qnn_func = get_funcs(\n        data_shape=data_shape,\n        data_dtype=data_dtype,\n        kernel_shape=kernel_shape,\n        kernel_dtype=kernel_dtype,\n        input_zero_point=[0],\n        kernel_zero_point=0,\n        input_scale=[1.0],\n        kernel_scale=1.0,\n        kernel_size=(2, 2),\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n    verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_per_channel_kernel_scale():\n    data_shape = (2, 1, 2, 4)\n    data_dtype = \"uint8\"\n    kernel_shape = (1, 3, 2, 2)\n    kernel_dtype = \"uint8\"\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n    kernel_scales = [2, 2, 2]\n    kernel_scales = relay.const(np.array(kernel_scales).astype(\"float32\"))\n    func = relay.qnn.op.conv2d_transpose(\n        data,\n        kernel,\n        input_zero_point=relay.const(0, \"int32\"),\n        kernel_zero_point=relay.const(0, \"int32\"),\n        input_scale=relay.const(2.0, \"float32\"),\n        kernel_scale=kernel_scales,\n        kernel_size=(2, 2),\n        channels=kernel_shape[0],\n        padding=(0, 0),\n        strides=(1, 1),\n        dilation=(1, 1),\n        data_layout=\"NCHW\",\n        kernel_layout=\"IOHW\",\n        out_dtype=\"int32\",\n    )\n\n    mod = relay.Function(relay.analysis.free_vars(func), func)\n    mod = tvm.IRModule.from_expr(mod)\n\n\nif __name__ == \"__main__\":\n    test_no_zero_point()\n    test_input_zero_point()\n    test_kernel_zero_point()\n    test_both_zero_point()\n    test_different_dtype()\n    test_layout()\n    test_padding()\n    test_const_folding()\n    test_broadcast_layout()\n    test_per_channel_kernel_scale()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n# We use llvm target for testing functionality. `llvm` points to an older Intel\n# generation machine, that legalizes to a simple lowering. Therefore, the\n# legalization is overwritten such that it can be skipped and we use the\n# QNNCanonicalizeOps lowering for the testing.\ndef legalize_qnn_conv2d(attrs, inputs, types):\n    return None\n\n\ndef get_ref_func(\n    data,\n    kernel,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    groups,\n    channels=None,\n):\n    if isinstance(input_zero_point, (int, float)):\n        input_zero_point = relay.const(input_zero_point, \"int32\")\n    if isinstance(kernel_zero_point, (int, float)):\n        kernel_zero_point = relay.const(kernel_zero_point, \"int32\")\n    else:\n        # Kernel zero point expression requires manual broadcasting for some layouts.\n        if kernel_layout == \"OIHW\":\n            kernel_zero_point = relay.reshape(kernel_zero_point, [-1, 1, 1, 1])\n        elif kernel_layout == \"HWOI\":\n            kernel_zero_point = relay.reshape(kernel_zero_point, [1, 1, -1, 1])\n\n    casted_data = relay.op.cast(data, \"int32\")\n    casted_kernel = relay.op.cast(kernel, \"int32\")\n    shifted_data = relay.op.subtract(casted_data, input_zero_point)\n    shifted_kernel = relay.op.subtract(casted_kernel, kernel_zero_point)\n    func = relay.op.nn.conv2d(\n        shifted_data,\n        shifted_kernel,\n        padding=padding,\n        strides=strides,\n        dilation=dilation,\n        groups=groups,\n        channels=channels,\n        kernel_size=kernel_size,\n        out_dtype=out_dtype,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    func = relay.Function(relay.analysis.free_vars(func), func)\n    return func\n\n\ndef get_qnn_func(\n    data,\n    kernel,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    channels,\n    groups,\n):\n    if isinstance(input_zero_point, (int, float)):\n        input_zero_point = relay.const(input_zero_point, \"int32\")\n    if isinstance(kernel_zero_point, (int, float)):\n        kernel_zero_point = relay.const(kernel_zero_point, \"int32\")\n\n    func = relay.qnn.op.conv2d(\n        data,\n        kernel,\n        input_zero_point=input_zero_point,\n        kernel_zero_point=kernel_zero_point,\n        input_scale=relay.const(input_scale, \"float32\"),\n        kernel_scale=relay.const(kernel_scale, \"float32\"),\n        kernel_size=kernel_size,\n        strides=strides,\n        dilation=dilation,\n        padding=padding,\n        out_dtype=out_dtype,\n        groups=groups,\n        channels=channels,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n\n    mod = relay.Function(relay.analysis.free_vars(func), func)\n    mod = tvm.IRModule.from_expr(mod)\n    return mod\n\n\ndef get_funcs(\n    data_shape,\n    data_dtype,\n    kernel_shape,\n    kernel_dtype,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    kernel_size,\n    padding,\n    strides,\n    dilation,\n    data_layout,\n    kernel_layout,\n    out_dtype,\n    groups=1,\n    channels=None,\n):\n    data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n    kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n\n    ref_func = get_ref_func(\n        data,\n        kernel,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        kernel_size,\n        padding,\n        strides,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_dtype,\n        groups,\n        channels,\n    )\n    ref_func = run_infer_type(ref_func)\n    ref_func = tvm.IRModule.from_expr(ref_func)\n    qnn_func = get_qnn_func(\n        data,\n        kernel,\n        input_zero_point,\n        kernel_zero_point,\n        input_scale,\n        kernel_scale,\n        kernel_size,\n        padding,\n        strides,\n        dilation,\n        data_layout,\n        kernel_layout,\n        out_dtype,\n        channels,\n        groups,\n    )\n\n    return (ref_func, qnn_func)\n\n\ndef verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype):\n    def get_inputs(data_shape, data_dtype, kernel_shape, kernel_dtype):\n        # Keeping inputs multiple of 4 because of a bug in Average Pool2d\n        # https://discuss.tvm.apache.org/t/pool2d-gives-bad-output-for-integer-inputs/3377\n        low = -128\n        high = 127\n        if data_dtype == \"uint8\":\n            low = 0\n            high = 255\n        golden_data = np.random.randint(low=low, high=high, size=data_shape).astype(data_dtype)\n        low = -128\n        high = 127\n        if kernel_dtype == \"uint8\":\n            low = 0\n            high = 255\n        golden_weight = np.random.randint(low=low, high=high, size=kernel_shape).astype(\n            kernel_dtype\n        )\n        return (golden_data, golden_weight)\n\n    def get_output(func, golden_inputs):\n        with tvm.transform.PassContext(opt_level=2):\n            golden_data, golden_weight = golden_inputs\n            params = {\"kernel\": golden_weight}\n            graph, lib, params = relay.build(func, \"llvm\", params=params)\n            mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            mod.set_input(\"data\", golden_data)\n            mod.set_input(**params)\n            mod.run()\n            res = mod.get_output(0).numpy()\n            return res\n\n    golden_inputs = get_inputs(data_shape, data_dtype, kernel_shape, kernel_dtype)\n    golden_output = get_output(ref_func, golden_inputs)\n    qnn_output = get_output(qnn_func, golden_inputs)\n    np.testing.assert_equal(qnn_output, golden_output)\n\n\ndef test_no_zero_point():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 1, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 1, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=0,\n            kernel_zero_point=0,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # int8 input\n        data_shape = (2, 1, 2, 4)\n        data_dtype = \"int8\"\n        kernel_shape = (3, 1, 2, 2)\n        kernel_dtype = \"int8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=0,\n            kernel_zero_point=0,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_kernel_zero_point():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=0,\n            kernel_zero_point=1,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # int8 input\n        data_shape = (2, 1, 2, 4)\n        data_dtype = \"int8\"\n        kernel_shape = (3, 1, 2, 2)\n        kernel_dtype = \"int8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=0,\n            kernel_zero_point=5,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_input_zero_point():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=0,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # int8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"int8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"int8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=0,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_both_zero_point():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # int8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"int8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"int8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_dynamic_zero_point():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input with non static zero points.\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        input_zero_point = relay.op.multiply(\n            relay.const(2, dtype=\"int32\"), relay.const(2, dtype=\"int32\")\n        )\n        kernel_zero_point = relay.const(np.random.randint(10, size=[3]), \"int32\")\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # int8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"int8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"int8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_layout():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 2, 4, 4)  # NHWC\n        data_dtype = \"uint8\"\n        kernel_shape = (2, 2, 4, 3)  # HWIO\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # NHWC and HWOI layout. Used in depthwise conv.\n        data_shape = (2, 2, 4, 3)  # NHWC\n        data_dtype = \"uint8\"\n        kernel_shape = (2, 2, 3, 1)  # HWOI\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            groups=3,\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWOI\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_padding():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (1, 4, 2, 2)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=8,\n            kernel_zero_point=5,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(1, 1),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # Try different layout\n        data_shape = (2, 2, 4, 4)  # NHWC\n        data_dtype = \"uint8\"\n        kernel_shape = (2, 2, 4, 3)  # HWIO\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=8,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(1, 1),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # Try asymmetric padding\n        data_shape = (2, 2, 4, 4)  # NHWC\n        data_dtype = \"uint8\"\n        kernel_shape = (2, 2, 4, 3)  # HWIO\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=8,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(1, 1, 2, 2),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_dilation():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # Non-zero kernel point - fall back to simpler lowering.\n        data_shape = (2, 4, 4, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(2, 2),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # Zero kernel point\n        data_shape = (2, 4, 4, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=0,\n            kernel_zero_point=0,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(2, 2),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_const_folding():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 2, 2)\n        kernel_dtype = \"uint8\"\n\n        golden_weight = np.random.randint(low=0, high=255, size=kernel_shape).astype(kernel_dtype)\n        data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n        kernel = relay.const(golden_weight)\n        qnn_func = get_qnn_func(\n            data,\n            kernel,\n            input_zero_point=8,\n            kernel_zero_point=3,\n            kernel_size=(2, 2),\n            input_scale=1.0,\n            kernel_scale=1.0,\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n            channels=kernel_shape[0],\n            groups=1,\n        )\n        folded_mod = transform.FoldConstant()(qnn_func)\n        folded_func = folded_mod[\"main\"]\n        assert \"reshape\" not in folded_func.astext()\n\n\ndef test_kernel_size_1x1():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 1, 1)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        assert \"avg_pool2d\" not in qnn_func.astext()\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_kernel_size_1x1_strides_2():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 4, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 4, 1, 1)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=5,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            strides=(2, 2),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        assert \"avg_pool2d\" not in qnn_func.astext()\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_tflite_large_irregular():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (1, 1024, 1, 1)\n        data_dtype = \"uint8\"\n        kernel_shape = (1001, 1024, 1, 1)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=127,\n            kernel_zero_point=127,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        golden_data = np.full(data_shape, 127).astype(\"uint8\")\n        golden_weight = np.full(kernel_shape, 127).astype(\"uint8\")\n\n        with tvm.transform.PassContext(opt_level=2):\n            params = {\"kernel\": golden_weight}\n            graph, lib, params = relay.build(qnn_func, \"llvm\", params=params)\n            mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            mod.set_input(\"data\", golden_data)\n            mod.set_input(**params)\n            mod.run()\n            qnn_output = mod.get_output(0).numpy()\n        golden_output = np.full((1, 1001, 1, 1), 0).astype(\"uint8\")\n        np.testing.assert_equal(qnn_output, golden_output)\n\n\ndef test_tflite_output_multiplier_greater_than_one():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (2, 1, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 1, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            input_zero_point=128,\n            kernel_zero_point=128,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(2, 2),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        golden_data = 128 + np.array((1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4)).reshape(\n            data_shape\n        ).astype(\"uint8\")\n        golden_weight = 128 + np.array((1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1)).reshape(\n            kernel_shape\n        )\n        golden_weight = golden_weight.astype(\"uint8\")\n\n        with tvm.transform.PassContext(opt_level=2):\n            params = {\"kernel\": golden_weight}\n            graph, lib, params = relay.build(qnn_func, \"llvm\", params=params)\n            mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            mod.set_input(\"data\", golden_data)\n            mod.set_input(**params)\n            mod.run()\n            qnn_output = mod.get_output(0).numpy()\n        golden_output = np.array((17, 17, 0, 0, 2, 2, 16, 36, 2, 2, 0, 0)).reshape(2, 3, 1, 2)\n        np.testing.assert_equal(qnn_output, golden_output)\n\n\ndef test_tflite_anistropic_strides():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input\n        data_shape = (1, 1, 3, 6)\n        data_dtype = \"uint8\"\n        kernel_shape = (1, 1, 2, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=127,\n            kernel_zero_point=127,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n            strides=(1, 3),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n        golden_data = np.array(\n            (\n                133,\n                131,\n                129,\n                125,\n                123,\n                121,\n                135,\n                133,\n                131,\n                123,\n                121,\n                119,\n                137,\n                135,\n                133,\n                121,\n                119,\n                117,\n            )\n        ).reshape(data_shape)\n        golden_data = golden_data.astype(\"uint8\")\n        golden_weight = np.array((129, 131, 133, 135)).reshape(kernel_shape)\n        golden_weight = golden_weight.astype(\"uint8\")\n\n        with tvm.transform.PassContext(opt_level=2):\n            params = {\"kernel\": golden_weight}\n            graph, lib, params = relay.build(qnn_func, \"llvm\", params=params)\n            mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n            mod.set_input(\"data\", golden_data)\n            mod.set_input(**params)\n            mod.run()\n            qnn_output = mod.get_output(0).numpy()\n        golden_output = np.array((124, -92, 164, -132)).reshape(1, 1, 2, 2)\n        np.testing.assert_equal(qnn_output, golden_output)\n\n\ndef test_broadcast_layout():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # Test broadcast support for NHWC layout.\n        data_shape = (1, 229, 229, 3)  # NHWC\n        data_dtype = \"uint8\"\n        kernel_shape = (7, 7, 3, 64)  # HWIO\n        kernel_dtype = \"int8\"\n        _, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=8,\n            kernel_zero_point=3,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(7, 7),\n            padding=(1, 1),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        func = qnn_func[\"main\"].body\n        bias = relay.var(\"bias\", shape=(64,), dtype=\"int32\")\n        bias2 = relay.var(\"bias2\", shape=(1, 225, 225, 1), dtype=\"int32\")\n\n        # Check broadcast support on both lhs and rhs\n        func = relay.add(func, bias2)\n        func = relay.add(bias2, func)\n        func = relay.add(bias, func)\n        func = relay.add(func, bias)\n        func = relay.Function(relay.analysis.free_vars(func), func)\n        mod = tvm.IRModule.from_expr(func)\n        with tvm.transform.PassContext(opt_level=3):\n            graph, lib, params = relay.build(mod, \"llvm -mcpu=skylake-avx512\")\n\n\ndef test_depthwise_depth_multiplier():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n\n        # uint8 input, NCHW and OIHW\n        # Depthwise multiplier = 1\n        data_shape = (2, 4, 16, 16)\n        data_dtype = \"uint8\"\n        kernel_shape = (4, 1, 3, 3)\n        kernel_dtype = \"uint8\"\n        input_zero_point = relay.op.multiply(\n            relay.const(2, dtype=\"int32\"), relay.const(2, dtype=\"int32\")\n        )\n        kernel_zero_point = relay.const(np.random.randint(10, size=[4]), \"int32\")\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(3, 3),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n            groups=4,\n            channels=4,\n        )\n\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # Depthwise multiplier = 2\n        data_shape = (10, 4, 16, 16)\n        data_dtype = \"uint8\"\n        kernel_shape = (4, 2, 3, 3)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(3, 3),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n            groups=4,\n            channels=8,\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # uint8 input, NHWC and HWOI\n        # Depthwise multiplier = 1\n        data_shape = (2, 16, 16, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 3, 4, 1)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(3, 3),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWOI\",\n            out_dtype=\"int32\",\n            groups=4,\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n        # Depthwise multiplier = 2\n        data_shape = (2, 16, 16, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 3, 4, 2)\n        kernel_dtype = \"uint8\"\n        ref_func, qnn_func = get_funcs(\n            data_shape=data_shape,\n            data_dtype=data_dtype,\n            kernel_shape=kernel_shape,\n            kernel_dtype=kernel_dtype,\n            input_zero_point=input_zero_point,\n            kernel_zero_point=kernel_zero_point,\n            input_scale=1.0,\n            kernel_scale=1.0,\n            kernel_size=(3, 3),\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWOI\",\n            out_dtype=\"int32\",\n            groups=4,\n            channels=8,\n        )\n        verify(ref_func, qnn_func, data_shape, data_dtype, kernel_shape, kernel_dtype)\n\n\ndef test_per_channel_kernel_scale():\n    with TempOpAttr(\"qnn.conv2d\", \"FTVMQnnLegalize\", legalize_qnn_conv2d):\n        data_shape = (2, 1, 2, 4)\n        data_dtype = \"uint8\"\n        kernel_shape = (3, 1, 2, 2)\n        kernel_dtype = \"uint8\"\n        data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n        kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n        kernel_scales = [2, 2, 2]\n        kernel_scales = relay.const(np.array(kernel_scales).astype(\"float32\"))\n        func = relay.qnn.op.conv2d(\n            data,\n            kernel,\n            input_zero_point=relay.const(0, \"int32\"),\n            kernel_zero_point=relay.const(0, \"int32\"),\n            input_scale=relay.const(2.0, \"float32\"),\n            kernel_scale=kernel_scales,\n            kernel_size=(2, 2),\n            channels=kernel_shape[0],\n            padding=(0, 0),\n            strides=(1, 1),\n            dilation=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n            out_dtype=\"int32\",\n        )\n\n        mod = relay.Function(relay.analysis.free_vars(func), func)\n        mod = tvm.IRModule.from_expr(mod)\n\n\nif __name__ == \"__main__\":\n    test_no_zero_point()\n    test_input_zero_point()\n    test_kernel_zero_point()\n    test_both_zero_point()\n    test_layout()\n    test_padding()\n    test_dilation()\n    test_const_folding()\n    test_kernel_size_1x1()\n    test_kernel_size_1x1_strides_2()\n    test_tflite_large_irregular()\n    test_broadcast_layout()\n    test_tflite_output_multiplier_greater_than_one()\n    test_tflite_anistropic_strides()\n    test_depthwise_depth_multiplier()\n    test_per_channel_kernel_scale()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\n# We use llvm target for testing functionality. `llvm` points to an older Intel\n# generation machine, that legalizes to a simple lowering. Therefore, the\n# legalization is overwritten such that it can be skipped and we use the\n# QNNCanonicalizeOps lowering for the testing.\ndef legalize_qnn_dense(attrs, inputs, types):\n    return None\n\n\ndef make_requantize_params(input_scale, output_scale, output_zero_point, out_dtype):\n    config = {\n        \"input_scale\": input_scale,\n        \"output_scale\": output_scale,\n        \"output_zero_point\": output_zero_point,\n        \"out_dtype\": out_dtype,\n    }\n    return config\n\n\ndef make_configuration(\n    quantized_data,\n    quantized_kernel,\n    dtype,\n    input_shape,\n    kernel_shape,\n    input_zero_point,\n    kernel_zero_point,\n    input_scale,\n    kernel_scale,\n    units,\n    output,\n    out_dtype=\"int32\",\n    bias=None,\n    requantize=None,\n):\n    if requantize is not None:\n        assert bias is not None\n    config = {\n        \"quantized_data\": quantized_data,\n        \"quantized_kernel\": quantized_kernel,\n        \"dtype\": dtype,\n        \"input_shape\": input_shape,\n        \"kernel_shape\": kernel_shape,\n        \"input_zero_point\": input_zero_point,\n        \"kernel_zero_point\": kernel_zero_point,\n        \"input_scale\": input_scale,\n        \"kernel_scale\": kernel_scale,\n        \"units\": units,\n        \"output\": output,\n        \"out_dtype\": out_dtype,\n        \"bias\": bias,\n        \"requantize\": requantize,\n    }\n    return config\n\n\ndef make_int_configuration(use_bias=False, requantize_output=False, per_channel=False):\n    input_shape, kernel_shape, output_shape = (2, 10), (3, 10), (2, 3)\n    input_zero_point, kernel_zero_point = -1, -1\n    in_dtype = \"int8\"\n    out_dtype = \"int32\" if not requantize_output else \"int8\"\n    units = 3\n    quantized_data_np = (\n        np.array([1, 3, 5, 7, 9, 11, 13, 15, -19, -21, 1, 3, 5, 7, 9, 11, 13, -17, 17, -21])\n        .astype(in_dtype)\n        .reshape(input_shape)\n    )\n    quantized_kernel_np = (\n        np.array(\n            [\n                1,\n                3,\n                5,\n                7,\n                9,\n                11,\n                13,\n                15,\n                17,\n                19,\n                1,\n                3,\n                5,\n                7,\n                9,\n                11,\n                13,\n                15,\n                17,\n                19,\n                1,\n                3,\n                5,\n                7,\n                9,\n                11,\n                13,\n                15,\n                17,\n                19,\n            ]\n        )\n        .astype(in_dtype)\n        .reshape(kernel_shape)\n    )\n    input_scale = 0.5\n    kernel_scale = 0.5\n    output_scale = 1.0\n    bias = np.array([4, 8, 12]).astype(out_dtype).reshape((units,)) if use_bias else None\n\n    if per_channel:\n        assert use_bias and requantize_output\n        kernel_scale = np.array([0.5, 0.3, 0.4], dtype=np.float32)\n        output = np.array([23, 14, 20, 57, 34, 47])\n    elif requantize_output:\n        assert use_bias\n        output = np.array([23, 24, 25, 57, 58, 59])\n    elif use_bias:\n        output = np.array([96, 100, 104, 232, 236, 240])\n    else:\n        output = np.array([92, 92, 92, 228, 228, 228])\n\n    requant_params = (\n        make_requantize_params(input_scale * kernel_scale, output_scale, -1, \"int8\")\n        if requantize_output\n        else None\n    )\n\n    output = output.astype(out_dtype).reshape(output_shape)\n    return make_configuration(\n        quantized_data=quantized_data_np,\n        quantized_kernel=quantized_kernel_np,\n        dtype=in_dtype,\n        input_shape=input_shape,\n        kernel_shape=kernel_shape,\n        input_zero_point=input_zero_point,\n        kernel_zero_point=kernel_zero_point,\n        input_scale=input_scale,\n        kernel_scale=kernel_scale,\n        units=units,\n        output=output,\n        bias=bias,\n        requantize=requant_params,\n    )\n\n\ndef qnn_dense_driver(test_configuration):\n    in_dtype = test_configuration[\"dtype\"]\n    out_dtype = test_configuration[\"out_dtype\"]\n    quantized_data_name = \"quantized_data\"\n    quantized_kernel_name = \"quantized_kernel\"\n    expected_out_dtype = test_configuration[\"out_dtype\"]\n    bias_name = \"bias\"\n    quantized_data = relay.var(\n        quantized_data_name, shape=test_configuration[\"input_shape\"], dtype=in_dtype\n    )\n    quantized_kernel = relay.var(\n        quantized_kernel_name, shape=test_configuration[\"kernel_shape\"], dtype=in_dtype\n    )\n    mod = relay.qnn.op.dense(\n        quantized_data,\n        quantized_kernel,\n        relay.const(test_configuration[\"input_zero_point\"], \"int32\"),\n        relay.const(test_configuration[\"kernel_zero_point\"], \"int32\"),\n        relay.const(test_configuration[\"input_scale\"], \"float32\"),\n        relay.const(test_configuration[\"kernel_scale\"], \"float32\"),\n        test_configuration[\"units\"],\n    )\n    if test_configuration[bias_name] is not None:\n        bias = relay.var(bias_name, shape=test_configuration[\"bias\"].shape, dtype=out_dtype)\n        mod = relay.nn.bias_add(mod, bias)\n    if test_configuration[\"requantize\"] is not None:\n        requantize_config = test_configuration[\"requantize\"]\n        mod = relay.qnn.op.requantize(\n            mod,\n            input_scale=relay.const(requantize_config[\"input_scale\"], \"float32\"),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(requantize_config[\"output_scale\"], \"float32\"),\n            output_zero_point=relay.const(requantize_config[\"output_zero_point\"], \"int32\"),\n            out_dtype=requantize_config[\"out_dtype\"],\n        )\n        expected_out_dtype = requantize_config[\"out_dtype\"]\n\n    mod = relay.Function(relay.analysis.free_vars(mod), mod)\n    mod = tvm.IRModule.from_expr(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    with tvm.transform.PassContext(opt_level=2):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n        mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n        mod.set_input(quantized_data_name, test_configuration[quantized_data_name])\n        mod.set_input(quantized_kernel_name, test_configuration[quantized_kernel_name])\n        if test_configuration[bias_name] is not None:\n            mod.set_input(bias_name, test_configuration[bias_name])\n        mod.set_input(**params)\n        mod.run()\n        res = mod.get_output(0).numpy()\n        np.testing.assert_equal(res, test_configuration[\"output\"])\n        assert res.dtype == expected_out_dtype\n\n\ndef test_qnn_dense_without_bias():\n    with TempOpAttr(\"qnn.dense\", \"FTVMQnnLegalize\", legalize_qnn_dense):\n\n        int32_output_without_bias_params = make_int_configuration(use_bias=False)\n        qnn_dense_driver(int32_output_without_bias_params)\n\n\ndef test_qnn_dense_with_bias():\n    with TempOpAttr(\"qnn.dense\", \"FTVMQnnLegalize\", legalize_qnn_dense):\n\n        int32_output_with_bias_params = make_int_configuration(use_bias=True)\n        qnn_dense_driver(int32_output_with_bias_params)\n\n\ndef test_qnn_dense_with_requantized_output():\n    with TempOpAttr(\"qnn.dense\", \"FTVMQnnLegalize\", legalize_qnn_dense):\n\n        int8_requantized_output_with_bias_params = make_int_configuration(\n            use_bias=True, requantize_output=True\n        )\n        qnn_dense_driver(int8_requantized_output_with_bias_params)\n\n\ndef test_per_channel_weight_scale():\n    with TempOpAttr(\"qnn.dense\", \"FTVMQnnLegalize\", legalize_qnn_dense):\n        config = make_int_configuration(use_bias=True, requantize_output=True, per_channel=True)\n        qnn_dense_driver(config)\n\n\nif __name__ == \"__main__\":\n    test_qnn_dense_without_bias()\n    test_qnn_dense_with_bias()\n    test_qnn_dense_with_requantized_output()\n    test_per_channel_weight_scale()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_dequantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.testing import run_infer_type\n\n\ndef dequantize_test_driver(in_dtype, quant_args, in_data, verify_output_data, axis):\n    shape = in_data.shape\n    input_data = relay.var(\"input_data\", shape=shape, dtype=in_dtype)\n    input_zero_point = relay.const(quant_args[\"in_zero_point\"], \"int32\")\n    input_scale = relay.const(quant_args[\"in_scale\"], \"float32\")\n    quantized_output = relay.qnn.op.dequantize(\n        input_data, input_scale=input_scale, input_zero_point=input_zero_point, axis=axis\n    )\n    mod = relay.Function(relay.analysis.free_vars(quantized_output), quantized_output)\n    mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n        rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n        rt_mod.set_input(input_data=in_data)\n        rt_mod.set_input(**params)\n        rt_mod.run()\n        res = rt_mod.get_output(0).numpy()\n        np.testing.assert_equal(res, verify_output_data)\n        assert res.dtype == np.float32\n\n\ndef test_uint8_to_float32():\n    data = np.array([0, 1, 2, 3, 4, 251, 252, 253, 254, 255]).astype(\"uint8\").reshape((2, 5))\n    output = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 62, 62.5, 63, 63.5, 64])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    quant_args = {\"in_zero_point\": 127, \"in_scale\": 0.5}\n    dequantize_test_driver(\n        in_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_int8_to_float32():\n    data = (\n        np.array([-128, -127, -126, -125, -124, 123, 124, 125, 126, 127])\n        .astype(\"int8\")\n        .reshape((2, 5))\n    )\n    output = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 62, 62.5, 63, 63.5, 64])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    quant_args = {\"in_zero_point\": -1, \"in_scale\": 0.5}\n    dequantize_test_driver(\n        in_dtype=\"int8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_scalar_int8_to_float32():\n    data = np.array(-128).astype(\"int8\")\n    output = np.array(-63.5).astype(\"float32\")\n    quant_args = {\"in_zero_point\": -1, \"in_scale\": 0.5}\n    dequantize_test_driver(\n        in_dtype=\"int8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_int32_to_float32():\n    data = np.array([113, 29, -1052]).astype(\"int32\")\n    output = np.array([0.6550452, 0.16810896, -6.098297]).astype(\"float32\")\n    quant_args = {\"in_zero_point\": 0, \"in_scale\": 0.0057968604}\n    dequantize_test_driver(\n        in_dtype=\"int32\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_channelwise_axis_1():\n    data = np.transpose(\n        np.array([0, 1, 2, 3, 4, 243, 247, 249, 250, 251]).astype(\"uint8\").reshape((2, 5))\n    )\n    output = np.transpose(\n        np.array([-63.5, -63, -62.5, -62, -61.5, 30, 31, 31.5, 31.75, 32])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    quant_args = {\n        \"in_zero_point\": np.array([127, 123]).astype(\"int32\"),\n        \"in_scale\": np.array([0.5, 0.25]).astype(\"float32\"),\n    }\n\n    dequantize_test_driver(\n        in_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_channelwise_axis_0():\n    data = np.array([0, 1, 2, 3, 4, 243, 247, 249, 250, 251]).astype(\"uint8\").reshape((2, 5))\n    output = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 30, 31, 31.5, 31.75, 32])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    quant_args = {\n        \"in_zero_point\": np.array([127, 123]).astype(\"int32\"),\n        \"in_scale\": np.array([0.5, 0.25]).astype(\"float32\"),\n    }\n\n    dequantize_test_driver(\n        in_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=0\n    )\n\n\ndef test_per_tensor_vector_args():\n    data = np.array([0, 1, 2, 3, 4, 251, 252, 253, 254, 255]).astype(\"uint8\")\n    output = np.array([-63.5, -63, -62.5, -62, -61.5, 62, 62.5, 63, 63.5, 64]).astype(\"float32\")\n\n    quant_args = {\n        \"in_zero_point\": np.array([127]).astype(\"int32\"),\n        \"in_scale\": np.array([0.5]).astype(\"float32\"),\n    }\n\n    dequantize_test_driver(\n        in_dtype=\"uint8\", quant_args=quant_args, in_data=data, verify_output_data=output, axis=-1\n    )\n\n\ndef test_dynamic_dequantize():\n    x = relay.var(\"x\", shape=(1, 2, 3, 4), dtype=\"int8\")\n    scale_var = relay.var(\"scale\", shape=(), dtype=\"float32\")\n    zp_var = relay.var(\"zp\", shape=(), dtype=\"int32\")\n\n    deq_x = relay.qnn.op.dequantize(x, scale_var * scale_var, zp_var + zp_var)\n    tt = run_infer_type(deq_x)\n\n    assert tt.checked_type == relay.TensorType((1, 2, 3, 4), \"float32\")\n    func = relay.Function([x, scale_var, zp_var], deq_x)\n    data = np.random.uniform(size=(1, 2, 3, 4)).astype(\"int8\")\n    scale = np.array(1).astype(\"float32\")\n    zp = np.array(0).astype(\"int32\")\n\n    mod = tvm.ir.IRModule.from_expr(func)\n\n    for target, dev in tvm.testing.enabled_targets():\n        # TODO: (electriclilies) enable AlterOpLayout when it is fixed\n        with relay.build_config(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            lib = relay.build(mod, target=target)\n\n    module = graph_executor.GraphModule(lib[\"default\"](dev))\n    module.set_input(**{\"x\": data, \"scale\": scale, \"zp\": zp})\n    module.run()\n\n\nif __name__ == \"__main__\":\n    test_uint8_to_float32()\n    test_int8_to_float32()\n    test_scalar_int8_to_float32()\n    test_int32_to_float32()\n    test_channelwise_axis_1()\n    test_channelwise_axis_0()\n    test_dynamic_dequantize()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_leaky_relu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\n\n\ndef dequantize(data, scale, zp):\n    return scale * (np.asarray(data) - zp)\n\n\ndef generate_golden_output(x_data, dequantized_x, alpha, o_scale, o_zero_point, i_zero_point):\n    prod = np.multiply(dequantized_x, alpha)\n    prod = np.around(prod / o_scale + o_zero_point)\n\n    q_min = np.iinfo(np.uint8).min\n    q_max = np.iinfo(np.uint8).max\n    prod = np.clip(prod, q_min, q_max)\n\n    requantized = np.clip(np.round(dequantized_x / o_scale + o_zero_point), q_min, q_max)\n\n    output = np.where(x_data < i_zero_point, prod, requantized)\n    return output\n\n\ndef test_qnn_leaky_relu():\n    data_dtype = \"uint8\"\n    input_scale = 0.125\n    input_zero_point = 60\n    output_scale = 0.6\n    output_zero_point = 17\n    alpha = 0.9\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.qnn.op.leaky_relu(\n        x=x,\n        alpha=alpha,\n        input_scale=relay.const(input_scale, \"float32\"),\n        input_zero_point=relay.const(input_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 133, 0, 9)).reshape((1, 4))\n    x_dequantized = dequantize(x_data, input_scale, input_zero_point)\n    golden_output = generate_golden_output(\n        x_data, x_dequantized, alpha, output_scale, output_zero_point, input_zero_point\n    )\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(x_data)\n\n    np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\nif __name__ == \"__main__\":\n    test_qnn_leaky_relu()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_mul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nimport tvm.topi.testing\n\n# \"unquantize\" a quantized tensor\ndef recover(data, scale, zp):\n    return scale * (np.asarray(data) - zp)\n\n\ndef generate_golden_output(x_recovered, y_recovered, scale, zp):\n    mul = x_recovered * y_recovered\n    output = np.around(mul / scale + zp)\n\n    q_min = np.iinfo(np.uint8).min\n    q_max = np.iinfo(np.uint8).max\n    return np.clip(output, q_min, q_max)\n\n\ndef test_tflite_same_io_qnn_params():\n    data_dtype = \"uint8\"\n\n    lhs_scale = rhs_scale = output_scale = 0.00784314\n    lhs_zero_point = rhs_zero_point = output_zero_point = 127\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.mul(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(lhs_scale, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zero_point, \"int32\"),\n        rhs_scale=relay.const(rhs_scale, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_datas = [\n        np.array((1, 153, 2, 178)).reshape((1, 4)),\n        np.array((25, 1, 178, 216)).reshape((1, 4)),\n        np.array((25, 153, 1, 165)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((204, 178, 1, 8)).reshape((1, 4)),\n        np.array((204, 178, 191, 1)).reshape((1, 4)),\n        np.array((204, 178, 1, 191)).reshape((1, 4)),\n    ]\n\n    for i in range(0, 3):\n        x_data = x_datas[i]\n        y_data = y_datas[i]\n\n        x_rec = recover(x_data, lhs_scale, lhs_zero_point)\n        y_rec = recover(y_data, rhs_scale, rhs_zero_point)\n        golden = generate_golden_output(x_rec, y_rec, output_scale, output_zero_point)\n\n        op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n            x_data, y_data\n        )\n\n        np.testing.assert_equal(op_res.numpy(), np.uint8(golden))\n\n\ndef test_tflite_different_io_qnn_params():\n    data_dtype = \"uint8\"\n\n    lhs_scale = 0.0156863\n    lhs_zero_point = 127\n    rhs_scale = 0.0117647\n    rhs_zero_point = 85\n    output_scale = 0.0235294\n    output_zero_point = 128\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.mul(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(lhs_scale, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zero_point, \"int32\"),\n        rhs_scale=relay.const(rhs_scale, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_datas = [\n        np.array((76, 140, 153, 172)).reshape((1, 4)),\n        np.array((133, 140, 146, 153)).reshape((1, 4)),\n        np.array((76, 140, 172, 146)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((136, 119, 128, 17)).reshape((1, 4)),\n        np.array((136, 119, 111, 94)).reshape((1, 4)),\n        np.array((136, 119, 17, 128)).reshape((1, 4)),\n    ]\n\n    for i in range(0, 3):\n        x_data = x_datas[i]\n        y_data = y_datas[i]\n\n        x_rec = recover(x_data, lhs_scale, lhs_zero_point)\n        y_rec = recover(y_data, rhs_scale, rhs_zero_point)\n        golden = generate_golden_output(x_rec, y_rec, output_scale, output_zero_point)\n\n        op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n            x_data, y_data\n        )\n        np.testing.assert_equal(op_res.numpy(), np.uint8(golden))\n\n\ndef test_saturation():\n    # Same params\n    data_dtype = \"uint8\"\n    lhs_scale = rhs_scale = output_scale = 0.125\n    lhs_zero_point = rhs_zero_point = output_zero_point = 0\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    z = relay.qnn.op.mul(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(lhs_scale, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zero_point, \"int32\"),\n        rhs_scale=relay.const(rhs_scale, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 1, 1, 0)).reshape((1, 4))\n    y_data = np.array((255, 255, 128, 0)).reshape((1, 4))\n\n    x_rec = recover(x_data, lhs_scale, lhs_zero_point)\n    y_rec = recover(y_data, rhs_scale, rhs_zero_point)\n\n    golden = generate_golden_output(x_rec, y_rec, output_scale, output_zero_point)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), np.uint8(golden))\n\n    # Same params, different scale\n\n    lhs_scale = rhs_scale = 0.125\n    output_scale = 0.25\n\n    z = relay.qnn.op.mul(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(lhs_scale, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zero_point, \"int32\"),\n        rhs_scale=relay.const(rhs_scale, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 1, 1, 0)).reshape((1, 4))\n    y_data = np.array((255, 255, 127, 0)).reshape((1, 4))\n\n    x_rec = recover(x_data, lhs_scale, lhs_zero_point)\n    y_rec = recover(y_data, rhs_scale, rhs_zero_point)\n\n    golden = generate_golden_output(x_rec, y_rec, output_scale, output_zero_point)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), np.uint8(golden))\n\n    # All params different\n\n    lhs_scale = 0.5\n    rhs_scale = 0.25\n    output_scale = 0.125\n\n    z = relay.qnn.op.mul(\n        lhs=x,\n        rhs=y,\n        lhs_scale=relay.const(lhs_scale, \"float32\"),\n        lhs_zero_point=relay.const(lhs_zero_point, \"int32\"),\n        rhs_scale=relay.const(rhs_scale, \"float32\"),\n        rhs_zero_point=relay.const(rhs_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    x_data = np.array((255, 0, 1, 0)).reshape((1, 4))\n    y_data = np.array((0, 128, 64, 0)).reshape((1, 4))\n\n    x_rec = recover(x_data, lhs_scale, lhs_zero_point)\n    y_rec = recover(y_data, rhs_scale, rhs_zero_point)\n\n    golden = generate_golden_output(x_rec, y_rec, output_scale, output_zero_point)\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n        x_data, y_data\n    )\n    np.testing.assert_equal(op_res.numpy(), np.uint8(golden))\n\n\nif __name__ == \"__main__\":\n    test_tflite_same_io_qnn_params()\n    test_tflite_different_io_qnn_params()\n    test_saturation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay.testing import run_infer_type\n\n\ndef quantize_test_driver(in_dtype, quant_args, axis, out_dtype, in_data, verify_output_data):\n    shape = in_data.shape\n    input_data = relay.var(\"input_data\", shape=shape, dtype=in_dtype)\n    output_zero_point = relay.const(quant_args[\"out_zero_point\"])\n    output_scale = relay.const(quant_args[\"out_scale\"])\n    quantized_output = relay.qnn.op.quantize(\n        input_data,\n        output_scale=output_scale,\n        output_zero_point=output_zero_point,\n        axis=axis,\n        out_dtype=out_dtype,\n    )\n    mod = relay.Function(relay.analysis.free_vars(quantized_output), quantized_output)\n    mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n        rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n        rt_mod.set_input(input_data=in_data)\n        rt_mod.set_input(**params)\n        rt_mod.run()\n        res = rt_mod.get_output(0).numpy()\n        np.testing.assert_equal(res, verify_output_data)\n        assert res.dtype == out_dtype\n\n\ndef test_float32_to_uint8():\n    data = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 62, 62.5, 63, 63.5, 64])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    output = np.array([0, 1, 2, 3, 4, 251, 252, 253, 254, 255]).astype(\"uint8\").reshape((2, 5))\n    quant_args = {\"out_zero_point\": np.int32(127), \"out_scale\": np.float32(0.5)}\n    quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"uint8\",\n        in_data=data,\n        verify_output_data=output,\n    )\n\n\ndef test_float32_to_int8():\n    data = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 62, 62.5, 63, 63.5, 64])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    output = (\n        np.array([-128, -127, -126, -125, -124, 123, 124, 125, 126, 127])\n        .astype(\"int8\")\n        .reshape((2, 5))\n    )\n    quant_args = {\"out_zero_point\": np.int32(-1), \"out_scale\": np.float32(0.5)}\n    quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"int8\",\n        in_data=data,\n        verify_output_data=output,\n    )\n\n\ndef test_scalar_float32_to_int8():\n    data = np.array(-63.5).astype(\"float32\")\n    output = np.array(-128).astype(\"int8\")\n    quant_args = {\"out_zero_point\": np.int32(-1), \"out_scale\": np.float32(0.5)}\n    quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"int8\",\n        in_data=data,\n        verify_output_data=output,\n    )\n\n\ndef test_channelwise_axis_0():\n    data = (\n        np.array([-63.5, -63, -62.5, -62, -61.5, 30, 31, 31.5, 31.75, 32])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    output = np.array([0, 1, 2, 3, 4, 243, 247, 249, 250, 251]).astype(\"uint8\").reshape((2, 5))\n    quant_args = {\n        \"out_zero_point\": np.array([127, 123]).astype(\"int32\"),\n        \"out_scale\": np.array([0.5, 0.25]).astype(\"float32\"),\n    }\n\n    quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=0,\n        out_dtype=\"uint8\",\n        in_data=data,\n        verify_output_data=output,\n    )\n\n\ndef test_channelwise_axis_1():\n    data = np.transpose(\n        np.array([-63.5, -63, -62.5, -62, -61.5, 30, 31, 31.5, 31.75, 32])\n        .astype(\"float32\")\n        .reshape((2, 5))\n    )\n    output = np.transpose(\n        np.array([0, 1, 2, 3, 4, 243, 247, 249, 250, 251]).astype(\"uint8\").reshape((2, 5))\n    )\n    quant_args = {\n        \"out_zero_point\": np.array([127, 123]).astype(\"int32\"),\n        \"out_scale\": np.array([0.5, 0.25]).astype(\"float32\"),\n    }\n\n    quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"uint8\",\n        in_data=data,\n        verify_output_data=output,\n    )\n\n\ndef test_dynamic_quantize():\n    x = relay.var(\"x\", shape=(1, 2, 3, 4), dtype=\"float32\")\n    scale_var = relay.var(\"scale\", shape=(), dtype=\"float32\")\n    zp_var = relay.var(\"zp\", shape=(), dtype=\"int32\")\n\n    q_x = relay.qnn.op.quantize(x, scale_var * scale_var, zp_var + zp_var)\n    tt = run_infer_type(q_x)\n\n    assert tt.checked_type == relay.TensorType((1, 2, 3, 4), \"int8\")\n    func = relay.Function([x, scale_var, zp_var], q_x)\n    data = np.random.uniform(size=(1, 2, 3, 4)).astype(\"float32\")\n    scale = np.array(1).astype(\"float32\")\n    zp = np.array(0).astype(\"int32\")\n\n    mod = tvm.ir.IRModule.from_expr(func)\n\n    for target, dev in tvm.testing.enabled_targets():\n        # TODO: (electriclilies) enable AlterOpLayout when it is fixed\n        with relay.build_config(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            lib = relay.build(mod, target=target)\n\n    module = graph_executor.GraphModule(lib[\"default\"](dev))\n    module.set_input(**{\"x\": data, \"scale\": scale, \"zp\": zp})\n    module.run()\n\n\nif __name__ == \"__main__\":\n    test_float32_to_uint8()\n    test_float32_to_int8()\n    test_scalar_float32_to_int8()\n    test_channelwise_axis_0()\n    test_channelwise_axis_1()\n    test_dynamic_quantize()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_requantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\nroundings = [\"UPWARD\", \"TONEAREST\"]\ncompute_dtypes = [\"float32\", \"float64\", \"int64\"]\n\n\ndef verify(mod, goldens, target=\"llvm\"):\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(mod, target, params=None)\n        golden_data, golden_output = goldens\n        rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n        rt_mod.set_input(\"input_data\", golden_data)\n        rt_mod.set_input(**params)\n        rt_mod.run()\n        res = rt_mod.get_output(0).numpy()\n        np.testing.assert_equal(res, golden_output)\n\n\ndef get_mod(\n    data_shape,\n    data_dtype,\n    out_dtype,\n    input_scale,\n    output_scale,\n    input_zero_point=0,\n    output_zero_point=0,\n    rounding=\"None\",\n    compute_dtype=\"None\",\n    axis=0,\n):\n    input_data = relay.var(\"input_data\", shape=data_shape, dtype=data_dtype)\n    if isinstance(input_scale, float):\n        input_scale_expr = relay.const(input_scale, \"float32\")\n    else:\n        input_scale_expr = relay.const(np.array(input_scale).astype(\"float32\"))\n\n    if isinstance(input_zero_point, float):\n        input_zero_point_expr = relay.const(input_zero_point, \"int32\")\n    else:\n        input_zero_point_expr = relay.const(np.array(input_zero_point).astype(\"int32\"))\n\n    mod = relay.qnn.op.requantize(\n        input_data,\n        input_scale=input_scale_expr,\n        input_zero_point=input_zero_point_expr,\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n        axis=axis,\n        rounding=rounding,\n        compute_dtype=compute_dtype,\n        out_dtype=out_dtype,\n    )\n\n    mod = relay.Function(relay.analysis.free_vars(mod), mod)\n    mod = tvm.IRModule.from_expr(mod)\n    return mod\n\n\ndef test_same_scale():\n    # Have same scales, everything within range\n    golden_data = np.arange(-100, 100, 1).astype(\"int32\")\n    golden_output = golden_data\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(200,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=0.5,\n                output_scale=0.5,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            assert \"right_shift\" not in mod.astext()\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_scalar_same_scale():\n    # Have same scales, everything within range\n    golden_data = np.array(-10).astype(\"int32\")\n    golden_output = golden_data\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=0.5,\n                output_scale=0.5,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            assert \"right_shift\" not in mod.astext()\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_downscale():\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=16,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n\n            # Try positive values\n            # 8 corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.repeat([0, 1, 2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            # -8 corresponds to -0.5. For UPWARD, this is 0\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n            if rounding == \"UPWARD\":\n                golden_output = np.repeat([0, -1, -2], [9, 16, 7])\n            else:\n                golden_output = np.repeat([0, -1, -2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n            # Try a different scale\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=4,\n                rounding=rounding,\n            )\n\n            # Try positive values\n            # 2I corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.repeat([0, 1, 2, 3, 4, 5, 6, 7, 8], [2, 4, 4, 4, 4, 4, 4, 4, 2])\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            # -8 corresponds to -0.5. For UPWARD, this is 0\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n            if rounding == \"UPWARD\":\n                golden_output = np.repeat(\n                    [0, -1, -2, -3, -4, -5, -6, -7, -8], [3, 4, 4, 4, 4, 4, 4, 4, 1]\n                )\n            else:\n                golden_output = np.repeat(\n                    [0, -1, -2, -3, -4, -5, -6, -7, -8], [2, 4, 4, 4, 4, 4, 4, 4, 2]\n                )\n            verify(mod, (golden_data, golden_output))\n\n            # Try uint8 out_dtype\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"uint8\",\n                input_scale=1,\n                output_scale=16,\n                rounding=rounding,\n            )\n\n            # Try positive values\n            # 8 corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.repeat([0, 1, 2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n            # Try uint8 in_dtyope and uint8 out_dtype\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"uint8\",\n                out_dtype=\"uint8\",\n                input_scale=1,\n                output_scale=16,\n                rounding=rounding,\n            )\n\n            # Try positive values\n            # 8 corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.repeat([0, 1, 2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_upscale():\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=2,\n                output_scale=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n\n            # Try positive values\n            # 8 corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.multiply(2, golden_data)\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            # -8 corresponds to -0.5. For UPWARD, this is 0\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n            golden_output = np.multiply(2, golden_data)\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_non_power_of_two():\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=3,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n\n            # Try positive values\n            golden_data = np.multiply(np.arange(0, 32, 1).astype(\"int32\"), 3)\n            golden_output = np.arange(0, 32, 1)\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            golden_data = np.multiply(np.arange(0, -32, -1).astype(\"int32\"), 3)\n            golden_output = np.arange(0, -32, -1)\n            verify(mod, (golden_data, golden_output))\n\n            # Try a different scale\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=3,\n                output_scale=1,\n                rounding=rounding,\n            )\n\n            # Try positive values\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.multiply(golden_data, 3)\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n            golden_output = np.multiply(golden_data, 3)\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_saturation():\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(16,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=0.5,\n                output_scale=0.5,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            golden_data = np.arange(0, 16, 1).astype(\"int32\")\n            golden_data = np.add(120, golden_data)\n            output = np.array(\n                [120, 121, 122, 123, 124, 125, 126, 127, 127, 127, 127, 127, 127, 127, 127, 127]\n            )\n            golden_output = output\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative numbers\n            golden_data = np.arange(0, -16, -1).astype(\"int32\")\n            golden_data = np.add(-120, golden_data)\n            output = np.array(\n                [\n                    -120,\n                    -121,\n                    -122,\n                    -123,\n                    -124,\n                    -125,\n                    -126,\n                    -127,\n                    -128,\n                    -128,\n                    -128,\n                    -128,\n                    -128,\n                    -128,\n                    -128,\n                    -128,\n                ]\n            )\n            golden_output = output\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_zero_point():\n    # Output zero point\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=16,\n                output_zero_point=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n\n            # Try positive values\n            # 8 corresponds to 0.5, resulting in 1\n            golden_data = np.arange(0, 32, 1).astype(\"int32\")\n            golden_output = np.repeat([0, 1, 2], [8, 16, 8])\n            golden_output = np.add(1, golden_output)\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            # -8 corresponds to -0.5. For UPWARD, this is 0\n            golden_data = np.arange(-32, -64, -1).astype(\"int32\")\n            if rounding == \"UPWARD\":\n                golden_output = np.repeat([-2, -3, -4], [9, 16, 7])\n            else:\n                golden_output = np.repeat([-2, -3, -4], [8, 16, 8])\n            golden_output = np.add(1, golden_output)\n            verify(mod, (golden_data, golden_output))\n\n    # Input zero point\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=16,\n                input_zero_point=16,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n\n            # Try positive values\n            golden_data = np.arange(32, 64, 1).astype(\"int32\")\n            golden_output = np.repeat([2, 3, 4], [8, 16, 8])\n            golden_output = np.subtract(golden_output, 1)\n            verify(mod, (golden_data, golden_output))\n\n            # Try negative values\n            golden_data = np.arange(-32, -64, -1).astype(\"int32\")\n            if rounding == \"UPWARD\":\n                golden_output = np.repeat([-2, -3, -4], [9, 16, 7])\n            else:\n                golden_output = np.repeat([-2, -3, -4], [8, 16, 8])\n            golden_output = np.subtract(golden_output, 1)\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_per_channel_same_scale():\n    # Have same scales, everything within range\n    golden_data = np.arange(-5, 5, 1).astype(\"int32\").reshape((5, 2))\n    golden_output = golden_data\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(5, 2),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=[0.5, 0.5],\n                output_scale=0.5,\n                axis=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            verify(mod, (golden_data, golden_output))\n\n    # Change axis\n    golden_data = np.arange(-10, 10, 1).astype(\"int32\").reshape((2, 2, 5))\n    golden_output = golden_data\n\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(2, 2, 5),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=[0.5, 0.5],\n                output_scale=0.5,\n                axis=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_per_channel_different_scale():\n    # Have same scales, everything within range\n    golden_data = np.arange(-5, 5, 1).astype(\"int32\").reshape((5, 2))\n    golden_output = np.array([-5, -2, -3, -1, -1, 0, 1, 1, 3, 2]).reshape((5, 2))\n\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(5, 2),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=[0.5, 0.25],\n                output_scale=0.5,\n                axis=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            verify(mod, (golden_data, golden_output))\n\n    # Change axis\n    golden_data = np.arange(-20, 20, 2).astype(\"int32\").reshape((2, 2, 5))\n    golden_output = np.array(\n        [-20, -18, -16, -14, -12, -5, -4, -3, -2, -1, 0, 2, 4, 6, 8, 5, 6, 7, 8, 9]\n    ).reshape((2, 2, 5))\n\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(2, 2, 5),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=[0.5, 0.25],\n                output_scale=0.5,\n                axis=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            verify(mod, (golden_data, golden_output))\n\n    # Have input scale > output scale\n    golden_data = np.arange(-5, 5, 1).astype(\"int32\").reshape((5, 2))\n    golden_output = np.array([-10, -2, -6, -1, -2, 0, 2, 1, 6, 2]).reshape((5, 2))\n\n    for compute_dtype in compute_dtypes:\n        for rounding in roundings:\n            mod = get_mod(\n                data_shape=(5, 2),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=[1.0, 0.25],\n                output_scale=0.5,\n                axis=1,\n                rounding=rounding,\n                compute_dtype=compute_dtype,\n            )\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_default_cfg_and_no_args():\n    mod = get_mod(\n        data_shape=(32,),\n        data_dtype=\"int32\",\n        out_dtype=\"int8\",\n        input_scale=1,\n        output_scale=16,\n    )\n    golden_data = np.arange(0, -32, -1).astype(\"int32\")\n    golden_output = np.repeat([0, -1, -2], [9, 16, 7])\n    verify(mod, (golden_data, golden_output))\n\n\ndef test_non_default_cfg_and_no_args():\n    for rounding_cfg in roundings:\n        with relay.qnn.op.requantize_config(rounding=rounding_cfg):\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=16,\n            )\n\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n\n            if rounding_cfg == \"UPWARD\":\n                golden_output = np.repeat([0, -1, -2], [9, 16, 7])\n            else:\n                golden_output = np.repeat([0, -1, -2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_default_cfg_and_args():\n    for rounding in roundings:\n        with relay.qnn.op.requantize_config(rounding=\"UPWARD\"):\n            mod = get_mod(\n                data_shape=(32,),\n                data_dtype=\"int32\",\n                out_dtype=\"int8\",\n                input_scale=1,\n                output_scale=16,\n                rounding=rounding,\n            )\n\n            golden_data = np.arange(0, -32, -1).astype(\"int32\")\n\n            if rounding == \"UPWARD\":\n                golden_output = np.repeat([0, -1, -2], [9, 16, 7])\n            else:\n                golden_output = np.repeat([0, -1, -2], [8, 16, 8])\n            verify(mod, (golden_data, golden_output))\n\n\ndef test_non_default_cfg_and_args():\n    for rounding_arg in roundings:\n        for rounding_cfg in roundings:\n            with relay.qnn.op.requantize_config(rounding=rounding_cfg):\n                mod = get_mod(\n                    data_shape=(32,),\n                    data_dtype=\"int32\",\n                    out_dtype=\"int8\",\n                    input_scale=1,\n                    output_scale=16,\n                    rounding=rounding_arg,\n                )\n\n                golden_data = np.arange(0, -32, -1).astype(\"int32\")\n\n                if rounding_arg == \"UPWARD\":\n                    golden_output = np.repeat([0, -1, -2], [9, 16, 7])\n                else:\n                    golden_output = np.repeat([0, -1, -2], [8, 16, 8])\n                verify(mod, (golden_data, golden_output))\n\n\nif __name__ == \"__main__\":\n    test_same_scale()\n    test_scalar_same_scale()\n    test_downscale()\n    test_upscale()\n    test_non_power_of_two()\n    test_saturation()\n    test_zero_point()\n    test_per_channel_same_scale()\n    test_per_channel_different_scale()\n    test_default_cfg_and_no_args()\n    test_non_default_cfg_and_no_args()\n    test_default_cfg_and_args()\n    test_non_default_cfg_and_args()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_simulated_dequantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.topi.nn.qnn import SQNN_DTYPE_TO_CODE\n\n\ndef dequantize_test_driver(in_dtype, quant_args, axis, in_data):\n    shape = in_data.shape\n    input_data = relay.var(\"input_data\", shape=shape, dtype=in_dtype)\n    input_zero_point = relay.const(quant_args[\"in_zero_point\"])\n    input_scale = relay.const(quant_args[\"in_scale\"])\n    dequantized_output = relay.qnn.op.dequantize(\n        input_data,\n        input_scale=input_scale,\n        input_zero_point=input_zero_point,\n        axis=axis,\n    )\n    mod = relay.Function(relay.analysis.free_vars(dequantized_output), dequantized_output)\n    mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n    rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n    rt_mod.set_input(input_data=in_data)\n    rt_mod.set_input(**params)\n    rt_mod.run()\n    res = rt_mod.get_output(0).numpy()\n    return res\n\n\ndef build_simulated_dequantize(input_data, scale, zp, dtype, axis=-1):\n    sim_q = relay.qnn.op.simulated_dequantize(\n        input_data,\n        scale,\n        zp,\n        axis=axis,\n        in_dtype=dtype,\n    )\n    mod = tvm.IRModule.from_expr(sim_q)\n    with tvm.transform.PassContext(opt_level=3):\n        vm_exec = relay.vm.compile(mod, \"llvm\", params=None)\n    vm = VirtualMachine(vm_exec, tvm.cpu(0))\n    return vm\n\n\ndef verify_simulated_dequantize_simple(dtype):\n    data = np.random.uniform(low=-128, high=127, size=[2, 5]).astype(dtype)\n    data_fp = data.astype(\"float32\")\n    scale_np = np.float32(0.5)\n    zp_np = np.int32(127)\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[dtype])\n    quant_args = {\"in_zero_point\": zp_np, \"in_scale\": scale_np}\n    dq_out = dequantize_test_driver(\n        in_dtype=dtype,\n        quant_args=quant_args,\n        axis=-1,\n        in_data=data,\n    )\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[])\n    zp = relay.var(\"zp\", shape=[], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_dequantize(input_data, scale, zp, dtype)\n    sim_dq_out = vm.invoke(\"main\", input_data=data_fp, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    np.testing.assert_allclose(sim_dq_out.numpy(), dq_out, rtol=1e-5)\n\n\ndef test_simulated_dequantize():\n    verify_simulated_dequantize_simple(\"uint8\")\n    verify_simulated_dequantize_simple(\"int8\")\n    verify_simulated_dequantize_simple(\"int32\")\n\n\ndef test_dynamic_channels():\n    # Compile simulated quantize once but support either per-channel or scalar params.\n    data = np.random.uniform(low=-64, high=64, size=[2, 5]).astype(\"int8\")\n    data_fp = data.astype(\"float32\")\n    # Test scalar qnn params.\n    scale_np = np.asarray([0.5]).astype(\"float32\")\n    zp_np = np.asarray([0]).astype(\"int32\")\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"int8\"])\n    quant_args = {\"in_zero_point\": zp_np[0], \"in_scale\": scale_np[0]}\n    dq_out = dequantize_test_driver(\n        in_dtype=\"int8\",\n        quant_args=quant_args,\n        axis=0,\n        in_data=data,\n    )\n    # Create variables with undefined shape and run with scalar inputs.\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[relay.Any()], dtype=\"float32\")\n    zp = relay.var(\"zp\", shape=[relay.Any()], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_dequantize(input_data, scale, zp, dtype, axis=0)\n    sim_dq_out = vm.invoke(\"main\", input_data=data_fp, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    np.testing.assert_allclose(sim_dq_out.numpy(), dq_out, rtol=1e-5)\n\n    # Now get the perchannel quantize output and compare without recompiling.\n    scale_np = np.array([0.5, 0.25]).astype(\"float32\")\n    zp_np = np.array([127, 123]).astype(\"int32\")\n\n    # Get the reference quantize output.\n    quant_args = {\"in_zero_point\": zp_np, \"in_scale\": scale_np}\n    dq_out = dequantize_test_driver(\n        in_dtype=\"int8\",\n        quant_args=quant_args,\n        axis=0,\n        in_data=data,\n    )\n    # Run the simulated quantize without recompiling and confirm results match.\n    sim_dq_out = vm.invoke(\"main\", input_data=data_fp, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    np.testing.assert_allclose(sim_dq_out.numpy(), dq_out, rtol=1e-5)\n\n\ndef test_dynamic_dtype():\n    # Compile simulated quantize once but support any type of quantization.\n    data = np.random.uniform(low=0, high=255, size=[2, 5]).astype(\"uint8\")\n    data_fp = data.astype(\"float32\")\n    # Test scalar uint8 to fp32.\n    scale_np = np.asarray([0.5]).astype(\"float32\")\n    zp_np = np.asarray([127]).astype(\"int32\")\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"uint8\"])\n    quant_args = {\"in_zero_point\": zp_np[0], \"in_scale\": scale_np[0]}\n    dq_out = dequantize_test_driver(\n        in_dtype=\"uint8\",\n        quant_args=quant_args,\n        axis=-1,\n        in_data=data,\n    )\n    # Create variables with undefined shape and run with scalar inputs.\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[relay.Any()], dtype=\"float32\")\n    zp = relay.var(\"zp\", shape=[relay.Any()], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_dequantize(input_data, scale, zp, dtype)\n    sim_dq_out = vm.invoke(\"main\", input_data=data_fp, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    np.testing.assert_allclose(sim_dq_out.numpy(), dq_out, rtol=1e-5)\n\n    # Now test int8 to float32 compilation.\n    data = np.random.uniform(low=0, high=255, size=[2, 5]).astype(\"int8\")\n    data_fp = data.astype(\"float32\")\n    # Get the reference quantize output.\n    dq_out = dequantize_test_driver(\n        in_dtype=\"int8\",\n        quant_args=quant_args,\n        axis=-1,\n        in_data=data,\n    )\n    # Run the simulated quantize without recompiling and confirm results match.\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"int8\"])\n    sim_dq_out = vm.invoke(\"main\", input_data=data_fp, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    np.testing.assert_allclose(sim_dq_out.numpy(), dq_out, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_simulated_dequantize()\n    test_dynamic_channels()\n    test_dynamic_dtype()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_simulated_quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.runtime.vm import VirtualMachine\nfrom tvm.topi.nn.qnn import SQNN_DTYPE_TO_CODE\n\n\ndef allclose_with_rounding(a, b):\n    # Find number of mismatches in inputs.\n    mismatch = a != b\n    # Allow some rounding errors due to GPU fp32 arithmetic.\n    assert np.sum(mismatch) <= 3\n\n\ndef quantize_test_driver(in_dtype, quant_args, axis, out_dtype, in_data):\n    shape = in_data.shape\n    input_data = relay.var(\"input_data\", shape=shape, dtype=in_dtype)\n    output_zero_point = relay.const(quant_args[\"out_zero_point\"])\n    output_scale = relay.const(quant_args[\"out_scale\"])\n    quantized_output = relay.qnn.op.quantize(\n        input_data,\n        output_scale=output_scale,\n        output_zero_point=output_zero_point,\n        axis=axis,\n        out_dtype=out_dtype,\n    )\n    mod = relay.Function(relay.analysis.free_vars(quantized_output), quantized_output)\n    mod = tvm.IRModule.from_expr(mod)\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, params = relay.build(mod, \"llvm\", params=None)\n    rt_mod = graph_executor.create(graph, lib, device=tvm.cpu(0))\n    rt_mod.set_input(input_data=in_data)\n    rt_mod.set_input(**params)\n    rt_mod.run()\n    res = rt_mod.get_output(0).numpy()\n    return res\n\n\ndef build_simulated_quantize(input_data, scale, zp, dtype, axis=-1):\n    sim_q = relay.qnn.op.simulated_quantize(\n        input_data,\n        scale,\n        zp,\n        axis=axis,\n        out_dtype=dtype,\n    )\n    mod = tvm.IRModule.from_expr(sim_q)\n    with tvm.transform.PassContext(opt_level=3):\n        vm_exec = relay.vm.compile(mod, \"llvm\", params=None)\n    vm = VirtualMachine(vm_exec, tvm.cpu(0))\n    return vm\n\n\ndef verify_simulated_quantize_simple(dtype):\n    data = np.random.uniform(low=-128, high=127, size=[2, 5]).astype(\"float32\")\n    scale_np = np.float32(0.5)\n    zp_np = np.int32(127)\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[dtype])\n    quant_args = {\"out_zero_point\": zp_np, \"out_scale\": scale_np}\n    q_out = quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=dtype,\n        in_data=data,\n    )\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[])\n    zp = relay.var(\"zp\", shape=[], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_quantize(input_data, scale, zp, dtype)\n    sim_q_out = vm.invoke(\"main\", input_data=data, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    allclose_with_rounding(sim_q_out.numpy(), q_out)\n\n\ndef test_simulated_quantize():\n    verify_simulated_quantize_simple(\"uint8\")\n    verify_simulated_quantize_simple(\"int8\")\n    verify_simulated_quantize_simple(\"int32\")\n\n\ndef test_dynamic_channels():\n    # Compile simulated quantize once but support either per-channel or scalar params.\n    data = np.random.uniform(low=-64, high=64, size=[2, 5]).astype(\"float32\")\n    # Test scalar qnn params.\n    scale_np = np.asarray([0.5]).astype(\"float32\")\n    zp_np = np.asarray([127]).astype(\"int32\")\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"uint8\"])\n    quant_args = {\"out_zero_point\": zp_np[0], \"out_scale\": scale_np[0]}\n    q_out = quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=0,\n        out_dtype=\"uint8\",\n        in_data=data,\n    )\n    # Create variables with undefined shape and run with scalar inputs.\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[relay.Any()], dtype=\"float32\")\n    zp = relay.var(\"zp\", shape=[relay.Any()], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_quantize(input_data, scale, zp, dtype, axis=0)\n    sim_q_out = vm.invoke(\"main\", input_data=data, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    allclose_with_rounding(sim_q_out.numpy(), q_out)\n\n    # Now get the perchannel quantize output and compare without recompiling.\n    scale_np = np.array([0.5, 0.25]).astype(\"float32\")\n    zp_np = np.array([127, 123]).astype(\"int32\")\n\n    # Get the reference quantize output.\n    quant_args = {\"out_zero_point\": zp_np, \"out_scale\": scale_np}\n    q_out = quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=0,\n        out_dtype=\"uint8\",\n        in_data=data,\n    )\n    # Run the simulated quantize without recompiling and confirm results match.\n    sim_q_out = vm.invoke(\"main\", input_data=data, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    allclose_with_rounding(sim_q_out.numpy(), q_out)\n\n\ndef test_dynamic_dtype():\n    # Compile simulated quantize once but support any type of quantization.\n    data = np.random.uniform(low=-64, high=64, size=[2, 5]).astype(\"float32\")\n    # Test scalar float32 to uint8.\n    scale_np = np.asarray([0.5]).astype(\"float32\")\n    zp_np = np.asarray([127]).astype(\"int32\")\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"uint8\"])\n    quant_args = {\"out_zero_point\": zp_np[0], \"out_scale\": scale_np[0]}\n    q_out = quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"uint8\",\n        in_data=data,\n    )\n    # Create variables with undefined shape and run with scalar inputs.\n    input_data = relay.var(\"input_data\", shape=data.shape, dtype=\"float32\")\n    scale = relay.var(\"scale\", shape=[relay.Any()], dtype=\"float32\")\n    zp = relay.var(\"zp\", shape=[relay.Any()], dtype=\"int32\")\n    dtype = relay.var(\"dtype\", shape=[], dtype=\"int32\")\n    vm = build_simulated_quantize(input_data, scale, zp, dtype)\n    sim_q_out = vm.invoke(\"main\", input_data=data, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    allclose_with_rounding(sim_q_out.numpy(), q_out)\n\n    # Now test float32 to int32 compilation.\n    # Get the reference quantize output.\n    q_out = quantize_test_driver(\n        in_dtype=\"float32\",\n        quant_args=quant_args,\n        axis=-1,\n        out_dtype=\"int32\",\n        in_data=data,\n    )\n    # Run the simulated quantize without recompiling and confirm results match.\n    dtype_np = np.int32(SQNN_DTYPE_TO_CODE[\"int32\"])\n    sim_q_out = vm.invoke(\"main\", input_data=data, scale=scale_np, zp=zp_np, dtype=dtype_np)\n    allclose_with_rounding(sim_q_out.numpy(), q_out)\n\n\nif __name__ == \"__main__\":\n    test_simulated_quantize()\n    test_dynamic_channels()\n    test_dynamic_dtype()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_subtract.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport numpy as np\nfrom tvm import relay\n\n\ndef qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp, data_dtype=\"uint8\"):\n    # all x, y and golden outputs should be of the same length\n    assert len(x_datas) == len(y_datas)\n    assert len(y_datas) == len(golden_outputs)\n\n    x = relay.var(\"x\", shape=(1, 4), dtype=data_dtype)\n    y = relay.var(\"y\", shape=(1, 4), dtype=data_dtype)\n    lhs_scale = relay.const(scale_and_zp[\"lhs_scale\"], \"float32\")\n    lhs_zp = relay.const(scale_and_zp[\"lhs_zp\"], \"int32\")\n    rhs_scale = relay.const(scale_and_zp[\"rhs_scale\"], \"float32\")\n    rhs_zp = relay.const(scale_and_zp[\"rhs_zp\"], \"int32\")\n    output_scale = relay.const(scale_and_zp[\"output_scale\"], \"float32\")\n    output_zp = relay.const(scale_and_zp[\"output_zp\"], \"int32\")\n    z = relay.qnn.op.subtract(\n        lhs=x,\n        rhs=y,\n        lhs_scale=lhs_scale,\n        lhs_zero_point=lhs_zp,\n        rhs_scale=rhs_scale,\n        rhs_zero_point=rhs_zp,\n        output_scale=output_scale,\n        output_zero_point=output_zp,\n    )\n    func = relay.Function([x, y], z)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n    for i in range(0, len(x_datas)):\n        x_data = x_datas[i]\n        y_data = y_datas[i]\n        golden_output = golden_outputs[i]\n        op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(\n            x_data, y_data\n        )\n        np.testing.assert_equal(op_res.numpy(), golden_output)\n\n\ndef test_tflite_same_io_qnn_params():\n    scale_and_zp = {\n        \"lhs_scale\": 0.00784314,\n        \"lhs_zp\": 127,\n        \"rhs_scale\": 0.00784314,\n        \"rhs_zp\": 127,\n        \"output_scale\": 0.00784314,\n        \"output_zp\": 127,\n    }\n    x_datas = [\n        np.array((140, 153, 165, 178)).reshape((1, 4)),\n        np.array((25, 153, 178, 216)).reshape((1, 4)),\n        np.array((25, 153, 216, 165)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((204, 178, 165, 140)).reshape((1, 4)),\n        np.array((204, 178, 191, 25)).reshape((1, 4)),\n        np.array((204, 178, 25, 191)).reshape((1, 4)),\n    ]\n    golden_outputs = [\n        np.array((63, 102, 127, 165)).reshape((1, 4)),\n        np.array((0, 102, 114, 255)).reshape((1, 4)),\n        np.array((0, 102, 255, 101)).reshape((1, 4)),\n    ]\n    qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp)\n\n\ndef test_tflite_different_io_qnn_params():\n    scale_and_zp = {\n        \"lhs_scale\": 0.0156863,\n        \"lhs_zp\": 127,\n        \"rhs_scale\": 0.0117647,\n        \"rhs_zp\": 85,\n        \"output_scale\": 0.0235294,\n        \"output_zp\": 128,\n    }\n    x_datas = [\n        np.array((76, 140, 153, 172)).reshape((1, 4)),\n        np.array((133, 140, 146, 153)).reshape((1, 4)),\n        np.array((76, 140, 172, 146)).reshape((1, 4)),\n    ]\n    y_datas = [\n        np.array((136, 119, 128, 17)).reshape((1, 4)),\n        np.array((136, 119, 111, 94)).reshape((1, 4)),\n        np.array((136, 119, 17, 128)).reshape((1, 4)),\n    ]\n    golden_outputs = [\n        np.array((68, 120, 123, 192)).reshape((1, 4)),\n        np.array((106, 120, 128, 140)).reshape((1, 4)),\n        np.array((68, 120, 192, 119)).reshape((1, 4)),\n    ]\n    qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp)\n\n\ndef test_saturation():\n    # Same params\n    scale_and_zp = {\n        \"lhs_scale\": 0.125,\n        \"lhs_zp\": 0,\n        \"rhs_scale\": 0.125,\n        \"rhs_zp\": 0,\n        \"output_scale\": 0.125,\n        \"output_zp\": 0,\n    }\n    x_data = [np.array((255, 1, 1, 0)).reshape((1, 4))]\n    y_data = [np.array((255, 255, 128, 0)).reshape((1, 4))]\n    golden_output = [np.array((0, 0, 0, 0)).reshape((1, 4))]\n    qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp)\n\n    # Same params, different scale\n    scale_and_zp = {\n        \"lhs_scale\": 0.125,\n        \"lhs_zp\": 0,\n        \"rhs_scale\": 0.125,\n        \"rhs_zp\": 0,\n        \"output_scale\": 0.25,\n        \"output_zp\": 0,\n    }\n    x_data = [np.array((255, 1, 200, 0)).reshape((1, 4))]\n    y_data = [np.array((255, 255, 127, 0)).reshape((1, 4))]\n    golden_output = [np.array((0, 0, 36, 0)).reshape((1, 4))]\n    qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp)\n\n    # All params different\n    scale_and_zp = {\n        \"lhs_scale\": 0.5,\n        \"lhs_zp\": 0,\n        \"rhs_scale\": 0.25,\n        \"rhs_zp\": 0,\n        \"output_scale\": 0.125,\n        \"output_zp\": 0,\n    }\n    x_data = [np.array((255, 0, 1, 0)).reshape((1, 4))]\n    y_data = [np.array((0, 128, 64, 0)).reshape((1, 4))]\n    golden_output = [np.array((255, 0, 0, 0)).reshape((1, 4))]\n    qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp)\n\n\nif __name__ == \"__main__\":\n    test_tflite_same_io_qnn_params()\n    test_tflite_different_io_qnn_params()\n    test_saturation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_op_qnn_unary_elementwise.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom typing import Callable, List\n\nimport numpy as np\nimport pytest\nimport scipy.special\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.qnn.op.legalizations import hardswish_func\n\n\ndef dequantize(data, scale, zp):\n    return scale * (np.asarray(data) - zp)\n\n\ndef generate_golden_output(\n    floating_point_golden_func, dequantized_x, output_scale, output_zero_point, dtype\n):\n    output = floating_point_golden_func(dequantized_x)\n    output = np.around(output / output_scale + output_zero_point)\n\n    np_dtype = {\"int8\": np.int8, \"uint8\": np.uint8}[dtype]\n\n    q_min = np.iinfo(np_dtype).min\n    q_max = np.iinfo(np_dtype).max\n    return np.clip(output, q_min, q_max)\n\n\ndef run_qnn_func(func: relay.Function, args: List[relay.Expr]):\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    mod = relay.qnn.transform.Legalize()(mod)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    func = mod[\"main\"]\n\n    op_res = relay.create_executor(\"graph\", device=tvm.cpu(0), target=\"llvm\").evaluate(func)(*args)\n    return op_res.numpy()\n\n\ndef create_qnn_func(\n    qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],\n    x_data: np.ndarray,\n    input_scale: float,\n    input_zero_point: int,\n    output_scale: float,\n    output_zero_point: int,\n    input_dtype: str = \"uint8\",\n):\n    x = relay.var(\"x\", shape=x_data.shape, dtype=input_dtype)\n    y = qnn_op(\n        x=x,\n        scale=relay.const(input_scale, \"float32\"),\n        zero_point=relay.const(input_zero_point, \"int32\"),\n        output_scale=relay.const(output_scale, \"float32\"),\n        output_zero_point=relay.const(output_zero_point, \"int32\"),\n    )\n    return relay.Function([x], y)\n\n\ndef run_condition(\n    qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],\n    floating_point_golden_func: Callable[[np.ndarray], np.ndarray],\n    x_data: np.ndarray,\n    input_scale: float,\n    input_zero_point: int,\n    output_scale: float,\n    output_zero_point: int,\n    input_dtype: str = \"uint8\",\n):\n    func = create_qnn_func(\n        qnn_op,\n        x_data,\n        input_scale=input_scale,\n        input_zero_point=input_zero_point,\n        output_scale=output_scale,\n        output_zero_point=output_zero_point,\n        input_dtype=input_dtype,\n    )\n\n    x_dequantized = dequantize(x_data, input_scale, input_zero_point)\n    golden_output = generate_golden_output(\n        floating_point_golden_func,\n        x_dequantized,\n        output_scale,\n        output_zero_point,\n        dtype=input_dtype,\n    )\n\n    op_res = run_qnn_func(func, [x_data])\n    np.testing.assert_equal(op_res, golden_output.astype(input_dtype))\n\n\ndef generic_test(\n    qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],\n    floating_point_golden_func: Callable[[np.ndarray], np.ndarray],\n    input_dtype: str = \"uint8\",\n    x_data: np.ndarray = np.arange(0, 256, dtype=\"uint8\"),\n):\n    x_data = x_data.view(input_dtype)\n    return run_condition(\n        qnn_op,\n        floating_point_golden_func,\n        x_data,\n        input_scale=0.125,\n        input_zero_point=0,\n        output_scale=0.125,\n        output_zero_point=0,\n        input_dtype=input_dtype,\n    )\n\n\nclass TestRSqrt:\n    def test_saturation(self):\n        # Same qparams in and out\n        x_data = np.array((255, 133, 0, 9)).reshape((1, 4))\n        run_condition(\n            relay.qnn.op.rsqrt,\n            lambda x: 1 / np.sqrt(x),\n            x_data,\n            input_scale=0.125,\n            input_zero_point=0,\n            output_scale=0.125,\n            output_zero_point=0,\n            input_dtype=\"uint8\",\n        )\n\n        # Different scale\n        run_condition(\n            relay.qnn.op.rsqrt,\n            lambda x: 1 / np.sqrt(x),\n            x_data,\n            input_scale=0.125,\n            input_zero_point=0,\n            output_scale=0.25,\n            output_zero_point=0,\n            input_dtype=\"uint8\",\n        )\n\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.rsqrt, lambda x: 1 / np.sqrt(x), input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(\n            relay.qnn.op.rsqrt,\n            lambda x: 1 / np.sqrt(x),\n            input_dtype=\"int8\",\n            x_data=np.arange(1, 128, dtype=\"int8\"),\n        )\n\n\nclass Sqrt:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.sqrt, np.sqrt, input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(\n            relay.qnn.op.sqrt,\n            np.sqrt,\n            input_dtype=\"int8\",\n            x_data=np.arange(1, 128, dtype=\"int8\"),\n        )\n\n\nclass TestExp:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.exp, np.exp, input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(relay.qnn.op.exp, np.exp, input_dtype=\"int8\")\n\n\nclass TestTanh:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.tanh, np.tanh, input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(relay.qnn.op.tanh, np.tanh, input_dtype=\"int8\")\n\n\nclass TestErf:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.erf, scipy.special.erf, input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(relay.qnn.op.erf, scipy.special.erf, input_dtype=\"int8\")\n\n\nclass TestSigmoid:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.sigmoid, lambda x: 1 / (1 + np.exp(-x)), input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(relay.qnn.op.sigmoid, lambda x: 1 / (1 + np.exp(-x)), input_dtype=\"int8\")\n\n\nclass TestHardswish:\n    def test_all_numbers_uint8(self):\n        generic_test(relay.qnn.op.hardswish, hardswish_func, input_dtype=\"uint8\")\n\n    def test_all_numbers_int8(self):\n        generic_test(relay.qnn.op.hardswish, hardswish_func, input_dtype=\"int8\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_param_dict.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te, runtime\nimport json\nimport base64\nfrom tvm._ffi.base import py_str\nfrom tvm.relay.op import add\nfrom tvm import relay\nfrom tvm import rpc\nfrom tvm.contrib import utils, graph_executor\n\n\ndef test_save_load():\n    x = np.ones((10, 2)).astype(\"float32\")\n    y = np.ones((1, 2, 3)).astype(\"float32\")\n    params = {\"x\": x, \"y\": y}\n    param_bytes = runtime.save_param_dict(params)\n    assert isinstance(param_bytes, bytearray)\n    param2 = relay.load_param_dict(param_bytes)\n    assert len(param2) == 2\n    np.testing.assert_equal(param2[\"x\"].numpy(), x)\n    np.testing.assert_equal(param2[\"y\"].numpy(), y)\n\n\ndef test_ndarray_reflection():\n    # Make two `NDArrayWrapper`s that point to the same underlying array.\n    np_array = np.random.uniform(size=(10, 2)).astype(\"float32\")\n    tvm_array = tvm.nd.array(np_array)\n    param_dict = {\"x\": tvm_array, \"y\": tvm_array}\n    assert param_dict[\"x\"].same_as(param_dict[\"y\"])\n    # Serialize then deserialize `param_dict`.\n    deser_param_dict = relay.load_param_dict(runtime.save_param_dict(param_dict))\n    # Make sure the data matches the original data and `x` and `y` contain the same data.\n    np.testing.assert_equal(deser_param_dict[\"x\"].numpy(), tvm_array.numpy())\n    # Make sure `x` and `y` contain the same data.\n    np.testing.assert_equal(deser_param_dict[\"x\"].numpy(), deser_param_dict[\"y\"].numpy())\n\n\ndef test_bigendian_rpc_param():\n    \"\"\"Test big endian rpc when there is a PowerPC RPC server available\"\"\"\n    host = os.environ.get(\"TVM_POWERPC_TEST_HOST\", None)\n    port = os.environ.get(\"TVM_POWERPC_TEST_PORT\", 9090)\n    if host is None:\n        return\n\n    def verify_graph_executor(remote, target, shape, dtype):\n        x = relay.var(\"x\")\n        y = relay.const(1)\n        z = relay.add(x, y)\n        func = relay.Function([x], z)\n\n        x_in = np.ones(shape).astype(dtype)\n        params = {\"x\": x_in}\n        graph, lib, params = relay.build(func, target=target, params=params)\n\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"dev_lib.o\")\n        lib.save(path_dso)\n        remote.upload(path_dso)\n        lib = remote.load_module(\"dev_lib.o\")\n        dev = remote.cpu(0)\n        mod = graph_executor.create(graph, lib, dev)\n        mod.load_params(runtime.save_param_dict(params))\n        mod.run()\n        out = mod.get_output(0, tvm.nd.empty(shape, dtype=dtype, device=dev))\n        tvm.testing.assert_allclose(x_in + 1, out.numpy())\n\n    print(\"Test RPC connection to PowerPC...\")\n    remote = rpc.connect(host, port)\n    target = \"llvm -mtriple=powerpc-linux-gnu\"\n    for dtype in [\"float32\", \"float64\", \"int32\", \"int8\"]:\n        verify_graph_executor(remote, target, (10,), dtype)\n\n\nif __name__ == \"__main__\":\n    test_save_load()\n    test_ndarray_reflection()\n    test_bigendian_rpc_param()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_alter_op_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test alter op layout pass\"\"\"\nimport pytest\n\nimport tvm\nfrom tvm import relay, topi\nfrom tvm.relay import transform, analysis\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\nfrom tvm.relay.testing import run_infer_type\nimport numpy as np\nimport tvm.testing\nfrom tvm.relay import testing\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_alter_op():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        weight = relay.multiply(weight, relay.const(2.0, \"float32\"))\n        return relay.nn.conv2d(data, weight, **attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            relay.multiply(weight, relay.const(2.0, \"float32\")),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_return_none():\n    \"\"\"Test doing nothing by returning 'None'\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        y = relay.nn.global_max_pool2d(x)\n        y = relay.Function([x], y)\n        return y\n\n    called = [False]\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        called[0] = True\n        return None\n\n    with TempOpAttr(\"nn.global_max_pool2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(before(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n    assert called[0]\n\n\ndef test_alter_layout():\n    \"\"\"Test alternating the layout of a conv2d.\n    The layout of broadcast operators and the weight should be changed accordingly.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\")\n        weight = relay.var(\"weight\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.bias_add(y, bias)\n        # a useless tuple, which will be eliminated\n        y = relay.Tuple([y])[0]\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2))\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW16i\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        w = relay.layout_transform(weight, \"OIHW\", \"OIHW16i\")\n        y = relay.nn.conv2d(\n            y,\n            w,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            kernel_layout=\"OIHW16i\",\n            data_layout=\"NCHW16c\",\n        )\n        b = relay.expand_dims(bias, axis=1, num_newaxis=2)\n        b = relay.expand_dims(b, axis=0, num_newaxis=1)\n        b = relay.layout_transform(b, \"NCHW\", \"NCHW16c\")\n        y = relay.add(y, b)\n\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NCHW16c\")\n        y = relay.cast(y, \"int32\")\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_multi():\n    \"\"\"Test alternating the layout of a conv2d.\n    The layout of broadcast operators and the weight should be changed accordingly.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\")\n        y = relay.nn.conv2d(x, weight, channels=128, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        new_attrs[\"kernel_layout\"] = \"OHWI16i64o2i\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(128, 64, 3, 3))\n\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        w = relay.layout_transform(weight, \"OIHW\", \"OHWI16i64o2i\")\n        y = relay.nn.conv2d(\n            y,\n            w,\n            channels=128,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            kernel_layout=\"OHWI16i64o2i\",\n            data_layout=\"NCHW16c\",\n        )\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_lrn():\n    \"\"\"Test alternating the layout of a conv2d.\n    The layout of broadcast operators and the weight should be changed accordingly.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\")\n        weight = relay.var(\"weight\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2))\n        y = relay.nn.lrn(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW16i\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        w = relay.layout_transform(weight, \"OIHW\", \"OIHW16i\")\n        y = relay.nn.conv2d(\n            y,\n            w,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            kernel_layout=\"OIHW16i\",\n            data_layout=\"NCHW16c\",\n        )\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NCHW16c\")\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.nn.lrn(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_dual_path():\n    \"\"\"\n    Test alternating the layout with two outputs.\n    One path continues to use the new layout while one path fall backs to old layout.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y1 = relay.nn.conv2d(y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.batch_flatten(y)\n        ret = relay.Tuple([y1, y2])\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.nn.relu(y)\n        y1 = relay.nn.conv2d(\n            y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y1 = relay.nn.relu(y1)\n        y1 = relay.layout_transform(y1, \"NCHW16c\", \"NCHW\")\n        y2 = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y2 = relay.nn.batch_flatten(y2)\n        ret = relay.Tuple([y1, y2])\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_resnet():\n    \"\"\"Test alternating the layout of a residual block\n    This also tests the elimination of duplicated transformation.\n    If a same transformation applies to a same node twice, only one transformation will be created.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(x, weight2, channels=32, kernel_size=(1, 1))\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.nn.global_max_pool2d(y)\n        return relay.Function(analysis.free_vars(y), y)\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(x, weight2, channels=32, kernel_size=(1, 1), data_layout=\"NCHW16c\")\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.nn.global_max_pool2d(y, layout=\"NCHW16c\")\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        return relay.Function(analysis.free_vars(y), y)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_broadcast_op():\n    \"\"\"Test boradcast operators\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\", shape=(64,))\n        scale = relay.var(\"scale\", shape=(64, 1, 1))\n        weight = relay.var(\"weight\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.bias_add(y, bias)  # test broadcasting to lhs\n        y = relay.multiply(scale, y)  # test broadcasting to rhs\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        bias = relay.var(\"bias\", shape=(64,))\n        scale = relay.var(\"scale\", shape=(64, 1, 1))\n        weight = relay.var(\"weight\")\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        bias = relay.expand_dims(bias, 1, 2)\n        bias = relay.expand_dims(bias, 0, 1)\n        bias = relay.layout_transform(bias, \"NCHW\", \"NCHW16c\")\n        scale = relay.expand_dims(scale, 0, 1)\n        scale = relay.layout_transform(scale, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.add(y, bias)  # test broadcasting to lhs\n        y = relay.multiply(scale, y)  # test broadcasting to rhs\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_broadcast_scalar_op():\n    \"\"\"Test alternating the layout of a conv2d.\n    The layout of broadcast operators and the weight should be changed accordingly.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 500, 500, 64))\n        kernel = relay.var(\"kernel\", shape=(3, 3, 64, 64), dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=(64,))\n        multiplier1 = relay.var(\"multiplier1\", shape=(1,), dtype=\"float32\")\n        multiplier2 = relay.var(\"multiplier2\", shape=(1, 1), dtype=\"float32\")\n\n        y = relay.nn.conv2d(x, kernel, data_layout=\"NHWC\", kernel_layout=\"HWIO\", kernel_size=(3, 3))\n        y = relay.add(bias, y)\n        y = relay.nn.relu(y)\n\n        y = relay.multiply(multiplier1, y)\n        y = relay.multiply(y, multiplier2)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 500, 500, 64))\n        kernel = relay.var(\"kernel\", shape=(3, 3, 64, 64), dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=(64,))\n        multiplier1 = relay.var(\"multiplier1\", shape=(1,), dtype=\"float32\")\n        multiplier2 = relay.var(\"multiplier2\", shape=(1, 1), dtype=\"float32\")\n\n        b = relay.expand_dims(bias, axis=0, num_newaxis=3)\n        b = relay.layout_transform(b, \"NHWC\", \"NCHW16c\")\n\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, kernel, data_layout=\"NCHW16c\", kernel_layout=\"HWIO\", kernel_size=(3, 3)\n        )\n\n        y = relay.add(b, y)\n        y = relay.nn.relu(y)\n\n        y = relay.multiply(multiplier1, y)\n        y = relay.multiply(y, multiplier2)\n        y = relay.layout_transform(y, \"NCHW16c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_scalar():\n    \"\"\"Test alternating the layout of a conv2d.\n    The layout of broadcast operators and the weight should be changed accordingly.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.add(y, relay.const(1, \"float32\"))\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        w = relay.var(\"weight\")\n\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, w, channels=64, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.add(y, relay.const(1.0, \"float32\"))\n\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_scalar_regression():\n    \"\"\"regression test where scalar fails\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 16))\n        bias = relay.var(\"bias\", shape=(1, 1, 1, 16))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=16,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.add(y, bias)\n        mean = relay.mean(y, axis=3, exclude=True)\n        var = relay.variance(y, axis=3, exclude=True)\n        gamma = relay.var(\"gamma\")\n        beta = relay.var(\"beta\")\n        y = relay.nn.batch_norm(y, gamma, beta, mean, var, axis=3)\n        y = y[0]\n        return relay.Function(analysis.free_vars(y), y)\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 16))\n        bias = relay.var(\"bias\", shape=(1, 1, 1, 16))\n        x = relay.layout_transform(x, src_layout=\"NHWC\", dst_layout=\"NCHW\")\n        x = relay.layout_transform(x, src_layout=\"NCHW\", dst_layout=\"NCHW16c\")\n        weight = relay.layout_transform(weight, src_layout=\"HWIO\", dst_layout=\"OIHW\")\n        y = relay.nn.conv2d(\n            x, weight, channels=16, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        bias = relay.layout_transform(bias, src_layout=\"NHWC\", dst_layout=\"NCHW\")\n        bias = relay.layout_transform(bias, src_layout=\"NCHW\", dst_layout=\"NCHW16c\")\n        add = relay.add(y, bias)\n        mean = relay.mean(add, axis=[1, 4], exclude=True)\n        var = relay.variance(add, axis=[1, 4], exclude=True)\n        denom = relay.const(1.0) / relay.sqrt(var + relay.const(1e-05))\n        gamma = relay.var(\"gamma\", shape=(16,))\n        denom_c16c = denom * relay.layout_transform(gamma, src_layout=\"C\", dst_layout=\"C16c\")\n        denom = relay.layout_transform(denom_c16c, src_layout=\"C16c\", dst_layout=\"C\")\n        denom_expand1 = relay.expand_dims(denom, axis=1, num_newaxis=2)\n        denom_expand2 = relay.expand_dims(denom_expand1, axis=0)\n        denom_nchwc16 = relay.layout_transform(\n            denom_expand2, src_layout=\"NCHW\", dst_layout=\"NCHW16c\"\n        )\n        out = add * denom_nchwc16\n        beta = relay.var(\"beta\", shape=(16,))\n        numerator_c16c = (-mean) * denom_c16c + relay.layout_transform(\n            beta, src_layout=\"C\", dst_layout=\"C16c\"\n        )\n        numerator = relay.layout_transform(numerator_c16c, src_layout=\"C16c\", dst_layout=\"C\")\n        numerator_expand1 = relay.expand_dims(numerator, axis=1, num_newaxis=2)\n        numerator_expand2 = relay.expand_dims(numerator_expand1, axis=0)\n        numerator_nchwc16 = relay.layout_transform(\n            numerator_expand2, src_layout=\"NCHW\", dst_layout=\"NCHW16c\"\n        )\n        out = out + numerator_nchwc16\n        out = relay.layout_transform(out, src_layout=\"NCHW16c\", dst_layout=\"NCHW\")\n        y = relay.layout_transform(out, src_layout=\"NCHW\", dst_layout=\"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        desired_layouts = {\"nn.conv2d\": [\"NCHW\", \"default\"], \"nn.batch_norm\": [\"NHWC\", \"default\"]}\n        a = run_opt_pass(\n            a,\n            [\n                transform.InferType(),\n                relay.transform.ConvertLayout(desired_layouts),\n                transform.SimplifyInference(),\n                transform.CanonicalizeOps(),\n                transform.AlterOpLayout(),\n            ],\n        )\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_concatenate():\n    \"\"\"NCHW, NHWC and corner case concatenate layout transform.\"\"\"\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    # NCHW layout transformation.\n    def before_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y1 = relay.nn.conv2d(y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.concatenate([y, y1], axis=1)\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y1 = relay.nn.conv2d(\n            y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.concatenate([y, y1], axis=1)\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nchw()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nchw(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # NHWC layout transformation.\n    def before_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.nn.conv2d(\n            x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NHWC\"\n        )\n        y1 = relay.nn.conv2d(\n            y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NHWC\"\n        )\n        ret = relay.concatenate([y, y1], axis=3)\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        weight2 = relay.var(\"weight2\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y1 = relay.nn.conv2d(\n            y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.concatenate([y, y1], axis=1)\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_nchw_upsamping_op():\n    \"\"\"Test upsamping operators\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.upsampling(y, scale_h=2, scale_w=2)\n        y = relay.nn.avg_pool2d(y, pool_size=(2, 2), strides=(2, 2))\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\")\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.nn.upsampling(y, scale_h=2, scale_w=2, layout=\"NCHW16c\")\n        y = relay.nn.avg_pool2d(y, pool_size=(2, 2), strides=(2, 2), layout=\"NCHW16c\")\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_nchw_dyn_upsamping_op():\n    \"\"\"Test upsamping operators\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.upsampling(y, scale_h=relay.const(2), scale_w=relay.const(2))\n        y = relay.nn.avg_pool2d(y, pool_size=(2, 2), strides=(2, 2))\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\")\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.nn.upsampling(y, scale_h=relay.const(2), scale_w=relay.const(2), layout=\"NCHW16c\")\n        y = relay.nn.avg_pool2d(y, pool_size=(2, 2), strides=(2, 2), layout=\"NCHW16c\")\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_alter_layout_strided_slice(target, dev):\n    \"\"\"Test rewriting strided_slice during alter_iop_layout\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.strided_slice(y, begin=[0, 16], end=[1, 33], strides=[1, 1])\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW4c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 32, 28, 28))\n        weight = relay.var(\"weight\", shape=(32, 32, 3, 3))\n        weight = relay.layout_transform(weight, \"OIHW\", \"OIHW4i4o\")\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW4c\")\n        y = relay.op.nn.contrib_conv2d_nchwc(\n            x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW4c\"\n        )\n\n        y = relay.strided_slice(y, begin=[0, 4], end=[1, 21], strides=[1, 1])\n\n        y = relay.layout_transform(y, \"NCHW4c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        b = run_opt_pass(expected(), transform.InferType())\n\n    # Verify inference result\n    mod_before = tvm.IRModule()\n    mod_new = tvm.IRModule()\n    mod_before[\"main\"] = a\n    mod_new[\"main\"] = b\n    mod_before = transform.InferType()(mod_before)\n    mod_new = transform.InferType()(mod_new)\n    with relay.build_config(opt_level=3):\n        for kind in [\"graph\", \"debug\", \"vm\"]:\n            np_data = np.random.uniform(size=(1, 32, 28, 28)).astype(\"float32\")\n            np_weight = np.random.uniform(size=(32, 32, 3, 3)).astype(\"float32\")\n            f_before = relay.create_executor(\n                kind, mod=mod_before, device=dev, target=target\n            ).evaluate()\n            result_before = f_before(np_data, np_weight)\n            f_new = relay.create_executor(kind, mod=mod_new, device=dev, target=target).evaluate()\n            result_new = f_new(np_data, np_weight)\n            tvm.testing.assert_allclose(\n                result_before.numpy(), result_new.numpy(), rtol=1e-5, atol=1e-5\n            )\n\n\ndef test_alter_layout_strided_slice_axes_nhwc():\n    \"\"\"Test rewriting strided_slice with axes during alter_iop_layout\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 28, 28, 32))\n        weight = relay.var(\"weight\", shape=(3, 3, 32, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.strided_slice(y, begin=[0, 16], end=[1, 32], strides=[1, 1], axes=[0, 3])\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NHWC4c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 28, 28, 32))\n        weight = relay.var(\"weight\", shape=(3, 3, 32, 32))\n        x = relay.layout_transform(x, \"NHWC\", \"NHWC4c\")\n        y = relay.op.nn.conv2d(\n            x,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC4c\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.strided_slice(y, begin=[0, 4], end=[1, 8], strides=[1, 1], axes=[0, 3])\n        y = relay.layout_transform(y, \"NHWC4c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    mod_before = tvm.IRModule()\n    mod_new = tvm.IRModule()\n    mod_before[\"main\"] = a\n    mod_new[\"main\"] = b\n    assert tvm.ir.structural_equal(mod_before, mod_new)\n\n\ndef test_alter_layout_depthwise_conv2d():\n    \"\"\"Test depthwise_conv2d operator\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 32, 56, 56))\n        w = relay.var(\"w\", shape=(32, 1, 3, 3))\n        y = relay.nn.conv2d(x, w, padding=(1, 1), channels=32, kernel_size=(3, 3), groups=32)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    from tvm import topi\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        with tvm.target.Target(\"llvm -mcpu=core-avx2\"):\n            return topi.nn.conv2d_alter_layout(attrs, inputs, tinfos, out_type)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 32, 56, 56))\n        w = relay.var(\"w\", shape=(32, 1, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NCHW8c\")\n        w = relay.layout_transform(w, \"OIHW\", \"OIHW1i8o\")\n        y = relay.nn.contrib_depthwise_conv2d_nchwc(\n            x,\n            w,\n            padding=(1, 1, 1, 1),\n            channels=32,\n            kernel_size=(3, 3),\n            groups=32,\n            data_layout=\"NCHW8c\",\n            kernel_layout=\"OIHW1i8o\",\n            out_layout=\"NCHW8c\",\n        )\n        y = relay.layout_transform(y, \"NCHW8c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b)\n\n\ndef test_alter_layout_prelu():\n    \"\"\"Test PRelu operator\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\")\n        alpha = relay.var(\"alpha\", relay.IncompleteType())\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.prelu(y, alpha)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        w = relay.var(\"weight\")\n        alpha = relay.var(\"alpha\", relay.IncompleteType())\n\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, w, channels=64, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        y = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        y = relay.nn.prelu(y, alpha)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, [transform.CanonicalizeOps(), transform.AlterOpLayout()])\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b)\n\n\ndef test_alter_layout_pad():\n    \"\"\"Check NCHW, NHWC and corner case for pad layout conversion\"\"\"\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    # Check NCHW conversion.\n    def before_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.nn.pad(y, pad_width=((0, 0), (0, 0), (1, 1), (1, 1)))\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.nn.pad(y, pad_width=((0, 0), (0, 0), (1, 1), (1, 1), (0, 0)))\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nchw()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nchw(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # Check NHWC conversion.\n    def before_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(\n            x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NHWC\"\n        )\n        ret = relay.nn.pad(y, pad_width=((0, 0), (1, 1), (1, 1), (0, 0)))\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.nn.pad(y, pad_width=((0, 0), (0, 0), (1, 1), (1, 1), (0, 0)))\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # Check that conversion does not happen when padding along split axis.\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.nn.pad(y, pad_width=((0, 0), (1, 1), (1, 1), (1, 1)))\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.layout_transform(y, \"NCHW16c\", \"NCHW\")\n        ret = relay.nn.pad(ret, pad_width=((0, 0), (1, 1), (1, 1), (1, 1)))\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_pool():\n    \"\"\"Check NCHW, NHWC pool layout conversion\"\"\"\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    # Check NCHW conversion.\n    def before_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.nn.avg_pool2d(y, pool_size=(1, 1))\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.nn.avg_pool2d(y, pool_size=(1, 1), layout=\"NCHW16c\")\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nchw()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nchw(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # Check NHWC conversion.\n    def before_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(\n            x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NHWC\"\n        )\n        ret = relay.nn.avg_pool2d(y, pool_size=(1, 1), layout=\"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.nn.avg_pool2d(y, pool_size=(1, 1), layout=\"NCHW16c\")\n        ret = relay.layout_transform(ret, \"NCHW16c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_sum():\n    \"\"\"Check NCHW, NHWC sum layout conversion\"\"\"\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    # Check NCHW conversion.\n    def before_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.sum(y, axis=1, keepdims=True)\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.sum(y, axis=[1, 4], keepdims=True)\n        ret = relay.layout_transform(ret, \"NCHW1c\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nchw()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nchw(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # Check NHWC conversion.\n    def before_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.nn.conv2d(\n            x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NHWC\"\n        )\n        ret = relay.sum(y, axis=3, keepdims=True)\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW16c\")\n        y = relay.nn.conv2d(\n            y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1), data_layout=\"NCHW16c\"\n        )\n        ret = relay.sum(y, axis=[1, 4], keepdims=True)\n        ret = relay.layout_transform(ret, \"NCHW1c\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_nhwc_arm():\n    \"\"\"Check that AlterOplayout does not alter NHWC data layout.\"\"\"\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        from tvm import topi\n\n        with tvm.target.Target(\"llvm -device=arm_cpu\"):\n            return topi.nn.conv2d_alter_layout(attrs, inputs, tinfos, out_type)\n\n    # Check NHWC conversion.\n    def before_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64))\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x, weight1, channels=64, kernel_size=(3, 3), data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n        )\n        y = relay.nn.relu(y)\n        y = relay.nn.avg_pool2d(y, pool_size=(1, 1), layout=\"NHWC\")\n        y = relay.nn.conv2d(\n            y, weight2, channels=64, kernel_size=(3, 3), data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected_nhwc():\n        return before_nhwc()\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_layout_nhwc_int8_aarch64():\n    \"\"\"Check that AlterOplayout does not alter NHWC data layout.\"\"\"\n    from tvm import autotvm\n\n    expected_workload_shape = (20, 42, 4, 16)\n\n    # We use Int8Fallback  to disable the fallback flag\n    # and to test the new workload produced during the pass\n    class Int8Fallback(autotvm.FallbackContext):\n        def _query_inside(self, target, workload):\n            key = (target, workload)\n            if key in self.memory:\n                return self.memory[key]\n            cfg = autotvm.task.space.FallbackConfigEntity()\n            cfg.is_fallback = False\n            cfg.cost = 0\n            self.memory[key] = cfg\n            return cfg\n\n        def update(self, target, workload, cfg):\n            key = (str(target), workload)\n            assert workload[2][1] == expected_workload_shape\n            assert workload[0] == \"conv2d_NHWC_quantized_interleaved_without_transform.arm_cpu\"\n            self.memory[key] = cfg\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        from tvm import topi\n\n        with tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\"):\n            with Int8Fallback():\n                tmp = topi.nn.conv2d_alter_layout(attrs, inputs, tinfos, out_type)\n                return tmp\n\n    # Check NHWC conversion.\n    def before_nhwc_int8():\n        x = relay.var(\"x\", shape=(1, 56, 56, 73), dtype=\"int8\")\n        weight = relay.var(\"weight1\", shape=(3, 3, 73, 79), dtype=\"int8\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=79,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected_nhwc_int8():\n        x = relay.var(\"x\", shape=(1, 56, 56, 73), dtype=\"int8\")\n        weight = relay.var(\"weight1\", shape=(3, 3, 73, 79), dtype=\"int8\")\n        tile_rows = 4\n        tile_cols = 16\n        weight_transformed = relay.nn.contrib_conv2d_gemm_weight_transform(\n            weight, tile_rows, tile_cols\n        )\n        y = relay.nn.contrib_conv2d_gemm_without_weight_transform(\n            x,\n            weight_transformed,\n            channels=79,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before_nhwc_int8()\n        a = run_opt_pass(a, transform.AlterOpLayout())\n        b = run_opt_pass(expected_nhwc_int8(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_op_with_global_var():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        mod = tvm.IRModule()\n        foo = relay.GlobalVar(\"foo\")\n        mod[foo] = relay.Function([x, weight], y)\n        mod = transform.InferType()(mod)\n        mod[\"main\"] = relay.Function([x, weight], foo(x, weight))\n        mod = transform.InferType()(mod)\n        return mod\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        weight = relay.multiply(weight, relay.const(2.0, \"float32\"))\n        return relay.nn.conv2d(data, weight, **attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            relay.multiply(weight, relay.const(2.0, \"float32\")),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.nn.relu(y)\n        mod = tvm.IRModule()\n        foo = relay.GlobalVar(\"foo\")\n        mod[foo] = relay.Function([x, weight], y)\n        mod = transform.InferType()(mod)\n        mod[\"main\"] = relay.Function([x, weight], foo(x, weight))\n        return mod\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = before()\n        a = transform.AlterOpLayout()(a)\n        b = transform.InferType()(expected())\n\n    assert tvm.ir.structural_equal(a, b, map_free_vars=True), \"Actual = \\n\" + str(a)\n\n\ndef test_alter_op_dense():\n    def before():\n        x = relay.var(\"x\", shape=(32, 1, 128))\n        weight = relay.var(\"weight\", shape=(48, 64))\n        avg1d = relay.nn.adaptive_avg_pool1d(x, [64])\n        squeeze = relay.squeeze(avg1d, axis=[1])\n        y = relay.nn.dense(squeeze, weight)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(32, 1, 128))\n        weight = relay.var(\"weight\", shape=(48, 64))\n        target_layout = \"NC16n\"\n        weight_transform = relay.layout_transform(weight, \"NC\", target_layout)\n        avg1d = relay.nn.adaptive_avg_pool1d(x, [64])\n        squeeze = relay.squeeze(avg1d, axis=[1])\n        y = relay.nn.contrib_dense_pack(\n            squeeze, weight_transform, target_layout, units=None, out_dtype=\"float32\"\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    target = \"llvm -mcpu=core-avx2\"\n    with tvm.target.Target(target):\n        with TempOpAttr(\n            \"nn.dense\", \"FTVMAlterOpLayout\", topi.x86.dense_alter_op._alter_dense_layout\n        ):\n            a = before()\n            a = run_opt_pass(a, transform.AlterOpLayout())\n            b = run_opt_pass(expected(), transform.InferType())\n            assert tvm.ir.structural_equal(a, b)\n\n\ndef test_not_inplace_modify():\n    def func():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=[2, 2], strides=[2, 2], padding=[0, 0, 0, 0])\n        y = relay.Function([x, weight], y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW16c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW16i\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        before = func()\n        run_opt_pass(before, [transform.AlterOpLayout()])\n        assert before.body.attrs.layout == \"NCHW\"\n\n\ndef test_alter_op_dense_packed_data():\n    def before():\n        x = relay.var(\"x\", shape=(1, 32, 8, 8))\n        weight = relay.var(\"conv2d_weight\", shape=(32, 32, 3, 3))\n        conv = relay.nn.conv2d(x, weight, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        pool = relay.nn.avg_pool2d(conv, pool_size=[8, 8], padding=[0, 0, 0, 0])\n        squeeze = relay.squeeze(pool, axis=[2, 3])\n        dense = relay.nn.dense(squeeze, relay.var(\"dense_weight\", shape=(16, 32)))\n        return relay.Function(analysis.free_vars(dense), dense)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 32, 8, 8))\n        conv_weight = relay.var(\"conv2d_weight\", shape=(32, 32, 3, 3))\n        dense_weight = relay.var(\"dense_weight\", shape=(16, 32))\n        conv = relay.nn.contrib_conv2d_nchwc(\n            relay.layout_transform(x, \"NCHW\", \"NCHW8c\"),\n            relay.layout_transform(conv_weight, \"OIHW\", \"OIHW8i8o\"),\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW8c\",\n            kernel_layout=\"OIHW8i8o\",\n            out_layout=\"NCHW8c\",\n        )\n        pool = relay.nn.avg_pool2d(conv, pool_size=[8, 8], padding=[0, 0, 0, 0], layout=\"NCHW8c\")\n        squeeze = relay.squeeze(pool, axis=[2, 3])\n        dense = relay.nn.contrib_dense_pack(\n            relay.layout_transform(squeeze, \"NC8c\", \"NC\"),\n            relay.layout_transform(dense_weight, \"NC\", \"NC16n\"),\n            \"NC16n\",\n            out_dtype=\"float32\",\n        )\n        return relay.Function(analysis.free_vars(dense), dense)\n\n    with tvm.target.Target(\"llvm -mcpu=core-avx2\"):\n        with TempOpAttr(\n            \"nn.dense\", \"FTVMAlterOpLayout\", topi.x86.dense_alter_op._alter_dense_layout\n        ):\n            a = run_opt_pass(before(), transform.AlterOpLayout())\n            b = run_opt_pass(expected(), transform.InferType())\n            assert tvm.ir.structural_equal(a, b)\n\n\ndef test_conv2d_strided_slice_packed_to_unpacked():\n    \"\"\"We do not support propagating through packed to unpacked layout\"\"\"\n    x_shape = (1, 1, 1, 1, 4)\n    w_shape = (9, 1, 3, 3, 4, 4)\n\n    def before():\n        x = relay.var(\"x\", shape=x_shape)\n        weight = relay.var(\"weight\", shape=w_shape)\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n        )\n        y = relay.strided_slice(y, begin=[0, 0], end=[1, -1], strides=[1, 8])\n        return relay.Function([x, weight], y)\n\n    def expected():\n        x = relay.var(\"x\", shape=x_shape)\n        weight = relay.var(\"weight\", shape=w_shape)\n        x_nchw = relay.layout_transform(x, src_layout=\"NCHW4c\", dst_layout=\"NCHW\")\n        weight_oihw = relay.layout_transform(weight, src_layout=\"OIHW4i4o\", dst_layout=\"OIHW\")\n        y = relay.nn.conv2d(\n            x_nchw,\n            weight_oihw,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.layout_transform(y, src_layout=\"NCHW\", dst_layout=\"NCHW4c\")\n        y = relay.strided_slice(y, begin=[0, 0], end=[1, -1], strides=[1, 8])\n        return relay.Function([x, weight], y)\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW\"\n        new_attrs[\"kernel_layout\"] = \"OIHW\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b)\n\n\ndef test_conv2d_strided_slice_arbitrary_stride():\n    \"\"\"Test rewriting strided_slice with arbitrary stride\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(4, 12, 1, 1))\n        weight = relay.var(\"weight\", shape=(9, 12, 1, 1))\n        y = relay.nn.conv2d(x, weight, channels=9, kernel_size=(1, 1), padding=(0, 0))\n        y = relay.strided_slice(y, begin=[3], end=[6], strides=[3], axes=[1])\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW3c\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        run_opt_pass(before(), transform.AlterOpLayout())\n\n\ndef test_conv2d_reduce_channels():\n    x = relay.var(\"data\", shape=(1, 8, 48, 48))\n    y = relay.nn.conv2d(\n        data=x,\n        weight=relay.var(\"weight\"),\n        kernel_size=(1, 1),\n        channels=8,\n        dilation=1,\n        strides=(47, 47),\n    )\n    z = relay.argmin(y, axis=1)\n\n    mod, params = testing.create_workload(z)\n\n    with tvm.transform.PassContext(opt_level=3):\n        relay.build(mod, params=params, target=\"llvm\")\n\n\ndef test_alter_layout_nonscalar_broadcast():\n    \"\"\"Test boradcast operators\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 16, 3, 3))\n        weight = relay.var(\"weight\", shape=(16, 16, 1, 1))\n        y = relay.nn.conv2d(\n            x, weight, channels=16, kernel_size=(1, 1), padding=(0, 0), data_layout=\"NCHW\"\n        )\n        z = relay.var(\"z\", shape=(1, 3, 3))\n        y = y + z\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16, 3, 3))\n        weight = relay.var(\"weight\", shape=(16, 16, 1, 1))\n        x = relay.layout_transform(x, src_layout=\"NCHW\", dst_layout=\"NCHW4c\")\n        weight = relay.layout_transform(weight, src_layout=\"OIHW\", dst_layout=\"OIHW4i4o\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=16,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n        )\n        z = relay.var(\"z\", shape=(1, 3, 3))\n        z = relay.expand_dims(z, 0)\n        z = relay.layout_transform(z, src_layout=\"NCHW\", dst_layout=\"NCHW1c\")\n        y = y + z\n        y = relay.layout_transform(y, src_layout=\"NCHW4c\", dst_layout=\"NCHW\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW4c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW4i4o\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n\n    inp = np.random.uniform(size=(1, 16, 3, 3)).astype(np.float32)\n    weight = np.random.uniform(size=(16, 16, 1, 1)).astype(np.float32)\n    z = np.random.uniform(size=(1, 3, 3)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight, z)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight, z)\n    np.testing.assert_allclose(res.numpy(), res1.numpy())\n\n\ndef test_alter_layout_blocked_no_broadcast():\n    \"\"\"Test boradcast operators working on already blocked layout\"\"\"\n\n    def before():\n        dtype = \"float32\"\n        input_shape = (1, 8, 16, 16, 4)\n        filter_shape = (1, 8, 4, 4, 4, 4)\n        bias_shape = (1, 1, 1, 1, 4)\n        A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n        B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n        C = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n        conv = relay.nn.conv2d(\n            A,\n            B,\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n            padding=[3, 3, 0, 0],\n            strides=[2, 2],\n            out_dtype=dtype,\n            channels=4,\n            kernel_size=(4, 4),\n        )\n        bias = relay.op.add(conv, C)\n        bias = relay.Function(analysis.free_vars(bias), bias)\n        return bias\n\n    def expected():\n        return before()\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW4c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW4i4o\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n\n    inp = np.random.uniform(size=(1, 8, 16, 16, 4)).astype(np.float32)\n    weight = np.random.uniform(size=(1, 8, 4, 4, 4, 4)).astype(np.float32)\n    z = np.random.uniform(size=(1, 1, 1, 1, 4)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight, z)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight, z)\n    np.testing.assert_allclose(res.numpy(), res1.numpy())\n\n\ndef test_alter_layout_blocked_broadcast():\n    \"\"\"Test boradcast operators working on already blocked layout\"\"\"\n\n    def before():\n        dtype = \"float32\"\n        input_shape = (1, 8, 16, 16, 4)\n        filter_shape = (1, 8, 4, 4, 4, 4)\n        bias_shape = (1, 1, 1, 1, 1)\n        A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n        B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n        C = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n        conv = relay.nn.conv2d(\n            A,\n            B,\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n            padding=[3, 3, 0, 0],\n            strides=[2, 2],\n            out_dtype=dtype,\n            channels=4,\n            kernel_size=(4, 4),\n        )\n        bias = relay.op.add(conv, C)\n        bias = relay.Function(analysis.free_vars(bias), bias)\n        return bias\n\n    def expected():\n        return before()\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW4c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW4i4o\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n\n    inp = np.random.uniform(size=(1, 8, 16, 16, 4)).astype(np.float32)\n    weight = np.random.uniform(size=(1, 8, 4, 4, 4, 4)).astype(np.float32)\n    z = np.random.uniform(size=(1, 1, 1, 1, 1)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight, z)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight, z)\n    np.testing.assert_allclose(res.numpy(), res1.numpy())\n\n\ndef test_alter_layout_re_blocking_broadcast():\n    \"\"\"Test of re-blocking shapes with boradcast operators\"\"\"\n\n    def before():\n        dtype = \"float32\"\n        input_shape = (1, 8, 16, 16, 4)\n        filter_shape = (1, 8, 4, 4, 4, 4)\n        bias_shape = (1, 1, 1, 1, 4)\n        A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n        B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n        C = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n        conv = relay.nn.conv2d(\n            A,\n            B,\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n            padding=[3, 3, 0, 0],\n            strides=[2, 2],\n            out_dtype=dtype,\n            channels=4,\n            kernel_size=(4, 4),\n        )\n        bias = relay.op.add(conv, C)\n        bias = relay.Function(analysis.free_vars(bias), bias)\n        return bias\n\n    def expected():\n        dtype = \"float32\"\n        input_shape = (1, 8, 16, 16, 4)\n        filter_shape = (1, 8, 4, 4, 4, 4)\n        bias_shape = (1, 1, 1, 1, 4)\n        A = relay.var(\"data\", shape=input_shape, dtype=dtype)\n        B = relay.var(\"weight\", shape=filter_shape, dtype=dtype)\n        C = relay.var(\"bias\", shape=bias_shape, dtype=dtype)\n\n        A = relay.layout_transform(A, src_layout=\"NCHW4c\", dst_layout=\"NCHW2c\")\n        B = relay.layout_transform(B, src_layout=\"OIHW4i4o\", dst_layout=\"OIHW2i2o\")\n\n        conv = relay.nn.conv2d(\n            A,\n            B,\n            data_layout=\"NCHW2c\",\n            kernel_layout=\"OIHW2i2o\",\n            padding=[3, 3, 0, 0],\n            strides=[2, 2],\n            out_dtype=dtype,\n            channels=4,\n            kernel_size=(4, 4),\n        )\n        C = relay.layout_transform(C, src_layout=\"NCHW4c\", dst_layout=\"NCHW2c\")\n        bias = relay.op.add(conv, C)\n        bias = relay.layout_transform(bias, src_layout=\"NCHW2c\", dst_layout=\"NCHW4c\")\n        bias = relay.Function(analysis.free_vars(bias), bias)\n        return bias\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW2c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW2i2o\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n\n    inp = np.random.uniform(size=(1, 8, 16, 16, 4)).astype(np.float32)\n    weight = np.random.uniform(size=(1, 8, 4, 4, 4, 4)).astype(np.float32)\n    z = np.random.uniform(size=(1, 1, 1, 1, 4)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight, z)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight, z)\n    np.testing.assert_allclose(res.numpy(), res1.numpy(), rtol=1e-5, atol=1e-5)\n\n\ndef test_broadcast_non_adaptable():\n    \"\"\"NCHW4c + [x, x, 4] and NCHW4c is being altered to NCHW\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 4, 3, 3, 4))\n        weight = relay.var(\"weight\", shape=(4, 4, 1, 1, 4, 4))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=16,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            data_layout=\"NCHW4c\",\n            kernel_layout=\"OIHW4i4o\",\n        )\n        z = relay.var(\"z\", shape=(3, 3, 4))\n        y = y + z\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 4, 3, 3, 4))\n        weight = relay.var(\"weight\", shape=(4, 4, 1, 1, 4, 4))\n        x = relay.layout_transform(x, src_layout=\"NCHW4c\", dst_layout=\"NCHW\")\n        weight = relay.layout_transform(weight, src_layout=\"OIHW4i4o\", dst_layout=\"OIHW\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=16,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        z = relay.var(\"z\", shape=(3, 3, 4))\n        y = relay.layout_transform(y, src_layout=\"NCHW\", dst_layout=\"NCHW4c\")\n        y = y + z\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW\"\n        new_attrs[\"kernel_layout\"] = \"OIHW\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        a = run_opt_pass(before(), transform.AlterOpLayout())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n\n    inp = np.random.uniform(size=(1, 4, 3, 3, 4)).astype(np.float32)\n    weight = np.random.uniform(size=(4, 4, 1, 1, 4, 4)).astype(np.float32)\n    z = np.random.uniform(size=(3, 3, 4)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight, z)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight, z)\n    np.testing.assert_allclose(res.numpy(), res1.numpy())\n\n\ndef test_broadcast_respect_input_layouts():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16, 1, 1))\n        w = relay.var(\"w\", shape=(16, 16, 1, 1))\n        x = relay.nn.conv2d(\n            x,\n            w,\n            kernel_size=(1, 1),\n            padding=(0, 0),\n            channels=16,\n        )\n        y1 = relay.min(x, axis=[2])\n        y2 = relay.min(x, axis=[3])\n        z = y1 + y2\n        z = relay.Function(analysis.free_vars(z), z)\n        return z\n\n    def alter_conv2d(attrs, inputs, tinfos, out_type):\n        data, weight = inputs\n        new_attrs = dict(attrs)\n        new_attrs[\"data_layout\"] = \"NCHW4c\"\n        new_attrs[\"kernel_layout\"] = \"OIHW4i4o\"\n        return relay.nn.conv2d(data, weight, **new_attrs)\n\n    inp = np.random.uniform(size=(1, 16, 1, 1)).astype(np.float32)\n    weight = np.random.uniform(size=(16, 16, 1, 1)).astype(np.float32)\n    mod = tvm.IRModule.from_expr(before())\n    with TempOpAttr(\"nn.conv2d\", \"FTVMAlterOpLayout\", alter_conv2d):\n        with tvm.transform.PassContext(opt_level=4):\n            res = relay.build_module.create_executor(\n                \"graph\", mod, target=\"llvm\", device=tvm.cpu()\n            ).evaluate()(inp, weight)\n    with tvm.transform.PassContext(opt_level=0):\n        res1 = relay.build_module.create_executor(\n            \"debug\", mod, target=\"llvm\", device=tvm.cpu()\n        ).evaluate()(inp, weight)\n    np.testing.assert_allclose(res.numpy(), res1.numpy())\n\n\ndef test_axis_semantic_change():\n    x = relay.var(\"x\", shape=(1, 1, 24, 48))\n    w1 = relay.const(np.random.uniform(size=(1, 1, 1, 1)))\n    w2 = relay.const(np.random.uniform(size=(1, 1, 1, 1)))\n    y = relay.nn.conv2d(x, w1, kernel_size=(1, 1), padding=(0, 0), channels=1)\n    y = relay.transpose(y, (0, 1, 3, 2))\n    z = relay.nn.conv2d(y, w2, kernel_size=(1, 1), padding=(0, 0), channels=1)\n    func = relay.Function([x], z)\n    mod = tvm.IRModule.from_expr(func)\n    with tvm.transform.PassContext(opt_level=3):\n        relay.build(mod, target=\"llvm\")\n\n\ndef test_alter_with_subfunc():\n    v1 = relay.var(\"v\", shape=[1, 256, 10, 10], dtype=\"float32\")\n    v2 = relay.image.resize2d(v1, size=[16, 16], roi=[0.0, 0.0, 0.0, 0.0], rounding_method=\"\")\n    sub_func = relay.Function([v1], v2)\n    x1 = relay.var(\"x\", shape=[1, 256, 10, 10], dtype=\"float32\")\n    x2 = sub_func(x1)\n    x3 = relay.image.resize2d(x2, size=[8, 8], roi=[0.0, 0.0, 0.0, 0.0], rounding_method=\"\")\n    func = relay.Function([x1], x3)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(relay.transform.AlterOpLayout()(mod), mod)\n\n\ndef test_alter_with_reduce():\n    x = relay.var(\"x\", shape=(1, 1, 1, 1))\n    y = relay.image.resize2d(x, (2, 4))\n    z = relay.mean(y, axis=0)\n    a = relay.image.resize1d(z, (1,))\n    func = relay.Function((x,), a)\n    mod = tvm.IRModule.from_expr(func)\n    mod = relay.transform.InferType()(mod)\n    with tvm.transform.PassContext(opt_level=4):\n        relay.build(mod, target=\"llvm\")\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_annotate_spans_defuse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for annotating spans.\"\"\"\n\n\nimport tvm\nimport tvm.relay as relay\nfrom tvm.relay import testing\nimport tvm.testing\n\n\ndef test_annotate_spans_compatibility():\n    data = relay.var(\"data\", relay.TensorType((1, 3, 64, 64), \"float32\"))\n    weight = relay.var(\"weight\")\n\n    bn_gamma = relay.var(\"bn_gamma\")\n    bn_beta = relay.var(\"bn_beta\")\n    bn_mmean = relay.var(\"bn_mean\")\n    bn_mvar = relay.var(\"bn_var\")\n\n    simple_net = relay.nn.conv2d(\n        data=data, weight=weight, kernel_size=(3, 3), channels=3, padding=(1, 1)\n    )\n    simple_net = relay.nn.batch_norm(simple_net, bn_gamma, bn_beta, bn_mmean, bn_mvar)[0]\n    simple_net = relay.Function(relay.analysis.free_vars(simple_net), simple_net)\n\n    module, params = testing.create_workload(simple_net)\n\n    # Apply some simple passes to legalize the IR.\n    with tvm.transform.PassContext(opt_level=0):\n        module, params = relay.optimize(\n            module, target=tvm.testing.enabled_targets()[0][0], params=params\n        )\n\n    seq = tvm.transform.Sequential([relay.transform.AnnotateSpans(), relay.transform.DefuseOps()])\n    with tvm.transform.PassContext(opt_level=3):\n        module = seq(module)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_annotate_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for annotating external targets.\"\"\"\nimport os\nimport sys\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.relay.testing\nimport tvm.relay.transform as transform\nfrom tvm import relay\nfrom tvm import runtime\nfrom tvm.contrib import utils\n\n\ndef check_result(\n    mod, map_inputs, out_shape, result, tol=1e-5, target=\"llvm\", device=tvm.cpu(), params=None\n):\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        return\n\n    def update_lib(lib):\n        test_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n        source_dir = os.path.join(test_dir, \"..\", \"..\", \"..\")\n        contrib_path = os.path.join(source_dir, \"src\", \"runtime\", \"contrib\")\n\n        kwargs = {}\n        kwargs[\"options\"] = [\"-O2\", \"-std=c++17\", \"-I\" + contrib_path]\n        tmp_path = utils.tempdir()\n        lib_name = \"lib.so\"\n        lib_path = tmp_path.relpath(lib_name)\n        lib.export_library(lib_path, fcompile=False, **kwargs)\n        lib = runtime.load_module(lib_path)\n\n        return lib\n\n    def check_vm_result():\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            exe = relay.vm.compile(mod, target=target, params=params)\n        code, lib = exe.save()\n        lib = update_lib(lib)\n        exe = runtime.vm.Executable.load_exec(code, lib)\n        vm = runtime.vm.VirtualMachine(exe, device)\n        out = vm.run(**map_inputs)\n        tvm.testing.assert_allclose(out.numpy(), result, rtol=tol, atol=tol)\n\n    def check_graph_executor_result():\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            json, lib, param = relay.build(mod, target=target, params=params)\n        lib = update_lib(lib)\n        rt_mod = tvm.contrib.graph_executor.create(json, lib, device)\n\n        for name, data in map_inputs.items():\n            rt_mod.set_input(name, data)\n        rt_mod.set_input(**param)\n        rt_mod.run()\n        out = tvm.nd.empty(out_shape, device=device)\n        out = rt_mod.get_output(0, out)\n\n        tvm.testing.assert_allclose(out.numpy(), result, rtol=tol, atol=tol)\n\n    check_vm_result()\n    check_graph_executor_result()\n\n\ndef test_extern_dnnl():\n    def annotated(dtype, ishape, w1shape):\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            data, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            depthwise_conv2d_1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n        f = relay.Function([data, weight1], out)\n\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    def expected(dtype, ishape, w1shape):\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        begin0 = relay.annotation.compiler_begin(data, \"dnnl\")\n        begin1 = relay.annotation.compiler_begin(weight1, \"dnnl\")\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            begin0, begin1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        end0 = relay.annotation.compiler_end(depthwise_conv2d_1, \"dnnl\")\n        end1 = relay.annotation.compiler_end(depthwise_conv2d_1, \"dnnl\")\n        begin2 = relay.annotation.compiler_begin(end1, \"dnnl\")\n        begin3 = relay.annotation.compiler_begin(end0, \"dnnl\")\n        begin4 = relay.annotation.compiler_begin(weight1, \"dnnl\")\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            begin3, begin4, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        end2 = relay.annotation.compiler_end(depthwise_conv2d_2, \"dnnl\")\n        begin5 = relay.annotation.compiler_begin(end2, \"dnnl\")\n        out = relay.add(begin2, begin5)\n        end3 = relay.annotation.compiler_end(out, \"dnnl\")\n        f = relay.Function([data, weight1], end3)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 1, 3, 3)\n\n    def test_annotate():\n        mod = annotated(dtype, ishape, w1shape)\n        mod = transform.AnnotateTarget(\"dnnl\")(mod)\n        mod = relay.transform.InferType()(mod)\n        ref_mod = expected(dtype, ishape, w1shape)\n        ref_mod = relay.transform.InferType()(ref_mod)\n        tvm.ir.assert_structural_equal(mod, ref_mod)\n\n    def test_run():\n        if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n            print(\"skip because DNNL codegen is not available\")\n            return\n\n        ref_mod = annotated(dtype, ishape, w1shape)\n        mod = annotated(dtype, ishape, w1shape)\n        mod = transform.PartitionGraph()(mod)\n\n        i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n        w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n        ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(\n            i_data, w1_data\n        )\n\n        check_result(\n            mod, {\"data\": i_data, \"weight1\": w1_data}, (1, 32, 14, 14), ref_res.numpy(), tol=1e-5\n        )\n\n    test_annotate()\n    test_run()\n\n\n@pytest.mark.skip(reason=\"fix constant node before opening this case\")\ndef test_extern_dnnl_mobilenet():\n    if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 3, 224, 224)\n    mod, params = relay.testing.mobilenet.get_workload(batch_size=1, dtype=\"float32\")\n\n    mod[\"main\"] = relay.build_module.bind_params_by_name(mod[\"main\"], params)\n    mod = transform.AnnotateTarget(\"dnnl\")(mod)\n    mod = transform.PartitionGraph()(mod)\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    ref_mod, params = relay.testing.mobilenet.get_workload(batch_size=1, dtype=\"float32\")\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n        i_data, **params\n    )\n\n    check_result(mod, {\"data\": i_data}, (1, 1000), ref_res.numpy(), tol=1e-5, params=params)\n\n\ndef test_multiple_ends():\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.test\")\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 10))\n        r = relay.nn.relu(x)\n        a_1 = relay.abs(r)\n        a_2 = relay.abs(r)\n        out = relay.add(a_1, a_2)\n        f = relay.Function([x], out)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    def after():\n        x = relay.var(\"x\", shape=(10, 10))\n        cb_1 = relay.annotation.compiler_begin(x, \"test\")\n        r = relay.nn.relu(cb_1)\n        ce_1 = relay.annotation.compiler_end(r, \"test\")\n        ce_2 = relay.annotation.compiler_end(r, \"test\")\n        cb_2 = relay.annotation.compiler_begin(ce_1, \"default\")\n        cb_3 = relay.annotation.compiler_begin(ce_2, \"default\")\n        a_1 = relay.abs(cb_2)\n        a_2 = relay.abs(cb_3)\n        ce_3 = relay.annotation.compiler_end(a_1, \"default\")\n        ce_4 = relay.annotation.compiler_end(a_2, \"default\")\n        cb_4 = relay.annotation.compiler_begin(ce_3, \"default\")\n        cb_5 = relay.annotation.compiler_begin(ce_4, \"default\")\n        out = relay.add(cb_4, cb_5)\n        ce_6 = relay.annotation.compiler_end(out, \"default\")\n        f = relay.Function([x], ce_6)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    for annotate_non_call_ops in [False, True]:\n        result = transform.AnnotateTarget(\"test\", annotate_non_call_ops)(before())\n        expected = transform.InferType()(after())\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_type_propagation():\n    target = \"test_type_propagation\"\n\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.\" + target)\n    def relu(expr):  # pylint: disable=unused-variable\n        return expr.args[0].checked_type.dtype == \"float32\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 10))\n        r = relay.nn.relu(x)\n        out = relay.nn.relu(r)\n        f = relay.Function([x], out)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    for annotate_non_call_ops in [False, True]:\n        # If the type isn't propogated, then the relu checker function will fail to get the dtype.\n        assert transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n\n\ndef test_ref_create_read_write():\n    target = \"relu\"\n\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.\" + target)\n    def annotate(expr):\n        return True\n\n    def before():\n        ref = relay.expr.RefCreate(relay.const(1.0))\n        r = relay.expr.RefWrite(ref, relay.nn.relu(relay.expr.RefRead(ref)))\n        return tvm.IRModule.from_expr(r)\n\n    def after(annotate_non_call_ops):\n        co = relay.const(1.0)\n        if annotate_non_call_ops:\n            co = relay.annotation.compiler_begin(co, \"default\")\n\n        ref = relay.expr.RefCreate(co)\n        ref1 = ref\n        if annotate_non_call_ops:\n            ref = relay.annotation.compiler_end(ref, \"default\")\n            ref = relay.annotation.compiler_begin(ref, \"default\")\n            ref1 = relay.annotation.compiler_end(ref1, \"default\")\n            ref1 = relay.annotation.compiler_begin(ref1, \"default\")\n\n        read = relay.expr.RefRead(ref1)\n        if annotate_non_call_ops:\n            read = relay.annotation.compiler_end(read, \"default\")\n\n        beg = relay.annotation.compiler_begin(read, target)\n        relu = relay.nn.relu(beg)\n        end = relay.annotation.compiler_end(relu, target)\n\n        if annotate_non_call_ops:\n            end = relay.annotation.compiler_begin(end, \"default\")\n\n        r = relay.expr.RefWrite(ref, end)\n\n        if annotate_non_call_ops:\n            r = relay.annotation.compiler_end(r, \"default\")\n        return tvm.IRModule.from_expr(r)\n\n    for annotate_non_call_ops in [True, False, True]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        expected = transform.InferType()(after(annotate_non_call_ops))\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_tuple():\n    target = \"test_tuple\"\n\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.\" + target)\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"concatenate\", \"target.\" + target)\n    def concatenate(expr):  # pylint: disable=unused-variable\n        return True\n\n    \"\"\"Test that TupleNode is included in annotation when surrounded by supported nodes.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 5))\n        y = relay.var(\"y\", shape=(10, 5))\n        a_1 = relay.nn.relu(x)\n        a_2 = relay.nn.relu(y)\n        out = relay.concatenate((a_1, a_2), axis=1)\n        f = relay.Function([x, y], out)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    def after(annotate_non_call_ops):\n        x = relay.var(\"x\", shape=(10, 5))\n        y = relay.var(\"y\", shape=(10, 5))\n        cb_1 = relay.annotation.compiler_begin(x, target)\n        cb_2 = relay.annotation.compiler_begin(y, target)\n        a_1 = relay.nn.relu(cb_1)\n        a_2 = relay.nn.relu(cb_2)\n        ce_1 = relay.annotation.compiler_end(a_1, target)\n        ce_2 = relay.annotation.compiler_end(a_2, target)\n\n        if annotate_non_call_ops:\n            cb_3 = relay.annotation.compiler_begin(ce_1, target)\n            cb_4 = relay.annotation.compiler_begin(ce_2, target)\n            tup = relay.Tuple([cb_3, cb_4])\n            ce_3 = relay.annotation.compiler_end(tup, target)\n        else:\n            ce_3 = relay.Tuple([ce_1, ce_2])\n\n        cb_3 = relay.annotation.compiler_begin(ce_3, target)\n        out = relay.op._make.concatenate(cb_3, 1)\n        ce_4 = relay.annotation.compiler_end(out, target)\n        f = relay.Function([x, y], ce_4)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    for annotate_non_call_ops in [False, True]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        expected = transform.InferType()(after(annotate_non_call_ops))\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_composite_function():\n    def before():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n\n        # add_relu function\n        in_1 = relay.var(\"in_1\", shape=(10, 10))\n        in_2 = relay.var(\"in_2\", shape=(10, 10))\n        add_node = relay.add(in_1, in_2)\n        relu_node = relay.nn.relu(add_node)\n        add_relu = relay.Function([in_1, in_2], relu_node)\n        add_relu = add_relu.with_attr(\"Composite\", \"test.add_relu\")\n\n        # merged function\n        r = relay.Call(add_relu, [a, b])\n        f = relay.Function([a, b], r)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    def after():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n\n        # add_relu function\n        in_1 = relay.var(\"in_1\", shape=(10, 10))\n        in_2 = relay.var(\"in_2\", shape=(10, 10))\n        add_node = relay.add(in_1, in_2)\n        relu_node = relay.nn.relu(add_node)\n        add_relu = relay.Function([in_1, in_2], relu_node)\n        add_relu = add_relu.with_attr(\"Composite\", \"test.add_relu\")\n\n        # merged function\n        cb_1 = relay.annotation.compiler_begin(a, \"test\")\n        cb_2 = relay.annotation.compiler_begin(b, \"test\")\n        r = relay.Call(add_relu, [cb_1, cb_2])\n        ce_1 = relay.annotation.compiler_end(r, \"test\")\n        f = relay.Function([a, b], ce_1)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    result = transform.AnnotateTarget(\"test\")(before())\n    expected = transform.InferType()(after())\n    assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_double_target():\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.double.A\")\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 5))\n        a_1 = relay.nn.relu(x)\n        mod = tvm.IRModule.from_expr(a_1)\n        return mod\n\n    for annotate_non_call_ops in [True, False]:\n        mod = before()\n        mod1 = transform.AnnotateTarget(\"double.A\", annotate_non_call_ops)(mod)\n        mod2 = transform.AnnotateTarget(\"double.A\", annotate_non_call_ops)(mod1)\n        assert tvm.ir.structural_equal(mod1, mod2)\n\n\ndef test_different_targets():\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.different.A\")\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"add\", \"target.different.B\")\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 5))\n        a_1 = relay.nn.relu(x)\n        b_1 = relay.add(a_1, a_1)\n        mod = tvm.IRModule.from_expr(b_1)\n        return mod\n\n    for annotate_non_call_ops in [True, False]:\n        mod = before()\n        mod1 = transform.AnnotateTarget(\"different.A\", annotate_non_call_ops)(mod)\n        mod1 = transform.AnnotateTarget(\"different.B\", annotate_non_call_ops)(mod1)\n        mod2 = transform.AnnotateTarget([\"different.A\", \"different.B\"], annotate_non_call_ops)(mod)\n        assert tvm.ir.structural_equal(mod1, mod2)\n\n\ndef test_multiple_runs():\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.A\")\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"add\", \"target.B\")\n    def add(expr):  # pylint: disable=unused-variable\n        return True\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 5))\n        a_1 = relay.nn.relu(x)\n        a_2 = relay.abs(a_1)\n        a_3 = relay.nn.relu(a_1)\n        out = relay.add(a_2, a_3)\n\n        f = relay.Function([x], out)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    for annotate_non_call_ops in [True, False]:\n        mod = transform.AnnotateTarget(\"A\", annotate_non_call_ops)(before())\n        mod = transform.AnnotateTarget(\"B\", annotate_non_call_ops)(mod)\n        expected = transform.AnnotateTarget([\"A\", \"B\"], annotate_non_call_ops)(before())\n        assert tvm.ir.structural_equal(expected, mod)\n\n\ndef test_ends_with_tuple():\n    trgt = \"clip\"\n\n    @tvm.ir.register_op_attr(\"clip\", \"target.\" + trgt)\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    def get_model(get_item):\n        \"\"\"Return a model\"\"\"\n        a = relay.var(\"a\", shape=(1, 16, 16, 4), dtype=\"uint8\")\n        z = relay.op.clip(a, 0, 255)\n        b = relay.op.clip(z, 0, 15)\n        c = relay.op.clip(z, 16, 31)\n        t = relay.Tuple((c, b))\n        tgi = relay.TupleGetItem(t, 1) if get_item else t\n        foo = relay.Function([a], tgi)\n        return tvm.IRModule.from_expr(tgi)\n\n    def get_expected(annotate_non_call_ops, get_item):\n        a_ = relay.var(\"a\", shape=(1, 16, 16, 4), dtype=\"uint8\")\n        a = relay.annotation.compiler_begin(a_, trgt)\n        z = relay.op.clip(a, 0, 255)\n        z1 = relay.annotation.compiler_end(z, trgt)\n        z1 = relay.annotation.compiler_begin(z1, trgt)\n        b = relay.op.clip(z1, 0, 15)\n        b = relay.annotation.compiler_end(b, trgt)\n        b = relay.annotation.compiler_begin(b, trgt) if annotate_non_call_ops else b\n        z2 = relay.annotation.compiler_end(z, trgt)\n        z2 = relay.annotation.compiler_begin(z2, trgt)\n        c = relay.op.clip(z2, 16, 31)\n        c = relay.annotation.compiler_end(c, trgt)\n        c = relay.annotation.compiler_begin(c, trgt) if annotate_non_call_ops else c\n        t = relay.Tuple((c, b))\n        t = relay.annotation.compiler_end(t, trgt) if annotate_non_call_ops else t\n        if get_item:\n            t = relay.annotation.compiler_begin(t, trgt) if annotate_non_call_ops else t\n            tgi = relay.TupleGetItem(t, 1)\n            tgi = relay.annotation.compiler_end(tgi, trgt) if annotate_non_call_ops else tgi\n        else:\n            tgi = t\n        foo = relay.Function([a_], tgi)\n        return tvm.IRModule.from_expr(foo)\n\n    for get_item in [True, False]:\n        for annotate_non_call_ops in [False, True]:\n            mod = get_model(get_item)\n            mod = transform.AnnotateTarget(\"clip\", annotate_non_call_ops)(mod)\n            expected = transform.InferType()(get_expected(annotate_non_call_ops, get_item))\n            assert tvm.ir.structural_equal(expected, mod)\n\n\ndef test_if_else():\n    target = \"test_if_else\"\n\n    @tvm.ir.register_op_attr(\"equal\", \"target.\" + target)\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"tanh\", \"target.\" + target)\n    def tanh(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"sigmoid\", \"target.\" + target)\n    def sigmoid(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"erf\", \"target.\" + target)\n    def erf(expr):  # pylint: disable=unused-variable\n        return True\n\n    \"\"\"Test that If-else nodes compiles correctly when surrounded by supported nodes.\"\"\"\n\n    def before():\n        data = relay.var(\"data\", shape=(1, 32))\n        eq1 = relay.var(\"e1\", shape=[], dtype=\"float32\")\n        eq2 = relay.var(\"e2\", shape=[], dtype=\"float32\")\n        eq = relay.equal(eq1, eq2)\n\n        true_branch = relay.tanh(data)\n        false_branch = relay.sigmoid(data)\n        ife = relay.If(eq, true_branch, false_branch)\n        out = relay.erf(ife)\n        func = relay.Function([data, eq1, eq2], out)\n        mod = tvm.IRModule.from_expr(func)\n\n        return mod\n\n    def after():\n\n        data = relay.var(\"data\", shape=(1, 32))\n        eq1 = relay.var(\"e1\", shape=[], dtype=\"float32\")\n        eq2 = relay.var(\"e2\", shape=[], dtype=\"float32\")\n\n        cb_1 = relay.annotation.compiler_begin(eq1, target)\n        cb_2 = relay.annotation.compiler_begin(eq2, target)\n\n        equality_condition = relay.equal(cb_1, cb_2)\n        ce_1 = relay.annotation.compiler_end(equality_condition, target)\n\n        # if condition\n        cb_3 = relay.annotation.compiler_begin(data, target)\n        true_branch = relay.tanh(cb_3)\n        ce_2 = relay.annotation.compiler_end(true_branch, target)\n\n        # else condition\n        cb_4 = relay.annotation.compiler_begin(data, target)\n        false_branch = relay.sigmoid(cb_4)\n        ce_3 = relay.annotation.compiler_end(false_branch, target)\n\n        if_condition = relay.If(ce_1, ce_2, ce_3)\n        cb_5 = relay.annotation.compiler_begin(if_condition, target)\n        erf_out = relay.erf(cb_5)\n        ce_4 = relay.annotation.compiler_end(erf_out, target)\n        func = relay.Function([data, eq1, eq2], ce_4)\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    expected = transform.InferType()(after())\n    for annotate_non_call_ops in [True, False]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_while_let():\n    target = \"test_while_let\"\n\n    @tvm.ir.register_op_attr(\"less\", \"target.\" + target)\n    def less(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"add\", \"target.\" + target)\n    def add(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"zeros_like\", \"target.\" + target)\n    def zeros_like(expr):  # pylint: disable=unused-variable\n        return True\n\n    \"\"\"Test that let nodes compiles correctly when surrounded by other nodes.\"\"\"\n\n    def before():\n\n        var1 = relay.var(\"var1\", shape=(2,))\n        var2 = relay.var(\"var2\", shape=(), dtype=\"int32\")\n        var3 = relay.var(\"var3\", shape=(2,))\n        cond = relay.less(var2, relay.const(10, dtype=\"int32\"))\n\n        loop = relay.var(\"while_loop\")\n        ii = var2 + relay.const(1, dtype=\"int32\")\n        ss = var3 + var1\n        true_branch = loop(ii, ss)\n        ife = relay.If(cond, true_branch, var3)\n        func_1 = relay.Function([var2, var3], ife)\n\n        ret = relay.Let(loop, func_1, loop(relay.const(0, dtype=\"int32\"), relay.zeros_like(var1)))\n        func_2 = relay.Function([var1], ret)\n        mod = tvm.IRModule.from_expr(func_2)\n        return mod\n\n    def after(annotate_non_call_ops):\n        var1 = relay.var(\"var1\", shape=(2,))\n        var2 = relay.var(\"var2\", shape=(), dtype=\"int32\")\n        var3 = relay.var(\"var3\", shape=(2,))\n        var4 = relay.const(10, dtype=\"int32\")\n\n        cb_1 = relay.annotation.compiler_begin(var2, target)\n        cb_2 = relay.annotation.compiler_begin(var4, target)\n\n        less_condition = relay.less(cb_1, cb_2)\n        ce_1 = relay.annotation.compiler_end(less_condition, target)\n\n        loop = relay.var(\"while_loop\")\n\n        # if condition\n        cb_3 = relay.annotation.compiler_begin(var2, target)\n        cb_4 = relay.annotation.compiler_begin(relay.const(1, dtype=\"int32\"), target)\n        add_op_1 = relay.add(cb_3, cb_4)\n        ce_2 = relay.annotation.compiler_end(add_op_1, target)\n\n        cb_5 = relay.annotation.compiler_begin(ce_2, \"default\") if annotate_non_call_ops else ce_2\n\n        cb_6 = relay.annotation.compiler_begin(var3, target)\n        cb_7 = relay.annotation.compiler_begin(var1, target)\n        add_op_2 = relay.add(cb_6, cb_7)\n        ce_3 = relay.annotation.compiler_end(add_op_2, target)\n\n        cb_8 = relay.annotation.compiler_begin(ce_3, \"default\") if annotate_non_call_ops else ce_3\n\n        true_branch = loop(cb_5, cb_8)  # while loop\n        ce_4 = (\n            relay.annotation.compiler_end(true_branch, \"default\")\n            if annotate_non_call_ops\n            else true_branch\n        )\n        if_condition = relay.If(ce_1, ce_4, var3)\n        const_1 = relay.const(0, dtype=\"int32\")\n        cb_9 = (\n            relay.annotation.compiler_begin(const_1, \"default\")\n            if annotate_non_call_ops\n            else const_1\n        )\n        cb_10 = relay.annotation.compiler_begin(var1, target)\n        zeros_like = relay.zeros_like(cb_10)\n        ce_5 = relay.annotation.compiler_end(zeros_like, target)\n        cb_11 = relay.annotation.compiler_begin(ce_5, \"default\") if annotate_non_call_ops else ce_5\n        while_condition = loop(cb_9, cb_11)\n        ce_6 = (\n            relay.annotation.compiler_end(while_condition, \"default\")\n            if annotate_non_call_ops\n            else while_condition\n        )\n\n        func_1 = relay.Function([var2, var3], if_condition)\n        ret = relay.Let(loop, func_1, ce_6)\n        func_2 = relay.Function([var1], ret)\n        mod = tvm.IRModule.from_expr(func_2)\n        return mod\n\n    for annotate_non_call_ops in [False, True]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        expected = transform.InferType()(after(annotate_non_call_ops))\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_if_free_vars():\n    target = \"test_if_free_vars\"\n\n    @tvm.ir.register_op_attr(\"equal\", \"target.\" + target)\n    def equal(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"sigmoid\", \"target.\" + target)\n    def sigmoid(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"erf\", \"target.\" + target)\n    def erf(expr):  # pylint: disable=unused-variable\n        return True\n\n    \"\"\"Test that If-else nodes compiles correctly when surrounded by free variables\"\"\"\n\n    def before():\n        data = relay.var(\"data\", shape=(1, 32))\n        eq1 = relay.var(\"e1\", shape=[], dtype=\"float32\")\n        eq2 = relay.var(\"e2\", shape=[], dtype=\"float32\")\n        eq = relay.equal(eq1, eq2)\n\n        true_branch = relay.zeros(shape=(1, 32), dtype=\"float32\")\n        false_branch = relay.sigmoid(data)\n        ife = relay.If(eq, true_branch, false_branch)\n        out = relay.erf(ife)\n\n        func = relay.Function([data, eq1, eq2], out)\n        mod = tvm.IRModule.from_expr(func)\n\n        return mod\n\n    def after():\n        data = relay.var(\"data\", shape=(1, 32))\n        eq1 = relay.var(\"e1\", shape=[], dtype=\"float32\")\n        eq2 = relay.var(\"e2\", shape=[], dtype=\"float32\")\n\n        cb_1 = relay.annotation.compiler_begin(eq1, target)\n        cb_2 = relay.annotation.compiler_begin(eq2, target)\n\n        equality_condition = relay.equal(cb_1, cb_2)\n        ce_1 = relay.annotation.compiler_end(equality_condition, target)\n\n        # if condition\n        true_branch = relay.zeros(shape=(1, 32), dtype=\"float32\")\n\n        # else condition\n        cb_3 = relay.annotation.compiler_begin(data, target)\n        false_branch = relay.sigmoid(cb_3)\n        ce_2 = relay.annotation.compiler_end(false_branch, target)\n\n        if_condition = relay.If(ce_1, true_branch, ce_2)\n        cb_4 = relay.annotation.compiler_begin(if_condition, target)\n        erf_out = relay.erf(cb_4)\n        ce_3 = relay.annotation.compiler_end(erf_out, target)\n        func = relay.Function([data, eq1, eq2], ce_3)\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    for annotate_non_call_ops in [True, False]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        expected = transform.InferType()(after())\n        assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_free_vars_zeros():\n    target = \"test_free_vars_zeros\"\n\n    \"\"\"Test that free variables compile correctly on their own\"\"\"\n\n    def before():\n        func = relay.Function([], relay.zeros(shape=(0), dtype=\"float32\"))\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    def after():\n        func = relay.Function([], relay.zeros(shape=(0), dtype=\"float32\"))\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    result = transform.AnnotateTarget(target)(before())\n    expected = transform.InferType()(after())\n    assert tvm.ir.structural_equal(expected, result)\n\n\ndef test_empty_tuple():\n    target = \"test_empty_tuple\"\n\n    \"\"\"An empty tuple should behave just like a call with no args (see above test).\"\"\"\n\n    def before():\n        func = relay.Function([], relay.Tuple([]))\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    def after():\n        func = relay.Function([], relay.Tuple([]))\n        mod = tvm.IRModule.from_expr(func)\n        return mod\n\n    for annotate_non_call_ops in [True, False]:\n        result = transform.AnnotateTarget(target, annotate_non_call_ops)(before())\n        expected = transform.InferType()(after())\n        assert tvm.ir.structural_equal(expected, result)\n\n\nif __name__ == \"__main__\":\n    test_extern_dnnl()\n    test_composite_function()\n    # test_extern_dnnl_mobilenet()\n    test_multiple_ends()\n    test_type_propagation()\n    test_tuple()\n    test_multiple_runs()\n    test_if_else()\n    test_while_let()\n    test_if_free_vars()\n    test_free_vars_zeros()\n    test_different_targets()\n    test_double_target()\n    test_ends_with_tuple()\n    test_ref_create_read_write()\n    test_empty_tuple()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_auto_quantize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.relay.expr import Call\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef quantize_and_build(out, skip_conv_layers=[]):\n    f = relay.Function(relay.analysis.free_vars(out), out)\n    mod, params = testing.create_workload(f)\n\n    with relay.quantize.qconfig(skip_conv_layers=skip_conv_layers):\n        qmod = relay.quantize.quantize(mod, params)\n\n    relay.build(qmod, \"llvm\", params=params)\n\n    return qmod\n\n\ndef test_mul_rewrite():\n    \"\"\"a test case where rhs of mul is not constant\"\"\"\n    data = relay.var(\"data\", shape=(1, 16, 64, 64))\n    multiplier = relay.sigmoid(relay.var(\"data\", shape=(1, 16, 1, 1)))\n    conv = relay.nn.conv2d(\n        data, relay.var(\"weight\"), kernel_size=(3, 3), padding=(1, 1), channels=16\n    )\n    act = relay.nn.relu(data=conv)\n\n    quantize_and_build(act * multiplier)\n\n    pool = relay.nn.global_avg_pool2d(data=act)\n\n    quantize_and_build(act * pool)\n\n\ndef test_skip_conv():\n    data = relay.var(\"data\", shape=(1, 16, 64, 64))\n    np_weight = np.random.rand(16, 16, 3, 3)\n    conv0_weight = relay.Constant(tvm.nd.array(np_weight)).astype(\"float32\")\n    conv1_weight = relay.Constant(tvm.nd.array(np_weight)).astype(\"float32\")\n    multiplier = relay.sigmoid(relay.var(\"data\", shape=(1, 16, 1, 1)))\n\n    conv0 = relay.nn.conv2d(data, conv0_weight, kernel_size=(3, 3), padding=(1, 1), channels=16)\n    act0 = relay.nn.relu(data=conv0)\n    conv1 = relay.nn.conv2d(act0, conv1_weight, kernel_size=(3, 3), padding=(1, 1), channels=16)\n    act1 = relay.nn.relu(data=conv1)\n\n    quantize_and_build(act1 * multiplier)\n    quantize_and_build(act1 * multiplier, skip_conv_layers=[0])\n    quantize_and_build(act1 * multiplier, skip_conv_layers=[1])\n    quantize_and_build(act1 * multiplier, skip_conv_layers=[0, 1])\n\n\ndef test_stop_quantize():\n    data = relay.var(\"data\", shape=(1, 16, 64, 64))\n    np_weight0 = np.random.rand(16, 16, 3, 3)\n    conv0_weight = relay.Constant(tvm.nd.array(np_weight0)).astype(\"float32\")\n    np_weight1 = np.random.rand(16, 16, 1, 1)\n    conv1_weight = relay.Constant(tvm.nd.array(np_weight1)).astype(\"float32\")\n    multiplier = relay.sigmoid(relay.var(\"data\", shape=(1, 16, 1, 1)))\n\n    conv0 = relay.nn.conv2d(data, conv0_weight, kernel_size=(3, 3), padding=(1, 1), channels=16)\n    act0 = relay.nn.relu(data=conv0)\n\n    pool = relay.nn.global_avg_pool2d(data=act0)\n\n    conv1 = relay.nn.conv2d(pool, conv1_weight, kernel_size=(1, 1), padding=(0, 0), channels=16)\n    act1 = relay.nn.relu(data=conv1)\n\n    quantize_and_build(act1 * multiplier)\n\n\ndef test_batch_flatten_rewrite():\n\n    data = relay.var(\"data\", shape=(1, 16, 64, 64), dtype=\"float32\")\n\n    out = relay.nn.conv2d(\n        data, relay.var(\"weight\"), kernel_size=(3, 3), padding=(1, 1), channels=16\n    )\n\n    out = relay.nn.batch_flatten(out)\n\n    qmod = quantize_and_build(out)\n\n    def _check_batch_flatten(node):\n        if isinstance(node, Call):\n            if node.op.name == \"nn.batch_flatten\":\n                assert node.checked_type.dtype == \"int8\"\n\n    # check if batch_flatten is quantized\n    relay.analysis.post_order_visit(qmod[\"main\"], _check_batch_flatten)\n\n\ndef test_batch_matmul_rewrite():\n    data = relay.var(\"data\", shape=(1, 4, 16, 16))\n    data2 = relay.sigmoid(relay.var(\"data\", shape=(4, 16, 64)))\n    out = relay.nn.conv2d(data, relay.var(\"weight\"), kernel_size=(3, 3), padding=(1, 1), channels=8)\n\n    out = relay.nn.batch_flatten(out)\n    out = relay.reshape(out, [1, 32, 64])\n    out = relay.nn.batch_matmul(out, data2)\n\n    qmod = quantize_and_build(out)\n\n    def _check_batch_matmul(node):\n        if isinstance(node, Call):\n\n            if node.op.name in [\"nn.batch_matmul\", \"nn.conv2d\"]:\n                assert node.checked_type.dtype == \"int32\"\n            elif node.op.name == \"nn.batch_flatten\":\n                assert node.checked_type.dtype == \"int8\"\n\n    # check if batch_matmul is quantized\n    relay.analysis.post_order_visit(qmod[\"main\"], _check_batch_matmul)\n\n\ndef get_calibration_dataset(mod, input_name):\n    dataset = []\n    input_shape = [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n    for i in range(5):\n        data = np.random.uniform(size=input_shape)\n        dataset.append({input_name: data})\n    return dataset\n\n\n@pytest.mark.parametrize(\"create_target\", [True, False])\ndef test_calibrate_target(create_target):\n    mod, params = testing.synthetic.get_workload()\n    dataset = get_calibration_dataset(mod, \"data\")\n    with relay.quantize.qconfig(calibrate_mode=\"kl_divergence\"):\n        if create_target:\n            with tvm.target.Target(\"llvm\"):\n                relay.quantize.quantize(mod, params, dataset)\n        else:\n            # current_target = None\n            relay.quantize.quantize(mod, params, dataset)\n\n\ndef test_calibrate_memory_bound():\n    mod, params = testing.synthetic.get_workload()\n    dataset = get_calibration_dataset(mod, \"data\")\n    import multiprocessing\n\n    num_cpu = multiprocessing.cpu_count()\n    with relay.quantize.qconfig(calibrate_mode=\"kl_divergence\", calibrate_chunk_by=num_cpu):\n        relay.quantize.quantize(mod, params, dataset)\n\n\ndef test_calibrate_percentile():\n    mod, params = testing.synthetic.get_workload()\n    dataset = get_calibration_dataset(mod, \"data\")\n    with relay.quantize.qconfig(calibrate_mode=\"percentile\"):\n        relay.quantize.quantize(mod, params, dataset)\n\n\n####################################\n# Quant/Dequant Partitioning Tests #\n####################################\n\nBASE_CFG = {\n    \"skip_conv_layers\": [],\n    \"skip_dense_layers\": False,\n    \"dtype_input\": \"int8\",\n    \"dtype_weight\": \"int8\",\n    \"dtype_activation\": \"int32\",\n}\n\n\ndef gen_rand_tvm(tt, low, high):\n    if \"int\" in tt.dtype:\n        data_np = np.random.randint(low, high, size=get_const_tuple(tt.shape), dtype=tt.dtype)\n    elif \"float\" in tt.dtype:\n        data_np = np.random.uniform(low, high, size=get_const_tuple(tt.shape)).astype(tt.dtype)\n    else:\n        assert False, \"unknown dtype\"\n    return tvm.nd.array(data_np, device=tvm.cpu(0))\n\n\ndef verify_partition_fails(mod, params):\n    # standard partition should always succeed\n    with relay.quantize.qconfig(**BASE_CFG, partition_conversions=\"enabled\"):\n        partitioned_mod = relay.quantize.quantize(mod, params)\n\n    try:\n        with relay.quantize.qconfig(**BASE_CFG, partition_conversions=\"fully_integral\"):\n            partitioned_mod = relay.quantize.quantize(mod, params)\n        raise RuntimeError(\"partitioning should have failed\")\n    except AssertionError:\n        pass\n\n\ndef verify_partition(mod, params):\n    with relay.quantize.qconfig(**BASE_CFG, paritition_conversions=\"disabled\"):\n        unpartitioned_mod = relay.quantize.quantize(mod, params)\n        assert (\n            len(unpartitioned_mod.get_global_vars()) == 1\n        ), \"unpartitioned module should only have one function\"\n    with relay.quantize.qconfig(**BASE_CFG, partition_conversions=\"fully_integral\"):\n        partitioned_mod = relay.quantize.quantize(mod, params)\n\n    # ensure partitioned and unpartitioned results agree\n    params = [gen_rand_tvm(param.type_annotation, 0, 1) for param in partitioned_mod[\"main\"].params]\n\n    def _eval_mod(mod):\n        return relay.create_executor(\"vm\", device=tvm.cpu(0), target=\"llvm\", mod=mod).evaluate()(\n            *params\n        )\n\n    partitioned_mod_result = _eval_mod(partitioned_mod)\n    unpartitioned_mod_result = _eval_mod(unpartitioned_mod)\n    tvm.testing.assert_allclose(unpartitioned_mod_result.numpy(), partitioned_mod_result.numpy())\n\n\ndef test_add_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x: Tensor[(10, 10), float32],\n        %y: Tensor[(10, 10), float32]) {\n      add(%x, %y)\n    }\n    \"\"\"\n    )\n    params = {}\n    verify_partition_fails(mod, params)\n\n\ndef test_conv2d_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x: Tensor[(1, 4, 16, 16), float32],\n        %w: Tensor[(4, 4, 3, 3), float32]) -> Tensor[(1, 4, 16, 16), float32] {\n      nn.conv2d(%x, %w,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3])\n    }\n    \"\"\"\n    )\n    weight_ty = mod[\"main\"].params[1].checked_type\n    params = {\"w\": gen_rand_tvm(weight_ty, 0, 1)}\n    verify_partition(mod, params)\n\n\ndef test_multiple_arg_conversions_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x1: Tensor[(1, 4, 16, 16), float32],\n        %w1: Tensor[(4, 4, 3, 3), float32],\n        %x2: Tensor[(1, 4, 16, 16), float32],\n        %w2: Tensor[(4, 4, 3, 3), float32]\n        ) -> Tensor[(1, 4, 16, 16), float32] {\n      %0 = nn.conv2d(%x1, %w1,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3]);\n      %1 = nn.conv2d(%x2, %w2,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3]);\n      add(%0, %1)\n    }\n    \"\"\"\n    )\n\n    w1_ty = mod[\"main\"].params[1].checked_type\n    w2_ty = mod[\"main\"].params[3].checked_type\n    params = {\"w1\": gen_rand_tvm(w1_ty, 0, 1), \"w2\": gen_rand_tvm(w2_ty, 0, 1)}\n    verify_partition(mod, params)\n\n\ndef test_unquantizable_prefix_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x: Tensor[(1, 4, 16, 16), float32],\n        %b: Tensor[(4), float32],\n        %w: Tensor[(4, 4, 3, 3), float32]) -> Tensor[(1, 4, 16, 16), float32] {\n      // NOTE bias_add isn't currently quantizable\n      %0 = nn.bias_add(%x, %b);\n      nn.conv2d(%0, %w,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3])\n    }\n    \"\"\"\n    )\n    bias_ty = mod[\"main\"].params[1].checked_type\n    weight_ty = mod[\"main\"].params[2].checked_type\n    params = {\"b\": gen_rand_tvm(bias_ty, 0, 1), \"w\": gen_rand_tvm(weight_ty, 0, 1)}\n    verify_partition_fails(mod, params)\n\n\ndef test_unquantizable_core_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x1: Tensor[(1, 4, 16, 16), float32],\n        %w1: Tensor[(4, 4, 3, 3), float32],\n        %b: Tensor[(4), float32],\n        %w2: Tensor[(4, 4, 3, 3), float32]) -> Tensor[(1, 4, 16, 16), float32] {\n      %0 = nn.conv2d(%x1, %w1,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3]);\n      // NOTE bias_add isn't currently quantizable\n      %1 = nn.bias_add(%0, %b);\n      nn.conv2d(%1, %w2,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3])\n    }\n    \"\"\"\n    )\n    w1_ty = mod[\"main\"].params[1].checked_type\n    bias_ty = mod[\"main\"].params[2].checked_type\n    w2_ty = mod[\"main\"].params[3].checked_type\n    params = {\n        \"w1\": gen_rand_tvm(w1_ty, 0, 1),\n        \"w2\": gen_rand_tvm(w2_ty, 0, 1),\n        \"b\": gen_rand_tvm(bias_ty, 0, 1),\n    }\n    verify_partition_fails(mod, params)\n\n\ndef test_unquantizable_suffix_partition():\n    mod = tvm.parser.parse(\n        \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(\n        %x: Tensor[(1, 4, 16, 16), float32],\n        %w: Tensor[(4, 4, 3, 3), float32],\n        %b: Tensor[(4), float32]) -> Tensor[(1, 4, 16, 16), float32] {\n      %0 = nn.conv2d(%x, %w,\n        padding=[1, 1, 1, 1],\n        channels=4,\n        kernel_size=[3, 3]);\n      // NOTE bias_add isn't currently quantizable\n      nn.bias_add(%0, %b)\n    }\n    \"\"\"\n    )\n    weight_ty = mod[\"main\"].params[1].checked_type\n    bias_ty = mod[\"main\"].params[2].checked_type\n    params = {\"w\": gen_rand_tvm(weight_ty, 0, 1), \"b\": gen_rand_tvm(bias_ty, 0, 1)}\n    verify_partition_fails(mod, params)\n\n\ndef test_left_shift_negative():\n    data = relay.var(\"data\", shape=(1, 16, 64, 64))\n    weight = relay.const(np.full((16, 16, 3, 3), 256.0))\n    conv2d = relay.nn.conv2d(data, weight, kernel_size=(3, 3), padding=(1, 1), channels=16)\n    relu = relay.nn.relu(conv2d)\n\n    mod = tvm.IRModule.from_expr(relu)\n\n    with tvm.transform.PassContext(opt_level=3):\n        with relay.quantize.qconfig(\n            calibrate_mode=\"global_scale\", global_scale=8.0, skip_conv_layers=None\n        ):\n            qnn_mod = relay.quantize.quantize(mod)\n\n    class OpFinder(relay.ExprVisitor):\n        def __init__(self, op_name):\n            super(OpFinder, self).__init__()\n            self._op_name = op_name\n            self.ops = list()\n\n        def visit_call(self, call):\n            super().visit_call(call)\n            if call.op.name == self._op_name:\n                self.ops.append(call)\n\n    opf = OpFinder(\"left_shift\")\n    opf.visit(qnn_mod[\"main\"])\n    assert len(opf.ops) > 0, 'Broken case, can\\'t find any \"left_shift\" operators.'\n    for left_shift_op in opf.ops:\n        shift_amount = left_shift_op.args[1].data.numpy()\n        assert shift_amount >= 0, \"Shift amount must be non-negative.\"\n\n\ndef test_dense_conv2d_rewrite():\n    n, c, h, w = 1, 16, 64, 64\n    data = relay.var(\"data\", relay.TensorType((n, c, h, w)))\n    inp = relay.var(\"inp\", relay.TensorType((n, c * h * w)))\n    weight_T = relay.const(np.random.random((n, c * h * w)), dtype=\"float32\")\n    bias = relay.const(np.random.random((n,)), dtype=\"float32\")\n    conv_w = relay.const(np.random.random((16, 16, 3, 3)), dtype=\"float32\")\n\n    dense_o = relay.nn.dense(inp, weight_T)\n    linear_o = relay.nn.bias_add(dense_o, bias)\n    conv2d_o = relay.nn.conv2d(data, conv_w, kernel_size=(3, 3), padding=(1, 1), channels=16)\n    result = relay.Tuple((linear_o, conv2d_o))\n\n    mod = tvm.IRModule.from_expr(result)\n    with tvm.transform.PassContext(opt_level=3):\n        with relay.quantize.qconfig(\n            calibrate_mode=\"global_scale\", global_scale=8.0, skip_dense_layer=False\n        ):\n            qnn_mod = relay.quantize.quantize(mod)\n\n    def _check_dense(node):\n        if isinstance(node, Call):\n            if node.op.name == \"nn.dense\":\n                assert node.args[0].checked_type.dtype == \"int8\"\n                assert node.args[1].checked_type.dtype == \"int8\"\n                assert node.checked_type.dtype == \"int32\"\n            if node.op.name == \"nn.conv2d\":\n                assert node.args[0].checked_type.dtype == \"float32\"\n                assert node.args[1].checked_type.dtype == \"float32\"\n                assert node.checked_type.dtype == \"float32\"\n\n    relay.analysis.post_order_visit(qnn_mod[\"main\"], _check_dense)\n\n\nif __name__ == \"__main__\":\n    test_mul_rewrite()\n    test_batch_flatten_rewrite()\n    test_batch_matmul_rewrite()\n    test_calibrate_target(False)\n    test_calibrate_target(True)\n    test_calibrate_memory_bound()\n    test_calibrate_percentile()\n\n    test_add_partition()\n    test_conv2d_partition()\n    test_multiple_arg_conversions_partition()\n    test_unquantizable_prefix_partition()\n    test_unquantizable_core_partition()\n    test_unquantizable_suffix_partition()\n    test_left_shift_negative()\n    test_dense_conv2d_rewrite()\n\n    test_skip_conv()\n    test_stop_quantize()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_canonicalize_cast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nimport tvm.relay as relay\nimport tvm.relay.transform as _transform\n\n\ndef test_canonicalize_cast():\n    def before(data, conv_weight, bias1, bias2):\n        x = relay.nn.conv2d(\n            data, conv_weight, channels=16, kernel_size=(3, 3), padding=(1, 1), out_dtype=\"int8\"\n        )\n        x1 = relay.cast(x, dtype=\"int32\")\n        y1 = relay.add(x1, bias1)\n        y2 = relay.add(x1, bias2)\n        y = relay.add(y1, y2)\n        return relay.Function([data, conv_weight, bias1, bias2], y)\n\n    def expected(data, conv_weight, bias1, bias2):\n        x = relay.nn.conv2d(\n            data, conv_weight, channels=16, kernel_size=(3, 3), padding=(1, 1), out_dtype=\"int8\"\n        )\n        x1 = relay.cast(x, dtype=\"int32\")\n        x2 = relay.cast(x, dtype=\"int32\")\n        y1 = relay.add(x1, bias1)\n        y2 = relay.add(x2, bias2)\n        y = relay.add(y1, y2)\n        return relay.Function([data, conv_weight, bias1, bias2], y)\n\n    def check(shape):\n        data = relay.var(\"data\", shape=shape, dtype=\"int8\")\n        conv_weight = relay.var(\"weight\")\n        bias1 = relay.var(\"bias1\", shape=(16, 1, 1), dtype=\"int32\")\n        bias2 = relay.var(\"bias2\", shape=(16, 1, 1), dtype=\"int32\")\n        y = before(data, conv_weight, bias1, bias2)\n        mod = tvm.IRModule.from_expr(y)\n        seq = tvm.transform.Sequential(\n            [_transform.InferType(), _transform.CanonicalizeCast(), _transform.InferType()]\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            mod = seq(mod)\n        y = mod[\"main\"]\n        y_expected = expected(data, conv_weight, bias1, bias2)\n        gv = relay.GlobalVar(\"expected\")\n        mod[gv] = y_expected\n        mod = _transform.InferType()(mod)\n        y_expected = mod[\"expected\"]\n        assert tvm.ir.structural_equal(y, y_expected)\n\n    check((1, 16, 7, 7))\n\n\nif __name__ == \"__main__\":\n    test_canonicalize_cast()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_check_kind.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import check_kind\nimport pytest\n\n\ndef test_typevar_kind():\n    # returns the same kind\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.ShapeVar)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.Constraint)\n\n    assert check_kind(tp1) == relay.TypeKind.Type\n    assert check_kind(tp2) == relay.TypeKind.ShapeVar\n    assert check_kind(tp3) == relay.TypeKind.Constraint\n\n\ndef test_tuple_kind():\n    # only contain type kinds\n    tp = relay.TypeVar(\"tp\", relay.TypeKind.Type)\n    tt = relay.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    tf = relay.FuncType(\n        tvm.runtime.convert([]), tt, tvm.runtime.convert([]), tvm.runtime.convert([])\n    )\n    fields = tvm.runtime.convert([tp, tf, tt])\n\n    tup_ty = relay.TupleType(fields)\n    assert check_kind(tup_ty) == relay.TypeKind.Type\n\n\ndef test_func_kind():\n    # only contain type kinds\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.Type)\n\n    shape = tvm.runtime.convert([1, 2, 3])\n    dtype = \"float32\"\n    tensor_type = relay.TensorType(shape, dtype)\n\n    tr = relay.TypeRelation(None, tvm.runtime.convert([tensor_type, tp1]), 1, None)\n\n    type_params = tvm.runtime.convert([tp1, tp2])\n    type_constraints = tvm.runtime.convert([tr])\n    arg_types = tvm.runtime.convert([tp1, tensor_type])\n    ret_type = relay.TupleType(tvm.runtime.convert([tp2, tensor_type]))\n\n    tf = relay.FuncType(arg_types, ret_type, type_params, type_constraints)\n    assert check_kind(tf) == relay.TypeKind.Type\n\n\ndef test_ref_kind():\n    # only contain type kinds\n    tt = relay.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    ft = relay.FuncType(\n        tvm.runtime.convert([]), tt, tvm.runtime.convert([]), tvm.runtime.convert([])\n    )\n\n    rt1 = relay.RefType(tt)\n    assert check_kind(rt1) == relay.TypeKind.Type\n    rt2 = relay.RefType(ft)\n    assert check_kind(rt2) == relay.TypeKind.Type\n    rt3 = relay.RefType(relay.TupleType([rt1, rt2]))\n    assert check_kind(rt3) == relay.TypeKind.Type\n\n\ndef test_relation_kind():\n    # only have type kinds for arguments\n    tp = relay.TypeVar(\"tp\", relay.TypeKind.Type)\n    tt = relay.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    tf = relay.FuncType(\n        tvm.runtime.convert([]), tt, tvm.runtime.convert([]), tvm.runtime.convert([])\n    )\n    args = tvm.runtime.convert([tf, tt, tp])\n\n    tr = relay.TypeRelation(None, args, 2, None)\n    assert check_kind(tr) == relay.TypeKind.Constraint\n\n\ndef test_global_typevar_kind():\n    v1 = relay.GlobalTypeVar(\"gtv1\", relay.TypeKind.AdtHandle)\n    v2 = relay.GlobalTypeVar(\"gtv2\", relay.TypeKind.Type)\n\n    assert check_kind(v1) == relay.TypeKind.AdtHandle\n    assert check_kind(v2) == relay.TypeKind.Type\n\n\ndef test_typecall_kind():\n    gtv = relay.GlobalTypeVar(\"gtv\")\n\n    mod = tvm.IRModule()\n    data = relay.TypeData(gtv, [], [])\n    mod[gtv] = data\n    empty_call = relay.TypeCall(gtv, [])\n    assert check_kind(empty_call, mod) == relay.TypeKind.Type\n\n    new_mod = tvm.IRModule()\n    tv = relay.TypeVar(\"tv\")\n    new_data = relay.TypeData(gtv, [tv], [])\n    new_mod[gtv] = new_data\n    call = relay.TypeCall(gtv, [relay.TupleType([])])\n    assert check_kind(call, new_mod) == relay.TypeKind.Type\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_tuple_kind():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.BaseType)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.Constraint)\n    fields = tvm.runtime.convert([tp1, tp2, tp3])\n\n    tup_ty = relay.TupleType(fields)\n    check_kind(tup_ty)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_func_kind():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.BaseType)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.Constraint)\n\n    type_params = tvm.runtime.convert([tp1, tp2, tp3])\n    type_constraints = tvm.runtime.convert([])\n    arg_types = tvm.runtime.convert([tp1, tp2])\n    ret_type = tp3\n\n    tf = relay.FuncType(arg_types, ret_type, type_params, type_constraints)\n    check_kind(tf)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_ref_kind():\n    tp = relay.TypeVar(\"tp\", relay.TypeKind.ShapeVar)\n    rt = relay.RefType(tp)\n    check_kind(rt)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_invalid_relation_kind():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.BaseType)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.Constraint)\n    args = tvm.runtime.convert([tp1, tp2, tp3])\n\n    func = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Broadcast\")\n    tr = relay.TypeRelation(func, args, 2, None)\n    check_kind(tr)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_typecall_invalid_callee():\n    # global type var must be an ADT handle\n    gtv = relay.GlobalTypeVar(\"v1\", relay.TypeKind.Type)\n    check_kind(relay.TypeCall(gtv, []))\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_typecall_invalid_args():\n    # args must all be type kind\n    mod = tvm.IRModule()\n    gtv = relay.GlobalTypeVar(\"v1\")\n    data = relay.TypeData(gtv, [], [])\n    mod[gtv] = data\n\n    check_kind(relay.TypeCall(gtv, [data]))\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_typecall_invalid_num_args():\n    mod = tvm.IRModule()\n    gtv = relay.GlobalTypeVar(\"v1\")\n    tv = relay.TypeVar(\"tv\")\n    data = relay.TypeData(gtv, [tv], [])\n    mod[gtv] = data\n    check_kind(relay.TypeCall(gtv, []))\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_func_with_invalid_ret_type():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.ShapeVar)\n    tf = relay.FuncType(\n        tvm.runtime.convert([tp1]), tp2, tvm.runtime.convert([tp1, tp2]), tvm.runtime.convert([])\n    )\n\n    check_kind(tf)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_func_with_invalid_arg_types():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.Type)\n    tf = relay.FuncType(\n        tvm.runtime.convert([tp1]), tp2, tvm.runtime.convert([tp1, tp2]), tvm.runtime.convert([])\n    )\n\n    check_kind(tf)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_func_with_invalid_tuple():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n\n    ret_type = relay.TupleType(tvm.runtime.convert([tp1, tp1, tp1]))\n\n    tf = relay.FuncType(\n        tvm.runtime.convert([]), ret_type, tvm.runtime.convert([tp1]), tvm.runtime.convert([])\n    )\n    check_kind(tf)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_func_with_invalid_relation():\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.Type)\n    tp2 = relay.TypeVar(\"tp2\", relay.TypeKind.ShapeVar)\n    tp3 = relay.TypeVar(\"tp3\", relay.TypeKind.Constraint)\n\n    func = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Identity\")\n    tr = relay.TypeRelation(func, tvm.runtime.convert([tp2, tp3]), 1, None)\n\n    tf = relay.FuncType(\n        tvm.runtime.convert([tp1]),\n        tp1,\n        tvm.runtime.convert([tp1, tp2, tp3]),\n        tvm.runtime.convert([tr]),\n    )\n    check_kind(tf)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_tuple_with_invalid_func():\n    tensor_type = relay.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n\n    tp1 = relay.TypeVar(\"tp1\", relay.TypeKind.ShapeVar)\n    tf = relay.FuncType(\n        tvm.runtime.convert([]), tp1, tvm.runtime.convert([tp1]), tvm.runtime.convert([])\n    )\n\n    tup_ty = relay.TupleType(tvm.runtime.convert([tensor_type, tf]))\n    check_kind(tup_ty)\n\n\nif __name__ == \"__main__\":\n    test_tuple_kind()\n    test_func_kind()\n    test_ref_kind()\n    test_relation_kind()\n    test_global_typevar_kind()\n    test_typecall_kind()\n    test_invalid_tuple_kind()\n    test_invalid_func_kind()\n    test_invalid_ref_kind()\n    test_invalid_relation_kind()\n    test_typecall_invalid_callee()\n    test_typecall_invalid_args()\n    test_typecall_invalid_num_args()\n    test_func_with_invalid_ret_type()\n    test_func_with_invalid_arg_types()\n    test_func_with_invalid_tuple()\n    test_func_with_invalid_relation()\n    test_tuple_with_invalid_func()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_collage_partition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nimport pytest\nfrom tvm.relay.transform import CollagePartition, InferType, CapturePostDfsIndexInSpans\nfrom tvm.target import make_compilation_config\nfrom tvm.relay.collage import MockCostEstimator\nfrom unittest.mock import patch\nfrom tvm.relay.dataflow_pattern import is_op, wildcard\n\n\n# We'll reuse the target kind \"example_target_hook\" (registered in\n# src/relay/backend/contrib/example_target_hooks/target.cc) as our\n# example external codegen target.\n\n\ndef test_pattern_table():\n    def relu_pattern():\n        return is_op(\"nn.relu\")(wildcard())\n\n    def add_pattern():\n        return is_op(\"add\")(wildcard(), wildcard())\n\n    def concatenate_pattern():\n        return is_op(\"concatenate\")(wildcard())\n\n    def predicate(expr):\n        return True\n\n    return [\n        (\"relu\", relu_pattern(), predicate),\n        (\"add\", add_pattern(), predicate),\n        (\"concatenate\", concatenate_pattern(), predicate),\n    ]\n\n\ndef _mock_get_pattern_table(target):\n    if target == \"example_target_hook\":\n        return test_pattern_table()\n\n\ndef run_collage(\n    input_mod, targets, cost_estimator, expected_mod, tvm_max_depth=8, byoc_max_depth=8\n):\n    ctxt = {\n        \"relay.collage.tvm_max_depth\": tvm_max_depth,\n        \"relay.collage.byoc_max_depth\": byoc_max_depth,\n    }\n    expected_mod = InferType()(expected_mod)\n    pass_ctxt = tvm.transform.PassContext(config=ctxt)\n    with pass_ctxt:\n        config = make_compilation_config(pass_ctxt, targets)\n        actual_mod = InferType()(input_mod)\n        # Capture indexes only to help debug failing tests\n        actual_mod = CapturePostDfsIndexInSpans()(actual_mod)\n        actual_mod = CollagePartition(config, cost_estimator)(actual_mod)\n\n        if not tvm.ir.structural_equal(actual_mod, expected_mod, map_free_vars=True):\n            # Print everything in full so we can see what's going on when things fail.\n            print(\"Input module:\")\n            print(input_mod)\n            print(\"Actual module:\")\n            print(actual_mod)\n            print(\"Expected module:\")\n            print(expected_mod)\n            # Assert again so as to see the actual disagreeing sub-expressions.\n            tvm.ir.assert_structural_equal(actual_mod, expected_mod, map_free_vars=True)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_partition_single_op_llvm(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        nn.relu(%x)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        nn.relu(%x)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 1,\n            \"example_target_hook\": 2,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_partition_single_op_byoc(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        nn.relu(%x)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_01)\n        };\n        %0(%FunctionVar_0)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        @collage_example_target_hook_nn_relu(%x)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod)\n\n\n@pytest.mark.parametrize(\"byoc_max_depth\", [1, 3])\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_partition_diamond_valid_topology(mock_get_pattern_table, byoc_max_depth):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = abs(%0);\n        %2 = nn.relu(%1);\n        add(%1, %2)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_3_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_01)\n        };\n        %0(%FunctionVar_0)\n      }\n\n      def @collage_example_target_hook_nn_relu_add(%FunctionVar_02: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu_add\") -> Tensor[(10, 10), float32] {\n        %1 = fn (%FunctionVar_04: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_04)\n        };\n        %2 = %1(%FunctionVar_02);\n        %3 = fn (%FunctionVar_03: Tensor[(10, 10), float32], %FunctionVar_1: Tensor[(10, 10), float32], Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_03, %FunctionVar_1)\n        };\n        %3(%FunctionVar_02, %2)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        %4 = @collage_example_target_hook_nn_relu(%x);\n        %5 = abs(%4);\n        @collage_example_target_hook_nn_relu_add(%5)\n      }\n    \"\"\"\n    expected_1_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_02)\n        };\n        %1 = %0(%FunctionVar_0);\n        %2 = fn (%FunctionVar_01: Tensor[(10, 10), float32], %FunctionVar_1: Tensor[(10, 10), float32], Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_01, %FunctionVar_1)\n        };\n        %2(%FunctionVar_0, %1)\n      }\n\n      def @collage_example_target_hook_nn_relu(%FunctionVar_03: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu\") -> Tensor[(10, 10), float32] {\n        %3 = fn (%FunctionVar_04: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_04)\n        };\n        %3(%FunctionVar_03)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        %4 = @collage_example_target_hook_nn_relu(%x);\n        %5 = abs(%4);\n        @collage_example_target_hook(%5)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_1_txt if byoc_max_depth == 1 else expected_3_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        }\n    )\n    run_collage(\n        mod, targets, cost_estimator, expected_mod, tvm_max_depth=1, byoc_max_depth=byoc_max_depth\n    )\n\n\n@pytest.mark.parametrize(\"tvm_max_depth\", [1, 2, 3])\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_tvm_max_depth(mock_get_pattern_table, tvm_max_depth):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        nn.relu(%1)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txts = {\n        1: \"\"\"\n          #[version = \"0.0.5\"]\n          def @collage_example_target_hook(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook\") -> Tensor[(10, 10), float32] {\n            %0 = fn (%FunctionVar_03: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_03)\n            };\n            %1 = %0(%FunctionVar_0);\n            %2 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_02)\n            };\n            %3 = %2(%1);\n            %4 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_01)\n            };\n            %4(%3)\n          }\n\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            @collage_example_target_hook(%x)\n          }\n        \"\"\",\n        2: \"\"\"\n          #[version = \"0.0.5\"]\n          def @collage_example_target_hook_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu\") -> Tensor[(10, 10), float32] {\n            %0 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_01)\n            };\n            %0(%FunctionVar_0)\n          }\n\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            %1 = @collage_example_target_hook_nn_relu(%x);\n            %2 = nn.relu(%1);\n            nn.relu(%2)\n          }\n        \"\"\",\n        3: \"\"\"\n          #[version = \"0.0.5\"]\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            %0 = nn.relu(%x);\n            %1 = nn.relu(%0);\n            nn.relu(%1)\n          }\n        \"\"\",\n    }\n    expected_mod = tvm.parser.fromtext(expected_txts[tvm_max_depth])\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 100,\n            \"example_target_hook\": 99,\n        }\n    )\n    run_collage(\n        mod, targets, cost_estimator, expected_mod, tvm_max_depth=tvm_max_depth, byoc_max_depth=1\n    )\n\n\n@pytest.mark.parametrize(\"byoc_max_depth\", [1, 2, 3])\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_byoc_max_depth(mock_get_pattern_table, byoc_max_depth):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        nn.relu(%1)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txts = {\n        1: \"\"\"\n          #[version = \"0.0.5\"]\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            %0 = nn.relu(%x);\n            %1 = nn.relu(%0);\n            nn.relu(%1)\n          }\n        \"\"\",\n        2: \"\"\"\n          #[version = \"0.0.5\"]\n          def @collage_example_target_hook_nn_relu_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu_nn_relu\") -> Tensor[(10, 10), float32] {\n            %0 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_02)\n            };\n            %1 = %0(%FunctionVar_0);\n            %2 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_01)\n            };\n            %2(%1)\n          }\n\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            %3 = nn.relu(%x);\n            @collage_example_target_hook_nn_relu_nn_relu(%3)\n          }\n        \"\"\",\n        3: \"\"\"\n          #[version = \"0.0.5\"]\n          def @collage_example_target_hook_nn_relu_nn_relu_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu_nn_relu_nn_relu\") -> Tensor[(10, 10), float32] {\n            %0 = fn (%FunctionVar_03: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_03)\n            };\n            %1 = %0(%FunctionVar_0);\n            %2 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_02)\n            };\n            %3 = %2(%1);\n            %4 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n              nn.relu(%FunctionVar_01)\n            };\n            %4(%3)\n          }\n\n          def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n            @collage_example_target_hook_nn_relu_nn_relu_nn_relu(%x)\n          }\n        \"\"\",\n    }\n    expected_mod = tvm.parser.fromtext(expected_txts[byoc_max_depth])\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 99,\n            \"example_target_hook\": 100,\n        }\n    )\n    run_collage(\n        mod, targets, cost_estimator, expected_mod, tvm_max_depth=1, byoc_max_depth=byoc_max_depth\n    )\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_partition_output_tuple(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        %2 = abs(%1);\n        (%0, %1, %2)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook\") -> (Tensor[(10, 10), float32], Tensor[(10, 10), float32]) {\n        %0 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_01)\n        };\n        %1 = %0(%FunctionVar_0);\n        %2 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_02)\n        };\n        %3 = %2(%1);\n        (%1, %3)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> (Tensor[(10, 10), float32], Tensor[(10, 10), float32], Tensor[(10, 10), float32]) {\n        %4 = @collage_example_target_hook(%x);\n        %5 = %4.1;\n        %6 = %4.0;\n        %7 = abs(%5);\n        (%6, %5, %7)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod, tvm_max_depth=2, byoc_max_depth=2)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_partition_intermediate_tuple(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        %2 = (%0, %1);\n        concatenate(%2)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook(%FunctionVar_0: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook\") -> (Tensor[(10, 10), float32], Tensor[(10, 10), float32]) {\n        %0 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_01)\n        };\n        %1 = %0(%FunctionVar_0);\n        %2 = fn (%FunctionVar_02: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_02)\n        };\n        %3 = %2(%1);\n        (%1, %3)\n      }\n\n      def @collage_example_target_hook_concatenate(%FunctionVar_03: (Tensor[(10, 10), float32], Tensor[(10, 10), float32]), Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_concatenate\") -> Tensor[(20, 10), float32] {\n        %4 = fn (%FunctionVar_04: (Tensor[(10, 10), float32], Tensor[(10, 10), float32]), Composite=\"concatenate\") -> Tensor[(20, 10), float32] {\n          concatenate(%FunctionVar_04)\n        };\n        %4(%FunctionVar_03)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(20, 10), float32] {\n        %5 = @collage_example_target_hook(%x);\n        %6 = %5.0;\n        %7 = %5.1;\n        %8 = (%6, %7);\n        @collage_example_target_hook_concatenate(%8)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod, tvm_max_depth=3, byoc_max_depth=5)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_fusion_benefit(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        %2 = abs(%x);\n        %3 = nn.relu(%2);\n        %4 = add(%1, %3);\n        %5 = nn.relu(%4);\n        abs(%5)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook_nn_relu_nn_relu_nn_relu_add_nn_relu(%FunctionVar_0: Tensor[(10, 10), float32], %FunctionVar_1: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu_nn_relu_nn_relu_add_nn_relu\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_04: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_04)\n        };\n        %1 = %0(%FunctionVar_0);\n        %2 = fn (%FunctionVar_03: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_03)\n        };\n        %3 = fn (%FunctionVar_05: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_05)\n        };\n        %4 = %2(%1);\n        %5 = %3(%FunctionVar_1);\n        %6 = fn (%FunctionVar_02: Tensor[(10, 10), float32], %FunctionVar_11: Tensor[(10, 10), float32], Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_02, %FunctionVar_11)\n        };\n        %7 = %6(%4, %5);\n        %8 = fn (%FunctionVar_01: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_01)\n        };\n        %8(%7)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        %9 = abs(%x);\n        %10 = @collage_example_target_hook_nn_relu_nn_relu_nn_relu_add_nn_relu(%x, %9);\n        abs(%10)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 5,\n            \"example_target_hook\": 6,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod, tvm_max_depth=1, byoc_max_depth=5)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_double_residual(mock_get_pattern_table):\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = abs(%0);\n        %2 = add(%0, %1);\n        add(%1, %2)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook_add_add(%FunctionVar_0: Tensor[(10, 10), float32], %FunctionVar_1: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_add_add\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_02: Tensor[(10, 10), float32], %FunctionVar_12: Tensor[(10, 10), float32], Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_02, %FunctionVar_12)\n        };\n        %1 = %0(%FunctionVar_1, %FunctionVar_0);\n        %2 = fn (%FunctionVar_01: Tensor[(10, 10), float32], %FunctionVar_11: Tensor[(10, 10), float32], Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_01, %FunctionVar_11)\n        };\n        %2(%FunctionVar_0, %1)\n      }\n\n      def @collage_example_target_hook_nn_relu(%FunctionVar_03: Tensor[(10, 10), float32], Primitive=1, Compiler=\"example_target_hook\", global_symbol=\"collage_example_target_hook_nn_relu\") -> Tensor[(10, 10), float32] {\n        %3 = fn (%FunctionVar_04: Tensor[(10, 10), float32], Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_04)\n        };\n        %3(%FunctionVar_03)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32]) -> Tensor[(10, 10), float32] {\n        %4 = @collage_example_target_hook_nn_relu(%x);\n        %5 = abs(%4);\n        @collage_example_target_hook_add_add(%5, %4)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        }\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod, tvm_max_depth=4, byoc_max_depth=4)\n\n\n@patch(\"tvm.relay.op.contrib.get_pattern_table\", wraps=_mock_get_pattern_table)\ndef test_pruning_heuristic(mock_get_pattern_table):\n    # In this example both the default TVM partition spec and the 'example_target_hook' partition\n    # spec will yield the same set of candidates, and those candidates will include all 7\n    # partitions of the four operators (ie 14 in total).\n    #\n    # However, the pruning heuristics will reduce those back to just two 'maximal' candidates\n    # which have all four operators fused. We'll then just estimate those for the two targets.\n    mod_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%x: Tensor[(10, 10), float32]) {\n        %0 = nn.relu(%x);\n        %1 = nn.relu(%0);\n        %2 = add(%0, %1);\n        add(%1, %2)\n      }\n    \"\"\"\n    mod = tvm.parser.fromtext(mod_txt)\n\n    expected_txt = \"\"\"\n      #[version = \"0.0.5\"]\n      def @collage_example_target_hook_nn_relu_nn_relu_add_add(\n        %FunctionVar_0: Tensor[(10, 10), float32],\n        Primitive=1,\n        Compiler=\"example_target_hook\",\n        global_symbol=\"collage_example_target_hook_nn_relu_nn_relu_add_add\") -> Tensor[(10, 10), float32] {\n        %0 = fn (%FunctionVar_03: Tensor[(10, 10), float32] , Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_03)\n        };\n        %1 = %0(%FunctionVar_0) ;\n        %2 = fn (%FunctionVar_02: Tensor[(10, 10), float32] , Composite=\"relu\") -> Tensor[(10, 10), float32] {\n          nn.relu(%FunctionVar_02)\n        };\n        %3 = %2(%1);\n        %4 = fn (%FunctionVar_04: Tensor[(10, 10), float32] , %FunctionVar_11: Tensor[(10, 10), float32] , Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_04, %FunctionVar_11)\n        };\n        %5 = %4(%1, %3);\n        %6 = fn (%FunctionVar_01: Tensor[(10, 10), float32] , %FunctionVar_1: Tensor[(10, 10), float32] , Composite=\"add\") -> Tensor[(10, 10), float32] {\n          add(%FunctionVar_01, %FunctionVar_1)\n        };\n        %6(%3, %5)\n      }\n\n      def @main(%x: Tensor[(10, 10), float32] ) -> Tensor[(10, 10), float32] {\n        @collage_example_target_hook_nn_relu_nn_relu_add_add(%x)\n      }\n    \"\"\"\n    expected_mod = tvm.parser.fromtext(expected_txt)\n\n    targets = [\n        tvm.target.Target(\"llvm\"),\n        tvm.target.Target(\"example_target_hook\"),\n    ]\n\n    cost_estimator = MockCostEstimator(\n        {\n            \"llvm\": 2,\n            \"example_target_hook\": 1,\n        },\n        # Limit the number of cost estimations to 2 to assert pruning did its job.\n        max_estimates=2,\n    )\n    run_collage(mod, targets, cost_estimator, expected_mod, tvm_max_depth=4, byoc_max_depth=4)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_combine_parallel_batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,too-many-locals,too-many-arguments,missing-module-docstring\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef run_opt_pass(expr, opt_pass):\n    \"runs the opt_pass on the expr of a function the function\"\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    return mod[\"main\"]\n\n\ndef test_combine_parallel_batch_matmul():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before(x, w1, w2, w3):\n        args = [x, w1, w2, w3]\n        y1 = relay.nn.batch_matmul(x, w1)\n        y2 = relay.nn.batch_matmul(x, w2)\n        y3 = relay.nn.batch_matmul(x, w3)\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, w3):\n        # use a fixed order of args so alpha equal check can pass\n        s1 = w1.type_annotation.shape[1]\n        s2 = w2.type_annotation.shape[1]\n        s3 = w3.type_annotation.shape[1]\n        args = [x, w1, w2, w3]\n        w = relay.concatenate((w1, w2, w3), axis=1)\n        y = relay.nn.batch_matmul(x, w)\n        y1 = relay.strided_slice(\n            y, begin=[0, 0, 0], end=[-1, -1, s1], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=[0, 0, s1], end=[-1, -1, s2], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y3 = relay.strided_slice(\n            y, begin=[0, 0, s1 + s2], end=[-1, -1, s3], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def check(b, i, j, k):\n        x = relay.var(\"x\", shape=(b, i, k))\n        w1 = relay.var(\"w1\", shape=(b, j, k))\n        w2 = relay.var(\"w2\", shape=(b, j, k))\n        w3 = relay.var(\"w3\", shape=(b, j, k))\n\n        y_before = before(x, w1, w2, w3)\n        y = run_opt_pass(y_before, transform.CombineParallelBatchMatmul(min_num_branches=2))\n        y_expected = expected(x, w1, w2, w3)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(2, 3, 5, 4)\n    check(1, 100, 200, 300)\n\n\ndef test_combine_parallel_batch_matmul_biasadd():\n    \"\"\"Simple testcase with bias\"\"\"\n\n    def before(x, w1, w2, w3, b1, b2, b3):\n        args = [x, w1, w2, w3, b1, b2, b3]\n        y1 = relay.nn.batch_matmul(x, w1)\n        y2 = relay.nn.batch_matmul(x, w2)\n        y3 = relay.nn.batch_matmul(x, w3)\n        y1 = relay.add(y1, b1)\n        y2 = relay.add(y2, b2)\n        y3 = relay.add(y3, b3)\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, w3, b1, b2, b3):\n        # use a fixed order of args so alpha equal check can pass\n        s1 = w1.type_annotation.shape[1]\n        s2 = w2.type_annotation.shape[1]\n        s3 = w3.type_annotation.shape[1]\n        args = [x, w1, w2, w3, b1, b2, b3]\n        w = relay.concatenate((w1, w2, w3), axis=1)\n        b = relay.concatenate((b1, b2, b3), axis=-1)\n        y = relay.nn.batch_matmul(x, w)\n        y = relay.add(y, b)\n        y1 = relay.strided_slice(\n            y, begin=[0, 0, 0], end=[-1, -1, s1], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=[0, 0, s1], end=[-1, -1, s2], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y3 = relay.strided_slice(\n            y, begin=[0, 0, s1 + s2], end=[-1, -1, s3], strides=[1, 1, 1], slice_mode=\"size\"\n        )\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def check(b, i, j, k):\n        x = relay.var(\"x\", shape=(b, i, k))\n        w1 = relay.var(\"w1\", shape=(b, j, k))\n        w2 = relay.var(\"w2\", shape=(b, j, k))\n        w3 = relay.var(\"w3\", shape=(b, j, k))\n        b1 = relay.var(\"b1\", shape=(j,))\n        b2 = relay.var(\"b2\", shape=(j,))\n        b3 = relay.var(\"b3\", shape=(j,))\n\n        y_before = before(x, w1, w2, w3, b1, b2, b3)\n        y = run_opt_pass(y_before, transform.CombineParallelBatchMatmul(min_num_branches=2))\n        y_expected = expected(x, w1, w2, w3, b1, b2, b3)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(2, 3, 5, 4)\n    check(1, 100, 200, 300)\n\n\nif __name__ == \"__main__\":\n    test_combine_parallel_batch_matmul()\n    test_combine_parallel_batch_matmul_biasadd()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_combine_parallel_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef run_combine_parallel(expr, min_num_branches=3):\n    mod = tvm.IRModule.from_expr(expr)\n    mod = transform.CombineParallelConv2D(min_num_branches)(mod)\n    return mod[\"main\"]\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    return mod[\"main\"]\n\n\ndef test_combine_parallel_conv2d():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before(x, w1, w2, w3, w4):\n        args = [x, w1, w2, w3, w4]\n        y1 = relay.nn.conv2d(x, w1)\n        y2 = relay.nn.conv2d(x, w2)\n        # y3 cannot be combined\n        y3 = relay.nn.conv2d(x, w3)\n        y4 = relay.nn.conv2d(x, w4)\n        y5 = relay.nn.max_pool2d(x)\n        y = relay.Tuple((y1, y2, y3, y4, y5))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, w3, w4, channels1, channels2, channels3, channels4):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, w1, w2, w3, w4]\n        w = relay.concatenate((w1, w2, w4), axis=0)\n        y = relay.nn.conv2d(x, w, channels=channels1 + channels2 + channels4)\n        y1 = relay.strided_slice(\n            y, begin=[0, 0], end=[-1, channels1], strides=[1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=[0, channels1], end=[-1, channels2], strides=[1, 1], slice_mode=\"size\"\n        )\n        y3 = relay.nn.conv2d(x, w3)\n        y4 = relay.strided_slice(\n            y,\n            begin=[0, channels1 + channels2],\n            end=[-1, channels4],\n            strides=[1, 1],\n            slice_mode=\"size\",\n        )\n        y5 = relay.nn.max_pool2d(x)\n        y = relay.Tuple((y1, y2, y3, y4, y5))\n        return relay.Function(args, y)\n\n    def check(x_shape, channels1, channels2, channels3, channels4):\n        x = relay.var(\"x\", shape=x_shape)\n        in_c = x_shape[1]\n        w1 = relay.var(\"w1\", shape=(channels1, in_c, 1, 1))\n        w2 = relay.var(\"w2\", shape=(channels2, in_c, 1, 1))\n        w3 = relay.var(\"w3\", shape=(channels3, in_c, 3, 3))\n        w4 = relay.var(\"w4\", shape=(channels4, in_c, 1, 1))\n\n        y_before = before(x, w1, w2, w3, w4)\n        y = run_opt_pass(y_before, transform.CombineParallelConv2D(min_num_branches=2))\n        y_expected = expected(x, w1, w2, w3, w4, channels1, channels2, channels3, channels4)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y, y_expected, map_free_vars=True)\n\n    check((1, 4, 16, 16), 4, 4, 4, 4)\n    check((1, 4, 16, 16), 4, 8, 4, 7)\n\n\ndef test_combine_parallel_conv2d_scale_relu():\n    \"\"\"Testcase of combining conv2d + scale + relu\"\"\"\n\n    def before(x, w1, w2, scale1, scale2, bias):\n        args = [x, w1, w2, scale1, scale2, bias]\n        y1 = relay.nn.conv2d(x, w1)\n        y1 = relay.multiply(y1, scale1)\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(x, w2)\n        y2 = relay.multiply(y2, scale2)\n        y2 = relay.nn.relu(y2)\n        y2 = relay.add(y2, bias)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, scale1, scale2, bias, channels1, channels2):\n        args = [x, w1, w2, scale1, scale2, bias]\n        w = relay.concatenate((w1, w2), axis=0)\n        scale = relay.concatenate((scale1, scale2), axis=0)\n        y = relay.nn.conv2d(x, w, channels=channels1 + channels2)\n        y = relay.multiply(y, scale)\n        y = relay.nn.relu(y)\n        y1 = relay.strided_slice(\n            y, begin=[0, 0], end=[-1, channels1], strides=[1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=[0, channels1], end=[-1, channels2], strides=[1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.add(y2, bias)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def check(x_shape, channels1, channels2):\n        x = relay.var(\"x\", shape=x_shape)\n        in_c = x_shape[1]\n        w1 = relay.var(\"w1\", shape=(channels1, in_c, 1, 1))\n        w2 = relay.var(\"w2\", shape=(channels2, in_c, 1, 1))\n        scale1 = relay.var(\"scale1\", shape=(channels1, 1, 1))\n        scale2 = relay.var(\"scale2\", shape=(channels2, 1, 1))\n        bias = relay.var(\"bias\", shape=(channels2, 1, 1))\n        y_before = before(x, w1, w2, scale1, scale2, bias)\n        y = run_opt_pass(y_before, transform.CombineParallelConv2D(min_num_branches=2))\n        y_expected = expected(x, w1, w2, scale1, scale2, bias, channels1, channels2)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y, y_expected, map_free_vars=True)\n\n    check((1, 4, 16, 16), 4, 8)\n\n\ndef test_combine_parallel_conv2d_scale():\n    \"\"\"Testcase of un-combinable scale\"\"\"\n\n    def before(x, w1, w2, scale1, scale2):\n        args = [x, w1, w2, scale1, scale2]\n        y1 = relay.nn.conv2d(x, w1)\n        y1 = relay.multiply(y1, scale1)\n        y2 = relay.nn.conv2d(x, w2)\n        y2 = relay.multiply(y2, scale2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, scale1, scale2, channels1, channels2):\n        args = [x, w1, w2, scale1, scale2]\n        w = relay.concatenate((w1, w2), axis=0)\n        y = relay.nn.conv2d(x, w, channels=channels1 + channels2)\n        y1 = relay.strided_slice(\n            y, begin=[0, 0], end=[-1, channels1], strides=[1, 1], slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=[0, channels1], end=[-1, channels2], strides=[1, 1], slice_mode=\"size\"\n        )\n        y1 = relay.multiply(y1, scale1)\n        y2 = relay.multiply(y2, scale2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def check(x_shape, channels1, channels2):\n        x = relay.var(\"x\", shape=x_shape)\n        in_c = x_shape[1]\n        w1 = relay.var(\"w1\", shape=(channels1, in_c, 1, 1))\n        w2 = relay.var(\"w2\", shape=(channels2, in_c, 1, 1))\n        scale1 = relay.var(\"scale1\", shape=(1,))\n        scale2 = relay.var(\"scale2\", shape=(1,))\n        y_before = before(x, w1, w2, scale1, scale2)\n        y = run_opt_pass(y_before, transform.CombineParallelConv2D(min_num_branches=2))\n        y_expected = expected(x, w1, w2, scale1, scale2, channels1, channels2)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y, y_expected, map_free_vars=True)\n\n    check((1, 4, 16, 16), 4, 8)\n\n\ndef test_combine_parallel_conv2d_multiple_blocks():\n    def before(x, w, repeat):\n        args = [x, w]\n        y = x\n        for i in range(repeat):\n            y1 = relay.nn.conv2d(y, w)\n            y2 = relay.nn.conv2d(y, w)\n            y = relay.concatenate((y1, y2), axis=1)\n        return relay.Function(args, y)\n\n    def expected(x, w, channels, repeat):\n        args = [x, w]\n        y = x\n        for i in range(repeat):\n            w_concat = relay.concatenate((w, w), axis=0)\n            y = relay.nn.conv2d(y, w_concat, channels=channels * 2)\n            y1 = relay.strided_slice(\n                y, begin=[0, 0], end=[-1, channels], strides=[1, 1], slice_mode=\"size\"\n            )\n            y2 = relay.strided_slice(\n                y, begin=[0, channels], end=[-1, channels], strides=[1, 1], slice_mode=\"size\"\n            )\n            y = relay.concatenate((y1, y2), axis=1)\n        return relay.Function(args, y)\n\n    def check(x_shape, repeat):\n        x = relay.var(\"x\", shape=x_shape)\n        in_c = x_shape[1]\n        out_c = in_c // 2\n        w = relay.var(\"w\", shape=(out_c, in_c, 1, 1))\n        y_before = before(x, w, repeat)\n        y = run_opt_pass(y_before, transform.CombineParallelConv2D(min_num_branches=2))\n        y_expected = expected(x, w, out_c, repeat)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y, y_expected, map_free_vars=True)\n\n    check((1, 4, 16, 16), 4)\n\n\nif __name__ == \"__main__\":\n    test_combine_parallel_conv2d()\n    test_combine_parallel_conv2d_scale_relu()\n    test_combine_parallel_conv2d_scale()\n    test_combine_parallel_conv2d_multiple_blocks()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_combine_parallel_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef run_combine_parallel(expr, min_num_branches=3, to_batch=True):\n    mod = tvm.IRModule.from_expr(expr)\n    mod = transform.CombineParallelDense(min_num_branches, to_batch)(mod)\n    return mod[\"main\"]\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    return mod[\"main\"]\n\n\ndef test_combine_parallel_dense():\n    \"\"\"Simple testcase. One dense cannot be combined due to shape mismatch\"\"\"\n\n    def before(x, w1, w2, w3, w4):\n        args = [x, w1, w2, w3, w4]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n\n        # y3 cannot be combined\n        y3 = relay.nn.dense(x, w3)\n\n        y4 = relay.nn.dense(x, w4)\n        y = relay.Tuple((y1, y2, y3, y4))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, w3, w4):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, w1, w2, w3, w4]\n        x_stacked = relay.stack((x, x, x), axis=0)\n        w = relay.stack((w1, w2, w4), axis=0)\n        y = relay.nn.batch_matmul(x_stacked, w)\n        (y1, y2, y4) = relay.split(y, 3)\n        y1 = relay.squeeze(y1, [0])\n        y2 = relay.squeeze(y2, [0])\n        y4 = relay.squeeze(y4, [0])\n\n        # y3 cannot be combined\n        y3 = relay.nn.dense(x, w3)\n\n        y = relay.Tuple((y1, y2, y3, y4))\n        return relay.Function(args, y)\n\n    def check(i, j, k):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(j, k))\n        w3 = relay.var(\"w3\", shape=(j + 1, k))\n        w4 = relay.var(\"w4\", shape=(j, k))\n\n        y_before = before(x, w1, w2, w3, w4)\n        y = run_opt_pass(y_before, transform.CombineParallelDense(min_num_branches=2))\n        y_expected = expected(x, w1, w2, w3, w4)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4)\n    check(100, 200, 300)\n\n\ndef test_combine_parallel_dense_biasadd():\n    \"\"\"Testcase of combining dense + 1d biasadd\"\"\"\n\n    def before(x, w1, w2, b1, b2):\n        args = [x, w1, w2, b1, b2]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n        y1 = relay.add(y1, b1)\n        y2 = relay.add(y2, b2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, b1, b2, is_2d_bias):\n        args = [x, w1, w2, b1, b2]\n        x_stacked = relay.stack((x, x), axis=0)\n        w = relay.stack((w1, w2), axis=0)\n        y = relay.nn.batch_matmul(x_stacked, w)\n\n        if not is_2d_bias:\n            b1 = relay.expand_dims(b1, 0)\n            b2 = relay.expand_dims(b2, 0)\n\n        b = relay.stack((b1, b2), axis=0)\n        y = relay.add(y, b)\n        (y1, y2) = relay.split(y, 2)\n        y1 = relay.squeeze(y1, [0])\n        y2 = relay.squeeze(y2, [0])\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def check(i, j, k, is_2d_bias):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(j, k))\n\n        if is_2d_bias:\n            b1 = relay.var(\"b1\", shape=(i, j))\n            b2 = relay.var(\"b2\", shape=(i, j))\n        else:\n            b1 = relay.var(\"b1\", shape=(j,))\n            b2 = relay.var(\"b2\", shape=(j,))\n\n        y_before = before(x, w1, w2, b1, b2)\n        y = run_opt_pass(y_before, transform.CombineParallelDense(min_num_branches=2))\n        y_expected = expected(x, w1, w2, b1, b2, is_2d_bias)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4, False)\n    check(100, 200, 300, False)\n    check(3, 5, 4, True)\n    check(100, 200, 300, True)\n\n\ndef test_combine_parallel_dense_biasadd_scale_reshape():\n    \"\"\"Testcase of combining dense + 1d biasadd + multiply with non-fused reshape\"\"\"\n\n    def before(x, w1, w2, b1, b2, scale1, scale2, newshape):\n        args = [x, w1, w2, b1, b2, scale1, scale2]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n        y1 = relay.add(y1, b1)\n        y2 = relay.add(y2, b2)\n        y1 = relay.multiply(y1, scale1)\n        y2 = relay.multiply(y2, scale2)\n        y1 = relay.reshape(y1, newshape=newshape)\n        y2 = relay.reshape(y2, newshape=newshape)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, b1, b2, scale1, scale2, newshape):\n        args = [x, w1, w2, b1, b2, scale1, scale2]\n        x_stacked = relay.stack((x, x), axis=0)\n        w = relay.stack((w1, w2), axis=0)\n        y = relay.nn.batch_matmul(x_stacked, w)\n        b1 = relay.expand_dims(b1, 0)\n        b2 = relay.expand_dims(b2, 0)\n        b = relay.stack((b1, b2), axis=0)\n        y = relay.add(y, b)\n        scale1 = relay.expand_dims(scale1, 0)\n        scale2 = relay.expand_dims(scale2, 0)\n        scale = relay.stack((scale1, scale2), axis=0)\n        y = relay.multiply(y, scale)\n        (y1, y2) = relay.split(y, 2)\n        y1 = relay.squeeze(y1, [0])\n        y2 = relay.squeeze(y2, [0])\n        y1 = relay.reshape(y1, newshape=newshape)\n        y2 = relay.reshape(y2, newshape=newshape)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def check(i, j, k, scale1, scale2, newshape):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(j, k))\n        b1 = relay.var(\"b1\", shape=(j,))\n        b2 = relay.var(\"b2\", shape=(j,))\n        scale1 = relay.var(\"scale1\", shape=(1,))\n        scale2 = relay.var(\"scale2\", shape=(1,))\n\n        y_before = before(x, w1, w2, b1, b2, scale1, scale2, newshape)\n        y = run_opt_pass(y_before, transform.CombineParallelDense(min_num_branches=2))\n        y_expected = expected(x, w1, w2, b1, b2, scale1, scale2, newshape)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4, 0.5, 0.25, (1, 1, 15))\n    check(100, 200, 300, 0.5, 0.25, (1, 1, 20000))\n\n\ndef test_combine_parallel_dense_flat():\n    \"\"\"Simple testcase. All matmul of different output dim can be combined\"\"\"\n\n    def before(x, w1, w2, w3):\n        args = [x, w1, w2, w3]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n        y3 = relay.nn.dense(x, w3)\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, w3, j):\n        args = [x, w1, w2, w3]\n        w_stacked = relay.concatenate((w1, w2, w3), axis=0)\n        y = relay.nn.dense(x, w_stacked, units=6 * j)\n        strides = [1, 1]\n        y1 = relay.strided_slice(y, begin=[0, 0], end=[-1, j], strides=strides, slice_mode=\"size\")\n        y2 = relay.strided_slice(\n            y, begin=[0, j], end=[-1, 2 * j], strides=strides, slice_mode=\"size\"\n        )\n        y3 = relay.strided_slice(\n            y, begin=[0, 3 * j], end=[-1, 3 * j], strides=strides, slice_mode=\"size\"\n        )\n        y = relay.Tuple((y1, y2, y3))\n        return relay.Function(args, y)\n\n    def check(i, j, k):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(2 * j, k))\n        w3 = relay.var(\"w3\", shape=(3 * j, k))\n\n        y_before = before(x, w1, w2, w3)\n        combine_pass = transform.CombineParallelDense(min_num_branches=3, to_batch=False)\n        y = run_opt_pass(y_before, combine_pass)\n        y_expected = expected(x, w1, w2, w3, j)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4)\n    check(100, 200, 300)\n\n\ndef test_combine_parallel_dense_flat_biasadd():\n    \"\"\"Testcase of combining dense + 1d biasadd with different out dims\"\"\"\n\n    def before(x, w1, w2, b1, b2):\n        args = [x, w1, w2, b1, b2]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n        y1 = relay.add(y1, b1)\n        y2 = relay.add(y2, b2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, b1, b2, j, bias_shape1, bias_shape2):\n        args = [x, w1, w2, b1, b2]\n        w_stacked = relay.concatenate((w1, w2), axis=0)\n        y = relay.nn.dense(x, w_stacked, units=3 * j)\n        n_out_dims = max(len(bias_shape1), 2)\n        if len(bias_shape1) == 0:\n            b1 = relay.repeat(relay.expand_dims(b1, -1), j, 0)\n        elif bias_shape1[-1] == 1:\n            b1 = relay.repeat(b1, j, len(bias_shape1) - 1)\n        if len(bias_shape2) == 0:\n            b2 = relay.repeat(relay.expand_dims(b2, -1), 2 * j, 0)\n        elif bias_shape2[-1] == 1:\n            b2 = relay.repeat(b2, 2 * j, len(bias_shape2) - 1)\n        b = relay.concatenate((b1, b2), axis=max(0, len(bias_shape1) - 1))\n        y = relay.add(y, b)\n        begin = [0 for _ in range(n_out_dims - 1)]\n        end = [-1 for _ in range(n_out_dims - 1)]\n        strides = [1 for _ in range(n_out_dims)]\n        y1 = relay.strided_slice(\n            y, begin=begin + [0], end=end + [j], strides=strides, slice_mode=\"size\"\n        )\n        y2 = relay.strided_slice(\n            y, begin=begin + [j], end=end + [2 * j], strides=strides, slice_mode=\"size\"\n        )\n        return relay.Function(args, relay.Tuple((y1, y2)))\n\n    def check(i, j, k, bias_shape1, bias_shape2):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(2 * j, k))\n        b1 = relay.var(\"b1\", shape=bias_shape1)\n        b2 = relay.var(\"b2\", shape=bias_shape2)\n\n        y_before = before(x, w1, w2, b1, b2)\n        combine_pass = transform.CombineParallelDense(min_num_branches=2, to_batch=False)\n        y = run_opt_pass(y_before, combine_pass)\n        y_expected = expected(x, w1, w2, b1, b2, j, bias_shape1, bias_shape2)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4, (), ())\n    check(3, 5, 4, (1,), (1,))\n    check(3, 5, 4, (5,), (1,))\n    check(3, 5, 4, (1,), (10,))\n    check(3, 5, 4, (3, 1), (3, 1))\n    check(3, 5, 4, (3, 5), (3, 10))\n    check(3, 5, 4, (3, 1), (3, 10))\n    check(3, 5, 4, (3, 5), (3, 1))\n    check(3, 5, 4, (9, 3, 5), (9, 3, 10))\n    check(3, 5, 4, (9, 3, 5), (9, 3, 1))\n    check(3, 5, 4, (9, 3, 1), (9, 3, 10))\n\n\ndef test_combine_parallel_dense_flat_biasadd_scale_reshape():\n    \"\"\"Testcase of combining dense with different out dims\n    following bias add, scale, reshape ops\n    \"\"\"\n\n    def before(x, w1, w2, b1, b2, scale1, scale2, newshape1, newshape2):\n        args = [x, w1, w2, b1, b2, scale1, scale2]\n        y1 = relay.nn.dense(x, w1)\n        y2 = relay.nn.dense(x, w2)\n        y1 = relay.add(y1, b1)\n        y2 = relay.add(y2, b2)\n        y1 = relay.multiply(y1, scale1)\n        y2 = relay.multiply(y2, scale2)\n        y1 = relay.reshape(y1, newshape=newshape1)\n        y2 = relay.reshape(y2, newshape=newshape2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def expected(x, w1, w2, b1, b2, scale1, scale2, newshape1, newshape2, j):\n        args = [x, w1, w2, b1, b2, scale1, scale2]\n        w_stacked = relay.concatenate((w1, w2), axis=0)\n        y = relay.nn.dense(x, w_stacked, units=3 * j)\n        b = relay.concatenate((b1, b2), axis=0)\n        y = relay.add(y, b)\n        scale1 = relay.repeat(scale1, j, 0)\n        scale2 = relay.repeat(scale2, 2 * j, 0)\n        scale = relay.concatenate((scale1, scale2), axis=0)\n        y = relay.multiply(y, scale)\n        strides = [1, 1]\n        y1 = relay.strided_slice(y, begin=[0, 0], end=[-1, j], strides=strides, slice_mode=\"size\")\n        y2 = relay.strided_slice(\n            y, begin=[0, j], end=[-1, 2 * j], strides=strides, slice_mode=\"size\"\n        )\n        y1 = relay.reshape(y1, newshape=newshape1)\n        y2 = relay.reshape(y2, newshape=newshape2)\n        y = relay.Tuple((y1, y2))\n        return relay.Function(args, y)\n\n    def check(i, j, k, scale1, scale2, newshape1, newshape2):\n        x = relay.var(\"x\", shape=(i, k))\n        w1 = relay.var(\"w1\", shape=(j, k))\n        w2 = relay.var(\"w2\", shape=(2 * j, k))\n        b1 = relay.var(\"b1\", shape=(j,))\n        b2 = relay.var(\"b2\", shape=(2 * j,))\n        scale1 = relay.var(\"scale1\", shape=(1,))\n        scale2 = relay.var(\"scale2\", shape=(1,))\n\n        y_before = before(x, w1, w2, b1, b2, scale1, scale2, newshape1, newshape2)\n        combine_pass = transform.CombineParallelDense(min_num_branches=2, to_batch=False)\n        y = run_opt_pass(y_before, combine_pass)\n        y_expected = expected(x, w1, w2, b1, b2, scale1, scale2, newshape1, newshape2, j)\n        y_expected = run_opt_pass(y_expected, transform.InferType())\n        tvm.ir.assert_structural_equal(y, y_expected, map_free_vars=True)\n\n    check(3, 5, 4, 0.5, 0.25, (1, 1, 15), (1, 1, 30))\n    check(100, 200, 300, 0.5, 0.25, (1, 1, 20000), (1, 1, 40000))\n\n\nif __name__ == \"__main__\":\n    test_combine_parallel_dense()\n    test_combine_parallel_dense_biasadd()\n    test_combine_parallel_dense_biasadd_scale_reshape()\n    test_combine_parallel_dense_flat()\n    test_combine_parallel_dense_flat_biasadd()\n    test_combine_parallel_dense_flat_biasadd_scale_reshape()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_convert_op_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test alter op layout pass\"\"\"\nimport pytest\nimport tvm\nfrom tvm import relay, te\nfrom tvm.relay import analysis, transform\nfrom tvm.relay.op import op as reg\nfrom tvm.relay.op import register_alter_op_layout\nfrom tvm.relay.transform.infer_layout_utils import InferCorrectLayoutOutput\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_no_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        return before()\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_binary_no_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(2, 2))\n        y = relay.var(\"y\", shape=(1, 2))\n        return relay.Function(\n            [x, y],\n            relay.qnn.op.add(\n                x,\n                y,\n                lhs_scale=relay.const(0.0156863, \"float32\"),\n                lhs_zero_point=relay.const(127, \"int32\"),\n                rhs_scale=relay.const(0.0117647, \"float32\"),\n                rhs_zero_point=relay.const(85, \"int32\"),\n                output_scale=relay.const(0.0235294, \"float32\"),\n                output_zero_point=relay.const(128, \"int32\"),\n            ),\n        )\n\n    def expected():\n        return before()\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({}))\n    b = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_nhwc_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight = relay.layout_transform(weight, \"OIHW\", \"HWIO\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_transpose_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d_transpose(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"IOHW\")\n        y = relay.nn.conv2d_transpose(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d_transpose\": [\"NCHW\", \"IOHW\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_bias_pool_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.bias_add(y, bias, axis=3)\n        # a useless tuple, which will be eliminated\n        y = relay.Tuple([y])[0]\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NHWC\")\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n\n        bias = relay.expand_dims(bias, axis=0, num_newaxis=3)\n        bias = relay.layout_transform(bias, \"NHWC\", \"NCHW\")\n        y = relay.add(y, bias)\n        # a useless tuple, which will be eliminated\n        y = relay.Tuple([y])[0]\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2))\n        y = relay.cast(y, \"int32\")\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_bias_pool_uses_specified_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.bias_add(y, bias, axis=3)\n        # a useless tuple, which will be eliminated\n        y = relay.Tuple([y])[0]\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NHWC\")\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        bias = relay.var(\"bias\", shape=(64,))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n\n        bias = relay.expand_dims(bias, axis=0, num_newaxis=3)\n        bias = relay.layout_transform(bias, \"NHWC\", \"NCHW\")\n        y = relay.add(y, bias)\n        # a useless tuple, which will be eliminated\n        y = relay.Tuple([y])[0]\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NHWC\", out_layout=\"NHWC\")\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(\n        a,\n        transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"OIHW\"], \"nn.max_pool2d\": [\"NHWC\"]}),\n    )\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n\ndef test_conv_concat_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64))\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y1 = relay.nn.conv2d(\n            y,\n            weight2,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        ret = relay.concatenate([y, y1], axis=3)\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64))\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64))\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(y, weight1, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y1 = relay.nn.conv2d(y, weight2, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        ret = relay.concatenate([y, y1], axis=1)\n        ret = relay.layout_transform(ret, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_deformable_conv_bias_pool_convert_layout():\n    def before(N, CI, H, W, CO, KH, KW, layout):\n        if layout == \"NCHW\":\n            data_shape = (N, CI, H, W)\n            weight_shape = (CO, CI, KH, KW)\n            kernel_layout = \"OIHW\"\n        else:\n            data_shape = (N, H, W, CI)\n            weight_shape = (KH, KW, CI, CO)\n            kernel_layout = \"HWIO\"\n        bias_shape = (CO,)\n\n        data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n        offset = relay.var(\"offset\")\n        weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n        y = relay.nn.deformable_conv2d(\n            data,\n            offset,\n            weight,\n            kernel_size=(KH, KW),\n            channels=CO,\n            data_layout=layout,\n            kernel_layout=kernel_layout,\n        )\n        y = relay.nn.bias_add(y, bias, axis=-1 if layout == \"NHWC\" else 1)\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=layout)\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected(N, CI, H, W, CO, KH, KW, OH, OW, src_layout, dst_layout):\n        layout_map = {\"src\": {}, \"dst\": {}}\n        if src_layout == \"NCHW\":\n            nchw = layout_map[\"src\"]\n            nhwc = layout_map[\"dst\"]\n        else:\n            nchw = layout_map[\"dst\"]\n            nhwc = layout_map[\"src\"]\n\n        nchw[\"data_layout\"] = \"NCHW\"\n        nchw[\"data_shape\"] = (N, CI, H, W)\n        nchw[\"offset_shape\"] = (N, KH * KW * 2, OH, OW)\n        nchw[\"weight_shape\"] = (CO, CI, KH, KW)\n        nchw[\"kernel_layout\"] = \"OIHW\"\n\n        nhwc[\"data_layout\"] = \"NHWC\"\n        nhwc[\"data_shape\"] = (N, H, W, CI)\n        nhwc[\"offset_shape\"] = (N, OH, OW, KH * KW * 2)\n        nhwc[\"weight_shape\"] = (KH, KW, CI, CO)\n        nhwc[\"kernel_layout\"] = \"HWIO\"\n\n        bias_shape = (CO,)\n\n        data = relay.var(\"data\", shape=layout_map[\"src\"][\"data_shape\"], dtype=\"float32\")\n        offset = relay.var(\"offset\", shape=layout_map[\"src\"][\"offset_shape\"], dtype=\"float32\")\n        weight = relay.var(\"weight\", shape=layout_map[\"src\"][\"weight_shape\"], dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n        data = relay.layout_transform(\n            data, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        offset = relay.layout_transform(\n            offset, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        weight = relay.layout_transform(\n            weight, layout_map[\"src\"][\"kernel_layout\"], layout_map[\"dst\"][\"kernel_layout\"]\n        )\n        y = relay.nn.deformable_conv2d(\n            data,\n            offset,\n            weight,\n            kernel_size=(KH, KW),\n            channels=CO,\n            data_layout=layout_map[\"dst\"][\"data_layout\"],\n            kernel_layout=layout_map[\"dst\"][\"kernel_layout\"],\n        )\n        if layout_map[\"src\"][\"data_layout\"] == \"NHWC\":\n            bias = relay.expand_dims(bias, axis=0, num_newaxis=3)\n        else:\n            bias = relay.expand_dims(bias, axis=1, num_newaxis=2)\n            bias = relay.expand_dims(bias, axis=0)\n        bias = relay.layout_transform(\n            bias, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        y = relay.add(y, bias)\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=layout_map[\"dst\"][\"data_layout\"])\n        y = relay.cast(y, \"int32\")\n        y = relay.layout_transform(\n            y, layout_map[\"dst\"][\"data_layout\"], layout_map[\"src\"][\"data_layout\"]\n        )\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    # NHWC -> NCHW\n    a = before(1, 3, 224, 224, 32, 3, 3, \"NHWC\")\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.deformable_conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(\n        expected(1, 3, 224, 224, 32, 3, 3, 222, 222, \"NHWC\", \"NCHW\"), transform.InferType()\n    )\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    # NCHW -> NHWC\n    a = before(1, 3, 224, 224, 32, 3, 3, \"NCHW\")\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.deformable_conv2d\": [\"NHWC\", \"default\"]}))\n    b = run_opt_pass(\n        expected(1, 3, 224, 224, 32, 3, 3, 222, 222, \"NCHW\", \"NHWC\"), transform.InferType()\n    )\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_deformable_conv_bias_pool_uses_specified_convert_layout():\n    def before(N, CI, H, W, CO, KH, KW, layout):\n        if layout == \"NCHW\":\n            data_shape = (N, CI, H, W)\n            weight_shape = (CO, CI, KH, KW)\n            kernel_layout = \"OIHW\"\n        else:\n            data_shape = (N, H, W, CI)\n            weight_shape = (KH, KW, CI, CO)\n            kernel_layout = \"HWIO\"\n        bias_shape = (CO,)\n\n        data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n        offset = relay.var(\"offset\")\n        weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n        y = relay.nn.deformable_conv2d(\n            data,\n            offset,\n            weight,\n            kernel_size=(KH, KW),\n            channels=CO,\n            data_layout=layout,\n            kernel_layout=kernel_layout,\n        )\n        y = relay.nn.bias_add(y, bias, axis=-1 if layout == \"NHWC\" else 1)\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=layout)\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected(N, CI, H, W, CO, KH, KW, OH, OW, src_layout, dst_layout, max_pool_layout=None):\n        layout_map = {\"src\": {}, \"dst\": {}}\n        if src_layout == \"NCHW\":\n            nchw = layout_map[\"src\"]\n            nhwc = layout_map[\"dst\"]\n        else:\n            nchw = layout_map[\"dst\"]\n            nhwc = layout_map[\"src\"]\n\n        nchw[\"data_layout\"] = \"NCHW\"\n        nchw[\"data_shape\"] = (N, CI, H, W)\n        nchw[\"offset_shape\"] = (N, KH * KW * 2, OH, OW)\n        nchw[\"weight_shape\"] = (CO, CI, KH, KW)\n        nchw[\"kernel_layout\"] = \"OIHW\"\n\n        nhwc[\"data_layout\"] = \"NHWC\"\n        nhwc[\"data_shape\"] = (N, H, W, CI)\n        nhwc[\"offset_shape\"] = (N, OH, OW, KH * KW * 2)\n        nhwc[\"weight_shape\"] = (KH, KW, CI, CO)\n        nhwc[\"kernel_layout\"] = \"HWIO\"\n\n        bias_shape = (CO,)\n\n        data = relay.var(\"data\", shape=layout_map[\"src\"][\"data_shape\"], dtype=\"float32\")\n        offset = relay.var(\"offset\", shape=layout_map[\"src\"][\"offset_shape\"], dtype=\"float32\")\n        weight = relay.var(\"weight\", shape=layout_map[\"src\"][\"weight_shape\"], dtype=\"float32\")\n        bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n        data = relay.layout_transform(\n            data, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        offset = relay.layout_transform(\n            offset, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        weight = relay.layout_transform(\n            weight, layout_map[\"src\"][\"kernel_layout\"], layout_map[\"dst\"][\"kernel_layout\"]\n        )\n        y = relay.nn.deformable_conv2d(\n            data,\n            offset,\n            weight,\n            kernel_size=(KH, KW),\n            channels=CO,\n            data_layout=layout_map[\"dst\"][\"data_layout\"],\n            kernel_layout=layout_map[\"dst\"][\"kernel_layout\"],\n        )\n        if layout_map[\"src\"][\"data_layout\"] == \"NHWC\":\n            bias = relay.expand_dims(bias, axis=0, num_newaxis=3)\n        else:\n            bias = relay.expand_dims(bias, axis=1, num_newaxis=2)\n            bias = relay.expand_dims(bias, axis=0)\n        bias = relay.layout_transform(\n            bias, layout_map[\"src\"][\"data_layout\"], layout_map[\"dst\"][\"data_layout\"]\n        )\n        y = relay.add(y, bias)\n        y = relay.nn.relu(y)\n        if max_pool_layout != layout_map[\"dst\"][\"data_layout\"]:\n            y = relay.layout_transform(y, layout_map[\"dst\"][\"data_layout\"], max_pool_layout)\n        y = relay.nn.max_pool2d(\n            y, pool_size=(2, 2), layout=max_pool_layout, out_layout=max_pool_layout\n        )\n        y = relay.cast(y, \"int32\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    # NHWC -> NCHW\n    a = before(1, 3, 224, 224, 32, 3, 3, \"NHWC\")\n    a = run_opt_pass(\n        a,\n        transform.ConvertLayout(\n            {\"nn.deformable_conv2d\": [\"NCHW\", \"default\"], \"nn.max_pool2d\": [\"NHWC\"]}\n        ),\n    )\n    # - in the before() func, its last argument \"NHWC\" is also the layout of max_pool\n    b = run_opt_pass(\n        # max_pool has its own layout argument\n        expected(1, 3, 224, 224, 32, 3, 3, 222, 222, \"NHWC\", \"NCHW\", max_pool_layout=\"NHWC\"),\n        transform.InferType(),\n    )\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n    # NCHW -> NHWC\n    a = before(1, 3, 224, 224, 32, 3, 3, \"NCHW\")\n    a = run_opt_pass(\n        a,\n        transform.ConvertLayout(\n            {\"nn.deformable_conv2d\": [\"NHWC\", \"default\"], \"nn.max_pool2d\": [\"NCHW\"]}\n        ),\n    )\n    # - in the before() func, its last argument \"NCHW\" is also the layout of max_pool\n    b = run_opt_pass(\n        # max_pool has its own layout argument\n        expected(1, 3, 224, 224, 32, 3, 3, 222, 222, \"NCHW\", \"NHWC\", max_pool_layout=\"NCHW\"),\n        transform.InferType(),\n    )\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n\ndef test_dual_path_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 32, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y1 = relay.nn.conv2d(\n            y,\n            weight2,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.batch_flatten(y)\n        ret = relay.Tuple([y1, y2])\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 32, 32))\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(y, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y1 = relay.nn.conv2d(y, weight2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y1 = relay.nn.relu(y1)\n        y1 = relay.layout_transform(y1, \"NCHW\", \"NHWC\")\n        y2 = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y2 = relay.nn.batch_flatten(y2)\n        ret = relay.Tuple([y1, y2])\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_bn_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        gamma = relay.var(\"gamma\")\n        beta = relay.var(\"beta\")\n        mean = relay.var(\"mean\")\n        variance = relay.var(\"variance\")\n        y, _, _ = relay.nn.batch_norm(y, gamma, beta, mean, variance, axis=3)\n        return relay.Function(analysis.free_vars(y), y)\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n\n    # Check that there is only 1 NHWC to NCHW transform.\n    has_lt = list()\n    find_op = lambda x: has_lt.append(\n        isinstance(x, tvm.relay.expr.Call)\n        and x.op.name == \"layout_transform\"\n        and x.attrs.src_layout == \"NCHW\"\n        and x.attrs.dst_layout == \"NHWC\"\n    )\n    relay.analysis.post_order_visit(a, find_op)\n    has_lt = list(filter(lambda x: x, has_lt))\n    assert len(has_lt) == 1\n\n\ndef test_slice_like_convert_layout():\n    def verify_slice_like(after, expected_axes):\n        # Verify if the slice_like after the convert layout has the expected axes.\n        has_expected = list()\n        checker = lambda x: has_expected.append(\n            isinstance(x, tvm.relay.expr.Call)\n            and x.op.name == \"slice_like\"\n            and str(x.attrs.axes) == str(expected_axes)\n        )\n        relay.analysis.post_order_visit(after, checker)\n        assert any(has_expected)\n\n    def func_nhwc():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        out = relay.slice_like(y, y, axes=[1, 2])\n        return relay.Function(analysis.free_vars(out), out)\n\n    after = run_opt_pass(func_nhwc(), transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    verify_slice_like(after, [2, 3])\n\n    def func_nchw():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(32, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        out = relay.slice_like(y, y, axes=[2, 3])\n        return relay.Function(analysis.free_vars(out), out)\n\n    after = run_opt_pass(func_nchw(), transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n    verify_slice_like(after, [1, 2])\n\n    def func_vars():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        # z has no layout information so convert layout won't happen.\n        z = relay.var(\"y\", shape=(1, 56, 56, 32))\n        out = relay.slice_like(y, z, axes=[1, 2])\n        return relay.Function(analysis.free_vars(out), out)\n\n    after = run_opt_pass(func_vars(), transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    verify_slice_like(after, [1, 2])\n\n\ndef test_transpose_convert_layout():\n    def verify_transpose(after, expected_axes, expected_transform_cnt):\n        # Verify if the transpose after the convert layout has the expected axes.\n        has_expected = list()\n        checker = lambda x: has_expected.append(\n            isinstance(x, tvm.relay.expr.Call)\n            and x.op.name == \"transpose\"\n            and str(x.attrs.axes) == str(expected_axes)\n        )\n        relay.analysis.post_order_visit(after, checker)\n        assert any(has_expected), after\n\n        is_transform = list()\n        checker = lambda x: is_transform.append(\n            1 if isinstance(x, tvm.relay.expr.Call) and x.op.name == \"layout_transform\" else 0\n        )\n        relay.analysis.post_order_visit(after, checker)\n        assert (\n            sum(is_transform) == expected_transform_cnt\n        ), \"Expected %s layout_transform, but get\\n%s\" % (expected_transform_cnt, after)\n\n    def nhwc_to_nchw():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        z = relay.var(\"z\", shape=(56, 56, 32))\n        out = relay.add(y, z)\n        out = relay.transpose(out, axes=[0, 3, 1, 2])\n        out = relay.nn.batch_flatten(out)\n        func = relay.Function(analysis.free_vars(out), out)\n        return run_opt_pass(func, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n\n    verify_transpose(nhwc_to_nchw(), [0, 1, 2, 3], 3)\n\n    def nchw_to_nhwc():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(32, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        z = relay.var(\"z\", shape=(32, 56, 56))\n        out = relay.add(y, z)\n        out = relay.transpose(out, axes=[0, 2, -1, 1])  # Also test a negative axis.\n        out = relay.nn.batch_flatten(out)\n        func = relay.Function(analysis.free_vars(out), out)\n        return run_opt_pass(func, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n\n    verify_transpose(nchw_to_nhwc(), [0, 1, 2, 3], 3)\n\n    def default_axes():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(32, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        z = relay.var(\"z\", shape=(32, 56, 56))\n        out = relay.add(y, z)\n        out = relay.transpose(out)  # No axes provided, will use the reversed axes.\n        func = relay.Function(analysis.free_vars(out), out)\n        return run_opt_pass(func, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n\n    verify_transpose(default_axes(), [2, 1, 3, 0], 3)\n\n\ndef test_resnet_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(1, 1, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(\n            x, weight2, channels=32, kernel_size=(1, 1), data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n        )\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.nn.global_max_pool2d(y, layout=\"NHWC\")\n        return relay.Function(analysis.free_vars(y), y)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(1, 1, 64, 32))\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(x, weight2, channels=32, kernel_size=(1, 1))\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.nn.global_max_pool2d(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        return relay.Function(analysis.free_vars(y), y)\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_resnet_pool_uses_specified_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(1, 1, 64, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(\n            x, weight2, channels=32, kernel_size=(1, 1), data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n        )\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.nn.global_max_pool2d(y, layout=\"NHWC\")\n        return relay.Function(analysis.free_vars(y), y)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 32))\n        weight2 = relay.var(\"weight2\", shape=(1, 1, 64, 32))\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(x, weight1, channels=32, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y2 = relay.nn.conv2d(x, weight2, channels=32, kernel_size=(1, 1))\n        y2 = relay.nn.relu(y2)\n        y = y + y2\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.nn.global_max_pool2d(y, layout=\"NHWC\", out_layout=\"NHWC\")\n        return relay.Function(analysis.free_vars(y), y)\n\n    a = before()\n    a = run_opt_pass(\n        a,\n        transform.ConvertLayout(\n            {\"nn.conv2d\": [\"NCHW\", \"default\"], \"nn.global_max_pool2d\": [\"NHWC\"]}\n        ),\n    )\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n\ndef test_scalar_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.add(y, relay.const(1, \"float32\"))\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.add(y, relay.const(1.0, \"float32\"))\n\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_ln_convert_layout():\n    \"\"\"Check that layout transforms are propagated through ln.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.layer_norm(y, gamma, beta, axis=3)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.layer_norm(y, gamma, beta, axis=1)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_InstanceNorm_convert_layout():\n    \"\"\"Check that layout transforms are propagated through instance norm.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.instance_norm(y, gamma, beta, axis=3)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.instance_norm(y, gamma, beta, axis=1)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_bn_convert_layout():\n    \"\"\"Check that layout transforms are propagated through bn.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n        moving_mean = relay.var(\"moving_mean\", relay.TensorType((64,), dtype))\n        moving_var = relay.var(\"moving_var\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.batch_norm(y, gamma, beta, moving_mean, moving_var, axis=3)\n        y = relay.nn.relu(y[0])\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n\n        dtype = \"float32\"\n        beta = relay.var(\"beta\", relay.TensorType((64,), dtype))\n        gamma = relay.var(\"gamma\", relay.TensorType((64,), dtype))\n        moving_mean = relay.var(\"moving_mean\", relay.TensorType((64,), dtype))\n        moving_var = relay.var(\"moving_var\", relay.TensorType((64,), dtype))\n\n        y = relay.nn.batch_norm(y, gamma, beta, moving_mean, moving_var, axis=1)\n        y = relay.nn.relu(y[0])\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_conv_requantize_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.qnn.op.requantize(\n            y,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            out_dtype=\"int32\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.qnn.op.requantize(\n            y,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            axis=1,\n            out_dtype=\"int32\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"qnn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_conv_concat_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight1,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y1 = relay.qnn.op.conv2d(\n            y,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.cast(y, \"int8\")\n        y1 = relay.cast(y, \"int8\")\n        ret = relay.qnn.op.concatenate(\n            [y, y1],\n            [relay.const(1, \"float32\"), relay.const(1, \"float32\")],\n            [relay.const(1, \"int32\"), relay.const(1, \"int32\")],\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            axis=3,\n        )\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.qnn.op.conv2d(\n            y,\n            weight1,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y1 = relay.qnn.op.conv2d(\n            y,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.cast(y, \"int8\")\n        y1 = relay.cast(y, \"int8\")\n        ret = relay.qnn.op.concatenate(\n            [y, y1],\n            [relay.const(1, \"float32\"), relay.const(1, \"float32\")],\n            [relay.const(1, \"int32\"), relay.const(1, \"int32\")],\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            axis=1,\n        )\n        ret = relay.layout_transform(ret, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"qnn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_conv_add_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight1,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y1 = relay.qnn.op.conv2d(\n            y,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.cast(y, \"int8\")\n        y1 = relay.cast(y, \"int8\")\n        ret = relay.qnn.op.add(\n            y,\n            y1,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n        )\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight1 = relay.var(\"weight1\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        weight1 = relay.layout_transform(weight1, \"HWIO\", \"OIHW\")\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"OIHW\")\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.qnn.op.conv2d(\n            y,\n            weight1,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y1 = relay.qnn.op.conv2d(\n            y,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.cast(y, \"int8\")\n        y1 = relay.cast(y, \"int8\")\n        ret = relay.qnn.op.add(\n            y,\n            y1,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n        )\n        ret = relay.layout_transform(ret, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"qnn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_conv_nhwc_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3), dtype=\"int8\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3), dtype=\"int8\")\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight = relay.layout_transform(weight, \"OIHW\", \"HWIO\")\n        y = relay.qnn.op.conv2d(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"qnn.conv2d\": [\"NHWC\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_conv_transpose_requantize_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        y = relay.qnn.op.conv2d_transpose(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            out_dtype=\"int32\",\n        )\n        y = relay.qnn.op.requantize(\n            y,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            out_dtype=\"int32\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        weight = relay.layout_transform(weight, \"HWIO\", \"IOHW\")\n        y = relay.qnn.op.conv2d_transpose(\n            x,\n            weight,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            out_dtype=\"int32\",\n        )\n        y = relay.qnn.op.requantize(\n            y,\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"int32\"),\n            axis=1,\n            out_dtype=\"int32\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"qnn.conv2d_transpose\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_convert_kernel_layout():\n    \"\"\"Check that convolution kernel layout is correctly transformed.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        w = relay.layout_transform(w, \"HWIO\", \"OHWI\")\n        y = relay.nn.conv2d(\n            x,\n            w,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"OHWI\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_roi_align_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_align(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, sample_ratio=2, layout=\"NCHW\"\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight1 = relay.layout_transform(weight1, \"OIHW\", \"HWIO\")\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_align(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, sample_ratio=2, layout=\"NHWC\"\n        )\n        ret = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    desired_layouts = {\n        \"nn.conv2d\": [\"NHWC\", \"HWIO\"],\n        \"vision.roi_align\": [\"NHWC\", \"default\"],\n    }\n    a = run_opt_pass(a, transform.ConvertLayout(desired_layouts))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_strided_slice_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.strided_slice(y, begin=[0, 1], end=[1, -1, 10], strides=[1, 1, 2, 1])\n        y = relay.Function([x, weight], y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight = relay.layout_transform(weight, \"OIHW\", \"HWIO\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.strided_slice(y, begin=[0, 0, 0, 1], end=[1, 10, 56, -1], strides=[1, 2, 1, 1])\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.Function(relay.analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_split_convert_layout():\n    def _test_conv_split_convert_layout1():\n        def before():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=2, axis=-1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=512, kernel_size=(3, 3))\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=2, axis=1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            a = relay.layout_transform(a, \"NCHW\", \"NHWC\")\n            b = relay.layout_transform(b, \"NCHW\", \"NHWC\")\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_split_convert_layout2():\n        def before():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=2, axis=3).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=512, kernel_size=(3, 3))\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=2, axis=1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            a = relay.layout_transform(a, \"NCHW\", \"NHWC\")\n            b = relay.layout_transform(b, \"NCHW\", \"NHWC\")\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_split_convert_layout3():\n        def before():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=(5, 10), axis=-1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            c = relay.TupleGetItem(y, 2)\n            out = relay.Tuple([a, b, c])\n            return relay.Function(analysis.free_vars(out), out)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=512, kernel_size=(3, 3))\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=(5, 10), axis=1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            c = relay.TupleGetItem(y, 2)\n            a = relay.layout_transform(a, \"NCHW\", \"NHWC\")\n            b = relay.layout_transform(b, \"NCHW\", \"NHWC\")\n            c = relay.layout_transform(c, \"NCHW\", \"NHWC\")\n            out = relay.Tuple([a, b, c])\n            return relay.Function(analysis.free_vars(out), out)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_split_convert_layout_blocking():\n        def before():\n            x = relay.var(\"x\", shape=(1, 512, 38, 38))\n            weight = relay.var(\"weight\", shape=(512, 512, 3, 3))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                data_layout=\"NCHW\",\n                kernel_layout=\"OIHW\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=[256], axis=1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 512, 38, 38))\n            weight = relay.var(\"weight\", shape=(512, 512, 3, 3))\n            weight = relay.layout_transform(weight, \"OIHW\", \"OIHW4o\")\n            x = relay.layout_transform(x, \"NCHW\", \"NCHW4c\")\n            y = relay.op.nn.contrib_conv2d_nchwc(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                padding=(0, 0),\n                data_layout=\"NCHW4c\",\n                kernel_layout=\"OIHW4o\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.op.split(y, indices_or_sections=[64], axis=1).astuple()\n            a = relay.TupleGetItem(y, 0)\n            b = relay.TupleGetItem(y, 1)\n            a = relay.layout_transform(a, \"NCHW4c\", \"NCHW\")\n            b = relay.layout_transform(b, \"NCHW4c\", \"NCHW\")\n            out = relay.Tuple([a, b])\n            return relay.Function(analysis.free_vars(out), out)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW4c\", \"OIHW4o\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    _test_conv_split_convert_layout1()\n    _test_conv_split_convert_layout2()\n    _test_conv_split_convert_layout3()\n    _test_conv_split_convert_layout_blocking()\n\n\ndef test_conv_strided_slice_axes_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 28, 28, 32))\n        weight = relay.var(\"weight\", shape=(3, 3, 32, 32))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.strided_slice(y, begin=[0, 16], end=[1, 33], strides=[1, 1], axes=[0, 3])\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 28, 28, 32))\n        weight = relay.var(\"weight\", shape=(3, 3, 32, 32))\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=32,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.strided_slice(y, begin=[0, 16], end=[1, 33], strides=[1, 1], axes=[0, 1])\n\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = run_opt_pass(before(), transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_topk_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.topk(y, k=2, axis=2)\n        if isinstance(y, relay.expr.TupleWrapper):\n            y = y.astuple()\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.topk(y, k=2, axis=3).astuple()\n        a = relay.TupleGetItem(y, 0)\n        b = relay.TupleGetItem(y, 1)\n        a = relay.layout_transform(a, \"NCHW\", \"NHWC\")\n        b = relay.layout_transform(b, \"NCHW\", \"NHWC\")\n        out = relay.Tuple([a, b])\n        return relay.Function(analysis.free_vars(out), out)\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_roi_pool_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_pool(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, layout=\"NCHW\"\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight1 = relay.layout_transform(weight1, \"OIHW\", \"HWIO\")\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_pool(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, layout=\"NHWC\"\n        )\n        ret = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.Function(analysis.free_vars(ret), ret)\n        return y\n\n    a = before()\n    desired_layouts = {\n        \"nn.conv2d\": [\"NHWC\", \"HWIO\"],\n        \"vision.roi_pool\": [\"NHWC\", \"default\"],\n    }\n    a = run_opt_pass(a, transform.ConvertLayout(desired_layouts))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_default_keyword():\n    \"\"\"Check that the default keyword selects correct TVM default layout.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 3, 3, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OHWI\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        w = relay.var(\"weight\", shape=(64, 3, 3, 64))\n        w = relay.layout_transform(w, \"OHWI\", \"OIHW\")\n        y = relay.nn.conv2d(\n            x,\n            w,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_different_ops_convert_layout():\n    \"\"\"Check convert layout correctly supports converting the layout of\n    different ops in the same graph.\n    \"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 3, 3, 64))\n        weight2 = relay.var(\"weight2\", shape=(64, 3, 3, 64), dtype=\"int8\")\n        weight3 = relay.var(\"weight3\", shape=(64, 3, 3, 64))\n        out = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OHWI\",\n        )\n        out = relay.cast(out, \"int8\")\n        out = relay.qnn.op.conv2d(\n            out,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OHWI\",\n        )\n        out = relay.cast(out, \"float32\")\n        out = relay.nn.conv2d_transpose(\n            out,\n            weight3,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OHWI\",\n        )\n        out = relay.Function(analysis.free_vars(out), out)\n        return out\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 3, 3, 64))\n        weight2 = relay.var(\"weight2\", shape=(64, 3, 3, 64), dtype=\"int8\")\n        weight3 = relay.var(\"weight3\", shape=(64, 3, 3, 64))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight1 = relay.layout_transform(weight1, \"OHWI\", \"HWIO\")\n        out = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        out = relay.cast(out, \"int8\")\n        out = relay.layout_transform(out, \"NHWC\", \"NCHW\")\n        weight2 = relay.layout_transform(weight2, \"OHWI\", \"OIHW\")\n        out = relay.qnn.op.conv2d(\n            out,\n            weight2,\n            relay.const(1, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        out = relay.cast(out, \"float32\")\n        out = relay.layout_transform(out, \"NCHW\", \"NHWC\")\n        weight3 = relay.layout_transform(weight3, \"OHWI\", \"HWIO\")\n        out = relay.nn.conv2d_transpose(\n            out,\n            weight3,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        out = relay.layout_transform(out, \"NHWC\", \"NCHW\")\n        out = relay.Function(analysis.free_vars(out), out)\n        return out\n\n    a = before()\n    desired_layouts = {\n        \"nn.conv2d\": [\"NHWC\", \"HWIO\"],\n        \"qnn.conv2d\": [\"NCHW\", \"OIHW\"],\n        \"nn.conv2d_transpose\": [\"NHWC\", \"HWIO\"],\n    }\n    a = run_opt_pass(a, transform.ConvertLayout(desired_layouts))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_no_desired_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_align(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, sample_ratio=2, layout=\"NCHW\"\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight1 = relay.var(\"weight1\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight1 = relay.layout_transform(weight1, \"OIHW\", \"HWIO\")\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        rois = relay.var(\"rois\", shape=(32, 5))\n        y = relay.vision.roi_align(\n            y, rois, pooled_size=(14, 14), spatial_scale=0.0625, sample_ratio=2, layout=\"NCHW\"\n        )\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"HWIO\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_convert_with_config():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64))\n        y2 = relay.nn.conv2d(\n            y,\n            weight2,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y2 = relay.nn.relu(y2)\n\n        out = relay.Function([x, weight, weight2], y2)\n        return out\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n\n        weight2 = relay.var(\"weight2\", shape=(3, 3, 64, 64))\n        weight2 = relay.layout_transform(weight2, \"HWIO\", \"HWOI\")\n\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NHWC\", \"HWNC\")\n\n        y2 = relay.nn.conv2d(\n            y,\n            weight2,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"HWNC\",\n            kernel_layout=\"HWOI\",\n        )\n        y2 = relay.nn.relu(y2)\n\n        y2 = relay.layout_transform(y2, \"HWNC\", \"NHWC\")\n        output = relay.Function(relay.analysis.free_vars(y2), y2)\n        return output\n\n    a = before()\n    layout_config = relay.transform.LayoutConfig(skip_layers=[0])\n    with layout_config:\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"HWNC\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_squeeze_convert_layout():\n    def _test_conv_squeeze_convert_layout1():\n        # specified axis is squeezed\n        def before():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=1000,\n                kernel_size=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y, axis=[-3])\n            return relay.Function(analysis.free_vars(y), y)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=1000, kernel_size=(1, 1))\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y, axis=[2])\n            y = relay.layout_transform(y, \"NCW\", \"NWC\")\n            return relay.Function(analysis.free_vars(y), y)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_squeeze_convert_layout2():\n        # all axes of dimension 1 are squeezed\n        def before():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=1000,\n                kernel_size=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y)\n            return relay.Function(analysis.free_vars(y), y)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=1000, kernel_size=(1, 1))\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y, [0, 2, 3])\n            return relay.Function(analysis.free_vars(y), y)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_squeeze_convert_layout3():\n        # squeeze axis is empty\n        def before():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=1000,\n                kernel_size=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y, axis=[])\n            return relay.Function(analysis.free_vars(y), y)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=1000, kernel_size=(1, 1))\n            y = relay.nn.relu(y)\n            y = relay.squeeze(y, axis=[])\n            y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n            return relay.Function(analysis.free_vars(y), y)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    _test_conv_squeeze_convert_layout1()\n    _test_conv_squeeze_convert_layout2()\n    _test_conv_squeeze_convert_layout3()\n\n\ndef test_conv_reduce_convert_layout():\n    def _test_conv_reduce_convert_layout1():\n        def before():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=1000,\n                kernel_size=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.sum(y, axis=(1, 2))\n            y = relay.sum(y, axis=(1,))\n            y = relay.sum(y)\n            y = relay.sum(y)\n            return relay.Function(analysis.free_vars(y), y)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 1, 1, 2048))\n            weight = relay.var(\"weight\", shape=(1, 1, 2048, 1000))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=1000, kernel_size=(1, 1))\n            y = relay.nn.relu(y)\n            y = relay.sum(y, axis=(2, 3))\n            y = relay.sum(y, axis=(1,))\n            y = relay.sum(y)\n            y = relay.sum(y)\n            return relay.Function(analysis.free_vars(y), y)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_conv_reduce_convert_layout2():\n        def _set_span(y, text):\n            return relay.Call(\n                y.op, y.args, y.attrs, y.type_args, relay.Span(relay.SourceName(text), 0, 0, 0, 0)\n            )\n\n        def before():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=512,\n                kernel_size=(3, 3),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = _set_span(y, \"SpanConv2D\")\n            y = relay.nn.relu(y)\n            y = _set_span(y, \"SpanRelu\")\n            y = relay.multiply(y, y)\n            y = _set_span(y, \"SpanMultiply\")\n            y = relay.sum(y, axis=(3,), keepdims=True)\n            y = _set_span(y, \"SpanSum\")\n            return relay.Function(analysis.free_vars(y), y)\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 38, 38, 512))\n            weight = relay.var(\"weight\", shape=(3, 3, 512, 512))\n            weight = relay.layout_transform(weight, \"HWIO\", \"OIHW\")\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.nn.conv2d(x, weight, channels=512, kernel_size=(3, 3))\n            y = relay.nn.relu(y)\n            y = relay.multiply(y, y)\n            y = relay.sum(y, axis=(1,), keepdims=True)\n            y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n            return relay.Function(analysis.free_vars(y), y)\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n        assert \"SpanConv2D\" in a.astext()\n        assert \"SpanRelu\" in a.astext()\n        assert \"SpanMultiply\" in a.astext()\n        assert \"SpanSum\" in a.astext()\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    _test_conv_reduce_convert_layout1()\n    _test_conv_reduce_convert_layout2()\n\n\ndef test_image_resize2d_convert_layout():\n    def _test_image_resize_convert_layout_nchw_to_nhwc():\n        def before():\n            x = relay.var(\"x\", shape=(1, 2, 4, 4))\n            y = relay.image.resize2d(x, (8, 8))\n            y = relay.Function([x], y)\n            return y\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 2, 4, 4))\n            x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n            y = relay.image.resize2d(x, (8, 8), layout=\"NHWC\")\n            y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n            y = relay.Function(relay.analysis.free_vars(y), y)\n            return y\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"image.resize2d\": [\"NHWC\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    def _test_image_resize_convert_layout_nhwc_to_nchw():\n        def before():\n            x = relay.var(\"x\", shape=(1, 4, 4, 2))\n            y = relay.image.resize2d(x, (8, 8), layout=\"NHWC\")\n            y = relay.Function([x], y)\n            return y\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 4, 4, 2))\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            y = relay.image.resize2d(x, (8, 8), layout=\"NCHW\")\n            y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n            y = relay.Function(relay.analysis.free_vars(y), y)\n            return y\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"image.resize2d\": [\"NCHW\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n    _test_image_resize_convert_layout_nchw_to_nhwc()\n    _test_image_resize_convert_layout_nhwc_to_nchw()\n\n\ndef test_conv_image_resize2d_convert_layout():\n    \"\"\"Check that layout transforms are propagated through image resize.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.image.resize2d(y, (112, 112), layout=\"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n        w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n        y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.image.resize2d(y, (112, 112), layout=\"NCHW\")\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_infer_correct_layout():\n    test_infer_correct_layout_flag = False\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64))\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    @reg.register_infer_correct_layout(\"nn.relu\", level=11)\n    def infer_correct_layout_relu(attrs, new_in_layouts, old_in_layouts, old_in_types):\n        nonlocal test_infer_correct_layout_flag\n        test_infer_correct_layout_flag = True\n        ret = tvm.tir.layout(\"\")\n        if new_in_layouts:\n            assert len(new_in_layouts) >= 1\n            ret = new_in_layouts[0]\n        else:\n            for i in range(len(old_in_layouts)):\n                if old_in_layouts[i]:\n                    ret = old_in_layouts[i]\n                    break\n        input_layouts = []\n        for i in range(len(old_in_layouts)):\n            input_layouts.append(ret)\n        return InferCorrectLayoutOutput(input_layouts, [ret], attrs)\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    assert test_infer_correct_layout_flag == True\n\n\ndef test_reduce_op_convert_layout():\n    for reduce_op in [relay.argmax, relay.mean, relay.max]:\n\n        def before():\n            x = relay.var(\"x\", shape=(1, 64, 56, 56))\n            weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=64,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"NCHW\",\n                kernel_layout=\"OIHW\",\n            )\n            y = reduce_op(y, axis=[2, 3])\n            y = relay.Function([x, weight], y)\n            return y\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 64, 56, 56))\n            weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n            x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n            weight = relay.layout_transform(weight, \"OIHW\", \"HWIO\")\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=64,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = reduce_op(y, axis=[1, 2])\n            y = relay.Function(relay.analysis.free_vars(y), y)\n            return y\n\n        a = before()\n        a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"default\"]}))\n        b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_conv_max_pool_uses_specified_convert_layout():\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NCHW\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        x = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        weight = relay.layout_transform(weight, \"OIHW\", \"OHWI\")\n        y = relay.nn.conv2d(\n            x,\n            weight,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(2, 2), layout=\"NHWC\", out_layout=\"NHWC\")\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.nn.batch_flatten(y)\n        y = relay.Function(analysis.free_vars(y), y)\n        return y\n\n    a = before()\n    a = run_opt_pass(\n        a, transform.ConvertLayout({\"nn.conv2d\": [\"NHWC\", \"OHWI\"], \"nn.max_pool2d\": [\"NHWC\"]})\n    )\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n\n@pytest.mark.parametrize(\n    \"data_layout, kernel_layout\",\n    [\n        (\"NCHW1c\", \"OIHW1i1o\"),\n        (\"NCHW4c\", \"OIHW4i4o\"),\n        (\"NCHW8c\", \"OIHW8i8o\"),\n        (\"NCHW16c\", \"OIHW16i16o\"),\n    ],\n)\ndef test_resnet_convert_layout_nchwc(data_layout, kernel_layout):\n    x = relay.var(\"x\", shape=(1, 3, 224, 224))\n    weight1 = relay.var(\"weight1\", shape=(64, 3, 7, 7))\n    weight2 = relay.var(\"weight2\", shape=(64, 64, 3, 3))\n    weight3 = relay.var(\"weight3\", shape=(64, 64, 1, 1))\n\n    def before():\n        y = relay.nn.conv2d(\n            x,\n            weight1,\n            strides=(2, 2),\n            padding=(3, 3),\n            channels=64,\n            kernel_size=(7, 7),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.nn.max_pool2d(y, pool_size=(3, 3), strides=(2, 2), padding=(1, 1))\n        y1 = relay.nn.conv2d(\n            y,\n            weight2,\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(\n            y,\n            weight3,\n            channels=64,\n            kernel_size=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y2 = relay.nn.relu(y2)\n        y = y1 + y2\n        y = relay.nn.global_max_pool2d(y, layout=\"NCHW\")\n        return y\n\n    def expected():\n        if data_layout == \"NCHW1c\":\n            y = relay.nn.contrib_conv2d_nchwc(\n                relay.layout_transform(x, \"NCHW\", data_layout),\n                relay.layout_transform(weight1, \"OIHW\", kernel_layout),\n                strides=(2, 2),\n                padding=(3, 3),\n                channels=64,\n                kernel_size=(7, 7),\n                data_layout=data_layout,\n                kernel_layout=kernel_layout,\n            )\n            y = relay.nn.relu(y)\n            y = relay.nn.max_pool2d(\n                y, pool_size=(3, 3), strides=(2, 2), padding=(1, 1), layout=data_layout\n            )\n        else:\n            y = relay.nn.conv2d(\n                x,\n                weight1,\n                strides=(2, 2),\n                padding=(3, 3),\n                channels=64,\n                kernel_size=(7, 7),\n                data_layout=\"NCHW\",\n                kernel_layout=\"OIHW\",\n            )\n            y = relay.nn.relu(y)\n            y = relay.nn.max_pool2d(y, pool_size=(3, 3), strides=(2, 2), padding=(1, 1))\n            y = relay.layout_transform(y, \"NCHW\", data_layout)\n        y1 = relay.nn.contrib_conv2d_nchwc(\n            y,\n            relay.layout_transform(weight2, \"OIHW\", kernel_layout),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.contrib_conv2d_nchwc(\n            y,\n            relay.layout_transform(weight3, \"OIHW\", kernel_layout),\n            channels=64,\n            kernel_size=(1, 1),\n            data_layout=data_layout,\n            kernel_layout=kernel_layout,\n        )\n        y2 = relay.nn.relu(y2)\n        y = y1 + y2\n        y = relay.nn.global_max_pool2d(y, layout=data_layout)\n        y = relay.layout_transform(y, data_layout, \"NCHW\")\n        return y\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [data_layout, kernel_layout]}))\n    b = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n Expect = \\n\" + str(b)\n\n\ndef test_conv_l2n_convert_layout():\n    \"\"\"Check that layout transforms are propagated through bn.\"\"\"\n    axis_list = ([3], [-1], [2, 3])\n    expected_axis = ([1], [1], [3, 1])\n    for i, axis in enumerate(axis_list):\n\n        def before():\n            x = relay.var(\"x\", shape=(1, 56, 56, 64))\n            weight = relay.var(\"weight\", shape=(3, 3, 64, 64))\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=64,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            z = relay.nn.l2_normalize(y, eps=0.001, axis=axis)\n            z = relay.Function(analysis.free_vars(z), z)\n            return z\n\n        def expected():\n            x = relay.var(\"x\", shape=(1, 56, 56, 64))\n            w = relay.var(\"weight\", shape=(3, 3, 64, 64))\n            x = relay.layout_transform(x, \"NHWC\", \"NCHW\")\n            w = relay.layout_transform(w, \"HWIO\", \"OIHW\")\n            y = relay.nn.conv2d(x, w, channels=64, kernel_size=(3, 3), padding=(1, 1))\n            z = relay.nn.l2_normalize(y, eps=0.001, axis=expected_axis[i])\n            z = relay.layout_transform(z, \"NCHW\", \"NHWC\")\n            z = relay.Function(analysis.free_vars(z), z)\n            return z\n\n    a = before()\n    a = run_opt_pass(a, transform.ConvertLayout({\"nn.conv2d\": [\"NCHW\", \"default\"]}))\n    b = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"\\n\\n Expected = \\n\" + str(b)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_dead_code_elimination.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm.relay import Function, transform\nfrom tvm.relay.testing import inception_v3\nimport pytest\n\ncpu_scope = tvm.target.VirtualDevice(tvm.cpu(), tvm.target.Target(\"llvm\"))\nmetatable = {\"VirtualDevice\": [cpu_scope]}\ncore = tvm.IRModule()\ncore.import_from_std(\"core.rly\")\n\n\ndef optimize_and_check(before_program, after_program, passes):\n    if isinstance(before_program, str):\n        before_program = tvm.parser.parse(before_program)\n    if isinstance(after_program, str):\n        after_program = tvm.parser.parse(after_program)\n    if not isinstance(passes, list):\n        passes = [passes]\n    optimize = tvm.transform.Sequential(passes)\n    optimized_program = optimize(before_program)\n    print(\"Actual:\")\n    print(optimized_program)\n    print(\"Expected:\")\n    print(after_program)\n    assert tvm.ir.structural_equal(optimized_program, after_program, map_free_vars=True)\n\n\ndef test_dead_let():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%z: int) {\n        let %x = 1;\n        %z\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%z: int) {\n        %z\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.DeadCodeElimination())\n\n\ndef test_one_live_let():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%z: int) {\n        let %x = 1;\n        let %y = 2;\n        %x + %x\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%z: int) {\n        let %x = 1;\n        %x + %x\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.DeadCodeElimination())\n\n\ndef test_nested_let():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%d: int, %b: int) {\n        let %a = %b;\n        let %c = %d;\n        %c\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%d: int, %b: int) {\n        let %c = %d;\n        %c\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.DeadCodeElimination())\n\n\ndef test_live_recursion():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %f = fn (%n: int, %data: int) -> int {\n            if (%n == 0) {\n                %data\n            } else {\n                %f(%n - 1, log(%data))\n            }\n        };\n        %f(2, 10000)\n    }\n    \"\"\"\n\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %f = fn (%n: int, %data: int) -> int {\n            if (%n == 0) {\n                %data\n            } else {\n                %f(%n - 1, log(%data))\n            }\n        };\n        %f(2, 10000)\n    }\n    \"\"\"\n\n    optimize_and_check(\n        before_program, after_program, [transform.DeadCodeElimination(), transform.InferType()]\n    )\n\n\ndef test_dead_recursion():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %f = fn (%n: int, %data: int) -> int {\n            if (%n == 0) {\n                %data\n            } else {\n                %f(%n - 1, log(%data))\n            }\n        };\n        ()\n    }\n    \"\"\"\n\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        ()\n    }\n    \"\"\"\n\n    optimize_and_check(\n        before_program, after_program, [transform.DeadCodeElimination(), transform.InferType()]\n    )\n\n\ndef test_add_with_let():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        (let %a = 1; 3) + 2\n    }\n    \"\"\"\n\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        3 + 2\n    }\n    \"\"\"\n\n    optimize_and_check(\n        before_program, after_program, [transform.DeadCodeElimination(), transform.InferType()]\n    )\n\n\ndef test_tuple_get_item():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %a = 100;\n        (1, 2, 3, 4).0\n    }\n    \"\"\"\n\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        (1, 2, 3, 4).0\n    }\n    \"\"\"\n\n    optimize_and_check(before_program, after_program, transform.DeadCodeElimination())\n\n\ndef test_inline_into_function():\n    \"\"\"Don't inline across function boundaries.\"\"\"\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %x = 1 + 1;\n        let %f = fn (%y: int) -> int {\n          let %z = %y + %y;\n          %x + %z\n        };\n        (%f(2), %f(3))\n    }\n    \"\"\"\n\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main() {\n        let %x = 1 + 1;\n        let %f = fn (%y: int) -> int {\n          %x + (%y + %y)\n        };\n        (%f(2), %f(3))\n    }\n    \"\"\"\n\n    optimize_and_check(\n        before_program, after_program, transform.DeadCodeElimination(inline_once=True)\n    )\n\n\ndef test_impure_op():\n    \"\"\"Don't elide calls to side-effecting operators.\"\"\"\n    before_program = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main() {\n           let %size: int64 = cast(1024, dtype=\"int64\");\n           let %alignment: int64 = cast(64, dtype=\"int64\");\n           let %x = memory.alloc_storage(%size, %alignment, virtual_device=meta[VirtualDevice][0]);\n           let %_ = memory.kill(%x);\n           0\n        }\n        \"\"\",\n        \"from_string\",\n        core,\n        metatable,\n    )\n\n    after_program = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main() {\n           %0 = memory.alloc_storage(cast(1024, dtype=\"int64\"),\n                                     cast(64, dtype=\"int64\"),\n                                     virtual_device=meta[VirtualDevice][0]);\n           let %_ = memory.kill(%0);\n           0\n        }\n        \"\"\",\n        \"from_string\",\n        core,\n        metatable,\n    )\n\n    optimize_and_check(\n        before_program, after_program, transform.DeadCodeElimination(inline_once=True)\n    )\n\n\ndef test_impure_func():\n    \"\"\"Don't elide calls to side-effecting functions.\"\"\"\n    before_program = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @f() -> int {\n           let %size: int64 = cast(1024, dtype=\"int64\");\n           let %alignment: int64 = cast(64, dtype=\"int64\");\n           let %x = memory.alloc_storage(%size, %alignment, virtual_device=meta[VirtualDevice][0]);\n           let %_ = memory.kill(%x);\n           0\n        }\n        def @main() -> int {\n           let %y = @f();\n           0\n        }\n        \"\"\",\n        \"from_string\",\n        core,\n        metatable,\n    )\n\n    after_program = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @f() -> int {\n           %0 = memory.alloc_storage(cast(1024, dtype=\"int64\"),\n                                     cast(64, dtype=\"int64\"),\n                                     virtual_device=meta[VirtualDevice][0]);\n           let %_ = memory.kill(%0);\n           0\n        }\n        def @main() -> int {\n            let %y = @f();\n            0\n        }\n        \"\"\",\n        \"from_string\",\n        core,\n        metatable,\n    )\n\n    optimize_and_check(\n        before_program, after_program, transform.DeadCodeElimination(inline_once=True)\n    )\n\n\ndef test_refs():\n    \"\"\"Don't elide expressions with reference create/read/write side effects\"\"\"\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @f(%r) -> int {\n        let %v = ref_read(%r);\n        let %u = ref_write(%r, %v + 1);\n        %v\n    }\n    def @main() -> int {\n        let %r = ref(0);\n        let %y = @f(%r);\n        let %z = @f(%r);\n        %z\n    }\n    \"\"\"\n\n    after_program = before_program\n\n    optimize_and_check(\n        before_program,\n        after_program,\n        [transform.InferType(), transform.DeadCodeElimination(inline_once=True)],\n    )\n\n\ndef test_complexity():\n    mod = transform.InferType()(\n        tvm.IRModule.from_expr(inception_v3.get_net(1, 1000, (3, 299, 299), \"float32\"))\n    )\n\n    optimize_and_check(mod, mod, transform.DeadCodeElimination(inline_once=True))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_defunctionalization.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.backend.interpreter import ConstructorValue\nfrom tvm.relay import transform, ExprVisitor, TypeVisitor\nfrom tvm.relay.testing import Prelude\n\n# determine if type t is a FuncType or has a nested FuncType\ndef has_func_type(t):\n    class FuncTypeVisitor(TypeVisitor):\n        def __init__(self):\n            super().__init__()\n            self.has_func = False\n\n        def visit_func_type(self, ftt):\n            self.has_func = True\n\n    ftvisitor = FuncTypeVisitor()\n    ftvisitor.visit(t)\n    return ftvisitor.has_func\n\n\n# determine whether a program has any higher order functions\n# a higher order function is defined as one that:\n# - has function type arguments\n# - returns a function\ndef assert_no_higher_order_functions(expr, mod):\n    class CheckFirstOrderVisitor(ExprVisitor):\n        def __init__(self, mod):\n            super().__init__()\n            self.mod = mod\n            self.hof = []\n            self.visited_gv = set()\n\n        def visit_call(self, call):\n            is_higher_order = False\n            # check return type\n            if has_func_type(call.checked_type):\n                is_higher_order = True\n            # check argument types\n            for a in call.args:\n                if has_func_type(a.checked_type):\n                    is_higher_order = True\n            # if it is higher order, save it for debugging later\n            if is_higher_order:\n                self.hof.append(call)\n            super().visit_call(call)\n\n        def visit_global_var(self, gv):\n            # visit global vars to visit entire program\n            if gv not in self.visited_gv:\n                self.visited_gv.add(gv)\n                self.visit(self.mod[gv])\n\n    mod = transform.InferType()(mod)\n    check_fo_visitor = CheckFirstOrderVisitor(mod)\n    check_fo_visitor.visit(expr)\n\n    nl = \"\\n--------\\n\"\n    errmsg = f\"\"\"found {len(check_fo_visitor.hof)} higher order functions:\n  {nl.join(expr.astext() for expr in check_fo_visitor.hof)}\"\"\"\n\n    assert len(check_fo_visitor.hof) == 0, errmsg\n\n\n# assert that a program is defunctionalized and returns\n# defunctionalized module\n# assumes program starts from mod['main']\ndef defunctionalized(mod):\n    mod = transform.InferType()(mod)\n    mod[\"main\"] = transform.Defunctionalization(mod[\"main\"], mod)\n    mod = transform.InferType()(mod)\n    assert_no_higher_order_functions(mod[\"main\"], mod)\n\n    return mod\n\n\n# adt list to python list\ndef to_list(mod, l):\n    list = mod.get_global_type_var(\"List\")\n    list_adt = mod[list]\n    cons = list_adt.constructors[0]\n    nil = list_adt.constructors[1]\n\n    assert isinstance(l, ConstructorValue)\n    val = l\n    ret = []\n    while True:\n        if val.tag == cons.tag:\n            ret.append(val.fields[0].numpy())\n            val = val.fields[1]\n        else:\n            assert val.tag == nil.tag\n            break\n    return ret\n\n\n# list to adt list\ndef to_adt_list(mod, arr):\n    expr = mod[\"main\"]\n    l = mod.get_global_type_var(\"List\")\n    list_adt = mod[l]\n    cons = list_adt.constructors[0]\n    nil = list_adt.constructors[1]\n\n    li = nil()\n    for a in arr:\n        li = cons(relay.const(a), li)\n    adt = relay.create_executor(mod=mod).evaluate(li)\n    mod[\"main\"] = expr\n    return adt\n\n\ndef test_simple():\n    code = \"\"\"\n#[version = \"0.0.5\"]\ndef @simple[A, B](%f: fn(A) -> B, %xs: A) -> B {\n  %f(%xs)\n}\ndef @main(%l: Tensor[(5, 5), float32]) -> Tensor[(5, 5), float32] {\n  %0 = fn[A](%x: A) -> A {\n    %x\n  };\n  @simple(%0, %l)\n}\n\"\"\"\n    mod = tvm.parser.fromtext(code)\n    defunc_mod = defunctionalized(mod)\n\n    input = np.random.rand(5, 5).astype(\"float32\")\n\n    out = relay.create_executor(\"debug\", mod=mod).evaluate()(input)\n\n    defunc_out = relay.create_executor(\"debug\", mod=defunc_mod).evaluate()(input)\n\n    np.testing.assert_equal(out.numpy(), defunc_out.numpy())\n\n\ndef test_global_recursion():\n    code = \"\"\"\n#[version = \"0.0.5\"]\ntype List[A] {\n  Cons(A, List[A]),\n  Nil,\n}\ndef @id[A](%x: A) -> A {\n  %x\n}\ndef @map[A, B](%f: fn(A) -> B, %xs: List[A]) -> List[B] {\n  match (%xs) {\n    Cons(%x, %rest) => Cons(%f(%x), @map(%f, %rest)),\n    Nil => Nil,\n  }\n}\ndef @main(%l: List[float32]) -> List[float32] {\n  @map(@id, %l)\n}\n\"\"\"\n    mod = tvm.parser.fromtext(code)\n    defunc_mod = defunctionalized(mod)\n\n    input = np.random.rand(10).astype(\"float32\")\n\n    out = relay.create_executor(\"debug\", mod=mod).evaluate(mod[\"main\"])(to_adt_list(mod, input))\n\n    defunc_out = relay.create_executor(\"debug\", mod=defunc_mod).evaluate()(\n        to_adt_list(defunc_mod, input)\n    )\n\n    np.testing.assert_array_equal(to_list(mod, out), to_list(defunc_mod, defunc_out))\n\n\ndef test_recursive_datatype():\n    # CPS will create recursive datatype\n    code = \"\"\"\n#[version = \"0.0.5\"]\ntype List[A] {\n  Cons(A, List[A]),\n  Nil,\n}\ndef @sum(%f: fn(int32) -> int32, %k: List[int32]) -> int32 {\n  match (%k) {\n    Cons(%x, %rest) => %0 = fn(%n) {\n      %x + %f(%n)\n    };\n    @sum(%0, %rest),\n    Nil => %f(0),\n  }\n}\ndef @id[A](%x: A) -> A {\n  %x\n}\ndef @main(%l: List[int32]) -> int32 {\n  @sum(@id, %l)\n}\n\"\"\"\n    mod = tvm.parser.fromtext(code)\n    defunc_mod = defunctionalized(mod)\n\n    input = np.random.randint(1, 100, 10)\n\n    out = relay.create_executor(\"debug\", mod=mod).evaluate(mod[\"main\"])(to_adt_list(mod, input))\n\n    defunc_out = relay.create_executor(\"debug\", mod=defunc_mod).evaluate()(\n        to_adt_list(defunc_mod, input)\n    )\n\n    tvm.testing.assert_allclose(out.numpy(), defunc_out.numpy())\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_defuse_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_opt_pass\n\n\ndef test_defuse_simple():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.exp(y)\n        w = relay.squeeze(z)\n        return relay.Function([x], w)\n\n    x = before()\n    x = run_opt_pass(x, transform.InferType())\n    fused = run_opt_pass(x, transform.FuseOps())\n    defused = run_opt_pass(fused, transform.DefuseOps())\n\n    assert tvm.ir.structural_equal(x, defused)\n\n\ndef test_inception_like():\n    def conv(data):\n        y = relay.nn.conv2d(data, relay.var(\"w\"), kernel_size=(3, 3), padding=(1, 1), channels=16)\n        return relay.nn.relu(data=y)\n\n    def inception_like(data):\n        c0 = conv(data)\n        c1 = conv(data)\n        return relay.concatenate((c0, c1), axis=1)\n\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        in1 = inception_like(x)\n        in2 = inception_like(in1)\n        return relay.Function(relay.analysis.free_vars(in2), in2)\n\n    dshape = (1, 16, 64, 64)\n    x = before(dshape)\n    x = run_opt_pass(x, transform.InferType())\n    fused = run_opt_pass(x, transform.FuseOps())\n    defused = run_opt_pass(fused, transform.DefuseOps())\n\n    assert tvm.ir.structural_equal(x, defused)\n\n\ndef test_defuse_complex():\n    \"\"\"Complex defuse testcase\"\"\"\n\n    def fused_conv2d_batch_norm(w):\n        data = relay.var(\"data\", shape=(1, 224, 224, 3))\n        bn_gamma0 = relay.var(\"bn_gamma0\", relay.TensorType((64,), \"float32\"))\n        bn_beta0 = relay.var(\"bn_beta0\", relay.TensorType((64,), \"float32\"))\n        bn_mmean0 = relay.var(\"bn_mean0\", relay.TensorType((64,), \"float32\"))\n        bn_mvar0 = relay.var(\"bn_var0\", relay.TensorType((64,), \"float32\"))\n        c0 = relay.nn.conv2d(\n            data,\n            w,\n            strides=(2, 2),\n            padding=(3, 3, 3, 3),\n            channels=64,\n            kernel_size=(7, 7),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n            out_layout=\"NHWC\",\n        )\n        c1 = relay.nn.batch_norm(c0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0, axis=3)\n        c2 = c1[0]\n        return relay.Function(relay.analysis.free_vars(c2), c2)\n\n    def fused_conv2d_batch_norm_relu(z):\n        data2 = relay.var(\"data2\", shape=(1, 56, 56, 64))\n        bn_gamma0 = relay.var(\"bn_gamma0\", relay.TensorType((64,), \"float32\"))\n        bn_beta0 = relay.var(\"bn_beta0\", relay.TensorType((64,), \"float32\"))\n        bn_mmean0 = relay.var(\"bn_mean0\", relay.TensorType((64,), \"float32\"))\n        bn_mvar0 = relay.var(\"bn_var0\", relay.TensorType((64,), \"float32\"))\n        c0 = relay.nn.conv2d(\n            data2,\n            z,\n            padding=(1, 1, 1, 1),\n            channels=64,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n            out_layout=\"NHWC\",\n        )\n        c1 = relay.nn.batch_norm(c0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0, axis=3)\n        c2 = c1[0]\n        c3 = relay.nn.relu(data=c2)\n        return relay.Function(relay.analysis.free_vars(c3), c3)\n\n    def fused_max_pool2d():\n        data1 = relay.var(\"data1\", shape=(1, 112, 112, 64))\n        a1 = relay.nn.max_pool2d(\n            data1,\n            pool_size=(3, 3),\n            strides=(2, 2),\n            padding=(1, 1, 1, 1),\n            layout=\"NHWC\",\n            out_layout=\"NHWC\",\n        )\n        return relay.Function(relay.analysis.free_vars(a1), a1)\n\n    def fused_add_relu():\n        data1 = relay.var(\"data1\", shape=(1, 56, 56, 64))\n        data2 = relay.var(\"data2\", shape=(1, 56, 56, 64))\n        a0 = relay.add(data1, data2)\n        a1 = relay.nn.relu(a0)\n        return relay.Function(relay.analysis.free_vars(a1), a1)\n\n    def before_fused(conv_layer1_weight, conv_layer2_weight):\n        data = relay.var(\"data\", shape=(1, 3, 224, 224))\n        data1 = relay.layout_transform(data, src_layout=\"NCHW\", dst_layout=\"NHWC\")\n        bn_gamma0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_beta0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_mmean0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_mvar0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        a0 = fused_conv2d_batch_norm(conv_layer1_weight)\n        a1 = fused_max_pool2d()\n        a2 = fused_conv2d_batch_norm_relu(conv_layer2_weight)\n        a3 = fused_add_relu()\n        y0 = relay.Call(a0, [data1, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0])\n        y1 = relay.Call(a1, [y0])\n        y2 = relay.Call(a2, [y1, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0])\n        y3 = relay.Call(a3, [y1, y2])\n        return relay.Function(relay.analysis.free_vars(y3), y3)\n\n    def golden_defused(conv_layer1_weight, conv_layer2_weight):\n        data = relay.var(\"data\", shape=(1, 3, 224, 224))\n        data1 = relay.layout_transform(data, src_layout=\"NCHW\", dst_layout=\"NHWC\")\n        bn_gamma0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_beta0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_mmean0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        bn_mvar0 = relay.const(tvm.nd.array(numpy.ndarray(shape=(64,), dtype=\"float32\")))\n        c0 = relay.nn.conv2d(\n            data1,\n            conv_layer1_weight,\n            strides=(2, 2),\n            padding=(3, 3, 3, 3),\n            channels=64,\n            kernel_size=(7, 7),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n            out_layout=\"NHWC\",\n        )\n        c1 = relay.nn.batch_norm(c0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0, axis=3)\n        c2 = c1[0]\n        c3 = relay.nn.max_pool2d(\n            c2,\n            pool_size=(3, 3),\n            strides=(2, 2),\n            padding=(1, 1, 1, 1),\n            layout=\"NHWC\",\n            out_layout=\"NHWC\",\n        )\n        c4 = relay.nn.conv2d(\n            c3,\n            conv_layer2_weight,\n            padding=(1, 1, 1, 1),\n            channels=64,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC\",\n            kernel_layout=\"OHWI\",\n            out_layout=\"NHWC\",\n        )\n        c5 = relay.nn.batch_norm(c4, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0, axis=3)\n        c6 = c5[0]\n        c7 = relay.nn.relu(c6)\n        c8 = relay.add(c3, c7)\n        c9 = relay.nn.relu(c8)\n        return relay.Function(relay.analysis.free_vars(c9), c9)\n\n    # creating weight constants for the two convolution layers\n    # in the input fused model and the golden defused model.\n    conv_layer1_weight = relay.nn.Constant(\n        tvm.nd.array(numpy.ndarray(shape=(64, 7, 7, 3), dtype=\"float32\"))\n    )\n    conv_layer2_weight = relay.nn.Constant(\n        tvm.nd.array(numpy.ndarray(shape=(64, 3, 3, 64), dtype=\"float32\"))\n    )\n    x = before_fused(conv_layer1_weight, conv_layer2_weight)\n    x = run_opt_pass(x, transform.InferType())\n    defused = run_opt_pass(x, transform.DefuseOps())\n\n    golden1 = golden_defused(conv_layer1_weight, conv_layer2_weight)\n    golden1 = run_opt_pass(golden1, transform.InferType())\n\n    assert tvm.ir.structural_equal(defused, golden1), (\n        \"Actual = \\n\" + str(defused) + \"\\nGolden = \\n\" + str(golden1)\n    )\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_dynamic_to_static.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.testing import run_infer_type, create_workload\nimport tvm.topi.testing\nimport tvm.testing\n\n\ndef run_opt_pass(expr, opt_pass, params=None):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n\n    mod = tvm.IRModule.from_expr(expr)\n    if params is not None:\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef verify_func(func, data, ref_res, rtol=1e-5, atol=1e-7):\n    assert isinstance(data, list)\n    for target, dev in tvm.testing.enabled_targets():\n        for kind in [\"graph\", \"vm\", \"debug\"]:\n            mod = tvm.ir.IRModule.from_expr(func)\n            op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                *data\n            )\n            tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=rtol, atol=atol)\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_reshape():\n    def verify_reshape(shape, newshape, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(newshape, \"float32\"))\n        z = relay.reshape(x, relay.shape_of(y))\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"reshape\")\n        assert \"newshape=\" in zz.astext()\n        assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=newshape).astype(\"float32\")\n        ref_res = np.reshape(x_data, oshape)\n        verify_func(func2, [x_data, y_data], ref_res)\n\n    verify_reshape((2, 3, 4), (8, 3), (8, 3))\n    verify_reshape((4, 7), (2, 7, 2), (2, 7, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_squeeze():\n    def verify_squeeze(shape, axis, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(axis, \"float32\"))\n        z = relay.squeeze(x, relay.shape_of(y))\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"squeeze\")\n        assert \"axis=\" in zz.astext()\n        assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=axis).astype(\"float32\")\n        ref_res = np.squeeze(x_data, axis)\n        verify_func(func2, [x_data, y_data], ref_res)\n\n    verify_squeeze((1, 3, 4, 1), (0,), (3, 4, 1))\n    verify_squeeze((1, 3, 4, 1), (3,), (1, 3, 4))\n    verify_squeeze((1, 3, 4, 1), (0, 3), (3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_double_reshape():\n    def verify_reshape(shape, newshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(newshape, \"float32\"))\n        z = relay.reshape(x, relay.shape_of(y))\n        z = relay.reshape(z, relay.shape_of(x))\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"reshape\")\n        assert \"newshape=\" in zz.astext()\n        assert zz.checked_type == relay.ty.TensorType(shape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=newshape).astype(\"float32\")\n        verify_func(func2, [x_data, y_data], x_data)\n\n    verify_reshape((2, 3, 4), (8, 3))\n    verify_reshape((4, 7), (2, 7, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_quad_reshape():\n    def verify_reshape(shape, newshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(newshape, \"float32\"))\n        z1 = relay.reshape(x, relay.shape_of(y))\n        z2 = relay.reshape(z1, relay.shape_of(x))\n        z3 = relay.reshape(z2, relay.shape_of(z1))\n        z4 = relay.reshape(z3, relay.shape_of(z2))\n        func = run_infer_type(relay.Function([x, y], z4))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"reshape\")\n        assert \"newshape=\" in zz.astext()\n        assert zz.checked_type == relay.ty.TensorType(shape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=newshape).astype(\"float32\")\n        verify_func(func2, [x_data, y_data], x_data)\n\n    verify_reshape((2, 3, 4), (8, 3))\n    verify_reshape((4, 7), (2, 7, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_tile():\n    def verify_tile(shape, reps, oshape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(reps, \"float32\"))\n        z = relay.tile(x, relay.shape_of(y))\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"tile\")\n        assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=reps).astype(\"float32\")\n        ref_res = np.tile(x_data, reps)\n        verify_func(func2, [x_data, y_data], ref_res)\n\n    verify_tile((2, 3, 4), (2, 1, 5), (4, 3, 20))\n    verify_tile((4, 7), (4, 2), (16, 14))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_topk():\n    def verify_topk(k, axis, ret_type, is_ascend, dtype):\n        shape = (20, 100)\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        k_var = relay.var(\"k\", relay.TensorType((), \"int32\"))\n        out = relay.topk(x, k_var, axis, ret_type, is_ascend, dtype)\n        if isinstance(out, relay.expr.TupleWrapper):\n            out = out.astuple()\n        func = relay.Function([x, k_var], out)\n        params = {\"k\": k}\n\n        np_data = np.random.uniform(size=shape).astype(\"float32\")\n        if is_ascend:\n            np_indices = np.argsort(np_data, axis=axis)\n        else:\n            np_indices = np.argsort(-np_data, axis=axis)\n        kk = k if k >= 1 else shape[axis]\n        if axis == 0:\n            np_indices = np_indices[:kk, :]\n            np_values = np.zeros(np_indices.shape).astype(\"float32\")\n            for i in range(shape[1]):\n                np_values[:, i] = np_data[np_indices[:, i], i]\n        else:\n            np_indices = np_indices[:, :kk]\n            np_values = np.zeros(np_indices.shape).astype(\"float32\")\n            for i in range(shape[0]):\n                np_values[i, :] = np_data[i, np_indices[i, :]]\n        np_indices = np_indices.astype(dtype)\n\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"topk\")\n\n        for target, dev in tvm.testing.enabled_targets():\n            if \"llvm\" not in target:\n                continue\n            for kind in [\"graph\", \"vm\", \"debug\"]:\n                mod = tvm.ir.IRModule.from_expr(func2)\n                op_res = relay.create_executor(kind, mod=mod, device=dev, target=target).evaluate()(\n                    np_data\n                )\n                if ret_type == \"both\":\n                    tvm.testing.assert_allclose(op_res[0].numpy(), np_values)\n                    tvm.testing.assert_allclose(op_res[1].numpy(), np_indices)\n                elif ret_type == \"values\":\n                    tvm.testing.assert_allclose(op_res.numpy(), np_values)\n                else:\n                    tvm.testing.assert_allclose(op_res.numpy(), np_indices)\n\n    np.random.seed(0)\n    for k in [0, 1, 5]:\n        for axis in [0, -1, 1]:\n            for ret_type in [\"both\", \"values\", \"indices\"]:\n                verify_topk(k, axis, ret_type, True, \"int64\")\n                verify_topk(k, axis, ret_type, False, \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_broadcast_to():\n    def verify_broadcast_to(shape, broadcast_shape):\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(broadcast_shape, \"float32\"))\n        z = relay.broadcast_to(x, shape=relay.shape_of(y))\n\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"broadcast_to\")\n        assert zz.checked_type == relay.ty.TensorType(broadcast_shape, \"float32\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        y_data = np.random.uniform(low=-1, high=1, size=broadcast_shape).astype(\"float32\")\n\n        ref_res = np.broadcast_to(x_data, y_data.shape)\n        verify_func(func2, [x_data, y_data], ref_res)\n\n    verify_broadcast_to((3, 1), (3, 3))\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_zeros_ones():\n    def verify_ones_zeros(shape, dtype):\n        for op, ref in [(relay.zeros, np.zeros), (relay.ones, np.ones)]:\n            x = relay.var(\"x\", relay.TensorType(shape, dtype))\n            y = op(relay.shape_of(x), dtype)\n\n            func = run_infer_type(relay.Function([x], y))\n            func2 = run_opt_pass(\n                run_opt_pass(func, transform.DynamicToStatic()),\n                transform.InferType(),\n            )\n\n            zz = func2.body\n            assert zz.checked_type == relay.ty.TensorType(shape, dtype)\n\n            x_data = np.random.uniform(low=1, high=1, size=shape)\n            ref_res = ref(x_data.shape)\n            verify_func(func2, [x_data], ref_res)\n\n    verify_ones_zeros((1, 2, 3), \"int64\")\n    verify_ones_zeros((9, 8, 3, 4), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_resize2d():\n    def verify_resize(shape, scale, method, layout):\n        if layout == \"NHWC\":\n            size = (shape[1] * scale, shape[2] * scale)\n        else:\n            size = (shape[2] * scale, shape[3] * scale)\n\n        x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n        size_var = relay.var(\"size\", relay.TensorType((len(size),), \"float32\"))\n        coord_trans = \"asymmetric\" if method == \"nearest_neighbor\" else \"align_corners\"\n        z = relay.image.resize2d(\n            x, size_var, None, layout, method, coordinate_transformation_mode=coord_trans\n        )\n        params = {\"size\": np.array(size).astype(\"float32\")}\n\n        func = run_infer_type(relay.Function([x, size_var], z))\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"image.resize2d\")\n\n        x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n        ref_res = tvm.topi.testing.resize2d_python(\n            x_data, (scale, scale), layout, method, coord_trans\n        )\n\n    for method in [\"linear\", \"nearest_neighbor\"]:\n        for layout in [\"NCHW\", \"NHWC\"]:\n            verify_resize((1, 4, 4, 4), 2, method, layout)\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_one_hot():\n    def _verify(indices_shape, depth, on_value, off_value, axis, dtype):\n        indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n        depth_var = relay.const(depth)\n        on_value_var = relay.var(\"on_value\", relay.TensorType((), \"int32\"))\n        off_value_var = relay.var(\"off_value\", relay.TensorType((), \"int32\"))\n        out = relay.one_hot(indices, on_value_var, off_value_var, depth_var, axis, dtype)\n        params = {\n            \"on_value\": on_value,\n            \"off_value\": off_value,\n        }\n\n        func = relay.Function([indices, on_value_var, off_value_var], out)\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"one_hot\")\n\n        indices_np = np.random.randint(0, depth, size=indices_shape).astype(\"int32\")\n        out_np = tvm.topi.testing.one_hot(indices_np, on_value, off_value, depth, axis, dtype)\n        verify_func(func2, [indices_np], out_np)\n\n    _verify((3,), 3, 1, 0, -1, \"int32\")\n    _verify((3,), 3, 1.0, 0.0, -1, \"float32\")\n    _verify((2, 2), 5, 2, -2, 0, \"int32\")\n    _verify((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    _verify((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n    _verify((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_full():\n    def verify_full(fill_value, fill_shape, dtype):\n        x = relay.var(\"x\", relay.scalar_type(dtype))\n        y = relay.var(\"y\", relay.TensorType(fill_shape, \"int64\"))\n        z = relay.full(x, relay.shape_of(y), dtype)\n\n        func = run_infer_type(relay.Function([x, y], z))\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"full\")\n\n        ref_res = np.full(fill_shape, fill_value).astype(dtype)\n        y_data = np.random.uniform(low=-1, high=1, size=fill_shape).astype(\"int64\")\n        verify_func(func2, [fill_value, y_data], ref_res)\n\n    verify_full(4, (1, 2, 3, 4), \"int32\")\n    verify_full(4.0, (1, 2, 8, 10), \"float32\")\n\n\ndef test_dynamic_to_static_upsampling():\n    def verify_upsampling(data_shape, scale_h_val, scale_w_val, dtype):\n        x = relay.var(\"x\", relay.TensorType(data_shape, dtype))\n        scale_h = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n        scale_w = relay.var(\"scale_w\", relay.TensorType((), \"float32\"))\n        z = relay.nn.upsampling(x, scale_h, scale_w)\n        params = {\n            \"scale_h\": scale_h_val,\n            \"scale_w\": scale_w_val,\n        }\n\n        func = run_infer_type(relay.Function([x, scale_h, scale_w], z))\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"nn.upsampling\")\n\n        x_data = np.random.uniform(size=data_shape).astype(dtype)\n        ref_res = tvm.topi.testing.resize2d_python(\n            x_data, (scale_h_val, scale_w_val), \"NCHW\", \"nearest_neighbor\", \"asymmetric\"\n        )\n        verify_func(func2, [x_data], ref_res)\n\n    verify_upsampling((1, 16, 32, 32), 2, 2, \"int8\")\n    verify_upsampling((1, 16, 32, 32), 4, 4, \"int32\")\n\n\ndef test_dynamic_to_static_upsampling3d():\n    def verify_upsampling3d(data_shape, scale_d_val, scale_h_val, scale_w_val, dtype):\n        x = relay.var(\"x\", relay.TensorType(data_shape, dtype))\n        scale_d = relay.var(\"scale_d\", relay.TensorType((), \"float32\"))\n        scale_h = relay.var(\"scale_h\", relay.TensorType((), \"float32\"))\n        scale_w = relay.var(\"scale_w\", relay.TensorType((), \"float32\"))\n\n        z = relay.nn.upsampling3d(x, scale_d, scale_h, scale_w)\n        params = {\n            \"scale_d\": scale_d_val,\n            \"scale_h\": scale_h_val,\n            \"scale_w\": scale_w_val,\n        }\n\n        func = run_infer_type(relay.Function([x, scale_d, scale_h, scale_w], z))\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"nn.upsampling3d\")\n\n        x_data = np.random.uniform(size=data_shape).astype(dtype)\n        ref_res = tvm.topi.testing.resize3d_python(\n            x_data,\n            (scale_d_val, scale_h_val, scale_w_val),\n            \"NCDHW\",\n            \"nearest_neighbor\",\n            \"asymmetric\",\n        )\n        verify_func(func2, [x_data], ref_res)\n\n    verify_upsampling3d((1, 1, 1, 1, 1), 2, 3, 4, \"int8\")\n    verify_upsampling3d((5, 7, 8, 10, 32), 3, 2, 2, \"int8\")\n    verify_upsampling3d((1, 4, 2, 5, 3), 5, 4, 3, \"int32\")\n\n\ndef test_dynamic_to_static_pad():\n    def verify_pad(data_shape, pad_width_val, pad_val, dtype):\n        x = relay.var(\"x\", relay.TensorType(data_shape, dtype))\n        pad_width = relay.var(\n            \"pad_width\", relay.TensorType((len(pad_width_val), len(pad_width_val[0])), \"int32\")\n        )\n        z = relay.nn.pad(x, pad_width, pad_val)\n        func = run_infer_type(relay.Function([x, pad_width], z))\n        params = {\"pad_width\": np.array(pad_width_val)}\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"nn.pad\")\n\n        x_data = np.random.uniform(size=data_shape).astype(dtype)\n        ref_res = np.pad(\n            x_data, pad_width_val, \"constant\", constant_values=(((pad_val,) * 2),) * len(data_shape)\n        )\n        verify_func(func2, [x_data], ref_res)\n\n    verify_pad((4, 10, 7, 7), ((1, 1), (2, 2), (3, 3), (4, 4)), 2.0, \"int32\")\n    verify_pad((2, 7), ((1, 4), (2, 2)), 4.0, \"float64\")\n\n\ndef test_dynamic_to_static_strided_slice():\n    def verify(\n        dshape,\n        begin_val,\n        end_val,\n        strides_val,\n        output,\n        slice_mode=\"end\",\n        test_ref=True,\n        dtype=\"int32\",\n    ):\n        x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n        ndim = len(dshape)\n        begin_val = begin_val if begin_val else [0] * ndim\n        end_val = end_val if end_val else list(dshape)\n        if strides_val:\n            if len(strides_val) == 1:\n                strides_val = strides_val * ndim\n        else:\n            strides_val = [1] * ndim\n\n        # target numpy result\n        x_data = np.random.uniform(size=dshape).astype(\"float32\")\n        ref_res = tvm.topi.testing.strided_slice_python(\n            x_data, begin_val, end_val, strides_val, slice_mode\n        )\n        data = [x_data, np.array(begin_val), np.array(end_val)]\n\n        begin = relay.var(\"begin\", relay.TensorType((len(begin_val),), dtype))\n        end = relay.var(\"end\", relay.TensorType((len(end_val),), dtype))\n\n        func_params = [x, begin, end]\n        if strides_val:\n            data.append(np.array(strides_val))\n            strides = relay.var(\"strides\", relay.TensorType((len(strides_val),), dtype))\n            z = relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=slice_mode)\n            func_params.append(strides)\n        else:\n            z = relay.strided_slice(x, begin=begin, end=end, slice_mode=slice_mode)\n        func = relay.Function(func_params, z)\n        params = {\"begin\": begin_val, \"end\": end_val, \"strides\": strides_val}\n\n        func = run_infer_type(func)\n        func2 = run_opt_pass(\n            run_opt_pass(func, transform.DynamicToStatic(), params), transform.InferType()\n        )\n        assert isinstance(func2.body, relay.Call)\n        assert func2.body.op == relay.op.get(\"strided_slice\")\n        verify_func(func2, [x_data], ref_res)\n\n    verify((1, 3, 10, 10), [0, 0, 0, 0], [1, 3, 10, 10], [1], (0, 3, 10, 10), dtype=\"int64\")\n    verify(\n        (1, 224, 224, 3),\n        [0, 20, 20, 0],\n        [1, 140, 140, 3],\n        [1, 1, 1, 1],\n        (1, 120, 120, 3),\n        dtype=\"int64\",\n    )\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], (1, 3, 3), dtype=\"int16\")\n    verify((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], (3, 1, 2))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 4], None, (2, 3, 3))\n    verify((3, 4, 3), [1, 1, 0], [4, 4, 3], None, (2, 3, 3))\n    verify((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], (1, 4, 3))\n    verify((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], (1, 2, 3))\n    verify(\n        (3, 4, 3), [1, 0, 0], [3, -1, 3], [1, 1, 1], (2, 4, 3), slice_mode=\"size\", test_ref=False\n    )\n    verify((3, 4, 3), [1, 0, 0], [-1, 2, 3], [1, 1, 1], (2, 2, 3), slice_mode=\"size\", test_ref=True)\n\n\n@tvm.testing.uses_gpu\ndef test_dyn_to_static_sparse_to_dense():\n    def verify_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape, xpected):\n        sparse_indices_data = np.array(sparse_indices)\n        sparse_values_data = np.array(sparse_values)\n        default_value_data = np.array(default_value)\n        output_shape_data = np.array(output_shape)\n\n        a = relay.var(\n            \"a\", relay.TensorType(sparse_indices_data.shape, str(sparse_indices_data.dtype))\n        )\n        b = relay.var(\n            \"b\", relay.TensorType(sparse_values_data.shape, str(sparse_values_data.dtype))\n        )\n        output_shape_const = relay.const(output_shape_data)\n\n        if default_value is None:\n            args = [a, b]\n            d = relay.sparse_to_dense(a, output_shape_const, b)\n        else:\n            c = relay.var(\n                \"c\", relay.TensorType(default_value_data.shape, str(default_value_data.dtype))\n            )\n            args = [a, b, c]\n            d = relay.sparse_to_dense(a, output_shape_const, b, c)\n\n        zz = run_infer_type(d)\n        assert len(zz.checked_type.shape) == len(output_shape)\n\n        func = relay.Function(args, d)\n\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n        assert isinstance(func2.body, relay.Call)\n        assert func2.body.op == relay.op.get(\"sparse_to_dense\")\n\n        if default_value is None:\n            arguments = [sparse_indices_data, sparse_values_data]\n        else:\n            arguments = [sparse_indices_data, sparse_values_data, default_value_data]\n\n        verify_func(func2, arguments, xpected)\n\n    verify_sparse_to_dense(1, 3, 0, [5], [0, 3, 0, 0, 0])  # scalar\n    verify_sparse_to_dense([0, 1, 4], [3, 3, 3], 0, [5], [3, 3, 0, 0, 3])  # vector\n    verify_sparse_to_dense(\n        [[0, 0], [1, 2]], [1, 2], 0, [3, 4], [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]\n    )  # nXd\n    verify_sparse_to_dense(\n        [[0, 0, 0], [1, 2, 3]],\n        [1, 2],\n        4,\n        [2, 3, 4],\n        [[[1, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]], [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 2]]],\n    )  # nXd\n    verify_sparse_to_dense(\n        [0, 1, 4], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1]\n    )  # floats\n    verify_sparse_to_dense(1, 3, None, [5], [0, 3, 0, 0, 0])  # default value not specified\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_dynamic_rank():\n    def verify_full(fill_value, fill_shape, dtype):\n        x = relay.var(\"x\", relay.scalar_type(dtype))\n        y = relay.var(\"y\", relay.TensorType(fill_shape, \"int64\"))\n        shape = relay.shape_of(y)\n        shape = relay.strided_slice(shape, [0], relay.shape_of(shape))\n        z = relay.full(x, shape, dtype)\n\n        func = relay.Function([x, y], z)\n        func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n        zz = func2.body\n        assert isinstance(zz, relay.Call)\n        assert zz.op == relay.op.get(\"full\")\n\n        ref_res = np.full(fill_shape, fill_value).astype(dtype)\n        y_data = np.random.uniform(low=-1, high=1, size=fill_shape).astype(\"int64\")\n        verify_func(func2, [fill_value, y_data], ref_res)\n\n    verify_full(4, (1, 2, 3, 4), \"int32\")\n    verify_full(4.0, (1, 2, 8, 10), \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_to_static_dynamic_if():\n    x = relay.var(\"x\", relay.TensorType((2, 2), \"int64\"))\n    cond = relay.const(1)\n    iff = relay.If(cond, relay.reshape(x, [1, 4]), relay.reshape(x, (4, 1)))\n\n    func = relay.Function([x], iff)\n    func2 = run_opt_pass(run_opt_pass(func, transform.DynamicToStatic()), transform.InferType())\n\n    zz = func2.body\n    assert isinstance(zz, relay.Call)\n    assert zz.op == relay.op.get(\"reshape\")\n    x_data = np.random.uniform(low=-1, high=1, size=(2, 2)).astype(\"int64\")\n    verify_func(func2, [x_data], x_data.reshape(1, 4))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_eliminate_common_subexpr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test eliminate common subexpr pass\"\"\"\nimport tvm\nfrom tvm import te\n\nfrom tvm import relay\nfrom tvm.relay.op import register_alter_op_layout\nfrom tvm.relay import transform, analysis\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_simple():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16))\n        y1 = relay.nn.relu(x)\n        y2 = relay.nn.relu(x)\n        y1 = relay.add(y1, relay.const(1.0, \"float32\"))\n        y2 = relay.add(y2, relay.const(1.0, \"float32\"))\n        y = relay.add(y1, y2)\n        f = relay.Function([x], y)\n        return f\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16))\n        y = relay.nn.relu(x)\n        y = relay.add(y, relay.const(1.0, \"float32\"))\n        y = relay.add(y, y)\n        f = relay.Function([x], y)\n        return run_opt_pass(f, transform.InferType())\n\n    z = before()\n    z = run_opt_pass(z, transform.EliminateCommonSubexpr())\n    assert tvm.ir.structural_equal(z, expected())\n\n\ndef test_callback():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16))\n        y1 = relay.nn.relu(x)\n        y2 = relay.nn.relu(x)\n        y1 = relay.add(y1, relay.const(1.0, \"float32\"))\n        y2 = relay.add(y2, relay.const(1.0, \"float32\"))\n        y = relay.add(y1, y2)\n        f = relay.Function([x], y)\n        return f\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16))\n        y = relay.nn.relu(x)\n        y1 = relay.add(y, relay.const(1.0, \"float32\"))\n        y2 = relay.add(y, relay.const(1.0, \"float32\"))\n        y = relay.add(y1, y2)\n        f = relay.Function([x], y)\n        return run_opt_pass(f, transform.InferType())\n\n    def fskip(expr):\n        if isinstance(expr, relay.expr.Call) and expr.op.name == \"add\":\n            return True\n        return False\n\n    z = before()\n    z = run_opt_pass(z, transform.EliminateCommonSubexpr(fskip))\n    assert tvm.ir.structural_equal(z, expected())\n\n\ndef test_tuple_get_time():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16, 1, 1))\n        var = relay.var(\"var\", shape=(16,))\n        mean = relay.var(\"mean\", shape=(16,))\n        beta = relay.var(\"beta\", shape=(16,))\n        gamma = relay.var(\"gamma\", shape=(16,))\n        BN = relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)\n        T1 = BN[0]\n        T2 = BN[0]\n        add = T1 + T2\n        f = relay.Function([x, var, mean, beta, gamma], add)\n        return f\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16, 1, 1))\n        var = relay.var(\"var\", shape=(16,))\n        mean = relay.var(\"mean\", shape=(16,))\n        beta = relay.var(\"beta\", shape=(16,))\n        gamma = relay.var(\"gamma\", shape=(16,))\n        BN = relay.op.nn.batch_norm(x, gamma, beta, mean, var, epsilon=1e-5)\n        T1 = BN[0]\n        add = T1 + T1\n        f = relay.Function([x, var, mean, beta, gamma], add)\n        return run_opt_pass(f, transform.InferType())\n\n    z = before()\n    z = run_opt_pass(z, transform.EliminateCommonSubexpr())\n    assert tvm.ir.structural_equal(z, expected())\n\n\nif __name__ == \"__main__\":\n    test_simple()\n    test_callback()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_eta_expand.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nimport tvm.relay.transform as _transform\n\n\ndef test_eta_expand_global_var():\n    mod = tvm.parser.fromtext(\n        r\"\"\"\n        #[version = \"0.0.5\"]\n        def @aux(%x: Tensor[(), int32]) -> Tensor[(), int32] {\n            %x\n        }\n        def @main() -> fn(Tensor[(), int32]) -> Tensor[(), int32] {\n            @aux\n        }\n    \"\"\"\n    )\n    seq = tvm.transform.Sequential([_transform.EtaExpand(expand_global_var=True)])\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    expected = tvm.parser.fromtext(\n        r\"\"\"\n        #[version = \"0.0.5\"]\n        def @aux(%x: Tensor[(), int32]) -> Tensor[(), int32] {\n            %x\n        }\n        def @main() -> fn(Tensor[(), int32]) -> Tensor[(), int32] {\n            fn (%x: Tensor[(), int32]) -> Tensor[(), int32] {\n                @aux(%x)\n            }\n        }\n    \"\"\"\n    )\n    tvm.ir.assert_structural_equal(mod[\"main\"], expected[\"main\"], map_free_vars=True)\n\n\ndef test_eta_expand_constructor():\n    mod = tvm.parser.fromtext(\n        r\"\"\"\n        #[version = \"0.0.5\"]\n        type List[A] {\n            Cons(A, List[A]),\n            Nil,\n        }\n        def @main[A]() -> fn(A, List[A]) -> List[A] {\n            Cons\n        }\n    \"\"\"\n    )\n    seq = tvm.transform.Sequential(\n        [_transform.EtaExpand(expand_constructor=True), _transform.InferType()]\n    )\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    expected = tvm.parser.fromtext(\n        r\"\"\"\n        #[version = \"0.0.5\"]\n        type List[A] {\n            Cons(A, List[A]),\n            Nil,\n        }\n        def @main[A]() -> fn(A, List[A]) -> List[A] {\n            fn [A](%x: A, %xs: List[A]) -> List[A] {\n                Cons(%x, %xs)\n            }\n        }\n    \"\"\"\n    )\n    tvm.ir.assert_structural_equal(mod[\"main\"], expected[\"main\"], map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    test_eta_expand_global_var()\n    test_eta_expand_constructor()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fake_quantization_to_integer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-wildcard-import\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.transform import fake_quantization_to_integer\n\n\ndef compare_fq_to_int(expr, args, allow_rounding_error=False):\n    mod = tvm.IRModule.from_expr(expr)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod_int = tvm.relay.transform.FakeQuantizationToInteger()(mod)\n    assert not tvm.ir.structural_equal(mod, mod_int)\n    result = (\n        relay.create_executor(\"vm\", mod=mod, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    result_int = (\n        relay.create_executor(\"vm\", mod=mod_int, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n\n    if allow_rounding_error:\n        assert np.all(np.abs(result.astype(\"int32\") - result_int.astype(\"int32\")) <= 1)\n    else:\n        assert np.array_equal(result, result_int)\n\n\ndef test_fake_quantize_conv():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n        one = relay.const(1.0)\n        zero = relay.const(0)\n\n        op = relay.op.nn.conv2d(\n            relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n            relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n            kernel_size=[5, 5],\n        )\n        op = relay.qnn.op.quantize(op, one, zero, out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np])\n\n\ndef test_fake_quantize_conv_per_channel():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n        one = relay.const([1.0] * 16)\n        zero_point = relay.const([np.random.randint(0, 255)] * 16)\n\n        op = relay.op.nn.conv2d(\n            relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(0)),\n            relay.qnn.op.dequantize(\n                w, relay.const(np.random.random([16]).astype(\"float32\")), zero_point, axis=0\n            ),\n            kernel_size=[5, 5],\n            channels=16,\n        )\n        op = relay.qnn.op.quantize(op, relay.const(1.0), relay.const(0), out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np], allow_rounding_error=True)\n\n\ndef test_fake_quantize_transposeconv():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[3, 16, 5, 5], dtype=\"int8\")\n        one = relay.const(1.0)\n        zero = relay.const(0)\n\n        op = relay.op.nn.conv2d_transpose(\n            relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n            relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n            kernel_size=[5, 5],\n            data_layout=\"NCHW\",\n            kernel_layout=\"IOHW\",\n        )\n        op = relay.qnn.op.quantize(op, one, zero, out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[3, 16, 5, 5], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np])\n\n\ndef test_fake_quantize_dense():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[128, 64], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[256, 64], dtype=\"int8\")\n        one = relay.const(1.0)\n        zero = relay.const(0)\n\n        op = relay.op.nn.dense(\n            relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n            relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n        )\n        op = relay.qnn.op.quantize(op, one, zero, out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[128, 64], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[256, 64], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np])\n\n\ndef test_fake_quantize_dense_per_channel():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[128, 64], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[256, 64], dtype=\"int8\")\n        one = relay.const(1.0)\n        zero = relay.const(0)\n\n        op = relay.op.nn.dense(\n            relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n            relay.qnn.op.dequantize(\n                w,\n                relay.const(np.random.random([256]).astype(\"float32\")),\n                relay.const([0] * 256),\n                axis=0,\n            ),\n            units=256,\n        )\n        op = relay.qnn.op.quantize(op, one, zero, out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[128, 64], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[256, 64], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np], allow_rounding_error=True)\n\n\ndef test_fake_quantize_batch_matmul():\n    for out_dtype in [\"int8\", \"uint8\"]:\n        x = relay.var(\"x\", shape=[1, 128, 64], dtype=\"int8\")\n        w = relay.var(\"w\", shape=[1, 256, 64], dtype=\"int8\")\n        one = relay.const(1.0)\n        zero = relay.const(0)\n\n        op = relay.op.nn.batch_matmul(\n            relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n            relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n        )\n        op = relay.qnn.op.quantize(op, one, zero, out_dtype=out_dtype)\n\n        x_np = np.random.randint(-128, 127, size=[1, 128, 64], dtype=\"int8\")\n        w_np = np.random.randint(-128, 127, size=[1, 256, 64], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, w_np])\n\n\ndef test_fake_transpose_quantize_conv():\n    x = relay.var(\"x\", shape=[1, 224, 224, 3], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    one = relay.const(1.0)\n    zero = relay.const(0)\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    x = relay.transpose(x, [0, 3, 1, 2])\n    op = relay.op.nn.conv2d(\n        x, relay.qnn.op.dequantize(w, relay.const(0.5), zero), kernel_size=[5, 5]\n    )\n    op = relay.qnn.op.quantize(op, one, zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 224, 224, 3], dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np, w_np])\n\n\n@pytest.mark.parametrize(\"const_bias\", [False, True])\ndef test_fake_transpose_quantize_conv_bias_add(const_bias):\n    x = relay.var(\"x\", shape=[1, 224, 224, 3], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    one = relay.const(1.0)\n    zero = relay.const(0)\n    if const_bias:\n        bias = relay.const(np.random.random(16).astype(\"float32\"))\n    else:\n        bias = relay.qnn.op.dequantize(relay.var(\"bias\", shape=[16], dtype=\"int32\"), one, zero)\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    x = relay.transpose(x, [0, 3, 1, 2])\n    op = relay.op.nn.conv2d(\n        x, relay.qnn.op.dequantize(w, relay.const(0.5), zero), kernel_size=[5, 5]\n    )\n    op = relay.op.nn.bias_add(op, bias)\n    op = relay.qnn.op.quantize(op, one, zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 224, 224, 3], dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n    bias_np = np.random.randint(-32768, 32767, size=[16], dtype=\"int32\")\n    args = [x_np, w_np]\n\n    if not const_bias:\n        args.append(bias_np)\n    compare_fq_to_int(op, args)\n\n\ndef test_fake_transpose_quantize_conv_bias_add_per_channel():\n    x = relay.var(\"x\", shape=[1, 224, 224, 3], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    bias = relay.var(\"bias\", shape=[16], dtype=\"int32\")\n    one = relay.const(1.0)\n    zero = relay.const(0)\n    w_scale = (np.random.random([16]).astype(\"float32\") - 0.5) / 10 + 0.5\n    noise = (np.random.random([16]).astype(\"float32\") - 0.5) * 1e-15\n    w_zp = relay.const([0] * 16)\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    x = relay.transpose(x, [0, 3, 1, 2])\n    op = relay.op.nn.conv2d(\n        x, relay.qnn.op.dequantize(w, relay.const(w_scale), w_zp, axis=0), kernel_size=[5, 5]\n    )\n    op = relay.op.nn.bias_add(\n        op, relay.qnn.op.dequantize(bias, relay.const(2.0 * w_scale + noise), w_zp, axis=0)\n    )\n    op = relay.qnn.op.quantize(op, one, zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 224, 224, 3], dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n    bias_np = np.random.randint(-32768, 32767, size=[16], dtype=\"int32\")\n\n    compare_fq_to_int(op, [x_np, w_np, bias_np], allow_rounding_error=True)\n\n\ndef test_fake_transpose_quantize_conv_bias_add_mismatch():\n    x = relay.var(\"x\", shape=[1, 224, 224, 3], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    bias = relay.var(\"bias\", shape=[16], dtype=\"int32\")\n    one = relay.const(1.0)\n    two = relay.const(2.0)\n    zero = relay.const(0)\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    x = relay.transpose(x, [0, 3, 1, 2])\n    op = relay.op.nn.conv2d(\n        x, relay.qnn.op.dequantize(w, relay.const(0.5), zero), kernel_size=[5, 5]\n    )\n    op = relay.op.nn.bias_add(op, relay.qnn.op.dequantize(bias, two, zero))\n    op = relay.qnn.op.quantize(op, one, zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 224, 224, 3], dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=[16, 3, 5, 5], dtype=\"int8\")\n    bias_np = np.random.randint(-32768, 32767, size=[16], dtype=\"int32\")\n\n    compare_fq_to_int(op, [x_np, w_np, bias_np])\n\n\ndef test_fake_quantize_maxpool():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.nn.max_pool2d(x, [3, 3])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\n@pytest.mark.parametrize(\"output_size\", [None, 1])\ndef test_fake_quantize_adaptive_avgpool1d(output_size):\n    x = relay.var(\"x\", shape=[1, 128, 768], dtype=\"int8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(-12))\n    op = relay.op.nn.adaptive_avg_pool1d(x, output_size)\n    op = relay.qnn.op.quantize(op, relay.const(0.5), relay.const(10))\n\n    x_np = np.random.randint(-128, 127, size=[1, 128, 768], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np], True)\n\n\ndef test_fake_quantize_avgpool():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(-12))\n    op = relay.op.nn.avg_pool2d(x, [3, 3])\n    op = relay.qnn.op.quantize(op, relay.const(0.5), relay.const(10))\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np], True)\n\n\ndef test_fake_quantize_global_avg_pool():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(-12))\n    op = relay.op.nn.global_avg_pool2d(x)\n    op = relay.qnn.op.quantize(op, relay.const(0.5), relay.const(10))\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np], True)\n\n\nclass TestUnaryQNNOp:\n    def helper_test_fake_quantize_unary_op(self, fp32_op, pos_values=False):\n        for dtype in [\"int8\", \"uint8\"]:\n            x = relay.var(\"x\", shape=[1, 3, 3, 3], dtype=dtype)\n\n            zero = -128 if dtype == \"int8\" else 0\n            if pos_values:\n                # Use a positive range for quanitzed ops that only work on positive values\n                input_mid_point = relay.const(zero)\n                output_mid_point = relay.const(zero)\n            else:\n                input_mid_point = relay.const(np.random.randint(0, 255) + zero)\n                output_mid_point = relay.const(np.random.randint(0, 255) + zero)\n\n            input_scale = relay.const(np.random.rand())\n            output_scale = relay.const(np.random.rand())\n\n            x = relay.qnn.op.dequantize(x, input_scale, input_mid_point)\n            op = fp32_op(x)\n\n            op = relay.qnn.op.quantize(op, output_scale, output_mid_point, out_dtype=dtype)\n\n            x_np = np.random.randint(0 + zero, 255 + zero, size=[1, 3, 3, 3], dtype=dtype)\n\n            compare_fq_to_int(op, [x_np], True)\n\n    def test_sqrt(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.sqrt, pos_values=True)\n\n    def test_rsqrt(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.rsqrt, pos_values=True)\n\n    def test_exp(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.exp)\n\n    def test_erf(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.erf)\n\n    def test_sigmoid(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.sigmoid)\n\n    def test_tanh(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.tanh)\n\n    def test_log(self):\n        self.helper_test_fake_quantize_unary_op(fp32_op=relay.log, pos_values=True)\n\n\ndef test_fake_quantize_reshape():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.reshape(x, [1, 3, -1])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_image_resize_bilinear():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.image.resize2d(x, size=[4, 4], method=\"linear\")\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np], allow_rounding_error=True)\n\n\ndef test_fake_quantize_abs():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.abs(x)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_expand_dims():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.expand_dims(x, axis=1)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_squeeze():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.squeeze(x, axis=[0])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_strided_slice():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.strided_slice(x, begin=[0, 0, 0, 0], end=[1, 1, 112, 112])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_split():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.split(x, axis=3, indices_or_sections=2)\n    op = relay.qnn.op.quantize(op[0], relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n    op = relay.op.split(x, axis=3, indices_or_sections=[56, 112, 168])\n    op = relay.qnn.op.quantize(op[1], relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_batch_flatten():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.nn.batch_flatten(x)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_transpose_reshape():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.transpose(x, [1, 0, 2, 3])\n    op = relay.op.reshape(op, [3, -1])\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_concat():\n    zero = relay.const(0)\n    inputs = []\n    for i in range(4):\n        inputs.append(\n            relay.qnn.op.dequantize(\n                relay.var(\"x%d\" % i, shape=[1, 4], dtype=\"int8\"), relay.const(i + 0.5), zero\n            )\n        )\n    concat = relay.op.concatenate(inputs, axis=1)\n    out = relay.qnn.op.quantize(concat, relay.const(3.5), zero)\n\n    inputs_np = []\n    for i in range(4):\n        inputs_np.append(np.random.randint(-128, 127, size=[1, 4], dtype=\"int8\"))\n\n    compare_fq_to_int(out, inputs_np)\n\n\n@pytest.mark.parametrize(\"k\", [0, 1, 5])\n@pytest.mark.parametrize(\"axis\", [0, -1, 1])\n@pytest.mark.parametrize(\"is_ascend\", [True, False])\n@pytest.mark.parametrize(\"dtype\", [\"int8\", \"uint8\"])\ndef test_fake_quantize_topk(k, axis, is_ascend, dtype):\n    x = relay.var(\"x\", shape=[20, 100], dtype=dtype)\n    zero = relay.const(0)\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.topk(x, k, axis, \"values\", is_ascend, \"float32\")\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero, out_dtype=dtype)\n    x_np = np.random.randint(0, 127, size=[20, 100], dtype=dtype)\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_clip():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(114))\n    op = relay.op.clip(x, 0, 6)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), relay.const(114), out_dtype=\"uint8\")\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_clip_per_channel():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(\n        x, relay.const([1.0, 2.0, 3.0]), relay.const([96, 114, 128]), axis=1\n    )\n    op = relay.op.clip(x, 0, 6)\n    op = relay.qnn.op.quantize(\n        op, relay.const([1.0, 2.0, 3.0]), relay.const([96, 114, 128]), out_dtype=\"uint8\", axis=1\n    )\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_relu():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(114))\n    op = relay.op.nn.relu(x)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), relay.const(114), out_dtype=\"uint8\")\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_mean():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(114))\n    op = relay.op.mean(x)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), relay.const(114), out_dtype=\"uint8\")\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np], allow_rounding_error=True)\n\n\ndef test_fake_quantize_relu_per_channel():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(\n        x, relay.const([1.0, 2.0, 3.0]), relay.const([96, 114, 128]), axis=1\n    )\n    op = relay.op.nn.relu(x)\n    op = relay.qnn.op.quantize(\n        op, relay.const([1.0, 2.0, 3.0]), relay.const([96, 114, 128]), out_dtype=\"uint8\", axis=1\n    )\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_leaky_relu():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"uint8\")\n\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(114))\n    op = relay.op.nn.leaky_relu(x, 0.1)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), relay.const(114), out_dtype=\"uint8\")\n\n    x_np = np.random.randint(0, 255, size=[1, 3, 224, 224], dtype=\"uint8\")\n\n    compare_fq_to_int(op, [x_np], True)\n\n\n@pytest.mark.parametrize(\n    \"operator\",\n    [relay.op.add, relay.op.multiply, relay.op.subtract, relay.op.minimum, relay.op.maximum],\n)\ndef test_fake_quantize_binary(operator):\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n    x = relay.qnn.op.dequantize(x, relay.const(0.1), relay.const(0))\n\n    y = relay.var(\"y\", shape=[1, 3, 224, 224], dtype=\"int8\")\n    y = relay.qnn.op.dequantize(y, relay.const(0.2), relay.const(0))\n\n    op = operator(x, y)\n    if operator == relay.op.multiply:\n        out_scale = relay.const(20.0)\n    else:\n        out_scale = relay.const(0.1)\n\n    op = relay.qnn.op.quantize(op, out_scale, relay.const(0), out_dtype=\"int8\")\n\n    x_np = np.random.randint(-25, 25, size=[1, 3, 224, 224], dtype=\"int8\")\n    y_np = np.random.randint(-25, 25, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np, y_np])\n\n\n@pytest.mark.parametrize(\n    \"operator\",\n    [relay.op.add, relay.op.multiply, relay.op.subtract, relay.op.minimum, relay.op.maximum],\n)\ndef test_fake_quantize_binary_per_channel(operator):\n    def verify_binary_per_channel(lhs_scale, rhs_scale, lhs_zp, rhs_zp, out_zp, lhs_axis, rhs_axis):\n        if operator == relay.op.multiply:\n            out_scale = relay.const(2.0)\n            rhs_axis = lhs_axis  # TODO: Support different axes for per-channel quantized multiply\n        else:\n            out_scale = relay.const(0.1)\n\n        x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n        x = relay.qnn.op.dequantize(x, relay.const(lhs_scale), relay.const(lhs_zp), axis=lhs_axis)\n\n        y = relay.var(\"y\", shape=[1, 3, 224, 224], dtype=\"int8\")\n        y = relay.qnn.op.dequantize(y, relay.const(rhs_scale), relay.const(rhs_zp), axis=rhs_axis)\n\n        op = operator(x, y)\n\n        op = relay.qnn.op.quantize(op, out_scale, relay.const(out_zp), out_dtype=\"int8\")\n        x_np = np.random.randint(-25, 25, size=[1, 3, 224, 224], dtype=\"int8\")\n        y_np = np.random.randint(-25, 25, size=[1, 3, 224, 224], dtype=\"int8\")\n\n        compare_fq_to_int(op, [x_np, y_np], allow_rounding_error=True)\n\n    # Same axis\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 3),\n        rhs_scale=np.random.uniform(1.0, 5.0, 3),\n        lhs_zp=0,\n        rhs_zp=0,\n        out_zp=0,\n        lhs_axis=1,\n        rhs_axis=1,\n    )\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 3),\n        rhs_scale=np.random.uniform(1.0, 5.0, 3),\n        lhs_zp=np.random.randint(1, 3),\n        rhs_zp=np.random.randint(1, 3),\n        out_zp=0,\n        lhs_axis=1,\n        rhs_axis=1,\n    )\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 3),\n        rhs_scale=np.random.uniform(1.0, 5.0, 3),\n        lhs_zp=np.random.randint(1, 3),\n        rhs_zp=np.random.randint(1, 3),\n        out_zp=np.random.randint(1, 3),\n        lhs_axis=1,\n        rhs_axis=1,\n    )\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 224),\n        rhs_scale=np.random.uniform(1.0, 5.0, 224),\n        lhs_zp=np.random.randint(1, 3),\n        rhs_zp=np.random.randint(1, 3),\n        out_zp=np.random.randint(1, 3),\n        lhs_axis=-1,\n        rhs_axis=-1,\n    )\n\n    # Different axes\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 224),\n        rhs_scale=np.random.uniform(1.0, 5.0, 224),\n        lhs_zp=0,\n        rhs_zp=0,\n        out_zp=0,\n        lhs_axis=2,\n        rhs_axis=3,\n    )\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 224),\n        rhs_scale=np.random.uniform(1.0, 5.0, 224),\n        lhs_zp=np.random.randint(1, 3),\n        rhs_zp=np.random.randint(1, 3),\n        out_zp=0,\n        lhs_axis=2,\n        rhs_axis=3,\n    )\n    verify_binary_per_channel(\n        lhs_scale=np.random.uniform(1.0, 5.0, 224),\n        rhs_scale=np.random.uniform(1.0, 5.0, 224),\n        lhs_zp=np.random.randint(1, 3),\n        rhs_zp=np.random.randint(1, 3),\n        out_zp=np.random.randint(1, 3),\n        lhs_axis=2,\n        rhs_axis=3,\n    )\n\n\n@pytest.mark.parametrize(\n    \"operator\",\n    [\n        relay.op.add,\n        relay.op.multiply,\n        relay.op.subtract,\n        relay.op.minimum,\n        relay.op.maximum,\n    ],\n)\ndef test_fake_quantize_binary_const(operator):\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n    x = relay.qnn.op.dequantize(x, relay.const(0.1), relay.const(10))\n\n    y = relay.const(1.0)\n\n    op = operator(x, y)\n    op = relay.qnn.op.quantize(op, relay.const(0.1), relay.const(10), out_dtype=\"int8\")\n\n    x_np = np.random.randint(-25, 25, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_subtract_different_output_zp():\n    for dtype in [\"uint8\"]:\n        x = relay.var(\"x\", shape=[1, 128, 128, 3], dtype=dtype)\n        x = relay.qnn.op.dequantize(x, relay.const(0.1), relay.const(0), axis=1)\n\n        y = relay.const(0.5)\n\n        op = relay.subtract(x, y)\n        op = relay.transpose(op, axes=[0, 3, 1, 2])\n        op = relay.qnn.op.quantize(op, relay.const(0.2), relay.const(128), out_dtype=dtype, axis=1)\n\n        x_np = np.random.randint(0, 255, size=[1, 128, 128, 3], dtype=dtype)\n\n        compare_fq_to_int(op, [x_np], True)\n\n\ndef test_fake_quantize_pad():\n    x = relay.var(\"x\", shape=[1, 383, 128], dtype=\"int8\")\n    x = relay.qnn.op.dequantize(x, relay.const(1.0), relay.const(10))\n    op = relay.op.nn.pad(x, [[0, 0], [0, 1], [0, 0]], 0.0)\n    op = relay.qnn.op.quantize(op, relay.const(1.0), relay.const(10), out_dtype=\"int8\")\n\n    x_np = np.random.randint(-25, 25, size=[1, 383, 128], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_depth_to_space():\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n\n    zero = relay.const(0)\n    x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n    op = relay.op.nn.depth_to_space(x, 4)\n    op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n    x_np = np.random.randint(-128, 127, size=[1, 3, 224, 224], dtype=\"int8\")\n\n    compare_fq_to_int(op, [x_np])\n\n\ndef test_fake_quantize_max_min():\n    def run_test_case(partial_func):\n        x = relay.var(\"x\", shape=[1, 3, 10, 10], dtype=\"int8\")\n\n        zero = relay.const(0)\n        x = relay.qnn.op.dequantize(x, relay.const(2.0), zero)\n        # To be a little more realistic since max/min will rarely be by themselves\n        x = relay.op.nn.depth_to_space(x, 4)\n        op = partial_func(x)\n        op = relay.qnn.op.quantize(op, relay.const(2.0), zero)\n\n        x_np = np.random.randint(-128, 127, size=[1, 3, 10, 10], dtype=\"int8\")\n        compare_fq_to_int(op, [x_np])\n\n    run_test_case(relay.op.max)\n    run_test_case(relay.op.min)\n\n    # Test forwarding kwargs works\n    run_test_case(lambda x: relay.op.max(x, axis=1))\n    run_test_case(lambda x: relay.op.min(x, axis=1))\n\n\ndef test_fq_avg_pool_conv2d():\n    dtype = \"uint8\"\n    shape_x = [1, 4, 24, 24]\n    shape_w = [8, 4, 1, 1]\n    x = relay.var(\"x\", shape=shape_x, dtype=dtype)\n    w = relay.var(\"w\", shape=shape_w, dtype=dtype)\n    zero = relay.const(0)\n    one = relay.const(1.0)\n\n    # Tested expression.\n    op0 = relay.qnn.op.dequantize(x, relay.const(0.64), relay.const(2))\n    op1 = relay.op.nn.avg_pool2d(op0, [3, 3])\n    op2 = relay.qnn.op.dequantize(w, relay.const(0.5), relay.const(10))\n    op3 = relay.op.nn.conv2d(op1, op2, kernel_size=[1, 1])\n    expr = relay.qnn.op.quantize(op3, one, zero, out_dtype=\"uint8\")\n\n    x_np = np.random.randint(0, 255, size=shape_x, dtype=dtype)\n    w_np = np.random.randint(0, 255, size=shape_w, dtype=dtype)\n    compare_fq_to_int(expr, [x_np, w_np])\n\n\ndef test_fq_hard_fail():\n    @tvm.ir.register_op_attr(\"nn.conv2d\", \"FTVMFakeQuantizationToInteger\", level=11)\n    def conv2d(expr, type_map):  # pylint: disable=unused-variable\n        raise NotImplementedError\n\n    x = relay.var(\"x\", shape=[1, 3, 224, 224], dtype=\"int8\")\n    w = relay.var(\"w\", shape=[16, 3, 5, 5], dtype=\"int8\")\n    one = relay.const(1.0)\n    zero = relay.const(0)\n\n    op = relay.op.nn.conv2d(\n        relay.qnn.op.dequantize(x, relay.const(2.0), zero),\n        relay.qnn.op.dequantize(w, relay.const(0.5), zero),\n        kernel_size=[5, 5],\n    )\n    op = relay.qnn.op.quantize(op, one, zero, out_dtype=\"int8\")\n    mod = tvm.IRModule.from_expr(op)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_int = tvm.relay.transform.FakeQuantizationToInteger(hard_fail=False)(mod)\n    assert tvm.ir.structural_equal(mod_int, mod)\n    # Catch a generic exception because the tvm FFI eats the python exception type\n    with pytest.raises(Exception):\n        mod_int = tvm.relay.transform.FakeQuantizationToInteger(hard_fail=True)(mod)\n\n\ndef compare_expected_fq_qat_to_int(expr, expected_expr, args, allow_rounding_error=False):\n    mod = tvm.IRModule.from_expr(expr)\n    mod_def = tvm.relay.transform.InferType()(mod)\n    mod_int = tvm.relay.transform.FakeQuantizationToInteger(False, True)(mod_def)\n    mod_exp = tvm.relay.transform.InferType()(tvm.IRModule.from_expr(expected_expr))\n    assert not tvm.ir.structural_equal(mod, mod_int)\n    assert tvm.ir.structural_equal(mod_int, mod_exp)\n    result_def = (\n        relay.create_executor(\"vm\", mod=mod_def, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    result_int = (\n        relay.create_executor(\"vm\", mod=mod_int, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    result_exp = (\n        relay.create_executor(\"vm\", mod=mod_exp, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    if allow_rounding_error:\n        assert np.all(np.abs(result_def.astype(\"int32\") - result_int.astype(\"int32\")) <= 1)\n    else:\n        assert np.array_equal(result_def, result_int)\n\n    assert np.array_equal(result_int, result_exp)\n\n\ndef test_fq_qat_op_positive_part():\n    # Only the first operation is converted, since the next operation(\"add\") is not enabled.\n    shape_x = [1, 4, 2]\n    shape_w = [1, 4, 2]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n    b = relay.var(\"b\", shape=shape_w, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n    op1 = relay.qnn.op.dequantize(b, relay.const(6.0), relay.const(0))\n    op2 = relay.op.nn.batch_matmul(op0, op1)\n    op3 = relay.op.add(op2, relay.const(1.0))\n    expr = relay.op.erf(op3)\n\n    op0 = relay.qnn.op.qnn.batch_matmul(\n        a, b, relay.const(0), relay.const(0), relay.const(2.0), relay.const(6.0)\n    )\n    op1 = relay.qnn.op.qnn.dequantize(op0, relay.const(12.0), relay.const(0))\n    op2 = relay.op.add(op1, relay.const(1.0))\n    expected_expr = relay.op.erf(op2)\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np, w_np])\n\n\ndef test_fq_qat_negative_all():\n    # None of the operations are converted, since the first operation(\"add\") is not enabled.\n    shape_x = [1, 4, 2]\n    shape_w = [1, 4, 2]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n    b = relay.var(\"b\", shape=shape_w, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n    op1 = relay.qnn.op.dequantize(b, relay.const(6.0), relay.const(0))\n    op2 = relay.op.add(op1, relay.const(1.0))\n    op3 = relay.op.nn.batch_matmul(op0, op2)\n    expr = relay.op.erf(op3)\n\n    expected_expr = expr\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np, w_np])\n\n\ndef test_fq_qat_positive_single():\n    # The single operation is converted.\n    shape_x = [1, 4, 2]\n    shape_w = [1, 4, 2]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n    b = relay.var(\"b\", shape=shape_w, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n    op1 = relay.qnn.op.dequantize(b, relay.const(6.0), relay.const(0))\n    expr = relay.op.nn.batch_matmul(op0, op1)\n\n    op0 = relay.qnn.op.qnn.batch_matmul(\n        a, b, relay.const(0), relay.const(0), relay.const(2.0), relay.const(6.0)\n    )\n    expected_expr = relay.qnn.op.qnn.dequantize(op0, relay.const(12.0), relay.const(0))\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np, w_np])\n\n\ndef test_fq_qat_positive_nothing_to_do():\n    # All operations are converted by the non-QAT pass.\n    shape_x = [1, 4, 2]\n    shape_w = [1, 4, 2]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n    b = relay.var(\"b\", shape=shape_w, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n    op1 = relay.qnn.op.dequantize(b, relay.const(6.0), relay.const(0))\n    op2 = relay.op.nn.batch_matmul(op0, op1)\n    op3 = relay.op.add(op2, relay.const(1.0))\n    expr = relay.qnn.op.quantize(op3, relay.const(1.0), relay.const(0), out_dtype=\"int8\")\n\n    op0 = relay.qnn.op.batch_matmul(\n        a, b, relay.const(0), relay.const(0), relay.const(2.0), relay.const(6.0)\n    )\n    op1 = relay.qnn.op.quantize(\n        relay.const(1.0), relay.const(12.0), relay.const(0), out_dtype=\"int32\"\n    )\n    op2 = relay.qnn.op.add(\n        op0,\n        op1,\n        relay.const(12.0),\n        relay.const(0),\n        relay.const(12.0),\n        relay.const(0),\n        relay.const(12.0),\n        relay.const(0),\n    )\n    expected_expr = relay.qnn.op.requantize(\n        op2, relay.const(12.0), relay.const(0), relay.const(1.0), relay.const(0), out_dtype=\"int8\"\n    )\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np, w_np])\n\n\ndef test_fq_qat_positive_couple():\n    # Several consecutive operations are converted.\n    shape_x = [1, 2, 4]\n    shape_w = [2]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n    b = relay.var(\"b\", shape=shape_w, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n    op1 = relay.qnn.op.dequantize(b, relay.const(6.0), relay.const(0))\n    op2 = relay.op.reshape(op0, (1, 4, 2))\n    op3 = relay.op.broadcast_to(op1, (2, 2, 2))\n    op4 = relay.op.nn.batch_matmul(op2, op3)\n    expr = relay.op.erf(op4)\n\n    op0 = relay.op.reshape(a, (1, 4, 2))\n    op1 = relay.op.broadcast_to(b, (2, 2, 2))\n    op3 = relay.qnn.op.qnn.batch_matmul(\n        op0, op1, relay.const(0), relay.const(0), relay.const(2.0), relay.const(6.0)\n    )\n    op4 = relay.qnn.op.qnn.dequantize(op3, relay.const(12.0), relay.const(0))\n    expected_expr = relay.op.erf(op4)\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np, w_np])\n\n\ndef test_fq_positive_single_arg_part():\n    # The single-argument operation is converted.\n    shape_x = [1, 2, 4]\n    a = relay.var(\"a\", shape=shape_x, dtype=\"int8\")\n\n    op0 = relay.qnn.op.dequantize(a, relay.const(2.0), relay.const(0))\n\n    op1 = relay.op.reshape(op0, (1, 4, 2))\n    expr = relay.op.erf(op1)\n\n    op0 = relay.op.reshape(a, (1, 4, 2))\n    op1 = relay.qnn.op.dequantize(op0, relay.const(2.0), relay.const(0))\n    expected_expr = relay.op.erf(op1)\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np])\n\n\ndef test_fq_qat_intermediate_infertype():\n    # Complex conversion of non-QAT and QAT passes that form FakeQuantizationToInteger.\n    shape_x = [1, 2, 4]\n    x = relay.var(\"x\", shape=shape_x, dtype=\"float32\")\n    const_0 = relay.const(np.random.uniform(size=[1, 4, 2]).astype(\"float32\"))\n\n    op0 = relay.qnn.op.quantize(x, relay.const(17.0), relay.const(0), out_dtype=\"int8\")\n    op1 = relay.qnn.op.dequantize(op0, relay.const(17.0), relay.const(0))\n    op2 = relay.op.reshape(op1, (1, 4, 2))\n    op3 = relay.qnn.op.quantize(op2, relay.const(10.0), relay.const(0), out_dtype=\"int8\")\n    op4 = relay.qnn.op.quantize(const_0, relay.const(1.0), relay.const(8), out_dtype=\"int8\")\n    op5 = relay.qnn.op.dequantize(op3, relay.const(10.0), relay.const(0))\n    op6 = relay.qnn.op.dequantize(op4, relay.const(4.0), relay.const(9))\n    op7 = relay.op.nn.batch_matmul(op5, op6)\n    expr = relay.op.add(op7, relay.const(5.0))\n\n    op0 = relay.qnn.op.quantize(x, relay.const(17.0), relay.const(0), out_dtype=\"int8\")\n    op1 = relay.op.reshape(op0, (1, 4, 2))\n    op2 = relay.qnn.op.requantize(\n        op1, relay.const(17.0), relay.const(0), relay.const(10.0), relay.const(0), out_dtype=\"int8\"\n    )\n    op3 = relay.qnn.op.quantize(const_0, relay.const(1.0), relay.const(8), out_dtype=\"int8\")\n    op4 = relay.qnn.op.batch_matmul(\n        op2, op3, relay.const(0), relay.const(9), relay.const(10.0), relay.const(4.0)\n    )\n    op5 = relay.qnn.op.dequantize(op4, relay.const(40.0), relay.const(0))\n    expected_expr = relay.op.add(op5, relay.const(5.0))\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int32\").astype(\"float32\")\n    compare_expected_fq_qat_to_int(expr, expected_expr, [x_np])\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fast_math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm import relay\nfrom tvm.relay.transform import FastMath\n\n\ndef test_exp():\n    x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n    y = relay.exp(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(func)\n\n    fast_mod = FastMath()(mod)\n    assert \"fast_exp\" in fast_mod.astext()\n\n    # Check that FastMath option works for relay.build.\n    with tvm.transform.PassContext(opt_level=3, required_pass=[\"FastMath\"]):\n        fast_mod = relay.optimize(mod, target=\"llvm\", params=None)\n    assert \"fast_exp\" in fast_mod[0].astext()\n\n\ndef test_tanh():\n    x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n    y = relay.tanh(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(func)\n\n    fast_mod = FastMath()(mod)\n    assert \"fast_tanh\" in fast_mod.astext()\n\n    # Check that FastMath option works for relay.build.\n    with tvm.transform.PassContext(opt_level=3, required_pass=[\"FastMath\"]):\n        fast_mod = relay.optimize(mod, target=\"llvm\", params=None)\n    assert \"fast_tanh\" in fast_mod[0].astext()\n\n\ndef test_erf():\n    x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n    y = relay.erf(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(func)\n\n    fast_mod = FastMath()(mod)\n    assert \"fast_erf\" in fast_mod.astext()\n\n    # Check that FastMath option works for relay.build.\n    with tvm.transform.PassContext(opt_level=3, required_pass=[\"FastMath\"]):\n        fast_mod = relay.optimize(mod, target=\"llvm\", params=None)\n    assert \"fast_erf\" in fast_mod[0].astext()\n\n\ndef test_softmax():\n    x = relay.var(\"x\", shape=(1, 16), dtype=\"float32\")\n    y = relay.nn.softmax(x)\n    func = relay.Function([x], y)\n    mod = tvm.IRModule.from_expr(func)\n\n    with tvm.transform.PassContext(opt_level=3, required_pass=[\"FastMath\"]):\n        fast_mod = relay.optimize(mod, target=\"llvm\")\n    assert \"nn.fast_softmax\" in fast_mod[0].astext()\n\n\nif __name__ == \"__main__\":\n    test_exp()\n    test_tanh()\n    test_erf()\n    test_softmax()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_flatten_atrous_conv.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-wildcard-import\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\n\ndef compare_expected_fac(expr, expected_expr, args):\n    mod_def = tvm.relay.transform.InferType()(tvm.IRModule.from_expr(expr))\n    mod_flat = tvm.relay.transform.FlattenAtrousConv()(mod_def)\n    mod_exp = tvm.relay.transform.InferType()(tvm.IRModule.from_expr(expected_expr))\n\n    assert expr is expected_expr or not tvm.ir.structural_equal(mod_def, mod_flat)\n    assert tvm.ir.structural_equal(mod_flat, mod_exp)\n\n    result_def = (\n        relay.create_executor(\"vm\", mod=mod_def, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    result_flat = (\n        relay.create_executor(\"vm\", mod=mod_flat, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n    result_exp = (\n        relay.create_executor(\"vm\", mod=mod_exp, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(*args)\n        .numpy()\n    )\n\n    assert np.array_equal(result_def, result_flat)\n    assert np.array_equal(result_flat, result_exp)\n\n\ndef test_fac_block_shape_2():\n    # pattern entry with block_shape=[2, 2]\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = relay.nn.conv2d(\n        data,\n        weight,\n        padding=[2, 2, 2, 2],\n        dilation=[2, 2],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_block_shape_4():\n    # pattern entry with block_shape=[4, 4]\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[4, 4], paddings=[[4, 7], [4, 7]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op2, block_shape=[4, 4], crops=[[0, 3], [0, 3]])\n\n    expected_expr = relay.nn.conv2d(\n        data,\n        weight,\n        padding=[4, 4, 4, 4],\n        dilation=[4, 4],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_quantize():\n    # quantize pattern entry\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"int8\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.qnn.op.conv2d(\n        op1,\n        weight,\n        input_zero_point=relay.const(0),\n        kernel_zero_point=relay.const(0),\n        input_scale=relay.const(2.0),\n        kernel_scale=relay.const(1.0),\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = relay.qnn.op.conv2d(\n        data,\n        weight,\n        input_zero_point=relay.const(0),\n        kernel_zero_point=relay.const(0),\n        input_scale=relay.const(2.0),\n        kernel_scale=relay.const(1.0),\n        padding=[2, 2, 2, 2],\n        dilation=[2, 2],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_surrounding():\n    # pattern entry with surrounding operations add\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op0 = relay.op.add(data, relay.const(1.0))\n    op1 = relay.nn.space_to_batch_nd(op0, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    op3 = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n    expr = relay.op.add(op3, relay.const(-1.0))\n\n    op0 = relay.op.add(data, relay.const(1.0))\n    op1 = relay.nn.conv2d(\n        op0,\n        weight,\n        padding=[2, 2, 2, 2],\n        dilation=[2, 2],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expected_expr = relay.op.add(op1, relay.const(-1.0))\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_several():\n    # several pattern entries\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    op3 = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n    op4 = relay.nn.space_to_batch_nd(op3, block_shape=[4, 4], paddings=[[4, 7], [4, 7]])\n    op5 = relay.nn.conv2d(\n        op4,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op5, block_shape=[4, 4], crops=[[0, 3], [0, 3]])\n\n    op1 = relay.nn.conv2d(\n        data,\n        weight,\n        padding=[2, 2, 2, 2],\n        dilation=[2, 2],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    expected_expr = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[4, 4, 4, 4],\n        dilation=[4, 4],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test__fac_only_s2b_conv():\n    # negative case, only operations space_to_batch_nd-conv2d\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    expr = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_only_s2b():\n    # negative case, only operation space_to_batch_nd\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    expr = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_only_conv_b2s():\n    # negative case, only operations conv2d-batch_to_space_nd\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.conv2d(\n        data,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op1, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_only_b2s():\n    # negative case, only operation batch_to_space_nd\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    expr = relay.nn.batch_to_space_nd(data, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_op_btwn_s2b_conv():\n    # negative case, add operation between space_to_batch_nd-conv2d\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op_1_5 = relay.op.add(op1, relay.const(1.0))\n    op2 = relay.nn.conv2d(\n        op_1_5,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_op_btwn_conv_b2s():\n    # negative case, add operation between conv2d-batch_to_space_nd\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    op_2_5 = relay.op.add(op2, relay.const(1.0))\n    expr = relay.nn.batch_to_space_nd(op_2_5, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    expected_expr = expr\n\n    compare_expected_fac(expr, expected_expr, [x_np])\n\n\ndef test_fac_relay_build():\n    #  Check the default optimize pipeline\n    shape_x = [1, 5, 5, 4]\n    shape_w = [3, 3, 4, 1]\n\n    x_np = np.random.randint(-128, 127, size=shape_x, dtype=\"int8\").astype(\"float32\")\n    w_np = np.random.randint(-128, 127, size=shape_w, dtype=\"int8\").astype(\"float32\")\n\n    weight = relay.const(w_np)\n    data = relay.var(\"data\", shape=shape_x, dtype=\"float32\")\n    op1 = relay.nn.space_to_batch_nd(data, block_shape=[2, 2], paddings=[[2, 3], [2, 3]])\n    op2 = relay.nn.conv2d(\n        op1,\n        weight,\n        padding=[0, 0, 0, 0],\n        groups=4,\n        channels=4,\n        kernel_size=[3, 3],\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWOI\",\n    )\n    expr = relay.nn.batch_to_space_nd(op2, block_shape=[2, 2], crops=[[0, 1], [0, 1]])\n\n    mod_def = tvm.relay.transform.InferType()(tvm.IRModule.from_expr(expr))\n    result_def = (\n        relay.create_executor(\"vm\", mod=mod_def, device=tvm.cpu(), target=\"llvm\")\n        .evaluate()(x_np)\n        .numpy()\n    )\n\n    graph, lib, params = relay.build(mod_def, \"llvm\", params=None)\n    rt_mod = graph_executor.create(graph, lib, device=tvm.cpu())\n    rt_mod.set_input(\"data\", x_np)\n    rt_mod.set_input(**params)\n    rt_mod.run()\n    result_flat = rt_mod.get_output(0).numpy()\n\n    assert \"space_to_batch_nd\" not in graph\n    assert \"conv2d\" in graph\n    assert \"batch_to_space_nd\" not in graph\n\n    assert np.array_equal(result_def, result_flat)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_flexible_shape_dispatch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test flexible shape dispatch pass\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing.resnet import get_workload\nfrom tvm.relay import vm\nfrom tvm import runtime\n\n\ndef test_end_to_end():\n    # Load a resnet model.\n    mod, params = get_workload()\n    # Apply flexible dispatch pass.\n    mod = relay.transform.FlexibleShapeDispatch(axis=0, buckets=[1, 4], auto_pad=True)(mod)\n    # Compile and confirm result supports multiple shapes.\n    exe = relay.vm.compile(mod, \"llvm\", params=params)\n    vm = runtime.vm.VirtualMachine(exe, tvm.cpu())\n\n    # Evaluate various batch sizes\n    batch_1 = np.random.normal(size=[1, 3, 224, 224]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", batch_1).shape) == [1, 1000]\n\n    batch_4 = np.random.normal(size=[4, 3, 224, 224]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", batch_4).shape) == [4, 1000]\n\n    # Apply autopadding to an input.\n    batch_3 = np.random.normal(size=[3, 3, 224, 224]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", batch_3).shape) == [3, 1000]\n\n\ndef test_multiple_inputs():\n    # Create a small relay module with multiple inputs to dispatch over.\n    x = relay.var(\"x\", shape=[10, 10], dtype=\"float32\")\n    w = relay.var(\"w\", shape=[10, 10], dtype=\"float32\")\n    y = x + w\n    mod = tvm.IRModule.from_expr(y)\n\n    # Apply flexible dispatch to dim 1 for both inputs.\n    mod = relay.transform.FlexibleShapeDispatch(axis=1, buckets=[5, 10], input_indices=[0, 1])(mod)\n\n    # Compile and confirm that output shapes are correct.\n    exe = relay.vm.compile(mod, \"llvm\")\n    vm = runtime.vm.VirtualMachine(exe, tvm.cpu())\n\n    x_w_5 = np.random.normal(size=[10, 5]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", x_w_5, x_w_5).shape) == [10, 5]\n\n    x_w_10 = np.random.normal(size=[10, 10]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", x_w_10, x_w_10).shape) == [10, 10]\n\n\ndef test_fixed_output():\n    # Test a graph where the output shape is not based on input dynamism.\n    x = relay.var(\"x\", shape=[10, 10], dtype=\"float32\")\n    w = relay.var(\"w\", shape=[10, 10], dtype=\"float32\")\n    y = relay.nn.dense(x, w)\n    mod = tvm.IRModule.from_expr(y)\n\n    # Apply flexible dispatch to dimension 1 for both inputs.\n    mod = relay.transform.FlexibleShapeDispatch(\n        axis=1, buckets=[5, 7], input_indices=[0, 1], affects_output=False\n    )(mod)\n\n    # Compile and confirm that output shapes are correct.\n    exe = relay.vm.compile(mod, \"llvm\")\n    vm = runtime.vm.VirtualMachine(exe, tvm.cpu())\n\n    x_w_5 = np.random.normal(size=[10, 5]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", x_w_5, x_w_5).shape) == [10, 10]\n\n    x_w_7 = np.random.normal(size=[10, 7]).astype(\"float32\")\n    assert list(vm.invoke(\"main\", x_w_7, x_w_7).shape) == [10, 10]\n\n    return\n\n\ndef test_multiple_outputs():\n    # Create a graph with multiple outputs and test that it works.\n    x = relay.var(\"x\", shape=[10, 10], dtype=\"float32\")\n    y = relay.split(x, 2, axis=1)\n    mod = tvm.IRModule.from_expr(y.astuple())\n\n    # Apply flexible dispatch to batch dimension.\n    mod = relay.transform.FlexibleShapeDispatch(axis=0, buckets=[5, 10])(mod)\n\n    # Compile and confirm that both outputs are correct.\n    exe = relay.vm.compile(mod, \"llvm\")\n    vm = runtime.vm.VirtualMachine(exe, tvm.cpu())\n\n    x_5 = np.random.normal(size=[5, 10]).astype(\"float32\")\n    result_5 = vm.invoke(\"main\", x_5)\n    assert list(result_5[0].shape) == [5, 5]\n    assert list(result_5[1].shape) == [5, 5]\n\n    x_10 = np.random.normal(size=[10, 10]).astype(\"float32\")\n    result_10 = vm.invoke(\"main\", x_10)\n    assert list(result_10[0].shape) == [10, 5]\n    assert list(result_10[1].shape) == [10, 5]\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fold_constant.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.backend import Executor\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.testing import run_infer_type, create_workload\n\n\ndef annot_expr(e):\n    \"\"\"Returns e wrapped with an on_device annotation.\"\"\"\n    return relay.op.annotation.on_device(e, tvm.cpu(), constrain_result=True)\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n\n    mod = tvm.IRModule.from_expr(expr)\n    mod = relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_concatenate_const():\n    def before():\n        data = tvm.nd.array(np.array([1.0, 2.0, 3.0]))\n        const = relay.const(data)\n        concat = relay.op.concatenate([const, const], axis=0)\n        func = relay.Function([], concat)\n        return func\n\n    def expected():\n        data = tvm.nd.array(np.array([1.0, 2.0, 3.0, 1.0, 2.0, 3.0]))\n        const = relay.const(data)\n        func = relay.Function([], const)\n        return func\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(zz, zexpected)\n\n\ndef test_fold_const():\n    c_data = np.array([1, 2, 3]).astype(\"float32\")\n    t = relay.TensorType([1, 2, 3], \"float32\")\n\n    def before():\n        c = relay.const(c_data)\n        x = relay.var(\"x\", t)\n        y = relay.add(c, c)\n        y = relay.multiply(y, relay.const(2, \"float32\"))\n        y = relay.add(x, y)\n        z = relay.add(y, c)\n        return relay.Function([x], z)\n\n    def expected():\n        x = relay.var(\"x\", t)\n        c_folded = (c_data + c_data) * 2\n        y = relay.add(x, relay.const(c_folded))\n        z = relay.add(y, relay.const(c_data))\n        return relay.Function([x], z)\n\n    # the fold constant should work on any context.\n    with tvm.target.Target(\"cuda\"):\n        zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_const_with_on_device():\n    \"\"\"Make sure on_device annotations don't get in the way of constant folding\"\"\"\n    c_data = np.array([1, 2, 3]).astype(\"float32\")\n    t = relay.TensorType([1, 2, 3], \"float32\")\n\n    def before():\n        c = relay.const(c_data)\n        x = relay.var(\"x\", t)\n        x.virtual_device_ = tvm.cpu()\n        y = relay.add(c, c)\n        y = relay.multiply(y, relay.const(2, \"float32\"))\n        y = relay.add(x, y)\n        z = relay.add(y, c)\n        f = relay.Function([x], z)\n        f.virtual_device_ = tvm.cpu()\n        return f\n\n    def expected():\n        x = relay.var(\"x\", t)\n        x.virtual_device_ = tvm.cpu()\n        c_folded = (c_data + c_data) * 2\n        y = relay.add(x, relay.const(c_folded))\n        z = relay.add(y, relay.const(c_data))\n        f = relay.Function([x], z)\n        f.virtual_device_ = tvm.cpu()\n        return f\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_let():\n    c_data = np.array(1).astype(\"float32\")\n    t = relay.TensorType([1], \"float32\")\n\n    def before():\n        sb = relay.ScopeBuilder()\n        x = relay.var(\"x\", t)\n        t1 = sb.let(\"t1\", relay.const(c_data))\n        t2 = sb.let(\"t2\", relay.add(t1, t1))\n        t3 = sb.let(\"t3\", relay.add(t2, x))\n        sb.ret(t3)\n        return relay.Function([x], sb.get())\n\n    def expected():\n        sb = relay.ScopeBuilder()\n        x = relay.var(\"x\", t)\n        c_folded = c_data + c_data\n        t3 = sb.let(\"t3\", relay.add(relay.const(c_folded), x))\n        sb.ret(t3)\n        return relay.Function([x], sb.get())\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_let_with_on_device():\n    \"\"\"Make sure on_device annotations don't get in the way of constant folding,\n    and inlined constants bring their annotations with them.\"\"\"\n    c_data = np.array(1).astype(\"float32\")\n    t = relay.TensorType([1], \"float32\")\n\n    def before():\n        sb = relay.ScopeBuilder()\n        x = relay.var(\"x\", t)\n        x.virtual_device_ = tvm.cpu()\n        t1 = sb.let(\"t1\", annot_expr(relay.const(c_data)))\n        t2 = sb.let(\"t2\", annot_expr(relay.add(t1, t1)))\n        t3 = sb.let(\"t3\", annot_expr(relay.add(t2, x)))\n        sb.ret(t3)\n        f = relay.Function([x], sb.get())\n        f.virtual_device_ = tvm.cpu()\n        return f\n\n    def expected():\n        sb = relay.ScopeBuilder()\n        x = relay.var(\"x\", t)\n        x.virtual_device_ = tvm.cpu()\n        c_folded = c_data + c_data\n        t3 = sb.let(\"t3\", annot_expr(relay.add(annot_expr(relay.const(c_folded)), x)))\n        sb.ret(t3)\n        f = relay.Function([x], sb.get())\n        f.virtual_device_ = tvm.cpu()\n        return f\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_tuple():\n    c_data = np.array(1).astype(\"float32\")\n    t = relay.TensorType([1], \"float32\")\n\n    def before():\n        c = relay.const(c_data)\n        x = relay.var(\"x\", t)\n        y = relay.Tuple([x, c])\n        z = relay.add(y[1], c)\n        z = relay.add(z, y[0])\n        return relay.Function([x], z)\n\n    def expected():\n        c = relay.const(c_data + c_data)\n        x = relay.var(\"x\", t)\n        z = relay.add(c, x)\n        return relay.Function([x], z)\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_concat():\n    c_data = np.array([[1, 2, 3]]).astype(\"float32\")\n\n    def before():\n        a = relay.const(c_data)\n        b = relay.const(c_data)\n        y = relay.concatenate((a, b), axis=0)\n        return relay.Function([], y)\n\n    def expected():\n        y_data = np.concatenate((c_data, c_data), axis=0)\n        y = relay.const(y_data)\n        return relay.Function([], y)\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_if():\n    cond_data = np.array(1).astype(\"bool\")\n    x_data = np.array([[1, 2, 3]]).astype(\"float32\")\n\n    def before():\n        a = relay.const(cond_data)\n        x = relay.const(x_data)\n        y = relay.const(x_data)\n        iff = relay.If(a, x + y, x - y)\n        return relay.Function([], iff)\n\n    def expected():\n        y_data = x_data + x_data\n        y = relay.const(y_data)\n        return relay.Function([], y)\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n    cond_data = np.array(0).astype(\"bool\")\n\n    def before():\n        a = relay.const(cond_data)\n        x = relay.const(x_data)\n        y = relay.const(x_data)\n        iff = relay.If(a, x + y, x - y)\n        return relay.Function([], iff)\n\n    def expected():\n        y_data = x_data - x_data\n        y = relay.const(y_data)\n        return relay.Function([], y)\n\n    zz = run_opt_pass(before(), transform.FoldConstant())\n    zexpected = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_shape_of():\n    c_shape = (8, 9, 10)\n\n    def before(dtype):\n        x = relay.var(\"x\", shape=c_shape, dtype=\"float32\")\n        y = relay.var(\"y\", shape=c_shape, dtype=\"float32\")\n        z = relay.shape_of(x + y, dtype)\n        return relay.Function([x, y], z)\n\n    def expected(dtype):\n        x = relay.var(\"x\", shape=c_shape, dtype=\"float32\")\n        y = relay.var(\"y\", shape=c_shape, dtype=\"float32\")\n        z = relay.const(np.array(c_shape).astype(dtype), dtype=dtype)\n        func = relay.Function([x, y], z)\n        return func\n\n    for dtype in [\"int32\", \"float32\"]:\n        zz = run_opt_pass(before(dtype), transform.FoldConstant())\n        zexpected = run_opt_pass(expected(dtype), transform.InferType())\n        tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_ndarray_size():\n    c_shape = (8, 9, 10)\n\n    def before(dtype):\n        x = relay.var(\"x\", shape=c_shape, dtype=\"float32\")\n        y = relay.var(\"y\", shape=c_shape, dtype=\"float32\")\n        z = relay.ndarray_size(x + y, dtype)\n        return relay.Function([x, y], z)\n\n    def expected(dtype):\n        x = relay.var(\"x\", shape=c_shape, dtype=\"float32\")\n        y = relay.var(\"y\", shape=c_shape, dtype=\"float32\")\n        z = relay.const(np.size(np.zeros(c_shape)), dtype=dtype)\n        func = relay.Function([x, y], z)\n        mod = tvm.IRModule.from_expr(func)\n        return mod[\"main\"]\n\n    for dtype in [\"int32\", \"float32\"]:\n        zz = run_opt_pass(before(dtype), transform.FoldConstant())\n        zexpected = run_opt_pass(expected(dtype), transform.InferType())\n        tvm.ir.assert_structural_equal(zz, zexpected)\n\n\ndef test_fold_batch_norm():\n    def expected():\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.const(np.zeros((16, 3, 3, 3)))\n        bias = relay.const(np.zeros((16, 1, 1)))\n        conv = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n        add = relay.add(conv, bias)\n        return relay.Function(relay.analysis.free_vars(add), add)\n\n    remove_bn_pass = tvm.transform.Sequential(\n        [\n            relay.transform.InferType(),\n            relay.transform.SimplifyInference(),\n            relay.transform.FoldConstant(),\n            relay.transform.FoldScaleAxis(),\n        ]\n    )\n\n    data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n    weight = relay.var(\"weight\")\n    bn_gamma = relay.var(\"bn_gamma\")\n    bn_beta = relay.var(\"bn_beta\")\n    bn_mmean = relay.var(\"bn_mean\")\n    bn_mvar = relay.var(\"bn_var\")\n\n    conv = relay.nn.conv2d(\n        data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n    )\n    bn_output = relay.nn.batch_norm(conv, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n\n    def initializer(_, param):\n        param = np.zeros(param.shape)\n\n    mod, params = create_workload(bn_output[0], initializer)\n    mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n    with tvm.transform.PassContext(opt_level=3):\n        mod = remove_bn_pass(mod)\n\n    expect = run_infer_type(expected())\n    tvm.ir.assert_structural_equal(mod[\"main\"], expect)\n\n\ndef test_fold_dropout():\n    def before():\n        # A constant graph to fire fold constant\n        data = relay.const(np.arange(10).astype(np.float32))\n        dropout = relay.nn.dropout(data)\n        add = dropout + relay.const(1.0)\n        return relay.Function(relay.analysis.free_vars(add), add)\n\n    passes = tvm.transform.Sequential(\n        [\n            relay.transform.InferType(),\n            relay.transform.FoldConstant(),\n        ]\n    )\n\n    before_mod = tvm.IRModule.from_expr(before())\n\n    with tvm.transform.PassContext(opt_level=3):\n        after_mod = passes(before_mod)\n\n    tvm.ir.assert_structural_equal(run_infer_type(before_mod[\"main\"]), after_mod[\"main\"])\n\n\ndef test_fold_qnn_const():\n    def before():\n        # QNN op with 2 constant arguments.\n        add = relay.qnn.op.add(\n            relay.const(np.ones((2, 3), dtype=\"uint8\"), dtype=\"uint8\"),\n            relay.const(np.ones((2, 3), dtype=\"uint8\"), dtype=\"uint8\"),\n            lhs_scale=relay.const(2.0),\n            lhs_zero_point=relay.const(0),\n            rhs_scale=relay.const(2.0),\n            rhs_zero_point=relay.const(0),\n            output_scale=relay.const(1.0),\n            output_zero_point=relay.const(0),\n        )\n        # QNN op with 1 constant and 1 non-constant arguments.\n        a = relay.var(\"a\", shape=[2, 3], dtype=\"float32\")\n        dense = relay.qnn.op.dense(\n            relay.qnn.op.quantize(a, relay.const(1.0), relay.const(0)),\n            add,\n            input_zero_point=relay.const(0),\n            kernel_zero_point=relay.const(0),\n            input_scale=relay.const(2.0),\n            kernel_scale=relay.const(2.0),\n            units=None,\n        )\n        # QNN op with 2 non-constant arguments.\n        b = relay.var(\"b\", shape=[2], dtype=\"float32\")\n        bias = relay.qnn.op.add(\n            dense,\n            relay.qnn.op.quantize(b, relay.const(1.0), relay.const(0), out_dtype=\"int32\"),\n            lhs_scale=relay.const(2.0),\n            lhs_zero_point=relay.const(0),\n            rhs_scale=relay.const(2.0),\n            rhs_zero_point=relay.const(0),\n            output_scale=relay.const(1.0),\n            output_zero_point=relay.const(0),\n        )\n        return relay.Function([a, b], bias)\n\n    def expected():\n        a = relay.var(\"a\", shape=[2, 3], dtype=\"float32\")\n        dense = relay.qnn.op.dense(\n            relay.qnn.op.quantize(a, relay.const(1.0), relay.const(0)),\n            relay.const(np.array([[4, 4, 4], [4, 4, 4]], dtype=\"uint8\"), dtype=\"uint8\"),\n            input_zero_point=relay.const(0),\n            kernel_zero_point=relay.const(0),\n            input_scale=relay.const(2.0),\n            kernel_scale=relay.const(2.0),\n            units=None,\n        )\n        b = relay.var(\"b\", shape=[2], dtype=\"float32\")\n        bias = relay.qnn.op.add(\n            dense,\n            relay.qnn.op.quantize(b, relay.const(1.0), relay.const(0), out_dtype=\"int32\"),\n            lhs_scale=relay.const(2.0),\n            lhs_zero_point=relay.const(0),\n            rhs_scale=relay.const(2.0),\n            rhs_zero_point=relay.const(0),\n            output_scale=relay.const(1.0),\n            output_zero_point=relay.const(0),\n        )\n        return relay.Function([a, b], bias)\n\n    # Nothing changed after applying FoldConstant\n    a = run_opt_pass(before(), transform.FoldConstant())\n    b = run_opt_pass(before(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n    # Fold QNN constants\n    a = run_opt_pass(before(), transform.FoldConstant(fold_qnn=True))\n    b = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n\ndef test_fold_quantize():\n    t = relay.TensorType([1, 2, 3], \"int8\")\n\n    def before():\n        data = tvm.nd.array(np.array([1.0, 2.0, 3.0], dtype=\"float32\"))\n        const_fp = relay.const(data, dtype=\"float32\")\n        const_i8 = relay.qnn.op.quantize(\n            const_fp, output_scale=relay.const(0.5), output_zero_point=relay.const(0)\n        )\n        x = relay.var(\"x\", t)\n        sub = relay.op.subtract(x, const_i8)\n        func = relay.Function([x], sub)\n        return func\n\n    def expected():\n        data = tvm.nd.array(np.array([2, 4, 6], dtype=\"int8\"))\n        const_i8 = relay.const(data, dtype=\"int8\")\n        x = relay.var(\"x\", t)\n        sub = relay.op.subtract(x, const_i8)\n        func = relay.Function([x], sub)\n        return func\n\n    # Nothing changed after applying FoldConstant\n    a = run_opt_pass(before(), transform.FoldConstant())\n    b = run_opt_pass(before(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n    # Fold QNN constants\n    a = run_opt_pass(before(), transform.FoldConstant(fold_qnn=True))\n    b = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n\ndef test_fold_qnn_conv2d_qnn_mul():\n    def before():\n        dtype = \"uint8\"\n        op0 = relay.qnn.op.conv2d(\n            relay.const(np.ones((1, 1, 2, 2), dtype=dtype), dtype=dtype),\n            relay.const(np.ones((1, 1, 2, 2), dtype=dtype), dtype=dtype),\n            input_zero_point=relay.const(0, \"int32\"),\n            kernel_zero_point=relay.const(0, \"int32\"),\n            input_scale=relay.const(1.0, \"float32\"),\n            kernel_scale=relay.const(1.0, \"float32\"),\n            kernel_size=(2, 2),\n            channels=1,\n        )\n        op = relay.qnn.op.mul(\n            op0,\n            relay.const(np.array([10], dtype=\"int32\"), dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n            relay.const(1.0, dtype=\"float32\"),\n            relay.const(0, dtype=\"int32\"),\n        )\n        func = relay.Function([], op)\n        return func\n\n    def expected():\n        data = relay.const(np.array([[[[40]]]], dtype=\"int32\"), dtype=\"int32\")\n        func = relay.Function([], data)\n        return func\n\n    # Nothing changed after applying FoldConstant\n    a = run_opt_pass(before(), transform.FoldConstant())\n    b = run_opt_pass(before(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n    # Fold QNN constants\n    a = run_opt_pass(before(), transform.FoldConstant(fold_qnn=True))\n    b = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n\ndef test_fold_requantize():\n    def before():\n        data = tvm.nd.array(np.array([1, 2, 3], dtype=\"int8\"))\n        const_i8 = relay.const(data, dtype=\"int8\")\n        op = relay.qnn.op.requantize(\n            const_i8,\n            input_scale=relay.const(2.0, dtype=\"float32\"),\n            input_zero_point=relay.const(1, dtype=\"int32\"),\n            output_scale=relay.const(1.0, dtype=\"float32\"),\n            output_zero_point=relay.const(1, dtype=\"int32\"),\n        )\n        x = relay.var(\"x\", relay.TensorType([3], \"int8\"))\n        add = relay.op.add(op, x)\n        func = relay.Function([x], add)\n        return func\n\n    def expected():\n        data = tvm.nd.array(np.array([1, 3, 5], dtype=\"int8\"))\n        const_i8 = relay.const(data, dtype=\"int8\")\n        x = relay.var(\"x\", relay.TensorType([3], \"int8\"))\n        add = relay.op.add(const_i8, x)\n        func = relay.Function([x], add)\n        return func\n\n    # Nothing changed after applying FoldConstant\n    a = run_opt_pass(before(), transform.FoldConstant())\n    b = run_opt_pass(before(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n    # Fold QNN constants\n    a = run_opt_pass(before(), transform.FoldConstant(fold_qnn=True))\n    b = run_opt_pass(expected(), transform.InferType())\n    tvm.ir.assert_structural_equal(a, b)\n\n\ndef test_pass_link_params():\n    \"\"\"\n    This test checks ensures that proper executor is passed to interpreter instance\n    The test will fail if FoldConstant does not override the executor due to \"int8\"\n    is not supported in ScheduleBuilder\n    \"\"\"\n\n    def expr():\n        z = relay.const(10, dtype=\"int8\")\n        return relay.cast(z, dtype=\"int32\")\n\n    mod = tvm.IRModule.from_expr(expr())\n    mod = tvm.relay.transform.InferType()(mod)\n    # Add executor with link-params\n    mod = mod.with_attr(\"executor\", Executor(\"aot\", {\"link-params\": True}))\n    mod = tvm.relay.transform.FoldConstant()(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fold_explicit_padding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_opt_pass\n\nimport numpy as np\n\n\ndef test_simplify_conv_pad():\n    convs = [relay.nn.conv1d, relay.nn.conv2d, relay.nn.conv3d]\n\n    def validate(ndim, pad_width, pad_value, pad_mode, orig_padding, layout, no_fold=False):\n        if layout[1] == \"C\":\n            shape = [1, 3] + [10] * ndim\n            wshape = [8, 3] + [3] * ndim\n        elif layout[-1] == \"C\":\n            shape = [1] + [10] * ndim + [3]\n            wshape = [8] + [3] * ndim + [3]\n        else:\n            raise ValueError(\"This test only supports NC* and N*C\")\n\n        x = relay.var(\"x\", shape=shape, dtype=\"float32\")\n        w = relay.var(\"w\", shape=wshape, dtype=\"float32\")\n        pad = relay.nn.pad(x, pad_width, pad_value, pad_mode)\n        if layout[1] == \"C\":\n            conv = convs[ndim - 1](pad, w, padding=orig_padding)\n        else:\n            conv = convs[ndim - 1](\n                pad, w, padding=orig_padding, data_layout=layout, kernel_layout=\"DHWIO\"[3 - ndim :]\n            )\n\n        if pad_mode == \"constant\" and pad_value == 0:\n            new_padding = []\n            for j in range(2):\n                for i in range(len(pad_width)):\n                    if layout[i] in [\"D\", \"H\", \"W\"]:\n                        new_padding.append(pad_width[i][j])\n            for i in range(len(new_padding)):\n                new_padding[i] += orig_padding[i]\n            if layout[1] == \"C\":\n                after = convs[ndim - 1](x, w, padding=new_padding)\n            else:\n                after = convs[ndim - 1](\n                    x, w, padding=new_padding, data_layout=layout, kernel_layout=\"DHWIO\"[3 - ndim :]\n                )\n        else:\n            after = conv\n\n        zz = run_opt_pass(conv, transform.FoldExplicitPadding())\n        expected = run_opt_pass(after, transform.InferType())\n        assert tvm.ir.structural_equal(zz, expected)\n\n        mod1 = tvm.IRModule.from_expr(conv)\n        mod2 = tvm.IRModule.from_expr(zz)\n\n        if not no_fold:\n            op_freqs = relay.analysis.list_op_freqs(mod2)\n            assert \"nn.pad\" not in op_freqs\n\n        with tvm.transform.PassContext():\n            func1 = relay.create_executor(\n                \"vm\", mod=mod1, device=tvm.cpu(), target=\"llvm\"\n            ).evaluate()\n        func2 = relay.create_executor(\"vm\", mod=mod2, device=tvm.cpu(), target=\"llvm\").evaluate()\n        x_np = np.random.rand(*shape).astype(\"float32\")\n        w_np = np.random.rand(*wshape).astype(\"float32\")\n\n        result1 = func1(x_np, w_np)\n        result2 = func2(x_np, w_np)\n\n        tvm.testing.assert_allclose(result1.numpy(), result2.numpy(), rtol=1e-5, atol=1e-5)\n\n    # Test fold cases\n    for orig_pad in [[0, 0], [2, 0], [0, 2]]:\n        for i_pad in [[0, 0], [1, 1], [1, 0]]:\n            for ndim in [1, 2, 3]:\n                for channels_last in [0, 1]:\n                    if channels_last:\n                        layout = \"NDHWC\"\n                        layout = layout[0:1] + layout[4 - ndim : 4] + layout[-1:]\n                        padding = [[0, 0]] + [i_pad] * ndim + [[0, 0]]\n                    else:\n                        layout = \"NCDHW\"\n                        layout = layout[0:2] + layout[5 - ndim :]\n                        padding = [[0, 0]] * 2 + [i_pad] * ndim\n\n                    validate(ndim, padding, 0, \"constant\", orig_pad * ndim, layout)\n\n    # Test no fold cases\n    ndim = 2\n    # Conv only folds when pad_value=0\n    validate(\n        ndim, [[0, 0]] * 2 + [i_pad] * ndim, 1, \"constant\", orig_pad * ndim, \"NCHW\", no_fold=True\n    )\n    # Conv only folds when pad's pad_mode=\"constant\"\n    validate(ndim, [[0, 0]] * 2 + [i_pad] * ndim, 0, \"edge\", orig_pad * ndim, \"NCHW\", no_fold=True)\n\n\ndef get_min_value(dtype):\n    if np.issubdtype(dtype, np.floating):\n        return np.finfo(dtype).min\n    elif np.issubdtype(dtype, np.integer):\n        return np.iinfo(dtype).min\n    else:\n        raise ValueError(\"Cannot get min value for dtypes that are not integer or not floating\")\n\n\ndef test_simplify_pool_pad():\n    max_pools = [relay.nn.max_pool1d, relay.nn.max_pool2d, relay.nn.max_pool3d]\n    avg_pools = [relay.nn.avg_pool1d, relay.nn.avg_pool2d, relay.nn.avg_pool3d]\n\n    def validate(\n        pools,\n        ndim,\n        pad_width,\n        pad_value,\n        orig_padding,\n        layout,\n        pool_size,\n        pad_mode=\"constant\",\n        dtype=\"float32\",\n        no_fold=False,\n        **kwargs,\n    ):\n        pad_value_const = relay.const(pad_value, dtype=dtype)\n\n        if layout[1] == \"C\":\n            shape = [1, 3] + [10] * ndim\n        elif layout[-1] == \"C\":\n            shape = [1] + [10] * ndim + [3]\n        else:\n            raise ValueError(\"This test only supports NC* and N*C\")\n\n        x = relay.var(\"x\", shape=shape, dtype=dtype)\n        pad = relay.nn.pad(x, pad_width, pad_value_const, pad_mode)\n        if layout[1] == \"C\":\n            pool = pools[ndim - 1](pad, padding=orig_padding, pool_size=pool_size, **kwargs)\n        else:\n            pool = pools[ndim - 1](\n                pad, padding=orig_padding, layout=layout, pool_size=pool_size, **kwargs\n            )\n\n        if pools == max_pools:\n            foldable_pad_value = get_min_value(dtype)\n        else:\n            foldable_pad_value = 0\n\n        if pad_mode == \"constant\" and pad_value == foldable_pad_value:\n            new_padding = []\n            for j in range(2):\n                for i in range(len(pad_width)):\n                    if layout[i] in [\"D\", \"H\", \"W\"]:\n                        new_padding.append(pad_width[i][j])\n            for i in range(len(new_padding)):\n                new_padding[i] += orig_padding[i]\n\n            if pools == avg_pools and all(v == 0 for v in orig_padding):\n                # If the orig padding for AvgPool is all zero and the pad op to fold\n                # has non-zero pad width, the resultant folded AvgPool will have\n                # count_include_pad=True so AvgPool's divisor is agnostic of pad boundaries\n                kwargs[\"count_include_pad\"] = True\n            if layout[1] == \"C\":\n                after = pools[ndim - 1](x, padding=new_padding, pool_size=pool_size, **kwargs)\n            else:\n                after = pools[ndim - 1](\n                    x, padding=new_padding, layout=layout, pool_size=pool_size, **kwargs\n                )\n        else:\n            after = pool\n\n        zz = run_opt_pass(pool, transform.FoldExplicitPadding())\n        expected = run_opt_pass(after, transform.InferType())\n\n        assert tvm.ir.structural_equal(zz, expected)\n\n        mod1 = tvm.IRModule.from_expr(pool)\n        mod2 = tvm.IRModule.from_expr(zz)\n\n        if not no_fold:\n            op_freqs = relay.analysis.list_op_freqs(mod2)\n            assert \"nn.pad\" not in op_freqs\n\n        with tvm.transform.PassContext():\n            func1 = relay.create_executor(\n                \"vm\", mod=mod1, device=tvm.cpu(), target=\"llvm\"\n            ).evaluate()\n\n        func2 = relay.create_executor(\"vm\", mod=mod2, device=tvm.cpu(), target=\"llvm\").evaluate()\n        x_np = np.random.rand(*shape).astype(dtype)\n\n        result1 = func1(x_np)\n        result2 = func2(x_np)\n\n        tvm.testing.assert_allclose(result1.numpy(), result2.numpy(), rtol=1e-5, atol=1e-5)\n\n    # Test fold cases\n    float_min_val = get_min_value(\"float32\")\n    for orig_pad in [[0, 0], [2, 0]]:\n        for i_pad in [[1, 1], [1, 0]]:\n            for ndim in [1, 2, 3]:\n                for channels_last in [0, 1]:\n                    if channels_last:\n                        layout = \"NDHWC\"\n                        layout = layout[0:1] + layout[4 - ndim : 4] + layout[-1:]\n                        padding = [[0, 0]] + [i_pad] * ndim + [[0, 0]]\n                    else:\n                        layout = \"NCDHW\"\n                        layout = layout[0:2] + layout[5 - ndim :]\n                        padding = [[0, 0]] * 2 + [i_pad] * ndim\n\n                    validate(max_pools, ndim, padding, float_min_val, orig_pad * ndim, layout, 2)\n\n    # Check Pool pad folding when pad width on pad op is all zero.\n    validate(max_pools, 1, [[0, 0], [0, 0], [0, 0]], float_min_val, [2, 0], \"NCW\", 2)\n    # Check MaxPool pad folding with uint dtype\n    int_min_val = get_min_value(\"uint8\")\n    validate(\n        max_pools,\n        2,\n        [[0, 0], [0, 0], [0, 2], [2, 0]],\n        int_min_val,\n        [2, 0, 0, 0],\n        \"NCHW\",\n        2,\n        dtype=\"uint8\",\n    )\n    # Fold when original AvgPool has its own padding but count_include_pad=True\n    validate(\n        avg_pools,\n        2,\n        [[0, 0], [0, 0], [0, 2], [2, 0]],\n        0,\n        [0, 0, 1, 0],\n        \"NCHW\",\n        2,\n        count_include_pad=True,\n    )\n    # Fold when count_include_pad=False but original AvgPool has no orig padding\n    validate(avg_pools, 2, [[0, 0], [0, 0], [0, 2], [2, 0]], 0, [0, 0, 0, 0], \"NCHW\", 2)\n\n    # Test no fold cases\n    # AvgPool only folds pad when count_include_pad (False by default) is True\n    validate(\n        avg_pools, 2, [[0, 0], [0, 0], [0, 2], [2, 0]], 0, [0, 0, 0, 0], \"NCHW\", 2, no_fold=True\n    )\n    # MaxPool only folds pad when pad_value is the min for its dtype\n    validate(max_pools, 1, [[0, 0], [0, 0], [0, 2]], 0, [0, 0], \"NCHW\", 2, no_fold=True)\n    # AvgPool only folds pad when pad_value=0\n    validate(avg_pools, 1, [[0, 0], [0, 0], [0, 2]], 1, [0, 0], \"NCHW\", 2, no_fold=True)\n    # Pools only fold when pad_mode=\"constant\"\n    validate(\n        avg_pools, 1, [[0, 0], [0, 0], [0, 2]], 0, [0, 0], \"NCHW\", 2, pad_mode=\"edge\", no_fold=True\n    )\n\n\ndef test_fold_pad_qconv2d():\n    def before():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        input_zero_point = 10\n        pad = relay.nn.pad(x, [[0, 0], [1, 1], [1, 1], [0, 0]], pad_value=input_zero_point)\n        return relay.qnn.op.conv2d(\n            pad,\n            weight,\n            relay.const(input_zero_point, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(0, 0),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 56, 56, 64), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(3, 3, 64, 64), dtype=\"int8\")\n        input_zero_point = 10\n        return relay.qnn.op.conv2d(\n            x,\n            weight,\n            relay.const(input_zero_point, \"int32\"),\n            relay.const(1, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n        )\n\n    a = run_opt_pass(before(), relay.transform.FoldExplicitPadding())\n    b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b, map_free_vars=True), \"Actual = \\n\" + str(a)\n\n\ndef test_pad_qconv2d_no_fold():\n    def get_expr():\n        x = relay.var(\"x\", shape=(1, 1, 2, 2), dtype=\"int8\")\n        weight = relay.var(\"weight\", shape=(1, 1, 2, 2), dtype=\"int8\")\n        # Pad value and input zp are not equal\n        pad_value = 1\n        input_zero_point = 0\n        pad = relay.nn.pad(x, [[0, 0], [0, 0], [1, 1], [1, 1]], pad_value=pad_value)\n        return relay.qnn.op.conv2d(\n            pad,\n            weight,\n            relay.const(input_zero_point, \"int32\"),\n            relay.const(0, \"int32\"),\n            relay.const(1, \"float32\"),\n            relay.const(1, \"float32\"),\n            channels=1,\n            kernel_size=(2, 2),\n            padding=(0, 0),\n        )\n\n    a = run_opt_pass(get_expr(), relay.transform.FoldExplicitPadding())\n    b = run_opt_pass(get_expr(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b, map_free_vars=True), (\n        \"\\nActual = \\n\" + str(a) + \"\\nExpected = \\n\" + str(b)\n    )\n\n\nif __name__ == \"__main__\":\n    test_simplify_conv_pad()\n    test_simplify_pool_pad()\n    test_fold_pad_qconv2d()\n    test_pad_qconv2d_no_fold()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fold_scale_axis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import create_workload\nfrom tvm.relay.build_module import bind_params_by_name\n\n\ndef initializer(_, param):\n    param = np.zeros(param.shape)\n\n\ndef _get_positive_scale(size):\n    return np.random.uniform(0.5, 1, size=size).astype(\"float32\")\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_fold_fwd_simple():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels, blocking):\n        args = [x, conv_weight, in_bias]\n        x = relay.multiply(x, in_scale)\n        x = relay.nn.relu(x)\n        x = relay.add(x, in_bias)\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW2i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, in_bias, in_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, in_bias]\n        if blocking:\n            squeezed_scale = relay.squeeze(in_scale, axis=[0, 2, 3])\n            x = relay.nn.relu(x)\n            in_bias = relay.divide(\n                in_bias,\n                relay.reshape(squeezed_scale, (1, in_channels // blocking[0], 1, 1, blocking[0])),\n            )  # NCHWc\n            x = relay.add(x, in_bias)\n            conv_weight = relay.multiply(\n                conv_weight, relay.reshape(squeezed_scale, (1, in_channels // 2, 1, 1, 2, 1))\n            )  # OIHWio\n        else:\n            squeezed_scale = relay.squeeze(in_scale, axis=[1, 2])\n            x = relay.nn.relu(x)\n            in_bias = relay.divide(\n                in_bias, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=2)\n            )\n            x = relay.add(x, in_bias)\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=2)\n            )\n\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW2i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        return relay.Function(args, y)\n\n    def check(shape, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            in_channels = shape[1] * shape[4]\n            in_bias = relay.var(\"in_bias\", shape=(1, in_channels // blocking[0], 1, 1, blocking[0]))\n            in_scale = relay.const(\n                _get_positive_scale((1, in_channels // blocking[0], 1, 1, blocking[0]))\n            )\n        else:\n            in_channels = shape[1]\n            in_bias = relay.var(\"in_bias\", shape=(in_channels, 1, 1))\n            in_scale = relay.const(_get_positive_scale((in_channels, 1, 1)))\n        y1 = before(x, weight, in_bias, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        y1_expected = expected(x, weight, in_bias, in_scale, in_channels, channels, blocking)\n\n        y1_folded = run_opt_pass(y1_folded, transform.InferType())\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 2, None)\n    check((2, 2, 10, 10, 2), 8, (2, 4))\n\n\ndef test_fold_fwd_dual_path():\n    \"\"\"scale axis being consumed by two consumers\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels, blocking):\n        args = [x, conv_weight, in_bias]\n        x = relay.multiply(in_scale, x)\n        x = relay.nn.relu(x)\n        x = relay.subtract(x, in_bias)\n        y1 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            groups=channels,\n            padding=(1, 1),\n        )\n        y2 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            groups=channels,\n            padding=(1, 1),\n        )\n        z = relay.add(y1, y2)\n        return relay.Function(args, z)\n\n    def expected(x, conv_weight, in_bias, in_scale, channels, blocking):\n        args = [x, conv_weight, in_bias]\n        x = relay.nn.relu(x)\n        if blocking:\n            _in_scale = relay.reshape(\n                in_scale, (1, 1, 1, channels // blocking[0], blocking[0])\n            )  # NHWCc\n        else:\n            _in_scale = in_scale\n        in_bias = relay.divide(in_bias, _in_scale)\n        x = relay.subtract(x, in_bias)\n        if blocking:\n            _in_scale = relay.reshape(\n                in_scale, (1, 1, 1, channels // blocking[0], 1, blocking[0])\n            )  # HWIOio\n        y1 = relay.nn.conv2d(\n            x,\n            relay.multiply(conv_weight, _in_scale),\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            groups=channels,\n            padding=(1, 1),\n        )\n        if blocking:\n            _in_scale = relay.reshape(\n                in_scale, (1, 1, 1, channels // blocking[0], 1, blocking[0])\n            )  # HWIOio\n        y2 = relay.nn.conv2d(\n            x,\n            relay.multiply(conv_weight, _in_scale),\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            groups=channels,\n            padding=(1, 1),\n        )\n        z = relay.add(y1, y2)\n        return relay.Function(args, z)\n\n    def check(dshape, channels, blocking):\n        x = relay.var(\"x\", shape=dshape)\n        if blocking:\n            in_channels = dshape[3] * dshape[4]\n            wshape = (3, 3, 1, channels // blocking[1], 1, blocking[1])  # HWIOio\n            weight = relay.var(\"weight\", shape=wshape)\n            in_bias = relay.var(\"in_bias\", shape=(in_channels // blocking[0], blocking[0]))\n            in_scale = relay.const(_get_positive_scale((in_channels // blocking[0], blocking[0])))\n        else:\n            in_channels = dshape[-1]\n            wshape = (3, 3, 1, channels)  # HWIO\n            weight = relay.var(\"weight\", shape=wshape)\n            in_bias = relay.var(\"in_bias\", shape=(in_channels,))\n            in_scale = relay.const(\n                _get_positive_scale(\n                    in_channels,\n                )\n            )\n\n        # test depthwise\n        assert in_channels == channels\n\n        y1 = before(x, weight, in_bias, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_expected = expected(x, weight, in_bias, in_scale, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 3), 3, None)\n    check((2, 4, 10, 2, 2), 4, (2, 2))\n\n\ndef test_fold_fwd_fail():\n    \"\"\"testcase where we canont fold\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels, blocking):\n        x = relay.multiply(x, in_scale)\n        xx = relay.nn.leaky_relu(x, alpha=0.1)\n        y1 = relay.nn.conv2d(\n            xx,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            padding=(1, 1),\n        )\n        z = relay.add(y1, x)\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    def check(shape, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        if blocking:\n            in_channels = shape[3] * shape[4]\n            in_bias = relay.var(\"in_bias\", shape=(in_channels // blocking[0], blocking[0]))\n            in_scale = relay.const(_get_positive_scale((in_channels // blocking[0], blocking[0])))\n        else:\n            in_channels = shape[-1]\n            in_bias = relay.var(\"in_bias\", shape=(in_channels,))\n            in_scale = relay.const(_get_positive_scale(size=(in_channels,)))\n        # test depthwise\n        assert in_channels == channels\n        weight = relay.var(\"weight\")\n        y1 = before(x, weight, in_bias, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        assert tvm.ir.structural_equal(y1, y1_folded)\n\n    check((2, 11, 10, 4), 4, None)\n    check((2, 11, 10, 2, 2), 4, (2, 2))\n\n\ndef test_fold_fwd_relu_fail():\n    \"\"\"testcase where we canont fold because scale can not pass relu\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels, blocking):\n        x = relay.multiply(x, in_scale)\n        xx = relay.nn.relu(x)\n        y1 = relay.nn.conv2d(\n            xx,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC{}c\".format(blocking[0]) if blocking else \"NHWC\",\n            kernel_layout=\"HWIO1i{}o\".format(blocking[1]) if blocking else \"HWIO\",\n            padding=(1, 1),\n        )\n        z = relay.add(y1, x)\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    def check(shape, channels, blocking, in_scale):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            in_channels = shape[3] * shape[4]\n            in_bias = relay.var(\"in_bias\", shape=(1, in_channels // blocking[0], 1, 1, blocking[0]))\n        else:\n            in_channels = shape[-1]\n            in_bias = relay.var(\"in_bias\", shape=(in_channels,))\n\n        assert in_channels == channels\n        y1 = before(x, weight, in_bias, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        assert tvm.ir.structural_equal(y1, y1_folded)\n\n    in_scale = relay.var(\"in_scale\", shape=(4,))\n    check((2, 11, 10, 4), 4, None, in_scale)\n    in_scale = relay.const(-_get_positive_scale((4,)))\n    check((2, 11, 10, 4), 4, None, in_scale)\n\n    in_scale = relay.var(\"in_scale\", shape=(1, 1, 1, 2, 2))\n    check((2, 11, 10, 2, 2), 4, (2, 2), in_scale)\n    in_scale = relay.const(-_get_positive_scale((1, 1, 1, 2, 2)))\n    check((2, 11, 10, 2, 2), 4, (2, 2), in_scale)\n\n\ndef test_fold_fwd_let_fail():\n    \"\"\"testcase where we canont fold\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels):\n        args = [x, conv_weight, in_bias]\n        x = relay.multiply(x, in_scale)\n        x = relay.nn.relu(x)\n        x = relay.add(x, in_bias)\n        x_var = relay.Var(\"x_var\")\n        y1 = relay.nn.conv2d(\n            x_var,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            data_layout=\"NHWC\",\n            kernel_layout=\"HWIO\",\n            padding=(1, 1),\n        )\n        z = relay.add(y1, x)\n        let = relay.Let(x_var, x, z)\n        return relay.Function(args, let)\n\n    def check(shape, channels):\n        x = relay.var(\"x\", shape=shape)\n        in_channels = shape[-1]\n        in_bias = relay.var(\"in_bias\", shape=(in_channels,))\n        in_scale = relay.const(_get_positive_scale(size=(in_channels,)))\n        # test depthwise\n        assert in_channels == channels\n        weight = relay.var(\"weight\")\n        y1 = before(x, weight, in_bias, in_scale, channels)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        assert tvm.ir.structural_equal(y1, y1_folded)\n\n    check((2, 11, 10, 4), 4)\n\n\ndef test_fold_fwd_negative_scale():\n    \"\"\"Testcase of folding negative scale\"\"\"\n\n    def before(x, conv_weight, in_scale, channels, blocking):\n        args = [x, conv_weight]\n        x = relay.multiply(x, in_scale)\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW4i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, in_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight]\n        if blocking:\n            squeezed_scale = relay.squeeze(in_scale, axis=[0, 2, 3])\n            conv_weight = relay.multiply(\n                conv_weight, relay.reshape(squeezed_scale, (1, in_channels // 4, 1, 1, 4, 1))\n            )\n            # blocking by \"i\" in OIHWio\n        else:\n            squeezed_scale = relay.squeeze(in_scale, axis=[1, 2])\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=2)\n            )\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW4i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        return relay.Function(args, y)\n\n    def check(shape, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        if blocking:\n            in_channels = shape[1] * shape[4]\n            in_scale = relay.const(-_get_positive_scale((1, shape[1], 1, 1, shape[4])))\n        else:\n            in_channels = shape[1]\n            in_scale = relay.const(-_get_positive_scale((in_channels, 1, 1)))\n        weight = relay.var(\"weight\")\n        y1 = before(x, weight, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        y1_expected = expected(x, weight, in_scale, in_channels, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 4, None)\n    check((2, 2, 10, 10, 2), 8, (2, 2))\n\n\ndef test_fold_fwd_dense():\n    \"\"\"dense testcase.\"\"\"\n\n    def before(x, weight, in_bias, in_scale):\n        args = [x, weight, in_bias]\n        x = relay.multiply(x, in_scale)\n        x = relay.nn.relu(x)\n        x = relay.add(x, in_bias)\n        y = relay.nn.dense(x, weight)\n        return relay.Function(args, y)\n\n    def expected(x, weight, in_bias, in_scale):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, weight, in_bias]\n        x = relay.nn.relu(x)\n        in_bias = relay.divide(in_bias, in_scale)\n        x = relay.add(x, in_bias)\n        weight = relay.multiply(weight, in_scale)\n        y = relay.nn.dense(x, weight)\n        return relay.Function(args, y)\n\n    def check(data_shape, weight_shape):\n        x = relay.var(\"x\", shape=data_shape)\n        weight = relay.var(\"weight\", shape=weight_shape)\n        in_channels = data_shape[1]\n        in_bias = relay.var(\"in_bias\", shape=(in_channels,))\n        in_scale = relay.const(_get_positive_scale((in_channels,)))\n        y1 = before(x, weight, in_bias, in_scale)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        y1_expected = expected(x, weight, in_bias, in_scale)\n\n        y1_folded = run_opt_pass(y1_folded, transform.InferType())\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4), (3, 4))\n    check((3, 5), (4, 5))\n\n\ndef test_fold_bwd_simple():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        if blocking:\n            out_bias = relay.reshape(out_bias, (1, channels // blocking[1], 1, 1, blocking[1]))\n        else:\n            out_bias = relay.expand_dims(out_bias, axis=1, num_newaxis=2)\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y = relay.add(y, out_bias)\n        y = relay.nn.relu(y)\n        if blocking:\n            out_scale = relay.reshape(out_scale, (1, channels // blocking[1], 1, 1, blocking[1]))\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, out_bias]\n        if blocking:\n            out_bias = relay.reshape(out_bias, (1, channels // blocking[1], 1, 1, blocking[1]))\n            out_scale = relay.reshape(out_scale, (1, channels // blocking[1], 1, 1, blocking[1]))\n            squeezed_scale = relay.squeeze(out_scale, axis=[0, 2, 3])\n            conv_weight = relay.multiply(\n                conv_weight,\n                relay.reshape(squeezed_scale, (channels // blocking[1], 1, 1, 1, 1, blocking[1])),\n            )\n        else:\n            out_bias = relay.expand_dims(out_bias, axis=1, num_newaxis=2)\n            squeezed_scale = relay.squeeze(out_scale, axis=[1, 2])\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n            )\n\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        if blocking:\n            out_bias = relay.multiply(\n                out_bias,\n                relay.reshape(squeezed_scale, (1, channels // blocking[1], 1, 1, blocking[1])),\n            )\n        else:\n            out_bias = relay.multiply(\n                out_bias, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=2)\n            )\n        y = relay.add(y, out_bias)\n        y = relay.nn.relu(y)\n        return relay.Function(args, y)\n\n    def check(shape, in_channels, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        out_bias = relay.var(\"out_bias\", shape=(channels,))\n        if blocking:\n            out_scale = relay.const(_get_positive_scale((channels,)))\n        else:\n            out_scale = relay.const(_get_positive_scale((channels, 1, 1)))\n        y1 = before(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 4, 8, None)\n    check((2, 2, 10, 10, 16), 32, 64, (16, 16))\n\n\ndef test_fold_bwd_dual_path():\n    \"\"\"Dual path testcase.\"\"\"\n\n    def before(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        y1 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y2 = relay.nn.relu(y2)\n        y = relay.add(y1, y2)\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, out_bias]\n        if not blocking:\n            out_bias = relay.expand_dims(out_bias, axis=1, num_newaxis=2)\n        squeezed_scale = relay.squeeze(out_scale, axis=[1, 2])\n\n        def fold_conv_weight():\n            if blocking:\n                return relay.multiply(\n                    conv_weight,\n                    relay.reshape(\n                        squeezed_scale, (channels // blocking[1], 1, 1, 1, 1, blocking[1])\n                    ),\n                )\n            else:\n                return relay.multiply(\n                    conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n                )\n\n        y1 = relay.nn.conv2d(\n            x,\n            fold_conv_weight(),\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(\n            x,\n            fold_conv_weight(),\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y2 = relay.nn.relu(y2)\n        y = relay.add(y1, y2)\n        return relay.Function(args, y)\n\n    def check(shape, in_channels, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            out_bias = relay.var(\"out_bias\", shape=(channels // blocking[1], 1, 1, blocking[1]))\n            out_scale = relay.const(\n                _get_positive_scale((channels // blocking[1], 1, 1, blocking[1]))\n            )\n        else:\n            out_bias = relay.var(\"out_bias\", shape=(channels,))\n            out_scale = relay.const(_get_positive_scale((channels, 1, 1)))\n\n        y1 = before(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 4, 8, None)\n    check((2, 2, 10, 10, 2), 4, 8, (2, 2))\n\n\ndef test_fold_bwd_simple_constant():\n    def before(data, weight, out_bias, channels):\n        y = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n\n        y = relay.add(y, out_bias)\n        c2 = relay.const(2.0)\n        y = relay.nn.relu(y)\n        y = relay.multiply(y, c2)\n        mod, params = create_workload(y, initializer)\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n        return mod\n\n    def expected(data, weight, out_bias, channels):\n        y0 = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n        y0 = relay.add(y0, out_bias)\n        y0 = relay.nn.relu(y0)\n        mod, params = create_workload(y0, initializer)\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n        return mod\n\n    def check(shape, channels):\n        x = relay.var(\"data\", relay.TensorType(shape, \"float32\"))\n        weight = relay.var(\"weight\")\n        out_bias = relay.var(\"in_bias\", shape=(channels, 1, 1))\n\n        y0 = before(x, weight, out_bias, channels)\n        remove_last_multiply = tvm.transform.Sequential(\n            [\n                relay.transform.InferType(),\n                relay.transform.FoldScaleAxis(),\n            ]\n        )\n        with tvm.transform.PassContext(opt_level=3):\n            y0 = remove_last_multiply(y0)\n        _expect = expected(x, weight, out_bias, channels)\n        tvm.ir.assert_structural_equal(y0, _expect)\n\n    check((1, 3, 200, 200), 16)\n\n\ndef test_fold_bwd_dual_consumer():\n    def before(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        y0 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y0 = relay.multiply(y0, out_scale)\n        y0 = relay.nn.relu(y0)\n\n        y1 = relay.nn.conv2d(\n            y0,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y1 = relay.multiply(y1, out_scale)\n        y1 = relay.nn.relu(y1)\n\n        y2 = relay.nn.conv2d(\n            y0,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y2 = relay.multiply(y2, out_scale)\n        y2 = relay.nn.relu(y2)\n\n        y = relay.add(y1, y2)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, out_bias]\n\n        def fold_conv_weight():\n            squeezed_scale = relay.squeeze(out_scale, axis=[1, 2])\n            if blocking:\n                return relay.multiply(\n                    conv_weight,\n                    relay.reshape(\n                        squeezed_scale, (channels // blocking[1], 1, 1, 1, 1, blocking[1])\n                    ),\n                )\n            else:\n                return relay.multiply(\n                    conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n                )\n\n        y0 = relay.nn.conv2d(\n            x,\n            fold_conv_weight(),\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y0 = relay.nn.relu(y0)\n        y1 = relay.nn.conv2d(\n            y0,\n            fold_conv_weight(),\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(\n            y0,\n            fold_conv_weight(),\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y2 = relay.nn.relu(y2)\n        y = relay.add(y1, y2)\n        return relay.Function(args, y)\n\n    def check(shape, in_channels, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            out_bias = relay.var(\"out_bias\", shape=(channels // blocking[1], 1, 1, blocking[1]))\n            out_scale = relay.const(\n                _get_positive_scale((channels // blocking[1], 1, 1, blocking[1]))\n            )\n        else:\n            out_bias = relay.var(\"out_bias\", shape=(channels,))\n            out_scale = relay.const(_get_positive_scale((channels, 1, 1)))\n\n        y1 = before(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 4, 4, None)\n    check((2, 2, 10, 10, 2), 4, 4, (2, 2))\n\n\ndef test_fold_bwd_fail():\n    \"\"\"Dual path testcase.\"\"\"\n\n    def fail1(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        y1 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y1 = relay.nn.relu(y1)\n        y2 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n            out_layout=\"CNHW{}c\".format(blocking[1]) if blocking else \"CNHW\",\n        )\n        # fold will fail because the axis from two path\n        # differs from each other.\n        y2 = relay.nn.relu(y2)\n        y = relay.add(y1, y2)\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def fail2(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        y1 = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y2 = relay.nn.relu(y1)\n        # fold will fail because y1 is referred also by y2\n        y1 = relay.multiply(y1, out_scale)\n        y = relay.add(y1, y2)\n        return relay.Function(args, y)\n\n    def check(shape, in_channels, channels, blocking, fbefore):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            out_bias = relay.var(\"out_bias\", shape=(channels // blocking[1], 1, 1, blocking[1]))\n            out_scale = relay.const(\n                _get_positive_scale((channels // blocking[1], 1, 1, blocking[1]))\n            )\n        else:\n            out_bias = relay.var(\"out_bias\", shape=(channels, 1, 1))\n            out_scale = relay.const(_get_positive_scale((channels, 1, 1)))\n        y1 = fbefore(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        assert tvm.ir.structural_equal(y1_folded, y1)\n\n    check((4, 4, 10, 10), 4, 4, None, fail1)\n    check((2, 2, 10, 10, 2), 4, 4, (2, 2), fail1)\n    check((4, 4, 10, 10), 4, 4, None, fail2)\n    check((4, 2, 10, 10, 2), 4, 4, (2, 2), fail2)\n\n\ndef test_fold_bwd_relu_fail():\n    \"\"\"testcase where we canont fold because scale can not pass relu\"\"\"\n\n    def before(x, conv_weight, out_scale, channels, blocking):\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y = relay.nn.relu(y)\n        y = relay.multiply(x, out_scale)\n        return relay.Function(relay.analysis.free_vars(y), y)\n\n    def check(shape, channels, blocking, out_scale):\n        x = relay.var(\"x\", shape=shape)\n        in_channels = shape[1]\n        weight = relay.var(\"weight\")\n        y1 = before(x, weight, out_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        assert tvm.ir.structural_equal(y1, y1_folded)\n\n    out_scale = relay.var(\"in_scale\", shape=(4, 1, 1))\n    check((4, 4, 10, 10), 4, None, out_scale)\n    out_scale = relay.const(np.random.uniform(size=(4, 1, 1), low=-1.0, high=0.0)).astype(\"float32\")\n    check((4, 4, 10, 10), 4, None, out_scale)\n\n    out_scale = relay.var(\"in_scale\", shape=(1, 2, 1, 1, 2))\n    check((4, 2, 10, 10, 2), 4, (2, 2), out_scale)\n    out_scale = relay.const(np.random.uniform(size=(1, 2, 1, 1, 2), low=-1.0, high=0.0)).astype(\n        \"float32\"\n    )\n    check((4, 2, 10, 10, 2), 4, (2, 2), out_scale)\n\n\ndef test_fold_bwd_negative_scale():\n    \"\"\"Testcase of folding negative scale\"\"\"\n\n    def before(x, conv_weight, out_scale, channels, blocking):\n        args = [x, conv_weight]\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_scale, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight]\n        if blocking:\n            squeezed_scale = relay.squeeze(out_scale, axis=[0, 2, 3])\n            conv_weight = relay.multiply(\n                conv_weight,\n                relay.reshape(squeezed_scale, (channels // blocking[1], 1, 1, 1, 1, blocking[1])),\n            )\n        else:\n            squeezed_scale = relay.squeeze(out_scale, axis=[1, 2])\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n            )\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW{}c\".format(blocking[0]) if blocking else \"NCHW\",\n            kernel_layout=\"OIHW1i{}o\".format(blocking[1]) if blocking else \"OIHW\",\n        )\n        return relay.Function(args, y)\n\n    def check(shape, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            out_scale = relay.const(\n                -_get_positive_scale((1, channels // blocking[1], 1, 1, blocking[1]))\n            )\n        else:\n            out_scale = relay.const(-_get_positive_scale((channels, 1, 1)))\n        y1 = before(x, weight, out_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_scale, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 8, None)\n    check((2, 2, 10, 10, 2), 8, (2, 2))\n\n\ndef test_fold_bwd_dense():\n    \"\"\"dense testcase.\"\"\"\n\n    def before(x, weight, in_bias, in_scale):\n        args = [x, weight, in_bias]\n        x = relay.nn.dense(x, weight)\n        x = relay.add(x, in_bias)\n        x = relay.nn.relu(x)\n        y = relay.multiply(x, in_scale)\n        return relay.Function(args, y)\n\n    def expected(x, weight, in_bias, in_scale):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, weight, in_bias]\n        scale = relay.expand_dims(in_scale, axis=1)\n        weight = relay.multiply(weight, scale)\n        x = relay.nn.dense(x, weight)\n        bias = relay.multiply(in_bias, in_scale)\n        x = relay.add(x, bias)\n        y = relay.nn.relu(x)\n        return relay.Function(args, y)\n\n    def check(data_shape, weight_shape):\n        x = relay.var(\"x\", shape=data_shape)\n        weight = relay.var(\"weight\", shape=weight_shape)\n        out_channels = weight_shape[0]\n        in_bias = relay.var(\"in_bias\", shape=(out_channels,))\n        in_scale = relay.const(_get_positive_scale((out_channels,)))\n        y1 = before(x, weight, in_bias, in_scale)\n        y1 = run_opt_pass(y1, transform.InferType())\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, in_bias, in_scale)\n\n        y1_folded = run_opt_pass(y1_folded, transform.InferType())\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4), (3, 4))\n    check((3, 5), (4, 5))\n\n\ndef test_fold_bwd_bias_add():\n    \"\"\"bias add testcase.\"\"\"\n\n    def before(x, conv_weight, out_bias, out_scale, channels):\n        args = [x, conv_weight, out_bias]\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n        y = relay.nn.bias_add(y, out_bias)\n        y = relay.nn.relu(y)\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_bias, out_scale, channels):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, out_bias]\n        squeezed_scale = relay.squeeze(out_scale, axis=[1, 2])\n        conv_weight = relay.multiply(\n            conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n        )\n\n        y = relay.nn.conv2d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n\n        out_bias = relay.multiply(out_bias, squeezed_scale)\n        y = relay.nn.bias_add(y, out_bias)\n        y = relay.nn.relu(y)\n        return relay.Function(args, y)\n\n    def check(shape, channels):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        out_bias = relay.var(\"out_bias\", shape=(channels,))\n        out_scale = relay.const(_get_positive_scale((channels, 1, 1)))\n        y1 = before(x, weight, out_bias, out_scale, channels)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_bias, out_scale, channels)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10), 4)\n\n\ndef test_fold_fwd_conv3d():\n    \"\"\"Conv3d testcase.\"\"\"\n\n    def before(x, conv_weight, in_bias, in_scale, channels, blocking):\n        args = [x, conv_weight, in_bias]\n        x = relay.multiply(x, in_scale)\n        x = relay.nn.relu(x)\n        x = relay.add(x, in_bias)\n        y = relay.nn.conv3d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3, 3),\n            padding=(1, 1, 1),\n            data_layout=\"NCDHW{}c\".format(blocking[0]) if blocking else \"NCDHW\",\n            kernel_layout=\"OIDHW2i{}o\".format(blocking[1]) if blocking else \"OIDHW\",\n        )\n\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, in_bias, in_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, in_bias]\n        if blocking:\n            squeezed_scale = relay.squeeze(in_scale, axis=[0, 2, 3, 4])\n            x = relay.nn.relu(x)\n            in_bias = relay.divide(\n                in_bias,\n                relay.reshape(\n                    squeezed_scale, (1, in_channels // blocking[0], 1, 1, 1, blocking[0])\n                ),\n            )  # NCHWc\n            x = relay.add(x, in_bias)\n            conv_weight = relay.multiply(\n                conv_weight, relay.reshape(squeezed_scale, (1, in_channels // 2, 1, 1, 1, 2, 1))\n            )  # OIHWio\n        else:\n            squeezed_scale = relay.squeeze(in_scale, axis=[1, 2, 3])\n            x = relay.nn.relu(x)\n            in_bias = relay.divide(\n                in_bias, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n            )\n            x = relay.add(x, in_bias)\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n            )\n\n        y = relay.nn.conv3d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3, 3),\n            padding=(1, 1, 1),\n            data_layout=\"NCDHW{}c\".format(blocking[0]) if blocking else \"NCDHW\",\n            kernel_layout=\"OIDHW2i{}o\".format(blocking[1]) if blocking else \"OIDHW\",\n        )\n        return relay.Function(args, y)\n\n    def check(shape, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        if blocking:\n            in_channels = shape[1] * shape[-1]\n            in_bias = relay.var(\n                \"in_bias\", shape=(1, in_channels // blocking[0], 1, 1, 1, blocking[0])\n            )\n            in_scale = relay.const(\n                _get_positive_scale((1, in_channels // blocking[0], 1, 1, 1, blocking[0]))\n            )\n        else:\n            in_channels = shape[1]\n            in_bias = relay.var(\"in_bias\", shape=(in_channels, 1, 1, 1))\n            in_scale = relay.const(_get_positive_scale((in_channels, 1, 1, 1)))\n        y1 = before(x, weight, in_bias, in_scale, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.ForwardFoldScaleAxis())\n        y1_expected = expected(x, weight, in_bias, in_scale, in_channels, channels, blocking)\n\n        y1_folded = run_opt_pass(y1_folded, transform.InferType())\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10, 10), 2, None)\n    check((2, 2, 10, 10, 10, 2), 8, (2, 4))\n\n\ndef test_fold_bwd_conv3d():\n    \"\"\"Conv3d testcase.\"\"\"\n\n    def before(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        args = [x, conv_weight, out_bias]\n        if blocking:\n            out_bias = relay.reshape(out_bias, (1, channels // blocking[1], 1, 1, 1, blocking[1]))\n        else:\n            out_bias = relay.expand_dims(out_bias, axis=1, num_newaxis=3)\n        y = relay.nn.conv3d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3, 3),\n            padding=(1, 1, 1),\n            data_layout=\"NCDHW{}c\".format(blocking[0]) if blocking else \"NCDHW\",\n            kernel_layout=\"OIDHW1i{}o\".format(blocking[1]) if blocking else \"OIDHW\",\n        )\n        y = relay.add(y, out_bias)\n        y = relay.nn.relu(y)\n        if blocking:\n            out_scale = relay.reshape(out_scale, (1, channels // blocking[1], 1, 1, 1, blocking[1]))\n        y = relay.multiply(y, out_scale)\n        return relay.Function(args, y)\n\n    def expected(x, conv_weight, out_bias, out_scale, in_channels, channels, blocking):\n        # use a fixed order of args so alpha equal check can pass\n        args = [x, conv_weight, out_bias]\n        if blocking:\n            out_bias = relay.reshape(out_bias, (1, channels // blocking[1], 1, 1, 1, blocking[1]))\n            out_scale = relay.reshape(out_scale, (1, channels // blocking[1], 1, 1, 1, blocking[1]))\n            squeezed_scale = relay.squeeze(out_scale, axis=[0, 2, 3, 4])\n            conv_weight = relay.multiply(\n                conv_weight,\n                relay.reshape(\n                    squeezed_scale, (channels // blocking[1], 1, 1, 1, 1, 1, blocking[1])\n                ),\n            )\n        else:\n            out_bias = relay.expand_dims(out_bias, axis=1, num_newaxis=3)\n            squeezed_scale = relay.squeeze(out_scale, axis=[1, 2, 3])\n            conv_weight = relay.multiply(\n                conv_weight, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=4)\n            )\n\n        y = relay.nn.conv3d(\n            x,\n            conv_weight,\n            channels=channels,\n            kernel_size=(3, 3, 3),\n            padding=(1, 1, 1),\n            data_layout=\"NCDHW{}c\".format(blocking[0]) if blocking else \"NCDHW\",\n            kernel_layout=\"OIDHW1i{}o\".format(blocking[1]) if blocking else \"OIDHW\",\n        )\n        if blocking:\n            out_bias = relay.multiply(\n                out_bias,\n                relay.reshape(squeezed_scale, (1, channels // blocking[1], 1, 1, 1, blocking[1])),\n            )\n        else:\n            out_bias = relay.multiply(\n                out_bias, relay.expand_dims(squeezed_scale, axis=1, num_newaxis=3)\n            )\n        y = relay.add(y, out_bias)\n        y = relay.nn.relu(y)\n        return relay.Function(args, y)\n\n    def check(shape, in_channels, channels, blocking):\n        x = relay.var(\"x\", shape=shape)\n        weight = relay.var(\"weight\")\n        out_bias = relay.var(\"out_bias\", shape=(channels,))\n        if blocking:\n            out_scale = relay.const(_get_positive_scale((channels,)))\n        else:\n            out_scale = relay.const(_get_positive_scale((channels, 1, 1, 1)))\n        y1 = before(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1 = run_opt_pass(y1, transform.InferType())\n        type_dict = {x.name_hint: x.checked_type for x in y1.params}\n        weight = relay.var(\"weight\", type_dict[\"weight\"])\n        y1_folded = run_opt_pass(y1, transform.BackwardFoldScaleAxis())\n        y1_expected = expected(x, weight, out_bias, out_scale, in_channels, channels, blocking)\n        y1_expected = run_opt_pass(y1_expected, transform.InferType())\n        assert tvm.ir.structural_equal(y1_folded, y1_expected)\n\n    check((2, 4, 10, 10, 10), 4, 8, None)\n    check((2, 2, 10, 10, 10, 16), 32, 64, (16, 16))\n\n\nif __name__ == \"__main__\":\n    test_fold_fwd_simple()\n    test_fold_fwd_dual_path()\n    test_fold_fwd_fail()\n    test_fold_fwd_relu_fail()\n    test_fold_fwd_negative_scale()\n    test_fold_fwd_dense()\n    test_fold_bwd_simple_constant()\n    test_fold_bwd_simple()\n    test_fold_bwd_dual_path()\n    test_fold_bwd_dual_consumer()\n    test_fold_bwd_fail()\n    test_fold_bwd_relu_fail()\n    test_fold_bwd_negative_scale()\n    test_fold_bwd_dense()\n    test_fold_bwd_bias_add()\n    test_fold_fwd_conv3d()\n    test_fold_bwd_conv3d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_fuse_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_opt_pass\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef test_fuse_simple():\n    \"\"\"Simple testcase.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.exp(y)\n        w = relay.squeeze(z)\n        return relay.Function([x], w)\n\n    def expected():\n        x = relay.var(\"p\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.exp(y)\n        w = relay.squeeze(z)\n        f1 = relay.Function([x], w)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.Call(f1, [x])\n        return relay.Function([x], y)\n\n    z = before()\n    zz = run_opt_pass(z, transform.FuseOps())\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_conv2d_fuse():\n    \"\"\"Test fusion case of conv2d\"\"\"\n\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        x = relay.add(x, relay.const(1, \"float32\"))\n        y = relay.nn.conv2d(x, relay.var(\"w1\"), kernel_size=(3, 3), padding=(1, 1), channels=16)\n        # this is the next dominator.\n        y1 = relay.add(relay.const(1, \"float32\"), y)\n        y = relay.add(y, y1)\n        # second path\n        z2 = relay.nn.conv2d(y, relay.var(\"w2\"), kernel_size=(1, 1), padding=(0, 0), channels=16)\n        z3 = relay.nn.conv2d(y, relay.var(\"w3\"), kernel_size=(3, 3), padding=(1, 1), channels=16)\n        # add can only be fused to z1\n        z = relay.add(z2, z3)\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    def expected(dshape):\n        # segment 0\n        x = relay.var(\"p0\", shape=dshape)\n        y = relay.add(x, relay.const(1, \"float32\"))\n        f0 = relay.Function([x], y)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        # segment 1\n        x = relay.var(\"p0\", shape=dshape)\n        w = relay.var(\"p1\")\n        y = relay.nn.conv2d(x, w, kernel_size=(3, 3), padding=(1, 1), channels=16)\n        y1 = relay.add(relay.const(1, \"float32\"), y)\n        y = relay.add(y, y1)\n        f1 = relay.Function([x, w], y)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        # segment 2\n        x = relay.var(\"p0\", shape=dshape)\n        w = relay.var(\"p1\")\n        z2 = relay.nn.conv2d(x, w, kernel_size=(3, 3), padding=(1, 1), channels=16)\n        f2 = relay.Function([x, w], z2)\n        f2 = f2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        # segment 3\n        x = relay.var(\"p0\", shape=dshape)\n        w = relay.var(\"p1\")\n        offset = relay.var(\"p2\", shape=dshape)\n        z3 = relay.nn.conv2d(x, w, kernel_size=(1, 1), padding=(0, 0), channels=16)\n        z3 = relay.add(z3, offset)\n        f3 = relay.Function([x, w, offset], z3)\n        f3 = f3.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        # compose\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f0, [x])\n        y = relay.Call(f1, [y, relay.var(\"w1\")])\n        z2 = relay.Call(f2, [y, relay.var(\"w3\")])\n        z3 = relay.Call(f3, [y, relay.var(\"w2\"), z2])\n        z = z3\n        return relay.Function(relay.analysis.free_vars(z), z)\n\n    dshape = (1, 16, 64, 64)\n    z = before(dshape)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_concatenate():\n    \"\"\"Test fusion case involving concat op and Tuple node\"\"\"\n\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        pooled = relay.nn.max_pool2d(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        upsampled = relay.nn.upsampling(pooled, scale_h=2, scale_w=2, layout=\"NCHW\")\n        concat = relay.concatenate((upsampled, x), axis=1)\n        out = relay.add(concat, relay.const(1, \"float32\"))\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def expected(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        pooled = relay.nn.max_pool2d(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        f0 = relay.Function([x], pooled)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p0 = relay.var(\"p0\", shape=(dshape[0], dshape[1], dshape[2] // 2, dshape[3] // 2))\n        p1 = relay.var(\"p1\", shape=dshape)\n        upsampled = relay.nn.upsampling(p0, scale_h=2, scale_w=2, layout=\"NCHW\")\n        concat = relay.concatenate((upsampled, p1), axis=1)\n        out = relay.add(concat, relay.const(1, \"float32\"))\n        f1 = relay.Function([p0, p1], out)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f0, [x])\n        z = relay.Call(f1, [y, x])\n        return relay.Function([x], z)\n\n    dshape = (1, 16, 64, 64)\n    z = before(dshape)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=0))\n    assert not relay.analysis.free_vars(zz)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    assert not relay.analysis.free_vars(zz)\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_tuple_root():\n    \"\"\"Test fusion case where Tuple node is the root in its group\"\"\"\n\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        pooled = relay.nn.max_pool2d(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        upsampled = relay.nn.upsampling(pooled, scale_h=2, scale_w=2, layout=\"NCHW\")\n        out = relay.Tuple((upsampled, x))\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def expected(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        pooled = relay.nn.max_pool2d(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        f0 = relay.Function([x], pooled)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p0 = relay.var(\"p0\", shape=(dshape[0], dshape[1], dshape[2] // 2, dshape[3] // 2))\n        upsampled = relay.nn.upsampling(p0, scale_h=2, scale_w=2, layout=\"NCHW\")\n        f1 = relay.Function([p0], upsampled)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f0, [x])\n        z = relay.Call(f1, [y])\n        tup = relay.Tuple((z, x))\n        return relay.Function([x], tup)\n\n    dshape = (1, 16, 64, 64)\n    z = before(dshape)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=0))\n    assert not relay.analysis.free_vars(zz)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    assert not relay.analysis.free_vars(zz)\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_stop_fusion():\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.add(x, relay.const(1, \"float32\"))\n        y = relay.annotation.stop_fusion(y)\n        z = relay.exp(y)\n        return relay.Function([x], z)\n\n    def expected(dshape):\n        x = relay.var(\"p0\", shape=dshape)\n        y = relay.add(x, relay.const(1, \"float32\"))\n        f1 = relay.Function([x], y)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"p01\", shape=dshape)\n        y = relay.exp(x)\n        f2 = relay.Function([x], y)\n        f2 = f2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f1, [x])\n        z = relay.Call(f2, [y])\n        return relay.Function([x], z)\n\n    dshape = (10, 20)\n    z = before(dshape)\n    zz = run_opt_pass(z, transform.FuseOps())\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_fuse_myia_regression():\n    def before(dshape, dtype):\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        y = relay.var(\"y\", shape=dshape, dtype=dtype)\n        sb = relay.ScopeBuilder()\n        with sb.if_scope(relay.op.greater(x, y)):\n            sb.ret(relay.Function([], x))\n        with sb.else_scope():\n            sb.ret(relay.Function([], y))\n        return relay.Function([x, y], relay.Call(sb.get(), []))\n\n    def expected(dshape, dtype):\n        x = relay.var(\"x\", shape=dshape, dtype=dtype)\n        y = relay.var(\"y\", shape=dshape, dtype=dtype)\n        sb = relay.ScopeBuilder()\n        p1 = relay.var(\"p1\", shape=dshape, dtype=dtype)\n        p2 = relay.var(\"p2\", shape=dshape, dtype=dtype)\n        fused_gt = relay.Function([p1, p2], relay.op.greater(p1, p2))\n        fused_gt = fused_gt.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        with sb.if_scope(fused_gt(x, y)):\n            sb.ret(relay.Function([], x))\n        with sb.else_scope():\n            sb.ret(relay.Function([], y))\n        return relay.Function([x, y], relay.Call(sb.get(), []))\n\n    dshape = ()\n    dtype = \"int64\"\n    f = before(dshape, dtype)\n    zz = run_opt_pass(f, transform.FuseOps())\n    after = run_opt_pass(expected(dshape, dtype), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_fuse_tuple_get_elemwise():\n    def before(dim):\n        X = relay.var(\"X\", shape=(1, dim))\n        W = relay.var(\"W\", shape=(3 * dim, dim))\n        matmul = relay.nn.dense(X, W)\n        splitted = relay.split(matmul, indices_or_sections=3, axis=1)\n        out = relay.sigmoid(splitted[0]) + relay.tanh(splitted[1]) * relay.exp(splitted[2])\n        return relay.Function([X, W], out)\n\n    def expected(dim):\n        p0 = relay.var(\"p0\", shape=(1, dim))\n        p1 = relay.var(\"p1\", shape=(3 * dim, dim))\n        matmul = relay.nn.dense(p0, p1)\n        f0 = relay.Function([p0, p1], matmul)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p01 = relay.var(\"p01\", shape=(1, 3 * dim))\n        splitted = relay.split(p01, indices_or_sections=3, axis=1)\n        out = relay.sigmoid(splitted[0]) + relay.tanh(splitted[1]) * relay.exp(splitted[2])\n        f1 = relay.Function([p01], out)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        X = relay.var(\"X\", shape=(1, dim))\n        W = relay.var(\"W\", shape=(3 * dim, dim))\n        y = relay.Call(f0, [X, W])\n        z = relay.Call(f1, [y])\n        return relay.Function([X, W], z)\n\n    dim = 10\n    z = before(dim)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=0))\n    assert not relay.analysis.free_vars(zz)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    assert not relay.analysis.free_vars(zz)\n    after = run_opt_pass(expected(dim), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_tuple_get_root():\n    def before(dim):\n        X = relay.var(\"X\", shape=(1, 3 * dim))\n        W = relay.var(\"W\", shape=(dim, dim))\n        splitted = relay.split(X, indices_or_sections=3, axis=1)\n        out = relay.nn.dense(splitted[0], W)\n        return relay.Function([X, W], out)\n\n    def expected(dim):\n        p0 = relay.var(\"p0\", shape=(1, 3 * dim))\n        splitted = relay.split(p0, indices_or_sections=3, axis=1)\n        out = splitted[0]\n        f0 = relay.Function([p0], out)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p01 = relay.var(\"p01\", shape=(1, dim))\n        p1 = relay.var(\"p1\", shape=(dim, dim))\n        out = relay.nn.dense(p01, p1)\n        f1 = relay.Function([p01, p1], out)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        X = relay.var(\"X\", shape=(1, 3 * dim))\n        W = relay.var(\"W\", shape=(dim, dim))\n        y = relay.Call(f0, [X])\n        z = relay.Call(f1, [y, W])\n        return relay.Function([X, W], z)\n\n    dim = 10\n    z = before(dim)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=0))\n    assert not relay.analysis.free_vars(zz)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    assert not relay.analysis.free_vars(zz)\n    after = run_opt_pass(expected(dim), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef fuse0(mod):\n    mod = relay.transform.InferType()(mod)\n    return relay.transform.FuseOps(fuse_opt_level=0)(mod)\n\n\ndef fuse2(mod):\n    mod = relay.transform.InferType()(mod)\n    return relay.transform.FuseOps(fuse_opt_level=2)(mod)\n\n\ndef test_tuple_intermediate():\n    def before(x):\n        inj = relay.squeeze(x)\n        y1 = relay.add(inj, relay.const(1, \"float32\"))\n        tmp = relay.squeeze(inj)\n        tmp = relay.add(tmp, relay.const(1, \"float32\"))\n        y2 = relay.add(tmp, relay.const(1, \"float32\"))\n        y3 = relay.add(inj, relay.const(1, \"float32\"))\n        concat = relay.concatenate((y1, y2, y3), axis=1)\n        out_inj = relay.squeeze(concat)\n        out = relay.add(out_inj, relay.const(1, \"float32\"))\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def expected(p0):\n        f0 = before(p0)\n        f1 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f1, [x])\n        return relay.Function([x], y)\n\n    dshape = (1, 16, 64, 64)\n    x = relay.var(\"x\", shape=dshape)\n    orig = before(x)\n    fuse0(tvm.IRModule.from_expr(orig))\n    m = fuse2(tvm.IRModule.from_expr(orig))\n    relay.build(m, \"llvm\")\n    after = run_opt_pass(expected(x), transform.InferType())\n    assert tvm.ir.structural_equal(m[\"main\"], after)\n\n\ndef test_tuple_consecutive():\n    def gen_intermediate_tuple(x):\n        y1 = relay.add(x, relay.const(1, \"float32\"))\n        y2 = relay.add(x, relay.const(1, \"float32\"))\n        y3 = relay.add(x, relay.const(1, \"float32\"))\n        concat = relay.concatenate((y1, y2, y3), axis=1)\n        out = relay.add(concat, relay.const(1, \"float32\"))\n        return out\n\n    def gen_consecutive_tuple(x):\n        y1 = gen_intermediate_tuple(x)\n        y2 = gen_intermediate_tuple(x)\n        y3 = gen_intermediate_tuple(x)\n        concat = relay.concatenate((y1, y2, y3), axis=1)\n        return concat\n\n    def before(x):\n        concat = gen_consecutive_tuple(x)\n        pooled = relay.nn.max_pool2d(concat, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        out = relay.add(pooled, relay.const(1, \"float32\"))\n        out2 = relay.add(out, relay.const(1, \"float32\"))\n        out_tup = relay.Tuple((out, out2))\n        return relay.Function(relay.analysis.free_vars(out_tup), out_tup)\n\n    def expected(dshape):\n        p0 = relay.var(\"p0\", shape=dshape)\n        concat = gen_consecutive_tuple(p0)\n        f0 = relay.Function([p0], concat)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p01 = relay.var(\"p01\", shape=(1, dshape[1] * 9, dshape[2], dshape[3]))\n        pooled = relay.nn.max_pool2d(p01, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))\n        out = relay.add(pooled, relay.const(1, \"float32\"))\n        f1 = relay.Function([p01], out)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p02 = relay.var(\"p02\", shape=(1, dshape[1] * 9, dshape[2] // 2, dshape[3] // 2))\n        out = relay.add(p02, relay.const(1, \"float32\"))\n        f2 = relay.Function([p02], out)\n        f2 = f2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=dshape)\n        y = relay.Call(f0, [x])\n        z = relay.Call(f1, [y])\n        z2 = relay.Call(f2, [z])\n\n        return relay.Function([x], relay.Tuple((z, z2)))\n\n    dshape = (1, 16, 64, 64)\n    x = relay.var(\"x\", shape=dshape)\n    orig = before(x)\n    fuse0(tvm.IRModule.from_expr(orig))\n    m = fuse2(tvm.IRModule.from_expr(orig))\n    relay.build(m, \"llvm\")\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(m[\"main\"], after)\n\n\ndef test_inception_like():\n    def conv(data):\n        y = relay.nn.conv2d(data, relay.var(\"w\"), kernel_size=(3, 3), padding=(1, 1), channels=16)\n        return relay.nn.relu(data=y)\n\n    def inception_like(data):\n        c0 = conv(data)\n        c1 = conv(data)\n        return relay.concatenate((c0, c1), axis=1)\n\n    def before(dshape):\n        x = relay.var(\"x\", shape=dshape)\n        in1 = inception_like(x)\n        in2 = inception_like(in1)\n        return relay.Function(relay.analysis.free_vars(in2), in2)\n\n    def expected(dshape):\n        p0 = relay.var(\"p0\", shape=dshape)\n        c = conv(p0)\n        f0 = relay.Function(relay.analysis.free_vars(c), c)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p01 = relay.var(\"p01\", shape=dshape)\n        c = conv(p01)\n        f1 = relay.Function(relay.analysis.free_vars(c), c)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p02 = relay.var(\"p02\", shape=dshape)\n        p12 = relay.var(\"p12\", shape=dshape)\n        concat1 = relay.concatenate((p02, p12), axis=1)\n        f_concat1 = relay.Function([p02, p12], concat1)\n        f_concat1 = f_concat1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        dshape2 = (dshape[0], dshape[1] * 2, dshape[2], dshape[3])\n\n        p03 = relay.var(\"p03\", shape=dshape2)\n        c = conv(p03)\n        f2 = relay.Function(relay.analysis.free_vars(c), c)\n        f2 = f2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p04 = relay.var(\"p04\", shape=dshape2)\n        c = conv(p04)\n        f3 = relay.Function(relay.analysis.free_vars(c), c)\n        f3 = f3.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        p05 = relay.var(\"p05\", shape=dshape)\n        p15 = relay.var(\"p15\", shape=dshape)\n        concat2 = relay.concatenate((p05, p15), axis=1)\n        f_concat2 = relay.Function([p05, p15], concat2)\n        f_concat2 = f_concat2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=dshape)\n        c1 = relay.Call(f0, [x, relay.var(\"w1\")])\n        c2 = relay.Call(f1, [x, relay.var(\"w2\")])\n        concat = relay.Call(f_concat1, [c1, c2])\n        c3 = relay.Call(f2, [concat, relay.var(\"w3\")])\n        c4 = relay.Call(f3, [concat, relay.var(\"w4\")])\n        out = relay.Call(f_concat2, [c3, c4])\n\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    dshape = (1, 16, 64, 64)\n    orig = before(dshape)\n    fuse0(tvm.IRModule.from_expr(orig))\n    m = fuse2(tvm.IRModule.from_expr(orig))\n    relay.build(m, \"llvm\")\n    after = run_opt_pass(expected(dshape), transform.InferType())\n    assert tvm.ir.structural_equal(m[\"main\"], after)\n\n\ndef test_fuse_parallel_injective():\n    \"\"\"Test fusing parallel injective ops to an elemwise op.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.squeeze(y)\n        u = relay.transpose(y, axes=[0, 1])\n        w = relay.left_shift(z, u)\n        return relay.Function([x], w)\n\n    def expected():\n        x = relay.var(\"p\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.squeeze(y)\n        u = relay.transpose(y, axes=[0, 1])\n        w = relay.left_shift(z, u)\n        f1 = relay.Function([x], w)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.Call(f1, [x])\n        return relay.Function([x], y)\n\n    z = before()\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=0))\n    assert not relay.analysis.free_vars(zz)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    assert not relay.analysis.free_vars(zz)\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_immutable():\n    \"\"\"Verify the fusion pass won't change original module.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.exp(y)\n        w = relay.squeeze(z)\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x], w)\n        return mod\n\n    def expected():\n        x = relay.var(\"p\", shape=(10, 20))\n        y = relay.add(x, relay.const(1, \"float32\"))\n        z = relay.exp(y)\n        w = relay.squeeze(z)\n        f1 = relay.Function([x], w)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        x = relay.var(\"x\", shape=(10, 20))\n        y = relay.Call(f1, [x])\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x], y)\n        return mod\n\n    mod = transform.InferType()(before())\n    new_mod = transform.FuseOps(fuse_opt_level=2)(mod)\n    assert tvm.ir.structural_equal(mod, transform.InferType()(before()))\n    assert tvm.ir.structural_equal(new_mod, transform.InferType()(expected()))\n\n\ndef test_split():\n    \"\"\"Test that the result is well formed.\"\"\"\n    x = relay.var(\"x\", shape=(6, 9))\n    y = relay.split(x, 3).astuple()\n    a = relay.TupleGetItem(y, 0)\n    b = relay.TupleGetItem(y, 1)\n    c = relay.TupleGetItem(y, 2)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], a + relay.RefRead(relay.RefCreate(b)) + c)\n    mod = transform.InferType()(mod)\n    mod = transform.FuseOps()(mod)\n\n\ndef test_fuse_max():\n    \"\"\"Test the constraint of number of nodes in op fusion.\"\"\"\n\n    def before(n):\n        x = relay.var(\"x\", shape=(10, 20))\n        y = x\n        for i in range(n):\n            y = relay.exp(y)\n        return relay.Function([x], y)\n\n    def expected(n, max_fused_ops):\n        x = relay.var(\"p\", shape=(10, 20))\n        y = x\n        for i in range(max_fused_ops):\n            y = relay.exp(y)\n        f1 = relay.Function([x], y)\n        f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        x = relay.var(\"x\", shape=(10, 20))\n        z = relay.Call(f1, [x])\n        xx = relay.var(\"pp\", shape=(10, 20))\n        yy = xx\n        # it is assumed that there are two fused functions\n        for i in range(n - max_fused_ops):\n            yy = relay.exp(yy)\n        f2 = relay.Function([xx], yy)\n        f2 = f2.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        zz = relay.Call(f2, [z])\n        return relay.Function([x], zz)\n\n    max_fused_ops = 256\n    n = 300\n    z = before(n)\n    zz = run_opt_pass(z, transform.FuseOps(fuse_opt_level=2))\n    zz = run_opt_pass(z, transform.FuseOps())\n    after = run_opt_pass(expected(n, max_fused_ops), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n    max_fused_ops = 10\n    n = 20\n    z = before(n)\n    after = run_opt_pass(expected(n, max_fused_ops), transform.InferType())\n\n    with tvm.transform.PassContext(config={\"relay.FuseOps.max_depth\": max_fused_ops}):\n        zz = run_opt_pass(z, transform.FuseOps())\n\n    assert tvm.ir.structural_equal(zz, after)\n\n\nlink_params = tvm.testing.parameter(False, True)\n\n\ndef test_fuse_take(link_params):\n    \"\"\"Test fusion case involving concat and take\"\"\"\n\n    def before():\n        shape = (tvm.tir.const(10, \"int64\"), tvm.tir.const(1, \"int64\"))\n        x = relay.var(\"x\", shape=shape)\n        concat = relay.concatenate([x, x], axis=-1)\n        out = relay.op.take(concat, indices=relay.const([0], dtype=\"int64\"))\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def expected(link_params):\n        shape1 = (tvm.tir.const(10, \"int64\"), tvm.tir.const(1, \"int64\"))\n        shape2 = (tvm.tir.const(1, \"int64\"),)\n        x = relay.var(\"x\", shape=shape1)\n        p0 = relay.var(\"p0\", shape=shape1)\n        p1 = relay.var(\"p1\", shape=shape2, dtype=\"int64\")\n        c = relay.const([0], dtype=\"int64\")\n        concat = relay.concatenate([p0, p0], axis=-1)\n        out = relay.op.take(concat, indices=c if link_params else p1)\n\n        f0 = relay.Function([p0] if link_params else [p0, p1], out)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        y = relay.Call(f0, [x] if link_params else [x, c])\n        return relay.Function([x], y)\n\n    after = run_opt_pass(expected(link_params), transform.InferType())\n    with tvm.transform.PassContext(opt_level=2, config={\"relay.FuseOps.link_params\": link_params}):\n        m = run_opt_pass(before(), transform.InferType())\n        m = run_opt_pass(m, transform.FuseOps())\n    assert tvm.ir.structural_equal(m, after)\n    relay.build(m, \"llvm\")\n\n\ndef test_fuse_gather_nd(link_params):\n    \"\"\"Test fusion case involving concat and gather_nd\"\"\"\n\n    def before():\n        shape = (tvm.tir.const(10, \"int64\"), tvm.tir.const(1, \"int64\"))\n        x = relay.var(\"x\", shape=shape)\n        concat = relay.concatenate([x, x], axis=-1)\n        out = relay.gather_nd(concat, indices=relay.expr.const([[0, 1], [1, 0]], dtype=\"int64\"))\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def expected(link_params):\n        shape1 = (tvm.tir.const(10, \"int64\"), tvm.tir.const(1, \"int64\"))\n        shape2 = (tvm.tir.const(2, \"int64\"), tvm.tir.const(2, \"int64\"))\n        x = relay.var(\"x\", shape=shape1)\n        p0 = relay.var(\"p0\", shape=shape1)\n        p1 = relay.var(\"p1\", shape=shape2, dtype=\"int64\")\n        c = relay.const([[0, 1], [1, 0]], dtype=\"int64\")\n        concat = relay.concatenate([p0, p0], axis=-1)\n        out = relay.gather_nd(concat, indices=c if link_params else p1)\n\n        f0 = relay.Function([p0] if link_params else [p0, p1], out)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        y = relay.Call(f0, [x] if link_params else [x, c])\n        return relay.Function([x], y)\n\n    after = run_opt_pass(expected(link_params), transform.InferType())\n    with tvm.transform.PassContext(opt_level=2, config={\"relay.FuseOps.link_params\": link_params}):\n        m = run_opt_pass(before(), transform.InferType())\n        m = run_opt_pass(m, transform.FuseOps())\n    assert tvm.ir.structural_equal(m, after)\n    relay.build(m, \"llvm\")\n\n\n@tvm.testing.uses_gpu\ndef test_fuse_bcast_reduce_scalar():\n    \"\"\"Test fusion case with broadcast and reduction involving scalar\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(), dtype=\"int32\")\n        less = relay.less(x, relay.const(10, dtype=\"int32\"))\n        z = relay.min(less)\n        return relay.Function([x], z)\n\n    def expected():\n        p0 = relay.var(\"p0\", shape=(), dtype=\"int32\")\n        less = relay.less(p0, relay.const(10, dtype=\"int32\"))\n        z0 = relay.min(less)\n        f0 = relay.Function([p0], z0)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n\n        x = relay.var(\"x\", shape=(), dtype=\"int32\")\n        f = relay.Call(f0, [x])\n        return relay.Function([x], f)\n\n    orig = before()\n    m = fuse2(tvm.IRModule.from_expr(orig))\n    for tgt, dev in tvm.testing.enabled_targets():\n        relay.build(m, tgt)\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(m[\"main\"], after)\n\n\ndef test_fuse_max_diamond():\n    def create_diamond(x, branch_len):\n        x1 = x\n        x2 = x\n        for _ in range(branch_len):\n            x1 = relay.exp(x1)\n            x2 = relay.exp(x2)\n        return relay.add(x1, x2)\n\n    def before(branch_len, num_diamond):\n        x = relay.var(\"x\", shape=(10, 20))\n        out = x\n        for _ in range(num_diamond):\n            out = create_diamond(out, branch_len)\n        return relay.Function([x], out)\n\n    def after(branch_len, num_diamond):\n        def create_diamond_func(inp):\n            inp_var = relay.var(\"p\", shape=(10, 20))\n            d = create_diamond(inp_var, branch_len)\n            f = relay.Function([inp_var], d)\n            f = f.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n            return relay.Call(f, [inp])\n\n        inp = relay.var(\"x\", shape=(10, 20))\n        out = inp\n        for _ in range(num_diamond):\n            out = create_diamond_func(out)\n        return relay.Function([inp], out)\n\n    branch_len = 5\n    max_fused_ops = branch_len * 2 + 1  # the number of ops in one diamond\n    num_diamond = 3\n\n    with tvm.transform.PassContext(config={\"relay.FuseOps.max_depth\": max_fused_ops}):\n        fused = run_opt_pass(before(branch_len, num_diamond), transform.FuseOps())\n\n    expected = run_opt_pass(after(branch_len, num_diamond), transform.InferType())\n    assert tvm.ir.structural_equal(fused, expected)\n\n\ndef test_fuse_dynamic_squeeze_slice_take():\n    input_data = [\n        np.random.random([1, 2, 4]).astype(\"float32\"),\n        np.array([0]).astype(\"int64\"),\n    ]\n\n    x = relay.var(\"p0107\", shape=(relay.Any(), relay.Any(), 4), dtype=\"float32\")\n    take_val = relay.var(\"p166\", shape=(relay.Any(),), dtype=\"int64\")\n\n    squeeze = relay.op.squeeze(x, axis=[0])\n    strided_slice = relay.op.strided_slice(\n        squeeze, begin=[0, 0], end=[15130, 2147483647], strides=[1, 1]\n    )\n    take = relay.op.take(strided_slice, take_val, axis=0)\n\n    mod = tvm.IRModule.from_expr(take)\n    result = relay.create_executor(\"vm\", mod=mod, device=tvm.cpu(), target=\"llvm\").evaluate()(\n        *input_data\n    )\n\n    np_result = np.squeeze(input_data[0][:, input_data[1][0], :], axis=0)\n\n    assert np.allclose(result.numpy(), np_result)\n\n\n@tvm.testing.uses_gpu\ndef test_fuse_softmax():\n    \"\"\"Test if softmax can be fused with following ops.\"\"\"\n    channel_size = 16\n\n    def before():\n        x = relay.var(\"x\", shape=(16, channel_size))\n        softmax = relay.nn.softmax(x)\n        out = relay.cast(softmax, \"float16\")\n        return relay.Function([x], out)\n\n    def expected():\n        p0 = relay.var(\"p0\", shape=(16, channel_size))\n        softmax = relay.nn.softmax(p0)\n        out = relay.cast(softmax, \"float16\")\n\n        x = relay.var(\"x\", shape=(16, channel_size))\n\n        f0 = relay.Function([p0], out)\n        f0 = f0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        y = relay.Call(f0, [x])\n        return relay.Function([x], y)\n\n    orig = before()\n    m = fuse2(tvm.IRModule.from_expr(orig))\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(m[\"main\"], after)\n\n    inp = np.random.randn(16, channel_size).astype(\"float32\")\n    ref = tvm.topi.testing.softmax_python(inp).astype(\"float16\")\n\n    for tgt, dev in tvm.testing.enabled_targets():\n        ex = relay.create_executor(\"graph\", mod=m, device=dev, target=tgt)\n        result = ex.evaluate()(inp).numpy()\n        tvm.testing.assert_allclose(result, ref, rtol=1e-4, atol=1e-4)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__pfile__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_gradient.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport collections\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import GlobalVar\nfrom tvm.relay.analysis import free_vars, free_type_vars\nfrom tvm.relay import create_executor, transform\nfrom tvm.relay.transform import gradient\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.testing import (\n    make_nat_expr,\n    run_infer_type,\n    check_grad,\n    rand,\n    count_ops,\n)\nimport tvm.relay.op as op\n\n\ndef test_fo_id():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func, mode=\"first_order\"))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), np.ones_like(x.numpy()))\n\n\ndef test_id():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), np.ones_like(x.numpy()))\n\n\ndef test_relu():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], op.nn.relu(x))\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    # gradient will implicitly check that no graph appear in result\n\n\ndef test_add():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x + x)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), 2 * x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), 2 * np.ones_like(x.numpy()))\n\n\ndef test_check_grad():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    y = relay.var(\"y\", t)\n    func = relay.Function([x, y], x + y)\n    check_grad(func)\n\n\ndef test_temp_add():\n    scope = relay.ScopeBuilder()\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    y = scope.let(\"y\", x + x)\n    scope.ret(y + y)\n    func = relay.Function([x], scope.get())\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), 4 * x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), 4 * np.ones_like(x.numpy()))\n\n\ndef test_sub():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x - x)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), np.zeros_like(x.numpy()))\n    tvm.testing.assert_allclose(grad.numpy(), np.zeros_like(x.numpy()))\n\n\ndef test_broadcast_add():\n    shape1 = (3, 4, 1)\n    shape2 = (1, 5)\n    dtype = \"float32\"\n    x_nd = rand(dtype, *shape1)\n    y_nd = rand(dtype, *shape2)\n    x_np = x_nd.numpy()\n    y_np = y_nd.numpy()\n    expected_forward = x_np + y_np\n    t1 = relay.TensorType(shape1, dtype)\n    t2 = relay.TensorType(shape2, dtype)\n    x = relay.var(\"x\", t1)\n    y = relay.var(\"y\", t2)\n    func = relay.Function([x, y], x + y)\n    func = run_infer_type(func)\n    full_func = run_infer_type(gradient(func))\n    assert full_func.checked_type == relay.FuncType(\n        [t1, t2],\n        relay.TupleType(\n            [relay.TensorType(expected_forward.shape, dtype), relay.TupleType([t1, t2])]\n        ),\n    )\n    forward, (grad_x, grad_y) = create_executor().evaluate(full_func)(x_nd, y_nd)\n    tvm.testing.assert_allclose(forward.numpy(), expected_forward)\n    tvm.testing.assert_allclose(\n        grad_x.numpy(), np.ones_like(expected_forward).sum(axis=2, keepdims=True)\n    )\n    tvm.testing.assert_allclose(\n        grad_y.numpy(),\n        np.ones_like(expected_forward).sum(axis=(0, 1), keepdims=True).squeeze(axis=0),\n    )\n\n\ndef test_broadcast_subtract():\n    shape1 = (3, 4, 1)\n    shape2 = (1, 5)\n    dtype = \"float32\"\n    x_nd = rand(dtype, *shape1)\n    y_nd = rand(dtype, *shape2)\n    x_np = x_nd.numpy()\n    y_np = y_nd.numpy()\n    expected_forward = x_np - y_np\n    t1 = relay.TensorType(shape1, dtype)\n    t2 = relay.TensorType(shape2, dtype)\n    x = relay.var(\"x\", t1)\n    y = relay.var(\"y\", t2)\n    func = relay.Function([x, y], x - y)\n    func = run_infer_type(func)\n    full_func = run_infer_type(gradient(func))\n    assert full_func.checked_type == relay.FuncType(\n        [t1, t2],\n        relay.TupleType(\n            [relay.TensorType(expected_forward.shape, dtype), relay.TupleType([t1, t2])]\n        ),\n    )\n    forward, (grad_x, grad_y) = create_executor().evaluate(full_func)(x_nd, y_nd)\n    tvm.testing.assert_allclose(forward.numpy(), expected_forward)\n    tvm.testing.assert_allclose(\n        grad_x.numpy(), np.ones_like(expected_forward).sum(axis=2, keepdims=True)\n    )\n    tvm.testing.assert_allclose(\n        grad_y.numpy(),\n        -np.ones_like(expected_forward).sum(axis=(0, 1), keepdims=True).squeeze(axis=0),\n    )\n\n\ndef _test_tuple(mode):\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    y = relay.var(\"y\", t)\n    z = relay.var(\"z\", t)\n    if mode == \"higher_order\":\n        tup = relay.Var(\"tup\")\n        func = relay.Function(\n            [x, y, z],\n            relay.Let(\n                tup,\n                relay.Tuple([x, y, z]),\n                relay.TupleGetItem(tup, 0)\n                + relay.TupleGetItem(tup, 1)\n                - relay.TupleGetItem(tup, 2),\n            ),\n        )\n    else:\n        # first order does not do let.\n        tup = relay.Tuple([x, y, z])\n        func = relay.Function(\n            [x, y, z],\n            relay.TupleGetItem(tup, 0) + relay.TupleGetItem(tup, 1) - relay.TupleGetItem(tup, 2),\n        )\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func, mode=mode))\n    assert back_func.checked_type == relay.FuncType(\n        [t, t, t], relay.TupleType([t, relay.TupleType([t, t, t])])\n    )\n    x_nd = rand(dtype, *shape)\n    y_nd = rand(dtype, *shape)\n    z_nd = rand(dtype, *shape)\n    x_np = x_nd.numpy()\n    y_np = y_nd.numpy()\n    z_np = z_nd.numpy()\n    expected_forward = x_np + y_np - z_np\n    forward, (grad_x, grad_y, grad_z) = create_executor().evaluate(back_func)(x_nd, y_nd, z_nd)\n    tvm.testing.assert_allclose(forward.numpy(), expected_forward)\n    tvm.testing.assert_allclose(grad_x.numpy(), np.ones_like(grad_x.numpy()))\n    tvm.testing.assert_allclose(grad_y.numpy(), np.ones_like(grad_y.numpy()))\n    tvm.testing.assert_allclose(grad_z.numpy(), -1 * np.ones_like(grad_z.numpy()))\n\n\ndef _test_tuple_argument(mode):\n    shape = (2, 3)\n    dtype = \"float32\"\n    tensor_type = relay.TensorType(shape, dtype)\n    fields = 3\n    tuple_type = relay.TupleType([tensor_type] * fields)\n    tup = relay.var(\"tup\", type_annotation=tuple_type)\n    body = relay.TupleGetItem(tup, 0)\n    for i in range(1, fields):\n        body = relay.add(body, relay.TupleGetItem(tup, i))\n    func = relay.Function([tup], body)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func, mode=mode))\n    xs = [rand(dtype, *shape) for _ in range(fields)]\n    xs_np = np.array([x.numpy() for x in xs])\n    expected_forward = np.sum(xs_np, axis=0)\n    forward, grad = create_executor().evaluate(back_func)(tuple(xs))\n    tvm.testing.assert_allclose(forward.numpy(), expected_forward)\n    for field in grad[0]:\n        tvm.testing.assert_allclose(field.numpy(), np.ones_like(field.numpy()))\n\n\ndef test_tuple():\n    _test_tuple(\"higher_order\")\n\n\ndef test_tuple_first_order():\n    _test_tuple(\"first_order\")\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_tuple_argument():\n    # fails until we add support for top-level tuple arguments in higher-order AD\n    _test_tuple_argument(\"higher_order\")\n\n\ndef test_tuple_argument_first_order():\n    _test_tuple_argument(\"first_order\")\n\n\ndef test_pow():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat_iterate = mod.get_global_var(\"nat_iterate\")\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    double = relay.Function([x], x + x)\n    i = relay.var(\"i\", t)\n    func = relay.Function([i], nat_iterate(double, make_nat_expr(p, 3))(i))\n    mod[\"main\"] = func\n    mod = transform.InferType()(mod)\n    mod[\"main\"] = gradient(mod[\"main\"], mod=mod)\n    m = transform.InferType()(mod)\n    back_func = m[\"main\"]\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    i_nd = rand(dtype, *shape)\n    forward, (grad_i,) = create_executor(mod=mod).evaluate(back_func)(i_nd)\n    tvm.testing.assert_allclose(forward.numpy(), 8 * i_nd.numpy())\n    tvm.testing.assert_allclose(grad_i.numpy(), 8 * np.ones_like(grad_i.numpy()))\n\n\ndef test_ref():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    r = relay.Var(\"r\")\n    u = relay.Var(\"u\")\n    body = relay.RefRead(r)\n    body = relay.Let(u, relay.RefWrite(r, relay.RefRead(r) + relay.RefRead(r)), body)\n    body = relay.Let(r, relay.RefCreate(x), body)\n    func = relay.Function([x], body)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x_nd = rand(dtype, *shape)\n    forward, (grad_x,) = create_executor().evaluate(back_func)(x_nd)\n    tvm.testing.assert_allclose(forward.numpy(), 2 * x_nd.numpy())\n    tvm.testing.assert_allclose(grad_x.numpy(), 2 * np.ones_like(grad_x.numpy()))\n\n\ndef test_square_second_order():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    func = relay.Function([x], x * x)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    y = relay.var(\"y\", t)\n    back_func_adjusted = relay.Function(\n        [y], relay.TupleGetItem(relay.TupleGetItem(back_func(y), 1), 0)\n    )\n    back_func_adjusted = run_infer_type(back_func_adjusted)\n    back_back_func = run_infer_type(gradient(back_func_adjusted))\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x_nd = rand(dtype, *shape)\n    forward, (grad_x,) = create_executor().evaluate(back_back_func)(x_nd)\n    tvm.testing.assert_allclose(forward.numpy(), 2 * x_nd.numpy())\n    tvm.testing.assert_allclose(grad_x.numpy(), 2 * np.ones_like(grad_x.numpy()))\n\n\ndef test_if():\n    x = relay.var(\"x\", shape=(1, 16, 64, 64))\n    y = relay.var(\"y\", shape=(1, 16, 64, 64))\n    cond = relay.var(\"cond\", shape=(), dtype=\"uint1\")\n    net = relay.If(cond, x, y)\n    net = relay.log(net)\n    func = relay.Function(free_vars(net), net)\n    func = run_infer_type(func)\n    net = gradient(func, mode=\"higher_order\")\n    net = run_infer_type(net)\n\n\ndef test_grad_tuple():\n    scope = relay.ScopeBuilder()\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    y = scope.let(\"y\", x + x)\n    scope.ret(relay.Tuple([y + y, y]))\n    func = relay.Function([x], scope.get())\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    assert back_func.checked_type == relay.FuncType(\n        [t], relay.TupleType([relay.TupleType([t, t]), relay.TupleType([t])])\n    )\n    x = rand(dtype, *shape)\n    (forward_four, forward_two), (grad,) = create_executor().evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward_four.numpy(), 4 * x.numpy())\n    tvm.testing.assert_allclose(forward_two.numpy(), 2 * x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), 4 * np.ones_like(x.numpy()))\n\n\ndef test_concat():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    rt = relay.TensorType((10, 20), dtype)\n    x = relay.var(\"x\", t)\n    y = op.concatenate([x, x], axis=1)\n    func = relay.Function([x], y)\n    func = run_infer_type(func)\n    back_func = run_infer_type(gradient(func))\n    tvm.ir.assert_structural_equal(\n        back_func.checked_type, relay.FuncType([t], relay.TupleType([rt, relay.TupleType([t])]))\n    )\n    # no value validation as concatenate has dummy gradient right now.\n\n\ndef test_no_duplication():\n    x = tvm.relay.Var(\"x\", type_annotation=tvm.relay.TensorType([12, 12]))\n    y = tvm.relay.Var(\"y\", type_annotation=tvm.relay.TensorType([12, 12]))\n    xy = tvm.relay.nn.dense(x, y)\n\n    m = tvm.relay.sum(xy, keepdims=True)\n    s = tvm.relay.sum(xy - m)\n    fn = tvm.relay.Function([x, y], s)\n    fn = run_infer_type(fn)\n    gr = tvm.relay.transform.gradient(fn, mode=\"first_order\")\n\n    counts = count_ops(gr)\n    assert counts[\"nn.dense\"] == 3, \"We expect 3 dense (1 forward, two backward)\"\n\n\ndef test_no_duplication_tuples():\n    x = tvm.relay.Var(\"x\", type_annotation=tvm.relay.TensorType([12, 12]))\n    y = tvm.relay.Var(\"y\", type_annotation=tvm.relay.TensorType([12, 12]))\n    xy = tvm.relay.nn.dense(x, y)\n\n    t = relay.Tuple([xy, xy])\n\n    m = tvm.relay.sum(xy, keepdims=True)\n    s = tvm.relay.sum(relay.TupleGetItem(t, 0) - m)\n    fn = tvm.relay.Function([x, y], s)\n    fn = run_infer_type(fn)\n    gr = tvm.relay.transform.gradient(fn, mode=\"first_order\")\n\n    counts = count_ops(gr)\n    assert counts[\"nn.dense\"] == 3, \"We expect 3 dense (1 forward, two backward)\"\n\n\ndef test_global_function():\n    m = tvm.IRModule()\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.Var(\"x\", t)\n    d = GlobalVar(\"double\")\n    m[d] = relay.Function([x], x + x)\n    y = relay.Var(\"y\", t)\n    q = GlobalVar(\"q\")\n    m[q] = relay.Function([y], d(d(y)))\n    g = GlobalVar(\"grad\")\n    m = tvm.relay.transform.InferType()(m)\n    m[g] = tvm.relay.transform.gradient(q, m)\n    m = tvm.relay.transform.InferType()(m)\n    back_func = m[g]\n    assert back_func.checked_type == relay.FuncType([t], relay.TupleType([t, relay.TupleType([t])]))\n    x = rand(dtype, *shape)\n    forward, (grad,) = create_executor(mod=m).evaluate(back_func)(x)\n    tvm.testing.assert_allclose(forward.numpy(), 4 * x.numpy())\n    tvm.testing.assert_allclose(grad.numpy(), 4 * np.ones_like(x.numpy()))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_inline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-docstring, too-many-statements\nimport tvm\nfrom tvm import relay\n\n\ndef get_recursive_count_loop():\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sb = relay.ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n        sb.ret(i)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n        rec_call = relay.Call(sum_up, [one_less])\n        sb.ret(relay.add(rec_call, i))\n    func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    mod[sum_up] = func\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n    return mod, sum_up\n\n\ndef test_call_chain_inline_leaf():\n    \"\"\"Test when only leaf call is inlined.\n\n    The call graph is like the following:\n              main\n              /  \\\n             g1   g2\n             /\n            g11(inline)\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x11 = relay.var(\"x11\", shape=(3, 5))\n        g11 = relay.GlobalVar(\"g11\")\n        fn11 = relay.Function([x11], x11)\n        fn11 = fn11.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        mod[g11] = fn11\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1 + g11(x1))\n        fn1 = relay.Function([x1, y1], sb.get())\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1 + x1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_call_chain_inline_multiple_levels():\n    \"\"\"Test when only leaf call is inlined.\n\n    The call graph is like the following:\n                  main\n                 /    \\\n          g1(inline)   g2\n               /\n        g11(inline)\n\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x11 = relay.var(\"x11\", shape=(3, 5))\n        g11 = relay.GlobalVar(\"g11\")\n        fn11 = relay.Function([x11], x11)\n        fn11 = fn11.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        mod[g11] = fn11\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1 + g11(x1))\n        fn1 = relay.Function([x1, y1], sb.get())\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = p0 + p1 + p0\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_call_chain_inline_multiple_levels_extern_compiler():\n    \"\"\"Test when only leaf call is inlined.\n\n    The call graph is like the following:\n                  main\n                 /    \\\n          g1(inline)   g2\n               /\n        g11(inline, external compiler)\n\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x11 = relay.var(\"x11\", shape=(3, 5))\n        g11 = relay.GlobalVar(\"g11\")\n        fn11 = relay.Function([x11], x11)\n        fn11 = fn11.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn11 = fn11.with_attr(\"Compiler\", \"a\")\n        mod[g11] = fn11\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1 + g11(x1))\n        fn1 = relay.Function([x1, y1], sb.get())\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x11 = relay.var(\"x11\", shape=(3, 5))\n        fn11 = relay.Function([x11], x11)\n        fn11 = fn11.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn11 = fn11.with_attr(\"Compiler\", \"a\")\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = p0 + p1 + fn11(p0)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_recursive_call_with_global():\n    def get_mod():\n        mod = tvm.IRModule({})\n\n        x = relay.var(\"x\", shape=[], dtype=\"int32\")\n        fn0 = relay.Function([x], x)\n        fn0 = fn0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        gx = relay.GlobalVar(\"gx\")\n        mod[gx] = fn0\n\n        sum_up = relay.GlobalVar(\"sum_up\")\n        i = relay.var(\"i\", shape=[], dtype=\"int32\")\n        sb = relay.ScopeBuilder()\n        with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n            sb.ret(i)\n        with sb.else_scope():\n            one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n            global_call = gx(i)\n            rec_call = relay.Call(sum_up, [one_less]) + global_call\n            sb.ret(relay.add(rec_call, i))\n        func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n        func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        mod[sum_up] = func\n        iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n        mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n\n        sum_up = relay.GlobalVar(\"sum_up\")\n        i = relay.var(\"i\", shape=[], dtype=\"int32\")\n        sb = relay.ScopeBuilder()\n        with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n            sb.ret(i)\n        with sb.else_scope():\n            one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n            rec_call = relay.Call(sum_up, [one_less]) + i\n            sb.ret(relay.add(rec_call, i))\n        func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n        func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        mod[sum_up] = func\n        iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n        mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_recursive_called():\n    mod, sum_up = get_recursive_count_loop()\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n    ref_mod = mod\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, ref_mod, map_free_vars=True)\n\n\ndef test_recursive_not_called():\n    def get_mod():\n        mod, sum_up = get_recursive_count_loop()\n        x = relay.var(\"x\", shape=(2, 2))\n        y = relay.var(\"y\", shape=(2, 2))\n        x1 = relay.var(\"x1\", shape=(2, 2))\n        fn1 = relay.Function([x1], x1)\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n        mod[\"main\"] = relay.Function([x, y], x + y + g1(x))\n        return mod\n\n    def expected():\n        mod, sum_up = get_recursive_count_loop()\n        x = relay.var(\"x\", shape=(2, 2))\n        y = relay.var(\"y\", shape=(2, 2))\n        mod[\"main\"] = relay.Function([x, y], x + y + x)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    ref_mod = expected()\n    assert tvm.ir.structural_equal(mod, ref_mod, map_free_vars=True)\n\n\ndef test_recursive_not_called_extern_compiler():\n    def get_mod():\n        mod, sum_up = get_recursive_count_loop()\n        x = relay.var(\"x\", shape=(2, 2))\n        y = relay.var(\"y\", shape=(2, 2))\n        x1 = relay.var(\"x1\", shape=(2, 2))\n        fn1 = relay.Function([x1], x1)\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n        mod[\"main\"] = relay.Function([x, y], x + y + g1(x))\n        return mod\n\n    def expected():\n        mod, sum_up = get_recursive_count_loop()\n        x = relay.var(\"x\", shape=(2, 2))\n        y = relay.var(\"y\", shape=(2, 2))\n        x1 = relay.var(\"x1\", shape=(2, 2))\n        fn1 = relay.Function([x1], x1)\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n        mod[\"main\"] = relay.Function([x, y], x + y + fn1(x))\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    ref_mod = expected()\n    assert tvm.ir.structural_equal(mod, ref_mod, map_free_vars=True)\n\n\ndef test_globalvar_as_call_arg():\n    def get_mod():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = p0 + p1\n        call_fn2 = p2 - p3\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_globalvar_as_call_arg_extern_compiler():\n    def get_mod():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = fn2.with_attr(\"Compiler\", \"b\")\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = fn2.with_attr(\"Compiler\", \"b\")\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = relay.Call(fn1, [p0, p1])\n        call_fn2 = relay.Call(fn2, [p2, p3])\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_inline_globalvar_without_args():\n    def get_mod():\n        mod = tvm.IRModule({})\n        fn1 = relay.Function([], relay.const(1))\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = relay.Function([], relay.const(2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g1] = fn1\n        mod = relay.transform.InferType()(mod)\n        mod[g2] = fn2\n        p = relay.var(\"p\", \"bool\")\n        mod[\"main\"] = relay.Function([p], relay.Call(relay.If(p, g1, g2), []))\n        return relay.transform.InferType()(mod)\n\n    def expected():\n        mod = tvm.IRModule({})\n        fn1 = relay.Function([], relay.const(1))\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = relay.Function([], relay.const(2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        p = relay.var(\"p\", \"bool\")\n        mod[\"main\"] = relay.Function([p], relay.Call(relay.If(p, fn1, fn2), []))\n        return relay.transform.InferType()(mod)\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_inline_globalvar_without_args_extern_compiler():\n    def get_mod():\n        mod = tvm.IRModule({})\n        fn1 = relay.Function([], relay.const(1))\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n        fn2 = relay.Function([], relay.const(2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = fn2.with_attr(\"Compiler\", \"b\")\n        g1 = relay.GlobalVar(\"g1\")\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g1] = fn1\n        mod[g2] = fn2\n        p = relay.var(\"p\", \"bool\")\n        mod[\"main\"] = relay.Function([p], relay.Call(relay.If(p, g1, g2), []))\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        fn1 = relay.Function([], relay.const(1))\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn1 = fn1.with_attr(\"Compiler\", \"a\")\n        fn2 = relay.Function([], relay.const(2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn2 = fn2.with_attr(\"Compiler\", \"b\")\n        p = relay.var(\"p\", \"bool\")\n        mod[\"main\"] = relay.Function([p], relay.Call(relay.If(p, fn1, fn2), []))\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_globalvar_called_by_multiple_functions():\n    \"\"\"Test when only leaf call is inlined.\n\n    The call graph is like the following:\n                  main    g0\n                 /    \\   /\n                g1    g2(inline)\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        sb1 = relay.ScopeBuilder()\n        sb1.ret(x2 - y2)\n        fn2 = relay.Function([x2, y2], sb1.get())\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        x0 = relay.var(\"x0\", shape=(3, 5))\n        y0 = relay.var(\"y0\", shape=(3, 5))\n        z0 = relay.var(\"z0\", shape=(3, 5))\n        fn0 = relay.Function([x0, y0, z0], g2(x0, y0) + z0)\n        g0 = relay.GlobalVar(\"g0\")\n        mod[g0] = fn0\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn1 = g1(p0, p1)\n        call_fn2 = g2(p2, p3)\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], call_fn1 * call_fn2)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        sb = relay.ScopeBuilder()\n        sb.ret(x1 + y1)\n        fn1 = relay.Function([x1, y1], sb.get())\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        p0 = relay.var(\"p0\", shape=(3, 5))\n        p1 = relay.var(\"p1\", shape=(3, 5))\n        p2 = relay.var(\"p2\", shape=(3, 5))\n        p3 = relay.var(\"p3\", shape=(3, 5))\n\n        call_fn2 = p2 - p3\n        mod[\"main\"] = relay.Function([p0, p1, p2, p3], g1(p0, p1) * call_fn2)\n\n        x0 = relay.var(\"x0\", shape=(3, 5))\n        y0 = relay.var(\"y0\", shape=(3, 5))\n        z0 = relay.var(\"z0\", shape=(3, 5))\n\n        fn0 = relay.Function([x0, y0, z0], x0 - y0 + z0)\n        g0 = relay.GlobalVar(\"g0\")\n        mod[g0] = fn0\n\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_entry_with_inline():\n    \"\"\"Test entry function with inline\n\n    The call graph is like the following:\n                g1(inline)    g2(inline)\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + y1)\n        fn1 = fn1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - y2)\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, get_mod(), map_free_vars=True)\n\n\ndef test_callee_not_inline():\n    \"\"\"Test entry function with inline\n\n    The call graph is like the following:\n                    main\n                      |\n                 g2(inline)\n                      |\n                     g1\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + y1)\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - g1(x2, y2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, get_mod(), map_free_vars=True)\n\n\ndef test_callee_not_inline_leaf_inline():\n    \"\"\"Test entry function with inline\n\n    The call graph is like the following:\n                    main\n                      |\n                 g2(inline)\n                      |\n                     g1\n                      |\n                 g0(inline)\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x0 = relay.var(\"x0\", shape=(3, 5))\n        y0 = relay.var(\"y0\", shape=(3, 5))\n        fn0 = relay.Function([x0, y0], x0 * y0)\n        fn0 = fn0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g0 = relay.GlobalVar(\"g0\")\n        mod[g0] = fn0\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + g0(x1, y1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - g1(x2, y2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + x1 * y1)\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - g1(x2, y2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\ndef test_callee_not_inline_leaf_inline_extern_compiler():\n    \"\"\"Test entry function with inline\n\n    The call graph is like the following:\n                    main\n                      |\n                 g2(inline)\n                      |\n                     g1\n                      |\n                 g0(inline, external compiler)\n    \"\"\"\n\n    def get_mod():\n        mod = tvm.IRModule({})\n        x0 = relay.var(\"x0\", shape=(3, 5))\n        y0 = relay.var(\"y0\", shape=(3, 5))\n        fn0 = relay.Function([x0, y0], x0 * y0)\n        fn0 = fn0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn0 = fn0.with_attr(\"Compiler\", \"aa\")\n        g0 = relay.GlobalVar(\"g0\")\n        mod[g0] = fn0\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + g0(x1, y1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - g1(x2, y2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n        return mod\n\n    def expected():\n        mod = tvm.IRModule({})\n        x0 = relay.var(\"x0\", shape=(3, 5))\n        y0 = relay.var(\"y0\", shape=(3, 5))\n        fn0 = relay.Function([x0, y0], x0 * y0)\n        fn0 = fn0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        fn0 = fn0.with_attr(\"Compiler\", \"aa\")\n\n        x1 = relay.var(\"x1\", shape=(3, 5))\n        y1 = relay.var(\"y1\", shape=(3, 5))\n        fn1 = relay.Function([x1, y1], x1 + fn0(x1, y1))\n        g1 = relay.GlobalVar(\"g1\")\n        mod[g1] = fn1\n\n        x2 = relay.var(\"x2\", shape=(3, 5))\n        y2 = relay.var(\"y2\", shape=(3, 5))\n        fn2 = relay.Function([x2, y2], x2 - g1(x2, y2))\n        fn2 = fn2.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g2] = fn2\n\n        return mod\n\n    mod = get_mod()\n    mod = relay.transform.Inline()(mod)\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_instrument.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Instrument test cases.\n\"\"\"\nimport pytest\nimport tvm\nimport tvm.relay\nfrom tvm.relay import op\nfrom tvm.ir.instrument import PassTimingInstrument, pass_instrument\n\n\ndef get_test_model():\n    x, y, z = [tvm.relay.var(c, shape=(3, 4), dtype=\"float32\") for c in \"xyz\"]\n    e1 = op.add(x, y)\n    e2 = op.subtract(x, z)\n    e3 = op.multiply(e1, e1 / e2)\n    return tvm.IRModule.from_expr(e3 + e2)\n\n\ndef test_pass_timing_instrument():\n    pass_timing = PassTimingInstrument()\n\n    # Override current PassContext's instruments\n    tvm.transform.PassContext.current().override_instruments([pass_timing])\n\n    mod = get_test_model()\n    mod = tvm.relay.transform.AnnotateSpans()(mod)\n    mod = tvm.relay.transform.ToANormalForm()(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    profiles = pass_timing.render()\n    assert \"AnnotateSpans\" in profiles\n    assert \"ToANormalForm\" in profiles\n    assert \"InferType\" in profiles\n\n    # Reset current PassContext's instruments to None\n    tvm.transform.PassContext.current().override_instruments(None)\n\n    mod = get_test_model()\n    mod = tvm.relay.transform.AnnotateSpans()(mod)\n    mod = tvm.relay.transform.ToANormalForm()(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    profiles = pass_timing.render()\n    assert profiles == \"\"\n\n\ninstrument_definition_type = tvm.testing.parameter(\"decorator\", \"subclass\")\n\n\ndef test_custom_instrument(instrument_definition_type):\n    class BaseTest:\n        def __init__(self):\n            self.events = []\n\n        def enter_pass_ctx(self):\n            self.events.append(\"enter ctx\")\n\n        def exit_pass_ctx(self):\n            self.events.append(\"exit ctx\")\n\n        def run_before_pass(self, mod, info):\n            self.events.append(\"run before \" + info.name)\n\n        def run_after_pass(self, mod, info):\n            self.events.append(\"run after \" + info.name)\n\n    if instrument_definition_type == \"decorator\":\n        MyTest = pass_instrument(BaseTest)\n\n    elif instrument_definition_type == \"subclass\":\n\n        class MyTest(BaseTest, tvm.ir.instrument.PassInstrument):\n            def __init__(self):\n                BaseTest.__init__(self)\n                tvm.ir.instrument.PassInstrument.__init__(self)\n\n    mod = get_test_model()\n    my_test = MyTest()\n    with tvm.transform.PassContext(instruments=[my_test]):\n        mod = tvm.relay.transform.InferType()(mod)\n\n    assert (\n        \"enter ctx\"\n        \"run before InferType\"\n        \"run after InferType\"\n        \"exit ctx\" == \"\".join(my_test.events)\n    )\n\n\ndef test_disable_pass():\n    @pass_instrument\n    class CustomPI:\n        def __init__(self):\n            self.events = []\n\n        def should_run(self, mod, info):\n            # Only run pass name contains \"InferType\"\n            if \"InferType\" not in info.name:\n                return False\n            return True\n\n        def run_before_pass(self, mod, info):\n            self.events.append(info.name)\n\n    mod = get_test_model()\n    custom_pi = CustomPI()\n    with tvm.transform.PassContext(instruments=[custom_pi]):\n        mod = tvm.relay.transform.AnnotateSpans()(mod)\n        mod = tvm.relay.transform.ToANormalForm()(mod)\n        mod = tvm.relay.transform.InferType()(mod)\n\n    assert \"InferType\" == \"\".join(custom_pi.events)\n\n\ndef test_multiple_instrument():\n    @pass_instrument\n    class SkipPass:\n        def __init__(self, skip_pass_name):\n            self.skip_pass_name = skip_pass_name\n\n        def should_run(self, mod, info):\n            if self.skip_pass_name in info.name:\n                return False\n            return True\n\n    skip_annotate = SkipPass(\"AnnotateSpans\")\n    skip_anf = SkipPass(\"ToANormalForm\")\n\n    @pass_instrument\n    class PrintPassName:\n        def __init__(self):\n            self.events = []\n\n        def run_before_pass(self, mod, info):\n            self.events.append(info.name)\n\n    mod = get_test_model()\n    print_pass_name = PrintPassName()\n    with tvm.transform.PassContext(instruments=[skip_annotate, skip_anf, print_pass_name]):\n        mod = tvm.relay.transform.AnnotateSpans()(mod)\n        mod = tvm.relay.transform.ToANormalForm()(mod)\n        mod = tvm.relay.transform.InferType()(mod)\n\n    assert \"InferType\" == \"\".join(print_pass_name.events)\n\n\ndef test_instrument_pass_counts():\n    @pass_instrument\n    class PassesCounter:\n        def __init__(self):\n            self.run_before_count = 0\n            self.run_after_count = 0\n\n        def __clear(self):\n            self.run_before_count = 0\n            self.run_after_count = 0\n\n        def enter_pass_ctx(self):\n            self.__clear()\n\n        def exit_pass_ctx(self):\n            self.__clear()\n\n        def run_before_pass(self, mod, info):\n            self.run_before_count = self.run_before_count + 1\n\n        def run_after_pass(self, mod, info):\n            self.run_after_count = self.run_after_count + 1\n\n    mod = get_test_model()\n    passes_counter = PassesCounter()\n    with tvm.transform.PassContext(instruments=[passes_counter]):\n        tvm.relay.build(mod, \"llvm\")\n        assert passes_counter.run_after_count != 0\n        assert passes_counter.run_after_count == passes_counter.run_before_count\n\n    # Out of pass context scope, should be reset\n    assert passes_counter.run_before_count == 0\n    assert passes_counter.run_after_count == 0\n\n\ndef test_list_pass_configs():\n    configs = tvm.transform.PassContext.list_configs()\n\n    assert len(configs) > 0\n    assert \"relay.backend.use_auto_scheduler\" in configs.keys()\n    assert configs[\"relay.backend.use_auto_scheduler\"][\"type\"] == \"IntImm\"\n\n\ndef test_enter_pass_ctx_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit ctx\")\n\n    @pass_instrument\n    class PIBroken(PI):\n        def __init__(self, id):\n            super().__init__(id)\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter ctx\")\n            raise RuntimeError(\"Just a dummy error\")\n\n    pass_ctx = tvm.transform.PassContext(instruments=[PI(\"%1\"), PIBroken(\"%2\"), PI(\"%3\")])\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with pass_ctx:\n            pass\n        assert \"Just a dummy error\" in str(cm.execption)\n\n    assert \"%1 enter ctx\" \"%2 enter ctx\" \"%1 exit ctx\" == \"\".join(events)\n\n    # Make sure we get correct PassContext\n    cur_pass_ctx = tvm.transform.PassContext.current()\n    assert pass_ctx != cur_pass_ctx\n    assert not cur_pass_ctx.instruments\n\n\ndef test_enter_pass_ctx_exception_global():\n    @pass_instrument\n    class PIBroken:\n        def enter_pass_ctx(self):\n            raise RuntimeError(\"Just a dummy error\")\n\n    cur_pass_ctx = tvm.transform.PassContext.current()\n    with pytest.raises(tvm.error.TVMError) as cm:\n        cur_pass_ctx.override_instruments([PIBroken()])\n        assert \"Just a dummy error\" in str(cm.exception)\n    assert not cur_pass_ctx.instruments\n\n\ndef test_exit_pass_ctx_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit ctx\")\n\n    @pass_instrument\n    class PIBroken(PI):\n        def __init__(self, id):\n            super().__init__(id)\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit ctx\")\n            raise RuntimeError(\"Just a dummy error\")\n\n    pass_ctx = tvm.transform.PassContext(instruments=[PI(\"%1\"), PIBroken(\"%2\"), PI(\"%3\")])\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with pass_ctx:\n            pass\n        assert \"Just a dummy error\" in str(cm.exception)\n\n    assert \"%1 exit ctx\" \"%2 exit ctx\" == \"\".join(events)\n\n    # Make sure we get correct PassContext\n    cur_pass_ctx = tvm.transform.PassContext.current()\n    assert pass_ctx != cur_pass_ctx\n    assert not cur_pass_ctx.instruments\n\n\ndef test_exit_pass_ctx_exception_global():\n    @pass_instrument\n    class PIBroken:\n        def exit_pass_ctx(self):\n            raise RuntimeError(\"Just a dummy error\")\n\n    cur_pass_ctx = tvm.transform.PassContext.current()\n    with pytest.raises(tvm.error.TVMError) as cm:\n        cur_pass_ctx.override_instruments([PIBroken()])\n        cur_pass_ctx.override_instruments([PIBroken()])\n        assert \"Just a dummy error\" in str(cm.exception)\n    assert not cur_pass_ctx.instruments\n\n\ndef test_pass_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def enter_pass_ctx(self):\n            events.append(\"enter_pass_ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(\"exit_pass_ctx\")\n\n        def should_run(self, mod, info):\n            events.append(\"should_run\")\n            return True\n\n        def run_before_pass(self, mod, info):\n            events.append(\"run_before_pass\")\n\n        def run_after_pass(self, mod, info):\n            events.append(\"run_after_pass\")\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform(mod, ctx):\n        events.append(\"transform pass\")\n        raise RuntimeError(\"Just a dummy error\")\n        return mod\n\n    mod = get_test_model()\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with tvm.transform.PassContext(instruments=[PI()]):\n            mod = transform(mod)\n        assert \"Just a dummy error\" in str(cm.exception)\n\n    assert (\n        \"enter_pass_ctx\"\n        \"should_run\"\n        \"run_before_pass\"\n        \"transform pass\"\n        \"exit_pass_ctx\" == \"\".join(events)\n    )\n\n\ndef test_should_run_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter_pass_ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit_pass_ctx\")\n\n        def should_run(self, mod, info):\n            events.append(self.id + \" should_run\")\n            raise RuntimeError(\"Just a dummy error\")\n            return True\n\n        def run_before_pass(self, mod, info):\n            events.append(self.id + \" run_before_pass\")\n\n        def run_after_pass(self, mod, info):\n            events.append(self.id + \" run_after_pass\")\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform(mod, ctx):\n        events.append(\"transform pass\")\n        return mod\n\n    mod = get_test_model()\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with tvm.transform.PassContext(instruments=[PI(\"%1\"), PI(\"%2\")]):\n            mod = transform(mod)\n        assert \"Just a dummy error\" in str(cm.exception)\n\n    assert (\n        \"%1 enter_pass_ctx\"\n        \"%2 enter_pass_ctx\"\n        \"%1 should_run\"\n        \"%1 exit_pass_ctx\"\n        \"%2 exit_pass_ctx\" == \"\".join(events)\n    )\n\n\ndef test_run_before_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter_pass_ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit_pass_ctx\")\n\n        def should_run(self, mod, info):\n            events.append(self.id + \" should_run\")\n            return True\n\n        def run_before_pass(self, mod, info):\n            events.append(self.id + \" run_before_pass\")\n            raise RuntimeError(\"Just a dummy error\")\n\n        def run_after_pass(self, mod, info):\n            events.append(self.id + \" run_after_pass\")\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform(mod, ctx):\n        events.append(\"transform pass\")\n        return mod\n\n    mod = get_test_model()\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with tvm.transform.PassContext(instruments=[PI(\"%1\"), PI(\"%2\")]):\n            mod = transform(mod)\n        assert \"Just a dummy error\" in str(cm.exception)\n\n    assert (\n        \"%1 enter_pass_ctx\"\n        \"%2 enter_pass_ctx\"\n        \"%1 should_run\"\n        \"%2 should_run\"\n        \"%1 run_before_pass\"\n        \"%1 exit_pass_ctx\"\n        \"%2 exit_pass_ctx\" == \"\".join(events)\n    )\n\n\ndef test_run_after_exception():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter_pass_ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit_pass_ctx\")\n\n        def should_run(self, mod, info):\n            events.append(self.id + \" should_run\")\n            return True\n\n        def run_before_pass(self, mod, info):\n            events.append(self.id + \" run_before_pass\")\n\n        def run_after_pass(self, mod, info):\n            events.append(self.id + \" run_after_pass\")\n            raise RuntimeError(\"Just a dummy error\")\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform(mod, ctx):\n        events.append(\"transform pass\")\n        return mod\n\n    x, y = [tvm.relay.var(c, shape=(3, 4), dtype=\"float32\") for c in \"xy\"]\n    mod = tvm.IRModule.from_expr(tvm.relay.add(x, y))\n\n    with pytest.raises(tvm.error.TVMError) as cm:\n        with tvm.transform.PassContext(instruments=[PI(\"%1\"), PI(\"%2\")]):\n            mod = transform(mod)\n        assert \"Just a dummy error\" in str(cm.exception)\n\n    assert (\n        \"%1 enter_pass_ctx\"\n        \"%2 enter_pass_ctx\"\n        \"%1 should_run\"\n        \"%2 should_run\"\n        \"%1 run_before_pass\"\n        \"%2 run_before_pass\"\n        \"transform pass\"\n        \"%1 run_after_pass\"\n        \"%1 exit_pass_ctx\"\n        \"%2 exit_pass_ctx\" == \"\".join(events)\n    )\n\n\ndef test_instrument_call_sequence():\n    events = []\n\n    @pass_instrument\n    class PI:\n        def __init__(self, id):\n            self.id = id\n\n        def enter_pass_ctx(self):\n            events.append(self.id + \" enter_pass_ctx\")\n\n        def exit_pass_ctx(self):\n            events.append(self.id + \" exit_pass_ctx\")\n\n        def should_run(self, mod, info):\n            events.append(\"  \" + self.id + \" should_run\")\n            return True\n\n        def run_before_pass(self, mod, info):\n            events.append(\"  \" + self.id + \" run_before_pass\")\n\n        def run_after_pass(self, mod, info):\n            events.append(\"  \" + self.id + \" run_after_pass\")\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform1(mod, ctx):\n        events.append(\"    transform1 pass\")\n        return mod\n\n    @tvm.transform.module_pass(opt_level=2)\n    def transform2(mod, ctx):\n        events.append(\"    transform2 pass\")\n        return mod\n\n    mod = get_test_model()\n    with tvm.transform.PassContext(instruments=[PI(\"%1\"), PI(\"%2\")]):\n        mod = transform1(mod)\n        mod = transform2(mod)\n\n    assert (\n        \"%1 enter_pass_ctx\"\n        \"%2 enter_pass_ctx\"\n        \"  %1 should_run\"\n        \"  %2 should_run\"\n        \"  %1 run_before_pass\"\n        \"  %2 run_before_pass\"\n        \"    transform1 pass\"\n        \"  %1 run_after_pass\"\n        \"  %2 run_after_pass\"\n        \"  %1 should_run\"\n        \"  %2 should_run\"\n        \"  %1 run_before_pass\"\n        \"  %2 run_before_pass\"\n        \"    transform2 pass\"\n        \"  %1 run_after_pass\"\n        \"  %2 run_after_pass\"\n        \"%1 exit_pass_ctx\"\n        \"%2 exit_pass_ctx\" == \"\".join(events)\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_lambda_lift.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef test_basic():\n    mod = tvm.IRModule()\n    x2 = relay.var(\"x2\", shape=(10, 5))\n    y2 = relay.var(\"y2\", shape=(1, 5))\n    level2_func = relay.Function([x2, y2], relay.op.add(x2, y2))\n\n    x1 = relay.var(\"x1\", shape=(10, 5))\n    y1 = relay.var(\"y1\", shape=(1, 5))\n    level1_func = relay.Function([x1, y1], level2_func(x1, y1))\n\n    mod[\"main\"] = level1_func\n    mod = relay.transform.InferType()(mod)\n    new_mod = transform.LambdaLift()(mod)\n    assert len(new_mod.functions) == 2\n\n\ndef test_closure():\n    mod = tvm.IRModule()\n\n    x = relay.var(\"x\", shape=(2,))\n    y = relay.var(\"y\", shape=(2,))\n    inner_func = relay.Function([x], x + y)\n    outer_func = relay.Function([y], inner_func)\n    clo = outer_func(relay.ones(shape=(2,), dtype=\"float32\"))\n    mod[\"main\"] = relay.Function([], relay.Call(clo, [relay.zeros(shape=(2,), dtype=\"float32\")]))\n\n    mod = relay.transform.InferType()(mod)\n    new_mod = transform.LambdaLift()(mod)\n    assert len(new_mod.functions) == 3\n\n\ndef test_recursive():\n    mod = tvm.IRModule()\n\n    x = relay.var(\"x\", shape=(2,))\n    i = relay.var(\"i\", shape=(), dtype=\"int32\")\n    s = relay.var(\"s\", shape=(2,))\n    cond = i < relay.const(10, dtype=\"int32\")\n\n    loop = relay.var(\"while_loop\")\n    sb = relay.scope_builder.ScopeBuilder()\n    with sb.if_scope(cond):\n        ii = i + relay.const(1, dtype=\"int32\")\n        ss = s + x\n        sb.ret(loop(ii, ss))\n    with sb.else_scope():\n        sb.ret(s)\n    func = relay.Function([i, s], sb.get())\n\n    ret = relay.Let(\n        loop, func, loop(relay.const(0, dtype=\"int32\"), relay.zeros(shape=(2,), dtype=\"float32\"))\n    )\n    mod[\"main\"] = relay.Function([x], ret)\n\n    mod = relay.transform.InferType()(mod)\n    new_mod = transform.LambdaLift()(mod)\n    assert len(new_mod.functions) == 2\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_lazy_gradient_init.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import create_executor, transform\nfrom tvm.relay.testing import rand, run_infer_type\nimport tvm.testing\nfrom tvm.testing import assert_allclose\n\n\ndef test_tc():\n    \"\"\"Simple testcase, check that transformation typechecks.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (20, 20)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x1 = relay.var(\"x1\", t)\n    x2 = relay.var(\"x2\", t)\n    # f(x1,x2) = (x1-x2)*x2\n    y = relay.Function([x1, x2], (x1 - x2) * x2)\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n\n    # function input/output types should remain the same\n    assert mod[\"main\"].checked_type == relay.FuncType([t, t], t)\n\n\ndef test_add():\n    \"\"\"Simple add testcase. Check types and semantic equivalence.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    # f(x) = x+x\n    y = relay.Function([x], x + x)\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy() + x.numpy())\n\n\ndef test_add_tuple():\n    \"\"\"Add elements of tuple. Check types and semantic equivalence.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    tensor_type = relay.TensorType(shape, dtype)\n    t = relay.TupleType([tensor_type, tensor_type])\n\n    x = relay.var(\"x\", t)\n    # f((x1,x2)) = x1 + x2\n    y = relay.Function([x], relay.TupleGetItem(x, 0) + relay.TupleGetItem(x, 1))\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    mod = tvm.transform.PrintIR(show_meta_data=True)(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], tensor_type)\n\n    x = (rand(dtype, *shape), rand(dtype, *shape))\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x[0].numpy() + x[1].numpy())\n\n\ndef test_mult():\n    \"\"\"Simple multiplication testcase. Check types and semantic equivalence.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (15, 15)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    # f(x) = x*x\n    y = relay.Function([x], x * x)\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy() * x.numpy())\n\n\ndef test_ret_tuple():\n    \"\"\"Test tuple return type. Check types and semantic equivalence.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    # f(x) = (x,x)\n    func = relay.Function([x], relay.Tuple([x, x * relay.const(2.0)]))\n    func = run_infer_type(func)\n\n    mod[\"main\"] = func\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    func = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], relay.TupleType([t, t]))\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(func)(x)\n    assert_allclose(y[0].numpy(), x.numpy())\n    assert_allclose(y[1].numpy(), x.numpy() * 2.0)\n\n\ndef test_add_broadcast():\n    \"\"\"Test adding matrices of different size. Check types and semantic equivalence.\"\"\"\n    mod = tvm.IRModule()\n\n    shape1 = (3, 4, 1)\n    shape2 = (1, 5)\n    dtype = \"float32\"\n    t1 = relay.TensorType(shape1, dtype)\n    t2 = relay.TensorType(shape2, dtype)\n\n    x1 = relay.var(\"x1\", t1)\n    x2 = relay.var(\"x2\", t2)\n    func = relay.Function([x1, x2], x1 + x2)\n    func = run_infer_type(func)\n\n    mod[\"main\"] = func\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    func = mod[\"main\"]\n\n    x1_np = rand(dtype, *shape1).numpy()\n    x2_np = rand(dtype, *shape2).numpy()\n    expected_forward = x1_np + x2_np\n\n    expected_forward_type = relay.TensorType(expected_forward.shape, dtype)\n    assert mod[\"main\"].checked_type == relay.FuncType([t1, t2], expected_forward_type)\n\n    forward = create_executor(mod=mod).evaluate(func)(x1_np, x2_np)\n\n    assert_allclose(forward.numpy(), expected_forward)\n\n\ndef test_reverse_ad_identity():\n    \"\"\"Simple test with reverse mode ad.\"\"\"\n    # of f(x) = x\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n\n    func = relay.Function([x], x)\n    func = run_infer_type(func)\n    back_func = transform.gradient(func)\n    back_func = run_infer_type(back_func)\n\n    mod[\"main\"] = back_func\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    back_func = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType(\n        [t], relay.TupleType([t, relay.TupleType([t])])\n    )\n\n    x = rand(dtype, *shape)\n    (forward), (grad,) = create_executor(mod=mod).evaluate(back_func)(x)\n    assert_allclose(forward.numpy(), x.numpy())\n    assert_allclose(grad.numpy(), np.ones_like(x.numpy()))\n\n\ndef test_multivar_reverse_ad():\n    \"\"\"Simple test with multivariate reverse mode ad.\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.var(\"y\", t)\n\n    func = relay.Function([x, y], (x * y) * relay.const(np.ones(shape, dtype)))\n    func = run_infer_type(func)\n    back_func = transform.gradient(func)\n    back_func = run_infer_type(back_func)\n\n    mod[\"main\"] = back_func\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    back_func = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType(\n        [t, t], relay.TupleType([t, relay.TupleType([t, t])])\n    )\n\n    x = rand(dtype, *shape)\n    y = rand(dtype, *shape)\n    (forward), (grad_x, grad_y,) = create_executor(mod=mod).evaluate(\n        back_func\n    )(x, y)\n    assert_allclose(forward.numpy(), x.numpy() * y.numpy())\n    assert_allclose(grad_x.numpy(), y.numpy())\n    assert_allclose(grad_y.numpy(), x.numpy())\n\n\ndef test_partial_eval():\n    \"\"\"Test transformation following reverse mode ad and PartialEval\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    func = relay.Function([], relay.const(np.ones(shape, dtype)))\n    func = run_infer_type(func)\n    back_func = transform.gradient(func)\n    back_func = run_infer_type(back_func)\n\n    mod[\"main\"] = back_func\n    mod = transform.InferType()(mod)\n    back_func = mod[\"main\"]\n\n    transform.PartialEvaluate()(mod)\n\n\ndef test_after_partial_eval():\n    \"\"\"Test transformation following reverse mode ad and PartialEval\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.var(\"y\", t)\n\n    func = relay.Function([x, y], (x * y) * relay.const(np.ones(shape, dtype)))\n    func = run_infer_type(func)\n    back_func = transform.gradient(func)\n    back_func = run_infer_type(back_func)\n\n    mod[\"main\"] = back_func\n    back_func = mod[\"main\"]\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.PartialEvaluate(),\n            transform.InferType(),\n            transform.LazyGradientInit(),\n            transform.InferType(),\n            transform.DeadCodeElimination(),\n            transform.InferType(),\n        ]\n    )\n\n    mod = seq(mod)\n\n    assert mod[\"main\"].checked_type == relay.FuncType(\n        [t, t], relay.TupleType([t, relay.TupleType([t, t])])\n    )\n\n    x = rand(dtype, *shape)\n    y = rand(dtype, *shape)\n    (forward), (grad_x, grad_y,) = create_executor(mod=mod).evaluate(\n        back_func\n    )(x, y)\n    assert_allclose(forward.numpy(), x.numpy() * y.numpy())\n    assert_allclose(grad_x.numpy(), y.numpy())\n    assert_allclose(grad_y.numpy(), x.numpy())\n\n\ndef test_before_partial_eval():\n    \"\"\"Test transformation before PartialEval\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.var(\"y\", t)\n\n    func = relay.Function([x, y], x * y)\n    func = run_infer_type(func)\n    back_func = transform.gradient(func)\n    back_func = run_infer_type(back_func)\n\n    mod[\"main\"] = back_func\n    seq = tvm.transform.Sequential(\n        [\n            transform.LazyGradientInit(),\n            transform.PartialEvaluate(),\n            transform.InferType(),\n            transform.DeadCodeElimination(),\n            transform.InferType(),\n        ]\n    )\n    mod = seq(mod)\n    back_func = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType(\n        [t, t], relay.TupleType([t, relay.TupleType([t, t])])\n    )\n\n    x = rand(dtype, *shape)\n    y = rand(dtype, *shape)\n    (forward), (grad_x, grad_y,) = create_executor(mod=mod).evaluate(\n        back_func\n    )(x, y)\n    assert_allclose(forward.numpy(), x.numpy() * y.numpy())\n    assert_allclose(grad_x.numpy(), y.numpy())\n    assert_allclose(grad_y.numpy(), x.numpy())\n\n\ndef test_zeros():\n    \"\"\"Simple test using \"zeros\" op\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.Function([x], x + relay.zeros(shape, dtype))\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy())\n\n\ndef test_ones():\n    \"\"\"Simple test using \"ones\" op\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.Function([x], x + relay.ones(shape, dtype))\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy() + np.ones_like(x.numpy()))\n\n\ndef test_zeros_like():\n    \"\"\"Simple test using \"zeros_like\" op\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.Function([x], x + relay.zeros_like(x))\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy())\n\n\ndef test_ones_like():\n    \"\"\"Simple test using \"ones_like\" op\"\"\"\n    mod = tvm.IRModule()\n\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n\n    x = relay.var(\"x\", t)\n    y = relay.Function([x], x + relay.ones_like(x))\n\n    mod[\"main\"] = y\n    mod = transform.InferType()(mod)\n    mod = transform.LazyGradientInit()(mod)\n    y = mod[\"main\"]\n\n    assert mod[\"main\"].checked_type == relay.FuncType([t], t)\n\n    x = rand(dtype, *shape)\n    y = create_executor(mod=mod).evaluate(y)(x)\n    assert_allclose(y.numpy(), x.numpy() + np.ones_like(x.numpy()))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_legalize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test legalize pass\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\n\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay import transform, analysis\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_legalize():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def legalize_conv2d(attrs, inputs, types):\n        data, weight = inputs\n        weight = relay.multiply(weight, relay.const(2.0, \"float32\"))\n        return relay.nn.conv2d(data, weight, **attrs)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            relay.multiply(weight, relay.const(2.0, \"float32\")),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", legalize_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.Legalize())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_legalize_none():\n    \"\"\"Test doing nothing by returning 'None'\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        y = relay.nn.global_max_pool2d(x)\n        y = relay.Function([x], y)\n        return y\n\n    called = [False]\n\n    def legalize_conv2d(attrs, inputs, types):\n        called[0] = True\n        return None\n\n    with TempOpAttr(\"nn.global_max_pool2d\", \"FTVMLegalize\", legalize_conv2d):\n        a = before()\n        a = run_opt_pass(a, transform.Legalize())\n        b = run_opt_pass(before(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n    assert called[0]\n\n\ndef test_legalize_multiple_ops():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(x, weight, channels=64, kernel_size=(3, 3), padding=(1, 1))\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    def legalize_conv2d(attrs, inputs, types):\n        data, weight = inputs\n        weight = relay.multiply(weight, relay.const(2.0, \"float32\"))\n        return relay.nn.conv2d(data, weight, **attrs)\n\n    def legalize_relu(attrs, inputs, types):\n        data = inputs[0]\n        add = relay.add(tvm.relay.const(0, \"float32\"), data)\n        return relay.nn.relu(add)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        weight = relay.var(\"weight\", shape=(64, 64, 3, 3))\n        y = relay.nn.conv2d(\n            x,\n            relay.multiply(weight, relay.const(2.0, \"float32\")),\n            channels=64,\n            kernel_size=(3, 3),\n            padding=(1, 1),\n        )\n        y = relay.add(tvm.relay.const(0, \"float32\"), y)\n        y = relay.nn.relu(y)\n        y = relay.Function([x, weight], y)\n        return y\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", legalize_conv2d):\n        with TempOpAttr(\"nn.relu\", \"FTVMLegalize\", legalize_relu):\n            a = before()\n            a = run_opt_pass(a, transform.Legalize())\n            b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_legalize_multi_input():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        y = relay.var(\"y\", shape=(1, 64, 56, 20))\n        z = relay.var(\"z\", shape=(1, 64, 56, 10))\n        func = relay.concatenate([x, y, z], axis=3)\n        func = relay.Function([x, y, z], func)\n        return func\n\n    def legalize_concatenate(attrs, inputs, types):\n        # Check that the correct multi-input case is handled.\n        assert len(inputs) == 1\n        assert isinstance(inputs[0], tvm.relay.expr.Tuple)\n        assert len(types) == 2\n        assert isinstance(types[0], tvm.relay.ty.TupleType)\n        assert isinstance(types[1], tvm.relay.ty.TensorType)\n        return None\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56))\n        y = relay.var(\"y\", shape=(1, 64, 56, 20))\n        z = relay.var(\"z\", shape=(1, 64, 56, 10))\n        func = relay.concatenate([x, y, z], axis=3)\n        func = relay.Function([x, y, z], func)\n        return func\n\n    with TempOpAttr(\"concatenate\", \"FTVMLegalize\", legalize_concatenate):\n        a = before()\n        a = run_opt_pass(a, transform.Legalize())\n        b = run_opt_pass(expected(), transform.InferType())\n\n    assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\nif __name__ == \"__main__\":\n    test_legalize()\n    test_legalize_none()\n    test_legalize_multiple_ops()\n    test_legalize_multi_input()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_legalize_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test legalize pass\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay import transform, analysis\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\n@tvm.testing.uses_gpu\ndef test_legalize_conv2d_NHWC():\n    \"\"\"test legalize NHWC conv2d to enable tensorcore\"\"\"\n\n    def _test_legalize_conv2d(data_shape, kernel_shape, pad_shape, dtype, do_pad=True):\n        out_channel = kernel_shape[3]\n        out_shape = list(data_shape)\n        out_shape[3] = out_channel\n        db, di, do = pad_shape\n\n        def before():\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            weight = relay.var(\"weight\", shape=kernel_shape, dtype=dtype)\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=out_channel,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            y = relay.Function([x, weight], y)\n            return y\n\n        def legalize_conv2d(attrs, inputs, types):\n            with tvm.target.Target(\"cuda\"):\n                return topi.nn.conv2d_legalize(attrs, inputs, types)\n\n        def expected():\n            if not do_pad:\n                return before()\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            if db or di:\n                x_pad = relay.nn.pad(x, pad_width=((0, db), (0, 0), (0, 0), (0, di)))\n            else:\n                x_pad = x\n            weight = relay.var(\"weight\", shape=(kernel_shape), dtype=dtype)\n            if di or do:\n                weight_pad = relay.nn.pad(weight, pad_width=((0, 0), (0, 0), (0, di), (0, do)))\n            else:\n                weight_pad = weight\n            y_pad = relay.nn.conv2d(\n                x_pad,\n                weight=weight_pad,\n                channels=out_channel + do,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"NHWC\",\n                kernel_layout=\"HWIO\",\n            )\n            if db or do:\n                y = relay.strided_slice(y_pad, begin=[0, 0, 0, 0], end=out_shape)\n            else:\n                y = y_pad\n            y = relay.Function([x, weight], y)\n            return y\n\n        with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", legalize_conv2d):\n            a = before()\n            a = run_opt_pass(a, transform.Legalize())\n            b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"Expected = \\n\" + str(b)\n\n    for dtype in [\"float16\", \"int8\", \"int4\"]:\n        # conv2d pad batch\n        _test_legalize_conv2d((7, 16, 16, 64), (3, 3, 64, 64), (1, 0, 0), dtype)\n        _test_legalize_conv2d((3, 16, 16, 64), (3, 3, 64, 64), (5, 0, 0), dtype)\n        _test_legalize_conv2d((2, 16, 16, 64), (3, 3, 64, 64), (0, 0, 0), dtype, False)\n        # conv2d pad in_channel\n        _test_legalize_conv2d((8, 16, 16, 63), (3, 3, 63, 64), (0, 1, 0), dtype)\n        _test_legalize_conv2d((8, 16, 16, 33), (3, 3, 33, 64), (0, 15, 0), dtype)\n        _test_legalize_conv2d((8, 16, 16, 13), (3, 3, 13, 64), (0, 3, 0), dtype)\n        _test_legalize_conv2d((8, 16, 16, 1), (3, 3, 1, 64), (0, 0, 0), dtype, False)\n        # conv2d pad out_channel\n        _test_legalize_conv2d((8, 16, 16, 64), (3, 3, 64, 63), (0, 0, 1), dtype)\n        _test_legalize_conv2d((8, 16, 16, 64), (3, 3, 64, 33), (0, 0, 31), dtype)\n        _test_legalize_conv2d((8, 16, 16, 64), (3, 3, 64, 1), (0, 0, 0), dtype, False)\n\n\n@tvm.testing.uses_gpu\ndef test_legalize_conv2d_HWNC():\n    \"\"\"test legalize HWNC conv2d to enable tensorcore\"\"\"\n\n    def _test_legalize_conv2d(data_shape, kernel_shape, pad_shape, dtype, do_pad=True):\n        out_channel = kernel_shape[2]\n        out_shape = list(data_shape)\n        out_shape[3] = out_channel\n        db, di, do = pad_shape\n\n        def before():\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            weight = relay.var(\"weight\", shape=kernel_shape, dtype=dtype)\n            y = relay.nn.conv2d(\n                x,\n                weight,\n                channels=out_channel,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"HWNC\",\n                kernel_layout=\"HWOI\",\n            )\n            y = relay.Function([x, weight], y)\n            return y\n\n        def legalize_conv2d(attrs, inputs, types):\n            with tvm.target.Target(\"cuda\"):\n                return topi.nn.conv2d_legalize(attrs, inputs, types)\n\n        def expected():\n            if not do_pad:\n                return before()\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            if db or di:\n                x_pad = relay.nn.pad(x, pad_width=((0, 0), (0, 0), (0, db), (0, di)))\n            else:\n                x_pad = x\n            weight = relay.var(\"weight\", shape=(kernel_shape), dtype=dtype)\n            if di or do:\n                weight_pad = relay.nn.pad(weight, pad_width=((0, 0), (0, 0), (0, do), (0, di)))\n            else:\n                weight_pad = weight\n            y_pad = relay.nn.conv2d(\n                x_pad,\n                weight=weight_pad,\n                channels=out_channel + do,\n                kernel_size=(3, 3),\n                padding=(1, 1),\n                data_layout=\"HWNC\",\n                kernel_layout=\"HWOI\",\n            )\n            if db or do:\n                y = relay.strided_slice(y_pad, begin=[0, 0, 0, 0], end=out_shape)\n            else:\n                y = y_pad\n            y = relay.Function([x, weight], y)\n            return y\n\n        with TempOpAttr(\"nn.conv2d\", \"FTVMLegalize\", legalize_conv2d):\n            a = before()\n            a = run_opt_pass(a, transform.Legalize())\n            b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"Expected = \\n\" + str(b)\n\n    # conv2d pad batch\n    _test_legalize_conv2d((16, 16, 7, 64), (3, 3, 64, 64), (1, 0, 0), \"int8\")\n    _test_legalize_conv2d((16, 16, 3, 64), (3, 3, 64, 64), (5, 0, 0), \"int8\")\n    _test_legalize_conv2d((2, 16, 16, 64), (3, 3, 64, 64), (0, 0, 0), \"int8\", False)\n    _test_legalize_conv2d((16, 16, 7, 64), (3, 3, 64, 64), (1, 0, 0), \"int4\")\n    _test_legalize_conv2d((16, 16, 3, 64), (3, 3, 64, 64), (5, 0, 0), \"int4\")\n    _test_legalize_conv2d((2, 16, 16, 64), (3, 3, 64, 64), (0, 0, 0), \"int4\", False)\n    # conv2d pad in_channel\n    _test_legalize_conv2d((16, 16, 8, 63), (3, 3, 64, 63), (0, 1, 0), \"int8\")\n    _test_legalize_conv2d((16, 16, 8, 33), (3, 3, 64, 33), (0, 15, 0), \"int8\")\n    _test_legalize_conv2d((16, 16, 8, 13), (3, 3, 64, 13), (0, 3, 0), \"int8\")\n    _test_legalize_conv2d((16, 16, 8, 1), (3, 3, 64, 1), (0, 0, 0), \"int8\", False)\n    _test_legalize_conv2d((16, 16, 8, 63), (3, 3, 64, 63), (0, 1, 0), \"int4\")\n    _test_legalize_conv2d((16, 16, 8, 33), (3, 3, 64, 33), (0, 31, 0), \"int4\")\n    _test_legalize_conv2d((16, 16, 8, 13), (3, 3, 64, 13), (0, 19, 0), \"int4\")\n    _test_legalize_conv2d((16, 16, 8, 1), (3, 3, 64, 1), (0, 0, 0), \"int4\", False)\n    # conv2d pad out_channel\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 63, 64), (0, 0, 1), \"int8\")\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 33, 64), (0, 0, 31), \"int8\")\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 1, 64), (0, 0, 0), \"int8\", False)\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 63, 64), (0, 0, 1), \"int4\")\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 33, 64), (0, 0, 7), \"int4\")\n    _test_legalize_conv2d((16, 16, 8, 64), (3, 3, 1, 64), (0, 0, 0), \"int4\", False)\n\n\n@tvm.testing.uses_gpu\ndef test_legalize_dense():\n    def _test_legalize_dense(data_shape, kernel_shape, pad_shape, dtype, do_pad=True, units=None):\n        \"\"\"test legalize dense to enable tensorcore\"\"\"\n        M, K = data_shape\n        N, _ = kernel_shape\n        out_shape = (M, N)\n        dm, dk, dn = pad_shape\n\n        def before():\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            weight = relay.var(\"weight\", shape=kernel_shape, dtype=dtype)\n            y = relay.nn.dense(x, weight, units)\n            y = relay.Function([x, weight], y)\n            return y\n\n        def legalize_dense(attrs, inputs, types):\n            with tvm.target.Target(\"cuda\"):\n                return topi.nn.dense_legalize(attrs, inputs, types)\n\n        def expected():\n            if not do_pad:\n                return before()\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            if dm or dk:\n                x_pad = relay.nn.pad(x, pad_width=((0, dm), (0, dk)))\n            else:\n                x_pad = x\n            weight = relay.var(\"weight\", shape=(kernel_shape), dtype=dtype)\n            if dn or dk:\n                weight_pad = relay.nn.pad(weight, pad_width=((0, dn), (0, dk)))\n            else:\n                weight_pad = weight\n            y_pad = relay.nn.dense(x_pad, weight_pad, units=N + dn if units else None)\n            if dm or dn:\n                y = relay.strided_slice(y_pad, begin=[0, 0], end=out_shape)\n            else:\n                y = y_pad\n            y = relay.Function([x, weight], y)\n            return y\n\n        with TempOpAttr(\"nn.dense\", \"FTVMLegalize\", legalize_dense):\n            a = before()\n            a = run_opt_pass(a, transform.Legalize())\n            b = run_opt_pass(expected(), transform.InferType())\n\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"Expected = \\n\" + str(b)\n\n    # dense\n    for dtype in [\"float16\", \"int8\"]:\n        _test_legalize_dense((8, 16), (32, 16), (0, 0, 0), dtype, False)\n        _test_legalize_dense((7, 16), (32, 16), (1, 0, 0), dtype)\n        _test_legalize_dense((8, 15), (32, 15), (0, 1, 0), dtype)\n        _test_legalize_dense((8, 16), (31, 16), (0, 0, 1), dtype)\n        _test_legalize_dense((7, 15), (31, 15), (1, 1, 1), dtype)\n        _test_legalize_dense((3, 16), (32, 16), (5, 0, 0), dtype)\n        _test_legalize_dense((1, 16), (32, 16), (0, 0, 0), dtype, False)\n\n    # Test if units parameter is correctly updated\n    _test_legalize_dense((8, 16), (30, 16), (0, 0, 2), \"float16\", units=30)\n\n    _test_legalize_dense((8, 32), (32, 32), (0, 0, 0), \"int4\", False)\n    _test_legalize_dense((7, 32), (32, 32), (1, 0, 0), \"int4\")\n    _test_legalize_dense((8, 31), (32, 31), (0, 1, 0), \"int4\")\n    _test_legalize_dense((8, 32), (31, 32), (0, 0, 1), \"int4\")\n    _test_legalize_dense((7, 31), (31, 31), (1, 1, 1), \"int4\")\n    _test_legalize_dense((3, 32), (32, 32), (5, 0, 0), \"int4\")\n    _test_legalize_dense((8, 16), (32, 16), (0, 16, 0), \"int4\")\n    _test_legalize_dense((2, 16), (32, 16), (0, 0, 0), \"int4\", False)\n\n\n@tvm.testing.uses_gpu\ndef test_legalize_batch_matmul():\n    def _test_legalize_batch_matmul(data_shape, kernel_shape, pad_shape, dtype, do_pad=True):\n        \"\"\"test legalize dense to enable tensorcore\"\"\"\n        B, M, _ = data_shape\n        _, N, _ = kernel_shape\n        out_shape = (B, M, N)\n        dm, dk, dn = pad_shape\n\n        def before():\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            weight = relay.var(\"weight\", shape=kernel_shape, dtype=dtype)\n            y = relay.nn.batch_matmul(x, weight)\n            y = relay.Function([x, weight], y)\n            return y\n\n        def legalize_batch_matmul(attrs, inputs, types):\n            with tvm.target.Target(\"cuda\"):\n                return topi.nn.batch_matmul_legalize(attrs, inputs, types)\n\n        def expected():\n            if not do_pad:\n                return before()\n            x = relay.var(\"x\", shape=data_shape, dtype=dtype)\n            if dm or dk:\n                x_pad = relay.nn.pad(x, pad_width=((0, 0), (0, dm), (0, dk)))\n            else:\n                x_pad = x\n            weight = relay.var(\"weight\", shape=(kernel_shape), dtype=dtype)\n            if dn or dk:\n                weight_pad = relay.nn.pad(weight, pad_width=((0, 0), (0, dn), (0, dk)))\n            else:\n                weight_pad = weight\n            y_pad = relay.nn.batch_matmul(\n                x_pad,\n                weight_pad,\n            )\n            if dm or dn:\n                y = relay.strided_slice(y_pad, begin=[0, 0, 0], end=out_shape)\n            else:\n                y = y_pad\n            y = relay.Function([x, weight], y)\n            return y\n\n        with TempOpAttr(\"nn.batch_matmul\", \"FTVMLegalize\", legalize_batch_matmul):\n            a = before()\n            a = run_opt_pass(a, transform.Legalize())\n            b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a) + \"Expected = \\n\" + str(b)\n\n    for dtype in [\"float16\", \"int8\"]:\n        _test_legalize_batch_matmul((16, 8, 16), (16, 32, 16), (0, 0, 0), dtype, False)\n        _test_legalize_batch_matmul((16, 7, 16), (16, 32, 16), (1, 0, 0), dtype)\n        _test_legalize_batch_matmul((16, 8, 15), (16, 32, 15), (0, 1, 0), dtype)\n        _test_legalize_batch_matmul((16, 8, 16), (16, 31, 16), (0, 0, 1), dtype)\n        _test_legalize_batch_matmul((16, 7, 15), (16, 31, 15), (1, 1, 1), dtype)\n        _test_legalize_batch_matmul((16, 3, 16), (16, 32, 16), (5, 0, 0), dtype)\n        _test_legalize_batch_matmul((16, 2, 16), (16, 32, 16), (0, 0, 0), dtype, False)\n\n    _test_legalize_batch_matmul((16, 8, 32), (16, 32, 32), (0, 0, 0), \"int4\", False)\n    _test_legalize_batch_matmul((16, 7, 32), (16, 32, 32), (1, 0, 0), \"int4\")\n    _test_legalize_batch_matmul((16, 8, 31), (16, 32, 31), (0, 1, 0), \"int4\")\n    _test_legalize_batch_matmul((16, 8, 32), (16, 31, 32), (0, 0, 1), \"int4\")\n    _test_legalize_batch_matmul((16, 7, 31), (16, 31, 31), (1, 1, 1), \"int4\")\n    _test_legalize_batch_matmul((16, 3, 32), (16, 32, 32), (5, 0, 0), \"int4\")\n    _test_legalize_batch_matmul((16, 8, 16), (16, 32, 16), (0, 16, 0), \"int4\")\n    _test_legalize_batch_matmul((16, 2, 16), (16, 32, 16), (0, 0, 0), \"int4\", False)\n\n\nif __name__ == \"__main__\":\n    test_legalize_conv2d_NHWC()\n    test_legalize_conv2d_HWNC()\n    test_legalize_dense()\n    test_legalize_batch_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_mac_count.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for MAC counter.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import analysis, transform\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = tvm.relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_gemm():\n    n = 512\n    k = 1024\n    m = 256\n    dshape1 = (n, k)\n    dshape2 = (m, k)\n    data1 = relay.var(\"data1\", shape=dshape1)\n    data2 = relay.var(\"data2\", shape=dshape2)\n    gemm = relay.nn.dense(data1, data2)\n    func = relay.Function([data1, data2], relay.Tuple(tvm.runtime.convert([gemm])))\n    func = run_opt_pass(func, transform.InferType())\n    compute_count = analysis.get_total_mac_number(func)\n    expect_count = n * m * k\n    assert compute_count == expect_count\n\n\ndef test_conv():\n    batch_size = 1\n    input_channel = 3\n    h = 224\n    w = 224\n    output_channel = 64\n    kh = 7\n    kw = 7\n    h_padding = 1\n    w_padding = 1\n    oh = h + h_padding * 2 - kh + 1\n    ow = w + w_padding * 2 - kw + 1\n    dshape = (batch_size, input_channel, h, w)\n    weight = relay.var(\"weight\", shape=(output_channel, input_channel, kh, kw))\n    data = relay.var(\"data\", shape=dshape)\n    conv2d = relay.nn.conv2d(\n        data, weight, channels=output_channel, kernel_size=(kh, kw), padding=(h_padding, w_padding)\n    )\n    func = relay.Function([data, weight], relay.Tuple(tvm.runtime.convert([conv2d])))\n    func = run_opt_pass(func, transform.InferType())\n    compute_count = analysis.get_total_mac_number(func)\n    expect_count = batch_size * input_channel * oh * ow * output_channel * kh * kw\n    assert compute_count == expect_count\n\n\ndef test_simple_network():\n    batch_size = 1\n    dshape = (batch_size, 64, 56, 56)\n    weight_conv = relay.var(\"weight_conv\", shape=(64, 64, 3, 3))\n    data1 = relay.var(\"data1\", shape=dshape)\n    data2 = relay.var(\"data2\", shape=dshape)\n    weight_dense = relay.var(\"weight_dense\", shape=(1, 56 * 56 * 64))\n\n    conv2d_1 = relay.nn.conv2d(data1, weight_conv, channels=64, kernel_size=(3, 3), padding=(1, 1))\n    conv2d_2 = relay.nn.conv2d(data2, weight_conv, channels=64, kernel_size=(3, 3), padding=(1, 1))\n    add = relay.add(conv2d_1, conv2d_2)\n    flattened = relay.nn.batch_flatten(add)\n    dense_1 = relay.nn.dense(flattened, weight_dense)\n\n    func = relay.Function(\n        [data1, data2, weight_conv, weight_dense],\n        relay.Tuple(tvm.runtime.convert([conv2d_1, conv2d_2, dense_1, add, flattened])),\n    )\n    # alter the CONV 2D data layout to test\n    func = run_opt_pass(func, transform.AlterOpLayout())\n    compute_count = analysis.get_total_mac_number(func)\n    expect_count = 231411712\n    assert compute_count == expect_count\n\n\ndef test_depthwise_conv2d():\n    batch_size = 1\n    dshape = (batch_size, 64, 56, 56)\n    weight_conv = relay.var(\"weight_depthwiseconv\", shape=(64, 1, 3, 3))\n    data1 = relay.var(\"data1\", shape=dshape)\n    data2 = relay.var(\"data2\", shape=dshape)\n    depthwise_conv2d_1 = relay.nn.conv2d(\n        data1, weight_conv, kernel_size=(3, 3), padding=(1, 1), groups=64\n    )\n    depthwise_conv2d_2 = relay.nn.conv2d(\n        data2, weight_conv, kernel_size=(3, 3), padding=(1, 1), groups=64\n    )\n    add = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n    func = relay.Function(\n        [data1, data2, weight_conv],\n        relay.Tuple(tvm.runtime.convert([depthwise_conv2d_1, depthwise_conv2d_2, add])),\n    )\n    func = run_opt_pass(func, transform.InferType())\n    compute_count = analysis.get_total_mac_number(func)\n    assert compute_count == 2 * np.prod(dshape) * 3 * 3\n\n\ndef test_conv_2d_transpose():\n    batch_size = 1\n    input_channel = 3\n    h = 224\n    w = 224\n    output_channel = 64\n    kh = 7\n    kw = 7\n    h_padding = 1\n    w_padding = 1\n    oh = h - h_padding * 2 + kh - 1\n    ow = w - w_padding * 2 + kw - 1\n    dshape = (batch_size, input_channel, h, w)\n    weight = relay.var(\"weight\", shape=(input_channel, output_channel, kh, kw))\n    data = relay.var(\"data\", shape=dshape)\n    conv2d_transpose = relay.nn.conv2d_transpose(\n        data, weight, channels=output_channel, kernel_size=(kh, kw), padding=(h_padding, w_padding)\n    )\n    func = relay.Function([data, weight], relay.Tuple(tvm.runtime.convert([conv2d_transpose])))\n    func = run_opt_pass(func, transform.InferType())\n    compute_count = analysis.get_total_mac_number(func)\n    expect_count = batch_size * input_channel * oh * ow * output_channel * kh * kw\n    assert compute_count == expect_count\n\n\nif __name__ == \"__main__\":\n    test_conv()\n    test_gemm()\n    test_simple_network()\n    test_depthwise_conv2d()\n    test_conv_2d_transpose()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_manager.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for relay pass manager.\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import ExprFunctor\nfrom tvm.relay import Function, Call\nfrom tvm.relay import analysis\nfrom tvm.relay import transform as _transform\nfrom tvm.ir import instrument as _instrument\nfrom tvm.relay.testing import run_infer_type\nimport tvm.testing\n\n\ndef get_var_func():\n    shape = (5, 10)\n    tp = relay.TensorType(shape, \"float32\")\n    x = relay.var(\"x\", tp)\n    gv = relay.GlobalVar(\"myAbs\")\n    func = relay.Function([x], relay.abs(x))\n    return gv, func\n\n\ndef extract_var_func(mod, name):\n    var = mod.get_global_var(name)\n    func = mod[var]\n    return var, func\n\n\ndef update_func(func):\n    # Double the value of Constants and vars.\n    class DoubleValues(ExprFunctor):\n        def __init__(self):\n            ExprFunctor.__init__(self)\n\n        def visit_constant(self, const):\n            return relay.add(const, const)\n\n        def visit_var(self, var):\n            return relay.add(var, var)\n\n        def visit_call(self, call):\n            new_op = self.visit(call.op)\n            new_args = [self.visit(arg) for arg in call.args]\n            return Call(new_op, new_args, call.attrs)\n\n        def visit_global_var(self, gvar):\n            return gvar\n\n        def visit_op(self, op):\n            return op\n\n        def visit_function(self, fn):\n            new_body = self.visit(fn.body)\n            return Function(list(fn.params), new_body, fn.ret_type, fn.type_params, fn.attrs)\n\n    double_value = DoubleValues()\n    return double_value.visit(func)\n\n\nclass OptTester:\n    \"\"\"A helper class for testing the pass manager.\"\"\"\n\n    def __init__(self, mod):\n        if not isinstance(mod, tvm.IRModule):\n            raise TypeError(\"mod is expected to be the type of \" \"tvm.IRModule\")\n        self.mod = mod\n\n    def analysis(self):\n        \"\"\"Perform analysis for the current module.\"\"\"\n        pass\n\n    @staticmethod\n    def transform(node, ctx=None):\n        \"\"\"Perform optimization on node.\"\"\"\n        if isinstance(node, tvm.IRModule):\n            # Add a function to the module and return an updated module.\n            gv, func = get_var_func()\n            mod = tvm.IRModule({gv: func})\n            mod.update(node)\n            return mod\n        if isinstance(node, relay.Function):\n            return update_func(node)\n\n        raise TypeError(\"Found not supported node type.\")\n\n\ndef get_rand(shape, dtype=\"float32\"):\n    return tvm.nd.array(np.random.rand(*shape).astype(dtype))\n\n\ndef check_func(func, ref_func):\n    func = run_infer_type(func)\n    ref_func = run_infer_type(ref_func)\n    assert tvm.ir.structural_equal(func, ref_func)\n\n\n@tvm.testing.uses_gpu\ndef test_module_pass():\n    shape = (5, 10)\n    dtype = \"float32\"\n    tp = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", tp)\n    y = relay.var(\"y\", tp)\n    v_add = relay.GlobalVar(\"myAdd\")\n    func = relay.Function([x, y], x + y)\n    mod = tvm.IRModule({v_add: func})\n\n    pass_name = \"module_pass_test\"\n    opt_level = 0\n    opt_tester = OptTester(mod)\n    pass_ctx = None\n\n    @tvm.transform.module_pass(opt_level=opt_level, name=pass_name)\n    def transform(expr, ctx):\n        return opt_tester.transform(expr, ctx)\n\n    def test_pass_registration():\n        mod_pass = transform\n        assert isinstance(mod_pass, tvm.transform.ModulePass)\n        pass_info = mod_pass.info\n        assert pass_info.name == pass_name\n        assert pass_info.opt_level == opt_level\n\n    def test_pass_registration_no_decorator():\n        def direct_transform(expr, ctx):\n            return opt_tester.transform(expr, ctx)\n\n        mod_pass = tvm.transform.module_pass(direct_transform, opt_level=3)\n        assert isinstance(mod_pass, tvm.transform.ModulePass)\n        pass_info = mod_pass.info\n        assert pass_info.name == \"direct_transform\"\n        assert pass_info.opt_level == 3\n\n    def test_pass_run():\n        module_pass = transform\n        assert pass_name in str(module_pass)\n\n        updated_mod = module_pass(mod)\n        assert isinstance(updated_mod, tvm.IRModule)\n\n        # Check the abs function in the updated module.\n        v_abs, myabs = get_var_func()\n        new_v_add = updated_mod.get_global_var(v_abs.name_hint)\n        new_abs = updated_mod[new_v_add]\n        check_func(new_abs, myabs)\n\n        # Check the add function in the updated module.\n        v_abs, myabs = get_var_func()\n        new_v_add = updated_mod.get_global_var(v_add.name_hint)\n        new_add = updated_mod[new_v_add]\n        check_func(new_add, func)\n\n        # Check the add function in the python transformed module.\n        ret = opt_tester.transform(mod, pass_ctx)\n        transformed_v_add = ret.get_global_var(v_add.name_hint)\n        transformed_add = mod[transformed_v_add]\n        check_func(new_add, transformed_add)\n\n        # Execute the add function.\n        x_nd = get_rand(shape, dtype)\n        y_nd = get_rand(shape, dtype)\n        ref_res = x_nd.numpy() + y_nd.numpy()\n        for target, dev in tvm.testing.enabled_targets():\n            res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(new_add)(\n                x_nd, y_nd\n            )\n            tvm.testing.assert_allclose(res1.numpy(), ref_res, rtol=1e-5)\n            res2 = relay.create_executor(\"debug\", device=dev, target=target).evaluate(new_add)(\n                x_nd, y_nd\n            )\n            tvm.testing.assert_allclose(res2.numpy(), ref_res, rtol=1e-5)\n\n    test_pass_registration()\n    test_pass_registration_no_decorator\n    test_pass_run()\n\n\ndef test_function_class_pass():\n    @relay.transform.function_pass(opt_level=1)\n    class TestReplaceFunc:\n        \"\"\"Simple test function to replace one argument to another.\"\"\"\n\n        def __init__(self, new_func):\n            self.new_func = new_func\n\n        def transform_function(self, func, mod, ctx):\n            return self.new_func\n\n    x = relay.var(\"x\", shape=(10, 20))\n    f1 = relay.Function([x], x)\n    f2 = relay.Function([x], relay.log(x))\n    fpass = TestReplaceFunc(f1)\n    assert fpass.info.opt_level == 1\n    assert fpass.info.name == \"TestReplaceFunc\"\n    mod = tvm.IRModule.from_expr(f2)\n    mod = fpass(mod)\n    # wrap in expr\n    mod2 = tvm.IRModule.from_expr(f1)\n    mod2 = tvm.relay.transform.InferType()(mod2)\n    assert tvm.ir.structural_equal(mod[\"main\"], mod2[\"main\"])\n\n\n@tvm.testing.uses_gpu\ndef test_function_pass():\n    shape = (10,)\n    dtype = \"float32\"\n    tp = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", tp)\n    v_log = relay.GlobalVar(\"myLog\")\n    log = relay.Function([x], relay.log(x))\n    mod = tvm.IRModule({v_log: log})\n\n    pass_name = \"function_pass_test\"\n    opt_level = 1\n    opt_tester = OptTester(mod)\n    pass_ctx = None\n\n    @_transform.function_pass(opt_level=opt_level, name=pass_name)\n    def transform(expr, mod, ctx):\n        return opt_tester.transform(expr, ctx)\n\n    def get_ref_log():\n        ref_log = relay.Function([x], relay.log(relay.add(x, x)))\n        return ref_log\n\n    def test_pass_registration():\n        function_pass = transform\n        assert isinstance(function_pass, _transform.FunctionPass)\n        pass_info = function_pass.info\n        assert pass_info.name == pass_name\n        assert pass_info.opt_level == opt_level\n\n    def test_pass_registration_no_decorator():\n        def direct_transform(expr, ctx):\n            return opt_tester.transform(expr, ctx)\n\n        mod_pass = _transform.function_pass(direct_transform, opt_level=0)\n        assert isinstance(mod_pass, _transform.FunctionPass)\n        pass_info = mod_pass.info\n        assert pass_info.name == \"direct_transform\"\n        assert pass_info.opt_level == 0\n\n    def test_pass_run():\n        function_pass = transform\n        assert pass_name in str(function_pass)\n\n        updated_mod = function_pass(mod)\n        assert isinstance(updated_mod, tvm.IRModule)\n\n        # Check the log function in the updated module.\n        new_v_log = updated_mod.get_global_var(v_log.name_hint)\n        new_log = updated_mod[new_v_log]\n        check_func(new_log, get_ref_log())\n\n        # Check the log function in the python transformed function.\n        ret = opt_tester.transform(log, pass_ctx)\n        check_func(new_log, ret)\n\n        # Execute the add function.\n        x_nd = get_rand(shape, dtype)\n        ref_res = np.log(x_nd.numpy() * 2)\n        for target, dev in tvm.testing.enabled_targets():\n            res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(new_log)(x_nd)\n            tvm.testing.assert_allclose(res1.numpy(), ref_res, rtol=1e-5)\n            res2 = relay.create_executor(\"debug\", device=dev, target=target).evaluate(new_log)(x_nd)\n            tvm.testing.assert_allclose(res2.numpy(), ref_res, rtol=1e-5)\n\n    test_pass_registration()\n    test_pass_registration_no_decorator()\n    test_pass_run()\n\n\ndef test_module_class_pass():\n    @tvm.transform.module_pass(opt_level=1)\n    class TestPipeline:\n        \"\"\"Simple test function to replace one argument to another.\"\"\"\n\n        def __init__(self, new_mod, replace):\n            self.new_mod = new_mod\n            self.replace = replace\n\n        def transform_module(self, mod, ctx):\n            if self.replace:\n                return self.new_mod\n            return mod\n\n    x = relay.var(\"x\", shape=(10, 20))\n    m1 = tvm.IRModule.from_expr(relay.Function([x], x))\n    m2 = tvm.IRModule.from_expr(relay.Function([x], relay.log(x)))\n    fpass = TestPipeline(m2, replace=True)\n    assert fpass.info.name == \"TestPipeline\"\n    mod3 = fpass(m1)\n    assert mod3.same_as(m2)\n    mod4 = TestPipeline(m2, replace=False)(m1)\n    assert mod4.same_as(m1)\n\n\ndef test_pass_info():\n    info = tvm.transform.PassInfo(opt_level=1, name=\"xyz\")\n    assert info.opt_level == 1\n    assert info.name == \"xyz\"\n\n\n@tvm.testing.uses_gpu\ndef test_sequential_pass():\n    shape = (10,)\n    dtype = \"float32\"\n    tp = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", tp)\n    y = relay.var(\"y\", tp)\n    v_sub = relay.GlobalVar(\"mySub\")\n    sub = relay.Function([x, y], relay.subtract(x, y))\n\n    z = relay.var(\"z\", tp)\n    v_log = relay.GlobalVar(\"myLog\")\n    log = relay.Function([z], relay.log(z))\n\n    mod = tvm.IRModule({v_sub: sub, v_log: log})\n\n    def get_ref_log():\n        ref_log = relay.Function([x], relay.log(relay.add(x, x)))\n        return ref_log\n\n    def get_ref_sub():\n        ref_sub = relay.Function([x, y], relay.subtract(relay.add(x, x), relay.add(y, y)))\n        return ref_sub\n\n    def get_ref_abs():\n        shape = (5, 10)\n        tp = relay.TensorType(shape, \"float32\")\n        a = relay.var(\"a\", tp)\n        ref_abs = relay.Function([a], relay.abs(relay.add(a, a)))\n        return ref_abs\n\n    # Register a module pass.\n    opt_tester = OptTester(mod)\n    pass_ctx = None\n\n    @tvm.transform.module_pass(opt_level=1)\n    def mod_transform(expr, ctx):\n        return opt_tester.transform(expr, ctx)\n\n    module_pass = mod_transform\n\n    # Register a function pass.\n    @_transform.function_pass(opt_level=1)\n    def func_transform(expr, mod, ctx):\n        return opt_tester.transform(expr, ctx)\n\n    function_pass = func_transform\n\n    def test_pass_registration():\n        passes = [module_pass, function_pass]\n        opt_level = 2\n        pass_name = \"sequential\"\n        sequential = tvm.transform.Sequential(passes=passes, opt_level=opt_level)\n        pass_info = sequential.info\n        assert pass_info.name == pass_name\n        assert pass_info.opt_level == opt_level\n\n    def test_no_pass():\n        passes = []\n        sequential = tvm.transform.Sequential(opt_level=1, passes=passes)\n        ret_mod = sequential(mod)\n        mod_func = ret_mod[v_sub]\n        check_func(sub, mod_func)\n\n    def test_only_module_pass():\n        passes = [module_pass]\n        sequential = tvm.transform.Sequential(opt_level=1, passes=passes)\n        with tvm.transform.PassContext(required_pass=[\"mod_transform\"]):\n            ret_mod = sequential(mod)\n        # Check the subtract function.\n        sub_var, new_sub = extract_var_func(ret_mod, v_sub.name_hint)\n        check_func(new_sub, sub)\n\n        # Check the abs function is added.\n        abs_var, abs_func = get_var_func()\n        abs_var, new_abs = extract_var_func(ret_mod, abs_var.name_hint)\n        check_func(new_abs, abs_func)\n\n    def test_only_function_pass():\n        # Check the subtract function.\n        passes = [function_pass]\n        sequential = tvm.transform.Sequential(opt_level=1, passes=passes)\n        with tvm.transform.PassContext(required_pass=[\"func_transform\"]):\n            ret_mod = sequential(mod)\n        _, new_sub = extract_var_func(ret_mod, v_sub.name_hint)\n        check_func(new_sub, get_ref_sub())\n\n        # Check the log function.\n        log_var, new_log = extract_var_func(ret_mod, v_log.name_hint)\n        check_func(new_log, get_ref_log())\n\n    def test_multiple_passes():\n        # Reset the current module since mod has been polluted by the previous\n        # function pass.\n        mod = tvm.IRModule({v_sub: sub, v_log: log})\n        passes = [module_pass, function_pass]\n        sequential = tvm.transform.Sequential(opt_level=1, passes=passes)\n        required = [\"mod_transform\", \"func_transform\"]\n        with tvm.transform.PassContext(required_pass=required):\n            ret_mod = sequential(mod)\n\n        # Check the abs function is added.\n        abs_var, abs_func = get_var_func()\n        abs_var, new_abs = extract_var_func(ret_mod, abs_var.name_hint)\n        check_func(new_abs, get_ref_abs())\n\n        # Check the subtract function is modified correctly.\n        _, new_sub = extract_var_func(ret_mod, v_sub.name_hint)\n        check_func(new_sub, get_ref_sub())\n\n        # Check the log function is modified correctly.\n        _, new_log = extract_var_func(ret_mod, v_log.name_hint)\n        check_func(new_log, get_ref_log())\n\n        # Execute the updated subtract function.\n        x_nd = get_rand(shape, dtype)\n        y_nd = get_rand(shape, dtype)\n        ref_res = np.subtract(x_nd.numpy() * 2, y_nd.numpy() * 2)\n        for target, dev in tvm.testing.enabled_targets():\n            res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(new_sub)(\n                x_nd, y_nd\n            )\n            tvm.testing.assert_allclose(res1.numpy(), ref_res, rtol=1e-5)\n            res2 = relay.create_executor(\"debug\", device=dev, target=target).evaluate(new_sub)(\n                x_nd, y_nd\n            )\n            tvm.testing.assert_allclose(res2.numpy(), ref_res, rtol=1e-5)\n\n        # Execute the updated abs function.\n        x_nd = get_rand((5, 10), dtype)\n        ref_res = np.abs(x_nd.numpy() * 2)\n        for target, dev in tvm.testing.enabled_targets():\n            res1 = relay.create_executor(\"graph\", device=dev, target=target).evaluate(new_abs)(x_nd)\n            tvm.testing.assert_allclose(res1.numpy(), ref_res, rtol=1e-5)\n            res2 = relay.create_executor(\"debug\", device=dev, target=target).evaluate(new_abs)(x_nd)\n            tvm.testing.assert_allclose(res2.numpy(), ref_res, rtol=1e-5)\n\n    test_pass_registration()\n    test_no_pass()\n    test_only_module_pass()\n    test_only_function_pass()\n    test_multiple_passes()\n\n\ndef test_sequential_with_scoping():\n    shape = (1, 2, 3)\n    c_data = np.array(shape).astype(\"float32\")\n    tp = relay.TensorType(shape, \"float32\")\n\n    def before():\n        c = relay.const(c_data)\n        x = relay.var(\"x\", tp)\n        y = relay.add(c, c)\n        y = relay.multiply(y, relay.const(2, \"float32\"))\n        y = relay.add(x, y)\n        z = relay.add(y, c)\n        z1 = relay.add(y, c)\n        z2 = relay.add(z, z1)\n        return relay.Function([x], z2)\n\n    def expected():\n        x = relay.var(\"x\", tp)\n        c_folded = (c_data + c_data) * 2\n        y = relay.add(x, relay.const(c_folded))\n        z = relay.add(y, relay.const(c_data))\n        z1 = relay.add(z, z)\n        return relay.Function([x], z1)\n\n    seq = tvm.transform.Sequential(\n        [\n            relay.transform.InferType(),\n            relay.transform.FoldConstant(),\n            relay.transform.EliminateCommonSubexpr(),\n            relay.transform.AlterOpLayout(),\n        ]\n    )\n\n    mod = tvm.IRModule({\"main\": before()})\n    with tvm.transform.PassContext(opt_level=3):\n        with tvm.target.Target(\"llvm\"):\n            mod = seq(mod)\n\n    zz = mod[\"main\"]\n    zexpected = run_infer_type(expected())\n    assert tvm.ir.structural_equal(zz, zexpected)\n\n\ndef test_nested_sequential_with_scoping():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n        w = relay.var(\"w\", shape=(32, 16, 3, 3), dtype=\"float32\")\n        y = relay.nn.conv2d(x, w, padding=(1, 1))\n        y = relay.reshape(y, newshape=(1, 16, -1))\n        y = relay.reshape(y, newshape=(4, 8, -1, 16))\n        y = relay.reverse_reshape(y, newshape=(32, 0, -1))\n        return tvm.IRModule.from_expr(y)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n        w = relay.var(\"w\", shape=(32, 16, 3, 3), dtype=\"float32\")\n        y = relay.nn.conv2d(x, w, padding=(1, 1))\n        y = relay.reshape(y, newshape=(32, 16, 16))\n        return tvm.IRModule.from_expr(y)\n\n    z = before()\n    passes = [\n        tvm.transform.Sequential([relay.transform.SimplifyExpr()]),\n    ]\n    with tvm.transform.PassContext(opt_level=1):\n        zz = tvm.transform.Sequential(passes)(z)\n\n    expected = relay.transform.InferType()(expected())\n    assert tvm.ir.structural_equal(zz, expected)\n\n\ndef test_print_ir(capfd):\n    shape = (1, 2, 3)\n    tp = relay.TensorType(shape, \"float32\")\n    x = relay.var(\"x\", tp)\n    y = relay.add(x, x)\n    y = relay.multiply(y, relay.const(2, \"float32\"))\n    func = relay.Function([x], y)\n\n    seq = tvm.transform.Sequential(\n        [\n            relay.transform.InferType(),\n            relay.transform.FoldConstant(),\n            tvm.transform.PrintIR(),\n            relay.transform.DeadCodeElimination(),\n        ]\n    )\n\n    mod = tvm.IRModule({\"main\": func})\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n\n    out = capfd.readouterr().err\n\n    assert \"PrintIR\" in out\n    assert \"multiply\" in out\n\n\n@tvm.instrument.pass_instrument\nclass PassCounter:\n    def __init__(self):\n        # Just setting a garbage value to test set_up callback\n        self.counts = 1234\n\n    def enter_pass_ctx(self):\n        self.counts = 0\n\n    def exit_pass_ctx(self):\n        self.counts = 0\n\n    def run_before_pass(self, module, info):\n        self.counts += 1\n\n    def get_counts(self):\n        return self.counts\n\n\ndef test_print_debug_callback():\n    shape = (1, 2, 3)\n    tp = relay.TensorType(shape, \"float32\")\n    x = relay.var(\"x\", tp)\n    y = relay.add(x, x)\n    y = relay.multiply(y, relay.const(2, \"float32\"))\n    func = relay.Function([x], y)\n\n    seq = tvm.transform.Sequential(\n        [\n            relay.transform.InferType(),\n            relay.transform.FoldConstant(),\n            relay.transform.DeadCodeElimination(),\n        ]\n    )\n\n    mod = tvm.IRModule({\"main\": func})\n\n    pass_counter = PassCounter()\n    with tvm.transform.PassContext(opt_level=3, instruments=[pass_counter]):\n        # Should be reseted when entering pass context\n        assert pass_counter.get_counts() == 0\n        mod = seq(mod)\n\n        # TODO(@jroesch): when we remove new fn pass behavior we need to remove\n        # change this back to match correct behavior\n        assert pass_counter.get_counts() == 6\n\n    # Should be cleanned up after exiting pass context\n    assert pass_counter.get_counts() == 0\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_manifest_lifetimes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm.relay import Function, transform\nfrom tvm.relay.testing import inception_v3\nimport pytest\nimport sys\n\n\ndef optimize_and_check(before_program, after_program, passes):\n    if isinstance(before_program, str):\n        before_program = tvm.parser.parse(before_program)\n    if isinstance(after_program, str):\n        after_program = tvm.parser.parse(after_program)\n    if not isinstance(passes, list):\n        passes = [passes]\n    optimize = tvm.transform.Sequential(passes)\n    optimized_program = optimize(before_program)\n    print(\"Actual:\")\n    print(optimized_program)\n    print(\"Expected:\")\n    print(after_program)\n    assert tvm.ir.structural_equal(optimized_program, after_program, map_free_vars=True)\n\n\ndef test_simple_linear():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%x: int) {\n        let %y = %x + %x;\n        let %z = %y + %y;\n        let %w = %z + %z;\n        %w\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%x: int) {\n        let %y = %x + %x;\n        let %_0 = memory.kill(%x);\n        let %z = %y + %y;\n        let %_1 = memory.kill(%y);\n        let %w = %z + %z;\n        let %_2 = memory.kill(%z);\n        %w\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.ManifestLifetimes())\n\n\ndef test_simple_if():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%x: int) {\n        let %y = cast(%x, dtype=\"bool\");\n        let %z = if (%y) {\n            let %v0 = %x + %x;\n            let %v1 = %v0 * 2;\n            %v1\n        } else {\n            %x\n        };\n        %z\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    def @main(%x: int) {\n        let %y = cast(%x, dtype=\"bool\");\n        let %z = if (%y) {\n            let %v0 = %x + %x;\n            let %_0 = memory.kill(%x);\n            let %v1 = %v0 * 2;\n            let %_1 = memory.kill(%v0);\n            %v1\n        } else {\n            %x\n        };\n        let %_1 = memory.kill(%y);\n        %z\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.ManifestLifetimes())\n\n\ndef test_simple_match():\n    before_program = \"\"\"\n    #[version = \"0.0.5\"]\n    type List[A] {\n        Cons(A, List[A]),\n        Nil,\n    }\n    def @main(%x: int) {\n        let %l : List[int] = Nil;\n        let %m = (match (%l) {\n            Cons(%head, %rest) => {\n                let %y = %x + 1;\n                let %z = %y + %y;\n                %z\n            },\n            Nil => -1,\n        });\n        %m\n    }\n    \"\"\"\n    after_program = \"\"\"\n    #[version = \"0.0.5\"]\n    type List[A] {\n        Cons(A, List[A]),\n        Nil,\n    }\n    def @main(%x: int) {\n        let %l : List[int] = Nil;\n        let %m = (match (%l) {\n            Cons(%head, %rest) => {\n                let %y = %x + 1;\n                let %_0 = memory.kill(%x);\n                let %z = %y + %y;\n                let %_1 = memory.kill(%y);\n                /* TODO: %head and %rest should be immediately killed */\n                %z\n            },\n            Nil => -1\n        });\n        let %_2 = memory.kill(%l);\n        %m\n    }\n    \"\"\"\n    optimize_and_check(before_program, after_program, transform.ManifestLifetimes())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_merge_compiler_regions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for merge compiler regions.\"\"\"\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.testing import run_opt_pass\n\n\ndef test_diamond_graph_fanouts():\n    \"\"\"\n    This tests that the data dependencies present in a diamond-shaped\n    graph are correctly resolved by the merging pass.\n\n    O = supported by target\n    X = not supported by target\n\n       O         O\n      / \\\\      /               \\\\\n     O   X --> O    +       +    X\n     \\\\ /             \\\\ /\n       O                O\n\n    Note that we can't just merge the three supported operators together,\n    otherwise both subgraphs would depend on the other.\n    \"\"\"\n\n    def diamond_graph_fanouts():\n        data = relay.var(\"data\", shape=(10, 10))\n        cb_1 = compiler_begin(data, \"test\")\n        O_1 = relay.abs(cb_1)\n        ce_1 = compiler_end(O_1, \"test\")\n        ce_2 = compiler_end(O_1, \"test\")\n        cb_2 = compiler_begin(ce_1, \"test\")\n        cb_3 = compiler_begin(ce_2, \"default\")\n        O_2 = relay.nn.relu(cb_2)\n        ce_3 = compiler_end(O_2, \"test\")\n\n        X = relay.tanh(cb_3)\n        ce_4 = compiler_end(X, \"default\")\n\n        cb_4 = compiler_begin(ce_3, \"test\")\n        cb_5 = compiler_begin(ce_4, \"test\")\n        O_3 = relay.add(cb_4, cb_5)\n        ce_5 = compiler_end(O_3, \"test\")\n\n        diamond = relay.Function([data], ce_5)\n        return diamond\n\n    def expected():\n        data = relay.var(\"data\", shape=(10, 10))\n        cb_1 = compiler_begin(data, \"test\")\n        O_1 = relay.abs(cb_1)\n        ce_2 = compiler_end(O_1, \"test\")\n        O_2 = relay.nn.relu(O_1)\n        ce_3 = compiler_end(O_2, \"test\")\n\n        cb_3 = compiler_begin(ce_2, \"default\")\n        X = relay.tanh(cb_3)\n        ce_4 = compiler_end(X, \"default\")\n\n        cb_4 = compiler_begin(ce_3, \"test\")\n        cb_5 = compiler_begin(ce_4, \"test\")\n        O_3 = relay.add(cb_4, cb_5)\n        ce_5 = compiler_end(O_3, \"test\")\n\n        func = relay.Function([data], ce_5)\n        return func\n\n    result = run_opt_pass(diamond_graph_fanouts(), relay.transform.MergeCompilerRegions())\n    golden = run_opt_pass(expected(), relay.transform.InferType())\n    assert tvm.ir.structural_equal(result, golden)\n\n\ndef test_example_graph():\n    \"\"\"This tests the merging algorithm on the example used in the RFC.\n\n    See the RFC here: https://discuss.tvm.apache.org/t/relay-improved-graph-partitioning-algorithm/5830\n    Blue nodes are adds (target: test), red nodes are subtracts (target: default).\n    \"\"\"\n\n    def annotated():\n        in_1 = relay.var(\"in_1\", shape=(10, 10), dtype=\"float32\")\n        in_2 = relay.var(\"in_2\", shape=(10, 10), dtype=\"float32\")\n        in_3 = relay.var(\"in_3\", shape=(10, 10), dtype=\"float32\")\n        in_4 = relay.var(\"in_4\", shape=(10, 10), dtype=\"float32\")\n        in_5 = relay.var(\"in_5\", shape=(10, 10), dtype=\"float32\")\n        in_6 = relay.var(\"in_6\", shape=(10, 10), dtype=\"float32\")\n        in_7 = relay.var(\"in_7\", shape=(10, 10), dtype=\"float32\")\n        in_8 = relay.var(\"in_8\", shape=(10, 10), dtype=\"float32\")\n        in_9 = relay.var(\"in_9\", shape=(10, 10), dtype=\"float32\")\n        in_10 = relay.var(\"in_10\", shape=(10, 10), dtype=\"float32\")\n\n        begin0 = compiler_begin(in_1, \"test\")\n        begin1 = compiler_begin(in_2, \"test\")\n        begin2 = compiler_begin(in_3, \"test\")\n        begin3 = compiler_begin(in_4, \"test\")\n        node0 = relay.add(begin0, begin1)\n        node1 = relay.add(begin2, begin3)\n        end0 = compiler_end(node0, \"test\")\n        end1 = compiler_end(node1, \"test\")\n        begin4 = compiler_begin(end0, \"test\")\n        begin5 = compiler_begin(end1, \"test\")\n        node2 = relay.add(begin4, begin5)\n        end2 = compiler_end(node2, \"test\")\n\n        dbegin0 = compiler_begin(in_5, \"default\")\n        dbegin1 = compiler_begin(in_6, \"default\")\n        node3 = relay.subtract(dbegin0, dbegin1)\n        dbegin2 = compiler_begin(in_7, \"default\")\n        dend1 = compiler_end(node3, \"default\")\n        dbegin3 = compiler_begin(dend1, \"default\")\n        node4 = relay.subtract(dbegin2, dbegin3)\n        dend2 = compiler_end(node4, \"default\")\n\n        begin6 = compiler_begin(end2, \"test\")\n        begin7 = compiler_begin(dend2, \"test\")\n        node5 = relay.add(begin6, begin7)\n        end3 = compiler_end(node5, \"test\")\n        end4 = compiler_end(node5, \"test\")\n        dbegin4 = compiler_begin(in_8, \"default\")\n        dbegin5 = compiler_begin(end3, \"default\")\n        node6 = relay.subtract(dbegin4, dbegin5)\n        begin8 = compiler_begin(in_9, \"test\")\n        begin9 = compiler_begin(end4, \"test\")\n        node7 = relay.add(begin8, begin9)\n        end5 = compiler_end(node7, \"test\")\n\n        dend3 = compiler_end(node6, \"default\")\n        begin10 = compiler_begin(dend3, \"test\")\n        begin11 = compiler_begin(end5, \"test\")\n        node8 = relay.add(begin10, begin11)\n        end6 = compiler_end(node8, \"test\")\n        begin12 = compiler_begin(in_10, \"test\")\n        begin13 = compiler_begin(end6, \"test\")\n        node9 = relay.add(begin12, begin13)\n        end7 = compiler_end(node9, \"test\")\n\n        f = relay.Function([in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9, in_10], end7)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    def expected():\n        in_1 = relay.var(\"in_1\", shape=(10, 10), dtype=\"float32\")\n        in_2 = relay.var(\"in_2\", shape=(10, 10), dtype=\"float32\")\n        in_3 = relay.var(\"in_3\", shape=(10, 10), dtype=\"float32\")\n        in_4 = relay.var(\"in_4\", shape=(10, 10), dtype=\"float32\")\n        in_5 = relay.var(\"in_5\", shape=(10, 10), dtype=\"float32\")\n        in_6 = relay.var(\"in_6\", shape=(10, 10), dtype=\"float32\")\n        in_7 = relay.var(\"in_7\", shape=(10, 10), dtype=\"float32\")\n        in_8 = relay.var(\"in_8\", shape=(10, 10), dtype=\"float32\")\n        in_9 = relay.var(\"in_9\", shape=(10, 10), dtype=\"float32\")\n        in_10 = relay.var(\"in_10\", shape=(10, 10), dtype=\"float32\")\n\n        begin0 = compiler_begin(in_1, \"test\")\n        begin1 = compiler_begin(in_2, \"test\")\n        begin2 = compiler_begin(in_3, \"test\")\n        begin3 = compiler_begin(in_4, \"test\")\n        node0 = relay.add(begin0, begin1)\n        node1 = relay.add(begin2, begin3)\n        node2 = relay.add(node0, node1)\n\n        dbegin0 = compiler_begin(in_5, \"default\")\n        dbegin1 = compiler_begin(in_6, \"default\")\n        dbegin2 = compiler_begin(in_7, \"default\")\n        node3 = relay.subtract(dbegin0, dbegin1)\n        node4 = relay.subtract(dbegin2, node3)\n        dend0 = compiler_end(node4, \"default\")\n\n        begin4 = compiler_begin(dend0, \"test\")\n        begin5 = compiler_begin(in_9, \"test\")\n        node5 = relay.add(node2, begin4)\n        end1 = compiler_end(node5, \"test\")\n\n        dbegin4 = compiler_begin(end1, \"default\")\n        dbegin5 = compiler_begin(in_8, \"default\")\n        node6 = relay.subtract(dbegin5, dbegin4)\n        dend1 = compiler_end(node6, \"default\")\n\n        node7 = relay.add(begin5, node5)\n        end2 = compiler_end(node7, \"test\")\n        begin6 = compiler_begin(end2, \"test\")\n        begin7 = compiler_begin(dend1, \"test\")\n\n        node8 = relay.add(begin7, begin6)\n\n        begin8 = compiler_begin(in_10, \"test\")\n        node9 = relay.add(begin8, node8)\n        end3 = compiler_end(node9, \"test\")\n\n        f = relay.Function([in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9, in_10], end3)\n        mod = tvm.IRModule.from_expr(f)\n        return mod\n\n    mod = annotated()\n    mod = relay.transform.MergeCompilerRegions()(mod)\n    mod = relay.transform.InferType()(mod)\n    ref_mod = expected()\n    ref_mod = relay.transform.InferType()(ref_mod)\n    assert tvm.ir.structural_equal(mod, ref_mod)\n\n\nif __name__ == \"__main__\":\n    test_diamond_graph_fanouts()\n    test_example_graph()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_merge_composite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for merge composite.\"\"\"\nimport pytest\nimport tvm\nfrom tvm import relay, tir\nfrom tvm.relay.dataflow_pattern import TupleGetItemPattern, is_op, wildcard\nfrom tvm.relay.testing import run_opt_pass\n\n\n\"\"\"\nThe merge composite pass is designed to merge multiple relay operators, that\nmatch a given pattern, and combine them into a single relay function.\n\nFor example suppose we have the graph:\n\n    conv2d\n      |       (merge composite pass)\n   bias_add            ====>           conv2d_bias_relu\n      |            (our target)\n     relu\n\nOur Relay IR before the pass:\n    fn (%data: Tensor[(1, 512, 28, 28), float32], %kernel: Tensor[(256, 512, 1, 1), float32],\n            %bias: Tensor[(256), float32]) -> Tensor[(1, 256, 28, 28), float32] {\n        %0 = nn.conv2d(%data, %kernel, kernel_size=[1, 1])\n            /* ty=Tensor[(1, 256, 28, 28), float32] */;\n        %1 = nn.bias_add(%0, %bias) /* ty=Tensor[(1, 256, 28, 28), float32] */;\n        nn.relu(%1) /* ty=Tensor[(1, 256, 28, 28), float32] */\n    }\n\nOur Relay IR after the pass:\n    fn (%data: Tensor[(1, 512, 28, 28), float32], %kernel: Tensor[(256, 512, 1, 1), float32],\n            %bias: Tensor[(256), float32]) -> Tensor[(1, 256, 28, 28), float32] {\n      %2 = fn (%x: Tensor[(1, 512, 28, 28), float32], %y: Tensor[(256, 512, 1, 1), float32],\n            %z: Tensor[(256), float32], Primitive=1, Composite=\"conv2d_bias_relu\") ->\n            Tensor[(1, 256, 28, 28), float32] {\n        %0 = nn.conv2d(%x, %y, kernel_size=[1, 1]) /* ty=Tensor[(1, 256, 28, 28), float32] */;\n        %1 = nn.bias_add(%0, %z) /* ty=Tensor[(1, 256, 28, 28), float32] */;\n        nn.relu(%1) /* ty=Tensor[(1, 256, 28, 28), float32] */\n      };\n      %2(%data, %kernel, %bias) /* ty=Tensor[(1, 256, 28, 28), float32] */\n    }\n\nAs you can see in the second relay example, the pattern we specified has been wrapped\nin a function. The function is then called, producing the same result as the first relay\nexample.\n\nOne convenient use for this pass is to offload multiple operators to a single external\ncodegen function.\n\"\"\"\n\n\ndef make_add_sub_mul_pattern():\n    r\"\"\"Create a pattern to match the following graph.\n\n    add  sub\n     \\   /\n      \\ /\n      mul\n    \"\"\"\n    x = wildcard()\n    y = wildcard()\n    return (x + y) * (x - y)\n\n\ndef make_add_relu_pattern():\n    r\"\"\"Create a pattern to match the following graph.\n\n     add\n      |\n    relu\n    \"\"\"\n    add_node = wildcard() + wildcard()\n    r = is_op(\"nn.relu\")(add_node)\n    return r\n\n\ndef make_conv_bias_relu_pattern():\n    r\"\"\"Create a pattern to match the following graph.\n\n     conv2d\n       |\n    bias_add\n       |\n     relu\n    \"\"\"\n    x = wildcard()\n    y = wildcard()\n    z = wildcard()\n    conv_node = is_op(\"nn.conv2d\")(x, y)\n    bias_node = is_op(\"nn.bias_add\")(conv_node, z)\n    r = is_op(\"nn.relu\")(bias_node)\n    return r\n\n\ndef make_pattern_with_optional():\n    r\"\"\"Create a pattern to match the following graph. Note that relu is optinal.\n\n     conv2d\n       |\n    bias_add\n       |\n     (relu)\n    \"\"\"\n    x = wildcard()\n    y = wildcard()\n    z = wildcard()\n    conv_node = is_op(\"nn.conv2d\")(x, y)\n    bias_node = is_op(\"nn.bias_add\")(conv_node, z)\n    r = bias_node.optional(lambda x: is_op(\"nn.relu\")(x))\n    return r\n\n\ndef make_add_add_add_pattern():\n    r\"\"\"Create a pattern to match the following graph.\n       Useful for testing re-using a call node.\n\n        x    y\n      /  \\  /\n      |  add\n       \\  |  \\\n         add |\n          | /\n         add\n    \"\"\"\n    x = wildcard()\n    y = wildcard()\n    add_node = is_op(\"add\")(x, y)\n    add_node_1 = is_op(\"add\")(x, add_node)\n    r = is_op(\"add\")(add_node_1, add_node)\n    return r\n\n\ndef make_bn_relu_pattern():\n    r\"\"\"Create a pattern to match the following graph.\n\n     batch_norm\n         |\n    TupleGetItem(0)\n         |\n       relu\n    \"\"\"\n    x = wildcard()\n    gamma = wildcard()\n    beta = wildcard()\n    moving_mean = wildcard()\n    moving_var = wildcard()\n    bn_node = is_op(\"nn.batch_norm\")(x, gamma, beta, moving_mean, moving_var)\n    tuple_get_item_node = TupleGetItemPattern(bn_node, 0)\n    r = is_op(\"nn.relu\")(tuple_get_item_node)\n    return r\n\n\ndef check_result(pattern_table, graph, expected_graph, import_prelude=False):\n    \"\"\"Utility function to check merge composite results.\"\"\"\n    result = run_opt_pass(\n        graph, relay.transform.MergeComposite(pattern_table), import_prelude=import_prelude\n    )\n    assert not relay.analysis.free_vars(result), \"Found free vars in the result graph: {0}\".format(\n        str(result)\n    )\n    expected = run_opt_pass(expected_graph, relay.transform.InferType())\n    assert tvm.ir.structural_equal(\n        result, expected, map_free_vars=True\n    ), \"Graph mismatch: output vs. expected\\n{0}\\n=====\\n{1}\".format(str(result), str(expected))\n\n\ndef test_simple_merge():\n    r\"\"\"Test composite function is correctly produced from simple graph.\n\n    We could expect the pattern `make_add_relu_pattern` to be merged\n    into a single op `add_relu`.\n\n        a  b\n        \\ /               a  b\n        add    ====>      \\ /\n         |             add_relu\n       relu\n\n    \"\"\"\n    pattern_table = [(\"add_relu\", make_add_relu_pattern())]\n\n    def before():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n        add_node = relay.add(a, b)\n        r = relay.nn.relu(add_node)\n        return relay.Function([a, b], r)\n\n    def expected():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n\n        # add_relu function\n        in_1 = relay.var(\"in_1\", shape=(10, 10))\n        in_2 = relay.var(\"in_2\", shape=(10, 10))\n        add_node = relay.add(in_1, in_2)\n        relu_node = relay.nn.relu(add_node)\n        add_relu = relay.Function([in_1, in_2], relu_node)\n        add_relu = add_relu.with_attr(\"Composite\", \"add_relu\")\n        add_relu = add_relu.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n\n        # merged function\n        r = relay.Call(add_relu, [a, b])\n        return relay.Function([a, b], r)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_branch_merge():\n    r\"\"\"Test composite function is correctly produced from branching graph.\n\n    We would expect the pattern `make_add_sub_mul_pattern` to be merged\n    into a single op `add_sub_mul`.\n\n       a  b  a  b\n        \\/    \\/\n        add  sub                       a  b\n         \\   /                          \\/\n          \\ /                      add_sub_mul\n          mul                     c     |\n          /  \\                     \\    |\n       c /  c |       ====>        add_sub_mul\n       \\/   \\/                          |\n       add  sub                         |\n        \\   /                         relu\n         \\ /\n         mul\n          |\n          |\n        relu\n    \"\"\"\n\n    pattern_table = [(\"add_sub_mul\", make_add_sub_mul_pattern())]\n\n    def before():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n        c = relay.var(\"c\", shape=(10, 10))\n        add_node = relay.add(a, b)\n        sub_node = relay.subtract(a, b)\n        mul_node = relay.multiply(add_node, sub_node)\n        add_node_2 = relay.add(c, mul_node)\n        sub_node_2 = relay.subtract(c, mul_node)\n        mul_node_2 = relay.multiply(add_node_2, sub_node_2)\n        r = relay.nn.relu(mul_node_2)\n        return relay.Function([a, b, c], r)\n\n    def expected():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n        c = relay.var(\"c\", shape=(10, 10))\n\n        # add_sub_mul function\n        in_1 = relay.var(\"in_1\", shape=(10, 10))\n        in_2 = relay.var(\"in_2\", shape=(10, 10))\n        add_node = relay.add(in_1, in_2)\n        sub_node = relay.subtract(in_1, in_2)\n        mul_node = relay.multiply(add_node, sub_node)\n        add_sub_mul = relay.Function([in_1, in_2], mul_node)\n        add_sub_mul = add_sub_mul.with_attr(\"Composite\", \"add_sub_mul\")\n        add_sub_mul = add_sub_mul.with_attr(\"PartitionedFromPattern\", \"add_subtract_multiply_\")\n\n        # add_sub_mul1 function\n        in_3 = relay.var(\"in_3\", shape=(10, 10))\n        in_4 = relay.var(\"in_4\", shape=(10, 10))\n        add_node_1 = relay.add(in_3, in_4)\n        sub_node_1 = relay.subtract(in_3, in_4)\n        mul_node_1 = relay.multiply(add_node_1, sub_node_1)\n        add_sub_mul_1 = relay.Function([in_3, in_4], mul_node_1)\n        add_sub_mul_1 = add_sub_mul_1.with_attr(\"Composite\", \"add_sub_mul\")\n        add_sub_mul_1 = add_sub_mul_1.with_attr(\"PartitionedFromPattern\", \"add_subtract_multiply_\")\n\n        # merged function\n        m_add_sub_mul_1 = relay.Call(add_sub_mul, [a, b])\n        m_add_sub_mul_2 = relay.Call(add_sub_mul_1, [c, m_add_sub_mul_1])\n        r = relay.nn.relu(m_add_sub_mul_2)\n        return relay.Function([a, b, c], r)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_reuse_call_merge():\n    r\"\"\"Test composite function is correctly produced from simple graph\n       which re-uses call nodes.\n\n    We could expect the pattern `make_add_add_add` to be merged\n    into a single op `add_add_add`.\n\n        x     y\n         \\   / \\\n          sub  |           x     y\n        /  |  /             \\   / |\n        | add      ====>     sub  |\n         \\ |  \\               |  /\n          add |           add_add_add\n           | /\n          add\n\n    \"\"\"\n    pattern_table = [(\"add_add_add\", make_add_add_add_pattern())]\n\n    def before():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n        sub_node = relay.subtract(a, b)\n\n        # pattern\n        add_node = relay.add(sub_node, b)\n        add_node_1 = relay.add(sub_node, add_node)\n        r = relay.add(add_node_1, add_node)\n\n        return relay.Function([a, b], r)\n\n    def expected():\n        a = relay.var(\"a\", shape=(10, 10))\n        b = relay.var(\"b\", shape=(10, 10))\n\n        # add_relu_add function\n        in_1 = relay.var(\"in_1\", shape=(10, 10))\n        in_2 = relay.var(\"in_2\", shape=(10, 10))\n        add_node = relay.add(in_1, in_2)\n        add_node_1 = relay.add(in_1, add_node)\n        add_node_2 = relay.add(add_node_1, add_node)\n        add_add_add = relay.Function([in_1, in_2], add_node_2)\n        add_add_add = add_add_add.with_attr(\"Composite\", \"add_add_add\")\n        add_add_add = add_add_add.with_attr(\"PartitionedFromPattern\", \"add_add_add_\")\n\n        # merged function\n        sub_node = relay.subtract(a, b)\n        call = relay.Call(add_add_add, [sub_node, b])\n        return relay.Function([a, b], call)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_multiple_patterns():\n    r\"\"\"Test different patterns are merged correctly in the graph.\n\n    We would expect the pattern `make_conv_bias_relu_pattern` to be merged\n    into a single op `conv_bias_relu`. We would also expect `make_add_relu_pattern`\n    to be merged into a single op `add_relu`.\n\n        data   kernel\n          \\      /\n           \\    /\n           conv2d                   data   kernel   bias\n             |                         \\      |      /\n             |   bias                 conv2d_bias_relu\n             |   /                            |\n          bias_add        ====>               |    a\n             |                                |   /\n           relu  a                        add_relu\n             \\  /                             |\n             add                              |  b\n              |                               | /\n            relu  b                          mul\n              |  /\n             mul\n    \"\"\"\n    pattern_table = [\n        (\"conv2d_bias_relu\", make_conv_bias_relu_pattern()),\n        (\"add_relu\", make_add_relu_pattern()),\n    ]\n\n    def before():\n        data = relay.var(\"data\", shape=(1, 512, 28, 28))\n        kernel = relay.var(\"kernel\", shape=(256, 512, 1, 1))\n        bias = relay.var(\"bias\", shape=(256,))\n        a = relay.var(\"a\", shape=(1, 256, 28, 28))\n        b = relay.var(\"b\", shape=(1, 256, 28, 28))\n\n        conv_node = relay.nn.conv2d(\n            data, kernel, kernel_size=(1, 1), padding=(0, 0), strides=(1, 1)\n        )\n\n        bias_node = relay.nn.bias_add(conv_node, bias)\n        relu_node = relay.nn.relu(bias_node)\n        add_node = relay.add(relu_node, a)\n        relu_node_2 = relay.nn.relu(add_node)\n        r = relay.multiply(relu_node_2, b)\n        return relay.Function([data, kernel, bias, a, b], r)\n\n    def expected():\n        data = relay.var(\"data\", shape=(1, 512, 28, 28))\n        kernel = relay.var(\"kernel\", shape=(256, 512, 1, 1))\n        bias = relay.var(\"bias\", shape=(256,))\n        a = relay.var(\"a\", shape=(1, 256, 28, 28))\n        b = relay.var(\"b\", shape=(1, 256, 28, 28))\n\n        # conv_bias_relu function\n        in_1 = relay.var(\"in_1\", shape=(1, 512, 28, 28))\n        in_2 = relay.var(\"in_2\", shape=(256, 512, 1, 1))\n        in_3 = relay.var(\"in_3\", shape=(256,))\n\n        conv_node = relay.nn.conv2d(in_1, in_2, kernel_size=(1, 1), padding=(0, 0), strides=(1, 1))\n\n        bias_node = relay.nn.bias_add(conv_node, in_3)\n        r = relay.nn.relu(bias_node)\n        conv_bias_add_relu = relay.Function([in_1, in_2, in_3], r)\n        conv_bias_add_relu = conv_bias_add_relu.with_attr(\"Composite\", \"conv2d_bias_relu\")\n        conv_bias_add_relu = conv_bias_add_relu.with_attr(\n            \"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\"\n        )\n\n        # add_relu function\n        in_4 = relay.var(\"in_4\", shape=(1, 256, 28, 28))\n        in_5 = relay.var(\"in_5\", shape=(1, 256, 28, 28))\n        add_node = relay.add(in_4, in_5)\n        r = relay.nn.relu(add_node)\n        add_relu = relay.Function([in_4, in_5], r)\n        add_relu = add_relu.with_attr(\"Composite\", \"add_relu\")\n        add_relu = add_relu.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n\n        # merged function\n        conv_bias_add_relu_1 = relay.Call(conv_bias_add_relu, [data, kernel, bias])\n        add_relu_1 = relay.Call(add_relu, [conv_bias_add_relu_1, a])\n        r = relay.multiply(add_relu_1, b)\n        return relay.Function([data, kernel, bias, a, b], r)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_optional_pattern():\n    r\"\"\"Test the pattern with optional operators. We can define a pattern with some operators\n    optional. The merge composite pass will create composite functions for all matched patterns,\n    but with different \"PartitionedFromPattern\" attribute. We expect the backend codegen to\n    analyze that attribute and determine the corresponding action.\n\n    Pattern:    Matched Case A:    Matched Case B:\n\n     conv2d        conv2d             conv2d\n       |             |                  |\n    bias_add      bias_add           bias_add\n       |             |\n     (relu)         relu\n\n    In the above example, the composite function for matched case A would have\n    PartitionedFromPattern=\"nn.conv2d_nn.bias_add_nn.relu_\" while the one for matched case B\n    woud be \"nn.conv2d_nn.bias_add_\".\n    \"\"\"\n    pattern_table = [(\"layer\", make_pattern_with_optional())]\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 3, 7, 7))\n        w1 = relay.var(\"w\", shape=(3, 3, 1, 1))\n        b1 = relay.var(\"b\", shape=(3,))\n        w2 = relay.var(\"w\", shape=(3, 3, 1, 1))\n        b2 = relay.var(\"b\", shape=(3,))\n        conv = relay.nn.conv2d(x, w1, kernel_size=(1, 1))\n        bias = relay.nn.bias_add(conv, b1)\n        relu = relay.nn.relu(bias)\n        conv = relay.nn.conv2d(relu, w2, kernel_size=(1, 1))\n        bias = relay.nn.bias_add(conv, b2)\n        return relay.Function([x, w1, w2, b1, b2], bias)\n\n    def expected():\n        # Matched composite function A\n        x = relay.var(\"x\")\n        w = relay.var(\"w\")\n        b = relay.var(\"b\")\n        conv = relay.nn.conv2d(x, w, kernel_size=(1, 1))\n        bias = relay.nn.bias_add(conv, b)\n        relu = relay.nn.relu(bias)\n        func1 = relay.Function([x, w, b], relu)\n        func1 = func1.with_attr(\"Composite\", \"layer\")\n        func1 = func1.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\")\n\n        # Matched composite function B\n        x = relay.var(\"x\")\n        w = relay.var(\"w\")\n        b = relay.var(\"b\")\n        conv = relay.nn.conv2d(x, w, kernel_size=(1, 1))\n        bias = relay.nn.bias_add(conv, b)\n        func2 = relay.Function([x, w, b], bias)\n        func2 = func2.with_attr(\"Composite\", \"layer\")\n        func2 = func2.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_\")\n\n        # Main function\n        x = relay.var(\"x\", shape=(1, 3, 7, 7))\n        w1 = relay.var(\"w\", shape=(3, 3, 1, 1))\n        b1 = relay.var(\"b\", shape=(3,))\n        w2 = relay.var(\"w\", shape=(3, 3, 1, 1))\n        b2 = relay.var(\"b\", shape=(3,))\n        out1 = func1(x, w1, b1)\n        out2 = func2(out1, w2, b2)\n        return relay.Function([x, w1, w2, b1, b2], out2)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_merge_order():\n    r\"\"\"Test that patterns are merged in the order they exist in the pattern table.\n\n    There can be cases where one pattern is a subgraph of another, in which case\n    it is not clear which match should take priority. The priority should come\n    from the order in which the patterns are declared in the pattern table. The\n    first patterns will be merged with highest priority and the last with lowest.\n\n    A:       B:       C:\n    add      add      abs\n     |        |        |\n    abs      abs      relu\n     |\n    relu\n\n    \"\"\"\n\n    def pattern_A():\n        x = wildcard()\n        y = wildcard()\n        out = is_op(\"add\")(x, y)\n        out = is_op(\"abs\")(out)\n        out = is_op(\"nn.relu\")(out)\n        return out\n\n    def pattern_B():\n        x = wildcard()\n        y = wildcard()\n        out = is_op(\"add\")(x, y)\n        out = is_op(\"abs\")(out)\n        return out\n\n    def pattern_C():\n        x = wildcard()\n        out = is_op(\"abs\")(x)\n        out = is_op(\"nn.relu\")(out)\n        return out\n\n    def before():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        out = relay.add(input_1, input_2)\n        out = relay.abs(out)\n        out = relay.nn.relu(out)\n        return relay.Function([input_1, input_2], out)\n\n    def after_A_priority():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n        out = relay.add(x, y)\n        out = relay.abs(out)\n        out = relay.nn.relu(out)\n        merged_func = relay.Function([x, y], out)\n        merged_func = merged_func.with_attr(\"Composite\", \"A\")\n        merged_func = merged_func.with_attr(\"PartitionedFromPattern\", \"add_abs_nn.relu_\")\n        ret = relay.Call(merged_func, [input_1, input_2])\n        return relay.Function([input_1, input_2], ret)\n\n    def after_B_priority():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n        out = relay.add(x, y)\n        out = relay.abs(out)\n        merged_func = relay.Function([x, y], out)\n        merged_func = merged_func.with_attr(\"Composite\", \"B\")\n        merged_func = merged_func.with_attr(\"PartitionedFromPattern\", \"add_abs_\")\n        out = relay.Call(merged_func, [input_1, input_2])\n        ret = relay.nn.relu(out)\n        return relay.Function([input_1, input_2], ret)\n\n    def after_C_priority():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        x = relay.var(\"x\")\n        out = relay.abs(x)\n        out = relay.nn.relu(out)\n        merged_func = relay.Function([x], out)\n        merged_func = merged_func.with_attr(\"Composite\", \"C\")\n        merged_func = merged_func.with_attr(\"PartitionedFromPattern\", \"abs_nn.relu_\")\n        out = relay.add(input_1, input_2)\n        ret = relay.Call(merged_func, [out])\n        return relay.Function([input_1, input_2], ret)\n\n    # check A highest priority\n    pattern_table = [\n        (\"A\", pattern_A()),\n        (\"B\", pattern_B()),\n        (\"C\", pattern_C()),\n    ]\n    check_result(pattern_table, before(), after_A_priority())\n\n    # check B highest priority\n    pattern_table = [\n        (\"B\", pattern_B()),\n        (\"C\", pattern_C()),\n        (\"A\", pattern_A()),\n    ]\n    check_result(pattern_table, before(), after_B_priority())\n\n    # check C highest priority\n    pattern_table = [\n        (\"C\", pattern_C()),\n        (\"A\", pattern_A()),\n        (\"B\", pattern_B()),\n    ]\n    check_result(pattern_table, before(), after_C_priority())\n\n\ndef test_parallel_merge():\n    r\"\"\"Tests that parallel patterns relying on the same inputs are correctly merged.\n\n    The test graph is difficult to draw out as ascii art. It is essentially two parallel\n    add-sub-mul units which both consume input_1 and input_2 with their results being multiplied\n    to give the output. We expect both parallel branches should get merged and both should still\n    consume the same input variables, input_1 and input_2.\"\"\"\n\n    def before():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        branch_1_add = relay.add(input_1, input_2)\n        branch_1_sub = relay.subtract(input_1, input_2)\n        branch_1 = relay.multiply(branch_1_add, branch_1_sub)\n        branch_2_add = relay.add(input_1, input_2)\n        branch_2_sub = relay.subtract(input_1, input_2)\n        branch_2 = relay.multiply(branch_2_add, branch_2_sub)\n        out = relay.multiply(branch_1, branch_2)\n        return relay.Function([input_1, input_2], out)\n\n    def expected():\n        input_1 = relay.var(\"input_1\", shape=(10, 10))\n        input_2 = relay.var(\"input_2\", shape=(10, 10))\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n        branch_1 = relay.multiply(relay.add(x, y), relay.subtract(x, y))\n        func_1 = relay.Function([x, y], branch_1)\n        func_1 = func_1.with_attr(\"Composite\", \"add_sub_mul\")\n        func_1 = func_1.with_attr(\"PartitionedFromPattern\", \"add_subtract_multiply_\")\n        call_1 = relay.Call(func_1, [input_1, input_2])\n        x1 = relay.var(\"x1\")\n        y1 = relay.var(\"y1\")\n        branch_2 = relay.multiply(relay.add(x1, y1), relay.subtract(x1, y1))\n        func_2 = relay.Function([x1, y1], branch_2)\n        func_2 = func_2.with_attr(\"Composite\", \"add_sub_mul\")\n        func_2 = func_2.with_attr(\"PartitionedFromPattern\", \"add_subtract_multiply_\")\n        call_2 = relay.Call(func_2, [input_1, input_2])\n        out = relay.multiply(call_1, call_2)\n        return relay.Function([input_1, input_2], out)\n\n    pattern_table = [(\"add_sub_mul\", make_add_sub_mul_pattern())]\n    check_result(pattern_table, before(), expected())\n\n\ndef test_multiple_input_subgraphs():\n    r\"\"\"Test the case when multiple input subgraphs feed into another subgraph.\n\n     (1)    (2)    (3)    (4)\n    add    add    add    add\n     |      |      |      |\n    relu   relu   relu   relu\n     \\      /      \\      /\n      \\   /         \\   /\n       add           sub\n        \\            /\n          \\        /\n            \\    /\n              mul\n\n    ----> When 1=3 and 2=4 (Case 'A')\n\n    add_relu  add_relu\n       \\         /\n        \\      /\n       add_sub_mul\n\n    ----> When 1!=3 and 2!=4 (Case 'B')\n\n    add_relu  add_relu  add_relu  add_relu\n       \\       /           \\       /\n         \\   /               \\   /\n          add                 sub\n           \\                  /\n            --------     -----\n                   \\    /\n                    mul\n\n    The difference in behaviour comes from the fact that add_sub_mul expects that the\n    inputs to add and sub are identical (the same two relay expressions). So when you\n    have 4 independent inputs, the pattern should not be merged.\n    \"\"\"\n\n    def before():\n        before_funcs = {}\n        inputs = [relay.var(\"input_\" + str(i), shape=(10, 10)) for i in range(8)]\n        add_relu_1 = relay.add(inputs[0], inputs[1])\n        add_relu_1 = relay.nn.relu(add_relu_1)\n        add_relu_2 = relay.add(inputs[2], inputs[3])\n        add_relu_2 = relay.nn.relu(add_relu_2)\n        add_relu_3 = relay.add(inputs[4], inputs[5])\n        add_relu_3 = relay.nn.relu(add_relu_3)\n        add_relu_4 = relay.add(inputs[6], inputs[7])\n        add_relu_4 = relay.nn.relu(add_relu_4)\n        add = relay.add(add_relu_1, add_relu_2)\n        sub = relay.subtract(add_relu_3, add_relu_4)\n        out = relay.multiply(add, sub)\n        before_funcs[\"B\"] = relay.Function(inputs, out)\n        sub = relay.subtract(add_relu_1, add_relu_2)\n        out = relay.multiply(add, sub)\n        before_funcs[\"A\"] = relay.Function(inputs[:4], out)\n        return before_funcs\n\n    def after_A():\n        inputs = [relay.var(\"input_\" + str(i), shape=(10, 10)) for i in range(4)]\n        x = relay.var(\"x\")\n        y = relay.var(\"y\")\n        add_relu_1 = relay.add(x, y)\n        add_relu_1 = relay.nn.relu(add_relu_1)\n        add_relu_1 = relay.Function([x, y], add_relu_1)\n        add_relu_1 = add_relu_1.with_attr(\"Composite\", \"add_relu\")\n        add_relu_1 = add_relu_1.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n        add_relu_call_1 = relay.Call(add_relu_1, [inputs[0], inputs[1]])\n        x1 = relay.var(\"x1\")\n        y1 = relay.var(\"y1\")\n        add_relu_2 = relay.add(x1, y1)\n        add_relu_2 = relay.nn.relu(add_relu_2)\n        add_relu_2 = relay.Function([x1, y1], add_relu_2)\n        add_relu_2 = add_relu_2.with_attr(\"Composite\", \"add_relu\")\n        add_relu_2 = add_relu_2.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n        add_relu_call_2 = relay.Call(add_relu_2, [inputs[2], inputs[3]])\n        x2 = relay.var(\"x2\")\n        y2 = relay.var(\"y2\")\n        add = relay.add(x2, y2)\n        sub = relay.subtract(x2, y2)\n        add_sub_mul = relay.multiply(add, sub)\n        add_sub_mul = relay.Function([x2, y2], add_sub_mul)\n        add_sub_mul = add_sub_mul.with_attr(\"Composite\", \"add_sub_mul\")\n        add_sub_mul = add_sub_mul.with_attr(\"PartitionedFromPattern\", \"add_subtract_multiply_\")\n        add_sub_mul_call = relay.Call(add_sub_mul, [add_relu_call_1, add_relu_call_2])\n        return relay.Function(inputs, add_sub_mul_call)\n\n    def after_B():\n        inputs = [relay.var(\"input_\" + str(i), shape=(10, 10)) for i in range(8)]\n        add_relu_calls = []\n        for i in range(4):\n            x = relay.var(\"x\" + str(i))\n            y = relay.var(\"x\" + str(i))\n            add_relu = relay.add(x, y)\n            add_relu = relay.nn.relu(add_relu)\n            add_relu = relay.Function([x, y], add_relu)\n            add_relu = add_relu.with_attr(\"Composite\", \"add_relu\")\n            add_relu = add_relu.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n            add_relu_call = relay.Call(add_relu, [inputs[i * 2], inputs[i * 2 + 1]])\n            add_relu_calls.append(add_relu_call)\n\n        add = relay.add(add_relu_calls[0], add_relu_calls[1])\n        sub = relay.subtract(add_relu_calls[2], add_relu_calls[3])\n        out = relay.multiply(add, sub)\n        return relay.Function(inputs, out)\n\n    pattern_table = [\n        (\"add_sub_mul\", make_add_sub_mul_pattern()),\n        (\"add_relu\", make_add_relu_pattern()),\n    ]\n    check_result(pattern_table, before()[\"A\"], after_A())\n    check_result(pattern_table, before()[\"B\"], after_B())\n\n\ndef test_tuple_get_item_merge():\n    \"\"\"Test composite function can be merged from pattern containing TupleGetItem nodes.\"\"\"\n    pattern_table = [(\"bn_relu\", make_bn_relu_pattern())]\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 8))\n        gamma = relay.var(\"gamma\", shape=(8,))\n        beta = relay.var(\"beta\", shape=(8,))\n        moving_mean = relay.var(\"moving_mean\", shape=(8,))\n        moving_var = relay.var(\"moving_var\", shape=(8,))\n        bn_node = relay.nn.batch_norm(x, gamma, beta, moving_mean, moving_var)\n        tuple_get_item_node = bn_node[0]\n        r = relay.nn.relu(tuple_get_item_node)\n        return relay.Function([x, gamma, beta, moving_mean, moving_var], r)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 8))\n        beta = relay.var(\"beta\", shape=(8,))\n        gamma = relay.var(\"gamma\", shape=(8,))\n        moving_mean = relay.var(\"moving_mean\", shape=(8,))\n        moving_var = relay.var(\"moving_var\", shape=(8,))\n\n        # bn_relu function\n        in_1 = relay.var(\"x1\", shape=(1, 8))\n        in_2 = relay.var(\"gamma1\", shape=(8,))\n        in_3 = relay.var(\"beta1\", shape=(8,))\n        in_4 = relay.var(\"moving_mean1\", shape=(8,))\n        in_5 = relay.var(\"moving_var1\", shape=(8,))\n        bn_node = relay.nn.batch_norm(in_1, in_2, in_3, in_4, in_5)\n        tuple_get_item_node = bn_node[0]\n        relu_node = relay.nn.relu(tuple_get_item_node)\n        bn_relu = relay.Function([in_1, in_2, in_3, in_4, in_5], relu_node)\n        bn_relu = bn_relu.with_attr(\"Composite\", \"bn_relu\")\n        bn_relu = bn_relu.with_attr(\n            \"PartitionedFromPattern\", \"nn.batch_norm_TupleGetItem0_nn.relu_\"\n        )\n\n        # merged function\n        r = relay.Call(bn_relu, [x, gamma, beta, moving_mean, moving_var])\n        return relay.Function([x, gamma, beta, moving_mean, moving_var], r)\n\n    check_result(pattern_table, before(), expected())\n\n\ndef test_pattern_with_check():\n    def before():\n        x = relay.var(\"x\", shape=(1, 10, 10, 10))\n        w = relay.var(\"w\", shape=(10, 10, 3, 3))\n        b = relay.var(\"b\", shape=(8,))\n        conv = relay.nn.conv2d(x, w, kernel_size=(3, 3), kernel_layout=\"OIHW\", data_layout=\"NHWC\")\n        bias = relay.nn.bias_add(conv, b)\n        relu = relay.nn.relu(bias)\n        return relay.Function([x, w, b], relu)\n\n    def _check_true(extract):\n        conv = extract.args[0].args[0]\n        return conv.attrs.data_layout == \"NHWC\"\n\n    def _check_false(extract):\n        conv = extract.args[0].args[0]\n        return conv.attrs.data_layout == \"NCHW\"\n\n    def expected():\n        x = relay.var(\"x\")\n        w = relay.var(\"w\")\n        b = relay.var(\"b\")\n        conv = relay.nn.conv2d(x, w, kernel_size=(3, 3), kernel_layout=\"OIHW\", data_layout=\"NHWC\")\n        bias = relay.nn.bias_add(conv, b)\n        relu = relay.nn.relu(bias)\n        func = relay.Function([x, w, b], relu)\n        func = func.with_attr(\"Composite\", \"conv_bias_relu\")\n        func = func.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\")\n\n        x = relay.var(\"x\", shape=(1, 10, 10, 10))\n        w = relay.var(\"w\", shape=(10, 10, 3, 3))\n        b = relay.var(\"b\", shape=(8,))\n        return relay.Function([x, w, b], func(x, w, b))\n\n    pattern_table_false = [(\"conv_bias_relu\", make_conv_bias_relu_pattern(), _check_false)]\n    check_result(pattern_table_false, before(), before())\n\n    pattern_table_true = [(\"conv_bias_relu\", make_conv_bias_relu_pattern(), _check_true)]\n    check_result(pattern_table_true, before(), expected())\n\n\ndef test_diamond_not_merge():\n    r\"\"\"\n    The pattern on the left shouldn't match the structure on the right\n\n    relu             relu\n     | \\              | \\\n     | clip           | add\n     |  /             |  |\n     mul              | clip\n                      |  /\n                      mul\n    \"\"\"\n\n    def get_pattern():\n        conv = make_conv_bias_relu_pattern()\n        clip = is_op(\"clip\")(conv, wildcard(), wildcard())\n        return is_op(\"multiply\")(conv, clip)\n\n    def get_net():\n        data = relay.var(\"data\", shape=(1, 512, 28, 28))\n        kernel = relay.var(\"kernel\", shape=(256, 512, 1, 1))\n        conv = relay.nn.conv2d(data, kernel, kernel_size=(1, 1), padding=(0, 0), strides=(1, 1))\n        bias = relay.nn.bias_add(conv, relay.var(\"bias\", shape=(256,)))\n        relu = relay.nn.relu(bias)\n        add = relay.op.add(relu, relay.const(1.0))\n        clip2 = relay.op.clip(add, 0, 255)\n        mul = relay.op.multiply(relu, clip2)\n        return relay.Function(relay.analysis.free_vars(mul), mul)\n\n    pattern_table = [(\"pat\", get_pattern())]\n    net = get_net()\n    check_result(pattern_table, net, net)\n\n\ndef test_type_check():\n    \"\"\"Test that we can query tensor types in the 'check' function.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 10, 10, 10))\n        w = relay.var(\"w\", shape=(10, 10, 3, 3))\n        b = relay.var(\"b\", shape=(8,))\n        add = relay.op.add(x, x)\n        relu = relay.nn.relu(add)\n        conv = relay.nn.conv2d(\n            relu, w, kernel_size=(3, 3), kernel_layout=\"OIHW\", data_layout=\"NHWC\"\n        )\n        bias = relay.nn.bias_add(conv, b)\n        relu2 = relay.nn.relu(bias)\n        return run_opt_pass(relay.Function([x, w, b], relu2), relay.transform.InferType())\n\n    def expected_false():\n        x = relay.var(\"x\", shape=(1, 10, 10, 10))\n        w = relay.var(\"w\", shape=(10, 10, 3, 3))\n        b = relay.var(\"b\", shape=(8,))\n\n        x0 = relay.var(\"x\")\n\n        add = relay.op.add(x0, x0)\n        relu = relay.nn.relu(add)\n        func = relay.Function([x0], relu)\n        func = func.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n        func = func.with_attr(\"Composite\", \"add_relu\")\n        call = relay.Call(func, [x])\n\n        conv = relay.nn.conv2d(\n            call, w, kernel_size=(3, 3), kernel_layout=\"OIHW\", data_layout=\"NHWC\"\n        )\n        bias = relay.nn.bias_add(conv, b)\n        relu2 = relay.nn.relu(bias)\n        return relay.Function([x, w, b], relu2)\n\n    def expected_true():\n        x = relay.var(\"x\", shape=(1, 10, 10, 10))\n        w = relay.var(\"w\", shape=(10, 10, 3, 3))\n        b = relay.var(\"b\", shape=(8,))\n\n        x0 = relay.var(\"x\")\n\n        add = relay.op.add(x0, x0)\n        relu = relay.nn.relu(add)\n        func = relay.Function([x0], relu)\n        func = func.with_attr(\"PartitionedFromPattern\", \"add_nn.relu_\")\n        func = func.with_attr(\"Composite\", \"add_relu\")\n        call = relay.Call(func, [x])\n\n        x2 = relay.var(\"x\")\n        w1 = relay.var(\"w\")\n        b1 = relay.var(\"b\")\n        conv = relay.nn.conv2d(x2, w1, kernel_size=(3, 3), kernel_layout=\"OIHW\", data_layout=\"NHWC\")\n        bias = relay.nn.bias_add(conv, b1)\n        relu2 = relay.nn.relu(bias)\n        func = relay.Function([x2, w1, b1], relu2)\n        func = func.with_attr(\"Composite\", \"conv_bias_relu\")\n        func = func.with_attr(\"PartitionedFromPattern\", \"nn.conv2d_nn.bias_add_nn.relu_\")\n        call = relay.Call(func, [call, w, b])\n        return relay.Function([x, w, b], call)\n\n    def _check_type_true(extract):\n        conv = extract.args[0].args[0]\n        typ = conv.checked_type\n        return bool(typ.shape[0] == 1)\n\n    def _check_type_false(extract):\n        conv = extract.args[0].args[0]\n        typ = conv.checked_type\n        return bool(typ.shape[0] != 1)\n\n    pattern_table_false = [\n        (\"add_relu\", make_add_relu_pattern()),\n        (\"conv_bias_relu\", make_conv_bias_relu_pattern(), _check_type_false),\n    ]\n    check_result(pattern_table_false, before(), expected_false())\n\n    pattern_table_true = [\n        (\"add_relu\", make_add_relu_pattern()),\n        (\"conv_bias_relu\", make_conv_bias_relu_pattern(), _check_type_true),\n    ]\n    check_result(pattern_table_true, before(), expected_true())\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_partial_eval.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay import op, create_executor, transform\nfrom tvm.relay import Var, TypeVar, TupleGetItem, Let, Function, const, RefRead, RefWrite, RefCreate\nfrom tvm.relay import TensorType, Tuple, If, Clause, PatternConstructor, PatternVar, Match\nfrom tvm.relay import GlobalVar, Call\nfrom tvm.relay.transform import gradient\nfrom tvm.relay.testing import make_nat_expr, run_infer_type\n\n\ndef check_eval(expr, expected_result, mod=None, rtol=1e-07):\n    dev = tvm.device(\"llvm\", 0)\n    result = create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(expr)\n    np.testing.assert_allclose(result.numpy(), expected_result, rtol=rtol)\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef tipe(expr):\n    return run_opt_pass(expr, [transform.PartialEvaluate(), transform.InferType()])\n\n\ndef dcpe(expr, mod=None, grad=False, ignore_impurity=False):\n    passes = [\n        transform.PartialEvaluate(),\n        transform.InferType(),\n        transform.DeadCodeElimination(inline_once=True, ignore_impurity=ignore_impurity),\n        transform.InferType(),\n    ]\n    if grad:\n        expr = gradient(run_infer_type(expr))\n    if mod:\n        assert isinstance(expr, Function)\n        mod[\"main\"] = expr\n        seq = tvm.transform.Sequential(passes)\n        mod = seq(mod)\n        return mod[\"main\"]\n    return run_opt_pass(expr, passes)\n\n\ndef test_tuple():\n    t = TypeVar(\"t\")\n    x = Var(\"x\", t)\n    body = TupleGetItem(relay.Tuple([relay.const(4.0), x]), 1)\n    f = Function([x], body, None, [t])\n    expected = relay.Function([x], x, None, [t])\n    expected = run_opt_pass(expected, transform.InferType())\n    assert tvm.ir.structural_equal(dcpe(f), expected)\n\n\ndef test_const_inline():\n    t = relay.TensorType([], \"float32\")\n    d = Var(\"d\", t)\n    double = Function([d], d + d)\n    orig = double(const(4.0))\n    assert tvm.ir.structural_equal(dcpe(orig), const(8.0))\n\n\ndef test_ref():\n    t = relay.TensorType([], \"float32\")\n    d = relay.Var(\"d\", t)\n    r = relay.Var(\"r\", relay.RefType(t))\n    x = relay.Var(\"x\")\n    body = relay.RefRead(r)\n    body = Let(x, RefWrite(r, RefRead(r) * RefRead(r)), body)\n    body = Let(r, RefCreate(d), body)\n    square = Function([d], body)\n    expected = run_opt_pass(Function([d], d * d), transform.InferType())\n    # TODO(mbs): Revisit once DCE eliminates dead writes.\n    actual = dcpe(square, ignore_impurity=True)\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_empty_ad():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = TensorType(shape, dtype)\n    d = Var(\"d\", t)\n    f = Function([d], d)\n    # TODO(mbs): Revisit once DCE eliminates dead writes.\n    g = dcpe(f, grad=True, ignore_impurity=True)\n    expected = Function([d], Tuple([d, Tuple([op.ones_like(d)])]))\n    expected = run_opt_pass(expected, transform.InferType())\n    assert tvm.ir.structural_equal(g, expected)\n\n\ndef test_ad():\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = TensorType(shape, dtype)\n    d = Var(\"d\", t)\n    f = Function([d], d * d)\n    # TODO(mbs): Revisit once DCE eliminates dead writes.\n    g = dcpe(f, grad=True, ignore_impurity=True)\n    m = d * d\n    x = relay.Var(\"x\")\n    o = op.ones_like(x)\n    x1 = relay.Var(\"x1\")\n    grad = op.zeros_like(d) + op.collapse_sum_like(x1 * d, d) + op.collapse_sum_like(x1 * d, d)\n    body = Tuple([x, Tuple([grad])])\n    body = relay.Let(x1, o, body)\n    expected = Function([d], relay.Let(x, m, body))\n    expected = run_opt_pass(expected, transform.InferType())\n    tvm.ir.assert_structural_equal(g, expected)\n\n\ndef test_if_ref():\n    shape = ()\n    dtype = \"bool\"\n    t = TensorType(shape, dtype)\n    d = Var(\"d\", t)\n    r = Var(\"r\")\n    update = Function([], RefWrite(r, RefRead(r) + RefRead(r)))\n    u = Var(\"u\")\n    body = If(d, u(), u())\n    eff = Var(\"eff\")\n    body = Let(eff, body, RefRead(r))\n    f = Function([d], Let(r, RefCreate(const(1)), Let(u, update, body)))\n    pe_f = tipe(f)\n    f_res = create_executor().evaluate(f)(const(True))\n    pe_f_res = create_executor().evaluate(pe_f)(const(True))\n    np.testing.assert_allclose(f_res.numpy(), 2 * np.ones_like(f_res.numpy()))\n    np.testing.assert_allclose(pe_f_res.numpy(), 2 * np.ones_like(pe_f_res.numpy()))\n\n\ndef test_function_invalidate():\n    shape = ()\n    dtype = \"bool\"\n    t = TensorType(shape, dtype)\n    d = Var(\"d\", t)\n    r = Var(\"r\")\n    fetch = Function([], RefRead(r))\n    fet = Var(\"fetch\")\n    fet_obscured = Var(\"fetch_obscured\")\n    u = Var(\"u\")\n    body = If(d, fet_obscured(), fet_obscured())\n    body = Let(u, RefWrite(r, const(1)), body)\n    body = Let(fet_obscured, If(d, fet, fet), body)\n    body = Let(fet, fetch, body)\n    body = Let(r, RefCreate(const(0)), body)\n    f = Function([d], body)\n    pe_f = tipe(f)\n    f_res = create_executor().evaluate(f)(const(True))\n    pe_f_res = create_executor().evaluate(pe_f)(const(True))\n    np.testing.assert_allclose(f_res.numpy(), np.ones_like(f_res.numpy()))\n    np.testing.assert_allclose(pe_f_res.numpy(), np.ones_like(pe_f_res.numpy()))\n\n\ndef test_head_cons():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    t = TypeVar(\"t\")\n    x = Var(\"x\", t)\n    rlist, cons, nil = p.mod.get_type(\"List\")\n    hd = p.mod.get_global_var(\"hd\")\n    body = hd(cons(x, nil()))\n    f = Function([x], body, None, [t])\n    res = dcpe(f, mod)\n    expected_mod = tvm.IRModule.from_expr(Function([x], x, t, [t]))\n    assert tvm.ir.structural_equal(res, expected_mod[\"main\"])\n\n\ndef test_map():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    rlist, cons, nil = p.mod.get_type(\"List\")\n    rmap = p.mod.get_global_var(\"map\")\n    f = GlobalVar(\"f\")\n    t = TypeVar(\"t\")\n    a = Var(\"a\", t)\n    mod[f] = Function([a], a, t, [t])\n    orig = rmap(f, cons(const(1), cons(const(2), cons(const(3), nil()))))\n    expected = cons((const(1)), cons((const(2)), cons((const(3)), nil())))\n    expected = Function([], expected)\n    mod[\"main\"] = expected\n    mod = transform.InferType()(mod)\n    expected = mod[\"main\"]\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, expected.body)\n\n\ndef test_loop():\n    mod = tvm.IRModule()\n    t = TypeVar(\"t\")\n    x = Var(\"x\", t)\n    loop = GlobalVar(\"loop\")\n    mod[loop] = Function([x], loop(x), t, [t])\n    expected = Call(loop, [const(1)])\n    mod[\"main\"] = Function([], expected)\n    mod = transform.InferType()(mod)\n    expected = mod[\"main\"].body\n    call = Function([], loop(const(1)))\n    res = dcpe(call, mod=mod)\n    assert tvm.ir.structural_equal(res.body, expected)\n\n\ndef test_swap_loop():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, _, _ = p.mod.get_type(\"nat\")\n    x = Var(\"x\", nat())\n    y = Var(\"y\", nat())\n    loop = GlobalVar(\"loop\")\n    mod[loop] = Function([x, y], loop(y, x), nat())\n    prog = loop(make_nat_expr(p, 1), make_nat_expr(p, 2))\n    res = Function([], prog)\n    res = dcpe(res, mod=mod)\n    assert tvm.ir.structural_equal(prog, res.body)\n\n\ndef test_abs_diff():\n    # TODO(@M.K.): refactor using tuple pattern (not yet implemented)\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, z, s = p.mod.get_type(\"nat\")\n    x = Var(\"x\", nat())\n    y = Var(\"y\", nat())\n    xp = Var(\"x'\", nat())\n    yp = Var(\"y'\", nat())\n    diff = GlobalVar(\"diff\")\n    y_z_case = Clause(PatternConstructor(z, []), x)\n    y_s_case = Clause(PatternConstructor(s, [PatternVar(yp)]), diff(yp, xp))\n    x_z_case = Clause(PatternConstructor(z, []), y)\n    x_s_case = Clause(PatternConstructor(s, [PatternVar(xp)]), Match(y, [y_z_case, y_s_case]))\n    mod[diff] = Function([x, y], Match(x, [x_z_case, x_s_case]))\n    orig = diff(make_nat_expr(p, 7), make_nat_expr(p, 3))\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, make_nat_expr(p, 4))\n\n\ndef test_match_nat_id():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, z, s = p.mod.get_type(\"nat\")\n    x = Var(\"x\", nat())\n    y = Var(\"y\", nat())\n    nat_id = GlobalVar(\"nat_id\")\n    z_case = Clause(PatternConstructor(z, []), z())\n    s_case = Clause(PatternConstructor(s, [PatternVar(y)]), s(y))\n    mod[nat_id] = Function([x], Match(x, [z_case, s_case]))\n    orig = nat_id(make_nat_expr(p, 3))\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, make_nat_expr(p, 3))\n\n\ndef test_nat_id():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, _, _ = p.mod.get_type(\"nat\")\n    x = Var(\"x\", nat())\n    y = Var(\"y\", nat())\n    nat_id = GlobalVar(\"nat_id\")\n    mod[nat_id] = Function([x], x)\n    orig = nat_id(make_nat_expr(p, 3))\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, make_nat_expr(p, 3))\n\n\ndef test_global_match_nat_id():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, z, s = p.mod.get_type(\"nat\")\n    x = Var(\"x\", nat())\n    z_case = Clause(PatternConstructor(z, []), z())\n    s_case = Clause(PatternConstructor(s, [PatternVar(x)]), s(x))\n    orig = Match(make_nat_expr(p, 3), [z_case, s_case])\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, make_nat_expr(p, 3))\n\n\ndef test_double():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    double = p.mod.get_global_var(\"nat_double\")\n    orig = double(make_nat_expr(p, 3))\n    orig = Function([], orig)\n    res = dcpe(orig, mod=mod)\n    assert tvm.ir.structural_equal(res.body, make_nat_expr(p, 6))\n\n\ndef test_concat():\n    t = relay.TensorType([10], \"float32\")\n    x = Var(\"x\", t)\n    y = Var(\"x\", t)\n    orig = run_infer_type(Function([x, y], op.concatenate([x, y], axis=0)))\n    tvm.ir.assert_structural_equal(dcpe(orig), orig)\n\n\ndef test_triangle_number():\n    t = relay.TensorType([], \"int32\")\n    x = Var(\"x\", t)\n    f_var = Var(\"f\")\n    f = Function([x], If(op.equal(x, const(0)), const(0), x + f_var(x - const(1))))\n    orig = run_infer_type(Let(f_var, f, f_var(const(10))))\n    tvm.ir.assert_structural_equal(dcpe(orig), const(55))\n\n\ndef test_nat_update():\n    m = tvm.IRModule()\n    p = Prelude(m)\n    p.mod.import_from_std(\"nat.rly\")\n    m = transform.ToANormalForm()(m)\n    transform.PartialEvaluate()(m)\n\n\ndef test_tuple_match():\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    clause = relay.Clause(relay.PatternTuple([relay.PatternVar(a), relay.PatternVar(b)]), a + b)\n    x = relay.Match(relay.Tuple([relay.const(1), relay.const(1)]), [clause])\n    tvm.ir.assert_structural_equal(dcpe(x), const(2))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_partition_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for graph partitioning.\"\"\"\n# pylint: disable=not-callable\nimport os\nimport sys\n\nimport numpy as np\n\nimport tvm\nfrom tvm.relay.backend import te_compiler\nfrom tvm.relay.backend.runtime import Runtime\nimport tvm.relay.testing\nimport tvm.relay.op as reg\nfrom tvm import relay\nfrom tvm import runtime as tvm_runtime\nfrom tvm.relay import transform\nfrom tvm.relay.testing import byoc\nfrom tvm.contrib import utils\nfrom tvm.relay.expr_functor import ExprMutator\nfrom tvm.relay.op.annotation import compiler_begin, compiler_end\nfrom tvm.relay.op.contrib.register import get_pattern_table\nfrom tvm.relay.build_module import bind_params_by_name\n\n\n# Leverage the pass manager to write a simple allowed list based annotator\n@transform.function_pass(opt_level=0)\nclass AllowedListAnnotator:\n    def __init__(self, op_list, compiler):\n        assert isinstance(op_list, (list, tuple, set))\n        self.op_list = op_list\n        self.compiler = compiler\n\n    def transform_function(self, func, mod, dev):\n\n        annotator = self\n\n        class Annotator(tvm.relay.ExprMutator):\n            def visit_call(self, call):\n                op_name = call.op.name\n                if op_name in annotator.op_list:\n                    new_args = []\n                    for arg in call.args:\n                        ann = compiler_begin(super().visit(arg), annotator.compiler)\n                        new_args.append(ann)\n                    new_call = relay.Call(call.op, new_args, call.attrs, call.type_args)\n                    return compiler_end(new_call, annotator.compiler)\n                else:\n                    return super().visit_call(call)\n\n        return Annotator().visit(func)\n\n\nclass WholeGraphAnnotator(ExprMutator):\n    \"\"\"\n    An annotator that creates a compiler for an entire graph.\n    \"\"\"\n\n    def __init__(self, compiler):\n        super(WholeGraphAnnotator, self).__init__()\n        self.compiler = compiler\n        self.last_call = True\n\n    def visit_call(self, call):\n        curr_last = self.last_call\n        self.last_call = False\n\n        params = []\n        for arg in call.args:\n            param = super().visit(arg)\n            if isinstance(param, relay.expr.Var):\n                param = compiler_begin(param, self.compiler)\n            params.append(param)\n\n        new_call = relay.Call(call.op, params, call.attrs)\n        if curr_last:\n            new_call = compiler_end(new_call, self.compiler)\n        return new_call\n\n\nclass MobileNetAnnotator(ExprMutator):\n    \"\"\"\n    Annotate mobilenet until global_avg_pool.\n    \"\"\"\n\n    def __init__(self, compiler):\n        super(MobileNetAnnotator, self).__init__()\n        self.compiler = compiler\n        self.compiler_open = False\n\n    def visit_call(self, call):\n\n        if call.op.name == \"nn.global_avg_pool2d\":\n            self.compiler_open = True\n        compiler_open = self.compiler_open\n\n        params = []\n        for arg in call.args:\n            param = super().visit(arg)\n            if call.op.name == \"nn.global_avg_pool2d\":\n                param = compiler_end(param, self.compiler)\n            if compiler_open and isinstance(param, relay.expr.Var):\n                param = compiler_begin(param, self.compiler)\n            params.append(param)\n\n        new_call = relay.Call(call.op, params, call.attrs)\n        return new_call\n\n\ndef check_result(\n    mod,\n    map_inputs,\n    out_shape,\n    result,\n    tol=1e-5,\n    target=\"llvm\",\n    device=tvm.cpu(),\n    params=None,\n    runtime=Runtime(\"cpp\"),\n):\n    if sys.platform == \"win32\":\n        print(\"Skip test on Windows for now\")\n        return\n\n    def update_lib(lib):\n        test_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n        source_dir = os.path.join(test_dir, \"..\", \"..\", \"..\")\n        contrib_path = os.path.join(source_dir, \"src\", \"runtime\", \"contrib\")\n\n        kwargs = {}\n        kwargs[\"options\"] = [\"-O2\", \"-std=c++17\", \"-I\" + contrib_path]\n        tmp_path = utils.tempdir()\n        lib_name = \"lib.so\"\n        lib_path = tmp_path.relpath(lib_name)\n        lib.export_library(lib_path, fcompile=False, **kwargs)\n        lib = tvm_runtime.load_module(lib_path)\n\n        return lib\n\n    def check_vm_result():\n        te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            exe = relay.vm.compile(mod, target=target, params=params)\n        code, lib = exe.save()\n        lib = update_lib(lib)\n        exe = tvm_runtime.vm.Executable.load_exec(code, lib)\n        vm = tvm_runtime.vm.VirtualMachine(exe, device)\n        outs = vm.run(**map_inputs)\n        outs = outs if isinstance(outs, tvm_runtime.container.ADT) else [outs]\n        results = result if isinstance(result, list) else [result]\n        for out, ref in zip(outs, results):\n            tvm.testing.assert_allclose(out.numpy(), ref, rtol=tol, atol=tol)\n\n    def check_graph_executor_result():\n        te_compiler.get().clear()\n        with tvm.transform.PassContext(opt_level=3):\n            json, lib, param = relay.build(mod, target=target, params=params, runtime=runtime)\n        lib = update_lib(lib)\n        rt_mod = tvm.contrib.graph_executor.create(json, lib, device)\n\n        for name, data in map_inputs.items():\n            rt_mod.set_input(name, data)\n        rt_mod.set_input(**param)\n        rt_mod.run()\n\n        out_shapes = out_shape if isinstance(out_shape, list) else [out_shape]\n        results = result if isinstance(result, list) else [result]\n\n        for idx, shape in enumerate(out_shapes):\n            out = tvm.nd.empty(shape, device=device)\n            out = rt_mod.get_output(idx, out)\n            tvm.testing.assert_allclose(out.numpy(), results[idx], rtol=tol, atol=tol)\n\n    check_vm_result()\n    check_graph_executor_result()\n\n\ndef test_multi_node_compiler():\n    x = relay.var(\"x\", shape=(10, 10))\n    w0 = relay.var(\"w0\", shape=(10, 10))\n    w1 = relay.var(\"w1\", shape=(10, 10))\n    w2 = relay.var(\"w2\", shape=(10, 10))\n    w3 = relay.var(\"w3\", shape=(10, 10))\n    w4 = relay.var(\"w4\", shape=(10, 10))\n    w5 = relay.var(\"w5\", shape=(10, 10))\n    w6 = relay.var(\"w6\", shape=(10, 10))\n    w7 = relay.var(\"w7\", shape=(10, 10))\n\n    # C compiler\n    # FIXME: We generate two compilers for this case but they should be merged to one\n    # due to the common input (x).\n    z0 = relay.add(x, w0)\n    p0 = relay.subtract(z0, w1)\n    q0 = relay.multiply(p0, w2)\n\n    z1 = relay.add(x, w3)\n    p1 = relay.subtract(z1, w4)\n    q1 = relay.multiply(p1, w5)\n\n    # Other parts on TVM\n    z2 = relay.add(x, w6)\n    q2 = relay.subtract(z2, w7)\n\n    r = relay.concatenate((q0, q1, q2), axis=0)\n    f = relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r)\n    mod = tvm.IRModule()\n    ann = byoc.CcompilerAnnotator()\n    mod[\"main\"] = ann.visit(f)\n    mod = transform.PartitionGraph()(mod)\n    mod = transform.InferType()(mod)\n\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    w_data = []\n    for _ in range(8):\n        w_data.append(np.random.rand(10, 10).astype(\"float32\"))\n\n    map_inputs = {\"w{}\".format(i): w_data[i] for i in range(8)}\n    map_inputs[\"x\"] = x_data\n\n    targets = [(\"llvm\", Runtime(\"cpp\")), (\"c\", Runtime(\"crt\", {\"system-lib\": True}))]\n    for tgt, rt in targets:\n        check_result(\n            mod,\n            map_inputs,\n            (30, 10),\n            np.concatenate(\n                (\n                    ((x_data + w_data[0]) - w_data[1]) * w_data[2],\n                    ((x_data + w_data[3]) - w_data[4]) * w_data[5],\n                    x_data + w_data[6] - w_data[7],\n                ),\n                axis=0,\n            ),\n            target=tgt,\n            runtime=rt,\n        )\n\n\ndef test_extern_ccompiler_single_op():\n    @transform.function_pass(opt_level=0)\n    class MyAnnotator:\n        def transform_function(self, func, mod, dev):\n            class Annotator(tvm.relay.ExprMutator):\n                def visit_call(self, call):\n                    new_args = []\n                    for arg in call.args:\n                        ann = compiler_begin(self.visit(arg), \"ccompiler\")\n                        new_args.append(ann)\n                    new_call = relay.Call(call.op, new_args)\n                    return compiler_end(new_call, \"ccompiler\")\n\n            return Annotator().visit(func)\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    z = x + y\n    f = relay.Function([x, y], z)\n    x_data = np.random.rand(8, 8).astype(\"float32\")\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = MyAnnotator()(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (8, 8), x_data + y_data)\n\n\ndef set_func_attr(func, compile_name, symbol_name):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compile_name)\n    func = func.with_attr(\"global_symbol\", symbol_name)\n    return func\n\n\ndef test_extern_ccompiler_default_ops():\n    def expected():\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        x0 = relay.var(\"x0\", shape=(8, 8))\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        add = x0 + y0\n        # Function that uses C compiler\n        func = relay.Function([x0, y0], add)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_0\")\n        mod[glb_0] = func\n        add_call = relay.Call(glb_0, [x, y])\n        # Function that uses default compiler. Ops are fused in this function.\n        p0 = relay.var(\"p0\", shape=(8, 8))\n        log = relay.log(p0)\n        exp = relay.exp(p0)\n        concat = relay.concatenate([log, exp], axis=0)\n        fused_func = relay.Function([p0], concat)\n        fused_func = fused_func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        fused_call = relay.Call(fused_func, [add_call])\n        main = relay.Function([x, y], fused_call)\n        mod[\"main\"] = main\n        mod = transform.InferType()(mod)\n        return mod\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    add = x + y\n    log = relay.log(add)\n    exp = relay.exp(add)\n    concat = relay.concatenate([log, exp], axis=0)\n    f = relay.Function([x, y], concat)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = AllowedListAnnotator([\"add\", \"subtract\", \"multiply\"], \"ccompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n    fused_mod = transform.FuseOps(2)(mod)\n    expected_mod = expected()\n    assert tvm.ir.structural_equal(fused_mod, expected_mod, map_free_vars=True)\n\n    x_data = np.random.rand(8, 8).astype(\"float32\")\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n    np_add = x_data + y_data\n    res = np.concatenate([np.log(np_add), np.exp(np_add)])\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (16, 8), res)\n\n\ndef test_extern_compiler_sanitized_ops():\n    def expected():\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        x0 = relay.var(\"x0\", shape=(8, 8))\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        add = x0 + y0\n        # Function that uses C compiler\n        func = relay.Function([x0, y0], add)\n        func = set_func_attr(func, \"unsanitary-name++\", \"tvmgen_default_unsanitary_name___main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_unsanitary_name___main_0\")\n        mod[glb_0] = func\n        add_call = relay.Call(glb_0, [x, y])\n        # Function that uses default compiler. Ops are fused in this function.\n        p0 = relay.var(\"p0\", shape=(8, 8))\n        log = relay.log(p0)\n        exp = relay.exp(p0)\n        concat = relay.concatenate([log, exp], axis=0)\n        fused_func = relay.Function([p0], concat)\n        fused_func = fused_func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        fused_call = relay.Call(fused_func, [add_call])\n        main = relay.Function([x, y], fused_call)\n        mod[\"main\"] = main\n        mod = transform.InferType()(mod)\n        return mod\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    add = x + y\n    log = relay.log(add)\n    exp = relay.exp(add)\n    concat = relay.concatenate([log, exp], axis=0)\n    f = relay.Function([x, y], concat)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = AllowedListAnnotator([\"add\", \"subtract\", \"multiply\"], \"unsanitary-name++\")(mod)\n    mod = transform.PartitionGraph()(mod)\n    fused_mod = transform.FuseOps(2)(mod)\n    expected_mod = expected()\n    assert tvm.ir.structural_equal(fused_mod, expected_mod, map_free_vars=True)\n\n\ndef test_extern_ccompiler_multiple_functions():\n    def expected():\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        x0 = relay.var(\"x0\", shape=(8, 8))\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        add = x0 + y0\n        # Function that uses C compiler\n        func = relay.Function([x0, y0], add)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_0\")\n        mod[glb_0] = func\n        add_call = relay.Call(glb_0, [x, y])\n        # Function that uses default compiler. Ops are fused in this function.\n        p0 = relay.var(\"p0\", shape=(8, 8))\n        log = relay.log(p0)\n        exp = relay.exp(p0)\n        concat = relay.concatenate([log, exp], axis=0)\n        fused_func = relay.Function([p0], concat)\n        fused_func = fused_func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        fused_call = relay.Call(fused_func, [add_call])\n        main = relay.Function([x, y], fused_call)\n        mod[\"main\"] = main\n        # define the second one\n        a = relay.var(\"a\", shape=(16, 16))\n        b = relay.var(\"b\", shape=(16, 16))\n        a0 = relay.var(\"a0\", shape=(16, 16))\n        b0 = relay.var(\"b0\", shape=(16, 16))\n        add = a0 + b0\n        # Function that uses C compiler\n        func = relay.Function([a0, b0], add)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_subfunction_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_subfunction_0\")\n        mod[glb_0] = func\n        add_call = relay.Call(glb_0, [a, b])\n        # Function that uses default compiler. Ops are fused in this function.\n        p0 = relay.var(\"p0\", shape=(16, 16))\n        log = relay.log(p0)\n        exp = relay.exp(p0)\n        concat = relay.concatenate([log, exp], axis=0)\n        fused_func = relay.Function([p0], concat)\n        fused_func = fused_func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        fused_call = relay.Call(fused_func, [add_call])\n        sunfunction = relay.Function([a, b], fused_call)\n        mod[\"subfunction\"] = sunfunction\n        mod = transform.InferType()(mod)\n        return mod\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    add = x + y\n    log = relay.log(add)\n    exp = relay.exp(add)\n    concat = relay.concatenate([log, exp], axis=0)\n    f = relay.Function([x, y], concat)\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    # define second function\n    a = relay.var(\"a\", shape=(16, 16))\n    b = relay.var(\"b\", shape=(16, 16))\n    add = a + b\n    log = relay.log(add)\n    exp = relay.exp(add)\n    concat = relay.concatenate([log, exp], axis=0)\n    f2 = relay.Function([a, b], concat)\n    mod[\"subfunction\"] = f2\n    mod = AllowedListAnnotator([\"add\", \"subtract\", \"multiply\"], \"ccompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    fused_mod = transform.FuseOps(2)(mod)\n    expected_mod = expected()\n    assert tvm.ir.structural_equal(fused_mod, expected_mod, map_free_vars=True)\n\n    x_data = np.random.rand(8, 8).astype(\"float32\")\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n    np_add = x_data + y_data\n    res = np.concatenate([np.log(np_add), np.exp(np_add)])\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (16, 8), res)\n\n\ndef test_extern_ccompiler():\n    x = relay.var(\"x\", shape=(2, 2))\n    y = relay.var(\"y\", shape=(2, 2))\n    z = x + x\n    p = y * y\n    f = relay.Function([x, y], p - z)\n    x_data = np.random.rand(2, 2).astype(\"float32\")\n    y_data = np.random.rand(2, 2).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = AllowedListAnnotator([\"add\", \"subtract\", \"multiply\"], \"ccompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    check_result(mod, {\"x\": x_data, \"y\": y_data}, (2, 2), (y_data * y_data) - (x_data + x_data))\n\n\ndef test_extern_dnnl():\n    if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 1, 3, 3)\n\n    def expected():\n        data0 = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        input0 = relay.var(\"input\", shape=(w1shape), dtype=dtype)\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            data0, input0, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            depthwise_conv2d_1, input0, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n        func = relay.Function([data0, input0], out)\n        func = set_func_attr(func, \"dnnl\", \"tvmgen_default_dnnl_main_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_dnnl_main_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight = relay.var(\"input\", shape=(w1shape), dtype=dtype)\n        main_f = relay.Function([data, weight], glb_var(data, weight))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        return mod\n\n    def get_func():\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            data, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            depthwise_conv2d_1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n        return relay.Function([data, weight1], out)\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = WholeGraphAnnotator(\"dnnl\").visit(get_func())\n    mod = transform.PartitionGraph()(mod)\n    mod = transform.InferType()(mod)\n\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n    ref_mod = tvm.IRModule()\n    ref_mod[\"main\"] = get_func()\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(\n        i_data, w1_data\n    )\n    check_result(\n        mod, {\"data\": i_data, \"weight1\": w1_data}, (1, 32, 14, 14), ref_res.numpy(), tol=1e-5\n    )\n\ndef test_extern_tachikoma():\n    if not tvm.get_global_func(\"relay.ext.tachikoma\", True):\n        print(\"skip because Tachikoma codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 32, 14, 14)\n    w1shape = (32, 1, 3, 3)\n\n    def expected():\n        data0 = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        input0 = relay.var(\"input\", shape=(w1shape), dtype=dtype)\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            data0, input0, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            depthwise_conv2d_1, input0, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n        func = relay.Function([data0, input0], out)\n        func = set_func_attr(func, \"tachikoma\", \"tvmgen_default_tachikoma_main_0\")\n        glb_var = relay.GlobalVar(\"tvmgen_default_tachikoma_main_0\")\n        mod = tvm.IRModule()\n        mod[glb_var] = func\n        mod = transform.InferType()(mod)\n\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight = relay.var(\"input\", shape=(w1shape), dtype=dtype)\n        main_f = relay.Function([data, weight], glb_var(data, weight))\n        mod[\"main\"] = main_f\n        mod = transform.InferType()(mod)\n\n        return mod\n\n    def get_func():\n        data = relay.var(\"data\", shape=(ishape), dtype=dtype)\n        weight1 = relay.var(\"weight1\", shape=(w1shape), dtype=dtype)\n        depthwise_conv2d_1 = relay.nn.conv2d(\n            data, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        depthwise_conv2d_2 = relay.nn.conv2d(\n            depthwise_conv2d_1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32\n        )\n        out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2)\n\n        return relay.Function([data, weight1], out)\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = WholeGraphAnnotator(\"tachikoma\").visit(get_func())\n    mod = transform.PartitionGraph()(mod)\n    mod = transform.InferType()(mod)\n\n    assert tvm.ir.structural_equal(mod, expected(), map_free_vars=True)\n\n    ref_mod = tvm.IRModule()\n    ref_mod[\"main\"] = get_func()\n\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n    w1_data = np.random.uniform(0, 1, w1shape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu()).evaluate()(\n        i_data, w1_data\n    )\n    check_result(\n        mod, {\"data\": i_data, \"weight1\": w1_data}, (1, 32, 14, 14), ref_res.numpy(), tol=1e-5\n    )\n\ndef test_extern_dnnl_mobilenet():\n    if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 3, 224, 224)\n    ref_mod, params = relay.testing.mobilenet.get_workload(batch_size=1, dtype=\"float32\")\n    mod = transform.AnnotateTarget([\"dnnl\"])(ref_mod)\n    mod = transform.MergeCompilerRegions()(mod)\n    mod = transform.PartitionGraph()(mod)\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n        i_data, **params\n    )\n    te_compiler.get().clear()\n\n    check_result(mod, {\"data\": i_data}, (1, 1000), ref_res.numpy(), tol=1e-5, params=params)\n\n\ndef test_extern_tachikoma_mobilenet():\n    if not tvm.get_global_func(\"relay.ext.tachikoma\", True):\n        print(\"skip because Tachikoma codegen is not available\")\n        return\n\n    dtype = \"float32\"\n    ishape = (1, 3, 224, 224)\n    ref_mod, params = relay.testing.mobilenet.get_workload(batch_size=1, dtype=\"float32\")\n    mod = transform.AnnotateTarget([\"tachikoma\"])(ref_mod)\n    mod = transform.MergeCompilerRegions()(mod)\n    mod = transform.PartitionGraph()(mod)\n    i_data = np.random.uniform(0, 1, ishape).astype(dtype)\n\n    ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n        i_data, **params\n    )\n    te_compiler.get().clear()\n\n    check_result(mod, {\"data\": i_data}, (1, 1000), ref_res.numpy(), tol=1e-5, params=params)\n\n\ndef test_function_lifting():\n    def partition():\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        conv = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n        bn_output = relay.nn.batch_norm(conv, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n\n        func = relay.Function(\n            [data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output.astuple()\n        )\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n        mod = relay.transform.InferType()(mod)\n        op_list = [\"nn.batch_norm\", \"nn.conv2d\"]\n        mod = AllowedListAnnotator(op_list, \"test_compiler\")(mod)\n\n        opt_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.PartitionGraph(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.AlterOpLayout(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3):\n            mod = opt_pass(mod)\n\n        return mod\n\n    def expected():\n        # function for batch_norm\n        data0 = relay.var(\"data0\", relay.TensorType((1, 16, 224, 224), \"float32\"))\n        mod = tvm.IRModule()\n        bn_gamma = relay.var(\"bn_gamma1\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta1\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean1\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var1\", relay.TensorType((16,), \"float32\"))\n\n        bn = relay.nn.batch_norm(data0, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        func0 = relay.Function([data0, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn.astuple())\n        func0 = set_func_attr(func0, \"test_compiler\", \"tvmgen_default_test_compiler_main_2\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_test_compiler_main_2\")\n        mod[gv0] = func0\n        mod = transform.InferType()(mod)\n\n        # function for conv2d\n        data1 = relay.var(\"data1\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight1 = relay.var(\"weight1\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        conv = relay.nn.conv2d(\n            data=data1, weight=weight1, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n        func1 = relay.Function([data1, weight1], conv)\n        func1 = set_func_attr(func1, \"test_compiler\", \"tvmgen_default_test_compiler_main_0\")\n        gv1 = relay.GlobalVar(\"tvmgen_default_test_compiler_main_0\")\n        mod[gv1] = func1\n        mod = transform.InferType()(mod)\n\n        # main function\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma0 = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta0 = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean0 = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar0 = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        call1 = gv1(data, weight)\n        call0 = gv0(call1, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0)\n        mod[\"main\"] = relay.Function(\n            [data, weight, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0], call0\n        )\n        mod = transform.InferType()(mod)\n        return mod\n\n    partitioned = partition()\n    ref_mod = expected()\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_function_lifting_inline():\n    def partition():\n        data = relay.var(\"data\", relay.TensorType((1, 16, 224, 224), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        bn_output = relay.nn.batch_norm(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n\n        func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output.astuple())\n        mod = tvm.IRModule()\n        mod[\"main\"] = func\n        op_list = [\"nn.batch_norm\", \"nn.conv2d\"]\n        mod = AllowedListAnnotator(op_list, \"test_compiler\")(mod)\n\n        opt_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.PartitionGraph(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.AlterOpLayout(),\n                transform.Inline(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3):\n            mod = opt_pass(mod)\n\n        return mod\n\n    def expected():\n        # function for batch_norm\n        data0 = relay.var(\"data0\", relay.TensorType((1, 16, 224, 224), \"float32\"))\n        mod = tvm.IRModule()\n        bn_gamma = relay.var(\"bn_gamma1\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta1\", relay.TensorType((16,), \"float32\"))\n        bn_mmean = relay.var(\"bn_mean1\", relay.TensorType((16,), \"float32\"))\n        bn_mvar = relay.var(\"bn_var1\", relay.TensorType((16,), \"float32\"))\n\n        bn = relay.nn.batch_norm(data0, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        func0 = relay.Function([data0, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn.astuple())\n        func0 = set_func_attr(func0, \"test_compiler\", \"tvmgen_default_test_compiler_main_0\")\n\n        # main function\n        data = relay.var(\"data\", relay.TensorType((1, 16, 224, 224), \"float32\"))\n        bn_gamma0 = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta0 = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mmean0 = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_mvar0 = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        call0 = func0(data, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0)\n        mod[\"main\"] = relay.Function([data, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0], call0)\n        mod = transform.InferType()(mod)\n        return mod\n\n    partitioned = partition()\n    ref_mod = expected()\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_constant_propagation():\n    ones = np.ones(shape=(8, 8), dtype=\"float32\")\n\n    def expected():\n        mod = tvm.IRModule()\n        y = relay.var(\"y\", shape=(8, 8))\n        x0 = relay.const(ones)\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        add = x0 + y0\n        # Function that uses C compiler\n        func = relay.Function([y0], add)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_0\")\n        mod[glb_0] = func\n        mod = relay.transform.InferType()(mod)\n        add_call = relay.Call(glb_0, [y])\n        log = relay.log(add_call)\n        main = relay.Function([y], log)\n        mod[\"main\"] = main\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    x = relay.var(\"x\", shape=(8, 8))\n    y = relay.var(\"y\", shape=(8, 8))\n    add = x + y\n    log = relay.log(add)\n    f = relay.Function([x, y], log)\n    f = bind_params_by_name(f, {\"x\": tvm.nd.array(ones)})\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = AllowedListAnnotator([\"add\"], \"ccompiler\")(mod)\n    mod = transform.PartitionGraph()(mod)\n    mod = relay.transform.InferType()(mod)\n\n    expected_mod = expected()\n    expected_mod = relay.transform.InferType()(expected_mod)\n    assert tvm.ir.structural_equal(mod, expected_mod, map_free_vars=True)\n\n    y_data = np.random.rand(8, 8).astype(\"float32\")\n    np_add = ones + y_data\n    check_result(mod, {\"y\": y_data}, (8, 8), np.log(np_add))\n\n\ndef test_multiple_outputs():\n    def create_graph():\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_var = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        data_cb = compiler_begin(data, \"test_target\")\n        weight_cb = compiler_begin(weight, \"test_target\")\n        bn_gamma_cb = compiler_begin(bn_gamma, \"test_target\")\n        bn_beta_cb = compiler_begin(bn_beta, \"test_target\")\n        bn_mean_cb = compiler_begin(bn_mean, \"test_target\")\n        bn_var_cb = compiler_begin(bn_var, \"test_target\")\n\n        conv_o = relay.nn.conv2d(\n            data=data_cb, weight=weight_cb, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n\n        bn_o = relay.nn.batch_norm(conv_o, bn_gamma_cb, bn_beta_cb, bn_mean_cb, bn_var_cb)\n\n        relu_o = relay.nn.relu(bn_o[0])\n        relu_o_ce = compiler_end(relu_o, \"test_target\")\n\n        bn_omean = bn_o[1]\n        rebn_omean_ce = compiler_end(bn_omean, \"test_target\")\n        bn_ovar = bn_o[2]\n        bn_ovar_ce = compiler_end(bn_ovar, \"test_target\")\n\n        dummy_mean_abs = relay.abs(rebn_omean_ce)\n        dummy_ovar_abs = relay.abs(bn_ovar_ce)\n        dummy_tuple = relay.Tuple((relu_o_ce, dummy_mean_abs, dummy_ovar_abs))\n\n        func = relay.Function([data, weight, bn_gamma, bn_beta, bn_mean, bn_var], dummy_tuple)\n        return func\n\n    def expected():\n        mod = tvm.IRModule()\n\n        # function 0\n        data = relay.var(\"test_target_0_i0\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"test_target_0_i1\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"test_target_0_i2\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"test_target_0_i3\", relay.TensorType((16,), \"float32\"))\n        bn_mean = relay.var(\"test_target_0_i4\", relay.TensorType((16,), \"float32\"))\n        bn_var = relay.var(\"test_target_0_i5\", relay.TensorType((16,), \"float32\"))\n\n        conv_o = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)\n        )\n\n        bn_o = relay.nn.batch_norm(conv_o, bn_gamma, bn_beta, bn_mean, bn_var)\n\n        relu_o = relay.nn.relu(bn_o[0])\n        tuple_o = relay.Tuple((relu_o, bn_o[1], bn_o[2]))\n\n        func0 = relay.Function([data, weight, bn_gamma, bn_beta, bn_mean, bn_var], tuple_o)\n        func0 = set_func_attr(func0, \"test_target\", \"tvmgen_default_test_target_main_0\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_test_target_main_0\")\n        mod[gv0] = func0\n        mod = relay.transform.InferType()(mod)\n\n        # body\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType((16, 3, 3, 3), \"float32\"))\n        bn_gamma = relay.var(\"bn_gamma\", relay.TensorType((16,), \"float32\"))\n        bn_beta = relay.var(\"bn_beta\", relay.TensorType((16,), \"float32\"))\n        bn_mean = relay.var(\"bn_mean\", relay.TensorType((16,), \"float32\"))\n        bn_var = relay.var(\"bn_var\", relay.TensorType((16,), \"float32\"))\n\n        f0_o = gv0(data, weight, bn_gamma, bn_beta, bn_mean, bn_var)\n        f0_relu_o = relay.TupleGetItem(f0_o, 0)\n        f0_mean_o = relay.TupleGetItem(f0_o, 1)\n        f0_var_o = relay.TupleGetItem(f0_o, 2)\n\n        f0_mean_abs = relay.abs(f0_mean_o)\n        f0_var_abs = relay.abs(f0_var_o)\n        main_tuple = relay.Tuple((f0_relu_o, f0_mean_abs, f0_var_abs))\n\n        func = relay.Function([data, weight, bn_gamma, bn_beta, bn_mean, bn_var], main_tuple)\n        mod[\"main\"] = func\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = create_graph()\n    ref_mod = expected()\n    partitioned = transform.PartitionGraph()(mod)\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_mixed_single_multiple_outputs():\n    def create_graph():\n        data = relay.var(\"data\", shape=(10, 10))\n\n        cb_1 = compiler_begin(data, \"test_target\")\n        O_1 = relay.abs(cb_1)\n        ce_2 = compiler_end(O_1, \"test_target\")\n        O_2 = relay.nn.relu(O_1)\n        ce_3 = compiler_end(O_2, \"test_target\")\n\n        X = relay.tanh(ce_2)\n\n        cb_3 = compiler_begin(ce_3, \"test_target\")\n        cb_4 = compiler_begin(X, \"test_target\")\n        O_3 = relay.add(cb_3, cb_4)\n        ce_4 = compiler_end(O_3, \"test_target\")\n\n        func = relay.Function([data], ce_4)\n        return func\n\n    def expected():\n        mod = tvm.IRModule()\n\n        # function 1\n        f1_cb1 = relay.var(\"test_target_0_i0\", shape=(10, 10))\n        f1_O_1 = relay.abs(f1_cb1)\n        f1_O_2 = relay.nn.relu(f1_O_1)\n        f1_out = relay.Tuple((f1_O_2, f1_O_1))\n        func1 = relay.Function([f1_cb1], f1_out)\n        func1 = set_func_attr(func1, \"test_target\", \"tvmgen_default_test_target_main_0\")\n        gv1 = relay.GlobalVar(\"tvmgen_default_test_target_main_0\")\n        mod[gv1] = func1\n        mod = relay.transform.InferType()(mod)\n\n        # function 0\n        f2_cb3 = relay.var(\"test_target_1_i0\", shape=(10, 10))\n        f2_cb4 = relay.var(\"test_target_1_i1\", shape=(10, 10))\n        f2_O_3 = relay.add(f2_cb3, f2_cb4)\n        func0 = relay.Function([f2_cb3, f2_cb4], f2_O_3)\n        func0 = set_func_attr(func0, \"test_target\", \"tvmgen_default_test_target_main_1\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_test_target_main_1\")\n        mod[gv0] = func0\n        mod = relay.transform.InferType()(mod)\n\n        # body\n        data = relay.var(\"data\", shape=(10, 10))\n        tuple_out = gv1(data)\n        ce_2 = relay.TupleGetItem(tuple_out, 1)\n        ce_3 = relay.TupleGetItem(tuple_out, 0)\n\n        X = relay.tanh(ce_2)\n        ce_4 = gv0(ce_3, X)\n        func = relay.Function([data], ce_4)\n        mod[\"main\"] = func\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = create_graph()\n    mod = transform.InferType()(mod)\n\n    ref_mod = expected()\n\n    partitioned = transform.PartitionGraph()(mod)\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_dnnl_fuse():\n    dnnl_patterns = get_pattern_table(\"dnnl\")\n    for pattern in dnnl_patterns:\n        if pattern[0] == \"dnnl.conv2d_bias_relu\":\n            conv2d_bias_relu_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_bias_sigmoid\":\n            conv2d_bias_sigmoid_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_bias\":\n            conv2d_bias_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_relu\":\n            conv2d_relu_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_sigmoid\":\n            conv2d_sigmoid_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_bias_sum\":\n            conv2d_bias_sum_pat = pattern\n        elif pattern[0] == \"dnnl.conv2d_bias_sum_relu\":\n            conv2d_bias_sum_relu_pat = pattern\n\n    def get_blocks(\n        prefix,\n        data,\n        in_channel,\n        out_channel,\n        include_bias_add=True,\n        include_bn=True,\n        include_sigmoid=False,\n    ):\n        weight = relay.var(prefix + \"weight\")\n        bias = relay.var(prefix + \"bias\")\n        bn_gamma = relay.var(prefix + \"bn_gamma\")\n        bn_beta = relay.var(prefix + \"bn_beta\")\n        bn_mmean = relay.var(prefix + \"bn_mean\")\n        bn_mvar = relay.var(prefix + \"bn_var\")\n\n        layer = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=out_channel, padding=(1, 1)\n        )\n        if include_bias_add:\n            layer = relay.nn.bias_add(layer, bias)\n        if include_bn:\n            bn_output = relay.nn.batch_norm(layer, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n            layer = bn_output[0]\n        if include_sigmoid:\n            # dummy layer to prevent pattern detection\n            layer = relay.sigmoid(layer)\n        layer = relay.nn.relu(layer)\n        return layer\n\n    def get_net(include_bias_add=True, include_bn=True, include_sigmoid=False):\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        block1 = get_blocks(\"block1_\", data, 3, 8, include_bias_add, include_bn, include_sigmoid)\n        # The second block is always conv + relu, to make it more interesting\n        block2 = get_blocks(\"block2_\", block1, 8, 8, False, False, include_sigmoid)\n        return relay.Function(relay.analysis.free_vars(block2), block2)\n\n    def get_partitoned_mod(mod, params, pattern_table):\n        # This is required for constant folding\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n        remove_bn_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        # fold consecutive add ops to simplify pattern `conv2d-bias_add-bn-relu`\n        remove_linear_pass = tvm.transform.Sequential(\n            [\n                transform.SimplifyExpr(),\n                transform.FoldConstant(),\n            ]\n        )\n        composite_partition = tvm.transform.Sequential(\n            [\n                transform.CanonicalizeOps(),\n                remove_bn_pass,\n                remove_linear_pass,\n                transform.MergeComposite(pattern_table),\n                transform.AnnotateTarget(\"dnnl\"),\n                transform.PartitionGraph(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            return composite_partition(mod)\n\n    def test_detect_pattern(\n        pattern_table, include_bias_add, include_bn, include_sigmoid, num_expected_partition\n    ):\n        net = get_net(include_bias_add, include_bn, include_sigmoid)\n        mod, params = tvm.relay.testing.create_workload(net)\n        mod = get_partitoned_mod(mod, params, pattern_table)\n        assert len(mod.functions) - 1 == num_expected_partition  # -1 for main\n\n    def test_sum_pattern(pattern_table, num_expected_partition):\n        def get_conv2d_bn_sum_relu(\n            x_shape=(1, 32, 8, 8),\n            k_shape=(16, 32, 3, 3),\n            sum_shape=(1, 16, 6, 6),\n            dtype=\"float32\",\n        ):\n            x = relay.var(\"x\", shape=(x_shape), dtype=dtype)\n            kernel = relay.const(np.random.randint(0, 1, k_shape).astype(dtype))\n            bias = relay.var(\"bias\", shape=(k_shape[0],), dtype=dtype)\n            beta = relay.const(np.zeros(k_shape[0]).astype(dtype))\n            gamma = relay.const(np.ones(k_shape[0]).astype(dtype))\n            moving_mean = relay.const(np.zeros(k_shape[0]).astype(dtype))\n            moving_var = relay.const(np.ones(k_shape[0]).astype(dtype))\n            sum_data = relay.var(\"data1\", shape=sum_shape, dtype=dtype)\n\n            dic = {\"x\": x_shape, \"bias\": (k_shape[0],), \"sum_data\": sum_shape}\n            param_lst = [\"bias\", \"sum_data\"]\n\n            conv = relay.nn.conv2d(\n                x,\n                kernel,\n                channels=k_shape[0],\n                kernel_size=k_shape[2:4],\n            )\n            conv_bias = relay.nn.bias_add(conv, bias)\n            conv_bias_bn, _, _ = relay.nn.batch_norm(\n                conv_bias,\n                gamma=gamma,\n                beta=beta,\n                moving_mean=moving_mean,\n                moving_var=moving_var,\n                axis=1,\n                center=True,\n                scale=True,\n                epsilon=1e-5,\n            )\n            conv_bias_bn_sum = relay.add(conv_bias_bn, sum_data)\n            return relay.nn.relu(conv_bias_bn_sum), dic, param_lst\n\n        net, dic, param_lst = get_conv2d_bn_sum_relu()\n        net = tvm.IRModule.from_expr(net)\n        params = {x: np.random.uniform(-1, 1, dic[x]).astype(\"float32\") for x in param_lst}\n        mod = get_partitoned_mod(net, params, pattern_table)\n        assert len(mod.functions) - 1 == num_expected_partition  # -1 for main\n\n    def test_partition():\n        # conv + bn + relu, conv + relu -> fused conv_bias_relu, conv, and relu\n        test_detect_pattern([conv2d_bias_relu_pat], False, True, False, 3)\n        # conv + bn + relu, conv + relu -> conv, bias, relu, and fused conv_relu\n        test_detect_pattern([conv2d_relu_pat], False, True, False, 4)\n        # conv + bn + relu, conv + relu -> fused conv_bias_relu, and fused conv_relu\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], False, True, False, 2)\n        # conv + bias_add + bn + relu, conv + relu -> fused conv_bias_relu, and fused conv_relu\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], True, True, False, 2)\n        # conv + relu, conv + relu -> two fused conv_relu\n        test_detect_pattern([conv2d_relu_pat], False, False, False, 2)\n        # conv + relu, conv + relu -> no fusion, 4 partition each with a single op\n        test_detect_pattern([conv2d_bias_relu_pat], False, False, False, 4)\n        # conv + bn + sigmoid + relu, conv + sigmoid + relu -> no fusion\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], False, True, True, 7)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias\n        # and single op sigmoid, relu, conv, sigmoid, relu\n        test_detect_pattern([conv2d_bias_pat, conv2d_relu_pat], True, True, True, 6)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias_sigmoid\n        # and single op relu, conv, sigmoid, relu\n        test_detect_pattern([conv2d_bias_sigmoid_pat, conv2d_relu_pat], True, True, True, 5)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias_sigmoid,\n        # fused conv_sigmoid and single op relu, relu\n        test_detect_pattern([conv2d_bias_sigmoid_pat, conv2d_sigmoid_pat], True, True, True, 4)\n        # conv + bias_add + bn + add + relu -> fused conv_bias_sum, relu\n        test_sum_pattern([conv2d_bias_sum_pat], 2)\n        # conv + bias_add + bn + add + relu -> fused conv_bias_sum_relu,\n        test_sum_pattern([conv2d_bias_sum_relu_pat], 1)\n\n    def test_partition_mobilenet():\n        mod, params = relay.testing.mobilenet.get_workload()\n        mod = get_partitoned_mod(mod, params, dnnl_patterns)\n        # 27 fused conv + bn + relu, one dense, one softmax and one global_avg_pooling\n        assert len(mod.functions) - 1 == 30  # -1 for main\n\n    def test_exec(mod, params, ref_mod, ref_params, out_shape):\n        ishape = (1, 3, 224, 224)\n        i_data = np.random.randn(*ishape).astype(np.float32)\n        ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n            i_data, **ref_params\n        )\n        te_compiler.get().clear()\n\n        mod = get_partitoned_mod(mod, params, dnnl_patterns)\n\n        check_result(mod, {\"data\": i_data}, out_shape, ref_res.numpy(), tol=1e-5, params=params)\n\n    test_partition()\n    test_partition_mobilenet()\n\n    if not tvm.get_global_func(\"relay.ext.dnnl\", True):\n        print(\"skip because DNNL codegen is not available\")\n        return\n\n    net = get_net()\n    mod, params = tvm.relay.testing.create_workload(net)\n    ref_mod, ref_params = tvm.relay.testing.create_workload(net)\n    test_exec(mod, params, ref_mod, ref_params, (1, 8, 224, 224))\n\n    mod, params = relay.testing.mobilenet.get_workload()\n    ref_mod, ref_params = relay.testing.mobilenet.get_workload()\n    test_exec(mod, params, ref_mod, ref_params, (1, 1000))\n\ndef test_tachikoma_fuse():\n    tachikoma_patterns = get_pattern_table(\"tachikoma\")\n    (\n        conv2d_bias_relu_pat,\n        conv2d_bias_sigmoid_pat,\n        conv2d_bias_pat,\n        conv2d_relu_pat,\n        conv2d_sigmoid_pat,\n    ) = (\n        tachikoma_patterns[3],\n        tachikoma_patterns[15],\n        tachikoma_patterns[21],\n        tachikoma_patterns[27],\n        tachikoma_patterns[39],\n    )\n\n    def get_blocks(\n        prefix,\n        data,\n        in_channel,\n        out_channel,\n        include_bias_add=True,\n        include_bn=True,\n        include_sigmoid=False,\n    ):\n        weight = relay.var(prefix + \"weight\")\n        bias = relay.var(prefix + \"bias\")\n        bn_gamma = relay.var(prefix + \"bn_gamma\")\n        bn_beta = relay.var(prefix + \"bn_beta\")\n        bn_mmean = relay.var(prefix + \"bn_mean\")\n        bn_mvar = relay.var(prefix + \"bn_var\")\n\n        layer = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=out_channel, padding=(1, 1)\n        )\n        if include_bias_add:\n            layer = relay.nn.bias_add(layer, bias)\n        if include_bn:\n            bn_output = relay.nn.batch_norm(layer, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n            layer = bn_output[0]\n        if include_sigmoid:\n            # dummy layer to prevent pattern detection\n            layer = relay.sigmoid(layer)\n        layer = relay.nn.relu(layer)\n        return layer\n\n    def get_net(include_bias_add=True, include_bn=True, include_sigmoid=False):\n        data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n        block1 = get_blocks(\"block1_\", data, 3, 8, include_bias_add, include_bn, include_sigmoid)\n        # The second block is always conv + relu, to make it more interesting\n        block2 = get_blocks(\"block2_\", block1, 8, 8, False, False, include_sigmoid)\n        return relay.Function(relay.analysis.free_vars(block2), block2)\n\n    def get_partitoned_mod(mod, params, pattern_table):\n        # This is required for constant folding\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n        remove_bn_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        # fold consecutive add ops to simplify pattern `conv2d-bias_add-bn-relu`\n        remove_linear_pass = tvm.transform.Sequential(\n            [\n                transform.SimplifyExpr(),\n                transform.FoldConstant(),\n            ]\n        )\n        composite_partition = tvm.transform.Sequential(\n            [\n                transform.CanonicalizeOps(),\n                remove_bn_pass,\n                remove_linear_pass,\n                transform.MergeComposite(pattern_table),\n                transform.AnnotateTarget(\"tachikoma\"),\n                transform.PartitionGraph(),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            return composite_partition(mod)\n\n    def test_detect_pattern(\n        pattern_table, include_bias_add, include_bn, include_sigmoid, num_expected_partition\n    ):\n        net = get_net(include_bias_add, include_bn, include_sigmoid)\n        mod, params = tvm.relay.testing.create_workload(net)\n        mod = get_partitoned_mod(mod, params, pattern_table)\n        assert len(mod.functions) - 1 == num_expected_partition  # -1 for main\n\n    def test_partition():\n        # conv + bn + relu, conv + relu -> fused conv_bias_relu, conv, and relu\n        test_detect_pattern([conv2d_bias_relu_pat], False, True, False, 3)\n        # conv + bn + relu, conv + relu -> conv, bias, relu, and fused conv_relu\n        test_detect_pattern([conv2d_relu_pat], False, True, False, 4)\n        # conv + bn + relu, conv + relu -> fused conv_bias_relu, and fused conv_relu\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], False, True, False, 2)\n        # conv + bias_add + bn + relu, conv + relu -> fused conv_bias_relu, and fused conv_relu\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], True, True, False, 2)\n        # conv + relu, conv + relu -> two fused conv_relu\n        test_detect_pattern([conv2d_relu_pat], False, False, False, 2)\n        # conv + relu, conv + relu -> no fusion, 4 partition each with a single op\n        test_detect_pattern([conv2d_bias_relu_pat], False, False, False, 4)\n        # conv + bn + sigmoid + relu, conv + sigmoid + relu -> no fusion\n        test_detect_pattern([conv2d_bias_relu_pat, conv2d_relu_pat], False, True, True, 7)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias\n        # and single op sigmoid, relu, conv, sigmoid, relu\n        test_detect_pattern([conv2d_bias_pat, conv2d_relu_pat], True, True, True, 6)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias_sigmoid\n        # and single op relu, conv, sigmoid, relu\n        test_detect_pattern([conv2d_bias_sigmoid_pat, conv2d_relu_pat], True, True, True, 5)\n        # conv + bias_add + bn + sigmoid + relu, conv + sigmoid + relu -> fused conv_bias_sigmoid,\n        # fused conv_sigmoid and single op relu, relu\n        test_detect_pattern([conv2d_bias_sigmoid_pat, conv2d_sigmoid_pat], True, True, True, 4)\n\n    def test_partition_mobilenet():\n        mod, params = relay.testing.mobilenet.get_workload()\n        mod = get_partitoned_mod(mod, params, tachikoma_patterns)\n        # 27 fused conv + bn + relu, one dense and one softmax\n        assert len(mod.functions) - 1 == 29  # -1 for main\n\n    def test_exec(mod, params, ref_mod, ref_params, out_shape):\n        ishape = (1, 3, 224, 224)\n        i_data = np.random.randn(*ishape).astype(np.float32)\n        ref_res = relay.create_executor(\"graph\", mod=ref_mod, device=tvm.cpu(0)).evaluate()(\n            i_data, **ref_params\n        )\n        te_compiler.get().clear()\n\n        mod = get_partitoned_mod(mod, params, tachikoma_patterns)\n\n        check_result(mod, {\"data\": i_data}, out_shape, ref_res.numpy(), tol=1e-5, params=params)\n\n    test_partition()\n    test_partition_mobilenet()\n\n    if not tvm.get_global_func(\"relay.ext.tachikoma\", True):\n        print(\"skip because tachikoma codegen is not available\")\n        return\n\n    net = get_net()\n    mod, params = tvm.relay.testing.create_workload(net)\n    ref_mod, ref_params = tvm.relay.testing.create_workload(net)\n    test_exec(mod, params, ref_mod, ref_params, (1, 8, 224, 224))\n\n    mod, params = relay.testing.mobilenet.get_workload()\n    ref_mod, ref_params = relay.testing.mobilenet.get_workload()\n    test_exec(mod, params, ref_mod, ref_params, (1, 1000))\n\n\ndef test_multiple_use_of_an_output():\n    def expected_same_output_region():\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        z = relay.var(\"z\", shape=(8, 8))\n        x0 = relay.var(\"x0\", shape=(8, 8))\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        log = relay.log(x0)\n        sub = x0 - y0\n        mul = log * sub\n        # The partitioned graph contains log, subtract, and multiply\n        func = relay.Function([x0, y0], mul)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_0\")\n        mod[glb_0] = func\n        mod = transform.InferType()(mod)\n\n        add = x + y\n        call = relay.Call(glb_0, [add, z])\n        main = relay.Function([x, y, z], call)\n        mod[\"main\"] = main\n        mod = transform.InferType()(mod)\n        return mod\n\n    def expected_different_output_region():\n        mod = tvm.IRModule()\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        z = relay.var(\"z\", shape=(8, 8))\n\n        # The partitioned graph contains log\n        i0 = relay.var(\"i0\", shape=(8, 8))\n        log = relay.log(i0)\n        func = relay.Function([i0], log)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_0\")\n        glb_0 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_0\")\n        mod[glb_0] = func\n        mod = transform.InferType()(mod)\n\n        # The partitioned graph contains subtract\n        x0 = relay.var(\"x0\", shape=(8, 8))\n        y0 = relay.var(\"y0\", shape=(8, 8))\n        sub = x0 - y0\n        func = relay.Function([x0, y0], sub)\n        func = set_func_attr(func, \"ccompiler\", \"tvmgen_default_ccompiler_main_1\")\n        glb_1 = relay.GlobalVar(\"tvmgen_default_ccompiler_main_1\")\n        mod[glb_1] = func\n        mod = transform.InferType()(mod)\n\n        add = x + y\n        call_log = relay.Call(glb_0, [add])\n        call_sub = relay.Call(glb_1, [add, z])\n        main = relay.Function([x, y, z], call_log * call_sub)\n        mod[\"main\"] = main\n        mod = transform.InferType()(mod)\n        return mod\n\n    def get_mod():\n        x = relay.var(\"x\", shape=(8, 8))\n        y = relay.var(\"y\", shape=(8, 8))\n        z = relay.var(\"z\", shape=(8, 8))\n        add = x + y\n        sub = add - z\n        log = relay.log(add)\n        sub1 = log * sub\n        f = relay.Function([x, y, z], sub1)\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n        return mod\n\n    def test_same_output_region():\n        mod = get_mod()\n        mod = AllowedListAnnotator([\"subtract\", \"log\", \"multiply\"], \"ccompiler\")(mod)\n        mod = transform.MergeCompilerRegions()(mod)\n        mod = transform.PartitionGraph()(mod)\n\n        expected_mod = expected_same_output_region()\n        assert tvm.ir.structural_equal(mod, expected_mod, map_free_vars=True)\n\n    def test_different_output_region():\n        mod = get_mod()\n        mod = AllowedListAnnotator([\"subtract\", \"log\"], \"ccompiler\")(mod)\n        mod = transform.MergeCompilerRegions()(mod)\n        mod = transform.PartitionGraph()(mod)\n\n        expected_mod = expected_different_output_region()\n        assert tvm.ir.structural_equal(mod, expected_mod, map_free_vars=True)\n\n    test_same_output_region()\n    test_different_output_region()\n\n\ndef test_duplicate_outputs():\n    target = \"test_duplicate_outputs\"\n\n    @tvm.ir.register_op_attr(\"abs\", \"target.\" + target)\n    def abs(expr):  # pylint: disable=unused-variable\n        return True\n\n    def create_graph():\n        data = relay.var(\"data\", shape=(10, 10))\n        x = relay.abs(data)\n        out_1 = relay.nn.relu(x)\n        out_2 = relay.tanh(x)\n        out_3 = relay.log(x)\n        out = relay.Tuple([out_1, out_2, out_3])\n        func = relay.Function([data], out)\n        return func\n\n    def expected():\n        mod = tvm.IRModule()\n\n        # function 0\n        f0_i0 = relay.var(target + \"_0_i0\", shape=(10, 10))\n        f0_o0 = relay.abs(f0_i0)\n        func0 = relay.Function([f0_i0], f0_o0)\n\n        func0 = func0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Compiler\", target)\n        func0 = func0.with_attr(\"global_symbol\", \"tvmgen_default_\" + target + \"_main_0\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_\" + target + \"_main_0\")\n        mod[gv0] = func0\n        mod = transform.InferType()(mod)\n\n        # body\n        data = relay.var(\"data\", shape=(10, 10))\n        function_out = gv0(data)\n        out_1 = relay.nn.relu(function_out)\n        out_2 = relay.tanh(function_out)\n        out_3 = relay.log(function_out)\n        out = relay.Tuple([out_1, out_2, out_3])\n        func = relay.Function([data], out)\n        mod[\"main\"] = func\n        mod = transform.InferType()(mod)\n        return mod\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = create_graph()\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.AnnotateTarget(target),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    ref_mod = expected()\n    partitioned = seq(mod)\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_duplicate_merge_and_tuplegetitem():\n    target = \"test_duplicate_merge_and_tuplegetitem\"\n\n    @tvm.ir.register_op_attr(\"nn.batch_norm\", \"target.\" + target)\n    def batch_norm(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"nn.relu\", \"target.\" + target)\n    def relu(expr):  # pylint: disable=unused-variable\n        return True\n\n    def create_graph():\n        data = relay.var(\"data\", shape=(10, 10))\n        bn_gamma = relay.var(\"bn_gamma\")\n        bn_beta = relay.var(\"bn_beta\")\n        bn_mmean = relay.var(\"bn_mean\")\n        bn_mvar = relay.var(\"bn_var\")\n        x = relay.nn.batch_norm(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        out_1 = relay.nn.relu(x[0])\n        bn_out_1 = x[1]\n        out_2 = relay.tanh(bn_out_1)\n        out_3 = relay.log(bn_out_1)\n        out = relay.Tuple([out_1, out_2, out_3])\n        func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], out)\n        return func\n\n    def expected():\n        mod = tvm.IRModule()\n\n        # function 0\n        f0_i0 = relay.var(target + \"_0_i0\", shape=(10, 10))\n        f0_i1 = relay.var(target + \"_0_i1\")\n        f0_i2 = relay.var(target + \"_0_i2\")\n        f0_i3 = relay.var(target + \"_0_i3\")\n        f0_i4 = relay.var(target + \"_0_i4\")\n        f0_n0 = relay.nn.batch_norm(f0_i0, f0_i1, f0_i2, f0_i3, f0_i4)\n        f0_n1 = f0_n0[1]\n        f0_n2 = relay.nn.relu(f0_n0[0])\n        f0_o0 = relay.Tuple([f0_n2, f0_n1])\n        func0 = relay.Function([f0_i0, f0_i1, f0_i2, f0_i3, f0_i4], f0_o0)\n\n        func0 = func0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Compiler\", target)\n        func0 = func0.with_attr(\"global_symbol\", \"tvmgen_default_\" + target + \"_main_0\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_\" + target + \"_main_0\")\n        mod[gv0] = func0\n        mod = transform.InferType()(mod)\n\n        # body\n        data = relay.var(\"data\", shape=(10, 10))\n        bn_gamma = relay.var(\"bn_gamma\")\n        bn_beta = relay.var(\"bn_beta\")\n        bn_mmean = relay.var(\"bn_mean\")\n        bn_mvar = relay.var(\"bn_var\")\n        function_out = gv0(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        get_out0 = relay.TupleGetItem(function_out, 0)\n        get_out1 = relay.TupleGetItem(function_out, 1)\n        out_2 = relay.tanh(get_out1)\n        out_3 = relay.log(get_out1)\n        out = relay.Tuple([get_out0, out_2, out_3])\n        func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], out)\n        mod[\"main\"] = func\n        mod = transform.InferType()(mod)\n        return mod\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = create_graph()\n    mod = transform.InferType()(mod)\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.AnnotateTarget(target),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    ref_mod = expected()\n    partitioned = seq(mod)\n    assert tvm.ir.structural_equal(partitioned, ref_mod, map_free_vars=True)\n\n\ndef test_constant_tuples():\n    @tvm.ir.register_op_attr(\"qnn.concatenate\", \"target.const_tuples\")\n    def add(expr):  # pylint: disable=unused-variable\n        return True\n\n    def create_graph():\n        a = relay.var(\"a\", shape=(10, 10), dtype=\"uint8\")\n        b = relay.var(\"b\", shape=(10, 10), dtype=\"uint8\")\n        a1 = relay.abs(a)\n\n        zeroi = relay.const(1, \"int32\")\n        zerof = relay.const(0, \"float32\")\n        con = relay.qnn.op.concatenate(\n            (a1, b),\n            input_scales=(zerof, zerof),\n            input_zero_points=(zeroi, zeroi),\n            output_scale=zerof,\n            output_zero_point=zeroi,\n            axis=1,\n        )\n\n        f = relay.Function([a, b], con)\n        mod = tvm.IRModule.from_expr(f)\n        mod = transform.InferType()(mod)\n        return mod\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.AnnotateTarget(\"const_tuples\"),\n            transform.InferType(),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    partitioned = seq(create_graph())\n\n    concat = partitioned[\"tvmgen_default_const_tuples_main_0\"].body\n    assert type(concat.args[1]) == relay.Tuple\n    assert type(concat.args[2]) == relay.Tuple\n    assert type(concat.args[3]) == relay.Constant\n    assert type(concat.args[4]) == relay.Constant\n\n\ndef test_flatten_tuple_output():\n    target = \"test_flatten_tuple_output\"\n\n    @tvm.ir.register_op_attr(\"split\", \"target.\" + target)\n    def split(expr):  # pylint: disable=unused-variable\n        return True\n\n    @tvm.ir.register_op_attr(\"abs\", \"target.\" + target)\n    def abs(expr):  # pylint: disable=unused-variable\n        return True\n\n    def create_graph():\n        a = relay.var(\"a\", shape=(10, 10), dtype=\"uint8\")\n\n        a_split = relay.split(a, 2)\n        a_split_0 = relay.TupleGetItem(a_split.astuple(), 0)\n        a_split_0_abs = relay.abs(a_split_0)\n\n        a_con = relay.concatenate(a_split, 0)\n        a_split_0_relu = relay.nn.relu(a_split_0_abs)\n\n        out = relay.Tuple((a_con, a_split_0_relu))\n        f = relay.Function([a], out)\n        mod = tvm.IRModule.from_expr(f)\n        mod = transform.InferType()(mod)\n        return mod\n\n    def expected():\n        mod = tvm.IRModule()\n\n        # function 0\n        f0_i0 = relay.var(target + \"_0_i0\", shape=(10, 10), dtype=\"uint8\")\n        a_split = relay.split(f0_i0, 2)\n        a_split_0 = relay.TupleGetItem(a_split.astuple(), 0)\n        a_split_1 = relay.TupleGetItem(a_split.astuple(), 1)\n        a_split_abs_in = relay.TupleGetItem(a_split.astuple(), 0)\n        abs = relay.abs(a_split_abs_in)\n        tuple_out = relay.Tuple((a_split_0, a_split_1, abs))\n        func0 = relay.Function([f0_i0], tuple_out)\n\n        func0 = func0.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n        func0 = func0.with_attr(\"Compiler\", target)\n        func0 = func0.with_attr(\"global_symbol\", \"tvmgen_default_\" + target + \"_main_0\")\n        gv0 = relay.GlobalVar(\"tvmgen_default_\" + target + \"_main_0\")\n        mod[gv0] = func0\n        mod = transform.InferType()(mod)\n\n        # body\n        data = relay.var(\"a\", shape=(10, 10), dtype=\"uint8\")\n        f_out = gv0(data)\n        f_out_0 = relay.TupleGetItem(f_out, 0)\n        f_out_1 = relay.TupleGetItem(f_out, 1)\n        tuple = relay.Tuple((f_out_0, f_out_1))\n        concat = relay.concatenate(tuple, 0)\n        f_out_2 = relay.TupleGetItem(f_out, 2)\n        relu = relay.nn.relu(f_out_2)\n        ret_tuple = relay.Tuple((concat, relu))\n        mod[\"main\"] = relay.Function([data], ret_tuple)\n        mod = transform.InferType()(mod)\n        return mod\n\n    seq = tvm.transform.Sequential(\n        [\n            transform.AnnotateTarget(target),\n            transform.MergeCompilerRegions(),\n            transform.PartitionGraph(),\n        ]\n    )\n\n    partitioned = seq(create_graph())\n    partitioned = transform.InferType()(partitioned)\n    expected_mod = transform.InferType()(expected())\n    assert tvm.ir.structural_equal(partitioned, expected_mod, map_free_vars=True)\n\n\ndef test_tuple_output_exec():\n    \"\"\"Test C codegen and runtime for a subgraph with a tuple output\"\"\"\n    a = relay.var(\"a\", shape=(10, 10), dtype=\"float32\")\n    b = relay.var(\"b\", shape=(10, 10), dtype=\"float32\")\n    ba = relay.annotation.compiler_begin(a, \"ccompiler\")\n    bb = relay.annotation.compiler_begin(b, \"ccompiler\")\n    add = relay.add(ba, bb)\n    sub = relay.subtract(ba, bb)\n    out = relay.Tuple((add, sub))\n    eout = relay.annotation.compiler_end(out, \"ccompiler\")\n    func = relay.Function([a, b], eout)\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    mod = transform.InferType()(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    a_data = np.random.rand(10, 10).astype(\"float32\")\n    b_data = np.random.rand(10, 10).astype(\"float32\")\n\n    check_result(\n        mod,\n        {\"a\": a_data, \"b\": b_data},\n        [(10, 10), (10, 10)],\n        [(a_data + b_data), (a_data - b_data)],\n    )\n\n\ndef test_extern_opt():\n    def Optimize(mod):\n        return relay.transform.FoldConstant()(mod)\n\n    tvm.register_func(\"relay.ext.test_target.optimize\", Optimize)\n\n    x = relay.var(\"x\", shape=(2, 2))\n    y0 = relay.var(\"y0\", shape=(2, 2))\n    y1 = relay.var(\"y1\", shape=(2, 2))\n    yy0 = relay.annotation.compiler_begin(y0, \"test_target\")\n    yy1 = relay.annotation.compiler_begin(y1, \"test_target\")\n    z = yy0 + yy1\n    end = relay.annotation.compiler_end(z, \"test_target\")\n    f = relay.Function([x, y0, y1], end * x)\n    c = np.ones(shape=(2, 2), dtype=\"float32\")\n    f = bind_params_by_name(f, {\"y0\": tvm.nd.array(c), \"y1\": tvm.nd.array(c)})\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    mod = transform.InferType()(mod)\n    mod = transform.PartitionGraph()(mod)\n\n    try:\n        t0 = mod[\"tvmgen_default_test_target_main_0\"]\n    except:\n        raise KeyError(\"test_target_main_0 not found\")\n\n    assert isinstance(t0.body, relay.Constant)\n    expected = np.empty([2, 2])\n    expected.fill(2)\n    tvm.testing.assert_allclose(t0.body.data.numpy(), expected, rtol=1e-5, atol=1e-5)\n\n\ndef test_preserve_type_import():\n    \"\"\"Test to make sure type definition and imports are preserved during the BYOC pipeline.\"\"\"\n    from tvm.relay.prelude import Prelude, StaticTensorArrayOps\n\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        write = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        gather = p.get_global_var_static(\"tensor_array_gather\", dtype, shape)\n        v = relay.var(\"v\")\n        indice = relay.var(\"indice\")\n        init_tensor_array = tensor_array(relay.const(3))\n        tensor_array1 = write(init_tensor_array, relay.const(0), tensor(v))\n        tensor_array2 = write(tensor_array1, relay.const(1), tensor(v))\n        tensor_array3 = write(tensor_array2, relay.const(2), tensor(v))\n        out = gather(tensor_array3, indice)\n        mod[\"main\"] = relay.Function([v, indice], out)\n        mod = transform.RemoveUnusedFunctions()(mod)\n        mod = transform.PartitionGraph()(mod)\n\n    run(\"float32\", [2, 3])\n\n\ndef test_not_bind_constant():\n    def get_net(prefix, data, out_channel):\n        weight = relay.var(prefix + \"weight\")\n        bn_gamma = relay.var(prefix + \"bn_gamma\")\n        bn_beta = relay.var(prefix + \"bn_beta\")\n        bn_mmean = relay.var(prefix + \"bn_mean\")\n        bn_mvar = relay.var(prefix + \"bn_var\")\n\n        layer = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=out_channel, padding=(1, 1)\n        )\n        bn_output = relay.nn.batch_norm(layer, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        out = relay.nn.relu(bn_output[0])\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def get_partitoned_mod(mod, params, pattern_table, bind_constants):\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n        remove_bn_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        composite_partition = tvm.transform.Sequential(\n            [\n                remove_bn_pass,\n                transform.MergeComposite(pattern_table),\n                transform.AnnotateTarget(\"tachikoma\"),\n                transform.PartitionGraph(bind_constants=bind_constants),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            return composite_partition(mod)\n\n    data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n    net = get_net(\"block_\", data, 8)\n    mod, params = tvm.relay.testing.create_workload(net)\n\n    mod = get_partitoned_mod(mod, params, get_pattern_table(\"tachikoma\"), bind_constants=True)\n    len(mod[\"main\"].body.args) == 1\n\n    mod = get_partitoned_mod(mod, params, get_pattern_table(\"tachikoma\"), bind_constants=False)\n    len(mod[\"main\"].body.args) == 3\n\ndef test_not_bind_constant_tachikoma():\n    def get_net(prefix, data, out_channel):\n        weight = relay.var(prefix + \"weight\")\n        bn_gamma = relay.var(prefix + \"bn_gamma\")\n        bn_beta = relay.var(prefix + \"bn_beta\")\n        bn_mmean = relay.var(prefix + \"bn_mean\")\n        bn_mvar = relay.var(prefix + \"bn_var\")\n\n        layer = relay.nn.conv2d(\n            data=data, weight=weight, kernel_size=(3, 3), channels=out_channel, padding=(1, 1)\n        )\n        bn_output = relay.nn.batch_norm(layer, bn_gamma, bn_beta, bn_mmean, bn_mvar)\n        out = relay.nn.relu(bn_output[0])\n        return relay.Function(relay.analysis.free_vars(out), out)\n\n    def get_partitoned_mod(mod, params, pattern_table, bind_constants):\n        mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n        remove_bn_pass = tvm.transform.Sequential(\n            [\n                transform.InferType(),\n                transform.SimplifyInference(),\n                transform.FoldConstant(),\n                transform.FoldScaleAxis(),\n            ]\n        )\n        composite_partition = tvm.transform.Sequential(\n            [\n                remove_bn_pass,\n                transform.MergeComposite(pattern_table),\n                transform.AnnotateTarget(\"tachikoma\"),\n                transform.PartitionGraph(bind_constants=bind_constants),\n            ]\n        )\n\n        with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n            return composite_partition(mod)\n\n    data = relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\"))\n    net = get_net(\"block_\", data, 8)\n    mod, params = tvm.relay.testing.create_workload(net)\n\n    mod = get_partitoned_mod(mod, params, get_pattern_table(\"tachikoma\"), bind_constants=True)\n    len(mod[\"main\"].body.args) == 1\n\n    mod = get_partitoned_mod(mod, params, get_pattern_table(\"tachikoma\"), bind_constants=False)\n    len(mod[\"main\"].body.args) == 3\n\n\nif __name__ == \"__main__\":\n    test_multi_node_compiler()\n    test_extern_ccompiler_single_op()\n    test_extern_ccompiler_default_ops()\n    test_extern_ccompiler_multiple_functions()\n    test_extern_ccompiler()\n    test_extern_dnnl()\n    test_extern_tachikoma()\n    test_extern_dnnl_mobilenet()\n    test_extern_tachikoma_mobilenet()\n    test_function_lifting()\n    test_function_lifting_inline()\n    test_constant_propagation()\n    test_multiple_outputs()\n    test_mixed_single_multiple_outputs()\n    test_dnnl_fuse()\n    test_tachikoma_fuse()\n    test_multiple_use_of_an_output()\n    test_duplicate_outputs()\n    test_duplicate_merge_and_tuplegetitem()\n    test_constant_tuples()\n    test_flatten_tuple_output()\n    test_tuple_output_exec()\n    test_extern_opt()\n    test_not_bind_constant()\n    test_not_bind_constant_tachikoma()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_plan_devices.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\n\n\n\"\"\"Unit tests for the PlanDevices pass. We check:\n    - The pass alone given the expected AST, though we need to manually run InferTypes.\n    - The pass is idempotent.\n    - Execution on the VM backend yields the correct result.\"\"\"\n\nimport tvm\nfrom tvm import relay\nfrom tvm.script import tir as T\nimport tvm.testing\nimport numpy as np\nimport os\n\nHOST_DEVICE = tvm.device(\"cpu\")\nHOST_TARGET = tvm.target.Target(\"llvm\")\n\nCPU_DEVICE = tvm.device(\"cpu\")\nCPU_TARGET = tvm.target.Target(\"llvm\").with_host(HOST_TARGET)\n\nGPU_DEVICE = tvm.device(\"cuda\")\nGPU_TARGET = tvm.target.Target(\"cuda\").with_host(HOST_TARGET)\n\nTARGETS = [CPU_TARGET, GPU_TARGET]\n\nHOST = tvm.target.VirtualDevice(HOST_DEVICE, HOST_TARGET)  # device_type=1\nCPU = tvm.target.VirtualDevice(CPU_DEVICE, CPU_TARGET)  # device_type=1\nGPU = tvm.target.VirtualDevice(GPU_DEVICE, GPU_TARGET)  # device_type=2\nDEFAULT = GPU\n\nCPU_SCOPE_A = tvm.target.VirtualDevice(CPU_DEVICE, CPU_TARGET, memory_scope=\"scopeA\")\nCPU_SCOPE_B = tvm.target.VirtualDevice(CPU_DEVICE, CPU_TARGET, memory_scope=\"scopeB\")\n\nCTXT = tvm.transform.PassContext(config={\"relay.fallback_device_type\": DEFAULT.device_type_int})\n\ncore = tvm.IRModule()\ncore.import_from_std(\"core.rly\")\n\nrecover_virtual_device_map = tvm._ffi.get_global_func(\"relay.transform.RecoverVirtualDeviceMap\")\n\n\ndef rewrite_and_assert(in_mod, expected_mod):\n    \"\"\"Manually run the pass and assert it's structurally equals to the expected.\"\"\"\n    config = tvm.target.make_compilation_config(CTXT, TARGETS)\n    actual_mod = relay.transform.InferType()(in_mod)\n    actual_mod = relay.transform.PlanDevices(config)(actual_mod)\n    actual_mod = relay.transform.InferType()(actual_mod)\n    expected_mod = relay.transform.InferType()(expected_mod)\n    if not tvm.ir.structural_equal(actual_mod, expected_mod, True):\n        # Print everything in full so we can see what's going on when things fail.\n        print(\"Input module:\")\n        print(in_mod)\n        print(\"Expected module:\")\n        print(expected_mod)\n        print(\"Actual module:\")\n        print(actual_mod)\n        # Assert again so as to see the actual disagreeing sub-expressions.\n        tvm.ir.assert_structural_equal(actual_mod, expected_mod, True)\n\n\ndef eval_and_assert(in_mod: tvm.IRModule, reference_func, args):\n    \"\"\"Test the standard compilation flow gives us a function which agrees with the Numpy\n    reference implementation.\"\"\"\n    if not tvm.runtime.enabled(\"cuda\"):\n        print(\"Not evaluating since GPU is not available\")\n        return\n    with tvm.transform.PassContext(opt_level=3):\n        compiled = relay.create_executor(\n            \"vm\", mod=in_mod, device=GPU_DEVICE, target=GPU_TARGET\n        ).evaluate()\n        actual = compiled(*args).numpy()\n        expected = reference_func(*args)\n        tvm.testing.assert_allclose(actual, expected)\n\n\ndef rand(shape):\n    return np.random.rand(*shape).astype(\"float32\")\n\n\ndef rands(shape, n):\n    return [rand(shape) for i in range(n)]\n\n\ndef exercise(in_mod: tvm.IRModule, expected_mod: tvm.IRModule, reference_func, args):\n    \"\"\"Test in_mod against expected_mod and reference_func using args.\"\"\"\n    # Correctness\n    rewrite_and_assert(in_mod, expected_mod)\n    # Idempotence\n    rewrite_and_assert(expected_mod, expected_mod)\n    # The VM can compile and possibly even run the module\n    if not (reference_func is None) and not (args is None):\n        eval_and_assert(in_mod, reference_func, args)\n\n\ndef test_plain():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Everything defaults to GPU\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = add(%c, %d);\n              subtract(%0, %1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              %1 = add(%c, %d);\n              subtract(%0, %1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_left_add_on_cpu():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Force some args to be on CPU, rest default to GPU.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = add(%c, %d);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device= meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device= meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %3 = add(%c, %d);\n              subtract(%2, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_left_add_on_cpu_via_copy():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # As for test_left_add_on_cpu, but with an explicit device_copy.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = device_copy(%0, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %2 = add(%c, %d);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %3 = add(%c, %d);\n              subtract(%2, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_left_add_on_cpu_via_copy_as_map():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # As for test_left_add_on_cpu, but with an explicit device_copy.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = device_copy(%0, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %2 = add(%c, %d);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    config = tvm.target.make_compilation_config(CTXT, TARGETS, HOST_TARGET)\n    actual_mod = relay.transform.InferType()(input())\n    actual_mod = relay.transform.PlanDevices(config)(actual_mod)\n    actual_mod = relay.transform.CapturePostDfsIndexInSpans()(actual_mod)\n\n    # Same expected result as for test_left_add_on_cpu, but we'll include indexes to help\n    # the test make sense.\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], // index 0\n                      %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], // index 1\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], // index 2\n                      %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], // index 3\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);                                                            // index 8\n              %1 = on_device(%0,\n                             virtual_device=meta[VirtualDevice][0],\n                             constrain_result=True);                                       // index 9\n              %2 = device_copy(%1,\n                               src_virtual_device=meta[VirtualDevice][0],\n                               dst_virtual_device=meta[VirtualDevice][1]);                 // index 10\n              %3 = add(%c, %d);                                                            // index 11\n              subtract(%2, %3)                                                             // index 12\n            }                                                                              // index 13\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    # Make sure actual matches.\n    tvm.ir.assert_structural_equal(actual_mod, expected(), True)\n\n    # Recover all the inferred virtual devices in map form\n    raw_map = recover_virtual_device_map(actual_mod, actual_mod[\"main\"])\n    # Rewrite the map to be from post-dfs indexes to device types\n    map = {e.span.line: d.device_type for e, d in raw_map.items()}\n    # Now we can express the expected map\n    expected_map = {\n        0: CPU.device_type,  # %a\n        1: CPU.device_type,  # %b\n        2: GPU.device_type,  # %c\n        3: GPU.device_type,  # %d\n        8: CPU.device_type,  # first add\n        9: CPU.device_type,  # on_device\n        10: GPU.device_type,  # device_copy\n        11: GPU.device_type,  # second add\n        12: GPU.device_type,  # subtract\n        13: GPU.device_type,  # @main\n    }\n    assert map == expected_map\n\n\ndef test_both_adds_on_cpu():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = add(%c, %d);\n              %2 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %3 = on_device(%1, virtual_device=meta[VirtualDevice][0]);\n              subtract(%2, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = add(%c, %d);\n              %3 = on_device(%2, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %4 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %5 = device_copy(%3, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              subtract(%4, %5)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_sharing():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # The same add sub-expression is annotated twice.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %3 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %4 = device_copy(%2, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              subtract(%3, %4)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b):\n        x = np.add(a, b)\n        return np.subtract(x, x)\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_let_on_cpu():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # The device for a let-bound expression can flow from uses of the let-bound var.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              let %l = add(%a, %b);\n              let %r = add(%c, %d);\n              %0 = on_device(%l, virtual_device=meta[VirtualDevice][0]);\n              subtract(%0, %r)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%a, %b);\n              let %l = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              let %r = on_device(add(%c, %d), virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %1 = device_copy(%l, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              subtract(%1, %r)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_func_param_on_cpu():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Devices for function parameters flow to call sites.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              let %f = fn (%x, %y) {\n                %0 = add(%x, %y);\n                on_device(%0, virtual_device=meta[VirtualDevice][0])\n              };\n              %1 = %f(%a, %b);\n              %2 = add(%c, %d);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              let %f = fn (%x {virtual_device=meta[VirtualDevice][0]}, %y {virtual_device=meta[VirtualDevice][0]},\n                           virtual_device=meta[VirtualDevice][0]) {\n                add(%x, %y)\n              };\n              %0 = %f(%a, %b);\n              %1 = add(%c, %d);\n              subtract(%0, %1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_func_result_on_cpu():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Devices for call sites flow to function results.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              let %f = fn (%x, %y) {\n                add(%x, %y)\n              };\n              %0 = %f(%a, %b);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = add(%c, %d);\n              subtract(%1, %2)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              let %f = fn (%x {virtual_device=meta[VirtualDevice][0]}, %y {virtual_device=meta[VirtualDevice][0]},\n                           virtual_device=meta[VirtualDevice][0]) {\n                add(%x, %y)\n              };\n              %1 = %f(%a, %b);\n              %2 = on_device(%1, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %3 = device_copy(%2, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %4 = add(%c, %d);\n              subtract(%3, %4)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.add(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_higher_order():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # The constraint on %a flows back to %y via %f and %h\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) {\n              let %f = fn (%g) {\n                fn (%a) {\n                  %0 = on_device(%a, virtual_device=meta[VirtualDevice][0]);\n                  %1 = %g(%0);\n                  add(%1, %x)\n                }\n              };\n              let %h = fn (%b) {\n                negative(%b)\n              };\n              %2 = %f(%h);\n              %3 = %2(%y);\n              subtract(%x, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              let %f = fn (%g {virtual_device=meta[VirtualDevice][1]}, virtual_device=meta[VirtualDevice][1]) {\n                fn (%a {virtual_device=meta[VirtualDevice][0]}, virtual_device=meta[VirtualDevice][1]) {\n                  %0 = device_copy(%a, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n                  %1 = %g(%0);\n                  add(%1, %x)\n                }\n              };\n              let %h = fn (%b  {virtual_device=meta[VirtualDevice][1]}, virtual_device=meta[VirtualDevice][1]) {\n                negative(%b)\n              };\n              %2 = %f(%h);\n              %3 = %2(%y);\n              subtract(%x, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        def f(g):\n            return lambda a: np.add(g(a), x)\n\n        def h(b):\n            return np.negative(b)\n\n        return np.subtract(x, f(h)(y))\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_function_in_tuple():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Since %f ends up in a tuple its argument and result is forced to be on the CPU\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) {\n              let %f = fn (%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) {\n                %0 = on_device(%b, virtual_device=meta[VirtualDevice][0]);\n                add(%a, %0)\n              };\n              let %t = (%f, %x);\n              %1 = %t.1;\n              %2 = %t.0;\n              %2(%1, %y)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              let %f = fn (%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                           virtual_device=meta[VirtualDevice][0]) {\n                add(%a, %b)\n              };\n              let %t = on_device((%f, %x), virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %0 = %t.1;\n              %1 = %t.0;\n              %1(%0, %y)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        return np.add(x, y)\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_device_copy():\n    const = rand((5, 7))\n    metatable = {\"VirtualDevice\": [CPU, GPU], \"relay.Constant\": [relay.const(const)]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32]) {\n              %0 = device_copy(%x, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              add(%0, meta[relay.Constant][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = device_copy(%x, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              add(%0, meta[relay.Constant][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x):\n        return np.add(x, const)\n\n    exercise(input(), expected(), ref, rands((5, 7), 1))\n\n\ndef test_shape_of():\n    metatable = {\"VirtualDevice\": [HOST, GPU]}\n\n    # We need to use constrain_result=True in the on_device call so that the tensor will be on the GPU. Otherwise the\n    # result defaults to the result device for @main which is the CPU, thus forcing a copy.\n    # TODO(mbs): Perhaps the defaulting heuristics are being too clever?\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(?, ?), float32]) {\n              %0 = on_device(%x, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              vm.shape_of(%0, dtype=\"int64\")\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(?, ?), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              vm.shape_of(%x, dtype=\"int64\")\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x):\n        return x.shape\n\n    exercise(input(), expected(), ref, rands((5, 7), 1))\n\n\ndef test_alloc_storage():\n    metatable = {\"VirtualDevice\": [HOST, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%size: int64, %alignment: int64) {\n              memory.alloc_storage(%size, %alignment, virtual_device=meta[VirtualDevice][1])\n            }\n        \"\"\",\n            \"from_string\",\n            core,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%size {virtual_device=meta[VirtualDevice][0]}: int64, %alignment {virtual_device=meta[VirtualDevice][0]}: int64,\n                      virtual_device=meta[VirtualDevice][1]) {\n              memory.alloc_storage(%size, %alignment, virtual_device=meta[VirtualDevice][1])\n            }\n        \"\"\",\n            \"from_string\",\n            core,\n            metatable,\n        )\n\n    # Don't try to execute, too fiddly to setup.\n    exercise(input(), expected(), None, None)\n\n\ndef test_alloc_tensor():\n    shape = np.array([3, 2])\n    metatable = {\n        \"VirtualDevice\": [HOST, GPU],\n        \"relay.Constant\": [relay.const(shape, dtype=\"int64\")],\n    }\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%sto: Storage[]) {\n              memory.alloc_tensor(%sto, 0, meta[relay.Constant][0],\n                                  const_shape=meta[relay.Constant][0], assert_shape=[])\n            }\n        \"\"\",\n            \"from_string\",\n            core,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%sto {virtual_device=meta[VirtualDevice][1]}: Storage[], virtual_device=meta[VirtualDevice][1]) {\n              %0 = on_device(0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %1 = on_device(meta[relay.Constant][0], virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              memory.alloc_tensor(%sto, %0, %1, const_shape=meta[relay.Constant][0], assert_shape=[])\n            }\n        \"\"\",\n            \"from_string\",\n            core,\n            metatable,\n        )\n\n    # Don't try to execute, too fiddly to setup.\n    exercise(input(), expected(), None, None)\n\n\ndef test_reshape_tensor():\n    newshape = [2, 4, 2]\n    metatable = {\n        \"VirtualDevice\": [HOST, GPU],\n        \"relay.Constant\": [relay.const(newshape, dtype=\"int64\")],\n    }\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(2, 8), float32]) {\n              vm.reshape_tensor(%x, meta[relay.Constant][0], newshape=[2, 4, 2])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(2, 8), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = on_device(meta[relay.Constant][0], virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              vm.reshape_tensor(%x, %0, newshape=[2, 4, 2])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x):\n        return np.reshape(x, newshape)\n\n    exercise(input(), expected(), ref, rands((2, 8), 1))\n\n\ndef test_dynamic_input():\n    metatable = {\"VirtualDevice\": [GPU]}\n\n    # There's nothing special about inferring devices for partially unknown types.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x0: Tensor[(?, ?), float32], %x1: Tensor[(?, ?), float32]) {\n              add(%x0, %x1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x0 {virtual_device=meta[VirtualDevice][0]}: Tensor[(?, ?), float32], %x1 {virtual_device=meta[VirtualDevice][0]}: Tensor[(?, ?), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              add(%x0, %x1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x0, x1):\n        return np.add(x0, x1)\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_redundant_annotation():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32], %z: Tensor[(5, 7), float32]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = subtract(%1, %z);\n              %3 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              add(%2, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %z {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %3 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %4 = subtract(%2, %z);\n              %5 = device_copy(%3, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              add(%4, %5)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y, z):\n        a = np.add(x, y)\n        return np.add(np.subtract(a, z), a)\n\n    exercise(input(), expected(), ref, rands((5, 7), 3))\n\n\ndef test_annotate_expr():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32], %z: Tensor[(5, 7), float32]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][1]);\n              %2 = subtract(%1, %z);\n              on_device(%2, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %z {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              subtract(%2, %z)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y, z):\n        return np.subtract(np.add(x, y), z)\n\n    exercise(input(), expected(), ref, rands((5, 7), 3))\n\n\ndef test_annotate_all():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32], %z: Tensor[(5, 7), float32]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = subtract(%1, %z);\n              on_device(%2, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %z {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = add(%x, %y);\n              subtract(%0, %z)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y, z):\n        return np.subtract(np.add(x, y), z)\n\n    exercise(input(), expected(), ref, rands((5, 7), 3))\n\n\ndef test_conv_network():\n    r\"\"\"The network and devices are as follows:\n    data1     data2    <--- CPU\n      |         |\n    conv2d    conv2d   <--- CPU\n       \\       /\n        \\     /\n          add          <--- GPU\n           |\n         conv2d        <--- CPU\n           |\n        <result>       <--- CPU\n    \"\"\"\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%data1: Tensor[(1, 64, 56, 56), float32], %data2: Tensor[(1, 64, 56, 56), float32],\n                      %weight: Tensor[(64, 64, 3, 3), float32]) {\n              %0 = nn.conv2d(%data1, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n              %1 = nn.conv2d(%data2, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n              %2 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %3 = on_device(%1, virtual_device=meta[VirtualDevice][0]);\n              %4 = add(%2, %3);\n              %5 = on_device(%4, virtual_device=meta[VirtualDevice][1]);\n              %6 = nn.conv2d(%5, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n              on_device(%6, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%data1 {virtual_device=meta[VirtualDevice][0]}: Tensor[(1, 64, 56, 56), float32], %data2 {virtual_device=meta[VirtualDevice][0]}: Tensor[(1, 64, 56, 56), float32],\n                      %weight {virtual_device=meta[VirtualDevice][0]}: Tensor[(64, 64, 3, 3), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = nn.conv2d(%data1, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = nn.conv2d(%data2, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3]);\n              %3 = on_device(%2, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %4 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %5 = device_copy(%3, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %6 = add(%4, %5);\n              %7 = on_device(%6, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %8 = device_copy(%7, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              nn.conv2d(%8, %weight, padding=[1, 1, 1, 1], channels=64, kernel_size=[3, 3])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    # Don't try to execute, we don't have a reference conv2d\n    exercise(input(), expected(), None, None)\n\n\ndef test_tuple_get_item():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Note that the device copy should be placed after projection rather than before. This is handled by\n    # a heuristic in the pass.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(3, 3, 4), float32]) {\n              let %t = split(%x, indices_or_sections=3);\n              %0 = on_device(%t, virtual_device=meta[VirtualDevice][0]);\n              %1 = on_device(%t, virtual_device=meta[VirtualDevice][0]);\n              %2 = %0.0;\n              %3 = %1.1;\n              %4 = subtract(%2, %3);\n              on_device(%4, virtual_device=meta[VirtualDevice][1])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(3, 3, 4), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = split(%x, indices_or_sections=3);\n              let %t = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %1 = %t.0;\n              %2 = on_device(%1, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %3 = %t.1;\n              %4 = on_device(%3, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %5 = device_copy(%2, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %6 = device_copy(%4, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              subtract(%5, %6)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x):\n        t = np.split(x, 3)\n        return np.subtract(t[0], t[1])\n\n    exercise(input(), expected(), ref, rands((3, 3, 4), 1))\n\n\ndef test_propogation():\n    r\"\"\" The network and devices are as follows:\n                  x             <--- CPU\n                  |\n                negative        <--- CPU\n                /   \\\n          negative  negative    <--- GPU\n                \\   /\n                 add            <--- GPU\n                  |\n                negative        <--- CPU\n                  |\n               <result>         <--- CPU\n    \"\"\"\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32]) {\n              %0 = negative(%x);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %2 = negative(%1);\n              %3 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %4 = negative(%3);\n              %5 = on_device(%2, virtual_device=meta[VirtualDevice][1]);\n              %6 = on_device(%4, virtual_device=meta[VirtualDevice][1]);\n              %7 = add(%5, %6);\n              %8 = on_device(%7, virtual_device=meta[VirtualDevice][1]);\n              %9 = negative(%8);\n              on_device(%9, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = negative(%x);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %3 = on_device(%0, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %4 = device_copy(%3, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %5 = negative(%2);\n              %6 = negative(%4);\n              %7 = add(%5, %6);\n              %8 = on_device(%7, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %9 = device_copy(%8, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              negative(%9)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x):\n        y = np.negative(x)\n        return np.negative(np.add(np.negative(y), np.negative(y)))\n\n    exercise(input(), expected(), ref, rands((5, 7), 1))\n\n\ndef test_fusible_network():\n    r\"\"\" The network is as follows:\n               x     y      <--- GPU\n                \\   /\n                 add        <--- GPU\n                /   \\\n           negative  \\      <--- CPU\n              \\       \\\n               \\  negative  <--- GPU\n                \\   /\n                 add        <--- GPU\n                  |\n               negative     <--- CPU\n                  |\n               <result>     <--- CPU\n    \"\"\"\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][1]);\n              %2 = negative(%1);\n              %3 = on_device(%2, virtual_device=meta[VirtualDevice][0]);\n              %4 = negative(%0);\n              %5 = add(%3, %4);\n              %6 = on_device(%5, virtual_device=meta[VirtualDevice][1]);\n              %7 = negative(%6);\n              on_device(%7, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = add(%x, %y);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %2 = device_copy(%1, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              %3 = negative(%2);\n              %4 = on_device(%3, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %5 = device_copy(%4, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              %6 = negative(%0);\n              %7 = add(%5, %6);\n              %8 = on_device(%7, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %9 = device_copy(%8, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              negative(%9)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        z = np.add(x, y)\n        return np.negative(np.add(np.negative(z), np.negative(z)))\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_unpropagatable_graph():\n    r\"\"\"The network is as follows:\n    a      b            <--- CPU\n    \\     /\n     \\   /   c     d    <--- GPU\n      \\ /    \\     /\n      add     \\   /     <--- CPU\n       \\       \\ /\n        \\    multiply   <--- GPU\n         \\     /\n        subtract        <--- CPU\n           |\n        <result>        <--- CPU\n    \"\"\"\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n              %0 = add(%a, %b);\n              %1 = multiply(%c, %d);\n              %2 = on_device(%0, virtual_device=meta[VirtualDevice][0]);\n              %3 = on_device(%1, virtual_device=meta[VirtualDevice][1]);\n              %4 = subtract(%2, %3);\n              on_device(%4, virtual_device=meta[VirtualDevice][0])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      %c {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %d {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = multiply(%c, %d);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %2 = add(%a, %b);\n              %3 = device_copy(%1, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][0]);\n              subtract(%2, %3)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(a, b, c, d):\n        return np.subtract(np.add(a, b), np.multiply(c, d))\n\n    exercise(input(), expected(), ref, rands((5, 7), 4))\n\n\ndef test_conditional():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # The conditional is over a function type, thus exercising the first-order/higher-order domain handling.\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: bool, %y: Tensor[(5, 7), float32], %z: Tensor[(5, 7), float32]) {\n              let %f = fn (%a) {\n                %0 = on_device(%y, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n                add(%a, %0)\n              };\n              let %g = fn (%a1) {\n                subtract(%a1, %y)\n              };\n              let %h = if (%x) {\n                %f\n              } else {\n                %g\n              };\n              %h(%z)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: bool, %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %z {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              let %f = fn (%a {virtual_device=meta[VirtualDevice][0]}, virtual_device=meta[VirtualDevice][0]) {\n                add(%a, %y)\n              };\n              let %g = fn (%a1 {virtual_device=meta[VirtualDevice][0]}, virtual_device=meta[VirtualDevice][0]) {\n                subtract(%a1, %y)\n              };\n              let %h = on_device(if (%x) {\n                %f\n              } else {\n                %g\n              }, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %h(%z)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y, z):\n        def f(a):\n            return np.add(a, y)\n\n        def g(a):\n            return np.subtract(a, y)\n\n        h = f if x else g\n        return h(z)\n\n    exercise(input(), expected(), ref, [True, rand((5, 7)), rand((5, 7))])\n\n\ndef test_global():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @f(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n              %0 = on_device(%b, virtual_device=meta[VirtualDevice][0]);\n              add(%a, %0)\n            }\n\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) -> Tensor[(5, 7), float32] {\n              @f(%y, %x)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @f(%a {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                   virtual_device=meta[VirtualDevice][1]) -> Tensor[(5, 7), float32] {\n              %0 = device_copy(%b, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              add(%a, %0)\n            }\n\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) -> Tensor[(5, 7), float32] {\n              @f(%y, %x)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        def f(a, b):\n            return np.add(a, b)\n\n        return f(x, y)\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_ref():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(5, 7), float32], %y: Tensor[(5, 7), float32]) {\n              let %r = ref(%x);\n              %0 = on_device(%y, virtual_device=meta[VirtualDevice][0]);\n              ref_write(%r, %0);\n              %1 = ref_read(%r);\n              add(%x, %1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              let %r = on_device(ref(%x), virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %0 = device_copy(%y, src_virtual_device=meta[VirtualDevice][0], dst_virtual_device=meta[VirtualDevice][1]);\n              on_device(ref_write(%r, %0), virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              %1 = ref_read(%r);\n              add(%x, %1)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        r = {\"value\": x}\n        r[\"value\"] = y\n        return np.add(x, r[\"value\"])\n\n    # Don't try to execute, no backend currently supports both hetrogeneous devices and references.\n    exercise(input(), expected(), None, None)\n\n\ndef test_adt():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            type List[A] {\n              Cons(A, List[A]),\n              Nil,\n            }\n            def @main(%x : Tensor[(5, 7), float32], %y : Tensor[(5, 7), float32]) {\n              %0 = on_device(%y, virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              %1 = Nil;\n              %2 = Cons(%0, %1);\n              let %l = Cons(%x, %2);\n              match? (%l) {\n                Cons(%z, _) => %z\n              }\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            type List[A] {\n              Cons(A, List[A]),\n              Nil,\n            }\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %y {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][0]) {\n              %0 = Nil;\n              %1 = Cons(%y, %0);\n              let %l = on_device(Cons(%x, %1), virtual_device=meta[VirtualDevice][0], constrain_result=True);\n              match? (%l) {\n                Cons(%z, _) => %z\n              }\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def ref(x, y):\n        l = [x, y]\n        return l[0]\n\n    exercise(input(), expected(), ref, rands((5, 7), 2))\n\n\ndef test_free_on_device():\n    \"\"\"Tests that the 'free' form of on_device (ie with constrain_body=False) can be used to allow\n    a device_copy to be inserted if necessary, but otherwise does not prevent the flow of\n    device information.\"\"\"\n    metatable = {\n        \"VirtualDevice\": [\n            CPU,  # no memory scope constraint\n            CPU_SCOPE_A,  # constrain to scopeA\n            CPU_SCOPE_B,\n        ]\n    }  # constrain to scopeB\n\n    # Everything defaults to GPU\n    def input():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @on_scope_b(%x {virtual_device=meta[VirtualDevice][2]}: Tensor[(5, 7), float32],\n                            virtual_device=meta[VirtualDevice][2]) -> Tensor[(5, 7), float32] {\n              %x\n            }\n            def @main(%a {virtual_device=meta[VirtualDevice][0]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %c {virtual_device=meta[VirtualDevice][2]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              // %a's memory scope is unconstrained, so will take on \"scopeB\" and on_device has no effect\n              %0 = @on_scope_b(on_device(%a, virtual_device=meta[VirtualDevice][0], constrain_body=False));\n              // %b's memory scope is \"scopeA\", so will require a \"scopeA\"->\"scopeB\" copy.\n              %1 = @on_scope_b(on_device(%b, virtual_device=meta[VirtualDevice][0], constrain_body=False));\n              // %c's memory scope is \"scopeB\", so no copy required.\n              %2 = @on_scope_b(on_device(%c, virtual_device=meta[VirtualDevice][0], constrain_body=False));\n              // result's memory scope is is on \"scopeA\", so will require a \"scopeB\"->\"scopeA\" copy.\n              %3 = add(add(%0, %1), %2);\n              on_device(%3, virtual_device=meta[VirtualDevice][0], constrain_body=False)\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    def expected():\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @on_scope_b(%x {virtual_device=meta[VirtualDevice][2]}: Tensor[(5, 7), float32],\n                            virtual_device=meta[VirtualDevice][2]) -> Tensor[(5, 7), float32] {\n              %x\n            }\n            def @main(%a {virtual_device=meta[VirtualDevice][2]}: Tensor[(5, 7), float32], %b {virtual_device=meta[VirtualDevice][1]}: Tensor[(5, 7), float32], %c {virtual_device=meta[VirtualDevice][2]}: Tensor[(5, 7), float32],\n                      virtual_device=meta[VirtualDevice][1]) {\n              %0 = @on_scope_b(%a);\n              %1 = device_copy(%b, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][2]);\n              %2 = @on_scope_b(%1);\n              %3 = @on_scope_b(%c);\n              %4 = add(add(%0, %2), %3);\n              %5 = on_device(%4, virtual_device=meta[VirtualDevice][2], constrain_result=True);\n              device_copy(%5, src_virtual_device=meta[VirtualDevice][2], dst_virtual_device=meta[VirtualDevice][1])\n            }\n        \"\"\",\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    exercise(input(), expected(), None, None)\n\n\ndef test_lowered():\n    \"\"\"\n    Tests propagation of memory scopes from PrimFuncs and insertion\n    of device_copies to mediate any scope changes.\n    \"\"\"\n\n    @T.prim_func\n    def input_gem(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128], scope=\"scopeA\")  # will flow out\n        B = T.match_buffer(b, [128, 128], scope=\"\")  # will flow in\n        C = T.match_buffer(c, [128, 128], scope=\"scopeB\")  # will flow out\n        D = T.match_buffer(d, [128, 128], scope=\"scopeA\")  # will flow out\n\n        for i, j, k in T.grid(128, 128, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    D[vi, vj] = C[vi, vj]\n                D[vi, vj] = D[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    @T.prim_func\n    def expected_gem(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128], scope=\"scopeA\")\n        B = T.match_buffer(b, [128, 128], scope=\"scopeB\")  # flowed in\n        C = T.match_buffer(c, [128, 128], scope=\"scopeB\")\n        D = T.match_buffer(d, [128, 128], scope=\"scopeA\")\n\n        for i, j, k in T.grid(128, 128, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    D[vi, vj] = C[vi, vj]\n                D[vi, vj] = D[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    metatable = {\n        \"VirtualDevice\": [\n            CPU,  # meta[VirtualDevice][0], no memory scope\n            CPU_SCOPE_A,  # meta[VirtualDevice][1], \"scopeA\"\n            CPU_SCOPE_B,\n        ]\n    }  # meta[VirtualDevice][2], \"scopeB\"\n    gem_ty = relay.FuncType(\n        [\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n            relay.TensorType((128, 128), \"float32\"),\n        ],\n        relay.TensorType((128, 128), \"float32\"),\n    )\n    gem_gv = relay.GlobalVar(\"gem\", type_annot=gem_ty)\n\n    def input():\n        mod = tvm.ir.IRModule()\n        mod[gem_gv] = input_gem\n        # - %x on CPU, no memory scope constraint, so will be constrained by first param of gem to \"scopeA\".\n        # - %y on CPU \"scopeB\", so will flow in to second param of gem.\n        # - %z on CPU \"scopeA\", so will clash with third param of gem and will need device_copy.\n        # - result on CPU \"scopeB\", but result of gem on \"scopeA\" so will need device_copy\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][0]}: Tensor[(128, 128), float32],\n                      %y {virtual_device=meta[VirtualDevice][2]}: Tensor[(128, 128), float32],\n                      %z {virtual_device=meta[VirtualDevice][1]}: Tensor[(128, 128), float32],\n                      virtual_device=meta[VirtualDevice][2]) {\n              call_lowered(@gem, (%x, %y, %z))\n            }\n            \"\"\",\n            \"from_string\",\n            mod,\n            metatable,\n        )\n\n    def expected():\n        mod = tvm.ir.IRModule()\n        mod[gem_gv] = expected_gem\n        # - %x now on CPU \"scopeA\", no device_copy needed.\n        # - %y still on CPU \"scopeB\", no device_copy needed.\n        # - %z still on CPU \"scopeA\", needs device_copy to \"scopeB\".\n        # - result still on CPU \"scopeB\", needs device_copy  from \"scopeA\".\n        return tvm.parser.parse(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x {virtual_device=meta[VirtualDevice][1]}: Tensor[(128, 128), float32],\n                      %y {virtual_device=meta[VirtualDevice][2]}: Tensor[(128, 128), float32],\n                      %z {virtual_device=meta[VirtualDevice][1]}: Tensor[(128, 128), float32],\n                      virtual_device=meta[VirtualDevice][2]) {\n              %0 = device_copy(%z, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][2]);\n              %1 = on_device(%0, virtual_device=meta[VirtualDevice][2], constrain_result=True);\n              %2 = call_lowered(@gem, (%x, %y, %1));\n              %3 = on_device(%2, virtual_device=meta[VirtualDevice][1], constrain_result=True);\n              device_copy(%3, src_virtual_device=meta[VirtualDevice][1], dst_virtual_device=meta[VirtualDevice][2])\n            }\n            \"\"\",\n            \"from_string\",\n            mod,\n            metatable,\n        )\n\n    exercise(input(), expected(), None, None)\n\n\ndef test_stack_overflow():\n    metatable = {\"VirtualDevice\": [CPU, GPU]}\n\n    # Everything defaults to GPU\n    def input():\n        tmp = \"test_stack_overflow_input.txt\"\n        mod = \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32], %b: Tensor[(5, 7), float32],\n                      %c: Tensor[(5, 7), float32], %d: Tensor[(5, 7), float32]) {\n            %0 = add(%a, %b);\n            %1 = add(%c, %d);\n            \"\"\"\n\n        end = 1555\n        for i in range(2, end):\n            s1 = \"\\n\\t\" + \"%\" + str(i) + \" = add(%\" + str(i - 1) + \", %\" + str(i - 2) + \");\"\n            mod += s1\n        mod += \"\\n\\t\" + \"add(%\" + str(end - 1) + \", %\" + str(end - 2) + \")\"\n        mod += \"\\n\\t}\"\n\n        return tvm.parser.parse(\n            mod,\n            \"from_string\",\n            None,\n            metatable,\n        )\n\n    config = tvm.target.make_compilation_config(CTXT, TARGETS)\n    actual_mod = relay.transform.InferType()(input())\n    actual_mod = relay.transform.PlanDevices(config)(actual_mod)\n    relay.transform.InferType()(actual_mod)\n\n\ndef test_primitive():\n    \"\"\"Annotations on Primitive functions should be accepted, even though the body\n    of the Primitive function is not considered during PlanDevices.\"\"\"\n    global_virtual_device = tvm.target.VirtualDevice(memory_scope=\"global\")\n    texture_virtual_device = tvm.target.VirtualDevice(memory_scope=\"global.texture\")\n    metatable = {\n        \"VirtualDevice\": [\n            global_virtual_device,\n            texture_virtual_device,\n        ]\n    }\n\n    mod = tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%data1: Tensor[(1, 32, 40, 40), float32],\n                  %data2: Tensor[(1, 32, 40, 40), float32]) {\n          %0 = fn (%a, Primitive=1) {\n            layout_transform(%a, src_layout=\"NCHW\", dst_layout=\"NCHW4c\")\n          };\n          %1 = %0(%data1);\n          %3 = %0(%data2);\n          %5 = fn (%a {virtual_device=meta[VirtualDevice][0]},  // global\n                   %b {virtual_device=meta[VirtualDevice][0]},  // global\n                   virtual_device=meta[VirtualDevice][1],       // texture\n                   Primitive=1) {\n            add(%a, %b)\n          };\n          %6 = %5(%1, %3);\n          %10 = fn (%a,\n                    virtual_device=meta[VirtualDevice][0],      // global\n                    Primitive=1) {\n            layout_transform(%a, src_layout=\"NCHW4c\", dst_layout=\"NCHW\")\n          };\n          %10(%6)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n    print(mod)\n\n    config = tvm.target.make_compilation_config(CTXT, GPU_TARGET)\n    mod = relay.transform.InferType()(mod)\n    # PlanDevices should succeed.\n    mod = relay.transform.PlanDevices(config)(mod)\n    print(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_qnn_legalize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test legalize pass\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\n\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\nfrom tvm.relay import transform, analysis\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\ndef alpha_equal(x, y):\n    \"\"\"\n    Wrapper around alpha equality which ensures that\n    the hash function respects equality.\n    \"\"\"\n    x = x[\"main\"]\n    y = y[\"main\"]\n    return tvm.ir.structural_equal(x, y) and tvm.ir.structural_hash(x) == tvm.ir.structural_hash(y)\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_qnn_legalize():\n    \"\"\"Test directly replacing an operator with a new one\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56), dtype=\"int8\")\n        y = relay.qnn.op.requantize(\n            x,\n            input_scale=relay.const(1, \"float32\"),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(1, \"float32\"),\n            output_zero_point=relay.const(0, \"int32\"),\n            out_dtype=\"int8\",\n        )\n        y = relay.Function([x], y)\n        return y\n\n    def legalize_qnn_requantize(attrs, inputs, types):\n        data = inputs[0]\n        data = relay.add(relay.const(0, \"int8\"), data)\n        y = relay.qnn.op.requantize(\n            data,\n            input_scale=relay.const(1, \"float32\"),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(1, \"float32\"),\n            output_zero_point=relay.const(0, \"int32\"),\n            out_dtype=\"int8\",\n        )\n        return y\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 64, 56, 56), dtype=\"int8\")\n        y = relay.add(relay.const(0, \"int8\"), x)\n        z = relay.qnn.op.requantize(\n            y,\n            input_scale=relay.const(1, \"float32\"),\n            input_zero_point=relay.const(0, \"int32\"),\n            output_scale=relay.const(1, \"float32\"),\n            output_zero_point=relay.const(0, \"int32\"),\n            out_dtype=\"int8\",\n        )\n        z = relay.Function([x], z)\n        return z\n\n    a = before()\n\n    with TempOpAttr(\"qnn.requantize\", \"FTVMQnnLegalize\", legalize_qnn_requantize):\n\n        # Check that Relay Legalize does not change the graph.\n        a = run_opt_pass(a, relay.transform.Legalize())\n        b = run_opt_pass(before(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n        # Check that QNN Legalize modifies the graph.\n        a = run_opt_pass(a, relay.qnn.transform.Legalize())\n        b = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(a, b), \"Actual = \\n\" + str(a)\n\n\ndef test_qnn_legalize_qnn_conv2d():\n    def _get_mod(data_dtype, kernel_dtype):\n        data_shape = (1, 64, 256, 256)\n        kernel_shape = (128, 64, 3, 3)\n        data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n        kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n        func = relay.qnn.op.conv2d(\n            data,\n            kernel,\n            input_zero_point=relay.const(1, \"int32\"),\n            kernel_zero_point=relay.const(1, \"int32\"),\n            input_scale=relay.const(1.0, \"float32\"),\n            kernel_scale=relay.const(1.0, \"float32\"),\n            kernel_size=(3, 3),\n            channels=kernel_shape[0],\n            strides=(1, 1),\n            dilation=(1, 1),\n            out_dtype=\"int32\",\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n\n        mod = relay.Function(relay.analysis.free_vars(func), func)\n        mod = tvm.IRModule.from_expr(mod)\n        return mod\n\n    # Check uint8 x uint8 and int8 x int8 transformation\n    for dtype in (\"uint8\", \"int8\"):\n        mod = _get_mod(dtype, dtype)\n\n        #############################################################\n        # Check transformations for platforms with fast Int8 support.\n        #############################################################\n        # Check that Intel VNNI gets picked up.\n        with tvm.target.Target(\"llvm -mcpu=skylake-avx512\"):\n            mod = relay.transform.InferType()(mod)\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn.conv2d\" in legalized_mod.astext()\n\n        # Since same dtype, there should not be any transformation\n        with tvm.target.Target(\n            \"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\"\n        ):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert tvm.ir.structural_equal(mod, legalized_mod)\n\n        ################################################################\n        # Check transformations for platforms without fast Int8 support.\n        ################################################################\n        # Older Intel versions.\n        with tvm.target.Target(\"llvm\"):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n        # Older ARM vesions.\n        with tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\"):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    # Check uint8 x int8 transformation\n    mod = _get_mod(\"uint8\", \"int8\")\n    #############################################################\n    # Check transformations for platforms with fast Int8 support.\n    #############################################################\n    # Check no transformation for Intel VNNI.\n    with tvm.target.Target(\"llvm -mcpu=skylake-avx512\"):\n        mod = relay.transform.InferType()(mod)\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert tvm.ir.structural_equal(mod, legalized_mod)\n\n    # ARM - so check that transformation has happened.\n    with tvm.target.Target(\n        \"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\"\n    ):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn.conv2d\" in legalized_mod.astext()\n\n    ################################################################\n    # Check transformations for platforms without fast Int8 support.\n    ################################################################\n    # Older Intel versions.\n    with tvm.target.Target(\"llvm\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    # Older ARM vesions.\n    with tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    ###########################################\n    # Check transformations for CUDA platforms.\n    ###########################################\n    with tvm.target.Target(\"cuda\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" in legalized_mod.astext()\n\n\ndef test_qnn_legalize_qnn_dense():\n    def _get_mod(data_dtype, kernel_dtype):\n        data_shape = (10, 3)\n        kernel_shape = (20, 3)\n        data = relay.var(\"data\", shape=data_shape, dtype=data_dtype)\n        kernel = relay.var(\"kernel\", shape=kernel_shape, dtype=kernel_dtype)\n        func = relay.qnn.op.dense(\n            data,\n            kernel,\n            input_zero_point=relay.const(1, \"int32\"),\n            kernel_zero_point=relay.const(1, \"int32\"),\n            input_scale=relay.const(1, \"float32\"),\n            kernel_scale=relay.const(1, \"float32\"),\n            units=kernel_shape[0],\n            out_dtype=\"int32\",\n        )\n\n        mod = relay.Function(relay.analysis.free_vars(func), func)\n        mod = tvm.IRModule.from_expr(mod)\n        return mod\n\n    # Check uint8 x uint8 and int8 x int8 transformation\n    for dtype in (\"uint8\", \"int8\"):\n        mod = _get_mod(dtype, dtype)\n\n        #############################################################\n        # Check transformations for platforms with fast Int8 support.\n        #############################################################\n        # Check that Intel VNNI gets picked up.\n        with tvm.target.Target(\"llvm -mcpu=skylake-avx512\"):\n            mod = relay.transform.InferType()(mod)\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn.dense\" in legalized_mod.astext()\n\n        # Since same dtype, there should not be any transformation\n        with tvm.target.Target(\n            \"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\"\n        ):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert tvm.ir.structural_equal(mod, legalized_mod)\n\n        ################################################################\n        # Check transformations for platforms without fast Int8 support.\n        ################################################################\n        # Older Intel versions.\n        with tvm.target.Target(\"llvm\"):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n        # Older ARM vesions.\n        with tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\"):\n            legalized_mod = relay.qnn.transform.Legalize()(mod)\n            assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    # Check uint8 x int8 transformation\n    mod = _get_mod(\"uint8\", \"int8\")\n    #############################################################\n    # Check transformations for platforms with fast Int8 support.\n    #############################################################\n    # Check no transformation for Intel VNNI.\n    with tvm.target.Target(\"llvm -mcpu=skylake-avx512\"):\n        mod = relay.transform.InferType()(mod)\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert tvm.ir.structural_equal(mod, legalized_mod)\n\n    # ARM - so check that transformation has happened.\n    with tvm.target.Target(\n        \"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu -mattr=+v8.2a,+dotprod\"\n    ):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn.dense\" in legalized_mod.astext()\n\n    ################################################################\n    # Check transformations for platforms without fast Int8 support.\n    ################################################################\n    # Older Intel versions.\n    with tvm.target.Target(\"llvm\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    # Older ARM vesions.\n    with tvm.target.Target(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" not in legalized_mod.astext()\n\n    ###########################################\n    # Check transformations for CUDA platforms.\n    ###########################################\n    with tvm.target.Target(\"cuda\"):\n        legalized_mod = relay.qnn.transform.Legalize()(mod)\n        assert \"cast\" in legalized_mod.astext() and \"qnn\" in legalized_mod.astext()\n\n\nif __name__ == \"__main__\":\n    test_qnn_legalize()\n    test_qnn_legalize_qnn_conv2d()\n    test_qnn_legalize_qnn_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_remove_unused_functions.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.prelude import Prelude\n\n\ndef test_remove_all_prelude_functions():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    x = relay.var(\"x\", shape=(1, 16))\n    mod[\"main\"] = relay.Function([x], x)\n    mod = relay.transform.RemoveUnusedFunctions()(mod)\n    l = set([x[0].name_hint for x in mod.functions.items()])\n    assert l == set([\"main\"])\n\n\ndef test_remove_all_prelude_functions_but_referenced_functions():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    x = relay.var(\"x\", shape=(1, 16))\n    id_func = relay.Function([x], x)\n    id_name = relay.GlobalVar(\"id_func\")\n    mod[id_name] = id_func\n\n    mod[\"main\"] = relay.Function([x], id_name(x))\n    mod = relay.transform.RemoveUnusedFunctions()(mod)\n    l = set([x[0].name_hint for x in mod.functions.items()])\n    assert l == set([\"id_func\", \"main\"])\n\n\ndef test_keep_only_referenced_prelude_functions():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n    hd = p.mod.get_global_var(\"hd\")\n    tl = p.mod.get_global_var(\"tl\")\n    l = nil()\n    for i in [4, 3, 2, 1, 0]:\n        l = cons(relay.const(i), l)\n    body = hd(tl(tl(l)))\n    mod[\"main\"] = relay.Function([], body)\n    mod = relay.transform.RemoveUnusedFunctions()(mod)\n    l = set([x[0].name_hint for x in mod.functions.items()])\n    assert l == set([\"tl\", \"hd\", \"main\"])\n\n\ndef test_multiple_entry_functions():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n    hd = p.mod.get_global_var(\"hd\")\n    tl = p.mod.get_global_var(\"tl\")\n    l = nil()\n    for i in [4, 3, 2, 1, 0]:\n        l = cons(relay.const(i), l)\n    body = hd(tl(tl(l)))\n    mod[\"main1\"] = relay.Function([], body)\n\n    x = relay.var(\"x\", shape=(1, 16))\n    id_func = relay.Function([x], x)\n    id_name = relay.GlobalVar(\"id_func\")\n    mod[id_name] = id_func\n    mod[\"main2\"] = relay.Function([x], id_name(x))\n    mod = relay.transform.RemoveUnusedFunctions([\"main1\", \"main2\"])(mod)\n    l = set([x[0].name_hint for x in mod.functions.items()])\n    assert l == set([\"tl\", \"hd\", \"main2\", \"id_func\", \"main1\"])\n\n\ndef test_globalvar_as_call_arg():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    tensor_array = p.get_global_var(\"tensor_array\", \"int32\")\n    tensor1 = p.get_ctor(p.get_name(\"tensor_t\", \"int32\"), \"tensor1\", \"int32\")\n    write = p.get_global_var(\"tensor_array_write\", \"int32\")\n    stack = p.get_global_var(\"tensor_array_stack\", \"int32\")\n    v = relay.var(\"v\")\n    init_tensor_array = tensor_array(relay.const(3))\n    tensor_array1 = write(init_tensor_array, relay.const(0), tensor1(v))\n    tensor_array2 = stack(tensor_array1)\n    mod[\"main\"] = relay.Function([v], tensor_array2)\n    mod = relay.transform.RemoveUnusedFunctions()(mod)\n    l = set([x[0].name_hint for x in mod.functions.items()])\n    assert \"tensor_array_int32\" in l\n\n\ndef test_call_globalvar_without_args():\n    def get_mod():\n        mod = tvm.IRModule({})\n        fn1 = relay.Function([], relay.const(1))\n        fn2 = relay.Function([], relay.const(2))\n        g1 = relay.GlobalVar(\"g1\")\n        g2 = relay.GlobalVar(\"g2\")\n        mod[g1] = fn1\n        mod[g2] = fn2\n        p = relay.var(\"p\", \"bool\")\n        mod[\"main\"] = relay.Function([p], relay.Call(relay.If(p, g1, g2), []))\n        return mod\n\n    mod = get_mod()\n    ref_mod = get_mod()\n    mod = relay.transform.RemoveUnusedFunctions()(mod)\n    assert tvm.ir.structural_equal(mod, ref_mod, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    pytest.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_simplify_expr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_opt_pass, run_infer_type\n\nimport numpy as np\n\n\ndef test_simplify_reshape():\n    def before():\n        x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n        w = relay.var(\"w\", shape=(32, 16, 3, 3), dtype=\"float32\")\n        y = relay.nn.conv2d(x, w, padding=(1, 1))\n        y = relay.reshape(y, newshape=(1, 16, -1))\n        y = relay.reshape(y, newshape=(4, 8, -1, 16))\n        y = relay.reverse_reshape(y, newshape=(32, 0, -1))\n        return relay.Function([x, w], y)\n\n    def expected():\n        x = relay.var(\"x\", shape=(1, 16, 16, 16), dtype=\"float32\")\n        w = relay.var(\"w\", shape=(32, 16, 3, 3), dtype=\"float32\")\n        y = relay.nn.conv2d(x, w, padding=(1, 1))\n        y = relay.reshape(y, newshape=(32, 16, 16))\n        return relay.Function([x, w], y)\n\n    def symbolic():\n        b = tvm.te.size_var(\"b\")\n        x = relay.var(\"x\", shape=(b, 16, 16, 16), dtype=\"float32\")\n        w = relay.var(\"w\", shape=(32, 16, 3, 3), dtype=\"float32\")\n        y = relay.nn.conv2d(x, w, padding=(1, 1))\n        y = relay.reshape(y, newshape=(1, 16, -1))\n        y = relay.reshape(y, newshape=(4, 8, -1, 16))\n        y = relay.reverse_reshape(y, newshape=(32, 0, -1))\n        return relay.Function([x, w], y)\n\n    z = before()\n    zz = run_opt_pass(z, transform.SimplifyExpr())\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n    z = symbolic()\n    zz = run_opt_pass(z, transform.SimplifyExpr())\n    after = run_opt_pass(symbolic(), transform.InferType())\n    assert tvm.ir.structural_equal(zz, after)\n\n\ndef test_simplify_transpose():\n    # Test a series of transpose and layout_transform ops\n    def before1():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.transpose(x, axes=[0, 2, 3, 1])  # To NHWC\n        y = relay.layout_transform(y, \"NHWC\", \"HWCN\")  # To HWCN\n        y = relay.transpose(y, axes=[3, 0, 1, 2])  # To NHWC\n        return relay.Function([x], y)\n\n    def expected1():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.transpose(x, axes=[0, 2, 3, 1])  # To NHWC\n        return relay.Function([x], y)\n\n    # Test that all transpose ops can be cancelled\n    def before2():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.nn.relu(x)\n        y = relay.transpose(y, axes=[0, 2, 3, 1])  # To NHWC\n        y = relay.transpose(y, axes=[1, 2, 3, 0])  # To HWCN\n        y = relay.transpose(y, axes=[3, 2, 0, 1])  # To NCHW\n        return relay.Function([x], y)\n\n    def expected2():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.nn.relu(x)\n        return relay.Function([x], y)\n\n    # Test default axis (reverse) and negative axis\n    def before3():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.nn.relu(x)\n        y = relay.transpose(y)  # Reverse\n        y = relay.transpose(y)  # Reverse\n        y = relay.transpose(y, axes=[0, 2, -1, 1])\n        y = relay.transpose(y)  # Reverse\n        y = relay.transpose(y)  # Reverse\n        return relay.Function([x], y)\n\n    def expected3():\n        x = relay.var(\"x\", shape=(1, 3, 224, 224), dtype=\"float32\")  # NCHW\n        y = relay.nn.relu(x)\n        y = relay.transpose(y, axes=[0, 2, 3, 1])\n        return relay.Function([x], y)\n\n    # Test a series of transpose and rank changing layout_transform\n    def before4():\n        \"\"\"\n        Simplify transpose->layout_transform and its inverse.\n\n        Input:\n        NHWC -> NCHW -> NCHW4c -> op -> NCHW4c -> NCHW -> NHWC\n\n        Simplified:\n        NHWC -> NCHW4c -> op -> NCHW4c -> NHWC\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 56, 56, 128), dtype=\"float32\")\n        y = relay.transpose(x, axes=[0, 3, 1, 2])\n        y = relay.layout_transform(y, \"NCHW\", \"NCHW4c\")\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW4c\", \"NCHW\")\n        y = relay.transpose(y, axes=[0, 2, 3, 1])\n        return relay.Function([x], y)\n\n    def expected4():\n        x = relay.var(\"x\", shape=(1, 56, 56, 128), dtype=\"float32\")  # NHWC\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW4c\")  # To NCHW4c\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW4c\", \"NHWC\")  # To NHWC\n        return relay.Function([x], y)\n\n    def before5():\n        \"\"\"\n        Simplify layout_transform->layout_transform and its inverse.\n\n        Input:\n        NHWC -> NCHW -> NCHW4c -> op -> NCHW4c -> NCHW -> NHWC\n\n        Simplified:\n        NHWC -> NCHW4c -> op -> NCHW4c -> NHWC\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 56, 56, 128), dtype=\"float32\")  # NHWC\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW\")  # To NCHW\n        y = relay.layout_transform(y, \"NCHW\", \"NCHW4c\")  # To NCHW4c\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW4c\", \"NCHW\")  # To NCHW\n        y = relay.layout_transform(y, \"NCHW\", \"NHWC\")  # To NHWC\n        return relay.Function([x], y)\n\n    def expected5():\n        x = relay.var(\"x\", shape=(1, 56, 56, 128), dtype=\"float32\")  # NHWC\n        y = relay.layout_transform(x, \"NHWC\", \"NCHW4c\")  # To NCHW4c\n        y = relay.nn.relu(y)\n        y = relay.layout_transform(y, \"NCHW4c\", \"NHWC\")  # To NHWC\n        return relay.Function([x], y)\n\n    def before6():\n        \"\"\"\n        Remove trivial layout_transform->layout_transform.\n\n        Input:\n        NCHW -> NHWC -> NCHW -> op\n\n        Simplified:\n        NHWC -> op\n        \"\"\"\n\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        y = relay.layout_transform(y, \"NHWC\", \"NCHW\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def expected6():\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.nn.relu(x)\n        return relay.Function([x], y)\n\n    def before7():\n        \"\"\"\n        Remove trivial layout_transform->layout_transform.\n\n        Input:\n        NCHW4c -> NCHW8c -> NCHW4c -> op\n\n        Simplified:\n        NCHW4c -> op\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 32, 56, 56, 4), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW4c\", \"NCHW8c\")\n        y = relay.layout_transform(y, \"NCHW8c\", \"NCHW4c\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def expected7():\n        x = relay.var(\"x\", shape=(1, 32, 56, 56, 4), dtype=\"float32\")\n        y = relay.nn.relu(x)\n        return relay.Function([x], y)\n\n    def before8():\n        \"\"\"\n        Simplify layout_transform->layout_transform with rank contraction and expansion\n\n        Input:\n        NCHW4c -> NCHW -> NCHW8c -> op\n\n        Simplified:\n        NCHW4c -> NCHW8c -> op\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 32, 56, 56, 4), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW4c\", \"NCHW\")\n        y = relay.layout_transform(y, \"NCHW\", \"NCHW8c\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def expected8():\n        x = relay.var(\"x\", shape=(1, 32, 56, 56, 4), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW4c\", \"NCHW8c\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def before9():\n        \"\"\"\n        Remove trivial layout_transform->layout_transform.\n\n        Input:\n        NCHW -> NCHW4c -> NCHW -> op\n\n        Simplified:\n        NCHW -> op\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW\", \"NCHW4c\")\n        y = relay.layout_transform(y, \"NCHW4c\", \"NCHW\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def expected9():\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.nn.relu(x)\n        return relay.Function([x], y)\n\n    def before10():\n        \"\"\"\n        Simplify layout_transform->layout_transform without rank change to transpose.\n\n        Input:\n        NCHW -> NHWC -> CHWN -> op\n\n        Simplified:\n        NCHW -> CHWN -> op\n        \"\"\"\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.layout_transform(x, \"NCHW\", \"NHWC\")\n        y = relay.layout_transform(y, \"NHWC\", \"CHWN\")\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    def expected10():\n        x = relay.var(\"x\", shape=(1, 128, 56, 56), dtype=\"float32\")\n        y = relay.transpose(x, axes=[1, 2, 3, 0])\n        y = relay.nn.relu(y)\n        return relay.Function([x], y)\n\n    for before, expected in [\n        [before1(), expected1()],\n        [before2(), expected2()],\n        [before3(), expected3()],\n        [before4(), expected4()],\n        [before5(), expected5()],\n        [before6(), expected6()],\n        [before7(), expected7()],\n        [before8(), expected8()],\n        [before9(), expected9()],\n        [before10(), expected10()],\n    ]:\n        after = run_opt_pass(before, transform.SimplifyExpr())\n        expected = run_opt_pass(expected, transform.InferType())\n        assert tvm.ir.structural_equal(after, expected), \"\\nafter: {} \\nexpected: {}\".format(\n            after, expected\n        )\n\n\ndef test_simplify_full_elementwise():\n    def validate(shape, value, dtype):\n        def before_left(x, elem_op, full):\n            return elem_op(full, x)\n\n        def after_left(x, elem_op, value):\n            if elem_op == relay.add and value == 0:\n                return x\n            elif elem_op == relay.multiply and (value == 1 or (value > 1 and dtype == \"bool\")):\n                return x\n            return elem_op(relay.const(value, dtype), x)\n\n        def before_right(x, elem_op, full):\n            return elem_op(x, full)\n\n        def after_right(x, elem_op, value):\n            if elem_op in [relay.add, relay.subtract] and value == 0:\n                return x\n            elif elem_op in [relay.multiply, relay.divide] and (\n                value == 1 or (value > 1 and dtype == \"bool\")\n            ):\n                return x\n            return elem_op(x, relay.const(value, dtype))\n\n        x = relay.var(\"x\", shape=shape, dtype=dtype)\n        elem_ops = [relay.add, relay.multiply, relay.subtract, relay.divide]\n        full_ops = []\n        if value == 0:\n            full_ops.append(relay.zeros(shape, dtype))\n            full_ops.append(relay.zeros_like(x))\n        if value == 1:\n            full_ops.append(relay.ones(shape, dtype))\n            full_ops.append(relay.ones_like(x))\n        else:\n            full_ops.append(relay.full(relay.const(value, dtype), shape))\n            full_ops.append(relay.full_like(x, relay.const(value, dtype)))\n        for op in elem_ops:\n            for full in full_ops:\n                z = before_left(x, op, full)\n                zz = run_opt_pass(z, transform.SimplifyExpr())\n                after = run_opt_pass(after_left(x, op, value), transform.InferType())\n                assert tvm.ir.structural_equal(zz, after)\n\n                z = before_right(x, op, full)\n                zz = run_opt_pass(z, transform.SimplifyExpr())\n                after = run_opt_pass(after_right(x, op, value), transform.InferType())\n                assert tvm.ir.structural_equal(zz, after)\n\n        # Test the case in which x is broadcast to full's shape\n        full_ops = []\n        if value == 0:\n            full_ops.append(relay.zeros(shape * 2, dtype))\n        if value == 1:\n            full_ops.append(relay.ones(shape * 2, dtype))\n        else:\n            full_ops.append(relay.full(relay.const(value, dtype), shape * 2))\n        for op in elem_ops:\n            for full in full_ops:\n                z = before_left(x, op, full)\n                zz = run_opt_pass(z, transform.SimplifyExpr())\n                after = run_opt_pass(before_left(x, op, full), transform.InferType())\n                assert tvm.ir.structural_equal(zz, after)\n\n                z = before_right(x, op, full)\n                zz = run_opt_pass(z, transform.SimplifyExpr())\n                after = run_opt_pass(before_right(x, op, full), transform.InferType())\n                assert tvm.ir.structural_equal(zz, after)\n\n    for shape in [[10], [10, 10], [10, 10, 10]]:\n        for dtype in [\"float32\", \"int32\", \"bool\"]:\n            for value in [0, 1, 2]:\n                validate(shape, value, dtype)\n\n\ndef test_eliminate_identity():\n    def check(x, y=None, do_nothing=False):\n        expected = run_infer_type(x)\n        if do_nothing:\n            actual = run_opt_pass(x, transform.SimplifyExpr())\n            assert tvm.ir.structural_equal(actual, expected)\n        else:\n            assert y is not None\n            actual = run_opt_pass(y, transform.SimplifyExpr())\n            assert tvm.ir.structural_equal(actual, expected)\n\n    shape = [2, 3, 4]\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    x = run_opt_pass(x, transform.InferType())\n\n    for (op, op_like, id_op, const) in [\n        (relay.zeros, relay.zeros_like, relay.add, relay.const(0, dtype)),\n        (relay.ones, relay.ones_like, relay.multiply, relay.const(1, dtype)),\n    ]:\n        check(x, id_op(op_like(x), x))\n        check(x, id_op(op(shape, dtype), x))\n        check(x, id_op(const, x))\n        check(x, id_op(op(shape[1:], dtype), x))\n        check(x, id_op(x, op_like(x)))\n        check(x, id_op(x, op(shape, dtype)))\n        check(x, id_op(x, const))\n        check(x, id_op(x, op(shape[1:], dtype)))\n        check(id_op(x, op([2] + shape, dtype)), do_nothing=True)\n        check(id_op(op([2] + shape, dtype), x), do_nothing=True)\n\n    for (op, op_like, id_op, const) in [\n        (relay.zeros, relay.zeros_like, relay.subtract, relay.const(0, dtype)),\n        (relay.ones, relay.ones_like, relay.divide, relay.const(1, dtype)),\n    ]:\n        check(x, id_op(x, op_like(x)))\n        check(x, id_op(x, const))\n        check(x, id_op(x, op(shape, dtype)))\n        check(x, id_op(x, op(shape[1:], dtype)))\n        check(id_op(x, op([2] + shape, dtype)), do_nothing=True)\n        check(id_op(const, x), id_op(op(shape, dtype), x))\n        check(id_op(const, x), id_op(op_like(x), x))\n\n\ndef test_simplify_same_cast():\n    dtype = \"int32\"\n    data = relay.var(\"data\", shape=(3, 4, 5), dtype=dtype)\n    expr1 = relay.cast(data, dtype)\n    dtype_like = relay.var(\"dtype_like\", shape=(2, 2, 2), dtype=dtype)\n    expr2 = relay.cast_like(data, dtype_like)\n\n    expected = run_infer_type(data)\n    actual1 = run_opt_pass(expr1, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual1, expected)\n    actual2 = run_opt_pass(expr2, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual2, expected)\n\n\ndef test_simplify_consecutive_cast():\n    x = relay.var(\"x\", shape=(3, 4, 5), dtype=\"int8\")\n    y = relay.var(\"y\", shape=(3, 4), dtype=\"int64\")\n    z = relay.var(\"z\", shape=(3,), dtype=\"float32\")\n\n    expr1 = relay.cast(x, \"int16\")\n    expr2 = relay.cast(expr1, \"int32\")\n    expr3 = relay.cast_like(expr2, y)\n    expr4 = relay.cast_like(expr3, z)\n\n    actual1 = run_opt_pass(expr2, relay.transform.SimplifyExpr())\n    expected = run_infer_type(relay.cast(x, \"int32\"))\n    assert tvm.ir.structural_equal(actual1, expected)\n    actual2 = run_opt_pass(expr3, relay.transform.SimplifyExpr())\n    expected = run_infer_type(relay.cast(x, \"int64\"))\n    assert tvm.ir.structural_equal(actual2, expected)\n    actual3 = run_opt_pass(expr4, relay.transform.SimplifyExpr())\n    expected = run_infer_type(relay.cast(x, \"float32\"))\n    assert tvm.ir.structural_equal(actual3, expected)\n\n    # cannot simplify the narrow cast\n    x = relay.var(\"x\", shape=(3, 4, 5), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(3, 4), dtype=\"float32\")\n    expr1 = relay.cast(x, \"int32\")\n    expr2 = relay.cast_like(expr1, y)\n    actual = run_opt_pass(expr2, relay.transform.SimplifyExpr())\n    expected = run_infer_type(relay.cast(expr1, \"float32\"))\n    assert tvm.ir.structural_equal(actual, expected)\n\n    x = relay.var(\"x\", shape=(3, 4), dtype=\"int64\")\n    expr1 = relay.cast(x, \"bool\")\n    expr2 = relay.cast(expr1, \"int32\")\n    actual = run_opt_pass(expr2, relay.transform.SimplifyExpr())\n    expected = run_infer_type(expr2)\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_reshape_like():\n    data = relay.var(\"data\", shape=(2, 3, 4), dtype=\"float32\")\n    shape_like = relay.var(\"shape_like\", shape=(6, 2, 2), dtype=\"float32\")\n    expr = relay.reshape_like(data, shape_like)\n\n    expected = run_infer_type(relay.reshape(data, (6, 2, 2)))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_reshape_like_attrs():\n    data = relay.var(\"data\", shape=(2, 3, 4), dtype=\"float32\")\n    shape_like = relay.var(\"shape_like\", shape=(6, 2, 2), dtype=\"float32\")\n    expr = relay.reshape_like(data, shape_like, lhs_begin=2, rhs_begin=1)\n\n    expected = run_infer_type(relay.reshape(data, (2, 3, 2, 2)))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_zeros_like():\n    dtype = \"int32\"\n    shape_like = relay.var(\"shape_like\", shape=(3, 4, 5), dtype=dtype)\n    expr = relay.zeros_like(shape_like)\n\n    expected = run_infer_type(relay.zeros((3, 4, 5), dtype))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_ones_like():\n    dtype = \"int32\"\n    shape_like = relay.var(\"shape_like\", shape=(3, 4, 5), dtype=dtype)\n    expr = relay.ones_like(shape_like)\n\n    expected = run_infer_type(relay.ones((3, 4, 5), dtype))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_full_like():\n    dtype = \"int32\"\n    shape_like = relay.var(\"shape_like\", shape=(3, 4, 5), dtype=dtype)\n    fill_value = relay.var(\"fill\", relay.TensorType((), \"float32\"))\n    expr = relay.full_like(shape_like, fill_value)\n\n    expected = run_infer_type(relay.full(fill_value, (3, 4, 5), dtype))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_collapse_sum_like():\n    data = relay.var(\"data\", shape=(3, 3, 3), dtype=\"float32\")\n    shape_like = relay.var(\"shape_like\", shape=(3,), dtype=\"float32\")\n    expr = relay.collapse_sum_like(data, shape_like)\n\n    expected = run_infer_type(relay.collapse_sum_to(data, (3,)))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_broadcast_to_like():\n    data = relay.var(\"data\", shape=(3,), dtype=\"float32\")\n    shape_like = relay.var(\"shape_like\", shape=(3, 3, 3), dtype=\"float32\")\n    expr = relay.broadcast_to_like(data, shape_like)\n\n    expected = run_infer_type(relay.broadcast_to(data, (3, 3, 3)))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_cast_like():\n    dim_any = tvm.tir.Any()\n    data = relay.var(\"data\", shape=(3, dim_any, 5), dtype=\"float32\")\n    dtype_like = relay.var(\"dtype_like\", shape=(dim_any, 3, 3), dtype=\"int32\")\n    expr = relay.cast_like(data, dtype_like)\n\n    expected = run_infer_type(relay.cast(data, \"int32\"))\n    actual = run_opt_pass(expr, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_concretize_multiple():\n    x = relay.var(\"x\", shape=(2, 3), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(3,), dtype=\"float32\")\n    l = x + y\n\n    dl = relay.ones_like(l)\n    dx = relay.zeros_like(x)\n    dy = relay.zeros_like(y)\n    dx = dx + relay.collapse_sum_like(dl, dx)\n    dy = dy + relay.collapse_sum_like(dl, dy)\n    ret = relay.Tuple([dx, dy])\n\n    dl_c = relay.ones((2, 3), \"float32\")\n    # NOTE: these are removed by EliminateIdentity\n    # dx_c = relay.zeros((2, 3), \"float32\")\n    # dy_c = relay.zeros((3,), \"float32\")\n    dx_c = relay.collapse_sum_to(dl_c, (2, 3))\n    dy_c = relay.collapse_sum_to(dl_c, (3,))\n    ret_c = relay.Tuple([dx_c, dy_c])\n\n    expected = run_infer_type(ret_c)\n    actual = run_opt_pass(ret, relay.transform.SimplifyExpr())\n    assert tvm.ir.structural_equal(actual, expected)\n\n\ndef test_simplify_mul_add():\n    def check_simple_fold(origin_exprs, expect_expr):\n        for origin_expr in origin_exprs:\n            simple_expr = run_opt_pass(origin_expr, transform.SimplifyExpr())\n            assert tvm.ir.structural_equal(simple_expr, expect_expr)\n\n    n = 32\n    c1_val = np.random.uniform(size=n).astype(\"float32\")\n    c2_val = np.random.uniform(size=n).astype(\"float32\")\n    c3_val = np.random.uniform(size=n).astype(\"float32\")\n\n    x = relay.var(\"x\", shape=(n,), dtype=\"float32\")\n    c1 = relay.const(c1_val)\n    c2 = relay.const(c2_val)\n    c3 = relay.const(c3_val)\n\n    # add-add -> add\n    origin_exprs = [\n        x + c1 + c2,\n        c1 + x + c2,\n    ]\n    expect_expr = x + relay.const(c1_val + c2_val)\n    check_simple_fold(origin_exprs, expect_expr)\n\n    # mul-mul -> mul\n    origin_exprs = [\n        x * c1 * c2,\n        c1 * x * c2,\n    ]\n    expect_expr = x * relay.const(c1_val * c2_val)\n    check_simple_fold(origin_exprs, expect_expr)\n\n    # add-mul -> mul-add\n    origin_exprs = [\n        (x + c1) * c2,\n        (c1 + x) * c2,\n        c2 * (x + c1),\n        c2 * (c1 + x),\n    ]\n    expect_expr = x * c2 + relay.const(c1_val * c2_val)\n    check_simple_fold(origin_exprs, expect_expr)\n\n    # add-mul-add -> mul-add\n    origin_exprs = [\n        (x + c1) * c2 + c3,\n        (c1 + x) * c2 + c3,\n        c2 * (x + c1) + c3,\n        c2 * (c1 + x) + c3,\n        c3 + (x + c1) * c2,\n        c3 + (c1 + x) * c2,\n        c3 + c2 * (x + c1),\n        c3 + c2 * (c1 + x),\n    ]\n    expect_expr = x * c2 + relay.const(c1_val * c2_val + c3_val)\n    check_simple_fold(origin_exprs, expect_expr)\n\n    # mul-add-mul -> mul-add\n    origin_exprs = [\n        (x * c1 + c2) * c3,\n        (c1 * x + c2) * c3,\n        (c2 + x * c1) * c3,\n        (c2 + c1 * x) * c3,\n        c3 * (x * c1 + c2),\n        c3 * (c1 * x + c2),\n        c3 * (c2 + x * c1),\n        c3 * (c2 + c1 * x),\n    ]\n    expect_expr = x * relay.const(c1_val * c3_val) + relay.const(c2_val * c3_val)\n    check_simple_fold(origin_exprs, expect_expr)\n\n\ndef test_simplify_rsqrt():\n    shape = (32, 1, 1)\n    x = relay.var(\"x\", shape=shape, dtype=\"float32\")\n\n    def before(c):\n        return relay.const(c) / relay.sqrt(x)\n\n    def expected(c):\n        if c == 1:\n            return relay.rsqrt(x)\n        else:\n            return relay.const(c) * relay.rsqrt(x)\n\n    for c in [1.0, 2.0, 2.5]:\n        opt = run_opt_pass(before(c), transform.SimplifyExpr())\n        after = run_opt_pass(expected(c), transform.InferType())\n        assert tvm.ir.structural_equal(opt, after)\n\n\ndef test_simplify_dq_argmax():\n    shape = (4, 32, 1, 1)\n    x = relay.var(\"x\", shape=shape, dtype=\"int8\")\n\n    def before():\n        y = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(0))\n        return relay.op.argmax(y, axis=1)\n\n    def expected():\n        return relay.op.argmax(x, axis=1)\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(opt, after)\n\n\ndef test_simplify_dq_argmin():\n    shape = (4, 32, 1, 1)\n    x = relay.var(\"x\", shape=shape, dtype=\"int8\")\n\n    def before():\n        y = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(0))\n        return relay.op.argmin(y, axis=1)\n\n    def expected():\n        return relay.op.argmin(x, axis=1)\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(opt, after)\n\n\ndef test_simplify_dq_argsort():\n    shape = (4, 32, 1, 1)\n    x = relay.var(\"x\", shape=shape, dtype=\"int8\")\n\n    def before():\n        y = relay.qnn.op.dequantize(x, relay.const(2.0), relay.const(0))\n        return relay.op.argsort(y, axis=1)\n\n    def expected():\n        return relay.op.argsort(x, axis=1)\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    after = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(opt, after)\n\n\ndef test_simplify_clip_cast():\n    x = relay.var(\"x\", shape=(4, 8), dtype=\"int32\")\n\n    def before():\n        clip = relay.clip(x, a_min=0.0, a_max=255.0)\n        cast = relay.cast(clip, \"uint8\")\n        return relay.cast(cast, \"int32\")\n\n    def expected():\n        return relay.clip(x, a_min=0.0, a_max=255.0)\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    ref = run_infer_type(expected())\n    assert tvm.ir.structural_equal(opt, ref)\n\n\ndef test_simplify_cast_clip():\n    x = relay.var(\"x\", shape=(4, 8), dtype=\"int32\")\n\n    def before():\n        cast = relay.cast(x, \"uint8\")\n        return relay.clip(cast, a_min=0.0, a_max=255.0)\n\n    def expected():\n        return relay.cast(x, \"uint8\")\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    ref = run_infer_type(expected())\n    assert tvm.ir.structural_equal(opt, ref)\n\n\ndef test_simplify_add():\n    x = relay.var(\"x\", shape=(1, 3, 100, 100), dtype=\"float32\")\n\n    def before():\n        return relay.add(x, x)\n\n    def expected():\n        s = relay.const(2.0)\n        return relay.multiply(x, s)\n\n    opt = run_opt_pass(before(), transform.SimplifyExpr())\n    ref = run_infer_type(expected())\n    assert tvm.ir.structural_equal(opt, ref)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_simplify_inference.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.ir import IRModule, structural_equal\nfrom tvm import relay as rly\nfrom tvm.relay.transform import SimplifyInference, InferType\n\n\ndef test_simplify_batchnorm(dtype=\"float32\"):\n    def simple_bn(x, gamma, beta, moving_mean, moving_var, axis=1, epsilon=1e-5, shape=None):\n        # expect = (x - moving_mean) / sqrt(moving_var + eps) * gamma + beta\n        scale = rly.multiply(\n            rly.const(1, dtype) / rly.sqrt(moving_var + rly.const(epsilon, dtype)), gamma\n        )\n        shift = rly.add(rly.multiply(rly.negative(moving_mean), scale), beta)\n        num_newaxis = len(shape) - (axis + 1)\n        if num_newaxis:\n            scale = rly.expand_dims(scale, axis=1, num_newaxis=num_newaxis)\n            shift = rly.expand_dims(shift, axis=1, num_newaxis=num_newaxis)\n        return x * scale + shift\n\n    def check(dim, axis, nstep):\n        eps = 0.01\n        ttype1 = rly.TensorType(tuple(10 for i in range(dim)), dtype)\n        ttype2 = rly.TensorType((10,), dtype)\n        x = rly.var(\"x\", ttype1)\n        beta = rly.var(\"beta\", ttype2)\n        gamma = rly.var(\"gamma\", ttype2)\n        moving_var = rly.var(\"moving_var\", ttype2)\n        moving_mean = rly.var(\"moving_mean\", ttype2)\n        y1, y2 = x, x\n\n        for _ in range(nstep):\n            y1, _, _ = rly.nn.batch_norm(\n                y1 + rly.const(1, dtype),\n                gamma,\n                beta,\n                moving_mean,\n                moving_var,\n                epsilon=eps,\n                axis=axis,\n            )\n            y1 = rly.nn.dropout(y1)\n            y2 = simple_bn(\n                y2 + rly.const(1, dtype),\n                gamma,\n                beta,\n                moving_mean,\n                moving_var,\n                epsilon=eps,\n                axis=axis,\n                shape=ttype1.shape,\n            )\n\n        mod = IRModule.from_expr(y1)\n\n        simplify = SimplifyInference()\n        mod = InferType()(mod)\n        mod = simplify(mod)\n        y1 = mod[\"main\"].body\n\n        assert structural_equal(y1, y2, map_free_vars=True)\n\n    check(2, 1, 1)\n    check(4, 1, 1)\n    check(4, 0, 3)\n\n\nif __name__ == \"__main__\":\n    test_simplify_batchnorm(dtype=\"float32\")\n    test_simplify_batchnorm(dtype=\"float16\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_split_args.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\nfrom tvm.relay.testing import run_infer_type, create_workload\n\n\ndef run_opt_pass(expr, opt_pass):\n    assert isinstance(opt_pass, tvm.transform.Pass)\n\n    mod = tvm.IRModule.from_expr(expr)\n    mod = relay.transform.InferType()(mod)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef test_split_concat_metal():\n    shape = (1, 1, 1, 3)\n    dtype = \"float32\"\n    axis = 1\n    inputs = []\n    for i in range(100):\n        inputs.append(relay.var(\"p{}\".format(i), shape=shape, dtype=dtype))\n\n    def before():\n        inp = relay.Tuple(inputs)\n        return relay.op.concatenate(inp, axis)\n\n    def expected():\n        limit = tvm.target.Target(\"metal\").max_function_args - 1  # one buffer with output\n        splitNum = int(len(inputs) / limit)\n        if len(inputs) % limit > 0:\n            splitNum += 1\n\n        splitted = []\n        for i in range(splitNum):\n            startIdx = i * limit\n            argsCount = min(limit, len(inputs) - startIdx)\n            args = []\n            for j in range(argsCount):\n                args.append(inputs[j + startIdx])\n            t = relay.Tuple(args)\n            concat = relay.op.concatenate(t, axis)\n            splitted.append(relay.annotation.stop_fusion(concat))\n        inp = relay.Tuple(splitted)\n        return relay.op.concatenate(inp, axis)\n\n    # the fold constant should work on any context.\n    res = run_opt_pass(before(), transform.SplitArgs(tvm.target.Target(\"metal\").max_function_args))\n    exp = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(res, exp)\n\n\ndef test_split_concat_cuda():\n    shape = (1, 1, 1, 3)\n    dtype = \"float32\"\n    axis = 1\n    inputs = []\n    for i in range(100):\n        inputs.append(relay.var(\"p{}\".format(i), shape=shape, dtype=dtype))\n\n    def before():\n        inp = relay.Tuple(inputs)\n        return relay.op.concatenate(inp, axis)\n\n    def expected():\n        inp = relay.Tuple(inputs)\n        return relay.op.concatenate(inp, axis)\n\n    # the fold constant should work on any context.\n    res = run_opt_pass(before(), transform.SplitArgs(tvm.target.Target(\"cuda\").max_function_args))\n    exp = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(res, exp)\n\n\nif __name__ == \"__main__\":\n    test_split_concat_metal()\n    test_split_concat_cuda()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_to_a_normal_form.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport sys\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import detect_feature\nfrom tvm.relay import op, create_executor, transform\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.testing import count\nfrom tvm.relay.analysis import Feature\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef check_eval(expr, expected_result, mod=None, rtol=1e-07):\n    dev = tvm.device(\"llvm\", 0)\n    result = create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(expr)\n    np.testing.assert_allclose(result.numpy(), expected_result, rtol=rtol)\n\n\ndef test_explicit_bound():\n    x = relay.const(1)\n    y = op.add(x, x)\n    z = op.add(y, y)\n    f = relay.Function([], op.add(z, z))\n    assert not Feature.fLet in detect_feature(f)\n    anf = run_opt_pass(f, transform.ToANormalForm())\n    assert Feature.fLet in detect_feature(anf)\n    check_eval(f(), 8.0)\n    check_eval(anf(), 8.0)\n\n\n# test that the construction order does not matter,\n# and is instead ordered by the scope and by post-dfs ordering.\ndef test_order():\n    z = relay.const(3)\n    y = relay.const(2)\n    x = relay.const(1)\n    val = x + y * z\n    check_eval(val, 7.0)\n    anf = run_opt_pass(val, [transform.ToANormalForm(), transform.InferType()])\n    a = relay.Var(\"a\", relay.IncompleteType())\n    b = relay.Var(\"b\", relay.IncompleteType())\n    c = relay.Var(\"c\", relay.IncompleteType())\n    d = relay.Var(\"d\", relay.IncompleteType())\n    e = relay.Var(\"e\", relay.IncompleteType())\n    expected_output = e\n    expected_output = relay.Let(e, a + d, expected_output)\n    expected_output = relay.Let(d, b * c, expected_output)\n    expected_output = relay.Let(c, z, expected_output)\n    expected_output = relay.Let(b, y, expected_output)\n    expected_output = relay.Let(a, x, expected_output)\n    expected_output = run_opt_pass(expected_output, transform.InferType())\n    assert tvm.ir.structural_equal(anf, expected_output)\n\n\ndef test_if():\n    cond = relay.const(True)\n    x = relay.If(cond, relay.const(2), relay.const(3))\n    anf = run_opt_pass(x, [transform.ToANormalForm(), transform.InferType()])\n    a = relay.Var(\"a\", relay.IncompleteType())\n    b = relay.Var(\"b\", relay.IncompleteType())\n    c = relay.Var(\"c\", relay.IncompleteType())\n    d = relay.Var(\"d\", relay.IncompleteType())\n    true_branch = relay.Let(a, relay.const(2), a)\n    false_branch = relay.Let(b, relay.const(3), b)\n    expected_output = relay.If(c, true_branch, false_branch)\n    expected_output = relay.Let(d, expected_output, d)\n    expected_output = relay.Let(c, cond, expected_output)\n    expected_output = run_opt_pass(expected_output, transform.InferType())\n    assert tvm.ir.structural_equal(anf, expected_output)\n\n\ndef test_let_as_subexpr():\n    def on_cpu(x):\n        return relay.annotation.on_device(x, tvm.device(\"cpu\"), constrain_result=True)\n\n    x = relay.Var(\"x\", relay.IncompleteType())\n    c = relay.const(1)\n    l = relay.Let(x, on_cpu(c + c), x)\n    body = l * l\n\n    anf = run_opt_pass(body, [transform.ToANormalForm(), transform.InferType()])\n\n    v0 = relay.Var(\"v0\", relay.IncompleteType())\n    v1 = relay.Var(\"v1\", relay.IncompleteType())\n    v2 = relay.Var(\"v2\", relay.IncompleteType())\n    expected_output = relay.Let(\n        v0,\n        on_cpu(c),\n        relay.Let(\n            x,\n            on_cpu(v0 + v0),\n            relay.Let(v1, x, relay.Let(v2, v1 * v1, v2)),\n        ),\n    )\n    expected_output = run_opt_pass(expected_output, transform.InferType())\n\n    tvm.ir.assert_structural_equal(anf, expected_output)\n\n\n# make sure we dont infinite loop.\n# it is too large so we wont check for the exact program.\ndef test_recursion():\n    \"\"\"\n    Program:\n       let f(n: i32) -> i32 = {\n          m = (n * 2)\n          if (n == 0) {\n              return m;\n          } else {\n              return m + f(n - 1);\n          }\n       }\n       f(5);\n    \"\"\"\n    mod = tvm.IRModule()\n    i64 = relay.TensorType((), \"int64\")\n    f = relay.GlobalVar(\"f\")\n    n = relay.Var(\"n\", i64)\n    m = n * relay.const(2, \"int64\")\n    funcbody = relay.If(\n        relay.equal(n, relay.const(0, \"int64\")), m, m + f(n - relay.const(1, \"int64\"))\n    )\n    value = relay.Function([n], funcbody, i64, [])\n    mod[f] = value\n    check_eval(f(relay.const(5, \"int64\")), 30.0, mod=mod)\n    old_f = mod[f]\n    mod = transform.ToANormalForm()(mod)\n    f = mod[f]\n    check_eval(f(relay.const(5, \"int64\")), 30.0, mod=mod)\n\n\ndef test_ref():\n    i = relay.Var(\"i\")\n    iv = relay.Var(\"iv\")\n    u = relay.Var(\"u\")\n    uv = relay.Var(\"uv\")\n    body = relay.add(iv, uv)\n    body = relay.Let(uv, relay.RefRead(i), body)\n    body = relay.Let(u, relay.RefWrite(i, relay.const(2)), body)\n    body = relay.Let(iv, relay.RefRead(i), body)\n    body = relay.Let(i, relay.RefCreate(relay.const(1)), body)\n    check_eval(body, 3)\n    opt_body = run_opt_pass(body, transform.ToANormalForm())\n    check_eval(opt_body, 3)\n\n\ndef test_nat_add():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, z, s = p.mod.get_type(\"nat\")\n    add = p.mod.get_global_var(\"nat_add\")\n    dev = tvm.device(\"llvm\", 0)\n    intrp = create_executor(mod=mod, device=dev, target=\"llvm\")\n    # CAUTION: Following calls to intrp.evaluate(...) will re-prepare the prelude.\n    assert mod[add].checked_type == relay.FuncType([nat(), nat()], nat())\n    assert count(p, intrp.evaluate(add(s(z()), s(z())))) == 2\n    expr = add(s(z()), s(z()))\n    f = relay.GlobalVar(\"f\")\n    mod[f] = relay.Function([], expr)\n    mod = transform.ToANormalForm()(mod)\n    expr = mod[\"f\"]\n    assert count(p, intrp.evaluate(expr.body)) == 2\n    assert Feature.fLet in detect_feature(mod[add])\n\n\ndef test_let():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    d = relay.const(4.0, \"float32\")\n    body = relay.Let(y, x, x + y)\n    body = relay.Let(x, d, body)\n    check_eval(body, 8)\n    opt_body = run_opt_pass(body, transform.ToANormalForm())\n    check_eval(opt_body, 8)\n\n\ndef test_function():\n    t = relay.TensorType((), \"float32\")\n    x = relay.Var(\"x\", t)\n    f = relay.Function([x], x + x)\n    d = relay.const(4.0, \"float32\")\n    anf_f = run_opt_pass(f, transform.ToANormalForm())\n    assert isinstance(anf_f, relay.Function)\n    check_eval(f(d), 8)\n    check_eval(anf_f(d), 8)\n\n\ndef test_gradient_if():\n    x = relay.var(\"a\", shape=(1, 16))\n    y = relay.var(\"y\", shape=(1, 16))\n    cond = relay.var(\"cond\", shape=(), dtype=\"uint1\")\n    net = relay.If(cond, x, x)\n    net = relay.add(x, net)\n    net = relay.Function([cond, x, y], net)\n    mod = tvm.IRModule.from_expr(net)\n    mod = relay.transform.ToANormalForm()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod[\"main\"] = relay.transform.gradient(mod[\"main\"], mode=\"higher_order\")\n    mod = relay.transform.ToANormalForm()(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_to_basic_block_normal_form.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import detect_feature\nfrom tvm.relay import op, create_executor, transform\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.testing import count, create_workload\nfrom tvm.relay.analysis import Feature\nfrom tvm.relay.analysis import check_basic_block_normal_form\n\n\ndef run_opt_pass(expr, passes):\n    passes = passes if isinstance(passes, list) else [passes]\n    mod = tvm.IRModule.from_expr(expr)\n    seq = tvm.transform.Sequential(passes)\n    with tvm.transform.PassContext(opt_level=3):\n        mod = seq(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef check_eval(expr, expected_result, mod=None, rtol=1e-07):\n    dev = tvm.device(\"llvm\", 0)\n    result = create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(expr)\n    np.testing.assert_allclose(result.numpy(), expected_result, rtol=rtol)\n\n\ndef test_no_explicit_bind():\n    x = relay.const(1)\n    y = op.add(x, x)\n    z = op.add(y, y)\n    f = relay.Function([], op.add(z, z))\n    \"\"\"\n    fn () {\n      %0 = add(1, 1);\n      %1 = add(%0, %0);\n      add(%1, %1)\n    }\n    \"\"\"\n    assert not Feature.fLet in detect_feature(f)\n    bblock = run_opt_pass(f, transform.ToBasicBlockNormalForm())\n    assert Feature.fLet not in detect_feature(bblock)\n    check_eval(f(), 8.0)\n    check_eval(bblock(), 8.0)\n    check_basic_block_normal_form(bblock)\n\n\ndef test_top_level_nested_if():\n    x = relay.var(\"x\", shape=(), dtype=\"bool\")\n    y = relay.var(\"y\", shape=(), dtype=\"float32\")\n    z = relay.var(\"z\", shape=(), dtype=\"float32\")\n    cond_t = relay.const(True)\n    cond_f = relay.const(False)\n    one = relay.const(1, dtype=\"float32\")\n    three = relay.const(3, dtype=\"float32\")\n    y2 = relay.add(y, y)\n    z2 = relay.add(z, z)\n    true_branch = relay.If(cond_t, relay.add(z2, y2), relay.add(three, y2))\n    false_branch = relay.If(cond_f, z2, one)\n    body = relay.If(x, true_branch, false_branch)\n    \"\"\"\n    free_var %x: bool\n    if (%x) {\n      if (True) {\n        free_var %z: float32\n        %0 = add(%z, %z);\n        free_var %y: float32\n        %1 = add(%y, %y);\n        add(%0, %1)\n      } else {\n        add(3f, %1)\n      }\n    } else {\n      if (False) {\n        %0\n      } else {\n        1f\n      }\n    }\n    \"\"\"\n\n    def expected():\n        x = relay.var(\"x\", shape=(), dtype=\"bool\")\n        y = relay.var(\"y\", shape=(), dtype=\"float32\")\n        z = relay.var(\"z\", shape=(), dtype=\"float32\")\n        cond_t = relay.const(True)\n        cond_f = relay.const(False)\n        one = relay.const(1, dtype=\"float32\")\n        three = relay.const(3, dtype=\"float32\")\n        y2 = relay.var(\"y2\")\n        z2 = relay.var(\"z2\")\n        true_branch = relay.If(cond_t, relay.add(z2, y2), relay.add(three, y2))\n        true_branch = relay.Let(y2, relay.add(y, y), true_branch)\n        false_branch = relay.If(cond_f, z2, one)\n        body = relay.If(x, true_branch, false_branch)\n        body = relay.Let(z2, relay.add(z, z), body)\n        return body\n\n    bblock = run_opt_pass(body, [transform.ToBasicBlockNormalForm(), transform.InferType()])\n    \"\"\"\n    free_var %z: float32\n    let %x: float32 = add(%z, %z) /* ty=float32 */;\n    free_var %x1: bool\n    if (%x1) {\n      free_var %y: float32\n      let %x2: float32 = add(%y, %y) /* ty=float32 */;\n      if (True /* ty=bool */) {\n        add(%x, %x2) /* ty=float32 */\n      } else {\n        add(3f /* ty=float32 */, %x2) /* ty=float32 */\n      }\n    } else {\n      if (False /* ty=bool */) {\n        %x\n      } else {\n        1f /* ty=float32 */\n      }\n    }\n    \"\"\"\n    expected_output = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(bblock, expected_output, map_free_vars=True)\n\n\ndef test_nested_if():\n    x = relay.var(\"x\", shape=(), dtype=\"bool\")\n    y = relay.var(\"y\", shape=(), dtype=\"float32\")\n    cond_t = relay.const(True)\n    cond_f = relay.const(False)\n    one = relay.const(1, dtype=\"float32\")\n    two = relay.const(2, dtype=\"float32\")\n    three = relay.const(3, dtype=\"float32\")\n    y2 = relay.add(y, y)\n    true_branch = relay.If(cond_t, y2, relay.add(three, y2))\n    false_branch = relay.If(cond_f, two, one)\n    body = relay.If(x, true_branch, false_branch)\n    \"\"\"\n    free_var %x: bool\n    if (%x) {\n      if (True) {\n        free_var %y: float32\n        %0 = add(%y, %y);\n        %0\n      } else {\n        add(3f, %0)\n      }\n    } else {\n      if (False) {\n        2f\n      } else {\n        1f\n      }\n    }\n    \"\"\"\n\n    def expected():\n        x = relay.var(\"x\", shape=(), dtype=\"bool\")\n        y = relay.var(\"y\", shape=(), dtype=\"float32\")\n        cond_t = relay.const(True)\n        cond_f = relay.const(False)\n        one = relay.const(1, dtype=\"float32\")\n        two = relay.const(2, dtype=\"float32\")\n        three = relay.const(3, dtype=\"float32\")\n        y2 = relay.var(\"y2\")\n        true_branch = relay.If(cond_t, y2, relay.add(three, y2))\n        true_branch = relay.Let(y2, relay.add(y, y), true_branch)\n        false_branch = relay.If(cond_f, two, one)\n        body = relay.If(x, true_branch, false_branch)\n        return body\n\n    bblock = run_opt_pass(body, [transform.ToBasicBlockNormalForm(), transform.InferType()])\n    \"\"\"\n    free_var %x: bool\n    if (%x) {\n      free_var %y: float32\n      let %x1: float32 = add(%y, %y) /* ty=float32 */;\n      if (True /* ty=bool */) {\n        %x1\n      } else {\n        add(3f /* ty=float32 */, %x1) /* ty=float32 */\n      }\n    } else {\n      if (False /* ty=bool */) {\n        2f /* ty=float32 */\n      } else {\n        1f /* ty=float32 */\n      }\n    }\n    \"\"\"\n    expected_output = run_opt_pass(expected(), transform.InferType())\n    assert tvm.ir.structural_equal(bblock, expected_output, map_free_vars=True)\n    check_basic_block_normal_form(bblock)\n\n\n# make sure we do not infinite loop.\n# it is too large so we won't check for the exact program.\ndef test_recursion():\n    \"\"\"\n    Program:\n       let f(n: i32) -> i32 = {\n          m = (n * 2)\n          if (n == 0) {\n              return m;\n          } else {\n              return m + f(n - 1);\n          }\n       }\n       f(5);\n    \"\"\"\n    mod = tvm.IRModule()\n    i64 = relay.TensorType((), \"int64\")\n    f = relay.GlobalVar(\"f\")\n    n = relay.Var(\"n\", i64)\n    m = n * relay.const(2, \"int64\")\n    cond = relay.equal(n, relay.const(0, \"int64\"))\n    false_branch = m + f(n - relay.const(1, \"int64\"))\n    funcbody = relay.If(cond, m, false_branch)\n    value = relay.Function([n], funcbody, i64, [])\n    mod[f] = value\n    check_eval(f(relay.const(5, \"int64\")), 30.0, mod=mod)\n    old_f = mod[f]\n    mod = transform.ToBasicBlockNormalForm()(mod)\n    f = mod[f]\n    check_eval(f(relay.const(5, \"int64\")), 30.0, mod=mod)\n    check_basic_block_normal_form(f)\n\n\ndef test_ref():\n    i = relay.Var(\"i\")\n    iv = relay.Var(\"iv\")\n    u = relay.Var(\"u\")\n    uv = relay.Var(\"uv\")\n    body = relay.add(iv, uv)\n    body = relay.Let(uv, relay.RefRead(i), body)\n    body = relay.Let(u, relay.RefWrite(i, relay.const(2)), body)\n    body = relay.Let(iv, relay.RefRead(i), body)\n    body = relay.Let(i, relay.RefCreate(relay.const(1)), body)\n    check_eval(body, 3)\n    opt_body = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n    check_eval(opt_body, 3)\n    check_basic_block_normal_form(opt_body)\n\n\ndef test_nat_add():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat, z, s = p.mod.get_type(\"nat\")\n    add = p.mod.get_global_var(\"nat_add\")\n    dev = tvm.device(\"llvm\", 0)\n    assert mod[add].checked_type == relay.FuncType([nat(), nat()], nat())\n    assert (\n        count(p, create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(add(s(z()), s(z()))))\n        == 2\n    )\n    expr = add(s(z()), s(z()))\n    f = relay.GlobalVar(\"f\")\n    mod[f] = relay.Function([], expr)\n    mod = transform.InferType()(mod)\n    mod = transform.ToBasicBlockNormalForm()(mod)\n    opt_expr = mod[\"f\"]\n    assert (\n        count(p, create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(opt_expr.body)) == 2\n    )\n    assert not Feature.fLet in detect_feature(mod[add])\n    check_basic_block_normal_form(opt_expr)\n\n\ndef test_let():\n    def test_let1():\n        x = relay.Var(\"x\")\n        c = relay.const(4.0, \"float32\")\n        body = relay.Let(x, c, x)\n        body = run_opt_pass(body, transform.InferType())\n        \"\"\"\n        let %x: float32 = 4f /* ty=float32 */;\n        %x\n        \"\"\"\n        opt_body = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n        assert tvm.ir.structural_equal(body, opt_body)\n        check_basic_block_normal_form(opt_body)\n\n    def test_let1_1():\n        x = relay.Var(\"y\")\n        d = relay.const(4.0, \"float32\")\n        body = relay.Let(x, d, relay.add(x, x))\n        body = run_opt_pass(body, transform.InferType())\n        opt_body = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n        assert tvm.ir.structural_equal(body, opt_body)\n        check_basic_block_normal_form(opt_body)\n\n    def test_let2():\n        x = relay.Var(\"x\")\n        y = relay.Var(\"y\")\n        d = relay.const(4.0, \"float32\")\n        body = relay.Let(y, x, x)\n        body = relay.Let(x, d, body)\n        body = run_opt_pass(body, transform.InferType())\n        check_eval(body, 4)\n\n        def expected():\n            x = relay.Var(\"x\")\n            y = relay.Var(\"y\")\n            d = relay.const(4.0, \"float32\")\n            body = relay.Let(y, x, y)\n            body = relay.Let(x, d, body)\n            return body\n\n        opt_body = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n        expected_body = run_opt_pass(expected(), transform.InferType())\n        assert tvm.ir.structural_equal(opt_body, expected_body)\n        check_basic_block_normal_form(opt_body)\n\n    def test_let3():\n        x = relay.Var(\"x\")\n        y = relay.Var(\"y\")\n        z = relay.Var(\"z\")\n        c = relay.const(3.0, \"float32\")\n        d = relay.const(4.0, \"float32\")\n        body = relay.Let(z, x + y, x + z)\n        body = relay.Let(x, d, body)\n        body = relay.Let(y, c, body)\n        body = run_opt_pass(body, transform.InferType())\n        opt_body = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n        assert tvm.ir.structural_equal(body, opt_body)\n        check_basic_block_normal_form(opt_body)\n\n    test_let1()\n    test_let1_1()\n    test_let2()\n    test_let3()\n\n\ndef test_function():\n    t = relay.TensorType((), \"float32\")\n    x = relay.Var(\"x\", t)\n    f = relay.Function([x], x + x)\n    d = relay.const(4.0, \"float32\")\n    bblock = run_opt_pass(f, transform.ToBasicBlockNormalForm())\n    assert isinstance(bblock, relay.Function)\n    check_eval(f(d), 8)\n    check_eval(bblock(d), 8)\n    check_basic_block_normal_form(bblock)\n\n\ndef test_gradient_if():\n    x = relay.var(\"a\", shape=(1, 16))\n    y = relay.var(\"y\", shape=(1, 16))\n    cond = relay.var(\"cond\", shape=(), dtype=\"uint1\")\n    net = relay.If(cond, x, x)\n    net = relay.add(x, net)\n    net = relay.Function([cond, x, y], net)\n    mod = tvm.IRModule.from_expr(net)\n    mod = relay.transform.ToBasicBlockNormalForm()(mod)\n    mod = relay.transform.InferType()(mod)\n    net_grad = relay.transform.gradient(mod[\"main\"], mode=\"higher_order\")\n    mod[\"main\"] = net_grad\n    mod_grad = relay.transform.ToBasicBlockNormalForm()(mod)\n    check_basic_block_normal_form(mod_grad[\"main\"])\n    check_basic_block_normal_form(mod[\"main\"])\n\n\ndef test_if():\n    def if_expr(x):\n        \"\"\"\n        free_var %x: float32\n        %0 = equal(%x, 2f);\n        if (%0) {\n          %1 = add(%x, 1f);\n          multiply(%1, 2f)\n        } else {\n          multiply(%1, 1f)\n        }\n        \"\"\"\n        one = relay.const(1, dtype=\"float32\")\n        two = relay.const(2, dtype=\"float32\")\n        v1 = relay.add(x, one)\n        v2 = relay.equal(x, two)\n        true_branch = relay.multiply(v1, two)\n        false_branch = relay.multiply(v1, one)\n        body = relay.If(v2, true_branch, false_branch)\n        return body\n\n    def expected_if_expr(x):\n        \"\"\"\n        free_var %x: float32\n        let %v1: float32 = add(%x, 1f /* ty=float32 */) /* ty=float32 */;\n        %0 = equal(%x, 2f /* ty=float32 */) /* ty=bool */;\n        if (%0) {\n          multiply(%v1, 2f /* ty=float32 */) /* ty=float32 */\n        } else {\n          multiply(%v1, 1f /* ty=float32 */) /* ty=float32 */\n        }\n        \"\"\"\n        one = relay.const(1, dtype=\"float32\")\n        two = relay.const(2, dtype=\"float32\")\n        v1 = relay.var(\"v1\")\n        v2 = relay.equal(x, two)\n        true_branch = relay.multiply(v1, two)\n        false_branch = relay.multiply(v1, one)\n        body = relay.If(v2, true_branch, false_branch)\n        body = relay.Let(v1, relay.add(x, one), body)\n        return body\n\n    x = relay.var(\"x\", shape=(), dtype=\"float32\")\n    body = if_expr(x)\n    expected_body = expected_if_expr(x)\n    bblock = run_opt_pass(body, [transform.ToBasicBlockNormalForm(), transform.InferType()])\n    expected_bblock = run_opt_pass(expected_body, transform.InferType())\n    assert tvm.ir.structural_equal(bblock, expected_bblock, map_free_vars=True)\n    check_basic_block_normal_form(bblock)\n\n    func = relay.Function([x], body)\n    expected_func = relay.Function([x], expected_body)\n    bblock = run_opt_pass(func, [transform.ToBasicBlockNormalForm(), transform.InferType()])\n    expected_bblock = run_opt_pass(expected_func, transform.InferType())\n    assert tvm.ir.structural_equal(bblock, expected_bblock)\n    check_basic_block_normal_form(bblock)\n\n\ndef test_higher_order_return():\n    x = relay.var(\"x\", shape=(1,), dtype=\"float32\")  # , a)\n    y = relay.var(\"y\", shape=(1,), dtype=\"float32\")  # , a)\n    z = relay.var(\"z\", shape=(1,), dtype=\"float32\")  # , a)\n    x2 = relay.add(x, x)\n    func_a = relay.Function([y], relay.add(x2, y))  # , a, [a])\n    func_b = relay.Function([z], relay.add(x2, z))  # , a, [a])\n    body = relay.Tuple([func_a, func_b])\n    body = relay.Function([x], body)\n    \"\"\"\n    fn (%x: Tensor[(1), float32]) {\n      %1 = fn (%y: Tensor[(1), float32]) {\n        %0 = add(%x, %x);\n        add(%0, %y)\n      };\n      %2 = fn (%z: Tensor[(1), float32]) {\n        add(%0, %z)\n      };\n      (%1, %2)\n    }\n    \"\"\"\n\n    bblock = run_opt_pass(body, transform.ToBasicBlockNormalForm())\n    check_basic_block_normal_form(bblock)\n\n\ndef test_higher_order_nested():\n    x = relay.var(\"x\", dtype=\"float32\", shape=(1,))\n    s = relay.var(\"s\", dtype=\"float32\", shape=(1,))\n    shared = relay.add(s, s)\n    func_true = relay.Function([x], relay.add(x, shared))\n    choice_t = relay.FuncType([], relay.scalar_type(\"bool\"))\n    f = relay.Var(\"f\", choice_t)\n    z = relay.Var(\"z\")\n    body = relay.If(f(), func_true, relay.Function([z], relay.add(z, shared)))\n    top = relay.Function([f, s], body)\n    \"\"\"\n    fn (%f: fn () -> bool, %s: Tensor[(1), float32]) {\n      %0 = %f();\n      if (%0) {\n        fn (%x: Tensor[(1), float32]) {\n          %1 = add(%s, %s);\n          add(%x, %1)\n        }\n      } else {\n        fn (%z) {\n          add(%z, %1)\n        }\n      }\n    }\n    \"\"\"\n\n    bblock = run_opt_pass(top, transform.ToBasicBlockNormalForm())\n    check_basic_block_normal_form(bblock)\n\n\ndef test_immutability():\n    simple_net = relay.nn.conv2d(\n        data=relay.var(\"data\", relay.TensorType((1, 3, 224, 224), \"float32\")),\n        weight=relay.var(\"weight\"),\n        kernel_size=(5, 5),\n        channels=3,\n        padding=(1, 1),\n    )\n    simple_net = relay.Function(relay.analysis.free_vars(simple_net), simple_net)\n    mod, _ = create_workload(simple_net)\n\n    old_mod = mod\n\n    with tvm.transform.PassContext(opt_level=4):\n        with tvm.target.Target(\"llvm\"):\n            seq = tvm.transform.Sequential(passes=[transform.ToBasicBlockNormalForm()], opt_level=4)\n            new_mod = seq(mod)\n\n    assert old_mod.astext() == mod.astext()\n    assert old_mod.astext() != new_mod.astext()\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_to_cps.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.analysis import detect_feature\nfrom tvm.relay.transform import to_cps, un_cps\nfrom tvm.relay.analysis import Feature\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.testing import make_nat_expr, rand, run_infer_type, run_opt_pass\nfrom tvm.relay import create_executor\nfrom tvm.relay import transform\n\n\ndef test_id():\n    x = relay.var(\"x\", shape=[])\n    id = run_infer_type(relay.Function([x], x))\n    id_cps = run_infer_type(to_cps(id))\n\n\ndef test_double():\n    t = relay.TypeVar(\"t\")\n    x = relay.var(\"x\", t)\n    f = relay.var(\"f\", relay.FuncType([t], t))\n    double = run_infer_type(relay.Function([f, x], f(f(x)), t, [t]))\n    double_cps = run_infer_type(to_cps(double))\n\n\n# make sure cps work for recursion.\ndef test_recursion():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    p.mod.import_from_std(\"nat.rly\")\n    nat_iterate = p.mod.get_global_var(\"nat_iterate\")\n    shape = (10, 10)\n    dtype = \"float32\"\n    t = relay.TensorType(shape, dtype)\n    x = relay.var(\"x\", t)\n    double = relay.Function([x], x + x)\n    i = relay.var(\"i\", t)\n    func = relay.Function([i], nat_iterate(double, make_nat_expr(p, 3))(i))\n    mod[\"main\"] = func\n    mod = relay.transform.InferType()(mod)\n    mod[\"main\"] = to_cps(mod[\"main\"], mod=mod)\n    mod = relay.transform.InferType()(mod)\n    mod[\"main\"] = un_cps(mod[\"main\"])\n    i_nd = rand(dtype, *shape)\n    forward = create_executor(mod=mod).evaluate()(i_nd)\n    tvm.testing.assert_allclose(forward.numpy(), 8 * i_nd.numpy())\n\n\n# This serve as an integration test.\n# It test that, given a program with reference,\n# cps and pe can completely eliminate the allocation of reference.\ndef test_cps_pe():\n    def destroy_ref(x):\n        x = run_infer_type(x)\n        x = to_cps(x)\n        x = run_infer_type(x)\n        y = un_cps(x)\n        y = run_infer_type(y)\n        # TODO(mbs): Revisit once DCE can eliminate dead writes.\n        x = run_opt_pass(\n            x,\n            tvm.transform.Sequential(\n                [\n                    transform.PartialEvaluate(),\n                    transform.InferType(),\n                    transform.DeadCodeElimination(inline_once=True, ignore_impurity=True),\n                ]\n            ),\n        )\n        assert Feature.fRefCreate not in detect_feature(x)\n\n    unit = relay.Function([], relay.const(0.0, dtype=\"float32\"))\n    f_ref = relay.Var(\"f_ref\")\n\n    one = relay.const(1.0, dtype=\"float32\")\n    two = relay.const(2.0, dtype=\"float32\")\n    cond = relay.var(shape=(), dtype=\"uint1\", name_hint=\"cond\")\n    true_branch = relay.RefWrite(f_ref, relay.Function([], one))\n    false_branch = relay.RefWrite(f_ref, relay.Function([], two))\n    if_expr = relay.If(cond, true_branch, false_branch)\n\n    stmt = relay.Let(\n        f_ref,\n        relay.RefCreate(unit),\n        relay.Let(relay.Var(\"x\"), if_expr, relay.Call(relay.RefRead(f_ref), [])),\n    )\n\n    F = relay.Function([cond], stmt)\n    destroy_ref(F)\n\n    G = relay.Function([cond], relay.If(cond, one, two))\n    G = run_infer_type(G)\n    G = relay.transform.gradient(G)\n    destroy_ref(G)\n\n    x = relay.var(\"x\", shape=(1, 16))\n    y = relay.var(\"y\", shape=(1, 16))\n    z = relay.var(\"z\", shape=(1, 16))\n    cond = relay.var(\"cond\", shape=(), dtype=\"uint1\")\n    H = relay.If(cond, x, y)\n    H = relay.add(H, z)\n    H = relay.Function([cond, x, y, z], H)\n    H = run_infer_type(H)\n    H = relay.transform.gradient(H)\n    destroy_ref(H)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_to_graph_normal_form.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import op, create_executor, transform\nfrom tvm.relay.analysis import Feature\nfrom tvm.relay.analysis import detect_feature\n\n\ndef run_opt_pass(expr, opt_pass):\n    mod = tvm.IRModule.from_expr(expr)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef check_eval(expr, args, expected_result, mod=None, rtol=1e-07):\n    if mod is None:\n        mod = tvm.IRModule()\n\n    dev = tvm.device(\"llvm\", 0)\n    result = create_executor(mod=mod, device=dev, target=\"llvm\").evaluate(expr)(*args)\n    np.testing.assert_allclose(result.numpy(), expected_result, rtol=rtol)\n\n\ndef test_implicit_share():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n    body = relay.Let(z, op.add(y, y), op.add(z, z))\n    body = relay.Let(y, op.add(x, x), body)\n    f = relay.Function([], relay.Let(x, relay.const(1), body))\n    g = run_opt_pass(f, transform.ToGraphNormalForm())\n    assert Feature.fLet in detect_feature(f)\n    assert not Feature.fLet in detect_feature(g)\n    check_eval(f, [], 8.0)\n    check_eval(g, [], 8.0)\n\n\ndef test_round_trip():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n    body = relay.Let(z, op.add(y, y), op.add(z, z))\n    body = relay.Let(y, op.add(x, x), body)\n    f = relay.Function([], relay.Let(x, relay.const(1), body))\n    g = run_opt_pass(f, transform.ToGraphNormalForm())\n    h = run_opt_pass(g, transform.ToANormalForm())\n    assert Feature.fLet in detect_feature(f)\n    assert not Feature.fLet in detect_feature(g)\n    check_eval(f, [], 8.0)\n    check_eval(g, [], 8.0)\n    check_eval(h, [], 8.0)\n\n\nif __name__ == \"__main__\":\n    test_implicit_share()\n    test_round_trip()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_unmatched_cases.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.analysis import unmatched_cases\nimport pytest\n\n\ndef test_empty_match_block():\n    # empty match block will not match anything, so it should return a wildcard pattern\n    v = relay.Var(\"v\")\n    match = relay.Match(v, [])\n\n    unmatched = unmatched_cases(match)\n    assert len(unmatched) == 1\n    assert isinstance(unmatched[0], relay.PatternWildcard)\n\n\ndef test_trivial_matches():\n    # a match clause with a wildcard will match anything\n    v = relay.Var(\"v\")\n    match = relay.Match(v, [relay.Clause(relay.PatternWildcard(), v)])\n    assert len(unmatched_cases(match)) == 0\n\n    # same with a pattern var\n    w = relay.Var(\"w\")\n    match = relay.Match(v, [relay.Clause(relay.PatternVar(w), w)])\n    assert len(unmatched_cases(match)) == 0\n\n\ndef test_single_constructor_adt():\n    mod = tvm.IRModule()\n    box = relay.GlobalTypeVar(\"box\")\n    a = relay.TypeVar(\"a\")\n    box_ctor = relay.Constructor(\"box\", [a], box)\n    box_data = relay.TypeData(box, [a], [box_ctor])\n    mod[box] = box_data\n\n    v = relay.Var(\"v\")\n    match = relay.Match(\n        v, [relay.Clause(relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]), v)]\n    )\n\n    # with one constructor, having one pattern constructor case is exhaustive\n    assert len(unmatched_cases(match, mod)) == 0\n\n    # this will be so if we nest the constructors too\n    nested_pattern = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    box_ctor,\n                    [\n                        relay.PatternConstructor(\n                            box_ctor,\n                            [relay.PatternConstructor(box_ctor, [relay.PatternWildcard()])],\n                        )\n                    ],\n                ),\n                v,\n            )\n        ],\n    )\n    assert len(unmatched_cases(nested_pattern, mod)) == 0\n\n\ndef test_too_specific_match():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = mod.get_type(\"List\")\n\n    v = relay.Var(\"v\")\n    match = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternWildcard(),\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                        ),\n                    ],\n                ),\n                v,\n            )\n        ],\n    )\n\n    unmatched = unmatched_cases(match, mod)\n\n    # will not match nil or a list of length 1\n    nil_found = False\n    single_length_found = False\n    assert len(unmatched) == 2\n    for case in unmatched:\n        assert isinstance(case, relay.PatternConstructor)\n        if case.constructor == nil:\n            nil_found = True\n        if case.constructor == cons:\n            assert isinstance(case.patterns[1], relay.PatternConstructor)\n            assert case.patterns[1].constructor == nil\n            single_length_found = True\n    assert nil_found and single_length_found\n\n    # if we add a wildcard, this should work\n    new_match = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternWildcard(),\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                        ),\n                    ],\n                ),\n                v,\n            ),\n            relay.Clause(relay.PatternWildcard(), v),\n        ],\n    )\n    assert len(unmatched_cases(new_match, mod)) == 0\n\n\ndef test_multiple_constructor_clauses():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = mod.get_type(\"List\")\n\n    v = relay.Var(\"v\")\n    match = relay.Match(\n        v,\n        [\n            # list of length exactly 1\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons, [relay.PatternWildcard(), relay.PatternConstructor(nil, [])]\n                ),\n                v,\n            ),\n            # list of length exactly 2\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternWildcard(),\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternConstructor(nil, [])]\n                        ),\n                    ],\n                ),\n                v,\n            ),\n            # empty list\n            relay.Clause(relay.PatternConstructor(nil, []), v),\n            # list of length 2 or more\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternWildcard(),\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                        ),\n                    ],\n                ),\n                v,\n            ),\n        ],\n    )\n    assert len(unmatched_cases(match, mod)) == 0\n\n\ndef test_missing_in_the_middle():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = mod.get_type(\"List\")\n\n    v = relay.Var(\"v\")\n    match = relay.Match(\n        v,\n        [\n            # list of length exactly 1\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons, [relay.PatternWildcard(), relay.PatternConstructor(nil, [])]\n                ),\n                v,\n            ),\n            # empty list\n            relay.Clause(relay.PatternConstructor(nil, []), v),\n            # list of length 3 or more\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternWildcard(),\n                        relay.PatternConstructor(\n                            cons,\n                            [\n                                relay.PatternWildcard(),\n                                relay.PatternConstructor(\n                                    cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                                ),\n                            ],\n                        ),\n                    ],\n                ),\n                v,\n            ),\n        ],\n    )\n\n    # fails to match a list of length exactly two\n    unmatched = unmatched_cases(match, mod)\n    assert len(unmatched) == 1\n    assert isinstance(unmatched[0], relay.PatternConstructor)\n    assert unmatched[0].constructor == cons\n    assert isinstance(unmatched[0].patterns[1], relay.PatternConstructor)\n    assert unmatched[0].patterns[1].constructor == cons\n    assert isinstance(unmatched[0].patterns[1].patterns[1], relay.PatternConstructor)\n    assert unmatched[0].patterns[1].patterns[1].constructor == nil\n\n\ndef test_mixed_adt_constructors():\n    mod = tvm.IRModule()\n    box = relay.GlobalTypeVar(\"box\")\n    a = relay.TypeVar(\"a\")\n    box_ctor = relay.Constructor(\"box\", [a], box)\n    box_data = relay.TypeData(box, [a], [box_ctor])\n    mod[box] = box_data\n\n    p = Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n\n    v = relay.Var(\"v\")\n    box_of_lists_inc = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    box_ctor,\n                    [\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                        )\n                    ],\n                ),\n                v,\n            )\n        ],\n    )\n\n    # will fail to match a box containing an empty list\n    unmatched = unmatched_cases(box_of_lists_inc, mod)\n    assert len(unmatched) == 1\n    assert isinstance(unmatched[0], relay.PatternConstructor)\n    assert unmatched[0].constructor == box_ctor\n    assert len(unmatched[0].patterns) == 1 and unmatched[0].patterns[0].constructor == nil\n\n    box_of_lists_comp = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(box_ctor, [relay.PatternConstructor(nil, [])]), v\n            ),\n            relay.Clause(\n                relay.PatternConstructor(\n                    box_ctor,\n                    [\n                        relay.PatternConstructor(\n                            cons, [relay.PatternWildcard(), relay.PatternWildcard()]\n                        )\n                    ],\n                ),\n                v,\n            ),\n        ],\n    )\n    assert len(unmatched_cases(box_of_lists_comp, mod)) == 0\n\n    list_of_boxes_inc = relay.Match(\n        v,\n        [\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                        relay.PatternWildcard(),\n                    ],\n                ),\n                v,\n            )\n        ],\n    )\n\n    # fails to match empty list of boxes\n    unmatched = unmatched_cases(list_of_boxes_inc, mod)\n    assert len(unmatched) == 1\n    assert isinstance(unmatched[0], relay.PatternConstructor)\n    assert unmatched[0].constructor == nil\n\n    list_of_boxes_comp = relay.Match(\n        v,\n        [\n            # exactly one box\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                        relay.PatternConstructor(nil, []),\n                    ],\n                ),\n                v,\n            ),\n            # exactly two boxes\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                        relay.PatternConstructor(\n                            cons,\n                            [\n                                relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                                relay.PatternConstructor(nil, []),\n                            ],\n                        ),\n                    ],\n                ),\n                v,\n            ),\n            # exactly three boxes\n            relay.Clause(\n                relay.PatternConstructor(\n                    cons,\n                    [\n                        relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                        relay.PatternConstructor(\n                            cons,\n                            [\n                                relay.PatternConstructor(box_ctor, [relay.PatternWildcard()]),\n                                relay.PatternConstructor(\n                                    cons,\n                                    [\n                                        relay.PatternConstructor(\n                                            box_ctor, [relay.PatternWildcard()]\n                                        ),\n                                        relay.PatternConstructor(nil, []),\n                                    ],\n                                ),\n                            ],\n                        ),\n                    ],\n                ),\n                v,\n            ),\n            # one or more boxes\n            relay.Clause(\n                relay.PatternConstructor(cons, [relay.PatternWildcard(), relay.PatternWildcard()]),\n                v,\n            ),\n            # no boxes\n            relay.Clause(relay.PatternConstructor(nil, []), v),\n        ],\n    )\n    assert len(unmatched_cases(list_of_boxes_comp, mod)) == 0\n\n\ndef test_tuple_match():\n    a = relay.Var(\"a\")\n    b = relay.Var(\"b\")\n    clause = relay.Clause(relay.PatternTuple([relay.PatternVar(a), relay.PatternVar(b)]), a + b)\n    x = relay.Match(relay.Tuple([relay.const(1), relay.const(1)]), [clause])\n    assert len(unmatched_cases(x)) == 0\n\n\ndef test_inf_loop_case():\n    code = \"\"\"\n#[version = \"0.0.5\"]\ntype Arith[A] {\n    Zero,\n    Const(A),\n    Plus(Arith[A], Arith[A])\n}\n\ndef @shallow_opt[A](%a: Arith[A]) -> Arith[A] {\n    match (%a) {\n        Plus(Zero, %r) => %r,\n        Plus(%l, Zero) => %l,\n        _ => %a\n    }\n}\n\"\"\"\n    tvm.parser.fromtext(code)\n    # fromtext parse the module, then checked it (which include strictness checking).\n\n\ndef test_expanding_ctor_with_no_args():\n    code = \"\"\"\n#[version = \"0.0.5\"]\ntype List[A] {\n    Cons(A, List[A]),\n    Nil,\n}\n\ndef @expand_on_nil_match(%a: List[(List[()],)]) -> int {\n    match (%a) {\n        Cons((Nil), Nil) => 1,\n        _ => 2,\n    }\n}\n\"\"\"\n    # exhausion checks:\n    # * hits Cons((Nil), Nil), expands to Cons(*, *), Nil()\n    # Nil() fails Cons((Nil), Nil), passes _\n    # Cons(*, *) hits Cons((Nil), Nil), expands to Cons((*), Cons(*, *)), Cons((*), Nil())\n    # Cons((*), Cons(*, *)) fails Cons((Nil), Nil), passes _\n    # Cons((*), Nil()) hits Cons((Nil), Nil), expands to Cons((Nil), Nil), Cons((Cons(*, *)), Nil)\n    # Cons((Nil), Nil) passes the first pattern\n    # Cons((Cons(*, *)), Nil) fails the first pattern, passes _\n    # Note Nil() is passed to ExpandWildcardsConstructor many times in the above!\n    tvm.parser.fromtext(code)\n\n\ndef test_expanding_empty_tuple():\n    # same principle as above, but with empty tuple\n    code = \"\"\"\n#[version = \"0.0.5\"]\ntype List[A] {\n    Cons(A, List[A]),\n    Nil,\n}\n\ndef @expand_on_empty_tuple_match(%a: (List[()], ())) -> int {\n    match (%a) {\n        (Cons((), Nil), ()) => 1,\n        _ => 2,\n    }\n}\n\"\"\"\n    tvm.parser.fromtext(code)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pass_vars.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.analysis import (\n    free_vars,\n    free_type_vars,\n    bound_vars,\n    bound_type_vars,\n    all_vars,\n    all_type_vars,\n)\n\n\ndef assert_vars_match(actual, expected):\n    assert len(actual) == len(expected)\n    for i in range(len(actual)):\n        assert actual[i] == expected[i]\n\n\ndef test_free_vars():\n    ty = relay.TensorType([], \"int32\")\n    x = relay.Var(\"x\", ty)\n    fvx = free_vars(x)\n    assert len(fvx) == 1\n    assert fvx[0] == x\n    v = relay.Constant(tvm.nd.array(10))\n\n    let = relay.Let(x, v, x)\n    fvx = free_vars(let)\n    assert len(free_vars(let)) == 0\n    f = relay.Function([x], x, ty)\n    assert len(free_vars(f)) == 0\n\n\ndef test_free_vars_tuple():\n    t = relay.Var(\"t\")\n    fv = free_vars(relay.Tuple([t, t]))\n    assert len(fv) == 1\n    assert fv[0] == t\n    fv = free_vars(relay.TupleGetItem(t, 123))\n    assert len(fv) == 1\n    assert fv[0] == t\n\n\ndef test_free_type_vars():\n    tp = relay.TypeVar(\"\")\n    ty = relay.TupleType([tp, relay.TensorType([], \"int32\")])\n    x = relay.Var(\"x\", ty)\n    y = relay.Var(\"y\")\n    let = relay.Let(x, y, x)\n    fvl = free_vars(let)\n    assert len(fvl) == 1\n    assert fvl[0] == y\n    ftvl = free_type_vars(let)\n    assert len(ftvl) == 1\n    assert ftvl[0] == tp\n\n\ndef test_bound_vars():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n    a = relay.Var(\"a\")\n\n    f1 = relay.Function([x, y, z], relay.Let(a, x, relay.Tuple([])))\n    assert_vars_match(bound_vars(f1), [x, y, z, a])\n\n    tup = relay.Tuple([x, y, z, a])\n    assert len(bound_vars(tup)) == 0\n\n    f2 = relay.Function([x, y], relay.Tuple([x, y, z, a]))\n    assert_vars_match(bound_vars(f2), [x, y])\n\n\ndef test_match_vars():\n    mod = tvm.IRModule()\n    p = relay.prelude.Prelude(mod)\n    rlist, cons, nil = p.mod.get_type(\"List\")\n\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n\n    match1 = relay.Match(\n        nil(),\n        [\n            relay.Clause(relay.PatternConstructor(nil), z),\n            relay.Clause(\n                relay.PatternConstructor(cons, [relay.PatternVar(x), relay.PatternVar(y)]),\n                cons(x, y),\n            ),\n        ],\n    )\n\n    match2 = relay.Match(\n        nil(),\n        [\n            relay.Clause(\n                relay.PatternConstructor(cons, [relay.PatternWildcard(), relay.PatternVar(x)]), y\n            ),\n            relay.Clause(relay.PatternWildcard(), z),\n        ],\n    )\n\n    assert_vars_match(bound_vars(match1), [x, y])\n    assert_vars_match(free_vars(match1), [z])\n    assert_vars_match(all_vars(match1), [z, x, y])\n\n    assert_vars_match(bound_vars(match2), [x])\n    assert_vars_match(free_vars(match2), [y, z])\n    assert_vars_match(all_vars(match2), [x, y, z])\n\n\ndef test_bound_type_vars():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    c = relay.TypeVar(\"c\")\n\n    ft1 = relay.FuncType([a], b, [a, b])\n    bound_ft1 = bound_type_vars(ft1)\n    assert_vars_match(bound_type_vars(ft1), [a, b])\n\n    ft2 = relay.FuncType([], c, [a])\n    assert_vars_match(bound_type_vars(ft2), [a])\n\n    tup_ty = relay.TupleType([a, b, c])\n    assert len(bound_type_vars(tup_ty)) == 0\n\n    f1 = relay.Function([], relay.Tuple([]), type_params=[a, b])\n    assert_vars_match(bound_type_vars(f1), [a, b])\n\n    f2 = relay.Function([], relay.Tuple([]), c)\n    assert len(bound_type_vars(f2)) == 0\n\n    x = relay.Var(\"x\", a)\n    let1 = relay.Let(x, relay.Tuple([]), x)\n    assert len(bound_type_vars(let1)) == 0\n\n    let2 = relay.Let(x, relay.Function([], relay.Tuple([]), type_params=[b, c]), x)\n    assert_vars_match(bound_type_vars(let2), [b, c])\n\n\ndef test_all_vars():\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n\n    f1 = relay.Function([x, y], z)\n    assert_vars_match(all_vars(f1), [x, y, z])\n\n    f2 = relay.Function([x], relay.Let(y, relay.Tuple([]), z))\n    assert_vars_match(all_vars(f2), [x, y, z])\n\n    f3 = relay.Function([x], relay.Tuple([y, z]))\n    assert_vars_match(all_vars(f3), [x, y, z])\n\n    tup = relay.Tuple([x, y, z])\n    assert_vars_match(all_vars(tup), [x, y, z])\n\n\ndef test_all_type_vars():\n    a = relay.TypeVar(\"a\")\n    b = relay.TypeVar(\"b\")\n    c = relay.TypeVar(\"c\")\n\n    ft1 = relay.FuncType([b], c, [a])\n    assert_vars_match(all_type_vars(ft1), [a, b, c])\n\n    ft2 = relay.FuncType([], relay.TupleType([a, b, c]), [])\n    assert_vars_match(all_type_vars(ft2), [a, b, c])\n\n    w = relay.Var(\"w\")\n    x = relay.Var(\"x\", a)\n    y = relay.Var(\"y\", b)\n    z = relay.Var(\"z\", c)\n\n    f1 = relay.Function([x], y, b, [a])\n    assert_vars_match(all_type_vars(f1), [a, b])\n\n    f2 = relay.Function([x], relay.Let(y, x, z))\n    assert_vars_match(all_type_vars(f2), [a, b, c])\n\n    f3 = relay.Function([], relay.Tuple([x, y, z]), ret_type=relay.TupleType([a, b, c]))\n    assert_vars_match(all_type_vars(f3), [a, b, c])\n\n    f4 = relay.Function([w], relay.Tuple([]), type_params=[a, b, c])\n    assert_vars_match(all_type_vars(f4), [a, b, c])\n\n    f5 = relay.Function([w], w)\n    assert len(all_type_vars(f5)) == 0\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_pipeline_executor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport os\nimport time\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay import transform, build_module\nfrom tvm.relay.testing import run_opt_pass\nfrom tvm.contrib import graph_executor, pipeline_executor, pipeline_executor_build\nfrom tvm._ffi import get_global_func\nfrom tvm.contrib import cc as _cc\n\n\ndef graph_split(expr, split_conf, params=None):\n    \"\"\"Splitting the graph into a list of subgraphs\"\"\"\n\n    def get_dep_var(sub_var_dep):\n        return [var for var in sub_var_dep[len(sub_var_dep) - 1][\"ref_nodes\"]]\n\n    def parse_dependency(value, snode_dep, new_input_idx):\n        new_args = []\n        need_update = False\n        for var in value.args:\n            is_free_var = False\n            for dep in snode_dep[:-1]:\n                if var in dep[\"nodes\"]:\n                    # Mark the previous subgraph node as a dependency.\n                    dep[\"nodes\"][var] += 1\n                    dep[\"ref_nodes\"][var] = dep[\"nodes\"][var]\n                    # The var of this call is a free_var\n                    is_free_var = True\n            # if the var of this call is a free_var, recreate it and give it a fixed input name.\n            if is_free_var:\n                need_update = True\n                new_args.append(relay.var(f\"data_n_{new_input_idx}\", var.checked_type))\n                new_input_idx += 1\n            else:\n                new_args.append(var)\n        # if the 'tvm.relay.expr.Call' has a free_var, recreate it with new name as 'data_n_*'.\n        if need_update:\n            value = tvm.relay.expr.Call(\n                value.op, new_args, value.attrs, value.type_args, value.span\n            )\n        return value, snode_dep, new_input_idx\n\n    def merge_constant_expr(constant_expr, expr):\n        # merge constant express with a express\n        if not isinstance(constant_expr.body, tvm.relay.expr.Let):\n            return tvm.relay.expr.Let(constant_expr.var, constant_expr.value, expr)\n\n        return tvm.relay.expr.Let(\n            constant_expr.var, constant_expr.value, merge_constant_expr(constant_expr.body, expr)\n        )\n\n    def _recursion(anf, pipeline_mods, split_conf, constant_expr):\n        # Enumurate all operators of compute graph, then split the compute graph into a group of\n        # subgraph.\n        nonlocal operator_index_map\n        nonlocal new_input_idx\n        nonlocal snode_dep\n        cur_node_dep = snode_dep[len(snode_dep) - 1]\n        if isinstance(anf, tvm.relay.Function):\n            return tvm.relay.Function(\n                anf.params,\n                _recursion(anf.body, pipeline_mods, split_conf, constant_expr),\n                anf.ret_type,\n                anf.type_params,\n                anf.attrs,\n            )\n        if isinstance(anf, tvm.relay.expr.Let):\n            value = anf.value\n            # record the constant expr to make sure all sugraphs can find correct constant.\n            if isinstance(value, tvm.relay.expr.Constant):\n                if not constant_expr:\n                    constant_expr = tvm.relay.expr.Let(anf.var, value, anf.var)\n                else:\n                    constant_expr = tvm.relay.expr.Let(anf.var, value, constant_expr)\n            if isinstance(value, tvm.relay.expr.Call):\n                new_args = []\n                # build current var list\n                cur_node_dep[\"nodes\"][anf.var] = 0\n                # Get the dependency information of the nodes.\n                value, snode_dep, new_input_idx = parse_dependency(value, snode_dep, new_input_idx)\n                if isinstance(value.op, tvm.ir.Op):\n                    if value.op.name in operator_index_map:\n                        operator_index_map[value.op.name] += 1\n                    else:\n                        operator_index_map[value.op.name] = 0\n                    split_operator_name = split_conf[0][\"op_name\"] if split_conf else \"\"\n                    split_operator_index = split_conf[0][\"op_index\"] if split_conf else \"\"\n                    # if a operator name and repeating count in the network match with the values\n                    # of the 'split configuration', then this place is where we should do the\n                    # graph splitting.\n                    if (\n                        split_conf\n                        and split_operator_name in operator_index_map\n                        and operator_index_map[split_operator_name] >= split_operator_index\n                    ):\n                        # Do graph splitting.\n                        split_conf.pop(0)\n                        snode_dep.append({\"nodes\": {}, \"ref_nodes\": {}})\n                        ann = _recursion(\n                            anf.body,\n                            pipeline_mods,\n                            split_conf,\n                            constant_expr,\n                        )\n                        snode_dep.pop()\n                        dep_vars = get_dep_var(snode_dep)\n                        # When the nodes of the current subgraph are the depedency node of another\n                        # subgraph, we need to set them as the output of current subgraph.\n                        body = relay.Tuple(dep_vars) if len(dep_vars) > 1 else anf.var\n                        # when the operator of current subgraph uses previous subgraph constant\n                        # as the argument of a \"relay.expr.call\", such constant may become a free\n                        # varaible if the constant does not exist in the current subgraph.\n                        # merge the previous constant with current subgraph to avoid such issue.\n                        if constant_expr:\n                            ann = merge_constant_expr(constant_expr, ann)\n                        ann = run_opt_pass(ann, transform.ToGraphNormalForm())\n                        mod = tvm.IRModule.from_expr(ann)\n                        pipeline_mods.insert(0, mod)\n                        # Return the last node of the current subgraph.\n                        return tvm.relay.expr.Let(anf.var, value, body)\n            return tvm.relay.expr.Let(\n                anf.var,\n                value,\n                _recursion(anf.body, pipeline_mods, split_conf, constant_expr),\n            )\n        else:\n            return anf\n\n    snode_dep = [{\"nodes\": {}, \"ref_nodes\": {}}]\n    pipeline_mods = []\n    operator_index_map = {}\n    # Used to tracking new input which caused by graph splitting.\n    new_input_idx = 0\n    constant_expr = None\n    subgraph_split_conf = split_conf.copy()\n    # Binding the parameters.\n    if params:\n        expr = build_module.bind_params_by_name(expr, params)\n    anf = run_opt_pass(expr, transform.ToANormalForm())\n    anf = run_opt_pass(anf, transform.InferType())\n    ann = _recursion(\n        anf,\n        pipeline_mods,\n        subgraph_split_conf,\n        constant_expr,\n    )\n    ann = run_opt_pass(ann.body, transform.ToGraphNormalForm())\n    mod = tvm.IRModule.from_expr(ann)\n    pipeline_mods.insert(0, mod)\n    return pipeline_mods\n\n\ndef get_network():\n    # Get a list of modules representing subgraphs.\n    mods = []\n    dshape = (3, 3)\n    data = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    data21 = relay.var(\"data_1\", relay.TensorType(dshape, \"float32\"))\n    data_net1_output_1 = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    data_net1_output_2 = relay.var(\"data_1\", relay.TensorType(dshape, \"float32\"))\n    data_net2_output_1 = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    mvalue1 = np.full((1), 1).astype(\"float32\")\n    mvalue2 = np.full((1), 2).astype(\"float32\")\n    mvalue3 = np.full((1), 3).astype(\"float32\")\n    mv1 = relay.Constant(tvm.nd.array(mvalue1))\n    mv2 = relay.Constant(tvm.nd.array(mvalue2))\n    mv3 = relay.Constant(tvm.nd.array(mvalue3))\n    # There are three outputs in the first model.\n    net1_output1 = relay.add(data, mv1)\n    net1_output2 = relay.subtract(data, mv2)\n    net1_output3 = relay.concatenate((net1_output1, net1_output2), axis=0)\n    (net1_output3, _) = relay.split(net1_output3, indices_or_sections=2, axis=0)\n    net1_output3 = relay.add(net1_output3, mv2)\n    # The second model uses the output named net1_output3 of the first model as the first input,\n    # the second input of the second model is data21.\n    net2 = relay.add(net1_output3, mv2)\n    net2 = relay.add(net2, data21)\n    net2_output = relay.add(net2, mv3)\n    # The third model uses the output named net2_output of the second model as the first input\n    # and uses the output named net1_output2 of the first model as the second input.\n    net3 = relay.multiply(net2_output, mv3)\n    net3 = relay.add(net3, net1_output2)\n    return tvm.IRModule.from_expr(relay.Function([data, data21], relay.Tuple([net3]))), dshape\n\n\ndef get_split_mod():\n    mod, dshape = get_network()\n    split_conf = [{\"op_name\": \"add\", \"op_index\": 1}, {\"op_name\": \"add\", \"op_index\": 4}]\n    mods = graph_split(mod[\"main\"], split_conf)\n    return mods, dshape\n\n\ndef get_mannual_mod():\n    # Get a list of modules representing subgraphs.\n    mods = []\n    dshape = (3, 3)\n    data = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    data21 = relay.var(\"data_1\", relay.TensorType(dshape, \"float32\"))\n    data_net1_output_1 = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    data_net1_output_2 = relay.var(\"data_1\", relay.TensorType(dshape, \"float32\"))\n    data_net2_output_1 = relay.var(\"data_0\", relay.TensorType(dshape, \"float32\"))\n    mvalue1 = np.full((1), 1).astype(\"float32\")\n    mvalue2 = np.full((1), 2).astype(\"float32\")\n    mvalue3 = np.full((1), 3).astype(\"float32\")\n    mv1 = relay.Constant(tvm.nd.array(mvalue1))\n    mv2 = relay.Constant(tvm.nd.array(mvalue2))\n    mv3 = relay.Constant(tvm.nd.array(mvalue3))\n\n    # There are three outputs in the first model.\n\n    net1_output1 = relay.add(data, mv1)\n    net1_output2 = relay.subtract(data, mv2)\n    net1_output3 = relay.multiply(data, mv3)\n\n    # The second model use output named net1_output1 of the first model as the first input,\n    # the second input of the second model is data21.\n    net2 = relay.add(data_net1_output_1, mv2)\n    net2 = relay.add(net2, data21)\n    net2_output = relay.add(net2, mv3)\n\n    # The third model use the output named net2_output of the second model as the first input\n    # and use the output named net1_output2 of the first model as the second input.\n    net3 = relay.multiply(data_net2_output_1, mv3)\n    net3 = relay.add(net3, data_net1_output_2)\n\n    mods.append(\n        tvm.IRModule.from_expr(\n            relay.Function([data], relay.Tuple([net1_output1, net1_output2, net1_output3]))\n        )\n    )\n    mods.append(tvm.IRModule.from_expr(relay.Function([data_net1_output_1, data21], net2_output)))\n    mods.append(\n        tvm.IRModule.from_expr(relay.Function([data_net1_output_2, data_net2_output_1], net3))\n    )\n\n    return mods, dshape\n\n\ndef get_manual_conf(mods, target):\n    # This function is used to generate manual pipeline configuration.\n    mod_config = {}\n    # The third output is the final output, the second output is for mod3, the first output\n    # is for mod2 input.\n    pipe_config1 = {\n        \"mod_idx\": 0,\n        \"cpu_affinity\": \"0\",\n        \"output\": [\n            {\"output_idx\": 0, \"dependencies\": [{\"mod_idx\": 1, \"input_name\": \"data_n_0\"}]},\n            {\"output_idx\": 1, \"dependencies\": [{\"mod_idx\": 2, \"input_name\": \"data_n_2\"}]},\n        ],\n    }\n    mod_config[mods[0]] = {\n        \"pipeline\": pipe_config1,\n        \"target_host\": None,\n        \"mod_name\": \"default\",\n        \"build\": None,\n        \"params\": None,\n        \"target\": target[0],\n        \"fcompile\": _cc.create_shared,\n        \"dev\": target[1],\n    }\n\n    pipe_config2 = {\n        \"mod_idx\": 1,\n        \"cpu_affinity\": \"0\",\n        \"output\": [\n            {\"output_idx\": 0, \"dependencies\": [{\"mod_idx\": 2, \"input_name\": \"data_n_1\"}]},\n        ],\n    }\n    mod_config[mods[1]] = {\n        \"pipeline\": pipe_config2,\n        \"target_host\": None,\n        \"mod_name\": \"default\",\n        \"build\": None,\n        \"params\": None,\n        \"target\": \"llvm\",\n        \"fcompile\": None,\n        \"dev\": tvm.cpu(0),\n    }\n\n    pipe_config3 = {\n        \"mod_idx\": 2,\n        \"cpu_affinity\": \"0\",\n        \"output\": [{\"output_idx\": 0, \"dependencies\": [{\"global_output_index\": 0}]}],\n    }\n    mod_config[mods[2]] = {\n        \"pipeline\": pipe_config3,\n        \"target_host\": None,\n        \"mod_name\": \"default\",\n        \"build\": None,\n        \"params\": None,\n        \"target\": \"llvm\",\n        \"fcompile\": None,\n        \"dev\": tvm.cpu(0),\n    }\n    return mod_config\n\n\ndef recreate_parameters(mod):\n    # Get the binding parameters from a module, then create the same parameters with different data.\n    # This function is used to test the \"parameter\" connection.\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(mod, \"llvm\")\n\n    mod_customized_params = {}\n    for key, value in lib.params.items():\n        new_value = value.numpy() + np.full(value.shape, 10).astype(value.dtype)\n        mod_customized_params[key] = tvm.nd.array(new_value)\n    return mod_customized_params, mod\n\n\ndef run_modules(\n    mod_configs,\n    dev,\n    target,\n    global_input_name,\n    global_input_data,\n    mod_set_input,\n    input_name,\n    input_data,\n    params_mod=None,\n    params=None,\n):\n    # Running modules in serialized model. The returnning data are used to verify the pipeline\n    # executor result.\n    mod_input = {}\n    final_output = {}\n    idx = 0\n    for mod in mod_configs:\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(mod, target)\n\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        # Getting the input data then setting the input data into the module.\n        if idx in mod_input:\n            for input in mod_input[idx]:\n                input = mod_input[idx][input]\n                m.set_input(input[\"index\"], input[\"data\"])\n        else:\n            m.set_input(global_input_name, global_input_data)\n\n        # Setting the \"input_data\" into the module.\n        if mod == mod_set_input:\n            m.set_input(input_name, input_data)\n        # If the module is \"params_mod\" then setting the parameters to this module.\n        if params_mod == mod:\n            m.set_input(None, None, **params)\n\n        m.run()\n        n = m.get_num_outputs()\n        # Setting current output data as  the input of next module.\n        mconfig = mod_configs[mod]\n        for output in mconfig[\"pipeline\"][\"output\"]:\n            output_data = m.get_output(output[\"output_idx\"]).numpy()\n            for dep in output[\"dependencies\"]:\n                is_global = False\n                if \"global_output_index\" in dep:\n                    is_global = True\n                    name = dep[\"global_output_index\"]\n                else:\n                    mod_idx = dep[\"mod_idx\"]\n                    name = dep[\"input_name\"]\n                if is_global:\n                    final_output[name] = output_data\n                else:\n                    if mod_idx in mod_input:\n                        mod_input[mod_idx][name] = {\"index\": name, \"data\": output_data}\n                    else:\n                        mod_input[mod_idx] = {name: {\"index\": name, \"data\": output_data}}\n        idx = idx + 1\n\n    return final_output\n\n\ndef reset_cpu_affinity(affinity):\n    # Restore the CPU affinity into the default value.\n    config_threadpool = get_global_func(\"runtime.config_threadpool\")\n    config_threadpool(-2, 0)\n    os.sched_setaffinity(0, affinity)\n\n\ndef test_pipe_runtime_error_check():\n    # This function is used to trigger runtime error by applying wrong logic.\n    if pipeline_executor_build.pipeline_executor_build_enabled():\n        # Get three pipeline modules here.\n        (mod1, mod2, mod3), dshape = get_split_mod()\n\n        # The input or output name is illegal and expects a runtime error.\n        pipe_error = pipeline_executor_build.PipelineConfig()\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"output\"][9]\n\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"input\"][\"data_9\"]\n\n        # The module connection will cause a cycle in DAG and expects runtime error.\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"output\"][0].connect(pipe_error[mod2][\"input\"][\"data_0\"])\n            pipe_error[mod2][\"output\"][0].connect(pipe_error[mod1][\"input\"][\"data_0\"])\n\n        # The module connection is illegal and expects runtime error.\n\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"output\"][0].connect(pipe_error[mod1][\"input\"][\"data_0\"])\n\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"input\"][\"data_0\"].connect(pipe_error[mod1][\"input\"][\"data_0\"])\n\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"input\"][\"data_0\"].connect(pipe_error[mod2][\"input\"][\"data_0\"])\n\n        with pytest.raises(RuntimeError):\n            pipe_error[mod1][\"output\"][0].connect(pipe_error[\"input\"][\"data_0\"])\n\n        with pytest.raises(RuntimeError):\n            pipe_error[\"input\"][\"data_0\"].connect(pipe_error[mod1][\"output\"][0])\n\n        with pytest.raises(RuntimeError):\n            pipe_error[\"output\"][\"0\"].connect(pipe_error[mod1][\"output\"][0])\n\n        # Create pipeline executor to check the executor runtime errors.\n        pipe_config = pipeline_executor_build.PipelineConfig()\n        pipe_config[mod1].target = \"llvm\"\n        pipe_config[mod1].dev = tvm.cpu(0)\n        pipe_config[\"param_group\"][\"param_0\"].connect(pipe_config[mod1][\"param\"])\n        pipe_config[mod1][\"output\"][0].connect(pipe_config[\"output\"][\"0\"])\n        # Build and create a pipeline module.\n        with tvm.transform.PassContext(opt_level=3):\n            pipeline_mod_factory = pipeline_executor_build.build(pipe_config)\n        pipeline_module = pipeline_executor.PipelineModule(pipeline_mod_factory)\n        customized_parameters, _ = recreate_parameters(mod1)\n\n        # Checking the pipeline executor runtime errors.\n        with pytest.raises(RuntimeError):\n            pipeline_module.set_params(\"param_0\", None)\n\n        with pytest.raises(RuntimeError):\n            pipeline_module.set_params(\"param_1\", customized_parameters)\n\n\ndef test_pipeline():\n    if pipeline_executor_build.pipeline_executor_build_enabled():\n        target_list = tvm.testing.enabled_targets()\n        for target in target_list:\n            affinity = os.sched_getaffinity(0)\n            # Get the three pipeline modules here.\n            (mod1, mod2, mod3), dshape = get_split_mod()\n\n            # Prepare batch data for pipeline computation.\n            datas = []\n            for i in range(5):\n                datas.append(np.full(dshape, 3 + i).astype(\"float32\"))\n\n            pipe_config = pipeline_executor_build.PipelineConfig()\n\n            customized_parameters, customized_parameters_mod = recreate_parameters(mod1)\n            assert customized_parameters_mod == mod1\n            # The global parameters group named \"param_0\" will be connected to \"mod1\" as parameters.\n            pipe_config[\"param_group\"][\"param_0\"].connect(pipe_config[mod1][\"param\"])\n            # The pipeline input named \"data_a\" will be connected to a input named \"data_0\"\n            # of mod1.\n            pipe_config[\"input\"][\"data_a\"].connect(pipe_config[mod1][\"input\"][\"data_0\"])\n\n            # The pipeline Input named \"data_b\" will be connected to a input named \"data_1\"\n            # of mod2.\n            pipe_config[\"input\"][\"data_b\"].connect(pipe_config[mod2][\"input\"][\"data_1\"])\n\n            # The mod1 output[0] will be connected to a input named \"data_n_0\" of mod2.\n            pipe_config[mod1][\"output\"][0].connect(pipe_config[mod2][\"input\"][\"data_n_0\"])\n\n            # The mod1 output[1] will be connected to a input named \"data_n_2\" of mod3.\n            pipe_config[mod1][\"output\"][1].connect(pipe_config[mod3][\"input\"][\"data_n_2\"])\n\n            # The mod2 output[2] will be connected to a input named \"data_n_1\" of mod3.\n            pipe_config[mod2][\"output\"][0].connect(pipe_config[mod3][\"input\"][\"data_n_1\"])\n\n            # The mod3 output[0] will be connected to pipeline output[0].\n            pipe_config[mod3][\"output\"][0].connect(pipe_config[\"output\"][\"0\"])\n            # Print configuration (print(pipe_config)), the result looks like following.\n            #\n            # Params\n            #   |param_0: mod0:param\n            #\n            # Inputs\n            #   |data_a: mod0:data_0\n            #   |data_b: mod1:data_1\n            #\n            # output\n            #   |output(0) : mod2.output(0)\n            #\n            # connections\n            #   |mod0.output(0)-> mod1.data_n_0\n            #   |mod0.output(1)-> mod2.data_n_2\n            #   |mod1.output(0)-> mod2.data_n_1\n\n            # Set other parameters.\n            pipe_config[mod1].target = target[0]\n            pipe_config[mod1].dev = target[1]\n            pipe_config[mod1].cpu_affinity = \"0\"\n            pipe_config[mod1].fcompile = _cc.create_shared\n\n            pipe_config[mod2].target = \"llvm\"\n            pipe_config[mod2].dev = tvm.cpu(0)\n            pipe_config[mod2].cpu_affinity = \"0\"\n\n            pipe_config[mod3].target = \"llvm\"\n            pipe_config[mod3].dev = tvm.cpu(0)\n            pipe_config[mod3].cpu_affinity = \"0\"\n            # Checking the configuration of modules dependency.\n            mconfig = pipe_config.get_config()\n            assert mconfig[\"module_connection\"] == get_manual_conf([mod1, mod2, mod3], target)\n\n            # Build and create a pipeline module.\n            with tvm.transform.PassContext(opt_level=3):\n                pipeline_mod_factory = pipeline_executor_build.build(pipe_config)\n\n            # Export the parameter configuration to a file.\n            directory_path = tvm.contrib.utils.tempdir().temp_dir\n            # If the directory does not exist, create it.\n            if not os.path.exists(directory_path):\n                os.makedirs(directory_path)\n            config_file_name = pipeline_mod_factory.export_library(directory_path)\n\n            # Use the output of build to create and initialize PipelineModule.\n            pipeline_module = pipeline_executor.PipelineModule(pipeline_mod_factory)\n            assert pipeline_module\n\n            # Use the import function to create and initialize PipelineModule.\n            pipeline_module_test = pipeline_executor.PipelineModule.load_library(config_file_name)\n            assert pipeline_module_test.num_outputs == 1\n\n            input_map = pipeline_module_test.get_input_pipeline_map(\"data_b\")\n            assert input_map[0] == \"1\" and input_map[1] == \"data_1\"\n            input_map = pipeline_module_test.get_input_pipeline_map(\"data_a\")\n            assert input_map[0] == \"0\" and input_map[1] == \"data_0\"\n            module_index = pipeline_module_test.get_params_group_pipeline_map(\"param_0\")\n            assert module_index == 0\n            # Using the parameters group name to set parameters.\n            pipeline_module_test.set_params(\"param_0\", customized_parameters)\n            normal_outputs = []\n            for round in range(0, len(datas)):\n                data = datas[round]\n                # Getting the result without setting customized parameters.\n                wrong_output = run_modules(\n                    mconfig[\"module_connection\"],\n                    tvm.cpu(),\n                    \"llvm\",\n                    \"data_0\",\n                    data,\n                    mod2,\n                    \"data_1\",\n                    data,\n                )\n                # Getting the result with setting customized parameters.\n                normal_output = run_modules(\n                    mconfig[\"module_connection\"],\n                    tvm.cpu(),\n                    \"llvm\",\n                    \"data_0\",\n                    data,\n                    mod2,\n                    \"data_1\",\n                    data,\n                    customized_parameters_mod,\n                    customized_parameters,\n                )\n                # Appending the normal output into the list in order to do future correctness\n                # checking.\n                normal_outputs.append(normal_output)\n                # Setting the input data into the pipeline executor.\n                pipeline_module_test.set_input(\"data_a\", tvm.nd.array(data))\n                pipeline_module_test.set_input(\"data_b\", tvm.nd.array(data))\n                input_map = pipeline_module_test.get_input_pipeline_map(\"data_a\")\n                # Checking whether the input setting of the first runtime is successful.\n                # The input of the rest of runtime will go into a queue and we can not check\n                # these input data here.\n                if input_map[0] == \"0\":\n                    input_data = pipeline_module_test.get_input(\"data_a\")\n                    tvm.testing.assert_allclose(data, input_data.numpy())\n\n                assert pipeline_module_test.num_inputs == 2\n                # Running the pipeline executor in the pipeline mode.\n                pipeline_module_test.run()\n\n            for k in range(0, len(datas)):\n                statistic_time = 0\n                outputs = pipeline_module_test.get_output()\n                while len(outputs) == 0:\n                    outputs = pipeline_module_test.get_output()\n                    statistic_time = statistic_time + 1\n                    # Setting the timeout to 10 seconds.\n                    assert statistic_time < 5\n                    time.sleep(1)\n\n                for i in range(len(outputs)):\n                    tvm.testing.assert_allclose(normal_outputs[k][i], outputs[i].numpy())\n                    assert not (normal_output[i] == wrong_output[i]).all()\n\n                    assert pipeline_module_test.num_executing_pipeline == round + 1\n\n            # Reset the cpu affinity after a test.\n            reset_cpu_affinity(affinity)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_prng.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nimport tvm.relay\nimport tvm.testing\nfrom tvm.relay.testing import run_infer_type\n\n\n@tvm.testing.parametrize_targets\ndef test_threefry_repeatability(target, dev):\n    key1 = tvm.relay.random.threefry_key(1)\n    rand1 = tvm.relay.random.threefry_generate(key1, (12,))\n    out_key1, out1 = tvm.relay.create_executor(\n        \"vm\", tvm.IRModule.from_expr(tvm.relay.Function([], rand1)), target=target, device=dev\n    ).evaluate()()\n\n    key2 = tvm.relay.random.threefry_key(1)\n    rand2 = tvm.relay.random.threefry_generate(key2, (12,))\n    out_key2, out2 = tvm.relay.create_executor(\n        \"vm\", tvm.IRModule.from_expr(tvm.relay.Function([], rand2)), target=target, device=dev\n    ).evaluate()()\n\n    assert (\n        out1.numpy() == out2.numpy()\n    ).all(), \"Generate on same seed should have the same output random numbers\"\n\n    assert (\n        out_key1.numpy() == out_key2.numpy()\n    ).all(), \"Generate on same seed should have the same next keys\"\n\n\n@tvm.testing.parametrize_targets\ndef test_threefry_split(target, dev):\n    key = tvm.relay.random.threefry_key(1)\n    left, right = tvm.relay.TupleWrapper(tvm.relay.random.threefry_split(key), 2)\n    _, rand1 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(left, (16,)), 2)\n    _, rand2 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(right, (16,)), 2)\n    out1, out2 = tvm.relay.create_executor(\n        \"vm\",\n        tvm.IRModule.from_expr(tvm.relay.Function([], tvm.relay.Tuple((rand1, rand2)))),\n        target=target,\n        device=dev,\n    ).evaluate()()\n\n    assert (\n        out1.numpy() != out2.numpy()\n    ).any(), \"Generate after split should not have the same output\"\n\n\n@tvm.testing.parametrize_targets\ndef test_threefry_sequential_generate(target, dev):\n    key = tvm.relay.random.threefry_key(1)\n    key, rand1 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(key, (4,)), 2)\n    _, rand2 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(key, (4,)), 2)\n    out1, out2 = tvm.relay.create_executor(\n        \"vm\",\n        tvm.IRModule.from_expr(tvm.relay.Function([], tvm.relay.Tuple((rand1, rand2)))),\n        target=target,\n        device=dev,\n    ).evaluate()()\n\n    assert (\n        out1.numpy() != out2.numpy()\n    ).any(), \"Sequential generates should not have the same output\"\n\n\n@tvm.testing.parametrize_targets\ndef test_threefry_sequential_generate_remaining(target, dev):\n    key = tvm.relay.random.threefry_key(1)\n    key, rand1 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(key, (7,)), 2)\n    _, rand2 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(key, (7,)), 2)\n    out1, out2 = tvm.relay.create_executor(\n        \"vm\",\n        tvm.IRModule.from_expr(tvm.relay.Function([], tvm.relay.Tuple((rand1, rand2)))),\n        target=target,\n        device=dev,\n    ).evaluate()()\n\n    assert (\n        out1.numpy()[-3:] != out2.numpy()[-3:]\n    ).any(), \"Sequential generates should not have the same output\"\n\n\ndef test_threefry_generate_infer():\n    oshape = (12,)\n    key_type = tvm.relay.TensorType([10], dtype=\"uint64\")\n    gen_type = tvm.relay.TensorType(oshape, dtype=\"uint64\")\n    expected_type = tvm.relay.TupleType([key_type, gen_type])\n\n    key = tvm.relay.random.threefry_key(1)\n    rand1 = tvm.relay.random.threefry_generate(key, oshape)\n    f = tvm.relay.Function([], rand1)\n    f = run_infer_type(f)\n    assert tvm.ir.structural_equal(f.ret_type, expected_type)\n\n\ndef test_threefry_split_infer():\n    key_type = tvm.relay.TensorType([10], dtype=\"uint64\")\n    expected_type = tvm.relay.TupleType([key_type, key_type])\n\n    key = tvm.relay.random.threefry_key(1)\n    out_keys = tvm.relay.random.threefry_split(key)\n    f = tvm.relay.Function([], out_keys)\n    f = run_infer_type(f)\n    assert tvm.ir.structural_equal(f.ret_type, expected_type)\n\n\ndef test_uniform_infer():\n    oshape = (12,)\n    odtypes = [\"float32\", \"float64\"]\n    for odtype in odtypes:\n        key_type = tvm.relay.TensorType([10], dtype=\"uint64\")\n        gen_type = tvm.relay.TensorType(oshape, dtype=odtype)\n        expected_type = tvm.relay.TupleType([key_type, gen_type])\n\n        key = tvm.relay.random.threefry_key(1)\n        rand1 = tvm.relay.random.uniform(key, oshape, odtype)\n        f = tvm.relay.Function([], rand1)\n        f = run_infer_type(f)\n        assert tvm.ir.structural_equal(f.ret_type, expected_type)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_threefry_generate_infer_fail():\n    # xfail: key size should be 10\n    fake_key = tvm.relay.const([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=\"uint64\")\n    rand1 = tvm.relay.random.threefry_generate(fake_key, (12,))\n    f = tvm.relay.Function([], rand1)\n    f = run_infer_type(f)\n\n\n@pytest.mark.xfail(raises=tvm.error.TVMError)\ndef test_threefry_split_infer_fail():\n    # xfail: key size should be 10\n    fake_key = tvm.relay.const([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=\"uint64\")\n    out_keys = tvm.relay.random.threefry_split(fake_key)\n    f = tvm.relay.Function([], out_keys)\n    f = run_infer_type(f)\n\n\n@tvm.testing.requires_llvm\ndef test_threefry_generate_out_size():\n    key = tvm.relay.random.threefry_key(1)\n    key, rand1 = tvm.relay.TupleWrapper(tvm.relay.random.threefry_generate(key, (5,)), 2)\n    out = tvm.relay.create_executor(\n        \"vm\",\n        tvm.IRModule.from_expr(tvm.relay.Function([], rand1)),\n        target=tvm.target.Target(\"llvm\"),\n        device=tvm.device(\"cpu\"),\n    ).evaluate()()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_py_converter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay.testing import to_python, run_as_python\nfrom tvm.relay.prelude import Prelude\nfrom tvm.runtime.container import ADT\nfrom tvm.relay.backend.interpreter import RefValue, ConstructorValue\n\n# helper: uses a dummy let binding to sequence a list\n# of expressions: expr1; expr2; expr3, etc.\ndef seq(*exprs):\n    ret = exprs[0]\n    for expr in exprs[1:]:\n        ret = relay.Let(relay.var(\"_\"), ret, expr)\n    return ret\n\n\n# creates a dummy ADT for testing\ndef init_box_adt(mod):\n    box = relay.GlobalTypeVar(\"box\")\n    a = relay.TypeVar(\"a\")\n    box_ctor = relay.Constructor(\"box\", [a], box)\n    mod[box] = relay.TypeData(box, [a], [box_ctor])\n    return (box, box_ctor)\n\n\n# assert that the candidate is a NDArray with value val\ndef assert_tensor_value(candidate, val):\n    assert isinstance(candidate, tvm.nd.NDArray)\n    assert np.array_equal(candidate.numpy(), np.array(val))\n\n\n# assert that the candidate is an ADT with the indicated number of fields\ndef assert_adt_len(candidate, fields):\n    assert isinstance(candidate, ADT)\n    assert len(candidate) == fields\n\n\n# assert that the candidate is a ConstructorValue with the approrpaite constructor\n# and number of fields\ndef assert_constructor_value(candidate, constructor, fields):\n    assert isinstance(candidate, ConstructorValue)\n    assert candidate.tag == constructor.tag\n    assert len(candidate.fields) == fields\n\n\ndef test_create_empty_tuple():\n    empty = relay.Tuple([])\n    tup_val = run_as_python(empty)\n    assert_adt_len(tup_val, 0)\n\n\ndef test_create_scalar():\n    scalar = relay.const(1)\n    tensor_val = run_as_python(scalar)\n    print(type(tensor_val))\n    assert_tensor_value(tensor_val, 1)\n\n\ndef test_create_tensor():\n    tensor = relay.const([[1, 1], [2, 2]])\n    tensor_val = run_as_python(tensor)\n    assert_tensor_value(tensor_val, [[1, 1], [2, 2]])\n\n\ndef test_create_nested_tuple():\n    relay_tup = relay.Tuple(\n        [relay.const(1), relay.const(2), relay.Tuple([relay.const(3), relay.const(4)])]\n    )\n    tup_val = run_as_python(relay_tup)\n    assert_adt_len(tup_val, 3)\n    for i in range(2):\n        assert_tensor_value(tup_val[i], i + 1)\n    assert_adt_len(tup_val[2], 2)\n    for i in range(2):\n        assert_tensor_value(tup_val[2][i], i + 3)\n\n\ndef test_tuple_get_item():\n    relay_tup = relay.Tuple(\n        [relay.const(1), relay.const(2), relay.Tuple([relay.const(3), relay.const(4)])]\n    )\n    for i in range(2):\n        index = relay.TupleGetItem(relay_tup, i)\n        val = run_as_python(index)\n        assert_tensor_value(val, i + 1)\n    # try the inner value too\n    for i in range(2):\n        index = relay.TupleGetItem(relay.TupleGetItem(relay_tup, 2), i)\n        val = run_as_python(index)\n        assert_tensor_value(val, i + 3)\n\n\ndef test_create_let():\n    v = relay.Var(\"v\")\n    let = relay.Let(v, relay.Tuple([]), relay.Tuple([v, v]))\n    tup_val = run_as_python(let)\n    assert_adt_len(tup_val, 2)\n    assert_adt_len(tup_val[0], 0)\n    assert_adt_len(tup_val[1], 0)\n\n\ndef test_create_ref():\n    relay_ref = relay.RefCreate(relay.Tuple([]))\n    ref_val = run_as_python(relay_ref)\n    assert isinstance(ref_val, RefValue)\n    assert_adt_len(ref_val.value, 0)\n\n\ndef test_ref_read():\n    v = relay.Var(\"v\")\n    assign = relay.Let(v, relay.RefCreate(relay.Tuple([])), relay.RefRead(v))\n    read_val = run_as_python(assign)\n    assert_adt_len(read_val, 0)\n\n\ndef test_ref_write():\n    # check that the result of a ref write is an empty tuple\n    v = relay.Var(\"v\")\n    initial_write = relay.Let(\n        v,\n        relay.RefCreate(relay.Tuple([relay.const(1)])),\n        relay.RefWrite(v, relay.Tuple([relay.const(2)])),\n    )\n    write_val = run_as_python(initial_write)\n    assert_adt_len(write_val, 0)\n\n    # now ensure that the value, once written, can be read back\n    # (we read the value before and after mutation)\n    w = relay.Var(\"w\")\n    read_after_write = relay.Let(\n        v,\n        relay.RefCreate(relay.Tuple([relay.const(1)])),\n        relay.Let(\n            w,\n            relay.RefCreate(relay.RefRead(v)),\n            seq(\n                relay.RefWrite(v, relay.Tuple([relay.const(2)])),\n                relay.Tuple([relay.RefRead(w), relay.RefRead(v)]),\n            ),\n        ),\n    )\n    read_val = run_as_python(read_after_write)\n    assert_adt_len(read_val, 2)\n    assert_adt_len(read_val[0], 1)\n    assert_adt_len(read_val[1], 1)\n    assert_tensor_value(read_val[0][0], 1)\n    assert_tensor_value(read_val[1][0], 2)\n\n\ndef test_if():\n    # we will have effects in the blocks to ensure only the intended one is executed\n    true_cond = relay.const(True)\n    false_cond = relay.const(False)\n\n    v = relay.Var(\"v\")\n    true_branch = seq(relay.RefWrite(v, relay.const(1)), relay.RefRead(v))\n    false_branch = seq(relay.RefWrite(v, relay.const(2)), relay.RefRead(v))\n\n    true_expr = relay.Let(\n        v, relay.RefCreate(relay.const(0)), relay.If(true_cond, true_branch, false_branch)\n    )\n    false_expr = relay.Let(\n        v, relay.RefCreate(relay.const(0)), relay.If(false_cond, true_branch, false_branch)\n    )\n\n    true_val = run_as_python(true_expr)\n    assert_tensor_value(true_val, 1)\n\n    false_val = run_as_python(false_expr)\n    assert_tensor_value(false_val, 2)\n\n\ndef test_local_function():\n    v = relay.Var(\"v\")\n    ident = relay.Function([v], v)\n    f = relay.Var(\"f\")\n    call1 = relay.Let(f, ident, f(relay.Tuple([])))\n    call2 = relay.Let(f, ident, f(relay.const(2)))\n\n    call_val1 = run_as_python(call1)\n    assert_adt_len(call_val1, 0)\n\n    call_val2 = run_as_python(call2)\n    assert_tensor_value(call_val2, 2)\n\n\ndef test_global_function():\n    mod = tvm.IRModule()\n    ident = relay.GlobalVar(\"ident\")\n    a = relay.TypeVar(\"a\")\n    v = relay.Var(\"v\", a)\n    mod[ident] = relay.Function([v], v, a, [a])\n\n    call1 = ident(relay.const(1))\n    call2 = ident(relay.Tuple([relay.const(2), relay.const(2)]))\n\n    call_val1 = run_as_python(call1, mod)\n    assert_tensor_value(call_val1, 1)\n\n    call_val2 = run_as_python(call2, mod)\n    assert_adt_len(call_val2, 2)\n    assert_tensor_value(call_val2[0], 2)\n    assert_tensor_value(call_val2[1], 2)\n\n\ndef test_constructor():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n\n    init_box_int = box_ctor(relay.const(1))\n    box_val_int = run_as_python(init_box_int, mod)\n\n    assert_constructor_value(box_val_int, box_ctor, 1)\n    assert_tensor_value(box_val_int.fields[0], 1)\n\n    init_box_tup = box_ctor(relay.Tuple([]))\n    box_val_tup = run_as_python(init_box_tup, mod)\n\n    assert_constructor_value(box_val_tup, box_ctor, 1)\n    assert_adt_len(box_val_tup.fields[0], 0)\n\n\ndef test_match_wildcard():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n    v = relay.Var(\"v\")\n    match = relay.Let(\n        v,\n        box_ctor(relay.Tuple([])),\n        relay.Match(v, [relay.Clause(relay.PatternWildcard(), relay.const(1))]),\n    )\n\n    match_val = run_as_python(match, mod)\n    assert_tensor_value(match_val, 1)\n\n\ndef test_match_var():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n    v = relay.Var(\"v\")\n    w = relay.Var(\"w\")\n    match = relay.Let(\n        v, box_ctor(relay.const(1)), relay.Match(v, [relay.Clause(relay.PatternVar(w), w)])\n    )\n\n    match_val = run_as_python(match, mod)\n    assert_constructor_value(match_val, box_ctor, 1)\n    assert_tensor_value(match_val.fields[0], 1)\n\n\ndef test_match_pattern():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n    v = relay.Var(\"v\")\n    w = relay.Var(\"w\")\n    match = relay.Let(\n        v,\n        box_ctor(relay.const(1)),\n        relay.Match(\n            v, [relay.Clause(relay.PatternConstructor(box_ctor, [relay.PatternVar(w)]), w)]\n        ),\n    )\n    match_val = run_as_python(match, mod)\n    assert_tensor_value(match_val, 1)\n\n\ndef test_nested_match_pattern():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n    v = relay.Var(\"v\")\n    w = relay.Var(\"w\")\n    match = relay.Let(\n        v,\n        box_ctor(box_ctor(relay.const(2))),\n        relay.Match(\n            v,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(\n                        box_ctor, [relay.PatternConstructor(box_ctor, [relay.PatternVar(w)])]\n                    ),\n                    w,\n                )\n            ],\n        ),\n    )\n    match_val = run_as_python(match, mod)\n    assert_tensor_value(match_val, 2)\n\n\ndef test_match_order():\n    mod = tvm.IRModule()\n    box, box_ctor = init_box_adt(mod)\n    v = relay.Var(\"v\")\n    w = relay.Var(\"w\")\n    # wildcard pattern goes first\n    match = relay.Let(\n        v,\n        box_ctor(box_ctor(relay.const(2))),\n        relay.Match(\n            v,\n            [\n                relay.Clause(relay.PatternWildcard(), relay.const(1)),\n                relay.Clause(\n                    relay.PatternConstructor(\n                        box_ctor, [relay.PatternConstructor(box_ctor, [relay.PatternVar(w)])]\n                    ),\n                    w,\n                ),\n            ],\n        ),\n    )\n    match_val = run_as_python(match, mod)\n    assert_tensor_value(match_val, 1)\n\n\ndef test_local_recursion():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n\n    v = relay.Var(\"v\")\n    h = relay.Var(\"h\")\n    t = relay.Var(\"t\")\n    f = relay.Var(\"f\")\n\n    # just returns the same list\n    let = relay.Let(\n        f,\n        relay.Function(\n            [v],\n            relay.Match(\n                v,\n                [\n                    relay.Clause(\n                        relay.PatternConstructor(cons, [relay.PatternVar(h), relay.PatternVar(t)]),\n                        cons(h, f(t)),\n                    ),\n                    relay.Clause(relay.PatternConstructor(nil, []), nil()),\n                ],\n            ),\n        ),\n        f(cons(relay.const(1), cons(relay.const(2), cons(relay.const(3), nil())))),\n    )\n\n    val = run_as_python(let, mod)\n    assert_constructor_value(val, cons, 2)\n    assert_tensor_value(val.fields[0], 1)\n    assert_constructor_value(val.fields[1], cons, 2)\n    assert_tensor_value(val.fields[1].fields[0], 2)\n    assert_constructor_value(val.fields[1].fields[1], cons, 2)\n    assert_tensor_value(val.fields[1].fields[1].fields[0], 3)\n    assert_constructor_value(val.fields[1].fields[1].fields[1], nil, 0)\n\n\ndef test_global_recursion():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    rlist, cons, nil = p.mod.get_type(\"List\")\n\n    copy = relay.GlobalVar(\"copy\")\n    # same as above: it copies the given list\n    a = relay.TypeVar(\"a\")\n    v = relay.Var(\"v\", rlist(a))\n    h = relay.Var(\"h\")\n    t = relay.Var(\"t\")\n    copy_def = relay.Function(\n        [v],\n        relay.Match(\n            v,\n            [\n                relay.Clause(\n                    relay.PatternConstructor(cons, [relay.PatternVar(h), relay.PatternVar(t)]),\n                    cons(h, copy(t)),\n                ),\n                relay.Clause(relay.PatternConstructor(nil, []), nil()),\n            ],\n        ),\n        rlist(a),\n        [a],\n    )\n    mod[copy] = copy_def\n\n    call1 = copy_def(cons(relay.const(1), cons(relay.const(2), nil())))\n    val1 = run_as_python(call1, mod)\n    assert_constructor_value(val1, cons, 2)\n    assert_tensor_value(val1.fields[0], 1)\n    assert_constructor_value(val1.fields[1], cons, 2)\n    assert_tensor_value(val1.fields[1].fields[0], 2)\n    assert_constructor_value(val1.fields[1].fields[1], nil, 0)\n\n    call2 = copy_def(cons(relay.Tuple([]), nil()))\n    val2 = run_as_python(call2, mod)\n    assert_constructor_value(val2, cons, 2)\n    assert_adt_len(val2.fields[0], 0)\n    assert_constructor_value(val2.fields[1], nil, 0)\n\n\ndef test_higher_order_call():\n    # test with anon func\n    h = relay.Var(\"h\")\n    f = relay.Var(\"f\")\n    x = relay.Var(\"x\")\n    ho_anon = relay.Let(\n        h, relay.Function([f], f(relay.Tuple([]))), h(relay.Function([x], relay.const(1)))\n    )\n\n    anon_val = run_as_python(ho_anon)\n    assert_tensor_value(anon_val, 1)\n\n    # test with named func\n    g = relay.Var(\"g\")\n    ho_named = relay.Let(\n        h,\n        relay.Function([f], f(relay.Tuple([]))),\n        relay.Let(g, relay.Function([x], relay.const(2)), h(g)),\n    )\n    named_val = run_as_python(ho_named)\n    assert_tensor_value(named_val, 2)\n\n\ndef test_match_effect_exactly_once():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = p.mod.get_type(\"List\")\n\n    # the list should be of length 1!\n    # Unless we mistakenly execute the data clause more than once\n    r = relay.Var(\"r\")\n    data = seq(relay.RefWrite(r, cons(relay.Tuple([]), relay.RefRead(r))), relay.RefRead(r))\n    match = relay.Let(\n        r,\n        relay.RefCreate(nil()),\n        relay.Match(\n            data,\n            [\n                relay.Clause(relay.PatternConstructor(nil, []), relay.const(0)),\n                relay.Clause(\n                    relay.PatternConstructor(\n                        cons, [relay.PatternWildcard(), relay.PatternConstructor(nil, [])]\n                    ),\n                    relay.const(1),\n                ),\n                relay.Clause(relay.PatternWildcard(), relay.const(2)),\n            ],\n        ),\n    )\n\n    match_val = run_as_python(match, mod)\n    assert_tensor_value(match_val, 1)\n\n\ndef test_arbitrary_let_nesting():\n    # something that is tricky to do in Python but comes naturally in Relay\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    x = relay.Var(\"x\")\n    r = relay.Var(\"r\")\n    y = relay.Var(\"y\")\n    z = relay.Var(\"z\")\n    expr = relay.Tuple(\n        [\n            relay.Let(x, relay.Tuple([relay.const(1), relay.const(2)]), relay.TupleGetItem(x, 1)),\n            relay.Let(\n                r,\n                relay.RefCreate(relay.const(1)),\n                seq(relay.RefWrite(r, relay.const(3)), relay.RefRead(r)),\n            ),\n            relay.Let(y, p.id(relay.Let(z, relay.const(4), z)), y),\n        ]\n    )\n\n    tup_val = run_as_python(expr, mod)\n    assert_adt_len(tup_val, 3)\n    assert_tensor_value(tup_val[0], 2)\n    assert_tensor_value(tup_val[1], 3)\n    assert_tensor_value(tup_val[2], 4)\n\n\ndef test_ref_execution_order():\n    # we want to have effects execute from left to right\n    x = relay.Var(\"x\")\n    y = relay.Var(\"y\")\n    f = relay.Var(\"f\")\n    r = relay.Var(\"r\")\n\n    expr = relay.Let(\n        f,\n        relay.Function([x, y], x),\n        # r = 1\n        relay.Let(\n            r,\n            relay.RefCreate(relay.const(1)),\n            relay.Tuple(\n                [\n                    # should be 1\n                    relay.RefRead(r),\n                    # set r to 2 and read back\n                    seq(relay.RefWrite(r, relay.const(2)), relay.RefRead(r)),\n                    # set r to 3 and read back\n                    seq(relay.RefWrite(r, relay.const(3)), relay.RefRead(r)),\n                    # set r to 4 and read as first arg to f\n                    # set r to 5 and read as second arg to f\n                    # f should evaluate to 4\n                    f(\n                        seq(relay.RefWrite(r, relay.const(4)), relay.RefRead(r)),\n                        seq(relay.RefWrite(r, relay.const(5)), relay.RefRead(r)),\n                    ),\n                    # read back 5\n                    relay.RefRead(r),\n                ]\n            ),\n        ),\n    )\n\n    tup_val = run_as_python(expr)\n    assert_adt_len(tup_val, 5)\n    assert_tensor_value(tup_val[0], 1)\n    assert_tensor_value(tup_val[1], 2)\n    assert_tensor_value(tup_val[2], 3)\n    assert_tensor_value(tup_val[3], 4)\n    assert_tensor_value(tup_val[4], 5)\n\n\ndef test_op_add():\n    add = relay.add(relay.const(1), relay.const(2))\n    add_val = run_as_python(add)\n    assert_tensor_value(add_val, 3)\n\n\n# test an op with a tuple input\n# adapted from test_stack in test_op_level3\ndef test_op_stack():\n    def verify_stack(dshapes, axis):\n        x_data = [np.random.normal(size=shape).astype(\"int32\") for shape in dshapes]\n        ref_res = np.stack(x_data, axis=axis)\n\n        args = []\n        for data in x_data:\n            args.append(relay.const(data))\n        call = relay.stack(relay.Tuple(args), axis)\n        call_val = run_as_python(call)\n        type(call_val)\n        assert_tensor_value(call_val, ref_res)\n\n    verify_stack([(2,), (2,), (2,)], -1)\n    verify_stack([(2,), (2,), (2,)], 0)\n    verify_stack([(2, 2, 4), (2, 2, 4), (2, 2, 4)], 1)\n    verify_stack([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], -1)\n\n\n# test an op with a tuple output\n# adapted from test_split_infer_type in test_op_level3\ndef test_split():\n    def verify_split(shape, indices_or_sections, axis=0):\n        x = np.random.normal(size=shape).astype(\"float32\")\n        ref_res = np.split(x, indices_or_sections, axis=axis)\n        call = relay.split(relay.const(x), indices_or_sections, axis=axis)\n        call_val = run_as_python(call)\n        assert_adt_len(call_val, len(ref_res))\n        for i in range(len(ref_res)):\n            assert_tensor_value(call_val[i], ref_res[i])\n\n    verify_split((2, 3), 2)\n    verify_split((5, 3), [3])\n    verify_split((5, 9, 3), [3, 4], 1)\n    verify_split((5, 5, 2, 2), 5, 1)\n    verify_split((5, 5, 2, 2), 5, 0)\n\n\n# ensure we can generate code for batch_norm, since it requires simplify_inference\ndef test_batch_norm():\n    def verify_batch_norm(shapes):\n        data = [np.absolute(np.random.normal(size=shape).astype(\"float32\")) for shape in shapes]\n        relay_args = [relay.const(arg) for arg in data]\n\n        eps = 1e-5\n\n        def reference(x, gamma, beta, moving_mean, moving_var):\n            return (x - moving_mean) / np.sqrt(moving_var + eps) * gamma + beta\n\n        ref_res = reference(*data)\n\n        call = relay.nn.batch_norm(*relay_args, epsilon=eps)[0]\n        call_val = run_as_python(call)\n\n        # there will be a change in accuracy so we need to check\n        # approximate equality\n        assert isinstance(call_val, tvm.nd.NDArray)\n        tvm.testing.assert_allclose(call_val.numpy(), ref_res, atol=eps, rtol=eps)\n\n    verify_batch_norm([(10, 20), (20,), (20,), (20,), (20,)])\n    verify_batch_norm([(20, 10), (10,), (10,), (10,), (10,)])\n    verify_batch_norm([(10, 50), (50,), (50,), (50,), (50,)])\n    verify_batch_norm([(30, 40), (40,), (40,), (40,), (40,)])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_recast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.transform import recast\n\n\ndef test_recast_simple():\n    \"\"\"Recast a single convolution operator.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        c = relay.nn.conv2d(x, w, padding=(1, 1), out_dtype=\"float32\")\n        return relay.Function([x, w], c)\n\n    def expected():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        x_int = relay.cast(x, \"int8\")\n        w_int = relay.cast(w, \"int8\")\n        c = relay.nn.conv2d(x_int, w_int, padding=(1, 1), out_dtype=\"int32\")\n        c_float = relay.cast(c, \"float32\")\n        return relay.Function([x, w], c_float)\n\n    pre = before()\n    post = recast(pre, \"int8\", \"int32\")\n    expected = expected()\n    assert tvm.ir.structural_equal(expected, post)\n\n\ndef test_recast_medium():\n    \"\"\"Recast a slightly larger graph.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        c = relay.nn.conv2d(x, w, padding=(1, 1), out_dtype=\"float32\")\n        w2 = relay.var(\"w2\", shape=[8, 8, 3, 3])\n        c2 = relay.nn.conv2d(c, w2, padding=(1, 1), out_dtype=\"float32\")\n        return relay.Function([x, w, w2], c2)\n\n    def expected():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        x_int = relay.cast(x, \"int8\")\n        w_int = relay.cast(w, \"int8\")\n        c = relay.nn.conv2d(x_int, w_int, padding=(1, 1), out_dtype=\"int32\")\n        c_float = relay.cast(c, \"float32\")\n        w2 = relay.var(\"w2\", shape=[8, 8, 3, 3])\n        w2_int = relay.cast(w2, \"int8\")\n        c_float_int = relay.cast(c_float, \"int8\")\n        c2 = relay.nn.conv2d(c_float_int, w2_int, padding=(1, 1), out_dtype=\"int32\")\n        c2_float = relay.cast(c2, \"float32\")\n        return relay.Function([x, w, w2], c2_float)\n\n    pre = before()\n    post = recast(pre, \"int8\", \"int32\")\n    expected = expected()\n    assert tvm.ir.structural_equal(expected, post)\n\n\ndef test_recast_skip():\n    \"\"\"Recast a graph using skip layers.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        c = relay.nn.conv2d(x, w, padding=(1, 1), out_dtype=\"float32\")\n        w2 = relay.var(\"w2\", shape=[8, 8, 3, 3])\n        c2 = relay.nn.conv2d(c, w2, padding=(1, 1), out_dtype=\"float32\")\n        return relay.Function([x, w, w2], c2)\n\n    def expected():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        c = relay.nn.conv2d(x, w, padding=(1, 1), out_dtype=\"float32\")\n        w2 = relay.var(\"w2\", shape=[8, 8, 3, 3])\n        w2_int = relay.cast(w2, \"int8\")\n        c_int = relay.cast(c, \"int8\")\n        c2 = relay.nn.conv2d(c_int, w2_int, padding=(1, 1), out_dtype=\"int32\")\n        c2_float = relay.cast(c2, \"float32\")\n        return relay.Function([x, w, w2], c2_float)\n\n    pre = before()\n    post = recast(pre, \"int8\", \"int32\", skip_layers=[0])\n    expected = expected()\n    assert tvm.ir.structural_equal(expected, post)\n\n\ndef test_recast_concat():\n    def before():\n        x = relay.var(\"x\", shape=[1, 4])\n        y = relay.var(\"y\", shape=[1, 4])\n        t = relay.Tuple([x, y])\n        c = relay.op.concatenate(t, axis=1)\n        return relay.Function([x, y], c)\n\n    def expected():\n        xv = relay.var(\"x\", shape=[1, 4])\n        yv = relay.var(\"y\", shape=[1, 4])\n        x = relay.cast(xv, \"float16\")\n        y = relay.cast(yv, \"float16\")\n        t = relay.Tuple([x, y])\n        c = relay.op.concatenate(t, axis=1)\n        c = relay.cast(c, \"float32\")\n        return relay.Function([xv, yv], c)\n\n    pre = before()\n    post = recast(pre, \"float16\", \"float32\", ops=[\"concatenate\"])\n    expected = expected()\n    assert tvm.ir.structural_equal(expected, post)\n\n\ndef test_recast_relu():\n    \"\"\"Recast a ReLU operator which does not have attributes.\"\"\"\n\n    def before():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        c = relay.nn.conv2d(x, w, padding=(1, 1), out_dtype=\"float32\")\n        r = relay.nn.relu(c)\n        return relay.Function([x, w], r)\n\n    def expected():\n        x = relay.var(\"x\", shape=[8, 8, 8, 8])\n        w = relay.var(\"w\", shape=[8, 8, 3, 3])\n        x_fp16 = relay.cast(x, \"float16\")\n        w_fp16 = relay.cast(w, \"float16\")\n        c = relay.nn.conv2d(x_fp16, w_fp16, padding=(1, 1), out_dtype=\"float16\")\n        c_float32 = relay.cast(c, \"float32\")\n        c_float16 = relay.cast(c_float32, \"float16\")\n        r = relay.nn.relu(c_float16)\n        r_float32 = relay.cast(r, \"float32\")\n        return relay.Function([x, w], r_float32)\n\n    pre = before()\n    post = recast(pre, \"float16\", \"float16\", ops=[\"nn.conv2d\", \"nn.relu\"])\n    expected = expected()\n    assert tvm.ir.structural_equal(expected, post)\n\n\nif __name__ == \"__main__\":\n    test_recast_simple()\n    test_recast_medium()\n    test_recast_skip()\n    test_recast_concat()\n    test_recast_relu()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_relay_te_compiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.testing\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm import topi\nfrom tvm.relay.backend import te_compiler\nfrom tvm.relay.testing import run_infer_type\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\n\n\n@autotvm.register_topi_compute(\"test/conv2d_1\")\ndef _compute_conv2d_1(cfg, input, filter, strides, padding, dilation, out_dtype):\n    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"test/conv2d_1\")\ndef _schedule_conv2d_1(cfg, outs):\n    return topi.generic.schedule_conv2d_nchw(outs)\n\n\n@autotvm.register_topi_compute(\"test/conv2d_2\")\ndef _compute_conv2d_2(cfg, input, filter, strides, padding, dilation, out_dtype):\n    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)\n\n\n@autotvm.register_topi_schedule(\"test/conv2d_2\")\ndef _schedule_conv2d_2(cfg, outs):\n    return topi.generic.schedule_conv2d_nchw(outs)\n\n\ndef _compute_conv2d_3(input, filter, strides, padding, dilation, out_dtype):\n    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)\n\n\ndef _schedule_conv2d_3(outs):\n    return topi.generic.schedule_conv2d_nchw(outs)\n\n\n@tvm.target.override_native_generic_func(\"test_conv2d_strategy\")\ndef _tmp_strategy(attrs, inputs, out_type, target):\n    strategy = relay.op.OpStrategy()\n    strategy.add_implementation(\n        relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_1),\n        relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_1),\n        name=\"conv2d_1\",\n        plevel=10,\n    )\n    strategy.add_implementation(\n        relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_2),\n        relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_2),\n        name=\"conv2d_2\",\n        plevel=15,\n    )\n    ic = inputs[0].shape[1]\n    with tvm.te.SpecializedCondition(ic >= 16):\n        strategy.add_implementation(\n            relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_3),\n            relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_3),\n            name=\"conv2d_3\",\n            plevel=20,\n        )\n    return strategy\n\n\ndef _create_record(task_name, dshape, wshape, target, cost):\n    args = [te.placeholder(dshape), te.placeholder(wshape), (1, 1), (1, 1, 1, 1), (1, 1), \"float32\"]\n    task = autotvm.task.create(task_name, args, target)\n    cfg = autotvm.ConfigEntity(0, None, {}, [])\n    cfg.cost = cost\n    inp = autotvm.MeasureInput(target=target, task=task, config=cfg)\n    result = autotvm.MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n    return (inp, result)\n\n\ndef test_get_valid_implementations():\n    target = tvm.target.Target(\"llvm\")\n\n    def _get_impls(dshape, wshape):\n        data = relay.var(\"data\", shape=dshape)\n        weight = relay.var(\"wshape\", shape=wshape)\n        out = relay.nn.conv2d(data, weight, padding=(1, 1))\n        out = run_infer_type(out)\n        return relay.backend.te_compiler.get_valid_implementations(\n            relay.op.get(\"nn.conv2d\"),\n            out.attrs,\n            [te.placeholder(dshape), te.placeholder(wshape)],\n            out.checked_type,\n            target,\n        )\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMStrategy\", _tmp_strategy):\n        impls = _get_impls((1, 8, 7, 7), (32, 8, 3, 3))\n        assert len(impls) == 2\n        impls = _get_impls((1, 16, 7, 7), (32, 16, 3, 3))\n        assert len(impls) == 3\n\n\ndef test_select_implementation():\n    target = tvm.target.Target(\"llvm\")\n\n    def _select_impl(dshape, wshape, use_autotvm=False):\n        data = relay.var(\"data\", shape=dshape)\n        weight = relay.var(\"wshape\", shape=wshape)\n        out = relay.nn.conv2d(data, weight, padding=(1, 1))\n        out = run_infer_type(out)\n        return relay.backend.te_compiler.select_implementation(\n            relay.op.get(\"nn.conv2d\"),\n            out.attrs,\n            [te.placeholder(dshape), te.placeholder(wshape)],\n            out.checked_type,\n            target,\n            use_autotvm,\n        )\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMStrategy\", _tmp_strategy):\n        impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3))\n        assert impl.name == \"conv2d_2\"\n        impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)\n        assert impl.name == \"conv2d_2\"\n        impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3))\n        assert impl.name == \"conv2d_3\"\n        impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)\n        assert impl.name == \"conv2d_3\"\n\n        # add autotvm record\n        records = []\n        records.append(_create_record(\"test/conv2d_1\", (1, 8, 7, 7), (32, 8, 3, 3), target, 0.5))\n        records.append(_create_record(\"test/conv2d_1\", (1, 16, 7, 7), (32, 16, 3, 3), target, 1.0))\n        with target:\n            with autotvm.apply_history_best(records):\n                impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)\n                assert impl.name == \"conv2d_1\"\n                impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)\n                assert impl.name == \"conv2d_1\"\n\n        records.append(_create_record(\"test/conv2d_2\", (1, 8, 7, 7), (32, 8, 3, 3), target, 0.2))\n        records.append(_create_record(\"test/conv2d_1\", (1, 16, 7, 7), (32, 16, 3, 3), target, 1.2))\n        with target:\n            with autotvm.apply_history_best(records):\n                impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)\n                assert impl.name == \"conv2d_2\"\n                impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)\n                assert impl.name == \"conv2d_1\"\n\n\ndef test_te_compiler():\n    tec = relay.backend.te_compiler.get()\n\n    def get_func(shape):\n        x = relay.var(\"x\", shape=shape)\n        y = relay.add(x, x)\n        z = relay.add(y, x)\n        f = relay.Function([x], z)\n        mod = tvm.IRModule.from_expr(f)\n        mod = relay.transform.InferType()(mod)\n        return mod[\"main\"]\n\n    z1 = tec.lower(get_func((10,)), \"llvm\")\n    z2 = tec.lower(get_func((10,)), \"llvm\")\n    z3 = tec.lower(get_func(()), \"llvm\")\n    assert z1.same_as(z2)\n    assert not z3.same_as(z1)\n    if tvm.testing.device_enabled(\"cuda\"):\n        z4 = tec.lower(get_func(()), \"cuda\")\n        assert not z3.same_as(z4)\n\n    # Test JIT target\n    for target in [\"llvm\"]:\n        dev = tvm.device(target)\n        if tvm.testing.device_enabled(target):\n            f = tec.jit(get_func((10,)), target)\n            x = tvm.nd.array(np.ones(10).astype(\"float32\"), device=dev)\n            y = tvm.nd.empty((10,), device=dev)\n            f(x, y)\n            tvm.testing.assert_allclose(y.numpy(), x.numpy() * 3)\n\n\n# Note: Once the te compiler is removed, we should keep this test so that\n# we make sure that opt_level=0 passes are being called correctly.\ndef test_compile_placeholder_bypass():\n    te_compiler = relay.backend.te_compiler.get()\n    x = relay.var(\"x\", shape=(2, 3))\n    y = relay.var(\"y\", shape=(2, 3))\n    z = relay.var(\"z\", shape=(2, 3))\n    result = relay.Tuple([x, relay.op.concatenate([y, z], axis=0)])\n    func = relay.Function(relay.analysis.free_vars(result), result)\n    with tvm.transform.PassContext(opt_level=0):\n        graph, lib, params = relay.build(tvm.IRModule.from_expr(func), \"llvm\")\n\n\ndef test_compile_injective_with_tuple():\n    x = relay.var(\"x\", shape=(2, 3))\n    y = relay.var(\"y\", shape=(2, 3))\n    x_transpose = relay.transpose(x)\n    output = relay.Tuple([x_transpose, y])\n    func = relay.Function([x, y], output)\n    relay.build(tvm.IRModule.from_expr(func), \"llvm\")\n\n\ndef test_compile_tuple_dup():\n    x = relay.var(\"data\", shape=(16, 16))\n    log = relay.log(x)\n    output = relay.Tuple([log, log])\n    f = relay.Function([x], output)\n    relay.build(tvm.IRModule.from_expr(f), \"llvm\")\n\n\ndef test_compile_full():\n    # Shape calculations can happen in int64. The test checks that full operator\n    # can handle when shapes are not int32\n    shape = (\n        tvm.tir.IntImm(\"int32\", 1),\n        tvm.tir.IntImm(\"int64\", 16),\n        tvm.tir.IntImm(\"int64\", 16),\n        tvm.tir.IntImm(\"int32\", 64),\n    )\n    output = relay.full(relay.const(0, \"int32\"), shape=shape, dtype=\"int32\")\n    f = relay.Function([], output)\n    mod = tvm.IRModule.from_expr(f)\n    mod = relay.qnn.transform.CanonicalizeOps()(mod)\n    relay.build(mod, \"llvm\")\n\n\ndef test_compile_nhwc_pack():\n    data = relay.var(\"data\", shape=(1, 1, 1, 1024), dtype=\"uint8\")\n    weight = relay.var(\"weight\", shape=(1, 1, 1024, 1001), dtype=\"int8\")\n    p2 = relay.var(\"p2\", shape=(1, 1, 1, 1), dtype=\"int32\")\n    conv = relay.nn.conv2d(\n        data,\n        weight,\n        kernel_size=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"int32\",\n    )\n    multiply = relay.multiply(relay.const(-22, dtype=\"int32\"), p2)\n    tile = relay.tile(multiply, reps=(1, 1, 1, 1001))\n    subtract = relay.subtract(conv, tile)\n\n    func = subtract\n    mod = relay.Function(relay.analysis.free_vars(func), func)\n    relay.build(mod, target=\"llvm\")\n\n\ndef test_compile_propogate_hash():\n    data = relay.var(\"data\", shape=(1, 1, 1, 1024), dtype=\"uint8\")\n    weight = relay.var(\"weight\", shape=(1, 1, 1024, 1001), dtype=\"int8\")\n    p2 = relay.var(\"p2\", shape=(1, 1, 1, 1), dtype=\"int32\")\n    conv = relay.nn.conv2d(\n        data,\n        weight,\n        kernel_size=(1, 1),\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"int32\",\n    )\n    multiply = relay.multiply(relay.const(-22, dtype=\"int32\"), p2)\n    tile = relay.tile(multiply, reps=(1, 1, 1, 1001))\n    subtract = relay.subtract(conv, tile)\n\n    func = subtract\n    mod = tvm.IRModule.from_expr(relay.Function(relay.analysis.free_vars(func), func))\n    vm = relay.vm.VMCompiler()\n    opt_mod, _ = vm.optimize(mod, target=\"llvm\")\n    for f in opt_mod.functions.values():\n        assert \"hash\" in f.attrs.keys()\n\n\nif __name__ == \"__main__\":\n    test_get_valid_implementations()\n    test_select_implementation()\n    test_te_compiler()\n    test_compile_placeholder_bypass()\n    test_compile_injective_with_tuple()\n    test_compile_tuple_dup()\n    test_compile_full()\n    test_compile_nhwc_pack()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_runtime.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nfrom tvm import TVMError\nfrom tvm.relay.backend import Runtime\n\n\ndef test_create():\n    runtime = Runtime(\"cpp\")\n    assert str(runtime) == \"cpp\"\n\n\ndef test_create_runtime_with_options():\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    assert str(runtime) == \"crt\"\n    assert runtime[\"system-lib\"]\n\n\ndef test_attr_check():\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    assert \"woof\" not in runtime\n    assert \"system-lib\" in runtime\n\n\ndef test_create_runtime_not_found():\n    with pytest.raises(TVMError, match='Runtime \"woof\" is not defined'):\n        Runtime(\"woof\", {})\n\n\ndef test_create_runtime_attr_not_found():\n    with pytest.raises(TVMError, match='Attribute \"woof\" is not available on this Runtime'):\n        Runtime(\"crt\", {\"woof\": \"bark\"})\n\n\ndef test_create_runtime_attr_type_incorrect():\n    with pytest.raises(\n        TVMError,\n        match='Attribute \"system-lib\" should have type \"IntImm\"'\n        ' but instead found \"runtime.String\"',\n    ):\n        Runtime(\"crt\", {\"system-lib\": \"woof\"})\n\n\ndef test_list_runtimes():\n    assert \"crt\" in Runtime.list_registered()\n\n\n@pytest.mark.parametrize(\"runtime\", [Runtime(\"crt\"), \"crt\"])\ndef test_list_runtime_options(runtime):\n    aot_options = Runtime.list_registered_options(runtime)\n    assert \"system-lib\" in aot_options\n    assert aot_options[\"system-lib\"] == \"IntImm\"\n\n\ndef test_list_runtime_options_not_found():\n    with pytest.raises(TVMError, match='Runtime \"woof\" is not defined'):\n        Runtime.list_registered_options(\"woof\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_simplify_fc_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport itertools\n\nimport numpy as np\nimport scipy.sparse as sp\n\n\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm import relay\nfrom tvm.relay.data_dep_optimization import simplify_fc_transpose\n\n\ndef run_func(func, params, x):\n    with tvm.transform.PassContext(opt_level=3):\n        lib = relay.build(func, \"llvm\", params=params)\n\n    from tvm.contrib import graph_executor\n\n    dev = tvm.cpu(0)\n    dtype = \"float32\"\n    m = graph_executor.GraphModule(lib[\"default\"](dev))\n    # set inputs\n    m.set_input(\"data\", tvm.nd.array(x.astype(dtype)))\n    # execute\n    m.run()\n    # get outputs\n    tvm_output = m.get_output(0)\n    return tvm_output.numpy()\n\n\ndef test_simplify_fc_transpose():\n    data = relay.var(\"data\", shape=(1, 32), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w1 = relay.var(\"w1\", shape=(32, 64), dtype=\"float32\")\n    y = relay.nn.dense(x, relay.transpose(w1, axes=[1, 0]))\n    z = relay.nn.relu(y)\n    w2 = relay.var(\"w2\", shape=(64, 16), dtype=\"float32\")\n    zz = relay.nn.dense(z, relay.transpose(w2, axes=[1, 0]))\n    func = relay.Function(relay.analysis.free_vars(zz), zz)\n    params = {\n        \"w1\": tvm.nd.array(np.random.uniform(-1, 1, (32, 64)).astype(\"float32\")),\n        \"w2\": tvm.nd.array(np.random.uniform(-1, 1, (64, 16)).astype(\"float32\")),\n    }\n    x_np = np.random.randn(1, 32).astype(\"float32\")\n    old_result = run_func(func, params, x_np)\n\n    new_func, new_params = simplify_fc_transpose.convert(func, params)\n    new_result = run_func(new_func, new_params, x_np)\n    np.testing.assert_allclose(old_result, new_result, atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_simplify_fc_transpose()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_sparse_conv2d_convert.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport itertools\n\nimport numpy as np\nimport scipy.sparse as sp\n\n\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm import relay\nfrom tvm.topi.sparse.utils import random_bsr_matrix\nfrom tvm.relay.build_module import bind_params_by_name\n\n\ndef run_func(func, params, x):\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, new_params = relay.build(func, \"llvm\", params=params)\n\n    from tvm.contrib import graph_executor\n\n    dev = tvm.cpu(0)\n    dtype = \"float32\"\n    m = graph_executor.create(graph, lib, dev)\n    # set inputs\n    m.set_input(\"data\", tvm.nd.array(x.astype(dtype)))\n    m.set_input(**new_params)\n    # execute\n    m.run()\n    # get outputs\n    tvm_output = m.get_output(0)\n    return tvm_output.numpy()\n\n\ndef test_bsr_sparse_conv2d_nchw():\n    data = relay.var(\"data\", shape=(1, 64, 32, 32), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w = relay.var(\"weight\", shape=(128, 64, 1, 1), dtype=\"float32\")\n    y = relay.nn.conv2d(x, w, channels=128, kernel_size=1, data_layout=\"NCHW\", kernel_layout=\"OIHW\")\n    z = relay.nn.relu(y)\n    func = relay.Function(relay.analysis.free_vars(z), z)\n\n    params = {\n        \"weight\": tvm.nd.array(\n            np.array(random_bsr_matrix(128, 64, 8, 1, 0.1, \"float32\").todense()).reshape(\n                128, 64, 1, 1\n            )\n        )\n    }\n\n    x_np = np.random.randn(1, 64, 32, 32).astype(\"float32\")\n    # dense output\n    dense_output = run_func(func, params, x_np)\n    # sparse\n    sparse_func, params = relay.data_dep_optimization.bsr_conv2d.convert(\n        func, params, (8, 1), 0.2, \"NCHW\"\n    )\n    sparse_output = run_func(sparse_func, params, x_np)\n    np.testing.assert_allclose(sparse_output, dense_output, atol=1e-5, rtol=1e-5)\n\n\ndef test_bsr_sparse_conv2d_nhwc():\n    data = relay.var(\"data\", shape=(1, 32, 32, 64), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w = relay.var(\"weight\", shape=(1, 1, 64, 128), dtype=\"float32\")\n    y = relay.nn.conv2d(x, w, channels=128, kernel_size=1, data_layout=\"NHWC\", kernel_layout=\"HWIO\")\n    z = relay.nn.relu(y)\n    func = relay.Function(relay.analysis.free_vars(z), z)\n\n    params = {\n        \"weight\": tvm.nd.array(\n            np.array(random_bsr_matrix(128, 64, 8, 1, 0.1, \"float32\").todense()).T.reshape(\n                1, 1, 64, 128\n            )\n        )\n    }\n\n    x_np = np.random.randn(1, 32, 32, 64).astype(\"float32\")\n    # dense output\n    dense_output = run_func(func, params, x_np)\n    # sparse\n    sparse_func, params = relay.data_dep_optimization.bsr_conv2d.convert(\n        func, params, (8, 1), 0.2, \"NHWC\"\n    )\n    sparse_output = run_func(sparse_func, params, x_np)\n    np.testing.assert_allclose(sparse_output, dense_output, atol=1e-5, rtol=1e-5)\n\n\ndef test_bsr_sparse_conv2d_3x3_nchw():\n    data = relay.var(\"data\", shape=(1, 64, 32, 32), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w = relay.var(\"weight\", shape=(128, 64, 3, 3), dtype=\"float32\")\n    y = relay.nn.conv2d(\n        x, w, channels=128, kernel_size=3, padding=1, data_layout=\"NCHW\", kernel_layout=\"OIHW\"\n    )\n    z = relay.nn.relu(y)\n    func = relay.Function(relay.analysis.free_vars(z), z)\n\n    params = {\n        \"weight\": tvm.nd.array(\n            np.array(random_bsr_matrix(128, 64 * 9, 16, 1, 0.1, \"float32\").todense()).reshape(\n                128, 64, 3, 3\n            )\n        )\n    }\n\n    x_np = np.random.randn(1, 64, 32, 32).astype(\"float32\")\n    # dense output\n    dense_output = run_func(func, params, x_np)\n    # sparse\n    func = bind_params_by_name(func, params)\n    sparse_func, params = relay.data_dep_optimization.bsr_conv2d.convert2(\n        func, {}, (16, 1), 0.2, \"NCHW\", 3\n    )\n    sparse_output = run_func(sparse_func, params, x_np)\n    np.testing.assert_allclose(sparse_output, dense_output, atol=1e-5, rtol=1e-5)\n\n\ndef test_bsr_sparse_conv2d_3x3_nhwc():\n    data = relay.var(\"data\", shape=(1, 32, 32, 64), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w = relay.var(\"weight\", shape=(3, 3, 64, 128), dtype=\"float32\")\n    y = relay.nn.conv2d(\n        x, w, channels=128, kernel_size=3, padding=1, data_layout=\"NHWC\", kernel_layout=\"HWIO\"\n    )\n    z = relay.nn.relu(y)\n    func = relay.Function(relay.analysis.free_vars(z), z)\n\n    params = {\n        \"weight\": tvm.nd.array(\n            np.array(random_bsr_matrix(128, 64 * 9, 16, 1, 0.1, \"float32\").todense()).T.reshape(\n                3, 3, 64, 128\n            )\n        )\n    }\n\n    x_np = np.random.randn(1, 32, 32, 64).astype(\"float32\")\n    # dense output\n    dense_output = run_func(func, params, x_np)\n    # sparse\n    func = bind_params_by_name(func, params)\n    sparse_func, params = relay.data_dep_optimization.bsr_conv2d.convert2(\n        func, {}, (16, 1), 0.2, \"NHWC\", 3\n    )\n    sparse_output = run_func(sparse_func, params, x_np)\n    np.testing.assert_allclose(sparse_output, dense_output, atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_bsr_sparse_conv2d_nhwc()\n    test_bsr_sparse_conv2d_nchw()\n    test_bsr_sparse_conv2d_3x3_nhwc()\n    test_bsr_sparse_conv2d_3x3_nchw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_sparse_dense_convert.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport itertools\n\nimport numpy as np\nimport scipy.sparse as sp\n\n\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm import relay\n\n\ndef random_bsr_matrix(M, N, BS_R, BS_C, density, dtype=\"float32\"):\n    Y = np.zeros((M, N), dtype=dtype)\n    assert M % BS_R == 0\n    assert N % BS_C == 0\n    nnz = int(density * M * N)\n    num_blocks = int(nnz / (BS_R * BS_C)) + 1\n    candidate_blocks = np.asarray(list(itertools.product(range(0, M, BS_R), range(0, N, BS_C))))\n    assert candidate_blocks.shape[0] == M // BS_R * N // BS_C\n    chosen_blocks = candidate_blocks[\n        np.random.choice(candidate_blocks.shape[0], size=num_blocks, replace=False)\n    ]\n    for i in range(len(chosen_blocks)):\n        r, c = chosen_blocks[i]\n        Y[r : r + BS_R, c : c + BS_C] = np.random.randn(BS_R, BS_C)\n    s = sp.bsr_matrix(Y, blocksize=(BS_R, BS_C))\n    assert s.data.shape == (num_blocks, BS_R, BS_C)\n    assert s.data.size >= nnz\n    assert s.indices.shape == (num_blocks,)\n    assert s.indptr.shape == (M // BS_R + 1,)\n    return s\n\n\ndef run_func(func, params, x):\n    with tvm.transform.PassContext(opt_level=3):\n        graph, lib, new_params = relay.build(func, \"llvm\", params=params)\n\n    from tvm.contrib import graph_executor\n\n    dev = tvm.cpu(0)\n    dtype = \"float32\"\n    m = graph_executor.create(graph, lib, dev)\n    # set inputs\n    m.set_input(\"data\", tvm.nd.array(x.astype(dtype)))\n    m.set_input(**new_params)\n    # execute\n    m.run()\n    # get outputs\n    tvm_output = m.get_output(0)\n    return tvm_output.numpy()\n\n\ndef test_bsr_sparse_dense():\n    data = relay.var(\"data\", shape=(1, 128), dtype=\"float32\")\n    x = relay.nn.relu(data)\n    w = relay.var(\"weight\", shape=(768, 128), dtype=\"float32\")\n    y = relay.nn.dense(x, w)\n    z = relay.nn.relu(y)\n    func = relay.Function(relay.analysis.free_vars(z), z)\n\n    params = {\"weight\": tvm.nd.array(random_bsr_matrix(768, 128, 32, 1, 0.1).todense())}\n\n    x_np = np.random.randn(1, 128).astype(\"float32\")\n    # dense output\n    dense_output = run_func(func, params, x_np)\n    # sparse\n    sparse_func, params = relay.data_dep_optimization.bsr_dense.convert(func, params, (32, 1), 0.2)\n    sparse_output = run_func(sparse_func, params, x_np)\n    np.testing.assert_allclose(sparse_output, dense_output, atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_bsr_sparse_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_target_hooks.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for target hooks.\"\"\"\nimport sys\nimport numpy as np\nimport pytest\nimport logging\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay, IRModule\n\nfrom utils.external_codegen import (\n    parametrize_external_codegen_checks,\n    set_external_func_attr,\n    check_aot_executor_result,\n    check_graph_executor_result,\n    check_vm_result,\n)\n\nlogging.basicConfig(level=logging.INFO)\n\n\n@parametrize_external_codegen_checks\ndef test_tir_external_generation_inline_without_target_instance(check_result):\n    shape = (8,)\n    x_data = np.random.randint(255, size=shape).astype(\"float32\")\n    y_data = np.random.randint(255, size=shape).astype(\"float32\")\n    inputs = {\"x\": x_data, \"y\": y_data}\n\n    x0 = relay.var(\"x0\", shape=shape, dtype=\"float32\")\n    y0 = relay.var(\"y0\", shape=shape, dtype=\"float32\")\n    z = x0 + y0\n    f = relay.Function([x0, y0], z)\n    f = set_external_func_attr(f, \"example_target_hook\", \"replace_add_with_subtract\")\n\n    x = relay.var(\"x\", shape=(8,), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(8,), dtype=\"float32\")\n    call = relay.Call(f, [x, y])\n    func = IRModule.from_expr(call)\n\n    check_result(func, inputs, (8,), x_data - y_data)\n\n\n# TODO(mbs): The check_aot_executor_result does not support list-of-targets, mostly because\n# tvm.testing.aot.compile_and_run requires the target to be a kind name string, and\n# tvm.testing.aot.compile_models requires a single Target object. However, code outside of\n# tvm.testing.aot is ready for this more general form.\n@pytest.mark.parametrize(\"check_result\", [check_graph_executor_result, check_vm_result])\ndef test_tir_external_generation_outline_with_target_instance(check_result):\n    shape = (8,)\n    x_data = np.random.randint(255, size=shape).astype(\"float32\")\n    y_data = np.random.randint(255, size=shape).astype(\"float32\")\n    inputs = {\"x\": x_data, \"y\": y_data}\n    # Compile with an instance of the hooked target kind to demonstrate plumbing target attributes\n    # into custom passes.\n    host_target = tvm.target.Target(\"llvm\")\n    generic_target = tvm.target.Target(\"llvm\", host=host_target)\n    extern_codegen_target = tvm.target.Target(\n        \"example_target_hook -example_attribute=42\", host=host_target\n    )\n    mod = tvm.parser.fromtext(\n        \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(8), float32], %y: Tensor[(8), float32]) -> Tensor[(8), float32] {\n              @replace_add_with_subtract(%x, %y) * 2.0f\n            }\n\n            def @replace_add_with_subtract(%x: Tensor[(8), float32], %y: Tensor[(8), float32],\n                                           Inline=1,\n                                           Primitive=1,\n                                           Compiler=\"example_target_hook\",\n                                           global_symbol=\"replace_add_with_subtract\") -> Tensor[(8), float32] {\n              %x + %y  // will be rewritten to TIR implementing %x - %y - 42.0f by custom pass\n            }\n        \"\"\"\n    )\n\n    check_result(\n        mod,\n        inputs,\n        (8,),\n        (x_data - y_data - 42.0) * 2.0,\n        target=[generic_target, extern_codegen_target],\n    )\n\n\n@pytest.mark.parametrize(\"check_result\", [check_aot_executor_result, check_graph_executor_result])\ndef test_runtime_module_generation(check_result):\n    shape = (8,)\n    x_data = np.random.randint(255, size=shape).astype(\"float32\")\n    y_data = np.random.randint(255, size=shape).astype(\"float32\")\n    inputs = {\"x\": x_data, \"y\": y_data}\n\n    x0 = relay.var(\"x0\", shape=shape, dtype=\"float32\")\n    y0 = relay.var(\"y0\", shape=shape, dtype=\"float32\")\n    z = x0 + y0\n    func = relay.Function([x0, y0], z)\n    func = set_external_func_attr(func, \"example_target_hook\", \"replace_add_with_subtract\")\n    # Test hook to trigger TIRToRuntime code generation\n    func = func.with_attr(\"tir_to_runtime\", True)\n\n    x = relay.var(\"x\", shape=(8,), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(8,), dtype=\"float32\")\n    call = relay.Call(func, [x, y])\n    func = IRModule.from_expr(call)\n\n    check_result(func, inputs, (8,), x_data * y_data)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_tensor_array.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.relay.backend.interpreter import ConstructorValue\nfrom tvm.relay import create_executor\nfrom tvm.relay.prelude import Prelude, StaticTensorArrayOps\nfrom tvm.relay.testing import count as count_, make_nat_value, make_nat_expr\n\nimport numpy as np\n\n\ndef vmobj_to_list(mod, o, dtype=\"float32\"):\n    _, tensor_nil, _, _, _, _, _, _, _ = mod.get_type(f\"tensor_{dtype}_t\")\n    if isinstance(o, tvm.nd.NDArray):\n        return [o.numpy().tolist()]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        if len(o) == 0:\n            if tensor_nil.tag == o.tag:\n                return [0]\n            return []\n\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(mod, f, dtype))\n        return result\n    elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):\n        if o.constructor.name_hint == \"Cons\":\n            tl = vmobj_to_list(mod, o.fields[1], dtype)\n            hd = vmobj_to_list(mod, o.fields[0], dtype)\n            hd.extend(tl)\n            return hd\n        elif o.constructor.name_hint == \"Nil\":\n            return []\n        elif \"tensor_nil\" in o.constructor.name_hint:\n            return [0]\n        elif \"tensor\" in o.constructor.name_hint:\n            return [o.fields[0].numpy()]\n        else:\n            raise RuntimeError(\"Unknown object type: %s\" % o.constructor.name_hint)\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef check_tensor_array(ta_mod, ref_res, *args, dtype=\"float32\", rtol=1e-5):\n    for kind in [\"debug\", \"vm\"]:\n        for target, dev in [(\"llvm\", tvm.cpu(0))]:  # testing.enabled_targets():\n            if kind == \"debug\" and dev.device_type != tvm.cpu().device_type:\n                continue\n            result = relay.create_executor(kind, mod=ta_mod, device=dev, target=target).evaluate()(\n                *args\n            )\n            got = vmobj_to_list(ta_mod, result, dtype)\n            tvm.testing.assert_allclose(ref_res, got, rtol=rtol, atol=rtol)\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_expand_dims():\n    def run(dtype):\n        x = relay.var(\"x\")\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        expand_dims_func = p.get_global_var(\"tensor_expand_dims\", dtype)\n        tensor1 = p.get_tensor_ctor(\"tensor1\", dtype)\n        mod[\"main\"] = relay.Function([x], expand_dims_func(tensor1(x)))\n        x_np = np.random.uniform(low=0.0, high=8.0, size=(1,)).astype(dtype)\n        expected = [np.expand_dims(x_np, axis=0)]\n        check_tensor_array(mod, expected, x_np)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_constructor():\n    def run(dtype):\n        x = relay.var(\"x\")\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        mod[\"main\"] = relay.Function([x], tensor_array(x))\n        expected = np.array([0, 0, 0, 0, 0])\n        check_tensor_array(mod, expected, 5, dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_read():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        l = relay.var(\"l\")\n        i = relay.var(\"i\")\n        read_func = p.get_global_var(\"tensor_array_read\", dtype)\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        mod[\"main\"] = relay.Function([l, i], read_func(tensor_array(l), i))\n        expected = [0]\n        check_tensor_array(mod, expected, *(1, 0), dtype=dtype)\n        check_tensor_array(mod, expected, *(5, 1), dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_write():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        tensor_t = p.get_type(\"tensor_t\", dtype)\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        init_tensor_array = tensor_array(relay.const(2))\n        write_func = p.get_global_var(\"tensor_array_write\", dtype)\n        tensor1 = p.get_tensor_ctor(\"tensor1\", dtype)\n        tensor_array1 = write_func(init_tensor_array, relay.const(0), tensor1(v1))\n        tensor_array2 = write_func(tensor_array1, relay.const(1), tensor1(v2))\n        mod[\"main\"] = relay.Function([v1, v2], tensor_array2)\n        expected = [3, 7]\n        check_tensor_array(mod, expected, *(3, 7), dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_stack():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        tensor_t = p.get_type(\"tensor_t\", dtype)\n        rlist = p.mod.get_global_type_var(f\"List\")\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        tensor1 = p.get_tensor_ctor(\"tensor1\", dtype)\n        write = p.get_global_var(\"tensor_array_write\", dtype)\n        stack = p.get_global_var(\"tensor_array_stack\", dtype)\n        # TODO extract test case from inference failures\n        # setting this wrong causes crashes\n        v = relay.var(\"v\", shape=(1,), dtype=dtype)\n        init_tensor_array = tensor_array(relay.const(3))\n        tensor_array1 = write(init_tensor_array, relay.const(0), tensor1(v))\n        tensor_array2 = write(tensor_array1, relay.const(1), tensor1(v))\n        tensor_array3 = write(tensor_array2, relay.const(2), tensor1(v))\n        tensor_array4 = stack(tensor_array3)\n        mod[\"main\"] = relay.Function([v], tensor_array4, tensor_t())\n        t = np.random.uniform(low=0.0, high=8.0, size=(1,)).astype(dtype)\n        expected = [np.stack([t, t, t])]\n        check_tensor_array(mod, expected, t, dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_unstack():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        unstack_tensor1 = p.get_global_var(\"tensor_array_unstack_tensor1\", dtype)\n        v = relay.var(\"v\")\n        mod[\"main\"] = relay.Function([v], unstack_tensor1(v))\n        t = np.random.uniform(low=0.0, high=8.0, size=(1,)).astype(dtype)\n        check_tensor_array(mod, t, t, dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_take():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        take = p.get_global_var(\"tensor_take\", dtype)\n        tensor2 = p.get_tensor_ctor(\"tensor2\", dtype)\n        v = relay.var(\"v\")\n        lower = relay.var(\"lower\")\n        upper = relay.var(\"upper\")\n        mod[\"main\"] = relay.Function([v, lower, upper], take(tensor2(v), lower, upper))\n        v_data = np.random.uniform(low=0.0, high=8.0, size=(10, 10)).astype(dtype)\n        expected = [np.take(v_data, range(2, 5), axis=0)]\n        check_tensor_array(mod, expected, *(v_data, 2, 5), dtype=dtype)\n        expected = [np.take(v_data, range(0, 9), axis=0)]\n        check_tensor_array(mod, expected, *(v_data, 0, 9), dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_concatenate():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        concat = p.get_global_var(\"tensor_concatenate\", dtype)\n        tensor1 = p.get_tensor_ctor(\"tensor1\", dtype)\n        v1 = relay.var(\"v1\", shape=(tvm.tir.Any(),), dtype=dtype)\n        v2 = relay.var(\"v2\", shape=(tvm.tir.Any(),), dtype=dtype)\n        mod[\"main\"] = relay.Function([v1, v2], concat(tensor1(v1), tensor1(v2)))\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=(5,)).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=(5,)).astype(dtype)\n        expected = [np.concatenate((v1_data, v2_data))]\n        check_tensor_array(mod, expected, *(v1_data, v2_data), dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_concat():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        tensor_array1 = tensor_array(relay.const(2))\n        write_func = p.get_global_var(\"tensor_array_write\", dtype)\n        concat_func = p.get_global_var(\"tensor_array_concat\", dtype)\n        tensor1 = p.get_tensor_ctor(\"tensor2\", dtype)\n        tensor_array1 = write_func(tensor_array1, relay.const(0), tensor1(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor1(v2))\n        tensor_array_concat = concat_func(tensor_array1)\n        mod[\"main\"] = relay.Function([v1, v2], tensor_array_concat)\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=(1, 3)).astype(dtype)\n        expected = [np.concatenate((v1_data, v2_data), axis=0)]\n        check_tensor_array(mod, expected, *(v1_data, v2_data), dtype=dtype)\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_scatter():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n\n        # tensor array\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        v3 = relay.var(\"v2\")\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        tensor_array1 = tensor_array(relay.const(3))\n        write_func = p.get_global_var(\"tensor_array_write\", dtype)\n        scatter_func = p.get_global_var(\"tensor_array_scatter\", dtype)\n        tensor2 = p.get_tensor_ctor(\"tensor2\", dtype)\n        tensor_array1 = write_func(tensor_array1, relay.const(0), tensor2(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor2(v2))\n        tensor_array1 = write_func(tensor_array1, relay.const(2), tensor2(v3))\n\n        # indices array\n        index = relay.var(\"index\")\n\n        # values array\n        value_0 = relay.var(\"value_0\")\n        value_1 = relay.var(\"value_1\")\n        values_array = tensor_array(relay.const(2))\n        values_array = write_func(values_array, relay.const(0), tensor2(value_0))\n        values_array = write_func(values_array, relay.const(1), tensor2(value_1))\n\n        # create the scatter function\n        tensor_array_scatter = scatter_func(tensor_array1, index, values_array)\n        mod[\"main\"] = relay.Function([v1, v2, v3, index, value_0, value_1], tensor_array_scatter)\n\n        # initialize and check\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v3_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        index_data = np.array([0, 1], dtype=\"int32\")\n        val1_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        val2_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        expected = [val1_data, val2_data, v3_data]\n        check_tensor_array(\n            mod,\n            expected,\n            *(v1_data, v2_data, v3_data, index_data, val1_data, val2_data),\n            dtype=dtype,\n        )\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_array_split():\n    def run(dtype):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n\n        # tensor array\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        v3 = relay.var(\"v2\")\n        tensor_array = p.get_global_var(\"tensor_array\", dtype)\n        tensor_array1 = tensor_array(relay.const(3))\n        write_func = p.get_global_var(\"tensor_array_write\", dtype)\n        split_func = p.get_global_var(\"tensor_array_split\", dtype)\n        tensor2 = p.get_tensor_ctor(\"tensor2\", dtype)\n        tensor_array1 = write_func(tensor_array1, relay.const(0), tensor2(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor2(v2))\n        tensor_array1 = write_func(tensor_array1, relay.const(2), tensor2(v3))\n\n        # value tensor\n        value = relay.var(\"value\")\n\n        # lengths tensor\n        ta_len = relay.var(\"length\")\n\n        # create the scatter function\n        tensor_array_split = split_func(tensor_array1, tensor2(value), ta_len)\n        mod[\"main\"] = relay.Function([v1, v2, v3, value, ta_len], tensor_array_split)\n\n        # initialize and check\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v3_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        value_data = np.random.uniform(low=0.0, high=8.0, size=(4, 3)).astype(dtype)\n        length_data = np.array([2, 2], dtype=\"int32\")\n        expected = np.concatenate([value_data, v3_data])\n        expected = np.split(expected, indices_or_sections=[2, 4])\n        check_tensor_array(\n            mod, expected, *(v1_data, v2_data, v3_data, value_data, length_data), dtype=dtype\n        )\n\n    run(\"float32\")\n    run(\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_take():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        take = p.get_global_var_static(\"tensor_take\", dtype, shape)\n        tensor_constructor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        v = relay.var(\"v\")\n        lower = relay.var(\"lower\")\n        upper = relay.var(\"upper\")\n        mod[\"main\"] = relay.Function([v, lower, upper], take(tensor_constructor(v), lower, upper))\n        v_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        expected = [np.take(v_data, range(2, 5), axis=0)]\n        check_tensor_array(mod, expected, *(v_data, 2, 5), dtype=dtype)\n        expected = [np.take(v_data, range(0, 9), axis=0)]\n        check_tensor_array(mod, expected, *(v_data, 0, 9), dtype=dtype)\n\n    run(\"float32\", [10, 10])\n    run(\"int32\", [15, 11])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_concatenate():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        concat = p.get_global_var_static(\"tensor_concatenate\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        mod[\"main\"] = relay.Function([v1, v2], concat(tensor(v1), tensor(v2)))\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        expected = [np.concatenate((v1_data, v2_data))]\n        check_tensor_array(mod, expected, *(v1_data, v2_data), dtype=dtype)\n\n    run(\n        \"float32\",\n        [\n            5,\n        ],\n    )\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_expand_dims():\n    def run(dtype, shape):\n        x = relay.var(\"x\")\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        expand_dims_func = p.get_global_var_static(\"tensor_expand_dims\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        mod[\"main\"] = relay.Function([x], expand_dims_func(tensor(x)))\n        x_np = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        expected = [np.expand_dims(x_np, axis=0)]\n        check_tensor_array(mod, expected, x_np)\n\n    run(\"float32\", [])\n    run(\n        \"int32\",\n        [\n            2,\n        ],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_constructor():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n        tensor_constructor = p.get_name_static(\"tensor_constructor\", dtype, shape)\n        assert tensor_constructor != None\n\n    run(\"float32\", [1, 1])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_read():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        np_data_list = []\n        ta_length = 3\n        for _ in range(ta_length):\n            np_data_list.append(np.random.uniform(0, 10, size=shape).astype(dtype))\n\n        v0 = relay.var(\"v0\")\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        n = relay.var(\"n\")\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        init_tensor_array = tensor_array(relay.const(ta_length))\n        read_func = p.get_global_var_static(\"tensor_array_read\", dtype, shape)\n        write_func = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        tensor_array0 = write_func(init_tensor_array, relay.const(0), tensor(v0))\n        tensor_array1 = write_func(tensor_array0, relay.const(1), tensor(v1))\n        tensor_array2 = write_func(tensor_array1, relay.const(2), tensor(v2))\n\n        mod[\"main\"] = relay.Function([v0, v1, v2, n], read_func(tensor_array2, n))\n        expected = [np_data_list[0]]\n        check_tensor_array(mod, expected, *list(np_data_list + [0]), dtype=dtype)\n        expected = [np_data_list[1]]\n        check_tensor_array(mod, expected, *list(np_data_list + [1]), dtype=dtype)\n        expected = [np_data_list[2]]\n        check_tensor_array(mod, expected, *list(np_data_list + [2]), dtype=dtype)\n\n    run(\"float32\", [])\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_write():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        ta_length = 2\n        np_data_list = [\n            np.random.uniform(0, 10, size=shape).astype(dtype) for _ in range(ta_length)\n        ]\n\n        v0 = relay.var(\"v0\")\n        v1 = relay.var(\"v1\")\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        init_tensor_array = tensor_array(relay.const(ta_length))\n        write_func = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        tensor_array0 = write_func(init_tensor_array, relay.const(0), tensor(v0))\n        tensor_array1 = write_func(tensor_array0, relay.const(1), tensor(v1))\n        mod[\"main\"] = relay.Function([v0, v1], tensor_array1)\n        expected = np_data_list\n        check_tensor_array(mod, expected, *np_data_list, dtype=dtype)\n\n    run(\"float32\", [])\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_unstack():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        unstack_tensor = p.get_global_var_static(\"tensor_array_unstack\", dtype, shape)\n        v = relay.var(\"v\")\n        mod[\"main\"] = relay.Function([v], unstack_tensor(v))\n        t = np.random.uniform(low=0, high=10, size=shape).astype(dtype)\n        (*expected,) = t\n        check_tensor_array(mod, expected, t, dtype=dtype)\n\n    run(\"float32\", [4])\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_scatter():\n    def run(dtype, shape, indices_shape=None):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n        if indices_shape is not None:\n            static_tensor_array_ops.define_tensor_array_scatter(indices_shape, True)\n\n        # tensor array\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        v3 = relay.var(\"v2\")\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        tensor_array0 = tensor_array(relay.const(3))\n        write_func = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        scatter_func = p.get_global_var_static(\"tensor_array_scatter\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        tensor_array1 = write_func(tensor_array0, relay.const(0), tensor(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor(v2))\n        tensor_array1 = write_func(tensor_array1, relay.const(2), tensor(v3))\n\n        # indices array\n        index = relay.var(\"index\")\n\n        # values array\n        value_0 = relay.var(\"value_0\")\n        value_1 = relay.var(\"value_1\")\n        values_array = tensor_array(relay.const(2))\n        values_array = write_func(values_array, relay.const(0), tensor(value_0))\n        values_array = write_func(values_array, relay.const(1), tensor(value_1))\n\n        # create the scatter function\n        tensor_array_scatter = scatter_func(tensor_array1, index, values_array)\n        mod[\"main\"] = relay.Function([v1, v2, v3, index, value_0, value_1], tensor_array_scatter)\n\n        # initialize and check\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        v3_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        index_data = np.array([0, 1], dtype=\"int32\")\n        val1_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        val2_data = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        expected = [val1_data, val2_data, v3_data]\n        check_tensor_array(\n            mod,\n            expected,\n            *(v1_data, v2_data, v3_data, index_data, val1_data, val2_data),\n            dtype=dtype,\n        )\n\n    run(\"float32\", [2, 3])\n    run(\"int32\", [2, 3])\n    run(\n        \"float32\",\n        [2, 3],\n        [\n            2,\n        ],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_split():\n    def run(dtype, shape, value_shape=None, lengths_shape=None):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n        if value_shape is not None or lengths_shape is not None:\n            static_tensor_array_ops.define_tensor_array_split(value_shape, lengths_shape, False)\n\n        # tensor array\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        v3 = relay.var(\"v2\")\n\n        adt_shape = [\n            relay.Any(),\n        ] + shape[1:]\n        test_ops = StaticTensorArrayOps(p, dtype, adt_shape)\n        test_ops.register()\n        tensor_array = test_ops.get_global_var(\"tensor_array\")\n\n        tensor_array1 = tensor_array(relay.const(3))\n        write_func = test_ops.get_global_var(\"tensor_array_write\")\n        split_ops = StaticTensorArrayOps(p, dtype, shape)\n        split_ops.register()\n        split_func = split_ops.get_global_var(\"tensor_array_split\")\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, test_ops.shape)\n        tensor_array1 = write_func(tensor_array1, relay.const(0), tensor(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor(v2))\n        tensor_array1 = write_func(tensor_array1, relay.const(2), tensor(v3))\n\n        # value tensor\n        value = relay.var(\"value\")\n\n        # lengths tensor\n        ta_len = relay.var(\"length\")\n\n        # create the split function\n        if value_shape is None:\n            tensor1 = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        else:\n            static_tensor_array_ops = StaticTensorArrayOps(p, dtype, value_shape)\n            static_tensor_array_ops.register()\n            tensor1 = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, test_ops.shape)\n\n        tensor_array_split = split_func(tensor_array1, tensor1(value), ta_len)\n        mod[\"main\"] = relay.Function([v1, v2, v3, value, ta_len], tensor_array_split)\n\n        # initialize and check\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=[2, 3]).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=[2, 3]).astype(dtype)\n        v3_data = np.random.uniform(low=0.0, high=8.0, size=[2, 3]).astype(dtype)\n        value_data = np.random.uniform(low=0.0, high=8.0, size=value_shape or shape).astype(dtype)\n        length_data = np.array([2, 2], dtype=\"int32\")\n        expected = np.concatenate([value_data, v3_data])\n        expected = np.split(expected, indices_or_sections=[2, 4])\n        check_tensor_array(\n            mod, expected, *(v1_data, v2_data, v3_data, value_data, length_data), dtype=dtype\n        )\n\n    run(\"float32\", [4, 3])\n    run(\"int32\", [4, 3])\n    run(\n        \"int32\",\n        [relay.Any(), 3],\n        [4, 3],\n        [\n            2,\n        ],\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_concat():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        tensor_array1 = tensor_array(relay.const(2))\n        write_func = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        concat_func = p.get_global_var_static(\"tensor_array_concat\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        tensor_array1 = write_func(tensor_array1, relay.const(0), tensor(v1))\n        tensor_array1 = write_func(tensor_array1, relay.const(1), tensor(v2))\n        tensor_array_concat = concat_func(tensor_array1)\n        mod[\"main\"] = relay.Function([v1, v2], tensor_array_concat)\n        v1_data = np.random.uniform(low=0.0, high=8.0, size=(2, 3)).astype(dtype)\n        v2_data = np.random.uniform(low=0.0, high=8.0, size=(1, 3)).astype(dtype)\n        expected = [np.concatenate((v1_data, v2_data), axis=0)]\n        check_tensor_array(mod, expected, *(v1_data, v2_data), dtype=dtype)\n\n    run(\"float32\", [relay.Any(), 3])\n    run(\"int32\", [relay.Any(), 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_gather():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        write = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        gather = p.get_global_var_static(\"tensor_array_gather\", dtype, shape)\n        v = relay.var(\"v\")\n        indice = relay.var(\"indice\")\n        init_tensor_array = tensor_array(relay.const(3))\n        tensor_array1 = write(init_tensor_array, relay.const(0), tensor(v))\n        tensor_array2 = write(tensor_array1, relay.const(1), tensor(v))\n        tensor_array3 = write(tensor_array2, relay.const(2), tensor(v))\n        out = gather(tensor_array3, indice)\n        mod[\"main\"] = relay.Function([v, indice], out)\n        t = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        indice_data = np.array([0, 2], dtype=\"int32\")\n        expected = [np.stack([t, t])]\n        check_tensor_array(mod, expected, *(t, indice_data), dtype=dtype)\n\n    run(\"float32\", [])\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_array_stack():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        write = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        stack = p.get_global_var_static(\"tensor_array_stack\", dtype, shape)\n        v = relay.var(\"v\")\n        init_tensor_array = tensor_array(relay.const(3))\n        tensor_array1 = write(init_tensor_array, relay.const(0), tensor(v))\n        tensor_array2 = write(tensor_array1, relay.const(1), tensor(v))\n        tensor_array3 = write(tensor_array2, relay.const(2), tensor(v))\n        tensor_array4 = stack(tensor_array3)\n        mod[\"main\"] = relay.Function([v], tensor_array4)\n        t = np.random.uniform(low=0.0, high=8.0, size=shape).astype(dtype)\n        expected = [np.stack([t, t, t])]\n        check_tensor_array(mod, expected, t, dtype=dtype)\n\n    run(\"float32\", [])\n    run(\"int32\", [2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_static_tensor_get_data():\n    def run(dtype, shape):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n        static_tensor_array_ops = StaticTensorArrayOps(p, dtype, shape)\n        static_tensor_array_ops.register()\n\n        np_data_list = []\n        ta_length = 3\n        for _ in range(ta_length):\n            np_data_list.append(np.random.uniform(0, 10, size=shape).astype(dtype))\n\n        v0 = relay.var(\"v0\")\n        v1 = relay.var(\"v1\")\n        v2 = relay.var(\"v2\")\n        n = relay.var(\"n\")\n        tensor = p.get_tensor_ctor_static(\"tensor_constructor\", dtype, shape)\n        tensor_array = p.get_global_var_static(\"tensor_array\", dtype, shape)\n        init_tensor_array = tensor_array(relay.const(ta_length))\n        read_func = p.get_global_var_static(\"tensor_array_read\", dtype, shape)\n        write_func = p.get_global_var_static(\"tensor_array_write\", dtype, shape)\n        get_data_func = p.get_global_var_static(\"tensor_get_data\", dtype, shape)\n        tensor_array0 = write_func(init_tensor_array, relay.const(0), tensor(v0))\n        tensor_array1 = write_func(tensor_array0, relay.const(1), tensor(v1))\n        tensor_array2 = write_func(tensor_array1, relay.const(2), tensor(v2))\n\n        mod[\"main\"] = relay.Function([v0, v1, v2, n], get_data_func(read_func(tensor_array2, n)))\n        expected = [np_data_list[0]]\n        check_tensor_array(mod, expected, *list(np_data_list + [0]), dtype=dtype)\n        expected = [np_data_list[1]]\n        check_tensor_array(mod, expected, *list(np_data_list + [1]), dtype=dtype)\n        expected = [np_data_list[2]]\n        check_tensor_array(mod, expected, *list(np_data_list + [2]), dtype=dtype)\n\n    run(\"float32\", [])\n    run(\"int32\", [2, 3])\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_to_mixed_precision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for testing ToMixedPrecision pass\"\"\"\nfrom typing import Any, Dict, List\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.testing import lstm\nfrom tvm.relay.transform import InferType, ToMixedPrecision, mixed_precision\n\ntarget_precision = tvm.testing.parameter(\n    pytest.param(\"float16\"),\n    pytest.param(\"bfloat16\"),\n    ids=[\"float16\", \"bfloat16\"],\n)\n\n\ndef run_module(mod: tvm.runtime.Module, mod_params: Dict[str, Any]) -> List:\n    dev = tvm.device(\"llvm\", 0)\n    result = relay.create_executor(\"debug\", mod, device=dev, target=\"llvm\").evaluate()(**mod_params)\n    if isinstance(result, tvm.runtime.container.ADT):\n        result = [r.numpy() for r in result]\n        return result\n    else:\n        return [result.numpy()]\n\n\ndef verify_mixed_precision_output_close(\n    mod: tvm.runtime.Module,\n    mod_params: Dict[str, Any],\n    mixed_precision_dtype=\"float16\",\n    rtol: float = 1e-3,\n    atol: float = 0,\n    keep_orig_output_dtype=False,\n) -> tvm.runtime.Module:\n\n    mod = InferType()(mod)\n    result_fp32 = run_module(mod, mod_params)\n\n    if not keep_orig_output_dtype:\n        amp_mod = ToMixedPrecision(mixed_precision_dtype)(mod)\n        result_amp = run_module(amp_mod, mod_params)\n    else:\n        with tvm.transform.PassContext(\n            config={\"relay.ToMixedPrecision.keep_orig_output_dtype\": True}\n        ):\n            amp_mod = ToMixedPrecision(mixed_precision_dtype)(mod)\n            result_amp = run_module(amp_mod, mod_params)\n\n    # Ensure the results are close\n    if mixed_precision_dtype != \"bfloat16\":\n        for fp32, amp in zip(result_fp32, result_amp):\n            np.testing.assert_allclose(fp32, amp, rtol=rtol, atol=atol)\n\n    if keep_orig_output_dtype:\n        assert (\n            np.array(result_amp).dtype == np.array(result_fp32).dtype\n        ), \"output type and original type mismatch\"\n\n    return amp_mod\n\n\ndef test_lstm(target_precision):\n    \"\"\"A small stress test on a single unrolled lstm unit.\n\n    Has internal functions and let statements the pass must work on.\n    \"\"\"\n    # TODO(AndrewZhaoLuo): investigate why non-even units cause failure in codegen for CUDA\n    # See discussion here: https://github.com/apache/tvm/issues/8294#issuecomment-866190408\n    units = 4\n    iterations = 5\n    mod, mod_params = lstm.get_workload(iterations=iterations, num_hidden=units)\n\n    # This is an unrolled lstm so each data should be the previous results but\n    # we don't care, we just want to stress test things.\n    for i in range(iterations):\n        mod_params[\"data\" if i == 0 else f\"data{i}\"] = np.random.uniform(\n            -10, 10, (1, units)\n        ).astype(\"float32\")\n\n    verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, rtol=0.01, atol=0.01\n    )\n\n\ndef test_lstm_float64():\n    \"\"\"Tests if can handle other mixed precision types.\n\n    As a toy example show can convert graph to float64 and have it run.\n\n    It doesn't really make sense to do it, this just shows we can change\n    the target mixed_precision_dtype.\n    \"\"\"\n    units = 3\n    iterations = 5\n    mod, mod_params = lstm.get_workload(iterations=iterations, num_hidden=units)\n\n    # This is an unrolled lstm so each data should be the previous results but\n    # we don't care, we just want to stress test things.\n    for i in range(iterations):\n        mod_params[\"data\" if i == 0 else f\"data{i}\"] = np.random.uniform(\n            -10, 10, (1, units)\n        ).astype(\"float32\")\n\n    verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=\"float64\", rtol=0.01, atol=0.01\n    )\n\n\ndef test_convert_single_conv(target_precision):\n    \"\"\"Conv is a green listed operation meaning it will always use fp16 workload.\n\n    By default it accumulates to fp32 and outputs fp16.\n    \"\"\"\n    data_shape = (1, 3, 32, 32)\n    weight_shape = (5, 3, 3, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=\"float32\")\n    mod = tvm.IRModule.from_expr(conv)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=data_shape).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=weight_shape).astype(\"float32\"),\n    }\n    amp_mod = verify_mixed_precision_output_close(\n        mod,\n        mod_params,\n        mixed_precision_dtype=target_precision,\n        atol=0.01,\n        rtol=1e-3,\n        keep_orig_output_dtype=True,\n    )\n\n    expected_mod = tvm.IRModule.from_expr(\n        relay.cast(\n            relay.nn.conv2d(\n                relay.cast(data, target_precision),\n                relay.cast(weight, target_precision),\n                strides=(1, 1),\n                padding=(1, 1),\n                out_dtype=target_precision,\n            ),\n            \"float32\",\n        )\n    )\n    expected_mod = tvm.relay.transform.InferType()(expected_mod)\n\n    assert not tvm.ir.structural_equal(amp_mod, mod)\n    assert tvm.ir.structural_equal(amp_mod, expected_mod)\n\n\ndef test_convert_single_conv_fp64():\n    \"\"\"As above but checks choosing a mixed_precision_type other than FP16 works\"\"\"\n    data_shape = (1, 3, 32, 32)\n    weight_shape = (5, 3, 3, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=\"float32\")\n    mod = tvm.IRModule.from_expr(conv)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=data_shape).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=weight_shape).astype(\"float32\"),\n    }\n    amp_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=\"float64\", atol=0.01, rtol=1e-3\n    )\n\n    # Note we still accumulate to FP32 by default, a user would need to overwrite default\n    # behavior to make this make more sense.\n    expected_mod = tvm.IRModule.from_expr(\n        relay.nn.conv2d(\n            relay.cast(data, \"float64\"),\n            relay.cast(weight, \"float64\"),\n            strides=(1, 1),\n            padding=(1, 1),\n            out_dtype=\"float64\",\n        ),\n    )\n    expected_mod = tvm.relay.transform.InferType()(expected_mod)\n\n    assert not tvm.ir.structural_equal(amp_mod, mod)\n    assert tvm.ir.structural_equal(amp_mod, expected_mod)\n\n\ndef test_convert_conv_bn(target_precision):\n    \"\"\"Conv is green and batch norm is gray. As Conv should output fp16 batch_norm should be green.\"\"\"\n    data_shape = (1, 3, 32, 32)\n    weight_shape = (5, 3, 3, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=\"float32\")\n\n    bn_shape = [5]\n    gamma = relay.var(\"gamma\", shape=bn_shape)\n    beta = relay.var(\"beta\", shape=bn_shape)\n    moving_mean = relay.var(\"moving_mean\", shape=bn_shape)\n    moving_var = relay.var(\"moving_var\", shape=bn_shape)\n    bn = relay.nn.batch_norm(conv, gamma, beta, moving_mean, moving_var)\n    mod = tvm.IRModule.from_expr(bn[0])\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=data_shape).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=weight_shape).astype(\"float32\"),\n        \"gamma\": np.random.uniform(-1, 1, size=bn_shape).astype(\"float32\"),\n        \"beta\": np.random.uniform(-1, 1, size=bn_shape).astype(\"float32\"),\n        \"moving_mean\": np.random.uniform(-1, 1, size=bn_shape).astype(\"float32\"),\n        \"moving_var\": np.random.uniform(-1, 1, size=bn_shape).astype(\"float32\"),\n    }\n    amp_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.025, rtol=0.01\n    )\n\n    # Creating expected module\n    data = relay.cast(relay.var(\"data\", shape=data_shape), target_precision)\n    weight = relay.cast(relay.var(\"weight\", shape=weight_shape), target_precision)\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=target_precision)\n\n    bn_shape = [5]\n    gamma = relay.cast(relay.var(\"gamma\", shape=bn_shape), target_precision)\n    beta = relay.cast(relay.var(\"beta\", shape=bn_shape), target_precision)\n    moving_mean = relay.cast(relay.var(\"moving_mean\", shape=bn_shape), target_precision)\n    moving_var = relay.cast(relay.var(\"moving_var\", shape=bn_shape), target_precision)\n    bn = relay.nn.batch_norm(conv, gamma, beta, moving_mean, moving_var)\n\n    expected_mod = tvm.IRModule.from_expr(bn[0])\n    expected_mod = tvm.relay.transform.InferType()(expected_mod)\n    assert not tvm.ir.structural_equal(amp_mod, mod)\n    assert tvm.ir.structural_equal(amp_mod, expected_mod)\n\n\ndef test_do_not_convert_softmax(target_precision):\n    \"\"\"Softmax is a red listed operation and therefore should never be fp16.\"\"\"\n    shape = [1, 2, 3]\n    a = relay.var(\"a\", shape=shape)\n    b = relay.nn.softmax(a)\n    mod = tvm.IRModule.from_expr(b)\n    mod = tvm.relay.transform.InferType()(mod)\n    out_mod = ToMixedPrecision(target_precision)(mod)\n    orig_mod = tvm.relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(orig_mod, out_mod)\n\n\ndef test_do_not_convert_arange(target_precision):\n    \"\"\"Arange is a red listed operation and therefore should never be fp16.\"\"\"\n    dtype = \"float32\"\n    arange = relay.arange(relay.const(1, dtype), relay.const(128, dtype))\n    mod = tvm.IRModule.from_expr(arange)\n    out_mod = ToMixedPrecision(target_precision)(mod)\n    orig_mod = tvm.relay.transform.InferType()(mod)\n    assert tvm.ir.structural_equal(orig_mod, out_mod)\n\n\ndef test_do_not_convert_summation(target_precision):\n    \"\"\"Ops that could involve a large summation are not allowed in fp16.\"\"\"\n    shape = [1, 3, 16, 16]\n    a = relay.var(\"a\", shape=shape)\n    ops = [\n        relay.sum,\n        relay.mean,\n        relay.nn.global_avg_pool2d,\n        lambda inp: relay.nn.adaptive_avg_pool2d(inp, (1, 1)),\n    ]\n    for op in ops:\n        mod = tvm.IRModule.from_expr(op(a))\n        out_mod = ToMixedPrecision(target_precision)(mod)\n        orig_mod = tvm.relay.transform.InferType()(mod)\n        assert tvm.ir.structural_equal(orig_mod, out_mod)\n\n\ndef test_green_gray_propagates_simple(target_precision):\n    \"\"\"Conv is a green listed operation, while addition is gray.\n\n    As Conv outputs fp16 the add should be done in fp16.\n    \"\"\"\n    data_shape = (1, 3, 32, 32)\n    weight_shape = (5, 3, 3, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=\"float32\")\n    conv = conv + conv\n    mod = tvm.IRModule.from_expr(conv)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=data_shape).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=weight_shape).astype(\"float32\"),\n    }\n    amp_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.01, rtol=0.01\n    )\n\n    conv_expr = relay.nn.conv2d(\n        relay.cast(data, target_precision),\n        relay.cast(weight, target_precision),\n        strides=(1, 1),\n        padding=(1, 1),\n        out_dtype=target_precision,\n    )\n    expected_mod = tvm.IRModule.from_expr(conv_expr + conv_expr)\n    expected_mod = tvm.relay.transform.InferType()(expected_mod)\n\n    assert not tvm.ir.structural_equal(amp_mod, mod)\n    assert tvm.ir.structural_equal(amp_mod, expected_mod)\n\n\ndef test_green_red_not_use_extraneous_cast(target_precision):\n    \"\"\"Conv. is a green listed operation, while softmax is red.\n\n    Conv. also by default accumulates to fp32 but outputs fp16.\n\n    We want to avoid a situation where we have extraneous casts.\n    E.g. because softmax wants to operate on FP32 we might have\n\n    conv (FP32) -> cast (FP16) -> cast (FP32) -> softmax (FP32)\n\n    To get around this internally when we cast in the pass we cache\n    the output nodes and the reverse of the cast back to the original\n    node. For example casting the `conv (FP32)` to FP16 would produce:\n\n    `conv (FP32) -> cast (FP16)`\n\n    As the outputs. Now anytime we try to cast the `conv (FP32)` node\n    to FP16 it would return the cached result instead of a new cast node:\n\n    `conv (FP32) -> cast (FP16)`\n\n    Furthermore, if we try to cast the `cast (FP16)` node back to FP32 it\n    would just return\n\n    `conv (FP32)`.\n\n    This test makes sure this behavior occurs.\n    \"\"\"\n    data_shape = (1, 3, 32, 32)\n    weight_shape = (5, 3, 3, 3)\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv = relay.nn.conv2d(data, weight, strides=(1, 1), padding=(1, 1), out_dtype=\"float32\")\n    result = relay.nn.softmax(conv)\n    mod = tvm.IRModule.from_expr(result)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=data_shape).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=weight_shape).astype(\"float32\"),\n    }\n    amp_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.01, rtol=1e-3\n    )\n\n    # Construct expected structure\n    conv = relay.cast(\n        relay.nn.conv2d(\n            relay.cast(data, target_precision),\n            relay.cast(weight, target_precision),\n            strides=(1, 1),\n            padding=(1, 1),\n            out_dtype=target_precision,\n        ),\n        \"float32\",\n    )\n    result = relay.nn.softmax(conv)\n    expected_mod = tvm.IRModule.from_expr(result)\n    expected_mod = InferType()(expected_mod)\n\n    assert tvm.ir.structural_equal(expected_mod, amp_mod)\n\n\ndef test_red_gray_propagates_simple(target_precision):\n    \"\"\"Everything after a softmax should be in FP32 (exception green colored ops)\"\"\"\n    shape = [1, 2, 3]\n    a = relay.var(\"a\", shape=shape)\n    b = relay.nn.softmax(a)\n    c = b + b\n    mod = tvm.IRModule.from_expr(c)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    mod_params = {\n        \"a\": np.random.uniform(-1, 1, size=shape).astype(\"float32\"),\n    }\n    output_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.0, rtol=0.0\n    )\n\n    assert tvm.ir.structural_equal(mod, output_mod)\n\n\ndef test_let_statement_simple(target_precision):\n    \"\"\"A 'simple' let statement example.\n\n    Noticeable is the mutation of the bound variable types.\n    \"\"\"\n    var1 = relay.var(\"var1\", shape=[1, 20])\n    var2 = relay.var(\"var2\", shape=[1, 20])\n\n    data = relay.var(\"data\", shape=[1, 20])\n    weight = relay.var(\"weight\", shape=[20, 20])\n\n    r1 = var1 + var1\n\n    r2 = var2 + var2\n    let2 = relay.Let(var2, relay.nn.dense(r1, weight, units=20), r2)\n    let1 = relay.Let(var1, relay.nn.dense(data, weight, units=20), let2)\n\n    mod = tvm.IRModule.from_expr(let1)\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=[1, 20]).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=[20, 20]).astype(\"float32\"),\n    }\n    output_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.05, rtol=0.15\n    )\n\n    # Construct expected structure\n    var1 = relay.var(\"var1\", shape=[1, 20], dtype=target_precision)\n    var2 = relay.var(\"var2\", shape=[1, 20], dtype=target_precision)\n    data = relay.cast(relay.var(\"data\", shape=[1, 20]), target_precision)\n    weight = relay.cast(relay.var(\"weight\", shape=[20, 20]), target_precision)\n    r1 = var1 + var1\n    r2 = var2 + var2\n    let2 = relay.Let(\n        var2,\n        relay.nn.dense(r1, weight, units=20, out_dtype=target_precision),\n        r2,\n    )\n    let1 = relay.Let(\n        var1,\n        relay.nn.dense(data, weight, units=20, out_dtype=target_precision),\n        let2,\n    )\n    expected_mod = tvm.IRModule.from_expr(let1)\n    expected_mod = InferType()(expected_mod)\n\n    assert tvm.ir.structural_equal(expected_mod, output_mod)\n\n\ndef test_where_simple(target_precision):\n    data = relay.var(\"data\", shape=[1, 20])\n    weight = relay.var(\"weight\", shape=[20, 20])\n    a = relay.nn.dense(data, weight, units=20)\n    b = relay.where(data, a, a)\n    mod = tvm.IRModule.from_expr(b)\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=[1, 20]).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=[20, 20]).astype(\"float32\"),\n    }\n\n    output_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.01, rtol=0.01\n    )\n\n    # Create expected module\n    data = relay.cast(relay.var(\"data\", shape=[1, 20]), target_precision)\n    weight = relay.cast(relay.var(\"weight\", shape=[20, 20]), target_precision)\n    a = relay.nn.dense(data, weight, units=20, out_dtype=target_precision)\n    b = relay.where(data, a, a)\n    expected_mod = tvm.IRModule.from_expr(b)\n    expected_mod = InferType()(expected_mod)\n\n    assert tvm.ir.structural_equal(expected_mod, output_mod)\n\n\ndef test_batch_matmul_simple(target_precision):\n    \"\"\"Batch matmul is a special case where we try to accumulate to fp16.\n\n    This is due to the fact heterogenous accumulation dtypes does not work\n    on all platforms at the moment.\n    \"\"\"\n    data = relay.var(\"data\", shape=[1, 1, 20])\n    weight = relay.var(\"weight\", shape=[1, 20, 20])\n    a = relay.nn.batch_matmul(data, weight)\n    mod = tvm.IRModule.from_expr(a)\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=[1, 1, 20]).astype(\"float32\"),\n        \"weight\": np.random.uniform(-1, 1, size=[1, 20, 20]).astype(\"float32\"),\n    }\n    output_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.01, rtol=0.01\n    )\n    # Create expected module\n    data = relay.cast(relay.var(\"data\", shape=[1, 1, 20]), target_precision)\n    weight = relay.cast(relay.var(\"weight\", shape=[1, 20, 20]), target_precision)\n    a = relay.nn.batch_matmul(data, weight, out_dtype=target_precision)\n    expected_mod = tvm.IRModule.from_expr(a)\n    expected_mod = InferType()(expected_mod)\n    assert tvm.ir.structural_equal(expected_mod, output_mod)\n\n\ndef test_convert_follow_node_with_integer_arguments(target_precision):\n    \"\"\"Tests the conversion of a follow op with integer arguments + constant float args.\n\n    The follow op should convert the floating point argument into fp16 as constants/vars\n    will always be converted if safe to do so.\n    \"\"\"\n\n    data = relay.var(\"data\", shape=[1, 10], dtype=\"float32\")\n\n    # We use an addition to make sure the input indices are not a var\n    # (which are always casted if safe)\n    indices = relay.var(\"indices\", shape=[1, 1], dtype=\"int32\") + relay.const(0, dtype=\"int32\")\n    take = relay.take(data, indices, axis=0)\n    mod = tvm.IRModule.from_expr(take)\n\n    mod_params = {\n        \"data\": np.random.uniform(-1, 1, size=[1, 10]).astype(\"float32\"),\n        \"indices\": np.array([[0]]).astype(\"int32\"),\n    }\n    output_mod = verify_mixed_precision_output_close(\n        mod, mod_params, mixed_precision_dtype=target_precision, atol=0.01, rtol=0.01\n    )\n\n    # Create expected module\n    data = relay.cast(relay.var(\"data\", shape=[1, 10]), target_precision)\n    take = relay.take(data, indices, axis=0)\n    expected_mod = tvm.IRModule.from_expr(take)\n    expected_mod = InferType()(expected_mod)\n    assert tvm.ir.structural_equal(expected_mod, output_mod)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_type_functor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import TypeFunctor, TypeMutator, TypeVisitor\nfrom tvm.relay.ty import (\n    TypeVar,\n    IncompleteType,\n    TensorType,\n    FuncType,\n    TupleType,\n    TypeRelation,\n    RefType,\n    GlobalTypeVar,\n    TypeCall,\n)\nfrom tvm.relay.adt import TypeData\n\n\ndef check_visit(typ):\n    try:\n        ef = TypeFunctor()\n        ef.visit(typ)\n        assert False\n    except NotImplementedError:\n        pass\n\n    ev = TypeVisitor()\n    ev.visit(typ)\n\n    tvm.ir.assert_structural_equal(TypeMutator().visit(typ), typ, map_free_vars=True)\n\n\ndef test_type_var():\n    tv = TypeVar(\"a\")\n    check_visit(tv)\n\n\ndef test_incomplete_type():\n    it = IncompleteType()\n    check_visit(it)\n\n\ndef test_tensor_type():\n    tt = TensorType([])\n    check_visit(tt)\n\n\ndef test_func_type():\n    tv = TypeVar(\"tv\")\n    tt = relay.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    ft = FuncType([tt], tt, type_params=[tv])\n    check_visit(ft)\n\n\ndef test_tuple_type():\n    tt = TupleType([TupleType([])])\n    check_visit(tt)\n\n\ndef test_type_relation():\n    func = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Broadcast\")\n    attrs = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n    tp = TypeVar(\"tp\")\n    tf = FuncType([], TupleType([]), [], [])\n    tt = TensorType([1, 2, 3], \"float32\")\n    tr = TypeRelation(func, [tp, tf, tt], 2, attrs)\n\n    check_visit(tr)\n\n\ndef test_ref_type():\n    rt = RefType(TupleType([]))\n    check_visit(rt)\n\n\ndef test_global_type_var():\n    gtv = GlobalTypeVar(\"gtv\")\n    check_visit(gtv)\n\n\ndef test_type_call():\n    tc = TypeCall(GlobalTypeVar(\"tf\"), [TupleType([])])\n    check_visit(tc)\n\n\ndef test_type_data():\n    td = TypeData(GlobalTypeVar(\"td\"), [TypeVar(\"tv\")], [])\n    check_visit(td)\n\n\nif __name__ == \"__main__\":\n    test_type_var()\n    test_incomplete_type()\n    test_tensor_type()\n    test_func_type()\n    test_tuple_type()\n    test_type_relation()\n    test_ref_type()\n    test_global_type_var()\n    test_type_call()\n    test_type_data()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_type_infer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test that type checker correcly computes types\n   for expressions.\n\"\"\"\nimport pytest\nimport tvm\nfrom tvm import IRModule, parser, relay, te\nfrom tvm.relay import analysis, op, transform\nfrom tvm.relay.op import op as _op\n\nimport numpy as np\n\n\ndef infer_mod(mod, annotate_spans=True):\n    if annotate_spans:\n        mod = relay.transform.AnnotateSpans()(mod)\n\n    mod = transform.InferType()(mod)\n    return mod\n\n\ndef infer_expr(expr):\n    transform.InferTypeLocal(expr)\n    return expr\n\n\ndef assert_has_type(expr, typ, mod=None):\n    if not mod:\n        mod = tvm.IRModule({})\n\n    mod[\"main\"] = expr\n    mod = infer_mod(mod)\n    checked_expr = mod[\"main\"]\n    checked_type = checked_expr.checked_type\n    if checked_type != typ:\n        raise RuntimeError(\"Type mismatch %s vs %s\" % (checked_type, typ))\n\n\ndef initialize_box_adt(mod):\n    # initializes simple ADT for tests\n    box = relay.GlobalTypeVar(\"box\")\n    tv = relay.TypeVar(\"tv\")\n    constructor = relay.Constructor(\"constructor\", [tv], box)\n    data = relay.TypeData(box, [tv], [constructor])\n    mod[box] = data\n    return box, constructor\n\n\ndef test_monomorphic_let():\n    \"Program: let %x = 1; %x\"\n    # TODO(@jroesch): this seems whack.\n    sb = relay.ScopeBuilder()\n    x = relay.var(\"x\", dtype=\"float64\", shape=())\n    x = sb.let(x, relay.const(1.0, \"float64\"))\n    sb.ret(x)\n    xchecked = infer_expr(sb.get())\n    assert xchecked.checked_type == relay.scalar_type(\"float64\")\n\n\ndef test_single_op():\n    \"Program: fn (%x : float32) { let %t1 = f(%x); %t1 }\"\n    x = relay.var(\"x\", shape=[])\n    func = relay.Function([x], op.log(x))\n    ttype = relay.TensorType([], dtype=\"float32\")\n    assert_has_type(func, relay.FuncType([ttype], ttype))\n\n\ndef test_add_broadcast_op():\n    \"\"\"\n    Program:\n        fn (%x: Tensor[(10, 4), float32], %y: Tensor[(5, 10, 1), float32])\n            -> Tensor[(5, 10, 4), float32] {\n            %x + %y\n        }\n    \"\"\"\n    x = relay.var(\"x\", shape=(10, 4))\n    y = relay.var(\"y\", shape=(5, 10, 1))\n    z = x + y\n    func = relay.Function([x, y], z)\n    t1 = relay.TensorType((10, 4), \"float32\")\n    t2 = relay.TensorType((5, 10, 1), \"float32\")\n    t3 = relay.TensorType((5, 10, 4), \"float32\")\n    expected_ty = relay.FuncType([t1, t2], t3)\n    assert_has_type(func, expected_ty)\n\n\ndef test_dual_op():\n    \"\"\"Program:\n    fn (%x : Tensor[(10, 10), float32]) {\n      let %t1 = log(x);\n      let %t2 = add(%t1, %x);\n      %t1\n    }\n    \"\"\"\n    tp = relay.TensorType((10, 10), \"float32\")\n    x = relay.var(\"x\", tp)\n    sb = relay.ScopeBuilder()\n    t1 = sb.let(\"t1\", relay.log(x))\n    t2 = sb.let(\"t2\", relay.add(t1, x))\n    sb.ret(t2)\n    f = relay.Function([x], sb.get())\n    fchecked = infer_expr(f)\n    assert fchecked.checked_type == relay.FuncType([tp], tp)\n\n\ndef test_decl():\n    \"\"\"Program:\n    def @f(%x : Tensor[(10, 10), float32]) {\n        log(%x)\n    }\n    \"\"\"\n    tp = relay.TensorType((10, 10))\n    x = relay.var(\"x\", tp)\n    f = relay.Function([x], relay.log(x))\n    fchecked = infer_expr(f)\n    assert fchecked.checked_type == relay.FuncType([tp], tp)\n\n\ndef test_recursion():\n    \"\"\"\n    Program:\n       def @f(%n: int32, %data: float32) -> float32 {\n          if (%n == 0) {\n              %data\n          } else {\n              @f(%n - 1, log(%data))\n          }\n       }\n    \"\"\"\n    sb = relay.ScopeBuilder()\n    f = relay.GlobalVar(\"f\")\n    ti32 = relay.scalar_type(\"int32\")\n    tf32 = relay.scalar_type(\"float32\")\n    n = relay.var(\"n\", ti32)\n    data = relay.var(\"data\", tf32)\n\n    with sb.if_scope(relay.equal(n, relay.const(0, ti32))):\n        sb.ret(data)\n    with sb.else_scope():\n        sb.ret(f(relay.subtract(n, relay.const(1, ti32)), relay.log(data)))\n    mod = tvm.IRModule()\n    mod[f] = relay.Function([n, data], sb.get())\n    mod = infer_mod(mod)\n    assert \"@f(%1, %2)\" in mod.astext()\n    assert mod[\"f\"].checked_type == relay.FuncType([ti32, tf32], tf32)\n\n\ndef test_incomplete_call():\n    tt = relay.scalar_type(\"int32\")\n    x = relay.var(\"x\", tt)\n    f_type = relay.FuncType([tt], tt)\n    f = relay.var(\"f\")\n    func = relay.Function([x, f], relay.Call(f, [x]), tt)\n\n    ft = infer_expr(func)\n    assert ft.checked_type == relay.FuncType([tt, f_type], tt)\n\n\ndef test_higher_order_argument():\n    a = relay.TypeVar(\"a\")\n    x = relay.Var(\"x\", a)\n    id_func = relay.Function([x], x, a, [a])\n\n    b = relay.TypeVar(\"b\")\n    f = relay.Var(\"f\", relay.FuncType([b], b))\n    y = relay.Var(\"y\", b)\n    ho_func = relay.Function([f, y], f(y), b, [b])\n\n    # id func should be an acceptable argument to the higher-order\n    # function even though id_func takes a type parameter\n    ho_call = ho_func(id_func, relay.const(0, \"int32\"))\n\n    hc = infer_expr(ho_call)\n    expected = relay.scalar_type(\"int32\")\n    assert hc.checked_type == expected\n\n\ndef test_higher_order_return():\n    a = relay.TypeVar(\"a\")\n    x = relay.Var(\"x\", a)\n    id_func = relay.Function([x], x, a, [a])\n\n    b = relay.TypeVar(\"b\")\n    nested_id = relay.Function([], id_func, relay.FuncType([b], b), [b])\n\n    ft = infer_expr(nested_id)\n    assert ft.checked_type == relay.FuncType([], relay.FuncType([b], b), [b])\n\n\ndef test_higher_order_nested():\n    a = relay.TypeVar(\"a\")\n    x = relay.Var(\"x\", a)\n    id_func = relay.Function([x], x, a, [a])\n\n    choice_t = relay.FuncType([], relay.scalar_type(\"bool\"))\n    f = relay.Var(\"f\", choice_t)\n\n    b = relay.TypeVar(\"b\")\n    z = relay.Var(\"z\")\n    top = relay.Function(\n        [f], relay.If(f(), id_func, relay.Function([z], z)), relay.FuncType([b], b), [b]\n    )\n\n    expected = relay.FuncType([choice_t], relay.FuncType([b], b), [b])\n    ft = infer_expr(top)\n    assert ft.checked_type == expected\n\n\ndef test_tuple():\n    tp = relay.TensorType((10,))\n    x = relay.var(\"x\", tp)\n    res = relay.Tuple([x, x])\n    assert infer_expr(res).checked_type == relay.TupleType([tp, tp])\n\n\ndef test_ref():\n    x = relay.var(\"x\", \"float32\")\n    y = relay.var(\"y\", \"float32\")\n    r = relay.RefCreate(x)\n    st = relay.scalar_type(\"float32\")\n    assert infer_expr(r).checked_type == relay.RefType(st)\n    g = relay.RefRead(r)\n    assert infer_expr(g).checked_type == st\n    w = relay.RefWrite(r, y)\n    assert infer_expr(w).checked_type == relay.TupleType([])\n\n\ndef test_free_expr():\n    x = relay.var(\"x\", \"float32\")\n    y = relay.add(x, x)\n    yy = infer_expr(y)\n    assert tvm.ir.structural_equal(yy.args[0], x, map_free_vars=True)\n    assert yy.checked_type == relay.scalar_type(\"float32\")\n    assert x.vid.same_as(yy.args[0].vid)\n\n\ndef test_type_args():\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    z = relay.add(x, y)\n\n    # InferTypeLocal does not support populating the type_args field\n    mod = infer_mod(IRModule.from_expr(z))\n    mod = infer_mod(mod, annotate_spans=False)\n    ty_args = mod[\"main\"].body.type_args\n    assert len(ty_args) == 2\n    assert ty_args[0].dtype == \"float32\"\n    assert ty_args[1].dtype == \"float32\"\n    sh1 = ty_args[0].shape\n    sh2 = ty_args[1].shape\n    assert sh1[0].value == 10\n    assert sh1[1].value == 10\n    assert sh2[0].value == 1\n    assert sh2[1].value == 10\n\n\ndef test_global_var_recursion():\n    mod = tvm.IRModule({})\n    gv = relay.GlobalVar(\"main\")\n    x = relay.var(\"x\", shape=[])\n    tt = relay.scalar_type(\"float32\")\n\n    func = relay.Function([x], relay.Call(gv, [x]), tt)\n    mod[gv] = func\n    mod = infer_mod(mod)\n    func_ty = mod[\"main\"].checked_type\n\n    assert func_ty == relay.FuncType([tt], tt)\n\n\ndef test_equal():\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    eq = op.equal(i, relay.const(0, dtype=\"int32\"))\n    func = relay.Function([i], eq)\n    ft = infer_expr(func)\n    expected = relay.FuncType([relay.scalar_type(\"int32\")], relay.scalar_type(\"bool\"))\n    assert ft.checked_type == expected\n\n    assert ft.checked_type == relay.FuncType(\n        [relay.scalar_type(\"int32\")], relay.scalar_type(\"bool\")\n    )\n\n\ndef test_constructor_type():\n    mod = tvm.IRModule()\n    box, constructor = initialize_box_adt(mod)\n\n    a = relay.TypeVar(\"a\")\n    x = relay.Var(\"x\", a)\n    func = relay.Function([x], constructor(x), box(a), [a])\n    mod[\"main\"] = func\n    mod = infer_mod(mod)\n    func_ty = mod[\"main\"].checked_type\n    box = mod.get_global_type_var(\"box\")\n    expected = relay.FuncType([a], box(a), [a])\n    assert func_ty == expected\n\n\ndef test_constructor_call():\n    mod = tvm.IRModule()\n    box, constructor = initialize_box_adt(mod)\n\n    box_unit = constructor(relay.Tuple([]))\n    box_constant = constructor(relay.const(0, \"float32\"))\n\n    func = relay.Function([], relay.Tuple([box_unit, box_constant]))\n    mod[\"main\"] = func\n    mod = infer_mod(mod)\n    ret_type = mod[\"main\"].checked_type.ret_type.fields\n    # NB(@jroesch): when we annotate spans the ast fragments before\n    # annotation the previous fragments will no longer be directly equal.\n    box = mod.get_global_type_var(\"box\")\n    expected1 = box(relay.TupleType([]))\n    expected2 = box(relay.TensorType((), \"float32\"))\n    assert ret_type[0] == expected1\n    assert ret_type[1] == expected2\n\n\ndef test_adt_match():\n    mod = tvm.IRModule()\n    box, constructor = initialize_box_adt(mod)\n\n    v = relay.Var(\"v\", relay.TensorType((), \"float32\"))\n    match = relay.Match(\n        constructor(relay.const(0, \"float32\")),\n        [\n            relay.Clause(\n                relay.PatternConstructor(constructor, [relay.PatternVar(v)]), relay.Tuple([])\n            ),\n            # redundant but shouldn't matter to typechecking\n            relay.Clause(relay.PatternWildcard(), relay.Tuple([])),\n        ],\n    )\n\n    func = relay.Function([], match)\n    mod[\"main\"] = func\n    mod = infer_mod(mod)\n    actual = mod[\"main\"].checked_type.ret_type\n    assert actual == relay.TupleType([])\n\n\ndef test_adt_match_type_annotations():\n    mod = tvm.IRModule()\n    box, constructor = initialize_box_adt(mod)\n\n    # the only type annotation is inside the match pattern var\n    # but that should be enough info\n    tt = relay.TensorType((2, 2), \"float32\")\n    x = relay.Var(\"x\")\n    mv = relay.Var(\"mv\", tt)\n    match = relay.Match(\n        constructor(x),\n        [\n            relay.Clause(\n                relay.PatternConstructor(constructor, [relay.PatternVar(mv)]), relay.Tuple([])\n            )\n        ],\n    )\n\n    mod[\"main\"] = relay.Function([x], match)\n    mod = infer_mod(mod)\n    ft = mod[\"main\"].checked_type\n    assert ft == relay.FuncType([tt], relay.TupleType([]))\n\n\ndef test_let_polymorphism():\n    id = relay.Var(\"id\")\n    xt = relay.TypeVar(\"xt\")\n    x = relay.Var(\"x\", xt)\n    body = relay.Tuple([id(relay.const(1)), id(relay.Tuple([]))])\n    body = relay.Let(id, relay.Function([x], x, xt, [xt]), body)\n    body = infer_expr(body)\n    int32 = relay.TensorType((), \"int32\")\n    tvm.ir.assert_structural_equal(body.checked_type, relay.TupleType([int32, relay.TupleType([])]))\n\n\ndef test_type_arg_infer():\n    code = \"\"\"\n#[version = \"0.0.5\"]\ndef @id[A](%x: A) -> A {\n  %x\n}\ndef @main(%f: float32) -> float32 {\n  @id(%f)\n}\n\"\"\"\n    mod = tvm.parser.fromtext(code)\n    mod = transform.InferType()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"].body.type_args, [relay.TensorType((), \"float32\")])\n\n\ndef test_dynamic_function():\n    dy_tt = relay.TensorType([relay.Any()], \"float32\")\n    s_tt = relay.TensorType([10], \"float32\")\n    x = relay.Var(\"x\", dy_tt)\n    f = relay.Function([x], x + x)\n    y = relay.Var(\"y\", s_tt)\n    c = f(y)\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([y], c)\n    mod = transform.InferType()(mod)\n    assert mod[\"main\"].params[0].checked_type == s_tt\n\n\ndef test_custom_op_infer():\n    \"\"\"Tests infer type for custom_op\"\"\"\n    op_name = \"custom_log\"\n    _op.register(op_name, r\"code(cal log of a tensor.)code\")\n    _op.get(op_name).set_num_inputs(1)\n    _op.get(op_name).add_argument(\"data_0\", \"Tensor\", \"The input data tensor.\")\n    # call default relation functions\n    _op.get(op_name).add_type_rel(\"Identity\")\n    _op.get(op_name).set_support_level(1)\n    _op.register_pattern(op_name, _op.OpPattern.ELEMWISE)\n    _op.register_stateful(op_name, False)\n\n    def clog(x):\n        return relay.Call(_op.get(op_name), [x])\n\n    tp = relay.TensorType((10, 10), \"float32\")\n    x = relay.var(\"x\", tp)\n    sb = relay.ScopeBuilder()\n    t1 = sb.let(\"t1\", clog(x))\n    t2 = sb.let(\"t2\", relay.add(t1, x))\n    sb.ret(t2)\n    f = relay.Function([x], sb.get())\n    fchecked = infer_expr(f)\n    assert fchecked.checked_type == relay.FuncType([tp], tp)\n\n\ndef test_custom_add_broadcast_op():\n    \"\"\"Tests infer type for broadcast custom_op\"\"\"\n    op_name = \"custom_broadcast_add\"\n    _op.register(op_name, r\"code(Add two tensor with inner broadcasting.)code\")\n    _op.get(op_name).set_num_inputs(2)\n    _op.get(op_name).add_argument(\"data_0\", \"Tensor\", \"The input data tensor.\")\n    _op.get(op_name).add_argument(\"data_1\", \"Tensor\", \"The input data tensor.\")\n    # call default relation functions\n    _op.get(op_name).add_type_rel(\"Broadcast\")\n    _op.get(op_name).set_support_level(1)\n    _op.register_stateful(op_name, False)\n\n    def broadcast_add(x, y):\n        return relay.Call(_op.get(op_name), [x, y])\n\n    x = relay.var(\"x\", shape=(10, 4))\n    y = relay.var(\"y\", shape=(5, 10, 1))\n    z = broadcast_add(x, y)\n    func = relay.Function([x, y], z)\n    t1 = relay.TensorType((10, 4), \"float32\")\n    t2 = relay.TensorType((5, 10, 1), \"float32\")\n    t3 = relay.TensorType((5, 10, 4), \"float32\")\n    expected_ty = relay.FuncType([t1, t2], t3)\n    assert_has_type(func, expected_ty)\n\n\ndef test_custom_op_rel_infer():\n    \"\"\"Tests infer type for custom_op\"\"\"\n\n    def custom_log1_rel(arg_types, attrs):\n        assert len(arg_types) == 1, \"type relation arg number mismatch!\"\n        if attrs:\n            assert isinstance(attrs, DictAttrs)\n        inputa_type = arg_types[0]\n        return relay.TensorType(inputa_type.shape, inputa_type.dtype)\n\n    op_name = \"custom_log1\"\n    _op.register(op_name, r\"code(cal log of a tensor.)code\")\n    _op.get(op_name).set_num_inputs(1)\n    _op.get(op_name).add_argument(\"data_0\", \"Tensor\", \"The input data tensor.\")\n    _op.get(op_name).set_attrs_type_key(\"DictAttrs\")\n    # call customized relation functions\n    _op.get(op_name).add_type_rel(\"custom_log1\", custom_log1_rel)\n    _op.get(op_name).set_support_level(1)\n    _op.register_pattern(op_name, _op.OpPattern.ELEMWISE)\n    _op.register_stateful(op_name, False)\n\n    def clog(x):\n        return relay.Call(_op.get(op_name), [x])\n\n    tp = relay.TensorType((10, 10), \"float32\")\n    x = relay.var(\"x\", tp)\n    sb = relay.ScopeBuilder()\n    t1 = sb.let(\"t1\", clog(x))\n    t2 = sb.let(\"t2\", relay.add(t1, x))\n    sb.ret(t2)\n    f = relay.Function([x], sb.get())\n    fchecked = infer_expr(f)\n    assert fchecked.checked_type == relay.FuncType([tp], tp)\n\n\ndef test_custom_op_rel_infer_exception():\n    \"\"\"Tests infer type for custom_op\"\"\"\n\n    def custom_log1_rel(arg_types, attrs):\n        assert len(arg_types) == 2, \"type relation arg number mismatch!\"\n        return None\n\n    op_name = \"custom_log2\"\n    _op.register(op_name, r\"code(cal log of a tensor.)code\")\n    _op.get(op_name).set_num_inputs(1)\n    _op.get(op_name).add_argument(\"data_0\", \"Tensor\", \"The input data tensor.\")\n    _op.get(op_name).set_attrs_type_key(\"DictAttrs\")\n    # call customized relation functions\n    _op.get(op_name).add_type_rel(\"custom_log2\", custom_log1_rel)\n    _op.get(op_name).set_support_level(1)\n    _op.register_pattern(op_name, _op.OpPattern.ELEMWISE)\n    _op.register_stateful(op_name, False)\n\n    def clog(x):\n        return relay.Call(_op.get(op_name), [x])\n\n    tp = relay.TensorType((10, 10), \"float32\")\n    x = relay.var(\"x\", tp)\n    sb = relay.ScopeBuilder()\n    t1 = sb.let(\"t1\", clog(x))\n    t2 = sb.let(\"t2\", relay.add(t1, x))\n    sb.ret(t2)\n    f = relay.Function([x], sb.get())\n    with pytest.raises(tvm.error.TVMError) as cm:\n        fchecked = infer_expr(f)\n        assert \"type relation arg number mismatch\" in str(cm.execption)\n\n\ndef test_repeat_register():\n    op_name = \"custom_log3\"\n    _op.register(op_name, r\"code(cal log of a tensor.)code\")\n    with pytest.raises(tvm.error.TVMError) as cm:\n        _op.register(op_name)\n        assert \"Operator custom_log3 is registered before\" in str(cm.execption)\n\n\ndef test_argreduce_infer_return_type():\n    x_shape = (1, 1)\n    broadcast_shape = [1, 1]\n    shape_dtypes = [(\"int32\", lambda x: np.int32(x)), (\"int64\", lambda x: np.int64(x))]\n\n    # Testing with argmax\n    for (sdtype, conv) in shape_dtypes:\n        x = relay.var(\"data\", relay.TensorType(x_shape, \"float32\"))\n        broadcast_to = relay.op.broadcast_to(x, relay.const(broadcast_shape, dtype=sdtype))\n        argmax = relay.op.argmax(broadcast_to, axis=[1])\n\n        f = relay.Function([x], argmax)\n        assert_has_type(\n            f,\n            relay.FuncType(\n                [relay.TensorType(broadcast_shape, \"float32\")],\n                relay.TensorType([conv(1)], dtype=sdtype),\n            ),\n        )\n\n    # Testing with argmin\n    for (sdtype, conv) in shape_dtypes:\n        x = relay.var(\"data\", relay.TensorType(x_shape, \"float32\"))\n        broadcast_to = relay.op.broadcast_to(x, relay.const(broadcast_shape, dtype=sdtype))\n        argmin = relay.op.argmin(broadcast_to, axis=[1])\n\n        f = relay.Function([x], argmin)\n        assert_has_type(\n            f,\n            relay.FuncType(\n                [relay.TensorType(broadcast_shape, \"float32\")],\n                relay.TensorType([conv(1)], dtype=sdtype),\n            ),\n        )\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    pytest.main(sys.argv)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_type_solver.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import testing\n\nimport pytest\nimport numpy as np\n\n\ndef make_rel(name, args, num_inputs=None, attrs=None):\n    func = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.\" + name)\n    if num_inputs is None:\n        num_inputs = len(args) - 1\n    return relay.ty.TypeRelation(func, args, num_inputs, attrs)\n\n\ndef make_solver():\n    solver = relay.analysis._ffi_api._test_type_solver()\n    solver.Solve = solver(\"Solve\")\n    solver.Unify = solver(\"Unify\")\n    solver.Resolve = solver(\"Resolve\")\n    solver.AddConstraint = solver(\"AddConstraint\")\n\n    def gen_type(name, args, out=None):\n        out = out if out else relay.ty.IncompleteType()\n        solver.AddConstraint(make_rel(name, args + [out]))\n        return out\n\n    solver.gen_type = gen_type\n    return solver\n\n\ndef test_bcast():\n    solver = make_solver()\n    t0 = relay.ty.TensorType((10, 20), \"float32\")\n    t1 = relay.ty.TensorType((10, 1), \"float32\")\n    tc = relay.ty.TensorType((10, 1, 1), \"float32\")\n    t2 = solver.gen_type(\"Broadcast\", [t0, t1])\n    t3 = solver.gen_type(\"Identity\", [t2])\n    t4 = solver.gen_type(\"Broadcast\", [t3, tc])\n    assert solver.Solve()\n    assert solver.Resolve(t2) == relay.ty.TensorType((10, 20), \"float32\")\n    assert solver.Resolve(t4) == relay.ty.TensorType((10, 10, 20), \"float32\")\n\n\ndef test_backward_solving():\n    solver = make_solver()\n    t0 = relay.ty.TensorType((10, 20), \"float32\")\n    tc = relay.ty.TensorType((10, 1, 1), \"float32\")\n    t1 = relay.ty.IncompleteType()\n    t3 = solver.gen_type(\"Broadcast\", [t0, t1])\n    t2 = solver.gen_type(\"Identity\", [t1], out=tc)\n    assert solver.Solve()\n    assert solver.Resolve(t3) == relay.ty.TensorType((10, 10, 20), \"float32\")\n\n\ndef test_unify_tuple():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.TensorType((10, 20), \"float32\")\n\n    tup1 = relay.ty.TupleType([t1, t2])\n    tup2 = relay.ty.TupleType([t3, t3])\n\n    unified = solver.Unify(tup1, tup2)\n    assert unified == tup2\n\n\ndef test_unify_global_type_var():\n    # should only be able to unify if they're the same\n    solver = make_solver()\n    gtv = relay.GlobalTypeVar(\"gtv\")\n    unified = solver.Unify(gtv, gtv)\n    assert unified == gtv\n\n\ndef test_unify_typecall():\n    solver = make_solver()\n    gtv = relay.GlobalTypeVar(\"gtv\")\n\n    # yeah, typecalls are shaped like tuples so the same\n    # tests work out\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.TensorType((10, 20), \"float32\")\n\n    tc1 = relay.ty.TypeCall(gtv, [t1, t2])\n    tc2 = relay.ty.TypeCall(gtv, [t3, t3])\n    unified = solver.Unify(tc1, tc2)\n    assert unified == tc2\n\n\ndef test_unify_functype():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.IncompleteType()\n\n    unit = relay.ty.TupleType([])\n    tensor1 = relay.ty.TensorType((10, 20), \"float32\")\n    tensor2 = relay.ty.TensorType((10,), \"float32\")\n\n    ft1 = relay.ty.FuncType([t1, t2], t3)\n    ft2 = relay.ty.FuncType([tensor1, tensor2], unit)\n\n    unified = solver.Unify(ft1, ft2)\n    assert unified == ft2\n\n\ndef test_recursive_unify():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.IncompleteType()\n\n    tensor1 = relay.ty.TensorType((10, 10, 20), \"float32\")\n    tensor2 = relay.ty.TensorType((10, 20), \"float32\")\n    tensor3 = relay.ty.TensorType((10,), \"float32\")\n\n    tup1 = relay.ty.TupleType([relay.ty.TupleType([t1, t2]), t2])\n    tup2 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor2])\n\n    ft1 = relay.ty.FuncType([tup1, t3], t3)\n    ft2 = relay.ty.FuncType([tup2, tensor3], tensor3)\n\n    unified = solver.Unify(ft1, ft2)\n    assert unified == ft2\n\n\ndef test_unify_vars_under_tuples():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n\n    tup1 = relay.ty.TupleType([t1, t1])\n    unified = solver.Unify(tup1, tup1)\n    assert unified == tup1\n\n    t2 = relay.ty.IncompleteType()\n    tup2 = relay.ty.TupleType([t2, t2])\n\n    tup3 = relay.ty.TupleType([t1, t2])\n    tup4 = relay.ty.TupleType([t2, t1])\n    unified = solver.Unify(tup3, tup4)\n    assert unified == tup1 or unified == tup2\n\n\ndef test_binding_over_typevars():\n    solver = make_solver()\n\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n\n    a = relay.ty.TypeVar(\"a\")\n    b = relay.ty.TypeVar(\"b\")\n    c = relay.ty.TypeVar(\"c\")\n    d = relay.ty.TypeVar(\"d\")\n\n    ft1 = relay.ty.FuncType([t1], t2, [c, d])\n    ft2 = relay.ty.FuncType([a], b, [a, b])\n    unified = solver.Unify(ft1, ft2)\n    assert unified == solver.Resolve(ft1)\n\n\ndef test_recursive_backward_solving():\n    solver = make_solver()\n\n    tensor1 = relay.ty.TensorType((10, 20), \"float32\")\n    tensor2 = relay.ty.TensorType((10, 1, 1), \"float32\")\n    tensor3 = relay.ty.TensorType((10,), \"float32\")\n\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.IncompleteType()\n\n    tup1 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor3])\n    tup2 = relay.ty.TupleType([relay.ty.TupleType([t1, t2]), t3])\n    solver.gen_type(\"Identity\", [tup1], out=tup2)\n\n    assert solver.Solve()\n    assert solver.Resolve(tup2) == tup1\n\n\ndef test_backward_solving_after_child_update():\n    solver = make_solver()\n\n    tensor1 = relay.ty.TensorType((10, 20), \"float32\")\n    tensor2 = relay.ty.TensorType((10, 1, 1), \"float32\")\n\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n    t3 = relay.ty.IncompleteType()\n\n    tup1 = relay.ty.TupleType([t1, t2])\n    tup2 = relay.ty.TupleType([t1, t3])\n\n    tup_concrete = relay.ty.TupleType([tensor1, tensor2])\n\n    t4 = solver.gen_type(\"Identity\", [tup1])\n    t5 = solver.gen_type(\"Identity\", [tup2])\n\n    solver.gen_type(\"Identity\", [t4], out=t5)\n    assert solver.Solve()\n    assert solver.Resolve(t3) == t3 or solver.Resolve(t3) == t2\n    assert solver.Resolve(t4) == tup1 or solver.Resolve(t4) == tup2\n    assert solver.Resolve(t5) == tup1 or solver.Resolve(t5) == tup2\n\n    # updating the variables *inside* tup1 and tup2 should update t4 and t5\n    solver.gen_type(\"Identity\", [t1], out=tensor1)\n    solver.gen_type(\"Identity\", [t2], out=tensor2)\n    assert solver.Solve()\n    assert solver.Resolve(t4) == tup_concrete\n    assert solver.Resolve(t5) == tup_concrete\n\n\ndef test_unify_quantified_funcs():\n    solver = make_solver()\n    a, b, c = relay.TypeVar(\"a\"), relay.TypeVar(\"b\"), relay.TypeVar(\"c\")\n    ft1 = relay.FuncType([a, b], c, [a, b, c])\n    ft2 = relay.FuncType([a, a], a, [a])\n    unified = solver.Unify(ft1, ft2)\n    assert unified == ft2\n\n    ft3 = relay.FuncType([a], a, [a])\n    ft4 = relay.FuncType([b], c, [b, c])\n    unified = solver.Unify(ft3, ft4)\n    assert unified == ft3\n\n\ndef test_unify_quantified_func_and_concrete():\n    solver = make_solver()\n    a, b = relay.TypeVar(\"a\"), relay.TypeVar(\"b\")\n    ft1 = relay.FuncType([a], b, [a, b])\n    ft2 = relay.FuncType([b], relay.TupleType([]), [b])\n    unified = solver.Unify(ft1, ft2)\n    assert unified == ft2\n\n\ndef test_unify_quantified_funcs_nesting():\n    solver = make_solver()\n    a, b, c = relay.TypeVar(\"a\"), relay.TypeVar(\"b\"), relay.TypeVar(\"c\")\n\n    ft1 = relay.FuncType([a, relay.TupleType([b, c])], relay.TupleType([a, b, c]), [a, b, c])\n    ft2 = relay.FuncType([a, relay.TupleType([a, a])], relay.TupleType([a, a, a]), [a])\n    unified = solver.Unify(ft1, ft2)\n    assert unified == ft2\n\n\ndef test_unify_quantified_funcs_var_order():\n    solver = make_solver()\n    a, b, c = relay.TypeVar(\"a\"), relay.TypeVar(\"b\"), relay.TypeVar(\"c\")\n\n    ft1 = relay.FuncType([a, relay.TupleType([b, c])], relay.TupleType([a, b, c]), [a, b, c])\n    ft2 = relay.FuncType([a, relay.TupleType([a, c])], relay.TupleType([a, a, c]), [a, c])\n    # unified = solver.Unify(ft1, ft2) # crashes here but it shouldn't\n    # assert unified == ft2\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_incompatible_tuple_unification():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n    t2 = relay.ty.IncompleteType()\n\n    tensor1 = relay.ty.TensorType((1, 2, 3), \"float32\")\n    tensor2 = relay.ty.TensorType((2, 3), \"float32\")\n    tensor3 = relay.ty.TensorType((3,), \"float32\")\n\n    tup1 = relay.ty.TupleType([relay.ty.TupleType([t1, t1]), t2])\n    tup2 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor3])\n    solver.Unify(tup1, tup2)\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_bad_recursive_unification():\n    solver = make_solver()\n    t1 = relay.ty.IncompleteType()\n    solver.Unify(t1, relay.ty.TupleType([t1, t1]))\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_unify_invalid_global_typevars():\n    solver = make_solver()\n    gtv1 = relay.GlobalTypeVar(\"gtv1\")\n    gtv2 = relay.GlobalTypeVar(\"gtv2\")\n    solver.Unify(gtv1, gtv2)\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_incompatible_typecall_var_unification():\n    solver = make_solver()\n    gtv1 = relay.GlobalTypeVar(\"gtv1\")\n    gtv2 = relay.GlobalTypeVar(\"gtv2\")\n\n    t1 = relay.IncompleteType()\n    t2 = relay.IncompleteType()\n\n    tc1 = relay.TypeCall(gtv1, [t1])\n    tc2 = relay.TypeCall(gtv2, [t2])\n    solver.Unify(tc1, tc2)\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_incompatible_typecall_args_unification():\n    solver = make_solver()\n    gtv = relay.GlobalTypeVar(\"gtv1\")\n    t1 = relay.IncompleteType()\n    t2 = relay.IncompleteType()\n\n    tensor1 = relay.TensorType((1, 2, 3), \"float32\")\n    tensor2 = relay.TensorType((2, 3), \"float32\")\n    tensor3 = relay.TensorType((3,), \"float32\")\n\n    tc1 = relay.TypeCall(gtv, [relay.TupleType([t1, t1]), t2])\n    tc2 = relay.TypeCall(gtv, [relay.TupleType([tensor1, tensor2]), tensor3])\n    solver.Unify(tc1, tc2)\n\n\n@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)\ndef test_incompatible_quantified_func_unification():\n    solver = make_solver()\n    a, b, c = relay.TypeVar(\"a\"), relay.TypeVar(\"b\"), relay.TypeVar(\"c\")\n\n    ft1 = relay.FuncType([a, b], c, [a, b, c])\n    ft2 = relay.FuncType([b, c], relay.TupleType([a]), [a, b, c])\n    solver.Unify(ft1, ft2)\n\n\ndef test_integer_compatibility_in_layout_transform():\n    x = relay.var(\"data\", shape=(2, 3, 48, 48), dtype=\"float32\")\n    conv_out = relay.nn.conv2d(\n        x,\n        relay.var(\"weight\", shape=(1, 3, 1, 1), dtype=\"float32\"),\n        strides=[47, 47],\n        channels=1,\n        kernel_size=[1, 1],\n    )\n    bias_out = relay.nn.bias_add(conv_out, relay.var(\"bias\"))\n    broadcast_out = relay.op.broadcast_to(bias_out, relay.const([2, 1, 2, 2], dtype=\"int64\"))\n    y = relay.add(bias_out, broadcast_out)\n\n    mod, _ = testing.create_workload(y)\n    with tvm.transform.PassContext(opt_level=3):\n        with tvm.target.Target(\"llvm\"):\n            mod = relay.transform.CanonicalizeOps()(mod)\n            mod = relay.transform.AlterOpLayout()(mod)\n\n\nif __name__ == \"__main__\":\n    test_bcast()\n    test_backward_solving()\n    test_unify_tuple()\n    test_unify_typecall()\n    test_unify_functype()\n    test_recursive_unify()\n    test_unify_vars_under_tuples()\n    test_recursive_backward_solving()\n    test_backward_solving_after_child_update()\n    test_unify_quantified_funcs()\n    test_unify_quantified_func_and_concrete()\n    test_unify_quantified_funcs_nesting()\n    test_unify_quantified_funcs_var_order()\n    test_incompatible_tuple_unification()\n    test_bad_recursive_unification()\n    test_incompatible_typecall_var_unification()\n    test_incompatible_typecall_args_unification()\n    test_incompatible_quantified_func_unification()\n    test_integer_compatibility_in_layout_transform()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_typecall.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.relay import transform\n\n\ndef test_dup_type():\n    a = relay.TypeVar(\"a\")\n    av = relay.Var(\"av\", a)\n    make_id = relay.Function([av], relay.Tuple([av, av]), None, [a])\n    t = relay.scalar_type(\"float32\")\n    b = relay.Var(\"b\", t)\n    mod = tvm.IRModule.from_expr(make_id(b))\n    mod = transform.InferType()(mod)\n    inferred = mod[\"main\"].body\n    assert inferred.checked_type == relay.TupleType([t, t])\n\n\ndef test_id_type():\n    mod = tvm.IRModule()\n    id_type = relay.GlobalTypeVar(\"id\")\n    a = relay.TypeVar(\"a\")\n    mod[id_type] = relay.TypeData(id_type, [a], [])\n\n    b = relay.TypeVar(\"b\")\n    make_id = relay.Var(\"make_id\", relay.FuncType([b], id_type(b), [b]))\n    t = relay.scalar_type(\"float32\")\n    b = relay.Var(\"b\", t)\n    mod[\"main\"] = relay.Function([make_id, b], make_id(b))\n    mod = transform.InferType()(mod)\n    assert mod[\"main\"].body.checked_type == id_type(t)\n\n\nif __name__ == \"__main__\":\n    test_dup_type()\n    test_id_type()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_used_memory_annotator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\n\"\"\"\nTesting for the pass that annotates used memory for each primitive\nRelay function.\n\"\"\"\n\nimport pytest\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay.expr_functor import ExprVisitor\n\n\ndef AnnotateUsedMemory():\n    return relay.transform._ffi_api.AnnotateUsedMemory()\n\n\nclass CheckUsedMemoryAnnotation(ExprVisitor):\n    \"\"\"\n    Check that the annotations on each function in the graph match\n    what is expected.\n    \"\"\"\n\n    def __init__(self, expected_annotations, expected_io_annotation):\n        self.expected_annotations = expected_annotations\n        self.expected_io_annotation = expected_io_annotation\n        super().__init__()\n\n    def visit_function(self, fn):\n        if \"Primitive\" in fn.attrs:\n            assert (\n                \"used_memory\" in fn.attrs\n            ), \"Primitive function does not have used_memory annotation.\"\n\n            assert len(self.expected_annotations) > 0, \"Not all expected annotations were compared\"\n\n            expected_mem = self.expected_annotations.pop(0)\n            actual_mem = [int(x) for x in fn.attrs[\"used_memory\"]]\n            assert expected_mem == actual_mem, (\n                f\"Expected used memory annotation {expected_mem} \"\n                f\"did not match actual annotation {actual_mem}\"\n            )\n        super().visit_function(fn)\n\n    def __call__(self, fn):\n        assert (\n            fn.attrs[\"io_used_memory\"] == self.expected_io_annotation\n        ), \"Expected IO annotation did not match.\"\n        self.visit(fn.body)\n\n\ndef _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation):\n    mod = relay.transform.InferType()(mod)\n    mod = relay.transform.ToANormalForm()(mod)\n    mod = relay.transform.InferType()(mod)\n    mod = AnnotateUsedMemory()(mod)\n\n    CheckUsedMemoryAnnotation(expected_annotations, expected_io_annotation)(mod[\"main\"])\n\n\ndef _create_primitive_function(expr):\n    func = relay.Function(relay.analysis.free_vars(expr), expr)\n    func = func.with_attr(\"Primitive\", 1)\n    return func\n\n\ndef test_simple():\n    \"\"\"\n    Test simple graph with one primitive function.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x)\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call = relay.Call(get_inner_func(), [ifm])\n    mod = tvm.IRModule.from_expr(call)\n\n    expected_annotations = [\n        [2 * (1 * 2 * 2 * 4)],\n    ]\n    expected_io_annotation = 2 * (1 * 2 * 2 * 4)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_multiple_functions():\n    \"\"\"\n    Test a graph with multiple primitive functions.\n    \"\"\"\n\n    def get_inner_func(ifm_shape):\n        x = relay.var(\"x\", shape=ifm_shape, dtype=\"int8\")\n        x = relay.nn.max_pool2d(x, pool_size=(2, 2), layout=\"NHWC\")\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 8, 8, 2), dtype=\"int8\")\n    x = get_inner_func((1, 8, 8, 2))\n    x = relay.Call(x, [ifm])\n    y = get_inner_func((1, 7, 7, 2))\n    y = relay.Call(y, [x])\n    z = get_inner_func((1, 6, 6, 2))\n    z = relay.Call(z, [y])\n    mod = tvm.IRModule.from_expr(z)\n\n    expected_annotations = [\n        [(1 * 8 * 8 * 2) + (1 * 7 * 7 * 2)],\n        [(1 * 7 * 7 * 2) + (1 * 6 * 6 * 2)],\n        [(1 * 6 * 6 * 2) + (1 * 5 * 5 * 2)],\n    ]\n    expected_io_annotation = (1 * 8 * 8 * 2) + (1 * 5 * 5 * 2)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_mixed_data_types():\n    \"\"\"\n    Test a graph with a primitive function that has mixed datatypes.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 2), dtype=\"int16\")\n        x = relay.cast(x, dtype=\"uint32\")\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 2), dtype=\"int16\")\n    x = get_inner_func()\n    x = relay.Call(x, [ifm])\n    mod = tvm.IRModule.from_expr(x)\n\n    expected_annotations = [\n        [(1 * 2 * 2 * 2) * 2 + (1 * 2 * 2 * 2) * 4],\n    ]\n    expected_io_annotation = (1 * 2 * 2 * 2) * 2 + (1 * 2 * 2 * 2) * 4\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_parallel_function_call():\n    \"\"\"\n    Test a graph when the results of two functions are concatenated\n    into a single result. The second function will also have the result\n    of the first function alive so will be annotated with a larger\n    \"used memory\" value.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.reshape(x, newshape=(1, 4, 30))\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 4, 5, 6), dtype=\"int8\")\n    x = relay.Call(get_inner_func(), [ifm])\n    y = relay.Call(get_inner_func(), [ifm])\n    z = relay.concatenate([x, y], axis=0)\n    mod = tvm.IRModule.from_expr(z)\n\n    expected_annotations = [\n        [(1 * 4 * 5 * 6) + (1 * 4 * 30)],\n        # the output tensor from the previous function is also alive\n        [(1 * 4 * 5 * 6) + (1 * 4 * 30) + (1 * 4 * 30)],\n    ]\n    expected_io_annotation = (1 * 4 * 5 * 6) + (1 * 4 * 60)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_many_different_parallel_calls():\n    \"\"\"\n    Test a graph that calls many different functions in parallel.\n\n                    input\n            /         |         \\\n    prim_func_1  prim_func_2  prim_func_3\n           \\         |         /\n                 prim_func_4\n    \"\"\"\n\n    def get_inner_func_1():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.tanh(x)\n        x = _create_primitive_function(x)\n        return x\n\n    def get_inner_func_2():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x, pool_size=(1, 1), layout=\"NHWC\")\n        x = _create_primitive_function(x)\n        return x\n\n    def get_inner_func_3():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.abs(x)\n        x = relay.nn.relu(x)\n        x = relay.exp(x)\n        x = _create_primitive_function(x)\n        return x\n\n    def get_inner_func_4():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        y = relay.var(\"y\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        z = relay.var(\"z\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        out = relay.concatenate([x, y, z], axis=3)\n        out = _create_primitive_function(out)\n        return out\n\n    ifm = relay.var(\"input\", shape=(1, 4, 5, 6), dtype=\"int8\")\n    x = relay.Call(get_inner_func_1(), [ifm])\n    y = relay.Call(get_inner_func_2(), [ifm])\n    z = relay.Call(get_inner_func_3(), [ifm])\n    a = relay.Call(get_inner_func_4(), [x, y, z])\n    mod = tvm.IRModule.from_expr(a)\n\n    expected_annotations = [\n        [(1 * 4 * 5 * 6) + (1 * 4 * 5 * 6)],\n        # output from prim_func_1 is also still alive\n        [(1 * 4 * 5 * 6) + (1 * 4 * 5 * 6) + (1 * 4 * 5 * 6)],\n        # outputs from prim_func_1 and prim_func_2 are also still alive\n        [(1 * 4 * 5 * 6) + (1 * 4 * 5 * 6) + (1 * 4 * 5 * 6) + (1 * 4 * 5 * 6)],\n        [(1 * 4 * 5 * 6) + (1 * 4 * 5 * 6) + (1 * 4 * 5 * 6) + (1 * 4 * 5 * 18)],\n    ]\n    expected_io_annotation = (1 * 4 * 5 * 6) + (1 * 4 * 5 * 18)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_nested_branches():\n    \"\"\"\n    Tests a graph with branches that also branch.\n\n             input\n            /     \\\n          /        \\\n    prim_func_1  prim_func_2\n                   /     \\\n                  /       \\\n            prim_func_3   prim_func_4\n    \"\"\"\n\n    def get_generic_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.relu(x)\n        return _create_primitive_function(x)\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    a = relay.Call(get_generic_inner_func(), [ifm])\n    b = relay.Call(get_generic_inner_func(), [ifm])\n    c = relay.Call(get_generic_inner_func(), [b])\n    d = relay.Call(get_generic_inner_func(), [b])\n    out = relay.concatenate([a, c, d], axis=3)\n    mod = tvm.IRModule.from_expr(out)\n\n    expected_annotations = [\n        [(1 * 2 * 2 * 4) + (1 * 2 * 2 * 4)],\n        # output from prim_func_1 is also still alive\n        [(1 * 2 * 2 * 4) + (1 * 2 * 2 * 4) + (1 * 2 * 2 * 4)],\n        # output from prim_func_1 is also still alive\n        [(1 * 2 * 2 * 4) + (1 * 2 * 2 * 4) + (1 * 2 * 2 * 4)],\n        # outputs from prim_func_1 and prim_func_3 are also still alive\n        [(1 * 2 * 2 * 4) + (1 * 2 * 2 * 4) + (1 * 2 * 2 * 4) + (1 * 2 * 2 * 4)],\n    ]\n    expected_io_annotation = (1 * 2 * 2 * 4) + (1 * 2 * 2 * 12)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_composite_inner_function():\n    \"\"\"\n    Tests the typical BYOC use case where a primitive function\n    contains a composite function.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x, pool_size=(2, 2), layout=\"NHWC\")\n        x = relay.Function(relay.analysis.free_vars(x), x)\n        x = x.with_attr(\"Composite\", \"my_composite_func\")\n\n        y = relay.var(\"y\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        z = relay.Call(x, [y])\n        return _create_primitive_function(z)\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    x = relay.Call(get_inner_func(), [ifm])\n    mod = tvm.IRModule.from_expr(x)\n\n    expected_annotations = [\n        [(1 * 2 * 2 * 4) + (1 * 1 * 1 * 4)],\n    ]\n    expected_io_annotation = (1 * 2 * 2 * 4) + (1 * 1 * 1 * 4)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_multiple_calls_to_same_function():\n    \"\"\"\n    Tests the case when there are multiple calls to the same function.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x)\n        x = _create_primitive_function(x)\n        return x\n\n    inner_func = get_inner_func()\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call1 = relay.Call(inner_func, [ifm])\n    call2 = relay.Call(inner_func, [call1])\n    mod = tvm.IRModule.from_expr(call2)\n\n    expected_annotations = [[2 * (1 * 2 * 2 * 4), 2 * (1 * 2 * 2 * 4)]]\n    expected_io_annotation = 2 * (1 * 2 * 2 * 4)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_parallel_calls_to_same_function():\n    \"\"\"\n    Test parallel calls to the same function.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x)\n        x = _create_primitive_function(x)\n        return x\n\n    inner_func = get_inner_func()\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call1 = relay.Call(inner_func, [ifm])\n    call2 = relay.Call(inner_func, [ifm])\n    concat = relay.concatenate([call1, call2], axis=0)\n    mod = tvm.IRModule.from_expr(concat)\n\n    expected_annotations = [[2 * (1 * 2 * 2 * 4), 3 * (1 * 2 * 2 * 4)]]\n    expected_io_annotation = 3 * (1 * 2 * 2 * 4)\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_parallel_calls_with_non_ifm_input():\n    \"\"\"\n    Test a graph that calls many different functions in parallel where\n    the input is not the input to the function.\n\n                    y = f(x)\n            /         |         \\\n       z0 = g0(y)    ...      zi = gi(y)\n           \\         |         /\n                  concat\n    \"\"\"\n\n    def get_inner_func_1():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.tanh(x)\n        x = _create_primitive_function(x)\n        return x\n\n    def get_inner_func_2():\n        x = relay.var(\"x\", shape=(1, 4, 5, 6), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x, pool_size=(2, 2))\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 4, 5, 6), dtype=\"int8\")\n    y = relay.Call(get_inner_func_1(), [ifm])\n    g = get_inner_func_2()\n\n    no_calls = 20\n    z = [relay.Call(g, [y]) for _ in range(0, no_calls)]\n    out = relay.concatenate(z, axis=3)\n    mod = tvm.IRModule.from_expr(out)\n\n    expected_annotations = [\n        [(1 * 4 * 5 * 6) + (1 * 4 * 5 * 6)],\n        [(1 * 4 * 5 * 6) + (1 * 4 * 4 * 5) * i for i in range(1, no_calls + 1)],\n    ]\n    expected_io_annotation = (1 * 4 * 5 * 6) + (1 * 4 * 4 * (5 * no_calls))\n    _check_used_memory_annotations(mod, expected_annotations, expected_io_annotation)\n\n\ndef test_dynamic_io_tensor_not_supported():\n    \"\"\"\n    Test to check dynamic IO tensor error.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x)\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, relay.Any()), dtype=\"int8\")\n    call = relay.Call(get_inner_func(), [ifm])\n    mod = tvm.IRModule.from_expr(call)\n\n    err_rgx = r\"AnnotateUsedMemory does not support dynamic shapes\"\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        _check_used_memory_annotations(mod, [], [])\n\n\ndef test_dynamic_callsite_tensor_not_supported():\n    \"\"\"\n    Test to check dynamic callsite tensor error.\n    \"\"\"\n\n    def get_inner_func():\n        x = relay.var(\"x\", shape=(relay.Any(), 2, 2, 4), dtype=\"int8\")\n        x = relay.nn.max_pool2d(x)\n        x = _create_primitive_function(x)\n        return x\n\n    ifm = relay.var(\"input\", shape=(1, 2, 2, 4), dtype=\"int8\")\n    call = relay.Call(get_inner_func(), [ifm])\n    mod = tvm.IRModule.from_expr(call)\n\n    err_rgx = r\"AnnotateUsedMemory does not support dynamic shapes\"\n    with pytest.raises(tvm.TVMError, match=err_rgx):\n        _check_used_memory_annotations(mod, [], [])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_vm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nimport time\nfrom unittest.mock import patch\n\nimport tvm\nfrom tvm import runtime\nfrom tvm import relay, IRModule\nfrom tvm.relay.backend import vm\nfrom tvm.relay.scope_builder import ScopeBuilder\nfrom tvm.relay.prelude import Prelude\nfrom tvm.relay.loops import while_loop\nfrom tvm.relay import testing\nfrom tvm.contrib import utils\nfrom tvm import rpc\nimport tvm.testing\nfrom tvm.relay.transform import InferType\nfrom tvm.relay.testing import mlp\nfrom tvm.relay.dataflow_pattern import wildcard, is_op\nfrom tvm.relay.backend.vm import VMCompiler\n\n\ndef check_result(target, dev, args, expected_result, mod):\n    \"\"\"\n    Check that evaluating `expr` applied to the arguments produces\n    `result` on Relay VM.\n\n    Parameters\n    ----------\n    args: list of Expr\n        The arguments to supply the expr.\n\n    expected_result:\n        The expected result of running the expression.\n    \"\"\"\n    rts_result = relay.create_executor(\"vm\", device=dev, target=target, mod=mod).evaluate()(*args)\n    tvm.testing.assert_allclose(expected_result, rts_result.numpy())\n\n\ndef veval(f, *args, device=tvm.cpu(), target=\"llvm\"):\n    if isinstance(f, relay.Expr):\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n    else:\n        assert isinstance(f, tvm.IRModule), \"expected expression or module\"\n        mod = f\n    exe = relay.vm.compile(mod, target)\n    vm = runtime.vm.VirtualMachine(exe, device)\n    return vm.invoke(\"main\", *args)\n\n\ndef vmobj_to_list(o):\n    if isinstance(o, tvm.nd.NDArray):\n        return [o.numpy().tolist()]\n    elif isinstance(o, tvm.runtime.container.ADT):\n        result = []\n        for f in o:\n            result.extend(vmobj_to_list(f))\n        return result\n    else:\n        raise RuntimeError(\"Unknown object type: %s\" % type(o))\n\n\ndef test_split(target, dev):\n    x = relay.var(\"x\", shape=(12,))\n    y = relay.split(x, 3, axis=0).astuple()\n    f = relay.Function([x], y)\n\n    x_data = np.random.rand(\n        12,\n    ).astype(\"float32\")\n    ref_res = np.split(x_data, 3, axis=0)\n    res = veval(f, x_data, device=dev, target=target)\n    for i in range(3):\n        tvm.testing.assert_allclose(res[i].numpy(), ref_res[i])\n\n\ndef test_split_no_fuse(target, dev):\n    x = relay.var(\"x\", shape=(12,))\n    y = relay.split(x, 3, axis=0).astuple()\n    z = relay.concatenate([relay.TupleGetItem(y, 0)], axis=0)\n    z = relay.annotation.stop_fusion(z)\n    f = relay.Function([x], z)\n    x_data = np.random.rand(\n        12,\n    ).astype(\"float32\")\n\n    res = veval(f, x_data, device=dev, target=target)\n    tvm.testing.assert_allclose(res.numpy(), np.split(x_data, 3, axis=0)[0])\n\n\ndef test_id(target, dev):\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float64\")\n    f = relay.Function([x], x)\n    x_data = np.random.rand(10, 10).astype(\"float64\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [x_data], x_data, mod)\n\n\ndef test_op(target, dev):\n    x = relay.var(\"x\", shape=(10, 10))\n    f = relay.Function([x], x + x)\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [x_data], 2 * x_data, mod)\n\n\ndef any(x):\n    x = relay.op.nn.batch_flatten(x)\n    return relay.op.min(x, axis=[0, 1])\n\n\n@tvm.testing.known_failing_targets(\"vulkan\")\ndef test_cond(target, dev):\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(10, 10))\n    # f = relay.Function([x, y], relay.op.equal(x, y))\n    f = relay.Function([x, y], any(relay.op.equal(x, y)))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(10, 10).astype(\"float32\")\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    # same\n    check_result(target, dev, [x_data, x_data], True, mod)\n\n    # diff\n    check_result(target, dev, [x_data, y_data], False, mod)\n\n\n@tvm.testing.known_failing_targets(\"vulkan\")\ndef test_simple_if(target, dev):\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(10, 10))\n    f = relay.Function([x, y], relay.If(any(relay.op.equal(x, y)), x, y))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(10, 10).astype(\"float32\")\n\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    # same\n    check_result(target, dev, [x_data, x_data], x_data, mod)\n\n    # diff\n    check_result(target, dev, [x_data, y_data], y_data, mod)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_multiple_ifs(target, dev):\n    mod = tvm.IRModule({})\n    b = relay.var(\"b\")\n    v0 = relay.var(\"v0\")\n    v1 = relay.var(\"v1\")\n    v2 = relay.var(\"v2\")\n    v3 = relay.var(\"v3\")\n    out = relay.Tuple([v2, v3])\n    out = relay.Let(v3, relay.If(b, v1, v0), out)\n    out = relay.Let(v2, relay.If(b, v0, v1), out)\n    out = relay.Let(v1, relay.Tuple([relay.const(1)]), out)\n    out = relay.Let(v0, relay.Tuple([relay.const(0)]), out)\n    fn = relay.Function([b], out)\n    mod[\"main\"] = fn\n    func = relay.create_executor(device=dev, mod=mod, kind=\"vm\").evaluate()\n    res = vmobj_to_list(func(False))\n    assert res == [1, 0]\n\n\ndef test_unused_function(target, dev):\n    cond = relay.const(True)\n    mod = tvm.IRModule()\n    then_name = relay.GlobalVar(\"times_2\")\n    # define unused function\n    else_name = relay.GlobalVar(\"times_3\")\n    t1 = relay.TensorType((2, 2), dtype=\"float32\")\n    x1 = relay.var(\"x1\", t1, dtype=\"float32\")\n    x2 = relay.var(\"x2\", t1, dtype=\"float32\")\n    f2 = relay.multiply(x1, relay.const(2.0))\n    f3 = relay.multiply(x2, relay.const(3.0))\n    mod[then_name] = relay.Function([x1], f2)\n    mod[else_name] = relay.Function([x2], f3)\n    mod = InferType()(mod)\n    x3 = relay.var(\"x3\", t1, dtype=\"float32\")\n    # put unused function in else branch\n    f = relay.If(cond, then_name(x3), else_name(x3))\n    mod[\"main\"] = relay.Function([x3], f)\n    x_data = np.random.rand(2, 2).astype(\"float32\")\n    y_data = x_data * 2\n\n    check_result(target, dev, [x_data], y_data, mod)\n\n\ndef test_simple_call(target, dev):\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    sb.ret(i)\n    func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n    mod[sum_up] = func\n    i_data = np.array(0, dtype=\"int32\")\n    iarg = relay.var(\"iarg\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n    check_result(target, dev, [i_data], i_data, mod)\n\n\ndef test_count_loop(target, dev):\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, dtype=\"int32\"))):\n        sb.ret(i)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, dtype=\"int32\"))\n        rec_call = relay.Call(sum_up, [one_less])\n        sb.ret(relay.add(rec_call, i))\n    func = relay.Function([i], sb.get(), ret_type=relay.TensorType([], \"int32\"))\n    mod[sum_up] = func\n    i_data = np.array(0, dtype=\"int32\")\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg], sum_up(iarg))\n    result = veval(mod, i_data, device=dev, target=target)\n    tvm.testing.assert_allclose(result.numpy(), i_data)\n    check_result(target, dev, [i_data], i_data, mod)\n\n\ndef test_sum_loop(target, dev):\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    accum = relay.var(\"accum\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, \"int32\"))):\n        sb.ret(accum)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, \"int32\"))\n        new_accum = relay.add(accum, i)\n        sb.ret(relay.Call(sum_up, [one_less, new_accum]))\n    func = relay.Function([i, accum], sb.get())\n    mod[sum_up] = func\n    mod = relay.transform.InferType()(mod)\n    loop_bound = 0\n    i_data = np.array(loop_bound, dtype=\"int32\")\n    accum_data = np.array(0, dtype=\"int32\")\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    aarg = relay.var(\"accum\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg, aarg], sum_up(iarg, aarg))\n    check_result(target, dev, [i_data, accum_data], sum(range(1, loop_bound + 1)), mod)\n\n\ndef test_tuple_fst(target, dev):\n    ttype = relay.TupleType([relay.TensorType((1,)), relay.TensorType((10,))])\n    tup = relay.var(\"tup\", type_annotation=ttype)\n    f = relay.Function([tup], relay.TupleGetItem(tup, 0))\n    i_data = np.random.rand(41).astype(\"float32\")\n    j_data = np.random.rand(10).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [(i_data, j_data)], i_data, mod)\n\n\ndef test_tuple_second(target, dev):\n    ttype = relay.TupleType([relay.TensorType((1,)), relay.TensorType((10,))])\n    tup = relay.var(\"tup\", type_annotation=ttype)\n    f = relay.Function([tup], relay.TupleGetItem(tup, 1))\n    i_data = np.random.rand(41).astype(\"float32\")\n    j_data = np.random.rand(10).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [(i_data, j_data)], j_data, mod)\n\n\ndef test_list_constructor(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    l, cons, nil = mod.get_type(\"List\")\n\n    one2 = cons(relay.const(1), nil())\n    one3 = cons(relay.const(2), one2)\n    one4 = cons(relay.const(3), one3)\n    f = relay.Function([], one4)\n\n    mod[\"main\"] = f\n\n    result = veval(mod, device=dev, target=target)\n    assert len(result) == 2\n    assert len(result[1]) == 2\n\n    obj = vmobj_to_list(result)\n    tvm.testing.assert_allclose(obj, np.array([3, 2, 1]))\n\n\ndef test_let_tensor(target, dev):\n    sb = relay.ScopeBuilder()\n    shape = (1,)\n    x = relay.var(\"x\", shape=shape, dtype=\"float32\")\n    x1 = relay.var(\"x1\", shape=shape, dtype=\"float32\")\n\n    x1 = sb.let(x1, x)\n    xplusone = x1 + relay.const(42.0, \"float32\")\n    sb.ret(xplusone)\n    body = sb.get()\n\n    f = relay.Function([x], body)\n\n    x_data = np.random.rand(*shape).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [x_data], x_data + 42.0, mod)\n\n\ndef test_let_scalar(target, dev):\n    sb = relay.ScopeBuilder()\n\n    x = relay.var(\"x\", \"float32\")\n    x1 = sb.let(\"x1\", x)\n    xplusone = x1 + relay.const(42.0, \"float32\")\n    sb.ret(xplusone)\n    body = sb.get()\n\n    f = relay.Function([x], body)\n\n    x_data = np.array(np.random.rand()).astype(\"float32\")\n    mod = tvm.IRModule()\n    mod[\"main\"] = f\n    check_result(target, dev, [x_data], x_data + 42.0, mod)\n\n\ndef test_compose(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    compose = p.compose\n\n    # add_one = fun x -> x + 1\n    sb = relay.ScopeBuilder()\n    x = relay.var(\"x\", \"float32\")\n    x1 = sb.let(\"x1\", x)\n    xplusone = x1 + relay.const(1.0, \"float32\")\n    sb.ret(xplusone)\n    body = sb.get()\n    add_one = relay.GlobalVar(\"add_one\")\n    add_one_func = relay.Function([x], body)\n\n    # add_two = compose(add_one, add_one)\n    sb = relay.ScopeBuilder()\n    y = relay.var(\"y\", \"float32\")\n    add_two_func = sb.let(\"add_two\", compose(add_one_func, add_one_func))\n    add_two_res = add_two_func(y)\n    sb.ret(add_two_res)\n    add_two_body = sb.get()\n\n    mod[add_one] = add_one_func\n\n    f = relay.Function([y], add_two_body)\n    mod[\"main\"] = f\n\n    x_data = np.array(np.random.rand()).astype(\"float32\")\n    result = veval(mod, [x_data], device=dev, target=target)\n    tvm.testing.assert_allclose(result.numpy(), x_data + 2.0)\n\n\ndef test_list_hd(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    l, cons, nil = mod.get_type(\"List\")\n    hd = mod.get_global_var(\"hd\")\n\n    one2 = cons(relay.const(1), nil())\n    one3 = cons(relay.const(2), one2)\n    one4 = cons(relay.const(3), one3)\n    three = hd(one4)\n    f = relay.Function([], three)\n\n    mod[\"main\"] = f\n\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(result.numpy(), 3)\n\n\ndef test_list_tl_empty_list(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    l, cons, nil = mod.get_type(\"List\")\n    tl = mod.get_global_var(\"tl\")\n\n    f = relay.Function([], tl(nil()))\n\n    mod[\"main\"] = f\n\n    with pytest.raises(tvm.error.TVMError):\n        result = veval(mod, device=dev, target=target)\n\n\ndef test_list_tl(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    l, cons, nil = mod.get_type(\"List\")\n    tl = mod.get_global_var(\"tl\")\n\n    one2 = cons(relay.const(1), nil())\n    one3 = cons(relay.const(2), one2)\n    one4 = cons(relay.const(3), one3)\n\n    f = relay.Function([], tl(one4))\n\n    mod[\"main\"] = f\n\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array([2, 1]))\n\n\ndef test_list_nth(target, dev):\n    expected = list(range(10))\n\n    for i in range(len(expected)):\n        mod = tvm.IRModule()\n        p = Prelude(mod)\n\n        _, cons, nil = mod.get_type(\"List\")\n        nth = mod.get_global_var(\"nth\")\n\n        l = nil()\n        for i in reversed(expected):\n            l = cons(relay.const(i), l)\n\n        f = relay.Function([], nth(l, relay.const(i)))\n        mod[\"main\"] = f\n        result = veval(mod, device=dev, target=target)\n        tvm.testing.assert_allclose(result.numpy(), expected[i])\n\n\ndef test_list_update(target, dev):\n    expected = list(range(10))\n\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    update = mod.get_global_var(\"update\")\n\n    l = nil()\n    # create zero initialized list\n    for i in range(len(expected)):\n        l = cons(relay.const(0), l)\n\n    # set value\n    for i, v in enumerate(expected):\n        l = update(l, relay.const(i), relay.const(v))\n\n    f = relay.Function([], l)\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array(expected))\n\n\ndef test_list_length(target, dev):\n    expected = list(range(10))\n\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    length = mod.get_global_var(\"length\")\n\n    l = nil()\n    # create zero initialized list\n    for _ in range(len(expected)):\n        l = cons(relay.const(0), l)\n\n    l = length(l)\n\n    f = relay.Function([], l)\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(result.numpy(), 10)\n\n\ndef test_list_map(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    x = relay.var(\"x\", \"int32\")\n    add_one_func = relay.Function([x], relay.const(1) + x)\n\n    _, cons, nil = mod.get_type(\"List\")\n    map = mod.get_global_var(\"map\")\n\n    l = cons(relay.const(2), cons(relay.const(1), nil()))\n\n    f = relay.Function([], map(add_one_func, l))\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array([3, 2]))\n\n\ndef test_list_foldl(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    foldl = mod.get_global_var(\"foldl\")\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    rev_dup_func = relay.Function([y, x], cons(x, cons(x, y)))\n\n    l = cons(relay.const(1), cons(relay.const(2), cons(relay.const(3), nil())))\n    f = relay.Function([], foldl(rev_dup_func, nil(), l))\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array([3, 3, 2, 2, 1, 1]))\n\n\ndef test_list_foldr(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    foldr = mod.get_global_var(\"foldr\")\n\n    x = relay.var(\"x\")\n    y = relay.var(\"y\")\n    identity_func = relay.Function([x, y], cons(x, y))\n\n    l = cons(relay.const(1), cons(relay.const(2), cons(relay.const(3), nil())))\n    f = relay.Function([], foldr(identity_func, nil(), l))\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array([1, 2, 3]))\n\n\ndef test_list_sum(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    sum = mod.get_global_var(\"sum\")\n\n    l = cons(relay.const(1), cons(relay.const(2), cons(relay.const(3), nil())))\n    f = relay.Function([], sum(l))\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(result.numpy(), 6)\n\n\ndef test_list_filter(target, dev):\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    _, cons, nil = mod.get_type(\"List\")\n    filter = mod.get_global_var(\"filter\")\n\n    x = relay.var(\"x\", \"int32\")\n    greater_than_one = relay.Function([x], x > relay.const(1))\n    l = cons(\n        relay.const(1),\n        cons(\n            relay.const(3), cons(relay.const(1), cons(relay.const(5), cons(relay.const(1), nil())))\n        ),\n    )\n    f = relay.Function([], filter(greater_than_one, l))\n    mod[\"main\"] = f\n    result = veval(mod, device=dev, target=target)\n    tvm.testing.assert_allclose(vmobj_to_list(result), np.array([3, 5]))\n\n\ndef test_closure(target, dev):\n    x = relay.var(\"x\", shape=())\n    y = relay.var(\"y\", shape=())\n    f = relay.Function([x], x + y)\n    ff = relay.Function([y], f)\n    clo = ff(relay.const(1.0))\n    main = clo(relay.const(2.0))\n    res = veval(main, device=dev, target=target)\n    tvm.testing.assert_allclose(res.numpy(), 3.0)\n\n\ndef test_add_op_scalar(target, dev):\n    \"\"\"\n    test_add_op_scalar:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=())  # Default to float32\n    y = relay.var(\"y\", shape=())  # Default to float32\n    func = relay.Function([x, y], relay.op.add(x, y))\n    x_y_data = [\n        (np.array(10.0, dtype=\"float32\"), np.array(1.0, dtype=\"float32\")),\n        (np.float32(10.0), np.float32(1.0)),\n        (10.0, 1.0),\n    ]\n    for (x_data, y_data) in x_y_data:\n        mod[\"main\"] = func\n        check_result(target, dev, [x_data, y_data], x_data + y_data, mod)\n\n\ndef test_add_op_scalar_float16(target, dev):\n    \"\"\"\n    test_add_op_scalar_float16:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=(), dtype=\"float16\")  # Default to float16\n    y = relay.var(\"y\", shape=(), dtype=\"float16\")  # Default to float16\n    func = relay.Function([x, y], relay.op.add(x, y))\n    x_y_data = [\n        (np.array(10.0, dtype=\"float16\"), np.array(1.0, dtype=\"float16\")),\n        (np.float16(10.0), np.float16(1.0)),\n    ]\n    for (x_data, y_data) in x_y_data:\n        mod[\"main\"] = func\n        check_result(target, dev, [x_data, y_data], x_data + y_data, mod)\n\n\ndef test_add_op_scalar_int(target, dev):\n    \"\"\"\n    test_add_op_scalar_int:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=(), dtype=\"int32\")\n    y = relay.var(\"y\", shape=(), dtype=\"int32\")\n    func = relay.Function([x, y], relay.op.add(x, y))\n    x_y_data = [\n        (np.array(10.0, dtype=\"int32\"), np.array(1.0, dtype=\"int32\")),\n        (np.int32(10), np.int32(1)),\n        (10, 1),\n    ]\n    for (x_data, y_data) in x_y_data:\n        mod[\"main\"] = func\n        check_result(target, dev, [x_data, y_data], x_data + y_data, mod)\n\n\ndef test_add_op_tensor(target, dev):\n    \"\"\"\n    test_add_op_tensor:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(10, 5))\n    func = relay.Function([x, y], relay.op.add(x, y))\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(10, 5).astype(\"float32\")\n    mod[\"main\"] = func\n    check_result(target, dev, [x_data, y_data], x_data + y_data, mod)\n\n\ndef test_add_op_broadcast(target, dev):\n    \"\"\"\n    test_add_op_broadcast:\n        fn (x, y) {\n            return x + y;\n        }\n    \"\"\"\n    mod = tvm.IRModule()\n    x = relay.var(\"x\", shape=(10, 5))\n    y = relay.var(\"y\", shape=(1, 5))\n    func = relay.Function([x, y], relay.op.add(x, y))\n    x_data = np.random.rand(10, 5).astype(\"float32\")\n    y_data = np.random.rand(1, 5).astype(\"float32\")\n    mod[\"main\"] = func\n    check_result(target, dev, [x_data, y_data], x_data + y_data, mod)\n\n\ndef test_vm_optimize_dynamic():\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=(relay.Any(), relay.Any()), dtype=dtype)\n    y = relay.var(\"y\", shape=(relay.Any(), relay.Any()), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], relay.add(x, y))\n    comp = relay.vm.VMCompiler()\n    opt_mod, _ = comp.optimize(mod, target=\"llvm\")\n    assert \"shape_func\" in opt_mod.astext(False)\n\n\ndef test_vm_optimize():\n    mod, params = testing.synthetic.get_workload()\n    comp = relay.vm.VMCompiler()\n    opt_mod, _ = comp.optimize(mod, target=\"llvm\", params=params)\n\n    free_vars = relay.analysis.free_vars(opt_mod[\"main\"].body)\n    # Paremeters should all be bound, so the only free var is data\n    assert len(free_vars) == 1\n\n\ndef test_loop_free_var(target, dev):\n    x = relay.var(\"x\", shape=(), dtype=\"int32\")\n    i = relay.var(\"i\", shape=(), dtype=\"int32\")\n    s = relay.var(\"s\", shape=(), dtype=\"int32\")\n\n    def cond(i, _):\n        return i < relay.const(10, dtype=\"int32\")\n\n    def body_no_free_var(i, acc):\n        incr = relay.const(1, \"int32\")\n        return i + incr, acc + i\n\n    def body_with_free_var(i, acc):\n        incr = relay.const(1, \"int32\")\n        return i + incr, acc + x\n\n    for args, body, expected in zip([[], [1]], [body_no_free_var, body_with_free_var], [45, 10]):\n        loop = while_loop(cond, [i, s], body)\n        tup = loop(relay.const(0, dtype=\"int32\"), relay.zeros(shape=(), dtype=\"int32\"))\n        ret = relay.TupleGetItem(tup, 1)\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function(relay.analysis.free_vars(ret), ret)\n        check_result(target, dev, args, expected, mod)\n\n\ndef test_vm_reshape_tensor(target, dev):\n    x_np = np.random.uniform(size=(8, 16)).astype(\"float32\")\n    x = relay.var(\"x\", shape=(8, 16), dtype=\"float32\")\n    y = relay.reshape(x, [-1, 4, 8])\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y)\n    with tvm.transform.PassContext(opt_level=3):\n        exec = relay.vm.compile(mod, \"llvm\")\n    assert \"reshape_tensor\" in exec.bytecode\n    check_result(target, dev, [x_np], x_np.reshape([4, 4, 8]), mod)\n\n    x = relay.var(\"x\", shape=(8, 16), dtype=\"float32\")\n    y = relay.reshape(x, [16, -1])\n    y = relay.reverse_reshape(y, [-1, 4, 0])\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y)\n    with tvm.transform.PassContext(opt_level=3):\n        exec = relay.vm.compile(mod, \"llvm\")\n    assert exec.bytecode.count(\"reshape_tensor\") == 1\n    check_result(target, dev, [x_np], x_np.reshape([4, 4, 8]), mod)\n\n    # reshape with symbolic/any shape\n    for n in [tvm.tir.Any(), tvm.te.size_var(\"n\")]:\n        x = relay.var(\"x\", shape=(n, 16), dtype=\"float32\")\n        y = relay.reshape(x, [-1, 4])\n        y = relay.reshape(y, [0, 2, -1])\n        mod = tvm.IRModule()\n        mod[\"main\"] = relay.Function([x], y)\n        with tvm.transform.PassContext(opt_level=3):\n            exec = relay.vm.compile(mod, \"llvm\")\n        assert exec.bytecode.count(\"reshape_tensor\") == 1\n        check_result(target, dev, [x_np], x_np.reshape([32, 2, 2]), mod)\n\n    # dyn.reshape\n    x = relay.var(\"x\", shape=(8, 16), dtype=\"float32\")\n    y = relay.var(\"y\", shape=(3,), dtype=\"int32\")\n    z = relay.reshape(x, [-1, 4, 8])\n    z = relay.reshape(z, y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], z)\n    with tvm.transform.PassContext(opt_level=3):\n        exec = relay.vm.compile(mod, \"llvm\")\n    assert exec.bytecode.count(\"reshape_tensor\") == 2\n    assert \"reshape_tensor\" in exec.bytecode\n    y_np = np.array([8, 2, 8]).astype(\"int32\")\n    check_result(target, dev, [x_np, y_np], x_np.reshape([8, 2, 8]), mod)\n\n\ndef test_vm_reshape_and_copy(target, dev):\n    \"\"\"Make sure the compiler notices the reshape result shape is a literal and can use\n    the immediate-mode alloc_tensor instruction instead of alloc_tensor_reg.\"\"\"\n    x_np = np.random.uniform(size=(1, 1)).astype(\"float32\")\n    x = relay.var(\"x\", shape=(1, 1), dtype=\"float32\")\n    mod = tvm.IRModule.from_expr(relay.Function([x], relay.copy(relay.reshape(x, [0, 1]))))\n    with tvm.transform.PassContext(opt_level=3):\n        exec = relay.vm.compile(mod, \"llvm\")\n    assert \"alloc_tensor\" in exec.bytecode\n    assert not \"alloc_tensor_reg\" in exec.bytecode\n    check_result(target, dev, [x_np], x_np.reshape([1, 1]), mod)\n\n\ndef test_vm_reshape_tuple(target, dev, x_shape=(1, 4, 2), y_shape=(1, 2, 10)):\n    tup = relay.var(\n        \"tup\",\n        type_annotation=relay.TupleType([relay.TensorType(x_shape), relay.TensorType(y_shape)]),\n    )\n    out = relay.reshape(relay.TupleGetItem(tup, 0), (1, -1))\n    f = relay.Function([tup], out)\n\n    x_data = np.random.uniform(size=x_shape).astype(\"float32\")\n    y_data = np.random.uniform(size=y_shape).astype(\"float32\")\n\n    res = veval(f, (x_data, y_data), device=dev, target=target)\n    tvm.testing.assert_allclose(res.numpy(), np.reshape(x_data, (1, -1)))\n\n\ndef test_constant_shape_with_external_codegen():\n    @tvm.register_func(\"relay.ext.test1\")\n    def relay_ext_test(func):\n        return None\n\n    mod = tvm.IRModule()\n    shape = (relay.Any(), 25)\n    dtype = \"float32\"\n\n    # external function\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    weight = relay.const(np.random.rand(5, 25).astype(\"float32\"), dtype=\"float32\")\n    out = relay.nn.dense(x, weight)\n    f1 = relay.Function([x], out)\n    f1 = f1.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    f1 = f1.with_attr(\"Inline\", tvm.tir.IntImm(\"int32\", 1))\n    f1 = f1.with_attr(\"Compiler\", \"test1\")\n    f1 = f1.with_attr(\"global_symbol\", \"f1\")\n    glb_f1 = relay.GlobalVar(\"f1\")\n    mod[glb_f1] = f1\n    mod = relay.transform.InferType()(mod)\n\n    # Main function\n    x = relay.var(\"x\", shape=shape, dtype=dtype)\n    mod[\"main\"] = relay.Function([x], glb_f1(x))\n    comp = relay.vm.VMCompiler()\n    opt_mod, _ = comp.optimize(mod, target=\"llvm\")\n    assert \"shape_func\" in opt_mod.astext(False)\n\n\ndef prepare_vm_model(path, tensor_shape):\n    \"\"\"\n    Virtual Machine is compiled for simple topology and\n    exported as library to given path\n    \"\"\"\n    target = tvm.target.Target(\"llvm --host=llvm\")\n\n    # Build a IRModule.\n    x = relay.var(\"x\", shape=tensor_shape)\n    f = relay.Function([x], x + x)\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n\n    # Export to Disk\n    vm_exec.mod.export_library(path)\n\n\ndef test_vm_rpc():\n    \"\"\"\n    This test checks to make sure you can export a VMExecutable,\n    upload it to a remote machine using RPC and then execute it\n    on the other machine.\n    \"\"\"\n    # Shape for input and output tensors\n    shape = (10, 1)\n\n    # Export to Disk\n    temp = utils.tempdir()\n    path = temp.relpath(\"vm_library.so\")\n    prepare_vm_model(path, shape)\n\n    # Use local rpc server for testing.\n    # Server must use popen so it doesn't inherit the current process state. It\n    # will crash otherwise.\n    def check_remote(server):\n        remote = rpc.connect(server.host, server.port, session_timeout=10)\n\n        # Upload the serialized Executable.\n        remote.upload(path)\n        # Get a handle to remote Executable.\n        rexec = remote.load_module(\"vm_library.so\")\n\n        device = remote.cpu()\n        # Build a VM out of the executable and context.\n        vm_factory = runtime.vm.VirtualMachine(rexec, device)\n        np_input = np.random.uniform(size=shape).astype(\"float32\")\n        input_tensor = tvm.nd.array(np_input, device)\n        # Invoke its \"main\" function.\n        out = vm_factory.invoke(\"main\", input_tensor)\n        # Check the result.\n        np.testing.assert_allclose(out.numpy(), np_input + np_input)\n\n    check_remote(rpc.Server(\"127.0.0.1\"))\n\n\ndef test_vm_invoke_with_outputs_rpc():\n    \"\"\"\n    This test checks to make sure you can export a VMExecutable,\n    upload it to a remote machine using RPC and then execute it\n    on the other machine with preallocated outputs.\n    \"\"\"\n    # Shape for input and output tensors\n    shape = (3, 2)\n\n    # Export to Disk\n    temp = utils.tempdir()\n    path = temp.relpath(\"vm_library.so\")\n    prepare_vm_model(path, shape)\n\n    # Use local rpc server for testing.\n    # Server must use popen so it doesn't inherit the current process state. It\n    # will crash otherwise.\n    def check_remote_invoke_with_outputs(server):\n        remote = rpc.connect(server.host, server.port, session_timeout=10)\n\n        # Upload the serialized Executable.\n        remote.upload(path)\n        # Get a handle to remote Executable.\n        rexec = remote.load_module(\"vm_library.so\")\n\n        device = remote.cpu()\n        # Build a VM out of the executable and context.\n        vm_factory = runtime.vm.VirtualMachine(rexec, device)\n        np_input = np.random.uniform(size=shape).astype(\"float32\")\n        input_tensor = tvm.nd.array(np_input, device)\n        np_output = np.empty(shape, dtype=\"float32\")\n        output_tensor = tvm.nd.array(np_output, device)\n        # Invoke its \"main\" function.\n        vm_factory.invoke_with_outputs(\n            \"main\", input_args={\"x\": input_tensor}, output_args=[output_tensor]\n        )\n        # Check the result.\n        np.testing.assert_allclose(output_tensor.numpy(), np_input + np_input)\n\n    check_remote_invoke_with_outputs(rpc.Server(\"127.0.0.1\"))\n\n\ndef test_vm_invoke_with_outputs():\n    target = tvm.target.Target(\"llvm\")\n    shape = (3, 2)\n\n    # Build a IRModule.\n    x = relay.var(\"x\", shape=shape)\n    f = relay.Function([x], x + x)\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    vm_factory = runtime.vm.VirtualMachine(vm_exec, tvm.cpu())\n    np_input = np.random.uniform(size=shape).astype(\"float32\")\n    input_tensor = tvm.nd.array(np_input)\n    np_output = np.empty(shape, dtype=\"float32\")\n    output_tensor = tvm.nd.array(np_output)\n    # Invoke\n    vm_factory.invoke_with_outputs(\n        \"main\", input_args={\"x\": input_tensor}, output_args=[output_tensor]\n    )\n    # Check the result.\n    np.testing.assert_allclose(output_tensor.numpy(), np_input + np_input)\n\n\ndef test_get_output_single():\n    target = tvm.target.Target(\"llvm\")\n\n    # Build a IRModule.\n    x = relay.var(\"x\", shape=(10,))\n    f = relay.Function([x], x + x)\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    vm_factory = runtime.vm.VirtualMachine(vm_exec, tvm.cpu())\n    inp = np.ones(10, dtype=\"float32\")\n    vm_factory.invoke_stateful(\"main\", inp)\n    outputs = vm_factory.get_outputs()\n    assert len(outputs) == 1\n    np.testing.assert_allclose(outputs[0].numpy(), inp + inp)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_get_output_multiple(target, dev):\n    # Build a IRModule.\n    x = relay.var(\"x\", shape=(10,))\n    f = relay.Function([x], relay.Tuple([x + x, x]))\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    vm_factory = runtime.vm.VirtualMachine(vm_exec, dev)\n    inp = np.ones(10, dtype=\"float32\")\n    vm_factory.invoke_stateful(\"main\", inp)\n    outputs = vm_factory.get_outputs()\n    assert len(outputs) == 2\n    np.testing.assert_allclose(outputs[0].numpy(), inp + inp)\n    np.testing.assert_allclose(outputs[1].numpy(), inp)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_get_input_index(target, dev):\n    # Build a IRModule.\n    data_0, data_1 = [\"d1\", \"d2\"]\n    x, y = [relay.var(c, shape=(10,)) for c in [data_0, data_1]]\n    f = relay.Function([x, y], x + y)\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    vm_factory = runtime.vm.VirtualMachine(vm_exec, dev)\n    assert vm_factory.get_input_index(data_1) == 1\n    assert vm_factory.get_input_index(data_0) == 0\n    assert vm_factory.get_input_index(\"invalid\") == -1\n\n\ndef get_one_input_relay_mod(tensor_type, shape, data_name):\n    x = relay.var(data_name, shape=shape, dtype=tensor_type)\n    y = relay.exp(x)\n    f = relay.Function([x], y)\n    return IRModule.from_expr(f)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_one_set_input(target, dev):\n    dtype = \"float32\"\n    in_shape = [1, 2, 3, 3]\n    in_data_name_0 = \"d0\"\n\n    mod = get_one_input_relay_mod(dtype, in_shape, in_data_name_0)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    exe = runtime.vm.VirtualMachine(vm_exec, dev)\n\n    data0_core = np.random.uniform(size=in_shape).astype(dtype)\n    data0 = tvm.nd.array(data0_core)\n    ref_res_core = np.exp(data0_core)\n    ref_res = tvm.nd.array(ref_res_core)\n\n    exe.set_input(\"main\", data0)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    data_dict = {in_data_name_0: data0}\n    exe.set_input(\"main\", **data_dict)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n\ndef get_multiple_input_relay_mod(tensor_type, shape, data_name0, data_name1):\n    x, y = [relay.var(c, shape=shape, dtype=tensor_type) for c in [data_name0, data_name1]]\n    f = relay.Function([x, y], x + y)\n    return IRModule.from_expr(f)\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_multiple_set_input(target, dev):\n    dtype = \"float32\"\n    in_shape = [1, 2, 3, 3]\n    in_data_name_0 = \"d0\"\n    in_data_name_1 = \"d1\"\n\n    mod = get_multiple_input_relay_mod(dtype, in_shape, in_data_name_0, in_data_name_1)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    exe = runtime.vm.VirtualMachine(vm_exec, dev)\n\n    data0_core = np.random.uniform(size=in_shape).astype(dtype)\n    data0 = tvm.nd.array(data0_core)\n    data1_core = np.random.uniform(size=in_shape).astype(dtype)\n    data1 = tvm.nd.array(data1_core)\n    ref_res_core = data0_core + data1_core\n    ref_res = tvm.nd.array(ref_res_core)\n\n    exe.set_input(\"main\", data0, data1)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    data_dict = {in_data_name_1: data1, in_data_name_0: data0}\n    exe.set_input(\"main\", **data_dict)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_one_set_one_input(target, dev):\n    dtype = \"float32\"\n    in_shape = [1, 2, 3, 3]\n    in_data_name_0 = \"d0\"\n\n    mod = get_one_input_relay_mod(dtype, in_shape, in_data_name_0)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    exe = runtime.vm.VirtualMachine(vm_exec, dev)\n\n    data0_core = np.random.uniform(size=in_shape).astype(dtype)\n    data0 = tvm.nd.array(data0_core)\n    ref_res_core = np.exp(data0_core)\n    ref_res = tvm.nd.array(ref_res_core)\n\n    exe.set_one_input(\"main\", 0, data0)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    exe.set_one_input(\"main\", in_data_name_0, data0)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    data_dict = {in_data_name_0: data0}\n    exe.set_one_input(\"main\", **data_dict)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_multiple_set_one_input(target, dev):\n    dtype = \"float32\"\n    in_shape = [1, 2, 3, 3]\n    in_data_name_0 = \"d0\"\n    in_data_name_1 = \"d1\"\n\n    mod = get_multiple_input_relay_mod(dtype, in_shape, in_data_name_0, in_data_name_1)\n\n    # Compile to VMExecutable.\n    vm_exec = vm.compile(mod, target=target)\n    exe = runtime.vm.VirtualMachine(vm_exec, dev)\n\n    data0_core = np.random.uniform(size=in_shape).astype(dtype)\n    data0 = tvm.nd.array(data0_core)\n    data1_core = np.random.uniform(size=in_shape).astype(dtype)\n    data1 = tvm.nd.array(data1_core)\n    ref_res_core = data0_core + data1_core\n    ref_res = tvm.nd.array(ref_res_core)\n\n    exe.set_one_input(\"main\", 1, data1)\n    exe.set_one_input(\"main\", 0, data0)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    exe.set_one_input(\"main\", in_data_name_1, data1)\n    exe.set_one_input(\"main\", in_data_name_0, data0)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n    data_dict = {in_data_name_1: data1}\n    exe.set_one_input(\"main\", **data_dict)\n    data_dict = {in_data_name_0: data0}\n    exe.set_one_input(\"main\", **data_dict)\n    output = exe.invoke(\"main\")\n    assert output.dtype == ref_res.dtype\n    tvm.testing.assert_allclose(ref_res_core, output.numpy())\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_benchmark(target, dev):\n    mod, params = mlp.get_workload(1)\n    lib = vm.compile(mod, target=target, params=params)\n    exe = runtime.vm.VirtualMachine(lib, tvm.cpu())\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"))\n    result = exe.benchmark(tvm.cpu(), data, func_name=\"main\", repeat=2, number=1)\n    assert result.mean == result.median\n    assert result.mean > 0\n    assert len(result.results) == 2\n\n    with patch.object(\n        tvm.runtime.module.Module,\n        \"time_evaluator\",\n        return_value=lambda x: tvm.runtime.module.BenchmarkResult([1, 2, 2, 5]),\n    ) as method:\n        result = exe.benchmark(dev, data, func_name=\"main\", repeat=2, number=1)\n        assert result.mean == 2.5\n        assert result.median == 2.0\n        assert result.max == 5\n        assert result.min == 1\n        assert result.std == 1.5\n\n\ndef test_benchmark_end_to_end(target, dev):\n    mod, params = mlp.get_workload(1)\n    lib = vm.compile(mod, target=target, params=params)\n    exe = runtime.vm.VirtualMachine(lib, dev)\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"), device=dev)\n    result = exe.benchmark(dev, data, func_name=\"main\", repeat=2, number=1, end_to_end=True)\n    assert result.mean > 0\n\n\n@tvm.testing.requires_cuda\ndef test_benchmark_end_to_end_rpc():\n    server = rpc.Server(\"127.0.0.1\")\n    remote = rpc.connect(server.host, server.port)\n\n    mod, params = mlp.get_workload(1)\n    lib = vm.compile(mod, target=\"cuda\", params=params)\n\n    temp = utils.tempdir()\n    path = temp.relpath(\"vm_library.so\")\n    lib.mod.export_library(path)\n    remote.upload(path)\n    rlib = remote.load_module(\"vm_library.so\")\n\n    exe = runtime.vm.VirtualMachine(rlib, remote.device(\"cuda\"))\n    data = tvm.nd.array(\n        np.random.rand(1, 1, 28, 28).astype(\"float32\"), device=remote.device(\"cuda\")\n    )\n    result = exe.benchmark(\n        remote.device(\"cuda\"), data=data, func_name=\"main\", repeat=2, number=1, end_to_end=True\n    )\n    assert result.mean > 0\n\n\ndef test_shape_func_nested_function():\n    @tvm.register_func(\"relay.ext.test2\")\n    def relay_ext_test(func):\n        return None\n\n    data_shape = (relay.Any(), 16)\n    weight_shape = (relay.Any(), 16)\n\n    dense = relay.nn.dense(\n        relay.var(\"data\", shape=data_shape), relay.var(\"weight\", shape=weight_shape)\n    )\n    mod = tvm.IRModule.from_expr(dense)\n\n    patterns = [(\"test.dense\", is_op(\"nn.dense\")(wildcard(), wildcard()))]\n    passes = tvm.transform.Sequential(\n        [\n            relay.transform.MergeComposite(patterns),\n            relay.transform.AnnotateTarget([\"test2\"]),\n            relay.transform.PartitionGraph(),\n        ]\n    )\n\n    mod = passes(mod)\n\n    compiler = VMCompiler()\n    compiler.lower(mod, \"llvm\")\n\n\n@tvm.testing.requires_cuda\ndef test_storage_size_and_offset_on_cpu():\n    \"\"\"Tests allocations place sizes and offsets on the CPU host even if the rest\n    of the computation is on a different device type.\"\"\"\n\n    # TODO(mbs): Better would be to test ManifestAlloc independently.\n    # And/or move this to C++ and test the VM executable in it's C++ instead of\n    # pretty-printed form.\n\n    # CPU = device type 1\n    # GPU = device type 2\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a: Tensor[(5, 7), float32],\n                      param_device_types=[2], result_device_type=2) {\n              add(%a, %a)\n            }\n        \"\"\"\n        )\n\n    exe = relay.vm.compile(\n        input(),\n        tvm.target.Target(\"cuda\"),\n    )\n\n    # This program needs two constants:\n    # - The size of the tensor's storage (first arg) to alloc_storage\n    # - The offset of the tensor within the storage (second arg) to alloc_tensor\n    # Both should be on the CPU\n    assert \"VirtualDevice[0]: device type 1\" in exe.virtual_devices\n    assert \"VM Const[0]: NDArray[(),int64,(1,0)]=[140] on device index 0\" in exe.constants\n    assert \"VM Const[1]: NDArray[(),int64,(1,0)]=[0] on device index 0\" in exe.constants\n\n\n@tvm.testing.requires_cuda\ndef test_reshape_shape_on_cpu():\n    \"\"\"Tests the argument to a reshape places the shape on the CPU host even if the rest\n    of the computation is on a different device type.\"\"\"\n\n    # TODO(mbs): Better would be to test ManifestAlloc independently.\n    # And/or move this to C++ and test the VM executable in it's C++ instead of\n    # pretty-printed form.\n\n    # CPU = device type 1\n    # GPU = device type 2\n    def input():\n        return tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%x: Tensor[(2, 8), float32],\n                      param_device_types=[2], result_device_type=2) {\n              reshape(%x, newshape=[2, 4, 2])\n            }\n        \"\"\"\n        )\n\n    exe = relay.vm.compile(\n        input(),\n        tvm.target.Target(\"cuda\"),\n    )\n\n    # The newshape annotation should have been turned into a constant on the CPU.\n    assert \"VirtualDevice[0]: device type 1\" in exe.virtual_devices\n    assert \"VM Const[0]: NDArray[(3),int64,(1,0)]=[2,4,2] on device index 0\" in exe.constants\n\n\n@tvm.testing.requires_cuda\ndef test_multi_targets():\n    # Build an IRModule.\n    n = 10\n    x = relay.var(\"x\", shape=(n,))\n    y = relay.var(\"y\", shape=(n,))\n    z = relay.var(\"z\", shape=(n,))\n    f = relay.Function([x, y, z], x + relay.op.annotation.on_device(y + z, tvm.cpu()))\n    mod = IRModule.from_expr(f)\n\n    # Compile to VMExecutable.\n    with tvm.transform.PassContext(\n        opt_level=3, config={\"relay.fallback_device_type\": tvm.cuda().device_type}\n    ):\n        exe = relay.vm.compile(\n            mod, target={\"cpu\": tvm.target.Target(\"llvm\"), \"cuda\": tvm.target.Target(\"cuda\")}\n        )\n\n    # Run\n    vm = runtime.vm.VirtualMachine(exe, [tvm.cuda(), tvm.cpu()])\n    x_data = np.random.rand(\n        n,\n    ).astype(\"float32\")\n    y_data = np.random.rand(\n        n,\n    ).astype(\"float32\")\n    z_data = np.random.rand(\n        n,\n    ).astype(\"float32\")\n    actual_result = vm.invoke(\"main\", x_data, y_data, z_data)\n\n    # Test\n    expected_result = x_data + y_data + z_data\n    tvm.testing.assert_allclose(actual_result.numpy(), expected_result)\n\n\ndef test_let_bound_constants():\n    \"\"\"This tests for an ICHECK failure for ill-formed IR with let-bound constants\"\"\"\n\n    x = relay.var(\"x\", shape=(3,), dtype=\"int32\")\n    y = relay.take(x, relay.const(0))\n    z = relay.const(1)\n\n    f = relay.Function([x], relay.stack((z, y), axis=0))\n    mod = IRModule.from_expr(f)\n\n    compiler = VMCompiler()\n    compiler.optimize(mod, target=\"llvm\")\n\n\ndef test_large_constants():\n    \"\"\"Large constants can be serialized outside of executable\"\"\"\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n\n    # fn(x) { add(x, <large constant>) }\n    x = relay.var(\"x\", shape=(1000, 1000))\n    const_data = np.random.rand(1000, 1000).astype(\"float32\")\n    const = relay.const(const_data, dtype=\"float32\")\n    func = relay.Function([x], relay.op.add(x, const))\n    mod = tvm.IRModule.from_expr(func)\n\n    # Compile to executable.\n    vm_exec = vm.compile(mod, target=target)\n\n    # Save to constants and library files\n    temp = utils.tempdir()\n    path_consts = temp.relpath(\"consts\")\n    vm_exec.move_late_bound_consts(path_consts, byte_limit=256)\n    path_dso = temp.relpath(\"lib.so\")\n    vm_exec.mod.export_library(path_dso)\n\n    # Load library files and constants\n    mod = runtime.load_module(path_dso)\n    mod[\"load_late_bound_consts\"](path_consts)\n\n    # Test main\n    x_data = np.random.rand(1000, 1000).astype(\"float32\")\n    the_vm = runtime.vm.VirtualMachine(mod, dev)\n    actual = the_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n    # We load the mod again so it's missing the consts.\n    mod = runtime.load_module(path_dso)\n    exe = runtime.vm.Executable(mod)\n\n    # Also test loading consts via the VM's wrapper API.\n    exe.load_late_bound_consts(path_consts)\n\n    # Test main again with consts now loaded via the above API.\n    x_data = np.random.rand(1000, 1000).astype(\"float32\")\n    the_vm = runtime.vm.VirtualMachine(exe, dev)\n    actual = the_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n\ndef test_load_late_bound_consts_with_no_late_bound_consts():\n    \"\"\"Check that load_late_bound_consts handles a model with no late bound consts.\"\"\"\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n\n    const_data = np.random.rand(1).astype(\"float64\")\n    x = relay.var(\"x\", shape=(1,), dtype=\"float64\")\n    const = relay.const(const_data, dtype=\"float64\")\n\n    func = relay.Function([x], relay.op.add(x, const))\n    mod = tvm.IRModule.from_expr(func)\n\n    vm_exec = vm.compile(mod, target=target)\n\n    temp = utils.tempdir()\n    path_consts = temp.relpath(\"consts\")\n    path_dso = temp.relpath(\"lib.so\")\n\n    # Ensure const_data is below the byte threshold for a late-bound const.\n    byte_limit = len(const_data.tobytes()) + 1\n    vm_exec.move_late_bound_consts(path_consts, byte_limit=byte_limit)\n    vm_exec.mod.export_library(path_dso)\n\n    mod = runtime.load_module(path_dso)\n    mod[\"load_late_bound_consts\"](path_consts)\n\n    x_data = np.random.rand(1).astype(\"float64\")\n    loaded_vm = runtime.vm.VirtualMachine(mod, dev)\n    actual = loaded_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n\ndef test_vm_save_and_load_without_designating_late_bound_consts():\n    \"\"\"Check that a VM can be saved and loaded without late-bound consts in play.\n\n    Specifically, this test ensures that the machinery behind late-bound const\n    loading does not assume the need to load late-bound consts (and cause an error)\n    when the user did not choose to designate any consts as such.\n    \"\"\"\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n\n    const_data = np.random.rand(1).astype(\"float64\")\n    x = relay.var(\"x\", shape=(1,), dtype=\"float64\")\n    const = relay.const(const_data, dtype=\"float64\")\n\n    func = relay.Function([x], relay.op.add(x, const))\n    mod = tvm.IRModule.from_expr(func)\n\n    vm_exec = vm.compile(mod, target=target)\n\n    code, lib = vm_exec.save()\n    exe = runtime.vm.Executable.load_exec(code, lib)\n\n    x_data = np.random.rand(1).astype(\"float64\")\n    loaded_vm = runtime.vm.VirtualMachine(exe, dev)\n    actual = loaded_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n\ndef test_load_and_save_constants_via_map():\n    \"\"\"Large constants can be serialized outside of executable\"\"\"\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n\n    # fn(x) { add(x, <large constant>) }\n    x = relay.var(\"x\", shape=(1000, 1000))\n    const_data = np.random.rand(1000, 1000).astype(\"float32\")\n    const = relay.const(const_data, dtype=\"float32\")\n    func = relay.Function([x], relay.op.add(x, const))\n    mod = tvm.IRModule.from_expr(func)\n\n    # Compile to executable.\n    vm_exec = vm.compile(mod, target=target)\n\n    consts_map = vm_exec.get_late_bound_consts(byte_limit=256)\n\n    # Save to constants and library files\n    temp = utils.tempdir()\n    path_dso = temp.relpath(\"lib.so\")\n    vm_exec.mod.export_library(path_dso)\n\n    # Load library files and constants\n    mod = runtime.load_module(path_dso)\n    mod[\"load_late_bound_consts_from_map\"](consts_map)\n\n    # Test main\n    x_data = np.random.rand(1000, 1000).astype(\"float32\")\n    the_vm = runtime.vm.VirtualMachine(mod, dev)\n    actual = the_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n    # We load the mod again so it's missing the consts.\n    mod = runtime.load_module(path_dso)\n    exe = runtime.vm.Executable(mod)\n\n    # Also test loading consts via the VM's wrapper API.\n    exe.load_late_bound_consts_from_map(consts_map)\n\n    # Test main again with consts now loaded via the above API.\n    x_data = np.random.rand(1000, 1000).astype(\"float32\")\n    the_vm = runtime.vm.VirtualMachine(exe, dev)\n    actual = the_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n\ndef test_load_late_bound_consts_via_map_with_no_late_bound_consts():\n    \"\"\"Check that load_late_bound_consts handles a model with no late bound consts.\"\"\"\n    target = tvm.target.Target(\"llvm\")\n    dev = tvm.cpu()\n\n    const_data = np.random.rand(1).astype(\"float64\")\n    x = relay.var(\"x\", shape=(1,), dtype=\"float64\")\n    const = relay.const(const_data, dtype=\"float64\")\n\n    func = relay.Function([x], relay.op.add(x, const))\n    mod = tvm.IRModule.from_expr(func)\n\n    vm_exec = vm.compile(mod, target=target)\n\n    temp = utils.tempdir()\n    path_dso = temp.relpath(\"lib.so\")\n\n    # Ensure const_data is below the byte threshold for a late-bound const.\n    byte_limit = len(const_data.tobytes()) + 1\n    consts_map = vm_exec.get_late_bound_consts(byte_limit=byte_limit)\n    vm_exec.mod.export_library(path_dso)\n\n    mod = runtime.load_module(path_dso)\n    mod[\"load_late_bound_consts_from_map\"](consts_map)\n\n    x_data = np.random.rand(1).astype(\"float64\")\n    loaded_vm = runtime.vm.VirtualMachine(mod, dev)\n    actual = loaded_vm.invoke(\"main\", x_data)\n    expected = x_data + const_data\n    tvm.testing.assert_allclose(expected, actual.numpy())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/test_vm_serialization.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-docstring, no-else-return\n\"\"\"Unit tests for the Relay VM serialization and deserialization.\"\"\"\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm.runtime import vm as _vm\nfrom tvm.relay import vm as rly_vm\nfrom tvm import relay\n\nfrom tvm.relay.scope_builder import ScopeBuilder\nfrom tvm.relay import transform\nfrom tvm.relay.prelude import Prelude\nfrom tvm.contrib import utils\nfrom tvm.relay import testing\n\n\ndef create_exec(f, target=\"llvm\", params=None):\n    if isinstance(f, relay.Expr):\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n        executable = rly_vm.compile(mod, target=target, params=params)\n        return executable\n    else:\n        assert isinstance(f, tvm.IRModule), \"expected mod as tvm.IRModule\"\n        executable = rly_vm.compile(f, target=target, params=params)\n        return executable\n\n\ndef get_serialized_output(mod, *data, params=None, target=\"llvm\", device=tvm.cpu()):\n    exe = create_exec(mod, target, params=params)\n    code, lib = exe.save()\n    des_exec = _vm.Executable.load_exec(code, lib)\n    des_vm = _vm.VirtualMachine(des_exec, device)\n    result = des_vm.run(*data)\n    return result\n\n\ndef run_network(mod, params, dtype=\"float32\"):\n    def get_vm_output(mod, data, params, target, device, dtype=\"float32\"):\n        result = relay.create_executor(\"vm\", mod=mod, device=device).evaluate()(data, **params)\n        return result.numpy().astype(dtype)\n\n    data_shape = [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n    data = np.random.uniform(size=data_shape).astype(dtype)\n    target = \"llvm\"\n    dev = tvm.cpu(0)\n\n    tvm_out = get_vm_output(mod, tvm.nd.array(data.astype(dtype)), params, target, dev, dtype)\n    vm_out = get_serialized_output(\n        mod, tvm.nd.array(data.astype(dtype)), params=params, target=target, device=dev\n    )\n    tvm.testing.assert_allclose(vm_out.numpy().astype(dtype), tvm_out, rtol=1e-5, atol=1e-5)\n\n\ndef test_serializer():\n    mod = tvm.IRModule({})\n    a = relay.const(1.0, \"float32\")\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float32\")\n    f1 = relay.Function([x], x + a)\n    glb_f1 = relay.GlobalVar(\"f1\")\n    mod[glb_f1] = f1\n\n    # TODO(@jroesch): look into optimizing away the need to do this\n    mod = transform.InferType()(mod)\n\n    b = relay.const(2.0, \"float32\")\n    y = relay.var(\"y\", shape=(10, 10), dtype=\"float32\")\n    f2 = relay.Function([y], y - b)\n    glb_f2 = relay.GlobalVar(\"f2\")\n    mod[glb_f2] = f2\n\n    # TODO(@jroesch): look into optimizing away the need to do this\n    mod = transform.InferType()(mod)\n\n    x1 = relay.var(\"x1\", shape=(10, 10), dtype=\"float32\")\n    y1 = relay.var(\"y1\", shape=(10, 10), dtype=\"float32\")\n    main = relay.Function([x1, y1], glb_f1(x1) * glb_f2(y1))\n    mod[\"main\"] = main\n\n    exe = create_exec(mod)\n\n    glbs = exe.globals\n    assert len(glbs) == 3\n    assert \"f1\" in glbs\n    assert \"f2\" in glbs\n    assert \"main\" in glbs\n\n    prim_ops = exe.primitive_ops\n    assert any(item.startswith(\"vm_mod_fused_add\") for item in prim_ops)\n    assert any(item.startswith(\"vm_mod_fused_subtract\") for item in prim_ops)\n    assert any(item.startswith(\"vm_mod_fused_multiply\") for item in prim_ops)\n\n    code = exe.bytecode\n    assert \"main(x1, y1)\" in code\n    assert \"f1(x)\" in code\n    assert \"f2(y)\" in code\n\n    code, lib = exe.save()\n    assert isinstance(code, bytearray)\n    assert isinstance(lib, tvm.runtime.Module)\n\n\ndef test_save_load():\n    x = relay.var(\"x\", shape=(10, 10))\n    f = relay.Function([x], x + x)\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n\n    # serialize.\n    vm = create_exec(f)\n    code, lib = vm.save()\n    assert isinstance(code, bytearray)\n\n    # save and load the code and lib file.\n    tmp = utils.tempdir()\n    path_lib = tmp.relpath(\"lib.so\")\n    lib.export_library(path_lib)\n    with open(tmp.relpath(\"code.ro\"), \"wb\") as fo:\n        fo.write(code)\n\n    loaded_lib = tvm.runtime.load_module(path_lib)\n    loaded_code = bytearray(open(tmp.relpath(\"code.ro\"), \"rb\").read())\n\n    # deserialize.\n    des_exec = _vm.Executable.load_exec(loaded_code, loaded_lib)\n    des_vm = _vm.VirtualMachine(des_exec, tvm.cpu())\n\n    res = des_vm.run(x_data)\n    tvm.testing.assert_allclose(res.numpy(), x_data + x_data)\n\n\ndef test_const():\n    c = relay.const(1.0, \"float32\")\n    x = relay.var(\"x\", shape=(10, 10), dtype=\"float32\")\n    f = relay.Function([x], x + c)\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    res = get_serialized_output(f, x_data)\n    tvm.testing.assert_allclose(res.numpy(), x_data + 1)\n\n\ndef test_if():\n    x = relay.var(\"x\", shape=(10, 10))\n    y = relay.var(\"y\", shape=(10, 10))\n    equal = relay.op.equal(x, y)\n    equal = relay.op.nn.batch_flatten(equal)\n    f = relay.Function([x, y], relay.If(relay.op.min(equal, axis=[0, 1]), x, y))\n    x_data = np.random.rand(10, 10).astype(\"float32\")\n    y_data = np.random.rand(10, 10).astype(\"float32\")\n\n    # same\n    res = get_serialized_output(f, x_data, x_data)\n    tvm.testing.assert_allclose(res.numpy(), x_data)\n\n    # diff\n    res = get_serialized_output(f, x_data, y_data)\n    tvm.testing.assert_allclose(res.numpy(), y_data)\n\n\ndef test_loop():\n    mod = tvm.IRModule({})\n    sum_up = relay.GlobalVar(\"sum_up\")\n    i = relay.var(\"i\", shape=[], dtype=\"int32\")\n    accum = relay.var(\"accum\", shape=[], dtype=\"int32\")\n    sb = ScopeBuilder()\n    with sb.if_scope(relay.equal(i, relay.const(0, \"int32\"))):\n        sb.ret(accum)\n    with sb.else_scope():\n        one_less = relay.subtract(i, relay.const(1, \"int32\"))\n        new_accum = relay.add(accum, i)\n        sb.ret(relay.Call(sum_up, [one_less, new_accum]))\n    func = relay.Function([i, accum], sb.get())\n    mod[sum_up] = func\n    mod = transform.InferType()(mod)\n    loop_bound = 0\n    i_data = np.array(loop_bound, dtype=\"int32\")\n    accum_data = np.array(0, dtype=\"int32\")\n    iarg = relay.var(\"i\", shape=[], dtype=\"int32\")\n    aarg = relay.var(\"accum\", shape=[], dtype=\"int32\")\n    mod[\"main\"] = relay.Function([iarg, aarg], sum_up(iarg, aarg))\n\n    result = get_serialized_output(mod, i_data, accum_data)\n    tvm.testing.assert_allclose(result.numpy(), sum(range(1, loop_bound + 1)))\n\n\ndef test_tuple():\n    ttype = relay.TupleType([relay.TensorType((1,)), relay.TensorType((10,))])\n    tup = relay.var(\"tup\", type_annotation=ttype)\n    f = relay.Function([tup], relay.TupleGetItem(tup, 1))\n    i_data = np.random.rand(41).astype(\"float32\")\n    j_data = np.random.rand(10).astype(\"float32\")\n\n    result = get_serialized_output(f, (i_data, j_data))\n    tvm.testing.assert_allclose(result.numpy(), j_data)\n\n\ndef test_adt_list():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n    _, cons, nil = mod.get_type(\"List\")\n    l1 = cons(relay.const(1), nil())\n    l21 = cons(relay.const(2), l1)\n    l321 = cons(relay.const(3), l21)\n\n    f = relay.Function([], l321)\n    mod[\"main\"] = f\n\n    result = get_serialized_output(mod)\n    assert len(result) == 2\n    assert len(result[1]) == 2\n    assert len(result[1][1]) == 2\n    res = []\n    res.append(result[0].numpy().tolist())\n    res.append(result[1][0].numpy().tolist())\n    res.append(result[1][1][0].numpy().tolist())\n    tvm.testing.assert_allclose(res, np.array([3, 2, 1]))\n\n\ndef test_adt_compose():\n    mod = tvm.IRModule()\n    p = Prelude(mod)\n\n    compose = mod.get_global_var(\"compose\")\n\n    # add_one = fun x -> x + 1\n    sb = relay.ScopeBuilder()\n    x = relay.var(\"x\", \"float32\")\n    x1 = sb.let(\"x1\", x)\n    xplusone = x1 + relay.const(1.0, \"float32\")\n    sb.ret(xplusone)\n    body = sb.get()\n    add_one = relay.GlobalVar(\"add_one\")\n    add_one_func = relay.Function([x], body)\n\n    # add_two = compose(add_one, add_one)\n    sb = relay.ScopeBuilder()\n    y = relay.var(\"y\", \"float32\")\n    add_two_func = sb.let(\"add_two\", compose(add_one_func, add_one_func))\n    add_two_res = add_two_func(y)\n    sb.ret(add_two_res)\n    add_two_body = sb.get()\n\n    mod[add_one] = add_one_func\n\n    f = relay.Function([y], add_two_body)\n    mod[\"main\"] = f\n\n    x_data = np.array(np.random.rand()).astype(\"float32\")\n    result = get_serialized_output(mod, x_data)\n    tvm.testing.assert_allclose(result.numpy(), x_data + 2.0)\n\n\ndef test_closure():\n    x = relay.var(\"x\", shape=())\n    y = relay.var(\"y\", shape=())\n    f = relay.Function([x], x + y)\n    ff = relay.Function([y], f)\n    clo = ff(relay.const(1.0))\n    main = clo(relay.const(2.0))\n\n    res = get_serialized_output(main)\n    tvm.testing.assert_allclose(res.numpy(), 3.0)\n\n\ndef test_synthetic():\n    mod, params = testing.synthetic.get_workload()\n    run_network(mod, params)\n\n\ndef test_mobilenet():\n    mod, params = testing.mobilenet.get_workload(batch_size=1)\n    run_network(mod, params)\n\n\ndef test_vm_shape_of():\n    x = relay.var(\"x\", shape=(relay.Any(), relay.Any(), relay.Any()), dtype=\"float32\")\n    relu_x = relay.nn.relu(x)\n    data = np.random.uniform(size=(2, 3, 4)).astype(\"float32\")\n    args = [data]\n\n    newshape_var = relay.var(\"newshape\", shape=(2,), dtype=\"int64\")\n    args.append(np.array((1, -1), dtype=\"int64\"))\n    main = relay.Function([x, newshape_var], relay.reshape(relu_x, newshape=newshape_var))\n\n    res = get_serialized_output(main, *args).numpy()\n    tvm.testing.assert_allclose(res.flatten(), data.flatten())\n\n\ndef test_dynamic_bcast():\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=(relay.Any(), 2), dtype=dtype)\n    y = relay.var(\"y\", shape=(3, 2), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], relay.add(x, y))\n    x_data = np.random.uniform(size=(1, 2)).astype(dtype)\n    y_data = np.random.uniform(size=(3, 2)).astype(dtype)\n    res_np = np.add(x_data, y_data)\n    for target, dev in testing.enabled_targets():\n        res = get_serialized_output(mod, *(x_data, y_data), target=target, device=dev)\n        tvm.testing.assert_allclose(res.numpy(), res_np)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/transform/test_capture_postdfsindex_in_spans.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\n\"\"\"Unit tests for the CapturePostDfsIndexInSpans debugging pass.\"\"\"\n\nimport tvm\nimport tvm.testing\nimport numpy as np\n\n\ndef make_const(dtype, shape):\n    return tvm.relay.const(np.random.rand(*shape).astype(dtype))\n\n\ndef make_consts(dtype, shapes):\n    return [make_const(dtype, shape) for shape in shapes]\n\n\nmetatable = {\n    \"relay.Constant\": make_consts(\n        \"float16\",\n        [\n            (2304, 768),  # 0\n            (2304,),  # 1\n            (600, 32, 64),  # 2\n        ],\n    )\n}\n\n\ndef input_mod():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          %0 = nn.dense(%x0, meta[relay.Constant][0], units=2304);\n          %1 = add(%0, meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\nexpected_pretty_printed_output_mod = r\"\"\"def @main(%x0: Tensor[(1600, 768), float16] /* ty=Tensor[(1600, 768), float16] span=index:0:5 */, %x3: Tensor[(600, 32, 64), float16] /* ty=Tensor[(600, 32, 64), float16] span=index:1:18 */) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n  %0 = nn.dense(%x0, meta[relay.Constant][0] /* ty=Tensor[(2304, 768), float16] span=index:4:5 */, units=2304) /* ty=Tensor[(1600, 2304), float16] span=index:5:7 */;\n  %2 = fn (%y_3_i0: Tensor[(600, 32, 64), float16] /* ty=Tensor[(600, 32, 64), float16] span=index:8:15 */, %y_3_i1: Tensor[(600, 32, 64), float16] /* ty=Tensor[(600, 32, 64), float16] span=index:9:15 */, Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n    %1 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16] /* ty=Tensor[(600, 32, 64), float16] span=index:10:13 */, %FunctionVar_0_11: Tensor[(600, 32, 64), float16] /* ty=Tensor[(600, 32, 64), float16] span=index:11:13 */, PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n      nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True) /* ty=Tensor[(600, 32, 32), float16] span=index:13:14 */\n    } /* ty=fn (Tensor[(600, 32, 64), float16], Tensor[(600, 32, 64), float16]) -> Tensor[(600, 32, 32), float16] span=index:14:15 */;\n    %1(%y_3_i0, %y_3_i1) /* ty=Tensor[(600, 32, 32), float16] span=index:15:16 */\n  } /* ty=fn (Tensor[(600, 32, 64), float16], Tensor[(600, 32, 64), float16]) -> Tensor[(600, 32, 32), float16] span=index:16:18 */;\n  %3 = add(%0, meta[relay.Constant][1] /* ty=Tensor[(2304), float16] span=index:6:7 */) /* ty=Tensor[(1600, 2304), float16] span=index:7:19 */;\n  %4 = %2(%x3, meta[relay.Constant][2] /* ty=Tensor[(600, 32, 64), float16] span=index:17:18 */) /* ty=Tensor[(600, 32, 32), float16] span=index:18:19 */;\n  (%3, %4) /* ty=(Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) span=index:19:20 */\n}\n\n\"\"\"\n\n\ndef test_capture_index_in_spans():\n    output_mod = str(tvm.relay.transform.CapturePostDfsIndexInSpans()(input_mod()))\n    assert output_mod == expected_pretty_printed_output_mod\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/transform/test_compiler_function_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\n\"\"\"Unit tests for the OutlineCompilerFunctionsWithExistingGlobalSymbols and\n   MarkCompilerFunctionsAsExtern external codegen helper passes.\"\"\"\n\nimport tvm\nimport tvm.testing\nimport numpy as np\n\n\ndef make_const(dtype, shape):\n    return tvm.relay.const(np.random.rand(*shape).astype(dtype))\n\n\ndef make_consts(dtype, shapes):\n    return [make_const(dtype, shape) for shape in shapes]\n\n\nmetatable = {\n    \"relay.Constant\": make_consts(\n        \"float16\",\n        [\n            (2304, 768),  # 0\n            (2304,),  # 1\n            (600, 32, 64),  # 2\n        ],\n    )\n}\n\n\ndef original_mod():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          %0 = fn(%y_0_i0: Tensor[(1600, 768), float16], %y_0_i1: Tensor[(2304, 768), float16], %y_0_i2: Tensor[(2304), float16],\n                  Inline=1, Compiler=\"cutlass\", global_symbol=\"tvmgen_default_cutlass_main_0\", Primitive=1) -> Tensor[(1600, 2304), float16] {\n            %4 = fn (%FunctionVar_0_0: Tensor[(1600, 768), float16], %FunctionVar_0_1: Tensor[(2304, 768), float16], %FunctionVar_0_2: Tensor[(2304), float16],\n                     PartitionedFromPattern=\"nn.dense_add_\", Composite=\"cutlass.dense_bias\") -> Tensor[(1600, 2304), float16] {\n              %5 = nn.dense(%FunctionVar_0_0, %FunctionVar_0_1, units=2304);\n              add(%5, %FunctionVar_0_2)\n            };\n            %4(%y_0_i0, %y_0_i1, %y_0_i2)\n          };\n          %1 = %0(%x0, meta[relay.Constant][0], meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\ndef original_mod_let_bound():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          let %f = fn(%y_0_i0: Tensor[(1600, 768), float16], %y_0_i1: Tensor[(2304, 768), float16], %y_0_i2: Tensor[(2304), float16],\n                      Inline=1, Compiler=\"cutlass\", global_symbol=\"tvmgen_default_cutlass_main_0\", Primitive=1) -> Tensor[(1600, 2304), float16] {\n            %4 = fn (%FunctionVar_0_0: Tensor[(1600, 768), float16], %FunctionVar_0_1: Tensor[(2304, 768), float16], %FunctionVar_0_2: Tensor[(2304), float16],\n                     PartitionedFromPattern=\"nn.dense_add_\", Composite=\"cutlass.dense_bias\") -> Tensor[(1600, 2304), float16] {\n              %5 = nn.dense(%FunctionVar_0_0, %FunctionVar_0_1, units=2304);\n              add(%5, %FunctionVar_0_2)\n            };\n            %4(%y_0_i0, %y_0_i1, %y_0_i2)\n          };\n          %1 = %f(%x0, meta[relay.Constant][0], meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\ndef expected_outlined_mod():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          %1 = @tvmgen_default_cutlass_main_0(%x0, meta[relay.Constant][0], meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n\n        def @tvmgen_default_cutlass_main_0(%y_0_i0: Tensor[(1600, 768), float16], %y_0_i1: Tensor[(2304, 768), float16], %y_0_i2: Tensor[(2304), float16],\n                  Inline=1, Compiler=\"cutlass\", global_symbol=\"tvmgen_default_cutlass_main_0\", Primitive=1) -> Tensor[(1600, 2304), float16] {\n          %4 = fn (%FunctionVar_0_0: Tensor[(1600, 768), float16], %FunctionVar_0_1: Tensor[(2304, 768), float16], %FunctionVar_0_2: Tensor[(2304), float16],\n                   PartitionedFromPattern=\"nn.dense_add_\", Composite=\"cutlass.dense_bias\") -> Tensor[(1600, 2304), float16] {\n            %5 = nn.dense(%FunctionVar_0_0, %FunctionVar_0_1, units=2304);\n            add(%5, %FunctionVar_0_2)\n          };\n          %4(%y_0_i0, %y_0_i1, %y_0_i2)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\ndef expected_extern_mod():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          %1 = @tvmgen_default_cutlass_main_0(%x0, meta[relay.Constant][0], meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n\n        def @tvmgen_default_cutlass_main_0(%y_0_i0: Tensor[(1600, 768), float16], %y_0_i1: Tensor[(2304, 768), float16], %y_0_i2: Tensor[(2304), float16],\n                  Extern=1) -> Tensor[(1600, 2304), float16] {\n          %4 = fn (%FunctionVar_0_0: Tensor[(1600, 768), float16], %FunctionVar_0_1: Tensor[(2304, 768), float16], %FunctionVar_0_2: Tensor[(2304), float16],\n                   PartitionedFromPattern=\"nn.dense_add_\", Composite=\"cutlass.dense_bias\") -> Tensor[(1600, 2304), float16] {\n            %5 = nn.dense(%FunctionVar_0_0, %FunctionVar_0_1, units=2304);\n            add(%5, %FunctionVar_0_2)\n          };\n          %4(%y_0_i0, %y_0_i1, %y_0_i2)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\ndef expected_inlined_mod():\n    return tvm.parser.parse(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%x0 : Tensor[(1600, 768), float16], %x3 : Tensor[(600, 32, 64), float16]) -> (Tensor[(1600, 2304), float16], Tensor[(600, 32, 32), float16]) {\n          %0 = nn.dense(%x0, meta[relay.Constant][0], units=2304);\n          %1 = add(%0, meta[relay.Constant][1]);\n          %2 = fn(%y_3_i0: Tensor[(600, 32, 64), float16], %y_3_i1: Tensor[(600, 32, 64), float16],\n                  Inline=1, Compiler=\"cublas\", global_symbol=\"tvmgen_default_cublas_main_3\", Primitive=1) -> Tensor[(600, 32, 32), float16] {\n            %6 = fn (%FunctionVar_0_01: Tensor[(600, 32, 64), float16], %FunctionVar_0_11: Tensor[(600, 32, 64), float16],\n                     PartitionedFromPattern=\"nn.batch_matmul_\", Composite=\"cublas.batch_matmul\") -> Tensor[(600, 32, 32), float16] {\n              nn.batch_matmul(%FunctionVar_0_01, %FunctionVar_0_11, out_dtype=\"float16\", transpose_b=True)\n            };\n            %6(%y_3_i0, %y_3_i1)\n          };\n          %3 = %2(%x3, meta[relay.Constant][2]);\n          (%1, %3)\n        }\n        \"\"\",\n        \"from_string\",\n        None,\n        metatable,\n    )\n\n\ndef test_outline_compiler_functions_with_existing_global_symbols():\n    actual_outlined_mod = tvm.relay.transform.OutlineCompilerFunctionsWithExistingGlobalSymbols(\n        \"cutlass\"\n    )(original_mod())\n    tvm.ir.assert_structural_equal(actual_outlined_mod, expected_outlined_mod(), map_free_vars=True)\n\n\ndef test_outline_let_bound_compiler_functions_with_existing_global_symbols():\n    actual_outlined_mod = tvm.relay.transform.OutlineCompilerFunctionsWithExistingGlobalSymbols(\n        \"cutlass\"\n    )(original_mod_let_bound())\n    tvm.ir.assert_structural_equal(actual_outlined_mod, expected_outlined_mod(), map_free_vars=True)\n\n\ndef test_mark_compiler_functions_as_extern():\n    actual_extern_mod = tvm.relay.transform.MarkCompilerFunctionsAsExtern(\"cutlass\")(\n        expected_outlined_mod()\n    )\n    tvm.ir.assert_structural_equal(actual_extern_mod, expected_extern_mod(), map_free_vars=True)\n\n\ndef test_inline_compiler_functions():\n    mod = expected_outlined_mod()\n    gv = mod.get_global_var(\"tvmgen_default_cutlass_main_0\")\n    actual_inlined_mod = tvm.relay.transform.InlineCompilerFunctionsBoundTo([gv])(mod)\n    tvm.ir.assert_structural_equal(actual_inlined_mod, expected_inlined_mod(), map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/utils/assert_diagnostic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\n\nfrom tvm import register_func, get_global_func, IRModule\nfrom tvm import relay\nfrom tvm.parser import SpanCheck\nfrom tvm.relay.transform import AnnotateSpans\nfrom tvm.runtime import Object\nfrom tvm.ir.diagnostics import get_renderer, override_renderer\nfrom tvm.error import DiagnosticError\n\nDEFAULT_RENDERER = get_renderer()\n\n__TESTING__ = None\n\n\ndef testing_renderer(diag_ctx):\n    global __TESTING__\n    if __TESTING__ and __TESTING__.mirror:\n        DEFAULT_RENDERER.render(diag_ctx)\n\n    if __TESTING__:\n        __TESTING__._render(diag_ctx)\n\n\nclass DiagnosticTesting:\n    def __init__(self, mirror=False):\n        self.mirror = mirror\n        self.messages = []\n\n    def __enter__(self):\n        global __TESTING__\n        __TESTING__ = self\n        override_renderer(testing_renderer)\n        return self\n\n    def __exit__(self, type, value, traceback):\n        global __TESTING__\n        __TESTING__ = None\n        override_renderer(None)\n        if type is DiagnosticError and self.matches:\n            return True\n\n    def assert_message(self, in_message):\n        self.messages.append(in_message)\n\n    def _render(self, diag_ctx):\n        self.matches = False\n        for diagnostic in diag_ctx.diagnostics:\n            message = diagnostic.message\n            for partial_msg in self.messages:\n                if partial_msg in message:\n                    self.matches = True\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/utils/external_codegen.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for testing external code generation\"\"\"\n\nimport os\nimport sys\n\nimport pytest\n\nimport tvm\nfrom tvm import relay, runtime, testing\nfrom tvm.contrib import utils\n\n\nskip_windows = pytest.mark.skipif(sys.platform == \"win32\", reason=\"Skip test on Windows for now\")\nskip_micro = pytest.mark.skipif(\n    tvm.support.libinfo().get(\"USE_MICRO\", \"OFF\") != \"ON\",\n    reason=\"MicroTVM support not enabled. Set USE_MICRO=ON in config.cmake to enable.\",\n)\n\n\ndef parametrize_external_codegen_checks(test):\n    \"\"\"Parametrize over the various check_result functions which are available\"\"\"\n    return pytest.mark.parametrize(\n        \"check_result\",\n        [\n            pytest.param(check_aot_executor_result, marks=[skip_windows, skip_micro]),\n            pytest.param(check_graph_executor_result, marks=[skip_windows]),\n            pytest.param(check_vm_result, marks=[skip_windows]),\n        ],\n    )(test)\n\n\ndef parametrize_external_json_codegen_checks(test):\n    \"\"\"Parametrize over the various check_result functions which are available for JSON\"\"\"\n    return pytest.mark.parametrize(\n        \"check_result\",\n        [\n            pytest.param(check_graph_executor_result, marks=[skip_windows]),\n            pytest.param(check_vm_result, marks=[skip_windows]),\n        ],\n    )(test)\n\n\ndef update_lib(lib):\n    test_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))\n    source_dir = os.path.join(test_dir, \"..\", \"..\", \"..\", \"..\")\n    contrib_path = os.path.join(source_dir, \"src\", \"runtime\", \"contrib\")\n\n    kwargs = {}\n    kwargs[\"options\"] = [\"-O2\", \"-std=c++17\", \"-I\" + contrib_path]\n    tmp_path = utils.tempdir()\n    lib_name = \"lib.so\"\n    lib_path = tmp_path.relpath(lib_name)\n    lib.export_library(lib_path, fcompile=False, **kwargs)\n    lib = tvm.runtime.load_module(lib_path)\n\n    return lib\n\n\ndef check_vm_result(mod, map_inputs, out_shape, result, tol=1e-5, target=\"llvm\", device=tvm.cpu()):\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n        exe = relay.vm.compile(mod, target=target)\n    code, lib = exe.save()\n    lib = update_lib(lib)\n    exe = runtime.vm.Executable.load_exec(code, lib)\n    vm = runtime.vm.VirtualMachine(exe, device)\n    out = vm.run(**map_inputs)\n    tvm.testing.assert_allclose(out.numpy(), result, rtol=tol, atol=tol)\n\n\ndef check_graph_executor_result(\n    mod, map_inputs, out_shape, result, tol=1e-5, target=\"llvm\", device=tvm.cpu()\n):\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"AlterOpLayout\"]):\n        executor_factory = relay.build(mod, target=target)\n    lib = update_lib(executor_factory.lib)\n    rt_mod = tvm.contrib.graph_executor.create(executor_factory.graph_json, lib, device)\n\n    for name, data in map_inputs.items():\n        rt_mod.set_input(name, data)\n    rt_mod.run()\n    out = tvm.nd.empty(out_shape, device=device)\n    out = rt_mod.get_output(0, out)\n\n    tvm.testing.assert_allclose(out.numpy(), result, rtol=tol, atol=tol)\n\n\ndef check_aot_executor_result(\n    mod, map_inputs, out_shape, result, tol=1e-5, target=\"llvm\", device=tvm.cpu()\n):\n    # Late import to avoid breaking test with USE_MICRO=OFF.\n    from tvm.testing.aot import AOTTestModel, compile_and_run\n    from tvm.micro.testing.aot_test_utils import AOT_DEFAULT_RUNNER\n\n    interface_api = \"packed\"\n    use_unpacked_api = False\n    test_runner = AOT_DEFAULT_RUNNER\n    compile_and_run(\n        AOTTestModel(module=mod, inputs=map_inputs, outputs={\"output\": result}),\n        test_runner,\n        interface_api,\n        use_unpacked_api,\n    )\n\n\ndef set_external_func_attr(func, compiler, ext_symbol):\n    func = func.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n    func = func.with_attr(\"Compiler\", compiler)\n    func = func.with_attr(\"global_symbol\", ext_symbol)\n    return func\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/relay/utils/ref_funcs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\n\ndef gather_nd(data_np, indices_np, batch_dims=0):\n    \"\"\"gather_nd implemented using numpy\"\"\"\n    data_shape = data_np.shape\n    indices_shape = indices_np.shape\n\n    def gather_nd_batch_dims_1_ref(data, indices):\n        res = []\n        for i, row in enumerate(data):\n            indices_tuple = tuple(indices[:, i])  # the indices for the i-th batch\n            res.append(row[indices_tuple])\n        # stack on the batch dim\n        return np.stack(res, 0)\n\n    if batch_dims > 1:\n        data_np_reshape = np.reshape(data_np, (-1,) + data_shape[batch_dims:])\n        indices_np_reshape = np.reshape(\n            indices_np, (indices_shape[0], -1) + indices_shape[(batch_dims + 1) :]\n        )\n\n        ref_res = gather_nd_batch_dims_1_ref(data_np_reshape, indices_np_reshape)\n\n        out_shape = indices_shape[1 : (batch_dims + 1)] + ref_res.shape[1:]\n        ref_res = np.reshape(ref_res, out_shape)\n    elif batch_dims == 1:\n        ref_res = gather_nd_batch_dims_1_ref(data_np, indices_np)\n    else:\n        ref_res = data_np[tuple(indices_np)]\n\n    return ref_res\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/target/test_arm_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm.topi.arm_cpu.conv2d_int8 import is_int8_hw_support\nfrom tvm.target import codegen\n\nllvm_version, arm_target, input_dtype, kernel_dtype, is_supported = tvm.testing.parameters(\n    # Testing mcpu type\n    (8, \"c -mcpu=cortex-m4\", \"int8\", \"int8\", False),\n    (8, \"c -mcpu=cortex-m7\", \"int8\", \"int8\", False),\n    (8, \"c -mcpu=cortex-m33\", \"int8\", \"int8\", False),\n    (8, \"c -mcpu=cortex-m55\", \"int8\", \"int8\", False),\n    (8, \"c -mcpu=cortex-m3\", \"int8\", \"int8\", False),\n    (7, \"llvm -mtriple=arm-linux-gnueabi -mattr=+neon\", \"int8\", \"int8\", False),\n    (8, \"llvm -mtriple=arm-linux-gnueabi -mattr=+neon\", \"int8\", \"int8\", True),\n    (9, \"llvm -mtriple=arm-linux-gnueabi -mattr=+neon\", \"int8\", \"int8\", True),\n    (8, \"llvm -mtriple=arm-linux-gnueabi\", \"int8\", \"int8\", False),\n    (7, \"llvm -mtriple=aarch64-linux-gnu -mattr=+v8.4a,+dotprod\", \"int8\", \"int8\", False),\n    (8, \"llvm -mtriple=aarch64-linux-gnu -mattr=+v8.4a,+dotprod\", \"int8\", \"int8\", True),\n    (9, \"llvm -mtriple=arm-linux-gnueabi -mattr=+neon\", \"int8\", \"int8\", True),\n    (8, \"llvm -mtriple=aarch64-linux-gnu\", \"int8\", \"int8\", True),\n    # Testing dtype\n    (8, \"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\", \"int16\", \"int8\", False),\n    (8, \"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\", \"int8\", \"int16\", False),\n    (8, \"llvm -mtriple=aarch64-linux-gnu -mattr=+neon\", \"int16\", \"int16\", False),\n)\n\n\ndef test_arm_conv2d_int8_support(\n    monkeypatch, llvm_version, arm_target, input_dtype, kernel_dtype, is_supported\n):\n    \"\"\"Test ARM conv2d int8 support for different targets.\n\n    Parameters\n    ----------\n    arm_target : str\n        ARM CPU target.\n    input_dtype : str\n        Conv2d input data type.\n    kernel_dtype : Session\n        Conv2d kernel data type.\n    is_supported : bool\n        Expected result.\n    \"\"\"\n    with tvm.target.Target(arm_target):\n        monkeypatch.setattr(codegen, \"llvm_version_major\", lambda: llvm_version)\n        assert is_int8_hw_support(input_dtype, kernel_dtype) == is_supported\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/target/test_virtual_device.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nimport tvm.testing\n\n\ndef test_make_virtual_device_for_device():\n    virtual_device = tvm.target.VirtualDevice(tvm.device(\"cuda\"))\n    assert virtual_device.device_type == 2\n    # ie kDLCUDA\n    assert virtual_device.virtual_device_id == 0\n    assert virtual_device.target is None\n    assert virtual_device.memory_scope == \"\"\n\n\ndef test_make_virtual_device_for_device_and_target():\n    target = tvm.target.Target(\"cuda\")\n    virtual_device = tvm.target.VirtualDevice(tvm.device(\"cuda\"), target)\n    assert virtual_device.device_type == 2  # ie kDLCUDA\n    assert virtual_device.target == target\n    assert virtual_device.memory_scope == \"\"\n\n\ndef test_make_virtual_device_for_device_target_and_memory_scope():\n    target = tvm.target.Target(\"cuda\")\n    scope = \"local\"\n    virtual_device = tvm.target.VirtualDevice(tvm.device(\"cuda\"), target, scope)\n    assert virtual_device.device_type == 2  # ie kDLCUDA\n    assert virtual_device.target == target\n    assert virtual_device.memory_scope == scope\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/tir/analysis/test_device_constraint_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test retrieving and applying memory scope constraints to PrimFuncs\"\"\"\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm import relay\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef gem(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], scope=\"scopeA\")\n    B = T.match_buffer(b, [128, 128], scope=\"scopeA\")\n    C = T.match_buffer(c, [128, 128], scope=\"scopeB\")\n    D = T.match_buffer(d, [128, 128], scope=\"scopeC\")\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                D[vi, vj] = C[vi, vj]\n            D[vi, vj] = D[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\ngem_ty = relay.FuncType(\n    [\n        relay.TupleType(\n            [\n                relay.TensorType((128, 128), \"float32\"),\n                relay.TensorType((128, 128), \"float32\"),\n            ]\n        ),\n        relay.TensorType((128, 128), \"float32\"),\n    ],\n    relay.TensorType((128, 128), \"float32\"),\n)\n\n\ndef test_get_prim_func_arg_and_result_constraints():\n    scopes = tir.analysis.get_prim_func_arg_and_result_memory_constraints(gem, gem_ty)\n    assert [x for x in scopes] == [\"scopeA\", \"scopeB\", \"scopeC\"]\n\n\ndef test_apply_prim_func_arg_and_result_memory_constraints():\n    rewritten = tir.analysis.apply_prim_func_arg_and_result_memory_constraints(\n        gem, gem_ty, [\"scopeX\", \"scopeY\", \"scopeZ\"]\n    )\n    scopes = tir.analysis.get_prim_func_arg_and_result_memory_constraints(rewritten, gem_ty)\n    assert [x for x in scopes] == [\"scopeX\", \"scopeY\", \"scopeZ\"]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/common.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Common utility for topi test\"\"\"\n\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import FallbackConfigEntity\n\n\nclass Int8Fallback(autotvm.FallbackContext):\n    def _query_inside(self, target, workload):\n        key = (target, workload)\n        if key in self.memory:\n            return self.memory[key]\n        cfg = FallbackConfigEntity()\n        self.memory[key] = cfg\n        cfg.is_fallback = False\n        return cfg\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_fifo_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for FIFO buffer\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nimport numpy as np\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_fifo_buffer(buffer_shape, data_shape, axis, dtype=\"float32\"):\n    buffer = te.placeholder(buffer_shape, name=\"buffer\", dtype=dtype)\n    data = te.placeholder(data_shape, name=\"data\", dtype=dtype)\n\n    # Use memoize, pickle the test data for next time use\n    @memoize(\"topi.tests.test_fifo_buffer\")\n    def get_ref_data():\n        buffer_np = np.random.uniform(size=buffer_shape).astype(dtype)\n        data_np = np.random.uniform(size=data_shape).astype(dtype)\n\n        # Reference implementation of FIFO queue\n        begin = data_np.shape[axis]\n        end = buffer_np.shape[axis] + data_np.shape[axis]\n        ndim = len(buffer_np.shape)\n        ss = tuple((slice(begin, end, 1) if x == axis else slice(None)) for x in range(ndim))\n        out_np = np.concatenate((buffer_np, data_np), axis=axis)[ss]\n        return (buffer_np, data_np, out_np)\n\n    # Get the test data\n    buffer_np, data_np, out_np = get_ref_data()\n\n    def check_device(target, dev):\n        print(\"  Running on target: {}\".format(target))\n\n        with tvm.target.Target(target):\n            out = topi.nn.fifo_buffer(data, buffer, axis=axis)\n            s = tvm.topi.testing.get_injective_schedule(target)([out])\n\n        buffer_tvm = tvm.nd.array(buffer_np, device=dev)\n        data_tvm = tvm.nd.array(data_np, device=dev)\n        out_tvm = tvm.nd.empty(shape=buffer_shape, device=dev, dtype=dtype)\n        f = tvm.build(s, [data, buffer, out], target, name=\"fifo\")\n        f(data_tvm, buffer_tvm, out_tvm)\n        tvm.testing.assert_allclose(out_tvm.numpy(), out_np)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_conv1d_integration():\n    batch_size = 1\n    num_channel = 1\n    num_filter = 1\n\n    # Note: TVM doesn't have a separate op for 1D convolution, so we use conv2d instead.\n    # We set height=1 to indicate that convolution is really 1D.\n    stride = (1, 1)\n    dilate = (1, 1)\n    padding = (0, 0)\n\n    kernel_size = (1, 3)\n    input_window_size = (1, 10)\n    inc_input_size = (1, 2)\n    context_size = (1, 4)\n    inc_output_size = (1, 2)\n    output_window_size = (1, 8)\n\n    num_iteration = 20\n    buffer_axis = 3\n\n    kernel_shape = (num_filter, num_channel, kernel_size[0], kernel_size[1])\n    input_window_shape = (batch_size, num_channel, input_window_size[0], input_window_size[1])\n    inc_input_shape = (batch_size, num_channel, inc_input_size[0], inc_input_size[1])\n    inc_output_shape = (batch_size, num_filter, inc_output_size[0], inc_output_size[1])\n    context_shape = (batch_size, num_channel, context_size[0], context_size[1])\n    output_window_shape = (batch_size, num_filter, output_window_size[0], output_window_size[1])\n    # Rule: Convolution of Tensor[context_shape] and Tensor[kernel_shape]\n    #       produces Tensor[inc_input_shape]\n\n    dtype = \"float32\"\n\n    inc_input = te.placeholder(inc_input_shape, name=\"inc_input\", dtype=dtype)\n    input_window = te.placeholder(input_window_shape, name=\"input_window\", dtype=dtype)\n    context = te.placeholder(context_shape, name=\"context\", dtype=dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=dtype)\n    inc_output = te.placeholder(inc_input_shape, name=\"inc_output\", dtype=dtype)\n    output_window = te.placeholder(output_window_shape, name=\"output_window\", dtype=dtype)\n\n    # Use memoize, pickle the test data for next time use\n    @memoize(\"topi.tests.test_fifo_buffer_conv1d_integration\")\n    def get_data():\n        # Generate [num_iteration] slices of input\n        inc_input_np = np.random.uniform(\n            size=tuple([num_iteration] + list(inc_input_shape))\n        ).astype(dtype)\n        input_window_np = np.zeros(input_window_shape, dtype=dtype)\n        kernel_np = np.random.uniform(size=kernel_shape).astype(dtype)\n        context_np = np.zeros(context_shape, dtype=dtype)\n        output_window_np = np.zeros(output_window_shape, dtype=dtype)\n\n        return (inc_input_np, input_window_np, kernel_np, context_np, output_window_np)\n\n    # Get the test data\n    inc_input_np, input_window_np, kernel_np, context_np, output_window_np = get_data()\n\n    def check_device(target, dev):\n        print(\"  Running on target: {}\".format(target))\n\n        conv2d_nchw, schedule_conv2d_nchw = tvm.topi.testing.get_conv2d_nchw_implement(target)\n\n        with tvm.target.Target(target):\n            out = topi.nn.fifo_buffer(inc_input, context, axis=buffer_axis)\n            s = tvm.topi.testing.get_injective_schedule(target)([out])\n            update_context = tvm.build(s, [inc_input, context, out], target, name=\"update_context\")\n\n            out = conv2d_nchw(context, kernel, stride, padding, dilate, dtype)\n            s = schedule_conv2d_nchw([out])\n            conv2d_inc = tvm.build(s, [context, kernel, out], target, name=\"conv2d_inc\")\n\n            out = topi.nn.fifo_buffer(inc_output, output_window, axis=buffer_axis)\n            s = tvm.topi.testing.get_injective_schedule(target)([out])\n            update_output_window = tvm.build(\n                s, [inc_output, output_window, out], target, name=\"update_output_window\"\n            )\n\n            out = topi.nn.fifo_buffer(inc_input, input_window, axis=buffer_axis)\n            s = tvm.topi.testing.get_injective_schedule(target)([out])\n            update_input_window = tvm.build(\n                s, [inc_input, input_window, out], target, name=\"update_input_window\"\n            )\n\n            out = conv2d_nchw(input_window, kernel, stride, padding, dilate, dtype)\n            s = schedule_conv2d_nchw([out])\n            conv2d = tvm.build(s, [input_window, kernel, out], target, name=\"conv2d\")\n\n        input_window_tvm = tvm.nd.array(input_window_np, device=dev)\n        new_input_window_tvm = tvm.nd.empty(shape=input_window_shape, device=dev, dtype=dtype)\n        kernel_tvm = tvm.nd.array(kernel_np, device=dev)\n        context_tvm = tvm.nd.array(context_np, device=dev)\n        new_context_tvm = tvm.nd.empty(shape=context_shape, device=dev, dtype=dtype)\n        inc_output_tvm = tvm.nd.empty(shape=inc_output_shape, device=dev, dtype=dtype)\n        output_window_tvm = tvm.nd.array(output_window_np, device=dev)\n        new_output_window_tvm = tvm.nd.empty(shape=output_window_shape, device=dev, dtype=dtype)\n        output_window_ref_tvm = tvm.nd.empty(shape=output_window_shape, device=dev, dtype=dtype)\n\n        for i in range(num_iteration):\n            # Take i-th slice of inc_input_np\n            inc_input_tvm = tvm.nd.array(inc_input_np[i], device=dev)\n\n            # Compute new output window incrementally, using the FIFO buffer op\n            update_context(inc_input_tvm, context_tvm, new_context_tvm)\n            conv2d_inc(new_context_tvm, kernel_tvm, inc_output_tvm)\n            update_output_window(inc_output_tvm, output_window_tvm, new_output_window_tvm)\n            context_tvm = new_context_tvm\n            output_window_tvm = new_output_window_tvm\n\n            # Compute full input window, so that we have a baseline\n            update_input_window(inc_input_tvm, input_window_tvm, new_input_window_tvm)\n            input_window_tvm = new_input_window_tvm\n            conv2d(input_window_tvm, kernel_tvm, output_window_ref_tvm)\n            # Incrementally updating the output window should be equivalent to computing it from\n            # scratch using the input window\n            tvm.testing.assert_allclose(output_window_tvm.numpy(), output_window_ref_tvm.numpy())\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_fifo_buffer():\n    for ndim in [1, 2, 3, 4, 5, 6]:\n        for axis in range(ndim):\n            buffer_shape = tuple(7 for _ in range(ndim))\n            data_shape = tuple((2 if i == axis else 7) for i in range(ndim))\n            print(\n                \"Testing FIFO buffer op: buffer_shape = {}, data_shape = {}, axis = {}\".format(\n                    buffer_shape, data_shape, axis\n                )\n            )\n            verify_fifo_buffer(buffer_shape, data_shape, axis)\n\n\n@tvm.testing.uses_gpu\ndef test_conv1d_integration():\n    print(\"Testing FIFO buffer with 1D convolution\")\n    verify_conv1d_integration()\n\n\nif __name__ == \"__main__\":\n    test_fifo_buffer()\n    test_conv1d_integration()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_argwhere.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test for argwhere operator\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\n\n_argwhere_schedule = {\n    \"generic\": topi.generic.schedule_argwhere,\n    \"gpu\": topi.cuda.schedule_argwhere,\n}\n\n_argwhere_compute = {\"llvm\": topi.argwhere, \"cuda\": topi.cuda.argwhere}\n\ndata_shape = tvm.testing.parameter(\n    (1,),\n    (100,),\n    (1, 1),\n    (5, 3),\n    (32, 64),\n    (128, 65),\n    (200, 500),\n    (6, 5, 3),\n    (1, 1, 1),\n    (1, 1, 1, 1),\n    (6, 4, 5, 3),\n    (1, 1, 1, 1, 1),\n    (6, 4, 5, 3, 7),\n)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\ndef test_argwhere(target, dev, data_shape):\n    dtype = \"int32\"\n    np_data = np.random.choice([0, 1, 2, 3], size=data_shape).astype(dtype)\n    np_out = np.argwhere(np_data)\n    out_shape = np_out.shape[0]\n\n    np_shape = np.ones(shape=(out_shape, len(data_shape)), dtype=dtype)\n\n    out_shape = te.placeholder(shape=(out_shape, len(data_shape)), name=\"out_shape\", dtype=dtype)\n    condition = te.placeholder(shape=data_shape, name=\"condition\", dtype=dtype)\n\n    with tvm.target.Target(target):\n        out = _argwhere_compute[target](out_shape, condition)\n        s_func = tvm.topi.testing.dispatch(target, _argwhere_schedule)\n        sch = s_func(out)\n\n    func = tvm.build(sch, [out_shape, condition, out], target, name=\"argwhere\")\n\n    args = [tvm.nd.array(np_shape, dev)]\n    args.append(tvm.nd.array(np_data, dev))\n    args.append(tvm.nd.empty(out.shape, device=dev, dtype=condition.dtype))\n    func(*args)\n    np.set_printoptions(threshold=np.inf)\n    tvm_out = args[-1].numpy()\n    tvm.testing.assert_allclose(tvm_out, np_out)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_basic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi import utils\n\n\ndef test_util():\n    x = tvm.tir.const(100, \"int32\")\n    assert utils.get_const_int(x) == 100\n    assert utils.get_const_tuple((x, x)) == (100, 100)\n\n\ndef test_ewise():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n\n    def test_apply(func, name):\n        B = func(A)\n        assert tuple(B.shape) == tuple(A.shape)\n        assert B.op.body[0].op.name == \"tir.\" + name\n\n    test_apply(topi.exp, \"exp\")\n    test_apply(topi.erf, \"erf\")\n    test_apply(topi.tanh, \"tanh\")\n    test_apply(topi.sigmoid, \"sigmoid\")\n    test_apply(topi.log, \"log\")\n    test_apply(topi.sqrt, \"sqrt\")\n    test_apply(topi.rsqrt, \"rsqrt\")\n    test_apply(topi.sin, \"sin\")\n    test_apply(topi.cos, \"cos\")\n    test_apply(topi.tan, \"tan\")\n    test_apply(topi.atan, \"atan\")\n\n\nif __name__ == \"__main__\":\n    test_util()\n    test_ewise()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_batch_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for batch_matmul operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\nimport tvm.testing\nfrom common import Int8Fallback\n\n_batch_matmul_implement = {\n    \"generic\": (topi.nn.batch_matmul, topi.generic.schedule_batch_matmul),\n    \"cpu\": (topi.x86.batch_matmul, topi.x86.schedule_batch_matmul),\n    \"gpu\": (topi.cuda.batch_matmul, topi.cuda.schedule_batch_matmul),\n}\n\n\ndef verify_batch_matmul(x_batch, y_batch, M, N, K, dynamic=False, debug=False):\n\n    if not dynamic:\n        x = te.placeholder((x_batch, M, K), name=\"x\")\n        y = te.placeholder((y_batch, N, K), name=\"y\")\n        dtype = x.dtype\n    else:\n        assert x_batch == y_batch or x_batch == 1 or y_batch == 1\n        batch_size = max(x_batch, y_batch)\n        dynamic_batch_size = te.var(\"dynamic_batch_size\")\n        dynamic_M = te.var(\"dynamic_M\")\n        dynamic_N = te.var(\"dynamic_N\")\n        dynamic_K = te.var(\"dynamic_K\")\n\n        x = te.placeholder((dynamic_batch_size, dynamic_M, dynamic_K), name=\"x\")\n        y = te.placeholder((dynamic_batch_size, dynamic_N, dynamic_K), name=\"y\")\n        dtype = x.dtype\n\n    # use memoize to pickle the test data for next time use\n    @memoize(\"topi.tests.test_topi_batch_matmul\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=(x_batch, M, K)).astype(dtype)\n        b_np = np.random.uniform(size=(y_batch, N, K)).astype(dtype)\n        c_np = tvm.topi.testing.batch_matmul(a_np, b_np)\n        return (a_np, b_np, c_np)\n\n    # get the test data\n    a_np, b_np, c_np = get_ref_data()\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _batch_matmul_implement)\n            out = fcompute(x, y)\n            if not dynamic:\n                s = fschedule([out])\n                out_shape = out.shape\n            else:\n                s = te.create_schedule(out.op)\n                out_shape = (batch_size, M, N)\n\n            if debug:\n                print(tvm.lower(s, [x, y, out], simple_mode=True))\n\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(out_shape), dtype=dtype), dev)\n        f = tvm.build(s, [x, y, out], target, name=\"dense\")\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        target_kind = tvm.target.Target(target).kind.name\n        if dynamic and target_kind in [\"cuda\", \"nvptx\", \"vulkan\", \"opencl\"]:\n            print(\"Dynamic batch matmul test is skippped on %s\" % target)\n            continue\n\n        check_device(target, dev)\n\n\ndef verify_batch_matmul_int8(x_batch, y_batch, M, N, K):\n    dtype = \"int8\"\n    out_dtype = \"int32\"\n    assert x_batch == y_batch or x_batch == 1 or y_batch == 1\n    x = te.placeholder((x_batch, M, K), name=\"x\", dtype=dtype)\n    y = te.placeholder((y_batch, N, K), name=\"y\", dtype=dtype)\n\n    # use memoize to pickle the test data for next time use\n    @memoize(\"topi.tests.test_topi_batch_matmul\")\n    def get_ref_data():\n        a_np = np.random.randint(low=-128, high=127, size=(x_batch, M, K)).astype(dtype)\n        b_np = np.random.randint(low=-128, high=127, size=(y_batch, N, K)).astype(dtype)\n        c_np = tvm.topi.testing.batch_matmul(a_np, b_np, out_dtype=out_dtype)\n        return (a_np, b_np, c_np)\n\n    # get the test data\n    a_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if device == \"cuda\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            print(\"Skip because int8 intrinsics are not available\")\n            return\n\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            out = topi.cuda.batch_matmul_int8(x, y, None, out_dtype)\n            s = topi.cuda.schedule_batch_matmul_int8([out])\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(out.shape), dtype=out_dtype), dev)\n        f = tvm.build(s, [x, y, out], device, name=\"batch_matmul_int8\")\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for device in [\"cuda\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_batch_matmul():\n    verify_batch_matmul(1, 1, 16, 16, 32)\n    verify_batch_matmul(5, 5, 16, 16, 32)\n    verify_batch_matmul(5, 5, 16, 20, 32)\n    verify_batch_matmul(30, 30, 16, 20, 32)\n    # Test batch broadcasting.\n    verify_batch_matmul(1, 5, 16, 16, 32)\n    verify_batch_matmul(5, 1, 16, 16, 32)\n\n    # Test dynamic batch\n    verify_batch_matmul(1, 1, 16, 16, 32, dynamic=True)\n    verify_batch_matmul(5, 5, 16, 16, 32, dynamic=True)\n\n\n@tvm.testing.requires_cuda\n@tvm.testing.requires_gpu\ndef test_batch_matmul_int8():\n    with Int8Fallback():\n        verify_batch_matmul_int8(1, 1, 2, 3, 1)\n        verify_batch_matmul_int8(1, 1, 16, 24, 32)\n        verify_batch_matmul_int8(5, 5, 24, 16, 32)\n        verify_batch_matmul_int8(30, 30, 16, 20, 32)\n        verify_batch_matmul_int8(1, 5, 16, 16, 32)\n        verify_batch_matmul_int8(5, 1, 16, 16, 32)\n\n\nif __name__ == \"__main__\":\n    test_batch_matmul()\n    test_batch_matmul_int8()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_batch_matmul_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for batch_matmul operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\nimport tvm.testing\n\n_batch_matmul_implement = {\n    \"gpu\": (topi.cuda.batch_matmul_tensorcore, topi.cuda.schedule_batch_matmul_tensorcore),\n}\n\n\ndef convert_int32_into_int4(a_int32):\n    \"\"\"convert int32 values into int4\n    Parameters\n    ----------\n    a_int32 : int\n\n    Return\n    ------\n    a_int4 : int\n    \"\"\"\n    B, K, L = a_int32.shape\n    assert L % 8 == 0\n    a_int4 = np.zeros(shape=(B, K, L // 8), dtype=np.int32)\n    for b in range(B):\n        for k in range(K):\n            for l in range(L // 8):\n                for m in range(min(8, L - l * 8)):\n                    a_int4[b, k, l] = a_int4[b, k, l] | (\n                        (a_int32[b, k, l * 8 + m] & 0xF) << ((7 - m) * 4)\n                    )\n    return a_int4\n\n\ndef verify_batch_matmul(x_batch, y_batch, M, N, K, dtype):\n    x = te.placeholder((x_batch, M, K), name=\"x\", dtype=dtype)\n    y = te.placeholder((y_batch, N, K), name=\"y\", dtype=dtype)\n\n    assert dtype in [\"int4\", \"int8\", \"float16\"]\n\n    out_dtype = \"float32\"\n    if dtype in [\"int8\", \"int4\"]:\n        out_dtype = \"int32\"\n\n    # use memoize to pickle the test data for next time use\n    @memoize(\"topi.tests.test_topi_batch_matmul_tensorcore\")\n    def get_ref_data():\n        if dtype == \"int4\":\n            a_np = np.random.randint(low=-8, high=7, size=(x_batch, M, K))\n            b_np = np.random.randint(low=-8, high=7, size=(y_batch, N, K))\n        elif dtype == \"int8\":\n            a_np = np.random.randint(low=-128, high=127, size=(x_batch, M, K)).astype(dtype)\n            b_np = np.random.randint(low=-128, high=127, size=(y_batch, N, K)).astype(dtype)\n        else:\n            a_np = np.random.uniform(size=(x_batch, M, K)).astype(dtype)\n            b_np = np.random.uniform(size=(y_batch, N, K)).astype(dtype)\n        c_np = tvm.topi.testing.batch_matmul(a_np, b_np, out_dtype)\n        return (a_np, b_np, c_np)\n\n    # get the test data\n    a_np, b_np, c_np = get_ref_data()\n    if dtype == \"int4\":\n        a_np = convert_int32_into_int4(a_np)\n        b_np = convert_int32_into_int4(b_np)\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            fcompute, fschedule = tvm.topi.testing.dispatch(device, _batch_matmul_implement)\n            out = fcompute(x, y, None, out_dtype)\n            s = fschedule([out])\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(out.shape), dtype=out_dtype), dev)\n        f = tvm.build(s, [x, y, out], device, name=\"batch_matmul\")\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3)\n\n    check_device(\"cuda\")\n\n\n@tvm.testing.requires_tensorcore\ndef test_batch_matmul():\n    for dtype in [\"float16\", \"int8\", \"int4\"]:\n        verify_batch_matmul(1, 1, 16, 16, 32, dtype)\n        verify_batch_matmul(5, 5, 16, 16, 32, dtype)\n        verify_batch_matmul(5, 5, 16, 32, 32, dtype)\n        verify_batch_matmul(30, 30, 16, 32, 32, dtype)\n\n\nif __name__ == \"__main__\":\n    test_batch_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_batch_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for the batch_norm operator.\"\"\"\nimport numpy as np\nimport pytest\n\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\n_DEVICE = \"llvm\"\n_BATCH_NORM_IMPLEMENT = {\n    \"generic\": (topi.nn.batch_norm, topi.generic.schedule_batch_norm),\n    \"cpu\": (topi.nn.batch_norm, topi.x86.schedule_batch_norm),\n}\n\n\n@pytest.mark.parametrize(\n    \"shape, axis, epsilon, center, scale\",\n    [\n        ((1,), 0, 0.1, True, True),\n        ((2, 3), 0, 0.1, True, True),\n        ((1, 2, 4), 0, 0.1, True, True),\n        ((1, 2, 3, 4), 0, 0.001, False, False),\n        ((2, 3, 4, 1), 1, 0.01, False, True),\n        ((3, 4, 1, 2), 2, 0.1, True, False),\n        ((4, 1, 2, 3), 3, 1.0, True, True),\n        ((1, 2, 4, 4, 5), 0, 0.1, True, True),\n    ],\n)\ndef test_batch_norm(shape, axis, epsilon, center, scale):\n    x_np = np.random.random(shape).astype(\"float32\")\n    gamma_np = np.random.random(shape[axis]).astype(\"float32\")\n    beta_np = np.random.random(shape[axis]).astype(\"float32\")\n    moving_mean_np = np.random.random(shape[axis]).astype(\"float32\")\n    moving_var_np = np.random.random(shape[axis]).astype(\"float32\")\n\n    out_x_np, out_moving_mean_np, out_moving_var_np = tvm.topi.testing.batch_norm(\n        x_np, gamma_np, beta_np, moving_mean_np, moving_var_np, axis, epsilon, center, scale\n    )\n\n    x_te = te.placeholder(shape, name=\"x\", dtype=\"float32\")\n    gamma_te = te.placeholder((shape[axis],), name=\"gamma\", dtype=\"float32\")\n    beta_te = te.placeholder((shape[axis],), name=\"beta\", dtype=\"float32\")\n    moving_mean_te = te.placeholder((shape[axis],), name=\"moving_mean\", dtype=\"float32\")\n    moving_var_te = te.placeholder((shape[axis],), name=\"moving_var\", dtype=\"float32\")\n\n    with tvm.target.Target(_DEVICE):\n        fcompute, fschedule = tvm.topi.testing.dispatch(_DEVICE, _BATCH_NORM_IMPLEMENT)\n        out_x, out_moving_mean, out_moving_var = fcompute(\n            x_te, gamma_te, beta_te, moving_mean_te, moving_var_te, axis, epsilon, center, scale\n        )\n        s = fschedule([out_x, out_moving_mean, out_moving_var])\n\n        dev = tvm.device(_DEVICE, 0)\n\n        x_tvm = tvm.nd.array(x_np, dev)\n        gamma_tvm = tvm.nd.array(gamma_np, dev)\n        beta_tvm = tvm.nd.array(beta_np, dev)\n        moving_mean_tvm = tvm.nd.array(moving_mean_np, dev)\n        moving_var_tvm = tvm.nd.array(moving_var_np, dev)\n        out_x_tvm = tvm.nd.array(np.zeros(shape, dtype=out_x.dtype), dev)\n        out_moving_mean_tvm = tvm.nd.array(\n            np.zeros((shape[axis],), dtype=out_moving_mean.dtype), dev\n        )\n        out_moving_var_tvm = tvm.nd.array(np.zeros((shape[axis],), dtype=out_moving_var.dtype), dev)\n\n        f = tvm.build(\n            s,\n            [\n                x_te,\n                gamma_te,\n                beta_te,\n                moving_mean_te,\n                moving_var_te,\n                out_x,\n                out_moving_mean,\n                out_moving_var,\n            ],\n            _DEVICE,\n        )\n        f(\n            x_tvm,\n            gamma_tvm,\n            beta_tvm,\n            moving_mean_tvm,\n            moving_var_tvm,\n            out_x_tvm,\n            out_moving_mean_tvm,\n            out_moving_var_tvm,\n        )\n\n        tvm.testing.assert_allclose(out_x_tvm.numpy(), out_x_np, rtol=1e-3)\n        tvm.testing.assert_allclose(out_moving_mean_tvm.numpy(), out_moving_mean_np, rtol=1e-3)\n        tvm.testing.assert_allclose(out_moving_var_tvm.numpy(), out_moving_var_np, rtol=1e-3)\n\n\nif __name__ == \"__main__\":\n    test_batch_norm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_batch_to_space_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for batch to space\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_batch_to_space_nd(input_shape, block_shape, crop_begin_list, crop_end_list):\n    out_shape = []\n    out_shape.append(int((input_shape[0] / np.prod(block_shape))))\n    for i in range(1, len(block_shape) + 1):\n        crop = crop_begin_list[i - 1] + crop_end_list[i - 1]\n        out_shape.append(input_shape[i] * block_shape[i - 1] - crop)\n    for i in range(len(block_shape) + 1, len(input_shape)):\n        out_shape.append(input_shape[i])\n\n    A = te.placeholder(input_shape, name=\"A\", dtype=\"float32\")\n    dtype = A.dtype\n    a_np = np.random.uniform(size=input_shape).astype(dtype)\n\n    B = topi.nn.batch_to_space_nd(A, block_shape, crop_begin_list, crop_end_list)\n\n    b_np = tvm.topi.testing.batch_to_space_nd_python(\n        a_np, block_shape, crop_begin_list, crop_end_list\n    )\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.create(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_batch_to_space():\n    # Without crops\n    verify_batch_to_space_nd([4, 1, 1, 1], [2, 2], [0, 0], [0, 0])\n    # With crops\n    verify_batch_to_space_nd([8, 1, 3, 1], [2, 2], [0, 2], [0, 0])\n    verify_batch_to_space_nd([18, 2, 1, 2], [2, 3], [1, 1], [0, 0])\n    verify_batch_to_space_nd([20, 5, 8, 7], [2, 2], [1, 1], [1, 1])\n\n\nif __name__ == \"__main__\":\n    test_batch_to_space()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_bitserial_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef generate_quantized_np(shape, bits, out_dtype):\n    min_val = 0\n    max_val = 1 << bits\n    return np.random.randint(min_val, max_val, size=shape).astype(out_dtype)\n\n\ndef verify_bitserial_conv2d_nchw(\n    batch,\n    in_size,\n    in_channel,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    unipolar,\n):\n    in_height = in_width = in_size\n    input_dtype = \"uint32\"\n    out_dtype = \"int32\"\n\n    with tvm.target.Target(\"llvm\"):\n        A = te.placeholder((batch, in_channel, in_height, in_width), dtype=input_dtype, name=\"A\")\n        W = te.placeholder((num_filter, in_channel, kernel, kernel), dtype=input_dtype, name=\"W\")\n        B = topi.x86.bitserial_conv2d_nchw(\n            A, W, stride, padding, activation_bits, weight_bits, input_dtype, out_dtype, unipolar\n        )\n        s = topi.x86.schedule_bitserial_conv2d_nchw([B])\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n\n    @memoize(\"topi.tests.test_topi_bitseral_conv2d_nchw\")\n    def get_ref_data():\n        a_np = generate_quantized_np(get_const_tuple(a_shape), activation_bits, input_dtype)\n        w_np = generate_quantized_np(get_const_tuple(w_shape), weight_bits, input_dtype)\n        if unipolar:\n            w_ = np.copy(w_np).astype(out_dtype)\n            for x in np.nditer(w_, op_flags=[\"readwrite\"]):\n                x[...] = 1 if x == 1 else -1\n            b_np = tvm.topi.testing.conv2d_nchw_python(a_np.astype(out_dtype), w_, stride, padding)\n        else:\n            b_np = tvm.topi.testing.conv2d_nchw_python(a_np, w_np, stride, padding)\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data()\n\n    dev = tvm.cpu(0)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], \"llvm\")\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\ndef verify_bitserial_conv2d_nhwc(\n    batch,\n    in_size,\n    in_channel,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    unipolar,\n):\n    in_height = in_width = in_size\n    input_dtype = \"uint32\"\n    out_dtype = \"int32\"\n\n    with tvm.target.Target(\"llvm\"):\n        A = te.placeholder((batch, in_height, in_width, in_channel), dtype=input_dtype, name=\"A\")\n        W = te.placeholder((kernel, kernel, in_channel, num_filter), dtype=input_dtype, name=\"W\")\n        B = topi.x86.bitserial_conv2d_nhwc(\n            A, W, stride, padding, activation_bits, weight_bits, input_dtype, out_dtype, unipolar\n        )\n        s = topi.x86.schedule_bitserial_conv2d_nhwc([B])\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n\n    @memoize(\"topi.tests.test_topi_bitseral_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = generate_quantized_np(get_const_tuple(a_shape), activation_bits, input_dtype)\n        w_np = generate_quantized_np(get_const_tuple(w_shape), weight_bits, input_dtype)\n        if unipolar:\n            w_ = np.copy(w_np).astype(out_dtype)\n            for x in np.nditer(w_, op_flags=[\"readwrite\"]):\n                x[...] = 1 if x == 1 else -1\n            b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, w_, stride, padding).astype(out_dtype)\n        else:\n            b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, w_np, stride, padding).astype(\n                out_dtype\n            )\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data()\n\n    dev = tvm.cpu(0)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], \"llvm\")\n\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\ndef test_bitserial_conv2d():\n    in_size = 56\n    ic, oc = 64, 64\n    k = 3\n    stride = 1\n    pad = 1\n    verify_bitserial_conv2d_nchw(1, in_size, ic, oc, k, stride, pad, 1, 1, True)\n    verify_bitserial_conv2d_nchw(1, in_size, ic, oc, k, stride, pad, 2, 1, True)\n    verify_bitserial_conv2d_nchw(1, in_size, ic, oc, k, stride, pad, 1, 1, False)\n    verify_bitserial_conv2d_nchw(1, in_size, ic, oc, k, stride, pad, 2, 1, False)\n    verify_bitserial_conv2d_nchw(1, in_size, ic, oc, k, stride, pad, 2, 2, False)\n\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 1, 1, True)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 1, True)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 1, 1, False)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 1, False)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 2, False)\n\n\nif __name__ == \"__main__\":\n    test_bitserial_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_bitserial_conv2d_rasp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport re\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef generate_quantized_np(shape, bits, out_dtype):\n    np.random.seed(0)\n    min_val = 0\n    max_val = 1 << bits\n    return np.random.randint(min_val, max_val, size=shape).astype(out_dtype)\n\n\n# Verify that certain special instructions from the tensorize pass exist\ndef verify_bitserial_conv2d_nhwc(\n    batch,\n    in_size,\n    in_channel,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    activation_bits,\n    weight_bits,\n    unipolar,\n    use_relu=False,\n):\n    in_height = in_width = in_size\n    input_type = \"uint32\"\n    out_dtype = \"int16\"\n\n    device = \"llvm -device=arm_cpu -model=bcm2837 -mtriple=armv7l-linux-gnueabihf -mattr=+neon\"\n    with tvm.target.Target(device):\n        A = te.placeholder((batch, in_height, in_width, in_channel), dtype=input_type, name=\"A\")\n        W = te.placeholder((kernel, kernel, in_channel, num_filter), dtype=input_type, name=\"W\")\n        B = topi.arm_cpu.bitserial_conv2d_nhwc(\n            A, W, stride, padding, activation_bits, weight_bits, \"uint8\", out_dtype, unipolar\n        )\n        if use_relu:\n            B = topi.nn.relu(B)\n        s = topi.arm_cpu.schedule_bitserial_conv2d_nhwc([B])\n\n    func = tvm.build(s, [A, W, B], device)\n\n    assembly = func.get_source(\"asm\")\n    matches = re.findall(\"vpadal\", assembly)\n    assert len(matches) > 0\n    matches = re.findall(\"vcnt\", assembly)\n    assert len(matches) > 0\n    matches = re.findall(\"vpadd\", assembly)\n    assert len(matches) > 0\n\n    dev = tvm.device(device, 0)\n    if \"arm\" not in os.uname()[4]:\n        print(\"Skipped running code, not an arm device\")\n        return\n\n    print(\"Running on target: %s\" % device)\n\n    def get_ref_data():\n        a_np = generate_quantized_np(get_const_tuple(A.shape), activation_bits, input_type)\n        w_np = generate_quantized_np(get_const_tuple(W.shape), weight_bits, input_type)\n        if unipolar:\n            w_ = np.copy(w_np).astype(out_dtype)\n            for x in np.nditer(w_, op_flags=[\"readwrite\"]):\n                x[...] = 1 if x == 1 else -1\n            b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, w_, stride, padding).astype(out_dtype)\n        else:\n            b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, w_np, stride, padding).astype(\n                out_dtype\n            )\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data()\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], device)\n\n    func(a, w, b)\n    np.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\ndef test_bitserial_conv2d():\n    in_size = 56\n    ic, oc = 64, 64\n    k = 3\n    stride = 1\n    pad = 1\n\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 1, 1, False)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 1, False)\n\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 1, 1, True)\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 1, True)\n\n    verify_bitserial_conv2d_nhwc(1, in_size, ic, oc, k, stride, pad, 2, 1, True, True)\n\n\nif __name__ == \"__main__\":\n    test_bitserial_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_bitserial_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for bitserial_dense operator\"\"\"\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n_bitserial_dense_implement = {\n    \"generic\": (topi.nn.bitserial_dense, topi.generic.schedule_bitserial_dense),\n    \"cpu\": (topi.x86.bitserial_dense, topi.x86.schedule_bitserial_dense),\n    \"arm_cpu\": (topi.arm_cpu.bitserial_dense, topi.arm_cpu.schedule_bitserial_dense),\n}\n\n\ndef generate_quantized_np(shape, bits, out_dtype):\n    min_val = 0\n    max_val = 1 << bits\n    return np.random.randint(min_val, max_val, size=shape).astype(out_dtype)\n\n\ndef verify_bitserial_dense(batch, in_dim, out_dim, activation_bits, weight_bits, unipolar):\n    out_dtype = \"int16\"\n\n    def get_ref_data(a_shape, b_shape, input_dtype):\n        a_np = generate_quantized_np(get_const_tuple(a_shape), activation_bits, input_dtype)\n        b_np = generate_quantized_np(get_const_tuple(b_shape), weight_bits, input_dtype)\n        if unipolar:\n            b_ = np.copy(b_np).astype(out_dtype)\n            for x in np.nditer(b_, op_flags=[\"readwrite\"]):\n                x[...] = 1 if x == 1 else -1\n            c_np = np.dot(a_np, b_.T)\n        else:\n            c_np = np.dot(a_np, b_np.T)\n        return a_np, b_np, c_np\n\n    for target in [\"llvm\", \"llvm -device=arm_cpu\"]:\n        if \"arm_cpu\" in target and \"arm\" not in os.uname()[4]:\n            print(\"Skipped running code, not an arm device\")\n            continue\n        input_dtype = \"uint8\" if \"arm_cpu\" in target else \"uint32\"\n        A = te.placeholder((batch, in_dim), dtype=input_dtype, name=\"A\")\n        B = te.placeholder((out_dim, in_dim), dtype=input_dtype, name=\"B\")\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _bitserial_dense_implement)\n        C = fcompute(A, B, activation_bits, weight_bits, input_dtype, out_dtype, unipolar)\n        s = fschedule([C])\n\n        a_shape = get_const_tuple(A.shape)\n        b_shape = get_const_tuple(B.shape)\n        a_np, b_np, c_np = get_ref_data(a_shape, b_shape, input_dtype)\n\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        func = tvm.build(s, [A, B, C], target)\n        func(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\ndef test_bitserial_dense():\n    verify_bitserial_dense(1, 1024, 1000, 1, 1, True)\n    verify_bitserial_dense(1, 1024, 1000, 2, 1, True)\n\n    verify_bitserial_dense(1, 1024, 1000, 1, 1, False)\n    verify_bitserial_dense(1, 1024, 1000, 2, 1, False)\n\n\nif __name__ == \"__main__\":\n    test_bitserial_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_bnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for binary neural network operators.\"\"\"\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_binary_dense(batch, in_dim, out_dim):\n    A = te.placeholder((batch, in_dim), name=\"A\")\n    B = te.placeholder((out_dim, in_dim), name=\"B\")\n    bnn_A = topi.nn.binarize_pack(A)\n    bnn_B = topi.nn.binarize_pack(B)\n    # binary dense\n    bnn_A1 = te.placeholder(bnn_A.shape, dtype=bnn_A.dtype)\n    bnn_B1 = te.placeholder(bnn_B.shape, dtype=bnn_B.dtype)\n    bnn_C = topi.nn.binary_dense(bnn_A1, bnn_B1)\n    # schedule\n    with tvm.target.Target(\"llvm\"):\n        s1 = topi.x86.schedule_binarize_pack(bnn_A)\n        s2 = topi.x86.schedule_binarize_pack(bnn_B)\n        s3 = topi.x86.schedule_binary_dense(bnn_C)\n\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_binary_dense\")\n    def get_ref_data():\n        # generate random matrix of +1 or -1 value\n        a_np = (np.random.randint(2, size=(batch, in_dim)) * 2 - 1).astype(dtype)\n        b_np = (np.random.randint(2, size=(out_dim, in_dim)) * 2 - 1).astype(dtype)\n        c_np = np.dot(a_np, b_np.T)\n        return a_np, b_np, c_np\n\n    a_np, b_np, c_np = get_ref_data()\n\n    dev = tvm.cpu(0)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    bnn_a = tvm.nd.array(np.zeros(get_const_tuple(bnn_A.shape), dtype=bnn_A.dtype), dev)\n    bnn_b = tvm.nd.array(np.zeros(get_const_tuple(bnn_B.shape), dtype=bnn_B.dtype), dev)\n    bnn_c = tvm.nd.array(np.zeros(get_const_tuple(bnn_C.shape), dtype=bnn_C.dtype), dev)\n    f1 = tvm.build(s1, [A, bnn_A], \"llvm\")\n    f2 = tvm.build(s2, [B, bnn_B], \"llvm\")\n    f3 = tvm.build(s3, [bnn_A1, bnn_B1, bnn_C], \"llvm\")\n    f1(a, bnn_a)\n    f2(b, bnn_b)\n    f3(bnn_a, bnn_b, bnn_c)\n    tvm.testing.assert_allclose(bnn_c.numpy(), c_np, rtol=1e-5)\n\n\ndef test_binary_dense():\n    verify_binary_dense(1, 4096, 1024)\n    verify_binary_dense(1, 1024, 1000)\n\n\nif __name__ == \"__main__\":\n    test_binary_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_broadcast.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for broadcasting operators.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_broadcast_to_ele(in_shape, out_shape, fbcast):\n    # Build the logic and compile the function\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = fbcast(A, out_shape)\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"broadcast_to\")\n        data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = np.broadcast_to(data_npy, out_shape)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), dev)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target)\n    check_target(\"sdaccel\")\n\n\ndef verify_broadcast_binary_ele(\n    lhs_shape,\n    rhs_shape,\n    ftopi,\n    fnumpy,\n    lhs_min=-100,\n    lhs_max=100,\n    rhs_min=-100,\n    rhs_max=100,\n    dtype=\"float32\",\n):\n    # Build the logic and compile the function\n    A = (\n        te.var(\"A\", dtype=dtype)\n        if lhs_shape is None\n        else te.placeholder(shape=lhs_shape, name=\"A\", dtype=dtype)\n    )\n    B = (\n        te.var(\"B\", dtype=dtype)\n        if rhs_shape is None\n        else te.placeholder(shape=rhs_shape, name=\"B\", dtype=dtype)\n    )\n    C = ftopi(A, B)\n    if isinstance(A, tvm.tir.PrimExpr) and isinstance(B, tvm.tir.PrimExpr):\n        assert isinstance(C, tvm.tir.PrimExpr)\n        return\n\n    def gen_operand(shape, low, high, dev):\n        if shape is None:\n            npy = float(np.random.uniform(low=low, high=high))\n            if dtype.startswith(\"int\"):\n                npy = int(npy)\n            nd = npy\n        else:\n            npy = np.random.uniform(low=low, high=high, size=shape).astype(dtype)\n            nd = tvm.nd.array(npy, dev)\n        return npy, nd\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(C)\n        foo = tvm.build(s, [A, B, C], target, name=\"broadcast_binary\" + \"_\" + ftopi.__name__)\n\n        lhs_npy, lhs_nd = gen_operand(lhs_shape, lhs_min, lhs_max, dev)\n        rhs_npy, rhs_nd = gen_operand(rhs_shape, rhs_min, rhs_max, dev)\n        out_npy = fnumpy(lhs_npy, rhs_npy)\n\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(C.dtype), dev)\n        foo(lhs_nd, rhs_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy, rtol=1e-4, atol=1e-4)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target)\n    check_target(\"sdaccel\")\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_to():\n    verify_broadcast_to_ele((1,), (10,), topi.broadcast_to)\n    verify_broadcast_to_ele((), (10,), topi.broadcast_to)\n    verify_broadcast_to_ele((1, 1, 5, 4), (3, 4, 4, 4, 5, 4), topi.broadcast_to)\n    verify_broadcast_to_ele((1, 128, 1, 32), (64, 128, 64, 32), topi.broadcast_to)\n\n\n@tvm.testing.uses_gpu\ndef test_add():\n    verify_broadcast_binary_ele((), (), topi.add, np.add)\n    verify_broadcast_binary_ele((5, 2, 3), (2, 1), topi.add, np.add)\n\n\n@tvm.testing.uses_gpu\ndef test_subtract():\n    verify_broadcast_binary_ele((5, 2, 3), (), topi.subtract, np.subtract)\n    verify_broadcast_binary_ele((5, 2, 3), None, topi.subtract, np.subtract)\n    verify_broadcast_binary_ele(None, None, topi.subtract, np.subtract)\n    verify_broadcast_binary_ele((1, 32), (64, 32), topi.subtract, np.subtract)\n\n\n@tvm.testing.uses_gpu\ndef test_multiply():\n    verify_broadcast_binary_ele((5, 64, 128), (2, 5, 64, 1), topi.multiply, np.multiply)\n\n\n@tvm.testing.uses_gpu\ndef test_divide():\n    verify_broadcast_binary_ele(None, (10,), topi.divide, np.divide, rhs_min=0.0001)\n    verify_broadcast_binary_ele((), None, topi.divide, np.divide, rhs_min=0.0001)\n    verify_broadcast_binary_ele((2, 3, 1, 32), (64, 32), topi.divide, np.divide, rhs_min=0.0001)\n\n\n@tvm.testing.uses_gpu\ndef test_floor_divide():\n    def _canonical_floor_div(a, b):\n        return np.floor(a / b)\n\n    verify_broadcast_binary_ele(\n        None, (10,), topi.floor_divide, _canonical_floor_div, rhs_min=0.0001\n    )\n    verify_broadcast_binary_ele((), None, topi.floor_divide, _canonical_floor_div, rhs_min=0.0001)\n    verify_broadcast_binary_ele(\n        (2, 3, 64, 32), (64, 32), topi.floor_divide, _canonical_floor_div, rhs_min=0.0001\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_maximum_minmum():\n    verify_broadcast_binary_ele((32,), (64, 32), topi.maximum, np.maximum)\n    verify_broadcast_binary_ele((1, 2, 2, 1, 32), (64, 32), topi.minimum, np.minimum)\n\n\n@tvm.testing.uses_gpu\ndef test_power():\n    verify_broadcast_binary_ele(\n        (1, 2, 2), (2,), topi.power, np.power, lhs_min=0.001, rhs_min=0.001, rhs_max=2\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_mod():\n    verify_broadcast_binary_ele(\n        (1, 2, 2), (2,), topi.mod, np.mod, lhs_min=0.001, rhs_min=1, dtype=\"int32\"\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_floor_mod():\n    def _canonical_floor_mod(a, b):\n        return a - np.floor(a / b) * b\n\n    verify_broadcast_binary_ele(\n        (1, 2, 2),\n        (2,),\n        topi.floor_mod,\n        _canonical_floor_mod,\n        lhs_min=0.001,\n        rhs_min=1,\n        dtype=\"int32\",\n    )\n    verify_broadcast_binary_ele(\n        (3, 4, 5),\n        (3, 4, 5),\n        topi.floor_mod,\n        _canonical_floor_mod,\n        lhs_min=0.001,\n        rhs_min=1,\n        dtype=\"float32\",\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_cmp():\n    # explicit specify the output type\n    def greater(x, y):\n        return topi.greater(x, y).astype(\"int8\")\n\n    def less(x, y):\n        return topi.less(x, y).astype(\"int8\")\n\n    def equal(x, y):\n        return topi.equal(x, y).astype(\"int8\")\n\n    def not_equal(x, y):\n        return topi.not_equal(x, y).astype(\"int8\")\n\n    def greater_equal(x, y):\n        return topi.greater_equal(x, y).astype(\"int8\")\n\n    def less_equal(x, y):\n        return topi.less_equal(x, y).astype(\"int8\")\n\n    verify_broadcast_binary_ele((1, 2, 2), (2,), greater, np.greater)\n    verify_broadcast_binary_ele((2, 1, 2), (2, 3, 1), less, np.less)\n    verify_broadcast_binary_ele(\n        (2, 1, 2),\n        (2, 3, 1),\n        equal,\n        np.equal,\n        lhs_min=-2,\n        lhs_max=2,\n        rhs_min=-2,\n        rhs_max=2,\n        dtype=\"int32\",\n    )\n    verify_broadcast_binary_ele(\n        (2, 1, 2),\n        (2, 3, 1),\n        not_equal,\n        np.not_equal,\n        lhs_min=-2,\n        lhs_max=2,\n        rhs_min=-2,\n        rhs_max=2,\n        dtype=\"int32\",\n    )\n    verify_broadcast_binary_ele(\n        (7, 1, 5),\n        (7, 3, 1),\n        greater_equal,\n        np.greater_equal,\n        lhs_min=-3,\n        lhs_max=3,\n        rhs_min=-3,\n        rhs_max=3,\n        dtype=\"int32\",\n    )\n    verify_broadcast_binary_ele(\n        (7, 1, 5),\n        (7, 3, 1),\n        less_equal,\n        np.less_equal,\n        lhs_min=-3,\n        lhs_max=3,\n        rhs_min=-3,\n        rhs_max=3,\n        dtype=\"int32\",\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_shift():\n    # explicit specify the output type\n    verify_broadcast_binary_ele(\n        (2, 1, 2), None, topi.right_shift, np.right_shift, dtype=\"int32\", rhs_min=0, rhs_max=32\n    )\n\n    verify_broadcast_binary_ele(\n        (1, 2, 2), (2,), topi.left_shift, np.left_shift, dtype=\"int32\", rhs_min=0, rhs_max=32\n    )\n\n    verify_broadcast_binary_ele(\n        (1, 2, 2), (2,), topi.left_shift, np.left_shift, dtype=\"int32\", rhs_min=0, rhs_max=32\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_logical_single_ele():\n    def test_apply(\n        func,\n        name,\n        f_numpy,\n        indata,\n        dtype=\"bool\",\n    ):\n        # Build the logic and compile the function\n        A = te.placeholder(shape=indata.shape, name=\"A\", dtype=dtype)\n        B = func(A)\n        if isinstance(A, tvm.tir.PrimExpr):\n            assert isinstance(B, tvm.tir.PrimExpr)\n            return\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n            foo = tvm.build(s, [A, B], target, name=name)\n\n            data_npy = indata.astype(A.dtype)\n            data_nd = tvm.nd.array(data_npy, dev)\n\n            out_npy = f_numpy(indata)\n            out_nd = tvm.nd.array(np.empty(data_npy.shape).astype(B.dtype), dev)\n            foo(data_nd, out_nd)\n            tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    test_apply(topi.logical_not, \"logical_not\", np.logical_not, np.array([True, False, 0, 1]))\n    test_apply(topi.logical_not, \"logical_not\", np.logical_not, np.array(np.arange(5) < 3))\n\n\n@tvm.testing.uses_gpu\ndef test_bitwise_not():\n    def test_apply(\n        func,\n        name,\n        f_numpy,\n        shape,\n        dtype=\"int32\",\n    ):\n        # Build the logic and compile the function\n        A = te.placeholder(shape=shape, name=\"A\", dtype=dtype)\n        B = func(A)\n\n        if isinstance(A, tvm.tir.PrimExpr):\n            assert isinstance(B, tvm.tir.PrimExpr)\n            return\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n            foo = tvm.build(s, [A, B], target, name=name)\n\n            data_npy = np.random.uniform(size=shape).astype(A.dtype)\n            data_nd = tvm.nd.array(data_npy, dev)\n\n            out_npy = f_numpy(data_npy)\n            out_nd = tvm.nd.array(np.empty(data_npy.shape).astype(B.dtype), dev)\n            foo(data_nd, out_nd)\n            tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    test_apply(topi.bitwise_not, \"bitwise_not\", np.bitwise_not, ())\n    test_apply(topi.bitwise_not, \"bitwise_not\", np.bitwise_not, (2, 1, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_logical_binary_ele():\n    def test_apply(\n        func,\n        name,\n        f_numpy,\n        lhs,\n        rhs,\n        dtype=\"bool\",\n    ):\n        # Build the logic and compile the function\n        A = te.var(\"A\", dtype=dtype)\n        B = te.var(\"B\", dtype=dtype)\n        C = func(A, B)\n        if isinstance(A, tvm.tir.PrimExpr) and isinstance(B, tvm.tir.PrimExpr):\n            assert isinstance(C, tvm.tir.PrimExpr)\n            return\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_broadcast_schedule(target)(C)\n            foo = tvm.build(s, [A, B, C], target, name=name)\n\n            lhs_nd = tvm.nd.array(lhs, dev)\n            rhs_nd = tvm.nd.array(rhs, dev)\n\n            out_npy = f_numpy(lhs, rhs)\n            out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(C.dtype), dev)\n            foo(lhs_nd, rhs_nd, out_nd)\n            tvm.testing.assert_allclose(out_nd.numpy(), out_npy, rtol=1e-4, atol=1e-4)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    test_apply(topi.logical_and, \"logical_and\", np.logical_and, True, False)\n    test_apply(topi.logical_and, \"logical_and\", np.logical_and, [True, False], [False, False])\n    test_apply(topi.logical_or, \"logical_or\", np.logical_or, True, False)\n    test_apply(topi.logical_or, \"logical_or\", np.logical_or, [True, False], [False, False])\n    test_apply(topi.logical_xor, \"logical_xor\", np.logical_xor, True, False)\n    test_apply(topi.logical_xor, \"logical_xor\", np.logical_xor, [True, False], [False, False])\n\n\n@tvm.testing.uses_gpu\ndef test_bitwise_and():\n    verify_broadcast_binary_ele(None, None, topi.bitwise_and, np.bitwise_and, dtype=\"int32\")\n    verify_broadcast_binary_ele(\n        (2, 1, 2), (2, 1, 2), topi.bitwise_and, np.bitwise_and, dtype=\"int32\"\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_bitwise_or():\n    verify_broadcast_binary_ele(None, None, topi.bitwise_or, np.bitwise_or, dtype=\"int32\")\n    verify_broadcast_binary_ele((2, 1, 2), (2, 1, 2), topi.bitwise_or, np.bitwise_or, dtype=\"int32\")\n\n\n@tvm.testing.uses_gpu\ndef test_bitwise_xor():\n    verify_broadcast_binary_ele(None, None, topi.bitwise_xor, np.bitwise_xor, dtype=\"int32\")\n    verify_broadcast_binary_ele(\n        (2, 1, 2), (2, 1, 2), topi.bitwise_xor, np.bitwise_xor, dtype=\"int32\"\n    )\n\n\nif __name__ == \"__main__\":\n    test_add()\n    test_shift()\n    test_cmp()\n    test_mod()\n    test_floor_mod()\n    test_subtract()\n    test_multiply()\n    test_divide()\n    test_floor_divide()\n    test_maximum_minmum()\n    test_power()\n    test_broadcast_to()\n    test_logical_single_ele()\n    test_bitwise_not()\n    test_logical_binary_ele()\n    test_bitwise_and()\n    test_bitwise_or()\n    test_bitwise_xor()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_clip.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for clip operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_clip(N, a_min, a_max, dtype):\n    A = te.placeholder((N, N), dtype=dtype, name=\"A\")\n    B = topi.clip(A, a_min, a_max)\n    s = te.create_schedule([B.op])\n\n    # use memoize to pickle the test data for next time use\n    @memoize(\"topi.tests.test_topi_clip\")\n    def get_ref_data():\n        a_np = np.random.uniform(a_min * 2, a_max * 2, size=(N, N)).astype(dtype)\n        b_np = np.clip(a_np, a_min, a_max)\n        return a_np, b_np\n\n    a_np, b_np = get_ref_data()\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target, name=\"clip\")\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_clip():\n    verify_clip(1024, -127, 127, \"float32\")\n    verify_clip(1024, -127, 127, \"int16\")\n    verify_clip(1024, -127, 127, \"int8\")\n\n\nif __name__ == \"__main__\":\n    test_clip()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv1d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for transposed convolution.\"\"\"\nimport numpy as np\nimport itertools\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n\n_conv1d_ncw_implement = {\n    \"generic\": (topi.nn.conv1d_ncw, topi.generic.schedule_conv1d_ncw),\n    \"cpu\": (topi.nn.conv1d_ncw, topi.x86.schedule_conv1d_ncw),\n    \"gpu\": (topi.cuda.conv1d_ncw, topi.cuda.schedule_conv1d_ncw),\n}\n\n_conv1d_nwc_implement = {\n    \"generic\": (topi.nn.conv1d_nwc, topi.generic.schedule_conv1d_nwc),\n    \"cpu\": (topi.nn.conv1d_nwc, topi.x86.schedule_conv1d_nwc),\n    \"gpu\": (topi.cuda.conv1d_nwc, topi.cuda.schedule_conv1d_nwc),\n}\n\n_group_conv1d_implementations = {\n    \"NCW\": {\n        \"generic\": (topi.nn.group_conv1d_ncw, topi.generic.schedule_group_conv1d_ncw),\n        \"cpu\": (topi.nn.group_conv1d_ncw, topi.x86.schedule_group_conv1d_ncw),\n        \"gpu\": (topi.cuda.group_conv1d_ncw, topi.cuda.schedule_group_conv1d_ncw),\n    },\n    \"NWC\": {\n        \"generic\": (topi.nn.group_conv1d_nwc, topi.generic.schedule_group_conv1d_nwc),\n        \"cpu\": (topi.nn.group_conv1d_nwc, topi.x86.schedule_group_conv1d_nwc),\n        \"gpu\": (topi.cuda.group_conv1d_nwc, topi.cuda.schedule_group_conv1d_nwc),\n    },\n}\n\n\ndef verify_conv1d(\n    batch,\n    in_channels,\n    in_width,\n    filters,\n    kernel_size=3,\n    stride=1,\n    dilation=1,\n    padding=\"VALID\",\n    layout=\"NCW\",\n):\n    if layout == \"NCW\":\n        in_shape = [batch, in_channels, in_width]\n        kernel_shape = [filters, in_channels, kernel_size]\n    else:\n        in_shape = [batch, in_width, in_channels]\n        kernel_shape = [kernel_size, in_channels, filters]\n\n    dtype = \"float32\"\n    A = te.placeholder(in_shape, name=\"A\", dtype=dtype)\n    W = te.placeholder(kernel_shape, name=\"W\", dtype=dtype)\n\n    def get_ref_data(layout):\n        a_np = np.random.uniform(size=in_shape).astype(dtype)\n        w_np = np.random.uniform(size=kernel_shape).astype(dtype)\n        if layout == \"NWC\":\n            np_in = np.transpose(a_np, [0, 2, 1])\n            np_w = np.transpose(w_np, [2, 1, 0])\n        else:\n            np_in = a_np\n            np_w = w_np\n        b_np = tvm.topi.testing.conv1d_ncw_python(np_in, np_w, stride, padding, dilation)\n        if layout == \"NWC\":\n            b_np = np.transpose(b_np, [0, 2, 1])\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data(layout)\n\n    def check_target(target, dev):\n        if layout == \"NCW\":\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv1d_ncw_implement)\n        else:\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv1d_nwc_implement)\n        with tvm.target.Target(target):\n            B = fcompute(A, W, stride, padding, dilation, \"float32\")\n            s = fschedule([B])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n\n        func = tvm.build(s, [A, W, B], target)\n        func(a, w, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_conv1d():\n    for layout in [\"NCW\", \"NWC\"]:\n        # Most basic test case\n        verify_conv1d(1, 1, 8, 1, 3, 1, 1, \"VALID\", layout)\n        # With padding\n        verify_conv1d(1, 1, 8, 1, 3, 1, 1, \"SAME\", layout)\n        # Realistic dimensions\n        verify_conv1d(1, 16, 32, 16, 3, 1, 1, \"SAME\", layout)\n        # With stride\n        verify_conv1d(1, 16, 32, 16, 3, 2, 1, \"SAME\", layout)\n        # With dilation\n        verify_conv1d(1, 16, 32, 16, 3, 1, 2, \"SAME\", layout)\n        # Large batch size\n        verify_conv1d(8, 16, 32, 16, 3, 1, 1, \"SAME\", layout)\n        # Other kernel sizes\n        verify_conv1d(1, 16, 32, 16, 3, 1, 1, \"SAME\", layout)\n        verify_conv1d(1, 16, 32, 16, 2, 1, 1, \"SAME\", layout)\n        verify_conv1d(1, 16, 32, 16, 1, 1, 1, \"SAME\", layout)\n        # Non-power-of-two shape\n        verify_conv1d(1, 17, 12, 21, 3, 1, 1, \"SAME\", layout)\n        verify_conv1d(1, 5, 27, 18, 3, 1, 1, \"VALID\", layout)\n\n\nlayout = tvm.testing.parameter(\"NCW\", \"NWC\")\npadding = tvm.testing.parameter(\"SAME\", \"VALID\")\ndtype = tvm.testing.parameter(\"float32\")\n\n# batch, in_channels, in_width, filters, kernel_size, stride, dilation, groups\nshape = tvm.testing.parameter(\n    [1, 4, 8, 4, 3, 1, 1, 4],\n    [1, 4, 8, 4, 3, 1, 1, 4],\n    [1, 16, 32, 16, 3, 1, 1, 4],\n    [1, 16, 32, 16, 3, 2, 1, 4],\n    [1, 16, 32, 16, 3, 1, 2, 4],\n    [8, 16, 32, 16, 3, 1, 1, 4],\n    [1, 16, 32, 16, 3, 1, 1, 4],\n    [1, 16, 32, 16, 2, 1, 1, 4],\n    [1, 16, 32, 16, 1, 1, 1, 4],\n    [1, 21, 12, 21, 3, 1, 1, 3],\n    [1, 20, 27, 20, 3, 1, 1, 5],\n)\n\n\ndef test_group_conv1d(shape, layout, padding, target, dev, dtype):\n    batch, in_channels, in_width, filters, kernel_size, stride, dilation, groups = shape\n    if layout == \"NCW\":\n        in_shape = [batch, in_channels, in_width]\n        kernel_shape = [filters, in_channels // groups, kernel_size]\n    else:\n        in_shape = [batch, in_width, in_channels]\n        kernel_shape = [kernel_size, in_channels // groups, filters]\n\n    # reference data\n    a_np = np.random.uniform(size=in_shape).astype(dtype)\n    w_np = np.random.uniform(size=kernel_shape).astype(dtype)\n    if layout == \"NWC\":\n        np_in = np.transpose(a_np, [0, 2, 1])\n        np_w = np.transpose(w_np, [2, 1, 0])\n    else:\n        np_in = a_np\n        np_w = w_np\n    b_np = tvm.topi.testing.group_conv1d_ncw_python(np_in, np_w, stride, padding, dilation, groups)\n    if layout == \"NWC\":\n        b_np = np.transpose(b_np, [0, 2, 1])\n\n    A = te.placeholder(in_shape, name=\"A\", dtype=dtype)\n    W = te.placeholder(kernel_shape, name=\"W\", dtype=dtype)\n\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, _group_conv1d_implementations[layout])\n    with tvm.target.Target(target):\n        B = fcompute(A, W, stride, padding, dilation, groups, \"float32\")\n        s = fschedule([B])\n\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n    print(tvm.lower(s, [A, W, B], target))\n\n    func = tvm.build(s, [A, W, B], target)\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    test_conv1d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv1d_transpose_ncw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for transposed convolution.\"\"\"\n\nimport itertools\nimport os\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\nfrom tvm.topi.utils import get_const_tuple\n\n_conv1d_transpose_ncw_implement = {\n    \"generic\": (topi.nn.conv1d_transpose_ncw, topi.generic.schedule_conv1d_transpose_ncw),\n    \"gpu\": (topi.cuda.conv1d_transpose_ncw, topi.cuda.schedule_conv1d_transpose_ncw),\n}\n\n\n(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    output_padding,\n) = tvm.testing.parameters(\n    (1, 3, 224, 32, 5, 1, 0, (0,)),\n    (1, 3, 224, 32, 7, 1, 2, (0,)),\n    (1, 3, 224, 32, 5, 2, 1, (0,)),\n    (1, 3, 224, 32, 5, 2, 1, (1,)),\n    (1, 3, 224, 32, 5, 2, 0, (0,)),\n    (1, 32, 32, 128, 5, 1, 0, (0,)),\n    (1, 32, 32, 128, 5, 2, 1, (0,)),\n    (1, 1, 1024, 1, 512, 1, 256, (0,)),\n    (1, 1, 1024, 1, 512, 2, 256, (0,)),\n    (1, 1, 1024, 1, 512, 5, 256, (0,)),\n    (1, 1, 1024, 1, 512, 5, 256, (3,)),\n    (1, 2, 1024, 1, 128, 128, 0, (0,)),\n    (1, 1, 1024, 2, 128, 128, 0, (0,)),\n    (1, 1, 1024, 2, 2, 2, 0, (0,)),\n    (1, 1, 10, 1, 5, 1, (0, 3), (0,)),\n    (1, 1, 10, 1, 5, 1, (1, 3), (0,)),\n    (1, 1, 10, 1, 5, 1, (2, 3), (0,)),\n    (1, 257, 128, 1, 512, 128, 256, (0,)),\n)\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(\n    dtype, batch, in_channel, in_size, num_filter, kernel, stride, padding, output_padding\n):\n    dtype = \"float32\"\n    a_shape = (batch, in_channel, in_size)\n    w_shape = (in_channel, num_filter, kernel)\n\n    a_np = np.random.uniform(size=a_shape).astype(dtype)\n    w_np = np.random.uniform(size=w_shape).astype(dtype)\n    b_np = tvm.topi.testing.conv1d_transpose_ncw_python(a_np, w_np, stride, padding, output_padding)\n    c_np = np.maximum(b_np, 0)\n    return a_np, w_np, b_np, c_np\n\n\n@tvm.testing.known_failing_targets(\"vulkan\")\ndef test_conv1d_transpose_ncw(\n    target,\n    dev,\n    ref_data,\n    dtype,\n    stride,\n    padding,\n    output_padding,\n):\n\n    a_np, w_np, b_np, c_np = ref_data\n\n    A = te.placeholder(a_np.shape, name=\"A\", dtype=dtype)\n    W = te.placeholder(w_np.shape, name=\"W\", dtype=dtype)\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv1d_transpose_ncw_implement)\n        B = fcompute(A, W, stride, padding, A.dtype, output_padding)\n        C = topi.nn.relu(B)\n        s1 = fschedule([B])\n        s2 = fschedule([C])\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n    func1 = tvm.build(s1, [A, W, B], target)\n    func2 = tvm.build(s2, [A, W, C], target)\n    func1(a, w, b)\n    func2(a, w, c)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n    tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_NCHWc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test for NCHW[x]c convolution\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef _transform_data(data, bn):\n    # NCHW -> NCHW[x]c\n    batch_size, channel, height, width = data.shape\n    data = np.reshape(data, (batch_size, channel // bn, bn, height, width))\n    data = np.transpose(data, (0, 1, 3, 4, 2))\n    return data\n\n\ndef _transform_kernel(kernel, ic_bn, oc_bn):\n    # OIHW -> OIHW[x]i[x]o\n    out_channel, in_channel, kh, kw = kernel.shape\n    kernel = np.reshape(kernel, (out_channel // oc_bn, oc_bn, in_channel // ic_bn, ic_bn, kh, kw))\n    kernel = np.transpose(kernel, (0, 2, 4, 5, 3, 1))\n    return kernel\n\n\ndef _transform_bias(bias, bn):\n    # [num_filter, 1, 1] -> [num_filter//bn, 1, 1, bn]\n    num_filter, h, w = bias.shape\n    bias = np.reshape(bias, (num_filter // bn, bn, h, w))\n    bias = np.transpose(bias, (0, 2, 3, 1))\n    return bias\n\n\ndef verify_conv2d_NCHWc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    dtype=\"float32\",\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    in_height = in_width = in_size\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum)\n    )\n\n    # for testing functionality,\n    # we choose arbitrary block size that can divide the channel,\n    # regardless of the performance.\n    oc_block = 1\n    for bn in range(16, 0, -1):\n        if num_filter % bn == 0:\n            oc_block = bn\n            break\n\n    ic_block = 1\n    for bn in range(oc_block, 0, -1):\n        if in_channel % bn == 0:\n            ic_block = bn\n            break\n\n    A = te.placeholder((batch, in_channel // ic_block, in_height, in_width, ic_block), name=\"A\")\n    W = te.placeholder(\n        (num_filter // oc_block, in_channel // ic_block, kernel, kernel, ic_block, oc_block),\n        name=\"W\",\n    )\n    bias = te.placeholder((num_filter // oc_block, 1, 1, oc_block), name=\"bias\")\n\n    @memoize(\"topi.tests.test_topi_conv2d_NCHWc.verify_conv2d_NCHWc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=(batch, in_channel, in_height, in_width)).astype(dtype)\n        w_np = np.random.uniform(size=(num_filter, in_channel, kernel, kernel)).astype(dtype)\n        b_np = np.random.uniform(size=(num_filter, 1, 1)).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return (\n            _transform_data(a_np, ic_block),\n            _transform_kernel(w_np, ic_block, oc_block),\n            _transform_bias(b_np, oc_block),\n            _transform_data(c_np, oc_block),\n        )\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            C = topi.x86.conv2d_NCHWc(\n                A,\n                W,\n                (stride, stride),\n                padding,\n                (dilation, dilation),\n                \"NCHW%dc\" % ic_block,\n                \"NCHW%dc\" % oc_block,\n                dtype,\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = topi.x86.schedule_conv2d_NCHWc([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3)\n\n    # test llvm only for now since conv2d_NCHWc implement is missing in other backend.\n    for device in [\"llvm\"]:\n        with autotvm.tophub.context(device):  # load tophub pre-tuned parameters\n            check_device(device)\n\n\ndef test_conv2d_NCHWc():\n    # ResNet18 workloads\n    verify_conv2d_NCHWc(1, 3, 224, 64, 7, 2, 3)\n    verify_conv2d_NCHWc(1, 64, 56, 64, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 64, 56, 64, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 64, 56, 128, 3, 2, 1)\n    verify_conv2d_NCHWc(1, 64, 56, 128, 1, 2, 0)\n    verify_conv2d_NCHWc(1, 128, 28, 128, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 128, 28, 256, 3, 2, 1)\n    verify_conv2d_NCHWc(1, 128, 28, 256, 1, 2, 0)\n    verify_conv2d_NCHWc(1, 256, 14, 256, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 256, 14, 512, 3, 2, 1)\n    verify_conv2d_NCHWc(1, 256, 14, 512, 1, 2, 0)\n    verify_conv2d_NCHWc(1, 512, 7, 512, 3, 1, 1)\n\n    # bias, relu\n    verify_conv2d_NCHWc(1, 64, 56, 64, 3, 1, 1, add_relu=True)\n    verify_conv2d_NCHWc(1, 64, 56, 64, 3, 1, 1, add_bias=True)\n    verify_conv2d_NCHWc(1, 64, 56, 64, 3, 1, 1, add_bias=True, add_relu=True)\n\n    # dilation\n    verify_conv2d_NCHWc(1, 64, 56, 64, 3, 1, 1, dilation=2)\n\n    # batch size\n    verify_conv2d_NCHWc(4, 64, 56, 64, 3, 1, 1)\n    verify_conv2d_NCHWc(9, 64, 56, 64, 3, 1, 1)\n\n    # weird workloads\n    verify_conv2d_NCHWc(2, 2, 2, 2, 2, 2, 2)\n    verify_conv2d_NCHWc(3, 3, 3, 3, 3, 3, 3)\n    verify_conv2d_NCHWc(4, 4, 4, 4, 4, 4, 4)\n    verify_conv2d_NCHWc(5, 5, 5, 5, 5, 5, 5)\n    verify_conv2d_NCHWc(6, 6, 6, 6, 6, 6, 6)\n\n    # disable these tests due to some bugs of llvm with nvptx\n    # verify_conv2d_NCHWc(1, 1, 1, 1, 1, 1, 1, dilation=1)\n    # verify_conv2d_NCHWc(1, 1, 1, 1, 1, 1, 1, dilation=2)\n    # verify_conv2d_NCHWc(2, 13, 71, 59, 3, 1, 1)\n\n    # inception v3 workloads\n    verify_conv2d_NCHWc(1, 3, 299, 32, 3, 2, 0)\n    verify_conv2d_NCHWc(1, 32, 149, 32, 3, 1, 0)\n    verify_conv2d_NCHWc(1, 32, 147, 64, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 64, 73, 80, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 80, 73, 192, 3, 1, 0)\n    verify_conv2d_NCHWc(1, 192, 35, 64, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 192, 35, 48, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 48, 35, 64, 5, 1, 2)\n    verify_conv2d_NCHWc(1, 64, 35, 96, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 96, 35, 96, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 192, 35, 32, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 256, 35, 64, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 256, 35, 48, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 288, 35, 64, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 288, 35, 48, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 288, 35, 384, 3, 2, 0)\n    verify_conv2d_NCHWc(1, 96, 35, 96, 3, 2, 0)\n    verify_conv2d_NCHWc(1, 768, 17, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 768, 17, 128, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 128, 17, 128, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 128, 17, 192, 7, 1, 3)\n    verify_conv2d_NCHWc(1, 128, 17, 128, 7, 1, 3)\n    verify_conv2d_NCHWc(1, 128, 17, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 768, 17, 160, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 160, 17, 160, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 160, 17, 192, 7, 1, 3)\n    verify_conv2d_NCHWc(1, 160, 17, 160, 7, 1, 3)\n    verify_conv2d_NCHWc(1, 160, 17, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 192, 17, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 192, 17, 192, 7, 1, 3)\n    verify_conv2d_NCHWc(1, 192, 17, 320, 3, 2, 0)\n    verify_conv2d_NCHWc(1, 192, 17, 192, 3, 2, 0)\n    verify_conv2d_NCHWc(1, 1280, 8, 320, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 1280, 8, 384, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 384, 8, 384, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 384, 8, 384, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 1280, 8, 448, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 448, 8, 384, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 1280, 8, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 2048, 8, 320, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 2048, 8, 384, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 2048, 8, 448, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 2048, 8, 192, 1, 1, 0)\n    verify_conv2d_NCHWc(1, 1024, 19, 84, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 2048, 10, 126, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 512, 5, 126, 3, 1, 1)\n    verify_conv2d_NCHWc(1, 256, 3, 126, 3, 1, 1)\n\n    # Asymmetric padding\n    verify_conv2d_NCHWc(1, 32, 17, 64, 7, 2, (0, 0, 1, 1))\n    verify_conv2d_NCHWc(1, 32, 35, 128, 3, 1, (3, 3, 2, 2))\n    verify_conv2d_NCHWc(1, 32, 35, 32, 1, 1, (1, 2, 2, 1))\n    verify_conv2d_NCHWc(1, 32, 17, 192, 1, 1, (1, 2))\n    verify_conv2d_NCHWc(1, 32, 8, 32, 3, 1, (3, 1))\n    verify_conv2d_NCHWc(1, 128, 8, 384, 3, 1, (0, 2))\n    verify_conv2d_NCHWc(1, 32, 8, 32, 1, 1, \"VALID\")\n    verify_conv2d_NCHWc(1, 388, 8, 32, 3, 1, \"VALID\")\n    verify_conv2d_NCHWc(1, 512, 19, 32, 1, 1, \"SAME\")\n    verify_conv2d_NCHWc(1, 32, 10, 32, 2, 1, \"SAME\")\n    verify_conv2d_NCHWc(1, 32, 8, 32, 3, 1, (1, 2, 2, 1), add_relu=True)\n    verify_conv2d_NCHWc(1, 32, 8, 32, 5, 2, (1, 3), add_bias=True)\n    verify_conv2d_NCHWc(1, 32, 8, 32, 3, 1, \"VALID\", add_bias=True, add_relu=True)\n    verify_conv2d_NCHWc(1, 32, 8, 32, 24, 1, \"SAME\", add_bias=True, add_relu=True)\n\n\nif __name__ == \"__main__\":\n    test_conv2d_NCHWc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_hwcn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv2d_hwcn_implement = {\n    \"generic\": (topi.nn.conv2d_hwcn, topi.generic.schedule_conv2d_hwcn),\n    \"gpu\": (topi.cuda.conv2d_hwcn, topi.cuda.schedule_conv2d_hwcn),\n    \"opencl\": (topi.cuda.conv2d_hwcn, topi.cuda.schedule_conv2d_hwcn),\n}\n\n\ndef verify_conv2d_hwcn(batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation=1):\n    in_height = in_width = in_size\n\n    A = te.placeholder((in_height, in_width, in_channel, batch), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    B = te.placeholder((1, num_filter, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    b_shape = get_const_tuple(B.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_hwcn.verify_hwcn\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=b_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        c1_np = tvm.topi.testing.conv2d_hwcn_python(a_np, dw_np, stride, padding)\n        c2_np = c1_np + b_np\n        c3_np = np.maximum(c2_np, 0)\n        return a_np, w_np, b_np, c1_np, c2_np, c3_np\n\n    a_np, w_np, b_np, c1_np, c2_np, c3_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv2d_hwcn_implement)\n            t_conv = fcompute(A, W, stride, padding, dilation)\n            t_bias = topi.add(t_conv, B)\n            t_relu = topi.nn.relu(t_bias)\n            s1 = fschedule([t_conv])\n            s2 = fschedule([t_bias])\n            s3 = fschedule([t_relu])\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n\n        conv_out = tvm.nd.array(np.zeros(get_const_tuple(t_conv.shape), dtype=t_conv.dtype), dev)\n        bias_out = tvm.nd.array(np.zeros(get_const_tuple(t_bias.shape), dtype=t_bias.dtype), dev)\n        relu_out = tvm.nd.array(np.zeros(get_const_tuple(t_relu.shape), dtype=t_relu.dtype), dev)\n        func1 = tvm.build(s1, [A, W, t_conv], target)\n        func2 = tvm.build(s2, [A, W, B, t_bias], target)\n        func3 = tvm.build(s3, [A, W, B, t_relu], target)\n        func1(a, w, conv_out)\n        func2(a, w, b, bias_out)\n        func3(a, w, b, relu_out)\n        tvm.testing.assert_allclose(conv_out.numpy(), c1_np, rtol=1e-5)\n        tvm.testing.assert_allclose(bias_out.numpy(), c2_np, rtol=1e-5)\n        tvm.testing.assert_allclose(relu_out.numpy(), c3_np, rtol=1e-5)\n\n    for target in [\"cuda\", \"opencl\", \"metal\", \"rocm\", \"vulkan\", \"nvptx\"]:\n        check_target(target)\n\n\n@tvm.testing.requires_gpu\ndef test_conv2d_hwcn():\n    verify_conv2d_hwcn(1, 256, 32, 128, 3, 1, \"SAME\")\n    verify_conv2d_hwcn(1, 256, 32, 256, 3, 1, \"SAME\")\n    verify_conv2d_hwcn(4, 128, 16, 128, 5, 2, \"SAME\")\n    verify_conv2d_hwcn(4, 128, 16, 256, 5, 2, \"SAME\")\n    verify_conv2d_hwcn(1, 256, 32, 128, 3, 1, \"VALID\")\n    verify_conv2d_hwcn(1, 256, 32, 256, 3, 1, \"VALID\")\n    verify_conv2d_hwcn(4, 128, 16, 128, 5, 2, \"VALID\")\n    verify_conv2d_hwcn(4, 128, 16, 256, 5, 2, \"VALID\")\n    # dilation = 2\n    verify_conv2d_hwcn(1, 256, 32, 256, 3, 1, \"SAME\", dilation=2)\n    # Pass stride as tuple\n    verify_conv2d_hwcn(1, 256, 32, 128, 3, (1, 1), \"SAME\")\n    verify_conv2d_hwcn(1, 256, 32, 256, 3, (1, 1), \"SAME\")\n    verify_conv2d_hwcn(4, 128, 16, 128, 5, (2, 2), \"SAME\")\n    verify_conv2d_hwcn(4, 128, 16, 256, 5, (2, 2), \"SAME\")\n    verify_conv2d_hwcn(1, 256, 32, 128, 3, (1, 1), \"VALID\")\n    verify_conv2d_hwcn(1, 256, 32, 256, 3, (1, 1), \"VALID\")\n    verify_conv2d_hwcn(4, 128, 16, 128, 5, (2, 2), \"VALID\")\n    verify_conv2d_hwcn(4, 128, 16, 256, 5, (2, 2), \"VALID\")\n\n\nif __name__ == \"__main__\":\n    test_conv2d_hwcn()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_hwnc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nimport os\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import te, autotvm, topi, relay\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.contrib import nvcc\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\n\n_conv2d_hwnc_tensorcore_implement = {\n    \"cuda\": (topi.cuda.conv2d_hwnc_tensorcore, topi.cuda.schedule_conv2d_hwnc_tensorcore)\n}\n\n\ndef verify_conv2d_hwnc(\n    batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation=1, dtype=\"int4\"\n):\n    \"\"\"Test the conv2d with tensorcore for hwnc layout\"\"\"\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n    # choose dtype from int4, int8\n    assert dtype in [\"int4\", \"int8\"]\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((in_height, in_width, batch, in_channel), name=\"A\", dtype=dtype)\n    W = te.placeholder((kernel, kernel, num_filter, in_channel), name=\"W\", dtype=dtype)\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n\n    @memoize(\"topi.tests.test_topi_conv2d_hwnc.verify_conv2d_hwnc\")\n    def get_ref_data():\n        if dtype == \"int4\":\n            a_np = np.random.randint(low=-8, high=7, size=a_shape).transpose((2, 0, 1, 3))\n            w_np = np.random.randint(low=-8, high=7, size=w_shape)\n            dw_np = topi.testing.dilate_python(\n                w_np.transpose((0, 1, 3, 2)), (1, 1, dilation, dilation)\n            )\n        elif dtype == \"int8\":\n            a_np = (\n                np.random.randint(low=-128, high=127, size=a_shape)\n                .transpose((2, 0, 1, 3))\n                .astype(dtype)\n            )\n            w_np = np.random.randint(low=-128, high=127, size=w_shape).astype(dtype)\n            dw_np = topi.testing.dilate_python(\n                w_np.transpose((0, 1, 3, 2)), (1, 1, dilation, dilation)\n            )\n\n        c_np = topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        return a_np, w_np, c_np\n\n    def convert_int32_into_int4(a_int32):\n        \"\"\"convert int32 values into int4\n        Parameters\n        ----------\n        a_int32 : int\n\n        Return\n        ------\n        a_int4 : int\n        \"\"\"\n        I, J, K, L = a_int32.shape\n        a_int4 = np.zeros(shape=(I, J, K, L // 8), dtype=np.int32)\n        for i in range(I):\n            for j in range(J):\n                for k in range(K):\n                    for l in range(L // 8):\n                        for m in range(min(8, L - l * 8)):\n                            a_int4[i, j, k, l] = a_int4[i, j, k, l] | (\n                                (a_int32[i, j, k, l * 8 + m] & 0xF) << ((7 - m) * 4)\n                            )\n        return a_int4\n\n    a_np, w_np, c_np = get_ref_data()\n    if dtype == \"int4\":\n        a_np = convert_int32_into_int4(a_np)\n        w_np = convert_int32_into_int4(w_np)\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        if not nvcc.have_tensorcore(dev.compute_version):\n            print(\"skip because gpu does not support Tensor Cores\")\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = topi.testing.dispatch(target, _conv2d_hwnc_tensorcore_implement)\n            C = fcompute(A, W, stride, padding, dilation, dtype, \"int32\")\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np.transpose((1, 2, 0, 3)), dev)\n        w = tvm.nd.array(w_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n        func = tvm.build(\n            s,\n            [A, W, C],\n            target,\n            name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n            % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n        )\n        func(a, w, c)\n\n        rtol = 1e-3\n        tvm.testing.assert_allclose(c.numpy().transpose((2, 0, 1, 3)), c_np, rtol=rtol)\n\n    check_target(\"cuda\")\n\n\ndef verify_feature_length():\n    np.random.seed(123)\n    target = \"cuda\"\n    ctx = tvm.device(target)\n\n    batch_size = 32\n\n    input_shape = (32, 512, 7, 7)\n    kernel_shape = (512, 512, 3, 3)\n\n    def get_mod():\n        x = relay.var(\"x\", relay.TensorType(input_shape, \"float32\"))\n        y = relay.var(\"y\", relay.TensorType(kernel_shape, \"float32\"))\n        f = relay.Function(\n            [x, y], relay.nn.conv2d(x, y, padding=[1, 1, 1, 1], channels=512, kernel_size=[3, 3])\n        )\n        mod = tvm.IRModule()\n        mod[\"main\"] = f\n        mod = relay.transform.InferType()(mod)\n        return mod, {}\n\n    mod, params = get_mod()\n    layout_config = relay.transform.LayoutConfig()\n    desired_layouts = {\"nn.conv2d\": [\"HWNC\", \"default\"]}\n    with layout_config:\n        seq = tvm.transform.Sequential([relay.transform.ConvertLayout(desired_layouts)])\n        with tvm.transform.PassContext(opt_level=3):\n            mod = seq(mod)\n    mod = relay.transform.recast(mod, \"int4\", \"int32\")\n\n    tasks = autotvm.task.extract_from_program(\n        mod, target=target, params=params, ops=(relay.op.get(\"nn.conv2d\"),)\n    )\n\n    assert len(tasks) == 1\n    task = tasks[0]\n\n    space = task.config_space\n\n    idx1 = space.get_rand_index()\n    idx2 = space.get_rand_index()\n\n    cfg = space.get(idx1)\n    sch, arg_bufs = task.instantiate(cfg)\n    fea1 = autotvm.feature.get_itervar_feature_flatten(sch, arg_bufs, take_log=True)\n\n    cfg = space.get(idx2)\n    sch, arg_bufs = task.instantiate(cfg)\n    fea2 = autotvm.feature.get_itervar_feature_flatten(sch, arg_bufs, take_log=True)\n\n    assert len(fea1) == len(fea2)\n\n\n@tvm.testing.requires_tensorcore\ndef test_conv2d_hwnc_tensorcore():\n    \"\"\"Test the conv2d with tensorcore for hwnc layout\"\"\"\n    verify_conv2d_hwnc(8, 64, 56, 64, 3, 1, 1, dtype=\"int8\")\n    verify_conv2d_hwnc(8, 64, 56, 64, 1, 1, 0, dtype=\"int4\")\n    verify_conv2d_hwnc(8, 64, 56, 128, 3, 2, 1)\n    verify_conv2d_hwnc(8, 64, 56, 64, 1, 2, 0)\n    verify_conv2d_hwnc(8, 128, 28, 128, 3, 1, 1)\n    verify_conv2d_hwnc(8, 128, 28, 256, 3, 2, 1)\n    verify_conv2d_hwnc(8, 128, 28, 256, 1, 2, 0)\n    verify_conv2d_hwnc(8, 256, 14, 256, 3, 1, 1)\n    verify_conv2d_hwnc(8, 256, 14, 512, 3, 2, 1)\n    verify_conv2d_hwnc(8, 256, 14, 512, 1, 2, 0)\n    verify_conv2d_hwnc(8, 512, 9, 512, 3, 1, 1)\n    verify_feature_length()\n\n\nif __name__ == \"__main__\":\n    test_conv2d_hwnc_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.conv2d import _get_workload\nfrom tvm.topi.generic.conv2d import fallback_schedule_cpu_common_int8\n\nfrom common import Int8Fallback\nimport tvm.testing\nimport pytest\nimport platform\n\n\ndef compile_conv2d_NHWC_gemm_int8_arm(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\", dtype=\"int8\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\", dtype=\"int8\")\n    bias = te.placeholder((num_filter,), name=\"bias\", dtype=\"int8\")\n    dtype = \"int32\"\n    devices = [\n        (\n            \"llvm --device arm_cpu --mtriple aarch64-linux-gnu\",\n            topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved,\n            topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved,\n        ),\n        (\n            \"llvm --device arm_cpu --mtriple aarch64-linux-gnu -mattr=+v8.2a,+dotprod\",\n            topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved,\n            topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved,\n        ),\n        (\n            \"llvm --device arm_cpu --mtriple aarch64-linux-gnu -mattr=+v8.2a,+dotprod\",\n            topi.arm_cpu.compute_conv2d_NHWC_quantized_native,\n            topi.arm_cpu.schedule_conv2d_NHWC_quantized_native,\n        ),\n        # TODO(giuseros) Need LLVM-11 in order to compile with +i8mm extension\n        # (\n        #   \"llvm --device arm_cpu --mtriple aarch64-linux-gnu -mattr=+v8.2a,+i8mm\",\n        #   topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved,\n        #   topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved,\n        # ),\n    ]\n\n    for device_tuple in devices:\n        target = device_tuple[0]\n        compute = device_tuple[1]\n        schedule = device_tuple[2]\n\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Compiling on arm AArch64 target: %s\" % target)\n        with tvm.target.Target(target) as tvm_target:\n            assert tvm_target.features.is_aarch64, \"AArch64 target not recognized\"\n\n            C = compute(A, W, (stride, stride), padding, (dilation, dilation), dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = schedule([C])\n\n        if add_bias:\n            tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%dnnn_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n\n\ndef verify_conv2d_NHWC_gemm_int8(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\", dtype=\"int8\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\", dtype=\"int8\")\n    bias = te.placeholder((num_filter,), name=\"bias\", dtype=\"int8\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_int8.verify_conv2d_nchw\")\n    def get_ref_data():\n        a_np = np.random.randint(low=-128, high=127, size=a_shape).astype(dtype)\n        w_np = np.random.randint(low=-128, high=128, size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        c_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding).astype(dtype)\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            C = topi.arm_cpu.compute_conv2d_NHWC_quantized_interleaved(\n                A, W, (stride, stride), padding, (dilation, dilation), dtype\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = topi.arm_cpu.schedule_conv2d_NHWC_quantized_interleaved([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    check_target(\"llvm\")\n\n\ndef verify_conv2d_NCHWc_int8(\n    in_dtype,\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\", dtype=in_dtype)\n    W = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\", dtype=in_dtype)\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    dtype = A.dtype\n    out_dtype = \"int32\" if in_dtype == \"int8\" else \"uint32\"\n    lo = -128 if in_dtype == \"int8\" else 0\n    hi = 127 if in_dtype == \"int8\" else 255\n\n    def check_target(target, compute, schedule, oc_block_factor, build_only):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        if target == \"cuda\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            print(\"Skip because int8 intrinsics are not available\")\n            return\n\n        bias = te.placeholder(\n            (num_filter // oc_block_factor, 1, 1, oc_block_factor), name=\"bias\", dtype=out_dtype\n        )\n        bias_shape = get_const_tuple(bias.shape)\n\n        @memoize(\"topi.tests.test_topi_conv2d_int8.verify_conv2d_nchw\")\n        def get_ref_data():\n            a_np = np.random.randint(low=lo, high=hi, size=a_shape).astype(out_dtype)\n            w_np = np.random.randint(low=lo, high=hi, size=w_shape).astype(out_dtype)\n            b_np = np.random.uniform(size=bias_shape).astype(out_dtype)\n            dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n            c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding).astype(\n                out_dtype\n            )\n\n            # convert to NCHWc\n            _, _, out_height, out_width = c_np.shape\n            c_np = c_np.reshape(\n                (batch, num_filter // oc_block_factor, oc_block_factor, out_height, out_width)\n            ).transpose(0, 1, 3, 4, 2)\n\n            if add_bias:\n                b_np = np.random.uniform(size=bias_shape).astype(out_dtype)\n                c_np += b_np\n            if add_relu:\n                c_np = np.maximum(c_np, 0)\n\n            return a_np, w_np, b_np, c_np\n\n        a_np, w_np, b_np, c_np = get_ref_data()\n\n        with tvm.target.Target(target):\n            C = compute(\n                A,\n                W,\n                (stride, stride),\n                padding,\n                (dilation, dilation),\n                \"NCHW\",\n                \"NCHW\",\n                out_dtype,\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = schedule([C])\n\n        a = tvm.nd.array(a_np.astype(dtype), dev)\n        w = tvm.nd.array(w_np.astype(dtype), dev)\n        b = tvm.nd.array(b_np.astype(out_dtype), dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n        if add_bias:\n            compile_args = [A, W, bias, C]\n            run_args = [a, w, b, c]\n        else:\n            compile_args = [A, W, C]\n            run_args = [a, w, c]\n\n        func = tvm.build(\n            s,\n            compile_args,\n            target,\n            name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n            % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n        )\n\n        if build_only:\n            return\n\n        print(\"Running on target: %s\" % target)\n\n        func(*run_args)\n\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    targets = [\n        (\n            \"cuda\",\n            lambda a, w, s, p, d, l, ol, o: topi.cuda.conv2d_NCHWc_int8(a, w, s, p, d, l, o),\n            topi.cuda.schedule_conv2d_NCHWc_int8,\n            4,\n            False,\n        ),\n        # Disable on CI since it does not support spirv int8 dot product\n        # (\n        #     \"vulkan -from_device=0\",\n        #     lambda a, w, s, p, d, l, ol, o: topi.cuda.conv2d_NCHWc_int8(a, w, s, p, d, l, o),\n        #     topi.cuda.schedule_conv2d_NCHWc_int8,\n        #     4,\n        #     False,\n        # ),\n    ]\n\n    build_only_aarch64 = platform.machine() != \"aarch64\"\n\n    targets.append(\n        (\n            \"llvm -device arm_cpu -mtriple aarch64-linux-gnu -mattr=+neon,+v8.2a,+dotprod\",\n            topi.arm_cpu.conv2d_NCHWc_int8,\n            topi.arm_cpu.schedule_conv2d_NCHWc_int8,\n            8,\n            build_only_aarch64,\n        )\n    )\n\n    if in_dtype == \"int8\":\n        targets += [\n            (\n                \"llvm -device arm_cpu -mtriple aarch64-linux-gnu -mattr=+neon\",\n                topi.arm_cpu.conv2d_NCHWc_int8,\n                topi.arm_cpu.schedule_conv2d_NCHWc_int8,\n                8,\n                build_only_aarch64,\n            ),\n            (\n                \"rocm -mattr=+dotprod\",\n                lambda a, w, s, p, d, l, ol, o: topi.cuda.conv2d_NCHWc_int8(a, w, s, p, d, l, o),\n                topi.cuda.schedule_conv2d_NCHWc_int8,\n                4,\n                False,\n            ),\n        ]\n\n    for target, compute, schedule, oc_block_factor, build_only in targets:\n        check_target(target, compute, schedule, oc_block_factor, build_only)\n\n\ndef verify_conv2d_nchw_int8(\n    in_dtype,\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\", dtype=in_dtype)\n    W = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\", dtype=in_dtype)\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\", dtype=in_dtype)\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_int8.verify_conv2d_nchw\")\n    def get_ref_data():\n        a_np = np.random.randint(low=-128, high=127, size=a_shape).astype(dtype)\n        w_np = np.random.randint(low=-128, high=128, size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding).astype(dtype)\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def verify_workload_padding():\n        _, _, out_height, out_width = get_const_tuple(c_np.shape)\n        wkl = _get_workload(A, W, (stride, stride), padding, dilation, dtype)\n\n        # for testing functionality,\n        # we choose arbitrary int32_lanes and num_int8_elements can divide the channel,\n        # regardless of the performance.\n        int32_lanes, num_int8_elements = num_filter, in_channel\n\n        # check if tile_ow candidates are the factors of the right output weight.\n        cfg = autotvm.get_config()\n        fallback_schedule_cpu_common_int8(cfg, wkl, int32_lanes, num_int8_elements)\n        ow_tile = np.prod(cfg[\"tile_ow\"].size)\n\n        tvm.testing.assert_allclose(ow_tile, out_width)\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        if target == \"cuda\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            print(\"Skip because int8 intrinsics are not available\")\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            C = topi.cuda.conv2d_nchw_int8(\n                A, W, (stride, stride), padding, (dilation, dilation), dtype\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = topi.cuda.schedule_conv2d_nchw_int8([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    verify_workload_padding()\n\n    for target in [\"cuda\"]:\n        check_target(target)\n\n\n@pytest.mark.parametrize(\"in_dtype\", [\"int8\", \"uint8\"])\ndef test_conv2d_nchw(in_dtype):\n    with Int8Fallback():\n        # ResNet18 workloads where channels in / out are multiple of oc_block_factor\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 128, 3, 2, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 128, 1, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 28, 128, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 28, 256, 3, 2, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 28, 256, 1, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 256, 14, 256, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 256, 14, 512, 3, 2, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 256, 14, 512, 1, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 512, 7, 512, 3, 1, 1)\n\n        # bias, relu\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, add_relu=True)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, add_bias=True)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, add_bias=True, add_relu=True)\n\n        # dilation = 2\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, dilation=2)\n\n        # batch size\n        verify_conv2d_NCHWc_int8(in_dtype, 4, 64, 56, 64, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 9, 64, 56, 64, 3, 1, 1)\n\n        # weird workloads\n        verify_conv2d_NCHWc_int8(in_dtype, 4, 4, 4, 8, 4, 4, 4)\n\n        # inception v3 workloads where channels in / out are multiple of oc_block_factor\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 32, 149, 32, 3, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 32, 147, 64, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 73, 80, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 80, 73, 192, 3, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 35, 64, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 35, 48, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 48, 35, 64, 5, 1, 2)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 35, 96, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 96, 35, 96, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 35, 32, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 256, 35, 64, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 256, 35, 48, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 288, 35, 64, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 288, 35, 48, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 288, 35, 384, 3, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 96, 35, 96, 3, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 768, 17, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 768, 17, 128, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 17, 128, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 17, 192, 7, 1, 3)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 17, 128, 7, 1, 3)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 17, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 768, 17, 160, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 160, 17, 160, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 160, 17, 192, 7, 1, 3)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 160, 17, 160, 7, 1, 3)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 160, 17, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 17, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 17, 192, 7, 1, 3)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 17, 320, 3, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 192, 17, 192, 3, 2, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 1280, 8, 320, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 1280, 8, 384, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 384, 8, 384, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 384, 8, 384, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 1280, 8, 448, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 448, 8, 384, 3, 1, 1)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 1280, 8, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 2048, 8, 320, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 2048, 8, 384, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 2048, 8, 448, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 2048, 8, 192, 1, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 1024, 19, 88, 3, 1, 1)\n\n        # batch > 1\n        verify_conv2d_NCHWc_int8(in_dtype, 7, 32, 149, 32, 3, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 8, 32, 149, 32, 3, 1, 0)\n        verify_conv2d_NCHWc_int8(in_dtype, 32, 32, 149, 32, 3, 1, 0)\n\n        # Asymmetric padding\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 32, 35, 64, 7, 2, (0, 0, 1, 1))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 128, 3, 1, (3, 3, 2, 2))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 64, 1, 1, (1, 2, 2, 1))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 17, 192, 1, 1, (1, 2))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 64, 3, 1, (3, 1))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 128, 8, 384, 3, 1, (0, 2))\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 64, 1, 1, \"VALID\")\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 392, 8, 64, 3, 1, \"VALID\")\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 512, 19, 64, 1, 1, \"SAME\")\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 16, 32, 2, 1, \"SAME\")\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 64, 3, 1, (1, 2, 2, 1), add_relu=True)\n        verify_conv2d_NCHWc_int8(in_dtype, 1, 64, 8, 64, 5, 2, (1, 3), add_bias=True)\n        verify_conv2d_NCHWc_int8(\n            in_dtype, 1, 64, 56, 64, 3, 1, \"VALID\", add_bias=True, add_relu=True\n        )\n        verify_conv2d_NCHWc_int8(\n            in_dtype, 1, 64, 56, 64, 24, 1, \"SAME\", add_bias=True, add_relu=True\n        )\n\n        # Conv2d NCHW int8 schedule testing. Internally, it uses NCHWc schedule. So, just\n        # performing basic testing - one test for all different scenarios - batch, dilation etc..\n        verify_conv2d_nchw_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1)\n        verify_conv2d_nchw_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, add_relu=True)\n        verify_conv2d_nchw_int8(in_dtype, 1, 64, 56, 64, 3, 1, 1, dilation=2)\n        verify_conv2d_nchw_int8(in_dtype, 9, 64, 56, 64, 3, 1, 1)\n        verify_conv2d_nchw_int8(in_dtype, 4, 4, 4, 4, 4, 4, 4)\n        verify_conv2d_nchw_int8(in_dtype, 1, 32, 149, 32, 3, 1, 0)\n        verify_conv2d_nchw_int8(in_dtype, 7, 32, 149, 32, 3, 1, 0)\n        verify_conv2d_nchw_int8(in_dtype, 1, 32, 35, 64, 7, 2, (0, 0, 1, 1))\n        verify_conv2d_nchw_int8(in_dtype, 1, 32, 35, 64, 7, 2, (0, 0, 2, 2))\n\n\ndef test_conv2d_nhwc():\n    with Int8Fallback():\n        # Subset of inception v3 expanded (dilation > 1, batch > 1, 'VALID' padding)\n        verify_conv2d_NHWC_gemm_int8(1, 3, 299, 32, 3, 2, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 32, 149, 32, 3, 1, \"SAME\", dilation=2)\n        verify_conv2d_NHWC_gemm_int8(4, 32, 147, 64, 3, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 64, 73, 80, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 80, 73, 192, 3, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 35, 48, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 35, 64, 1, 1, \"VALID\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 35, 32, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 48, 35, 64, 5, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 96, 35, 96, 3, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 256, 35, 48, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 256, 35, 64, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 288, 35, 64, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 288, 35, 48, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 96, 35, 96, 3, 2, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 128, 17, 192, 7, 1, \"SAME\", dilation=2)\n        verify_conv2d_NHWC_gemm_int8(1, 160, 17, 160, 7, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 160, 17, 192, 1, 1, \"VALID\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 17, 192, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 768, 5, 128, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 17, 320, 3, 2, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 192, 17, 192, 3, 2, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 1280, 8, 192, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 1280, 8, 384, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 1280, 8, 320, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 1280, 8, 448, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 384, 8, 384, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 384, 8, 384, 3, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 448, 8, 384, 3, 1, \"VALID\")\n        verify_conv2d_NHWC_gemm_int8(1, 2048, 8, 320, 1, 1, \"SAME\")\n        verify_conv2d_NHWC_gemm_int8(1, 2048, 8, 448, 1, 1, \"SAME\", add_bias=True, add_relu=True)\n        verify_conv2d_NHWC_gemm_int8(1, 2048, 8, 192, 1, 1, \"SAME\", add_bias=True)\n\n        # Let's also verify that it compiles fine on AArch64 targets\n        compile_conv2d_NHWC_gemm_int8_arm(1, 3, 299, 32, 3, 2, \"SAME\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\n\nimport sys\n\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import autotvm, te, topi\nimport tvm.topi.testing\nfrom tvm.contrib import cudnn\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.conv2d import _get_workload\nfrom tvm.topi.x86.conv2d_avx_common import _fallback_schedule\n\nimport tvm.testing\n\ndtype = tvm.testing.parameter(\"float16\", \"float32\")\nrandom_seed = tvm.testing.parameter(0)\n\n\n@tvm.testing.fixture\ndef input_shape(batch, in_channel, in_size):\n    return (batch, in_channel, in_size, in_size)\n\n\n@tvm.testing.fixture\ndef weight_shape(num_filter, in_channel, kernel):\n    return (num_filter, in_channel, kernel, kernel)\n\n\n@tvm.testing.fixture\ndef bias_shape(num_filter):\n    return (num_filter, 1, 1)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(\n    random_seed,\n    input_shape,\n    weight_shape,\n    bias_shape,\n    dtype,\n    stride,\n    padding,\n    dilation,\n    add_bias,\n    apply_relu,\n):\n    np.random.seed(random_seed)\n\n    # scipy.signal.convolve2d does not support float16 data types, and\n    # the python fallback is too slow for general use.  Computing\n    # ref_data in float32 will have fewer rounding errors than the TVM\n    # float16 compute, but those vary based on schedule anyways.\n    conv_dtype = \"float32\" if dtype == \"float16\" else dtype\n\n    a_np = np.random.uniform(size=input_shape).astype(dtype)\n    w_np = np.random.uniform(size=weight_shape).astype(dtype)\n    b_np = np.random.uniform(size=bias_shape).astype(dtype)\n    dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n    c_np = tvm.topi.testing.conv2d_nchw_python(\n        a_np.astype(conv_dtype), dw_np.astype(conv_dtype), stride, padding\n    ).astype(dtype)\n\n    if add_bias:\n        c_np = c_np + b_np\n    if apply_relu:\n        c_np = np.maximum(c_np, 0)\n    return a_np, w_np, b_np, c_np\n\n\nclass BaseConv2DTests:\n    add_bias = tvm.testing.parameter(False)\n    apply_relu = tvm.testing.parameter(False)\n    dilation = tvm.testing.parameter(1)\n    batch = tvm.testing.parameter(1)\n\n    def test_conv2d_nchw(\n        self,\n        target,\n        dev,\n        batch,\n        in_channel,\n        in_size,\n        num_filter,\n        kernel,\n        stride,\n        padding,\n        dtype,\n        ref_data,\n        dilation,\n        add_bias,\n        apply_relu,\n    ):\n        target = tvm.target.Target(target)\n        is_cudnn_target = target.kind.name == \"cuda\" and \"cudnn\" in target.attrs.get(\"libs\", [])\n\n        if target.kind.name == \"vulkan\" and dtype == \"float16\":\n            if not target.attrs.get(\"supports_float16\", False) or not target.attrs.get(\n                \"supports_16bit_buffer\", False\n            ):\n                pytest.xfail(\"Vulkan device does not support float16\")\n\n        if (\n            target.kind.name == \"cuda\"\n            and dtype == \"float16\"\n            and not tvm.contrib.nvcc.have_fp16(dev.compute_version)\n        ):\n            pytest.xfail(\"CUDA float16 intrinsics not available\")\n\n        pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n        padding_sum = pad_top + pad_left + pad_bottom + pad_right\n\n        has_asymmetric_padding = (pad_top != pad_bottom) or (pad_left != pad_right)\n        if is_cudnn_target and has_asymmetric_padding:\n            pytest.xfail(\"CuDNN does not support asymmetric padding\")\n\n        a_np, w_np, b_np, c_np = ref_data\n\n        A = te.placeholder(a_np.shape, name=\"A\", dtype=dtype)\n        W = te.placeholder(w_np.shape, name=\"W\", dtype=dtype)\n        bias = te.placeholder(b_np.shape, name=\"bias\", dtype=dtype)\n\n        if \"int\" in dtype:\n            tol = {\"atol\": 0, \"rtol\": 0}\n        elif dtype == \"float32\":\n            tol = {\"rtol\": 1e-4, \"atol\": 2e-4}\n        elif dtype == \"float16\":\n            # A summation in float16 with a single accumulator very\n            # quickly runs into large rounding errors.  At some point,\n            # this tolerance should be schedule-dependent for to avoid\n            # false negatives.\n            num_values_summed = in_channel * kernel * kernel\n            gap_size = np.nextafter(c_np.max(), np.inf, dtype=c_np.dtype) - c_np.max()\n            tol = {\"rtol\": 1e-3, \"atol\": num_values_summed * gap_size / 2}\n\n        with autotvm.tophub.context(target):  # load tophub pre-tuned parameters\n            if is_cudnn_target:\n                fcompute, fschedule = topi.cuda.conv2d_cudnn, topi.cuda.schedule_conv2d_cudnn\n            else:\n                fcompute, fschedule = tvm.topi.testing.get_conv2d_nchw_implement(target)\n\n            with target:\n                if is_cudnn_target:\n                    C = fcompute(\n                        A, W, (stride, stride), padding, (dilation, dilation), 1, \"NCHW\", dtype\n                    )\n                else:\n                    C = fcompute(A, W, (stride, stride), padding, (dilation, dilation), dtype)\n                if add_bias:\n                    C = topi.add(C, bias)\n                if apply_relu:\n                    C = topi.nn.relu(C)\n                s = fschedule([C])\n\n            a = tvm.nd.array(a_np, dev)\n            w = tvm.nd.array(w_np, dev)\n            b = tvm.nd.array(b_np, dev)\n\n            c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"conv2d_{}_{}_{}_{}_{}_{}_{}_{}_{}\".format(\n                    dtype,\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding_sum,\n                    dilation,\n                ),\n            )\n            func(a, w, b, c)\n            tvm.testing.assert_allclose(c.numpy(), c_np, **tol)\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_workload_padding(\n        self,\n        target,\n        input_shape,\n        weight_shape,\n        stride,\n        padding,\n        dilation,\n        dtype,\n        ref_data,\n    ):\n        a_np, w_np, b_np, c_np = ref_data\n        _, _, out_height, out_width = c_np.shape\n\n        A = te.placeholder(input_shape, name=\"A\", dtype=dtype)\n        W = te.placeholder(weight_shape, name=\"W\", dtype=dtype)\n\n        with tvm.target.Target(target):\n            wkl = _get_workload(A, W, (stride, stride), padding, dilation, dtype)\n\n            # check if tile_ow candidates are the factors of the right output weight.\n            cfg = autotvm.get_config()\n            _fallback_schedule(cfg, wkl)\n            ow_tile = np.prod(cfg[\"tile_ow\"].size)\n\n        tvm.testing.assert_allclose(ow_tile, out_width)\n\n\nclass TestResNet18Workloads(BaseConv2DTests):\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (3, 224, 64, 7, 2, 3),\n        (64, 56, 64, 3, 1, 1),\n        (64, 56, 64, 1, 1, 0),\n        (64, 56, 128, 3, 2, 1),\n        (64, 56, 128, 1, 2, 0),\n        (128, 28, 128, 3, 1, 1),\n        (128, 28, 256, 3, 2, 1),\n        (128, 28, 256, 1, 2, 0),\n        (256, 14, 256, 3, 1, 1),\n        (256, 14, 512, 3, 2, 1),\n        (256, 14, 512, 1, 2, 0),\n        (512, 7, 512, 3, 1, 1),\n    )\n\n\nclass TestInceptionV3Workloads(BaseConv2DTests):\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (3, 299, 32, 3, 2, 0),\n        (32, 149, 32, 3, 1, 0),\n        (32, 147, 64, 3, 1, 1),\n        (64, 73, 80, 1, 1, 0),\n        (80, 73, 192, 3, 1, 0),\n        (192, 35, 64, 1, 1, 0),\n        (192, 35, 48, 1, 1, 0),\n        (48, 35, 64, 5, 1, 2),\n        (64, 35, 96, 3, 1, 1),\n        (96, 35, 96, 3, 1, 1),\n        (192, 35, 32, 1, 1, 0),\n        (256, 35, 64, 1, 1, 0),\n        (256, 35, 48, 1, 1, 0),\n        (288, 35, 64, 1, 1, 0),\n        (288, 35, 48, 1, 1, 0),\n        (288, 35, 384, 3, 2, 0),\n        (96, 35, 96, 3, 2, 0),\n        (768, 17, 192, 1, 1, 0),\n        (768, 17, 128, 1, 1, 0),\n        (128, 17, 128, 1, 1, 0),\n        (128, 17, 192, 7, 1, 3),\n        (128, 17, 128, 7, 1, 3),\n        (128, 17, 192, 1, 1, 0),\n        (768, 17, 160, 1, 1, 0),\n        # disable these tests due to some bugs of llvm with nvptx\n        # (160,  17, 160, 1, 1, 0),\n        (160, 17, 192, 7, 1, 3),\n        (160, 17, 160, 7, 1, 3),\n        (160, 17, 192, 1, 1, 0),\n        (192, 17, 192, 1, 1, 0),\n        (192, 17, 192, 7, 1, 3),\n        (192, 17, 320, 3, 2, 0),\n        (192, 17, 192, 3, 2, 0),\n        (1280, 8, 320, 1, 1, 0),\n        (1280, 8, 384, 1, 1, 0),\n        (384, 8, 384, 1, 1, 0),\n        (384, 8, 384, 3, 1, 1),\n        (1280, 8, 448, 1, 1, 0),\n        (448, 8, 384, 3, 1, 1),\n        (1280, 8, 192, 1, 1, 0),\n        (2048, 8, 320, 1, 1, 0),\n        (2048, 8, 384, 1, 1, 0),\n        (2048, 8, 448, 1, 1, 0),\n        (2048, 8, 192, 1, 1, 0),\n        (1024, 19, 84, 3, 1, 1),\n        (2048, 10, 126, 3, 1, 1),\n        (512, 5, 126, 3, 1, 1),\n        (256, 3, 126, 3, 1, 1),\n    )\n\n\nclass TestWeirdWorkloads(BaseConv2DTests):\n    batch, in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (2, 2, 2, 2, 2, 2, 2),\n        (3, 3, 3, 3, 3, 3, 3),\n        (4, 4, 4, 4, 4, 4, 4),\n        (5, 5, 5, 5, 5, 5, 5),\n        (6, 6, 6, 6, 6, 6, 6),\n        # disable these tests due to some bugs of llvm with nvptx\n        # (1, 1, 1, 1, 1, 1, 1),\n        # (2, 13, 71, 59, 3, 1, 1),\n    )\n\n\nclass TestAsymmetricPadding(BaseConv2DTests):\n    dilation = tvm.testing.parameter(1, 2)\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (3, 35, 64, 7, 2, (0, 0, 1, 1)),\n        (64, 8, 128, 3, 1, (3, 3, 2, 2)),\n        (64, 8, 64, 1, 1, (1, 2, 2, 1)),\n        (64, 17, 192, 1, 1, (1, 2)),\n        (64, 8, 64, 3, 1, (3, 1)),\n        (128, 8, 384, 3, 1, (0, 2)),\n        (64, 35, 64, 3, 1, (1, 2)),\n        (64, 8, 64, 1, 1, \"VALID\"),\n        (388, 8, 64, 3, 1, \"VALID\"),\n        (64, 10, 48, 3, 1, \"VALID\"),\n        (512, 19, 64, 1, 1, \"SAME\"),\n        (64, 5, 32, 2, 1, \"SAME\"),\n        (64, 8, 64, 3, 1, \"SAME\"),\n        (64, 8, 64, 3, 1, (1, 2, 2, 1)),\n        (64, 8, 64, 5, 2, (1, 3)),\n        (64, 8, 64, 3, 1, \"VALID\"),\n        (64, 8, 64, 24, 1, \"SAME\"),\n        (32, 35, 64, 7, 2, (0, 0, 2, 2)),\n    )\n\n\nclass TestBatchSize(BaseConv2DTests):\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (64, 56, 64, 3, 1, 1),\n    )\n    batch = tvm.testing.parameter(1, 4, 9)\n\n\nclass TestBiasRelu(BaseConv2DTests):\n    apply_relu = tvm.testing.parameter(True, False, ids=[\"relu\", \"no_relu\"])\n    add_bias = tvm.testing.parameter(True, False, ids=[\"bias\", \"no_bias\"])\n    in_channel, in_size, num_filter, kernel, stride, padding = tvm.testing.parameters(\n        (64, 56, 64, 3, 1, 1),\n        (64, 8, 64, 3, 1, (1, 2, 2, 1)),\n        (64, 8, 64, 5, 2, (1, 3)),\n        (64, 8, 64, 3, 1, \"VALID\"),\n        (64, 8, 64, 24, 1, \"SAME\"),\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_nhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv2d_nhwc_implement = {\n    \"generic\": (topi.nn.conv2d_nhwc, topi.generic.schedule_conv2d_nhwc),\n    \"gpu\": (topi.gpu.conv2d_nhwc, topi.gpu.schedule_conv2d_nhwc),\n    \"cpu\": (topi.nn.conv2d_nhwc, topi.x86.schedule_conv2d_nhwc),\n    \"arm_cpu\": (\n        topi.arm_cpu.conv2d_nhwc_spatial_pack,\n        topi.arm_cpu.schedule_conv2d_nhwc_spatial_pack,\n    ),\n    \"mali\": (\n        topi.mali.conv2d_nhwc_spatial_pack,\n        topi.mali.schedule_conv2d_nhwc_spatial_pack,\n    ),\n    \"bifrost\": (\n        topi.mali.conv2d_nhwc_spatial_pack,\n        topi.mali.schedule_conv2d_nhwc_spatial_pack,\n    ),\n    \"hls\": (topi.nn.conv2d_nhwc, topi.hls.schedule_conv2d_nhwc),\n}\n\ndtype = tvm.testing.parameter(\"float32\")\n\nbatch, in_channel, in_size, num_filter, kernel, stride, padding, dilation = tvm.testing.parameters(\n    (1, 256, 32, 256, 3, 1, \"SAME\", 1),\n    (4, 128, 16, 128, 5, 2, \"SAME\", 1),\n    (4, 128, 16, 256, 5, 2, \"SAME\", 1),\n    (1, 256, 32, 256, 3, 1, \"VALID\", 1),\n    (1, 256, 32, 256, 3, 1, \"VALID\", 1),\n    (4, 128, 16, 128, 5, 2, \"VALID\", 1),\n    (4, 128, 16, 256, 5, 2, \"VALID\", 1),\n    (1, 128, 16, 256, 3, 2, (0, 0, 1, 1), 1),\n    (1, 128, 16, 256, 3, 2, (1, 1, 2, 2), 1),\n    (1, 128, 16, 128, 5, 2, (3, 3, 2, 2), 1),\n    (1, 128, 16, 256, 3, 2, (0, 1, 2, 3), 1),\n    (1, 256, 32, 256, 3, 1, \"SAME\", 2),\n    (1, 256, 32, 256, 3, 1, (1, 1, 2, 2), 2),\n)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(dtype, batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation):\n    in_height = in_width = in_size\n    a_shape = (batch, in_height, in_width, in_channel)\n    w_shape = (kernel, kernel, in_channel, num_filter)\n\n    a_np = np.random.uniform(size=a_shape).astype(dtype)\n    w_np = np.random.uniform(size=w_shape).astype(dtype)\n    dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n    b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n    return a_np, w_np, b_np\n\n\ndef test_conv2d_nhwc_hwio(target, dev, ref_data, dtype, stride, padding, dilation):\n    a_np, w_np, b_np = ref_data\n\n    A = te.placeholder(a_np.shape, name=\"A\", dtype=dtype)\n    W = te.placeholder(w_np.shape, name=\"W\", dtype=dtype)\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv2d_nhwc_implement)\n        B = fcompute(A, W, stride, padding, dilation, dtype)\n        s = fschedule([B])\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], target)\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\ndef test_conv2d_nhwc_ohwi(ref_data, dtype, stride, padding, dilation):\n    # only test on CPU target because topi doesn't have schedules for this layout\n    target = \"llvm\"\n    dev = tvm.device(target, 0)\n    a_np, w_np_hwio, b_np = ref_data\n    w_np_ohwi = w_np_hwio.transpose(3, 0, 1, 2)  # HWIO -> OHWI\n\n    A = te.placeholder(a_np.shape, name=\"A\", dtype=dtype)\n    W = te.placeholder(w_np_ohwi.shape, name=\"W\", dtype=dtype)\n\n    B = topi.nn.conv2d(\n        A,\n        W,\n        stride,\n        padding,\n        dilation,\n        data_layout=\"NHWC\",\n        kernel_layout=\"OHWI\",\n        out_dtype=\"float32\",\n    )\n    s = tvm.te.create_schedule(B.op)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np_ohwi, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], target)\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_nhwc_pack_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\nimport pytest\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import FallbackConfigEntity\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef verify_conv2d_1x1_nhwc_pack_int8(\n    batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation=1\n):\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\", dtype=\"uint8\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\", dtype=\"int8\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    adtype = A.dtype\n    wdtype = W.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_1x1_nhwc_pack_int8.verify_nhwc.v2\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(adtype)\n        w_np = np.random.uniform(size=w_shape).astype(wdtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        b_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n\n        with tvm.target.Target(device):\n            B = topi.nn.conv2d(A, W, stride, padding, dilation, layout=\"NHWC\", out_dtype=\"int32\")\n            s = topi.x86.schedule_conv2d_nhwc_pack_int8([B])\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        func = tvm.build(s, [A, W, B], device)\n        func(a, w, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n    # for device in ['llvm -mcpu=skylake-avx512']:\n    for device in [\"llvm\"]:\n        check_device(device)\n\n\n# TODO(@llyfacebook): Please fix https://github.com/apache/tvm/issues/4122 to enable this test.\n@pytest.mark.skip\ndef test_conv2d_nhwc():\n    verify_conv2d_1x1_nhwc_pack_int8(1, 256, 32, 256, 1, 1, 0)\n\n\nif __name__ == \"__main__\":\n    # test_conv2d_nhwc()\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_nhwc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm import te\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.contrib import nvcc\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv2d_nhwc_tensorcore_implement = {\n    \"cuda\": (topi.cuda.conv2d_nhwc_tensorcore, topi.cuda.schedule_conv2d_nhwc_tensorcore)\n}\n\n\ndef verify_conv2d_nhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    devices=\"cuda\",\n):\n    \"\"\"Test the conv2d with tensorcore for nhwc layout\"\"\"\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    bias = te.placeholder((1, 1, 1, num_filter), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_nhwc.verify_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        if not nvcc.have_tensorcore(dev.compute_version):\n            print(\"skip because gpu does not support Tensor Cores\")\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            fcompute, fschedule = tvm.topi.testing.dispatch(\n                device, _conv2d_nhwc_tensorcore_implement\n            )\n            C = fcompute(A, W, stride, padding, dilation, \"float32\")\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n\n        rtol = 1e-3\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=rtol)\n\n    check_device(devices)\n\n\n@tvm.testing.requires_cuda\n@tvm.testing.requires_gpu\ndef test_conv2d_nhwc_tensorcore():\n    \"\"\"Test the conv2d with tensorcore for nhwc layout\"\"\"\n    verify_conv2d_nhwc(16, 16, 14, 16, 3, 1, 1)\n    verify_conv2d_nhwc(16, 128, 7, 128, 7, 1, 3)\n    verify_conv2d_nhwc(16, 160, 7, 160, 7, 1, 3)\n\n    verify_conv2d_nhwc(32, 64, 14, 64, 3, 1, 1, add_bias=True)\n    verify_conv2d_nhwc(32, 64, 14, 64, 3, 1, 1, add_relu=True)\n    verify_conv2d_nhwc(32, 64, 14, 64, 3, 1, 1, add_relu=True, add_bias=True)\n\n    verify_conv2d_nhwc(16, 64, 17, 64, 7, 1, (3, 3, 2, 2))\n    verify_conv2d_nhwc(16, 64, 17, 64, 7, 1, \"SAME\")\n    verify_conv2d_nhwc(16, 48, 35, 48, 5, 1, \"VALID\")\n    verify_conv2d_nhwc(16, 48, 56, 48, 3, 1, (1, 1, 1, 1))\n    verify_conv2d_nhwc(16, 64, 28, 64, 3, 1, (1, 1, 1, 1))\n\n\nif __name__ == \"__main__\":\n    test_conv2d_nhwc_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_nhwc_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n# pylint: disable=bad-whitespace\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm import te\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv2d_nhwc_winograd_tensorcore = {\n    \"cuda\": (\n        topi.cuda.conv2d_nhwc_winograd_tensorcore,\n        topi.cuda.schedule_conv2d_nhwc_winograd_tensorcore,\n    )\n}\n\n_conv2d_nhwc_winograd_direct = {\n    \"cuda\": (topi.cuda.conv2d_nhwc_winograd_direct, topi.cuda.schedule_conv2d_nhwc_winograd_direct)\n}\n\n\ndef verify_conv2d_nhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    devices=\"cuda\",\n    bgemm=\"direct\",\n):\n    \"\"\"Test the conv2d with winograd for nhwc layout\"\"\"\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    bias = te.placeholder((1, 1, 1, num_filter), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_nhwc_winograd.verify_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        c_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            if bgemm == \"direct\":\n                fcompute, fschedule = tvm.topi.testing.dispatch(\n                    device, _conv2d_nhwc_winograd_direct\n                )\n            elif bgemm == \"tensorcore\":\n                fcompute, fschedule = tvm.topi.testing.dispatch(\n                    device, _conv2d_nhwc_winograd_tensorcore\n                )\n            C = fcompute(A, W, stride, padding, dilation, \"float32\")\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=2e-3)\n\n    check_device(devices)\n\n\n@tvm.testing.requires_cuda\n@tvm.testing.requires_gpu\ndef test_conv2d_nhwc_winograd_direct():\n    \"\"\"Test the conv2d with winograd for nhwc layout\"\"\"\n    # resnet 18 workloads\n    print(\"test_winograd_direct...\")\n    verify_conv2d_nhwc(1, 64, 56, 64, 3, 1, 1, bgemm=\"direct\")\n    verify_conv2d_nhwc(1, 128, 28, 128, 3, 1, 1)\n    verify_conv2d_nhwc(1, 256, 14, 256, 3, 1, 1)\n    verify_conv2d_nhwc(1, 512, 7, 512, 3, 1, 1)\n    verify_conv2d_nhwc(1, 48, 35, 64, 5, 1, 2)\n\n    # weird workloads\n    verify_conv2d_nhwc(1, 1, 1, 1, 3, 1, 1)\n    verify_conv2d_nhwc(3, 3, 3, 3, 3, 1, 1)\n    verify_conv2d_nhwc(2, 13, 71, 59, 3, 1, 1)\n\n    # Asymmetric padding\n    verify_conv2d_nhwc(1, 512, 7, 512, 3, 1, \"SAME\")\n    verify_conv2d_nhwc(2, 48, 56, 48, 3, 1, (1, 1), add_relu=True)\n    verify_conv2d_nhwc(2, 48, 56, 48, 3, 1, \"SAME\", add_relu=True, add_bias=True)\n    verify_conv2d_nhwc(1, 48, 35, 48, 5, 1, \"VALID\")\n\n\n@tvm.testing.requires_cuda\n@tvm.testing.requires_tensorcore\ndef test_conv2d_nhwc_winograd_tensorcore():\n    \"\"\"Test the conv2d with winograd for nhwc layout\"\"\"\n    verify_conv2d_nhwc(8, 64, 56, 64, 3, 1, 1, bgemm=\"tensorcore\")\n    verify_conv2d_nhwc(8, 128, 28, 128, 3, 1, 1, bgemm=\"tensorcore\")\n    verify_conv2d_nhwc(8, 256, 14, 256, 3, 1, 1, bgemm=\"tensorcore\")\n\n    verify_conv2d_nhwc(2, 64, 56, 64, 3, 1, (1, 1), add_relu=True, bgemm=\"tensorcore\")\n    verify_conv2d_nhwc(2, 64, 56, 64, 3, 1, \"SAME\", add_relu=True, bgemm=\"tensorcore\")\n\n\nif __name__ == \"__main__\":\n    test_conv2d_nhwc_winograd_direct()\n    test_conv2d_nhwc_winograd_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_transpose_nchw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for transposed convolution.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\nimport tvm.testing\n\n\n_conv2d_transpose_nchw_implement = {\n    \"generic\": (topi.nn.conv2d_transpose_nchw, topi.generic.schedule_conv2d_transpose_nchw),\n    \"cpu\": (topi.x86.conv2d_transpose_nchw, topi.x86.schedule_conv2d_transpose_nchw),\n    \"arm_cpu\": (topi.arm_cpu.conv2d_transpose_nchw, topi.arm_cpu.schedule_conv2d_transpose_nchw),\n    \"gpu\": (topi.cuda.conv2d_transpose_nchw, topi.cuda.schedule_conv2d_transpose_nchw),\n    \"hls\": (topi.nn.conv2d_transpose_nchw, topi.hls.schedule_conv2d_transpose_nchw),\n}\n\n\ndef verify_conv2d_transpose_nchw(\n    batch, in_channel, in_size, num_filter, kernel, stride, padding, output_padding\n):\n    in_height, in_width = in_size\n    kernel_height, kernel_width = kernel\n    stride_height, stride_width = stride\n    pad_top, pad_left, pad_bottom, pad_right = padding\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    W = te.placeholder((in_channel, num_filter, kernel_height, kernel_width), name=\"W\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_transpose.verify_conv2d_transpose_nchw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = tvm.topi.testing.conv2d_transpose_nchw_python(\n            a_np, w_np, stride, padding, output_padding\n        )\n        c_np = np.maximum(b_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check(fcompute, fschedule, target, dev):\n        B = fcompute(\n            A,\n            W,\n            [stride_height, stride_width],\n            [pad_top, pad_left, pad_bottom, pad_right],\n            A.dtype,\n            output_padding,\n        )\n        C = topi.nn.relu(B)\n        s1 = fschedule([B])\n        s2 = fschedule([C])\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n        func1 = tvm.build(s1, [A, W, B], target)\n        func2 = tvm.build(s2, [A, W, C], target)\n        func1(a, w, b)\n        func2(a, w, c)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    def check_generic(target, dev):\n        print(\"Running generic on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = _conv2d_transpose_nchw_implement[\"generic\"]\n            check(fcompute, fschedule, target, dev)\n\n    check_generic(\"llvm\", tvm.cpu(0))\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(\n                target, _conv2d_transpose_nchw_implement\n            )\n            check(fcompute, fschedule, target, dev)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_transpose_nchw():\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 1, (1, 1), (1, 1), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (3, 3), (1, 1), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (3, 3), (3, 3), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (3, 3), (1, 1), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (3, 3), (2, 2), (1, 1, 1, 1), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (3, 3), (2, 2), (1, 1, 1, 1), (1, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (2, 2), (2, 2), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 3, (224, 224), 32, (2, 2), (2, 2), (0, 0, 0, 0), (1, 1))\n    verify_conv2d_transpose_nchw(1, 32, (32, 32), 128, (5, 5), (1, 1), (0, 0, 0, 0), (0, 0))\n    verify_conv2d_transpose_nchw(1, 32, (32, 32), 128, (5, 5), (2, 2), (1, 1, 1, 1), (0, 0))\n    verify_conv2d_transpose_nchw(16, 32, (8192, 1), 8, (31, 1), (2, 1), (14, 0, 15, 0), (0, 0))\n    verify_conv2d_transpose_nchw(16, 512, (8, 1), 128, (31, 1), (2, 1), (14, 0, 15, 0), (0, 0))\n    verify_conv2d_transpose_nchw(16, 512, (8, 1), 128, (31, 1), (2, 1), (14, 0, 15, 0), (1, 0))\n\n\nif __name__ == \"__main__\":\n    test_conv2d_transpose_nchw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv2d_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import FallbackConfigEntity\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv2d_nchw_winograd_implement = {\n    \"arm_cpu\": (topi.arm_cpu.conv2d_nchw_winograd, topi.arm_cpu.schedule_conv2d_nchw_winograd),\n    \"cuda\": (topi.cuda.conv2d_nchw_winograd, topi.cuda.schedule_conv2d_nchw_winograd),\n    \"mali\": (topi.mali.conv2d_nchw_winograd, topi.mali.schedule_conv2d_nchw_winograd),\n}\n\n\ndef verify_conv2d_nchw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    devices=[\"cuda\", \"llvm -device=arm_cpu\", \"opencl -device=mali\"],\n):\n    pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel, kernel))\n    padding_sum = pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    W = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_winograd.verify_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            fcompute, fschedule = tvm.topi.testing.dispatch(device, _conv2d_nchw_winograd_implement)\n            C = fcompute(A, W, stride, padding, dilation, dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n\n        rtol = 1e-3\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=rtol)\n\n    for device in devices:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_nchw():\n    # inception v3 workloads\n    verify_conv2d_nchw(1, 128, 17, 192, 7, 1, 3, devices=[\"cuda\"])\n    verify_conv2d_nchw(1, 128, 17, 128, 7, 1, 3, devices=[\"cuda\"])\n    verify_conv2d_nchw(1, 160, 17, 160, 7, 1, 3, devices=[\"cuda\"])\n\n    # resnet 18 workloads\n    verify_conv2d_nchw(1, 64, 56, 64, 3, 1, 1)\n    verify_conv2d_nchw(1, 128, 28, 128, 3, 1, 1)\n    verify_conv2d_nchw(1, 256, 14, 256, 3, 1, 1)\n    verify_conv2d_nchw(1, 512, 7, 512, 3, 1, 1)\n\n    # batch size = 2\n    verify_conv2d_nchw(2, 64, 56, 64, 3, 1, 1)\n\n    # relu, bias\n    verify_conv2d_nchw(2, 64, 56, 64, 3, 1, 1, add_bias=True)\n    verify_conv2d_nchw(2, 64, 56, 64, 3, 1, 1, add_relu=True)\n    verify_conv2d_nchw(2, 64, 56, 64, 3, 1, 1, add_relu=True, add_bias=True)\n\n    # weird workloads\n    verify_conv2d_nchw(1, 1, 1, 1, 3, 1, 1)\n    verify_conv2d_nchw(3, 3, 3, 3, 3, 1, 1)\n    verify_conv2d_nchw(2, 13, 71, 59, 3, 1, 1)\n    verify_conv2d_nchw(1, 48, 35, 64, 5, 1, 2, devices=[\"cuda\"])\n\n    # Asymmetric padding\n    verify_conv2d_nchw(1, 48, 56, 48, 3, 1, (1, 1, 1, 1))\n    verify_conv2d_nchw(1, 64, 28, 64, 3, 1, (1, 1, 1, 1))\n    verify_conv2d_nchw(1, 128, 14, 128, 3, 1, (1, 1))\n    verify_conv2d_nchw(1, 512, 7, 512, 3, 1, \"SAME\")\n    verify_conv2d_nchw(2, 13, 71, 59, 3, 1, (1, 1, 1, 1))\n    verify_conv2d_nchw(2, 48, 56, 48, 3, 1, (1, 1, 1, 1), add_bias=True)\n    verify_conv2d_nchw(2, 48, 56, 48, 3, 1, (1, 1), add_relu=True)\n    verify_conv2d_nchw(2, 48, 56, 48, 3, 1, \"SAME\", add_relu=True, add_bias=True)\n    verify_conv2d_nchw(1, 64, 17, 192, 7, 1, (3, 1), devices=[\"cuda\"])\n    verify_conv2d_nchw(1, 64, 17, 64, 7, 1, (3, 3, 2, 2), devices=[\"cuda\"])\n    verify_conv2d_nchw(1, 160, 17, 160, 7, 1, \"SAME\", devices=[\"cuda\"])\n    verify_conv2d_nchw(1, 48, 35, 48, 5, 1, \"VALID\", devices=[\"cuda\"])\n\n\ndef verify_conv2d_nhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n):\n    # This version is intented to be used by the auto-scheduler,\n    # so we only test the correctness of compute declaration\n    # with the default naive schedule in cpu\n\n    A = te.placeholder((batch, in_size, in_size, in_channel), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    bias = te.placeholder((1, 1, 1, num_filter), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv2d_winograd.verify_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        c_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    target = \"llvm\"\n    dev = tvm.device(target)\n\n    C = topi.nn.conv2d_winograd_nhwc(A, W, stride, padding, dilation, dtype)\n    s = te.create_schedule([C.op])\n\n    a = tvm.nd.array(a_np, device=dev)\n    w = tvm.nd.array(w_np, device=dev)\n    b = tvm.nd.array(b_np, device=dev)\n    c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), device=dev)\n    func = tvm.build(s, [A, W, C], target=target)\n    func(a, w, c)\n\n    rtol = 1e-3\n    tvm.testing.assert_allclose(c.numpy(), c_np, rtol=rtol)\n\n\ndef test_conv2d_nhwc():\n    # This version is intented to be used by the auto-scheduler,\n    # so we only test the correctness of compute declaration\n    # with the default naive schedule in cpu\n\n    # resnet 18 workloads\n    verify_conv2d_nhwc(1, 64, 56, 64, 3, 1, 1)\n    verify_conv2d_nhwc(1, 128, 28, 128, 3, 1, 1)\n    verify_conv2d_nhwc(1, 256, 14, 256, 3, 1, 1)\n    verify_conv2d_nhwc(1, 512, 7, 512, 3, 1, 1)\n\n    # more shapes\n    verify_conv2d_nhwc(2, 64, 56, 64, 3, 1, 1)\n    verify_conv2d_nhwc(1, 1, 1, 1, 3, 1, 1)\n    verify_conv2d_nhwc(3, 3, 3, 3, 3, 1, 1)\n    verify_conv2d_nhwc(2, 13, 71, 59, 3, 1, 1)\n\n    # Asymmetric padding\n    verify_conv2d_nhwc(1, 3, 7, 3, 3, 1, \"SAME\")\n    verify_conv2d_nhwc(1, 48, 35, 48, 3, 1, \"VALID\")\n\n\nif __name__ == \"__main__\":\n    test_conv2d_nchw()\n    test_conv2d_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv3d_ncdhw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple3d\nfrom tvm.topi.utils import get_const_tuple\n\n_conv3d_ncdhw_implement = {\n    \"generic\": (topi.nn.conv3d_ncdhw, topi.generic.schedule_conv3d_ncdhw),\n    \"cpu\": (topi.x86.conv3d_ncdhw, topi.x86.schedule_conv3d_ncdhw),\n    \"gpu\": (topi.cuda.conv3d_ncdhw, topi.cuda.schedule_conv3d_ncdhw),\n}\n\n\ndef verify_conv3d_ncdhw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    groups=1,\n    add_bias=False,\n    add_relu=False,\n):\n    if isinstance(kernel, (tuple, list)):\n        if len(kernel) == 3:\n            kernel_d = kernel[0]\n            kernel_h = kernel[1]\n            kernel_w = kernel[2]\n        else:\n            raise ValueError(\"Size of kernel can only be 3\")\n    elif isinstance(kernel, int):\n        kernel_d = kernel_h = kernel_w = kernel\n    else:\n        raise ValueError(\"Unknown kernel option %s\" % kernel)\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(\n        padding, (kernel_d, kernel_h, kernel_w)\n    )\n    padding_sum = pad_front + pad_back + pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (\n            batch,\n            in_channel,\n            in_size,\n            num_filter,\n            kernel_d,\n            kernel_h,\n            kernel_w,\n            stride,\n            padding_sum,\n            dilation,\n        )\n    )\n\n    in_depth = in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name=\"A\")\n    W = te.placeholder((num_filter, in_channel // groups, kernel_d, kernel_h, kernel_w), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv3d_ncdhw.verify_conv3d_ncdhw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation, dilation))\n        c_np = tvm.topi.testing.conv3d_ncdhw_python(a_np, dw_np, stride, padding, groups)\n        if add_bias:\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv3d_ncdhw_implement)\n        with tvm.target.Target(target):\n            C = fcompute(\n                A,\n                W,\n                (stride, stride, stride),\n                padding,\n                (dilation, dilation, dilation),\n                groups,\n                dtype,\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel_d,\n                    kernel_h,\n                    kernel_w,\n                    stride,\n                    padding_sum,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel_d,\n                    kernel_h,\n                    kernel_w,\n                    stride,\n                    padding_sum,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-4, atol=1e-6)\n\n    for target, dev in tvm.testing.enabled_targets():\n        with autotvm.tophub.context(target):  # load tophub pre-tuned parameters\n            check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_ncdhw():\n    # 3DCNN  workloads\n    verify_conv3d_ncdhw(1, 32, 32, 5, 1, 1, 0)\n    verify_conv3d_ncdhw(1, 32, 32, 1, 1, 1, 0)\n    verify_conv3d_ncdhw(1, 32, 32, 5, 1, 1, 1)\n    verify_conv3d_ncdhw(1, 32, 32, 1, 1, 1, 1)\n\n    # bias, relu\n    verify_conv3d_ncdhw(1, 64, 56, 3, 1, 1, 1, add_relu=True)\n    verify_conv3d_ncdhw(1, 64, 56, 3, 1, 1, 1, add_bias=True)\n    verify_conv3d_ncdhw(1, 64, 56, 3, 1, 1, 1, add_bias=True, add_relu=True)\n\n    # dilation = 2\n    verify_conv3d_ncdhw(1, 64, 56, 3, 3, 1, 1, dilation=2)\n\n    # batch size\n    verify_conv3d_ncdhw(4, 64, 56, 5, 3, 1, 1)\n\n    # weird workloads\n    verify_conv3d_ncdhw(2, 2, 2, 2, 2, 2, 2)\n    verify_conv3d_ncdhw(3, 3, 3, 3, 3, 3, 3)\n\n    # Asymmetric padding\n    verify_conv3d_ncdhw(1, 32, 32, 5, 1, 1, (0, 0, 0, 1, 1, 1))\n    verify_conv3d_ncdhw(1, 32, 32, 1, 1, 1, (2, 1, 2, 1, 2, 1))\n    verify_conv3d_ncdhw(1, 64, 56, 3, 3, 1, (2, 2, 2, 1, 1, 1), dilation=2)\n    verify_conv3d_ncdhw(1, 32, 32, 5, 1, 1, (0, 1, 1))\n    verify_conv3d_ncdhw(1, 32, 32, 1, 1, 1, (2, 1, 0))\n    verify_conv3d_ncdhw(1, 32, 32, 1, 3, 1, \"VALID\")\n    verify_conv3d_ncdhw(1, 32, 32, 5, 1, 1, \"VALID\")\n\n    # DHW kernel layout\n    verify_conv3d_ncdhw(1, 32, 56, 16, (3, 5, 7), 2, (1, 2, 3))\n    verify_conv3d_ncdhw(1, 3, 56, 16, (3, 7, 7), 2, (1, 2, 3, 0, 3, 2))\n    verify_conv3d_ncdhw(1, 3, 56, 16, (3, 3, 7), 2, (1, 2, 3))\n    verify_conv3d_ncdhw(1, 3, 56, 16, (3, 7, 3), 2, (1, 3, 1))\n\n    # grouped workloads\n    verify_conv3d_ncdhw(1, 32, 32, 8, 1, 1, 0, groups=4)\n    verify_conv3d_ncdhw(1, 32, 32, 4, 1, 1, 0, groups=4)\n    verify_conv3d_ncdhw(1, 32, 32, 8, 1, 1, 1, groups=4)\n    verify_conv3d_ncdhw(1, 32, 32, 4, 1, 1, 1, groups=4)\n\n\nif __name__ == \"__main__\":\n    test_conv3d_ncdhw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv3d_ndhwc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do convolution.\"\"\"\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n\n_conv3d_ndhwc_implement = {\n    \"generic\": (topi.nn.conv3d_ndhwc, topi.generic.schedule_conv3d_ndhwc),\n    \"cpu\": (topi.x86.conv3d_ndhwc, topi.x86.schedule_conv3d_ndhwc),\n    \"gpu\": (topi.cuda.conv3d_ndhwc, topi.cuda.schedule_conv3d_ndhwc),\n}\n\n\ndef verify_conv3d_ndhwc(\n    target,\n    dev,\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    groups=1,\n):\n    if isinstance(in_size, tuple):\n        in_depth, in_height, in_width = in_size\n    else:\n        in_depth = in_height = in_width = in_size\n    if isinstance(kernel, tuple):\n        kernel_depth, kernel_height, kernel_width = kernel\n    else:\n        kernel_depth = kernel_height = kernel_width = kernel\n\n    A = te.placeholder((batch, in_depth, in_height, in_width, in_channel), name=\"A\")\n    W = te.placeholder(\n        (kernel_depth, kernel_height, kernel_width, in_channel // groups, num_filter), name=\"W\"\n    )\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv3d_ndhwc.verify_ndhwc.v2\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, dilation, 1, 1))\n        b_np = tvm.topi.testing.conv3d_ndhwc_python(a_np, dw_np, stride, padding, groups)\n        return a_np, w_np, b_np\n\n    a_np, w_np, b_np = get_ref_data()\n\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, _conv3d_ndhwc_implement)\n    with tvm.target.Target(target):\n        B = fcompute(A, W, stride, padding, dilation, groups, dtype)\n        s = fschedule([B])\n    dev = tvm.device(target, 0)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    func = tvm.build(s, [A, W, B], target)\n    print(tvm.lower(s, [A, W, B], target))\n    func(a, w, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\ndef test_conv3d_ndhwc(target, dev):\n    verify_conv3d_ndhwc(target, dev, 1, 16, 32, 16, 3, 1, \"SAME\")\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 32, 5, 2, \"SAME\")\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 64, 5, 2, \"SAME\")\n    verify_conv3d_ndhwc(target, dev, 1, 64, 32, 64, 3, 1, \"VALID\")\n    verify_conv3d_ndhwc(target, dev, 1, 64, 32, 64, 3, 1, \"VALID\")\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 32, 5, 2, \"VALID\")\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 64, 5, 2, \"VALID\")\n    # dilation = 2\n    verify_conv3d_ndhwc(target, dev, 1, 64, 32, 64, 3, 1, \"SAME\", dilation=2)\n\n    verify_conv3d_ndhwc(target, dev, 1, 1, (20, 256, 256), 32, (1, 3, 3), (1, 2, 2), \"SAME\")\n    verify_conv3d_ndhwc(target, dev, 1, 1, (20, 256, 256), 32, (1, 6, 6), (1, 2, 2), (0, 2, 2))\n    verify_conv3d_ndhwc(target, dev, 1, 4, (20, 256, 256), 8, (1, 5, 5), (1, 2, 2), (0, 2, 2))\n\n    verify_conv3d_ndhwc(target, dev, 1, 16, 32, 16, 3, 1, \"SAME\", groups=4)\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 32, 5, 2, \"SAME\", groups=4)\n    verify_conv3d_ndhwc(target, dev, 4, 32, 16, 64, 5, 2, \"SAME\", groups=4)\n\n\nif __name__ == \"__main__\":\n    test_conv3d_ndhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv3d_ndhwc_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Example code to do convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm import te\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.contrib import nvcc\nfrom tvm.topi.nn.utils import get_pad_tuple3d\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\n_conv3d_ndhwc_tensorcore_implement = {\n    \"cuda\": (topi.cuda.conv3d_ndhwc_tensorcore, topi.cuda.schedule_conv3d_ndhwc_tensorcore)\n}\n\n\ndef verify_conv3d_ndhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    devices=\"cuda\",\n):\n    \"\"\"Test the conv3d with tensorcore for ndhwc layout\"\"\"\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(\n        padding, (kernel, kernel, kernel)\n    )\n    padding_sum = pad_front + pad_top + pad_left + pad_back + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation)\n    )\n\n    in_depth = in_height = in_width = in_size\n\n    dtype = \"float16\"\n    A = te.placeholder((batch, in_depth, in_height, in_width, in_channel), dtype, name=\"A\")\n    W = te.placeholder((kernel, kernel, kernel, in_channel, num_filter), dtype, name=\"W\")\n    bias = te.placeholder((1, 1, 1, 1, num_filter), dtype, name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n\n    @memoize(\"topi.tests.test_topi_conv3d_ndhwc.verify_conv3d_ndhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv3d_ndhwc_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            fcompute, fschedule = tvm.topi.testing.dispatch(\n                device, _conv3d_ndhwc_tensorcore_implement\n            )\n            C = fcompute(A, W, stride, padding, dilation, 1, \"float16\")\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (batch, in_channel, in_size, num_filter, kernel, stride, padding_sum, dilation),\n            )\n            func(a, w, c)\n\n        # Tensorcores are very inaccurate, with large shapes, the accumulation\n        # error is high especially away from 1. We disable atol as it is very\n        # large for these numbers that are far away from 1.\n        tvm.testing.assert_allclose(c.numpy(), c_np, atol=1e200, rtol=0.01)\n\n    check_device(devices)\n\n\n@tvm.testing.requires_tensorcore\n@tvm.testing.requires_cuda\ndef test_conv3d_ndhwc_tensorcore():\n    \"\"\"Test the conv3d with tensorcore for ndhwc layout\"\"\"\n    verify_conv3d_ndhwc(16, 16, 14, 16, 3, 1, 1)\n    verify_conv3d_ndhwc(16, 64, 7, 64, 7, 1, 3)\n    verify_conv3d_ndhwc(16, 32, 7, 32, 7, 1, 3)\n\n    verify_conv3d_ndhwc(32, 16, 14, 16, 3, 1, 1, add_bias=True)\n    verify_conv3d_ndhwc(32, 16, 14, 16, 3, 1, 1, add_relu=True)\n    verify_conv3d_ndhwc(32, 16, 14, 16, 3, 1, 1, add_relu=True, add_bias=True)\n\n    verify_conv3d_ndhwc(16, 16, 17, 16, 7, 1, (3, 3, 3, 2, 2, 2))\n    verify_conv3d_ndhwc(16, 16, 17, 16, 7, 1, \"SAME\")\n    verify_conv3d_ndhwc(8, 16, 35, 32, 5, 1, \"VALID\")\n    verify_conv3d_ndhwc(16, 32, 16, 32, 3, 1, (1, 1, 1, 1, 1, 1))\n    verify_conv3d_ndhwc(16, 16, 12, 16, 3, 1, (1, 1, 1, 1, 1, 1))\n\n\nif __name__ == \"__main__\":\n    test_conv3d_ndhwc_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv3d_transpose_ncdhw.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for transposed convolution.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n\n_conv3d_transpose_ncdhw_implement = {\n    \"generic\": (topi.nn.conv3d_transpose_ncdhw, topi.generic.schedule_conv3d_transpose_ncdhw),\n    \"cpu\": (topi.x86.conv3d_transpose_ncdhw, topi.x86.schedule_conv3d_transpose_ncdhw),\n    \"gpu\": (topi.cuda.conv3d_transpose_ncdhw, topi.cuda.schedule_conv3d_transpose_ncdhw),\n}\n\n\ndef verify_conv3d_transpose_ncdhw(\n    batch, in_channel, in_size, num_filter, kernel, stride, padding, output_padding\n):\n    in_depth, in_height, in_width = in_size\n    kernel_depth, kernel_height, kernel_width = kernel\n    stride_depth, stride_height, stride_width = stride\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = padding\n\n    A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name=\"A\")\n    W = te.placeholder(\n        (in_channel, num_filter, kernel_depth, kernel_height, kernel_width), name=\"W\"\n    )\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv3d_transpose.verify_conv3d_transpose_ncdhw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = tvm.topi.testing.conv3d_transpose_ncdhw_python(\n            a_np, w_np, stride, padding, output_padding\n        )\n        c_np = np.maximum(b_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(\n                target, _conv3d_transpose_ncdhw_implement\n            )\n            B = fcompute(\n                A,\n                W,\n                [stride_depth, stride_height, stride_width],\n                [pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right],\n                A.dtype,\n                output_padding,\n            )\n            C = topi.nn.relu(B)\n            s1 = fschedule([B])\n            s2 = fschedule([C])\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n\n        func1 = tvm.build(s1, [A, W, B], target)\n        func2 = tvm.build(s2, [A, W, C], target)\n        func1(a, w, b)\n        func2(a, w, c)\n        tvm.testing.assert_allclose(b.numpy(), b_np, atol=1e-4, rtol=1e-4)\n        tvm.testing.assert_allclose(c.numpy(), c_np, atol=1e-4, rtol=1e-4)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_conv3d_transpose_ncdhw():\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 1, (1, 1, 1), (1, 1, 1), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 2, (3, 3, 3), (1, 1, 1), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (1, 1, 1), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (3, 3, 3), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (3, 3, 3), (0, 0, 0, 0, 0, 0), (2, 2, 2)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (3, 3, 3), (0, 0, 0, 0, 0, 0), (1, 0, 2)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (1, 1, 1), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (3, 3, 3), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 3, (24, 24, 24), 16, (2, 2, 2), (2, 2, 2), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 32, (5, 5, 5), (1, 1, 1), (0, 0, 0, 0, 0, 0), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (5, 5, 5), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (5, 5, 5), (2, 2, 2), (1, 1, 1, 1, 1, 1), (1, 1, 1)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (3, 5, 7), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (3, 5, 5), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (3, 3, 7), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n    verify_conv3d_transpose_ncdhw(\n        1, 8, (32, 32, 32), 64, (3, 5, 3), (2, 2, 2), (1, 1, 1, 1, 1, 1), (0, 0, 0)\n    )\n\n\nif __name__ == \"__main__\":\n    test_conv3d_transpose_ncdhw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_conv3d_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for 3d convolution with winograd.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.utils import get_pad_tuple3d\nfrom tvm.topi.utils import get_const_tuple\n\n\n_conv3d_ncdhw_implement = {\n    \"gpu\": (topi.cuda.conv3d_ncdhw_winograd, topi.cuda.schedule_conv3d_ncdhw_winograd),\n}\n\n\ndef verify_conv3d_ncdhw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    depth_kernel,\n    space_kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n):\n    pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(\n        padding, (depth_kernel, space_kernel, space_kernel)\n    )\n    padding_sum = pad_front + pad_back + pad_top + pad_left + pad_bottom + pad_right\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, space_kernel, stride, padding_sum, dilation)\n    )\n\n    in_depth = in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name=\"A\")\n    W = te.placeholder((num_filter, in_channel, depth_kernel, space_kernel, space_kernel), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_conv3d_ncdhw.verify_conv3d_ncdhw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation, dilation))\n        c_np = tvm.topi.testing.conv3d_ncdhw_python(a_np, dw_np, stride, padding)\n        if add_bias:\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        fcompute, fschedule = tvm.topi.testing.dispatch(device, _conv3d_ncdhw_implement)\n        with tvm.target.Target(device):\n            C = fcompute(\n                A, W, (stride, stride, stride), padding, (dilation, dilation, dilation), 1, dtype\n            )\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    space_kernel,\n                    stride,\n                    padding_sum,\n                    dilation,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                device,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    space_kernel,\n                    stride,\n                    padding_sum,\n                    dilation,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-4, atol=1e-6)\n\n    for device in [\"cuda\"]:\n        with autotvm.tophub.context(device):  # load tophub pre-tuned parameters\n            check_device(device)\n\n\n@tvm.testing.requires_gpu\ndef test_conv3d_ncdhw():\n    # Try without depth transformation\n    # 3DCNN  workloads\n    verify_conv3d_ncdhw(1, 61, 20, 120, 3, 3, 1, 0)\n    verify_conv3d_ncdhw(1, 61, 20, 120, 1, 3, 1, 0)\n    verify_conv3d_ncdhw(1, 61, 20, 120, 5, 3, 1, 0)\n    verify_conv3d_ncdhw(1, 61, 20, 120, 5, 5, 1, 2)\n    verify_conv3d_ncdhw(1, 61, 20, 120, 1, 5, 1, 2)\n    verify_conv3d_ncdhw(1, 61, 20, 120, 7, 7, 1, 3)\n    verify_conv3d_ncdhw(1, 128, 12, 256, 3, 3, 1, 1)\n    verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1)\n\n    # bias, relu\n    verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True)\n    verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True, add_bias=True)\n    verify_conv3d_ncdhw(1, 64, 12, 128, 1, 3, 1, 1, add_relu=True, add_bias=True)\n\n    # dilation = 2\n    verify_conv3d_ncdhw(1, 16, 12, 16, 3, 3, 1, \"VALID\", dilation=2)\n    verify_conv3d_ncdhw(1, 16, 12, 16, 1, 3, 1, \"VALID\", dilation=2)\n\n    # batch size\n    verify_conv3d_ncdhw(4, 32, 12, 64, 3, 3, 1, 1)\n    verify_conv3d_ncdhw(4, 32, 12, 64, 1, 3, 1, 1)\n\n    # weird workloads\n    verify_conv3d_ncdhw(2, 2, 2, 2, 3, 3, 1, 2)\n    verify_conv3d_ncdhw(3, 3, 3, 3, 3, 3, 1, 3)\n\n\nif __name__ == \"__main__\":\n    test_conv3d_ncdhw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_correlation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License\n\"\"\"test of correlation operator in NCHW layout\"\"\"\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import autotvm, te, topi\n\n_correlation_implement = {\n    \"generic\": (topi.nn.correlation_nchw, topi.generic.schedule_correlation_nchw),\n    \"gpu\": (topi.cuda.correlation_nchw, topi.cuda.schedule_correlation_nchw),\n}\n\n(\n    data_shape,\n    kernel_size,\n    max_displacement,\n    stride1,\n    stride2,\n    pad_size,\n    is_multiply,\n) = tvm.testing.parameters(\n    ((1, 3, 10, 10), 1, 4, 1, 1, 4, True),\n    ((1, 3, 10, 10), 1, 5, 1, 1, 5, True),\n    ((5, 1, 4, 4), 3, 1, 2, 1, 2, True),\n    ((5, 1, 6, 4), 3, 1, 2, 2, 2, False),\n    ((5, 1, 11, 11), 5, 1, 1, 1, 2, False),\n)\n\ndtype = tvm.testing.parameter(\"float32\")\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(\n    dtype, data_shape, kernel_size, max_displacement, stride1, stride2, pad_size, is_multiply\n):\n    a_np = np.random.uniform(size=data_shape).astype(dtype)\n    b_np = np.random.uniform(size=data_shape).astype(dtype)\n    c_np = tvm.topi.testing.correlation_nchw_python(\n        a_np, b_np, kernel_size, max_displacement, stride1, stride2, pad_size, is_multiply\n    )\n    return a_np, b_np, c_np\n\n\ndef test_correlation_nchw(\n    target,\n    dev,\n    ref_data,\n    dtype,\n    kernel_size,\n    max_displacement,\n    stride1,\n    stride2,\n    pad_size,\n    is_multiply,\n):\n    a_np, b_np, c_np = ref_data\n\n    A = te.placeholder(a_np.shape, name=\"data1\", dtype=dtype)\n    B = te.placeholder(b_np.shape, name=\"data2\", dtype=dtype)\n\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, _correlation_implement)\n    with tvm.target.Target(target):\n        C = fcompute(A, B, kernel_size, max_displacement, stride1, stride2, pad_size, is_multiply)\n        s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.empty(c_np.shape, dtype=dtype, device=dev)\n\n        func = tvm.build(s, [A, B, C], target)\n        func(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_deformable_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\nimport tvm.testing\n\n\n_deformable_conv2d_nchw_implement = {\n    \"generic\": (topi.nn.deformable_conv2d_nchw, topi.generic.schedule_deformable_conv2d_nchw),\n    \"cuda\": (topi.cuda.deformable_conv2d_nchw, topi.cuda.schedule_deformable_conv2d_nchw),\n}\n\n_deformable_conv2d_nhwc_implement = {\n    \"generic\": (topi.nn.deformable_conv2d_nhwc, topi.generic.schedule_deformable_conv2d_nhwc),\n}\n\n\ndef verify_deformable_conv2d_nchw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    deformable_groups=1,\n    groups=1,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (\n            batch,\n            in_channel,\n            in_size,\n            num_filter,\n            kernel,\n            stride,\n            padding,\n            dilation,\n            deformable_groups,\n            groups,\n        )\n    )\n\n    A = te.placeholder((batch, in_channel, in_size, in_size), name=\"A\")\n    out_size = (in_size - (kernel - 1) * dilation - 1 + 2 * padding) // stride + 1\n    Offset = te.placeholder(\n        (batch, deformable_groups * kernel * kernel * 2, out_size, out_size), name=\"offset\"\n    )\n    W = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    offset_shape = get_const_tuple(Offset.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_deformable_conv2d_nchw.verify_deformable_conv2d_nchw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        offset_np = np.random.randn(*offset_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        c_np = tvm.topi.testing.deformable_conv2d_nchw_python(\n            a_np, offset_np, w_np, stride, padding, dilation, deformable_groups, groups\n        )\n\n        return a_np, offset_np, w_np, c_np\n\n    a_np, offset_np, w_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        fcompute, fschedule = tvm.topi.testing.dispatch(device, _deformable_conv2d_nchw_implement)\n        with tvm.target.Target(device):\n            C = fcompute(A, Offset, W, stride, padding, dilation, deformable_groups, groups, dtype)\n            s = fschedule([C])\n\n            a = tvm.nd.array(a_np, dev)\n            offset = tvm.nd.array(offset_np, dev)\n            w = tvm.nd.array(w_np, dev)\n            c = tvm.nd.empty(c_np.shape, dtype=c_np.dtype, device=dev)\n\n            func = tvm.build(s, [A, Offset, W, C], device)\n            func(a, offset, w, c)\n            tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for device in [\"llvm\", \"cuda\"]:\n        check_device(device)\n\n\ndef verify_deformable_conv2d_nhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    deformable_groups=1,\n    groups=1,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (\n            batch,\n            in_channel,\n            in_size,\n            num_filter,\n            kernel,\n            stride,\n            padding,\n            dilation,\n            deformable_groups,\n            groups,\n        )\n    )\n\n    A = te.placeholder((batch, in_size, in_size, in_channel), name=\"A\")\n    out_size = (in_size - (kernel - 1) * dilation - 1 + 2 * padding) // stride + 1\n    Offset = te.placeholder(\n        (batch, out_size, out_size, deformable_groups * kernel * kernel * 2), name=\"offset\"\n    )\n    W = te.placeholder((kernel, kernel, in_channel, num_filter), name=\"W\")\n    bias = te.placeholder((num_filter,), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    offset_shape = get_const_tuple(Offset.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_deformable_conv2d_nchw.verify_deformable_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        offset_np = np.random.randn(*offset_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        c_np = tvm.topi.testing.deformable_conv2d_nhwc_python(\n            a_np, offset_np, w_np, stride, padding, dilation, deformable_groups, groups\n        )\n\n        return a_np, offset_np, w_np, c_np\n\n    a_np, offset_np, w_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        fcompute, fschedule = tvm.topi.testing.dispatch(device, _deformable_conv2d_nhwc_implement)\n        with tvm.target.Target(device):\n            C = fcompute(A, Offset, W, stride, padding, dilation, deformable_groups, groups, dtype)\n            s = fschedule([C])\n\n            a = tvm.nd.array(a_np, dev)\n            offset = tvm.nd.array(offset_np, dev)\n            w = tvm.nd.array(w_np, dev)\n            c = tvm.nd.empty(c_np.shape, dtype=c_np.dtype, device=dev)\n\n            func = tvm.build(s, [A, Offset, W, C], device)\n            func(a, offset, w, c)\n            tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for device in [\"llvm\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_deformable_conv2d_nchw():\n    verify_deformable_conv2d_nchw(1, 16, 7, 16, 1, 1, 0, deformable_groups=4)\n    verify_deformable_conv2d_nchw(1, 16, 7, 16, 3, 1, 1, dilation=2, deformable_groups=4)\n    verify_deformable_conv2d_nchw(1, 16, 7, 16, 3, 1, 2, dilation=2)\n\n\ndef test_deformable_conv2d_nhwc():\n    verify_deformable_conv2d_nhwc(1, 16, 7, 16, 1, 1, 0, deformable_groups=4)\n    verify_deformable_conv2d_nhwc(1, 16, 7, 16, 3, 1, 1, dilation=2, deformable_groups=4)\n    verify_deformable_conv2d_nhwc(1, 16, 7, 16, 3, 1, 2, dilation=2)\n\n\nif __name__ == \"__main__\":\n    test_deformable_conv2d_nchw()\n    test_deformable_conv2d_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for dense operator\"\"\"\nimport contextlib\nimport numpy as np\nimport pytest\nimport sys\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import te, topi\nfrom tvm.topi.utils import get_const_tuple\n\nfrom common import Int8Fallback\n\nrandom_seed = tvm.testing.parameter(0)\n\nuse_bias = tvm.testing.parameter(True, False)\nbatch_size = tvm.testing.parameter(1, 2, 128)\nin_dim, out_dim = tvm.testing.parameters((1024, 1000))\nin_dtype, out_dtype = tvm.testing.parameters(\n    (\"float32\", \"float32\"),\n    (\"float16\", \"float16\"),\n    (\"int8\", \"int32\"),\n)\n\n\n_dense_implementations = {\n    \"generic\": [(topi.nn.dense, topi.generic.schedule_dense)],\n    \"cpu\": [\n        (topi.x86.dense_nopack, topi.x86.schedule_dense_nopack),\n        (topi.x86.dense_pack, topi.x86.schedule_dense_pack),\n    ],\n    \"gpu\": [\n        (topi.gpu.dense_small_batch, topi.gpu.schedule_dense_small_batch),\n        (topi.gpu.dense_large_batch, topi.gpu.schedule_dense_large_batch),\n    ],\n    \"mali\": [(topi.mali.dense, topi.mali.schedule_dense)],\n    \"bifrost\": [(topi.bifrost.dense, topi.bifrost.schedule_dense)],\n    \"hls\": [(topi.nn.dense, topi.hls.schedule_dense)],\n}\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef dense_ref_data(random_seed, batch_size, in_dim, out_dim, use_bias, in_dtype, out_dtype):\n    np.random.seed(random_seed)\n\n    if \"float\" in in_dtype:\n        a_np = np.random.uniform(size=(batch_size, in_dim)).astype(in_dtype)\n        b_np = np.random.uniform(size=(out_dim, in_dim)).astype(in_dtype)\n        c_np = np.random.uniform(size=(out_dim,)).astype(out_dtype)\n    elif in_dtype == \"int8\":\n        a_np = np.random.randint(low=-128, high=127, size=(batch_size, in_dim)).astype(in_dtype)\n        b_np = np.random.randint(low=-128, high=127, size=(out_dim, in_dim)).astype(in_dtype)\n        c_np = np.random.randint(low=-128, high=127, size=(out_dim,)).astype(out_dtype)\n    else:\n        raise ValueError(\"No method to generate test data for data type '{}'\".format(in_dtype))\n\n    matmul = np.dot(a_np.astype(out_dtype), b_np.T.astype(out_dtype))\n\n    if use_bias:\n        matmul += c_np\n\n    d_np = np.maximum(matmul, 0)\n    return (a_np, b_np, c_np, d_np)\n\n\ndef test_dense(\n    target,\n    dev,\n    batch_size,\n    in_dim,\n    out_dim,\n    use_bias,\n    dense_ref_data,\n    in_dtype,\n    out_dtype,\n    implementations=None,\n):\n    target = tvm.target.Target(target)\n\n    if target.kind.name == \"cuda\":\n        if in_dtype == \"int8\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            pytest.xfail(\"CUDA int8 intrinsics not available\")\n\n        if in_dtype == \"float16\" and not tvm.contrib.nvcc.have_fp16(dev.compute_version):\n            pytest.xfail(\"CUDA float16 intrinsics not available\")\n\n    if target.kind.name == \"vulkan\":\n        if in_dtype == \"int8\" and (\n            not target.attrs.get(\"supports_int8\", False)\n            or not target.attrs.get(\"supports_8bit_buffer\", False)\n        ):\n            pytest.xfail(\"Vulkan int8 driver support not available\")\n        if in_dtype == \"float16\" and (\n            not target.attrs.get(\"supports_float16\", False)\n            or not target.attrs.get(\"supports_16bit_buffer\", False)\n        ):\n            pytest.xfail(\"Vulkan float16 driver support not available\")\n\n    if (\n        target.kind.name not in [\"llvm\", \"c\"]\n        and len(set(target.keys) & set(_dense_implementations)) == 0\n    ):\n        pytest.xfail(\"No implementation for tvm.topi.testing.dispatch to find\")\n\n    if \"int\" in in_dtype:\n        tol = {\"atol\": 0, \"rtol\": 0}\n    elif in_dtype == \"float32\":\n        tol = {\"rtol\": 1e-5, \"atol\": 1e-5}\n    elif in_dtype == \"float16\":\n        tol = {\"rtol\": 5e-2, \"atol\": 1e-5}\n\n    A = te.placeholder((batch_size, in_dim), name=\"A\", dtype=in_dtype)\n    B = te.placeholder((out_dim, in_dim), name=\"B\", dtype=in_dtype)\n    C = te.placeholder((out_dim,), name=\"C\", dtype=out_dtype)\n\n    a_np, b_np, c_np, d_np = dense_ref_data\n\n    if implementations is None:\n        implementations = tvm.topi.testing.dispatch(target, _dense_implementations)\n\n    for fcompute, fschedule in implementations:\n        with tvm.target.Target(target):\n            D = fcompute(A, B, C if use_bias else None, out_dtype)\n            D = topi.nn.relu(D)\n            s = fschedule([D])\n\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(c_np, dev)\n        d = tvm.nd.array(np.zeros(get_const_tuple(D.shape), dtype=out_dtype), dev)\n        f = tvm.build(s, [A, B, C, D], target, name=\"dense\")\n        f(a, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), d_np, **tol)\n\n\n@pytest.mark.parametrize(\"target,in_dtype,out_dtype\", [(\"cuda\", \"int8\", \"int32\")])\ndef test_dense_cuda_int8(\n    target,\n    dev,\n    batch_size,\n    in_dim,\n    out_dim,\n    use_bias,\n    dense_ref_data,\n    in_dtype,\n    out_dtype,\n):\n    implementations = [\n        (topi.cuda.dense_int8, topi.cuda.schedule_dense_int8),\n    ]\n    with Int8Fallback():\n        test_dense(\n            target,\n            dev,\n            batch_size,\n            in_dim,\n            out_dim,\n            use_bias,\n            dense_ref_data,\n            in_dtype,\n            out_dtype,\n            implementations=implementations,\n        )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_dense_tensorcore.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument\n\"\"\"Test code for dense tensorcore operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm import te\nfrom tvm.contrib.pickle_memoize import memoize\nimport tvm.testing\n\n\n_dense_implement = {\"gpu\": [(topi.cuda.dense_tensorcore, topi.cuda.schedule_dense_tensorcore)]}\n\n\ndef convert_int32_into_int4(a_int32):\n    \"\"\"convert int32 values into int4\n    Parameters\n    ----------\n    a_int32 : int\n\n    Return\n    ------\n    a_int4 : int\n    \"\"\"\n    K, L = a_int32.shape\n    assert L % 8 == 0\n    a_int4 = np.zeros(shape=(K, L // 8), dtype=np.int32)\n    for k in range(K):\n        for l in range(L // 8):\n            for m in range(min(8, L - l * 8)):\n                a_int4[k, l] = a_int4[k, l] | ((a_int32[k, l * 8 + m] & 0xF) << ((7 - m) * 4))\n    return a_int4\n\n\ndef convert_int32_into_int4_bias(a_int32):\n    \"\"\"convert int32 values into int4\n    Parameters\n    ----------\n    a_int32 : int\n\n    Return\n    ------\n    a_int4 : int\n    \"\"\"\n    (L,) = a_int32.shape\n    assert L % 8 == 0\n    a_int4 = np.zeros(shape=(L // 8), dtype=np.int32)\n    for l in range(L // 8):\n        for m in range(min(8, L - l * 8)):\n            a_int4[l] = a_int4[l] | ((a_int32[l * 8 + m] & 0xF) << ((7 - m) * 4))\n    return a_int4\n\n\ndef verify_dense(batch, in_dim, out_dim, dtype, use_bias=True):\n    \"\"\"Dense tensorcore verify function\"\"\"\n    A = te.placeholder((batch, in_dim), name=\"A\", dtype=dtype)\n    B = te.placeholder((out_dim, in_dim), name=\"B\", dtype=dtype)\n    C = te.placeholder((out_dim,), name=\"C\", dtype=dtype)\n\n    assert dtype in [\"int4\", \"int8\", \"float16\"]\n\n    out_dtype = \"float32\"\n    if dtype in [\"int8\", \"int4\"]:\n        out_dtype = \"int32\"\n\n    # use memoize to pickle the test data for next time use\n    @memoize(\"topi.tests.test_topi_dense_tensorcore\")\n    def get_ref_data():\n        if dtype == \"int4\":\n            a_np = np.random.randint(low=-8, high=7, size=(batch, in_dim))\n            b_np = np.random.randint(low=-8, high=7, size=(out_dim, in_dim))\n            c_np = np.random.randint(low=-8, high=7, size=(out_dim,))\n        elif dtype == \"int8\":\n            a_np = np.random.randint(low=-128, high=127, size=(batch, in_dim)).astype(dtype)\n            b_np = np.random.randint(low=-128, high=127, size=(out_dim, in_dim)).astype(dtype)\n            c_np = np.random.randint(low=-128, high=127, size=(out_dim,)).astype(dtype)\n        else:\n            a_np = np.random.uniform(size=(batch, in_dim)).astype(dtype)\n            b_np = np.random.uniform(size=(out_dim, in_dim)).astype(dtype)\n            c_np = np.random.uniform(size=(out_dim,)).astype(dtype)\n        d_np = tvm.topi.testing.dense(a_np, b_np, c_np, use_bias, True, out_dtype)\n        return (a_np, b_np, c_np, d_np)\n\n    # get the test data\n    a_np, b_np, c_np, d_np = get_ref_data()\n    if dtype == \"int4\":\n        a_np = convert_int32_into_int4(a_np)\n        b_np = convert_int32_into_int4(b_np)\n        c_np = convert_int32_into_int4_bias(c_np)\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        print(\"Running on target: %s\" % device)\n        for fcompute, fschedule in tvm.topi.testing.dispatch(device, _dense_implement):\n            with tvm.target.Target(device):\n                D = fcompute(A, B, C if use_bias else None, out_dtype)\n                D = topi.nn.relu(D)\n                s = fschedule([D])\n            a = tvm.nd.array(a_np, dev)\n            b = tvm.nd.array(b_np, dev)\n            c = tvm.nd.array(c_np, dev)\n            d = tvm.nd.array(np.zeros(get_const_tuple(D.shape), dtype=out_dtype), dev)\n            f = tvm.build(s, [A, B, C, D], device, name=\"dense\")\n            f(a, b, c, d)\n            tvm.testing.assert_allclose(d.numpy(), d_np, rtol=1e-3)\n\n    check_device(\"cuda\")\n\n\n@tvm.testing.requires_tensorcore\ndef test_dense_tensorcore():\n    \"\"\"Test cases\"\"\"\n    for dtype in [\"float16\", \"int8\"]:\n        verify_dense(8, 16, 32, \"float16\", use_bias=True)\n        verify_dense(16, 32, 16, dtype, use_bias=True)\n        verify_dense(256, 1024, 1024, dtype, use_bias=True)\n        verify_dense(1000, 1024, 1024, dtype, use_bias=False)\n        verify_dense(256, 2048, 1000, dtype, use_bias=False)\n    # TODO: need fix int4 use_bias=True, wyc-ruiker\n    verify_dense(16, 32, 16, \"int4\", use_bias=False)\n    verify_dense(256, 1024, 1024, \"int4\", use_bias=False)\n    verify_dense(1000, 1024, 1024, \"int4\", use_bias=False)\n    verify_dense(256, 2048, 1000, \"int4\", use_bias=False)\n\n\nif __name__ == \"__main__\":\n    test_dense_tensorcore()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_depth_to_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for depth to space\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_depth_to_space(\n    block_size, batch, in_channel, in_height, in_width, layout=\"NCHW\", mode=\"DCR\"\n):\n    out_channel = int(in_channel / (block_size * block_size))\n    out_height = int(in_height * block_size)\n    out_width = int(in_width * block_size)\n\n    if layout == \"NCHW\":\n        in_shape = [batch, in_channel, in_height, in_width]\n        out_shape = [batch, out_channel, out_height, out_width]\n    elif layout == \"NHWC\":\n        in_shape = [batch, in_height, in_width, in_channel]\n        out_shape = [batch, out_height, out_width, out_channel]\n    else:\n        raise NotImplementedError(\"Layout not supported {}\".format(layout))\n\n    A = te.placeholder(in_shape, name=\"A\", dtype=\"float32\")\n    dtype = A.dtype\n    a_np = np.random.uniform(size=in_shape).astype(dtype)\n\n    B = topi.nn.depth_to_space(A, block_size=block_size, layout=layout, mode=mode)\n    if layout == \"NHWC\":\n        a_np = np.transpose(a_np, axes=[0, 3, 1, 2])\n    b_np = tvm.topi.testing.depth_to_space_python(a_np, block_size, mode=mode)\n    if layout == \"NHWC\":\n        a_np = np.transpose(a_np, axes=[0, 2, 3, 1])\n        b_np = np.transpose(b_np, axes=[0, 2, 3, 1])\n\n    def check_device(device, dev):\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s = tvm.topi.testing.get_injective_schedule(device)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], device)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for device, dev in tvm.testing.enabled_targets():\n        check_device(device, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_depth_to_space():\n    for layout in [\"NCHW\", \"NHWC\"]:\n        for mode in [\"DCR\", \"CDR\"]:\n            # Simplest possible case\n            verify_depth_to_space(2, 1, 4, 1, 1, layout=layout, mode=mode)\n            # Average input size\n            verify_depth_to_space(2, 1, 32, 32, 32, layout=layout, mode=mode)\n            # Large block size\n            verify_depth_to_space(8, 1, 256, 32, 32, layout=layout, mode=mode)\n            # Large batch size\n            verify_depth_to_space(4, 8, 32, 32, 32, layout=layout, mode=mode)\n            # Large input size\n            verify_depth_to_space(4, 8, 32, 128, 128, layout=layout, mode=mode)\n\n\nif __name__ == \"__main__\":\n    test_depth_to_space()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_depthwise_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import autotvm, te, topi\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.nn.depthwise_conv2d import _get_workload\nfrom tvm.topi.x86.depthwise_conv2d import _fallback_schedule\nfrom tvm.topi.generic import conv2d as conv2d_generic\n\n\n_depthwise_conv2d_implement = {\n    \"NCHW\": {\n        \"generic\": [(topi.nn.depthwise_conv2d_nchw, topi.generic.schedule_depthwise_conv2d_nchw)],\n        \"arm_cpu\": [\n            (topi.arm_cpu.depthwise_conv2d_nchw, topi.arm_cpu.schedule_depthwise_conv2d_nchw),\n            (\n                topi.arm_cpu.depthwise_conv2d_nchw_spatial_pack,\n                topi.arm_cpu.schedule_depthwise_conv2d_nchw_spatial_pack,\n            ),\n        ],\n        \"gpu\": [(topi.cuda.depthwise_conv2d_nchw, topi.cuda.schedule_depthwise_conv2d_nchw)],\n        \"mali\": [(topi.mali.depthwise_conv2d_nchw, topi.mali.schedule_depthwise_conv2d_nchw)],\n        \"bifrost\": [(topi.nn.depthwise_conv2d_nchw, topi.bifrost.schedule_depthwise_conv2d_nchw)],\n        \"intel_graphics\": [\n            (\n                topi.intel_graphics.depthwise_conv2d_nchw,\n                topi.intel_graphics.schedule_depthwise_conv2d_nchw,\n            )\n        ],\n    },\n    \"NHWC\": {\n        \"generic\": [\n            (topi.nn.depthwise_conv2d_nhwc, topi.generic.schedule_depthwise_conv2d_nhwc),\n            (topi.nn.depthwise_conv2d_nhwc, conv2d_generic.schedule_depthwise_conv2d_nhwc),\n        ],\n        \"arm_cpu\": [\n            (\n                topi.arm_cpu.compute_depthwise_conv2d_nhwc,\n                topi.arm_cpu.schedule_depthwise_conv2d_nhwc,\n            )\n        ],\n        \"gpu\": [(topi.nn.depthwise_conv2d_nhwc, topi.cuda.schedule_depthwise_conv2d_nhwc)],\n        \"mali\": [(topi.mali.depthwise_conv2d_nhwc, topi.mali.schedule_depthwise_conv2d_nhwc)],\n        \"bifrost\": [(topi.mali.depthwise_conv2d_nhwc, topi.mali.schedule_depthwise_conv2d_nhwc)],\n    },\n    \"NCHWc\": {\n        \"generic\": [(topi.x86.depthwise_conv2d_NCHWc, topi.x86.schedule_depthwise_conv2d_NCHWc)],\n    },\n}\n\nrandom_seed = tvm.testing.parameter(0)\n\nin_dtype, out_dtype = tvm.testing.parameters(\n    (\"float32\", \"float32\"),\n    (\"float16\", \"float16\"),\n)\n\n\n@tvm.testing.fixture\ndef input_shape(layout, batch, in_channel, in_size, filter_shape):\n    if layout == \"NCHW\":\n        return (batch, in_channel, in_size, in_size)\n    elif layout == \"NHWC\":\n        return (batch, in_size, in_size, in_channel)\n    elif layout == \"NCHWc\":\n        oc_block = filter_shape[-1]\n        ic_block = next(bn for bn in range(oc_block, 0, -1) if in_channel % bn == 0)\n        return (batch, in_channel // ic_block, in_size, in_size, ic_block)\n\n\n@tvm.testing.fixture\ndef filter_shape(layout, in_channel, channel_multiplier, kernel):\n    filter_channel = in_channel\n    if layout == \"NCHW\":\n        return (filter_channel, channel_multiplier, kernel, kernel)\n    elif layout == \"NHWC\":\n        return (kernel, kernel, filter_channel, channel_multiplier)\n    elif layout == \"NCHWc\":\n        out_channel = in_channel * channel_multiplier\n        # For testing the functionality, we choose an arbitrary block\n        # size that can divide out_channel, regardless of the\n        # performance.\n        oc_block = next(bn for bn in range(16, 0, -1) if out_channel % bn == 0)\n        return (out_channel // oc_block, 1, kernel, kernel, 1, oc_block)\n\n\n@tvm.testing.fixture\ndef scale_shape(layout, in_channel, channel_multiplier, filter_shape):\n    out_channel = in_channel * channel_multiplier\n\n    if layout in (\"NCHW\", \"NHWC\"):\n        return (out_channel,)\n\n    if layout == \"NCHWc\":\n        oc_block = filter_shape[-1]\n        return (out_channel // oc_block, oc_block)\n\n    raise ValueError(\"Unknown layout {}\".format(layout))\n\n\n@tvm.testing.fixture\ndef shift_shape(scale_shape):\n    return scale_shape\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(\n    random_seed,\n    in_dtype,\n    out_dtype,\n    layout,\n    input_shape,\n    filter_shape,\n    dilation,\n    stride,\n    padding,\n    scale_shape,\n    shift_shape,\n    use_scale_shift,\n    apply_relu,\n):\n    np.random.seed(random_seed)\n\n    # scipy.signal.convolve2d does not support float16 data types, and\n    # the python fallback is too slow for general use.  Computing\n    # ref_data in float32 will have fewer rounding errors than the TVM\n    # float16 compute, but those vary based on schedule anyways.\n    conv_dtype = \"float32\" if in_dtype == \"float16\" else in_dtype\n\n    input_np = np.random.uniform(size=input_shape).astype(in_dtype)\n    filter_np = np.random.uniform(size=filter_shape).astype(in_dtype)\n    scale_np = np.random.uniform(size=scale_shape).astype(out_dtype)\n    shift_np = np.random.uniform(size=shift_shape).astype(out_dtype)\n    if layout == \"NCHW\":\n        np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nchw\n        dilation = (1, 1, dilation, dilation)\n        reshape = (1, -1, 1, 1)\n    elif layout == \"NHWC\":\n        np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nhwc\n        dilation = (dilation, dilation, 1, 1)\n        reshape = (1, 1, 1, -1)\n    elif layout == \"NCHWc\":\n        np_depthwise_conv2d = tvm.topi.testing.depthwise_conv2d_python_nchwc\n        dilation = (1, 1, dilation, dilation, 1, 1)\n        reshape = (1, scale_shape[0], 1, 1, scale_shape[1])\n\n    dilated_filter_np = tvm.topi.testing.dilate_python(filter_np, dilation)\n    output_np = np_depthwise_conv2d(\n        input_np.astype(conv_dtype), dilated_filter_np.astype(conv_dtype), stride, padding\n    ).astype(out_dtype)\n\n    if use_scale_shift:\n        output_np = output_np * scale_np.reshape(reshape) + shift_np.reshape(reshape)\n    if apply_relu:\n        output_np = np.maximum(output_np, 0)\n\n    return (\n        input_np,\n        filter_np,\n        scale_np,\n        shift_np,\n        output_np,\n    )\n\n\nclass BaseDepthwiseConv2D:\n    \"\"\"Provides the test_conv2d test function, to be used by other test classes.\n\n    Test parameter sets are split out into different classes for\n    readability (e.g. used for mobilenet), and for restrictions\n    (e.g. implemented only for llvm).\n    \"\"\"\n\n    layout = tvm.testing.parameter(\"NCHW\", \"NHWC\")\n\n    (batch, in_channel, in_size, channel_multiplier, kernel, stride) = tvm.testing.parameters(\n        (1, 728, 32, 1, 3, 1),\n        (4, 256, 64, 2, 5, 2),\n    )\n    padding = tvm.testing.parameter(\"SAME\", \"VALID\")\n    dilation = tvm.testing.parameter(1, 2)\n\n    use_scale_shift = tvm.testing.parameter(True, False, ids=[\"with_scale_shift\", \"no_scale_shift\"])\n    apply_relu = tvm.testing.parameter(True, False, ids=[\"with_relu\", \"no_relu\"])\n\n    run_after_compile = True\n\n    def test_conv2d(\n        self,\n        target,\n        dev,\n        in_dtype,\n        out_dtype,\n        layout,\n        input_shape,\n        filter_shape,\n        scale_shape,\n        shift_shape,\n        use_scale_shift,\n        apply_relu,\n        batch,\n        in_channel,\n        channel_multiplier,\n        kernel,\n        stride,\n        padding,\n        dilation,\n        ref_data,\n    ):\n        target = tvm.target.Target(target)\n        if (\n            target.kind.name == \"cuda\"\n            and in_dtype == \"float16\"\n            and not tvm.contrib.nvcc.have_fp16(dev.compute_version)\n        ):\n            pytest.xfail(\"CUDA float16 intrinsics not available\")\n\n        if (\n            target.kind.name == \"vulkan\"\n            and in_dtype == \"float16\"\n            and (\n                not target.attrs.get(\"supports_float16\", False)\n                or not target.attrs.get(\"supports_16bit_buffer\", False)\n            )\n        ):\n            pytest.xfail(\"Vulkan float16 driver support not available\")\n\n        # Transform the padding argument from 'str' to 'tuple' to\n        # match the \"workload\" tuple in TopHub.  Which padding_args to\n        # use for each layout chosen to reproduce previous behavior.\n        if dilation == 1:\n            padding_args = get_pad_tuple(padding, (kernel, kernel))\n            padding_args_i = [0, 1, 2, 3] if layout == \"NCHW\" else [0, 1]\n            padding_args = [padding_args[i] for i in padding_args_i]\n        else:\n            padding_args = padding\n\n        # placeholder\n        Input = te.placeholder(input_shape, name=\"Input\", dtype=in_dtype)\n        Filter = te.placeholder(filter_shape, name=\"Filter\", dtype=in_dtype)\n        Scale = te.placeholder(scale_shape, name=\"Scale\", dtype=out_dtype)\n        Shift = te.placeholder(shift_shape, name=\"Shift\", dtype=out_dtype)\n\n        if layout == \"NCHW\":\n            topi_scale_shift = topi.nn.scale_shift_nchw\n            fcompute_args = (Input, Filter, stride, padding_args, dilation, out_dtype)\n\n        elif layout == \"NHWC\":\n            topi_scale_shift = topi.nn.scale_shift_nhwc\n            fcompute_args = (Input, Filter, stride, padding_args, dilation, out_dtype)\n\n        elif layout == \"NCHWc\":\n            topi_scale_shift = topi.nn.scale_shift_nchwc\n            in_layout = \"NCHW{}c\".format(input_shape[-1])\n            out_layout = \"NCHW{}c\".format(filter_shape[-1])\n            fcompute_args = (\n                Input,\n                Filter,\n                stride,\n                padding,\n                dilation,\n                in_layout,\n                out_layout,\n                out_dtype,\n            )\n\n        with autotvm.tophub.context(target):  # load tophub pre-tuned parameters\n            impl_list = tvm.topi.testing.dispatch(target, _depthwise_conv2d_implement[layout])[:]\n            if target == \"llvm\" and layout == \"NCHW\" and channel_multiplier == 1 and dilation == 1:\n                impl_list.append(\n                    (topi.x86.depthwise_conv2d_nchw, topi.x86.schedule_depthwise_conv2d_nchw)\n                )\n\n            for fcompute, fschedule in impl_list:\n                with tvm.target.Target(target):\n                    # Declare, build schedule\n                    C = fcompute(*fcompute_args)\n                    if use_scale_shift:\n                        C = topi_scale_shift(C, Scale, Shift)\n                    if apply_relu:\n                        C = topi.nn.relu(C)\n\n                    s = fschedule(C)\n\n                # Build and run\n                f = tvm.build(s, [Input, Filter, Scale, Shift, C], target)\n\n                if self.run_after_compile:\n                    input_np, filter_np, scale_np, shift_np, output_np = ref_data\n                    if \"int\" in out_dtype:\n                        tol = {\"atol\": 0, \"rtol\": 0}\n                    elif out_dtype == \"float32\":\n                        tol = {\"rtol\": 1e-4, \"atol\": 1e-5}\n                    elif out_dtype == \"float16\":\n                        # A summation in float16 with a single accumulator very\n                        # quickly runs into large rounding errors.  At some point,\n                        # this tolerance should be schedule-dependent for to avoid\n                        # false negatives.\n                        num_values_summed = kernel * kernel\n                        gap_size = (\n                            np.nextafter(output_np.max(), np.inf, dtype=output_np.dtype)\n                            - output_np.max()\n                        )\n                        tol = {\"rtol\": 1e-3, \"atol\": num_values_summed * gap_size / 2}\n\n                    input_tvm = tvm.nd.array(input_np, dev)\n                    filter_tvm = tvm.nd.array(filter_np, dev)\n                    scale_tvm = tvm.nd.array(scale_np, dev)\n                    shift_tvm = tvm.nd.array(shift_np, dev)\n                    output_tvm = tvm.nd.array(\n                        np.zeros(shape=get_const_tuple(C.shape), dtype=C.dtype),\n                        dev,\n                    )\n\n                    f(input_tvm, filter_tvm, scale_tvm, shift_tvm, output_tvm)\n                    tvm.testing.assert_allclose(output_np, output_tvm.numpy(), **tol)\n\n\nclass TestDepthwiseConv2D(BaseDepthwiseConv2D):\n    \"\"\"Test variety of parameters, defined in BaseDepthwiseConv2D.  Also\n    has llvm-specific tests for workload padding.\"\"\"\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_workload_padding(\n        self,\n        out_dtype,\n        layout,\n        input_shape,\n        filter_shape,\n        target,\n        ref_data,\n        stride,\n        padding,\n        dilation,\n    ):\n        input_np, filter_np, scale_np, shift_np, output_np = ref_data\n        if layout == \"NCHW\":\n            _, _, out_height, out_width = output_np.shape\n        elif layout == \"NHWC\":\n            _, out_height, out_width, _ = output_np.shape\n        elif layout == \"NCHWc\":\n            _, _, out_height, out_width, _ = output_np.shape\n\n        Input = te.placeholder(input_shape, name=\"Input\")\n        Filter = te.placeholder(filter_shape, name=\"Filter\")\n        wkl = _get_workload(Input, Filter, (stride, stride), padding, dilation, out_dtype, layout)\n\n        # check if tile_ow candidates are the factors of the right output weight.\n        with tvm.target.Target(target):\n            cfg = autotvm.get_config()\n            _fallback_schedule(cfg, wkl)\n            ow_tile = np.prod(cfg[\"tile_ow\"].size)\n\n            tvm.testing.assert_allclose(ow_tile, out_width)\n\n\nclass TestDepthwiseConv2D_MobilenetWorkloads(BaseDepthwiseConv2D):\n    \"\"\"Extra tests to verify functionality for workloads used by mobilenet.\"\"\"\n\n    layout = tvm.testing.parameter(\"NCHW\")\n\n    batch = tvm.testing.parameter(1)\n    channel_multiplier = tvm.testing.parameter(1)\n    kernel = tvm.testing.parameter(3)\n    padding = tvm.testing.parameter(\"SAME\")\n    dilation = tvm.testing.parameter(1)\n\n    in_channel, in_size, stride = tvm.testing.parameters(\n        (32, 112, 1),\n        (64, 112, 2),\n        (128, 56, 1),\n        (128, 56, 2),\n        (256, 28, 1),\n        (256, 28, 2),\n        (512, 14, 1),\n        (512, 14, 2),\n        (1024, 7, 1),\n    )\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\nclass TestDepthwiseConv2D_NCHWc(BaseDepthwiseConv2D):\n    \"\"\"Tests specific to NCHWc layouts.\n\n    Once the implementation supports channel_multiplier>1 and GPU\n    devices, this class can be merged into TestDepthwiseConv2D.\n    \"\"\"\n\n    # depthwise_conv2d_NCHWc currently does not support channel multiplier > 1\n    layout = tvm.testing.parameter(\"NCHWc\")\n    (batch, in_channel, in_size, channel_multiplier, kernel, stride) = tvm.testing.parameters(\n        (1, 728, 32, 1, 3, 1),\n    )\n\n\n@tvm.testing.parametrize_targets(\"llvm -device=arm_cpu -mtriple=aarch64-linux-gnu\")\nclass TestDepthwiseConv2DArmCompile(BaseDepthwiseConv2D):\n    \"\"\"Compile-only tests for cross-compiling to ARM.\"\"\"\n\n    layout = tvm.testing.parameter(\"NHWC\", \"NCHW\")\n    batch = tvm.testing.parameter(1)\n    dilation = tvm.testing.parameter(1)\n    in_dtype, out_dtype = tvm.testing.parameters((\"int16\", \"int32\"))\n    in_channel = tvm.testing.parameter(728)\n    in_size = tvm.testing.parameter(32)\n    kernel = tvm.testing.parameter(1)\n    channel_multiplier = tvm.testing.parameter(1, 3)\n    stride = tvm.testing.parameter(1)\n    padding = tvm.testing.parameter(\"SAME\")\n    use_scale_shift = tvm.testing.parameter(True, False, ids=[\"with_scale_shift\", \"no_scale_shift\"])\n\n    run_after_compile = False\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_depthwise_conv2d_back_input.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport numpy as np\nfrom tvm.contrib.pickle_memoize import memoize\nfrom scipy import signal\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\nimport tvm.topi.testing\nfrom tvm.topi.cuda.depthwise_conv2d import schedule_depthwise_conv2d_backward_input_nhwc\nimport tvm.testing\n\n\ndef verify_depthwise_conv2d_back_input(\n    batch, in_channel, in_h, channel_multiplier, filter_h, stride_h, padding_h\n):\n    in_w = in_h\n    filter_channel = in_channel\n    filter_w = filter_h\n    stride_w = stride_h\n    padding_w = padding_h\n\n    out_h = np.int((in_h + 2 * padding_h - filter_h) / stride_h + 1)\n    out_w = np.int((in_w + 2 * padding_w - filter_w) / stride_w + 1)\n    out_channel = in_channel * channel_multiplier\n\n    ishape = [batch, in_h, in_w, in_channel]\n    oshape = [batch, out_h, out_w, out_channel]\n\n    # placeholder\n    Out_grad = te.placeholder(oshape, name=\"Out_grad\")\n    Filter = te.placeholder((filter_h, filter_w, filter_channel, channel_multiplier))\n    # declare\n    In_grad = topi.nn.depthwise_conv2d_backward_input_nhwc(\n        Filter,\n        Out_grad,\n        oshape,\n        ishape,\n        stride=[stride_h, stride_w],\n        padding=[padding_h, padding_w],\n    )\n    # schedule\n    schedule = schedule_depthwise_conv2d_backward_input_nhwc(In_grad)\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        # build the kernel\n        f = tvm.build(schedule, [Filter, Out_grad, In_grad], device)\n        # prepare pod type for test data closure\n        dtype = Out_grad.dtype\n        out_grad_shape = get_const_tuple(Out_grad.shape)\n        filter_shape = get_const_tuple(Filter.shape)\n\n        # use memoize to pickle the test data for next time use\n        @memoize(\"topi.tests.test_topi_depthwise_conv2d_backward_input.nhwc\")\n        def get_ref_data():\n            out_grad_np = np.random.uniform(size=out_grad_shape).astype(dtype)\n            filter_np = np.random.uniform(size=filter_shape).astype(dtype)\n            dilated_out_grad_np = tvm.topi.testing.dilate_python(\n                out_grad_np, [1, stride_h, stride_w, 1]\n            )\n            # padding params in forward propagation\n            fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(\n                [padding_h, padding_w], (filter_h, filter_w)\n            )\n            # padding params in backward propagation\n            bpad_top = filter_h - 1 - fpad_top\n            bpad_bottom = (filter_h - 1 - fpad_bottom) + (stride_h - 1)\n            bpad_left = filter_w - 1 - fpad_left\n            bpad_right = (filter_w - 1 - fpad_right) + (stride_w - 1)\n\n            padded_out_grad = np.zeros(\n                (\n                    batch,\n                    dilated_out_grad_np.shape[1] + bpad_top + bpad_bottom,\n                    dilated_out_grad_np.shape[2] + bpad_left + bpad_right,\n                    out_channel,\n                )\n            )\n            padded_out_grad[\n                :,\n                bpad_top : dilated_out_grad_np.shape[1] + bpad_top,\n                bpad_left : dilated_out_grad_np.shape[2] + bpad_left,\n                :,\n            ] = dilated_out_grad_np\n\n            in_grad_np = np.zeros((batch, in_h, in_w, in_channel))\n            for b in range(batch):\n                for c in range(in_channel):\n                    for m in range(channel_multiplier):\n                        in_grad_np[b, :, :, c] += signal.convolve2d(\n                            padded_out_grad[b, :, :, c * channel_multiplier + m],\n                            filter_np[:, :, c, m],\n                            mode=\"valid\",\n                        )[0:in_h, 0:in_w]\n            return (out_grad_np, filter_np, in_grad_np)\n\n        (out_grad_np, filter_np, in_grad_np) = get_ref_data()\n\n        out_grad_tvm = tvm.nd.array(out_grad_np, dev)\n        filter_tvm = tvm.nd.array(filter_np, dev)\n        in_grad_tvm = tvm.nd.array(np.zeros(shape=ishape, dtype=dtype), dev)\n        # launch the kernel\n        timer = f.time_evaluator(f.entry_name, dev, number=1)\n        tcost = timer(filter_tvm, out_grad_tvm, in_grad_tvm).mean\n        tvm.testing.assert_allclose(in_grad_np, in_grad_tvm.numpy(), rtol=1e-5)\n\n    check_device(\"opencl\")\n    check_device(\"cuda\")\n    check_device(\"metal\")\n    check_device(\"rocm\")\n    check_device(\"vulkan\")\n    check_device(\"nvptx\")\n\n\n@tvm.testing.requires_gpu\ndef test_topi_depthwise_conv2d_backward_input_nhwc():\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 1, 1)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 1, 1)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 1, 2)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 1, 2)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 2, 1)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 2, 1)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 2, 2)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 2, 2)\n\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 1, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 1, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 1, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 1, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 2, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 2, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 2, 0)\n    verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 2, 0)\n\n\nif __name__ == \"__main__\":\n    test_topi_depthwise_conv2d_backward_input_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_depthwise_conv2d_back_weight.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nimport numpy as np\nfrom tvm.contrib.pickle_memoize import memoize\nfrom scipy import signal\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\nfrom tvm.topi.cuda.depthwise_conv2d import schedule_depthwise_conv2d_backward_weight_nhwc\nimport tvm.testing\n\n\ndef verify_depthwise_conv2d_back_weight(\n    batch, in_channel, in_h, channel_multiplier, filter_h, stride_h, padding_h\n):\n    in_w = in_h\n    filter_channel = in_channel\n    filter_w = filter_h\n    stride_w = stride_h\n    padding_w = padding_h\n\n    out_h = int((in_h + 2 * padding_h - filter_h) / stride_h + 1)\n    out_w = int((in_w + 2 * padding_w - filter_w) / stride_w + 1)\n    out_channel = in_channel * channel_multiplier\n\n    oshape = [batch, out_h, out_w, out_channel]\n    fshape = [filter_h, filter_w, in_channel, channel_multiplier]\n\n    # placeholder\n    Out_grad = te.placeholder(oshape, name=\"Out_grad\")\n    Input = te.placeholder((batch, in_h, in_w, in_channel), name=\"In_grad\")\n    # declare\n    Weight_grad = topi.nn.depthwise_conv2d_backward_weight_nhwc(\n        Input, Out_grad, oshape, fshape, stride=[stride_h, stride_w], padding=[padding_h, padding_w]\n    )\n    # schedule\n    schedule = schedule_depthwise_conv2d_backward_weight_nhwc(Weight_grad)\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        # build the kernel\n        f = tvm.build(schedule, [Input, Out_grad, Weight_grad], device)\n        # prepare pod type for test data closure\n        dtype = Out_grad.dtype\n        out_grad_shape = get_const_tuple(Out_grad.shape)\n        in_shape = get_const_tuple(Input.shape)\n\n        # use memoize to pickle the test data for next time use\n        @memoize(\"topi.tests.test_topi_depthwise_conv2d_backward_weight.nhwc\")\n        def get_ref_data():\n            out_grad_np = np.random.uniform(size=out_grad_shape).astype(dtype)\n            input_np = np.random.uniform(size=in_shape).astype(dtype)\n            dilated_out_grad_np = tvm.topi.testing.dilate_python(\n                out_grad_np, [1, stride_h, stride_w, 1]\n            )\n\n            pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(\n                [padding_h, padding_w], (filter_h, filter_w)\n            )\n            padded_input_np = np.zeros(\n                (batch, in_h + pad_top + pad_bottom, in_w + pad_left + pad_right, in_channel)\n            )\n            padded_input_np[:, pad_top : in_h + pad_top, pad_left : in_w + pad_left, :] = input_np\n\n            weight_grad_np = np.zeros((filter_h, filter_w, in_channel, channel_multiplier))\n            for c in range(in_channel):\n                for m in range(channel_multiplier):\n                    for b in range(batch):\n                        weight_grad_np[:, :, c, m] += signal.convolve2d(\n                            padded_input_np[b, :, :, c],\n                            np.rot90(\n                                dilated_out_grad_np[\n                                    b, :, :, c * channel_multiplier + m % channel_multiplier\n                                ],\n                                2,\n                            ),\n                            mode=\"valid\",\n                        )[0:filter_h, 0:filter_w]\n            return (out_grad_np, input_np, weight_grad_np)\n\n        (out_grad_np, input_np, weight_grad_np) = get_ref_data()\n\n        out_grad_tvm = tvm.nd.array(out_grad_np, dev)\n        input_tvm = tvm.nd.array(input_np, dev)\n        weight_grad_tvm = tvm.nd.array(np.zeros(shape=fshape, dtype=dtype), dev)\n        # launch the kernel\n        timer = f.time_evaluator(f.entry_name, dev, number=1)\n        tcost = timer(input_tvm, out_grad_tvm, weight_grad_tvm).mean\n        tvm.testing.assert_allclose(weight_grad_np, weight_grad_tvm.numpy(), rtol=1e-4)\n\n    check_device(\"opencl\")\n    check_device(\"cuda\")\n    check_device(\"metal\")\n    check_device(\"rocm\")\n    check_device(\"vulkan\")\n    check_device(\"nvptx\")\n\n\n@tvm.testing.requires_gpu\ndef test_topi_depthwise_conv2d_backward_weight_nhwc():\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 3, 1, 1)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 3, 1, 1)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 5, 1, 2)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 5, 1, 2)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 3, 2, 1)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 3, 2, 1)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 5, 2, 2)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 5, 2, 2)\n\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 3, 1, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 3, 1, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 5, 1, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 5, 1, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 3, 2, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 2, 3, 2, 0)\n    verify_depthwise_conv2d_back_weight(16, 256, 56, 1, 5, 2, 0)\n    verify_depthwise_conv2d_back_weight(15, 256, 56, 2, 5, 2, 0)\n\n\nif __name__ == \"__main__\":\n    test_topi_depthwise_conv2d_backward_weight_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_dilate.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nimport numpy as np\n\n\ndef test_dilate():\n    target = \"llvm\"\n    dev = tvm.cpu(0)\n\n    def _test_dilate(input_size, strides, dilation_value=None):\n        Input = te.placeholder((input_size))\n        if dilation_value is None:\n            Output = topi.nn.dilate(Input, strides)\n        else:\n            Output = topi.nn.dilate(Input, strides, dilation_value)\n        schedule = te.create_schedule(Output.op)\n        input_np = np.random.uniform(size=input_size).astype(Input.dtype)\n        if dilation_value is None:\n            output_np = tvm.topi.testing.dilate_python(input_np, strides)\n        else:\n            output_np = tvm.topi.testing.dilate_python(input_np, strides, dilation_value)\n        input_tvm = tvm.nd.array(input_np, device=dev)\n        output_size = topi.utils.get_const_tuple(Output.shape)\n        output_tvm = tvm.nd.array(np.zeros(shape=output_size).astype(Output.dtype), device=dev)\n        f = tvm.build(schedule, [Input, Output], target)\n        f(input_tvm, output_tvm)\n        tvm.testing.assert_allclose(output_tvm.numpy(), output_np, rtol=1e-5)\n\n    _test_dilate((32,), (2,))\n    _test_dilate((32, 32), (2, 2))\n    _test_dilate((1, 3, 32, 32), (1, 1, 1, 1))\n    _test_dilate((1, 3, 32, 32), (2, 2, 2, 2))\n    _test_dilate((1, 32, 32, 3, 3), (1, 1, 1, 1, 1))\n    _test_dilate((1, 32, 32, 3, 3), (2, 2, 2, 2, 2))\n    _test_dilate((1, 32, 32, 32, 3, 3), (1, 1, 1, 2, 2, 2))\n    _test_dilate((1, 32, 32, 32, 3, 3), (2, 2, 2, 1, 1, 1))\n    _test_dilate((1, 32, 32, 32, 3, 3), (2, 2, 2, 1, 1, 1), 1.0)\n\n\nif __name__ == \"__main__\":\n    test_dilate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_einsum.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef with_tvm(lam, *args):\n    \"\"\"Take numpy arrays as args, convert them to TVM tensors and call `lam`.\n    Result of lambda is converted back to numpy array and returned.\n    \"\"\"\n    dev = tvm.cpu(0)\n    pls = []  # placeholders\n    vals_nd = []  # initial values\n    for i, arg in enumerate(args):\n        pls.append(te.placeholder(arg.shape, name=\"pl\" + str(i)))\n        vals_nd.append(tvm.nd.array(arg, dev))\n\n    out = lam(*pls)\n    out_nd = tvm.nd.array(np.zeros(get_const_tuple(out.shape), dtype=out.dtype), dev)\n    s = te.create_schedule([out.op])\n    m = tvm.build(s, pls + [out], \"llvm\")\n    m(*(vals_nd + [out_nd]))\n    return out_nd.numpy()\n\n\ndef verify_einsum(subscripts, shapes):\n    ops = []\n    for shape in shapes:\n        tmp = np.random.uniform(low=-1.0, high=1.0, size=shape).astype(np.float32)\n        ops.append(tmp)\n\n    c1 = np.einsum(subscripts, *ops)\n\n    if len(ops) == 1:\n        c2 = with_tvm(lambda A: topi.einsum(subscripts, A), *ops)\n    elif len(ops) == 2:\n        c2 = with_tvm(lambda A, B: topi.einsum(subscripts, A, B), *ops)\n    elif len(ops) == 3:\n        c2 = with_tvm(lambda A, B, C: topi.einsum(subscripts, A, B, C), *ops)\n\n    tvm.testing.assert_allclose(c1, c2, rtol=1e-5, atol=1e-5)\n\n\n@pytest.mark.parametrize(\n    \"equation,inputs\",\n    [\n        (\"ii\", [(5, 5)]),\n        (\"ii->i\", [(5, 5)]),\n        (\"ij->i\", [(5, 5)]),\n        (\"...j->...\", [(5, 5)]),\n        (\"...j, j\", [(5, 5), (5,)]),\n        (\"..., ...\", [(), (2, 3)]),\n        (\"ijk, jil->kl\", [(3, 4, 5), (4, 3, 2)]),\n        (\"ij, ij -> i\", [(1, 4), (2, 4)]),\n        (\"...ij, ...jk -> ...ik\", [(1, 4), (4, 2)]),\n        (\"...ij, ...ik -> ...jk\", [(1, 1, 1, 4), (1, 1, 1, 3)]),\n        (\"...ik, ...jk, ...hk -> i...jh\", [(3, 4, 4), (1, 5, 3, 8, 4), (2, 5, 3, 6, 4)]),\n        (\"ij,jk->ik\", [(2, 3), (3, 4)]),\n        (\"ij,jk,km->im\", [(2, 3), (3, 4), (4, 5)]),\n    ],\n)\ndef test_einsum(equation, inputs):\n    verify_einsum(equation, inputs)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do group convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm.task.space import FallbackConfigEntity\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\nfrom common import Int8Fallback\nimport tvm.testing\n\n\ndef _transform_data(data, bn):\n    # NCHW -> NCHW[x]c\n    batch_size, channel, height, width = data.shape\n    data = np.reshape(data, (batch_size, channel // bn, bn, height, width))\n    data = np.transpose(data, (0, 1, 3, 4, 2))\n    return data\n\n\ndef _transform_kernel(kernel, ic_bn, oc_bn):\n    # OIHW -> OIHW[x]o[x]i\n    out_channel, in_channel, kh, kw = kernel.shape\n    kernel = np.reshape(kernel, (out_channel // oc_bn, oc_bn, in_channel // ic_bn, ic_bn, kh, kw))\n    kernel = np.transpose(kernel, (0, 2, 4, 5, 1, 3))\n    return kernel\n\n\n_group_conv2d_nchw_implement = {\n    \"generic\": (topi.nn.group_conv2d_nchw, topi.generic.schedule_group_conv2d_nchw),\n    \"gpu\": (topi.cuda.group_conv2d_nchw, topi.cuda.schedule_group_conv2d_nchw),\n}\n\n_group_conv2d_nhwc_implement = {\n    \"generic\": (topi.nn.group_conv2d_nhwc, topi.generic.schedule_group_conv2d_nhwc),\n}\n\n\ndef verify_group_conv2d_nchw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation,\n    groups,\n    add_bias=False,\n    add_relu=False,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation, groups)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    W = te.placeholder((num_filter, in_channel // groups, kernel, kernel), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_group_conv2d.verify_group_conv2d_nchw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding, groups).astype(\n            dtype\n        )\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _group_conv2d_nchw_implement)\n            C = fcompute(A, W, stride, padding, dilation, groups, dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for target in [\"llvm\", \"cuda\"]:\n        check_target(target)\n\n\noc_block_factor = 4\nic_block_factor = 4\n\n\ndef verify_group_conv2d_NCHWc_int8(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation,\n    groups,\n    add_bias=False,\n    add_relu=False,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation, groups)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder(\n        (batch, in_channel // ic_block_factor, in_height, in_width, ic_block_factor),\n        name=\"A\",\n        dtype=\"int8\",\n    )\n    W = te.placeholder(\n        (\n            num_filter // oc_block_factor,\n            (in_channel // groups) // ic_block_factor,\n            kernel,\n            kernel,\n            oc_block_factor,\n            ic_block_factor,\n        ),\n        name=\"W\",\n        dtype=\"int8\",\n    )\n    bias = te.placeholder(\n        (num_filter // oc_block_factor, 1, 1, oc_block_factor), name=\"bias\", dtype=\"int8\"\n    )\n\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_group_conv2d.verify_group_conv2d_NCHWc_int8\")\n    def get_ref_data():\n        a_np = np.random.randint(\n            low=-128, high=127, size=(batch, in_channel, in_height, in_width)\n        ).astype(dtype)\n        w_np = np.random.randint(\n            low=-128, high=128, size=(num_filter, in_channel // groups, kernel, kernel)\n        ).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding, groups).astype(\n            dtype\n        )\n\n        # convert to NCHWc\n        _, _, out_height, out_width = c_np.shape\n        c_np = c_np.reshape(\n            (batch, num_filter // oc_block_factor, oc_block_factor, out_height, out_width)\n        ).transpose(0, 1, 3, 4, 2)\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return (\n            _transform_data(a_np, ic_block_factor),\n            _transform_kernel(w_np, ic_block_factor, oc_block_factor),\n            b_np,\n            c_np,\n        )\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        if target == \"cuda\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            print(\"Skip because int8 intrinsics are not available\")\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            C = topi.cuda.group_conv2d_NCHWc_int8(A, W, stride, padding, dilation, groups, dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = topi.cuda.schedule_group_conv2d_NCHWc_int8([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for target in [\"cuda\"]:\n        check_target(target)\n\n\ndef verify_group_conv2d_nchw_int8(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation,\n    groups,\n    add_bias=False,\n    add_relu=False,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation, groups)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\", dtype=\"int8\")\n    W = te.placeholder((num_filter, in_channel // groups, kernel, kernel), name=\"W\", dtype=\"int8\")\n    bias = te.placeholder(\n        (num_filter // oc_block_factor, 1, 1, oc_block_factor), name=\"bias\", dtype=\"int8\"\n    )\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_group_conv2d.verify_group_conv2d_nchw_int8\")\n    def get_ref_data():\n        a_np = np.random.randint(low=-128, high=127, size=a_shape).astype(dtype)\n        w_np = np.random.randint(low=-128, high=128, size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation))\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, dw_np, stride, padding, groups).astype(\n            dtype\n        )\n\n        # convert to NCHWc\n        _, _, out_height, out_width = c_np.shape\n        c_np = c_np.reshape(\n            (batch, num_filter // oc_block_factor, oc_block_factor, out_height, out_width)\n        ).transpose(0, 1, 3, 4, 2)\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        if target == \"cuda\" and not tvm.contrib.nvcc.have_int8(dev.compute_version):\n            print(\"Skip because int8 intrinsics are not available\")\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            C = topi.cuda.group_conv2d_NCHWc_int8(A, W, stride, padding, dilation, groups, dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = topi.cuda.schedule_group_conv2d_NCHWc_int8([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for target in [\"cuda\"]:\n        check_target(target)\n\n\ndef verify_group_conv2d_nhwc(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation,\n    groups,\n    add_bias=False,\n    add_relu=False,\n):\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation, groups)\n    )\n\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\")\n    W = te.placeholder((kernel, kernel, in_channel // groups, num_filter), name=\"W\")\n    bias = te.placeholder((1, 1, num_filter), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_group_conv2d.verify_group_conv2d_nhwc\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        dw_np = tvm.topi.testing.dilate_python(w_np, (dilation, dilation, 1, 1))\n        c_np = tvm.topi.testing.conv2d_nhwc_python(a_np, dw_np, stride, padding, groups).astype(\n            dtype\n        )\n\n        if add_bias:\n            b_np = np.random.uniform(size=bias_shape).astype(dtype)\n            c_np += b_np\n        if add_relu:\n            c_np = np.maximum(c_np, 0)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _group_conv2d_nhwc_implement)\n            C = fcompute(A, W, stride, padding, dilation, groups, dtype)\n            if add_bias:\n                C = topi.add(C, bias)\n            if add_relu:\n                C = topi.nn.relu(C)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        if add_bias:\n            func = tvm.build(\n                s,\n                [A, W, bias, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, b, c)\n        else:\n            func = tvm.build(\n                s,\n                [A, W, C],\n                target,\n                name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n                % (\n                    batch,\n                    in_channel,\n                    in_size,\n                    num_filter,\n                    kernel,\n                    stride,\n                    padding,\n                    dilation,\n                    groups,\n                ),\n            )\n            func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n    for target in [\"llvm\"]:\n        check_target(target)\n\n\n@tvm.testing.uses_gpu\ndef test_group_conv2d_nchw():\n    # ResNeXt-50 workload\n    verify_group_conv2d_nchw(1, 128, 56, 128, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 256, 56, 256, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 256, 28, 256, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 512, 28, 512, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 512, 14, 512, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 1024, 14, 1024, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nchw(1, 1024, 7, 1024, 3, 1, 1, 1, 32)\n\n    # bias, relu\n    verify_group_conv2d_nchw(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True)\n    verify_group_conv2d_nchw(1, 128, 56, 128, 3, 1, 1, 1, 32, add_bias=True)\n    verify_group_conv2d_nchw(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True, add_bias=True)\n\n    # dilation\n    verify_group_conv2d_nchw(1, 128, 56, 128, 3, 1, 1, 2, 32)\n\n    # batch size\n    verify_group_conv2d_nchw(2, 128, 56, 128, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nchw(9, 128, 56, 128, 3, 1, 1, 1, 32)\n\n\n@tvm.testing.requires_cuda\ndef test_group_conv2d_NCHWc_int8():\n    with Int8Fallback():\n        # ResNeXt-50 workload\n        verify_group_conv2d_NCHWc_int8(1, 128, 56, 128, 3, 1, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 256, 56, 256, 3, 2, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 256, 28, 256, 3, 1, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 512, 28, 512, 3, 2, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 512, 14, 512, 3, 1, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 1024, 14, 1024, 3, 2, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(1, 1024, 7, 1024, 3, 1, 1, 1, 32)\n\n        # bias, relu\n        verify_group_conv2d_NCHWc_int8(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True)\n        verify_group_conv2d_NCHWc_int8(1, 128, 56, 128, 3, 1, 1, 1, 32, add_bias=True)\n        verify_group_conv2d_NCHWc_int8(\n            1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True, add_bias=True\n        )\n        # dilation\n        verify_group_conv2d_NCHWc_int8(1, 128, 56, 128, 3, 1, 1, 2, 32)\n\n        # batch size\n        verify_group_conv2d_NCHWc_int8(2, 128, 56, 128, 3, 1, 1, 1, 32)\n        verify_group_conv2d_NCHWc_int8(9, 128, 56, 128, 3, 1, 1, 1, 32)\n\n\n@tvm.testing.requires_cuda\ndef test_group_conv2d_nchw_int8():\n    with Int8Fallback():\n        # ResNeXt-50 workload\n        verify_group_conv2d_nchw_int8(1, 128, 56, 128, 3, 1, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 256, 56, 256, 3, 2, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 256, 28, 256, 3, 1, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 512, 28, 512, 3, 2, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 512, 14, 512, 3, 1, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 1024, 14, 1024, 3, 2, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(1, 1024, 7, 1024, 3, 1, 1, 1, 32)\n\n        # bias, relu\n        verify_group_conv2d_nchw_int8(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True)\n        verify_group_conv2d_nchw_int8(1, 128, 56, 128, 3, 1, 1, 1, 32, add_bias=True)\n        verify_group_conv2d_nchw_int8(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True, add_bias=True)\n        # dilation\n        verify_group_conv2d_nchw_int8(1, 128, 56, 128, 3, 1, 1, 2, 32)\n\n        # batch size\n        verify_group_conv2d_nchw_int8(2, 128, 56, 128, 3, 1, 1, 1, 32)\n        verify_group_conv2d_nchw_int8(9, 128, 56, 128, 3, 1, 1, 1, 32)\n\n\ndef test_group_conv2d_nhwc():\n    # ResNeXt-50 workload\n    verify_group_conv2d_nhwc(1, 128, 56, 128, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 256, 56, 256, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 256, 28, 256, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 512, 28, 512, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 512, 14, 512, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 1024, 14, 1024, 3, 2, 1, 1, 32)\n    verify_group_conv2d_nhwc(1, 1024, 7, 1024, 3, 1, 1, 1, 32)\n\n    # bias, relu\n    verify_group_conv2d_nhwc(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True)\n    verify_group_conv2d_nhwc(1, 128, 56, 128, 3, 1, 1, 1, 32, add_bias=True)\n    verify_group_conv2d_nhwc(1, 128, 56, 128, 3, 1, 1, 1, 32, add_relu=True, add_bias=True)\n\n    # dilation\n    verify_group_conv2d_nhwc(1, 128, 56, 128, 3, 1, 1, 2, 32)\n\n    # batch size\n    verify_group_conv2d_nhwc(2, 128, 56, 128, 3, 1, 1, 1, 32)\n    verify_group_conv2d_nhwc(9, 128, 56, 128, 3, 1, 1, 1, 32)\n\n\nif __name__ == \"__main__\":\n    test_group_conv2d_nchw()\n    test_group_conv2d_NCHWc_int8()\n    test_group_conv2d_nchw_int8()\n    test_group_conv2d_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_group_conv2d_NCHWc_int8.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test for NCHW[x]c convolution\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\nimport pytest\n\n\ndef _transform_data(data, bn):\n    # NCHW -> NCHW[x]c\n    batch_size, channel, height, width = data.shape\n    data = np.reshape(data, (batch_size, channel // bn, bn, height, width))\n    data = np.transpose(data, (0, 1, 3, 4, 2))\n    return data\n\n\ndef _transform_kernel(kernel, ic_bn, oc_bn):\n    # OIHW -> OIHW[x]i[x]o\n    out_channel, in_channel, kh, kw = kernel.shape\n    kernel = np.reshape(\n        kernel, (out_channel // oc_bn, oc_bn, in_channel // ic_bn, ic_bn // 4, kh, kw, 4)\n    )\n    kernel = np.transpose(kernel, (0, 2, 4, 5, 3, 1, 6))\n    return kernel\n\n\ndef verify_group_conv2d_NCHWc_int8(\n    batch,\n    in_channel,\n    groups,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    dilation=1,\n    add_bias=False,\n    add_relu=False,\n    dtype=\"int32\",\n):\n    assert dilation == 1, \"conv2d_NCHWc does not support dilation for now.\"\n    print(\n        \"Workload: (%d, %d, %d, %d, %d, %d, %d, %d)\"\n        % (batch, in_channel, groups, in_size, num_filter, kernel, stride, padding)\n    )\n\n    in_height = in_width = in_size\n\n    # for testing functionality,\n    # we choose arbitrary block size that can divide the channel,\n    # regardless of the performance.\n    oc_block = 1\n    for bn in range(16, 0, -1):\n        if num_filter % bn == 0:\n            oc_block = bn\n            break\n\n    ic_block = 8\n    autotvm.GLOBAL_SCOPE.silent = True\n    A = te.placeholder(\n        (batch, in_channel // ic_block, in_height, in_width, ic_block), name=\"A\", dtype=\"uint8\"\n    )\n    W = te.placeholder(\n        (\n            num_filter // oc_block,\n            in_channel // ic_block // groups,\n            kernel,\n            kernel,\n            ic_block // 4,\n            oc_block,\n            4,\n        ),\n        name=\"W\",\n        dtype=\"int8\",\n    )\n\n    @memoize(\"topi.tests.test_topi_conv2d_NCHWc_int8.verify_conv2d_NCHWc_int8\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=(batch, in_channel, in_height, in_width)).astype(\"uint8\")\n        w_np = np.random.uniform(size=(num_filter, in_channel // groups, kernel, kernel)).astype(\n            \"int8\"\n        )\n        c_np = tvm.topi.testing.conv2d_nchw_python(a_np, w_np, stride, padding, groups)\n        return (\n            _transform_data(a_np, ic_block),\n            _transform_kernel(w_np, ic_block, oc_block),\n            _transform_data(c_np, oc_block),\n        )\n\n    a_np, w_np, c_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(dev):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            C = topi.x86.conv2d_NCHWc(\n                A,\n                W,\n                (stride, stride),\n                (padding, padding),\n                (dilation, dilation),\n                \"NCHW%dc\" % ic_block,\n                \"NCHW%dc\" % oc_block,\n                dtype,\n            )\n            s = topi.x86.schedule_conv2d_NCHWc([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        func = tvm.build(\n            s,\n            [A, W, C],\n            device,\n            name=\"relu_%d_%d_%d_%d_%d_%d_%d_%d\"\n            % (batch, in_channel, in_size, num_filter, kernel, stride, padding, dilation),\n        )\n        # print(tvm.lower(s, [A, W, C], simple_mode=True))\n        func(a, w, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3)\n\n    # for device in [\"llvm\"]:\n    for device in [\"llvm -mcpu=skylake-avx512\"]:\n        with autotvm.tophub.context(device):  # load tophub pre-tuned parameters\n            check_device(device)\n    autotvm.GLOBAL_SCOPE.silent = False\n\n\n@tvm.testing.uses_gpu\n@pytest.mark.skip\ndef test_conv2d_NCHWc():\n    # ResNet50 workloads\n    verify_group_conv2d_NCHWc_int8(1, 256, 32, 224, 64, 7, 2, 3)\n\n\nif __name__ == \"__main__\":\n    # The test requires Skylake and newer Intel machines to generate the correct\n    # instruction. This test directly calls the topi operator, requiring correct\n    # kernel shape. For older generation of Intel machines, the kernel needs to\n    # be 6D. This test tests 7D kernel, that can only work on Skylake+ machines.\n    # So, disabling the test.\n\n    # test_conv2d_NCHWc()\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_group_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do group transpose convolution.\"\"\"\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import te, topi\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.topi.utils import get_const_tuple\n\n_group_conv2d_nchw_implement = {\n    \"generic\": (\n        topi.nn.group_conv2d_transpose_nchw,\n        topi.generic.schedule_group_conv2d_transpose_nchw,\n    ),\n    \"cuda\": (topi.cuda.conv2d_transpose_nchw, topi.cuda.schedule_conv2d_transpose_nchw),\n}\n\n\ndef verify_group_conv2d_transpose_nchw(\n    batch,\n    in_channel,\n    in_size,\n    num_filter,\n    kernel,\n    stride,\n    padding,\n    output_padding,\n    groups,\n):\n    print(\n        \"Workload: (%d, %d, %s, %d, %s, %s, %s, %s, %d)\"\n        % (batch, in_channel, in_size, num_filter, kernel, stride, padding, output_padding, groups)\n    )\n\n    in_height, in_width = in_size\n    kernel_height, kernel_width = kernel\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    W = te.placeholder((in_channel, num_filter // groups, kernel_height, kernel_width), name=\"W\")\n    bias = te.placeholder((num_filter, 1, 1), name=\"bias\")\n\n    a_shape = get_const_tuple(A.shape)\n    w_shape = get_const_tuple(W.shape)\n    bias_shape = get_const_tuple(bias.shape)\n    dtype = A.dtype\n\n    @memoize(\"topi.tests.test_topi_group_conv2d_transpose.verify_group_conv2d_transpose_nchw\")\n    def get_ref_data():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        w_np = np.random.uniform(size=w_shape).astype(dtype)\n        b_np = np.random.uniform(size=bias_shape).astype(dtype)\n        c_np = tvm.topi.testing.conv2d_transpose_nchw_python(\n            a_np, w_np, stride, padding, output_padding, groups\n        ).astype(dtype)\n\n        return a_np, w_np, b_np, c_np\n\n    a_np, w_np, b_np, c_np = get_ref_data()\n\n    def check_target(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _group_conv2d_nchw_implement)\n            C = fcompute(A, W, stride, padding, dtype, output_padding, groups)\n            s = fschedule([C])\n\n        a = tvm.nd.array(a_np, dev)\n        w = tvm.nd.array(w_np, dev)\n        c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), dev)\n        func = tvm.build(\n            s,\n            [A, W, C],\n            target,\n            name=\"group_conv2d_transpose_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d\"\n            % (\n                batch,\n                in_channel,\n                in_size[0],\n                in_size[1],\n                num_filter,\n                kernel[0],\n                kernel[1],\n                stride[0],\n                stride[1],\n                padding[0],\n                padding[1],\n                padding[2],\n                padding[3],\n                output_padding[0],\n                output_padding[1],\n                groups,\n            ),\n        )\n        func(a, w, c)\n        c = c.numpy()\n        for measurement, reference in zip(c, c_np):\n            tvm.testing.assert_allclose(measurement, reference, rtol=1e-5)\n\n    for target in [\"llvm\", \"cuda\"]:\n        check_target(target)\n\n\n@tvm.testing.uses_gpu\ndef test_group_conv2d_transpose_nchw():\n    verify_group_conv2d_transpose_nchw(1, 4, (32, 32), 4, (5, 5), (1, 1), (0, 0, 0, 0), (0, 0), 2)\n    verify_group_conv2d_transpose_nchw(1, 9, (32, 32), 9, (5, 5), (1, 1), (0, 0, 0, 0), (0, 0), 3)\n    verify_group_conv2d_transpose_nchw(1, 4, (32, 32), 16, (5, 5), (2, 2), (1, 1, 1, 1), (0, 0), 4)\n    verify_group_conv2d_transpose_nchw(\n        1, 32, (8192, 1), 8, (31, 1), (2, 1), (14, 0, 15, 0), (0, 0), 2\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 512, (8, 1), 256, (31, 1), (2, 1), (14, 0, 15, 0), (0, 0), 16\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 512, (8, 1), 256, (31, 1), (2, 1), (14, 0, 15, 0), (1, 0), 16\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 64, (64, 64), 64, (4, 4), (1, 1), (0, 0, 0, 0), (0, 0), 64\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 128, (32, 32), 128, (4, 4), (1, 1), (0, 0, 0, 0), (0, 0), 128\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 256, (16, 16), 256, (4, 4), (1, 1), (0, 0, 0, 0), (0, 0), 256\n    )\n    verify_group_conv2d_transpose_nchw(1, 1, (224, 224), 1, (1, 1), (1, 1), (0, 0, 0, 0), (0, 0), 1)\n    verify_group_conv2d_transpose_nchw(\n        1, 3, (224, 224), 32, (3, 3), (1, 1), (0, 0, 0, 0), (0, 0), 1\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 3, (224, 224), 32, (3, 3), (3, 3), (0, 0, 0, 0), (0, 0), 1\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 3, (224, 224), 32, (3, 3), (1, 1), (0, 0, 0, 0), (0, 0), 1\n    )\n    verify_group_conv2d_transpose_nchw(\n        1, 3, (224, 224), 32, (3, 3), (2, 2), (1, 1, 1, 1), (0, 0), 1\n    )\n    verify_group_conv2d_transpose_nchw(1, 48, (64, 64), 12, (4, 4), (2, 2), (1, 1, 1, 1), (0, 0), 1)\n\n\nif __name__ == \"__main__\":\n    test_group_conv2d_transpose_nchw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_image.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for bilinear scale \"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_resize2d(\n    batch,\n    in_channel,\n    in_height,\n    in_width,\n    out_height,\n    out_width,\n    layout=\"NCHW\",\n    coord_trans=\"align_corners\",\n    method=\"linear\",\n):\n    if layout == \"NCHW\":\n        A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\", dtype=\"float32\")\n        dtype = A.dtype\n        out_shape = (batch, in_channel, out_height, out_width)\n        a_np = np.random.uniform(size=(batch, in_channel, in_height, in_width)).astype(dtype)\n    elif layout == \"NHWC\":\n        A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\", dtype=\"float32\")\n        dtype = A.dtype\n        out_shape = (batch, out_height, out_width, in_channel)\n        a_np = np.random.uniform(size=(batch, in_height, in_width, in_channel)).astype(dtype)\n    else:\n        raise NotImplementedError(\"Layout not supported {} \".format(layout))\n    B = topi.image.resize2d(\n        A,\n        [0.0] * 4,\n        (out_height, out_width),\n        layout=layout,\n        coordinate_transformation_mode=coord_trans,\n        method=method,\n    )\n    scale_h = out_height / in_height\n    scale_w = out_width / in_width\n    b_np = tvm.topi.testing.resize2d_python(a_np, (scale_h, scale_w), layout, method, coord_trans)\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_resize2d():\n    # Scale NCHW\n    verify_resize2d(4, 16, 32, 32, 50, 50, \"NCHW\")\n    # Scale NCHW + Align Corners\n    verify_resize2d(6, 32, 64, 64, 20, 20, \"NCHW\")\n    # Scale NHWC\n    verify_resize2d(4, 16, 32, 32, 50, 50, \"NHWC\")\n    # Scale NHWC + Align Corners\n    verify_resize2d(6, 32, 64, 64, 20, 20, \"NHWC\")\n    for layout in [\"NCHW\", \"NHWC\"]:\n        verify_resize2d(4, 16, 32, 32, 50, 50, layout, \"asymmetric\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 64, 50, layout, \"asymmetric\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 50, 96, layout, \"asymmetric\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 96, 96, layout, \"asymmetric\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 50, 50, layout, \"align_corners\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 50, 50, layout, \"half_pixel\", method=\"nearest_neighbor\")\n        verify_resize2d(4, 16, 32, 32, 50, 50, layout, \"asymmetric\", method=\"linear\")\n        verify_resize2d(4, 16, 32, 32, 50, 50, layout, \"half_pixel\", method=\"linear\")\n\n\ndef verify_resize3d(\n    batch,\n    in_channel,\n    in_depth,\n    in_height,\n    in_width,\n    out_depth,\n    out_height,\n    out_width,\n    layout=\"NCDHW\",\n    coordinate_transformation_mode=\"asymmetric\",\n    method=\"linear\",\n):\n    if layout == \"NCDHW\":\n        A = te.placeholder(\n            (batch, in_channel, in_depth, in_height, in_width), name=\"A\", dtype=\"float32\"\n        )\n        dtype = A.dtype\n        out_shape = (batch, in_channel, out_depth, out_height, out_width)\n        a_np = np.random.uniform(size=(batch, in_channel, in_depth, in_height, in_width)).astype(\n            dtype\n        )\n    elif layout == \"NDHWC\":\n        A = te.placeholder(\n            (batch, in_depth, in_height, in_width, in_channel), name=\"A\", dtype=\"float32\"\n        )\n        dtype = A.dtype\n        out_shape = (batch, out_depth, out_height, out_width, in_channel)\n        a_np = np.random.uniform(size=(batch, in_depth, in_height, in_width, in_channel)).astype(\n            dtype\n        )\n    else:\n        raise NotImplementedError(\"Layout not supported {} \".format(layout))\n\n    B = topi.image.resize3d(\n        A,\n        [0.0] * 6,\n        (out_depth, out_height, out_width),\n        layout=layout,\n        coordinate_transformation_mode=coordinate_transformation_mode,\n        method=method,\n    )\n\n    scale_d = out_depth / in_depth\n    scale_h = out_height / in_height\n    scale_w = out_width / in_width\n    b_np = tvm.topi.testing.resize3d_python(\n        a_np, (scale_d, scale_h, scale_w), layout, method, coordinate_transformation_mode\n    )\n\n    def check_target(target, dev):\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_resize3d():\n    # Trilinear\n    for method in [\"nearest_neighbor\", \"linear\"]:\n        for coord_trans in [\"asymmetric\", \"align_corners\", \"half_pixel\"]:\n            for layout in [\"NCDHW\", \"NDHWC\"]:\n                verify_resize3d(3, 16, 32, 32, 32, 10, 10, 10, layout, coord_trans, method)\n\n\n@tvm.testing.uses_gpu\ndef test_crop_and_resize():\n    def verify_crop_and_resize(\n        image_shape,\n        np_boxes,\n        np_box_indices,\n        np_crop_size,\n        layout=\"NHWC\",\n        method=\"bilinear\",\n        extrapolation_value=0.0,\n    ):\n\n        images = te.placeholder(image_shape, name=\"images\", dtype=\"float32\")\n        np_images = np.random.uniform(size=image_shape).astype(\"float32\")\n        boxes = te.placeholder(np_boxes.shape, name=\"boxes\", dtype=\"float32\")\n        box_ind = te.placeholder(np_box_indices.shape, name=\"box_ind\", dtype=\"int32\")\n\n        batch = len(np_box_indices)\n        target_height, target_width = np_crop_size[0], np_crop_size[1]\n        if layout == \"NHWC\":\n            channel = image_shape[3]\n            out_shape = (batch, target_height, target_width, channel)\n        elif layout == \"NCHW\":\n            channel = image_shape[1]\n            out_shape = (batch, channel, target_height, target_width)\n        else:\n            raise NotImplementedError(\"Layout {} is not supported.\".format(layout))\n\n        out = topi.image.crop_and_resize(\n            images,\n            boxes,\n            box_ind,\n            np_crop_size,\n            layout=layout,\n            method=method,\n            extrapolation_value=extrapolation_value,\n        )\n\n        baseline_np = tvm.topi.testing.crop_and_resize_python(\n            np_images, np_boxes, np_box_indices, np_crop_size, layout, method, extrapolation_value\n        )\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_injective_schedule(target)(out)\n            tvm_images = tvm.nd.array(np_images, dev)\n            tvm_boxes = tvm.nd.array(np_boxes, dev)\n            tvm_indices = tvm.nd.array(np_box_indices, dev)\n            tvm_out = tvm.nd.array(np.zeros(out_shape, dtype=\"float32\"), dev)\n            f = tvm.build(s, [images, boxes, box_ind, out], target, name=\"crop_and_resize\")\n            f(tvm_images, tvm_boxes, tvm_indices, tvm_out)\n\n            tvm.testing.assert_allclose(tvm_out.numpy(), baseline_np, rtol=1e-3, atol=1e-3)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    boxes_1 = np.array([[0.2, 0.3, 0.7, 0.9]], dtype=\"float32\")\n    boxes_2 = np.array([[0.2, 0.3, 0.7, 0.9], [0, 0.1, 0.8, 1]], dtype=\"float32\")\n    indices_1 = np.array([0], dtype=\"int32\")\n    indices_2 = np.array([1, 0], dtype=\"int32\")\n    size_1 = (7, 11)\n    size_2 = (90, 60)\n\n    verify_crop_and_resize((1, 255, 255, 3), boxes_1, indices_1, size_1, layout=\"NHWC\")\n    verify_crop_and_resize(\n        (10, 224, 224, 5), boxes_2, indices_2, size_2, extrapolation_value=0.3, layout=\"NHWC\"\n    )\n    verify_crop_and_resize((1, 100, 100, 3), boxes_1, indices_1, size_1, method=\"nearest_neighbor\")\n    verify_crop_and_resize((1, 3, 224, 224), boxes_1, indices_1, size_1, layout=\"NCHW\")\n\n\n@tvm.testing.uses_gpu\ndef test_affine_grid():\n    def verify_affine_grid(num_batch, target_shape):\n        dtype = \"float32\"\n        data_shape = (num_batch, 2, 3)\n        data = te.placeholder(data_shape, dtype=dtype)\n        out = topi.image.affine_grid(data, target_shape)\n\n        @memoize(\"topi.tests.test_affine_grid.verify_affine_grid\")\n        def get_ref_data():\n            data_np = np.random.uniform(size=data_shape).astype(dtype)\n            out_np = tvm.topi.testing.affine_grid_python(data_np, target_shape)\n            return data_np, out_np\n\n        data_np, out_np = get_ref_data()\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_injective_schedule(target)(out)\n            tvm_data = tvm.nd.array(data_np, dev)\n            tvm_out = tvm.nd.empty(out_np.shape, dtype, dev)\n            f = tvm.build(s, [data, out], target)\n            f(tvm_data, tvm_out)\n\n            tvm.testing.assert_allclose(tvm_out.numpy(), out_np, rtol=1e-5, atol=1e-5)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    verify_affine_grid(1, (16, 32))\n    verify_affine_grid(4, (16, 32))\n\n\n@tvm.testing.uses_gpu\ndef test_grid_sample():\n    def verify_grid_sample(\n        data_shape,\n        grid_shape,\n        method=\"bilinear\",\n        layout=\"NCHW\",\n        padding_mode=\"zeros\",\n        align_corners=True,\n    ):\n        dtype = \"float32\"\n        data = te.placeholder(data_shape, dtype=dtype)\n        grid = te.placeholder(grid_shape, dtype=dtype)\n        out = topi.image.grid_sample(data, grid, method, layout, padding_mode, align_corners)\n\n        @memoize(\"topi.tests.test_grid_sample.verify_grid_sample\")\n        def get_ref_data():\n            data_np = np.random.uniform(size=data_shape).astype(dtype)\n            # allow grid values to be out-of-bound\n            grid_np = np.random.uniform(size=grid_shape, low=-1.5, high=1.5).astype(dtype)\n            out_np = tvm.topi.testing.grid_sample_python(\n                data_np, grid_np, method, layout, padding_mode, align_corners\n            )\n            return data_np, grid_np, out_np\n\n        data_np, grid_np, out_np = get_ref_data()\n\n        def check_target(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_injective_schedule(target)(out)\n            tvm_data = tvm.nd.array(data_np, dev)\n            tvm_grid = tvm.nd.array(grid_np, dev)\n            tvm_out = tvm.nd.empty(out_np.shape, dtype, dev)\n            f = tvm.build(s, [data, grid, out], target)\n            f(tvm_data, tvm_grid, tvm_out)\n\n            tvm.testing.assert_allclose(tvm_out.numpy(), out_np, rtol=1e-5, atol=1e-5)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_target(target, dev)\n\n    methods = [\"nearest\", \"bilinear\", \"bicubic\"]\n    padding_modes = [\"zeros\", \"border\", \"reflection\"]\n    align_corners = [True, False]\n    data_2D_shape = (4, 4, 8, 8)\n    grid_2D_shape = (4, 2, 16, 16)\n    layout_2D = \"NCHW\"\n    # choosing smaller sizes to be testable on weaker GPUs\n    data_3D_shape = (4, 4, 4, 4, 4)\n    grid_3D_shape = (4, 3, 8, 8, 8)\n    layout_3D = \"NCDHW\"\n\n    for _method in methods:\n        for _padding in padding_modes:\n            for _align in align_corners:\n                verify_grid_sample(\n                    data_2D_shape, grid_2D_shape, _method, layout_2D, _padding, _align\n                )\n\n                # 3D \"bicubic\"(tricubic) is not supported in pytorch\n                if _method != \"bicubic\":\n                    verify_grid_sample(\n                        data_3D_shape, grid_3D_shape, _method, layout_3D, _padding, _align\n                    )\n\n\nif __name__ == \"__main__\":\n    test_resize2d()\n    test_resize3d()\n    test_crop_and_resize()\n    test_affine_grid()\n    test_grid_sample()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_layer_norm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for layer_norm.\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.topi.testing\n\nimport tvm.testing\n\n\n_layer_norm_schedule = {\n    \"generic\": topi.generic.schedule_injective,\n}\n\n\n# only test on llvm because schedule is missing\n@tvm.testing.parametrize_targets(\"llvm\")\n@pytest.mark.parametrize(\"shape,axis\", [([4, 16], (1,)), ([4, 16, 16], (1, 2))])\ndef test_layer_norm(target, dev, shape, axis, episilon=1e-5, dtype=\"float32\", rtol=1e-5, atol=1e-5):\n    data = te.placeholder(shape, dtype=dtype, name=\"data\")\n    scale_shape = [shape[dim] for dim in axis]\n    gamma = te.placeholder(scale_shape, dtype=dtype, name=\"gamma\")\n    beta = te.placeholder(scale_shape, dtype=dtype, name=\"beta\")\n    B = topi.nn.layer_norm(data, gamma, beta, axis, episilon)\n\n    data_np = np.random.uniform(size=shape).astype(dtype)\n    gamma_np = np.random.uniform(size=scale_shape).astype(dtype)\n    beta_np = np.random.uniform(size=scale_shape).astype(dtype)\n    b_np = tvm.topi.testing.layer_norm_python(data_np, gamma_np, beta_np, axis, episilon)\n\n    with tvm.target.Target(target):\n        s_func = tvm.topi.testing.dispatch(target, _layer_norm_schedule)\n        s = s_func([B])\n    data_tvm = tvm.nd.array(data_np, dev)\n    gamma_tvm = tvm.nd.array(gamma_np, dev)\n    beta_tvm = tvm.nd.array(beta_np, dev)\n    b_tvm = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n    f = tvm.build(s, [data, gamma, beta, B], target)\n    f(data_tvm, gamma_tvm, beta_tvm, b_tvm)\n    tvm.testing.assert_allclose(b_tvm.asnumpy(), b_np, rtol=rtol, atol=atol)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_loss.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for loss operators.\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\n\nimport tvm.testing\n\n\nprediction_shape, reduction, ignore_index, dtype = tvm.testing.parameters(\n    ((10, 5), \"mean\", -100, \"float32\"),\n    ((10, 5, 2, 2), \"mean\", -100, \"float32\"),\n    ((10, 5), \"sum\", -100, \"float32\"),\n    ((10, 5), \"none\", -100, \"float32\"),\n    ((10, 5), \"mean\", 3, \"float32\"),\n    ((10, 5), \"mean\", -100, \"float64\"),\n)\n\n\ndef test_nll_loss(target, dev, prediction_shape, reduction, ignore_index, dtype):\n    C = prediction_shape[1]\n    target_shape = prediction_shape[:1] + prediction_shape[2:]\n    predictions = te.placeholder(shape=prediction_shape, name=\"predictions\", dtype=dtype)\n    targets = te.placeholder(shape=target_shape, name=\"targets\", dtype=\"int32\")\n    weights = te.placeholder(shape=(C,), name=\"weights\", dtype=dtype)\n    nll_loss_result = topi.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)\n\n    with tvm.target.Target(target):\n        fschedule = tvm.topi.testing.get_reduce_schedule(target)\n        s = fschedule([nll_loss_result])\n    fn = tvm.build(s, [predictions, targets, weights, nll_loss_result], target, name=\"nll_loss\")\n\n    predictions_npy = np.random.uniform(size=prediction_shape).astype(dtype)\n    targets_npy = np.random.randint(0, C, target_shape).astype(\"int32\")\n    weights_npy = np.random.uniform(size=(C,)).astype(dtype)\n    out_npy = tvm.topi.testing.nll_loss(\n        predictions_npy, targets_npy, weights_npy, reduction, ignore_index\n    )\n\n    predictions_nd = tvm.nd.array(predictions_npy, dev)\n    targets_nd = tvm.nd.array(targets_npy, dev)\n    weights_nd = tvm.nd.array(weights_npy, dev)\n    out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(nll_loss_result.dtype), dev)\n    fn(predictions_nd, targets_nd, weights_nd, out_nd)\n    out_topi = out_nd.numpy()\n    tvm.testing.assert_allclose(out_topi, out_npy, rtol=1e-4, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_lrn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for local response normalization\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.topi.testing\nimport tvm.testing\n\n_lrn_schedule = {\n    \"generic\": topi.generic.schedule_lrn,\n    \"gpu\": topi.cuda.schedule_lrn,\n    \"opencl\": topi.cuda.schedule_lrn,\n    \"metal\": topi.cuda.schedule_lrn,\n    \"rocm\": topi.cuda.schedule_lrn,\n    \"vulkan\": topi.cuda.schedule_lrn,\n    \"nvptx\": topi.cuda.schedule_lrn,\n}\n\n\ndef verify_lrn(shape, size, axis, bias, alpha, beta, dtype=\"float32\", rtol=1e-5, atol=1e-5):\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = topi.nn.lrn(A, size, axis, alpha, beta, bias)\n\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    b_np = tvm.topi.testing.lrn_python(a_np, size, axis, bias, alpha, beta)\n\n    def check_device(device):\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s_func = tvm.topi.testing.dispatch(device, _lrn_schedule)\n            s = s_func([B])\n        dev = tvm.device(device, 0)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A, B], device)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=rtol, atol=atol)\n\n    for device in [\"llvm\", \"cuda\", \"opencl\", \"metal\", \"rocm\", \"vulkan\", \"nvptx\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_lrn():\n    verify_lrn((1, 3, 5, 5), 3, 1, 1.0, 1.0, 0.5)\n    verify_lrn((1, 3, 5, 5), 3, 3, 1.0, 1.0, 0.5)\n    verify_lrn((1, 3, 20, 20), 3, 1, 2.0, 1.0, 0.75)\n    verify_lrn((1, 3, 5, 5), 3, 3, 1.0, 1.0, 0.5, dtype=\"float16\", rtol=1e-3, atol=1e-3)\n\n\nif __name__ == \"__main__\":\n    test_lrn()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name\n\"\"\"Test code for LSTM.\"\"\"\nimport numpy as np\nfrom rsa import verify\nimport tvm\nfrom tvm import te, topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_lstm(\n    target,\n    dev,\n    seq_len,\n    batch_size,\n    in_dim,\n    hidden_dim,\n    proj_dim=0,\n    bias=True,\n    zero_init=True,\n    peephole=False,\n    reverse=False,\n    weight_layout=\"IFGO\",\n):\n    out_dim = proj_dim if proj_dim > 0 else hidden_dim\n\n    def rand(*shape):\n        sqrt_k = np.sqrt(1 / hidden_dim)\n        return np.random.uniform(-sqrt_k, sqrt_k, size=shape).astype(\"float32\")\n\n    def get_ref_data():\n        Xs = np.random.normal(size=(seq_len, batch_size, in_dim)).astype(\"float32\")\n        Wi = rand(4 * hidden_dim, in_dim)\n        Wh = rand(4 * hidden_dim, out_dim)\n        Bi = None\n        Bh = None\n        h0 = None\n        c0 = None\n        proj = None\n        p_i = None\n        p_f = None\n        p_o = None\n\n        if bias:\n            Bi = rand(4 * hidden_dim)\n            Bh = rand(4 * hidden_dim)\n\n        if not zero_init:\n            h0 = np.random.normal(size=(batch_size, out_dim)).astype(\"float32\")\n            c0 = np.random.normal(size=(batch_size, hidden_dim)).astype(\"float32\")\n\n        if proj_dim > 0:\n            proj = rand(proj_dim, hidden_dim)\n\n        if peephole:\n            p_i, p_f, p_o = [rand(batch_size, hidden_dim) for _ in range(3)]\n\n        hs, cs = tvm.topi.testing.lstm_python(\n            Xs,\n            Wi,\n            Wh,\n            Bi=Bi,\n            Bh=Bh,\n            h_init=h0,\n            c_init=c0,\n            proj=proj,\n            p_i=p_i,\n            p_f=p_f,\n            p_o=p_o,\n            reverse=reverse,\n            weight_layout=weight_layout,\n        )\n\n        return [Xs, Wi, Wh, Bi, Bh, h0, c0, proj, p_i, p_f, p_o], [hs, cs]\n\n    args_np, (hs_np, cs_np) = get_ref_data()\n\n    args = [te.placeholder(a.shape, \"float32\") if a is not None else a for a in args_np]\n    real_args = [a for a in args if a is not None]\n\n    hs, cs = topi.nn.lstm(*args, reverse=reverse, weight_layout=weight_layout)\n    with tvm.target.Target(target):\n        sch = topi.generic.schedule_lstm([hs, cs])\n    func = tvm.build(sch, real_args + [hs, cs], target=target)\n\n    args_nd = [tvm.nd.array(a, dev) for a in args_np if a is not None]\n    hs_nd = tvm.nd.array(np.zeros((seq_len, batch_size, out_dim), \"float32\"), dev)\n    cs_nd = tvm.nd.array(np.zeros((seq_len, batch_size, hidden_dim), \"float32\"), dev)\n    func(*args_nd, hs_nd, cs_nd)\n\n    tvm.testing.assert_allclose(hs_nd.numpy(), hs_np, rtol=1e-4)\n    tvm.testing.assert_allclose(cs_nd.numpy(), cs_np, rtol=1e-4)\n\n\ndef test_lstm():\n    verify_lstm(\n        \"llvm\",\n        tvm.cpu(0),\n        1,\n        1,\n        1,\n        1,\n        0,\n        True,\n        True,\n        False,\n        False,\n        \"IFGO\",\n    )\n\n    verify_lstm(\n        \"llvm\",\n        tvm.cpu(0),\n        8,\n        4,\n        8,\n        16,\n        0,\n        True,\n        False,\n        False,\n        False,\n        \"IFGO\",\n    )\n\n\ndef test_lstm_proj():\n    verify_lstm(\"llvm\", tvm.cpu(0), 8, 4, 16, 32, 8, True, True, False, False, \"IFGO\")\n\n\ndef test_lstm_peephole():\n    verify_lstm(\"llvm\", tvm.cpu(0), 8, 4, 16, 32, 0, True, True, True, False, \"IFGO\")\n\n\ndef test_lstm_reverse():\n    verify_lstm(\"llvm\", tvm.cpu(0), 8, 4, 16, 32, 0, True, True, False, True, \"IFGO\")\n\n\ndef test_lstm_weight_layout_iofg():\n    # IOFG is used by ONNX, while IFGO is used by PyTorch\n    verify_lstm(\"llvm\", tvm.cpu(0), 8, 4, 16, 32, 0, True, True, False, False, \"IOFG\")\n\n\ndef test_lstm_assorted():\n    verify_lstm(\"llvm\", tvm.cpu(0), 8, 4, 16, 32, 16, True, False, True, True, \"OIGF\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_math.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nimport numpy as np\nimport pytest\nimport scipy\nfrom scipy import special\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\nfrom tvm.topi import utils\n\n\ndef test_util():\n    x = tvm.tir.const(100, \"int32\")\n    assert utils.get_const_int(x) == 100\n    assert utils.get_const_tuple((x, x)) == (100, 100)\n\n\newise_operations = {\n    \"floor\": {\"topi\": topi.floor, \"ref\": np.floor, \"input_range\": (-100, 100)},\n    \"ceil\": {\"topi\": topi.ceil, \"ref\": np.ceil, \"input_range\": (-100, 100)},\n    \"sign\": {\n        \"topi\": topi.sign,\n        \"ref\": np.sign,\n        \"input_range\": (-100, 100),\n        \"skip_name_check\": True,\n    },\n    \"trunc\": {\"topi\": topi.trunc, \"ref\": np.trunc, \"input_range\": (-100, 100)},\n    \"fabs\": {\"topi\": topi.abs, \"ref\": np.fabs, \"input_range\": (-100, 100)},\n    \"round\": {\"topi\": topi.round, \"ref\": np.round, \"input_range\": (-100, 100), \"check_round\": True},\n    \"exp\": {\"topi\": topi.exp, \"ref\": np.exp, \"input_range\": (-1, 1)},\n    \"tanh\": {\n        \"topi\": topi.tanh,\n        \"ref\": np.tanh,\n        \"input_range\": (-10, 10),\n        \"shape\": (128, 128),\n        \"dtype\": [\"float32\", \"float64\"],\n    },\n    \"sigmoid\": {\n        \"topi\": topi.sigmoid,\n        \"ref\": lambda x: 1 / (1 + np.exp(-x)),\n        \"input_range\": (-1, 1),\n    },\n    \"log\": {\"topi\": topi.log, \"ref\": np.log, \"input_range\": (0, 100)},\n    \"sqrt\": {\"topi\": topi.sqrt, \"ref\": np.sqrt, \"input_range\": (0, 100)},\n    \"rsqrt\": {\n        \"topi\": topi.rsqrt,\n        \"ref\": lambda x: np.ones_like(x) / np.sqrt(x),\n        \"input_range\": (0, 100),\n        \"skip_name_check\": True,\n    },\n    \"cos\": {\"topi\": topi.cos, \"ref\": np.cos, \"input_range\": (-2.0 * np.pi, 2.0 * np.pi)},\n    \"tan\": {\n        \"topi\": topi.tan,\n        \"ref\": np.tan,\n        \"input_range\": (-2.0 * np.pi, 2.0 * np.pi),\n        \"dtypes\": [\"float32\", \"float64\"],\n    },\n    \"sin\": {\"topi\": topi.sin, \"ref\": np.sin, \"input_range\": (-2.0 * np.pi, 2.0 * np.pi)},\n    \"erf\": {\"topi\": topi.erf, \"ref\": scipy.special.erf, \"input_range\": (-0.1, 0.1)},\n    \"isnan\": {\n        \"topi\": topi.isnan,\n        \"ref\": np.isnan,\n        \"input_range\": (-1, 1),\n        \"replace_with_nan\": True,\n    },\n    \"isfinite\": {\n        \"topi\": topi.isfinite,\n        \"ref\": np.isfinite,\n        \"input_range\": (0, 1),\n        \"shape\": (8, 8),\n        \"skip_name_check\": True,\n        \"replace_with_nan\": True,\n        \"replace_with_inf\": True,\n        \"dtypes\": [\"float32\", \"float64\", \"int32\", \"int16\"],\n    },\n    \"isinf\": {\n        \"topi\": topi.isinf,\n        \"ref\": np.isinf,\n        \"input_range\": (0, 1),\n        \"shape\": (8, 8),\n        \"skip_name_check\": True,\n        \"replace_with_nan\": True,\n        \"replace_with_inf\": True,\n        \"dtypes\": [\"float32\", \"float64\", \"int32\", \"int16\"],\n    },\n    \"fast_exp\": {\n        \"topi\": topi.fast_exp,\n        \"ref\": np.exp,\n        \"skip_name_check\": True,\n        \"input_range\": (-88, 88),\n        \"step\": 0.01,\n    },\n    \"fast_erf\": {\n        \"topi\": topi.fast_erf,\n        \"ref\": scipy.special.erf,\n        \"skip_name_check\": True,\n        \"input_range\": (-10, 10),\n        \"step\": 0.01,\n        \"dtypes\": [\"float32\", \"float16\"],\n        \"cast_output\": True,\n        \"tolerance\": [1e-5, 1e-1],\n    },\n    \"fast_tanh\": {\n        \"topi\": topi.fast_tanh,\n        \"ref\": np.tanh,\n        \"skip_name_check\": True,\n        \"input_range\": (-10, 10),\n        \"step\": 0.01,\n    },\n}\n\ntopi_name, dtype, tolerance = tvm.testing.parameters(\n    *[\n        (name, dtype, config.get(\"tolerance\", [1e-5] * len(dtype))[i])\n        for name, config in ewise_operations.items()\n        for i, dtype in enumerate(config.get(\"dtypes\", [\"float32\"]))\n    ]\n)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ewise_ref_data(topi_name, dtype):\n    config = ewise_operations[topi_name]\n\n    input_range = config[\"input_range\"]\n    shape = config.get(\"shape\", (20, 3))\n\n    a_np = np.random.uniform(*input_range, size=shape).astype(dtype)\n\n    if dtype.startswith(\"float\"):\n        if config.get(\"replace_with_nan\", False):\n            a_np.ravel()[np.random.choice(a_np.size, int(a_np.size * 0.5), replace=False)] = np.nan\n        if config.get(\"replace_with_inf\", False):\n            a_np.ravel()[\n                np.random.choice(a_np.size, int(a_np.size * 0.5), replace=False)\n            ] = np.infty\n\n    # avoid round check too close to boundary\n    if topi_name == \"round\":\n        a_np += ((np.abs(np.fmod(a_np, 1)) - 0.5) < 1e-6) * 1e-4\n\n    b_np = config[\"ref\"](a_np)\n\n    if config.get(\"cast_output\", False):\n        b_np = b_np.astype(dtype)\n\n    return a_np, b_np\n\n\ndef test_ewise(target, dev, topi_name, dtype, tolerance, ewise_ref_data):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\" and topi_name in [\"tan\", \"erf\", \"isnan\", \"isfinite\", \"isinf\"]:\n        pytest.xfail(f\"Vulkan runtime doesn't support {topi_name} yet\")\n\n    topi_op = ewise_operations[topi_name][\"topi\"]\n    skip_name_check = ewise_operations[topi_name].get(\"skip_name_check\", False)\n\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), dtype=dtype, name=\"A\")\n\n    B = topi_op(A)\n    assert tuple(B.shape) == tuple(A.shape)\n    if not skip_name_check:\n        assert B.op.body[0].op.name == \"tir.\" + topi_name\n\n    a_np, b_np = ewise_ref_data\n\n    with tvm.target.Target(target):\n        s = tvm.topi.testing.get_injective_schedule(target)(B)\n    foo = tvm.build(s, [A, B], target, name=topi_name)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros_like(b_np), dev)\n    foo(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=tolerance, atol=tolerance)\n\n\nfrom_dtype, to_dtype = tvm.testing.parameters(\n    (\"int32\", \"float32\"),\n    (\"int32\", \"float64\"),\n    (\"int32\", \"bool\"),\n    (\"float32\", \"int32\"),\n    (\"float32\", \"float64\"),\n    (\"float32\", \"bool\"),\n    (\"bool\", \"float32\"),\n    (\"bool\", \"int32\"),\n)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef cast_ref_data(from_dtype, to_dtype):\n    shape = (5, 4)\n    input_range = (-100, 100)\n\n    if from_dtype == \"bool\":\n        a_np = np.random.choice([True, False], size=shape)\n    else:\n        a_np = np.random.uniform(*input_range, size=shape).astype(from_dtype)\n\n    if to_dtype == \"bool\":\n        a_np = a_np - a_np[2, 3]\n    b_np = a_np.astype(to_dtype)\n\n    return a_np, b_np\n\n\ndef test_cast(target, dev, cast_ref_data, from_dtype, to_dtype):\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), dtype=from_dtype, name=\"A\")\n    B = topi.cast(A, to_dtype)\n\n    a_np, b_np = cast_ref_data\n\n    with tvm.target.Target(target):\n        s = tvm.topi.testing.get_injective_schedule(target)(B)\n    foo = tvm.build(s, [A, B], target)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.empty(b_np.shape, dtype=to_dtype, device=dev)\n    foo(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_matmul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef with_tvm(lam, *args):\n    \"\"\"Take numpy arrays as args, convert them to TVM tensors and call `lam`.\n    Result of lambda is converted back to numpy array and returned.\n    \"\"\"\n    dev = tvm.cpu(0)\n    pls = []  # placeholders\n    vals_nd = []  # initial values\n    for i, arg in enumerate(args):\n        pls.append(te.placeholder(arg.shape, name=\"pl\" + str(i)))\n        vals_nd.append(tvm.nd.array(arg, dev))\n\n    out = lam(*pls)\n    out_nd = tvm.nd.array(np.zeros(get_const_tuple(out.shape), dtype=out.dtype), dev)\n    s = te.create_schedule([out.op])\n    m = tvm.build(s, pls + [out], \"llvm\")\n    m(*(vals_nd + [out_nd]))\n    return out_nd.numpy()\n\n\ndef verify_nn_matmul(sa, sb, transp_a, transp_b):\n    a = np.random.uniform(low=-1.0, high=1.0, size=sa).astype(np.float32)\n    b = np.random.uniform(low=-1.0, high=1.0, size=sb).astype(np.float32)\n    c1 = np.matmul(np.transpose(a) if transp_a else a, np.transpose(b) if transp_b else b)\n    c2 = with_tvm(\n        lambda A, B: topi.nn.matmul(A, B, transpose_a=transp_a, transpose_b=transp_b),\n        a,\n        b,\n    )\n    tvm.testing.assert_allclose(c1, c2, rtol=1e-5, atol=1e-5)\n\n\ndef test_nn_matmul():\n    verify_nn_matmul((1, 1), (1, 1), False, False)\n    verify_nn_matmul((1, 1), (1, 1), True, True)\n    verify_nn_matmul((2, 2), (2, 2), False, False)\n    verify_nn_matmul((2, 2), (2, 2), True, True)\n    verify_nn_matmul((2, 3), (3, 5), False, False)\n    verify_nn_matmul((5, 3), (3, 2), False, False)\n    verify_nn_matmul((3, 5), (3, 2), True, False)\n    verify_nn_matmul((3, 5), (2, 3), True, True)\n    verify_nn_matmul((3, 5), (3, 2), True, False)\n    verify_nn_matmul((5, 3), (2, 3), False, True)\n\n\ndef verify_matmul(sa, sb, transp_a, transp_b):\n    a = np.random.uniform(low=-1.0, high=1.0, size=sa).astype(np.float32)\n    b = np.random.uniform(low=-1.0, high=1.0, size=sb).astype(np.float32)\n    c1 = np.matmul(np.transpose(a) if transp_a else a, np.transpose(b) if transp_b else b)\n    c2 = with_tvm(lambda A, B: topi.matmul(A, B, transp_a, transp_b), a, b)\n    tvm.testing.assert_allclose(c1, c2, rtol=1e-5, atol=1e-5)\n\n\ndef test_matmul():\n    verify_matmul((1, 1), (1, 1), False, False)\n    verify_matmul((1, 1), (1, 1), True, True)\n    verify_matmul((2, 2), (2, 2), False, False)\n    verify_matmul((2, 2), (2, 2), True, True)\n    verify_matmul((2, 3), (3, 5), False, False)\n    verify_matmul((5, 3), (3, 2), False, False)\n    verify_matmul((3, 5), (3, 2), True, False)\n    verify_matmul((3, 5), (2, 3), True, True)\n\n\ndef verify_tensordot(sa, sb, axes):\n    a = np.random.uniform(low=-1.0, high=1.0, size=sa).astype(np.float32)\n    b = np.random.uniform(low=-1.0, high=1.0, size=sb).astype(np.float32)\n    c1 = np.tensordot(a, b, axes)\n    c2 = with_tvm(lambda A, B: topi.tensordot(A, B, axes), a, b)\n    tvm.testing.assert_allclose(c1, c2, rtol=1e-5, atol=1e-5)\n\n\ndef test_tensordot():\n    verify_tensordot((3), (3), 0)\n    verify_tensordot((2, 3), (3, 5), 1)\n    verify_tensordot((2, 2, 3), (2, 3, 5), 2)\n    verify_tensordot((2, 2, 3, 4), (2, 3, 4, 5), 3)\n    verify_tensordot((3, 2, 2), (2, 3, 5), (1, 0))\n    verify_tensordot((3, 2, 2), (2, 3, 5), ((1, 0), (0, 1)))\n    verify_tensordot((4, 3, 2, 2), (2, 4, 3, 5), ((1, 2, 0), (2, 0, 1)))\n\n\nif __name__ == \"__main__\":\n    test_nn_matmul()\n    test_matmul()\n    test_tensordot()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_pooling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument\n\"\"\"Test code for pooling\"\"\"\nimport math\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import te, topi\nfrom tvm.topi.utils import get_const_tuple\n\n_pool_schedule = {\n    \"generic\": topi.generic.schedule_pool,\n    \"cpu\": topi.x86.schedule_pool,\n    \"gpu\": topi.cuda.schedule_pool,\n    \"hls\": topi.hls.schedule_pool,\n}\n\n_adaptive_pool_schedule = {\n    \"generic\": topi.generic.schedule_adaptive_pool,\n    \"cpu\": topi.x86.schedule_adaptive_pool,\n    \"gpu\": topi.cuda.schedule_adaptive_pool,\n    \"hls\": topi.hls.schedule_adaptive_pool,\n}\n\n_pool_grad_schedule = {\n    \"generic\": topi.generic.schedule_pool_grad,\n    \"gpu\": topi.cuda.schedule_pool_grad,\n}\n\n\ndef verify_pool_grad(\n    n, ic, ih, kh, sh, padding, pool_type, ceil_mode, count_include_pad=True, add_relu=False\n):\n    \"\"\"verify function of pool_grad\"\"\"\n    iw = ih\n    kw = kh\n    sw = sh\n    pt, pl, pb, pr = padding\n    A = te.placeholder((n, ic, ih, iw), name=\"A\")\n    B = topi.nn.pool2d(\n        A,\n        kernel=[kh, kw],\n        stride=[sh, sw],\n        dilation=[1, 1],\n        padding=padding,\n        pool_type=pool_type,\n        ceil_mode=ceil_mode,\n        layout=\"NCHW\",\n        count_include_pad=count_include_pad,\n    )\n    dtype = A.dtype\n\n    bshape = get_const_tuple(B.shape)\n    ashape = get_const_tuple(A.shape)\n    if ceil_mode:\n        assert bshape[2] == int(math.ceil(float(ashape[2] - kh + pt + pb) / sh) + 1)\n        assert bshape[3] == int(math.ceil(float(ashape[3] - kw + pl + pr) / sw) + 1)\n    else:\n        assert bshape[2] == int(math.floor(float(ashape[2] - kh + pt + pb) / sh) + 1)\n        assert bshape[3] == int(math.floor(float(ashape[3] - kw + pl + pr) / sw) + 1)\n    OutGrad = te.placeholder(bshape, name=\"OutGrad\")\n    PoolGrad = topi.nn.pool_grad(\n        OutGrad,\n        A,\n        kernel=[kh, kw],\n        stride=[sh, sw],\n        padding=padding,\n        pool_type=pool_type,\n        ceil_mode=ceil_mode,\n        layout=\"NCHW\",\n        count_include_pad=count_include_pad,\n    )\n    if add_relu:\n        PoolGrad = topi.nn.relu(PoolGrad)\n\n    a_np = np.random.uniform(low=0.001, size=(n, ic, ih, iw)).astype(dtype)\n    out_grad_np = np.random.uniform(low=0.001, size=bshape).astype(dtype)\n    pool_grad_np = tvm.topi.testing.pool_grad_nchw(\n        a_np,\n        out_grad_np,\n        pool_size=(kh, kw),\n        strides=(sh, sw),\n        padding=padding,\n        pool_type=pool_type,\n        ceil_mode=ceil_mode,\n        count_include_pad=count_include_pad,\n    )\n    if add_relu:\n        pool_grad_np = np.maximum(pool_grad_np, 0.0)\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s_func = tvm.topi.testing.dispatch(target, _pool_grad_schedule)\n            s = s_func(PoolGrad)\n\n        a = tvm.nd.array(a_np, dev)\n        out_grad = tvm.nd.array(out_grad_np, dev)\n        pool_grad = tvm.nd.array(np.zeros(get_const_tuple(PoolGrad.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A, OutGrad, PoolGrad], target)\n        f(a, out_grad, pool_grad)\n        tvm.testing.assert_allclose(pool_grad.numpy(), pool_grad_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_pool_grad():\n    \"\"\"test cases of pool_grad\"\"\"\n    verify_pool_grad(1, 256, 32, 3, 2, [1, 1, 1, 1], \"avg\", False, False)\n    verify_pool_grad(1, 256, 32, 2, 2, [0, 0, 0, 0], \"avg\", False, True)\n    verify_pool_grad(1, 256, 31, 3, 3, [1, 2, 1, 2], \"avg\", False, True)\n    verify_pool_grad(1, 256, 32, 2, 2, [1, 2, 1, 2], \"avg\", False, False)\n    verify_pool_grad(1, 256, 31, 4, 4, [2, 2, 2, 2], \"avg\", False, False)\n    verify_pool_grad(1, 256, 31, 4, 4, [0, 0, 0, 0], \"avg\", False, False)\n    verify_pool_grad(1, 256, 32, 2, 2, [0, 0, 0, 0], \"max\", False)\n    verify_pool_grad(1, 256, 31, 3, 3, [2, 1, 2, 1], \"max\", False)\n    verify_pool_grad(1, 256, 31, 3, 3, [2, 1, 2, 1], \"max\", True)\n\n    verify_pool_grad(1, 256, 31, 3, 3, [2, 1, 0, 3], \"avg\", False, True)\n    verify_pool_grad(1, 256, 32, 2, 2, [0, 3, 2, 1], \"avg\", False, False)\n    verify_pool_grad(1, 256, 31, 3, 3, [1, 0, 3, 2], \"max\", False)\n    verify_pool_grad(1, 256, 31, 3, 3, [3, 2, 1, 0], \"max\", True)\n    verify_pool_grad(1, 256, 32, 3, 2, [1, 1, 1, 1], \"max\", False)\n    verify_pool_grad(1, 256, 32, 1, 2, [1, 1, 1, 1], \"avg\", False, False)\n\n    verify_pool_grad(1, 256, 31, 4, 4, [0, 0, 0, 0], \"avg\", False, False, add_relu=True)\n    verify_pool_grad(1, 256, 32, 2, 2, [0, 0, 0, 0], \"max\", False, add_relu=True)\n\n\ndef verify_global_pool(dshape, pool_type, layout=\"NCHW\"):\n    \"\"\"verify function of global_pool\"\"\"\n    assert layout in [\"NCHW\", \"NHWC\"]\n    A = te.placeholder(shape=dshape, name=\"A\")\n    B = topi.nn.global_pool(A, pool_type=pool_type, layout=layout)\n    B = topi.nn.relu(B)\n\n    a_np = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)\n\n    axis = (layout.find(\"H\"), layout.find(\"W\"))\n    if pool_type == \"avg\":\n        b_np = np.mean(a_np, axis=axis, keepdims=True)\n    elif pool_type == \"max\":\n        b_np = np.max(a_np, axis=axis, keepdims=True)\n    b_np = np.maximum(b_np, 0.0)\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s_func = tvm.topi.testing.dispatch(target, _adaptive_pool_schedule)\n            if target == \"cuda\":\n                s = s_func(B, layout)\n            else:\n                s = s_func(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_global_pool():\n    \"\"\"test cases of global_pool\"\"\"\n    verify_global_pool((1, 1024, 7, 7), \"avg\")\n    verify_global_pool((4, 1024, 7, 7), \"avg\")\n    verify_global_pool((1, 1024, 7, 7), \"max\")\n    verify_global_pool((4, 1024, 7, 7), \"max\")\n    verify_global_pool((1, 7, 7, 1024), \"avg\", \"NHWC\")\n    verify_global_pool((4, 7, 7, 1024), \"avg\", \"NHWC\")\n    verify_global_pool((1, 7, 7, 1024), \"max\", \"NHWC\")\n    verify_global_pool((4, 7, 7, 1024), \"max\", \"NHWC\")\n\n\ndef verify_adaptive_pool(dshape, out_size, pool_type, layout=\"NCHW\", dtype=\"float32\"):\n    \"\"\"verify function of adaptive_pool\"\"\"\n    np_data = np.random.uniform(low=0, high=255, size=dshape).astype(dtype)\n    np_out = tvm.topi.testing.adaptive_pool(np_data, out_size, pool_type, layout)\n    oshape = np_out.shape\n\n    data = te.placeholder(dshape, name=\"data\", dtype=dtype)\n    if len(out_size) == 2:\n        out = topi.nn.adaptive_pool(data, out_size, pool_type, layout)\n    else:\n        assert len(out_size) == 3\n        out = topi.nn.adaptive_pool3d(data, out_size, pool_type, layout)\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s_func = tvm.topi.testing.dispatch(target, _adaptive_pool_schedule)\n            if target == \"cuda\":\n                s = s_func(out, layout)\n            else:\n                s = s_func(out)\n        a = tvm.nd.array(np_data, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(oshape), dtype=out.dtype), dev)\n        f = tvm.build(s, [data, out], target)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np_out, rtol=4e-5, atol=1e-6)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_adaptive_pool():\n    \"\"\"test cases of adaptive_pool\"\"\"\n    verify_adaptive_pool((1, 3, 224, 224), (1, 1), \"max\")\n    verify_adaptive_pool((1, 3, 224, 224), (1, 1), \"avg\")\n    verify_adaptive_pool((1, 14, 56, 78), (34, 13), \"max\")\n    verify_adaptive_pool((1, 5, 46, 97), (4, 96), \"avg\")\n    verify_adaptive_pool((1, 224, 224, 3), (1, 1), \"max\", layout=\"NHWC\")\n    verify_adaptive_pool((1, 5, 46, 97), (4, 96), \"avg\", layout=\"NHWC\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (1, 1, 1), \"max\", layout=\"NCDHW\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NCDHW\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (2, 2, 2), \"avg\", layout=\"NCDHW\")\n    verify_adaptive_pool((1, 16, 64, 32, 32), (7, 8, 9), \"avg\", layout=\"NCDHW\")\n    verify_adaptive_pool((1, 16, 64, 32, 32), (8, 16, 16), \"avg\", layout=\"NCDHW\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NDHWC\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (2, 2, 2), \"max\", layout=\"NDHWC\")\n    verify_adaptive_pool((1, 16, 32, 32, 32), (2, 4, 4), \"max\", layout=\"NDHWC\")\n\n\ndef verify_poolnd(\n    n,\n    input_shape,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode,\n    layout,\n    count_include_pad=True,\n):\n    \"\"\"verify function of pool1d\"\"\"\n    A = te.placeholder(input_shape, name=\"A\")\n\n    if n == 1:\n        B = topi.nn.pool1d(\n            A,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    elif n == 2:\n        B = topi.nn.pool2d(\n            A,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    elif n == 3:\n        B = topi.nn.pool3d(\n            A,\n            kernel=kernel,\n            stride=stride,\n            dilation=dilation,\n            padding=padding,\n            pool_type=pool_type,\n            ceil_mode=ceil_mode,\n            layout=layout,\n            count_include_pad=count_include_pad,\n        )\n    else:\n        raise ValueError(f\"PoolND only supports n=1, 2, 3 got n={n}\")\n\n    B = topi.nn.relu(B)\n    dtype = A.dtype\n    output_shape = [int(i) for i in B.shape]\n\n    input_np = np.random.uniform(low=0.001, size=input_shape).astype(dtype)\n\n    padding_before = padding[:n]\n    padding_after = padding[n:]\n    ref_np = tvm.topi.testing.poolnd_python(\n        input_np,\n        kernel,\n        stride,\n        dilation,\n        padding_before,\n        padding_after,\n        pool_type,\n        count_include_pad,\n        ceil_mode,\n        layout=layout,\n    )\n\n    np.testing.assert_equal(tuple(output_shape), tuple(ref_np.shape))\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s_func = tvm.topi.testing.dispatch(target, _pool_schedule)\n            s = s_func(B, layout)\n\n        a = tvm.nd.array(input_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), ref_np, rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\ndef verify_pool3d(\n    input_shape,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode,\n    count_include_pad=True,\n    layout=\"NCDHW\",\n):\n    verify_poolnd(\n        3,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        layout=layout,\n        count_include_pad=count_include_pad,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_pool3d():\n    \"\"\"test cases of pool3d\"\"\"\n    verify_pool3d(\n        [1, 16, 32, 32, 32], [2, 2, 2], [2, 2, 2], [1, 1, 1], [0, 0, 0, 0, 0, 0], \"avg\", False, True\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [1, 1, 2, 2, 2, 1], \"avg\", False, True\n    )\n    verify_pool3d(\n        [1, 16, 32, 32, 32],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [1, 1, 2, 2, 2, 1],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31],\n        [4, 4, 4],\n        [4, 4, 4],\n        [1, 1, 1],\n        [3, 3, 3, 3, 3, 3],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31],\n        [4, 4, 4],\n        [4, 4, 4],\n        [1, 1, 1],\n        [0, 0, 0, 0, 0, 0],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 32, 32, 32], [2, 2, 2], [2, 2, 2], [1, 1, 1], [0, 0, 0, 0, 0, 0], \"max\", False\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [2, 2, 1, 1, 1, 2], \"max\", False\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [2, 2, 1, 1, 1, 2], \"max\", True\n    )\n\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [2, 1, 0, 5, 4, 3], \"avg\", False, True\n    )\n    verify_pool3d(\n        [1, 16, 32, 32, 32],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [0, 5, 4, 3, 2, 1],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [1, 0, 5, 4, 3, 2], \"max\", False\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [1, 1, 1], [3, 2, 1, 0, 5, 4], \"max\", True\n    )\n\n    # Test non-1 dilation\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [3, 3, 3], [2, 1, 0, 5, 4, 3], \"avg\", False, True\n    )\n    verify_pool3d(\n        [1, 16, 32, 32, 32],\n        [2, 2, 2],\n        [2, 2, 2],\n        [2, 2, 2],\n        [0, 5, 4, 3, 2, 1],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [2, 1, 3], [1, 0, 5, 4, 3, 2], \"max\", False\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [2, 2, 3], [3, 2, 1, 0, 5, 4], \"max\", True\n    )\n    # Test channel last layouts\n    verify_pool3d(\n        [1, 32, 32, 32, 16],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [0, 0, 0, 0, 0, 0],\n        \"avg\",\n        False,\n        True,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [1, 1, 2, 2, 2, 1],\n        \"avg\",\n        False,\n        True,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 32, 32, 32, 16],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [1, 1, 2, 2, 2, 1],\n        \"avg\",\n        False,\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [4, 4, 4],\n        [4, 4, 4],\n        [1, 1, 1],\n        [3, 3, 3, 3, 3, 3],\n        \"avg\",\n        False,\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [4, 4, 4],\n        [4, 4, 4],\n        [1, 1, 1],\n        [0, 0, 0, 0, 0, 0],\n        \"avg\",\n        False,\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 32, 32, 32, 16],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [0, 0, 0, 0, 0, 0],\n        \"max\",\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [2, 2, 1, 1, 1, 2],\n        \"max\",\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [2, 2, 1, 1, 1, 2],\n        \"max\",\n        True,\n        layout=\"NDHWC\",\n    )\n\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [2, 1, 0, 5, 4, 3],\n        \"avg\",\n        False,\n        True,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 32, 32, 32, 16],\n        [2, 2, 2],\n        [2, 2, 2],\n        [1, 1, 1],\n        [0, 5, 4, 3, 2, 1],\n        \"avg\",\n        False,\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [1, 0, 5, 4, 3, 2],\n        \"max\",\n        False,\n        layout=\"NDHWC\",\n    )\n    verify_pool3d(\n        [1, 31, 31, 31, 16],\n        [3, 3, 3],\n        [3, 3, 3],\n        [1, 1, 1],\n        [3, 2, 1, 0, 5, 4],\n        \"max\",\n        True,\n        layout=\"NDHWC\",\n    )\n\n    # Test non-1 dilation\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [3, 3, 3], [2, 1, 0, 5, 4, 3], \"avg\", False, True\n    )\n    verify_pool3d(\n        [1, 16, 32, 32, 32],\n        [2, 2, 2],\n        [2, 2, 2],\n        [2, 2, 2],\n        [0, 5, 4, 3, 2, 1],\n        \"avg\",\n        False,\n        False,\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [2, 1, 3], [1, 0, 5, 4, 3, 2], \"max\", False\n    )\n    verify_pool3d(\n        [1, 16, 31, 31, 31], [3, 3, 3], [3, 3, 3], [2, 2, 3], [3, 2, 1, 0, 5, 4], \"max\", True\n    )\n\n\ndef verify_pool2d(\n    input_shape,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode,\n    count_include_pad=True,\n    layout=\"NCHW\",\n):\n    verify_poolnd(\n        2,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        layout=layout,\n        count_include_pad=count_include_pad,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_pool2d():\n    \"\"\"test cases of pool\"\"\"\n    verify_pool2d([1, 16, 32, 32], [2, 2], [2, 2], [1, 1], [0, 0, 0, 0], \"avg\", False, True)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [1, 2, 1, 2], \"avg\", False, True)\n    verify_pool2d([1, 16, 32, 32], [2, 2], [2, 2], [1, 1], [1, 2, 1, 2], \"avg\", False, False)\n    verify_pool2d([1, 16, 31, 31], [4, 4], [4, 4], [1, 1], [3, 3, 3, 3], \"avg\", False, False)\n    verify_pool2d([1, 16, 31, 31], [4, 4], [4, 4], [1, 1], [0, 0, 0, 0], \"avg\", False, False)\n    verify_pool2d([1, 16, 32, 32], [2, 3], [2, 2], [1, 1], [0, 0, 0, 0], \"max\", False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", True)\n\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [2, 1, 0, 3], \"avg\", False, True)\n    verify_pool2d([1, 16, 32, 32], [2, 3], [2, 2], [1, 1], [0, 3, 2, 1], \"avg\", False, False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [1, 0, 3, 2], \"max\", False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [1, 1], [3, 2, 1, 0], \"max\", True)\n\n    # Test non-1 dilations\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [2, 1], [2, 1, 0, 3], \"avg\", False, True)\n    verify_pool2d([1, 16, 32, 32], [2, 3], [2, 2], [2, 3], [0, 3, 2, 1], \"avg\", False, False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [3, 3], [1, 0, 3, 2], \"max\", False)\n    verify_pool2d([1, 16, 31, 31], [3, 3], [3, 3], [2, 2], [3, 2, 1, 0], \"max\", True)\n    # Test channel last\n    verify_pool2d(\n        [1, 32, 32, 16], [2, 2], [2, 2], [1, 1], [0, 0, 0, 0], \"avg\", False, True, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [1, 2, 1, 2], \"avg\", False, True, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 32, 32, 16], [2, 2], [2, 2], [1, 1], [1, 2, 1, 2], \"avg\", False, False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [4, 4], [4, 4], [1, 1], [3, 3, 3, 3], \"avg\", False, False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [4, 4], [4, 4], [1, 1], [0, 0, 0, 0], \"avg\", False, False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 32, 32, 16], [2, 3], [2, 2], [1, 1], [0, 0, 0, 0], \"max\", False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", False, layout=\"NHWC\"\n    )\n    verify_pool2d([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 2, 1], \"max\", True, layout=\"NHWC\")\n\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [2, 1, 0, 3], \"avg\", False, True, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 32, 32, 16], [2, 3], [2, 2], [1, 1], [0, 3, 2, 1], \"avg\", False, False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [1, 0, 3, 2], \"max\", False, layout=\"NHWC\"\n    )\n    verify_pool2d([1, 31, 31, 16], [3, 3], [3, 3], [1, 1], [3, 2, 1, 0], \"max\", True, layout=\"NHWC\")\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [2, 1], [2, 1, 0, 3], \"avg\", False, True, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 32, 32, 16], [2, 3], [2, 2], [2, 3], [0, 3, 2, 1], \"avg\", False, False, layout=\"NHWC\"\n    )\n    verify_pool2d(\n        [1, 31, 31, 16], [3, 3], [3, 3], [3, 3], [1, 0, 3, 2], \"max\", False, layout=\"NHWC\"\n    )\n    verify_pool2d([1, 31, 31, 16], [3, 3], [3, 3], [2, 2], [3, 2, 1, 0], \"max\", True, layout=\"NHWC\")\n\n\ndef verify_pool1d(\n    input_shape,\n    kernel,\n    stride,\n    dilation,\n    padding,\n    pool_type,\n    ceil_mode,\n    count_include_pad=True,\n    layout=\"NCW\",\n):\n    verify_poolnd(\n        1,\n        input_shape,\n        kernel,\n        stride,\n        dilation,\n        padding,\n        pool_type,\n        ceil_mode,\n        layout=layout,\n        count_include_pad=count_include_pad,\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_pool1d():\n    \"\"\"test cases of pool1d\"\"\"\n    verify_pool1d([1, 16, 32], [2], [2], [1], [0, 0], \"avg\", False, True)\n    verify_pool1d([1, 16, 31], [3], [3], [1], [1, 2], \"avg\", False, True)\n    verify_pool1d([1, 16, 32], [2], [2], [1], [1, 2], \"avg\", False, False)\n    verify_pool1d([1, 16, 31], [4], [4], [1], [3, 3], \"avg\", False, False)\n    verify_pool1d([1, 16, 31], [4], [4], [1], [0, 0], \"avg\", False, False)\n    verify_pool1d([1, 16, 32], [2], [2], [1], [0, 0], \"max\", False)\n    verify_pool1d([1, 16, 31], [3], [3], [1], [2, 1], \"max\", False)\n    verify_pool1d([1, 16, 31], [3], [3], [1], [2, 1], \"max\", True)\n\n    verify_pool1d([1, 16, 31], [3], [3], [1], [2, 5], \"avg\", False, True)\n    verify_pool1d([1, 16, 32], [2], [2], [1], [0, 3], \"avg\", False, False)\n    verify_pool1d([1, 16, 31], [3], [3], [1], [1, 4], \"max\", False)\n    verify_pool1d([1, 16, 31], [3], [3], [1], [3, 0], \"max\", True)\n\n    # Test non-1 dilations\n    verify_pool1d([1, 16, 31], [3], [3], [2], [2, 5], \"avg\", False, True)\n    verify_pool1d([1, 16, 32], [2], [2], [3], [0, 3], \"avg\", False, False)\n    verify_pool1d([1, 16, 31], [3], [3], [2], [1, 4], \"max\", False)\n    verify_pool1d([1, 16, 31], [3], [3], [3], [3, 0], \"max\", True)\n    # Test Channel last\n    verify_pool1d([1, 32, 16], [2], [2], [1], [0, 0], \"avg\", False, True, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [1], [1, 2], \"avg\", False, True, layout=\"NWC\")\n    verify_pool1d([1, 32, 16], [2], [2], [1], [1, 2], \"avg\", False, False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [4], [4], [1], [3, 3], \"avg\", False, False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [4], [4], [1], [0, 0], \"avg\", False, False, layout=\"NWC\")\n    verify_pool1d([1, 32, 16], [2], [2], [1], [0, 0], \"max\", False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [1], [2, 1], \"max\", False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [1], [2, 1], \"max\", True, layout=\"NWC\")\n\n    verify_pool1d([1, 31, 16], [3], [3], [1], [2, 5], \"avg\", False, True, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [2], [2], [1], [0, 3], \"avg\", False, False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [1], [1, 4], \"max\", False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [1], [3, 0], \"max\", True, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [2], [2, 5], \"avg\", False, True, layout=\"NWC\")\n    verify_pool1d([1, 32, 16], [2], [2], [3], [0, 3], \"avg\", False, False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [2], [1, 4], \"max\", False, layout=\"NWC\")\n    verify_pool1d([1, 31, 16], [3], [3], [3], [3, 0], \"max\", True, layout=\"NWC\")\n\n\nif __name__ == \"__main__\":\n    test_pool1d()\n    test_pool2d()\n    test_pool3d()\n    test_pool_grad()\n    test_global_pool()\n    test_adaptive_pool()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_prng.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.relay\nimport tvm.testing\nimport tvm.topi\nimport numpy as np\nimport scipy.stats\n\n\ndef threefry_split(target, dev, gen):\n    gen_placeholder = tvm.te.placeholder(gen.shape, name=\"gen\", dtype=\"uint64\")\n    left_placeholder, right_placeholder = tvm.topi.random.threefry_split(gen_placeholder)\n    s = tvm.topi.generic.schedule_extern([left_placeholder, right_placeholder])\n    f = tvm.build(s, [gen_placeholder, left_placeholder, right_placeholder])\n    left = tvm.nd.array(np.zeros(gen.shape, dtype=\"uint64\"))\n    right = tvm.nd.array(np.zeros(gen.shape, dtype=\"uint64\"))\n    f(tvm.nd.array(gen), left, right)\n    return left.numpy(), right.numpy()\n\n\ndef threefry_generate(target, dev, gen, size):\n    gen_placeholder = tvm.te.placeholder(gen.shape, name=\"gen\", dtype=\"uint64\")\n    left_placeholder, right_placeholder = tvm.topi.random.threefry_generate(gen_placeholder, size)\n    s = tvm.topi.generic.schedule_extern([left_placeholder, right_placeholder])\n    f = tvm.build(s, [gen_placeholder, left_placeholder, right_placeholder])\n    out_gen = tvm.nd.array(np.zeros(gen.shape, dtype=\"uint64\"))\n    rands = tvm.nd.array(np.zeros(size, dtype=\"uint64\"))\n    f(tvm.nd.array(gen), out_gen, rands)\n    return out_gen.numpy(), rands.numpy()\n\n\ndef uniform(target, dev, gen, low, high, size, dtype):\n    gen_placeholder = tvm.te.placeholder(gen.shape, name=\"gen\", dtype=\"uint64\")\n    low_placeholder = tvm.te.placeholder(low.shape, name=\"low\", dtype=dtype)\n    high_placeholder = tvm.te.placeholder(high.shape, name=\"high\", dtype=dtype)\n    left_placeholder, right_placeholder = tvm.topi.random.uniform(\n        gen_placeholder, low_placeholder, high_placeholder, size, dtype\n    )\n    s = tvm.topi.generic.schedule_extern([left_placeholder, right_placeholder])\n    f = tvm.build(\n        s,\n        [gen_placeholder, low_placeholder, high_placeholder, left_placeholder, right_placeholder],\n        target=target,\n    )\n    out_gen = tvm.nd.array(np.zeros(gen.shape, dtype=\"uint64\"), device=dev)\n    rands = tvm.nd.array(np.zeros(size, dtype=dtype), device=dev)\n    f(\n        tvm.nd.array(gen, device=dev),\n        tvm.nd.array(low, device=dev),\n        tvm.nd.array(high, device=dev),\n        out_gen,\n        rands,\n    )\n    return out_gen.numpy(), rands.asnumpy()\n\n\ndef multinomial(target, dev, gen, probs, num_samples):\n    gen_placeholder = tvm.te.placeholder(gen.shape, name=\"gen\", dtype=\"uint64\")\n    probs_placeholder = tvm.te.placeholder(probs.shape, name=\"probs\", dtype=\"float32\")\n    new_gen_placeholder, indices_placeholder = tvm.topi.random.multinomial(\n        gen_placeholder, probs_placeholder, num_samples\n    )\n    s = tvm.topi.generic.schedule_extern([new_gen_placeholder, indices_placeholder])\n    f = tvm.build(\n        s,\n        [gen_placeholder, probs_placeholder, new_gen_placeholder, indices_placeholder],\n        target=target,\n    )\n    out_gen = tvm.nd.array(np.zeros(gen.shape, dtype=\"uint64\"), device=dev)\n    indices = tvm.nd.array(np.zeros((*probs.shape[:-1], num_samples), dtype=\"int32\"), device=dev)\n    f(tvm.nd.array(gen), tvm.nd.array(probs), out_gen, indices)\n    return out_gen.numpy(), indices.asnumpy()\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_threefry_split(target, dev):\n    # test that results of split do not equal eachother or the input\n    gen = tvm.relay.random.threefry_key(0).data.numpy()\n    a, b = threefry_split(target, dev, gen)\n    assert (a != b).any() and (\n        a != gen\n    ).any(), \"Splitting a gen should result in different output gens\"\n    # unittest some split inputs\n    assert (a == np.array([0, 0, 0, 0, 0, 0, 0, 0, 1 << 62, 0], dtype=\"uint64\")).all()\n    assert (b == np.array([0, 0, 0, 0, 1 << 63, 0, 0, 0, 1 << 62, 0], dtype=\"uint64\")).all()\n\n    # test enough splits to go over path length\n    for i in range(129):\n        a, b = threefry_split(target, dev, b)\n    assert (a[0:4] == b[0:4]).all(), \"State part of split should be the same\"\n    assert (b[0:4] != np.zeros(4, dtype=\"uint64\")).any()\n\n    # check that split then generate does not generate the same for both sides\n    a, a_rands = threefry_generate(target, dev, a, (100,))\n    b, b_rands = threefry_generate(target, dev, b, (100,))\n    assert (\n        a_rands != b_rands\n    ).all(), \"Numbers generated from different initial states should be different\"\n\n    # check repeatability\n    _, rands1 = threefry_generate(target, dev, a, (100,))\n    _, rands2 = threefry_generate(target, dev, a, (100,))\n    assert (\n        rands1 == rands2\n    ).all(), \"Numbers generated from the same initial state should be the same\"\n\n    a1, b1 = threefry_split(target, dev, a)\n    a2, b2 = threefry_split(target, dev, a)\n    assert (a1 == a2).all() and (\n        b1 == b2\n    ).all(), \"Split called on the same input should return the same result\"\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_threefry_generate(target, dev):\n    gen = tvm.relay.random.threefry_key(0).data.numpy()\n\n    # check that we can generate some data\n    a, rands = threefry_generate(target, dev, gen, (2048,))\n    assert (\n        rands.shape[0] == 2048 and len(rands.shape) == 1\n    ), \"Output shape should match requested shape\"\n\n    # check that gen out does not equal input\n    assert (a != gen).any(), \"Output generator should be different from input generator\"\n\n    # check that we can generate data whose total number of elements is not a multiple of 4.\n    a, rands = threefry_generate(target, dev, gen, (7,))\n    assert (\n        rands.shape[0] == 7 and len(rands.shape) == 1\n    ), \"Output shape should match requested shape\"\n\n    # test enough generates to go over generate limit\n    gen = np.array(\n        [0, 0, 0, 0, 0, 0, 0, 2**64 - 2, 1 << 63, 0], dtype=\"uint64\"\n    )  # make counter large\n    a, rands = threefry_generate(target, dev, gen, (2048,))\n    assert gen[4] != a[4], \"Overflow of counter should trigger path change\"\n    assert a[7] == 2048, \"Overflow of counter should still update counter\"\n\n    # check generate with path at length limit\n    gen = np.array([0, 0, 0, 0, 0, 0, 0, 2**64 - 2, 0, 0], dtype=\"uint64\")  # make counter large\n    a, rands = threefry_generate(target, dev, gen, (2048,))\n    assert (\n        gen[0:4] != a[0:4]\n    ).any(), \"Overflowing counter with no space left in path should change state\"\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_threefry_wrapping(target, dev):\n    assert tvm.topi.random.threefry_test_wrapping(\n        target, dev\n    ), f\"{target} does not suppport wrapping unsigned integer arithmetic\"\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_uniform(target, dev):\n    gen = tvm.relay.random.threefry_key(0).data.numpy()\n    m = 1024\n    n = 1024\n    dtypes = [\"float32\", \"float64\"]\n    for dtype in dtypes:\n        low = np.array(5.0, dtype=dtype)\n        high = np.array(10.0, dtype=dtype)\n        new_gen, rands = uniform(target, dev, gen, low, high, (m, n), dtype)\n        assert (gen != new_gen).any()\n        assert abs(np.mean(rands) - 7.5) < 1e-1\n        assert np.min(rands) >= 5.0\n        assert np.max(rands) <= 10.0\n\n\n@tvm.testing.parametrize_targets(\"llvm\")\ndef test_multinomial(target, dev):\n    def _verify_multinomial(size, num_samples, test_statistics=False):\n        gen = tvm.relay.random.threefry_key(np.random.randint(0, 1e5)).data.numpy()\n        probs = np.random.randint(low=-50, high=1000, size=size).astype(\"float32\")\n        new_gen, indices = multinomial(target, dev, gen, probs, num_samples)\n        assert (gen != new_gen).any()\n        assert np.min(indices) >= 0\n        assert np.max(indices) < probs.shape[-1]\n        # Note, only use test_statistics with sample size > 10,000.\n        if test_statistics:\n            # Clipped and normalized probabilities * number of samples\n            # represents expected frequency of each category.\n            # First upcast to float64 to remove numerical error.\n            probs = probs.astype(\"float64\")\n            probs = np.reshape(probs, [-1, probs.shape[-1]])\n            probs = np.maximum(probs, 0)\n            probs = probs / np.expand_dims(np.sum(probs, axis=-1), axis=-1)\n            # Multiply by number of samples and add epsilon to get non-zero expected samples per index.\n            expected_frequency = probs * num_samples + np.finfo(float).eps\n            # Do a small adjustment to make sure each row of expected_frequencies sums to exactly num_samples.\n            expected_frequency = (\n                np.expand_dims((num_samples / np.sum(expected_frequency, axis=-1)), axis=-1)\n                * expected_frequency\n            )\n            # Reduce shape to a 2D matrix.\n            indices = np.reshape(indices, [-1, indices.shape[-1]])\n            # Split indendent rows of indices.\n            index_list = [np.squeeze(x, 0) for x in np.split(indices, indices.shape[0], axis=0)]\n            # Count frequency of selected indices in each row.\n            observed_freqs = [np.bincount(samples, minlength=size[-1]) for samples in index_list]\n            # Stack observed frequencies back into a matrix.\n            observed_freqs = np.stack(observed_freqs, axis=0)\n            # Test how closely observed samples match expectations.\n            _, p_value = scipy.stats.chisquare(observed_freqs, expected_frequency, axis=-1)\n            # If sampled correctly, p_value should be greater than 1e-6 almost all the time.\n            assert np.all(p_value > 1e-6)\n\n    # Test simple 1-D case.\n    _verify_multinomial([3], 2)\n    # Test 2-D case.\n    _verify_multinomial([2, 10], 1)\n    # Test 3-D case.\n    _verify_multinomial([2, 3, 10], 4)\n    # Test large sample size statistics.\n    _verify_multinomial([3, 10], 10000, test_statistics=True)\n\n\nif __name__ == \"__main__\":\n    test_threefry_split(tvm.target.Target(\"llvm\"), tvm.device(\"cpu\"))\n    test_threefry_generate(tvm.target.Target(\"llvm\"), tvm.device(\"cpu\"))\n    test_threefry_wrapping(tvm.target.Target(\"llvm\"), tvm.device(\"cpu\"))\n    test_uniform(tvm.target.Target(\"llvm\"), tvm.device(\"cpu\"))\n    test_multinomial(tvm.target.Target(\"llvm\"), tvm.device(\"cpu\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_qnn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for QNN operators.\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import topi, relay, te\nfrom tvm.contrib import graph_executor\nimport tvm.topi.testing\n\n\ndef verify_simulated_quantize(data_shape, out_dtype, channels, axis):\n    # Create placeholder variables for all qnn inputs.\n    A = te.placeholder(data_shape, name=\"value\", dtype=\"float32\")\n    D = te.placeholder([], name=\"dtype\", dtype=\"int32\")\n    S = te.placeholder([te.size_var(\"scale_dim\")], name=\"scale\", dtype=\"float32\")\n    Z = te.placeholder([te.size_var(\"zp_dim\")], name=\"zp\", dtype=\"int32\")\n    SIM_Q = topi.nn.simulated_quantize(A, D, output_scale=S, output_zero_point=Z, axis=axis)\n\n    # Create random numpy values to assign to inputs.\n    a_np = np.random.uniform(size=data_shape).astype(\"float32\")\n    d_np = np.int32(topi.nn.SQNN_DTYPE_TO_CODE[out_dtype])\n    s_np = np.random.uniform(low=1e-4, high=0.1, size=channels).astype(\"float32\")\n    z_np = np.random.uniform(low=-10, high=10, size=channels).astype(\"int32\")\n    q_np = np.zeros(shape=data_shape, dtype=\"float32\")\n\n    def check_target(target, dev):\n        # Wrap the numpy arrays in nd arrays.\n        a = tvm.nd.array(a_np, dev)\n        d = tvm.nd.array(d_np, dev)\n        s = tvm.nd.array(s_np, dev)\n        z = tvm.nd.array(z_np, dev)\n        q = tvm.nd.array(q_np, dev)\n\n        # Construct equivalent relay graph.\n        per_channel = channels[0] != 1\n        a_var = relay.var(\"a\", shape=data_shape, dtype=\"float32\")\n        if per_channel:\n            s_var = relay.const(s_np)\n            z_var = relay.const(z_np)\n        else:\n            s_var = relay.const(s_np[0])\n            z_var = relay.const(z_np[0])\n        real_q_op = relay.qnn.op.quantize(a_var, s_var, z_var, axis=axis, out_dtype=out_dtype)\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(tvm.IRModule.from_expr(real_q_op), target=target)\n\n        # Get real qnn quantize output.\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        m.set_input(\"a\", a_np)\n\n        m.run()\n        real_q_out = m.get_output(0)\n\n        # Compile the simulated quantize function.\n        with tvm.target.Target(target):\n            sched = tvm.topi.testing.get_injective_schedule(target)(SIM_Q)\n        func = tvm.build(sched, [A, D, S, Z, SIM_Q], target, name=\"sim_quantize\")\n        func(a, d, s, z, q)\n\n        # Check correctness against the true qnn output.\n        mismatch = q.numpy() != real_q_out.numpy().astype(\"float32\")\n        # Allow some rounding errors due to GPU fp32 arithmetic.\n        assert np.sum(mismatch) <= 3\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\ndef test_simulated_quantize():\n    verify_simulated_quantize([1], \"int8\", [1], -1)\n    verify_simulated_quantize([2, 5], \"int8\", [5], 1)\n    verify_simulated_quantize([1, 32, 32, 32], \"int8\", [32], -1)\n    verify_simulated_quantize([1, 32, 32, 32], \"uint8\", [32], -2)\n    verify_simulated_quantize([2, 5], \"int32\", [5], 1)\n\n\ndef verify_simulated_dequantize(data_shape, in_dtype, channels, axis):\n    # Create placeholder variables for all qnn inputs.\n    A = te.placeholder(data_shape, name=\"value\", dtype=\"float32\")\n    D = te.placeholder([], name=\"dtype\", dtype=\"int32\")\n    S = te.placeholder([te.size_var(\"scale_dim\")], name=\"scale\", dtype=\"float32\")\n    Z = te.placeholder([te.size_var(\"zp_dim\")], name=\"zp\", dtype=\"int32\")\n    SIM_DQ = topi.nn.simulated_dequantize(A, D, input_scale=S, input_zero_point=Z, axis=axis)\n\n    # Create random numpy values to assign to inputs.\n    a_np = np.random.uniform(low=-128, high=127, size=data_shape).astype(in_dtype)\n    a_np_f = a_np.astype(\"float32\")\n    d_np = np.int32(topi.nn.SQNN_DTYPE_TO_CODE[in_dtype])\n    s_np = np.random.uniform(low=1e-4, high=0.1, size=channels).astype(\"float32\")\n    z_np = np.random.uniform(low=-10, high=10, size=channels).astype(\"int32\")\n    dq_np = np.zeros(shape=data_shape, dtype=\"float32\")\n\n    def check_target(target, dev):\n        # Wrap the numpy arrays in nd arrays.\n        a = tvm.nd.array(a_np_f, dev)\n        d = tvm.nd.array(d_np, dev)\n        s = tvm.nd.array(s_np, dev)\n        z = tvm.nd.array(z_np, dev)\n        dq = tvm.nd.array(dq_np, dev)\n\n        # Construct equivalent relay graph.\n        per_channel = channels[0] != 1\n        a_var = relay.var(\"a\", shape=data_shape, dtype=in_dtype)\n        if per_channel:\n            s_var = relay.const(s_np)\n            z_var = relay.const(z_np)\n        else:\n            s_var = relay.const(s_np[0])\n            z_var = relay.const(z_np[0])\n        real_dq_op = relay.qnn.op.dequantize(a_var, s_var, z_var, axis=axis)\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build(tvm.IRModule.from_expr(real_dq_op), target=target)\n\n        # Get real qnn quantize output.\n        m = graph_executor.GraphModule(lib[\"default\"](dev))\n        m.set_input(\"a\", a_np)\n\n        m.run()\n        real_dq_out = m.get_output(0)\n\n        # Compile the simulated quantize function.\n        with tvm.target.Target(target):\n            sched = tvm.topi.testing.get_injective_schedule(target)(SIM_DQ)\n        func = tvm.build(sched, [A, D, S, Z, SIM_DQ], target, name=\"sim_quantize\")\n        func(a, d, s, z, dq)\n\n        # Check correctness against the true qnn output.\n        tvm.testing.assert_allclose(dq.numpy(), real_dq_out.numpy().astype(\"float32\"), rtol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\ndef test_simulated_dequantize():\n    verify_simulated_dequantize([1], \"int8\", [1], -1)\n    verify_simulated_dequantize([2, 5], \"int8\", [5], 1)\n    verify_simulated_dequantize([2, 5], \"int8\", [2], 0)\n    verify_simulated_dequantize([1, 32, 32, 32], \"int8\", [32], -1)\n    verify_simulated_dequantize([1, 32, 32, 32], \"uint8\", [32], -2)\n    verify_simulated_dequantize([2, 5], \"int32\", [5], 1)\n\n\nif __name__ == \"__main__\":\n    test_simulated_quantize()\n    test_simulated_dequantize()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_reduce.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for reduce.\"\"\"\nimport os\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\n\nin_shape, axis, keepdims, reduce_type, dtype = tvm.testing.parameters(\n    ((32,), 0, False, \"argmax\", \"float32\"),\n    ((128, 24, 128, 24), (1, 2, 3), True, \"sum\", \"float32\"),\n    ((2, 3), None, True, \"all\", \"bool\"),\n    ((128, 24 * 128 * 24), (1,), False, \"max\", \"float32\"),\n    ((32, 128, 24), None, True, \"sum\", \"float32\"),\n    ((32, 128, 24), None, True, \"all\", \"bool\"),\n    ((128, 24, 128, 24), (0, 2), False, \"min\", \"float32\"),\n    ((32, 128), 1, True, \"argmax\", \"float32\"),\n    ((32, 24, 32, 24), 2, False, \"argmin\", \"float32\"),\n    ((31, 21, 15), None, True, \"argmax\", \"float32\"),\n    ((31, 21, 15), None, False, \"sum\", \"float32\"),\n    ((128, 24, 128, 24), (1, 2, 3), True, \"sum\", \"float64\"),\n    ((2, 3), None, True, \"any\", \"bool\"),\n    ((32, 128, 24), None, True, \"any\", \"bool\"),\n    ((1, 4, 7), 1, True, \"any\", \"bool\"),\n    ((128, 24, 128, 24), 2, False, \"any\", \"bool\"),\n)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(in_shape, axis, keepdims, reduce_type, dtype):\n    # Test\n    if dtype == \"bool\":\n        in_npy_map = in_npy = np.random.choice([True, False], size=in_shape)\n    else:\n        in_npy = np.random.uniform(-1, 1, size=in_shape).astype(dtype)\n        in_npy_map = np.sqrt(np.exp(in_npy)).astype(dtype)\n\n    if reduce_type == \"sum\":\n        out_npy = in_npy_map.sum(axis=axis, keepdims=keepdims)\n    elif reduce_type == \"all\" and dtype == \"bool\":\n        out_npy = in_npy_map.all(axis=axis, keepdims=keepdims)\n    elif reduce_type == \"any\" and dtype == \"bool\":\n        out_npy = in_npy_map.any(axis=axis, keepdims=keepdims)\n    elif reduce_type == \"max\":\n        out_npy = in_npy_map.max(axis=axis, keepdims=keepdims)\n    elif reduce_type == \"min\":\n        out_npy = in_npy_map.min(axis=axis, keepdims=keepdims)\n    elif reduce_type == \"argmax\":\n        out_npy = _my_npy_argmax(in_npy_map, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"argmin\":\n        out_npy = _my_npy_argmin(in_npy_map, axis=axis, keepdims=keepdims)\n    else:\n        raise NotImplementedError\n\n    return in_npy, in_npy_map, out_npy\n\n\ndef _my_npy_argmax(arr, axis, keepdims):\n    if not keepdims:\n        return arr.argmax(axis=axis)\n    else:\n        if axis is None:\n            out_shape = [1 for _ in arr.shape]\n        else:\n            out_shape = list(arr.shape)\n            out_shape[axis] = 1\n\n        return arr.argmax(axis=axis).reshape(out_shape)\n\n\ndef _my_npy_argmin(arr, axis, keepdims):\n    if not keepdims:\n        return arr.argmin(axis=axis)\n    else:\n        if axis is None:\n            out_shape = [1 for _ in arr.shape]\n        else:\n            out_shape = list(arr.shape)\n            out_shape[axis] = 1\n        return arr.argmin(axis=axis).reshape(out_shape)\n\n\ndef test_reduce_map(target, dev, ref_data, in_shape, axis, keepdims, reduce_type, dtype):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\" and reduce_type in [\"sum\", \"any\", \"all\"]:\n        pytest.xfail(f\"Vulkan backend has known errors on {reduce_type}\")\n\n    in_npy, in_npy_map, out_npy = ref_data\n\n    # Build the logic and compile the function\n    A = te.placeholder(shape=in_shape, name=\"A\", dtype=dtype)\n    A1 = topi.sqrt(topi.exp(A))\n    out_dtype = dtype\n    if reduce_type == \"sum\":\n        B = topi.sum(A1, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"all\":\n        B = topi.all(A, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"any\":\n        B = topi.any(A, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"max\":\n        B = topi.max(A1, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"min\":\n        B = topi.min(A1, axis=axis, keepdims=keepdims)\n    elif reduce_type == \"argmax\":\n        B = topi.argmax(A1, axis=axis, keepdims=keepdims)\n        out_dtype = \"int32\"\n    elif reduce_type == \"argmin\":\n        B = topi.argmin(A1, axis=axis, keepdims=keepdims)\n        out_dtype = \"int32\"\n    else:\n        raise NotImplementedError\n\n    with tvm.target.Target(target):\n        s = tvm.topi.testing.get_reduce_schedule(target)(B)\n\n    foo = tvm.build(s, [A, B], target, name=reduce_type)\n\n    data_tvm = tvm.nd.array(in_npy, device=dev)\n    out_tvm = tvm.nd.empty(shape=out_npy.shape, device=dev, dtype=out_dtype)\n    foo(data_tvm, out_tvm)\n\n    if reduce_type == \"argmax\" or reduce_type == \"argmin\":\n        out_tvm_indices = out_tvm.numpy()\n        if keepdims:\n            out_tvm_indices = np.take(out_tvm_indices, indices=0, axis=axis)\n        if axis is None:\n            out_tvm_val = in_npy_map.ravel()[out_tvm_indices]\n        else:\n            other_indices = tuple(np.indices(in_shape[0:axis] + in_shape[(axis + 1) :]))\n            sel_indices = other_indices[0:axis] + (out_tvm_indices,) + other_indices[axis:]\n            out_tvm_val = in_npy_map[sel_indices]\n        if reduce_type == \"argmax\":\n            tvm.testing.assert_allclose(out_tvm_val, in_npy_map.max(axis=axis), 1e-3, 1e-3)\n        elif reduce_type == \"argmin\":\n            tvm.testing.assert_allclose(out_tvm_val, in_npy_map.min(axis=axis), 1e-3, 1e-3)\n    else:\n        tvm.testing.assert_allclose(out_tvm.numpy(), out_npy, 1e-3, 1e-3)\n\n\ndef test_complex_reduce(target, dev):\n    in_shape = (2, 3)\n    dtype = \"float32\"\n    axis = 0\n    keepdims = False\n    A = te.placeholder(shape=in_shape, name=\"A\", dtype=dtype)\n    B = topi.sum(A, axis=axis, keepdims=keepdims)\n    C = topi.add(B, B)\n    D = topi.multiply(B, B)\n    E = topi.add(C, D)\n\n    with tvm.target.Target(target):\n        s = tvm.topi.testing.get_reduce_schedule(target)(E)\n    foo = tvm.build(s, [A, E], target, name=\"sum\")\n\n    in_npy = np.random.uniform(-1, 1, size=in_shape).astype(dtype)\n    sum_npy = in_npy.sum(axis=axis, keepdims=keepdims)\n    out_npy = sum_npy * 2 + sum_npy * sum_npy\n\n    data_tvm = tvm.nd.array(in_npy, device=dev)\n    out_tvm = tvm.nd.empty(shape=out_npy.shape, device=dev, dtype=dtype)\n    foo(data_tvm, out_tvm)\n    tvm.testing.assert_allclose(out_tvm.numpy(), out_npy, 1e-3, 1e-3)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_relu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for relu activation\"\"\"\nimport sys\nimport os\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.contrib.nvcc import have_fp16\n\nimport pytest\nimport tvm.testing\n\n\nm, n, dtype = tvm.testing.parameters(\n    (10, 128, \"float32\"),\n    (128, 64, \"float16\"),\n    # Commented due to weird killed\n    # (1024 * 100, 512, \"float32\"),\n)\n\n\ndef test_relu(target, dev, m, n, dtype):\n    A = te.placeholder((m, n), name=\"A\", dtype=dtype)\n    B = topi.nn.relu(A)\n\n    a_np = np.random.uniform(low=-1.0, high=1.0, size=get_const_tuple(A.shape)).astype(A.dtype)\n    b_np = a_np * (a_np > 0)\n\n    if dtype == \"float16\" and target == \"cuda\" and not have_fp16(tvm.cuda(0).compute_version):\n        pytest.skip(\"Skip because %s does not have fp16 support\" % target)\n\n    print(\"Running on target: %s\" % target)\n    with tvm.target.Target(target):\n        s = tvm.topi.testing.get_elemwise_schedule(target)(B)\n\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    # Building with the CSE pass disabled\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        foo = tvm.build(s, [A, B], target, name=\"relu\")\n    foo(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nsize, alpha = tvm.testing.parameters((100, 0.1))\n\n\ndef test_leaky_relu(size, alpha):\n    A = te.placeholder((size,), name=\"A\")\n    B = topi.nn.leaky_relu(A, alpha)\n    s = te.create_schedule([B.op])\n\n    a_np = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)\n    b_np = a_np * (a_np > 0) + a_np * (a_np < 0) * alpha\n    dev = tvm.cpu(0)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    # Building with the CSE pass disabled\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        foo = tvm.build(s, [A, B], \"llvm\", name=\"leaky_relu\")\n    foo(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nx, w, axis, weight_reshape = tvm.testing.parameters(\n    ((1, 3, 2, 2), (3,), 1, (3, 1, 1)),\n    ((1, 3, 2, 2), (2,), 2, (2, 1)),\n    ((1, 3), (3,), 1, (3,)),\n)\n\n\ndef test_prelu(x, w, axis, weight_reshape):\n    X = te.placeholder((x), name=\"X\")\n    W = te.placeholder((w), name=\"W\")\n    x_np = np.random.uniform(low=-1.0, high=1.0, size=get_const_tuple(X.shape)).astype(X.dtype)\n    w_np = np.random.uniform(low=-1.0, high=1.0, size=get_const_tuple(W.shape)).astype(W.dtype)\n\n    def _prelu_numpy(x, W):\n        return (x < 0) * (x * W.reshape(weight_reshape)) + (x >= 0) * x\n\n    B = topi.nn.prelu(X, W, axis)\n    s = te.create_schedule([B.op])\n\n    dev = tvm.cpu(0)\n    x_tvm = tvm.nd.array(x_np, dev)\n    w_tvm = tvm.nd.array(w_np, dev)\n\n    b = tvm.nd.array(np.zeros(get_const_tuple(X.shape), dtype=B.dtype), dev)\n    # Building with the CSE pass disabled\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        foo = tvm.build(s, [X, W, B], \"llvm\", name=\"prelu\")\n    foo(x_tvm, w_tvm, b)\n    out_np = _prelu_numpy(x_np, w_np)\n    tvm.testing.assert_allclose(b.numpy(), out_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_reorg.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Example code to do reorg.\"\"\"\nimport numpy as np\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nimport tvm\nfrom tvm import te\nimport tvm.topi.testing\nimport tvm.testing\n\n_reorg_schedule = {\n    \"generic\": topi.generic.schedule_reorg,\n    \"gpu\": topi.cuda.schedule_reorg,\n}\n\n\ndef verify_reorg(batch, in_size, in_channel, stride):\n    \"\"\"Verify reorg operator by comparing outputs from tvm and numpy implementation\"\"\"\n    in_height = in_width = in_size\n\n    A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n    B = topi.vision.reorg(A, stride)\n\n    a_shape = get_const_tuple(A.shape)\n    dtype = A.dtype\n\n    def get_ref_data_reorg():\n        a_np = np.random.uniform(size=a_shape).astype(dtype)\n        b_np = tvm.topi.testing.reorg_python(a_np, stride)\n        return a_np, b_np\n\n    a_np, b_np = get_ref_data_reorg()\n\n    def check_device(device):\n        \"\"\"Cheching devices is enabled or not\"\"\"\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s_func = tvm.topi.testing.dispatch(device, _reorg_schedule)\n            s = s_func([B])\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n        func = tvm.build(s, [A, B], device)\n        func(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n    for device in [\"llvm\", \"cuda\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_reorg():\n    verify_reorg(1, 20, 8, 2)\n\n\nif __name__ == \"__main__\":\n    test_reorg()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_scan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom typing import Callable\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import topi\n\ntopi_funcs = {\n    \"cumsum\": {\"generic\": topi.cumsum, \"cuda\": topi.cuda.cumsum},\n    \"cumprod\": {\"generic\": topi.cumprod, \"cuda\": topi.cuda.cumprod},\n}\n\nidentity_value = {\"cumsum\": 0, \"cumprod\": 1}\n\n\ndef get_implementations(name, axis, dtype, exclusive):\n    topi_func_generic = topi_funcs[name][\"generic\"]\n    topi_func_cuda = topi_funcs[name][\"cuda\"]\n\n    return {\n        \"generic\": (\n            lambda x: topi_func_generic(x, axis, dtype, exclusive=exclusive),\n            topi.generic.schedule_extern,\n        ),\n        \"cuda\": (\n            lambda x: topi_func_cuda(x, axis, dtype, exclusive=exclusive),\n            topi.cuda.schedule_scan,\n        ),\n        \"nvptx\": (\n            lambda x: topi_func_cuda(x, axis, dtype, exclusive=exclusive),\n            topi.cuda.schedule_scan,\n        ),\n        \"vulkan\": (\n            lambda x: topi_func_cuda(x, axis, dtype, exclusive=exclusive),\n            topi.cuda.schedule_scan,\n        ),\n        \"metal\": (\n            lambda x: topi_func_cuda(x, axis, dtype, exclusive=exclusive),\n            topi.cuda.schedule_scan,\n        ),\n    }\n\n\ndef _run_tests(\n    dev,\n    target,\n    op_name: str = \"cumsum\",\n    gt_func: Callable[..., np.array] = np.cumsum,\n):\n    def check_scan(np_ref, data, axis=None, dtype=None, exclusive=False):\n        implementations = get_implementations(op_name, axis, dtype, exclusive)\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, implementations)\n        tvm.topi.testing.compare_numpy_tvm([data], np_ref, target, dev, fcompute, fschedule)\n\n    data = np.array([2, 3, 0])\n    check_scan(gt_func(data), data)\n\n    data = np.random.rand(10) > 0.5\n    data = data.astype(np.int32)\n    check_scan(gt_func(data, dtype=np.int32), data)\n    check_scan(gt_func(data), data, dtype=\"int64\")\n\n    data = np.random.rand(10) > 0.5\n    check_scan(gt_func(data, dtype=np.int32), data, dtype=\"int32\")\n\n    for in_dtype in [\"float32\", \"float64\"]:\n        if target == \"metal\" and in_dtype == \"float64\":\n            # float64 is not supported in metal\n            continue\n        data = np.random.randn(10, 10).astype(in_dtype)\n        check_scan(gt_func(data), data)\n        check_scan(gt_func(data, axis=0), data, axis=0)\n        check_scan(gt_func(data, axis=1), data, axis=1)\n\n        data = np.random.randn(10, 5, 10).astype(in_dtype)\n        check_scan(gt_func(data), data)\n        check_scan(gt_func(data, axis=0), data, axis=0)\n        check_scan(gt_func(data, axis=1), data, axis=1)\n        check_scan(gt_func(data, axis=-1), data, axis=-1)\n\n    for in_dtype in [\"int32\", \"int64\"]:\n        data = np.random.randint(-100, 100, size=(100, 100)).astype(in_dtype)\n        check_scan(gt_func(data, dtype=in_dtype), data)\n        check_scan(gt_func(data), data, dtype=\"int64\")\n        check_scan(gt_func(data, axis=0, dtype=in_dtype), data, axis=0)\n        check_scan(gt_func(data, axis=1, dtype=in_dtype), data, axis=1)\n\n        data = np.random.randint(1 << 30, (1 << 31) - 1, size=(100)).astype(in_dtype)\n        check_scan(gt_func(data), data, dtype=\"int64\")\n\n    data = np.random.randint(-100, 100, size=(100, 100)).astype(\"int64\")\n\n    expected_result = np.roll(gt_func(data), 1)\n    expected_result[0] = identity_value[op_name]\n    check_scan(expected_result, data, dtype=\"int64\", exclusive=True)\n\n    expected_result = np.roll(gt_func(data, axis=0, dtype=in_dtype), 1, axis=0)\n    expected_result[0, :] = identity_value[op_name]\n    check_scan(expected_result, data, axis=0, exclusive=True)\n\n    expected_result = np.roll(gt_func(data, axis=1, dtype=in_dtype), 1, axis=1)\n    expected_result[:, 0] = identity_value[op_name]\n    check_scan(gt_func(data, axis=1, dtype=in_dtype), data, axis=1)\n\n\n@tvm.testing.parametrize_targets\ndef test_cumsum(dev, target):\n    _run_tests(dev, target, op_name=\"cumsum\", gt_func=np.cumsum)\n\n\n@tvm.testing.parametrize_targets\ndef test_cumprod(dev, target):\n    _run_tests(dev, target, op_name=\"cumprod\", gt_func=np.cumprod)\n\n\nif __name__ == \"__main__\":\n    test_cumsum(tvm.device(\"cpu\"), tvm.target.Target(\"llvm\"))\n    test_cumsum(tvm.device(\"cuda\"), tvm.target.Target(\"cuda\"))\n    test_cumsum(tvm.device(\"nvptx\"), tvm.target.Target(\"nvptx\"))\n    test_cumsum(tvm.device(\"vulkan\"), tvm.target.Target(\"vulkan\"))\n    test_cumsum(tvm.device(\"metal\"), tvm.target.Target(\"metal\"))\n\n    test_cumprod(tvm.device(\"cpu\"), tvm.target.Target(\"llvm\"))\n    test_cumprod(tvm.device(\"cuda\"), tvm.target.Target(\"cuda\"))\n    test_cumprod(tvm.device(\"nvptx\"), tvm.target.Target(\"nvptx\"))\n    test_cumprod(tvm.device(\"vulkan\"), tvm.target.Target(\"vulkan\"))\n    test_cumprod(tvm.device(\"metal\"), tvm.target.Target(\"metal\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_scatter.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nimport tvm.topi.testing\n\n\n@tvm.testing.parametrize_targets\ndef test_scatter_nd(dev, target):\n    def check_scatter_nd(data, indices, updates, out, mode=\"add\"):\n        implementations = {\n            \"generic\": (\n                lambda x, y, z: topi.scatter_nd(x, y, z, mode),\n                topi.generic.schedule_extern,\n            ),\n            \"gpu\": (\n                lambda x, y, z: topi.cuda.scatter_nd(x, y, z, mode),\n                topi.generic.schedule_extern,\n            ),\n            \"cpu\": (\n                lambda x, y, z: topi.x86.scatter_nd(x, y, z, mode),\n                topi.generic.schedule_extern,\n            ),\n        }\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, implementations)\n        tvm.topi.testing.compare_numpy_tvm(\n            [data, indices, updates], out, target, dev, fcompute, fschedule\n        )\n\n    data = np.zeros((2, 2)).astype(\"int64\")\n    indices = np.array([[1, 1, 0], [0, 1, 0]])\n    updates = np.array([2, 3, 0])\n    out = np.array([[0, 0], [2, 3]])\n    check_scatter_nd(data, indices, updates, out)\n\n    data = np.zeros((2, 2, 2, 2)).astype(\"int64\")\n    indices = np.array([[0, 1], [1, 1]])\n    updates = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])\n    out = np.array([[[[0, 0], [0, 0]], [[1, 2], [3, 4]]], [[[0, 0], [0, 0]], [[5, 6], [7, 8]]]])\n    check_scatter_nd(data, indices, updates, out)\n\n    indices = np.array([[1, 0, 0]])\n    updates = np.reshape(np.arange(1560 * 3), (3, 1560)).astype(\"float32\")\n    shape = (2, 1560)\n    data = np.zeros(shape).astype(\"float32\")\n    out = data.copy()\n    out[1, :] += updates[0, :]\n    out[0, :] += updates[1, :]\n    out[0, :] += updates[2, :]\n    check_scatter_nd(data, indices, updates, out)\n\n    for mode in [\"add\", \"update\"]:\n        updates = np.ones((5, 3)).astype(\"float64\")\n        indices = np.stack((np.random.randint(2, size=5), np.random.randint(7, size=5))).astype(\n            \"int64\"\n        )\n        shape = (2, 7, 3)\n        data = np.random.random(shape).astype(\"float64\")\n        out = data.copy()\n        for i in range(indices.shape[1]):\n            for j in range(updates.shape[1]):\n                if mode == \"add\":\n                    out[indices[0, i], indices[1, i], j] += updates[i, j]\n                elif mode == \"update\":\n                    out[indices[0, i], indices[1, i], j] = updates[i, j]\n\n        check_scatter_nd(data, indices, updates, out, mode)\n\n\nif __name__ == \"__main__\":\n    test_scatter_nd(tvm.device(\"cpu\"), tvm.target.Target(\"llvm\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_searchsorted.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm.topi.testing import searchsorted_ref\nfrom tvm import te, topi\n\ntopi_funcs = {\"generic\": topi.searchsorted, \"cuda\": topi.cuda.searchsorted}\n\n\ndef get_implementations():\n    topi_func_generic = topi_funcs[\"generic\"]\n    topi_func_cuda = topi_funcs[\"cuda\"]\n\n    return {\n        \"generic\": (\n            lambda x, y, side, out_dtype: topi_func_generic(x, y, side, out_dtype),\n            topi.generic.schedule_extern,\n        ),\n        \"cuda\": (\n            lambda x, y, side, out_dtype: topi_func_cuda(x, y, side, out_dtype),\n            topi.cuda.schedule_extern,\n        ),\n        \"vulkan\": (\n            lambda x, y, side, out_dtype: topi_func_cuda(x, y, side, out_dtype),\n            topi.cuda.schedule_extern,\n        ),\n    }\n\n\n@tvm.testing.parametrize_targets\ndef test_searchsorted(dev, target):\n    def verify_with_input(sorted_sequence_np, values_np, right):\n        sorted_sequence = te.placeholder(sorted_sequence_np.shape, dtype=\"float32\")\n        values = te.placeholder(values_np.shape, dtype=\"float32\")\n        out_dtype = \"int32\"\n        implementations = get_implementations()\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, implementations)\n\n        with tvm.target.Target(target):\n            indices = fcompute(sorted_sequence, values, right, out_dtype)\n            s = fschedule([indices])\n\n        func = tvm.build(s, [sorted_sequence, values, indices], target=target)\n        dev = tvm.device(target, 0)\n\n        a = tvm.nd.array(sorted_sequence_np, dev)\n        b = tvm.nd.array(values_np, dev)\n        c = tvm.nd.array(np.zeros(values_np.shape, dtype=indices.dtype), dev)\n        func(a, b, c)\n        ref = searchsorted_ref(sorted_sequence_np, values_np, right, out_dtype)\n        np.testing.assert_equal(c.numpy(), ref)\n\n    def verify(sequence_len, num_search, outer_axes, right, sorted_sequence_1d=False):\n        if sorted_sequence_1d:\n            sorted_sequence_shape = (sequence_len,)\n        else:\n            sorted_sequence_shape = outer_axes + (sequence_len,)\n        values_shape = outer_axes + (num_search,)\n\n        verify_with_input(\n            np.sort(np.random.randn(*sorted_sequence_shape).astype(\"float32\"), axis=-1),\n            np.random.randn(*values_shape).astype(\"float32\"),\n            right,\n        )\n\n    verify(1024, 1000, (10, 5, 3), False)\n    verify(999, 2000, (10, 5, 3), True)\n    verify(1000, 1000, (), False)\n    verify(2001, 100, (500,), True)\n    verify(2001, 100, (500,), False, sorted_sequence_1d=True)\n\n    # Check edge cases\n    for right in [True, False]:\n        sorted_sequence = np.array([1, 2, 3, 4, 5], dtype=\"float32\")\n        verify_with_input(sorted_sequence, np.array([6], dtype=\"float32\"), right)\n        verify_with_input(sorted_sequence, np.array([0], dtype=\"float32\"), right)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_softmax.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for softmax\"\"\"\nimport logging\nimport os\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import te, topi\nfrom tvm.topi.utils import get_const_tuple\n\n\n_softmax_schedule = {\n    \"generic\": topi.generic.schedule_softmax,\n    \"cpu\": topi.x86.schedule_softmax,\n    \"gpu\": topi.cuda.schedule_softmax,\n    \"hls\": topi.hls.schedule_softmax,\n}\n\n\ndtype = tvm.testing.parameter(\"float32\", \"float64\")\n\n\nconfigs = {\n    \"softmax\": {\n        \"topi\": topi.nn.softmax,\n        \"ref\": tvm.topi.testing.softmax_python,\n        \"dimensions\": [1, 2, 4],\n        \"axis\": [0, 1, 2, 3],\n    },\n    \"log_softmax\": {\n        \"topi\": topi.nn.log_softmax,\n        \"ref\": tvm.topi.testing.log_softmax_python,\n        \"dimensions\": [2, 3],\n        \"axis\": [1],\n    },\n}\nshapes = [(32, 10), (3, 4), (1, 16, 256, 256), (32,)]\nsoftmax_operation, shape, axis = tvm.testing.parameters(\n    *[\n        (name, shape, axis)\n        for name, config in configs.items()\n        for shape in shapes\n        if len(shape) in config[\"dimensions\"]\n        for axis in range(len(shape))\n        if axis in config[\"axis\"]\n    ]\n)\n\n\n@tvm.testing.fixture(cache_return_value=True)\ndef ref_data(shape, dtype, softmax_operation, axis):\n    ref_func = configs[softmax_operation][\"ref\"]\n\n    a_np = np.random.uniform(size=shape).astype(dtype)\n    perm = list(range(a_np.ndim))\n    perm[-1], perm[axis] = perm[axis], perm[-1]\n    trans_shape = [a_np.shape[i] for i in perm]\n    a_np_2d = a_np.transpose(perm).reshape(-1, trans_shape[-1])\n    b_np_2d = ref_func(a_np_2d)\n    b_np = b_np_2d.reshape(*trans_shape).transpose(perm)\n\n    return a_np, b_np\n\n\ndef test_softmax(target, dev, shape, dtype, ref_data, softmax_operation, axis):\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\" and dtype == \"float64\":\n        # https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html\n        pytest.xfail(\"Vulkan GLSL.std.450 does not support 64-bit floats\")\n\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n\n    topi_op = configs[softmax_operation][\"topi\"]\n    B = topi_op(A, axis=axis)\n\n    with tvm.target.Target(target):\n        fschedule = tvm.topi.testing.dispatch(target, _softmax_schedule)\n        s = fschedule(B)\n\n    a_np, b_np = ref_data\n\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)\n    f = tvm.build(s, [A, B], target)\n    f(a, b)\n    tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_sort.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for vision package\"\"\"\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\n\n_sort_implement = {\n    \"generic\": (topi.sort, topi.generic.schedule_sort),\n    \"gpu\": (topi.cuda.sort, topi.cuda.schedule_sort),\n}\n\n_argsort_implement = {\n    \"generic\": (topi.argsort, topi.generic.schedule_argsort),\n    \"gpu\": (topi.cuda.argsort, topi.cuda.schedule_argsort),\n}\n\n_topk_implement = {\n    \"generic\": (topi.topk, topi.generic.schedule_topk),\n    \"gpu\": (topi.cuda.topk, topi.cuda.schedule_topk),\n}\n\naxis = tvm.testing.parameter(0, -1, 1)\nis_ascend = tvm.testing.parameter(True, False, ids=[\"is_ascend\", \"not_ascend\"])\ndtype = tvm.testing.parameter(\"int64\", \"float32\")\n\ntopk = tvm.testing.parameter(0, 1, 5)\ntopk_ret_type = tvm.testing.parameter(\"values\", \"indices\", \"both\")\n\n\ndef test_sort(target, dev, axis, is_ascend):\n    np.random.seed(0)\n\n    dshape = (20, 100)\n    data_dtype = \"float32\"\n    data = te.placeholder(dshape, name=\"data\", dtype=data_dtype)\n\n    perm = np.arange(dshape[0] * dshape[1], dtype=data_dtype)\n    np.random.shuffle(perm)\n    np_data = perm.reshape(dshape)\n\n    if is_ascend:\n        np_sort = np.sort(np_data, axis=axis)\n    else:\n        np_sort = -np.sort(-np_data, axis=axis)\n\n    if axis == 0:\n        np_sort = np_sort[: dshape[axis], :]\n    else:\n        np_sort = np_sort[:, : dshape[axis]]\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _sort_implement)\n        out = fcompute(data, axis=axis, is_ascend=is_ascend)\n        s = fschedule(out)\n\n    tvm_data = tvm.nd.array(np_data, dev)\n    tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data_dtype), dev)\n    f = tvm.build(s, [data, out], target)\n    f(tvm_data, tvm_out)\n    tvm.testing.assert_allclose(tvm_out.numpy(), np_sort, rtol=1e0)\n\n\ndef test_argsort(target, dev, axis, is_ascend):\n    dshape = (20, 100)\n    data_dtype = \"float32\"\n    data = te.placeholder(dshape, name=\"data\", dtype=data_dtype)\n\n    perm = np.arange(dshape[0] * dshape[1], dtype=data_dtype)\n    np.random.shuffle(perm)\n    np_data = perm.reshape(dshape)\n\n    if is_ascend:\n        np_indices = np.argsort(np_data, axis=axis)\n    else:\n        np_indices = np.argsort(-np_data, axis=axis)\n\n    if axis == 0:\n        np_indices = np_indices[: dshape[axis], :]\n    else:\n        np_indices = np_indices[:, : dshape[axis]]\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _argsort_implement)\n        out = fcompute(data, axis=axis, is_ascend=is_ascend)\n        s = fschedule(out)\n\n    tvm_data = tvm.nd.array(np_data, dev)\n    tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data_dtype), dev)\n    f = tvm.build(s, [data, out], target)\n    f(tvm_data, tvm_out)\n    tvm.testing.assert_allclose(tvm_out.numpy(), np_indices.astype(data_dtype), rtol=1e0)\n\n\ndef test_topk(target, dev, topk, axis, topk_ret_type, is_ascend, dtype):\n    np.random.seed(0)\n\n    shape = (20, 100)\n    data_dtype = \"float32\"\n    data = te.placeholder(shape, name=\"data\", dtype=data_dtype)\n\n    np_data = np.random.uniform(size=shape).astype(data_dtype)\n    if is_ascend:\n        np_indices = np.argsort(np_data, axis=axis)\n    else:\n        np_indices = np.argsort(-np_data, axis=axis)\n    kk = topk if topk >= 1 else shape[axis]\n    if axis == 0:\n        np_indices = np_indices[:kk, :]\n        np_values = np.zeros(np_indices.shape).astype(data_dtype)\n        for i in range(shape[1]):\n            np_values[:, i] = np_data[np_indices[:, i], i]\n    else:\n        np_indices = np_indices[:, :kk]\n        np_values = np.zeros(np_indices.shape).astype(data_dtype)\n        for i in range(shape[0]):\n            np_values[i, :] = np_data[i, np_indices[i, :]]\n    np_indices = np_indices.astype(dtype)\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _topk_implement)\n        outs = fcompute(data, topk, axis, topk_ret_type, is_ascend, dtype)\n        outs = outs if isinstance(outs, list) else [outs]\n        s = fschedule(outs)\n    tvm_data = tvm.nd.array(np_data, dev)\n    tvm_res = []\n    for t in outs:\n        tvm_res.append(tvm.nd.empty(t.shape, dtype=t.dtype, device=dev))\n    f = tvm.build(s, [data] + outs, target)\n    f(tvm_data, *tvm_res)\n    if topk_ret_type == \"both\":\n        tvm.testing.assert_allclose(tvm_res[0].numpy(), np_values)\n        tvm.testing.assert_allclose(tvm_res[1].numpy(), np_indices)\n    elif topk_ret_type == \"values\":\n        tvm.testing.assert_allclose(tvm_res[0].numpy(), np_values)\n    else:\n        tvm.testing.assert_allclose(tvm_res[0].numpy(), np_indices)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_space_to_batch_nd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for space to batch\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_space_to_batch_nd(input_shape, block_shape, pad_before, pad_after, pad_value=0):\n    out_shape = []\n    out_shape.append(int((input_shape[0] * np.prod(block_shape))))\n    for i in range(1, len(block_shape) + 1):\n        pad = pad_before[i - 1] + pad_after[i - 1]\n        out_shape.append(int((input_shape[i] + pad) // block_shape[i - 1]))\n    for i in range(len(block_shape) + 1, len(input_shape)):\n        out_shape.append(input_shape[i])\n\n    A = te.placeholder(input_shape, name=\"A\", dtype=\"float32\")\n    dtype = A.dtype\n    a_np = np.random.uniform(size=input_shape).astype(dtype)\n\n    B = topi.nn.space_to_batch_nd(A, block_shape, pad_before, pad_after, pad_value)\n\n    b_np = tvm.topi.testing.space_to_batch_nd_python(\n        a_np, block_shape, pad_before, pad_after, pad_value\n    )\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.create(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_space_to_batch():\n    # Without paddings\n    verify_space_to_batch_nd([3, 3, 2, 1], [3], [0], [0])\n    # With paddings\n    verify_space_to_batch_nd([3, 3, 2, 1], [3], [1], [2])\n    # Multiple spatial dims\n    verify_space_to_batch_nd([3, 3, 4, 5, 2], [3, 4, 2], [1, 0, 3], [2, 0, 0])\n    # No remaining dims\n    verify_space_to_batch_nd([3, 3, 4, 5, 2], [3, 4, 2, 2], [1, 4, 0, 0], [2, 0, 1, 0])\n\n\nif __name__ == \"__main__\":\n    test_space_to_batch()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_space_to_depth.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for space to depth\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef verify_space_to_depth(block_size, batch, in_channel, in_height, in_width, layout=\"NCHW\"):\n    out_channel = int(in_channel * (block_size * block_size))\n    out_height = int(in_height / block_size)\n    out_width = int(in_width / block_size)\n\n    if layout == \"NCHW\":\n        in_shape = [batch, in_channel, in_height, in_width]\n        out_shape = [batch, out_channel, out_height, out_width]\n    elif layout == \"NHWC\":\n        in_shape = [batch, in_height, in_width, in_channel]\n        out_shape = [batch, out_height, out_width, out_channel]\n    else:\n        raise NotImplementedError(\"Layout not supported {}\".format(layout))\n\n    A = te.placeholder(in_shape, name=\"A\", dtype=\"float32\")\n    dtype = A.dtype\n    a_np = np.random.uniform(size=in_shape).astype(dtype)\n\n    B = topi.nn.space_to_depth(A, block_size=block_size, layout=layout)\n    if layout == \"NHWC\":\n        a_np = np.transpose(a_np, axes=[0, 3, 1, 2])\n    b_np = tvm.topi.testing.space_to_depth_python(a_np, block_size)\n    if layout == \"NHWC\":\n        a_np = np.transpose(a_np, axes=[0, 2, 3, 1])\n        b_np = np.transpose(b_np, axes=[0, 2, 3, 1])\n\n    def check_device(device, dev):\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s = tvm.topi.testing.get_injective_schedule(device)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], device)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-3, atol=1e-3)\n\n    for device, dev in tvm.testing.enabled_targets():\n        check_device(device, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_space_to_depth():\n    for layout in [\"NCHW\", \"NHWC\"]:\n        # Simplest possible case\n        verify_space_to_depth(2, 1, 1, 2, 2, layout=layout)\n        # Average input size\n        verify_space_to_depth(2, 1, 32, 32, 32, layout=layout)\n        # Large block size\n        verify_space_to_depth(8, 1, 32, 64, 64, layout=layout)\n        # Large batch size\n        verify_space_to_depth(4, 8, 32, 32, 32, layout=layout)\n        # Large input size\n        verify_space_to_depth(4, 8, 32, 128, 128, layout=layout)\n\n\nif __name__ == \"__main__\":\n    test_space_to_depth()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_sparse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for sparse operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm import relay\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.contrib.sparse as tvmsp\nfrom collections import namedtuple\nimport time\nimport scipy.sparse as sp\nimport tvm.testing\n\n_sparse_dense_implement = {\n    \"generic\": (topi.nn.sparse_dense, topi.generic.schedule_sparse_dense),\n    \"cuda\": (topi.cuda.sparse_dense, topi.cuda.schedule_sparse_dense),\n    \"x86\": (topi.nn.sparse_dense, topi.x86.schedule_sparse_dense),\n}\n\n\ndef verify_dynamic_csrmv(batch, in_dim, out_dim, dtype, use_bias=True):\n    nr, nc, n = te.var(\"nr\"), te.var(\"nc\"), te.var(\"n\")\n    A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, dtype=dtype, name=\"A\")\n    B = te.placeholder((in_dim, 1), dtype=dtype, name=\"B\")\n    C = te.placeholder((nr,), dtype=dtype, name=\"C\")\n    D = topi.sparse.csrmv(A, B, C if use_bias else None)\n    s = te.create_schedule(D.op)\n    dtype = A.dtype\n\n    # get the test data\n    def get_ref_data():\n        a_np = np.random.uniform(size=(batch, in_dim), high=100).astype(dtype)\n        b_np = np.random.uniform(size=(in_dim, 1), high=100).astype(dtype)\n        c_np = np.random.uniform(size=(batch,), high=100).astype(dtype)\n        if use_bias:\n            d_np = np.dot(a_np, b_np) + c_np.reshape((batch, 1))\n        else:\n            d_np = np.dot(a_np, b_np)\n        return (a_np, b_np, c_np, d_np)\n\n    a_np, b_np, c_np, d_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        a = tvmsp.array(a_np, dev)\n        _nr, _nc, _n = a.shape[0], a.shape[1], a.data.shape[0]\n        assert a.shape[0] == a.indptr.shape[0] - 1\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(c_np, dev)\n        d = tvm.nd.array(np.zeros((_nr, 1), dtype=dtype), dev)\n        assert a.data.dtype == A.data.dtype\n        assert a.indices.dtype == A.indices.dtype\n        assert a.indptr.dtype == A.indptr.dtype\n        f = tvm.build(s, [nr, A.data, A.indices, A.indptr, B, C, D], device, name=\"csrmv\")\n        f(_nr, a.data, a.indices, a.indptr, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), d_np, rtol=1e-4, atol=1e-4)\n\n    for device in [\"llvm\"]:\n        check_device(device)\n\n\ndef verify_dynamic_csrmm(batch, in_dim, out_dim, dtype, use_bias=True):\n    nr, nc, n = te.var(\"nr\"), te.var(\"nc\"), te.var(\"n\")\n    A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, dtype=dtype, name=\"A\")\n    B = te.placeholder((in_dim, out_dim), dtype=dtype, name=\"B\")\n    C = te.placeholder((nr,), dtype=dtype, name=\"C\")\n    D = topi.sparse.csrmm(A, B, C if use_bias else None)\n    s = te.create_schedule(D.op)\n    dtype = A.dtype\n\n    # get the test data\n    def get_ref_data():\n        a_np = np.random.uniform(size=(batch, in_dim), high=100).astype(dtype)\n        b_np = np.random.uniform(size=(in_dim, out_dim), high=100).astype(dtype)\n        c_np = np.random.uniform(size=(batch,), high=100).astype(dtype)\n        if use_bias:\n            d_np = np.dot(a_np, b_np) + c_np.reshape((batch, 1))\n        else:\n            d_np = np.dot(a_np, b_np)\n        return (a_np, b_np, c_np, d_np)\n\n    a_np, b_np, c_np, d_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        a = tvmsp.array(a_np, dev)\n        _nr, _nc, _n = a.shape[0], a.shape[1], a.data.shape[0]\n        assert a.shape[0] == a.indptr.shape[0] - 1\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(c_np, dev)\n        d = tvm.nd.array(np.zeros((_nr, out_dim), dtype=dtype), dev)\n        f = tvm.build(s, [nr, A.data, A.indices, A.indptr, B, C, D], device, name=\"csrmm\")\n\n        f(_nr, a.data, a.indices, a.indptr, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), d_np, rtol=1e-2, atol=1e-2)\n\n    for device in [\"llvm\"]:\n        check_device(device)\n\n\ndef verify_dense_si(batch, in_dim, out_dim, use_bias=True, dtype=\"float32\"):\n    nonzeros = te.var(\"nonzeros\")\n    A = tvmsp.placeholder(shape=(batch, in_dim), nonzeros=nonzeros, dtype=dtype, name=\"A\")\n    B = te.placeholder((out_dim, in_dim), dtype=dtype, name=\"B\")\n    C = te.placeholder((out_dim,), dtype=dtype, name=\"C\")\n    D = topi.sparse.dense(A, B, C if use_bias else None)\n    s = te.create_schedule(D.op)\n\n    # get the test data\n    def get_ref_data():\n        mag = 10.0\n        a_np = np.maximum(\n            mag * (np.random.uniform(size=(batch, in_dim)).astype(\"float32\") - 0.5), 0.0\n        ).astype(dtype)\n        b_np = (mag * (np.random.uniform(size=(out_dim, in_dim)).astype(\"float32\") - 0.5)).astype(\n            dtype\n        )\n        c_np = (mag * (np.random.uniform(size=(out_dim,)).astype(\"float32\") - 0.5)).astype(dtype)\n        if use_bias:\n            d_np = np.dot(a_np, b_np.T) + c_np\n        else:\n            d_np = np.dot(a_np, b_np.T)\n        return (a_np, b_np, c_np, d_np)\n\n    a_np, b_np, c_np, d_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        a = tvmsp.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(c_np, dev)\n        d = tvm.nd.array(np.zeros(get_const_tuple(D.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A.data, A.indices, A.indptr, B, C, D], device, name=\"dense\")\n        f(a.data, a.indices, a.indptr, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), d_np, rtol=1e-4, atol=1e-4)\n\n    check_device(\"llvm\")\n\n\ndef verify_dense_sw(batch, in_dim, out_dim, use_bias=True, dtype=\"float32\"):\n    nonzeros = te.var(\"nonzeros\")\n    A = te.placeholder((batch, in_dim), dtype=dtype, name=\"A\")\n    B = tvmsp.placeholder(shape=(out_dim, in_dim), nonzeros=nonzeros, dtype=dtype, name=\"B\")\n    C = te.placeholder((out_dim,), dtype=dtype, name=\"C\")\n    D = topi.sparse.dense(A, B, C if use_bias else None)\n    s = te.create_schedule(D.op)\n\n    # get the test data\n    def get_ref_data():\n        mag = 10.0\n        a_np = (mag * (np.random.uniform(size=(batch, in_dim)).astype(\"float32\") - 0.5)).astype(\n            dtype\n        )\n        b_np = np.maximum(\n            mag * (np.random.uniform(size=(out_dim, in_dim)).astype(\"float32\") - 0.5), 0.0\n        ).astype(dtype)\n        c_np = (mag * (np.random.uniform(size=(out_dim,)).astype(\"float32\") - 0.5)).astype(dtype)\n        if use_bias:\n            d_np = np.dot(a_np, b_np.T) + c_np\n        else:\n            d_np = np.dot(a_np, b_np.T)\n        return (a_np, b_np, c_np, d_np)\n\n    a_np, b_np, c_np, d_np = get_ref_data()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        a = tvm.nd.array(a_np, dev)\n        b = tvmsp.array(b_np, dev)\n        c = tvm.nd.array(c_np, dev)\n        d = tvm.nd.array(np.zeros(get_const_tuple(D.shape), dtype=dtype), dev)\n        f = tvm.build(s, [A, B.data, B.indices, B.indptr, C, D], device, name=\"dense\")\n        f(a, b.data, b.indices, b.indptr, c, d)\n        tvm.testing.assert_allclose(d.numpy(), d_np, rtol=1e-4, atol=1e-4)\n\n    check_device(\"llvm\")\n\n\ndef test_csrmv():\n    verify_dynamic_csrmv(batch=5, in_dim=7, out_dim=1, dtype=\"float32\", use_bias=False)\n    verify_dynamic_csrmv(batch=5, in_dim=7, out_dim=1, dtype=\"float64\", use_bias=True)\n    verify_dynamic_csrmv(batch=5, in_dim=7, out_dim=1, dtype=\"int32\", use_bias=True)\n\n\ndef test_csrmm():\n    M, K, N = 5, 7, 2\n    verify_dynamic_csrmm(batch=M, in_dim=K, out_dim=N, dtype=\"int64\", use_bias=False)\n    verify_dynamic_csrmm(batch=M, in_dim=K, out_dim=N, dtype=\"float64\", use_bias=True)\n\n\ndef test_dense_si():\n    M, K, N = 3, 5, 2\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"float32\")\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"float32\")\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"int32\")\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"int32\")\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"int16\")\n    verify_dense_si(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"int16\")\n\n\ndef test_dense_sw():\n    M, K, N = 3, 5, 2\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"float32\")\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"float32\")\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"int32\")\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"int32\")\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=False, dtype=\"int16\")\n    verify_dense_sw(batch=M, in_dim=K, out_dim=N, use_bias=True, dtype=\"int16\")\n\n\ndef test_dense():\n    test_dense_si()\n    test_dense_sw()\n\n\ndef test_sparse_dense_csr():\n    M, N, K, density = 1, 17, 47, 0.2\n    X_np = np.random.randn(M, K).astype(\"float32\")\n    W_sp_np = sp.random(N, K, density=density, format=\"csr\", dtype=\"float32\")\n    W_np = W_sp_np.todense()\n    Y_np = X_np.dot(W_np.T)\n\n    W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n    W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n    W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n    Y = topi.nn.sparse_dense(X, W_data, W_indices, W_indptr)\n    s = te.create_schedule(Y.op)\n    func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n    Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype))\n    func(\n        tvm.nd.array(X_np),\n        tvm.nd.array(W_sp_np.data),\n        tvm.nd.array(W_sp_np.indices),\n        tvm.nd.array(W_sp_np.indptr),\n        Y_tvm,\n    )\n    tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-4, rtol=1e-4)\n\n\ndef test_sparse_dense_csr_reverse():\n    M, N, K, density = 1, 17, 47, 0.2\n    X_np = np.random.randn(M, K).astype(\"float32\")\n    W_sp_np = sp.random(N, K, density=density, format=\"csr\", dtype=\"float32\")\n    W_np = W_sp_np.todense()\n    Y_np = W_np.dot(X_np.T)\n\n    W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n    W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n    W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n    Y = topi.nn.sparse_dense(X, W_data, W_indices, W_indptr, sparse_lhs=True)\n    s = te.create_schedule(Y.op)\n    func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n    Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype))\n    func(\n        tvm.nd.array(X_np),\n        tvm.nd.array(W_sp_np.data),\n        tvm.nd.array(W_sp_np.indices),\n        tvm.nd.array(W_sp_np.indptr),\n        Y_tvm,\n    )\n    tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-4, rtol=1e-4)\n\n\ndef test_sparse_transpose_csr():\n    N, density = 1023, 0.3\n\n    X_sp = sp.random(N, N, density=density, format=\"csr\", dtype=\"float32\")\n\n    X_sp_T = X_sp.transpose()\n    X_np_T = X_sp_T.todense()\n\n    X_data = te.placeholder(shape=X_sp.data.shape, dtype=str(X_sp.data.dtype))\n    X_indices = te.placeholder(shape=X_sp.indices.shape, dtype=str(X_sp.indices.dtype))\n    X_indptr = te.placeholder(shape=X_sp.indptr.shape, dtype=str(X_sp.indptr.dtype))\n\n    X_T_data, X_T_indices, X_T_indptr = topi.nn.sparse_transpose(X_data, X_indices, X_indptr)\n    s = te.create_schedule([X_T_data.op, X_T_indices.op, X_T_indptr.op])\n    func = tvm.build(s, [X_data, X_indices, X_indptr, X_T_data, X_T_indices, X_T_indptr])\n\n    X_T_data_tvm = tvm.nd.array(np.zeros(X_sp_T.data.shape, dtype=X_sp_T.data.dtype))\n    X_T_indices_tvm = tvm.nd.array(np.zeros(X_sp_T.indices.shape, dtype=X_sp_T.indices.dtype))\n    X_T_indptr_tvm = tvm.nd.array(np.zeros(X_sp_T.indptr.shape, dtype=X_sp_T.indptr.dtype))\n\n    func(\n        tvm.nd.array(X_sp.data),\n        tvm.nd.array(X_sp.indices),\n        tvm.nd.array(X_sp.indptr),\n        X_T_data_tvm,\n        X_T_indices_tvm,\n        X_T_indptr_tvm,\n    )\n\n    X_T_out = sp.csr_matrix(\n        (X_T_data_tvm.numpy(), X_T_indices_tvm.numpy(), X_T_indptr_tvm.numpy()), shape=(N, N)\n    ).todense()\n    tvm.testing.assert_allclose(X_np_T, X_T_out, atol=1e-4, rtol=1e-4)\n\n\ndef random_bsr_matrix(M, N, BS_R, BS_C, density, dtype):\n    import itertools\n\n    Y = np.zeros((M, N), dtype=dtype)\n    assert M % BS_R == 0\n    assert N % BS_C == 0\n    nnz = int(density * M * N)\n    num_blocks = int(nnz / (BS_R * BS_C)) + 1\n    candidate_blocks = np.asarray(list(itertools.product(range(0, M, BS_R), range(0, N, BS_C))))\n    assert candidate_blocks.shape[0] == M // BS_R * N // BS_C\n    chosen_blocks = candidate_blocks[\n        np.random.choice(candidate_blocks.shape[0], size=num_blocks, replace=False)\n    ]\n    for i in range(len(chosen_blocks)):\n        r, c = chosen_blocks[i]\n        Y[r : r + BS_R, c : c + BS_C] = np.random.randn(BS_R, BS_C)\n    s = sp.bsr_matrix(Y, blocksize=(BS_R, BS_C))\n    assert s.data.shape == (num_blocks, BS_R, BS_C)\n    assert s.indices.shape == (num_blocks,)\n    assert s.indptr.shape == (M // BS_R + 1,)\n    return s\n\n\ndef verify_sparse_dense_bsr(M, N, K, BS_R, BS_C, density, use_relu, device, target):\n    X_np = np.random.randn(M, K).astype(\"float32\")\n    W_sp_np = random_bsr_matrix(N, K, BS_R, BS_C, density=density, dtype=\"float32\")\n    W_np = W_sp_np.todense()\n    Y_np = X_np @ W_np.T\n    if use_relu:\n        Y_np = np.maximum(Y_np, 0.0)\n\n    W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n    W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n    W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, _sparse_dense_implement)\n    with tvm.target.Target(target):\n        Y = fcompute(X, W_data, W_indices, W_indptr)\n        if use_relu:\n            Y = topi.nn.relu(Y)\n        s = fschedule([Y])\n        func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n        Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype), device=device)\n        func(\n            tvm.nd.array(X_np, device=device),\n            tvm.nd.array(W_sp_np.data, device=device),\n            tvm.nd.array(W_sp_np.indices, device=device),\n            tvm.nd.array(W_sp_np.indptr, device=device),\n            Y_tvm,\n        )\n        tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"cuda\")\ndef test_sparse_dense_bsr_relu(dev, target):\n    M, N, K, BS_R, BS_C, density = 1, 64, 128, 8, 16, 0.9\n    verify_sparse_dense_bsr(M, N, K, BS_R, BS_C, density, True, dev, target)\n    verify_sparse_dense_bsr(M, N, K, BS_R, BS_C, density, False, dev, target)\n\n\ndef test_sparse_dense_bsr_reverse():\n    M, N, K, BS_R, BS_C, density = 1, 64, 128, 8, 16, 0.9\n    X_np = np.random.randn(M, K).astype(\"float32\")\n    W_sp_np = random_bsr_matrix(N, K, BS_R, BS_C, density=density, dtype=\"float32\")\n    W_np = W_sp_np.todense()\n    Y_np = W_np.dot(X_np.T)\n\n    W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n    W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n    W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n    Y = topi.nn.sparse_dense(X, W_data, W_indices, W_indptr, sparse_lhs=True)\n    s = te.create_schedule(Y.op)\n    func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n    Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype))\n    func(\n        tvm.nd.array(X_np),\n        tvm.nd.array(W_sp_np.data),\n        tvm.nd.array(W_sp_np.indices),\n        tvm.nd.array(W_sp_np.indptr),\n        Y_tvm,\n    )\n    tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-4, rtol=1e-4)\n\n\n@tvm.testing.uses_gpu\ndef test_sparse_dense_bsr_randomized():\n    for _ in range(20):\n        BS_R = np.random.randint(1, 16)\n        BS_C = np.random.randint(1, 16)\n        M = np.random.randint(1, 32)\n        N = int(np.random.randint(1, 16) * BS_R)\n        K = int(np.random.randint(1, 16) * BS_C)\n        density = np.clip(np.random.random(), 0.1, 0.9)\n        X_np = np.random.randn(M, K).astype(\"float32\")\n        W_sp_np = random_bsr_matrix(N, K, BS_R, BS_C, density=density, dtype=\"float32\")\n\n        W_np = W_sp_np.todense()\n        Y_np = np.array(X_np.dot(W_np.T))\n\n        W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n        W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n        W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n        X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n\n        def check_device(device):\n            dev = tvm.device(device, 0)\n            if not tvm.testing.device_enabled(device):\n                print(\"Skip because %s is not enabled\" % device)\n                return\n            print(\"Running on target: %s\" % device)\n            fcompute, fschedule = tvm.topi.testing.dispatch(device, _sparse_dense_implement)\n            with tvm.target.Target(device):\n                Y = fcompute(X, W_data, W_indices, W_indptr)\n                s = fschedule([Y])\n                func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n                Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype), device=dev)\n                func(\n                    tvm.nd.array(X_np, device=dev),\n                    tvm.nd.array(W_sp_np.data, device=dev),\n                    tvm.nd.array(W_sp_np.indices, device=dev),\n                    tvm.nd.array(W_sp_np.indptr, device=dev),\n                    Y_tvm,\n                )\n                tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-5, rtol=1e-5)\n\n        for device in [\"llvm\", \"cuda\"]:\n            check_device(device)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_sparse_dense_padded_gpu(target, dev):\n    M = 128\n    N = 1280\n    K = 128\n    X_np = np.random.randn(M, K).astype(\"float32\")\n    W_sp_np = random_bsr_matrix(N, K, 1, 1, density=0.01, dtype=\"float32\")\n    W_sp_np_padded = tvm.topi.cuda.pad_sparse_matrix(W_sp_np, 32)\n\n    W_np = W_sp_np.todense()\n    Y_np = X_np @ W_sp_np.T\n\n    W_data = te.placeholder(shape=W_sp_np_padded.data.shape, dtype=str(W_sp_np_padded.data.dtype))\n    W_indices = te.placeholder(\n        shape=W_sp_np_padded.indices.shape, dtype=str(W_sp_np_padded.indices.dtype)\n    )\n    W_indptr = te.placeholder(\n        shape=W_sp_np_padded.indptr.shape, dtype=str(W_sp_np_padded.indptr.dtype)\n    )\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n    with tvm.target.Target(target):\n        Y = topi.cuda.sparse_dense_padded(X, W_data, W_indices, W_indptr)\n        s = topi.cuda.schedule_sparse_dense_padded([Y])\n        func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n        Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=Y_np.dtype), device=dev)\n        func(\n            tvm.nd.array(X_np, device=dev),\n            tvm.nd.array(W_sp_np_padded.data, device=dev),\n            tvm.nd.array(W_sp_np_padded.indices, device=dev),\n            tvm.nd.array(W_sp_np_padded.indptr, device=dev),\n            Y_tvm,\n        )\n        tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np, atol=1e-5, rtol=1e-5)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_sparse_dense_padded_alter_op(target, dev):\n    with tvm.target.Target(target):\n        M = 128\n        N = 16\n        K = 128\n        X_np = np.random.randn(M, K).astype(\"float32\")\n        W_sp_np = random_bsr_matrix(N, K, 2, 2, density=0.01, dtype=\"float32\")\n        x = relay.var(\"x\", relay.TensorType(X_np.shape, \"float32\"))\n        mult = relay.op.nn.sparse_dense(\n            x,\n            (\n                relay.Constant(tvm.nd.array(W_sp_np.data)),\n                relay.Constant(tvm.nd.array(W_sp_np.indices)),\n                relay.Constant(tvm.nd.array(W_sp_np.indptr)),\n            ),\n        )\n        f = relay.Function([x], mult)\n        f_ = relay.transform.InferType()(tvm.IRModule.from_expr(f))\n        f_ = relay.transform.AlterOpLayout()(f_)\n        assert f_[\"main\"].body.op.name == \"nn.internal.sparse_dense_padded\"\n\n        # build with cuda and AlterOpLayout to ensure that sparse_dense_padded is in action\n        with tvm.transform.PassContext(opt_level=3, required_pass=\"AlterOpLayout\"):\n            x = relay.build(tvm.IRModule.from_expr(f), target=target)\n\n\ndef test_sparse_add_csr():\n    for indices_dtype in [\"int32\", \"int64\"]:\n        for data_dtype in [\"float32\", \"float64\"]:\n            M, K, density = 3, 49, 0.2\n            X_np = np.random.randn(M, K).astype(data_dtype)\n            Y_sp_np = sp.random(M, K, density=density, format=\"csr\", dtype=data_dtype)\n            Y_np = Y_sp_np.todense()\n            Z_np = X_np + Y_np\n\n            Y_data = te.placeholder(shape=Y_sp_np.data.shape, dtype=data_dtype)\n            Y_indices = te.placeholder(shape=Y_sp_np.indices.shape, dtype=indices_dtype)\n            Y_indptr = te.placeholder(shape=Y_sp_np.indptr.shape, dtype=indices_dtype)\n            X = te.placeholder(shape=X_np.shape, dtype=data_dtype)\n            Z = topi.nn.sparse_add(X, Y_data, Y_indices, Y_indptr)\n            s = te.create_schedule(Z.op)\n            func = tvm.build(s, [X, Y_data, Y_indices, Y_indptr, Z])\n            Z_tvm = tvm.nd.array(np.zeros(Z_np.shape, dtype=Z_np.dtype))\n            func(\n                tvm.nd.array(X_np.astype(data_dtype)),\n                tvm.nd.array(Y_sp_np.data.astype(data_dtype)),\n                tvm.nd.array(Y_sp_np.indices.astype(indices_dtype)),\n                tvm.nd.array(Y_sp_np.indptr.astype(indices_dtype)),\n                Z_tvm,\n            )\n            tvm.testing.assert_allclose(Z_tvm.numpy(), Z_np, atol=1e-4, rtol=1e-4)\n\n\ndef verify_sparse_conv2d_bsr(M, H, W, N, K, BS_R, BS_C, density, layout):\n    if layout == \"NHWC\":\n        X_np = np.random.randn(M, H, W, K).astype(\"float32\")\n    elif layout == \"NCHW\":\n        X_np = np.random.randn(M, K, H, W).astype(\"float32\")\n    W_sp_np = random_bsr_matrix(N, K, BS_R, BS_C, density=density, dtype=\"float32\")\n    W_np = W_sp_np.todense()\n    if layout == \"NHWC\":\n        Y_np = tvm.topi.testing.conv2d_nhwc_python(X_np, np.array(W_np).T.reshape(1, 1, K, N), 1, 0)\n    elif layout == \"NCHW\":\n        Y_np = tvm.topi.testing.conv2d_nchw_python(X_np, np.array(W_np).reshape(N, K, 1, 1), 1, 0)\n\n    if BS_C == 1:\n        W_data = te.placeholder(shape=W_sp_np.data.shape[:-1], dtype=str(W_sp_np.data.dtype))\n        W_sp_np_data = W_sp_np.data.reshape(W_sp_np.data.shape[0], BS_R)\n    else:\n        W_data = te.placeholder(shape=W_sp_np.data.shape, dtype=str(W_sp_np.data.dtype))\n        W_sp_np_data = W_sp_np.data\n    W_indices = te.placeholder(shape=W_sp_np.indices.shape, dtype=str(W_sp_np.indices.dtype))\n    W_indptr = te.placeholder(shape=W_sp_np.indptr.shape, dtype=str(W_sp_np.indptr.dtype))\n    X = te.placeholder(shape=X_np.shape, dtype=str(X_np.dtype))\n\n    Y = topi.nn.sparse_conv2d(X, W_data, W_indices, W_indptr, layout)\n    s = te.create_schedule(Y.op)\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n\n        func = tvm.build(s, [X, W_data, W_indices, W_indptr, Y])\n        Y_tvm = tvm.nd.array(np.zeros(Y_np.shape, dtype=\"float32\"))\n        func(\n            tvm.nd.array(X_np, dev),\n            tvm.nd.array(W_sp_np_data, dev),\n            tvm.nd.array(W_sp_np.indices, dev),\n            tvm.nd.array(W_sp_np.indptr, dev),\n            Y_tvm,\n        )\n        tvm.testing.assert_allclose(Y_tvm.numpy(), Y_np.astype(\"float32\"), atol=1e-4, rtol=1e-4)\n\n    check_device(\"llvm\")\n\n\ndef test_sparse_conv2d_bsr():\n    M, H, W, N, K, BS_R, BS_C, density = 1, 32, 32, 128, 64, 8, 16, 0.9\n    verify_sparse_conv2d_bsr(M, H, W, N, K, BS_R, BS_C, density, \"NHWC\")\n    verify_sparse_conv2d_bsr(M, H, W, N, K, BS_R, BS_C, density, \"NCHW\")\n    verify_sparse_conv2d_bsr(M, H, W, N, K, BS_R, 1, density, \"NHWC\")\n\n\nif __name__ == \"__main__\":\n    # test_csrmv()\n    # test_csrmm()\n    # test_dense()\n    # test_sparse_dense_csr()\n    # test_sparse_dense_bsr_randomized()\n    # test_sparse_transpose_csr()\n    # test_sparse_dense_padded_cuda()\n    # test_sparse_dense_padded_alter_op()\n    # test_sparse_dense_csr_reverse()\n    # test_sparse_dense_bsr_reverse()\n    # test_sparse_add_csr()\n    test_sparse_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for tensor operator\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm.contrib.nvcc import have_fp16\nimport tvm.testing\n\n\ndef verify_elemwise_sum(num_args, dtype):\n    shape = (3, 5, 4)\n\n    tvm_placeholders = []\n    for i in range(num_args):\n        tvm_placeholders.append(te.placeholder(shape, name=\"data\" + str(i), dtype=dtype))\n    esum = topi.elemwise_sum(tvm_placeholders)\n    s = te.create_schedule([esum.op])\n\n    @memoize(\"topi.tests.test_topi_elemwise_sum\")\n    def get_ref_data():\n        np_nd = [np.random.uniform(0, 10, size=shape).astype(dtype) for i in range(num_args)]\n        return np_nd\n\n    np_nd = get_ref_data()\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n\n        dev = tvm.device(target, 0)\n        out = tvm.nd.array(np.zeros(shape, dtype=dtype), dev)\n        f = tvm.build(s, tvm_placeholders + [esum], target, name=\"elemwise_sum\")\n        tvm_nd = [tvm.nd.array(nd, dev) for nd in np_nd] + [out]\n        f(*tvm_nd)\n        np_out = np.sum(np.array(np_nd), axis=0)\n        tvm.testing.assert_allclose(out.numpy(), np_out, rtol=1e-5)\n\n    for target in [\"llvm\"]:\n        check_target(target)\n\n\ndef verify_full(shape, dtype, fill_value):\n    A = te.placeholder(shape, dtype=dtype, name=\"A\")\n    B = topi.full_like(A, fill_value=fill_value)\n    C = topi.full(shape=shape, dtype=dtype, fill_value=fill_value)\n    s1 = te.create_schedule([B.op])\n    s2 = te.create_schedule([C.op])\n\n    @memoize(\"topi.tests.test_topi_full\")\n    def get_ref_data():\n        return np.full(shape, fill_value, dtype)\n\n    np_nd = get_ref_data()\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n\n        dev = tvm.device(target, 0)\n        out = tvm.nd.array(np.zeros(shape, dtype=dtype), dev)\n        f = tvm.build(s1, [A, B], target, name=\"full_like\")\n        f(tvm.nd.array(np.zeros(shape, dtype), dev), out)\n        tvm.testing.assert_allclose(out.numpy(), np_nd, rtol=1e-5)\n\n        f = tvm.build(s2, [C], target, name=\"full\")\n        f(out)\n        tvm.testing.assert_allclose(out.numpy(), np_nd, rtol=1e-5)\n\n    for target in [\"llvm\"]:\n        check_target(target)\n\n\ndef verify_vectorization(n, m, dtype):\n    def check_targeta(targeta):\n        if not tvm.testing.device_enabled(targeta):\n            print(\"Skip because %s is not enabled\" % targeta)\n            return\n        if dtype == \"float16\" and targeta == \"cuda\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n        with tvm.target.Target(targeta):\n            dev = tvm.device(targeta, 0)\n            A = te.placeholder((n, m), name=\"A\", dtype=dtype)\n            B = te.compute((n, m), lambda i, j: A[i, j] + tvm.tir.const(1, A.dtype), name=\"B\")\n            S = tvm.topi.testing.get_elemwise_schedule(targeta)(B)\n\n            fun = tvm.build(S, [A, B], targeta)\n            np_A = tvm.nd.empty((n, m), A.dtype, dev).copyfrom(np.random.uniform(size=(n, m)))\n            np_B = tvm.nd.empty((n, m), B.dtype, dev)\n            fun(np_A, np_B)\n            tvm.testing.assert_allclose(np_B.numpy(), np_A.numpy() + 1, rtol=1e-5)\n\n    for targeta in [\"cuda\"]:\n        check_targeta(targeta)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorization():\n    verify_vectorization(128, 64, \"float16\")\n\n\ndef test_elemwise_sum():\n    verify_elemwise_sum(1, \"float32\")\n    verify_elemwise_sum(5, \"float32\")\n    verify_elemwise_sum(4, \"int32\")\n\n\ndef test_full():\n    verify_full((3, 4, 5), \"float32\", 3.14)\n    verify_full((10,), \"int32\", 7)\n\n\nif __name__ == \"__main__\":\n    test_elemwise_sum()\n    test_full()\n    test_vectorization()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for broadcasting operators.\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nfrom tvm import relay\nimport tvm.topi.testing\nfrom tvm.contrib.nvcc import have_fp16\n\nimport tvm.testing\n\n\ndef verify_expand_dims(in_shape, out_shape, axis, num_newaxis):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.expand_dims(A, axis, num_newaxis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"expand_dims\")\n        data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = data_npy.reshape(out_shape)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), dev)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_reinterpret(in_shape, in_dtype, out_dtype, generator):\n    A = te.placeholder(shape=in_shape, name=\"A\", dtype=in_dtype)\n    B = topi.reinterpret(A, out_dtype)\n\n    def check_device(target, dev):\n        if in_dtype == \"float16\" and target == \"cuda\" and not have_fp16(dev.compute_version):\n            print(\"Skip because %s does not have fp16 support\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_elemwise_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"reinterpret\")\n        data_npy = generator(in_shape).astype(in_dtype)\n        out_npy = data_npy.view(B.dtype)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.array(np.empty(in_shape).astype(B.dtype), dev)\n        foo(data_nd, out_nd)\n        np.testing.assert_equal(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_transpose(in_shape, axes):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.transpose(A, axes)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"transpose\")\n        data_npy = np.arange(np.prod(in_shape)).reshape(in_shape).astype(A.dtype)\n        out_npy = data_npy.transpose(axes)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=B.dtype)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_reshape(src_shape, dst_shape):\n    A = te.placeholder(shape=src_shape, name=\"A\")\n    B = topi.reshape(A, dst_shape)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"reshape\")\n        data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n        out_npy = np.reshape(data_npy, newshape=dst_shape)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.empty(dst_shape, device=dev, dtype=B.dtype)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_squeeze(src_shape, axis):\n    A = te.placeholder(shape=src_shape, name=\"A\")\n    B = topi.squeeze(A, axis=axis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        foo = tvm.build(s, [A, B], target, name=\"squeeze\")\n        data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n        out_npy = np.squeeze(data_npy, axis=axis)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd_shape = out_npy.shape\n        out_nd = tvm.nd.empty(out_nd_shape, device=dev, dtype=B.dtype)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_concatenate(shapes, axis):\n    def get_concat_schedule(target):\n        schedule_map = {\n            \"cpu\": topi.x86.schedule_concatenate,\n            \"arm_cpu\": topi.arm_cpu.schedule_concatenate,\n        }\n        if isinstance(target, str):\n            target = tvm.target.Target(target)\n        for key in target.keys:\n            if key in schedule_map:\n                return schedule_map[key]\n        return tvm.topi.testing.get_injective_schedule(target)\n\n    tensor_l = []\n    for i, shape in enumerate(shapes):\n        tensor_l.append(te.placeholder(shape, name=\"A\" + str(i)))\n    out_tensor = topi.concatenate(a_tuple=tensor_l, axis=axis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = get_concat_schedule(target)(out_tensor)\n\n        foo = tvm.build(s, tensor_l + [out_tensor], target, name=\"concatenate\")\n        data_npys = [np.random.normal(size=shape).astype(tensor_l[0].dtype) for shape in shapes]\n        out_npy = np.concatenate(data_npys, axis=axis)\n        data_nds = [tvm.nd.array(data_npy, dev) for data_npy in data_npys]\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=out_tensor.dtype)\n        foo(*(data_nds + [out_nd]))\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_stack(shapes, axis):\n    tensor_l = []\n    for i, shape in enumerate(shapes):\n        tensor_l.append(te.placeholder(shape, name=\"A\" + str(i)))\n    out_tensor = topi.stack(tensor_l, axis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(out_tensor)\n\n        foo = tvm.build(s, tensor_l + [out_tensor], target, name=\"stack\")\n        data_npys = [np.random.normal(size=shape).astype(tensor_l[0].dtype) for shape in shapes]\n        out_npy = np.stack(data_npys, axis=axis)\n        data_nds = [tvm.nd.array(data_npy, dev) for data_npy in data_npys]\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=out_tensor.dtype)\n        foo(*(data_nds + [out_nd]))\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_split(src_shape, indices_or_sections, axis):\n    A = te.placeholder(shape=src_shape, name=\"A\")\n    tensor_l = topi.split(A, indices_or_sections, axis=axis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(tensor_l)\n\n        foo = tvm.build(s, [A] + list(tensor_l), target, name=\"split\")\n        data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n        out_npys = np.split(data_npy, indices_or_sections, axis=axis)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nds = [\n            tvm.nd.empty(out_npy.shape, device=dev, dtype=tensor_l[0].dtype) for out_npy in out_npys\n        ]\n        foo(*([data_nd] + out_nds))\n        for out_nd, out_npy in zip(out_nds, out_npys):\n            tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_expand_like(in_shape, out_shape, axis):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = te.placeholder(shape=out_shape, name=\"B\")\n    C = topi.expand_like(A, B, axis)\n    s = te.create_schedule([C.op])\n\n    def check_device(target):\n        print(\"Running on target: %s\" % target)\n\n        dev = tvm.device(target, 0)\n        f = tvm.build(s, [A, B, C], target, name=\"expand_like\")\n        input = np.random.uniform(size=in_shape).astype(A.dtype)\n        tvm_input = tvm.nd.array(input, dev)\n\n        odim = len(out_shape)\n        real_axis = [x if x >= 0 else x + odim for x in axis]\n        real_axis = sorted(real_axis)\n        for x in real_axis:\n            input = np.expand_dims(input, x).astype(A.dtype)\n        for x in real_axis:\n            input = np.concatenate([input] * out_shape[x], axis=x).astype(A.dtype)\n        assert input.shape == out_shape\n\n        tvm_shape_like = tvm.nd.array(np.zeros(out_shape).astype(B.dtype), dev)\n        out = tvm.nd.array(np.zeros(out_shape).astype(A.dtype), dev)\n        f(tvm_input, tvm_shape_like, out)\n        tvm.testing.assert_allclose(out.numpy(), input)\n\n    for target in [\"llvm\"]:\n        check_device(target)\n\n\ndef verify_flip(in_shape, axis):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.flip(A, axis) + 1\n\n    def check_device(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        foo = tvm.build(s, [A, B], target, name=\"reverse\")\n        x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = np.flip(x_np, axis) + 1\n        data_nd = tvm.nd.array(x_np, dev)\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=A.dtype)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target in [\"llvm\", \"cuda\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n        check_device(target)\n\n\n@tvm.testing.uses_gpu\ndef test_reverse_sequence():\n    def verify_reverse_sequence(in_data, seq_lengths, batch_axis, seq_axis, ref_res):\n        seq_lengths = np.array(seq_lengths).astype(\"int32\")\n        A = te.placeholder(shape=in_data.shape, name=\"A\", dtype=str(in_data.dtype))\n        B = te.placeholder(shape=seq_lengths.shape, name=\"B\", dtype=str(seq_lengths.dtype))\n        C = topi.reverse_sequence(A, B, seq_axis, batch_axis)\n\n        def check_device(target, dev):\n            print(\"Running on target: %s\" % target)\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_injective_schedule(target)(C)\n\n            foo = tvm.build(s, [A, B, C], target, name=\"reverse_sequence\")\n\n            data_nd = tvm.nd.array(in_data, dev)\n            seq_lengths_nd = tvm.nd.array(seq_lengths, dev)\n            out_nd = tvm.nd.empty(in_data.shape, device=dev, dtype=A.dtype)\n            foo(data_nd, seq_lengths_nd, out_nd)\n            tvm.testing.assert_allclose(out_nd.numpy(), ref_res)\n\n        for target, dev in tvm.testing.enabled_targets():\n            check_device(target, dev)\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 5, 10, 15], [4, 1, 6, 11], [8, 9, 2, 7], [12, 13, 14, 3]]\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 1, 0, np.array(result))\n    verify_reverse_sequence(indata, [1, 2, 3, 4], -1, 0, np.array(result))\n    verify_reverse_sequence(\n        indata.astype(\"float32\"), [1, 2, 3, 4], 1, 0, np.array(result).astype(\"float32\")\n    )\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 1, 2, 3], [5, 4, 6, 7], [10, 9, 8, 11], [15, 14, 13, 12]]\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 0, 1, np.array(result))\n    verify_reverse_sequence(indata, [1, 2, 3, 4], 0, -1, np.array(result))\n    verify_reverse_sequence(\n        indata.astype(\"float32\"), [1, 2, 3, 4], 0, 1, np.array(result).astype(\"float32\")\n    )\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [15, 14, 13, 12]]\n    verify_reverse_sequence(indata, [-1, 0, 1, 5], 0, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n    result = [\n        [\n            [[18, 19, 20], [21, 22, 23], [24, 25, 26]],\n            [[9, 10, 11], [12, 13, 14], [15, 16, 17]],\n            [[0, 1, 2], [3, 4, 5], [6, 7, 8]],\n        ],\n        [\n            [[45, 46, 47], [48, 49, 50], [51, 52, 53]],\n            [[36, 37, 38], [39, 40, 41], [42, 43, 44]],\n            [[27, 28, 29], [30, 31, 32], [33, 34, 35]],\n        ],\n    ]\n    verify_reverse_sequence(indata, [3, 3], 0, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n    result = [\n        [\n            [[9, 10, 11], [21, 22, 23], [15, 16, 17]],\n            [[0, 1, 2], [12, 13, 14], [6, 7, 8]],\n            [[18, 19, 20], [3, 4, 5], [24, 25, 26]],\n        ],\n        [\n            [[36, 37, 38], [48, 49, 50], [42, 43, 44]],\n            [[27, 28, 29], [39, 40, 41], [33, 34, 35]],\n            [[45, 46, 47], [30, 31, 32], [51, 52, 53]],\n        ],\n    ]\n    verify_reverse_sequence(indata, [2, 3, 2], 2, 1, np.array(result))\n\n    indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n    result = []\n    with pytest.raises(Exception) as execinfo:\n        verify_reverse_sequence(indata, [2, 3, 2, 4, 5], 1, 0, np.array(result))\n\n    assert (\n        \"For reverse_sequnece seq_lengths size should match with dimension of batch axis,\"\n        \" but got dimension of batch_axis = 4, and seq_length size = 5\" in execinfo.value.args[0]\n    )\n\n\ndef verify_take(src_shape, indices_src, axis=None, mode=\"clip\", indices_dtype=\"int32\"):\n    src_dtype = \"float32\"\n    indices_src = np.array(indices_src, dtype=indices_dtype)\n    A = te.placeholder(shape=src_shape, dtype=src_dtype, name=\"A\")\n    indices = te.placeholder(shape=indices_src.shape, dtype=indices_dtype, name=\"indices\")\n    if axis is None:\n        out_tensor = topi.take(a=A, indices=indices, mode=mode)\n    else:\n        out_tensor = topi.take(a=A, indices=indices, axis=axis, mode=mode)\n\n    def check_device(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(out_tensor)\n\n        foo = tvm.build(s, [A] + [indices] + [out_tensor], target, name=\"take\")\n        shape_size = 1\n        for i in range(len(src_shape)):\n            shape_size = shape_size * src_shape[i]\n        data_npy = np.arange(shape_size, dtype=src_dtype).reshape((src_shape))\n\n        if axis is None:\n            np_mode = \"raise\" if mode == \"fast\" else mode\n            out_npys = np.take(data_npy, indices_src, mode=np_mode)\n        else:\n            np_mode = \"raise\" if mode == \"fast\" else mode\n            out_npys = np.take(data_npy, indices_src, axis=axis, mode=np_mode)\n        data_nd = tvm.nd.array(data_npy, dev)\n        indices_nd = tvm.nd.array(indices_src, dev)\n        out_nd = tvm.nd.empty(out_npys.shape, device=dev, dtype=src_dtype)\n        foo(data_nd, indices_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npys)\n\n    for target in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n        check_device(target)\n\n\ndef verify_strided_slice(in_shape, begin, end, strides=None, axes=None):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    strides = [1, 1, 1] if strides is None else strides\n    if axes:\n        strides = [strides[axis] for axis in axes]\n    B = topi.strided_slice(A, begin, end, strides, axes) + 1\n\n    def check_device(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        foo = tvm.build(s, [A, B], target, name=\"stride_slice\")\n        x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = tvm.topi.testing.strided_slice_python(x_np, begin, end, strides, axes=axes) + 1\n        data_nd = tvm.nd.array(x_np, dev)\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=A.dtype)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n        check_device(target)\n\n\ndef verify_dynamic_strided_slice(in_shape, begin, end, strides=None):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    Begin = te.placeholder(shape=[len(in_shape)], name=\"begin\", dtype=\"int64\")\n    End = te.placeholder(shape=[len(in_shape)], name=\"end\", dtype=\"int64\")\n    Strides = te.placeholder(shape=[len(in_shape)], name=\"strides\", dtype=\"int64\")\n    strides = [1, 1, 1] if strides is None else strides\n    B = topi.strided_slice(A, Begin, End, Strides) + 1\n\n    def check_device(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        foo = tvm.build(s, [A, Begin, End, Strides, B], target, name=\"stride_slice\")\n        x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = tvm.topi.testing.strided_slice_python(x_np, begin, end, strides) + 1\n        data_nd = tvm.nd.array(x_np, dev)\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=A.dtype)\n        begin_nd = tvm.nd.array(np.array(begin).astype(\"int64\"), dev)\n        end_nd = tvm.nd.array(np.array(end).astype(\"int64\"), dev)\n        strides_nd = tvm.nd.array(np.array(strides).astype(\"int64\"), dev)\n        foo(data_nd, begin_nd, end_nd, strides_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n        check_device(target)\n\n\ndef verify_strided_set(in_shape, v_shape, begin, end, strides=None):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    V = te.placeholder(shape=v_shape, name=\"V\")\n    b = te.placeholder(shape=(len(begin),), name=\"b\", dtype=\"int32\")\n    e = te.placeholder(shape=(len(end),), name=\"e\", dtype=\"int32\")\n    if strides is not None:\n        st = te.placeholder(shape=(len(strides),), name=\"st\", dtype=\"int32\")\n        B = topi.strided_set(A, V, b, e, st) + 1\n    else:\n        B = topi.strided_set(A, V, b, e) + 1\n\n    def check_device(target):\n        dev = tvm.device(target, 0)\n        if not tvm.testing.device_enabled(target):\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n\n        if strides is not None:\n            foo = tvm.build(s, [A, V, b, e, st, B], target, name=\"stride_set\")\n            s_np = np.asarray(strides).astype(\"int32\")\n            s_nd = tvm.nd.array(s_np, dev)\n        else:\n            foo = tvm.build(s, [A, V, b, e, B], target, name=\"stride_set\")\n        x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n        v_np = np.random.uniform(size=v_shape).astype(V.dtype)\n        b_np = np.asarray(begin).astype(\"int32\")\n        e_np = np.asarray(end).astype(\"int32\")\n        out_npy = tvm.topi.testing.strided_set_python(x_np, v_np, begin, end, strides) + 1\n        data_nd = tvm.nd.array(x_np, dev)\n        v_nd = tvm.nd.array(v_np, dev)\n        b_nd = tvm.nd.array(b_np, dev)\n        e_nd = tvm.nd.array(e_np, dev)\n        out_nd = tvm.nd.empty(out_npy.shape, device=dev, dtype=A.dtype)\n        if strides is not None:\n            foo(data_nd, v_nd, b_nd, e_nd, s_nd, out_nd)\n        else:\n            foo(data_nd, v_nd, b_nd, e_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n        check_device(target)\n\n\ndef verify_gather(data, axis, indices):\n    data = np.asarray(data)\n    indices = np.asarray(indices)\n\n    var_data = te.placeholder(shape=data.shape, dtype=data.dtype.name, name=\"data\")\n    var_indices = te.placeholder(shape=indices.shape, dtype=indices.dtype.name, name=\"indices\")\n    out_tensor = topi.gather(var_data, axis, var_indices)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(out_tensor)\n\n        func = tvm.build(s, [var_data, var_indices, out_tensor], target, name=\"gather\")\n        out_npys = tvm.topi.testing.gather_python(data, axis, indices)\n\n        data_nd = tvm.nd.array(data, dev)\n        indices_nd = tvm.nd.array(indices, dev)\n        out_nd = tvm.nd.empty(out_npys.shape, device=dev, dtype=data.dtype.name)\n        func(data_nd, indices_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npys)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_gather_nd(src_shape, indices_src, indices_dtype):\n    src_dtype = \"float32\"\n    indices_src = np.array(indices_src, dtype=indices_dtype)\n    A = te.placeholder(shape=src_shape, dtype=src_dtype, name=\"A\")\n    indices = te.placeholder(shape=indices_src.shape, dtype=indices_dtype, name=\"indices\")\n    out_tensor = topi.gather_nd(a=A, indices=indices)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(out_tensor)\n\n        func = tvm.build(s, [A, indices, out_tensor], target, name=\"take\")\n        shape_size = 1\n        for i in range(len(src_shape)):\n            shape_size = shape_size * src_shape[i]\n        data_npy = np.arange(shape_size, dtype=src_dtype).reshape((src_shape))\n        out_npys = tvm.topi.testing.gather_nd_python(data_npy, indices_src)\n\n        data_nd = tvm.nd.array(data_npy, dev)\n        indices_nd = tvm.nd.array(indices_src, dev)\n        out_nd = tvm.nd.empty(out_npys.shape, device=dev, dtype=src_dtype)\n        func(data_nd, indices_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npys)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_arange(start, stop, step):\n    if start is None and step is None:\n        A = topi.arange(stop)\n        a_np = np.arange(stop)\n    elif start is None:\n        A = topi.arange(stop, step=step)\n        a_np = np.arange(stop, step=step)\n    elif step is None:\n        A = topi.arange(start, stop)\n        a_np = np.arange(start, stop)\n    else:\n        A = topi.arange(start, stop, step)\n        a_np = np.arange(start, stop, step)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(A)\n        f = tvm.build(s, [A], target, name=\"arange\")\n        a_nd = tvm.nd.empty(a_np.shape, dtype=\"float32\", device=dev)\n        f(a_nd)\n        tvm.testing.assert_allclose(a_nd.numpy(), a_np)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_repeat(in_shape, repeats, axis):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.repeat(A, repeats, axis)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"repeat\")\n        data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = np.repeat(data_npy, repeats, axis)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), dev)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_tile(in_shape, reps):\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = topi.tile(A, reps)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(B)\n        foo = tvm.build(s, [A, B], target, name=\"tile\")\n        data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n        out_npy = np.tile(data_npy, reps)\n        data_nd = tvm.nd.array(data_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), dev)\n        foo(data_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_where(in_shape):\n    Cond = te.placeholder(shape=in_shape, name=\"cond\")\n    dtype = Cond.dtype\n    A = te.placeholder(shape=in_shape, name=\"A\")\n    B = te.placeholder(shape=in_shape, name=\"B\")\n    C = topi.where(Cond, A, B)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_broadcast_schedule(target)(C)\n        f = tvm.build(s, [Cond, A, B, C], target, name=\"where\")\n        cond_npy = np.random.uniform(low=-1, high=1, size=in_shape).astype(dtype)\n        x_npy = np.random.uniform(size=in_shape).astype(dtype)\n        y_npy = np.random.uniform(size=in_shape).astype(dtype)\n        out_npy = np.where(cond_npy, x_npy, y_npy)\n        cond_nd = tvm.nd.array(cond_npy, dev)\n        x_nd = tvm.nd.array(x_npy, dev)\n        y_nd = tvm.nd.array(y_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(C.dtype), dev)\n        f(cond_nd, x_nd, y_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_one_hot(indices_shape, depth, on_value, off_value, axis, dtype):\n    indices = te.placeholder(shape=indices_shape, name=\"indices\", dtype=\"int32\")\n    on_value_const = tvm.tir.const(on_value, dtype)\n    off_value_const = tvm.tir.const(off_value, dtype)\n    one_hot_result = topi.transform.one_hot(\n        indices, on_value_const, off_value_const, depth, axis, dtype\n    )\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(one_hot_result)\n        fn = tvm.build(s, [indices, one_hot_result], target, name=\"one_hot\")\n        indices_npy = np.random.randint(0, depth, size=indices_shape).astype(indices.dtype)\n        out_npy = tvm.topi.testing.one_hot(indices_npy, on_value, off_value, depth, axis, dtype)\n        indices_nd = tvm.nd.array(indices_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(one_hot_result.dtype), dev)\n        fn(indices_nd, out_nd)\n        out_topi = out_nd.numpy()\n        tvm.testing.assert_allclose(out_topi, out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_unravel_index(indices, shape, dtype, indice_dtype=\"int64\"):\n    x_data = np.array(indices).astype(indice_dtype)\n    y_data = np.array(shape).astype(dtype)\n    if len(x_data.shape) == 1:\n        dst_shape = [y_data.shape[0], x_data.shape[0]]\n    else:\n        dst_shape = [y_data.shape[0]]\n\n    X = te.placeholder(shape=x_data.shape, dtype=indice_dtype, name=\"X\")\n    Y = te.placeholder(shape=y_data.shape, dtype=dtype, name=\"Y\")\n    Z = topi.unravel_index(X, Y)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(Z)\n        foo = tvm.build(s, [X, Y, Z], target, name=\"unravel_index\")\n\n        out_npy = np.unravel_index(x_data, y_data)\n        datax_nd = tvm.nd.array(x_data, dev)\n        datay_nd = tvm.nd.array(y_data, dev)\n        out_nd = tvm.nd.empty(dst_shape, device=dev, dtype=Z.dtype)\n        foo(datax_nd, datay_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape, xpected):\n    sparse_indices_data = np.array(sparse_indices)\n    sparse_values_data = np.array(sparse_values)\n    output_shape_data = np.array(output_shape)\n    default_value_data = np.array(default_value)\n\n    A = te.placeholder(\n        shape=sparse_indices_data.shape, name=\"sparse_indices\", dtype=str(sparse_indices_data.dtype)\n    )\n    B = te.placeholder(\n        shape=sparse_values_data.shape, name=\"sparse_values\", dtype=str(sparse_values_data.dtype)\n    )\n    if default_value is None:\n        args = [A, B]\n        D = topi.sparse_to_dense(A, output_shape, B)\n    else:\n        C = te.placeholder(shape=(), name=\"default_value\", dtype=str(default_value_data.dtype))\n        args = [A, B, C]\n        D = topi.sparse_to_dense(A, output_shape, B, C)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(D)\n\n        foo = tvm.build(s, args + [D], target, name=\"sparse_to_dense\")\n\n        sparse_indices_nd = tvm.nd.array(sparse_indices_data, dev)\n        sparse_values_nd = tvm.nd.array(sparse_values_data, dev)\n        out_nd = tvm.nd.empty(output_shape_data, device=dev, dtype=B.dtype)\n\n        if default_value is None:\n            foo(sparse_indices_nd, sparse_values_nd, out_nd)\n        else:\n            default_value_nd = tvm.nd.array(default_value_data, dev)\n            foo(sparse_indices_nd, sparse_values_nd, default_value_nd, out_nd)\n\n        tvm.testing.assert_allclose(out_nd.numpy(), np.array(xpected))\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_matrix_set_diag(input_shape, diagonal_shape, dtype, k=0, align=\"RIGHT_LEFT\"):\n    input = te.placeholder(shape=input_shape, name=\"input\", dtype=dtype)\n    diagonal = te.placeholder(shape=diagonal_shape, name=\"diagonal\", dtype=dtype)\n    matrix_set_diag_result = topi.transform.matrix_set_diag(input, diagonal, k, align)\n\n    def check_device(target, dev):\n        dev = tvm.device(target, 0)\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(matrix_set_diag_result)\n        fn = tvm.build(s, [input, diagonal, matrix_set_diag_result], target, name=\"matrix_set_diag\")\n        input_npy = np.random.randint(-100, 100, size=input_shape).astype(dtype)\n        diagonal_npy = np.random.randint(-100, 100, size=diagonal_shape).astype(dtype)\n        out_npy = tvm.topi.testing.matrix_set_diag(input_npy, diagonal_npy, k, align)\n        input_nd = tvm.nd.array(input_npy, dev)\n        diagonal_nd = tvm.nd.array(diagonal_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(matrix_set_diag_result.dtype), dev)\n        fn(input_nd, diagonal_nd, out_nd)\n        out_topi = out_nd.numpy()\n        tvm.testing.assert_allclose(out_topi, out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_adv_index(data_shape, index_shapes, indice_dtype=\"int64\"):\n    dtype = \"float32\"\n    data = te.placeholder(shape=data_shape, name=\"data\", dtype=dtype)\n    indices = []\n    np_data = np.random.uniform(size=data_shape).astype(dtype)\n    np_indices = []\n    for i, index_shape in enumerate(index_shapes):\n        limit = data_shape[i]\n        np_indices.append(np.random.uniform(0, limit - 1, size=index_shape).astype(indice_dtype))\n        indices.append(\n            te.placeholder(shape=index_shape, name=\"index_{}\".format(i), dtype=indice_dtype)\n        )\n    np_out = np_data[tuple(np_indices)]\n    out = topi.adv_index(data, indices)\n\n    def check_device(target, dev):\n        dev = tvm.device(target, 0)\n        if not dev.exist:\n            print(\"Skip because %s is not enabled\" % target)\n            return\n        print(\"Running on target: %s\" % target)\n        with tvm.target.create(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(out)\n\n        func = tvm.build(s, [data] + indices + [out], target, name=\"adv_index\")\n\n        nd_list = [tvm.nd.array(np_data, dev)]\n        for np_index in np_indices:\n            nd_list.append(tvm.nd.array(np_index, dev))\n        nd_list.append(tvm.nd.empty(out.shape, device=dev, dtype=data.dtype))\n\n        func(*nd_list)\n        tvm.testing.assert_allclose(nd_list[-1].numpy(), np.array(np_out))\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\ndef verify_trilu(input_shape, upper, k=0):\n    x = te.placeholder(shape=input_shape, name=\"x\", dtype=\"float32\")\n    k_tir = tvm.tir.const(k, dtype=\"int32\")\n    trilu_result = topi.transform.trilu(x, k_tir, upper)\n\n    def check_device(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(trilu_result)\n        fn = tvm.build(s, [x, trilu_result], target, name=\"trilu\")\n        x_npy = np.random.normal(size=input_shape).astype(x.dtype)\n        if upper:\n            out_npy = np.triu(x_npy, k)\n        else:\n            out_npy = np.tril(x_npy, k)\n        x_nd = tvm.nd.array(x_npy, dev)\n        out_nd = tvm.nd.array(np.empty(x_npy.shape).astype(trilu_result.dtype), dev)\n        fn(x_nd, out_nd)\n        out_topi = out_nd.numpy()\n        tvm.testing.assert_allclose(out_topi, out_npy)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_device(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_strided_slice():\n    verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n    verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1])\n    verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1])\n    verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2])\n    verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1])\n    verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3])\n    verify_strided_slice((3, 4, 3), [0, 2, 0], [1, 2, 3])\n    verify_strided_slice((3, 4, 3), [0, 0, 0], [None, None, None])\n    verify_strided_slice((3, 4, 3), [0], [2], None, axes=[1])\n\n\n@tvm.testing.uses_gpu\ndef test_dynamic_strided_slice():\n    verify_dynamic_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n    verify_dynamic_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1])\n    verify_dynamic_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2])\n    verify_dynamic_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3])\n    verify_dynamic_strided_slice((3, 4, 3), [0, 2, 0], [1, 2, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_strided_set():\n    verify_strided_set((3, 4, 3), (3, 2, 2), [0, 3, 0], [4, 1, 4], [1, -1, 2])\n    verify_strided_set((3, 4, 3), (3, 1, 2), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n    verify_strided_set((3, 4, 3), (1, 3, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1])\n    verify_strided_set((3, 4, 3), (1, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1])\n    verify_strided_set((3, 4, 3), (1, 2, 2), [1, 0, 0], [2, 2, 3], [1, 1, 2])\n    verify_strided_set((3, 4, 3), (1, 2, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1])\n    verify_strided_set((3, 4, 3), (1, 2, 3), [1, 1, 0], [2, 3, 3], [1])\n    verify_strided_set((3, 4, 3), (2, 3, 3), [1, 1, 0], [4, 4, 3])\n    verify_strided_set((3, 4, 3), (2, 3, 3), [1, 1], [4, 4, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_expand_dims():\n    verify_expand_dims((3, 10), (3, 10, 1, 1), 2, 2)\n    verify_expand_dims((3, 10), (1, 3, 10), -3, 1)\n\n\n@tvm.testing.uses_gpu\ndef test_reinterpret():\n    verify_reinterpret((1000,), \"float32\", \"int32\", lambda shape: np.random.randn(*shape) * 1000)\n    verify_reinterpret((1000,), \"float16\", \"int16\", lambda shape: np.random.randn(*shape) * 100)\n    verify_reinterpret(\n        (1000,), \"int16\", \"uint16\", lambda shape: np.random.randint(-1000, 1000, size=shape)\n    )\n    verify_reinterpret(\n        (1000,), \"uint32\", \"int32\", lambda shape: np.random.randint(0, 2**32 - 1, size=shape)\n    )\n    verify_reinterpret(\n        (1000,), \"uint32\", \"int32\", lambda shape: np.random.randint(0, 2**32 - 1, size=shape)\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_transpose():\n    verify_transpose((3, 10, 2), (1, 0, 2))\n    verify_transpose((3, 10, 5), (2, 0, 1))\n    verify_transpose((3, 10), None)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_transpose_unfused_schedule(target, dev):\n    shape = (100, tvm.target.Target(target).thread_warp_size + 3)\n    x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n    f = relay.transpose(x)\n    r = np.random.rand(*shape)\n    func = relay.create_executor(\n        kind=\"graph\", mod=tvm.IRModule.from_expr(relay.Function([x], f)), device=dev, target=target\n    ).evaluate()\n    tvm.testing.assert_allclose(func(r).numpy(), np.transpose(r))\n\n    # We want to make sure schedule does not fire here, but there is no way of\n    # inspecting which schedules were used.\n    x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n    y = relay.var(\"y\", relay.TensorType(shape, \"float32\"))\n    f = relay.transpose(x + y)\n    func = relay.create_executor(\n        kind=\"graph\",\n        mod=tvm.IRModule.from_expr(relay.Function([x, y], f)),\n        device=dev,\n        target=target,\n    ).evaluate()\n    tvm.testing.assert_allclose(func(r, r).numpy(), np.transpose(r + r))\n\n\n@tvm.testing.uses_gpu\ndef test_reshape():\n    verify_reshape((1, 2, 3, 4), (2, 3, 4))\n    verify_reshape((4, 2, 3, 4), (2, 4, 12))\n    verify_reshape((4, 2, 3, 4), (2, 48))\n    verify_reshape((16,), (2, 2, 2, 2))\n    verify_reshape((4, 0), (2, 0, 2))\n\n\n@tvm.testing.uses_gpu\ndef test_where():\n    verify_where(())\n    verify_where((1, 2, 3, 4))\n\n\n@tvm.testing.uses_gpu\ndef test_squeeze():\n    verify_squeeze((1, 2, 3, 4), 0)\n    verify_squeeze((1, 2, 1, 4), None)\n    verify_squeeze((1, 1, 1, 4), (1, 2))\n    verify_squeeze((1, 1, 1, 1), None)\n    verify_squeeze((1, 1, 1, 1), ())\n\n    # a special case to trigger inline let expression\n    A = te.placeholder((2,), \"float32\", \"A\")\n    E = topi.squeeze(A)\n    C = te.compute((1,), lambda i: E[(2 * A[0] - 1).astype(\"int32\")])\n    for target in [\"llvm\", \"cuda\", \"opencl\"]:\n        dev = tvm.device(target, 0)\n        if tvm.testing.device_enabled(target):\n            with tvm.target.Target(target):\n                s = tvm.topi.testing.get_injective_schedule(target)(C)\n                func = tvm.build(s, [A, C])\n            a = tvm.nd.array(np.array((1, 2)).astype(\"float32\"), device=dev)\n            c = tvm.nd.empty((1,), dtype=\"float32\", device=dev)\n            func(a, c)\n            assert c.numpy()[0] == 2\n\n\n@tvm.testing.uses_gpu\ndef test_concatenate():\n    verify_concatenate([(2,), (2,), (2,)], -1)\n    verify_concatenate([(2, 3, 4), (2, 2, 4), (2, 5, 4)], 1)\n    verify_concatenate([(1, 2, 4), (1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 1)], -1)\n    verify_concatenate([(5, 6, 7, 3), (16, 6, 7, 3), (12, 6, 7, 3), (8, 6, 7, 3), (2, 6, 7, 3)], 0)\n    verify_concatenate([(1, 14400), (1, 2400), (1, 640), (1, 240)], 1)\n\n\n@tvm.testing.uses_gpu\ndef test_stack():\n    verify_stack([(2,), (2,), (2,)], -1)\n    verify_stack([(2,), (2,), (2,)], 1)\n    verify_stack([(2,), (2,), (2,)], 0)\n    verify_stack([(2, 2, 4), (2, 2, 4), (2, 2, 4)], 1)\n    verify_stack([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], -1)\n\n\n@tvm.testing.uses_gpu\ndef test_split():\n    verify_split((2, 12, 3), 3, 1)\n    verify_split((2, 12, 3), [2, 4], 1)\n    verify_split((10, 12, 24), [5, 7, 9], -1)\n\n\n@tvm.testing.uses_gpu\ndef test_flip():\n    verify_flip((3, 4, 3), 1)\n    verify_flip((3, 4, 3), 0)\n    verify_flip((3, 4, 3), 2)\n    verify_flip((3, 4, 3), -1)\n    verify_flip((3, 4, 3), -3)\n    verify_flip((3, 4, 3), -2)\n\n\n@tvm.testing.requires_llvm\ndef test_expand_like():\n    verify_expand_like((3,), (2, 3), [0])\n    verify_expand_like((2,), (2, 3), [1])\n    verify_expand_like((3, 4), (3, 5, 4), [1])\n    verify_expand_like((5, 7), (5, 6, 7, 8), [1, 3])\n\n\n@tvm.testing.uses_gpu\ndef test_take():\n    verify_take((4,), [1])\n    verify_take((4,), [[0, 1, 2, 3]])\n    verify_take((3, 3, 3), [[11, 25]])\n    verify_take((4,), [[0, 1], [2, 3]])\n    verify_take((4,), [1], 0)\n    verify_take((2, 2), [[[1, 0], [0, 1]]], 0)\n    verify_take((2, 2), [[[1, 0], [0, 1]]], 1)\n    verify_take((4, 3, 5, 6), [[2, 1, 0, 0]], -2)\n    verify_take((3, 4), [-5, 20])\n    verify_take((3, 4), [-5, 20], mode=\"wrap\")\n    verify_take((3, 4), [-1, 2], axis=0)\n    verify_take((3, 4), [-1, 2], axis=0, mode=\"wrap\")\n    verify_take((3, 4), [-1, 2], axis=1)\n    verify_take((3, 4), [-1, 2], axis=1, mode=\"wrap\")\n    verify_take((3, 3, 3), [[11, 25]], mode=\"fast\")\n    verify_take((3, 4), [0, 2], axis=0, mode=\"fast\")\n    verify_take((3, 4), [0, 2], axis=1, mode=\"fast\")\n    verify_take((3, 4), [1, 2], axis=1, indices_dtype=\"uint32\")\n    verify_take((3, 4), [1, 2], axis=1, mode=\"wrap\", indices_dtype=\"uint16\")\n    verify_take((3, 3, 3), [[11, 20]], mode=\"fast\", indices_dtype=\"uint8\")\n\n\n@tvm.testing.uses_gpu\ndef test_gather():\n    verify_gather([[1, 2], [3, 4]], 1, [[0, 0], [1, 0]])\n    verify_gather(np.random.randn(4, 7, 5), 0, np.random.randint(low=0, high=4, size=(1, 7, 5)))\n    verify_gather(np.random.randn(4, 7, 5), 0, np.random.randint(low=0, high=4, size=(4, 7, 5)))\n    verify_gather(np.random.randn(4, 7, 5), 1, np.random.randint(low=0, high=7, size=(4, 10, 5)))\n    verify_gather(np.random.randn(4, 7, 5), 1, np.random.randint(low=0, high=7, size=(4, 10, 5)))\n    verify_gather(np.random.randn(4, 7, 5), 2, np.random.randint(low=0, high=5, size=(4, 7, 2)))\n    verify_gather(np.random.randn(4, 7, 5), 2, np.random.randint(low=0, high=5, size=(4, 7, 10)))\n\n\n@tvm.testing.uses_gpu\ndef test_gather_nd():\n    for indices_dtype in [\"int32\", \"float32\", \"uint8\"]:\n        verify_gather_nd((4,), [[1.8]], indices_dtype)\n        verify_gather_nd((4,), [[1, 3, 2]], indices_dtype)\n        verify_gather_nd((2, 3), [[1]], indices_dtype)\n        verify_gather_nd((2, 3), [[1], [0]], indices_dtype)\n        verify_gather_nd((2, 3), [[1, 0], [0, 2]], indices_dtype)\n        verify_gather_nd((2, 3, 4), [[1, 0], [0, 2]], indices_dtype)\n        verify_gather_nd((2, 3, 4), [[1, 0], [0, 2], [3, 1]], indices_dtype)\n        verify_gather_nd(\n            (2, 3, 4), [[[1, 0], [0, 1]], [[0, 2], [1, 2]], [[3, 1], [0, 2]]], indices_dtype\n        )\n        verify_gather_nd((2, 3, 4, 5), [[1, 0], [0, 2]], indices_dtype)\n        verify_gather_nd((2, 3, 4, 5), [[1, 0], [2, 1], [3, 2], [4, 2]], indices_dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_arange():\n    verify_arange(None, 20, None)\n    verify_arange(None, 20, 2)\n    verify_arange(1, 20, None)\n    verify_arange(1, 20, 2)\n    verify_arange(1, 20, 1.5)\n    verify_arange(1, 20.5, None)\n    verify_arange(1, 20, 3)\n    verify_arange(20, 1, -1)\n    verify_arange(20, 1, -1.5)\n\n\n@tvm.testing.uses_gpu\ndef test_repeat():\n    verify_repeat((2,), 1, 0)\n    verify_repeat((3, 2), 2, 0)\n    verify_repeat((3, 2, 4), 3, 1)\n    verify_repeat((1, 3, 2, 4), 4, -1)\n\n\n@tvm.testing.uses_gpu\ndef test_tile():\n    verify_tile((3, 2), (2, 3))\n    verify_tile((3, 2, 5), (2,))\n    verify_tile((3,), (2, 3, 3))\n    verify_tile((4, 0), (5,))\n\n\n@tvm.testing.uses_gpu\ndef test_layout_transform():\n    in_shape = (1, 32, 8, 8)\n    A = te.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n    B = topi.layout_transform(A, \"NCHW\", \"NCHW16c\")\n\n    input = np.random.uniform(size=in_shape).astype(A.dtype)\n    output = np.transpose(input, axes=(0, 2, 3, 1))\n    output = np.reshape(output, newshape=(1, 8, 8, 2, 16))\n    output = np.transpose(output, axes=(0, 3, 1, 2, 4))\n\n    def check_device(target, dev):\n        tvm_input = tvm.nd.array(input, dev)\n        tvm_output = tvm.nd.empty(output.shape, device=dev, dtype=B.dtype)\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        f = tvm.build(s, [A, B], target, name=\"layout_transform\")\n        f(tvm_input, tvm_output)\n        tvm.testing.assert_allclose(tvm_output.numpy(), output)\n\n    for backend, dev in tvm.testing.enabled_targets():\n        check_device(backend, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_shape():\n    in_shape = (8, 7, 13)\n    dtype = \"int32\"\n    A = te.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n    B = topi.shape(A, dtype)\n\n    input = np.random.uniform(size=in_shape).astype(A.dtype)\n    output = np.asarray(in_shape).astype(dtype)\n\n    def check_device(target, dev):\n        tvm_input = tvm.nd.array(input, dev)\n        tvm_output = tvm.nd.empty(output.shape, device=dev, dtype=dtype)\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        f = tvm.build(s, [A, B], target, name=\"shape\")\n        f(tvm_input, tvm_output)\n        tvm.testing.assert_allclose(tvm_output.numpy(), output)\n\n    for backend, dev in tvm.testing.enabled_targets():\n        check_device(backend, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_sequence_mask():\n    for in_shape in (5, 10), (3, 4, 5, 4):\n        for axis in [0, 1]:\n            for mask_value in [0.0, 1.0]:\n                max_length = in_shape[axis]\n                batch_size = in_shape[1 - axis]\n                A = te.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n                B = te.placeholder(shape=(batch_size,), dtype=\"int32\", name=\"B\")\n                C = topi.sequence_mask(A, B, axis=axis, mask_value=mask_value)\n                A_data = np.random.normal(0, 1, in_shape).astype(np.float32)\n                B_data = np.random.randint(1, max_length, (batch_size,)).astype(np.int32)\n                C_gt_data = tvm.topi.testing.sequence_mask(A_data, B_data, mask_value, axis)\n\n                def check_device(target, dev):\n                    tvm_A = tvm.nd.array(A_data, dev)\n                    tvm_B = tvm.nd.array(B_data, dev)\n                    tvm_C = tvm.nd.empty(in_shape, device=dev, dtype=\"float32\")\n                    print(\"Running on target: %s\" % target)\n                    with tvm.target.Target(target):\n                        s = tvm.topi.testing.get_injective_schedule(target)(C)\n                    f = tvm.build(s, [A, B, C], target, name=\"SequenceMask\")\n                    f(tvm_A, tvm_B, tvm_C)\n                    tvm.testing.assert_allclose(tvm_C.numpy(), C_gt_data)\n\n                for backend, dev in tvm.testing.enabled_targets():\n                    check_device(backend, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_ndarray_size():\n    in_shape = (5, 11, 7)\n    dtype = \"int32\"\n    A = te.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n    B = topi.ndarray_size(A, dtype)\n\n    input = np.random.uniform(size=in_shape).astype(A.dtype)\n    output = np.asarray(np.size(input)).astype(dtype)\n\n    def check_device(target, dev):\n        tvm_input = tvm.nd.array(input, device=dev)\n        tvm_output = tvm.nd.empty((), device=dev, dtype=B.dtype)\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        f = tvm.build(s, [A, B], target, name=\"ndarray_size\")\n        f(tvm_input, tvm_output)\n        tvm.testing.assert_allclose(tvm_output.numpy(), output)\n\n    for backend, dev in tvm.testing.enabled_targets():\n        check_device(backend, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_where_fusion():\n    \"\"\"integration test that where and zeros should be properly inlined\"\"\"\n\n    def check_device(target, dev):\n        with tvm.target.Target(target):\n            print(\"Running on target: %s\" % target)\n            conv2d_compute, conv2d_schedule = tvm.topi.testing.get_conv2d_nchw_implement(target)\n            data = te.placeholder((2, 1, 2, 4), \"int8\", \"data\")\n            w = te.placeholder((3, 1, 2, 2), \"int8\", \"w\")\n            conv1 = conv2d_compute(data, w, 1, 0, 1, \"int32\")\n            zeros = topi.full((2, 3, 1, 3), \"int32\", tvm.tir.const(0, dtype=\"int32\"))\n            gt = topi.greater_equal(conv1, zeros)\n            one = topi.full((2, 3, 1, 3), \"int32\", tvm.tir.const(1, dtype=\"int32\"))\n            two = topi.full((2, 3, 1, 3), \"int32\", tvm.tir.const(2, dtype=\"int32\"))\n            where = topi.where(gt, one, two)\n            add = topi.add(conv1, where)\n            outs = [add]\n            s = conv2d_schedule(outs)\n            tvm.build(s, [data, w, add], target=backend)\n\n    for backend, dev in tvm.testing.enabled_targets():\n        check_device(backend, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_one_hot():\n    verify_one_hot((3,), 3, 1, 0, -1, \"int32\")\n    verify_one_hot((3,), 3, 1.0, 0.0, -1, \"float32\")\n    verify_one_hot((2, 2), 5, 2, -2, 0, \"int32\")\n    verify_one_hot((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n    verify_one_hot((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n    verify_one_hot((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\n@tvm.testing.uses_gpu\ndef test_unravel_index():\n    for dtype in [\"int32\", \"int64\"]:\n        for indice_dtype in [\"int64\", \"uint8\", \"uint16\", \"uint32\"]:\n            verify_unravel_index([0, 1, 2, 3], [2, 2], dtype, indice_dtype)\n            verify_unravel_index([144], [5, 5, 5, 2], dtype, indice_dtype)\n            verify_unravel_index(144, [5, 5, 5, 2], dtype, indice_dtype)\n            verify_unravel_index([100, 13, 5], [5, 5, 5, 2], dtype, indice_dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_sparse_to_dense():\n    verify_sparse_to_dense(1, 3, 0, [5], [0, 3, 0, 0, 0])  # scalar\n    verify_sparse_to_dense([0, 1, 4], [3, 3, 3], 0, [5], [3, 3, 0, 0, 3])  # vector\n    verify_sparse_to_dense(\n        [[0, 0], [1, 2]], [1, 2], 0, [3, 4], [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]\n    )  # nXd\n    verify_sparse_to_dense(\n        [[0, 0, 0], [1, 2, 3]],\n        [1, 2],\n        4,\n        [2, 3, 4],\n        [[[1, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]], [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 2]]],\n    )  # nXd\n    verify_sparse_to_dense(\n        [0, 1, 4], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1]\n    )  # floats\n    verify_sparse_to_dense(1, 3, None, [5], [0, 3, 0, 0, 0])  # default value not specified\n\n    # negative test cases\n    # sparse indices should be ints\n    # verify_sparse_to_dense([[0.1, 1.1, 4.1], [0,2,4]], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n    # sparse_values should be 0d or 1d only\n    # verify_sparse_to_dense([[0, 1, 4], [0, 2, 4]], [[[3.1, 3.1, 3.1]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n    # sparse_indices should not be > 2d tensor\n    # verify_sparse_to_dense([[[[0, 1, 4], [0, 2, 4]]]], [[[3.1, 3.1, 3.1]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n\n\n@tvm.testing.uses_gpu\ndef test_matrix_set_diag():\n    for dtype in [\"float32\", \"int32\"]:\n        verify_matrix_set_diag((2, 2), (2,), dtype)\n        verify_matrix_set_diag((4, 3, 3), (4, 3), dtype)\n        verify_matrix_set_diag((2, 3, 4), (2, 3), dtype, 1)\n        verify_matrix_set_diag((2, 3, 4), (2, 4, 3), dtype, (-1, 2), \"LEFT_RIGHT\")\n        verify_matrix_set_diag((2, 3, 4), (2, 4, 3), dtype, (-1, 2), \"LEFT_LEFT\")\n        verify_matrix_set_diag((2, 3, 4), (2, 4, 3), dtype, (-1, 2), \"RIGHT_RIGHT\")\n\n\n@tvm.testing.uses_gpu\ndef test_adv_index():\n    for indice_dtype in [\"int32\", \"int64\", \"uint8\", \"uint16\", \"uint32\"]:\n        verify_adv_index((3, 4, 5), [(2,), (2,), (1,)], indice_dtype=indice_dtype)\n        verify_adv_index((10, 15, 5), [(4, 1), (1, 7)], indice_dtype=indice_dtype)\n        verify_adv_index((10, 5, 15), [(1, 2, 1), (1, 2, 7)], indice_dtype=indice_dtype)\n\n\n@tvm.testing.uses_gpu\ndef test_trilu():\n    # Test upper and lower triangle\n    verify_trilu((3, 3), True, 0)\n    verify_trilu((3, 3), False, 0)\n    # Test larger matrices with offset.\n    verify_trilu((6, 6), True, 1)\n    verify_trilu((6, 6), False, 2)\n    verify_trilu((6, 6), False, -2)\n    # Test batch size\n    verify_trilu((8, 6, 6), False, -2)\n\n\nif __name__ == \"__main__\":\n    test_strided_slice()\n    test_concatenate()\n    test_stack()\n    test_transpose()\n    test_expand_dims()\n    test_reshape()\n    test_where()\n    test_squeeze()\n    test_split()\n    test_flip()\n    test_expand_like()\n    test_take()\n    test_gather_nd()\n    test_arange()\n    test_layout_transform()\n    test_repeat()\n    test_tile()\n    test_shape()\n    test_sequence_mask()\n    test_ndarray_size()\n    test_where_fusion()\n    test_one_hot()\n    test_unravel_index()\n    test_sparse_to_dense()\n    test_matrix_set_diag()\n    test_adv_index()\n    test_trilu()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_unique.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nimport tvm.topi.testing\n\nin_dtype = tvm.testing.parameter(\"int32\", \"int64\")\nis_sorted = tvm.testing.parameter(True, False, ids=[\"sorted\", \"unsorted\"])\nwith_counts = tvm.testing.parameter(True, False, ids=[\"with_counts\", \"no_counts\"])\narr_size, maxval = tvm.testing.parameters((1, 100), (10, 10), (10000, 100))\n\n\n@tvm.testing.parametrize_targets\ndef test_unique(dev, target, in_dtype, is_sorted, with_counts, arr_size, maxval):\n    def calc_numpy_unique(data, is_sorted=False):\n        uniq, index, inverse, counts = np.unique(\n            data, return_index=True, return_inverse=True, return_counts=True\n        )\n        num_uniq = np.array([len(uniq)]).astype(\"int32\")\n        if not is_sorted:\n            order = np.argsort(index)\n            index = np.sort(index)\n            reverse_order = np.argsort(order)\n            uniq = uniq[order].astype(data.dtype)\n            inverse = np.array([reverse_order[i] for i in inverse]).astype(\"int32\")\n            counts = counts[order].astype(\"int32\")\n        return [\n            uniq.astype(data.dtype),\n            index.astype(\"int32\"),\n            inverse.astype(\"int32\"),\n            counts,\n            num_uniq,\n        ]\n\n    data = np.random.randint(0, maxval, size=(arr_size)).astype(in_dtype)\n\n    # numpy reference\n    np_unique, np_indices, np_inverse_indices, np_counts, np_num_unique = calc_numpy_unique(\n        data, is_sorted\n    )\n    num_unique = np_num_unique[0]\n\n    implementations = {\n        \"generic\": (\n            lambda x, return_counts: topi.unique(x, is_sorted, return_counts),\n            topi.generic.schedule_unique,\n        ),\n        \"gpu\": (\n            lambda x, return_counts: topi.cuda.unique(x, is_sorted, return_counts),\n            topi.cuda.schedule_scan,\n        ),\n        \"nvptx\": (\n            lambda x, return_counts: topi.cuda.unique(x, is_sorted, return_counts),\n            topi.cuda.schedule_scan,\n        ),\n    }\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, implementations)\n    tvm_data = tvm.nd.array(data, device=dev)\n    tvm_unique = tvm.nd.array(np.zeros(data.shape).astype(data.dtype), device=dev)\n    tvm_indices = tvm.nd.array(np.zeros(data.shape).astype(\"int32\"), device=dev)\n    tvm_inverse_indices = tvm.nd.array(np.zeros(data.shape).astype(\"int32\"), device=dev)\n    tvm_num_unique = tvm.nd.array(np.zeros([1]).astype(\"int32\"), device=dev)\n\n    with tvm.target.Target(target):\n        te_input = tvm.te.placeholder(shape=data.shape, dtype=str(data.dtype))\n        outs = fcompute(te_input, with_counts)\n        s = fschedule(outs)\n        func = tvm.build(s, [te_input, *outs])\n\n        if with_counts:\n            tvm_counts = tvm.nd.array(np.zeros(data.shape).astype(\"int32\"), device=dev)\n            func(\n                tvm_data,\n                tvm_unique,\n                tvm_indices,\n                tvm_inverse_indices,\n                tvm_num_unique,\n                tvm_counts,\n            )\n        else:\n            func(tvm_data, tvm_unique, tvm_indices, tvm_inverse_indices, tvm_num_unique)\n\n    num_unique = np_num_unique[0]\n    assert tvm_num_unique.numpy()[0] == np_num_unique\n\n    np.testing.assert_allclose(tvm_unique.numpy()[:num_unique], np_unique, atol=1e-5, rtol=1e-5)\n    np.testing.assert_allclose(tvm_indices.numpy()[:num_unique], np_indices, atol=1e-5, rtol=1e-5)\n\n    np.testing.assert_allclose(\n        tvm_inverse_indices.numpy(), np_inverse_indices, atol=1e-5, rtol=1e-5\n    )\n\n    if with_counts:\n        np.testing.assert_allclose(tvm_counts.numpy()[:num_unique], np_counts, atol=1e-5, rtol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_upsampling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for upsampling\"\"\"\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\nimport math\nfrom tvm.topi.utils import nchw_pack_layout\n\n\ndef verify_upsampling(\n    batch,\n    in_channel,\n    in_height,\n    in_width,\n    scale_h,\n    scale_w,\n    layout=\"NCHW\",\n    method=\"nearest_neighbor\",\n    in_batch_block=0,\n    in_channel_block=0,\n):\n    if layout == \"NCHW\":\n        A = te.placeholder((batch, in_channel, in_height, in_width), name=\"A\")\n        dtype = A.dtype\n        out_shape = (\n            batch,\n            in_channel,\n            int(round(in_height * scale_h)),\n            int(round(in_width * scale_w)),\n        )\n        a_np = np.random.uniform(size=(batch, in_channel, in_height, in_width)).astype(dtype)\n    elif nchw_pack_layout(layout):\n        A = te.placeholder(\n            (batch, in_channel, in_height, in_width, in_batch_block, in_channel_block), name=\"A\"\n        )\n        dtype = A.dtype\n        out_shape = (\n            batch,\n            in_channel,\n            int(round(in_height * scale_h)),\n            int(round(in_width * scale_w)),\n            in_batch_block,\n            in_channel_block,\n        )\n        a_np = np.random.uniform(\n            size=(batch, in_channel, in_height, in_width, in_batch_block, in_channel_block)\n        ).astype(dtype)\n    elif layout == \"NHWC\":\n        A = te.placeholder((batch, in_height, in_width, in_channel), name=\"A\")\n        dtype = A.dtype\n        out_shape = (\n            batch,\n            int(round(in_height * scale_h)),\n            int(round(in_width * scale_w)),\n            in_channel,\n        )\n        a_np = np.random.uniform(size=(batch, in_height, in_width, in_channel)).astype(dtype)\n    else:\n        raise NotImplementedError(\"Layout not supported {} \".format(layout))\n\n    B = topi.nn.upsampling(A, scale_h, scale_w, layout=layout, method=method, align_corners=False)\n\n    b_np = tvm.topi.testing.resize2d_python(\n        a_np,\n        (scale_h, scale_w),\n        layout,\n        method[2:] if method[0:2] == \"bi\" else method,\n        \"asymmetric\",\n    )\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5, atol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\ndef test_int_div_upsampling():\n    \"\"\"Test whether upsampling op is tilable when scale_h and scale_w is integer.\n\n    Compute_at cannot work correctly in the original floating-point multiplication.\n    After using integer division,compute_at can work correctly and reduce the\n    capacity of cache buffer.\n\n    In this test case, scale_h and scale_w are set to integers, the size\n    of cache buffer should be equal to (h_i/scale_h * w_i/scale_w * c_i).\n    \"\"\"\n    dtype = \"int8\"\n    scale_h = 2\n    scale_w = 2\n\n    x = te.placeholder([1, 32, 64, 64], dtype, \"x\")\n    y = topi.nn.upsampling(x, scale_h, scale_w)\n    func = te.create_prim_func([x, y])\n\n    s = tvm.tir.Schedule(func)\n    block = s.get_block(\"resize\")\n    cache = s.cache_read(block, 0, \"local\")\n    n, c, h, w = s.get_loops(block)\n    s_factor = 8\n    c_o, c_i = s.split(c, factors=[None, s_factor])\n    h_o, h_i = s.split(h, factors=[None, s_factor])\n    w_o, w_i = s.split(w, factors=[None, s_factor])\n    s.reorder(n, c_o, h_o, w_o, h_i, w_i, c_i)\n    s.compute_at(cache, w_o)\n    wanted_rt = s_factor**3 / (scale_h * scale_w)\n\n    def analyze_upsampling_allocate(stmt):\n        if isinstance(stmt, tvm.tir.stmt.Allocate):\n            tvm.testing.assert_allclose(stmt.extents[0].value, wanted_rt)\n\n    lowerd_irmodule = tvm.lower(s.mod[\"main\"])\n    tvm.tir.stmt_functor.post_order_visit(\n        lowerd_irmodule.functions.items()[0][1].body, analyze_upsampling_allocate\n    )\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling():\n    # nearest_neighbor - NCHW\n    verify_upsampling(8, 16, 32, 32, 2.0, 2.0)\n    verify_upsampling(2, 32, 64, 64, 3.0, 3.0)\n    verify_upsampling(1, 64, 22, 32, 1.954545497894287, 2.0)\n\n    ## nearest_neighbor - NHWC\n    verify_upsampling(8, 16, 32, 32, 2.0, 2.0, layout=\"NHWC\")\n    verify_upsampling(2, 32, 64, 64, 3.0, 3.0, layout=\"NHWC\")\n    verify_upsampling(1, 64, 22, 32, 1.954545497894287, 2.0, layout=\"NHWC\")\n\n    # bilinear - NCHW\n    verify_upsampling(2, 2, 32, 32, 2.0, 2.0, method=\"bilinear\")\n    verify_upsampling(2, 2, 32, 32, 3.0, 3.0, method=\"bilinear\")\n    verify_upsampling(1, 64, 22, 32, 1.954545497894287, 2.0, method=\"bilinear\")\n\n    # nearest_neighbor - NCHWinic\n    verify_upsampling(2, 2, 32, 32, in_batch_block=4, in_channel_block=8, scale_h=2.0, scale_w=2.0)\n    verify_upsampling(2, 2, 64, 64, in_batch_block=1, in_channel_block=16, scale_h=3.0, scale_w=3.0)\n    verify_upsampling(\n        1, 4, 22, 32, in_batch_block=1, in_channel_block=16, scale_h=1.954545497894287, scale_w=2.0\n    )\n\n    # bilinear - NCHWinic\n    verify_upsampling(\n        2,\n        2,\n        32,\n        32,\n        in_batch_block=1,\n        in_channel_block=1,\n        scale_h=2.0,\n        scale_w=2.0,\n        method=\"bilinear\",\n    )\n    verify_upsampling(\n        2,\n        2,\n        32,\n        32,\n        in_batch_block=1,\n        in_channel_block=1,\n        scale_h=3.0,\n        scale_w=3.0,\n        method=\"bilinear\",\n    )\n    verify_upsampling(\n        2,\n        4,\n        22,\n        32,\n        in_batch_block=1,\n        in_channel_block=16,\n        scale_h=1.954545497894287,\n        scale_w=2.0,\n        layout=\"NCHW1n16c\",\n        method=\"bilinear\",\n    )\n\n    # bilinear - NHWC\n    verify_upsampling(2, 2, 32, 32, 2.0, 2.0, layout=\"NHWC\", method=\"bilinear\")\n    verify_upsampling(2, 2, 32, 32, 3.0, 3.0, layout=\"NHWC\", method=\"bilinear\")\n    verify_upsampling(1, 64, 22, 32, 3.0, 3.0, layout=\"NHWC\", method=\"bilinear\")\n\n\ndef verify_upsampling3d(\n    batch,\n    in_channel,\n    in_depth,\n    in_height,\n    in_width,\n    scale_d,\n    scale_h,\n    scale_w,\n    layout=\"NCDHW\",\n    method=\"nearest_neighbor\",\n):\n    if layout == \"NCDHW\":\n        A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name=\"A\")\n        dtype = A.dtype\n        out_shape = (\n            batch,\n            in_channel,\n            int(round(in_depth * scale_d)),\n            int(round(in_height * scale_h)),\n            int(round(in_width * scale_w)),\n        )\n        a_np = np.random.uniform(size=(batch, in_channel, in_depth, in_height, in_width)).astype(\n            dtype\n        )\n    elif layout == \"NDHWC\":\n        A = te.placeholder((batch, in_depth, in_height, in_width, in_channel), name=\"A\")\n        dtype = A.dtype\n        out_shape = (\n            batch,\n            int(round(in_depth * scale_d)),\n            int(round(in_height * scale_h)),\n            int(round(in_width * scale_w)),\n            in_channel,\n        )\n        a_np = np.random.uniform(size=(batch, in_depth, in_height, in_width, in_channel)).astype(\n            dtype\n        )\n    else:\n        raise NotImplementedError(\"Layout not supported {} \".format(layout))\n\n    B = topi.nn.upsampling3d(\n        A,\n        scale_d,\n        scale_h,\n        scale_w,\n        layout=layout,\n        method=method,\n        coordinate_transformation_mode=\"asymmetric\",\n    )\n\n    b_np = tvm.topi.testing.resize3d_python(\n        a_np,\n        (scale_d, scale_h, scale_w),\n        layout,\n        method[3:] if method[0:3] == \"tri\" else method,\n        \"asymmetric\",\n    )\n\n    def check_target(target, dev):\n        print(\"Running on target: %s\" % target)\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_injective_schedule(target)(B)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros(out_shape, dtype=dtype), dev)\n        f = tvm.build(s, [A, B], target)\n        f(a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5, atol=1e-5)\n\n    for target, dev in tvm.testing.enabled_targets():\n        check_target(target, dev)\n\n\n@tvm.testing.uses_gpu\ndef test_upsampling3d():\n    # nearest_neighbor - NCDHW\n    verify_upsampling3d(8, 8, 16, 16, 16, 2.0, 2.0, 2.0)\n    verify_upsampling3d(2, 16, 32, 32, 32, 3.0, 3.0, 3.0)\n    verify_upsampling3d(1, 8, 11, 16, 6, 1.954545497894287, 2.0, 1.5)\n\n    ## nearest_neighbor - NDHWC\n    verify_upsampling3d(8, 8, 16, 16, 16, 2.0, 2.0, 2.0, layout=\"NDHWC\")\n    verify_upsampling3d(2, 16, 32, 32, 32, 3.0, 3.0, 3.0, layout=\"NDHWC\")\n    verify_upsampling3d(1, 8, 11, 16, 6, 1.954545497894287, 2.0, 1.5, layout=\"NDHWC\")\n\n    # trilinear - NCDHW\n    verify_upsampling3d(2, 2, 16, 16, 16, 2.0, 2.0, 2.0, method=\"trilinear\")\n    verify_upsampling3d(2, 2, 32, 32, 32, 3.0, 3.0, 3.0, method=\"trilinear\")\n    verify_upsampling3d(1, 2, 11, 16, 6, 1.954545497894287, 2.0, 1.5, method=\"trilinear\")\n\n    # trilinear - NDHWC\n    verify_upsampling3d(2, 2, 16, 16, 16, 2.0, 2.0, 2.0, layout=\"NDHWC\", method=\"trilinear\")\n    verify_upsampling3d(2, 2, 32, 32, 32, 3.0, 3.0, 3.0, layout=\"NDHWC\", method=\"trilinear\")\n    verify_upsampling3d(\n        1, 2, 11, 16, 6, 1.954545497894287, 2.0, 1.5, layout=\"NDHWC\", method=\"trilinear\"\n    )\n\n\nif __name__ == \"__main__\":\n    test_upsampling()\n    test_upsampling3d()\n    test_int_div_upsampling()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_util.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for util\"\"\"\n\nfrom tvm import topi\n\n\ndef verify_get_shape(src_shape, src_layout, dst_layout, expect_shape):\n    dst_shape = topi.utils.get_shape(src_shape, src_layout, dst_layout)\n    assert dst_shape == expect_shape, \"Shape mismatch: expecting %s but got %s\" % (\n        expect_shape,\n        dst_shape,\n    )\n\n\ndef test_get_shape():\n    verify_get_shape((1, 3, 224, 224), \"NCHW\", \"NCHW\", (1, 3, 224, 224))\n    verify_get_shape((1, 3, 224, 224), \"NCHW\", \"NHWC\", (1, 224, 224, 3))\n    verify_get_shape((3, 2, 32, 48, 16), \"NCHW16c\", \"NC16cWH\", (3, 2, 16, 48, 32))\n    verify_get_shape((2, 3, 32, 32, 16, 8), \"OIHW16i8o\", \"HWO8oI16i\", (32, 32, 2, 8, 3, 16))\n\n\nif __name__ == \"__main__\":\n    test_get_shape()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/topi/python/test_topi_vision.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for vision package\"\"\"\nimport math\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\n\nfrom tvm import te, topi\nfrom tvm.topi.vision import ssd, non_max_suppression, get_valid_counts\n\n_get_valid_counts_implement = {\n    \"generic\": (topi.vision.get_valid_counts, topi.generic.schedule_get_valid_counts),\n    \"gpu\": (topi.cuda.get_valid_counts, topi.cuda.schedule_get_valid_counts),\n}\n\n_nms_implement = {\n    \"generic\": (topi.vision.non_max_suppression, topi.generic.schedule_nms),\n    \"gpu\": (topi.cuda.non_max_suppression, topi.cuda.schedule_nms),\n}\n\n_multibox_prior_implement = {\n    \"generic\": (topi.vision.ssd.multibox_prior, topi.generic.schedule_multibox_prior),\n    \"gpu\": (topi.cuda.multibox_prior, topi.cuda.schedule_multibox_prior),\n}\n\n_multibox_detection_implement = {\n    \"generic\": (topi.vision.ssd.multibox_detection, topi.generic.schedule_multibox_detection),\n    \"gpu\": (topi.cuda.multibox_detection, topi.cuda.schedule_multibox_detection),\n}\n\n_roi_align_implement = {\n    \"generic\": (topi.vision.roi_align_nchw, topi.generic.schedule_roi_align),\n    \"cpu\": (topi.x86.roi_align_nchw, topi.generic.schedule_roi_align),\n    \"gpu\": (topi.vision.roi_align_nchw, topi.cuda.schedule_roi_align),\n}\n\n_roi_pool_schedule = {\n    \"generic\": topi.generic.schedule_roi_pool,\n    \"gpu\": topi.cuda.schedule_roi_pool,\n}\n\n_proposal_implement = {\n    \"generic\": (topi.vision.rcnn.proposal, topi.generic.schedule_proposal),\n    \"gpu\": (topi.cuda.proposal, topi.cuda.schedule_proposal),\n}\n\n_all_class_nms_implement = {\n    \"generic\": (topi.vision.all_class_non_max_suppression, topi.generic.schedule_nms),\n    \"gpu\": (topi.cuda.all_class_non_max_suppression, topi.cuda.schedule_nms),\n}\n\n\nclass TestValidCounts:\n    dshape, score_threshold, id_index, score_index = tvm.testing.parameters(\n        ((1, 1000, 5), 0.5, -1, 0),\n        ((1, 2500, 6), 0, 0, 1),\n        ((1, 2500, 5), -1, -1, 0),\n        ((3, 1000, 6), 0.55, 1, 0),\n        ((16, 500, 5), 0.95, -1, 1),\n    )\n    dtype = tvm.testing.parameter(\"float32\")\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(self, dtype, dshape, score_threshold, id_index, score_index):\n        batch_size, num_anchor, elem_length = dshape\n        np_data = np.random.uniform(low=-2, high=2, size=dshape).astype(dtype)\n        np_out1 = np.zeros(shape=(batch_size,))\n        np_out2 = np.zeros(shape=dshape).astype(dtype)\n        np_out3 = np.zeros(shape=(batch_size, num_anchor))\n        for i in range(batch_size):\n            np_out1[i] = 0\n            inter_idx = 0\n            for j in range(num_anchor):\n                score = np_data[i, j, score_index]\n                if score > score_threshold and (id_index < 0 or np_data[i, j, id_index] >= 0):\n                    for k in range(elem_length):\n                        np_out2[i, inter_idx, k] = np_data[i, j, k]\n                    np_out1[i] += 1\n                    np_out3[i, inter_idx] = j\n                    inter_idx += 1\n                if j >= np_out1[i]:\n                    for k in range(elem_length):\n                        np_out2[i, j, k] = -1.0\n                    np_out3[i, j] = -1\n\n        return np_data, np_out1, np_out2, np_out3\n\n    def test_get_valid_counts(\n        self, target, dev, ref_data, dtype, dshape, score_threshold, id_index, score_index\n    ):\n        np_data, np_out1, np_out2, np_out3 = ref_data\n\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _get_valid_counts_implement)\n            data = te.placeholder(dshape, name=\"data\", dtype=dtype)\n            outs = fcompute(data, score_threshold, id_index, score_index)\n            s = fschedule(outs)\n\n        tvm_input_data = tvm.nd.array(np_data, dev)\n        tvm_out1 = tvm.nd.array(np.zeros(np_out1.shape, dtype=\"int32\"), dev)\n        tvm_out2 = tvm.nd.array(np.zeros(np_out2.shape, dtype=dtype), dev)\n        tvm_out3 = tvm.nd.array(np.zeros(np_out3.shape, dtype=\"int32\"), dev)\n\n        f = tvm.build(s, [data, outs[0], outs[1], outs[2]], target)\n        f(tvm_input_data, tvm_out1, tvm_out2, tvm_out3)\n        tvm.testing.assert_allclose(tvm_out1.numpy(), np_out1, rtol=1e-3)\n        tvm.testing.assert_allclose(tvm_out2.numpy(), np_out2, rtol=1e-3)\n        tvm.testing.assert_allclose(tvm_out3.numpy(), np_out3, rtol=1e-3)\n\n\ndef verify_non_max_suppression(\n    target,\n    dev,\n    np_data,\n    np_valid_count,\n    np_indices,\n    np_result,\n    np_indices_result,\n    max_output_size,\n    iou_threshold,\n    force_suppress,\n    top_k,\n    coord_start,\n    score_index,\n    id_index,\n):\n    dshape = np_data.shape\n    batch, num_anchors, _ = dshape\n    indices_dshape = (batch, num_anchors)\n    data = te.placeholder(dshape, name=\"data\")\n    valid_count = te.placeholder((batch,), dtype=\"int32\", name=\"valid_count\")\n    indices = te.placeholder((batch, num_anchors), dtype=\"int32\", name=\"indices\")\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _nms_implement)\n        out = fcompute(\n            data,\n            valid_count,\n            indices,\n            max_output_size,\n            iou_threshold,\n            force_suppress,\n            top_k,\n            coord_start=coord_start,\n            score_index=score_index,\n            id_index=id_index,\n            return_indices=False,\n        )\n        indices_out = fcompute(\n            data,\n            valid_count,\n            indices,\n            max_output_size,\n            iou_threshold,\n            force_suppress,\n            top_k,\n            coord_start=coord_start,\n            score_index=score_index,\n            id_index=id_index,\n            return_indices=True,\n        )\n        s = fschedule(out)\n        indices_s = fschedule(indices_out)\n\n    tvm_data = tvm.nd.array(np_data, dev)\n    tvm_valid_count = tvm.nd.array(np_valid_count, dev)\n    tvm_indices = tvm.nd.array(np_indices, dev)\n\n    tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), dev)\n    f = tvm.build(s, [data, valid_count, indices, out], target)\n    f(tvm_data, tvm_valid_count, tvm_indices, tvm_out)\n    tvm.testing.assert_allclose(tvm_out.numpy(), np_result, rtol=1e-4)\n\n    tvm_indices_out = tvm.nd.array(np.zeros(indices_dshape, dtype=\"int32\"), dev)\n    f = tvm.build(indices_s, [data, valid_count, indices, indices_out[0]], target)\n    f(tvm_data, tvm_valid_count, tvm_indices, tvm_indices_out)\n    tvm.testing.assert_allclose(tvm_indices_out.numpy(), np_indices_result, rtol=1e-4)\n\n\ndef test_non_max_suppression(target, dev):\n    np_data = np.array(\n        [\n            [\n                [0, 0.8, 1, 20, 25, 45],\n                [1, 0.7, 30, 60, 50, 80],\n                [0, 0.4, 4, 21, 19, 40],\n                [2, 0.9, 35, 61, 52, 79],\n                [1, 0.5, 100, 60, 70, 110],\n            ]\n        ]\n    ).astype(\"float32\")\n    np_valid_count = np.array([4]).astype(\"int32\")\n    np_indices = np.array([[0, 1, 2, 3, 4]]).astype(\"int32\")\n    max_output_size = -1\n    np_result = np.array(\n        [\n            [\n                [2, 0.9, 35, 61, 52, 79],\n                [0, 0.8, 1, 20, 25, 45],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1, -1],\n            ]\n        ]\n    )\n    np_indices_result = np.array([[3, 0, -1, -1, -1]])\n\n    verify_non_max_suppression(\n        target,\n        dev,\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_result,\n        np_indices_result,\n        max_output_size,\n        0.7,\n        True,\n        2,\n        2,\n        1,\n        0,\n    )\n\n    np_data = np.array(\n        [\n            [\n                [0.8, 1, 20, 25, 45],\n                [0.7, 30, 60, 50, 80],\n                [0.4, 4, 21, 19, 40],\n                [0.9, 35, 61, 52, 79],\n                [0.5, 100, 60, 70, 110],\n            ]\n        ]\n    ).astype(\"float32\")\n    np_valid_count = np.array([4]).astype(\"int32\")\n    np_indices = np.array([[0, 1, 2, 3, 4]]).astype(\"int32\")\n    max_output_size = 2\n    np_result = np.array(\n        [\n            [\n                [0.9, 35, 61, 52, 79],\n                [0.8, 1, 20, 25, 45],\n                [-1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1],\n                [-1, -1, -1, -1, -1],\n            ]\n        ]\n    )\n    np_indices_result = np.array([[3, 0, -1, -1, -1]])\n    verify_non_max_suppression(\n        target,\n        dev,\n        np_data,\n        np_valid_count,\n        np_indices,\n        np_result,\n        np_indices_result,\n        max_output_size,\n        0.7,\n        False,\n        2,\n        1,\n        0,\n        -1,\n    )\n\n\nclass TestMultiboxPrior:\n    dshape, sizes, ratios, steps, offsets, clip = tvm.testing.parameters(\n        ((1, 3, 50, 50), (1,), (1,), (-1, -1), (0.5, 0.5), False),\n        ((1, 3, 224, 224), (0.5, 0.25, 0.1), (1, 2, 0.5), (-1, -1), (0.5, 0.5), False),\n        ((1, 32, 32, 32), (0.5, 0.25), (1, 2), (2, 2), (0.5, 0.5), True),\n    )\n\n    dtype = tvm.testing.parameter(\"float32\")\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(self, dtype, dshape, sizes, ratios, offsets, steps, clip):\n        in_height = dshape[2]\n        in_width = dshape[3]\n        num_sizes = len(sizes)\n        num_ratios = len(ratios)\n        size_ratio_concat = sizes + ratios\n        steps_h = steps[0] if steps[0] > 0 else 1.0 / in_height\n        steps_w = steps[1] if steps[1] > 0 else 1.0 / in_width\n        offset_h = offsets[0]\n        offset_w = offsets[1]\n\n        out_shape = (1, in_height * in_width * (num_sizes + num_ratios - 1), 4)\n\n        np_in = np.random.uniform(size=dshape).astype(dtype)\n        np_out = np.zeros(out_shape).astype(dtype)\n\n        for i in range(in_height):\n            center_h = (i + offset_h) * steps_h\n            for j in range(in_width):\n                center_w = (j + offset_w) * steps_w\n                for k in range(num_sizes + num_ratios - 1):\n                    w = (\n                        size_ratio_concat[k] * in_height / in_width / 2.0\n                        if k < num_sizes\n                        else size_ratio_concat[0]\n                        * in_height\n                        / in_width\n                        * math.sqrt(size_ratio_concat[k + 1])\n                        / 2.0\n                    )\n                    h = (\n                        size_ratio_concat[k] / 2.0\n                        if k < num_sizes\n                        else size_ratio_concat[0] / math.sqrt(size_ratio_concat[k + 1]) / 2.0\n                    )\n                    count = (\n                        i * in_width * (num_sizes + num_ratios - 1)\n                        + j * (num_sizes + num_ratios - 1)\n                        + k\n                    )\n                    np_out[0][count][0] = center_w - w\n                    np_out[0][count][1] = center_h - h\n                    np_out[0][count][2] = center_w + w\n                    np_out[0][count][3] = center_h + h\n        if clip:\n            np_out = np.clip(np_out, 0, 1)\n\n        return np_in, np_out\n\n    def test_multibox_prior(\n        self, target, dev, dtype, dshape, ref_data, sizes, ratios, steps, offsets, clip\n    ):\n        np_in, np_out = ref_data\n\n        data = te.placeholder(dshape, name=\"data\", dtype=dtype)\n\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _multibox_prior_implement)\n        with tvm.target.Target(target):\n            out = fcompute(data, sizes, ratios, steps, offsets, clip)\n            s = fschedule(out)\n\n        tvm_input_data = tvm.nd.array(np_in, dev)\n        tvm_out = tvm.nd.array(np.zeros(np_out.shape, dtype=dtype), dev)\n        f = tvm.build(s, [data, out], target)\n        f(tvm_input_data, tvm_out)\n        tvm.testing.assert_allclose(tvm_out.numpy(), np_out, rtol=1e-3)\n\n\ndef test_multibox_detection(target, dev):\n    batch_size = 1\n    num_anchors = 3\n    num_classes = 3\n    cls_prob = te.placeholder((batch_size, num_anchors, num_classes), name=\"cls_prob\")\n    loc_preds = te.placeholder((batch_size, num_anchors * 4), name=\"loc_preds\")\n    anchors = te.placeholder((1, num_anchors, 4), name=\"anchors\")\n\n    # Manually create test case\n    np_cls_prob = np.array([[[0.2, 0.5, 0.3], [0.25, 0.3, 0.45], [0.7, 0.1, 0.2]]])\n    np_loc_preds = np.array([[0.1, -0.2, 0.3, 0.2, 0.2, 0.4, 0.5, -0.3, 0.7, -0.2, -0.4, -0.8]])\n    np_anchors = np.array([[[-0.1, -0.1, 0.1, 0.1], [-0.2, -0.2, 0.2, 0.2], [1.2, 1.2, 1.5, 1.5]]])\n\n    expected_np_out = np.array(\n        [\n            [\n                [1, 0.69999999, 0, 0, 0.10818365, 0.10008108],\n                [0, 0.44999999, 1, 1, 1, 1],\n                [0, 0.30000001, 0, 0, 0.22903419, 0.20435292],\n            ]\n        ]\n    )\n\n    fcompute, fschedule = tvm.topi.testing.dispatch(target, _multibox_detection_implement)\n    with tvm.target.Target(target):\n        out = fcompute(cls_prob, loc_preds, anchors)\n        s = fschedule(out)\n\n    tvm_cls_prob = tvm.nd.array(np_cls_prob.astype(cls_prob.dtype), dev)\n    tvm_loc_preds = tvm.nd.array(np_loc_preds.astype(loc_preds.dtype), dev)\n    tvm_anchors = tvm.nd.array(np_anchors.astype(anchors.dtype), dev)\n    tvm_out = tvm.nd.array(np.zeros((batch_size, num_anchors, 6)).astype(out.dtype), dev)\n    f = tvm.build(s, [cls_prob, loc_preds, anchors, out], target)\n    f(tvm_cls_prob, tvm_loc_preds, tvm_anchors, tvm_out)\n    tvm.testing.assert_allclose(tvm_out.numpy(), expected_np_out, rtol=1e-4)\n\n\nclass TestRoiAlign:\n    (\n        batch,\n        in_channel,\n        in_size,\n        num_roi,\n        pooled_size,\n        spatial_scale,\n        sample_ratio,\n        mode,\n    ) = tvm.testing.parameters(\n        (1, 16, 32, 64, 7, 1.0, -1, 0),\n        (4, 16, 32, 64, 7, 0.5, 2, 0),\n        (1, 32, 32, 80, 8, 0.0625, 2, 0),\n        (1, 32, 500, 80, 8, 0.0625, 2, 0),\n        (1, 16, 32, 64, 7, 1.0, -1, 1),\n        (4, 16, 32, 64, 7, 0.5, 2, 1),\n        (1, 32, 32, 80, 8, 0.0625, 2, 1),\n        (1, 32, 500, 80, 8, 0.0625, 2, 1),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(\n        self,\n        batch,\n        in_channel,\n        in_size,\n        num_roi,\n        pooled_size,\n        spatial_scale,\n        sample_ratio,\n        mode,\n    ):\n        a_shape = (batch, in_channel, in_size, in_size)\n        rois_shape = (num_roi, 5)\n\n        a_np = np.random.uniform(-1, 1, size=a_shape).astype(\"float32\")\n        rois_np = np.random.uniform(-1, 1, size=rois_shape).astype(\"float32\") * in_size\n        rois_np[:, 0] = np.random.randint(low=0, high=batch, size=num_roi)\n        b_np = tvm.topi.testing.roi_align_nchw_python(\n            a_np,\n            rois_np,\n            pooled_size=pooled_size,\n            spatial_scale=spatial_scale,\n            sample_ratio=sample_ratio,\n            mode=mode,\n        )\n\n        return a_np, rois_np, b_np\n\n    def test_roi_align(\n        self,\n        target,\n        dev,\n        ref_data,\n        pooled_size,\n        spatial_scale,\n        sample_ratio,\n        mode,\n    ):\n        # For mode, 0 = avg, 1 = max\n        a_np, rois_np, b_np = ref_data\n\n        a = te.placeholder(a_np.shape)\n        rois = te.placeholder(rois_np.shape)\n\n        with tvm.target.Target(target):\n            fcompute, fschedule = tvm.topi.testing.dispatch(target, _roi_align_implement)\n            b = fcompute(\n                a,\n                rois,\n                pooled_size=pooled_size,\n                spatial_scale=spatial_scale,\n                sample_ratio=sample_ratio,\n                mode=mode,\n            )\n            s = fschedule(b)\n\n        tvm_a = tvm.nd.array(a_np, dev)\n        tvm_rois = tvm.nd.array(rois_np, dev)\n        tvm_b = tvm.nd.array(np.zeros(b_np.shape, dtype=b.dtype), device=dev)\n        f = tvm.build(s, [a, rois, b], target)\n        f(tvm_a, tvm_rois, tvm_b)\n        tvm_val = tvm_b.numpy()\n        tvm.testing.assert_allclose(tvm_val, b_np, rtol=1e-3, atol=1e-4)\n\n\nclass TestRoiPool:\n    batch, in_channel, in_size, num_roi, pooled_size, spatial_scale = tvm.testing.parameters(\n        (1, 4, 16, 32, 7, 1.0),\n        (4, 4, 16, 32, 7, 0.5),\n    )\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def ref_data(self, batch, in_channel, in_size, num_roi, pooled_size, spatial_scale):\n        a_shape = (batch, in_channel, in_size, in_size)\n        rois_shape = (num_roi, 5)\n\n        a_np = np.random.uniform(size=a_shape).astype(\"float32\")\n        rois_np = np.random.uniform(size=rois_shape).astype(\"float32\") * in_size\n        rois_np[:, 0] = np.random.randint(low=0, high=batch, size=num_roi).astype(\"float32\")\n\n        b_np = tvm.topi.testing.roi_pool_nchw_python(\n            a_np, rois_np, pooled_size=pooled_size, spatial_scale=spatial_scale\n        )\n        return a_np, rois_np, b_np\n\n    def test_roi_pool(self, target, dev, ref_data, pooled_size, spatial_scale):\n        a_np, rois_np, b_np = ref_data\n\n        a = te.placeholder(a_np.shape)\n        rois = te.placeholder(rois_np.shape)\n\n        with tvm.target.Target(target):\n            b = topi.vision.rcnn.roi_pool_nchw(\n                a, rois, pooled_size=pooled_size, spatial_scale=spatial_scale\n            )\n            s_func = tvm.topi.testing.dispatch(target, _roi_pool_schedule)\n            s = s_func(b)\n\n        tvm_a = tvm.nd.array(a_np, dev)\n        tvm_rois = tvm.nd.array(rois_np, dev)\n        tvm_b = tvm.nd.array(np.zeros(b_np.shape, dtype=b.dtype), device=dev)\n        f = tvm.build(s, [a, rois, b], target)\n        f(tvm_a, tvm_rois, tvm_b)\n        tvm.testing.assert_allclose(tvm_b.numpy(), b_np, rtol=1e-4)\n\n\ndef verify_proposal(target, dev, np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs):\n    cls_prob = te.placeholder(np_cls_prob.shape)\n    bbox_pred = te.placeholder(np_bbox_pred.shape)\n    im_info = te.placeholder(np_im_info.shape)\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _proposal_implement)\n        out = fcompute(cls_prob, bbox_pred, im_info, **attrs)\n        s = fschedule(out)\n        f = tvm.build(s, [cls_prob, bbox_pred, im_info, out], target)\n        tvm_cls_prob = tvm.nd.array(np_cls_prob, device=dev)\n        tvm_bbox_pred = tvm.nd.array(np_bbox_pred, device=dev)\n        tvm_im_info = tvm.nd.array(np_im_info, device=dev)\n        tvm_out = tvm.nd.empty(device=dev, shape=out.shape, dtype=out.dtype)\n        f(tvm_cls_prob, tvm_bbox_pred, tvm_im_info, tvm_out)\n        tvm.testing.assert_allclose(tvm_out.numpy(), np_out, rtol=1e-4)\n\n\n@tvm.testing.known_failing_targets(\"vulkan\")\ndef test_proposal(target, dev):\n    attrs = {\n        \"scales\": (0.5,),\n        \"ratios\": (0.5,),\n        \"feature_stride\": 16,\n        \"iou_loss\": False,\n        \"rpn_min_size\": 16,\n        \"threshold\": 0.7,\n        \"rpn_pre_nms_top_n\": 200,\n        \"rpn_post_nms_top_n\": 4,\n    }\n    np_cls_prob = np.array(\n        [\n            [\n                [[0.3, 0.6, 0.2], [0.4, 0.7, 0.5], [0.1, 0.4, 0.3]],\n                [[0.7, 0.5, 0.3], [0.6, 0.4, 0.8], [0.9, 0.2, 0.5]],\n            ]\n        ],\n        dtype=\"float32\",\n    )\n    np_bbox_pred = np.array(\n        [\n            [\n                [[0.5, 1.0, 0.6], [0.8, 1.2, 2.0], [0.9, 1.0, 0.8]],\n                [[0.5, 1.0, 0.7], [0.8, 1.2, 1.6], [2.1, 1.5, 0.7]],\n                [[1.0, 0.5, 0.7], [1.5, 0.9, 1.6], [1.4, 1.5, 0.8]],\n                [[1.0, 0.5, 0.6], [1.5, 0.9, 2.0], [1.8, 1.0, 0.9]],\n            ]\n        ],\n        dtype=\"float32\",\n    )\n    np_im_info = np.array([[48.0, 48.0, 1.0]], dtype=\"float32\")\n    np_out = np.array(\n        [\n            [0.0, 0.0, 2.8451548, 28.38012, 18.154846],\n            [0.0, 0.0, 15.354933, 41.96971, 41.245064],\n            [0.0, 18.019852, 1.0538368, 51.98015, 25.946163],\n            [0.0, 27.320923, -1.266357, 55.0, 24.666357],\n        ],\n        dtype=\"float32\",\n    )\n\n    verify_proposal(target, dev, np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs)\n\n    np_out = np.array(\n        [\n            [0.0, -5.25, -2.5, 21.75, 19.0],\n            [0.0, 11.25, -2.0, 37.25, 18.5],\n            [0.0, 26.849998, -2.3000002, 53.45, 18.6],\n            [0.0, -4.95, 13.799999, 22.25, 35.5],\n        ],\n        dtype=\"float32\",\n    )\n\n    attrs[\"iou_loss\"] = True\n    verify_proposal(target, dev, np_cls_prob, np_bbox_pred, np_im_info, np_out, attrs)\n\n\ndef verify_all_class_non_max_suppression(\n    target,\n    dev,\n    boxes_np,\n    scores_np,\n    max_output_boxes_per_class,\n    iou_threshold,\n    score_threshold,\n    expected_indices,\n):\n    dshape = boxes_np.shape\n    batch, num_boxes, _ = dshape\n    _, num_class, _ = scores_np.shape\n    boxes = te.placeholder(dshape, name=\"boxes\")\n    scores = te.placeholder(scores_np.shape, dtype=\"float32\", name=\"scores\")\n\n    with tvm.target.Target(target):\n        fcompute, fschedule = tvm.topi.testing.dispatch(target, _all_class_nms_implement)\n        out = fcompute(boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold)\n        s = fschedule(out)\n\n    tvm_boxes = tvm.nd.array(boxes_np, dev)\n    tvm_scores = tvm.nd.array(scores_np, dev)\n    selected_indices = tvm.nd.array(np.zeros((batch * num_class * num_boxes, 3), \"int64\"), dev)\n    num_detections = tvm.nd.array(np.zeros((1,), \"int64\"), dev)\n\n    f = tvm.build(s, [boxes, scores, out[0], out[1]], target)\n    f(tvm_boxes, tvm_scores, selected_indices, num_detections)\n\n    tvm_res = selected_indices.numpy()[: num_detections.numpy()[0]]\n    np.testing.assert_equal(tvm_res, expected_indices)\n\n\ndef test_all_class_non_max_suppression(target, dev):\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.0, 0.0, 0.5, 0.5],\n                [0.5, 0.5, 0.9, 0.9],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n            [\n                [0.0, 0.0, 0.3, 0.3],\n                [0.0, 0.0, 0.4, 0.4],\n                [0.5, 0.5, 0.95, 0.95],\n                [0.5, 0.5, 0.96, 0.96],\n                [0.5, 0.5, 1.0, 1.0],\n            ],\n        ]\n    ).astype(\"float32\")\n\n    scores = np.array(\n        [\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n            [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n        ]\n    ).astype(\"float32\")\n\n    max_output_boxes_per_class = 2\n    iou_threshold = 0.8\n    score_threshold = 0.0\n\n    expected = np.array(\n        [[0, 0, 4], [0, 0, 2], [0, 1, 4], [0, 1, 2], [1, 0, 4], [1, 0, 1], [1, 1, 4], [1, 1, 1]]\n    )\n\n    verify_all_class_non_max_suppression(\n        target,\n        dev,\n        boxes,\n        scores,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        expected,\n    )\n\n    boxes = np.array(\n        [\n            [\n                [0.0, 0.0, 1.0, 1.0],\n                [0.0, 0.1, 1.0, 1.1],\n                [0.0, -0.1, 1.0, 0.9],\n                [0.0, 10.0, 1.0, 11.0],\n                [0.0, 10.1, 1.0, 11.1],\n                [0.0, 100.0, 1.0, 101.0],\n            ]\n        ]\n    ).astype(np.float32)\n    scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\n    max_output_boxes_per_class = 3\n    iou_threshold = 0.5\n    score_threshold = 0.4\n\n    expected = np.array([[0, 0, 3], [0, 0, 0]])\n\n    verify_all_class_non_max_suppression(\n        target,\n        dev,\n        boxes,\n        scores,\n        max_output_boxes_per_class,\n        iou_threshold,\n        score_threshold,\n        expected,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_aot_legalize_packed_call.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n\n@tvm.script.ir_module\nclass Module:\n    @T.prim_func\n    def tvm_test_cpacked(\n        A: T.handle, B: T.handle, C: T.handle, device_context: T.handle\n    ) -> T.handle:\n        A_0 = T.match_buffer(A, (1,), dtype=\"float32\")\n        T.preflattened_buffer(A_0, (1,), dtype=\"float32\")\n        B_0 = T.match_buffer(B, (1,), dtype=\"float32\")\n        T.preflattened_buffer(B_0, (1,), dtype=\"float32\")\n        C_0 = T.match_buffer(C, (1,), dtype=\"float32\")\n        T.preflattened_buffer(C_0, (1,), dtype=\"float32\")\n        T.evaluate(C)\n\n    @T.prim_func\n    def tir_packed_call() -> None:\n        A = T.var(\"handle\")\n        B = T.var(\"handle\")\n        C = T.var(\"handle\")\n        device_context = T.var(\"handle\")\n        # body\n        T.evaluate(\n            T.tvm_call_cpacked(\n                \"tvm_test_cpacked\",\n                A,\n                B,\n                C,\n                device_context,\n                dtype=\"int32\",\n            )\n        )\n\n\n@tvm.script.ir_module\nclass Expected:\n    @T.prim_func\n    def tvm_test_cpacked(\n        A: T.handle, B: T.handle, C: T.handle, device_context: T.handle\n    ) -> T.handle:\n        A_0 = T.match_buffer(A, (1,), dtype=\"float32\")\n        T.preflattened_buffer(A_0, (1,), dtype=\"float32\")\n        B_0 = T.match_buffer(B, (1,), dtype=\"float32\")\n        T.preflattened_buffer(B_0, (1,), dtype=\"float32\")\n        C_0 = T.match_buffer(C, (1,), dtype=\"float32\")\n        T.preflattened_buffer(C_0, (1,), dtype=\"float32\")\n        T.evaluate(C)\n\n    @T.prim_func\n    def tir_packed_call() -> None:\n        A = T.var(\"handle\")\n        B = T.var(\"handle\")\n        C = T.var(\"handle\")\n        device_context = T.var(\"handle\")\n\n        # body\n        T.evaluate(\n            T.tvm_call_cpacked(\n                \"tvm_test_cpacked\",\n                T.tvm_stack_make_array(\n                    A,\n                    T.tvm_stack_make_shape(1, dtype=\"handle\"),\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    T.uint32(1),\n                    T.Cast(\"float32\", 0),\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    B,\n                    T.tvm_stack_make_shape(1, dtype=\"handle\"),\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    T.uint32(1),\n                    T.Cast(\"float32\", 0),\n                    0,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    C,\n                    T.tvm_stack_make_shape(1, dtype=\"handle\"),\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    T.uint32(1),\n                    T.Cast(\"float32\", 0),\n                    0,\n                    dtype=\"handle\",\n                ),\n                device_context,\n                dtype=\"int32\",\n            )\n        )\n\n\ndef test_aot_packed_call():\n    mod = Module\n    expected = Expected\n    out = tir.transform.LegalizePackedCalls()(mod)\n    tvm.ir.assert_structural_equal(expected, out, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_canonical_simplify.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\nclass CanonicalChecker:\n    def __init__(self):\n        self.analyzer = tvm.arith.Analyzer()\n\n    def verify(self, data, expected):\n        res = self.analyzer.canonical_simplify(data)\n        expected = tvm.runtime.convert(expected)\n        assert tvm.ir.structural_equal(res, expected), \"\\ndata={}\\nres={}\\nexpected={}\".format(\n            data, res, expected\n        )\n\n\ndef test_mul_sum_simplify():\n    ck = CanonicalChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n\n    ck.verify(2 + (3 * x + z + y + 1) * 4 + x, x * 13 + z * 4 + y * 4 + 6)\n    ck.verify(x * 3 - 4 * x + 1, 1 - x)\n    ck.verify(y + x * 3 - 5 * x + 1 + y, y * 2 + 1 - x * 2)\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # trucdiv\n    ck.verify(tdiv(x + y + x + y * 3, 2), y * 2 + x)\n    ck.verify(tmod(x + y + x + y * 3, 2), 0)\n\n    # floordiv\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck.verify(flm(x + x + y * 3, 2), flm(y * 3, 2))\n    ck.verify(fld(x + y + x + y * 3, 2), y * 2 + x)\n    ck.verify(flm(x + y + x + y * 3, 2), 0)\n    ck.verify(fld(x + x + y * 3, 2), fld(y * 3, 2) + x)\n\n\ndef test_split_index_simplify():\n    ck = CanonicalChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n\n    # trucdiv\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n\n    # split div const\n    ck.verify(tdiv(x, 3) * 3 + tmod(x, 3), x)\n    ck.verify(tdiv(x, 6) * 6 + tmod(tdiv(x, 3), 2) * 3 + tmod(x, 3), x)\n    ck.verify(tdiv(tdiv(tmod(x, 16), 2) * 2, 4), tdiv(tmod(x, 16), 4))\n    ck.verify(tdiv(tmod(x, 2), 8), 0)\n    ck.verify(tdiv(tmod(x, 2), 7), 0)\n    ck.verify(tdiv(tdiv(tmod(x, 16), 2) * 2, 6), tdiv(tmod(x, 16), 6))\n\n    # split mod const\n    ck.verify(tmod((x * 8), 16), tmod(x, 2) * 8)\n    ck.verify(tmod(x * 8, 2), 0)\n\n    # simplify then fold\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000))\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 1000))\n    ck.verify(tdiv(x * 4 + y, 2) * 2 + tmod(x * 4 + y, 2), x * 4 + y)\n    # complex fold\n    ck.verify(tdiv(z * 9 + y, 2) * 2 + tmod(z * 9 + y, 2), z * 9 + y)\n\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-100, 1000), True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(-100, 1000), True)\n    ck.verify(tdiv(x * 4 + y, 2) * 2 + tmod(x * 4 + y, 2), x * 4 + y)\n\n    # floordiv\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck.verify(fld(x * 5, 2), fld(x * 5, 2))\n    ck.verify(fld(x, 3) * 3 + flm(x, 3), x)\n    ck.verify(fld(x, 6) * 6 + flm(fld(x, 3), 2) * 3 + flm(x, 3), x)\n    ck.verify(fld(fld(flm(x, 16), 2) * 2, 4), fld(flm(x, 16), 4))\n    ck.verify(fld(flm(x, 2), 8), 0)\n    ck.verify(fld(flm(x, 2), 7), 0)\n    ck.verify(fld(fld(flm(x, 16), 2) * 2, 6), fld(flm(x, 16), 6))\n\n    # cannot simplify mixed case, unless we canonicalize into one mode.\n    ck.verify(tdiv(x, 6) * 2 + tmod(fld(x, 3), 2), tdiv(x, 6) * 2 + tmod(fld(x, 3), 2))\n\n    ck.verify(tmod(-x, 2), tmod(x, -2) * -1)\n\n\ndef test_div_simplify():\n    ck = CanonicalChecker()\n    x = te.var(\"x\")\n    tdiv = tvm.tir.truncdiv\n\n    # truc div\n    ck.verify(tdiv(16 + 48 * x, 16), x * 3 + 1)\n    # (17+48*x)/16 is not simplifiable for arbitrary x because when 17+48*x<0\n    # (17+48*x)/16 != 1+3*x\n    ck.verify(tdiv(17 + 48 * x, 16), tdiv(x * 48 + 17, 16))\n    # However, when x >= 0, then 17+48*x >= 0 and (17+48*x)/16 can be simplified\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 10))\n    ck.verify(tdiv(17 + 48 * x, 16), x * 3 + 1)\n    # Trying expressions that are not simplifiable for any values of the variables\n    ck.verify(tdiv(17 + 47 * x, 16), tdiv(x * 47 + 17, 16))\n\n    # floordiv\n    fld = tvm.te.floordiv\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-1000, 10000), True)\n    ck.verify(fld(16 + 48 * x, 16), x * 3 + 1)\n    ck.verify(fld(17 + 48 * x, 16), x * 3 + 1)\n    ck.verify(fld(17 + 47 * x, 16), fld(x * 47 + 17, 16))\n\n\ndef test_floormod_simplify():\n    ck = CanonicalChecker()\n    flm = tvm.te.floormod\n    x, y = te.var(\"x\"), te.var(\"y\")\n    ck.verify(flm(flm((x * 4) + y - 466036, 24528) - 24512, 16), flm((x * 4) + y + 12, 16))\n    ck.verify(flm(flm((x * 4), 16), 8), flm(x, 2) * 4)\n\n    ck.verify(flm(-x, 2), flm(x, -2) * -1)\n\n\ndef test_canonical_mixed():\n    ck = CanonicalChecker()\n    x = te.var(\"x\")\n    z = tvm.tir.const(3, \"int32\")\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    ck.verify(tdiv(x, (z * z)) - tdiv(x, (z * z)), 0)\n    ck.verify(tdiv(x, (z + z)) - tdiv(x, (z + z)), 0)\n    ck.verify(x - 2 < 3, x < 5)\n    ck.verify(tvm.te.max(x, 1) - tvm.te.max(x, 1), 0)\n    ck.verify(tvm.te.min(x, 1) - tvm.te.min(x, 1), 0)\n    ck.verify(x * x - x * x, 0)\n    ck.verify(tmod(tdiv(tmod(x, 20), 2) * 2, 4), tdiv(tmod(x, 4), 2) * 2)\n\n    fld = tvm.te.floordiv\n    ck.verify(fld(x, (z * z)) - fld(x, (z * z)), 0)\n    ck.verify(fld(x, (z + z)) - fld(x, (z + z)), 0)\n\n\ndef test_reduce_combiner_simplify():\n    ck = CanonicalChecker()\n    dummy = te.var(\"dummy\")\n    comm_reducer = te.comm_reducer\n    prod = comm_reducer(lambda x, y: x * y, lambda t0: tvm.tir.const(1, t0))\n\n    sum_or_prod = comm_reducer(\n        lambda x, y: tvm.tir.Select(dummy < 0, x + y, x * y),\n        lambda t0: tvm.tir.Select(dummy < 0, tvm.tir.const(0, t0), tvm.tir.const(1, t0)),\n    )\n    sum_and_prod = comm_reducer(\n        lambda x, y: (x[0] + y[0], x[1] * y[1]),\n        lambda t0, t1: (tvm.tir.const(0, t0), tvm.tir.const(5, t1) - tvm.tir.const(4, t1)),\n    )\n    some_reducer1 = comm_reducer(\n        lambda x, y: (\n            x[0] + y[0],\n            x[0] + y[0] + x[1] + y[1],\n            x[0] * y[2] + y[0] * x[2],\n            x[1] + y[2],\n            4.0,\n        ),\n        lambda t0, t1, t2, t3, t4: (\n            tvm.tir.const(0, t0),\n            tvm.tir.const(1, t1),\n            tvm.tir.const(2, t2),\n            tvm.tir.const(3, t3),\n            tvm.tir.const(4, t4),\n        ),\n    )\n\n    k = te.reduce_axis((0, 10), name=\"k\")\n    A = te.placeholder((10,), name=\"A\")\n    # Test that SimplifyCombiner makes use of vranges\n    ck.analyzer.update(dummy, tvm.arith.ConstIntBound(-10, -4))\n    ck.verify(sum_or_prod(A[k], k), te.sum(A[k], k))\n    ck.verify(sum_or_prod(A[k], k, init=1), te.sum(A[k], k, init=1))\n    ck.analyzer.update(dummy, tvm.arith.ConstIntBound(5, 9), True)\n    ck.verify(sum_or_prod(A[k], k), prod(A[k], k))\n    ck.verify(sum_or_prod(A[k], k, init=1), prod(A[k], k, init=1))\n    ck.analyzer.update(dummy, tvm.arith.ConstIntBound(-10, 100), True)\n    ck.verify(sum_and_prod((A[k], A[10 - k]), k)[0], te.sum(A[k], k))\n    ck.verify(sum_and_prod((A[k], A[10 - k]), k)[1], prod(A[10 - k], k))\n\n    reference_simplified_sources = [\n        [A[0]],\n        [A[0], A[1]],\n        [A[0], A[2]],\n        [A[0], A[1], A[2], A[3]],\n        [A[4]],\n    ]\n    for j in range(5):\n        # Here we use the j-th component of the result, so only it and the components it\n        # depends on are left.\n        simplified = ck.analyzer.canonical_simplify(\n            some_reducer1((A[0], A[1], A[2], A[3], A[4]), k)[j]\n        )\n\n        # Check that the remaining components are the expected ones.\n        for lhs, rhs in zip(simplified.source, reference_simplified_sources[j]):\n            assert tvm.ir.structural_equal(lhs, rhs)\n\n    # Test that components with side effects are not removed\n    dummy = tvm.ir.GlobalVar(\"dummy\")\n    side_effect = lambda *xs: tvm.tir.Call(\"int32\", dummy, xs)\n    ck.verify(\n        sum_and_prod((A[k], side_effect(A[10 - k])), k)[0],\n        sum_and_prod((A[k], side_effect(A[10 - k])), k)[0],\n    )\n    ck.verify(sum_and_prod((side_effect(A[k]), A[10 - k]), k)[0], te.sum(side_effect(A[k]), k))\n\n\ndef test_reduce_simplify():\n    ck = CanonicalChecker()\n    k = te.reduce_axis((0, 10), name=\"k\")\n    j = te.reduce_axis((-5, 3), name=\"j\")\n    A = te.placeholder((10,), name=\"A\")\n    ck.verify(te.sum(tvm.tir.Select(k + j < 12, k + j, 0), [k, j]), te.sum(k + j, [k, j]))\n    ck.verify(te.sum(A[3], []), A[3])\n    ck.verify(te.sum(A[3], [], where=k > 12, init=1.0), tvm.tir.const(1.0, dtype=\"float32\"))\n    # The rule below is not typical, removed for now\n    ck.verify(te.sum(te.div(k, 10), k), te.sum(tvm.tir.const(0, \"int32\"), k))\n\n\ndef test_simplify_if_then_else():\n    ck = CanonicalChecker()\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # simplification that takes condition into account.\n    res = tvm.tir.if_then_else(\n        (x * 4 + y) >= 466036,\n        tvm.tir.if_then_else(\n            24512 <= tmod(((x * 4) + y) - 466036, 24528),\n            tmod(tmod(((x * 4) + y) - 466036, 24528) - 24512, 16),\n            x,\n        ),\n        y,\n    )\n\n    res2 = tvm.tir.if_then_else(\n        (x * 4) >= 466036 - y,\n        tvm.tir.if_then_else(\n            24512 <= tmod(((x * 4) + y) - 466036, 24528),\n            tmod(tmod(((x * 4) + y) - 466036, 24528) - 24512, 16),\n            x,\n        ),\n        y,\n    )\n    expected = tvm.tir.if_then_else(\n        tvm.tir.LE(466036, (x * 4 + y)),\n        tvm.tir.if_then_else(\n            tvm.tir.LE(24512, tmod(((x * 4) + y) - 4, 24528)), tmod(((x * 4) + y) - 4, 16), x\n        ),\n        y,\n    )\n    ck.verify(res, expected)\n    ck.verify(res2, expected)\n    # can only simplify if condition\n    res = tvm.tir.Select(tvm.tir.all(x >= -1, y >= 0), tmod(x + y + 100, 3), tmod(x + 100, 3))\n    expected = tvm.tir.Select(tvm.tir.all(x >= -1, y >= 0), tmod(x + y + 1, 3), tmod(x + 100, 3))\n    ck.verify(res, ck.analyzer.canonical_simplify(expected))\n\n    res = tvm.tir.Select(x >= 10, tvm.tir.if_then_else(tdiv(x, 3) > 2, x, 0), 0)\n    expected = tvm.tir.Select(x >= 10, x, 0)\n    ck.verify(res, ck.analyzer.canonical_simplify(expected))\n\n    res = tvm.tir.Select(x >= 10, tvm.tir.if_then_else(tdiv(x, 3) < 2, x, 0), 0)\n    ck.verify(res, 0)\n\n\ndef test_complex_cases():\n    ck = CanonicalChecker()\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    res2 = (\n        tdiv(tdiv(tmod(x * 128 + y, 1296), 36) * 2 + 1, 2) * 36\n        + tdiv(tmod((x * 128) + y, 36) * 2 + 1, 2)\n        - tmod((x * 128) + y, 1296)\n        + 1\n    )\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 5))\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 127))\n    ck.verify(res2, 1)\n\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 1024), True)\n    res3 = (\n        tdiv(x * 1024 + y, 65536)\n        + tdiv(tmod(x * 1024 + y, 65536), 256)\n        + tdiv(tmod(x * 1024 + y, 256), 16)\n        + tmod(x * 1024 + y, 16)\n        - tdiv(y, 256)\n        - tdiv(tmod(y, 256), 16)\n        - tmod(y, 16)\n        - (x * 4)\n    )\n    ck.verify(res3, tdiv((x * 1024) + y, 256) - tdiv(y, 256) - (x * 4))\n\n\ndef test_simplify_cast():\n    ck = CanonicalChecker()\n    tcast = tvm.tir.Cast\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    # cast(i64, i + j + 1) - cast(i64, i)\n    i = te.var(\"i\", dtype=\"int32\")\n    j = te.var(\"j\", dtype=\"int32\")\n    res = tcast(\"int64\", i + j + 1) - tcast(\"int64\", i)\n    ck.verify(res, tcast(\"int64\", j) + tvm.tir.const(1, \"int64\"))\n    # cast(i32, i + j + 1) - cast(i32, i)\n    i = te.var(\"i\", dtype=\"int64\")\n    j = te.var(\"j\", dtype=\"int64\")\n    ck.analyzer.update(i, tvm.arith.ConstIntBound(0, 10))\n    ck.analyzer.update(j, tvm.arith.ConstIntBound(0, 10))\n    res = tcast(\"int32\", i + j + 1) - tcast(\"int32\", i)\n    ck.verify(res, tcast(\"int32\", j) + 1)\n    # cast(i32, i + j - 100)\n    i = te.var(\"i\", dtype=\"int64\")\n    j = te.var(\"j\", dtype=\"int64\")\n    ck.analyzer.update(i, tvm.arith.ConstIntBound(0, 2**31 - 1))\n    ck.analyzer.update(j, tvm.arith.ConstIntBound(0, 10))\n    res = tcast(\"int32\", i + j - 100)\n    ck.verify(res, res)\n    # cast(i32, flm(axis, 7i64) * 2i64 + 1i64) + 1i32\n    # - cast(i32, flm(axis, 7i64) * 2i64)\n    axis = te.var(\"axis\", dtype=\"int64\")\n    ck.analyzer.update(axis, tvm.arith.ConstIntBound(0, 42))\n    res = (\n        tcast(\n            \"int32\",\n            flm(axis, tvm.tir.const(7, \"int64\")) * tvm.tir.const(2, \"int64\")\n            + tvm.tir.const(1, \"int64\"),\n        )\n        + tvm.tir.const(1, \"int32\")\n        - tcast(\"int32\", flm(axis, tvm.tir.const(7, \"int64\")) * tvm.tir.const(2, \"int64\"))\n    )\n    ck.verify(res, 2)\n\n\nif __name__ == \"__main__\":\n    test_floormod_simplify()\n    test_mul_sum_simplify()\n    test_simplify_if_then_else()\n    test_div_simplify()\n    test_reduce_simplify()\n    test_reduce_combiner_simplify()\n\n    test_split_index_simplify()\n    test_canonical_mixed()\n    test_complex_cases()\n    test_simplify_cast()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_const_int_bound.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\n\nfrom tvm import te\n\n\ndef test_dtype_bound():\n    analyzer = tvm.arith.Analyzer()\n\n    x = te.var(\"x\", dtype=\"int64\")\n    bd = analyzer.const_int_bound(x)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n    x = te.var(\"x\", dtype=\"int8\")\n    bd = analyzer.const_int_bound(x)\n    assert bd.min_value == -128\n    assert bd.max_value == 127\n\n    x = te.var(\"x\", dtype=\"uint8\")\n    bd = analyzer.const_int_bound(x)\n    assert bd.min_value == 0\n    assert bd.max_value == 255\n\n\ndef test_cast_bound():\n    analyzer = tvm.arith.Analyzer()\n    x = te.var(\"x\", dtype=\"int8\")\n    tmod = tvm.tir.truncmod\n    bd = analyzer.const_int_bound(tmod(x, 3).astype(\"uint32\"))\n    assert bd.min_value == 0\n    assert bd.max_value == 2\n\n    bd = analyzer.const_int_bound(tmod(x, 3).astype(\"float32\").astype(\"int32\"))\n    assert bd.min_value == -2\n    assert bd.max_value == 2\n\n\ndef test_add_sub_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\", \"int64\"), te.var(\"y\", \"int64\")\n    bd = analyzer.const_int_bound(x + y)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n    analyzer.update(x, tvm.arith.ConstIntBound(0, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(1, 10))\n    bd = analyzer.const_int_bound(x + y)\n    assert bd.min_value == 1\n    assert bd.max_value == 14\n\n    bd = analyzer.const_int_bound(x - y)\n    assert bd.min_value == -10\n    assert bd.max_value == 3\n\n    analyzer.update(x, tvm.arith.ConstIntBound(0, bd.POS_INF), override=True)\n    bd = analyzer.const_int_bound(x - y)\n    assert bd.min_value == -10\n    assert bd.max_value == bd.POS_INF\n\n    bd = analyzer.const_int_bound(1 - x)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == 1\n\n    ## constants with negative or positive max(int64) occassionally show up\n    ## in models, this is to ensure we can handle those cases\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, bd.NEG_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(bd.NEG_INF, bd.POS_INF), override=True)\n    bd = analyzer.const_int_bound(x + y)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.POS_INF, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(bd.NEG_INF, bd.POS_INF), override=True)\n    bd = analyzer.const_int_bound(x + y)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n\ndef test_mul_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-2, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(x * y + 20)\n    assert bd.min_value == 0\n    assert bd.max_value == 60\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-3, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-8, 2), override=True)\n    bd = analyzer.const_int_bound(x * y)\n    assert bd.min_value == -32\n    assert bd.max_value == 24\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-8, 2), override=True)\n    bd = analyzer.const_int_bound(x * y)\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n\ndef test_truncdiv_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    tdiv = tvm.tir.truncdiv\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(tdiv(x, y))\n    assert bd.min_value == -2\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-2, 0), override=True)\n    bd = analyzer.const_int_bound(tdiv(x, y))\n    assert bd.min_value == -4\n    assert bd.max_value == 9\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-2, 1), override=True)\n    bd = analyzer.const_int_bound(tdiv(x, y))\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-4, 12), override=True)\n    bd = analyzer.const_int_bound(tdiv(x, y))\n    assert bd.min_value == -9\n    assert bd.max_value == 9\n\n\ndef test_truncmod_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    tmod = tvm.tir.truncmod\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(tmod(x, y))\n    assert bd.min_value == -9\n    assert bd.max_value == 4\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(tmod(x, y))\n    assert bd.min_value == -9\n    assert bd.max_value == 9\n\n    analyzer.update(x, tvm.arith.ConstIntBound(1, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(tmod(x, y))\n    assert bd.min_value == 0\n    assert bd.max_value == 9\n\n\ndef test_floordiv_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    fld = tvm.te.floordiv\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(fld(x, y))\n    assert bd.min_value == -9 // 4\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-2, 0), override=True)\n    bd = analyzer.const_int_bound(fld(x, y))\n    assert bd.min_value == -4\n    assert bd.max_value == 9\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-2, 1), override=True)\n    bd = analyzer.const_int_bound(fld(x, y))\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == bd.POS_INF\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(-4, 12), override=True)\n    bd = analyzer.const_int_bound(fld(x, y))\n    assert bd.min_value == -9\n    assert bd.max_value == 9\n\n    # Test handling unsigned integers well\n    x, y = te.var(\"x\", dtype=\"uint32\"), te.var(\"y\", dtype=\"uint32\")\n    analyzer.update(x, tvm.arith.ConstIntBound(1, 4), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(0, 12), override=True)\n    bd = analyzer.const_int_bound(fld(x, y))\n    assert bd.min_value == 0\n    assert bd.max_value == 4\n\n\ndef test_floormod_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    flm = tvm.te.floormod\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 4))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(flm(x, y))\n    assert bd.min_value == 0\n    assert bd.max_value == 9\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(flm(x, y))\n    assert bd.min_value == 0\n    assert bd.max_value == 9\n\n    analyzer.update(x, tvm.arith.ConstIntBound(1, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(flm(x, y))\n    assert bd.min_value == 0\n    assert bd.max_value == 9\n\n\ndef test_min_max_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 11))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n    bd = analyzer.const_int_bound(tvm.te.min(x, y))\n    assert bd.min_value == -9\n    assert bd.max_value == 10\n\n    analyzer.update(x, tvm.arith.ConstIntBound(bd.NEG_INF, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(tvm.te.min(x, y))\n    assert bd.min_value == bd.NEG_INF\n    assert bd.max_value == 10\n\n    bd = analyzer.const_int_bound(tvm.te.max(x, y))\n    assert bd.min_value == 4\n    assert bd.max_value == bd.POS_INF\n\n    analyzer.update(x, tvm.arith.ConstIntBound(1, bd.POS_INF), override=True)\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10), override=True)\n    bd = analyzer.const_int_bound(tvm.te.max(x, y))\n    assert bd.min_value == 4\n    assert bd.max_value == bd.POS_INF\n\n\ndef test_select_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 11))\n    analyzer.update(y, tvm.arith.ConstIntBound(4, 10))\n\n    bd = analyzer.const_int_bound(tvm.tir.Select(x > 1, (y < 0).astype(\"int32\"), y + 1))\n    assert bd.min_value == 0\n    assert bd.max_value == 11\n\n\ndef test_shift_and_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    analyzer.update(x, tvm.arith.ConstIntBound(-9, 11))\n    analyzer.update(y, tvm.arith.ConstIntBound(2, 10))\n\n    bd = analyzer.const_int_bound(x >> y)\n    assert bd.min_value == -3\n    assert bd.max_value == 2\n\n    bd = analyzer.const_int_bound(x & y)\n    assert bd.min_value == 0\n    assert bd.max_value == 10\n\n    analyzer.update(x, tvm.arith.ConstIntBound(10, 11), override=True)\n    bd = analyzer.const_int_bound(x & y)\n    assert bd.min_value == 0\n    assert bd.max_value == 10\n\n\ndef test_mix_index_bound():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n\n    analyzer.update(x, tvm.arith.ConstIntBound(0, 24 - 1))\n    analyzer.update(y, tvm.arith.ConstIntBound(0, 3 - 1))\n    bd = analyzer.const_int_bound(tmod(x, 8) + tdiv(x, 8) * 8)\n    assert bd.min_value == 0\n    assert bd.max_value == 24 - 1\n\n    bd = analyzer.const_int_bound(y + x * 3)\n    assert bd.min_value == 0\n    assert bd.max_value == 24 * 3 - 1\n\n    bd = analyzer.const_int_bound(tmod(x, 7) + tdiv(x, 7) * 7)\n    assert bd.min_value == 0\n    assert bd.max_value == (23 // 7) * 7 + 6\n\n\ndef test_size_var_bound():\n    analyzer = tvm.arith.Analyzer()\n    x = te.size_var(\"x\")\n    bd = analyzer.const_int_bound(x)\n    assert bd.min_value == 0\n    assert bd.max_value == bd.POS_INF\n\n\ndef test_let_bound():\n    analyzer = tvm.arith.Analyzer()\n    x = te.var(\"x\")\n    bd = analyzer.const_int_bound(tvm.tir.Let(x, 1, x + 1))\n    assert bd.min_value == 2\n    assert bd.max_value == 2\n\n\ndef test_floormod_negative_divisor():\n    analyzer = tvm.arith.Analyzer()\n    flm, fld = tvm.te.floormod, tvm.te.floordiv\n    a, b = te.var(\"a\"), te.var(\"b\")\n    analyzer.update(a, tvm.arith.ConstIntBound(0, 6))\n    analyzer.update(b, tvm.arith.ConstIntBound(-5, 7))\n    bd = analyzer.const_int_bound(flm(a, b))\n    assert bd.min_value == -4\n    assert bd.max_value == 6\n\n\ndef test_multiple_condition():\n    analyzer = tvm.arith.Analyzer()\n    flm, fld = tvm.te.floormod, tvm.te.floordiv\n    a = te.var(\"a\")\n    analyzer.update(a, tvm.arith.ConstIntBound(0, 128))\n    with analyzer.constraint_scope(tvm.tir.all(1 <= flm(a, 58), flm(a, 58) < 57)):\n        bound = analyzer.const_int_bound(flm(a, 58) - 1)\n    assert bound.min_value == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_deduce_bound.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.tir.buffer import decl_buffer\n\n\ndef test_deduce():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = te.var(\"c\")\n    d = te.var(\"d\")\n\n    b_s = tvm.arith.IntervalSet(2, 3)\n    c_s = tvm.arith.IntervalSet(10, 15)\n    d_s = tvm.arith.IntervalSet(-3, -1)\n    zero = tvm.tir.const(0, \"int32\")\n\n    fdiv = tvm.te.floordiv\n\n    e0 = (-b) * a + c - d\n    res0 = tvm.arith.deduce_bound(a, e0 >= 0, {b: b_s, c: c_s, d: d_s}, {})\n    ans0 = fdiv(d - c, b * -1)\n    tvm.testing.assert_prim_expr_equal(res0.max_value, ans0)\n\n    # expression containing variable a is on rhs\n    res0 = tvm.arith.deduce_bound(a, zero <= e0, {b: b_s, c: c_s, d: d_s}, {})\n    tvm.testing.assert_prim_expr_equal(res0.max_value, ans0)\n\n    e0 = d * a + c - d\n    res0 = tvm.arith.deduce_bound(a, e0 >= 0, {b: b_s, c: c_s, d: d_s}, {})\n    ans0 = fdiv(d - c, d)\n    tvm.testing.assert_prim_expr_equal(res0.max_value, ans0)\n\n    # expression containing variable a is on rhs\n    res0 = tvm.arith.deduce_bound(a, zero <= e0, {b: b_s, c: c_s, d: d_s}, {})\n    tvm.testing.assert_prim_expr_equal(res0.max_value, ans0)\n\n    e1 = a * 4 + b < c\n    res1 = tvm.arith.deduce_bound(a, e1, {b: b_s, c: c_s, d: d_s}, {})\n    ans1 = fdiv(c - 1 - b, 4)\n    tvm.testing.assert_prim_expr_equal(res1.max_value, ans1)\n\n    # expression containing variable a is on rhs\n    e1 = c > a * 4 + b\n    res1 = tvm.arith.deduce_bound(a, e1, {b: b_s, c: c_s, d: d_s}, {})\n    tvm.testing.assert_prim_expr_equal(res1.max_value, ans1)\n\n    e2 = tvm.te.max(5, a * 4) < 0\n    res2 = tvm.arith.deduce_bound(a, e2, {b: b_s, c: c_s, d: d_s}, {})\n    assert str(res2.max_value) == \"neg_inf: handle\"\n    assert str(res2.min_value) == \"pos_inf: handle\"\n\n    # expression containing variable a is on rhs\n    e2 = zero < tvm.te.max(5, a * 4)\n    res2 = tvm.arith.deduce_bound(a, e2, {b: b_s, c: c_s, d: d_s}, {})\n    assert str(res2.max_value) == \"neg_inf: handle\"\n    assert str(res2.min_value) == \"pos_inf: handle\"\n\n    e3 = (-b) + a * c - d\n    res3 = tvm.arith.deduce_bound(a, e3 >= 0, {b: b_s, c: c_s, d: d_s}, {b: b_s, d: d_s})\n    ans3 = fdiv(2, c) + 1\n    tvm.testing.assert_prim_expr_equal(res3.min_value, ans3)\n\n    res3 = tvm.arith.deduce_bound(a, zero <= e3, {b: b_s, c: c_s, d: d_s}, {b: b_s, d: d_s})\n    tvm.testing.assert_prim_expr_equal(res3.min_value, ans3)\n\n    # tests for `EQ` op\n    res4 = tvm.arith.deduce_bound(a, a == b, {}, {})\n    tvm.testing.assert_prim_expr_equal(res4.max_value, b)\n    tvm.testing.assert_prim_expr_equal(res4.min_value, b)\n\n    # Unsatisfiable `EQ`, variable as one of the Operand\n    res5 = tvm.arith.deduce_bound(a, (a == b), {b: b_s}, {b: b_s})\n    assert str(res5.max_value) == \"neg_inf: handle\"\n    assert str(res5.min_value) == \"pos_inf: handle\"\n\n    # variable `a` on the RHS side\n    res6 = tvm.arith.deduce_bound(a, 10 == a, {}, {})\n    tvm.testing.assert_prim_expr_equal(res6.max_value, 10)\n    tvm.testing.assert_prim_expr_equal(res6.min_value, 10)\n\n    # Add, Sub in `EQ`\n    e4 = (a - c) == (b + d)\n    ans4 = b + d + c\n    res7 = tvm.arith.deduce_bound(a, e4, {b: b_s, c: c_s, d: d_s}, {})\n    tvm.testing.assert_prim_expr_equal(res7.max_value, ans4)\n    tvm.testing.assert_prim_expr_equal(res7.min_value, ans4)\n\n    # Satisfiable Mul in `EQ` with negative sign\n    res8 = tvm.arith.deduce_bound(a, (5 * a == -10), {}, {})\n    tvm.testing.assert_prim_expr_equal(res8.max_value, -2)\n    tvm.testing.assert_prim_expr_equal(res8.min_value, -2)\n\n    # Unsatisfiable Mul in `EQ`\n    e5 = 4 * a == b\n    res9 = tvm.arith.deduce_bound(a, e5, {b: b_s}, {})\n    assert str(res9.max_value) == \"neg_inf: handle\"\n    assert str(res9.min_value) == \"pos_inf: handle\"\n\n    # Unsatisfiable Mul in `EQ`\n    res10 = tvm.arith.deduce_bound(\n        a, (b * a == b), {b: b_s}, {}\n    )  # simplifier is not able to prove that (b % b == 0)\n    assert str(res10.max_value) == \"neg_inf: handle\"\n    assert str(res10.min_value) == \"pos_inf: handle\"\n\n\ndef test_check():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = te.var(\"c\")\n    d = te.var(\"d\")\n\n    b_s = tvm.arith.IntervalSet(2, 3)\n    c_s = tvm.arith.IntervalSet(5, 7)\n    d_s = tvm.arith.IntervalSet(-3, -1)\n\n    # no compare operator\n    res1 = tvm.arith.deduce_bound(a, a + b, {b: b_s}, {})\n    assert res1.is_nothing()\n\n    # multiple compare operators\n    res2 = tvm.arith.deduce_bound(a, (a + b > 3).astype(c.dtype) > c, {b: b_s, c: c_s}, {})\n    assert res2.is_nothing()\n\n    # multiple target variable\n    res2 = tvm.arith.deduce_bound(a, a * 2 - a > b, {b: b_s}, {})\n    assert res2.is_nothing()\n\n\ndef test_deduce_basic():\n    def test_basic(a1, a2, coff):\n        a = te.var(\"a\")\n        b = te.var(\"b\")\n        b_s = tvm.arith.IntervalSet(a1, a2)\n        e0 = b + a * coff + 3\n\n        res1 = tvm.arith.deduce_bound(a, e0 < 17, {b: b_s}, {b: b_s})\n        [x, y] = [res1.max_value, b_s.max_value] if coff > 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal((x * coff + 3 + y) < 17, True)\n\n        # expression containing variable a is on rhs\n        res1 = tvm.arith.deduce_bound(a, tvm.tir.const(17, \"int32\") < e0, {b: b_s}, {b: b_s})\n        [x, y] = [res1.max_value, b_s.max_value] if coff < 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal((x * coff + 3 + y) > 17, True)\n\n        # expression containing variable a is on rhs\n        res1 = tvm.arith.deduce_bound(a, tvm.tir.const(17, \"int32\") >= e0, {b: b_s}, {b: b_s})\n        [x, y] = [res1.max_value, b_s.max_value] if coff > 0 else [res1.min_value, b_s.min_value]\n\n        tvm.testing.assert_prim_expr_equal((x * coff + 3 + y) <= 17, True)\n\n        res1 = tvm.arith.deduce_bound(a, e0 >= 17, {b: b_s}, {b: b_s})\n        [x, y] = [res1.max_value, b_s.max_value] if coff < 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal((x * coff + 3 + y) >= 17, True)\n\n    test_basic(0, 4, 4)\n    test_basic(1, 5, 4)\n    test_basic(2, 6, 4)\n    test_basic(0, 4, -4)\n    test_basic(1, 5, -4)\n    test_basic(2, 6, -4)\n\n\ndef test_deduce_complex():\n    def test_complex(a1, a2, coff):\n        a = te.var(\"a\")\n        b = te.var(\"b\")\n        b_s = tvm.arith.IntervalSet(a1, a2)\n        e0 = (b * 3 + a * coff) * 4\n\n        res1 = tvm.arith.deduce_bound(a, e0 < 63, {b: b_s}, {b: b_s})\n        [t, x] = [res1.max_value, b_s.max_value] if coff > 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal(((x * 3 + t * coff) * 4) < 63, True)\n\n        # expression containing variable a is on rhs\n        res1 = tvm.arith.deduce_bound(a, tvm.tir.const(63, \"int32\") >= e0, {b: b_s}, {b: b_s})\n        [t, x] = [res1.max_value, b_s.max_value] if coff > 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal(((x * 3 + t * coff) * 4) <= 63, True)\n\n        res1 = tvm.arith.deduce_bound(a, e0 > 63, {b: b_s}, {b: b_s})\n        [t, x] = [res1.max_value, b_s.max_value] if coff < 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal(((x * 3 + t * coff) * 4) > 63, True)\n\n        # expression containing variable a is on rhs\n        res1 = tvm.arith.deduce_bound(a, tvm.tir.const(63, \"int32\") <= e0, {b: b_s}, {b: b_s})\n        [t, x] = [res1.max_value, b_s.max_value] if coff < 0 else [res1.min_value, b_s.min_value]\n        tvm.testing.assert_prim_expr_equal(((x * 3 + t * coff) * 4) >= 63, True)\n\n    test_complex(0, 4, 4)\n    test_complex(0, 4, -4)\n    test_complex(2, 6, 4)\n    test_complex(0, 4, -4)\n    test_complex(1, 5, -4)\n    test_complex(2, 6, -4)\n\n\ndef test_deduce_non_support():\n    a = te.var(\"a\")\n\n    def test_non_support(lhs):\n        res = tvm.arith.deduce_bound(a, lhs < 10, {}, {})\n        assert res.is_nothing()\n\n    test_non_support(tvm.tir.floordiv(a, 16))\n    test_non_support(tvm.tir.floormod(a, 16))\n    test_non_support(tvm.tir.Min(a, 16))\n    test_non_support(tvm.tir.Max(a, 16))\n    test_non_support(tvm.tir.LE(a, 16))\n    test_non_support(tvm.tir.LT(a, 16))\n    test_non_support(tvm.tir.GE(a, 16))\n    test_non_support(tvm.tir.GT(a, 16))\n    test_non_support(tvm.tir.EQ(a, 16))\n    test_non_support(tvm.tir.NE(a, 16))\n    test_non_support(tvm.tir.log(a))\n    test_non_support(tvm.tir.BufferLoad(decl_buffer([16], \"int32\"), [a]))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_detect_clip_bound.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\ndef test_basic():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = te.var(\"c\")\n    m = tvm.arith.detect_clip_bound(tvm.tir.all(a * 1 < b * 6, a - 1 > 0), [a])\n    tvm.testing.assert_prim_expr_equal(m[1], b * 6 - 1)\n    assert m[0].value == 2\n    m = tvm.arith.detect_clip_bound(tvm.tir.all(a * 1 < b * 6, a - 1 > 0), [a, b])\n    assert len(m) == 0\n    m = tvm.arith.detect_clip_bound(tvm.tir.all(a + 10 * c <= 20, b - 1 > 0), [a, b])\n    tvm.testing.assert_prim_expr_equal(m[1], 20 - 10 * c)\n    tvm.testing.assert_prim_expr_equal(m[2], 2)\n    m = tvm.arith.detect_clip_bound(tvm.tir.all(tvm.tir.Not(a * 1 > b * 6), a - 1 > 0), [a])\n    tvm.testing.assert_prim_expr_equal(m[1], b * 6)\n    m = tvm.arith.detect_clip_bound(tvm.tir.all(tvm.tir.Min(a, b) > 3, a - 10 < 0), [a, b])\n    tvm.testing.assert_prim_expr_equal(m[0], 4)\n    tvm.testing.assert_prim_expr_equal(m[1], 9)\n    tvm.testing.assert_prim_expr_equal(m[2], 4)\n\n\nif __name__ == \"__main__\":\n    test_basic()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_detect_linear_equation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\ndef test_basic():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    m = tvm.arith.detect_linear_equation(a * 4 + b * 6 + 7, [a])\n    assert m[0].value == 4\n    tvm.testing.assert_prim_expr_equal(m[1], b * 6 + 7)\n\n    m = tvm.arith.detect_linear_equation(a * 4 * (a + 1) + b * 6 + 7, [a])\n    assert len(m) == 0\n\n    m = tvm.arith.detect_linear_equation(a * 4 + (a + 1) + b * 6 + 7, [a])\n    assert m[0].value == 5\n    tvm.testing.assert_prim_expr_equal(m[1], b * 6 + 7 + 1)\n\n    m = tvm.arith.detect_linear_equation(a * b + 7, [a])\n    assert m[0] == b\n\n    m = tvm.arith.detect_linear_equation(b * 7, [a])\n    assert m[0].value == 0\n\n    m = tvm.arith.detect_linear_equation(b * 7, [])\n    assert len(m) == 1\n    tvm.testing.assert_prim_expr_equal(m[0], b * 7)\n\n\ndef test_multivariate():\n    v = [te.var(\"v%d\" % i) for i in range(4)]\n    b = te.var(\"b\")\n    m = tvm.arith.detect_linear_equation(v[0] * (b + 4) + v[0] + v[1] * 8, v)\n\n    tvm.testing.assert_prim_expr_equal(m[0], b + 5)\n\n    assert m[1].value == 8\n\n    m = tvm.arith.detect_linear_equation(v[0] * (b + 4) + v[0] + v[1] * 8 * v[2], v)\n    assert len(m) == 0\n\n    m = tvm.arith.detect_linear_equation(v[0] * (b + 4) + v[0] + v[1] * 8 * v[1] + v[3], v)\n    assert len(m) == 0\n\n    m = tvm.arith.detect_linear_equation(((v[0] * b + v[1]) * 8 + v[2] + 1) * 2, v)\n    assert m[1].value == 16\n    assert m[2].value == 2\n    assert m[len(m) - 1].value == 2\n\n    m = tvm.arith.detect_linear_equation((v[0] - v[1]), [v[2]])\n    assert m[0].value == 0\n\n    tvm.testing.assert_prim_expr_equal(m[1], v[0] - v[1])\n\n    m = tvm.arith.detect_linear_equation((v[0] - v[1]), [])\n    assert len(m) == 1\n    tvm.testing.assert_prim_expr_equal(m[0], v[0] - v[1])\n\n\nif __name__ == \"__main__\":\n    test_basic()\n    test_multivariate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_domain_touched.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef scalar_func(a: T.handle, b: T.handle):\n    m = T.var(\"int32\")\n    n = 100\n    A = T.match_buffer(a, (n, m))\n    B = T.match_buffer(b, (n, m))\n\n    for i, j in T.grid(n, m):\n        A[i, j] = B[i - 1, j + 1] + A[i - 1, j - 1]\n\n\n@T.prim_func\ndef vector_func(a: T.handle, b: T.handle):\n    n = T.var(\"int32\")\n    m = 128\n    A = T.match_buffer(a, (n, m))\n    B = T.match_buffer(b, (n, m))\n\n    for i in T.serial(n):\n        for j in T.vectorized(m):\n            A[i, j] = A[i, j] + B[i, j]\n\n\ndef test_domain_touched():\n    func = scalar_func\n    a, b = [func.buffer_map[var] for var in func.params]\n    ir = func.body\n\n    a_domain_r = tvm.arith._ffi_api.DomainTouched(ir, a, True, False)\n\n    assert a_domain_r[0].min.value == -1\n    assert a_domain_r[0].extent.value == 100\n    assert a_domain_r[1].min.value == -1\n    assert a_domain_r[1].extent.name == \"m\"\n\n    a_domain_w = tvm.arith._ffi_api.DomainTouched(ir, a, False, True)\n    assert a_domain_w[0].min.value == 0\n    assert a_domain_w[0].extent.value == 100\n    assert a_domain_w[1].min.value == 0\n    assert a_domain_w[1].extent.name == \"m\"\n\n    a_domain_rw = tvm.arith._ffi_api.DomainTouched(ir, a, True, True)\n    assert a_domain_rw[0].min.value == -1\n    assert a_domain_rw[0].extent.value == 101\n    assert a_domain_rw[1].min.value == -1\n    assert isinstance(a_domain_rw[1].extent, tvm.tir.Add)\n    assert a_domain_rw[1].extent.a.name == \"m\"\n    assert a_domain_rw[1].extent.b.value == 1\n\n    b_domain_r = tvm.arith._ffi_api.DomainTouched(ir, b, True, False)\n    assert b_domain_r\n    assert b_domain_r[0].min.value == -1\n    assert b_domain_r[0].extent.value == 100\n    assert b_domain_r[1].min.value == 1\n    assert b_domain_r[1].extent.name == \"m\"\n\n    b_domain_w = tvm.arith._ffi_api.DomainTouched(ir, b, False, True)\n    assert isinstance(b_domain_w, tvm.container.Array)\n    assert len(b_domain_w) == 0\n\n\ndef test_domain_touched_vector():\n    func = tvm.lower(vector_func)[\"main\"]\n    a, b = [func.buffer_map[var] for var in func.params]\n\n    assert tvm.arith._ffi_api.DomainTouched(func.body, a, True, False)[0].extent.value == 128\n    assert tvm.arith._ffi_api.DomainTouched(func.body, a, True, False)[0].extent.value == 128\n    assert tvm.arith._ffi_api.DomainTouched(func.body, a, True, True)[0].extent.value == 128\n    assert tvm.arith._ffi_api.DomainTouched(func.body, b, True, False)[0].extent.value == 128\n    assert tvm.arith._ffi_api.DomainTouched(func.body, b, True, False)[0].extent.value == 128\n\n\nif __name__ == \"__main__\":\n    test_domain_touched()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_intset.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm import tir\nfrom tvm.arith.analyzer import Analyzer\n\n\nclass IntSetChecker:\n    def __init__(self):\n        self.analyzer = tvm.arith.Analyzer()\n\n    def verify(self, data, dmap, expected):\n        res = self.analyzer.int_set(data, dmap)\n\n        def err_msg():\n            return \"\\ndata={}\\ndmap={}\\nres={}\\nexpected={}\".format(data, dmap, res, expected)\n\n        assert self.analyzer.can_prove_equal(res.min_value, expected[0]), err_msg()\n        assert self.analyzer.can_prove_equal(res.max_value, expected[1]), err_msg()\n\n\ndef test_basic():\n    s = tvm.arith.IntervalSet(2, 3)\n    assert s.min_value.value == 2\n    assert s.max_value.value == 3\n\n    s = tvm.arith.IntSet.single_point(2)\n    assert s.min_value.value == 2\n    assert s.max_value.value == 2\n\n\ndef test_vector():\n    base = 10\n    stride = 3\n    lanes = 2\n    s = tvm.arith.IntSet.vector(tvm.tir.Ramp(base, stride, lanes))\n    assert s.min_value.value == base\n    assert s.max_value.value == base + stride * (lanes - 1)\n\n\ndef test_add_sub():\n    ck = IntSetChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    ck.verify(x + y, {x: tvm.arith.IntervalSet(0, 10)}, (y, 10 + y))\n    ck.verify(x + y, {x: tvm.arith.IntervalSet(0, 10), y: tvm.arith.IntervalSet(1, 11)}, (1, 21))\n    ck.verify(x - y, {x: tvm.arith.IntervalSet(0, 10), y: tvm.arith.IntervalSet(1, 11)}, (-11, 9))\n\n\ndef test_mul_div():\n    ck = IntSetChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    tdiv = tvm.tir.truncdiv\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(1, 100), override=True)\n    ck.verify(x * y, {x: tvm.arith.IntervalSet(0, 10)}, (0, 10 * y))\n    ck.verify(x * 2, {x: tvm.arith.IntervalSet(1, 10)}, (2, 20))\n    ck.verify(x * -2, {x: tvm.arith.IntervalSet(1, 10)}, (-20, -2))\n\n    ck.verify(tdiv(x, y), {x: tvm.arith.IntervalSet(0, 10)}, (0, tdiv(10, y)))\n    ck.verify(tdiv(x, 2), {x: tvm.arith.IntervalSet(1, 10)}, (0, 5))\n\n    fld = tvm.te.floordiv\n    ck.verify(fld(x, y), {x: tvm.arith.IntervalSet(0, 10)}, (0, fld(10, y)))\n    ck.verify(fld(x, 2), {x: tvm.arith.IntervalSet(-1, 10)}, (-1, 5))\n\n\ndef test_mod():\n    ck = IntSetChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    tmod = tvm.tir.truncmod\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(1, 100), override=True)\n    ck.verify(tmod(x, y), {x: tvm.arith.IntervalSet(0, 10)}, (0, y - 1))\n    ck.verify(tmod(x, 10), {x: tvm.arith.IntervalSet(1, 10)}, (0, 9))\n\n    flm = tvm.te.floormod\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(-10, 10)}, (0, 9))\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(3, 5)}, (3, 5))\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(13, 15)}, (3, 5))\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(3, 15)}, (0, 9))\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(3, 11)}, (0, 9))\n    ck.verify(flm(x, 10), {x: tvm.arith.IntervalSet(1, 21)}, (0, 9))\n\n    fld = tvm.te.floordiv\n    z = te.var(\"z\")\n    ck.analyzer.bind(x, tvm.ir.Range.from_min_extent(0, 3))\n    ck.verify(\n        flm(y, 8),\n        {y: tvm.arith.IntervalSet(z * 8 + x * 4, z * 8 + x * 4 + 3)},\n        (\n            z * 8 + x * 4 - 8 * fld(z * 8 + x * 4, 8),\n            z * 8 + x * 4 + 3 - 8 * fld(z * 8 + x * 4, 8),\n        ),\n    )\n    ck1 = IntSetChecker()\n    ck1.analyzer.bind(x, tvm.ir.Range.from_min_extent(0, 2))\n    ck1.verify(\n        flm(y, 8), {y: tvm.arith.IntervalSet(z * 8 + x * 4, z * 8 + x * 4 + 3)}, (x * 4, x * 4 + 3)\n    )\n\n\ndef test_max_min():\n    ck = IntSetChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    ck.verify(tvm.te.max(x, x + 1), {x: tvm.arith.IntervalSet(0, 10)}, (1, 11))\n    ck.verify(tvm.te.min(x - 1, x + 1), {x: tvm.arith.IntervalSet(0, 10)}, (-1, 9))\n    ck.verify(tvm.te.min(x, y), {}, (tvm.te.min(x, y), tvm.te.min(x, y)))\n    ck.verify(tvm.te.max(x, y), {}, (tvm.te.max(x, y), tvm.te.max(x, y)))\n\n\ndef test_select():\n    ck = IntSetChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    ck.verify(tvm.tir.Select(x > 0, x - 1, x + 1), {x: tvm.arith.IntervalSet(0, 10)}, (-1, 11))\n\n\ndef check_region_bound(expect_region, var_dom, mode, predicate=None):\n    \"\"\"Helper to check region bound estimation.\n\n    Parameters\n    ----------\n    expect_region: dict\n        The keys are of form (begin, end) or PrimExpr as a single point. The values are\n        expected estimated region or region dict on different bindings.\n\n    var_dom: dict\n        Map var to iteration domain range.\n\n    mode: str\n        Specify \"lowerbound\", \"upperbound\" or else use strict bound estimation.\n\n    predicate: PrimExpr\n        Extra predicate, defaults to True.\n    \"\"\"\n    if predicate is None:\n        predicate = tvm.tir.IntImm(\"bool\", 1)\n    region = []\n    expect = []\n    for k, v in expect_region.items():\n        if not isinstance(k, (tuple, list)):\n            k = (k, k + 1)\n        region.append(tvm.ir.Range.from_min_extent(k[0], Analyzer().simplify(k[1] - k[0])))\n        expect.append(v)\n    if mode == \"lowerbound\":\n        result = tvm.arith.estimate_region_lower_bound(\n            region=region, var_dom=var_dom, predicate=predicate\n        )\n    elif mode == \"upperbound\":\n        result = tvm.arith.estimate_region_upper_bound(\n            region=region, var_dom=var_dom, predicate=predicate\n        )\n    else:\n        result = tvm.arith.estimate_region_strict_bound(\n            region=region, var_dom=var_dom, predicate=predicate\n        )\n    if result is None:\n        assert all([_ is None for _ in expect])\n        return\n    assert len(result) == len(expect)\n    for intset, expect_desc in zip(result, expect):\n        if isinstance(expect_desc, dict):\n            # check range on different free var bindings\n            for binding in expect_desc:\n                analyzer = Analyzer()\n                for k, v in binding:\n                    analyzer.bind(k, v)\n                expect_begin, expect_end = expect_desc[binding]\n                result_begin = analyzer.simplify(intset.min_value, 3)\n                result_end = analyzer.simplify(intset.max_value + 1, 3)\n                print(result_end)\n                assert analyzer.can_prove_equal(\n                    result_begin - expect_begin, 0\n                ), f\"{result_begin} vs {expect_begin}\"\n                assert analyzer.can_prove_equal(\n                    result_end - expect_end, 0\n                ), f\"{result_end} vs {expect_end}\"\n        else:\n            # check range\n            expect_begin, expect_end = expect_desc\n            analyzer = Analyzer()\n            assert analyzer.can_prove_equal(\n                intset.min_value - expect_begin, 0\n            ), f\"{intset.min_value} vs {expect_begin}\"\n            assert analyzer.can_prove_equal(\n                intset.max_value - expect_end + 1, 0\n            ), f\"{intset.max_value} vs {expect_end - 1}\"\n\n\ndef test_region_bound_not_independent():\n    # (i, i+2) and (i+2, i+4) are dependent, this the lowerbound is not available\n    i = tvm.tir.Var(\"i\", \"int32\")\n    var_dom = {\n        i: tvm.ir.Range(begin=0, end=64),\n    }\n    check_region_bound({(i, i + 2): None, (i + 2, i + 4): None}, var_dom, mode=\"lowerbound\")\n    check_region_bound({(i, i + 2): (0, 65), (i + 2, i + 4): (2, 67)}, var_dom, mode=\"upperbound\")\n\n    # when only a subset of access indices are affine\n    i, j, k = tvm.tir.Var(\"i\", \"int32\"), tvm.tir.Var(\"j\", \"int32\"), tvm.tir.Var(\"k\", \"int32\")\n    var_dom = {\n        i: tvm.ir.Range(begin=0, end=16),\n        j: tvm.ir.Range(begin=0, end=16),\n        k: tvm.ir.Range(begin=0, end=16),\n    }\n    check_region_bound(\n        {i // 4: None, j * 4 + i % 4: None, tir.truncdiv(k, 2): None},\n        var_dom,\n        predicate=j * 4 + i % 4 > 3,\n        mode=\"lowerbound\",\n    )\n    check_region_bound(\n        {i // 4: (0, 4), j * 4 + i % 4: (4, 64), tir.truncdiv(k, 2): (0, 8)},\n        var_dom,\n        predicate=j * 4 + i % 4 > 3,\n        mode=\"upperbound\",\n    )\n\n\ndef test_region_bound_stride_too_wide():\n    i = tvm.tir.Var(\"i\", \"int32\")\n    var_dom = {i: tvm.ir.Range(begin=0, end=64)}\n    check_region_bound({(i * 4, i * 4 + 2): None}, var_dom, mode=\"lowerbound\")\n    check_region_bound({(i * 4, i * 4 + 2): (0, 254)}, var_dom, mode=\"upperbound\")\n\n\ndef test_region_bound_small_stride():\n    i = tvm.tir.Var(\"i\", \"int32\")\n    var_dom = {\n        i: tvm.ir.Range(begin=0, end=64),\n    }\n    check_region_bound({(i * 4, i * 4 + 8): (0, 260)}, var_dom, mode=\"lowerbound\")\n\n\ndef test_region_lower_bound_split_predicate():\n    x_o = tvm.tir.Var(\"xo\", \"int32\")\n    x_i = tvm.tir.Var(\"xi\", \"int32\")\n    x = x_o * 4 + x_i\n    var_dom = {\n        x_o: tvm.ir.Range(begin=0, end=16),\n        x_i: tvm.ir.Range(begin=0, end=4),\n    }\n    check_region_bound({(x * 4, x * 4 + 8): (0, 256)}, var_dom, predicate=x < 63, mode=\"lowerbound\")\n\n    check_region_bound(\n        {(x * 4, x * 4 + 8): (0, 256), (x * 3, x * 3 + 5): (0, 191)},\n        var_dom,\n        predicate=x < 63,\n        mode=\"upperbound\",\n    )\n\n\ndef test_region_lower_bound_multiple_variables():\n    div = tvm.tir.floordiv\n    mod = tvm.tir.floormod\n    x = tvm.tir.Var(\"x\", \"int32\")\n    wid = tvm.tir.Var(\"wid\", \"int32\")\n    i = div(x, 16)\n    j = div(mod(x, 16), 4) * 8 + mod(x, 4) + div(wid, 32) * 4\n    k = wid % 32\n    var_dom = {\n        x: tvm.ir.Range(begin=0, end=32),\n        wid: tvm.ir.Range(begin=0, end=64),\n    }\n    check_region_bound({i: (0, 2), j: (0, 32), k: (0, 32)}, var_dom, mode=\"lowerbound\")\n\n\ndef test_region_lower_bound_negative_scale():\n    i = tvm.tir.Var(\"i\", \"int32\")\n    j = tvm.tir.Var(\"j\", \"int32\")\n    var_dom = {\n        i: tvm.ir.Range(begin=0, end=4),\n        j: tvm.ir.Range(begin=0, end=4),\n    }\n    check_region_bound(\n        {(1 - i, 5 - i): (-2, 5), (20 - j * 4, 36 - j * 4): (8, 36)}, var_dom, mode=\"lowerbound\"\n    )\n\n\ndef test_region_lower_bound_for_non_perfect_tile():\n    h1 = tvm.tir.Var(\"h1\", \"int32\")\n    h2 = tvm.tir.Var(\"h2\", \"int32\")\n    h3 = tvm.tir.Var(\"h3\", \"int32\")\n\n    # non-uniform tiling, single inner variable\n    var_dom = {\n        h2: tvm.ir.Range(begin=0, end=10),\n    }\n    check_region_bound(\n        {\n            h3 * 8\n            + h2: {\n                (): (\n                    tvm.tir.max(h3 * 8, 1),\n                    tvm.tir.max(h3 * 8, 1)\n                    - tvm.tir.max(h3 * 8, 214)\n                    - tvm.tir.max(1 - h3 * 8, 0)\n                    + 224,\n                ),\n                ((h3, 0),): (1, 10),  # h3 == 0: region is [1, 10)\n                ((h3, 10),): (h3 * 8, h3 * 8 + 10),  # 0 < h3 <= 26: region is [h3 * 8, h3 * 8 + 10)\n                ((h3, 27),): (h3 * 8, 224),  # h3 > 26: region is [h3 * 8, 224)\n            }\n        },\n        var_dom,\n        predicate=tvm.tir.all(1 <= h3 * 8 + h2, h3 * 8 + h2 < 224),\n        mode=\"lowerbound\",\n    )\n\n    # non-uniform tiling, two inner variables\n    var_dom = {\n        h1: tvm.ir.Range(begin=0, end=5),\n        h2: tvm.ir.Range(begin=0, end=2),\n    }\n    check_region_bound(\n        {\n            h3 * 8\n            + h2 * 5\n            + h1: {\n                (): (\n                    tvm.tir.max(h3 * 8, 1),\n                    tvm.tir.max(h3 * 8, 1)\n                    - tvm.tir.max(h3 * 8, 214)\n                    - tvm.tir.max(1 - h3 * 8, 0)\n                    + 224,\n                ),\n                ((h3, 0),): (1, 10),\n                ((h3, 10),): (h3 * 8, h3 * 8 + 10),\n                ((h3, 27),): (h3 * 8, 224),\n            }\n        },\n        var_dom,\n        predicate=tvm.tir.all(1 <= h3 * 8 + h2 * 5 + h1, h3 * 8 + h2 * 5 + h1 < 224),\n        mode=\"lowerbound\",\n    )\n\n    # lowerbound should fail on incompatible predicates\n    check_region_bound(\n        {h3 * 8 + h2 * 5 + h1: None},\n        var_dom,\n        predicate=tvm.tir.all(1 <= h3 * 8 + h2 * 5 + h1, h3 * 8 + h1 * 2 + h2 < 224),\n        mode=\"lowerbound\",\n    )\n    check_region_bound(\n        {h3 * 8 + h2 * 5 + h1: (h3 * 8, h3 * 8 + 10)},\n        var_dom,\n        predicate=tvm.tir.all(1 <= h3 * 8 + h2 * 5 + h1, h3 * 8 + h1 * 2 + h2 < 224),\n        mode=\"upperbound\",\n    )\n\n\ndef test_region_lower_bound_unfusable():\n    var_dom = {\n        tvm.tir.Var(\"i\", \"int32\"): tvm.ir.Range(8),\n        tvm.tir.Var(\"j\", \"int32\"): tvm.ir.Range(4),\n    }\n    i, j = var_dom\n    check_region_bound({(i + j) // 2: (0, 6)}, var_dom, mode=\"lowerbound\")\n\n\ndef test_union_lower_bound():\n    neg_inf = tvm.arith.int_set.neg_inf()\n    pos_inf = tvm.arith.int_set.pos_inf()\n    set_0 = tvm.arith.IntervalSet(min_value=neg_inf, max_value=0)\n    set_1 = tvm.arith.IntervalSet(min_value=1, max_value=pos_inf)\n    result = tvm.arith.int_set.union_lower_bound([set_0, set_1])\n    assert result.min_value.same_as(neg_inf)\n    assert result.max_value.same_as(pos_inf)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_iter_affine_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom xml import dom\nimport tvm\nimport tvm.testing\nfrom tvm.tir import floormod, floordiv\n\n\ndef ifuse(inputs, pred_extent=None):\n    \"\"\"Fuse iterators\"\"\"\n    value, extent = 0, 1\n    for i, ext in inputs:\n        value = value * ext + i\n        extent = extent * ext\n    return value, extent if pred_extent is None else pred_extent\n\n\ndef isplit(axis, factor):\n    \"\"\"Split iterators\"\"\"\n    fld = tvm.tir.floordiv\n    flm = tvm.tir.floormod\n    return [\n        (fld(axis[0], factor), fld(axis[1] + (factor - 1), factor)),\n        (flm(axis[0], factor), factor),\n    ]\n\n\ndef var_dom(iters):\n    \"\"\"Get domains of iterators\"\"\"\n    return {var: tvm.ir.Range(0, ext) for var, ext in iters}\n\n\ndef convert_iter_expr(expr):\n    return tvm.arith.normalize_iter_map_to_expr(expr)\n\n\ndef assert_iter_sum_pattern(\n    expect_dict, dom_map, predicate=True, check_level=\"surjective\", simplify_trivial_iterators=True\n):\n    keys = list(expect_dict.keys())\n    res = tvm.arith.detect_iter_map(\n        keys,\n        dom_map,\n        predicate=predicate,\n        check_level=check_level,\n        simplify_trivial_iterators=simplify_trivial_iterators,\n    )\n    indices = res.indices\n    assert len(indices) == len(keys), res.errors\n    for i, input_iter in enumerate(keys):\n        spec = expect_dict[input_iter]\n        (\n            extent,\n            base,\n        ) = spec[0:2]\n        scale = spec[2] if len(spec) > 2 else 1\n        expect_iter = spec[3] if len(spec) > 3 else None\n        sum_expr = indices[i]\n        assert isinstance(sum_expr, tvm.arith.IterSumExpr)\n        if extent == 1:\n            assert len(sum_expr.args) == 0\n        else:\n            assert len(sum_expr.args) == 1\n            tvm.testing.assert_prim_expr_equal(sum_expr.args[0].extent, extent)\n            tvm.testing.assert_prim_expr_equal(sum_expr.args[0].scale, scale)\n        tvm.testing.assert_prim_expr_equal(sum_expr.base, base)\n        if expect_iter is not None:\n            if not isinstance(expect_iter, tvm.arith.IterMapExpr):\n                sum_expr = convert_iter_expr(sum_expr)\n            tvm.ir.assert_structural_equal(sum_expr, expect_iter)\n\n\ndef assert_iter_sum_failure(iters, dom_map, predicate=True, check_level=\"surjective\"):\n    res = tvm.arith.detect_iter_map(\n        list(iters), dom_map, predicate=predicate, check_level=check_level\n    ).indices\n    assert len(res) == 0\n\n\ndef test_trivial():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    z = tvm.tir.Var(\"z\", \"int32\")\n    dom_map = var_dom([(x, 3), (y, 4), (z, 1)])\n\n    assert_iter_sum_pattern({x: (3, 0), y: (4, 0), 3: (1, 3)}, dom_map)\n    assert_iter_sum_pattern({x: (3, 0), 3: (1, 3)}, dom_map)\n\n    # not independent\n    assert_iter_sum_failure([x, x, 3], dom_map)\n\n    assert_iter_sum_pattern(\n        {x: (3, 0), y: (4, 0)}, dom_map, check_level=\"bijective\", simplify_trivial_iterators=True\n    )\n    assert_iter_sum_pattern(\n        {x: (3, 0), y: (4, 0)}, dom_map, check_level=\"bijective\", simplify_trivial_iterators=False\n    )\n    assert_iter_sum_failure([x, z], dom_map, check_level=\"bijective\")\n\n\ndef test_fuse():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    c = tvm.tir.SizeVar(\"c\", \"int32\")\n    c0 = tvm.tir.SizeVar(\"c0\", \"int32\")\n\n    assert_iter_sum_pattern({y * 3 + 1 + c + x: (12, 1 + c)}, var_dom([(x, 3), (y, 4)]))\n\n    assert_iter_sum_pattern({ifuse([(x, 3), (y, 4)])[0]: (12, 0)}, var_dom([(x, 3), (y, 4)]))\n\n    # fuse with symbolic factor\n    assert_iter_sum_pattern({(y + 1) * c + x: (4 * c, c)}, var_dom([(x, c), (y, 4)]))\n\n    # duplication\n    assert_iter_sum_failure([y * 3 + x, y], var_dom([(x, 3), (y, 4)]))\n    assert_iter_sum_failure([y, x + 1, y], var_dom([(x, 3), (y, 4)]))\n\n    # factor mismatch\n    assert_iter_sum_failure([y * 4 + x], var_dom([(x, 3), (y, 4)]))\n\n    # simple stride pattern\n    assert_iter_sum_pattern({x * 4 + y * 2: (6, 0, 2, (x * 2 + y) * 2)}, var_dom([(x, 3), (y, 2)]))\n\n    # simple stride pattern with symbolic\n    assert_iter_sum_pattern(\n        {x * 2 * c0 + y * 2: (3 * c0, 0, 2, (x * c0 + y) * 2)}, var_dom([(x, 3), (y, c0)])\n    )\n\n\ndef test_split():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    c0 = tvm.tir.SizeVar(\"c0\", \"int32\")\n    c1 = tvm.tir.SizeVar(\"c1\", \"int32\")\n    fld = tvm.tir.floordiv\n    flm = tvm.tir.floormod\n\n    assert_iter_sum_pattern({fld(x, 3): (8, 0), flm(x, 3) * 2 + c1: (3, c1, 2)}, var_dom([(x, 24)]))\n\n    assert_iter_sum_pattern(\n        {fld(x, 6): (4, 0), fld(flm(x, 6), 2): (3, 0), flm(x, 2): (2, 0)}, var_dom([(x, 24)])\n    )\n\n    # simple symbolic bound\n    # TODO(tvm-team) improve symbolic divisible check to enable\n    # more complicated symbolic bound\n    assert_iter_sum_pattern({fld(x, c0): (c1, 0), flm(x, c0): (c0, 0)}, var_dom([(x, c1 * c0)]))\n\n    assert_iter_sum_pattern({fld(x * 2, 4): (4, 0, 1), flm(x * 2, 4): (2, 0, 2)}, var_dom([(x, 8)]))\n\n    assert_iter_sum_pattern(\n        {\n            fld(x * 2, 4) * 4 + flm(x * 2, 4): (8, 0, 2),\n        },\n        var_dom([(x, 8)]),\n    )\n\n    assert_iter_sum_failure([fld(x, flm(flm(y, 8), 6))], var_dom([(x, 24), (y, 8)]))\n\n    # domain of x is undefined\n    assert_iter_sum_pattern(\n        {fld(flm(x, 49) + y, 49): (1, fld(flm(x, 49) + y, 49))}, var_dom([(y, 1)])\n    )\n\n\ndef test_compound():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n\n    xo, xi = isplit((x, 10), 5)\n    yo, yi = isplit((y, 9), 3)\n    z = ifuse([yo, xo, yi])\n\n    # reconstruct the pattern manually\n    mx = tvm.arith.IterMark(x, 10)\n    my = tvm.arith.IterMark(y, 9)\n    xoscale = 3\n    yoscale = 6\n    yiscale = 1\n    mxo = tvm.arith.IterSplitExpr(mx, 5, 2, xoscale)\n    myo = tvm.arith.IterSplitExpr(my, 3, 3, yoscale)\n    myi = tvm.arith.IterSplitExpr(my, 1, 3, yiscale)\n    mz = tvm.arith.IterMark(tvm.arith.IterSumExpr([myo, mxo, myi], 0), 18)\n    sz = tvm.arith.IterSumExpr([tvm.arith.IterSplitExpr(mz, 1, 18, 1)], 0)\n    assert_iter_sum_pattern({z[0]: (18, 0, 1, sz), xi[0]: (5, 0)}, var_dom([(x, 10), (y, 9)]))\n\n\ndef test_predicate():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n\n    # available contraints\n    # upper bound only\n    assert_iter_sum_pattern(\n        {x * 10 + y: (128, 0)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 + y < 128\n    )\n\n    assert_iter_sum_pattern(\n        {x * 10 + y: (128, 0)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 + y <= 127\n    )\n\n    # lower bound only\n    assert_iter_sum_pattern(\n        {x * 10 + y: (124, 6)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 + y > 5\n    )\n\n    assert_iter_sum_pattern(\n        {x * 10 + y: (124, 6)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 + y >= 6\n    )\n\n    # lower bound + upper bound\n    assert_iter_sum_pattern(\n        {x * 10 + y: (122, 6)},\n        var_dom([(x, 13), (y, 10)]),\n        predicate=tvm.tir.And(x * 10 + y > 5, x * 10 + y < 128),\n    )\n\n    assert_iter_sum_pattern(\n        {x * 10 + y: (122, 6)},\n        var_dom([(x, 13), (y, 10)]),\n        predicate=tvm.tir.And(x * 10 + y >= 6, x * 10 + y <= 127),\n    )\n\n    # constraint on one fused iter\n    i = tvm.tir.Var(\"i\", \"int32\")\n    j = tvm.tir.Var(\"j\", \"int32\")\n    k = tvm.tir.Var(\"k\", \"int32\")\n    assert_iter_sum_pattern(\n        {i * 8 + j * 2 + k: (88, 1)},\n        var_dom([(i, 11), (j, 5), (k, 2)]),\n        predicate=tvm.tir.all(1 <= j * 2 + k, j * 2 + k < 9),\n    )\n\n    # constraint on single var\n    assert_iter_sum_pattern({i: (10, 0)}, var_dom([(i, 48)]), predicate=i < 10)\n\n    # iterations are subparts of constraint, invalid case 1\n    assert_iter_sum_failure(\n        [i, j, k],\n        var_dom([(i, 128), (j, 128), (k, 128)]),\n        predicate=tvm.tir.all(i * 16384 + j * 128 + k < 100),\n    )\n\n    # iterations are subparts of constraint, invalid case 2\n    assert_iter_sum_failure(\n        [i * 128 + j, k],\n        var_dom([(i, 128), (j, 128), (k, 128)]),\n        predicate=i * 16384 + j * 128 + k < 100,\n    )\n\n    # irrelavant predicate\n    assert_iter_sum_pattern({i + j: (1, j)}, var_dom([(i, 1)]), predicate=j <= 24)\n\n    # constraint on nested fused iters\n    assert_iter_sum_pattern(\n        {i * 8 + j * 2 + k: (22, 3)},\n        var_dom([(i, 11), (j, 5), (k, 2)]),\n        predicate=tvm.tir.all(\n            1 <= j * 2 + k, j * 2 + k < 9, 3 <= i * 8 + j * 2 + k, i * 8 + j * 2 + k < 25\n        ),\n    )\n\n    # duplicate constraint on one fused iter\n    assert_iter_sum_pattern(\n        {i * 6 + j * 2 + k: (66, 2)},\n        var_dom([(i, 11), (j, 5), (k, 2)]),\n        predicate=tvm.tir.all(1 <= j * 2 + k, 2 <= j * 2 + k, j * 2 + k < 8, j * 2 + k < 9),\n    )\n\n    # duplicate constraint on nested fused iters\n    assert_iter_sum_pattern(\n        {i * 6 + j * 2 + k: (15, 3)},\n        var_dom([(i, 11), (j, 5), (k, 2)]),\n        predicate=tvm.tir.all(\n            1 <= j * 2 + k,\n            2 <= j * 2 + k,\n            j * 2 + k < 8,\n            j * 2 + k < 9,\n            3 <= i * 6 + j * 2 + k,\n            i * 6 + j * 2 + k < 25,\n            1 <= i * 6 + j * 2 + k,\n            i * 6 + j * 2 + k < 18,\n        ),\n    )\n\n    # constraint on non-disjoint fused iters should fail\n    assert_iter_sum_failure(\n        [i * 8 + j * 2 + k],\n        var_dom([(i, 11), (j, 5), (k, 2)]),\n        predicate=tvm.tir.all(2 <= j * 2 + k, 0 <= i * 4 + j),\n    )\n\n    # constraint on many disjoint fused iters, case 1\n    # i4 * 6 + i5 in [3, 9), extent=6 (= scale of i2)\n    # i2 * 30 + i3 * 15 in [30, 90), extent=60 (= scale of i1)\n    # i1 * 60 in [60, 240), extent=180 (= scale of i0)\n    i0 = tvm.tir.Var(\"i0\", \"int32\")\n    i1 = tvm.tir.Var(\"i1\", \"int32\")\n    i2 = tvm.tir.Var(\"i2\", \"int32\")\n    i3 = tvm.tir.Var(\"i3\", \"int32\")\n    i4 = tvm.tir.Var(\"i4\", \"int32\")\n    i5 = tvm.tir.Var(\"i5\", \"int32\")\n    assert_iter_sum_pattern(\n        {i0 * 180 + i1 * 60 + i2 * 30 + i3 * 15 + i4 * 6 + i5: (540, 93)},\n        var_dom([(i0, 3), (i1, 4), (i2, 3), (i3, 2), (i4, 3), (i5, 6)]),\n        predicate=tvm.tir.all(1 <= i1, 2 <= i2 * 2 + i3, 3 <= i4 * 6 + i5),\n    )\n\n    # constraint on many disjoint fused iters, case 2\n    assert_iter_sum_pattern(\n        {i0 * 45 + i1 * 45 + i2 * 9 + i3 * 4 + i4: (135, 28)},\n        var_dom([(i0, 3), (i1, 2), (i2, 5), (i3, 3), (i4, 4)]),\n        predicate=tvm.tir.all(\n            3 <= i1 * 5 + i2, i1 * 5 + i2 < 8, 1 <= i3 * 4 + i4, i3 * 4 + i4 < 10\n        ),\n    )\n\n    # constraint on split iters\n    assert_iter_sum_pattern(\n        {i % 16: (7, 3), i // 16: (8, 4)},\n        var_dom([(i, 1024)]),\n        predicate=tvm.tir.all(3 <= i % 16, i % 16 < 10, 4 <= i // 16, i // 16 < 12),\n        check_level=\"bijective\",\n    )\n\n    # constraint on split iters, nested case 1\n    assert_iter_sum_pattern(\n        {(i * 32 + j) % 16: (7, 3)},\n        var_dom([(i, 5), (j, 32)]),\n        predicate=tvm.tir.all(3 <= (i * 32 + j) % 16, (i * 32 + j) % 16 < 10),\n    )\n\n    # constraint on split iters, nested case 2\n    assert_iter_sum_failure(\n        [\n            (i * 32 + j) % 16,\n        ],\n        var_dom([(i, 5), (j, 32)]),\n        predicate=tvm.tir.all(1 <= i * 32 + j, i * 32 + j <= 32),\n        check_level=\"bijective\",\n    )\n    assert_iter_sum_pattern(\n        {(i * 32 + j) % 16: (16, 0)},\n        var_dom([(i, 5), (j, 32)]),\n        predicate=tvm.tir.all(1 <= i * 32 + j, i * 32 + j <= 32),\n    )\n    assert_iter_sum_pattern(\n        {(i * 32 + j - 1) % 16: (16, 0), (i * 32 + j - 1) // 16: (4, 0)},\n        var_dom([(i, 5), (j, 32)]),\n        predicate=tvm.tir.all(1 <= i * 32 + j, i * 32 + j <= 64),\n    )\n\n    # non-standard form of predicate\n    assert_iter_sum_pattern(\n        {x * 10 + y: (128, 0)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 < 128 - y\n    )\n\n    # duplicate constraint\n    assert_iter_sum_pattern(\n        {x * 10 + y: (64, 0)},\n        var_dom([(x, 13), (y, 10)]),\n        predicate=tvm.tir.all(x * 10 + y < 128, x * 10 + y < 64),\n    )\n\n    # useless constraint\n    assert_iter_sum_pattern(\n        {x * 10 + y: (130, 0)}, var_dom([(x, 13), (y, 10)]), predicate=x * 10 + y < 140\n    )\n\n    i1 = tvm.tir.Var(\"i1\", \"int32\")\n    i2 = tvm.tir.Var(\"i2\", \"int32\")\n    i3 = tvm.tir.Var(\"i3\", \"int32\")\n    i4 = tvm.tir.Var(\"i4\", \"int32\")\n    assert_iter_sum_pattern(\n        {i1 * 20 + i2 * 10 + i3 * 3 + i4: (128, 0)},\n        var_dom([(i1, 7), (i2, 2), (i3, 4), (i4, 3)]),\n        predicate=(\n            tvm.tir.all(\n                i1 * 2 + i2 < 13,\n                i1 * 20 + i2 * 10 + i3 * 3 + i4 < 128,\n                i3 * 3 + i4 < 10,\n            )\n        ),\n    )\n\n    # wrong constraint\n    assert_iter_sum_failure(\n        [i1 * 20 + i2 * 10 + i3 * 3 + i4],\n        var_dom([(i1, 7), (i2, 2), (i3, 4), (i4, 3)]),\n        predicate=(\n            tvm.tir.all(\n                i1 * 2 + i2 < 13,\n                i1 * 20 + i2 * 10 + i3 * 3 + i4 < 128,\n                i3 * 3 + i4 < 7,\n            )\n        ),\n    )\n\n    # incompatible constraint\n    assert_iter_sum_failure(\n        [i1 * 20 + i2 * 10 + i3 * 3 + i4],\n        var_dom([(i1, 7), (i2, 2), (i3, 4), (i4, 3)]),\n        predicate=(\n            tvm.tir.all(\n                i1 * 2 + i2 < 13,\n                i1 * 20 + i2 * 10 + i3 * 3 + i4 < 128,\n                i3 * 3 + i4 < 10,\n                i1 * 4 + i3 < 20,\n            )\n        ),\n    )\n    assert_iter_sum_failure(\n        [i1 * 20 + i2 * 10 + i3 * 3 + i4],\n        var_dom([(i1, 7), (i2, 2), (i3, 4), (i4, 3)]),\n        predicate=(\n            tvm.tir.all(\n                i1 * 2 + i2 < 13,\n                i1 * 20 + i2 * 10 + i3 * 3 + i4 < 128,\n                i1 * 4 + i3 < 20,\n            )\n        ),\n    )\n\n    # zero iter\n    xo = tvm.tir.Var(\"xo\", \"int32\")\n    xi = tvm.tir.Var(\"xi\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    assert_iter_sum_pattern(\n        {xo * 129 + xi: (128, 0), y: (128, 0)},\n        var_dom([(xo, 1), (xi, 129), (y, 128)]),\n        predicate=xo * 129 + xi < 128,\n    )\n\n    # strided iteration predicate\n    assert_iter_sum_pattern(\n        {xo * 16 + xi * 4: (10, 0, 4)},\n        var_dom([(xo, 3), (xi, 4)]),\n        predicate=xo * 4 + xi < 10,\n    )\n\n\ndef convert_division(divisions):\n    if divisions is None or len(divisions) == 0:\n        return []\n    res = []\n    for division in divisions[:-1]:\n        res.append(\n            [\n                tvm.arith.normalize_iter_map_to_expr(division[0].source),\n                tvm.arith.normalize_iter_map_to_expr(division[1].source),\n            ]\n        )\n    res.append([divisions[-1][0].extent, divisions[-1][1].extent])\n    return res\n\n\ndef create_iter(name, extent):\n    return tvm.tir.Var(name, \"int32\"), extent\n\n\ndef test_subspace_division():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    z = tvm.tir.Var(\"z\", \"int32\")\n    c = tvm.tir.SizeVar(\"c\", \"int32\")\n\n    # simple 1.1\n    res = tvm.arith.subspace_divide(\n        [z * 12 + y * 3 + x + c], var_dom([(x, 3), (y, 4), (z, 5)]), [x]\n    )\n    res = convert_division(res)\n    assert len(res) == 2\n    tvm.ir.assert_structural_equal(res[0][0], z * 4 + y)\n    tvm.ir.assert_structural_equal(res[0][1], x + c)\n\n    # simple 1.2\n    res = tvm.arith.subspace_divide(\n        [z * 12 + y * 3 + x + c], var_dom([(x, 3), (y, 4), (z, 5)]), [x], z * 4 + y < 18\n    )\n    res = convert_division(res)\n    assert len(res) == 2\n    tvm.ir.assert_structural_equal(res[0][0], z * 4 + y)\n    tvm.ir.assert_structural_equal(res[0][1], x + c)\n    tvm.ir.assert_structural_equal(res[1][0], z * 4 + y < 18)\n    tvm.ir.assert_structural_equal(res[1][1], True)\n\n    # compound 1\n    i0 = create_iter(\"i0\", 4)\n    j0 = create_iter(\"j0\", 8)\n    i3 = create_iter(\"i3\", 2)\n\n    i1, i2 = isplit(j0, 4)\n    k0 = ifuse([i0, i1])\n    k1 = ifuse([i2, i3])\n\n    # compound 1.1\n    res = tvm.arith.subspace_divide([k0[0], k1[0]], var_dom([i0, j0, i3]), [i3[0]])\n    res = convert_division(res)\n    assert len(res) == 3\n    tvm.ir.assert_structural_equal(res[0][0], (i0[0] * 2) + floordiv(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[0][1], 0)\n    tvm.ir.assert_structural_equal(res[1][0], floormod(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[1][1], i3[0])\n\n    assert_iter_sum_pattern\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1]], var_dom([i3])).indices\n    assert len(res1) == 2\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0]], var_dom([i0, j0])).indices\n    assert len(res2) == 2\n\n    # compound 1.2\n    res = tvm.arith.subspace_divide([k0[0], k1[0]], var_dom([i0, j0, i3]), [j0[0], i3[0]])\n    res = convert_division(res)\n    assert len(res) == 3\n    tvm.ir.assert_structural_equal(res[0][0], i0[0])\n    tvm.ir.assert_structural_equal(res[0][1], floordiv(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[1][0], 0)\n    tvm.ir.assert_structural_equal(res[1][1], (floormod(j0[0], 4) * 2) + i3[0])\n\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1]], var_dom([j0, i3])).indices\n    assert len(res1) == 2\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0]], var_dom([i0])).indices\n    assert len(res2) == 2\n\n    # compound 1.3\n    res = tvm.arith.subspace_divide([k0[0], k1[0]], var_dom([i0, j0, i3]), [i0[0], i3[0]])\n    res = convert_division(res)\n    assert len(res) == 0\n\n    # compound 1.4\n    res = tvm.arith.subspace_divide([k0[0], k1[0]], var_dom([i0, j0, i3]), [i3[0]], k0[0] < 7)\n    res = convert_division(res)\n    assert len(res) == 3\n    tvm.ir.assert_structural_equal(res[0][0], (i0[0] * 2) + floordiv(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[0][1], 0)\n    tvm.ir.assert_structural_equal(res[1][0], floormod(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[1][1], i3[0])\n    tvm.ir.assert_structural_equal(res[2][0], (i0[0] * 2) + floordiv(j0[0], 4) < 7)\n    tvm.ir.assert_structural_equal(res[2][1], True)\n\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1]], var_dom([i3])).indices\n    assert len(res1) == 2\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0]], var_dom([i0, j0])).indices\n    assert len(res2) == 2\n\n    # compound 1.5\n    res = tvm.arith.subspace_divide(\n        [k0[0], k1[0]], var_dom([i0, j0, i3]), [j0[0], i3[0]], k1[0] < 7\n    )\n    res = convert_division(res)\n    assert len(res) == 3\n    tvm.ir.assert_structural_equal(res[0][0], i0[0])\n    tvm.ir.assert_structural_equal(res[0][1], floordiv(j0[0], 4))\n    tvm.ir.assert_structural_equal(res[1][0], 0)\n    tvm.ir.assert_structural_equal(res[1][1], (floormod(j0[0], 4) * 2) + i3[0])\n    tvm.ir.assert_structural_equal(res[2][0], True)\n    tvm.ir.assert_structural_equal(res[2][1], (floormod(j0[0], 4) * 2) + i3[0] < 7)\n\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1]], var_dom([j0, i3])).indices\n    assert len(res1) == 2\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0]], var_dom([i0])).indices\n    assert len(res2) == 2\n\n    # compound 1.6\n    res = tvm.arith.subspace_divide(\n        [k0[0], k1[0]], var_dom([i0, j0, i3]), [i3[0]], tvm.tir.all(k0[0] < 7, k1[0] < 7)\n    )\n    res = convert_division(res)\n    assert len(res) == 0\n\n    # compound 2\n    j0 = create_iter(\"j0\", 4)\n    l0 = create_iter(\"l0\", 2)\n    l1 = create_iter(\"l1\", 6)\n    j3 = create_iter(\"j3\", 3)\n\n    k0 = ifuse([l0, l1])\n    i1, j2 = isplit(k0, 3)\n    j1, i1 = isplit(i1, 2)\n    i0 = ifuse([j0, j1])\n    i2 = ifuse([j2, j3])\n\n    # compound 2.1\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0], i2[0]], var_dom([j0, l0, l1, j3]), [l1[0], j3[0]]\n    )\n    res = convert_division(res)\n    assert len(res) == 4\n    tvm.ir.assert_structural_equal(res[0][0], (j0[0] * 2) + l0[0])\n    tvm.ir.assert_structural_equal(res[0][1], 0)\n    tvm.ir.assert_structural_equal(res[1][0], 0)\n    tvm.ir.assert_structural_equal(res[1][1], floordiv(l1[0], 3))\n    tvm.ir.assert_structural_equal(res[2][0], 0)\n    tvm.ir.assert_structural_equal(res[2][1], (floormod(l1[0], 3) * 3) + j3[0])\n\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1], res[2][1]], var_dom([l1, j3])).indices\n    assert len(res1) == 3\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0], res[2][0]], var_dom([j0, l0])).indices\n    assert len(res2) == 3\n\n    # compound 2.2\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0], i2[0]], var_dom([j0, l0, l1, j3]), [l0[0], l1[0], j3[0]]\n    )\n    res = convert_division(res)\n    assert len(res) == 4\n    tvm.ir.assert_structural_equal(res[0][0], j0[0])\n    tvm.ir.assert_structural_equal(res[0][1], floordiv(l0[0] * 6 + l1[0], 6))\n    tvm.ir.assert_structural_equal(res[1][0], 0)\n    tvm.ir.assert_structural_equal(res[1][1], floordiv(floormod(l0[0] * 6 + l1[0], 6), 3))\n    tvm.ir.assert_structural_equal(res[2][0], 0)\n    tvm.ir.assert_structural_equal(res[2][1], (floormod(l0[0] * 6 + l1[0], 3) * 3) + j3[0])\n\n    res1 = tvm.arith.detect_iter_map(\n        [res[0][1], res[1][1], res[2][1]], var_dom([l0, l1, j3])\n    ).indices\n    assert len(res1) == 3\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0], res[2][0]], var_dom([j0])).indices\n    assert len(res2) == 3\n\n    # compound 2.3\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0], i2[0]], var_dom([j0, l0, l1, j3]), [l0[0], j3[0]]\n    )\n    res = convert_division(res)\n    assert len(res) == 0\n\n    # compound 2.4\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0], i2[0]],\n        var_dom([j0, l0, l1, j3]),\n        [l1[0], j3[0]],\n        tvm.tir.all(i0[0] < 7, i2[0] < 8),\n    )\n    res = convert_division(res)\n    assert len(res) == 4\n    tvm.ir.assert_structural_equal(res[0][0], (j0[0] * 2) + l0[0])\n    tvm.ir.assert_structural_equal(res[0][1], 0)\n    tvm.ir.assert_structural_equal(res[1][0], 0)\n    tvm.ir.assert_structural_equal(res[1][1], floordiv(l1[0], 3))\n    tvm.ir.assert_structural_equal(res[2][0], 0)\n    tvm.ir.assert_structural_equal(res[2][1], (floormod(l1[0], 3) * 3) + j3[0])\n    tvm.ir.assert_structural_equal(res[3][0], (j0[0] * 2) + l0[0] < 7)\n    tvm.ir.assert_structural_equal(res[3][1], (floormod(l1[0], 3) * 3) + j3[0] < 8)\n\n    res1 = tvm.arith.detect_iter_map([res[0][1], res[1][1], res[2][1]], var_dom([l1, j3])).indices\n    assert len(res1) == 3\n    res2 = tvm.arith.detect_iter_map([res[0][0], res[1][0], res[2][0]], var_dom([j0, l0])).indices\n    assert len(res2) == 3\n\n    # compound 2.5\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0], i2[0]], var_dom([j0, l0, l1, j3]), [j3[0]], i2[0] < 8\n    )\n    res = convert_division(res)\n    assert len(res) == 0\n\n\ndef test_complex():\n    n0 = create_iter(\"n0\", 2)\n    n1 = create_iter(\"n1\", 4)\n\n    m0 = ifuse([n0, n1], 6)\n    m1 = create_iter(\"m1\", 3)\n\n    l0 = create_iter(\"l0\", 4)\n    l1 = create_iter(\"l1\", 8)\n    l2 = ifuse([m0, m1], 16)\n    l3 = create_iter(\"l3\", 32)\n\n    k0, k4 = isplit(l0, 2)\n    k1, k5 = isplit(l1, 2)\n    k2, k6 = isplit(l2, 4)\n    k3, k7 = isplit(l3, 4)\n\n    j0 = ifuse([k0, k1], 7)\n    j1 = ifuse([k2, k3])\n    j2 = ifuse([k4, k5])\n    j3 = ifuse([k6, k7], 15)\n\n    i0 = ifuse([j0, j1], 200)\n    i1 = ifuse([j2, j3], 50)\n\n    n0_mark = tvm.arith.IterMark(n0[0], n0[1])\n    n1_mark = tvm.arith.IterMark(n1[0], n1[1])\n    l0_mark = tvm.arith.IterMark(l0[0], l0[1])\n    l1_mark = tvm.arith.IterMark(l1[0], l1[1])\n    m1_mark = tvm.arith.IterMark(m1[0], m1[1])\n    l3_mark = tvm.arith.IterMark(l3[0], l3[1])\n\n    m0_expr = tvm.arith.IterSumExpr(\n        [\n            tvm.arith.IterSplitExpr(n0_mark, 1, n0[1], 4),\n            tvm.arith.IterSplitExpr(n1_mark, 1, n1[1], 1),\n        ],\n        0,\n    )\n    m0_mark = tvm.arith.IterMark(m0_expr, 6)\n    l2_expr = tvm.arith.IterSumExpr(\n        [tvm.arith.IterSplitExpr(m0_mark, 1, 6, 3), tvm.arith.IterSplitExpr(m1_mark, 1, m1[1], 1)],\n        0,\n    )\n    l2_mark = tvm.arith.IterMark(l2_expr, 16)\n    k0_expr = tvm.arith.IterSplitExpr(l0_mark, 2, 2, 4)\n    k1_expr = tvm.arith.IterSplitExpr(l1_mark, 2, 4, 1)\n    k2_expr = tvm.arith.IterSplitExpr(l2_mark, 4, 4, 8)\n    k3_expr = tvm.arith.IterSplitExpr(l3_mark, 4, 8, 1)\n    k4_expr = tvm.arith.IterSplitExpr(l0_mark, 1, 2, 30)\n    k5_expr = tvm.arith.IterSplitExpr(l1_mark, 1, 2, 15)\n    k6_expr = tvm.arith.IterSplitExpr(l2_mark, 1, 4, 4)\n    k7_expr = tvm.arith.IterSplitExpr(l3_mark, 1, 4, 1)\n\n    j0_expr = tvm.arith.IterSumExpr([k0_expr, k1_expr], 0)\n    j0_mark = tvm.arith.IterMark(j0_expr, 7)\n    i0_expr = tvm.arith.IterSumExpr(\n        [tvm.arith.IterSplitExpr(j0_mark, 1, 7, 32), k2_expr, k3_expr], 0\n    )\n\n    j3_expr = tvm.arith.IterSumExpr([k6_expr, k7_expr], 0)\n    j3_mark = tvm.arith.IterMark(j3_expr, 15)\n    i1_expr = tvm.arith.IterSumExpr(\n        [k4_expr, k5_expr, tvm.arith.IterSplitExpr(j3_mark, 1, 15, 1)], 0\n    )\n\n    i0_mark = tvm.arith.IterMark(i0_expr, i0[1])\n    i1_mark = tvm.arith.IterMark(i1_expr, i1[1])\n\n    i0_final = tvm.arith.IterSumExpr([tvm.arith.IterSplitExpr(i0_mark, 1, i0[1], 1)], 0)\n    i1_final = tvm.arith.IterSumExpr([tvm.arith.IterSplitExpr(i1_mark, 1, i1[1], 1)], 0)\n\n    assert_iter_sum_pattern(\n        {i0[0]: (200, 0, 1, i0_final), i1[0]: (50, 0, 1, i1_final)},\n        var_dom([l0, l1, n0, n1, m1, l3]),\n        predicate=tvm.tir.all(\n            i0[0] < 200, i1[0] < 50, m0[0] < 6, l2[0] < 16, j0[0] < 7, j3[0] < 15\n        ),\n    )\n\n    # wrong constraint\n    assert_iter_sum_failure(\n        [i0[0], i1[0]],\n        var_dom([l0, l1, n0, n1, m1, l3]),\n        tvm.tir.all(i0[0] < 200, i1[0] < 50, m0[0] < 9, l2[0] < 16, j0[0] < 7, j3[0] < 14),\n    )\n\n    # subspace_division\n    res = tvm.arith.subspace_divide(\n        [i0[0], i1[0]],\n        var_dom([l0, l1, n0, n1, m1, l3]),\n        [n0[0], n1[0], m1[0], l3[0]],\n        tvm.tir.all(m0[0] < 6, l2[0] < 16, j0[0] < 7, j3[0] < 15),\n    )\n    res = convert_division(res)\n    assert len(res) == 3\n    tvm.ir.assert_structural_equal(res[0][0], floordiv(l0[0], 2) * 4 + floordiv(l1[0], 2))\n    tvm.ir.assert_structural_equal(\n        res[0][1], (floordiv((n0[0] * 4 + n1[0]) * 3 + m1[0], 4) * 8) + floordiv(l3[0], 4)\n    )\n    tvm.ir.assert_structural_equal(res[1][0], ((floormod(l0[0], 2) * 2) + floormod(l1[0], 2)))\n    tvm.ir.assert_structural_equal(\n        res[1][1], ((floormod(((n0[0] * 4 + n1[0]) * 3 + m1[0]), 4) * 4) + floormod(l3[0], 4))\n    )\n    tvm.ir.assert_structural_equal(res[2][0], (floordiv(l0[0], 2) * 4) + floordiv(l1[0], 2) < 7)\n    tvm.ir.assert_structural_equal(\n        res[2][1],\n        tvm.tir.all(\n            n0[0] * 4 + n1[0] < 6,\n            (n0[0] * 4 + n1[0]) * 3 + m1[0] < 16,\n            floormod(((n0[0] * 4 + n1[0]) * 3 + m1[0]), 4) * 4 + floormod(l3[0], 4) < 15,\n        ),\n    )\n\n    assert_iter_sum_pattern(\n        {res[0][1]: (32, 0), res[1][1]: (15, 0)}, var_dom([n0, n1, m1, l3]), res[2][1]\n    )\n    assert_iter_sum_pattern({res[0][0]: (8, 0), res[1][0]: (4, 0)}, var_dom([l0, l1]))\n\n\ndef test_normalize_iter_map_to_expr():\n    fld = tvm.tir.floordiv\n    flm = tvm.tir.floormod\n\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n\n    xo, xi = isplit((x, 10), 5)\n    yo, yi = isplit((y, 9), 3)\n    z = ifuse([yo, xo, yi])\n    res = tvm.arith.detect_iter_map([z[0], xi[0]], var_dom([(x, 10), (y, 9)]))\n\n    tvm.ir.assert_structural_equal(\n        tvm.arith.normalize_iter_map_to_expr(res.indices[0]),\n        fld(y, 3) * 6 + fld(x, 5) * 3 + flm(y, 3),\n    )\n    tvm.ir.assert_structural_equal(tvm.arith.normalize_iter_map_to_expr(res.indices[1]), flm(x, 5))\n\n    # iter mark wrap a complex expr\n    split = tvm.arith.IterSplitExpr(tvm.arith.IterMark(x * y + 1, 1024), 1, 1024, 1)\n    tvm.ir.assert_structural_equal(tvm.arith.normalize_iter_map_to_expr(split), x * y + 1)\n\n\ndef test_inverse_affine_iter_map():\n    analyzer = tvm.arith.Analyzer()\n    l0 = create_iter(\"l0\", 64)\n    l1 = create_iter(\"l1\", 64)\n    l2 = create_iter(\"l2\", 64)\n\n    # simple case\n    l0_0, l0_1 = isplit(l0, 16)\n    l1_0, l1_1 = isplit(l1, 4)\n    l0_1_l1_1_fused = ifuse([l0_1, l1_1])\n\n    iter_map = tvm.arith.detect_iter_map(\n        [l0_1_l1_1_fused[0], l0_0[0], l1_0[0]], var_dom([l0, l1])\n    ).indices\n    outputs = [tvm.tir.Var(\"output_{}\".format(i), \"int32\") for i in range(len(iter_map))]\n    res = tvm.arith.inverse_affine_iter_map(iter_map, outputs)\n    assert len(res) == 2\n    l0_inverse = floordiv(outputs[0], 4) + outputs[1] * 16\n    l1_inverse = floormod(outputs[0], 4) + outputs[2] * 4\n    assert analyzer.can_prove_equal(res[l0[0]], l0_inverse)\n    assert analyzer.can_prove_equal(res[l1[0]], l1_inverse)\n\n    # compound case\n    l0_0, l0_1 = isplit(l0, 16)\n    l1_0, l1_1 = isplit(l1, 4)\n    l2_1, l2_2 = isplit(l2, 4)\n    l2_0, l2_1 = isplit(l2_1, 4)\n\n    l0_1_l2_1_l1_1_l2_0_fused = ifuse([l0_1, l2_1, l1_1, l2_0])\n\n    iter_map = tvm.arith.detect_iter_map(\n        [l0_1_l2_1_l1_1_l2_0_fused[0], l0_0[0], l2_2[0], l1_0[0]], var_dom([l0, l1, l2])\n    ).indices\n    outputs = [tvm.tir.Var(\"output_{}\".format(i), \"int32\") for i in range(len(iter_map))]\n    res = tvm.arith.inverse_affine_iter_map(iter_map, outputs)\n    assert len(res) == 3\n    l0_inverse = floordiv(outputs[0], 64) + outputs[1] * 16\n    l1_inverse = floormod(floordiv(outputs[0], 4), 4) + outputs[3] * 4\n    l2_inverse = (\n        floormod(outputs[0], 4) * 16 + floormod(floordiv(outputs[0], 16), 4) * 4 + outputs[2]\n    )\n\n    assert analyzer.can_prove_equal(res[l0[0]], l0_inverse)\n    assert analyzer.can_prove_equal(res[l1[0]], l1_inverse)\n    assert analyzer.can_prove_equal(res[l2[0]], l2_inverse)\n\n    # diamond-shape DAG\n    l0_0, l0_1 = isplit(l0, 16)\n    l1 = ifuse([l0_1, l0_0])\n    l1_0, l1_1 = isplit(l1, 8)\n    l2 = ifuse([l1_1, l1_0])\n\n    iter_map = tvm.arith.detect_iter_map([l2[0]], var_dom([l0])).indices\n    outputs = [tvm.tir.Var(\"output_{}\".format(i), \"int32\") for i in range(len(iter_map))]\n    res = tvm.arith.inverse_affine_iter_map(iter_map, outputs)\n    assert len(res) == 1\n    l1_inverse = floormod(outputs[0], 8) * 8 + floordiv(outputs[0], 8)\n    l0_inverse = floormod(l1_inverse, 4) * 16 + floordiv(l1_inverse, 4)\n\n    assert analyzer.can_prove_equal(res[l0[0]], l0_inverse)\n\n\ndef test_inverse_affine_map_trivial_iter():\n    analyzer = tvm.arith.Analyzer()\n    l0 = create_iter(\"l0\", 64)\n    l1 = create_iter(\"l1\", 64)\n    iter_map = tvm.arith.detect_iter_map([0, l0[0], l1[0]], var_dom([l0, l1])).indices\n    outputs = [tvm.tir.Var(\"output_{}\".format(i), \"int32\") for i in range(len(iter_map))]\n    res = tvm.arith.inverse_affine_iter_map(iter_map, outputs)\n    # output_0 is expected to be constant and it is not included in the inverse map\n    assert len(res) == 2\n    assert analyzer.can_prove_equal(res[l0[0]], outputs[1])\n    assert analyzer.can_prove_equal(res[l1[0]], outputs[2])\n\n\ndef test_free_variables():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    z = tvm.tir.Var(\"z\", \"int32\")\n\n    # illegal iter if z is within dom\n    assert_iter_sum_failure([z * 19 + y * 3 + x], var_dom([(x, 3), (y, 3), (z, 3)]))\n\n    # iter is valid if z is free, even there are linear forms of z\n    assert_iter_sum_pattern(\n        {z * 19 + y * 3 + x: (9, z * 19)},\n        var_dom(\n            [\n                (x, 3),\n                (y, 3),\n            ]\n        ),\n    )\n    assert_iter_sum_pattern(\n        {z * z + y * 3 + x: (9, z * z)},\n        var_dom(\n            [\n                (x, 3),\n                (y, 3),\n            ]\n        ),\n    )\n\n\ndef test_padding():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    fld = tvm.tir.floordiv\n    flm = tvm.tir.floormod\n\n    # left padding only, offset divisible\n    sum = 64 + y\n    dom_map = var_dom([(y, 192)])\n    assert_iter_sum_pattern(\n        {fld(sum, 32): (6, 2, 1), flm(sum, 32): (32, 0, 1)},\n        dom_map,\n        check_level=\"bijective\",\n    )\n\n    # left padding only, offset non-divisible\n    sum = 80 + y\n    dom_map = var_dom([(y, 176)])\n    assert_iter_sum_pattern(\n        {fld(sum, 32): (6, 2, 1)},\n        dom_map,\n    )\n    assert_iter_sum_pattern(\n        {flm(fld(sum, 2), 16): (16, 0, 1), flm(sum, 2): (2, 0, 1)},\n        dom_map,\n    )\n    assert_iter_sum_failure({fld(sum, 32), flm(sum, 32)}, dom_map)\n    assert_iter_sum_failure({fld(sum, 32), fld(sum, 4)}, dom_map)\n\n    # right padding only, offset divisible\n    sum = x * 32 + y * 8\n    dom_map = var_dom([(x, 5), (y, 4)])\n    assert_iter_sum_pattern(\n        {fld(sum, 16): (10, 0, 1), flm(sum, 16): (2, 0, 8)},\n        dom_map,\n    )\n    assert_iter_sum_failure({fld(sum, 5)}, dom_map)\n\n    # right padding only, offset non-divisible\n    dom_map = var_dom([(x, 26)])\n    assert_iter_sum_pattern(\n        {fld(x, 15): (2, 0, 1)},\n        dom_map,\n    )\n    assert_iter_sum_pattern(\n        {flm(fld(x, 3), 5): (5, 0, 1), flm(x, 3): (3, 0, 1)},\n        dom_map,\n    )\n\n    # padding constants on both side\n    sum = x + 71\n    dom_map = var_dom([(x, 45)])\n    assert_iter_sum_pattern({fld(sum, 32): (2, 2, 1)}, dom_map)\n    assert_iter_sum_pattern(\n        {flm(fld(x, 4), 8): (8, 0, 1), flm(x, 4): (4, 0, 1)},\n        dom_map,\n    )\n\n    # padding for free iteration part\n    sum = x * 360 + y\n    dom_map = var_dom([(y, 360)])\n    assert_iter_sum_pattern({fld(sum, 16): (23, fld(x * 360 - flm(x, 2) * 8, 16), 1)}, dom_map)\n    assert_iter_sum_pattern({flm(x * 360 + y, 16): (16, 0, 1)}, dom_map)\n\n    # multiple split with same mark offset, could\n    # be surjective on missing (padded // LCM)\n    assert_iter_sum_pattern(\n        {\n            flm(x + 10, 3): (3, 0),\n            flm(fld(x + 10, 3), 4): (4, 0),\n            flm(fld(fld(x + 10, 3), 4), 5): (5, 0),\n        },\n        var_dom([(x, 240)]),\n    )\n    assert_iter_sum_failure(\n        {\n            flm(x + 10, 3),\n            flm(fld(x + 10, 3), 4),\n            flm(fld(fld(x + 10, 3), 4), 5),\n            fld(fld(fld(x + 10, 3), 4), 5),\n        },\n        var_dom([(x, 240)]),\n    )\n\n    # different offsets on splits\n    assert_iter_sum_pattern(\n        {\n            flm(x + 1, 3): (3, 0),\n            flm(fld(x + 10, 3) + 2, 4): (4, 0),\n            flm(fld(fld(x + 10, 3), 4) + 3, 5): (5, 0),\n        },\n        var_dom([(x, 240)]),\n    )\n\n    # original extent is smaller than the divident\n    # it is not surjective wrt to the region [0, 16)\n    assert_iter_sum_failure({flm(x, 16)}, var_dom([(x, 3)]))\n\n\ndef test_overlapped_fuse():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    z = tvm.tir.Var(\"z\", \"int32\")\n    a = tvm.tir.Var(\"x\", \"int32\")\n    b = tvm.tir.Var(\"y\", \"int32\")\n\n    # non-bijective fuse of two\n    assert_iter_sum_pattern(\n        {\n            x * 7 + y: (22, 0, 1),\n        },\n        var_dom([(x, 3), (y, 8)]),\n        check_level=\"surjective\",\n    )\n    assert_iter_sum_failure([x * 7 + y], var_dom([(x, 3), (y, 8)]), check_level=\"bijective\")\n\n    # non-bijective fuse of three\n    assert_iter_sum_pattern(\n        {\n            x * 18 + y * 7 + z: (40, 0, 1),\n        },\n        var_dom([(x, 2), (y, 3), (z, 8)]),\n        check_level=\"surjective\",\n    )\n    assert_iter_sum_failure([x * 7 + y], var_dom([(x, 2), (y, 3), (z, 8)]), check_level=\"bijective\")\n\n    # negative scale fusion is not allowed\n    assert_iter_sum_failure([x * -7 + y], var_dom([(x, 3), (y, 8)]), check_level=\"surjective\")\n    assert_iter_sum_failure([x * 7 - y], var_dom([(x, 3), (y, 8)]), check_level=\"surjective\")\n\n    # with predicate\n    assert_iter_sum_pattern(\n        {\n            a * 40 + b * 20 + x * 18 + y * 3 + z: (125, 6, 1),\n        },\n        var_dom([(a, 3), (b, 2), (x, 2), (y, 6), (z, 8)]),\n        predicate=tvm.tir.all(z < 4, 1 < x * 6 + y, x * 6 + y < 10),\n        check_level=\"surjective\",\n    )\n\n    # stride=1 kernel\n    assert_iter_sum_pattern(\n        {x + a: (230, 0, 1)}, var_dom([(x, 224), (a, 7)]), check_level=\"surjective\"\n    )\n\n    # do not allow both strided and overlapped\n    assert_iter_sum_failure([5 * x + 2 * y], var_dom([(x, 4), (y, 3)]), check_level=\"surjective\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_modular_set.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\ndef test_cast():\n    analyzer = tvm.arith.Analyzer()\n    x = te.var(\"x\", dtype=\"int8\")\n    m = analyzer.modular_set((x * 3).astype(\"uint32\"))\n    assert m.coeff == 3\n    assert m.base == 0\n    m = analyzer.modular_set((x * 3 + 1).astype(\"float32\").astype(\"int32\"))\n    assert m.coeff == 3\n    assert m.base == 1\n\n\ndef test_add_sub():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\", \"int64\"), te.var(\"y\", \"int64\")\n    m = analyzer.modular_set(x * 6 + y * 4)\n    assert m.coeff == 2\n    assert m.base == 0\n\n    analyzer.bind(y, x * 4 + 1)\n    m = analyzer.modular_set(1 - y)\n    assert m.coeff == 4\n    assert m.base == 0\n\n\ndef test_mul():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    m = analyzer.modular_set((x * 4 + 2) * (y * 6 + 1))\n    assert m.coeff == 4\n    assert m.base == 2\n\n\ndef test_floormod():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    m = analyzer.modular_set(tvm.tir.floormod(x * 128 + y * 4, 256))\n    assert m.coeff == 4\n    assert m.base == 0\n\n\ndef test_div_shift():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    # not sure if x is non-negative\n    tdiv = tvm.tir.truncdiv\n    m = analyzer.modular_set(tdiv(x * 4 + 2, 2))\n    assert m.coeff == 1\n    assert m.base == 0\n    # right shift always round down so it is fine\n    m = analyzer.modular_set((x * 4 + 2) >> 1)\n    assert m.coeff == 2\n    assert m.base == 1\n    fld = tvm.te.floordiv\n    m = analyzer.modular_set(fld(x * 4 + 2, 2))\n    assert m.coeff == 2\n    assert m.base == 1\n    # x is non-negative\n    analyzer.update(x, tvm.arith.ConstIntBound(0, 100))\n    m = analyzer.modular_set(tdiv(x * 4 + 2, 2))\n    assert m.coeff == 2\n    assert m.base == 1\n\n\ndef test_mod():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    tmod = tvm.tir.truncmod\n    fmod = tvm.tir.floormod\n    # not sure if x is non-negative\n    m = analyzer.modular_set(tmod(x * 4 + 1, 4))\n    assert m.coeff == 1\n    assert m.base == 0\n    # no need to be positive if base == 0\n    m = analyzer.modular_set(tmod(x * 4, 4))\n    assert m.coeff == 4\n    assert m.base == 0\n    # floor mod tests\n    m = analyzer.modular_set(fmod(x * 4 + 3, 2))\n    assert m.coeff == 2\n    assert m.base == 1\n    m = analyzer.modular_set(fmod(x * 4 + 3, 8))\n    assert m.coeff == 4\n    assert m.base == 3\n    # x is non-negative\n    analyzer.update(x, tvm.arith.ConstIntBound(0, 100))\n    m = analyzer.modular_set(tmod(x * 4 + 3, 2))\n    assert m.coeff == 2\n    assert m.base == 1\n\n\ndef test_min_max_select():\n    analyzer = tvm.arith.Analyzer()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    m = analyzer.modular_set(tvm.te.min(x * 3, y * 9))\n    assert m.coeff == 3\n    assert m.base == 0\n\n    m = analyzer.modular_set(tvm.te.max(x * 3 + 1, y * 9 + 4))\n    assert m.coeff == 3\n    assert m.base == 1\n\n    m = analyzer.modular_set(tvm.tir.Select(x > 0, x * 3 + 1, y * 9 + 2))\n    assert m.coeff == 1\n    assert m.base == 0\n\n\ndef test_mix_index():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    analyzer = tvm.arith.Analyzer()\n    tdiv = tvm.tir.truncdiv\n    m = analyzer.modular_set(a * 4 + b * 6 + 7)\n    assert m.coeff == 2\n    assert m.base == 1\n\n    m = analyzer.modular_set((a * 4 + 1) * (b * 8 + 3))\n    assert m.coeff == 4\n    assert m.base == 3\n\n    m = analyzer.modular_set(tdiv(a * 4 + 1, b * 8 + 3))\n    assert m.coeff == 1\n    assert m.base == 0\n\n    m = analyzer.modular_set((a * 4 + 1) * tdiv(b * 8, 4))\n    assert m.coeff == 2\n    assert m.base == 0\n\n    m = analyzer.modular_set((a * 12 + 1) - (b * 3 * 7 + 2))\n    assert m.coeff == 3\n    assert m.base == 2\n\n    m = analyzer.modular_set(a * 12 + tvm.te.min(b * 3 * 7, 2))\n    assert m.coeff == 1\n    assert m.base == 0\n\n\ndef test_constraint_scope():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    analyzer = tvm.arith.Analyzer()\n    tmod = tvm.tir.truncmod\n\n    with analyzer.constraint_scope(tmod(b, 4) == 2):\n        m = analyzer.modular_set(b + 1)\n        assert m.coeff == 4\n        assert m.base == 3\n        with analyzer.constraint_scope(tmod(a, 2) == 1):\n            m = analyzer.modular_set(b + a * 2)\n            assert m.coeff == 4\n            assert m.base == 0\n        m = analyzer.modular_set(b + a * 2)\n        assert m.coeff == 2\n        assert m.base == 0\n\n    m = analyzer.modular_set(b + 1)\n    assert m.coeff == 1\n    assert m.base == 0\n\n\ndef test_intersect():\n    a = te.var(\"a\")\n    analyzer = tvm.arith.Analyzer()\n    tmod = tvm.tir.truncmod\n    with analyzer.constraint_scope(tmod(a, 4) == 1):\n        with analyzer.constraint_scope(tmod(a, 3) == 1):\n            m = analyzer.modular_set(a)\n            assert m.coeff == 12\n            assert m.base == 1\n\n    with analyzer.constraint_scope(tmod(a, 3) == 2):\n        with analyzer.constraint_scope(tmod(a, 5) == 3):\n            with analyzer.constraint_scope(tmod(a, 7) == 2):\n                m = analyzer.modular_set(a)\n                assert m.coeff == 105\n                assert m.base == 23\n\n\ndef test_let():\n    analyzer = tvm.arith.Analyzer()\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    m = analyzer.modular_set(tvm.tir.Let(x, y * 10, x + 1))\n    assert m.coeff == 10\n    assert m.base == 1\n\n\ndef test_bitwise_and():\n    analyzer = tvm.arith.Analyzer()\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n\n    # RHS of bitwise_and is 2^p - 1\n    m = analyzer.modular_set((x * 16 + y * 4) & 31)\n    assert m.coeff == 4\n    assert m.base == 0\n\n    # arbitrary RHS\n    m = analyzer.modular_set((x * 16 + y * 4) & 17)\n    assert m.coeff == 1\n    assert m.base == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_narrow_predicate_expression.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\n\nfrom tvm import tir\nfrom tvm.runtime import convert\n\n\ni = tir.Var(\"i\", \"int32\")\nj = tir.Var(\"j\", \"int32\")\nn = tir.Var(\"n\", \"int32\")\nm = tir.Var(\"m\", \"int32\")\nb = tir.Var(\"b\", \"bool\")\nbuf = tir.decl_buffer(16, \"int32\", \"buf\")\n\ntir_false = tir.IntImm(\"bool\", False)\ntir_true = tir.IntImm(\"bool\", True)\n\nbefore, expected = tvm.testing.parameters(\n    # General arithmatic\n    [tir_true, tir_true],\n    [tir_false, tir_false],\n    [b, b],\n    [i > 5, i > 5],\n    [i > n, i > 7],\n    [i < n, i < 0],\n    [i <= n, i <= 0],\n    [i >= n, i >= 7],\n    [n > i, convert(0) > i],\n    [n < i, convert(7) < i],\n    [n <= i, convert(7) <= i],\n    [n >= i, convert(0) >= i],\n    [i == n, tir.all(i <= 0, convert(7) <= i)],\n    [n == i, tir.all(convert(7) <= i, i <= 0)],\n    [i != n, tir.any(i < 0, convert(7) < i)],\n    [n != i, tir.any(convert(7) < i, i < 0)],\n    [i // 4 > n, i // 4 > 7],\n    [n < i // 4, convert(7) < i // 4],\n    [(i + n) // 4 > 0, tir.Add(i, 0) // 4 > 0],\n    [(i + n) // 4 == 0, tir.all(tir.Add(i, 7) // 4 <= 0, convert(0) <= tir.Add(i, 0) // 4)],\n    [i + n < 10, i + 7 < 10],\n    [i - n < 10, tir.Sub(i, 0) < 10],\n    [tir.Not(i < n), tir.Not(i < 7)],\n    # Use of FloorMod should make the narrowing strategy bail out, as\n    # it is non-monotonic.\n    [i % 8 == n, tir_false],\n    # Ensure that dividing by a free parameter doesn't generate a\n    # divide-by-zero to be triggered later.\n    [i // n == 0, tir_false],\n    ### Buffer handling\n    [buf.vload(0) > 0, tir_false],\n    [buf.vload(0) > i, tir_false],\n    [buf.vload(i) > 0, tir_false],\n    [tir.And(buf.vload(i) > 0, i <= 0), tir.And(tir_false, i <= 0)],\n    [tir.Or(buf.vload(i) > 0, i <= n), tir.Or(tir_false, i <= 0)],\n    [tir.Or(tir.Not(buf.vload(i) > 0), i <= n), tir.Or(tir_false, i <= 0)],\n)\n\n\ndef test_narrow_expression(before, expected):\n    ranges = {n: tvm.ir.Range(0, 8)}\n    after = tvm.arith._ffi_api.NarrowPredicateExpression(before, ranges)\n\n    if expected is None:\n        assert after is None\n    else:\n        tvm.ir.assert_structural_equal(after, expected)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_rewrite_simplify.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\n\n\nclass RewriteChecker:\n    def __init__(self):\n        self.analyzer = tvm.arith.Analyzer()\n\n    def verify(self, data, expected):\n        res = self.analyzer.rewrite_simplify(data)\n        assert tvm.ir.structural_equal(res, expected), \"data={}, res={}, expected={}\".format(\n            data, res, expected\n        )\n\n\ndef test_vector_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    # Add rules\n    ck.verify(tvm.tir.Ramp(x, 1, 4) + tvm.tir.Ramp(y, 2, 4), tvm.tir.Ramp(x + y, 3, 4))\n    ck.verify(tvm.tir.Ramp(x, 1, 2) + y, tvm.tir.Ramp(x + y, 1, 2))\n    ck.verify(y + tvm.tir.Ramp(x, 1, 2), tvm.tir.Ramp(y + x, 1, 2))\n    ck.verify(y.astype(\"int32x2\") + x.astype(\"int32x2\"), (y + x).astype(\"int32x2\"))\n    ck.verify(tvm.tir.Broadcast(0, 4) + y, tvm.tir.Broadcast(y, 4))\n    ck.verify(\n        tvm.tir.Ramp(x, 1, 4).astype(\"float32x4\") + tvm.tir.Broadcast(0.0, 4),\n        tvm.tir.Ramp(x, 1, 4).astype(\"float32x4\"),\n    )\n    # Sub rules\n    ck.verify(tvm.tir.Ramp(x, 4, 4) - tvm.tir.Ramp(y, 2, 4), tvm.tir.Ramp(x - y, 2, 4))\n    ck.verify(tvm.tir.Ramp(x, 1, 2) - y, tvm.tir.Ramp(x - y, 1, 2))\n    ck.verify(y - tvm.tir.Ramp(x, 1, 2), tvm.tir.Ramp(y - x, -1, 2))\n    ck.verify(y.astype(\"int32x2\") - x.astype(\"int32x2\"), (y - x).astype(\"int32x2\"))\n\n    # Mul rules\n    ck.verify(y.astype(\"int32x2\") * x.astype(\"int32x2\"), (y * x).astype(\"int32x2\"))\n    ck.verify(tvm.tir.Ramp(x, 4, 4) * 2, tvm.tir.Ramp(x * 2, 8, 4))\n    ck.verify(2 * tvm.tir.Ramp(x, 4, 4), tvm.tir.Ramp(x * 2, 8, 4))\n    ck.verify(tvm.tir.Broadcast(0, 4) * x, tvm.tir.Broadcast(0, 4))\n    ck.verify(tvm.tir.Broadcast(0.0, 4) * x, tvm.tir.Broadcast(0.0, 4))\n\n    ## DivMod rules\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # truc div\n    ck.verify(tdiv(y.astype(\"int32x2\"), x.astype(\"int32x2\")), tdiv(y, x).astype(\"int32x2\"))\n    ck.verify(tdiv(tvm.tir.Ramp(x, 4, 4), 2), tvm.tir.Ramp(tdiv(x, 2), 2, 4))\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.verify(tdiv(tvm.tir.Ramp(x * 8 + 1, 1, 4), 8), (x).astype(\"int32x4\"))\n    ck.verify(tdiv(tvm.tir.Ramp(x * 8 + 15, 1, 4), 8), tdiv(tvm.tir.Ramp(x * 8 + 15, 1, 4), 8))\n    # truc mod\n    ck.verify(tmod(y.astype(\"int32x2\"), x.astype(\"int32x2\")), tmod(y, x).astype(\"int32x2\"))\n    ck.verify(tmod(tvm.tir.Ramp(x, 4, 4), 2), tvm.tir.Broadcast(tmod(x, 2), 4))\n    ck.verify(tmod(tvm.tir.Ramp(x * 8 + 1, 1, 4), 8), tvm.tir.Ramp(1, 1, 4))\n    ck.verify(tmod(tvm.tir.Ramp(x * 8 + 1, 15, 4), 8), tmod(tvm.tir.Ramp(1, 15, 4), 8))\n\n    # floor div\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-10, 1000), override=True)\n    ck.verify(fld(y.astype(\"int32x2\"), x.astype(\"int32x2\")), fld(y, x).astype(\"int32x2\"))\n    ck.verify(fld(tvm.tir.Ramp(x, 4, 4), 2), tvm.tir.Ramp(fld(x, 2), 2, 4))\n    ck.verify(fld(tvm.tir.Ramp(x * 8 + 1, 1, 4), 8), (x).astype(\"int32x4\"))\n    ck.verify(fld(tvm.tir.Ramp(x * 8 + 15, 1, 4), 8), fld(tvm.tir.Ramp(x * 8 + 15, 1, 4), 8))\n    ck.verify(fld(tvm.tir.Ramp(x, 8, 5), tvm.tir.Broadcast(4, 5)), tvm.tir.Ramp(fld(x, 4), 2, 5))\n    ck.verify(\n        fld(tvm.tir.Ramp(flm(x * 4, 256), 1, 4), tvm.tir.Broadcast(8, 4)),\n        tvm.tir.Broadcast(fld(flm(x * 4, 256), 8), 4),\n    )\n    ck.verify(\n        fld(tvm.tir.Ramp(x, 7, 4), tvm.tir.Broadcast(4, 4)),\n        fld(tvm.tir.Ramp(x, 7, 4), tvm.tir.Broadcast(4, 4)),\n    )\n    ck.verify(fld(tvm.tir.Ramp(x * 8, 1, 4), tvm.tir.Broadcast(4, 4)), tvm.tir.Broadcast(x * 2, 4))\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 8, 3, 4), tvm.tir.Broadcast(4, 4)),\n        fld(tvm.tir.Ramp(x * 8, 3, 4), tvm.tir.Broadcast(4, 4)),\n    )\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 8 + 15, 1, 4), tvm.tir.Broadcast(4, 4)),\n        fld(tvm.tir.Ramp(x * 8 + 15, 1, 4), tvm.tir.Broadcast(4, 4)),\n    )\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 4, 1, 4), tvm.tir.Broadcast(64, 4)), tvm.tir.Broadcast(fld(x, 16), 4)\n    )\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 8, 2, 4), tvm.tir.Broadcast(64, 4)), tvm.tir.Broadcast(fld(x, 8), 4)\n    )\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 4, 1, 5), tvm.tir.Broadcast(64, 5)),\n        fld(tvm.tir.Ramp(x * 4, 1, 5), tvm.tir.Broadcast(64, 5)),\n    )  # Example negative case: x = 15; [60, 61, 62, 63, 64] / 64 = [0, 0, 0, 0, 1]\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 4 + 3, 1, 4), tvm.tir.Broadcast(64, 4)),\n        fld(tvm.tir.Ramp(x * 4 + 3, 1, 4), tvm.tir.Broadcast(64, 4)),\n    )  # Example negative case: x = 15; [63, 64, 65, 66] % 64 = [0, 1, 1, 1]\n    ck.verify(\n        fld(tvm.tir.Ramp(x * 7, 1, 4), tvm.tir.Broadcast(64, 4)),\n        fld(tvm.tir.Ramp(x * 7, 1, 4), tvm.tir.Broadcast(64, 4)),\n    )  # Example negative case: x = 9; [63, 70, 77, 84] % 64 = [0, 1, 1, 1]\n\n    # floor mod\n    ck.verify(flm(y.astype(\"int32x2\"), x.astype(\"int32x2\")), flm(y, x).astype(\"int32x2\"))\n    ck.verify(flm(tvm.tir.Ramp(x, 4, 4), 2), tvm.tir.Broadcast(flm(x, 2), 4))\n    ck.verify(flm(tvm.tir.Ramp(x * 8 + 1, 1, 4), 8), tvm.tir.Ramp(1, 1, 4))\n    ck.verify(flm(tvm.tir.Ramp(x * 8 + 1, 15, 4), 8), flm(tvm.tir.Ramp(1, 15, 4), 8))\n    ck.verify(flm(tvm.tir.Ramp(x, 8, 4), tvm.tir.Broadcast(4, 4)), tvm.tir.Broadcast(flm(x, 4), 4))\n    ck.verify(\n        flm(tvm.tir.Ramp(x, 7, 4), tvm.tir.Broadcast(4, 4)),\n        flm(tvm.tir.Ramp(x, 7, 4), tvm.tir.Broadcast(4, 4)),\n    )\n    ck.verify(flm(tvm.tir.Ramp(x * 8, 1, 4), tvm.tir.Broadcast(4, 4)), tvm.tir.Ramp(0, 1, 4))\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 8, 1, 5), tvm.tir.Broadcast(4, 5)),\n        flm(tvm.tir.Ramp(0, 1, 5), tvm.tir.Broadcast(4, 5)),\n    )\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 8 + 7, 1, 4), tvm.tir.Broadcast(4, 4)),\n        flm(tvm.tir.Ramp(3, 1, 4), tvm.tir.Broadcast(4, 4)),\n    )\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 4, 1, 4), tvm.tir.Broadcast(64, 4)), tvm.tir.Ramp(flm(x * 4, 64), 1, 4)\n    )\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 8, 2, 4), tvm.tir.Broadcast(64, 4)), tvm.tir.Ramp(flm(x * 8, 64), 2, 4)\n    )\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 4, 1, 5), tvm.tir.Broadcast(64, 5)),\n        flm(tvm.tir.Ramp(x * 4, 1, 5), tvm.tir.Broadcast(64, 5)),\n    )  # Example negative case: x = 15; [60, 61, 62, 63, 64] % 64 = [60, 61, 62, 63, 0]\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 4 + 3, 1, 4), tvm.tir.Broadcast(64, 4)),\n        flm(tvm.tir.Ramp(x * 4 + 3, 1, 4), tvm.tir.Broadcast(64, 4)),\n    )  # Example negative case: x = 15; [63, 64, 65, 66] % 64 = [63, 0, 1, 2]\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 2, 1, 8), tvm.tir.Broadcast(20, 8)),\n        flm(tvm.tir.Ramp(x * 2, 1, 8), tvm.tir.Broadcast(20, 8)),\n    )  # Example negative case: x = 9; [18, 19, 20, ..., 25] % 20 = [18, 19, 0, 1, ..., 5]\n    ck.verify(\n        flm(tvm.tir.Ramp(x * 7, 1, 4), tvm.tir.Broadcast(64, 4)),\n        flm(tvm.tir.Ramp(x * 7, 1, 4), tvm.tir.Broadcast(64, 4)),\n    )  # Example negative case: x = 9; [63, 70, 77, 84] % 64 = [63, 6, 13, 20]\n\n    # Min/Max rules\n    vx = te.var(\"vx\", dtype=\"int32x2\")\n    vc = te.var(\"vc\", dtype=\"uint1\")\n    ck.verify(\n        tvm.te.min(y.astype(\"int32x2\"), x.astype(\"int32x2\")), tvm.te.min(y, x).astype(\"int32x2\")\n    )\n    ck.verify(\n        tvm.te.min(tvm.te.min(vx, y.astype(\"int32x2\")), x.astype(\"int32x2\")),\n        tvm.te.min(vx, tvm.te.min(y, x).astype(\"int32x2\")),\n    )\n    ck.verify(\n        tvm.te.max(y.astype(\"int32x2\"), x.astype(\"int32x2\")), tvm.te.max(y, x).astype(\"int32x2\")\n    )\n    ck.verify(\n        tvm.te.max(tvm.te.max(vx, y.astype(\"int32x2\")), x.astype(\"int32x2\")),\n        tvm.te.max(vx, tvm.te.max(y, x).astype(\"int32x2\")),\n    )\n\n    ## Logical rules\n    ck.verify(y.astype(\"int32x2\").equal(x.astype(\"int32x2\")), (y.equal(x)).astype(\"uint1x2\"))\n    ck.verify(\n        tvm.tir.NE(y.astype(\"int32x2\"), (x.astype(\"int32x2\"))), (tvm.tir.NE(y, x)).astype(\"uint1x2\")\n    )\n    ck.verify(y.astype(\"int32x2\") > x.astype(\"int32x2\"), (x < y).astype(\"uint1x2\"))\n    ck.verify(y.astype(\"int32x2\") >= x.astype(\"int32x2\"), (x <= y).astype(\"uint1x2\"))\n    ck.verify(y.astype(\"int32x2\") < x.astype(\"int32x2\"), (y < x).astype(\"uint1x2\"))\n    ck.verify(y.astype(\"int32x2\") <= x.astype(\"int32x2\"), (y <= x).astype(\"uint1x2\"))\n    ck.verify(\n        tvm.tir.And(y.astype(\"int32x2\") <= x.astype(\"int32x2\"), vc.astype(\"uint1x2\")),\n        (tvm.tir.And(y <= x, vc)).astype(\"uint1x2\"),\n    )\n    ck.verify(\n        tvm.tir.Or(y.astype(\"int32x2\") <= x.astype(\"int32x2\"), vc.astype(\"uint1x2\")),\n        (tvm.tir.Or(y <= x, vc)).astype(\"uint1x2\"),\n    )\n\n\ndef test_select_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    # Add rules\n    ck.verify(\n        tvm.tir.Select(x < 0, y, 0) + tvm.tir.Select(x < 0, 1, z), tvm.tir.Select(x < 0, y + 1, z)\n    )\n    ck.verify(\n        tvm.tir.Select(x < 0, y, 1) - tvm.tir.Select(x < 0, 1, z),\n        tvm.tir.Select(x < 0, y + (-1), 1 - z),\n    )\n    ck.verify(tvm.tir.Select(x < 0, y, z) - y, tvm.tir.Select(x < 0, 0, z - y))\n    ck.verify(tvm.tir.Select(x < 0, y, z) - z, tvm.tir.Select(x < 0, y - z, 0))\n    ck.verify(\n        tvm.te.min(tvm.tir.Select(x < 0, y, 0), tvm.tir.Select(x < 0, 1, z)),\n        tvm.tir.Select(x < 0, tvm.te.min(y, 1), tvm.te.min(0, z)),\n    )\n    ck.verify(\n        tvm.te.max(tvm.tir.Select(x < 0, y, 0), tvm.tir.Select(x < 0, 1, z)),\n        tvm.tir.Select(x < 0, tvm.te.max(y, 1), tvm.te.max(0, z)),\n    )\n\n    ck.verify(tvm.tir.Select(x * 3 + 1 != 0, y, z), y)\n    ck.verify(tvm.tir.Select(x * 3 + 1 == 0, y, z), z)\n    ck.verify(tvm.tir.Select(x > 0, y + 1, y + 1), y + 1)\n\n\ndef test_add_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n\n    ck.verify(x + (y - x), y)\n    ck.verify(x - (y + 1) + (y + 1), x)\n    ck.verify((x - 10) + (10 - z), x - z)\n    ck.verify((x - y) + (z - x), z - y)\n\n    ck.verify(tvm.te.min(x, y - z) + z, tvm.te.min(x + z, y))\n    ck.verify(tvm.te.min(x - z, y) + z, tvm.te.min(x, y + z))\n    ck.verify(tvm.te.max(x, y - 10) + 10, tvm.te.max(x + 10, y))\n    ck.verify(tvm.te.max(x - 11, y) + 11, tvm.te.max(x, y + 11))\n\n    ck.verify(tvm.te.max(x, y * 2) + tvm.te.min(x, y * 2), x + y * 2)\n    ck.verify(tvm.te.min(x, y * 2) + tvm.te.max(x, y * 2), x + y * 2)\n\n    ck.verify(tvm.te.max(x, y + 2) + (-2), tvm.te.max(x + (-2), y))\n    ck.verify(tvm.te.min(x, y + 2) + (-2), tvm.te.min(x + (-2), y))\n    ck.verify(tvm.te.min(x + 2, y + 3) + (-2), tvm.te.min(x, y + 1))\n\n    ck.verify(tvm.te.max(0, 1 - x * 4) + x * 4, tvm.te.max(x * 4, 1))\n    ck.verify(tvm.te.max(2 - x * 4, 0) + x * 4, tvm.te.max(x * 4, 2))\n\n    ck.verify(tvm.te.min(0, 1 - x * 4) + x * 4, tvm.te.min(x * 4, 1))\n    ck.verify(tvm.te.min(2 - x * 4, 0) + x * 4, tvm.te.min(x * 4, 2))\n\n    ck.verify(x * y + x * 10, x * (y + 10))\n    ck.verify(y * x + x * 10, x * (y + 10))\n    ck.verify(y * x + 10 * x, x * (y + 10))\n    ck.verify(x * y + 10 * x, x * (y + 10))\n\n    ck.verify((2 * z) + tvm.te.min(x, y - (2 * z)), tvm.te.min(x + (z * 2), y))\n    ck.verify(y * x + x, x * (y + 1))\n    ck.verify(x * y + x, x * (y + 1))\n    ck.verify((x + 10) + 13, x + 23)\n    ck.verify((x + 10) + (13 + z), x + z + 23)\n    ck.verify(x * y + 10 * x, x * (y + 10))\n    ck.verify(y * x + x * 3, x * (y + 3))\n    ck.verify(x + 3 + y, x + y + 3)\n    ck.verify((3 - y) + x, x - y + 3)\n\n    # canonicalization\n    ck.verify(x + 2 + 3 + 4 + x, x * 2 + 9)\n    ck.verify(x + 2 + 3 + 4 + x * 3, x * 4 + 9)\n\n    # DivMod rules\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # truc div\n    ck.verify(y * tmod(x, 8) + 10 * tmod(x, 8), tmod(x, 8) * (y + 10))\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-1, 1000), override=True)\n    ck.verify(tdiv(x, 8) * 8 + tmod(x, 8), x)\n\n    # floor div\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck.verify(y * flm(x, 8) + 10 * flm(x, 8), flm(x, 8) * (y + 10))\n    ck.verify(fld(x, 8) * 8 + flm(x, 8), x)\n    ck.verify(fld(flm(x, 2) + 7, 2) + fld(x, 2), fld(x + 7, 2))\n\n\ndef test_sub_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    a, b = tvm.tir.Any(), tvm.tir.Any()\n\n    ck.verify(x + y - y, x)\n    ck.verify(x + y - x, y)\n    ck.verify(x - (y + x), 0 - y)\n    ck.verify(x - (x + y), 0 - y)\n\n    ck.verify(tvm.te.min(x, y) - x, tvm.te.min(0, y - x))\n    ck.verify(tvm.te.min(x, y) - y, tvm.te.min(x - y, 0))\n    ck.verify(tvm.te.max(x, y) - x, tvm.te.max(0, y - x))\n    ck.verify(tvm.te.max(x, y) - y, tvm.te.max(x - y, 0))\n\n    ck.verify(x - tvm.te.min(x, y), tvm.te.max(0, x - y))\n    ck.verify(y - tvm.te.min(x, y), tvm.te.max(y - x, 0))\n    ck.verify(x - tvm.te.max(x, y), tvm.te.min(0, x - y))\n    ck.verify(y - tvm.te.max(x, y), tvm.te.min(y - x, 0))\n\n    # mul co-efficient foldng\n    ck.verify(x - x, 0)\n    ck.verify(a - a, 0)\n    ck.verify(a - b, a - b)\n    ck.verify(x * y - x, x * (y + (-1)))\n    ck.verify(x * y - 10 * x, x * (y + (-10)))\n    ck.verify(y * x - x * z, x * (y - z))\n    ck.verify(y * x - z * x, x * (y - z))\n\n    ck.verify(x + 10 - 20, x + (-10))\n\n    # 4-operands pattern\n    ck.verify((x + y) - (x + z), y - z)\n    ck.verify((y + x) - (x + z), y - z)\n    ck.verify((x + y) - (z + x), y - z)\n    ck.verify((y + x) - (z + x), y - z)\n\n    ck.verify(tvm.te.min(x + y, z) - x, tvm.te.min(y, z - x))\n    ck.verify(tvm.te.min(y + x, z) - x, tvm.te.min(y, z - x))\n    ck.verify(tvm.te.min(z, x + y) - x, tvm.te.min(z - x, y))\n    ck.verify(tvm.te.min(z, y + x) - x, tvm.te.min(z - x, y))\n\n    ck.verify(tvm.te.max(x + y, z) - x, tvm.te.max(y, z - x))\n    ck.verify(tvm.te.max(y + x, z) - x, tvm.te.max(y, z - x))\n    ck.verify(tvm.te.max(z, x + y) - x, tvm.te.max(z - x, y))\n    ck.verify(tvm.te.max(z, y + x) - x, tvm.te.max(z - x, y))\n\n    ck.verify(x - tvm.te.min(x + y, z), tvm.te.max(0 - y, x - z))\n    ck.verify(x - tvm.te.min(y + x, z), tvm.te.max(0 - y, x - z))\n    ck.verify(x - tvm.te.min(z, x + y), tvm.te.max(x - z, 0 - y))\n    ck.verify(x - tvm.te.min(z, y + x), tvm.te.max(x - z, 0 - y))\n\n    ck.verify(tvm.te.min(x, y) - tvm.te.min(y, x), 0)\n    ck.verify(tvm.te.max(x, y) - tvm.te.max(y, x), 0)\n    ck.verify(tvm.te.min(x, y) - tvm.te.min(x + 10, y + 10), -10)\n    ck.verify(tvm.te.min(x + 10, y + 1) - tvm.te.min(x, y - 9), 10)\n\n    # DivMod patterns\n    # truc div\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.verify(x - tdiv(x, 3) * 3, tmod(x, 3))\n\n    ck.verify(tdiv(x + 5, 3) - tdiv(x, 3), tdiv(tmod(x, 3) + 5, 3))\n    ck.verify(tdiv(x + 5, 3) - tdiv(x + 1, 3), tdiv(tmod(x + 1, 3) + 4, 3))\n\n    ck.verify(y - tdiv(y, (-5)) * (-5), tmod(y, 5))\n    ck.verify(tdiv(y, 3) * 3 - y, 0 - tmod(y, 3))\n    ck.verify(y - tdiv(y - 6, 5) * 5, tmod(y + (-6), 5) + 6)\n    ck.verify(tdiv(y - 6, 5) * 5 - y, (-6) - tmod(y + (-6), 5))\n    ck.verify(y - tdiv(y + z, 5) * 5, tmod(y + z, 5) - z)\n    ck.verify(tdiv(y + z, 5) * 5 - y, z - tmod(y + z, 5))\n    ck.verify(y - tdiv(y - z, 5) * 5, tmod(y - z, 5) + z)\n    ck.verify(tdiv(y - z, 5) * 5 - y, 0 - tmod(y - z, 5) - z)\n\n    ck.verify(y * 3 - tdiv(y, 2) * 6, tmod(y, 2) * 3)\n    ck.verify(tdiv(y, 3) * 6 - y * 2, tmod(y, 3) * (-2))\n    ck.verify(y * 5 - tdiv(y + z, 2) * 10, (tmod(y + z, 2) - z) * 5)\n    ck.verify(y * 5 - tdiv(y - z, 2) * 10, (tmod(y - z, 2) + z) * 5)\n    ck.verify(tdiv(y + z, 3) * 6 - y * 2, (z - tmod(y + z, 3)) * 2)\n    ck.verify(tdiv(y - z, 3) * 6 - y * 2, (0 - tmod(y - z, 3) - z) * 2)\n    ck.verify(5 * y - tdiv(y + z, 2) * 10, (tmod(y + z, 2) - z) * 5)\n    ck.verify(5 * y - 10 * tdiv(y - z, 2), (tmod(y - z, 2) + z) * 5)\n    ck.verify(6 * tdiv(y + z, 3) - y * 2, (z - tmod(y + z, 3)) * 2)\n    ck.verify(tdiv(y - z, 3) * 6 - 2 * y, (0 - tmod(y - z, 3) - z) * 2)\n\n    # floor div\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-1000, 1000), override=True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(-1000, 1000), override=True)\n    ck.verify(x - fld(x, 3) * 3, flm(x, 3))\n    ck.verify(fld(x + 5, 3) - fld(x, 3), fld(flm(x, 3) + 5, 3))\n    ck.verify(fld(x + 5, 3) - fld(x + 2, 3), fld(flm(x + 2, 3), 3) + 1)\n\n    ck.verify(fld(y, 3) * 3 - y, 0 - flm(y, 3))\n    ck.verify(y - fld(y - 6, 5) * 5, flm(y + (-6), 5) + 6)\n    ck.verify(fld(y - 6, 5) * 5 - y, (-6) - flm(y + (-6), 5))\n    ck.verify(y - fld(y + z, 5) * 5, flm(y + z, 5) - z)\n    ck.verify(fld(y + z, 5) * 5 - y, z - flm(y + z, 5))\n    ck.verify(y - fld(y - z, 5) * 5, flm(y - z, 5) + z)\n    ck.verify(fld(y - z, 5) * 5 - y, 0 - flm(y - z, 5) - z)\n    ck.verify(y * 3 - fld(y, 2) * 6, flm(y, 2) * 3)\n    ck.verify(fld(y, 3) * 6 - y * 2, flm(y, 3) * (-2))\n    ck.verify(y * 5 - fld(y + z, 2) * 10, (flm(y + z, 2) - z) * 5)\n    ck.verify(y * 5 - fld(y - z, 2) * 10, (flm(y - z, 2) + z) * 5)\n    ck.verify(fld(y + z, 3) * 6 - y * 2, (z - flm(y + z, 3)) * 2)\n    ck.verify(fld(y - z, 3) * 6 - y * 2, (0 - flm(y - z, 3) - z) * 2)\n    ck.verify(5 * y - fld(y + z, 2) * 10, (flm(y + z, 2) - z) * 5)\n    ck.verify(5 * y - 10 * fld(y - z, 2), (flm(y - z, 2) + z) * 5)\n    ck.verify(6 * fld(y + z, 3) - y * 2, (z - flm(y + z, 3)) * 2)\n    ck.verify(fld(y - z, 3) * 6 - 2 * y, (0 - flm(y - z, 3) - z) * 2)\n\n\ndef test_mul_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    ck.verify((x + 2) * 3, x * 3 + 6)\n    ck.verify((x * 2) * 3, x * 6)\n    ck.verify(tvm.te.min(x, y) * tvm.te.max(x, y), x * y)\n    ck.verify(tvm.te.max(x, y) * tvm.te.min(x, y), x * y)\n    ck.verify((x - y) * (-2), (y - x) * 2)\n\n\ndef test_div_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n\n    ck.verify(tdiv(x, x), 1)\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.analyzer.update(z, tvm.arith.ConstIntBound(0, 1000), override=True)\n\n    ck.verify(tdiv(tdiv(x, 2), 3), tdiv(x, 6))\n    ck.verify(tdiv(tdiv(x, 2) + 1, 3), tdiv(x + 2, 6))\n    ck.verify(tdiv(x * 2, 4), tdiv(x, 2))\n    ck.verify(tdiv(x * 4, 2), x * 2)\n\n    ck.verify(tdiv(x * 4 + y, 2), x * 2 + tdiv(y, 2))\n    ck.verify(tdiv(tvm.te.min(x * 6, y), 2), tvm.te.min(x * 3, tdiv(y, 2)))\n    ck.verify(tdiv(tvm.te.max(x * 6, y), 2), tvm.te.max(x * 3, tdiv(y, 2)))\n\n    ck.verify(tdiv(y + x * 4, 2), tdiv(y, 2) + x * 2)\n    ck.verify(tdiv(tvm.te.min(y, x * 6), 2), tvm.te.min(tdiv(y, 2), x * 3))\n    ck.verify(tdiv(tvm.te.max(y, x * 6), 2), tvm.te.max(tdiv(y, 2), x * 3))\n\n    # 3-operands\n    ck.verify(tdiv(x * 6 + y + z, 2), x * 3 + tdiv(y + z, 2))\n    ck.verify(tdiv(x * 6 - y + (y + 3), 2), x * 3 + 1)\n    ck.verify(tdiv(x * 6 + (y + 3) - y, 2), x * 3 + 1)\n    ck.verify(tdiv(y + x * 6 + z, 2), x * 3 + tdiv(y + z, 2))\n    ck.verify(tdiv(x + 4, 2), tdiv(x, 2) + 2)\n\n    ck.verify(tdiv(x + y, x), tdiv(y, x) + 1)\n    ck.verify(tdiv(y + x, x), tdiv(y, x) + 1)\n    ck.verify(tdiv((x + y) + z, x), tdiv(y + z, x) + 1)\n    ck.verify(tdiv((y + x) + z, x), tdiv(y + z, x) + 1)\n    ck.verify(tdiv(y + (x + z), x), tdiv(y + z, x) + 1)\n    ck.verify(tdiv(y + (z + x), x), tdiv(y + z, x) + 1)\n\n    ck.verify(tdiv(x * y, y), x)\n    ck.verify(tdiv(y * x, y), x)\n\n    ck.verify(tdiv(x * z + y, z), x + tdiv(y, z))\n    ck.verify(tdiv(z * x + y, z), x + tdiv(y, z))\n    ck.verify(tdiv(y + x * z, z), tdiv(y, z) + x)\n    ck.verify(tdiv(y + z * x, z), tdiv(y, z) + x)\n\n\ndef test_floordiv_index_simplify():\n    # short name for floordiv\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n\n    ck.verify(fld(fld(x, 2), 3), fld(x, 6))\n    ck.verify(fld(fld(x, 2) + 1, 3), fld(x + 2, 6))\n    ck.verify(fld(x - flm(x, 21), 21), fld(x, 21))\n\n    ck.verify(fld(x * 2, 4), fld(x, 2))\n    ck.verify(fld(x * 4, 2), x * 2)\n    ck.verify(fld(x * 8 + 7, 16), fld(x, 2))\n    ck.verify(fld(x * 8 + 39, 16), fld(x, 2) + 2)\n    ck.verify(fld(x * 8 - 1, 16), fld(x * 8 + -1, 16))\n    ck.verify(fld(x * 8 - 9, 16), fld(x, 2) + -1)\n\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1), override=True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 7), override=True)\n    ck.verify(fld(x * 360 + y, 16), x * 22)\n    ck.verify(fld(x * 360 + y, 25), x * 14)\n    ck.verify(fld(x * 360 - 8, 25), fld(x * 360 + -8, 25))\n\n    ck.verify(fld(x * 4 + y, 2), x * 2 + fld(y, 2))\n    ck.verify(fld(tvm.te.min(x * 6, y), 2), tvm.te.min(x * 3, fld(y, 2)))\n    ck.verify(fld(tvm.te.max(x * 6, y), 2), tvm.te.max(x * 3, fld(y, 2)))\n\n    ck.verify(fld(y + x * 4, 2), x * 2 + fld(y, 2))\n    ck.verify(fld(tvm.te.min(y, x * 6), 2), tvm.te.min(fld(y, 2), x * 3))\n    ck.verify(fld(tvm.te.max(y, x * 6), 2), tvm.te.max(fld(y, 2), x * 3))\n\n    # 3-operands\n    ck.verify(fld(x * 6 + y + z, 2), x * 3 + fld(y + z, 2))\n    ck.verify(fld(x * 6 - y + (y + 3), 2), x * 3 + 1)\n    ck.verify(fld(x * 6 + (y + 3) - y, 2), x * 3 + 1)\n    ck.verify(fld(y + x * 6 + z, 2), x * 3 + fld(y + z, 2))\n    ck.verify(fld(x + 4, 2), fld(x, 2) + 2)\n\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.verify(fld(x + y, x), fld(y, x) + 1)\n    ck.verify(fld(y + x, x), fld(y, x) + 1)\n    ck.verify(fld((x + y) + z, x), fld(y + z, x) + 1)\n    ck.verify(fld((y + x) + z, x), fld(y + z, x) + 1)\n    ck.verify(fld(y + (x + z), x), fld(y + z, x) + 1)\n    ck.verify(fld(y + (z + x), x), fld(y + z, x) + 1)\n\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.analyzer.update(z, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.verify(fld(x * y, y), x)\n    ck.verify(fld(y * x, y), x)\n    ck.verify(fld(x * z + y, z), x + fld(y, z))\n    ck.verify(fld(z * x + y, z), x + fld(y, z))\n    ck.verify(fld(y + x * z, z), fld(y, z) + x)\n    ck.verify(fld(y + z * x, z), fld(y, z) + x)\n\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 31), override=True)\n    ck.analyzer.update(z, tvm.arith.ConstIntBound(0, 3), override=True)\n    ck.verify(fld(x * 32 + y, 64), fld(x, 2))\n    ck.verify(fld(x * 128 + y * 4 + z, 512), fld(x, 4))\n\n\ndef test_mod_index_simplify():\n    ck = RewriteChecker()\n    x, y, nx, ny, z = te.var(\"x\"), te.var(\"y\"), te.var(\"nx\"), te.var(\"ny\"), te.var(\"z\")\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 1000), override=True)\n    ck.analyzer.update(nx, tvm.arith.ConstIntBound(-1000, 0), override=True)\n    ck.analyzer.update(ny, tvm.arith.ConstIntBound(-1000, 0), override=True)\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n\n    ck.verify(tmod(x * 10, 2), 0)\n    ck.verify(tmod(x * 10 + y, 2), tmod(y, 2))\n    ck.verify(tmod(x + 10, 2), tmod(x, 2))\n    ck.verify(tmod(x + y * 10, 2), tmod(x, 2))\n    ck.verify(tmod(x * 10 + 1 + y * 2 + 2, 2), 1)\n    ck.verify(tmod(x * 10, -2), 0)\n    ck.verify(tmod(x * 10 + y, -2), tmod(y, 2))\n    ck.verify(tmod(x + 10, -2), tmod(x, 2))\n    ck.verify(tmod(x + y * 10, -2), tmod(x, 2))\n    ck.verify(tmod(x * 10 + 1 + y * 2 + 2, -2), 1)\n\n    ck.verify(tmod(x * (-10), 2), 0)\n    ck.verify(tmod(x * (-10) + y, 2), tmod(x * (-10) + y, 2))\n    ck.verify(tmod(x + (-10), 2), tmod(x + (-10), 2))\n    ck.verify(tmod(x + y * (-10), 2), tmod(x + y * (-10), 2))\n    ck.verify(tmod(x * (-10), -2), 0)\n\n    ck.verify(tmod(nx * 10, 2), 0)\n    ck.verify(tmod(nx * (-10) + y, 2), tmod(y, 2))\n    ck.verify(tmod(x + ny * (-10), 2), tmod(x, 2))\n    ck.verify(tmod(nx * (-10) + 1 + ny * (-2) + 2, 2), 1)\n    ck.verify(tmod(nx * 10, -2), 0)\n    ck.verify(tmod(nx * (-10) + y, -2), tmod(y, 2))\n    ck.verify(tmod(x + ny * (-10), -2), tmod(x, 2))\n\n\ndef test_floormod_index_simplify():\n    # short name for floordiv\n    flm = tvm.te.floormod\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    ck = RewriteChecker()\n    x, y, nx, ny, z = te.var(\"x\"), te.var(\"y\"), te.var(\"nx\"), te.var(\"ny\"), te.var(\"z\")\n\n    ck.verify(flm(x * 10, 2), 0)\n    ck.verify(flm(x * 9600, 6400), flm(x * 3200, 6400))\n    ck.verify(flm(x * 10 + y, 2), flm(y, 2))\n    ck.verify(flm(x * 360 + y, 16), flm(x * 8 + y, 16))\n    ck.verify(flm(x + 10, 2), flm(x, 2))\n    ck.verify(flm(x + y * 10, 2), flm(x, 2))\n    ck.verify(flm(x + y * 360, 16), flm(x + y * 8, 16))\n    ck.verify(flm(x * 10 + 1 + y * 2 + 2, 2), 1)\n    ck.verify(flm(x * (-10), 2), 0)\n    ck.verify(flm(x * (-10) + y, 2), flm(y, 2))\n    ck.verify(flm(x + (-10), 2), flm(x, 2))\n    ck.verify(flm(x + y * (-10), 2), flm(x, 2))\n\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(0, 31), override=True)\n    ck.verify(flm(x * 32 + y, 64), flm(x, 2) * 32 + y)\n    ck.verify(flm(x * 32 - y, 64), flm(x * 32 - y, 64))\n\n\ndef test_min_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    fld = tvm.te.floordiv\n    flm = tvm.te.floormod\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # const int bound\n    ck.verify(tvm.te.min(tmod(x, 2), tmod(y, 2) + 10), tmod(x, 2))\n    ck.verify(tvm.te.min(flm(x, 2), flm(y, 2) + 10), flm(x, 2))\n\n    ck.verify(tvm.te.min(x + 1, x + 10), x + 1)\n    ck.verify(tvm.te.min(x + 111, x + 10), x + 10)\n    ck.verify(tvm.te.min(x + 1, x), x)\n    ck.verify(tvm.te.min(x, x + 2), x)\n    ck.verify(tvm.te.min(1 - x, 2 - x), 1 - x)\n    ck.verify(tvm.te.min(3 - x, 2 - x), 2 - x)\n\n    ck.verify(tvm.te.min(tvm.te.max(x, y), tvm.te.min(x, y)), tvm.te.min(x, y))\n    ck.verify(tvm.te.min(tvm.te.max(x, y), tvm.te.min(y, x)), tvm.te.min(x, y))\n\n    ck.verify(tvm.te.min(tvm.te.max(x, y), x), x)\n    ck.verify(tvm.te.min(tvm.te.max(y, x), x), x)\n    ck.verify(tvm.te.min(tvm.te.min(x, y), x), tvm.te.min(x, y))\n    ck.verify(tvm.te.min(tvm.te.min(x, y), y), tvm.te.min(x, y))\n\n    ck.verify(tvm.te.min(x, tvm.te.max(x, y)), x)\n    ck.verify(tvm.te.min(x, tvm.te.max(y, x)), x)\n    ck.verify(tvm.te.min(x, tvm.te.min(x, y)), tvm.te.min(x, y))\n    ck.verify(tvm.te.min(y, tvm.te.min(x, y)), tvm.te.min(x, y))\n\n    ck.verify(tvm.te.min(tvm.te.min(tvm.te.min(x, y), z), y), tvm.te.min(tvm.te.min(x, y), z))\n    ck.verify(\n        tvm.te.min(tvm.te.min(tvm.te.min(tvm.te.min(x, y), z), x * 2), y),\n        tvm.te.min(tvm.te.min(tvm.te.min(x, y), z), x * 2),\n    )\n    ck.verify(\n        tvm.te.min(tvm.te.min(tvm.te.min(tvm.te.min(tvm.te.min(x, y), z), x * 2), z * 2), y),\n        tvm.te.min(tvm.te.min(tvm.te.min(tvm.te.min(x, y), z), x * 2), z * 2),\n    )\n\n    ck.verify(tvm.te.min(tvm.te.max(x, y), tvm.te.max(x, z)), tvm.te.max(tvm.te.min(y, z), x))\n    ck.verify(tvm.te.min(tvm.te.max(x, y), tvm.te.max(z, x)), tvm.te.max(tvm.te.min(y, z), x))\n    ck.verify(tvm.te.min(tvm.te.max(y, x), tvm.te.max(x, z)), tvm.te.max(tvm.te.min(y, z), x))\n    ck.verify(tvm.te.min(tvm.te.max(y, x), tvm.te.max(z, x)), tvm.te.max(tvm.te.min(y, z), x))\n\n    ck.verify(tvm.te.min(y + x, z + x), tvm.te.min(y, z) + x)\n    ck.verify(tvm.te.min(y + x, x + z), tvm.te.min(y, z) + x)\n    ck.verify(tvm.te.min(x + y, z + x), tvm.te.min(y, z) + x)\n    ck.verify(tvm.te.min(x + y, x + z), tvm.te.min(y, z) + x)\n\n    ck.verify(tvm.te.min(x - y, x - z), x - tvm.te.max(y, z))\n    ck.verify(tvm.te.min(y - x, z - x), tvm.te.min(y, z) - x)\n\n    ck.verify(tvm.te.min(tvm.te.min(x, 1), 10), tvm.te.min(x, 1))\n    ck.verify(tvm.te.min(tvm.te.min(x, 11), 10), tvm.te.min(x, 10))\n\n    ck.verify(tvm.te.min(x * 3, 9), tvm.te.min(x, 3) * 3)\n    ck.verify(tvm.te.min(x * 2, 0), tvm.te.min(x, 0) * 2)\n    ck.verify(tvm.te.min(0 - x * 2, 0), tvm.te.max(x, 0) * -2)\n    ck.verify(tvm.te.min(3 - x, 2), 3 - tvm.te.max(x, 1))\n    ck.verify(tvm.te.min(x * (-2), -4), tvm.te.max(x, 2) * -2)\n    ck.verify(tvm.te.min(x * (-2), 4), tvm.te.max(x, -2) * -2)\n    ck.verify(tvm.te.min(x * (0), 4), 0)\n    ck.verify(tvm.te.min(x * (0), -4), -4)\n\n    # DivMod rules\n    # truc div\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 1000))\n    ck.verify(tvm.te.min(tdiv(x + 3, 4) * 4, x), x)\n    ck.verify(tvm.te.min(tdiv(x + 3, 4) * 4, tvm.te.max(x, 4)), tvm.te.max(x, 4))\n    ck.verify(tvm.te.min(x, tdiv(x + 3, 4) * 4), x)\n    ck.verify(tvm.te.min(tvm.te.max(x, 4), tdiv(x + 3, 4) * 4), tvm.te.max(x, 4))\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-1000, 1000), True)\n    ck.verify(tvm.te.min(tdiv(x, 10), tdiv(y, 10)), tdiv(tvm.te.min(x, y), 10))\n    ck.verify(tvm.te.min(tdiv(x, (-10)), tdiv(y, (-10))), tdiv(tvm.te.max(x, y), (-10)))\n\n    # floor div\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(-1000, 1000), True)\n    ck.verify(tvm.te.min(fld(x + 3, 4) * 4, x), x)\n    ck.verify(tvm.te.min(fld(x + 3, 4) * 4, tvm.te.max(x, 4)), tvm.te.max(x, 4))\n    ck.verify(tvm.te.min(x, fld(x + 3, 4) * 4), x)\n    ck.verify(tvm.te.min(x, fld(x, 4) * 4), fld(x, 4) * 4)\n    ck.verify(tvm.te.min(tvm.te.max(x, 4), fld(x + 3, 4) * 4), tvm.te.max(x, 4))\n    ck.verify(tvm.te.min(fld(x, 10), fld(y, 10)), fld(tvm.te.min(x, y), 10))\n    ck.verify(tvm.te.min(fld(x, (-10)), fld(y, (-10))), fld(tvm.te.max(x, y), (-10)))\n\n\ndef test_max_index_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    flm = tvm.te.floormod\n    fld = tvm.te.floordiv\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # const int bound\n    ck.verify(tvm.te.max(tmod(x, 2), tmod(y, 2) + 10), tmod(y, 2) + 10)\n    ck.verify(tvm.te.max(flm(x, 2), flm(y, 2) + 10), flm(y, 2) + 10)\n\n    ck.verify(tvm.te.max(x + 1, x + 10), x + 10)\n    ck.verify(tvm.te.max(x + 111, x + 10), x + 111)\n    ck.verify(tvm.te.max(x + 1, x), x + 1)\n    ck.verify(tvm.te.max(x, x + 2), x + 2)\n    ck.verify(tvm.te.max(1 - x, 2 - x), 2 - x)\n    ck.verify(tvm.te.max(3 - x, 2 - x), 3 - x)\n\n    ck.verify(tvm.te.max(tvm.te.min(x, y), tvm.te.max(x, y)), tvm.te.max(x, y))\n    ck.verify(tvm.te.max(tvm.te.min(x, y), tvm.te.max(y, x)), tvm.te.max(x, y))\n\n    ck.verify(tvm.te.max(tvm.te.min(x, y), x), x)\n    ck.verify(tvm.te.max(tvm.te.min(y, x), x), x)\n    ck.verify(tvm.te.max(tvm.te.max(x, y), x), tvm.te.max(x, y))\n    ck.verify(tvm.te.max(tvm.te.max(x, y), y), tvm.te.max(x, y))\n\n    ck.verify(tvm.te.max(x, tvm.te.min(x, y)), x)\n    ck.verify(tvm.te.max(x, tvm.te.min(y, x)), x)\n    ck.verify(tvm.te.max(x, tvm.te.max(x, y)), tvm.te.max(x, y))\n    ck.verify(tvm.te.max(y, tvm.te.max(x, y)), tvm.te.max(x, y))\n\n    ck.verify(tvm.te.max(tvm.te.max(tvm.te.max(x, y), z), y), tvm.te.max(tvm.te.max(x, y), z))\n    ck.verify(\n        tvm.te.max(tvm.te.max(tvm.te.max(tvm.te.max(x, y), z), x * 2), y),\n        tvm.te.max(tvm.te.max(tvm.te.max(x, y), z), x * 2),\n    )\n    ck.verify(\n        tvm.te.max(tvm.te.max(tvm.te.max(tvm.te.max(tvm.te.max(x, y), z), x * 2), z * 2), y),\n        tvm.te.max(tvm.te.max(tvm.te.max(tvm.te.max(x, y), z), x * 2), z * 2),\n    )\n\n    ck.verify(tvm.te.max(tvm.te.min(x, y), tvm.te.min(x, z)), tvm.te.min(tvm.te.max(y, z), x))\n    ck.verify(tvm.te.max(tvm.te.min(x, y), tvm.te.min(z, x)), tvm.te.min(tvm.te.max(y, z), x))\n    ck.verify(tvm.te.max(tvm.te.min(y, x), tvm.te.min(x, z)), tvm.te.min(tvm.te.max(y, z), x))\n    ck.verify(tvm.te.max(tvm.te.min(y, x), tvm.te.min(z, x)), tvm.te.min(tvm.te.max(y, z), x))\n\n    ck.verify(tvm.te.max(y + x, z + x), tvm.te.max(y, z) + x)\n    ck.verify(tvm.te.max(y + x, x + z), tvm.te.max(y, z) + x)\n    ck.verify(tvm.te.max(x + y, z + x), tvm.te.max(y, z) + x)\n    ck.verify(tvm.te.max(x + y, x + z), tvm.te.max(y, z) + x)\n\n    ck.verify(tvm.te.max(x - y, x - z), x - tvm.te.min(y, z))\n    ck.verify(tvm.te.max(y - x, z - x), tvm.te.max(y, z) - x)\n\n    ck.verify(tvm.te.max(tvm.te.max(x, 1), 10), tvm.te.max(x, 10))\n    ck.verify(tvm.te.max(tvm.te.max(x, 11), 10), tvm.te.max(x, 11))\n\n    ck.verify(tvm.te.max(x * 3, 9), tvm.te.max(x, 3) * 3)\n    ck.verify(tvm.te.max(3 - x, 1), 3 - tvm.te.min(x, 2))\n    ck.verify(tvm.te.max(x * 2, 0), tvm.te.max(x, 0) * 2)\n    ck.verify(tvm.te.max(0 - x * 2, 0), tvm.te.min(x, 0) * -2)\n    ck.verify(tvm.te.max(x * (-2), -4), tvm.te.min(x, 2) * -2)\n    ck.verify(tvm.te.max(x * (-2), 4), tvm.te.min(x, -2) * -2)\n    ck.verify(tvm.te.max(x * (0), 4), 4)\n    ck.verify(tvm.te.max(x * (0), -4), 0)\n\n    # DivMod rules\n    # truc div\n    ck.verify(tvm.te.max(tdiv(x, 10), tdiv(y, 10)), tdiv(tvm.te.max(x, y), 10))\n    ck.verify(tvm.te.max(tdiv(x, (-10)), tdiv(y, (-10))), tdiv(tvm.te.min(x, y), (-10)))\n    ck.verify(tvm.te.max(tdiv(x + 3, 4) * 4, x), tdiv(x + 3, 4) * 4)\n\n    # floordiv\n    ck.verify(tvm.te.max(fld(x, 10), fld(y, 10)), fld(tvm.te.max(x, y), 10))\n    ck.verify(tvm.te.max(fld(x, (-10)), fld(y, (-10))), fld(tvm.te.min(x, y), (-10)))\n    ck.verify(tvm.te.max(fld(x + 3, 4) * 4, x), fld(x + 3, 4) * 4)\n    ck.verify(tvm.te.max(fld(x, 4) * 4, x), x)\n    ck.verify(tvm.te.max(x, fld(x, 4) * 4), x)\n\n\ndef test_cmp_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    flm = tvm.te.floormod\n    fld = tvm.te.floordiv\n    tdiv = tvm.tir.truncdiv\n    tmod = tvm.tir.truncmod\n    # const int bound\n    ck.verify((tmod(x, 2) + 10).equal(0), tvm.tir.const(0, \"bool\"))\n    ck.verify(tvm.tir.NE(tmod(x, 2) + 10, 0), tvm.tir.const(1, \"bool\"))\n    ck.verify(tmod(x, 2) + 10 > 1, tvm.tir.const(1, \"bool\"))\n    ck.verify(tmod(x, 2) + 10 <= 1, tvm.tir.const(0, \"bool\"))\n    ck.verify(flm(x, 2) + 2 > 1, tvm.tir.const(1, \"bool\"))\n    ck.verify(flm(x, 2) + 10 <= 1, tvm.tir.const(0, \"bool\"))\n\n    ck.verify(x * 3 + 10 == 0, tvm.tir.const(0, \"bool\"))\n    ck.verify(x * 3 + 10 != 0, tvm.tir.const(1, \"bool\"))\n\n    # canonicalization\n    ck.verify((x - 10).equal(0), x.equal(10))\n    ck.verify((10 - x).equal(0), x.equal(10))\n    ck.verify((x * y).equal(0), tvm.tir.Or(x.equal(0), y.equal(0)))\n\n    # cmp bound\n    ck.verify(x + y < x + z, y < z)\n    ck.verify(x + y < z + x, y < z)\n    ck.verify(y + x < x + z, y < z)\n    ck.verify(y + x < z + x, y < z)\n    ck.verify(y - x < z - x, y < z)\n    ck.verify(x - y < x - z, z < y)\n\n    ck.verify(x < z + x, tvm.tir.LT(0, z))\n    ck.verify(x < x + z, tvm.tir.LT(0, z))\n\n    ck.verify(100 < x + 1, tvm.tir.LT(99, x))\n    ck.verify(1 < 100 - x, tvm.tir.LT(x, 99))\n    ck.verify(x * 3 < y * 3, x < y)\n    ck.verify(x * (-3) < y * (-3), y < x)\n    ck.verify(x * 3 >= y * 3, y <= x)\n\n    ck.verify(x * 4 >= 2, tvm.tir.LE(1, x))\n    ck.verify(x * 2 >= 50, tvm.tir.LE(25, x))\n    ck.verify(x * 4 <= 2, x <= 0)\n    ck.verify((0 - x * 3) <= 0, tvm.tir.LE(0, x))\n    ck.verify((0 - x * 3) >= 0, tvm.tir.LE(x, 0))\n    ck.verify(2 * x <= 0, x <= 0)\n\n    ck.verify(x * 2 >= 3, tvm.tir.LE(2, x))\n    ck.verify(x * 2 >= 2, tvm.tir.LE(1, x))\n    ck.verify(x * 2 >= 1, tvm.tir.LE(1, x))\n    ck.verify(x * 2 >= 0, tvm.tir.LE(0, x))\n    ck.verify(x * 2 >= -1, tvm.tir.LE(0, x))\n    ck.verify(x * 2 >= -2, tvm.tir.LE(-1, x))\n    ck.verify(x * 2 >= -3, tvm.tir.LE(-1, x))\n\n    ck.verify(x * 2 <= 3, tvm.tir.LE(x, 1))\n    ck.verify(x * 2 <= 2, tvm.tir.LE(x, 1))\n    ck.verify(x * 2 <= 1, tvm.tir.LE(x, 0))\n    ck.verify(x * 2 <= 0, tvm.tir.LE(x, 0))\n    ck.verify(x * 2 <= -1, tvm.tir.LE(x, -1))\n    ck.verify(x * 2 <= -2, tvm.tir.LE(x, -1))\n    ck.verify(x * 2 <= -3, tvm.tir.LE(x, -2))\n\n    ck.verify(x * (-2) >= 3, tvm.tir.LE(x, -2))\n    ck.verify(x * (-2) >= 2, tvm.tir.LE(x, -1))\n    ck.verify(x * (-2) >= 1, tvm.tir.LE(x, -1))\n    ck.verify(x * (-2) >= 0, tvm.tir.LE(x, 0))\n    ck.verify(x * (-2) >= -1, tvm.tir.LE(x, 0))\n    ck.verify(x * (-2) >= -2, tvm.tir.LE(x, 1))\n    ck.verify(x * (-2) >= -3, tvm.tir.LE(x, 1))\n\n    ck.verify(x * (-2) <= 3, tvm.tir.LE(-1, x))\n    ck.verify(x * (-2) <= 2, tvm.tir.LE(-1, x))\n    ck.verify(x * (-2) <= 1, tvm.tir.LE(0, x))\n    ck.verify(x * (-2) <= 0, tvm.tir.LE(0, x))\n    ck.verify(x * (-2) <= -1, tvm.tir.LE(1, x))\n    ck.verify(x * (-2) <= -2, tvm.tir.LE(1, x))\n    ck.verify(x * (-2) <= -3, tvm.tir.LE(2, x))\n\n    # DivMod rules\n    # truc div\n    ck.verify(tdiv(x, 2) < 3, x < 6)\n    ck.verify(3 < tdiv(x, 2), tvm.tir.LT(7, x))\n    ck.verify(tdiv(x, 3) >= 0, tvm.tir.LE(-2, x))\n    ck.verify(tdiv(x, 2) >= 1, tvm.tir.LE(2, x))\n    ck.verify(tdiv(x, 2) >= 0, tvm.tir.LE(-1, x))\n    ck.verify(tdiv(x, 2) >= -1, tvm.tir.LE(-3, x))\n\n    ck.verify(tdiv(x, 2) <= 1, tvm.tir.LE(x, 3))\n    ck.verify(tdiv(x, 2) <= 0, tvm.tir.LE(x, 1))\n    ck.verify(tdiv(x, 2) <= -1, tvm.tir.LE(x, -2))\n\n    ck.verify(tdiv(x, 4) * 4 < x, tvm.tir.LT(0, tmod(x, 4)))\n    ck.verify(tdiv(x, 4) * 4 >= x, tvm.tir.LE(tmod(x, 4), 0))\n\n    ck.verify(tdiv(x, 4) * 4 < x + y, tvm.tir.LT(0, tmod(x, 4) + y))\n    ck.verify(tdiv(x, 4) * 4 < x - y, tvm.tir.LT(y, tmod(x, 4)))\n\n    ck.verify(tdiv(x + 2, 4) * 4 >= x, tvm.tir.LE(tmod(x + 2, 4), 2))\n    ck.verify(tdiv(x + 2, 4) * 4 >= x + y, tvm.tir.LE(tmod(x + 2, 4) + y, 2))\n    ck.verify(tdiv(x + 2, 4) * 4 >= x - y, tvm.tir.LE(tmod(x + 2, 4) + (-2), y))\n\n    # floor div\n    ck.verify(fld(x, 2) < 3, x < 6)\n    ck.verify(3 < fld(x, 2), tvm.tir.LT(7, x))\n    ck.verify(-3 < fld(x, 2), tvm.tir.LT(-5, x))\n    ck.verify(fld(x, 3) >= 0, tvm.tir.LE(0, x))\n    ck.verify(fld(x, 2) >= 1, tvm.tir.LE(2, x))\n    ck.verify(fld(x, 2) >= 0, tvm.tir.LE(0, x))\n    ck.verify(fld(x, 2) >= -1, tvm.tir.LE(-2, x))\n\n    ck.verify(fld(x, 2) <= 1, tvm.tir.LE(x, 3))\n    ck.verify(fld(x, 2) <= 0, tvm.tir.LE(x, 1))\n    ck.verify(fld(x, 2) <= -1, tvm.tir.LE(x, -1))\n\n    ck.verify(fld(x, 4) * 4 < x, tvm.tir.LT(0, flm(x, 4)))\n    ck.verify(fld(x, 4) * 4 >= x, tvm.tir.EQ(flm(x, 4), 0))\n\n    ck.verify(fld(x, 4) * 4 < x + y, tvm.tir.LT(0, flm(x, 4) + y))\n    ck.verify(fld(x, 4) * 4 < x - y, tvm.tir.LT(y, flm(x, 4)))\n\n    ck.verify(fld(x + 2, 4) * 4 >= x, tvm.tir.LE(flm(x + 2, 4), 2))\n    ck.verify(fld(x + 2, 4) * 4 >= x + y, tvm.tir.LE(flm(x + 2, 4) + y, 2))\n    ck.verify(fld(x + 2, 4) * 4 >= x - y, tvm.tir.LE(flm(x + 2, 4) + (-2), y))\n    # End DivMod Rules\n\n    ck.verify(tvm.te.min(x, 11) < 10, x < 10)\n    ck.verify(tvm.te.min(x, 8) < 10, tvm.tir.const(1, \"bool\"))\n    ck.verify(tvm.te.max(8, x) > 10, tvm.tir.LT(10, x))\n    ck.verify(x + 1 < tvm.te.max(8, x), x < 7)\n\n    ck.analyzer.update(x, tvm.arith.ConstIntBound(0, 10), override=True)\n    ck.analyzer.update(y, tvm.arith.ConstIntBound(-10, 0), override=True)\n    ck.analyzer.update(z, tvm.arith.ConstIntBound(-5, 5), override=True)\n\n    ck.verify(x < 11, tvm.tir.const(1, \"bool\"))\n    ck.verify(x <= 10, tvm.tir.const(1, \"bool\"))\n    ck.verify(z <= 5, tvm.tir.const(1, \"bool\"))\n    ck.verify(x + y <= 10, tvm.tir.const(1, \"bool\"))\n    ck.verify(x + y >= -10, tvm.tir.const(1, \"bool\"))\n    ck.verify(z - 5 <= y + 10, tvm.tir.const(1, \"bool\"))\n    ck.verify(tvm.tir.all(x > -1, z <= x + 5), tvm.tir.const(1, \"bool\"))\n    ck.verify(x * y <= 0, tvm.tir.const(1, \"bool\"))\n    ck.verify((x + 1) * (y - 1) < 0, tvm.tir.const(1, \"bool\"))\n    ck.verify(y * y >= 0, tvm.tir.const(1, \"bool\"))\n    ck.verify(x * 6 <= -3, tvm.tir.const(0, \"bool\"))\n    ck.verify(tmod(y - 1, 3) == 0, tmod(y + (-1), 3) == 0)\n\n\ndef test_logical_simplify():\n    ck = RewriteChecker()\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n\n    ck.verify(tvm.tir.And(tvm.tir.EQ(x, y), tvm.tir.NE(x, y)), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(tvm.tir.NE(x, y), tvm.tir.EQ(x, y)), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x > 1, tvm.tir.Not(x > 1)), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x <= y, y < x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(y < x, x <= y), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x < 1, 0 < x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x < 0, 1 < x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x < 1, 1 <= x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x <= 1, 1 < x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(1 <= x, x < 1), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(1 < x, x <= 1), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x <= 1, 2 <= x), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(2 <= x, x <= 1), tvm.tir.const(False, \"bool\"))\n    ck.verify(tvm.tir.And(x == 1, x != 2), x == 1)\n\n    ck.verify(tvm.tir.Or(tvm.tir.EQ(x, y), tvm.tir.NE(x, y)), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(tvm.tir.NE(x, y), tvm.tir.EQ(x, y)), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(x > y, tvm.tir.Not(x > y)), tvm.tir.const(True, \"bool\"))\n\n    ck.verify(tvm.tir.Or(x <= y, y < x), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(y < x, y >= x), tvm.tir.const(True, \"bool\"))\n\n    ck.verify(tvm.tir.Or(x < 1, 0 < x), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(0 < x, x < 1), tvm.tir.const(True, \"bool\"))\n\n    ck.verify(tvm.tir.Or(x < 1, 1 <= x), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(x <= 1, 1 < x), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(1 <= x, x < 1), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(1 < x, x <= 1), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(x <= 1, 2 <= x), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(2 <= x, x <= 1), tvm.tir.const(True, \"bool\"))\n    ck.verify(tvm.tir.Or(x != 1, x == 2), x != 1)\n\n\ndef test_let_simplify():\n    ck = RewriteChecker()\n    x, y = te.var(\"x\"), te.var(\"y\")\n    z = tvm.tir.Let(x, 1, x + 1)\n    ck.verify(z + z, 4)\n\n\ndef test_cast_simplify():\n    ck = RewriteChecker()\n    x = te.var(\"x\")\n\n    dtypes = [\"float32\", \"float16\", \"int32\", \"int8\", \"bool\"]\n    for dtype1 in dtypes:\n        ck.verify(tvm.tir.Cast(dtype1, x - x), tvm.tir.const(0, dtype1))\n        ck.verify(tvm.tir.Cast(dtype1, x == x), tvm.tir.const(1, dtype1))\n        for dtype2 in dtypes:\n            for i in [0, 1, 2, 3]:\n                if i > 1 and (dtype1 == \"bool\" or dtype2 == \"bool\"):\n                    continue\n                ck.verify(tvm.tir.Cast(dtype1, tvm.tir.const(i, dtype2)), tvm.tir.const(i, dtype1))\n\n\ndef test_shift_left_simplify():\n    ck = RewriteChecker()\n    z = tvm.tir.op.call_intrin(\"int32\", \"tir.shift_left\", 1, 10)\n    ck.verify(z, tvm.tir.const(1 << 10, \"int32\"))\n\n\ndef test_div_zero_simplify():\n    ck = RewriteChecker()\n    ramp = tvm.tir.Ramp(1, 1, 2)\n    broadcast = tvm.tir.Broadcast(0, 2)\n\n    with pytest.raises(tvm.error.TVMError) as cm:\n        ck.analyzer.rewrite_simplify(tvm.tir.Div(ramp, broadcast))\n        assert \"division by zero\" in str(cm.execption)\n\n    with pytest.raises(tvm.error.TVMError) as cm:\n        ck.analyzer.rewrite_simplify(tvm.tir.Mod(ramp, broadcast))\n        assert \"division by zero\" in str(cm.execption)\n\n    with pytest.raises(tvm.error.TVMError) as cm:\n        ck.analyzer.rewrite_simplify(tvm.tir.FloorDiv(ramp, broadcast))\n        assert \"division by zero\" in str(cm.execption)\n\n    with pytest.raises(tvm.error.TVMError) as cm:\n        ck.analyzer.rewrite_simplify(tvm.tir.FloorMod(ramp, broadcast))\n        assert \"division by zero\" in str(cm.execption)\n\n\ndef test_sub_bufferload():\n    ck = RewriteChecker()\n    buf = tvm.tir.decl_buffer([1], dtype=\"float32\")\n    load = tvm.tir.BufferLoad(buf, [0])\n    expr = load - load\n    ck.verify(expr, 0.0)\n\n\ndef test_if_then_else_simplify():\n    ck = RewriteChecker()\n    x = te.var(\"x\", \"int32\")\n    z = tvm.tir.if_then_else(x < 5, tvm.tir.if_then_else(x > 1, 1, 0), 0)\n    ck.verify(z, tvm.tir.if_then_else(tvm.tir.And(tvm.tir.LT(x, 5), tvm.tir.LT(1, x)), 1, 0))\n\n    z = tvm.tir.if_then_else(x > 2, tvm.tir.if_then_else(x > 1, 1, 0), 0)\n    ck.verify(z, tvm.tir.if_then_else(tvm.tir.LT(2, x), 1, 0))\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_solve_linear_equations.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport random\nimport sys\nimport pytest\nimport tvm\nfrom tvm import te, arith, ir, tir, testing\n\n\ndef test_solution_consistency():\n    seed = random.randrange(sys.maxsize)\n    print(\n        \"\\nThis test is intentionally non-deterministic, \"\n        \"if it fails please report it in github issue together with this seed {}\\n\".format(seed)\n    )\n    random.seed(seed)\n\n    def _check(num_vars, num_formulas, coef=(-5, 5), bounds=(-20, 20)):\n        variables = [te.var(\"x\" + str(i)) for i in range(num_vars)]\n\n        relations = []\n        for i in range(num_formulas):\n            s1 = sum([v * random.randint(coef[0], coef[1]) for v in variables])\n            s1 += random.randint(coef[0], coef[1])\n            s2 = sum([v * random.randint(coef[0], coef[1]) for v in variables])\n            s2 += random.randint(coef[0], coef[1])\n            if random.random() < 0.7:\n                op = tvm.tir.EQ\n            else:\n                # we also make sure it can correctly handle inequalities\n                op = random.choice([tvm.tir.LE, tvm.tir.LT, tvm.tir.GE, tvm.tir.GT])\n            relations.append(op(s1, s2))\n\n        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in variables}\n        solution = arith.solve_linear_equations(relations, variables, vranges)\n\n        testing.check_int_constraints_trans_consistency(solution)\n\n        # leaving some variables as parameters should also be ok\n        for k in [1, 2]:\n            if len(variables) > k:\n                solution = arith.solve_linear_equations(relations, variables[:-k], vranges)\n                param_ranges = {v: vranges[v] for v in variables[-k:]}\n                testing.check_int_constraints_trans_consistency(solution, param_ranges)\n\n    for i in range(2):\n        _check(num_vars=1, num_formulas=1)\n    for i in range(2):\n        _check(num_vars=1, num_formulas=2)\n\n    for i in range(2):\n        _check(num_vars=2, num_formulas=1)\n    for i in range(2):\n        _check(num_vars=2, num_formulas=2)\n    for i in range(2):\n        _check(num_vars=2, num_formulas=3)\n\n    for i in range(3):\n        _check(num_vars=3, num_formulas=3, coef=(-2, 2))\n    for i in range(3):\n        _check(num_vars=3, num_formulas=4, coef=(-2, 2))\n\n    for i in range(3):\n        _check(num_vars=4, num_formulas=3, coef=(-1, 1))\n\n    for i in range(3):\n        _check(num_vars=10, num_formulas=2, coef=(-1, 1), bounds=(0, 4))\n    for i in range(3):\n        _check(num_vars=10, num_formulas=3, coef=(0, 1), bounds=(0, 4))\n\n\ndef test_empty_var_to_solve():\n    x, y = te.var(\"x\"), te.var(\"y\")\n    equations = [\n        tvm.tir.EQ(x + y, 20),\n        tvm.tir.EQ(x - y, 10),\n    ]\n    solution = arith.solve_linear_equations(equations)\n    assert len(solution.src_to_dst) == 0\n    assert len(solution.dst_to_src) == 0\n    assert len(solution.src.variables) == 0\n    assert len(solution.src.ranges) == 0\n    assert ir.structural_equal(solution.src.relations, equations)\n    assert ir.structural_equal(solution.src, solution.dst)\n\n\ndef test_unique_solution():\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    solution = arith.solve_linear_equations(\n        [\n            tvm.tir.EQ(x + y, 20),\n            tvm.tir.EQ(x - y, 10),\n        ],\n        [x, y],\n    )\n    assert list(solution.dst.variables) == []\n    assert ir.structural_equal(solution.src_to_dst[x], 15)\n    assert ir.structural_equal(solution.src_to_dst[y], 5)\n\n\ndef test_low_rank():\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    ranges = {}\n\n    solution = arith.solve_linear_equations(\n        [\n            tvm.tir.EQ(x + y + z, 15),\n            tvm.tir.EQ(x + y, 10),\n        ],\n        [x, y, z],\n        ranges,\n    )\n    [n0] = solution.dst.variables\n    assert ir.structural_equal(solution.src_to_dst[x], n0 + 10)\n    assert ir.structural_equal(solution.src_to_dst[y], -n0)\n    assert ir.structural_equal(solution.src_to_dst[z], 5)\n\n\ndef test_infer_range():\n    x, y = te.var(\"x\"), te.var(\"y\")\n    ranges = {\n        x: tvm.ir.Range.from_min_extent(-5, 10),\n        y: tvm.ir.Range.from_min_extent(0, 10),\n    }\n\n    solution = arith.solve_linear_equations(\n        [\n            tvm.tir.EQ(x + y, 0),\n        ],\n        [x, y],\n        ranges,\n    )\n    [n0] = solution.dst.variables\n    assert ir.structural_equal(solution.src_to_dst[x], n0)\n    assert ir.structural_equal(solution.src_to_dst[y], -n0)\n    # inferred from y's range\n    assert ir.structural_equal(solution.dst.ranges[n0].min, -9)\n    assert ir.structural_equal(solution.dst.ranges[n0].extent, 10)\n    # additional inequality is added into the system for x\n    [ineq] = solution.dst.relations\n    assert isinstance(ineq, tvm.tir.LE)\n    assert ir.structural_equal(ineq.a, -5)\n    assert ir.structural_equal(ineq.b, n0)\n\n\ndef test_ill_formed():\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    solution = arith.solve_linear_equations(\n        [\n            tvm.tir.EQ(x + y, 0),\n            tvm.tir.EQ(x - y, 0),\n            tvm.tir.EQ(x, 5),\n        ],\n        [x, y],\n        {},\n    )\n    assert list(solution.dst.variables) == []\n    [rel] = solution.dst.relations\n    assert ir.structural_equal(rel, False)\n    assert len(solution.src_to_dst) == 0\n    assert len(solution.dst_to_src) == 0\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_arith_solve_linear_inequality.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport random\nimport sys\nimport pytest\nimport tvm\nfrom tvm import te, arith, ir, tir, testing\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/11458\")\ndef test_solution_consistency():\n    seed = random.randrange(sys.maxsize)\n    print(\n        \"\\nThis test is intentionally non-deterministic, \"\n        \"if it fails please report it in github issue together with this seed {}\\n\".format(seed)\n    )\n    random.seed(seed)\n\n    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):\n        vs = [te.var(\"x\" + str(i)) for i in range(variables)]\n\n        fs = []\n        for i in range(formulas):\n            s1 = sum([v * random.randint(coef[0], coef[1]) for v in vs])\n            s1 += random.randint(coef[0], coef[1])\n            s2 = sum([v * random.randint(coef[0], coef[1]) for v in vs])\n            s2 += random.randint(coef[0], coef[1])\n            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])\n            fs.append(op(s1, s2))\n\n        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}\n        before = te.all(tir.const(1, \"bool\"), *fs)\n        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)\n        after = te.all(tir.const(1, \"bool\"), *after)\n        testing.check_bool_expr_is_true(before == after, vranges)\n\n        solution = arith.solve_linear_inequalities(fs, vs, vranges, deskew_range=True)\n        testing.check_int_constraints_trans_consistency(solution)\n\n    for i in range(3):\n        _check(1, 1)\n    for i in range(3):\n        _check(1, 2)\n\n    for i in range(3):\n        _check(2, 1)\n    for i in range(3):\n        _check(2, 2)\n    for i in range(3):\n        _check(2, 3)\n\n    # Somewhere here coefficients in the results become too large, leading to overflow,\n    # so we use smaller initial coefficients\n    for i in range(5):\n        _check(3, 3, coef=(-2, 2))\n    for i in range(5):\n        _check(3, 4, coef=(-2, 2))\n\n    for i in range(5):\n        _check(4, 3, coef=(-1, 1))\n\n    for i in range(5):\n        _check(10, 2, coef=(-1, 1), bounds=(0, 4))\n    for i in range(5):\n        _check(10, 3, coef=(0, 1), bounds=(0, 4))\n\n\ndef test_dual_variable():\n    x, y = te.var(\"x\"), te.var(\"y\")\n\n    variables = [x, y]\n    ranges = {\n        x: tvm.ir.Range(-100, 100),\n        y: tvm.ir.Range(0, 10),\n    }\n    problem = [\n        tvm.tir.LE(x + y, 20),\n        tvm.tir.GE(x - y, 10),\n    ]\n\n    # solution as conditions\n    solution = arith._ffi_api.SolveInequalitiesAsCondition(variables, ranges, problem)\n    assert ir.structural_equal(solution[0], x >= (y + 10))\n    assert ir.structural_equal(solution[1], x <= (20 - y))\n    assert ir.structural_equal(solution[2], y >= 0)\n    assert ir.structural_equal(solution[3], y <= 5)\n\n    # solve and get the ranges\n    solution = arith.solve_linear_inequalities(problem, variables, ranges)\n    # 0 <= y <=5\n    assert solution.ranges[y].min == 0\n    assert solution.ranges[y].extent == 6\n    # y + 10 <= x <= 20 - y\n    assert ir.structural_equal(solution.ranges[x].min, y + 10)\n    assert solution.ranges[x].extent == 11  # max(10 - 2y)\n\n    # deskew the solved ranges to be starting from zero\n    solution = arith.solve_linear_inequalities(problem, variables, ranges, deskew_range=True)\n    [x_new, y_new] = solution.dst.variables\n    [rel] = solution.dst.relations\n    assert ir.structural_equal(rel, (y_new * 2) + x_new <= 10)\n    assert ir.structural_equal(solution.dst.ranges[x_new].min, 0)\n    assert ir.structural_equal(solution.dst.ranges[x_new].extent, 11)\n    assert ir.structural_equal(solution.dst.ranges[y_new].min, 0)\n    assert ir.structural_equal(solution.dst.ranges[y_new].extent, 6)\n    assert ir.structural_equal(solution.src_to_dst[x], x_new + (y_new + 10))\n    assert ir.structural_equal(solution.src_to_dst[y], y_new)\n    assert ir.structural_equal(solution.dst_to_src[x_new], x - y - 10)\n    assert ir.structural_equal(solution.dst_to_src[y_new], y)\n\n\ndef test_equal():\n    x, y = te.var(\"x\"), te.var(\"y\")\n    problem = [\n        tvm.tir.GE(x + y, 10),\n        tvm.tir.GE(x - y, 2),\n        tvm.tir.LE(x, 6),\n    ]\n\n    solution = arith.solve_linear_inequalities(problem, [x, y])\n    assert solution.ranges[x].min == 6\n    assert solution.ranges[x].extent == 1\n    assert solution.ranges[y].min == 4\n    assert solution.ranges[y].extent == 1\n\n    solution = arith.solve_linear_inequalities(problem, [x, y], deskew_range=True)\n    assert len(solution.dst.variables) == 0\n    assert len(solution.dst.ranges) == 0\n    assert len(solution.dst.relations) == 0\n    assert solution.src_to_dst[x] == 6\n    assert solution.src_to_dst[y] == 4\n\n\ndef test_multi_equal():\n    x, y, z = te.var(\"x\"), te.var(\"y\"), te.var(\"z\")\n    problem = [\n        tvm.tir.LE(x, 6),\n        tvm.tir.GE(x, 6),\n        tvm.tir.GE(x - z * y, 0),\n        tvm.tir.LE(x - z * y, 0),\n    ]\n\n    solution = arith.solve_linear_inequalities(problem, [x, y, z])\n    assert solution.ranges[x].min == 6\n    assert solution.ranges[x].extent == 1\n    assert len(solution.relations) == 3\n    assert ir.structural_equal(solution.relations[0], x == z * y)\n\n    assert isinstance(solution.relations[1], tvm.tir.LE)\n    assert solution.relations[1].b == 0\n    assert isinstance(solution.relations[2], tvm.tir.LE)\n    assert solution.relations[2].b == 0\n    # (z*y - 6) <= 0 && (6 - z*y) <= 0\n    ana = tvm.arith.Analyzer()\n    assert ana.simplify(solution.relations[1].a + solution.relations[2].a) == 0\n    assert ir.structural_equal(solution.relations[1].a, (z * y - 6)) or ir.structural_equal(\n        solution.relations[2].a, (z * y - 6)\n    )\n\n    solution = arith.solve_linear_inequalities(problem, [x, y, z], deskew_range=True)\n    assert solution.src_to_dst[y] == y\n    assert solution.src_to_dst[z] == z\n    assert solution.src_to_dst[x] == 6\n\n\ndef test_no_solution():\n    x = te.var(\"x0\")\n    vranges = {x: tvm.ir.Range.from_min_extent(-20, 41)}\n    problem = [-x - 4 <= -5 * x + 2, x * 4 + 5 <= x * 5]\n\n    solution = arith.solve_linear_inequalities(problem, [x], vranges, deskew_range=True)\n    assert list(solution.dst.variables) == []\n    [rel] = solution.dst.relations\n    assert ir.structural_equal(rel, False)\n    assert len(solution.src_to_dst) == 0\n    assert len(solution.dst_to_src) == 0\n\n    solution = arith.solve_linear_inequalities(problem, [x], vranges)\n    assert len(solution.variables) == 0\n    assert len(solution.ranges) == 0\n    [rel] = solution.relations\n    assert not rel\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_compute_dag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test ComputeDAG (replay, infer bound)\"\"\"\nimport json\nimport pickle\n\nimport tvm\nfrom tvm import topi\nfrom tvm import auto_scheduler, te\n\nfrom tvm.testing.auto_scheduler import (\n    get_tiled_matmul,\n    invalid_compute_definition,\n    matmul_auto_scheduler_test,\n    parallel_matmul_auto_scheduler_test,\n)\n\n\ndef test_apply_steps():\n    dag, s = get_tiled_matmul()\n    dag.print_python_code_from_state(s)\n    sch, tensors = dag.apply_steps_from_state(s)\n    tvm.lower(sch, tensors, simple_mode=True)\n\n\ndef test_infer_bound():\n    dag, s = get_tiled_matmul()\n    s = dag.infer_bound_from_state(s)\n\n\ndef test_estimate_flop():\n    N = 512\n    A, B, C = matmul_auto_scheduler_test(N, N, N)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    assert abs(dag.flop_ct - 2 * N**3) < 0.5\n\n    D = topi.nn.relu(C)\n    dag = auto_scheduler.ComputeDAG([A, B, D])\n    assert abs(dag.flop_ct - (2 * N**3 + N * N)) < 0.5\n\n    # should not count the comparison operations in padding\n    E = topi.nn.pad(C, [1, 1])\n    dag = auto_scheduler.ComputeDAG([A, B, E])\n    assert abs(dag.flop_ct - 2 * N**3) < 0.5\n\n    F = te.compute((N, N), lambda i, j: E[i, j], name=\"F\", attrs={\"FLOP\": 1234})\n    dag = auto_scheduler.ComputeDAG([A, B, F])\n    assert abs(dag.flop_ct - (2 * N**3 + 1234)) < 0.5\n\n    A = te.placeholder((N, N), dtype=\"float32\", name=\"A\")\n    F = te.compute((N, N), lambda i, j: te.if_then_else(A[i, j] > 0, A[i, j], 0))\n    dag = auto_scheduler.ComputeDAG([A, F])\n    assert abs(dag.flop_ct - N**2) < 0.5\n\n\ndef test_stage_order():\n    \"\"\"Test if the stage order is preserved when recovering a DAG.\"\"\"\n    N = 512\n    A, B, C, D, E = parallel_matmul_auto_scheduler_test(N)\n    sch = te.create_schedule([D.op, E.op])\n    (D_local,) = sch.cache_write([D], \"local\")\n    (E_local,) = sch.cache_write([E], \"local\")\n    sch.cache_read(A, \"shared\", [D_local])\n    sch.cache_read(B, \"shared\", [D_local])\n    sch.cache_read(A, \"shared\", [E_local])\n    sch.cache_read(C, \"shared\", [E_local])\n\n    dag = auto_scheduler.ComputeDAG(sch)\n    stage_ops_1 = dag.get_init_state().stage_ops\n\n    # 3 placeholder, 4 x.shared, 2 {D,E}.local, 2 {D,E} compute\n    assert len(stage_ops_1) == 11\n\n    # Cache read stage should follow the source stage\n    for idx, op in enumerate(stage_ops_1):\n        if op.name == \"A\":\n            assert (\n                stage_ops_1[idx + 1].name == \"A.d.shared\"\n                and stage_ops_1[idx + 2].name == \"A.shared\"\n            )\n        elif op.name in [\"B\", \"C\"]:\n            assert stage_ops_1[idx + 1].name == \"%s.shared\" % op.name\n\n    # Apply the same schedule to Ansor state and it should have the same stage order\n    dag = auto_scheduler.ComputeDAG([A, B, C, D, E])\n    state = dag.get_init_state()\n\n    D_local = state.cache_write(D, \"local\")\n    E_local = state.cache_write(E, \"local\")\n    state.cache_read(A, \"shared\", [D_local])\n    state.cache_read(B, \"shared\", [D_local])\n    state.cache_read(A, \"shared\", [E_local])\n    state.cache_read(C, \"shared\", [E_local])\n\n    stage_ops_2 = state.stage_ops\n    assert len(stage_ops_1) == len(stage_ops_2)\n\n    # Cache read stage should follow the source stage\n    for op1, op2 in zip(stage_ops_1, stage_ops_2):\n        assert op1.name == op2.name\n\n    # Serialize and deserialize the ComputeDAG constructed by a list of tensor ops.\n    loaded_dag = pickle.loads(pickle.dumps(dag))\n    assert str(loaded_dag.get_init_state()) == str(dag.get_init_state())\n    assert len(loaded_dag.get_init_state().stage_ops) == len(dag.get_init_state().stage_ops)\n\n    # Serialize and deserialize the search task. Note that we intentionally skip hardware_params\n    # to test if the default one is serialized along with other attributes as well.\n    task = auto_scheduler.SearchTask(\n        compute_dag=dag, workload_key=json.dumps((\"test-key\",)), target=tvm.target.Target(\"llvm\")\n    )\n\n    task2 = pickle.loads(pickle.dumps(task))\n    assert '[\"test-key\"]' in auto_scheduler.workload_registry.WORKLOAD_FUNC_REGISTRY\n    assert str(task.compute_dag.get_init_state()) == str(task2.compute_dag.get_init_state())\n    assert len(task.compute_dag.get_init_state().stage_ops) == len(\n        task2.compute_dag.get_init_state().stage_ops\n    )\n    assert task.workload_key == task2.workload_key\n    assert str(task.target) == str(task2.target)\n    assert task.hardware_params.num_cores == task2.hardware_params.num_cores\n    assert task.hardware_params.vector_unit_bytes == task2.hardware_params.vector_unit_bytes\n    assert task.hardware_params.cache_line_bytes == task2.hardware_params.cache_line_bytes\n\n\ndef test_invalid_compute_dag():\n    failed = False\n    try:\n        A, B = invalid_compute_definition()\n        auto_scheduler.ComputeDAG([A, B])\n    except tvm.TVMError:\n        failed = True\n\n    assert failed\n\n\nif __name__ == \"__main__\":\n    test_apply_steps()\n    test_infer_bound()\n    test_estimate_flop()\n    test_stage_order()\n    test_invalid_compute_dag()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test cost models\"\"\"\n\nimport tempfile\n\nimport numpy as np\n\nimport tvm\nfrom tvm import auto_scheduler\n\nfrom tvm.testing.auto_scheduler import matmul_auto_scheduler_test\n\n\ndef get_sample_records(number):\n    \"\"\"Generate a list of random MeasureInput and MeasureResult pairs\"\"\"\n    N = 128\n    task = auto_scheduler.SearchTask(func=matmul_auto_scheduler_test, args=(N, N, N), target=\"llvm\")\n    policy = auto_scheduler.SketchPolicy(task, verbose=0)\n    states = policy.sample_initial_population()[:number]\n\n    inputs = [auto_scheduler.MeasureInput(task, s) for s in states]\n    results = [\n        auto_scheduler.MeasureResult([np.random.uniform(0.5, 1.0)], 0, \"\", 0.1, 0)\n        for _ in range(len(inputs))\n    ]\n\n    return task, inputs, results\n\n\ndef test_random_model():\n    task, inputs, results = get_sample_records(50)\n\n    model = auto_scheduler.RandomModel()\n    model.update(inputs, results)\n    scores = model.predict(task, [x.state for x in inputs])\n    assert len(scores) == len(inputs)\n\n\ndef test_xgb_model():\n    task, inputs, results = get_sample_records(50)\n\n    model = auto_scheduler.XGBModel(num_warmup_sample=-1)\n    model.update(inputs, results)\n    preds = model.predict(task, [x.state for x in inputs])\n    assert len(preds) == len(inputs)\n\n    costs = [np.mean([x.value for x in res.costs]) for res in results]\n    throughputs = np.min(costs) / costs\n\n    # test regression quality\n    rmse = np.sqrt(np.mean([np.square(pred - label) for pred, label in zip(preds, throughputs)]))\n    assert rmse <= 0.3\n\n    # test loading a record file\n    tmpdir = tvm.contrib.utils.tempdir()\n    tmpfile = tmpdir.relpath(\"test1\")\n    auto_scheduler.save_records(tmpfile, inputs, results)\n    model.update_from_file(tmpfile)\n\n    # test model serialization\n    tmpfile = tmpdir.relpath(\"test2\")\n    model.save(tmpfile)\n    model.load(tmpfile)\n\n\nif __name__ == \"__main__\":\n    test_random_model()\n    test_xgb_model()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_evolutionary_search.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test evolutionary search. \"\"\"\n\nimport tvm\nimport pytest\nfrom tvm.testing.auto_scheduler import matmul_auto_scheduler_test\nfrom tvm import auto_scheduler, te\nfrom tvm.auto_scheduler.cost_model.cost_model import PythonBasedModel\n\n\ndef test_mutate_tile_size():\n    \"\"\"\n    The test case initializes evo search with a batch of \"bad\" states and check whether\n    the search algorithm can find \"good\" states by mutating the \"bad\" states.\n\n    This unit test has been tested with 1,000 runs with no failures, meaning that\n    the failure rate is less than 0.1%.\n    \"\"\"\n\n    class MockCostModel(PythonBasedModel):\n        \"\"\"A mock cost model that rates 1 only for the states with tile_k=2.\"\"\"\n\n        @staticmethod\n        def is_good_state(state):\n            for line in str(state).split(\"\\n\"):\n                if line.find(\"k.1\") != -1 and line.find(\"(0,2)\") != -1:\n                    return True\n            return False\n\n        def predict(self, task, states):\n            scores = []\n            for state in states:\n                scores.append(1 if self.is_good_state(state) else 0)\n            return scores\n\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(10, 10, 4), target=tvm.target.Target(\"llvm\")\n    )\n    policy = auto_scheduler.SketchPolicy(task, program_cost_model=MockCostModel(), verbose=0)\n    states = policy.sample_initial_population()[:50]\n\n    bad_states = []\n    for state in states:\n        if not MockCostModel.is_good_state(state):\n            bad_states.append(state)\n\n    new_states = policy.evolutionary_search(bad_states, 50)\n    found = False\n    for state in new_states:\n        if MockCostModel.is_good_state(state):\n            found = True\n            break\n    assert found\n\n\n@pytest.mark.skip(reason=\"See https://github.com/apache/tvm/issues/11440\")\ndef test_mutate_parallel():\n    \"\"\"\n    The test case initializes evo search with a batch of \"bad\" states and check whether\n    the search algorithm can find \"good\" states by mutating the \"bad\" states.\n    \"\"\"\n\n    class MockCostModel(PythonBasedModel):\n        @staticmethod\n        def is_good_state(state):\n            for line in str(state).split(\"\\n\"):\n                if (\n                    line.find(\"parallel i.0@ (0\") != -1\n                    or line.find(\"parallel i.0@j.0@ (0\") != -1\n                    or line.find(\"parallel i.0@j.0@i.1@ (0\") != -1\n                ):\n                    return True\n            return False\n\n        def predict(self, task, states):\n            scores = []\n            for state in states:\n                scores.append(1 if self.is_good_state(state) else 0)\n            return scores\n\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(1024, 1024, 1024), target=\"llvm\"\n    )\n    policy = auto_scheduler.SketchPolicy(task, program_cost_model=MockCostModel(), verbose=0)\n\n    found = False\n    retry_ct = 0\n    while retry_ct < 10 and not found:\n        states = policy.sample_initial_population()[:100]\n        bad_states = []\n        for state in states:\n            if not MockCostModel.is_good_state(state):\n                bad_states.append(state)\n\n        new_states = policy.evolutionary_search(bad_states, 50)\n        for state in new_states:\n            if MockCostModel.is_good_state(state):\n                found = True\n                break\n        retry_ct += 1\n\n    assert found\n\n\nif __name__ == \"__main__\":\n    test_mutate_tile_size()\n    test_mutate_parallel()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test feature extraction\"\"\"\n\nimport math\nimport tempfile\n\nimport tvm\nfrom tvm import te, auto_scheduler, relay\nfrom tvm.script import tir as T\n\nfrom tvm.testing.auto_scheduler import matmul_auto_scheduler_test\n\n\ndef fequal(a, b):\n    return math.fabs(a - b) < 1e-6\n\n\ndef test_cpu_matmul():\n    dag = auto_scheduler.ComputeDAG(matmul_auto_scheduler_test(512, 512, 512))\n    s = dag.get_init_state()\n    C = s.stage_ops[2]\n\n    i, j, k = s[C].iters\n    io, ii = s.split(C, i, [16])\n    jo, ji = s.split(C, j, [8])\n    s.reorder(C, [io, jo, k, ji, ii])\n    s.vectorize(C, ji)\n    s.parallel(C, io)\n    s.parallel(C, jo)\n    s.unroll(C, k)\n\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(compute_dag=dag, workload_key=\"test\", target=target)\n    names = auto_scheduler.feature.get_per_store_feature_names()\n    fea = auto_scheduler.feature.get_per_store_features_from_states([s], task)[0]\n\n    stage_0 = fea[0]\n    assert len(stage_0) == len(names), \"%d vs %d\" % (len(stage_0), len(names))\n    fea_dict = {}\n    for name, value in zip(names, stage_0):\n        fea_dict[name] = value\n\n    for name in [\"B0\", \"B1\", \"B2\"]:\n        if fequal(fea_dict[name + \".acc_type.kReadWrite\"], 1.0):\n            c_name = name\n        if fequal(fea_dict[name + \".acc_type.kRead\"], 1.0):\n            if fequal(fea_dict[name + \".stride\"], 0.0):\n                b_name = name\n            else:\n                a_name = name\n\n    \"\"\"\n    lowered IR:\n\n    Placeholder: A, B\n    parallel i.0 (0,32)\n      parallel j.0 (0,64)\n        unroll k (0,512)\n          vectorize j.1 (0,8)\n            for i.1 (0,16)\n              C...] = A[...] * B[...]\n    \"\"\"\n\n    # check touched memory in bytes, touched unique memory in bytes, reuse distance, etc.\n    assert fequal(fea_dict[c_name + \".bytes\"], math.log2(512**3 * 4 + 1))\n    assert fequal(fea_dict[b_name + \".unique_bytes\"], math.log2(512**2 * 4 + 1))\n    assert fequal(fea_dict[c_name + \".reuse_dis_iter\"], math.log2(8 * 16 + 1))\n    assert fequal(fea_dict[c_name + \".reuse_dis_bytes\"], math.log2((8 * 16 + 8 + 16) * 4 + 1))\n    assert fequal(fea_dict[c_name + \".reuse_ct\"], math.log2(512 + 1))\n\n    # check annotations\n    assert fequal(fea_dict[\"unroll_num\"], math.log2(1 + 1))\n    # assert fequal(fea_dict[\"unroll_type.kPosInnerReduce\"], 1.0)\n    assert fequal(fea_dict[\"vec_num\"], math.log2(1 + 1))\n    assert fequal(fea_dict[\"parallel_num\"], math.log2(2 + 1))\n    assert fequal(fea_dict[\"parallel_prod\"], math.log2((512 * 512 / 16 / 8) + 1))\n\n\ndef test_cpu_fusion():\n    def fusion_test(N, M):\n        A = te.placeholder((N, M), name=\"A\")\n        B = te.compute((N, M), lambda i, j: A[i][j], name=\"B\")\n        C = te.compute((N, M), lambda i, j: B[i][j], name=\"C\")\n        return [A, B, C]\n\n    dag = auto_scheduler.ComputeDAG(fusion_test(64, 32))\n    s = dag.get_init_state()\n    s.compute_at(1, 2, s.stages[2].iters[1])\n\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(compute_dag=dag, workload_key=\"test\", target=target)\n    names = auto_scheduler.feature.get_per_store_feature_names()\n    fea = auto_scheduler.feature.get_per_store_features_from_states([s], task)[0]\n\n    \"\"\"\n    lowered IR:\n\n    Placeholder: A\n    for i (0,64)\n        for j (0,32)\n            for ii (1)\n                for jj (1)\n                    B[...] = A[...]\n            C[...] = B[...]\n    \"\"\"\n\n    # check reuse distance and reuse type after fusion\n    found = False\n    for stage_fea in fea:\n        for i, (name, value) in enumerate(zip(names, stage_fea)):\n            if \"reuse_type.kSerialMultipleReadWrite\" in name and value > 0.5:\n                # reuse distance in #iter\n                assert fequal(stage_fea[i + 2], 1.0)\n                # reuse distance in bytes\n                assert fequal(stage_fea[i + 3], math.log2(16 + 1))\n                found = True\n    assert found\n\n\ndef test_gpu_feature():\n    # Use records to build a complicated GPU program\n    json_records = \"\\n\".join(\n        (\n            \"\"\"{\"i\": [[\"[\\\\\"matmul_auto_scheduler_test\\\\\", 512, 512, 512]\", \"cuda\"], [[], [[\"CHW\", 2, \"local\"], [\"SP\", 2, 0, 512, [1, 16, 32, 1], 1], [\"SP\", 2, 5, 512, [4, 1, 1, 16], 1], [\"SP\", 2, 10, 512, [1, 2], 1], [\"RE\", 2, [0, 5, 1, 6, 2, 7, 10, 11, 3, 8, 12, 4, 9]], [\"FSP\", 3, 0, 1, 3], [\"FSP\", 3, 4, 2, 3], [\"RE\", 3, [0, 4, 1, 5, 2, 6, 3, 7]], [\"FU\", 2, [0, 1]], [\"FU\", 3, [0, 1]], [\"FU\", 2, [1, 2]], [\"FU\", 3, [1, 2]], [\"FU\", 2, [2, 3]], [\"FU\", 3, [2, 3]], [\"CA\", 2, 3, 2], [\"CHR\", 1, \"shared\", [2]], [\"CA\", 2, 3, 3], [\"FU\", 2, [0, 1]], [\"FFSP\", 2, 0, [1, 2], 1, 1], [\"AN\", 2, 1, 6], [\"CHR\", 0, \"shared\", [3]], [\"CA\", 1, 4, 3], [\"FU\", 1, [0, 1]], [\"FFSP\", 1, 0, [1, 2], 1, 1], [\"AN\", 1, 1, 6], [\"AN\", 5, 0, 5], [\"AN\", 5, 1, 4], [\"AN\", 5, 2, 6], [\"PR\", 4, 0, \"auto_unroll_max_step$1024\"]]]], \"r\": [[0.00536798], 0, 2.49277, 1585564852], \"v\": \"v0.1\"}\"\"\",\n        )\n    )\n\n    # load states\n    with tempfile.NamedTemporaryFile(mode=\"w\") as f:\n        f.write(json_records)\n        f.flush()\n        inputs, _ = auto_scheduler.RecordReader(f.name).read_lines()\n\n        inp = inputs[0]\n        task = auto_scheduler.SearchTask(\n            workload_key=inp.task.workload_key,\n            target=inp.task.target,\n            hardware_params=auto_scheduler.HardwareParams(\n                100000, 16, 64, 1 << 30, 1 << 30, 1 << 30, 1 << 30, 1 << 30\n            ),\n        )\n\n        state = task.compute_dag.infer_bound_from_state(inputs[0].state)\n        fea = auto_scheduler.feature.get_per_store_features_from_states([state], task)[0]\n        names = auto_scheduler.feature.get_per_store_feature_names()\n\n        # build feature dict\n        fea_dicts = []\n        for i in range(len(fea)):\n            tmp_dict = {}\n            for j in range(len(names)):\n                tmp_dict[names[j]] = fea[i][j]\n            fea_dicts.append(tmp_dict)\n\n        \"\"\"\n        lowered IR:\n\n        Placeholder: A, B\n        blockIdx.x i.0@j.0@ (0,8)\n          vthread i.1@j.1@ (0,4)\n            threadIdx.x i.2@j.2@ (0,16)\n              C.local auto_unroll: 1024\n              for k.0 (0,256)\n                for ax0@ax1@.0 (0,8)\n                  threadIdx.x ax0@ax1@.1 (0,16)\n                    B.shared = ...\n                for ax0@ax1@.0 (0,64)\n                  threadIdx.x ax0@ax1@.1 (0,16)\n                    A.shared = ...\n                for i_c.3 (0,32)\n                  for k.2 (0,2)\n                    for j_c.4 (0,16)\n                      C.local = ...\n              for i.3 (0,32)\n                for j.3 (0,16)\n                  C = ...\n        \"\"\"\n\n        # check gpu-related features\n        assert fequal(fea_dicts[0][\"blockIdx_x_len\"], math.log2(8 + 1))\n        assert fequal(fea_dicts[0][\"vthread_len\"], math.log2(4 + 1))\n        assert fequal(fea_dicts[1][\"threadIdx_x_len\"], math.log2(16 + 1))\n        assert fequal(fea_dicts[0][\"threadIdx_y_len\"], math.log2(1 + 1))\n        assert fequal(fea_dicts[2][\"blockIdx_z_len\"], math.log2(1 + 1))\n        assert fequal(fea_dicts[0][\"is_gpu\"], 1.0)\n\n\n@T.prim_func\ndef tir_matmul(\n    A: T.Buffer[(16384,), \"float32\"],\n    B: T.Buffer[(16384,), \"float32\"],\n    C: T.Buffer[(16384,), \"float32\"],\n) -> None:\n    # function attr dict\n    T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n    T.preflattened_buffer(A, [128, 128], dtype=\"float32\", data=A.data)\n    T.preflattened_buffer(B, [128, 128], dtype=\"float32\", data=B.data)\n    T.preflattened_buffer(C, [128, 128], dtype=\"float32\", data=C.data)\n    # body\n    for x, y in T.grid(128, 128):\n        C[x * 128 + y] = T.float32(0)\n        for k in T.serial(128):\n            C[x * 128 + y] = C[x * 128 + y] + A[x * 128 + k] * B[y * 128 + k]\n\n\ndef test_primfunc_without_lowering():\n    features = auto_scheduler.feature.named_features_from_primfunc(tir_matmul)\n    assert features[\"float_mad\"].shape == (1,)\n    # featurization does not handle multiple-add right now, so they are split out\n    assert abs(features[\"float_addsub\"][0] - 128 * 128 * 128) < 10\n    assert abs(features[\"float_mul\"][0] - 128 * 128 * 128) < 10\n    for i in range(0, 3):\n        assert abs(features[f\"B{i}.unique_bytes\"][0] - 128 * 128 * 4) < 10  # 4 bytes per float32\n\n\ndef test_primfunc_lowered():\n    # Lower tir function so all passes get applied\n    f = tvm.lower(tir_matmul)\n    features = auto_scheduler.feature.named_features_from_primfunc(f[\"main\"])\n    assert features[\"float_mad\"].shape == (1,)\n    # featurization does not handle multiple-add right now, so they are split out\n    assert abs(features[\"float_addsub\"][0] - 128 * 128 * 128) < 10\n    assert abs(features[\"float_mul\"][0] - 128 * 128 * 128) < 10\n    for i in range(0, 3):\n        assert abs(features[f\"B{i}.unique_bytes\"][0] - 128 * 128 * 4) < 10  # 4 bytes per float32\n\n\ndef test_dense_lowered():\n    a = relay.var(\"a\", relay.TensorType((128, 128), \"float32\"))\n    b = relay.var(\"b\", relay.TensorType((128, 128), \"float32\"))\n    c = relay.nn.dense(a, b)\n    mod = tvm.IRModule.from_expr(relay.Function([a, b], c))\n    target = \"llvm\"\n    comp = relay.vm.VMCompiler()\n    mod, params = comp.optimize(mod, params={}, target=target)\n    for name, func in mod.functions.items():\n        if name.name_hint != \"main\":\n            break\n    features = auto_scheduler.feature.named_features_from_primfunc(func)\n    # featurization does not handle multiple-add right now, so they are split out\n    assert features[\"float_addsub\"].sum() >= 128 * 128 * 128\n    assert features[\"float_mul\"].sum() >= 128 * 128 * 128\n    total_bytes_loaded = 0\n    for i in range(0, 4):\n        total_bytes_loaded += features[f\"B{i}.unique_bytes\"].sum()\n    assert total_bytes_loaded > 2 * 128 * 128 * 4  # 4 bytes per float32\n\n\n@T.prim_func\ndef negative_extent(A: T.Buffer[(1,), \"float32\"]):\n    for j in range(0, -1):\n        A[j] = A[j] + 1.0\n\n\ndef test_negative_extent():\n    features = auto_scheduler.feature.named_features_from_primfunc(negative_extent)\n    assert features[\"B0.unique_bytes\"] == 0\n\n\nif __name__ == \"__main__\":\n    test_cpu_matmul()\n    test_cpu_fusion()\n    test_gpu_feature()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_layout_rewrite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test AutoScheduler Layout Rewrite\"\"\"\nimport tempfile\nimport numpy as np\n\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import topi\nfrom tvm import auto_scheduler, te\n\nfrom tvm.testing.auto_scheduler import get_tiled_matmul, matmul_auto_scheduler_test\n\n\ndef test_apply_steps_with_layout_rewrite():\n    dag, s = get_tiled_matmul()\n    _, bufs = dag.apply_steps_from_state(s)\n    assert bufs[1].shape[0] == 512\n    assert bufs[1].shape[1] == 512\n    _, bufs = dag.apply_steps_from_state(\n        s, layout_rewrite=auto_scheduler.LayoutRewriteOption.REWRITE_FOR_PRE_TRANSFORMED\n    )\n    assert bufs[1].shape[0] == 4\n    assert bufs[1].shape[1] == 8\n    assert bufs[1].shape[2] == 4\n    assert bufs[1].shape[3] == 4\n    assert bufs[1].shape[4] == 512\n    _, bufs = dag.apply_steps_from_state(\n        s, layout_rewrite=auto_scheduler.LayoutRewriteOption.INSERT_TRANSFORM_STAGE\n    )\n    assert bufs[1].shape[0] == 512\n    assert bufs[1].shape[1] == 512\n\n\ndef test_apply_steps_with_layout_rewrite_corner_case():\n    A, B, C = matmul_auto_scheduler_test(1, 1, 1)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n\n    s = dag.get_init_state()\n\n    s.compute_root(C)\n    i_j_fused = s.fuse(C, [s[C].iters[0], s[C].iters[1]])\n    s.parallel(C, i_j_fused)\n\n    _, bufs = dag.apply_steps_from_state(\n        s, layout_rewrite=auto_scheduler.LayoutRewriteOption.REWRITE_FOR_PRE_TRANSFORMED\n    )\n\n\n@tvm.testing.requires_llvm\ndef test_correctness_layout_rewrite_rewrite_for_preTransformed():\n    N = 16\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(func=matmul_auto_scheduler_test, args=(N, N, N), target=target)\n    dag = task.compute_dag\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        search_policy = auto_scheduler.SketchPolicy(task)\n\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n        tuning_options = auto_scheduler.TuningOptions(\n            num_measure_trials=100,\n            runner=measure_ctx.runner,\n            verbose=2,\n            early_stopping=1,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        task.tune(tuning_options, search_policy=search_policy)\n        inp, _ = auto_scheduler.load_best_record(log_file, task.workload_key, target)\n        s, bufs = dag.apply_steps_from_state(\n            inp.state, layout_rewrite=auto_scheduler.LayoutRewriteOption.REWRITE_FOR_PRE_TRANSFORMED\n        )\n        s_ref, bufs_ref = dag.apply_steps_from_state(inp.state)\n        np_args = [np.random.randn(*topi.get_const_tuple(x.shape)).astype(x.dtype) for x in bufs]\n        np_args_ref = [np.array(x) for x in np_args]\n\n        weight = np_args_ref[1]\n        # infer shape for the rewritten layout\n        if len(weight.shape) >= 6:\n            # For cpu tile structure SSRSRS\n            base = len(weight.shape) - 6\n            red_dim = weight.shape[2 + base] * weight.shape[4 + base]\n            out_dim = weight.shape[3 + base] * weight.shape[5 + base]\n            for i in range(base + 2):\n                out_dim *= weight.shape[i]\n            new_order = (\n                [\n                    2 + base,\n                    4 + base,\n                ]\n                + list(range(base + 2))\n                + [\n                    3 + base,\n                    5 + base,\n                ]\n            )\n            np_args_ref[1] = np_args_ref[1].transpose(new_order)\n            np_args_ref[1] = np_args_ref[1].reshape((red_dim, out_dim))\n\n        func = tvm.build(s, bufs, target=target)\n        func_ref = tvm.build(s_ref, bufs_ref, target=target)\n\n        dev = tvm.device(str(target))\n        dev_ref = tvm.cpu()\n\n        args = [tvm.nd.array(x, device=dev) for x in np_args]\n        args_ref = [tvm.nd.array(x, device=dev_ref) for x in np_args_ref]\n        dev.sync()\n\n        func(*args)\n        func_ref(*args_ref)\n        dev.sync()\n\n        tvm.testing.assert_allclose(args[0].numpy(), args_ref[0].numpy(), atol=1e-3, rtol=1e-3)\n        tvm.testing.assert_allclose(args[2].numpy(), args_ref[2].numpy(), atol=1e-3, rtol=1e-3)\n        del measure_ctx\n\n\n@tvm.testing.requires_llvm\ndef test_correctness_layout_rewrite_insert_transform_stage():\n    N = 128\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(func=matmul_auto_scheduler_test, args=(N, N, N), target=target)\n    dag = task.compute_dag\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        search_policy = auto_scheduler.SketchPolicy(task)\n\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n        tuning_options = auto_scheduler.TuningOptions(\n            num_measure_trials=2,\n            runner=measure_ctx.runner,\n            verbose=1,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        task.tune(tuning_options, search_policy=search_policy)\n        inp, _ = auto_scheduler.load_best_record(log_file, task.workload_key, target)\n        s, bufs = dag.apply_steps_from_state(\n            inp.state, layout_rewrite=auto_scheduler.LayoutRewriteOption.INSERT_TRANSFORM_STAGE\n        )\n\n        s_ref, bufs_ref = dag.apply_steps_from_state(inp.state)\n        np_args = [np.random.randn(*topi.get_const_tuple(x.shape)).astype(x.dtype) for x in bufs]\n\n        func = tvm.build(s, bufs, target=target)\n        func_ref = tvm.build(s_ref, bufs_ref, target=target)\n\n        dev = tvm.device(str(target))\n        dev_ref = tvm.cpu()\n\n        args = [tvm.nd.array(x, device=dev) for x in np_args]\n        args_ref = [tvm.nd.array(x, device=dev_ref) for x in np_args]\n        dev.sync()\n\n        func(*args)\n        func_ref(*args_ref)\n        dev.sync()\n\n        tvm.testing.assert_allclose(args[0].numpy(), args_ref[0].numpy(), atol=1e-3, rtol=1e-3)\n        tvm.testing.assert_allclose(args[1].numpy(), args_ref[1].numpy(), atol=1e-3, rtol=1e-3)\n        tvm.testing.assert_allclose(args[2].numpy(), args_ref[2].numpy(), atol=1e-3, rtol=1e-3)\n        del measure_ctx\n\n\nif __name__ == \"__main__\":\n    test_apply_steps_with_layout_rewrite()\n    test_apply_steps_with_layout_rewrite_corner_case()\n    test_correctness_layout_rewrite_rewrite_for_preTransformed()\n    test_correctness_layout_rewrite_insert_transform_stage()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_loop_state.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test loop state and schedule primitives\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import auto_scheduler, te\nfrom tvm import topi\n\nfrom tvm.testing.auto_scheduler import (\n    matmul_auto_scheduler_test,\n    conv2d_nchw_bn_relu_auto_scheduler_test,\n)\n\n\ndef test_split_fuse_reorder_annotation():\n    A, B, C = matmul_auto_scheduler_test(N=512, M=512, K=512)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s0 = dag.get_init_state()\n    i, j, k = s0[C].iters\n\n    assert i.range.extent == 512\n\n    io, ii = s0.split(C, i, [16])\n    assert s0[C].iters[0] == io\n    assert s0[C].iters[1] == ii\n    assert io.range.extent == 32\n    assert ii.range.extent == 16\n\n    jo, ji = s0.split(C, j, [8])\n    assert jo.range.extent == 64\n    assert ji.range.extent == 8\n\n    s0.reorder(C, [io, jo, k, ji, ii])\n    assert s0[C].iters[2].range.extent == 512\n\n    fused_it = s0.fuse(C, [io, jo])\n    assert fused_it.range.extent == 2048\n\n    s1 = dag.get_init_state()\n    i, j, _ = s1[C].iters\n    i1, i2, i3 = s1.split(C, i, [8, 2])\n    j1, j2, j3 = s1.split(C, j, [32, 8], False)\n    assert s1[C].iters[0].range.extent == 32\n    assert s1[C].iters[1].range.extent == 8\n    assert s1[C].iters[2].range.extent == 2\n    assert s1[C].iters[3].range.extent == 32\n    assert s1[C].iters[4].range.extent == 8\n    assert s1[C].iters[5].range.extent == 2\n\n    res = s1.bind(C, i1, \"blockIdx.x\")\n    assert res == s1[C].iters[0]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"blockIdx.x\"]\n\n    res = s1.bind(C, i2, \"vthread\")\n    assert res == s1[C].iters[1]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"vthread\"]\n\n    res = s1.bind(C, i3, \"threadIdx.y\")\n    assert res == s1[C].iters[2]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"threadIdx.y\"]\n\n    res = s1.parallel(C, j1)\n    assert res == s1[C].iters[3]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"parallel\"]\n\n    res = s1.unroll(C, j2)\n    assert res == s1[C].iters[4]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"unroll\"]\n\n    res = s1.vectorize(C, j3)\n    assert res == s1[C].iters[5]\n    assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE[\"vectorize\"]\n\n\ndef test_compute_at_root_inline():\n    dag = auto_scheduler.ComputeDAG(\n        conv2d_nchw_bn_relu_auto_scheduler_test(\n            N=1, H=224, W=224, CI=3, CO=64, kernel_size=7, strides=2, padding=3\n        )\n    )\n    s0 = dag.get_init_state()\n\n    # data, padding, kernel = 0, 1, 2\n    conv = s0.stage_ops[3]\n    # bias = 4\n    bias_add = s0.stage_ops[5]\n    # bn_scale = 6\n    bn_mul = s0.stage_ops[7]\n    # bn_offset = 8\n    bn_add = s0.stage_ops[9]\n    relu = s0.stage_ops[10]\n\n    s0.compute_inline(bn_add)\n    assert s0[bn_add].compute_at == 1\n\n    s0.compute_inline(bn_mul)\n    assert s0[bn_mul].compute_at == 1\n\n    s0.compute_inline(bias_add)\n    assert s0[bias_add].compute_at == 1\n\n    assert s0[conv].iters[0].range.extent == 1\n    assert s0[conv].iters[1].range.extent == 64\n    assert s0[conv].iters[2].range.extent == 112\n    assert s0[conv].iters[3].range.extent == 112\n    assert s0[conv].iters[4].range.extent == 3\n    assert s0[conv].iters[5].range.extent == 7\n    assert s0[conv].iters[6].range.extent == 7\n    s0.compute_at(conv, relu, s0[relu].iters[2])\n    assert s0[conv].compute_at == 2\n    s0 = dag.infer_bound_from_state(s0)\n    assert s0[conv].iters[0].range.extent == 1\n    assert s0[conv].iters[1].range.extent == 1\n    assert s0[conv].iters[2].range.extent == 1\n    assert s0[conv].iters[3].range.extent == 112\n    assert s0[conv].iters[4].range.extent == 3\n    assert s0[conv].iters[5].range.extent == 7\n    assert s0[conv].iters[6].range.extent == 7\n\n    s0.compute_root(bn_mul)\n    assert s0[bn_mul].compute_at == 0\n\n    s0.compute_root(conv)\n    assert s0[conv].compute_at == 0\n    s0 = dag.infer_bound_from_state(s0)\n    assert s0[conv].iters[0].range.extent == 1\n    assert s0[conv].iters[1].range.extent == 64\n    assert s0[conv].iters[2].range.extent == 112\n    assert s0[conv].iters[3].range.extent == 112\n    assert s0[conv].iters[4].range.extent == 3\n    assert s0[conv].iters[5].range.extent == 7\n    assert s0[conv].iters[6].range.extent == 7\n\n\ndef test_cache_read_write():\n    N, H, W, CO, CI, KH, KW, strides, padding = 4, 7, 7, 512, 512, 3, 3, (1, 1), (1, 1)\n\n    data = te.placeholder((N, CI, H, W), name=\"Data\")\n    kernel_data = te.placeholder((CO, CI, KH, KW), name=\"Kernel_data\")\n    k0, k1 = te.compute(\n        kernel_data.shape,\n        lambda *i: (kernel_data(*i) + 1, kernel_data(*i) / 2),\n        name=\"Kernel_split\",\n    )\n    kernel = te.compute(kernel_data.shape, lambda *i: k0(*i) + k1(*i), name=\"Kernel\")\n    conv = topi.nn.conv2d_nchw(data, kernel, strides, padding, dilation=1)\n    relu = topi.nn.relu(conv)\n    add = topi.add(data, relu)\n\n    dag = auto_scheduler.ComputeDAG([data, kernel_data, add])\n    s0 = dag.get_init_state()\n\n    pad_temp = s0.stage_ops[1]\n    kernel_split = s0.stage_ops[3]\n\n    # 0: init state\n    ori_its = s0[add].iters\n    its = s0.split(add, s0[add].iters[0], [2])\n    s0.reorder(add, [its[0], ori_its[1], its[1], ori_its[2], ori_its[3]])\n    s0.compute_inline(relu)\n\n    # 1: simple cache_write with compute_at\n    conv_global = s0.cache_write(conv, \"global\")\n    s0.compute_at(conv_global, conv, s0[conv].iters[3])\n\n    # 2: simple cache_read with compute_at\n    kernel_global = s0.cache_read(kernel, \"global\", [conv_global])\n    s0.compute_at(kernel_global, conv_global, s0[conv_global].iters[4])\n    \"\"\"\n        Placeholder: Data, Kernel_data\n        for i0 (0,4)\n          for i1 (0,512)\n            for i2 (0,9)\n              for i3 (0,9)\n                pad_temp = ...\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel_split = ...\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel = ...\n        for nn (0,4)\n          for ff (0,512)\n            for yy (0,7)\n              for xx (0,7)\n                for nn_c (None)\n                  for ff_c (None)\n                    for yy_c (None)\n                      for xx_c (None)\n                        for rc (None)\n                          for ax0 (None)\n                            for ax1 (None)\n                              for ax2 (None)\n                                for ax3 (None)\n                                  Kernel.global = ...\n                          for ry (None)\n                            for rx (None)\n                              compute.global = ...\n                compute = ...\n        for ax0.0 (0,2)\n          for ax1 (0,512)\n            for ax0.1 (0,2)\n              for ax2 (0,7)\n                for ax3 (0,7)\n                  T_add = ...\n    \"\"\"\n    s1 = dag.infer_bound_from_state(s0)\n    assert s1[conv].iters[0].range.extent == 4\n    assert s1[conv].iters[1].range.extent == 512\n    assert s1[conv].iters[2].range.extent == 7\n    assert s1[conv].iters[3].range.extent == 7\n    assert s1[kernel_global].iters[0].range.extent == 1\n    assert s1[kernel_global].iters[1].range.extent == 1\n    assert s1[kernel_global].iters[2].range.extent == 3\n    assert s1[kernel_global].iters[3].range.extent == 3\n    assert s1[conv_global].iters[0].range.extent == 1\n    assert s1[conv_global].iters[1].range.extent == 1\n    assert s1[conv_global].iters[2].range.extent == 1\n    assert s1[conv_global].iters[3].range.extent == 1\n    assert s1[conv_global].iters[4].range.extent == 512\n    assert s1[conv_global].iters[5].range.extent == 3\n    assert s1[conv_global].iters[6].range.extent == 3\n\n    # 3: two level cache_read with compute_at\n    #    preparing for GPU's shared memory & local memory\n    pad_temp_global = s0.cache_read(pad_temp, \"global\", [conv_global])\n    pad_temp_shared = s0.cache_read(pad_temp_global, \"shared\", [conv_global])\n    s0.compute_at(pad_temp_global, conv_global, s0[conv_global].iters[2])\n    s0.compute_at(pad_temp_shared, conv_global, s0[conv_global].iters[4])\n\n    # 4: cache_read with multi readers\n    #    This stage cannot be compute at to its consumer\n    s0.cache_read(data, \"global\", [pad_temp, add])\n    \"\"\"\n        Placeholder: Data, Kernel_data\n        for ax0 (0,4)\n          for ax1 (0,512)\n            for ax2 (0,7)\n              for ax3 (0,7)\n                Data.global = ...\n        for i0 (0,4)\n          for i1 (0,512)\n            for i2 (0,9)\n              for i3 (0,9)\n                pad_temp = ...\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel_split = ...\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel = ...\n        for nn (0,4)\n          for ff (0,512)\n            for yy (0,7)\n              for xx (0,7)\n                for nn_c (None)\n                  for ff_c (None)\n                    for yy_c (None)\n                      for ax0 (None)\n                        for ax1 (None)\n                          for ax2 (None)\n                            for ax3 (None)\n                              pad_temp.global = ...\n                      for xx_c (None)\n                        for rc (None)\n                          for ax0 (None)\n                            for ax1 (None)\n                              for ax2 (None)\n                                for ax3 (None)\n                                  Kernel.global = ...\n                          for ax0 (None)\n                            for ax1 (None)\n                              for ax2 (None)\n                                for ax3 (None)\n                                  pad_temp.global.shared = ...\n                          for ry (None)\n                            for rx (None)\n                              compute.global = ...\n                compute = ...\n        for ax0.0 (0,2)\n          for ax1 (0,512)\n            for ax0.1 (0,2)\n              for ax2 (0,7)\n                for ax3 (0,7)\n                  T_add = ...\n    \"\"\"\n    s1 = dag.infer_bound_from_state(s0)\n    assert s1[conv].iters[0].range.extent == 4\n    assert s1[conv].iters[1].range.extent == 512\n    assert s1[conv].iters[2].range.extent == 7\n    assert s1[conv].iters[3].range.extent == 7\n    assert s1[kernel_global].iters[0].range.extent == 1\n    assert s1[kernel_global].iters[1].range.extent == 1\n    assert s1[kernel_global].iters[2].range.extent == 3\n    assert s1[kernel_global].iters[3].range.extent == 3\n    assert s1[conv_global].iters[0].range.extent == 1\n    assert s1[conv_global].iters[1].range.extent == 1\n    assert s1[conv_global].iters[2].range.extent == 1\n    assert s1[conv_global].iters[3].range.extent == 1\n    assert s1[conv_global].iters[4].range.extent == 512\n    assert s1[conv_global].iters[5].range.extent == 3\n    assert s1[conv_global].iters[6].range.extent == 3\n    assert s1[pad_temp_global].iters[0].range.extent == 1\n    assert s1[pad_temp_global].iters[1].range.extent == 512\n    assert s1[pad_temp_global].iters[2].range.extent == 3\n    assert s1[pad_temp_global].iters[3].range.extent == 3\n    assert s1[pad_temp_shared].iters[0].range.extent == 1\n    assert s1[pad_temp_shared].iters[1].range.extent == 1\n    assert s1[pad_temp_shared].iters[2].range.extent == 3\n    assert s1[pad_temp_shared].iters[3].range.extent == 3\n\n    # 5: cache_write with multi outputs\n    # TVM's cache_write actually has a bug with this case:\n    #\n    # After schedule.cache_write, TVM generate one new stage:\n    #   From: kernel_data -> kernel_split -> kernel\n    #   To:   kernel_data -> kernel_split_global -> kernel_split -> kernel\n    #\n    # But with topo sort analyse, we get:\n    #  //   kernel_data -> kernel_split_global -> kernel_split -> kernel\n    #         \\                                                /\n    #          ----------------> kernel_split ---------------->\n    #\n    # TODO(jcf94): Seems there's bug with the input/output tensor. Such multi outputs case\n    # should be unusual, so we make some hack on DoCacheWrite. This should be fixed later.\n    kernel_split_global = s0.cache_write(kernel_split, \"global\")\n    \"\"\"\n        Placeholder: Data, Kernel_data\n        for ax0 (0,4)\n          for ax1 (0,512)\n            for ax2 (0,7)\n              for ax3 (0,7)\n                Data.global = ...\n        for i0 (0,4)\n          for i1 (0,512)\n            for i2 (0,9)\n              for i3 (0,9)\n                pad_temp = ...\n        for i0_c (0,512)\n          for i1_c (0,512)\n            for i2_c (0,3)\n              for i3_c (0,3)\n                Kernel_split.global = ...\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel_split = ...\n        (******* Bug here, there should not be two kernel_split stage *******)\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel_split = ...\n        (******* Bug here, there should not be two kernel_split stage *******)\n        for i0 (0,512)\n          for i1 (0,512)\n            for i2 (0,3)\n              for i3 (0,3)\n                Kernel = ...\n        for nn (0,4)\n          for ff (0,512)\n            for yy (0,7)\n              for xx (0,7)\n                for nn_c (None)\n                  for ff_c (None)\n                    for yy_c (None)\n                      for ax0 (None)\n                        for ax1 (None)\n                          for ax2 (None)\n                            for ax3 (None)\n                              pad_temp.global = ...\n                      for xx_c (None)\n                        for rc (None)\n                          for ax0 (None)\n                            for ax1 (None)\n                              for ax2 (None)\n                                for ax3 (None)\n                                  Kernel.global = ...\n                          for ax0 (None)\n                            for ax1 (None)\n                              for ax2 (None)\n                                for ax3 (None)\n                                  pad_temp.global.shared = ...\n                          for ry (None)\n                            for rx (None)\n                              compute.global = ...\n                compute = ...\n        for ax0.0 (0,2)\n          for ax1 (0,512)\n            for ax0.1 (0,2)\n              for ax2 (0,7)\n                for ax3 (0,7)\n                  T_add = ...\n    \"\"\"\n    assert len(s0[kernel_split].iters) == len(s0[kernel_split_global].iters)\n    for it0, it1 in zip(s0[kernel_split].iters, s0[kernel_split_global].iters):\n        assert it0.range == it1.range\n\n\ndef test_follow_split_follow_fused_split():\n    A, B, C = matmul_auto_scheduler_test(512, 512, 512)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s0 = dag.get_init_state()\n\n    C_global = s0.cache_write(C, \"global\")\n    its0 = s0.split(C, s0[C].iters[0], [4, 2, 8, 4], True)\n    split_step0 = len(s0.transform_steps) - 1\n    for level in range(1, 6):\n        tmp = s0.copy()\n        tmp.follow_split(C_global, tmp[C_global].iters[0], split_step0, level)\n        for i in range(0, level):\n            assert tmp[C].iters[i].range.extent == tmp[C_global].iters[i].range.extent\n\n    its1 = s0.split(C, s0[C].iters[5], [2, 2, 4, 8])\n    split_step1 = len(s0.transform_steps) - 1\n    its = []\n    for i0, i1 in zip(its0, its1):\n        its.append(i0)\n        its.append(i1)\n    s0.reorder(C, its)\n    for i in range(0, 5):\n        s0.fuse(C, [s0[C].iters[i], s0[C].iters[i + 1]])\n\n    for level in range(0, 4):\n        tmp = s0.copy()\n        tmp.follow_fused_split(\n            C_global, tmp[C_global].iters[0], [split_step0, split_step1], level, False\n        )\n        assert tmp[C].iters[level + 1].range.extent == tmp[C_global].iters[0].range.extent\n\n    for level in range(0, 4):\n        tmp = s0.copy()\n        tmp.follow_fused_split(\n            C_global, tmp[C_global].iters[0], [split_step0, split_step1], level, True\n        )\n        assert tmp[C].iters[level + 1].range.extent == tmp[C_global].iters[1].range.extent\n\n\ndef test_rfactor():\n    A, B, C = matmul_auto_scheduler_test(8, 8, 512)\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s0 = dag.get_init_state()\n\n    ko, ki = s0.split(C, s0[C].iters[2], [16])\n\n    s1 = s0.copy()\n    C_r = s1.rfactor(C, ko, 2)\n    \"\"\"\n        Placeholder: A, B\n        for i (0,8)\n          for j (0,8)\n            for k_o (0,32)\n              for k_i (0,16)\n                C.rf = ...\n        for ax0 (0,8)\n          for ax1 (0,8)\n            for k_o_v (0,32)\n              C.repl = ...\n    \"\"\"\n    assert s1[C_r].iters[0].range.extent == 8\n    assert s1[C_r].iters[1].range.extent == 8\n    assert s1[C_r].iters[2].range.extent == 32\n    assert s1[C_r].iters[3].range.extent == 16\n    assert s1[C].iters[0].range.extent == 8\n    assert s1[C].iters[1].range.extent == 8\n    assert s1[C].iters[2].range.extent == 32\n\n    s2 = s0.copy()\n    C_r = s2.rfactor(C, ki, 2)\n    \"\"\"\n        Placeholder: A, B\n        for i (0,8)\n          for j (0,8)\n            for k_i (0,16)\n              for k_o (0,32)\n                C.rf = ...\n        for ax0 (0,8)\n          for ax1 (0,8)\n            for k_i_v (0,16)\n              C.repl = ...\n    \"\"\"\n    assert s2[C_r].iters[0].range.extent == 8\n    assert s2[C_r].iters[1].range.extent == 8\n    assert s2[C_r].iters[2].range.extent == 16\n    assert s2[C_r].iters[3].range.extent == 32\n    assert s2[C].iters[0].range.extent == 8\n    assert s2[C].iters[1].range.extent == 8\n    assert s2[C].iters[2].range.extent == 16\n\n\nif __name__ == \"__main__\":\n    test_split_fuse_reorder_annotation()\n    test_compute_at_root_inline()\n    test_cache_read_write()\n    test_follow_split_follow_fused_split()\n    test_rfactor()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_measure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test measurement and log serialization. \"\"\"\nimport json\n\nimport multiprocessing\nimport numpy as np\nimport tvm\nfrom tvm import topi\nfrom tvm import te, auto_scheduler\nimport tempfile\nimport tvm.testing\nimport pickle\nfrom tvm.testing.auto_scheduler import matmul_auto_scheduler_test\nfrom tvm.auto_scheduler import workload_registry\n\n\ndef record_common(dag, s):\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(compute_dag=dag, workload_key=\"test\", target=target)\n\n    inp = auto_scheduler.measure.MeasureInput(task, s)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n\n    # Test in-memory record processing.\n    record_str = auto_scheduler.measure_record.dump_record_to_string(inp, res)\n    r_inp, r_res = auto_scheduler.measure_record.load_record_from_string(record_str)\n    # Only check the workload_key for simplification.\n    assert inp.task.workload_key == r_inp.task.workload_key\n    assert str(res) == str(r_res)\n\n    # Test file-based record processing.\n    with tempfile.NamedTemporaryFile() as fp:\n        auto_scheduler.save_records(fp.name, [inp], [res])\n\n        log_reader = auto_scheduler.RecordReader(fp.name)\n        inputs, _ = log_reader.read_lines()\n        assert len(inputs) == 1\n\n        s1 = dag.infer_bound_from_state(s)\n        s2 = dag.infer_bound_from_state(inputs[0].state)\n\n        assert s1 == s2\n        assert not (s1 == dag.get_init_state())\n\n\ndef test_record_split_reorder_fuse_annotation():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    A = te.placeholder((512, 512), name=\"A\")\n    B = te.placeholder((512, 512), name=\"B\")\n    k = te.reduce_axis((0, 512), name=\"k\")\n    C = te.compute((512, 512), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s = dag.get_init_state()\n\n    # Split\n    its0 = s.split(C, s[C].iters[0], [4, 8, 8])\n    its1 = s.split(C, s[C].iters[4], [8, 4, 4])\n    # Reorder\n    s.reorder(\n        C, [its0[0], its1[0], its0[1], its1[1], its0[2], its1[2], its0[3], s[C].iters[8], its1[3]]\n    )\n    # Fuse\n    s.fuse(C, [s[C].iters[0], s[C].iters[1], s[C].iters[2]])\n    # Parallel\n    s.parallel(C, s[C].iters[0])\n    # Thread bind(The blockIdx & threadIdx are used in GPU, just for record testing here)\n    s.bind(C, s[C].iters[1], \"blockIdx.x\")\n    s.bind(C, s[C].iters[2], \"threadIdx.z\")\n    s.bind(C, s[C].iters[3], \"vthread\")\n    # Unroll\n    s.unroll(C, s[C].iters[4])\n    # Vectorize\n    s.vectorize(C, s[C].iters[6])\n\n    record_common(dag, s)\n\n\ndef test_record_compute_at_root_inline_cache_read_write():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    A = te.placeholder((512, 512), name=\"A\")\n    AA = topi.nn.relu(A)\n    B = te.placeholder((512, 512), name=\"B\")\n    k = te.reduce_axis((0, 512), name=\"k\")\n    C = te.compute((512, 512), lambda i, j: te.sum(AA[i][k] * B[k][j], axis=[k]), name=\"C\")\n\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s = dag.get_init_state()\n\n    # Cache Write\n    C_shared = s.cache_write(C, \"shared\")\n    # Compute At\n    s.compute_at(C_shared, C, s[C].iters[0])\n    # Cache Read\n    B_global = s.cache_read(B, \"global\", [C_shared])\n    s.compute_at(B_global, C_shared, s[C_shared].iters[2])\n    # Compute Inline\n    s.compute_inline(AA)\n    # Compute Root\n    s.compute_root(C_shared)\n\n    record_common(dag, s)\n\n\ndef test_record_follow_split_follow_fused_split():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    A = te.placeholder((512, 512), name=\"A\")\n    B = te.placeholder((512, 512), name=\"B\")\n    k = te.reduce_axis((0, 512), name=\"k\")\n    C = te.compute((512, 512), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n    D = topi.nn.relu(C)\n    E = topi.nn.relu(D)\n\n    dag = auto_scheduler.ComputeDAG([A, B, E])\n    s = dag.get_init_state()\n\n    # Follow Split\n    s.split(C, s[C].iters[0], [4, 2, 8, 4], True)\n    split_step0 = len(s.transform_steps) - 1\n    s.follow_split(C, s[C].iters[5], split_step0, 4)\n    # Follow Fused Split\n    its0 = s.split(E, s[E].iters[0], [4, 2, 8, 4], True)\n    split_step1 = len(s.transform_steps) - 1\n    its1 = s.split(E, s[E].iters[5], [2, 4, 2, 4], True)\n    split_step2 = len(s.transform_steps) - 1\n    its = []\n    for i0, i1 in zip(its0, its1):\n        its.append(i0)\n        its.append(i1)\n    for i in range(0, 5):\n        s.fuse(E, [s[E].iters[i], s[E].iters[i + 1]])\n    s.follow_fused_split(D, s[D].iters[0], [split_step1, split_step2], 2, True)\n\n    record_common(dag, s)\n\n\ndef test_record_pragma_storage_align_rfactor():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    A = te.placeholder((512, 512), name=\"A\")\n    B = te.placeholder((512, 512), name=\"B\")\n    k = te.reduce_axis((0, 512), name=\"k\")\n    C = te.compute((512, 512), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n\n    dag = auto_scheduler.ComputeDAG([A, B, C])\n    s = dag.get_init_state()\n\n    # Rfactor\n    ko, _ = s.split(C, s[C].iters[2], [16])\n    s.rfactor(C, ko, 2)\n    # Pragma\n    s.pragma(C, s[C].iters[0], \"auto_unroll_max_step$64\")\n    # StorageAlign\n    s.storage_align(C, s[C].iters[-1], 8, 4)\n\n    record_common(dag, s)\n\n\ndef test_recover_measure_input():\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(512, 512, 512), target=\"llvm\"\n    )\n\n    inp = auto_scheduler.measure.MeasureInput(task, task.compute_dag.init_state)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n\n    with tempfile.NamedTemporaryFile() as fp:\n        auto_scheduler.save_records(fp.name, [inp], [res])\n\n        log_reader = auto_scheduler.RecordReader(fp.name)\n        inputs, _ = log_reader.read_lines()\n        assert len(inputs) == 1\n\n        raw_inp = inputs[0]\n\n        correct_inp = auto_scheduler.measure.recover_measure_input(raw_inp)\n        assert str(correct_inp.task.compute_dag) == str(inp.task.compute_dag)\n\n        correct_inp = auto_scheduler.measure.recover_measure_input(raw_inp, rebuild_state=True)\n        assert str(correct_inp.state) == str(inp.state)\n\n\ndef test_workload_dis_factor():\n    calc = auto_scheduler.utils.calc_workload_dis_factor\n    decode = auto_scheduler.utils.decode_workload_key\n\n    # Identical\n    target_wkl_key = json.dumps(\n        [\"func1\", [8, 3, 224, 224], [32, 3, 3, 3], [0, 0], [1, 1], \"float32\"]\n    )\n    assert calc(decode(target_wkl_key), decode(target_wkl_key)) == 1\n\n    # Compatible with a factor\n    wkl_key = json.dumps([\"func1\", [1, 3, 112, 112], [32, 3, 3, 3], [0, 0], [1, 1], \"float32\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == 8 * 2 * 2\n\n    # Incompatible argument with zeros\n    wkl_key = json.dumps([\"func1\", [8, 3, 224, 224], [32, 3, 3, 3], [1, 1], [1, 1], \"float32\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == float(\"inf\")\n    wkl_key = json.dumps([\"func1\", [8, 3, 224, 224], [32, 3, 3, 3], [0, 0], [0, 0], \"float32\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == float(\"inf\")\n\n    # Incompatible non-integter argument\n    wkl_key = json.dumps([\"func1\", [8, 3, 224, 224], [32, 3, 3, 3], [0, 0], [1, 1], \"int8\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == float(\"inf\")\n\n    # Incompatible function\n    wkl_key = json.dumps([\"func2\", [8, 3, 224, 224], [32, 3, 3, 3], [0, 0], [1, 1], \"float32\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == float(\"inf\")\n\n    # Incompatible due to non-dividable factor\n    wkl_key = json.dumps([\"func1\", [8, 3, 223, 223], [32, 3, 3, 3], [0, 0], [1, 1], \"float32\"])\n    assert calc(decode(target_wkl_key), decode(wkl_key)) == float(\"inf\")\n\n\ndef test_measure_local_builder_runner():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(512, 512, 512), target=\"llvm\"\n    )\n\n    for enable_cpu_cache_flush in [True, False]:\n        minp = auto_scheduler.MeasureInput(task, task.compute_dag.init_state)\n        local_builder = auto_scheduler.LocalBuilder()\n        local_runner = auto_scheduler.LocalRunner(\n            timeout=60, enable_cpu_cache_flush=enable_cpu_cache_flush\n        )\n\n        bress = local_builder.build([minp])\n        assert bress[0].error_no == 0\n        mress = local_runner.run([minp], bress)\n        assert mress[0].error_no == 0\n\n\ndef test_dag_measure_local_builder_runner():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    A = te.placeholder((512, 512), name=\"A\")\n    B = te.placeholder((512, 512), name=\"B\")\n    k = te.reduce_axis((0, 512), name=\"k\")\n    C = te.compute((512, 512), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n    D = topi.nn.relu(C)\n    E = topi.nn.relu(D)\n\n    tensors = [A, B, E]\n    dag = auto_scheduler.ComputeDAG(tensors)\n    key = workload_registry.register_workload_tensors(dag.workload_key(), tensors)\n    transfer_data = workload_registry.serialize_workload_registry_entry(key)\n    f_data = pickle.dumps(transfer_data)\n    f_new = pickle.loads(f_data)\n    del workload_registry.WORKLOAD_FUNC_REGISTRY[key]\n    workload_registry.deserialize_workload_registry_entry(f_new)\n\n    target = tvm.target.Target(\"llvm\")\n    task = auto_scheduler.SearchTask(compute_dag=dag, workload_key=key, target=target)\n\n    for enable_cpu_cache_flush in [True, False]:\n        minp = auto_scheduler.MeasureInput(task, task.compute_dag.init_state)\n        local_builder = auto_scheduler.LocalBuilder()\n        local_runner = auto_scheduler.LocalRunner(\n            timeout=60, enable_cpu_cache_flush=enable_cpu_cache_flush\n        )\n\n        bress = local_builder.build([minp])\n        assert bress[0].error_no == 0\n        mress = local_runner.run([minp], bress)\n        assert mress[0].error_no == 0\n\n\ndef test_workload_serialization():\n    key = tvm.auto_scheduler.utils.get_func_name(matmul_auto_scheduler_test)\n    transfer_data = workload_registry.serialize_workload_registry_entry(key)\n    f_data = pickle.dumps(transfer_data)\n    f_new = pickle.loads(f_data)\n    del workload_registry.WORKLOAD_FUNC_REGISTRY[key]\n    workload_registry.deserialize_workload_registry_entry(f_new)\n\n\ndef test_measure_local_builder_rpc_runner():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(512, 512, 512), target=\"llvm\"\n    )\n\n    for enable_cpu_cache_flush in [True, False]:\n        minp = auto_scheduler.MeasureInput(task, task.compute_dag.init_state)\n        local_builder = auto_scheduler.LocalBuilder()\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext(\n            timeout=60, enable_cpu_cache_flush=enable_cpu_cache_flush\n        )\n        rpc_runner = measure_ctx.runner\n\n        bress = local_builder.build([minp])\n        assert bress[0].error_no == 0\n        mress = rpc_runner.run([minp], bress)\n        assert mress[0].error_no == 0\n\n        del measure_ctx\n\n\ndef measure_local_builder_rpc_runner_spawn():\n    assert multiprocessing.get_start_method(False) == \"spawn\"\n    test_measure_local_builder_rpc_runner()\n\n\n@tvm.testing.requires_llvm\ndef test_measure_local_builder_rpc_runner_spawn():\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=measure_local_builder_rpc_runner_spawn)\n    p.start()\n    p.join()\n\n\n@tvm.testing.requires_llvm\ndef test_measure_target_host():\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test,\n        args=(512, 512, 512),\n        target=tvm.target.Target(\"llvm\", \"llvm -mtriple=aarch64-linux-gnu\"),\n    )\n\n    inp = auto_scheduler.measure.MeasureInput(task, task.compute_dag.init_state)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n\n    with tempfile.NamedTemporaryFile() as fp:\n        auto_scheduler.save_records(fp.name, [inp], [res])\n\n        log_reader = auto_scheduler.RecordReader(fp.name)\n        inputs, _ = log_reader.read_lines()\n        assert len(inputs) == 1\n\n        raw_inp = inputs[0]\n\n        recovered_inp = auto_scheduler.measure.recover_measure_input(raw_inp)\n        assert str(recovered_inp.task.target.host) == str(inp.task.target.host)\n\n\n@tvm.testing.requires_llvm\ndef test_measure_special_inputs_map_by_name_local_runner():\n    @auto_scheduler.register_workload\n    def foo():\n        X = te.placeholder(shape=[10], dtype=\"int32\")\n        Index = te.placeholder(shape=[1], dtype=\"int32\", name=\"Index\")\n        Y = te.compute((1,), lambda i: X[Index[i]])\n        return [X, Index, Y]\n\n    # This workload cannot use random input for the `Index` input\n    task = auto_scheduler.SearchTask(\n        func=foo,\n        target=\"llvm\",\n        task_inputs={\n            \"Index\": tvm.nd.array(np.array([5], dtype=\"int32\")),\n        },\n    )\n\n    minp = auto_scheduler.MeasureInput(task, task.compute_dag.init_state)\n    local_builder = auto_scheduler.LocalBuilder()\n    local_runner = auto_scheduler.LocalRunner(timeout=10)\n\n    bress = local_builder.build([minp])\n    assert bress[0].error_no == 0\n    mress = local_runner.run([minp], bress)\n    assert mress[0].error_no == 0\n\n\n@tvm.testing.requires_llvm\ndef test_measure_special_inputs_map_by_name_rpc_runner():\n    @auto_scheduler.register_workload\n    def foo():\n        X = te.placeholder(shape=[10], dtype=\"int32\")\n        Index = te.placeholder(shape=[1], dtype=\"int32\", name=\"Index\")\n        Y = te.compute((1,), lambda i: X[Index[i]])\n        return [X, Index, Y]\n\n    # This workload cannot use random input for the `Index` input\n    task = auto_scheduler.SearchTask(\n        func=foo,\n        target=\"llvm\",\n        task_inputs={\n            \"Index\": tvm.nd.array(np.array([5], dtype=\"int32\")),\n        },\n    )\n\n    for enable_cpu_cache_flush in [True, False]:\n        minp = auto_scheduler.MeasureInput(task, task.compute_dag.init_state)\n        local_builder = auto_scheduler.LocalBuilder()\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext(\n            timeout=60, enable_cpu_cache_flush=enable_cpu_cache_flush\n        )\n        rpc_runner = measure_ctx.runner\n\n        bress = local_builder.build([minp])\n        assert bress[0].error_no == 0\n        mress = rpc_runner.run([minp], bress)\n        assert mress[0].error_no == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_search_policy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test search policy\"\"\"\n\nimport random\nimport multiprocessing\nimport numpy as np\nimport tempfile\n\nimport tvm\nimport tvm.testing\nfrom tvm import auto_scheduler\nfrom tvm.auto_scheduler.utils import get_const_tuple\n\nfrom tvm.testing.auto_scheduler import (\n    matmul_auto_scheduler_test,\n    zero_rank_compute_auto_scheduler_test,\n    zero_rank_reduce_auto_scheduler_test,\n)\nimport multiprocessing\n\n\nclass CustomMeasureCallback(auto_scheduler.measure.PythonBasedMeasureCallback):\n    \"\"\"A simple Python-based callback for testing.\"\"\"\n\n    def callback(self, policy, inputs, results):\n        assert isinstance(policy, auto_scheduler.search_policy.SearchPolicy)\n        for inp, res in zip(inputs, results):\n            assert isinstance(inp, auto_scheduler.MeasureInput)\n            assert isinstance(res, auto_scheduler.MeasureResult)\n\n\ndef search_common(\n    task=None,\n    target=\"llvm\",\n    search_policy=\"sketch\",\n    runner=\"local\",\n    num_measure_trials=100,\n    cost_model=auto_scheduler.RandomModel(),\n    init_search_callbacks=None,\n):\n    if task is None:\n        task = auto_scheduler.SearchTask(\n            func=matmul_auto_scheduler_test, args=(64, 64, 64), target=target\n        )\n    target = task.target\n\n    print(\"Test search policy '%s' for '%s'\" % (search_policy, target))\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        init_search_callbacks = init_search_callbacks or []\n        init_search_callbacks.append(auto_scheduler.PreloadMeasuredStates(log_file))\n\n        if search_policy == \"empty\":\n            search_policy = auto_scheduler.EmptyPolicy(task)\n        elif search_policy == \"sketch\":\n            search_policy = auto_scheduler.SketchPolicy(\n                task, program_cost_model=cost_model, init_search_callbacks=init_search_callbacks\n            )\n        else:\n            raise ValueError(\"Invalid policy: \" + search_policy)\n\n        # Tune\n        tuning_options = auto_scheduler.TuningOptions(\n            num_measure_trials=num_measure_trials,\n            num_measures_per_round=2,\n            early_stopping=1,\n            runner=runner,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file), CustomMeasureCallback()],\n        )\n        task.tune(tuning_options=tuning_options, search_policy=search_policy)\n\n        # Compile with the best schedule\n        sch, args = task.apply_best(log_file)\n        mod = tvm.build(sch, args, target)\n\n        # Compile with naive schedule for correctness check\n        sch, args = task.compute_dag.apply_steps_from_state(task.compute_dag.init_state)\n        mod_ref = tvm.build(sch, args, \"llvm\")\n\n        ctx = tvm.device(str(target), 0)\n        np_arrays = [np.random.uniform(size=get_const_tuple(x.shape)).astype(x.dtype) for x in args]\n\n        tvm_arrays = [tvm.nd.array(x, ctx) for x in np_arrays]\n        mod(*tvm_arrays)\n        actual = [x.numpy() for x in tvm_arrays]\n\n        tvm_arrays = [tvm.nd.array(x) for x in np_arrays]\n        mod_ref(*tvm_arrays)\n        expected = [x.numpy() for x in tvm_arrays]\n\n        for x, y in zip(actual, expected):\n            tvm.testing.assert_allclose(x, y, rtol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_workload_registry_empty_policy():\n    search_common(search_policy=\"empty\", num_measure_trials=2)\n\n    N = 64\n    target = \"llvm\"\n    search_common(\n        task=auto_scheduler.SearchTask(\n            func=\"matmul_auto_scheduler_test\", args=(N, N, N), target=target\n        ),\n        num_measure_trials=2,\n        search_policy=\"empty\",\n    )\n    search_common(\n        task=auto_scheduler.SearchTask(\n            func=\"matmul_auto_scheduler_test_rename_1\", args=(N, N, N), target=target\n        ),\n        num_measure_trials=2,\n        search_policy=\"empty\",\n    )\n\n\n@tvm.testing.requires_llvm\ndef test_sketch_search_policy_basic():\n    search_common()\n\n\ndef sketch_search_policy_basic_spawn():\n    assert multiprocessing.get_start_method(False) == \"spawn\"\n    test_sketch_search_policy_basic()\n\n\n@tvm.testing.requires_llvm\ndef test_sketch_search_policy_basic_spawn():\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=sketch_search_policy_basic_spawn)\n    p.start()\n    p.join()\n\n\n@tvm.testing.requires_llvm\ndef test_sketch_search_policy_xgbmodel():\n    search_common(cost_model=auto_scheduler.XGBModel())\n\n\n@tvm.testing.requires_cuda\ndef test_sketch_search_policy_cuda_rpc_runner():\n    measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n    search_common(target=\"cuda\", runner=measure_ctx.runner)\n\n\n@tvm.testing.requires_cuda\ndef test_sketch_search_policy_cuda_xgbmodel_rpc_runner():\n    measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n    search_common(target=\"cuda\", runner=measure_ctx.runner, cost_model=auto_scheduler.XGBModel())\n\n\n@tvm.testing.requires_llvm\n@tvm.testing.requires_cuda\ndef test_sketch_search_policy_zero_rank():\n    measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n    for target in [\"llvm\", \"cuda\"]:\n        task = auto_scheduler.SearchTask(\n            func=zero_rank_compute_auto_scheduler_test, args=(10,), target=target\n        )\n        search_common(task, runner=measure_ctx.runner)\n\n        task = auto_scheduler.SearchTask(\n            func=zero_rank_reduce_auto_scheduler_test, args=(10,), target=target\n        )\n        search_common(task, runner=measure_ctx.runner)\n\n\n@tvm.testing.requires_llvm\ndef test_sketch_search_policy_custom_sketch():\n    def meet_condition_func(search_policy, state, stage_id):\n        return auto_scheduler.PreloadCustomSketchRule.APPLY_AND_SKIP_REST\n\n    def apply_func(search_policy, state, stage_id):\n        ret = []\n        state = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n        C = state.stage_ops[2]\n\n        ret.append([state.state_object, -1])\n\n        s1 = state.copy()\n        i, _, _ = s1[C].iters\n        s1.split(C, i, [8])\n        ret.append([s1.state_object, -1])\n        return ret\n\n    search_common(\n        cost_model=auto_scheduler.XGBModel(),\n        init_search_callbacks=[\n            auto_scheduler.PreloadCustomSketchRule(meet_condition_func, apply_func)\n        ],\n    )\n\n\nif __name__ == \"__main__\":\n    test_workload_registry_empty_policy()\n    test_sketch_search_policy_basic()\n    test_sketch_search_policy_basic_spawn()\n    test_sketch_search_policy_xgbmodel()\n    test_sketch_search_policy_cuda_rpc_runner()\n    test_sketch_search_policy_cuda_xgbmodel_rpc_runner()\n    test_sketch_search_policy_zero_rank()\n    test_sketch_search_policy_custom_sketch()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_search_task.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Test search policy\"\"\"\n\nimport numpy as np\nimport tempfile\n\nimport tvm\nimport tvm.testing\nfrom tvm import auto_scheduler\nfrom tvm.auto_scheduler.utils import get_const_tuple\nfrom tvm.testing.auto_scheduler import (\n    matmul_auto_scheduler_test,\n    zero_rank_compute_auto_scheduler_test,\n    zero_rank_reduce_auto_scheduler_test,\n)\n\n\ndef test_search_task_add_task_input():\n    auto_scheduler.search_task.TASK_INPUT_BUFFER_TABLE.clear()\n    N = 64\n    target = \"llvm\"\n    test_input_0 = tvm.runtime.ndarray.empty((64, 64))\n    test_input_1 = tvm.runtime.ndarray.empty((10, 20))\n    test_input_2 = tvm.runtime.ndarray.empty((30, 40, 50))\n    task = auto_scheduler.SearchTask(\n        func=\"matmul_auto_scheduler_test\",\n        args=(N, N, N),\n        target=target,\n        task_inputs={\n            \"test_input_0\": test_input_0,\n            \"test_input_1\": test_input_1,\n            \"test_input_2\": test_input_2,\n        },\n        task_inputs_overwrite=True,\n    )\n\n    assert len(task.task_input_names) == 3\n    assert task.task_input_names[0] == \"test_input_0\"\n    assert task.task_input_names[1] == \"test_input_1\"\n    assert task.task_input_names[2] == \"test_input_2\"\n\n\ndef test_search_task_record():\n    auto_scheduler.search_task.TASK_INPUT_BUFFER_TABLE.clear()\n    N = 64\n    target = \"llvm\"\n\n    # Log with no task input\n    task = auto_scheduler.SearchTask(\n        func=\"matmul_auto_scheduler_test\", args=(N, N, N), target=target\n    )\n    task_record = auto_scheduler._ffi_api.SerializeSearchTask(task)\n    new_task = auto_scheduler._ffi_api.DeserializeSearchTask(task_record)\n    # TODO(jcf94): Check the compute dag & hardware parameter\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n\n    # Log with 1 task input\n    test_input_0 = tvm.runtime.ndarray.empty((64, 64))\n    task = auto_scheduler.SearchTask(\n        func=\"matmul_auto_scheduler_test\",\n        args=(N, N, N),\n        target=target,\n        task_inputs={\"test_input_0\": test_input_0},\n        task_inputs_overwrite=True,\n    )\n    task_record = auto_scheduler._ffi_api.SerializeSearchTask(task)\n    new_task = auto_scheduler._ffi_api.DeserializeSearchTask(task_record)\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 1\n    assert new_task.task_input_names[0] == \"test_input_0\"\n\n    # Log with multiple task inputs\n    test_input_1 = tvm.runtime.ndarray.empty((64, 64))\n    task = auto_scheduler.SearchTask(\n        func=\"matmul_auto_scheduler_test\",\n        args=(N, N, N),\n        target=target,\n        task_inputs={\n            \"test_input_0\": test_input_0,\n            \"test_input_1\": test_input_1,\n        },\n        task_inputs_overwrite=True,\n    )\n    task_record = auto_scheduler._ffi_api.SerializeSearchTask(task)\n    new_task = auto_scheduler._ffi_api.DeserializeSearchTask(task_record)\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 2\n    assert new_task.task_input_names[0] == \"test_input_0\"\n    assert new_task.task_input_names[1] == \"test_input_1\"\n\n    # Log with version 0.5\n    v5_log = \"\"\"[\"[\\\\\\\"matmul_auto_scheduler_test\\\\\\\", 64, 64, 64]\", \"llvm -keys=cpu\", [6, 64, 64, 0, 0, 0, 0, 0], \"\", 1]\"\"\"\n    new_task = auto_scheduler._ffi_api.DeserializeSearchTask(v5_log)\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 0\n\n\ndef test_recover_measure_input_with_task_input():\n    auto_scheduler.search_task.TASK_INPUT_BUFFER_TABLE.clear()\n\n    # Since this file is tests for search_task, we only check the search_task here\n\n    # Log with no task input\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test, args=(512, 512, 512), target=\"llvm\"\n    )\n    inp = auto_scheduler.measure.MeasureInput(task, task.compute_dag.init_state)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n    measure_record = auto_scheduler.measure_record.dump_record_to_string(inp, res)\n    measure_log = auto_scheduler.measure_record.load_record_from_string(measure_record)\n    new_task = measure_log[0].task\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n\n    # Log with 1 task input\n    test_input_0 = tvm.runtime.ndarray.empty((64, 64))\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test,\n        args=(512, 512, 512),\n        target=\"llvm\",\n        task_inputs={\n            \"test_input_0\": test_input_0,\n        },\n        task_inputs_overwrite=True,\n    )\n    inp = auto_scheduler.measure.MeasureInput(task, task.compute_dag.init_state)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n    measure_record = auto_scheduler.measure_record.dump_record_to_string(inp, res)\n    measure_log = auto_scheduler.measure_record.load_record_from_string(measure_record)\n    new_task = measure_log[0].task\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 1\n    assert new_task.task_input_names[0] == \"test_input_0\"\n\n    # Log with multiple task inputs\n    test_input_1 = tvm.runtime.ndarray.empty((64, 64))\n    task = auto_scheduler.SearchTask(\n        func=matmul_auto_scheduler_test,\n        args=(512, 512, 512),\n        target=\"llvm\",\n        task_inputs={\n            \"test_input_0\": test_input_0,\n            \"test_input_1\": test_input_1,\n        },\n        task_inputs_overwrite=True,\n    )\n    inp = auto_scheduler.measure.MeasureInput(task, task.compute_dag.init_state)\n    res = auto_scheduler.measure.MeasureResult([0.1], 0, \"\", 0.2, 1)\n    measure_record = auto_scheduler.measure_record.dump_record_to_string(inp, res)\n    measure_log = auto_scheduler.measure_record.load_record_from_string(measure_record)\n    new_task = measure_log[0].task\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 2\n    assert new_task.task_input_names[0] == \"test_input_0\"\n    assert new_task.task_input_names[1] == \"test_input_1\"\n\n    # Log with version 0.5\n    v5_log = \"\"\"{\"i\": [[\"[\\\\\\\"matmul_auto_scheduler_test\\\\\\\", 512, 512, 512]\", \"llvm -keys=cpu\", [6, 64, 64, 0, 0, 0, 0, 0], \"\", 1], [[], []]], \"r\": [[0.1], 0, 0.2, 1], \"v\": \"v0.6\"}\"\"\"\n    measure_log = auto_scheduler.measure_record.load_record_from_string(v5_log)\n    new_task = measure_log[0].task\n    assert task.workload_key == new_task.workload_key\n    assert str(task.target) == str(new_task.target)\n    assert str(task.target.host) == str(new_task.target.host)\n    assert task.layout_rewrite_option == new_task.layout_rewrite_option\n    assert len(new_task.task_input_names) == 0\n\n\nif __name__ == \"__main__\":\n    test_search_task_add_task_input()\n    test_search_task_record()\n    test_recover_measure_input_with_task_input()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_sketch_generation.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Test sketch generation. \"\"\"\n\nimport sys\nimport tvm\nimport tvm.testing\n\nimport pytest\n\nfrom tvm import te, auto_scheduler\nfrom tvm.auto_scheduler import _ffi_api\nfrom tvm.auto_scheduler.loop_state import Stage\n\nfrom tvm.testing.auto_scheduler import (\n    matmul_auto_scheduler_test,\n    double_matmul_auto_scheduler_test,\n    conv2d_nchw_bn_relu_auto_scheduler_test,\n    max_pool2d_auto_scheduler_test,\n    min_nm_auto_scheduler_test,\n    softmax_nm_auto_scheduler_test,\n    softmax_abcd_auto_scheduler_test,\n    conv2d_winograd_nhwc_auto_scheduler_test,\n    zero_rank_reduce_auto_scheduler_test,\n)\n\n\ndef generate_sketches(\n    workload_func, args, target, print_for_debug=False, init_search_callbacks=None\n):\n    # NOTE: test_cpu_matmul_sketch and test_cpu_max_pool2d_sketch assume 4 cores to trigger all\n    # possible sketch generations.\n    task = auto_scheduler.SearchTask(\n        func=workload_func,\n        args=args,\n        target=target,\n        hardware_params=auto_scheduler.HardwareParams(num_cores=4, target=target),\n    )\n    policy = auto_scheduler.SketchPolicy(\n        task, verbose=0, init_search_callbacks=init_search_callbacks\n    )\n    return policy.generate_sketches(print_for_debug)\n\n\ndef assert_compute_at_condition(stage, condition):\n    assert stage.compute_at == Stage.COMPUTE_AT_TRANS_TABLE[condition]\n\n\ndef assert_is_tiled(stage):\n    assert _ffi_api.SearchPolicyUtilsIsTiled(stage)\n\n\ndef assert_is_not_tiled(stage):\n    assert not _ffi_api.SearchPolicyUtilsIsTiled(stage)\n\n\ndef assert_has_cache_write(state, stage_id):\n    assert _ffi_api.SearchPolicyUtilsHasCacheWriteStage(state, stage_id)\n\n\ndef assert_has_cache_read(state, stage_id):\n    assert _ffi_api.SearchPolicyUtilsHasCacheReadStage(state, stage_id)\n\n\ndef assert_has_rfactor(state, stage_id):\n    assert _ffi_api.SearchPolicyUtilsHasRfactorStage(state, stage_id)\n\n\ndef assert_has_cross_thread_reduction(state, stage_id):\n    assert _ffi_api.SearchPolicyUtilsHasCrossThreadReduction(state, stage_id)\n\n\ndef test_cpu_matmul_sketch():\n    sketches = generate_sketches(matmul_auto_scheduler_test, (512, 512, 512), \"llvm\")\n    \"\"\" 3 multi-level tiling sketches\n        No.0 : Multi-level tiling\n        No.1 : Multi-level tiling with cache write on position 0\n        No.2 : Multi-level tiling with cache write on position 1\n    \"\"\"\n    assert len(sketches) == 3\n    # Sketch 0\n    assert_is_tiled(sketches[0].stages[2])\n    # Sketch 1\n    assert_is_tiled(sketches[1].stages[2])\n    assert_has_cache_write(sketches[1], 2)\n    assert_compute_at_condition(sketches[1].stages[2], \"iter\")\n    # Sketch 2\n    assert_is_tiled(sketches[2].stages[2])\n    assert_has_cache_write(sketches[2], 2)\n    assert_compute_at_condition(sketches[2].stages[2], \"iter\")\n    assert sketches[1] != sketches[2]\n\n    sketches = generate_sketches(matmul_auto_scheduler_test, (8, 8, 512), \"llvm\")\n    \"\"\" 2 rfactor sketches + 3 multi-level tiling sketches\n        No.0 : Rfactor with factor position 0\n        No.1 : Rfactor with factor position 1\n        No.2 : Multi-level tiling\n        No.3 : Multi-level tiling with cache write on position 0\n        No.4 : Multi-level tiling with cache write on position 1\n    \"\"\"\n    assert len(sketches) == 5\n    # Sketch 0\n    assert_has_rfactor(sketches[0], 2)\n    # Sketch 1\n    assert_has_rfactor(sketches[1], 2)\n    assert sketches[0] != sketches[1]\n    # Sketch 2\n    assert_is_tiled(sketches[2].stages[2])\n    # Sketch 3\n    assert_is_tiled(sketches[3].stages[2])\n    assert_has_cache_write(sketches[3], 2)\n    assert_compute_at_condition(sketches[3].stages[2], \"iter\")\n    # Sketch 4\n    assert_is_tiled(sketches[4].stages[2])\n    assert_has_cache_write(sketches[4], 2)\n    assert_compute_at_condition(sketches[4].stages[2], \"iter\")\n    assert sketches[3] != sketches[4]\n\n    sketches = generate_sketches(double_matmul_auto_scheduler_test, (512,), \"llvm\")\n    \"\"\" 3 multi-level tiling sketches for one matmul, so 3 * 3 = 9 sketches in total \"\"\"\n    assert len(sketches) == 9\n    assert_is_tiled(sketches[8].stages[5])\n\n\ndef test_cpu_conv2d_bn_relu_sketch():\n    sketches = generate_sketches(\n        conv2d_nchw_bn_relu_auto_scheduler_test, (1, 56, 56, 512, 512, 3, 1, 1), \"llvm\"\n    )\n    \"\"\" 3 multi-level tiling sketches\n        No.0 : Conv2d multi-level tiling with fusion on position 0\n        No.1 : Conv2d multi-level tiling with fusion on position 1\n        No.2 : Conv2d multi-level tiling without fusion\n    \"\"\"\n    assert len(sketches) == 3\n    # Sketch 0\n    assert_is_not_tiled(sketches[0].stages[1])\n    assert_is_tiled(sketches[0].stages[3])\n    assert_compute_at_condition(sketches[0].stages[3], \"iter\")\n    assert_compute_at_condition(sketches[0].stages[5], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[7], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[9], \"inlined\")\n    assert_is_tiled(sketches[0].stages[10])\n    # Sketch 1\n    assert_is_not_tiled(sketches[1].stages[1])\n    assert_is_tiled(sketches[1].stages[3])\n    assert_compute_at_condition(sketches[1].stages[3], \"iter\")\n    assert_compute_at_condition(sketches[1].stages[5], \"inlined\")\n    assert_compute_at_condition(sketches[1].stages[7], \"inlined\")\n    assert_compute_at_condition(sketches[1].stages[9], \"inlined\")\n    assert_is_tiled(sketches[1].stages[10])\n    # Sketch 2\n    assert_is_not_tiled(sketches[2].stages[1])\n    assert_is_tiled(sketches[2].stages[3])\n    assert_compute_at_condition(sketches[2].stages[3], \"root\")\n    assert_compute_at_condition(sketches[2].stages[5], \"inlined\")\n    assert_compute_at_condition(sketches[2].stages[7], \"inlined\")\n    assert_compute_at_condition(sketches[2].stages[9], \"inlined\")\n    assert_is_not_tiled(sketches[2].stages[10])\n\n\ndef test_cpu_max_pool2d_sketch():\n    sketches = generate_sketches(max_pool2d_auto_scheduler_test, (1, 56, 56, 512, 1), \"llvm\")\n    \"\"\" 1 default sketch \"\"\"\n    assert len(sketches) == 1\n    # Sketch 0\n    assert len(sketches[0].transform_steps) == 0\n\n\ndef test_cpu_min_sketch():\n    sketches = generate_sketches(min_nm_auto_scheduler_test, (10, 1024), \"llvm\")\n    \"\"\" 2 rfactor sketches + 1 default sketch\n        No.0 : Rfactor with factor position 0\n        No.1 : Rfactor with factor position 1\n        No.2 : Default sketch\n    \"\"\"\n    assert len(sketches) == 3\n    # Sketch 0\n    assert_has_rfactor(sketches[0], 1)\n    # Sketch 1\n    assert_has_rfactor(sketches[1], 1)\n    assert sketches[0] != sketches[1]\n    # Sketch 2\n    assert len(sketches[2].transform_steps) == 0\n\n\ndef test_cpu_softmax_sketch():\n    sketches = generate_sketches(softmax_nm_auto_scheduler_test, (1, 1024), \"llvm\")\n    \"\"\" (2 rfactor sketches + 1 default sketch) * (2 rfactor sketches + 1 default sketch) \"\"\"\n    assert len(sketches) == (3 * 3)\n    for i in range(0, 3):\n        for j in range(0, 3):\n            sketch = sketches[i * 3 + j]\n            if j in [0, 1]:\n                assert_has_rfactor(sketch, 1)\n            if i in [0, 1]:\n                assert_has_rfactor(sketch, 4 if j in [0, 1] else 3)\n    assert len(sketches[8].transform_steps) == 0\n\n    sketches = generate_sketches(softmax_abcd_auto_scheduler_test, (1, 12, 128, 128), \"llvm\")\n    \"\"\" (2 rfactor sketches + 1 default sketch) * (2 rfactor sketches + 1 default sketch) \"\"\"\n    assert len(sketches) == (3 * 3)\n    for i in range(0, 3):\n        for j in range(0, 3):\n            sketch = sketches[i * 3 + j]\n            if j in [0, 1]:\n                assert_has_rfactor(sketch, 1)\n            if i in [0, 1]:\n                assert_has_rfactor(sketch, 4 if j in [0, 1] else 3)\n    assert len(sketches[8].transform_steps) == 0\n\n\ndef test_cpu_conv2d_winograd_sketch():\n    sketches = generate_sketches(\n        conv2d_winograd_nhwc_auto_scheduler_test, (1, 28, 28, 128, 128, 3, 1, 1), \"llvm\"\n    )\n    \"\"\" 3 multi-level tiling sketches\n        No.0 : Bgemm multi-level tiling\n        No.1 : Bgemm multi-level tiling with cache write on position 0\n        No.2 : Bgemm multi-level tiling with cache write on position 1\n    \"\"\"\n    assert len(sketches) == 3\n    # Sketch 0\n    assert_is_not_tiled(sketches[0].stages[1])\n    assert_is_not_tiled(sketches[0].stages[2])\n    assert_compute_at_condition(sketches[0].stages[3], \"inlined\")\n    assert_is_tiled(sketches[0].stages[4])\n    assert_is_tiled(sketches[0].stages[6])\n    assert_compute_at_condition(sketches[0].stages[7], \"inlined\")\n    assert_is_tiled(sketches[0].stages[8])\n    assert_is_not_tiled(sketches[0].stages[9])\n    # Sketch 1\n    assert_is_not_tiled(sketches[1].stages[1])\n    assert_is_not_tiled(sketches[1].stages[2])\n    assert_compute_at_condition(sketches[1].stages[3], \"inlined\")\n    assert_is_tiled(sketches[1].stages[4])\n    assert_is_tiled(sketches[1].stages[6])\n    assert_has_cache_write(sketches[1], 6)\n    assert_compute_at_condition(sketches[1].stages[6], \"iter\")\n    assert_compute_at_condition(sketches[1].stages[8], \"inlined\")\n    assert_is_tiled(sketches[1].stages[9])\n    assert_is_not_tiled(sketches[1].stages[10])\n    # Sketch 2\n    assert_is_not_tiled(sketches[2].stages[1])\n    assert_is_not_tiled(sketches[2].stages[2])\n    assert_compute_at_condition(sketches[2].stages[3], \"inlined\")\n    assert_is_tiled(sketches[2].stages[4])\n    assert_is_tiled(sketches[2].stages[6])\n    assert_has_cache_write(sketches[2], 6)\n    assert_compute_at_condition(sketches[2].stages[6], \"iter\")\n    assert_compute_at_condition(sketches[2].stages[8], \"inlined\")\n    assert_is_tiled(sketches[2].stages[9])\n    assert_is_not_tiled(sketches[2].stages[10])\n    assert sketches[1] != sketches[2]\n\n\ndef test_cpu_zero_rank_sketch():\n    sketches = generate_sketches(zero_rank_reduce_auto_scheduler_test, (128,), \"llvm\")\n    \"\"\" 2 rfactor sketches + 1 multi-level tiling sketches \"\"\"\n    assert len(sketches) == 3\n\n\ndef test_cpu_custom_sketch():\n    def meet_condition_func(search_policy, state, stage_id):\n        return auto_scheduler.PreloadCustomSketchRule.APPLY_AND_SKIP_REST\n\n    def apply_func(search_policy, state, stage_id):\n        ret = []\n        state = auto_scheduler.loop_state.State(state, search_policy.search_task.compute_dag)\n        C = state.stage_ops[2]\n\n        ret.append([state.state_object, -1])\n\n        s1 = state.copy()\n        i, _, _ = s1[C].iters\n        s1.split(C, i, [8, 2])\n        ret.append([s1.state_object, -1])\n        return ret\n\n    sketches = generate_sketches(\n        matmul_auto_scheduler_test,\n        (512, 512, 512),\n        \"llvm\",\n        init_search_callbacks=[\n            auto_scheduler.PreloadCustomSketchRule(meet_condition_func, apply_func)\n        ],\n    )\n    assert len(sketches) == 2\n    assert sketches[0].stages[2].iters[0].range.extent == 512\n    assert sketches[0].stages[2].iters[1].range.extent == 512\n    assert sketches[0].stages[2].iters[2].range.extent == 512\n    assert sketches[1].stages[2].iters[0].range.extent == 32\n    assert sketches[1].stages[2].iters[1].range.extent == 8\n    assert sketches[1].stages[2].iters[2].range.extent == 2\n    assert sketches[1].stages[2].iters[3].range.extent == 512\n    assert sketches[1].stages[2].iters[4].range.extent == 512\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_matmul_sketch():\n    sketches = generate_sketches(matmul_auto_scheduler_test, (512, 512, 512), \"cuda\")\n    \"\"\" 1 multi-level tiling sketch \"\"\"\n    assert len(sketches) == 1\n    assert_has_cache_read(sketches[0], 0)\n    assert_compute_at_condition(sketches[0].stages[1], \"iter\")\n    assert_has_cache_read(sketches[0], 2)\n    assert_compute_at_condition(sketches[0].stages[3], \"iter\")\n    assert_has_cache_write(sketches[0], 4)\n    assert_is_tiled(sketches[0].stages[4])\n    assert_compute_at_condition(sketches[0].stages[4], \"iter\")\n    assert_is_tiled(sketches[0].stages[5])\n\n    sketches = generate_sketches(matmul_auto_scheduler_test, (8, 8, 1024), \"cuda\")\n    \"\"\" 1 cross thread reuction sketch + 1 multi-level tiling sketch \"\"\"\n    assert len(sketches) == 2\n    # Sketch 0\n    assert_has_cross_thread_reduction(sketches[0], 2)\n    # Sketch 1\n    assert_has_cache_read(sketches[1], 0)\n    assert_compute_at_condition(sketches[1].stages[1], \"iter\")\n    assert_has_cache_read(sketches[1], 2)\n    assert_compute_at_condition(sketches[1].stages[3], \"iter\")\n    assert_has_cache_write(sketches[1], 4)\n    assert_is_tiled(sketches[1].stages[4])\n    assert_compute_at_condition(sketches[1].stages[4], \"iter\")\n    assert_is_tiled(sketches[1].stages[5])\n\n    sketches = generate_sketches(double_matmul_auto_scheduler_test, (512,), \"cuda\")\n    \"\"\" 1 multi-level tiling sketch for one matmul, so 1 x 1 = 1 sketch in total \"\"\"\n    assert len(sketches) == 1\n    assert_compute_at_condition(sketches[0].stages[5], \"root\")\n    assert_compute_at_condition(sketches[0].stages[6], \"iter\")\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_conv2d_bn_relu_sketch():\n    sketches = generate_sketches(\n        conv2d_nchw_bn_relu_auto_scheduler_test, (1, 56, 56, 512, 512, 3, 1, 1), \"cuda\"\n    )\n    \"\"\" 1 multi-level tiling sketch \"\"\"\n    assert len(sketches) == 1\n    assert_has_cache_read(sketches[0], 1)\n    assert_compute_at_condition(sketches[0].stages[1], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[2], \"iter\")\n    assert_has_cache_read(sketches[0], 3)\n    assert_compute_at_condition(sketches[0].stages[4], \"iter\")\n    assert_is_tiled(sketches[0].stages[5])\n    assert_compute_at_condition(sketches[0].stages[5], \"iter\")\n    assert_compute_at_condition(sketches[0].stages[7], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[9], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[11], \"inlined\")\n    assert_is_tiled(sketches[0].stages[12])\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_max_pool2d_sketch():\n    sketches = generate_sketches(max_pool2d_auto_scheduler_test, (1, 56, 56, 512, 0), \"cuda\")\n    \"\"\" 1 default sketch \"\"\"\n    assert len(sketches) == 1\n    assert len(sketches[0].transform_steps) == 0\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_min_sketch():\n    sketches = generate_sketches(min_nm_auto_scheduler_test, (10, 1024), \"cuda\")\n    \"\"\" 1 cross thread reuction sketch + 1 default sketch \"\"\"\n    assert len(sketches) == 2\n    # Sketch 0\n    assert_has_cross_thread_reduction(sketches[0], 1)\n    # Sketch 1\n    assert len(sketches[1].transform_steps) == 0\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_softmax_sketch():\n    sketches = generate_sketches(softmax_nm_auto_scheduler_test, (2, 1024), \"cuda\")\n    \"\"\" (1 cross thread reuction sketch + 1 default sketch) * (1 cross thread reuction sketch + 1 default sketch) \"\"\"\n    assert len(sketches) == (2 * 2)\n    # Sketch 0\n    assert_has_cross_thread_reduction(sketches[0], 1)\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    assert_has_cross_thread_reduction(sketches[0], 3)\n    # Sketch 1\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    assert_has_cross_thread_reduction(sketches[1], 3)\n    # Sketch 2\n    assert_has_cross_thread_reduction(sketches[2], 1)\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    # Sketch 3\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n\n    sketches = generate_sketches(softmax_abcd_auto_scheduler_test, (1, 12, 128, 128), \"cuda\")\n    \"\"\" (1 cross thread reuction sketch + 1 default sketch) * (1 cross thread reuction sketch + 1 default sketch) \"\"\"\n    assert len(sketches) == (2 * 2)\n    # Sketch 0\n    assert_has_cross_thread_reduction(sketches[0], 1)\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    assert_has_cross_thread_reduction(sketches[0], 3)\n    # Sketch 1\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    assert_has_cross_thread_reduction(sketches[1], 3)\n    # Sketch 2\n    assert_has_cross_thread_reduction(sketches[2], 1)\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n    # Sketch 3\n    assert_compute_at_condition(sketches[3].stages[2], \"inlined\")\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_conv2d_winograd_sketch():\n    sketches = generate_sketches(\n        conv2d_winograd_nhwc_auto_scheduler_test, (1, 28, 28, 128, 128, 3, 1, 1), \"cuda\"\n    )\n    \"\"\" 1 multi-level tiling sketch \"\"\"\n    assert len(sketches) == 1\n    assert_compute_at_condition(sketches[0].stages[1], \"inlined\")\n    assert_compute_at_condition(sketches[0].stages[2], \"iter\")\n    assert_compute_at_condition(sketches[0].stages[3], \"inlined\")\n    assert_is_tiled(sketches[0].stages[4])\n    assert_has_cache_read(sketches[0], 4)\n    assert_compute_at_condition(sketches[0].stages[5], \"iter\")\n    assert_has_cache_read(sketches[0], 6)\n    assert_compute_at_condition(sketches[0].stages[7], \"iter\")\n    assert_is_tiled(sketches[0].stages[8])\n    assert_compute_at_condition(sketches[0].stages[8], \"iter\")\n    assert_has_cache_write(sketches[0], 8)\n    assert_compute_at_condition(sketches[0].stages[9], \"root\")\n    assert_is_tiled(sketches[0].stages[11])\n    assert_is_not_tiled(sketches[0].stages[12])\n\n\n@tvm.testing.requires_cuda\ndef test_cuda_zero_rank_sketch():\n    sketches = generate_sketches(zero_rank_reduce_auto_scheduler_test, (128,), \"cuda\")\n    \"\"\" 1 cross thread reuction sketch + 1 multi-level tiling sketch \"\"\"\n    assert len(sketches) == 2\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_auto_scheduler_task_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test task scheduler \"\"\"\n\nimport tempfile\n\nimport multiprocessing\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import auto_scheduler\n\nfrom tvm.testing.auto_scheduler import matmul_auto_scheduler_test\n\n\n@tvm.testing.requires_llvm\ndef test_task_scheduler_round_robin():\n    tasks = []\n    for n in [2, 4, 8]:\n        tasks.append(\n            auto_scheduler.SearchTask(\n                func=matmul_auto_scheduler_test, args=(n, n, n), target=\"llvm\"\n            )\n        )\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n        num_trials_per_task = 2\n\n        # Tune all tasks\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=num_trials_per_task * len(tasks),\n            runner=measure_ctx.runner,\n            num_measures_per_round=1,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        task_scheduler = auto_scheduler.TaskScheduler(tasks, strategy=\"round-robin\", callbacks=[])\n        task_scheduler.tune(tune_option, search_policy=\"sketch.random\")\n\n        # Check the result of round robin\n        counters = {}\n        for task in tasks:\n            counters[task.workload_key] = 0\n\n        for inp, _ in auto_scheduler.load_records(log_file):\n            counters[inp.task.workload_key] += 1\n\n        for task in tasks:\n            assert counters[task.workload_key] == num_trials_per_task\n\n        # test continuous tuning (restoring the status)\n        task_scheduler = auto_scheduler.TaskScheduler(\n            tasks, strategy=\"round-robin\", load_log_file=log_file, callbacks=[]\n        )\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=len(tasks),\n            num_measures_per_round=1,\n        )\n        task_scheduler.tune(tune_option, search_policy=\"sketch.random\")\n        del measure_ctx\n\n\n@tvm.testing.requires_llvm\ndef task_scheduler_round_robin_spawn():\n    assert multiprocessing.get_start_method(False) == \"spawn\"\n    test_task_scheduler_round_robin()\n\n\n@tvm.testing.requires_llvm\ndef test_task_scheduler_round_robin_spawn():\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=task_scheduler_round_robin_spawn)\n    p.start()\n    p.join()\n\n\n@tvm.testing.requires_llvm\ndef test_task_scheduler_gradient():\n    tasks = []\n    for n in [2, 4]:\n        tasks.append(\n            auto_scheduler.SearchTask(\n                func=matmul_auto_scheduler_test, args=(n, n, n), target=\"llvm\"\n            )\n        )\n\n    def objective_func(costs):\n        return 1e5 * costs[0]\n\n    with tempfile.NamedTemporaryFile() as fp:\n        log_file = fp.name\n\n        n_trials = 5\n\n        # Tune all tasks\n        measure_ctx = auto_scheduler.LocalRPCMeasureContext()\n        tune_option = auto_scheduler.TuningOptions(\n            num_measure_trials=n_trials,\n            runner=measure_ctx.runner,\n            num_measures_per_round=1,\n            measure_callbacks=[auto_scheduler.RecordToFile(log_file)],\n        )\n        task_scheduler = auto_scheduler.TaskScheduler(\n            tasks, objective_func=objective_func, callbacks=[]\n        )\n\n        # Forcely rewrite the initial values.\n        # This can make this test more stable on the slow CI machines\n        task_scheduler.best_costs = np.array([1e2, 1e-8])\n\n        task_scheduler.tune(tune_option, search_policy=\"sketch.random\")\n\n        # Check the allocation results\n        counters = {}\n        for task in tasks:\n            counters[task.workload_key] = 0\n\n        for inp, _ in auto_scheduler.load_records(log_file):\n            counters[inp.task.workload_key] += 1\n\n        assert counters[tasks[0].workload_key] == n_trials - 1\n        assert counters[tasks[1].workload_key] == 1\n        del measure_ctx\n\n\nif __name__ == \"__main__\":\n    test_task_scheduler_round_robin()\n    test_task_scheduler_round_robin_spawn()\n    test_task_scheduler_gradient()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test database\"\"\"\nimport copy\nimport logging\n\nfrom tvm.autotvm import database\nfrom tvm.autotvm.record import encode, MeasureResult\n\nfrom tvm.testing.autotvm import get_sample_records\n\n\ndef test_save_load():\n    logging.info(\"test basic db load/save ...\")\n    records = get_sample_records(3)\n    inp1, res1 = records[0]\n    inp2, res2 = records[1]\n    inp3, _ = records[2]\n\n    _db = database.DummyDatabase()\n    _db.flush()\n    _db.save(inp1, res1)\n    _db.save(inp2, res2)\n\n    load1 = _db.load(inp1)\n    load2 = _db.load(inp2)\n    load3 = _db.load(inp3)\n    assert load1 == res1\n    assert load2 == res2\n    assert load3 is None\n    assert load1 != load2\n\n\nTRIAL_LIMIT = 2\n\n\ndef test_db_hash():\n    logging.info(\"test db hash check ...\")\n    inp1, res1 = get_sample_records(1)[0]\n    inp2 = copy.deepcopy(inp1)\n    inp1.config.code_hash = \"cafecafe\"\n    inp2.config.code_hash = \"dbffdbff\"\n    res2l = list(tuple(res1))\n\n    # set timestamp\n    res2l[-1] = -1\n    res2 = MeasureResult(*res2l)\n    _db = database.DummyDatabase()\n    _db.flush()\n    _db.save(inp1, res1, extend=True)\n    _db.save(inp2, res2, extend=True)\n\n    load1 = _db.load(inp1)\n    load2 = _db.load(inp2)\n    assert load1 != load2\n    assert load1.timestamp != -1\n    assert load2.timestamp == -1\n\n\ndef test_db_latest_all():\n    logging.info(\"test db load w/ multiple results ...\")\n    inp1, res1 = get_sample_records(1)[0]\n    lis1 = list(tuple(res1))\n    lis2 = list(tuple(res1))\n    lis3 = list(tuple(res1))\n\n    # set timestamp\n    lis1[-1] = 0.0\n    lis2[-1] = 1.1\n    lis3[-1] = 9999.9999\n    res1 = MeasureResult(*lis1)\n    res2 = MeasureResult(*lis2)\n    res3 = MeasureResult(*lis3)\n\n    _db = database.DummyDatabase()\n    _db.flush()\n    _db.save(inp1, res1, extend=True)\n    load1 = _db.load(inp1)\n    assert load1.timestamp == 0.0\n    _db.save(inp1, res2, extend=True)\n    load2 = _db.load(inp1)\n    assert load2.timestamp == 1.1\n    _db.save(inp1, res3, extend=True)\n    load3 = _db.load(inp1)\n    assert load3.timestamp == 9999.9999\n\n    load4 = _db.load(inp1, get_all=True)\n    assert encode(inp1, load4[0]) == encode(inp1, res1)\n    assert encode(inp1, load4[1]) == encode(inp1, res2)\n    assert encode(inp1, load4[2]) == encode(inp1, res3)\n\n\ndef test_db_filter():\n    logging.info(\"test db filter ...\")\n    records = get_sample_records(5)\n    _db = database.DummyDatabase()\n    _db.flush()\n    for inp, result in records:\n        _db.save(inp, result)\n\n    records = _db.filter(lambda inp, ress: any(r.costs[0] <= 2 for r in ress))\n    assert len(records) == 2\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n    test_save_load()\n    test_db_hash()\n    test_db_latest_all()\n    test_db_filter()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_dispatch_context.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test dispatcher.\nThe dispatcher can choose which template to use according\nto the parameters of workload\"\"\"\n\nfrom tvm import autotvm\n\n\n@autotvm.template(\"testing/dispatch_fallback\")\ndef simple_template(a, b):\n    cfg = autotvm.get_config()\n    assert cfg.is_fallback\n\n\ndef test_fallback():\n    simple_template(2, 3)\n\n\nif __name__ == \"__main__\":\n    test_fallback()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test feature extraction\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.autotvm import feature\n\n\ndef test_iter_feature_gemm():\n    N = 128\n\n    k = te.reduce_axis((0, N), \"k\")\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"B\")\n    C = te.compute(A.shape, lambda y, x: te.sum(A[y, k] * B[k, x], axis=k), name=\"C\")\n\n    s = te.create_schedule(C.op)\n\n    feas = feature.get_itervar_feature(s, [A, B, C], take_log=False)\n\n    expected = [\n        {\n            \"_attr_\": [128, 1, 128, 2097152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n            \"A_0\": [128, -1, 16384, 128, 0, 0],\n            \"B_0\": [0, -1, 16384, 128, 0, 0],\n            \"C_0\": [128, -1, 16384, 128, 0, 0],\n            \"C_1\": [128, -1, 16384, 128, 0, 0],\n        },\n        {\n            \"_attr_\": [128, 2, 16384, 16384, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n            \"A_0\": [0, -1, 128, 128, 0, 0],\n            \"B_0\": [1, -1, 16384, 1, 0, 0],\n            \"C_0\": [1, -1, 128, 128, 0, 0],\n            \"C_1\": [1, -1, 128, 128, 0, 0],\n        },\n        {\n            \"_attr_\": [128, 3, 2097152, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n            \"A_0\": [1, -1, 128, 1, 0, 0],\n            \"B_0\": [128, -1, 128, 1, 0, 0],\n            \"C_1\": [0, -1, 1, 128, 0, 0],\n            \"C_2\": [0, -1, 1, 128, 0, 0],\n        },\n    ]\n\n    for ans, row in zip(expected, feas):\n        for pair in row:\n            if pair[0] not in ans:\n                continue\n            assert ans[pair[0]] == pair[1:], \"%s: %s vs %s\" % (pair[0], ans[pair[0]], pair[1:])\n\n\ndef test_curve_feature_gemm():\n    N = 128\n\n    k = te.reduce_axis((0, N), \"k\")\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"B\")\n    C = te.compute(A.shape, lambda y, x: te.sum(A[y, k] * B[k, x], axis=k), name=\"C\")\n\n    s = te.create_schedule(C.op)\n\n    feas = feature.get_buffer_curve_sample_flatten(s, [A, B, C], sample_n=30)\n    # sample_n * #buffers * #curves * 2 numbers per curve\n    assert len(feas) == 30 * 3 * 4 * 2\n\n\ndef test_feature_shape():\n    \"\"\"test the dimensions of flatten feature are the same\"\"\"\n\n    N = 1024\n    n_sample = 100\n\n    def get_gemm_feature(target):\n        k = te.reduce_axis((0, N), \"k\")\n        A = te.placeholder((N, N), name=\"A\")\n        B = te.placeholder((N, N), name=\"B\")\n        C = te.compute(A.shape, lambda y, x: te.sum(A[y, k] * B[k, x], axis=k), name=\"C\")\n\n        s = te.create_schedule(C.op)\n\n        y, x = s[C].op.axis\n        axes = list(s[C].tile(y, x, 8, 8)) + [k]\n        perm = np.random.permutation(5)\n        axes = [axes[x] for x in perm]\n        s[C].reorder(*axes)\n\n        if \"gpu\" in target.keys:\n            pick = []\n            # filter out reduction axis\n            for i in range(len(perm)):\n                if perm[i] != 4:\n                    pick.append(axes[i])\n            s[C].bind(pick[0], te.thread_axis(\"blockIdx.x\"))\n            s[C].bind(pick[1], te.thread_axis(\"vthread\"))\n            s[C].bind(pick[2], te.thread_axis(\"threadIdx.y\"))\n\n        with target:\n            feas = feature.get_itervar_feature(s, [A, B, C])\n            feas = feature.flatten_itervar_feature(feas)\n        return feas\n\n    targets = [\n        tvm.target.cuda(),\n        tvm.target.mali(),\n        tvm.target.arm_cpu(),\n    ]\n\n    for target in targets:\n        dim = len(get_gemm_feature(target))\n        for i in range(n_sample):\n            assert dim == len(get_gemm_feature(target)), (\n                \"dimensions of feature do not match\" \" for different configurations\"\n            )\n\n\nif __name__ == \"__main__\":\n    test_iter_feature_gemm()\n    test_curve_feature_gemm()\n    test_feature_shape()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_flop_calculator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test flop calculation\"\"\"\n\nimport tvm\nfrom tvm import te\nimport numpy as np\n\nfrom tvm.autotvm.task.task import compute_flop\n\n\ndef random_dtypes():\n    \"\"\"Return pair of (input, accumulator) dtypes\"\"\"\n    candidates = [(\"float32\", \"float32\"), (\"float16\", \"float32\"), (\"int8\", \"int32\")]\n    return candidates[np.random.choice(len(candidates))]\n\n\ndef test_conv():\n    for i in range(5):\n        N, H, W, CO, CI, KH, KW = [np.random.randint(10, 32) for _ in range(7)]\n        (input_dtype, acc_dtype) = random_dtypes()\n        D = te.placeholder((N, CI, H, W), dtype=input_dtype)\n        K = te.placeholder((CO, CI, KH, KW), dtype=input_dtype)\n\n        KH = min(H, KH)\n        KW = min(W, KW)\n\n        ci = te.reduce_axis((0, CI))\n        kh = te.reduce_axis((0, KH))\n        kw = te.reduce_axis((0, KW))\n\n        OH = (H - KH) + 1\n        OW = (W - KW) + 1\n\n        C = te.compute(\n            (N, CO, OH, OW),\n            lambda n, co, h, w: te.sum(\n                D[n][ci][h][w].astype(acc_dtype) * K[co][ci][h][w].astype(acc_dtype),\n                axis=[ci, kh, kw],\n            ),\n        )\n\n        s = te.create_schedule([C.op])\n\n        assert compute_flop(s) == 2 * N * CO * OH * OW * CI * KH * KW\n\n\ndef test_pack_gemm():\n    for i in range(5):\n        N, L, M = [np.random.randint(10, 128) * 4 for _ in range(3)]\n        (input_dtype, acc_dtype) = random_dtypes()\n        A = te.placeholder((N, L), dtype=input_dtype)\n        B = te.placeholder((M, L), dtype=input_dtype)\n        k = te.reduce_axis((0, L))\n\n        bn = 4\n        idxd = tvm.tir.indexdiv\n        idxm = tvm.tir.indexmod\n\n        A_pack = te.compute((N // bn, L, bn), lambda i, j, k: A[i * bn + k][j])\n        B_pack = te.compute((M // bn, L, bn), lambda i, j, k: B[i * bn + k][j])\n        C_pack = te.compute(\n            (N // bn, M // bn, bn, bn),\n            lambda i, j, ii, jj: te.sum(\n                A_pack[i, k, ii].astype(acc_dtype) * B_pack[j, k, jj].astype(acc_dtype), axis=[k]\n            ),\n        )\n        C = te.compute(\n            (N, M), lambda i, j: C_pack[idxd(i, bn)][idxd(j, bn)][idxm(i, bn)][idxm(j, bn)]\n        )\n\n        s = te.create_schedule([C.op])\n        assert compute_flop(s) == 2 * N * L * M\n\n\ndef test_outer_dot():\n    for i in range(5):\n        N, M = [np.random.randint(10, 128) * 4 for _ in range(2)]\n        (input_dtype, acc_dtype) = random_dtypes()\n        A = te.placeholder((N,), dtype=input_dtype)\n        B = te.placeholder((M,), dtype=input_dtype)\n\n        C = te.compute((N, M), lambda i, j: A[i].astype(acc_dtype) * B[j].astype(acc_dtype))\n\n        s = te.create_schedule([C.op])\n        assert compute_flop(s) == N * M\n\n\ndef test_max_pool():\n    for i in range(5):\n        N, H, W, CO, CI, KH, KW = [np.random.randint(10, 32) for _ in range(7)]\n        (input_dtype, _) = random_dtypes()\n        D = te.placeholder((N, CI, H, W), dtype=input_dtype)\n\n        KH = min(H, KH)\n        KW = min(W, KW)\n\n        kh = te.reduce_axis((0, KH))\n        kw = te.reduce_axis((0, KW))\n\n        OH = (H - KH) + 1\n        OW = (W - KW) + 1\n\n        C = te.compute(\n            (N, CO, OH, OW), lambda n, co, h, w: tvm.te.max(D[n][co][h + kh][w + kw], axis=[kh, kw])\n        )\n\n        s = te.create_schedule([C.op])\n\n        assert compute_flop(s) == N * CO * OH * OW * KH * KW\n\n\ndef test_average_pool():\n    for i in range(5):\n        N, H, W, CO, CI, KH, KW = [np.random.randint(10, 32) for _ in range(7)]\n        (input_dtype, acc_dtype) = random_dtypes()\n        D = te.placeholder((N, CI, H, W), dtype=input_dtype)\n\n        KH = min(H, KH)\n        KW = min(W, KW)\n\n        kh = te.reduce_axis((0, KH))\n        kw = te.reduce_axis((0, KW))\n\n        OH = (H - KH) + 1\n        OW = (W - KW) + 1\n\n        C = te.compute(\n            (N, CO, OH, OW),\n            lambda n, co, h, w: te.sum(\n                te.div(D[n][co][h + kh][w + kw].astype(acc_dtype), (KW * KH)), axis=[kh, kw]\n            ),\n        )\n\n        s = te.create_schedule([C.op])\n\n        assert compute_flop(s) == 2 * N * CO * OH * OW * KH * KW\n\n\ndef test_move():\n    \"\"\"No float number operation in simple move. So the estimator should raise an error\"\"\"\n    N = 1024\n\n    A = te.placeholder((N,))\n    C = te.compute((N,), lambda i: A[i])\n    s = te.create_schedule([C.op])\n\n    try:\n        compute_flop(s)\n        assert False\n    except RuntimeError:\n        pass\n\n\nif __name__ == \"__main__\":\n    test_conv()\n    test_pack_gemm()\n    test_outer_dot()\n    test_move()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_ga_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test genetic algorithm tuner\"\"\"\n\nfrom tvm.testing.autotvm import DummyRunner, get_sample_task\nfrom tvm import autotvm\n\n\ndef test_ga_tuner():\n    \"\"\"Test GATuner\"\"\"\n    # Test population size smaller than space size tuning configuration\n    task, _ = get_sample_task()\n    tuner = autotvm.tuner.GATuner(task, pop_size=32)\n    valid_indexes = list(\n        filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length))\n    )\n    assert tuner.visited.issubset(valid_indexes)\n    assert tuner.pop_size == len(tuner.visited) == len(tuner.genes)\n    assert len(tuner.space) == 64\n\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n    tuner.tune(n_trial=len(tuner.space), measure_option=measure_option)\n    assert tuner.visited.issubset(valid_indexes)\n\n    # Test population size bigger than space size tuning configuration\n    task, _ = get_sample_task()\n    tuner = autotvm.tuner.GATuner(task, pop_size=100)\n    valid_indexes = list(\n        filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length))\n    )\n    assert tuner.visited.issubset(valid_indexes)\n    assert tuner.pop_size == len(tuner.visited) == len(tuner.genes)\n    assert len(tuner.space) == 64\n\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n    tuner.tune(n_trial=len(tuner.space), measure_option=measure_option)\n    assert tuner.visited.issubset(valid_indexes)\n\n    # Test population size smaller than multi-filtered space size tuning configuration\n    task, _ = get_sample_task()\n    task.config_space.multi_filter(\n        filter=lambda entity: 8 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    tuner = autotvm.tuner.GATuner(task, pop_size=32)\n    valid_indexes = list(\n        filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length))\n    )\n    assert tuner.visited.issubset(valid_indexes)\n    assert tuner.pop_size == len(tuner.visited) == len(tuner.genes)\n    assert len(tuner.space) == 43\n\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n    tuner.tune(n_trial=len(tuner.space), measure_option=measure_option)\n    assert tuner.visited.issubset(valid_indexes)\n\n    # Test population size bigger than multi-filtered space size tuning configuration\n    task, _ = get_sample_task()\n    task.config_space.multi_filter(\n        filter=lambda entity: 8 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    tuner = autotvm.tuner.GATuner(task, pop_size=100)\n    valid_indexes = list(\n        filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length))\n    )\n    assert tuner.visited.issubset(valid_indexes)\n    assert tuner.pop_size == len(tuner.visited) == len(tuner.genes)\n    assert len(tuner.space) == 43\n\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n    tuner.tune(n_trial=len(tuner.space), measure_option=measure_option)\n    assert tuner.visited.issubset(valid_indexes)\n\n\nif __name__ == \"__main__\":\n    test_ga_tuner()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_graph_tuner_core.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# NOTE: We name this test file to start with test_graph_tuner\n# to make it execute after zero_rank tensor test cases. This\n# helps avoid topi arithmetic operator overloading issue:\n# https://github.com/apache/tvm/issues/3240.\n# TODO: restore the file name after this issue is resolved.\nimport os\nimport copy\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.relay.testing\n\nfrom tvm import autotvm\nfrom tvm import relay\nfrom tvm.autotvm.task import ConfigEntity\nfrom tvm.autotvm.measure import MeasureResult, MeasureInput\nfrom tvm.autotvm.graph_tuner import DPTuner, PBQPTuner\n\n\ndef _create_args(dshape, kshape, strides, padding, dilation, layout, out_layout, dtype, out_dtype):\n    data = tvm.te.placeholder(dshape, dtype=dtype)\n    kernel = tvm.te.placeholder(kshape, dtype=dtype)\n    return autotvm.task.serialize_args(\n        [data, kernel, strides, padding, dilation, layout, layout, out_dtype]\n    )\n\n\ndef _create_data(target, dshape, dtype, layout):\n    data = relay.var(\"data\", shape=dshape, dtype=dtype)\n    w0 = relay.var(\"w0_weight\")\n    conv0 = relay.nn.conv2d(data, w0, channels=16, kernel_size=(3, 3), padding=(1, 1))\n    w1 = relay.var(\"w1_weight\")\n    conv1 = relay.nn.conv2d(conv0, w1, channels=32, kernel_size=(1, 1))\n    w2 = relay.var(\"w2_weight\")\n    conv2 = relay.nn.conv2d(conv1, w2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n    out = relay.add(conv1, conv2)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    mod, params = relay.testing.create_workload(net)\n    tasks = autotvm.task.extract_from_program(\n        mod[\"main\"], target=target, params=params, ops=(relay.op.get(\"nn.conv2d\"),)\n    )\n    new_args = [\n        _create_args(\n            (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n        _create_args(\n            (1, 16, 8, 8),\n            (32, 16, 1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            layout,\n            layout,\n            dtype,\n            dtype,\n        ),\n        _create_args(\n            (1, 32, 8, 8),\n            (32, 32, 3, 3),\n            (1, 1),\n            (1, 1, 1, 1),\n            (1, 1),\n            layout,\n            layout,\n            dtype,\n            dtype,\n        ),\n    ]\n\n    costs = [0.04, 0.012, 0.03]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [3, 1]],\n            [\"tile_oc\", \"sp\", [4, 4]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [2, 8]],\n            [\"tile_oc\", \"sp\", [1, 32]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [8, 4]],\n            [\"tile_oc\", \"sp\", [4, 8]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n\n    records = []\n    for args, cost, config, task in zip(new_args, costs, config_list, tasks):\n        task.args = args\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    ltf_records = []\n    ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), \"NCHW8c\", \"NCHW512c\"]\n    ltf_task = autotvm.task.create(\"layout_transform\", ltf_arg, target)\n    ms_input = MeasureInput(target=target, task=ltf_task, config=None)\n    ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1)\n    ltf_records.append((ms_input, ms_output))\n\n    ltf_keys = []\n    ltf_arg = [te.placeholder((1, 4, 8, 8, 4), dtype=dtype), \"NCHW4c\", \"NCHW8c\"]\n    ltf_wkl = autotvm.task.args_to_workload(ltf_arg, \"layout_transform\")\n    ltf_keys.append(ltf_wkl)\n    ltf_arg = [te.placeholder((1, 1, 8, 8, 32), dtype=dtype), \"NCHW32c\", \"NCHW4c\"]\n    ltf_wkl = autotvm.task.args_to_workload(ltf_arg, \"layout_transform\")\n    ltf_keys.append(ltf_wkl)\n    ltf_arg = [te.placeholder((1, 4, 8, 8, 8), dtype=dtype), \"NCHW8c\", \"NCHW32c\"]\n    ltf_wkl = autotvm.task.args_to_workload(ltf_arg, \"layout_transform\")\n    ltf_keys.append(ltf_wkl)\n\n    return net, records, ltf_records, ltf_keys, tasks\n\n\ndef test_graph_tuner_layout_transform():\n    log_file = \"%s/test_tuner.log\" % (os.getcwd())\n    target = \"llvm\"\n    dshape = (1, 3, 8, 8)\n    dtype = \"float32\"\n    layout = \"NCHW\"\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    g, records, ltf_records, ltf_keys, _ = _create_data(target, dshape, dtype, layout)\n    executor = DPTuner(g, {\"data\": dshape}, records, target_ops, target=target, log_file=log_file)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    out = executor._layout_transform_perf_records\n\n    num_flops = 0\n    total_time = 0\n    for record in ltf_records:\n        ltf_wkl = record[0].task.workload\n        input_shape = ltf_wkl[1][1]\n        flops = np.prod(input_shape)\n        num_flops += flops\n        total_time += record[1].costs[0]\n    avg_time = total_time / num_flops\n\n    for ltf_workload in out:\n        input_shape = ltf_workload[1][1]\n        flops = 1\n        for i in input_shape:\n            flops *= i\n        expected_time = flops * avg_time\n        out_time = out[ltf_workload][1].costs[0]\n        assert (\n            expected_time == out_time\n        ), \"Inferred layout transformation time mismatch for %s: \" \"expecting %f but got %f\" % (\n            str(ltf_workload),\n            expected_time,\n            out_time,\n        )\n\n\ndef test_graph_tuner_layout_transform_runner():\n    log_file = \"%s/test_tuner.log\" % (os.getcwd())\n    target = \"llvm\"\n    dshape = (1, 3, 8, 8)\n    dtype = \"float32\"\n    layout = \"NCHW\"\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    g, records, ltf_records, ltf_keys, _ = _create_data(target, dshape, dtype, layout)\n    executor = DPTuner(g, {\"data\": dshape}, records, target_ops, target=target, log_file=log_file)\n    runner = autotvm.LocalRunner(number=100, repeat=1, timeout=10)\n    executor.benchmark_layout_transform(\n        layout_records=ltf_records, infer_layout=True, runner=runner\n    )\n    out = executor._layout_transform_perf_records\n\n    num_flops = 0\n    total_time = 0\n    for record in ltf_records:\n        ltf_wkl = record[0].task.workload\n        input_shape = ltf_wkl[1][1]\n        flops = np.prod(input_shape)\n        num_flops += flops\n        total_time += record[1].costs[0]\n    avg_time = total_time / num_flops\n\n    for ltf_workload in out:\n        input_shape = ltf_workload[1][1]\n        flops = 1\n        for i in input_shape:\n            flops *= i\n        expected_time = flops * avg_time\n        out_time = out[ltf_workload][1].costs[0]\n        assert (\n            expected_time == out_time\n        ), \"Inferred layout transformation time mismatch for %s: \" \"expecting %f but got %f\" % (\n            str(ltf_workload),\n            expected_time,\n            out_time,\n        )\n\n\ndef test_DPTuner_run():\n    log_file = \"%s/test_tuner.log\" % (os.getcwd())\n    target = \"llvm\"\n    dtype = \"float32\"\n    layout = \"NCHW\"\n    dshape = (1, 3, 8, 8)\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout)\n    mod = tvm.IRModule()\n    mod[\"main\"] = g\n    costs = [0.02, 0.02, 0.045]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 3]],\n            [\"tile_oc\", \"sp\", [2, 8]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [4, 4]],\n            [\"tile_oc\", \"sp\", [2, 16]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [16, 2]],\n            [\"tile_oc\", \"sp\", [8, 4]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    for cost, config, task in zip(costs, config_list, tasks):\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    executor = DPTuner(mod, {\"data\": dshape}, records, target_ops, target, log_file=log_file)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n    assert os.path.isfile(log_file), \"No log file with name %s exists.\" % log_file\n\n\ndef test_PBQPTuner_run():\n    target = \"llvm\"\n    dtype = \"float32\"\n    layout = \"NCHW\"\n    dshape = (1, 3, 8, 8)\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout)\n    costs = [0.02, 0.02, 0.045]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 3]],\n            [\"tile_oc\", \"sp\", [2, 8]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [4, 4]],\n            [\"tile_oc\", \"sp\", [2, 16]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [16, 2]],\n            [\"tile_oc\", \"sp\", [8, 4]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    for cost, config, task in zip(costs, config_list, tasks):\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    executor = PBQPTuner(g, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n\ndef test_many_sub_graphs():\n    target = \"llvm\"\n    dtype = \"float32\"\n    dshape = (1, 8, 8, 3)\n    layout = \"NCHW\"\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    data = relay.var(\"data\", shape=dshape, dtype=dtype)\n    t0 = relay.transpose(data, (0, 3, 1, 2))\n    w0 = relay.var(\"w0_weight\")\n    conv0 = relay.nn.conv2d(t0, w0, channels=16, kernel_size=(3, 3), padding=(1, 1))\n    t1 = relay.transpose(conv0, (0, 2, 3, 1))\n    w1 = relay.var(\"w1_weight\")\n    t2 = relay.transpose(t1, (0, 3, 1, 2))\n    conv1 = relay.nn.conv2d(t2, w1, channels=32, kernel_size=(1, 1))\n    t3 = relay.transpose(conv1, (0, 2, 3, 1))\n    w2 = relay.var(\"w2_weight\")\n    t4 = relay.transpose(t3, (0, 3, 1, 2))\n    conv2 = relay.nn.conv2d(t4, w2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n    t5 = relay.transpose(conv2, (0, 2, 3, 1))\n    out = relay.add(t3, t5)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net, params = relay.testing.create_workload(net)\n\n    tasks = autotvm.task.extract_from_program(\n        net[\"main\"], target=target, params=params, ops=(conv2d,)\n    )\n    new_args = [\n        _create_args(\n            (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n        _create_args(\n            (1, 16, 8, 8),\n            (32, 16, 1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            layout,\n            layout,\n            dtype,\n            dtype,\n        ),\n        _create_args(\n            (1, 32, 8, 8),\n            (32, 32, 3, 3),\n            (1, 1),\n            (1, 1, 1, 1),\n            (1, 1),\n            layout,\n            layout,\n            dtype,\n            dtype,\n        ),\n    ]\n\n    costs = [0.04, 0.012, 0.03, 0.02, 0.02, 0.045]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [3, 1]],\n            [\"tile_oc\", \"sp\", [4, 4]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [2, 8]],\n            [\"tile_oc\", \"sp\", [1, 32]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [8, 4]],\n            [\"tile_oc\", \"sp\", [4, 8]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 3]],\n            [\"tile_oc\", \"sp\", [2, 8]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [4, 4]],\n            [\"tile_oc\", \"sp\", [2, 16]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [16, 2]],\n            [\"tile_oc\", \"sp\", [8, 4]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n\n    records = []\n    new_args = new_args + new_args\n    tasks = tasks + tasks\n    for args, cost, config, task in zip(new_args, costs, config_list, tasks):\n        task.args = args\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    ltf_records = []\n    ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), \"NCHW8c\", \"NCHW512c\"]\n    ltf_task = autotvm.task.create(\"layout_transform\", ltf_arg, target)\n    ms_input = MeasureInput(target=target, task=ltf_task, config=None)\n    ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1)\n    ltf_records.append((ms_input, ms_output))\n\n    executor = DPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n    executor = PBQPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n\ndef test_tuple():\n    target = \"llvm\"\n    dtype = \"float32\"\n    dshape = (1, 5, 32, 32)\n    layout = \"NCHW\"\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    data = relay.var(\"data\", shape=dshape, dtype=dtype)\n    w0 = relay.var(\"w0_weight\")\n    conv0 = relay.nn.conv2d(data, w0, channels=2, kernel_size=(3, 3), padding=(1, 1))\n    w1 = relay.var(\"w1_weight\")\n    conv1 = relay.nn.conv2d(data, w1, channels=3, kernel_size=(3, 3), padding=(1, 1))\n    out = relay.concatenate([conv0, conv1], axis=1)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net, params = relay.testing.create_workload(net)\n\n    tasks = autotvm.task.extract_from_program(\n        net[\"main\"], target=target, params=params, ops=(conv2d,)\n    )\n    new_args = [\n        _create_args(\n            (1, 5, 32, 32), (2, 5, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n        _create_args(\n            (1, 5, 32, 32), (3, 5, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n    ]\n    costs = [0.01, 0.012, 0.03, 0.04]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 5]],\n            [\"tile_oc\", \"sp\", [1, 2]],\n            [\"tile_ow\", \"sp\", [4, 8]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 5]],\n            [\"tile_oc\", \"sp\", [1, 3]],\n            [\"tile_ow\", \"sp\", [2, 16]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 5]],\n            [\"tile_oc\", \"sp\", [2, 1]],\n            [\"tile_ow\", \"sp\", [4, 8]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 5]],\n            [\"tile_oc\", \"sp\", [3, 1]],\n            [\"tile_ow\", \"sp\", [2, 16]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n\n    records = []\n    new_args = new_args + new_args\n    tasks = tasks + tasks\n    for args, cost, config, task in zip(new_args, costs, config_list, tasks):\n        task.args = args\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    ltf_records = []\n    ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), \"NCHW8c\", \"NCHW512c\"]\n    ltf_task = autotvm.task.create(\"layout_transform\", ltf_arg, target)\n    ms_input = MeasureInput(target=target, task=ltf_task, config=None)\n    ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1)\n    ltf_records.append((ms_input, ms_output))\n\n    executor = DPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[2][0].config, records[1][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n    executor = PBQPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[2][0].config, records[1][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n\ndef test_triangle_block():\n    target = \"llvm\"\n    dtype = \"float32\"\n    dshape = (1, 3, 8, 8)\n    layout = \"NCHW\"\n    conv2d = relay.op.get(\"nn.conv2d\")\n    target_ops = [conv2d]\n\n    data = relay.var(\"data\", shape=dshape, dtype=dtype)\n    w0 = relay.var(\"w0_weight\")\n    conv0 = relay.nn.conv2d(data, w0, channels=16, kernel_size=(3, 3), padding=(1, 1))\n    w1 = relay.var(\"w1_weight\")\n    conv1 = relay.nn.conv2d(conv0, w1, channels=32, kernel_size=(1, 1))\n    w2 = relay.var(\"w2_weight\")\n    conv2 = relay.nn.conv2d(data, w2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n    out = relay.concatenate([conv0, conv1, conv2], axis=1)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net, params = relay.testing.create_workload(net)\n\n    tasks = autotvm.task.extract_from_program(\n        net[\"main\"], target=target, params=params, ops=(conv2d,)\n    )\n    new_args = [\n        _create_args(\n            (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n        _create_args(\n            (1, 16, 8, 8),\n            (32, 16, 1, 1),\n            (1, 1),\n            (0, 0, 0, 0),\n            (1, 1),\n            layout,\n            layout,\n            dtype,\n            dtype,\n        ),\n        _create_args(\n            (1, 3, 8, 8), (32, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype\n        ),\n    ]\n    costs = [0.04, 0.012, 0.03, 0.02, 0.02, 0.045]\n    config_list = []\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [3, 1]],\n            [\"tile_oc\", \"sp\", [4, 4]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [2, 8]],\n            [\"tile_oc\", \"sp\", [1, 32]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [8, 4]],\n            [\"tile_oc\", \"sp\", [4, 8]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [1, 3]],\n            [\"tile_oc\", \"sp\", [2, 8]],\n            [\"tile_ow\", \"sp\", [4, 2]],\n            [\"unroll_kw\", \"ot\", True],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [4, 4]],\n            [\"tile_oc\", \"sp\", [2, 16]],\n            [\"tile_oh\", \"ot\", 1],\n            [\"tile_ow\", \"sp\", [4, 2]],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n    cfg_dict = {\n        \"index\": -1,\n        \"code_hash\": None,\n        \"entity\": [\n            [\"tile_ic\", \"sp\", [16, 2]],\n            [\"tile_oc\", \"sp\", [8, 4]],\n            [\"tile_ow\", \"sp\", [2, 4]],\n            [\"unroll_kw\", \"ot\", False],\n        ],\n    }\n    config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n\n    records = []\n    new_args = new_args + new_args\n    tasks = tasks + tasks\n    for args, cost, config, task in zip(new_args, costs, config_list, tasks):\n        task.args = args\n        ms_input = MeasureInput(target=target, task=task, config=config)\n        ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n        records.append((ms_input, ms_output))\n\n    ltf_records = []\n    ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), \"NCHW8c\", \"NCHW512c\"]\n    ltf_task = autotvm.task.create(\"layout_transform\", ltf_arg, target)\n    ms_input = MeasureInput(target=target, task=ltf_task, config=None)\n    ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1)\n    ltf_records.append((ms_input, ms_output))\n\n    executor = DPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n    executor = PBQPTuner(net, {\"data\": dshape}, records, target_ops, target)\n    executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n    executor.run()\n    out = [record[0].config for record in executor.get_optimal_records()]\n    expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n    assert expected_out == out, \"Output mismatch: expecting %s but got %s\" % (\n        str(expected_out),\n        str(out),\n    )\n\n\nif __name__ == \"__main__\":\n    test_graph_tuner_layout_transform()\n    test_DPTuner_run()\n    test_PBQPTuner_run()\n    test_many_sub_graphs()\n    test_tuple()\n    test_triangle_block()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_graph_tuner_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# NOTE: We name this test file to start with test_graph_tuner\n# to make it execute after zero_rank tensor test cases. This\n# helps avoid topi arithmetic operator overloading issue:\n# https://github.com/apache/tvm/issues/3240\n# TODO: restore the file name after this issue is resolved.\nimport pytest\n\nimport tvm\nfrom tvm import te\n\nfrom tvm import autotvm, relay\nfrom tvm.relay.testing import synthetic\nfrom tvm.autotvm.graph_tuner.utils import (\n    has_multiple_inputs,\n    get_direct_ancestor,\n    get_in_nodes,\n    get_out_nodes,\n    expr2graph,\n    bind_inputs,\n)\nfrom tvm.autotvm.graph_tuner._base import OPT_OUT_OP\nfrom tvm.autotvm.graph_tuner.utils.traverse_graph import _replace_device_with_tracing\nfrom tvm.relay.expr import Call, TupleGetItem, Tuple, Var\n\n\ndef verify_has_multiple_inputs(node_list, node_idx, input_names, expected_result):\n    out = has_multiple_inputs(node_list, node_idx, input_names, OPT_OUT_OP)\n    assert out == expected_result, \"Output mismatch: expecting checking %s to be %s but got %s.\" % (\n        node_list[node_idx][\"op\"],\n        str(expected_result),\n        str(out),\n    )\n\n\ndef test_has_multiple_inputs():\n    data = relay.var(\"data\")\n    out1 = data * relay.expr.const(3.0)\n    w0 = relay.var(\"w0\")\n    out2 = relay.nn.conv2d(data, w0)\n    out = relay.add(out1, out2)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net = bind_inputs(net, {\"data\": (1, 16, 224, 224), \"w0\": (16, 16, 1, 1)})\n    target_ops = [relay.op.get(\"nn.conv2d\")]\n    node_list = []\n    node_dict = {}\n    expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target(\"llvm\"))\n    input_names = [\"data\"]\n    verify_has_multiple_inputs(node_list, 2, input_names, False)\n    verify_has_multiple_inputs(node_list, 4, input_names, False)\n    verify_has_multiple_inputs(node_list, 5, input_names, True)\n\n\ndef test_expr2graph():\n    mod, _ = synthetic.get_workload()\n    node_dict = {}\n    node_list = []\n    target_ops = [relay.op.get(\"nn.conv2d\")]\n    op_name_list = []\n\n    def _count_node(node):\n        if isinstance(node, Call):\n            op_name_list.append(node.op)\n        elif isinstance(node, (Var, TupleGetItem, Tuple)):\n            op_name_list.append(None)\n\n    relay.analysis.post_order_visit(mod[\"main\"], _count_node)\n\n    expr2graph(mod[\"main\"], target_ops, node_dict, node_list, tvm.target.Target(\"llvm\"))\n    assert len(node_list) == len(op_name_list)\n    for i, item in enumerate(zip(op_name_list, node_list)):\n        op_name, node = item\n        assert op_name == node[\"op\"], \"%dth Node operator mismatch: expecting %s but got %s\" % (\n            i,\n            str(op_name),\n            str(node[\"op\"]),\n        )\n\n\ndef test_get_direct_ancestor():\n    data = relay.var(\"data\")\n    w0 = relay.var(\"w0\")\n    out1 = relay.nn.conv2d(data, w0)\n    out2 = relay.add(out1, data * relay.expr.const(5.0))\n    out3 = out2 + relay.expr.const(2.5)\n    w1 = relay.var(\"w1\")\n    out = relay.nn.conv2d(out3, w1)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net = bind_inputs(net, {\"data\": (1, 16, 224, 224), \"w0\": (16, 16, 1, 1), \"w1\": (16, 16, 1, 1)})\n    target_ops = [relay.op.get(\"nn.conv2d\")]\n    node_list = []\n    node_dict = {}\n    expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target(\"llvm\"))\n    visited_dict = {}\n    input_names = [\"data\"]\n    out = get_direct_ancestor(node_list, visited_dict, target_ops, 5, input_names)\n    assert out == [0], \"Output mismatch: expecting [0] but got %s.\" % str(out)\n\n    # non-regression test\n    out = relay.add(relay.log(data), relay.sqrt(data))\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net = bind_inputs(net, {\"data\": (1, 16, 224, 224)})\n    node_list = []\n    node_dict = {}\n    expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target(\"llvm\"))\n    out = get_direct_ancestor(node_list, visited_dict, target_ops, 3, input_names)\n    assert out == [0], \"Output mismatch: expecting [0] but got %s.\" % str(out)\n\n\ndef test_get_in_nodes():\n    data = relay.var(\"data\")\n    w0 = relay.var(\"w0\")\n    out1 = relay.nn.conv2d(data, w0)\n    out2 = relay.add(out1, data)\n    out3 = out2 + relay.expr.const(2.5)\n    w1 = relay.var(\"w1\")\n    out = relay.nn.conv2d(out3, w1)\n    net = relay.Function(relay.analysis.free_vars(out), out)\n    net = bind_inputs(net, {\"data\": (1, 16, 224, 224), \"w0\": (16, 16, 1, 1), \"w1\": (16, 16, 1, 1)})\n    target_ops = [relay.op.get(\"nn.conv2d\")]\n    input_names = [\"data\"]\n    node_list = []\n    node_dict = {}\n    expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target(\"llvm\"))\n    out = get_in_nodes(node_list, target_ops, input_names)\n    expected_out = {3: [0], 4: [3, 0], 7: [4]}\n    diff_set = set(out) ^ set(expected_out)\n    if len(diff_set) != 0:\n        raise RuntimeError(\n            \"Output mismatch: expecting %s but got %s.\" % (str(expected_out), str(out))\n        )\n\n\ndef test_get_out_nodes():\n    in_nodes_dict = {8: [4], 4: [3, 0], 3: [0]}\n    expected_out = {0: [3, 4], 3: [4], 4: [8], 8: []}\n    out = get_out_nodes(in_nodes_dict)\n    diff_set = set(out) ^ set(expected_out)\n    if len(diff_set) != 0:\n        raise RuntimeError(\n            \"Output mismatch: expecting %s but got %s.\" % (str(expected_out), str(out))\n        )\n\n\ndef test_target_device_replacement():\n    assert _replace_device_with_tracing(\"cuda\") == \"cuda -device=tracing\"\n    assert (\n        _replace_device_with_tracing(\"cuda -device=some_device -libs=cudnn\")\n        == \"cuda -device=tracing -libs=cudnn\"\n    )\n    assert (\n        _replace_device_with_tracing(\"llvm -device=arm_cpu -arg=xxx\")\n        == \"llvm -device=tracing -arg=xxx\"\n    )\n    assert _replace_device_with_tracing(\"llvm -device=arm_cpu\") == \"llvm -device=tracing\"\n    assert _replace_device_with_tracing(\"llvm -device=abc, def\") == \"llvm -device=tracing\"\n\n\nif __name__ == \"__main__\":\n    test_has_multiple_inputs()\n    test_expr2graph()\n    test_get_direct_ancestor()\n    test_get_in_nodes()\n    test_get_out_nodes()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_index_tuner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test index based tuners\"\"\"\n\nimport multiprocessing\nfrom tvm.testing.autotvm import DummyRunner, get_sample_task\nfrom tvm import autotvm\n\n\ndef test_grid_search_tuner():\n    \"\"\"Test GridSearchTuner\"\"\"\n\n    task, _ = get_sample_task()\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n\n    # When no range index, range_length should be the length of config space\n    tuner = autotvm.tuner.GridSearchTuner(task)\n    assert tuner.begin_idx == 0\n    assert tuner.end_idx == 64\n    assert tuner.index == 0\n    assert tuner.range_length == 64\n    assert tuner.visited_max == 64\n\n    # With range index, range_length should be the length of the specified range\n    tuner = autotvm.tuner.GridSearchTuner(task, range_idx=(8, 15))\n    assert tuner.begin_idx == 8\n    assert tuner.end_idx == 16\n    assert tuner.index == 8\n    assert tuner.range_length == 8\n    assert tuner.visited_max == 8\n\n    # Tuner should only focus on the specified range\n    tuner.tune(n_trial=8, measure_option=measure_option)\n    assert len(tuner.visited) == 8\n    assert not tuner.has_next()\n\n    # With multi-filter\n    task, _ = get_sample_task()\n    task.config_space.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n\n    tuner = autotvm.tuner.GridSearchTuner(task)\n    assert tuner.begin_idx == 0\n    assert tuner.end_idx == 64\n    assert tuner.index == 5\n    assert tuner.range_length == 64\n    assert tuner.visited_max == 34\n\n    # With range index, range_length should be the length of the specified range\n    tuner = autotvm.tuner.GridSearchTuner(task, range_idx=(8, 15))\n    assert tuner.begin_idx == 8\n    assert tuner.end_idx == 16\n    assert tuner.index == 12\n    assert tuner.range_length == 8\n    assert tuner.visited_max == 4\n\n    # Tuner should only focus on the specified range\n    tuner.tune(n_trial=8, measure_option=measure_option)\n    assert len(tuner.visited) == 4\n    assert not tuner.has_next()\n\n\ndef grid_search_spawn():\n    assert multiprocessing.get_spawn_method(False) == \"spawn\"\n    test_grid_search_tuner()\n\n\ndef test_grid_search_tuner_spawn():\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=test_grid_search_tuner)\n    p.start()\n    p.join()\n\n\ndef test_random_tuner():\n    \"\"\"Test RandomTuner\"\"\"\n\n    task, _ = get_sample_task()\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n\n    tuner = autotvm.tuner.RandomTuner(task, range_idx=(8, 15))\n    assert tuner.begin_idx == 8\n    assert tuner.end_idx == 16\n    assert tuner.range_length == 8\n    assert tuner.visited_max == 8\n\n    # Tuner should only focus on the specified range and should visit all indices\n    tuner.tune(n_trial=8, measure_option=measure_option)\n    assert len(tuner.visited) == 8\n    assert not tuner.has_next()\n    for idx in tuner.visited:\n        assert 8 <= idx <= 15\n\n    # With multi-filter\n    task, _ = get_sample_task()\n    task.config_space.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    tuner = autotvm.tuner.RandomTuner(task, range_idx=(8, 15))\n    assert tuner.begin_idx == 8\n    assert tuner.end_idx == 16\n    assert tuner.range_length == 8\n    assert tuner.visited_max == 4\n\n    # Tuner should only focus on the specified range and should visit all indices\n    tuner.tune(n_trial=8, measure_option=measure_option)\n    assert len(tuner.visited) == 4\n    assert not tuner.has_next()\n    for idx in tuner.visited:\n        assert 8 <= idx <= 15\n\n\nif __name__ == \"__main__\":\n    test_grid_search_tuner()\n    test_grid_search_tuner_spawn()\n    test_random_tuner()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_measure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test builder and runner\"\"\"\nimport logging\nimport multiprocessing\nimport concurrent\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.autotvm.measure import executor\nfrom tvm.testing.autotvm import DummyRunner, bad_matmul, get_sample_task\nfrom tvm import autotvm\nfrom tvm.autotvm.measure.measure import MeasureErrorNo, MeasureResult\nfrom tvm.autotvm import measure\nfrom inspect import Signature\n\n\ndef test_task_tuner_without_measurement():\n    \"\"\"test task and tuner without measurement\"\"\"\n    task, _ = get_sample_task()\n\n    measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner())\n\n    logging.info(\"%s\", task.config_space)\n\n    for tuner_class in [\n        autotvm.tuner.RandomTuner,\n        autotvm.tuner.GridSearchTuner,\n        autotvm.tuner.GATuner,\n        autotvm.tuner.XGBTuner,\n    ]:\n        tuner = tuner_class(task)\n        tuner.tune(n_trial=10, measure_option=measure_option)\n        assert tuner.best_flops > 1\n\n\ndef task_tuner_spawn():\n    assert multiprocessing.get_start_method(False) == \"spawn\"\n    test_task_tuner_without_measurement()\n\n\ndef test_task_tuner_without_measurement_spawn():\n    # Subprocesses inherit the spawn method of their parents\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=task_tuner_spawn)\n    p.start()\n    p.join()\n\n\ndef test_task_runner_with_ref_input():\n    \"\"\"test runner ref_input without measurement\"\"\"\n    refinp = [np.random.rand(128, 128) for i in range(3)]\n    runner = measure.LocalRunner()\n    runner.ref_input = refinp\n\n    class DummyExecutor(measure.executor.Executor):\n        def __init__(self):\n            self.ran_dummy_executor = False\n\n        def submit(self, func, *args, **kwargs):\n            self.ran_dummy_executor = True\n            sig = Signature.from_callable(func)\n            assert sig.bind(*args, **kwargs).arguments[\"ref_input\"] == refinp\n            dummy_future = concurrent.futures.Future()\n            dummy_future.set_result(None)\n            return dummy_future\n\n    runner.executor = DummyExecutor()\n    runner.run([None], [None])\n    assert runner.executor.ran_dummy_executor\n\n\nif __name__ == \"__main__\":\n    logging.basicConfig(level=logging.INFO)\n\n    test_task_tuner_without_measurement()\n    test_task_tuner_without_measurement_spawn()\n    test_task_runner_with_ref_input()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_record.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"test the correctness of dump and load of data log\"\"\"\nfrom io import StringIO\nfrom os import PathLike\nimport time\n\nfrom tvm.contrib import utils\n\nfrom tvm import autotvm\nfrom tvm.autotvm.measure import MeasureInput, MeasureResult, MeasureErrorNo\nfrom tvm.autotvm.record import encode, decode, ApplyHistoryBest, measure_str_key\n\nfrom tvm.testing.autotvm import get_sample_task\n\n\ndef test_load_dump():\n    task, target = get_sample_task()\n\n    inp = MeasureInput(target, task, task.config_space.get(0))\n    result = MeasureResult(\n        (2.0, 2.23, 0.23, 0.123, 0.234, 0.123), MeasureErrorNo.NO_ERROR, 2.3, time.time()\n    )\n\n    for protocol in [\"json\", \"pickle\"]:\n        row = encode(inp, result, protocol=protocol)\n        inp_2, result_2 = decode(row, protocol=protocol)\n\n        assert measure_str_key(inp) == measure_str_key(inp_2), \"%s vs %s\" % (\n            measure_str_key(inp),\n            measure_str_key(inp_2),\n        )\n        assert result.costs == result_2.costs\n        assert result.error_no == result_2.error_no\n        assert result.timestamp == result_2.timestamp\n\n\ndef test_file_io():\n    temp = utils.tempdir()\n    file_path = temp.relpath(\"temp.log\")\n\n    tsk, target = get_sample_task()\n    inputs = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(0, 10)]\n    results = [MeasureResult((i,), 0, 0, 0) for i in range(0, 10)]\n\n    invalid_inp = MeasureInput(target, tsk, tsk.config_space.get(10))\n    invalid_res = MeasureResult((10,), 0, 0, 0)\n\n    # Erase the entity map to test if it will be ignored when loading back.\n    invalid_inp.config._entity_map = {}\n\n    with open(file_path, \"w\") as fo:\n        cb = autotvm.callback.log_to_file(fo)\n        cb(None, inputs, results)\n        cb(None, [invalid_inp], [invalid_res])\n\n    ref = zip(inputs, results)\n    for x, y in zip(ref, autotvm.record.load_from_file(file_path)):\n        assert x[1] == y[1]\n\n    # Confirm functionality of multiple file loads\n    hist_best = ApplyHistoryBest([file_path, file_path])\n    x = hist_best.query(target, tsk.workload)\n    assert str(x) == str(inputs[0][2])\n\n\ndef test_apply_history_best(tmpdir):\n    tsk, target = get_sample_task()\n    best = str(tsk.config_space.get(2))\n\n    inputs_batch_1 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(3)]\n    results_batch_1 = [MeasureResult((i,), 0, 0, 0) for i in range(1, 3)]\n    results_batch_1.append(MeasureResult((0.5,), 0, 2.3, 0))\n\n    # Write data out to file\n    filepath_batch_1 = tmpdir / \"batch_1.log\"\n    with open(filepath_batch_1, \"w\") as file:\n        autotvm.callback.log_to_file(file)(None, inputs_batch_1, results_batch_1)\n\n    # Load best results from Path\n    assert isinstance(filepath_batch_1, PathLike)\n    hist_best = ApplyHistoryBest(filepath_batch_1)\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Load best results from str(Path)\n    hist_best = ApplyHistoryBest(str(filepath_batch_1))\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Write data into StringIO buffer\n    stringio_batch_1 = StringIO()\n    assert isinstance(filepath_batch_1, PathLike)\n    callback = autotvm.callback.log_to_file(stringio_batch_1)\n    callback(None, inputs_batch_1, results_batch_1)\n    stringio_batch_1.seek(0)\n\n    # Load best results from strIO\n    hist_best = ApplyHistoryBest(stringio_batch_1)\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Load best result from list of tuples (MeasureInput, MeasureResult)\n    hist_best = ApplyHistoryBest(list(zip(inputs_batch_1, results_batch_1)))\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Same thing, but iterable instead of list (i.e. no subscripting)\n    hist_best = ApplyHistoryBest(zip(inputs_batch_1, results_batch_1))\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n\ndef test_apply_history_best_multiple_batches(tmpdir):\n    tsk, target = get_sample_task()\n    best = str(tsk.config_space.get(2))\n\n    inputs_batch_1 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(2)]\n    results_batch_1 = [MeasureResult((i,), 0, 0, 0) for i in range(1, 3)]\n    filepath_batch_1 = tmpdir / \"batch_1.log\"\n    with open(filepath_batch_1, \"w\") as file:\n        autotvm.callback.log_to_file(file)(None, inputs_batch_1, results_batch_1)\n\n    inputs_batch_2 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(2, 4)]\n    results_batch_2 = [MeasureResult((0.5,), 0, 0, 0), MeasureResult((3,), 0, 0, 0)]\n    filepath_batch_2 = tmpdir / \"batch_2.log\"\n    with open(filepath_batch_2, \"w\") as file:\n        autotvm.callback.log_to_file(file)(None, inputs_batch_2, results_batch_2)\n\n    # Check two Path filepaths works\n    hist_best = ApplyHistoryBest([filepath_batch_1, filepath_batch_2])\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Check that an arbitrary Iterable of Paths works\n    # Calling zip() on a single list gives a non-subscriptable Iterable\n    hist_best = ApplyHistoryBest(zip([filepath_batch_1, filepath_batch_2]))\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n    # Check that Iterable of Iterable of tuples is correctly merged\n    hist_best = ApplyHistoryBest(\n        zip(\n            [\n                zip(inputs_batch_1, results_batch_1),\n                zip(inputs_batch_2, results_batch_2),\n            ]\n        )\n    )\n    assert str(hist_best.query(target, tsk.workload)) == best\n\n\nif __name__ == \"__main__\":\n    test_load_dump()\n    test_apply_history_best()\n    test_file_io()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_space.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test space definition primitives\"\"\"\n\nfrom tvm import te\nfrom tvm.autotvm.task.space import ConfigSpace, FallbackConfigEntity\n\n\ndef gemm_func(cfg, N, filter_y=None, filter_x=None):\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"B\")\n\n    k = te.reduce_axis((0, N), name=\"k\")\n    C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=[k]), name=\"C\")\n\n    s = te.create_schedule([C.op])\n\n    y, x = s[C].op.axis\n\n    cfg.define_split(\"tile_y\", cfg.axis(y), num_outputs=2, filter=filter_y)\n    cfg.define_split(\"tile_x\", cfg.axis(x), num_outputs=2, filter=filter_x)\n\n    return s, [A, B, C]\n\n\ndef test_split():\n    cfg = ConfigSpace()\n\n    gemm_func(cfg, 128)\n    assert cfg.range_length == 64\n    assert len(cfg.space_map[\"tile_y\"]) == 8\n\n    # test policy\n    cfg = ConfigSpace()\n    cfg.define_split(\"tile_x\", cfg.axis(256), policy=\"factors\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_x\"]) == 45\n\n    cfg.define_split(\"tile_y\", cfg.axis(256), policy=\"power2\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_y\"]) == 45\n\n    cfg.define_split(\"tile_z\", cfg.axis(256), policy=\"verbose\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_z\"]) == 45\n\n    cfg.define_split(\"tile_a\", cfg.axis(224), policy=\"factors\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_a\"]) == 63\n\n    cfg.define_split(\"tile_b\", cfg.axis(224), policy=\"power2\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_b\"]) == 36\n\n    cfg.define_split(\"tile_c\", cfg.axis(224), policy=\"verbose\", num_outputs=3)\n    assert len(cfg.space_map[\"tile_c\"]) == 84\n\n    # Count the number of non-negative integer solutions of a + b + c + d = n\n    def count4(n):\n        cnt = 0\n        for a in range(0, n + 1):\n            for b in range(0, n - a + 1):\n                cnt += n - a - b + 1\n        return cnt\n\n    # test overflow\n    n = 25\n    cfg = ConfigSpace()\n    cfg.define_split(\"x\", cfg.axis(2**n), policy=\"factors\", num_outputs=4)\n    # count4(25) is 3276.\n    assert len(cfg.space_map[\"x\"]) == count4(n)\n\n    # test fallback\n    cfg = FallbackConfigEntity()\n    cfg.define_split(\"tile_n\", cfg.axis(128), num_outputs=3)\n    cfg.fallback_split(\"tile_n\", [-1, 8, 4])\n    # verify if define_split override previously manualy defined split params\n    cfg.define_split(\"tile_n\", cfg.axis(128), num_outputs=3)\n    assert cfg[\"tile_n\"].size == [4, 8, 4]\n\n    cfg = FallbackConfigEntity()\n    cfg.define_split(\"tile_n\", cfg.axis(49), num_outputs=3)\n    cfg.fallback_split(\"tile_n\", [-1, 8, 4])\n    assert cfg[\"tile_n\"].size == [7, 7, 1]\n\n    cfg = FallbackConfigEntity()\n    cfg.define_split(\"tile_n\", cfg.axis(49), num_outputs=3)\n    try:\n        cfg.fallback_split(\"tile_n\", [-1, 1, 0])\n        assert False\n    except RuntimeError:\n        pass\n\n\ndef _raises_exception(f):\n    try:\n        f()\n    except Exception:\n        return True\n    return False\n\n\ndef test_multi_filter():\n    # create config without multi_filter\n    cfg = ConfigSpace()\n    gemm_func(cfg, 128)\n    # create config with multi_filter\n    cfg_mf = ConfigSpace()\n    gemm_func(cfg_mf, 128)\n    cfg_mf.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    # test len\n    assert len(cfg) == 64\n    assert len(cfg_mf) == 34\n    # test range_length\n    assert cfg.range_length == 64\n    assert cfg_mf.range_length == 64\n    # test dims\n    assert cfg.dims == [8, 8]\n    assert cfg_mf.dims == [8, 8]\n    # test is_index_valid\n    assert cfg.is_index_valid(0) is True\n    assert cfg.is_index_valid(15) is True\n    assert cfg_mf.is_index_valid(0) is False\n    assert cfg_mf.is_index_valid(15) is True\n    # test get\n    assert _raises_exception(lambda: cfg.get(0)) is False\n    assert _raises_exception(lambda: cfg.get(15)) is False\n    assert _raises_exception(lambda: cfg_mf.get(0)) is True\n    assert _raises_exception(lambda: cfg_mf.get(15)) is False\n    # test subrange_length\n    assert cfg.subrange_length(0, 64) == 64\n    assert cfg.subrange_length(0, 32) == 32\n    assert cfg.subrange_length(16, 32) == 16\n    assert cfg.subrange_length(16, 16) == 0\n    assert _raises_exception(lambda: cfg.subrange_length(0, 128))\n    assert _raises_exception(lambda: cfg.subrange_length(-64, 64))\n    assert _raises_exception(lambda: cfg.subrange_length(64, 0))\n    assert cfg_mf.subrange_length(0, 64) == 34\n    assert cfg_mf.subrange_length(0, 32) == 17\n    assert cfg_mf.subrange_length(16, 32) == 10\n    assert cfg_mf.subrange_length(16, 16) == 0\n    assert _raises_exception(lambda: cfg_mf.subrange_length(0, 128))\n    assert _raises_exception(lambda: cfg_mf.subrange_length(-64, 64))\n    assert _raises_exception(lambda: cfg_mf.subrange_length(64, 0))\n    # test point2knob\n    assert cfg.point2knob(0) == [0, 0]\n    assert cfg.point2knob(4) == [4, 0]\n    assert cfg.point2knob(8) == [0, 1]\n    assert cfg.point2knob(12) == [4, 1]\n    assert cfg_mf.point2knob(0) == [0, 0]\n    assert cfg_mf.point2knob(4) == [4, 0]\n    assert cfg_mf.point2knob(8) == [0, 1]\n    assert cfg_mf.point2knob(12) == [4, 1]\n    # test knob2point\n    assert cfg.knob2point([0, 0]) == 0\n    assert cfg.knob2point([4, 0]) == 4\n    assert cfg.knob2point([0, 1]) == 8\n    assert cfg.knob2point([4, 1]) == 12\n    assert cfg_mf.knob2point([0, 0]) == 0\n    assert cfg_mf.knob2point([4, 0]) == 4\n    assert cfg_mf.knob2point([0, 1]) == 8\n    assert cfg_mf.knob2point([4, 1]) == 12\n    # get_rand_index\n    cfg_valid_indexes = list(filter(lambda idx: cfg.is_index_valid(idx), range(cfg.range_length)))\n    assert cfg.get_rand_index() in cfg_valid_indexes\n    assert cfg.get_rand_index(start=15, end=16) == 15\n    assert 10 <= cfg.get_rand_index(start=10, end=20) < 20\n    assert cfg.get_rand_index(to_exclude=cfg_valid_indexes[:-1]) == cfg_valid_indexes[-1:][0]\n    cfg_mf_valid_indexes = list(\n        filter(lambda idx: cfg_mf.is_index_valid(idx), range(cfg_mf.range_length))\n    )\n    assert cfg_mf.get_rand_index() in cfg_mf_valid_indexes\n    assert cfg_mf.get_rand_index(start=15, end=16) == 15\n    assert 10 <= cfg_mf.get_rand_index(start=10, end=20) < 20\n    assert (\n        cfg_mf.get_rand_index(to_exclude=cfg_mf_valid_indexes[:-1]) == cfg_mf_valid_indexes[-1:][0]\n    )\n    # get_next_index\n    assert cfg.get_next_index(0) == 1\n    assert cfg.get_next_index(0, 1) == 1\n    assert cfg.get_next_index(0, 2) == 2\n    assert cfg.get_next_index(0, -1) is None\n    assert cfg.get_next_index(0, -2) is None\n    assert cfg.get_next_index(63) is None\n    assert cfg.get_next_index(63, 1) is None\n    assert cfg.get_next_index(63, 2) is None\n    assert cfg.get_next_index(63, -1) == 62\n    assert cfg.get_next_index(63, -2) == 61\n    assert cfg.get_next_index(60, 1, end=63) == 61\n    assert cfg.get_next_index(63, -1, start=60) == 62\n    assert cfg_mf.get_next_index(0) == 5\n    assert cfg_mf.get_next_index(0, 1) == 5\n    assert cfg_mf.get_next_index(0, 2) == 6\n    assert cfg_mf.get_next_index(0, -1) is None\n    assert cfg_mf.get_next_index(0, -2) is None\n    assert cfg_mf.get_next_index(63) is None\n    assert cfg_mf.get_next_index(63, 1) is None\n    assert cfg_mf.get_next_index(63, 2) is None\n    assert cfg_mf.get_next_index(63, -1) == 58\n    assert cfg_mf.get_next_index(63, -2) == 57\n    assert cfg_mf.get_next_index(60, 1, end=63) is None\n    assert cfg_mf.get_next_index(63, -1, start=60) is None\n    # test sample_ints\n    cfg_ints = cfg.sample_ints(5)\n    assert len(cfg_ints) == 5\n    assert set(cfg_ints).issubset(cfg_valid_indexes)\n    cfg_mf_ints = cfg_mf.sample_ints(5)\n    assert len(cfg_mf_ints) == 5\n    assert set(cfg_mf_ints).issubset(cfg_mf_valid_indexes)\n    # test random_walk\n    cfg_walk = cfg.random_walk(15)\n    assert cfg_walk != 15\n    assert cfg_walk in cfg_valid_indexes\n    cfg_mf_walk = cfg_mf.random_walk(15)\n    assert cfg_mf_walk != 15\n    assert cfg_mf_walk in cfg_mf_valid_indexes\n\n\ndef test_filter_and_multi_filter():\n    # test the order: filter -> multi_filter\n    cfg = ConfigSpace()\n    gemm_func(cfg, 128, filter_y=lambda y: y.size[-1] < 64)\n    # after adding filter\n    assert len(cfg) == 48\n    assert cfg.range_length == 48\n    cfg.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    # after adding multi_filter\n    assert len(cfg) == 27\n    assert cfg.range_length == 48\n\n    # test the order: multi_filter -> filter\n    cfg = ConfigSpace()\n    s, (A, B, C) = gemm_func(cfg, 128, filter_y=None)\n    cfg.multi_filter(\n        filter=lambda entity: 32 <= (entity[\"tile_x\"].size[1] * entity[\"tile_y\"].size[1]) < 1024\n    )\n    # after adding multi_filter\n    assert len(cfg) == 34\n    assert cfg.range_length == 64\n    y, x = s[C].op.axis\n    cfg.define_split(\"tile_y\", cfg.axis(y), num_outputs=2, filter=lambda y: y.size[-1] < 64)\n    # after adding filter\n    assert len(cfg) == 27\n    assert cfg.range_length == 48\n\n\nif __name__ == \"__main__\":\n    test_split()\n    test_multi_filter()\n    test_filter_and_multi_filter()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_autotvm_xgboost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport time\n\nimport multiprocessing\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.autotvm import MeasureInput, MeasureResult\nfrom tvm.autotvm.tuner.xgboost_cost_model import XGBoostCostModel\n\nfrom tvm.testing.autotvm import get_sample_task, get_sample_records\n\n\ndef test_fit():\n    task, target = get_sample_task()\n    records = get_sample_records(n=500)\n\n    base_model = XGBoostCostModel(task, feature_type=\"itervar\", loss_type=\"rank\")\n    base_model.fit_log(records, plan_size=32)\n\n    upper_model = XGBoostCostModel(task, feature_type=\"itervar\", loss_type=\"rank\")\n    upper_model.load_basemodel(base_model)\n\n    xs = np.arange(10)\n    ys = np.arange(10)\n\n    upper_model.fit(xs, ys, plan_size=32)\n\n    # feature lengths are not guaranteed to always be the same\n    upper_model.predict(np.ones(12))\n    upper_model.predict(np.ones(8))\n\n\ndef fit_spawn():\n    assert multiprocessing.get_start_method(False) == \"spawn\"\n    test_fit()\n\n\ndef test_fit_spawn():\n    # Subprocesses inherit the spawn method of their parents\n    ctx = multiprocessing.get_context(\"spawn\")\n    p = ctx.Process(target=test_fit)\n    p.start()\n    p.join()\n\n\ndef test_tuner():\n    task, target = get_sample_task()\n    records = get_sample_records(n=10)\n\n    tuner = autotvm.tuner.XGBTuner(task)\n    tuner.load_history(records, min_seed_records=10)\n    # Confirm that loading history successfully loaded a\n    # base_model.\n    assert tuner.cost_model.base_model is not None\n\n    tuner = autotvm.tuner.XGBTuner(task)\n    tuner.load_history(records, min_seed_records=11)\n    # Confirm that loading history did not load base_model\n    # when not enough records according to `min_seed_records`\n    # are provided\n    assert tuner.cost_model.base_model is None\n\n\ndef test_update():\n    task, target = get_sample_task()\n    tuner = autotvm.tuner.XGBTuner(task)\n    n_records = 5\n    records = get_sample_records(n=n_records)\n    tuner.update([inp for inp, _ in records], [res for _, res in records])\n    assert len(tuner.xs) == n_records\n    assert len(tuner.ys) == n_records\n    assert len(tuner.visited) == n_records\n    assert all(x in tuner.visited for x in tuner.xs)\n\n\nif __name__ == \"__main__\":\n    test_fit()\n    test_fit_spawn()\n    test_tuner()\n    test_update()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_container_structural_equal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm.ir.base import get_first_structural_mismatch\nfrom tvm.runtime import ObjectPath\n\n\ndef get_first_mismatch_ensure_symmetry(a, b):\n    mismatch = get_first_structural_mismatch(a, b)\n    mismatch_swapped = get_first_structural_mismatch(b, a)\n\n    if mismatch is None and mismatch_swapped is None:\n        return None\n\n    if (\n        mismatch is None\n        or mismatch_swapped is None\n        or mismatch[0] != mismatch_swapped[1]\n        or mismatch[1] != mismatch_swapped[0]\n    ):\n        raise AssertionError(\n            \"get_first_structural_mismatch(a, b) and get_first_structural_mismatch(b, a) returned\"\n            \" inconsistent results '{}' and '{}' for a='{}', b='{}'\".format(\n                mismatch, mismatch_swapped, a, b\n            )\n        )\n\n    a_path, b_path = mismatch\n    b_path_swapped, a_path_swapped = mismatch_swapped\n    assert a_path == a_path_swapped\n    assert b_path == b_path_swapped\n\n    return mismatch\n\n\n@pytest.mark.parametrize(\n    \"a, b, expected_a_path, expected_b_path\",\n    [\n        (\n            [1, 2, 3],\n            [1, 4, 3],\n            ObjectPath.root().array_index(1).attr(\"value\"),\n            ObjectPath.root().array_index(1).attr(\"value\"),\n        ),\n        (\n            [1, 2, 3],\n            [10, 2, 30],\n            ObjectPath.root().array_index(0).attr(\"value\"),\n            ObjectPath.root().array_index(0).attr(\"value\"),\n        ),\n        (\n            [1, 3, 4],\n            [1, 2, 3, 4],\n            ObjectPath.root().array_index(1).attr(\"value\"),\n            ObjectPath.root().array_index(1).attr(\"value\"),\n        ),\n        (\n            [1, 2, 3],\n            [1, 2, 3, 4],\n            ObjectPath.root().missing_array_element(3),\n            ObjectPath.root().array_index(3),\n        ),\n        (\n            [],\n            [1],\n            ObjectPath.root().missing_array_element(0),\n            ObjectPath.root().array_index(0),\n        ),\n    ],\n)\ndef test_array_structural_mismatch(a, b, expected_a_path, expected_b_path):\n    a = tvm.runtime.convert(a)\n    b = tvm.runtime.convert(b)\n    a_path, b_path = get_first_mismatch_ensure_symmetry(a, b)\n    assert a_path == expected_a_path\n    assert b_path == expected_b_path\n\n\n@pytest.mark.parametrize(\n    \"contents\",\n    [\n        [],\n        [1],\n        [1, 2, 3],\n    ],\n)\ndef test_array_structural_equal_to_self(contents):\n    a = tvm.runtime.convert(list(contents))\n    b = tvm.runtime.convert(list(contents))\n    assert get_first_mismatch_ensure_symmetry(a, b) is None\n\n\n@pytest.mark.parametrize(\n    \"a, b, expected_a_path, expected_b_path\",\n    [\n        (\n            dict(a=3, b=4),\n            dict(a=3, b=5),\n            ObjectPath.root().map_value(\"b\").attr(\"value\"),\n            ObjectPath.root().map_value(\"b\").attr(\"value\"),\n        ),\n        (\n            dict(a=3, b=4),\n            dict(a=3, b=4, c=5),\n            ObjectPath.root().missing_map_entry(),\n            ObjectPath.root().map_value(\"c\"),\n        ),\n    ],\n)\ndef test_string_map_structural_mismatch(a, b, expected_a_path, expected_b_path):\n    a = tvm.runtime.convert(a)\n    b = tvm.runtime.convert(b)\n    a_path, b_path = get_first_mismatch_ensure_symmetry(a, b)\n    assert a_path == expected_a_path\n    assert b_path == expected_b_path\n\n\n@pytest.mark.parametrize(\n    \"contents\",\n    [\n        dict(),\n        dict(a=1),\n        dict(a=3, b=4, c=5),\n    ],\n)\ndef test_string_structural_equal_to_self(contents):\n    a = tvm.runtime.convert(dict(contents))\n    b = tvm.runtime.convert(dict(contents))\n    assert get_first_mismatch_ensure_symmetry(a, b) is None\n\n\n# The behavior of structural equality for maps with non-string keys is fairly specific\n# to IR variables because it assumes that map keys have been \"mapped\" using\n# `SEqualReducer::FreeVarEqualImpl()`. So we leave this case to TIR tests.\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_crt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport os\nimport pathlib\nimport shutil\nimport pytest\n\npytest.importorskip(\"pty\")\n\nimport pytest\n\nimport tvm\nimport tvm.relay\nimport tvm.testing\nfrom tvm.target import Target\nfrom tvm.relay.backend import Runtime\nfrom tvm.relay.backend import Executor\n\nBUILD = True\nDEBUG = False\n\nTARGET = tvm.target.target.micro(\"host\")\n\n\ndef _make_sess_from_op(temp_dir, op_name, sched, arg_bufs):\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        mod = tvm.build(sched, arg_bufs, Target(TARGET, TARGET), runtime=runtime, name=op_name)\n\n    return _make_session(temp_dir, mod)\n\n\ndef _make_session(temp_dir, mod):\n    template_project_dir = os.path.join(tvm.micro.get_standalone_crt_dir(), \"template\", \"host\")\n    project = tvm.micro.generate_project(\n        template_project_dir, mod, temp_dir / \"project\", {\"verbose\": 1}\n    )\n    project.build()\n    project.flash()\n    return tvm.micro.Session(project.transport())\n\n\ndef _make_add_sess(temp_dir):\n    A = tvm.te.placeholder((2,), dtype=\"int8\")\n    B = tvm.te.placeholder((1,), dtype=\"int8\")\n    C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name=\"C\")\n    sched = tvm.te.create_schedule(C.op)\n    return _make_sess_from_op(temp_dir, \"add\", sched, [A, B, C])\n\n\ndef _make_ident_sess(temp_dir):\n    A = tvm.te.placeholder((2,), dtype=\"int8\")\n    B = tvm.te.compute(A.shape, lambda i: A[i], name=\"B\")\n    sched = tvm.te.create_schedule(B.op)\n    return _make_sess_from_op(temp_dir, \"ident\", sched, [A, B])\n\n\n@tvm.testing.requires_micro\ndef test_compile_runtime():\n    \"\"\"Test compiling the on-device runtime.\"\"\"\n    import tvm.micro\n\n    temp_dir = tvm.contrib.utils.tempdir()\n\n    with _make_add_sess(temp_dir) as sess:\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        system_lib.get_function(\"add\")(A_data, B_data, C_data)\n        assert (C_data.numpy() == np.array([6, 7])).all()\n\n\n@tvm.testing.requires_micro\ndef test_compile_runtime_llvm():\n    \"\"\"Test targeting the on-device runtime with the llvm backend.\"\"\"\n    global TARGET\n    old_target = TARGET\n    try:\n        # NOTE: test_compile_runtime uses the \"c\" backend--re run it using the llvm backend.\n        target_str = str(TARGET)\n        assert target_str.startswith(\"c \")\n        TARGET = tvm.target.Target(\"llvm \" + str(TARGET)[len(\"c \") :])\n\n        test_compile_runtime()\n\n    finally:\n        TARGET = old_target\n\n\n@tvm.testing.requires_micro\ndef test_reset():\n    \"\"\"Test when the remote end resets during a session.\"\"\"\n    import tvm.micro\n    from tvm.micro import transport\n\n    temp_dir = tvm.contrib.utils.tempdir()\n\n    with _make_add_sess(temp_dir) as sess:\n        try:\n            sess._rpc.get_function(\"tvm.testing.reset_server\")()\n            assert False, \"expected to raise SessionTerminatedError; did not raise\"\n        except tvm.micro.SessionTerminatedError:\n            pass\n\n\n@tvm.testing.requires_micro\ndef test_graph_executor():\n    \"\"\"Test use of the graph executor with microTVM.\"\"\"\n\n    ws_root = pathlib.Path(os.path.dirname(__file__) + \"/micro-workspace\")\n    if ws_root.exists():\n        shutil.rmtree(ws_root)\n    temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve())\n    relay_mod = tvm.parser.fromtext(\n        \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8]) {\n          %0 = %a + %b;\n          %0\n      }\"\"\"\n    )\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory = tvm.relay.build(relay_mod, target=TARGET, runtime=runtime)\n\n    def do_test(graph_mod):\n\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"uint8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4, 7], dtype=\"uint8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4, 7])).all()\n\n        assert graph_mod.get_input_index(\"a\") == 0\n        assert graph_mod.get_input_index(\"b\") == 1\n\n        graph_mod.run(a=A_data, b=B_data)\n\n        out = graph_mod.get_output(0)\n        assert (out.numpy() == np.array([6, 10])).all()\n\n    with _make_session(temp_dir, factory) as sess:\n\n        graph_mod_local = tvm.micro.create_local_graph_executor(\n            factory.get_graph_json(), sess.get_system_lib(), sess.device\n        )\n\n        do_test(graph_mod_local)\n\n        graph_mod = tvm.contrib.graph_executor.create(\n            factory.get_graph_json(), sess.get_system_lib(), sess.device\n        )\n\n        do_test(graph_mod)\n\n\n@tvm.testing.requires_micro\ndef test_aot_executor():\n    \"\"\"Test use of the AOT executor with microTVM.\"\"\"\n\n    ws_root = pathlib.Path(os.path.dirname(__file__) + \"/micro-workspace\")\n    if ws_root.exists():\n        shutil.rmtree(ws_root)\n    temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve())\n    relay_mod = tvm.parser.fromtext(\n        \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8]) {\n          %0 = %a + %b;\n          %0\n      }\"\"\"\n    )\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"aot\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory = tvm.relay.build(relay_mod, target=TARGET, runtime=runtime, executor=executor)\n\n    def do_test():\n        aot_executor = tvm.runtime.executor.aot_executor.AotModule(\n            sess._rpc.get_function(\"tvm.aot_executor.create\")(\n                sess.get_system_lib(), sess.device, \"default\"\n            )\n        )\n\n        assert aot_executor.get_input_index(\"a\") == 0\n        assert aot_executor.get_input_index(\"b\") == 1\n\n        assert aot_executor.get_num_inputs() == 2\n        assert aot_executor.get_num_outputs() == 1\n\n        A_np = np.array([[2, 3]], dtype=\"uint8\")\n        B_np = np.array([[4, 7]], dtype=\"uint8\")\n\n        A_data = aot_executor.get_input(\"a\").copyfrom(A_np)\n        B_data = aot_executor.get_input(\"b\").copyfrom(B_np)\n\n        aot_executor.run()\n\n        out = aot_executor.get_output(0)\n        assert (out.numpy() == np.array([6, 10])).all()\n\n        B_np_new = np.array([[5, 8]])\n        aot_executor.set_input(\"b\", B_np_new)\n        assert (B_data.numpy() == B_np_new).all()\n\n    with _make_session(temp_dir, factory) as sess:\n        do_test()\n\n\nenable_usmp, expect_exception = tvm.testing.parameters((True, True), (False, False))\n\n\n@tvm.testing.requires_micro\ndef test_aot_executor_usmp_const_pool(enable_usmp, expect_exception):\n    \"\"\"Test the AOT executor with microTVM using usmp.\n    Test should fail if const pool is supplied to executor\n    as these are currently not supported\n    \"\"\"\n    ws_root = pathlib.Path(os.path.dirname(__file__) + \"/micro-workspace-usmp\")\n    if ws_root.exists():\n        shutil.rmtree(ws_root)\n    temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve())\n    relay_mod = tvm.parser.fromtext(\n        \"\"\"\n      #[version = \"0.0.5\"]\n      def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8], %c : Tensor[(1,2), uint8]) {\n          %0 = %a + %b;\n          %1 = %0 + %c;\n          %1\n      }\"\"\"\n    )\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"aot\")\n    main_func = relay_mod[\"main\"]\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n    B_np = np.array([[4, 7]], dtype=\"uint8\").astype(type_dict[\"b\"])\n    C_np = np.array([[8, 9]], dtype=\"uint8\").astype(type_dict[\"c\"])\n    params = {\"c\": C_np}\n    with tvm.transform.PassContext(\n        opt_level=3, config={\"tir.disable_vectorize\": True, \"tir.usmp.enable\": enable_usmp}\n    ):\n        factory = tvm.relay.build(\n            relay_mod,\n            target=TARGET,\n            runtime=runtime,\n            executor=executor,\n            params=params,\n        )\n\n    def do_test():\n        try:\n            aot_executor = tvm.runtime.executor.aot_executor.AotModule(\n                sess._rpc.get_function(\"tvm.aot_executor.create\")(\n                    sess.get_system_lib(), sess.device, \"default\"\n                )\n            )\n        except tvm._ffi.base.TVMError as e:\n            if expect_exception:\n                return\n            else:\n                raise e\n\n        assert aot_executor.get_input_index(\"a\") == 0\n        assert aot_executor.get_input_index(\"b\") == 1\n\n        assert aot_executor.get_num_inputs() == 2\n        assert aot_executor.get_num_outputs() == 1\n\n        A_np = np.array([[2, 3]], dtype=\"uint8\")\n        B_np = np.array([[4, 7]], dtype=\"uint8\")\n\n        A_data = aot_executor.get_input(\"a\").copyfrom(A_np)\n        B_data = aot_executor.get_input(\"b\").copyfrom(B_np)\n        aot_executor.run()\n\n        out = aot_executor.get_output(0)\n        assert (out.numpy() == np.array([14, 19])).all()\n\n        B_np_new = np.array([[5, 8]])\n        aot_executor.set_input(\"b\", B_np_new)\n        assert (B_data.numpy() == B_np_new).all()\n\n    with _make_session(temp_dir, factory) as sess:\n        do_test()\n\n\n@tvm.testing.requires_micro\ndef test_std_math_functions():\n    \"\"\"Verify that standard math functions can be used.\"\"\"\n    import tvm.micro\n\n    temp_dir = tvm.contrib.utils.tempdir()\n\n    with _make_add_sess(temp_dir) as sess:\n        A_data = tvm.nd.array(np.array([2, 3], dtype=\"int8\"), device=sess.device)\n        assert (A_data.numpy() == np.array([2, 3])).all()\n        B_data = tvm.nd.array(np.array([4], dtype=\"int8\"), device=sess.device)\n        assert (B_data.numpy() == np.array([4])).all()\n        C_data = tvm.nd.array(np.array([0, 0], dtype=\"int8\"), device=sess.device)\n        assert (C_data.numpy() == np.array([0, 0])).all()\n\n        system_lib = sess.get_system_lib()\n        system_lib.get_function(\"add\")(A_data, B_data, C_data)\n\n    temp_dir = tvm.contrib.utils.tempdir()\n    A = tvm.te.placeholder((2,), dtype=\"float32\", name=\"A\")\n    B = tvm.te.compute(A.shape, lambda i: tvm.te.exp(A[i]), name=\"B\")\n    s = tvm.te.create_schedule(B.op)\n\n    with _make_sess_from_op(temp_dir, \"myexpf\", s, [A, B]) as sess:\n        A_data = tvm.nd.array(np.array([2.0, 3.0], dtype=\"float32\"), device=sess.device)\n        B_data = tvm.nd.array(np.array([2.0, 3.0], dtype=\"float32\"), device=sess.device)\n        lib = sess.get_system_lib()\n        func = lib[\"myexpf\"]\n        func(A_data, B_data)\n        np.testing.assert_allclose(B_data.numpy(), np.array([7.389056, 20.085537]))\n\n\n@tvm.testing.requires_micro\ndef test_platform_timer():\n    \"\"\"Verify the platform timer can be used to time remote functions.\"\"\"\n    import tvm.micro\n\n    temp_dir = tvm.contrib.utils.tempdir()\n    A = tvm.te.placeholder((2,), dtype=\"float32\", name=\"A\")\n    B = tvm.te.compute(A.shape, lambda i: tvm.te.exp(A[i]), name=\"B\")\n    s = tvm.te.create_schedule(B.op)\n\n    with _make_sess_from_op(temp_dir, \"myexpf\", s, [A, B]) as sess:\n        A_data = tvm.nd.array(np.array([2.0, 3.0], dtype=\"float32\"), device=sess.device)\n        B_data = tvm.nd.array(np.array([2.0, 3.0], dtype=\"float32\"), device=sess.device)\n        lib = sess.get_system_lib()\n        time_eval_f = lib.time_evaluator(\n            \"myexpf\", sess.device, number=2000, repeat=3, min_repeat_ms=40\n        )\n        result = time_eval_f(A_data, B_data)\n        assert result.mean > 0\n        assert len(result.results) == 3\n\n\n@tvm.testing.requires_micro\ndef test_autotune():\n    \"\"\"Verify that autotune works with micro.\"\"\"\n    import tvm.relay as relay\n    from tvm.micro.testing.utils import check_tune_log\n\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n\n    data = relay.var(\"data\", relay.TensorType((1, 3, 64, 64), \"float32\"))\n    weight = relay.var(\"weight\", relay.TensorType((8, 3, 5, 5), \"float32\"))\n    y = relay.nn.conv2d(\n        data,\n        weight,\n        padding=(2, 2),\n        kernel_size=(5, 5),\n        kernel_layout=\"OIHW\",\n        out_dtype=\"float32\",\n    )\n    f = relay.Function([data, weight], y)\n    mod = tvm.IRModule.from_expr(f)\n    mod = relay.transform.InferType()(mod)\n\n    main_func = mod[\"main\"]\n    shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params}\n    type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params}\n\n    weight_data = np.ones(shape_dict[\"weight\"]).astype(type_dict[\"weight\"])\n    input_data = np.ones(shape_dict[\"data\"]).astype(type_dict[\"data\"])\n    params = {\"weight\": weight_data}\n    inputs = {\"data\": input_data}\n\n    target = tvm.target.target.micro(\"host\")\n    template_project_dir = pathlib.Path(tvm.micro.get_microtvm_template_projects(\"crt\"))\n\n    pass_context = tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True})\n    with pass_context:\n        tasks = tvm.autotvm.task.extract_from_program(mod[\"main\"], {}, target)\n    assert len(tasks) > 0\n\n    module_loader = tvm.micro.AutoTvmModuleLoader(\n        template_project_dir=template_project_dir,\n        project_options={},\n    )\n    builder = tvm.autotvm.LocalBuilder(\n        n_parallel=1,\n        build_kwargs={\"build_option\": {\"tir.disable_vectorize\": True}},\n        do_fork=True,\n        build_func=tvm.micro.autotvm_build_func,\n        runtime=runtime,\n    )\n    runner = tvm.autotvm.LocalRunner(number=1, repeat=1, module_loader=module_loader)\n\n    measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner)\n\n    tune_log_file = pathlib.Path(\"crt_autotune.log\")\n    if tune_log_file.exists():\n        tune_log_file.unlink()\n\n    num_trials = 10\n    for task in tasks:\n        tuner = tvm.autotvm.tuner.GATuner(task)\n        tuner.tune(\n            n_trial=num_trials,\n            measure_option=measure_option,\n            callbacks=[\n                tvm.autotvm.callback.log_to_file(str(tune_log_file)),\n                tvm.autotvm.callback.progress_bar(num_trials, si_prefix=\"M\"),\n            ],\n            si_prefix=\"M\",\n        )\n        assert tuner.best_flops > 0\n\n    # TODO(mehrdadh): commented due to autotuning errors\n    # check_tune_log(tune_log_file)\n\n    # Build without tuning\n    with pass_context:\n        lowered = tvm.relay.build(mod, target=TARGET, runtime=runtime, params=params)\n\n    temp_dir = tvm.contrib.utils.tempdir()\n    project = tvm.micro.generate_project(template_project_dir, lowered, temp_dir / \"project\")\n    project.build()\n    with tvm.micro.Session(project.transport()) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            lowered.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**lowered.get_params())\n        graph_mod.run(**inputs)\n        expected_output = graph_mod.get_output(0).numpy()\n        del graph_mod\n\n    # Build using autotune logs\n    with tvm.autotvm.apply_history_best(str(tune_log_file)):\n        with pass_context:\n            lowered_tuned = tvm.relay.build(mod, target=target, runtime=runtime, params=params)\n\n    temp_dir = tvm.contrib.utils.tempdir()\n    project = tvm.micro.generate_project(template_project_dir, lowered_tuned, temp_dir / \"project\")\n    project.build()\n    with tvm.micro.Session(project.transport()) as session:\n        graph_mod = tvm.micro.create_local_graph_executor(\n            lowered_tuned.get_graph_json(), session.get_system_lib(), session.device\n        )\n        graph_mod.set_input(**lowered_tuned.get_params())\n        graph_mod.run(**inputs)\n        output = graph_mod.get_output(0).numpy()\n        del graph_mod\n\n    tvm.testing.assert_allclose(output, expected_output, rtol=1e-4, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_custom_datatypes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit tests for the Bring Your Own Datatype framework.\n\nTODO(@gussmith23 @hypercubestart) link to documentation\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.topi.testing\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.relay.testing.layers import batch_norm_infer\nfrom tvm.target.datatype import (\n    create_lower_func,\n    create_min_lower_func,\n    lower_call_pure_extern,\n    lower_ite,\n    register,\n    register_min_func,\n    register_op,\n)\nfrom tvm.tir.op import call_pure_extern\n\n\n# note: we can't use relay.testing models because params are randomly initialized,\n# which lead the output to have the same values\n# get mobilenet model from Gluon CV\n# because: https://discuss.tvm.apache.org/t/mobilenet-intermediate-values-are-0/7812\ndef get_mobilenet():\n    dshape = (1, 3, 224, 224)\n    from mxnet.gluon.model_zoo.vision import get_model\n\n    block = get_model(\"mobilenet0.25\", pretrained=True)\n    shape_dict = {\"data\": dshape}\n    return relay.frontend.from_mxnet(block, shape_dict)\n\n\n# use real image instead of random data for end-to-end model training\n# or else output would all be around the same value\ndef get_cat_image(dimensions):\n    from PIL import Image\n    from tvm.contrib.download import download_testdata\n\n    url = \"https://gist.githubusercontent.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png\"\n    dst = \"cat.png\"\n    real_dst = download_testdata(url, dst, module=\"data\")\n    img = Image.open(real_dst).resize(dimensions)\n    # CoreML's standard model image format is BGR\n    img_bgr = np.array(img)[:, :, ::-1]\n    img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :]\n    return np.asarray(img, dtype=\"float32\")\n\n\n# we use a random seed to generate input_data\n# to guarantee stable tests\nnp.random.seed(0)\n\n\ndef convert_ndarray(dst_dtype, array):\n    \"\"\"Converts NDArray(s) into the specified datatype\"\"\"\n    x = relay.var(\"x\", shape=array.shape, dtype=str(array.dtype))\n    cast = relay.Function([x], x.astype(dst_dtype))\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        return relay.create_executor(\"graph\").evaluate(cast)(array)\n\n\ndef change_dtype(src, dst, module, params):\n    \"\"\"Convert constants and functions in module from src type to dst type.\n    Returns changed module and converted params of type dst_type.\n    \"\"\"\n    module = relay.frontend.ChangeDatatype(src, dst)(module)\n    module = relay.transform.InferType()(module)\n    params = {k: convert_ndarray(dst, v) for k, v in params.items()}\n    return module, params\n\n\ndef compare(module, input, src_dtype, dst_dtype, rtol, atol, params={}, target=\"llvm\"):\n    module = relay.transform.InferType()(module)\n    module = relay.transform.SimplifyInference()(module)\n\n    correct = relay.create_executor(\"graph\", mod=module).evaluate()(*input, **params)\n    module, converted_params = change_dtype(src_dtype, dst_dtype, module, params)\n    # converts all inputs to dst_dtype\n    x_converted = [convert_ndarray(dst_dtype, arr) for arr in input]\n\n    # Vectorization is not implemented with custom datatypes\n    with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n        maybe_correct = relay.create_executor(\"graph\", mod=module, target=target).evaluate()(\n            *x_converted, **converted_params\n        )\n        # currently this only works for comparing single output\n        maybe_correct_converted = convert_ndarray(src_dtype, maybe_correct)\n    np.testing.assert_allclose(\n        maybe_correct_converted.numpy(), correct.numpy(), rtol=rtol, atol=atol\n    )\n\n\ndef setup_myfloat():\n    \"\"\"Set up tests for myfloat (a custom datatype that under the hood is float)\n\n    Currently, this registers some custom datatypes using the Bring Your\n    Own Datatypes framework.\n    \"\"\"\n\n    # To use datatype operations in an external library, you should first load\n    # the library containing the datatype implementation:\n    # CDLL(\"libposit.so\", RTLD_GLOBAL)\n    # In this case, the datatype library we are using is built right into TVM,\n    # so we do not need to explicitly load any library.\n\n    # You can pick a code for your datatype arbitrarily, as long as it is\n    # greater than 128 and has not already been chosen.\n    register(\"myfloat\", 131)\n\n    register_op(\n        create_lower_func({(32, 32): \"FloatToCustom32\"}), \"Cast\", \"llvm\", \"float\", \"myfloat\"\n    )\n    register_op(\n        create_lower_func({(32, 32): \"Custom32ToFloat\"}), \"Cast\", \"llvm\", \"myfloat\", \"float\"\n    )\n    register_op(create_lower_func({32: \"Custom32Add\"}), \"Add\", \"llvm\", \"myfloat\")\n    register_op(\n        create_lower_func(\n            {\n                32: \"Custom32Sub\",\n            }\n        ),\n        \"Sub\",\n        \"llvm\",\n        \"myfloat\",\n    )\n    register_op(create_lower_func({32: \"Custom32Mul\"}), \"Mul\", \"llvm\", \"myfloat\")\n    register_op(\n        create_lower_func(\n            {\n                32: \"FloatToCustom32\",\n            }\n        ),\n        \"FloatImm\",\n        \"llvm\",\n        \"myfloat\",\n    )\n    register_op(\n        create_lower_func(\n            {\n                32: \"Custom32Div\",\n            }\n        ),\n        \"Div\",\n        \"llvm\",\n        \"myfloat\",\n    )\n    register_op(create_lower_func({32: \"Custom32Max\"}), \"Max\", \"llvm\", \"myfloat\")\n    register_op(\n        create_lower_func({32: \"Custom32Sqrt\"}),\n        \"Call\",\n        \"llvm\",\n        \"myfloat\",\n        intrinsic_name=\"tir.sqrt\",\n    )\n    register_op(\n        create_lower_func({32: \"Custom32Exp\"}), \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.exp\"\n    )\n    register_op(\n        create_lower_func({32: \"Custom32Log\"}), \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.log\"\n    )\n    register_op(\n        create_lower_func({32: \"Custom32Sigmoid\"}),\n        \"Call\",\n        \"llvm\",\n        \"myfloat\",\n        intrinsic_name=\"tir.sigmoid\",\n    )\n    register_op(\n        create_lower_func({32: \"Custom32Tanh\"}),\n        \"Call\",\n        \"llvm\",\n        \"myfloat\",\n        intrinsic_name=\"tir.tanh\",\n    )\n    register_op(lower_ite, \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.if_then_else\")\n    register_op(\n        lower_call_pure_extern, \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.call_pure_extern\"\n    )\n\n    register_min_func(create_min_lower_func({32: \"MinCustom32\"}, \"myfloat\"), \"myfloat\")\n\n\ndef setup_posites2():\n    \"\"\"Set up tests for posites2\n    Currently, this registers some custom datatypes using the Bring Your\n    Own Datatypes framework.\n    \"\"\"\n\n    # To use datatype operations in an external library, you should first load\n    # the library containing the datatype implementation:\n    # CDLL(\"libposit.so\", RTLD_GLOBAL)\n    # In this case, the datatype library we are using is built right into TVM,\n    # so we do not need to explicitly load any library.\n\n    # You can pick a code for your datatype arbitrarily, as long as it is\n    # greater than 128 and has not already been chosen.\n\n    register(\"posites2\", 132)\n\n    register_op(\n        create_lower_func(\n            {\n                (32, 32): \"FloatToPosit32es2\",\n                (32, 16): \"FloatToPosit16es2\",\n                (32, 8): \"FloatToPosit8es2\",\n            }\n        ),\n        \"Cast\",\n        \"llvm\",\n        \"float\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func(\n            {\n                (32, 32): \"Posit32es2ToFloat\",\n                (16, 32): \"Posit16es2ToFloat\",\n                (8, 32): \"Posit8es2ToFloat\",\n            }\n        ),\n        \"Cast\",\n        \"llvm\",\n        \"posites2\",\n        \"float\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Add\", 16: \"Posit16es2Add\", 8: \"Posit8es2Add\"}),\n        \"Add\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Sub\", 16: \"Posit16es2Sub\", 8: \"Posit8es2Sub\"}),\n        \"Sub\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func(\n            {32: \"FloatToPosit32es2\", 16: \"FloatToPosit16es2\", 8: \"FloatToPosit8es2\"}\n        ),\n        \"FloatImm\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Mul\", 16: \"Posit16es2Mul\", 8: \"Posit8es2Mul\"}),\n        \"Mul\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Div\", 16: \"Posit16es2Div\", 8: \"Posit8es2Div\"}),\n        \"Div\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Max\", 16: \"Posit16es2Max\", 8: \"Posit8es2Max\"}),\n        \"Max\",\n        \"llvm\",\n        \"posites2\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Sqrt\", 16: \"Posit16es2Sqrt\", 8: \"Posit8es2Sqrt\"}),\n        \"Call\",\n        \"llvm\",\n        \"posites2\",\n        intrinsic_name=\"tir.sqrt\",\n    )\n    register_op(lower_ite, \"Call\", \"llvm\", \"posites2\", intrinsic_name=\"tir.if_then_else\")\n    register_op(\n        lower_call_pure_extern, \"Call\", \"llvm\", \"posites2\", intrinsic_name=\"tir.call_pure_extern\"\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Exp\", 16: \"Posit16es2Exp\", 8: \"Posit8es2Exp\"}),\n        \"Call\",\n        \"llvm\",\n        \"posites2\",\n        intrinsic_name=\"tir.exp\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Log\", 16: \"Posit16es2Log\", 8: \"Posit8es2Log\"}),\n        \"Call\",\n        \"llvm\",\n        \"posites2\",\n        intrinsic_name=\"tir.log\",\n    )\n    register_op(\n        create_lower_func(\n            {32: \"Posit32es2Sigmoid\", 16: \"Posit16es2Sigmoid\", 8: \"Posit8es2Sigmoid\"}\n        ),\n        \"Call\",\n        \"llvm\",\n        \"posites2\",\n        intrinsic_name=\"tir.sigmoid\",\n    )\n    register_op(\n        create_lower_func({32: \"Posit32es2Tanh\", 16: \"Posit16es2Tanh\", 8: \"Posit8es2Tanh\"}),\n        \"Call\",\n        \"llvm\",\n        \"posites2\",\n        intrinsic_name=\"tir.tanh\",\n    )\n\n    register_min_func(\n        create_min_lower_func(\n            {32: \"MinPosit32es2\", 16: \"MinPosit16es2\", 8: \"MinPosit8es2\"}, \"posites2\"\n        ),\n        \"posites2\",\n    )\n\n\ndef run_ops(src_dtype, dst_dtype, rtol=1e-7, atol=1e-7):\n    \"\"\"Run the same op, but with two different datatypes\"\"\"\n    # used for unary ops, first shape in binary ops\n    shape1 = (5, 10, 5)\n    # second shape for binary ops\n    shape2 = (5,)\n\n    def check_unary_op(op, src_dtype, dst_dtype, shape):\n        t1 = relay.TensorType(shape, src_dtype)\n        x = relay.var(\"x\", t1)\n        z = op(x)\n        x_data = np.random.rand(*shape).astype(t1.dtype)\n\n        module = tvm.IRModule.from_expr(relay.Function([x], z))\n\n        compare(module, (x_data,), src_dtype, dst_dtype, rtol, atol)\n\n    # test unary ops\n    for op in [\n        relay.nn.softmax,\n        tvm.relay.log,\n        tvm.relay.exp,\n        tvm.relay.sqrt,\n        tvm.relay.rsqrt,\n        tvm.relay.sigmoid,\n        tvm.relay.tanh,\n        relay.nn.relu,\n        relay.nn.batch_flatten,\n    ]:\n        check_unary_op(op, src_dtype, dst_dtype, shape1)\n\n    # test unary ops over 4d data\n    for op in [relay.nn.max_pool2d, relay.nn.avg_pool2d, relay.nn.global_avg_pool2d]:\n        shape_2d = (3, 32, 32, 32)\n        check_unary_op(op, src_dtype, dst_dtype, shape_2d)\n\n    def check_binary_op(opfunc, src_dtype, dst_dtype):\n        t1 = relay.TensorType(shape1, src_dtype)\n        t2 = relay.TensorType(shape2, src_dtype)\n        x = relay.var(\"x\", t1)\n        y = relay.var(\"y\", t2)\n        z = opfunc(x, y)\n        x_data = np.random.rand(*shape1).astype(t1.dtype)\n        y_data = np.random.rand(*shape2).astype(t2.dtype)\n        module = tvm.IRModule.from_expr(relay.Function([x, y], z))\n\n        compare(module, (x_data, y_data), src_dtype, dst_dtype, rtol, atol)\n\n    for op in [\n        relay.add,\n        relay.subtract,\n        relay.divide,\n        relay.multiply,\n    ]:\n        check_binary_op(op, src_dtype, dst_dtype)\n\n    # we would like to test tvm_if_then_else\n    # but Relay.IfNode is not lowered to this intrinsic,\n    # so to keep our tests consistent with relay, we decide to not unit test\n    # Note: tvm_if_then_else is tested as part of the mobile_net model\n\n\ndef run_model(get_workload, input, src_dtype, dst_dtype, rtol=1e-4, atol=1e-4):\n    module, params = get_workload()\n\n    # we don't generate random data here\n    # because then the output data would all be around the same value\n    compare(module, input, src_dtype, dst_dtype, rtol, atol, params)\n\n\ndef run_conv2d(src_dtype, dst_dtype, rtol=1e-7, atol=1e-4):\n    def run_test_conv2d(\n        src_dtype,\n        dst_dtype,\n        scale,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        groups=1,\n        dilation=(1, 1),\n        **attrs,\n    ):\n        x = relay.var(\"x\", shape=dshape, dtype=src_dtype)\n        w = relay.var(\"w\", shape=kshape, dtype=src_dtype)\n        y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs)\n        module = tvm.IRModule.from_expr(relay.Function([x, w], y))\n        data = np.random.uniform(-scale, scale, size=dshape).astype(src_dtype)\n        kernel = np.random.uniform(-scale, scale, size=kshape).astype(src_dtype)\n\n        compare(module, (data, kernel), src_dtype, dst_dtype, rtol, atol)\n\n    # depthwise conv2d\n    dshape = (1, 32, 18, 18)\n    kshape = (32, 1, 3, 3)\n    run_test_conv2d(\n        src_dtype,\n        dst_dtype,\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=32,\n        groups=32,\n        kernel_size=(3, 3),\n    )\n\n    # CUDA is disabled for 'direct' schedule:\n    # https://github.com/dmlc/tvm/pull/3070#issuecomment-486597553\n    # group conv2d\n    dshape = (1, 32, 18, 18)\n    kshape = (32, 4, 3, 3)\n    run_test_conv2d(\n        src_dtype,\n        dst_dtype,\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=32,\n        groups=8,\n        kernel_size=(3, 3),\n    )\n    # also group conv2d\n    dshape = (1, 32, 18, 18)\n    kshape = (64, 1, 3, 3)\n    run_test_conv2d(\n        src_dtype,\n        dst_dtype,\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=64,\n        groups=32,\n        kernel_size=(3, 3),\n    )\n\n    # normal conv2d\n    dshape = (1, 3, 224, 224)\n    kshape = (10, 3, 3, 3)\n    run_test_conv2d(\n        src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3)\n    )\n\n    # dilated conv2d\n    dshape = (1, 3, 18, 18)\n    kshape = (10, 3, 3, 3)\n    run_test_conv2d(\n        src_dtype,\n        dst_dtype,\n        1,\n        dshape,\n        kshape,\n        padding=(1, 1),\n        channels=10,\n        kernel_size=(3, 3),\n        dilation=(3, 3),\n    )\n\n\ndef run_batchnorm(src_dtype, dst_dtype, rtol=1e-6, atol=1e-6):\n    shape = (3, 32, 32)\n    t = relay.TensorType(shape, src_dtype)\n    x = relay.var(\"x\", t)\n    bn = batch_norm_infer(data=x, epsilon=2e-5, scale=False, name=\"bn_x\")\n    f = relay.Function(relay.analysis.free_vars(bn), bn)\n\n    x_data = np.random.rand(*shape).astype(t.dtype)\n    module = tvm.IRModule.from_expr(f)\n\n    zero_data = np.zeros((32), \"float32\")\n    compare(\n        module,\n        (x_data, zero_data, zero_data, zero_data, zero_data),\n        src_dtype,\n        dst_dtype,\n        rtol,\n        atol,\n    )\n\n\ndef test_myfloat():\n    try:\n        setup_myfloat()\n    except tvm._ffi.base.TVMError as e:\n        if \"float is already registered\" not in str(e):\n            # Ignore this specific error which can happen if this test runs twice within the same process\n            raise e\n    run_ops(\"float32\", \"custom[myfloat]32\", rtol=1e-6, atol=1e-6)\n    run_conv2d(\"float32\", \"custom[myfloat]32\", rtol=1e-6, atol=1e-6)\n    run_batchnorm(\"float32\", \"custom[myfloat]32\", rtol=1e-6, atol=1e-6)\n\n    # mxnet python package not available\n    # run_model(get_mobilenet, (get_cat_image((224, 224)), ),\n    #           'float32',\n    #           'custom[myfloat]32')\n\n\ndef _has_posit():\n    return tvm.support.libinfo()[\"USE_BYODT_POSIT\"] == \"ON\"\n\n\n@pytest.mark.skipif(not _has_posit(), reason=\"compiled with USE_BYODT_POSIT flag OFF\")\ndef test_posites2():\n    setup_posites2()\n    run_ops(\"float32\", \"custom[posites2]8\", rtol=1, atol=1)\n    run_ops(\"float32\", \"custom[posites2]16\", rtol=0.01, atol=1)\n    run_ops(\"float32\", \"custom[posites2]32\", rtol=1e-6, atol=1e-6)\n\n    run_conv2d(\"float32\", \"custom[posites2]8\", rtol=1, atol=1)\n    run_conv2d(\"float32\", \"custom[posites2]16\", rtol=0.01, atol=1)\n    run_conv2d(\"float32\", \"custom[posites2]32\")\n\n    run_batchnorm(\"float32\", \"custom[posites2]8\", rtol=1, atol=1)\n    run_batchnorm(\"float32\", \"custom[posites2]16\", rtol=0.01, atol=1)\n    run_batchnorm(\"float32\", \"custom[posites2]32\", rtol=1e-4, atol=1e-4)\n    # Expected posit8 might be faster, but it's not.\n    # run_model(get_mobilenet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit8]8')\n    # run_model(get_mobilenet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit32]32')\n    # run_model(get_inception, (get_cat_image((229, 229)), ), 'float32', 'custom[posit32]32')\n    # run_model(get_resnet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit32]32')\n\n    # can't run cifar-10 sizes because dimensions\n    # don't match pretrained weights\n\n    # runs on the order of minutes...\n    # run_model(get_inception, (get_cat_image((229, 229)), ),\n    #           'float32',\n    #           'custom[posites2]32')\n    # run_model(get_resnet, (get_cat_image((224, 224)), ),\n    #           'float32',\n    #           'custom[posites2]32')\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_div_to_mul.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay\nimport pytest\nimport numpy as np\n\n\n@pytest.mark.parametrize(\"dtype, rtol\", [(\"float16\", 1e-3), (\"float32\", 1e-7), (\"float64\", 1e-12)])\ndef test_div_to_mul(dtype, rtol):\n    x = relay.var(\"x\", relay.TensorType((), dtype))\n    y = relay.Constant(tvm.nd.array(np.array([1.5]).astype(dtype)))\n    z = x / y\n    mod = tvm.IRModule.from_expr(z)\n    transformed = relay.transform.DivToMul()(mod)\n    assert transformed[\"main\"].body.op.name == \"multiply\"\n    np.testing.assert_allclose(transformed[\"main\"].body.args[1].data.numpy()[0], 1 / 1.5, rtol=rtol)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_filter_untracked.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\n\ndef setup_git_repo(worktree=False):\n    git_repo_dir = tempfile.mkdtemp()\n    to_rm = [git_repo_dir]\n    try:\n        subprocess.check_output([\"git\", \"init\", \".\"], cwd=git_repo_dir)\n\n        with open(f\"{git_repo_dir}/committed\", \"w\") as committed_f:\n            committed_f.write(\"normal committed file\\n\")\n\n        subprocess.check_output([\"git\", \"add\", \"committed\"], cwd=git_repo_dir)\n\n        with open(f\"{git_repo_dir}/committed-ignored\", \"w\") as gitignore_f:\n            gitignore_f.write(\"this file is gitignored, but committed already\")\n\n        subprocess.check_output([\"git\", \"add\", \"committed-ignored\"], cwd=git_repo_dir)\n\n        with open(f\"{git_repo_dir}/.gitignore\", \"w\") as gitignore_f:\n            gitignore_f.write(\"ignored\\n\" \"committed-ignored\\n\")\n\n        subprocess.check_output([\"git\", \"add\", \".gitignore\"], cwd=git_repo_dir)\n\n        # NOTE: explicitly set the author so this test passes in the CI.\n        subprocess.check_output(\n            [\n                \"git\",\n                \"-c\",\n                \"user.name=Unit Test\",\n                \"-c\",\n                \"user.email=unit.test@testing.tvm.ai\",\n                \"commit\",\n                \"-m\",\n                \"initial commit\",\n            ],\n            cwd=git_repo_dir,\n        )\n\n        if worktree:\n            worktree_dir = tempfile.mkdtemp()\n            to_rm.append(worktree_dir)\n            subprocess.check_output([\"git\", \"worktree\", \"add\", worktree_dir], cwd=git_repo_dir)\n            git_repo_dir = worktree_dir\n\n        with open(f\"{git_repo_dir}/ignored\", \"w\") as gitignore_f:\n            gitignore_f.write(\"this file is gitignored\")\n\n        with open(f\"{git_repo_dir}/added-to-index\", \"w\") as added_f:\n            added_f.write(\"only added to git index\\n\")\n\n        subprocess.check_output([\"git\", \"add\", \"added-to-index\"], cwd=git_repo_dir)\n\n        with open(f\"{git_repo_dir}/ignored-added-to-index\", \"w\") as ignored_f:\n            ignored_f.write(\"this file is gitignored but in the index already\\n\")\n\n        subprocess.check_output([\"git\", \"add\", \"-f\", \"ignored-added-to-index\"], cwd=git_repo_dir)\n\n        with open(f\"{git_repo_dir}/untracked\", \"w\") as untracked_f:\n            untracked_f.write(\"this file is untracked\\n\")\n\n        os.mkdir(f\"{git_repo_dir}/subdir\")\n        with open(f\"{git_repo_dir}/subdir/untracked\", \"w\") as untracked_f:\n            untracked_f.write(\"this file is untracked\\n\")\n\n        with open(f\"{git_repo_dir}/subdir/untracked2\", \"w\") as untracked_f:\n            untracked_f.write(\"this file is also untracked\\n\")\n\n        return git_repo_dir, to_rm\n\n    except Exception:\n        for rm_dir in to_rm:\n            shutil.rmtree(rm_dir)\n        raise\n\n\ndef run_test(repo_path, passed_files, filtered_files):\n    test_input = (\n        \"\\n\".join(\n            passed_files\n            + filtered_files\n            + [f\"./{f}\" for f in passed_files]\n            + [f\"./{f}\" for f in filtered_files]\n        )\n        + \"\\n\"\n    )\n\n    test_script_dir = f\"{repo_path}/test-script-dir\"\n    os.mkdir(test_script_dir)\n\n    filter_script_path = f\"{test_script_dir}/filter_untracked.py\"\n    test_script_dirname = os.path.dirname(__file__) or os.getcwd()\n    shutil.copy(\n        os.path.realpath(f\"{test_script_dirname}/../../lint/filter_untracked.py\"),\n        filter_script_path,\n    )\n    filter_proc = subprocess.Popen(\n        [sys.executable, filter_script_path],\n        cwd=repo_path,\n        stdin=subprocess.PIPE,\n        stdout=subprocess.PIPE,\n        encoding=\"utf-8\",\n    )\n    filter_output, _ = filter_proc.communicate(test_input)\n    filter_output_lines = [l for l in filter_output.split(\"\\n\") if l]\n\n    for pass_f in passed_files:\n        assert (\n            pass_f in filter_output_lines\n        ), f\"expected in filter output: {pass_f}\\filter output: {filter_output}\"\n        assert (\n            f\"./{pass_f}\" in filter_output_lines\n        ), f\"expected in filter output: ./{pass_f}\\filter output: {filter_output}\"\n\n    for filter_f in filtered_files:\n        assert (\n            filter_f not in filter_output_lines\n        ), f\"expected not in filter output: {filter_f}\\nfilter_output: {filter_output}\"\n        assert (\n            f\"./{filter_f}\" not in filter_output_lines\n        ), f\"expected not in filter output: ./{filter_f}\\nfilter_output: {filter_output}\"\n\n    assert len(filter_output_lines) == 2 * len(\n        passed_files\n    ), f\"expected {len(filter_output_lines)} == 2 * {len(passed_files)}\"\n\n\ndef test_filter_untracked():\n    repo_path, to_rm = setup_git_repo()\n    try:\n        passed_files = [\n            \"committed\",\n            \"committed-ignored\",\n            \"added-to-index\",\n            \"ignored-added-to-index\",\n        ]\n        filtered_files = [\n            \"ignored\",\n            \"untracked\",\n            \"subdir/untracked\",\n            \"subdir/untracked2\",\n        ]\n        run_test(repo_path, passed_files, filtered_files)\n\n    finally:\n        for rm_dir in to_rm:\n            shutil.rmtree(rm_dir)\n\n\ndef test_worktree():\n    repo_path, to_rm = setup_git_repo(worktree=True)\n    try:\n        passed_files = [\n            \"committed\",\n            \"committed-ignored\",\n            \"added-to-index\",\n            \"ignored-added-to-index\",\n        ]\n        filtered_files = [\n            \"ignored\",\n            \"untracked\",\n            \"subdir/untracked\",\n            \"subdir/untracked2\",\n            \".git\",\n        ]\n        run_test(repo_path, passed_files, filtered_files)\n\n    finally:\n        for rm_dir in to_rm:\n            shutil.rmtree(rm_dir)\n\n\nif __name__ == \"__main__\":\n    test_filter_untracked()\n    test_worktree()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_format_si_prefix.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom numpy import isclose\nimport random\nfrom tvm.autotvm import utils\n\n\nSI_PREFIXES = \"yzafpn\\xb5m kMGTPEZY\"\n\n\ndef test_format_si_prefix():\n    # test float conversion\n    assert utils.format_si_prefix(1024, \"k\") == 1.024\n\n    for i, prefix in enumerate(SI_PREFIXES):\n        integer, decimal = random.randint(0, 1000), random.randint(0, 1000)\n        exp = -24 + 3 * i  # 0th prefix (yocto) is 10^-24\n        number = integer * (10**exp) + decimal * (10 ** (exp - 3))\n        expected = integer + decimal / 1000\n        assert isclose(utils.format_si_prefix(number, prefix), expected)\n\n    assert utils.format_si_prefix(0, \"y\") == 0\n\n\nif __name__ == \"__main__\":\n    test_format_si_prefix()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_gen_requirements.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tests for gen_requirements, found in python/.\"\"\"\n\nimport collections\nimport contextlib\nimport os\nimport sys\n\nimport tvm\nimport tvm.testing\n\nimport pytest\n\n# Insert the parent dir to python/tvm into the import path, so that gen_requirements may be\n# imported.\nsys.path.insert(0, os.path.dirname(tvm.__file__))\ntry:\n    import gen_requirements\nfinally:\n    sys.path.pop(0)\n\n\n@contextlib.contextmanager\ndef patch(obj, **kw):\n    old = {}\n    for prop_name, new in kw.items():\n        old[prop_name] = getattr(obj, prop_name)\n        setattr(obj, prop_name, new)\n    yield\n    for prop_name, value in old.items():\n        setattr(obj, prop_name, value)\n\n\nPROBLEM_REQUIREMENTS = [\n    (\"extras-pre-core\", (\"\", [\"foo\", 123])),  # entry before core\n    (456, (\"\", [\"foo\", \"bar\"])),  # invalid extras name, deps should not be processed\n    (\"core\", (\"\", [\"foo\"])),  # ordinary core entry.\n    (\"wrong-description-type\", (None, [\"foo\"])),  # wrong description type\n    (\"bad-value\", None),  # value field is not a 2-tuple\n    (\"bad-value-2\", (\"\", [\"foo\"], 34)),  # value field is not a 2-tuple\n    (\"invalid\", (\"\", [\"qux\"])),  # duplicate invalid entry, all items valid.\n    (\"extras-foo\", (\"\", [\"bar\", \"baz\"])),  # ordinary extras entry.\n    (\"invalid\", (\"\", [\"baz\", None, 123])),  # valid extra name, invalid deps.\n    (\"unsorted\", (\"\", [\"qux\", \"bar\", \"foo\"])),  # deps out of order\n    (\"versioned_dep\", (\"\", [\"baz==1.2\", \"foo==^2.0\", \"buz<3\", \"bar>4\"])),\n    (\"duplicate_dep\", (\"\", [\"buz\", \"buz\", \"foo\"])),  # duplicate listed dependency\n    (\"dev\", (\"\", [\"baz\", \"qux\"])),  # ordinary dev entry.\n    (\"extras-post-dev\", (\"\", [\"bar\", \"buzz\"])),  # entry after dev\n]\n\n\ndef test_validate_requirements():\n    with patch(gen_requirements, REQUIREMENTS_BY_PIECE=None):\n        assert gen_requirements.validate_requirements_by_piece() == [\n            \"must be list or tuple, see None\"\n        ]\n\n    with patch(gen_requirements, REQUIREMENTS_BY_PIECE=PROBLEM_REQUIREMENTS):\n        problems = gen_requirements.validate_requirements_by_piece()\n        assert problems == [\n            'piece extras-pre-core: must list after \"core\" (core must be first)',\n            \"piece extras-pre-core: deps should be a list of strings, got ['foo', 123]\",\n            \"piece 456: must be str\",\n            \"piece wrong-description-type: description should be a string, got None\",\n            (\n                'piece bad-value: should be formatted like (\"bad-value\", (\"<requirements.txt '\n                'comment>\", [\"dep1\", \"dep2\", ...])). got: None'\n            ),\n            (\n                'piece bad-value-2: should be formatted like (\"bad-value-2\", '\n                '(\"<requirements.txt comment>\", [\"dep1\", \"dep2\", ...])). got: (\\'\\', '\n                \"['foo'], 34)\"\n            ),\n            \"piece invalid: listed twice\",\n            \"piece invalid: deps should be a list of strings, got ['baz', None, 123]\",\n            \"piece unsorted: deps must be sorted. Correct order:\\n  ['bar', 'foo', 'qux']\",\n            \"piece versioned_dep: deps must be sorted. Correct order:\\n  ['bar>4', 'baz==1.2', 'buz<3', 'foo==^2.0']\",\n            \"piece versioned_dep: dependency baz==1.2 should not specify a version. Add it to CONSTRAINTS instead.\",\n            \"piece versioned_dep: dependency foo==^2.0 should not specify a version. Add it to CONSTRAINTS instead.\",\n            \"piece versioned_dep: dependency buz<3 should not specify a version. Add it to CONSTRAINTS instead.\",\n            \"piece versioned_dep: dependency bar>4 should not specify a version. Add it to CONSTRAINTS instead.\",\n            \"piece duplicate_dep: dependency buz listed twice\",\n            'piece extras-post-dev: must list before \"dev\" (dev must be last)',\n            'pieces other than \"core\" and \"dev\" must appear in alphabetical order: '\n            \"['bad-value', 'bad-value-2', 'duplicate_dep', 'extras-foo', 'extras-post-dev', \"\n            \"'extras-pre-core', 'invalid', 'invalid', 'unsorted', 'versioned_dep', \"\n            \"'wrong-description-type']\",\n        ]\n\n\nTEST_REQUIREMENTS_BY_PIECE = (\n    (\"core\", (\"core tvm requirements\", (\"bar\", \"foo\", \"non-constrained\"))),\n    (\"extra-one\", (\"requirements for one feature\", (\"baz\", \"qux\"))),\n    (\"extra-two\", (\"requirements for two feature\", (\"buz\", \"qux\", \"semver-minor\", \"semver-patch\"))),\n    (\"dev\", (\"requirements for dev\", (\"buz\", \"oof\", \"rab\"))),\n)\n\n\ndef test_validate_constraints():\n    with patch(\n        gen_requirements,\n        REQUIREMENTS_BY_PIECE=TEST_REQUIREMENTS_BY_PIECE,\n        CONSTRAINTS=(\n            (\"unlisted\", \"~=3\"),\n            (\"double-specified\", \"<2\"),\n            (\n                \"double-specified\",\n                \"==3\",\n            ),\n            (\"bad-constraint\", \"1.2.0\"),\n            (\"bad-semver-constraint\", \"i don't match the regex :P\"),\n            (\"alpha-semver-constraint\", \"^foo.bar.23\"),\n        ),\n    ):\n        problems = gen_requirements.validate_constraints()\n        assert problems == [\n            \"unlisted: not specified in REQUIREMENTS_BY_PIECE\",\n            \"double-specified: not specified in REQUIREMENTS_BY_PIECE\",\n            \"double-specified: specified twice\",\n            \"double-specified: not specified in REQUIREMENTS_BY_PIECE\",\n            \"bad-constraint: not specified in REQUIREMENTS_BY_PIECE\",\n            'bad-constraint: constraint \"1.2.0\" does not look like a valid constraint',\n            \"bad-semver-constraint: not specified in REQUIREMENTS_BY_PIECE\",\n            'bad-semver-constraint: constraint \"i don\\'t match the regex :P\" does not look like a valid constraint',\n            \"alpha-semver-constraint: not specified in REQUIREMENTS_BY_PIECE\",\n            \"alpha-semver-constraint: invalid semver constraint ^foo.bar.23\",\n            \"CONSTRAINTS entries should be in this sorted order: ['alpha-semver-constraint', 'bad-constraint', 'bad-semver-constraint', 'double-specified', 'double-specified', 'unlisted']\",\n        ]\n\n\nTEST_CONSTRAINTS = (\n    (\"bar\", \"==1.0\"),\n    (\"baz\", \">2.3\"),\n    (\"buz\", \"^1.3.0\"),\n    (\"non-constrained\", None),  # Support a comment.\n    (\"oof\", \"==0.3.4\"),\n    (\"qux\", \"~=1.2.4\"),\n    (\"semver-minor\", \"^0.2.2-patch2.post3+buildmeta\"),  # Ensure prerelease and buildmeta preserved.\n    (\"semver-patch\", \"^0.0.2+bm\"),  # Ensure postrelease preserved.\n)\n\n\ndef test_join_requirements():\n    with patch(\n        gen_requirements,\n        REQUIREMENTS_BY_PIECE=TEST_REQUIREMENTS_BY_PIECE,\n        CONSTRAINTS=TEST_CONSTRAINTS,\n    ):\n        requirements = gen_requirements.join_requirements()\n        assert requirements == collections.OrderedDict(\n            [\n                (\"core\", (\"core tvm requirements\", [\"bar==1.0\", \"foo\", \"non-constrained\"])),\n                (\"extra-one\", (\"requirements for one feature\", [\"baz>2.3\", \"qux~=1.2.4\"])),\n                (\n                    \"extra-two\",\n                    (\n                        \"requirements for two feature\",\n                        [\n                            \"buz>=1.3.0,<2.0.0\",\n                            \"qux~=1.2.4\",\n                            \"semver-minor>=0.2.2-patch2.post3+buildmeta,<0.3.0\",\n                            \"semver-patch>=0.0.2+bm,<0.0.3\",\n                        ],\n                    ),\n                ),\n                (\"dev\", (\"requirements for dev\", [\"buz>=1.3.0,<2.0.0\", \"oof==0.3.4\", \"rab\"])),\n                (\n                    \"all-prod\",\n                    (\n                        \"Combined dependencies for all TVM pieces, excluding dev\",\n                        [\n                            \"bar==1.0\",\n                            \"baz>2.3\",\n                            \"buz>=1.3.0,<2.0.0\",\n                            \"foo\",\n                            \"non-constrained\",\n                            \"qux~=1.2.4\",\n                            \"semver-minor>=0.2.2-patch2.post3+buildmeta,<0.3.0\",\n                            \"semver-patch>=0.0.2+bm,<0.0.3\",\n                        ],\n                    ),\n                ),\n            ]\n        )\n\n\ndef test_semver():\n    problems = []\n\n    assert gen_requirements.parse_semver(\"C\", \"^1.2.0\", problems) == ([\"1\", \"2\", \"0\"], 0, 1)\n    assert problems == []\n\n    assert gen_requirements.parse_semver(\"C\", \"^0.2.0\", problems) == ([\"0\", \"2\", \"0\"], 1, 2)\n    assert problems == []\n\n    assert gen_requirements.parse_semver(\"C\", \"^0.0.0\", problems) == ([\"0\", \"0\", \"0\"], 0, 0)\n    assert problems == []\n\n    assert gen_requirements.parse_semver(\"C\", \"^0.a.0\", problems) == ([], 0, 0)\n    assert problems == [\"C: invalid semver constraint ^0.a.0\"]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_index_map.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm.ir import assert_structural_equal\nfrom tvm.tir import IndexMap, IntImm, floordiv, floormod\nfrom tvm.runtime import const\n\n\ndef assert_equal_index_map(map1: IndexMap, map2: IndexMap) -> None:\n\n    iters_1 = map1.map_indices(map2.initial_indices)\n    iters_2 = map2.final_indices\n    assert len(iters_1) == len(iters_2)\n\n    analyzer = tvm.arith.Analyzer()\n    for iter1, iter2 in zip(iters_1, iters_2):\n        assert analyzer.can_prove_equal(iter1, iter2)\n\n\ndef test_index_mapping():\n    index_map = IndexMap.from_func(lambda i: [i // 4, i % 4])\n\n    assert_structural_equal(index_map.map_indices([0]), [0, 0])\n    assert_structural_equal(index_map.map_indices([3]), [0, 3])\n    assert_structural_equal(index_map.map_indices([4]), [1, 0])\n    assert_structural_equal(index_map.map_indices([42]), [10, 2])\n    assert_structural_equal(\n        index_map.map_indices([const(42, \"int64\")]), [const(10, \"int64\"), const(2, \"int64\")]\n    )\n\n\ndef test_shape_mapping():\n    index_map = IndexMap.from_func(lambda i: [i // 4, i % 4])\n\n    assert_structural_equal(index_map.map_shape([4]), [1, 4])\n    assert_structural_equal(index_map.map_shape([16]), [4, 4])\n\n    assert_structural_equal(index_map.map_shape([14]), [4, 4])\n    assert_structural_equal(\n        index_map.map_shape([const(16, \"int64\")]), [const(4, \"int64\"), const(4, \"int64\")]\n    )\n    assert_structural_equal(\n        index_map.map_shape([const(14, \"int64\")]), [const(4, \"int64\"), const(4, \"int64\")]\n    )\n\n\ndef test_inverse():\n    index_map = IndexMap.from_func(lambda i: [i // 4, i % 4])\n    expected_inverse = IndexMap.from_func(lambda i, j: [4 * i + j])\n\n    assert index_map.inverse([16]).is_equivalent_to(expected_inverse)\n\n\ndef test_nonbijective_inverse_gives_error():\n    index_map = IndexMap.from_func(lambda i: [i // 4, i % 4])\n\n    with pytest.raises(tvm.TVMError):\n        index_map.inverse([14])\n\n\ndynamic_N = tvm.tir.Var(\"N\", \"int32\")\npadding_test_case = tvm.testing.parameter(\n    by_dict={\n        \"no_padding\": dict(\n            forward=lambda i: [i // 4, i % 4],\n            inverse=lambda i, j: [4 * i + j],\n            pre_shape=[16],\n            post_shape=[4, 4],\n            padding=lambda i, j: tvm.runtime.convert(False),\n        ),\n        \"right_padding\": dict(\n            forward=lambda i: [i // 4, i % 4],\n            inverse=lambda i, j: [4 * i + j],\n            pre_shape=[15],\n            post_shape=[4, 4],\n            padding=lambda i, j: tvm.tir.And(i == 3, tvm.runtime.convert(3) == j),\n        ),\n        \"left_padding\": dict(\n            forward=lambda i: [(i + 1) // 4, (i + 1) % 4],\n            inverse=lambda i, j: [4 * i + j - 1],\n            pre_shape=[15],\n            post_shape=[4, 4],\n            padding=lambda i, j: tvm.tir.And(i == 0, j < 1),\n        ),\n        \"left_and_right_padding\": dict(\n            forward=lambda i: [(i + 1) // 4, (i + 1) % 4],\n            inverse=lambda i, j: [4 * i + j - 1],\n            pre_shape=[14],\n            post_shape=[4, 4],\n            padding=lambda i, j: tvm.tir.Or(\n                tvm.tir.And(i == 0, j < 1),\n                tvm.tir.And(i == 3, tvm.runtime.convert(3) == j),\n            ),\n        ),\n        \"dynamic_size\": dict(\n            forward=lambda i: [i // 4, i % 4],\n            inverse=lambda i, j: [4 * i + j],\n            pre_shape=[dynamic_N],\n            post_shape=[(dynamic_N - dynamic_N % (-4)) // 4, 4],\n            padding=lambda i, j: tvm.tir.And(\n                dynamic_N % (-4) != 0,\n                tvm.tir.And(i == dynamic_N // 4, j >= dynamic_N % 4),\n            ),\n        ),\n        \"2d_padding\": dict(\n            forward=lambda i, j: [(i + 1) // 4, (j + 5) // 8, (i + 1) % 4, (j + 5) % 8],\n            inverse=lambda i_outer, j_outer, i_inner, j_inner: [\n                4 * i_outer + i_inner - 1,\n                8 * j_outer + j_inner - 5,\n            ],\n            pre_shape=[14, 31],\n            post_shape=[\n                4,  # ceildiv(left_pad + i.extent, 4) = ceildiv(1 + 14, 4) = 4\n                5,  # ceildiv(left_pad + j.extent, 8) = ceildiv(5 + 31, 8) = 5\n                4,  # Range of iter%4\n                8,  # Range of iter%8\n            ],\n            padding=lambda i_outer, j_outer, i_inner, j_inner: tvm.tir.Or(\n                tvm.tir.Or(\n                    tvm.tir.And(i_outer == 0, i_inner < 1),\n                    tvm.tir.And(i_outer == 3, tvm.runtime.convert(3) == i_inner),\n                ),\n                tvm.tir.Or(\n                    tvm.tir.And(j_outer == 0, j_inner < 5),\n                    tvm.tir.And(j_outer == 4, j_inner >= 4),\n                ),\n            ),\n        ),\n        \"multiple_right_padding\": dict(\n            forward=lambda i: [i // 32, (i // 4) % 8, i % 4],\n            inverse=lambda i, j, k: [32 * i + 4 * j + k],\n            pre_shape=[116],\n            post_shape=[4, 8, 4],\n            padding=lambda i, j, k: tvm.tir.And(i == 3, 4 * j + k >= 20),\n        ),\n        \"multiple_right_padding_transpose\": dict(\n            forward=lambda i: [(i // 4) % 8, i // 32, i % 4],\n            inverse=lambda j, i, k: [32 * i + 4 * j + k],\n            pre_shape=[116],\n            post_shape=[8, 4, 4],\n            padding=lambda j, i, k: tvm.tir.And(i == 3, 4 * j + k >= 20),\n        ),\n        \"multiple_left_padding\": dict(\n            forward=lambda i: [(i + 5) // 32, ((i + 5) // 4) % 8, (i + 5) % 4],\n            inverse=lambda i, j, k: [32 * i + 4 * j + k - 5],\n            pre_shape=[123],\n            post_shape=[4, 8, 4],\n            padding=lambda i, j, k: tvm.tir.And(i == 0, j * 4 + k < 5),\n        ),\n        \"multiple_left_padding_with_transpose\": dict(\n            forward=lambda i: [((i + 5) // 4) % 8, (i + 5) // 32, (i + 5) % 4],\n            inverse=lambda j, i, k: [32 * i + 4 * j + k - 5],\n            pre_shape=[123],\n            post_shape=[8, 4, 4],\n            padding=lambda j, i, k: tvm.tir.And(i == 0, j * 4 + k < 5),\n        ),\n        \"outer_loop_extent_one\": dict(\n            forward=lambda i: [i // 4, i % 4],\n            inverse=lambda i, j: [i * 4 + j],\n            pre_shape=[3],\n            post_shape=[1, 4],\n            padding=lambda i, j: tvm.runtime.convert(3) == j,\n        ),\n    }\n)\n\n\ndef test_nonsurjective_inverse(padding_test_case):\n    index_map = IndexMap.from_func(padding_test_case[\"forward\"])\n\n    inverse, padding_predicate = index_map.non_surjective_inverse(padding_test_case[\"pre_shape\"])\n    expected_inverse = IndexMap.from_func(padding_test_case[\"inverse\"])\n    assert inverse.is_equivalent_to(expected_inverse)\n\n    post_shape = index_map.map_shape(padding_test_case[\"pre_shape\"])\n    tvm.ir.assert_structural_equal(post_shape, padding_test_case[\"post_shape\"])\n\n    expected_predicate = padding_test_case[\"padding\"](*inverse.initial_indices)\n\n    # Can't use analyzer.can_prove_equal, because it can't simplify\n    # expressions like `(4*i+j >= 14) - (4*i+j >= 14)`.\n    analyzer = tvm.arith.Analyzer()\n    expected_predicate = analyzer.simplify(expected_predicate)\n    padding_predicate = analyzer.simplify(padding_predicate)\n    tvm.ir.assert_structural_equal(padding_predicate, expected_predicate)\n\n\ndef test_index_map_inverse_no_iter():\n    def input_example(i0, i1, i2, i3):\n        j0 = floordiv(i3, 32)\n        j1 = floordiv(i2, 2)\n        j2 = floormod(i2, 2)\n        j3 = floormod(i3, 32)\n        return j0, j1, j2, j3\n\n    def expected_inverse(i0, i1, i2, i3):\n        return IntImm(\"int32\", 0), IntImm(\"int32\", 0), i2 + i1 * 2, i3 + i0 * 32\n\n    index_map = IndexMap.from_func(input_example)\n    inverse_map = index_map.inverse([1, 1, 64, 64])\n    expected_map = IndexMap.from_func(expected_inverse)\n    assert expected_map.is_equivalent_to(inverse_map)\n\n\ndef test_map_ndarray():\n    index_map = IndexMap.from_func(lambda i: [i // 4, i % 4])\n\n    inp = np.arange(16).astype(\"int8\")\n\n    out = index_map.map_ndarray(tvm.nd.array(inp)).numpy()\n\n    ref = np.zeros(out.shape).astype(\"int8\")\n\n    for i in range(16):\n        ref[i // 4, i % 4] = inp[i]\n\n    np.testing.assert_equal(ref, out)\n\n    index_map = IndexMap.from_func(lambda i0, i1, i2, i3: (i3, i0, i1, i2))\n\n    inp = np.random.randn(10, 10, 10, 10).astype(\"float16\")\n\n    out = index_map.map_ndarray(tvm.nd.array(inp)).numpy()\n\n    ref = np.transpose(inp, (3, 0, 1, 2))\n\n    np.testing.assert_equal(ref, out)\n\n    index_map = IndexMap.from_func(\n        lambda i0, i1, i2, i3: (\n            floordiv(i3, 32),\n            i0,\n            floordiv(i2, 8),\n            floordiv(floormod(i3, 32), 16),\n            i1,\n            floormod(i2, 8),\n            floormod(i3, 16),\n        )\n    )\n\n    kH = kW = 3\n    I = 64\n    O = 64\n    inp = np.random.randn(kH, kW, I, O).astype(\"float32\")\n    arr = tvm.nd.array(inp)\n    out = index_map.map_ndarray(arr).numpy()\n\n    ref = np.zeros(out.shape).astype(\"float32\")\n\n    for i0 in range(kH):\n        for i1 in range(kW):\n            for i2 in range(I):\n                for i3 in range(O):\n                    v = inp[i0, i1, i2, i3]\n                    ref[i3 // 32, i0, i2 // 8, (i3 % 32) // 16, i1, i2 % 8, i3 % 16] = v\n\n    np.testing.assert_equal(ref, out)\n\n    inverse_map = index_map.inverse(inp.shape)\n    np.testing.assert_equal(inverse_map.map_ndarray(index_map.map_ndarray(arr)).numpy(), inp)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_ir_attrs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport pytest\nimport tvm.ir._ffi_api\n\n\ndef test_make_attrs():\n    with pytest.raises(AttributeError):\n        x = tvm.ir.make_node(\"attrs.TestAttrs\", unknown_key=1, name=\"xx\")\n\n    with pytest.raises(AttributeError):\n        x = tvm.ir.make_node(\"attrs.TestAttrs\", axis=100, name=\"xx\")\n\n    x = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"xx\", padding=(3, 4))\n    assert x.name == \"xx\"\n    assert x.padding[0].value == 3\n    assert x.padding[1].value == 4\n    assert x.axis == 10\n\n\ndef test_dict_attrs():\n    dattr = tvm.ir.make_node(\"DictAttrs\", x=1, y=10, name=\"xyz\", padding=(0, 0))\n    assert dattr.x.value == 1\n    datrr = tvm.ir.load_json(tvm.ir.save_json(dattr))\n    assert dattr.name == \"xyz\"\n    assert isinstance(dattr, tvm.ir.DictAttrs)\n    assert \"name\" in dattr\n    assert dattr[\"x\"].value == 1\n    assert len(dattr) == 4\n    assert len([x for x in dattr.keys()]) == 4\n    assert len(dattr.items()) == 4\n\n\ndef test_attrs_equal():\n    dattr0 = tvm.ir.make_node(\"DictAttrs\", x=1, y=[10, 20])\n    dattr1 = tvm.ir.make_node(\"DictAttrs\", y=[10, 20], x=1)\n    dattr2 = tvm.ir.make_node(\"DictAttrs\", x=1, y=None)\n    assert tvm.ir.structural_equal(dattr0, dattr1)\n    assert not tvm.ir.structural_equal(dattr0, dattr2)\n    assert not tvm.ir.structural_equal({\"x\": 1}, tvm.runtime.convert(1))\n    assert not tvm.ir.structural_equal([1, 2], tvm.runtime.convert(1))\n\n\nif __name__ == \"__main__\":\n    test_make_attrs()\n    test_dict_attrs()\n    test_attrs_equal()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_ir_container.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n\ndef test_array():\n    a = tvm.runtime.convert([1, 2, 3])\n    assert len(a) == 3\n    assert a[-1].value == 3\n    a_slice = a[-3:-1]\n    assert (a_slice[0].value, a_slice[1].value) == (1, 2)\n\n\ndef test_array_save_load_json():\n    a = tvm.runtime.convert([1, 2, 3])\n    json_str = tvm.ir.save_json(a)\n    a_loaded = tvm.ir.load_json(json_str)\n    assert a_loaded[1].value == 2\n\n\ndef test_dir_array():\n    a = tvm.runtime.convert([1, 2, 3])\n    assert dir(a)\n\n\ndef test_getattr_array():\n    a = tvm.runtime.convert([1, 2, 3])\n    assert getattr(a, \"type_key\") == \"Array\"\n    assert not hasattr(a, \"test_key\")\n\n\ndef test_map():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    amap = tvm.runtime.convert({a: 2, b: 3})\n    assert a in amap\n    assert len(amap) == 2\n    dd = dict(amap.items())\n    assert a in dd\n    assert b in dd\n    assert a + 1 not in amap\n    assert {x for x in amap} == {a, b}\n    assert set(amap.keys()) == {a, b}\n    assert set(amap.values()) == {2, 3}\n\n\ndef test_str_map():\n    amap = tvm.runtime.convert({\"a\": 2, \"b\": 3})\n    assert \"a\" in amap\n    assert len(amap) == 2\n    dd = dict(amap.items())\n    assert amap[\"a\"].value == 2\n    assert \"a\" in dd\n    assert \"b\" in dd\n\n\ndef test_map_save_load_json():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    amap = tvm.runtime.convert({a: 2, b: 3})\n    json_str = tvm.ir.save_json(amap)\n    amap = tvm.ir.load_json(json_str)\n    assert len(amap) == 2\n    dd = {kv[0].name: kv[1].value for kv in amap.items()}\n    assert dd == {\"a\": 2, \"b\": 3}\n\n\ndef test_dir_map():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    amap = tvm.runtime.convert({a: 2, b: 3})\n    assert dir(amap)\n\n\ndef test_getattr_map():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    amap = tvm.runtime.convert({a: 2, b: 3})\n    assert getattr(amap, \"type_key\") == \"Map\"\n    assert not hasattr(amap, \"test_key\")\n\n\ndef test_in_container():\n    arr = tvm.runtime.convert([\"a\", \"b\", \"c\"])\n    assert \"a\" in arr\n    assert tvm.tir.StringImm(\"a\") in arr\n    assert \"d\" not in arr\n\n\ndef test_ndarray_container():\n    x = tvm.nd.array([1, 2, 3])\n    arr = tvm.runtime.convert([x, x])\n    assert arr[0].same_as(x)\n    assert arr[1].same_as(x)\n    assert isinstance(arr[0], tvm.nd.NDArray)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_ir_type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test type nodes in the IR\"\"\"\nimport tvm\n\n\ndef check_json_roundtrip(node):\n    json_str = tvm.ir.save_json(node)\n    back = tvm.ir.load_json(json_str)\n    assert tvm.ir.structural_equal(back, node, map_free_vars=True)\n\n\ndef test_prim_type():\n    x = tvm.ir.PrimType(\"int32\")\n    assert isinstance(x, tvm.ir.PrimType)\n    assert x.dtype == \"int32\"\n\n\ndef test_tensor_type_bad_constructor():\n    try:\n        x = tvm.ir.TensorType(\"xx\", \"xx\")\n    except tvm.error.TVMError:\n        pass\n\n\ndef test_tensor_type():\n    shape = tvm.runtime.convert([1, 2, 3])\n    dtype = \"float32\"\n    tt = tvm.ir.TensorType(shape, dtype)\n    assert tt.dtype == dtype\n    assert tt.shape == shape\n    assert tt.span == None\n    str(tt)\n    check_json_roundtrip(tt)\n\n\ndef test_type_param():\n    tp = tvm.ir.TypeVar(\"name\", tvm.ir.TypeKind.Type)\n    assert tp.kind == tvm.ir.TypeKind.Type\n    # assert tp.span  # TODO allow us to set span\n    str(tp)\n    check_json_roundtrip(tp)\n\n\ndef test_func_type():\n    type_params = tvm.runtime.convert([])\n    type_constraints = tvm.runtime.convert([])  # TODO: fill me in\n    arg_types = tvm.runtime.convert([])\n    ret_type = tvm.ir.TensorType((1, 2, 3), \"float32\")\n    tf = tvm.ir.FuncType(arg_types, ret_type, type_params, type_constraints)\n    assert tf.type_params == type_params\n    assert tf.type_constraints == type_constraints\n    assert tf.arg_types == arg_types\n    assert tf.ret_type == ret_type\n    assert tf.span == None\n    # TODO make sure we can set span\n    str(tf)\n    check_json_roundtrip(tf)\n\n\ndef test_tuple_type():\n    tp = tvm.ir.TypeVar(\"tp\", tvm.ir.TypeKind.Type)\n    tf = tvm.ir.FuncType([], tvm.ir.TupleType([]), [], [])\n    tt = tvm.ir.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    fields = tvm.runtime.convert([tp, tf, tt])\n\n    tup_ty = tvm.ir.TupleType(fields)\n    assert tup_ty.fields == fields\n    str(tup_ty)\n    check_json_roundtrip(tup_ty)\n\n\ndef test_type_relation():\n    tp = tvm.ir.TypeVar(\"tp\", tvm.ir.TypeKind.Type)\n    tf = tvm.ir.FuncType([], None, [], [])\n    tt = tvm.ir.TensorType(tvm.runtime.convert([1, 2, 3]), \"float32\")\n    args = tvm.runtime.convert([tp, tf, tt])\n\n    num_inputs = 2\n    func = tvm.ir.EnvFunc.get(\"tvm.relay.type_relation.Broadcast\")\n    attrs = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"attr\", padding=(3, 4))\n\n    tr = tvm.ir.TypeRelation(func, args, num_inputs, attrs)\n    assert tr.args == args\n    assert tr.num_inputs == num_inputs\n    str(tr)\n    check_json_roundtrip(tr)\n\n\nif __name__ == \"__main__\":\n    test_tensor_type_bad_constructor()\n    test_tensor_type()\n    test_type_param()\n    test_func_type()\n    test_tuple_type()\n    test_type_relation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_link_params.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport collections\nimport ctypes\nimport json\nimport os\nimport re\nfrom contextlib import redirect_stderr\nfrom io import StringIO\n\nimport numpy as np\nimport tvm\nimport tvm.relay\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm.contrib import utils\nfrom tvm.relay.backend import Executor, Runtime\n\nINPUT_SHAPE = (1, 3, 16, 16)\n\nKERNEL_SHAPE = (3, 3, 3, 3)\n\n\n# The data types that are linkable.\nlinkable_dtype = tvm.testing.parameter(\n    *(\n        [f\"uint{b}\" for b in (8, 16, 32, 64)]\n        + [f\"int{b}\" for b in (8, 16, 32, 64)]\n        + [\"float32\", \"float64\"]\n    )\n)\n\n\ndef dtype_info(dtype):\n    \"\"\"Lookup numpy type info for the given string dtype (of linkable_dtype params above).\"\"\"\n    if \"int\" in dtype:\n        return np.iinfo(getattr(np, dtype))\n    else:\n        return np.finfo(getattr(np, dtype))\n\n\n# Note: for debugging, set this to an integer (i.e. 1.0). Then all \"random\" tensors will become\n# predictable\nRANDOM_TENSOR_START = None\n\n\ndef _make_random_tensor(dtype, shape):\n    \"\"\"Create a random test tensor with given shape and dtype.\"\"\"\n    global RAND_SEED\n    if RANDOM_TENSOR_START is not None:\n        to_return = np.arange(\n            RANDOM_TENSOR_START, RANDOM_TENSOR_START + np.prod(shape), dtype=dtype\n        ).reshape(shape)\n        RAND_SEED += np.prod(shape)\n        return to_return\n\n    dinfo = dtype_info(dtype)\n    if \"int\" in dtype:\n        return np.random.randint(dinfo.min, dinfo.max, shape, dtype=dtype)\n    else:\n        to_return = np.random.uniform(0, dinfo.max, shape).astype(dtype)\n        np.reshape(to_return, np.prod(shape))[::2] *= -1\n        return to_return\n\n\ndef _lookup_sid(graph, name):\n    \"\"\"Lookup the storage id of a named parameter.\n\n    Arguments\n    ---------\n    graph : dict\n        Parsed JSON graph.\n\n    name : str\n        Name of the tensor parameter to lookup.\n\n    Returns\n    -------\n    int :\n        The storage_id of the parameter.\n    \"\"\"\n    num_outputs_seen = 0\n    for i, n in enumerate(graph[\"nodes\"]):\n        if n[\"name\"] == name:\n            print(\"sid\", name, graph[\"attrs\"][\"storage_id\"][1], num_outputs_seen)\n            return graph[\"attrs\"][\"storage_id\"][1][num_outputs_seen]\n        else:\n            if \"attrs\" in n and \"num_outputs\" in n[\"attrs\"]:\n                num_outputs_seen += int(n[\"attrs\"][\"num_outputs\"])\n            else:\n                num_outputs_seen += 1\n\n    raise KeyError(f\"no such param: {name}\")\n\n\ndef _get_ctypes_dtype(dt):\n    \"\"\"Return a ctypes c_* datatype given a string data type.\"\"\"\n    if \"int\" in dt:\n        return getattr(ctypes, f\"c_{dt}\")\n    elif dt == \"float32\":\n        return ctypes.c_float\n    elif dt == \"float64\":\n        return ctypes.c_double\n    else:\n        assert False, f\"unknown dtype: {dt}\"\n\n\ndef _verify_linked_param(dtype, lib, mod, graph, name):\n    \"\"\"Directly read memory from the linked library to verify the linked parameter is correct.\"\"\"\n    sid = _lookup_sid(graph, name)\n    # NOTE: query_imports=True because when loading a module from disk (i.e. for C backend),\n    # a GraphExecutorFactory module is created instead of the module itself.\n    param_ptr = mod.get_function(\"_lookup_linked_param\", True)(sid)\n    gen_param = lib.params[name]\n    arr_data = (_get_ctypes_dtype(dtype) * np.prod(gen_param.shape)).from_address(param_ptr.value)\n    arr = np.ndarray(shape=gen_param.shape, dtype=gen_param.dtype, buffer=arr_data, order=\"C\")\n    if \"int\" in gen_param.dtype:\n        np.testing.assert_equal(gen_param.numpy(), arr)\n    else:\n        np.testing.assert_allclose(gen_param.numpy(), arr)\n    return dtype == gen_param.dtype\n\n\ndef _make_mod_and_params(dtype):\n    \"\"\"Create a Relay module and parameters to test the given datatype.\"\"\"\n    param_decls = collections.OrderedDict()\n    param_init = {}\n\n    def _add_decl(name, dtype):\n        param_decls[name] = f\"%{name} : Tensor[{KERNEL_SHAPE}, {dtype}]\"\n        param_init[name] = _make_random_tensor(dtype, KERNEL_SHAPE)\n\n    # Add several parameters so that the number of parameters\n    _add_decl(f\"{dtype}_a\", dtype)\n    _add_decl(f\"{dtype}_b\", dtype)\n\n    mod_lines = [\n        '#[version = \"0.0.5\"]',\n        f\"def @main(%rand_input : Tensor[{INPUT_SHAPE}, {dtype}], { ', '.join(param_decls.values()) } )  {{\",\n        # This program ensures that GraphPlanMemory alternates between the same two storage IDs for a\n        # while. In doing this, it ensures that param %{dtype}_b will be placed into the graph at an\n        # index unequal to its storage_id. This ensures that GraphExecutorCodegen encodes the storage_id\n        # and not the parameter index into the graph.\n        (\n            f'    %0 = nn.conv2d(%rand_input, %{dtype}_a, data_layout=\"NCHW\", kernel_layout=\"OIHW\", '\n            f'kernel_size=[3, 3], out_dtype=\"{dtype}\");'\n        ),\n        (\n            f'    %1 = nn.conv2d(%0, %{dtype}_a, data_layout=\"NCHW\", kernel_layout=\"OIHW\", '\n            f'kernel_size=[3, 3], out_dtype=\"{dtype}\");'\n        ),\n        (\n            f'    %2 = nn.conv2d(%1, %{dtype}_a, data_layout=\"NCHW\", kernel_layout=\"OIHW\", '\n            f'kernel_size=[3, 3], out_dtype=\"{dtype}\");'\n        ),\n        (\n            f'    %3 = nn.conv2d(%2, %{dtype}_b, data_layout=\"NCHW\", kernel_layout=\"OIHW\", '\n            f'kernel_size=[3, 3], out_dtype=\"{dtype}\");'\n        ),\n        \"    %3\",\n        \"}\",\n    ]\n\n    mod = tvm.parser.fromtext(\"\\n\".join(mod_lines))\n    return mod, param_init\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_link_params(linkable_dtype):\n    ir_mod, param_init = _make_mod_and_params(linkable_dtype)\n    rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE)\n    main_func = ir_mod[\"main\"]\n    target = \"llvm\"\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"graph\", {\"link-params\": True})\n    with tvm.transform.PassContext(opt_level=3):\n        lib = tvm.relay.build(ir_mod, target, runtime=runtime, executor=executor, params=param_init)\n\n        # NOTE: Need to export_library() and load_library() to link all the Module(llvm, ...)\n        # against one another.\n        temp_dir = utils.TempDirectory()\n        export_file = temp_dir / \"lib.so\"\n        lib.lib.export_library(export_file)\n        mod = tvm.runtime.load_module(export_file)\n        assert len(lib.params.keys()) == 0  # NOTE: params became tir.constants\n        assert mod.get_function(\"TVMSystemLibEntryPoint\") != None\n\n        graph = json.loads(lib.graph_json)\n        for p in lib.params:\n            _verify_linked_param(linkable_dtype, lib, mod, graph, p) or found_one\n\n        # Wrap in function to explicitly deallocate the runtime.\n        def _run_linked(lib, mod):\n            graph_json, _, _ = lib\n            graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0))\n            graph_rt.set_input(\"rand_input\", rand_input)  # NOTE: params not required.\n            graph_rt.run()\n            return graph_rt.get_output(0)\n\n        linked_output = _run_linked(lib, mod)\n\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3):\n        lib = tvm.relay.build(ir_mod, \"llvm\", runtime=runtime, params=param_init)\n\n        def _run_unlinked(lib):\n            graph_json, mod, lowered_params = lib\n            graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0))\n            graph_rt.set_input(\"rand_input\", rand_input, **lowered_params)\n            graph_rt.run()\n            return graph_rt.get_output(0)\n\n        unlinked_output = _run_unlinked(lib)\n\n    if \"int\" in linkable_dtype:\n        np.testing.assert_equal(unlinked_output.numpy(), linked_output.numpy())\n    else:\n        np.testing.assert_allclose(unlinked_output.numpy(), linked_output.numpy())\n\n\ndef _get_c_datatype(dtype):\n    \"\"\"Translate LINKABLE_DTYPES element to c datatype.\"\"\"\n    if \"int\" in dtype:\n        return f\"{dtype}_t\"\n    elif dtype == \"float32\":\n        return \"float\"\n    elif dtype == \"float64\":\n        return \"double\"\n    else:\n        assert False, f\"unknown dtype {dtype}\"\n\n\nHEX_NUM_RE = re.compile(r\"[+\\-]?(?:(?:0x[0-9A-Fa-f.p+-]+)|(?:INFINITY)|(?:NAN))\")\n\n\ndef test_c_link_params(linkable_dtype):\n    temp_dir = utils.tempdir()\n    mod, param_init = _make_mod_and_params(linkable_dtype)\n    rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE)\n    main_func = mod[\"main\"]\n    target = \"c\"\n    executor = Executor(\"graph\", {\"link-params\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lib = tvm.relay.build(mod, target, executor=executor, params=param_init)\n        assert len(lib.params.keys()) == 0  # NOTE: params became tir.constants\n\n        src = lib.lib.get_source()\n        lib.lib.save(temp_dir.relpath(\"test.c\"), \"c\")\n        c_dtype = _get_c_datatype(linkable_dtype)\n        src_lines = src.split(\"\\n\")\n        param = param_init[f\"{linkable_dtype}_a\"].reshape(np.prod(KERNEL_SHAPE))\n        param_def = rf\"^static const {c_dtype} __attribute__\\(\\(section\\(\\\".rodata.tvm\\\"\\), aligned\\(16\\)\\)\\) [a-zA-Z_0-9]*constant_\\d+\\[{np.prod(param.shape)}\\] = {{$\"\n\n        for i, line in enumerate(src_lines):\n            if re.match(param_def, line):\n                i += 1\n                break\n        else:\n            assert False, f'did not find parameter definition \"{param_def}\":\\n{src}'\n\n        cursor = 0\n        width = dtype_info(linkable_dtype).bits // 4 + 2\n        if linkable_dtype.startswith(\"int\"):\n            width += 1  # Account for sign\n\n        while \"};\" not in src_lines[i]:\n            for match in HEX_NUM_RE.finditer(src_lines[i]):\n                cursor += 1\n            i += 1\n\n        assert cursor == np.prod(param.shape)\n\n        # Need a unique name per library to avoid dlopen caching the lib load.\n        lib_path = temp_dir.relpath(f\"test-{linkable_dtype}-linked.so\")\n        lib[\"remove_params\"]().export_library(lib_path)\n        lib_mod = tvm.runtime.load_module(lib_path)\n\n        #            lib_mod = lib_factory['default']()\n        graph = json.loads(lib.graph_json)\n        for p in lib.params:\n            _verify_linked_param(linkable_dtype, lib, lib_mod, graph, p)\n\n        # Wrap in function to explicitly deallocate the runtime.\n        def _run_linked(lib_mod):\n            graph_rt = tvm.contrib.graph_executor.GraphModule(lib_mod[\"default\"](tvm.cpu(0)))\n            graph_rt.set_input(\"rand_input\", rand_input)  # NOTE: params not required.\n            graph_rt.run()\n\n            return graph_rt.get_output(0)\n\n        linked_output = _run_linked(lib_mod)\n\n    linked_params = lib.params\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        lib = tvm.relay.build(mod, \"c\", params=param_init)\n        _, _, params = lib\n        # Need a unique name per library to avoid dlopen caching the lib load.\n        lib_path = temp_dir.relpath(f\"test-{linkable_dtype}-unlinked.so\")\n        lib.export_library(lib_path)\n        lib_mod = tvm.runtime.load_module(lib_path)\n\n        def _run_unlinked(lib_mod):\n            graph_rt = tvm.contrib.graph_executor.GraphModule(lib_mod[\"default\"](tvm.cpu(0)))\n            graph_rt.set_input(\"rand_input\", rand_input, **params)\n            graph_rt.run()\n            return graph_rt.get_output(0)\n\n        unlinked_output = _run_unlinked(lib_mod)\n\n    if \"int\" in linkable_dtype:\n        np.testing.assert_equal(unlinked_output.numpy(), linked_output.numpy())\n    else:\n        np.testing.assert_allclose(unlinked_output.numpy(), linked_output.numpy())\n\n\n@tvm.testing.requires_micro\ndef test_crt_link_params(linkable_dtype):\n    from tvm import micro\n\n    mod, param_init = _make_mod_and_params(linkable_dtype)\n    rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE)\n    main_func = mod[\"main\"]\n    target = \"c\"\n    runtime = Runtime(\"crt\", {\"system-lib\": True})\n    executor = Executor(\"graph\", {\"link-params\": True})\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory = tvm.relay.build(\n            mod, target, runtime=runtime, executor=executor, params=param_init\n        )\n        assert len(factory.get_params().keys()) == 0  # NOTE: params became tir.constants\n\n        temp_dir = tvm.contrib.utils.tempdir()\n        template_project_dir = os.path.join(tvm.micro.get_standalone_crt_dir(), \"template\", \"host\")\n        project = tvm.micro.generate_project(\n            template_project_dir, factory, temp_dir / \"project\", {\"verbose\": 1}\n        )\n        project.build()\n        project.flash()\n        with tvm.micro.Session(project.transport()) as sess:\n            graph_rt = tvm.micro.session.create_local_graph_executor(\n                factory.get_graph_json(), sess.get_system_lib(), sess.device\n            )\n\n            assert len(factory.params.keys()) == 0  # NOTE: params became tir.constants\n\n            # NOTE: not setting params here.\n            graph_rt.set_input(\"rand_input\", rand_input)\n            graph_rt.run()\n            linked_output = graph_rt.get_output(0).numpy()\n\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    with tvm.transform.PassContext(opt_level=3):\n        lib = tvm.relay.build(mod, \"llvm\", runtime=runtime, params=param_init)\n\n        def _run_unlinked(lib):\n            graph_json, mod, lowered_params = lib\n            graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0))\n            graph_rt.set_input(\"rand_input\", rand_input, **lowered_params)\n            graph_rt.run()\n            return graph_rt.get_output(0).numpy()\n\n        unlinked_output = _run_unlinked(lib)\n\n    if \"int\" in linkable_dtype:\n        np.testing.assert_equal(unlinked_output, linked_output)\n    else:\n        np.testing.assert_allclose(unlinked_output, linked_output)\n\n\ndef test_tir_link_params():\n    def get_dense(data_shape, weight_shape):\n        data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n        weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n        dense = relay.nn.dense(data, weight)\n        return relay.Function([data, weight], dense)\n\n    def get_ref_dense(data_np, weight_np):\n        return np.dot(data_np, np.transpose(weight_np))\n\n    def schedule_dense(sch):\n        dense = sch.get_block(\"T_matmul_NT\")\n        _y, _x, _k = sch.get_loops(dense)\n\n    M, N, K = 128, 128, 128\n    data_shape = (M, K)\n    weight_shape = (N, K)\n    relay_mod = tvm.IRModule.from_expr(get_dense(data_shape, weight_shape))\n    relay_mod = relay.transform.InferType()(relay_mod)\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    weight_np = np.random.randn(*weight_shape).astype(\"float32\")\n    target = \"llvm\"\n    params = {\"weight\": weight_np}\n\n    def schedule_fn(sch):\n        if \"nn_dense\" in sch.mod.attrs[\"task_name\"]:\n            schedule_dense(sch)\n            return True\n        return False\n\n    with StringIO() as stderr_buf, redirect_stderr(stderr_buf):\n        with ms.database.ScheduleFnDatabase(schedule_fn), tvm.transform.PassContext(\n            opt_level=3,\n            config={\"relay.backend.use_meta_schedule\": True},\n        ):\n            executor = Executor(\"graph\", {\"link-params\": True})\n            lib = relay.build(relay_mod, target=target, executor=executor)\n\n        # Workload look up should succeed. This does not work when the test is invoked from pytest.\n        assert not \"Cannot find workload\" in stderr_buf.getvalue()\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    runtime.set_input(**params)\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n    out = runtime.get_output(0).numpy()\n    ref = get_ref_dense(data_np, weight_np)\n    tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_lower_build.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nimport tvm.testing\n\n\ndef _check_module_with_numpy(mod, shape=(128, 128, 128)):\n    m, n, k = shape\n    a = tvm.nd.array(np.random.rand(m, k).astype(\"float32\"))\n    b = tvm.nd.array(np.random.rand(n, k).astype(\"float32\"))\n    c = tvm.nd.array(np.zeros((m, n), dtype=\"float32\"))\n    c_np = np.dot(a.numpy(), b.numpy().transpose())\n    mod(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5)\n\n\n# pylint: disable=no-self-argument, missing-class-docstring, missing-function-docstring\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = T.float32(0)\n        for k in range(128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@tvm.script.ir_module\nclass LoweredModule:\n    @T.prim_func\n    def main(\n        A: T.Buffer[(16384,), \"float32\"],\n        B: T.Buffer[(16384,), \"float32\"],\n        C: T.Buffer[(16384,), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"from_legacy_te_schedule\": True, \"tir.noalias\": True})\n        T.preflattened_buffer(A, [128, 128], data=A.data)\n        T.preflattened_buffer(B, [128, 128], data=B.data)\n        T.preflattened_buffer(C, [128, 128], data=C.data)\n        # body\n        for x, y in T.grid(128, 128):\n            C[x * 128 + y] = 0.0\n            for k in T.serial(0, 128):\n                C[x * 128 + y] = C[x * 128 + y] + A[x * 128 + k] * B[y * 128 + k]\n\n\n@tvm.script.ir_module\nclass LoweredTIRModule:\n    @T.prim_func\n    def main(\n        A: T.Buffer[(16384,), \"float32\"],\n        B: T.Buffer[(16384,), \"float32\"],\n        C: T.Buffer[(16384,), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        T.preflattened_buffer(A, [128, 128], data=A.data)\n        T.preflattened_buffer(B, [128, 128], data=B.data)\n        T.preflattened_buffer(C, [128, 128], data=C.data)\n        # body\n        for x, y in T.grid(128, 128):\n            C[x * 128 + y] = 0.0\n            for k in T.serial(0, 128):\n                C[x * 128 + y] = C[x * 128 + y] + A[x * 128 + k] * B[y * 128 + k]\n\n\ndef test_lower_build_te_schedule():\n    m, n, k = 128, 128, 128\n    axis_k = te.reduce_axis((0, k), \"k\")\n    A = te.placeholder((m, k), name=\"A\")\n    B = te.placeholder((k, n), name=\"B\")\n    C = te.compute((m, n), lambda x, y: te.sum(A[x, axis_k] * B[y, axis_k], axis=axis_k), name=\"C\")\n    s = te.create_schedule(C.op)\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        ir_mod = tvm.lower(s, [A, B, C])\n    tvm.ir.assert_structural_equal(ir_mod, LoweredModule)\n    # check building\n    mod = tvm.build(s, [A, B, C], target=\"llvm\")\n    _check_module_with_numpy(mod)\n\n\ndef test_lower_build_tir_func():\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        ir_mod = tvm.lower(matmul)\n    tvm.ir.assert_structural_equal(ir_mod, LoweredTIRModule)\n    # check building\n    mod = tvm.build(matmul, target=\"llvm\")\n    _check_module_with_numpy(mod)\n\n\ndef test_lower_build_tir_module():\n    func = matmul.with_attr(\"global_symbol\", \"main\")\n    func = func.with_attr(\"tir.noalias\", True)\n    ir_mod = IRModule({\"main\": func})\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        lowered_mod = tvm.lower(ir_mod)\n    tvm.ir.assert_structural_equal(lowered_mod, LoweredTIRModule)\n    # check building\n    mod = tvm.build(ir_mod, target=\"llvm\")\n    _check_module_with_numpy(mod)\n\n\ndef test_lower_build_lowered_module():\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        ir_mod = tvm.lower(LoweredTIRModule)\n    tvm.ir.assert_structural_equal(ir_mod, LoweredTIRModule)\n    # check building\n    mod = tvm.build(ir_mod, target=\"llvm\")\n    _check_module_with_numpy(mod)\n\n\nif __name__ == \"__main__\":\n    test_lower_build_te_schedule()\n    test_lower_build_tir_func()\n    test_lower_build_tir_module()\n    test_lower_build_lowered_module()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_arg_info.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nfrom tvm.meta_schedule.arg_info import ArgInfo, TensorInfo\nfrom tvm.script import tir as T\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n# fmt: off\n\n@T.prim_func\ndef Matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\"})\n    A = T.match_buffer(a, (128, 256), \"float32\")\n    B = T.match_buffer(b, (256, 512), \"float32\")\n    C = T.match_buffer(c, (128, 512), \"float32\")\n    for i, j, k in T.grid(128, 256, 512):\n        with T.block(\"matmul\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef test_meta_schedule_tensor_info_creation():\n    info = TensorInfo(\"float32\", [1, 224, 224, 3])\n    info = str(info)\n    assert info == 'TensorInfo(\"float32\", [1, 224, 224, 3])'\n\n\ndef test_meta_schedule_tensor_info_as_json():\n    info = TensorInfo(\"float32\", [1, 224, 224, 3])\n    info = info.as_json()\n    assert info == [\"TENSOR\", \"float32\", [1, 224, 224, 3]]\n\n\ndef test_meta_schedule_tensor_info_from_json():\n    info = [\"TENSOR\", \"float32\", [1, 224, 224, 3]]\n    info = TensorInfo.from_json(info)\n    assert str(info) == 'TensorInfo(\"float32\", [1, 224, 224, 3])'\n\n\ndef test_meta_schedule_arg_info_from_prim_func():\n    a_info, b_info, c_info = ArgInfo.from_prim_func(Matmul)\n    assert str(a_info) == 'TensorInfo(\"float32\", [128, 256])'\n    assert str(b_info) == 'TensorInfo(\"float32\", [256, 512])'\n    assert str(c_info) == 'TensorInfo(\"float32\", [128, 512])'\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_tensor_info_creation()\n    test_meta_schedule_tensor_info_as_json()\n    test_meta_schedule_tensor_info_from_json()\n    test_meta_schedule_arg_info_from_prim_func()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule Builder \"\"\"\n\nimport os\nimport sys\nimport time\nfrom typing import List\n\nimport pytest\nimport tvm.testing\n\nfrom tvm import script\nfrom tvm._ffi import register_func\nfrom tvm.meta_schedule.builder import (\n    BuilderInput,\n    BuilderResult,\n    LocalBuilder,\n    PyBuilder,\n)\nfrom tvm.runtime import Module\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\n@script.ir_module\nclass MatmulModule:\n    @T.prim_func\n    def matmul(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"matmul\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@script.ir_module\nclass MatmulReluModule:\n    @T.prim_func\n    def matmul_relu(  # pylint: disable=no-self-argument\n        a: T.handle, b: T.handle, d: T.handle\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"matmul_relu\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        D = T.match_buffer(d, (1024, 1024), \"float32\")\n        C = T.alloc_buffer((1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n        for i, j in T.grid(1024, 1024):\n            with T.block(\"relu\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n@script.ir_module\nclass BatchMatmulModule:\n    @T.prim_func\n    def batch_matmul(  # pylint: disable=no-self-argument\n        a: T.handle, b: T.handle, c: T.handle\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"batch_matmul\", \"tir.noalias\": True})\n        A = T.match_buffer(a, [16, 128, 128])\n        B = T.match_buffer(b, [16, 128, 128])\n        C = T.match_buffer(c, [16, 128, 128])\n        for n, i, j, k in T.grid(16, 128, 128, 128):\n            with T.block(\"update\"):\n                vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n                with T.init():\n                    C[vn, vi, vj] = 0.0\n                C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk]\n\n\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\ndef _check_build_results(builder_results: List[BuilderResult]):\n    \"\"\"Simple check whether the build is successful\"\"\"\n    for result in builder_results:\n        artifact_path = result.artifact_path\n        error_msg = result.error_msg\n        assert artifact_path is not None\n        assert error_msg is None\n        os.remove(artifact_path)\n        os.rmdir(os.path.dirname(artifact_path))\n\n\ndef test_meta_schedule_single_build():\n    \"\"\"Test meta schedule builder for a single build\"\"\"\n    mod = MatmulModule\n    builder = LocalBuilder()\n    builder_inputs = [BuilderInput(mod, Target(\"llvm\"))]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    _check_build_results(builder_results)\n\n\ndef test_meta_schedule_multiple_build():\n    \"\"\"Test meta schedule builder for multiple builds\"\"\"\n    builder = LocalBuilder()\n    builder_inputs = [\n        BuilderInput(MatmulModule, Target(\"llvm\")),\n        BuilderInput(MatmulReluModule, Target(\"llvm\")),\n        BuilderInput(BatchMatmulModule, Target(\"llvm\")),\n    ]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    _check_build_results(builder_results)\n\n\ndef test_meta_schedule_error_handle_test_builder():\n    \"\"\"Test the error handing during building\"\"\"\n\n    class TestBuilder(PyBuilder):\n        def build(  # pylint: disable=no-self-use\n            self,\n            build_inputs: List[BuilderInput],\n        ) -> List[BuilderResult]:\n            return [BuilderResult(None, \"error\") for w in build_inputs]\n\n    builder = TestBuilder()\n    builder_inputs = [\n        BuilderInput(MatmulModule, Target(\"llvm\")),\n        BuilderInput(MatmulReluModule, Target(\"llvm\")),\n        BuilderInput(BatchMatmulModule, Target(\"llvm\")),\n    ]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    for result in builder_results:\n        artifact_path = result.artifact_path\n        error_msg = result.error_msg\n        assert artifact_path is None\n        assert error_msg == \"error\"\n\n\ndef test_meta_schedule_error_handle_build_func():\n    \"\"\"Test the error handing during building\"\"\"\n\n    def initializer():\n        @register_func(\"meta_schedule.builder.test_build\")\n        def test_build(mod: Module, target: Target, _) -> None:  # pylint: disable=unused-variable\n            raise ValueError(\"Builder intended Test Error (build func).\")\n\n    builder = LocalBuilder(f_build=\"meta_schedule.builder.test_build\", initializer=initializer)\n    builder_inputs = [BuilderInput(MatmulModule, Target(\"llvm\"))]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    for result in builder_results:\n        artifact_path = result.artifact_path\n        error_msg = result.error_msg\n        assert artifact_path is None\n        assert error_msg.startswith(\"LocalBuilder: An exception occurred\")\n\n\ndef test_meta_schedule_error_handle_export_func():\n    \"\"\"Test the error handing during building\"\"\"\n\n    def initializer():\n        @register_func(\"meta_schedule.builder.test_export\")\n        def test_build(mod: Module) -> str:  # pylint: disable=unused-variable\n            raise ValueError(\"Builder intended Test Error (export func).\")\n\n    builder = LocalBuilder(f_export=\"meta_schedule.builder.test_export\", initializer=initializer)\n    builder_inputs = [BuilderInput(MatmulModule, Target(\"llvm\"))]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    for result in builder_results:\n        artifact_path = result.artifact_path\n        error_msg = result.error_msg\n        assert artifact_path is None\n        assert error_msg.startswith(\"LocalBuilder: An exception occurred\")\n\n\ndef test_meta_schedule_error_handle_time_out():\n    \"\"\"Test the error handing time out during building\"\"\"\n\n    def initializer():\n        @register_func(\"meta_schedule.builder.test_time_out\")\n        def timeout_build(mod, target, _):  # pylint: disable=unused-argument, unused-variable\n            time.sleep(2)\n\n    builder = LocalBuilder(\n        timeout_sec=1,\n        f_build=\"meta_schedule.builder.test_time_out\",\n        initializer=initializer,\n    )\n    builder_inputs = [BuilderInput(MatmulModule, Target(\"llvm\"))]\n    builder_results = builder.build(builder_inputs)\n    assert len(builder_results) == len(builder_inputs)\n    for result in builder_results:\n        artifact_path = result.artifact_path\n        error_msg = result.error_msg\n        assert artifact_path is None\n        assert error_msg.startswith(\"LocalBuilder: Timeout\")\n\n\ndef test_meta_schedule_missing_build_func():\n    with pytest.raises(ValueError):\n        LocalBuilder(f_build=\"wrong-name\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_byoc_tensorrt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule Builder \"\"\"\n# pylint: disable=missing-docstring\n\nimport sys\nfrom typing import List\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import relay\nfrom tvm.meta_schedule.arg_info import TensorInfo\nfrom tvm.meta_schedule.builder import BuilderInput, LocalBuilder\nfrom tvm.meta_schedule.runner import EvaluatorConfig, LocalRunner, RunnerInput\nfrom tvm.meta_schedule.testing.custom_builder_runner import (\n    build_relay,\n    build_relay_with_tensorrt,\n    run_with_graph_executor,\n)\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.relay import testing\nfrom tvm.relay.op.contrib import tensorrt\nfrom tvm.target import Target\nfrom tvm.tir import FloatImm\n\nhas_tensorrt_codegen = pytest.mark.skipif(\n    not tvm.get_global_func(\"relay.ext.tensorrt\", True),\n    reason=\"TensorRT codegen not available\",\n)\nhas_tensorrt_runtime = pytest.mark.skipif(\n    not tensorrt.is_tensorrt_runtime_enabled(),\n    reason=\"TensorRT runtime not available\",\n)\n\n# conv2d+relu network\ndef get_conv2d_relu(\n    data_shape,\n    out_channels,\n    kernel_size,\n    strides,\n    padding,\n    dilation,\n    groups,\n    data_layout,\n    kernel_layout,\n    dtype,\n):\n\n    data = relay.var(\"data\", relay.TensorType(data_shape, dtype))\n    weight = relay.var(\"weight\")\n\n    net = relay.nn.conv2d(\n        data=data,\n        weight=weight,  # conv kernel\n        strides=strides,\n        padding=padding,\n        dilation=dilation,\n        groups=groups,\n        channels=out_channels,\n        kernel_size=kernel_size,\n        data_layout=data_layout,\n        kernel_layout=kernel_layout,\n    )\n    net = relay.add(net, net)\n    net = relay.nn.relu(net)\n\n    inputs = relay.analysis.free_vars(net)\n    return relay.Function(inputs, net)\n\n\ndef verify_meta_schedule_with_tensorrt(\n    mod,\n    params,\n    data_shape,\n    use_trt: bool = True,\n):\n    # Build\n    builder = LocalBuilder(\n        f_build=build_relay_with_tensorrt if use_trt else build_relay,\n        timeout_sec=1000,\n    )\n    builder_input = BuilderInput(mod, Target(\"cuda\"), params)\n    builder_result = builder.build([builder_input])[0]\n    assert builder_result.error_msg is None, builder_result.error_msg\n    assert builder_result.artifact_path is not None\n\n    # Run\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        device_type=\"cuda\",\n        args_info=[TensorInfo(\"float32\", data_shape)],\n    )\n    runner = LocalRunner(\n        evaluator_config=EvaluatorConfig(\n            number=5,\n            repeat=2,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        ),\n        f_run_evaluator=run_with_graph_executor,\n    )\n\n    # Run the module\n    runner_future = runner.run([runner_input])[0]\n    runner_result = runner_future.result()\n    assert runner_result is not None\n    assert runner_result.error_msg is None, runner_result.error_msg\n    assert runner_result.run_secs is not None\n\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n\n\n@has_tensorrt_codegen\ndef test_conv2d_relu():\n    data_shape = (1, 1280, 14, 14)\n    out_channels = 256\n    kernel_size, strides, padding, dilation, groups = (1, 1), (1, 1), (0, 0, 0, 0), (1, 1), 1\n    data_layout, kernel_layout = \"NCHW\", \"OIHW\"\n    dtype = \"float32\"\n\n    f = get_conv2d_relu(\n        data_shape,\n        out_channels,\n        kernel_size,\n        strides,\n        padding,\n        dilation,\n        groups,\n        data_layout,\n        kernel_layout,\n        dtype,\n    )\n\n    mod, params = testing.create_workload(f)\n    verify_meta_schedule_with_tensorrt(mod, params, data_shape)\n\n\n@has_tensorrt_codegen\n@pytest.mark.parametrize(\"model_name\", [\"resnet_50\"])\n@pytest.mark.parametrize(\"input_shape\", [[1, 3, 224, 224]])\n@pytest.mark.parametrize(\"use_trt\", [True, False])\ndef test_relay_model(model_name: str, input_shape: List[int], use_trt: bool):\n    mod, params, _ = get_network(model_name, input_shape)\n    verify_meta_schedule_with_tensorrt(\n        mod,\n        params,\n        input_shape,\n        use_trt,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_cost_model.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport os\nimport re\nimport shutil\nimport tempfile\nimport unittest\nfrom functools import partial\nfrom typing import List\n\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm.meta_schedule.cost_model import PyCostModel, RandomModel, XGBModel\nfrom tvm.meta_schedule.cost_model.xgb_model import PackSum, _get_custom_call_back\nfrom tvm.meta_schedule.feature_extractor import RandomFeatureExtractor\nfrom tvm.meta_schedule.runner import RunnerResult\nfrom tvm.meta_schedule.search_strategy import MeasureCandidate\nfrom tvm.meta_schedule.tune_context import TuneContext\nfrom tvm.meta_schedule.utils import derived_object\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.schedule import Schedule\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,disable=unused-argument\n\n\ndef test_meta_schedule_cost_model():\n    @derived_object\n    class FancyCostModel(PyCostModel):\n        def load(self, path: str) -> None:\n            pass\n\n        def save(self, path: str) -> None:\n            pass\n\n        def update(\n            self,\n            context: TuneContext,\n            candidates: List[MeasureCandidate],\n            results: List[RunnerResult],\n        ) -> None:\n            pass\n\n        def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray:\n            return np.random.rand(10)\n\n    model = FancyCostModel()\n    model.save(\"fancy_test_location\")\n    model.load(\"fancy_test_location\")\n    model.update(TuneContext(), [], [])\n    results = model.predict(\n        TuneContext(), [MeasureCandidate(Schedule(mod=Matmul), []) for _ in range(10)]\n    )\n    assert results.shape == (10,)\n\n\ndef test_meta_schedule_cost_model_as_string():\n    @derived_object\n    class NotSoFancyCostModel(PyCostModel):\n        def load(self, path: str) -> None:\n            pass\n\n        def save(self, path: str) -> None:\n            pass\n\n        def update(\n            self,\n            context: TuneContext,\n            candidates: List[MeasureCandidate],\n            results: List[RunnerResult],\n        ) -> None:\n            pass\n\n        def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray:\n            return np.random.rand(10)\n\n    cost_model = NotSoFancyCostModel()\n    pattern = re.compile(r\"meta_schedule.NotSoFancyCostModel\\(0x[a-f|0-9]*\\)\")\n    assert pattern.match(str(cost_model))\n\n\ndef test_meta_schedule_random_model():\n    model = RandomModel()\n    model.update(TuneContext(), [], [])\n    res = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(10)])\n    assert len(res) == 10\n    assert min(res) >= 0 and max(res) <= model.max_range\n\n\ndef test_meta_schedule_random_model_reseed():\n    model = RandomModel(seed=100)\n    res = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(20)])\n    new_model = RandomModel(seed=100)\n    new_res = new_model.predict(\n        TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(20)]\n    )\n    assert (res == new_res).all()\n\n\ndef test_meta_schedule_random_model_reload():\n    model = RandomModel(seed=25973)\n    model.predict(\n        TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(30)]\n    )  # change state\n    path = os.path.join(tempfile.mkdtemp(), \"test_output_meta_schedule_random_model.npy\")\n    model.save(path)\n    res1 = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(70)])\n    model.load(path)\n    res2 = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(70)])\n    shutil.rmtree(os.path.dirname(path))\n    assert (res1 == res2).all()\n\n\ndef _dummy_candidate():\n    return MeasureCandidate(Schedule(Matmul), [])\n\n\ndef _dummy_result(num_samples: int = 4, max_run_sec: int = 10):\n    return RunnerResult(list(np.random.rand(num_samples) * max_run_sec + 1e-6), None)\n\n\ndef test_meta_schedule_xgb_model():\n    extractor = RandomFeatureExtractor()\n    model = XGBModel(extractor=extractor, num_warmup_samples=2)\n    update_sample_count = 10\n    predict_sample_count = 100\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)])\n\n\ndef test_meta_schedule_xgb_model_reload():\n    extractor = RandomFeatureExtractor()\n    model = XGBModel(extractor=extractor, num_warmup_samples=10)\n    update_sample_count = 20\n    predict_sample_count = 30\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)])\n    with tempfile.NamedTemporaryFile() as path:\n        # Backup\n        random_state = model.extractor.random_state  # save feature extractor's random state\n        old_data = model.data\n        old_data_size = model.data_size\n        model.save(path.name)\n        res1 = model.predict(\n            TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]\n        )\n        # Load\n        model.extractor.random_state = random_state  # load feature extractor's random state\n        model.load(path.name)\n        new_data = model.data\n        new_data_size = model.data_size\n        res2 = model.predict(\n            TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]\n        )\n    assert (res1 == res2).all()\n    assert old_data_size == new_data_size\n    assert len(old_data) == len(new_data)\n    for (k1, g1), (k2, g2) in zip(  # pylint: disable=invalid-name\n        old_data.items(), new_data.items()\n    ):\n        assert k1 == k2\n        assert k1 == g1.group_hash\n        assert k2 == g2.group_hash\n        assert (g1.costs == g2.costs).all()\n        assert len(g1.features) == len(g2.features)\n        for f1, f2 in zip(g1.features, g2.features):  # pylint: disable=invalid-name\n            assert (f1 == f2).all()\n\n\ndef test_meta_schedule_xgb_model_reupdate():\n    extractor = RandomFeatureExtractor()\n    model = XGBModel(extractor=extractor, num_warmup_samples=2)\n    update_sample_count = 60\n    predict_sample_count = 100\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)])\n\n\ndef xgb_version_check():\n\n    # pylint: disable=import-outside-toplevel\n    import xgboost as xgb\n    from packaging import version\n\n    # pylint: enable=import-outside-toplevel\n    return version.parse(xgb.__version__) >= version.parse(\"1.6.0\")\n\n\n@unittest.skipIf(xgb_version_check(), \"test not supported for xgboost version after 1.6.0\")\ndef test_meta_schedule_xgb_model_callback_as_function():\n    # pylint: disable=import-outside-toplevel\n    from itertools import chain as itertools_chain\n\n    import xgboost as xgb\n\n    # pylint: enable=import-outside-toplevel\n\n    extractor = RandomFeatureExtractor()\n    model = XGBModel(extractor=extractor, num_warmup_samples=10)\n    update_sample_count = 20\n    predict_sample_count = 30\n\n    model.update(\n        TuneContext(),\n        [_dummy_candidate() for i in range(update_sample_count)],\n        [_dummy_result() for i in range(update_sample_count)],\n    )\n    model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)])\n    with tempfile.NamedTemporaryFile() as path:\n        # Backup and train on new TrainingCallBack api\n        random_state = model.extractor.random_state  # save feature extractor's random state\n\n        model.save(path.name)\n\n        old_booster = model.booster\n        xs = [  # pylint: disable=invalid-name\n            x.numpy().astype(\"float32\")\n            for x in extractor.extract_from(\n                TuneContext(),\n                [_dummy_candidate() for i in range(predict_sample_count)],\n            )\n        ]\n        d_test = PackSum(xs=xs, ys=None)\n        pred1 = old_booster.predict(d_test.dmatrix)\n\n        # Load and train on deprecated TrainingCallBack api\n        model.extractor.random_state = random_state  # load feature extractor's random state\n        model.load(path.name)\n        d_train = PackSum(\n            xs=list(itertools_chain.from_iterable([g.features for g in model.data.values()])),\n            ys=np.concatenate(\n                [g.min_cost / g.costs for g in model.data.values()],\n                axis=0,\n            ),\n        )\n\n        def obj(ys_pred: np.ndarray, d_train1: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return d_train.obj_square_error(ys_pred)\n\n        def rmse(ys_pred: np.ndarray, d_train1: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return d_train.rmse(ys_pred)\n\n        def avg_peak_score(ys_pred: np.ndarray, d_train1: \"xgb.DMatrix\"):  # type: ignore # pylint: disable = unused-argument\n            return d_train.average_peak_score(ys_pred, model.average_peak_n)\n\n        new_booster = xgb.train(\n            model.config.to_dict(),\n            d_train.dmatrix,\n            num_boost_round=10000,\n            obj=obj,\n            callbacks=[\n                partial(\n                    _get_custom_call_back(\n                        early_stopping_rounds=model.early_stopping_rounds,\n                        verbose_eval=model.verbose_eval,\n                        fevals=[rmse, avg_peak_score],\n                        evals=[(d_train.dmatrix, \"tr\")],\n                        cvfolds=None,\n                    )\n                )\n            ],\n        )\n\n        xs = [  # pylint: disable=invalid-name\n            x.numpy().astype(\"float32\")\n            for x in extractor.extract_from(\n                TuneContext(),\n                [_dummy_candidate() for i in range(predict_sample_count)],\n            )\n        ]\n        d_test = PackSum(xs=xs, ys=None)\n        pred2 = new_booster.predict(d_test.dmatrix)\n\n    assert np.allclose(pred1, pred2, rtol=1e-3, atol=1e-3)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_database.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\"\"\"Test Meta Schedule Database\"\"\"\nimport os.path as osp\nimport tempfile\nfrom typing import Callable, Optional, List\n\nimport tvm\nimport tvm.testing\nfrom tvm.target import Target\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.database import TuningRecord, Workload\nfrom tvm import tir\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nfrom tvm.tir import Schedule\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n# fmt: off\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass MatmulRelu:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, d: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (16, 16), \"float32\")\n        D = T.match_buffer(d, (16, 16), \"float32\")\n        C = T.alloc_buffer((16, 16), \"float32\")\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n        for i, j in T.grid(16, 16):\n            with T.block(\"relu\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef _schedule_matmul(sch: Schedule):\n    block = sch.get_block(\"matmul\")\n    i, j, k = sch.get_loops(block=block)\n    i_tiles = [1, 1, 2, 512]\n    j_tiles = [1, 512, 1, 2]\n    k_tiles = [256, 4]\n    i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=i_tiles)\n    j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=j_tiles)\n    k_0, k_1 = sch.split(loop=k, factors=k_tiles)\n    sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n\n\ndef _create_schedule(mod: IRModule, sch_fn: Callable[[Schedule], None]) -> Schedule:\n    sch = tir.Schedule(mod=mod, debug_mask=\"all\")\n    sch_fn(sch)\n    return sch\n\n\ndef _create_tmp_database(tmpdir: str) -> ms.database.JSONDatabase:\n    path_workload = osp.join(tmpdir, \"workloads.json\")\n    path_tuning_record = osp.join(tmpdir, \"tuning_records.json\")\n    return ms.database.JSONDatabase(path_workload, path_tuning_record)\n\n\ndef _equal_record(a: ms.database.TuningRecord, b: ms.database.TuningRecord):\n    assert str(a.trace) == str(b.trace)\n    assert str(a.run_secs) == str(b.run_secs)\n    # AWAIT(@zxybazh): change to export after fixing \"(bool)0\"\n    assert str(a.target) == str(b.target)\n    assert tvm.ir.structural_equal(a.workload.mod, b.workload.mod)\n    for arg0, arg1 in zip(a.args_info, b.args_info):\n        assert str(arg0.as_json()) == str(arg1.as_json())\n\n\n@ms.utils.derived_object\nclass PyMemoryDatabaseDefault(ms.database.PyDatabase):\n    def __init__(self):\n        super().__init__()\n        self.tuning_records_: List[TuningRecord] = []\n        self.workloads_: List[Workload] = []\n\n    def has_workload(self, mod: IRModule) -> bool:\n        for workload in self.workloads_:\n            if tvm.ir.structural_equal(mod, workload.mod):\n                return True\n\n    def commit_workload(self, mod: IRModule) -> ms.database.Workload:\n        if self.has_workload(mod):\n            for workload in self.workloads_:\n                if tvm.ir.structural_equal(mod, workload.mod):\n                    return workload\n        else:\n            workload = ms.database.Workload(mod)\n            self.workloads_.append(workload)\n            return workload\n\n    def commit_tuning_record(self, record: TuningRecord) -> None:\n        self.tuning_records_.append(record)\n\n    def get_all_tuning_records(self) -> List[TuningRecord]:\n        return self.tuning_records_\n\n    def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]:\n        return sorted(\n            list(\n                filter(\n                    lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod),\n                    self.tuning_records_,\n                )\n            ),\n            key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9,\n        )[:top_k]\n\n    def __len__(self) -> int:\n        return len(self.tuning_records_)\n\n\n@ms.utils.derived_object\nclass PyMemoryDatabaseOverride(ms.database.PyDatabase):\n    def __init__(self):\n        super().__init__()\n        self.tuning_records_: List[TuningRecord] = []\n        self.workloads_: List[Workload] = []\n\n    def has_workload(self, mod: IRModule) -> bool:\n        for workload in self.workloads_:\n            if tvm.ir.structural_equal(mod, workload.mod):\n                return True\n\n    def commit_workload(self, mod: IRModule) -> ms.database.Workload:\n        if self.has_workload(mod):\n            for workload in self.workloads_:\n                if tvm.ir.structural_equal(mod, workload.mod):\n                    return workload\n        else:\n            workload = ms.database.Workload(mod)\n            self.workloads_.append(workload)\n            return workload\n\n    def commit_tuning_record(self, record: TuningRecord) -> None:\n        self.tuning_records_.append(record)\n\n    def get_all_tuning_records(self) -> List[TuningRecord]:\n        return self.tuning_records_\n\n    def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]:\n        return sorted(\n            list(\n                filter(\n                    lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod),\n                    self.tuning_records_,\n                )\n            ),\n            key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9,\n        )[:top_k]\n\n    def __len__(self) -> int:\n        return len(self.tuning_records_)\n\n    def query_tuning_record(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[TuningRecord]:\n        if self.has_workload(mod):\n            records = self.get_top_k(self.commit_workload(mod), 2)\n            if len(records) == 1:\n                return records[0]\n            elif len(records) == 2:\n                return records[1]  # return the 2nd best if there are two records\n        return None\n\n    def query_schedule(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[Schedule]:\n        record = self.query_tuning_record(mod, target, workload_name)\n        if record is not None:\n            sch = Schedule(record.workload.mod)\n            record.trace.apply_to_schedule(sch, remove_postproc=False)\n            return sch\n        return None\n\n    def query_ir_module(\n        self, mod: IRModule, target: Target, workload_name: Optional[str] = None\n    ) -> Optional[IRModule]:\n        record = self.query_tuning_record(mod, target, workload_name)\n        if record is not None:\n            sch = Schedule(record.workload.mod)\n            record.trace.apply_to_schedule(sch, remove_postproc=False)\n            return sch.mod\n        return None\n\n\ndef test_meta_schedule_tuning_record_round_trip():\n    mod: IRModule = Matmul\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        workload = database.commit_workload(mod)\n        record = ms.database.TuningRecord(\n            _create_schedule(mod, _schedule_matmul).trace,\n            workload,\n            [1.5, 2.5, 1.8],\n            tvm.target.Target(\"llvm\"),\n            ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n        )\n        database.commit_tuning_record(record)\n        new_record = ms.database.TuningRecord.from_json(record.as_json(), workload)\n        _equal_record(record, new_record)\n\n\ndef test_meta_schedule_database_create():\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        assert osp.exists(database.path_workload)\n        assert osp.exists(database.path_tuning_record)\n\n\ndef test_meta_schedule_database_has_workload():\n    mod: IRModule = Matmul\n    missing_mod: IRModule = MatmulRelu\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        workload = database.commit_workload(mod)\n        record = ms.database.TuningRecord(\n            _create_schedule(mod, _schedule_matmul).trace,\n            workload,\n            [1.5, 2.5, 1.8],\n            tvm.target.Target(\"llvm\"),\n            ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n        )\n        database.commit_tuning_record(record)\n        assert len(database) == 1\n        assert database.has_workload(mod)\n        assert not database.has_workload(missing_mod)\n\n\ndef test_meta_schedule_database_add_entry():\n    mod: IRModule = Matmul\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        workload = database.commit_workload(mod)\n        record = ms.database.TuningRecord(\n            _create_schedule(mod, _schedule_matmul).trace,\n            workload,\n            [1.5, 2.5, 1.8],\n            tvm.target.Target(\"llvm\"),\n            ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n        )\n        database.commit_tuning_record(record)\n        assert len(database) == 1\n        (ret,) = database.get_top_k(workload, 3)\n        _equal_record(ret, record)\n\n\ndef test_meta_schedule_database_missing():\n    mod: IRModule = Matmul\n    mod_2: IRModule = MatmulRelu\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        workload = database.commit_workload(mod)\n        workload_2 = database.commit_workload(mod_2)\n        record = ms.database.TuningRecord(\n            _create_schedule(mod, _schedule_matmul).trace,\n            workload,\n            [1.5, 2.5, 1.8],\n            tvm.target.Target(\"llvm\"),\n            ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n        )\n        database.commit_tuning_record(record)\n        ret = database.get_top_k(workload_2, 3)\n        assert len(ret) == 0\n\n\ndef test_meta_schedule_database_sorting():\n    mod: IRModule = Matmul\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        token = database.commit_workload(mod)\n        trace = _create_schedule(mod, _schedule_matmul).trace\n        records = [\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [7.0, 8.0, 9.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [1.0, 2.0, 3.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [4.0, 5.0, 6.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [1.1, 1.2, 600.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [1.0, 100.0, 6.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [4.0, 9.0, 8.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n        ]\n        for record in records:\n            database.commit_tuning_record(record)\n        ret = database.get_top_k(token, 2)\n        assert len(ret) == 2\n        try:\n            _equal_record(ret[0], records[2])\n            _equal_record(ret[1], records[1])\n        except AssertionError:\n            _equal_record(ret[0], records[1])\n            _equal_record(ret[1], records[2])\n\n\ndef test_meta_schedule_database_reload():\n    mod: IRModule = Matmul\n    with tempfile.TemporaryDirectory() as tmpdir:\n        database = _create_tmp_database(tmpdir)\n        token = database.commit_workload(mod)\n        trace = _create_schedule(mod, _schedule_matmul).trace\n        records = [\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [7.0, 8.0, 9.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [1.0, 2.0, 3.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n            ms.database.TuningRecord(\n                trace,\n                token,\n                [4.0, 5.0, 6.0],\n                tvm.target.Target(\"llvm\"),\n                ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"]),\n            ),\n        ]\n        for record in records:\n            database.commit_tuning_record(record)\n        new_database = ms.database.JSONDatabase(\n            path_workload=database.path_workload,\n            path_tuning_record=database.path_tuning_record,\n        )\n        token = new_database.commit_workload(mod)\n        ret = new_database.get_top_k(token, 2)\n        assert len(ret) == 2\n        try:\n            _equal_record(ret[0], records[2])\n            _equal_record(ret[1], records[1])\n        except AssertionError:\n            _equal_record(ret[0], records[1])\n            _equal_record(ret[1], records[2])\n\n\ndef test_meta_schedule_database_union():\n    mod: IRModule = Matmul\n    target = tvm.target.Target(\"llvm\")\n    arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"])\n    db_1 = ms.database.MemoryDatabase()\n    db_2 = ms.database.MemoryDatabase()\n    trace = _create_schedule(mod, _schedule_matmul).trace\n\n    def query(db):  # pylint: disable=invalid-name\n        return db.query_tuning_record(mod=mod, target=target, workload_name=\"main\").run_secs\n\n    def commit_record(db, run_sec):  # pylint: disable=invalid-name\n        db.commit_tuning_record(\n            ms.database.TuningRecord(\n                trace,\n                workload=db.commit_workload(mod),\n                run_secs=[run_sec],\n                target=target,\n                args_info=arg_info,\n            )\n        )\n\n    commit_record(db_1, 1.0)\n    (run_sec,) = query(db_1)\n    assert run_sec.value == 1.0\n\n    commit_record(db_2, 0.5)\n    (run_sec,) = query(db_2)\n    assert run_sec.value == 0.5\n\n    (run_secs,) = query(ms.database.UnionDatabase(db_1, db_2))\n    assert run_secs.value == 0.5\n\n    (run_secs,) = query(ms.database.OrderedUnionDatabase(db_1, db_2))\n    assert run_secs.value == 1.0\n\n\ndef test_meta_schedule_pydatabase_default_query():\n\n    mod: IRModule = Matmul\n    target = tvm.target.Target(\"llvm\")\n    arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"])\n    db = PyMemoryDatabaseDefault()  # pylint: disable=invalid-name\n    sch = _create_schedule(mod, _schedule_matmul)\n    trace = sch.trace\n\n    def query(db, mod, target, kind):  # pylint: disable=invalid-name\n        return db.query(mod=mod, target=target, workload_name=\"main\", kind=kind)\n\n    def commit_record(trace, db, run_sec):  # pylint: disable=invalid-name\n        db.commit_tuning_record(\n            ms.database.TuningRecord(\n                trace,\n                workload=db.commit_workload(mod),\n                run_secs=[run_sec],\n                target=target,\n                args_info=arg_info,\n            )\n        )\n\n    commit_record(trace, db, 1.0)\n    record = query(db, mod, target, \"record\")\n    assert record is not None and record.run_secs[0].value == 1.0\n    sch_res = query(db, mod, target, \"schedule\")\n    assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod)\n    mod_res = query(db, mod, target, \"ir_module\")\n    assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod)\n\n    commit_record(Schedule(mod).trace, db, 0.2)  # Empty Trace\n    record = query(db, mod, target, \"record\")\n    assert record is not None and record.run_secs[0].value == 0.2\n    sch_res = query(db, mod, target, \"schedule\")\n    assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, mod)\n    mod_res = query(db, mod, target, \"ir_module\")\n    assert mod_res is not None and tvm.ir.structural_equal(mod_res, mod)\n\n\ndef test_meta_schedule_pydatabase_override_query():\n\n    mod: IRModule = Matmul\n    target = tvm.target.Target(\"llvm\")\n    arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod[\"main\"])\n    db = PyMemoryDatabaseOverride()  # pylint: disable=invalid-name\n    sch = _create_schedule(mod, _schedule_matmul)\n    trace = sch.trace\n\n    def query(db, mod, target, kind):  # pylint: disable=invalid-name\n        return db.query(mod=mod, target=target, workload_name=\"main\", kind=kind)\n\n    def commit_record(trace, db, run_sec):  # pylint: disable=invalid-name\n        db.commit_tuning_record(\n            ms.database.TuningRecord(\n                trace,\n                workload=db.commit_workload(mod),\n                run_secs=[run_sec],\n                target=target,\n                args_info=arg_info,\n            )\n        )\n\n    commit_record(trace, db, 1.14)\n    record = query(db, mod, target, \"record\")\n    assert record is not None and record.run_secs[0].value == 1.14\n    sch_res = query(db, mod, target, \"schedule\")\n    assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod)\n    mod_res = query(db, mod, target, \"ir_module\")\n    assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod)\n\n    commit_record(Schedule(mod).trace, db, 0.514)  # Empty Trace\n    record = query(db, mod, target, \"record\")\n    assert record is not None and record.run_secs[0].value == 1.14  # Override to 2nd best\n    sch_res = query(db, mod, target, \"schedule\")\n    assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod)\n    mod_res = query(db, mod, target, \"ir_module\")\n    assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod)\n\n\ndef test_meta_schedule_pydatabase_current():\n    db = PyMemoryDatabaseDefault()  # pylint: disable=invalid-name\n    with db:  # pylint: disable=not-context-manager\n        assert ms.database.Database.current() == db\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_feature_extractor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport re\nfrom typing import List\n\nimport numpy as np\nfrom tvm.meta_schedule import TuneContext\nfrom tvm.meta_schedule.feature_extractor import PyFeatureExtractor\nfrom tvm.meta_schedule.search_strategy import MeasureCandidate\nfrom tvm.meta_schedule.utils import derived_object\nfrom tvm.runtime.ndarray import array\n\n\ndef test_meta_schedule_feature_extractor():\n    @derived_object\n    class FancyFeatureExtractor(PyFeatureExtractor):\n        def extract_from(\n            self,\n            context: TuneContext,  # pylint: disable = unused-argument\n            candidates: List[MeasureCandidate],  # pylint: disable = unused-argument\n        ) -> List[np.ndarray]:\n            return [array(np.random.rand(4, 5))]\n\n    extractor = FancyFeatureExtractor()\n    features = extractor.extract_from(TuneContext(), [])\n    assert len(features) == 1\n    assert features[0].shape == (4, 5)\n\n\ndef test_meta_schedule_feature_extractor_as_string():\n    @derived_object\n    class NotSoFancyFeatureExtractor(PyFeatureExtractor):\n        def extract_from(\n            self,\n            context: TuneContext,  # pylint: disable = unused-argument\n            candidates: List[MeasureCandidate],  # pylint: disable = unused-argument\n        ) -> List[np.ndarray]:\n            return []\n\n    feature_extractor = NotSoFancyFeatureExtractor()\n    pattern = re.compile(r\"meta_schedule.NotSoFancyFeatureExtractor\\(0x[a-f|0-9]*\\)\")\n    assert pattern.match(str(feature_extractor))\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_feature_extractor()\n    test_meta_schedule_feature_extractor_as_string()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_feature_extractor_per_store_feature.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport sys\nfrom typing import Callable, List\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom numpy.testing import assert_allclose\nfrom tvm import meta_schedule as ms\nfrom tvm import te, tir\nfrom tvm.script import tir as T\n\nN_FEATURES = 164\n\n\n@T.prim_func\ndef matmul(\n    A: T.Buffer[(512, 512), \"float32\"],\n    B: T.Buffer[(512, 512), \"float32\"],\n    C: T.Buffer[(512, 512), \"float32\"],\n) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    # body\n    # with T.block(\"root\")\n    for i0, i1, i2 in T.grid(512, 512, 512):\n        with T.block(\"C\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(C[i, j], A[i, k], B[k, j])\n            T.writes(C[i, j])\n            with T.init():\n                C[i, j] = T.float32(0)\n            C[i, j] = C[i, j] + A[i, k] * B[k, j]\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n# fmt: off\n\n# from tvm.script import tir as T\n@tvm.script.ir_module\nclass LayoutTransform:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(1, 16, 7, 7, 32), \"float32\"], placeholder_1: T.Buffer[(25088,), \"float32\"], T_layout_trans: T.Buffer[(1, 1, 7, 7, 512), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        for i0_i1_i2_i3_i4_fused in T.parallel(25088, annotations={\"pragma_auto_unroll_max_step\":64, \"pragma_unroll_explicit\":1}):\n            with T.block(\"T_layout_trans_1\"):\n                ax0 = T.axis.spatial(1, 0)\n                ax1 = T.axis.spatial(1, 0)\n                ax2 = T.axis.spatial(7, i0_i1_i2_i3_i4_fused // 3584)\n                ax3 = T.axis.spatial(7, i0_i1_i2_i3_i4_fused % 3584 // 512)\n                ax4 = T.axis.spatial(512, i0_i1_i2_i3_i4_fused % 512)\n                T.reads(placeholder[0, (ax4 * 49 + ax2 * 7 + ax3) % 25088 // 1568, (ax2 * 7 + ax3) % 49 // 7, ax3 % 7, (ax4 * 49 + ax2 * 7 + ax3) % 1568 // 49], placeholder_1[(ax4 * 49 + ax2 * 7 + ax3) % 25088])\n                T.writes(T_layout_trans[ax0, ax1, ax2, ax3, ax4])\n                T_layout_trans[ax0, ax1, ax2, ax3, ax4] = T.if_then_else(ax0 < 1 and ax1 * 512 + ax4 < 512 and ax2 < 7 and ax3 < 7, T.Select(T.float32(0) < T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype=\"float32\"), T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype=\"float32\"), T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype=\"float32\") * placeholder_1[((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088]), T.float32(0), dtype=\"float32\")\n\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef _make_context(target) -> ms.TuneContext:\n    return ms.TuneContext(\n        target=target,\n        num_threads=1,\n    )\n\n\ndef _make_candidate(f_sch: Callable[[], tir.Schedule]) -> ms.MeasureCandidate:\n    return ms.MeasureCandidate(sch=f_sch(), args_info=[])\n\n\ndef _feature_names(  # pylint: disable=invalid-name\n    buffers_per_store: int = 5,\n    arith_intensity_curve_num_samples: int = 10,\n) -> List[str]:\n    result = [\n        \"float_mad\",\n        \"float_addsub\",\n        \"float_mul\",\n        \"float_divmod\",\n        \"float_cmp\",\n        \"float_mathfunc\",\n        \"float_otherfunc\",\n        \"int_mad\",\n        \"int_addsub\",\n        \"int_mul\",\n        \"int_divmod\",\n        \"int_cmp\",\n        \"int_mathfunc\",\n        \"int_otherfunc\",\n        \"bool_op\",\n        \"select_op\",\n        \"vec_num\",\n        \"vec_prod\",\n        \"vec_len\",\n        \"vec_type.kPosNone\",\n        \"vec_type.kPosInnerSpatial\",\n        \"vec_type.kPosMiddleSpatial\",\n        \"vec_type.kPosOuterSpatial\",\n        \"vec_type.kPosInnerReduce\",\n        \"vec_type.kPosMiddleReduce\",\n        \"vec_type.kPosOuterReduce\",\n        \"vec_type.kPosMixed\",\n        \"unroll_num\",\n        \"unroll_prod\",\n        \"unroll_len\",\n        \"unroll_type.kPosNone\",\n        \"unroll_type.kPosInnerSpatial\",\n        \"unroll_type.kPosMiddleSpatial\",\n        \"unroll_type.kPosOuterSpatial\",\n        \"unroll_type.kPosInnerReduce\",\n        \"unroll_type.kPosMiddleReduce\",\n        \"unroll_type.kPosOuterReduce\",\n        \"unroll_type.kPosMixed\",\n        \"parallel_num\",\n        \"parallel_prod\",\n        \"parallel_len\",\n        \"parallel_type.kPosNone\",\n        \"parallel_type.kPosInnerSpatial\",\n        \"parallel_type.kPosMiddleSpatial\",\n        \"parallel_type.kPosOuterSpatial\",\n        \"parallel_type.kPosInnerReduce\",\n        \"parallel_type.kPosMiddleReduce\",\n        \"parallel_type.kPosOuterReduce\",\n        \"parallel_type.kPosMixed\",\n        \"is_gpu\",\n        \"blockIdx_x_len\",\n        \"blockIdx_y_len\",\n        \"blockIdx_z_len\",\n        \"threadIdx_x_len\",\n        \"threadIdx_y_len\",\n        \"threadIdx_z_len\",\n        \"vthread_len\",\n    ]\n    for i in range(buffers_per_store):\n        result.extend(\n            f\"B{i}.{s}\"\n            for s in [\n                \"acc_type.kRead\",\n                \"acc_type.kWrite\",\n                \"acc_type.kReadWrite\",\n                \"bytes\",\n                \"unique_bytes\",\n                \"lines\",\n                \"unique_lines\",\n                \"reuse_type.kLoopMultipleRead\",\n                \"reuse_type.kSerialMultipleReadWrite\",\n                \"reuse_type.kNoReuse\",\n                \"reuse_dis_iter\",\n                \"reuse_dis_bytes\",\n                \"reuse_ct\",\n                \"bytes_d_reuse_ct\",\n                \"unique_bytes_d_reuse_ct\",\n                \"lines_d_reuse_ct\",\n                \"unique_lines_d_reuse_ct\",\n                \"stride\",\n            ]\n        )\n    result.extend(f\"arith_intensity_curve_{i}\" for i in range(arith_intensity_curve_num_samples))\n    result.extend(\n        [\n            \"alloc_size\",\n            \"alloc_prod\",\n            \"alloc_outer_prod\",\n            \"alloc_inner_prod\",\n            \"outer_prod\",\n            \"num_loops\",\n            \"auto_unroll_max_step\",\n        ]\n    )\n    # 57 + 18 * 5 + 10 + 4 + 3\n    assert len(result) == N_FEATURES\n    return result\n\n\ndef _zip_feature(feature, names):\n    assert feature.ndim == 1\n    assert feature.shape[0] == N_FEATURES\n    assert len(names) == N_FEATURES\n    return list(zip(names, feature))\n\n\ndef _print_feature(feature, st, ed):  # pylint: disable=invalid-name\n    named_feature = _zip_feature(feature, _feature_names())\n    for k, v in named_feature[st:ed]:\n        print(\"\\t\", k, v)\n\n\ndef test_cpu_matmul():\n    def _create_schedule():\n        func = matmul\n        sch = tir.Schedule(func, debug_mask=\"all\")\n        block = sch.get_block(\"C\")\n        i, j, k = sch.get_loops(block)\n        i_o, i_i = sch.split(i, factors=[None, 16])  # outer: 32\n        j_o, j_i = sch.split(j, factors=[None, 8])  # outer: 64\n        sch.reorder(i_o, j_o, k, j_i, i_i)\n        sch.vectorize(j_i)\n        sch.parallel(i_o)\n        sch.parallel(j_o)\n        sch.unroll(k)\n        return sch\n\n    extractor = ms.feature_extractor.PerStoreFeature()\n    (feature,) = extractor.extract_from(\n        _make_context(tvm.target.Target(\"llvm\")),\n        candidates=[_make_candidate(_create_schedule)],\n    )\n    feature = feature.numpy()\n    assert feature.shape == (1, N_FEATURES)\n    f = feature[0]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        # fmt: off\n        desired=[\n            # float math ops\n            0, 27, 27, 0, 0, 0, 0,\n            # int math ops\n            0, 29, 29, 0, 0, 0, 0,\n            # bool/select ops\n            0, 0,\n        ],\n        # fmt: on\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[1.0, 3.169924, 3.169924, 0, 0, 0, 0, 0, 0, 0, 1],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[1.0, 9.002815, 9.002815, 0, 0, 0, 0, 0, 0, 0, 1],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[1.58496, 11.0007, 6.022368, 0, 0, 0, 0, 0, 0, 0, 1],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer A\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1,\n            0,\n            0,\n            29,\n            20,\n            27,\n            14,\n            1,\n            0,\n            0,\n            4.087463,\n            7.0552826,\n            3.169925,\n            26,\n            17,\n            24,\n            11.0007038,\n            9.002815,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer C\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            0.0,\n            1.0,\n            29.0,\n            20.000001907348633,\n            27.0,\n            14.00008773803711,\n            1.0,\n            0.0,\n            0.0,\n            7.011227130889893,\n            9.250298500061035,\n            9.002815246582031,\n            20.000001907348633,\n            11.000703811645508,\n            18.0000057220459,\n            5.044394016265869,\n            9.002815246582031,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Buffer B\n    assert_allclose(\n        actual=f[93:111],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            29.0,\n            20.000001907348633,\n            19.000001907348633,\n            14.00008773803711,\n            1.0,\n            0.0,\n            0.0,\n            1.0,\n            3.700439691543579,\n            4.087462902069092,\n            25.0,\n            16.000022888183594,\n            15.000043869018555,\n            10.001408194392809,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    # arithmetic intensity = flops/bytes touched = 2*512*512*512/(3 * 4 * 512*512)\n    #                             add and multiply ^     3 arrays ^   ^ 4 bytes per f32\n    # = 85.3 but log2 is used so values should be around 6.4\n    assert_allclose(\n        actual=f[147:157],\n        desired=[\n            3.812599,\n            4.464822,\n            4.912349,\n            5.253426,\n            5.529086,\n            5.76043,\n            5.959752,\n            6.134849,\n            6.290977,\n            6.431846,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            20.000001907348633,\n            18.0000057220459,\n            1.0,\n            27.0,\n            27.0,\n            2.5849626064300537,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n\n\ndef test_cpu_fusion():\n    # pylint: disable=all\n    @T.prim_func\n    def func(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [64, 32], dtype=\"float32\")\n        B = T.match_buffer(b, [64, 32], dtype=\"float32\")\n        C = T.match_buffer(c, [64, 32], dtype=\"float32\")\n        for i, j in T.grid(64, 32):  # type: ignore\n            with T.block():\n                T.reads([A[i, j], B[i, j]])  # type: ignore\n                T.writes([B[i, j], C[i, j]])  # type: ignore\n                with T.block(\"B\"):\n                    T.reads([A[i, j]])  # type: ignore\n                    T.writes([B[i, j]])  # type: ignore\n                    B[i, j] = A[i, j]  # type: ignore\n                with T.block(\"C\"):\n                    T.reads([B[i, j]])  # type: ignore\n                    T.writes([C[i, j]])  # type: ignore\n                    C[i, j] = B[i, j]  # type: ignore\n\n    # pylint: enable=all\n\n    def _create_schedule():\n        return tir.Schedule(func, debug_mask=\"all\")\n\n    extractor = ms.feature_extractor.PerStoreFeature()\n    (feature,) = extractor.extract_from(\n        _make_context(tvm.target.Target(\"llvm\")),\n        candidates=[_make_candidate(_create_schedule)],\n    )\n    feature = feature.numpy()\n    assert feature.shape == (2, N_FEATURES)\n    ## Features for BufferStore(B)\n    f = feature[0]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        # fmt: off\n        desired=[0.0] * 16,\n        # fmt: on\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer A\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            13.000176429748535,\n            13.000176429748535,\n            7.011227130889893,\n            7.011227130889893,\n            0.0,\n            0.0,\n            1.0,\n            0.0,\n            0.0,\n            0.0,\n            14.00008773803711,\n            14.00008773803711,\n            8.005624771118164,\n            8.005624771118164,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer B\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            1.0,\n            0.0,\n            13.000176429748535,\n            13.000176429748535,\n            7.011227130889893,\n            7.011227130889893,\n            0.0,\n            0.0,\n            1.0,\n            0.0,\n            0.0,\n            0.0,\n            14.00008773803711,\n            14.00008773803711,\n            8.005624771118164,\n            8.005624771118164,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Dummy padding\n    assert_allclose(\n        actual=f[93:111],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    assert_allclose(\n        actual=f[147:157],\n        desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            13.000176,\n            11.000703811645508,\n            1.0,\n            11.000703811645508,\n            11.000703811645508,\n            1.5849624872207642,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    ## Features for BufferStore(C)\n    f = feature[1]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        # fmt: off\n        desired=[0.0] * 16,\n        # fmt: on\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer B\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            13.000176429748535,\n            13.000176429748535,\n            7.011227130889893,\n            7.011227130889893,\n            0.0,\n            1.0,\n            0.0,\n            1.0,\n            4.087462902069092,\n            1.0,\n            13.000176429748535,\n            13.000176429748535,\n            7.011227130889893,\n            7.011227130889893,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer C\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            1.0,\n            0.0,\n            13.000176429748535,\n            13.000176429748535,\n            7.011227130889893,\n            7.011227130889893,\n            0.0,\n            0.0,\n            1.0,\n            0.0,\n            0.0,\n            0.0,\n            14.00008773803711,\n            14.00008773803711,\n            8.005624771118164,\n            8.005624771118164,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Dummy padding\n    assert_allclose(\n        actual=f[93:111],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[0.0] * 18,\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    assert_allclose(\n        actual=f[147:157],\n        desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            13.000176429748535,\n            11.000703811645508,\n            1.0,\n            11.000703811645508,\n            11.000703811645508,\n            1.5849624872207642,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n\n\ndef test_gpu():\n    def _create_schedule():\n        func = matmul\n        sch = tir.Schedule(func, debug_mask=\"all\")\n        c = sch.get_block(\"C\")\n        c_local = sch.cache_write(c, 0, \"local\")\n        i, j, k = sch.get_loops(c)\n        # pylint: disable=invalid-name\n        i0, i1, i2, i3, i4 = sch.split(i, factors=[None, 1, 16, 32, 1])  # outer: 1\n        j0, j1, j2, j3, j4 = sch.split(j, factors=[None, 4, 1, 1, 16])  # outer: 8\n        k0, k1, k2 = sch.split(k, factors=[None, 1, 2])  # outer: 256\n        # pylint: enable=invalid-name\n        # fmt: off\n        sch.reorder(\n            i0, j0,  # S\n            i1, j1,  # S\n            i2, j2,  # S\n            k0,      # R\n            k1,      # R\n            i3, j3,  # S\n            k2,      # R\n            i4, j4,  # S\n        )\n        # fmt: on\n        # thread binding\n        i0_j0 = sch.fuse(i0, j0)\n        i1_j1 = sch.fuse(i1, j1)\n        i2_j2 = sch.fuse(i2, j2)\n        sch.bind(i0_j0, \"blockIdx.x\")\n        sch.bind(i1_j1, \"vthread.x\")\n        sch.bind(i2_j2, \"threadIdx.x\")\n        # fusion\n        sch.reverse_compute_at(c_local, i2_j2)\n        # cache read 'A'\n        a_shared = sch.cache_read(c, 1, \"shared\")\n        sch.compute_at(a_shared, k0)\n        _, _, _, _, a_i, a_j = sch.get_loops(a_shared)\n        a_ij = sch.fuse(a_i, a_j)\n        _, a_j = sch.split(a_ij, factors=[None, 16])  # outer: 64\n        sch.bind(a_j, \"threadIdx.x\")\n        # cache read 'B'\n        b_shared = sch.cache_read(c, 2, \"shared\")\n        sch.compute_at(b_shared, k0)\n        _, _, _, _, b_i, b_j = sch.get_loops(b_shared)\n        b_ij = sch.fuse(b_i, b_j)\n        _, b_j = sch.split(b_ij, factors=[None, 16])  # outer: 8\n        sch.bind(b_j, \"threadIdx.x\")\n        # auto unroll\n        sch.annotate(i0_j0, \"pragma_auto_unroll_max_step\", tir.IntImm(\"int32\", 1024))\n        sch.annotate(i0_j0, \"pragma_unroll_explicit\", tir.IntImm(\"int32\", 1))\n        return sch\n\n    extractor = ms.feature_extractor.PerStoreFeature()\n    (feature,) = extractor.extract_from(\n        _make_context(tvm.target.Target(\"cuda\")),\n        candidates=[_make_candidate(_create_schedule)],\n    )\n    feature = feature.numpy()\n    assert feature.shape == (4, N_FEATURES)\n    ### Check feature[0]: BufferStore(A_shared) <= A[...]\n    f = feature[0]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            24.000000085991324,\n            24.000000085991324,\n            24.000000085991324,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer A\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            25.000000042995662,\n            20.000001375860553,\n            23.00000017198264,\n            14.000088052430122,\n            1.0,\n            0.0,\n            0.0,\n            18.00000550343433,\n            20.00562591970089,\n            2.321928094887362,\n            23.00000017198264,\n            18.00000550343433,\n            21.000000687930438,\n            12.0003521774803,\n            12.0003521774803,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer A.shared\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            1.0,\n            0.0,\n            25.000000042995662,\n            12.0003521774803,\n            23.00000017198264,\n            9.002815015607053,\n            1.0,\n            0.0,\n            0.0,\n            6.022367813028454,\n            11.98049663618346,\n            8.005624549193879,\n            17.000011006847668,\n            4.087462841250339,\n            15.000044026886828,\n            1.584962500721156,\n            4.087462841250339,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Dummy padding\n    assert_allclose(\n        actual=f[93:111],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    assert_allclose(\n        actual=f[147:157],\n        desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            12.0003521774803,\n            27.000000010748916,\n            17.000011006847668,\n            6.022367813028454,\n            23.00000017198264,\n            2.584962500721156,\n            10.001408,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    ### Check feature[1]: BufferStore(B_shared) <= B[...]\n    f = feature[1]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            21.584962959341485,\n            21.584962959341485,\n            21.000000687930438,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer B\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            22.00000034396526,\n            20.000001375860553,\n            20.000001375860553,\n            14.000088052430122,\n            1.0,\n            0.0,\n            0.0,\n            15.000044026886828,\n            20.17555076886471,\n            2.321928094887362,\n            20.000001375860553,\n            18.00000550343433,\n            18.00000550343433,\n            12.0003521774803,\n            4.087462841250339,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer B.shared\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            1.0,\n            0.0,\n            22.00000034396526,\n            9.002815015607053,\n            20.000001375860553,\n            3.169925001442312,\n            1.0,\n            0.0,\n            0.0,\n            3.169925001442312,\n            9.61654884377899,\n            8.005624549193879,\n            14.000088052430122,\n            1.584962500721156,\n            12.0003521774803,\n            0.044394119358453436,\n            4.087462841250339,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Dummy padding\n    assert_allclose(\n        actual=f[93:111],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    assert_allclose(\n        actual=f[147:157],\n        desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            9.002815015607053,\n            24.000000085991324,\n            17.000011006847668,\n            3.169925001442312,\n            20.000001375860553,\n            2.584962500721156,\n            10.001408,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    ### Check feature[2]: BufferStore(C_local) <= C_local[...] + A_shared[...] * B_shared[...]\n    f = feature[2]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        desired=[\n            0.0,\n            27.000000010748916,\n            27.000000010748916,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            28.000000005374456,\n            28.000000005374456,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer B.shared\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            29.00000000268723,\n            9.002815015607053,\n            23.00000017198264,\n            3.169925001442312,\n            1.0,\n            0.0,\n            0.0,\n            5.044394119358453,\n            7.651051691178929,\n            5.044394119358453,\n            24.000000085991324,\n            4.087462841250339,\n            18.00000550343433,\n            0.32192809488736235,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer C.local\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            0.0,\n            0.0,\n            1.0,\n            29.00000000268723,\n            11.000704269011246,\n            23.00000017198264,\n            5.044394119358453,\n            1.0,\n            0.0,\n            0.0,\n            4.087462841250339,\n            7.05528243550119,\n            1.584962500721156,\n            28.000000005374456,\n            10.001408194392809,\n            22.00000034396526,\n            4.087462841250339,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Buffer A.shared\n    assert_allclose(\n        actual=f[93:111],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            29.00000000268723,\n            12.0003521774803,\n            19.00000275171979,\n            9.002815015607053,\n            1.0,\n            0.0,\n            0.0,\n            1.0,\n            3.700439718141092,\n            4.087462841250339,\n            25.000000042995662,\n            8.005624549193879,\n            15.000044026886828,\n            5.044394119358453,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    # Arithmetic intensity is high here because of repeated use of a shared\n    # buffer. Multiple accesses to the same memory location are counted as a\n    # single byte, skewing these numbers towards higher intensity.\n    assert_allclose(\n        actual=f[147:157],\n        desired=[\n            11.98533,\n            12.977811,\n            13.562714,\n            13.977722,\n            14.299632,\n            14.562654,\n            14.785038,\n            14.977677,\n            15.147597,\n            15.299596,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            11.000704269011246,\n            18.00000550343433,\n            9.002815015607053,\n            18.00000550343433,\n            27.000000010748916,\n            3.0,\n            10.001408,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    ### Check feature[3]: BufferStore(C) <= C_local[...]\n    f = feature[3]\n    # Group 1.1: arith\n    assert_allclose(\n        actual=f[0:16],\n        desired=[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],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.2: vectorize\n    assert_allclose(\n        actual=f[16:27],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.3: unroll\n    assert_allclose(\n        actual=f[27:38],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.4: parallel\n    assert_allclose(\n        actual=f[38:49],\n        desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread\n    assert_allclose(\n        actual=f[49:57],\n        desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.1: Buffer C\n    assert_allclose(\n        actual=f[57:75],\n        desired=[\n            0.0,\n            1.0,\n            0.0,\n            20.000001375860553,\n            20.000001375860553,\n            14.000088052430122,\n            14.000088052430122,\n            0.0,\n            0.0,\n            1.0,\n            0.0,\n            0.0,\n            0.0,\n            21.000000687930438,\n            21.000000687930438,\n            15.000044026886828,\n            15.000044026886828,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.2: Buffer C.local\n    assert_allclose(\n        actual=f[75:93],\n        desired=[\n            1.0,\n            0.0,\n            0.0,\n            20.000001375860553,\n            11.000704269011246,\n            14.000088052430122,\n            5.044394119358453,\n            1.0,\n            0.0,\n            0.0,\n            9.002815015607053,\n            12.0003521774803,\n            4.087462841250339,\n            16.00002201361136,\n            7.011227255423254,\n            10.001408194392809,\n            1.584962500721156,\n            1.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.3: Dummy padding\n    assert_allclose(\n        actual=f[93:111],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.4: Dummy padding\n    assert_allclose(\n        actual=f[111:129],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 2.5: Dummy padding\n    assert_allclose(\n        actual=f[129:147],\n        desired=[\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n            0.0,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 3: Arithmetic intensity\n    assert_allclose(\n        actual=f[147:157],\n        desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n    # Group 4 & 5\n    assert_allclose(\n        actual=f[157:164],\n        desired=[\n            20.000001375860553,\n            18.00000550343433,\n            1.0,\n            18.00000550343433,\n            18.00000550343433,\n            2.584962500721156,\n            10.001408,\n        ],\n        rtol=1e-5,\n        atol=1e-5,\n    )\n\n\ndef test_cpu_layout_transform():\n    extractor = ms.feature_extractor.PerStoreFeature()\n    (feature,) = extractor.extract_from(\n        _make_context(tvm.target.Target(\"llvm\")),\n        candidates=[_make_candidate(lambda: tir.Schedule(LayoutTransform))],\n    )\n\n\n@T.prim_func\ndef negative_extent(A: T.Buffer[(1,), \"float32\"]):\n    for j in range(0, -1):\n        A[j] = A[j] + 1.0\n\n\ndef test_negative_extent():\n    extractor = ms.feature_extractor.PerStoreFeature()\n    (features,) = extractor.extract_from(\n        _make_context(tvm.target.Target(\"llvm\")),\n        candidates=[_make_candidate(lambda: tir.Schedule(negative_extent))],\n    )\n    named_features = dict(zip(_feature_names(), list(features.numpy()[0, :])))\n    assert named_features[\"B0.unique_bytes\"] == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_measure_callback.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport re\nimport tempfile\nfrom typing import List\n\nimport pytest\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import Schedule\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,\n# fmt: off\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef test_meta_schedule_measure_callback():\n    @ms.derived_object\n    class FancyMeasureCallback(ms.measure_callback.PyMeasureCallback):\n        def apply(\n            self,\n            task_scheduler: ms.task_scheduler.TaskScheduler,\n            task_id: int,\n            measure_candidates: List[ms.MeasureCandidate],\n            builder_results: List[ms.builder.BuilderResult],\n            runner_results: List[ms.runner.RunnerResult],\n        ) -> None:\n            assert len(measure_candidates) == 1\n            tvm.ir.assert_structural_equal(measure_candidates[0].sch.mod, Matmul)\n            assert (\n                len(builder_results) == 1\n                and builder_results[0].error_msg is None\n                and builder_results[0].artifact_path == \"test_build\"\n            )\n            assert (\n                len(runner_results) == 1\n                and runner_results[0].error_msg is None\n                and len(runner_results[0].run_secs) == 2\n            )\n\n    measure_callback = FancyMeasureCallback()\n    measure_callback.apply(\n        ms.task_scheduler.RoundRobin(),\n        0,\n        [ms.MeasureCandidate(Schedule(Matmul), None)],\n        [ms.builder.BuilderResult(\"test_build\", None)],\n        [ms.runner.RunnerResult([1.0, 2.1], None)],\n    )\n\n\ndef test_meta_schedule_measure_callback_fail():\n    @ms.derived_object\n    class FailingMeasureCallback(ms.measure_callback.PyMeasureCallback):\n        def apply(\n            self,\n            task_scheduler: ms.task_scheduler.TaskScheduler,\n            task_id: int,\n            measure_candidates: List[ms.MeasureCandidate],\n            builder_results: List[ms.builder.BuilderResult],\n            runner_results: List[ms.runner.RunnerResult],\n        ) -> None:\n            raise ValueError(\"test\")\n\n    measure_callback = FailingMeasureCallback()\n    with pytest.raises(ValueError, match=\"test\"):\n        measure_callback.apply(\n            ms.task_scheduler.RoundRobin(),\n            0,\n            [ms.MeasureCandidate(Schedule(Matmul), None)],\n            [ms.builder.BuilderResult(\"test_build\", None)],\n            [ms.runner.RunnerResult([1.0, 2.1], None)],\n        )\n\n\ndef test_meta_schedule_measure_callback_as_string():\n    @ms.derived_object\n    class NotSoFancyMeasureCallback(ms.measure_callback.PyMeasureCallback):\n        def apply(\n            self,\n            task_scheduler: ms.task_scheduler.TaskScheduler,\n            task_id: int,\n            measure_candidates: List[ms.MeasureCandidate],\n            builder_results: List[ms.builder.BuilderResult],\n            runner_results: List[ms.runner.RunnerResult],\n        ) -> None:\n            pass\n\n    measure_callback = NotSoFancyMeasureCallback()\n    pattern = re.compile(r\"meta_schedule.NotSoFancyMeasureCallback\\(0x[a-f|0-9]*\\)\")\n    assert pattern.match(str(measure_callback))\n\n\ndef test_meta_schedule_measure_callback_update_cost_model_with_zero():\n    @ms.derived_object\n    class AllZeroRunnerFuture(ms.runner.PyRunnerFuture):\n        def done(self) -> bool:\n            return True\n\n        def result(self) -> ms.runner.RunnerResult:\n            return ms.runner.RunnerResult([0.0, 0.0], None)\n\n    @ms.derived_object\n    class AllZeroRunner(ms.runner.PyRunner):\n        def run(self, runner_inputs: List[ms.runner.RunnerInput]) -> List[ms.runner.RunnerResult]:\n            return [AllZeroRunnerFuture() for _ in runner_inputs]\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        ms.tune_tir(\n            mod=Matmul,\n            target=\"llvm -num-cores=1\",\n            work_dir=work_dir,\n            max_trials_global=10,\n            runner=AllZeroRunner(),\n            measure_callbacks=[ms.measure_callback.UpdateCostModel()],\n        )\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_measure_callback()\n    test_meta_schedule_measure_callback_fail()\n    test_meta_schedule_measure_callback_as_string()\n    test_meta_schedule_measure_callback_update_cost_model_with_zero()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_multi_anchor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\n\n\ndef get_dense_dense(data_shape, weight_shape):\n    def multi_dense():\n        p_data = relay.var(\"p_data\", shape=data_shape, dtype=\"float32\")\n        p_weight1 = relay.var(\"p_weight1\", shape=weight_shape, dtype=\"float32\")\n        p_weight2 = relay.var(\"p_weight2\", shape=weight_shape, dtype=\"float32\")\n        dense1 = relay.nn.dense(p_data, p_weight1)\n        dense2 = relay.nn.dense(dense1, p_weight2)\n        f = relay.Function([p_data, p_weight1, p_weight2], dense2)\n        f = f.with_attr(\"Primitive\", tvm.tir.IntImm(\"int32\", 1))\n        return f\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight1 = relay.var(\"weight1\", shape=weight_shape, dtype=\"float32\")\n    weight2 = relay.var(\"weight2\", shape=weight_shape, dtype=\"float32\")\n    out = relay.Call(multi_dense(), [data, weight1, weight2])\n    return relay.Function([data, weight1, weight2], out)\n\n\ndef get_ref(data_np, weight1_np, weight2_np):\n    dense1 = np.dot(data_np, np.transpose(weight1_np))\n    return np.dot(dense1, np.transpose(weight2_np))\n\n\ndef schedule_dense_dense(sch):\n    dense1 = sch.get_block(\"T_matmul_NT\")\n    dense2 = sch.get_block(\"T_matmul_NT_1\")\n    _y1, _x1, _k1 = sch.get_loops(dense1)\n    _y2, _x2, _k2 = sch.get_loops(dense2)\n\n\ndef test_dense_dense():\n    M, N, K = 128, 128, 128\n    data_shape = (M, K)\n    weight_shape = (N, K)\n    relay_mod = tvm.IRModule.from_expr(get_dense_dense(data_shape, weight_shape))\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    weight1_np = np.random.randn(*weight_shape).astype(\"float32\")\n    weight2_np = np.random.randn(*weight_shape).astype(\"float32\")\n    target = \"llvm\"\n    params = {\"weight1\": weight1_np, \"weight2\": weight2_np}\n\n    def schedule_fn(sch):\n        if \"nn_dense_nn_dense\" in sch.mod.attrs[\"task_name\"]:\n            schedule_dense_dense(sch)\n            return True\n        return False\n\n    with ms.database.ScheduleFnDatabase(schedule_fn):\n        with tvm.transform.PassContext(\n            opt_level=3,\n            config={\"relay.backend.use_meta_schedule\": True},\n        ):\n            lib = relay.build(relay_mod, target=target, params=params)\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n    out = runtime.get_output(0).numpy()\n    ref = get_ref(data_np, weight1_np, weight2_np)\n    tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4)\n\n\nif __name__ == \"__main__\":\n    test_dense_dense()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_mutator_mutate_compute_location.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name, no-member\n\n\n@T.prim_func\ndef add(a: T.handle, b: T.handle) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\"})\n    A = T.match_buffer(a, [2048, 2048, 2048], dtype=\"float32\")\n    B = T.match_buffer(b, [2048, 2048, 2048], dtype=\"float32\")\n    A_cached = T.alloc_buffer([2048, 2048, 2048], dtype=\"float32\")\n    # body\n    for i, j, k in T.grid(2048, 2048, 2048):\n        with T.block(\"move\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            T.reads([A[vi, vj, vk]])\n            T.writes([A_cached[vi, vj, vk]])\n            A_cached[vi, vj, vk] = A[vi, vj, vk]\n    for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32):\n        with T.block(\"add\"):\n            vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2)\n            vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2)\n            vk = T.axis.spatial(2048, k0 * 32 + k1)\n            T.reads([A_cached[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1)\n\n\n# pylint: enable=invalid-name, no-member\n\n\ndef _sch(decision: int) -> Schedule:\n    sch = Schedule(add, debug_mask=\"all\")\n    # pylint: disable=invalid-name\n    b0 = sch.get_block(name=\"move\", func_name=\"main\")\n    l1 = sch.sample_compute_location(block=b0, decision=decision)\n    sch.compute_at(block=b0, loop=l1, preserve_unit_loops=True)\n    # pylint: enable=invalid-name\n    return sch\n\n\ndef _make_mutator(target: Target) -> ms.Mutator:\n    ctx = ms.TuneContext(\n        mod=add,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={ms.mutator.MutateComputeLocation(): 1.0},\n        ),\n    )\n    return list(ctx.space_generator.mutator_probs.keys())[0]\n\n\ndef test_mutate_compute_location_add():\n    mutator = _make_mutator(\n        target=Target(\"llvm\"),\n    )\n    sch = _sch(decision=4)\n    results = set()\n    for _ in range(100):\n        trace = mutator.apply(sch.trace)\n        decision = trace.decisions[trace.insts[-2]]\n        assert not decision == 4\n        results.add(decision)\n    assert len(results) == 9\n\n\nif __name__ == \"__main__\":\n    test_mutate_compute_location_add()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_mutator_mutate_parallel.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom typing import List\n\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name, no-member\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [512, 512])\n    B = T.match_buffer(b, [512, 512])\n    C = T.match_buffer(c, [512, 512])\n    for i, j, k in T.grid(512, 512, 512):  # type: ignore\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])  # type: ignore\n            with T.init():\n                C[vi, vj] = 0.0  # type: ignore\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n# pylint: enable=invalid-name, no-member\n\n\ndef _sch(decisions: List[List[int]], ann_val: int) -> Schedule:\n    sch = Schedule(matmul, debug_mask=\"all\")\n    # pylint: disable=invalid-name\n    d0, d1, d2 = decisions\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    root = sch.get_block(name=\"root\", func_name=\"main\")\n    sch.get_consumers(block=b0)\n    b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"global\")\n    l2, l3, l4 = sch.get_loops(block=b0)\n    v5, v6, v7, v8 = sch.sample_perfect_tile(\n        loop=l2,\n        n=4,\n        max_innermost_factor=64,\n        decision=d0,\n    )\n    l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8])\n    v13, v14, v15, v16 = sch.sample_perfect_tile(\n        loop=l3,\n        n=4,\n        max_innermost_factor=64,\n        decision=d1,\n    )\n    l17, l18, l19, l20 = sch.split(loop=l3, factors=[v13, v14, v15, v16])\n    v21, v22 = sch.sample_perfect_tile(\n        loop=l4,\n        n=2,\n        max_innermost_factor=64,\n        decision=d2,\n    )\n    l23, l24 = sch.split(loop=l4, factors=[v21, v22])\n    sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20)\n    sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True)\n    sch.annotate(block_or_loop=root, ann_key=\"meta_schedule.parallel\", ann_val=ann_val)\n    # pylint: enable=invalid-name\n    return sch\n\n\ndef _make_mutator(target: Target, max_jobs_per_core: int) -> ms.Mutator:\n    ctx = ms.TuneContext(\n        mod=matmul,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={ms.mutator.MutateParallel(max_jobs_per_core): 1.0},\n        ),\n    )\n    return list(ctx.space_generator.mutator_probs.keys())[0]\n\n\ndef test_mutate_parallel_matmul():\n    mutator = _make_mutator(\n        target=Target(\"llvm --num-cores=16\"),\n        max_jobs_per_core=256,\n    )\n    sch = _sch(\n        decisions=[\n            [4, 32, 4, 1],\n            [8, 4, 8, 2],\n            [512, 1],\n        ],\n        ann_val=64,\n    )\n    results = set()\n    for _ in range(100):\n        trace = mutator.apply(sch.trace)\n        ann_val = int(trace.insts[-1].inputs[1])\n        results.add(ann_val)\n        if len(results) == 3:\n            break\n    assert len(results) == 3\n    assert results == {4, 32, 4096}\n\n\nif __name__ == \"\"\"__main__\"\"\":\n    test_mutate_parallel_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_mutator_mutate_thread_binding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name, no-member\n\n\n@T.prim_func\ndef element_wise(var_A: T.handle, var_B: T.handle) -> None:\n    A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n    B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n    for i, j in T.grid(512, 512):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] + 1.0\n\n\n# pylint: enable=invalid-name, no-member\n\n\ndef _sch() -> Schedule:\n    sch = Schedule(element_wise, debug_mask=\"all\")\n    # pylint: disable=invalid-name\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    l1, l2 = sch.get_loops(block=b0)\n    l3 = sch.fuse(l1, l2)\n    v4 = sch.sample_categorical(\n        candidates=[32, 64, 128, 256, 512, 1024],\n        probs=[\n            0.16666666666666666,\n            0.16666666666666666,\n            0.16666666666666666,\n            0.16666666666666666,\n            0.16666666666666666,\n            0.16666666666666666,\n        ],\n        decision=3,\n    )\n    l5, l6 = sch.split(loop=l3, factors=[None, v4])\n    sch.bind(loop=l5, thread_axis=\"blockIdx.x\")\n    sch.bind(loop=l6, thread_axis=\"threadIdx.x\")\n    # pylint: enable=invalid-name\n    return sch\n\n\ndef _make_mutator(target: Target) -> ms.Mutator:\n    ctx = ms.TuneContext(\n        mod=element_wise,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={ms.mutator.MutateThreadBinding(): 1.0},\n        ),\n    )\n    return list(ctx.space_generator.mutator_probs.keys())[0]\n\n\ndef test_mutate_thread_binding():\n    mutator = _make_mutator(target=Target(\"cuda\"))\n    sch = _sch()\n    results = set()\n    for _ in range(100):\n        trace = mutator.apply(sch.trace)\n        decision = trace.decisions[trace.insts[-4]]\n        results.add(decision)\n        if len(results) == 5:\n            break\n    assert len(results) == 5\n    assert results == {0, 1, 2, 4, 5}\n\n\nif __name__ == \"__main__\":\n    test_mutate_thread_binding()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_mutator_mutate_tile_size.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport operator\nfrom functools import reduce\nfrom typing import List\n\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name, no-member\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [512, 512])\n    B = T.match_buffer(b, [512, 512])\n    C = T.match_buffer(c, [512, 512])\n    for i, j, k in T.grid(512, 512, 512):  # type: ignore\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])  # type: ignore\n            with T.init():\n                C[vi, vj] = 0.0  # type: ignore\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n# pylint: enable=invalid-name, no-member\n\n\ndef _sch(decisions: List[List[int]]) -> Schedule:\n    sch = Schedule(matmul, debug_mask=\"all\")\n    # pylint: disable=invalid-name\n    (d0,) = decisions\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    sch.get_consumers(block=b0)\n    b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"global\")\n    l2, l3, l4 = sch.get_loops(block=b0)\n    v5, v6, v7, v8 = sch.sample_perfect_tile(\n        loop=l2,\n        n=4,\n        max_innermost_factor=64,\n        decision=d0,\n    )\n    l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8])\n    l17, l18, l19, l20 = sch.split(loop=l3, factors=[8, 4, 8, 2])\n    l23, l24 = sch.split(loop=l4, factors=[512, 1])\n    sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20)\n    sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True)\n    # pylint: enable=invalid-name\n    return sch\n\n\ndef _make_mutator(target: Target) -> ms.Mutator:\n    ctx = ms.TuneContext(\n        mod=matmul,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={ms.mutator.MutateTileSize(): 1.0},\n        ),\n    )\n    return list(ctx.space_generator.mutator_probs.keys())[0]\n\n\ndef test_mutate_tile_size_matmul():\n    mutator = _make_mutator(\n        target=Target(\"llvm --num-cores=16\"),\n    )\n    results = {}\n    sch = _sch(decisions=[[4, 32, 4, 1]])\n    for _ in range(1000):\n        trace = mutator.apply(sch.trace)\n        assert trace.insts[4].kind.name == \"SamplePerfectTile\"\n        decision = trace.decisions[trace.insts[4]]\n        decision = [int(x) for x in decision]\n        results[str(decision)] = decision\n        assert reduce(operator.mul, decision, 1) == 512\n    assert len(results) > 15\n\n\nif __name__ == \"__main__\":\n    test_mutate_tile_size_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_mutator_mutate_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom typing import List\n\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name, no-member\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [512, 512])\n    B = T.match_buffer(b, [512, 512])\n    C = T.match_buffer(c, [512, 512])\n    for i, j, k in T.grid(512, 512, 512):  # type: ignore\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])  # type: ignore\n            with T.init():\n                C[vi, vj] = 0.0  # type: ignore\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n# pylint: enable=invalid-name, no-member\n\n\ndef _sch(decisions: List[List[int]]) -> Schedule:\n    sch = Schedule(matmul, debug_mask=\"all\")\n    # pylint: disable=invalid-name\n    d0, d1, d2 = decisions\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    root = sch.get_block(name=\"root\", func_name=\"main\")\n    sch.get_consumers(block=b0)\n    b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"global\")\n    l2, l3, l4 = sch.get_loops(block=b0)\n    v5, v6, v7, v8 = sch.sample_perfect_tile(\n        loop=l2,\n        n=4,\n        max_innermost_factor=64,\n        decision=d0,\n    )\n    l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8])\n    v13, v14, v15, v16 = sch.sample_perfect_tile(\n        loop=l3,\n        n=4,\n        max_innermost_factor=64,\n        decision=d1,\n    )\n    l17, l18, l19, l20 = sch.split(loop=l3, factors=[v13, v14, v15, v16])\n    v21, v22 = sch.sample_perfect_tile(\n        loop=l4,\n        n=2,\n        max_innermost_factor=64,\n        decision=d2,\n    )\n    l23, l24 = sch.split(loop=l4, factors=[v21, v22])\n    sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20)\n    sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True)\n    v57 = sch.sample_categorical(\n        candidates=[0, 16, 64, 512],\n        probs=[0.25, 0.25, 0.25, 0.25],\n        decision=0,\n    )\n    sch.annotate(block_or_loop=root, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v57)\n    # pylint: enable=invalid-name\n    return sch\n\n\ndef _make_mutator(target: Target) -> ms.Mutator:\n    ctx = ms.TuneContext(\n        mod=matmul,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={ms.mutator.MutateUnroll(): 1.0},\n        ),\n    )\n    return list(ctx.space_generator.mutator_probs.keys())[0]\n\n\ndef test_mutate_unroll_matmul():\n    mutator = _make_mutator(target=Target(\"llvm --num-cores=16\"))\n    sch = _sch(\n        decisions=[\n            [4, 32, 4, 1],\n            [8, 4, 8, 2],\n            [512, 1],\n        ],\n    )\n    results = set()\n    for _ in range(100):\n        trace = mutator.apply(sch.trace)\n        decision = trace.decisions[trace.insts[-2]]\n        results.add(decision)\n        if len(results) == 3:\n            break\n    assert len(results) == 3\n    assert results == {1, 2, 3}\n\n\nif __name__ == \"\"\"__main__\"\"\":\n    test_mutate_unroll_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_post_order_apply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport math\nimport sys\nfrom typing import List\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm._ffi import register_func\nfrom tvm.error import TVMError\nfrom tvm.meta_schedule import TuneContext\nfrom tvm.meta_schedule.schedule_rule import PyScheduleRule\nfrom tvm.meta_schedule.space_generator import PostOrderApply\nfrom tvm.meta_schedule.utils import derived_object\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir.schedule import BlockRV, Schedule\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,\n# fmt: off\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass DuplicateMatmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass TrinityMatmul:\n    @T.prim_func\n    def main(a: T.handle, d: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.alloc_buffer((1024, 1024), \"float32\")\n        C = T.alloc_buffer((1024, 1024), \"float32\")\n        D = T.match_buffer(d, (1024, 1024), \"float32\")\n        for i, j in T.grid(1024, 1024):\n            with T.block(\"A\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for i, j in T.grid(1024, 1024):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 3.0\n        for i, j in T.grid(1024, 1024):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                D[vi, vj] = C[vi, vj] * 5.0\n\n\n@tvm.script.ir_module\nclass TrinityMatmulProcessedForReference:\n    @T.prim_func\n    def main(a: T.handle, d: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, [1024, 1024], dtype=\"float32\")\n        D = T.match_buffer(d, [1024, 1024], dtype=\"float32\")\n        # body\n        # with tir.block(\"root\")\n        B = T.alloc_buffer([1024, 1024], dtype=\"float32\")\n        for i0_0, i1_0, i0_1, i1_1 in T.grid(16, 64, 64, 16):\n            with T.block(\"A\"):\n                vi = T.axis.S(1024, i0_0 * 64 + i0_1)\n                vj = T.axis.S(1024, i1_0 * 16 + i1_1)\n                T.reads([A[vi, vj]])\n                T.writes([B[vi, vj]])\n                B[vi, vj] = A[vi, vj] * T.float32(2)\n        for i0_0, i1_0, i0_1, i1_1 in T.grid(16, 64, 64, 16):\n            with T.block(\"C\"):\n                vi = T.axis.S(1024, i0_0 * 64 + i0_1)\n                vj = T.axis.S(1024, i1_0 * 16 + i1_1)\n                T.reads([B[vi, vj]])\n                T.writes([D[vi, vj]])\n                D[vi, vj] = (B[vi, vj] + T.float32(3)) * T.float32(5)\n\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef _is_root(sch: Schedule, block: BlockRV) -> bool:\n    return sch.get_sref(block).parent is None\n\n\ndef _check_correct(schedule: Schedule):\n    trace = schedule.trace\n    for inst in trace.decisions:\n        assert math.prod(trace.decisions[inst]) == 1024\n\n\n@derived_object\nclass WowSoFancyScheduleRule(PyScheduleRule):\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        pass\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        if _is_root(sch, block):\n            return [sch]\n        new_sch = sch.copy()\n        i, j, k = new_sch.get_loops(block=block)\n        i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[2, 4, 64, 2])\n        j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[4, 64, 2, 2])\n        k_0, k_1 = new_sch.split(loop=k, factors=[32, 32])\n        new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n        return [new_sch]\n\n\n@derived_object\nclass DoubleScheduleRule(PyScheduleRule):\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        pass\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        if _is_root(sch, block):\n            return [sch]\n        new_sch = sch.copy()\n        i, j, k = new_sch.get_loops(block=block)\n        i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[4, 64, 2, 2])\n        j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[2, 4, 64, 2])\n        k_0, k_1 = new_sch.split(loop=k, factors=[32, 32])\n        new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n        result = [new_sch]\n        new_sch = sch.copy()\n        i, j, k = new_sch.get_loops(block=block)\n        i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[4, 64, 2, 2])\n        j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[2, 4, 64, 2])\n        k_0, k_1 = new_sch.split(loop=k, factors=[32, 32])\n        new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n        result.append(new_sch)\n        return result\n\n\n@derived_object\nclass TrinityDoubleRule(PyScheduleRule):\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        pass\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        if _is_root(sch, block):\n            return [sch]\n        new_sch = sch.copy()\n        i, j = new_sch.get_loops(block=block)\n        i_0, i_1 = new_sch.split(loop=i, factors=[16, 64])\n        j_0, j_1 = new_sch.split(loop=j, factors=[64, 16])\n        new_sch.reorder(i_0, j_0, i_1, j_1)\n        result = [new_sch]\n        new_sch = sch.copy()\n        i, j = new_sch.get_loops(block=block)\n        i_0, i_1 = new_sch.split(loop=i, factors=[2, 512])\n        j_0, j_1 = new_sch.split(loop=j, factors=[2, 512])\n        new_sch.reorder(i_0, j_0, i_1, j_1)\n        result.append(new_sch)\n        return result\n\n\n@derived_object\nclass ReorderScheduleRule(PyScheduleRule):\n    def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n        pass\n\n    def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n        if _is_root(sch, block):\n            return [sch]\n        new_sch = sch.copy()\n        i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3 = new_sch.get_loops(block=block)\n        new_sch.reorder(i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3, i_0, j_0)\n        result = [new_sch]\n        new_sch = sch.copy()\n        i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3 = new_sch.get_loops(block=block)\n        new_sch.reorder(i_1, j_3, i_0, j_0, j_1, k_0, i_2, j_2, k_1, i_3)\n        result.append(new_sch)\n        return result\n\n\ndef test_meta_schedule_post_order_apply():\n    mod = Matmul\n    context = TuneContext(\n        mod=mod,\n        target=Target(\"llvm\"),\n        task_name=\"Test Task\",\n        space_generator=PostOrderApply(\n            sch_rules=[WowSoFancyScheduleRule()],\n            postprocs=[],\n            mutator_probs={},\n        ),\n    )\n    post_order_apply = context.space_generator\n    schs = post_order_apply.generate_design_space(mod)\n    assert len(schs) == 1\n    assert not tvm.ir.structural_equal(schs[0].mod, mod)\n    _check_correct(schs[0])\n\n\ndef test_meta_schedule_post_order_apply_double():\n    mod = Matmul\n    context = TuneContext(\n        mod=mod,\n        target=Target(\"llvm\"),\n        task_name=\"Double Rules Task\",\n        space_generator=PostOrderApply(\n            sch_rules=[DoubleScheduleRule()],\n            postprocs=[],\n            mutator_probs={},\n        ),\n    )\n    post_order_apply = context.space_generator\n    schs = post_order_apply.generate_design_space(mod)\n    assert len(schs) == 2\n    for sch in schs:\n        assert not tvm.ir.structural_equal(sch.mod, mod)\n        _check_correct(sch)\n\n\ndef test_meta_schedule_post_order_apply_multiple():\n    mod = Matmul\n    context = TuneContext(\n        mod=mod,\n        target=Target(\"llvm\"),\n        task_name=\"Double Rules Task\",\n        space_generator=PostOrderApply(\n            sch_rules=[DoubleScheduleRule(), ReorderScheduleRule()],\n            postprocs=[],\n            mutator_probs={},\n        ),\n    )\n    post_order_apply = context.space_generator\n    schs = post_order_apply.generate_design_space(mod)\n    assert len(schs) == 4\n    for sch in schs:\n        assert not tvm.ir.structural_equal(sch.mod, mod)\n        _check_correct(sch)\n\n\ndef test_meta_schedule_post_order_apply_duplicate_matmul():\n    mod = DuplicateMatmul\n    context = TuneContext(\n        mod=mod,\n        target=Target(\"llvm\"),\n        task_name=\"Duplicate Matmul Task\",\n        space_generator=PostOrderApply(\n            sch_rules=[WowSoFancyScheduleRule()],\n            postprocs=[],\n            mutator_probs={},\n        ),\n    )\n    post_order_apply = context.space_generator\n    with pytest.raises(\n        TVMError,\n        match=r\".*TVMError: Check failed: \\(block_names_.count\\(block->name_hint\\) == 0\\)\"\n        r\" is false: Duplicated block name matmul in function main not supported!\",\n    ):\n        post_order_apply.generate_design_space(mod)\n\n\ndef test_meta_schedule_post_order_apply_remove_block():\n    @derived_object\n    class RemoveBlock(PyScheduleRule):\n        def _initialize_with_tune_context(self, context: \"TuneContext\") -> None:\n            pass\n\n        def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]:\n            if _is_root(sch, block):\n                return [sch]\n            sch = sch.copy()\n            if sch.get(block).name_hint == \"B\":\n                sch.compute_inline(block)\n            return [sch]\n\n    def correct_trace(a, b, c, d):\n        return \"\\n\".join(\n            [\n                \"# from tvm import tir\",\n                \"def apply_trace(sch: tir.Schedule) -> None:\",\n                '  b0 = sch.get_block(name=\"A\", func_name=\"main\")',\n                '  b1 = sch.get_block(name=\"B\", func_name=\"main\")',\n                '  b2 = sch.get_block(name=\"C\", func_name=\"main\")',\n                \"  sch.compute_inline(block=b1)\",\n                \"  l3, l4 = sch.get_loops(block=b2)\",\n                \"  l5, l6 = sch.split(loop=l3, factors=\" + str(a) + \", preserve_unit_iters=True)\",\n                \"  l7, l8 = sch.split(loop=l4, factors=\" + str(b) + \", preserve_unit_iters=True)\",\n                \"  sch.reorder(l5, l7, l6, l8)\",\n                \"  l9, l10 = sch.get_loops(block=b0)\",\n                \"  l11, l12 = sch.split(loop=l9, factors=\" + str(c) + \", preserve_unit_iters=True)\",\n                \"  l13, l14 = sch.split(loop=l10, factors=\"\n                + str(d)\n                + \", preserve_unit_iters=True)\",\n                \"  sch.reorder(l11, l13, l12, l14)\",\n            ]\n        )\n\n    mod = TrinityMatmul\n    context = TuneContext(\n        mod=mod,\n        target=Target(\"llvm\"),\n        task_name=\"Remove Block Task\",\n        space_generator=PostOrderApply(\n            sch_rules=[RemoveBlock(), TrinityDoubleRule()],\n            postprocs=[],\n            mutator_probs={},\n        ),\n    )\n    post_order_apply = context.space_generator\n    schs = post_order_apply.generate_design_space(mod)\n    assert len(schs) == 4\n    for sch in schs:\n        with pytest.raises(\n            tvm.tir.schedule.schedule.ScheduleError,\n            match=\"ScheduleError: An error occurred in the schedule primitive 'get-block'.\",\n        ):\n            sch.get_block(\"B\", \"main\")\n        sch_trace = sch.trace.simplified(True)\n        assert (\n            str(sch_trace) == correct_trace([16, 64], [64, 16], [2, 512], [2, 512])\n            or str(sch_trace) == correct_trace([2, 512], [2, 512], [2, 512], [2, 512])\n            or str(sch_trace) == correct_trace([16, 64], [64, 16], [16, 64], [64, 16])\n            or str(sch_trace) == correct_trace([2, 512], [2, 512], [16, 64], [64, 16])\n        )\n\n\ndef test_target_blocks_search_space():\n    # Test that specific blocks of trinity matmul can be targeted.\n    def filter_fn(block, target_names) -> bool:\n        return block.name_hint in target_names\n\n    def _get_sch(filter_fn):\n        mod = TrinityMatmul\n        context = TuneContext(\n            mod=mod,\n            target=Target(\"llvm\"),\n            task_name=\"Custom Search Space Task\",\n            space_generator=PostOrderApply(\n                f_block_filter=filter_fn,\n                sch_rules=[TrinityDoubleRule()],\n                postprocs=[],\n                mutator_probs={},\n            ),\n        )\n        post_order_apply = context.space_generator\n        schs = post_order_apply.generate_design_space(mod)\n        return schs\n\n    # Start by checking that by default each block has a space generated.\n    schs = _get_sch(None)\n    assert len(schs) == 8\n\n    # Next check that we can target a specific block and only get its' revelant schedules.\n    schs = _get_sch(lambda block: filter_fn(block, [\"B\"]))\n    assert len(schs) == 2\n\n    ## Check that extracting two blocks works.\n    schs = _get_sch(lambda block: filter_fn(block, [\"A\", \"C\"]))\n    assert len(schs) == 4\n\n    ## Finally check that all blocks can be extracted by name.\n    schs = _get_sch(lambda block: filter_fn(block, [\"A\", \"B\", \"C\"]))\n    assert len(schs) == 8\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_disallow_dynamic_loop.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target() -> Target:\n    return Target(\"cuda\", host=\"llvm\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[\n                ms.postproc.DisallowDynamicLoop(),\n            ],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n# fmt: off\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass DynamicLoop:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j in T.grid(1024, 1024):\n            for k in T.serial(0, i):\n                with T.block(\"matmul\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    with T.init():\n                        C[vi, vj] = 0.0\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef test_postproc_disallow_dynamic_loops():\n    mod = Matmul\n    ctx = _create_context(mod, target=_target())\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    assert ctx.space_generator.postprocs[0].apply(sch)\n\n\ndef test_postproc_disallow_dynamic_loops_fail():\n    mod = DynamicLoop\n    ctx = _create_context(mod, target=_target())\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    assert not ctx.space_generator.postprocs[0].apply(sch)\n\n\nif __name__ == \"__main__\":\n    test_postproc_disallow_dynamic_loops()\n    test_postproc_disallow_dynamic_loops_fail()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_cooperative_fetch.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.te import create_prim_func\n\n\ndef _target() -> Target:\n    return Target(\"cuda\", host=\"llvm\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[\n                ms.postproc.RewriteCooperativeFetch(),\n            ],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n@tvm.script.ir_module\nclass AfterRewrite0:\n    @T.prim_func\n    def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n        C = T.match_buffer(var_C, [512, 512], dtype=\"float32\")\n        # body\n        # with T.block(\"root\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(0, 16, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                    for i2_0 in T.serial(0, 1):\n                        for ax0_ax1_fused_0 in T.serial(0, 32768):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                with T.block(\"A_shared\"):\n                                    v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512)\n                                    v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512)\n                                    T.reads([A[v0, v1]])\n                                    T.writes([A_shared[v0, v1]])\n                                    A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused_0 in T.serial(0, 1024):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_2 in T.vectorized(0, 2):\n                                    with T.block(\"B_shared\"):\n                                        v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32)\n                                        v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32)\n                                        T.reads([B[v0, v1]])\n                                        T.writes([B_shared[v0, v1]])\n                                        B_shared[v0, v1] = B[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2):\n                            with T.block(\"C\"):\n                                i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4)\n                                j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4)\n                                k = T.axis.reduce(512, i2_0 * 512 + i2_1 * 32 + i2_2)\n                                T.reads([A_shared[i, k], B_shared[k, j]])\n                                T.writes([C_local[i, j]])\n                                with T.init():\n                                    C_local[i, j] = T.float32(0)\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(32, 4):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1)\n                            T.reads([C_local[v0, v1]])\n                            T.writes([C[v0, v1]])\n                            C[v0, v1] = C_local[v0, v1]\n\n\n@tvm.script.ir_module\nclass WarpExecutionAfterRewrite:\n    @T.prim_func\n    def main(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        C: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(0, 16, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(0, 8, thread=\"threadIdx.y\"):\n                    for i2_0 in T.serial(0, 1):\n                        for ax0_ax1_fused_0 in T.serial(0, 1024):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.y\"):\n                                for ax0_ax1_fused_2 in T.thread_binding(\n                                    0, 32, thread=\"threadIdx.x\"\n                                ):\n                                    with T.block(\"A_shared\"):\n                                        v0 = T.axis.spatial(\n                                            512,\n                                            (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 32\n                                                + ax0_ax1_fused_2\n                                            )\n                                            // 512,\n                                        )\n                                        v1 = T.axis.spatial(\n                                            512,\n                                            (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 32\n                                                + ax0_ax1_fused_2\n                                            )\n                                            % 512,\n                                        )\n                                        T.reads([A[v0, v1]])\n                                        T.writes([A_shared[v0, v1]])\n                                        A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused_0 in T.serial(0, 32):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.y\"):\n                                for ax0_ax1_fused_2 in T.thread_binding(\n                                    0, 32, thread=\"threadIdx.x\"\n                                ):\n                                    for ax0_ax1_fused_3 in T.vectorized(0, 2):\n                                        with T.block(\"B_shared\"):\n                                            v0 = T.axis.spatial(\n                                                512,\n                                                (\n                                                    ax0_ax1_fused_0 * 512\n                                                    + ax0_ax1_fused_1 * 64\n                                                    + ax0_ax1_fused_2 * 2\n                                                    + ax0_ax1_fused_3\n                                                )\n                                                // 32,\n                                            )\n                                            v1 = T.axis.spatial(\n                                                512,\n                                                i0_0_i1_0_fused * 32\n                                                + (\n                                                    ax0_ax1_fused_0 * 512\n                                                    + ax0_ax1_fused_1 * 64\n                                                    + ax0_ax1_fused_2 * 2\n                                                    + ax0_ax1_fused_3\n                                                )\n                                                % 32,\n                                            )\n                                            T.reads([B[v0, v1]])\n                                            T.writes([B_shared[v0, v1]])\n                                            B_shared[v0, v1] = B[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2):\n                            with T.block(\"C\"):\n                                i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4)\n                                j = T.axis.spatial(\n                                    512,\n                                    i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4,\n                                )\n                                k = T.axis.reduce(512, i2_0 * 512 + i2_1 * 32 + i2_2)\n                                T.reads([A_shared[i, k], B_shared[k, j]])\n                                T.writes([C_local[i, j]])\n                                T.block_attr({\"warp_execution\": 1})\n                                with T.init():\n                                    C_local[i, j] = T.float32(0)\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(32, 4):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(\n                                512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1\n                            )\n                            T.reads([C_local[v0, v1]])\n                            T.writes([C[v0, v1]])\n                            C[v0, v1] = C_local[v0, v1]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_rewrite_cooperative_fetch():\n    mod = create_prim_func(te_workload.matmul(n=512, m=512, k=512))\n    target = _target()\n    ctx = _create_context(mod, target)\n\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    # fmt: off\n    # pylint: disable=line-too-long,invalid-name\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"local\")\n    l2, l3, l4 = sch.get_loops(block=b0)\n    v5, v6, v7, v8, v9 = sch.sample_perfect_tile(loop=l2, n=5, max_innermost_factor=64, decision=[1, 16, 1, 2, 16])\n    l10, l11, l12, l13, l14 = sch.split(loop=l2, factors=[v5, v6, v7, v8, v9])\n    v15, v16, v17, v18, v19 = sch.sample_perfect_tile(loop=l3, n=5, max_innermost_factor=64, decision=[16, 1, 8, 2, 2])\n    l20, l21, l22, l23, l24 = sch.split(loop=l3, factors=[v15, v16, v17, v18, v19])\n    v25, v26, v27 = sch.sample_perfect_tile(loop=l4, n=3, max_innermost_factor=64, decision=[1, 16, 32])\n    l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27])\n    sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24)\n    l31 = sch.fuse(l10, l20)\n    sch.bind(loop=l31, thread_axis=\"blockIdx.x\")\n    l32 = sch.fuse(l11, l21)\n    sch.bind(loop=l32, thread_axis=\"vthread.x\")\n    l33 = sch.fuse(l12, l22)\n    sch.bind(loop=l33, thread_axis=\"threadIdx.x\")\n    b34 = sch.cache_read(block=b0, read_buffer_index=0, storage_scope=\"shared\")\n    sch.compute_at(block=b34, loop=l28, preserve_unit_loops=True)\n    _, _, _, _, l39, l40 = sch.get_loops(block=b34)\n    l41 = sch.fuse(l39, l40)\n    _, v43 = sch.sample_perfect_tile(loop=l41, n=2, max_innermost_factor=4, decision=[262144, 1])\n    sch.annotate(block_or_loop=b34, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v43)\n    b44 = sch.cache_read(block=b0, read_buffer_index=1, storage_scope=\"shared\")\n    sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True)\n    _, _, _, _, l49, l50 = sch.get_loops(block=b44)\n    l51 = sch.fuse(l49, l50)\n    _, v53 = sch.sample_perfect_tile(loop=l51, n=2, max_innermost_factor=4, decision=[8192, 2])\n    sch.annotate(block_or_loop=b44, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v53)\n    sch.reverse_compute_at(block=b1, loop=l33, preserve_unit_loops=True)\n    # pylint: enable=line-too-long,invalid-name\n    # fmt: on\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, AfterRewrite0)\n\n\ndef test_rewrite_warp_execution():\n    mod = create_prim_func(te_workload.matmul(n=512, m=512, k=512))\n    target = _target()\n    ctx = _create_context(mod, target)\n\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    # fmt: off\n    # pylint: disable=line-too-long,invalid-name\n    b0 = sch.get_block(name=\"C\", func_name=\"main\")\n    b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"local\")\n    l2, l3, l4 = sch.get_loops(block=b0)\n    sch.annotate(b0, \"warp_execution\", 1)\n    v5, v6, v7, v8, v9 = sch.sample_perfect_tile(loop=l2, n=5, max_innermost_factor=64, decision=[1, 16, 1, 2, 16])\n    l10, l11, l12, l13, l14 = sch.split(loop=l2, factors=[v5, v6, v7, v8, v9])\n    v15, v16, v17, v18, v19 = sch.sample_perfect_tile(loop=l3, n=5, max_innermost_factor=64, decision=[16, 1, 8, 2, 2])\n    l20, l21, l22, l23, l24 = sch.split(loop=l3, factors=[v15, v16, v17, v18, v19])\n    v25, v26, v27 = sch.sample_perfect_tile(loop=l4, n=3, max_innermost_factor=64, decision=[1, 16, 32])\n    l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27])\n    sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24)\n    l31 = sch.fuse(l10, l20)\n    sch.bind(loop=l31, thread_axis=\"blockIdx.x\")\n    l32 = sch.fuse(l11, l21)\n    sch.bind(loop=l32, thread_axis=\"vthread.x\")\n    l33 = sch.fuse(l12, l22)\n    sch.bind(loop=l33, thread_axis=\"threadIdx.y\")\n    b34 = sch.cache_read(block=b0, read_buffer_index=0, storage_scope=\"shared\")\n    sch.compute_at(block=b34, loop=l28, preserve_unit_loops=True)\n    _, _, _, _, l39, l40 = sch.get_loops(block=b34)\n    l41 = sch.fuse(l39, l40)\n    _, v43 = sch.sample_perfect_tile(loop=l41, n=2, max_innermost_factor=4, decision=[262144, 1])\n    sch.annotate(block_or_loop=b34, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v43)\n    b44 = sch.cache_read(block=b0, read_buffer_index=1, storage_scope=\"shared\")\n    sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True)\n    _, _, _, _, l49, l50 = sch.get_loops(block=b44)\n    l51 = sch.fuse(l49, l50)\n    _, v53 = sch.sample_perfect_tile(loop=l51, n=2, max_innermost_factor=4, decision=[8192, 2])\n    sch.annotate(block_or_loop=b44, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v53)\n    sch.reverse_compute_at(block=b1, loop=l33, preserve_unit_loops=True)\n    # pylint: enable=line-too-long,invalid-name\n    # fmt: on\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, WarpExecutionAfterRewrite)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target() -> Target:\n    return Target(\"cuda\", host=\"llvm\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[\n                ms.postproc.RewriteLayout(),\n            ],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\nclass BaseBeforeAfter(tvm.testing.CompareBeforeAfter):\n    def transform(self):\n        def inner(mod):\n            target = Target(\"cuda\", host=\"llvm\")\n            ctx = ms.TuneContext(\n                mod=mod,\n                target=target,\n                space_generator=ms.space_generator.PostOrderApply(\n                    sch_rules=[],\n                    postprocs=[\n                        ms.postproc.RewriteLayout(),\n                    ],\n                    mutator_probs={},\n                ),\n                task_name=\"test\",\n            )\n            sch = tvm.tir.Schedule(mod, debug_mask=\"all\")\n            sch.enter_postproc()\n            assert ctx.space_generator.postprocs[0].apply(sch)\n            return sch.mod\n\n        return inner\n\n\nclass TestTIRMatmul(BaseBeforeAfter):\n    \"\"\"Main functionality test\n\n    A new block should be inserted to transform the layout, with the\n    compute block operating on the temporary transformed buffer.\n    \"\"\"\n\n    def before(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 16), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [1]})\n        for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n            with T.block(\"matmul\"):\n                vi = T.axis.S(16, i0 * 4 + i1)\n                vj = T.axis.S(16, j)\n                vk = T.axis.R(16, k0 * 4 + k1)\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n    def expected(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 16), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [1]})\n        B_reindex = T.alloc_buffer([16, 4, 4], dtype=\"float32\")\n        for ax0, ax1 in T.grid(16, 16):\n            with T.block(\"layout_rewrite\"):\n                i0, i1 = T.axis.remap(\"SS\", [ax0, ax1])\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\": True})\n                B_reindex[i1, i0 // 4, i0 % 4] = B[i0, i1]\n        for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n            with T.block(\"matmul\"):\n                vi = T.axis.spatial(16, i0 * 4 + i1)\n                vj = T.axis.spatial(16, j)\n                vk = T.axis.reduce(16, k0 * 4 + k1)\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B_reindex[vj, vk // 4, vk % 4]\n\n\nclass TestRewrittenBuffersMustOccurWithinBlock(BaseBeforeAfter):\n    \"\"\"Buffers must occur within a Block\"\"\"\n\n    def before(\n        A: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [0]})\n        for i, j in T.grid(16, 16):\n            T.evaluate(A[i, j])\n\n    expected = tvm.TVMError\n\n\nclass TestExtentOne(BaseBeforeAfter):\n    \"\"\"Buffers with dimensions of extent 1 can be transformed\n\n    Regression test for a previous bug, in which the removal of\n    trivial variables resulted in an error in `IndexMap::Inverse`.\n    \"\"\"\n\n    def before(\n        A: T.Buffer[(16, 1), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [0]})\n        for i, j in T.grid(16, 1):\n            with T.block(\"block\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.evaluate(A[vi, vj])\n\n    def expected(A: T.Buffer[(16, 1), \"float32\"]):\n        T.func_attr({\"layout_free_buffers\": [0]})\n\n        A_global = T.alloc_buffer([16], dtype=\"float32\")\n        for ax0, ax1 in T.grid(16, 1):\n            with T.block(\"A_global\"):\n                v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\": True})\n                A_global[v0] = A[v0, v1]\n\n        for i, j in T.grid(16, 1):\n            with T.block(\"block\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.evaluate(A_global[vi])\n\n\n@T.prim_func\ndef tir_matmul(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n) -> None:\n    T.func_attr({\"layout_free_buffers\": [1]})\n    for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n        with T.block(\"matmul\"):\n            vi = T.axis.S(16, i0 * 4 + i1)\n            vj = T.axis.S(16, j)\n            vk = T.axis.R(16, k0 * 4 + k1)\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@T.prim_func\ndef rewritten_tir_matmul(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n) -> None:\n    T.func_attr({\"layout_free_buffers\": [1]})\n    B_reindex = T.alloc_buffer([16, 4, 4], dtype=\"float32\")\n    for ax0, ax1 in T.grid(16, 16):\n        with T.block(\"layout_rewrite\"):\n            i0, i1 = T.axis.remap(\"SS\", [ax0, ax1])\n            T.block_attr({\"meta_schedule.layout_rewrite_preproc\": True})\n            B_reindex[i1, i0 // 4, i0 % 4] = B[i0, i1]\n    for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n        with T.block(\"matmul\"):\n            vi = T.axis.spatial(16, i0 * 4 + i1)\n            vj = T.axis.spatial(16, j)\n            vk = T.axis.reduce(16, k0 * 4 + k1)\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B_reindex[vj, vk // 4, vk % 4]\n\n\ndef test_layout_rewrite():\n    target = _target()\n    ctx = _create_context(tir_matmul, target)\n    sch = tvm.tir.Schedule(tir_matmul, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], rewritten_tir_matmul)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_parallel_vectorize_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nfrom tvm.meta_schedule.postproc import RewriteParallelVectorizeUnroll\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import Schedule\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant\n# fmt: off\n\n@tvm.script.ir_module\nclass Move_PUV:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, [1024, 1024, 1024], dtype=\"float32\")\n        B = T.match_buffer(b, [1024, 1024, 1024], dtype=\"float32\")\n        # body\n        with T.block(\"root\"):\n            T.block_attr({\"meta_schedule.parallel\":128, \"meta_schedule.vectorize\":32})\n            for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32):\n                with T.block(\"move\"):\n                    vi = T.axis.spatial(1024, i0 * 16 + i1 * 4 + i2)\n                    vj = T.axis.spatial(1024, j0 * 32 + j1 * 8 + j2)\n                    vk = T.axis.spatial(1024, k0 * 32 + k1)\n                    T.where((i0 * 4 + i1) * 4 + i2 < 1024 and (j0 * 4 + j1) * 8 + j2 < 1024 and k0 * 32 + k1 < 1024)\n                    T.reads([A[vi, vj, vk]])\n                    T.writes([B[vi, vj, vk]])\n                    B[vi, vj, vk] = A[vi, vj, vk]\n\n\n@T.prim_func\ndef Move_PUV0(a: T.handle, b: T.handle) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\"})\n    A = T.match_buffer(a, [1024, 1024, 1024], dtype=\"float32\")\n    B = T.match_buffer(b, [1024, 1024, 1024], dtype=\"float32\")\n    # body\n    with T.block(\"root\"):\n        for i0_j0_fused in T.parallel(0, 8192):\n            for i1, j1, k0, i2, j2 in T.grid(4, 4, 64, 4, 8):\n                for k1_fused in T.vectorized(0, 32):\n                    with T.block(\"move\"):\n                        vi = T.axis.spatial(1024, i0_j0_fused // 64 * 16 + i1 * 4 + i2)\n                        vj = T.axis.spatial(1024, i0_j0_fused % 64 * 32 + j1 * 8 + j2)\n                        vk = T.axis.spatial(1024, k0 * 32 + k1_fused)\n                        T.where(\n                            i0_j0_fused // 64 * 16 + i1 * 4 + i2 < 1024\n                            and i0_j0_fused % 64 * 32 + j1 * 8 + j2 < 1024\n                            and k0 * 32 + k1_fused < 1024\n                        )\n                        T.reads([A[vi, vj, vk]])\n                        T.writes([B[vi, vj, vk]])\n                        B[vi, vj, vk] = A[vi, vj, vk]\n\n\n@tvm.script.ir_module\nclass Fused_NN_Dense:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(64, 768), \"float32\"], placeholder_1: T.Buffer[(768, 768), \"float32\"], T_matmul_NT: T.Buffer[(64, 768), \"float32\"]) -> None:\n        for i0, i1, i2 in T.grid(64, 768, 768):\n            with T.block(\"T_matmul_NT\"):\n                i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                T.reads(placeholder[i, k], placeholder_1[j, k])\n                T.writes(T_matmul_NT[i, j])\n                with T.init():\n                    T_matmul_NT[i, j] = T.float32(0)\n                T_matmul_NT[i, j] = T_matmul_NT[i, j] + placeholder[i, k] * placeholder_1[j, k]\n\n@T.prim_func\ndef before_matmul_vectorize(\n    placeholder: T.Buffer[(64, 768), \"float32\"],\n    placeholder_1: T.Buffer[(768, 768), \"float32\"],\n    T_matmul_NT: T.Buffer[(64, 768), \"float32\"],\n) -> None:\n    with T.block(\"root\"):\n        T.reads()\n        T.writes()\n        T.block_attr({\"meta_schedule.vectorize\":64})\n        T_matmul_NT_global = T.alloc_buffer([64, 768], dtype=\"float32\")\n        for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 16, 1, 3):\n            for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(48, 8, 1, 16, 8, 16):\n                with T.block(\"T_matmul_NT\"):\n                    i = T.axis.spatial(64, i0_2 * 8 + i0_3)\n                    j = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + i1_3)\n                    k = T.axis.reduce(768, i2_0 * 16 + i2_1)\n                    T.reads(placeholder[i, k], placeholder_1[j, k])\n                    T.writes(T_matmul_NT_global[i, j])\n                    with T.init():\n                        T_matmul_NT_global[i, j] = T.float32(0)\n                    T_matmul_NT_global[i, j] = T_matmul_NT_global[i, j] + placeholder[i, k] * placeholder_1[j, k]\n            for ax0, ax1 in T.grid(64, 16):\n                with T.block(\"T_matmul_NT_global\"):\n                    v0 = T.axis.spatial(64, ax0)\n                    v1 = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + ax1)\n                    T.reads(T_matmul_NT_global[v0, v1])\n                    T.writes(T_matmul_NT[v0, v1])\n                    T_matmul_NT[v0, v1] = T_matmul_NT_global[v0, v1]\n\n@T.prim_func\ndef after_matmul_vectorize(\n    placeholder: T.Buffer[(64, 768), \"float32\"],\n    placeholder_1: T.Buffer[(768, 768), \"float32\"],\n    T_matmul_NT: T.Buffer[(64, 768), \"float32\"],\n) -> None:\n    T_matmul_NT_global = T.alloc_buffer([64, 768], dtype=\"float32\")\n    for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 16, 1, 3):\n        for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(48, 8, 1, 16, 8):\n            for i1_3_fused in T.vectorized(16):\n                with T.block(\"T_matmul_NT\"):\n                    i = T.axis.spatial(64, i0_2 * 8 + i0_3)\n                    j = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + i1_3_fused)\n                    k = T.axis.reduce(768, i2_0 * 16 + i2_1)\n                    T.reads(placeholder[i, k], placeholder_1[j, k])\n                    T.writes(T_matmul_NT_global[i, j])\n                    with T.init():\n                        T_matmul_NT_global[i, j] = T.float32(0)\n                    T_matmul_NT_global[i, j] = T_matmul_NT_global[i, j] + placeholder[i, k] * placeholder_1[j, k]\n        for ax0 in T.serial(64):\n            for ax1_fused in T.vectorized(16):\n                with T.block(\"T_matmul_NT_global\"):\n                    v0 = T.axis.spatial(64, ax0)\n                    v1 = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + ax1_fused)\n                    T.reads(T_matmul_NT_global[v0, v1])\n                    T.writes(T_matmul_NT[v0, v1])\n                    T_matmul_NT[v0, v1] = T_matmul_NT_global[v0, v1]\n\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable\n\n\ndef test_meta_schedule_postproc_rewrite_parallel_unroll_vectorize():\n    postproc = RewriteParallelVectorizeUnroll()\n    sch = Schedule(Move_PUV)\n    assert postproc.apply(sch)\n    mod = tvm.tir.transform.Simplify()(sch.mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], Move_PUV0)\n\n\ndef test_vectorize_inner_loop():\n    sch = Schedule(before_matmul_vectorize)\n    rule = RewriteParallelVectorizeUnroll()\n    assert rule.apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], after_matmul_vectorize)\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_postproc_rewrite_parallel_unroll_vectorize()\n    test_vectorize_inner_loop()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_reduction_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target() -> Target:\n    return Target(\"cuda\", host=\"llvm\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[\n                ms.postproc.RewriteReductionBlock(),\n            ],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n@tvm.script.ir_module\nclass Matmul_before_rewrite:\n    @T.prim_func\n    def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None:\n        A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n        C = T.match_buffer(var_C, [512, 512], dtype=\"float32\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(0, 16, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                    for i2_0 in T.serial(0, 1):\n                        for ax0_ax1_fused_0 in T.serial(0, 32768):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                with T.block(\"A_shared\"):\n                                    v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512)\n                                    v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512)\n                                    T.reads([A[v0, v1]])\n                                    T.writes([A_shared[v0, v1]])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused_0 in T.serial(0, 1024):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_2 in T.vectorized(0, 2):\n                                    with T.block(\"B_shared\"):\n                                        v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32)\n                                        v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32)\n                                        T.reads([B[v0, v1]])\n                                        T.writes([B_shared[v0, v1]])\n                                        T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                        B_shared[v0, v1] = B[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2):\n                            with T.block(\"C\"):\n                                i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4)\n                                j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4)\n                                k = T.axis.reduce(512, i2_1 * 32 + i2_2)\n                                T.reads([C_local[i, j], A_shared[i, k], B_shared[k, j]])\n                                T.writes([C_local[i, j]])\n                                with T.init():\n                                    C_local[i, j] = T.float32(0)\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(32, 4):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1)\n                            T.reads([C_local[v0, v1]])\n                            T.writes([C[v0, v1]])\n                            C[v0, v1] = C_local[v0, v1]\n\n\n@tvm.script.ir_module\nclass Matmul_after_rewrite:\n    @T.prim_func\n    def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None:\n        A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n        C = T.match_buffer(var_C, [512, 512], dtype=\"float32\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(0, 16, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                    for i2_0 in T.serial(0, 1):\n                        for ax0_ax1_fused_0 in T.serial(0, 32768):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                with T.block(\"A_shared\"):\n                                    v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512)\n                                    v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512)\n                                    T.reads([A[v0, v1]])\n                                    T.writes([A_shared[v0, v1]])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused_0 in T.serial(0, 1024):\n                            for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_2 in T.vectorized(0, 2):\n                                    with T.block(\"B_shared\"):\n                                        v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32)\n                                        v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32)\n                                        T.reads([B[v0, v1]])\n                                        T.writes([B_shared[v0, v1]])\n                                        T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                        B_shared[v0, v1] = B[v0, v1]\n                        for i0_3_init, i1_3_init, i0_4_init, i1_4_init in T.grid(2, 2, 16, 2):\n                            with T.block(\"C_init\"):\n                                i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3_init * 16 + i0_4_init)\n                                j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3_init * 2 + i1_4_init)\n                                T.reads([])\n                                T.writes([C_local[i, j]])\n                                C_local[i, j] = T.float32(0)\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2):\n                            with T.block(\"C_update\"):\n                                i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4)\n                                j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4)\n                                k = T.axis.reduce(512, i2_1 * 32 + i2_2)\n                                T.reads([C_local[i, j], A_shared[i, k], B_shared[k, j]])\n                                T.writes([C_local[i, j]])\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(32, 4):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1)\n                            T.reads([C_local[v0, v1]])\n                            T.writes([C[v0, v1]])\n                            C[v0, v1] = C_local[v0, v1]\n\n\n@tvm.script.ir_module\nclass Softmax_cross_thread_reduction:\n    @T.prim_func\n    def main(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        for i0 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 8):\n                for ax1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_maxelem\"):\n                        i0_1 = T.axis.spatial(256, i0)\n                        k = T.axis.reduce(256, ax1_0 * 32 + ax1_1)\n                        T.reads(T_softmax_maxelem_shared[i0_1], A[i0_1, k])\n                        T.writes(T_softmax_maxelem_shared[i0_1])\n                        with T.init():\n                            T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem_shared[i0_1] = T.max(T_softmax_maxelem_shared[i0_1], A[i0_1, k])\n            for ax0, ax1_0 in T.grid(1, 8):\n                for ax1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_expsum\"):\n                        i0_2 = T.axis.spatial(256, i0)\n                        k = T.axis.reduce(256, ax1_0 * 32 + ax1_1)\n                        T.reads(T_softmax_expsum_shared[i0_2], A[i0_2, k], T_softmax_maxelem_shared[i0_2])\n                        T.writes(T_softmax_expsum_shared[i0_2])\n                        with T.init():\n                            T_softmax_expsum_shared[i0_2] = T.float32(0)\n                        T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\")\n            for i1_0 in T.serial(8):\n                for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        i0_3 = T.axis.spatial(256, i0)\n                        i1 = T.axis.spatial(256, i1_0 * 32 + i1_1)\n                        T.reads(A[i0_3, i1], T_softmax_maxelem_shared[i0_3], T_softmax_expsum_shared[i0_3])\n                        T.writes(T_softmax_norm[i0_3, i1])\n                        T.block_attr({\"axis\":1})\n                        T_softmax_norm[i0_3, i1] = T.exp(A[i0_3, i1] - T_softmax_maxelem_shared[i0_3], dtype=\"float32\") / T_softmax_expsum_shared[i0_3]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_rewrite_tiled_matmul():\n    mod = Matmul_before_rewrite\n    target = _target()\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, Matmul_after_rewrite)\n\n\ndef test_rewrite_softmax():\n    mod = Softmax_cross_thread_reduction\n    target = _target()\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    # The module should not be rewritten\n    tvm.ir.assert_structural_equal(sch.mod, Softmax_cross_thread_reduction)\n\n\nif __name__ == \"__main__\":\n    test_rewrite_tiled_matmul()\n    test_rewrite_softmax()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.tir.tensor_intrin import arm_cpu, cuda, rocm, x86\n\n\n@tvm.script.ir_module\nclass Conv2dNCHWcVNNIModuleTiled:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for (\n            i0_0,\n            i1_0,\n            i2_0,\n            i3_0,\n            i4_0_0,\n            i0_1,\n            i1_1,\n            i2_1,\n            i3_1,\n            i4_0_1,\n            i5_0,\n            i6_0,\n            i7_0,\n            i8_0,\n            i9_0_0,\n            i0_2,\n            i1_2,\n            i2_2,\n            i3_2,\n            i4_0_2,\n            i5_1,\n            i6_1,\n            i7_1,\n            i8_1,\n            i9_0_1,\n            i0_3,\n            i1_3,\n            i2_3,\n            i3_3,\n            i4_0_3,\n        ) in T.grid(\n            1,\n            1,\n            2,\n            1,\n            1,\n            1,\n            4,\n            1,\n            14,\n            1,\n            1,\n            1,\n            4,\n            1,\n            1,\n            1,\n            4,\n            7,\n            1,\n            1,\n            1,\n            1,\n            1,\n            4,\n            1,\n            1,\n            1,\n            4,\n            4,\n            1,\n        ):\n            with T.block(\"conv2d_NCHWc_int8_o\"):\n                n = T.axis.spatial(1, 0)\n                oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2)\n                oh = T.axis.spatial(56, i2_0 * 28 + i2_2 * 4 + i2_3)\n                ow = T.axis.spatial(56, i3_1 * 4 + i3_3)\n                oc_block_o = T.axis.spatial(1, 0)\n                kh = T.axis.reduce(1, 0)\n                kw = T.axis.reduce(1, 0)\n                ic_outer, ic_f_inner = T.axis.remap(\"RR\", [i7_0, i8_1])\n                ic_s_inner_o = T.axis.reduce(1, 0)\n                T.reads(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4],\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4],\n                )\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16])\n                T.block_attr({\"meta_schedule.auto_tensorize\": \"dot_16x4_vnni\"})\n                with T.init():\n                    for i4_1 in T.serial(16):\n                        with T.block(\"conv2d_NCHWc_int8_init\"):\n                            oc_block_init = T.axis.spatial(16, i4_1)\n                            T.reads()\n                            T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init])\n                            conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init] = 0\n                for i4_1, i9_1 in T.grid(16, 4):\n                    with T.block(\"conv2d_NCHWc_int8\"):\n                        oc_block, ic_s_inner = T.axis.remap(\"SR\", [i4_1, i9_1])\n                        T.reads(\n                            conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block],\n                            placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                            placeholder_1[\n                                oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner\n                            ],\n                        )\n                        T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                        T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                        conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[\n                            n, oc_chunk, oh, ow, oc_block\n                        ] + T.cast(\n                            placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                            \"int32\",\n                        ) * T.cast(\n                            placeholder_1[\n                                oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner\n                            ],\n                            \"int32\",\n                        )\n\n\n@tvm.script.ir_module\nclass Conv2dNCHWcVNNIModuleTensorized:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0 in T.grid(\n            1, 1, 2, 1, 1, 1, 4, 1, 14, 1, 1, 1\n        ):\n            for i1_2_init, i2_2_init, i2_3_init, i3_3_init in T.grid(4, 7, 4, 4):\n                with T.block(\"conv2d_NCHWc_int8_o_init\"):\n                    n = T.axis.spatial(1, 0)\n                    oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2_init)\n                    oh = T.axis.spatial(56, i2_0 * 28 + i2_2_init * 4 + i2_3_init)\n                    ow = T.axis.spatial(56, i3_1 * 4 + i3_3_init)\n                    oc_block_o = T.axis.spatial(1, 0)\n                    T.reads()\n                    T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16])\n                    for i4_1 in T.vectorized(16):\n                        with T.block(\"conv2d_NCHWc_int8_init\"):\n                            oc_block_init = T.axis.spatial(16, i4_1)\n                            T.reads()\n                            T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init])\n                            conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init] = 0\n            for (\n                i7_0,\n                i8_0,\n                i9_0_0,\n                i0_2,\n                i1_2,\n                i2_2,\n                i3_2,\n                i4_0_2,\n                i5_1,\n                i6_1,\n                i7_1,\n                i8_1,\n                i9_0_1,\n                i0_3,\n                i1_3,\n                i2_3,\n                i3_3,\n                i4_0_3,\n            ) in T.grid(4, 1, 1, 1, 4, 7, 1, 1, 1, 1, 1, 4, 1, 1, 1, 4, 4, 1):\n                with T.block(\"conv2d_NCHWc_int8_o_update\"):\n                    n = T.axis.spatial(1, 0)\n                    oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2)\n                    oh = T.axis.spatial(56, i2_0 * 28 + i2_2 * 4 + i2_3)\n                    ow = T.axis.spatial(56, i3_1 * 4 + i3_3)\n                    oc_block_o = T.axis.spatial(1, 0)\n                    kh = T.axis.reduce(1, 0)\n                    kw = T.axis.reduce(1, 0)\n                    ic_outer, ic_f_inner = T.axis.remap(\"RR\", [i7_0, i8_1])\n                    ic_s_inner_o = T.axis.reduce(1, 0)\n                    T.reads(\n                        conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16],\n                        placeholder[\n                            n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4\n                        ],\n                        placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4],\n                    )\n                    T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16])\n                    A = T.match_buffer(\n                        placeholder[\n                            n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4\n                        ],\n                        [4],\n                        dtype=\"uint8\",\n                        offset_factor=1,\n                    )\n                    B = T.match_buffer(\n                        placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4],\n                        [16, 4],\n                        dtype=\"int8\",\n                        offset_factor=1,\n                    )\n                    C = T.match_buffer(\n                        conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16],\n                        [16],\n                        dtype=\"int32\",\n                        offset_factor=1,\n                    )\n                    A_u8x4 = A.vload([0], \"uint8x4\")\n                    A_i32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n                    B_i8x64 = B.vload([0, 0], dtype=\"int8x64\")\n                    B_i32x16 = T.reinterpret(B_i8x64, dtype=\"int32x16\")\n                    C_i32x16 = C.vload([0], dtype=\"int32x16\")\n                    C[T.ramp(0, 1, 16)] = T.call_llvm_pure_intrin(\n                        T.llvm_lookup_intrinsic_id(\"llvm.x86.avx512.vpdpbusd.512\"),\n                        T.uint32(0),\n                        C_i32x16,\n                        T.broadcast(A_i32, 16),\n                        B_i32x16,\n                        dtype=\"int32x16\",\n                    )\n\n\n@tvm.script.ir_module\nclass DenseDP4ATiled:\n    @T.prim_func\n    def main(\n        X: T.Buffer[(128, 128), \"int8\"],\n        W: T.Buffer[(128, 128), \"int8\"],\n        compute: T.Buffer[(128, 128), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        compute_local = T.alloc_buffer([128, 128], dtype=\"int32\", scope=\"local\")\n        X_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        W_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(2, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(2, thread=\"threadIdx.x\"):\n                    for i2_0_0 in T.serial(2):\n                        for ax0_ax1_fused in T.serial(1024):\n                            with T.block(\"X_shared\"):\n                                v0 = T.axis.spatial(\n                                    128, i0_0_i1_0_fused // 2 * 16 + ax0_ax1_fused // 64\n                                )\n                                v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(X[v0, v1])\n                                T.writes(X_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 4})\n                                X_shared[v0, v1] = X[v0, v1]\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"W_shared\"):\n                                v0 = T.axis.spatial(\n                                    128, i0_0_i1_0_fused % 2 * 64 + ax0_ax1_fused // 64\n                                )\n                                v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(W[v0, v1])\n                                T.writes(W_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 1})\n                                W_shared[v0, v1] = W[v0, v1]\n                        for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(2, 4, 16, 8, 4, 1):\n                            with T.block(\"compute_o\"):\n                                i = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + i0_3 * 4 + i0_4)\n                                j = T.axis.spatial(\n                                    128,\n                                    i0_0_i1_0_fused % 2 * 64\n                                    + i0_1_i1_1_fused * 32\n                                    + i0_2_i1_2_fused * 16\n                                    + i1_3,\n                                )\n                                k_o = T.axis.reduce(32, i2_0_0 * 16 + i2_0_1 * 8 + i2_0_2)\n                                T.reads(\n                                    X_shared[i, k_o * 4 : k_o * 4 + 4],\n                                    W_shared[j, k_o * 4 : k_o * 4 + 4],\n                                )\n                                T.writes(compute_local[i, j])\n                                T.block_attr({\"meta_schedule.auto_tensorize\": \"dp4a\"})\n                                with T.init():\n                                    with T.block(\"compute_init\"):\n                                        T.reads()\n                                        T.writes(compute_local[i, j])\n                                        compute_local[i, j] = 0\n                                for i2_1 in T.serial(4):\n                                    with T.block(\"compute\"):\n                                        k = T.axis.reduce(4, i2_1)\n                                        T.reads(\n                                            compute_local[i, j],\n                                            X_shared[i, k_o * 4 + k],\n                                            W_shared[j, k_o * 4 + k],\n                                        )\n                                        T.writes(compute_local[i, j])\n                                        T.block_attr({\"meta_schedule.tiling_structure\": \"SSSRRSRS\"})\n                                        compute_local[i, j] = compute_local[i, j] + T.cast(\n                                            X_shared[i, k_o * 4 + k], \"int32\"\n                                        ) * T.cast(W_shared[j, k_o * 4 + k], \"int32\")\n                    for ax0, ax1 in T.grid(16, 16):\n                        with T.block(\"compute_local\"):\n                            v0 = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + ax0)\n                            v1 = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused % 2 * 64\n                                + i0_1_i1_1_fused * 32\n                                + i0_2_i1_2_fused * 16\n                                + ax1,\n                            )\n                            T.reads(compute_local[v0, v1])\n                            T.writes(compute[v0, v1])\n                            compute[v0, v1] = compute_local[v0, v1]\n\n\n@tvm.script.ir_module\nclass DenseDP4ATensorized:\n    @T.prim_func\n    def main(\n        X: T.Buffer[(128, 128), \"int8\"],\n        W: T.Buffer[(128, 128), \"int8\"],\n        compute: T.Buffer[(128, 128), \"int32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        compute_local = T.alloc_buffer([128, 128], dtype=\"int32\", scope=\"local\")\n        X_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        W_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(2, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(2, thread=\"threadIdx.x\"):\n                    for i0_3_init, i1_3_init, i0_4_init in T.grid(4, 16, 4):\n                        with T.block(\"compute_o_init\"):\n                            i = T.axis.spatial(\n                                128, i0_0_i1_0_fused // 2 * 16 + i0_3_init * 4 + i0_4_init\n                            )\n                            j = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused % 2 * 64\n                                + i0_1_i1_1_fused * 32\n                                + i0_2_i1_2_fused * 16\n                                + i1_3_init,\n                            )\n                            T.reads()\n                            T.writes(compute_local[i, j])\n                            T.block_attr({\"meta_schedule.auto_tensorize\": \"\"})\n                            with T.block(\"compute_init\"):\n                                T.reads()\n                                T.writes(compute_local[i, j])\n                                compute_local[i, j] = 0\n                    for i2_0_0 in T.serial(2):\n                        for ax0_ax1_fused in T.serial(1024):\n                            with T.block(\"X_shared\"):\n                                v0 = T.axis.spatial(\n                                    128, i0_0_i1_0_fused // 2 * 16 + ax0_ax1_fused // 64\n                                )\n                                v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(X[v0, v1])\n                                T.writes(X_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 4})\n                                X_shared[v0, v1] = X[v0, v1]\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"W_shared\"):\n                                v0 = T.axis.spatial(\n                                    128, i0_0_i1_0_fused % 2 * 64 + ax0_ax1_fused // 64\n                                )\n                                v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(W[v0, v1])\n                                T.writes(W_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 1})\n                                W_shared[v0, v1] = W[v0, v1]\n                        for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(2, 4, 16, 8, 4, 1):\n                            with T.block(\"compute_o_update\"):\n                                i = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + i0_3 * 4 + i0_4)\n                                j = T.axis.spatial(\n                                    128,\n                                    i0_0_i1_0_fused % 2 * 64\n                                    + i0_1_i1_1_fused * 32\n                                    + i0_2_i1_2_fused * 16\n                                    + i1_3,\n                                )\n                                k_o = T.axis.reduce(32, i2_0_0 * 16 + i2_0_1 * 8 + i2_0_2)\n                                T.reads(\n                                    compute_local[i, j],\n                                    X_shared[i, k_o * 4 : k_o * 4 + 4],\n                                    W_shared[j, k_o * 4 : k_o * 4 + 4],\n                                )\n                                T.writes(compute_local[i, j])\n                                A = T.match_buffer(\n                                    X_shared[i, k_o * 4 : k_o * 4 + 4],\n                                    [4],\n                                    dtype=\"int8\",\n                                    scope=\"shared\",\n                                    align=4,\n                                    offset_factor=1,\n                                )\n                                B = T.match_buffer(\n                                    W_shared[j, k_o * 4 : k_o * 4 + 4],\n                                    [4],\n                                    dtype=\"int8\",\n                                    scope=\"shared\",\n                                    align=4,\n                                    offset_factor=1,\n                                )\n                                C = T.match_buffer(\n                                    compute_local[i, j],\n                                    [1],\n                                    dtype=\"int32\",\n                                    scope=\"local\",\n                                    align=4,\n                                    offset_factor=1,\n                                )\n                                C[0] = C[0] + T.call_pure_extern(\n                                    \"__dp4a\",\n                                    A[T.ramp(0, 1, 4)],\n                                    B[T.ramp(0, 1, 4)],\n                                    0,\n                                    dtype=\"int32\",\n                                )\n                    for ax0, ax1 in T.grid(16, 16):\n                        with T.block(\"compute_local\"):\n                            v0 = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + ax0)\n                            v1 = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused % 2 * 64\n                                + i0_1_i1_1_fused * 32\n                                + i0_2_i1_2_fused * 16\n                                + ax1,\n                            )\n                            T.reads(compute_local[v0, v1])\n                            T.writes(compute[v0, v1])\n                            compute[v0, v1] = compute_local[v0, v1]\n\n\ndef _create_context(mod, target, postprocs) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=postprocs,\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\ndef test_rewrite_tensorize_conv2d_nchwc_vnni():\n    mod = Conv2dNCHWcVNNIModuleTiled\n    target = tvm.target.Target(\"llvm -mcpu=cascadelake -num-cores 4\")\n    ctx = _create_context(\n        mod,\n        target,\n        [\n            ms.postproc.RewriteReductionBlock(),\n            ms.postproc.RewriteTensorize(True),\n        ],\n    )\n    sch = tvm.tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n\n    for proc in ctx.space_generator.postprocs:\n        proc.apply(sch)\n\n    tvm.ir.assert_structural_equal(sch.mod, Conv2dNCHWcVNNIModuleTensorized)\n\n\ndef test_rewrite_tensorize_dense_dp4a():\n    mod = DenseDP4ATiled\n    target = tvm.target.Target(\"nvidia/geforce-rtx-3070\")\n    ctx = _create_context(\n        mod,\n        target,\n        [\n            ms.postproc.RewriteCooperativeFetch(),\n            ms.postproc.RewriteReductionBlock(),\n            ms.postproc.RewriteTensorize(),\n        ],\n    )\n    sch = tvm.tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n\n    for proc in ctx.space_generator.postprocs:\n        proc.apply(sch)\n\n    tvm.ir.assert_structural_equal(sch.mod, DenseDP4ATensorized)\n\n\nif __name__ == \"__main__\":\n    test_rewrite_tensorize_conv2d_nchwc_vnni()\n    test_rewrite_tensorize_dense_dp4a()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_rewrite_unbound_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target() -> Target:\n    return Target(\"cuda --max_threads_per_block=1024\", host=\"llvm\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    ctx = ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[ms.postproc.RewriteUnboundBlock()],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n    return ctx\n\n\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n\n@tvm.script.ir_module\nclass Before_cooperative_fetch:\n    @T.prim_func\n    def main(var_A: T.handle, var_B: T.handle) -> None:\n        A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n        for i, j in T.grid(512, 512):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] + 1.0\n\n\n@tvm.script.ir_module\nclass After_cooperative_fetch:\n    @T.prim_func\n    def main(var_A: T.handle, var_B: T.handle) -> None:\n        A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n        for i_j_fused_0 in T.thread_binding(256, thread=\"blockIdx.x\"):\n            for i_j_fused_1 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) // 512)\n                    vj = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) % 512)\n                    B[vi, vj] = A[vi, vj] + 1.0\n\n\n@tvm.script.ir_module\nclass Before_norm_bmn:\n    @T.prim_func\n    def main(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[(1,), \"float32\"]) -> None:\n        C = T.alloc_buffer([1], dtype=\"float32\")\n        for i0, i1, i2 in T.grid(1, 256, 256):\n            with T.block(\"C\"):\n                b, i, j = T.axis.remap(\"SRR\", [i0, i1, i2])\n                with T.init():\n                    C[b] = T.float32(0)\n                C[b] = C[b] + A[b, i, j] * A[b, i, j]\n        for i0 in T.serial(1):\n            with T.block(\"D\"):\n                b = T.axis.S(1, i0)\n                D[b] = T.sqrt(C[b], dtype=\"float32\")\n\n\n@tvm.script.ir_module\nclass After_norm_bmn:\n    @T.prim_func\n    def main(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[(1,), \"float32\"]) -> None:\n        C = T.alloc_buffer([1], dtype=\"float32\")\n        for i0_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for i0_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                for i1, i2 in T.grid(256, 256):\n                    with T.block(\"C\"):\n                        b = T.axis.S(1, 0)\n                        i, j = T.axis.remap(\"RR\", [i1, i2])\n                        with T.init():\n                            C[b] = T.float32(0)\n                        C[b] = C[b] + A[b, i, j] * A[b, i, j]\n        for i0_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for i0_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                with T.block(\"D\"):\n                    b = T.axis.S(1, 0)\n                    D[b] = T.sqrt(C[b], dtype=\"float32\")\n\n\n@tvm.script.ir_module\nclass Bert_fused_reshape_transpose_reshape:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(12, 64, 64), \"float32\"], T_reshape: T.Buffer[(64, 768), \"float32\"]\n    ) -> None:\n        for i0_i1_fused_0, i0_i1_fused_1 in T.grid(1536, 32):\n            with T.block(\"T_reshape_1\"):\n                ax0 = T.axis.spatial(64, (i0_i1_fused_0 * 32 + i0_i1_fused_1) // 768)\n                ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 32 + i0_i1_fused_1) % 768)\n                T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64])\n                T.writes(T_reshape[ax0, ax1])\n                T_reshape[ax0, ax1] = placeholder[\n                    ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12,\n                    (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64,\n                    ax1 % 64 % 64,\n                ]\n\n\n@tvm.script.ir_module\nclass Bert_fused_reshape_transpose_reshape_large:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(12, 64, 64), \"float32\"], T_reshape: T.Buffer[(64, 768), \"float32\"]\n    ) -> None:\n        for i0_i1_fused_0, i0_i1_fused_1 in T.grid(1536000, 32):\n            with T.block(\"T_reshape_1\"):\n                ax0 = T.axis.spatial(64, (i0_i1_fused_0 * 32 + i0_i1_fused_1) // 768)\n                ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 32 + i0_i1_fused_1) % 768)\n                T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64])\n                T.writes(T_reshape[ax0, ax1])\n                T_reshape[ax0, ax1] = placeholder[\n                    ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12,\n                    (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64,\n                    ax1 % 64 % 64,\n                ]\n\n\n@tvm.script.ir_module\nclass Bert_fused_reshape_transpose_reshape_after_rub:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(12, 64, 64), \"float32\"], T_reshape: T.Buffer[(64, 768), \"float32\"]\n    ) -> None:\n        for i0_i1_fused_0_i0_i1_fused_1_fused_0 in T.thread_binding(48, thread=\"blockIdx.x\"):\n            for i0_i1_fused_0_i0_i1_fused_1_fused_1 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n                with T.block(\"T_reshape_1\"):\n                    ax0 = T.axis.spatial(\n                        64,\n                        (\n                            (\n                                i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024\n                                + i0_i1_fused_0_i0_i1_fused_1_fused_1\n                            )\n                            // 32\n                            * 32\n                            + (\n                                i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024\n                                + i0_i1_fused_0_i0_i1_fused_1_fused_1\n                            )\n                            % 32\n                        )\n                        // 768,\n                    )\n                    ax1 = T.axis.spatial(\n                        768,\n                        (\n                            (\n                                i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024\n                                + i0_i1_fused_0_i0_i1_fused_1_fused_1\n                            )\n                            // 32\n                            * 32\n                            + (\n                                i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024\n                                + i0_i1_fused_0_i0_i1_fused_1_fused_1\n                            )\n                            % 32\n                        )\n                        % 768,\n                    )\n                    T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64])\n                    T.writes(T_reshape[ax0, ax1])\n                    T_reshape[ax0, ax1] = placeholder[\n                        ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12,\n                        (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64,\n                        ax1 % 64 % 64,\n                    ]\n\n\n@tvm.script.ir_module\nclass Bert_fused_reshape_transpose_reshape_after_rub_large:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(12, 64, 64), \"float32\"], T_reshape: T.Buffer[(64, 768), \"float32\"]\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i0_i1_fused_0_i0_i1_fused_1_fused_1 in T.thread_binding(256, thread=\"blockIdx.x\"):\n            for i0_i1_fused_0_i0_i1_fused_1_fused_2 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n                for i0_i1_fused_0_i0_i1_fused_1_fused_0 in T.serial(188):\n                    with T.block(\"T_reshape_1\"):\n                        ax0 = T.axis.spatial(\n                            64,\n                            (\n                                (\n                                    i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_2\n                                )\n                                // 32\n                                * 32\n                                + (\n                                    i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_2\n                                )\n                                % 32\n                            )\n                            // 768,\n                        )\n                        ax1 = T.axis.spatial(\n                            768,\n                            (\n                                (\n                                    i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_2\n                                )\n                                // 32\n                                * 32\n                                + (\n                                    i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024\n                                    + i0_i1_fused_0_i0_i1_fused_1_fused_2\n                                )\n                                % 32\n                            )\n                            % 768,\n                        )\n                        T.where(\n                            (\n                                i0_i1_fused_0_i0_i1_fused_1_fused_0 * 256\n                                + i0_i1_fused_0_i0_i1_fused_1_fused_1\n                            )\n                            * 1024\n                            + i0_i1_fused_0_i0_i1_fused_1_fused_2\n                            < 49152000\n                        )\n                        T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64])\n                        T.writes(T_reshape[ax0, ax1])\n                        T_reshape[ax0, ax1] = placeholder[\n                            ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64)\n                            % 12,\n                            (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64,\n                            ax1 % 64 % 64,\n                        ]\n\n\n@T.prim_func\ndef before_unrolled_loop(\n    placeholder: T.Buffer[(1, 56, 56, 64), \"float32\"],\n) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    bgemm = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n    inverse = T.alloc_buffer([4, 4, 196, 64], dtype=\"float32\")\n    for i2_0, i3_0, i2_1, i3_1 in T.grid(98, 4, 2, 16):\n        for i0 in T.unroll(4):\n            for i1 in T.unroll(4):\n                for i4 in T.unroll(6):\n                    for i5 in T.unroll(6):\n                        with T.block(\"inverse\"):\n                            vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                            p = T.axis.spatial(196, i2_0 * 2 + i2_1)\n                            co = T.axis.spatial(64, i3_0 * 16 + i3_1)\n                            r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                            T.reads(bgemm[r_a, r_b, p, co])\n                            T.writes(inverse[vh, vw, p, co])\n                            with T.init():\n                                inverse[vh, vw, p, co] = T.float32(0)\n                            inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co]\n\n\n@T.prim_func\ndef after_unrolled_loop(\n    placeholder: T.Buffer[(1, 56, 56, 64), \"float32\"],\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    # body\n    # with T.block(\"root\")\n    bgemm = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n    inverse = T.alloc_buffer([4, 4, 196, 64], dtype=\"float32\")\n    for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(13, thread=\"blockIdx.x\"):\n        for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n            for i0 in T.unroll(4):\n                for i1 in T.unroll(4):\n                    for i4 in T.unroll(6):\n                        for i5 in T.unroll(6):\n                            with T.block(\"inverse\"):\n                                vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                                p = T.axis.spatial(\n                                    196,\n                                    (\n                                        i2_0_i3_0_i2_1_i3_1_fused_0 * 1024\n                                        + i2_0_i3_0_i2_1_i3_1_fused_1\n                                    )\n                                    // 128\n                                    * 2\n                                    + (\n                                        i2_0_i3_0_i2_1_i3_1_fused_0 * 1024\n                                        + i2_0_i3_0_i2_1_i3_1_fused_1\n                                    )\n                                    % 32\n                                    // 16,\n                                )\n                                co = T.axis.spatial(\n                                    64,\n                                    (\n                                        i2_0_i3_0_i2_1_i3_1_fused_0 * 1024\n                                        + i2_0_i3_0_i2_1_i3_1_fused_1\n                                    )\n                                    % 128\n                                    // 32\n                                    * 16\n                                    + (\n                                        i2_0_i3_0_i2_1_i3_1_fused_0 * 1024\n                                        + i2_0_i3_0_i2_1_i3_1_fused_1\n                                    )\n                                    % 16,\n                                )\n                                r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                T.where(\n                                    i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1\n                                    < 12544\n                                )\n                                T.reads(bgemm[r_a, r_b, p, co])\n                                T.writes(inverse[vh, vw, p, co])\n                                with T.init():\n                                    inverse[vh, vw, p, co] = T.float32(0)\n                                inverse[vh, vw, p, co] = (\n                                    inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co]\n                                )\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_rewrite_cooperative_fetch():\n    mod = Before_cooperative_fetch\n    target = _target()\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, After_cooperative_fetch)\n\n\ndef test_rewrite_norm_bmn():\n    mod = Before_norm_bmn\n    target = _target()\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, After_norm_bmn)\n\n\ndef test_rewrite_cuda_loop_split_no_reduction():\n    mod = Bert_fused_reshape_transpose_reshape\n    target = Target(\"nvidia/nvidia-v100\", host=\"llvm\")\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, Bert_fused_reshape_transpose_reshape_after_rub)\n\n\ndef test_rewrite_cuda_loop_split_no_reduction_large():\n    mod = Bert_fused_reshape_transpose_reshape_large\n    target = Target(\"nvidia/nvidia-v100\", host=\"llvm\")\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod, Bert_fused_reshape_transpose_reshape_after_rub_large)\n\n\ndef test_rewrite_cuda_loop_split_for_kind():\n    mod = before_unrolled_loop\n    target = Target(\"nvidia/nvidia-v100\", host=\"llvm\")\n    ctx = _create_context(mod, target)\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    sch.enter_postproc()\n    assert ctx.space_generator.postprocs[0].apply(sch)\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], after_unrolled_loop)\n\n\nif __name__ == \"__main__\":\n    test_rewrite_cooperative_fetch()\n    test_rewrite_norm_bmn()\n    test_rewrite_cuda_loop_split_no_reduction()\n    test_rewrite_cuda_loop_split_no_reduction_large()\n    test_rewrite_cuda_loop_split_for_kind()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_postproc_verify_gpu_code.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target() -> Target:\n    return Target(\"nvidia/geforce-rtx-3080\")\n\n\ndef _create_context(mod, target) -> ms.TuneContext:\n    return ms.TuneContext(\n        mod=mod,\n        target=target,\n        space_generator=ms.space_generator.PostOrderApply(\n            sch_rules=[],\n            postprocs=[ms.postproc.VerifyGPUCode()],\n            mutator_probs={},\n        ),\n        task_name=\"test\",\n    )\n\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant\n# fmt: off\n\n@tvm.script.ir_module\nclass Conv2dCuda0:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"T.noalias\": True})\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        threadIdx_y = T.env_thread(\"threadIdx.y\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        blockIdx_y = T.env_thread(\"blockIdx.y\")\n        blockIdx_z = T.env_thread(\"blockIdx.z\")\n        A = T.match_buffer(a, [14*14*256*256], dtype=\"float32\")\n        B = T.match_buffer(b, [14*14*512*256], dtype=\"float32\")\n        # body\n        T.launch_thread(blockIdx_z, 196)\n        B_local = T.decl_buffer([64], \"float32\", scope=\"local\")\n        Apad_shared = T.decl_buffer([512], \"float32\", scope=\"shared\")\n        Apad_shared_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        T.launch_thread(blockIdx_y, 8)\n        T.launch_thread(blockIdx_x, 4)\n        T.launch_thread(threadIdx_y, 8)\n        T.launch_thread(threadIdx_x, 8)\n        for ff_c_init, nn_c_init in T.grid(8, 8):\n            B_local[ff_c_init * 8 + nn_c_init] = T.float32(0)\n        for rc_outer, ry, rx in T.grid(32, 3, 3):\n            for ax3_inner_outer in T.serial(0, 2):\n                Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else(\n                    1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15,\n                    A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)],\n                    T.broadcast(T.float32(0), 4),\n                    dtype=\"float32x4\",\n                )\n            for rc_inner in T.serial(0, 8):\n                for ax3 in T.serial(0, 8):\n                    Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3]\n                for ff_c, nn_c in T.grid(8, 8):\n                    B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c]\n        for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8):\n            B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner] # fmt: on\n\n\n@tvm.script.ir_module\nclass Conv2dCuda1:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"T.noalias\": True})\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        threadIdx_y = T.env_thread(\"threadIdx.y\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        blockIdx_y = T.env_thread(\"blockIdx.y\")\n        blockIdx_z = T.env_thread(\"blockIdx.z\")\n        A = T.match_buffer(a, [14*14*256*256], dtype=\"float32\")\n        B = T.match_buffer(b, [14*14*512*256], dtype=\"float32\")\n        # body\n        T.launch_thread(blockIdx_z, 196)\n        B_local = T.decl_buffer([6400000], \"float32\", scope=\"local\")\n        Apad_shared = T.decl_buffer([512], \"float32\", scope=\"shared\")\n        Apad_shared_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        T.launch_thread(blockIdx_y, 8)\n        T.launch_thread(blockIdx_x, 4)\n        T.launch_thread(threadIdx_y, 8)\n        T.launch_thread(threadIdx_x, 8)\n        for ff_c_init, nn_c_init in T.grid(8, 8):\n            B_local[ff_c_init * 8 + nn_c_init] = T.float32(0)\n            # Access of the last element of B_local prevents buffer\n            # compacting from reducing the amount of shared memory\n            # used.\n            B_local[6400000-1 + ff_c_init*8] = 0.0\n        for rc_outer, ry, rx in T.grid(32, 3, 3):\n            for ax3_inner_outer in T.serial(0, 2):\n                Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else(\n                    1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15,\n                    A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)],\n                    T.broadcast(T.float32(0), 4),\n                    dtype=\"float32x4\",\n                )\n            for rc_inner in T.serial(0, 8):\n                for ax3 in T.serial(0, 8):\n                    Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3]\n                for ff_c, nn_c in T.grid(8, 8):\n                    B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c]\n        for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8):\n            B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on\n\n\n@tvm.script.ir_module\nclass Conv2dCuda2:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"T.noalias\": True})\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        threadIdx_y = T.env_thread(\"threadIdx.y\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        blockIdx_y = T.env_thread(\"blockIdx.y\")\n        blockIdx_z = T.env_thread(\"blockIdx.z\")\n        A = T.match_buffer(a, [14*14*256*256], dtype=\"float32\")\n        B = T.match_buffer(b, [14*14*512*256], dtype=\"float32\")\n        # body\n        T.launch_thread(blockIdx_z, 196)\n        B_local = T.decl_buffer([64], \"float32\", scope=\"local\")\n        Apad_shared = T.decl_buffer([512000], \"float32\", scope=\"shared\")\n        Apad_shared_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        T.launch_thread(blockIdx_y, 8)\n        T.launch_thread(blockIdx_x, 4)\n        T.launch_thread(threadIdx_y, 8)\n        T.launch_thread(threadIdx_x, 8)\n        for ff_c_init, nn_c_init in T.grid(8, 8):\n            B_local[ff_c_init * 8 + nn_c_init] = T.float32(0)\n        for rc_outer, ry, rx in T.grid(32, 3, 3):\n            for ax3_inner_outer in T.serial(0, 2):\n                Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else(\n                    1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15,\n                    A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)],\n                    T.broadcast(T.float32(0), 4),\n                    dtype=\"float32x4\",\n                )\n                # Access of the last element of Apad_shared prevents\n                # buffer compacting from reducing the amount of shared\n                # memory used.\n                Apad_shared[512000-1] = 0.0\n            for rc_inner in T.serial(0, 8):\n                for ax3 in T.serial(0, 8):\n                    Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3]\n                for ff_c, nn_c in T.grid(8, 8):\n                    B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c]\n        for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8):\n            B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on\n\n\n@tvm.script.ir_module\nclass Conv2dCuda3:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"T.noalias\": True})\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        threadIdx_y = T.env_thread(\"threadIdx.y\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        blockIdx_y = T.env_thread(\"blockIdx.y\")\n        blockIdx_z = T.env_thread(\"blockIdx.z\")\n        A = T.match_buffer(a, [14*14*256*256], dtype=\"float32\")\n        B = T.match_buffer(b, [14*14*512*256], dtype=\"float32\")\n        # body\n        T.launch_thread(blockIdx_z, 196)\n        B_local = T.decl_buffer([64], \"float32\", scope=\"local\")\n        Apad_shared = T.decl_buffer([512], \"float32\", scope=\"shared\")\n        Apad_shared_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        T.launch_thread(blockIdx_y, 8)\n        T.launch_thread(blockIdx_x, 4)\n        T.launch_thread(threadIdx_y, 8)\n        T.launch_thread(threadIdx_x, 800000)\n        for ff_c_init, nn_c_init in T.grid(8, 8):\n            B_local[ff_c_init * 8 + nn_c_init] = T.float32(0)\n        for rc_outer, ry, rx in T.grid(32, 3, 3):\n            for ax3_inner_outer in T.serial(0, 2):\n                Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else(\n                    1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15,\n                    A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)],\n                    T.broadcast(T.float32(0), 4),\n                    dtype=\"float32x4\",\n                )\n            for rc_inner in T.serial(0, 8):\n                for ax3 in T.serial(0, 8):\n                    Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3]\n                for ff_c, nn_c in T.grid(8, 8):\n                    B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c]\n        for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8):\n            B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on\n\n@T.prim_func\ndef GmmCuda0(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n    Z_local = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"local\")\n    X_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    Y_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n        for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n            for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread=\"threadIdx.x\"):\n                for i1_3_init, i2_4_init in T.grid(4, 2):\n                    with T.block(\"Z_init\"):\n                        b = T.axis.spatial(1, 0)\n                        i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init)\n                        j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init)\n                        T.reads()\n                        T.writes(Z_local[b, i, j])\n                        Z_local[b, i, j] = T.float32(0)\n                for i3_0 in T.serial(4):\n                    for ax0_ax1_ax2_fused_0 in T.serial(4):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            for ax0_ax1_ax2_fused_2 in T.vectorized(2):\n                                with T.block(\"X_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32)\n                                    v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32)\n                                    T.reads(X[v0, v1, v2])\n                                    T.writes(X_shared[v0, v1, v2])\n                                    X_shared[v0, v1, v2] = X[v0, v1, v2]\n                    for ax0_ax1_ax2_fused_0 in T.serial(8):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            with T.block(\"Y_shared\"):\n                                v0 = T.axis.spatial(1, 0)\n                                v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32)\n                                v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32)\n                                T.reads(Y[v0, v1, v2])\n                                T.writes(Y_shared[v0, v1, v2])\n                                Y_shared[v0, v1, v2] = Y[v0, v1, v2]\n                    for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2):\n                        with T.block(\"Z_update\"):\n                            b = T.axis.spatial(1, 0)\n                            i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3)\n                            j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4)\n                            k = T.axis.reduce(128, i3_0 * 32 + i3_2)\n                            T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j])\n                            T.writes(Z_local[b, i, j])\n                            Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j]\n                for ax0, ax1, ax2 in T.grid(1, 4, 2):\n                    with T.block(\"Z_local\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1)\n                        v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2)\n                        T.reads(Z_local[v0, v1, v2])\n                        T.writes(Z[v0, v1, v2])\n                        Z[v0, v1, v2] = Z_local[v0, v1, v2]\n\n@T.prim_func\ndef GmmCuda1(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n    Z_local = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"local\")\n    X_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    Y_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n        for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n            for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread=\"threadIdx.x\"):\n                for i1_3_init, i2_4_init in T.grid(4, 2):\n                    with T.block(\"Z_init\"):\n                        b = T.axis.spatial(1, 0)\n                        i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init)\n                        j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init)\n                        T.reads()\n                        T.writes(Z_local[b, i, j])\n                        Z_local[b, i, j] = T.float32(0)\n                for i3_0 in T.serial(4):\n                    for ax0_ax1_ax2_fused_0 in T.serial(4):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            for ax0_ax1_ax2_fused_2 in T.vectorized(2):\n                                with T.block(\"X_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32)\n                                    v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32)\n                                    T.reads(X[v0, v1, v2])\n                                    T.writes(X_shared[v0, v1, v2])\n                                    X_shared[v0, v1, v2] = X[v0, v1, v2]\n                    for ax0_ax1_ax2_fused_0 in T.serial(8):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            with T.block(\"Y_shared\"):\n                                v0 = T.axis.spatial(1, 0)\n                                v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32)\n                                v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32)\n                                T.reads(Y[v0, v1, v2])\n                                T.writes(Y_shared[v0, v1, v2])\n                                Y_shared[v0, v1, v2] = Y[v0, v1, v2]\n                    for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2):\n                        with T.block(\"Z_update\"):\n                            b = T.axis.spatial(1, 0)\n                            i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3)\n                            j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4)\n                            k = T.axis.reduce(128, i3_0 * 32 + i3_2)\n                            T.block_attr({\n                                \"meta_schedule.thread_extent_low_inclusive\": 0,\n                                \"meta_schedule.thread_extent_high_inclusive\": 32,\n                            })\n                            T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j])\n                            T.writes(Z_local[b, i, j])\n                            Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j]\n                for ax0, ax1, ax2 in T.grid(1, 4, 2):\n                    with T.block(\"Z_local\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1)\n                        v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2)\n                        T.reads(Z_local[v0, v1, v2])\n                        T.writes(Z[v0, v1, v2])\n                        Z[v0, v1, v2] = Z_local[v0, v1, v2]\n\n\n@T.prim_func\ndef GmmCuda2(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n    Z_local = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"local\")\n    X_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    Y_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n    for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n        for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n            for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread=\"threadIdx.x\"):\n                for i1_3_init, i2_4_init in T.grid(4, 2):\n                    with T.block(\"Z_init\"):\n                        b = T.axis.spatial(1, 0)\n                        i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init)\n                        j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init)\n                        T.reads()\n                        T.writes(Z_local[b, i, j])\n                        Z_local[b, i, j] = T.float32(0)\n                for i3_0 in T.serial(4):\n                    for ax0_ax1_ax2_fused_0 in T.serial(4):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            for ax0_ax1_ax2_fused_2 in T.vectorized(2):\n                                with T.block(\"X_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32)\n                                    v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32)\n                                    T.reads(X[v0, v1, v2])\n                                    T.writes(X_shared[v0, v1, v2])\n                                    X_shared[v0, v1, v2] = X[v0, v1, v2]\n                    for ax0_ax1_ax2_fused_0 in T.serial(8):\n                        for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            with T.block(\"Y_shared\"):\n                                v0 = T.axis.spatial(1, 0)\n                                v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32)\n                                v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32)\n                                T.reads(Y[v0, v1, v2])\n                                T.writes(Y_shared[v0, v1, v2])\n                                Y_shared[v0, v1, v2] = Y[v0, v1, v2]\n                    for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2):\n                        with T.block(\"Z_update\"):\n                            b = T.axis.spatial(1, 0)\n                            i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3)\n                            j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4)\n                            k = T.axis.reduce(128, i3_0 * 32 + i3_2)\n                            T.block_attr({\n                                \"meta_schedule.thread_extent_low_inclusive\": 1024,\n                                \"meta_schedule.thread_extent_high_inclusive\": 1024,\n                            })\n                            T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j])\n                            T.writes(Z_local[b, i, j])\n                            Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j]\n                for ax0, ax1, ax2 in T.grid(1, 4, 2):\n                    with T.block(\"Z_local\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1)\n                        v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2)\n                        T.reads(Z_local[v0, v1, v2])\n                        T.writes(Z[v0, v1, v2])\n                        Z[v0, v1, v2] = Z_local[v0, v1, v2]\n\n\n@T.prim_func\ndef GMMCUDATensorCore(\n    X: T.Buffer[(1024, 1024), \"float16\"],\n    Y: T.Buffer[(1024, 1024), \"float16\"],\n    Z: T.Buffer[(1024, 1024), \"float32\"],\n) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    s0 = T.var(\"int32\")\n    s0_1 = T.var(\"int32\")\n    s0_2 = T.var(\"int32\")\n    s1 = T.var(\"int32\")\n    s1_1 = T.var(\"int32\")\n    s1_2 = T.var(\"int32\")\n    # body\n    # with T.block(\"root\")\n    Z_wmma_accumulator = T.alloc_buffer([1024, 1024], dtype=\"float32\", scope=\"wmma.accumulator\")\n    X_shared = T.alloc_buffer([1024, 1024], dtype=\"float16\", scope=\"shared\")\n    Y_shared = T.alloc_buffer([1024, 1024], dtype=\"float16\", scope=\"shared\")\n    X_shared_wmma_matrix_a = T.alloc_buffer([1024, 1024], dtype=\"float16\", scope=\"wmma.matrix_a\")\n    Y_shared_wmma_matrix_b = T.alloc_buffer([1024, 1024], dtype=\"float16\", scope=\"wmma.matrix_b\")\n    for ax0_0_ax1_0_0_ax2_0_0_fused in T.thread_binding(64, thread=\"blockIdx.x\"):\n        for ax0_1_ax1_0_1_ax2_0_1_fused in T.thread_binding(2, thread=\"blockIdx.y\"):\n            for ax0_2_ax1_0_2_ax2_0_2_fused in T.thread_binding(2, thread=\"threadIdx.y\"):\n                for ax1_0_3_init, ax2_0_3_init, ax1_0_4_init, ax2_0_4_init in T.grid(2, 1, 2, 4):\n                    with T.block(\"Z_o_init\"):\n                        v0 = T.axis.spatial(1, 0)\n                        v1_o = T.axis.spatial(\n                            64,\n                            ax0_0_ax1_0_0_ax2_0_0_fused % 64 // 16 * 16\n                            + ax0_1_ax1_0_1_ax2_0_1_fused % 2 * 8\n                            + ax0_2_ax1_0_2_ax2_0_2_fused % 2 * 4\n                            + ax1_0_3_init * 2\n                            + ax1_0_4_init,\n                        )\n                        v2_o = T.axis.spatial(\n                            64,\n                            (ax0_0_ax1_0_0_ax2_0_0_fused % 16 + 0 + 0 + ax2_0_3_init) * 4\n                            + ax2_0_4_init,\n                        )\n                        T.reads()\n                        T.writes(\n                            Z_wmma_accumulator[\n                                v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                            ]\n                        )\n                        T.block_attr(\n                            {\n                                \"meta_schedule.thread_extent_high_inclusive\": 1024,\n                                \"meta_schedule.thread_extent_low_inclusive\": 32,\n                                \"warp_execution\": 1,\n                            }\n                        )\n                        C = T.match_buffer(\n                            Z_wmma_accumulator[\n                                v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                            ],\n                            [16, 16],\n                            dtype=\"float32\",\n                            scope=\"wmma.accumulator\",\n                            offset_factor=16,\n                        )\n                        T.evaluate(\n                            T.tvm_fill_fragment(\n                                C.data,\n                                16,\n                                16,\n                                16,\n                                C.elem_offset // 256 + C.elem_offset % 256 // 16,\n                                T.float32(0),\n                                dtype=\"handle\",\n                            )\n                        )\n                for ax3_0_0 in T.serial(32):\n                    for ax0_ax1_fused_0 in T.serial(16):\n                        for ax0_ax1_fused_1 in T.thread_binding(2, thread=\"threadIdx.y\"):\n                            for ax0_ax1_fused_2 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_3 in T.vectorized(4):\n                                    with T.block(\"X_shared\"):\n                                        v0 = T.axis.spatial(\n                                            1024,\n                                            ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 256\n                                            + ax0_1_ax1_0_1_ax2_0_1_fused * 128\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 128\n                                                + ax0_ax1_fused_2 * 4\n                                                + ax0_ax1_fused_3\n                                            )\n                                            // 32,\n                                        )\n                                        v1 = T.axis.spatial(\n                                            1024,\n                                            ax3_0_0 * 32\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 128\n                                                + ax0_ax1_fused_2 * 4\n                                                + ax0_ax1_fused_3\n                                            )\n                                            % 32,\n                                        )\n                                        T.reads(X[v0, v1])\n                                        T.writes(X_shared[v0, v1])\n                                        T.block_attr({\"buffer_dim_align\": [[0, 0, 32, 8]]})\n                                        X_shared[v0, v1] = X[v0, v1]\n                    for ax0_ax1_fused_0 in T.serial(8):\n                        for ax0_ax1_fused_1 in T.thread_binding(2, thread=\"threadIdx.y\"):\n                            for ax0_ax1_fused_2 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_3 in T.vectorized(4):\n                                    with T.block(\"Y_shared\"):\n                                        v0 = T.axis.spatial(\n                                            1024,\n                                            ax3_0_0 * 32\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 128\n                                                + ax0_ax1_fused_2 * 4\n                                                + ax0_ax1_fused_3\n                                            )\n                                            // 64,\n                                        )\n                                        v1 = T.axis.spatial(\n                                            1024,\n                                            ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 64\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 128\n                                                + ax0_ax1_fused_2 * 4\n                                                + ax0_ax1_fused_3\n                                            )\n                                            % 64,\n                                        )\n                                        T.reads(Y[v0, v1])\n                                        T.writes(Y_shared[v0, v1])\n                                        T.block_attr({\"buffer_dim_align\": [[0, 0, 32, 8]]})\n                                        Y_shared[v0, v1] = Y[v0, v1]\n                    for ax3_0_1 in T.serial(2):\n                        for ax0_0, ax1_0 in T.grid(4, 1):\n                            with T.block(\"X_shared_wmma.matrix_a_o\"):\n                                v0_o = T.axis.spatial(\n                                    64,\n                                    ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 16\n                                    + ax0_1_ax1_0_1_ax2_0_1_fused * 8\n                                    + ax0_2_ax1_0_2_ax2_0_2_fused * 4\n                                    + ax0_0,\n                                )\n                                v1_o = T.axis.spatial(64, ax3_0_0 * 2 + ax3_0_1)\n                                T.reads(\n                                    X_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]\n                                )\n                                T.writes(\n                                    X_shared_wmma_matrix_a[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ]\n                                )\n                                A = T.match_buffer(\n                                    X_shared[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    strides=[s1, s0],\n                                    scope=\"shared\",\n                                    offset_factor=16,\n                                )\n                                C_1 = T.match_buffer(\n                                    X_shared_wmma_matrix_a[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    scope=\"wmma.matrix_a\",\n                                    offset_factor=16,\n                                )\n                                T.evaluate(\n                                    T.tvm_load_matrix_sync(\n                                        C_1.data,\n                                        16,\n                                        16,\n                                        16,\n                                        C_1.elem_offset // 256 + C_1.elem_offset % 256 // 16,\n                                        T.tvm_access_ptr(\n                                            T.type_annotation(dtype=\"float16\"),\n                                            A.data,\n                                            A.elem_offset,\n                                            s1 * 16,\n                                            1,\n                                            dtype=\"handle\",\n                                        ),\n                                        s1,\n                                        \"row_major\",\n                                        dtype=\"handle\",\n                                    )\n                                )\n                        for ax0_0, ax1_0 in T.grid(1, 4):\n                            with T.block(\"Y_shared_wmma.matrix_b_o\"):\n                                v0_o = T.axis.spatial(64, ax3_0_0 * 2 + ax3_0_1)\n                                v1_o = T.axis.spatial(\n                                    64, ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 4 + ax1_0\n                                )\n                                T.reads(\n                                    Y_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]\n                                )\n                                T.writes(\n                                    Y_shared_wmma_matrix_b[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ]\n                                )\n                                A_1 = T.match_buffer(\n                                    Y_shared[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    strides=[s1_1, s0_1],\n                                    scope=\"shared\",\n                                    offset_factor=16,\n                                )\n                                C_2 = T.match_buffer(\n                                    Y_shared_wmma_matrix_b[\n                                        v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    scope=\"wmma.matrix_b\",\n                                    offset_factor=16,\n                                )\n                                T.evaluate(\n                                    T.tvm_load_matrix_sync(\n                                        C_2.data,\n                                        16,\n                                        16,\n                                        16,\n                                        C_2.elem_offset // 256 + C_2.elem_offset % 256 // 16,\n                                        T.tvm_access_ptr(\n                                            T.type_annotation(dtype=\"float16\"),\n                                            A_1.data,\n                                            A_1.elem_offset,\n                                            s1_1 * 16,\n                                            1,\n                                            dtype=\"handle\",\n                                        ),\n                                        s1_1,\n                                        \"row_major\",\n                                        dtype=\"handle\",\n                                    )\n                                )\n                        for ax0_3, ax1_0_3, ax2_0_3, ax3_0_2, ax0_4, ax1_0_4, ax2_0_4 in T.grid(\n                            1, 2, 1, 1, 1, 2, 4\n                        ):\n                            with T.block(\"Z_o_update\"):\n                                v0 = T.axis.spatial(1, 0)\n                                v1_o = T.axis.spatial(\n                                    64,\n                                    ax0_0_ax1_0_0_ax2_0_0_fused % 64 // 16 * 16\n                                    + ax0_1_ax1_0_1_ax2_0_1_fused % 2 * 8\n                                    + ax0_2_ax1_0_2_ax2_0_2_fused % 2 * 4\n                                    + ax1_0_3 * 2\n                                    + ax1_0_4,\n                                )\n                                v2_o = T.axis.spatial(\n                                    64,\n                                    (ax0_0_ax1_0_0_ax2_0_0_fused % 16 + 0 + 0 + ax2_0_3) * 4\n                                    + ax2_0_4,\n                                )\n                                v3_o = T.axis.reduce(64, ax3_0_0 * 2 + ax3_0_1 + ax3_0_2)\n                                T.reads(\n                                    Z_wmma_accumulator[\n                                        v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                                    ],\n                                    X_shared_wmma_matrix_a[\n                                        v1_o * 16 : v1_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16\n                                    ],\n                                    Y_shared_wmma_matrix_b[\n                                        v3_o * 16 : v3_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                                    ],\n                                )\n                                T.writes(\n                                    Z_wmma_accumulator[\n                                        v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                                    ]\n                                )\n                                T.block_attr(\n                                    {\n                                        \"meta_schedule.thread_extent_high_inclusive\": 1024,\n                                        \"meta_schedule.thread_extent_low_inclusive\": 32,\n                                        \"warp_execution\": 1,\n                                    }\n                                )\n                                A_2 = T.match_buffer(\n                                    X_shared_wmma_matrix_a[\n                                        v1_o * 16 : v1_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    scope=\"wmma.matrix_a\",\n                                    offset_factor=16,\n                                )\n                                B = T.match_buffer(\n                                    Y_shared_wmma_matrix_b[\n                                        v3_o * 16 : v3_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float16\",\n                                    scope=\"wmma.matrix_b\",\n                                    offset_factor=16,\n                                )\n                                C_3 = T.match_buffer(\n                                    Z_wmma_accumulator[\n                                        v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16\n                                    ],\n                                    [16, 16],\n                                    dtype=\"float32\",\n                                    scope=\"wmma.accumulator\",\n                                    offset_factor=16,\n                                )\n                                T.evaluate(\n                                    T.tvm_mma_sync(\n                                        C_3.data,\n                                        C_3.elem_offset // 256 + C_3.elem_offset % 256 // 16,\n                                        A_2.data,\n                                        A_2.elem_offset // 256,\n                                        B.data,\n                                        B.elem_offset // 256,\n                                        C_3.data,\n                                        C_3.elem_offset // 256 + C_3.elem_offset % 256 // 16,\n                                        dtype=\"handle\",\n                                    )\n                                )\n                for ax0_0, ax1_0 in T.grid(4, 4):\n                    with T.block(\"Z_wmma.accumulator_o\"):\n                        v0_o = T.axis.spatial(\n                            64,\n                            ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 16\n                            + ax0_1_ax1_0_1_ax2_0_1_fused * 8\n                            + ax0_2_ax1_0_2_ax2_0_2_fused * 4\n                            + ax0_0,\n                        )\n                        v1_o = T.axis.spatial(64, ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 4 + ax1_0)\n                        T.reads(\n                            Z_wmma_accumulator[\n                                v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                            ]\n                        )\n                        T.writes(Z[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                        A_3 = T.match_buffer(\n                            Z_wmma_accumulator[\n                                v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16\n                            ],\n                            [16, 16],\n                            dtype=\"float32\",\n                            scope=\"wmma.accumulator\",\n                            offset_factor=16,\n                        )\n                        C_4 = T.match_buffer(\n                            Z[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16],\n                            [16, 16],\n                            dtype=\"float32\",\n                            strides=[s1_2, s0_2],\n                            offset_factor=16,\n                        )\n                        T.evaluate(\n                            T.tvm_store_matrix_sync(\n                                A_3.data,\n                                16,\n                                16,\n                                16,\n                                A_3.elem_offset // 256 + A_3.elem_offset % 256 // 16,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float32\"),\n                                    C_4.data,\n                                    C_4.elem_offset,\n                                    s1_2 * 16,\n                                    2,\n                                    dtype=\"handle\",\n                                ),\n                                s1_2,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant\n\n\n@pytest.mark.parametrize(\"mod\", [Conv2dCuda0, Conv2dCuda1, GmmCuda0, GMMCUDATensorCore])\ndef test_postproc_check_pass(mod):\n    ctx = _create_context(mod, target=_target())\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    assert ctx.space_generator.postprocs[0].apply(sch)\n\n\n@pytest.mark.parametrize(\n    \"mod\",\n    [\n        Conv2dCuda2,  # Should fail due to too much local memory per block (large Apad_shared allocation)\n        Conv2dCuda3,  # Should fail due to too many threads per block (large threadIdx.x extent)\n        GmmCuda1,\n        GmmCuda2,\n    ],\n)\ndef test_postproc_check_fail(mod):\n    ctx = _create_context(mod, target=_target())\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    assert not ctx.space_generator.postprocs[0].apply(sch)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule Profiler \"\"\"\nimport time\n\nfrom tvm import meta_schedule as ms\n\n\ndef test_meta_schedule_profiler_context_manager():\n    with ms.Profiler() as profiler:\n        time.sleep(1)\n        with ms.Profiler.timeit(\"Level0\"):\n            time.sleep(1)\n            with ms.Profiler.timeit(\"Level1\"):\n                time.sleep(2)\n    # Note that the results are in seconds\n\n    result = profiler.get()\n    assert len(result) == 3\n    assert 3.9 <= result[\"Total\"] <= 4.1\n    assert 2.9 <= result[\"Level0\"] <= 3.1\n    assert 1.9 <= result[\"Level1\"] <= 2.1\n\n\ndef test_meta_schedule_no_context():\n    with ms.Profiler.timeit(\"Level0\"):\n        assert ms.Profiler.current() is None\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_profiler_context_manager()\n    test_meta_schedule_no_context()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_relay_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Integration test for MetaSchedule\"\"\"\nimport tempfile\nfrom typing import List\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import IRModule\nfrom tvm import meta_schedule as ms\nfrom tvm import relay, te, tir\nfrom tvm._ffi import register_func\nfrom tvm.contrib import graph_executor\nfrom tvm.ir.transform import PassContext\nfrom tvm.meta_schedule.database import TuningRecord, Workload\nfrom tvm.meta_schedule.testing.relay_workload import get_network\nfrom tvm.meta_schedule.testing.tlcbench import load_quantized_bert_base\nfrom tvm.meta_schedule.tune_context import _normalize_mod\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n# pylint: disable=no-member,line-too-long,too-many-nested-blocks,unbalanced-tuple-unpacking,no-self-argument,missing-docstring,invalid-name\n\n\n@tvm.script.ir_module\nclass MockModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:  # type: ignore\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (16,), \"float32\")\n        B = T.match_buffer(b, (16,), \"float32\")\n        for i in T.serial(0, 16):\n            with T.block(\"matmul\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n\n# pylint: enable=no-member,line-too-long,too-many-nested-blocks,unbalanced-tuple-unpacking,no-self-argument\n\n\ndef _has_torch():\n    import importlib.util  # pylint: disable=unused-import,import-outside-toplevel\n\n    spec = importlib.util.find_spec(\"torch\")\n    return spec is not None\n\n\nrequires_torch = pytest.mark.skipif(not _has_torch(), reason=\"torch is not installed\")\n\n\ndef test_meta_schedule_dynamic_loop_extent():\n    a = relay.var(\"a\", shape=(1, 8, 8, 512), dtype=\"float32\")\n    b = relay.nn.adaptive_avg_pool2d(a, (7, 7), \"NHWC\")\n    mod = IRModule({\"main\": relay.Function([a], b)})\n    extracted_tasks = ms.relay_integration.extract_tasks(mod, target=\"llvm\", params={})\n    assert not extracted_tasks\n\n\n@requires_torch\ndef test_meta_schedule_integration_extract_from_resnet():\n    mod, params, _ = get_network(name=\"resnet_18\", input_shape=[1, 3, 224, 224])\n    extracted_tasks = ms.relay_integration.extract_tasks(mod, target=\"llvm\", params=params)\n    expected_task_names = [\n        \"fused_\" + s\n        for s in [\n            \"nn_max_pool2d\",\n            \"nn_adaptive_avg_pool2d\",\n            \"nn_dense_add\",\n            \"nn_conv2d_add\",\n            \"nn_conv2d_add_1\",\n            \"nn_conv2d_add_2\",\n            \"nn_conv2d_add_add_nn_relu\",\n            \"nn_conv2d_add_add_nn_relu_1\",\n            \"nn_conv2d_add_nn_relu\",\n            \"nn_conv2d_add_nn_relu_1\",\n            \"nn_conv2d_add_nn_relu_2\",\n            \"nn_conv2d_add_nn_relu_3\",\n            \"nn_conv2d_add_nn_relu_4\",\n            \"nn_conv2d_add_nn_relu_5\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu_1\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1\",\n            # The two tasks below are purely spatial and are ruled out by AutoScheduler\n            \"layout_transform\",\n            \"layout_transform_reshape_squeeze\",\n        ]\n    ]\n\n    assert len(extracted_tasks) == len(expected_task_names)\n    for t in extracted_tasks:\n        assert t.task_name in expected_task_names, t.task_name\n\n\n@requires_torch\ndef test_task_extraction_anchor_block():\n    mod, params, _ = get_network(name=\"resnet_18\", input_shape=[1, 3, 224, 224])\n    extracted_tasks = ms.relay_integration.extract_tasks(\n        mod, target=\"llvm\", params=params, module_equality=\"anchor-block\"\n    )\n\n    # Note that there is no task from residual blocks\n    expected_task_names = [\n        \"fused_\" + s\n        for s in [\n            \"nn_max_pool2d\",\n            \"nn_adaptive_avg_pool2d\",\n            \"nn_dense_add\",\n            \"nn_conv2d_add\",\n            \"nn_conv2d_add_1\",\n            \"nn_conv2d_add_2\",\n            \"nn_conv2d_add_nn_relu\",\n            \"nn_conv2d_add_nn_relu_1\",\n            \"nn_conv2d_add_nn_relu_2\",\n            \"nn_conv2d_add_nn_relu_3\",\n            \"nn_conv2d_add_nn_relu_4\",\n            \"nn_conv2d_add_nn_relu_5\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1\",\n            \"layout_transform\",\n            \"layout_transform_reshape_squeeze\",\n        ]\n    ]\n\n    assert len(extracted_tasks) == len(expected_task_names)\n    for t in extracted_tasks:\n        assert t.task_name in expected_task_names, t.task_name\n\n\n@requires_torch\ndef test_meta_schedule_integration_extract_from_bert_base():\n    pytest.importorskip(\n        \"transformers\", reason=\"transformers package is required to import bert_base\"\n    )\n\n    expected = {\n        \"fused_nn_dense_2\": (\n            12,\n            [[64, 3072], [768, 3072], [64, 768]],\n        ),\n        \"fused_nn_dense\": (\n            48,\n            [[64, 768], [768, 768], [64, 768]],\n        ),\n        \"fused_nn_dense_1\": (\n            12,\n            [[64, 768], [3072, 768], [64, 3072]],\n        ),\n        \"fused_subtract_add_rsqrt_multiply_multiply_add\": (\n            25,\n            [[1, 64, 768], [1, 64, 1], [1, 64, 1], [768], [768], [1, 64, 768]],\n        ),\n        \"fused_nn_batch_matmul\": (\n            24,\n            [[12, 64, 64], [12, 64, 64], [12, 64, 64]],\n        ),\n        \"fused_reshape_add_add\": (\n            24,\n            [[64, 768], [768], [1, 64, 768], [1, 64, 768]],\n        ),\n        \"fused_variance\": (\n            25,\n            [[1, 64, 768], [1, 64, 1], [1, 64, 1]],\n        ),\n        \"fused_mean\": (\n            25,\n            [[1, 64, 768], [1, 64, 1]],\n        ),\n        \"fused_reshape_add_reshape_transpose_reshape\": (\n            12,\n            [[64, 768], [768], [12, 64, 64]],\n        ),\n        \"fused_reshape_add_multiply_fast_erf_multiply_add_multiply_reshape\": (\n            12,\n            [[64, 3072], [3072], [64, 3072]],\n        ),\n        \"fused_nn_fast_softmax\": (\n            12,\n            [[1, 12, 64, 64], [1, 12, 64, 64]],\n        ),\n        \"fused_reshape_add_reshape_transpose_reshape_1\": (\n            24,\n            [[64, 768], [768], [12, 64, 64]],\n        ),\n        \"fused_reshape_divide_add\": (\n            12,\n            [[12, 64, 64], [1, 1, 1, 64], [1, 12, 64, 64]],\n        ),\n        \"fused_reshape_transpose_reshape\": (\n            12,\n            [[12, 64, 64], [64, 768]],\n        ),\n        \"fused_nn_dense_add_fast_tanh\": (\n            1,\n            [[1, 768], [768, 768], [1, 768], [1, 768]],\n        ),\n        \"fused_cast_take_add\": (\n            1,\n            [[1, 64], [30522, 768], [1, 64, 768], [1, 64, 768]],\n        ),\n        \"fused_take\": (\n            1,\n            [[1, 64, 768], [1, 768]],\n        ),\n        \"fused_reshape\": (\n            12,\n            [[1, 12, 64, 64], [12, 64, 64]],\n        ),\n        \"fused_reshape_1\": (\n            24,\n            [[1, 64, 768], [64, 768]],\n        ),\n    }\n    mod, params, _ = get_network(name=\"bert_base\", input_shape=[1, 64])\n    extracted_tasks = ms.relay_integration.extract_tasks(mod, target=\"llvm\", params=params)\n    assert len(extracted_tasks) == len(expected)\n    for t in extracted_tasks:\n        prim_func = None\n        for _, v in t.dispatched[0].functions.items():\n            prim_func = v\n        shape = [[int(x) for x in prim_func.buffer_map[b].shape] for b in prim_func.params]\n        assert t.task_name in expected\n        expected_weight, expected_shape = expected[t.task_name]\n        assert expected_weight == t.weight, t.task_name\n        assert expected_shape == shape, t.task_name\n\n\n@requires_torch\ndef test_meta_schedule_integration_extract_from_resnet_with_filter_func():\n    @register_func(\"relay.backend.tir_converter.remove_purely_spatial\", override=True)\n    def filter_func(args, _) -> bool:\n        from tvm.te import create_prim_func  # pylint: disable=import-outside-toplevel\n\n        has_complex_op = False\n        visited = set()\n\n        def traverse(t):\n            nonlocal has_complex_op\n            assert t.handle is not None\n            if t.handle.value in visited:\n                return\n            if isinstance(t.op, te.PlaceholderOp):\n                pass\n            elif isinstance(t.op, te.ComputeOp):\n                has_complex_op = has_complex_op or any(isinstance(e, tir.Reduce) for e in t.op.body)\n                for x in t.op.input_tensors:\n                    traverse(x)\n            visited.add(t.handle.value)\n\n        for t in args:\n            traverse(t)\n        if not has_complex_op:\n            return None\n        return create_prim_func(args)\n\n    mod, params, _ = get_network(name=\"resnet_18\", input_shape=[1, 3, 224, 224])\n    extracted_tasks = ms.relay_integration.extract_tasks(\n        mod,\n        target=\"llvm\",\n        params=params,\n        pass_config={\n            \"relay.backend.use_meta_schedule\": True,\n            \"relay.backend.tir_converter\": \"remove_purely_spatial\",\n        },\n    )\n    expected_task_names = [\n        \"fused_\" + s\n        for s in [\n            \"nn_max_pool2d\",\n            \"nn_adaptive_avg_pool2d\",\n            \"nn_dense_add\",\n            \"nn_conv2d_add\",\n            \"nn_conv2d_add_1\",\n            \"nn_conv2d_add_2\",\n            \"nn_conv2d_add_add_nn_relu\",\n            \"nn_conv2d_add_add_nn_relu_1\",\n            \"nn_conv2d_add_nn_relu\",\n            \"nn_conv2d_add_nn_relu_1\",\n            \"nn_conv2d_add_nn_relu_2\",\n            \"nn_conv2d_add_nn_relu_3\",\n            \"nn_conv2d_add_nn_relu_4\",\n            \"nn_conv2d_add_nn_relu_5\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu_1\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu\",\n            \"nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1\",\n        ]\n    ]\n\n    assert len(extracted_tasks) == len(expected_task_names)\n    for t in extracted_tasks:\n        assert t.task_name in expected_task_names, t.task_name\n\n\n@pytest.mark.skip(\"Too slow on CI\")\ndef extract_task_qbert():\n    def _test(mod, params, target):\n        extracted_tasks = ms.relay_integration.extract_tasks(mod, target, params)\n        tune_tasks = list(\n            filter(\n                lambda task: \"dense\" in task.task_name or \"batch_matmul\" in task.task_name,\n                extracted_tasks,\n            )\n        )\n        # three int8 dense, two int8 bmm, and one fp32 dense\n        assert len(tune_tasks) == 6\n\n        for task in tune_tasks:\n            relay_func = list(task.mod.functions.values())[0]\n            out_type = relay_func.body.checked_type\n\n            if out_type.dtype == \"float32\":\n                continue\n\n            sch = tvm.tir.Schedule(_normalize_mod(task.dispatched[0]))\n            block = sch.get_block(\"compute\")\n            annotations = sch.get(block).annotations\n\n            assert \"schedule_rule\" in annotations\n            assert \"vnni\" in annotations[\"schedule_rule\"]\n\n    mod, params, _ = load_quantized_bert_base(batch_size=1, seq_len=128)\n    _test(mod, params, target=\"llvm -mcpu=cascadelake\")\n\n\n@tvm.testing.skip_if_32bit(reason=\"Apparently the LLVM version on i386 image is too old\")\ndef test_extract_task_arm_conv2d_nchwc():\n    data_shape = (1, 64, 128, 128)\n    weight_shape = (32, 64, 1, 1)\n    bias_shape = (weight_shape[0],)\n    padding = (1, 1)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"int8\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"int8\")\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"int32\")\n    conv2d = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=weight_shape[2:],\n        channels=weight_shape[0],\n        padding=padding,\n        strides=(1, 1),\n        out_dtype=\"int32\",\n    )\n    bias_add = relay.nn.bias_add(conv2d, bias)\n    relay_mod = tvm.IRModule.from_expr(bias_add)\n\n    weight_np = np.random.uniform(1, 10, size=weight_shape).astype(\"int8\")\n    bias_np = np.random.uniform(1, 10, size=bias_shape).astype(\"int32\")\n\n    params = {\"weight\": weight_np, \"bias\": bias_np}\n\n    target = \"llvm -device arm_cpu -mtriple aarch64-linux-gnu -mattr=+neon\"\n    extracted_tasks = ms.relay_integration.extract_tasks(relay_mod, target, params)\n    tune_tasks = list(\n        filter(\n            lambda task: \"conv2d\" in task.task_name,\n            extracted_tasks,\n        )\n    )\n\n    assert len(tune_tasks) == 1\n\n    relay_func = list(tune_tasks[0].mod.functions.values())[0]\n    out_type = relay_func.body.checked_type\n\n    # Check that the output is in NCHWc layout\n    assert list(out_type.shape) == [1, 8, 130, 130, 4]\n\n\ndef test_meta_schedule_te2primfunc_argument_order_and_lowering():\n    # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n    # fmt: off\n    @tvm.script.ir_module\n    class _fused_layout_transform:\n        @T.prim_func\n        def main( # type: ignore\n            placeholder: T.Buffer[(1, 3, 16, 16), \"float32\"], # type: ignore\n            T_layout_trans: T.Buffer[(1, 1, 16, 16, 3), \"float32\"], # type: ignore\n        ) -> None: # type: ignore\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            for i0, i1, i2, i3, i4 in T.grid(1, 1, 16, 16, 3):\n                with T.block(\"T_layout_trans\"):\n                    ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                    T.reads(placeholder[ax0, ax1 * 3 + ax4, ax2, ax3])\n                    T.writes(T_layout_trans[ax0, ax1, ax2, ax3, ax4])\n                    T_layout_trans[ax0, ax1, ax2, ax3, ax4] = T.if_then_else(\n                        ax0 < 1 and ax1 * 3 + ax4 < 3 and ax2 < 16 and ax3 < 16, # type: ignore\n                        placeholder[ax0, ax1 * 3 + ax4, ax2, ax3],\n                        T.float32(0),\n                        dtype=\"float32\",\n                    )\n\n    @tvm.script.ir_module\n    class _fused_layout_transform_1:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(1, 2, 16, 16, 4), \"float32\"], T_layout_trans: T.Buffer[(1, 8, 16, 16), \"float32\"]) -> None: # type: ignore\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            for i0, i1, i2, i3 in T.grid(1, 8, 16, 16):\n                with T.block(\"T_layout_trans\"):\n                    ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(placeholder[ax0, ax1 // 4, ax2, ax3, ax1 % 4]) # type: ignore\n                    T.writes(T_layout_trans[ax0, ax1, ax2, ax3])\n                    T_layout_trans[ax0, ax1, ax2, ax3] = T.if_then_else(ax0 < 1 and ax1 < 8 and ax2 < 16 and ax3 < 16, placeholder[ax0, ax1 // 4, ax2, ax3, ax1 % 4], T.float32(0), dtype=\"float32\") # type: ignore\n\n    @tvm.script.ir_module\n    class _fused_nn_contrib_conv2d_NCHWc:\n        @T.prim_func\n        def main(placeholder: T.Buffer[(1, 1, 16, 16, 3), \"float32\"], placeholder_1: T.Buffer[(2, 1, 5, 5, 3, 4), \"float32\"], conv2d_NCHWc: T.Buffer[(1, 2, 16, 16, 4), \"float32\"]) -> None: # type: ignore\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            data_pad = T.alloc_buffer([1, 1, 20, 20, 3], dtype=\"float32\")\n            for i0, i1, i2, i3, i4 in T.grid(1, 1, 20, 20, 3):\n                with T.block(\"data_pad\"):\n                    i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                    T.reads(placeholder[i0_1, i1_1, i2_1 - 2, i3_1 - 2, i4_1])\n                    T.writes(data_pad[i0_1, i1_1, i2_1, i3_1, i4_1])\n                    data_pad[i0_1, i1_1, i2_1, i3_1, i4_1] = T.if_then_else(2 <= i2_1 and i2_1 < 18 and 2 <= i3_1 and i3_1 < 18, placeholder[i0_1, i1_1, i2_1 - 2, i3_1 - 2, i4_1], T.float32(0), dtype=\"float32\") # type: ignore # pylint: disable=R1716\n            for i0, i1, i2, i3, i4, i5, i6, i7 in T.grid(1, 2, 16, 16, 4, 3, 5, 5):\n                with T.block(\"conv2d_NCHWc\"):\n                    n, oc_chunk, oh, ow, oc_block, ic, kh, kw = T.axis.remap(\"SSSSSRRR\", [i0, i1, i2, i3, i4, i5, i6, i7])\n                    T.reads(data_pad[n, ic // 3, oh + kh, ow + kw, ic % 3], placeholder_1[oc_chunk, ic // 3, kh, kw, ic % 3, oc_block]) # type: ignore\n                    T.writes(conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block])\n                    with T.init():\n                        conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] = T.float32(0)\n                    conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] + data_pad[n, ic // 3, oh + kh, ow + kw, ic % 3] * placeholder_1[oc_chunk, ic // 3, kh, kw, ic % 3, oc_block] # type: ignore\n\n    # fmt: on\n    # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n    def _create_verification_database():\n        @ms.derived_object\n        class VerificationDatabase(ms.database.PyDatabase):\n            def __init__(self):\n                super().__init__()\n                self.tuning_records_: List[TuningRecord] = []\n                self.workloads_: List[Workload] = []\n\n            def has_workload(self, mod: IRModule) -> bool:\n                for workload in self.workloads_:\n                    if tvm.ir.structural_equal(mod, workload.mod):\n                        return True\n                # Note: The database has already put in all correct workloads\n                # This is where we can check if the workload is correct\n                raise ValueError(\n                    \"The workload searched for is not in given database!\"\n                    + \" Incorrect TIR was generated from TE subgraph.\"\n                )\n\n            def commit_workload(self, mod: IRModule) -> ms.database.Workload:\n                # No need to deduplicate workload because they are specified\n                workload = ms.database.Workload(mod)\n                self.workloads_.append(workload)\n                return workload\n\n            def commit_tuning_record(self, record: TuningRecord) -> None:\n                self.tuning_records_.append(record)\n\n            def get_all_tuning_records(self) -> List[TuningRecord]:\n                return self.tuning_records_\n\n            def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]:\n                return sorted(\n                    list(\n                        filter(\n                            lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod),\n                            self.tuning_records_,\n                        )\n                    ),\n                    key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9,\n                )[:top_k]\n\n            def __len__(self) -> int:\n                return len(self.tuning_records_)\n\n        database = VerificationDatabase()\n\n        def _commit(mod):\n            workload = database.commit_workload(mod)\n            database.commit_tuning_record(\n                ms.database.TuningRecord(\n                    tir.schedule.Trace([], {}),\n                    workload=workload,\n                    run_secs=[0.1],\n                )\n            )\n\n        _commit(_fused_layout_transform)\n        _commit(_fused_layout_transform_1)\n        _commit(_fused_nn_contrib_conv2d_NCHWc)\n        return database\n\n    data_shape = (1, 3, 16, 16)\n    weight_shape = (8, 3, 5, 5)\n\n    def _create_relay_mod():\n        data = relay.var(\"data\", relay.TensorType(data_shape, \"float32\"))\n        weight = relay.var(\"weight\", relay.TensorType(weight_shape, \"float32\"))\n        y = relay.nn.conv2d(\n            data,\n            weight,\n            padding=(2, 2),\n            kernel_size=(5, 5),\n            kernel_layout=\"OIHW\",\n            out_dtype=\"float32\",\n        )\n        f = relay.Function([data, weight], y)\n        mod = tvm.IRModule.from_expr(f)\n        mod = relay.transform.InferType()(mod)\n        return mod\n\n    mod = _create_relay_mod()\n    dev = tvm.cpu()\n    target = Target(\"llvm --num-cores=16\")\n    params = {\n        \"weight\": np.random.rand(*weight_shape).astype(\"float32\"),\n    }\n    data = tvm.nd.array(\n        np.random.rand(*data_shape).astype(\"float32\"),\n        dev,\n    )\n\n    with target, _create_verification_database(), PassContext(  # pylint: disable=not-context-manager\n        opt_level=3,\n        config={\n            \"relay.backend.use_meta_schedule\": True,\n            \"relay.backend.use_meta_schedule_dispatch\": 7,\n            \"relay.backend.tir_converter\": \"default\",\n        },\n    ):\n        rt_mod1 = relay.build(mod, target=target, params=params)\n\n    # Compile without meta-schedule for correctness check\n    with tvm.transform.PassContext(opt_level=0):\n        rt_mod2 = relay.build(mod, target=target, params=params)\n\n    def get_output(data, lib):\n        module = graph_executor.GraphModule(lib[\"default\"](dev))\n        module.set_input(\"data\", data)\n        module.run()\n        return module.get_output(0).numpy()\n\n    # Check correctness\n    actual_output = get_output(data, rt_mod1)\n    expected_output = get_output(data, rt_mod2)\n    assert np.allclose(actual_output, expected_output, rtol=1e-4, atol=2e-4)\n\n\ndef test_rewrite_layout_link_params():\n    I, O, H, W = 64, 64, 56, 56\n    kH = kW = 3\n\n    strides = (1, 1)\n    padding = (1, 1)\n\n    data_shape = (1, H, W, I)\n    w_shape = (kH, kW, I, O)\n    bias_shape = (1, 1, 1, O)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight1\", shape=w_shape, dtype=\"float32\")\n    bias = relay.var(\"bias\", shape=bias_shape, dtype=\"float32\")\n\n    conv = relay.nn.conv2d(\n        data=data,\n        weight=weight,\n        kernel_size=(kH, kW),\n        channels=O,\n        padding=padding,\n        strides=strides,\n        data_layout=\"NHWC\",\n        kernel_layout=\"HWIO\",\n        out_dtype=\"float32\",\n    )\n\n    mod = tvm.IRModule.from_expr(conv + bias)\n\n    weight_np = np.random.randn(*w_shape).astype(\"float32\")\n    bias_np = np.random.randn(*bias_shape).astype(\"float32\")\n\n    params = {\"weight1\": weight_np, \"bias\": bias_np}\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight_np, bias_np])\n        .numpy()\n    )\n\n    link_params = True\n\n    target = \"llvm --num-cores=4\"\n\n    executor = relay.backend.Executor(\"graph\", {\"link-params\": link_params})\n    mod = mod.with_attr(\"executor\", executor)\n\n    for strategy in [\"replay-trace\", \"evolutionary\"]:\n        with tempfile.TemporaryDirectory() as work_dir:\n            database = ms.relay_integration.tune_relay(\n                mod=mod,\n                target=target,\n                params=params,\n                work_dir=work_dir,\n                max_trials_global=4,\n                strategy=strategy,\n            )\n\n            lib = ms.relay_integration.compile_relay(\n                database=database,\n                mod=mod,\n                target=target,\n                params=params,\n            )\n\n        dev = tvm.device(target, 0)\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n        runtime.set_input(\"data\", data_np)\n        runtime.run()\n\n        out = runtime.get_output(0).numpy()\n\n        np.testing.assert_allclose(ref, out, rtol=1e-4, atol=1e-4)\n\n\ndef test_module_equality_ignore_ndarray():\n    target = \"llvm --num-cores=4\"\n\n    data_shape = (128, 128)\n    weight_shape1 = (128, 128)\n    weight_shape2 = (128, 128)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight1 = relay.var(\"weight1\", shape=weight_shape1, dtype=\"float32\")\n    weight2 = relay.var(\"weight2\", shape=weight_shape2, dtype=\"float32\")\n    dense1 = relay.nn.dense(data, weight1)\n    dense2 = relay.nn.dense(dense1, weight2)\n    mod = tvm.IRModule.from_expr(dense2)\n\n    weight1_np = np.random.randn(*weight_shape1).astype(\"float32\")\n    weight2_np = np.random.randn(*weight_shape2).astype(\"float32\")\n\n    params = {\"weight1\": weight1_np, \"weight2\": weight2_np}\n\n    executor = relay.backend.Executor(\"graph\", {\"link-params\": True})\n    mod = mod.with_attr(\"executor\", executor)\n\n    # Without using ignore-ndarray for module equality, we get duplicated tasks\n    assert len(ms.relay_integration.extract_tasks(mod, target, params)) == 2\n\n    module_eqality = \"ignore-ndarray\"\n    extracted_tasks = ms.relay_integration.extract_tasks(\n        mod, target, params, module_equality=module_eqality\n    )\n\n    assert len(extracted_tasks) == 1\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        tasks, task_weights = ms.relay_integration.extracted_tasks_to_tune_contexts(\n            extracted_tasks, work_dir, strategy=\"replay-trace\"\n        )\n        database = ms.tune.tune_tasks(\n            tasks=tasks,\n            task_weights=task_weights,\n            work_dir=work_dir,\n            max_trials_global=4,\n            module_equality=module_eqality,\n        )\n        lib = ms.relay_integration.compile_relay(database, mod, target, params)\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n\n    out = runtime.get_output(0).numpy()\n\n    ref = np.dot(np.dot(data_np, weight1_np.transpose()), weight2_np.transpose())\n    np.testing.assert_allclose(ref, out, rtol=1e-4, atol=1e-4)\n\n\ndef _test_anchor_tuning(target):\n    data_shape = (128, 128)\n    weight_shape1 = (128, 128)\n    weight_shape2 = (128, 128)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight1 = relay.var(\"weight1\", shape=weight_shape1, dtype=\"float32\")\n    weight2 = relay.var(\"weight2\", shape=weight_shape2, dtype=\"float32\")\n    dense1 = relay.nn.dense(data, weight1)\n    dense2 = relay.nn.dense(dense1 + relay.const(1.0, dtype=\"float32\"), weight2)\n    mod = tvm.IRModule.from_expr(dense2 - data + relay.const(1.0, dtype=\"float32\"))\n\n    weight1_np = np.random.randn(*weight_shape1).astype(\"float32\")\n    weight2_np = np.random.randn(*weight_shape2).astype(\"float32\")\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    params = {\"weight1\": weight1_np, \"weight2\": weight2_np}\n\n    module_equality = \"anchor-block\"\n\n    extracted_tasks = ms.relay_integration.extract_tasks(\n        mod, target, params, module_equality=module_equality\n    )\n\n    assert len(extracted_tasks) == 1\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=target,\n            params=params,\n            work_dir=work_dir,\n            max_trials_global=4,\n            strategy=\"replay-trace\",\n            module_equality=module_equality,\n        )\n        lib = ms.relay_integration.compile_relay(database, mod, target, params)\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n    out = runtime.get_output(0).numpy()\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight1_np, weight2_np])\n        .numpy()\n    )\n\n    np.testing.assert_allclose(ref, out, atol=1e-3)\n\n\ndef test_anchor_tuning_cpu():\n    _test_anchor_tuning(\"llvm --num-cores=4\")\n\n\ndef test_anchor_tuning_cpu_link_params():\n    data_shape = (128, 128)\n    weight_shape1 = (128, 128)\n    weight_shape2 = (128, 128)\n\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight1 = relay.var(\"weight1\", shape=weight_shape1, dtype=\"float32\")\n    weight2 = relay.var(\"weight2\", shape=weight_shape2, dtype=\"float32\")\n    dense1 = relay.nn.dense(data, weight1)\n    dense2 = relay.nn.dense(dense1, weight2)\n    mod = tvm.IRModule.from_expr(dense2 + relay.const(1.0, dtype=\"float32\"))\n\n    weight1_np = np.random.randn(*weight_shape1).astype(\"float32\")\n    weight2_np = np.random.randn(*weight_shape2).astype(\"float32\")\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    params = {\"weight1\": weight1_np, \"weight2\": weight2_np}\n\n    module_equality = \"anchor-block\"\n    target = \"llvm --num-cores=4\"\n\n    executor = relay.backend.Executor(\"graph\", {\"link-params\": True})\n    mod = mod.with_attr(\"executor\", executor)\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        database = ms.relay_integration.tune_relay(\n            mod=mod,\n            target=target,\n            params=params,\n            work_dir=work_dir,\n            max_trials_global=4,\n            strategy=\"replay-trace\",\n            module_equality=module_equality,\n        )\n        lib = ms.relay_integration.compile_relay(database, mod, target, params)\n\n    dev = tvm.device(target, 0)\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n    out = runtime.get_output(0).numpy()\n\n    ref = (\n        relay.create_executor(\"graph\", mod=mod, device=tvm.cpu(0), target=\"llvm\")\n        .evaluate()(*[data_np, weight1_np, weight2_np])\n        .numpy()\n    )\n\n    np.testing.assert_allclose(ref, out, atol=1e-3)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_relay_tir_compute.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import autotvm\nfrom tvm import meta_schedule as ms\nfrom tvm import relay, te\nfrom tvm.relay.testing.temp_op_attr import TempOpAttr\nfrom tvm.script import tir as T\n\n\ndef compute_tir_conv2d_nchw_oihw(data_shape, weight_shape, dtype):\n    assert dtype == \"float32\"\n    OC, IC, FH, FW = weight_shape\n\n    padding = (0, 0, 0, 0)\n    strides = (1, 1)\n    dilation = (1, 1)\n    output_shape = (\n        data_shape[0],\n        weight_shape[0],\n        (data_shape[2] - ((weight_shape[2] - 1) * dilation[0] + 1) + padding[0] + padding[1])\n        // strides[0]\n        + 1,\n        (data_shape[3] - ((weight_shape[3] - 1) * dilation[1] + 1) + padding[2] + padding[3])\n        // strides[1]\n        + 1,\n    )\n    N, K, BH, BW = output_shape\n\n    # fmt: off\n    @T.prim_func\n    def conv2d(a: T.handle, filt: T.handle, b: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, data_shape, dtype=dtype)\n        Filter = T.match_buffer(filt, weight_shape, dtype=dtype)\n        B = T.match_buffer(b, output_shape, dtype=dtype)\n        for n, k, bh, bw in T.grid(N, K, BH, BW):\n            with T.block(\"init\"):\n                vn, vk, vbh, vbw = T.axis.remap(\"SSSS\", [n, k, bh, bw])\n                B[vn, vk, vbh, vbw] = T.float32(0)\n            for ic, fh, fw in T.grid(IC, FH, FW):\n                with T.block(\"update\"):\n                    vn, vk, vbh, vbw, vc, vfh, vfw = T.axis.remap(\"SSSSRRR\", [n, k, bh, bw, ic, fh, fw])\n                    B[vn, vk, vbh, vbw] = B[vn, vk, vbh, vbw] + A[vn, vc, vbh + vfh, vbw + vfw] * Filter[vk, vc, vfh, vfw]\n    # fmt: on\n\n    return conv2d\n\n\ndef schedule_tir_conv2d_nchw_oihw(sch):\n    update_block = sch.get_block(\"update\")\n    vn, vk, vbh, vbw, vc, vfh, vfw = sch.get_loops(update_block)\n    sch.split(vk, factors=(None, 32))\n\n\n@autotvm.register_topi_compute(\"test/conv2d_1\")\ndef _compute_conv2d_1(cfg, input, filter, strides, padding, dilation, out_dtype):\n    prim_func = compute_tir_conv2d_nchw_oihw(input.shape, filter.shape, input.dtype)\n    output = te.extern_primfunc([input, filter], prim_func, name=\"tir\")\n    return output\n\n\n@autotvm.register_topi_schedule(\"test/conv2d_1\")\ndef _schedule_conv2d_1(cfg, outs):\n    s = te.create_schedule([x.op for x in outs])\n    return s\n\n\n@tvm.target.override_native_generic_func(\"test_conv2d_strategy\")\ndef _tmp_strategy(attrs, inputs, out_type, target):\n    strategy = relay.op.OpStrategy()\n    if attrs.groups == 1 and attrs.data_layout == \"NCHW\" and attrs.kernel_layout == \"OIHW\":\n        strategy.add_implementation(\n            relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_1),\n            relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_1),\n            name=\"conv2d_2\",\n            plevel=15,\n        )\n    else:\n        raise ValueError(\"No valid strategy found\")\n    return strategy\n\n\ndef get_conv2d(data_shape, weight_shape, **kwargs):\n    data = relay.var(\"data\", shape=data_shape, dtype=\"float32\")\n    weight = relay.var(\"weight\", shape=weight_shape, dtype=\"float32\")\n    conv2d = relay.nn.conv2d(\n        data,\n        weight,\n        **kwargs,\n    )\n    return relay.Function([data, weight], conv2d)\n\n\ndef get_ref(data, weight, stride, padding):\n    return tvm.topi.testing.conv2d_nchw_python(data, weight, stride, padding)\n\n\ndef test_conv2d():\n    N, IC, H, W = 1, 64, 56, 56\n    OC, IC, FH, FW = 128, 64, 3, 3\n    data_shape = (N, IC, H, W)\n    weight_shape = (OC, IC, FH, FW)\n    padding = (0, 0)\n    strides = (1, 1)\n\n    relay_mod = tvm.IRModule.from_expr(\n        get_conv2d(\n            data_shape,\n            weight_shape,\n            padding=padding,\n            strides=strides,\n            channels=OC,\n            kernel_size=(FH, FW),\n            data_layout=\"NCHW\",\n            kernel_layout=\"OIHW\",\n        )\n    )\n\n    data_np = np.random.randn(*data_shape).astype(\"float32\")\n    weight_np = np.random.randn(*weight_shape).astype(\"float32\")\n\n    target = \"llvm\"\n    params = {\"weight\": weight_np}\n\n    def schedule_fn(sch):\n        if \"nn_conv2d\" in sch.mod.attrs[\"task_name\"]:\n            schedule_tir_conv2d_nchw_oihw(sch)\n            return True\n        return False\n\n    with TempOpAttr(\"nn.conv2d\", \"FTVMStrategy\", _tmp_strategy):\n        with ms.database.ScheduleFnDatabase(schedule_fn), tvm.transform.PassContext(\n            opt_level=3,\n            config={\n                \"relay.backend.use_meta_schedule\": True,\n                \"relay.backend.tir_converter\": \"allow_extern\",\n            },\n        ):\n            lib = relay.build(relay_mod, target=target, params=params)\n\n    dev = tvm.device(target, 0)\n\n    runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n\n    runtime.set_input(\"data\", data_np)\n    runtime.run()\n\n    out = runtime.get_output(0).numpy()\n\n    ref = get_ref(data_np, weight_np, strides, padding)\n\n    tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4)\n\n\nif __name__ == \"__main__\":\n    test_conv2d()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_runner.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule Runner \"\"\"\n\nimport itertools\nimport sys\nimport time\nfrom typing import Any, List\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm._ffi import register_func\nfrom tvm.meta_schedule.arg_info import TensorInfo\nfrom tvm.meta_schedule.builder import BuilderInput, LocalBuilder\nfrom tvm.meta_schedule.runner import (\n    EvaluatorConfig,\n    LocalRunner,\n    PyRunner,\n    RPCConfig,\n    RPCRunner,\n    RunnerFuture,\n    RunnerInput,\n)\nfrom tvm.meta_schedule.runner.local_runner import (\n    default_alloc_argument as local_default_alloc_argument,\n)\nfrom tvm.meta_schedule.runner.rpc_runner import (\n    T_ARG_INFO_JSON_OBJ_LIST,\n    T_ARGUMENT_LIST,\n)\nfrom tvm.meta_schedule.runner.rpc_runner import (\n    default_alloc_argument as rpc_default_alloc_argument,\n)\nfrom tvm.meta_schedule.testing.local_rpc import LocalRPC\nfrom tvm.meta_schedule.utils import (\n    derived_object,\n    get_global_func_with_default_on_worker,\n)\nfrom tvm.rpc import RPCSession\nfrom tvm.runtime import Device, Module\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir import FloatImm\n\nMATMUL_N = 16\nMATMUL_M = 32\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring,unbalanced-tuple-unpacking\n\n\n@tvm.script.ir_module\nclass MatmulModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (16, 16), \"float32\")\n        C = T.match_buffer(c, (16, 16), \"float32\")\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass MatmulReluModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, d: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (16, 16), \"float32\")\n        D = T.match_buffer(d, (16, 16), \"float32\")\n        C = T.alloc_buffer((16, 16), \"float32\")\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n        for i, j in T.grid(16, 16):\n            with T.block(\"relu\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n@tvm.script.ir_module\nclass BatchMatmulModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, [16, 32, 32])\n        B = T.match_buffer(b, [16, 32, 32])\n        C = T.match_buffer(c, [16, 32, 32])\n        for n, i, j, k in T.grid(16, 32, 32, 32):\n            with T.block(\"update\"):\n                vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n                with T.init():\n                    C[vn, vi, vj] = 0.0\n                C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk]\n\n\n@tvm.script.ir_module\nclass AddModule:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, [32], \"float32\")\n        B = T.match_buffer(b, [32], \"float32\")\n        C = T.match_buffer(c, [32], \"float32\")\n        for i in range(32):\n            with T.block(\"add\"):\n                vi = T.axis.S(32, i)\n                C[vi] = A[vi] + B[vi]\n\n\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\ndef _clean_build(artifact_path: str) -> None:\n    f_clean_build = get_global_func_with_default_on_worker(\"meta_schedule.remove_build_dir\", None)\n    if f_clean_build is not None:\n        f_clean_build(artifact_path)\n    else:\n        raise RuntimeError(\"Unable to find remove_build_dir function.\")\n\n\ndef test_meta_schedule_rpc_single_run():\n    \"\"\"Test meta schedule rpc runner for a single run\"\"\"\n    # Build the module\n    mod = MatmulModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(rpc_config, evaluator_config)\n        # Run the module\n        (runner_future,) = runner.run([runner_input])\n        runner_result = runner_future.result()\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_local_single_run():\n    \"\"\"Test meta schedule local runner for a single run\"\"\"\n    # Build the module\n    mod = MatmulModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    evaluator_config = EvaluatorConfig(\n        number=1,\n        repeat=1,\n        min_repeat_ms=0,\n        enable_cpu_cache_flush=False,\n    )\n    runner = LocalRunner(timeout_sec=100, evaluator_config=evaluator_config)\n    # Run the module\n    (runner_future,) = runner.run([runner_input])\n    runner_result = runner_future.result()\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_rpc_multiple_runs():\n    \"\"\"Test meta schedule rpc runner for multiple runs\"\"\"\n    # Build the module\n    mods = [\n        MatmulModule,\n        MatmulReluModule,\n        BatchMatmulModule,\n    ]\n    builder = LocalBuilder()\n    builder_inputs = [BuilderInput(mod, Target(\"llvm\")) for mod in mods]\n    builder_results = builder.build(builder_inputs)\n    for builder_result in builder_results:\n        assert builder_result.artifact_path is not None\n        assert builder_result.error_msg is None\n\n    args_infos = [\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n        [\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n        ],\n    ]\n\n    runner_inputs = [\n        RunnerInput(builder_results[i].artifact_path, \"llvm\", args_infos[i])\n        for i in range(len(mods))\n    ]\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(rpc_config, evaluator_config)\n        # Run the module\n        runner_futures = runner.run(runner_inputs)\n        runner_results = [runner_future.result() for runner_future in runner_futures]\n\n    for runner_result in runner_results:\n        assert runner_result.error_msg is None\n        for result in runner_result.run_secs:\n            if isinstance(result, FloatImm):\n                result = result.value\n            assert isinstance(result, float)\n            assert result >= 0.0\n\n    for builder_result in builder_results:\n        _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_local_multiple_runs():\n    \"\"\"Test meta schedule local runner for multiple runs\"\"\"\n    # Build the module\n    mods = [\n        MatmulModule,\n        MatmulReluModule,\n        BatchMatmulModule,\n    ]\n    builder = LocalBuilder()\n    builder_inputs = [BuilderInput(mod, Target(\"llvm\")) for mod in mods]\n    builder_results = builder.build(builder_inputs)\n    for builder_result in builder_results:\n        assert builder_result.artifact_path is not None\n        assert builder_result.error_msg is None\n\n    args_infos = [\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n        [\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n            TensorInfo(\"float32\", [16, MATMUL_M, MATMUL_M]),\n        ],\n    ]\n\n    runner_inputs = [\n        RunnerInput(builder_results[i].artifact_path, \"llvm\", args_infos[i])\n        for i in range(len(mods))\n    ]\n\n    evaluator_config = EvaluatorConfig(\n        number=1,\n        repeat=1,\n        min_repeat_ms=0,\n        enable_cpu_cache_flush=False,\n    )\n\n    runner = LocalRunner(timeout_sec=100, evaluator_config=evaluator_config)\n\n    # Run the module\n    runner_futures = runner.run(runner_inputs)\n    runner_results = [runner_future.result() for runner_future in runner_futures]\n\n    for runner_result in runner_results:\n        assert runner_result.error_msg is None\n        for result in runner_result.run_secs:\n            if isinstance(result, FloatImm):\n                result = result.value\n            assert isinstance(result, float)\n            assert result >= 0.0\n\n    for builder_result in builder_results:\n        _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_py_runner():\n    \"\"\"Test meta schedule PyRunner\"\"\"\n\n    @derived_object\n    class TestRunner(PyRunner):\n        def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]:\n            raise ValueError(\"TestRunner\")\n\n    runner = TestRunner()\n    with pytest.raises(ValueError, match=\"TestRunner\"):\n        runner.run([])\n\n\ndef test_meta_schedule_rpc_runner_time_out():\n    \"\"\"Test meta schedule RPC Runner time out\"\"\"\n\n    def initializer():\n        @register_func(\"meta_schedule.runner.test_time_out\")\n        def timeout_session_creator(  # pylint: disable=unused-variable\n            rpc_config: RPCConfig,  # pylint: disable=unused-argument\n        ) -> RPCSession:\n            time.sleep(2)\n\n    runner_input = RunnerInput(\n        \"test\",\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=1,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(\n            rpc_config,\n            evaluator_config,\n            initializer=initializer,\n            f_create_session=\"meta_schedule.runner.test_time_out\",\n        )\n        # Run the module\n        (runner_future,) = runner.run([runner_input])\n        runner_result = runner_future.result()\n\n    assert runner_result.error_msg is not None and runner_result.error_msg.startswith(\n        \"RPCRunner: Timeout, killed after\"\n    )\n    assert runner_result.run_secs is None\n\n\ndef test_meta_schedule_local_runner_time_out():\n    \"\"\"Test meta schedule Local Runner time out\"\"\"\n    mod = MatmulModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    def initializer():\n        @register_func(\"meta_schedule.runner.test_time_out\")\n        def timeout_session_creator(  # pylint: disable=unused-variable\n            device: Device,  # pylint: disable=unused-argument\n            args_info: T_ARG_INFO_JSON_OBJ_LIST,  # pylint: disable=unused-argument\n            alloc_repeat: int,  # pylint: disable=unused-argument\n        ) -> RPCSession:\n            time.sleep(2)\n\n    evaluator_config = EvaluatorConfig(\n        number=1,\n        repeat=1,\n        min_repeat_ms=0,\n        enable_cpu_cache_flush=False,\n    )\n\n    runner = LocalRunner(\n        timeout_sec=1,\n        evaluator_config=evaluator_config,\n        initializer=initializer,\n        f_alloc_argument=\"meta_schedule.runner.test_time_out\",\n    )\n\n    # Run the module\n    (runner_future,) = runner.run([runner_input])\n    runner_result = runner_future.result()\n\n    assert runner_result.error_msg is not None and runner_result.error_msg.startswith(\n        \"LocalRunner: Timeout, killed after\"\n    )\n    assert runner_result.run_secs is None\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_rpc_runner_exception():\n    \"\"\"Test meta schedule RPC Runner exception\"\"\"\n\n    def initializer():\n        @register_func(\"meta_schedule.runner.test_exception\")\n        def exception_session_creator(  # pylint: disable=unused-variable\n            rpc_config: RPCConfig,  # pylint: disable=unused-argument\n        ) -> RPCSession:\n            raise Exception(\"Test\")\n\n    runner_input = RunnerInput(\n        \"test\",\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(\n            rpc_config,\n            evaluator_config,\n            initializer=initializer,\n            f_create_session=\"meta_schedule.runner.test_exception\",\n        )\n        (runner_future,) = runner.run([runner_input])\n        runner_result = runner_future.result()\n\n    assert runner_result.error_msg is not None and runner_result.error_msg.startswith(\n        \"RPCRunner: An exception occurred\\n\"\n    )\n    assert runner_result.run_secs is None\n\n\ndef test_meta_schedule_local_runner_exception():\n    \"\"\"Test meta schedule Local Runner exception\"\"\"\n    mod = MatmulModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    def initializer():\n        @register_func(\"meta_schedule.runner.test_exception\")\n        def timeout_session_creator(  # pylint: disable=unused-variable\n            device: Device,  # pylint: disable=unused-argument\n            args_info: T_ARG_INFO_JSON_OBJ_LIST,  # pylint: disable=unused-argument\n            alloc_repeat: int,  # pylint: disable=unused-argument\n        ) -> RPCSession:\n            raise Exception(\"Test\")\n\n    evaluator_config = EvaluatorConfig(\n        number=1,\n        repeat=1,\n        min_repeat_ms=0,\n        enable_cpu_cache_flush=False,\n    )\n\n    runner = LocalRunner(\n        evaluator_config=evaluator_config,\n        initializer=initializer,\n        f_alloc_argument=\"meta_schedule.runner.test_exception\",\n    )\n\n    # Run the module\n    (runner_future,) = runner.run([runner_input])\n    runner_result = runner_future.result()\n\n    assert runner_result.error_msg is not None and runner_result.error_msg.startswith(\n        \"LocalRunner: An exception occurred\\n\"\n    )\n    assert runner_result.run_secs is None\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_runner_matmul_test():\n    \"\"\"Test meta schedule runner with add module\"\"\"\n\n    def _check_correct_matmul(\n        args_before: List[np.ndarray],\n        args_after: List[np.ndarray],\n    ) -> None:\n        a_before, b_before, c_before = args_before\n        a_after, b_after, c_after = args_after\n        c_before = np.matmul(a_before, b_before)\n        assert (a_before == a_after).all()\n        assert (b_before == b_after).all()\n        tvm.testing.assert_allclose(c_before, c_after, rtol=1e-5)\n\n    def test_alloc_argument(\n        session: RPCSession,\n        device: Device,\n        args_info: Any,\n        alloc_repeat: int,\n    ) -> List[Any]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_before = []  # type: ignore\n        repeated_args = rpc_default_alloc_argument(session, device, args_info, alloc_repeat)\n        for args in repeated_args:\n            repeated_args_before.append([arg.numpy() for arg in args])  # type: ignore\n        return repeated_args\n\n    def test_run_evaluator(\n        session: RPCSession,  # pylint: disable=unused-argument\n        rt_mod: Module,\n        device: Device,\n        evaluator_config: EvaluatorConfig,\n        repeated_args: List[Any],\n    ) -> List[float]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_after = []\n        evaluator = rt_mod.time_evaluator(\n            func_name=rt_mod.entry_name,\n            dev=device,\n            number=evaluator_config.number,\n            repeat=evaluator_config.repeat,\n            min_repeat_ms=evaluator_config.min_repeat_ms,\n            f_preproc=\"cache_flush_cpu_non_first_arg\"\n            if evaluator_config.enable_cpu_cache_flush\n            else \"\",\n        )\n        repeated_costs: List[List[float]] = []\n        for args in repeated_args:\n            device.sync()\n            profile_result = evaluator(*args)\n            repeated_costs.append(profile_result.results)\n            repeated_args_after.append([arg.numpy() for arg in args])\n        costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)]\n        for args_before, args_after in zip(\n            repeated_args_before,  # type: ignore\n            repeated_args_after,\n        ):\n            _check_correct_matmul(args_before, args_after)\n        del repeated_args_before  # type: ignore\n        return costs\n\n    # Build the module\n    mod = MatmulModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n            TensorInfo(\"float32\", (MATMUL_N, MATMUL_N)),\n        ],\n    )\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(\n            rpc_config,\n            evaluator_config,\n            f_alloc_argument=test_alloc_argument,\n            f_run_evaluator=test_run_evaluator,\n        )\n        # Run the module\n        (runner_future,) = runner.run([runner_input])\n        runner_result = runner_future.result()\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_runner_add_test():\n    \"\"\"Test meta schedule runner with add module\"\"\"\n\n    def _check_correct_add(args_before: List[np.ndarray], args_after: List[np.ndarray]) -> None:\n        a_before, b_before, c_before = args_before\n        a_after, b_after, c_after = args_after\n        c_before = a_before + b_before\n        assert (a_before == a_after).all()\n        assert (b_before == b_after).all()\n        assert (c_before == c_after).all()\n\n    def test_alloc_argument(\n        session: RPCSession,\n        device: Device,\n        args_info: Any,\n        alloc_repeat: int,\n    ) -> List[Any]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_before = []  # type: ignore\n        repeated_args = rpc_default_alloc_argument(\n            session,\n            device,\n            args_info,\n            alloc_repeat,\n        )\n        for args in repeated_args:\n            repeated_args_before.append([arg.numpy() for arg in args])  # type: ignore\n        return repeated_args\n\n    def test_run_evaluator(\n        session: RPCSession,  # pylint: disable=unused-argument\n        rt_mod: Module,\n        device: Device,\n        evaluator_config: EvaluatorConfig,\n        repeated_args: List[Any],\n    ) -> List[float]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_after = []\n        evaluator = rt_mod.time_evaluator(\n            func_name=rt_mod.entry_name,\n            dev=device,\n            number=evaluator_config.number,\n            repeat=evaluator_config.repeat,\n            min_repeat_ms=evaluator_config.min_repeat_ms,\n            f_preproc=\"cache_flush_cpu_non_first_arg\"\n            if evaluator_config.enable_cpu_cache_flush\n            else \"\",\n        )\n        repeated_costs: List[List[float]] = []\n        for args in repeated_args:\n            device.sync()\n            profile_result = evaluator(*args)\n            repeated_costs.append(profile_result.results)\n            repeated_args_after.append([arg.numpy() for arg in args])\n        costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)]\n        for args_before, args_after in zip(\n            repeated_args_before,  # type: ignore\n            repeated_args_after,\n        ):\n            _check_correct_add(args_before, args_after)\n        del repeated_args_before  # type: ignore\n        return costs\n\n    # Build the module\n    mod = AddModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", [MATMUL_M]),\n            TensorInfo(\"float32\", [MATMUL_M]),\n            TensorInfo(\"float32\", [MATMUL_M]),\n        ],\n    )\n\n    with LocalRPC() as rpc:\n        rpc_config = RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n        evaluator_config = EvaluatorConfig(\n            number=1,\n            repeat=1,\n            min_repeat_ms=0,\n            enable_cpu_cache_flush=False,\n        )\n        runner = RPCRunner(\n            rpc_config,\n            evaluator_config,\n            f_alloc_argument=test_alloc_argument,\n            f_run_evaluator=test_run_evaluator,\n        )\n        # Run the module\n        (runner_future,) = runner.run([runner_input])\n        runner_result = runner_future.result()\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n    _clean_build(builder_result.artifact_path)\n\n\ndef test_meta_schedule_local_runner_add_test():\n    \"\"\"Test meta schedule local runner with add module\"\"\"\n\n    def _check_correct_add(args_before: List[np.array], args_after: List[np.array]) -> None:\n        a_before, b_before, c_before = args_before\n        a_after, b_after, c_after = args_after\n        c_before = a_before + b_before\n        assert (a_before == a_after).all()\n        assert (b_before == b_after).all()\n        assert (c_before == c_after).all()\n\n    def test_alloc_argument(\n        device: Device,\n        args_info: T_ARG_INFO_JSON_OBJ_LIST,  # pylint: disable=unused-argument\n        alloc_repeat: int,\n    ) -> List[T_ARGUMENT_LIST]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_before = []\n        repeated_args = local_default_alloc_argument(device, args_info, alloc_repeat)\n        for args in repeated_args:\n            repeated_args_before.append([arg.asnumpy() for arg in args])\n        return repeated_args\n\n    def test_run_evaluator(\n        rt_mod: Module,\n        device: Device,\n        evaluator_config: EvaluatorConfig,\n        repeated_args: List[Any],\n    ) -> List[float]:\n        global repeated_args_before  # pylint: disable=global-variable-undefined, invalid-name\n        repeated_args_after = []\n        evaluator = rt_mod.time_evaluator(\n            func_name=rt_mod.entry_name,\n            dev=device,\n            number=evaluator_config.number,\n            repeat=evaluator_config.repeat,\n            min_repeat_ms=evaluator_config.min_repeat_ms,\n            f_preproc=\"cache_flush_cpu_non_first_arg\"\n            if evaluator_config.enable_cpu_cache_flush\n            else \"\",\n        )\n        repeated_costs: List[List[float]] = []\n        for args in repeated_args:\n            device.sync()\n            profile_result = evaluator(*args)\n            repeated_costs.append(profile_result.results)\n            repeated_args_after.append([arg.asnumpy() for arg in args])\n        costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)]\n        for args_before, args_after in zip(repeated_args_before, repeated_args_after):\n            _check_correct_add(args_before, args_after)\n        del repeated_args_before\n        return costs\n\n    # Build the module\n    mod = AddModule\n    builder = LocalBuilder()\n    (builder_result,) = builder.build([BuilderInput(mod, Target(\"llvm\"))])\n    assert builder_result.artifact_path is not None\n    assert builder_result.error_msg is None\n\n    runner_input = RunnerInput(\n        builder_result.artifact_path,\n        \"llvm\",\n        [\n            TensorInfo(\"float32\", [MATMUL_M]),\n            TensorInfo(\"float32\", [MATMUL_M]),\n            TensorInfo(\"float32\", [MATMUL_M]),\n        ],\n    )\n\n    evaluator_config = EvaluatorConfig(\n        number=1,\n        repeat=1,\n        min_repeat_ms=0,\n        enable_cpu_cache_flush=False,\n    )\n    runner = LocalRunner(\n        timeout_sec=100,\n        evaluator_config=evaluator_config,\n        f_alloc_argument=test_alloc_argument,\n        f_run_evaluator=test_run_evaluator,\n    )\n    # Run the module\n    (runner_future,) = runner.run([runner_input])\n    runner_result = runner_future.result()\n    assert runner_result.error_msg is None\n    for result in runner_result.run_secs:\n        if isinstance(result, FloatImm):\n            result = result.value\n        assert isinstance(result, float)\n        assert result >= 0.0\n    _clean_build(builder_result.artifact_path)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_add_rfactor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.te import create_prim_func\n\n\ndef test_cpu_matmul():\n    @T.prim_func\n    def cpu_matmul_0(\n        A: T.Buffer[(4, 512), \"float32\"],\n        B: T.Buffer[(512, 4), \"float32\"],\n        C: T.Buffer[(4, 4), \"float32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0, i1, i2 in T.grid(4, 4, 512):\n            with T.block(\"C\"):\n                i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                T.reads(A[i, k], B[k, j])\n                T.writes(C[i, j])\n                with T.init():\n                    C[i, j] = T.float32(0)\n                C[i, j] = C[i, j] + A[i, k] * B[k, j]\n\n    @T.prim_func\n    def cpu_matmul_1(\n        A: T.Buffer[(4, 512), \"float32\"],\n        B: T.Buffer[(512, 4), \"float32\"],\n        C: T.Buffer[(4, 4), \"float32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        C_rf = T.alloc_buffer([4, 4, 128], dtype=\"float32\")\n        for i0, i1, i2_0, i2_1 in T.grid(4, 4, 4, 128):\n            with T.block(\"C_rf\"):\n                vi2_1, i, j, vi2_0 = T.axis.remap(\"SSSR\", [i2_1, i0, i1, i2_0])\n                T.reads(A[i, vi2_0 * 128 + vi2_1], B[vi2_0 * 128 + vi2_1, j])\n                T.writes(C_rf[i, j, vi2_1])\n                with T.init():\n                    C_rf[i, j, vi2_1] = T.float32(0)\n                C_rf[i, j, vi2_1] = (\n                    C_rf[i, j, vi2_1] + A[i, vi2_0 * 128 + vi2_1] * B[vi2_0 * 128 + vi2_1, j]\n                )\n        for i0, i1, i2_1 in T.grid(4, 4, 128):\n            with T.block(\"C\"):\n                vi2_1, i, j = T.axis.remap(\"RSS\", [i2_1, i0, i1])\n                T.reads(C_rf[i, j, vi2_1])\n                T.writes(C[i, j])\n                T.block_attr({\"meta_schedule.random_compute_producer\": 1})\n                with T.init():\n                    C[i, j] = T.float32(0)\n                C[i, j] = C[i, j] + C_rf[i, j, vi2_1]\n\n    @T.prim_func\n    def cpu_matmul_2(\n        A: T.Buffer[(4, 512), \"float32\"],\n        B: T.Buffer[(512, 4), \"float32\"],\n        C: T.Buffer[(4, 4), \"float32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        C_rf = T.alloc_buffer([4, 4, 4], dtype=\"float32\")\n        for i0, i1, i2_0, i2_1 in T.grid(4, 4, 4, 128):\n            with T.block(\"C_rf\"):\n                vi2_0, i, j, vi2_1 = T.axis.remap(\"SSSR\", [i2_0, i0, i1, i2_1])\n                T.reads(A[i, vi2_0 * 128 + vi2_1], B[vi2_0 * 128 + vi2_1, j])\n                T.writes(C_rf[i, j, vi2_0])\n                with T.init():\n                    C_rf[i, j, vi2_0] = T.float32(0)\n                C_rf[i, j, vi2_0] = (\n                    C_rf[i, j, vi2_0] + A[i, vi2_0 * 128 + vi2_1] * B[vi2_0 * 128 + vi2_1, j]\n                )\n        for i0, i1, i2_0 in T.grid(4, 4, 4):\n            with T.block(\"C\"):\n                vi2_0, i, j = T.axis.remap(\"RSS\", [i2_0, i0, i1])\n                T.reads(C_rf[i, j, vi2_0])\n                T.writes(C[i, j])\n                T.block_attr({\"meta_schedule.random_compute_producer\": 1})\n                with T.init():\n                    C[i, j] = T.float32(0)\n                C[i, j] = C[i, j] + C_rf[i, j, vi2_0]\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SamplePerfectTile\", [4, 128]),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [4, 128]),\n    ]\n    mod = create_prim_func(te_workload.matmul(n=4, m=4, k=512))\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm --num-cores=32\"),\n        types=ms.schedule_rule.AddRFactor,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cpu_matmul_0, cpu_matmul_1, cpu_matmul_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_argmax():\n    @T.prim_func\n    def argmax(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[(128,), \"int32\"],\n        argmax_v1: T.Buffer[(128,), \"float32\"],\n    ) -> None:\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"argmax\"):\n                i = T.axis.spatial(128, i0)\n                k = T.axis.reduce(128, i1)\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.min_value(\"float32\")\n                v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    @T.prim_func\n    def argmax_0(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[128, \"int32\"],\n        argmax_v1: T.Buffer[128, \"float32\"],\n    ) -> None:\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"argmax\"):\n                i, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    @T.prim_func\n    def argmax_1(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[128, \"int32\"],\n        argmax_v1: T.Buffer[128, \"float32\"],\n    ) -> None:\n        argmax_v0_rf = T.alloc_buffer([128, 16], dtype=\"int32\")\n        argmax_v1_rf = T.alloc_buffer([128, 16], dtype=\"float32\")\n        for i0, i1_0, i1_1 in T.grid(128, 8, 16):\n            with T.block(\"argmax_rf\"):\n                vi1_1, i, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n                T.reads(idx[i, vi1_0 * 16 + vi1_1], val[i, vi1_0 * 16 + vi1_1])\n                T.writes(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1])\n                with T.init():\n                    argmax_v0_rf[i, vi1_1] = -1\n                    argmax_v1_rf[i, vi1_1] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0_rf: T.int32 = T.Select(\n                    argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 16 + vi1_1],\n                    argmax_v0_rf[i, vi1_1],\n                    idx[i, vi1_0 * 16 + vi1_1],\n                )\n                v_argmax_v1_rf: T.float32 = T.Select(\n                    argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 16 + vi1_1],\n                    argmax_v1_rf[i, vi1_1],\n                    val[i, vi1_0 * 16 + vi1_1],\n                )\n                argmax_v0_rf[i, vi1_1] = v_argmax_v0_rf\n                argmax_v1_rf[i, vi1_1] = v_argmax_v1_rf\n        for i0, i1_1 in T.grid(128, 16):\n            with T.block(\"argmax\"):\n                vi1_1, i = T.axis.remap(\"RS\", [i1_1, i0])\n                T.reads(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                T.block_attr({\"meta_schedule.random_compute_producer\": 1})\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(\n                    argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v0[i], argmax_v0_rf[i, vi1_1]\n                )\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v1[i], argmax_v1_rf[i, vi1_1]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    @T.prim_func\n    def argmax_2(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[128, \"int32\"],\n        argmax_v1: T.Buffer[128, \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        argmax_v0_rf = T.alloc_buffer([128, 8], dtype=\"int32\")\n        argmax_v1_rf = T.alloc_buffer([128, 8], dtype=\"float32\")\n        for i0, i1_0, i1_1 in T.grid(128, 8, 16):\n            with T.block(\"argmax_rf\"):\n                vi1_0, i, vi1_1 = T.axis.remap(\"SSR\", [i1_0, i0, i1_1])\n                T.reads(idx[i, vi1_0 * 16 + vi1_1], val[i, vi1_0 * 16 + vi1_1])\n                T.writes(argmax_v0_rf[i, vi1_0], argmax_v1_rf[i, vi1_0])\n                with T.init():\n                    argmax_v0_rf[i, vi1_0] = -1\n                    argmax_v1_rf[i, vi1_0] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0_rf: T.int32 = T.Select(\n                    argmax_v1_rf[i, vi1_0] >= val[i, vi1_0 * 16 + vi1_1],\n                    argmax_v0_rf[i, vi1_0],\n                    idx[i, vi1_0 * 16 + vi1_1],\n                )\n                v_argmax_v1_rf: T.float32 = T.Select(\n                    argmax_v1_rf[i, vi1_0] >= val[i, vi1_0 * 16 + vi1_1],\n                    argmax_v1_rf[i, vi1_0],\n                    val[i, vi1_0 * 16 + vi1_1],\n                )\n                argmax_v0_rf[i, vi1_0] = v_argmax_v0_rf\n                argmax_v1_rf[i, vi1_0] = v_argmax_v1_rf\n        for i0, i1_0 in T.grid(128, 8):\n            with T.block(\"argmax\"):\n                vi1_0, i = T.axis.remap(\"RS\", [i1_0, i0])\n                T.reads(argmax_v0_rf[i, vi1_0], argmax_v1_rf[i, vi1_0])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                T.block_attr({\"meta_schedule.random_compute_producer\": 1})\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(\n                    argmax_v1[i] >= argmax_v1_rf[i, vi1_0], argmax_v0[i], argmax_v0_rf[i, vi1_0]\n                )\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= argmax_v1_rf[i, vi1_0], argmax_v1[i], argmax_v1_rf[i, vi1_0]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SamplePerfectTile\", [8, 16]),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [8, 16]),\n    ]\n    mod = argmax\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm --num-cores=32\"),\n        types=ms.schedule_rule.AddRFactor,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[argmax_0, argmax_1, argmax_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\nif __name__ == \"__main__\":\n    test_cpu_matmul()\n    test_cpu_argmax()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_apply_custom_rule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom typing import List\nimport tempfile\nimport pytest\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.schedule_rule import ApplyCustomRule\nfrom tvm.script import tir as T\n\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                T.block_attr({\"schedule_rule\": \"test_apply_custom_rule\"})\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.register_func(\"meta_schedule.cpu.test_apply_custom_rule\")\ndef sch_fn(sch: tvm.tir.Schedule, block: tvm.tir.Block) -> List[tvm.tir.Schedule]:\n    raise ValueError(\"Intended for meta_schedule.cpu.test_apply_custom_rule\")\n\n\ndef test_custom_rule():\n    with pytest.raises(ValueError) as e_info:\n        with tempfile.TemporaryDirectory() as tmpdir:\n            sch_rules = [ApplyCustomRule()]\n            space_gen = ms.space_generator.PostOrderApply(sch_rules=sch_rules)\n            ms.tune_tir(\n                mod=Matmul,\n                target=\"llvm -num-cores=1\",\n                work_dir=tmpdir,\n                max_trials_global=10,\n                space=space_gen,\n            )\n    assert \"ValueError: Intended for meta_schedule.cpu.test_apply_custom_rule\" in str(e_info.value)\n\n\nif __name__ == \"__main__\":\n    test_custom_rule()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_auto_bind.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\n@T.prim_func\ndef element_wise(var_A: T.handle, var_B: T.handle) -> None:\n    A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n    B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n    for i, j in T.grid(512, 512):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] + 1.0\n\n\n@T.prim_func\ndef reduction_loop_only(\n    A: T.Buffer[2, \"float32\"],\n    B: T.Buffer[2, \"float32\"],\n    C: T.Buffer[(), \"float32\"],\n) -> None:\n    for i0 in T.serial(2):\n        with T.block(\"C\"):\n            k0 = T.axis.reduce(2, i0)\n            T.reads(A[k0], B[k0])\n            T.writes(C[()])\n            with T.init():\n                C[()] = T.float32(1.0)\n            C[()] = T.min(C[()], A[k0] / B[k0])\n\n\n@T.prim_func\ndef zero_dim_add(\n    A: T.Buffer[(), \"float32\"],\n    B: T.Buffer[(), \"float32\"],\n    C: T.Buffer[(), \"float32\"],\n) -> None:\n    with T.block(\"C\"):\n        vi = T.axis.spatial(1, 0)\n        C[()] = A[()] + B[()]\n\n\ndef test_cuda_element_wise():\n    @T.prim_func\n    def elementwise_0(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i_j_fused_0 in T.thread_binding(256, thread=\"blockIdx.x\"):\n            for i_j_fused_1 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) // 512)\n                    vj = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) % 512)\n                    T.reads(A[vi, vj])\n                    T.writes(B[vi, vj])\n                    B[vi, vj] = A[vi, vj] + T.float32(1)\n\n    decision_0 = [\n        (\"SampleCategorical\", 5),\n    ]\n    mod = element_wise\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\", host=\"llvm\"),\n        types=ms.schedule_rule.AutoBind,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[elementwise_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_reduction_loop_only():\n    @T.prim_func\n    def reduction_loop_only_0(\n        A: T.Buffer[2, \"float32\"],\n        B: T.Buffer[2, \"float32\"],\n        C: T.Buffer[(), \"float32\"],\n    ) -> None:\n        for u_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for u_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                for i0 in T.serial(2):\n                    with T.block(\"C\"):\n                        k0 = T.axis.reduce(2, i0)\n                        T.reads(A[k0], B[k0])\n                        T.writes(C[()])\n                        with T.init():\n                            C[()] = T.float32(1)\n                        C[()] = T.min(C[()], A[k0] / B[k0])\n\n    mod = reduction_loop_only\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\", host=\"llvm\"),\n        types=ms.schedule_rule.AutoBind,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[reduction_loop_only_0],\n        expected_decisions=[[]],\n    )\n\n\ndef test_cuda_zero_dim_add():\n    @T.prim_func\n    def zero_dim_add_0(\n        A: T.Buffer[(), \"float32\"],\n        B: T.Buffer[(), \"float32\"],\n        C: T.Buffer[(), \"float32\"],\n    ) -> None:\n        for u_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for u_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(1, 0)\n                    T.reads(A[()], B[()])\n                    T.writes(C[()])\n                    C[()] = A[()] + B[()]\n\n    mod = zero_dim_add\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\", host=\"llvm\"),\n        types=ms.schedule_rule.AutoBind,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[zero_dim_add_0],\n        expected_decisions=[[]],\n    )\n\n\nif __name__ == \"__main__\":\n    test_cuda_element_wise()\n    test_cuda_reduction_loop_only()\n    test_cuda_zero_dim_add()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_auto_inline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport pytest\n\nimport tvm\nfrom tvm.tir import Schedule\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import generate_design_space\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n@tvm.script.ir_module\nclass Conv2DBiasBnReLU:\n    @T.prim_func\n    def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None:\n        X = T.match_buffer(var_X, [1, 512, 56, 56], dtype=\"float32\")\n        W = T.match_buffer(var_W, [512, 512, 3, 3], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 1, 1], dtype=\"float32\")\n        bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype=\"float32\")\n        bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype=\"float32\")\n        compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype=\"float32\")\n        pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype=\"float32\")\n        compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        bias_add = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        bn_mul = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        bn_add = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(1, 512, 58, 58):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype=\"float32\")\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 512, 56, 56, 512, 3, 3):\n            with T.block(\"compute\"):\n                nn, ff, yy, xx, rc, ry, rx = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                with T.init():\n                    compute_1[nn, ff, yy, xx] = T.float32(0)\n                compute_1[nn, ff, yy, xx] = compute_1[nn, ff, yy, xx] + pad_temp[nn, rc, yy + ry, xx + rx] * W[ff, rc, ry, rx]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"bias_add\"):\n                i, j, k, l = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                bias_add[i, j, k, l] = compute_1[i, j, k, l] + B[j, 0, 0]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"bn_mul\"):\n                i, j, k, l = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                bn_mul[i, j, k, l] = bias_add[i, j, k, l] * bn_scale[j, 0, 0]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"bn_add\"):\n                i, j, k, l = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                bn_add[i, j, k, l] = bn_mul[i, j, k, l] + bn_offset[j, 0, 0]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"compute_1\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                compute[i0_2, i1_2, i2_2, i3_2] = T.max(bn_add[i0_2, i1_2, i2_2, i3_2], T.float32(0))\n\n\n@tvm.script.ir_module\nclass Conv2DBiasBnReLUInlined:\n    @T.prim_func\n    def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None:\n        X = T.match_buffer(var_X, [1, 512, 56, 56], dtype=\"float32\")\n        W = T.match_buffer(var_W, [512, 512, 3, 3], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 1, 1], dtype=\"float32\")\n        bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype=\"float32\")\n        bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype=\"float32\")\n        compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype=\"float32\")\n        pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype=\"float32\")\n        compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(1, 512, 58, 58):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype=\"float32\")\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 512, 56, 56, 512, 3, 3):\n            with T.block(\"compute\"):\n                nn, ff, yy, xx, rc, ry, rx = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                with T.init():\n                    compute_1[nn, ff, yy, xx] = T.float32(0)\n                compute_1[nn, ff, yy, xx] = compute_1[nn, ff, yy, xx] + pad_temp[nn, rc, yy + ry, xx + rx] * W[ff, rc, ry, rx]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"compute_1\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                compute[i0_2, i1_2, i2_2, i3_2] = T.max((compute_1[i0_2, i1_2, i2_2, i3_2] + B[i1_2, 0, 0]) * bn_scale[i1_2, 0, 0] + bn_offset[i1_2, 0, 0], T.float32(0))\n\n\n@tvm.script.ir_module\nclass MultiLevelTiledConv2D:\n    @T.prim_func\n    def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None:\n        X = T.match_buffer(var_X, [1, 512, 56, 56], dtype=\"float32\")\n        W = T.match_buffer(var_W, [512, 512, 3, 3], dtype=\"float32\")\n        B = T.match_buffer(var_B, [512, 1, 1], dtype=\"float32\")\n        bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype=\"float32\")\n        bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype=\"float32\")\n        compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype=\"float32\")\n        pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype=\"float32\")\n        compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\")\n        compute_local = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\", scope=\"local\")\n        pad_temp_shared = T.alloc_buffer([1, 512, 58, 58], dtype=\"float32\", scope=\"shared\")\n        W_shared = T.alloc_buffer([512, 512, 3, 3], dtype=\"float32\", scope=\"shared\")\n        for i0, i1, i2, i3 in T.grid(1, 512, 58, 58):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype=\"float32\")\n        for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(0, 224, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(0, 2, thread=\"vthread.x\"):\n                for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(0, 8, thread=\"threadIdx.x\"):\n                    for i4_0, i5_0, i6_0 in T.grid(1, 3, 1):\n                        for ax0_ax1_ax2_ax3_fused_0 in T.serial(0, 40960, annotations={\"meta_schedule.cooperative_fetch\":1}):\n                            for ax0_ax1_ax2_ax3_fused_1 in T.vectorized(0, 3):\n                                with T.block(\"pad_temp_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(512, (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) // 30 // 8 % 512)\n                                    v2 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i5_0 + (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) // 30 % 8)\n                                    v3 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) % 30)\n                                    pad_temp_shared[v0, v1, v2, v3] = pad_temp[v0, v1, v2, v3]\n                        for ax0_ax1_ax2_ax3_fused_0 in T.serial(0, 12288, annotations={\"meta_schedule.cooperative_fetch\":1}):\n                            for ax0_ax1_ax2_ax3_fused_1 in T.vectorized(0, 4):\n                                with T.block(\"W_shared\"):\n                                    v0 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) // 1536)\n                                    v1 = T.axis.spatial(512, (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) // 3 % 512)\n                                    v2 = T.axis.spatial(3, i5_0)\n                                    v3 = T.axis.spatial(3, (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) % 3)\n                                    W_shared[v0, v1, v2, v3] = W[v0, v1, v2, v3]\n                        for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(32, 1, 1, 1, 1, 1, 1, 16, 1, 3, 1, 8, 2, 28):\n                            with T.block(\"compute\"):\n                                nn = T.axis.spatial(1, 0)\n                                ff = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + i1_4)\n                                yy = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused // 2 % 7 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + i2_4)\n                                xx = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + i3_4)\n                                rc = T.axis.reduce(512, i4_1 * 16 + i4_2)\n                                ry, rx = T.axis.remap(\"RR\", [i5_0, i6_2])\n                                with T.init():\n                                    compute_local[nn, ff, yy, xx] = T.float32(0)\n                                compute_local[nn, ff, yy, xx] = compute_local[nn, ff, yy, xx] + pad_temp_shared[nn, rc, yy + ry, xx + rx] * W_shared[ff, rc, ry, rx]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 8, 2, 28):\n                        with T.block(\"compute_local\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + ax1)\n                            v2 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + ax2)\n                            v3 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + ax3)\n                            compute_1[v0, v1, v2, v3] = compute_local[v0, v1, v2, v3]\n        for i0, i1, i2, i3 in T.grid(1, 512, 56, 56):\n            with T.block(\"compute_1\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                compute[i0_2, i1_2, i2_2, i3_2] = T.max((compute_1[i0_2, i1_2, i2_2, i3_2] + B[i1_2, 0, 0]) * bn_scale[i1_2, 0, 0] + bn_offset[i1_2, 0, 0], T.float32(0))\n\n\n@tvm.script.ir_module\nclass MultiLevelTiledConv2DAfterInline:\n    @T.prim_func\n    def main(X: T.Buffer[(1, 512, 56, 56), \"float32\"], W: T.Buffer[(512, 512, 3, 3), \"float32\"], B: T.Buffer[(512, 1, 1), \"float32\"], bn_scale: T.Buffer[(512, 1, 1), \"float32\"], bn_offset: T.Buffer[(512, 1, 1), \"float32\"], compute: T.Buffer[(1, 512, 56, 56), \"float32\"]) -> None:\n        compute_local = T.alloc_buffer([1, 512, 56, 56], dtype=\"float32\", scope=\"local\")\n        for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(224, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(2, thread=\"vthread.x\"):\n                for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    for i4_0, i5_0, i6_0, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 3, 1, 32, 1, 1, 1, 1, 1, 1, 16, 1, 3, 1, 8, 2, 28):\n                        with T.block(\"compute\"):\n                            nn = T.axis.spatial(1, 0)\n                            ff = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + i1_4)\n                            yy = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused // 2 % 7 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + i2_4)\n                            xx = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + i3_4)\n                            rc = T.axis.reduce(512, i4_1 * 16 + i4_2)\n                            ry, rx = T.axis.remap(\"RR\", [i5_0, i6_2])\n                            with T.init():\n                                compute_local[nn, ff, yy, xx] = T.float32(0)\n                            compute_local[nn, ff, yy, xx] = compute_local[nn, ff, yy, xx] + T.if_then_else(yy + ry >= 1 and yy + ry < 57 and xx + rx >= 1 and xx + rx < 57, X[nn, rc, yy + ry - 1, xx + rx - 1], T.float32(0), dtype=\"float32\") * W[ff, rc, ry, rx]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 8, 2, 28):\n                        with T.block(\"compute_local\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + ax1)\n                            v2 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + ax2)\n                            v3 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + ax3)\n                            compute[v0, v1, v2, v3] = T.max((compute_local[v0, v1, v2, v3] + B[v1, 0, 0]) * bn_scale[v1, 0, 0] + bn_offset[v1, 0, 0], T.float32(0))\n\n\n@tvm.script.ir_module\nclass SoftmaxBeforeInline:\n    @T.prim_func\n    def main(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.min_value(\"float32\")\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_exp\"):\n                i0_2, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T_softmax_exp[i0_2, i1_1] = T.exp(A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype=\"float32\")\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_4, k = T.axis.remap(\"SR\", [i0_3, i1])\n                with T.init():\n                    T_softmax_expsum[i0_4] = T.float32(0)\n                T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k]\n        for i0_5, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_6, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6]\n\n\n@tvm.script.ir_module\nclass SoftmaxAfterInline:\n    @T.prim_func\n    def main(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.min_value(\"float32\")\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_2, k = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    T_softmax_expsum[i0_2] = T.float32(0)\n                T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp(A[i0_2, k] - T_softmax_maxelem[i0_2], dtype=\"float32\")\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_4, i1_1 = T.axis.remap(\"SS\", [i0_3, i1])\n                T_softmax_norm[i0_4, i1_1] = T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\") / T_softmax_expsum[i0_4]\n\n\n@tvm.script.ir_module\nclass BeforePureSpatial:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 384), \"int64\"],\n        placeholder_1: T.Buffer[(30522, 768), \"float32\"],\n        placeholder_2: T.Buffer[(1, 384, 768), \"float32\"],\n        T_add: T.Buffer[(1, 384, 768), \"float32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        compile_engine_const = T.alloc_buffer([], dtype=\"int64\")\n        T_less = T.alloc_buffer([1, 384], dtype=\"bool\")\n        compile_engine_const_1 = T.alloc_buffer([], dtype=\"int64\")\n        T_add_1 = T.alloc_buffer([1, 384], dtype=\"int64\")\n        T_where = T.alloc_buffer([1, 384], dtype=\"int64\")\n        T_take = T.alloc_buffer([1, 384, 768], dtype=\"float32\")\n        with T.block(\"compile_engine_const\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const[()])\n            compile_engine_const[()] = T.int64(0)\n        for i0, i1 in T.grid(1, 384):\n            with T.block(\"T_less\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(placeholder[ax0, ax1], compile_engine_const[()])\n                T.writes(T_less[ax0, ax1])\n                T_less[ax0, ax1] = placeholder[ax0, ax1] < compile_engine_const[()]\n        with T.block(\"compile_engine_const_1\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_1[()])\n            compile_engine_const_1[()] = T.int64(30522)\n        for i0, i1 in T.grid(1, 384):\n            with T.block(\"T_add\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(placeholder[ax0, ax1], compile_engine_const_1[()])\n                T.writes(T_add_1[ax0, ax1])\n                T_add_1[ax0, ax1] = placeholder[ax0, ax1] + compile_engine_const_1[()]\n        for i0, i1 in T.grid(1, 384):\n            with T.block(\"T_where\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_less[ax0, ax1], T_add_1[ax0, ax1], placeholder[ax0, ax1])\n                T.writes(T_where[ax0, ax1])\n                T_where[ax0, ax1] = T.Select(\n                    T.cast(T_less[ax0, ax1], \"int32\") != 0, T_add_1[ax0, ax1], placeholder[ax0, ax1]\n                )\n        for i0, i1, i2 in T.grid(1, 384, 768):\n            with T.block(\"T_take\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads(\n                    placeholder_1[T.min(T.max(T.int64(0), T_where[ax0, ax1]), T.int64(30521)), ax2],\n                    T_where[ax0, ax1],\n                )\n                T.writes(T_take[ax0, ax1, ax2])\n                T_take[ax0, ax1, ax2] = placeholder_1[\n                    T.min(T.max(T.int64(0), T_where[ax0, ax1]), T.int64(30521)), ax2\n                ]\n        for i0, i1, i2 in T.grid(1, 384, 768):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads(T_take[ax0, ax1, ax2], placeholder_2[ax0, ax1, ax2])\n                T.writes(T_add[ax0, ax1, ax2])\n                T_add[ax0, ax1, ax2] = T_take[ax0, ax1, ax2] + placeholder_2[ax0, ax1, ax2]\n\n\n@tvm.script.ir_module\nclass AfterPureSpatial:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(1, 384), \"int64\"], placeholder_1: T.Buffer[(30522, 768), \"float32\"], placeholder_2: T.Buffer[(1, 384, 768), \"float32\"], T_add: T.Buffer[(1, 384, 768), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2 in T.grid(1, 384, 768):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads(placeholder[ax0, ax1], placeholder_1[T.min(T.max(T.int64(0), placeholder[ax0, ax1]), T.int64(30521)) : T.min(T.max(T.int64(0), placeholder[ax0, ax1] + T.int64(30522)), T.int64(30521)) + T.int64(1), ax2], placeholder_2[ax0, ax1, ax2])\n                T.writes(T_add[ax0, ax1, ax2])\n                T_add[ax0, ax1, ax2] = placeholder_1[T.min(T.max(T.int64(0), T.Select(T.cast(placeholder[ax0, ax1] < T.int64(0), \"int32\") != 0, placeholder[ax0, ax1] + T.int64(30522), placeholder[ax0, ax1])), T.int64(30521)), ax2] + placeholder_2[ax0, ax1, ax2]\n\n@tvm.script.ir_module\nclass ConstConsumer:\n    @T.prim_func\n    def main(T_full: T.Buffer[(1, 12, 4096), \"int64\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2 in T.grid(1, 12, 4096):\n            with T.block(\"T_full\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads()\n                T.writes(T_full[ax0, ax1, ax2])\n                T_full[ax0, ax1, ax2] = T.int64(0)\n\n\n@tvm.script.ir_module\nclass Conv2dInt8:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 14, 14, 256), \"int8\"], p1: T.Buffer[(1024, 1, 1, 256), \"int8\"], p2: T.Buffer[(1, 1, 1, 1024), \"int32\"], p3: T.Buffer[(1, 1, 1, 1024), \"int32\"], p4: T.Buffer[1024, \"int32\"], p5: T.Buffer[1024, \"int32\"], p6: T.Buffer[1024, \"int32\"], p7: T.Buffer[1, \"int32\"], p8: T.Buffer[(16, 14, 14, 1024), \"int32\"], compute: T.Buffer[(16, 14, 14, 1024), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        compile_engine_const = T.alloc_buffer([], dtype=\"int32\")\n        pad_temp = T.alloc_buffer([16, 14, 14, 256], dtype=\"int8\")\n        conv2d_nhwc = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        T_subtract = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        T_add = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        T_add_1 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        compute_2 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        T_subtract_1 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        compute_3 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        T_add_2 = T.alloc_buffer([16, 14, 14, 1024], dtype=\"int32\")\n        with T.block(\"compile_engine_const\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const[()])\n            compile_engine_const[()] = 59\n        for i0, i1, i2, i3 in T.grid(16, 14, 14, 256):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1, i2_1, i3_1])\n                T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1]\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 14, 14, 1024, 1, 1, 256):\n            with T.block(\"conv2d_nhwc\"):\n                nn, yy, xx, ff, ry, rx, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc])\n                T.writes(conv2d_nhwc[nn, yy, xx, ff])\n                with T.init():\n                    conv2d_nhwc[nn, yy, xx, ff] = 0\n                conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], \"int32\") * T.cast(p1[ff, ry, rx, rc], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3])\n                T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024):\n            with T.block(\"compute\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype=\"int32\")\n        for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 14, 14, 1024):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_3, i1_3, i2_3, i3_3])\n                T.reads(compile_engine_const[()], compute_1[ax0, ax1, ax2, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = compile_engine_const[()] + compute_1[ax0, ax1, ax2, ax3]\n        for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 14, 14, 1024):\n            with T.block(\"compute_1\"):\n                i0_5, i1_5, i2_5, i3_5 = T.axis.remap(\"SSSS\", [i0_4, i1_4, i2_4, i3_4])\n                T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5])\n                T.writes(compute_2[i0_5, i1_5, i2_5, i3_5])\n                compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0)\n        for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 14, 14, 1024):\n            with T.block(\"T_subtract_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_6, i1_6, i2_6, i3_6])\n                T.reads(compute_2[ax0, ax1, ax2, ax3], p7[0])\n                T.writes(T_subtract_1[ax0, ax1, ax2, ax3])\n                T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p7[0]\n        for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 14, 14, 1024):\n            with T.block(\"compute_2\"):\n                i0_8, i1_8, i2_8, i3_8 = T.axis.remap(\"SSSS\", [i0_7, i1_7, i2_7, i3_7])\n                T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8])\n                T.writes(compute_3[i0_8, i1_8, i2_8, i3_8])\n                compute_3[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1408572815, 31, 1, dtype=\"int32\")\n        for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 14, 14, 1024):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_9, i1_9, i2_9, i3_9])\n                T.reads(compute_3[ax0, ax1, ax2, ax3], p8[ax0, ax1, ax2, ax3])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3])\n                T_add_2[ax0, ax1, ax2, ax3] = compute_3[ax0, ax1, ax2, ax3] + p8[ax0, ax1, ax2, ax3]\n        for i0_10, i1_10, i2_10, i3_10 in T.grid(16, 14, 14, 1024):\n            with T.block(\"compute_3\"):\n                i0_11, i1_11, i2_11, i3_11 = T.axis.remap(\"SSSS\", [i0_10, i1_10, i2_10, i3_10])\n                T.reads(T_add_2[i0_11, i1_11, i2_11, i3_11])\n                T.writes(compute[i0_11, i1_11, i2_11, i3_11])\n                compute[i0_11, i1_11, i2_11, i3_11] = T.max(T.min(T_add_2[i0_11, i1_11, i2_11, i3_11], 255), 0)\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_inline_consumer_chain():\n    mod = Conv2DBiasBnReLU\n    target = Target(\"llvm\")\n    (space,) = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=target,\n        types=ms.schedule_rule.AutoInline,\n    )\n    tvm.ir.assert_structural_equal(lhs=space.mod, rhs=Conv2DBiasBnReLUInlined)\n\n\ndef test_inline_into_cache():\n    mod = MultiLevelTiledConv2D\n    target = Target(\"cuda\", host=\"llvm\")\n    (space,) = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=target,\n        types=ms.schedule_rule.AutoInline,\n    )\n    tvm.ir.assert_structural_equal(lhs=space.mod, rhs=MultiLevelTiledConv2DAfterInline)\n\n\ndef test_inline_into_multiple_consumers():\n    mod = SoftmaxBeforeInline\n    target = Target(\"cuda\", host=\"llvm\")\n    (space,) = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=target,\n        types=ms.schedule_rule.AutoInline,\n    )\n    tvm.ir.assert_structural_equal(lhs=space.mod, rhs=SoftmaxAfterInline)\n\n\ndef test_inline_pure_spatial():\n    mod = BeforePureSpatial\n    target = Target(\"llvm\")\n    (space,) = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=target,\n        types=ms.schedule_rule.AutoInline,\n    )\n    tvm.ir.assert_structural_equal(lhs=space.mod, rhs=AfterPureSpatial)\n\n\ndef test_inline_constant_tensor():\n    mod = ConstConsumer\n    target = Target(\"cuda\", host=\"llvm\")\n    (space,) = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=target,\n        types=ms.schedule_rule.AutoInline,\n    )\n    tvm.ir.assert_structural_equal(lhs=space.mod, rhs=ConstConsumer)\n\n\ndef test_conv2d_int8_inline_constant_scalars():\n    sch = Schedule(Conv2dInt8)\n\n    conv2d = sch.get_block(\"conv2d_nhwc\")\n    sch.cache_write(conv2d, 0, \"shared\")\n\n    with pytest.raises(tvm.tir.ScheduleError) as e:\n        sch.reverse_compute_inline(sch.get_block(\"T_add_1\"))\n\n    err_msg = \"The block is only allowed to read a single buffer region, but it reads 2 region(s)\"\n    assert err_msg in str(e)\n\n    ms.schedule_rule.InlineConstantScalars().apply(sch, sch.get_block(\"compile_engine_const\"))\n    sch.reverse_compute_inline(sch.get_block(\"T_add_1\"))\n\n\nif __name__ == \"__main__\":\n    test_inline_consumer_chain()\n    test_inline_into_cache()\n    test_inline_into_multiple_consumers()\n    test_inline_pure_spatial()\n    test_inline_constant_tensor()\n    test_conv2d_int8_inline_constant_scalars()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_cross_thread_reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\n\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.te import create_prim_func\n\n\n@tvm.script.ir_module\nclass Softmax_mn_after_inline:\n    @T.prim_func\n    def main(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.min_value(\"float32\")\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_2, k = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    T_softmax_expsum[i0_2] = T.float32(0)\n                T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp(\n                    A[i0_2, k] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                )\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_4, i1_1 = T.axis.remap(\"SS\", [i0_3, i1])\n                T.block_attr({\"axis\": 1})\n                T_softmax_norm[i0_4, i1_1] = (\n                    T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n                    / T_softmax_expsum[i0_4]\n                )\n\n\ndef test_gpu_softmax_mn():\n    @T.prim_func\n    def softmax_mn_0(\n        A: T.Buffer[(256, 256), \"float32\"],\n        T_softmax_norm: T.Buffer[(256, 256), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_1, k])\n                T.writes(T_softmax_maxelem[i0_1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38)\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_exp\"):\n                i0_2, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2])\n                T.writes(T_softmax_exp[i0_2, i1_1])\n                T_softmax_exp[i0_2, i1_1] = T.exp(\n                    A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                )\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_4, k = T.axis.remap(\"SR\", [i0_3, i1])\n                T.reads(T_softmax_exp[i0_4, k])\n                T.writes(T_softmax_expsum[i0_4])\n                with T.init():\n                    T_softmax_expsum[i0_4] = T.float32(0)\n                T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k]\n        for i0_5, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_6, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6])\n                T.writes(T_softmax_norm[i0_6, i1_2])\n                T.block_attr({\"axis\": 1})\n                T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6]\n\n    @T.prim_func\n    def softmax_mn_1(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 1):\n                for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_maxelem\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_1 = T.axis.spatial(256, ax0 + i0)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_1, k])\n                        T.writes(T_softmax_maxelem_shared[i0_1])\n                        with T.init():\n                            T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38)\n                        T_softmax_maxelem_shared[i0_1] = T.max(\n                            T_softmax_maxelem_shared[i0_1], A[i0_1, k]\n                        )\n            for i1_0 in T.serial(1):\n                for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_exp\"):\n                        T.where(i1_0 * 512 + i1_1 < 256)\n                        i0_2 = T.axis.spatial(256, i0)\n                        i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                        T.reads(A[i0_2, i1], T_softmax_maxelem_shared[i0_2])\n                        T.writes(T_softmax_exp[i0_2, i1])\n                        T_softmax_exp[i0_2, i1] = T.exp(\n                            A[i0_2, i1] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\"\n                        )\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_4, k = T.axis.remap(\"SR\", [i0_3, i1])\n                T.reads(T_softmax_exp[i0_4, k])\n                T.writes(T_softmax_expsum[i0_4])\n                with T.init():\n                    T_softmax_expsum[i0_4] = T.float32(0)\n                T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k]\n        for i0_5, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_6, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6])\n                T.writes(T_softmax_norm[i0_6, i1_2])\n                T.block_attr({\"axis\": 1})\n                T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6]\n\n    @T.prim_func\n    def softmax_mn_2(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n        T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_1, k])\n                T.writes(T_softmax_maxelem[i0_1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38)\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_exp\"):\n                i0_2, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2])\n                T.writes(T_softmax_exp[i0_2, i1_1])\n                T_softmax_exp[i0_2, i1_1] = T.exp(\n                    A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                )\n        for i0_3 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 32):\n                for ax1_1 in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_expsum\"):\n                        i0_4 = T.axis.spatial(256, ax0 + i0_3)\n                        k = T.axis.reduce(256, ax1_0 * 8 + ax1_1)\n                        T.reads(T_softmax_exp[i0_4, k])\n                        T.writes(T_softmax_expsum_shared[i0_4])\n                        with T.init():\n                            T_softmax_expsum_shared[i0_4] = T.float32(0)\n                        T_softmax_expsum_shared[i0_4] = (\n                            T_softmax_expsum_shared[i0_4] + T_softmax_exp[i0_4, k]\n                        )\n            for i1_0 in T.serial(32):\n                for i1_1_1 in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        i0_5 = T.axis.spatial(256, i0_3)\n                        i1 = T.axis.spatial(256, i1_0 * 8 + i1_1_1)\n                        T.reads(T_softmax_exp[i0_5, i1], T_softmax_expsum_shared[i0_5])\n                        T.writes(T_softmax_norm[i0_5, i1])\n                        T.block_attr({\"axis\": 1})\n                        T_softmax_norm[i0_5, i1] = (\n                            T_softmax_exp[i0_5, i1] / T_softmax_expsum_shared[i0_5]\n                        )\n\n    @T.prim_func\n    def softmax_mn_3(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n        T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        for i0 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 1):\n                for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_maxelem\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_1 = T.axis.spatial(256, ax0 + i0)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_1, k])\n                        T.writes(T_softmax_maxelem_shared[i0_1])\n                        with T.init():\n                            T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38)\n                        T_softmax_maxelem_shared[i0_1] = T.max(\n                            T_softmax_maxelem_shared[i0_1], A[i0_1, k]\n                        )\n            for i1_0 in T.serial(1):\n                for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_exp\"):\n                        T.where(i1_0 * 512 + i1_1 < 256)\n                        i0_2 = T.axis.spatial(256, i0)\n                        i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                        T.reads(A[i0_2, i1], T_softmax_maxelem_shared[i0_2])\n                        T.writes(T_softmax_exp[i0_2, i1])\n                        T_softmax_exp[i0_2, i1] = T.exp(\n                            A[i0_2, i1] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\"\n                        )\n        for i0_3 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 32):\n                for ax1_1 in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_expsum\"):\n                        i0_4 = T.axis.spatial(256, ax0 + i0_3)\n                        k = T.axis.reduce(256, ax1_0 * 8 + ax1_1)\n                        T.reads(T_softmax_exp[i0_4, k])\n                        T.writes(T_softmax_expsum_shared[i0_4])\n                        with T.init():\n                            T_softmax_expsum_shared[i0_4] = T.float32(0)\n                        T_softmax_expsum_shared[i0_4] = (\n                            T_softmax_expsum_shared[i0_4] + T_softmax_exp[i0_4, k]\n                        )\n            for i1_0 in T.serial(32):\n                for i1_1 in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        i0_5 = T.axis.spatial(256, i0_3)\n                        i1 = T.axis.spatial(256, i1_0 * 8 + i1_1)\n                        T.reads(T_softmax_exp[i0_5, i1], T_softmax_expsum_shared[i0_5])\n                        T.writes(T_softmax_norm[i0_5, i1])\n                        T.block_attr({\"axis\": 1})\n                        T_softmax_norm[i0_5, i1] = (\n                            T_softmax_exp[i0_5, i1] / T_softmax_expsum_shared[i0_5]\n                        )\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SampleCategorical\", 7),\n    ]\n    decision_2 = [\n        (\"SampleCategorical\", 1),\n    ]\n    decision_3 = [\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 7),\n    ]\n    mod = create_prim_func(te_workload.softmax_mn(n=256, m=256))\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3090\", host=\"llvm\"),\n        types=ms.schedule_rule.CrossThreadReduction,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[softmax_mn_0, softmax_mn_1, softmax_mn_2, softmax_mn_3],\n        expected_decisions=[decision_0, decision_1, decision_2, decision_3],\n    )\n\n\ndef test_gpu_softmax_mn_after_inline():\n    @T.prim_func\n    def softmax_mn_after_inline_0(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_1, k])\n                T.writes(T_softmax_maxelem[i0_1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38)\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_2, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_2, k], T_softmax_maxelem[i0_2])\n                T.writes(T_softmax_expsum[i0_2])\n                with T.init():\n                    T_softmax_expsum[i0_2] = T.float32(0)\n                T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp(\n                    A[i0_2, k] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                )\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_4, i1_1 = T.axis.remap(\"SS\", [i0_3, i1])\n                T.reads(A[i0_4, i1_1], T_softmax_maxelem[i0_4], T_softmax_expsum[i0_4])\n                T.writes(T_softmax_norm[i0_4, i1_1])\n                T.block_attr({\"axis\": 1})\n                T_softmax_norm[i0_4, i1_1] = (\n                    T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n                    / T_softmax_expsum[i0_4]\n                )\n\n    @T.prim_func\n    def softmax_mn_after_inline_1(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n        for i0, i1_0 in T.grid(256, 4):\n            for i1_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_maxelem\"):\n                    i0_1 = T.axis.spatial(256, i0)\n                    k = T.axis.reduce(256, i1_0 * 64 + i1_1)\n                    T.reads(A[i0_1, k])\n                    T.writes(T_softmax_maxelem[i0_1])\n                    with T.init():\n                        T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38)\n                    T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_expsum\"):\n                i0_2, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_2, k], T_softmax_maxelem[i0_2])\n                T.writes(T_softmax_expsum[i0_2])\n                with T.init():\n                    T_softmax_expsum[i0_2] = T.float32(0)\n                T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp(\n                    A[i0_2, k] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                )\n        for i0_3, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_norm\"):\n                i0_4, i1_1 = T.axis.remap(\"SS\", [i0_3, i1])\n                T.reads(A[i0_4, i1_1], T_softmax_maxelem[i0_4], T_softmax_expsum[i0_4])\n                T.writes(T_softmax_norm[i0_4, i1_1])\n                T.block_attr({\"axis\": 1})\n                T_softmax_norm[i0_4, i1_1] = (\n                    T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n                    / T_softmax_expsum[i0_4]\n                )\n\n    @T.prim_func\n    def softmax_mn_after_inline_2(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n        T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        for i0, i1 in T.grid(256, 256):\n            with T.block(\"T_softmax_maxelem\"):\n                i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(A[i0_1, k])\n                T.writes(T_softmax_maxelem[i0_1])\n                with T.init():\n                    T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38)\n                T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n        for i0_3 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 1):\n                for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_expsum\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_2 = T.axis.spatial(256, ax0 + i0_3)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_2, k], T_softmax_maxelem[i0_2])\n                        T.writes(T_softmax_expsum_shared[i0_2])\n                        with T.init():\n                            T_softmax_expsum_shared[i0_2] = T.float32(0)\n                        T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(\n                            A[i0_2, k] - T_softmax_maxelem[i0_2], dtype=\"float32\"\n                        )\n            for i1_0 in T.serial(1):\n                for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        T.where(i1_0 * 512 + i1_1 < 256)\n                        i0_4 = T.axis.spatial(256, i0_3)\n                        i1_1_1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                        T.reads(\n                            A[i0_4, i1_1_1], T_softmax_maxelem[i0_4], T_softmax_expsum_shared[i0_4]\n                        )\n                        T.writes(T_softmax_norm[i0_4, i1_1_1])\n                        T.block_attr({\"axis\": 1})\n                        T_softmax_norm[i0_4, i1_1_1] = (\n                            T.exp(A[i0_4, i1_1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n                            / T_softmax_expsum_shared[i0_4]\n                        )\n\n    @T.prim_func\n    def softmax_mn_after_inline_3(\n        A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n    ) -> None:\n        T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n        for i0_3 in T.serial(256):\n            for ax0, ax1_0 in T.grid(1, 1):\n                for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_maxelem\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_1 = T.axis.spatial(256, ax0 + i0_3)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_1, k])\n                        T.writes(T_softmax_maxelem_shared[i0_1])\n                        with T.init():\n                            T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38)\n                        T_softmax_maxelem_shared[i0_1] = T.max(\n                            T_softmax_maxelem_shared[i0_1], A[i0_1, k]\n                        )\n            for ax0, ax1_0 in T.grid(1, 1):\n                for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_expsum\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_2 = T.axis.spatial(256, ax0 + i0_3)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_2, k], T_softmax_maxelem_shared[i0_2])\n                        T.writes(T_softmax_expsum_shared[i0_2])\n                        with T.init():\n                            T_softmax_expsum_shared[i0_2] = T.float32(0)\n                        T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(\n                            A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\"\n                        )\n            for i1_0 in T.serial(1):\n                for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        T.where(i1_0 * 512 + i1_1 < 256)\n                        i0_4 = T.axis.spatial(256, i0_3)\n                        i1_1_1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                        T.reads(\n                            A[i0_4, i1_1_1],\n                            T_softmax_maxelem_shared[i0_4],\n                            T_softmax_expsum_shared[i0_4],\n                        )\n                        T.writes(T_softmax_norm[i0_4, i1_1_1])\n                        T.block_attr({\"axis\": 1})\n                        T_softmax_norm[i0_4, i1_1_1] = (\n                            T.exp(A[i0_4, i1_1_1] - T_softmax_maxelem_shared[i0_4], dtype=\"float32\")\n                            / T_softmax_expsum_shared[i0_4]\n                        )\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SampleCategorical\", 4),\n    ]\n    decision_2 = [\n        (\"SampleCategorical\", 7),\n    ]\n    decision_3 = [\n        (\"SampleCategorical\", 7),\n        (\"SampleCategorical\", 0),\n    ]\n\n    mod = Softmax_mn_after_inline\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3090\", host=\"llvm\"),\n        types=ms.schedule_rule.CrossThreadReduction,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[\n            softmax_mn_after_inline_0,\n            softmax_mn_after_inline_1,\n            softmax_mn_after_inline_2,\n            softmax_mn_after_inline_3,\n        ],\n        expected_decisions=[decision_0, decision_1, decision_2, decision_3],\n    )\n\n\ndef test_gpu_batch_norm_bmn():\n    @T.prim_func\n    def batch_norm_bmn_0(A: T.Buffer[(1, 512, 512), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([1], dtype=\"float32\")\n        for i0, i1, i2 in T.grid(1, 512, 512):\n            with T.block(\"C\"):\n                b, i, j = T.axis.remap(\"SRR\", [i0, i1, i2])\n                T.reads(A[b, i, j])\n                T.writes(C[b])\n                with T.init():\n                    C[b] = T.float32(0)\n                C[b] = C[b] + A[b, i, j] * A[b, i, j]\n        for i0 in T.serial(1):\n            with T.block(\"D\"):\n                b = T.axis.spatial(1, i0)\n                T.reads(C[b])\n                T.writes(D[b])\n                D[b] = T.sqrt(C[b], dtype=\"float32\")\n\n    @T.prim_func\n    def batch_norm_bmn_1(A: T.Buffer[(1, 512, 512), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_shared = T.alloc_buffer([1], dtype=\"float32\", scope=\"shared\")\n        for i0_0 in T.serial(1):\n            for ax0, ax1_ax2_fused_0 in T.grid(1, 1024):\n                for ax1_ax2_fused_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n                    with T.block(\"C\"):\n                        b = T.axis.spatial(1, ax0)\n                        i = T.axis.reduce(512, (ax1_ax2_fused_0 * 256 + ax1_ax2_fused_1) // 512)\n                        j = T.axis.reduce(512, (ax1_ax2_fused_0 * 256 + ax1_ax2_fused_1) % 512)\n                        T.reads(A[b, i, j])\n                        T.writes(C_shared[b])\n                        with T.init():\n                            C_shared[b] = T.float32(0)\n                        C_shared[b] = C_shared[b] + A[b, i, j] * A[b, i, j]\n            for i0_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n                with T.block(\"D\"):\n                    T.where(i0_0 * 256 + i0_1 < 1)\n                    b = T.axis.spatial(1, i0_0 * 256 + i0_1)\n                    T.reads(C_shared[b])\n                    T.writes(D[b])\n                    D[b] = T.sqrt(C_shared[b], dtype=\"float32\")\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SampleCategorical\", 6),\n    ]\n\n    mod = create_prim_func(te_workload.norm_bmn(B=1, M=512, N=512))\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3090\", host=\"llvm\"),\n        types=ms.schedule_rule.CrossThreadReduction,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[batch_norm_bmn_0, batch_norm_bmn_1],\n        expected_decisions=[decision_0, decision_1],\n    )\n\n\n@T.prim_func\ndef argmax(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1 in T.grid(128, 128):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_32(\n    idx: T.Buffer[(1, 32), \"int32\"],\n    val: T.Buffer[(1, 32), \"float32\"],\n    argmax_v0: T.Buffer[(1,), \"int32\"],\n    argmax_v1: T.Buffer[(1,), \"float32\"],\n) -> None:\n    for i0, i1 in T.grid(1, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(1, i0)\n            k = T.axis.reduce(32, i1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\ndef test_gpu_argmax():\n    @T.prim_func\n    def argmax_0(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[128, \"int32\"],\n        argmax_v1: T.Buffer[128, \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"argmax\"):\n                i, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    @T.prim_func\n    def argmax_1(\n        idx: T.Buffer[(128, 128), \"int32\"],\n        val: T.Buffer[(128, 128), \"float32\"],\n        argmax_v0: T.Buffer[128, \"int32\"],\n        argmax_v1: T.Buffer[128, \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i0, i1_0 in T.grid(128, 2):\n            for i1_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                with T.block(\"argmax\"):\n                    i = T.axis.spatial(128, i0)\n                    k = T.axis.reduce(128, i1_0 * 64 + i1_1)\n                    T.reads(idx[i, k], val[i, k])\n                    T.writes(argmax_v0[i], argmax_v1[i])\n                    with T.init():\n                        argmax_v0[i] = -1\n                        argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                    v_argmax_v0: T.int32 = T.Select(\n                        argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]\n                    )\n                    v_argmax_v1: T.float32 = T.Select(\n                        argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                    )\n                    argmax_v0[i] = v_argmax_v0\n                    argmax_v1[i] = v_argmax_v1\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SampleCategorical\", 4),\n    ]\n\n    mod = argmax\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3090\", host=\"llvm\"),\n        types=ms.schedule_rule.CrossThreadReduction,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[argmax_0, argmax_1],\n        expected_decisions=[decision_0, decision_1],\n    )\n\n\ndef test_gpu_argmax_32():\n    @T.prim_func\n    def argmax_0(\n        idx: T.Buffer[(1, 32), \"int32\"],\n        val: T.Buffer[(1, 32), \"float32\"],\n        argmax_v0: T.Buffer[(1,), \"int32\"],\n        argmax_v1: T.Buffer[(1,), \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i0, i1 in T.grid(1, 32):\n            with T.block(\"argmax\"):\n                i, k = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n    @T.prim_func\n    def argmax_1(\n        idx: T.Buffer[(1, 32), \"int32\"],\n        val: T.Buffer[(1, 32), \"float32\"],\n        argmax_v0: T.Buffer[(1,), \"int32\"],\n        argmax_v1: T.Buffer[(1,), \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        for i0, i1_0 in T.grid(1, 1):\n            for i1_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                with T.block(\"argmax\"):\n                    i = T.axis.spatial(1, i0)\n                    k = T.axis.reduce(32, i1_0 * 64 + i1_1)\n                    T.where(i1_0 * 64 + i1_1 < 32)\n                    T.reads(idx[i, k], val[i, k])\n                    T.writes(argmax_v0[i], argmax_v1[i])\n                    with T.init():\n                        argmax_v0[i] = -1\n                        argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                    v_argmax_v0: T.int32 = T.Select(\n                        argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]\n                    )\n                    v_argmax_v1: T.float32 = T.Select(\n                        argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                    )\n                    argmax_v0[i] = v_argmax_v0\n                    argmax_v1[i] = v_argmax_v1\n\n    decision_0 = []  # type: ignore\n    decision_1 = [\n        (\"SampleCategorical\", 4),\n    ]\n\n    mod = argmax_32\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3090\", host=\"llvm\"),\n        types=ms.schedule_rule.CrossThreadReduction,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[argmax_0, argmax_1],\n        expected_decisions=[decision_0, decision_1],\n    )\n\n\nif __name__ == \"__main__\":\n    test_gpu_softmax_mn()\n    test_gpu_softmax_mn_after_inline()\n    test_gpu_batch_norm_bmn()\n    test_gpu_argmax()\n    test_gpu_argmax_32()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_mlt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm import target, te\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef test_cpu_matmul():\n    @T.prim_func\n    def cpu_matmul_0(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        C: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_global = T.alloc_buffer([512, 512], dtype=\"float32\")\n        for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 8, 8, 1):\n            for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(16, 2, 8, 32, 32, 8):\n                with T.block(\"C\"):\n                    i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3)\n                    j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3)\n                    k = T.axis.reduce(512, i2_0 * 32 + i2_1)\n                    T.reads(A[i, k], B[k, j])\n                    T.writes(C_global[i, j])\n                    T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                    with T.init():\n                        C_global[i, j] = T.float32(0)\n                    C_global[i, j] = C_global[i, j] + A[i, k] * B[k, j]\n            for ax0, ax1 in T.grid(64, 64):\n                with T.block(\"C_global\"):\n                    v0 = T.axis.spatial(512, i0_1 * 64 + ax0)\n                    v1 = T.axis.spatial(512, i1_0 * 64 + ax1)\n                    T.reads(C_global[v0, v1])\n                    T.writes(C[v0, v1])\n                    C[v0, v1] = C_global[v0, v1]\n\n    @T.prim_func\n    def cpu_matmul_1(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        C: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_global = T.alloc_buffer([512, 512], dtype=\"float32\")\n        for i0_0, i1_0 in T.grid(1, 8):\n            for i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(8, 1, 16, 2, 8, 32, 32, 8):\n                with T.block(\"C\"):\n                    i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3)\n                    j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3)\n                    k = T.axis.reduce(512, i2_0 * 32 + i2_1)\n                    T.reads(A[i, k], B[k, j])\n                    T.writes(C_global[i, j])\n                    T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                    with T.init():\n                        C_global[i, j] = T.float32(0)\n                    C_global[i, j] = C_global[i, j] + A[i, k] * B[k, j]\n            for ax0, ax1 in T.grid(512, 64):\n                with T.block(\"C_global\"):\n                    v0 = T.axis.spatial(512, ax0)\n                    v1 = T.axis.spatial(512, i1_0 * 64 + ax1)\n                    T.reads(C_global[v0, v1])\n                    T.writes(C[v0, v1])\n                    C[v0, v1] = C_global[v0, v1]\n\n    @T.prim_func\n    def cpu_matmul_2(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        C: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0_0, i1_0, i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(\n            1, 8, 8, 1, 16, 2, 8, 32, 32, 8\n        ):\n            with T.block(\"C\"):\n                i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3)\n                j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3)\n                k = T.axis.reduce(512, i2_0 * 32 + i2_1)\n                T.reads(A[i, k], B[k, j])\n                T.writes(C[i, j])\n                T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                with T.init():\n                    C[i, j] = T.float32(0)\n                C[i, j] = C[i, j] + A[i, k] * B[k, j]\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 8, 2, 32]),\n        (\"SamplePerfectTile\", [8, 1, 8, 8]),\n        (\"SamplePerfectTile\", [16, 32]),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 8, 2, 32]),\n        (\"SamplePerfectTile\", [8, 1, 8, 8]),\n        (\"SamplePerfectTile\", [16, 32]),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 8, 2, 32]),\n        (\"SamplePerfectTile\", [8, 1, 8, 8]),\n        (\"SamplePerfectTile\", [16, 32]),\n    ]\n\n    mod = te.create_prim_func(te_workload.matmul(512, 512, 512))\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cpu_matmul_0, cpu_matmul_1, cpu_matmul_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_matmul_relu():\n    @T.prim_func\n    def cpu_matmul_relu_0(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        compute: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([512, 512], dtype=\"float32\")\n        for i0_0, i1_0, i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(\n            256, 4, 1, 4, 64, 1, 32, 8, 2, 1\n        ):\n            with T.block(\"C\"):\n                i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3)\n                j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3)\n                k = T.axis.reduce(512, i2_0 * 8 + i2_1)\n                T.reads(A[i, k], B[k, j])\n                T.writes(C[i, j])\n                T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                with T.init():\n                    C[i, j] = T.float32(0)\n                C[i, j] = C[i, j] + A[i, k] * B[k, j]\n        for i0, i1 in T.grid(512, 512):\n            with T.block(\"compute\"):\n                i0_4, i1_4 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(C[i0_4, i1_4])\n                T.writes(compute[i0_4, i1_4])\n                compute[i0_4, i1_4] = T.max(C[i0_4, i1_4], T.float32(0))\n\n    @T.prim_func\n    def cpu_matmul_relu_1(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        compute: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([512, 512], dtype=\"float32\")\n        for i0_0, i1_0, i0_1, i1_1 in T.grid(256, 4, 1, 4):\n            for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(64, 1, 32, 8, 2, 1):\n                with T.block(\"C\"):\n                    i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3)\n                    j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3)\n                    k = T.axis.reduce(512, i2_0 * 8 + i2_1)\n                    T.reads(A[i, k], B[k, j])\n                    T.writes(C[i, j])\n                    T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                    with T.init():\n                        C[i, j] = T.float32(0)\n                    C[i, j] = C[i, j] + A[i, k] * B[k, j]\n            for ax0, ax1 in T.grid(2, 32):\n                with T.block(\"compute\"):\n                    i0 = T.axis.spatial(512, i0_0 * 2 + ax0)\n                    i1 = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + ax1)\n                    T.reads(C[i0, i1])\n                    T.writes(compute[i0, i1])\n                    compute[i0, i1] = T.max(C[i0, i1], T.float32(0))\n\n    @T.prim_func\n    def cpu_matmul_relu_2(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        compute: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([512, 512], dtype=\"float32\")\n        for i0_0, i1_0 in T.grid(256, 4):\n            for i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(1, 4, 64, 1, 32, 8, 2, 1):\n                with T.block(\"C\"):\n                    i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3)\n                    j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3)\n                    k = T.axis.reduce(512, i2_0 * 8 + i2_1)\n                    T.reads(A[i, k], B[k, j])\n                    T.writes(C[i, j])\n                    T.block_attr({\"meta_schedule.tiling_structure\": \"SSRSRS\"})\n                    with T.init():\n                        C[i, j] = T.float32(0)\n                    C[i, j] = C[i, j] + A[i, k] * B[k, j]\n            for ax0, ax1 in T.grid(2, 128):\n                with T.block(\"compute\"):\n                    i0 = T.axis.spatial(512, i0_0 * 2 + ax0)\n                    i1 = T.axis.spatial(512, i1_0 * 128 + ax1)\n                    T.reads(C[i0, i1])\n                    T.writes(compute[i0, i1])\n                    compute[i0, i1] = T.max(C[i0, i1], T.float32(0))\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [256, 1, 1, 2]),\n        (\"SamplePerfectTile\", [4, 4, 32, 1]),\n        (\"SamplePerfectTile\", [64, 8]),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [256, 1, 1, 2]),\n        (\"SamplePerfectTile\", [4, 4, 32, 1]),\n        (\"SamplePerfectTile\", [64, 8]),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [256, 1, 1, 2]),\n        (\"SamplePerfectTile\", [4, 4, 32, 1]),\n        (\"SamplePerfectTile\", [64, 8]),\n    ]\n    mod = te.create_prim_func(te_workload.matmul_relu(512, 512, 512))\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cpu_matmul_relu_0, cpu_matmul_relu_1, cpu_matmul_relu_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cuda_matmul():\n    @T.prim_func\n    def cuda_matmul_0(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        C: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(128, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(8, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(4, thread=\"threadIdx.x\"):\n                    for i2_0 in T.serial(128):\n                        for ax0_ax1_fused in T.serial(256):\n                            with T.block(\"A_shared\"):\n                                v0 = T.axis.spatial(\n                                    512, i0_0_i1_0_fused // 16 * 64 + ax0_ax1_fused // 4\n                                )\n                                v1 = T.axis.spatial(512, i2_0 * 4 + ax0_ax1_fused % 4)\n                                T.reads(A[v0, v1])\n                                T.writes(A_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 2})\n                                A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(128):\n                            with T.block(\"B_shared\"):\n                                v0 = T.axis.spatial(512, i2_0 * 4 + ax0_ax1_fused // 32)\n                                v1 = T.axis.spatial(\n                                    512, i0_0_i1_0_fused % 16 * 32 + ax0_ax1_fused % 32\n                                )\n                                T.reads(B[v0, v1])\n                                T.writes(B_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 1})\n                                B_shared[v0, v1] = B[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(2, 1, 1, 2, 16, 4):\n                            with T.block(\"C\"):\n                                i = T.axis.spatial(\n                                    512,\n                                    i0_0_i1_0_fused // 16 * 64\n                                    + i0_1_i1_1_fused // 2 * 16\n                                    + i0_3 * 16\n                                    + i0_4,\n                                )\n                                j = T.axis.spatial(\n                                    512,\n                                    i0_0_i1_0_fused % 16 * 32\n                                    + i0_1_i1_1_fused % 2 * 16\n                                    + i0_2_i1_2_fused * 4\n                                    + i1_3 * 4\n                                    + i1_4,\n                                )\n                                k = T.axis.reduce(512, i2_0 * 4 + i2_1 * 2 + i2_2)\n                                T.reads(A_shared[i, k], B_shared[k, j])\n                                T.writes(C_local[i, j])\n                                T.block_attr(\n                                    {\n                                        \"meta_schedule.thread_extent_high_inclusive\": 1024,\n                                        \"meta_schedule.thread_extent_low_inclusive\": 32,\n                                        \"meta_schedule.tiling_structure\": \"SSSRRSRS\",\n                                    }\n                                )\n                                with T.init():\n                                    C_local[i, j] = T.float32(0)\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(16, 4):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(\n                                512, i0_0_i1_0_fused // 16 * 64 + i0_1_i1_1_fused // 2 * 16 + ax0\n                            )\n                            v1 = T.axis.spatial(\n                                512,\n                                i0_0_i1_0_fused % 16 * 32\n                                + i0_1_i1_1_fused % 2 * 16\n                                + i0_2_i1_2_fused * 4\n                                + ax1,\n                            )\n                            T.reads(C_local[v0, v1])\n                            T.writes(C[v0, v1])\n                            C[v0, v1] = C_local[v0, v1]\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [8, 4, 1, 1, 16]),\n        (\"SamplePerfectTile\", [16, 2, 4, 1, 4]),\n        (\"SamplePerfectTile\", [128, 2, 2]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 0),\n    ]\n    mod = te.create_prim_func(te_workload.matmul(512, 512, 512))\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cuda_matmul_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_matmul_relu():\n    @T.prim_func\n    def cuda_matmul_relu_0(\n        A: T.Buffer[(512, 512), \"float32\"],\n        B: T.Buffer[(512, 512), \"float32\"],\n        compute: T.Buffer[(512, 512), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([512, 512], dtype=\"float32\")\n        C_local = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"local\")\n        A_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        B_shared = T.alloc_buffer([512, 512], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(64, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(64, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(8, thread=\"threadIdx.x\"):\n                    for i2_0 in T.serial(8):\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"A_shared\"):\n                                v0 = T.axis.spatial(\n                                    512, i0_0_i1_0_fused // 8 * 64 + ax0_ax1_fused // 64\n                                )\n                                v1 = T.axis.spatial(512, i2_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(A[v0, v1])\n                                T.writes(A_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 2})\n                                A_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"B_shared\"):\n                                v0 = T.axis.spatial(512, i2_0 * 64 + ax0_ax1_fused // 64)\n                                v1 = T.axis.spatial(\n                                    512, i0_0_i1_0_fused % 8 * 64 + ax0_ax1_fused % 64\n                                )\n                                T.reads(B[v0, v1])\n                                T.writes(B_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 4})\n                                B_shared[v0, v1] = B[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(8, 2, 1, 8, 2, 2):\n                            with T.block(\"C\"):\n                                i = T.axis.spatial(\n                                    512,\n                                    i0_0_i1_0_fused // 8 * 64\n                                    + i0_1_i1_1_fused // 8 * 8\n                                    + i0_2_i1_2_fused // 4 * 4\n                                    + i0_3 * 2\n                                    + i0_4,\n                                )\n                                j = T.axis.spatial(\n                                    512,\n                                    i0_0_i1_0_fused % 8 * 64\n                                    + i0_1_i1_1_fused % 8 * 8\n                                    + i0_2_i1_2_fused % 4 * 2\n                                    + i1_3 * 2\n                                    + i1_4,\n                                )\n                                k = T.axis.reduce(512, i2_0 * 64 + i2_1 * 8 + i2_2)\n                                T.reads(A_shared[i, k], B_shared[k, j])\n                                T.writes(C_local[i, j])\n                                T.block_attr(\n                                    {\n                                        \"meta_schedule.thread_extent_high_inclusive\": 1024,\n                                        \"meta_schedule.thread_extent_low_inclusive\": 32,\n                                        \"meta_schedule.tiling_structure\": \"SSSRRSRS\",\n                                    }\n                                )\n                                with T.init():\n                                    C_local[i, j] = T.float32(0)\n                                C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j]\n                    for ax0, ax1 in T.grid(4, 2):\n                        with T.block(\"C_local\"):\n                            v0 = T.axis.spatial(\n                                512,\n                                i0_0_i1_0_fused // 8 * 64\n                                + i0_1_i1_1_fused // 8 * 8\n                                + i0_2_i1_2_fused // 4 * 4\n                                + ax0,\n                            )\n                            v1 = T.axis.spatial(\n                                512,\n                                i0_0_i1_0_fused % 8 * 64\n                                + i0_1_i1_1_fused % 8 * 8\n                                + i0_2_i1_2_fused % 4 * 2\n                                + ax1,\n                            )\n                            T.reads(C_local[v0, v1])\n                            T.writes(C[v0, v1])\n                            C[v0, v1] = C_local[v0, v1]\n        for i0, i1 in T.grid(512, 512):\n            with T.block(\"compute\"):\n                i0_1, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(C[i0_1, i1_1])\n                T.writes(compute[i0_1, i1_1])\n                compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0))\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [8, 8, 2, 2, 2]),\n        (\"SamplePerfectTile\", [8, 8, 4, 1, 2]),\n        (\"SamplePerfectTile\", [8, 8, 8]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n    ]\n    mod = te.create_prim_func(te_workload.matmul_relu(512, 512, 512))\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cuda_matmul_relu_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_sum_with_trivial_block_iter():\n    @T.prim_func\n    def sum_with_trivial_block_iter(\n        A: T.Buffer[(1, 64, 768), \"float32\"],\n        B: T.Buffer[(1, 64, 1), \"float32\"],\n    ) -> None:\n        for i0, i1, i2, i3 in T.grid(1, 64, 1, 768):\n            with T.block(\"sum\"):\n                ax0, ax1, ax2, k2 = T.axis.remap(\"SSSR\", [i0, i1, i2, i3])\n                T.reads(A[ax0, ax1, k2])\n                T.writes(B[ax0, ax1, ax2])\n                with T.init():\n                    B[ax0, ax1, ax2] = T.float32(0)\n                B[ax0, ax1, ax2] = B[ax0, ax1, ax2] + A[ax0, ax1, k2]\n\n    # Expect nothing to happen - the rule is not supposed to be applied in this case\n    mod = sum_with_trivial_block_iter\n    (sch,) = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n    assert not sch.trace.simplified(remove_postproc=True).insts\n\n\ndef test_multi_level_tiling_hexagon():\n    @T.prim_func\n    def cpu_conv2d_nhwc(\n        inputs: T.Buffer[(1, 56, 56, 64), \"float16\"],\n        weight: T.Buffer[(3, 3, 64, 64), \"float16\"],\n        conv2d_nhwc: T.Buffer[(1, 56, 56, 64), \"float16\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        PadInput = T.alloc_buffer([1, 58, 58, 64], dtype=\"float16\")\n        for i0, i1, i2, i3 in T.grid(1, 58, 58, 64):\n            with T.block(\"PadInput\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                    1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57,\n                    inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1],\n                    T.float16(0),\n                    dtype=\"float16\",\n                )\n        for (\n            i0_0,\n            i1_0,\n            i2_0,\n            i3_0,\n            i4_0,\n            i5_0,\n            i6_0,\n            i0_1_1,\n            i1_1_1,\n            i2_1_1,\n            i3_1_1,\n            i4_1,\n            i5_1,\n            i6_1,\n            i0_2,\n            i1_2,\n            i2_2,\n            i3_2,\n        ) in T.grid(1, 1, 2, 1, 3, 3, 16, 1, 14, 2, 1, 1, 1, 4, 1, 4, 14, 64):\n            with T.block(\"conv2d_nhwc\"):\n                n = T.axis.spatial(1, i0_1_1 + i0_2 + i0_0)\n                h = T.axis.spatial(56, i1_0 * 56 + i1_1_1 * 4 + i1_2)\n                w = T.axis.spatial(56, i2_0 * 28 + i2_1_1 * 14 + i2_2)\n                co = T.axis.spatial(64, i3_0 * 64 + i3_1_1 * 64 + i3_2)\n                rh = T.axis.reduce(3, i4_1 + i4_0)\n                rw = T.axis.reduce(3, i5_0 + i5_1)\n                rc = T.axis.reduce(64, i6_0 * 4 + i6_1)\n                T.reads(PadInput[n, h + rh, w + rw, co // 64 * 64 + rc], weight[rh, rw, rc, co])\n                T.writes(conv2d_nhwc[n, h, w, co])\n                T.block_attr({\"meta_schedule.tiling_structure\": \"SRSRS\"})\n                with T.init():\n                    conv2d_nhwc[n, h, w, co] = T.float16(0)\n                conv2d_nhwc[n, h, w, co] = (\n                    conv2d_nhwc[n, h, w, co]\n                    + PadInput[n, h + rh, w + rw, co // 64 * 64 + rc] * weight[rh, rw, rc, co]\n                )\n\n    target_hexagon = target.hexagon(\"v69\", num_cores=4)\n\n    I = 64\n    O = 64\n    H = 56\n    W = 56\n\n    mod = te.create_prim_func(\n        te_workload.conv2d_nhwc(1, H, W, I, O, 3, 1, 1, 1, in_dtype=\"float16\", out_dtype=\"float16\")\n    )\n\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(target_hexagon, host=target_hexagon),\n        types=None,\n        sch_rules=[\n            ms.schedule_rule.MultiLevelTilingWideVector(\n                structure=\"SRSRS\",\n                vector_length_in_bits=1024,\n                max_innermost_factor=64,\n                reuse_read=None,\n                reuse_write=None,\n            )\n        ],\n    )\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 14, 4]),\n        (\"SamplePerfectTile\", [2, 2, 14]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [16, 4]),\n    ]\n\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cpu_conv2d_nhwc],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cache_read_specify_consumer():\n    A, B, C = te_workload.matmul(512, 512, 512)\n    mod = te.create_prim_func([A, B, C + A])\n\n    space = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"nvidia/geforce-rtx-3080\"),\n        types=ms.schedule_rule.MultiLevelTiling,\n    )\n\n    residual_block = \"\"\"\n        for i0, i1 in T.grid(512, 512):\n            with T.block(\"T_add\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(C[ax0, ax1], A[ax0, ax1])\n                T.writes(T_add[ax0, ax1])\n                T_add[ax0, ax1] = C[ax0, ax1] + A[ax0, ax1]\n    \"\"\"\n\n    assert residual_block in space[0].mod.script()\n\n\nif __name__ == \"__main__\":\n    test_cpu_matmul()\n    test_cpu_matmul_relu()\n    test_cuda_matmul()\n    test_cuda_matmul_relu()\n    test_cuda_sum_with_trivial_block_iter()\n    test_multi_level_tiling_hexagon()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_mlt_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nfrom tvm import meta_schedule as ms\nfrom tvm import te\nfrom tvm.ir import assert_structural_equal\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir.tensor_intrin.arm_cpu import DP4A_INTRIN\nfrom tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN\n\n\ndef test_vnni_conv2d_nchwc():\n    @T.prim_func\n    def conv2d_nchwc(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 16, 56, 56, 16, 1, 1, 4, 4, 4):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                (\n                    n,\n                    oc_chunk,\n                    oh,\n                    ow,\n                    oc_block,\n                    kh,\n                    kw,\n                    ic_outer,\n                    ic_f_inner,\n                    ic_s_inner,\n                ) = T.axis.remap(\"SSSSSRRRRR\", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9])\n                T.reads(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                )\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[\n                    n, oc_chunk, oh, ow, oc_block\n                ] + T.cast(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\"\n                ) * T.cast(\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                    \"int32\",\n                )\n\n    # fmt: off\n    @T.prim_func\n    def vnni_conv2d_nchwc_0(placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        conv2d_NCHWc_int8_global = T.alloc_buffer([1, 16, 56, 56, 16], dtype=\"int32\")\n        for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1 in T.grid(1, 8, 28, 56, 1, 1, 2, 1, 1, 1):\n            for i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1):\n                with T.block(\"conv2d_NCHWc_int8_o\"):\n                    n = T.axis.spatial(1, 0)\n                    oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3)\n                    oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3)\n                    ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2)\n                    oc_block_o = T.axis.spatial(1, 0)\n                    kh = T.axis.reduce(1, 0)\n                    kw = T.axis.reduce(1, 0)\n                    ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1)\n                    ic_f_inner = T.axis.reduce(4, i8_0 + i8_1)\n                    ic_s_inner_o = T.axis.reduce(1, 0)\n                    T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4])\n                    T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, 0 : 16])\n                    T.block_attr({\"meta_schedule.auto_tensorize\":\"dot_16x4_vnni\"})\n                    with T.init():\n                        for i4_1 in T.serial(16):\n                            with T.block(\"conv2d_NCHWc_int8_init\"):\n                                oc_block_i_init = T.axis.spatial(16, i4_1)\n                                T.reads()\n                                T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init])\n                                conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init] = 0\n                    for i4_1, i9_1 in T.grid(16, 4):\n                        with T.block(\"conv2d_NCHWc_int8\"):\n                            oc_block_i, ic_s_inner_i = T.axis.remap(\"SR\", [i4_1, i9_1])\n                            T.reads(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i])\n                            T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], \"int32\") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], \"int32\")\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 1, 2, 1, 16):\n                with T.block(\"conv2d_NCHWc_int8_global\"):\n                    v0 = T.axis.spatial(1, ax0)\n                    v1 = T.axis.spatial(16, i1_0 * 2 + i1_1 + ax1)\n                    v2 = T.axis.spatial(56, i2_0 * 2 + ax2)\n                    v3 = T.axis.spatial(56, i3_0 + ax3)\n                    v4 = T.axis.spatial(16, ax4)\n                    T.reads(conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4])\n                    T.writes(conv2d_NCHWc_int8[v0, v1, v2, v3, v4])\n                    conv2d_NCHWc_int8[v0, v1, v2, v3, v4] = conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4]\n\n    @T.prim_func\n    def vnni_conv2d_nchwc_1(placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        conv2d_NCHWc_int8_global = T.alloc_buffer([1, 16, 56, 56, 16], dtype=\"int32\")\n        for i0_0, i1_0, i2_0, i3_0, i4_0_0 in T.grid(1, 8, 28, 56, 1):\n            for i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1):\n                with T.block(\"conv2d_NCHWc_int8_o\"):\n                    n = T.axis.spatial(1, 0)\n                    oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3)\n                    oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3)\n                    ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2)\n                    oc_block_o = T.axis.spatial(1, 0)\n                    kh = T.axis.reduce(1, 0)\n                    kw = T.axis.reduce(1, 0)\n                    ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1)\n                    ic_f_inner = T.axis.reduce(4, i8_0 + i8_1)\n                    ic_s_inner_o = T.axis.reduce(1, 0)\n                    T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4])\n                    T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, 0 : 16])\n                    T.block_attr({\"meta_schedule.auto_tensorize\":\"dot_16x4_vnni\"})\n                    with T.init():\n                        for i4_1 in T.serial(16):\n                            with T.block(\"conv2d_NCHWc_int8_init\"):\n                                oc_block_i_init = T.axis.spatial(16, i4_1)\n                                T.reads()\n                                T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init])\n                                conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init] = 0\n                    for i4_1, i9_1 in T.grid(16, 4):\n                        with T.block(\"conv2d_NCHWc_int8\"):\n                            oc_block_i, ic_s_inner_i = T.axis.remap(\"SR\", [i4_1, i9_1])\n                            T.reads(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i])\n                            T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], \"int32\") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], \"int32\")\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 2, 2, 1, 16):\n                with T.block(\"conv2d_NCHWc_int8_global\"):\n                    v0 = T.axis.spatial(1, ax0)\n                    v1 = T.axis.spatial(16, i1_0 * 2 + ax1)\n                    v2 = T.axis.spatial(56, i2_0 * 2 + ax2)\n                    v3 = T.axis.spatial(56, i3_0 + ax3)\n                    v4 = T.axis.spatial(16, ax4)\n                    T.reads(conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4])\n                    T.writes(conv2d_NCHWc_int8[v0, v1, v2, v3, v4])\n                    conv2d_NCHWc_int8[v0, v1, v2, v3, v4] = conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4]\n\n    @T.prim_func\n    def vnni_conv2d_nchwc_2(placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 8, 28, 56, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1):\n            with T.block(\"conv2d_NCHWc_int8_o\"):\n                n = T.axis.spatial(1, 0)\n                oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3)\n                oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3)\n                ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2)\n                oc_block_o = T.axis.spatial(1, 0)\n                kh = T.axis.reduce(1, 0)\n                kw = T.axis.reduce(1, 0)\n                ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1)\n                ic_f_inner = T.axis.reduce(4, i8_0 + i8_1)\n                ic_s_inner_o = T.axis.reduce(1, 0)\n                T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4])\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16])\n                T.block_attr({\"meta_schedule.auto_tensorize\":\"dot_16x4_vnni\"})\n                with T.init():\n                    for i4_1 in T.serial(16):\n                        with T.block(\"conv2d_NCHWc_int8_init\"):\n                            oc_block_i_init = T.axis.spatial(16, i4_1)\n                            T.reads()\n                            T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init])\n                            conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init] = 0\n                for i4_1, i9_1 in T.grid(16, 4):\n                    with T.block(\"conv2d_NCHWc_int8\"):\n                        oc_block_i, ic_s_inner_i = T.axis.remap(\"SR\", [i4_1, i9_1])\n                        T.reads(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i])\n                        T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], \"int32\") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], \"int32\")\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [8, 2, 1, 1]),\n        (\"SamplePerfectTile\", [28, 1, 2, 1]),\n        (\"SamplePerfectTile\", [56, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 4]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [8, 2, 1, 1]),\n        (\"SamplePerfectTile\", [28, 1, 2, 1]),\n        (\"SamplePerfectTile\", [56, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 4]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [8, 2, 1, 1]),\n        (\"SamplePerfectTile\", [28, 1, 2, 1]),\n        (\"SamplePerfectTile\", [56, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n        (\"SamplePerfectTile\", [1, 4]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 1]),\n    ]\n\n    mod = conv2d_nchwc\n    target = Target(\"llvm -mcpu=cascadelake -num-cores=4\")\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(target),\n        types=None,\n        sch_rules=[\n            ms.schedule_rule.MultiLevelTilingWithIntrin(\n                VNNI_INTRIN,\n                structure=\"SSRSRS\",\n                tile_binds=None,\n                max_innermost_factor=64,\n                vector_load_lens=None,\n                reuse_read=None,\n                reuse_write=ms.schedule_rule.ReuseType(req=\"may\", levels=[1, 2], scope=\"global\"),\n            ),\n        ],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[vnni_conv2d_nchwc_0, vnni_conv2d_nchwc_1, vnni_conv2d_nchwc_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef _check_dp4a_dense(m, n, k, in_dtype, out_dtype, expected_mods, expected_decisions):\n    def _dense(m, n, k, in_dtype, out_dtype):\n        X = te.placeholder((m, k), name=\"X\", dtype=in_dtype)\n        W = te.placeholder((n, k), name=\"W\", dtype=in_dtype)\n        ak = te.reduce_axis((0, k), name=\"k\")\n        matmul = te.compute(\n            (m, n),\n            lambda i, j: te.sum(\n                X[i, ak].astype(out_dtype) * W[j, ak].astype(out_dtype),\n                axis=ak,\n            ),\n            name=\"compute\",\n        )\n        return te.create_prim_func([X, W, matmul])\n\n    mod = _dense(m, n, k, in_dtype, out_dtype)\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            ms.schedule_rule.MultiLevelTilingWithIntrin(\n                DP4A_INTRIN,\n                structure=\"SSSRRSRS\",\n                tile_binds=[\"blockIdx.x\", \"vthread.x\", \"threadIdx.x\"],\n                max_innermost_factor=64,\n                vector_load_lens=[1, 2, 3, 4],\n                reuse_read=ms.schedule_rule.ReuseType(req=\"must\", levels=[4], scope=\"shared\"),\n                reuse_write=ms.schedule_rule.ReuseType(req=\"must\", levels=[3], scope=\"local\"),\n            )\n        ],\n    )\n    if expected_mods is None:\n        assert expected_decisions is None\n        assert len(actual) == 1\n        assert_structural_equal(mod, actual[0].mod[\"main\"])\n    else:\n        check_sketches(mod, actual, expected_mods, expected_decisions)\n\n\ndef test_dp4a_dense():\n    @T.prim_func\n    def dp4a_dense_0(\n        X: T.Buffer[(128, 128), \"int8\"],\n        W: T.Buffer[(128, 128), \"int8\"],\n        compute: T.Buffer[(128, 128), \"int32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        compute_local = T.alloc_buffer([128, 128], dtype=\"int32\", scope=\"local\")\n        X_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        W_shared = T.alloc_buffer([128, 128], dtype=\"int8\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for i0_1_i1_1_fused in T.thread_binding(512, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(2, thread=\"threadIdx.x\"):\n                    for i2_0_0 in T.serial(1):\n                        for ax0_ax1_fused in T.serial(16384):\n                            with T.block(\"X_shared\"):\n                                v0 = T.axis.spatial(128, ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(X[v0, v1])\n                                T.writes(X_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 1})\n                                X_shared[v0, v1] = X[v0, v1]\n                        for ax0_ax1_fused in T.serial(16384):\n                            with T.block(\"W_shared\"):\n                                v0 = T.axis.spatial(128, ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(W[v0, v1])\n                                T.writes(W_shared[v0, v1])\n                                T.block_attr({\"meta_schedule.cooperative_fetch\": 1})\n                                W_shared[v0, v1] = W[v0, v1]\n                        for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(1, 2, 4, 32, 2, 1):\n                            with T.block(\"compute_o\"):\n                                i = T.axis.spatial(\n                                    128,\n                                    i0_1_i1_1_fused // 32 * 8\n                                    + i0_2_i1_2_fused * 4\n                                    + i0_3 * 2\n                                    + i0_4,\n                                )\n                                j = T.axis.spatial(128, i1_4 + i0_1_i1_1_fused % 32 * 4 + i1_3)\n                                k_o = T.axis.reduce(32, i2_0_0 * 32 + i2_0_1 * 32 + i2_0_2)\n                                T.reads(\n                                    X_shared[i, k_o * 4 : k_o * 4 + 4],\n                                    W_shared[j, k_o * 4 : k_o * 4 + 4],\n                                )\n                                T.writes(compute_local[i, j])\n                                T.block_attr({\"meta_schedule.auto_tensorize\": \"dp4a\"})\n                                with T.init():\n                                    with T.block(\"compute_init\"):\n                                        T.reads()\n                                        T.writes(compute_local[i, j])\n                                        compute_local[i, j] = 0\n                                for i2_1 in T.serial(4):\n                                    with T.block(\"compute\"):\n                                        k_i = T.axis.reduce(4, i2_1)\n                                        T.reads(\n                                            compute_local[i, j],\n                                            X_shared[i, k_o * 4 + k_i],\n                                            W_shared[j, k_o * 4 + k_i],\n                                        )\n                                        T.writes(compute_local[i, j])\n                                        T.block_attr({\"meta_schedule.tiling_structure\": \"SSSRRSRS\"})\n                                        compute_local[i, j] = compute_local[i, j] + T.cast(\n                                            X_shared[i, k_o * 4 + k_i], \"int32\"\n                                        ) * T.cast(W_shared[j, k_o * 4 + k_i], \"int32\")\n                    for ax0, ax1 in T.grid(4, 4):\n                        with T.block(\"compute_local\"):\n                            v0 = T.axis.spatial(\n                                128, i0_1_i1_1_fused // 32 * 8 + i0_2_i1_2_fused * 4 + ax0\n                            )\n                            v1 = T.axis.spatial(128, i0_1_i1_1_fused % 32 * 4 + ax1)\n                            T.reads(compute_local[v0, v1])\n                            T.writes(compute[v0, v1])\n                            compute[v0, v1] = compute_local[v0, v1]\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 16, 2, 2, 2]),\n        (\"SamplePerfectTile\", [1, 32, 1, 4, 1]),\n        (\"SamplePerfectTile\", [1, 1, 32]),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 0),\n    ]\n    _check_dp4a_dense(\n        m=128,\n        n=128,\n        k=128,\n        in_dtype=\"int8\",\n        out_dtype=\"int32\",\n        expected_mods=[dp4a_dense_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_dp4a_dense_no_tensorize_1():\n    _check_dp4a_dense(\n        m=128,\n        n=128,\n        k=128,\n        in_dtype=\"float32\",\n        out_dtype=\"float32\",\n        expected_mods=None,\n        expected_decisions=None,\n    )\n\n\ndef test_dp4a_dense_no_tensorize_2():\n    _check_dp4a_dense(\n        m=127,\n        n=127,\n        k=127,\n        in_dtype=\"int8\",\n        out_dtype=\"int32\",\n        expected_mods=None,\n        expected_decisions=None,\n    )\n\n\nif __name__ == \"__main__\":\n    test_vnni_conv2d_nchwc()\n    test_dp4a_dense()\n    test_dp4a_dense_no_tensorize_1()\n    test_dp4a_dense_no_tensorize_2()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_mlt_tc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import te\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n    get_rules,\n)\nfrom tvm.script import tir as T\nfrom tvm.tir.tensor_intrin.cuda import get_wmma_intrin_group\n\n\ndef multi_level_tiling_tensor_core(\n    *,\n    write_reuse_scope=\"shared\",\n    in_dtype=\"float16\",\n    out_dtype=\"float32\",\n    trans_b=False,\n    use_software_pipeline=False,\n) -> ms.schedule_rule.ScheduleRule:\n    assert write_reuse_scope in [\"shared\", \"global\"]\n    if not isinstance(in_dtype, list):\n        in_dtype = [in_dtype]\n    if not isinstance(out_dtype, list):\n        out_dtype = [out_dtype]\n    if not isinstance(trans_b, list):\n        trans_b = [trans_b]\n    return ms.schedule_rule.MultiLevelTilingTensorCore(\n        intrin_groups=[\n            get_wmma_intrin_group(write_reuse_scope, _in_dtype, _out_dtype, _trans_b)\n            for _in_dtype in in_dtype\n            for _out_dtype in out_dtype\n            for _trans_b in trans_b\n        ],\n        structure=\"SSSRRSRS\",\n        tile_binds=[\"blockIdx.y\", \"blockIdx.x\", \"threadIdx.y\"],\n        max_innermost_factor=4,  # 64 // tensor intrin size\n        vector_load_lens=[1, 2, 3, 4, 8, 16],\n        reuse_read=ms.schedule_rule.ReuseType(\n            req=\"must\",\n            levels=[4],\n            scope=\"shared\",\n        ),\n        reuse_write=ms.schedule_rule.ReuseType(\n            req=\"must\" if write_reuse_scope == \"shared\" else \"no\",\n            levels=[2],\n            scope=write_reuse_scope,\n        ),\n        use_software_pipeline=use_software_pipeline,\n    )\n\n\ndef test_matmul_relu():\n    # fmt: off\n    @T.prim_func\n    def matmul_relu_0(A: T.Buffer[(128, 128), \"float16\"], B: T.Buffer[(128, 128), \"float16\"], compute: T.Buffer[(128, 128), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        C_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n        A_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        B_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(8, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(1):\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"A_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(A[v0, v1])\n                                T.writes(A_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":8})\n                                A_reindex_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"B_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_ax1_fused // 32)\n                                v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32)\n                                T.reads(B[v0, v1])\n                                T.writes(B_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":1})\n                                B_reindex_shared[v0, v1] = B[v0, v1]\n                        for ax2_0_1 in T.serial(4):\n                            for ax0_0, ax1_0 in T.grid(2, 2):\n                                with T.block(\"A_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax2_0_1 * 2 + ax1_0)\n                                    T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"A_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(2, 1):\n                                with T.block(\"B_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o = T.axis.spatial(8, ax2_0_1 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused)\n                                    T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"B_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 2, 2, 1):\n                                with T.block(\"C_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0_3 * 2 + ax0_0_4)\n                                    v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused + ax1_0_3)\n                                    v2_o = T.axis.reduce(8, ax2_0_0 * 8 + ax2_0_1 * 2 + ax2_0_2)\n                                    T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"C_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"C\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(2, 1):\n                        with T.block(\"C_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0)\n                            v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused)\n                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.serial(1024):\n                    with T.block(\"C_reindex_shared\"):\n                        v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32)\n                        v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32)\n                        T.reads(C_reindex_shared[v0, v1])\n                        T.writes(compute[v0, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                        compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0))\n\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [4, 1, 1, 1, 2]),\n        (\"SamplePerfectTile\", [2, 2, 2, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 0),\n    ]\n\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(\n            n=128,\n            m=128,\n            k=128,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            multi_level_tiling_tensor_core(),\n        ]\n        + get_rules(kind=\"cuda\", types=ms.schedule_rule.AutoInline),\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[matmul_relu_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_matmul_relu_with_fallback():\n    # fmt: off\n    @T.prim_func\n    def matmul_relu_fallback_0(A: T.Buffer[(128, 128), \"float16\"], B: T.Buffer[(128, 128), \"float16\"], compute: T.Buffer[(128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n        A_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        B_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(2, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(2):\n                        for ax0_ax1_fused in T.serial(2048):\n                            with T.block(\"A_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused // 64)\n                                v1 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(A[v0, v1])\n                                T.writes(A_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":4})\n                                A_reindex_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(8192):\n                            with T.block(\"B_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(B[v0, v1])\n                                T.writes(B_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":2})\n                                B_reindex_shared[v0, v1] = B[v0, v1]\n                        for ax2_0_1 in T.serial(1):\n                            for ax0_0, ax1_0 in T.grid(2, 4):\n                                with T.block(\"A_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax2_0_0 * 4 + ax1_0)\n                                    T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"A_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(4, 4):\n                                with T.block(\"B_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o = T.axis.spatial(8, ax2_0_0 * 4 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0)\n                                    T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"B_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 4, 2, 4):\n                                with T.block(\"C_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_3 * 2 + ax0_0_4)\n                                    v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0_3 * 4 + ax1_0_4)\n                                    v2_o = T.axis.reduce(8, ax2_0_0 * 4 + ax2_0_1 * 4 + ax2_0_2)\n                                    T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"C_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"C\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(2, 4):\n                        with T.block(\"C_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0)\n                            v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0)\n                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.serial(4096):\n                    with T.block(\"C_reindex_shared\"):\n                        v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused // 128)\n                        v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                        T.reads(C_reindex_shared[v0, v1])\n                        T.writes(compute[v0, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                        compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0))\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [2, 2, 1, 1, 2]),\n        (\"SamplePerfectTile\", [1, 1, 2, 1, 4]),\n        (\"SamplePerfectTile\", [2, 1, 4]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n    ]\n\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(\n            n=128,\n            m=128,\n            k=128,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            multi_level_tiling_tensor_core(),\n        ]\n        + get_rules(\n            \"cuda\",\n            (\n                ms.schedule_rule.MultiLevelTiling,\n                ms.schedule_rule.AutoInline,\n            ),\n        ),\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[matmul_relu_fallback_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_conv2d():\n    # fmt: off\n    @T.prim_func\n    def conv2d_0(inputs: T.Buffer[(1, 16, 16, 32), \"float16\"], weight: T.Buffer[(3, 3, 32, 32), \"float16\"], conv2d_nhwc: T.Buffer[(1, 16, 16, 32), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        PadInput = T.alloc_buffer([1, 18, 18, 32], dtype=\"float16\")\n        conv2d_nhwc_reindex_shared = T.alloc_buffer([256, 32], dtype=\"float32\", scope=\"shared\")\n        conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([256, 32], dtype=\"float32\", scope=\"wmma.accumulator\")\n        PadInput_reindex_shared = T.alloc_buffer([256, 288], dtype=\"float16\", scope=\"shared\")\n        weight_reindex_shared = T.alloc_buffer([288, 32], dtype=\"float16\", scope=\"shared\")\n        PadInput_reindex_shared_wmma_matrix_a = T.alloc_buffer([256, 288], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        weight_reindex_shared_wmma_matrix_b = T.alloc_buffer([288, 32], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for i0, i1, i2, i3 in T.grid(1, 18, 18, 32):\n            with T.block(\"PadInput\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 17 and 1 <= i2_1 and i2_1 < 17, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float16(0), dtype=\"float16\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(2, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(1, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(1):\n                        for ax0_ax1_fused in T.serial(4608):\n                            with T.block(\"PadInput_reindex_shared\"):\n                                v0 = T.axis.spatial(256, ax0_0_1_ax1_0_1_fused * 16 + ax0_ax1_fused // 288)\n                                v1 = T.axis.spatial(288, ax0_ax1_fused % 288)\n                                T.reads(PadInput[v0 // 256, v1 // 96 + v0 // 16, v1 % 96 // 32 + v0 % 16, v1 % 32])\n                                T.writes(PadInput_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":2})\n                                PadInput_reindex_shared[v0, v1] = PadInput[v0 // 256, v1 // 96 + v0 // 16, v1 % 96 // 32 + v0 % 16, v1 % 32]\n                        for ax0_ax1_fused in T.serial(4608):\n                            with T.block(\"weight_reindex_shared\"):\n                                v0 = T.axis.spatial(288, ax0_ax1_fused // 16)\n                                v1 = T.axis.spatial(32, ax0_0_0_ax1_0_0_fused * 16 + ax0_ax1_fused % 16)\n                                T.reads(weight[v0 // 96, v0 % 96 // 32, v0 % 32, v1])\n                                T.writes(weight_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":8})\n                                weight_reindex_shared[v0, v1] = weight[v0 // 96, v0 % 96 // 32, v0 % 32, v1]\n                        for ax2_0_1 in T.serial(18):\n                            for ax0_0, ax1_0 in T.grid(1, 1):\n                                with T.block(\"PadInput_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o, v1_o = T.axis.remap(\"SS\", [ax0_0_1_ax1_0_1_fused, ax2_0_1])\n                                    T.reads(PadInput_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"PadInput_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(1, 1):\n                                with T.block(\"weight_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o, v1_o = T.axis.remap(\"SS\", [ax2_0_1, ax0_0_0_ax1_0_0_fused])\n                                    T.reads(weight_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(weight_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"weight_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(weight_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(weight_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            weight_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = weight_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 1, 1, 1):\n                                with T.block(\"conv2d_nhwc_o\"):\n                                    v0_o = T.axis.spatial(16, ax0_0_4 + ax0_0_1_ax1_0_1_fused + ax0_0_3)\n                                    v1_o = T.axis.spatial(2, ax0_0_0_ax1_0_0_fused + ax1_0_3 + ax1_0_4)\n                                    v2_o = T.axis.reduce(18, ax2_0_0 * 18 + ax2_0_1 + ax2_0_2)\n                                    T.reads(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], weight_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"conv2d_nhwc_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"conv2d_nhwc\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], weight_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(weight_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(1, 1):\n                        with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\"):\n                            v0_o, v1_o = T.axis.remap(\"SS\", [ax0_0_1_ax1_0_1_fused, ax0_0_0_ax1_0_0_fused])\n                            T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.serial(256):\n                    with T.block(\"conv2d_nhwc_reindex_shared\"):\n                        v0 = T.axis.spatial(256, ax0_0_1_ax1_0_1_fused * 16 + ax0_ax1_fused // 16)\n                        v1 = T.axis.spatial(32, ax0_0_0_ax1_0_0_fused * 16 +  ax0_ax1_fused % 16)\n                        T.reads(conv2d_nhwc_reindex_shared[v0, v1])\n                        T.writes(conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                        conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1] = conv2d_nhwc_reindex_shared[v0, v1]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 16, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 18, 1]),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n    ]\n    mod = te.create_prim_func(\n        te_workload.conv2d_nhwc(\n            N=1,\n            H=16,\n            W=16,\n            CI=32,\n            CO=32,\n            kernel_size=3,\n            stride=1,\n            padding=1,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            multi_level_tiling_tensor_core(),\n        ],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[conv2d_0],\n        expected_decisions=[decision_0],\n    )\n\n    # Test adding inapplicable tensor intrinsics doesn't change the search space\n    # This test case uses the same workload, decision and the expected sketch as above\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            multi_level_tiling_tensor_core(\n                in_dtype=\"float16\",\n                out_dtype=[\"float16\", \"float32\"],\n            ),\n        ],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[conv2d_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_matmul_relu_pipeline():\n    # fmt: off\n    @T.prim_func\n    def matmul_relu_pipeline_0(A: T.Buffer[(128, 128), \"float16\"], B: T.Buffer[(128, 128), \"float16\"], compute: T.Buffer[(128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([128, 128], dtype=\"float32\")\n        C_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n        A_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        B_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(1, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(1, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(4, annotations={\"software_pipeline_order\":[0, 3, 1, 4, 5, 2, 6], \"software_pipeline_stage\":[0, 0, 0, 0, 0, 1, 1]}):\n                        for ax0_ax1_fused in T.serial(1024):\n                            with T.block(\"A_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused // 4 * 32 + ax0_ax1_fused // 32)\n                                v1 = T.axis.spatial(128, ax2_0_0 * 32 + ax0_ax1_fused % 32)\n                                T.reads(A[v0, v1])\n                                T.writes(A_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"double_buffer_scope\":0, \"meta_schedule.cooperative_fetch\":4, \"tir.manifest_shared_memory_local_stage\":1})\n                                A_reindex_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(1024):\n                            with T.block(\"B_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax2_0_0 * 32 + ax0_ax1_fused // 32)\n                                v1 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused % 4 * 32 + ax0_ax1_fused % 32)\n                                T.reads(B[v0, v1])\n                                T.writes(B_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"double_buffer_scope\":0, \"meta_schedule.cooperative_fetch\":2, \"tir.manifest_shared_memory_local_stage\":1})\n                                B_reindex_shared[v0, v1] = B[v0, v1]\n                        for ax2_0_1 in T.serial(2, annotations={\"software_pipeline_order\":[0, 1, 2], \"software_pipeline_stage\":[0, 0, 1]}):\n                            for ax0_0, ax1_0 in T.grid(2, 1):\n                                with T.block(\"A_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax2_0_0 * 2 + ax2_0_1)\n                                    T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"A_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(1, 2):\n                                with T.block(\"B_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o = T.axis.spatial(8, ax2_0_0 * 2 + ax2_0_1)\n                                    v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0)\n                                    T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"B_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 1, 2, 2):\n                                with T.block(\"C_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0_3 * 2 + ax0_0_4)\n                                    v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0_3 * 2 + ax1_0_4)\n                                    v2_o = T.axis.reduce(8, ax2_0_0 * 2 + ax2_0_1 + ax2_0_2)\n                                    T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"C_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"C\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(2, 2):\n                        with T.block(\"C_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0)\n                            v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0)\n                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.grid(1024):\n                    with T.block(\"C_reindex_shared\"):\n                        v0 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused // 4 * 32 + ax0_ax1_fused // 32)\n                        v1 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused % 4 * 32 + ax0_ax1_fused % 32)\n                        T.reads(C_reindex_shared[v0, v1])\n                        T.writes(C[v0, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                        C[v0, v1] = C_reindex_shared[v0, v1]\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"compute\"):\n                i0_1, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(C[i0_1, i1_1])\n                T.writes(compute[i0_1, i1_1])\n                compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0))\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 4, 1, 1, 2]),\n        (\"SamplePerfectTile\", [1, 4, 1, 1, 2]),\n        (\"SamplePerfectTile\", [4, 2, 1]),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n    ]\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(\n            n=128,\n            m=128,\n            k=128,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[\n            multi_level_tiling_tensor_core(\n                use_software_pipeline=True,\n            ),\n        ],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[matmul_relu_pipeline_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_matmul_relu_global():\n    # fmt: off\n    @T.prim_func\n    def matmul_relu_global_0(A: T.Buffer[(128, 128), \"float16\"], B: T.Buffer[(128, 128), \"float16\"], compute: T.Buffer[(128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C = T.alloc_buffer([128, 128], dtype=\"float32\")\n        C_reindex_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n        A_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        B_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(1, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(16, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(2):\n                        for ax0_ax1_fused in T.serial(8192):\n                            with T.block(\"A_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_ax1_fused // 64)\n                                v1 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused % 64)\n                                T.reads(A[v0, v1])\n                                T.writes(A_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":1})\n                                A_reindex_shared[v0, v1] = A[v0, v1]\n                        for ax0_ax1_fused in T.serial(8192):\n                            with T.block(\"B_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(B[v0, v1])\n                                T.writes(B_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":1})\n                                B_reindex_shared[v0, v1] = B[v0, v1]\n                        for ax2_0_1 in T.serial(2):\n                            for ax0_0, ax1_0 in T.grid(1, 2):\n                                with T.block(\"A_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2)\n                                    v1_o = T.axis.spatial(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax1_0)\n                                    T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"A_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(2, 4):\n                                with T.block(\"B_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o = T.axis.spatial(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0)\n                                    T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"B_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 4, 2, 1, 1):\n                                with T.block(\"C_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2 + ax0_0_3 + ax0_0_4)\n                                    v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0_3)\n                                    v2_o = T.axis.reduce(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax2_0_2)\n                                    T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(C_reindex_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"C_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(C_reindex_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                C_reindex_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"C\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(1, 4):\n                        with T.block(\"C_reindex_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2)\n                            v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0)\n                            T.reads(C_reindex_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(C[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_global\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_reindex_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(C[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    C[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"compute\"):\n                i0_1, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(C[i0_1, i1_1])\n                T.writes(compute[i0_1, i1_1])\n                compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0))\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 8, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 2, 4, 1]),\n        (\"SamplePerfectTile\", [2, 2, 2]),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 0),\n    ]\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(\n            n=128,\n            m=128,\n            k=128,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope=\"global\")]\n        + get_rules(\"cuda\", ms.schedule_rule.AutoInline),\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[matmul_relu_global_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_matmul_relu_non_tensorizable():\n    # expected to do nothing on non-tensorizable workloads\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(  # dtype doesn't match tensor intrin\n            n=128,\n            m=128,\n            k=128,\n        )\n    )\n    (sch,) = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope=\"global\")]\n        + get_rules(\"cuda\", ms.schedule_rule.AutoInline),\n    )\n    tvm.ir.assert_structural_equal(mod, sch.mod[\"main\"])\n\n\ndef test_padded_matmul_relu():\n    # fmt: off\n    @T.prim_func\n    def padded_matmul_relu_0(A: T.Buffer[(127, 127), \"float16\"], B: T.Buffer[(127, 127), \"float16\"], compute: T.Buffer[(127, 127), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        C_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n        A_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        B_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"shared\")\n        A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax0_0_0_ax1_0_0_fused in T.thread_binding(8, thread=\"blockIdx.y\"):\n            for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for ax2_0_0 in T.serial(1):\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"A_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 128)\n                                v1 = T.axis.spatial(128, ax0_ax1_fused % 128)\n                                T.reads(A[v0, v1])\n                                T.writes(A_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":8})\n                                A_reindex_shared[v0, v1] = T.if_then_else(v0 < 127 and v1 < 127, A[v0, v1], T.float16(0), dtype=\"float16\")\n                        for ax0_ax1_fused in T.serial(4096):\n                            with T.block(\"B_reindex_shared\"):\n                                v0 = T.axis.spatial(128, ax0_ax1_fused // 32)\n                                v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32)\n                                T.reads(B[v0, v1])\n                                T.writes(B_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":1})\n                                B_reindex_shared[v0, v1] = T.if_then_else(v0 < 127 and v1 < 127, B[v0, v1], T.float16(0), dtype=\"float16\")\n                        for ax2_0_1 in T.serial(4):\n                            for ax0_0, ax1_0 in T.grid(2, 2):\n                                with T.block(\"A_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax2_0_1 * 2 + ax1_0)\n                                    T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"A_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0, ax1_0 in T.grid(2, 1):\n                                with T.block(\"B_reindex_shared_wmma.matrix_b_o\"):\n                                    v0_o = T.axis.spatial(8, ax2_0_1 * 2 + ax0_0)\n                                    v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused)\n                                    T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax0_1, ax1_1 in T.grid(16, 16):\n                                        with T.block(\"B_reindex_shared_wmma.matrix_b\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                            T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 2, 2, 1):\n                                with T.block(\"C_o\"):\n                                    v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0_3 * 2 + ax0_0_4)\n                                    v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused + ax1_0_3)\n                                    v2_o = T.axis.reduce(8, ax2_0_0 * 8 + ax2_0_1 * 2 + ax2_0_2)\n                                    T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax0_1, ax1_1 in T.grid(16, 16):\n                                            with T.block(\"C_init\"):\n                                                v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                                T.reads()\n                                                T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                                C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                                    for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                                        with T.block(\"C\"):\n                                            v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                            T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(2, 1):\n                        with T.block(\"C_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0)\n                            v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused)\n                            T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.serial(1024):\n                    with T.block(\"C_reindex_shared\"):\n                        T.where(ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32 < 127 and ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32 < 127)\n                        v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32)\n                        v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32)\n                        T.reads(C_reindex_shared[v0, v1])\n                        T.writes(compute[v0, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                        compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0))\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [4, 1, 1, 1, 2]),\n        (\"SamplePerfectTile\", [2, 2, 2, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 0),\n    ]\n\n    mod = te.create_prim_func(\n        te_workload.matmul_relu(\n            n=127,\n            m=127,\n            k=127,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope=\"shared\")]\n        + get_rules(\"cuda\", ms.schedule_rule.AutoInline),\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[padded_matmul_relu_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_conv_1x1():\n    # fmt: off\n    @T.prim_func\n    def conv2d_1x1_0(inputs: T.Buffer[(1, 16, 16, 64), \"float16\"], weight: T.Buffer[(1, 1, 64, 64), \"float16\"], conv2d_nhwc: T.Buffer[(1, 16, 16, 64), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        conv2d_nhwc_reindex_shared = T.alloc_buffer([256, 64], dtype=\"float32\", scope=\"shared\")\n        conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([256, 64], dtype=\"float32\", scope=\"wmma.accumulator\")\n        PadInput_reindex_shared = T.alloc_buffer([256, 64], dtype=\"float16\", scope=\"shared\")\n        weight_reindex_shared = T.alloc_buffer([1, 1, 64, 64], dtype=\"float16\", scope=\"shared\")\n        PadInput_reindex_shared_wmma_matrix_a = T.alloc_buffer([256, 64], dtype=\"float16\", scope=\"wmma.matrix_a\")\n        weight_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 64, 64], dtype=\"float16\", scope=\"wmma.matrix_b\")\n        for ax2_0_0_ax3_0_0_fused in T.thread_binding(16, thread=\"blockIdx.y\"):\n            for ax2_0_1_ax3_0_1_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for ax2_0_2_ax3_0_2_fused in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for ax0_0, ax1_0, ax4_0_0 in T.grid(1, 1, 1):\n                        for ax0_ax1_fused in T.serial(1024):\n                            with T.block(\"PadInput_reindex_shared\"):\n                                v0 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused // 2 * 32 + ax2_0_1_ax3_0_1_fused * 16 + ax0_ax1_fused // 64)\n                                v1 = T.axis.spatial(64, ax0_ax1_fused % 64)\n                                T.reads(inputs[v0 // 256, v0 // 16, v0 % 16, v1])\n                                T.writes(PadInput_reindex_shared[v0, v1])\n                                T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 8]], \"meta_schedule.cooperative_fetch\":1})\n                                PadInput_reindex_shared[v0, v1] = inputs[v0 // 256, v0 // 16, v0 % 16, v1]\n                        for ax0_ax1_ax2_ax3_fused in T.serial(2048):\n                            with T.block(\"weight_reindex_shared\"):\n                                v0 = T.axis.spatial(1, 0)\n                                v1 = T.axis.spatial(1, 0)\n                                v2 = T.axis.spatial(64, ax0_ax1_ax2_ax3_fused // 32)\n                                v3 = T.axis.spatial(64, ax2_0_0_ax3_0_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                T.reads(weight[v0, v1, v2, v3])\n                                T.writes(weight_reindex_shared[v0, v1, v2, v3])\n                                T.block_attr({\"buffer_dim_align\":[[0, 2, 32, 8]], \"meta_schedule.cooperative_fetch\":4})\n                                weight_reindex_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                        for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 1):\n                            for ax0_0_1, ax1_0_1 in T.grid(1, 4):\n                                with T.block(\"PadInput_reindex_shared_wmma.matrix_a_o\"):\n                                    v0_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused)\n                                    v1_o = T.axis.spatial(4, ax1_0_1)\n                                    T.reads(PadInput_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_a\"})\n                                    for ax0_1_1, ax1_1_1 in T.grid(16, 16):\n                                        with T.block(\"PadInput_reindex_shared_wmma.matrix_a\"):\n                                            v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1_1, ax1_1_1])\n                                            T.reads(PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                            PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                            for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 4, 1):\n                                with T.block(\"weight_reindex_shared_wmma.matrix_b_o\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(1, 0)\n                                    v2_o = T.axis.spatial(4, ax2_0)\n                                    v3_o = T.axis.spatial(4, ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused)\n                                    T.reads(weight_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                    T.writes(weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_f16_b\"})\n                                    for ax2_1, ax3_1 in T.grid(16, 16):\n                                        with T.block(\"weight_reindex_shared_wmma.matrix_b\"):\n                                            v2_i, v3_i = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                            T.reads(weight_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                            T.writes(weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                            weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] = weight_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]\n                            for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 4, 1, 1):\n                                with T.block(\"conv2d_nhwc_o\"):\n                                    v0 = T.axis.reduce(1, 0)\n                                    v1 = T.axis.reduce(1, 0)\n                                    v2_o = T.axis.spatial(16, ax2_0_4 + ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused + ax2_0_3)\n                                    v3_o = T.axis.spatial(4, ax3_0_4 + ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused + ax3_0_3)\n                                    v4_o = T.axis.reduce(4, ax4_0_0 * 4 + ax4_0_1 * 4 + ax4_0_2)\n                                    T.reads(PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 : v4_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                    T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                    T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                                    with T.init():\n                                        for ax2_1, ax3_1 in T.grid(16, 16):\n                                            with T.block(\"conv2d_nhwc_init\"):\n                                                v2_i_init, v3_i_init = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                                T.reads()\n                                                T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init])\n                                                conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init] = T.float32(0)\n                                    for ax2_1, ax3_1, ax4_1 in T.grid(16, 16, 16):\n                                        with T.block(\"conv2d_nhwc\"):\n                                            v2_i, v3_i, v4_i = T.axis.remap(\"SSR\", [ax2_1, ax3_1, ax4_1])\n                                            T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i], PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 + v4_i, v3_o * 16 + v3_i])\n                                            T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                            conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] + T.cast(PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], \"float32\") * T.cast(weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 + v4_i, v3_o * 16 + v3_i], \"float32\")\n                    for ax0_0, ax1_0 in T.grid(1, 1):\n                        with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused)\n                            v1_o = T.axis.spatial(4, ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused)\n                            T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_f32_shared\"})\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator\"):\n                                    v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                    conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                for ax0_ax1_fused in T.serial(512):\n                    with T.block(\"conv2d_nhwc_reindex_shared\"):\n                        v0 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused // 2 * 32 + ax2_0_1_ax3_0_1_fused * 16 + ax0_ax1_fused // 32)\n                        v1 = T.axis.spatial(64, ax2_0_0_ax3_0_0_fused % 2 * 32 + ax0_ax1_fused % 32)\n                        T.reads(conv2d_nhwc_reindex_shared[v0, v1])\n                        T.writes(conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1])\n                        T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                        conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1] = conv2d_nhwc_reindex_shared[v0, v1]\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1]),\n        (\"SamplePerfectTile\", [8, 2, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 2, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 2),\n    ]\n\n    mod = te.create_prim_func(\n        te_workload.conv2d_nhwc(\n            1,\n            16,\n            16,\n            64,\n            64,\n            1,\n            1,\n            0,\n            in_dtype=\"float16\",\n            out_dtype=\"float32\",\n        )\n    )\n    actual = generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=tvm.target.Target(\"cuda\"),\n        types=None,\n        sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope=\"shared\")]\n        + get_rules(\"cuda\", ms.schedule_rule.AutoInline),\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[conv2d_1x1_0],\n        expected_decisions=[decision_0],\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_parallel_vectorize_unroll.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass ParallelizeVectorizeUnroll:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        with T.block(\"root\"):\n            T.reads([])\n            T.writes([])\n            T.block_attr({\"meta_schedule.parallel\": 128, \"meta_schedule.vectorize\": 16, \"meta_schedule.unroll_explicit\": 2})\n            for i, j, k in T.grid(1024, 1024, 1024):\n                with T.block(\"matmul\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    with T.init():\n                        C[vi, vj] = 0.0\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n# from tvm.script import tir as T\n@tvm.script.ir_module\nclass PureSpatial:\n    @T.prim_func\n    def main(placeholder: T.Buffer[(1, 13, 13, 3, 85), \"float32\"], placeholder_1: T.Buffer[(1, 26, 26, 3, 85), \"float32\"], placeholder_2: T.Buffer[(1, 52, 52, 3, 85), \"float32\"], T_expand_dims: T.Buffer[(1, 80, 10647), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        T_strided_slice_with_axes = T.alloc_buffer([1, 52, 52, 3, 1], dtype=\"float32\")\n        T_sigmoid = T.alloc_buffer([1, 52, 52, 3, 1], dtype=\"float32\")\n        T_strided_slice_with_axes_1 = T.alloc_buffer([1, 52, 52, 3, 80], dtype=\"float32\")\n        T_sigmoid_1 = T.alloc_buffer([1, 52, 52, 3, 80], dtype=\"float32\")\n        T_multiply = T.alloc_buffer([1, 52, 52, 3, 80], dtype=\"float32\")\n        T_reshape = T.alloc_buffer([8112, 80], dtype=\"float32\")\n        T_strided_slice_with_axes_2 = T.alloc_buffer([1, 26, 26, 3, 1], dtype=\"float32\")\n        T_sigmoid_2 = T.alloc_buffer([1, 26, 26, 3, 1], dtype=\"float32\")\n        T_strided_slice_with_axes_3 = T.alloc_buffer([1, 26, 26, 3, 80], dtype=\"float32\")\n        T_sigmoid_3 = T.alloc_buffer([1, 26, 26, 3, 80], dtype=\"float32\")\n        T_multiply_1 = T.alloc_buffer([1, 26, 26, 3, 80], dtype=\"float32\")\n        T_reshape_1 = T.alloc_buffer([2028, 80], dtype=\"float32\")\n        T_strided_slice_with_axes_4 = T.alloc_buffer([1, 13, 13, 3, 1], dtype=\"float32\")\n        T_sigmoid_4 = T.alloc_buffer([1, 13, 13, 3, 1], dtype=\"float32\")\n        T_strided_slice_with_axes_5 = T.alloc_buffer([1, 13, 13, 3, 80], dtype=\"float32\")\n        T_sigmoid_5 = T.alloc_buffer([1, 13, 13, 3, 80], dtype=\"float32\")\n        T_multiply_2 = T.alloc_buffer([1, 13, 13, 3, 80], dtype=\"float32\")\n        T_reshape_2 = T.alloc_buffer([507, 80], dtype=\"float32\")\n        T_concat = T.alloc_buffer([10647, 80], dtype=\"float32\")\n        T_transpose = T.alloc_buffer([80, 10647], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 1):\n            with T.block(\"T_strided_slice_with_axes\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)])\n                T.writes(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4] = placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 1):\n            with T.block(\"T_sigmoid\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80):\n            with T.block(\"T_strided_slice_with_axes_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)])\n                T.writes(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4] = placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80):\n            with T.block(\"T_sigmoid_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid_1[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid_1[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80):\n            with T.block(\"T_multiply\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_sigmoid[ax0, ax1, ax2, ax3, 0], T_sigmoid_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4])\n                T_multiply[ax0, ax1, ax2, ax3, ax4] = T_sigmoid[ax0, ax1, ax2, ax3, 0] * T_sigmoid_1[ax0, ax1, ax2, ax3, ax4]\n        for i0, i1 in T.grid(8112, 80):\n            with T.block(\"T_reshape\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_multiply[0, (ax1 // 80 + ax0) % 8112 // 156, (ax1 // 80 + ax0) % 156 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80])\n                T.writes(T_reshape[ax0, ax1])\n                T_reshape[ax0, ax1] = T_multiply[0, (ax1 // 80 + ax0) % 8112 // 156, (ax1 // 80 + ax0) % 156 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]\n        for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 1):\n            with T.block(\"T_strided_slice_with_axes_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)])\n                T.writes(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4] = placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 1):\n            with T.block(\"T_sigmoid_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid_2[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid_2[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80):\n            with T.block(\"T_strided_slice_with_axes_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)])\n                T.writes(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4] = placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80):\n            with T.block(\"T_sigmoid_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid_3[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid_3[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80):\n            with T.block(\"T_multiply_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_sigmoid_2[ax0, ax1, ax2, ax3, 0], T_sigmoid_3[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4])\n                T_multiply_1[ax0, ax1, ax2, ax3, ax4] = T_sigmoid_2[ax0, ax1, ax2, ax3, 0] * T_sigmoid_3[ax0, ax1, ax2, ax3, ax4]\n        for i0, i1 in T.grid(2028, 80):\n            with T.block(\"T_reshape_1\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_multiply_1[0, (ax1 // 80 + ax0) % 2028 // 78, (ax1 // 80 + ax0) % 78 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80])\n                T.writes(T_reshape_1[ax0, ax1])\n                T_reshape_1[ax0, ax1] = T_multiply_1[0, (ax1 // 80 + ax0) % 2028 // 78, (ax1 // 80 + ax0) % 78 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]\n        for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 1):\n            with T.block(\"T_strided_slice_with_axes_4\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)])\n                T.writes(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4] = placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(4)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 1):\n            with T.block(\"T_sigmoid_4\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid_4[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid_4[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80):\n            with T.block(\"T_strided_slice_with_axes_5\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)])\n                T.writes(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4])\n                T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4] = placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, \"int64\") + T.int64(5)]\n        for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80):\n            with T.block(\"T_sigmoid_5\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_sigmoid_5[ax0, ax1, ax2, ax3, ax4])\n                T_sigmoid_5[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80):\n            with T.block(\"T_multiply_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_sigmoid_4[ax0, ax1, ax2, ax3, 0], T_sigmoid_5[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply_2[ax0, ax1, ax2, ax3, ax4])\n                T_multiply_2[ax0, ax1, ax2, ax3, ax4] = T_sigmoid_4[ax0, ax1, ax2, ax3, 0] * T_sigmoid_5[ax0, ax1, ax2, ax3, ax4]\n        for i0, i1 in T.grid(507, 80):\n            with T.block(\"T_reshape_2\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_multiply_2[0, (ax1 // 80 + ax0) % 507 // 39, (ax1 // 80 + ax0) % 39 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80])\n                T.writes(T_reshape_2[ax0, ax1])\n                T_reshape_2[ax0, ax1] = T_multiply_2[0, (ax1 // 80 + ax0) % 507 // 39, (ax1 // 80 + ax0) % 39 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]\n        for i0, i1 in T.grid(10647, 80):\n            with T.block(\"T_concat\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_reshape[ax0 - 2535, ax1], T_reshape_1[ax0 - 507, ax1], T_reshape_2[ax0, ax1])\n                T.writes(T_concat[ax0, ax1])\n                T_concat[ax0, ax1] = T.if_then_else(2535 <= ax0, T_reshape[ax0 - 2535, ax1], T.if_then_else(507 <= ax0, T_reshape_1[ax0 - 507, ax1], T_reshape_2[ax0, ax1], dtype=\"float32\"), dtype=\"float32\")\n        for i0, i1 in T.grid(80, 10647):\n            with T.block(\"T_transpose\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_concat[ax1, ax0])\n                T.writes(T_transpose[ax0, ax1])\n                T_transpose[ax0, ax1] = T_concat[ax1, ax0]\n        for i0, i1, i2 in T.grid(1, 80, 10647):\n            with T.block(\"T_expand_dims\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads(T_transpose[ax1, ax2])\n                T.writes(T_expand_dims[ax0, ax1, ax2])\n                T_expand_dims[ax0, ax1, ax2] = T_transpose[ax1, ax2]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_parallel_vectorize_unroll():\n    @T.prim_func\n    def Matmul_0(\n        A: T.Buffer[(1024, 1024), \"float32\"],\n        B: T.Buffer[(1024, 1024), \"float32\"],\n        C: T.Buffer[(1024, 1024), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\"})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr(\n                {\n                    \"meta_schedule.parallel\": 512,\n                    \"meta_schedule.unroll_explicit\": 16,\n                    \"meta_schedule.vectorize\": 32,\n                }\n            )\n            for i, j, k in T.grid(1024, 1024, 1024):\n                with T.block(\"matmul\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    T.reads(A[vi, vk], B[vk, vj])\n                    T.writes(C[vi, vj])\n                    with T.init():\n                        C[vi, vj] = T.float32(0)\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n    decision_0 = [\n        (\"SampleCategorical\", 1),\n    ]\n\n    mod = Matmul\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm --num-cores=32\"),\n        types=None,\n        sch_rules=[\n            ms.schedule_rule.ParallelizeVectorizeUnroll(\n                max_jobs_per_core=16,\n                max_vectorize_extent=32,\n                unroll_max_steps=[0, 16, 64, 512],\n                unroll_explicit=True,\n            ),\n        ],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[Matmul_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_parallel_vectorize_unroll_spatial():\n    mod = PureSpatial\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm --num-cores=32\"),\n        types=None,\n        sch_rules=[\n            ms.schedule_rule.ParallelizeVectorizeUnroll(\n                max_jobs_per_core=-1,\n                max_vectorize_extent=-1,\n                unroll_max_steps=[0, 16, 64, 512],\n                unroll_explicit=True,\n            ),\n        ],\n    )\n    assert len(actual) == 1\n    trace = actual[0].trace.simplified(remove_postproc=True)\n    assert not trace.insts\n\n\nif __name__ == \"__main__\":\n    test_parallel_vectorize_unroll()\n    test_parallel_vectorize_unroll_spatial()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_schedule_rule_random_compute_location.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring\nimport tvm\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n)\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n\n@tvm.script.ir_module\nclass Add:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, [2048, 2048, 2048], dtype=\"float32\")\n        B = T.match_buffer(b, [2048, 2048, 2048], dtype=\"float32\")\n        A_cached = T.alloc_buffer([2048, 2048, 2048], dtype=\"float32\")\n        # body\n        for i, j, k in T.grid(2048, 2048, 2048):\n            with T.block(\"move\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([A_cached[vi, vj, vk]])\n                A_cached[vi, vj, vk] = A[vi, vj, vk]\n        for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32):\n            with T.block(\"add\"):\n                vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2)\n                vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2)\n                vk = T.axis.spatial(2048, k0 * 32 + k1)\n                T.reads([A_cached[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1)\n\n# pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks\n# fmt: on\n\n\ndef test_random_compute_location():\n    @T.prim_func\n    def add_0(\n        A: T.Buffer[(2048, 2048, 2048), \"float32\"],\n        B: T.Buffer[(2048, 2048, 2048), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        A_cached = T.alloc_buffer([2048, 2048, 2048], dtype=\"float32\")\n        for i0, j0, i1, j1, k0, i2 in T.grid(128, 64, 4, 4, 64, 4):\n            for ax0, ax1, ax2 in T.grid(1, 8, 32):\n                with T.block(\"move\"):\n                    vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2 + ax0)\n                    vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + ax1)\n                    vk = T.axis.spatial(2048, k0 * 32 + ax2)\n                    T.reads(A[vi, vj, vk])\n                    T.writes(A_cached[vi, vj, vk])\n                    A_cached[vi, vj, vk] = A[vi, vj, vk]\n            for j2, k1 in T.grid(8, 32):\n                with T.block(\"add\"):\n                    vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2)\n                    vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2)\n                    vk = T.axis.spatial(2048, k0 * 32 + k1)\n                    T.reads(A_cached[vi, vj, vk])\n                    T.writes(B[vi, vj, vk])\n                    B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1)\n\n    decision_0 = [\n        (\"SampleComputeLocation\", 5),\n    ]\n\n    mod = Add\n    actual = generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=Target(\"llvm\"),\n        types=None,\n        sch_rules=[ms.schedule_rule.RandomComputeLocation()],\n    )\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[add_0],\n        expected_decisions=[decision_0],\n    )\n\n\nif __name__ == \"__main__\":\n    test_random_compute_location()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_search_strategy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule SearchStrategy \"\"\"\n# pylint: disable=missing-function-docstring\nfrom typing import List\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.utils import derived_object\nfrom tvm.meta_schedule.testing.dummy_object import DummyMutator\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import Schedule, Trace\n\nMATMUL_M = 32\n\n# pylint: disable=missing-class-docstring,invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument, unbalanced-tuple-unpacking\n# fmt: off\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None: # type: ignore\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (32, 32), \"float32\")\n        B = T.match_buffer(b, (32, 32), \"float32\")\n        C = T.match_buffer(c, (32, 32), \"float32\")\n        for i, j, k in T.grid(32, 32, 32):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0 # type: ignore\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n# fmt: on\n# pylint: enable=missing-class-docstring,invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef _is_trace_equal(sch_1: Schedule, sch_2: Schedule, remove_decisions=True) -> bool:\n    if remove_decisions:\n        trace_1 = Trace(sch_1.trace.insts, {})\n        trace_2 = Trace(sch_2.trace.insts, {})\n    else:\n        trace_1 = sch_1.trace\n        trace_2 = sch_2.trace\n    return str(trace_1) == str(trace_2)\n\n\ndef _schedule_matmul(sch: Schedule):\n    block = sch.get_block(\"matmul\")\n    i, j, k = sch.get_loops(block=block)\n    i_0, i_1, i_2, i_3 = sch.split(i, sch.sample_perfect_tile(i, n=4))\n    j_0, j_1, j_2, j_3 = sch.split(j, sch.sample_perfect_tile(j, n=4))\n    k_0, k_1 = sch.split(k, sch.sample_perfect_tile(k, n=2))\n    sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n\n\n@pytest.mark.parametrize(\n    \"TestClass\",\n    [\n        ms.search_strategy.ReplayFunc,\n        ms.search_strategy.ReplayTrace,\n    ],\n)\ndef test_meta_schedule_replay_func(\n    TestClass: ms.search_strategy.SearchStrategy,\n):  # pylint: disable = invalid-name\n    num_trials_per_iter = 7\n    max_trials_per_task = 20\n\n    context = ms.TuneContext(\n        mod=Matmul,\n        space_generator=ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul, postprocs=[]),\n        search_strategy=TestClass(),\n    )\n    strategy = context.search_strategy\n    spaces = context.space_generator.generate_design_space(context.mod)\n    strategy.pre_tuning(\n        max_trials=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        design_spaces=spaces,\n    )\n    (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space(\n        Matmul\n    )\n    num_trials_each_iter: List[int] = []\n    candidates = strategy.generate_measure_candidates()\n    while candidates is not None:\n        num_trials_each_iter.append(len(candidates))\n        runner_results: List[ms.runner.RunnerResult] = []\n        for candidate in candidates:\n            _is_trace_equal(\n                candidate.sch,\n                correct_sch,\n                remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)),\n            )\n            runner_results.append(\n                ms.runner.RunnerResult(\n                    run_secs=[0.11, 0.41, 0.54],\n                    error_msg=None,\n                )\n            )\n        strategy.notify_runner_results(candidates, runner_results)\n        candidates = strategy.generate_measure_candidates()\n    strategy.post_tuning()\n    assert num_trials_each_iter == [7, 7, 6]\n\n\ndef test_meta_schedule_evolutionary_search():  # pylint: disable = invalid-name\n    def _schedule_matmul_small(sch: Schedule):\n        block = sch.get_block(\"matmul\")\n        _, j, k = sch.get_loops(block=block)\n        _, _ = sch.split(j, sch.sample_perfect_tile(j, n=2))\n        _, _ = sch.split(k, sch.sample_perfect_tile(k, n=2))\n\n    num_trials_per_iter = 10\n    max_trials_per_task = 2000\n    (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space(\n        Matmul\n    )\n\n    context = ms.TuneContext(\n        mod=Matmul,\n        space_generator=ms.space_generator.ScheduleFn(\n            sch_fn=_schedule_matmul_small,\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={\n                DummyMutator(): 1.0,\n            },\n        ),\n        search_strategy=ms.search_strategy.EvolutionarySearch(\n            population_size=5,\n            init_measured_ratio=0.1,\n            init_min_unmeasured=50,\n            genetic_num_iters=3,\n            genetic_mutate_prob=0.5,\n            genetic_max_fail_count=10,\n            eps_greedy=0.9,\n        ),\n        target=tvm.target.Target(\"llvm\"),\n        num_threads=1,  # because we are using a mutator from the python side\n    )\n    strategy = context.search_strategy\n    strategy.pre_tuning(\n        max_trials=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        design_spaces=context.space_generator.generate_design_space(context.mod),\n        database=ms.database.MemoryDatabase(),\n        cost_model=ms.cost_model.RandomModel(),\n    )\n    num_trials_each_iter: List[int] = []\n    candidates = strategy.generate_measure_candidates()\n    while candidates is not None:\n        num_trials_each_iter.append(len(candidates))\n        runner_results: List[ms.runner.RunnerResult] = []\n        for candidate in candidates:\n            _is_trace_equal(\n                candidate.sch,\n                correct_sch,\n                remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)),\n            )\n            runner_results.append(\n                ms.runner.RunnerResult(\n                    run_secs=[0.11, 0.41, 0.54],\n                    error_msg=None,\n                )\n            )\n        strategy.notify_runner_results(candidates, runner_results)\n        candidates = strategy.generate_measure_candidates()\n    strategy.post_tuning()\n    assert sum(num_trials_each_iter) == 25\n    assert num_trials_each_iter.count(0) < 5\n\n\ndef test_meta_schedule_evolutionary_search_early_stop():  # pylint: disable = invalid-name\n    def _schedule_matmul_empty(sch: Schedule):\n        return sch\n\n    (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space(\n        Matmul\n    )\n\n    num_trials_per_iter = 10\n    max_trials_per_task = 100\n\n    context = ms.TuneContext(\n        mod=Matmul,\n        search_strategy=ms.search_strategy.EvolutionarySearch(\n            population_size=5,\n            init_measured_ratio=0.1,\n            init_min_unmeasured=50,\n            genetic_num_iters=3,\n            genetic_mutate_prob=0.5,\n            genetic_max_fail_count=10,\n            eps_greedy=0.9,\n        ),\n        space_generator=ms.space_generator.ScheduleFn(\n            sch_fn=_schedule_matmul_empty,\n            sch_rules=[],\n            postprocs=[],\n            mutator_probs={\n                DummyMutator(): 1.0,\n            },\n        ),\n        target=tvm.target.Target(\"llvm\"),\n        num_threads=1,\n    )\n    strategy = context.search_strategy\n    strategy.pre_tuning(\n        max_trials=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        design_spaces=context.space_generator.generate_design_space(context.mod),\n        database=ms.database.MemoryDatabase(),\n        cost_model=ms.cost_model.RandomModel(),\n    )\n    num_trials_each_iter: List[int] = []\n    candidates = strategy.generate_measure_candidates()\n    while candidates is not None:\n        num_trials_each_iter.append(len(candidates))\n        runner_results: List[ms.runner.RunnerResult] = []\n        for candidate in candidates:\n            _is_trace_equal(\n                candidate.sch,\n                correct_sch,\n                remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)),\n            )\n            runner_results.append(\n                ms.runner.RunnerResult(\n                    run_secs=[0.11, 0.41, 0.54],\n                    error_msg=None,\n                ),\n            )\n        strategy.notify_runner_results(candidates, runner_results)\n        candidates = strategy.generate_measure_candidates()\n    strategy.post_tuning()\n    assert num_trials_each_iter == [1, 0, 0, 0, 0]\n\n\ndef test_meta_schedule_evolutionary_search_fail_init_population():  # pylint: disable = invalid-name\n    @derived_object\n    class AlwaysFailPostproc(ms.postproc.PyPostproc):\n        \"\"\"A postproc that always fails.\"\"\"\n\n        def _initialize_with_tune_context(self, context: ms.TuneContext) -> None:\n            pass\n\n        def apply(self, sch: Schedule) -> bool:\n            return False\n\n        def clone(self) -> \"AlwaysFailPostproc\":\n            return AlwaysFailPostproc()\n\n        def __str__(self) -> str:\n            return \"AlwaysFailPostproc\"\n\n    num_trials_per_iter = 10\n    max_trials_per_task = 2000\n\n    context = ms.TuneContext(\n        mod=Matmul,\n        space_generator=ms.space_generator.ScheduleFn(\n            sch_fn=_schedule_matmul,\n            sch_rules=[],\n            postprocs=[AlwaysFailPostproc()],\n            mutator_probs={\n                DummyMutator(): 1.0,\n            },\n        ),\n        search_strategy=ms.search_strategy.EvolutionarySearch(\n            population_size=5,\n            init_measured_ratio=0.1,\n            init_min_unmeasured=50,\n            genetic_num_iters=3,\n            genetic_mutate_prob=0.5,\n            genetic_max_fail_count=10,\n            eps_greedy=0.9,\n        ),\n        target=tvm.target.Target(\"llvm\"),\n        num_threads=1,  # because we are using a mutator from the python side\n    )\n    strategy = context.search_strategy\n    strategy.pre_tuning(\n        max_trials=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        design_spaces=context.space_generator.generate_design_space(context.mod),\n        database=ms.database.MemoryDatabase(),\n        cost_model=ms.cost_model.RandomModel(),\n    )\n    candidates = strategy.generate_measure_candidates()\n    assert candidates is None\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_replay_func(ms.search_strategy.ReplayFunc)\n    test_meta_schedule_replay_func(ms.search_strategy.ReplayTrace)\n    test_meta_schedule_evolutionary_search()\n    test_meta_schedule_evolutionary_search_early_stop()\n    test_meta_schedule_evolutionary_search_fail_init_population()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_space_cpu.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for MetaSchedule search space on CPU\"\"\"\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    print_sketches,\n    generate_design_space,\n)\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target():\n    return Target(\"aws/cpu/c5.9xlarge\")\n\n\ndef _design_space(mod):\n    return generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=_target(),\n        types=ms.ScheduleRule,\n    )\n\n\ndef test_cpu_c1d():\n    # fmt: off\n    @T.prim_func\n    def c1d_0(inputs: T.Buffer[(1, 256, 64), \"float32\"], weight: T.Buffer[(3, 64, 128), \"float32\"], conv1d_nlc: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 258, 64], dtype=\"float32\")\n            conv1d_nlc_global = T.alloc_buffer([1, 128, 128], dtype=\"float32\")\n            for i0, i1, i2 in T.grid(1, 258, 64):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                    T.reads(inputs[i0_1, i1_1 - 1, i2_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1])\n                    PadInput[i0_1, i1_1, i2_1] = T.if_then_else(1 <= i1_1 and i1_1 < 257, inputs[i0_1, i1_1 - 1, i2_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i0_1_1, i1_1_1, i2_1_1 in T.grid(1, 1, 2, 1, 1, 8):\n                for i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 64, 1, 64, 8, 3, 1, 1, 2, 1):\n                    with T.block(\"conv1d_nlc\"):\n                        n = T.axis.spatial(1, i0_1_1 + i0_2 + i0_3 + i0_0)\n                        l = T.axis.spatial(128, i1_0 * 128 + i1_1_1 * 128 + i1_2 * 2 + i1_3)\n                        co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1_1 * 8 + i2_2)\n                        rl = T.axis.reduce(3, i3_0 * 3 + i3_1)\n                        rc = T.axis.reduce(64, i4_1 + i4_0)\n                        T.reads(PadInput[n, l * 2 + rl, co // 128 * 64 + rc], weight[rl, rc, co])\n                        T.writes(conv1d_nlc_global[n, l, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv1d_nlc_global[n, l, co] = T.float32(0)\n                        conv1d_nlc_global[n, l, co] = conv1d_nlc_global[n, l, co] + PadInput[n, l * 2 + rl, co // 128 * 64 + rc] * weight[rl, rc, co]\n                for ax0, ax1, ax2 in T.grid(1, 128, 8):\n                    with T.block(\"conv1d_nlc_global\"):\n                        v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                        v2 = T.axis.spatial(128, i2_0 * 64 + i2_1_1 * 8 + ax2)\n                        T.reads(conv1d_nlc_global[v0, v1, v2])\n                        T.writes(conv1d_nlc[v0, v1, v2])\n                        conv1d_nlc[v0, v1, v2] = conv1d_nlc_global[v0, v1, v2]\n    @T.prim_func\n    def c1d_1(inputs: T.Buffer[(1, 256, 64), \"float32\"], weight: T.Buffer[(3, 64, 128), \"float32\"], conv1d_nlc: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 258, 64], dtype=\"float32\")\n            conv1d_nlc_global = T.alloc_buffer([1, 128, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0 in T.grid(1, 1, 2):\n                for i0_1, i1_1, i2_1 in T.grid(1, 1, 8):\n                    for ax0, ax1, ax2 in T.grid(1, 257, 64):\n                        with T.block(\"PadInput\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(258, ax1)\n                            i2 = T.axis.spatial(64, ax2)\n                            T.reads(inputs[i0, i1 - 1, i2])\n                            T.writes(PadInput[i0, i1, i2])\n                            PadInput[i0, i1, i2] = T.if_then_else(1 <= i1 and i1 < 257, inputs[i0, i1 - 1, i2], T.float32(0), dtype=\"float32\")\n                    for i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 64, 1, 64, 8, 3, 1, 1, 2, 1):\n                        with T.block(\"conv1d_nlc\"):\n                            n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                            l = T.axis.spatial(128, i1_0 * 128 + i1_1 * 128 + i1_2 * 2 + i1_3)\n                            co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1 * 8 + i2_2)\n                            rl = T.axis.reduce(3, i3_0 * 3 + i3_1)\n                            rc = T.axis.reduce(64, i4_1 + i4_0)\n                            T.reads(PadInput[n, l * 2 + rl, co // 128 * 64 + rc], weight[rl, rc, co])\n                            T.writes(conv1d_nlc_global[n, l, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv1d_nlc_global[n, l, co] = T.float32(0)\n                            conv1d_nlc_global[n, l, co] = conv1d_nlc_global[n, l, co] + PadInput[n, l * 2 + rl, co // 128 * 64 + rc] * weight[rl, rc, co]\n                for ax0, ax1, ax2 in T.grid(1, 128, 64):\n                    with T.block(\"conv1d_nlc_global\"):\n                        v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                        v2 = T.axis.spatial(128, i2_0 * 64 + ax2)\n                        T.reads(conv1d_nlc_global[v0, v1, v2])\n                        T.writes(conv1d_nlc[v0, v1, v2])\n                        conv1d_nlc[v0, v1, v2] = conv1d_nlc_global[v0, v1, v2]\n\n    @T.prim_func\n    def c1d_2(inputs: T.Buffer[(1, 256, 64), \"float32\"], weight: T.Buffer[(3, 64, 128), \"float32\"], conv1d_nlc: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1, i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 1, 2, 1, 1, 8, 1, 64, 1, 64, 8, 3, 1, 1, 2, 1):\n                with T.block(\"conv1d_nlc\"):\n                    n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                    l = T.axis.spatial(128, i1_0 * 128 + i1_1 * 128 + i1_2 * 2 + i1_3)\n                    co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1 * 8 + i2_2)\n                    rl = T.axis.reduce(3, i3_0 * 3 + i3_1)\n                    rc = T.axis.reduce(64, i4_1 + i4_0)\n                    T.reads(inputs[n, l * 2 + rl - 1, co // 128 * 64 + rc], weight[rl, rc, co])\n                    T.writes(conv1d_nlc[n, l, co])\n                    T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                    with T.init():\n                        conv1d_nlc[n, l, co] = T.float32(0)\n                    conv1d_nlc[n, l, co] = conv1d_nlc[n, l, co] + T.if_then_else(1 <= l * 2 + rl and l * 2 + rl < 257, inputs[n, l * 2 + rl - 1, co // 128 * 64 + rc], T.float32(0), dtype=\"float32\") * weight[rl, rc, co]\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 64, 2]),\n        (\"SamplePerfectTile\", [2, 8, 8, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [64, 1]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 64, 2]),\n        (\"SamplePerfectTile\", [2, 8, 8, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [64, 1]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 5),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 64, 2]),\n        (\"SamplePerfectTile\", [2, 8, 8, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [64, 1]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", -2),\n    ]\n\n    mod = create_te_workload(\"C1D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c1d_0, c1d_1, c1d_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_c2d():\n    # fmt: off\n    @T.prim_func\n    def c2d_0(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1 in T.grid(1, 7, 4, 2, 1, 1, 28):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 37, 7, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 32 + ax1)\n                        i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 2 + ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i3_1 in T.serial(8):\n                    for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4):\n                        with T.block(\"conv2d_nhwc\"):\n                            n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                            h = T.axis.spatial(112, i1_0 * 16 + i1_1 * 16 + i1_2 * 8 + i1_3)\n                            w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1 + i2_2)\n                            co = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + i3_2 * 4 + i3_3)\n                            rh = T.axis.reduce(7, i4_1 + i4_0)\n                            rw = T.axis.reduce(7, i5_0 + i5_1)\n                            rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                            T.writes(conv2d_nhwc_global[n, h, w, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                            conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 16, 1, 4):\n                        with T.block(\"conv2d_nhwc_global\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(112, i1_0 * 16 + ax1)\n                            v2 = T.axis.spatial(112, i2_0 * 28 + i2_1 + ax2)\n                            v3 = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + ax3)\n                            T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                            T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                            conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def c2d_1(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(3 <= i1_1 and i1_1 < 227 and 3 <= i2_1 and i2_1 < 227, inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 4, 2):\n                for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 28, 8, 7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2)\n                        h = T.axis.spatial(112, i1_0 * 16 + i1_1_1 * 16 + i1_2 * 8 + i1_3)\n                        w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1_1 + i2_2)\n                        co = T.axis.spatial(64, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 4 + i3_3)\n                        rh = T.axis.reduce(7, i4_1 + i4_0)\n                        rw = T.axis.reduce(7, i5_0 + i5_1)\n                        rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc_global[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 16, 28, 32):\n                    with T.block(\"conv2d_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(112, i1_0 * 16 + ax1)\n                        v2 = T.axis.spatial(112, i2_0 * 28 + ax2)\n                        v3 = T.axis.spatial(64, i3_0 * 32 + ax3)\n                        T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                        conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def c2d_2(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            for i0_0, i1_0 in T.grid(1, 7):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 37, 229, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 32 + ax1)\n                        i2 = T.axis.spatial(230, ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(4, 2, 1, 1, 28, 8, 7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                        h = T.axis.spatial(112, i1_0 * 16 + i1_1 * 16 + i1_2 * 8 + i1_3)\n                        w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1 + i2_2)\n                        co = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + i3_2 * 4 + i3_3)\n                        rh = T.axis.reduce(7, i4_1 + i4_0)\n                        rw = T.axis.reduce(7, i5_0 + i5_1)\n                        rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 1, 2, 8]),\n        (\"SamplePerfectTile\", [4, 28, 1, 1]),\n        (\"SamplePerfectTile\", [2, 8, 1, 4]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", 6),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 1, 2, 8]),\n        (\"SamplePerfectTile\", [4, 28, 1, 1]),\n        (\"SamplePerfectTile\", [2, 8, 1, 4]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 1, 2, 8]),\n        (\"SamplePerfectTile\", [4, 28, 1, 1]),\n        (\"SamplePerfectTile\", [2, 8, 1, 4]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 1),\n    ]\n\n    mod = create_te_workload(\"C2D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c2d_0, c2d_1, c2d_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_c3d():\n    # fmt: off\n    @T.prim_func\n    def c3d_0(inputs: T.Buffer[(1, 16, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 7, 3, 64), \"float32\"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype=\"float32\")\n            conv3d_ndhwc_global = T.alloc_buffer([1, 8, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0 in T.grid(1, 2, 4, 1, 2):\n                for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 13, 61, 229, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(22, i1_0 * 8 + ax1)\n                        i2 = T.axis.spatial(230, i2_0 * 56 + ax2)\n                        i3 = T.axis.spatial(230, ax3)\n                        i4 = T.axis.spatial(3, ax4)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4])\n                        T.writes(PadInput[i0, i1, i2, i3, i4])\n                        PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype=\"float32\")\n                for i0_1, i1_1, i2_1, i3_1, i4_1 in T.grid(1, 4, 4, 14, 1):\n                    for i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1):\n                        with T.block(\"conv3d_ndhwc\"):\n                            n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                            d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2)\n                            h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3)\n                            w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3)\n                            co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2)\n                            rd = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                            rh = T.axis.reduce(7, i6_1 + i6_0)\n                            rw = T.axis.reduce(7, i7_0 + i7_1)\n                            rc = T.axis.reduce(3, i8_1 + i8_0)\n                            T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co])\n                            T.writes(conv3d_ndhwc_global[n, d, h, w, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv3d_ndhwc_global[n, d, h, w, co] = T.float32(0)\n                            conv3d_ndhwc_global[n, d, h, w, co] = conv3d_ndhwc_global[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co]\n                    for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 1, 7, 8, 32):\n                        with T.block(\"conv3d_ndhwc_global\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(8, i1_0 * 4 + i1_1 + ax1)\n                            v2 = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + ax2)\n                            v3 = T.axis.spatial(112, i3_1 * 8 + ax3)\n                            v4 = T.axis.spatial(64, i4_0 * 32 + ax4)\n                            T.reads(conv3d_ndhwc_global[v0, v1, v2, v3, v4])\n                            T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4])\n                            conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_global[v0, v1, v2, v3, v4]\n    @T.prim_func\n    def c3d_1(inputs: T.Buffer[(1, 16, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 7, 3, 64), \"float32\"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype=\"float32\")\n            conv3d_ndhwc_global = T.alloc_buffer([1, 8, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0 in T.grid(1, 2, 4, 1, 2):\n                for i0_1, i1_1, i2_1, i3_1 in T.grid(1, 4, 4, 14):\n                    for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 7, 19, 21, 3):\n                        with T.block(\"PadInput\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(22, i1_0 * 8 + i1_1 * 2 + ax1)\n                            i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 14 + ax2)\n                            i3 = T.axis.spatial(230, i3_1 * 16 + ax3)\n                            i4 = T.axis.spatial(3, ax4)\n                            T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4])\n                            T.writes(PadInput[i0, i1, i2, i3, i4])\n                            PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype=\"float32\")\n                    for i4_1, i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1):\n                        with T.block(\"conv3d_ndhwc\"):\n                            n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                            d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2)\n                            h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3)\n                            w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3)\n                            co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2)\n                            rd = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                            rh = T.axis.reduce(7, i6_1 + i6_0)\n                            rw = T.axis.reduce(7, i7_0 + i7_1)\n                            rc = T.axis.reduce(3, i8_1 + i8_0)\n                            T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co])\n                            T.writes(conv3d_ndhwc_global[n, d, h, w, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv3d_ndhwc_global[n, d, h, w, co] = T.float32(0)\n                            conv3d_ndhwc_global[n, d, h, w, co] = conv3d_ndhwc_global[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co]\n                for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 4, 28, 112, 32):\n                    with T.block(\"conv3d_ndhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(8, i1_0 * 4 + ax1)\n                        v2 = T.axis.spatial(112, i2_0 * 28 + ax2)\n                        v3 = T.axis.spatial(112, ax3)\n                        v4 = T.axis.spatial(64, i4_0 * 32 + ax4)\n                        T.reads(conv3d_ndhwc_global[v0, v1, v2, v3, v4])\n                        T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4])\n                        conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_global[v0, v1, v2, v3, v4]\n    @T.prim_func\n    def c3d_2(inputs: T.Buffer[(1, 16, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 7, 3, 64), \"float32\"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 2, 4, 1, 2, 1, 4, 4, 14):\n                for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 7, 19, 21, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(22, i1_0 * 8 + i1_1 * 2 + ax1)\n                        i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 14 + ax2)\n                        i3 = T.axis.spatial(230, i3_1 * 16 + ax3)\n                        i4 = T.axis.spatial(3, ax4)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4])\n                        T.writes(PadInput[i0, i1, i2, i3, i4])\n                        PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype=\"float32\")\n                for i4_1, i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1):\n                    with T.block(\"conv3d_ndhwc\"):\n                        n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                        d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2)\n                        h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3)\n                        w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3)\n                        co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2)\n                        rd = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                        rh = T.axis.reduce(7, i6_1 + i6_0)\n                        rw = T.axis.reduce(7, i7_0 + i7_1)\n                        rc = T.axis.reduce(3, i8_1 + i8_0)\n                        T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co])\n                        T.writes(conv3d_ndhwc[n, d, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv3d_ndhwc[n, d, h, w, co] = T.float32(0)\n                        conv3d_ndhwc[n, d, h, w, co] = conv3d_ndhwc[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co]\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [4, 4, 1, 7]),\n        (\"SamplePerfectTile\", [1, 14, 1, 8]),\n        (\"SamplePerfectTile\", [2, 1, 32, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 4),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [4, 4, 1, 7]),\n        (\"SamplePerfectTile\", [1, 14, 1, 8]),\n        (\"SamplePerfectTile\", [2, 1, 32, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 8),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [4, 4, 1, 7]),\n        (\"SamplePerfectTile\", [1, 14, 1, 8]),\n        (\"SamplePerfectTile\", [2, 1, 32, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", 8),\n    ]\n\n    mod = create_te_workload(\"C3D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c3d_0, c3d_1, c3d_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_cap():\n    # fmt: off\n    @T.prim_func\n    def cap_0(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), \"float32\"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), \"float32\"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype=\"float32\")\n            conv2d_capsule_nhwijc_global = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0, i0_1, i1_1 in T.grid(1, 2, 1, 1, 1, 1, 1, 4):\n                for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 3, 17, 4, 4, 32):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(18, i1_0 * 8 + i1_1 * 2 + ax1)\n                        i2 = T.axis.spatial(18, ax2)\n                        i3, i4, i5 = T.axis.remap(\"SSS\", [ax3, ax4, ax5])\n                        T.reads(inputs[i0, i1 - 1, i2 - 1, i3, i4, i5])\n                        T.writes(PadInput[i0, i1, i2, i3, i4, i5])\n                        PadInput[i0, i1, i2, i3, i4, i5] = T.if_then_else(1 <= i1 and i1 < 17 and 1 <= i2 and i2 < 17, inputs[i0, i1 - 1, i2 - 1, i3, i4, i5], T.float32(0), dtype=\"float32\")\n                for i2_1, i3_1, i4_1, i5_1 in T.grid(4, 1, 4, 2):\n                    for i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16):\n                        with T.block(\"conv2d_capsule_nhwijc\"):\n                            n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1)\n                            h = T.axis.spatial(8, i1_0 * 4 + i1_1 + i1_2 + i1_3)\n                            w = T.axis.spatial(8, i2_0 * 8 + i2_1 * 2 + i2_2 + i2_3)\n                            cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1 * 4 + i3_2 * 4 + i3_3)\n                            cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1 + i4_2 + i4_3)\n                            co = T.axis.spatial(32, i5_0 * 32 + i5_1 * 16 + i5_2 * 16 + i5_3)\n                            rh = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            rw = T.axis.reduce(3, i7_1 + i7_0)\n                            cap_k = T.axis.reduce(4, i8_0 + i8_1)\n                            rc = T.axis.reduce(32, i9_0 * 32 + i9_1)\n                            T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co])\n                            T.writes(conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = T.float32(0)\n                            conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co]\n                    for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 1, 2, 4, 1, 16):\n                        with T.block(\"conv2d_capsule_nhwijc_global\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(8, i1_0 * 4 + i1_1 + ax1)\n                            v2 = T.axis.spatial(8, i2_1 * 2 + ax2)\n                            v3 = T.axis.spatial(4, ax3)\n                            v4 = T.axis.spatial(4, i4_1 + ax4)\n                            v5 = T.axis.spatial(32, i5_1 * 16 + ax5)\n                            T.reads(conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5])\n                            T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5])\n                            conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5]\n    @T.prim_func\n    def cap_1(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), \"float32\"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), \"float32\"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype=\"float32\")\n            conv2d_capsule_nhwijc_global = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0 in T.grid(1, 2, 1, 1, 1, 1):\n                for i0_1, i1_1, i2_1, i3_1, i4_1, i5_1 in T.grid(1, 4, 4, 1, 4, 2):\n                    for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 3, 5, 4, 4, 32):\n                        with T.block(\"PadInput\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(18, i1_0 * 8 + i1_1 * 2 + ax1)\n                            i2 = T.axis.spatial(18, i2_1 * 4 + ax2)\n                            i3, i4, i5 = T.axis.remap(\"SSS\", [ax3, ax4, ax5])\n                            T.reads(inputs[i0, i1 - 1, i2 - 1, i3, i4, i5])\n                            T.writes(PadInput[i0, i1, i2, i3, i4, i5])\n                            PadInput[i0, i1, i2, i3, i4, i5] = T.if_then_else(1 <= i1 and i1 < 17 and 1 <= i2 and i2 < 17, inputs[i0, i1 - 1, i2 - 1, i3, i4, i5], T.float32(0), dtype=\"float32\")\n                    for i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16):\n                        with T.block(\"conv2d_capsule_nhwijc\"):\n                            n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1)\n                            h = T.axis.spatial(8, i1_0 * 4 + i1_1 + i1_2 + i1_3)\n                            w = T.axis.spatial(8, i2_0 * 8 + i2_1 * 2 + i2_2 + i2_3)\n                            cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1 * 4 + i3_2 * 4 + i3_3)\n                            cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1 + i4_2 + i4_3)\n                            co = T.axis.spatial(32, i5_0 * 32 + i5_1 * 16 + i5_2 * 16 + i5_3)\n                            rh = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            rw = T.axis.reduce(3, i7_1 + i7_0)\n                            cap_k = T.axis.reduce(4, i8_0 + i8_1)\n                            rc = T.axis.reduce(32, i9_0 * 32 + i9_1)\n                            T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co])\n                            T.writes(conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = T.float32(0)\n                            conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co]\n                for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 4, 8, 4, 4, 32):\n                    with T.block(\"conv2d_capsule_nhwijc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(8, i1_0 * 4 + ax1)\n                        v2, v3, v4, v5 = T.axis.remap(\"SSSS\", [ax2, ax3, ax4, ax5])\n                        T.reads(conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5])\n                        T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5])\n                        conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5]\n    @T.prim_func\n    def cap_2(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), \"float32\"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), \"float32\"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype=\"float32\")\n            for i0, i1, i2, i3, i4, i5 in T.grid(1, 18, 18, 4, 4, 32):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1, i4_1, i5_1 = T.axis.remap(\"SSSSSS\", [i0, i1, i2, i3, i4, i5])\n                    T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1, i4_1, i5_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1, i4_1, i5_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1, i4_1, i5_1] = T.if_then_else(1 <= i1_1 and i1_1 < 17 and 1 <= i2_1 and i2_1 < 17, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1, i4_1, i5_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_1_1, i5_1_1, i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 2, 1, 1, 1, 1, 1, 4, 4, 1, 4, 2, 1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16):\n                with T.block(\"conv2d_capsule_nhwijc\"):\n                    n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1)\n                    h = T.axis.spatial(8, i1_0 * 4 + i1_1_1 + i1_2 + i1_3)\n                    w = T.axis.spatial(8, i2_0 * 8 + i2_1_1 * 2 + i2_2 + i2_3)\n                    cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1_1 * 4 + i3_2 * 4 + i3_3)\n                    cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1_1 + i4_2 + i4_3)\n                    co = T.axis.spatial(32, i5_0 * 32 + i5_1_1 * 16 + i5_2 * 16 + i5_3)\n                    rh = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                    rw = T.axis.reduce(3, i7_1 + i7_0)\n                    cap_k = T.axis.reduce(4, i8_0 + i8_1)\n                    rc = T.axis.reduce(32, i9_0 * 32 + i9_1)\n                    T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co])\n                    T.writes(conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co])\n                    T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                    with T.init():\n                        conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] = T.float32(0)\n                    conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 4]),\n        (\"SamplePerfectTile\", [1, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 2, 1, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 32]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 7),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 4]),\n        (\"SamplePerfectTile\", [1, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 2, 1, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 32]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 11),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 1]),\n        (\"SamplePerfectTile\", [1, 1, 1, 4]),\n        (\"SamplePerfectTile\", [1, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 2, 1, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [4, 1]),\n        (\"SamplePerfectTile\", [1, 32]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    mod = create_te_workload(\"CAP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cap_0, cap_1, cap_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_dep():\n    # fmt: off\n    @T.prim_func\n    def dep_0(placeholder: T.Buffer[(1, 112, 112, 32), \"float32\"], placeholder_1: T.Buffer[(1, 3, 3, 32), \"float32\"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 114, 114, 32], dtype=\"float32\")\n            depth_conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 32], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 114, 114, 32):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 113 and 1 <= i2_1 and i2_1 < 113, placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1 in T.grid(1, 1, 1, 1, 1, 4, 4, 8):\n                for i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2):\n                    with T.block(\"depth_conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1)\n                        h = T.axis.spatial(112, i1_0 * 112 + i1_1_1 * 28 + i1_2 * 14 + i1_3)\n                        w = T.axis.spatial(112, i2_0 * 112 + i2_1_1 * 28 + i2_2 * 4 + i2_3)\n                        c = T.axis.spatial(32, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 2 + i3_3)\n                        rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                        rw = T.axis.reduce(3, i5_0 * 3 + i5_1)\n                        T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c])\n                        T.writes(depth_conv2d_nhwc_global[n, h, w, c])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            depth_conv2d_nhwc_global[n, h, w, c] = T.float32(0)\n                        depth_conv2d_nhwc_global[n, h, w, c] = depth_conv2d_nhwc_global[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 28, 28, 4):\n                    with T.block(\"depth_conv2d_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(112, i1_1_1 * 28 + ax1)\n                        v2 = T.axis.spatial(112, i2_1_1 * 28 + ax2)\n                        v3 = T.axis.spatial(32, i3_1_1 * 4 + ax3)\n                        T.reads(depth_conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(depth_conv2d_nhwc[v0, v1, v2, v3])\n                        depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def dep_1(placeholder: T.Buffer[(1, 112, 112, 32), \"float32\"], placeholder_1: T.Buffer[(1, 3, 3, 32), \"float32\"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 114, 114, 32], dtype=\"float32\")\n            depth_conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 32], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 114, 114, 32):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 113 and 1 <= i2_1 and i2_1 < 113, placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 1, 1):\n                for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 4, 8, 1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2):\n                    with T.block(\"depth_conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1)\n                        h = T.axis.spatial(112, i1_0 * 112 + i1_1_1 * 28 + i1_2 * 14 + i1_3)\n                        w = T.axis.spatial(112, i2_0 * 112 + i2_1_1 * 28 + i2_2 * 4 + i2_3)\n                        c = T.axis.spatial(32, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 2 + i3_3)\n                        rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                        rw = T.axis.reduce(3, i5_0 * 3 + i5_1)\n                        T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c])\n                        T.writes(depth_conv2d_nhwc_global[n, h, w, c])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            depth_conv2d_nhwc_global[n, h, w, c] = T.float32(0)\n                        depth_conv2d_nhwc_global[n, h, w, c] = depth_conv2d_nhwc_global[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 112, 112, 32):\n                    with T.block(\"depth_conv2d_nhwc_global\"):\n                        v0, v1, v2, v3 = T.axis.remap(\"SSSS\", [ax0, ax1, ax2, ax3])\n                        T.reads(depth_conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(depth_conv2d_nhwc[v0, v1, v2, v3])\n                        depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def dep_2(placeholder: T.Buffer[(1, 112, 112, 32), \"float32\"], placeholder_1: T.Buffer[(1, 3, 3, 32), \"float32\"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 114, 114, 32], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1 in T.grid(1, 1, 1, 1, 1, 4):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 30, 114, 32):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(114, i1_1 * 28 + ax1)\n                        i2, i3 = T.axis.remap(\"SS\", [ax2, ax3])\n                        T.reads(placeholder[i0, i1 - 1, i2 - 1, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 113 and 1 <= i2 and i2 < 113, placeholder[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype=\"float32\")\n                for i2_1, i3_1, i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(4, 8, 1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2):\n                    with T.block(\"depth_conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1)\n                        h = T.axis.spatial(112, i1_0 * 112 + i1_1 * 28 + i1_2 * 14 + i1_3)\n                        w = T.axis.spatial(112, i2_0 * 112 + i2_1 * 28 + i2_2 * 4 + i2_3)\n                        c = T.axis.spatial(32, i3_0 * 32 + i3_1 * 4 + i3_2 * 2 + i3_3)\n                        rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                        rw = T.axis.reduce(3, i5_0 * 3 + i5_1)\n                        T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c])\n                        T.writes(depth_conv2d_nhwc[n, h, w, c])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            depth_conv2d_nhwc[n, h, w, c] = T.float32(0)\n                        depth_conv2d_nhwc[n, h, w, c] = depth_conv2d_nhwc[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 14]),\n        (\"SamplePerfectTile\", [1, 4, 7, 4]),\n        (\"SamplePerfectTile\", [1, 8, 2, 2]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 14]),\n        (\"SamplePerfectTile\", [1, 4, 7, 4]),\n        (\"SamplePerfectTile\", [1, 8, 2, 2]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 2, 14]),\n        (\"SamplePerfectTile\", [1, 4, 7, 4]),\n        (\"SamplePerfectTile\", [1, 8, 2, 2]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 5),\n    ]\n    mod = create_te_workload(\"DEP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[dep_0, dep_1, dep_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_dil():\n    # fmt: off\n    @T.prim_func\n    def dil_0(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 109, 109, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 109, 1, 4, 1, 1, 1, 2):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 13, 229, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 2 + ax1)\n                        i2 = T.axis.spatial(230, ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                        h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1)\n                        w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2)\n                        co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3)\n                        rh = T.axis.reduce(7, i4_1 + i4_0)\n                        rw = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                        rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc_global[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 1, 109, 8):\n                    with T.block(\"conv2d_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(109, i1_0 + ax1)\n                        v2 = T.axis.spatial(109, ax2)\n                        v3 = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + ax3)\n                        T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                        conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def dil_1(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 109, 109, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 109, 1, 4):\n                for i0_1, i1_1, i2_1, i3_1, i4_0 in T.grid(1, 1, 1, 2, 7):\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 229, 3):\n                        with T.block(\"PadInput\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(230, i1_0 * 2 + i4_0 * 2 + ax1)\n                            i2 = T.axis.spatial(230, ax2)\n                            i3 = T.axis.spatial(3, ax3)\n                            T.reads(inputs[i0, i1 - 3, i2 - 3, i3])\n                            T.writes(PadInput[i0, i1, i2, i3])\n                            PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                    for i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1):\n                        with T.block(\"conv2d_nhwc\"):\n                            n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                            h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1)\n                            w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2)\n                            co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3)\n                            rh = T.axis.reduce(7, i4_1 + i4_0)\n                            rw = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                            rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                            T.writes(conv2d_nhwc_global[n, h, w, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                            conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 1, 109, 16):\n                    with T.block(\"conv2d_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(109, i1_0 + ax1)\n                        v2 = T.axis.spatial(109, ax2)\n                        v3 = T.axis.spatial(64, i3_0 * 16 + ax3)\n                        T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                        conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def dil_2(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            for i0_0, i1_0 in T.grid(1, 109):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 13, 229, 3):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 2 + ax1)\n                        i2 = T.axis.spatial(230, ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(inputs[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 1, 1, 2, 7, 1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                        h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1)\n                        w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2)\n                        co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3)\n                        rh = T.axis.reduce(7, i4_1 + i4_0)\n                        rw = T.axis.reduce(7, i5_0 * 7 + i5_1)\n                        rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [109, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 109, 1]),\n        (\"SamplePerfectTile\", [4, 2, 8, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 7),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [109, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 109, 1]),\n        (\"SamplePerfectTile\", [4, 2, 8, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 8),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [109, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 109, 1]),\n        (\"SamplePerfectTile\", [4, 2, 8, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 7]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 1),\n    ]\n    mod = create_te_workload(\"DIL\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[dil_0, dil_1, dil_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_gmm():\n    # fmt: off\n    @T.prim_func\n    def gmm_0(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            Z_global = T.alloc_buffer([1, 128, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1 in T.grid(1, 4, 2, 1, 1, 8):\n                for i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(128, 1, 16, 1, 1, 1, 2, 8):\n                    with T.block(\"Z\"):\n                        b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3)\n                        i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3)\n                        j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3)\n                        k = T.axis.reduce(128, i3_1 + i3_0)\n                        T.reads(X[b, i, k], Y[b, k, j])\n                        T.writes(Z_global[b, i, j])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            Z_global[b, i, j] = T.float32(0)\n                        Z_global[b, i, j] = Z_global[b, i, j] + X[b, i, k] * Y[b, k, j]\n                for ax0, ax1, ax2 in T.grid(1, 32, 8):\n                    with T.block(\"Z_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(128, i1_0 * 32 + ax1)\n                        v2 = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + ax2)\n                        T.reads(Z_global[v0, v1, v2])\n                        T.writes(Z[v0, v1, v2])\n                        Z[v0, v1, v2] = Z_global[v0, v1, v2]\n    @T.prim_func\n    def gmm_1(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            Z_global = T.alloc_buffer([1, 128, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0 in T.grid(1, 4, 2):\n                for i0_1, i1_1, i2_1, i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(1, 1, 8, 128, 1, 16, 1, 1, 1, 2, 8):\n                    with T.block(\"Z\"):\n                        b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3)\n                        i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3)\n                        j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3)\n                        k = T.axis.reduce(128, i3_1 + i3_0)\n                        T.reads(X[b, i, k], Y[b, k, j])\n                        T.writes(Z_global[b, i, j])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            Z_global[b, i, j] = T.float32(0)\n                        Z_global[b, i, j] = Z_global[b, i, j] + X[b, i, k] * Y[b, k, j]\n                for ax0, ax1, ax2 in T.grid(1, 32, 64):\n                    with T.block(\"Z_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(128, i1_0 * 32 + ax1)\n                        v2 = T.axis.spatial(128, i2_0 * 64 + ax2)\n                        T.reads(Z_global[v0, v1, v2])\n                        T.writes(Z[v0, v1, v2])\n                        Z[v0, v1, v2] = Z_global[v0, v1, v2]\n    @T.prim_func\n    def gmm_2(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1, i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(1, 4, 2, 1, 1, 8, 128, 1, 16, 1, 1, 1, 2, 8):\n                with T.block(\"Z\"):\n                    b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3)\n                    i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3)\n                    j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3)\n                    k = T.axis.reduce(128, i3_1 + i3_0)\n                    T.reads(X[b, i, k], Y[b, k, j])\n                    T.writes(Z[b, i, j])\n                    T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                    with T.init():\n                        Z[b, i, j] = T.float32(0)\n                    Z[b, i, j] = Z[b, i, j] + X[b, i, k] * Y[b, k, j]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 1, 16, 2]),\n        (\"SamplePerfectTile\", [2, 8, 1, 8]),\n        (\"SamplePerfectTile\", [128, 1]),\n        (\"SampleCategorical\", 1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 1, 16, 2]),\n        (\"SamplePerfectTile\", [2, 8, 1, 8]),\n        (\"SamplePerfectTile\", [128, 1]),\n        (\"SampleCategorical\", 1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 1, 16, 2]),\n        (\"SamplePerfectTile\", [2, 8, 1, 8]),\n        (\"SamplePerfectTile\", [128, 1]),\n        (\"SampleCategorical\", 1),\n    ]\n    mod = create_te_workload(\"GMM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[gmm_0, gmm_1, gmm_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_grp():\n    # fmt: off\n    @T.prim_func\n    def grp_0(inputs: T.Buffer[(1, 56, 56, 64), \"float32\"], weight: T.Buffer[(3, 3, 16, 128), \"float32\"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 28, 28, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 1, 2):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 9, 57, 32):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(58, i1_0 * 8 + ax1)\n                        i2 = T.axis.spatial(58, ax2)\n                        i3 = T.axis.spatial(64, i3_0 * 32 + ax3)\n                        T.reads(inputs[i0, i1 - 1, i2 - 1, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 57 and 1 <= i2 and i2 < 57, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype=\"float32\")\n                for i0_1, i1_1, i2_1, i3_1 in T.grid(1, 4, 1, 1):\n                    for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 3, 8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16):\n                        with T.block(\"conv2d_nhwc\"):\n                            n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                            h = T.axis.spatial(28, i1_0 * 4 + i1_1 + i1_2 + i1_3)\n                            w = T.axis.spatial(28, i2_0 * 28 + i2_1 * 28 + i2_2 * 7 + i2_3)\n                            co = T.axis.spatial(128, i3_0 * 64 + i3_1 * 64 + i3_2 * 16 + i3_3)\n                            rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                            rw = T.axis.reduce(3, i5_0 + i5_1)\n                            rc = T.axis.reduce(16, i6_0 * 2 + i6_1)\n                            T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co])\n                            T.writes(conv2d_nhwc_global[n, h, w, co])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                            conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 28, 64):\n                        with T.block(\"conv2d_nhwc_global\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(28, i1_0 * 4 + i1_1 + ax1)\n                            v2 = T.axis.spatial(28, ax2)\n                            v3 = T.axis.spatial(128, i3_0 * 64 + ax3)\n                            T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                            T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                            conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def grp_1(inputs: T.Buffer[(1, 56, 56, 64), \"float32\"], weight: T.Buffer[(3, 3, 16, 128), \"float32\"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\")\n            conv2d_nhwc_global = T.alloc_buffer([1, 28, 28, 128], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 58, 58, 64):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 1, 2):\n                for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 1, 1, 3, 8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2)\n                        h = T.axis.spatial(28, i1_0 * 4 + i1_1_1 + i1_2 + i1_3)\n                        w = T.axis.spatial(28, i2_0 * 28 + i2_1_1 * 28 + i2_2 * 7 + i2_3)\n                        co = T.axis.spatial(128, i3_0 * 64 + i3_1_1 * 64 + i3_2 * 16 + i3_3)\n                        rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                        rw = T.axis.reduce(3, i5_0 + i5_1)\n                        rc = T.axis.reduce(16, i6_0 * 2 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc_global[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc_global[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 4, 28, 64):\n                    with T.block(\"conv2d_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(28, i1_0 * 4 + ax1)\n                        v2 = T.axis.spatial(28, ax2)\n                        v3 = T.axis.spatial(128, i3_0 * 64 + ax3)\n                        T.reads(conv2d_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                        conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def grp_2(inputs: T.Buffer[(1, 56, 56, 64), \"float32\"], weight: T.Buffer[(3, 3, 16, 128), \"float32\"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0 in T.grid(1, 7, 1, 2, 1, 4, 1, 1, 1, 3):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 3, 55, 32):\n                    with T.block(\"PadInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(58, i1_0 * 8 + i1_1 * 2 + ax1)\n                        i2 = T.axis.spatial(58, i5_0 + ax2)\n                        i3 = T.axis.spatial(64, i3_0 * 32 + ax3)\n                        T.reads(inputs[i0, i1 - 1, i2 - 1, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 57 and 1 <= i2 and i2 < 57, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype=\"float32\")\n                for i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16):\n                    with T.block(\"conv2d_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                        h = T.axis.spatial(28, i1_0 * 4 + i1_1 + i1_2 + i1_3)\n                        w = T.axis.spatial(28, i2_0 * 28 + i2_1 * 28 + i2_2 * 7 + i2_3)\n                        co = T.axis.spatial(128, i3_0 * 64 + i3_1 * 64 + i3_2 * 16 + i3_3)\n                        rh = T.axis.reduce(3, i4_0 * 3 + i4_1)\n                        rw = T.axis.reduce(3, i5_0 + i5_1)\n                        rc = T.axis.reduce(16, i6_0 * 2 + i6_1)\n                        T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co])\n                        T.writes(conv2d_nhwc[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_nhwc[n, h, w, co] = T.float32(0)\n                        conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4, 7]),\n        (\"SamplePerfectTile\", [2, 1, 4, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [8, 2]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", 3),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4, 7]),\n        (\"SamplePerfectTile\", [2, 1, 4, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [8, 2]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [7, 4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4, 7]),\n        (\"SamplePerfectTile\", [2, 1, 4, 16]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SamplePerfectTile\", [3, 1]),\n        (\"SamplePerfectTile\", [8, 2]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", 9),\n    ]\n    mod = create_te_workload(\"GRP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[grp_0, grp_1, grp_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_t2d():\n    # fmt: off\n    @T.prim_func\n    def t2d_0(inputs: T.Buffer[(1, 4, 4, 512), \"float32\"], weight: T.Buffer[(4, 4, 512, 256), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 6, 6, 512], dtype=\"float32\")\n            conv2d_transpose_nhwc_global = T.alloc_buffer([1, 8, 8, 256], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 6, 6, 512):\n                with T.block(\"PadInput\"):\n                    i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                    T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n                    PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 5 and 1 <= i2_1 and i2_1 < 5, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1 in T.grid(1, 1, 2, 8, 1, 4, 1, 4):\n                for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8):\n                    with T.block(\"conv2d_transpose_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2)\n                        h = T.axis.spatial(8, i1_0 * 8 + i1_1_1 * 2 + i1_2 * 2 + i1_3)\n                        w = T.axis.spatial(8, i2_0 * 4 + i2_1_1 * 4 + i2_2 * 4 + i2_3)\n                        co = T.axis.spatial(256, i3_0 * 32 + i3_1_1 * 8 + i3_2 * 8 + i3_3)\n                        rh = T.axis.reduce(4, i4_0 * 2 + i4_1)\n                        rw = T.axis.reduce(4, i5_0 * 2 + i5_1)\n                        rc = T.axis.reduce(512, i6_0 * 8 + i6_1)\n                        T.reads(PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], weight[3 - rh, 3 - rw, rc, co])\n                        T.writes(conv2d_transpose_nhwc_global[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_transpose_nhwc_global[n, h, w, co] = T.float32(0)\n                        conv2d_transpose_nhwc_global[n, h, w, co] = conv2d_transpose_nhwc_global[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype=\"float32\") * weight[3 - rh, 3 - rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 2, 4, 8):\n                    with T.block(\"conv2d_transpose_nhwc_global\"):\n                        v0 = T.axis.spatial(1, ax0)\n                        v1 = T.axis.spatial(8, i1_1_1 * 2 + ax1)\n                        v2 = T.axis.spatial(8, i2_0 * 4 + ax2)\n                        v3 = T.axis.spatial(256, i3_0 * 32 + i3_1_1 * 8 + ax3)\n                        T.reads(conv2d_transpose_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3])\n                        conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def t2d_1(inputs: T.Buffer[(1, 4, 4, 512), \"float32\"], weight: T.Buffer[(4, 4, 512, 256), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PadInput = T.alloc_buffer([1, 6, 6, 512], dtype=\"float32\")\n            conv2d_transpose_nhwc_global = T.alloc_buffer([1, 8, 8, 256], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 2, 8):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 6, 4, 512):\n                    with T.block(\"PadInput\"):\n                        i0, i1 = T.axis.remap(\"SS\", [ax0, ax1])\n                        i2 = T.axis.spatial(6, i2_0 * 2 + ax2)\n                        i3 = T.axis.spatial(512, ax3)\n                        T.reads(inputs[i0, i1 - 1, i2 - 1, i3])\n                        T.writes(PadInput[i0, i1, i2, i3])\n                        PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 5 and 1 <= i2 and i2 < 5, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype=\"float32\")\n                for i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 4, 2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8):\n                    with T.block(\"conv2d_transpose_nhwc\"):\n                        n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                        h = T.axis.spatial(8, i1_0 * 8 + i1_1 * 2 + i1_2 * 2 + i1_3)\n                        w = T.axis.spatial(8, i2_0 * 4 + i2_1 * 4 + i2_2 * 4 + i2_3)\n                        co = T.axis.spatial(256, i3_0 * 32 + i3_1 * 8 + i3_2 * 8 + i3_3)\n                        rh = T.axis.reduce(4, i4_0 * 2 + i4_1)\n                        rw = T.axis.reduce(4, i5_0 * 2 + i5_1)\n                        rc = T.axis.reduce(512, i6_0 * 8 + i6_1)\n                        T.reads(PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], weight[3 - rh, 3 - rw, rc, co])\n                        T.writes(conv2d_transpose_nhwc_global[n, h, w, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            conv2d_transpose_nhwc_global[n, h, w, co] = T.float32(0)\n                        conv2d_transpose_nhwc_global[n, h, w, co] = conv2d_transpose_nhwc_global[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype=\"float32\") * weight[3 - rh, 3 - rw, rc, co]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 8, 4, 32):\n                    with T.block(\"conv2d_transpose_nhwc_global\"):\n                        v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                        v2 = T.axis.spatial(8, i2_0 * 4 + ax2)\n                        v3 = T.axis.spatial(256, i3_0 * 32 + ax3)\n                        T.reads(conv2d_transpose_nhwc_global[v0, v1, v2, v3])\n                        T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3])\n                        conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_global[v0, v1, v2, v3]\n    @T.prim_func\n    def t2d_2(inputs: T.Buffer[(1, 4, 4, 512), \"float32\"], weight: T.Buffer[(4, 4, 512, 256), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 8, 1, 4, 1, 4, 2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8):\n                with T.block(\"conv2d_transpose_nhwc\"):\n                    n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                    h = T.axis.spatial(8, i1_0 * 8 + i1_1 * 2 + i1_2 * 2 + i1_3)\n                    w = T.axis.spatial(8, i2_0 * 4 + i2_1 * 4 + i2_2 * 4 + i2_3)\n                    co = T.axis.spatial(256, i3_0 * 32 + i3_1 * 8 + i3_2 * 8 + i3_3)\n                    rh = T.axis.reduce(4, i4_0 * 2 + i4_1)\n                    rw = T.axis.reduce(4, i5_0 * 2 + i5_1)\n                    rc = T.axis.reduce(512, i6_0 * 8 + i6_1)\n                    T.reads(inputs[n, (h + rh) // 2 - 1, (w + rw) // 2 - 1, rc], weight[3 - rh, 3 - rw, rc, co])\n                    T.writes(conv2d_transpose_nhwc[n, h, w, co])\n                    T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                    with T.init():\n                        conv2d_transpose_nhwc[n, h, w, co] = T.float32(0)\n                    conv2d_transpose_nhwc[n, h, w, co] = conv2d_transpose_nhwc[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, T.if_then_else(1 <= (h + rh) // 2 and (h + rh) // 2 < 5 and 1 <= (w + rw) // 2 and (w + rw) // 2 < 5, inputs[n, (h + rh) // 2 - 1, (w + rw) // 2 - 1, rc], T.float32(0), dtype=\"float32\"), T.float32(0), dtype=\"float32\") * weight[3 - rh, 3 - rw, rc, co]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 1, 2]),\n        (\"SamplePerfectTile\", [2, 1, 1, 4]),\n        (\"SamplePerfectTile\", [8, 4, 1, 8]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [64, 8]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 1, 2]),\n        (\"SamplePerfectTile\", [2, 1, 1, 4]),\n        (\"SamplePerfectTile\", [8, 4, 1, 8]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [64, 8]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 3),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 1, 2]),\n        (\"SamplePerfectTile\", [2, 1, 1, 4]),\n        (\"SamplePerfectTile\", [8, 4, 1, 8]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [2, 2]),\n        (\"SamplePerfectTile\", [64, 8]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -2),\n    ]\n    mod = create_te_workload(\"T2D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[t2d_0, t2d_1, t2d_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n        debug_mask=0,\n    )\n\n\ndef test_cpu_nrm():\n    # fmt: off\n    @T.prim_func\n    def nrm_0(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            C = T.alloc_buffer([1], dtype=\"float32\")\n            C_rf = T.alloc_buffer([1, 32768], dtype=\"float32\")\n            for i0, i1_i2_fused_0, i1_i2_fused_1 in T.grid(1, 32768, 2):\n                with T.block(\"C_rf\"):\n                    vi1_i2_fused_0, b, vi1_i2_fused_1 = T.axis.remap(\"SSR\", [i1_i2_fused_0, i0, i1_i2_fused_1])\n                    T.reads(A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256])\n                    T.writes(C_rf[b, vi1_i2_fused_0])\n                    with T.init():\n                        C_rf[b, vi1_i2_fused_0] = T.float32(0)\n                    C_rf[b, vi1_i2_fused_0] = C_rf[b, vi1_i2_fused_0] + A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] * A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256]\n            for i0, i1_i2_fused_0 in T.grid(1, 32768):\n                with T.block(\"C\"):\n                    vi1_i2_fused_0, b = T.axis.remap(\"RS\", [i1_i2_fused_0, i0])\n                    T.reads(C_rf[b, vi1_i2_fused_0])\n                    T.writes(C[b])\n                    with T.init():\n                        C[b] = T.float32(0)\n                    C[b] = C[b] + C_rf[b, vi1_i2_fused_0]\n            for i0 in T.serial(1):\n                with T.block(\"D\"):\n                    b = T.axis.spatial(1, i0)\n                    T.reads(C[b])\n                    T.writes(D[b])\n                    D[b] = T.sqrt(C[b], dtype=\"float32\")\n    @T.prim_func\n    def nrm_1(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            C = T.alloc_buffer([1], dtype=\"float32\")\n            C_rf = T.alloc_buffer([1, 2], dtype=\"float32\")\n            for i0, i1_i2_fused_0, i1_i2_fused_1 in T.grid(1, 32768, 2):\n                with T.block(\"C_rf\"):\n                    vi1_i2_fused_1, b, vi1_i2_fused_0 = T.axis.remap(\"SSR\", [i1_i2_fused_1, i0, i1_i2_fused_0])\n                    T.reads(A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256])\n                    T.writes(C_rf[b, vi1_i2_fused_1])\n                    with T.init():\n                        C_rf[b, vi1_i2_fused_1] = T.float32(0)\n                    C_rf[b, vi1_i2_fused_1] = C_rf[b, vi1_i2_fused_1] + A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] * A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256]\n            for i0, i1_i2_fused_1 in T.grid(1, 2):\n                with T.block(\"C\"):\n                    vi1_i2_fused_1, b = T.axis.remap(\"RS\", [i1_i2_fused_1, i0])\n                    T.reads(C_rf[b, vi1_i2_fused_1])\n                    T.writes(C[b])\n                    with T.init():\n                        C[b] = T.float32(0)\n                    C[b] = C[b] + C_rf[b, vi1_i2_fused_1]\n            for i0 in T.serial(1):\n                with T.block(\"D\"):\n                    b = T.axis.spatial(1, i0)\n                    T.reads(C[b])\n                    T.writes(D[b])\n                    D[b] = T.sqrt(C[b], dtype=\"float32\")\n    @T.prim_func\n    def nrm_2(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            C = T.alloc_buffer([1], dtype=\"float32\")\n            for i0, i1, i2 in T.grid(1, 256, 256):\n                with T.block(\"C\"):\n                    b, i, j = T.axis.remap(\"SRR\", [i0, i1, i2])\n                    T.reads(A[b, i, j])\n                    T.writes(C[b])\n                    with T.init():\n                        C[b] = T.float32(0)\n                    C[b] = C[b] + A[b, i, j] * A[b, i, j]\n            for i0 in T.serial(1):\n                with T.block(\"D\"):\n                    b = T.axis.spatial(1, i0)\n                    T.reads(C[b])\n                    T.writes(D[b])\n                    D[b] = T.sqrt(C[b], dtype=\"float32\")\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [32768, 2]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [32768, 2]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_2 = [\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", -1),\n    ]\n    mod = create_te_workload(\"NRM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[nrm_0, nrm_1, nrm_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_sfm():\n    # fmt: off\n    @T.prim_func\n    def sfm_0(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 4], dtype=\"float32\")\n            for i0, i1_0, i1_1 in T.grid(256, 4, 64):\n                with T.block(\"T_softmax_maxelem_rf\"):\n                    vi1_0, i0_1, vi1_1 = T.axis.remap(\"SSR\", [i1_0, i0, i1_1])\n                    T.reads(A[i0_1, vi1_0 * 64 + vi1_1])\n                    T.writes(T_softmax_maxelem_rf[i0_1, vi1_0])\n                    with T.init():\n                        T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38)\n                    T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_0 * 64 + vi1_1])\n            for i0, i1_0 in T.grid(256, 4):\n                with T.block(\"T_softmax_maxelem\"):\n                    vi1_0, i0_2 = T.axis.remap(\"RS\", [i1_0, i0])\n                    T.reads(T_softmax_maxelem_rf[i0_2, vi1_0])\n                    T.writes(T_softmax_maxelem[i0_2])\n                    with T.init():\n                        T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                    T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0])\n            for i0_3, i1_0, i1_1 in T.grid(256, 16, 16):\n                with T.block(\"T_softmax_expsum_rf\"):\n                    vi1_0, i0_4, vi1_1 = T.axis.remap(\"SSR\", [i1_0, i0_3, i1_1])\n                    T.reads(A[i0_4, vi1_0 * 16 + vi1_1], T_softmax_maxelem[i0_4])\n                    T.writes(T_softmax_expsum_rf[i0_4, vi1_0])\n                    with T.init():\n                        T_softmax_expsum_rf[i0_4, vi1_0] = T.float32(0)\n                    T_softmax_expsum_rf[i0_4, vi1_0] = T_softmax_expsum_rf[i0_4, vi1_0] + T.exp(A[i0_4, vi1_0 * 16 + vi1_1] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n            for i0_5, i1 in T.grid(256, 256):\n                for ax0, ax1 in T.grid(16, 1):\n                    with T.block(\"T_softmax_expsum\"):\n                        vi1_0 = T.axis.reduce(16, ax0)\n                        i0_6 = T.axis.spatial(256, i0_5 + ax1)\n                        T.reads(T_softmax_expsum_rf[i0_6, vi1_0])\n                        T.writes(T_softmax_expsum[i0_6])\n                        with T.init():\n                            T_softmax_expsum[i0_6] = T.float32(0)\n                        T_softmax_expsum[i0_6] = T_softmax_expsum[i0_6] + T_softmax_expsum_rf[i0_6, vi1_0]\n                with T.block(\"T_softmax_norm\"):\n                    i0_7, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                    T.reads(A[i0_7, i1_2], T_softmax_maxelem[i0_7], T_softmax_expsum[i0_7])\n                    T.writes(T_softmax_norm[i0_7, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_7, i1_2] = T.exp(A[i0_7, i1_2] - T_softmax_maxelem[i0_7], dtype=\"float32\") / T_softmax_expsum[i0_7]\n    @T.prim_func\n    def sfm_1(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":16, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 64], dtype=\"float32\")\n            for i0 in T.serial(256):\n                for ax0, ax1, ax2 in T.grid(64, 1, 4):\n                    with T.block(\"T_softmax_maxelem_rf\"):\n                        vi1_1 = T.axis.spatial(64, ax0)\n                        i0_1 = T.axis.spatial(256, i0 + ax1)\n                        vi1_0 = T.axis.reduce(4, ax2)\n                        T.reads(A[i0_1, vi1_0 * 64 + vi1_1])\n                        T.writes(T_softmax_maxelem_rf[i0_1, vi1_1])\n                        with T.init():\n                            T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_0 * 64 + vi1_1])\n                for i1 in T.serial(256):\n                    for ax0, ax1 in T.grid(64, 1):\n                        with T.block(\"T_softmax_maxelem\"):\n                            vi1_1 = T.axis.reduce(64, ax0)\n                            i0_2 = T.axis.spatial(256, i0 + ax1)\n                            T.reads(T_softmax_maxelem_rf[i0_2, vi1_1])\n                            T.writes(T_softmax_maxelem[i0_2])\n                            with T.init():\n                                T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                            T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1])\n                    with T.block(\"T_softmax_exp\"):\n                        i0_3, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(A[i0_3, i1_1], T_softmax_maxelem[i0_3])\n                        T.writes(T_softmax_exp[i0_3, i1_1])\n                        T_softmax_exp[i0_3, i1_1] = T.exp(A[i0_3, i1_1] - T_softmax_maxelem[i0_3], dtype=\"float32\")\n            for i0_4, i1_0, i1_1_1 in T.grid(256, 16, 16):\n                with T.block(\"T_softmax_expsum_rf\"):\n                    vi1_0, i0_5, vi1_1 = T.axis.remap(\"SSR\", [i1_0, i0_4, i1_1_1])\n                    T.reads(T_softmax_exp[i0_5, vi1_0 * 16 + vi1_1])\n                    T.writes(T_softmax_expsum_rf[i0_5, vi1_0])\n                    with T.init():\n                        T_softmax_expsum_rf[i0_5, vi1_0] = T.float32(0)\n                    T_softmax_expsum_rf[i0_5, vi1_0] = T_softmax_expsum_rf[i0_5, vi1_0] + T_softmax_exp[i0_5, vi1_0 * 16 + vi1_1]\n            for i0_6, i1_0 in T.grid(256, 16):\n                with T.block(\"T_softmax_expsum\"):\n                    vi1_0, i0_7 = T.axis.remap(\"RS\", [i1_0, i0_6])\n                    T.reads(T_softmax_expsum_rf[i0_7, vi1_0])\n                    T.writes(T_softmax_expsum[i0_7])\n                    with T.init():\n                        T_softmax_expsum[i0_7] = T.float32(0)\n                    T_softmax_expsum[i0_7] = T_softmax_expsum[i0_7] + T_softmax_expsum_rf[i0_7, vi1_0]\n            for i0_8, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_norm\"):\n                    i0_9, i1_2 = T.axis.remap(\"SS\", [i0_8, i1])\n                    T.reads(T_softmax_exp[i0_9, i1_2], T_softmax_expsum[i0_9])\n                    T.writes(T_softmax_norm[i0_9, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_9, i1_2] = T_softmax_exp[i0_9, i1_2] / T_softmax_expsum[i0_9]\n    @T.prim_func\n    def sfm_2(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            for i0, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_maxelem\"):\n                    i0_1, k = T.axis.remap(\"SR\", [i0, i1])\n                    T.reads(A[i0_1, k])\n                    T.writes(T_softmax_maxelem[i0_1])\n                    with T.init():\n                        T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38)\n                    T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n            for i0, i1_0, i1_1 in T.grid(256, 16, 16):\n                with T.block(\"T_softmax_expsum_rf\"):\n                    vi1_0, i0_2, vi1_1 = T.axis.remap(\"SSR\", [i1_0, i0, i1_1])\n                    T.reads(A[i0_2, vi1_0 * 16 + vi1_1], T_softmax_maxelem[i0_2])\n                    T.writes(T_softmax_expsum_rf[i0_2, vi1_0])\n                    with T.init():\n                        T_softmax_expsum_rf[i0_2, vi1_0] = T.float32(0)\n                    T_softmax_expsum_rf[i0_2, vi1_0] = T_softmax_expsum_rf[i0_2, vi1_0] + T.exp(A[i0_2, vi1_0 * 16 + vi1_1] - T_softmax_maxelem[i0_2], dtype=\"float32\")\n            for i0_3, i1_0 in T.grid(256, 16):\n                with T.block(\"T_softmax_expsum\"):\n                    vi1_0, i0_4 = T.axis.remap(\"RS\", [i1_0, i0_3])\n                    T.reads(T_softmax_expsum_rf[i0_4, vi1_0])\n                    T.writes(T_softmax_expsum[i0_4])\n                    with T.init():\n                        T_softmax_expsum[i0_4] = T.float32(0)\n                    T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_expsum_rf[i0_4, vi1_0]\n            for i0_5, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_norm\"):\n                    i0_6, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                    T.reads(A[i0_6, i1_2], T_softmax_maxelem[i0_6], T_softmax_expsum[i0_6])\n                    T.writes(T_softmax_norm[i0_6, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_6, i1_2] = T.exp(A[i0_6, i1_2] - T_softmax_maxelem[i0_6], dtype=\"float32\") / T_softmax_expsum[i0_6]\n    @T.prim_func\n    def sfm_3(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 256], dtype=\"float32\")\n            for i0, i1 in T.grid(256, 256):\n                for ax0, ax1, ax2 in T.grid(256, 1, 1):\n                    with T.block(\"T_softmax_maxelem_rf\"):\n                        vi1_0 = T.axis.spatial(256, ax0)\n                        i0_1 = T.axis.spatial(256, i0 + ax1)\n                        vi1_1 = T.axis.reduce(1, ax2)\n                        T.reads(A[i0_1, vi1_1 + vi1_0])\n                        T.writes(T_softmax_maxelem_rf[i0_1, vi1_0])\n                        with T.init():\n                            T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_1 + vi1_0])\n                for ax0, ax1 in T.grid(256, 1):\n                    with T.block(\"T_softmax_maxelem\"):\n                        vi1_0 = T.axis.reduce(256, ax0)\n                        i0_2 = T.axis.spatial(256, i0 + ax1)\n                        T.reads(T_softmax_maxelem_rf[i0_2, vi1_0])\n                        T.writes(T_softmax_maxelem[i0_2])\n                        with T.init():\n                            T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0])\n                for ax0, ax1 in T.grid(1, 256):\n                    with T.block(\"T_softmax_exp\"):\n                        i0_3 = T.axis.spatial(256, i0 + ax0)\n                        i1_1 = T.axis.spatial(256, ax1)\n                        T.reads(A[i0_3, i1_1], T_softmax_maxelem[i0_3])\n                        T.writes(T_softmax_exp[i0_3, i1_1])\n                        T_softmax_exp[i0_3, i1_1] = T.exp(A[i0_3, i1_1] - T_softmax_maxelem[i0_3], dtype=\"float32\")\n                for ax0 in T.serial(16):\n                    for ax0_1, ax1, ax2 in T.grid(1, 1, 16):\n                        with T.block(\"T_softmax_expsum_rf\"):\n                            vi1_1 = T.axis.spatial(16, ax0 + ax0_1)\n                            i0_4 = T.axis.spatial(256, i0 + ax1)\n                            vi1_0 = T.axis.reduce(16, ax2)\n                            T.reads(T_softmax_exp[i0_4, vi1_0 * 16 + vi1_1])\n                            T.writes(T_softmax_expsum_rf[i0_4, vi1_1])\n                            with T.init():\n                                T_softmax_expsum_rf[i0_4, vi1_1] = T.float32(0)\n                            T_softmax_expsum_rf[i0_4, vi1_1] = T_softmax_expsum_rf[i0_4, vi1_1] + T_softmax_exp[i0_4, vi1_0 * 16 + vi1_1]\n                    for ax1 in T.serial(1):\n                        with T.block(\"T_softmax_expsum\"):\n                            vi1_1 = T.axis.reduce(16, ax0)\n                            i0_5 = T.axis.spatial(256, i0 + ax1)\n                            T.reads(T_softmax_expsum_rf[i0_5, vi1_1])\n                            T.writes(T_softmax_expsum[i0_5])\n                            with T.init():\n                                T_softmax_expsum[i0_5] = T.float32(0)\n                            T_softmax_expsum[i0_5] = T_softmax_expsum[i0_5] + T_softmax_expsum_rf[i0_5, vi1_1]\n                with T.block(\"T_softmax_norm\"):\n                    i0_6, i1_2 = T.axis.remap(\"SS\", [i0, i1])\n                    T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6])\n                    T.writes(T_softmax_norm[i0_6, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6]\n    @T.prim_func\n    def sfm_4(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":0, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 1], dtype=\"float32\")\n            for i0 in T.serial(256):\n                for ax0, ax1, ax2 in T.grid(1, 1, 256):\n                    with T.block(\"T_softmax_maxelem_rf\"):\n                        vi1_1 = T.axis.spatial(1, ax0)\n                        i0_1 = T.axis.spatial(256, i0 + ax1)\n                        vi1_0 = T.axis.reduce(256, ax2)\n                        T.reads(A[i0_1, vi1_1 + vi1_0])\n                        T.writes(T_softmax_maxelem_rf[i0_1, vi1_1])\n                        with T.init():\n                            T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_1 + vi1_0])\n                for i1_1 in T.serial(1):\n                    with T.block(\"T_softmax_maxelem\"):\n                        vi1_1, i0_2 = T.axis.remap(\"RS\", [i1_1, i0])\n                        T.reads(T_softmax_maxelem_rf[i0_2, vi1_1])\n                        T.writes(T_softmax_maxelem[i0_2])\n                        with T.init():\n                            T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1])\n            for i0_3, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_exp\"):\n                    i0_4, i1_2 = T.axis.remap(\"SS\", [i0_3, i1])\n                    T.reads(A[i0_4, i1_2], T_softmax_maxelem[i0_4])\n                    T.writes(T_softmax_exp[i0_4, i1_2])\n                    T_softmax_exp[i0_4, i1_2] = T.exp(A[i0_4, i1_2] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n            for i0_5, i1_0, i1_1 in T.grid(256, 16, 16):\n                with T.block(\"T_softmax_expsum_rf\"):\n                    vi1_1, i0_6, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0_5, i1_0])\n                    T.reads(T_softmax_exp[i0_6, vi1_0 * 16 + vi1_1])\n                    T.writes(T_softmax_expsum_rf[i0_6, vi1_1])\n                    with T.init():\n                        T_softmax_expsum_rf[i0_6, vi1_1] = T.float32(0)\n                    T_softmax_expsum_rf[i0_6, vi1_1] = T_softmax_expsum_rf[i0_6, vi1_1] + T_softmax_exp[i0_6, vi1_0 * 16 + vi1_1]\n            for i0_7, i1_1 in T.grid(256, 16):\n                with T.block(\"T_softmax_expsum\"):\n                    vi1_1, i0_8 = T.axis.remap(\"RS\", [i1_1, i0_7])\n                    T.reads(T_softmax_expsum_rf[i0_8, vi1_1])\n                    T.writes(T_softmax_expsum[i0_8])\n                    with T.init():\n                        T_softmax_expsum[i0_8] = T.float32(0)\n                    T_softmax_expsum[i0_8] = T_softmax_expsum[i0_8] + T_softmax_expsum_rf[i0_8, vi1_1]\n            for i0_9, i1_3 in T.grid(256, 256):\n                with T.block(\"T_softmax_norm\"):\n                    i0_10, i1_4 = T.axis.remap(\"SS\", [i0_9, i1_3])\n                    T.reads(T_softmax_exp[i0_10, i1_4], T_softmax_expsum[i0_10])\n                    T.writes(T_softmax_norm[i0_10, i1_4])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_10, i1_4] = T_softmax_exp[i0_10, i1_4] / T_softmax_expsum[i0_10]\n    @T.prim_func\n    def sfm_5(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype=\"float32\")\n            for i0 in T.serial(256):\n                for ax0, ax1 in T.grid(1, 256):\n                    with T.block(\"T_softmax_maxelem\"):\n                        i0_1 = T.axis.spatial(256, i0 + ax0)\n                        k = T.axis.reduce(256, ax1)\n                        T.reads(A[i0_1, k])\n                        T.writes(T_softmax_maxelem[i0_1])\n                        with T.init():\n                            T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n                for ax0, ax1 in T.grid(1, 256):\n                    with T.block(\"T_softmax_exp\"):\n                        i0_2 = T.axis.spatial(256, i0 + ax0)\n                        i1 = T.axis.spatial(256, ax1)\n                        T.reads(A[i0_2, i1], T_softmax_maxelem[i0_2])\n                        T.writes(T_softmax_exp[i0_2, i1])\n                        T_softmax_exp[i0_2, i1] = T.exp(A[i0_2, i1] - T_softmax_maxelem[i0_2], dtype=\"float32\")\n                for ax0 in T.serial(16):\n                    for ax0_1, ax1, ax2 in T.grid(1, 1, 16):\n                        with T.block(\"T_softmax_expsum_rf\"):\n                            vi1_1 = T.axis.spatial(16, ax0 + ax0_1)\n                            i0_3 = T.axis.spatial(256, i0 + ax1)\n                            vi1_0 = T.axis.reduce(16, ax2)\n                            T.reads(T_softmax_exp[i0_3, vi1_0 * 16 + vi1_1])\n                            T.writes(T_softmax_expsum_rf[i0_3, vi1_1])\n                            with T.init():\n                                T_softmax_expsum_rf[i0_3, vi1_1] = T.float32(0)\n                            T_softmax_expsum_rf[i0_3, vi1_1] = T_softmax_expsum_rf[i0_3, vi1_1] + T_softmax_exp[i0_3, vi1_0 * 16 + vi1_1]\n                    for ax1 in T.serial(1):\n                        with T.block(\"T_softmax_expsum\"):\n                            vi1_1 = T.axis.reduce(16, ax0)\n                            i0_4 = T.axis.spatial(256, i0 + ax1)\n                            T.reads(T_softmax_expsum_rf[i0_4, vi1_1])\n                            T.writes(T_softmax_expsum[i0_4])\n                            with T.init():\n                                T_softmax_expsum[i0_4] = T.float32(0)\n                            T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_expsum_rf[i0_4, vi1_1]\n                for i1 in T.serial(256):\n                    with T.block(\"T_softmax_norm\"):\n                        i0_5, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(T_softmax_exp[i0_5, i1_1], T_softmax_expsum[i0_5])\n                        T.writes(T_softmax_norm[i0_5, i1_1])\n                        T.block_attr({\"axis\":1})\n                        T_softmax_norm[i0_5, i1_1] = T_softmax_exp[i0_5, i1_1] / T_softmax_expsum[i0_5]\n    @T.prim_func\n    def sfm_6(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 64], dtype=\"float32\")\n            for i0 in T.serial(256):\n                for ax0, ax1, ax2 in T.grid(64, 1, 4):\n                    with T.block(\"T_softmax_maxelem_rf\"):\n                        vi1_0 = T.axis.spatial(64, ax0)\n                        i0_1 = T.axis.spatial(256, i0 + ax1)\n                        vi1_1 = T.axis.reduce(4, ax2)\n                        T.reads(A[i0_1, vi1_0 * 4 + vi1_1])\n                        T.writes(T_softmax_maxelem_rf[i0_1, vi1_0])\n                        with T.init():\n                            T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_0 * 4 + vi1_1])\n                for i1_0 in T.serial(64):\n                    with T.block(\"T_softmax_maxelem\"):\n                        vi1_0, i0_2 = T.axis.remap(\"RS\", [i1_0, i0])\n                        T.reads(T_softmax_maxelem_rf[i0_2, vi1_0])\n                        T.writes(T_softmax_maxelem[i0_2])\n                        with T.init():\n                            T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0])\n            for i0_3, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_expsum\"):\n                    i0_4, k = T.axis.remap(\"SR\", [i0_3, i1])\n                    T.reads(A[i0_4, k], T_softmax_maxelem[i0_4])\n                    T.writes(T_softmax_expsum[i0_4])\n                    with T.init():\n                        T_softmax_expsum[i0_4] = T.float32(0)\n                    T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T.exp(A[i0_4, k] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n            for i0_5, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_norm\"):\n                    i0_6, i1_1 = T.axis.remap(\"SS\", [i0_5, i1])\n                    T.reads(A[i0_6, i1_1], T_softmax_maxelem[i0_6], T_softmax_expsum[i0_6])\n                    T.writes(T_softmax_norm[i0_6, i1_1])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_6, i1_1] = T.exp(A[i0_6, i1_1] - T_softmax_maxelem[i0_6], dtype=\"float32\") / T_softmax_expsum[i0_6]\n    @T.prim_func\n    def sfm_7(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_maxelem_rf = T.alloc_buffer([256, 4], dtype=\"float32\")\n            for i0, i1_0, i1_1 in T.grid(256, 64, 4):\n                with T.block(\"T_softmax_maxelem_rf\"):\n                    vi1_1, i0_1, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n                    T.reads(A[i0_1, vi1_0 * 4 + vi1_1])\n                    T.writes(T_softmax_maxelem_rf[i0_1, vi1_1])\n                    with T.init():\n                        T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38)\n                    T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_0 * 4 + vi1_1])\n            for i0, i1_1 in T.grid(256, 4):\n                with T.block(\"T_softmax_maxelem\"):\n                    vi1_1, i0_2 = T.axis.remap(\"RS\", [i1_1, i0])\n                    T.reads(T_softmax_maxelem_rf[i0_2, vi1_1])\n                    T.writes(T_softmax_maxelem[i0_2])\n                    with T.init():\n                        T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38)\n                    T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1])\n            for i0_3, i1 in T.grid(256, 256):\n                for ax0, ax1 in T.grid(1, 256):\n                    with T.block(\"T_softmax_expsum\"):\n                        i0_4 = T.axis.spatial(256, i0_3 + ax0)\n                        k = T.axis.reduce(256, ax1)\n                        T.reads(A[i0_4, k], T_softmax_maxelem[i0_4])\n                        T.writes(T_softmax_expsum[i0_4])\n                        with T.init():\n                            T_softmax_expsum[i0_4] = T.float32(0)\n                        T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T.exp(A[i0_4, k] - T_softmax_maxelem[i0_4], dtype=\"float32\")\n                with T.block(\"T_softmax_norm\"):\n                    i0_5, i1_2 = T.axis.remap(\"SS\", [i0_3, i1])\n                    T.reads(A[i0_5, i1_2], T_softmax_maxelem[i0_5], T_softmax_expsum[i0_5])\n                    T.writes(T_softmax_norm[i0_5, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_5, i1_2] = T.exp(A[i0_5, i1_2] - T_softmax_maxelem[i0_5], dtype=\"float32\") / T_softmax_expsum[i0_5]\n    @T.prim_func\n    def sfm_8(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_exp = T.alloc_buffer([256, 256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            for i0 in T.serial(256):\n                for ax0, ax1 in T.grid(1, 256):\n                    with T.block(\"T_softmax_maxelem\"):\n                        i0_1 = T.axis.spatial(256, i0 + ax0)\n                        k = T.axis.reduce(256, ax1)\n                        T.reads(A[i0_1, k])\n                        T.writes(T_softmax_maxelem[i0_1])\n                        with T.init():\n                            T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38)\n                        T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k])\n                for i1 in T.serial(256):\n                    with T.block(\"T_softmax_exp\"):\n                        i0_2, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n                        T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2])\n                        T.writes(T_softmax_exp[i0_2, i1_1])\n                        T_softmax_exp[i0_2, i1_1] = T.exp(A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype=\"float32\")\n            for i0_3, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_expsum\"):\n                    i0_4, k = T.axis.remap(\"SR\", [i0_3, i1])\n                    T.reads(T_softmax_exp[i0_4, k])\n                    T.writes(T_softmax_expsum[i0_4])\n                    with T.init():\n                        T_softmax_expsum[i0_4] = T.float32(0)\n                    T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k]\n            for i0_5, i1 in T.grid(256, 256):\n                with T.block(\"T_softmax_norm\"):\n                    i0_6, i1_2 = T.axis.remap(\"SS\", [i0_5, i1])\n                    T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6])\n                    T.writes(T_softmax_norm[i0_6, i1_2])\n                    T.block_attr({\"axis\":1})\n                    T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SamplePerfectTile\", [4, 64]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -2),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SamplePerfectTile\", [4, 64]),\n        (\"SampleCategorical\", 1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 0),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -2),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_3 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SamplePerfectTile\", [256, 1]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 2),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 1),\n    ]\n    decision_4 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SamplePerfectTile\", [256, 1]),\n        (\"SampleCategorical\", 0),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", 0),\n    ]\n    decision_5 = [\n        (\"SamplePerfectTile\", [16, 16]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 0),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 0),\n        (\"SampleComputeLocation\", 0),\n    ]\n    decision_6 = [\n        (\"SamplePerfectTile\", [64, 4]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -2),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", 0),\n    ]\n    decision_7 = [\n        (\"SamplePerfectTile\", [64, 4]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", -2),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_8 = [\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", -1),\n        (\"SampleComputeLocation\", 0),\n    ]\n    mod = create_te_workload(\"SFM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[sfm_0, sfm_1, sfm_2, sfm_3, sfm_4, sfm_5, sfm_6, sfm_7, sfm_8],\n        expected_decisions=[\n            decision_0,\n            decision_1,\n            decision_2,\n            decision_3,\n            decision_4,\n            decision_5,\n            decision_6,\n            decision_7,\n            decision_8,\n        ],\n    )\n\n\ndef test_cpu_cbr():\n    # fmt: off\n    @T.prim_func\n    def cbr_0(data: T.Buffer[(1, 224, 224, 3), \"float32\"], kernel: T.Buffer[(7, 7, 3, 64), \"float32\"], bias: T.Buffer[64, \"float32\"], bn_offset: T.Buffer[64, \"float32\"], bn_scale: T.Buffer[64, \"float32\"], compute: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 2, 7, 1, 1, 2, 2, 32, 7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2):\n                with T.block(\"Conv2dOutput\"):\n                    nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                    yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3)\n                    xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3)\n                    ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3)\n                    ry = T.axis.reduce(7, i4_1 + i4_0)\n                    rx = T.axis.reduce(7, i5_0 + i5_1)\n                    rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                    T.reads(data[nn, yy * 2 + ry - 3, xx * 2 + rx - 3, rc], kernel[ry, rx, rc, ff])\n                    T.writes(Conv2dOutput[nn, yy, xx, ff])\n                    T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                    with T.init():\n                        Conv2dOutput[nn, yy, xx, ff] = T.float32(0)\n                    Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + T.if_then_else(3 <= yy * 2 + ry and yy * 2 + ry < 227 and 3 <= xx * 2 + rx and xx * 2 + rx < 227, data[nn, yy * 2 + ry - 3, xx * 2 + rx - 3, rc], T.float32(0), dtype=\"float32\") * kernel[ry, rx, rc, ff]\n            for i0, i1, i2, i3 in T.grid(1, 112, 112, 64):\n                with T.block(\"compute\"):\n                    i0_4, i1_4, i2_4, i3_4 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(Conv2dOutput[i0_4, i1_4, i2_4, i3_4], bias[i3_4], bn_scale[i3_4], bn_offset[i3_4])\n                    T.writes(compute[i0_4, i1_4, i2_4, i3_4])\n                    compute[i0_4, i1_4, i2_4, i3_4] = T.max((Conv2dOutput[i0_4, i1_4, i2_4, i3_4] + bias[i3_4]) * bn_scale[i3_4] + bn_offset[i3_4], T.float32(0))\n    @T.prim_func\n    def cbr_1(data: T.Buffer[(1, 224, 224, 3), \"float32\"], kernel: T.Buffer[(7, 7, 3, 64), \"float32\"], bias: T.Buffer[64, \"float32\"], bn_offset: T.Buffer[64, \"float32\"], bn_scale: T.Buffer[64, \"float32\"], compute: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            PaddedInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0 in T.grid(1, 2):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 117, 229, 3):\n                    with T.block(\"PaddedInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 112 + ax1)\n                        i2 = T.axis.spatial(230, ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(data[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PaddedInput[i0, i1, i2, i3])\n                        PaddedInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, data[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(7, 1, 1, 2, 2, 32):\n                    for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2):\n                        with T.block(\"Conv2dOutput\"):\n                            nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                            yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3)\n                            xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3)\n                            ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3)\n                            ry = T.axis.reduce(7, i4_1 + i4_0)\n                            rx = T.axis.reduce(7, i5_0 + i5_1)\n                            rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            T.reads(PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel[ry, rx, rc, ff])\n                            T.writes(Conv2dOutput[nn, yy, xx, ff])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                Conv2dOutput[nn, yy, xx, ff] = T.float32(0)\n                            Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel[ry, rx, rc, ff]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 28, 8, 2):\n                        with T.block(\"compute\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + ax1)\n                            i2 = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + ax2)\n                            i3 = T.axis.spatial(64, i3_1 * 2 + ax3)\n                            T.reads(Conv2dOutput[i0, i1, i2, i3], bias[i3], bn_scale[i3], bn_offset[i3])\n                            T.writes(compute[i0, i1, i2, i3])\n                            compute[i0, i1, i2, i3] = T.max((Conv2dOutput[i0, i1, i2, i3] + bias[i3]) * bn_scale[i3] + bn_offset[i3], T.float32(0))\n    @T.prim_func\n    def cbr_2(data: T.Buffer[(1, 224, 224, 3), \"float32\"], kernel: T.Buffer[(7, 7, 3, 64), \"float32\"], bias: T.Buffer[64, \"float32\"], bn_offset: T.Buffer[64, \"float32\"], bn_scale: T.Buffer[64, \"float32\"], compute: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            PaddedInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n            Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\")\n            for i0_0, i1_0 in T.grid(1, 2):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 117, 229, 3):\n                    with T.block(\"PaddedInput\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(230, i1_0 * 112 + ax1)\n                        i2 = T.axis.spatial(230, ax2)\n                        i3 = T.axis.spatial(3, ax3)\n                        T.reads(data[i0, i1 - 3, i2 - 3, i3])\n                        T.writes(PaddedInput[i0, i1, i2, i3])\n                        PaddedInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, data[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype=\"float32\")\n                for i2_0, i3_0 in T.grid(7, 1):\n                    for i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 2, 2, 32, 7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2):\n                        with T.block(\"Conv2dOutput\"):\n                            nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2)\n                            yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3)\n                            xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3)\n                            ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3)\n                            ry = T.axis.reduce(7, i4_1 + i4_0)\n                            rx = T.axis.reduce(7, i5_0 + i5_1)\n                            rc = T.axis.reduce(3, i6_0 * 3 + i6_1)\n                            T.reads(PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel[ry, rx, rc, ff])\n                            T.writes(Conv2dOutput[nn, yy, xx, ff])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                Conv2dOutput[nn, yy, xx, ff] = T.float32(0)\n                            Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel[ry, rx, rc, ff]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 56, 16, 64):\n                        with T.block(\"compute\"):\n                            i0 = T.axis.spatial(1, ax0)\n                            i1 = T.axis.spatial(112, i1_0 * 56 + ax1)\n                            i2 = T.axis.spatial(112, i2_0 * 16 + ax2)\n                            i3 = T.axis.spatial(64, ax3)\n                            T.reads(Conv2dOutput[i0, i1, i2, i3], bias[i3], bn_scale[i3], bn_offset[i3])\n                            T.writes(compute[i0, i1, i2, i3])\n                            compute[i0, i1, i2, i3] = T.max((Conv2dOutput[i0, i1, i2, i3] + bias[i3]) * bn_scale[i3] + bn_offset[i3], T.float32(0))\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 2, 1, 28]),\n        (\"SamplePerfectTile\", [7, 2, 4, 2]),\n        (\"SamplePerfectTile\", [1, 32, 1, 2]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", -2),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 2, 1, 28]),\n        (\"SamplePerfectTile\", [7, 2, 4, 2]),\n        (\"SamplePerfectTile\", [1, 32, 1, 2]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 2, 1, 28]),\n        (\"SamplePerfectTile\", [7, 2, 4, 2]),\n        (\"SamplePerfectTile\", [1, 32, 1, 2]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [7, 1]),\n        (\"SamplePerfectTile\", [1, 3]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 1),\n    ]\n    mod = create_te_workload(\"CBR\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cbr_0, cbr_1, cbr_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\ndef test_cpu_tbg():\n    # fmt: off\n    @T.prim_func\n    def tbg_0(query: T.Buffer[(1, 128, 12, 64), \"float32\"], value: T.Buffer[(1, 128, 12, 64), \"float32\"], C: T.Buffer[(1, 12, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            query_T = T.alloc_buffer([1, 12, 128, 64], dtype=\"float32\")\n            value_T = T.alloc_buffer([1, 12, 64, 128], dtype=\"float32\")\n            C_global = T.alloc_buffer([1, 12, 128, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1 in T.grid(1, 1, 1, 2, 1, 6, 2):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 64):\n                    with T.block(\"value_T\"):\n                        b = T.axis.spatial(1, ax0)\n                        h = T.axis.spatial(12, i1_1 * 2 + ax1)\n                        d = T.axis.spatial(64, ax2)\n                        l = T.axis.spatial(128, i3_0 * 64 + ax3)\n                        T.reads(value[b, l, h, d])\n                        T.writes(value_T[b, h, d, l])\n                        value_T[b, h, d, l] = value[b, l, h, d]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 64):\n                    with T.block(\"query_T\"):\n                        b = T.axis.spatial(1, ax0)\n                        h = T.axis.spatial(12, i1_1 * 2 + ax1)\n                        l = T.axis.spatial(128, i2_1 * 64 + ax2)\n                        d = T.axis.spatial(64, ax3)\n                        T.reads(query[b, l, h, d])\n                        T.writes(query_T[b, h, l, d])\n                        query_T[b, h, l, d] = query[b, l, h, d]\n                for i3_1 in T.serial(8):\n                    for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 2, 4, 64, 1, 1, 32, 2):\n                        with T.block(\"C\"):\n                            b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                            h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3)\n                            i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3)\n                            j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3)\n                            k = T.axis.reduce(64, i4_0 * 64 + i4_1)\n                            T.reads(query_T[b, h, i, k], value_T[b, h, k, j])\n                            T.writes(C_global[b, h, i, j])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                C_global[b, h, i, j] = T.float32(0)\n                            C_global[b, h, i, j] = C_global[b, h, i, j] + query_T[b, h, i, k] * value_T[b, h, k, j]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 8):\n                        with T.block(\"C_global\"):\n                            v0 = T.axis.spatial(1, ax0)\n                            v1 = T.axis.spatial(12, i1_1 * 2 + ax1)\n                            v2 = T.axis.spatial(128, i2_1 * 64 + ax2)\n                            v3 = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + ax3)\n                            T.reads(C_global[v0, v1, v2, v3])\n                            T.writes(C[v0, v1, v2, v3])\n                            C[v0, v1, v2, v3] = C_global[v0, v1, v2, v3]\n    @T.prim_func\n    def tbg_1(query: T.Buffer[(1, 128, 12, 64), \"float32\"], value: T.Buffer[(1, 128, 12, 64), \"float32\"], C: T.Buffer[(1, 12, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            query_T = T.alloc_buffer([1, 12, 128, 64], dtype=\"float32\")\n            value_T = T.alloc_buffer([1, 12, 64, 128], dtype=\"float32\")\n            C_global = T.alloc_buffer([1, 12, 128, 128], dtype=\"float32\")\n            for i0, i1, i2, i3 in T.grid(1, 12, 128, 64):\n                with T.block(\"query_T\"):\n                    b, h, l, d = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(query[b, l, h, d])\n                    T.writes(query_T[b, h, l, d])\n                    query_T[b, h, l, d] = query[b, l, h, d]\n            for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 1, 2):\n                for i0_1, i1_1, i2_1, i3_1, i4_0, i0_2, i1_2, i2_2, i3_2, i4_1 in T.grid(1, 6, 2, 8, 1, 1, 2, 2, 4, 64):\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 2):\n                        with T.block(\"value_T\"):\n                            b = T.axis.spatial(1, ax0)\n                            h = T.axis.spatial(12, i1_1 * 2 + i1_2 + ax1)\n                            d = T.axis.spatial(64, i4_1 + ax2)\n                            l = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + ax3)\n                            T.reads(value[b, l, h, d])\n                            T.writes(value_T[b, h, d, l])\n                            value_T[b, h, d, l] = value[b, l, h, d]\n                    for i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 32, 2):\n                        with T.block(\"C\"):\n                            b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                            h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3)\n                            i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3)\n                            j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3)\n                            k = T.axis.reduce(64, i4_0 * 64 + i4_1)\n                            T.reads(query_T[b, h, i, k], value_T[b, h, k, j])\n                            T.writes(C_global[b, h, i, j])\n                            T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                            with T.init():\n                                C_global[b, h, i, j] = T.float32(0)\n                            C_global[b, h, i, j] = C_global[b, h, i, j] + query_T[b, h, i, k] * value_T[b, h, k, j]\n                for ax0, ax1, ax2, ax3 in T.grid(1, 12, 128, 64):\n                    with T.block(\"C_global\"):\n                        v0, v1, v2 = T.axis.remap(\"SSS\", [ax0, ax1, ax2])\n                        v3 = T.axis.spatial(128, i3_0 * 64 + ax3)\n                        T.reads(C_global[v0, v1, v2, v3])\n                        T.writes(C[v0, v1, v2, v3])\n                        C[v0, v1, v2, v3] = C_global[v0, v1, v2, v3]\n    @T.prim_func\n    def tbg_2(query: T.Buffer[(1, 128, 12, 64), \"float32\"], value: T.Buffer[(1, 128, 12, 64), \"float32\"], C: T.Buffer[(1, 12, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":512, \"meta_schedule.vectorize\":64})\n            value_T = T.alloc_buffer([1, 12, 64, 128], dtype=\"float32\")\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 1, 1, 2, 1, 6, 2, 8):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 8):\n                    with T.block(\"value_T\"):\n                        b = T.axis.spatial(1, ax0)\n                        h = T.axis.spatial(12, i1_1 * 2 + ax1)\n                        d = T.axis.spatial(64, ax2)\n                        l = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + ax3)\n                        T.reads(value[b, l, h, d])\n                        T.writes(value_T[b, h, d, l])\n                        value_T[b, h, d, l] = value[b, l, h, d]\n                for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 2, 4, 64, 1, 1, 32, 2):\n                    with T.block(\"C\"):\n                        b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0)\n                        h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3)\n                        i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3)\n                        j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3)\n                        k = T.axis.reduce(64, i4_0 * 64 + i4_1)\n                        T.reads(query[b, i, h, k], value_T[b, h, k, j])\n                        T.writes(C[b, h, i, j])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        with T.init():\n                            C[b, h, i, j] = T.float32(0)\n                        C[b, h, i, j] = C[b, h, i, j] + query[b, i, h, k] * value_T[b, h, k, j]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 6, 2, 1]),\n        (\"SamplePerfectTile\", [1, 2, 2, 32]),\n        (\"SamplePerfectTile\", [2, 8, 4, 2]),\n        (\"SamplePerfectTile\", [1, 64]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 6),\n        (\"SampleComputeLocation\", 6),\n    ]\n    decision_1 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 6, 2, 1]),\n        (\"SamplePerfectTile\", [1, 2, 2, 32]),\n        (\"SamplePerfectTile\", [2, 8, 4, 2]),\n        (\"SamplePerfectTile\", [1, 64]),\n        (\"SampleCategorical\", 2),\n        (\"SampleComputeLocation\", 13),\n        (\"SampleComputeLocation\", -1),\n    ]\n    decision_2 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 6, 2, 1]),\n        (\"SamplePerfectTile\", [1, 2, 2, 32]),\n        (\"SamplePerfectTile\", [2, 8, 4, 2]),\n        (\"SamplePerfectTile\", [1, 64]),\n        (\"SampleCategorical\", 3),\n        (\"SampleComputeLocation\", 7),\n        (\"SampleComputeLocation\", -2),\n    ]\n    mod = create_te_workload(\"TBG\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[tbg_0, tbg_1, tbg_2],\n        expected_decisions=[decision_0, decision_1, decision_2],\n    )\n\n\nif __name__ == \"__main__\":\n    test_cpu_c1d()\n    test_cpu_c2d()\n    test_cpu_c3d()\n    test_cpu_cap()\n    test_cpu_dep()\n    test_cpu_dil()\n    test_cpu_gmm()\n    test_cpu_grp()\n    test_cpu_t2d()\n    test_cpu_nrm()\n    test_cpu_sfm()\n    test_cpu_cbr()\n    test_cpu_tbg()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_space_cpu_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for MetaSchedule search space on CPU\"\"\"\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n    print_sketches,\n)\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target():\n    return Target(\"aws/cpu/c5.9xlarge\")\n\n\ndef _design_space(mod):\n    return generate_design_space(\n        kind=\"llvm\",\n        mod=mod,\n        target=_target(),\n        types=ms.ScheduleRule,\n    )\n\n\ndef test_cpu_nhwc():\n    # fmt: off\n    @T.prim_func\n    def cpu_nhwc_0(X: T.Buffer[(1, 14, 14, 128), \"float32\"], W: T.Buffer[(6, 6, 128, 128), \"float32\"], conv2d_winograd: T.Buffer[(1, 12, 12, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.parallel\":288, \"meta_schedule.unroll_explicit\":64, \"meta_schedule.vectorize\":64})\n            data_pad = T.alloc_buffer([1, 16, 16, 128], dtype=\"float32\")\n            input_tile = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            data_pack = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            bgemm = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            inverse = T.alloc_buffer([4, 4, 9, 128], dtype=\"float32\")\n            bgemm_global = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            for i2_0 in T.serial(9):\n                for ax0, ax1, ax2, ax3 in T.grid(1, 6, 6, 128):\n                    with T.block(\"data_pad\"):\n                        i0 = T.axis.spatial(1, ax0)\n                        i1 = T.axis.spatial(16, i2_0 // 3 * 4 + ax1)\n                        i2 = T.axis.spatial(16, i2_0 % 3 * 4 + ax2)\n                        i3 = T.axis.spatial(128, ax3)\n                        T.reads(X[i0, i1, i2, i3])\n                        T.writes(data_pad[i0, i1, i2, i3])\n                        T.block_attr({\"schedule_rule\":\"None\"})\n                        data_pad[i0, i1, i2, i3] = T.if_then_else(0 <= i1 and i1 < 14 and 0 <= i2 and i2 < 14, X[i0, i1, i2, i3], T.float32(0), dtype=\"float32\")\n                for i3_0 in T.serial(2):\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 64):\n                        with T.block(\"input_tile\"):\n                            eps, nu = T.axis.remap(\"SS\", [ax0, ax1])\n                            p = T.axis.spatial(9, i2_0 + ax2)\n                            ci = T.axis.spatial(128, i3_0 * 64 + ax3)\n                            T.reads(data_pad[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci])\n                            T.writes(input_tile[eps, nu, p, ci])\n                            T.block_attr({\"schedule_rule\":\"None\"})\n                            input_tile[eps, nu, p, ci] = data_pad[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci]\n                    for i2_1, i3_1 in T.grid(1, 64):\n                        for i0 in T.unroll(6):\n                            for i1 in T.unroll(6):\n                                for i4 in T.unroll(6):\n                                    for i5 in T.unroll(6):\n                                        with T.block(\"data_pack\"):\n                                            eps, nu = T.axis.remap(\"SS\", [i0, i1])\n                                            p = T.axis.spatial(9, i2_0 + i2_1)\n                                            ci = T.axis.spatial(128, i3_0 * 64 + i3_1)\n                                            r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                            T.reads(input_tile[r_a, r_b, p, ci])\n                                            T.writes(data_pack[eps, nu, p, ci])\n                                            T.block_attr({\"schedule_rule\":\"conv2d_nhwc_winograd_data_pack\"})\n                                            with T.init():\n                                                data_pack[eps, nu, p, ci] = T.float32(0)\n                                            data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n            for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(3, 2, 3, 1, 1, 1, 1, 1):\n                for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(32, 1, 1, 1, 2, 4, 2, 3, 3, 64):\n                    with T.block(\"bgemm\"):\n                        eps = T.axis.spatial(6, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3)\n                        nu = T.axis.spatial(6, i1_0 * 3 + i1_1 * 3 + i1_2 * 3 + i1_3)\n                        p = T.axis.spatial(9, i2_0 * 3 + i2_1 * 3 + i2_2 * 3 + i2_3)\n                        co = T.axis.spatial(128, i3_0 * 128 + i3_1 * 128 + i3_2 * 64 + i3_3)\n                        ci = T.axis.reduce(128, i4_0 * 4 + i4_1)\n                        T.reads(data_pack[eps, nu, p, ci], W[eps, nu, co, ci])\n                        T.writes(bgemm_global[eps, nu, p, co])\n                        T.block_attr({\"meta_schedule.tiling_structure\":\"SSRSRS\", \"meta_schedule.write_cache_level\":[2]})\n                        with T.init():\n                            bgemm_global[eps, nu, p, co] = T.float32(0)\n                        bgemm_global[eps, nu, p, co] = bgemm_global[eps, nu, p, co] + data_pack[eps, nu, p, ci] * W[eps, nu, co, ci]\n                for ax0, ax1, ax2, ax3 in T.grid(2, 3, 3, 128):\n                    with T.block(\"bgemm_global\"):\n                        v0 = T.axis.spatial(6, i0_0 * 2 + ax0)\n                        v1 = T.axis.spatial(6, i1_0 * 3 + ax1)\n                        v2 = T.axis.spatial(9, i2_0 * 3 + ax2)\n                        v3 = T.axis.spatial(128, ax3)\n                        T.reads(bgemm_global[v0, v1, v2, v3])\n                        T.writes(bgemm[v0, v1, v2, v3])\n                        bgemm[v0, v1, v2, v3] = bgemm_global[v0, v1, v2, v3]\n            for i2_0, i3_0, i2_1, i3_1 in T.grid(3, 8, 3, 16):\n                for i0 in T.unroll(4):\n                    for i1 in T.unroll(4):\n                        for i4 in T.unroll(6):\n                            for i5 in T.unroll(6):\n                                with T.block(\"inverse\"):\n                                    vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                                    p = T.axis.spatial(9, i2_0 * 3 + i2_1)\n                                    co = T.axis.spatial(128, i3_0 * 16 + i3_1)\n                                    r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                    T.reads(bgemm[r_a, r_b, p, co])\n                                    T.writes(inverse[vh, vw, p, co])\n                                    T.block_attr({\"schedule_rule\":\"conv2d_nhwc_winograd_inverse\"})\n                                    with T.init():\n                                        inverse[vh, vw, p, co] = T.float32(0)\n                                    inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n            for i0, i1, i2, i3 in T.grid(1, 12, 12, 128):\n                with T.block(\"conv2d_winograd\"):\n                    n, h, w, co = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                    T.reads(inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co])\n                    T.writes(conv2d_winograd[n, h, w, co])\n                    conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [3, 3]),\n        (\"SamplePerfectTile\", [8, 16]),\n        (\"SamplePerfectTile\", [9, 1]),\n        (\"SamplePerfectTile\", [2, 64]),\n        (\"SampleComputeLocation\", 1),\n        (\"SampleComputeLocation\", 0),\n        (\"SamplePerfectTile\", [3, 1, 1, 2]),\n        (\"SamplePerfectTile\", [2, 1, 1, 3]),\n        (\"SamplePerfectTile\", [3, 1, 1, 3]),\n        (\"SamplePerfectTile\", [1, 1, 2, 64]),\n        (\"SamplePerfectTile\", [32, 4]),\n        (\"SampleCategorical\", 2),\n    ]\n    with _target():\n        mod = create_te_workload(\"C2D_WIN_NHWC\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cpu_nhwc_0],\n        expected_decisions=[decision_0],\n    )\n\n\nif __name__ == \"__main__\":\n    test_cpu_nhwc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_space_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for MetaSchedule search space on CUDA\"\"\"\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n    print_sketches,\n)\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target():\n    return Target(\"nvidia/geforce-rtx-3070\")\n\n\ndef _design_space(mod):\n    return generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=_target(),\n        types=ms.ScheduleRule,\n    )\n\n\ndef test_cuda_c1d():\n    # fmt: off\n    @T.prim_func\n    def c1d_0(inputs: T.Buffer[(1, 256, 64), \"float32\"], weight: T.Buffer[(3, 64, 128), \"float32\"], conv1d_nlc: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            conv1d_nlc_local = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 258, 64], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([3, 64, 128], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_fused in T.thread_binding(4, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_fused in T.thread_binding(16, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_fused in T.thread_binding(4, thread=\"threadIdx.x\"):\n                        for i3_0, i4_0 in T.grid(1, 16):\n                            for ax0_ax1_ax2_fused in T.serial(260):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(258, i0_0_i1_0_i2_0_fused * 64 + ax0_ax1_ax2_fused // 4)\n                                    v2 = T.axis.spatial(64, i4_0 * 4 + ax0_ax1_ax2_fused % 4)\n                                    T.reads(inputs[v0, v1 - 1, v2])\n                                    T.writes(PadInput_shared[v0, v1, v2])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    PadInput_shared[v0, v1, v2] = T.if_then_else(1 <= v1 and v1 < 257, inputs[v0, v1 - 1, v2], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_fused in T.serial(1536):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(3, ax0_ax1_ax2_fused // 512)\n                                    v1 = T.axis.spatial(64, i4_0 * 4 + ax0_ax1_ax2_fused % 512 // 128)\n                                    v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128)\n                                    T.reads(weight[v0, v1, v2])\n                                    T.writes(weight_shared[v0, v1, v2])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    weight_shared[v0, v1, v2] = weight[v0, v1, v2]\n                            for i3_1, i4_1, i0_3, i1_3, i2_3, i3_2, i4_2, i0_4, i1_4, i2_4 in T.grid(1, 2, 1, 1, 2, 3, 2, 1, 4, 8):\n                                with T.block(\"conv1d_nlc\"):\n                                    n = T.axis.spatial(1, i0_4 + i0_3)\n                                    l = T.axis.spatial(128, i0_0_i1_0_i2_0_fused * 32 + i0_1_i1_1_i2_1_fused // 2 * 4 + i1_3 * 4 + i1_4)\n                                    co = T.axis.spatial(128, i0_1_i1_1_i2_1_fused % 2 * 64 + i0_2_i1_2_i2_2_fused * 16 + i2_3 * 8 + i2_4)\n                                    rl = T.axis.reduce(3, i3_0 * 3 + i3_1 * 3 + i3_2)\n                                    rc = T.axis.reduce(64, i4_0 * 4 + i4_1 * 2 + i4_2)\n                                    T.reads(PadInput_shared[n, l * 2 + rl, co // 128 * 64 + rc], weight_shared[rl, rc, co])\n                                    T.writes(conv1d_nlc_local[n, l, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv1d_nlc_local[n, l, co] = T.float32(0)\n                                    conv1d_nlc_local[n, l, co] = conv1d_nlc_local[n, l, co] + PadInput_shared[n, l * 2 + rl, co // 128 * 64 + rc] * weight_shared[rl, rc, co]\n                        for ax0, ax1, ax2 in T.grid(1, 4, 16):\n                            with T.block(\"conv1d_nlc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused * 32 + i0_1_i1_1_i2_1_fused // 2 * 4 + ax1)\n                                v2 = T.axis.spatial(128, i0_1_i1_1_i2_1_fused % 2 * 64 + i0_2_i1_2_i2_2_fused * 16 + ax2)\n                                T.reads(conv1d_nlc_local[v0, v1, v2])\n                                T.writes(conv1d_nlc[v0, v1, v2])\n                                conv1d_nlc[v0, v1, v2] = conv1d_nlc_local[v0, v1, v2]\n    # fmt: on\n\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 8, 1, 1, 4]),\n        (\"SamplePerfectTile\", [1, 2, 4, 2, 8]),\n        (\"SamplePerfectTile\", [1, 1, 3]),\n        (\"SamplePerfectTile\", [16, 2, 2]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n    ]\n\n    mod = create_te_workload(\"C1D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c1d_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_c2d():\n    # fmt: off\n    @T.prim_func\n    def c2d_0(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            conv2d_nhwc_local = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([7, 7, 3, 64], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(16, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(56, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(14, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0, i6_0 in T.grid(1, 1, 1):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(80379):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(230, ax0_ax1_ax2_ax3_fused // 351)\n                                    v2 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 8 * 112 + ax0_ax1_ax2_ax3_fused % 351 // 3)\n                                    v3 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 3)\n                                    T.reads(inputs[v0, v1 - 3, v2 - 3, v3])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    PadInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, inputs[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(1176):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused // 168)\n                                    v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused % 168 // 24)\n                                    v2 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 24 // 8)\n                                    v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + ax0_ax1_ax2_ax3_fused % 8)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 7, 1, 1, 8, 4, 1, 7, 1, 3, 1, 1, 1, 2):\n                                with T.block(\"conv2d_nhwc\"):\n                                    n = T.axis.spatial(1, i0_3 + i0_4)\n                                    h = T.axis.spatial(112, i1_4 + i0_2_i1_2_i2_2_i3_2_fused * 8 + i1_3)\n                                    w = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 8 * 56 + i0_1_i1_1_i2_1_i3_1_fused // 4 * 4 + i2_3 + i2_4)\n                                    co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + i0_1_i1_1_i2_1_i3_1_fused % 4 * 2 + i3_3 * 2 + i3_4)\n                                    rh = T.axis.reduce(7, i4_0 * 7 + i4_1 * 7 + i4_2)\n                                    rw = T.axis.reduce(7, i5_2 + i5_0 * 7 + i5_1)\n                                    rc = T.axis.reduce(3, i6_0 * 3 + i6_1 * 3 + i6_2)\n                                    T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight_shared[rh, rw, rc, co])\n                                    T.writes(conv2d_nhwc_local[n, h, w, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv2d_nhwc_local[n, h, w, co] = T.float32(0)\n                                    conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight_shared[rh, rw, rc, co]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 8, 4, 2):\n                            with T.block(\"conv2d_nhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(112, i0_2_i1_2_i2_2_i3_2_fused * 8 + ax1)\n                                v2 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 8 * 56 + i0_1_i1_1_i2_1_i3_1_fused // 4 * 4 + ax2)\n                                v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + i0_1_i1_1_i2_1_i3_1_fused % 4 * 2 + ax3)\n                                T.reads(conv2d_nhwc_local[v0, v1, v2, v3])\n                                T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                                conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 14, 8, 1]),\n        (\"SamplePerfectTile\", [2, 14, 1, 4, 1]),\n        (\"SamplePerfectTile\", [8, 4, 1, 1, 2]),\n        (\"SamplePerfectTile\", [1, 1, 7]),\n        (\"SamplePerfectTile\", [1, 7, 1]),\n        (\"SamplePerfectTile\", [1, 1, 3]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 1),\n    ]\n\n    mod = create_te_workload(\"C2D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c2d_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_c3d():\n    # fmt: off\n    @T.prim_func\n    def c3d_0(inputs: T.Buffer[(1, 16, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 7, 3, 64), \"float32\"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            conv3d_ndhwc_local = T.alloc_buffer([1, 8, 112, 112, 64], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 22, 230, 230, 3], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([7, 7, 7, 3, 64], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_i4_0_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_i4_1_fused in T.thread_binding(8, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_i4_2_fused in T.thread_binding(392, thread=\"threadIdx.x\"):\n                        for i5_0, i6_0, i7_0, i8_0 in T.grid(1, 1, 1, 1):\n                            for ax0_ax1_ax2_ax3_ax4_fused in T.serial(1687959):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(22, ax0_ax1_ax2_ax3_ax4_fused // 80379)\n                                    v2 = T.axis.spatial(230, ax0_ax1_ax2_ax3_ax4_fused % 80379 // 351)\n                                    v3 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 112 + ax0_ax1_ax2_ax3_ax4_fused % 351 // 3)\n                                    v4 = T.axis.spatial(3, ax0_ax1_ax2_ax3_ax4_fused % 3)\n                                    T.reads(inputs[v0, v1 - 3, v2 - 3, v3 - 3, v4])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3, v4])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    PadInput_shared[v0, v1, v2, v3, v4] = T.if_then_else(3 <= v1 and v1 < 19 and 3 <= v2 and v2 < 227 and 3 <= v3 and v3 < 227, inputs[v0, v1 - 3, v2 - 3, v3 - 3, v4], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_ax4_fused in T.serial(65856):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused // 9408)\n                                    v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused % 9408 // 1344)\n                                    v2 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused % 1344 // 192)\n                                    v3 = T.axis.spatial(3, ax0_ax1_ax2_ax3_ax4_fused % 192 // 64)\n                                    v4 = T.axis.spatial(64, ax0_ax1_ax2_ax3_ax4_fused % 64)\n                                    T.reads(weight[v0, v1, v2, v3, v4])\n                                    T.writes(weight_shared[v0, v1, v2, v3, v4])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    weight_shared[v0, v1, v2, v3, v4] = weight[v0, v1, v2, v3, v4]\n                            for i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_2, i6_2, i7_2, i8_2, i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(7, 7, 1, 3, 1, 2, 2, 1, 32, 1, 1, 7, 1, 1, 1, 2, 4, 1):\n                                with T.block(\"conv3d_ndhwc\"):\n                                    n = T.axis.spatial(1, i0_4 + i0_3)\n                                    d = T.axis.spatial(8, i1_4 + i0_2_i1_2_i2_2_i3_2_i4_2_fused // 98 * 2 + i1_3)\n                                    h = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_i4_1_fused // 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 98 // 14 * 4 + i2_3 * 2 + i2_4)\n                                    w = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 56 + i0_1_i1_1_i2_1_i3_1_i4_1_fused % 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 14 // 2 * 4 + i3_3 * 4 + i3_4)\n                                    co = T.axis.spatial(64, i0_2_i1_2_i2_2_i3_2_i4_2_fused % 2 * 32 + i4_3 + i4_4)\n                                    rd = T.axis.reduce(7, i5_2 + i5_0 * 7 + i5_1)\n                                    rh = T.axis.reduce(7, i6_0 * 7 + i6_1 + i6_2)\n                                    rw = T.axis.reduce(7, i7_0 * 7 + i7_1 * 7 + i7_2)\n                                    rc = T.axis.reduce(3, i8_0 * 3 + i8_1 + i8_2)\n                                    T.reads(PadInput_shared[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight_shared[rd, rh, rw, rc, co])\n                                    T.writes(conv3d_ndhwc_local[n, d, h, w, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv3d_ndhwc_local[n, d, h, w, co] = T.float32(0)\n                                    conv3d_ndhwc_local[n, d, h, w, co] = conv3d_ndhwc_local[n, d, h, w, co] + PadInput_shared[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight_shared[rd, rh, rw, rc, co]\n                        for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 2, 4, 4, 32):\n                            with T.block(\"conv3d_ndhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(8, i0_2_i1_2_i2_2_i3_2_i4_2_fused // 98 * 2 + ax1)\n                                v2 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_i4_1_fused // 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 98 // 14 * 4 + ax2)\n                                v3 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 56 + i0_1_i1_1_i2_1_i3_1_i4_1_fused % 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 14 // 2 * 4 + ax3)\n                                v4 = T.axis.spatial(64, i0_2_i1_2_i2_2_i3_2_i4_2_fused % 2 * 32 + ax4)\n                                T.reads(conv3d_ndhwc_local[v0, v1, v2, v3, v4])\n                                T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4])\n                                conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_local[v0, v1, v2, v3, v4]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4, 2, 1]),\n        (\"SamplePerfectTile\", [1, 4, 7, 2, 2]),\n        (\"SamplePerfectTile\", [2, 2, 7, 1, 4]),\n        (\"SamplePerfectTile\", [1, 1, 2, 32, 1]),\n        (\"SamplePerfectTile\", [1, 7, 1]),\n        (\"SamplePerfectTile\", [1, 7, 1]),\n        (\"SamplePerfectTile\", [1, 1, 7]),\n        (\"SamplePerfectTile\", [1, 3, 1]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n    ]\n    mod = create_te_workload(\"C3D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[c3d_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_cap():\n    # fmt: off\n    @T.prim_func\n    def cap_0(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), \"float32\"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), \"float32\"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":64})\n            conv2d_capsule_nhwijc_local = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([3, 3, 4, 4, 32, 32], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_i4_1_i5_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused in T.thread_binding(4, thread=\"threadIdx.x\"):\n                        for i6_0, i7_0, i8_0, i9_0 in T.grid(3, 3, 2, 8):\n                            for ax0_ax1_ax2_ax3_ax4_ax5_fused in T.serial(48):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(18, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 4 + i6_0 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 48 // 16)\n                                    v2 = T.axis.spatial(18, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8 * 2 + i7_0 + 0)\n                                    v3 = T.axis.spatial(4, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 16 // 8)\n                                    v4 = T.axis.spatial(4, i8_0 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 8 // 4)\n                                    v5 = T.axis.spatial(32, i9_0 * 4 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 4)\n                                    T.reads(inputs[v0, v1 - 1, v2 - 1, v3, v4, v5])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3, v4, v5])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    PadInput_shared[v0, v1, v2, v3, v4, v5] = T.if_then_else(1 <= v1 and v1 < 17 and 1 <= v2 and v2 < 17, inputs[v0, v1 - 1, v2 - 1, v3, v4, v5], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_ax4_ax5_fused in T.serial(256):\n                                with T.block(\"weight_shared\"):\n                                    v0, v1 = T.axis.remap(\"SS\", [i6_0, i7_0])\n                                    v2 = T.axis.spatial(4, i8_0 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused // 128)\n                                    v3 = T.axis.spatial(4, ax0_ax1_ax2_ax3_ax4_ax5_fused % 128 // 32)\n                                    v4 = T.axis.spatial(32, i9_0 * 4 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 32 // 8)\n                                    v5 = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 8)\n                                    T.reads(weight[v0, v1, v2, v3, v4, v5])\n                                    T.writes(weight_shared[v0, v1, v2, v3, v4, v5])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    weight_shared[v0, v1, v2, v3, v4, v5] = weight[v0, v1, v2, v3, v4, v5]\n                            for i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3, i6_2, i7_2, i8_2, i9_2, i0_4, i1_4, i2_4, i3_4, i4_4, i5_4 in T.grid(1, 1, 1, 4, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 8):\n                                with T.block(\"conv2d_capsule_nhwijc\"):\n                                    n = T.axis.spatial(1, i0_4 + i0_3)\n                                    h = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 2 + i1_3 + i1_4)\n                                    w = T.axis.spatial(8, i2_3 + i2_4 + i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8)\n                                    cap_i = T.axis.spatial(4, i3_3 + i3_4 + i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused // 2)\n                                    cap_j = T.axis.spatial(4, i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused % 2 * 2 + i4_3 * 2 + i4_4)\n                                    co = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + i5_3 * 8 + i5_4)\n                                    rh = T.axis.reduce(3, i6_1 + i6_2 + i6_0)\n                                    rw = T.axis.reduce(3, i7_0 + i7_1 + i7_2)\n                                    cap_k = T.axis.reduce(4, i8_0 * 2 + i8_1 * 2 + i8_2)\n                                    rc = T.axis.reduce(32, i9_0 * 4 + i9_1 + i9_2)\n                                    T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight_shared[rh, rw, cap_k, cap_j, rc, co])\n                                    T.writes(conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] = T.float32(0)\n                                    conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight_shared[rh, rw, cap_k, cap_j, rc, co]\n                        for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 2, 1, 1, 2, 8):\n                            with T.block(\"conv2d_capsule_nhwijc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 2 + ax1)\n                                v2 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8 + ax2)\n                                v3 = T.axis.spatial(4, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused // 2 + ax3)\n                                v4 = T.axis.spatial(4, i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused % 2 * 2 + ax4)\n                                v5 = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + ax5)\n                                T.reads(conv2d_capsule_nhwijc_local[v0, v1, v2, v3, v4, v5])\n                                T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5])\n                                conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_local[v0, v1, v2, v3, v4, v5]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 1, 1, 2, 1]),\n        (\"SamplePerfectTile\", [8, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 2, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 2, 1, 2]),\n        (\"SamplePerfectTile\", [4, 1, 1, 1, 8]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 2]),\n        (\"SamplePerfectTile\", [8, 4, 1]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n    ]\n    mod = create_te_workload(\"CAP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cap_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_dep():\n    # fmt: off\n    @T.prim_func\n    def dep_0(placeholder: T.Buffer[(1, 112, 112, 32), \"float32\"], placeholder_1: T.Buffer[(1, 3, 3, 32), \"float32\"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            depth_conv2d_nhwc_local = T.alloc_buffer([1, 112, 112, 32], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 114, 114, 32], dtype=\"float32\", scope=\"shared\")\n            placeholder_shared = T.alloc_buffer([1, 3, 3, 32], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(8, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(14, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0 in T.grid(1, 1):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(415872):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(114, ax0_ax1_ax2_ax3_fused // 3648)\n                                    v2 = T.axis.spatial(114, ax0_ax1_ax2_ax3_fused % 3648 // 32)\n                                    v3 = T.axis.spatial(32, ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(placeholder[v0, v1 - 1, v2 - 1, v3])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 113 and 1 <= v2 and v2 < 113, placeholder[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(288):\n                                with T.block(\"placeholder_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused // 96)\n                                    v2 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 96 // 32)\n                                    v3 = T.axis.spatial(32, ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(placeholder_1[v0, v1, v2, v3])\n                                    T.writes(placeholder_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    placeholder_shared[v0, v1, v2, v3] = placeholder_1[v0, v1, v2, v3]\n                            for i4_1, i5_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i0_4, i1_4, i2_4, i3_4 in T.grid(3, 1, 1, 4, 16, 8, 1, 3, 1, 7, 1, 1):\n                                with T.block(\"depth_conv2d_nhwc\"):\n                                    n = T.axis.spatial(1, i0_4 + i0_3)\n                                    h = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 28 + i1_3 * 7 + i1_4)\n                                    w = T.axis.spatial(112, i2_4 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 16 + i2_3)\n                                    c = T.axis.spatial(32, i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 8 + i3_3 + i3_4)\n                                    rh = T.axis.reduce(3, i4_2 + i4_0 * 3 + i4_1)\n                                    rw = T.axis.reduce(3, i5_0 * 3 + i5_1 * 3 + i5_2)\n                                    T.reads(PadInput_shared[n, h + rh, w + rw, c], placeholder_shared[0, rh, rw, c])\n                                    T.writes(depth_conv2d_nhwc_local[n, h, w, c])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        depth_conv2d_nhwc_local[n, h, w, c] = T.float32(0)\n                                    depth_conv2d_nhwc_local[n, h, w, c] = depth_conv2d_nhwc_local[n, h, w, c] + PadInput_shared[n, h + rh, w + rw, c] * placeholder_shared[0, rh, rw, c]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 28, 16, 8):\n                            with T.block(\"depth_conv2d_nhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 28 + ax1)\n                                v2 = T.axis.spatial(112, i0_2_i1_2_i2_2_i3_2_fused // 2 * 16 + ax2)\n                                v3 = T.axis.spatial(32, i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 8 + ax3)\n                                T.reads(depth_conv2d_nhwc_local[v0, v1, v2, v3])\n                                T.writes(depth_conv2d_nhwc[v0, v1, v2, v3])\n                                depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 4, 1, 4, 7]),\n        (\"SamplePerfectTile\", [1, 1, 7, 16, 1]),\n        (\"SamplePerfectTile\", [1, 2, 2, 8, 1]),\n        (\"SamplePerfectTile\", [1, 3, 1]),\n        (\"SamplePerfectTile\", [1, 1, 3]),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n    ]\n    mod = create_te_workload(\"DEP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[dep_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_dil():\n    # fmt: off\n    @T.prim_func\n    def dil_0(inputs: T.Buffer[(1, 224, 224, 3), \"float32\"], weight: T.Buffer[(7, 7, 3, 64), \"float32\"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":512})\n            conv2d_nhwc_local = T.alloc_buffer([1, 109, 109, 64], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([7, 7, 3, 64], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(218, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(109, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(1, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0, i6_0 in T.grid(7, 7, 3):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(217):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 2 * 2 + i4_0 * 2 + 0)\n                                    v2 = T.axis.spatial(230, i5_0 * 2 + ax0_ax1_ax2_ax3_fused % 217)\n                                    v3 = T.axis.spatial(3, i6_0 + 0)\n                                    T.reads(inputs[v0, v1 - 3, v2 - 3, v3])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    PadInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, inputs[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(32):\n                                with T.block(\"weight_shared\"):\n                                    v0, v1, v2 = T.axis.remap(\"SSS\", [i4_0, i5_0, i6_0])\n                                    v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 4):\n                                with T.block(\"conv2d_nhwc\"):\n                                    n = T.axis.spatial(1, i0_3 + i0_4)\n                                    h = T.axis.spatial(109, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 2 + i1_3)\n                                    w = T.axis.spatial(109, i0_1_i1_1_i2_1_i3_1_fused + i2_3 + i2_4)\n                                    co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i3_3 * 4 + i3_4)\n                                    rh = T.axis.reduce(7, i4_0 + i4_1 + i4_2)\n                                    rw = T.axis.reduce(7, i5_2 + i5_0 + i5_1)\n                                    rc = T.axis.reduce(3, i6_1 + i6_2 + i6_0)\n                                    T.reads(PadInput_shared[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight_shared[rh, rw, rc, co])\n                                    T.writes(conv2d_nhwc_local[n, h, w, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv2d_nhwc_local[n, h, w, co] = T.float32(0)\n                                    conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight_shared[rh, rw, rc, co]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 32):\n                            with T.block(\"conv2d_nhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(109, i0_0_i1_0_i2_0_i3_0_fused // 2 + ax1)\n                                v2 = T.axis.spatial(109, i0_1_i1_1_i2_1_i3_1_fused + ax2)\n                                v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax3)\n                                T.reads(conv2d_nhwc_local[v0, v1, v2, v3])\n                                T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                                conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [109, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 109, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 1, 8, 4]),\n        (\"SamplePerfectTile\", [7, 1, 1]),\n        (\"SamplePerfectTile\", [7, 1, 1]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 3),\n    ]\n    mod = create_te_workload(\"DIL\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[dil_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_gmm():\n    # fmt: off\n    @T.prim_func\n    def gmm_0(X: T.Buffer[(1, 128, 128), \"float32\"], Y: T.Buffer[(1, 128, 128), \"float32\"], Z: T.Buffer[(1, 128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":1024})\n            Z_local = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"local\")\n            X_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n            Y_shared = T.alloc_buffer([1, 128, 128], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_fused in T.thread_binding(32, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_fused in T.thread_binding(2, thread=\"threadIdx.x\"):\n                        for i3_0 in T.serial(1):\n                            for ax0_ax1_ax2_fused in T.serial(16384):\n                                with T.block(\"X_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(128, ax0_ax1_ax2_fused // 128)\n                                    v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128)\n                                    T.reads(X[v0, v1, v2])\n                                    T.writes(X_shared[v0, v1, v2])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    X_shared[v0, v1, v2] = X[v0, v1, v2]\n                            for ax0_ax1_ax2_fused in T.serial(16384):\n                                with T.block(\"Y_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(128, ax0_ax1_ax2_fused // 128)\n                                    v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128)\n                                    T.reads(Y[v0, v1, v2])\n                                    T.writes(Y_shared[v0, v1, v2])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    Y_shared[v0, v1, v2] = Y[v0, v1, v2]\n                            for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(32, 1, 2, 64, 4, 1, 2, 1):\n                                with T.block(\"Z\"):\n                                    b = T.axis.spatial(1, i0_4 + i0_3)\n                                    i = T.axis.spatial(128, i0_1_i1_1_i2_1_fused * 4 + i1_3 * 2 + i1_4)\n                                    j = T.axis.spatial(128, i2_4 + i0_2_i1_2_i2_2_fused * 64 + i2_3)\n                                    k = T.axis.reduce(128, i3_0 * 128 + i3_1 * 4 + i3_2)\n                                    T.reads(X_shared[b, i, k], Y_shared[b, k, j])\n                                    T.writes(Z_local[b, i, j])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        Z_local[b, i, j] = T.float32(0)\n                                    Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j]\n                        for ax0, ax1, ax2 in T.grid(1, 4, 64):\n                            with T.block(\"Z_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(128, i0_1_i1_1_i2_1_fused * 4 + ax1)\n                                v2 = T.axis.spatial(128, i0_2_i1_2_i2_2_fused * 64 + ax2)\n                                T.reads(Z_local[v0, v1, v2])\n                                T.writes(Z[v0, v1, v2])\n                                Z[v0, v1, v2] = Z_local[v0, v1, v2]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 32, 1, 2, 2]),\n        (\"SamplePerfectTile\", [1, 1, 2, 64, 1]),\n        (\"SamplePerfectTile\", [1, 32, 4]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 4),\n    ]\n    mod = create_te_workload(\"GMM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[gmm_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_grp():\n    # fmt: off\n    @T.prim_func\n    def grp_0(inputs: T.Buffer[(1, 56, 56, 64), \"float32\"], weight: T.Buffer[(3, 3, 16, 128), \"float32\"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            conv2d_nhwc_local = T.alloc_buffer([1, 28, 28, 128], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([3, 3, 16, 128], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(112, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0, i6_0 in T.grid(3, 3, 1):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(95040):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused * 28 + i4_0 + ax0_ax1_ax2_ax3_fused % 95040 // 3520)\n                                    v2 = T.axis.spatial(58, i5_0 + ax0_ax1_ax2_ax3_fused % 3520 // 64)\n                                    v3 = T.axis.spatial(64, ax0_ax1_ax2_ax3_fused % 64)\n                                    T.reads(inputs[v0, v1 - 1, v2 - 1, v3])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 57 and 1 <= v2 and v2 < 57, inputs[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(2048):\n                                with T.block(\"weight_shared\"):\n                                    v0, v1 = T.axis.remap(\"SS\", [i4_0, i5_0])\n                                    v2 = T.axis.spatial(16, ax0_ax1_ax2_ax3_fused // 128)\n                                    v3 = T.axis.spatial(128, ax0_ax1_ax2_ax3_fused % 128)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 2, 1, 2, 1, 2, 1, 1, 8, 1, 7, 4, 4):\n                                with T.block(\"conv2d_nhwc\"):\n                                    n = T.axis.spatial(1, i0_3 + i0_4)\n                                    h = T.axis.spatial(28, i0_0_i1_0_i2_0_i3_0_fused * 14 + i1_3 * 7 + i1_4)\n                                    w = T.axis.spatial(28, i0_2_i1_2_i2_2_i3_2_fused // 16 * 4 + i2_3 * 4 + i2_4)\n                                    co = T.axis.spatial(128, i0_2_i1_2_i2_2_i3_2_fused % 16 * 8 + i3_3 * 4 + i3_4)\n                                    rh = T.axis.reduce(3, i4_0 + i4_1 + i4_2)\n                                    rw = T.axis.reduce(3, i5_2 + i5_0 + i5_1)\n                                    rc = T.axis.reduce(16, i6_0 * 16 + i6_1 * 8 + i6_2)\n                                    T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight_shared[rh, rw, rc, co])\n                                    T.writes(conv2d_nhwc_local[n, h, w, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv2d_nhwc_local[n, h, w, co] = T.float32(0)\n                                    conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight_shared[rh, rw, rc, co]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 14, 4, 8):\n                            with T.block(\"conv2d_nhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(28, i0_0_i1_0_i2_0_i3_0_fused * 14 + ax1)\n                                v2 = T.axis.spatial(28, i0_2_i1_2_i2_2_i3_2_fused // 16 * 4 + ax2)\n                                v3 = T.axis.spatial(128, i0_2_i1_2_i2_2_i3_2_fused % 16 * 8 + ax3)\n                                T.reads(conv2d_nhwc_local[v0, v1, v2, v3])\n                                T.writes(conv2d_nhwc[v0, v1, v2, v3])\n                                conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [2, 1, 1, 2, 7]),\n        (\"SamplePerfectTile\", [1, 1, 7, 1, 4]),\n        (\"SamplePerfectTile\", [1, 1, 16, 2, 4]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SamplePerfectTile\", [1, 2, 8]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 1),\n    ]\n    mod = create_te_workload(\"GRP\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[grp_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_t2d():\n    # fmt: off\n    @T.prim_func\n    def t2d_0(inputs: T.Buffer[(1, 4, 4, 512), \"float32\"], weight: T.Buffer[(4, 4, 512, 256), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":64})\n            conv2d_transpose_nhwc_local = T.alloc_buffer([1, 8, 8, 256], dtype=\"float32\", scope=\"local\")\n            PadInput_shared = T.alloc_buffer([1, 6, 6, 512], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([4, 4, 512, 256], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(2, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(1, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0, i6_0 in T.grid(4, 1, 16):\n                            for ax0_ax1_ax2_ax3_fused in T.serial((i4_0 % 2 + 1) // 2 * 96 + 96):\n                                with T.block(\"PadInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 64 + i4_0 // 2 + ax0_ax1_ax2_ax3_fused % (96 * ((i4_0 % 2 + 1) // 2 + 1)) // 96)\n                                    v2 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 + ax0_ax1_ax2_ax3_fused % 96 // 32)\n                                    v3 = T.axis.spatial(512, i6_0 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(inputs[v0, v1 - 1, v2 - 1, v3])\n                                    T.writes(PadInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":2})\n                                    PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 5 and 1 <= v2 and v2 < 5, inputs[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(2048):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(4, i4_0 * -1 + 3)\n                                    v1 = T.axis.spatial(4, ax0_ax1_ax2_ax3_fused // 512)\n                                    v2 = T.axis.spatial(512, i6_0 * 32 + ax0_ax1_ax2_ax3_fused % 512 // 16)\n                                    v3 = T.axis.spatial(256, i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + ax0_ax1_ax2_ax3_fused % 16)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 4, 1, 2, 1, 8, 1, 4, 8, 1, 1, 2, 1):\n                                with T.block(\"conv2d_transpose_nhwc\"):\n                                    n = T.axis.spatial(1, i0_3 + i0_4)\n                                    h = T.axis.spatial(8, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 64 * 2 + i1_3)\n                                    w = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 * 2 + i2_3 * 2 + i2_4)\n                                    co = T.axis.spatial(256, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + i0_1_i1_1_i2_1_i3_1_fused * 8 + i3_3)\n                                    rh = T.axis.reduce(4, i4_0 + i4_1 + i4_2)\n                                    rw = T.axis.reduce(4, i5_0 * 4 + i5_1 * 4 + i5_2)\n                                    rc = T.axis.reduce(512, i6_0 * 32 + i6_1 * 8 + i6_2)\n                                    T.reads(PadInput_shared[n, (h + rh) // 2, (w + rw) // 2, rc], weight_shared[3 - rh, 3 - rw, rc, co])\n                                    T.writes(conv2d_transpose_nhwc_local[n, h, w, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        conv2d_transpose_nhwc_local[n, h, w, co] = T.float32(0)\n                                    conv2d_transpose_nhwc_local[n, h, w, co] = conv2d_transpose_nhwc_local[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput_shared[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype=\"float32\") * weight_shared[3 - rh, 3 - rw, rc, co]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 2, 2, 8):\n                            with T.block(\"conv2d_transpose_nhwc_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused // 64 * 2 + ax1)\n                                v2 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 * 2 + ax2)\n                                v3 = T.axis.spatial(256, i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + i0_1_i1_1_i2_1_i3_1_fused * 8 + ax3)\n                                T.reads(conv2d_transpose_nhwc_local[v0, v1, v2, v3])\n                                T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3])\n                                conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [4, 1, 1, 2, 1]),\n        (\"SamplePerfectTile\", [4, 1, 1, 1, 2]),\n        (\"SamplePerfectTile\", [16, 2, 1, 8, 1]),\n        (\"SamplePerfectTile\", [4, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 4]),\n        (\"SamplePerfectTile\", [16, 4, 8]),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n    ]\n    mod = create_te_workload(\"T2D\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[t2d_0],\n        expected_decisions=[decision_0],\n        debug_mask=0,\n    )\n\n\ndef test_cuda_nrm():\n    # fmt: off\n    @T.prim_func\n    def nrm_0(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":512})\n            C = T.alloc_buffer([1], dtype=\"float32\")\n            for i0_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                    for i1, i2 in T.grid(256, 256):\n                        with T.block(\"C\"):\n                            b = T.axis.spatial(1, 0)\n                            i, j = T.axis.remap(\"RR\", [i1, i2])\n                            T.reads(A[b, i, j])\n                            T.writes(C[b])\n                            with T.init():\n                                C[b] = T.float32(0)\n                            C[b] = C[b] + A[b, i, j] * A[b, i, j]\n            for i0_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(1, thread=\"threadIdx.x\"):\n                    with T.block(\"D\"):\n                        b = T.axis.spatial(1, 0)\n                        T.reads(C[b])\n                        T.writes(D[b])\n                        D[b] = T.sqrt(C[b], dtype=\"float32\")\n    @T.prim_func\n    def nrm_1(A: T.Buffer[(1, 256, 256), \"float32\"], D: T.Buffer[1, \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":1024})\n            C_shared = T.alloc_buffer([1], dtype=\"float32\", scope=\"shared\")\n            for i0_0_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for ax0, ax1_ax2_fused_0 in T.grid(1, 512):\n                    for ax1_ax2_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                        with T.block(\"C\"):\n                            b = T.axis.spatial(1, ax0)\n                            i = T.axis.reduce(256, (ax1_ax2_fused_0 * 128 + ax1_ax2_fused_1) // 256)\n                            j = T.axis.reduce(256, (ax1_ax2_fused_0 * 128 + ax1_ax2_fused_1) % 256)\n                            T.reads(A[b, i, j])\n                            T.writes(C_shared[b])\n                            with T.init():\n                                C_shared[b] = T.float32(0)\n                            C_shared[b] = C_shared[b] + A[b, i, j] * A[b, i, j]\n                for i0_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                    with T.block(\"D\"):\n                        b = T.axis.spatial(1, i0_1)\n                        T.where(T.Mul(0, 128) + i0_1 < 1)\n                        T.reads(C_shared[b])\n                        T.writes(D[b])\n                        D[b] = T.sqrt(C_shared[b], dtype=\"float32\")\n    # fmt: on\n    decision_0 = [\n        (\"SampleCategorical\", 3),\n    ]\n    decision_1 = [\n        (\"SampleCategorical\", 5),\n        (\"SampleCategorical\", 4),\n    ]\n    mod = create_te_workload(\"NRM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[nrm_0, nrm_1],\n        expected_decisions=[decision_0, decision_1],\n    )\n\n\ndef test_cuda_sfm():\n    # fmt: off\n    @T.prim_func\n    def sfm_0(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":0})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            for i0_fused_0 in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                    for i1 in T.serial(256):\n                        with T.block(\"T_softmax_maxelem\"):\n                            i0 = T.axis.spatial(256, i0_fused_0 * 128 + i0_fused_1)\n                            k = T.axis.reduce(256, i1)\n                            T.reads(A[i0, k])\n                            T.writes(T_softmax_maxelem[i0])\n                            with T.init():\n                                T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38)\n                            T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k])\n            for i0_fused_0 in T.thread_binding(1, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n                    for i1 in T.serial(256):\n                        with T.block(\"T_softmax_expsum\"):\n                            i0 = T.axis.spatial(256, i0_fused_0 * 256 + i0_fused_1)\n                            k = T.axis.reduce(256, i1)\n                            T.reads(A[i0, k], T_softmax_maxelem[i0])\n                            T.writes(T_softmax_expsum[i0])\n                            with T.init():\n                                T_softmax_expsum[i0] = T.float32(0)\n                            T_softmax_expsum[i0] = T_softmax_expsum[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype=\"float32\")\n            for i0_i1_fused_0 in T.thread_binding(1024, thread=\"blockIdx.x\"):\n                for i0_i1_fused_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        i0 = T.axis.spatial(256, (i0_i1_fused_0 * 64 + i0_i1_fused_1) // 256)\n                        i1 = T.axis.spatial(256, (i0_i1_fused_0 * 64 + i0_i1_fused_1) % 256)\n                        T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum[i0])\n                        T.writes(T_softmax_norm[i0, i1])\n                        T.block_attr({\"axis\":1})\n                        T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype=\"float32\") / T_softmax_expsum[i0]\n    @T.prim_func\n    def sfm_1(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum = T.alloc_buffer([256], dtype=\"float32\")\n            for i0_fused in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for i1_0 in T.serial(64):\n                    for i1_1 in T.thread_binding(4, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_maxelem\"):\n                            i0 = T.axis.spatial(256, i0_fused)\n                            k = T.axis.reduce(256, i1_0 * 4 + i1_1)\n                            T.reads(A[i0, k])\n                            T.writes(T_softmax_maxelem[i0])\n                            with T.init():\n                                T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38)\n                            T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k])\n            for i0_fused_0 in T.thread_binding(4, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                    for i1 in T.serial(256):\n                        with T.block(\"T_softmax_expsum\"):\n                            i0 = T.axis.spatial(256, i0_fused_0 * 64 + i0_fused_1)\n                            k = T.axis.reduce(256, i1)\n                            T.reads(A[i0, k], T_softmax_maxelem[i0])\n                            T.writes(T_softmax_expsum[i0])\n                            with T.init():\n                                T_softmax_expsum[i0] = T.float32(0)\n                            T_softmax_expsum[i0] = T_softmax_expsum[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype=\"float32\")\n            for i0_i1_fused_0 in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for i0_i1_fused_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n                    with T.block(\"T_softmax_norm\"):\n                        i0 = T.axis.spatial(256, (i0_i1_fused_0 * 256 + i0_i1_fused_1) // 256)\n                        i1 = T.axis.spatial(256, (i0_i1_fused_0 * 256 + i0_i1_fused_1) % 256)\n                        T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum[i0])\n                        T.writes(T_softmax_norm[i0, i1])\n                        T.block_attr({\"axis\":1})\n                        T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype=\"float32\") / T_softmax_expsum[i0]\n    @T.prim_func\n    def sfm_2(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":512})\n            T_softmax_maxelem = T.alloc_buffer([256], dtype=\"float32\")\n            T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n            for i0_fused_0 in T.thread_binding(8, thread=\"blockIdx.x\"):\n                for i0_fused_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                    for i1 in T.serial(256):\n                        with T.block(\"T_softmax_maxelem\"):\n                            i0 = T.axis.spatial(256, i0_fused_0 * 32 + i0_fused_1)\n                            k = T.axis.reduce(256, i1)\n                            T.reads(A[i0, k])\n                            T.writes(T_softmax_maxelem[i0])\n                            with T.init():\n                                T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38)\n                            T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k])\n            for i0_fused in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for ax0, ax1_0 in T.grid(1, 1):\n                    for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_expsum\"):\n                            i0 = T.axis.spatial(256, i0_fused + ax0)\n                            k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                            T.where(ax1_0 * 512 + ax1_1 < 256)\n                            T.reads(A[i0, k], T_softmax_maxelem[i0])\n                            T.writes(T_softmax_expsum_shared[i0])\n                            with T.init():\n                                T_softmax_expsum_shared[i0] = T.float32(0)\n                            T_softmax_expsum_shared[i0] = T_softmax_expsum_shared[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype=\"float32\")\n                for i1_0 in T.serial(1):\n                    for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_norm\"):\n                            i0 = T.axis.spatial(256, i0_fused)\n                            i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                            T.where(i1_0 * 512 + i1_1 < 256)\n                            T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum_shared[i0])\n                            T.writes(T_softmax_norm[i0, i1])\n                            T.block_attr({\"axis\":1})\n                            T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype=\"float32\") / T_softmax_expsum_shared[i0]\n    @T.prim_func\n    def sfm_3(A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":0})\n            T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n            T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n            for i0_fused in T.thread_binding(256, thread=\"blockIdx.x\"):\n                for ax0, ax1_0 in T.grid(1, 1):\n                    for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_maxelem\"):\n                            i0 = T.axis.spatial(256, i0_fused + ax0)\n                            k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                            T.where(ax1_0 * 512 + ax1_1 < 256)\n                            T.reads(A[i0, k])\n                            T.writes(T_softmax_maxelem_shared[i0])\n                            with T.init():\n                                T_softmax_maxelem_shared[i0] = T.float32(-3.4028234663852886e+38)\n                            T_softmax_maxelem_shared[i0] = T.max(T_softmax_maxelem_shared[i0], A[i0, k])\n                for ax0, ax1_0 in T.grid(1, 1):\n                    for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_expsum\"):\n                            i0 = T.axis.spatial(256, i0_fused + ax0)\n                            k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                            T.where(ax1_0 * 512 + ax1_1 < 256)\n                            T.reads(A[i0, k], T_softmax_maxelem_shared[i0])\n                            T.writes(T_softmax_expsum_shared[i0])\n                            with T.init():\n                                T_softmax_expsum_shared[i0] = T.float32(0)\n                            T_softmax_expsum_shared[i0] = T_softmax_expsum_shared[i0] + T.exp(A[i0, k] - T_softmax_maxelem_shared[i0], dtype=\"float32\")\n                for i1_0 in T.serial(1):\n                    for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                        with T.block(\"T_softmax_norm\"):\n                            i0 = T.axis.spatial(256, i0_fused)\n                            i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                            T.where(i1_0 * 512 + i1_1 < 256)\n                            T.reads(A[i0, i1], T_softmax_maxelem_shared[i0], T_softmax_expsum_shared[i0])\n                            T.writes(T_softmax_norm[i0, i1])\n                            T.block_attr({\"axis\":1})\n                            T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem_shared[i0], dtype=\"float32\") / T_softmax_expsum_shared[i0]\n    # fmt: on\n    decision_0 = [\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n    ]\n    decision_1 = [\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 1),\n    ]\n    decision_2 = [\n        (\"SampleCategorical\", 7),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 0),\n    ]\n    decision_3 = [\n        (\"SampleCategorical\", 7),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 0),\n    ]\n    mod = create_te_workload(\"SFM\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[sfm_0, sfm_1, sfm_2, sfm_3],\n        expected_decisions=[decision_0, decision_1, decision_2, decision_3],\n    )\n\n\ndef test_cuda_cbr():\n    # fmt: off\n    @T.prim_func\n    def cbr_0(data: T.Buffer[(1, 224, 224, 3), \"float32\"], kernel: T.Buffer[(7, 7, 3, 64), \"float32\"], bias: T.Buffer[64, \"float32\"], bn_offset: T.Buffer[64, \"float32\"], bn_scale: T.Buffer[64, \"float32\"], compute: T.Buffer[(1, 112, 112, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":512})\n            Conv2dOutput_local = T.alloc_buffer([1, 112, 112, 64], dtype=\"float32\", scope=\"local\")\n            PaddedInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\", scope=\"shared\")\n            kernel_shared = T.alloc_buffer([7, 7, 3, 64], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(14, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(128, thread=\"threadIdx.x\"):\n                        for i4_0, i5_0, i6_0 in T.grid(7, 1, 3):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(8251):\n                                with T.block(\"PaddedInput_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(230, ax0_ax1_ax2_ax3_fused // 37 + i4_0)\n                                    v2 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 2 * 32 + ax0_ax1_ax2_ax3_fused % 37)\n                                    v3 = T.axis.spatial(3, i6_0)\n                                    T.reads(data[v0, v1 - 3, v2 - 3, v3])\n                                    T.writes(PaddedInput_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    PaddedInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, data[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype=\"float32\")\n                            for ax0_ax1_ax2_ax3_fused in T.serial(224):\n                                with T.block(\"kernel_shared\"):\n                                    v0 = T.axis.spatial(7, i4_0)\n                                    v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused // 32)\n                                    v2 = T.axis.spatial(3, i6_0)\n                                    v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(kernel[v0, v1, v2, v3])\n                                    T.writes(kernel_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    kernel_shared[v0, v1, v2, v3] = kernel[v0, v1, v2, v3]\n                            for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 1, 1, 1, 1, 2, 1, 7, 1, 1, 7, 1, 8):\n                                with T.block(\"Conv2dOutput\"):\n                                    nn = T.axis.spatial(1, i0_3 + i0_4)\n                                    yy = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 56 + i0_2_i1_2_i2_2_i3_2_fused // 16 * 7 + i1_3 * 7 + i1_4)\n                                    xx = T.axis.spatial(112, i2_4 + i0_0_i1_0_i2_0_i3_0_fused // 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i2_3)\n                                    ff = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i3_3 * 8 + i3_4)\n                                    ry = T.axis.reduce(7, i4_0 + i4_1 + i4_2)\n                                    rx = T.axis.reduce(7, i5_0 * 7 + i5_1 * 7 + i5_2)\n                                    rc = T.axis.reduce(3, i6_1 + i6_2 + i6_0)\n                                    T.reads(PaddedInput_shared[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel_shared[ry, rx, rc, ff])\n                                    T.writes(Conv2dOutput_local[nn, yy, xx, ff])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        Conv2dOutput_local[nn, yy, xx, ff] = T.float32(0)\n                                    Conv2dOutput_local[nn, yy, xx, ff] = Conv2dOutput_local[nn, yy, xx, ff] + PaddedInput_shared[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel_shared[ry, rx, rc, ff]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 7, 1, 16):\n                            with T.block(\"Conv2dOutput_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 56 + i0_2_i1_2_i2_2_i3_2_fused // 16 * 7 + ax1)\n                                v2 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + ax2)\n                                v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + ax3)\n                                T.reads(Conv2dOutput_local[v0, v1, v2, v3], bias[v3], bn_scale[v3], bn_offset[v3])\n                                T.writes(compute[v0, v1, v2, v3])\n                                compute[v0, v1, v2, v3] = T.max((Conv2dOutput_local[v0, v1, v2, v3] + bias[v3]) * bn_scale[v3] + bn_offset[v3], T.float32(0))\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 2, 8, 1, 7]),\n        (\"SamplePerfectTile\", [7, 1, 16, 1, 1]),\n        (\"SamplePerfectTile\", [2, 2, 1, 2, 8]),\n        (\"SamplePerfectTile\", [7, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 7]),\n        (\"SamplePerfectTile\", [3, 1, 1]),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 3),\n    ]\n    mod = create_te_workload(\"CBR\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cbr_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_tbg():\n    # fmt: off\n    @T.prim_func\n    def tbg_0(query: T.Buffer[(1, 128, 12, 64), \"float32\"], value: T.Buffer[(1, 128, 12, 64), \"float32\"], C: T.Buffer[(1, 12, 128, 128), \"float32\"]) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":1024})\n            C_local = T.alloc_buffer([1, 12, 128, 128], dtype=\"float32\", scope=\"local\")\n            query_T_shared = T.alloc_buffer([1, 12, 128, 64], dtype=\"float32\", scope=\"shared\")\n            value_T_shared = T.alloc_buffer([1, 12, 64, 128], dtype=\"float32\", scope=\"shared\")\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(4, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(192, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(32, thread=\"threadIdx.x\"):\n                        for i4_0 in T.serial(8):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(12288):\n                                with T.block(\"query_T_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(12, ax0_ax1_ax2_ax3_fused // 1024)\n                                    v2 = T.axis.spatial(128, ax0_ax1_ax2_ax3_fused % 1024 // 8)\n                                    v3 = T.axis.spatial(64, i4_0 * 8 + ax0_ax1_ax2_ax3_fused % 8)\n                                    T.reads(query[v0, v2, v1, v3])\n                                    T.writes(query_T_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    query_T_shared[v0, v1, v2, v3] = query[v0, v2, v1, v3]\n                            for ax0_ax1_ax2_ax3_fused in T.serial(3072):\n                                with T.block(\"value_T_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(12, ax0_ax1_ax2_ax3_fused // 256)\n                                    v2 = T.axis.spatial(64, i4_0 * 8 + ax0_ax1_ax2_ax3_fused % 256 // 32)\n                                    v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(value[v0, v3, v1, v2])\n                                    T.writes(value_T_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    value_T_shared[v0, v1, v2, v3] = value[v0, v3, v1, v2]\n                            for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(4, 1, 2, 1, 1, 2, 1, 1, 4, 1):\n                                with T.block(\"C\"):\n                                    b = T.axis.spatial(1, i0_4 + i0_3)\n                                    h = T.axis.spatial(12, i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 32 * 2 + i1_3)\n                                    i = T.axis.spatial(128, i0_1_i1_1_i2_1_i3_1_fused % 32 // 8 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 4 * 4 + i2_3 * 4 + i2_4)\n                                    j = T.axis.spatial(128, i3_4 + i0_0_i1_0_i2_0_i3_0_fused * 32 + i0_1_i1_1_i2_1_i3_1_fused % 8 * 4 + i0_2_i1_2_i2_2_i3_2_fused % 4 + i3_3)\n                                    k = T.axis.reduce(64, i4_0 * 8 + i4_1 * 2 + i4_2)\n                                    T.reads(query_T_shared[b, h, i, k], value_T_shared[b, h, k, j])\n                                    T.writes(C_local[b, h, i, j])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        C_local[b, h, i, j] = T.float32(0)\n                                    C_local[b, h, i, j] = C_local[b, h, i, j] + query_T_shared[b, h, i, k] * value_T_shared[b, h, k, j]\n                        for ax0, ax1, ax2, ax3 in T.grid(1, 2, 4, 1):\n                            with T.block(\"C_local\"):\n                                v0 = T.axis.spatial(1, ax0)\n                                v1 = T.axis.spatial(12, i0_1_i1_1_i2_1_i3_1_fused // 32 * 2 + ax1)\n                                v2 = T.axis.spatial(128, i0_1_i1_1_i2_1_i3_1_fused % 32 // 8 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 4 * 4 + ax2)\n                                v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused * 32 + i0_1_i1_1_i2_1_i3_1_fused % 8 * 4 + i0_2_i1_2_i2_2_i3_2_fused % 4 + ax3)\n                                T.reads(C_local[v0, v1, v2, v3])\n                                T.writes(C[v0, v1, v2, v3])\n                                C[v0, v1, v2, v3] = C_local[v0, v1, v2, v3]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [1, 1, 1, 1, 1]),\n        (\"SamplePerfectTile\", [1, 6, 1, 2, 1]),\n        (\"SamplePerfectTile\", [1, 4, 8, 1, 4]),\n        (\"SamplePerfectTile\", [4, 8, 4, 1, 1]),\n        (\"SamplePerfectTile\", [8, 4, 2]),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 4),\n    ]\n    mod = create_te_workload(\"TBG\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[tbg_0],\n        expected_decisions=[decision_0],\n    )\n\n\nif __name__ == \"__main__\":\n    test_cuda_c1d()\n    test_cuda_c2d()\n    test_cuda_c3d()\n    test_cuda_cap()\n    test_cuda_dep()\n    test_cuda_dil()\n    test_cuda_gmm()\n    test_cuda_grp()\n    test_cuda_t2d()\n    test_cuda_nrm()\n    test_cuda_sfm()\n    test_cuda_cbr()\n    test_cuda_tbg()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_space_cuda_winograd.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests for MetaSchedule search space on CUDA\"\"\"\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.space_generation import (\n    check_sketches,\n    generate_design_space,\n    print_sketches,\n)\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.script import tir as T\nfrom tvm.target import Target\n\n\ndef _target():\n    return Target(\"nvidia/geforce-rtx-3070\")\n\n\ndef _design_space(mod):\n    return generate_design_space(\n        kind=\"cuda\",\n        mod=mod,\n        target=_target(),\n        types=ms.ScheduleRule,\n    )\n\n\ndef test_cuda_nhwc():\n    # fmt: off\n    @T.prim_func\n    def cuda_nhwc_0(data: T.Buffer[(1, 14, 14, 128), \"float32\"], weight: T.Buffer[(6, 6, 128, 128), \"float32\"], conv2d_winograd: T.Buffer[(1, 12, 12, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            input_tile_local = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\", scope=\"local\")\n            data_pack = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            bgemm = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\")\n            inverse = T.alloc_buffer([4, 4, 9, 128], dtype=\"float32\")\n            data_pack_local = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\", scope=\"local\")\n            bgemm_local = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\", scope=\"local\")\n            data_pack_shared = T.alloc_buffer([6, 6, 9, 128], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([6, 6, 128, 128], dtype=\"float32\", scope=\"shared\")\n            for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(2, thread=\"blockIdx.x\"):\n                for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(1024, thread=\"threadIdx.x\"):\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1):\n                        with T.block(\"input_tile\"):\n                            T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152)\n                            eps, nu = T.axis.remap(\"SS\", [ax0, ax1])\n                            p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8 + ax2)\n                            ci = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3)\n                            T.reads(data[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci])\n                            T.writes(input_tile_local[eps, nu, p, ci])\n                            T.block_attr({\"schedule_rule\":\"None\"})\n                            input_tile_local[eps, nu, p, ci] = T.if_then_else(0 <= p % 9 // 3 * 4 + eps and p % 9 // 3 * 4 + eps < 14 and 0 <= p % 3 * 4 + nu and p % 3 * 4 + nu < 14, data[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci], T.float32(0), dtype=\"float32\")\n                    for i0 in T.unroll(6):\n                        for i1 in T.unroll(6):\n                            for i4 in T.unroll(6):\n                                for i5 in T.unroll(6):\n                                    with T.block(\"data_pack\"):\n                                        T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152)\n                                        eps, nu = T.axis.remap(\"SS\", [i0, i1])\n                                        p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8)\n                                        ci = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8)\n                                        r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                        T.reads(input_tile_local[r_a, r_b, p, ci])\n                                        T.writes(data_pack_local[eps, nu, p, ci])\n                                        T.block_attr({\"schedule_rule\":\"conv2d_nhwc_winograd_data_pack\"})\n                                        with T.init():\n                                            data_pack_local[eps, nu, p, ci] = T.float32(0)\n                                        data_pack_local[eps, nu, p, ci] = data_pack_local[eps, nu, p, ci] + input_tile_local[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1):\n                        with T.block(\"data_pack_local\"):\n                            T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152)\n                            v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                            v2 = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8 + ax2)\n                            v3 = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3)\n                            T.reads(data_pack_local[v0, v1, v2, v3])\n                            T.writes(data_pack[v0, v1, v2, v3])\n                            data_pack[v0, v1, v2, v3] = data_pack_local[v0, v1, v2, v3]\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(96, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(27, thread=\"threadIdx.x\"):\n                        for i4_0 in T.serial(8):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(1728):\n                                with T.block(\"data_pack_shared\"):\n                                    v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0_ax1_ax2_ax3_fused // 864)\n                                    v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 864 // 144)\n                                    v2 = T.axis.spatial(9, ax0_ax1_ax2_ax3_fused % 144 // 16)\n                                    v3 = T.axis.spatial(128, i4_0 * 16 + ax0_ax1_ax2_ax3_fused % 16)\n                                    T.reads(data_pack[v0, v1, v2, v3])\n                                    T.writes(data_pack_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":1})\n                                    data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3]\n                            for ax0_ax1_ax2_ax3_fused in T.serial(768):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0_ax1_ax2_ax3_fused // 384)\n                                    v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 384 // 64)\n                                    v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + ax0_ax1_ax2_ax3_fused % 64 // 16)\n                                    v3 = T.axis.spatial(128, i4_0 * 16 + ax0_ax1_ax2_ax3_fused % 16)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 2, 1, 1, 2, 16, 1, 1, 1, 1):\n                                with T.block(\"bgemm\"):\n                                    eps = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + i0_3 + i0_4)\n                                    nu = T.axis.spatial(6, i1_3 + i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 9)\n                                    p = T.axis.spatial(9, i0_2_i1_2_i2_2_i3_2_fused % 9 + i2_3 + i2_4)\n                                    co = T.axis.spatial(128, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 2 + i3_3)\n                                    ci = T.axis.reduce(128, i4_0 * 16 + i4_1 * 16 + i4_2)\n                                    T.reads(data_pack_shared[eps, nu, p, ci], weight_shared[eps, nu, co, ci])\n                                    T.writes(bgemm_local[eps, nu, p, co])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\", \"meta_schedule.write_cache_level\":[3]})\n                                    with T.init():\n                                        bgemm_local[eps, nu, p, co] = T.float32(0)\n                                    bgemm_local[eps, nu, p, co] = bgemm_local[eps, nu, p, co] + data_pack_shared[eps, nu, p, ci] * weight_shared[eps, nu, co, ci]\n                        for ax0, ax1, ax2, ax3 in T.grid(2, 1, 1, 2):\n                            with T.block(\"bgemm_local\"):\n                                v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0)\n                                v1 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 9 + ax1)\n                                v2 = T.axis.spatial(9, i0_2_i1_2_i2_2_i3_2_fused % 9 + ax2)\n                                v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 2 + ax3)\n                                T.reads(bgemm_local[v0, v1, v2, v3])\n                                T.writes(bgemm[v0, v1, v2, v3])\n                                bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3]\n            for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(18, thread=\"blockIdx.x\"):\n                for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                    for i0 in T.unroll(4):\n                        for i1 in T.unroll(4):\n                            for i4 in T.unroll(6):\n                                for i5 in T.unroll(6):\n                                    with T.block(\"inverse\"):\n                                        vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                                        p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8)\n                                        co = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8)\n                                        r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                        T.reads(bgemm[r_a, r_b, p, co])\n                                        T.writes(inverse[vh, vw, p, co])\n                                        T.block_attr({\"schedule_rule\":\"conv2d_nhwc_winograd_inverse\"})\n                                        with T.init():\n                                            inverse[vh, vw, p, co] = T.float32(0)\n                                        inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n            for i0_i1_i2_i3_fused_0 in T.thread_binding(144, thread=\"blockIdx.x\"):\n                for i0_i1_i2_i3_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                    with T.block(\"conv2d_winograd\"):\n                        n = T.axis.spatial(1, 0)\n                        h = T.axis.spatial(12, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) // 1536)\n                        w = T.axis.spatial(12, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 1536 // 128)\n                        co = T.axis.spatial(128, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 128)\n                        T.reads(inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co])\n                        T.writes(conv2d_winograd[n, h, w, co])\n                        conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co]\n    # fmt: on\n    decision_0 = [\n        (\"SamplePerfectTile\", [3, 3]),\n        (\"SamplePerfectTile\", [16, 8]),\n        (\"SampleCategorical\", 1),\n        (\"SamplePerfectTile\", [3, 3]),\n        (\"SamplePerfectTile\", [16, 8]),\n        (\"SampleCategorical\", 5),\n        (\"SamplePerfectTile\", [3, 1, 1, 2, 1]),\n        (\"SamplePerfectTile\", [1, 2, 3, 1, 1]),\n        (\"SamplePerfectTile\", [1, 1, 9, 1, 1]),\n        (\"SamplePerfectTile\", [32, 2, 1, 2, 1]),\n        (\"SamplePerfectTile\", [8, 1, 16]),\n        (\"SampleCategorical\", 0),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 2),\n    ]\n    with _target():\n        mod = create_te_workload(\"C2D_WIN_NHWC\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cuda_nhwc_0],\n        expected_decisions=[decision_0],\n    )\n\n\ndef test_cuda_nchw():\n    # fmt: off\n    @T.prim_func\n    def cuda_nchw_0(data: T.Buffer[(1, 64, 56, 56), \"float32\"], weight: T.Buffer[(6, 6, 64, 64), \"float32\"], conv2d_winograd: T.Buffer[(1, 64, 56, 56), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":16})\n            input_tile_local = T.alloc_buffer([64, 196, 6, 6], dtype=\"float32\", scope=\"local\")\n            data_pack = T.alloc_buffer([6, 6, 64, 196], dtype=\"float32\")\n            bgemm = T.alloc_buffer([6, 6, 64, 196], dtype=\"float32\")\n            inverse_local = T.alloc_buffer([64, 196, 4, 4], dtype=\"float32\", scope=\"local\")\n            data_pack_local = T.alloc_buffer([6, 6, 64, 196], dtype=\"float32\", scope=\"local\")\n            bgemm_local = T.alloc_buffer([6, 6, 64, 196], dtype=\"float32\", scope=\"local\")\n            data_pack_shared = T.alloc_buffer([6, 6, 64, 196], dtype=\"float32\", scope=\"shared\")\n            weight_shared = T.alloc_buffer([6, 6, 64, 64], dtype=\"float32\", scope=\"shared\")\n            for i2_i3_fused_0 in T.thread_binding(25, thread=\"blockIdx.x\"):\n                for i2_i3_fused_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 6, 6):\n                        with T.block(\"input_tile\"):\n                            T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544)\n                            ci = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196 + ax0)\n                            p = T.axis.spatial(196, (i2_i3_fused_0 * 120 + i2_i3_fused_1) % 196 + ax1)\n                            eps, nu = T.axis.remap(\"SS\", [ax2, ax3])\n                            T.reads(data[p // 196, ci, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1])\n                            T.writes(input_tile_local[ci, p, eps, nu])\n                            T.block_attr({\"schedule_rule\":\"None\"})\n                            input_tile_local[ci, p, eps, nu] = T.if_then_else(1 <= p % 196 // 14 * 4 + eps and p % 196 // 14 * 4 + eps < 57 and 1 <= p % 14 * 4 + nu and p % 14 * 4 + nu < 57, data[p // 196, ci, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1], T.float32(0), dtype=\"float32\")\n                    for i0 in T.unroll(6):\n                        for i1 in T.unroll(6):\n                            for i4 in T.unroll(6):\n                                for i5 in T.unroll(6):\n                                    with T.block(\"data_pack\"):\n                                        T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544)\n                                        eps, nu = T.axis.remap(\"SS\", [i0, i1])\n                                        ci = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196)\n                                        p = T.axis.spatial(196, (i2_i3_fused_0 * 512 + i2_i3_fused_1) % 196)\n                                        r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                        T.reads(input_tile_local[ci, p, r_a, r_b])\n                                        T.writes(data_pack_local[eps, nu, ci, p])\n                                        T.block_attr({\"schedule_rule\":\"conv2d_nchw_winograd_data_pack\"})\n                                        with T.init():\n                                            data_pack_local[eps, nu, ci, p] = T.float32(0)\n                                        data_pack_local[eps, nu, ci, p] = data_pack_local[eps, nu, ci, p] + input_tile_local[ci, p, r_a, r_b] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n                    for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1):\n                        with T.block(\"data_pack_local\"):\n                            T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544)\n                            v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                            v2 = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196 + ax2)\n                            v3 = T.axis.spatial(196, (i2_i3_fused_0 * 120 + i2_i3_fused_1) % 196 + ax3)\n                            T.reads(data_pack_local[v0, v1, v2, v3])\n                            T.writes(data_pack[v0, v1, v2, v3])\n                            data_pack[v0, v1, v2, v3] = data_pack_local[v0, v1, v2, v3]\n            for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(14, thread=\"blockIdx.x\"):\n                for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(224, thread=\"vthread.x\"):\n                    for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(2, thread=\"threadIdx.x\"):\n                        for i4_0 in T.serial(2):\n                            for ax0_ax1_ax2_ax3_fused in T.serial(32256):\n                                with T.block(\"data_pack_shared\"):\n                                    v0 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused // 5376)\n                                    v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 5376 // 896)\n                                    v2 = T.axis.spatial(64, i4_0 * 32 + ax0_ax1_ax2_ax3_fused % 896 // 28)\n                                    v3 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + ax0_ax1_ax2_ax3_fused % 28)\n                                    T.reads(data_pack[v0, v1, v2, v3])\n                                    T.writes(data_pack_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":4})\n                                    data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3]\n                            for ax0_ax1_ax2_ax3_fused in T.serial(36864):\n                                with T.block(\"weight_shared\"):\n                                    v0 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused // 6144)\n                                    v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 6144 // 1024)\n                                    v2 = T.axis.spatial(64, i4_0 * 32 + ax0_ax1_ax2_ax3_fused % 1024 // 32)\n                                    v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(weight[v0, v1, v2, v3])\n                                    T.writes(weight_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                                    weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3]\n                            for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(16, 2, 3, 1, 4, 2, 3, 1, 1, 1):\n                                with T.block(\"bgemm\"):\n                                    eps = T.axis.spatial(6, i0_3 * 3 + i0_4)\n                                    nu = T.axis.spatial(6, i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 112 * 3 + i1_3)\n                                    co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 112 // 7 * 2 + i0_2_i1_2_i2_2_i3_2_fused + i2_3 + i2_4)\n                                    p = T.axis.spatial(196, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 7 * 4 + i3_3)\n                                    ci = T.axis.reduce(64, i4_0 * 32 + i4_1 * 2 + i4_2)\n                                    T.reads(data_pack_shared[eps, nu, ci, p], weight_shared[eps, nu, ci, co])\n                                    T.writes(bgemm_local[eps, nu, co, p])\n                                    T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                    with T.init():\n                                        bgemm_local[eps, nu, co, p] = T.float32(0)\n                                    bgemm_local[eps, nu, co, p] = bgemm_local[eps, nu, co, p] + data_pack_shared[eps, nu, ci, p] * weight_shared[eps, nu, ci, co]\n                        for ax0, ax1, ax2, ax3 in T.grid(6, 3, 1, 4):\n                            with T.block(\"bgemm_local\"):\n                                v0 = T.axis.spatial(6, ax0)\n                                v1 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 112 * 3 + ax1)\n                                v2 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 112 // 7 * 2 + i0_2_i1_2_i2_2_i3_2_fused + ax2)\n                                v3 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 7 * 4 + ax3)\n                                T.reads(bgemm_local[v0, v1, v2, v3])\n                                T.writes(bgemm[v0, v1, v2, v3])\n                                bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3]\n            for i0_i1_i2_0_i3_0_fused_0 in T.thread_binding(196, thread=\"blockIdx.x\"):\n                for i0_i1_i2_0_i3_0_fused_1 in T.thread_binding(64, thread=\"threadIdx.x\"):\n                    for ax0, ax1 in T.grid(1, 1):\n                        for ax2 in T.unroll(4):\n                            for ax3 in T.unroll(4):\n                                for ax4 in T.unroll(6):\n                                    for ax5 in T.unroll(6):\n                                        with T.block(\"inverse\"):\n                                            co = T.axis.spatial(64, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) // 196 + ax0)\n                                            p = T.axis.spatial(196, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 196 // 14 * 14 + (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 14 + ax1)\n                                            vh, vw, r_a, r_b = T.axis.remap(\"SSRR\", [ax2, ax3, ax4, ax5])\n                                            T.reads(bgemm[r_a, r_b, co, p])\n                                            T.writes(inverse_local[co, p, vh, vw])\n                                            T.block_attr({\"schedule_rule\":\"conv2d_nchw_winograd_inverse\"})\n                                            with T.init():\n                                                inverse_local[co, p, vh, vw] = T.float32(0)\n                                            inverse_local[co, p, vh, vw] = inverse_local[co, p, vh, vw] + bgemm[r_a, r_b, co, p] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n                    for i2_1, i3_1 in T.grid(4, 4):\n                        with T.block(\"conv2d_winograd\"):\n                            n = T.axis.spatial(1, 0)\n                            co = T.axis.spatial(64, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) // 196)\n                            h = T.axis.spatial(56, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 196 // 14 * 4 + i2_1)\n                            w = T.axis.spatial(56, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 14 * 4 + i3_1)\n                            T.reads(inverse_local[co, n * 196 + h // 4 * 14 + w // 4, h % 4, w % 4])\n                            T.writes(conv2d_winograd[n, co, h, w])\n                            conv2d_winograd[n, co, h, w] = inverse_local[co, n * 196 + h // 4 * 14 + w // 4, h % 4, w % 4]\n    # fmt: on\n    decision_0 = [\n        (\"SampleCategorical\", 4),\n        (\"SamplePerfectTile\", [1, 1, 1, 2, 3]),\n        (\"SamplePerfectTile\", [1, 2, 1, 3, 1]),\n        (\"SamplePerfectTile\", [2, 16, 2, 1, 1]),\n        (\"SamplePerfectTile\", [7, 7, 1, 4, 1]),\n        (\"SamplePerfectTile\", [2, 16, 2]),\n        (\"SampleCategorical\", 3),\n        (\"SampleCategorical\", 2),\n        (\"SampleCategorical\", 1),\n        (\"SampleCategorical\", 1),\n    ]\n    with _target():\n        mod = create_te_workload(\"C2D_WIN_NCHW\", 0)\n    actual = _design_space(mod)\n    check_sketches(\n        mod,\n        sketches=actual,\n        expected_mods=[cuda_nchw_0],\n        expected_decisions=[decision_0],\n        debug_mask=0,\n    )\n\n\nif __name__ == \"__main__\":\n    test_cuda_nhwc()\n    test_cuda_nchw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_space_generator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule SpaceGenerator \"\"\"\n# pylint: disable=missing-function-docstring\n\nimport math\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm._ffi.base import TVMError\nfrom tvm.meta_schedule.space_generator import (\n    PySpaceGenerator,\n    ScheduleFn,\n    SpaceGeneratorUnion,\n)\nfrom tvm.meta_schedule.tune_context import TuneContext\nfrom tvm.meta_schedule.utils import derived_object\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import Schedule\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n# fmt: off\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\"})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n# fmt: on\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument\n\n\ndef schedule_matmul(sch: Schedule):\n    block = sch.get_block(\"matmul\")\n    i, j, k = sch.get_loops(block=block)\n    # TODO(@zxybazh): Change to `sample_perfect_tile` after upstreaming\n    i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 4, 64, 2])\n    j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[4, 64, 2, 2])\n    k_0, k_1 = sch.split(loop=k, factors=[32, 32])\n    sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n\n\ndef _check_correct(schedule: Schedule):\n    trace = schedule.trace\n    for inst in trace.decisions:\n        assert math.prod(trace.decisions[inst]) == 1024\n\n\ndef test_meta_schedule_space_generator_schedule_fn():\n    mod = Matmul\n    space_generator = ScheduleFn(sch_fn=schedule_matmul)\n    design_spaces = space_generator.generate_design_space(mod)\n    assert len(design_spaces) == 1\n    (schedule,) = design_spaces\n    _check_correct(schedule)\n\n\ndef test_meta_schedule_design_space_generator_union():\n    mod = Matmul\n    space_generator = ScheduleFn(sch_fn=schedule_matmul)\n    space_generator_union = SpaceGeneratorUnion([space_generator, space_generator])\n    design_spaces = space_generator_union.generate_design_space(mod)\n    assert len(design_spaces) == 2\n    for design_space in design_spaces:\n        _check_correct(design_space)\n\n\ndef test_meta_schedule_design_space_generator_NIE():\n    @derived_object\n    class TestPySpaceGenerator(PySpaceGenerator):\n        def __init__(self):\n            super().__init__()\n            self.sch_rules = []\n            self.postprocs = []\n            self.mutator_probs = {}\n\n    with pytest.raises(\n        TVMError, match=\"PySpaceGenerator's InitializeWithTuneContext method not implemented!\"\n    ):\n        generator = TestPySpaceGenerator()\n        generator._initialize_with_tune_context(TuneContext())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_task_scheduler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Test Meta Schedule Task Scheduler \"\"\"\nimport random\nimport weakref\nfrom typing import Set\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.dummy_object import DummyBuilder, DummyRunner\nfrom tvm.script import tir as T\nfrom tvm.tir import Schedule\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\n@tvm.script.ir_module\nclass MatmulModule:\n    @T.prim_func\n    def main(  # type: ignore\n        a: T.handle,\n        b: T.handle,\n        c: T.handle,\n    ) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0  # type: ignore\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n@tvm.script.ir_module\nclass MatmulReluModule:\n    @T.prim_func\n    def main(  # type: ignore\n        a: T.handle,\n        b: T.handle,\n        d: T.handle,\n    ) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        D = T.match_buffer(d, (1024, 1024), \"float32\")\n        C = T.alloc_buffer((1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0  # type: ignore\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n        for i, j in T.grid(1024, 1024):\n            with T.block(\"relu\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                D[vi, vj] = T.max(C[vi, vj], 0.0)  # type: ignore\n\n\n@tvm.script.ir_module\nclass BatchMatmulModule:\n    @T.prim_func\n    def main(  # type: ignore\n        a: T.handle,\n        b: T.handle,\n        c: T.handle,\n    ) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, [16, 128, 128])\n        B = T.match_buffer(b, [16, 128, 128])\n        C = T.match_buffer(c, [16, 128, 128])\n        for n, i, j, k in T.grid(16, 128, 128, 128):\n            with T.block(\"matmul\"):\n                vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n                with T.init():\n                    C[vn, vi, vj] = 0.0  # type: ignore\n                C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk]\n\n\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks\n\n\ndef _schedule_matmul(sch: Schedule):\n    block = sch.get_block(\"matmul\")\n    i, j, k = sch.get_loops(block=block)\n    i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 4, 64, 2])\n    j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[4, 64, 2, 2])\n    k_0, k_1 = sch.split(loop=k, factors=[32, 32])\n    sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3)\n\n\ndef _schedule_batch_matmul(sch: Schedule):\n    block = sch.get_block(\"matmul\")\n    i, j, k, t = sch.get_loops(block=block)\n    i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 2, 2, 2])\n    j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[2, 4, 64, 2])\n    k_0, k_1 = sch.split(loop=k, factors=[32, 32])\n    t_0, t_1 = sch.split(loop=t, factors=[2, 512])\n    sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3, t_0, t_1)\n\n\n@ms.derived_object\nclass MyTaskScheduler(ms.task_scheduler.PyTaskScheduler):\n    done: Set = set()\n\n    def next_task_id(self) -> int:\n        tasks = self._outer().tasks_\n        while len(self.done) != len(tasks):\n            x = random.randint(0, len(tasks) - 1)\n            task = tasks[x]\n            if not task.is_terminated:\n                \"\"\"Calling base func via following route:\n                Python side:\n                    PyTaskScheduler does not have `_touch_task`\n                    Call TaskScheduler's `touch_task`, which calls ffi\n                C++ side:\n                    The ffi calls TaskScheduler's `touch_task`\n                    But it is overridden in PyTaskScheduler\n                    PyTaskScheduler checks if the function is overridden in python\n                    If not, it returns the TaskScheduler's vtable, calling\n                        TaskScheduler::TouchTask\n                \"\"\"\n                if task.runner_futures is not None:\n                    self.join_running_task(x)\n                return x\n            self.done.add(x)\n        return -1\n\n\ndef test_meta_schedule_task_scheduler_single():\n    num_trials_per_iter = 3\n    max_trials_per_task = 10\n    database = ms.database.MemoryDatabase()\n    round_robin = ms.task_scheduler.RoundRobin()\n    round_robin.tune(\n        [\n            ms.TuneContext(\n                MatmulModule,\n                target=tvm.target.Target(\"llvm\"),\n                space_generator=_schedule_matmul,\n                search_strategy=ms.search_strategy.ReplayTrace(),\n                task_name=\"Test\",\n                rand_state=42,\n            )\n        ],\n        [1.0],\n        max_trials_global=num_trials_per_iter,\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=64,\n        builder=DummyBuilder(),\n        runner=DummyRunner(),\n        database=database,\n        measure_callbacks=[ms.measure_callback.AddToDatabase()],\n        cost_model=None,\n    )\n    assert len(database) == max_trials_per_task\n\n\ndef test_meta_schedule_task_scheduler_multiple():\n    num_trials_per_iter = 6\n    max_trials_per_task = 101\n    tasks = [\n        ms.TuneContext(\n            MatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"Matmul\",\n            rand_state=42,\n        ),\n        ms.TuneContext(\n            MatmulReluModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"MatmulRelu\",\n            rand_state=0xDEADBEEF,\n        ),\n        ms.TuneContext(\n            BatchMatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_batch_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"BatchMatmul\",\n            rand_state=0x114514,\n        ),\n    ]\n    database = ms.database.MemoryDatabase()\n    round_robin = ms.task_scheduler.RoundRobin()\n    round_robin.tune(\n        tasks,\n        [1.0, 1.0, 1.0],\n        builder=DummyBuilder(),\n        runner=DummyRunner(),\n        database=database,\n        measure_callbacks=[ms.measure_callback.AddToDatabase()],\n        max_trials_global=max_trials_per_task * len(tasks),\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=num_trials_per_iter,\n        cost_model=None,\n    )\n    assert len(database) == max_trials_per_task * len(tasks)\n    for task in tasks:\n        assert (\n            len(\n                database.get_top_k(\n                    database.commit_workload(task.mod),\n                    100000,\n                )\n            )\n            == max_trials_per_task\n        )\n\n\ndef test_meta_schedule_task_scheduler_NIE():  # pylint: disable=invalid-name\n    @ms.derived_object\n    class NIETaskScheduler(ms.task_scheduler.PyTaskScheduler):\n        pass\n\n    with pytest.raises(ValueError, match=\"next_task_id is not defined\"):\n        scheduler = NIETaskScheduler()\n        scheduler.next_task_id()\n\n\ndef test_meta_schedule_task_scheduler_avoid_cyclic():  # pylint: disable=invalid-name\n    scheduler = MyTaskScheduler()\n    test = weakref.ref(scheduler)  # test if it can be destructed successfully\n    del scheduler\n    assert test() is None\n\n\ndef test_meta_schedule_task_scheduler_override_next_task_id_only():  # pylint: disable=invalid-name\n    max_trials_per_task = 101\n    tasks = [\n        ms.TuneContext(\n            MatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"Matmul\",\n            rand_state=42,\n        ),\n        ms.TuneContext(\n            MatmulReluModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"MatmulRelu\",\n            rand_state=0xDEADBEEF,\n        ),\n        ms.TuneContext(\n            BatchMatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_batch_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"BatchMatmul\",\n            rand_state=0x114514,\n        ),\n    ]\n    database = ms.database.MemoryDatabase()\n    scheduler = MyTaskScheduler()\n    scheduler.tune(\n        tasks,\n        task_weights=[1.0] * len(tasks),\n        builder=DummyBuilder(),\n        runner=DummyRunner(),\n        database=database,\n        measure_callbacks=[ms.measure_callback.AddToDatabase()],\n        max_trials_global=max_trials_per_task * len(tasks),\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=6,\n        cost_model=None,\n    )\n    assert len(database) == max_trials_per_task * len(tasks)\n    for task in tasks:\n        assert (\n            len(\n                database.get_top_k(\n                    database.commit_workload(task.mod),\n                    100000,\n                )\n            )\n            == max_trials_per_task\n        )\n\n\ndef test_meta_schedule_task_scheduler_multiple_gradient_based():\n    max_trials_per_task = 101\n    tasks = [\n        ms.TuneContext(\n            MatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"Matmul\",\n            rand_state=42,\n        ),\n        ms.TuneContext(\n            MatmulReluModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"MatmulRelu\",\n            rand_state=0xDEADBEEF,\n        ),\n        ms.TuneContext(\n            BatchMatmulModule,\n            target=tvm.target.Target(\"llvm\"),\n            space_generator=_schedule_batch_matmul,\n            search_strategy=ms.search_strategy.ReplayTrace(),\n            task_name=\"BatchMatmul\",\n            rand_state=0x114514,\n        ),\n    ]\n    database = ms.database.MemoryDatabase()\n    gradient_based = ms.task_scheduler.GradientBased()\n    gradient_based.tune(\n        tasks,\n        task_weights=[1.0, 1.0, 1.0],\n        builder=DummyBuilder(),\n        runner=DummyRunner(),\n        database=database,\n        measure_callbacks=[ms.measure_callback.AddToDatabase()],\n        max_trials_global=max_trials_per_task * len(tasks),\n        max_trials_per_task=max_trials_per_task,\n        num_trials_per_iter=6,\n        cost_model=None,\n    )\n    assert len(database) == max_trials_per_task * len(tasks)\n    for task in tasks:\n        assert (\n            len(database.get_top_k(database.commit_workload(task.mod), 10000))\n            == max_trials_per_task\n        )\n\n\nif __name__ == \"__main__\":\n    test_meta_schedule_task_scheduler_single()\n    test_meta_schedule_task_scheduler_multiple()\n    test_meta_schedule_task_scheduler_NIE()\n    test_meta_schedule_task_scheduler_avoid_cyclic()\n    test_meta_schedule_task_scheduler_override_next_task_id_only()\n    test_meta_schedule_task_scheduler_multiple_gradient_based()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_trace_apply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nimport tvm.testing\nimport tvm.meta_schedule as ms\nfrom tvm.script import tir as T\nfrom tvm.tir import Schedule, floormod, floordiv\nfrom tvm.tir.tensor_intrin.cuda import *\nfrom tvm.target import Target\nfrom tvm.target.codegen import llvm_lookup_intrinsic_id\n\n\n# fmt: off\n@tvm.script.ir_module\nclass Dense:\n    @T.prim_func\n    def main(\n        p0: T.Buffer[(128, 128), \"float32\"],\n        p1: T.Buffer[(128, 128), \"float32\"],\n        T_matmul_NT: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"layout_free_buffers\": [1], \"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2 in T.grid(128, 128, 128):\n            with T.block(\"T_matmul_NT\"):\n                i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                T.reads(p0[i, k], p1[j, k])\n                T.writes(T_matmul_NT[i, j])\n                T.block_attr({\"layout_free_placeholders\": []})\n                with T.init():\n                    T_matmul_NT[i, j] = T.float32(0)\n                T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1[j, k]\n\n\n@tvm.script.ir_module\nclass DenseAdd:\n    @T.prim_func\n    def main(\n        p0: T.Buffer[(128, 128), \"float32\"],\n        p1: T.Buffer[(128, 128), \"float32\"],\n        T_add: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        T_matmul_NT = T.alloc_buffer([128, 128], dtype=\"float32\")\n        compile_engine_const = T.alloc_buffer([], dtype=\"float32\")\n        for i0, i1, i2 in T.grid(128, 128, 128):\n            with T.block(\"T_matmul_NT\"):\n                i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                T.reads(p0[i, k], p1[j, k])\n                T.writes(T_matmul_NT[i, j])\n                T.block_attr({\"layout_free_placeholders\": []})\n                with T.init():\n                    T_matmul_NT[i, j] = T.float32(0)\n                T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1[j, k]\n        with T.block(\"compile_engine_const\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const[()])\n            compile_engine_const[()] = T.float32(1)\n        for i0, i1 in T.grid(128, 128):\n            with T.block(\"T_add\"):\n                ax0, ax1 = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(T_matmul_NT[ax0, ax1], compile_engine_const[()])\n                T.writes(T_add[ax0, ax1])\n                T_add[ax0, ax1] = T_matmul_NT[ax0, ax1] + compile_engine_const[()]\n\n\n@tvm.script.ir_module\nclass DenseAdd_scheduled_cpu:\n    @T.prim_func\n    def main(\n        p0: T.Buffer[(128, 128), \"float32\"],\n        p1: T.Buffer[(128, 128), \"float32\"],\n        T_add: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        T_matmul_NT_global = T.alloc_buffer([128, 128], dtype=\"float32\")\n        p1_global = T.alloc_buffer([2, 128, 64], dtype=\"float32\")\n        for ax0, ax1 in T.grid(128, 128):\n            with T.block(\"p1_global\"):\n                v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                T.reads(p1[v0, v1])\n                T.writes(p1_global[v0 // 64, v1, v0 % 64])\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\": 1})\n                p1_global[v0 // 64, v1, v0 % 64] = p1[v0, v1]\n        for i0_0_i1_0_fused_fused in T.parallel(4):\n            for i0_1, i1_1 in T.grid(8, 1):\n                for i0_2_init, i1_2_init, i0_3_init in T.grid(4, 1, 2):\n                    for i1_3_fused_init in T.vectorized(64):\n                        with T.block(\"T_matmul_NT_init\"):\n                            i = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused_fused // 2 * 64\n                                + i0_1 * 8\n                                + i0_2_init * 2\n                                + i0_3_init,\n                            )\n                            j = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused_fused % 2 * 64\n                                + i1_1 * 64\n                                + i1_2_init * 64\n                                + i1_3_fused_init,\n                            )\n                            T.reads()\n                            T.writes(T_matmul_NT_global[i, j])\n                            T.block_attr(\n                                {\n                                    \"layout_free_placeholders\": [],\n                                    \"meta_schedule.tiling_structure\": \"SSRSRS\",\n                                }\n                            )\n                            T_matmul_NT_global[i, j] = T.float32(0)\n                for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(128, 4, 1, 1, 2):\n                    for i1_3_fused in T.vectorized(64):\n                        with T.block(\"T_matmul_NT_update\"):\n                            i = T.axis.spatial(\n                                128, i0_0_i1_0_fused_fused // 2 * 64 + i0_1 * 8 + i0_2 * 2 + i0_3\n                            )\n                            j = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused_fused % 2 * 64 + i1_1 * 64 + i1_2 * 64 + i1_3_fused,\n                            )\n                            k = T.axis.reduce(128, i2_0 + i2_1)\n                            T.reads(\n                                T_matmul_NT_global[i, j], p0[i, k], p1_global[j // 64, k, j % 64]\n                            )\n                            T.writes(T_matmul_NT_global[i, j])\n                            T.block_attr(\n                                {\n                                    \"layout_free_placeholders\": [],\n                                    \"meta_schedule.tiling_structure\": \"SSRSRS\",\n                                }\n                            )\n                            T_matmul_NT_global[i, j] = (\n                                T_matmul_NT_global[i, j] + p0[i, k] * p1_global[j // 64, k, j % 64]\n                            )\n            for ax0 in T.serial(64):\n                for ax1_fused in T.vectorized(64):\n                    with T.block(\"T_matmul_NT_global\"):\n                        v0 = T.axis.spatial(128, i0_0_i1_0_fused_fused // 2 * 64 + ax0)\n                        v1 = T.axis.spatial(128, i0_0_i1_0_fused_fused % 2 * 64 + ax1_fused)\n                        T.reads(T_matmul_NT_global[v0, v1])\n                        T.writes(T_add[v0, v1])\n                        T_add[v0, v1] = T_matmul_NT_global[v0, v1] + T.float32(1)\n\n\n@tvm.script.ir_module\nclass DenseAdd_cpu_no_write_cache:\n    @T.prim_func\n    def main(p0: T.Buffer[(128, 128), \"float32\"], p1: T.Buffer[(128, 128), \"float32\"], T_add: T.Buffer[(128, 128), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        T_matmul_NT = T.alloc_buffer([128, 128], dtype=\"float32\")\n        p1_global = T.alloc_buffer([8, 4, 16, 32], dtype=\"float32\")\n        for ax0, ax1 in T.grid(128, 128):\n            with T.block(\"p1_global\"):\n                v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n                T.reads(p1[v0, v1])\n                T.writes(p1_global[v1 // 16, v0 // 32, v1 % 16, v0 % 32])\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\":1})\n                p1_global[v1 // 16, v0 // 32, v1 % 16, v0 % 32] = p1[v0, v1]\n        for i0_0_i1_0_i0_1_i1_1_fused in T.parallel(16, annotations={\"pragma_auto_unroll_max_step\":16, \"pragma_unroll_explicit\":1}):\n            for i0_2_init, i1_2_init, i0_3_init in T.grid(4, 4, 2):\n                for i1_3_fused_init in T.vectorized(32):\n                    with T.block(\"T_matmul_NT_init\"):\n                        i = T.axis.spatial(128, i0_0_i1_0_i0_1_i1_1_fused // 4 * 32 + i0_0_i1_0_i0_1_i1_1_fused % 4 * 8 + i0_2_init * 2 + i0_3_init)\n                        j = T.axis.spatial(128, i1_2_init * 32 + i1_3_fused_init)\n                        T.reads()\n                        T.writes(T_matmul_NT[i, j])\n                        T.block_attr({\"layout_free_placeholders\":[], \"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        T_matmul_NT[i, j] = T.float32(0)\n            for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(8, 4, 4, 16, 2):\n                for i1_3_fused in T.vectorized(32):\n                    with T.block(\"T_matmul_NT_update\"):\n                        i = T.axis.spatial(128, i0_0_i1_0_i0_1_i1_1_fused // 4 * 32 + i0_0_i1_0_i0_1_i1_1_fused % 4 * 8 + i0_2 * 2 + i0_3)\n                        j = T.axis.spatial(128, i1_2 * 32 + i1_3_fused)\n                        k = T.axis.reduce(128, i2_0 * 16 + i2_1)\n                        T.reads(T_matmul_NT[i, j], p0[i, k], p1_global[k // 16, j // 32, k % 16, j % 32])\n                        T.writes(T_matmul_NT[i, j])\n                        T.block_attr({\"layout_free_placeholders\":[], \"meta_schedule.tiling_structure\":\"SSRSRS\"})\n                        T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1_global[k // 16, j // 32, k % 16, j % 32]\n        for i0_i1_fused in T.parallel(16384):\n            with T.block(\"T_add\"):\n                ax0 = T.axis.spatial(128, i0_i1_fused // 128)\n                ax1 = T.axis.spatial(128, i0_i1_fused % 128)\n                T.reads(T_matmul_NT[ax0, ax1])\n                T.writes(T_add[ax0, ax1])\n                T_add[ax0, ax1] = T_matmul_NT[ax0, ax1] + T.float32(1)\n\n\n@tvm.script.ir_module\nclass DenseAdd_scheduled_gpu:\n    @T.prim_func\n    def main(\n        p0: T.Buffer[(128, 128), \"float32\"],\n        p1: T.Buffer[(128, 128), \"float32\"],\n        T_add: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        T_matmul_NT_local = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"local\")\n        p0_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        p1_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n        for i0_0_i1_0_fused in T.thread_binding(\n            32,\n            thread=\"blockIdx.x\",\n            annotations={\"pragma_auto_unroll_max_step\": 64, \"pragma_unroll_explicit\": 1},\n        ):\n            for i0_1_i1_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n                for i0_2_i1_2_fused in T.thread_binding(128, thread=\"threadIdx.x\"):\n                    for i0_3_init, i1_3_init, i0_4_init, i1_4_init in T.grid(1, 4, 1, 1):\n                        with T.block(\"T_matmul_NT_init\"):\n                            i = T.axis.spatial(\n                                128,\n                                i0_0_i1_0_fused // 4 * 16\n                                + i0_2_i1_2_fused // 8\n                                + i0_3_init\n                                + i0_4_init,\n                            )\n                            j = T.axis.spatial(\n                                128,\n                                i1_4_init\n                                + i0_0_i1_0_fused % 4 * 32\n                                + i0_2_i1_2_fused % 8 * 4\n                                + i1_3_init,\n                            )\n                            T.reads()\n                            T.writes(T_matmul_NT_local[i, j])\n                            T.block_attr(\n                                {\n                                    \"layout_free_placeholders\": [],\n                                    \"meta_schedule.thread_extent_high_inclusive\": 256,\n                                    \"meta_schedule.thread_extent_low_inclusive\": 16,\n                                    \"meta_schedule.tiling_structure\": \"SSSRRSRS\",\n                                }\n                            )\n                            T_matmul_NT_local[i, j] = T.float32(0)\n                    for i2_0 in T.serial(32):\n                        for ax0_ax1_fused_0 in T.serial(1):\n                            for ax0_ax1_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_2 in T.vectorized(2):\n                                    with T.block(\"p0_shared\"):\n                                        T.where(\n                                            (ax0_ax1_fused_0 * 128 + ax0_ax1_fused_1) * 2\n                                            + ax0_ax1_fused_2\n                                            < 64\n                                        )\n                                        v0 = T.axis.spatial(\n                                            128,\n                                            i0_0_i1_0_fused // 4 * 16\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 2\n                                                + ax0_ax1_fused_2\n                                            )\n                                            // 4,\n                                        )\n                                        v1 = T.axis.spatial(\n                                            128,\n                                            i2_0 * 4\n                                            + (\n                                                ax0_ax1_fused_0 * 256\n                                                + ax0_ax1_fused_1 * 2\n                                                + ax0_ax1_fused_2\n                                            )\n                                            % 4,\n                                        )\n                                        T.reads(p0[v0, v1])\n                                        T.writes(p0_shared[v0, v1])\n                                        p0_shared[v0, v1] = p0[v0, v1]\n                        for ax0_ax1_fused_0 in T.serial(1):\n                            for ax0_ax1_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                                for ax0_ax1_fused_2 in T.vectorized(4):\n                                    with T.block(\"p1_shared\"):\n                                        T.where(\n                                            (ax0_ax1_fused_0 * 128 + ax0_ax1_fused_1) * 4\n                                            + ax0_ax1_fused_2\n                                            < 128\n                                        )\n                                        v0 = T.axis.spatial(\n                                            128,\n                                            i0_0_i1_0_fused % 4 * 32\n                                            + (\n                                                ax0_ax1_fused_0 * 512\n                                                + ax0_ax1_fused_1 * 4\n                                                + ax0_ax1_fused_2\n                                            )\n                                            // 4,\n                                        )\n                                        v1 = T.axis.spatial(\n                                            128,\n                                            i2_0 * 4\n                                            + (\n                                                ax0_ax1_fused_0 * 512\n                                                + ax0_ax1_fused_1 * 4\n                                                + ax0_ax1_fused_2\n                                            )\n                                            % 4,\n                                        )\n                                        T.reads(p1[v0, v1])\n                                        T.writes(p1_shared[v0, v1])\n                                        p1_shared[v0, v1] = p1[v0, v1]\n                        for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(1, 1, 4, 4, 1, 1):\n                            with T.block(\"T_matmul_NT_update\"):\n                                i = T.axis.spatial(\n                                    128,\n                                    i0_0_i1_0_fused // 4 * 16 + i0_2_i1_2_fused // 8 + i0_3 + i0_4,\n                                )\n                                j = T.axis.spatial(\n                                    128,\n                                    i1_4\n                                    + i0_0_i1_0_fused % 4 * 32\n                                    + i0_2_i1_2_fused % 8 * 4\n                                    + i1_3,\n                                )\n                                k = T.axis.reduce(128, i2_0 * 4 + i2_1 * 4 + i2_2)\n                                T.reads(T_matmul_NT_local[i, j], p0_shared[i, k], p1_shared[j, k])\n                                T.writes(T_matmul_NT_local[i, j])\n                                T.block_attr(\n                                    {\n                                        \"layout_free_placeholders\": [],\n                                        \"meta_schedule.thread_extent_high_inclusive\": 256,\n                                        \"meta_schedule.thread_extent_low_inclusive\": 16,\n                                        \"meta_schedule.tiling_structure\": \"SSSRRSRS\",\n                                    }\n                                )\n                                T_matmul_NT_local[i, j] = (\n                                    T_matmul_NT_local[i, j] + p0_shared[i, k] * p1_shared[j, k]\n                                )\n                    for ax0, ax1 in T.grid(1, 4):\n                        with T.block(\"T_matmul_NT_local\"):\n                            v0 = T.axis.spatial(\n                                128, i0_0_i1_0_fused // 4 * 16 + i0_2_i1_2_fused // 8 + ax0\n                            )\n                            v1 = T.axis.spatial(\n                                128, i0_0_i1_0_fused % 4 * 32 + i0_2_i1_2_fused % 8 * 4 + ax1\n                            )\n                            T.reads(T_matmul_NT_local[v0, v1])\n                            T.writes(T_add[v0, v1])\n                            T_add[v0, v1] = T_matmul_NT_local[v0, v1] + T.float32(1)\n\n\n@tvm.script.ir_module\nclass Conv2dInt8:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[(1, 1, 1, 256), \"int64\"], p5: T.Buffer[(1, 1, 1, 256), \"int64\"], p6: T.Buffer[(1, 1, 1, 256), \"int64\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype=\"int8\")\n        conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_cast = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_multiply = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_right_shift = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_cast_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_cast_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"uint8\")\n        T_cast_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 64):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1, i2_1, i3_1])\n                T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1]\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64):\n            with T.block(\"conv2d_nhwc\"):\n                nn, yy, xx, ff, ry, rx, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc])\n                T.writes(conv2d_nhwc[nn, yy, xx, ff])\n                with T.init():\n                    conv2d_nhwc[nn, yy, xx, ff] = 0\n                conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], \"int32\") * T.cast(p1[ff, ry, rx, rc], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3])\n                T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[ax0, ax1, ax2, ax3])\n                T.writes(T_cast[ax0, ax1, ax2, ax3])\n                T_cast[ax0, ax1, ax2, ax3] = T.cast(T_add[ax0, ax1, ax2, ax3], \"int64\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_multiply\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_cast[ax0, ax1, ax2, ax3], p4[0, 0, 0, ax3])\n                T.writes(T_multiply[ax0, ax1, ax2, ax3])\n                T_multiply[ax0, ax1, ax2, ax3] = T_cast[ax0, ax1, ax2, ax3] * p4[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_multiply[ax0, ax1, ax2, ax3], p5[0, 0, 0, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = T_multiply[ax0, ax1, ax2, ax3] + p5[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_right_shift\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3])\n                T.writes(T_right_shift[ax0, ax1, ax2, ax3])\n                T_right_shift[ax0, ax1, ax2, ax3] = T.shift_right(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3], dtype=\"int64\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_right_shift[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_1[ax0, ax1, ax2, ax3])\n                T_cast_1[ax0, ax1, ax2, ax3] = T.cast(T_right_shift[ax0, ax1, ax2, ax3], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p7[()], T_cast_1[ax0, ax1, ax2, ax3])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3])\n                T_add_2[ax0, ax1, ax2, ax3] = p7[()] + T_cast_1[ax0, ax1, ax2, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add_2[i0_2, i1_2, i2_2, i3_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2] = T.max(T.min(T_add_2[i0_2, i1_2, i2_2, i3_2], 255), 0)\n        for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_3, i1_3, i2_3, i3_3])\n                T.reads(compute_1[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_2[ax0, ax1, ax2, ax3])\n                T_cast_2[ax0, ax1, ax2, ax3] = T.cast(compute_1[ax0, ax1, ax2, ax3], \"uint8\")\n        for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_3\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_4, i1_4, i2_4, i3_4])\n                T.reads(T_cast_2[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_3[ax0, ax1, ax2, ax3])\n                T_cast_3[ax0, ax1, ax2, ax3] = T.cast(T_cast_2[ax0, ax1, ax2, ax3], \"int32\")\n        for i0_5, i1_5, i2_5, i3_5 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_5, i1_5, i2_5, i3_5])\n                T.reads(T_cast_3[ax0, ax1, ax2, ax3], p8[0])\n                T.writes(T_subtract_1[ax0, ax1, ax2, ax3])\n                T_subtract_1[ax0, ax1, ax2, ax3] = T_cast_3[ax0, ax1, ax2, ax3] - p8[0]\n        for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_1\"):\n                i0_7, i1_7, i2_7, i3_7 = T.axis.remap(\"SSSS\", [i0_6, i1_6, i2_6, i3_6])\n                T.reads(T_subtract_1[i0_7, i1_7, i2_7, i3_7])\n                T.writes(compute[i0_7, i1_7, i2_7, i3_7])\n                compute[i0_7, i1_7, i2_7, i3_7] = T.q_multiply_shift(T_subtract_1[i0_7, i1_7, i2_7, i3_7], 1963325822, 31, 1, dtype=\"int32\")\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_target:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[(1, 1, 1, 256), \"int64\"], p5: T.Buffer[(1, 1, 1, 256), \"int64\"], p6: T.Buffer[(1, 1, 1, 256), \"int64\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], p9: T.Buffer[(16, 56, 56, 256), \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"uint8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype=\"int8\")\n        conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_cast = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_multiply = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_right_shift = T.alloc_buffer([16, 56, 56, 256], dtype=\"int64\")\n        T_cast_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_cast_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"uint8\")\n        T_cast_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_cast_4 = T.alloc_buffer([16, 56, 56, 256], dtype=\"uint8\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 64):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1, i2_1, i3_1])\n                T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1]\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64):\n            with T.block(\"conv2d_nhwc\"):\n                nn, yy, xx, ff, ry, rx, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc])\n                T.writes(conv2d_nhwc[nn, yy, xx, ff])\n                with T.init():\n                    conv2d_nhwc[nn, yy, xx, ff] = 0\n                conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], \"int32\") * T.cast(p1[ff, ry, rx, rc], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3])\n                T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[ax0, ax1, ax2, ax3])\n                T.writes(T_cast[ax0, ax1, ax2, ax3])\n                T_cast[ax0, ax1, ax2, ax3] = T.cast(T_add[ax0, ax1, ax2, ax3], \"int64\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_multiply\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_cast[ax0, ax1, ax2, ax3], p4[0, 0, 0, ax3])\n                T.writes(T_multiply[ax0, ax1, ax2, ax3])\n                T_multiply[ax0, ax1, ax2, ax3] = T_cast[ax0, ax1, ax2, ax3] * p4[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_multiply[ax0, ax1, ax2, ax3], p5[0, 0, 0, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = T_multiply[ax0, ax1, ax2, ax3] + p5[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_right_shift\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3])\n                T.writes(T_right_shift[ax0, ax1, ax2, ax3])\n                T_right_shift[ax0, ax1, ax2, ax3] = T.shift_right(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3], dtype=\"int64\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_right_shift[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_1[ax0, ax1, ax2, ax3])\n                T_cast_1[ax0, ax1, ax2, ax3] = T.cast(T_right_shift[ax0, ax1, ax2, ax3], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p7[()], T_cast_1[ax0, ax1, ax2, ax3])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3])\n                T_add_2[ax0, ax1, ax2, ax3] = p7[()] + T_cast_1[ax0, ax1, ax2, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add_2[i0_2, i1_2, i2_2, i3_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2] = T.max(T.min(T_add_2[i0_2, i1_2, i2_2, i3_2], 255), 0)\n        for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_3, i1_3, i2_3, i3_3])\n                T.reads(compute_1[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_2[ax0, ax1, ax2, ax3])\n                T_cast_2[ax0, ax1, ax2, ax3] = T.cast(compute_1[ax0, ax1, ax2, ax3], \"uint8\")\n        for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_3\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_4, i1_4, i2_4, i3_4])\n                T.reads(T_cast_2[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_3[ax0, ax1, ax2, ax3])\n                T_cast_3[ax0, ax1, ax2, ax3] = T.cast(T_cast_2[ax0, ax1, ax2, ax3], \"int32\")\n        for i0_5, i1_5, i2_5, i3_5 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_5, i1_5, i2_5, i3_5])\n                T.reads(T_cast_3[ax0, ax1, ax2, ax3], p8[0])\n                T.writes(T_subtract_1[ax0, ax1, ax2, ax3])\n                T_subtract_1[ax0, ax1, ax2, ax3] = T_cast_3[ax0, ax1, ax2, ax3] - p8[0]\n        for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_1\"):\n                i0_7, i1_7, i2_7, i3_7 = T.axis.remap(\"SSSS\", [i0_6, i1_6, i2_6, i3_6])\n                T.reads(T_subtract_1[i0_7, i1_7, i2_7, i3_7])\n                T.writes(compute_2[i0_7, i1_7, i2_7, i3_7])\n                compute_2[i0_7, i1_7, i2_7, i3_7] = T.q_multiply_shift(T_subtract_1[i0_7, i1_7, i2_7, i3_7], 1098990753, 31, 1, dtype=\"int32\")\n        for i0_8, i1_8, i2_8, i3_8 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_3\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_8, i1_8, i2_8, i3_8])\n                T.reads(compute_2[ax0, ax1, ax2, ax3], p9[ax0, ax1, ax2, ax3])\n                T.writes(T_add_3[ax0, ax1, ax2, ax3])\n                T_add_3[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] + p9[ax0, ax1, ax2, ax3]\n        for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_2\"):\n                i0_10, i1_10, i2_10, i3_10 = T.axis.remap(\"SSSS\", [i0_9, i1_9, i2_9, i3_9])\n                T.reads(T_add_3[i0_10, i1_10, i2_10, i3_10])\n                T.writes(compute_3[i0_10, i1_10, i2_10, i3_10])\n                compute_3[i0_10, i1_10, i2_10, i3_10] = T.max(T.min(T_add_3[i0_10, i1_10, i2_10, i3_10], 255), 0)\n        for i0_11, i1_11, i2_11, i3_11 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_cast_4\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_11, i1_11, i2_11, i3_11])\n                T.reads(compute_3[ax0, ax1, ax2, ax3])\n                T.writes(T_cast_4[ax0, ax1, ax2, ax3])\n                T_cast_4[ax0, ax1, ax2, ax3] = T.cast(compute_3[ax0, ax1, ax2, ax3], \"uint8\")\n        for i0_12, i1_12, i2_12, i3_12 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_3\"):\n                i0_13, i1_13, i2_13, i3_13 = T.axis.remap(\"SSSS\", [i0_12, i1_12, i2_12, i3_12])\n                T.reads(T_cast_4[i0_13, i1_13, i2_13, i3_13])\n                T.writes(compute[i0_13, i1_13, i2_13, i3_13])\n                compute[i0_13, i1_13, i2_13, i3_13] = T.max(T.min(T_cast_4[i0_13, i1_13, i2_13, i3_13], T.uint8(255)), T.uint8(0))\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_tensorcore_scheduled:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[(1, 1, 1, 256), \"int64\"], p5: T.Buffer[(1, 1, 1, 256), \"int64\"], p6: T.Buffer[(1, 1, 1, 256), \"int64\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], p9: T.Buffer[(16, 56, 56, 256), \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"uint8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        a0 = T.var(\"int32\")\n        a1 = T.var(\"int32\")\n        b0 = T.var(\"int32\")\n        b1 = T.var(\"int32\")\n        c0 = T.var(\"int32\")\n        c1 = T.var(\"int32\")\n        d0 = T.var(\"int32\")\n        d0_1 = T.var(\"int32\")\n        d0_2 = T.var(\"int32\")\n        d0_3 = T.var(\"int32\")\n        d1 = T.var(\"int32\")\n        d1_1 = T.var(\"int32\")\n        d1_2 = T.var(\"int32\")\n        d1_3 = T.var(\"int32\")\n        s0 = T.var(\"int32\")\n        s0_1 = T.var(\"int32\")\n        s0_2 = T.var(\"int32\")\n        s1 = T.var(\"int32\")\n        s1_1 = T.var(\"int32\")\n        s1_2 = T.var(\"int32\")\n        # body\n        # with T.block(\"root\")\n        conv2d_nhwc_reindex_shared = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"shared\")\n        conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"wmma.accumulator\")\n        pad_temp_reindex_shared = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"shared\")\n        p1_reindex_shared = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"shared\")\n        pad_temp_reindex_shared_wmma_matrix_a = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"wmma.matrix_a\")\n        p1_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"wmma.matrix_b\")\n        for ax2_0_0_ax3_0_0_fused in T.thread_binding(3136, thread=\"blockIdx.x\", annotations={\"pragma_auto_unroll_max_step\":512, \"pragma_unroll_explicit\":1}):\n            for ax2_0_1_ax3_0_1_fused in T.thread_binding(1, thread=\"vthread.x\"):\n                for ax2_0_2_ax3_0_2_fused in T.thread_binding(16, thread=\"threadIdx.x\"):\n                    for ax0_0, ax1_0 in T.grid(1, 1):\n                        for ax2_0_3_init, ax3_0_3_init, ax2_0_4_init, ax3_0_4_init in T.grid(1, 1, 1, 1):\n                            with T.block(\"conv2d_nhwc_o_init\"):\n                                v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3_init + ax2_0_4_init)\n                                v3_o = T.axis.spatial(16, ax3_0_4_init + ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2 + ax3_0_3_init)\n                                T.reads()\n                                T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"warp_execution\":1})\n                                C = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype=\"int32\", strides=[d1, d0], scope=\"wmma.accumulator\", offset_factor=16)\n                                T.evaluate(T.tvm_fill_fragment(C.data, 16, 16, 16, C.elem_offset // d1 // 16 * (d1 // 16) + C.elem_offset % d1 // 16, T.float32(0), dtype=\"handle\"))\n                        for ax4_0_0 in T.serial(2):\n                            for ax0_ax1_fused_0 in T.serial(16):\n                                for ax0_ax1_fused_1 in T.thread_binding(16, thread=\"threadIdx.x\"):\n                                    for ax0_ax1_fused_2 in T.vectorized(16):\n                                        with T.block(\"pad_temp_reindex_shared\"):\n                                            v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 8 * 128 + (ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 16 + ax0_ax1_fused_2) // 32)\n                                            v1 = T.axis.spatial(64, ax4_0_0 * 32 + (ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 16 + ax0_ax1_fused_2) % 32)\n                                            T.reads(p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                                            T.writes(pad_temp_reindex_shared[v0, v1])\n                                            T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 16]]})\n                                            pad_temp_reindex_shared[v0, v1] = p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]\n                            for ax0_ax1_ax2_ax3_fused_0 in T.serial(8):\n                                for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(16, thread=\"threadIdx.x\"):\n                                    for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(8):\n                                        with T.block(\"p1_reindex_shared\"):\n                                            v0 = T.axis.spatial(1, 0)\n                                            v1 = T.axis.spatial(1, 0)\n                                            v2 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 8 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 128 + ax0_ax1_ax2_ax3_fused_1 * 8 + ax0_ax1_ax2_ax3_fused_2) // 32)\n                                            v3 = T.axis.spatial(64, ax4_0_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 128 + ax0_ax1_ax2_ax3_fused_1 * 8 + ax0_ax1_ax2_ax3_fused_2) % 32)\n                                            T.reads(p1[v2, v0, v1, v3])\n                                            T.writes(p1_reindex_shared[v0, v1, v2, v3])\n                                            T.block_attr({\"buffer_dim_align\":[[0, 2, 32, 16]]})\n                                            p1_reindex_shared[v0, v1, v2, v3] = p1[v2, v0, v1, v3]\n                            for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 1):\n                                for ax0_0_1, ax1_0_1 in T.grid(1, 2):\n                                    with T.block(\"pad_temp_reindex_shared_wmma.matrix_a_o\"):\n                                        v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2)\n                                        v1_o = T.axis.spatial(4, ax4_0_0 * 2 + ax1_0_1)\n                                        T.reads(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        A = T.match_buffer(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[s1, s0], scope=\"shared\", offset_factor=16)\n                                        C_1 = T.match_buffer(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[d1_1, d0_1], scope=\"wmma.matrix_a\", offset_factor=16)\n                                        T.evaluate(T.tvm_load_matrix_sync(C_1.data, 16, 16, 16, C_1.elem_offset // d1_1 // 16 * (d1_1 // 16) + C_1.elem_offset % d1_1 // 16, T.tvm_access_ptr(T.type_annotation(dtype=\"int8\"), A.data, A.elem_offset, s1 * 16, 1, dtype=\"handle\"), s1, \"row_major\", dtype=\"handle\"))\n                                for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 1, 2):\n                                    with T.block(\"p1_reindex_shared_wmma.matrix_b_o\"):\n                                        v0 = T.axis.spatial(1, 0)\n                                        v1 = T.axis.spatial(1, 0)\n                                        v2_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2)\n                                        v3_o = T.axis.spatial(4, ax4_0_0 * 2 + ax3_0)\n                                        T.reads(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        A_1 = T.match_buffer(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[s1_1, s0_1], scope=\"shared\", offset_factor=16)\n                                        C_2 = T.match_buffer(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[d1_2, d0_2], scope=\"wmma.matrix_b\", offset_factor=16)\n                                        T.evaluate(T.tvm_load_matrix_sync(C_2.data, 16, 16, 16, C_2.elem_offset // d1_2 // 16 * (d1_2 // 16) + C_2.elem_offset % d1_2 // 16, T.tvm_access_ptr(T.type_annotation(dtype=\"int8\"), A_1.data, A_1.elem_offset, s1_1 * 16, 1, dtype=\"handle\"), s1_1, \"col_major\", dtype=\"handle\"))\n                                for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 2, 1, 1):\n                                    with T.block(\"conv2d_nhwc_o_update\"):\n                                        v0 = T.axis.reduce(1, 0)\n                                        v1 = T.axis.reduce(1, 0)\n                                        v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3 + ax2_0_4)\n                                        v3_o = T.axis.spatial(16, ax3_0_4 + ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2 + ax3_0_3)\n                                        v4_o = T.axis.reduce(4, ax4_0_0 * 2 + ax4_0_1 * 2 + ax4_0_2)\n                                        T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16])\n                                        T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"warp_execution\":1})\n                                        A_2 = T.match_buffer(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[a1, a0], scope=\"wmma.matrix_a\", offset_factor=16)\n                                        B = T.match_buffer(p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], [16, 16], dtype=\"int8\", strides=[b1, b0], scope=\"wmma.matrix_b\", offset_factor=16)\n                                        C_3 = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype=\"int32\", strides=[c1, c0], scope=\"wmma.accumulator\", offset_factor=16)\n                                        T.evaluate(T.tvm_mma_sync(C_3.data, C_3.elem_offset // c1 // 16 * (c1 // 16) + C_3.elem_offset % c1 // 16, A_2.data, A_2.elem_offset // a1 // 16 * (a1 // 16) + A_2.elem_offset % a1 // 16, B.data, B.elem_offset // b1 // 16 * (b1 // 16) + B.elem_offset % b1 // 16, C_3.data, C_3.elem_offset // c1 // 16 * (c1 // 16) + C_3.elem_offset % c1 // 16, dtype=\"handle\"))\n                    for ax0_0, ax1_0 in T.grid(1, 1):\n                        with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\"):\n                            v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2)\n                            v1_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2)\n                            T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                            A_3 = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype=\"int32\", strides=[d1_3, d0_3], scope=\"wmma.accumulator\", offset_factor=16)\n                            C_4 = T.match_buffer(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype=\"int32\", strides=[s1_2, s0_2], scope=\"shared\", offset_factor=16)\n                            T.evaluate(T.tvm_store_matrix_sync(A_3.data, 16, 16, 16, A_3.elem_offset // d1_3 // 16 * (d1_3 // 16) + A_3.elem_offset % d1_3 // 16, T.tvm_access_ptr(T.type_annotation(dtype=\"int32\"), C_4.data, C_4.elem_offset, s1_2 * 16, 2, dtype=\"handle\"), s1_2, \"row_major\", dtype=\"handle\"))\n                for ax0, ax1_0 in T.grid(128, 2):\n                    for ax1_1 in T.thread_binding(16, thread=\"threadIdx.x\"):\n                        with T.block(\"conv2d_nhwc_reindex_shared\"):\n                            v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 8 * 128 + ax0)\n                            v1 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 8 * 32 + ax1_0 * 16 + ax1_1)\n                            T.reads(p7[()], conv2d_nhwc_reindex_shared[v0, v1], p2[0, 0, 0, v1], p3[0, 0, 0, v1], p4[0, 0, 0, v1], p5[0, 0, 0, v1], p6[0, 0, 0, v1], p8[0], p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                            T.writes(compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                            compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] = T.max(T.min(T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(p7[()] + T.cast(T.shift_right(T.cast(conv2d_nhwc_reindex_shared[v0, v1] - p2[0, 0, 0, v1] + p3[0, 0, 0, v1], \"int64\") * p4[0, 0, 0, v1] + p5[0, 0, 0, v1], p6[0, 0, 0, v1], dtype=\"int64\"), \"int32\"), 255), 0), \"uint8\"), \"int32\") - p8[0], 1098990753, 31, 1, dtype=\"int32\") + p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1], 255), 0), \"uint8\"), T.uint8(255)), T.uint8(0))\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_NCHWc:\n    @T.prim_func\n    def main(p0: T.Buffer[(1, 32, 7, 7, 16), \"uint8\"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), \"int8\"], p2: T.Buffer[(1, 128, 1, 1, 16), \"int32\"], p3: T.Buffer[(1, 128, 1, 1, 16), \"float32\"], p4: T.Buffer[1, \"float32\"], p5: T.Buffer[(1, 128, 7, 7, 16), \"int32\"], compute: T.Buffer[(1, 128, 7, 7, 16), \"uint8\"]) -> None:\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        compile_engine_const = T.alloc_buffer([], dtype=\"float32\")\n        conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_add = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_multiply = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        compile_engine_const_1 = T.alloc_buffer([], dtype=\"float32\")\n        T_add_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_floor = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_cast_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"uint8\")\n        T_cast_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_subtract = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_multiply_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        compile_engine_const_2 = T.alloc_buffer([], dtype=\"float32\")\n        T_add_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_floor_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_cast_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_add_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        compute_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast_5 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"uint8\")\n        with T.block(\"compile_engine_const\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const[()])\n            compile_engine_const[()] = T.float32(0.94537687301635742)\n        for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 128, 7, 7, 16, 1, 1, 32, 4, 4):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                n, oc_chunk, oh, ow, oc_block, kh, kw, ic_outer, ic_f_inner, ic_s_inner = T.axis.remap(\"SSSSSRRRRR\", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9])\n                T.reads(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner])\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                T.block_attr({\"schedule_rule\":\"meta_schedule.conv2d_NCHWc_int8\", \"workload\":[\"conv2d_NCHWc_int8.x86\", [\"TENSOR\", [1, 32, 7, 7, 16], \"uint8\"], [\"TENSOR\", [128, 32, 1, 1, 4, 16, 4], \"int8\"], [1, 1], [0, 0, 0, 0], [1, 1], \"NCHW16c\", \"NCHW16c\", \"int32\"]})\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] + T.cast(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\") * T.cast(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4], p2[ax0, ax1, 0, 0, ax4])\n                T.writes(T_add[ax0, ax1, ax2, ax3, ax4])\n                T_add[ax0, ax1, ax2, ax3, ax4] = conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4] + p2[ax0, ax1, 0, 0, ax4]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast[ax0, ax1, ax2, ax3, ax4])\n                T_cast[ax0, ax1, ax2, ax3, ax4] = T.cast(T_add[ax0, ax1, ax2, ax3, ax4], \"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_multiply\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast[ax0, ax1, ax2, ax3, ax4], p3[ax0, ax1, 0, 0, ax4])\n                T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4])\n                T_multiply[ax0, ax1, ax2, ax3, ax4] = T_cast[ax0, ax1, ax2, ax3, ax4] * p3[ax0, ax1, 0, 0, ax4]\n        with T.block(\"compile_engine_const_1\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_1[()])\n            compile_engine_const_1[()] = T.float32(54.5)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_multiply[ax0, ax1, ax2, ax3, ax4], compile_engine_const_1[()])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3, ax4])\n                T_add_1[ax0, ax1, ax2, ax3, ax4] = T_multiply[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_1[()]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_floor\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_floor[ax0, ax1, ax2, ax3, ax4])\n                T_floor[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_1[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_floor[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_1[ax0, ax1, ax2, ax3, ax4])\n                T_cast_1[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor[ax0, ax1, ax2, ax3, ax4], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute\"):\n                i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_1[i0_1, i1_1, i2_1, i3_1, i4_1])\n                T.writes(compute_1[i0_1, i1_1, i2_1, i3_1, i4_1])\n                compute_1[i0_1, i1_1, i2_1, i3_1, i4_1] = T.max(T.min(T_cast_1[i0_1, i1_1, i2_1, i3_1, i4_1], 255), 0)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(compute_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_2[ax0, ax1, ax2, ax3, ax4])\n                T_cast_2[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_1[ax0, ax1, ax2, ax3, ax4], \"uint8\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_3[ax0, ax1, ax2, ax3, ax4])\n                T_cast_3[ax0, ax1, ax2, ax3, ax4] = T.cast(T_cast_2[ax0, ax1, ax2, ax3, ax4], \"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_3[ax0, ax1, ax2, ax3, ax4], p4[0])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3, ax4])\n                T_subtract[ax0, ax1, ax2, ax3, ax4] = T_cast_3[ax0, ax1, ax2, ax3, ax4] - p4[0]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_multiply_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(compile_engine_const[()], T_subtract[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4])\n                T_multiply_1[ax0, ax1, ax2, ax3, ax4] = compile_engine_const[()] * T_subtract[ax0, ax1, ax2, ax3, ax4]\n        with T.block(\"compile_engine_const_2\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_2[()])\n            compile_engine_const_2[()] = T.float32(0.5)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_multiply_1[ax0, ax1, ax2, ax3, ax4], compile_engine_const_2[()])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3, ax4])\n                T_add_2[ax0, ax1, ax2, ax3, ax4] = T_multiply_1[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_2[()]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_floor_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_floor_1[ax0, ax1, ax2, ax3, ax4])\n                T_floor_1[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_2[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_4\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_floor_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_4[ax0, ax1, ax2, ax3, ax4])\n                T_cast_4[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_1[ax0, ax1, ax2, ax3, ax4], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_4[ax0, ax1, ax2, ax3, ax4], p5[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_add_3[ax0, ax1, ax2, ax3, ax4])\n                T_add_3[ax0, ax1, ax2, ax3, ax4] = T_cast_4[ax0, ax1, ax2, ax3, ax4] + p5[ax0, ax1, ax2, ax3, ax4]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute_1\"):\n                i0_2, i1_2, i2_2, i3_2, i4_2 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_3[i0_2, i1_2, i2_2, i3_2, i4_2])\n                T.writes(compute_2[i0_2, i1_2, i2_2, i3_2, i4_2])\n                compute_2[i0_2, i1_2, i2_2, i3_2, i4_2] = T.max(T.min(T_add_3[i0_2, i1_2, i2_2, i3_2, i4_2], 255), 0)\n        for i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_5\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0_3, i1_3, i2_3, i3_3, i4_3])\n                T.reads(compute_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_5[ax0, ax1, ax2, ax3, ax4])\n                T_cast_5[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_2[ax0, ax1, ax2, ax3, ax4], \"uint8\")\n        for i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute_2\"):\n                i0_5, i1_5, i2_5, i3_5, i4_5 = T.axis.remap(\"SSSSS\", [i0_4, i1_4, i2_4, i3_4, i4_4])\n                T.reads(T_cast_5[i0_5, i1_5, i2_5, i3_5, i4_5])\n                T.writes(compute[i0_5, i1_5, i2_5, i3_5, i4_5])\n                compute[i0_5, i1_5, i2_5, i3_5, i4_5] = T.max(T.min(T_cast_5[i0_5, i1_5, i2_5, i3_5, i4_5], T.uint8(255)), T.uint8(0))\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_NCHWc_target:\n    @T.prim_func\n    def main(p0: T.Buffer[(1, 32, 7, 7, 16), \"uint8\"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), \"int8\"], p2: T.Buffer[(1, 128, 1, 1, 16), \"int32\"], p3: T.Buffer[(1, 128, 1, 1, 16), \"float32\"], p4: T.Buffer[1, \"float32\"], p5: T.Buffer[(1, 128, 7, 7, 16), \"uint8\"], T_cast: T.Buffer[(1, 128, 7, 7, 16), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        compile_engine_const = T.alloc_buffer([], dtype=\"float32\")\n        conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_add = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_multiply = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        compile_engine_const_1 = T.alloc_buffer([], dtype=\"float32\")\n        T_add_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_floor = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_cast_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        compute = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"uint8\")\n        T_cast_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_subtract = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_multiply_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        compile_engine_const_2 = T.alloc_buffer([], dtype=\"float32\")\n        T_add_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_floor_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_cast_5 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        compile_engine_const_3 = T.alloc_buffer([], dtype=\"float32\")\n        T_cast_6 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_multiply_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        compile_engine_const_4 = T.alloc_buffer([], dtype=\"float32\")\n        T_add_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_floor_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"float32\")\n        T_cast_7 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_add_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n        T_cast_8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"uint8\")\n        compute_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"uint8\")\n        with T.block(\"compile_engine_const\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const[()])\n            compile_engine_const[()] = T.float32(0.95489668846130371)\n        for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 128, 7, 7, 16, 1, 1, 32, 4, 4):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                n, oc_chunk, oh, ow, oc_block, kh, kw, ic_outer, ic_f_inner, ic_s_inner = T.axis.remap(\"SSSSSRRRRR\", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9])\n                T.reads(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner])\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                T.block_attr({\"schedule_rule\":\"meta_schedule.conv2d_NCHWc_int8\", \"workload\":[\"conv2d_NCHWc_int8.x86\", [\"TENSOR\", [1, 32, 7, 7, 16], \"uint8\"], [\"TENSOR\", [128, 32, 1, 1, 4, 16, 4], \"int8\"], [1, 1], [0, 0, 0, 0], [1, 1], \"NCHW16c\", \"NCHW16c\", \"int32\"]})\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] + T.cast(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\") * T.cast(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4], p2[ax0, ax1, 0, 0, ax4])\n                T.writes(T_add[ax0, ax1, ax2, ax3, ax4])\n                T_add[ax0, ax1, ax2, ax3, ax4] = conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4] + p2[ax0, ax1, 0, 0, ax4]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_1[ax0, ax1, ax2, ax3, ax4])\n                T_cast_1[ax0, ax1, ax2, ax3, ax4] = T.cast(T_add[ax0, ax1, ax2, ax3, ax4], \"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_multiply\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_1[ax0, ax1, ax2, ax3, ax4], p3[ax0, ax1, 0, 0, ax4])\n                T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4])\n                T_multiply[ax0, ax1, ax2, ax3, ax4] = T_cast_1[ax0, ax1, ax2, ax3, ax4] * p3[ax0, ax1, 0, 0, ax4]\n        with T.block(\"compile_engine_const_1\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_1[()])\n            compile_engine_const_1[()] = T.float32(65.5)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_multiply[ax0, ax1, ax2, ax3, ax4], compile_engine_const_1[()])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3, ax4])\n                T_add_1[ax0, ax1, ax2, ax3, ax4] = T_multiply[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_1[()]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_floor\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_floor[ax0, ax1, ax2, ax3, ax4])\n                T_floor[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_1[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_floor[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_2[ax0, ax1, ax2, ax3, ax4])\n                T_cast_2[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor[ax0, ax1, ax2, ax3, ax4], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute\"):\n                i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_2[i0_1, i1_1, i2_1, i3_1, i4_1])\n                T.writes(compute[i0_1, i1_1, i2_1, i3_1, i4_1])\n                compute[i0_1, i1_1, i2_1, i3_1, i4_1] = T.max(T.min(T_cast_2[i0_1, i1_1, i2_1, i3_1, i4_1], 255), 0)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(compute[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_3[ax0, ax1, ax2, ax3, ax4])\n                T_cast_3[ax0, ax1, ax2, ax3, ax4] = T.cast(compute[ax0, ax1, ax2, ax3, ax4], \"uint8\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_3[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_4[ax0, ax1, ax2, ax3, ax4])\n                T_cast_4[ax0, ax1, ax2, ax3, ax4] = T.cast(T_cast_3[ax0, ax1, ax2, ax3, ax4], \"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_4[ax0, ax1, ax2, ax3, ax4], p4[0])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3, ax4])\n                T_subtract[ax0, ax1, ax2, ax3, ax4] = T_cast_4[ax0, ax1, ax2, ax3, ax4] - p4[0]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_multiply_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(compile_engine_const[()], T_subtract[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4])\n                T_multiply_1[ax0, ax1, ax2, ax3, ax4] = compile_engine_const[()] * T_subtract[ax0, ax1, ax2, ax3, ax4]\n        with T.block(\"compile_engine_const_2\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_2[()])\n            compile_engine_const_2[()] = T.float32(0.5)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_multiply_1[ax0, ax1, ax2, ax3, ax4], compile_engine_const_2[()])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3, ax4])\n                T_add_2[ax0, ax1, ax2, ax3, ax4] = T_multiply_1[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_2[()]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_floor_1\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_floor_1[ax0, ax1, ax2, ax3, ax4])\n                T_floor_1[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_2[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_4\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_floor_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_5[ax0, ax1, ax2, ax3, ax4])\n                T_cast_5[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_1[ax0, ax1, ax2, ax3, ax4], \"int32\")\n        with T.block(\"compile_engine_const_3\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_3[()])\n            compile_engine_const_3[()] = T.float32(0.71245479583740234)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_5\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(p5[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_6[ax0, ax1, ax2, ax3, ax4])\n                T_cast_6[ax0, ax1, ax2, ax3, ax4] = T.cast(p5[ax0, ax1, ax2, ax3, ax4], \"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_multiply_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(compile_engine_const_3[()], T_cast_6[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_multiply_2[ax0, ax1, ax2, ax3, ax4])\n                T_multiply_2[ax0, ax1, ax2, ax3, ax4] = compile_engine_const_3[()] * T_cast_6[ax0, ax1, ax2, ax3, ax4]\n        with T.block(\"compile_engine_const_4\"):\n            vi = T.axis.spatial(1, 0)\n            T.reads()\n            T.writes(compile_engine_const_4[()])\n            compile_engine_const_4[()] = T.float32(0.5)\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_3\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_multiply_2[ax0, ax1, ax2, ax3, ax4], compile_engine_const_4[()])\n                T.writes(T_add_3[ax0, ax1, ax2, ax3, ax4])\n                T_add_3[ax0, ax1, ax2, ax3, ax4] = T_multiply_2[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_4[()]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_floor_2\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_3[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_floor_2[ax0, ax1, ax2, ax3, ax4])\n                T_floor_2[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_3[ax0, ax1, ax2, ax3, ax4], dtype=\"float32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_6\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_floor_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_7[ax0, ax1, ax2, ax3, ax4])\n                T_cast_7[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_2[ax0, ax1, ax2, ax3, ax4], \"int32\")\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_add_4\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_cast_5[ax0, ax1, ax2, ax3, ax4], T_cast_7[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_add_4[ax0, ax1, ax2, ax3, ax4])\n                T_add_4[ax0, ax1, ax2, ax3, ax4] = T_cast_5[ax0, ax1, ax2, ax3, ax4] + T_cast_7[ax0, ax1, ax2, ax3, ax4]\n        for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute_1\"):\n                i0_2, i1_2, i2_2, i3_2, i4_2 = T.axis.remap(\"SSSSS\", [i0, i1, i2, i3, i4])\n                T.reads(T_add_4[i0_2, i1_2, i2_2, i3_2, i4_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2, i4_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2, i4_2] = T.max(T.min(T_add_4[i0_2, i1_2, i2_2, i3_2, i4_2], 255), 0)\n        for i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_7\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0_3, i1_3, i2_3, i3_3, i4_3])\n                T.reads(compute_1[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast_8[ax0, ax1, ax2, ax3, ax4])\n                T_cast_8[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_1[ax0, ax1, ax2, ax3, ax4], \"uint8\")\n        for i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"compute_2\"):\n                i0_5, i1_5, i2_5, i3_5, i4_5 = T.axis.remap(\"SSSSS\", [i0_4, i1_4, i2_4, i3_4, i4_4])\n                T.reads(T_cast_8[i0_5, i1_5, i2_5, i3_5, i4_5])\n                T.writes(compute_2[i0_5, i1_5, i2_5, i3_5, i4_5])\n                compute_2[i0_5, i1_5, i2_5, i3_5, i4_5] = T.max(T.min(T_cast_8[i0_5, i1_5, i2_5, i3_5, i4_5], T.uint8(255)), T.uint8(0))\n        for i0_6, i1_6, i2_6, i3_6, i4_6 in T.grid(1, 128, 7, 7, 16):\n            with T.block(\"T_cast_8\"):\n                ax0, ax1, ax2, ax3, ax4 = T.axis.remap(\"SSSSS\", [i0_6, i1_6, i2_6, i3_6, i4_6])\n                T.reads(compute_2[ax0, ax1, ax2, ax3, ax4])\n                T.writes(T_cast[ax0, ax1, ax2, ax3, ax4])\n                T_cast[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_2[ax0, ax1, ax2, ax3, ax4], \"int32\")\n\n\ndef get_conv2d_vnni_mod(intrin_id):\n    @tvm.script.ir_module\n    class Conv2dInt8_NCHWc_scheduled:\n        @T.prim_func\n        def main(p0: T.Buffer[(1, 32, 7, 7, 16), \"uint8\"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), \"int8\"], p2: T.Buffer[(1, 128, 1, 1, 16), \"int32\"], p3: T.Buffer[(1, 128, 1, 1, 16), \"float32\"], p4: T.Buffer[1, \"float32\"], p5: T.Buffer[(1, 128, 7, 7, 16), \"uint8\"], T_cast: T.Buffer[(1, 128, 7, 7, 16), \"int32\"]) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype=\"int32\")\n            for i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused in T.parallel(128, annotations={\"pragma_auto_unroll_max_step\":64, \"pragma_unroll_explicit\":1}):\n                for i2_1, i3_1, i4_0_1 in T.grid(7, 1, 1):\n                    for i5_0, i6_0 in T.grid(1, 1):\n                        for i1_2_init, i2_2_init, i3_2_init, i1_3_init, i2_3_init, i3_3_init in T.grid(1, 1, 1, 1, 1, 7):\n                            with T.block(\"conv2d_NCHWc_int8_o_init\"):\n                                n = T.axis.spatial(1, 0)\n                                oc_chunk = T.axis.spatial(128, i1_2_init + i1_3_init + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32)\n                                oh = T.axis.spatial(7, i2_1 + i2_2_init + i2_3_init)\n                                ow = T.axis.spatial(7, i3_1 * 7 + i3_2_init * 7 + i3_3_init)\n                                oc_block_o = T.axis.spatial(1, 0)\n                                T.reads()\n                                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16])\n                                for i4_1 in T.vectorized(16):\n                                    with T.block(\"conv2d_NCHWc_int8_init\"):\n                                        oc_block_i_init = T.axis.spatial(16, i4_1)\n                                        T.reads()\n                                        T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init])\n                                        conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init] = 0\n                        for i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 7, 1):\n                            with T.block(\"conv2d_NCHWc_int8_o_update\"):\n                                n = T.axis.spatial(1, 0)\n                                oc_chunk = T.axis.spatial(128, i1_2 + i1_3 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32)\n                                oh = T.axis.spatial(7, i2_1 + i2_2 + i2_3)\n                                ow = T.axis.spatial(7, i3_1 * 7 + i3_2 * 7 + i3_3)\n                                oc_block_o = T.axis.spatial(1, 0)\n                                kh = T.axis.reduce(1, 0)\n                                kw = T.axis.reduce(1, 0)\n                                ic_outer = T.axis.reduce(32, i7_0 * 8 + i7_1)\n                                ic_f_inner = T.axis.reduce(4, i8_1 + i8_0)\n                                ic_s_inner_o = T.axis.reduce(1, 0)\n                                T.reads(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16], p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4])\n                                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16])\n                                A = T.match_buffer(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], [4], dtype=\"uint8\", offset_factor=1)\n                                B = T.match_buffer(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4], [16, 4], dtype=\"int8\", offset_factor=1)\n                                C = T.match_buffer(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16], [16], dtype=\"int32\", offset_factor=1)\n                                A_u8x4: T.uint8x4 = A[0:4]\n                                A_i32: T.int32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n                                B_i8x64: T.int8x64 = B[0, 0:64]\n                                B_i32x16: T.int32x16 = T.reinterpret(B_i8x64, dtype=\"int32x16\")\n                                C_i32x16: T.int32x16 = C[0:16]\n                                C[0:16] = T.call_llvm_pure_intrin(intrin_id, T.uint32(0), C_i32x16, T.broadcast(A_i32, 16), B_i32x16, dtype=\"int32x16\")\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 7):\n                        for ax4_fused in T.vectorized(16):\n                            with T.block(\"T_cast_8\"):\n                                ax0_1 = T.axis.spatial(1, ax0)\n                                ax1_1 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32 + ax1)\n                                ax2_1 = T.axis.spatial(7, i2_1 + ax2)\n                                ax3_1, ax4 = T.axis.remap(\"SS\", [ax3, ax4_fused])\n                                T.reads(conv2d_NCHWc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4], p2[ax0_1, ax1_1, 0, 0, ax4], p3[ax0_1, ax1_1, 0, 0, ax4], p4[0], p5[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                                T.writes(T_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4])\n                                T_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4] = T.cast(T.max(T.min(T.cast(T.max(T.min(T.cast(T.floor(T.float32(0.95489668846130371) * (T.cast(T.cast(T.max(T.min(T.cast(T.floor(T.cast(conv2d_NCHWc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4] + p2[ax0_1, ax1_1, 0, 0, ax4], \"float32\") * p3[ax0_1, ax1_1, 0, 0, ax4] + T.float32(65.5), dtype=\"float32\"), \"int32\"), 255), 0), \"uint8\"), \"float32\") - p4[0]) + T.float32(0.5), dtype=\"float32\"), \"int32\") + T.cast(T.floor(T.float32(0.71245479583740234) * T.cast(p5[ax0_1, ax1_1, ax2_1, ax3_1, ax4], \"float32\") + T.float32(0.5), dtype=\"float32\"), \"int32\"), 255), 0), \"uint8\"), T.uint8(255)), T.uint8(0)), \"int32\")\n\n    return Conv2dInt8_NCHWc_scheduled\n\n\n@tvm.script.ir_module\nclass Conv2dWinogradAddRelu:\n    @T.prim_func\n    def main(p0: T.Buffer[(1, 56, 56, 64), \"float32\"], p1: T.Buffer[(6, 6, 64, 64), \"float32\"], p2: T.Buffer[(1, 1, 1, 64), \"float32\"], T_relu: T.Buffer[(1, 56, 56, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"layout_free_buffers\": [1], \"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        data_pad = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\")\n        input_tile = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        B = T.alloc_buffer([6, 6], dtype=\"float32\")\n        data_pack = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        bgemm = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        A = T.alloc_buffer([6, 4], dtype=\"float32\")\n        inverse = T.alloc_buffer([4, 4, 196, 64], dtype=\"float32\")\n        conv2d_winograd = T.alloc_buffer([1, 56, 56, 64], dtype=\"float32\")\n        T_add = T.alloc_buffer([1, 56, 56, 64], dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(1, 58, 58, 64):\n            with T.block(\"data_pad\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                T.writes(data_pad[i0_1, i1_1, i2_1, i3_1])\n                T.block_attr({\"schedule_rule\":\"None\"})\n                data_pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(6, 6, 196, 64):\n            with T.block(\"input_tile\"):\n                eps, nu, p, ci = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci])\n                T.writes(input_tile[eps, nu, p, ci])\n                T.block_attr({\"schedule_rule\":\"None\"})\n                input_tile[eps, nu, p, ci] = data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci]\n        for i0, i1 in T.grid(6, 6):\n            with T.block(\"B\"):\n                i, j = T.axis.remap(\"SS\", [i0, i1])\n                T.reads()\n                T.writes(B[i, j])\n                T.block_attr({\"const_matrix\":True, \"schedule_rule\":\"meta_schedule.compute_inline\"})\n                B[i, j] = T.Select(i % 6 == 5 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 5 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 6 == 5, T.float32(1.5), T.Select(i % 6 == 4 and j % 6 == 4, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 3, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 2, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 6 == 5, T.float32(-2), T.Select(i % 6 == 3 and j % 6 == 4, T.float32(-0.5), T.Select(i % 6 == 3 and j % 6 == 3, T.float32(2), T.Select(i % 6 == 3 and j % 6 == 2, T.float32(2.5), T.Select(i % 6 == 3 and j % 6 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 6 == 0, T.float32(1.5), T.Select(i % 6 == 2 and j % 6 == 5, T.float32(-1.5), T.Select(i % 6 == 2 and j % 6 == 4, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 3, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 2, T.float32(0.5), T.Select(i % 6 == 2 and j % 6 == 1, T.float32(-2.5), T.Select(i % 6 == 2 and j % 6 == 0, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 4, T.float32(0.5), T.Select(i % 6 == 1 and j % 6 == 3, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 2, T.float32(-1), T.Select(i % 6 == 1 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 0, T.float32(-1.5), T.Select(i % 6 == 0 and j % 6 == 5, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n        for i0, i1, i2, i3, i4, i5 in T.grid(6, 6, 196, 64, 6, 6):\n            with T.block(\"data_pack\"):\n                eps, nu, p, ci, r_a, r_b = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                T.reads(input_tile[r_a, r_b, p, ci], B[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(eps, nu) : T.max(eps, nu) + 1])\n                T.writes(data_pack[eps, nu, p, ci])\n                T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"eps\", \"nu\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_data_pack.cuda\"})\n                with T.init():\n                    data_pack[eps, nu, p, ci] = T.float32(0)\n                data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu]\n        for i0, i1, i2, i3, i4 in T.grid(6, 6, 196, 64, 64):\n            with T.block(\"bgemm\"):\n                eps, nu, p, co, ci = T.axis.remap(\"SSSSR\", [i0, i1, i2, i3, i4])\n                T.reads(data_pack[eps, nu, p, ci], p1[eps, nu, co, ci])\n                T.writes(bgemm[eps, nu, p, co])\n                T.block_attr({\"layout_free_placeholders\":[]})\n                with T.init():\n                    bgemm[eps, nu, p, co] = T.float32(0)\n                bgemm[eps, nu, p, co] = bgemm[eps, nu, p, co] + data_pack[eps, nu, p, ci] * p1[eps, nu, co, ci]\n        for i0, i1 in T.grid(6, 4):\n            with T.block(\"A\"):\n                i, j = T.axis.remap(\"SS\", [i0, i1])\n                T.reads()\n                T.writes(A[i, j])\n                T.block_attr({\"const_matrix\":True, \"schedule_rule\":\"meta_schedule.compute_inline\"})\n                A[i, j] = T.Select(i % 6 == 5 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 5 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 4 == 3, T.float32(-8), T.Select(i % 6 == 4 and j % 4 == 2, T.float32(4), T.Select(i % 6 == 4 and j % 4 == 1, T.float32(-2), T.Select(i % 6 == 4 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 4 == 3, T.float32(0.125), T.Select(i % 6 == 3 and j % 4 == 2, T.float32(0.25), T.Select(i % 6 == 3 and j % 4 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 1, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 3, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 1, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 0 and j % 4 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n        for i0, i1, i2, i3, i4, i5 in T.grid(4, 4, 196, 64, 6, 6):\n            with T.block(\"inverse\"):\n                vh, vw, p, co, r_a, r_b = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                T.reads(bgemm[r_a, r_b, p, co], A[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(vh, vw) : T.max(vh, vw) + 1])\n                T.writes(inverse[vh, vw, p, co])\n                T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"vh\", \"vw\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_inverse.cuda\"})\n                with T.init():\n                    inverse[vh, vw, p, co] = T.float32(0)\n                inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"conv2d_winograd\"):\n                n, h, w, co = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co])\n                T.writes(conv2d_winograd[n, h, w, co])\n                conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_winograd[ax0, ax1, ax2, ax3], p2[ax0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = conv2d_winograd[ax0, ax1, ax2, ax3] + p2[ax0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"T_relu\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[ax0, ax1, ax2, ax3])\n                T.writes(T_relu[ax0, ax1, ax2, ax3])\n                T_relu[ax0, ax1, ax2, ax3] = T.max(T_add[ax0, ax1, ax2, ax3], T.float32(0))\n\n\n@tvm.script.ir_module\nclass Conv2dWinogradAddResidualRelu:\n    @T.prim_func\n    def main(p0: T.Buffer[(1, 56, 56, 64), \"float32\"], p1: T.Buffer[(6, 6, 64, 64), \"float32\"], p2: T.Buffer[(1, 1, 1, 64), \"float32\"], p3: T.Buffer[(1, 56, 56, 64), \"float32\"], T_relu: T.Buffer[(1, 56, 56, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        data_pad = T.alloc_buffer([1, 58, 58, 64], dtype=\"float32\")\n        input_tile = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        B = T.alloc_buffer([6, 6], dtype=\"float32\")\n        data_pack = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        bgemm = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        A = T.alloc_buffer([6, 4], dtype=\"float32\")\n        inverse = T.alloc_buffer([4, 4, 196, 64], dtype=\"float32\")\n        conv2d_winograd = T.alloc_buffer([1, 56, 56, 64], dtype=\"float32\")\n        T_add = T.alloc_buffer([1, 56, 56, 64], dtype=\"float32\")\n        T_add_1 = T.alloc_buffer([1, 56, 56, 64], dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(1, 58, 58, 64):\n            with T.block(\"data_pad\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1])\n                T.writes(data_pad[i0_1, i1_1, i2_1, i3_1])\n                T.block_attr({\"schedule_rule\":\"None\"})\n                data_pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype=\"float32\")\n        for i0, i1, i2, i3 in T.grid(6, 6, 196, 64):\n            with T.block(\"input_tile\"):\n                eps, nu, p, ci = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci])\n                T.writes(input_tile[eps, nu, p, ci])\n                T.block_attr({\"schedule_rule\":\"None\"})\n                input_tile[eps, nu, p, ci] = data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci]\n        for i0, i1 in T.grid(6, 6):\n            with T.block(\"B\"):\n                i, j = T.axis.remap(\"SS\", [i0, i1])\n                T.reads()\n                T.writes(B[i, j])\n                T.block_attr({\"const_matrix\":True, \"schedule_rule\":\"meta_schedule.compute_inline\"})\n                B[i, j] = T.Select(i % 6 == 5 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 5 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 6 == 5, T.float32(1.5), T.Select(i % 6 == 4 and j % 6 == 4, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 3, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 2, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 6 == 5, T.float32(-2), T.Select(i % 6 == 3 and j % 6 == 4, T.float32(-0.5), T.Select(i % 6 == 3 and j % 6 == 3, T.float32(2), T.Select(i % 6 == 3 and j % 6 == 2, T.float32(2.5), T.Select(i % 6 == 3 and j % 6 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 6 == 0, T.float32(1.5), T.Select(i % 6 == 2 and j % 6 == 5, T.float32(-1.5), T.Select(i % 6 == 2 and j % 6 == 4, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 3, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 2, T.float32(0.5), T.Select(i % 6 == 2 and j % 6 == 1, T.float32(-2.5), T.Select(i % 6 == 2 and j % 6 == 0, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 4, T.float32(0.5), T.Select(i % 6 == 1 and j % 6 == 3, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 2, T.float32(-1), T.Select(i % 6 == 1 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 0, T.float32(-1.5), T.Select(i % 6 == 0 and j % 6 == 5, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n        for i0, i1, i2, i3, i4, i5 in T.grid(6, 6, 196, 64, 6, 6):\n            with T.block(\"data_pack\"):\n                eps, nu, p, ci, r_a, r_b = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                T.reads(input_tile[r_a, r_b, p, ci], B[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(eps, nu) : T.max(eps, nu) + 1])\n                T.writes(data_pack[eps, nu, p, ci])\n                T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"eps\", \"nu\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_data_pack.cuda\"})\n                with T.init():\n                    data_pack[eps, nu, p, ci] = T.float32(0)\n                data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu]\n        for i0, i1, i2, i3, i4 in T.grid(6, 6, 196, 64, 64):\n            with T.block(\"bgemm\"):\n                eps, nu, p, co, ci = T.axis.remap(\"SSSSR\", [i0, i1, i2, i3, i4])\n                T.reads(data_pack[eps, nu, p, ci], p1[eps, nu, co, ci])\n                T.writes(bgemm[eps, nu, p, co])\n                T.block_attr({\"layout_free_placeholders\":[]})\n                with T.init():\n                    bgemm[eps, nu, p, co] = T.float32(0)\n                bgemm[eps, nu, p, co] = bgemm[eps, nu, p, co] + data_pack[eps, nu, p, ci] * p1[eps, nu, co, ci]\n        for i0, i1 in T.grid(6, 4):\n            with T.block(\"A\"):\n                i, j = T.axis.remap(\"SS\", [i0, i1])\n                T.reads()\n                T.writes(A[i, j])\n                T.block_attr({\"const_matrix\":True, \"schedule_rule\":\"meta_schedule.compute_inline\"})\n                A[i, j] = T.Select(i % 6 == 5 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 5 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 4 == 3, T.float32(-8), T.Select(i % 6 == 4 and j % 4 == 2, T.float32(4), T.Select(i % 6 == 4 and j % 4 == 1, T.float32(-2), T.Select(i % 6 == 4 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 4 == 3, T.float32(0.125), T.Select(i % 6 == 3 and j % 4 == 2, T.float32(0.25), T.Select(i % 6 == 3 and j % 4 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 1, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 3, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 1, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 0 and j % 4 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n        for i0, i1, i2, i3, i4, i5 in T.grid(4, 4, 196, 64, 6, 6):\n            with T.block(\"inverse\"):\n                vh, vw, p, co, r_a, r_b = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                T.reads(bgemm[r_a, r_b, p, co], A[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(vh, vw) : T.max(vh, vw) + 1])\n                T.writes(inverse[vh, vw, p, co])\n                T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"vh\", \"vw\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_inverse.cuda\"})\n                with T.init():\n                    inverse[vh, vw, p, co] = T.float32(0)\n                inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"conv2d_winograd\"):\n                n, h, w, co = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co])\n                T.writes(conv2d_winograd[n, h, w, co])\n                conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_winograd[ax0, ax1, ax2, ax3], p2[ax0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = conv2d_winograd[ax0, ax1, ax2, ax3] + p2[ax0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[ax0, ax1, ax2, ax3], p3[ax0, ax1, ax2, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = T_add[ax0, ax1, ax2, ax3] + p3[ax0, ax1, ax2, ax3]\n        for i0, i1, i2, i3 in T.grid(1, 56, 56, 64):\n            with T.block(\"T_relu\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add_1[ax0, ax1, ax2, ax3])\n                T.writes(T_relu[ax0, ax1, ax2, ax3])\n                T_relu[ax0, ax1, ax2, ax3] = T.max(T_add_1[ax0, ax1, ax2, ax3], T.float32(0))\n\n\n@tvm.script.ir_module\nclass Conv2dWinogradAddResidualRelu_scheduled:\n    @T.prim_func\n    def main(p0: T.Buffer[(1, 56, 56, 64), \"float32\"], p1: T.Buffer[(6, 6, 64, 64), \"float32\"], p2: T.Buffer[(1, 1, 1, 64), \"float32\"], p3: T.Buffer[(1, 56, 56, 64), \"float32\"], T_relu: T.Buffer[(1, 56, 56, 64), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n        # body\n        # with T.block(\"root\")\n        input_tile_local = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\", scope=\"local\")\n        data_pack = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        bgemm = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\")\n        inverse = T.alloc_buffer([4, 4, 196, 64], dtype=\"float32\")\n        bgemm_local = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\", scope=\"local\")\n        data_pack_shared = T.alloc_buffer([6, 6, 196, 64], dtype=\"float32\", scope=\"shared\")\n        p1_shared = T.alloc_buffer([6, 6, 64, 64], dtype=\"float32\", scope=\"shared\")\n        for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(98, thread=\"blockIdx.x\", annotations={\"pragma_auto_unroll_max_step\":1024, \"pragma_unroll_explicit\":1}):\n            for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1):\n                    with T.block(\"input_tile\"):\n                        eps, nu = T.axis.remap(\"SS\", [ax0, ax1])\n                        p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8 + ax2)\n                        ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3)\n                        T.reads(p0[p // 196, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1, ci])\n                        T.writes(input_tile_local[eps, nu, p, ci])\n                        T.block_attr({\"schedule_rule\":\"None\"})\n                        input_tile_local[eps, nu, p, ci] = T.if_then_else(1 <= p % 196 // 14 * 4 + eps and p % 196 // 14 * 4 + eps < 57 and 1 <= p % 14 * 4 + nu and p % 14 * 4 + nu < 57, p0[p // 196, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1, ci], T.float32(0), dtype=\"float32\")\n                for i0 in T.unroll(6):\n                    for i1 in T.unroll(6):\n                        with T.block(\"data_pack_init\"):\n                            eps, nu = T.axis.remap(\"SS\", [i0, i1])\n                            p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8)\n                            ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8)\n                            T.reads()\n                            T.writes(data_pack[eps, nu, p, ci])\n                            T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"eps\", \"nu\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_data_pack.cuda\"})\n                            data_pack[eps, nu, p, ci] = T.float32(0)\n                        for i4 in T.unroll(6):\n                            for i5 in T.unroll(6):\n                                with T.block(\"data_pack_update\"):\n                                    eps, nu = T.axis.remap(\"SS\", [i0, i1])\n                                    p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8)\n                                    ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8)\n                                    r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                    T.reads(data_pack[eps, nu, p, ci], input_tile_local[r_a, r_b, p, ci])\n                                    T.writes(data_pack[eps, nu, p, ci])\n                                    T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"eps\", \"nu\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_data_pack.cuda\"})\n                                    data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile_local[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))))))))))))))\n        for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(168, thread=\"blockIdx.x\", annotations={\"pragma_auto_unroll_max_step\":1024, \"pragma_unroll_explicit\":1}):\n            for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread=\"vthread.x\"):\n                for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(48, thread=\"threadIdx.x\"):\n                    for i0_3_init, i1_3_init, i2_3_init, i3_3_init, i0_4_init, i1_4_init, i2_4_init, i3_4_init in T.grid(1, 1, 14, 1, 1, 1, 1, 1):\n                        with T.block(\"bgemm_init\"):\n                            eps = T.axis.spatial(6, i0_4_init + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + i0_3_init)\n                            nu = T.axis.spatial(6, i1_4_init + i0_0_i1_0_i2_0_i3_0_fused // 28 + i1_3_init)\n                            p = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + i2_3_init + i2_4_init)\n                            co = T.axis.spatial(64, i3_4_init + i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i3_3_init)\n                            T.reads()\n                            T.writes(bgemm_local[eps, nu, p, co])\n                            T.block_attr({\"layout_free_placeholders\":[], \"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                            bgemm_local[eps, nu, p, co] = T.float32(0)\n                    for i4_0 in T.serial(2):\n                        for ax0_ax1_ax2_ax3_fused_0 in T.serial(28):\n                            for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(48, thread=\"threadIdx.x\"):\n                                for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(4):\n                                    with T.block(\"data_pack_shared\"):\n                                        v0 = T.axis.spatial(6, (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) // 896)\n                                        v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28)\n                                        v2 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 896 // 32)\n                                        v3 = T.axis.spatial(64, i4_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 32)\n                                        T.reads(data_pack[v0, v1, v2, v3])\n                                        T.writes(data_pack_shared[v0, v1, v2, v3])\n                                        data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3]\n                        for ax0_ax1_ax2_ax3_fused_0 in T.serial(16):\n                            for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(48, thread=\"threadIdx.x\"):\n                                for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(4):\n                                    with T.block(\"p1_shared\"):\n                                        v0 = T.axis.spatial(6, (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) // 512)\n                                        v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28)\n                                        v2 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 512 // 32)\n                                        v3 = T.axis.spatial(64, i4_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 32)\n                                        T.reads(p1[v0, v1, v2, v3])\n                                        T.writes(p1_shared[v0, v1, v2, v3])\n                                        p1_shared[v0, v1, v2, v3] = p1[v0, v1, v2, v3]\n                        for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(2, 1, 1, 14, 1, 16, 1, 1, 1, 1):\n                            with T.block(\"bgemm_update\"):\n                                eps = T.axis.spatial(6, i0_4 + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + i0_3)\n                                nu = T.axis.spatial(6, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 28 + i1_3)\n                                p = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + i2_3 + i2_4)\n                                co = T.axis.spatial(64, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i3_3)\n                                ci = T.axis.reduce(64, i4_0 * 32 + i4_1 * 16 + i4_2)\n                                T.reads(bgemm_local[eps, nu, p, co], data_pack_shared[eps, nu, p, ci], p1_shared[eps, nu, co, ci])\n                                T.writes(bgemm_local[eps, nu, p, co])\n                                T.block_attr({\"layout_free_placeholders\":[], \"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                bgemm_local[eps, nu, p, co] = bgemm_local[eps, nu, p, co] + data_pack_shared[eps, nu, p, ci] * p1_shared[eps, nu, co, ci]\n                    for ax0, ax1, ax2, ax3 in T.grid(1, 1, 14, 1):\n                        with T.block(\"bgemm_local\"):\n                            v0 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + ax0)\n                            v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28 + ax1)\n                            v2 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + ax2)\n                            v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + ax3)\n                            T.reads(bgemm_local[v0, v1, v2, v3])\n                            T.writes(bgemm[v0, v1, v2, v3])\n                            bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3]\n        for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(25, thread=\"blockIdx.x\", annotations={\"pragma_auto_unroll_max_step\":1024, \"pragma_unroll_explicit\":1}):\n            for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                for i0 in T.unroll(4):\n                    for i1 in T.unroll(4):\n                        with T.block(\"inverse_init\"):\n                            T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1 < 12544)\n                            vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                            p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) // 448 * 7 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 224 // 32)\n                            co = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 448 // 224 * 32 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 32)\n                            T.reads()\n                            T.writes(inverse[vh, vw, p, co])\n                            T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"vh\", \"vw\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_inverse.cuda\"})\n                            inverse[vh, vw, p, co] = T.float32(0)\n                        for i4 in T.unroll(6):\n                            for i5 in T.unroll(6):\n                                with T.block(\"inverse_update\"):\n                                    T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1 < 12544)\n                                    vh, vw = T.axis.remap(\"SS\", [i0, i1])\n                                    p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) // 448 * 7 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 224 // 32)\n                                    co = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 448 // 224 * 32 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 32)\n                                    r_a, r_b = T.axis.remap(\"RR\", [i4, i5])\n                                    T.reads(inverse[vh, vw, p, co], bgemm[r_a, r_b, p, co])\n                                    T.writes(inverse[vh, vw, p, co])\n                                    T.block_attr({\"auto_scheduler_simplify_const_tensor_indices\":[\"vh\", \"vw\", \"r_a\", \"r_b\"], \"schedule_rule\":\"meta_schedule.winograd_inverse.cuda\"})\n                                    inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0)))))))))))))))))))))))))\n        for i0_i1_i2_i3_fused_0 in T.thread_binding(1568, thread=\"blockIdx.x\", annotations={\"pragma_auto_unroll_max_step\":1024, \"pragma_unroll_explicit\":1}):\n            for i0_i1_i2_i3_fused_1 in T.thread_binding(128, thread=\"threadIdx.x\"):\n                with T.block(\"conv2d_winograd\"):\n                    n = T.axis.spatial(1, 0)\n                    h = T.axis.spatial(56, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) // 3584)\n                    w = T.axis.spatial(56, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 3584 // 64)\n                    co = T.axis.spatial(64, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 64)\n                    T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co], p2[n, 0, 0, co], p3[n, h, w, co])\n                    T.writes(T_relu[n, h, w, co])\n                    T_relu[n, h, w, co] = T.max(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co] + p2[n, 0, 0, co] + p3[n, h, w, co], T.float32(0))\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_with_predicate:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[256, \"int32\"], p5: T.Buffer[256, \"int32\"], p6: T.Buffer[256, \"int32\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"tir.noalias\": True, \"global_symbol\": \"main\"})\n        # body\n        # with T.block(\"root\")\n        pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype=\"int8\")\n        conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 64):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1, i2_1, i3_1])\n                T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1]\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64):\n            with T.block(\"conv2d_nhwc\"):\n                nn, yy, xx, ff, ry, rx, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc])\n                T.writes(conv2d_nhwc[nn, yy, xx, ff])\n                with T.init():\n                    conv2d_nhwc[nn, yy, xx, ff] = 0\n                conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], \"int32\") * T.cast(p1[ff, ry, rx, rc], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3])\n                T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype=\"int32\")\n        for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_3, i1_3, i2_3, i3_3])\n                T.reads(p7[()], compute_1[ax0, ax1, ax2, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = p7[()] + compute_1[ax0, ax1, ax2, ax3]\n        for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_1\"):\n                i0_5, i1_5, i2_5, i3_5 = T.axis.remap(\"SSSS\", [i0_4, i1_4, i2_4, i3_4])\n                T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5])\n                T.writes(compute_2[i0_5, i1_5, i2_5, i3_5])\n                compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0)\n        for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_6, i1_6, i2_6, i3_6])\n                T.reads(compute_2[ax0, ax1, ax2, ax3], p8[0])\n                T.writes(T_subtract_1[ax0, ax1, ax2, ax3])\n                T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p8[0]\n        for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_2\"):\n                i0_8, i1_8, i2_8, i3_8 = T.axis.remap(\"SSSS\", [i0_7, i1_7, i2_7, i3_7])\n                T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8])\n                T.writes(compute[i0_8, i1_8, i2_8, i3_8])\n                compute[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1963325822, 31, 1, dtype=\"int32\")\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_with_predicate_target:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[256, \"int32\"], p5: T.Buffer[256, \"int32\"], p6: T.Buffer[256, \"int32\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], p9: T.Buffer[(16, 56, 56, 256), \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype=\"int8\")\n        conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        compute_4 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 64):\n            with T.block(\"pad_temp\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(p0[i0_1, i1_1, i2_1, i3_1])\n                T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1])\n                pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1]\n        for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64):\n            with T.block(\"conv2d_nhwc\"):\n                nn, yy, xx, ff, ry, rx, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n                T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc])\n                T.writes(conv2d_nhwc[nn, yy, xx, ff])\n                with T.init():\n                    conv2d_nhwc[nn, yy, xx, ff] = 0\n                conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], \"int32\") * T.cast(p1[ff, ry, rx, rc], \"int32\")\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3])\n                T.writes(T_subtract[ax0, ax1, ax2, ax3])\n                T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3])\n                T.writes(T_add[ax0, ax1, ax2, ax3])\n                T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3]\n        for i0, i1, i2, i3 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute\"):\n                i0_2, i1_2, i2_2, i3_2 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2])\n                T.writes(compute_1[i0_2, i1_2, i2_2, i3_2])\n                compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype=\"int32\")\n        for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_3, i1_3, i2_3, i3_3])\n                T.reads(p7[()], compute_1[ax0, ax1, ax2, ax3])\n                T.writes(T_add_1[ax0, ax1, ax2, ax3])\n                T_add_1[ax0, ax1, ax2, ax3] = p7[()] + compute_1[ax0, ax1, ax2, ax3]\n        for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_1\"):\n                i0_5, i1_5, i2_5, i3_5 = T.axis.remap(\"SSSS\", [i0_4, i1_4, i2_4, i3_4])\n                T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5])\n                T.writes(compute_2[i0_5, i1_5, i2_5, i3_5])\n                compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0)\n        for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_subtract_1\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_6, i1_6, i2_6, i3_6])\n                T.reads(compute_2[ax0, ax1, ax2, ax3], p8[0])\n                T.writes(T_subtract_1[ax0, ax1, ax2, ax3])\n                T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p8[0]\n        for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_2\"):\n                i0_8, i1_8, i2_8, i3_8 = T.axis.remap(\"SSSS\", [i0_7, i1_7, i2_7, i3_7])\n                T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8])\n                T.writes(compute_3[i0_8, i1_8, i2_8, i3_8])\n                compute_3[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1457846997, 31, 0, dtype=\"int32\")\n        for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_3\"):\n                i0_10, i1_10, i2_10, i3_10 = T.axis.remap(\"SSSS\", [i0_9, i1_9, i2_9, i3_9])\n                T.reads(p9[i0_10, i1_10, i2_10, i3_10])\n                T.writes(compute_4[i0_10, i1_10, i2_10, i3_10])\n                compute_4[i0_10, i1_10, i2_10, i3_10] = T.q_multiply_shift(p9[i0_10, i1_10, i2_10, i3_10], 2101000910, 31, 0, dtype=\"int32\")\n        for i0_11, i1_11, i2_11, i3_11 in T.grid(16, 56, 56, 256):\n            with T.block(\"T_add_2\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0_11, i1_11, i2_11, i3_11])\n                T.reads(compute_3[ax0, ax1, ax2, ax3], compute_4[ax0, ax1, ax2, ax3])\n                T.writes(T_add_2[ax0, ax1, ax2, ax3])\n                T_add_2[ax0, ax1, ax2, ax3] = compute_3[ax0, ax1, ax2, ax3] + compute_4[ax0, ax1, ax2, ax3]\n        for i0_12, i1_12, i2_12, i3_12 in T.grid(16, 56, 56, 256):\n            with T.block(\"compute_4\"):\n                i0_13, i1_13, i2_13, i3_13 = T.axis.remap(\"SSSS\", [i0_12, i1_12, i2_12, i3_12])\n                T.reads(T_add_2[i0_13, i1_13, i2_13, i3_13])\n                T.writes(compute[i0_13, i1_13, i2_13, i3_13])\n                compute[i0_13, i1_13, i2_13, i3_13] = T.max(T.min(T_add_2[i0_13, i1_13, i2_13, i3_13], 255), 0)\n\n\n@tvm.script.ir_module\nclass Conv2dInt8_with_predicate_scheduled:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[256, \"int32\"], p5: T.Buffer[256, \"int32\"], p6: T.Buffer[256, \"int32\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], p9: T.Buffer[(16, 56, 56, 256), \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"int32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":1024})\n            conv2d_nhwc_reindex_shared = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"shared\")\n            conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"wmma.accumulator\")\n            pad_temp_reindex_shared = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"shared\")\n            p1_reindex_shared = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"shared\")\n            pad_temp_reindex_shared_wmma_matrix_a = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"wmma.matrix_a\")\n            p1_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"wmma.matrix_b\")\n            for ax2_0_0_ax3_0_0_fused in T.thread_binding(32, thread=\"blockIdx.y\"):\n                for ax2_0_1_ax3_0_1_fused in T.thread_binding(196, thread=\"blockIdx.x\"):\n                    for ax2_0_2_ax3_0_2_fused in T.thread_binding(4, thread=\"threadIdx.y\"):\n                        for ax0_0, ax1_0, ax4_0_0 in T.grid(1, 1, 2):\n                            for ax0_ax1_fused in T.serial(1024):\n                                with T.block(\"pad_temp_reindex_shared\"):\n                                    v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0_ax1_fused // 32)\n                                    v1 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_fused % 32)\n                                    T.reads(p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                                    T.writes(pad_temp_reindex_shared[v0, v1])\n                                    T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 16]], \"meta_schedule.cooperative_fetch\":4})\n                                    pad_temp_reindex_shared[v0, v1] = p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]\n                            for ax0_ax1_ax2_ax3_fused in T.serial(2048):\n                                with T.block(\"p1_reindex_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(1, 0)\n                                    v2 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + ax0_ax1_ax2_ax3_fused // 32)\n                                    v3 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(p1[v2, v0, v1, v3])\n                                    T.writes(p1_reindex_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"buffer_dim_align\":[[0, 2, 32, 16]], \"meta_schedule.cooperative_fetch\":3})\n                                    p1_reindex_shared[v0, v1, v2, v3] = p1[v2, v0, v1, v3]\n                            for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 2):\n                                for ax0_0_1, ax1_0_1 in T.grid(1, 1):\n                                    with T.block(\"pad_temp_reindex_shared_wmma.matrix_a_o\"):\n                                        v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2)\n                                        v1_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1)\n                                        T.reads(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_s8_a\"})\n                                        for ax0_1_1, ax1_1_1 in T.grid(16, 16):\n                                            with T.block(\"pad_temp_reindex_shared_wmma.matrix_a\"):\n                                                v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1_1, ax1_1_1])\n                                                T.reads(pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                                T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                                pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                                for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 2, 1):\n                                    with T.block(\"p1_reindex_shared_wmma.matrix_b_o\"):\n                                        v0 = T.axis.spatial(1, 0)\n                                        v1 = T.axis.spatial(1, 0)\n                                        v2_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax2_0)\n                                        v3_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1)\n                                        T.reads(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_s8_b_trans\"})\n                                        for ax2_1, ax3_1 in T.grid(16, 16):\n                                            with T.block(\"p1_reindex_shared_wmma.matrix_b\"):\n                                                v2_i, v3_i = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                                T.reads(p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] = p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]\n                                for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 1, 1, 2):\n                                    with T.block(\"conv2d_nhwc_o\"):\n                                        v0 = T.axis.reduce(1, 0)\n                                        v1 = T.axis.reduce(1, 0)\n                                        v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3 + ax2_0_4)\n                                        v3_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax3_0_3 * 2 + ax3_0_4)\n                                        v4_o = T.axis.reduce(4, ax4_0_0 * 2 + ax4_0_1 + ax4_0_2)\n                                        T.reads(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16])\n                                        T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_s8s8s32_trans\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_s32\", \"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"warp_execution\":1})\n                                        with T.init():\n                                            for ax2_1, ax3_1 in T.grid(16, 16):\n                                                with T.block(\"conv2d_nhwc_init\"):\n                                                    v2_i_init, v3_i_init = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                                    T.reads()\n                                                    T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init])\n                                                    conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init] = 0\n                                        for ax2_1, ax3_1, ax4_1 in T.grid(16, 16, 16):\n                                            with T.block(\"conv2d_nhwc\"):\n                                                v2_i, v3_i, v4_i = T.axis.remap(\"SSR\", [ax2_1, ax3_1, ax4_1])\n                                                T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i], pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i])\n                                                T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                                conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] + T.cast(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], \"int32\") * T.cast(p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i], \"int32\")\n                        for ax0_0, ax1_0 in T.grid(1, 2):\n                            with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\"):\n                                v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2)\n                                v1_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax1_0)\n                                T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_s32_shared\"})\n                                for ax0_1, ax1_1 in T.grid(16, 16):\n                                    with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator\"):\n                                        v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                        T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                        T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                        conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                    for ax0, ax1_0, ax1_1, ax1_2, ax1_3 in T.grid(32, 1, 4, 32, 2):\n                        with T.block(\"conv2d_nhwc_reindex_shared\"):\n                            T.where(((ax1_0 * 4 + ax1_1) * 32 + ax1_2) * 2 + ax1_3 < 64)\n                            v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + (ax1_0 * 256 + ax1_1 * 64 + ax1_2 * 2 + ax1_3))\n                            T.reads(p7[()], conv2d_nhwc_reindex_shared[v0, v1], p2[0, 0, 0, v1], p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], p8[0], p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                            T.writes(compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                            compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] = T.max(T.min(T.q_multiply_shift(T.max(T.min(p7[()] + T.q_multiply_shift_per_axis(conv2d_nhwc_reindex_shared[v0, v1] - p2[0, 0, 0, v1] + p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], 31, False, True, dtype=\"int32\"), 255), 0) - p8[0], 1457846997, 31, 0, dtype=\"int32\") + T.q_multiply_shift(p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1], 2101000910, 31, 0, dtype=\"int32\"), 255), 0)\n\n\n# fmt: on\ndef verify(anchor_mod, anchor_trace_fun, target_mod, target, ref):\n    anchor_sch = Schedule(anchor_mod)\n    anchor_trace_fun(anchor_sch)\n    anchor_trace = anchor_sch.trace\n\n    sch = Schedule(target_mod)\n\n    ms.trace_apply.schedule_using_anchor_trace(sch, anchor_trace, Target(target))\n\n    tvm.ir.assert_structural_equal(ref, sch.mod)\n\n\ndef test_dense_add_cpu():\n    def apply_anchor_trace(sch: Schedule) -> None:\n        b0 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        b1 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.annotate(block_or_loop=b0, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSRSRS\")\n        l2, l3, l4 = sch.get_loops(block=b0)\n        v5, v6, v7, v8 = sch.sample_perfect_tile(\n            loop=l2, n=4, max_innermost_factor=64, decision=[2, 8, 4, 2]\n        )\n        l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8], preserve_unit_iters=True)\n        v13, v14, v15, v16 = sch.sample_perfect_tile(\n            loop=l3, n=4, max_innermost_factor=64, decision=[2, 1, 1, 64]\n        )\n        l17, l18, l19, l20 = sch.split(\n            loop=l3, factors=[v13, v14, v15, v16], preserve_unit_iters=True\n        )\n        v21, v22 = sch.sample_perfect_tile(loop=l4, n=2, max_innermost_factor=64, decision=[128, 1])\n        l23, l24 = sch.split(loop=l4, factors=[v21, v22], preserve_unit_iters=True)\n        sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20)\n        b25 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"global\")\n        sch.reverse_compute_at(block=b25, loop=l17, preserve_unit_loops=True, index=-1)\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.parallel\", ann_val=160)\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.vectorize\", ann_val=64)\n        v26 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=0\n        )\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v26)\n        sch.enter_postproc()\n        b27 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b27, ann_key=\"meta_schedule.parallel\")\n        sch.unannotate(block_or_loop=b27, ann_key=\"meta_schedule.vectorize\")\n        sch.unannotate(block_or_loop=b27, ann_key=\"meta_schedule.unroll_explicit\")\n        b28, b29 = sch.get_child_blocks(b27)\n        l30, l31, l32, l33, l34, l35, l36, l37, l38, l39 = sch.get_loops(block=b28)\n        l40 = sch.fuse(l30, l31, preserve_unit_iters=True)\n        sch.parallel(loop=l40)\n        l41 = sch.fuse(l39, preserve_unit_iters=True)\n        sch.vectorize(loop=l41)\n        l42, l43, l44 = sch.get_loops(block=b29)\n        l45 = sch.fuse(l42, preserve_unit_iters=True)\n        sch.parallel(loop=l45)\n        l46 = sch.fuse(l44, preserve_unit_iters=True)\n        sch.vectorize(loop=l46)\n        b47 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        l48, l49, l50, l51, l52, l53, l54, l55, l56 = sch.get_loops(block=b47)\n        b57 = sch.decompose_reduction(block=b47, loop=l51)\n        b58 = sch.get_block(name=\"T_matmul_NT_update\", func_name=\"main\")\n        b59 = sch.cache_read(block=b58, read_buffer_index=2, storage_scope=\"global\")\n        sch.transform_layout(\n            block=b58,\n            buffer=(\"read\", 2),\n            index_map=tvm.tir.IndexMap.from_func(\n                lambda i0, i1: (\n                    floordiv(i0, 64),\n                    i1,\n                    floormod(i0, 64),\n                ),\n                inverse_index_map=lambda i0, i1, i2: (\n                    ((i0 * 64) + i2),\n                    i1,\n                ),\n            ),\n            pad_value=None,\n        )\n        sch.annotate(block_or_loop=b59, ann_key=\"meta_schedule.layout_rewrite_preproc\", ann_val=1)\n\n    verify(Dense, apply_anchor_trace, DenseAdd, \"llvm\", DenseAdd_scheduled_cpu)\n\n\ndef test_dense_add_cpu_no_write_cache():\n    def apply_trace(sch):\n        b0 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        b1 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.annotate(block_or_loop=b0, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSRSRS\")\n        l2, l3, l4 = sch.get_loops(block=b0)\n        v5, v6, v7, v8 = sch.sample_perfect_tile(\n            loop=l2, n=4, max_innermost_factor=64, decision=[4, 4, 4, 2]\n        )\n        l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8], preserve_unit_iters=True)\n        v13, v14, v15, v16 = sch.sample_perfect_tile(\n            loop=l3, n=4, max_innermost_factor=64, decision=[1, 1, 4, 32]\n        )\n        l17, l18, l19, l20 = sch.split(\n            loop=l3, factors=[v13, v14, v15, v16], preserve_unit_iters=True\n        )\n        v21, v22 = sch.sample_perfect_tile(loop=l4, n=2, max_innermost_factor=64, decision=[8, 16])\n        l23, l24 = sch.split(loop=l4, factors=[v21, v22], preserve_unit_iters=True)\n        sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20)\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.parallel\", ann_val=160)\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.vectorize\", ann_val=64)\n        v25 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=1\n        )\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v25)\n        sch.enter_postproc()\n        b26 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b26, ann_key=\"meta_schedule.parallel\")\n        sch.unannotate(block_or_loop=b26, ann_key=\"meta_schedule.vectorize\")\n        sch.unannotate(block_or_loop=b26, ann_key=\"meta_schedule.unroll_explicit\")\n        (b27,) = sch.get_child_blocks(b26)\n        l28, l29, l30, l31, l32, l33, l34, l35, l36, l37 = sch.get_loops(block=b27)\n        l38 = sch.fuse(l28, l29, l30, l31, preserve_unit_iters=True)\n        sch.parallel(loop=l38)\n        l39 = sch.fuse(l37, preserve_unit_iters=True)\n        sch.vectorize(loop=l39)\n        sch.annotate(block_or_loop=l38, ann_key=\"pragma_auto_unroll_max_step\", ann_val=16)\n        sch.annotate(block_or_loop=l38, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        b40 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        l41, l42, l43, l44, l45, l46, l47 = sch.get_loops(block=b40)\n        b48 = sch.decompose_reduction(block=b40, loop=l42)\n        b49 = sch.get_block(name=\"T_matmul_NT_update\", func_name=\"main\")\n        b50 = sch.cache_read(block=b49, read_buffer_index=2, storage_scope=\"global\")\n        sch.transform_layout(\n            block=b49,\n            buffer=(\"read\", 2),\n            index_map=tvm.tir.IndexMap.from_func(\n                lambda i0, i1: (\n                    floordiv(i1, 16),\n                    floordiv(i0, 32),\n                    floormod(i1, 16),\n                    floormod(i0, 32),\n                ),\n                inverse_index_map=lambda i0, i1, i2, i3: (\n                    ((i1 * 32) + i3),\n                    ((i0 * 16) + i2),\n                ),\n            ),\n            pad_value=None,\n        )\n        sch.annotate(block_or_loop=b50, ann_key=\"meta_schedule.layout_rewrite_preproc\", ann_val=1)\n\n    verify(Dense, apply_trace, DenseAdd, \"llvm\", DenseAdd_cpu_no_write_cache)\n\n\ndef test_dense_add_gpu():\n    def apply_anchor_trace(sch: Schedule) -> None:\n        b0 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        b1 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.annotate(block_or_loop=b0, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSSRRSRS\")\n        l2, l3, l4 = sch.get_loops(block=b0)\n        v5, v6, v7, v8, v9 = sch.sample_perfect_tile(\n            loop=l2, n=5, max_innermost_factor=64, decision=[8, 1, 16, 1, 1]\n        )\n        l10, l11, l12, l13, l14 = sch.split(\n            loop=l2, factors=[v5, v6, v7, v8, v9], preserve_unit_iters=True\n        )\n        v15, v16, v17, v18, v19 = sch.sample_perfect_tile(\n            loop=l3, n=5, max_innermost_factor=64, decision=[4, 1, 8, 4, 1]\n        )\n        l20, l21, l22, l23, l24 = sch.split(\n            loop=l3, factors=[v15, v16, v17, v18, v19], preserve_unit_iters=True\n        )\n        v25, v26, v27 = sch.sample_perfect_tile(\n            loop=l4, n=3, max_innermost_factor=64, decision=[32, 1, 4]\n        )\n        l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27], preserve_unit_iters=True)\n        sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24)\n        l31 = sch.fuse(l10, l20, preserve_unit_iters=True)\n        sch.bind(loop=l31, thread_axis=\"blockIdx.x\")\n        l32 = sch.fuse(l11, l21, preserve_unit_iters=True)\n        sch.bind(loop=l32, thread_axis=\"vthread.x\")\n        l33 = sch.fuse(l12, l22, preserve_unit_iters=True)\n        sch.bind(loop=l33, thread_axis=\"threadIdx.x\")\n        sch.annotate(\n            block_or_loop=b0, ann_key=\"meta_schedule.thread_extent_low_inclusive\", ann_val=16\n        )\n        sch.annotate(\n            block_or_loop=b0, ann_key=\"meta_schedule.thread_extent_high_inclusive\", ann_val=256\n        )\n        b34 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope=\"local\")\n        sch.reverse_compute_at(block=b34, loop=l33, preserve_unit_loops=True, index=-1)\n        b35 = sch.cache_read(\n            block=b0, read_buffer_index=0, storage_scope=\"shared\", consumer_blocks=[b0]\n        )\n        sch.compute_at(block=b35, loop=l28, preserve_unit_loops=True, index=-1)\n        l36, l37, l38, l39, l40, l41 = sch.get_loops(block=b35)\n        l42 = sch.fuse(l40, l41, preserve_unit_iters=True)\n        v43 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=1\n        )\n        sch.annotate(block_or_loop=b35, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v43)\n        b44 = sch.cache_read(\n            block=b0, read_buffer_index=1, storage_scope=\"shared\", consumer_blocks=[b0]\n        )\n        sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True, index=-1)\n        l45, l46, l47, l48, l49, l50 = sch.get_loops(block=b44)\n        l51 = sch.fuse(l49, l50, preserve_unit_iters=True)\n        v52 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3\n        )\n        sch.annotate(block_or_loop=b44, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v52)\n        v53 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512, 1024],\n            probs=[\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n            ],\n            decision=2,\n        )\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v53)\n        sch.enter_postproc()\n        sch.unannotate(block_or_loop=b35, ann_key=\"meta_schedule.cooperative_fetch\")\n        l54, l55, l56, l57, l58 = sch.get_loops(block=b35)\n        l59, l60, l61 = sch.split(loop=l58, factors=[None, 128, 2], preserve_unit_iters=True)\n        sch.vectorize(loop=l61)\n        sch.bind(loop=l60, thread_axis=\"threadIdx.x\")\n        sch.unannotate(block_or_loop=b44, ann_key=\"meta_schedule.cooperative_fetch\")\n        l62, l63, l64, l65, l66 = sch.get_loops(block=b44)\n        l67, l68, l69 = sch.split(loop=l66, factors=[None, 128, 4], preserve_unit_iters=True)\n        sch.vectorize(loop=l69)\n        sch.bind(loop=l68, thread_axis=\"threadIdx.x\")\n        b70 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b70, ann_key=\"meta_schedule.unroll_explicit\")\n        b71, b72, b73, b74 = sch.get_child_blocks(b70)\n        l75, l76, l77, l78, l79, l80, l81 = sch.get_loops(block=b71)\n        sch.annotate(block_or_loop=l75, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l75, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l82, l83, l84, l85, l86, l87, l88 = sch.get_loops(block=b72)\n        sch.annotate(block_or_loop=l82, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l82, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l89, l90, l91, l92, l93, l94, l95, l96, l97, l98 = sch.get_loops(block=b73)\n        sch.annotate(block_or_loop=l89, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l89, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l99, l100, l101, l102, l103 = sch.get_loops(block=b74)\n        sch.annotate(block_or_loop=l99, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l99, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        b104 = sch.get_block(name=\"T_matmul_NT\", func_name=\"main\")\n        l105, l106, l107, l108, l109, l110, l111, l112, l113, l114 = sch.get_loops(block=b104)\n        b115 = sch.decompose_reduction(block=b104, loop=l108)\n\n    verify(Dense, apply_anchor_trace, DenseAdd, \"cuda\", DenseAdd_scheduled_gpu)\n\n\ndef test_conv2d_int8_tensorcore():\n    def apply_trace(sch):\n        b0 = sch.get_block(name=\"pad_temp\", func_name=\"main\")\n        b1 = sch.get_block(name=\"conv2d_nhwc\", func_name=\"main\")\n        b2 = sch.get_block(name=\"T_subtract\", func_name=\"main\")\n        b3 = sch.get_block(name=\"T_add\", func_name=\"main\")\n        b4 = sch.get_block(name=\"T_cast\", func_name=\"main\")\n        b5 = sch.get_block(name=\"T_multiply\", func_name=\"main\")\n        b6 = sch.get_block(name=\"T_add_1\", func_name=\"main\")\n        b7 = sch.get_block(name=\"T_right_shift\", func_name=\"main\")\n        b8 = sch.get_block(name=\"T_cast_1\", func_name=\"main\")\n        b9 = sch.get_block(name=\"T_add_2\", func_name=\"main\")\n        b10 = sch.get_block(name=\"compute\", func_name=\"main\")\n        b11 = sch.get_block(name=\"T_cast_2\", func_name=\"main\")\n        b12 = sch.get_block(name=\"T_cast_3\", func_name=\"main\")\n        b13 = sch.get_block(name=\"T_subtract_1\", func_name=\"main\")\n        b14 = sch.get_block(name=\"compute_1\", func_name=\"main\")\n        b15 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSSRRSRS\")\n        b16 = sch.reindex(block=b1, buffer=(\"write\", 0))\n        b17 = sch.reindex(block=b1, buffer=(\"read\", 0))\n        b18 = sch.reindex(block=b1, buffer=(\"read\", 1))\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"read\", 0),\n            index_map=lambda nn, yy, xx, rc: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                rc,\n            ),\n            pad_value=None,\n        )\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"read\", 1),\n            index_map=lambda ff, ry, rx, rc: (\n                ry,\n                rx,\n                ff,\n                rc,\n            ),\n            pad_value=None,\n        )\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"write\", 0),\n            index_map=lambda nn, yy, xx, ff: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n            ),\n            pad_value=None,\n        )\n        sch.transform_block_layout(\n            block=b16,\n            index_map=lambda nn, yy, xx, ff: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b17,\n            index_map=lambda nn, yy, xx, rc: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                rc,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b18,\n            index_map=lambda ff, ry, rx, rc: (\n                ry,\n                rx,\n                ff,\n                rc,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b1,\n            index_map=lambda nn, yy, xx, ff, ry, rx, rc: (\n                ry,\n                rx,\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n                rc,\n            ),\n        )\n        l19, l20, l21, l22, l23 = sch.get_loops(block=b1)\n        l24, l25 = sch.split(loop=l23, factors=[None, 16], preserve_unit_iters=True)\n        l26, l27 = sch.split(loop=l22, factors=[None, 16], preserve_unit_iters=True)\n        l28, l29 = sch.split(loop=l21, factors=[None, 16], preserve_unit_iters=True)\n        l30, l31, l32, l33, l34, l35, l36, l37 = sch.get_loops(block=b1)\n        sch.reorder(l34, l36, l29, l27, l25)\n        b38 = sch.blockize(loop=l29)\n        sch.annotate(\n            block_or_loop=b38,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_sync_16x16x16_s8s8s32_trans\",\n        )\n        sch.annotate(\n            block_or_loop=b38,\n            ann_key=\"meta_schedule.auto_tensorize_init\",\n            ann_val=\"wmma_fill_16x16x16_s32\",\n        )\n        sch.annotate(block_or_loop=b38, ann_key=\"warp_execution\", ann_val=1)\n        l39, l40, l41, l42, l43 = sch.get_loops(block=b38)\n        v44, v45, v46 = sch.sample_perfect_tile(\n            loop=l39, n=3, max_innermost_factor=4, decision=[1, 1, 1]\n        )\n        l47, l48, l49 = sch.split(loop=l39, factors=[v44, v45, v46], preserve_unit_iters=True)\n        v50, v51, v52 = sch.sample_perfect_tile(\n            loop=l40, n=3, max_innermost_factor=4, decision=[1, 1, 1]\n        )\n        l53, l54, l55 = sch.split(loop=l40, factors=[v50, v51, v52], preserve_unit_iters=True)\n        v56, v57, v58, v59, v60 = sch.sample_perfect_tile(\n            loop=l41, n=5, max_innermost_factor=4, decision=[392, 1, 8, 1, 1]\n        )\n        l61, l62, l63, l64, l65 = sch.split(\n            loop=l41, factors=[v56, v57, v58, v59, v60], preserve_unit_iters=True\n        )\n        v66, v67, v68, v69, v70 = sch.sample_perfect_tile(\n            loop=l42, n=5, max_innermost_factor=4, decision=[8, 1, 2, 1, 1]\n        )\n        l71, l72, l73, l74, l75 = sch.split(\n            loop=l42, factors=[v66, v67, v68, v69, v70], preserve_unit_iters=True\n        )\n        v76, v77, v78 = sch.sample_perfect_tile(\n            loop=l43, n=3, max_innermost_factor=4, decision=[2, 1, 2]\n        )\n        l79, l80, l81 = sch.split(loop=l43, factors=[v76, v77, v78], preserve_unit_iters=True)\n        sch.reorder(\n            l61,\n            l71,\n            l62,\n            l72,\n            l63,\n            l73,\n            l47,\n            l53,\n            l79,\n            l48,\n            l54,\n            l80,\n            l64,\n            l74,\n            l49,\n            l55,\n            l81,\n            l65,\n            l75,\n        )\n        l82 = sch.fuse(l61, l71, preserve_unit_iters=True)\n        sch.bind(loop=l82, thread_axis=\"blockIdx.x\")\n        l83 = sch.fuse(l62, l72, preserve_unit_iters=True)\n        sch.bind(loop=l83, thread_axis=\"vthread.x\")\n        l84 = sch.fuse(l63, l73, preserve_unit_iters=True)\n        sch.bind(loop=l84, thread_axis=\"threadIdx.x\")\n        sch.annotate(\n            block_or_loop=b38, ann_key=\"meta_schedule.thread_extent_low_inclusive\", ann_val=32\n        )\n        sch.annotate(\n            block_or_loop=b38, ann_key=\"meta_schedule.thread_extent_high_inclusive\", ann_val=1024\n        )\n        b85 = sch.cache_write(block=b38, write_buffer_index=0, storage_scope=\"shared\")\n        sch.reverse_compute_at(block=b85, loop=l83, preserve_unit_loops=True, index=-1)\n        b86 = sch.cache_write(block=b38, write_buffer_index=0, storage_scope=\"wmma.accumulator\")\n        sch.reverse_compute_at(block=b86, loop=l84, preserve_unit_loops=True, index=-1)\n        v87 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=0,\n        )\n        sch.annotate(block_or_loop=b85, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v87)\n        sch.reverse_compute_inline(block=b16)\n        l88, l89, l90, l91, l92 = sch.get_loops(block=b86)\n        l93, l94 = sch.split(loop=l92, factors=[None, 16], preserve_unit_iters=True)\n        l95, l96 = sch.split(loop=l91, factors=[None, 16], preserve_unit_iters=True)\n        l97, l98, l99, l100, l101, l102, l103 = sch.get_loops(block=b86)\n        sch.reorder(l102, l96, l94)\n        b104 = sch.blockize(loop=l96)\n        sch.annotate(\n            block_or_loop=b104,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_store_16x16x16_s32_shared\",\n        )\n        b105 = sch.cache_read(\n            block=b38, read_buffer_index=0, storage_scope=\"shared\", consumer_blocks=[b38]\n        )\n        sch.compute_at(block=b105, loop=l79, preserve_unit_loops=True, index=-1)\n        l106, l107, l108, l109, l110, l111, l112, l113 = sch.get_loops(block=b105)\n        l114 = sch.fuse(l112, l113, preserve_unit_iters=True)\n        v115 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=5,\n        )\n        sch.annotate(block_or_loop=b105, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v115)\n        b116 = sch.cache_read(\n            block=b38, read_buffer_index=1, storage_scope=\"shared\", consumer_blocks=[b38]\n        )\n        sch.compute_at(block=b116, loop=l79, preserve_unit_loops=True, index=-1)\n        l117, l118, l119, l120, l121, l122, l123, l124, l125, l126 = sch.get_loops(block=b116)\n        l127 = sch.fuse(l123, l124, l125, l126, preserve_unit_iters=True)\n        v128 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=4,\n        )\n        sch.annotate(block_or_loop=b116, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v128)\n        b129 = sch.cache_read(block=b38, read_buffer_index=0, storage_scope=\"wmma.matrix_a\")\n        sch.compute_at(block=b129, loop=l80, preserve_unit_loops=True, index=-1)\n        l130, l131, l132, l133, l134, l135, l136, l137, l138, l139, l140 = sch.get_loops(block=b129)\n        l141, l142 = sch.split(loop=l140, factors=[None, 16], preserve_unit_iters=True)\n        l143, l144 = sch.split(loop=l139, factors=[None, 16], preserve_unit_iters=True)\n        (\n            l145,\n            l146,\n            l147,\n            l148,\n            l149,\n            l150,\n            l151,\n            l152,\n            l153,\n            l154,\n            l155,\n            l156,\n            l157,\n        ) = sch.get_loops(block=b129)\n        sch.reorder(l156, l144, l142)\n        b158 = sch.blockize(loop=l144)\n        sch.annotate(\n            block_or_loop=b158,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_load_16x16x16_s8_a\",\n        )\n        b159 = sch.cache_read(block=b38, read_buffer_index=1, storage_scope=\"wmma.matrix_b\")\n        sch.compute_at(block=b159, loop=l80, preserve_unit_loops=True, index=-1)\n        (\n            l160,\n            l161,\n            l162,\n            l163,\n            l164,\n            l165,\n            l166,\n            l167,\n            l168,\n            l169,\n            l170,\n            l171,\n            l172,\n        ) = sch.get_loops(block=b159)\n        l173, l174 = sch.split(loop=l172, factors=[None, 16], preserve_unit_iters=True)\n        l175, l176 = sch.split(loop=l171, factors=[None, 16], preserve_unit_iters=True)\n        (\n            l177,\n            l178,\n            l179,\n            l180,\n            l181,\n            l182,\n            l183,\n            l184,\n            l185,\n            l186,\n            l187,\n            l188,\n            l189,\n            l190,\n            l191,\n        ) = sch.get_loops(block=b159)\n        sch.reorder(l190, l176, l174)\n        b192 = sch.blockize(loop=l176)\n        sch.annotate(\n            block_or_loop=b192,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_load_16x16x16_s8_b_trans\",\n        )\n        sch.compute_inline(block=b17)\n        sch.compute_inline(block=b18)\n        sch.storage_align(block=b105, buffer_index=0, axis=-2, factor=32, offset=16)\n        sch.storage_align(block=b116, buffer_index=0, axis=-2, factor=32, offset=16)\n        sch.reverse_compute_inline(block=b14)\n        sch.reverse_compute_inline(block=b13)\n        sch.reverse_compute_inline(block=b12)\n        sch.reverse_compute_inline(block=b11)\n        sch.reverse_compute_inline(block=b10)\n        sch.reverse_compute_inline(block=b9)\n        sch.reverse_compute_inline(block=b8)\n        sch.reverse_compute_inline(block=b7)\n        sch.reverse_compute_inline(block=b6)\n        sch.reverse_compute_inline(block=b5)\n        sch.reverse_compute_inline(block=b4)\n        sch.reverse_compute_inline(block=b3)\n        sch.reverse_compute_inline(block=b2)\n        sch.compute_inline(block=b0)\n        v193 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512, 1024],\n            probs=[\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n            ],\n            decision=3,\n        )\n        sch.annotate(block_or_loop=b15, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v193)\n        sch.enter_postproc()\n        sch.unannotate(block_or_loop=b85, ann_key=\"meta_schedule.cooperative_fetch\")\n        l194, l195, l196, l197 = sch.get_loops(block=b85)\n        l198, l199 = sch.split(loop=l197, factors=[None, 16], preserve_unit_iters=True)\n        sch.bind(loop=l199, thread_axis=\"threadIdx.x\")\n        sch.unannotate(block_or_loop=b105, ann_key=\"meta_schedule.cooperative_fetch\")\n        l200, l201, l202, l203, l204, l205, l206 = sch.get_loops(block=b105)\n        l207, l208, l209 = sch.split(loop=l206, factors=[None, 16, 16], preserve_unit_iters=True)\n        sch.vectorize(loop=l209)\n        sch.bind(loop=l208, thread_axis=\"threadIdx.x\")\n        sch.unannotate(block_or_loop=b116, ann_key=\"meta_schedule.cooperative_fetch\")\n        l210, l211, l212, l213, l214, l215, l216 = sch.get_loops(block=b116)\n        l217, l218, l219 = sch.split(loop=l216, factors=[None, 16, 8], preserve_unit_iters=True)\n        sch.vectorize(loop=l219)\n        sch.bind(loop=l218, thread_axis=\"threadIdx.x\")\n        b220 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b220, ann_key=\"meta_schedule.unroll_explicit\")\n        b221, b222, b223, b224, b225, b226, b227 = sch.get_child_blocks(b220)\n        l228, l229, l230, l231, l232, l233, l234, l235, l236 = sch.get_loops(block=b221)\n        sch.annotate(block_or_loop=l228, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l228, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l237, l238, l239, l240, l241, l242, l243, l244, l245 = sch.get_loops(block=b222)\n        sch.annotate(block_or_loop=l237, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l237, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l246, l247, l248, l249, l250, l251, l252, l253, l254, l255, l256 = sch.get_loops(block=b223)\n        sch.annotate(block_or_loop=l246, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l246, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        (\n            l257,\n            l258,\n            l259,\n            l260,\n            l261,\n            l262,\n            l263,\n            l264,\n            l265,\n            l266,\n            l267,\n            l268,\n            l269,\n        ) = sch.get_loops(block=b224)\n        sch.annotate(block_or_loop=l257, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l257, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        (\n            l270,\n            l271,\n            l272,\n            l273,\n            l274,\n            l275,\n            l276,\n            l277,\n            l278,\n            l279,\n            l280,\n            l281,\n            l282,\n            l283,\n            l284,\n            l285,\n        ) = sch.get_loops(block=b225)\n        sch.annotate(block_or_loop=l270, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l270, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l286, l287, l288, l289, l290 = sch.get_loops(block=b226)\n        sch.annotate(block_or_loop=l286, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l286, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l291, l292, l293, l294, l295 = sch.get_loops(block=b227)\n        sch.annotate(block_or_loop=l291, ann_key=\"pragma_auto_unroll_max_step\", ann_val=512)\n        sch.annotate(block_or_loop=l291, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        b296 = sch.get_block(name=\"conv2d_nhwc_o\", func_name=\"main\")\n        (\n            l297,\n            l298,\n            l299,\n            l300,\n            l301,\n            l302,\n            l303,\n            l304,\n            l305,\n            l306,\n            l307,\n            l308,\n            l309,\n            l310,\n            l311,\n            l312,\n        ) = sch.get_loops(block=b296)\n        b313 = sch.decompose_reduction(block=b296, loop=l302)\n        sch.unannotate(block_or_loop=b313, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.annotate(\n            block_or_loop=b313,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_fill_16x16x16_s32\",\n        )\n        sch.unannotate(block_or_loop=b296, ann_key=\"meta_schedule.auto_tensorize_init\")\n        sch.unannotate(block_or_loop=b313, ann_key=\"meta_schedule.auto_tensorize_init\")\n        b314 = sch.get_block(name=\"conv2d_nhwc_o_init\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b314, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b314, tensor_intrin=\"wmma_fill_16x16x16_s32\")\n        b315 = sch.get_block(name=\"pad_temp_reindex_shared_wmma.matrix_a_o\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b315, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b315, tensor_intrin=\"wmma_load_16x16x16_s8_a\")\n        b316 = sch.get_block(name=\"p1_reindex_shared_wmma.matrix_b_o\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b316, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b316, tensor_intrin=\"wmma_load_16x16x16_s8_b_trans\")\n        b317 = sch.get_block(name=\"conv2d_nhwc_o_update\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b317, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b317, tensor_intrin=\"wmma_sync_16x16x16_s8s8s32_trans\")\n        b318 = sch.get_block(name=\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b318, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b318, tensor_intrin=\"wmma_store_16x16x16_s32_shared\")\n\n    verify(Conv2dInt8, apply_trace, Conv2dInt8_target, \"cuda\", Conv2dInt8_tensorcore_scheduled)\n\n\ndef test_conv2d_int8_vnni():\n    def apply_trace(sch):\n        b0 = sch.get_block(name=\"compile_engine_const\", func_name=\"main\")\n        b1 = sch.get_block(name=\"conv2d_NCHWc_int8\", func_name=\"main\")\n        b2 = sch.get_block(name=\"T_add\", func_name=\"main\")\n        b3 = sch.get_block(name=\"T_cast\", func_name=\"main\")\n        b4 = sch.get_block(name=\"T_multiply\", func_name=\"main\")\n        b5 = sch.get_block(name=\"compile_engine_const_1\", func_name=\"main\")\n        b6 = sch.get_block(name=\"T_add_1\", func_name=\"main\")\n        b7 = sch.get_block(name=\"T_floor\", func_name=\"main\")\n        b8 = sch.get_block(name=\"T_cast_1\", func_name=\"main\")\n        b9 = sch.get_block(name=\"compute\", func_name=\"main\")\n        b10 = sch.get_block(name=\"T_cast_2\", func_name=\"main\")\n        b11 = sch.get_block(name=\"T_cast_3\", func_name=\"main\")\n        b12 = sch.get_block(name=\"T_subtract\", func_name=\"main\")\n        b13 = sch.get_block(name=\"T_multiply_1\", func_name=\"main\")\n        b14 = sch.get_block(name=\"compile_engine_const_2\", func_name=\"main\")\n        b15 = sch.get_block(name=\"T_add_2\", func_name=\"main\")\n        b16 = sch.get_block(name=\"T_floor_1\", func_name=\"main\")\n        b17 = sch.get_block(name=\"T_cast_4\", func_name=\"main\")\n        b18 = sch.get_block(name=\"T_add_3\", func_name=\"main\")\n        b19 = sch.get_block(name=\"compute_1\", func_name=\"main\")\n        b20 = sch.get_block(name=\"T_cast_5\", func_name=\"main\")\n        b21 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.compute_inline(block=b20)\n        sch.compute_inline(block=b19)\n        sch.compute_inline(block=b18)\n        sch.compute_inline(block=b17)\n        sch.compute_inline(block=b16)\n        sch.compute_inline(block=b15)\n        sch.compute_inline(block=b14)\n        sch.compute_inline(block=b13)\n        sch.compute_inline(block=b12)\n        sch.compute_inline(block=b11)\n        sch.compute_inline(block=b10)\n        sch.compute_inline(block=b9)\n        sch.compute_inline(block=b8)\n        sch.compute_inline(block=b7)\n        sch.compute_inline(block=b6)\n        sch.compute_inline(block=b5)\n        sch.compute_inline(block=b4)\n        sch.compute_inline(block=b3)\n        sch.compute_inline(block=b2)\n        sch.compute_inline(block=b0)\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSRSRS\")\n        l22, l23, l24, l25, l26, l27, l28, l29, l30, l31 = sch.get_loops(block=b1)\n        l32, l33 = sch.split(loop=l31, factors=[None, 4], preserve_unit_iters=True)\n        l34, l35 = sch.split(loop=l26, factors=[None, 16], preserve_unit_iters=True)\n        l36, l37, l38, l39, l40, l41, l42, l43, l44, l45, l46, l47 = sch.get_loops(block=b1)\n        sch.reorder(l42, l43, l44, l45, l46, l35, l33)\n        b48 = sch.blockize(loop=l35)\n        sch.annotate(\n            block_or_loop=b48, ann_key=\"meta_schedule.auto_tensorize\", ann_val=\"dot_16x4_vnni\"\n        )\n        l49, l50, l51, l52, l53, l54, l55, l56, l57, l58 = sch.get_loops(block=b48)\n        v59, v60, v61, v62 = sch.sample_perfect_tile(\n            loop=l49, n=4, max_innermost_factor=64, decision=[1, 1, 1, 1]\n        )\n        l63, l64, l65, l66 = sch.split(\n            loop=l49, factors=[v59, v60, v61, v62], preserve_unit_iters=True\n        )\n        v67, v68, v69, v70 = sch.sample_perfect_tile(\n            loop=l50, n=4, max_innermost_factor=64, decision=[4, 32, 1, 1]\n        )\n        l71, l72, l73, l74 = sch.split(\n            loop=l50, factors=[v67, v68, v69, v70], preserve_unit_iters=True\n        )\n        v75, v76, v77, v78 = sch.sample_perfect_tile(\n            loop=l51, n=4, max_innermost_factor=64, decision=[1, 7, 1, 1]\n        )\n        l79, l80, l81, l82 = sch.split(\n            loop=l51, factors=[v75, v76, v77, v78], preserve_unit_iters=True\n        )\n        v83, v84, v85, v86 = sch.sample_perfect_tile(\n            loop=l52, n=4, max_innermost_factor=64, decision=[1, 1, 1, 7]\n        )\n        l87, l88, l89, l90 = sch.split(\n            loop=l52, factors=[v83, v84, v85, v86], preserve_unit_iters=True\n        )\n        v91, v92, v93, v94 = sch.sample_perfect_tile(\n            loop=l53, n=4, max_innermost_factor=64, decision=[1, 1, 1, 1]\n        )\n        l95, l96, l97, l98 = sch.split(\n            loop=l53, factors=[v91, v92, v93, v94], preserve_unit_iters=True\n        )\n        v99, v100 = sch.sample_perfect_tile(loop=l54, n=2, max_innermost_factor=64, decision=[1, 1])\n        l101, l102 = sch.split(loop=l54, factors=[v99, v100], preserve_unit_iters=True)\n        v103, v104 = sch.sample_perfect_tile(\n            loop=l55, n=2, max_innermost_factor=64, decision=[1, 1]\n        )\n        l105, l106 = sch.split(loop=l55, factors=[v103, v104], preserve_unit_iters=True)\n        v107, v108 = sch.sample_perfect_tile(\n            loop=l56, n=2, max_innermost_factor=64, decision=[4, 8]\n        )\n        l109, l110 = sch.split(loop=l56, factors=[v107, v108], preserve_unit_iters=True)\n        v111, v112 = sch.sample_perfect_tile(\n            loop=l57, n=2, max_innermost_factor=64, decision=[4, 1]\n        )\n        l113, l114 = sch.split(loop=l57, factors=[v111, v112], preserve_unit_iters=True)\n        v115, v116 = sch.sample_perfect_tile(\n            loop=l58, n=2, max_innermost_factor=64, decision=[1, 1]\n        )\n        l117, l118 = sch.split(loop=l58, factors=[v115, v116], preserve_unit_iters=True)\n        sch.reorder(\n            l63,\n            l71,\n            l79,\n            l87,\n            l95,\n            l64,\n            l72,\n            l80,\n            l88,\n            l96,\n            l101,\n            l105,\n            l109,\n            l113,\n            l117,\n            l65,\n            l73,\n            l81,\n            l89,\n            l97,\n            l102,\n            l106,\n            l110,\n            l114,\n            l118,\n            l66,\n            l74,\n            l82,\n            l90,\n            l98,\n        )\n        (b119,) = sch.get_consumers(block=b48)\n        sch.reverse_compute_at(block=b119, loop=l96, preserve_unit_loops=True, index=-1)\n        sch.annotate(block_or_loop=b21, ann_key=\"meta_schedule.parallel\", ann_val=96)\n        sch.annotate(block_or_loop=b21, ann_key=\"meta_schedule.vectorize\", ann_val=64)\n        v120 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=2\n        )\n        sch.annotate(block_or_loop=b21, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v120)\n        sch.enter_postproc()\n        b121 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b121, ann_key=\"meta_schedule.parallel\")\n        sch.unannotate(block_or_loop=b121, ann_key=\"meta_schedule.vectorize\")\n        sch.unannotate(block_or_loop=b121, ann_key=\"meta_schedule.unroll_explicit\")\n        b122, b123 = sch.get_child_blocks(b121)\n        (\n            l124,\n            l125,\n            l126,\n            l127,\n            l128,\n            l129,\n            l130,\n            l131,\n            l132,\n            l133,\n            l134,\n            l135,\n            l136,\n            l137,\n            l138,\n            l139,\n            l140,\n            l141,\n            l142,\n            l143,\n            l144,\n            l145,\n            l146,\n            l147,\n            l148,\n            l149,\n            l150,\n            l151,\n            l152,\n            l153,\n        ) = sch.get_loops(block=b122)\n        l154 = sch.fuse(l124, l125, l126, l127, l128, l129, l130, preserve_unit_iters=True)\n        sch.parallel(loop=l154)\n        sch.annotate(block_or_loop=l154, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l154, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l155, l156, l157, l158, l159, l160, l161, l162, l163 = sch.get_loops(block=b123)\n        l164 = sch.fuse(l163, preserve_unit_iters=True)\n        sch.vectorize(loop=l164)\n        sch.annotate(block_or_loop=l155, ann_key=\"pragma_auto_unroll_max_step\", ann_val=64)\n        sch.annotate(block_or_loop=l155, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        b165 = sch.get_block(name=\"conv2d_NCHWc_int8_o\", func_name=\"main\")\n        (\n            l166,\n            l167,\n            l168,\n            l169,\n            l170,\n            l171,\n            l172,\n            l173,\n            l174,\n            l175,\n            l176,\n            l177,\n            l178,\n            l179,\n            l180,\n            l181,\n            l182,\n            l183,\n            l184,\n            l185,\n            l186,\n            l187,\n            l188,\n            l189,\n        ) = sch.get_loops(block=b165)\n        b190 = sch.decompose_reduction(block=b165, loop=l172)\n        sch.unannotate(block_or_loop=b190, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.annotate(block_or_loop=b190, ann_key=\"meta_schedule.auto_tensorize\", ann_val=\"\")\n        b191 = sch.get_block(name=\"conv2d_NCHWc_int8_o_init\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b191, ann_key=\"meta_schedule.auto_tensorize\")\n        (b192,) = sch.get_child_blocks(b191)\n        (l193,) = sch.get_loops(block=b192)\n        sch.vectorize(loop=l193)\n        b194 = sch.get_block(name=\"conv2d_NCHWc_int8_o_update\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b194, ann_key=\"meta_schedule.auto_tensorize\")\n        sch.tensorize(block_or_loop=b194, tensor_intrin=\"dot_16x4_vnni\")\n\n    vnni_id = llvm_lookup_intrinsic_id(\"llvm.x86.avx512.vpdpbusd.512\")\n    verify(\n        Conv2dInt8_NCHWc,\n        apply_trace,\n        Conv2dInt8_NCHWc_target,\n        \"llvm -mcpu=cascadelake\",\n        get_conv2d_vnni_mod(vnni_id),\n    )\n\n\ndef test_winograd_gpu():\n    def apply_trace(sch):\n        b0 = sch.get_block(name=\"B\", func_name=\"main\")\n        b1 = sch.get_block(name=\"data_pack\", func_name=\"main\")\n        b2 = sch.get_block(name=\"bgemm\", func_name=\"main\")\n        b3 = sch.get_block(name=\"A\", func_name=\"main\")\n        b4 = sch.get_block(name=\"inverse\", func_name=\"main\")\n        b5 = sch.get_block(name=\"conv2d_winograd\", func_name=\"main\")\n        b6 = sch.get_block(name=\"T_add\", func_name=\"main\")\n        b7 = sch.get_block(name=\"T_relu\", func_name=\"main\")\n        b8 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.compute_inline(block=b0)\n        (b9,) = sch.get_producers(block=b1)\n        (b10,) = sch.get_producers(block=b9)\n        l11, l12, l13, l14, l15, l16 = sch.get_loops(block=b1)\n        v17, v18 = sch.sample_perfect_tile(\n            loop=l13, n=2, max_innermost_factor=64, decision=[14, 14]\n        )\n        l19, l20 = sch.split(loop=l13, factors=[v17, v18], preserve_unit_iters=True)\n        v21, v22 = sch.sample_perfect_tile(loop=l14, n=2, max_innermost_factor=64, decision=[8, 8])\n        l23, l24 = sch.split(loop=l14, factors=[v21, v22], preserve_unit_iters=True)\n        sch.unroll(loop=l11)\n        sch.unroll(loop=l12)\n        sch.unroll(loop=l15)\n        sch.unroll(loop=l16)\n        sch.reorder(l19, l23, l20, l24, l11, l12, l15, l16)\n        sch.compute_at(block=b9, loop=l24, preserve_unit_loops=True, index=-1)\n        sch.set_scope(block=b9, buffer_index=0, storage_scope=\"local\")\n        sch.compute_inline(block=b10)\n        l25, l26, l27, l28, l29, l30, l31, l32 = sch.get_loops(block=b1)\n        l33 = sch.fuse(l25, l26, l27, l28, preserve_unit_iters=True)\n        v34 = sch.sample_categorical(\n            candidates=[32, 64, 128, 256, 512, 1024],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=2,\n        )\n        l35, l36 = sch.split(loop=l33, factors=[None, v34], preserve_unit_iters=True)\n        sch.bind(loop=l35, thread_axis=\"blockIdx.x\")\n        sch.bind(loop=l36, thread_axis=\"threadIdx.x\")\n        sch.compute_inline(block=b3)\n        l37, l38, l39, l40, l41, l42 = sch.get_loops(block=b4)\n        v43, v44 = sch.sample_perfect_tile(loop=l39, n=2, max_innermost_factor=64, decision=[28, 7])\n        l45, l46 = sch.split(loop=l39, factors=[v43, v44], preserve_unit_iters=True)\n        v47, v48 = sch.sample_perfect_tile(loop=l40, n=2, max_innermost_factor=64, decision=[2, 32])\n        l49, l50 = sch.split(loop=l40, factors=[v47, v48], preserve_unit_iters=True)\n        sch.unroll(loop=l37)\n        sch.unroll(loop=l38)\n        sch.unroll(loop=l41)\n        sch.unroll(loop=l42)\n        sch.reorder(l45, l49, l46, l50, l37, l38, l41, l42)\n        l51, l52, l53, l54, l55, l56, l57, l58 = sch.get_loops(block=b4)\n        l59 = sch.fuse(l51, l52, l53, l54, preserve_unit_iters=True)\n        v60 = sch.sample_categorical(\n            candidates=[32, 64, 128, 256, 512, 1024],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=4,\n        )\n        l61, l62 = sch.split(loop=l59, factors=[None, v60], preserve_unit_iters=True)\n        sch.bind(loop=l61, thread_axis=\"blockIdx.x\")\n        sch.bind(loop=l62, thread_axis=\"threadIdx.x\")\n        sch.annotate(block_or_loop=b2, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSSRRSRS\")\n        l63, l64, l65, l66, l67 = sch.get_loops(block=b2)\n        v68, v69, v70, v71, v72 = sch.sample_perfect_tile(\n            loop=l63, n=5, max_innermost_factor=64, decision=[1, 2, 3, 1, 1]\n        )\n        l73, l74, l75, l76, l77 = sch.split(\n            loop=l63, factors=[v68, v69, v70, v71, v72], preserve_unit_iters=True\n        )\n        v78, v79, v80, v81, v82 = sch.sample_perfect_tile(\n            loop=l64, n=5, max_innermost_factor=64, decision=[6, 1, 1, 1, 1]\n        )\n        l83, l84, l85, l86, l87 = sch.split(\n            loop=l64, factors=[v78, v79, v80, v81, v82], preserve_unit_iters=True\n        )\n        v88, v89, v90, v91, v92 = sch.sample_perfect_tile(\n            loop=l65, n=5, max_innermost_factor=64, decision=[7, 2, 1, 14, 1]\n        )\n        l93, l94, l95, l96, l97 = sch.split(\n            loop=l65, factors=[v88, v89, v90, v91, v92], preserve_unit_iters=True\n        )\n        v98, v99, v100, v101, v102 = sch.sample_perfect_tile(\n            loop=l66, n=5, max_innermost_factor=64, decision=[4, 1, 16, 1, 1]\n        )\n        l103, l104, l105, l106, l107 = sch.split(\n            loop=l66, factors=[v98, v99, v100, v101, v102], preserve_unit_iters=True\n        )\n        v108, v109, v110 = sch.sample_perfect_tile(\n            loop=l67, n=3, max_innermost_factor=64, decision=[2, 2, 16]\n        )\n        l111, l112, l113 = sch.split(loop=l67, factors=[v108, v109, v110], preserve_unit_iters=True)\n        sch.reorder(\n            l73,\n            l83,\n            l93,\n            l103,\n            l74,\n            l84,\n            l94,\n            l104,\n            l75,\n            l85,\n            l95,\n            l105,\n            l111,\n            l112,\n            l76,\n            l86,\n            l96,\n            l106,\n            l113,\n            l77,\n            l87,\n            l97,\n            l107,\n        )\n        l114 = sch.fuse(l73, l83, l93, l103, preserve_unit_iters=True)\n        sch.bind(loop=l114, thread_axis=\"blockIdx.x\")\n        l115 = sch.fuse(l74, l84, l94, l104, preserve_unit_iters=True)\n        sch.bind(loop=l115, thread_axis=\"vthread.x\")\n        l116 = sch.fuse(l75, l85, l95, l105, preserve_unit_iters=True)\n        sch.bind(loop=l116, thread_axis=\"threadIdx.x\")\n        sch.annotate(\n            block_or_loop=b2, ann_key=\"meta_schedule.thread_extent_low_inclusive\", ann_val=32\n        )\n        sch.annotate(\n            block_or_loop=b2, ann_key=\"meta_schedule.thread_extent_high_inclusive\", ann_val=1024\n        )\n        b117 = sch.cache_write(block=b2, write_buffer_index=0, storage_scope=\"local\")\n        sch.reverse_compute_at(block=b117, loop=l116, preserve_unit_loops=True, index=-1)\n        b118 = sch.cache_read(\n            block=b2, read_buffer_index=0, storage_scope=\"shared\", consumer_blocks=[b2]\n        )\n        sch.compute_at(block=b118, loop=l111, preserve_unit_loops=True, index=-1)\n        l119, l120, l121, l122, l123, l124, l125, l126 = sch.get_loops(block=b118)\n        l127 = sch.fuse(l123, l124, l125, l126, preserve_unit_iters=True)\n        v128 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3\n        )\n        sch.annotate(block_or_loop=b118, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v128)\n        b129 = sch.cache_read(\n            block=b2, read_buffer_index=1, storage_scope=\"shared\", consumer_blocks=[b2]\n        )\n        sch.compute_at(block=b129, loop=l111, preserve_unit_loops=True, index=-1)\n        l130, l131, l132, l133, l134, l135, l136, l137 = sch.get_loops(block=b129)\n        l138 = sch.fuse(l134, l135, l136, l137, preserve_unit_iters=True)\n        v139 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3\n        )\n        sch.annotate(block_or_loop=b129, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v139)\n        sch.reverse_compute_inline(block=b7)\n        sch.reverse_compute_inline(block=b6)\n        v140 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512, 1024],\n            probs=[\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n            ],\n            decision=4,\n        )\n        sch.annotate(block_or_loop=b8, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v140)\n        l141, l142, l143, l144 = sch.get_loops(block=b5)\n        l145 = sch.fuse(l141, l142, l143, l144, preserve_unit_iters=True)\n        v146 = sch.sample_categorical(\n            candidates=[32, 64, 128, 256, 512, 1024],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=2,\n        )\n        l147, l148 = sch.split(loop=l145, factors=[None, v146], preserve_unit_iters=True)\n        sch.bind(loop=l147, thread_axis=\"blockIdx.x\")\n        sch.bind(loop=l148, thread_axis=\"threadIdx.x\")\n        sch.enter_postproc()\n        sch.unannotate(block_or_loop=b118, ann_key=\"meta_schedule.cooperative_fetch\")\n        l149, l150, l151, l152, l153 = sch.get_loops(block=b118)\n        l154, l155, l156 = sch.split(loop=l153, factors=[None, 48, 4], preserve_unit_iters=True)\n        sch.vectorize(loop=l156)\n        sch.bind(loop=l155, thread_axis=\"threadIdx.x\")\n        sch.unannotate(block_or_loop=b129, ann_key=\"meta_schedule.cooperative_fetch\")\n        l157, l158, l159, l160, l161 = sch.get_loops(block=b129)\n        l162, l163, l164 = sch.split(loop=l161, factors=[None, 48, 4], preserve_unit_iters=True)\n        sch.vectorize(loop=l164)\n        sch.bind(loop=l163, thread_axis=\"threadIdx.x\")\n        b165 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.unannotate(block_or_loop=b165, ann_key=\"meta_schedule.unroll_explicit\")\n        b166, b167, b168, b169, b170, b171, b172, b173 = sch.get_child_blocks(b165)\n        l174, l175, l176, l177, l178, l179 = sch.get_loops(block=b166)\n        sch.annotate(block_or_loop=l174, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l174, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l180, l181, l182, l183, l184, l185 = sch.get_loops(block=b167)\n        sch.annotate(block_or_loop=l180, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l180, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l186, l187, l188, l189, l190, l191, l192 = sch.get_loops(block=b168)\n        sch.annotate(block_or_loop=l186, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l186, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l193, l194, l195, l196, l197, l198, l199 = sch.get_loops(block=b169)\n        sch.annotate(block_or_loop=l193, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l193, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        (\n            l200,\n            l201,\n            l202,\n            l203,\n            l204,\n            l205,\n            l206,\n            l207,\n            l208,\n            l209,\n            l210,\n            l211,\n            l212,\n            l213,\n        ) = sch.get_loops(block=b170)\n        sch.annotate(block_or_loop=l200, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l200, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l214, l215, l216, l217, l218, l219, l220 = sch.get_loops(block=b171)\n        sch.annotate(block_or_loop=l214, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l214, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l221, l222, l223, l224, l225, l226 = sch.get_loops(block=b172)\n        sch.annotate(block_or_loop=l221, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l221, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        l227, l228 = sch.get_loops(block=b173)\n        sch.annotate(block_or_loop=l227, ann_key=\"pragma_auto_unroll_max_step\", ann_val=1024)\n        sch.annotate(block_or_loop=l227, ann_key=\"pragma_unroll_explicit\", ann_val=1)\n        b229 = sch.get_block(name=\"data_pack\", func_name=\"main\")\n        l230, l231, l232, l233, l234, l235 = sch.get_loops(block=b229)\n        b236 = sch.decompose_reduction(block=b229, loop=l234)\n        b237 = sch.get_block(name=\"bgemm\", func_name=\"main\")\n        (\n            l238,\n            l239,\n            l240,\n            l241,\n            l242,\n            l243,\n            l244,\n            l245,\n            l246,\n            l247,\n            l248,\n            l249,\n            l250,\n            l251,\n        ) = sch.get_loops(block=b237)\n        b252 = sch.decompose_reduction(block=b237, loop=l241)\n        b253 = sch.get_block(name=\"inverse\", func_name=\"main\")\n        l254, l255, l256, l257, l258, l259 = sch.get_loops(block=b253)\n        b260 = sch.decompose_reduction(block=b253, loop=l258)\n\n    verify(\n        Conv2dWinogradAddRelu,\n        apply_trace,\n        Conv2dWinogradAddResidualRelu,\n        \"cuda\",\n        Conv2dWinogradAddResidualRelu_scheduled,\n    )\n\n\ndef test_inline_order():\n    # In this test, the order of applying AutoInline is tested.\n    # We need to make sure that the last block in Conv2dInt8_with_predicate_target,\n    # \"compute_4\", is AutoInline-ed after all other blocks have been processed.\n    #\n    # Otherwise, if the order is \"T_add_2\" -> \"compute_4\" -> \"compute_3\", \"compute_4\" is neither\n    # inlined (because this is the last block) nor reverse-inlined\n    # (because it has multiple producers). This results in the \"compute_4\" block being\n    # reverse-inlined at the very end of ScheduleUsingAnchorTrace, where its producer block\n    # \"conv2d_nhwc_reindex_shared\" has the predicate\n    # T.where(((ax1_0 * 4 + ax1_1) * 32 + ax1_2) * 2 + ax1_3 < 64) due to anchor-block scheduling\n    # (see Conv2dInt8_with_predicate_scheduled). ReverseComputeInline cannot be applied in\n    # such cases.\n\n    def apply_trace(sch: Schedule) -> None:\n        b0 = sch.get_block(name=\"pad_temp\", func_name=\"main\")\n        b1 = sch.get_block(name=\"conv2d_nhwc\", func_name=\"main\")\n        b2 = sch.get_block(name=\"T_subtract\", func_name=\"main\")\n        b3 = sch.get_block(name=\"T_add\", func_name=\"main\")\n        b4 = sch.get_block(name=\"compute\", func_name=\"main\")\n        b5 = sch.get_block(name=\"T_add_1\", func_name=\"main\")\n        b6 = sch.get_block(name=\"compute_1\", func_name=\"main\")\n        b7 = sch.get_block(name=\"T_subtract_1\", func_name=\"main\")\n        b8 = sch.get_block(name=\"compute_2\", func_name=\"main\")\n        b9 = sch.get_block(name=\"root\", func_name=\"main\")\n        sch.annotate(block_or_loop=b1, ann_key=\"meta_schedule.tiling_structure\", ann_val=\"SSSRRSRS\")\n        b10 = sch.reindex(block=b1, buffer=(\"write\", 0))\n        b11 = sch.reindex(block=b1, buffer=(\"read\", 0))\n        b12 = sch.reindex(block=b1, buffer=(\"read\", 1))\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"read\", 0),\n            index_map=lambda nn, yy, xx, rc: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                rc,\n            ),\n            pad_value=None,\n        )\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"read\", 1),\n            index_map=lambda ff, ry, rx, rc: (\n                ry,\n                rx,\n                ff,\n                rc,\n            ),\n            pad_value=None,\n        )\n        sch.transform_layout(\n            block=b1,\n            buffer=(\"write\", 0),\n            index_map=lambda nn, yy, xx, ff: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n            ),\n            pad_value=None,\n        )\n        sch.transform_block_layout(\n            block=b10,\n            index_map=lambda nn, yy, xx, ff: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b11,\n            index_map=lambda nn, yy, xx, rc: (\n                (((nn * 3136) + (yy * 56)) + xx),\n                rc,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b12,\n            index_map=lambda ff, ry, rx, rc: (\n                ry,\n                rx,\n                ff,\n                rc,\n            ),\n        )\n        sch.transform_block_layout(\n            block=b1,\n            index_map=lambda nn, yy, xx, ff, ry, rx, rc: (\n                ry,\n                rx,\n                (((nn * 3136) + (yy * 56)) + xx),\n                ff,\n                rc,\n            ),\n        )\n        l13, l14, l15, l16, l17 = sch.get_loops(block=b1)\n        l18, l19 = sch.split(loop=l17, factors=[None, 16], preserve_unit_iters=True)\n        l20, l21 = sch.split(loop=l16, factors=[None, 16], preserve_unit_iters=True)\n        l22, l23 = sch.split(loop=l15, factors=[None, 16], preserve_unit_iters=True)\n        l24, l25, l26, l27, l28, l29, l30, l31 = sch.get_loops(block=b1)\n        sch.reorder(l28, l30, l23, l21, l19)\n        b32 = sch.blockize(loop=l23)\n        sch.annotate(\n            block_or_loop=b32,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_sync_16x16x16_s8s8s32_trans\",\n        )\n        sch.annotate(\n            block_or_loop=b32,\n            ann_key=\"meta_schedule.auto_tensorize_init\",\n            ann_val=\"wmma_fill_16x16x16_s32\",\n        )\n        sch.annotate(block_or_loop=b32, ann_key=\"warp_execution\", ann_val=1)\n        l33, l34, l35, l36, l37 = sch.get_loops(block=b32)\n        v38, v39, v40 = sch.sample_perfect_tile(\n            loop=l33, n=3, max_innermost_factor=4, decision=[1, 1, 1]\n        )\n        l41, l42, l43 = sch.split(loop=l33, factors=[v38, v39, v40], preserve_unit_iters=True)\n        v44, v45, v46 = sch.sample_perfect_tile(\n            loop=l34, n=3, max_innermost_factor=4, decision=[1, 1, 1]\n        )\n        l47, l48, l49 = sch.split(loop=l34, factors=[v44, v45, v46], preserve_unit_iters=True)\n        v50, v51, v52, v53, v54 = sch.sample_perfect_tile(\n            loop=l35, n=5, max_innermost_factor=4, decision=[8, 196, 2, 1, 1]\n        )\n        l55, l56, l57, l58, l59 = sch.split(\n            loop=l35, factors=[v50, v51, v52, v53, v54], preserve_unit_iters=True\n        )\n        v60, v61, v62, v63, v64 = sch.sample_perfect_tile(\n            loop=l36, n=5, max_innermost_factor=4, decision=[4, 1, 2, 1, 2]\n        )\n        l65, l66, l67, l68, l69 = sch.split(\n            loop=l36, factors=[v60, v61, v62, v63, v64], preserve_unit_iters=True\n        )\n        v70, v71, v72 = sch.sample_perfect_tile(\n            loop=l37, n=3, max_innermost_factor=4, decision=[2, 2, 1]\n        )\n        l73, l74, l75 = sch.split(loop=l37, factors=[v70, v71, v72], preserve_unit_iters=True)\n        sch.reorder(\n            l55,\n            l65,\n            l56,\n            l66,\n            l57,\n            l67,\n            l41,\n            l47,\n            l73,\n            l42,\n            l48,\n            l74,\n            l58,\n            l68,\n            l43,\n            l49,\n            l75,\n            l59,\n            l69,\n        )\n        l76 = sch.fuse(l55, l65, preserve_unit_iters=True)\n        sch.bind(loop=l76, thread_axis=\"blockIdx.y\")\n        l77 = sch.fuse(l56, l66, preserve_unit_iters=True)\n        sch.bind(loop=l77, thread_axis=\"blockIdx.x\")\n        l78 = sch.fuse(l57, l67, preserve_unit_iters=True)\n        sch.bind(loop=l78, thread_axis=\"threadIdx.y\")\n        sch.annotate(\n            block_or_loop=b32, ann_key=\"meta_schedule.thread_extent_low_inclusive\", ann_val=32\n        )\n        sch.annotate(\n            block_or_loop=b32, ann_key=\"meta_schedule.thread_extent_high_inclusive\", ann_val=1024\n        )\n        b79 = sch.cache_write(block=b32, write_buffer_index=0, storage_scope=\"shared\")\n        sch.reverse_compute_at(block=b79, loop=l77, preserve_unit_loops=True, index=-1)\n        b80 = sch.cache_write(block=b32, write_buffer_index=0, storage_scope=\"wmma.accumulator\")\n        sch.reverse_compute_at(block=b80, loop=l78, preserve_unit_loops=True, index=-1)\n        v81 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=1,\n        )\n        sch.annotate(block_or_loop=b79, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v81)\n        sch.reverse_compute_inline(block=b10)\n        l82, l83, l84, l85, l86 = sch.get_loops(block=b80)\n        l87, l88 = sch.split(loop=l86, factors=[None, 16], preserve_unit_iters=True)\n        l89, l90 = sch.split(loop=l85, factors=[None, 16], preserve_unit_iters=True)\n        l91, l92, l93, l94, l95, l96, l97 = sch.get_loops(block=b80)\n        sch.reorder(l96, l90, l88)\n        b98 = sch.blockize(loop=l90)\n        sch.annotate(\n            block_or_loop=b98,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_store_16x16x16_s32_shared\",\n        )\n        b99 = sch.cache_read(\n            block=b32, read_buffer_index=0, storage_scope=\"shared\", consumer_blocks=[b32]\n        )\n        sch.compute_at(block=b99, loop=l73, preserve_unit_loops=True, index=-1)\n        l100, l101, l102, l103, l104, l105, l106, l107 = sch.get_loops(block=b99)\n        l108 = sch.fuse(l106, l107, preserve_unit_iters=True)\n        v109 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=3,\n        )\n        sch.annotate(block_or_loop=b99, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v109)\n        b110 = sch.cache_read(\n            block=b32, read_buffer_index=1, storage_scope=\"shared\", consumer_blocks=[b32]\n        )\n        sch.compute_at(block=b110, loop=l73, preserve_unit_loops=True, index=-1)\n        l111, l112, l113, l114, l115, l116, l117, l118, l119, l120 = sch.get_loops(block=b110)\n        l121 = sch.fuse(l117, l118, l119, l120, preserve_unit_iters=True)\n        v122 = sch.sample_categorical(\n            candidates=[1, 2, 3, 4, 8, 16],\n            probs=[\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n                0.16666666666666666,\n            ],\n            decision=2,\n        )\n        sch.annotate(block_or_loop=b110, ann_key=\"meta_schedule.cooperative_fetch\", ann_val=v122)\n        b123 = sch.cache_read(block=b32, read_buffer_index=0, storage_scope=\"wmma.matrix_a\")\n        sch.compute_at(block=b123, loop=l74, preserve_unit_loops=True, index=-1)\n        l124, l125, l126, l127, l128, l129, l130, l131, l132, l133, l134 = sch.get_loops(block=b123)\n        l135, l136 = sch.split(loop=l134, factors=[None, 16], preserve_unit_iters=True)\n        l137, l138 = sch.split(loop=l133, factors=[None, 16], preserve_unit_iters=True)\n        (\n            l139,\n            l140,\n            l141,\n            l142,\n            l143,\n            l144,\n            l145,\n            l146,\n            l147,\n            l148,\n            l149,\n            l150,\n            l151,\n        ) = sch.get_loops(block=b123)\n        sch.reorder(l150, l138, l136)\n        b152 = sch.blockize(loop=l138)\n        sch.annotate(\n            block_or_loop=b152,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_load_16x16x16_s8_a\",\n        )\n        b153 = sch.cache_read(block=b32, read_buffer_index=1, storage_scope=\"wmma.matrix_b\")\n        sch.compute_at(block=b153, loop=l74, preserve_unit_loops=True, index=-1)\n        (\n            l154,\n            l155,\n            l156,\n            l157,\n            l158,\n            l159,\n            l160,\n            l161,\n            l162,\n            l163,\n            l164,\n            l165,\n            l166,\n        ) = sch.get_loops(block=b153)\n        l167, l168 = sch.split(loop=l166, factors=[None, 16], preserve_unit_iters=True)\n        l169, l170 = sch.split(loop=l165, factors=[None, 16], preserve_unit_iters=True)\n        (\n            l171,\n            l172,\n            l173,\n            l174,\n            l175,\n            l176,\n            l177,\n            l178,\n            l179,\n            l180,\n            l181,\n            l182,\n            l183,\n            l184,\n            l185,\n        ) = sch.get_loops(block=b153)\n        sch.reorder(l184, l170, l168)\n        b186 = sch.blockize(loop=l170)\n        sch.annotate(\n            block_or_loop=b186,\n            ann_key=\"meta_schedule.auto_tensorize\",\n            ann_val=\"wmma_load_16x16x16_s8_b_trans\",\n        )\n        sch.compute_inline(block=b11)\n        sch.compute_inline(block=b12)\n        sch.storage_align(block=b99, buffer_index=0, axis=-2, factor=32, offset=16)\n        sch.storage_align(block=b110, buffer_index=0, axis=-2, factor=32, offset=16)\n        sch.reverse_compute_inline(block=b8)\n        sch.reverse_compute_inline(block=b7)\n        sch.reverse_compute_inline(block=b6)\n        sch.reverse_compute_inline(block=b5)\n        sch.reverse_compute_inline(block=b4)\n        sch.reverse_compute_inline(block=b3)\n        sch.reverse_compute_inline(block=b2)\n        sch.compute_inline(block=b0)\n\n        v187 = sch.sample_categorical(\n            candidates=[0, 16, 64, 512, 1024],\n            probs=[\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n                0.20000000000000001,\n            ],\n            decision=4,\n        )\n        sch.annotate(block_or_loop=b9, ann_key=\"meta_schedule.unroll_explicit\", ann_val=v187)\n        sch.enter_postproc()\n        sch.unannotate(block_or_loop=b79, ann_key=\"meta_schedule.cooperative_fetch\")\n        l188, l189, l190, l191 = sch.get_loops(block=b79)\n\n        l192, l193, l194, l195 = sch.split(\n            loop=l191, factors=[None, 4, 32, 2], preserve_unit_iters=True\n        )\n\n    verify(\n        Conv2dInt8_with_predicate,\n        apply_trace,\n        Conv2dInt8_with_predicate_target,\n        \"cuda\",\n        Conv2dInt8_with_predicate_scheduled,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_tune_context.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test the tune context of meta schedule.\"\"\"\n\nimport sys\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.meta_schedule import TuneContext\n\n# pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\n@tvm.script.ir_module\nclass Matmul:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=no-self-argument\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        A = T.match_buffer(a, (1024, 1024), \"float32\")\n        B = T.match_buffer(b, (1024, 1024), \"float32\")\n        C = T.match_buffer(c, (1024, 1024), \"float32\")\n        for i, j, k in T.grid(1024, 1024, 1024):\n            with T.block(\"matmul\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = 0.0\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\n# pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring\n\n\ndef test_tune_context_create():\n    mod = Matmul\n    context = TuneContext(mod=mod, target=Target(\"llvm\"), task_name=\"Test Task\")\n    assert context.num_threads > 0\n    assert context.rand_state != -1\n    assert context.task_name == \"Test Task\"\n    assert context.mod == mod or tvm.ir.structural_equal(context.mod, mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_tune_tir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring,no-member,invalid-name,unused-variable\nimport logging\nimport tempfile\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc\nfrom tvm.meta_schedule.testing.local_rpc import LocalRPC\nfrom tvm.script import tir as T\nfrom tvm.target import Target\nfrom tvm.tir.schedule import BlockRV, Schedule\n\nlogging.basicConfig()\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef two_step(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (1024, 1024), \"float32\")\n    B = T.alloc_buffer((1024, 1024), \"float32\")\n    C = T.match_buffer(c, (1024, 1024), \"float32\")\n    for i, j in T.grid(1024, 1024):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(1024, 1024):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 3.0\n\n\n@tvm.testing.requires_llvm\ndef test_tune_matmul_cpu():\n    with tempfile.TemporaryDirectory() as work_dir:\n        target = Target(\"llvm --num-cores=16\")\n        database = ms.tir_integration.tune_tir(\n            mod=matmul,\n            target=target,\n            work_dir=work_dir,\n            max_trials_global=32,\n            num_trials_per_iter=16,\n        )\n        sch = ms.tir_integration.compile_tir(database, matmul, target)\n        if sch is None:\n            print(\"No valid schedule found!\")\n        else:\n            sch.mod.show()\n            sch.trace.show()\n\n\n@tvm.testing.requires_cuda\ndef test_tune_matmul_cuda():\n    with tempfile.TemporaryDirectory() as work_dir:\n        target = Target(\"nvidia/geforce-rtx-3070\")\n        database = ms.tir_integration.tune_tir(\n            mod=matmul,\n            target=target,\n            work_dir=work_dir,\n            max_trials_global=32,\n            num_trials_per_iter=16,\n        )\n        sch = ms.tir_integration.compile_tir(database, matmul, target)\n        if sch is None:\n            print(\"No valid schedule found!\")\n        else:\n            sch.mod.show()\n            sch.trace.show()\n\n\ndef test_tune_run_module_via_rpc():\n    target = tvm.target.Target(\"llvm\")\n    rt_mod = tvm.build(matmul, target)\n\n    # construct the input\n    input_data = {}\n    input_shape = (128, 128)\n    input_dtype = \"float32\"\n    a_np = np.random.uniform(size=input_shape).astype(input_dtype)\n    b_np = np.random.uniform(size=input_shape).astype(input_dtype)\n    c_np = np.zeros(input_shape).astype(input_dtype)\n    for i in range(128):\n        for j in range(128):\n            for k in range(128):\n                c_np[i, j] = c_np[i, j] + a_np[i, k] * b_np[j, k]\n    input_data[\"a\"] = a_np\n    input_data[\"b\"] = b_np\n    input_data[\"c\"] = np.zeros(input_shape).astype(input_dtype)\n\n    with LocalRPC() as rpc:\n        rpc_config = ms.runner.RPCConfig(\n            tracker_host=rpc.tracker_host,\n            tracker_port=rpc.tracker_port,\n            tracker_key=rpc.tracker_key,\n            session_priority=1,\n            session_timeout_sec=100,\n        )\n\n        def f_timer(rt_mod, dev, input_data):\n            rt_mod(input_data[\"a\"], input_data[\"b\"], input_data[\"c\"])\n            return input_data[\"c\"]\n\n        result = run_module_via_rpc(\n            rpc_config=rpc_config,\n            lib=rt_mod,\n            dev_type=target.kind.name,\n            args=input_data,\n            continuation=f_timer,\n        )\n        tvm.testing.assert_allclose(result.numpy(), c_np, rtol=1e-3)\n\n\ndef test_tune_block_cpu():\n    @ms.derived_object\n    class RemoveBlock(ms.schedule_rule.PyScheduleRule):\n        def _initialize_with_tune_context(self, context: ms.TuneContext) -> None:\n            pass\n\n        def apply(self, sch: Schedule, block: BlockRV):\n            if sch.get(block).name_hint == \"root\":\n                return [sch]\n            sch = sch.copy()\n            sch.compute_inline(block)\n            return [sch]\n\n        def clone(self) -> \"RemoveBlock\":\n            return RemoveBlock()\n\n    with tempfile.TemporaryDirectory() as work_dir:\n        target = Target(\"llvm --num-cores=16\")\n        database = ms.tir_integration.tune_tir(\n            mod=two_step,\n            target=target,\n            work_dir=work_dir,\n            max_trials_global=32,\n            num_trials_per_iter=16,\n            space=ms.space_generator.PostOrderApply(\n                f_block_filter=lambda block: block.name_hint == \"A\",\n                sch_rules=[RemoveBlock()],\n                postprocs=[],\n                mutator_probs={},\n            ),\n        )\n        sch = ms.tir_integration.compile_tir(database, two_step, target)\n        assert sch is not None\n        sch.mod.show()\n        sch.trace.show()\n\n\nif __name__ == \"\"\"__main__\"\"\":\n    test_tune_matmul_cpu()\n    test_tune_matmul_cuda()\n    test_tune_run_module_via_rpc()\n    test_tune_block_cpu()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_meta_schedule_vnni_integration.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport logging\nimport tempfile\nfrom typing import Optional\n\nimport numpy as np  # type: ignore\nimport tvm\nimport tvm.testing\nfrom tvm import meta_schedule as ms\nfrom tvm import relay\nfrom tvm._ffi import register_func\nfrom tvm.tir.schedule import BlockRV, Schedule\nfrom tvm.tir.schedule.analysis import has_block\nfrom tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN\n\nlogging.basicConfig(\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\nlogging.getLogger(\"tvm.meta_schedule\").setLevel(logging.DEBUG)\n\n\ndef _schedule_dense(m: Optional[int], do_tune: bool):\n    \"\"\"Manually schedule a dense block, created from TE compute op via CreatePrimFunc,\n    using VNNI instruction.\n    \"\"\"\n\n    def schedule_fn(sch, dense_block: Optional[BlockRV] = None) -> bool:\n        if sch.mod.attrs is not None and \"dense\" not in sch.mod.attrs[\"task_name\"]:\n            return False\n        if dense_block is None:\n            assert has_block(sch, \"compute\")\n            dense_block = sch.get_block(\"compute\")\n            assert \"dense_vnni\" in sch.get(dense_block).annotations[\"schedule_rule\"]\n\n        post_blocks = sch.get_consumers(dense_block)\n        if len(post_blocks) > 0:\n            # Fuse all intermediate post ops into the last op.\n            # This is equivalent to the traverse_inline function used in TE schedules.\n            while True:\n                next_post_blocks = []\n                for post_block in post_blocks:\n                    next_consumers = sch.get_consumers(post_block)\n                    if len(next_consumers) > 0:\n                        sch.compute_inline(post_block)\n                    next_post_blocks += next_consumers\n                if len(next_post_blocks) == 0:\n                    assert len(post_blocks) == 1\n                    outer_block = post_blocks[0]\n                    a_y, a_x = sch.get_loops(outer_block)[-2:]\n                    break\n                post_blocks = next_post_blocks\n        else:\n            a_y, a_x, _ = sch.get_loops(dense_block)[-3:]\n            outer_block = dense_block\n        if do_tune:\n            y_factors = sch.sample_perfect_tile(a_y, n=2, max_innermost_factor=128)\n            a_yo, a_yi = sch.split(a_y, factors=y_factors)\n        else:\n            a_yo, a_yi = sch.split(a_y, factors=[None, min(m, 64)])\n        a_xo, a_xi = sch.split(a_x, factors=[None, 16])\n        sch.reorder(a_yo, a_xo, a_yi, a_xi)\n        fused = sch.fuse(a_yo, a_xo)\n        if outer_block != dense_block:\n            # Handle the case when dense is fused with post ops.\n            sch.vectorize(a_xi)\n            sch.compute_at(dense_block, a_yi)\n        a_xi, a_k = sch.get_loops(dense_block)[-2:]\n        a_ko, a_ki = sch.split(a_k, factors=[None, 4])\n        sch.reorder(a_ko, a_xi, a_ki)\n        # We need to parallelize before decompose_reduction, otherwise the so-called \"Compact dataflow\"\n        # condition is violated.\n        sch.parallel(fused)\n        dec = sch.decompose_reduction(dense_block, a_ko)\n        init_loop = sch.get_loops(dec)[-1]\n        sch.vectorize(init_loop)\n        sch.tensorize(a_xi, VNNI_INTRIN)\n        return True\n\n    return schedule_fn\n\n\ndef _relay_dense(m, n, k):\n    data = relay.var(\"data\", shape=(m, k), dtype=\"uint8\")\n    weight = relay.var(\"weight\", shape=(n, k), dtype=\"int8\")\n    bias = relay.var(\"bias\", shape=(n,), dtype=\"int32\")\n    # dense is tuned by the TIR schedule above, bmm is scheduled by TE (topi/x86/batch_matmul.py)\n    dense = relay.nn.dense(data, weight, out_dtype=\"int32\")\n    bias_add = relay.nn.bias_add(dense, bias) + relay.const(1, dtype=\"int32\")\n    out = relay.nn.batch_matmul(\n        relay.cast(relay.expand_dims(bias_add, 0), \"uint8\"),\n        relay.cast(relay.expand_dims(bias_add, 0), \"int8\"),\n        out_dtype=\"int32\",\n    )\n    relay_mod = tvm.IRModule.from_expr(out)\n    data = np.random.uniform(1, 10, size=(m, k)).astype(\"uint8\")\n    params = {\n        \"weight\": np.random.uniform(1, 10, size=(n, k)).astype(\"int8\"),\n        \"bias\": np.random.uniform(1, 10, size=(n,)).astype(\"int32\"),\n    }\n\n    def f_check(lib, dev):\n        ref = (\n            relay.create_executor(\n                \"vm\",\n                mod=relay_mod,\n                device=dev,\n                target=\"llvm\",\n            )\n            .evaluate()(data, params[\"weight\"], params[\"bias\"])\n            .numpy()\n        )\n        runtime = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n        runtime.set_input(\"data\", data)\n        runtime.run()\n        out = runtime.get_output(0).numpy()\n        np.testing.assert_equal(out, ref)\n\n    return relay_mod, params, f_check\n\n\n@tvm.testing.requires_cascadelake\ndef test_vnni_schedule_fn_database():\n    m, n, k = 1024, 1024, 1024\n    target = tvm.target.Target(\"llvm -mcpu=cascadelake -num-cores 4\")\n    dev = tvm.cpu(0)\n    relay_mod, params, f_check = _relay_dense(m, n, k)\n\n    with ms.database.ScheduleFnDatabase(\n        _schedule_dense(\n            m=m,\n            do_tune=False,\n        )\n    ), tvm.transform.PassContext(\n        opt_level=3,\n        config={\"relay.backend.use_meta_schedule\": True},\n    ):\n        # pylint: disable=W0105\n        \"\"\"The log should say\n        Warning: Cannot find workload: tvmgen_default_fused_expand_dims\n        Warning: Cannot find workload: tvmgen_default_fused_cast\n        Warning: Cannot find workload: tvmgen_default_fused_cast_1\n        Warning: Cannot find workload: tvmgen_default_fused_nn_batch_matmul\n\n        This means batch matmul and others are scheduled by TE, and dense (the one not warned)\n        is found in the meta schedule tuning database during compilation\n        \"\"\"\n        # pylint: enable=W0105\n        lib = relay.build(relay_mod, target=target, params=params)\n    f_check(lib, dev)\n\n\n@tvm.testing.requires_cascadelake\ndef test_vnni_schedule_fn_tune():\n    # pylint: disable=W0105\n    \"\"\"\n    We can inject and apply a custom TIR scheduling to a TE compute of interest, using\n    the \"schedule_rule\" annotation. For example, in topi/x86/dense.py we have the following\n    declaration for int8 dense targeting the VNNI instruction.\n\n    C = te.compute(\n        ...\n        attrs={\"schedule_rule\": \"meta_schedule.x86.dense_vnni\"},\n    )\n\n    When the MetaSchedule encounters a TensorIR block with the \"schedule_rule\" annotation,\n    it looks up the packed func registry for a function that is associated with the given schedule\n    rule key (\"meta_schedule.x86.dense_vnni\" in this example). The signature of such custom\n    schedule functions must be\n\n       (tir.schedule.Schedule, tir.schedule.BlockRV) -> [tir.schedule.Schedule].\n\n    The BlockRV argument corresponds to the TE compute annotated with \"schedule_rule\".\n\n    The relevant code is in `src/meta_schedule/space_generator/apply_custom_rule.cc`.\n    \"\"\"\n\n    def schedule_rule_dense_vnni(sch: Schedule, dense_block: BlockRV):\n        _schedule_dense(m=None, do_tune=True)(sch, dense_block)\n        return [sch]\n\n    register_func(\"meta_schedule.x86.dense_vnni\", schedule_rule_dense_vnni)\n\n    m, n, k = 1024, 1024, 1024\n    target = tvm.target.Target(\"llvm -keys=x86,cpu -mcpu=cascadelake -num-cores=4\")\n    dev = tvm.cpu(0)\n    relay_mod, params, f_check = _relay_dense(m, n, k)\n\n    extracted_tasks = ms.relay_integration.extract_tasks(relay_mod, target, params)\n    with tempfile.TemporaryDirectory() as work_dir:\n        # postprocs=lambda: [] is important to prevent default post processors from\n        # tampering with the manual schedule.\n        tasks, weights = ms.relay_integration.extracted_tasks_to_tune_contexts(\n            list(\n                filter(\n                    lambda task: \"dense\" in task.task_name,\n                    extracted_tasks,\n                )\n            ),\n            work_dir=work_dir,\n            space=ms.space_generator.PostOrderApply(\n                f_block_filter=None,\n                sch_rules=\"from-target\",\n                postprocs=[],\n                mutator_probs=\"from-target\",\n            ),\n        )\n        database = ms.relay_integration.tune_tasks(\n            tasks=tasks,\n            task_weights=weights,\n            work_dir=work_dir,\n            max_trials_per_task=32,\n            max_trials_global=20000,\n        )\n    with database, tvm.transform.PassContext(\n        opt_level=3,\n        config={\"relay.backend.use_meta_schedule\": True},\n    ):\n        # pylint: disable=W0105\n        \"\"\"The log should say\n        Warning: Cannot find workload: tvmgen_default_fused_expand_dims\n        Warning: Cannot find workload: tvmgen_default_fused_cast\n        Warning: Cannot find workload: tvmgen_default_fused_cast_1\n        Warning: Cannot find workload: tvmgen_default_fused_nn_batch_matmul\n\n        This means batch matmul and others are scheduled by TE, and dense (the one not warned)\n        is found in the meta schedule tuning database during compilation\n        \"\"\"\n        # pylint: enable=W0105\n        lib = relay.build(relay_mod, target=target, params=params)\n    f_check(lib, dev)\n\n\nif __name__ == \"\"\"__main__\"\"\":\n    test_vnni_schedule_fn_database()\n    test_vnni_schedule_fn_tune()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_micro_model_library_format.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pathlib\nimport sys\nimport datetime\nimport json\nimport os\nimport tarfile\n\nimport numpy as np\nimport pytest\nimport platform\n\npytest.importorskip(\"tvm.micro\")\n\nimport tvm\nimport tvm.relay\nfrom tvm.relay.backend import Executor, Runtime\nfrom tvm.relay.testing import byoc\nimport tvm.runtime.module\nimport tvm.testing\nfrom tvm.contrib import utils\nimport tvm.micro as micro\nfrom tvm.micro.testing.utils import get_conv2d_relay_module\nimport tvm.micro.model_library_format as model_library_format\nfrom tvm.micro.model_library_format import _GENERATED_VERSION\n\n\n@tvm.testing.requires_micro\ndef test_export_operator_model_library_format():\n    target = tvm.target.target.micro(\"host\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        A = tvm.te.placeholder((2,), dtype=\"int8\")\n        B = tvm.te.placeholder((1,), dtype=\"int8\")\n        C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name=\"C\")\n        sched = tvm.te.create_schedule(C.op)\n        mod = tvm.build(\n            sched,\n            [A, B, C],\n            tvm.target.Target(target, target),\n            runtime=Runtime(\"crt\", {\"system-lib\": True}),\n            name=\"add\",\n        )\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n    micro.export_model_library_format(mod, mlf_tar_path)\n\n    tf = tarfile.open(mlf_tar_path)\n\n    extract_dir = temp_dir.relpath(\"extract\")\n    os.mkdir(extract_dir)\n    tf.extractall(extract_dir)\n\n    with open(os.path.join(extract_dir, \"metadata.json\")) as json_f:\n        metadata = json.load(json_f)\n        assert metadata[\"version\"] == _GENERATED_VERSION\n        assert metadata[\"model_name\"] == \"add\"\n        export_datetime = datetime.datetime.strptime(\n            metadata[\"export_datetime\"], \"%Y-%m-%d %H:%M:%SZ\"\n        )\n        assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5)\n        assert metadata[\"target\"] == [str(target)]\n\n        assert metadata[\"memory\"][\"add\"][0][\"dtype\"] == \"int8\"\n        assert metadata[\"memory\"][\"add\"][0][\"shape\"] == [2]\n        assert metadata[\"memory\"][\"add\"][0][\"size_bytes\"] == 2\n\n        assert metadata[\"memory\"][\"add\"][1][\"dtype\"] == \"int8\"\n        assert metadata[\"memory\"][\"add\"][1][\"shape\"] == [1]\n        assert metadata[\"memory\"][\"add\"][1][\"size_bytes\"] == 1\n\n        assert metadata[\"memory\"][\"add\"][2][\"dtype\"] == \"int8\"\n        assert metadata[\"memory\"][\"add\"][2][\"shape\"] == [2]\n        assert metadata[\"memory\"][\"add\"][2][\"size_bytes\"] == 2\n\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"lib0.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"lib1.c\"))\n\n    assert (\n        len(mod.ir_module_by_target) == 1\n    ), f\"expect 1 ir_model_by_target: {mod.ir_module_by_target!r}\"\n    for target, ir_mod in mod.ir_module_by_target.items():\n        assert int(tvm.runtime.ndarray.device(str(target)).device_type) == 1\n        with open(os.path.join(extract_dir, \"src\", \"tir-1.txt\")) as tir_f:\n            assert tir_f.read() == str(ir_mod)\n\n\n@tvm.testing.requires_micro\ndef test_export_multiple_operator_model_library_format():\n    target = tvm.target.target.micro(\"host\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        A = tvm.te.placeholder((2,), dtype=\"int8\")\n        B = tvm.te.placeholder((1,), dtype=\"int8\")\n        C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name=\"C\")\n        sched = tvm.te.create_schedule(C.op)\n        mod = tvm.build(\n            sched,\n            [A, B, C],\n            tvm.target.Target(target, target),\n            runtime=Runtime(\"crt\", {\"system-lib\": True}),\n            name=\"add\",\n        )\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    with pytest.raises(RuntimeError) as exc:\n        micro.export_model_library_format([mod, mod], mlf_tar_path)\n\n        assert str(exc.exception) == (\"Multiple operator is not supported.\")\n\n\ndef validate_graph_json(extract_dir, factory):\n    with open(\n        os.path.join(extract_dir, \"executor-config\", \"graph\", f\"{factory.libmod_name}.graph\")\n    ) as graph_f:\n        graph_json = graph_f.read()\n        assert graph_json == factory.graph_json\n\n        # Just check it parses and looks roughly right.\n        graph = json.loads(graph_json)\n        assert \"nodes\" in graph\n        assert len(graph[\"nodes\"]) == 4\n        assert \"attrs\" in graph\n\n\n@tvm.testing.requires_micro\n@pytest.mark.parametrize(\n    \"executor,runtime,should_generate_interface,json_constants_size_bytes\",\n    [\n        (Executor(\"graph\"), Runtime(\"crt\", {\"system-lib\": True}), False, 8),\n        (Executor(\"aot\", {\"link-params\": True}), Runtime(\"crt\"), False, 0),\n        (\n            Executor(\"aot\", {\"unpacked-api\": True, \"interface-api\": \"c\"}),\n            Runtime(\"crt\"),\n            True,\n            0,\n        ),\n    ],\n)\ndef test_export_model_library_format_c(\n    executor, runtime, should_generate_interface, json_constants_size_bytes\n):\n    target = tvm.target.target.micro(\"host\")\n    with utils.TempDirectory.set_keep_for_debug(True):\n        with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n            relay_mod = tvm.parser.fromtext(\n                \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), float32], %c : Tensor[(1, 2), float32]) {\n            %0 = cast(%a, dtype=\"float32\") + %b * %c;\n            %0\n            }\"\"\"\n            )\n            factory = tvm.relay.build(\n                relay_mod,\n                target,\n                executor=executor,\n                runtime=runtime,\n                mod_name=\"add\",\n                params={\"c\": np.array([[2.0, 4.0]], dtype=\"float32\")},\n            )\n\n        temp_dir = utils.tempdir()\n        mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n        micro.export_model_library_format(factory, mlf_tar_path)\n        tf = tarfile.open(mlf_tar_path)\n\n        extract_dir = temp_dir.relpath(\"extract\")\n        os.mkdir(extract_dir)\n        tf.extractall(extract_dir)\n\n        with open(os.path.join(extract_dir, \"metadata.json\")) as json_f:\n            metadata = json.load(json_f)\n            module_name = factory.libmod_name\n            assert metadata[\"version\"] == _GENERATED_VERSION\n            assert metadata[\"modules\"][module_name][\"model_name\"] == \"add\"\n            export_datetime = datetime.datetime.strptime(\n                metadata[\"modules\"][module_name][\"export_datetime\"], \"%Y-%m-%d %H:%M:%SZ\"\n            )\n            assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5)\n            assert metadata[\"modules\"][module_name][\"target\"] == [str(target)]\n            if executor.name == \"graph\":\n                assert metadata[\"modules\"][module_name][\"memory\"][\"sids\"] == [\n                    {\"storage_id\": 0, \"size_bytes\": 2, \"input_binding\": \"a\"},\n                    {\"storage_id\": 1, \"size_bytes\": 8, \"input_binding\": \"b\"},\n                    {\"storage_id\": 2, \"size_bytes\": 8, \"input_binding\": \"p0\"},\n                    {\"storage_id\": 3, \"size_bytes\": 8},\n                ]\n            assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"main\"] == [\n                {\n                    \"constants_size_bytes\": json_constants_size_bytes,\n                    \"device\": 1,\n                    \"io_size_bytes\": 18,\n                    \"workspace_size_bytes\": 0,\n                }\n            ]\n            assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n                \"workspace\"\n            ] == [{\"device\": 1, \"workspace_size_bytes\": 0}]\n            assert (\n                \"fused_cast_multiply_add\"\n                in metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n                    \"function_name\"\n                ]\n            )\n\n        assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"add_lib0.c\"))\n        assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"add_lib1.c\"))\n        assert should_generate_interface == os.path.exists(\n            os.path.join(extract_dir, \"codegen\", \"host\", \"include\", \"tvmgen_add.h\")\n        )\n\n        if executor.name == \"graph\":\n            validate_graph_json(extract_dir, factory)\n\n        with open(os.path.join(extract_dir, \"src\", f\"{module_name}.relay\")) as relay_f:\n            assert relay_f.read() == str(relay_mod)\n\n        with open(os.path.join(extract_dir, \"parameters\", \"add.params\"), \"rb\") as params_f:\n            params = tvm.relay.load_param_dict(params_f.read())\n            if json_constants_size_bytes != 0:\n                assert \"p0\" in params\n            else:\n                assert len(params) == 0\n\n\n@tvm.testing.requires_micro\ndef test_export_model_library_format_llvm():\n    with utils.TempDirectory.set_keep_for_debug(True):\n        target = tvm.target.target.micro(\"host\")\n        assert str(target)[:2] == \"c \"\n        target = tvm.target.Target(\"llvm \" + str(target)[2:])\n        with tvm.transform.PassContext(opt_level=3):\n            relay_mod = tvm.parser.fromtext(\n                \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), float32], %c : Tensor[(1, 2), float32]) {\n            %0 = cast(%a, dtype=\"float32\") + %b * %c;\n            %0\n            }\"\"\"\n            )\n            factory = tvm.relay.build(\n                relay_mod,\n                target,\n                runtime=Runtime(\"crt\", {\"system-lib\": True}),\n                mod_name=\"add\",\n                params={\"c\": np.array([[2.0, 4.0]], dtype=\"float32\")},\n            )\n\n        temp_dir = utils.tempdir()\n        mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n        micro.export_model_library_format(factory, mlf_tar_path)\n        tf = tarfile.open(mlf_tar_path)\n\n        extract_dir = temp_dir.relpath(\"extract\")\n        os.mkdir(extract_dir)\n        tf.extractall(extract_dir)\n\n        with open(os.path.join(extract_dir, \"metadata.json\")) as json_f:\n            metadata = json.load(json_f)\n            module_name = factory.libmod_name\n            assert metadata[\"version\"] == _GENERATED_VERSION\n            assert metadata[\"modules\"][module_name][\"model_name\"] == \"add\"\n            export_datetime = datetime.datetime.strptime(\n                metadata[\"modules\"][module_name][\"export_datetime\"], \"%Y-%m-%d %H:%M:%SZ\"\n            )\n            assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5)\n            assert metadata[\"modules\"][module_name][\"target\"] == [str(target)]\n            assert metadata[\"modules\"][module_name][\"memory\"][\"sids\"] == [\n                {\"storage_id\": 0, \"size_bytes\": 2, \"input_binding\": \"a\"},\n                {\"storage_id\": 1, \"size_bytes\": 8, \"input_binding\": \"b\"},\n                {\"storage_id\": 2, \"size_bytes\": 8, \"input_binding\": \"p0\"},\n                {\"storage_id\": 3, \"size_bytes\": 8},\n            ]\n            assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"main\"] == [\n                {\n                    \"constants_size_bytes\": 8,\n                    \"device\": 1,\n                    \"io_size_bytes\": 18,\n                    \"workspace_size_bytes\": 0,\n                }\n            ]\n            assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n                \"workspace\"\n            ] == [{\"device\": 1, \"workspace_size_bytes\": 0}]\n            assert (\n                \"fused_cast_multiply_add\"\n                in metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n                    \"function_name\"\n                ]\n            )\n\n        assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"lib\", \"add_lib0.o\"))\n\n        validate_graph_json(extract_dir, factory)\n\n        with open(os.path.join(extract_dir, \"src\", f\"{module_name}.relay\")) as relay_f:\n            assert relay_f.read() == str(relay_mod)\n\n        with open(os.path.join(extract_dir, \"parameters\", \"add.params\"), \"rb\") as params_f:\n            params = tvm.relay.load_param_dict(params_f.read())\n            assert \"p0\" in params\n\n\n@tvm.testing.requires_micro\n@pytest.mark.parametrize(\n    \"executor,runtime\",\n    [(Executor(\"graph\"), Runtime(\"crt\", {\"system-lib\": True})), (Executor(\"aot\"), Runtime(\"crt\"))],\n)\ndef test_export_model_library_format_workspace(executor, runtime):\n    target = tvm.target.target.micro(\"host\")\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        relay_mod = tvm.parser.fromtext(\n            \"\"\"\n            #[version = \"0.0.5\"]\n            def @main(%p0: Tensor[(1, 56, 56, 128), int16], %p1: Tensor[(3, 3, 128, 1), int16], %p2: Tensor[(1, 1, 1, 128), int32]){\n              %0 = nn.conv2d(%p0, %p1, padding=[1, 1, 1, 1], groups=128, channels=128, kernel_size=[3, 3], data_layout=\"NHWC\", kernel_layout=\"HWOI\", out_dtype=\"int32\") /* ty=Tensor[(1, 56, 56, 128), int32] */;\n              %1 = add(%0, %p2) /* ty=Tensor[(1, 56, 56, 128), int32] */;\n              %2 = fixed_point_multiply(%1, multiplier=2080045879, shift=-4) /* ty=Tensor[(1, 56, 56, 128), int32] */;\n              %3 = clip(%2, a_min=0f, a_max=255f) /* ty=Tensor[(1, 56, 56, 128), int32] */;\n              cast(%3, dtype=\"uint8\") /* ty=Tensor[(1, 56, 56, 128), uint8] */\n            }\n            \"\"\"\n        )\n        factory = tvm.relay.build(\n            relay_mod,\n            target,\n            executor=executor,\n            runtime=runtime,\n            mod_name=\"qnn_conv2d\",\n        )\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    micro.export_model_library_format(factory, mlf_tar_path)\n    tf = tarfile.open(mlf_tar_path)\n\n    extract_dir = temp_dir.relpath(\"extract\")\n    os.mkdir(extract_dir)\n    tf.extractall(extract_dir)\n\n    with open(os.path.join(extract_dir, \"metadata.json\")) as json_f:\n        metadata = json.load(json_f)\n        module_name = factory.libmod_name\n        assert metadata[\"version\"] == _GENERATED_VERSION\n        assert metadata[\"modules\"][module_name][\"model_name\"] == \"qnn_conv2d\"\n        export_datetime = datetime.datetime.strptime(\n            metadata[\"modules\"][module_name][\"export_datetime\"], \"%Y-%m-%d %H:%M:%SZ\"\n        )\n        assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5)\n        assert metadata[\"modules\"][module_name][\"target\"] == [str(target)]\n        assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"main\"] == [\n            {\n                \"constants_size_bytes\": 0,\n                \"device\": 1,\n                \"io_size_bytes\": 1207040,\n                \"workspace_size_bytes\": 2466816,\n            }\n        ]\n        assert metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n            \"workspace\"\n        ] == [{\"device\": 1, \"workspace_size_bytes\": 2466816}]\n        assert (\n            \"fused_nn_conv2d_add_fixed_point_multiply_clip_cast\"\n            in metadata[\"modules\"][module_name][\"memory\"][\"functions\"][\"operator_functions\"][0][\n                \"function_name\"\n            ]\n        )\n\n\n@tvm.testing.requires_micro\ndef test_export_non_dso_exportable():\n    module = tvm.support.FrontendTestModule()\n\n    temp_dir = utils.tempdir()\n\n    with pytest.raises(micro.UnsupportedInModelLibraryFormatError) as exc:\n        model_library_format._populate_codegen_dir([module], temp_dir.relpath(\"codegen\"))\n\n        assert str(exc.exception) == (\n            \"Don't know how to export non-c or non-llvm modules; found: ffi_testing\"\n        )\n\n\n@tvm.testing.requires_micro\ndef test_export_byoc_c_module():\n    \"\"\"Test BYOC flow when it produces DSO-exportable modules.\n\n    NOTE the general BYOC flow is not fully supported by Model Library Format right now.\n    \"\"\"\n    x = tvm.relay.var(\"x\", shape=(10, 10))\n    w0 = tvm.relay.var(\"w0\", shape=(10, 10))\n    w1 = tvm.relay.var(\"w1\", shape=(10, 10))\n    w2 = tvm.relay.var(\"w2\", shape=(10, 10))\n    w3 = tvm.relay.var(\"w3\", shape=(10, 10))\n    w4 = tvm.relay.var(\"w4\", shape=(10, 10))\n    w5 = tvm.relay.var(\"w5\", shape=(10, 10))\n    w6 = tvm.relay.var(\"w6\", shape=(10, 10))\n    w7 = tvm.relay.var(\"w7\", shape=(10, 10))\n\n    # C compiler\n    z0 = tvm.relay.add(x, w0)\n    p0 = tvm.relay.subtract(z0, w1)\n    q0 = tvm.relay.multiply(p0, w2)\n\n    z1 = tvm.relay.add(x, w3)\n    p1 = tvm.relay.subtract(z1, w4)\n    q1 = tvm.relay.multiply(p1, w5)\n\n    # Other parts on TVM\n    z2 = tvm.relay.add(x, w6)\n    q2 = tvm.relay.subtract(z2, w7)\n\n    r = tvm.relay.concatenate((q0, q1, q2), axis=0)\n    f = tvm.relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r)\n    mod = tvm.IRModule()\n    ann = byoc.CcompilerAnnotator()\n    mod[\"main\"] = ann.visit(f)\n    mod = tvm.relay.transform.PartitionGraph(\"mod_name\")(mod)\n    mod = tvm.relay.transform.InferType()(mod)\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory = tvm.relay.build(mod, tvm.target.target.micro(\"host\"), runtime=Runtime(\"crt\"))\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    micro.export_model_library_format(factory, mlf_tar_path)\n\n    with tarfile.open(mlf_tar_path, \"r:*\") as tf:\n        tar_members = [ti.name for ti in tf.getmembers()]\n        print(\"tar members\", tar_members)\n        assert \"./metadata.json\" in tar_members\n        with tf.extractfile(\"./metadata.json\") as f:\n            metadata = json.load(f)\n        main_md = metadata[\"modules\"][factory.libmod_name][\"memory\"][\"functions\"][\"main\"]\n        if platform.architecture()[0] == \"64bit\":\n            assert main_md == [\n                {\n                    \"constants_size_bytes\": 0,\n                    \"device\": 1,\n                    \"io_size_bytes\": 4800,\n                    \"workspace_size_bytes\": 1200,\n                }\n            ]\n        else:\n            assert main_md == [\n                {\n                    \"constants_size_bytes\": 0,\n                    \"device\": 1,\n                    \"io_size_bytes\": 4800,\n                    \"workspace_size_bytes\": 1200,\n                }\n            ]\n\n\n@tvm.testing.requires_micro\ndef test_multiple_relay_modules_same_module_name():\n    mod = get_conv2d_relay_module()\n\n    executor = Executor(\"graph\")\n    runtime = Runtime(\"crt\")\n    target = tvm.target.target.micro(\"host\")\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod\")\n        factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod\")\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    with pytest.raises(AssertionError, match=\"Multiple modules should have unique names\"):\n        micro.export_model_library_format([factory1, factory2], mlf_tar_path)\n\n\n@tvm.testing.requires_micro\ndef test_multiple_relay_modules_graph():\n    mod = get_conv2d_relay_module()\n\n    executor = Executor(\"graph\")\n    runtime = Runtime(\"crt\")\n    target = tvm.target.target.micro(\"host\")\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod1\")\n        factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod2\")\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n    micro.export_model_library_format([factory1, factory2], mlf_tar_path)\n\n    with tarfile.open(mlf_tar_path, \"r:*\") as tf:\n        tar_members = [ti.name for ti in tf.getmembers()]\n        print(\"tar members\", tar_members)\n        assert \"./metadata.json\" in tar_members\n        assert \"./codegen/host/src/mod1_lib0.c\" in tar_members\n        assert \"./codegen/host/src/mod2_lib0.c\" in tar_members\n\n        with tf.extractfile(\"./metadata.json\") as f:\n            metadata = json.load(f)\n        mod2_main_md = metadata[\"modules\"][\"mod2\"][\"memory\"][\"functions\"][\"main\"]\n        assert mod2_main_md == [\n            {\n                \"constants_size_bytes\": 0,\n                \"device\": 1,\n                \"io_size_bytes\": 143960,\n                \"workspace_size_bytes\": 158088,\n            }\n        ]\n        assert metadata[\"modules\"][\"mod1\"][\"model_name\"] == \"mod1\"\n        assert metadata[\"modules\"][\"mod2\"][\"model_name\"] == \"mod2\"\n\n\n@tvm.testing.requires_micro\ndef test_multiple_relay_modules_c():\n    mod = get_conv2d_relay_module()\n\n    executor = Executor(\"aot\", {\"unpacked-api\": True, \"interface-api\": \"c\"})\n    runtime = Runtime(\"crt\")\n    target = tvm.target.target.micro(\"host\")\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod1\")\n        factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name=\"mod2\")\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    micro.export_model_library_format([factory1, factory2], mlf_tar_path)\n\n    tf = tarfile.open(mlf_tar_path)\n\n    extract_dir = temp_dir.relpath(\"extract\")\n    os.mkdir(extract_dir)\n    tf.extractall(extract_dir)\n\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod1_lib0.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod1_lib1.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod2_lib0.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod2_lib1.c\"))\n\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"include\", \"tvmgen_mod1.h\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"include\", \"tvmgen_mod2.h\"))\n\n    # check CRT runtime directory\n    assert os.path.exists(os.path.join(extract_dir, \"runtime\"))\n\n\n@tvm.testing.requires_micro\ndef test_multiple_relay_modules_aot_graph():\n    mod = get_conv2d_relay_module()\n\n    executor1 = Executor(\"graph\")\n    executor2 = Executor(\"aot\", {\"unpacked-api\": True, \"interface-api\": \"c\"})\n    runtime = Runtime(\"crt\")\n    target = tvm.target.target.micro(\"host\")\n\n    with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n        factory1 = tvm.relay.build(\n            mod, target, runtime=runtime, executor=executor1, mod_name=\"mod1\"\n        )\n        factory2 = tvm.relay.build(\n            mod, target, runtime=runtime, executor=executor2, mod_name=\"mod2\"\n        )\n\n    temp_dir = utils.tempdir()\n    mlf_tar_path = temp_dir.relpath(\"lib.tar\")\n\n    micro.export_model_library_format([factory1, factory2], mlf_tar_path)\n\n    tf = tarfile.open(mlf_tar_path)\n    extract_dir = temp_dir.relpath(\"extract\")\n    os.mkdir(extract_dir)\n    tf.extractall(extract_dir)\n\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod1_lib0.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod1_lib1.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod1_lib2.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod2_lib0.c\"))\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"src\", \"mod2_lib1.c\"))\n\n    assert os.path.exists(os.path.join(extract_dir, \"codegen\", \"host\", \"include\", \"tvmgen_mod2.h\"))\n\n    with open(os.path.join(extract_dir, \"metadata.json\")) as f:\n        metadata = json.load(f)\n\n    assert metadata[\"modules\"][\"mod1\"][\"executors\"] == [\"graph\"]\n    assert metadata[\"modules\"][\"mod2\"][\"executors\"] == [\"aot\"]\n    assert metadata[\"version\"] == _GENERATED_VERSION\n\n\nif __name__ == \"__main__\":\n    sys.exit(pytest.main([__file__] + sys.argv[1:]))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_micro_project_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport collections\nimport io\nimport json\nimport sys\nimport unittest\nfrom unittest import mock\n\nimport pytest\n\nimport tvm\nimport tvm.testing\n\n\n# Implementing as a fixture so that the tvm.micro import doesn't occur\n# until fixture setup time.  This is necessary for pytest's collection\n# phase to work when USE_MICRO=OFF, while still explicitly listing the\n# tests as skipped.\n@tvm.testing.fixture\ndef BaseTestHandler():\n    from tvm.micro import project_api\n\n    class BaseTestHandler_Impl(project_api.server.ProjectAPIHandler):\n\n        DEFAULT_TEST_SERVER_INFO = project_api.server.ServerInfo(\n            platform_name=\"platform_name\",\n            is_template=True,\n            model_library_format_path=\"./model-library-format-path.sh\",\n            project_options=[\n                project_api.server.ProjectOption(\n                    name=\"foo\", optional=[\"build\"], type=\"bool\", help=\"Option foo\"\n                ),\n                project_api.server.ProjectOption(\n                    name=\"bar\",\n                    required=[\"generate_project\"],\n                    type=\"str\",\n                    choices=[\"qux\"],\n                    help=\"Option bar\",\n                ),\n            ],\n        )\n\n        def server_info_query(self, tvm_version):\n            return self.DEFAULT_TEST_SERVER_INFO\n\n        def generate_project(self, model_library_format_path, crt_path, project_path, options):\n            assert False, \"generate_project is not implemented for this test\"\n\n        def build(self, options):\n            assert False, \"build is not implemented for this test\"\n\n        def flash(self, options):\n            assert False, \"flash is not implemented for this test\"\n\n        def open_transport(self, options):\n            assert False, \"open_transport is not implemented for this test\"\n\n        def close_transport(self, options):\n            assert False, \"open_transport is not implemented for this test\"\n\n        def read_transport(self, n, timeout_sec):\n            assert False, \"read_transport is not implemented for this test\"\n\n        def write_transport(self, data, timeout_sec):\n            assert False, \"write_transport is not implemented for this test\"\n\n    return BaseTestHandler_Impl\n\n\nclass Transport:\n    def readable(self):\n        return True\n\n    def writable(self):\n        return True\n\n    def seekable(self):\n        return False\n\n    closed = False\n\n    def __init__(self):\n        self.data = bytearray()\n        self.rpos = 0\n\n        self.items = []\n\n    def read(self, size=-1):\n        to_read = len(self.data) - self.rpos\n        if size != -1:\n            to_read = min(size, to_read)\n\n        rpos = self.rpos\n        self.rpos += to_read\n        return self.data[rpos : self.rpos]\n\n    def write(self, data):\n        self.data.extend(data)\n\n\nclass ClientServerFixture:\n    def __init__(self, handler):\n        from tvm.micro import project_api\n\n        self.handler = handler\n        self.client_to_server = Transport()\n        self.server_to_client = Transport()\n\n        self.server = project_api.server.ProjectAPIServer(\n            self.client_to_server, self.server_to_client, handler\n        )\n        self.client = project_api.client.ProjectAPIClient(\n            self.server_to_client,\n            self.client_to_server,\n            testonly_did_write_request=self._process_server_request,\n        )\n\n        self.expect_failure = False\n\n    def _process_server_request(self):\n        assert self.server.serve_one_request() == (\n            not self.expect_failure\n        ), \"Server failed to process request\"\n\n\n@tvm.testing.requires_micro\ndef test_server_info_query(BaseTestHandler):\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    # Examine reply explicitly because these are the defaults for all derivative test cases.\n    reply = fixture.client.server_info_query(tvm.__version__)\n    assert reply[\"protocol_version\"] == 1\n    assert reply[\"platform_name\"] == \"platform_name\"\n    assert reply[\"is_template\"] == True\n    assert reply[\"model_library_format_path\"] == \"./model-library-format-path.sh\"\n    assert reply[\"project_options\"] == [\n        {\n            \"name\": \"foo\",\n            \"choices\": None,\n            \"default\": None,\n            \"type\": \"bool\",\n            \"required\": None,\n            \"optional\": [\"build\"],\n            \"help\": \"Option foo\",\n        },\n        {\n            \"name\": \"bar\",\n            \"choices\": [\"qux\"],\n            \"default\": None,\n            \"type\": \"str\",\n            \"required\": [\"generate_project\"],\n            \"optional\": None,\n            \"help\": \"Option bar\",\n        },\n    ]\n\n\n@tvm.testing.requires_micro\ndef test_server_info_query_wrong_tvm_version(BaseTestHandler):\n    from tvm.micro import project_api\n\n    def server_info_query(tvm_version):\n        raise project_api.server.UnsupportedTVMVersionError()\n\n    with mock.patch.object(BaseTestHandler, \"server_info_query\", side_effect=server_info_query):\n        fixture = ClientServerFixture(BaseTestHandler())\n        with pytest.raises(project_api.server.UnsupportedTVMVersionError) as exc_info:\n            fixture.client.server_info_query(tvm.__version__)\n\n        assert \"UnsupportedTVMVersionError\" in str(exc_info.value)\n\n\n@tvm.testing.requires_micro\ndef test_server_info_query_wrong_protocol_version(BaseTestHandler):\n    from tvm.micro import project_api\n\n    ServerInfoProtocol = collections.namedtuple(\n        \"ServerInfoProtocol\", list(project_api.server.ServerInfo._fields) + [\"protocol_version\"]\n    )\n\n    def server_info_query(tvm_version):\n        return ServerInfoProtocol(\n            protocol_version=0, **BaseTestHandler.DEFAULT_TEST_SERVER_INFO._asdict()\n        )\n\n    with mock.patch.object(BaseTestHandler, \"server_info_query\", side_effect=server_info_query):\n        fixture = ClientServerFixture(BaseTestHandler())\n        with pytest.raises(project_api.client.UnsupportedProtocolVersionError) as exc_info:\n            fixture.client.server_info_query(tvm.__version__)\n\n        assert \"microTVM API Server supports protocol version 0; want 1\" in str(exc_info.value)\n\n\n@tvm.testing.requires_micro\ndef test_base_test_handler(BaseTestHandler):\n    \"\"\"All methods should raise AssertionError on BaseTestHandler.\"\"\"\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    for method in dir(fixture.handler):\n        if method.startswith(\"_\") or not callable(method) or method == \"server_info_query\":\n            continue\n\n        with self.assertThrows(AssertionError) as exc_info:\n            getattr(fixture.client, method)()\n\n            assert (exc_info.exception) == f\"{method} is not implemented for this test\"\n\n\n@tvm.testing.requires_micro\ndef test_build(BaseTestHandler):\n    with mock.patch.object(BaseTestHandler, \"build\", return_value=None) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        fixture.client.build(options={\"bar\": \"baz\"})\n\n        fixture.handler.build.assert_called_once_with(options={\"bar\": \"baz\"})\n\n\n@tvm.testing.requires_micro\ndef test_flash(BaseTestHandler):\n    with mock.patch.object(BaseTestHandler, \"flash\", return_value=None) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        fixture.client.flash(options={\"bar\": \"baz\"})\n        fixture.handler.flash.assert_called_once_with(options={\"bar\": \"baz\"})\n\n\n@tvm.testing.requires_micro\ndef test_open_transport(BaseTestHandler):\n    from tvm.micro import project_api\n\n    timeouts = project_api.server.TransportTimeouts(\n        session_start_retry_timeout_sec=1.0,\n        session_start_timeout_sec=2.0,\n        session_established_timeout_sec=3.0,\n    )\n\n    with mock.patch.object(BaseTestHandler, \"open_transport\", return_value=timeouts) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        assert fixture.client.open_transport(options={\"bar\": \"baz\"}) == {\n            \"timeouts\": dict(timeouts._asdict())\n        }\n        fixture.handler.open_transport.assert_called_once_with({\"bar\": \"baz\"})\n\n\n@tvm.testing.requires_micro\ndef test_close_transport(BaseTestHandler):\n    with mock.patch.object(BaseTestHandler, \"close_transport\", return_value=None) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        fixture.client.close_transport()\n        fixture.handler.close_transport.assert_called_once_with()\n\n\n@tvm.testing.requires_micro\ndef test_read_transport(BaseTestHandler):\n    from tvm.micro import project_api\n\n    with mock.patch.object(BaseTestHandler, \"read_transport\", return_value=b\"foo\\x1b\") as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        assert fixture.client.read_transport(128, timeout_sec=5.0) == {\"data\": b\"foo\\x1b\"}\n\n        fixture.handler.read_transport.assert_called_with(128, 5.0)\n\n        fixture.handler.read_transport.side_effect = project_api.server.IoTimeoutError\n        with pytest.raises(project_api.server.IoTimeoutError) as exc_info:\n            fixture.client.read_transport(256, timeout_sec=10.0)\n\n        fixture.handler.read_transport.assert_called_with(256, 10.0)\n\n        fixture.handler.read_transport.side_effect = project_api.server.TransportClosedError\n        with pytest.raises(project_api.server.TransportClosedError) as exc_info:\n            fixture.client.read_transport(512, timeout_sec=15.0)\n\n        fixture.handler.read_transport.assert_called_with(512, 15.0)\n\n        assert fixture.handler.read_transport.call_count == 3\n\n\n@tvm.testing.requires_micro\ndef test_write_transport(BaseTestHandler):\n    from tvm.micro import project_api\n\n    with mock.patch.object(BaseTestHandler, \"write_transport\", return_value=None) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        assert fixture.client.write_transport(b\"foo\", timeout_sec=5.0) is None\n        fixture.handler.write_transport.assert_called_with(b\"foo\", 5.0)\n\n        fixture.handler.write_transport.side_effect = project_api.server.IoTimeoutError\n        with pytest.raises(project_api.server.IoTimeoutError) as exc_info:\n            fixture.client.write_transport(b\"bar\", timeout_sec=10.0)\n\n        fixture.handler.write_transport.assert_called_with(b\"bar\", 10.0)\n\n        fixture.handler.write_transport.side_effect = project_api.server.TransportClosedError\n        with pytest.raises(project_api.server.TransportClosedError) as exc_info:\n            fixture.client.write_transport(b\"baz\", timeout_sec=15.0)\n\n        fixture.handler.write_transport.assert_called_with(b\"baz\", 15.0)\n\n        assert fixture.handler.write_transport.call_count == 3\n\n\nclass ProjectAPITestError(Exception):\n    \"\"\"An error raised in test.\"\"\"\n\n\n@tvm.testing.requires_micro\ndef test_method_raises_error(BaseTestHandler):\n    from tvm.micro import project_api\n\n    with mock.patch.object(\n        BaseTestHandler, \"close_transport\", side_effect=ProjectAPITestError\n    ) as patch:\n        fixture = ClientServerFixture(BaseTestHandler())\n        with pytest.raises(project_api.server.ServerError) as exc_info:\n            fixture.client.close_transport()\n\n        fixture.handler.close_transport.assert_called_once_with()\n        assert \"ProjectAPITestError\" in str(exc_info.value)\n\n\n@tvm.testing.requires_micro\ndef test_method_not_found(BaseTestHandler):\n    from tvm.micro import project_api\n\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"invalid_method\", {\"bar\": None})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.METHOD_NOT_FOUND\n\n\n@tvm.testing.requires_micro\ndef test_extra_param(BaseTestHandler):\n    from tvm.micro import project_api\n\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    # test one with has_preprocssing and one without\n    assert hasattr(fixture.server, \"_dispatch_build\") == False\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"build\", {\"invalid_param_name\": None, \"options\": {}})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS\n    assert \"build: extra parameters: invalid_param_name\" in str(exc_info.value)\n\n    assert hasattr(fixture.server, \"_dispatch_open_transport\") == True\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"open_transport\", {\"invalid_param_name\": None, \"options\": {}})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS\n    assert \"open_transport: extra parameters: invalid_param_name\" in str(exc_info.value)\n\n\n@tvm.testing.requires_micro\ndef test_missing_param(BaseTestHandler):\n    from tvm.micro import project_api\n\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    # test one with has_preprocssing and one without\n    assert hasattr(fixture.server, \"_dispatch_build\") == False\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"build\", {})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS\n    assert \"build: parameter options not given\" in str(exc_info.value)\n\n    assert hasattr(fixture.server, \"_dispatch_open_transport\") == True\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"open_transport\", {})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS\n    assert \"open_transport: parameter options not given\" in str(exc_info.value)\n\n\n@tvm.testing.requires_micro\ndef test_incorrect_param_type(BaseTestHandler):\n    from tvm.micro import project_api\n\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    # The error message given at the JSON-RPC server level doesn't make sense when preprocessing is\n    # used. Only test without preprocessing here.\n    assert hasattr(fixture.server, \"_dispatch_build\") == False\n    with pytest.raises(project_api.server.JSONRPCError) as exc_info:\n        fixture.client._request_reply(\"build\", {\"options\": None})\n\n    assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS\n    assert \"build: parameter options: want <class 'dict'>, got <class 'NoneType'>\" in str(\n        exc_info.value\n    )\n\n\n@tvm.testing.requires_micro\ndef test_invalid_request(BaseTestHandler):\n    from tvm.micro import project_api\n\n    fixture = ClientServerFixture(BaseTestHandler())\n\n    # Invalid JSON does not get a reply.\n    fixture.client_to_server.write(b\"foobar\\n\")\n    assert fixture.server.serve_one_request() == False\n    assert fixture.server_to_client.read() == b\"\"\n\n    # EOF causes a clean return\n    assert fixture.server.serve_one_request() == False\n    assert fixture.server_to_client.read() == b\"\"\n\n    def _request_reply(request):\n        fixture.client_to_server.write(request + b\"\\n\")\n        assert fixture.server.serve_one_request() == False\n        return json.loads(fixture.server_to_client.read())\n\n    # Parseable JSON with the wrong schema gets a reply.\n    assert _request_reply(b\"1\") == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": \"request: want dict; got 1\",\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n    # Incorrect JSON-RPC spec version.\n    assert _request_reply(b'{\"jsonrpc\": 1.0}') == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": 'request[\"jsonrpc\"]: want \"2.0\"; got 1.0',\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n    # Method not a str\n    assert _request_reply(b'{\"jsonrpc\": \"2.0\", \"method\": 123}') == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": 'request[\"method\"]: want str; got 123',\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n    # Method name has invalid characters\n    assert _request_reply(b'{\"jsonrpc\": \"2.0\", \"method\": \"bar!\"}') == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": \"request[\\\"method\\\"]: should match regex ^[a-zA-Z0-9_]+$; got 'bar!'\",\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n    # params not a dict\n    assert _request_reply(b'{\"jsonrpc\": \"2.0\", \"method\": \"bar\", \"params\": 123}') == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": \"request[\\\"params\\\"]: want dict; got <class 'int'>\",\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n    # id not valid\n    assert _request_reply(b'{\"jsonrpc\": \"2.0\", \"method\": \"bar\", \"params\": {}, \"id\": {}}') == {\n        \"error\": {\n            \"code\": project_api.server.ErrorCode.INVALID_REQUEST,\n            \"data\": None,\n            \"message\": 'request[\"id\"]: want str, number, null; got {}',\n        },\n        \"id\": None,\n        \"jsonrpc\": \"2.0\",\n    }\n\n\n@tvm.testing.requires_micro\ndef test_default_project_options():\n    from tvm.micro import project_api\n\n    default_options = project_api.server.default_project_options()\n    names = []\n    for option in default_options:\n        names.append(option.name)\n        if option.name == \"verbose\":\n            assert \"generate_project\" in option.optional\n        if option.name in [\"project_type\", \"board\"]:\n            assert \"generate_project\" in option.required\n        if option.name == \"warning_as_error\":\n            assert \"generate_project\" in option.optional\n\n    for name in [\"verbose\", \"project_type\", \"board\", \"cmsis_path\", \"warning_as_error\"]:\n        assert name in names\n\n\n@tvm.testing.requires_micro\ndef test_modified_project_options():\n    from tvm.micro import project_api\n\n    modified_options = project_api.server.default_project_options(\n        verbose={\"optional\": [\"flash\"], \"required\": [\"build\"]},\n        board={\"choices\": [\"board1\", \"board2\"]},\n    )\n    for option in modified_options:\n        if option.name == \"verbose\":\n            assert option.optional == [\"flash\"]\n            assert option.required == [\"build\"]\n        if option.name == \"board\":\n            assert option.choices == [\"board1\", \"board2\"]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_micro_transport.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tests for common micro transports.\"\"\"\n\nimport logging\nimport sys\nimport unittest\n\nimport pytest\n\nimport tvm.testing\n\n\n# Implementing as a fixture so that the tvm.micro import doesn't occur\n# until fixture setup time.  This is necessary for pytest's collection\n# phase to work when USE_MICRO=OFF, while still explicitly listing the\n# tests as skipped.\n@tvm.testing.fixture\ndef transport():\n    import tvm.micro\n\n    class MockTransport_Impl(tvm.micro.transport.Transport):\n        def __init__(self):\n            self.exc = None\n            self.to_return = None\n\n        def _raise_or_return(self):\n            if self.exc is not None:\n                to_raise = self.exc\n                self.exc = None\n                raise to_raise\n            elif self.to_return is not None:\n                to_return = self.to_return\n                self.to_return = None\n                return to_return\n            else:\n                assert False, \"should not get here\"\n\n        def open(self):\n            pass\n\n        def close(self):\n            pass\n\n        def timeouts(self):\n            raise NotImplementedError()\n\n        def read(self, n, timeout_sec):\n            return self._raise_or_return()\n\n        def write(self, data, timeout_sec):\n            return self._raise_or_return()\n\n    return MockTransport_Impl()\n\n\n@tvm.testing.fixture\ndef transport_logger(transport):\n    logger = logging.getLogger(\"transport_logger_test\")\n    return tvm.micro.transport.TransportLogger(\"foo\", transport, logger=logger)\n\n\n@tvm.testing.fixture\ndef get_latest_log(caplog):\n    def inner():\n        return caplog.records[-1].getMessage()\n\n    with caplog.at_level(logging.INFO, \"transport_logger_test\"):\n        yield inner\n\n\n@tvm.testing.requires_micro\ndef test_open(transport_logger, get_latest_log):\n    transport_logger.open()\n    assert get_latest_log() == \"foo: opening transport\"\n\n\n@tvm.testing.requires_micro\ndef test_close(transport_logger, get_latest_log):\n    transport_logger.close()\n    assert get_latest_log() == \"foo: closing transport\"\n\n\n@tvm.testing.requires_micro\ndef test_read_normal(transport, transport_logger, get_latest_log):\n    transport.to_return = b\"data\"\n    transport_logger.read(23, 3.0)\n    assert get_latest_log() == (\n        \"foo: read { 3.00s}   23 B -> [  4 B]: 64 61 74 61\"\n        \"                                      data\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_read_multiline(transport, transport_logger, get_latest_log):\n    transport.to_return = b\"data\" * 6\n    transport_logger.read(23, 3.0)\n    assert get_latest_log() == (\n        \"foo: read { 3.00s}   23 B -> [ 24 B]:\\n\"\n        \"0000  64 61 74 61 64 61 74 61 64 61 74 61 64 61 74 61  datadatadatadata\\n\"\n        \"0010  64 61 74 61 64 61 74 61                          datadata\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_read_no_timeout_prints(transport, transport_logger, get_latest_log):\n    transport.to_return = b\"data\"\n    transport_logger.read(15, None)\n    assert get_latest_log() == (\n        \"foo: read { None }   15 B -> [  4 B]: 64 61 74 61\"\n        \"                                      data\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_read_io_timeout(transport, transport_logger, get_latest_log):\n    # IoTimeoutError includes the timeout value.\n    transport.exc = tvm.micro.transport.IoTimeoutError()\n    with pytest.raises(tvm.micro.transport.IoTimeoutError):\n        transport_logger.read(23, 0.0)\n\n    assert get_latest_log() == (\"foo: read { 0.00s}   23 B -> [IoTimeoutError  0.00s]\")\n\n\n@tvm.testing.requires_micro\ndef test_read_other_exception(transport, transport_logger, get_latest_log):\n    # Other exceptions are logged by name.\n    transport.exc = tvm.micro.transport.TransportClosedError()\n    with pytest.raises(tvm.micro.transport.TransportClosedError):\n        transport_logger.read(8, 0.0)\n\n    assert get_latest_log() == (\"foo: read { 0.00s}    8 B -> [err: TransportClosedError]\")\n\n\n@tvm.testing.requires_micro\ndef test_read_keyboard_interrupt(transport, transport_logger, get_latest_log):\n    # KeyboardInterrupt produces no log record.\n    transport.exc = KeyboardInterrupt()\n    with pytest.raises(KeyboardInterrupt):\n        transport_logger.read(8, 0.0)\n\n    with pytest.raises(IndexError):\n        get_latest_log()\n\n\n@tvm.testing.requires_micro\ndef test_write_normal(transport, transport_logger, get_latest_log):\n    transport.to_return = 3\n    transport_logger.write(b\"data\", 3.0)\n    assert get_latest_log() == (\n        \"foo: write { 3.00s}        <- [  4 B]: 64 61 74 61\"\n        \"                                      data\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_write_multiline(transport, transport_logger, get_latest_log):\n    # Normal log, multi-line data written.\n    transport.to_return = 20\n    transport_logger.write(b\"data\" * 6, 3.0)\n    assert get_latest_log() == (\n        \"foo: write { 3.00s}        <- [ 24 B]:\\n\"\n        \"0000  64 61 74 61 64 61 74 61 64 61 74 61 64 61 74 61  datadatadatadata\\n\"\n        \"0010  64 61 74 61 64 61 74 61                          datadata\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_write_no_timeout_prints(transport, transport_logger, get_latest_log):\n    transport.to_return = 3\n    transport_logger.write(b\"data\", None)\n    assert get_latest_log() == (\n        \"foo: write { None }        <- [  4 B]: 64 61 74 61\"\n        \"                                      data\"\n    )\n\n\n@tvm.testing.requires_micro\ndef test_write_io_timeout(transport, transport_logger, get_latest_log):\n    # IoTimeoutError includes the timeout value.\n    transport.exc = tvm.micro.transport.IoTimeoutError()\n    with pytest.raises(tvm.micro.transport.IoTimeoutError):\n        transport_logger.write(b\"data\", 0.0)\n\n    assert get_latest_log() == (\"foo: write { 0.00s}       <- [  4 B]: [IoTimeoutError  0.00s]\")\n\n\n@tvm.testing.requires_micro\ndef test_write_other_exception(transport, transport_logger, get_latest_log):\n    # Other exceptions are logged by name.\n    transport.exc = tvm.micro.transport.TransportClosedError()\n    with pytest.raises(tvm.micro.transport.TransportClosedError):\n        transport_logger.write(b\"data\", 0.0)\n\n    assert get_latest_log() == (\"foo: write { 0.00s}       <- [  4 B]: [err: TransportClosedError]\")\n\n\n@tvm.testing.requires_micro\ndef test_write_keyboard_interrupt(transport, transport_logger, get_latest_log):\n    # KeyboardInterrupt produces no log record.\n    transport.exc = KeyboardInterrupt()\n    with pytest.raises(KeyboardInterrupt):\n        transport_logger.write(b\"data\", 0.0)\n\n    with pytest.raises(IndexError):\n        get_latest_log()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_node_reflection.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nimport sys\nimport pytest\nfrom tvm import te\nimport numpy as np\n\n\ndef test_const_saveload_json():\n    # save load json\n    x = tvm.tir.const(1, \"int32\")\n    y = tvm.tir.const(10, \"int32\")\n    z = x + y\n    z = z + z\n    json_str = tvm.ir.save_json(z)\n    zz = tvm.ir.load_json(json_str)\n    tvm.ir.assert_structural_equal(zz, z, map_free_vars=True)\n\n\ndef _test_infinity_value(value, dtype):\n    x = tvm.tir.const(value, dtype)\n    json_str = tvm.ir.save_json(x)\n    tvm.ir.assert_structural_equal(x, tvm.ir.load_json(json_str))\n\n\ndef test_infinity_value():\n    _test_infinity_value(float(\"inf\"), \"float64\")\n    _test_infinity_value(float(\"-inf\"), \"float64\")\n    _test_infinity_value(float(\"inf\"), \"float32\")\n    _test_infinity_value(float(\"-inf\"), \"float32\")\n\n\ndef _test_minmax_value(value):\n    json_str = tvm.ir.save_json(value)\n    tvm.ir.assert_structural_equal(value, tvm.ir.load_json(json_str))\n\n\ndef test_minmax_value():\n    _test_minmax_value(tvm.tir.min_value(\"float32\"))\n    _test_minmax_value(tvm.tir.max_value(\"float32\"))\n\n\ndef test_make_smap():\n    # save load json\n    x = tvm.tir.const(1, \"int32\")\n    y = tvm.tir.const(10, \"int32\")\n    z = tvm.tir.Add(x, y)\n    smap = tvm.runtime.convert({\"z\": z, \"x\": x})\n    json_str = tvm.ir.save_json(tvm.runtime.convert([smap]))\n    arr = tvm.ir.load_json(json_str)\n    assert len(arr) == 1\n    assert arr[0][\"z\"].a == arr[0][\"x\"]\n    tvm.ir.assert_structural_equal(arr, [smap], map_free_vars=True)\n\n\ndef test_make_node():\n    x = tvm.ir.make_node(\"IntImm\", dtype=\"int32\", value=10, span=None)\n    assert isinstance(x, tvm.tir.IntImm)\n    assert x.value == 10\n    A = te.placeholder((10,), name=\"A\")\n    AA = tvm.ir.make_node(\n        \"Tensor\", shape=A.shape, dtype=A.dtype, op=A.op, value_index=A.value_index\n    )\n    assert AA.op == A.op\n    assert AA.value_index == A.value_index\n\n    y = tvm.ir.make_node(\"IntImm\", dtype=tvm.runtime.String(\"int32\"), value=10, span=None)\n\n\ndef test_make_sum():\n    A = te.placeholder((2, 10), name=\"A\")\n    k = te.reduce_axis((0, 10), \"k\")\n    B = te.compute((2,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n    json_str = tvm.ir.save_json(B)\n    BB = tvm.ir.load_json(json_str)\n    assert B.op.body[0].combiner is not None\n    assert BB.op.body[0].combiner is not None\n\n\ndef test_env_func():\n    @tvm.register_func(\"test.env_func\")\n    def test(x):\n        return x + 1\n\n    f = tvm.get_global_func(\"test.env_func\")\n    x = tvm.ir.EnvFunc.get(\"test.env_func\")\n    assert x.name == \"test.env_func\"\n    json_str = tvm.ir.save_json([x])\n    y = tvm.ir.load_json(json_str)[0]\n    assert y.name == x.name\n    assert y(1) == 2\n    assert y.func(1) == 2\n\n    x = tvm.ir.make_node(\"attrs.TestAttrs\", name=\"xx\", padding=(3, 4), func=y)\n    assert x.name == \"xx\"\n    assert x.padding[0].value == 3\n    assert x.padding[1].value == 4\n    assert x.axis == 10\n    x = tvm.ir.load_json(tvm.ir.save_json(x))\n    assert isinstance(x.func, tvm.ir.EnvFunc)\n    assert x.func(10) == 11\n\n\ndef test_string():\n    # non printable str, need to store by b64\n    s1 = tvm.runtime.String(\"xy\\x01z\")\n    s2 = tvm.ir.load_json(tvm.ir.save_json(s1))\n    tvm.ir.assert_structural_equal(s1, s2)\n\n    # printable str, need to store by repr_str\n    s1 = tvm.runtime.String(\"xyz\")\n    s2 = tvm.ir.load_json(tvm.ir.save_json(s1))\n    tvm.ir.assert_structural_equal(s1, s2)\n\n\ndef test_pass_config():\n    cfg = tvm.transform.PassContext(\n        opt_level=1,\n        config={\n            \"tir.UnrollLoop\": {\n                \"auto_max_step\": 10,\n            }\n        },\n    )\n    cfg.opt_level == 1\n\n    assert cfg.config[\"tir.UnrollLoop\"].auto_max_step == 10\n    # default option\n    assert cfg.config[\"tir.UnrollLoop\"].explicit_unroll == True\n\n    # schema checking for specific config key\n    with pytest.raises(AttributeError):\n        cfg = tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"invalid\": 1}})\n\n    # schema check for un-registered config\n    with pytest.raises(AttributeError):\n        cfg = tvm.transform.PassContext(config={\"inavlid-opt\": True})\n\n    # schema check for wrong type\n    with pytest.raises(AttributeError):\n        cfg = tvm.transform.PassContext(config={\"tir.UnrollLoop\": 1})\n\n\ndef test_dict():\n    x = tvm.tir.const(1)  # a class that has Python-defined methods\n    # instances should see the full class dict\n    assert set(dir(x.__class__)) <= set(dir(x))\n\n\ndef test_ndarray():\n    dev = tvm.cpu(0)\n    tvm_arr = tvm.nd.array(np.random.rand(4), device=dev)\n    tvm_arr2 = tvm.ir.load_json(tvm.ir.save_json(tvm_arr))\n    tvm.ir.assert_structural_equal(tvm_arr, tvm_arr2)\n    np.testing.assert_array_equal(tvm_arr.numpy(), tvm_arr2.numpy())\n\n\ndef test_ndarray_dict():\n    dev = tvm.cpu(0)\n    m1 = {\n        \"key1\": tvm.nd.array(np.random.rand(4), device=dev),\n        \"key2\": tvm.nd.array(np.random.rand(4), device=dev),\n    }\n    m2 = tvm.ir.load_json(tvm.ir.save_json(m1))\n    tvm.ir.assert_structural_equal(m1, m2)\n\n\ndef test_alloc_const():\n    dev = tvm.cpu(0)\n    dtype = \"float32\"\n    shape = (16,)\n    buf = tvm.tir.decl_buffer(shape, dtype)\n    np_data = np.random.rand(*shape).astype(dtype)\n    data = tvm.nd.array(np_data, device=dev)\n    body = tvm.tir.Evaluate(0)\n    alloc_const = tvm.tir.AllocateConst(buf.data, dtype, shape, data, body)\n    alloc_const2 = tvm.ir.load_json(tvm.ir.save_json(alloc_const))\n    tvm.ir.assert_structural_equal(alloc_const, alloc_const2)\n    np.testing.assert_array_equal(np_data, alloc_const2.data.numpy())\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_object_path.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport tvm\nfrom tvm.runtime import object_path\nfrom tvm.runtime.object_path import ObjectPath\n\n\ndef test_root_path():\n    root = ObjectPath.root()\n    assert isinstance(root, object_path.RootPath)\n    assert str(root) == \"<root>\"\n    assert len(root) == 1\n    assert root == ObjectPath.root()\n    assert root.parent is None\n\n\ndef test_path_attr():\n    path = ObjectPath.root().attr(\"foo\")\n    assert isinstance(path, object_path.AttributeAccessPath)\n    assert str(path) == \"<root>.foo\"\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\ndef test_path_attr_unknown():\n    path = ObjectPath.root().attr(None)\n    assert isinstance(path, object_path.UnknownAttributeAccessPath)\n    assert str(path) == \"<root>.<unknown attribute>\"\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\ndef test_path_array_index():\n    path = ObjectPath.root().array_index(2)\n    assert isinstance(path, object_path.ArrayIndexPath)\n    assert str(path) == \"<root>[2]\"\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\ndef test_path_missing_array_element():\n    path = ObjectPath.root().missing_array_element(2)\n    assert isinstance(path, object_path.MissingArrayElementPath)\n    assert str(path) == \"<root>[<missing element #2>]\"\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\ndef test_path_map_value():\n    path = ObjectPath.root().map_value(\"foo\")\n    assert isinstance(path, object_path.MapValuePath)\n    assert str(path) == '<root>[\"foo\"]'\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\ndef test_path_missing_map_entry():\n    path = ObjectPath.root().missing_map_entry()\n    assert isinstance(path, object_path.MissingMapEntryPath)\n    assert str(path) == \"<root>[<missing entry>]\"\n    assert len(path) == 2\n    assert path.parent == ObjectPath.root()\n\n\n@pytest.mark.parametrize(\n    \"a, b, expected\",\n    [\n        (ObjectPath.root(), ObjectPath.root(), True),\n        (ObjectPath.root(), ObjectPath.root().attr(\"foo\"), True),\n        (ObjectPath.root().attr(\"foo\"), ObjectPath.root(), False),\n        (ObjectPath.root().attr(\"foo\"), ObjectPath.root().attr(\"foo\"), True),\n        (ObjectPath.root().attr(\"bar\"), ObjectPath.root().attr(\"foo\"), False),\n        (ObjectPath.root().attr(\"foo\"), ObjectPath.root().attr(\"foo\").array_index(2), True),\n        (ObjectPath.root().attr(\"foo\").array_index(2), ObjectPath.root().attr(\"foo\"), False),\n        (ObjectPath.root().attr(\"foo\"), ObjectPath.root().attr(\"bar\").array_index(2), False),\n    ],\n)\ndef test_path_is_prefix_of(a, b, expected):\n    assert a.is_prefix_of(b) == expected\n\n\npaths_for_equality_test = [\n    ObjectPath.root(),\n    ObjectPath.root().attr(\"foo\"),\n    ObjectPath.root().attr(\"bar\"),\n    ObjectPath.root().array_index(3),\n    ObjectPath.root().array_index(4),\n    ObjectPath.root().missing_array_element(3),\n    ObjectPath.root().missing_array_element(4),\n    ObjectPath.root().map_value(\"foo\"),\n    ObjectPath.root().map_value(\"bar\"),\n    ObjectPath.root().missing_map_entry(),\n    ObjectPath.root().attr(\"foo\").missing_map_entry(),\n]\n\n\ndef make_test_params_for_eq_test():\n    return [\n        pytest.param(idx, path, id=\"path{}\".format(idx))\n        for idx, path in enumerate(paths_for_equality_test)\n    ]\n\n\n@pytest.mark.parametrize(\"a_idx, a_path\", make_test_params_for_eq_test())\n@pytest.mark.parametrize(\"b_idx, b_path\", make_test_params_for_eq_test())\ndef test_path_equal(a_idx, a_path, b_idx, b_path):\n    expected = a_idx == b_idx\n    result = a_path == b_path\n    assert result == expected\n\n\ndef test_path_get_prefix():\n    p1 = ObjectPath.root()\n    p2 = p1.attr(\"foo\")\n    p3 = p2.array_index(5)\n\n    assert p3.parent == p2\n    assert p2.parent == p1\n    assert p1.parent is None\n\n    assert p2.get_prefix(1) == p1\n\n    assert p3.get_prefix(1) == p1\n    assert p3.get_prefix(2) == p2\n    assert p3.get_prefix(3) == p3\n\n    with pytest.raises(IndexError) as e:\n        p3.get_prefix(0)\n    assert \"Prefix length must be at least 1\" in str(e.value)\n\n    with pytest.raises(IndexError) as e:\n        p3.get_prefix(4)\n    assert \"Attempted to get a prefix longer than the path itself\" in str(e.value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_roofline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport csv\nimport json\nimport os\nimport platform\nfrom io import StringIO\n\nimport numpy as np\nimport pytest\n\nimport tvm.testing\nimport tvm.utils\nfrom tvm import relay, rpc\nfrom tvm.contrib import utils\nfrom tvm.contrib.debugger import debug_executor\nfrom tvm.relay.testing import mlp\nfrom tvm.runtime import profiler_vm\nfrom tvm.runtime.profiling import Report\nfrom tvm.script import tir as T\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.parametrize(\"dtype\", [\"float32\", \"int8\", \"int32\"])\ndef test_estimate_peak_flops_cpu(dtype):\n    server = rpc.Server(key=\"roofline_flops_cpu\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"roofline_flops_cpu\")\n    target = tvm.target.Target(\"llvm -mattr=+fma,+avx2\")\n    dev = remote.device(str(target))\n    # This test uses vectorized instructions so we need a target that supports them\n    flops = tvm.utils.roofline.x86.estimate_peak_fma_vector_flops(target, dev, remote, \"float32\")\n    # Assume we can achieve 1 GFLOP/s per thread, which is 1 FLOP per cycle on a 1GHz cpu.\n    assert (\n        flops > 10**9 and flops < 10**14\n    ), f\"FLOP/s should be between 10^9 and 10^14, but it is {flops}\"\n\n\n@tvm.testing.requires_cuda\ndef test_estimate_peak_flops_gpu():\n    server = rpc.Server(key=\"roofline_flops_gpu\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"roofline_flops_gpu\")\n    target = tvm.target.Target(\"cuda\")\n    dev = remote.device(str(target))\n    # This test uses vectorized instructions so we need a target that supports them\n    flops = tvm.utils.roofline.cuda.estimate_peak_flops_tensorcore(target, dev, remote)\n    # should be able to hit a TFLOP/s with tensor cores\n    assert (\n        flops > 10**12 and flops < 10**14\n    ), f\"FLOP/s should be between 10^12 and 10^14, but it is {flops}\"\n\n\n@tvm.testing.skip_if_32bit(reason=\"Cannot allocate enough memory on i386\")\n@tvm.testing.requires_llvm\ndef test_estimate_peak_bandwidth_cpu():\n    server = rpc.Server(key=\"roofline_bandwidth_cpu\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"roofline_bandwidth_cpu\")\n    target = tvm.target.Target(\"llvm -mattr=+fma,+avx2\")\n    dev = remote.device(str(target))\n    # This test uses vectorized instructions so we need a target that supports them\n    bandwidth = tvm.utils.roofline.x86.estimate_peak_bandwidth_dram(target, dev, remote)\n    # Assume we can achieve 1 GB/s. DDR2 should transfer somewhere around 6\n    # GB/s, so this should leave enough wiggle room.\n    assert (\n        bandwidth > 10**9 and bandwidth < 10**12\n    ), f\"Bandwidth should be between 10^9 and 10^12, but it is {bandwidth}\"\n\n\n@tvm.testing.requires_cuda\ndef test_estimate_peak_bandwidth_gpu():\n    server = rpc.Server(key=\"roofline_bandwidth_gpu\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"roofline_bandwidth_gpu\")\n    target = tvm.target.Target(\"cuda\")\n    dev = remote.device(str(target))\n    # This test uses vectorized instructions so we need a target that supports them\n    bandwidth = tvm.utils.roofline.cuda.estimate_peak_bandwidth_global_mem(target, dev, remote)\n    # should be able to hit a 100 GB/s on a GPU. GTX 280 hits 140 GB/s and\n    # it is really old.\n    assert (\n        bandwidth > 10**11 and bandwidth < 10**13\n    ), f\"Bandwidth should be between 10^9 and 10^12, but it is {bandwidth}\"\n\n\n@tvm.testing.skip_if_32bit(reason=\"Cannot allocate enough memory on i386\")\n@tvm.testing.parametrize_targets(\"llvm -mattr=+fma,+avx2\", \"cuda\")\ndef test_roofline_analysis(target, dev):\n    a = relay.var(\"a\", relay.TensorType((512, 512), \"float32\"))\n    b = relay.var(\"b\", relay.TensorType((512, 512), \"float32\"))\n    c = relay.nn.dense(a, b)\n    mod = tvm.IRModule.from_expr(relay.Function([a, b], c))\n    params = {}\n\n    server = rpc.Server(key=\"roofline\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"roofline\")\n    dev = remote.device(target)\n\n    report = tvm.utils.roofline_analysis(mod, params, target, dev, remote=remote)\n    print(report)\n\n    assert \"Bound\" in report.table()\n    assert \"Percent of Theoretical Optimal\" in report.table()\n    for call in report.calls:\n        if \"Percent of Theoretical Optimal\" in call:\n            if target.startswith(\"llvm\"):\n                # Ideally we'd like a little tighter bound here, but it is hard to\n                # know how well this dense will perform without tuning. And we\n                # don't have an operator that uses a specific number of flops.\n                assert call[\"Percent of Theoretical Optimal\"].ratio >= 5.0\n            elif target == \"cuda\":\n                # The cuda gpu kernel is really poorly optimized\n                assert 90 >= call[\"Percent of Theoretical Optimal\"].ratio >= 0.01\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_container.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport random\nimport tvm\nimport tvm.testing\nimport pickle\nfrom tvm import te\nfrom tvm import nd, relay\nfrom tvm.runtime import container as _container\n\n\ndef test_adt_constructor():\n    arr = nd.array([1, 2, 3])\n    fields = [arr, arr]\n    y = _container.ADT(0, [arr, arr])\n\n    assert len(y) == 2\n    assert isinstance(y, _container.ADT)\n    y[0:1][-1] == arr\n    assert y.tag == 0\n    assert isinstance(arr, nd.NDArray)\n\n\ndef test_tuple_object():\n    x = relay.var(\n        \"x\",\n        type_annotation=relay.ty.TupleType(\n            [relay.ty.TensorType((), \"int32\"), relay.ty.TensorType((), \"int32\")]\n        ),\n    )\n\n    fn = relay.Function([x], relay.expr.TupleGetItem(x, 0))\n    mod = tvm.IRModule.from_expr(fn)\n\n    f = relay.create_executor(kind=\"vm\", mod=mod, device=nd.cpu(), target=\"llvm\").evaluate()\n    value_tuple = _container.tuple_object([nd.array(np.array(11)), nd.array(np.array(12))])\n    # pass an ADT object to evaluate\n    out = f(value_tuple)\n    tvm.testing.assert_allclose(out.numpy(), np.array(11))\n\n\ndef test_string():\n    s = tvm.runtime.String(\"xyz\")\n\n    assert isinstance(s, tvm.runtime.String)\n    assert isinstance(s, str)\n    assert s.startswith(\"xy\")\n    assert s + \"1\" == \"xyz1\"\n    y = tvm.testing.echo(s)\n    assert isinstance(y, tvm.runtime.String)\n    assert s.__tvm_object__.same_as(y.__tvm_object__)\n    assert s == y\n\n    x = tvm.ir.load_json(tvm.ir.save_json(y))\n    assert isinstance(x, tvm.runtime.String)\n    assert x == y\n\n    # test pickle\n    z = pickle.loads(pickle.dumps(s))\n    assert isinstance(z, tvm.runtime.String)\n    assert s == z\n\n\ndef test_shape_tuple():\n    shape = [random.randint(-10, 10) for _ in range(5)]\n    stuple = _container.ShapeTuple(shape)\n    len(stuple) == len(shape)\n    for a, b in zip(stuple, shape):\n        assert a == b\n    # ShapleTuple vs. list\n    assert stuple == list(shape)\n    # ShapleTuple vs. tuple\n    assert stuple == tuple(shape)\n    # ShapleTuple vs. ShapeTuple\n    assert stuple == _container.ShapeTuple(shape)\n\n\nif __name__ == \"__main__\":\n    test_string()\n    test_adt_constructor()\n    test_tuple_object()\n    test_shape_tuple()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_error.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test runtime error handling\"\"\"\nimport tvm\nfrom tvm import te\nimport tvm.testing\n\n\ndef test_op_translation():\n    ferror = tvm.testing.test_raise_error_callback(\"OpNotImplemented: myop\")\n    try:\n        ferror()\n        assert False\n    except tvm.error.OpNotImplemented as e:\n        msg = str(e)\n        assert isinstance(e, NotImplementedError)\n        assert msg.find(\"ffi_testing.cc\") != -1\n\n    fchk_eq = tvm.testing.test_check_eq_callback(\"InternalError: myop\")\n    try:\n        fchk_eq(0, 1)\n        assert False\n    except tvm.error.InternalError as e:\n        msg = str(e)\n        assert msg.find(\"ffi_testing.cc\") != -1\n\n    try:\n        tvm.testing.ErrorTest(0, 1)\n        assert False\n    except ValueError as e:\n        msg = str(e)\n        assert msg.find(\"ffi_testing.cc\") != -1\n\n\ndef test_deep_callback():\n    def error_callback():\n        raise ValueError(\"callback error\")\n\n    wrap1 = tvm.testing.test_wrap_callback(error_callback)\n\n    def flevel2():\n        wrap1()\n\n    wrap2 = tvm.testing.test_wrap_callback(flevel2)\n\n    def flevel3():\n        wrap2()\n\n    wrap3 = tvm.testing.test_wrap_callback(flevel3)\n\n    try:\n        wrap3()\n        assert False\n    except ValueError as e:\n        msg = str(e)\n        idx2 = msg.find(\"in flevel2\")\n        idx3 = msg.find(\"in flevel3\")\n        assert idx2 != -1 and idx3 != -1\n        assert idx2 > idx3\n\n\nif __name__ == \"__main__\":\n    test_op_translation()\n    test_deep_callback()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_extension.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n\n@tvm.register_extension\nclass MyTensorView(object):\n    _tvm_tcode = tvm._ffi.runtime_ctypes.ArgTypeCode.DLTENSOR_HANDLE\n\n    def __init__(self, arr):\n        self.arr = arr\n\n    @property\n    def _tvm_handle(self):\n        return self.arr._tvm_handle\n\n\ndef test_dltensor_compatible():\n    dtype = \"int64\"\n    n = te.var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    i = te.var(\"i\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.buffer_ptr(Ab)\n    with ib.for_range(0, n - 1, \"i\") as i:\n        A[i + 1] = A[i] + 1\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"arange\"))\n    f = tvm.build(mod, target=\"stackvm\")\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n    aview = MyTensorView(a)\n    f(aview)\n    np.testing.assert_equal(a.numpy(), np.arange(a.shape[0]))\n\n\nif __name__ == \"__main__\":\n    test_dltensor_compatible()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te, runtime\nimport numpy as np\nimport json\nfrom tvm import rpc\nfrom tvm import relay\nfrom tvm.contrib import utils, graph_executor\n\n\n@tvm.testing.requires_llvm\ndef test_graph_simple():\n    n = 4\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    node0 = {\"op\": \"null\", \"name\": \"x\", \"inputs\": []}\n    node1 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"add\",\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\"func_name\": \"myadd\", \"flatten_data\": \"1\", \"num_inputs\": \"1\", \"num_outputs\": \"1\"},\n    }\n    nodes = [node0, node1]\n    arg_nodes = [0]\n    node_row_ptr = [0, 1, 2]\n    outputs = [[1, 0, 0]]\n    shape = (4,)\n    attrs = {\n        \"shape\": [\"list_shape\", [shape, shape]],\n        \"dltype\": [\"list_str\", [\"float32\", \"float32\"]],\n        \"storage_id\": [\"list_int\", [0, 1]],\n    }\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": outputs,\n        \"attrs\": attrs,\n    }\n    graph = json.dumps(graph)\n\n    def check_verify():\n        mlib = tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n        mod = graph_executor.create(graph, mlib, tvm.cpu(0))\n        a = np.random.uniform(size=(n,)).astype(A.dtype)\n        mod.run(x=a)\n        out = mod.get_output(0, tvm.nd.empty((n,)))\n        np.testing.assert_equal(out.numpy(), a + 1)\n\n    def check_remote(server):\n        mlib = tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n        remote = rpc.connect(server.host, server.port)\n        temp = utils.tempdir()\n        dev = remote.cpu(0)\n        path_dso = temp.relpath(\"dev_lib.so\")\n        mlib.export_library(path_dso)\n        remote.upload(path_dso)\n        mlib = remote.load_module(\"dev_lib.so\")\n        mod = graph_executor.create(graph, mlib, remote.cpu(0))\n        a = np.random.uniform(size=(n,)).astype(A.dtype)\n        mod.run(x=tvm.nd.array(a, dev))\n        out = tvm.nd.empty((n,), device=dev)\n        out = mod.get_output(0, out)\n        np.testing.assert_equal(out.numpy(), a + 1)\n\n    def check_sharing():\n        x = relay.var(\"x\", shape=(1, 10))\n        y = relay.var(\"y\", shape=(1, 10))\n        z = relay.add(x, y)\n        func = relay.Function([x, y], z)\n\n        x_in = np.ones((1, 10)).astype(\"float32\")\n        params = {\"x\": x_in}\n        graph, lib, params = relay.build(func, target=\"llvm\", params=params)\n\n        mod_shared = graph_executor.create(graph, lib, tvm.cpu(0))\n        mod_shared.load_params(runtime.save_param_dict(params))\n        num_mods = 10\n        mods = [graph_executor.create(graph, lib, tvm.cpu(0)) for _ in range(num_mods)]\n\n        for mod in mods:\n            mod.share_params(mod_shared, runtime.save_param_dict(params))\n\n        a = np.random.uniform(size=(1, 10)).astype(\"float32\")\n        for mod in mods:\n            mod.run(y=a)\n            out = mod.get_output(0, tvm.nd.empty((1, 10)))\n            np.testing.assert_equal(out.numpy(), x_in + a)\n\n        # Explicitly delete the shared module and verify correctness.\n        del mod_shared\n        for mod in mods:\n            mod.run(y=a)\n            out = mod.get_output(0, tvm.nd.empty((1, 10)))\n            np.testing.assert_equal(out.numpy(), x_in + a)\n            del mod\n\n    check_verify()\n    check_remote(rpc.Server(\"127.0.0.1\"))\n    check_sharing()\n\n\ndef test_load_unexpected_params():\n    # Test whether graph_executor.load_params works if parameters\n    # are provided that are not an expected input.\n    mod = tvm.IRModule()\n    params = {}\n    x = relay.var(\"x\", shape=(1, 10))\n    y = relay.var(\"y\", shape=(1, 10))\n    z = relay.add(x, y)\n    mod[\"main\"] = relay.Function([x, y], z)\n\n    graph_module = relay.build(mod, target=\"llvm\", params=params)\n    rt_mod = tvm.contrib.graph_executor.create(\n        graph_module.get_graph_json(), graph_module.get_lib(), tvm.cpu(0)\n    )\n\n    new_params = graph_module.get_params()\n    new_params.update({\"y_unknown\": np.ones((1,)).astype(\"float32\")})\n    rt_mod.load_params(runtime.save_param_dict(new_params))\n\n\nif __name__ == \"__main__\":\n    test_graph_simple()\n    test_load_unexpected_params()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_graph_cuda_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport json\nimport os\nimport re\nimport sys\nimport time\n\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\nfrom tvm.contrib import utils, graph_executor\nfrom tvm.contrib.cuda_graph import cuda_graph_executor\n\n\nbx = te.thread_axis(\"blockIdx.x\")\ntx = te.thread_axis(\"threadIdx.x\")\n\n\n@tvm.testing.requires_cudagraph\ndef test_graph_simple():\n    n = 32\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=8)\n    s[B].bind(xo, bx)\n    s[B].bind(xi, tx)\n\n    node0 = {\"op\": \"null\", \"name\": \"x\", \"inputs\": []}\n    node1 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"add\",\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\"func_name\": \"myadd\", \"flatten_data\": \"1\", \"num_inputs\": \"1\", \"num_outputs\": \"1\"},\n    }\n    nodes = [node0, node1]\n    arg_nodes = [0]\n    node_row_ptr = [0, 1, 2]\n    outputs = [[1, 0, 0]]\n    shape = (n,)\n    attrs = {\n        \"shape\": [\"list_shape\", [shape, shape]],\n        \"dltype\": [\"list_str\", [\"float32\", \"float32\"]],\n        \"storage_id\": [\"list_int\", [0, 1]],\n    }\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": outputs,\n        \"attrs\": attrs,\n    }\n    graph = json.dumps(graph)\n\n    def check_verify():\n        mlib = tvm.build(s, [A, B], \"cuda\", name=\"myadd\")\n        dev = tvm.cuda(0)\n        try:\n            mod = cuda_graph_executor.create(graph, mlib, dev)\n        except ValueError:\n            return\n\n        for i in range(3):\n            a = np.random.uniform(size=(n,)).astype(A.dtype)\n            mod.run(x=a)  # The first run captured a CUDA graph\n            out = mod.get_output(0, tvm.nd.empty((n,)))\n            np.testing.assert_equal(out.numpy(), a + 1)\n\n        # capture / run CUDA graph manually\n        mod.capture_cuda_graph()\n        a = np.random.uniform(size=(n,)).astype(A.dtype)\n        mod.set_input(x=a)\n        mod.run_cuda_graph()\n        out = mod.get_output(0, tvm.nd.empty((n,)))\n        np.testing.assert_equal(out.numpy(), a + 1)\n\n    check_verify()\n\n\nif __name__ == \"__main__\":\n    test_graph_simple()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_graph_debug.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport json\nimport os\nimport re\nimport sys\nimport time\nfrom distutils.log import debug\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import rpc, te\nfrom tvm._ffi.base import TVMError\nfrom tvm.contrib import utils\nfrom tvm.contrib.debugger import debug_executor\n\n\n# Constants for creating simple graphs, fixtures to avoid free globals\n@pytest.fixture\ndef n():\n    return 4\n\n\n@pytest.fixture\ndef A(n):\n    return te.placeholder((n,), name=\"A\")\n\n\n@pytest.fixture\ndef B(A):\n    return te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n\n\n@pytest.fixture\ndef s(B):\n    return te.create_schedule(B.op)\n\n\n@pytest.fixture\ndef mlib(s, A, B):\n    return tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n\n\n@pytest.fixture\ndef myadd(mlib):\n    def _myadd(*args):\n        to_return = mlib[\"myadd\"](*args)\n        time.sleep(0.25)\n        return to_return\n\n    return _myadd\n\n\n@pytest.fixture\ndef graph():\n    node0 = {\"op\": \"null\", \"name\": \"x\", \"inputs\": []}\n    node1 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"add\",\n        \"inputs\": [[0, 0, 0]],\n        \"attrs\": {\"func_name\": \"myadd\", \"flatten_data\": \"1\", \"num_inputs\": \"1\", \"num_outputs\": \"1\"},\n    }\n    nodes = [node0, node1]\n    arg_nodes = [0]\n    node_row_ptr = [0, 1, 2]\n    outputs = [[1, 0, 0]]\n    shape = (4,)\n    attrs = {\n        \"shape\": [\"list_shape\", [shape, shape]],\n        \"dltype\": [\"list_str\", [\"float32\", \"float32\"]],\n        \"storage_id\": [\"list_int\", [0, 1]],\n    }\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": outputs,\n        \"attrs\": attrs,\n    }\n    graph = json.dumps(graph)\n    return graph\n\n\n@tvm.testing.requires_llvm\n@tvm.testing.requires_rpc\n@pytest.mark.skipif(\n    tvm.support.libinfo()[\"USE_PROFILER\"] != \"ON\", reason=\"TVM was not built with profiler support\"\n)\ndef test_end_to_end_graph_simple(graph, n, A, B, s, myadd):\n    def check_verify():\n        mlib_proxy = tvm.support.FrontendTestModule()\n        mlib_proxy[\"myadd\"] = myadd\n        mod = debug_executor.create(graph, mlib_proxy, tvm.cpu(0))\n\n        a = np.random.uniform(size=(n,)).astype(A.dtype)\n        mod.set_input(x=a)\n\n        # verify dumproot created\n        directory = mod._dump_path\n        assert os.path.exists(directory)\n\n        # verify graph is there\n        GRAPH_DUMP_FILE_NAME = \"_tvmdbg_graph_dump.json\"\n        assert len(os.listdir(directory)) == 1\n\n        # verify the file name is proper\n        graph_dump_path = os.path.join(directory, GRAPH_DUMP_FILE_NAME)\n        assert os.path.exists(graph_dump_path)\n\n        # verify the graph contains some expected keys\n        with open(graph_dump_path) as graph_f:\n            dumped_graph = json.load(graph_f)\n\n        assert isinstance(dumped_graph, dict)\n        for k in (\"nodes\", \"arg_nodes\", \"node_row_ptr\", \"heads\", \"attrs\"):\n            assert k in dumped_graph, f\"key {k} not in dumped graph {graph!r}\"\n\n        mod.run()\n        # Verify the tensors are dumped\n        assert len(os.listdir(directory)) > 1\n\n        debug_lines = mod.debug_datum.get_debug_result().split(\"\\n\")\n\n        def split_debug_line(i):\n            to_return = re.split(r\"  [ ]*\", debug_lines[i])\n            assert to_return[-1] == \"\"\n            to_return = to_return[:-1]  # strip empty trailing part\n            return to_return\n\n        assert split_debug_line(0) == [\n            \"Node Name\",\n            \"Ops\",\n            \"Time(us)\",\n            \"Time(%)\",\n            \"Shape\",\n            \"Inputs\",\n            \"Outputs\",\n            \"Measurements(us)\",\n        ]\n        myadd_lines = split_debug_line(2)\n        assert myadd_lines[0] == \"add\"\n        assert myadd_lines[1] == \"myadd\"\n        runtime_sec = float(myadd_lines[2]) / 1e6  # printed in us\n\n        # Ensure runtime is at least the sleep time and less than a unit prefix order of magnitude.\n        # Here we just care that the prefix is correct.\n        assert runtime_sec > 0.25 and runtime_sec < 0.25 * 1000\n\n        total_lines = split_debug_line(3)\n        assert total_lines[0] == \"Total_time\"\n        assert total_lines[2] == myadd_lines[2]\n\n        CHROME_TRACE_FILE_NAME = \"_tvmdbg_execution_trace.json\"\n        assert os.path.exists(os.path.join(directory, CHROME_TRACE_FILE_NAME))\n\n        with open(os.path.join(directory, CHROME_TRACE_FILE_NAME)) as f:\n            trace = json.load(f)\n        assert trace[\"displayTimeUnit\"] == \"ns\"\n        events = trace[\"traceEvents\"]\n        assert len(events) == 4\n        assert all(event[\"ph\"] in (\"B\", \"E\") for event in events)\n        assert all(event[\"pid\"] == 1 for event in events)\n        assert all(event[\"tid\"] == 1 for event in events)\n        assert all(event[\"name\"] == \"x\" for event in events[:2])\n        assert all(event[\"name\"] == \"add\" for event in events[2:])\n        assert events[0][\"ts\"] == 0\n        assert events[0][\"ph\"] == \"B\"\n\n        # verify the output is correct\n        out = mod.get_output(0, tvm.nd.empty((n,)))\n        np.testing.assert_equal(out.numpy(), a + 1)\n\n        mod.exit()\n        # verify dump root delete after cleanup\n        assert not os.path.exists(directory)\n\n    def check_remote(server):\n        mlib = tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n        remote = rpc.connect(server.host, server.port)\n        temp = utils.tempdir()\n        dev = remote.cpu(0)\n        path_dso = temp.relpath(\"dev_lib.so\")\n        mlib.export_library(path_dso)\n        remote.upload(path_dso)\n        mlib = remote.load_module(\"dev_lib.so\")\n        try:\n            mod = debug_executor.create(graph, mlib, remote.cpu(0))\n        except ValueError:\n            print(\"Skip because debug runtime not enabled\")\n            return\n        a = np.random.uniform(size=(n,)).astype(A.dtype)\n        mod.run(x=tvm.nd.array(a, dev))\n        out = tvm.nd.empty((n,), device=dev)\n        out = mod.get_output(0, out)\n        np.testing.assert_equal(out.numpy(), a + 1)\n\n    check_verify()\n    check_remote(rpc.Server(\"127.0.0.1\"))\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.skipif(\n    tvm.support.libinfo()[\"USE_PROFILER\"] != \"ON\", reason=\"TVM was not built with profiler support\"\n)\ndef test_run_single_node(graph, n, A, myadd):\n    mlib_proxy = tvm.support.FrontendTestModule()\n    mlib_proxy[\"myadd\"] = myadd\n    mod: debug_executor.GraphModuleDebug = debug_executor.create(graph, mlib_proxy, tvm.cpu(0))\n\n    a = np.random.uniform(size=(n,)).astype(A.dtype)\n    mod.set_input(x=a)\n\n    assert len(mod.debug_datum.get_graph_nodes()) == 2\n    assert mod.debug_datum.get_graph_nodes()[0][\"op\"] == \"param\"\n    assert mod.debug_datum.get_graph_nodes()[1][\"op\"] == \"myadd\"\n\n    # Running a node with no associated function should return instantly and have 0 runtime\n    assert mod.run_individual_node(0, number=1).mean == 0\n\n    # Meanwhile the actual function should take some time, more time if you run it more times\n    repeat_1_result = mod.run_individual_node(1, repeat=1)\n    assert repeat_1_result.mean > 0\n\n    # Running multiple times (10) should take longer than 1 time\n    repeat_3_results = mod.run_individual_node(1, repeat=3)\n    assert sum(repeat_3_results.results) > sum(repeat_1_result.results)\n\n    # Increasing the number of repeats should give you the number of results asked for\n    assert len(mod.run_individual_node(1, repeat=10).results) == 10\n\n    # Doing repeat_ms should have the run time greater than the asked amount\n    start = time.time()\n    mod.run_individual_node(1, min_repeat_ms=500)\n    end = time.time()\n    elapsed_time_in_seconds = end - start\n    assert elapsed_time_in_seconds >= 0.5\n\n    # Doing `cooldown_interval_ms` should have the execution time increases\n    start = time.time()\n    mod.run_individual_node(1, repeat=2, min_repeat_ms=500, cooldown_interval_ms=1000)\n    end = time.time()\n    elapsed_time_in_seconds_with_def_rep = end - start\n    assert elapsed_time_in_seconds_with_def_rep >= 3\n\n    # Doing with `repeats_to_cooldown` not equal 1 should not trigger\n    # cooldown after each repeat\n    start = time.time()\n    mod.run_individual_node(\n        1, repeat=2, min_repeat_ms=500, cooldown_interval_ms=1000, repeats_to_cooldown=2\n    )\n    end = time.time()\n    elapsed_time_in_seconds_with_rep_2 = end - start\n    assert elapsed_time_in_seconds_with_rep_2 >= 2 and (\n        elapsed_time_in_seconds_with_rep_2 < elapsed_time_in_seconds_with_def_rep\n    )\n\n    # Going out of bounds of node index throws a tvm error\n    with pytest.raises(TVMError):\n        mod.run_individual_node(2)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_heterogeneous.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=too-many-locals\n\"\"\"Unit tests for heterogeneous runtime\"\"\"\nimport json\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import graph_executor, utils\nfrom tvm import topi\n\n\ndef get_simplex_graph(host_dev_type, device_dev_type):\n    r\"\"\" Return the hand-crafted json object where only one copy node is\n    inserted. This node copies data from the target device to cpu.\n    The network is constructed as following:\n                 A    B\n                  \\  /\n             elemwise_add  (gpu)\n                     \\\n                     copy      C\n                       \\      /\n                     elemwise_sub  (cpu)\n\n    Parameters\n    ----------\n    host_dev_type : int\n        The device type of the host processor, e.g. cpu.\n    device_dev_type : int\n        The device type of the device processor, e.g. gpu, opencl, etc.\n\n    Returns\n    -------\n    json : json\n        A json encoded object.\n    \"\"\"\n    # Construct each node in the graph.\n    var_a = {\"op\": \"null\", \"name\": \"A\", \"inputs\": []}\n    var_b = {\"op\": \"null\", \"name\": \"B\", \"inputs\": []}\n    elemwise_add = {\n        \"op\": \"tvm_op\",\n        \"name\": \"elemwise_add\",\n        \"attrs\": {\n            \"flatten_data\": \"1\",\n            \"func_name\": \"elemwise_add\",\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[0, 0, 0], [1, 0, 0]],\n    }\n    copy = {\n        \"op\": \"tvm_op\",\n        \"name\": \"__copy_add_to_sub\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"__copy\",\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[2, 0, 0]],\n    }\n    var_c = {\"op\": \"null\", \"name\": \"C\", \"inputs\": []}\n    elemwise_sub = {\n        \"op\": \"tvm_op\",\n        \"name\": \"elemwise_sub\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"elemwise_sub\",\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[3, 0, 0], [4, 0, 0]],\n    }\n\n    # Group the nodes.\n    nodes = [var_a, var_b, elemwise_add, copy, var_c, elemwise_sub]\n    arg_nodes = [0, 1, 4]\n    node_row_ptr = [0, 1, 2, 3, 4, 5, 6]\n    heads = [[5, 0, 0]]\n    shape = (4,)\n    attrs = {\n        \"storage_id\": [\"list_int\", [3, 4, 0, 1, 5, 2]],\n        \"shape\": [\"list_shape\", [shape, shape, shape, shape, shape, shape]],\n        \"device_index\": [\n            \"list_int\",\n            [\n                device_dev_type,\n                device_dev_type,\n                device_dev_type,\n                host_dev_type,\n                host_dev_type,\n                host_dev_type,\n            ],\n        ],\n        \"dtype\": [\"list_int\", [0, 0, 0, 0, 0, 0]],\n        \"dltype\": [\"list_str\", [\"float32\", \"float32\", \"float32\", \"float32\", \"float32\", \"float32\"]],\n    }\n\n    # Construct the graph.\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": heads,\n        \"attrs\": attrs,\n    }\n    return json.dumps(graph)\n\n\ndef test_simplex_data_transferring():\n    r\"\"\"\n    Test the heterogeneous execution of a simple network where data\n    transferring is from the target device to the host processor at runtime.\n    The host processor is always assumed to be cpu, and the device varies.\n    \"\"\"\n    host = \"cpu\"\n    target_host = \"llvm\"\n    host_dev = tvm.device(host)\n    if not tvm.runtime.enabled(target_host):\n        print(\"Skip test because llvm is not enabled.\")\n        return\n\n    def check_device(device, target_device):\n        if not tvm.runtime.enabled(target_device):\n            print(\"Skip test because {} is not enabled.\".format(target_device))\n            return\n\n        device_dev = tvm.device(device)\n        graph = get_simplex_graph(host_dev.device_type, device_dev.device_type)\n        shape = (4,)\n\n        # Create module for add whose target is the device.\n        tensor_a = te.placeholder(shape, name=\"A\")\n        tensor_b = te.placeholder(shape, name=\"B\")\n        elemwise_add = te.compute(\n            shape, lambda *i: tensor_a(*i) + tensor_b(*i), name=\"elemwise_add\"\n        )\n        target = topi.cpp.TEST_create_target(device)\n        schedule_add = topi.cpp.cuda.schedule_injective(target, [elemwise_add])\n        lower_add = tvm.lower(schedule_add, [tensor_a, tensor_b, elemwise_add], name=\"elemwise_add\")\n\n        # Insert copy. Neither compute nor schedule is required for the copy\n        # node. The compute will be performed at runtime which is just data\n        # copy from the input to the output.\n        tensor_copy = te.placeholder(shape, name=\"__copy\")\n\n        # Create module for sub whose target is the host.\n        tensor_c = te.placeholder(shape, name=\"C\")\n        elemwise_sub = te.compute(\n            shape, lambda *i: tensor_copy(*i) - tensor_c(*i), name=\"elemwise_sub\"\n        )\n        schedule_sub = te.create_schedule(elemwise_sub.op)\n        lower_sub = tvm.lower(\n            schedule_sub, [tensor_copy, tensor_c, elemwise_sub], name=\"elemwise_sub\"\n        )\n\n        target_flist = {target_device: lower_add, target_host: lower_sub}\n        target = tvm.target.Target(target, target_host)\n        mhost = tvm.build(target_flist, target=target)\n        dev = [host_dev, device_dev]\n        mod = graph_executor.create(graph, mhost, dev)\n        params = {}\n        params[\"A\"] = tensor_a = np.random.uniform(size=shape).astype(tensor_a.dtype)\n        params[\"B\"] = tensor_b = np.random.uniform(size=shape).astype(tensor_b.dtype)\n        params[\"C\"] = tensor_c = np.random.uniform(size=shape).astype(tensor_c.dtype)\n        mod.set_input(**params)\n        mod.run()\n        out = mod.get_output(0, tvm.nd.empty(shape))\n        np.testing.assert_equal(out.numpy(), (tensor_a + tensor_b) - tensor_c)\n\n    dev_tar = {\"cuda\": \"cuda\", \"opencl\": \"opencl\"}\n    for device, target in dev_tar.items():\n        with tvm.target.Target(device):\n            check_device(device, target)\n\n\ndef get_duplex_graph(host_dev_type, device_dev_type):\n    r\"\"\" Return the hand-crafted json object where two copy nodes are inserted.\n    Data transferring happens back-and-forth between the target device and CPU.\n    The network is constructed as following:\n                 A    B\n                  \\  /\n             elemwise_add  (gpu)\n                     \\\n                     copy        C\n                       \\        /\n                      elemwise_sub  (cpu)\n                         \\\n                         copy          D\n                           \\          /\n                           elemwise_add  (gpu)\n\n    Parameters\n    ----------\n    host_dev_type : int\n        The device type of the host processor, e.g. cpu.\n    device_dev_type : int\n        The device type of the device processor, e.g. gpu, opencl, etc.\n\n    Returns\n    -------\n    json : json\n        A json encoded object.\n    \"\"\"\n    # Construct each node in the graph.\n    var_a = {\"op\": \"null\", \"name\": \"A\", \"inputs\": []}\n    var_b = {\"op\": \"null\", \"name\": \"B\", \"inputs\": []}\n    elemwise_add0 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"elemwise_add0\",\n        \"attrs\": {\n            \"flatten_data\": \"1\",\n            \"func_name\": \"elemwise_add0\",\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[0, 0, 0], [1, 0, 0]],\n    }\n    copy_add_sub = {\n        \"op\": \"tvm_op\",\n        \"name\": \"__copy_add_to_sub\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"__copy\",\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[2, 0, 0]],\n    }\n    var_c = {\"op\": \"null\", \"name\": \"C\", \"inputs\": []}\n    elemwise_sub = {\n        \"op\": \"tvm_op\",\n        \"name\": \"elemwise_sub\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"elemwise_sub\",\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[3, 0, 0], [4, 0, 0]],\n    }\n    copy_sub_add = {\n        \"op\": \"tvm_op\",\n        \"name\": \"__copy_sub_to_add\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"__copy\",\n            \"num_inputs\": \"1\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[5, 0, 0]],\n    }\n    var_d = {\"op\": \"null\", \"name\": \"D\", \"inputs\": []}\n    elemwise_add1 = {\n        \"op\": \"tvm_op\",\n        \"name\": \"elemwise_add1\",\n        \"attrs\": {\n            \"flatten_data\": \"0\",\n            \"func_name\": \"elemwise_add1\",\n            \"num_inputs\": \"2\",\n            \"num_outputs\": \"1\",\n        },\n        \"inputs\": [[6, 0, 0], [7, 0, 0]],\n    }\n\n    # Group the nodes.\n    nodes = [\n        var_a,\n        var_b,\n        elemwise_add0,\n        copy_add_sub,\n        var_c,\n        elemwise_sub,\n        copy_sub_add,\n        var_d,\n        elemwise_add1,\n    ]\n    arg_nodes = [0, 1, 4, 7]\n    node_row_ptr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n    heads = [[8, 0, 0]]\n    shape = (4,)\n    attrs = {\n        \"storage_id\": [\"list_int\", [4, 5, 0, 1, 6, 2, 0, 7, 3]],\n        \"shape\": [\"list_shape\", [shape, shape, shape, shape, shape, shape, shape, shape, shape]],\n        \"device_index\": [\n            \"list_int\",\n            [\n                device_dev_type,\n                device_dev_type,\n                device_dev_type,\n                host_dev_type,\n                host_dev_type,\n                host_dev_type,\n                device_dev_type,\n                device_dev_type,\n                device_dev_type,\n            ],\n        ],\n        \"dtype\": [\"list_int\", [0, 0, 0, 0, 0, 0, 0, 0, 0]],\n        \"dltype\": [\n            \"list_str\",\n            [\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n                \"float32\",\n            ],\n        ],\n    }\n\n    # Construct the graph.\n    graph = {\n        \"nodes\": nodes,\n        \"arg_nodes\": arg_nodes,\n        \"node_row_ptr\": node_row_ptr,\n        \"heads\": heads,\n        \"attrs\": attrs,\n    }\n    return json.dumps(graph)\n\n\ndef test_duplex_data_transferring():\n    r\"\"\"\n    Test the heterogeneous execution of a simple network where data\n    transferring occurs back-and-forth between the target device and host\n    processor.\n    The host processor is always assumed to be cpu, and the target device\n    varies.\n    \"\"\"\n    host = \"cpu\"\n    target_host = \"llvm\"\n    host_dev = tvm.device(host)\n    if not tvm.runtime.enabled(target_host):\n        print(\"Skip test because llvm is not enabled.\")\n        return\n\n    def check_device(device, target_device):\n        if not tvm.runtime.enabled(target_device):\n            print(\"Skip test because {} is not enabled.\".format(target_device))\n            return\n\n        device_dev = tvm.device(device)\n        graph = get_duplex_graph(host_dev.device_type, device_dev.device_type)\n        shape = (4,)\n\n        # Insert copy nodes for data transferring between add and sub nodes.\n        # Transfers data from gpu to cpu.\n        copy_add_sub = te.placeholder(shape, name=\"__copy0\")\n        # Transfers data from cpu to gpu.\n        copy_sub_add = te.placeholder(shape, name=\"__copy1\")\n\n        # Create a module containing adds on the device.\n        tensor_a = te.placeholder(shape, name=\"A\")\n        tensor_b = te.placeholder(shape, name=\"B\")\n        tensor_d = te.placeholder(shape, name=\"D\")\n        elemwise_add0 = te.compute(\n            shape, lambda *i: tensor_a(*i) + tensor_b(*i), name=\"elemwise_add0\"\n        )\n        elemwise_add1 = te.compute(\n            shape, lambda *i: copy_sub_add(*i) + tensor_d(*i), name=\"elemwise_add1\"\n        )\n        target = topi.cpp.TEST_create_target(device)\n        add_schedule0 = topi.cpp.cuda.schedule_injective(target, [elemwise_add0])\n        lower_add0 = tvm.lower(\n            add_schedule0, [tensor_a, tensor_b, elemwise_add0], name=\"elemwise_add0\"\n        )\n        add_schedule1 = topi.cpp.cuda.schedule_injective(target, [elemwise_add1])\n        lower_add1 = tvm.lower(\n            add_schedule1, [tensor_d, copy_sub_add, elemwise_add1], name=\"elemwise_add1\"\n        )\n        # Create module for sub whose target is the host.\n        tensor_c = te.placeholder(shape, name=\"C\")\n        elemwise_sub = te.compute(\n            shape, lambda *i: copy_add_sub(*i) - tensor_c(*i), name=\"elemwise_sub\"\n        )\n        sub_schedule = te.create_schedule(elemwise_sub.op)\n        lower_sub = tvm.lower(\n            sub_schedule, [copy_add_sub, tensor_c, elemwise_sub], name=\"elemwise_sub\"\n        )\n\n        lower_add0.update(lower_add1)\n        target_flist = {target_device: lower_add0, target_host: lower_sub}\n        target = tvm.target.Target(target, target_host)\n        mhost = tvm.build(target_flist, target=target)\n        dev = [host_dev, device_dev]\n        params = {}\n        params[\"A\"] = tensor_a = np.random.uniform(size=shape).astype(tensor_a.dtype)\n        params[\"B\"] = tensor_b = np.random.uniform(size=shape).astype(tensor_b.dtype)\n        params[\"C\"] = tensor_c = np.random.uniform(size=shape).astype(tensor_c.dtype)\n        params[\"D\"] = tensor_d = np.random.uniform(size=shape).astype(tensor_d.dtype)\n\n        def check_verify():\n            mod = graph_executor.create(graph, mhost, dev)\n            mod.set_input(**params)\n            mod.run()\n            out = mod.get_output(0, tvm.nd.empty(shape))\n            np.testing.assert_equal(out.numpy(), tensor_a + tensor_b - tensor_c + tensor_d)\n\n        def check_load_module():\n            temp = utils.tempdir()\n            path_lib = temp.relpath(\"deploy.so\")\n            mhost.export_library(path_lib)\n            with open(temp.relpath(\"deploy.json\"), \"w\") as out_file:\n                out_file.write(graph)\n            loaded_lib = tvm.runtime.load_module(path_lib)\n            loaded_graph = open(temp.relpath(\"deploy.json\")).read()\n            mod = graph_executor.create(loaded_graph, loaded_lib, dev)\n            mod.set_input(**params)\n            mod.run()\n            out = mod.get_output(0, tvm.nd.empty(shape))\n            np.testing.assert_equal(out.numpy(), tensor_a + tensor_b - tensor_c + tensor_d)\n\n        check_verify()\n        check_load_module()\n\n    dev_tar = {\"cuda\": \"cuda\", \"opencl\": \"opencl\"}\n    for device, target in dev_tar.items():\n        with tvm.target.Target(device):\n            check_device(device, target)\n\n\nif __name__ == \"__main__\":\n    test_simplex_data_transferring()\n    test_duplex_data_transferring()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_measure.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport time\nimport ctypes\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib.utils import tempdir\nfrom tvm.runtime.module import BenchmarkResult\n\n\ndef test_min_repeat_ms():\n    tmp = tempdir()\n    filename = tmp.relpath(\"log\")\n\n    @tvm.register_func\n    def my_debug(filename):\n        \"\"\"one call lasts for 100 ms and writes one character to a file\"\"\"\n        time.sleep(0.1)\n        with open(filename, \"a\") as fout:\n            fout.write(\"c\")\n\n    X = te.compute((), lambda: tvm.tir.call_packed(\"my_debug\", filename))\n    s = te.create_schedule(X.op)\n    func = tvm.build(s, [X])\n\n    x = tvm.nd.empty((), dtype=\"int32\")\n    ftimer = func.time_evaluator(func.entry_name, tvm.cpu(), number=1, repeat=1)\n    ftimer(x)\n\n    with open(filename, \"r\") as fin:\n        ct = len(fin.readline())\n\n    assert ct == 2\n\n    ftimer = func.time_evaluator(func.entry_name, tvm.cpu(), number=1, repeat=1, min_repeat_ms=1000)\n    ftimer(x)\n\n    # make sure we get more than 10 calls\n    with open(filename, \"r\") as fin:\n        ct = len(fin.readline())\n\n    assert ct > 10 + 2\n\n\ndef test_benchmark_result():\n    r = BenchmarkResult([1, 2, 2, 5])\n    assert r.mean == 2.5\n    assert r.median == 2.0\n    assert r.min == 1\n    assert r.max == 5\n    assert r.std == 1.5\n\n\nif __name__ == \"__main__\":\n    test_min_repeat_ms()\n    test_benchmark_result()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_module_based_interface.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport os\nfrom tvm import relay, runtime\nfrom tvm.relay import testing\nimport tvm\nfrom tvm.contrib import graph_executor\nfrom tvm.contrib.debugger import debug_executor\nfrom tvm.contrib.cuda_graph import cuda_graph_executor\nimport tvm.testing\n\n\ndef input_shape(mod):\n    return [int(x) for x in mod[\"main\"].checked_type.arg_types[0].shape]\n\n\ndef verify(data):\n    if not tvm.runtime.enabled(\"llvm\"):\n        print(\"Skip because llvm is not enabled\")\n        return\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        graph, lib, graph_params = relay.build_module.build(mod, \"llvm\", params=params)\n\n    dev = tvm.cpu()\n    module = graph_executor.create(graph, lib, dev)\n    module.set_input(\"data\", data)\n    module.set_input(**graph_params)\n    module.run()\n    out = module.get_output(0).numpy()\n\n    return out\n\n\n@tvm.testing.requires_llvm\ndef test_legacy_compatibility():\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        graph, lib, graph_params = relay.build_module.build(mod, \"llvm\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n    dev = tvm.cpu()\n    module = graph_executor.create(graph, lib, dev)\n    module.set_input(\"data\", data)\n    module.set_input(**graph_params)\n    module.run()\n    out = module.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_cpu():\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n    # raw api\n    dev = tvm.cpu()\n    gmod = complied_graph_lib[\"default\"](dev)\n    set_input = gmod[\"set_input\"]\n    run = gmod[\"run\"]\n    get_output = gmod[\"get_output\"]\n    set_input(\"data\", tvm.nd.array(data))\n    run()\n    out = get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    # graph executor wrapper\n    gmod = graph_executor.GraphModule(complied_graph_lib[\"default\"](dev))\n    gmod.set_input(\"data\", data)\n    gmod.run()\n    out = gmod.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_cpu_get_graph_json():\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n    from tvm.contrib import utils\n\n    temp = utils.tempdir()\n    file_name = \"deploy_lib.so\"\n    path_lib = temp.relpath(file_name)\n    complied_graph_lib.export_library(path_lib)\n    loaded_lib = tvm.runtime.load_module(path_lib)\n    json = loaded_lib[\"get_graph_json\"]()\n    assert isinstance(json, str) == True\n    assert json.find(\"tvmgen_default_fused_nn_softmax_add\") > -1\n\n\n@tvm.testing.requires_llvm\ndef test_cpu_get_graph_params_run():\n    mod, params = relay.testing.synthetic.get_workload()\n    with tvm.transform.PassContext(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n    dev = tvm.cpu()\n    from tvm.contrib import utils\n\n    temp = utils.tempdir()\n    file_name = \"deploy_lib.so\"\n    path_lib = temp.relpath(file_name)\n    complied_graph_lib.export_library(path_lib)\n\n    loaded_lib = tvm.runtime.load_module(path_lib)\n    loaded_params = loaded_lib[\"get_graph_params\"]()\n\n    gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n    gmod.set_input(key=\"data\", value=data, **loaded_params)\n    gmod.run()\n    out = gmod.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_cpu_get_graph_params_compare():\n    # Create sample net\n    from tvm.relay.testing.init import create_workload, Constant\n\n    inp_shape = (1, 3, 24, 12)\n    dtype = \"float32\"\n    data = relay.var(\"data\", shape=inp_shape, dtype=dtype)\n    conv_shape = [inp_shape[1], inp_shape[1], 3, 3]\n    conv = relay.nn.conv2d(\n        data,\n        relay.var(\"conv_weight\", shape=conv_shape, dtype=dtype),\n        padding=1,\n        kernel_size=3,\n    )\n    args = relay.analysis.free_vars(conv)\n    func = relay.Function(args, conv)\n\n    mod, params = create_workload(func, initializer=Constant())\n\n    with tvm.transform.PassContext(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n    from tvm.contrib import utils\n\n    temp = utils.tempdir()\n    file_name = \"deploy_lib.so\"\n    path_lib = temp.relpath(file_name)\n    complied_graph_lib.export_library(path_lib)\n\n    loaded_lib = tvm.runtime.load_module(path_lib)\n    loaded_params = loaded_lib[\"get_graph_params\"]()\n\n    tvm.testing.assert_allclose(\n        params[\"conv_weight\"].numpy(), loaded_params[\"p0\"].numpy()[0][0], atol=1e-5\n    )\n\n\n@tvm.testing.requires_cuda\n@tvm.testing.requires_gpu\ndef test_gpu():\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n    dev = tvm.cuda()\n\n    # raw api\n    gmod = complied_graph_lib[\"default\"](dev)\n    set_input = gmod[\"set_input\"]\n    run = gmod[\"run\"]\n    get_output = gmod[\"get_output\"]\n    set_input(\"data\", tvm.nd.array(data))\n    run()\n    out = get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    # graph executor wrapper\n    gmod = graph_executor.GraphModule(complied_graph_lib[\"default\"](dev))\n    gmod.set_input(\"data\", data)\n    gmod.run()\n    out = gmod.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_mod_export():\n    def verify_cpu_export(obj_format):\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib.export_library(path_lib)\n\n        # run the setup in a separate function, so the load_lib\n        # can get destructed right away\n        # test the robustness wrt to parent module destruction\n        def setup_gmod():\n            loaded_lib = tvm.runtime.load_module(path_lib)\n            dev = tvm.cpu(0)\n            return loaded_lib[\"default\"](dev)\n\n        gmod = setup_gmod()\n        # raw api\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        set_input(\"data\", tvm.nd.array(data))\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(setup_gmod())\n        gmod.set_input(\"data\", data)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    def verify_gpu_export(obj_format):\n        if not tvm.testing.device_enabled(\"cuda\"):\n            print(\"Skip because cuda is not enabled\")\n            return\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib.export_library(path_lib)\n\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n\n        # run the setup in a separate function, so the load_lib\n        # can get destructed right away\n        # test the robustness wrt to parent module destruction\n        def setup_gmod():\n            loaded_lib = tvm.runtime.load_module(path_lib)\n            dev = tvm.cuda()\n            return loaded_lib[\"default\"](dev)\n\n        gmod = setup_gmod()\n        # raw api\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        set_input(\"data\", tvm.nd.array(data))\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(setup_gmod())\n        gmod.set_input(\"data\", data)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    @tvm.testing.requires_llvm\n    def verify_rpc_cpu_export(obj_format):\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib.export_library(path_lib)\n\n        from tvm import rpc\n\n        remote = rpc.LocalSession()\n        remote.upload(path_lib)\n        loaded_lib = remote.load_module(path_lib)\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        dev = remote.cpu()\n\n        # raw api\n        gmod = loaded_lib[\"default\"](dev)\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        set_input(\"data\", tvm.nd.array(data, device=dev))\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        gmod.set_input(\"data\", data)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    def verify_rpc_gpu_export(obj_format):\n        if not tvm.testing.device_enabled(\"cuda\"):\n            print(\"Skip because cuda is not enabled\")\n            return\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib.export_library(path_lib)\n\n        from tvm import rpc\n\n        def check_remote(server):\n            remote = rpc.connect(server.host, server.port)\n            remote.upload(path_lib)\n            loaded_lib = remote.load_module(path_lib)\n            data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n            dev = remote.cuda()\n\n            # raw api\n            gmod = loaded_lib[\"default\"](dev)\n            set_input = gmod[\"set_input\"]\n            run = gmod[\"run\"]\n            get_output = gmod[\"get_output\"]\n            set_input(\"data\", tvm.nd.array(data, device=dev))\n            run()\n            out = get_output(0).numpy()\n            tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n            # graph executor wrapper\n            gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n            gmod.set_input(\"data\", data)\n            gmod.run()\n            out = gmod.get_output(0).numpy()\n            tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        check_remote(rpc.Server(\"127.0.0.1\"))\n\n    for obj_format in [\".so\", \".tar\"]:\n        verify_cpu_export(obj_format)\n        verify_gpu_export(obj_format)\n        verify_rpc_cpu_export(obj_format)\n        verify_rpc_gpu_export(obj_format)\n\n\n@tvm.testing.requires_llvm\n@tvm.testing.uses_gpu\ndef test_remove_package_params():\n    def verify_cpu_remove_package_params(obj_format):\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib_no_params = complied_graph_lib[\"remove_params\"]()\n        complied_graph_lib_no_params.export_library(path_lib)\n        with open(temp.relpath(\"deploy_param.params\"), \"wb\") as fo:\n            fo.write(runtime.save_param_dict(complied_graph_lib.get_params()))\n        loaded_lib = tvm.runtime.load_module(path_lib)\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        dev = tvm.cpu(0)\n\n        # raw api\n        gmod = loaded_lib[\"default\"](dev)\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        load_params = gmod[\"load_params\"]\n        loaded_params = bytearray(open(temp.relpath(\"deploy_param.params\"), \"rb\").read())\n        set_input(\"data\", tvm.nd.array(data))\n        load_params(loaded_params)\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        loaded_params = bytearray(open(temp.relpath(\"deploy_param.params\"), \"rb\").read())\n        gmod.set_input(\"data\", data)\n        gmod.load_params(loaded_params)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    def verify_gpu_remove_package_params(obj_format):\n        if not tvm.testing.device_enabled(\"cuda\"):\n            print(\"Skip because cuda is not enabled\")\n            return\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib_no_params = complied_graph_lib[\"remove_params\"]()\n        complied_graph_lib_no_params.export_library(path_lib)\n        with open(temp.relpath(\"deploy_param.params\"), \"wb\") as fo:\n            fo.write(runtime.save_param_dict(complied_graph_lib.get_params()))\n        loaded_lib = tvm.runtime.load_module(path_lib)\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        dev = tvm.cuda(0)\n\n        # raw api\n        gmod = loaded_lib[\"default\"](dev)\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        load_params = gmod[\"load_params\"]\n        loaded_params = bytearray(open(temp.relpath(\"deploy_param.params\"), \"rb\").read())\n        set_input(\"data\", tvm.nd.array(data))\n        load_params(loaded_params)\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        loaded_params = bytearray(open(temp.relpath(\"deploy_param.params\"), \"rb\").read())\n        gmod.set_input(\"data\", data)\n        gmod.load_params(loaded_params)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    @tvm.testing.requires_llvm\n    def verify_rpc_cpu_remove_package_params(obj_format):\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib_no_params = complied_graph_lib[\"remove_params\"]()\n        complied_graph_lib_no_params.export_library(path_lib)\n        path_params = temp.relpath(\"deploy_param.params\")\n        with open(path_params, \"wb\") as fo:\n            fo.write(runtime.save_param_dict(complied_graph_lib.get_params()))\n\n        from tvm import rpc\n\n        remote = rpc.LocalSession()\n        remote.upload(path_lib)\n        loaded_lib = remote.load_module(path_lib)\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        dev = remote.cpu()\n\n        # raw api\n        gmod = loaded_lib[\"default\"](dev)\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        load_params = gmod[\"load_params\"]\n        loaded_params = bytearray(open(path_params, \"rb\").read())\n        set_input(\"data\", tvm.nd.array(data, device=dev))\n        load_params(loaded_params)\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        loaded_params = bytearray(open(path_params, \"rb\").read())\n        gmod.set_input(\"data\", data)\n        gmod.load_params(loaded_params)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    def verify_rpc_gpu_remove_package_params(obj_format):\n        if not tvm.testing.device_enabled(\"cuda\"):\n            print(\"Skip because cuda is not enabled\")\n            return\n        mod, params = relay.testing.synthetic.get_workload()\n        with relay.build_config(opt_level=3):\n            complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n\n        from tvm.contrib import utils\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        complied_graph_lib_no_params = complied_graph_lib[\"remove_params\"]()\n        complied_graph_lib_no_params.export_library(path_lib)\n        path_params = temp.relpath(\"deploy_param.params\")\n        with open(path_params, \"wb\") as fo:\n            fo.write(runtime.save_param_dict(complied_graph_lib.get_params()))\n\n        from tvm import rpc\n\n        remote = rpc.LocalSession()\n        remote.upload(path_lib)\n        loaded_lib = remote.load_module(path_lib)\n        data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n        dev = remote.cuda()\n\n        # raw api\n        gmod = loaded_lib[\"default\"](dev)\n        set_input = gmod[\"set_input\"]\n        run = gmod[\"run\"]\n        get_output = gmod[\"get_output\"]\n        load_params = gmod[\"load_params\"]\n        loaded_params = bytearray(open(path_params, \"rb\").read())\n        set_input(\"data\", tvm.nd.array(data, device=dev))\n        load_params(loaded_params)\n        run()\n        out = get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n        # graph executor wrapper\n        gmod = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n        loaded_params = bytearray(open(path_params, \"rb\").read())\n        gmod.set_input(\"data\", data)\n        gmod.load_params(loaded_params)\n        gmod.run()\n        out = gmod.get_output(0).numpy()\n        tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    for obj_format in [\".so\", \".tar\"]:\n        verify_cpu_remove_package_params(obj_format)\n        verify_gpu_remove_package_params(obj_format)\n        verify_rpc_cpu_remove_package_params(obj_format)\n        verify_rpc_gpu_remove_package_params(obj_format)\n\n\n@tvm.testing.requires_llvm\ndef test_debug_graph_executor():\n    mod, params = relay.testing.synthetic.get_workload()\n    with relay.build_config(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"llvm\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n\n    # raw api\n    dev = tvm.cpu()\n    try:\n        gmod = complied_graph_lib[\"debug_create\"](\"default\", dev)\n    except:\n        print(\"Skip because debug graph_executor not enabled\")\n        return\n    set_input = gmod[\"set_input\"]\n    run = gmod[\"run\"]\n    get_output = gmod[\"get_output\"]\n    set_input(\"data\", tvm.nd.array(data))\n    run()\n    out = get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    # debug graph executor wrapper\n    debug_g_mod = debug_executor.GraphModuleDebug(\n        complied_graph_lib[\"debug_create\"](\"default\", dev),\n        [dev],\n        complied_graph_lib.get_graph_json(),\n        None,\n    )\n    debug_g_mod.set_input(\"data\", data)\n    debug_g_mod.run()\n    out = debug_g_mod.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.requires_cudagraph\ndef test_cuda_graph_executor():\n    mod, params = relay.testing.synthetic.get_workload()\n    with tvm.transform.PassContext(opt_level=3):\n        complied_graph_lib = relay.build_module.build(mod, \"cuda\", params=params)\n    data = np.random.uniform(-1, 1, size=input_shape(mod)).astype(\"float32\")\n\n    dev = tvm.cuda()\n    try:\n        gmod = complied_graph_lib[\"cuda_graph_create\"](dev)\n    except:\n        print(\"Skip because cuda_graph not enabled\")\n        return\n    set_input = gmod[\"set_input\"]\n    run = gmod[\"run\"]\n    get_output = gmod[\"get_output\"]\n    set_input(\"data\", tvm.nd.array(data))\n    run()\n    out = get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n    # cuda graph executor wrapper\n    cu_gmod = cuda_graph_executor.GraphModuleCudaGraph(gmod)\n    cu_gmod.set_input(\"data\", data)\n    cu_gmod.run()\n    out = cu_gmod.get_output(0).numpy()\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\ndef test_multiple_imported_modules():\n    def make_func(symbol):\n        n = tvm.te.size_var(\"n\")\n        Ab = tvm.tir.decl_buffer((n,), dtype=\"float32\")\n        i = tvm.te.var(\"i\")\n        stmt = tvm.tir.For(\n            i,\n            0,\n            n - 1,\n            tvm.tir.ForKind.SERIAL,\n            tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1]),\n        )\n        return tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", symbol)\n\n    def make_module(mod):\n        mod = tvm.IRModule(mod)\n        mod = tvm.driver.build(mod, target=\"llvm\")\n        return mod\n\n    module_main = make_module({\"main\": make_func(\"main\")})\n    module_a = make_module({\"func_a\": make_func(\"func_a\")})\n    module_b = make_module({\"func_b\": make_func(\"func_b\")})\n    module_main.import_module(module_a)\n    module_main.import_module(module_b)\n    module_main.get_function(\"func_a\", query_imports=True)\n    module_main.get_function(\"func_b\", query_imports=True)\n\n\ndef test_num_threads():\n    reported = tvm.runtime.num_threads()\n    env_threads = os.getenv(\"TVM_NUM_THREADS\")\n    omp_env_threads = os.getenv(\"OMP_NUM_THREADS\")\n    if env_threads is not None:\n        assert reported == env_threads\n    elif omp_env_threads is not None:\n        assert reported == omp_env_threads\n    else:\n        hardware_threads = os.cpu_count()\n        assert reported == hardware_threads or reported == hardware_threads // 2\n\n\nif __name__ == \"__main__\":\n    test_legacy_compatibility()\n    test_cpu()\n    test_gpu()\n    test_mod_export()\n    test_remove_package_params()\n    test_debug_graph_executor()\n    test_multiple_imported_modules()\n    test_cpu_get_graph_json()\n    test_cpu_get_graph_params_run()\n    test_cpu_get_graph_params_compare()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_module_export.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm import relay\nfrom tvm.relay import testing\nimport tvm\nfrom tvm import te\nimport tvm.testing\n\nfrom tvm.contrib import utils\n\nheader_file_dir_path = utils.tempdir()\n\n\ndef gen_engine_header():\n    code = r\"\"\"\n        #ifndef _ENGINE_H_\n        #define _ENGINE_H_\n        #include <cstdint>\n        #include <string>\n        #include <sstream>\n        #include <vector>\n        class Engine {\n        };\n\n        #endif\n        \"\"\"\n    header_file = header_file_dir_path.relpath(\"gcc_engine.h\")\n    with open(header_file, \"w\") as f:\n        f.write(code)\n\n\ndef generate_engine_module():\n    code = r\"\"\"\n        #include <tvm/runtime/c_runtime_api.h>\n        #include <dlpack/dlpack.h>\n        #include \"gcc_engine.h\"\n\n        extern \"C\" void gcc_1_(float* gcc_input4, float* gcc_input5,\n                float* gcc_input6, float* gcc_input7, float* out) {\n            Engine engine;\n        }\n        \"\"\"\n    import tvm.runtime._ffi_api\n\n    gen_engine_header()\n    csource_module = tvm.runtime._ffi_api.CSourceModuleCreate(code, \"cc\", [], None)\n    return csource_module\n\n\n@tvm.testing.uses_gpu\ndef test_mod_export():\n    def verify_gpu_mod_export(obj_format):\n        for device in [\"llvm\", \"cuda\"]:\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled...\" % device)\n                return\n\n        synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload()\n        synthetic_llvm_mod, synthetic_llvm_params = relay.testing.synthetic.get_workload()\n        with tvm.transform.PassContext(opt_level=3):\n            _, synthetic_gpu_lib, _ = relay.build_module.build(\n                synthetic_mod, \"cuda\", params=synthetic_params, mod_name=\"cudalib\"\n            )\n            _, synthetic_llvm_cpu_lib, _ = relay.build_module.build(\n                synthetic_llvm_mod, \"llvm\", params=synthetic_llvm_params, mod_name=\"llvmlib\"\n            )\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        synthetic_gpu_lib.import_module(synthetic_llvm_cpu_lib)\n        synthetic_gpu_lib.export_library(path_lib)\n        loaded_lib = tvm.runtime.load_module(path_lib)\n        assert loaded_lib.type_key == \"library\"\n        assert loaded_lib.imported_modules[0].type_key == \"cuda\"\n        #  dso modules are merged together\n        assert len(loaded_lib.imported_modules) == 1\n\n    def verify_multi_dso_mod_export(obj_format):\n        for device in [\"llvm\"]:\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled...\" % device)\n                return\n\n        A = te.placeholder((1024,), name=\"A\")\n        B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n        s = te.create_schedule(B.op)\n        mod0 = tvm.build(s, [A, B], \"llvm\", name=\"myadd0\")\n        mod1 = tvm.build(s, [A, B], \"llvm\", name=\"myadd1\")\n\n        temp = utils.tempdir()\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n\n        mod0.import_module(mod1)\n        mod0.export_library(path_lib)\n        loaded_lib = tvm.runtime.load_module(path_lib)\n        assert loaded_lib.type_key == \"library\"\n        # dso modules are merged\n        assert len(loaded_lib.imported_modules) == 0\n\n    def verify_json_import_dso(obj_format):\n        for device in [\"llvm\"]:\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled...\" % device)\n                return\n\n        # Get subgraph Json.\n        subgraph_json = (\n            \"json_rt_0\\n\"\n            + \"input 0 10 10\\n\"\n            + \"input 1 10 10\\n\"\n            + \"input 2 10 10\\n\"\n            + \"input 3 10 10\\n\"\n            + \"add 4 inputs: 0 1 shape: 10 10\\n\"\n            + \"sub 5 inputs: 4 2 shape: 10 10\\n\"\n            + \"mul 6 inputs: 5 3 shape: 10 10\\n\"\n            + \"json_rt_1\\n\"\n            + \"input 0 10 10\\n\"\n            + \"input 1 10 10\\n\"\n            + \"input 2 10 10\\n\"\n            + \"input 3 10 10\\n\"\n            + \"add 4 inputs: 0 1 shape: 10 10\\n\"\n            + \"sub 5 inputs: 4 2 shape: 10 10\\n\"\n            + \"mul 6 inputs: 5 3 shape: 10 10\"\n        )\n\n        temp = utils.tempdir()\n        subgraph_path = temp.relpath(\"subgraph.examplejson\")\n        with open(subgraph_path, \"w\") as f:\n            f.write(subgraph_json)\n\n        # Get Json and module.\n        A = te.placeholder((1024,), name=\"A\")\n        B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n        try:\n            ext_lib = tvm.runtime.load_module(subgraph_path, \"examplejson\")\n        except:\n            print(\"skip because Loader of examplejson is not presented\")\n            return\n        ext_lib.import_module(f)\n        if obj_format == \".so\":\n            file_name = \"deploy_lib.so\"\n        else:\n            assert obj_format == \".tar\"\n            file_name = \"deploy_lib.tar\"\n        path_lib = temp.relpath(file_name)\n        ext_lib.export_library(path_lib)\n        lib = tvm.runtime.load_module(path_lib)\n        assert lib.type_key == \"examplejson\"\n        assert lib.imported_modules[0].type_key == \"library\"\n\n    def verify_multi_c_mod_export():\n        from shutil import which\n\n        if which(\"gcc\") is None:\n            print(\"Skip test because gcc is not available.\")\n\n        for device in [\"llvm\"]:\n            if not tvm.testing.device_enabled(device):\n                print(\"skip because %s is not enabled...\" % device)\n                return\n\n        synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload()\n        with tvm.transform.PassContext(opt_level=3):\n            _, synthetic_cpu_lib, _ = relay.build_module.build(\n                synthetic_mod, \"llvm\", params=synthetic_params\n            )\n\n        A = te.placeholder((1024,), name=\"A\")\n        B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], \"c\", name=\"myadd\")\n        engine_module = generate_engine_module()\n\n        temp = utils.tempdir()\n        file_name = \"deploy_lib.so\"\n        path_lib = temp.relpath(file_name)\n        synthetic_cpu_lib.import_module(f)\n        synthetic_cpu_lib.import_module(engine_module)\n        kwargs = {\"options\": [\"-O2\", \"-std=c++17\", \"-I\" + header_file_dir_path.relpath(\"\")]}\n        synthetic_cpu_lib.export_library(path_lib, fcompile=False, **kwargs)\n        loaded_lib = tvm.runtime.load_module(path_lib)\n        assert loaded_lib.type_key == \"library\"\n        # dso modules are merged\n        assert len(loaded_lib.imported_modules) == 0\n\n    for obj_format in [\".so\", \".tar\"]:\n        verify_gpu_mod_export(obj_format)\n        verify_multi_dso_mod_export(obj_format)\n        verify_json_import_dso(obj_format)\n\n    verify_multi_c_mod_export()\n\n\n@tvm.testing.requires_llvm\ndef test_import_static_library():\n    # Generate two LLVM modules.\n    A = te.placeholder((1024,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    mod0 = tvm.build(s, [A, B], \"llvm\", name=\"myadd0\")\n    mod1 = tvm.build(s, [A, B], \"llvm\", name=\"myadd1\")\n\n    assert mod0.implements_function(\"myadd0\")\n    assert mod1.implements_function(\"myadd1\")\n    assert mod1.is_dso_exportable\n\n    # mod1 is currently an 'llvm' module.\n    # Save and reload it as a vanilla 'static_library'.\n    temp = utils.tempdir()\n    mod1_o_path = temp.relpath(\"mod1.o\")\n    mod1.save(mod1_o_path)\n    mod1_o = tvm.runtime.load_static_library(mod1_o_path, [\"myadd1\"])\n    assert mod1_o.implements_function(\"myadd1\")\n    assert mod1_o.is_dso_exportable\n\n    # Import mod1 as a static library into mod0 and compile to its own DSO.\n    mod0.import_module(mod1_o)\n    mod0_dso_path = temp.relpath(\"mod0.so\")\n    mod0.export_library(mod0_dso_path)\n\n    # The imported mod1 is statically linked into mod0.\n    loaded_lib = tvm.runtime.load_module(mod0_dso_path)\n    assert loaded_lib.type_key == \"library\"\n    assert len(loaded_lib.imported_modules) == 0\n    assert loaded_lib.implements_function(\"myadd0\")\n    assert loaded_lib.get_function(\"myadd0\")\n    assert loaded_lib.implements_function(\"myadd1\")\n    assert loaded_lib.get_function(\"myadd1\")\n    assert not loaded_lib.is_dso_exportable\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_module_load.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import cc, utils\nimport ctypes\nimport sys\nimport numpy as np\nimport subprocess\nimport tvm.testing\nfrom tvm.relay.backend import Runtime\n\nruntime_py = \"\"\"\nimport os\nimport sys\n\nos.environ[\"TVM_USE_RUNTIME_LIB\"] = \"1\"\nos.environ[\"TVM_FFI\"] = \"ctypes\"\nimport tvm\nfrom tvm import te\nimport numpy as np\npath_dso = sys.argv[1]\ndtype = sys.argv[2]\nff = tvm.runtime.load_module(path_dso)\na = tvm.nd.array(np.zeros(10, dtype=dtype))\nff(a)\nnp.testing.assert_equal(a.numpy(), np.arange(a.shape[0]))\nprint(\"Finish runtime checking...\")\n\"\"\"\n\n\ndef test_dso_module_load():\n    if not tvm.testing.device_enabled(\"llvm\"):\n        return\n    dtype = \"int64\"\n    temp = utils.tempdir()\n\n    def save_object(names):\n        n = te.size_var(\"n\")\n        Ab = tvm.tir.decl_buffer((n,), dtype)\n        i = te.var(\"i\")\n        # for i in 0 to n-1:\n        stmt = tvm.tir.For(\n            i,\n            0,\n            n - 1,\n            tvm.tir.ForKind.SERIAL,\n            tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1]),\n        )\n        mod = tvm.IRModule.from_expr(\n            tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"main\")\n        )\n        m = tvm.driver.build(mod, target=\"llvm\")\n        for name in names:\n            m.save(name)\n\n    path_obj = temp.relpath(\"test.o\")\n    path_ll = temp.relpath(\"test.ll\")\n    path_bc = temp.relpath(\"test.bc\")\n    path_dso = temp.relpath(\"test.so\")\n    save_object([path_obj, path_ll, path_bc])\n    cc.create_shared(path_dso, [path_obj])\n\n    f1 = tvm.runtime.load_module(path_dso)\n    f2 = tvm.runtime.load_module(path_ll)\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n    f1(a)\n    np.testing.assert_equal(a.numpy(), np.arange(a.shape[0]))\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n    f2(a)\n    np.testing.assert_equal(a.numpy(), np.arange(a.shape[0]))\n\n    path_runtime_py = temp.relpath(\"runtime.py\")\n    with open(path_runtime_py, \"w\") as fo:\n        fo.write(runtime_py)\n\n    proc = subprocess.run(\n        [sys.executable, path_runtime_py, path_dso, dtype],\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n    )\n    assert proc.returncode == 0, f\"{proc.args} exited with {proc.returncode}: {proc.stdout}\"\n\n\n@tvm.testing.requires_gpu\ndef test_device_module_dump():\n    # graph\n    n = tvm.runtime.convert(1024)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    # create iter var and assign them tags.\n    num_thread = 8\n    bx, tx = s[B].split(B.op.axis[0], factor=num_thread)\n    s[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        temp = utils.tempdir()\n        name = \"myadd_%s\" % device\n        if sys.platform == \"darwin\" or sys.platform.startswith(\"linux\"):\n            runtime = Runtime(\"cpp\", {\"system-lib\": True})\n            f = tvm.build(s, [A, B], device, \"llvm\", runtime=runtime, name=name)\n        elif sys.platform == \"win32\":\n            f = tvm.build(s, [A, B], device, \"llvm\", name=name)\n        else:\n            raise ValueError(\"Unsupported platform\")\n\n        path_dso = temp.relpath(\"dev_lib.so\")\n        # test cross compiler function\n        f.export_library(path_dso, cc.cross_compiler(\"g++\"))\n\n        f1 = tvm.runtime.load_module(path_dso)\n        a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n        f1(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n        if sys.platform != \"win32\":\n            f2 = tvm.runtime.system_lib()\n            f2[name](a, b)\n            np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    def check_stackvm(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        temp = utils.tempdir()\n        name = \"myadd_%s\" % device\n        f = tvm.build(s, [A, B], device, \"stackvm\", name=name)\n        path_dso = temp.relpath(\"dev_lib.stackvm\")\n        f.export_library(path_dso)\n        f1 = tvm.runtime.load_module(path_dso)\n        a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n        f(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    for device in [\"cuda\", \"vulkan\", \"opencl\", \"metal\"]:\n        check_device(device)\n        check_stackvm(device)\n\n\ndef test_combine_module_llvm():\n    \"\"\"Test combine multiple module into one shared lib.\"\"\"\n    # graph\n    nn = 12\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    def check_llvm():\n        dev = tvm.cpu(0)\n        if not tvm.testing.device_enabled(\"llvm\"):\n            print(\"Skip because llvm is not enabled\")\n            return\n        temp = utils.tempdir()\n        fadd1 = tvm.build(s, [A, B], \"llvm\", name=\"myadd1\")\n        fadd2 = tvm.build(s, [A, B], \"llvm\", name=\"myadd2\")\n        path1 = temp.relpath(\"myadd1.o\")\n        path2 = temp.relpath(\"myadd2.o\")\n        path_dso = temp.relpath(\"mylib.so\")\n        fadd1.save(path1)\n        fadd2.save(path2)\n        # create shared library with multiple functions\n        cc.create_shared(path_dso, [path1, path2])\n        m = tvm.runtime.load_module(path_dso)\n        fadd1 = m[\"myadd1\"]\n        fadd2 = m[\"myadd2\"]\n        a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev)\n        fadd1(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n        fadd2(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    def check_system_lib():\n        dev = tvm.cpu(0)\n        if not tvm.testing.device_enabled(\"llvm\"):\n            print(\"Skip because llvm is not enabled\")\n            return\n        temp = utils.tempdir()\n        runtime = Runtime(\"cpp\", {\"system-lib\": True})\n        fadd1 = tvm.build(s, [A, B], \"llvm\", runtime=runtime, name=\"myadd1\")\n        fadd2 = tvm.build(s, [A, B], \"llvm\", runtime=runtime, name=\"myadd2\")\n        path1 = temp.relpath(\"myadd1.o\")\n        path2 = temp.relpath(\"myadd2.o\")\n        path_dso = temp.relpath(\"mylib.so\")\n        fadd1.save(path1)\n        fadd2.save(path2)\n        cc.create_shared(path_dso, [path1, path2])\n        # Load dll, will trigger system library registration\n        ctypes.CDLL(path_dso)\n        # Load the system wide library\n        mm = tvm.runtime.system_lib()\n        a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev)\n        mm[\"myadd1\"](a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n        mm[\"myadd2\"](a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    if sys.platform != \"win32\":\n        check_system_lib()\n    check_llvm()\n\n\nif __name__ == \"__main__\":\n    test_combine_module_llvm()\n    test_device_module_dump()\n    test_dso_module_load()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_profiling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport pytest\nfrom io import StringIO\nimport csv\nimport os\nimport json\nimport platform\n\nimport tvm.testing\nimport tvm.utils\nfrom tvm.runtime import profiler_vm\nfrom tvm import relay\nfrom tvm.relay.testing import mlp\nfrom tvm.contrib.debugger import debug_executor\nfrom tvm import rpc\nfrom tvm.contrib import utils\nfrom tvm.runtime.profiling import Report\nfrom tvm.script import tir as T\n\n\ndef read_csv(report):\n    f = StringIO(report.csv())\n    headers = []\n    rows = []\n    reader = csv.reader(f, delimiter=\",\")\n    # force parsing\n    in_header = True\n    for row in reader:\n        if in_header:\n            headers = row\n            in_header = False\n            rows = [[] for x in headers]\n        else:\n            for i in range(len(row)):\n                rows[i].append(row[i])\n    return dict(zip(headers, rows))\n\n\n@pytest.mark.skipif(not profiler_vm.enabled(), reason=\"VM Profiler not enabled\")\n@tvm.testing.skip_if_wheel_test\n@tvm.testing.parametrize_targets\ndef test_vm(target, dev):\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=(relay.Any(), relay.Any()), dtype=dtype)\n    y = relay.var(\"y\", shape=(relay.Any(), relay.Any()), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x, y], relay.add(x, y))\n    exe = relay.vm.compile(mod, target)\n    vm = profiler_vm.VirtualMachineProfiler(exe, dev)\n\n    data = np.random.rand(28, 28).astype(\"float32\")\n    report = vm.profile(data, data, func_name=\"main\")\n    assert \"fused_add\" in str(report)\n    assert \"Total\" in str(report)\n    assert \"AllocTensorReg\" in str(report)\n    assert \"AllocStorage\" in str(report)\n    assert report.configuration[\"Executor\"] == \"VM\"\n\n    csv = read_csv(report)\n    assert \"Hash\" in csv.keys()\n    # Ops should have a duration greater than zero.\n    assert all(\n        [\n            float(dur) > 0\n            for dur, name in zip(csv[\"Duration (us)\"], csv[\"Name\"])\n            if name[:5] == \"fused\"\n        ]\n    )\n    # AllocTensor or AllocStorage may be cached, so their duration could be 0.\n    assert all(\n        [\n            float(dur) >= 0\n            for dur, name in zip(csv[\"Duration (us)\"], csv[\"Name\"])\n            if name[:5] != \"fused\"\n        ]\n    )\n\n\n@tvm.testing.parametrize_targets\ndef test_graph_executor(target, dev):\n    mod, params = mlp.get_workload(1)\n\n    exe = relay.build(mod, target, params=params)\n    gr = debug_executor.create(exe.get_graph_json(), exe.lib, dev)\n\n    data = np.random.rand(1, 1, 28, 28).astype(\"float32\")\n    report = gr.profile(data=data)\n    assert \"fused_nn_softmax\" in str(report)\n    assert \"Total\" in str(report)\n    assert \"Hash\" in str(report)\n    assert \"Graph\" in str(report)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"llvm\")\n@pytest.mark.skipif(\n    tvm.get_global_func(\"runtime.profiling.PAPIMetricCollector\", allow_missing=True) is None,\n    reason=\"PAPI profiling not enabled\",\n)\ndef test_papi(target, dev):\n    target = tvm.target.Target(target)\n    if str(target.kind) == \"llvm\":\n        metric = \"PAPI_FP_OPS\"\n    elif str(target.kind) == \"cuda\":\n        metric = \"cuda:::event:shared_load:device=0\"\n    else:\n        pytest.skip(f\"Target {target.kind} not supported by this test\")\n    mod, params = mlp.get_workload(1)\n\n    exe = relay.vm.compile(mod, target, params=params)\n    vm = profiler_vm.VirtualMachineProfiler(exe, dev)\n\n    data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype(\"float32\"), device=dev)\n    report = vm.profile(\n        data,\n        func_name=\"main\",\n        collectors=[tvm.runtime.profiling.PAPIMetricCollector({dev: [metric]})],\n    )\n    assert metric in str(report)\n\n    csv = read_csv(report)\n    assert metric in csv.keys()\n    assert any([float(x) > 0 for x in csv[metric]])\n\n\n@tvm.testing.requires_llvm\ndef test_json():\n    mod, params = mlp.get_workload(1)\n\n    exe = relay.vm.compile(mod, \"llvm\", params=params)\n    vm = profiler_vm.VirtualMachineProfiler(exe, tvm.cpu())\n\n    data = np.random.rand(1, 1, 28, 28).astype(\"float32\")\n    report = vm.profile(data, func_name=\"main\")\n    parsed = json.loads(report.json())\n    assert \"device_metrics\" in parsed\n    assert \"calls\" in parsed\n    assert \"configuration\" in parsed\n    assert \"Duration (us)\" in parsed[\"calls\"][0]\n    assert \"microseconds\" in parsed[\"calls\"][0][\"Duration (us)\"]\n    assert len(parsed[\"calls\"]) > 0\n    for call in parsed[\"calls\"]:\n        assert isinstance(call[\"Name\"][\"string\"], str)\n        assert isinstance(call[\"Count\"][\"count\"], int)\n        assert isinstance(call[\"Duration (us)\"][\"microseconds\"], float)\n\n\n@tvm.testing.requires_llvm\ndef test_rpc_vm():\n    server = rpc.Server(key=\"profiling\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"profiling\")\n\n    mod, params = mlp.get_workload(1)\n    exe = relay.vm.compile(mod, \"llvm\", params=params)\n    temp = utils.tempdir()\n    path = temp.relpath(\"lib.tar\")\n    exe.mod.export_library(path)\n    remote.upload(path)\n    rexec = remote.load_module(\"lib.tar\")\n    vm = profiler_vm.VirtualMachineProfiler(rexec, remote.cpu())\n    report = vm.profile(tvm.nd.array(np.ones((1, 1, 28, 28), dtype=\"float32\"), device=remote.cpu()))\n    assert len(report.calls) > 0\n\n\ndef test_rpc_graph():\n    server = rpc.Server(key=\"profiling\")\n    remote = rpc.connect(\"127.0.0.1\", server.port, key=\"profiling\")\n\n    mod, params = mlp.get_workload(1)\n    exe = relay.build(mod, \"llvm\", params=params)\n    temp = utils.tempdir()\n    path = temp.relpath(\"lib.tar\")\n    exe.export_library(path)\n    remote.upload(path)\n    rexec = remote.load_module(\"lib.tar\")\n\n    gr = debug_executor.create(exe.get_graph_json(), rexec, remote.cpu())\n\n    data = np.random.rand(1, 1, 28, 28).astype(\"float32\")\n    report = gr.profile(data=data)\n    assert len(report.calls) > 0\n\n\ndef test_report_serialization():\n    mod, params = mlp.get_workload(1)\n\n    exe = relay.vm.compile(mod, \"llvm\", params=params)\n    vm = profiler_vm.VirtualMachineProfiler(exe, tvm.cpu())\n\n    data = np.random.rand(1, 1, 28, 28).astype(\"float32\")\n    report = vm.profile(data, func_name=\"main\")\n\n    report2 = Report.from_json(report.json())\n    # Equality on reports compares pointers, so we compare the printed\n    # results instead.\n\n    # Use .table() instead of str(), because str() includes aggregate\n    # and column summations whose values may be impacted by otherwise\n    # negligible conversion errors. (2 occurrences / 3000 trials)\n    assert report.table(aggregate=False, col_sums=False) == report2.table(\n        aggregate=False, col_sums=False\n    )\n\n\n@T.prim_func\ndef axpy_cpu(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [10], \"float64\")\n    B = T.match_buffer(b, [10], \"float64\")\n    C = T.match_buffer(c, [10], \"float64\")\n    for i in range(10):\n        C[i] = A[i] + B[i]\n\n\n@T.prim_func\ndef axpy_gpu(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [10], \"float64\")\n    B = T.match_buffer(b, [10], \"float64\")\n    C = T.match_buffer(c, [10], \"float64\")\n    for i in T.thread_binding(0, 10, \"threadIdx.x\"):\n        C[i] = A[i] + B[i]\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"llvm\")\n@pytest.mark.skipif(\n    tvm.get_global_func(\"runtime.profiling.PAPIMetricCollector\", allow_missing=True) is None,\n    reason=\"PAPI profiling not enabled\",\n)\ndef test_profile_function(target, dev):\n    target = tvm.target.Target(target)\n    if str(target.kind) == \"llvm\":\n        metric = \"PAPI_FP_OPS\"\n        func = axpy_cpu\n    elif str(target.kind) == \"cuda\":\n        metric = (\n            \"cuda:::gpu__compute_memory_access_throughput.max.pct_of_peak_sustained_region:device=0\"\n        )\n        func = axpy_gpu\n    else:\n        pytest.skip(f\"Target {target.kind} not supported by this test\")\n    f = tvm.build(func, target=target)\n    a = tvm.nd.array(np.ones(10), device=dev)\n    b = tvm.nd.array(np.ones(10), device=dev)\n    c = tvm.nd.array(np.zeros(10), device=dev)\n    report = tvm.runtime.profiling.profile_function(\n        f, dev, [tvm.runtime.profiling.PAPIMetricCollector({dev: [metric]})]\n    )(a, b, c)\n    assert metric in report.keys()\n    assert report[metric].value > 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport tvm.testing\nimport multiprocessing\nimport os\nimport stat\nimport sys\nimport time\n\nimport pytest\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.relay.backend import Runtime\nfrom tvm.contrib import utils, cc\nfrom tvm.rpc.tracker import Tracker\nfrom tvm.rpc.proxy import Proxy\n\n\nif __name__ == \"__main__\":\n    # NOTE: must live here to avoid registering PackedFunc with libtvm.so twice.\n    tvm.testing.main()\n\n\n# tkonolige: The issue as I understand it is this: multiprocessing's spawn\n# method launches a new process and then imports the relevant modules. This\n# means that all registered functions must exist at the top level scope. In\n# this file they are, so all is well when we run this file directly.\n# However, when run under pytest, the functions aren't registered on the\n# server. I believe this is because pytest is also using multiprocessing to\n# run individual functions. Somewhere along the way, the imports are being\n# lost, so the server ends up not registering the functions.\npytestmark = pytest.mark.skipif(\n    # Windows does not support fork so we can enable Windows for testing\n    sys.platform.startswith(\"win\") == False and multiprocessing.get_start_method() != \"fork\",\n    reason=(\n        \"pytest + multiprocessing spawn method causes tvm.register_func to \"\n        \"not work on the rpc.Server.\"\n    ),\n)\n\n# NOTE: When writing tests, wrap remote related checking in a sub-function\n# to ensure all the remote resources destructs before the server terminates\n\n\n@tvm.testing.requires_rpc\ndef test_bigendian_rpc():\n    \"\"\"Test big endian rpc when there is a PowerPC RPC server available\"\"\"\n    host = os.environ.get(\"TVM_POWERPC_TEST_HOST\", None)\n    port = os.environ.get(\"TVM_POWERPC_TEST_PORT\", 9090)\n    if host is None:\n        return\n\n    def verify_rpc(remote, target, shape, dtype):\n        A = te.placeholder(shape, dtype=dtype)\n        B = te.compute(A.shape, lambda i: A[i] + tvm.tir.const(1, A.dtype))\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], target, name=\"myadd\")\n\n        dev = remote.cpu(0)\n        a = tvm.nd.array(np.random.randint(0, 256, size=shape).astype(A.dtype), device=dev)\n        b = tvm.nd.array(np.zeros(shape).astype(A.dtype), device=dev)\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"dev_lib.o\")\n        f.save(path_dso)\n        remote.upload(path_dso)\n        f = remote.load_module(\"dev_lib.o\")\n        f(a, b)\n        tvm.testing.assert_allclose(a.numpy() + 1, b.numpy())\n\n    print(\"Test RPC connection to PowerPC...\")\n    remote = rpc.connect(host, port)\n    target = \"llvm -mtriple=powerpc-linux-gnu\"\n    for dtype in [\"float32\", \"float64\", \"int32\", \"int8\"]:\n        verify_rpc(remote, target, (10,), dtype)\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_simple():\n    server = rpc.Server(key=\"x1\")\n    client = rpc.connect(\"127.0.0.1\", server.port, key=\"x1\")\n\n    def check_remote():\n        f1 = client.get_function(\"rpc.test.addone\")\n        assert f1(10) == 11\n        f3 = client.get_function(\"rpc.test.except\")\n\n        with pytest.raises(tvm._ffi.base.TVMError):\n            f3(\"abc\")\n\n        f2 = client.get_function(\"rpc.test.strcat\")\n        assert f2(\"abc\", 11) == \"abc:11\"\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_simple_wlog():\n    server = rpc.Server(key=\"x1\")\n    client = rpc.connect(\"127.0.0.1\", server.port, key=\"x1\", enable_logging=True)\n\n    def check_remote():\n        f1 = client.get_function(\"rpc.test.addone\")\n        assert f1(10) == 11\n        f3 = client.get_function(\"rpc.test.except\")\n\n        with pytest.raises(tvm._ffi.base.TVMError):\n            f3(\"abc\")\n\n        f2 = client.get_function(\"rpc.test.strcat\")\n        assert f2(\"abc\", 11) == \"abc:11\"\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_runtime_string():\n    server = rpc.Server(key=\"x1\")\n    client = rpc.connect(\"127.0.0.1\", server.port, key=\"x1\")\n\n    def check_remote():\n        func = client.get_function(\"rpc.test.runtime_str_concat\")\n        x = tvm.runtime.container.String(\"abc\")\n        y = tvm.runtime.container.String(\"def\")\n        assert str(func(x, y)) == \"abcdef\"\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_array():\n    server = rpc.Server()\n    remote = rpc.connect(\"127.0.0.1\", server.port)\n\n    def check_remote():\n        x = np.ones((3, 4))\n        r_cpu = tvm.nd.array(x, remote.cpu(0))\n        assert str(r_cpu.device).startswith(\"remote\")\n        np.testing.assert_equal(r_cpu.numpy(), x)\n        fremote = remote.get_function(\"rpc.test.remote_array_func\")\n        fremote(r_cpu)\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_large_array():\n    # testcase of large array creation\n    server = rpc.Server()\n    remote = rpc.connect(\"127.0.0.1\", server.port)\n\n    def check_remote():\n        dev = remote.cpu(0)\n        a_np = np.ones((5041, 720)).astype(\"float32\")\n        b_np = np.ones((720, 192)).astype(\"float32\")\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        np.testing.assert_equal(a.numpy(), a_np)\n        np.testing.assert_equal(b.numpy(), b_np)\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_echo():\n    def check(remote):\n        fecho = remote.get_function(\"testing.echo\")\n        assert fecho(1, 2, 3) == 1\n        assert fecho(100, 2, 3) == 100\n        assert fecho(\"xyz\") == \"xyz\"\n        assert bytes(fecho(bytearray(b\"123\"))) == b\"123\"\n\n        with pytest.raises(RuntimeError):\n            raise_err = remote.get_function(\"testing.test_raise_error_callback\")(\"RuntimeError\")\n            raise_err()\n\n        remote.cpu().sync()\n        with pytest.raises(AttributeError):\n            f3 = remote.system_lib()[\"notexist\"]\n\n    temp = rpc.server._server_env([])\n    server = rpc.Server()\n    client = rpc.connect(\"127.0.0.1\", server.port)\n    check(rpc.LocalSession())\n\n    check(client)\n\n    def check_minrpc():\n        if tvm.get_global_func(\"rpc.CreatePipeClient\", allow_missing=True) is None:\n            return\n        # Test minrpc server.\n        temp = utils.tempdir()\n        minrpc_exec = temp.relpath(\"minrpc\")\n        tvm.rpc.with_minrpc(cc.create_executable)(minrpc_exec, [])\n        check(rpc.PopenSession(minrpc_exec))\n        # minrpc on the remote\n        server = rpc.Server()\n        client = rpc.connect(\n            \"127.0.0.1\",\n            server.port,\n            session_constructor_args=[\"rpc.PopenSession\", open(minrpc_exec, \"rb\").read()],\n        )\n        check(client)\n\n    check_minrpc()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_file_exchange():\n    server = rpc.Server()\n    remote = rpc.connect(\"127.0.0.1\", server.port)\n\n    def check_remote():\n        blob = bytearray(np.random.randint(0, 10, size=(10)))\n        remote.upload(blob, \"dat.bin\")\n        rev = remote.download(\"dat.bin\")\n        assert rev == blob\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\n@tvm.testing.requires_llvm\ndef test_rpc_remote_module():\n    # graph\n    n = tvm.runtime.convert(102)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    server0 = rpc.Server(key=\"x0\")\n    server1 = rpc.Server(key=\"x1\")\n\n    client = rpc.connect(\n        \"127.0.0.1\",\n        server0.port,\n        key=\"x0\",\n        session_constructor_args=[\"rpc.Connect\", \"127.0.0.1\", server1.port, \"x1\", False],\n    )\n\n    def check_remote(remote):\n        temp = utils.tempdir()\n        dev = remote.cpu(0)\n        f = tvm.build(s, [A, B], \"llvm\", name=\"myadd\")\n        path_dso = temp.relpath(\"dev_lib.so\")\n        f.export_library(path_dso)\n        remote.upload(path_dso)\n        f1 = remote.load_module(\"dev_lib.so\")\n        a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev)\n        time_f = f1.time_evaluator(f1.entry_name, remote.cpu(0), number=10)\n        cost = time_f(a, b).mean\n        print(\"%g secs/op\" % cost)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n        # Download the file from the remote\n        path_tar = temp.relpath(\"dev_lib.tar\")\n        f.export_library(path_tar)\n        remote.upload(path_tar)\n        local_download_path = temp.relpath(\"dev_lib.download.so\")\n        with open(local_download_path, \"wb\") as fo:\n            fo.write(remote.download_linked_module(\"dev_lib.tar\"))\n        fupdated = tvm.runtime.load_module(local_download_path)\n        a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), tvm.cpu(0))\n        b = tvm.nd.array(np.zeros(102, dtype=A.dtype), tvm.cpu(0))\n        fupdated(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    def check_minrpc():\n        if tvm.get_global_func(\"rpc.CreatePipeClient\", allow_missing=True) is None:\n            return\n        # export to minrpc\n        temp = utils.tempdir()\n        runtime = Runtime(\"cpp\", {\"system-lib\": True})\n        f = tvm.build(s, [A, B], \"llvm\", name=\"myadd\", runtime=runtime)\n        path_minrpc = temp.relpath(\"dev_lib.minrpc\")\n        f.export_library(path_minrpc, rpc.with_minrpc(cc.create_executable))\n\n        with pytest.raises(RuntimeError):\n            rpc.PopenSession(\"filenotexist\")\n\n        # statrt the minrpc session.\n        remote = tvm.rpc.PopenSession(path_minrpc)\n        dev = remote.cpu(0)\n        f1 = remote.system_lib()\n\n        a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev)\n        time_f = f1.time_evaluator(\"myadd\", remote.cpu(0), number=1)\n        cost = time_f(a, b).mean\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n        # change to not executable\n        os.chmod(path_minrpc, stat.S_IRUSR)\n        with pytest.raises(RuntimeError):\n            rpc.PopenSession(path_minrpc)\n\n    def check_remote_link_cl(remote):\n        \"\"\"Test function to run remote code such as cl\n\n        This is not enabled because there is forking issue\n        of TVM runtime when server launches after OpenCL\n        runtime initializes. We leave it as an example\n        on how to do rpc when we want to do linking on remote.\n        \"\"\"\n        if not tvm.testing.device_enabled(\"opencl\"):\n            print(\"Skip because opencl is not enabled\")\n            return\n        temp = utils.tempdir()\n        dev = remote.cl(0)\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=32)\n        s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n        s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n        f = tvm.build(s, [A, B], \"opencl --host=llvm\", name=\"myadd\")\n        # Option 1: save modules separately and rely on remote compiler\n        path_o = temp.relpath(\"myadd.o\")\n        path_cl = temp.relpath(\"myadd.cl\")\n        path_json = temp.relpath(\"myadd.tvm_meta.json\")\n        f.save(path_o)\n        f.imported_modules[0].save(path_cl)\n        remote.upload(path_o)\n        remote.upload(path_cl)\n        # upload meta data\n        remote.upload(path_json)\n        fhost = remote.load_module(\"myadd.o\")\n        fdev = remote.load_module(\"myadd.cl\")\n        fhost.import_module(fdev)\n        a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev)\n        fhost(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n        # Option 2: export library as a tar ball then handled by remote compiler\n        path_tar = temp.relpath(\"myadd.tar\")\n        f.export_library(path_tar)\n        remote.upload(path_tar)\n        fhost = remote.load_module(\"myadd.tar\")\n        a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev)\n        fhost(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    check_remote(rpc.LocalSession())\n    check_remote(client)\n    check_minrpc()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_return_func():\n    server = rpc.Server(key=\"x1\")\n    client = rpc.connect(\"127.0.0.1\", server.port, key=\"x1\")\n\n    def check_remote():\n        f1 = client.get_function(\"rpc.test.add_to_lhs\")\n        fadd = f1(10)\n        assert fadd(12) == 22\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_session_constructor_args():\n    # start server\n    server0 = rpc.Server(key=\"x0\")\n    server1 = rpc.Server(key=\"x1\")\n\n    def check_multi_hop():\n        # use server0 as proxy to connect to server1\n        client = rpc.connect(\n            \"127.0.0.1\",\n            server0.port,\n            key=\"x0\",\n            session_constructor_args=[\"rpc.Connect\", \"127.0.0.1\", server1.port, \"x1\", False],\n        )\n\n        fecho = client.get_function(\"testing.echo\")\n        assert fecho(1, 2, 3) == 1\n        assert fecho(100, 2, 3) == 100\n        assert fecho(\"xyz\") == \"xyz\"\n        assert bytes(fecho(bytearray(b\"123\"))) == b\"123\"\n\n        nd = tvm.nd.array([1, 2, 3], device=client.cpu(0))\n        assert nd.numpy()[1] == 2\n\n    def check_error_handling():\n        with pytest.raises(tvm.error.RPCError):\n            client = rpc.connect(\n                \"127.0.0.1\",\n                server0.port,\n                key=\"x0\",\n                session_constructor_args=[\"rpc.NonExistingConstructor\"],\n            )\n\n    check_multi_hop()\n    check_error_handling()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_return_ndarray():\n    # start server\n    server = rpc.Server(key=\"x1\")\n    client = rpc.connect(\"127.0.0.1\", server.port, key=\"x1\")\n\n    m = client.get_function(\"rpc.test.remote_return_nd\")\n    get_arr = m(\"get_arr\")\n    ref_count = m(\"ref_count\")\n    get_elem = m(\"get_elem\")\n    get_arr_elem = m(\"get_arr_elem\")\n    # array test\n    def run_arr_test():\n        arr = get_arr()\n        assert get_elem(0) == 0.0\n        assert get_arr_elem(arr, 0) == 0.0\n\n    run_arr_test()\n\n\n@tvm.testing.requires_rpc\ndef test_local_func():\n    client = rpc.LocalSession()\n\n    def check_remote():\n        f1 = client.get_function(\"rpc.test.add_to_lhs\")\n        fadd = f1(10)\n        assert fadd(12) == 22\n\n        blob = bytearray(np.random.randint(0, 10, size=(10)))\n        client.upload(blob, \"dat.bin\")\n        rev = client.download(\"dat.bin\")\n        assert rev == blob\n\n    check_remote()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_tracker_register():\n    # test registration\n    tracker = Tracker(port=9000, port_end=10000)\n    device_key = \"test_device\"\n    server1 = rpc.Server(\n        host=\"127.0.0.1\",\n        port=9000,\n        port_end=10000,\n        key=device_key,\n        tracker_addr=(\"127.0.0.1\", tracker.port),\n    )\n    server2 = rpc.Server(\n        host=\"127.0.0.1\",\n        port=9000,\n        port_end=10000,\n        key=device_key,\n        tracker_addr=(\"127.0.0.1\", tracker.port),\n        custom_addr=\"test_addr\",  # this is a test address, which is unable to connect\n    )\n    time.sleep(1)\n    client = rpc.connect_tracker(\"127.0.0.1\", tracker.port)\n\n    def exist_address(summary, key, host, port):\n        server_info = summary[\"server_info\"]\n        for device in server_info:\n            if device[\"key\"] == \"server:%s\" % key:\n                addr = device[\"addr\"]\n                if (host is None or host == addr[0]) and port == addr[1]:\n                    return True\n        return False\n\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 2\n    assert exist_address(summary, device_key, \"127.0.0.1\", server1.port)\n    assert exist_address(summary, device_key, \"test_addr\", server2.port)\n\n    remote = client.request(device_key)\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 1\n\n    del remote\n    time.sleep(1)\n\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 2\n\n    server1.terminate()\n    time.sleep(1)\n\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 1\n    assert not exist_address(summary, device_key, \"127.0.0.1\", server1.port)\n    assert exist_address(summary, device_key, \"test_addr\", server2.port)\n\n    server2.terminate()\n    time.sleep(1)\n\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 0\n    assert not exist_address(summary, device_key, \"test_addr\", server2.port)\n\n    tracker.terminate()\n\n\ndef _target(host, port, device_key, timeout):\n    client = rpc.connect_tracker(host, port)\n    remote = client.request(device_key, session_timeout=timeout)\n    while True:\n        pass\n    remote.cpu()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_tracker_request():\n    # test concurrent request\n    tracker = Tracker(port=9000, port_end=10000)\n    device_key = \"test_device\"\n    server = rpc.Server(\n        port=9000,\n        port_end=10000,\n        key=device_key,\n        tracker_addr=(\"127.0.0.1\", tracker.port),\n    )\n    client = rpc.connect_tracker(\"127.0.0.1\", tracker.port)\n\n    proc1 = multiprocessing.Process(target=_target, args=(\"127.0.0.1\", tracker.port, device_key, 4))\n    proc2 = multiprocessing.Process(\n        target=_target, args=(\"127.0.0.1\", tracker.port, device_key, 200)\n    )\n    proc1.start()\n    time.sleep(0.5)\n    proc2.start()\n    time.sleep(0.5)\n\n    summary = client.summary()\n\n    assert summary[\"queue_info\"][device_key][\"free\"] == 0\n    assert summary[\"queue_info\"][device_key][\"pending\"] == 1\n\n    proc1.terminate()\n    proc1.join()\n    time.sleep(0.5)\n\n    summary = client.summary()\n    assert summary[\"queue_info\"][device_key][\"free\"] == 0\n    assert summary[\"queue_info\"][device_key][\"pending\"] == 0\n\n    proc2.terminate()\n    proc2.join()\n    server.terminate()\n    tracker.terminate()\n\n\n@tvm.testing.requires_rpc\ndef test_rpc_tracker_via_proxy():\n    \"\"\"\n         tracker\n         /     \\\n    Host   --   Proxy -- RPC server\n    \"\"\"\n\n    device_key = \"test_device\"\n\n    tracker_server = Tracker(port=9000, port_end=9100)\n    proxy_server = Proxy(\n        host=tracker_server.host,\n        port=8888,\n        port_end=8988,\n        tracker_addr=(tracker_server.host, tracker_server.port),\n    )\n\n    server1 = rpc.Server(\n        host=proxy_server.host,\n        port=proxy_server.port,\n        key=device_key,\n        tracker_addr=(tracker_server.host, tracker_server.port),\n        is_proxy=True,\n    )\n    server2 = rpc.Server(\n        host=proxy_server.host,\n        port=proxy_server.port,\n        key=device_key,\n        tracker_addr=(tracker_server.host, tracker_server.port),\n        is_proxy=True,\n    )\n\n    client = rpc.connect_tracker(tracker_server.host, tracker_server.port)\n    remote1 = client.request(device_key, session_timeout=30)  # pylint: disable=unused-variable\n    remote2 = client.request(device_key, session_timeout=30)  # pylint: disable=unused-variable\n\n    server2.terminate()\n    server1.terminate()\n    proxy_server.terminate()\n    tracker_server.terminate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_trace.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\n\n\ndef test_trace_default_action():\n    n = 2\n    x = te.placeholder((n, n, n), name=\"X\", dtype=\"float32\")\n    y = te.compute(x.shape, lambda i, j, k: tvm.tir.trace([i, j, k, x[i][j][k]]))\n    s = te.create_schedule(y.op)\n    f = tvm.build(s, [x, y], target=\"llvm\")\n    xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype))\n    ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype))\n    f(xnd, ynd)\n\n\ndef test_trace_expr_assign():\n    @tvm.register_func(\"tvm.tir.trace_callback2\")\n    def trace_buffer(x):\n        return\n\n    def check_assign(dtype):\n        n = 4\n        x = te.placeholder((n, n, n), name=\"X\", dtype=dtype)\n        y = te.compute(\n            x.shape, lambda i, j, k: tvm.tir.trace([x[i][j][k]], \"tvm.tir.trace_callback2\")\n        )\n        z = te.compute(\n            x.shape, lambda i, j, k: tvm.tir.trace([y[i][j][k]], \"tvm.tir.trace_callback2\")\n        )\n        s = te.create_schedule(z.op)\n        f = tvm.build(s, [x, y, z], \"llvm\")\n\n        xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype))\n        ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype))\n        znd = tvm.nd.array(np.zeros((n, n, n), dtype=z.dtype))\n        f(xnd, ynd, znd)\n\n        assert np.array_equal(xnd.numpy(), np.ones((n, n, n)))\n        assert np.array_equal(ynd.numpy(), np.ones((n, n, n)))\n        assert np.array_equal(znd.numpy(), np.ones((n, n, n)))\n\n    for t in [\"float64\", \"float32\", \"int64\", \"int32\"]:\n        check_assign(t)\n\n\ndef test_trace_expr_sum_generated():\n    @tvm.register_func(\"tvm.tir.trace_callback3\")\n    def trace_buffer(x):\n        return\n\n    def check_expr_sum(dtype):\n        n = 4\n        a = te.placeholder((n, n, n), name=\"a\", dtype=dtype)\n        b = te.placeholder((n, n, n), name=\"b\", dtype=dtype)\n        c = te.compute(\n            a.shape,\n            lambda i, j, k: tvm.tir.trace([a[i][j][k]], \"tvm.tir.trace_callback3\")\n            + tvm.tir.trace([b[i][j][k]], \"tvm.tir.trace_callback3\"),\n        )\n        s = te.create_schedule(c.op)\n        f = tvm.build(s, [a, b, c])\n        xnd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype)))\n        ynd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype)))\n        znd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype))\n        f(xnd, ynd, znd)\n        assert np.array_equal(znd.numpy(), xnd.numpy() + ynd.numpy())\n\n    for t in [\"float64\", \"float32\", \"int64\", \"int32\"]:\n        check_expr_sum(t)\n\n\ndef test_trace_expr_sum_args():\n    @tvm.register_func(\"tvm.tir.trace_silent\")\n    def silent(*args):\n        return\n\n    def check_expr_sum(dtype):\n        n = 4\n        a = te.placeholder((n, n, n), name=\"a\", dtype=dtype)\n        b = te.placeholder((n, n, n), name=\"b\", dtype=dtype)\n        e = te.placeholder((n, n, n), name=\"e\", dtype=dtype)\n        d = te.placeholder((n, n, n), name=\"d\", dtype=dtype)\n\n        c = te.compute(\n            a.shape,\n            lambda i, j, k: tvm.tir.trace([i, j, k, a[i][j][k]], \"tvm.tir.trace_silent\")\n            + tvm.tir.trace([i, j, k, b[i][j][k]], \"tvm.tir.trace_silent\")\n            + tvm.tir.trace([i, j, k, d[i][j][k]], \"tvm.tir.trace_silent\")\n            + tvm.tir.trace([i, j, k, e[i][j][k]], \"tvm.tir.trace_silent\"),\n        )\n        s = te.create_schedule(c.op)\n        f = tvm.build(s, [a, b, d, e, c])\n        a_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype)))\n        b_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype)))\n        d_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=d.dtype)))\n        e_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=e.dtype)))\n        c_nd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype))\n        f(a_nd, b_nd, d_nd, e_nd, c_nd)\n        assert np.array_equal(\n            c_nd.numpy(), a_nd.numpy() + b_nd.numpy() + d_nd.numpy() + e_nd.numpy()\n        )\n\n    for t in [\"float64\", \"float32\", \"int64\", \"int32\"]:\n        check_expr_sum(t)\n\n\ndef test_trace_expr_sum_custom():\n    @tvm.register_func(\"tvm.tir.trace_callback4\")\n    def trace_buffer(x):\n        return\n\n    def check_expr_sum_custom(dtype):\n        n = 4\n        a = te.placeholder((n, n), name=\"a\", dtype=dtype)\n        b = te.placeholder((n, n), name=\"b\", dtype=dtype)\n        c = te.compute(\n            a.shape,\n            lambda i, j: tvm.tir.trace([a[i][j]], \"tvm.tir.trace_callback4\")\n            + tvm.tir.trace([b[i][j]], \"tvm.tir.trace_callback4\"),\n        )\n        s = te.create_schedule(c.op)\n        f = tvm.build(s, [a, b, c])\n        npa = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype)\n        npb = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype)\n        xnd = tvm.nd.array(npa)\n        ynd = tvm.nd.array(npb)\n        znd = tvm.nd.array(np.zeros((n, n), dtype=c.dtype))\n        f(xnd, ynd, znd)\n        assert np.array_equal(znd.numpy(), npa + npb)\n\n    for t in [\"float64\", \"float32\", \"int64\", \"int32\"]:\n        check_expr_sum_custom(t)\n\n\ndef test_trace_can_change_traced_value_int():\n    @tvm.register_func(\"tvm.tir.trace_change_int_first\")\n    def trace_buffer(x):\n        return 13\n\n    @tvm.register_func(\"tvm.tir.trace_change_int_second\")\n    def trace_buffer(x):\n        return 14\n\n    def check_assign(dtype):\n        n = 4\n        x = te.placeholder((n,), name=\"X\", dtype=dtype)\n        y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], \"tvm.tir.trace_change_int_first\"))\n        z = te.compute(x.shape, lambda i: tvm.tir.trace([y[i]], \"tvm.tir.trace_change_int_second\"))\n        s = te.create_schedule(z.op)\n        f = tvm.build(s, [x, y, z], \"llvm\")\n\n        xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype))\n        ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype))\n        znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype))\n        f(xnd, ynd, znd)\n        check_array_first = np.array([13, 13, 13, 13])\n        check_array_second = np.array([14, 14, 14, 14])\n        assert np.array_equal(ynd.numpy(), check_array_first)\n        assert np.array_equal(znd.numpy(), check_array_second)\n\n    for t in [\"int64\", \"int32\"]:\n        check_assign(t)\n\n\ndef test_trace_can_change_traced_value_float():\n    @tvm.register_func(\"tvm.tir.trace_change_float_first\")\n    def trace_buffer(x):\n        return 13.0\n\n    @tvm.register_func(\"tvm.tir.trace_change_float_second\")\n    def trace_buffer(x):\n        return 14.0\n\n    def check_assign(dtype):\n        n = 4\n        x = te.placeholder((n,), name=\"X\", dtype=dtype)\n        y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], \"tvm.tir.trace_change_float_first\"))\n        z = te.compute(\n            x.shape, lambda i: tvm.tir.trace([y[i]], \"tvm.tir.trace_change_float_second\")\n        )\n        s = te.create_schedule(z.op)\n        f = tvm.build(s, [x, y, z], \"llvm\")\n\n        xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype))\n        ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype))\n        znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype))\n        f(xnd, ynd, znd)\n        check_array_first = np.array([13.0, 13.0, 13.0, 13.0])\n        check_array_second = np.array([14.0, 14.0, 14.0, 14.0])\n        assert np.array_equal(ynd.numpy(), check_array_first)\n        assert np.array_equal(znd.numpy(), check_array_second)\n\n    for t in [\"float64\", \"float32\"]:\n        check_assign(t)\n\n\nif __name__ == \"__main__\":\n    test_trace_expr_assign()\n    test_trace_expr_sum_generated()\n    test_trace_expr_sum_custom()\n    test_trace_expr_sum_args()\n    test_trace_default_action()\n    test_trace_can_change_traced_value_int()\n    test_trace_can_change_traced_value_float()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_runtime_vm_profiler.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm.runtime import profiler_vm\nfrom tvm import relay\nfrom tvm.relay.testing import mlp\n\n\n@tvm.testing.parametrize_targets\ndef test_basic(dev, target):\n    mod, params = mlp.get_workload(batch_size=1)\n    if not profiler_vm.enabled():\n        return\n\n    exe = relay.vm.compile(mod, target, params=params)\n    code, lib = exe.save()\n    des_exe = tvm.runtime.vm.Executable.load_exec(code, lib)\n    vm = profiler_vm.VirtualMachineProfiler(des_exe, dev)\n\n    data = np.random.rand(1, 1, 28, 28).astype(\"float32\")\n    res = vm.profile(tvm.nd.array(data), func_name=\"main\")\n    assert \"softmax\" in str(res)\n\n\ndef test_vm_reshape_and_copy():\n    target = \"llvm\"\n    dev = tvm.gpu()\n    x_np = np.random.uniform(size=(8, 16)).astype(\"float32\")\n    x = relay.var(\"x\", shape=(8, 16), dtype=\"float32\")\n    y = relay.reshape(x, [-1, 4, 8])\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], y)\n    with tvm.transform.PassContext(opt_level=3):\n        exec = relay.vm.compile(mod, \"llvm\")\n    assert \"reshape_tensor\" in exec.bytecode\n    vm = profiler_vm.VirtualMachineProfiler(exec, dev)\n    vm.profile(tvm.nd.array(x_np))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_slice_tir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nimport pytest\n\n# ---------------------------------------------------------------------------------------------------\n# ABOUT THIS FILE:\n# ---------------------------------------------------------------------------------------------------\n# We (cconvey / OctoML) are working on a sequence of PRs to allow a single TIR primfunc's\n# AST to be sliced into multiple partitiones, where each partition will be converted into\n# a new TIR primfunc. (See https://en.wikipedia.org/wiki/Program_slicing).\n#\n# The unit tests below provide a roadmap for that sequence of PRs; each PR should allow\n# one more of these tests to pass.\n#\n# NOTE: These unit tests may change as work progresses.  They aren't meant to\n# indicate hard requirements.\n\n# NOTE! The `tvm.testing.CompareBeforeAfter` class provides TWO useful mechanisms for\n# these tests:\n#\n# (a) It lets us specify code snippets which are valid Python, but which aren't YET\n#     recognized as valid TVMScript.  This allows unit tests for new constructs,\n#     e.g. 'call_tir(...)' to simply be disabled rather than fully commented out.\n#\n# (b) It lets us structurally compare the TIR bodies of two primfuncs.\n#\n#     Note that some of the tests below will require the structural comparison of\n#     two entire IRModules, not just primfuncs.  This will require adding functionality\n#     to the `CompareBeforeAfter` class, or implementing that level of comparison within\n#     the individual unit tests.\n#\n# Some of the unit tests below which require whole-IRModule comparison.  For expedience\n# we simply comment out the (early draft) bodies of those unit tests, rather than\n# hacking their structure to get the benefits of (a).\n\n\n# ---------------------------------------------------------------------------------------------------\n# 'CALL_TIR' (AND RELATED) CAVEATS:\n# ---------------------------------------------------------------------------------------------------\n# (c) \"call_tir\" is a placeholder name.\n#     The TVM \"Relax\" effort also defines a node named \"call_tir\", which is likely\n#     become something different from what we're calling \"call_tir\" here.  So\n#     we may rename *this* \"call_tir\" during implementation.\n#\n# (d) For \"call_tir\" calls, the syntax/semantics for passing buffer regions is still\n#     an active area of development.  So that detail of these unit tests is likely\n#     to change.\n#\n# (e) The specific string \"extract_as_subroutine\" used to annotate some IR Blocks,\n#     i.e., `T.annotate(\"extract_as_subroutine\", ...)`, may change as work progresses.\n\n\n# ---------------------------------------------------------------------------------------------------\n# step 1: Simply passes Python / TVMScript parsing.\n# ---------------------------------------------------------------------------------------------------\n#\n#   The only requirement for this test is that the TVMScript parser\n#   doesn't raise an error when encountering `T.call_tir(foo)`,\n#   where \"foo\" is a syntactically valid TVMScript function name.\n#\n#   NOTE! The role of this unit test should evolve as follows:\n#   1) Initially the test should fail, because we haven't yet changed the TVMScript\n#      parser to support 'call_tir'.\n#\n#   2) Initial TVMScript support for 'call_tir' will be minimal, essentially ignoring\n#      it.  This test should pass once that change is made.\n#\n#   3) As support for 'call_tir' becomes more complete, this test should once again\n#      fail, because the specified callee doesn't exist.  This test should be updated\n#      to once again expect failure.\n@pytest.mark.xfail(reason=\"Awaiting TVMScript support for 'call_tir' token.\", strict=True)\nclass TestParseCallTIR(tvm.testing.CompareBeforeAfter):\n    \"\"\"\n    Simply confirm that the TIR node `call_tir` doesn't interfere with\n    the successful parsing of the TVMScript.\n    \"\"\"\n\n    def before():\n        T.call_tir(add_one)\n        T.evalute(0)\n\n    def expected():\n        T.evaluate(0)\n\n    # Provide a trivial 'transform' pass to satisfy the requirements of\n    # tvm.testing.CompareBeforeAfter.\n    transform = tvm.tir.transform.prim_func_pass(lambda func, _mod, _ctx: func, 0)\n\n\n# ---------------------------------------------------------------------------------------------------\n# step 2: transform annotated block ==> separate primfuncs + call_tir\n#\n# NOTE: This early-draft version of the unit test contains pseudocode to compare entire IRModule\n# objects, analogously to how tvm.testing.CompareBeforeAfter compares two primfuncs.\n# TVM's testing infrastructure currently has no such functionality, and it will need to be added\n# (or approximated) to make this unit test useable.\n# ---------------------------------------------------------------------------------------------------\n@pytest.mark.xfail(\n    reason=\"Awaiting TVMScript support for 'call_tir' and T.annotation(\\\"extract_as_subroutine\\\").\",\n    strict=True,\n)\nclass TestAnnotateAndSliceTIR(tvm.testing.CompareBeforeAfter):\n    # def test_annotate_and_slice():\n    #    @tvm.script.ir_module\n    #    class irmod_before:\n    #        @T.prim_func\n    #        def main(A: T.Buffer[(1,), \"int8\"):\n    #            #A = T.match_buffer(a, (1,), \"int8\")\n    #            A[0] = 0\n    #            with T.block(\"block_foo\"): # optional: give this block a name, perhaps for testing?\n    #                # NOTE: nice to have: human control over name used for the generated callee\n    #                T.annotate(\"extract_as_subroutine\", \"add_one\")\n    #                A[0] += 1\n    #                return 42\n    #\n    #    @tvm.script.ir_module\n    #    class irmod_after:\n    #        @T.prim_func\n    #        def main():\n    #            A = T.buffer[[1], \"int8\"]\n    #            A[0] = 0\n    #            with T.block(\"block_foo\"):\n    #                call_tir(add_one, A)\n    #\n    #        @T.prim_func\n    #        def add_one(X: T.buffer[[1], \"int8\"]):\n    #            X[0] += 1\n    pass\n\n\n# ---------------------------------------------------------------------------------------------------\n# step 3: transform call_tir ==> packed call\n# ---------------------------------------------------------------------------------------------------\n@pytest.mark.xfail(\n    reason=\"Awaiting TVMScript support for lowering of 'T.call_tir' to 'T.call_packed'.\",\n    strict=True,\n)\nclass TestLowerCallTir(tvm.testing.CompareBeforeAfter):\n    # @tvm.script.ir_module\n    # class test_lower_before:\n    #    @T.prim_func\n    #    def main():\n    #        A = T.buffer[[1], \"int8\"]\n    #        A[0] = 0\n    #        with T.block():\n    #            call_tir(add_one, A)\n    #\n    #    @T.prim_func\n    #    def add_one(X: T.buffer[[1], \"int8\"]):\n    #        X[0] += 1\n    #\n    # @tvm.script.ir_module\n    # class test_lower_after:\n    #    @T.prim_func\n    #    def main():\n    #        A = T.buffer[[1], \"int8\"]\n    #        A[0] = 0\n    #        with T.block():\n    #            # TODO: figure out the right TVMScript thing to do here\n    #            call_packed(add_one, A)  # not sure about this function / interface\n    #\n    #    @T.prim_func\n    #    def add_one(X: T.buffer[[1], \"int8\"]):\n    #        X[0] += 1\n    #\n    # TODO(cconvey): additional test logic needed.\n    # NOTE(lunderberg): Will also need a `transform` defined here.\n    #      I think we'll want it to occur in `tvm.tir.transform.MakePackedAPI`.\n    pass\n\n\n# ---------------------------------------------------------------------------------------------------\n# step 4: end-to-end functionality\n# ---------------------------------------------------------------------------------------------------\n\n\n@pytest.mark.xfail(reason=\"Awaiting end-to-end support for Primfunc slicing.\", strict=True)\nclass TestPrimfuncSlicingEndToEnd(tvm.testing.CompareBeforeAfter):\n    # @tvm.script.ir_module\n    # class test_annotate_before:\n    #    @T.prim_func\n    #    def main():\n    #        A = T.buffer[[1], \"int8\"]\n    #        A[0] = 0\n    #        with T.block(): # optional: give this block a name, perhaps for testing?\n    #            # NOTE: nice to have: human control over name used for the generated callee\n    #            T.annotate(\"extract_as_subroutine\", \"add_one\")\n    #            A[0] += 1\n    #        assert(A[0] == 1)\n    #\n    # TODO(cconvey): additional test logic needed:\n    #     Starting with the IRModule shown above, end up with a running test that\n    #     module actually increments A[0] on Hexagon and x86-64 Linux.\n    #\n    # NOTE(lunderberg): We can use the function calls currently generated by `SplitHostDevice` as a template\n    #     (see https://github.com/apache/tvm/blob/9a673faa74ed7cd715a4e011716bcce3fd2158b6/src/tir/transforms/split_host_device.cc#L336).\n    #     Overall, we'll want to output a Call node with the operation builtin::tvm_call_packed().\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_subwarp_reduction_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nimport numpy as np\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef reduce(a: T.handle, b: T.handle, d1: T.int32, d2: T.int32, d3: T.int32) -> None:\n    A = T.match_buffer(a, [1, d1, d2, d3])\n    B = T.match_buffer(b, [1, d1, d2])\n\n    for i, j, k, l in T.grid(1, d1, d2, d3):\n        with T.block(\"reduce\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSR\", [i, j, k, l])\n            with T.init():\n                B[vi, vj, vk] = 0.0\n            B[vi, vj, vk] = B[vi, vj, vk] + A[vi, vj, vk, vl]\n\n\n@T.prim_func\ndef reduce_max(a: T.handle, b: T.handle, d1: T.int32, d2: T.int32, d3: T.int32) -> None:\n    A = T.match_buffer(a, [1, d1, d2, d3])\n    B = T.match_buffer(b, [1, d1, d2])\n\n    for i, j, k, l in T.grid(1, d1, d2, d3):\n        with T.block(\"reduce\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSR\", [i, j, k, l])\n            with T.init():\n                B[vi, vj, vk] = T.float32(-3.4028234663852886e38)\n            B[vi, vj, vk] = T.max(B[vi, vj, vk], A[vi, vj, vk, vl])\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_subwarp_reduction():\n    def check_sum(d1: int, d2: int, d3: int):\n        _, _, _d1, _d2, _d3 = reduce.params\n        mod = reduce.specialize({_d1: d1, _d2: d2, _d3: d3})\n        sch = tvm.tir.Schedule(mod)\n        blk = sch.get_block(\"reduce\")\n        i, j, k, l = sch.get_loops(blk)\n        sch.bind(i, \"blockIdx.x\")\n        sch.bind(j, \"threadIdx.z\")\n        sch.bind(k, \"threadIdx.y\")\n        sch.bind(l, \"threadIdx.x\")\n        f = tvm.build(sch.mod[\"main\"], target=\"cuda\")\n\n        # prepare input and output array\n        a_np = np.random.rand(1, d1, d2, d3).astype(\"float32\")\n        b_np = a_np.sum(axis=-1).astype(\"float32\")\n        a = tvm.nd.array(a_np, tvm.cuda(0))\n        b = tvm.nd.array(np.zeros_like(b_np), tvm.cuda(0))\n\n        # launch kernel\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-6, atol=1e-6)\n\n    def check_max(d1: int, d2: int, d3: int):\n        _, _, _d1, _d2, _d3 = reduce_max.params\n        mod = reduce_max.specialize({_d1: d1, _d2: d2, _d3: d3})\n        sch = tvm.tir.Schedule(mod)\n        blk = sch.get_block(\"reduce\")\n        i, j, k, l = sch.get_loops(blk)\n        sch.bind(i, \"blockIdx.x\")\n        sch.bind(j, \"threadIdx.z\")\n        sch.bind(k, \"threadIdx.y\")\n        sch.bind(l, \"threadIdx.x\")\n        f = tvm.build(sch.mod[\"main\"], target=\"cuda\")\n\n        # prepare input and output array\n        a_np = -np.random.rand(1, d1, d2, d3).astype(\"float32\")\n        b_np = a_np.max(axis=-1).astype(\"float32\")\n        a = tvm.nd.array(a_np, tvm.cuda(0))\n        b = tvm.nd.array(np.zeros_like(b_np), tvm.cuda(0))\n\n        # launch kernel\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-6, atol=1e-6)\n\n    for d1 in range(1, 5):\n        for d2 in range(1, 5):\n            for d3 in range(2, 33):\n                check_sum(d1, d2, d3)\n                check_max(d1, d2, d3)\n\n\nif __name__ == \"__main__\":\n    test_cuda_subwarp_reduction()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_arm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport re\nimport os\nimport ctypes\n\n\ndef test_popcount():\n    target = \"llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon\"\n\n    def check_correct_assembly(type, elements, counts):\n        n = tvm.runtime.convert(elements)\n        A = te.placeholder(n, dtype=type, name=\"A\")\n        B = te.compute(A.shape, lambda i: tvm.tir.popcount(A[i]), name=\"B\")\n        s = te.create_schedule(B.op)\n        s[B].vectorize(s[B].op.axis[0])\n        f = tvm.build(s, [A, B], target)\n\n        # Verify we see the correct number of vpaddl and vcnt instructions in the assembly\n        assembly = f.get_source(\"asm\")\n        matches = re.findall(\"vpaddl\", assembly)\n        assert len(matches) == counts\n        matches = re.findall(\"vcnt\", assembly)\n        assert len(matches) == 1\n\n    check_correct_assembly(\"uint16\", 8, 1)\n    check_correct_assembly(\"uint16\", 4, 1)\n    check_correct_assembly(\"uint32\", 4, 2)\n    check_correct_assembly(\"uint32\", 2, 2)\n    check_correct_assembly(\"uint64\", 2, 3)\n\n\ndef test_vmlal_s16():\n    target = \"llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon\"\n\n    def check_correct_assembly(N):\n        K = te.size_var(\"K\")\n        A = te.placeholder((K, N), dtype=\"int8\", name=\"A\")\n        B = te.placeholder((K, N), dtype=\"int8\", name=\"B\")\n        k = te.reduce_axis((0, K))\n        C = te.compute(\n            (N,),\n            lambda n: te.sum(A[k, n].astype(\"int32\") * B[k, n].astype(\"int32\"), axis=[k]),\n            name=\"C\",\n        )\n        s = te.create_schedule(C.op)\n        s[C].vectorize(s[C].op.axis[0])\n        f = tvm.build(s, [A, B, C], target)\n\n        # Verify we see the correct number of vmlal.s16 instructions\n        assembly = f.get_source(\"asm\")\n        matches = re.findall(\"vmlal.s16\", assembly)\n        assert len(matches) == N // 4\n\n    check_correct_assembly(8)\n    check_correct_assembly(16)\n    check_correct_assembly(32)\n    check_correct_assembly(64)\n\n    def check_broadcast_correct_assembly(N):\n        K = te.size_var(\"K\")\n        A = te.placeholder((K, N), dtype=\"int8\", name=\"A\")\n        B = te.placeholder((K,), dtype=\"int8\", name=\"B\")\n        k = te.reduce_axis((0, K))\n        C = te.compute(\n            (N,),\n            lambda n: te.sum(A[k, n].astype(\"int32\") * B[k].astype(\"int32\"), axis=[k]),\n            name=\"C\",\n        )\n        s = te.create_schedule(C.op)\n        s[C].vectorize(s[C].op.axis[0])\n        f = tvm.build(s, [A, B, C], target)\n\n        # Verify we see the correct number of vmlal.s16 instructions\n        assembly = f.get_source(\"asm\")\n        matches = re.findall(\"vmlal.s16\", assembly)\n        assert len(matches) == N // 4\n\n    check_broadcast_correct_assembly(8)\n    check_broadcast_correct_assembly(16)\n    check_broadcast_correct_assembly(32)\n    check_broadcast_correct_assembly(64)\n\n\nif __name__ == \"__main__\":\n    test_popcount()\n    test_vmlal_s16()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_blob.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import graph_executor\nimport tvm\nfrom tvm import te\nimport ctypes\nimport tvm.testing\n\n\n@tvm.testing.uses_gpu\ndef test_synthetic():\n    for device in [\"llvm\", \"cuda\"]:\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled...\" % device)\n            return\n\n    input_shape = (1, 5, 23, 61)\n\n    def verify(data):\n        mod, params = relay.testing.synthetic.get_workload(input_shape=input_shape)\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, \"llvm\", params=params)\n        dev = tvm.cpu()\n        module = graph_executor.GraphModule(lib[\"default\"](dev))\n        module.set_input(\"data\", data)\n        module.run()\n        out = module.get_output(0).numpy()\n        return out\n\n    synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload(input_shape=input_shape)\n    with tvm.transform.PassContext(opt_level=3):\n        synthetic_gpu_lib = relay.build_module.build(synthetic_mod, \"cuda\", params=synthetic_params)\n\n    from tvm.contrib import utils\n\n    temp = utils.tempdir()\n    path_lib = temp.relpath(\"deploy_lib.so\")\n    synthetic_gpu_lib.export_library(path_lib)\n\n    loaded_lib = tvm.runtime.load_module(path_lib)\n    data = np.random.uniform(-1, 1, size=input_shape).astype(\"float32\")\n    dev = tvm.cuda()\n    module = graph_executor.GraphModule(loaded_lib[\"default\"](dev))\n    module.set_input(\"data\", data)\n    module.run()\n    out = module.get_output(0).numpy()\n\n    tvm.testing.assert_allclose(out, verify(data), atol=1e-5)\n\n\n@tvm.testing.uses_gpu\ndef test_cuda_lib():\n    dev = tvm.cuda(0)\n    for device in [\"llvm\", \"cuda\"]:\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because %s is not enabled...\" % device)\n            return\n    nn = 12\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    bx, tx = s[B].split(B.op.axis[0], factor=4)\n    s[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    from tvm.contrib import utils\n\n    temp = utils.tempdir()\n    fn_add = tvm.build(s, [A, B], target=\"cuda --host=llvm\", name=\"add\")\n    path_lib = temp.relpath(\"deploy_lib.so\")\n    fn_add.export_library(path_lib)\n    m = tvm.runtime.load_module(path_lib)\n    a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev)\n    b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev)\n    m[\"add\"](a, b)\n    np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n\nif __name__ == \"__main__\":\n    test_synthetic()\n    test_cuda_lib()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_bool.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"codegen related to bool types\"\"\"\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nimport tvm.testing\n\narr_size = tvm.testing.parameter(32)\n\n\n@tvm.testing.fixture\ndef compute(arr_size):\n    A = te.placeholder((arr_size,), name=\"A\")\n    B = te.placeholder((arr_size,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) > B(*i), name=\"C\")\n    D = te.compute(C.shape, lambda *i: tvm.tir.all(C(*i), A(*i) > 1).astype(\"float32\"), name=\"D\")\n    return [A, B, C, D]\n\n\n@tvm.testing.fixture\ndef schedule(target, compute):\n    target = tvm.target.Target(target)\n    A, B, C, D = compute\n    if target.kind.name == \"llvm\":\n        s = te.create_schedule(D.op)\n        xo, xi = s[C].split(C.op.axis[0], factor=4)\n        xo1, xo2 = s[C].split(xo, factor=13)\n        s[C].parallel(xo2)\n\n    else:\n        s = te.create_schedule(D.op)\n        for stage in [C, D]:\n            xo, xi = s[stage].split(stage.op.axis[0], factor=4)\n            s[stage].bind(xo, te.thread_axis(\"blockIdx.x\"))\n            s[stage].bind(xi, te.thread_axis(\"threadIdx.x\"))\n\n    return s\n\n\n@tvm.testing.uses_gpu\ndef test_cmp_load_store(target, dev, arr_size, compute, schedule):\n    A, B, _, D = compute\n    f = tvm.build(schedule, [A, B, D], target)\n\n    a_np = np.random.uniform(size=arr_size).astype(A.dtype)\n    b_np = np.random.uniform(size=arr_size).astype(B.dtype)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    d = tvm.nd.array(np.zeros(arr_size, dtype=D.dtype), dev)\n    f(a, b, d)\n    np.testing.assert_equal(\n        d.numpy(),\n        np.logical_and(a_np > b_np, a_np > 1).astype(\"float32\"),\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_c_host.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import utils\n\n\ndef test_add():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    def check_c():\n        mhost = tvm.build(s, [A, B, C], \"c\", name=\"test_fadd\")\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        fadd = m[\"test_fadd\"]\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_c()\n\n\ndef test_add_pipeline():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    AA = te.compute((n,), lambda *i: A(*i), name=\"A\")\n    BB = te.compute((n,), lambda *i: B(*i), name=\"B\")\n    T = te.compute(A.shape, lambda *i: AA(*i) + BB(*i), name=\"T\")\n    C = te.compute(A.shape, lambda *i: T(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    xo1, xo2 = s[C].split(xo, factor=13)\n    s[C].parallel(xo2)\n    s[C].pragma(xo1, \"parallel_launch_point\")\n    s[C].pragma(xo2, \"parallel_stride_pattern\")\n    s[C].pragma(xo2, \"parallel_barrier_when_finish\")\n    s[C].vectorize(xi)\n\n    def check_c():\n        # Specifically allow offset to test codepath when offset is available\n        Ab = tvm.tir.decl_buffer(\n            A.shape, A.dtype, elem_offset=te.size_var(\"Aoffset\"), offset_factor=8, name=\"A\"\n        )\n        binds = {A: Ab}\n        # BUILD and invoke the kernel.\n        f1 = tvm.lower(s, [A, B, C], name=\"test_fadd_pipeline\")\n        mhost = tvm.build(f1, target=\"c\")\n\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        fadd = m[\"test_fadd_pipeline\"]\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_c()\n\n\ndef test_reinterpret():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\", dtype=\"int32\")\n    B = te.compute(\n        A.shape, lambda *i: tvm.tir.call_intrin(\"float32\", \"tir.reinterpret\", 2 + A(*i)), name=\"B\"\n    )\n    s = te.create_schedule(B.op)\n\n    def check_c():\n        mhost = tvm.build(s, [A, B], \"c\", name=\"test_reinterpret\")\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        fadd = m[\"test_reinterpret\"]\n        dev = tvm.cpu(0)\n        n = nn\n        a = tvm.nd.array(np.random.randint(-(2**30), 2**30, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        fadd(a, b)\n        tvm.testing.assert_allclose(b.numpy(), (2 + a.numpy()).view(\"float32\"))\n\n    check_c()\n\n\ndef test_ceil():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n    B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin(\"float32\", \"tir.ceil\", A(*i)), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    def check_c():\n        mhost = tvm.build(s, [A, B], \"c\", name=\"test_ceil\")\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        fceil = m[\"test_ceil\"]\n        dev = tvm.cpu(0)\n        n = nn\n        a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        fceil(a, b)\n        tvm.testing.assert_allclose(b.numpy(), (np.ceil(a.numpy()).view(\"float32\")))\n\n    check_c()\n\n\ndef test_floor():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n    B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin(\"float32\", \"tir.floor\", A(*i)), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    def check_c():\n        mhost = tvm.build(s, [A, B], \"c\", name=\"test_floor\")\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        ffloor = m[\"test_floor\"]\n        dev = tvm.cpu(0)\n        n = nn\n        a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        ffloor(a, b)\n        tvm.testing.assert_allclose(b.numpy(), (np.floor(a.numpy()).view(\"float32\")))\n\n    check_c()\n\n\ndef test_round():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n    B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin(\"float32\", \"tir.round\", A(*i)), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    def check_c():\n        mhost = tvm.build(s, [A, B], \"c\", name=\"test_round\")\n        temp = utils.tempdir()\n        path_dso = temp.relpath(\"temp.so\")\n        mhost.export_library(path_dso)\n        m = tvm.runtime.load_module(path_dso)\n        fround = m[\"test_round\"]\n        dev = tvm.cpu(0)\n        n = nn\n        a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n        fround(a, b)\n        tvm.testing.assert_allclose(b.numpy(), (np.round(a.numpy()).view(\"float32\")))\n\n    check_c()\n\n\ndef test_call_packed():\n    def fake_func(fname=\"fake.func\"):\n        ib = tvm.tir.ir_builder.create()\n        A = ib.pointer(\"float32\", name=\"A\")\n        fake_func1 = tvm.tir.call_packed(fname, A[0])\n\n        ib.emit(fake_func1)\n        body = ib.get()\n        return A, body\n\n    def check_global_packed_func():\n        fname = \"fake.func\"\n        A, body = fake_func(fname)\n        func1 = tvm.tir.PrimFunc([A], body).with_attr(\"global_symbol\", \"func1\")\n        B, body = fake_func()\n        func2 = tvm.tir.PrimFunc([B], body).with_attr(\"global_symbol\", \"func2\")\n        mod = tvm.IRModule({\"fake_func1\": func1, \"fake_func2\": func2})\n        fcode = tvm.build(mod, None, \"c\")\n        src = fcode.get_source()\n\n        # there are two locations calling the packed func\n        assert src.count(fname) == 2\n\n        suffix = \"_packed\"\n        packed_func_name = fname + suffix\n        # func name will be standardized by GetUniqueName and not exists anymore\n        assert src.find(packed_func_name) == -1\n\n        packed_func_real_name = \"_\".join(fname.split(\".\")) + suffix\n        func_declaration = \"static void* %s = NULL;\" % packed_func_real_name\n        # src only has 1 valid declaration\n        assert src.count(func_declaration) == 1\n\n    check_global_packed_func()\n\n\nif __name__ == \"__main__\":\n    test_add()\n    test_add_pipeline()\n    test_reinterpret()\n    test_ceil()\n    test_floor()\n    test_round()\n    test_call_packed()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_cross_llvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test cross compilation\"\"\"\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport os\nimport struct\nfrom tvm import rpc\nfrom tvm.contrib import utils, cc\nimport numpy as np\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_add_pipeline():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    s[C].parallel(xo)\n    s[C].vectorize(xi)\n\n    def verify_elf(path, e_machine):\n        with open(path, \"rb\") as fi:\n            arr = fi.read(20)\n            assert struct.unpack(\"ccc\", arr[1:4]) == (b\"E\", b\"L\", b\"F\")\n            endian = struct.unpack(\"b\", arr[0x5:0x6])[0]\n            endian = \"<\" if endian == 1 else \">\"\n            assert struct.unpack(endian + \"h\", arr[0x12:0x14])[0] == e_machine\n\n    def build_i386():\n        temp = utils.tempdir()\n        target = \"llvm -mtriple=i386-pc-linux-gnu\"\n        f = tvm.build(s, [A, B, C], target)\n        path = temp.relpath(\"myadd.o\")\n        f.save(path)\n        verify_elf(path, 0x03)\n\n    def build_arm():\n        target = \"llvm -mtriple=armv7-none-linux-gnueabihf\"\n        if not tvm.runtime.enabled(target):\n            print(\"Skip because %s is not enabled..\" % target)\n            return\n        temp = utils.tempdir()\n        f = tvm.build(s, [A, B, C], target)\n        path = temp.relpath(\"myadd.o\")\n        f.save(path)\n        verify_elf(path, 0x28)\n        asm_path = temp.relpath(\"myadd.asm\")\n        f.save(asm_path)\n        # Do a RPC verification, launch kernel on Arm Board if available.\n        host = os.environ.get(\"TVM_RPC_ARM_HOST\", None)\n        remote = None\n        if host:\n            port = int(os.environ[\"TVM_RPC_ARM_PORT\"])\n            try:\n                remote = rpc.connect(host, port)\n            except tvm.error.TVMError as e:\n                pass\n\n        if remote:\n            remote.upload(path)\n            farm = remote.load_module(\"myadd.o\")\n            dev = remote.cpu(0)\n            n = nn\n            a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n            b = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n            c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n            farm(a, b, c)\n            tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n            print(\"Verification finish on remote..\")\n\n    build_i386()\n    build_arm()\n\n\nif __name__ == \"__main__\":\n    test_llvm_add_pipeline()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_cuda.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport re\n\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import topi\nfrom tvm.contrib.nvcc import have_fp16, have_int8, have_bf16\nimport tvm.testing\nimport pytest\n\ntx = te.thread_axis(\"threadIdx.x\")\nbx = te.thread_axis(\"blockIdx.x\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_vectorize_add():\n    num_thread = 8\n\n    def check_cuda(dtype, n, lanes):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n        if dtype == \"int8\" and not have_int8(tvm.cuda(0).compute_version):\n            print(\"skip because gpu does not support int8\")\n            return\n        A = te.placeholder((n,), name=\"A\", dtype=\"%sx%d\" % (dtype, lanes))\n        B = te.compute((n,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name=\"B\")\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=num_thread)\n        s[B].bind(xo, bx)\n        s[B].bind(xi, tx)\n        fun = tvm.build(s, [A, B], \"cuda\")\n        dev = tvm.cuda(0)\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np.random.uniform(size=(n, lanes)))\n        c = tvm.nd.empty((n,), B.dtype, dev)\n        fun(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n    check_cuda(\"float32\", 64, 2)\n    check_cuda(\"float32\", 64, 3)\n    check_cuda(\"float32\", 64, 4)\n    check_cuda(\"int8\", 64, 2)\n    check_cuda(\"int8\", 64, 3)\n    check_cuda(\"int8\", 64, 4)\n    check_cuda(\"uint8\", 64, 2)\n    check_cuda(\"uint8\", 64, 3)\n    check_cuda(\"uint8\", 64, 4)\n    check_cuda(\"float16\", 64, 2)\n    check_cuda(\"float16\", 64, 4)\n    check_cuda(\"float16\", 64, 6)\n    check_cuda(\"float16\", 64, 8)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_bf16_vectorize_add():\n    if not have_bf16(tvm.cuda(0).compute_version):\n        print(\"skip because gpu does not support bf16\")\n        return\n    num_thread = 8\n\n    def np_float2np_bf16(arr):\n        \"\"\"Convert a numpy array of float to a numpy array\n        of bf16 in uint16\"\"\"\n        orig = arr.view(\"<u4\")\n        bias = np.bitwise_and(np.right_shift(orig, 16), 1) + 0x7FFF\n        return np.right_shift(orig + bias, 16).astype(\"uint16\")\n\n    def np_bf162np_float(arr):\n        \"\"\"Convert a numpy array of bf16 (uint16) to a numpy array\n        of float\"\"\"\n        u32 = np.left_shift(arr.astype(\"uint32\"), 16)\n        return u32.view(\"<f4\")\n\n    def check_cuda(n, lanes):\n        A = te.placeholder((n,), name=\"A\", dtype=\"bfloat16x%d\" % lanes)\n        B = te.compute((n,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name=\"B\")\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=num_thread)\n        s[B].bind(xo, bx)\n        s[B].bind(xi, tx)\n        with tvm.transform.PassContext(\n            disabled_pass=[\"tir.BF16Promote\", \"tir.BF16CastElimination\", \"tir.BF16TypeLowering\"]\n        ):\n            fun = tvm.build(s, [A, B], \"cuda\")\n        dev = tvm.cuda(0)\n        np_a = np.random.uniform(size=(n, lanes)).astype(\"float32\")\n        np_a = np_bf162np_float(np_float2np_bf16(np_a))\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_float2np_bf16(np_a))\n        c = tvm.nd.empty((n,), B.dtype, dev)\n        fun(a, c)\n        c = tvm.nd.empty((n, lanes), \"uint16\", dev).copyfrom(c)\n        tvm.testing.assert_allclose(c.numpy(), np_float2np_bf16(np_a + 1))\n\n    check_cuda(64, 2)\n    check_cuda(64, 4)\n    check_cuda(64, 6)\n    check_cuda(64, 8)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_multiply_add():\n    num_thread = 8\n\n    def check_cuda(dtype, n, lanes):\n        if dtype == \"int8\" and not have_int8(tvm.cuda(0).compute_version):\n            print(\"skip because gpu does not support int8\")\n            return\n        A = te.placeholder((n,), name=\"A\", dtype=\"%sx%d\" % (dtype, lanes))\n        B = te.placeholder((n,), name=\"B\", dtype=\"%sx%d\" % (dtype, lanes))\n        C = te.placeholder((n,), name=\"C\", dtype=\"int32\")\n        D = te.compute(\n            (n,), lambda i: tvm.tir.call_pure_extern(\"int32\", \"__dp4a\", A[i], B[i], C[i]), name=\"D\"\n        )\n        s = te.create_schedule(D.op)\n        xo, xi = s[D].split(D.op.axis[0], factor=num_thread)\n        s[D].bind(xo, bx)\n        s[D].bind(xi, tx)\n        fun = tvm.build(s, [A, B, C, D], \"cuda\")\n        np_a = np.random.randint(low=-128, high=127, size=(n, lanes))\n        np_b = np.random.randint(low=-128, high=127, size=(n, lanes))\n        np_c = np.random.randint(low=0, high=127, size=(n,))\n        np_d = [sum(x * y) + z for x, y, z in zip(np_a, np_b, np_c)]\n        dev = tvm.cuda(0)\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_a)\n        b = tvm.nd.empty((n,), B.dtype, dev).copyfrom(np_b)\n        c = tvm.nd.empty((n,), C.dtype, dev).copyfrom(np_c)\n        d = tvm.nd.empty((n,), D.dtype, dev)\n        fun(a, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), np_d)\n\n    check_cuda(\"int8\", 64, 4)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_vectorize_load():\n    num_thread = 8\n\n    def check_cuda(dtype, n, lanes):\n        dev = tvm.cuda(0)\n        A = te.placeholder((n,), name=\"A\", dtype=\"%sx%d\" % (dtype, lanes))\n        B = te.compute((n,), lambda i: A[i], name=\"B\")\n        s = te.create_schedule(B.op)\n        block, thread = s[B].split(B.op.axis[0], factor=num_thread)\n        s[B].bind(block, bx)\n        s[B].bind(thread, tx)\n        fun = tvm.build(s, [A, B], \"cuda\", name=\"vector_load\")\n        np_a = np.random.randint(low=-128, high=127, size=(n, lanes))\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_a)\n        b = tvm.nd.empty((n,), B.dtype, dev)\n        fun(a, b)\n        tvm.testing.assert_allclose(a.numpy(), b.numpy())\n\n    check_cuda(\"int8\", 64, 2)\n    check_cuda(\"int8\", 64, 3)\n    check_cuda(\"int8\", 64, 4)\n    check_cuda(\"int8\", 64, 8)\n    check_cuda(\"int8\", 64, 16)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_make_int8():\n    def check_cuda(n, value, lanes):\n        dtype = \"int8\"\n        dev = tvm.cuda(0)\n        A = te.compute((n, lanes), lambda i, j: tvm.tir.const(value, dtype=dtype))\n        s = te.create_schedule(A.op)\n        y, x = s[A].op.axis\n        s[A].vectorize(x)\n        s[A].bind(y, bx)\n        fun = tvm.build(s, [A], \"cuda\", name=\"make_int8x4\")\n        np_a = np.full((n, lanes), value, dtype=dtype)\n        a = tvm.nd.empty(np_a.shape, dtype, dev)\n        fun(a)\n        np.testing.assert_equal(a.numpy(), np_a)\n\n    check_cuda(64, np.int8(0xAB), 4)\n    check_cuda(64, 0, 4)\n    check_cuda(64, -3, 4)\n    check_cuda(64, np.int8(0xAB), 3)\n    check_cuda(64, 0, 3)\n    check_cuda(64, -3, 3)\n    check_cuda(64, np.int8(0xAB), 2)\n    check_cuda(64, 0, 2)\n    check_cuda(64, -3, 2)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_make_int4():\n    def check_cuda(n, value, lanes):\n        dtype = \"int4\"\n        dev = tvm.cuda(0)\n        A = te.compute((n, lanes), lambda i, j: tvm.tir.const(value, dtype=dtype))\n        s = te.create_schedule(A.op)\n        y, x = s[A].op.axis\n        s[A].vectorize(x)\n        s[A].bind(y, bx)\n        kernel_name = \"make_int4x\" + str(lanes)\n        fun = tvm.build(s, [A], \"cuda\", name=kernel_name)\n        np_a = np.full((n, lanes), value, dtype=\"int8\")\n        a = tvm.nd.empty((n, lanes), dtype, dev)\n        fun(a)\n        np.testing.assert_equal(a.numpy(), np_a)\n\n    check_cuda(64, 1, 4)\n    check_cuda(64, 7, 4)\n    check_cuda(64, 1, 8)\n    check_cuda(64, 7, 8)\n    check_cuda(64, 1, 16)\n    check_cuda(64, 7, 16)\n    check_cuda(64, 1, 32)\n    check_cuda(64, 7, 32)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_inf_nan():\n    target = \"cuda\"\n\n    def check_inf_nan(dev, n, value, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        inf_value = tvm.tir.const(value, dtype=dtype)\n        C = te.compute((n,), lambda i: inf_value, name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], tx)\n        fun = tvm.build(s, [A, C], target)\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float64\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_shuffle():\n    idxm = tvm.tir.indexmod\n    a = te.placeholder((64,), \"int32\")\n    b = te.placeholder((64,), \"int32\")\n    c = te.compute((64,), lambda x: a[x] + b[x - idxm(x, 4) + (3 - idxm(x, 4))])\n    sch = te.create_schedule(c.op)\n    x = c.op.axis[0]\n    xo, xi = sch[c].split(x, 4)\n    thrx = te.thread_axis(\"threadIdx.x\")\n    sch[c].bind(xo, thrx)\n    sch[c].vectorize(xi)\n\n    def MyVectorize():\n        def vectorizer(op):\n            if op.kind == tvm.tir.ForKind.VECTORIZED:\n                idx = tvm.tir.Ramp(4 * thrx.var, 1, 4)\n                store = op.body\n                value = store.value\n                new_a = tvm.tir.BufferLoad(value.a.buffer, [idx])\n                bs, ids = [], []\n                for i in range(4):\n                    bs.append(tvm.tir.BufferLoad(value.b.buffer, [4 * thrx.var + i]))\n                    ids.append(3 - i)\n                new_b = tvm.tir.Shuffle(bs, ids)\n                return tvm.tir.BufferStore(store.buffer, new_a + new_b, [idx])\n            return None\n\n        def _transform(f, *_):\n            return f.with_body(\n                tvm.tir.stmt_functor.ir_transform(f.body, None, vectorizer, [\"tir.For\"])\n            )\n\n        return tvm.tir.transform.prim_func_pass(_transform, opt_level=0, name=\"MyVectorize\")\n\n    with tvm.transform.PassContext(config={\"tir.add_lower_pass\": [(1, MyVectorize())]}):\n        module = tvm.build(sch, [a, b, c], target=\"cuda\")\n        a_ = np.array(list(range(64)), dtype=\"int32\")\n        b_ = np.array((list(range(4))[::-1]) * 16, dtype=\"int32\")\n        c_ = np.zeros((64,), dtype=\"int32\")\n        ref = a_ + np.array((list(range(4))) * 16, dtype=\"int32\")\n        nda, ndb, ndc = [tvm.nd.array(i, tvm.cuda(0)) for i in [a_, b_, c_]]\n        module(nda, ndb, ndc)\n        tvm.testing.assert_allclose(ndc.numpy(), ref)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_crossthread_reduction1(target, dev):\n    n = te.var(\"n\")\n    m = te.var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"m\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n\n    def sched(nthd):\n        s = te.create_schedule(B.op)\n        ko, _ = s[B].split(B.op.reduce_axis[0], nparts=nthd)\n        s[B].bind(ko, te.thread_axis(\"threadIdx.x\"))\n        s[B].bind(B.op.axis[0], te.thread_axis(\"blockIdx.x\"))\n        func = tvm.build(s, [A, B], target)\n        return func\n\n    def verify(nthd):\n        func = sched(nthd)\n        nn = 3\n        # checks three typical cases\n        vals = [nthd - 1, nthd, nthd + 1]\n        for kk in [x for x in vals]:\n            size = (nn, kk)\n            a = tvm.nd.array(np.random.uniform(size=size).astype(A.dtype), dev)\n            b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev)\n            func(a, b)\n            tvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=1), rtol=1e-3)\n\n    verify(16)\n    verify(32)\n    verify(64)\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_crossthread_reduction2(target, dev):\n    n = te.var(\"n\")\n    k0 = te.var(\"k0\")\n    k1 = te.var(\"k1\")\n    A = te.placeholder((n, k0, k1), name=\"A\")\n    k0 = te.reduce_axis((0, k0), \"k0\")\n    k1 = te.reduce_axis((0, k1), \"k1\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k0, k1], axis=(k0, k1)), name=\"B\")\n\n    def sched(nthdx, nthdy):\n        s = te.create_schedule(B.op)\n        k0o, _ = s[B].split(B.op.reduce_axis[0], nparts=nthdx)\n        k1o, _ = s[B].split(B.op.reduce_axis[1], nparts=nthdy)\n        s[B].bind(k0o, te.thread_axis(\"threadIdx.x\"))\n        s[B].bind(k1o, te.thread_axis(\"threadIdx.y\"))\n        s[B].bind(B.op.axis[0], te.thread_axis(\"blockIdx.x\"))\n        func = tvm.build(s, [A, B], target)\n        return func\n\n    def verify(nthdx, nthdy):\n        func = sched(nthdx, nthdy)\n        nn = 3\n        # checks three typical cases\n        vx = [nthdx - 1, nthdx, nthdx + 1]\n        vy = [nthdy - 1, nthdy, nthdy + 1]\n        for kk0, kk1 in [(x, y) for x in vx for y in vy]:\n            size = (nn, kk0, kk1)\n            a = tvm.nd.array(np.random.uniform(size=size).astype(A.dtype), dev)\n            b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev)\n            func(a, b)\n            tvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=(1, 2)), rtol=1e-3)\n\n    verify(16, 16)\n    verify(32, 32)\n    verify(16, 32)\n    verify(32, 16)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_reduction_binding():\n    k = te.reduce_axis((0, 32), \"k\")\n    A = te.placeholder((96, 32), name=\"A\")\n    B = te.compute((96,), lambda m: te.sum(A[m, k], axis=k), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    s[B].reorder(B.op.reduce_axis[0], B.op.axis[0])\n\n    mo, _ = s[B].split(B.op.axis[0], 32)\n    s[B].bind(mo, te.thread_axis(\"blockIdx.x\"))\n\n    fcuda = tvm.build(s, [A, B], \"cuda\")\n\n\n@tvm.testing.parametrize_targets(\"cuda\", \"rocm\")\ndef test_rfactor_predicates(target, dev):\n    n = te.reduce_axis((0, 129), \"n\")\n    A = te.placeholder((129,), name=\"A\")\n    B = te.compute((1,), lambda b: te.sum(A[n], axis=n), name=\"B\")\n\n    s = te.create_schedule(B.op)\n\n    _, ni = s[B].split(s[B].op.reduce_axis[0], factor=8)\n\n    BF = s.rfactor(B, ni, 0)\n    s[B].set_store_predicate(tx.var.equal(0))\n\n    s[B].bind(s[B].op.reduce_axis[0], tx)\n    s[B].bind(s[B].op.axis[0], bx)\n\n    s[BF].compute_at(s[B], s[B].op.axis[0])\n\n    _, noi = s[BF].split(s[BF].op.reduce_axis[0], factor=2)\n\n    BF2 = s.rfactor(BF, noi, 0)\n\n    s[BF].bind(s[BF].op.axis[0], tx)\n    s[BF2].compute_at(s[BF], s[BF].op.axis[1])\n\n    fcuda = tvm.build(s, [A, B], target)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_const_float_to_half():\n    # This import is required to use nvcc to perform code gen;\n    # otherwise it is found that the code gen is done by nvrtc.\n    from tvm import autotvm\n\n    shape = (2, 3, 4)\n    a = te.placeholder(shape, dtype=\"float16\", name=\"a\")\n    b = tvm.tir.const(0.5, dtype=\"float16\")\n    c = te.compute(shape, lambda i, j, k: a[i, j, k] > b, name=\"c\")\n    s = te.create_schedule(c.op)\n    axes = [axis for axis in c.op.axis]\n    fused = s[c].fuse(*axes)\n    bx, tx = s[c].split(fused, factor=64)\n    s[c].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[c].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    func = tvm.build(s, [a, c], \"cuda\")\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=shape).astype(a.dtype)\n    c_np = np.zeros(shape=shape, dtype=c.dtype)\n    a = tvm.nd.array(a_np, dev)\n    c = tvm.nd.array(c_np, dev)\n    func(a, c)\n    np.testing.assert_equal(c.numpy(), a_np > b.value)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_reduction():\n    def check(device, dtype, m=32, n=32):\n        if not tvm.testing.device_enabled(device):\n            print(\"Skipping\", device)\n            return\n        dev = tvm.device(device, 0)\n        a = te.placeholder((m, n), name=\"a\", dtype=dtype)\n        b = te.placeholder((m, n), name=\"b\", dtype=dtype)\n        c = a + b\n        d = a * b\n        e = topi.elemwise_sum([c, d])\n        g = topi.sum(e)\n        with tvm.target.Target(device):\n            sg = topi.cuda.schedule_reduce(g)\n            func = tvm.build(sg, [a, b, g], device)\n            a_np = np.random.uniform(size=(m, n)).astype(a.dtype)\n            b_np = np.random.uniform(size=(m, n)).astype(b.dtype)\n            g_np = np.sum(np.add(a_np * b_np, a_np + b_np))\n            a_nd = tvm.nd.array(a_np, dev)\n            b_nd = tvm.nd.array(b_np, dev)\n            g_nd = tvm.nd.array(np.zeros(g_np.shape, dtype=g_np.dtype), dev)\n            func(a_nd, b_nd, g_nd)\n            tvm.testing.assert_allclose(g_nd.numpy(), g_np, rtol=1e-3)\n\n    check(\"cuda\", \"float32\")\n    check(\"rocm\", \"float32\")\n    check(\"cuda\", \"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_mix_threaded_and_normal_reduction():\n    def check(device, dtype, m=32, n=32):\n        if not tvm.testing.device_enabled(device):\n            print(\"Skipping\", device)\n            return\n        dev = tvm.device(device, 0)\n        if dtype == \"float16\" and not have_fp16(dev.compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        a = tvm.te.placeholder((m, n), name=\"a\", dtype=dtype)\n        b = topi.sum(a)\n        with tvm.target.Target(device):\n            sb = tvm.te.create_schedule(b.op)\n            i, _ = b.op.reduce_axis\n            sb[b].bind(i, tvm.te.thread_axis(\"threadIdx.x\"))\n            func = tvm.build(sb, [a, b], device)\n            a_np = np.random.uniform(size=(m, n)).astype(a.dtype)\n            b_np = np.sum(a_np)\n            a_nd = tvm.nd.array(a_np, dev)\n            b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev)\n            func(a_nd, b_nd)\n            tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3)\n\n    check(\"cuda\", \"float32\")\n    check(\"rocm\", \"float32\")\n    check(\"cuda\", \"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_floordiv_with_vectorization():\n    with tvm.target.cuda():\n        # B[i] = A[floordiv(i, k)]\n        n = 256\n        k = 37\n        A = te.placeholder((n,), name=\"A\")\n        B = te.compute((n,), lambda i: A[tvm.tir.floordiv(i, k)], name=\"B\")\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], nparts=1)\n        xio, xii = s[B].split(xi, factor=4)\n        s[B].vectorize(xii)\n        s[B].bind(xo, bx)\n        s[B].bind(xio, tx)\n        func = tvm.build(s, [A, B], \"cuda\")\n\n        dev = tvm.cuda(0)\n        a_np = np.random.uniform(size=(n,)).astype(A.dtype)\n        b_np = np.array([a_np[i // k] for i in range(0, n)])\n        a_nd = tvm.nd.array(a_np, dev)\n        b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev)\n        func(a_nd, b_nd)\n        tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_floormod_with_vectorization():\n    with tvm.target.cuda():\n        # B[i] = A[floormod(i, k)]\n        n = 256\n        k = 37\n        A = te.placeholder((n,), name=\"A\")\n        B = te.compute((n,), lambda i: A[tvm.tir.floormod(i, k)], name=\"B\")\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], nparts=1)\n        xio, xii = s[B].split(xi, factor=4)\n        s[B].vectorize(xii)\n        s[B].bind(xo, bx)\n        s[B].bind(xio, tx)\n        func = tvm.build(s, [A, B], \"cuda\")\n\n        dev = tvm.cuda(0)\n        a_np = np.random.uniform(size=(n,)).astype(A.dtype)\n        b_np = np.array([a_np[i % k] for i in range(0, n)])\n        a_nd = tvm.nd.array(a_np, dev)\n        b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev)\n        func(a_nd, b_nd)\n        tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_casts():\n    def check(t0, t1, factor):\n        if (t0 == \"float16\" or t1 == \"float16\") and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        # compute\n        n = 128\n        A = te.placeholder((n,), dtype=t0, name=\"A\")\n        B = te.placeholder((n,), dtype=t1, name=\"B\")\n        C = te.compute((n,), lambda i: A[i] + topi.cast(B[i], A.dtype), name=\"C\")\n\n        # schedule\n        s = tvm.te.create_schedule(C.op)\n        ob, ib = s[C].split(s[C].op.axis[0], factor=factor)\n        s[C].vectorize(ib)\n        s[C].bind(ob, tx)\n        func = tvm.build(s, [A, B, C], \"cuda\")\n\n        # correctness\n        dev = tvm.cuda(0)\n        low, high = (0, 20) if t0.startswith(\"u\") or t1.startswith(\"u\") else (-10, 10)\n        a_np = np.random.randint(low, high, size=n).astype(A.dtype)\n        b_np = np.random.randint(low, high, size=n).astype(B.dtype)\n        c_np = (a_np + b_np).astype(A.dtype)\n        a_nd = tvm.nd.array(a_np, dev)\n        b_nd = tvm.nd.array(b_np, dev)\n        c_nd = tvm.nd.array(np.zeros(c_np.shape, dtype=c_np.dtype), dev)\n        func(a_nd, b_nd, c_nd)\n        tvm.testing.assert_allclose(c_nd.numpy(), c_np, rtol=1e-3)\n\n    def skip(t0, t1):\n        if t0 == t1:\n            return True\n        # CUDA does support cast between {u}int8 and fp16.\n        skip_set = {\"float16\", \"uint8\", \"int8\"}\n        if t0 in skip_set and t1 in skip_set:\n            return True\n        return False\n\n    types_4 = [\n        \"float16\",\n        \"float32\",\n        \"int8\",\n        \"uint8\",\n        \"int16\",\n        \"uint16\",\n        \"int32\",\n        \"uint32\",\n        \"float64\",\n        \"int64\",\n        \"uint64\",\n    ]\n    types_8 = [\"float16\", \"float32\", \"int8\", \"uint8\", \"int16\", \"uint16\", \"int32\", \"uint32\"]\n    for t0, t1 in [(x, y) for x in types_4 for y in types_4 if not skip(x, y)]:\n        check(t0, t1, 4)\n    for t0, t1 in [(x, y) for x in types_8 for y in types_8 if not skip(x, y)]:\n        check(t0, t1, 8)\n    check(\"int8\", \"uint8\", 16)\n    check(\"uint8\", \"int8\", 16)\n\n\ndef sched(B):\n    s = te.create_schedule(B.op)\n    io, ii = s[B].split(s[B].op.axis[0], nparts=1)\n    iio, iii = s[B].split(ii, nparts=32)\n    _, iiii = s[B].split(iii, factor=4)\n    s[B].vectorize(iiii)\n    s[B].bind(io, bx)\n    s[B].bind(iio, tx)\n    return s\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_intrin1():\n    test_funcs = [\n        (tvm.tir.floor, lambda x: np.floor(x)),\n        (tvm.tir.ceil, lambda x: np.ceil(x)),\n        (tvm.tir.trunc, lambda x: np.trunc(x)),\n        (tvm.tir.abs, lambda x: np.fabs(x)),\n        (tvm.tir.round, lambda x: np.round(x)),\n        (tvm.tir.exp, lambda x: np.exp(x)),\n        (tvm.tir.exp2, lambda x: np.exp2(x)),\n        (tvm.tir.exp10, lambda x: np.power(10, x)),\n        (tvm.tir.log, lambda x: np.log(x)),\n        (tvm.tir.log2, lambda x: np.log2(x)),\n        (tvm.tir.log10, lambda x: np.log10(x)),\n        (tvm.tir.tan, lambda x: np.tan(x)),\n        (tvm.tir.cos, lambda x: np.cos(x)),\n        (tvm.tir.cosh, lambda x: np.cosh(x)),\n        (tvm.tir.sin, lambda x: np.sin(x)),\n        (tvm.tir.sinh, lambda x: np.sinh(x)),\n        (tvm.tir.atan, lambda x: np.arctan(x)),\n        (tvm.tir.tanh, lambda x: np.tanh(x)),\n        (tvm.tir.sqrt, lambda x: np.sqrt(x)),\n    ]\n\n    def run_test(tvm_intrin, np_func, dtype):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n        # set of intrinsics does not support fp16 yet.\n        skip_set = {\n            tvm.tir.abs,\n            tvm.tir.round,\n            tvm.tir.tan,\n            tvm.tir.atan,\n            tvm.tir.tanh,\n            tvm.tir.cosh,\n            tvm.tir.sinh,\n        }\n        if dtype == \"float16\" and tvm_intrin in skip_set:\n            print(\"Skip because '{0}' does not support fp16 yet\".format(tvm_intrin.__name__))\n            return\n\n        n = 128\n        A = te.placeholder((n,), dtype=dtype, name=\"A\")\n        B = te.compute((n,), lambda *i: tvm_intrin(A(*i)), name=\"B\")\n        s = sched(B)\n        f = tvm.build(s, [A, B], \"cuda\")\n        dev = tvm.cuda(0)\n        a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(shape=(n,)).astype(A.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-3, rtol=1e-3)\n\n    for func in test_funcs:\n        run_test(*func, \"float32\")\n        run_test(*func, \"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_intrin2(dtype=\"float32\"):\n    c2 = tvm.tir.const(2, dtype=dtype)\n    test_funcs = [\n        (tvm.tir.power, lambda x: np.power(x, 2.0)),\n        (tvm.tir.fmod, lambda x: np.fmod(x, 2.0)),\n    ]\n\n    def run_test(tvm_intrin, np_func):\n        n = 128\n        A = te.placeholder((n,), dtype=dtype, name=\"A\")\n        B = te.compute((n,), lambda i: tvm_intrin(A[i], c2), name=\"B\")\n        s = sched(B)\n        f = tvm.build(s, [A, B], \"cuda\")\n        dev = tvm.cuda(0)\n        a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(shape=(n,)).astype(A.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-3, rtol=1e-3)\n\n    for func in test_funcs:\n        run_test(*func)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_popcount():\n    def ref_popcount(x):\n        cnt = 0\n        while x:\n            x -= x & -x\n            cnt += 1\n        return cnt\n\n    def run_test(dtype):\n        n = 128\n        A = te.placeholder((n,), dtype=dtype, name=\"A\")\n        B = te.compute((n,), lambda i: tvm.tir.popcount(A[i]), name=\"B\")\n        s = sched(B)\n        f = tvm.build(s, [A, B], \"cuda\")\n        dev = tvm.cuda(0)\n        a = tvm.nd.array(np.random.randint(0, 100000, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(shape=(n,)).astype(B.dtype), dev)\n        f(a, b)\n        ref = np.vectorize(ref_popcount)(a.numpy())\n        tvm.testing.assert_allclose(b.numpy(), ref)\n\n    run_test(\"uint32\")\n    run_test(\"uint64\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_cuda_vectorize_load_permute_pad():\n    def check_cuda(dtype, n, l, padding, lanes):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        dev = tvm.cuda(0)\n        A = tvm.te.placeholder((n, l), name=\"A\", dtype=dtype)\n        B = tvm.te.compute(\n            (n // lanes, l + 2 * padding, lanes),\n            lambda i, j, k: tvm.te.if_then_else(\n                tvm.te.any(j < padding, j >= l + padding),\n                tvm.runtime.convert(0).astype(dtype),\n                A[i * lanes + k, j - padding],\n            ),\n            name=\"B\",\n        )\n        s = te.create_schedule(B.op)\n        block, thread, vectorize = s[B].op.axis\n        s[B].bind(block, bx)\n        s[B].bind(thread, tx)\n        s[B].vectorize(vectorize)\n        fun = tvm.build(s, [A, B], \"cuda\", name=\"vector_load_permute_pad\")\n        np_a = np.random.randint(low=-128, high=127, size=(n, l)).astype(A.dtype)\n        a = tvm.nd.empty((n, l), A.dtype, dev).copyfrom(np_a)\n        b = tvm.nd.empty((n // lanes, l + padding * 2, lanes), B.dtype, dev)\n        fun(a, b)\n        np_a_reshape = np_a.reshape(n // lanes, lanes, l).transpose(0, 2, 1)\n        ref = np.pad(\n            np_a_reshape, ((0, 0), (padding, padding), (0, 0)), mode=\"constant\", constant_values=0\n        )\n        tvm.testing.assert_allclose(b.numpy(), ref)\n\n    check_cuda(\"int8\", 64, 16, 3, 2)\n    check_cuda(\"uint8\", 64, 16, 3, 2)\n    check_cuda(\"int8\", 64, 16, 3, 4)\n    check_cuda(\"uint8\", 64, 16, 3, 4)\n    check_cuda(\"int32\", 64, 16, 3, 4)\n    check_cuda(\"float16\", 64, 16, 3, 4)\n    check_cuda(\"float32\", 64, 16, 3, 4)\n\n\ndef vcf_check_common(s, args):\n    N = 512\n\n    # To check if every vectorize loop transforms to ramp expr successfully\n    stmt = tvm.lower(s, args)\n    # Use this as a stack flag to show whether this stmt is inside a BroadcastNode\n    inside_broadcast = [False]\n\n    # Possible patterns:\n    # Reduce init:          BufferStore[Ramp] = Broadcast(0)\n    # Shared memory copy:   BufferStore[Ramp] = BufferLoad[Ramp]\n    # Compute:              BufferStore[Ramp] = BufferLoad[Ramp] ... Broadcast[Load]\n\n    def pre_visit(stmt):\n        if isinstance(stmt, tvm.tir.Broadcast):\n            inside_broadcast[0] = True\n            # Check Broadcast[Imm numbers] or Broadcast[Load] patterns\n            assert isinstance(stmt.value, (tvm.tir.IntImm, tvm.tir.FloatImm, tvm.tir.BufferLoad))\n\n        if isinstance(stmt, (tvm.tir.BufferStore, tvm.tir.BufferLoad)):\n            is_ramp_index = isinstance(stmt.indices[-1], tvm.tir.Ramp)\n            is_vectorized_buffer = re.match(r\"^.*x\\d+$\", stmt.buffer.dtype)\n            if isinstance(stmt, tvm.tir.BufferLoad):\n                # Check Broadcast[BufferLoad] or BufferLoad[Ramp] patterns\n                assert inside_broadcast[0] or is_ramp_index or is_vectorized_buffer\n                # Skip the rest of the BufferLoad\n                return stmt\n            else:\n                assert is_ramp_index or is_vectorized_buffer\n\n        return None\n\n    def post_visit(stmt):\n        if isinstance(stmt, tvm.tir.Broadcast):\n            inside_broadcast[0] = False\n        return None\n\n    tvm.tir.stmt_functor.ir_transform(stmt[\"main\"].body, pre_visit, post_visit)\n\n    tgt = tvm.target.cuda()\n    mod = tvm.build(s, args, tgt)\n    # To check if every vectorize loop transforms to correct instruction\n    # print(mod.imported_modules[0].get_source())\n\n    dev = tvm.device(\"cuda\", 0)\n    a = tvm.nd.array(np.random.uniform(size=(512, 512)).astype(\"float32\"), dev)\n    b = tvm.nd.array(np.random.uniform(size=(512, 512)).astype(\"float32\"), dev)\n    c = tvm.nd.array(np.zeros((512, 512), dtype=\"float32\"), dev)\n    mod(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), np.dot(a.numpy(), b.numpy()), rtol=1e-5)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_cooperative_fetching_x():\n    N = 512\n    A = te.placeholder((N, N), name=\"A\", dtype=\"float32\")\n    B = te.placeholder((N, N), name=\"B\", dtype=\"float32\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k))\n    s = te.create_schedule(C.op)\n    i, j = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    AA = s.cache_read(A, \"shared\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n\n    i3, i4 = s[C].split(i, factor=4)\n    i2, i3 = s[C].split(i3, factor=2)\n    i1, i2 = s[C].split(i2, factor=8)\n    i0, i1 = s[C].split(i1, factor=1)\n    j3, j4 = s[C].split(j, factor=4)\n    j2, j3 = s[C].split(j3, factor=2)\n    j1, j2 = s[C].split(j2, factor=8)\n    j0, j1 = s[C].split(j1, factor=2)\n    k1, k2 = s[C].split(k, factor=8)\n    k0, k1 = s[C].split(k1, factor=8)\n    s[C].reorder(i0, j0, i1, j1, i2, j2, k0, k1, i3, j3, k2, i4, j4)\n    block_it = s[C].fuse(i0, j0)\n    s[C].bind(block_it, tvm.te.thread_axis(\"blockIdx.x\"))\n    vthread_it = s[C].fuse(i1, j1)\n    s[C].bind(vthread_it, tvm.te.thread_axis(\"vthread\"))\n    thread_it = s[C].fuse(i2, j2)\n    s[C].bind(thread_it, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[C].vectorize(j4)\n\n    s[AA].compute_at(s[C], k0)\n    iaa, jaa = s[AA].op.axis\n    s[BB].compute_at(s[C], k0)\n    ibb, jbb = s[BB].op.axis\n    aa_fused = s[AA].fuse(iaa, jaa)\n    bb_fused = s[BB].fuse(ibb, jbb)\n    aa1, aa2 = s[AA].split(aa_fused, factor=4)\n    aa0, aa1 = s[AA].split(aa1, factor=64)\n    bb1, bb2 = s[BB].split(bb_fused, factor=4)\n    bb0, bb1 = s[BB].split(bb1, factor=64)\n    s[AA].bind(aa1, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[AA].vectorize(aa2)\n    s[BB].bind(bb1, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[BB].vectorize(bb2)\n\n    vcf_check_common(s, [A, B, C])\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_vectorized_cooperative_fetching_xy():\n    N = 512\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"B\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k))\n    s = te.create_schedule(C.op)\n    i, j = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    AA = s.cache_read(A, \"shared\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n\n    i3, i4 = s[C].split(i, factor=4)\n    i2, i3 = s[C].split(i3, factor=2)\n    i1, i2 = s[C].split(i2, factor=8)\n    i0, i1 = s[C].split(i1, factor=1)\n    j3, j4 = s[C].split(j, factor=4)\n    j2, j3 = s[C].split(j3, factor=2)\n    j1, j2 = s[C].split(j2, factor=8)\n    j0, j1 = s[C].split(j1, factor=2)\n    k1, k2 = s[C].split(k, factor=8)\n    k0, k1 = s[C].split(k1, factor=8)\n    s[C].reorder(i0, j0, i1, j1, i2, j2, k0, k1, i3, j3, k2, i4, j4)\n    block_it = s[C].fuse(i0, j0)\n    s[C].bind(block_it, tvm.te.thread_axis(\"blockIdx.x\"))\n    vthread_it = s[C].fuse(i1, j1)\n    s[C].bind(vthread_it, tvm.te.thread_axis(\"vthread\"))\n    s[C].bind(i2, tvm.te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(j2, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[C].vectorize(j4)\n\n    s[AA].compute_at(s[C], k0)\n    iaa, jaa = s[AA].op.axis\n    s[BB].compute_at(s[C], k0)\n    ibb, jbb = s[BB].op.axis\n    aa_fused = s[AA].fuse(iaa, jaa)\n    bb_fused = s[BB].fuse(ibb, jbb)\n    aa2, aa3 = s[AA].split(aa_fused, factor=4)\n    aa1, aa2 = s[AA].split(aa2, factor=8)\n    aa0, aa1 = s[AA].split(aa1, factor=8)\n    bb2, bb3 = s[BB].split(bb_fused, factor=4)\n    bb1, bb2 = s[BB].split(bb2, factor=8)\n    bb0, bb1 = s[BB].split(bb1, factor=8)\n    s[AA].bind(aa1, tvm.te.thread_axis(\"threadIdx.y\"))\n    s[AA].bind(aa2, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[AA].vectorize(aa3)\n    s[BB].bind(bb1, tvm.te.thread_axis(\"threadIdx.y\"))\n    s[BB].bind(bb2, tvm.te.thread_axis(\"threadIdx.x\"))\n    s[BB].vectorize(bb3)\n\n    vcf_check_common(s, [A, B, C])\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_unrolled_vectorization():\n    dtype = \"float32\"\n    target = \"cuda\"\n\n    # Compute declaration\n    N = 128\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.placeholder((N, N), name=\"B\")\n    k = te.reduce_axis((0, N), name=\"k\")\n    C = te.compute((N, N), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name=\"C\")\n\n    # Schedule\n    s = te.create_schedule([C.op])\n    CC = s.cache_write(C, \"local\")\n    i, j = s[C].op.axis\n    bx, tx, ii, ji = s[C].tile(i, j, 1, 2)\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].vectorize(ji)\n    s[CC].compute_at(s[C], tx)\n    i, j = s[CC].op.axis\n    k = s[CC].op.reduce_axis[0]\n    ko, ki = s[CC].split(k, 2)\n    s[CC].unroll(ki)\n    s[CC].vectorize(j)\n\n    # Check correctness\n    dev = tvm.device(target)\n    a_tvm = tvm.nd.array(np.ones((N, N)).astype(dtype), device=dev)\n    b_tvm = tvm.nd.array(np.ones((N, N)).astype(dtype), device=dev)\n    c_tvm = tvm.nd.empty((N, N), device=dev)\n    func_tvm = tvm.build(s, [A, B, C], target=target)\n    func_tvm(a_tvm, b_tvm, c_tvm)\n    c_np = c_tvm.numpy()\n    tvm.testing.assert_allclose(c_np, N * np.ones((N, N)))\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_try_unaligned_vector_load():\n    def get_compute(N, C_N, offset):\n        A = te.placeholder((N,), name=\"A\", dtype=\"float16\")\n        C = te.compute((C_N,), lambda i: A[i + offset], name=\"C\")\n        return N, C_N, A, C\n\n    def get_compute_unaligned():\n        return get_compute(3, 2, 1)\n\n    def get_compute_aligned():\n        return get_compute(4, 2, 2)\n\n    def build(A, C, N, C_N):\n        s = te.create_schedule(C.op)\n        oi, ii = s[C].split(C.op.axis[0], factor=2)\n        s[C].bind(oi, te.thread_axis(\"threadIdx.x\"))\n        s[C].vectorize(ii)  # BUG: misalignment\n\n        tgt = tvm.target.Target(target=\"cuda\", host=\"llvm\")\n        dev = tvm.device(tgt.kind.name, 0)\n        f = tvm.build(s, [A, C], tgt, name=\"foo\")\n        kernel_source = f.imported_modules[0].get_source()\n\n        a_data = np.arange(0, N).astype(A.dtype)\n        a = tvm.nd.array(a_data, dev)\n        c = tvm.nd.array(np.zeros(C_N, dtype=C.dtype), dev)\n        f(a, c)\n\n        return a_data, c.numpy(), kernel_source\n\n    N, C_N, A, C = get_compute_unaligned()\n    a_data, c, kernel_source = build(A, C, N, C_N)\n    # (uint1*)(A + (1)) is invalid\n    assert \"A + (1)\" not in kernel_source\n\n    expected = a_data[1 : C_N + 1]\n    assert np.allclose(c, expected), f\"expected={expected}\\nactual={c}\"\n\n    N, C_N, A, C = get_compute_aligned()\n    a_data, c, kernel_source = build(A, C, N, C_N)\n    # (uint1*)(A + (2)) is a valid vector load\n    assert \"A + 2\" in kernel_source\n\n    expected = a_data[2 : C_N + 2]\n    assert np.allclose(c, expected), f\"expected={expected}\\nactual={c}\"\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_device.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import utils\nimport numpy as np\nimport tvm.testing\n\n\n@tvm.testing.requires_gpu\ndef test_large_uint_imm():\n    value = (1 << 63) + 123\n    other = tvm.tir.const(3, \"uint64\")\n    n = 12\n    num_thread = 2\n\n    A = te.compute((n,), lambda *i: tvm.tir.const(value, \"uint64\") + other, name=\"A\")\n    s = te.create_schedule(A.op)\n    xo, xi = s[A].split(A.op.axis[0], factor=num_thread)\n    s[A].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[A].bind(xo, te.thread_axis(\"blockIdx.x\"))\n\n    def check_target(device):\n        if not tvm.testing.device_enabled(device):\n            return\n        dev = tvm.device(device, 0)\n        f = tvm.build(s, [A], device)\n        # launch the kernel.\n        a = tvm.nd.empty((n,), dtype=A.dtype, device=dev)\n        f(a)\n        assert a.numpy()[0] == value + 3\n\n    check_target(\"cuda\")\n    check_target(\"vulkan -from_device=0\")\n\n\n@tvm.testing.requires_gpu\ndef test_add_pipeline():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(), name=\"C\")\n    D = te.compute(A.shape, lambda *i: C(*i) + 1, name=\"D\")\n    s = te.create_schedule(D.op)\n\n    # GPU schedule have to split by gridIdx and threadIdx\n    num_thread = 256\n    xo, xi = s[C].split(C.op.axis[0], factor=num_thread)\n    s[C].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n\n    xo, xi = s[D].split(D.op.axis[0], factor=num_thread)\n    s[D].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[D].bind(xo, te.thread_axis(\"blockIdx.x\"))\n\n    def check_target(device, host=\"stackvm\"):\n        if not tvm.testing.device_enabled(device) or not tvm.testing.device_enabled(host):\n            return\n        dev = tvm.device(device, 0)\n        mhost = tvm.driver.build(s, [A, B, D], target=tvm.target.Target(device, host))\n        f = mhost.entry_func\n        # launch the kernel.\n        n = 1027\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=()).astype(B.dtype), dev)\n        d = tvm.nd.array(np.zeros(n, dtype=D.dtype), dev)\n        f(a, b, d)\n        tvm.testing.assert_allclose(d.numpy(), a.numpy() + b.numpy() + 1)\n\n    check_target(\"cuda\", host=\"llvm\")\n    check_target(\"nvptx\", host=\"llvm\")\n    check_target(\"vulkan\", host=\"llvm\")\n    check_target(\"rocm\", host=\"llvm\")\n\n\nif __name__ == \"__main__\":\n    test_large_uint_imm()\n    test_add_pipeline()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_extern.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nimport tvm.testing\n\n\n@tvm.testing.uses_gpu\ndef test_add_pipeline():\n    nn = 64\n    max_threads = 4\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n\n    def extern_generator(ins, outs):\n        \"\"\"Manually write the IR for the extern function, add pipeline\"\"\"\n        ib = tvm.tir.ir_builder.create()\n        with ib.for_range(0, (n + 1) // 2) as i:\n            ib.emit(\n                outs[0].vstore(\n                    i * 2, ins[0].vload(i * 2, \"float32x2\") + tvm.tir.const(1, \"float32x2\")\n                )\n            )\n        return ib.get()\n\n    def extern_generator_gpu(ins, outs):\n        \"\"\"Manually write the IR for the extern function, add pipeline\"\"\"\n        ib = tvm.tir.ir_builder.create()\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", (nn + max_threads - 1) // max_threads)\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        idx = bx.var * max_threads + tx.var\n        with ib.if_scope(ib.likely(idx < n)):\n            ib.emit(\n                outs[0].vstore(\n                    idx * 2, ins[0].vload(idx * 2, \"float32x2\") + tvm.tir.const(1, \"float32x2\")\n                )\n            )\n        return ib.get()\n\n    C_cpu = te.extern(A.shape, [A], extern_generator, name=\"C\")\n    C_gpu = te.extern(A.shape, [A], extern_generator_gpu, name=\"C\")\n    s_cpu = te.create_schedule(C_cpu.op)\n    s_gpu = te.create_schedule(C_gpu.op)\n    print(tvm.lower(s_cpu, [A, C_cpu], simple_mode=True))\n    print(tvm.lower(s_gpu, [A, C_gpu], simple_mode=True))\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n        s = s_gpu if target in [\"opencl\", \"cuda\"] else s_cpu\n        C = C_gpu if target in [\"opencl\", \"cuda\"] else C_cpu\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], target)\n        dev = tvm.device(target, 0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n    check_target(\"llvm\")\n    check_target(\"opencl\")\n    check_target(\"cuda\")\n\n\ndef test_pack_buffer_simple():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n\n    def extern_generator(ins, outs):\n        \"\"\"Manually write the IR for the extern function, add pipeline.\"\"\"\n        return tvm.tir.call_packed(\"my_extern_array_func1\", ins[0], outs[0])\n\n    C = te.extern(A.shape, [A], extern_generator, name=\"C\")\n    s = te.create_schedule(C.op)\n\n    @tvm.register_func\n    def my_extern_array_func1(aa, bb):\n        aa.copyto(bb)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], target)\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy())\n\n    check_target(\"stackvm\")\n    check_target(\"llvm\")\n\n\ndef test_pack_buffer_intermediate():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute((n,), lambda i: A[i] + 1, name=\"B\")\n\n    def extern_generator(ins, outs):\n        \"\"\"Manually write the IR for the extern function, add pipeline.\"\"\"\n        return tvm.tir.call_packed(\"my_extern_array_func2\", ins[0], outs[0])\n\n    C = te.extern(B.shape, [B], extern_generator, name=\"C\")\n    s = te.create_schedule(C.op)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], target)\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n\n        @tvm.register_func\n        def my_extern_array_func2(aa, bb):\n            assert aa.shape == a.shape\n            tvm.testing.assert_allclose(aa.numpy(), a.numpy() + 1)\n            aa.copyto(bb)\n\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n    check_target(\"llvm\")\n\n\nif __name__ == \"__main__\":\n    test_pack_buffer_simple()\n    test_pack_buffer_intermediate()\n    test_add_pipeline()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_hexagon.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport os\nimport pytest\nimport re\nimport sys\nimport tvm\nimport tvm.relay\nimport tvm.testing\nimport tvm.contrib.hexagon as hexagon\n\n\n@pytest.fixture(autouse=True)\ndef register_linker():\n    original_linker = hexagon.hexagon_link()\n    # Register a phony linker, so that we can test codegen without a Hexagon toolchain.\n    hexagon.register_linker(lambda: \"/bin/true\")\n    yield None\n    # Restore registration.\n    hexagon.register_linker(original_linker)\n\n\n@tvm.testing.requires_hexagon\ndef test_basic():\n    target = tvm.target.hexagon(\"v66\", hvx=128)\n\n    def check_add(offload):\n        A = tvm.te.placeholder((128,), dtype=\"uint8\", name=\"A\")\n        B = tvm.te.placeholder((128,), dtype=\"uint8\", name=\"A\")\n        C = tvm.te.compute((128,), lambda i: A[i] + B[i], name=\"C\")\n        s = tvm.te.create_schedule(C.op)\n\n        if offload:\n            xo, xi = s[C].split(s[C].op.axis[0], nparts=1)\n            s[C].bind(xo, tvm.te.thread_axis(\"pipeline\"))\n            m = tvm.build(s, [C, A, B], target=target, name=\"offload_add\")\n            hexm = m.imported_modules[0]\n        else:\n            hexm = tvm.build(\n                s, [C, A, B], target=tvm.target.Target(target, target), name=\"native_add\"\n            )\n\n        asm = hexm.get_source(\"s\")\n        vadds = re.findall(r\"v[0-9]+.b = vadd\\(v[0-9]+.b,v[0-9]+.b\\)\", asm)\n        assert vadds  # Check that it's non-empty\n\n    check_add(True)\n    check_add(False)\n\n\n@tvm.testing.requires_hexagon\ndef test_llvm_target_features():\n    target = tvm.target.hexagon(\"v66\", hvx=128)\n    # Define some trivial compute\n    A = tvm.te.placeholder((128,), dtype=\"uint8\", name=\"A\")\n    C = tvm.te.compute((128,), lambda i: A[i] + 1, name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n    m = tvm.build(s, [C, A], target=tvm.target.Target(target, target), name=\"add_one\")\n    llvm_ir = m.get_source(\"ll\")\n    # Make sure we find +hvx-length128b in \"attributes\".\n    fs = re.findall(r\"attributes.*\\+hvx-length128b\", llvm_ir)\n    assert fs  # Check that it's non-empty\n\n\n@tvm.testing.requires_hexagon\ndef test_alloc_vtcm():\n    target = tvm.target.hexagon(\"v66\")\n\n    buf_len = 2048\n    A = tvm.te.placeholder((buf_len,), name=\"A\", dtype=\"int8\")\n    B = tvm.te.placeholder((buf_len,), name=\"B\", dtype=\"int8\")\n\n    A_buf = tvm.te.compute((buf_len,), lambda *i: A(*i), \"A_buf\")\n    B_buf = tvm.te.compute((buf_len,), lambda *i: B(*i), \"B_buf\")\n    C = tvm.te.compute((buf_len,), lambda *i: A_buf(*i) + B_buf(*i), name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n\n    # Use VTCM for each buffer.\n    s[A_buf].set_scope(\"local.vtcm\")\n    s[B_buf].set_scope(\"local.vtcm\")\n\n    config = {\"tir.add_lower_pass\": hexagon.ir_lower_vtcm_pass()}\n    with tvm.transform.PassContext(config=config):\n        irmod = tvm.lower(s, [A, B, C], name=\"alloc_vtcm\")\n\n    calls = re.findall(\"HexagonBackend[A-Za-z]*VTCM\", str(irmod[\"alloc_vtcm\"]))\n    assert \"HexagonBackendAllocateVTCM\" in calls\n    assert \"HexagonBackendFreeVTCM\" in calls\n\n\n@tvm.testing.requires_hexagon\ndef test_llvm_options():\n    target = tvm.target.hexagon(\"v66\", llvm_options=\"-hexagon-noopt\")\n    Zero = tvm.te.compute((10,), lambda _: tvm.tir.const(0, \"int32\"))\n    s = tvm.te.create_schedule(Zero.op)\n    tvm.build(s, [Zero], target=target, name=\"zero\")\n    # Check that BuildHexagon hasn't crashed because of target attribute\n    # type mismatch.\n    assert re.search(\"-hexagon-noopt\", str(target))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_llvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport collections\nimport ctypes\nimport json\nimport math\nimport numpy as np\nimport pytest\nimport re\nimport sys\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.contrib import clang, utils\nfrom tvm.relay.backend import Runtime\nfrom tvm.script import tir as T\nfrom tvm.target.codegen import llvm_get_intrinsic_name, llvm_lookup_intrinsic_id\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_intrin():\n    ib = tvm.tir.ir_builder.create()\n    n = tvm.runtime.convert(4)\n    A = ib.pointer(\"float32\", name=\"A\")\n    args = [tvm.tir.call_intrin(\"handle\", \"tir.address_of\", A[0]), 0, 3, 1]\n    ib.emit(tvm.tir.Evaluate(tvm.tir.Call(\"int32\", \"tir.prefetch\", args)))\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], body).with_attr(\"global_symbol\", \"prefetch\"))\n    fcode = tvm.build(mod, None, \"llvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_void_intrin():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"uint8\", name=\"A\")\n    # Create an intrinsic that returns void.\n    x = tvm.tir.call_llvm_intrin(\"\", \"llvm.va_start\", tvm.tir.const(1, \"uint32\"), A.asobject().data)\n    ib.emit(x)\n    body = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], body).with_attr(\"global_symbol\", \"main\"))\n    fcode = tvm.build(mod, None, \"llvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_intrinsic_id():\n    orig_name = \"llvm.x86.sse2.pmadd.wd\"\n    intrin_id = llvm_lookup_intrinsic_id(orig_name)\n    name = llvm_get_intrinsic_name(intrin_id)\n    assert orig_name == name\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_overloaded_intrin():\n    # Name lookup for overloaded intrinsics in LLVM 4- requires a name\n    # that includes the overloaded types.\n    if tvm.target.codegen.llvm_version_major() < 5:\n        return\n\n    def use_llvm_intrinsic(A, C):\n        ib = tvm.tir.ir_builder.create()\n        L = A.vload((0, 0))\n        I = tvm.tir.call_llvm_pure_intrin(\n            \"int32\", \"llvm.ctlz\", tvm.tir.const(2, \"uint32\"), L, tvm.tir.const(0, \"int1\")\n        )\n        S = C.vstore((0, 0), I)\n        ib.emit(S)\n        return ib.get()\n\n    A = tvm.te.placeholder((1, 1), dtype=\"int32\", name=\"A\")\n    C = tvm.te.extern(\n        (1, 1), [A], lambda ins, outs: use_llvm_intrinsic(ins[0], outs[0]), name=\"C\", dtype=\"int32\"\n    )\n    s = tvm.te.create_schedule(C.op)\n    f = tvm.build(s, [A, C], target=\"llvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_lookup_intrin():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"uint8x8\", name=\"A\")\n    z = tvm.tir.const(0, \"int32\")\n    x = tvm.tir.call_llvm_pure_intrin(\n        \"uint8x8\", \"llvm.ctpop.v8i8\", tvm.tir.const(1, \"uint32\"), A[z]\n    )\n    ib.emit(x)\n    body = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], body).with_attr(\"global_symbol\", \"main\"))\n    fcode = tvm.build(mod, None, \"llvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_large_uintimm():\n    value = (1 << 63) + 123\n    other = tvm.tir.const(3, \"uint64\")\n    A = te.compute((), lambda: tvm.tir.const(value, \"uint64\") + other, name=\"A\")\n    s = te.create_schedule(A.op)\n\n    def check_llvm():\n        f = tvm.build(s, [A], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.empty((), dtype=A.dtype, device=dev)\n        f(a)\n        assert a.numpy() == value + 3\n\n    check_llvm()\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_persist_parallel():\n    n = 128\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1, name=\"B\")\n    C = te.compute(A.shape, lambda *i: te.sqrt(B(*i)) * 2 + 2, name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=8)\n    xo1, xo2 = s[C].split(xo, nparts=1)\n    s[B].compute_at(s[C], xo1)\n    s[B].parallel(s[B].op.axis[0])\n    s[B].pragma(s[B].op.axis[0], \"parallel_barrier_when_finish\")\n    s[C].parallel(xi)\n    s[C].pragma(xo1, \"parallel_launch_point\")\n    s[C].pragma(xi, \"parallel_stride_pattern\")\n\n    def check_llvm():\n        # BUILD and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), np.sqrt(a.numpy() + 1) * 2 + 2, rtol=1e-5)\n\n    check_llvm()\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_flip_pipeline():\n    def check_llvm(nn, base):\n        n = tvm.runtime.convert(nn)\n        A = te.placeholder((n + base), name=\"A\")\n        C = te.compute((n,), lambda i: A(nn + base - i - 1), name=\"C\")\n        s = te.create_schedule(C.op)\n        xo, xi = s[C].split(C.op.axis[0], factor=4)\n        s[C].parallel(xo)\n        s[C].vectorize(xi)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=(n + base)).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy()[::-1][:n])\n\n    check_llvm(4, 0)\n    check_llvm(128, 8)\n    check_llvm(3, 0)\n    check_llvm(128, 1)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_vadd_pipeline():\n    def check_llvm(n, lanes):\n        A = te.placeholder((n,), name=\"A\", dtype=\"float32x%d\" % lanes)\n        B = te.compute((n,), lambda i: A[i], name=\"B\")\n        C = te.compute((n,), lambda i: B[i] + tvm.tir.const(1, A.dtype), name=\"C\")\n        s = te.create_schedule(C.op)\n        xo, xi = s[C].split(C.op.axis[0], nparts=2)\n        _, xi = s[C].split(xi, factor=2)\n        s[C].parallel(xo)\n        s[C].vectorize(xi)\n        s[B].compute_at(s[C], xo)\n        xo, xi = s[B].split(B.op.axis[0], factor=2)\n        s[B].vectorize(xi)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.empty((n,), A.dtype).copyfrom(np.random.uniform(size=(n, lanes)))\n        c = tvm.nd.empty((n,), C.dtype, dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n    check_llvm(64, 2)\n    check_llvm(512, 2)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_madd_pipeline():\n    def check_llvm(nn, base, stride):\n        n = tvm.runtime.convert(nn)\n        A = te.placeholder((n + base, stride), name=\"A\")\n        C = te.compute((n, stride), lambda i, j: A(base + i, j) + 1, name=\"C\")\n        s = te.create_schedule(C.op)\n        xo, xi = s[C].split(C.op.axis[0], factor=4)\n        s[C].parallel(xo)\n        s[C].vectorize(xi)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=(n + base, stride)).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros((n, stride), dtype=C.dtype), dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy()[base:] + 1)\n\n    check_llvm(64, 0, 2)\n    check_llvm(4, 0, 1)\n\n    with tvm.transform.PassContext(config={\"tir.noalias\": False}):\n        check_llvm(4, 0, 3)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_temp_space():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda i: A(i) + 1, name=\"B\")\n    C = te.compute(A.shape, lambda i: B(i) + 1, name=\"C\")\n    s = te.create_schedule(C.op)\n\n    def check_llvm():\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        f(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1 + 1)\n\n    check_llvm()\n\n\n@tvm.testing.requires_llvm\ndef test_multiple_func():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    s[C].parallel(xo)\n    s[C].vectorize(xi)\n\n    def check_llvm():\n        # build two functions\n        f2 = tvm.lower(s, [A, B, C], name=\"fadd1\")\n        f1 = tvm.lower(s, [A, B, C], name=\"fadd2\")\n        m = tvm.build([f1, f2], \"llvm\")\n        fadd2 = m[\"fadd2\"]\n        fadd1 = m[\"fadd1\"]\n\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        n = nn\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        fadd1(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n        fadd2(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_llvm()\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_condition():\n    def check_llvm(n, offset):\n        A = te.placeholder((n,), name=\"A\")\n        C = te.compute((n,), lambda i: tvm.tir.if_then_else(i >= offset, A[i], 0.0), name=\"C\")\n        s = te.create_schedule(C.op)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        f(a, c)\n        c_np = a.numpy()\n        c_np[:offset] = 0\n        tvm.testing.assert_allclose(c.numpy(), c_np)\n\n    check_llvm(64, 8)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_bool():\n    def check_llvm(n):\n        A = te.placeholder((n,), name=\"A\", dtype=\"int32\")\n        C = te.compute((n,), lambda i: A[i].equal(1).astype(\"float\"), name=\"C\")\n        s = te.create_schedule(C.op)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, C], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.randint(0, 2, size=(n,)).astype(A.dtype), dev)\n        c = tvm.nd.empty((n,), C.dtype, dev)\n        f(a, c)\n        c_np = a.numpy() == 1\n        tvm.testing.assert_allclose(c.numpy(), c_np)\n\n    check_llvm(64)\n\n\n@tvm.testing.requires_llvm\ndef test_rank_zero():\n    def check_llvm(n):\n        A = te.placeholder((n,), name=\"A\")\n        scale = te.placeholder((), name=\"scale\")\n        k = te.reduce_axis((0, n), name=\"k\")\n        C = te.compute((), lambda: te.sum(A[k] * scale(), axis=k), name=\"C\")\n        D = te.compute((), lambda: C() + 1)\n        s = te.create_schedule(D.op)\n        # build and invoke the kernel.\n        f = tvm.build(s, [A, scale, D], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.randint(0, 2, size=(n,)).astype(A.dtype), dev)\n        sc = tvm.nd.array(np.random.randint(0, 2, size=()).astype(scale.dtype), dev)\n        d = tvm.nd.empty((), D.dtype, dev)\n        f(a, sc, d)\n        d_np = np.sum(a.numpy()) * sc.numpy() + 1\n        tvm.testing.assert_allclose(d.numpy(), d_np)\n\n    check_llvm(64)\n\n\n@tvm.testing.requires_llvm\ndef test_rank_zero_bound_checkers():\n    def check_llvm(n):\n        with tvm.transform.PassContext(config={\"tir.instrument_bound_checkers\": True}):\n            A = te.placeholder((n,), name=\"A\")\n            scale = te.placeholder((), name=\"scale\")\n            k = te.reduce_axis((0, n), name=\"k\")\n            C = te.compute((), lambda: te.sum(A[k] * scale(), axis=k), name=\"C\")\n            D = te.compute((), lambda: C() + 1)\n            s = te.create_schedule(D.op)\n            # build and invoke the kernel.\n            f = tvm.build(s, [A, scale, D], \"llvm\")\n            dev = tvm.cpu(0)\n            # launch the kernel.\n            a = tvm.nd.array(np.random.randint(0, 2, size=(n,)).astype(A.dtype), dev)\n            sc = tvm.nd.array(np.random.randint(0, 2, size=()).astype(scale.dtype), dev)\n            d = tvm.nd.empty((), D.dtype, dev)\n            f(a, sc, d)\n            d_np = np.sum(a.numpy()) * sc.numpy() + 1\n            tvm.testing.assert_allclose(d.numpy(), d_np)\n\n    check_llvm(64)\n\n\n@tvm.testing.requires_llvm\ndef test_alignment():\n    n = tvm.runtime.convert(1024)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda i: A[i] * 3, name=\"B\")\n    s = te.create_schedule(B.op)\n    bx, tx = s[B].split(B.op.axis[0], factor=8)\n    s[B].vectorize(tx)\n    f = tvm.build(s, [A, B], \"llvm\", name=\"test_alignment\")\n\n    lines = f.get_source().split(\"\\n\")\n\n    # Check alignment on load/store.\n    for l in lines:\n        if \"align\" in l and \"4 x float\" in l:\n            assert \"align 32\" in l\n\n    # Check parameter alignment. This looks for the definition of the\n    # outlined \"compute_\" function to see if there is an \"align\" attribute\n    # listed there.\n    def has_param_alignment():\n        for l in lines:\n            if re.search(r\"test_alignment_compute_\\([^(]*align [0-9]\", l):\n                return True\n        return False\n\n    if tvm.target.codegen.llvm_version_major() >= 5:\n        assert has_param_alignment()\n\n    # Check for assume intrinsics. This isn't 100% accurate, since it just\n    # checks if the llvm.assume is there, but detailed check would require\n    # a much more detailed analysis of the LLVM IR.\n    def has_call_to_assume():\n        for l in lines:\n            if re.search(r\"call.*llvm.assume\", l):\n                return True\n        return False\n\n    assert has_call_to_assume()\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_div():\n    \"\"\"Check that the semantics of div and mod is correct\"\"\"\n\n    def check(start, end, dstart, dend, dtype, floor_div=False):\n        div = tvm.te.floordiv if floor_div else tvm.tir.truncdiv\n        mod = tvm.te.floormod if floor_div else tvm.tir.truncmod\n\n        # A are dividends, B are divisors. Note that we add 1 to make include end in the range.\n        A = te.placeholder((end - start + 1,), name=\"A\", dtype=dtype)\n        B = te.placeholder((dend - dstart + 1,), name=\"B\", dtype=dtype)\n        # We clip values with min and max so that simplifiers know the ranges of values\n\n        def clipa(x):\n            return tvm.te.min(tvm.tir.const(end, dtype), tvm.te.max(tvm.tir.const(start, dtype), x))\n\n        def clipb(x):\n            return tvm.te.min(\n                tvm.tir.const(dend, dtype), tvm.te.max(tvm.tir.const(dstart, dtype), x)\n            )\n\n        # If the range is just a single point, use the constant itself\n        if start == end:\n\n            def clipa(x):\n                return tvm.tir.const(start, dtype)\n\n        if dstart == dend:\n\n            def clipb(x):\n                return tvm.tir.const(dstart, dtype)\n\n        # D are division results and M are modulo results\n        [D, M] = te.compute(\n            (end - start + 1, dend - dstart + 1),\n            lambda i, j: (div(clipa(A[i]), clipb(B[j])), mod(clipa(A[i]), clipb(B[j]))),\n        )\n\n        s = te.create_schedule([D.op, M.op])\n        f = tvm.build(s, [A, B, D, M], \"llvm\")\n\n        # Fill input arrays with values\n        A_arr = tvm.nd.empty((end - start + 1,), dtype)\n        B_arr = tvm.nd.empty((dend - dstart + 1,), dtype)\n        A_arr.copyfrom(np.arange(start, end + 1, dtype=dtype))\n        B_np = np.arange(dstart, dend + 1, dtype=dtype)\n        # If the range of the divisor contains 0, replace it with 1 to avoid division by zero\n        if dend >= 0 and dstart <= 0:\n            B_np[-dstart] = 1\n        B_arr.copyfrom(B_np)\n        D_arr = tvm.nd.empty((end - start + 1, dend - dstart + 1), dtype)\n        M_arr = tvm.nd.empty((end - start + 1, dend - dstart + 1), dtype)\n\n        # Run the function and convert the results to numpy\n        f(A_arr, B_arr, D_arr, M_arr)\n        D_arr = D_arr.numpy()\n        M_arr = M_arr.numpy()\n\n        # This helper just prints additional info on failure\n        def _show_info():\n            print(\"dtype: {}\".format(dtype))\n            print(\"dividend range: [{}, {}]\".format(start, end))\n            print(\"divisor range: [{}, {}]\".format(dstart, dend))\n            lowered = tvm.lower(s, [A, B, D, M], simple_mode=True)\n            print(\"Lowered code:\")\n            print(lowered)\n\n        # Check that the computed values are correct\n        for i in range(start, end + 1):\n            for j in range(dstart, dend + 1):\n                if j == 0:\n                    continue\n\n                if floor_div:\n                    dref = i // j\n                    mref = i % j\n                else:\n                    dref = int(float(i) / j)\n                    mref = int(math.fmod(i, j))\n\n                if D_arr[i - start, j - dstart] != dref:\n                    _show_info()\n                    raise AssertionError(\n                        \"Incorrect division result: {}({}, {}) is {} \"\n                        \"but should be {}\".format(\n                            div.__name__, i, j, D_arr[i - start, j - dstart], dref\n                        )\n                    )\n                if M_arr[i - start, j - dstart] != mref:\n                    _show_info()\n                    raise AssertionError(\n                        \"Incorrect modulo result: {}({}, {}) is {} \"\n                        \"but should be {}\".format(\n                            mod.__name__, i, j, M_arr[i - start, j - dstart], mref\n                        )\n                    )\n\n    # Try different ranges to cover different cases\n    for start, end in [\n        (-12, -12),\n        (-11, -1),\n        (-11, 0),\n        (0, 0),\n        (12, 12),\n        (1, 11),\n        (0, 11),\n        (-11, 11),\n    ]:\n        for dstart, dend in [\n            (-11, -1),\n            (-11, 0),\n            (-4, -4),\n            (-2, -2),\n            (1, 11),\n            (0, 11),\n            (4, 4),\n            (2, 2),\n            (-11, 11),\n        ]:\n            if end < start or dend < dstart or (dend == 0 and dstart == 0):\n                continue\n            check(start, end, dstart, dend, \"int32\", floor_div=False)\n            check(start, end, dstart, dend, \"int32\", floor_div=True)\n            check(start, end, dstart, dend, \"int8\", floor_div=False)\n            check(start, end, dstart, dend, \"int8\", floor_div=True)\n            if start >= 0 and dstart >= 0:\n                check(start, end, dstart, dend, \"uint32\", floor_div=False)\n                check(start, end, dstart, dend, \"uint32\", floor_div=True)\n\n    # Additional tests for uint8\n    for dstart, dend in [(0, 11), (1, 11), (2, 2), (4, 4)]:\n        check(123, 133, dstart, dend, \"uint8\", floor_div=False)\n        check(123, 133, dstart, dend, \"uint8\", floor_div=True)\n        check(0, 255, dstart, dend, \"uint8\", floor_div=False)\n        check(0, 255, dstart, dend, \"uint8\", floor_div=True)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_fp_math():\n    def check_llvm_reciprocal(n):\n        A = te.placeholder((n,), name=\"A\")\n        B = te.compute((n,), lambda i: te.div(1.0, (1e37 * A[i])), name=\"B\")\n\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], \"llvm\")\n\n        a = tvm.nd.array(np.full((n,), 100, \"float32\"))\n        b = tvm.nd.empty((n,), \"float32\")\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np.zeros((n,), \"float32\"))\n\n    check_llvm_reciprocal(4)\n    check_llvm_reciprocal(8)\n    check_llvm_reciprocal(16)\n\n    def check_llvm_sigmoid(n):\n        A = te.placeholder((n,), name=\"A\")\n        B = te.compute((n,), lambda i: te.sigmoid(A[i]), name=\"B\")\n\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], \"llvm\")\n\n        a = tvm.nd.array(np.full((n,), -1000, \"float32\"))\n        b = tvm.nd.empty((n,), \"float32\")\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np.zeros((n,), \"float32\"))\n\n    check_llvm_sigmoid(4)\n    check_llvm_sigmoid(8)\n    check_llvm_sigmoid(16)\n\n\n@tvm.testing.requires_llvm\ndef test_dwarf_debug_information():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    s[C].parallel(xo)\n    s[C].vectorize(xi)\n\n    def check_llvm_object():\n        if tvm.target.codegen.llvm_version_major() < 5:\n            return\n        if tvm.target.codegen.llvm_version_major() > 6:\n            return\n        # build two functions\n        f2 = tvm.lower(s, [A, B, C], name=\"fadd1\")\n        f1 = tvm.lower(s, [A, B, C], name=\"fadd2\")\n        m = tvm.build([f1, f2], \"llvm\")\n        temp = utils.tempdir()\n        o_path = temp.relpath(\"temp.o\")\n        m.save(o_path)\n        import shutil\n        import subprocess\n        import sys\n\n        # Try the dwarfdump utility (OS X)\n        if shutil.which(\"dwarfdump\"):\n            output = subprocess.check_output([\"dwarfdump\", o_path])\n            assert re.search(r\"\"\"DW_AT_name\\\\t\\(\"fadd1\"\\)\"\"\", str(output))\n            assert re.search(r\"\"\"DW_AT_name\\\\t\\(\"fadd2\"\\)\"\"\", str(output))\n\n        # Try gobjdump (OS X)\n        if shutil.which(\"gobjdump\"):\n            output = subprocess.check_output([\"gobjdump\", \"--dwarf\", o_path])\n            assert re.search(r\"\"\"DW_AT_name.*fadd1\"\"\", str(output))\n            assert re.search(r\"\"\"DW_AT_name.*fadd2\"\"\", str(output))\n\n        # Try objdump (Linux) - Darwin objdump has different DWARF syntax.\n        if shutil.which(\"objdump\") and sys.platform != \"darwin\":\n            output = subprocess.check_output([\"objdump\", \"--dwarf\", o_path])\n            assert re.search(r\"\"\"DW_AT_name.*fadd1\"\"\", str(output))\n            assert re.search(r\"\"\"DW_AT_name.*fadd2\"\"\", str(output))\n\n    def check_llvm_ir():\n        if tvm.target.codegen.llvm_version_major() < 5:\n            return\n        if tvm.target.codegen.llvm_version_major() > 6:\n            return\n        # build two functions\n        f2 = tvm.lower(s, [A, B, C], name=\"fadd1\")\n        f1 = tvm.lower(s, [A, B, C], name=\"fadd2\")\n        m = tvm.build([f1, f2], target=\"llvm -mtriple=aarch64-linux-gnu\")\n        ll = m.get_source(\"ll\")\n\n        # On non-Darwin OS, don't explicitly specify DWARF version.\n        import re\n\n        assert not re.search(r\"\"\"\"Dwarf Version\"\"\" \"\", ll)\n        assert re.search(r\"\"\"llvm.dbg.value\"\"\", ll)\n\n        # Try Darwin, require DWARF-2\n        m = tvm.build([f1, f2], target=\"llvm -mtriple=x86_64-apple-darwin-macho\")\n        ll = m.get_source(\"ll\")\n        assert re.search(r\"\"\"i32 4, !\"Dwarf Version\", i32 2\"\"\", ll)\n        assert re.search(r\"\"\"llvm.dbg.value\"\"\", ll)\n\n    check_llvm_object()\n    check_llvm_ir()\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_shuffle():\n    a = te.placeholder((8,), \"int32\")\n    b = te.placeholder((8,), \"int32\")\n    c = te.compute((8,), lambda x: a[x] + b[7 - x])\n    sch = te.create_schedule(c.op)\n\n    def my_vectorize():\n        def vectorizer(op):\n            store = op.body\n            idx = tvm.tir.Ramp(tvm.tir.const(0, \"int32\"), tvm.tir.const(1, \"int32\"), 8)\n            value = store.value\n            b_idx = tvm.tir.Shuffle([idx], [tvm.tir.const(i, \"int32\") for i in range(7, -1, -1)])\n            new_a = tvm.tir.BufferLoad(value.a.buffer, [idx])\n            new_b = tvm.tir.BufferLoad(value.b.buffer, [b_idx])\n            value = new_a + new_b\n            return tvm.tir.BufferStore(store.buffer, new_a + new_b, [idx])\n\n        def _transform(f, *_):\n            return f.with_body(\n                tvm.tir.stmt_functor.ir_transform(f.body, None, vectorizer, [\"tir.For\"])\n            )\n\n        return tvm.tir.transform.prim_func_pass(_transform, opt_level=0, name=\"my_vectorize\")\n\n    with tvm.transform.PassContext(config={\"tir.add_lower_pass\": [(1, my_vectorize())]}):\n        ir = tvm.lower(sch, [a, b, c], simple_mode=True)\n        module = tvm.build(sch, [a, b, c])\n        a_ = tvm.nd.array(np.arange(1, 9, dtype=\"int32\"))\n        b_ = tvm.nd.array(np.arange(8, 0, -1, dtype=\"int32\"))\n        c_ = tvm.nd.array(np.zeros((8,), dtype=\"int32\"))\n        module(a_, b_, c_)\n        tvm.testing.assert_allclose(c_.numpy(), (a_.numpy() * 2).astype(\"int32\"))\n\n\ndef np_float2np_bf16(arr):\n    \"\"\"Convert a numpy array of float to a numpy array\n    of bf16 in uint16\"\"\"\n    orig = arr.view(\"<u4\")\n    bias = np.bitwise_and(np.right_shift(orig, 16), 1) + 0x7FFF\n    return np.right_shift(orig + bias, 16).astype(\"uint16\")\n\n\ndef np_float2tvm_bf16(arr):\n    \"\"\"Convert a numpy array of float to a TVM array\n    of bf16\"\"\"\n    nparr = np_float2np_bf16(arr)\n    return tvm.nd.empty(nparr.shape, \"uint16\").copyfrom(nparr)\n\n\ndef np_bf162np_float(arr):\n    \"\"\"Convert a numpy array of bf16 (uint16) to a numpy array\n    of float\"\"\"\n    u32 = np.left_shift(arr.astype(\"uint32\"), 16)\n    return u32.view(\"<f4\")\n\n\ndef np_bf16_cast_and_cast_back(arr):\n    \"\"\"Convert a numpy array of float to bf16 and cast back\"\"\"\n    return np_bf162np_float(np_float2np_bf16(arr))\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_bf16():\n    def dotest(do_vectorize):\n        np.random.seed(122)\n        A = te.placeholder((32,), dtype=\"bfloat16\")\n        B = te.placeholder((32,), dtype=\"bfloat16\")\n        d = te.compute((32,), lambda x: A[x] + B[x])\n        sch = te.create_schedule(d.op)\n        print(tvm.lower(sch, [A, B, d]))\n        if do_vectorize:\n            sch[d].vectorize(d.op.axis[0])\n        module = tvm.build(sch, [A, B, d])\n        npa = np.random.rand(32).astype(\"float32\")\n        npb = np.random.rand(32).astype(\"float32\")\n        va = np_bf16_cast_and_cast_back(npa)\n        vb = np_bf16_cast_and_cast_back(npb)\n        res = np_bf16_cast_and_cast_back(va + vb)\n        a_ = np_float2tvm_bf16(npa)\n        b_ = np_float2tvm_bf16(npb)\n        c_ = tvm.nd.empty((32,), \"uint16\")\n        module(a_, b_, c_)\n        tvm.testing.assert_allclose(np_bf162np_float(c_.numpy()), res)\n\n    dotest(True)\n    dotest(False)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_crt_static_lib():\n    A = te.placeholder((32,), dtype=\"bfloat16\")\n    B = te.placeholder((32,), dtype=\"bfloat16\")\n    d = te.compute((32,), lambda x: A[x] + B[x])\n    sch = te.create_schedule(d.op)\n    module = tvm.build(\n        sch,\n        [A, B, d],\n        target=tvm.target.Target(\"llvm\"),\n        runtime=Runtime(\"crt\", {\"system-lib\": True}),\n    )\n    print(module.get_source())\n    module.save(\"test.o\")\n\n\ndef atomic_add(x, y):\n    return tvm.tir.call_intrin(y.dtype, \"tir.atomic_add\", x, y)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_lower_atomic():\n    def do_atomic_add(A):\n        ib = tvm.tir.ir_builder.create()\n        n = A.shape[0]\n        atomic_add_return = ib.allocate(A.dtype, (1,), name=\"atomic_add_return\", scope=\"local\")\n        one = tvm.tir.const(1, A.dtype)\n        A_ptr = ib.buffer_ptr(A)\n        with ib.for_range(0, n, name=\"i\", kind=\"parallel\") as i:\n            atomic_add_return[0] = atomic_add(\n                tvm.tir.call_intrin(\"handle\", \"tir.address_of\", A_ptr[0]), one\n            )\n        return ib.get()\n\n    A = tvm.te.placeholder((100,), dtype=\"int32\", name=\"A\")\n    C = tvm.te.extern((100,), [A], lambda ins, _: do_atomic_add(ins[0]), name=\"C\", dtype=\"int32\")\n    s = tvm.te.create_schedule(C.op)\n    # This does not work because of pointer type mismatch\n    # TVMError: LLVM module verification failed with the following errors:\n    # Argument value type does not match pointer operand type!\n    # %21 = atomicrmw add i8* %7, i32 1 monotonic\n    # i8\n    # f = tvm.build(s, [A], target=\"llvm\")\n\n\n@tvm.testing.requires_llvm\n@tvm.testing.requires_gpu\ndef test_llvm_gpu_lower_atomic():\n    def do_atomic_add(A):\n        ib = tvm.tir.ir_builder.create()\n        n = A.shape[0]\n        atomic_add_return = ib.allocate(A.dtype, (1,), name=\"atomic_add_return\", scope=\"local\")\n        one = tvm.tir.const(1, A.dtype)\n        A_ptr = ib.buffer_ptr(A)\n        nthread_tx = 64\n        with ib.new_scope():\n            nthread_bx = (n + nthread_tx - 1) // nthread_tx\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n            ib.scope_attr(tx, \"thread_extent\", nthread_tx)\n            ib.scope_attr(bx, \"thread_extent\", nthread_bx)\n            atomic_add_return[0] = atomic_add(\n                tvm.tir.call_intrin(\"handle\", \"tir.address_of\", A_ptr[0]), one\n            )\n        return ib.get()\n\n    size = 1024\n    # CI uses LLVM 8, which does not support float atomic\n    for dtype in [\"int32\"]:\n        A = tvm.te.placeholder((size,), dtype=dtype, name=\"A\")\n        C = tvm.te.extern((size,), [A], lambda ins, _: do_atomic_add(ins[0]), dtype=dtype)\n        s = tvm.te.create_schedule(C.op)\n        f = tvm.build(s, [A], target=\"nvptx\")\n\n        dev = tvm.cuda()\n        a = tvm.nd.array(np.zeros((size,)).astype(A.dtype), dev)\n        f(a)\n        ref = np.zeros((size,)).astype(A.dtype)\n        ref[0] = size\n        tvm.testing.assert_allclose(a.numpy(), ref, rtol=1e-5)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_order_functions():\n    \"\"\"Check that functions in the LLVM module are ordered alphabetically.\"\"\"\n\n    # Note: the order is alphabetical because that's a predictable ordering. Any predictable\n    # ordering will work fine, but if the ordering changes, this test will need to be updated.\n    def make_call_extern(caller, callee):\n        # Create a function:\n        #   float32 caller(float32 v) { return callee(v); }\n        ib = tvm.tir.ir_builder.create()\n        v = tvm.te.var(\"v\", dtype=\"float32\")\n        t = tvm.tir.call_extern(\"float32\", callee, v)\n        ib.emit(t)\n        return tvm.tir.PrimFunc([v], ib.get()).with_attr(\"global_symbol\", caller)\n\n    # Create some functions in a random order.\n    functions = {\n        \"Danny\": make_call_extern(\"Danny\", \"Dave\"),\n        \"Sammy\": make_call_extern(\"Sammy\", \"Eve\"),\n        \"Kirby\": make_call_extern(\"Kirby\", \"Fred\"),\n    }\n    mod = tvm.IRModule(functions=functions)\n    ir_text = tvm.build(mod, None, target=\"llvm\").get_source(\"ll\")\n    # Skip functions whose names start with _.\n    matches = re.findall(r\"^define[^@]*@([a-zA-Z][a-zA-Z0-9_]*)\", ir_text, re.MULTILINE)\n    assert matches == sorted(matches)\n\n\n@tvm.testing.requires_llvm\n@tvm.testing.skip_if_32bit\ndef test_llvm_import():\n    \"\"\"all-platform-minimal-test: check shell dependent clang behavior.\"\"\"\n    # extern \"C\" is necessary to get the correct signature\n    cc_code = \"\"\"\n    extern \"C\" float my_add(float x, float y) {\n      return x + y;\n    }\n    \"\"\"\n    n = 10\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(\n        (n,), lambda *i: tvm.tir.call_pure_extern(\"float32\", \"my_add\", A(*i), 1.0), name=\"B\"\n    )\n\n    def check_llvm(use_file):\n        if not clang.find_clang(required=False):\n            print(\"skip because clang is not available\")\n            return\n        temp = utils.tempdir()\n        ll_path = temp.relpath(\"temp.ll\")\n        ll_code = clang.create_llvm(cc_code, output=ll_path)\n        s = te.create_schedule(B.op)\n        if use_file:\n            s[B].pragma(s[B].op.axis[0], \"import_llvm\", ll_path)\n        else:\n            s[B].pragma(s[B].op.axis[0], \"import_llvm\", ll_code)\n        # BUILD and invoke the kernel.\n        f = tvm.build(s, [A, B], \"llvm\")\n        dev = tvm.cpu(0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), a.numpy() + 1.0)\n\n    check_llvm(use_file=True)\n    check_llvm(use_file=False)\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_scalar_concat():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    z = tvm.tir.decl_buffer((1,), \"int32x2\")\n    s = tvm.tir.Shuffle([x, y], [0, 1])\n    f = tvm.tir.PrimFunc([x, y, z], z.vstore(0, s))\n\n    mod = tvm.ir.IRModule.from_expr(f.with_attr(\"global_symbol\", \"codegen_scalar_concat\"))\n\n    # This will crash in LLVM codegen if CodeGenLLVM::CreateVecConcat doesn't convert\n    # scalars to single-lane LLVM vectors.\n    with tvm.transform.PassContext(config={\"tir.disable_assert\": True}):\n        m = tvm.build(mod, [x, y, z], target=\"llvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_raise_exception_during_codegen():\n    @T.prim_func\n    def threadpool_nested_parallel_loop(\n        A: T.Buffer[(4, 4), \"float32\"], B: T.Buffer[(4, 4), \"float32\"]\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i in T.parallel(4):\n            for j in T.parallel(4):\n                B[i, j] = A[i, j] * 2.0\n\n    with pytest.raises(tvm.TVMError) as e:\n        tvm.build({\"llvm\": tvm.IRModule.from_expr(threadpool_nested_parallel_loop)})\n    msg = str(e)\n    assert msg.find(\"Nested parallel loop is not supported\") != -1\n\n\n@tvm.testing.requires_llvm\ndef test_llvm_target_attributes():\n    \"\"\"Check that when LLVM codegen creates new functions, they get the same target\n    attributes as the original function.\n    \"\"\"\n    n = te.var()\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n    B = te.compute((n,), lambda i: A[i], name=\"B\")\n    C = te.compute((n,), lambda i: B[i] + tvm.tir.const(1, A.dtype), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], nparts=2)\n    s[C].parallel(xo)\n\n    target_llvm = \"llvm -mcpu=skylake -mattr=+avx512f\"\n    target = tvm.target.Target(target_llvm, host=target_llvm)\n    module = tvm.build(s, [A, B, C, n], target=target, name=\"test_func\")\n\n    llvm_ir = module.get_source()\n    llvm_ir_lines = llvm_ir.split(\"\\n\")\n\n    attribute_definitions = dict()\n    attributes_with_target = dict()\n    functions_with_target = []\n\n    for line in llvm_ir_lines:\n        func_def = re.match(\n            \"define.* @(?P<func_name>[^(]*)[(].* #(?P<attr_num>[0-9]+) (!.* |){$\", line\n        )\n        if func_def:\n            functions_with_target.append(func_def.group(\"func_name\"))\n            attributes_with_target[func_def.group(\"attr_num\")] = True\n            continue\n        attr_def = re.match(\"attributes #(?P<attr_num>[0-9]+) = {(?P<attr_list>.*)}\", line)\n        if attr_def:\n            attribute_definitions[attr_def.group(\"attr_num\")] = attr_def.group(\"attr_list\")\n\n    for k in list(attributes_with_target.keys()):\n        assert re.match('.*\"target-cpu\"=\"skylake\".*', attribute_definitions[k])\n        assert re.match('.*\"target-features\"=\".*[+]avx512f.*\".*', attribute_definitions[k])\n\n    expected_functions = [\"test_func\", \"test_func_compute_\", \"__tvm_parallel_lambda\"]\n    for n in expected_functions:\n        assert n in functions_with_target\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_metal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import topi\nimport unittest\nfrom tvm.contrib.nvcc import have_fp16, have_int8, have_bf16\nfrom tvm.contrib import nvcc\nimport tvm.testing\n\ntx = te.thread_axis(\"threadIdx.x\")\nbx = te.thread_axis(\"blockIdx.x\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_metal\ndef test_metal_inf_nan():\n    target = \"metal\"\n\n    def check_inf_nan(dev, n, value, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        inf_value = tvm.tir.const(value, dtype=dtype)\n        C = te.compute((n,), lambda i: inf_value, name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], tx)\n        fun = tvm.build(s, [A, C], target)\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float16\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float16\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_metal\ndef test_metal_erf():\n    target = \"metal\"\n\n    def check_erf(dev, n, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        C = te.compute(A.shape, lambda *i: te.erf(A(*i)), name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], tx)\n        fun = tvm.build(s, [A, C], target)\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_erf(dev, 1, \"float32\")\n    check_erf(dev, 1, \"float16\")\n\n\nif __name__ == \"__main__\":\n    test_metal_inf_nan()\n    test_metal_erf()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_opencl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport tvm.testing\nimport re\n\ntarget = \"opencl\"\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_opencl\ndef test_opencl_ternary_expression():\n    def check_if_then_else(dev, n, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        true_value = tvm.tir.const(1, dtype=dtype)\n        false_value = tvm.tir.const(3, dtype=dtype)\n        max_lhs = tvm.tir.const(2, dtype=dtype)\n        max_rhs = tvm.tir.if_then_else(A[0] > 0, true_value, false_value)\n        C = te.compute((n,), lambda i: tvm.te.max(max_lhs, max_rhs), name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n        fun = tvm.build(s, [A, C], target)\n\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    def check_select(dev, n, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        true_value = tvm.tir.const(1, dtype=dtype)\n        false_value = tvm.tir.const(3, dtype=dtype)\n        max_lhs = tvm.tir.const(2, dtype=dtype)\n        max_rhs = tvm.tir.Select(A[0] > 0, true_value, false_value)\n        C = te.compute((n,), lambda i: tvm.te.max(max_lhs, max_rhs), name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n        fun = tvm.build(s, [A, C], target)\n\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_if_then_else(dev, 1, \"int8\")\n    check_if_then_else(dev, 1, \"uint8\")\n    check_if_then_else(dev, 1, \"int16\")\n    check_if_then_else(dev, 1, \"uint16\")\n    check_select(dev, 1, \"int8\")\n    check_select(dev, 1, \"uint8\")\n    check_select(dev, 1, \"int16\")\n    check_select(dev, 1, \"uint16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_opencl\ndef test_opencl_inf_nan():\n    def check_inf_nan(dev, n, value, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        inf_value = tvm.tir.const(value, dtype=dtype)\n        C = te.compute((n,), lambda i: inf_value, name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n        fun = tvm.build(s, [A, C], target)\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float64\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_opencl\ndef test_opencl_max():\n    def check_max(dev, n, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        max_lhs = A[0] + tvm.tir.const(1, dtype=dtype)\n        max_rhs = tvm.tir.const(0, dtype=dtype)\n        C = te.compute((n,), lambda i: tvm.te.max(max_lhs, max_rhs), name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n        fun = tvm.build(s, [A, C], target)\n\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.device(target, 0)\n\n    check_max(dev, 1, \"int8\")\n    check_max(dev, 1, \"uint8\")\n    check_max(dev, 1, \"int16\")\n    check_max(dev, 1, \"uint16\")\n    check_max(dev, 1, \"float32\")\n    check_max(dev, 1, \"float64\")\n\n\ndef test_opencl_erf():\n    def check_erf(dev, n, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        C = te.compute(A.shape, lambda *i: te.erf(A(*i)), name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n        fun = tvm.build(s, [A, C], target)\n        source_str = fun.imported_modules[0].get_source()\n        matches = re.findall(\"erf\", source_str)\n        error_matches = re.findall(\"erff\", source_str)\n        assert len(matches) == 1 and len(error_matches) == 0\n\n    dev = tvm.device(target, 0)\n\n    check_erf(dev, 1, \"float32\")\n    check_erf(dev, 1, \"float64\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_opencl\ndef test_opencl_type_casting():\n    def check_type_casting(ctx, n, dtype):\n        block_size = 4\n        C = te.compute(\n            (n,),\n            lambda i: tvm.tir.Select(\n                tvm.tir.all(\n                    *[\n                        i // block_size == tvm.tir.const(3, \"int32\"),\n                        i % block_size == tvm.tir.const(3, \"int32\"),\n                    ]\n                ),\n                tvm.tir.const(1, dtype),\n                tvm.tir.const(0, dtype),\n            ),\n            name=\"C\",\n        )\n        s = te.create_schedule(C.op)\n        (tx, vx) = s[C].split(s[C].op.axis[0], factor=block_size)\n        s[C].vectorize(vx)\n        thrx = te.thread_axis(\"threadIdx.x\")\n\n        s[C].bind(tx, thrx)\n        fun = tvm.build(s, [C], target)\n\n        c = tvm.nd.empty((n,), dtype, ctx)\n        assembly = fun.imported_modules[0].get_source()\n        false_branch = \"((float4)(0.000000e+00f, 0.000000e+00f, 0.000000e+00f, 0.000000e+00f))\"\n        true_branch = \"((float4)(1.000000e+00f, 1.000000e+00f, 1.000000e+00f, 1.000000e+00f))\"\n        lcond = \"(convert_uint4(((uint4)((((int)get_local_id(0)) == 3), (((int)get_local_id(0)) == 3), (((int)get_local_id(0)) == 3), (((int)get_local_id(0)) == 3)))))\"\n        rcond = \"(convert_uint4((((int4)((0)+(1*0), (0)+(1*1), (0)+(1*2), (0)+(1*3))) == ((int4)(3, 3, 3, 3)))))\"\n        cond = \"({} && {})\".format(lcond, rcond)\n        select = \"select({}, {}, {})\".format(false_branch, true_branch, cond)\n        count = assembly.count(select)\n        assert count == 1\n\n        fun(c)\n\n    dev = tvm.device(target, 0)\n\n    check_type_casting(dev, 16, \"float32\")\n\n\nif __name__ == \"__main__\":\n    test_opencl_ternary_expression()\n    test_opencl_inf_nan()\n    test_opencl_max()\n    test_opencl_erf()\n    test_opencl_type_casting()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_rocm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nimport unittest\n\ntx = te.thread_axis(\"threadIdx.x\")\nty = te.thread_axis(\"threadIdx.y\")\nbx = te.thread_axis(\"blockIdx.x\")\nby = te.thread_axis(\"blockIdx.y\")\n\n\n@tvm.testing.requires_rocm\ndef test_rocm_cross_thread_reduction():\n    # based on the reduction tutorial\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"k\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n    s = te.create_schedule(B.op)\n    ko, ki = s[B].split(B.op.reduce_axis[0], factor=16)\n    BF = s.rfactor(B, ki)\n    xo, xi = s[B].split(s[B].op.axis[0], factor=32)\n    s[B].bind(xo, bx)\n    s[B].bind(xi, ty)\n    s[B].bind(s[B].op.reduce_axis[0], tx)\n    s[BF].compute_at(s[B], s[B].op.reduce_axis[0])\n    s[B].set_store_predicate(tx.var.equal(0))\n    frocm = tvm.build(s, [A, B], \"rocm\")\n\n    nn = 128\n    dev = tvm.rocm(0)\n    a = tvm.nd.array(np.random.uniform(size=(nn, nn)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev)\n    frocm(a, b)\n    tvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=1), rtol=1e-4)\n\n\n@tvm.testing.requires_rocm\ndef test_rocm_inf_nan():\n    def check_inf_nan(dev, n, value, dtype):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        inf_value = tvm.tir.const(value, dtype=dtype)\n        C = te.compute((n,), lambda i: inf_value, name=\"C\")\n        s = te.create_schedule(C.op)\n        s[C].bind(s[C].op.axis[0], tx)\n        fun = tvm.build(s, [A, C], \"rocm\")\n        a = tvm.nd.empty((n,), A.dtype, dev)\n        c = tvm.nd.empty((n,), A.dtype, dev)\n        # Only need to test compiling here\n        fun(a, c)\n\n    dev = tvm.rocm(0)\n\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, -float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"inf\"), \"float64\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float32\")\n    check_inf_nan(dev, 1, float(\"nan\"), \"float64\")\n\n\n@tvm.testing.requires_rocm\ndef test_rocm_reduction_binding():\n    k = te.reduce_axis((0, 32), \"k\")\n    A = te.placeholder((96, 32), name=\"A\")\n    B = te.compute((96,), lambda m: te.sum(A[m, k], axis=k), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    s[B].reorder(B.op.reduce_axis[0], B.op.axis[0])\n\n    mo, _ = s[B].split(B.op.axis[0], 32)\n    s[B].bind(mo, bx)\n\n\n@tvm.testing.requires_rocm\ndef test_rocm_copy():\n    def check_rocm(dtype, n):\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        dev = tvm.rocm(0)\n        a_np = np.random.uniform(size=(n,)).astype(A.dtype)\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(a_np)\n        b_np = a.numpy()\n        tvm.testing.assert_allclose(a_np, b_np)\n        tvm.testing.assert_allclose(a_np, a.numpy())\n\n    for _ in range(100):\n        dtype = np.random.choice([\"float32\", \"float16\", \"int8\", \"int32\"])\n        logN = np.random.randint(1, 15)\n        peturb = np.random.uniform(low=0.5, high=1.5)\n        check_rocm(dtype, int(peturb * (2**logN)))\n\n\n@tvm.testing.requires_rocm\ndef test_rocm_vectorize_add():\n    num_thread = 8\n\n    def check_rocm(dtype, n, lanes):\n        A = te.placeholder((n,), name=\"A\", dtype=\"%sx%d\" % (dtype, lanes))\n        B = te.compute((n,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name=\"B\")\n        s = te.create_schedule(B.op)\n        xo, xi = s[B].split(B.op.axis[0], factor=num_thread)\n        s[B].bind(xo, bx)\n        s[B].bind(xi, tx)\n        fun = tvm.build(s, [A, B], \"rocm\")\n        dev = tvm.rocm(0)\n        a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np.random.uniform(size=(n, lanes)))\n        c = tvm.nd.empty((n,), B.dtype, dev)\n        fun(a, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n    check_rocm(\"float32\", 64, 2)\n    check_rocm(\"float16\", 64, 2)\n\n\nif __name__ == \"__main__\":\n    test_rocm_cross_thread_reduction()\n    test_rocm_inf_nan()\n    test_rocm_reduction_binding()\n    test_rocm_copy()\n    test_rocm_vectorize_add()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_static_init.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport ctypes\nimport numpy as np\n\n\ndef test_static_callback():\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    i = te.size_var(\"i\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.buffer_ptr(Ab)\n    cp = te.thread_axis((0, 1), \"cop\")\n    finit = tvm.tir.StringImm(\"TVMBackendRunOnce\")\n    ib.scope_attr(cp, \"coproc_uop_scope\", finit)\n    with ib.for_range(0, n, \"i\", kind=\"parallel\") as i:\n        A[i] = A[i] + 1\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"ramp\"))\n    f = tvm.driver.build(mod, target=\"llvm\")\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n    f(a)\n    f(a)\n    np.testing.assert_equal(a.numpy(), np.ones(a.shape[0]))\n\n\ndef test_static_init():\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    i = te.size_var(\"i\")\n    ib = tvm.tir.ir_builder.create()\n    handle = tvm.tir.call_intrin(\"handle\", \"tir.tvm_static_handle\")\n    ib.emit(tvm.tir.call_packed(\"test_static_callback\", handle, Ab))\n\n    @tvm.register_func(\"test_static_callback\")\n    def test_cb(sh, A):\n        assert isinstance(sh, ctypes.c_void_p)\n        return sh\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"ramp\"))\n    f = tvm.driver.build(mod, target=\"llvm\")\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n    f(a)\n\n\nif __name__ == \"__main__\":\n    test_static_callback()\n    test_static_init()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_vm_basic.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n\ndef run_jit(fapi, check):\n    for target in [\"llvm\", \"stackvm\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n        f = tvm.driver.build(fapi, target=target)\n        s = f.get_source()\n        check(f)\n\n\ndef test_stack_vm_basic():\n    a = tvm.nd.array(np.zeros(10, dtype=\"float32\"))\n\n    @tvm.register_func\n    def tvm_call_back_get_shape(shape0):\n        print(shape0)\n        assert shape0 == a.shape[0]\n\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), \"float32\")\n    stmt = tvm.tir.Evaluate(tvm.tir.call_packed(\"tvm_call_back_get_shape\", Ab.shape[0]))\n\n    mod = tvm.IRModule.from_expr(\n        tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"print_shape\")\n    )\n\n    run_jit(mod, lambda f: f(a))\n\n\n@tvm.register_func\ndef tvm_stack_vm_print(*x):\n    print(x)\n\n\ndef test_stack_vm_loop():\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    i = te.size_var(\"i\")\n\n    ib = tvm.tir.ir_builder.create()\n    A = ib.buffer_ptr(Ab)\n    with ib.for_range(0, n - 1, \"i\") as i:\n        A[i + 1] = A[i] + 1\n        ib.emit(tvm.tir.call_packed(\"tvm_stack_vm_print\", i))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"ramp\"))\n    a = tvm.nd.array(np.zeros(10, dtype=dtype))\n\n    def check(f):\n        f(a)\n        np.testing.assert_equal(a.numpy(), np.arange(a.shape[0]))\n\n    run_jit(mod, check)\n\n\ndef test_stack_vm_cond():\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n\n    ib = tvm.tir.ir_builder.create()\n    A = ib.buffer_ptr(Ab)\n    with ib.for_range(0, n - 1, \"i\") as i:\n        with ib.if_scope(tvm.tir.EQ(i, 4)):\n            A[i + 1] = A[i] + 1\n        with ib.else_scope():\n            A[i + 1] = A[i] + 2\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"test\"))\n\n    def check(f):\n        a = tvm.nd.array(np.zeros(10, dtype=dtype))\n        f(a)\n        y = np.arange(a.shape[0]) * 2\n        y[5:] -= 1\n        np.testing.assert_equal(a.numpy(), y)\n\n    run_jit(mod, check)\n\n\ndef test_vm_parallel():\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    i = te.size_var(\"i\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.buffer_ptr(Ab)\n    with ib.for_range(0, n, \"i\", kind=\"parallel\") as i:\n        A[i] = A[i] + 1\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"test\"))\n\n    def check(f):\n        a = tvm.nd.array(np.zeros(10, dtype=dtype))\n        f(a)\n        np.testing.assert_equal(a.numpy(), np.ones(a.shape[0]))\n\n    run_jit(mod, check)\n\n\nif __name__ == \"__main__\":\n    test_vm_parallel()\n    test_stack_vm_loop()\n    test_stack_vm_basic()\n    test_stack_vm_cond()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_vulkan.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nfrom posixpath import split\nimport random\nimport re\nimport threading\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import relay, te\nfrom tvm.topi.math import cast\n\n\ndtype = tvm.testing.parameter(\"float32\", \"int32\", \"float16\", \"int8\")\nfuzz_seed = tvm.testing.parameter(range(25))\n\n\n# Explicitly specify a target, as this test is looking at the\n# generated shader code, and is not running on an actual device.\n@tvm.testing.parametrize_targets(\n    \" \".join(\n        [\n            \"vulkan\",\n            \"-supports_int8=1\",\n            \"-supports_8bit_buffer=1\",\n            \"-supports_storage_buffer_storage_class=1\",\n            \"-supports_float16=1\",\n            \"-supports_16bit_buffer=1\",\n        ]\n    )\n)\ndef test_vector_comparison(target, dtype):\n    n = (1024,)\n    A = te.placeholder(n, dtype=dtype, name=\"A\")\n    B = te.compute(\n        A.shape,\n        lambda i: tvm.tir.Select(\n            A[i] >= 0, A[i] + tvm.tir.const(1, dtype), tvm.tir.const(0, dtype)\n        ),\n        name=\"B\",\n    )\n    s = te.create_schedule(B.op)\n\n    (bx, tx) = s[B].split(s[B].op.axis[0], factor=128)\n    (tx, vx) = s[B].split(tx, factor=4)\n    s[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[B].vectorize(vx)\n    f = tvm.build(s, [A, B], target)\n\n    # Verify we generate the boolx4 type declaration and the OpSelect\n    # v4{float,half,int} instruction\n    assembly = f.imported_modules[0].get_source()\n    matches = re.findall(\"%v4bool = OpTypeVector %bool 4\", assembly)\n    assert len(matches) == 1\n    matches = re.findall(\"OpSelect %v4.*\", assembly)\n    assert len(matches) == 1\n\n\ndef test_array_copy(dev, dtype, fuzz_seed):\n    np.random.seed(fuzz_seed)\n\n    log_arr_size = np.random.uniform(low=np.log(1), high=np.log(32768))\n    arr_size = np.exp(log_arr_size).astype(int)\n    a_np = np.random.uniform(size=(arr_size,)).astype(dtype)\n    a = tvm.nd.empty((arr_size,), dtype, dev).copyfrom(a_np)\n    b_np = a.numpy()\n    tvm.testing.assert_allclose(a_np, b_np)\n    tvm.testing.assert_allclose(a_np, a.numpy())\n\n\n@tvm.testing.exclude_targets(\"llvm\")\ndef test_array_vectorize_add(target, dev, dtype):\n    arr_size = 64\n    lanes = 2\n    if \"opencl\" in target and dtype == \"float16\":\n        pytest.xfail(\"Opencl target does not support float16\")\n\n    num_thread = 8\n\n    A = te.placeholder((arr_size,), name=\"A\", dtype=\"%sx%d\" % (dtype, lanes))\n    B = te.compute((arr_size,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name=\"B\")\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=num_thread)\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    fun = tvm.build(s, [A, B], target)\n    a = tvm.nd.empty((arr_size,), A.dtype, dev).copyfrom(np.random.uniform(size=(arr_size, lanes)))\n    c = tvm.nd.empty((arr_size,), B.dtype, dev)\n    fun(a, c)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n\n@tvm.testing.parametrize_targets(\"vulkan\")\n@pytest.mark.skip(\"Flaky, https://github.com/apache/tvm/issues/10779\")\ndef test_vulkan_stress(target, dev):\n    \"\"\"\n    Launch a randomized test with multiple kernels per stream, multiple uses of\n    kernels per stream, over multiple threads.\n    \"\"\"\n\n    n = 1024\n    num_thread = 64\n\n    def run_stress():\n        def worker():\n            A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n            B = te.placeholder((n,), name=\"B\", dtype=\"float32\")\n            functions = [\n                (\n                    lambda: te.compute((n,), lambda i: 2 * A[i] + 3 * B[i]),\n                    lambda a, b: 2 * a + 3 * b,\n                ),\n                (lambda: te.compute((n,), lambda i: A[i] + B[i]), lambda a, b: a + b),\n                (lambda: te.compute((n,), lambda i: A[i] + 2 * B[i]), lambda a, b: a + 2 * b),\n            ]\n\n            def build_f(f_ref):\n                (C_f, ref) = f_ref\n                C = C_f()\n                s = te.create_schedule(C.op)\n                xo, xi = s[C].split(C.op.axis[0], factor=num_thread)\n                s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n                s[C].bind(xi, te.thread_axis(\"threadIdx.x\"))\n                fun = tvm.build(s, [A, B, C], target)\n                return (fun, ref)\n\n            fs = [\n                build_f(random.choice(functions)) for _ in range(np.random.randint(low=1, high=10))\n            ]\n            a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np.random.uniform(size=(n,)))\n            b = tvm.nd.empty((n,), B.dtype, dev).copyfrom(np.random.uniform(size=(n,)))\n            cs = [tvm.nd.empty((n,), A.dtype, dev) for _ in fs]\n            for ((f, _), c) in zip(fs, cs):\n                f(a, b, c)\n\n            for ((_, ref), c) in zip(fs, cs):\n                tvm.testing.assert_allclose(c.numpy(), ref(a.numpy(), b.numpy()))\n\n        ts = [threading.Thread(target=worker) for _ in range(np.random.randint(1, 10))]\n        for t in ts:\n            t.start()\n        for t in ts:\n            t.join()\n\n    run_stress()\n\n\n@tvm.testing.exclude_targets(\"llvm\")\ndef test_vulkan_bool_load(target, dev):\n    arr_size = 1024\n\n    target = tvm.target.Target(target)\n    if target.kind.name == \"vulkan\":\n        supports_int8_buffer = target.attrs.get(\"supports_int8\", False) and target.attrs.get(\n            \"supports_8bit_buffer\", False\n        )\n        if not supports_int8_buffer:\n            pytest.xfail(\n                \"Vulkan target does not support int8 buffer access, used to transfer booleans\"\n            )\n\n    def do_copy(A, B, n):\n        ib = tvm.tir.ir_builder.create()\n        A = ib.buffer_ptr(A)\n        B = ib.buffer_ptr(B)\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        bx = te.thread_axis(\"blockIdx.x\")\n\n        max_threads = 32\n        ib.scope_attr(bx, \"thread_extent\", tvm.tir.indexdiv(n + max_threads - 1, max_threads))\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        tid = bx * max_threads + tx\n\n        with ib.if_scope(tid < n):\n            B[tid] = cast(A[tid], \"int32\")\n\n        return ib.get()\n\n    A = te.placeholder((arr_size,), name=\"A\", dtype=\"bool\")\n    B = te.placeholder((arr_size,), name=\"B\", dtype=\"int32\")\n\n    B = te.extern(\n        A.shape,\n        [A],\n        lambda ins, outs: do_copy(ins[0], outs[0], arr_size),\n        name=\"bool_copy_ir\",\n        dtype=\"int32\",\n    )\n    s = te.create_schedule(B.op)\n\n    with tvm.transform.PassContext(opt_level=3):\n        func = tvm.build(s, [A, B], target)\n\n    a_np = np.random.uniform(size=arr_size) > 0.5\n    b_np = np.zeros((arr_size,), dtype=\"int32\")\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    func(a, b)\n    ref = a_np.astype(np.int32)\n    tvm.testing.assert_allclose(b.numpy(), ref)\n\n\ndef check_mod(target, dev, mod, x_np, res_np):\n    res = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(x_np).numpy()\n    tvm.testing.assert_allclose(res, res_np, atol=1e-5)\n\n\ndef test_sqrt(target, dev):\n    # Three 32 bit pushconstants: any_dim, stride, stride\n    dtype = \"float32\"\n    x = relay.var(\"x\", shape=(relay.Any(),), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], relay.sqrt(x))\n    x_np = np.random.uniform(size=(10,)).astype(dtype)\n    res_np = np.sqrt(x_np)\n\n    check_mod(target, dev, mod, x_np, res_np)\n\n\ndef test_argsort(target, dev):\n    # One 64 bit and one 32 bit constants\n    dtype = \"int32\"\n    x = relay.var(\"x\", shape=(relay.Any(),), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], relay.argsort(x))\n    x_np = np.random.randint(0, high=10, size=(10,)).astype(dtype)\n    res_np = np.argsort(x_np)\n\n    check_mod(target, dev, mod, x_np, res_np)\n\n\ndef test_cumsum(target, dev):\n    # One 64 bit and one 32 bit constants\n    dtype = \"int32\"\n    x = relay.var(\"x\", shape=(relay.Any(),), dtype=dtype)\n    mod = tvm.IRModule()\n    mod[\"main\"] = relay.Function([x], relay.cumsum(x))\n    x_np = np.random.randint(0, high=10, size=(10,)).astype(dtype)\n    res_np = np.cumsum(x_np)\n\n    check_mod(target, dev, mod, x_np, res_np)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_unique(target, dev):\n    dtype = \"int32\"\n    x = relay.var(\"x\", shape=(relay.Any(),), dtype=dtype)\n    mod = tvm.IRModule()\n    [unique, _, _, num_unique] = relay.unique(x, is_sorted=True)\n    mod[\"main\"] = relay.Function([x], relay.op.strided_slice(unique, begin=[0], end=num_unique))\n    x_np = np.random.randint(0, high=10, size=(10,)).astype(dtype)\n    res_np = np.unique(x_np)\n    check_mod(target, dev, mod, x_np, res_np)\n\n\nvulkan_parameter_impl = tvm.testing.parameter(\"push_constants\", \"ubo\")\nvulkan_parameter_dtype = tvm.testing.parameter(\"int32\", \"float32\", \"int64\")\n\n# Only run on vulkan because extremely large numbers of input\n# parameters can crash cuda/llvm compiler.\n@tvm.testing.parametrize_targets(\"vulkan -from_device=0\")\ndef test_vulkan_constant_passing(target, dev, vulkan_parameter_impl, vulkan_parameter_dtype):\n    target = tvm.target.Target(target)\n    dtype = vulkan_parameter_dtype\n\n    if not target.attrs.get(\"supports_int64\", False):\n        pytest.xfail(\"Vulkan target does not support Int64 variables\")\n\n    # f_add has 3+num_int_params scalar parameters.  The other three\n    # are length_n, stride1, and stride2.\n    if vulkan_parameter_impl == \"push_constants\":\n        # 4 params, 32 bytes.  Within 128-byte spec-guaranteed size of\n        # push constants.  Uses push constants.\n        num_int_params = 1\n    else:\n        # 24 params, 192 bytes.  May be above spec-guaranteed size of 128\n        # bytes for push constants.  Uses either push constants or UBO,\n        # depending on the device.\n        max_push_constants_size = int(target.attrs.get(\"max_push_constants_size\", 128))\n        max_int_params_in_push = max_push_constants_size // 8 - 3\n        num_int_params = max_int_params_in_push + 1\n\n    n = te.var(\"n\")\n    scalars = [te.var(\"scale{}\".format(i), dtype=dtype) for i in range(num_int_params)]\n    scalar_sum = scalars[0]\n    for s in scalars[1:]:\n        scalar_sum += s\n\n    A = te.placeholder((n,), name=\"A\", dtype=dtype)\n    B = te.compute(A.shape, lambda i: scalar_sum + A[i], name=\"B\")\n\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=64)\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    f_add = tvm.build(s, scalars + [A, B], target)\n\n    n = 1024\n    scalars = np.array([1 for _ in scalars]).astype(dtype)\n    a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n    b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev)\n    f_add(*scalars, a, b)\n\n    tvm.testing.assert_allclose(a.numpy() + sum(scalars), b.numpy())\n\n\ndef test_vulkan_while_if(target, dev):\n    target = tvm.target.Target(target)\n\n    def do_compute(A, B, n):\n        ib = tvm.tir.ir_builder.create()\n        A = ib.buffer_ptr(A)\n        B = ib.buffer_ptr(B)\n\n        if \"gpu\" in target.keys:\n            ib.scope_attr(te.thread_axis(\"blockIdx.x\"), \"thread_extent\", 0)\n\n        iterations = ib.allocate(\"int32\", (1,), name=\"iterations\", scope=\"local\")\n        iterations[0] = 0\n        B[0] = 0\n\n        # WhileNode's condition is re-evaluated every loop.  The\n        # if_then_else block introduces additional labels/blocks that\n        # must be kept separate from the WhileNode's block.\n        loop_condition = iterations[0] < tvm.tir.if_then_else(A[0] > 0, 10, 20)\n        with ib.while_loop(loop_condition):\n            iterations[0] += 1\n            B[0] += iterations[0]\n\n        return ib.get()\n\n    n = 1\n    dtype = \"int32\"\n    A = te.placeholder((n,), name=\"A\", dtype=dtype)\n\n    B = te.extern(\n        A.shape,\n        [A],\n        lambda ins, outs: do_compute(ins[0], outs[0], n),\n        dtype=dtype,\n    )\n    s = te.create_schedule(B.op)\n\n    # Point of failure would be here, at tvm.build.\n    with tvm.transform.PassContext(opt_level=3):\n        func = tvm.build(s, [A, B], target)\n\n    a = tvm.nd.array(np.array([5], dtype=A.dtype), dev)\n    b = tvm.nd.array(np.zeros(n, dtype=A.dtype), dev)\n    func(a, b)\n    tvm.testing.assert_allclose(b.numpy(), [55])\n\n    a = tvm.nd.array(np.array([-5], dtype=A.dtype), dev)\n    b = tvm.nd.array(np.zeros(n, dtype=A.dtype), dev)\n    func(a, b)\n    tvm.testing.assert_allclose(b.numpy(), [210])\n\n\n@tvm.testing.exclude_targets(\"llvm\")\ndef test_vulkan_local_threadidx(target, dev):\n    # To access the thread index, the vulkan runtime accesses a global\n    # array of thread indices, storing the result in a local variable.\n    # In CUDA, these are the built-in threadIdx.x variables, which are\n    # globally accessible.  In vulkan, these local variables must be\n    # defined inside a function, but are hoisted up to the function\n    # header to mimic the global CUDA semantics.  Before this\n    # hoisting, this test could trigger spvValidate errors for\n    # potentially undeclared variables.\n\n    def do_compute(A, B, n):\n        ib = tvm.tir.ir_builder.create()\n        A = ib.buffer_ptr(A)\n        B = ib.buffer_ptr(B)\n\n        # One single declaration of te.thread_axis.\n        tx = te.thread_axis(\"threadIdx.x\")\n\n        with ib.for_range(0, 1):\n            # Used inside a for-loop scope, defines local thread_id\n            # variable.\n            ib.scope_attr(tx, \"thread_extent\", 16)\n            B[tx + 0] = A[tx + 0]\n\n        with ib.for_range(0, 1):\n            # Used in next scope.  If local variable defined at point\n            # of use instead of function header, will fail spvValidate\n            # for access of out-of-scope local variable.\n            ib.scope_attr(tx, \"thread_extent\", 16)\n            B[tx + 16] = A[tx + 16]\n\n        return ib.get()\n\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\", dtype=\"int32\")\n    B = te.placeholder((n,), name=\"B\", dtype=\"int32\")\n\n    B = te.extern(\n        A.shape,\n        [A],\n        lambda ins, outs: do_compute(ins[0], outs[0], n),\n        dtype=\"int32\",\n    )\n    s = te.create_schedule(B.op)\n\n    # Expected failure occurs at build step.\n    func = tvm.build(s, [A, B], target)\n\n    n = 32\n    a_np = np.arange(n).astype(dtype=A.dtype)\n    b_np = np.zeros((n,), dtype=\"int32\")\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    func(a, b)\n    tvm.testing.assert_allclose(b.numpy(), a_np)\n\n\nclass TestVectorizedIndices:\n    load_type, store_type = tvm.testing.parameters(\n        # Load N values, write to N locations.\n        # Vectorized copy.\n        (\"ramp\", \"ramp\"),\n        # Load 1 value, write to N locations.\n        # Scalar load, vectorized store.\n        #\n        # Most TVM operations (e.g. schedule[tensor].vectorize(axis)) have\n        # the broadcast outside of the index, but it is semantically okay\n        # for the broadcast to be inside the index, and it shows up with\n        # some optimizations.\n        (\"broadcast\", \"ramp\"),\n        # Load 1 values, write to 1 location.\n        # Broadcasting on both sides should be equivalent to a scalar copy.\n        (\"broadcast\", \"broadcast\"),\n        # Loads N values, write to 1 location.\n        # Disabled as it would have unclear semantics.\n        # (\"ramp\",\"broadcoast\"),\n    )\n    indirect_indices = tvm.testing.parameter(True, False, ids=[\"reorder\", \"no_reorder\"])\n\n    @tvm.testing.fixture\n    def ref_data(self, load_type, store_type, indirect_indices):\n        n = 4\n\n        index_map = {\n            \"ramp\": np.arange(n),\n            \"broadcast\": np.zeros(n, dtype=\"int32\"),\n        }\n\n        a_np = np.random.randint(np.iinfo(\"int32\").max, size=n).astype(\"int32\")\n        b_np = np.zeros(shape=n, dtype=a_np.dtype)\n        reorder_np = np.arange(n, dtype=\"int32\")[::-1]\n\n        load_index = index_map[load_type]\n        store_index = index_map[store_type]\n\n        if indirect_indices:\n            load_index = reorder_np[load_index]\n\n        b_np[store_index] = a_np[load_index]\n\n        return a_np, reorder_np, b_np\n\n    @tvm.testing.fixture\n    def mod(self, target, load_type, store_type, indirect_indices):\n        target = tvm.target.Target(target)\n\n        n = 4\n        dtype = \"int32\"\n        A = te.placeholder((n,), dtype=dtype, name=\"A\")\n        R = te.placeholder((n,), dtype=dtype, name=\"R\")\n\n        def do_compute(ins, outs):\n            ib = tvm.tir.ir_builder.create()\n            A, R = map(ib.buffer_ptr, ins)\n            B = ib.buffer_ptr(outs[0])\n\n            if \"gpu\" in target.keys:\n                ib.scope_attr(te.thread_axis(\"blockIdx.x\"), \"thread_extent\", 0)\n\n            index_map = {\n                \"ramp\": tvm.tir.Ramp(0, 1, 4),\n                \"broadcast\": tvm.tir.Broadcast(0, 4),\n            }\n\n            load_index = index_map[load_type]\n            store_index = index_map[store_type]\n\n            if indirect_indices:\n                load_index = R[load_index]\n\n            B[store_index] = A[load_index]\n\n            return ib.get()\n\n        B = te.extern(A.shape, [A, R], do_compute, dtype=\"int32\")\n        s = te.create_schedule(B.op)\n\n        return tvm.lower(s, [A, R, B])\n\n    def test_ramp_broadcast_index(self, target, dev, mod, ref_data):\n        f = tvm.build(mod, target=target)\n\n        a_np, reorder_np, b_np = ref_data\n        a = tvm.nd.array(a_np, dev)\n        r = tvm.nd.array(reorder_np, dev)\n        b = tvm.nd.array(np.zeros(shape=b_np.shape, dtype=\"int32\"), dev)\n        f(a, r, b)\n        tvm.testing.assert_allclose(b.numpy(), b_np)\n\n\n@tvm.testing.parametrize_targets(\"vulkan -max_shared_memory_per_block=16384\")\ndef test_shared_mem_alloc(target, dev):\n    alloc_nbytes = 16384 * 2\n\n    def do_compute(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        out = ib.buffer_ptr(outs[0])\n\n        ib.scope_attr(te.thread_axis(\"blockIdx.x\"), \"thread_extent\", 0)\n\n        array = ib.allocate(\"int32\", (alloc_nbytes,), name=\"array\", scope=\"shared\")\n        array[0] = 0\n        out[0] = array[0]\n\n        return ib.get()\n\n    Out = te.extern(\n        shape=(1,),\n        inputs=[],\n        fcompute=do_compute,\n        dtype=\"int32\",\n    )\n    s = te.create_schedule(Out.op)\n\n    # Codegen should raise error when allocating more memory than the\n    # target supports.\n    with pytest.raises(tvm.TVMError):\n        tvm.build(s, [Out], target)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_codegen_x86.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport platform\nimport pytest\nimport re\nimport textwrap\n\nimport tvm\nfrom tvm import te\n\nllvm_version = tvm.target.codegen.llvm_version_major()\nmachine = platform.machine()\n\nif machine not in [\"i386\", \"x86_64\", \"AMD64\", \"amd64\"]:\n    pytest.skip(f\"Requires x86_64/i386, but machine is {machine}\", allow_module_level=True)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.skipif(llvm_version < 6, reason=f\"Requires LLVM 6+, got {llvm_version}\")\ndef test_fp16_to_fp32():\n    def fp16_to_fp32(target, width, match=None, not_match=None):\n        elements = 64\n        n = tvm.runtime.convert(elements)\n        A = te.placeholder((n, width), dtype=\"float16\", name=\"A\")\n        B = te.compute(A.shape, lambda *i: A(*i).astype(\"float32\"), name=\"B\")\n        s = te.create_schedule(B.op)\n        s[B].vectorize(s[B].op.axis[1])\n        f = tvm.build(s, [A, B], target)\n\n        assembly = f.get_source(\"asm\").splitlines()\n        if match:\n            matches = [l for l in assembly if re.search(match, l)]\n            assert matches\n        if not_match:\n            not_matches = [l for l in assembly if re.search(not_match, l)]\n            assert not not_matches\n\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512\", 15, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512\", 16, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512\", 17, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512\", 49, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512 -mattr=-avx512f\", 49, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=skylake-avx512 -mattr=-f16c,-avx512f\", 49, not_match=\"vcvtph2ps\")\n    fp16_to_fp32(\"llvm -mcpu=core-avx2\", 8, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm -mcpu=core-avx2\", 9, match=\"vcvtph2ps.*mm\")\n    fp16_to_fp32(\"llvm\", 9, not_match=\"vcvtph2ps\")\n\n\nis_32bit = platform.architecture()[0] == \"32bit\"\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.skipif(is_32bit, reason=f\"Fails in CI due to architecture mismatch in JIT\")\n@pytest.mark.parametrize(\"feature_string\", [\"-sse2\", \"+sse2\"])\ndef test_fp16_fp32_conversions(feature_string):\n    relay_model = textwrap.dedent(\n        \"\"\"\n        #[version = \"0.0.5\"]\n        def @main(%inp : Tensor[(3), float32], %cst : Tensor[(3), float32]) {\n            %1 = cast(%inp, dtype=\"float16\");\n            %2 = cast(%cst, dtype=\"float16\");\n            %3 = add(%1, %2);\n            %4 = cast(%3, dtype=\"float32\");\n            %4\n        }\n        \"\"\"\n    )\n\n    ir_mod = tvm.parser.fromtext(relay_model)\n\n    arch = \"i386\" if machine == \"i386\" else \"x86_64\"\n    aot_factory = tvm.relay.build(\n        ir_mod,\n        params={\"cst\": np.array([1.0, 2.0, 3.0], dtype=\"float32\")},\n        target=f\"llvm --mtriple={arch} --mattr={feature_string}\",\n        executor=tvm.relay.backend.Executor(\n            \"aot\", {\"interface-api\": \"packed\", \"unpacked-api\": False}\n        ),\n    )\n\n    mod_name = aot_factory[\"list_module_names\"]()[0]\n    executor = aot_factory[mod_name]\n    mod = executor(tvm.cpu(0))\n\n    inp = tvm.nd.array(np.array([1.1, 2.1, 3.1], dtype=\"float32\"), device=tvm.cpu(0))\n\n    mod.get_function(\"set_input\")(0, inp)\n    mod.get_function(\"run\")()\n    out = mod.get_function(\"get_output\")(0)\n\n    expected = np.array([2.1, 4.1, 6.1], dtype=\"float32\")\n    np.testing.assert_allclose(out.asnumpy(), expected, rtol=1e-3)\n\n\nif __name__ == \"__main__\":\n    test_fp16_to_fp32()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_parser_mprofile.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nTests to verify Python interactions with Target Parsing\n\"\"\"\n\nimport pytest\n\nfrom tvm.target import Target\n\n\n@pytest.mark.parametrize([\"cpu_target\"], [[\"c\"], [\"llvm\"]])\ndef test_target_parser_mprofile(cpu_target):\n    parsed_target = Target(f\"{cpu_target} -mcpu=cortex-m55\")\n    assert len(parsed_target.keys) == 2\n    assert parsed_target.keys[0] == \"arm_cpu\"\n    assert parsed_target.keys[1] == \"cpu\"\n    assert parsed_target.features\n    assert parsed_target.features.has_dsp\n    assert parsed_target.features.has_mve\n\n\n@pytest.mark.parametrize([\"cpu_target\"], [[\"c\"], [\"llvm\"]])\ndef test_target_parser_mprofile_no_mve(cpu_target):\n    parsed_target = Target(f\"{cpu_target} -mcpu=cortex-m7\")\n    assert len(parsed_target.keys) == 2\n    assert parsed_target.keys[0] == \"arm_cpu\"\n    assert parsed_target.keys[1] == \"cpu\"\n    assert parsed_target.features\n    assert parsed_target.features.has_dsp\n    assert not parsed_target.features.has_mve\n\n\n@pytest.mark.parametrize([\"cpu_target\"], [[\"c\"], [\"llvm\"]])\ndef test_target_parser_mprofile_no_dsp(cpu_target):\n    parsed_target = Target(f\"{cpu_target} -mcpu=cortex-m3\")\n    assert len(parsed_target.keys) == 2\n    assert parsed_target.keys[0] == \"arm_cpu\"\n    assert parsed_target.keys[1] == \"cpu\"\n    assert parsed_target.features\n    assert not parsed_target.features.has_dsp\n    assert not parsed_target.features.has_mve\n\n\n@pytest.mark.parametrize([\"cpu_target\"], [[\"llvm\"]])\ndef test_target_parser_mprofile_mattr(cpu_target):\n    parsed_target = Target(f\"{cpu_target} -mcpu=cortex-m55 -mattr=+nomve,+woof\")\n    assert len(parsed_target.keys) == 2\n    assert parsed_target.keys[0] == \"arm_cpu\"\n    assert parsed_target.keys[1] == \"cpu\"\n    assert parsed_target.features\n    assert parsed_target.features.has_dsp\n    assert not parsed_target.features.has_mve\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_target.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport json\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm.target import Target, arm_cpu, bifrost, cuda, intel_graphics, mali, rocm, vta\n\n\n@tvm.target.generic_func\ndef mygeneric(data):\n    # default generic function\n    return data + 1\n\n\n@mygeneric.register([\"cuda\", \"gpu\"])\ndef cuda_func(data):\n    return data + 2\n\n\n@mygeneric.register(\"rocm\")\ndef rocm_func(data):\n    return data + 3\n\n\n@mygeneric.register(\"cpu\")\ndef rocm_func(data):\n    return data + 10\n\n\ndef test_all_targets_device_type_verify():\n    \"\"\"Consistency verification for all targets' device type\"\"\"\n    all_targets = [tvm.target.Target(t) for t in tvm.target.Target.list_kinds()]\n\n    for tgt in all_targets:\n        # skip targets with hooks or otherwise intended to be used with external codegen\n        relay_to_tir = tgt.get_kind_attr(\"RelayToTIR\")\n        tir_to_runtime = tgt.get_kind_attr(\"TIRToRuntime\")\n        is_external_codegen = tgt.get_kind_attr(\"is_external_codegen\")\n        if relay_to_tir is not None or tir_to_runtime is not None or is_external_codegen:\n            continue\n\n        if tgt.kind.name not in tvm._ffi.runtime_ctypes.Device.STR2MASK:\n            raise KeyError(\"Cannot find target kind: %s in Device.STR2MASK\" % tgt.kind.name)\n\n        assert (\n            tgt.get_target_device_type() == tvm._ffi.runtime_ctypes.Device.STR2MASK[tgt.kind.name]\n        )\n\n\ndef test_target_dispatch():\n    with tvm.target.cuda():\n        assert mygeneric(1) == 3\n        assert mygeneric.get_packed_func()(1) == 3\n\n    with tvm.target.rocm():\n        assert mygeneric(1) == 4\n        assert mygeneric.get_packed_func()(1) == 4\n\n    with tvm.target.Target(\"cuda\"):\n        assert mygeneric(1) == 3\n        assert mygeneric.get_packed_func()(1) == 3\n\n    with tvm.target.arm_cpu():\n        assert mygeneric(1) == 11\n        assert mygeneric.get_packed_func()(1) == 11\n\n    with tvm.target.Target(\"metal\"):\n        assert mygeneric(1) == 3\n        assert mygeneric.get_packed_func()(1) == 3\n\n    assert tvm.target.Target.current() is None\n\n\n@tvm.target.override_native_generic_func(\"test_target_temp_strategy\")\ndef target_generic(data):\n    # default generic function\n    return data + 1\n\n\n@target_generic.register([\"cuda\", \"gpu\"])\ndef target_cuda_func(data):\n    return data + 2\n\n\ndef temp_target_cuda_func(data):\n    return data + 3\n\n\ndef test_target_temp_strategy():\n    class TempStrategy(object):\n        def __init__(self, name, target, fstrategy):\n            generic_fstrategy = tvm.target.get_native_generic_func(name)\n            self.target = target\n            self.name = name\n            self.origin_func = {}\n            with tvm.target.Target(target) as target_obj:\n                for tgt_key in target_obj.keys:\n                    self.origin_func[tgt_key] = generic_fstrategy.get_packed_func()\n                    generic_fstrategy.register(fstrategy, tgt_key, allow_override=True)\n\n        def __enter__(self):\n            return self\n\n        def __exit__(self, typ, value, traceback):\n            generic_fstrategy = tvm.target.get_native_generic_func(self.name)\n            with tvm.target.Target(self.target) as target_obj:\n                for tgt_key in target_obj.keys:\n                    generic_fstrategy.register(\n                        self.origin_func[tgt_key], tgt_key, allow_override=True\n                    )\n\n    with tvm.target.Target(\"cuda\"):\n        assert target_generic(1) == 3\n\n    # The strategy func change to temp_target_cuda_func.\n    with TempStrategy(\"test_target_temp_strategy\", \"cuda\", temp_target_cuda_func):\n        with tvm.target.Target(\"cuda\"):\n            assert target_generic(1) == 4\n\n    with tvm.target.Target(\"cuda\"):\n        assert target_generic(1) == 3\n\n\ndef test_target_string_parse():\n    target = tvm.target.Target(\"cuda -model=unknown -libs=cublas,cudnn\")\n\n    assert target.kind.name == \"cuda\"\n    assert target.model == \"unknown\"\n    assert set(target.keys) == set([\"cuda\", \"gpu\"])\n    assert set(target.libs) == set([\"cublas\", \"cudnn\"])\n    assert str(target) == str(tvm.target.cuda(options=\"-libs=cublas,cudnn\"))\n\n    assert tvm.target.intel_graphics().device_name == \"intel_graphics\"\n    assert tvm.target.mali().device_name == \"mali\"\n    assert tvm.target.arm_cpu().device_name == \"arm_cpu\"\n\n\ndef test_target_string_with_spaces():\n    target = tvm.target.Target(\n        \"vulkan -device_name='Name of GPU with spaces' -device_type=discrete\"\n    )\n    assert target.attrs[\"device_name\"] == \"Name of GPU with spaces\"\n    assert target.attrs[\"device_type\"] == \"discrete\"\n\n    target = tvm.target.Target(str(target))\n\n    assert target.attrs[\"device_name\"] == \"Name of GPU with spaces\"\n    assert target.attrs[\"device_type\"] == \"discrete\"\n\n\ndef test_target_llvm_options():\n    target = tvm.target.Target(\"llvm -cl-opt='-unroll-threshold:uint=100,-unroll-count:uint=3'\")\n    assert sorted(target.attrs[\"cl-opt\"]) == sorted(\n        [\"-unroll-threshold:uint=100\", \"-unroll-count:uint=3\"]\n    )\n\n\ndef test_target_create():\n    targets = [cuda(), rocm(), mali(), intel_graphics(), arm_cpu(\"rk3399\"), vta(), bifrost()]\n    for tgt in targets:\n        assert tgt is not None\n\n\ndef test_target_config():\n    \"\"\"\n    Test that constructing a target from a dictionary works.\n    \"\"\"\n    target_config = {\n        \"kind\": \"llvm\",\n        \"keys\": [\"arm_cpu\", \"cpu\"],\n        \"device\": \"arm_cpu\",\n        \"libs\": [\"cblas\"],\n        \"mfloat-abi\": \"hard\",\n        \"mattr\": [\"+neon\", \"-avx512f\"],\n    }\n    # Convert config dictionary to json string.\n    target_config_str = json.dumps(target_config)\n    # Test both dictionary input and json string.\n    for config in [target_config, target_config_str]:\n        target = tvm.target.Target(config)\n        assert target.kind.name == \"llvm\"\n        assert all([key in target.keys for key in [\"arm_cpu\", \"cpu\"]])\n        assert target.device_name == \"arm_cpu\"\n        assert target.libs == [\"cblas\"]\n        assert target.attrs[\"mfloat-abi\"] == \"hard\"\n        assert all([attr in target.attrs[\"mattr\"] for attr in [\"+neon\", \"-avx512f\"]])\n\n\ndef test_config_map():\n    \"\"\"\n    Confirm that constructing a target with invalid\n    attributes fails as expected.\n    \"\"\"\n    target_config = {\"kind\": \"llvm\", \"libs\": {\"a\": \"b\", \"c\": \"d\"}}\n    with pytest.raises(ValueError):\n        tvm.target.Target(target_config)\n\n\ndef test_composite_target():\n    tgt = tvm.target.Target(\"composite --host=llvm --devices=cuda,opencl\")\n    assert tgt.kind.name == \"composite\"\n    assert tgt.host.kind.name == \"llvm\"\n    assert len(tgt.attrs[\"devices\"]) == 2\n    cuda_device, opencl_device = tgt.attrs[\"devices\"]\n    assert cuda_device.kind.name == \"cuda\"\n    assert opencl_device.kind.name == \"opencl\"\n\n\ndef test_target_tag_0():\n    tgt = tvm.target.Target(\"nvidia/geforce-rtx-2080-ti\")\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.attrs[\"arch\"] == \"sm_75\"\n    assert tgt.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.attrs[\"thread_warp_size\"] == 32\n    assert tgt.attrs[\"registers_per_block\"] == 65536\n\n\ndef test_target_tag_1():\n    tgt = tvm.target.Target(\"nvidia/jetson-nano\")\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.attrs[\"thread_warp_size\"] == 32\n    assert tgt.attrs[\"registers_per_block\"] == 32768\n\n\ndef test_list_kinds():\n    targets = tvm.target.Target.list_kinds()\n    assert len(targets) != 0\n    assert \"llvm\" in targets\n    assert all(isinstance(target_name, str) for target_name in targets)\n\n\ndef test_target_host_tags():\n    tgt = tvm.target.Target(\"nvidia/jetson-nano\", \"nvidia/geforce-rtx-2080-ti\")\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.attrs[\"thread_warp_size\"] == 32\n    assert tgt.attrs[\"registers_per_block\"] == 32768\n    assert tgt.host.kind.name == \"cuda\"\n    assert tgt.host.attrs[\"arch\"] == \"sm_75\"\n    assert tgt.host.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.host.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.host.attrs[\"thread_warp_size\"] == 32\n    assert tgt.host.attrs[\"registers_per_block\"] == 65536\n\n\ndef test_target_host_tag_dict():\n    tgt = tvm.target.Target(\"nvidia/jetson-nano\", {\"kind\": \"llvm\"})\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.attrs[\"thread_warp_size\"] == 32\n    assert tgt.attrs[\"registers_per_block\"] == 32768\n    assert tgt.host.kind.name == \"llvm\"\n\n\ndef test_target_host_single_dict():\n    tgt = tvm.target.Target({\"kind\": \"llvm\", \"host\": \"nvidia/jetson-nano\"})\n    assert tgt.kind.name == \"llvm\"\n    assert tgt.host.kind.name == \"cuda\"\n    assert tgt.host.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.host.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.host.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.host.attrs[\"thread_warp_size\"] == 32\n    assert tgt.host.attrs[\"registers_per_block\"] == 32768\n\n\ndef test_target_host_single_string():\n    tgt = tvm.target.Target(\"cuda --host llvm\")\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n\n\ndef test_target_host_single_string_with_tag():\n    tgt = tvm.target.Target(\"cuda --host nvidia/jetson-nano\")\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"cuda\"\n    assert tgt.host.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.host.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.host.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.host.attrs[\"thread_warp_size\"] == 32\n    assert tgt.host.attrs[\"registers_per_block\"] == 32768\n\n\ndef test_target_host_merge_0():\n    tgt = tvm.target.Target(tvm.target.Target(\"cuda --host nvidia/jetson-nano\"), None)\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"cuda\"\n    assert tgt.host.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.host.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.host.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.host.attrs[\"thread_warp_size\"] == 32\n    assert tgt.host.attrs[\"registers_per_block\"] == 32768\n\n\ndef test_target_host_merge_1():\n    tgt = tvm.target.Target(\"cuda --host llvm\")\n    tgt = tvm.target.Target(tgt, tgt.host)\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n\n\ndef test_target_host_merge_2():\n    \"\"\"Test picking the same host is ok.\"\"\"\n    tgt = tvm.target.Target(tvm.target.Target(\"cuda --host llvm\"), tvm.target.Target(\"llvm\"))\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n\n\ndef test_target_tvm_object():\n    \"\"\"Test creating Target by using TVM Objects\"\"\"\n    String = tvm.runtime.container.String\n    tgt = tvm.target.Target(target=String(\"cuda --host llvm\"))\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n    tgt = tvm.target.Target(target=String(\"cuda\"), host=String(\"llvm\"))\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n\n\n@pytest.mark.skip(reason=\"Causing infinite loop because of pytest and handle issue\")\ndef test_target_host_merge_3():\n    with pytest.raises(ValueError, match=r\"target host has to be a string or dictionary.\"):\n        tvm.target.Target(tvm.target.Target(\"cuda --host llvm\"), 12.34)\n\n\ndef test_target_with_host():\n    tgt = tvm.target.Target(\"cuda\")\n    llvm = tvm.target.Target(\"llvm\")\n    tgt = tgt.with_host(llvm)\n    assert tgt.kind.name == \"cuda\"\n    assert tgt.host.kind.name == \"llvm\"\n    cuda_host = tvm.target.Target(\"nvidia/jetson-nano\")\n    tgt = tgt.with_host(cuda_host)\n    assert tgt.host.kind.name == \"cuda\"\n    assert tgt.host.attrs[\"arch\"] == \"sm_53\"\n    assert tgt.host.attrs[\"max_shared_memory_per_block\"] == 49152\n    assert tgt.host.attrs[\"max_threads_per_block\"] == 1024\n    assert tgt.host.attrs[\"thread_warp_size\"] == 32\n    assert tgt.host.attrs[\"registers_per_block\"] == 32768\n\n\ndef test_canon_target_and_host_0():\n    target = None\n    host = None\n    target, host = Target.canon_target_and_host(target, host)\n    assert target is None\n    assert host is None\n\n\ndef test_canon_target_and_host_1():\n    target = None\n    host = \"llvm\"\n    with pytest.raises(AssertionError, match=r\"Target host is not empty when target is empty.\"):\n        target, host = Target.canon_target_and_host(target, host)\n\n\ndef test_canon_target_and_host_2():\n    target = Target(\"cuda\")\n    host = Target(\"llvm\")\n    target, host = Target.canon_target_and_host(target, host)\n    assert target.kind.name == \"cuda\"\n    assert target.host.kind.name == \"llvm\"\n\n\ndef test_canon_target_and_host_3():\n    target = Target(target=\"cuda\", host=\"llvm\")\n    host = None\n    target, host = Target.canon_target_and_host(target, host)\n    assert target.kind.name == \"cuda\"\n    assert target.host.kind.name == \"llvm\"\n    assert host.kind.name == \"llvm\"\n    assert target.host == host\n\n\ndef test_canon_multi_target_and_host_0():\n    with pytest.raises(AssertionError):\n        Target.canon_multi_target_and_host(None)\n\n\ndef test_canon_multi_target_and_host_1():\n    raw_targets = Target.canon_multi_target_and_host({\"kind\": \"llvm\"})\n    assert len(raw_targets) == 1\n    assert raw_targets[0].kind.name == \"llvm\"\n\n\ndef test_canon_multi_target_and_host_2():\n    raw_targets = Target.canon_multi_target_and_host({1: \"llvm\", 2: \"cuda\"})\n    assert len(raw_targets) == 2\n    assert raw_targets[0].kind.name == \"llvm\"\n    assert raw_targets[1].kind.name == \"cuda\"\n\n\ndef test_canon_multi_target_and_host_3():\n    raw_targets = Target.canon_multi_target_and_host([\"llvm\", \"cuda\"])\n    assert len(raw_targets) == 2\n    assert raw_targets[0].kind.name == \"llvm\"\n    assert raw_targets[1].kind.name == \"cuda\"\n\n\ndef test_canon_multi_target_and_host_4():\n    raw_targets = Target.canon_multi_target_and_host(\"llvm\")\n    assert len(raw_targets) == 1\n    assert raw_targets[0].kind.name == \"llvm\"\n\n\ndef test_canon_multi_target_and_host_5():\n    raw_targets = Target.canon_multi_target_and_host(\"cuda\", \"llvm\")\n    assert len(raw_targets) == 1\n    assert raw_targets[0].kind.name == \"cuda\"\n    assert raw_targets[0].host.kind.name == \"llvm\"\n\n\ndef test_canon_multi_target_and_host_6():\n    \"\"\"Test `canon_target_and_host` by using TVM Objects\"\"\"\n    cuda_device_type = tvm.device(\"cuda\").device_type\n    target = {cuda_device_type: Target(target=\"cuda\", host=\"llvm\")}\n    host = None\n    raw_targets_1 = Target.canon_multi_target_and_host(target, host)\n    assert len(raw_targets_1) == 1\n    assert raw_targets_1[0].kind.name == \"cuda\"\n    assert raw_targets_1[0].host.kind.name == \"llvm\"\n\n    target = {cuda_device_type: Target(tvm.runtime.container.String(\"cuda\"))}\n    host = Target(tvm.runtime.container.String(\"llvm\"))\n    target = tvm.runtime.convert(target)\n    assert isinstance(target, tvm.ir.container.Map)\n    raw_targets_2 = Target.canon_multi_target_and_host(target, host)\n    assert len(raw_targets_2) == 1\n    assert raw_targets_2[0].kind.name == \"cuda\"\n    assert raw_targets_2[0].host.kind.name == \"llvm\"\n\n\ndef test_canon_target_map_and_host():\n    target_map = {\"cuda\": \"cuda_module\", \"llvm\": \"cpu_module\"}\n    target_map, host = Target.canon_target_map_and_host(target_map, \"llvm\")\n    assert host.kind.name == \"llvm\"\n    for t, v in target_map.items():\n        assert t.host.kind.name == \"llvm\"\n        if t.kind.name == \"cuda\":\n            assert v == \"cuda_module\"\n        elif t.kind.name == \"llvm\":\n            assert v == \"cpu_module\"\n        else:\n            assert False\n\n\ndef test_target_attr_bool_value():\n    target0 = Target(\"vulkan --supports_float16=True\")\n    assert target0.attrs[\"supports_float16\"] == 1\n    target1 = Target(\"vulkan --supports_float16=true\")\n    assert target1.attrs[\"supports_float16\"] == 1\n    target2 = Target(\"vulkan --supports_float16=False\")\n    assert target2.attrs[\"supports_float16\"] == 0\n    target3 = Target(\"vulkan --supports_float16=false\")\n    assert target3.attrs[\"supports_float16\"] == 0\n\n\ndef test_target_features():\n    target_no_features = Target(\"cuda\")\n    assert target_no_features.features\n    assert not target_no_features.features.is_test\n\n    target_with_features = Target(\"test\")\n    assert target_with_features.features.is_test\n    assert not target_with_features.features.is_missing\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_target_texture_codegen_opencl.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# 'License'); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import autotvm\nfrom tvm import te\nfrom tvm.topi import testing\nfrom tvm.topi.utils import get_const_tuple, simplify\nfrom tvm.topi import nn\n\n\ndef compute_plus_one_rank3(shape):\n    X = te.placeholder(shape, name=\"X\", dtype=\"float32\")\n    Y = te.compute(shape, lambda i, j, k: X[i, j, k] + 1, name=\"Compute_Y\")\n    return X, Y\n\n\ndef schedule_plus_one_rank3(X, Y):\n    s = te.create_schedule(Y.op)\n    # Xt = s.cache_read(X, \"texture\", [Y])\n    # Xt = s.cache_read(X, \"global\", [Y])\n    Xt = s.cache_read(X, \"global.texture\", [Y])\n\n    # copy to texture stage\n    x, y, c = s[Xt].op.axis\n    s[Xt].bind(x, te.thread_axis(\"blockIdx.x\"))\n    s[Xt].bind(y, te.thread_axis(\"threadIdx.x\"))\n    s[Xt].vectorize(c)\n\n    # the compute stage\n    x, y, c = s[Y].op.axis\n    xo, yo, xi, yi = s[Y].tile(x, y, 4, 4)\n    s[Y].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[Y].bind(yo, te.thread_axis(\"threadIdx.x\"))\n    s[Y].vectorize(c)\n    return s\n\n\ndef compute_plus_one_rank5(shape):\n    X = te.placeholder(shape, name=\"X\", dtype=\"float32\")\n    Y = te.compute(shape, lambda i, j, k, l, m: X[i, j, k, l, m] + 1, name=\"Compute_Y\")\n    return X, Y\n\n\ndef schedule_plus_one_rank5(X, Y):\n    s = te.create_schedule(Y.op)\n    Xt = s.cache_read(X, \"global.texture\", [Y])\n\n    # copy to texture stage\n    a, b, c, d, e = s[Xt].op.axis\n    abc = s[Xt].fuse(a, b, c)\n    s[Xt].bind(abc, te.thread_axis(\"blockIdx.x\"))\n    s[Xt].bind(d, te.thread_axis(\"threadIdx.x\"))\n    s[Xt].vectorize(e)\n\n    # the compute stage\n    a, b, c, d, e = s[Y].op.axis\n    abc = s[Y].fuse(a, b, c)\n    xo, yo, xi, yi = s[Y].tile(abc, d, 4, 4)\n    s[Y].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[Y].bind(yo, te.thread_axis(\"threadIdx.x\"))\n    s[Y].vectorize(e)\n    return s\n\n\ndef compute_matmul(shape):\n    A = te.placeholder(shape, name=\"A\", dtype=\"float32\")\n    B = te.placeholder(shape, name=\"B\", dtype=\"float32\")\n    k = te.reduce_axis((0, shape[1]), name=\"k\")\n    C = te.compute(\n        (shape[0] * shape[2], shape[0] * shape[2]),\n        lambda i, j: te.sum(\n            A[i // shape[2], k, i % shape[2]].astype(\"float32\")\n            * B[j // shape[2], k, j % shape[2]].astype(\"float32\"),\n            axis=[k],\n        ),\n        name=\"Compute_MatMul\",\n    )\n    return A, B, C\n\n\ndef schedule_matmul(A, B, C, local=False):\n    s = te.create_schedule(C.op)\n    At = s.cache_read(A, \"global.texture\", [C])\n    Bt = s.cache_read(B, \"global.texture\", [C])\n    if local:\n        Al = s.cache_read(At, \"local\", [C])\n        Bl = s.cache_read(Bt, \"local\", [C])\n    Cl = s.cache_write(C, \"local\")\n\n    bx = te.thread_axis(\"blockIdx.x\")\n    tx = te.thread_axis(\"threadIdx.x\")\n\n    def copy_to_texture(stage):\n        _io, _k, _ii = s[stage].op.axis\n        s[stage].vectorize(_ii)\n        s[stage].bind(_io, bx)\n        s[stage].bind(_k, tx)\n\n    copy_to_texture(At)\n    copy_to_texture(Bt)\n\n    # copy to global stage\n    _i, _j = s[C].op.axis\n    xo, yo, xi, yi = s[C].tile(_i, _j, 4, 4)\n    s[C].unroll(xi)\n    s[C].vectorize(yi)\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(yo, te.thread_axis(\"threadIdx.x\"))\n\n    # the compute stage\n    s[Cl].compute_at(s[C], yo)\n    (_k,) = Cl.op.reduce_axis\n    _x, _y = s[Cl].op.axis\n    s[Cl].reorder(_k, _x, _y)\n    s[Cl].unroll(_x)\n    s[Cl].vectorize(_y)\n\n    if local:\n        s[Al].compute_at(s[Cl], _k)\n        s[Al].vectorize(s[Al].op.axis[-1])\n        s[Bl].compute_at(s[Cl], _k)\n        s[Bl].vectorize(s[Bl].op.axis[-1])\n\n    return s\n\n\ndef compute_matmul_inner(shape):\n    A = te.placeholder(shape, name=\"A\", dtype=\"float32\")\n    B = te.placeholder(shape, name=\"B\", dtype=\"float32\")\n    k = te.reduce_axis((0, shape[1] * shape[2]), name=\"k\")\n    # (M, K) x (N, K)\n    # (32, 256) x (32, 256)\n    # (32, 64, 4) x (32, 64, 4)\n    C = te.compute(\n        (shape[0], shape[0]),\n        lambda i, j: te.sum(\n            A[i, k // shape[2], k % shape[2]].astype(\"float32\")\n            * B[j, k // shape[2], k % shape[2]].astype(\"float32\"),\n            axis=[k],\n        ),\n        name=\"Compute_MatMul\",\n    )\n    return A, B, C\n\n\ndef schedule_matmul_inner(A, B, C, local=False):\n    s = te.create_schedule(C.op)\n    At = s.cache_read(A, \"global.texture\", [C])\n    Bt = s.cache_read(B, \"global.texture\", [C])\n    if local:\n        Al = s.cache_read(At, \"local\", [C])\n        Bl = s.cache_read(Bt, \"local\", [C])\n    Cl = s.cache_write(C, \"local\")\n\n    bx = te.thread_axis(\"blockIdx.x\")\n    tx = te.thread_axis(\"threadIdx.x\")\n\n    def copy_to_texture(stage):\n        _i, _ko, _ki = s[stage].op.axis\n        s[stage].vectorize(_ki)\n        s[stage].bind(_i, bx)\n        s[stage].bind(_ko, tx)\n\n    copy_to_texture(At)\n    copy_to_texture(Bt)\n\n    # copy to global stage\n    _i, _j = s[C].op.axis\n    xo, yo, xi, yi = s[C].tile(_i, _j, 4, 4)\n    s[C].unroll(xi)\n    s[C].vectorize(yi)\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(yo, te.thread_axis(\"threadIdx.x\"))\n\n    # the compute stage\n    s[Cl].compute_at(s[C], yo)\n    (_k,) = Cl.op.reduce_axis\n    _x, _y = s[Cl].op.axis\n    s[Cl].reorder(_x, _y, _k)\n    s[Cl].unroll(_x)\n    # TODO(csullivan): consider whether the below error is worth resolving\n    # s[Cl].vectorize(_y) # error\n\n    if local:\n        s[Al].compute_at(s[Cl], _x)\n        s[Al].vectorize(s[Al].op.axis[-1])\n        s[Bl].compute_at(s[Cl], _x)\n        s[Bl].vectorize(s[Bl].op.axis[-1])\n\n    return s\n\n\ndef compute_matmul_vector_accumulator(shapeA, shapeB):\n    # A x B\n    # (K/4, M, K%4) x (K, N/4, N%4) = (M, N)\n    # (32, 64, 4) x (128, 16, 4) = (64, 64)\n    A = te.placeholder(shapeA, name=\"A\", dtype=\"float32\")\n    B = te.placeholder(shapeB, name=\"B\", dtype=\"float32\")\n    k = te.reduce_axis((0, shapeB[0]), name=\"k\")\n    C = te.compute(\n        (shapeA[1], shapeB[1] * shapeB[2]),\n        lambda i, j: te.sum(\n            A[k // shapeA[-1], i, k % shapeA[-1]].astype(\"float32\")\n            * B[k, j // shapeB[-1], j % shapeB[-1]].astype(\"float32\"),\n            axis=[k],\n        ),\n        name=\"Compute_MatMul\",\n    )\n    return A, B, C\n\n\ndef schedule_matmul_vector_accumulator(A, B, C, local=False):\n    s = te.create_schedule(C.op)\n    At = s.cache_read(A, \"global.texture\", [C])\n    Bt = s.cache_read(B, \"global.texture\", [C])\n    if local:\n        Al = s.cache_read(At, \"local\", [C])\n        Bl = s.cache_read(Bt, \"local\", [C])\n    Cl = s.cache_write(C, \"local\")\n\n    def copy_to_texture(stage):\n        _y, _x, _v = s[stage].op.axis\n        # TODO(csullivan): removing this vectorize results in numerical errors, autovectorize\n        s[stage].vectorize(_v)\n        s[stage].bind(_y, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(_x, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(At)\n    copy_to_texture(Bt)\n\n    # copy to global stage\n    _i, _j = s[C].op.axis\n    xo, yo, xi, yi = s[C].tile(_i, _j, 4, 4)\n    s[C].unroll(xi)\n    s[C].vectorize(yi)\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(yo, te.thread_axis(\"threadIdx.x\"))\n\n    # the compute stage\n    s[Cl].compute_at(s[C], yo)\n    (_k,) = Cl.op.reduce_axis\n    _a, _b = s[Cl].op.axis\n    _ko, _ki = s[Cl].split(_k, factor=4)\n    s[Cl].reorder(_ko, _a, _ki, _b)\n    s[Cl].unroll(_ki)\n    s[Cl].unroll(_a)\n    s[Cl].vectorize(_b)\n\n    if local:\n        s[Al].compute_at(s[Cl], _a)\n        _aa, _ka, _ba = s[Al].op.axis\n        # TODO(csullivan)[BEFORE PR]: removing this vectorize command causes a crash. This needs to be autovectorized.\n        s[Al].vectorize(_ba)\n        s[Bl].compute_at(s[Cl], _ko)\n        _ab, _kb, _bb = s[Bl].op.axis\n        s[Bl].vectorize(_bb)\n        s[Bl].unroll(_ab)\n\n    return s\n\n\ndef compute_conv2d_1x1_NCHWc_RSCKk(input_shape, filter_shape):\n    # conv2d( [N, C, H, W, c] , [1, 1, C, K, k]\n    data = te.placeholder(input_shape, name=\"data\", dtype=\"float32\")\n    filt = te.placeholder(filter_shape, name=\"filter\", dtype=\"float32\")\n    c = te.reduce_axis((0, input_shape[1]), name=\"C\")\n    c4 = te.reduce_axis((0, input_shape[-1]), name=\"c4\")\n    kh = te.reduce_axis((0, filter_shape[0]), name=\"kh\")\n    kw = te.reduce_axis((0, filter_shape[1]), name=\"kw\")\n    conv = te.compute(\n        (input_shape[0], filter_shape[-2], input_shape[2], input_shape[3], filter_shape[-1]),\n        lambda n, ko, i, j, ki: te.sum(\n            data[n, c, i, j, c4].astype(\"float32\")\n            * filt[kh, kw, c * input_shape[-1] + c4, ko, ki].astype(\"float32\"),\n            axis=[kh, kw, c, c4],\n        ),\n        # name=\"Compute_conv2d_1x1_NCHWc_RSCKk\",\n        name=\"conv2d_1x1\",\n    )\n    return data, filt, conv\n\n\ndef schedule_conv2d_1x1_NCHWc_RSCKk(data, filt, conv):\n    # inputs: (1, 128//4, 56, 56, 4), (1, 1, 128, 128//4, 4)\n    # outputs:\n    s = te.create_schedule(conv.op)\n    A, B, C = data, filt, conv\n    At = s.cache_read(A, \"global.texture\", [C])\n    Bt = s.cache_read(B, \"global.texture\", [C])\n    Al = s.cache_read(At, \"local\", [C])\n    Bl = s.cache_read(Bt, \"local\", [C])\n    Cl = s.cache_write(C, \"local\")\n\n    def copy_to_texture(stage):\n        axes = s[stage].op.axis\n        fused = s[stage].fuse(*axes[:-1])\n        block, thread = s[stage].split(fused, factor=32)\n        s[stage].vectorize(axes[-1])\n        s[stage].bind(block, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(thread, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(At)\n    copy_to_texture(Bt)\n\n    _n, _ko, _h, _w, _ki = s[C].op.axis\n    s[C].vectorize(_ki)\n    s[C].bind(_n, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(_ko, te.thread_axis(\"threadIdx.x\"))\n\n    s[Cl].compute_at(s[C], _w)\n    _nl, _kol, _hl, _wl, _kil = s[Cl].op.axis\n    _khl, _kwl, _cl, _cl4 = s[Cl].op.reduce_axis\n    _clo, _cli = s[Cl].split(_cl, factor=4)\n    s[Cl].reorder(_clo, _cli, _cl4, _kil)\n    s[Cl].unroll(_cli)\n    s[Cl].unroll(_cl4)\n    s[Cl].vectorize(_kil)\n\n    s[Al].compute_at(s[Cl], _cli)\n    s[Al].vectorize(s[Al].op.axis[-1])\n    s[Bl].compute_at(s[Cl], _kwl)\n    s[Bl].vectorize(s[Bl].op.axis[-1])\n\n    return s\n\n\ndef compute_conv2d_1x1_WCHNc_CRSKk(input_shape, filter_shape):\n    # input_shape = [W, C, H, N, c] -> [W, C, H*N, c]\n    # filter_shape = [C, R, S, K, k] -> [C, R*S*K, k]\n    # output_shape: [WK, HN, k] -> [W, K, H, N, k]\n    data = te.placeholder(input_shape, name=\"data\", dtype=\"float32\")\n    filt = te.placeholder(filter_shape, name=\"filter\", dtype=\"float32\")\n\n    packed_data = te.compute(\n        (input_shape[0], input_shape[1], input_shape[2] * input_shape[3], input_shape[4]),\n        lambda i, j, k, l: data[i, j, k // input_shape[3], k % input_shape[3], l],\n        name=\"packed_data\",\n    )\n\n    # Logical transformation of Nd -> 3d tensor\n    # CRSKk -> C|RSK|k\n    # r = rsk // SK\n    # sk = rsk % SK\n    # s = sk // K == (rsk % SK) // K == (rsk // K) % S\n    # k = sk % K == (rsk % SK) % K == rsk % K\n    packed_filter = te.compute(\n        (filter_shape[0], filter_shape[1] * filter_shape[2] * filter_shape[3], filter_shape[4]),\n        lambda i, j, k: filt[\n            i,\n            j // (filter_shape[3] * filter_shape[2]),\n            (j // filter_shape[3]) % filter_shape[2],\n            j % filter_shape[3],\n            k,\n        ],\n        name=\"packed_filter\",\n    )\n\n    c = te.reduce_axis((0, input_shape[1]), name=\"C\")\n    c4 = te.reduce_axis((0, input_shape[-1]), name=\"c4\")\n    r = te.reduce_axis((0, filter_shape[1]), name=\"r\")\n    s = te.reduce_axis((0, filter_shape[2]), name=\"s\")\n\n    conv = te.compute(\n        (input_shape[0], filter_shape[3], input_shape[2], input_shape[3], filter_shape[4]),\n        lambda w, ko, h, n, ki: te.sum(\n            packed_data[w, c, h * input_shape[3] + n, c4].astype(\"float32\")\n            * packed_filter[\n                c * input_shape[-1] + c4, ((r * filter_shape[2]) + s) * filter_shape[3] + ko, ki\n            ].astype(\"float32\"),\n            axis=[r, s, c, c4],\n        ),\n        name=\"conv2d_1x1\",\n    )\n    return data, filt, packed_data, packed_filter, conv\n\n\ndef schedule_conv2d_1x1_WCHNc_CRSKk(data, filt, packed_data, packed_filter, conv):\n    # data: [W, C, H*N, c]\n    # filter: [C, R*S*K, k]\n    # output: [W, K, H, N, k]\n\n    # conv2d( [N, C, H, W, c] , [1, 1, C, K, k]\n    # inputs: (1, 128//4, 56, 56, 4), (1, 1, 128, 128//4, 4)\n\n    # data: (56, 128//4, 56*1, 4) = (56, 32, 56, 4)\n    # filt: (128, 1*1*128//4, 4) = (128, 32, 4)\n    # conv: (56, 32, 56, 1, 4)\n\n    s = te.create_schedule(conv.op)\n    cfg = autotvm.get_config()\n\n    s[packed_data].compute_inline()\n    s[packed_filter].compute_inline()\n    A, B, C = packed_data, packed_filter, conv\n    At = s.cache_read(A, \"global.texture\", [C])\n    Bt = s.cache_read(B, \"global.texture\", [C])\n    Al = s.cache_read(At, \"local\", [C])\n    Bl = s.cache_read(Bt, \"local\", [C])\n    Cl = s.cache_write(C, \"local\")\n\n    def copy_to_texture(stage):\n        axes = s[stage].op.axis\n        fused = s[stage].fuse(*axes[:-1])\n        block, thread = s[stage].split(fused, factor=32)\n        s[stage].vectorize(axes[-1])\n        s[stage].bind(block, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(thread, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(At)\n    copy_to_texture(Bt)\n\n    _w, _ko, _h, _n, _ki = s[C].op.axis\n    kernel_scope, _n = s[C].split(_n, nparts=1)\n\n    cfg.define_split(\"tile_f\", _ko, num_outputs=4)\n    cfg.define_split(\"tile_w\", _w, num_outputs=4)\n    cfg.define_split(\"tile_h\", _h, num_outputs=4)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    bk, vk, tk, ki = cfg[\"tile_f\"].apply(s, C, _ko)\n    bw, vw, tw, wi = cfg[\"tile_w\"].apply(s, C, _w)\n    bh, vh, th, hi = cfg[\"tile_h\"].apply(s, C, _h)\n    s[C].reorder(bh, _n, vh, th, hi)\n    bhn = s[C].fuse(bh, _n)\n\n    s[C].bind(bk, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(bhn, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(bw, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(vk, te.thread_axis(\"vthread\"))\n    s[C].bind(vh, te.thread_axis(\"vthread\"))\n    s[C].bind(vw, te.thread_axis(\"vthread\"))\n    s[C].bind(tk, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(th, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tw, te.thread_axis(\"threadIdx.x\"))\n    s[C].reorder(bw, bk, bhn, vw, vk, vh, tw, tk, th, ki, hi, wi, _ki)\n    s[C].vectorize(_ki)\n\n    # TODO(csullivan): Try uneven workgroup split\n    # _wo, _wi = s[C].split(_w, factor=4)\n    # #_hno, _hni = s[C].split(_hn, factor=8)\n    # #s[C].reorder(_wo, _wi, _ko, _hno, _hni, _ki)\n    # s[C].reorder(_wo, _ko, _hn, _ki, _wi)\n    # s[C].unroll(_wi)\n\n    # # mace:\n    # # const int out_ch_blk = get_global_id(0);\n    # # const int out_w_blk = get_global_id(1);\n    # # const int out_hb = get_global_id(2);\n\n    # bx = te.thread_axis(\"blockIdx.x\")\n    # by = te.thread_axis(\"blockIdx.y\")\n    # bz = te.thread_axis(\"blockIdx.z\")\n    # s[C].bind(_ko, bx)\n    # s[C].bind(_wo, by)\n    # s[C].bind(_hn, bz)\n\n    # s[Cl].compute_at(s[C], _hn)\n    s[Cl].compute_at(s[C], th)\n\n    _wl, _kol, _hl, _nl, _kil = s[Cl].op.axis\n    _khl, _kwl, _cl, _cl4 = s[Cl].op.reduce_axis\n\n    cfg.define_split(\"tile_c\", _cl, num_outputs=2)\n    cfg.define_split(\"tile_kh\", _khl, num_outputs=2)\n    cfg.define_split(\"tile_kw\", _kwl, num_outputs=2)\n\n    _clo, _cli = cfg[\"tile_c\"].apply(s, Cl, _cl)\n    _khlo, _khli = cfg[\"tile_kh\"].apply(s, Cl, _khl)\n    _kwlo, _kwli = cfg[\"tile_kw\"].apply(s, Cl, _kwl)\n    # s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, n, f, y, x)\n    s[Cl].reorder(_clo, _khlo, _kwlo, _cli, _cl4, _khli, _kwli, _kol, _hl, _nl, _kil, _wl)\n    # s[Cl].reorder(_clo, _khlo, _kwlo, _cli, _cl4, _khli, _kwli)\n    # s[Cl].reorder(_cl, _cl4, _kil, _wl)\n    s[Cl].unroll(_cl4)\n    s[Cl].unroll(_wl)\n    s[Cl].vectorize(_kil)\n\n    _wla, _cla, _hnla, _cl4a = s[Al].op.axis\n    s[Al].compute_at(s[Cl], _cli)\n    s[Al].vectorize(_cl4a)\n    s[Al].unroll(_wla)\n\n    _clb, _rskolb, _kilb = s[Bl].op.axis\n    s[Bl].compute_at(s[Cl], _cli)\n    s[Bl].vectorize(_kilb)\n    s[Bl].unroll(_clb)\n\n    s[C].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n\n    WO, K, HO, N, K4 = get_const_tuple(C.shape)\n    RSC, _, _ = get_const_tuple(B.shape)\n    cfg.add_flop(2 * N * K * K4 * HO * WO * RSC)\n\n    return s\n\n\ndef compute_conv2d_NCHWc_KCRSk(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Convolution operator in NCHWc layout.\"\"\"\n\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_channel_chunk, in_height, in_width, in_channel_block = Input.shape\n    num_filter_chunk, channel, kernel_h, kernel_w, num_filter_block = Filter.shape\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    # compute graph\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down, pad_right, 0]\n    temp = nn.pad(Input, pad_before, pad_after, name=\"pad_temp\")\n\n    rcc = te.reduce_axis((0, in_channel_chunk), name=\"rc\")\n    rcb = te.reduce_axis((0, in_channel_block), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    # NCHWc x KCRSk\n    # texture: NCH|W|c\n    # texture: K|CRS|k\n    # c = crs//RS\n    # rs = crs % RS\n    # r = rs // W == (crs // S) % R\n    # s = rs % W == crs % S\n    Filter = te.compute(\n        (num_filter_chunk, channel * kernel_h * kernel_w, num_filter_block),\n        lambda ffc, crs, ffb: Filter[\n            ffc, crs // (kernel_h * kernel_w), (crs // kernel_w) % kernel_h, crs % kernel_w, ffb\n        ],\n        name=\"packed_filter\",\n    )\n    return te.compute(\n        (batch, num_filter_chunk, out_height, out_width, num_filter_block),\n        lambda nn, ffc, yy, xx, ffb: te.sum(\n            temp[\n                nn, rcc, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rcb\n            ].astype(out_dtype)\n            * Filter[\n                ffc, ((rcc * in_channel_block + rcb) * kernel_h + ry) * kernel_w + rx, ffb\n            ].astype(out_dtype),\n            axis=[rcc, rcb, ry, rx],\n        ),\n        tag=\"conv2d_nchwc_kcrsk_texture\",\n    )\n\n\ndef schedule_conv2d_NCHWc_KCRSk(cfg, s, conv):\n    \"\"\"schedule optimized for batch size = 1\"\"\"\n\n    ##### space definition begin #####\n    n, fc, y, x, fb = s[conv].op.axis\n    rcc, rcb, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_fc\", fc, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rcc\", rcc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    pad_data, flattened_kernel = s[conv].op.input_tensors\n    kernel = s[flattened_kernel].op.input_tensors[0]\n    s[flattened_kernel].compute_inline()\n\n    s[pad_data].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n    kernel = flattened_kernel\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AT = s.cache_read(pad_data, \"global.texture\", [OL])\n    WT = s.cache_read(kernel, \"global.texture\", [OL])\n\n    def copy_to_texture(stage):\n        axes = s[stage].op.axis\n        fused = s[stage].fuse(*axes[:-1])\n        block, thread = s[stage].split(fused, factor=32)\n        s[stage].vectorize(axes[-1])\n        s[stage].bind(block, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(thread, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(AT)\n    copy_to_texture(WT)\n\n    AA = s.cache_read(AT, \"shared\", [OL])\n    WW = s.cache_read(WT, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, fc, y, x, fb = s[output].op.axis\n\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_fc\"].apply(s, output, fc)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi, fb)\n    s[output].vectorize(fb)\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, fc, y, x, fb = s[OL].op.axis\n\n    rcc, rcb, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rcc\"].apply(s, OL, rcc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n\n    # TODO(csullivan): check position of rcb\n    s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, rcb, n, fc, y, x, fb)\n    s[OL].vectorize(fb)\n    s[OL].unroll(rcb)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n    # cooperative fetching\n    for load in [AA, WW]:\n        if load == WW:\n            n, fyx, v = s[load].op.axis\n            fused = s[load].fuse(n, fyx)\n        else:\n            n, f, y, x, v = s[load].op.axis\n            fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_fc\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[load].vectorize(v)\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n\n    N, OCC, OH, OW, OCB = get_const_tuple(output.shape)\n    _, ICKHKW, _ = get_const_tuple(kernel.shape)\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * ICKHKW)\n\n\ndef compute_conv2d_NCHWc_KCRSk_acc32(Input, Filter, stride, padding, dilation, out_dtype=None):\n    \"\"\"Convolution operator in NCHWc layout.\"\"\"\n\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, in_channel_chunk, in_height, in_width, in_channel_block = Input.shape\n    num_filter_chunk, channel, kernel_h, kernel_w, num_filter_block = Filter.shape\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    # compute graph\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down, pad_right, 0]\n    temp = nn.pad(Input, pad_before, pad_after, name=\"pad_temp\")\n\n    rcc = te.reduce_axis((0, in_channel_chunk), name=\"rc\")\n    rcb = te.reduce_axis((0, in_channel_block), name=\"rc\")\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    # NCHWc x KCRSk\n    # texture: NCH|W|c\n    # texture: K|CRS|k\n    # c = crs//RS\n    # rs = crs % RS\n    # r = rs // W == (crs // S) % R\n    # s = rs % W == crs % S\n    Filter = te.compute(\n        (num_filter_chunk, channel * kernel_h * kernel_w, num_filter_block),\n        lambda ffc, crs, ffb: Filter[\n            ffc, crs // (kernel_h * kernel_w), (crs // kernel_w) % kernel_h, crs % kernel_w, ffb\n        ],\n        name=\"packed_filter\",\n    )\n    conv = te.compute(\n        (batch, num_filter_chunk, out_height, out_width, num_filter_block),\n        lambda nn, ffc, yy, xx, ffb: te.sum(\n            (\n                temp[nn, rcc, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, rcb]\n                * Filter[ffc, ((rcc * in_channel_block + rcb) * kernel_h + ry) * kernel_w + rx, ffb]\n            ).astype(out_dtype),\n            axis=[rcc, rcb, ry, rx],\n        ),\n        tag=\"conv2d_nchwc_kcrsk_texture\",\n    )\n    output = te.compute(conv.shape, lambda n, fc, y, x, fb: conv[n, fc, y, x, fb].astype(\"float32\"))\n    return output\n\n\ndef schedule_conv2d_NCHWc_KCRSk_acc32(cfg, s, output):\n    \"\"\"schedule optimized for batch size = 1\"\"\"\n\n    conv = output.op.input_tensors[0]\n\n    ##### space definition begin #####\n    n, fc, y, x, fb = s[conv].op.axis\n    rcc, rcb, ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_fc\", fc, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_rcc\", rcc, num_outputs=2)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    pad_data, flattened_kernel = s[conv].op.input_tensors\n    kernel = s[flattened_kernel].op.input_tensors[0]\n    s[flattened_kernel].compute_inline()\n\n    s[pad_data].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n    kernel = flattened_kernel\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AT = s.cache_read(pad_data, \"global.texture\", [OL])\n    WT = s.cache_read(kernel, \"global.texture\", [OL])\n\n    def copy_to_texture(stage):\n        axes = s[stage].op.axis\n        fused = s[stage].fuse(*axes[:-1])\n        block, thread = s[stage].split(fused, factor=32)\n        s[stage].vectorize(axes[-1])\n        s[stage].bind(block, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(thread, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(AT)\n    copy_to_texture(WT)\n\n    AA = s.cache_read(AT, \"shared\", [OL])\n    WW = s.cache_read(WT, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, fc, y, x, fb = s[output].op.axis\n\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_fc\"].apply(s, output, fc)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi, fb)\n    s[output].vectorize(fb)\n\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, fc, y, x, fb = s[OL].op.axis\n\n    rcc, rcb, ry, rx = s[OL].op.reduce_axis\n    rco, rci = cfg[\"tile_rcc\"].apply(s, OL, rcc)\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n\n    # TODO(csullivan): check position of rcb\n    s[OL].reorder(rco, ryo, rxo, rci, ryi, rxi, rcb, n, fc, y, x, fb)\n    s[OL].vectorize(fb)\n    s[OL].unroll(rcb)\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n    # cooperative fetching\n    for load in [AA, WW]:\n        if load == WW:\n            n, fyx, v = s[load].op.axis\n            fused = s[load].fuse(n, fyx)\n        else:\n            n, f, y, x, v = s[load].op.axis\n            fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_fc\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[load].vectorize(v)\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n\n    N, OCC, OH, OW, OCB = get_const_tuple(output.shape)\n    _, ICKHKW, _ = get_const_tuple(kernel.shape)\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * ICKHKW)\n\n\ndef compute_depthwise_conv2d_NCHWc_KCRSk_acc32(\n    Input, Filter, stride, padding, dilation, out_dtype=None\n):\n    \"\"\"Depthwise convolution operator in NCHWc layout.\"\"\"\n    if out_dtype is None:\n        out_dtype = Input.dtype\n    assert isinstance(stride, int) or len(stride) == 2\n    assert isinstance(dilation, int) or len(dilation) == 2\n\n    if isinstance(stride, int):\n        stride_h = stride_w = stride\n    else:\n        stride_h, stride_w = stride\n\n    if isinstance(dilation, int):\n        dilation_h = dilation_w = dilation\n    else:\n        dilation_h, dilation_w = dilation\n\n    batch, channel_chunk, in_height, in_width, channel_block = Input.shape\n    _, channel_multiplier, kernel_h, kernel_w, _ = Filter.shape\n\n    # compute the output shape\n    dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n    dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n    pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(\n        padding, (dilated_kernel_h, dilated_kernel_w)\n    )\n    out_channel_chunk = simplify(channel_chunk * channel_multiplier)\n    out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1)\n    out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1)\n    # compute graph\n    pad_before = [0, 0, pad_top, pad_left, 0]\n    pad_after = [0, 0, pad_down, pad_right, 0]\n    temp = nn.pad(Input, pad_before, pad_after, name=\"pad_temp\")\n\n    ry = te.reduce_axis((0, kernel_h), name=\"ry\")\n    rx = te.reduce_axis((0, kernel_w), name=\"rx\")\n\n    # NCHWc x CMRSc = [N,(C//4)M,OH,OW, 4c]\n    # NCHWc x CMRS\n    # texture: NCH|W|c\n    # texture: C|MRS|c\n    # output: N\n    # m = mrs//RS\n    # rs = mrs % RS\n    # r = rs // W == (mrs // S) % R\n    # s = rs % W == mrs % S\n    Filter = te.compute(\n        (channel_chunk, channel_multiplier * kernel_h * kernel_w, channel_block),\n        lambda ffc, mrs, ffb: Filter[\n            ffc, mrs // (kernel_h * kernel_w), (mrs // kernel_w) % kernel_h, mrs % kernel_w, ffb\n        ],\n        name=\"packed_filter\",\n    )\n\n    conv = te.compute(\n        (batch, out_channel_chunk, out_height, out_width, channel_block),\n        lambda nn, ffc, yy, xx, ffb: te.sum(\n            (\n                temp[\n                    nn,\n                    ffc // channel_multiplier,\n                    yy * stride_h + ry * dilation_h,\n                    xx * stride_w + rx * dilation_w,\n                    ffb,\n                ]\n                * Filter[\n                    ffc // channel_multiplier,\n                    ((ffc % channel_multiplier) * kernel_h + ry) * kernel_w + rx,\n                    ffb,\n                ]\n            ).astype(out_dtype),\n            axis=[ry, rx],\n        ),\n        tag=\"depthwise_conv2d_nchwc_kcrsk_texture\",\n    )\n    return te.compute(\n        conv.shape, lambda n, ffc, y, x, ffb: conv[n, ffc, y, x, ffb].astype(\"float32\")\n    )\n\n\ndef schedule_depthwise_conv2d_NCHWc_KCRSk_acc32(cfg, s, output):\n    \"\"\"schedule optimized for batch size = 1\"\"\"\n\n    conv = output.op.input_tensors[0]\n\n    ##### space definition begin #####\n    n, fc, y, x, fb = s[conv].op.axis\n    ry, rx = s[conv].op.reduce_axis\n    cfg.define_split(\"tile_fc\", fc, num_outputs=4)\n    cfg.define_split(\"tile_y\", y, num_outputs=4)\n    cfg.define_split(\"tile_x\", x, num_outputs=4)\n    cfg.define_split(\"tile_ry\", ry, num_outputs=2)\n    cfg.define_split(\"tile_rx\", rx, num_outputs=2)\n    cfg.define_knob(\"auto_unroll_max_step\", [0, 512, 1500])\n\n    pad_data, flattened_kernel = s[conv].op.input_tensors\n    kernel = s[flattened_kernel].op.input_tensors[0]\n    s[flattened_kernel].compute_inline()\n\n    s[pad_data].compute_inline()\n    if isinstance(kernel.op, tvm.te.ComputeOp) and \"dilate\" in kernel.op.tag:\n        s[kernel].compute_inline()\n    kernel = flattened_kernel\n\n    if conv.op in s.outputs:\n        output = conv\n        OL = s.cache_write(conv, \"local\")\n    else:\n        output = s.outputs[0].output(0)\n        s[conv].set_scope(\"local\")\n        OL = conv\n\n    # create cache stage\n    AT = s.cache_read(pad_data, \"global.texture\", [OL])\n    WT = s.cache_read(kernel, \"global.texture\", [OL])\n\n    def copy_to_texture(stage):\n        axes = s[stage].op.axis\n        fused = s[stage].fuse(*axes[:-1])\n        block, thread = s[stage].split(fused, factor=32)\n        s[stage].vectorize(axes[-1])\n        s[stage].bind(block, te.thread_axis(\"blockIdx.x\"))\n        s[stage].bind(thread, te.thread_axis(\"threadIdx.x\"))\n\n    copy_to_texture(AT)\n    copy_to_texture(WT)\n\n    AA = s.cache_read(AT, \"shared\", [OL])\n    WW = s.cache_read(WT, \"shared\", [OL])\n\n    # tile and bind spatial axes\n    n, fc, y, x, fb = s[output].op.axis\n\n    kernel_scope, n = s[output].split(n, nparts=1)\n\n    bf, vf, tf, fi = cfg[\"tile_fc\"].apply(s, output, fc)\n    by, vy, ty, yi = cfg[\"tile_y\"].apply(s, output, y)\n    bx, vx, tx, xi = cfg[\"tile_x\"].apply(s, output, x)\n\n    bf = s[output].fuse(n, bf)\n    s[output].bind(bf, te.thread_axis(\"blockIdx.z\"))\n    s[output].bind(by, te.thread_axis(\"blockIdx.y\"))\n    s[output].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[output].bind(vf, te.thread_axis(\"vthread\"))\n    s[output].bind(vy, te.thread_axis(\"vthread\"))\n    s[output].bind(vx, te.thread_axis(\"vthread\"))\n    s[output].bind(tf, te.thread_axis(\"threadIdx.z\"))\n    s[output].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[output].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi, fb)\n    s[output].vectorize(fb)\n\n    s[OL].compute_at(s[output], tx)\n\n    # tile reduction axes\n    n, fc, y, x, fb = s[OL].op.axis\n\n    ry, rx = s[OL].op.reduce_axis\n    ryo, ryi = cfg[\"tile_ry\"].apply(s, OL, ry)\n    rxo, rxi = cfg[\"tile_rx\"].apply(s, OL, rx)\n\n    s[OL].reorder(ryo, rxo, ryi, rxi, n, fc, y, x, fb)\n    s[OL].vectorize(fb)\n    # s[OL].unroll()\n\n    s[AA].compute_at(s[OL], rxo)\n    s[WW].compute_at(s[OL], rxo)\n    # cooperative fetching\n    for load in [AA, WW]:\n        if load == WW:\n            n, fyx, v = s[load].op.axis\n            fused = s[load].fuse(n, fyx)\n        else:\n            n, f, y, x, v = s[load].op.axis\n            fused = s[load].fuse(n, f, y, x)\n        tz, fused = s[load].split(fused, nparts=cfg[\"tile_fc\"].size[2])\n        ty, fused = s[load].split(fused, nparts=cfg[\"tile_y\"].size[2])\n        tx, fused = s[load].split(fused, nparts=cfg[\"tile_x\"].size[2])\n        s[load].bind(tz, te.thread_axis(\"threadIdx.z\"))\n        s[load].bind(ty, te.thread_axis(\"threadIdx.y\"))\n        s[load].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[load].vectorize(v)\n\n    # unroll\n    s[output].pragma(kernel_scope, \"auto_unroll_max_step\", cfg[\"auto_unroll_max_step\"].val)\n\n    N, OCC, OH, OW, OCB = get_const_tuple(output.shape)\n    ICC, MKHKW, ICB = get_const_tuple(kernel.shape)\n    M = (OCC * OCB) // (ICC * ICB)\n    KHKW = MKHKW // M\n\n    if isinstance(N, int):\n        cfg.add_flop(2 * N * OH * OW * OCC * OCB * KHKW)\n\n\ndef scheduler(compute, schedule, *args, **kwargs):\n    placeholders = compute(*args)\n    s = schedule(*placeholders, **kwargs)\n    return s, placeholders\n\n\ndef conv2d_1x1_NCHWc_RSCKk(input_shape, filter_shape):\n    placeholders = compute_conv2d_1x1_NCHWc_RSCKk(input_shape, filter_shape)\n    s = schedule_conv2d_1x1_NCHWc_RSCKk(*placeholders)\n    return s, placeholders\n\n\ndef conv2d_1x1_WCHNc_CRSKk(input_shape, filter_shape):\n    placeholders = compute_conv2d_1x1_WCHNc_CRSKk(input_shape, filter_shape)\n    s = schedule_conv2d_1x1_WCHNc_CRSKk(*placeholders)\n    return s, (placeholders[0], placeholders[1], placeholders[-1])\n\n\ndef conv2d_NCHWc_KCRSk(input_shape, filter_shape):\n    data = te.placeholder(input_shape, name=\"data\", dtype=\"float32\")\n    filt = te.placeholder(filter_shape, name=\"filter\", dtype=\"float32\")\n    conv = compute_conv2d_NCHWc_KCRSk(data, filt, [1, 1], [0, 0], [1, 1], \"float32\")\n    cfg = autotvm.get_config()\n    s = te.create_schedule([x.op for x in [conv]])\n    schedule_conv2d_NCHWc_KCRSk(cfg, s, conv)\n    return s, (data, filt, conv)\n\n\ndef conv2d_NCHWc_KCRSk_fp32_acc(input_shape, filter_shape):\n    data = te.placeholder(input_shape, name=\"data\", dtype=\"float32\")\n    filt = te.placeholder(filter_shape, name=\"filter\", dtype=\"float32\")\n    output = compute_conv2d_NCHWc_KCRSk_acc32(data, filt, [1, 1], [0, 0], [1, 1], \"float32\")\n    cfg = autotvm.get_config()\n    s = te.create_schedule([x.op for x in [output]])\n    schedule_conv2d_NCHWc_KCRSk_acc32(cfg, s, output)\n    return s, (data, filt, output)\n\n\ndef depthwise_conv2d_NCHWc_KCRSk_acc32(input_shape, filter_shape):\n    data = te.placeholder(input_shape, name=\"data\", dtype=\"float32\")\n    filt = te.placeholder(filter_shape, name=\"filter\", dtype=\"float32\")\n    output = compute_depthwise_conv2d_NCHWc_KCRSk_acc32(\n        data, filt, [1, 1], [0, 0], [1, 1], \"float32\"\n    )\n    cfg = autotvm.get_config()\n    s = te.create_schedule([x.op for x in [output]])\n    schedule_depthwise_conv2d_NCHWc_KCRSk_acc32(cfg, s, output)\n    return s, (data, filt, output)\n\n\ndef ref_convolution(data, kernel, stride, pad):\n    import mxnet as mx\n\n    groups = 1\n    kernel_size = (kernel.shape[2], kernel.shape[3])\n    num_filter = kernel.shape[0]\n    ref_res = mx.nd.Convolution(\n        data=mx.nd.array(data),\n        weight=mx.nd.array(kernel),\n        bias=None,\n        no_bias=True,\n        kernel=kernel_size,\n        stride=stride,\n        pad=pad,\n        num_filter=num_filter,\n        num_group=groups,\n    )\n    return ref_res.asnumpy()\n\n\ndef ref_depthwise_convolution(data, kernel, stride, pad):\n    import mxnet as mx\n\n    groups = kernel.shape[0]\n    kernel_size = (kernel.shape[2], kernel.shape[3])\n    num_filter = kernel.shape[0]\n    multiplier = kernel.shape[1]\n    ref_res = mx.nd.Convolution(\n        data=mx.nd.array(data),\n        weight=mx.nd.array(kernel),\n        bias=None,\n        no_bias=True,\n        kernel=kernel_size,\n        stride=stride,\n        pad=pad,\n        num_filter=num_filter,\n        num_group=groups,\n    )\n    return ref_res.asnumpy()\n\n\ndef validate(workload, target, dev, input_shapes, *args, **kwargs):\n    s, placeholders = workload(*input_shapes, *args, **kwargs)\n    func = tvm.driver.build(s, [*placeholders], target=target, name=\"TestFunction\")\n\n    args_tvm = []\n    args_np = []\n    for var in placeholders[:-1]:\n        var_np = np.random.uniform(size=[i.value for i in var.shape]).astype(var.dtype)\n        args_np.append(var_np)\n        args_tvm.append(tvm.nd.array(var_np, dev))\n    args_tvm.append(\n        tvm.nd.array(\n            np.zeros([i.value for i in placeholders[-1].shape], dtype=placeholders[-1].dtype), dev\n        )\n    )\n    func(*args_tvm)\n\n    if \"plus_one\" in workload.__name__:\n        np_result = args_np[0] + 1.0\n    elif \"matmul\" in workload.__name__:\n        if \"inner\" in workload.__name__:\n            np_result = np.matmul(\n                args_np[0].reshape(32, 256), args_np[1].reshape(32, 256).transpose(1, 0)\n            )\n        elif \"accum\" in workload.__name__:\n            np_result = np.matmul(\n                args_np[0].transpose((1, 0, 2)).reshape(64, 128), args_np[1].reshape(128, 64)\n            )\n        else:\n            np_result = np.matmul(\n                args_np[0].transpose((0, 2, 1)).reshape(128, 64),\n                args_np[1].transpose(1, 0, 2).reshape(64, 128),\n            )\n    elif \"conv2d_1x1_NCHWc_RSCKk\" in workload.__name__:\n        vec_length = args_np[1].shape[-1]\n        # nchwc -> nchw\n        args_np[0] = (\n            args_np[0]\n            .transpose((0, 1, 4, 2, 3))\n            .reshape(\n                args_np[0].shape[0],\n                args_np[0].shape[1] * args_np[0].shape[-1],\n                args_np[0].shape[2],\n                args_np[0].shape[3],\n            )\n        )\n        # rsckk -> rsck -> kcrs\n        args_np[1] = (\n            args_np[1]\n            .reshape(\n                args_np[1].shape[0],\n                args_np[1].shape[1],\n                args_np[1].shape[2],\n                args_np[1].shape[3] * args_np[1].shape[4],\n            )\n            .transpose((3, 2, 0, 1))\n        )\n        np_result = testing.conv2d_nchw_python(args_np[0], args_np[1], 1, 0)\n        # nkhw -> nkhwk\n        np_result = np_result.reshape(\n            np_result.shape[0],\n            np_result.shape[1] // vec_length,\n            vec_length,\n            np_result.shape[2],\n            np_result.shape[3],\n        ).transpose(0, 1, 3, 4, 2)\n    elif \"conv2d_1x1_WCHNc_CRSKk\" in workload.__name__:\n        vec_length = args_np[1].shape[-1]\n        # wchnc -> nchw\n        args_np[0] = (\n            args_np[0]\n            .transpose((3, 1, 4, 2, 0))\n            .reshape(\n                args_np[0].shape[3],\n                args_np[0].shape[1] * args_np[0].shape[-1],\n                args_np[0].shape[2],\n                args_np[0].shape[0],\n            )\n        )\n        # crskk -> crsk -> kcrs\n        args_np[1] = (\n            args_np[1]\n            .reshape(\n                args_np[1].shape[0],\n                args_np[1].shape[1],\n                args_np[1].shape[2],\n                args_np[1].shape[3] * args_np[1].shape[4],\n            )\n            .transpose((3, 0, 1, 2))\n        )\n        np_result = testing.conv2d_nchw_python(args_np[0], args_np[1], 1, 0)\n        # nkhw -> nkkhw -> wkhnk\n        np_result = np_result.reshape(\n            np_result.shape[0],\n            np_result.shape[1] // vec_length,\n            vec_length,\n            np_result.shape[2],\n            np_result.shape[3],\n        ).transpose(4, 1, 3, 0, 2)\n    elif \"NCHW_KCRS\" in workload.__name__:\n        np_result = testing.conv2d_nchw_python(args_np[0], args_np[1], 1, 0)\n    elif \"NCHWc_KCRSk\" in workload.__name__:\n        vec_length = args_np[1].shape[-1]\n        # nchwc -> nchw\n        args_np[0] = (\n            args_np[0]\n            .transpose((0, 1, 4, 2, 3))\n            .reshape(\n                args_np[0].shape[0],\n                args_np[0].shape[1] * args_np[0].shape[-1],\n                args_np[0].shape[2],\n                args_np[0].shape[3],\n            )\n        )\n        # kcrsk/cmrsc -> kcrs/cmrs\n        args_np[1] = (\n            args_np[1]\n            .transpose((0, 4, 1, 2, 3))\n            .reshape(\n                args_np[1].shape[0] * args_np[1].shape[4],\n                args_np[1].shape[1],\n                args_np[1].shape[2],\n                args_np[1].shape[3],\n            )\n        )\n        if \"depthwise\" in workload.__name__:\n            # np_result = testing.depthwise_conv2d_python_nchw(args_np[0], args_np[1], 1, \"VALID\")\n            np_result = ref_depthwise_convolution(args_np[0], args_np[1], [], [])\n        else:\n            # np_result = testing.conv2d_nchw_python(args_np[0], args_np[1], 1, 0)\n            np_result = ref_convolution(args_np[0], args_np[1], [], [])\n        # nkhw -> nkhwk\n        np_result = np_result.reshape(\n            np_result.shape[0],\n            np_result.shape[1] // vec_length,\n            vec_length,\n            np_result.shape[2],\n            np_result.shape[3],\n        ).transpose(0, 1, 3, 4, 2)\n    np.testing.assert_allclose(args_tvm[-1].asnumpy(), np_result, rtol=1e-2, atol=1e-2)\n\n\nclass BaseSingleShapeValidator:\n    @tvm.testing.parametrize_targets(\"opencl\")\n    def test_unary(self, test_func, input_shape, target, dev):\n        validate(test_func, target, dev, [input_shape])\n\n\nclass TestPlusOneRank3(BaseSingleShapeValidator):\n    input_shape = tvm.testing.parameter((32, 32, 4))\n\n    def plus_one(input_shape):\n        return scheduler(compute_plus_one_rank3, schedule_plus_one_rank3, input_shape)\n\n    test_func = tvm.testing.parameter(plus_one)\n\n\nclass TestPlusOneRank5(BaseSingleShapeValidator):\n    input_shape = tvm.testing.parameter((32, 2, 4, 4, 4))\n\n    def plus_one(input_shape):\n        return scheduler(compute_plus_one_rank5, schedule_plus_one_rank5, input_shape)\n\n    test_func = tvm.testing.parameter(plus_one)\n\n\nclass TestMatmul:\n    input_shape = tvm.testing.parameter((32, 64, 4))\n    local = tvm.testing.parameter(False, True)\n\n    def matmul(input_shape, local):\n        return scheduler(compute_matmul, schedule_matmul, input_shape, local=local)\n\n    def matmul_inner(input_shape, local):\n        return scheduler(compute_matmul_inner, schedule_matmul_inner, input_shape, local=local)\n\n    test_func = tvm.testing.parameter(matmul, matmul_inner)\n\n    @tvm.testing.parametrize_targets(\"opencl\")\n    def test_matmul(self, test_func, input_shape, local, target, dev):\n        validate(test_func, target, dev, [input_shape], local=local)\n\n\nclass TestMatmulVectorAccumulator:\n    shapeA = tvm.testing.parameter((32, 64, 4))\n    shapeB = tvm.testing.parameter((128, 16, 4))\n    local = tvm.testing.parameter(False, True)\n\n    def matmul_vector_accumulator(shapeA, shapeB, local):\n        return scheduler(\n            compute_matmul_vector_accumulator,\n            schedule_matmul_vector_accumulator,\n            shapeA,\n            shapeB,\n            local=local,\n        )\n\n    test_func = tvm.testing.parameter(matmul_vector_accumulator)\n\n    @tvm.testing.parametrize_targets(\"opencl\")\n    def test_matmul_vec_acc(self, test_func, shapeA, shapeB, local, target, dev):\n        validate(test_func, target, dev, [shapeA, shapeB], local=local)\n\n\nclass BaseConv2DValidator:\n    @tvm.testing.parametrize_targets(\"opencl\")\n    def test_conv2d(self, test_func, input_shapes, target, dev):\n        validate(test_func, target, dev, input_shapes)\n\n\nclass TestConv2dNCHWcRSCKk(BaseConv2DValidator):\n    input_shapes = tvm.testing.parameter([(1, 32, 56, 56, 4), (1, 1, 128, 32, 4)])\n    test_func = tvm.testing.parameter(conv2d_1x1_NCHWc_RSCKk)\n\n\nclass TestConv2dWCHNcCRSKk(BaseConv2DValidator):\n    input_shapes = tvm.testing.parameter([(56, 32, 56, 1, 4), (128, 1, 1, 32, 4)])\n    test_func = tvm.testing.parameter(conv2d_1x1_WCHNc_CRSKk)\n\n\nclass TestConv2dNCHWcKCRSk(BaseConv2DValidator):\n    input_shapes = tvm.testing.parameter(\n        [(1, 32, 56, 56, 4), (32, 128, 1, 1, 4)], [(1, 32, 112, 112, 4), (32, 128, 3, 3, 4)]\n    )\n    test_func = tvm.testing.parameter(conv2d_NCHWc_KCRSk, conv2d_NCHWc_KCRSk_fp32_acc)\n\n\nclass TestDepthwiseConv2dNCHWcKCRSk(BaseConv2DValidator):\n    input_shapes = tvm.testing.parameter([(1, 24, 257, 257, 4), (24, 1, 3, 3, 4)])\n    test_func = tvm.testing.parameter(depthwise_conv2d_NCHWc_KCRSk_acc32)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_autodiff.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te, topi\nfrom tvm.testing import assert_allclose\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef check_grad(\n    out, inputs, args=[], data_range=(-10, 10), desired_grads=None, assert_no_jacobian=True\n):\n    inputs = inputs if isinstance(inputs, list) else [inputs]\n\n    def check_device(device, host=\"llvm\"):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(host):\n            return\n\n        sout = te.create_schedule(out.op)\n        mout = tvm.build(sout, [out] + inputs + args)\n        out_shape = get_const_tuple(out.shape)\n\n        l, h = data_range\n        input_data = [\n            tvm.nd.array(\n                np.random.uniform(l, h, size=get_const_tuple(input.shape)).astype(input.dtype)\n            )\n            for input in inputs\n        ]\n        arg_vals = [\n            tvm.nd.array(np.random.uniform(l, h, size=get_const_tuple(arg.shape)).astype(arg.dtype))\n            for arg in args\n        ]\n\n        ones = topi.full_like(out, 1.0)\n        # we provide head to sum and reduce the output dimension,\n        # which equals to grad(out.sum(), inputs)\n        grads = te.gradient(out, inputs, head=ones)\n        grad_sched = te.create_schedule([grad.op for grad in grads])\n        mgrad = tvm.build(grad_sched, list(grads) + inputs + args)\n        if assert_no_jacobian:\n            # TODO(yzhliu): it is better to visit the expression and do assertion\n            lowered_ir = str(tvm.lower(grad_sched, list(grads) + inputs + args, simple_mode=True))\n            assert \"jacobian\" not in lowered_ir, lowered_ir\n\n        grad_data = [tvm.nd.empty(get_const_tuple(i.shape), g.dtype) for i, g in zip(inputs, grads)]\n\n        mgrad(*grad_data, *input_data, *arg_vals)\n        g_res = [g.numpy() for g in grad_data]\n\n        if desired_grads:\n            assert isinstance(desired_grads, list)\n            for actual, desired in zip(g_res, desired_grads):\n                assert_allclose(actual, desired, rtol=0.1, atol=1e-2)\n        else:\n\n            def forward(*in_data):\n                out_data = tvm.nd.empty(out_shape, out.dtype)\n                mout(out_data, *[tvm.nd.array(d) for d in list(in_data)])\n                return out_data.numpy().sum()\n\n            tvm.testing.check_numerical_grads(\n                forward, [d.numpy() for d in input_data + arg_vals], g_res\n            )\n\n    check_device(\"cpu\")\n\n\ndef test_basic_operation():\n    np.random.seed(0)\n    shape = (10, 10)\n    x = te.var(\"x\", dtype=\"float32\")\n    k = te.reduce_axis((0, 10), name=\"k\")\n    l = te.reduce_axis((0, 10), name=\"l\")\n    A0 = te.placeholder(shape, name=\"A0\")\n    A1 = te.placeholder(shape, name=\"A1\")\n    zeros = np.zeros(shape)\n\n    B = te.compute(shape, lambda i, j: A0[i, j], name=\"B\")\n    check_grad(B, [A0])\n\n    B = te.compute(shape, lambda i, j: A0[i, j] + A1[i, j], name=\"B\")\n    check_grad(B, [A0, A1])\n\n    B = te.compute(shape, lambda i, j: A0[i, j] + A0[j, i], name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.floor(A0[i, j]), name=\"B\")\n    check_grad(B, A0, desired_grads=[zeros])\n\n    B = te.compute(shape, lambda i, j: te.ceil(A0[i, j]), name=\"B\")\n    check_grad(B, A0, desired_grads=[zeros])\n\n    B = te.compute(shape, lambda i, j: te.trunc(A0[i, j]), name=\"B\")\n    check_grad(B, A0, desired_grads=[zeros])\n\n    B = te.compute(shape, lambda i, j: te.round(A0[i, j]), name=\"B\")\n    check_grad(B, A0, desired_grads=[zeros])\n\n    B = te.compute(shape, lambda i, j: A0[i, j] + te.exp(A0[j, i]), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.log(0.1 + te.abs(A0[i, j] + te.exp(A0[j, i]))), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.sigmoid(A0[i, j] * A0[i, j] * A0[j, i]), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.tanh(A0[i, j] * A0[i, j] * A0[j, i]), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.sqrt(A0[i, j] * A0[i, j] * A0[j, i]), name=\"B\")\n    check_grad(B, A0, data_range=(0.1, 10))\n\n    B = te.compute(shape, lambda i, j: te.power(te.abs(A0[i, j]), A0[j, i]), name=\"B\")\n    check_grad(B, A0, data_range=(-4, 4))\n\n    B = te.compute(shape, lambda i, j: A0[i, j] * A0[j, i], name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute((10,), lambda i: te.sum(A0[i, k] * A0[k, i], axis=k), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.sum(A0[i, k] * A0[k, i] + 5, axis=k), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: te.max(A0[i, k] * A0[k, j] + 5, axis=k), name=\"B\")\n    check_grad(B, A0)\n\n    B = te.compute(shape, lambda i, j: A0[i, j] * (A1[j, i] + A0[j, i]), name=\"B\")\n    check_grad(B, [A0, A1])\n\n    B = te.compute(\n        shape, lambda i, j: te.sum(A0[k, k] - A0[te.min(j + k, 9), j] * A0[i, k], axis=k), name=\"B\"\n    )\n    check_grad(B, A0)\n\n    def fcombine(x, y):\n        return x * y\n\n    def fidentity(t0):\n        return tvm.tir.const(1, t0)\n\n    prod = te.comm_reducer(fcombine, fidentity, name=\"prod\")\n    B = te.compute((10, 10), lambda i, j: prod(A0[i, k] + A0[k, i], axis=k), name=\"B\")\n    check_grad(B, A0)\n\n    X = te.placeholder((10,), name=\"X\")\n    A = te.compute((10,), lambda i: X[i] + X[9 - i])\n    B = te.compute((10,), lambda i: X[i] * X[9 - i])\n    Y = topi.tensordot(A, B, 1)\n    check_grad(Y, X)\n\n    X = te.placeholder((3, 3), name=\"X\")\n    Y = topi.einsum(\"ii->i\", (X))\n    check_grad(Y, X)\n\n\ndef test_topi():\n    X = te.placeholder((1, 2, 4, 4), name=\"X\")\n    W = te.placeholder((5, 2, 3, 3), name=\"W\")\n    W1 = te.placeholder((2, 5, 3, 3), name=\"W1\")\n    W2 = te.placeholder((1,), name=\"W2\")\n\n    R = topi.nn.conv2d(X, W, 1, 1, 1)\n    check_grad(R, [X, W])\n\n    R1 = topi.nn.conv2d(topi.nn.relu(R), W1, 1, 0, 1)\n    check_grad(R1, [X, W, W1])\n\n    R = topi.broadcast_to(W2, (5, 2, 3, 3))\n    check_grad(R, [W2])\n\n    R = topi.nn.conv2d(X, topi.broadcast_to(W2, (5, 2, 3, 3)), 1, 1, 1)\n    check_grad(R, [X, W2])\n\n    R = topi.nn.pool2d(X, [2, 2], [1, 1], [2, 2], [0, 0, 0, 0], \"avg\")\n    check_grad(R, X)\n\n    R = topi.nn.pool2d(X, [2, 2], [1, 1], [2, 2], [0, 0, 0, 0], \"max\")\n    check_grad(R, X)\n\n    X = te.placeholder((1, 2, 5, 5), name=\"X\")\n    R = topi.reshape(X, (1, 32))\n    check_grad(R, [X])\n\n    X = te.placeholder((1, 2, 5, 5), name=\"X\")\n    W = te.placeholder((2, 2, 3, 3), name=\"W\")\n\n    S = topi.reshape(X, (1, 50))\n    check_grad(S, [X])\n\n    R = X + topi.nn.conv2d(X + topi.nn.conv2d(X, W, 1, 1, 1), W, 1, 1, 1)\n    check_grad(R, [X, W])\n\n    S = topi.nn.softmax(topi.reshape(R, (1, 50)))\n    check_grad(S, [X, W])\n\n    S = topi.sigmoid(topi.reshape(R, (1, 50)))\n    check_grad(S, [X, W])\n\n    S = topi.tanh(topi.reshape(R, (1, 50)))\n    check_grad(S, [X, W])\n\n    S = topi.nn.log_softmax(topi.reshape(R, (1, 50)))\n    check_grad(S, [X, W])\n    check_grad(S, [W], [X])\n\n    X = te.placeholder((1, 2, 3, 5), name=\"X\")\n    Y = te.placeholder((1, 2, 7, 5), name=\"Y\")\n    S = topi.concatenate((X, Y), 2)\n    check_grad(S, [X, Y])\n\n    X = te.placeholder((1, 2, 6, 5), name=\"X\")\n    (S, R) = topi.split(X, 2, 2)\n    check_grad(S, [X])\n    check_grad(R, [X])\n    R1 = topi.concatenate((S, R), 2)\n    check_grad(R1, [X])\n    R2 = topi.concatenate((R, S), 2)\n    check_grad(R2, [X])\n\n    X = te.placeholder((4, 5), name=\"X\")\n    I = te.placeholder((100,), name=\"I\", dtype=\"int32\")\n    R = topi.take(X, topi.abs(I))\n    check_grad(R, [X], [I])\n\n    W = te.placeholder((5, 5), name=\"W\")\n    exps = topi.exp(topi.nn.dense(X, W))\n    sumexps = topi.sum(exps, axis=-1, keepdims=True)\n    R = exps / sumexps\n    check_grad(R, [X, W], data_range=(-1, 1))\n\n\ndef test_stride_dilation():\n    X = te.placeholder((1, 2, 10, 10), name=\"X\")\n    W = te.placeholder((2, 2, 1, 1), name=\"W\")\n\n    Y = topi.nn.conv2d(X, W, 1, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 3)\n    check_grad(Y, [X, W])\n\n    W = te.placeholder((2, 2, 2, 2), name=\"W\")\n\n    Y = topi.nn.conv2d(X, W, 1, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 3)\n    check_grad(Y, [X, W])\n\n    W = te.placeholder((2, 2, 3, 3), name=\"W\")\n\n    Y = topi.nn.conv2d(X, W, 1, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 1)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 2)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 1, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 2, 0, 3)\n    check_grad(Y, [X, W])\n    Y = topi.nn.conv2d(X, W, 3, 0, 3)\n    check_grad(Y, [X, W])\n\n    Y = topi.nn.pool2d(X, [1, 1], [1, 1], [1, 1], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [1, 1], [1, 1], [2, 2], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [1, 1], [1, 1], [3, 3], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [2, 2], [1, 1], [1, 1], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [2, 2], [1, 1], [2, 2], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [2, 2], [1, 1], [3, 3], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [3, 3], [1, 1], [1, 1], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [3, 3], [1, 1], [2, 2], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n    Y = topi.nn.pool2d(X, [3, 3], [1, 1], [3, 3], [0, 0, 0, 0], \"max\")\n    check_grad(Y, [X])\n\n\n@pytest.mark.xfail\ndef test_reduction_init():\n    np.random.seed(0)\n    shape = (10, 10)\n    k = te.reduce_axis((0, 10), name=\"k\")\n    A0 = te.placeholder(shape, name=\"A0\")\n\n    B = te.compute((10,), lambda i: te.sum(A0[i, k] * A0[k, i], axis=k, init=0.0), name=\"B\")\n    check_grad(B, A0)\n\n\nif __name__ == \"__main__\":\n    test_basic_operation()\n    test_topi()\n    test_stride_dilation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_build_lower.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_lower_rfactor():\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"k\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n    s = te.create_schedule(B.op)\n    ko, ki = s[B].split(B.op.reduce_axis[0], factor=16)\n    BF = s.rfactor(B, ki)\n    xo, xi = s[B].split(s[B].op.axis[0], factor=32)\n    s[B.op].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[B.op].bind(xi, te.thread_axis(\"threadIdx.y\"))\n    s[B].bind(s[B].op.reduce_axis[0], te.thread_axis(\"threadIdx.x\"))\n    s[BF].compute_at(s[B], s[B].op.reduce_axis[0])\n    fapi = tvm.lower(s, [A, B])\n\n\ndef test_dependent_output_shape():\n    n, m, x = te.size_var(\"n\"), te.size_var(\"m\"), te.size_var(\"x\")\n    A = te.placeholder((n, m))\n    B = te.compute((m, n // x), lambda i, j: A[i, j], name=\"B\")\n    s = te.create_schedule(B.op)\n    mod = tvm.build(s, [A, B, x])\n\n\ndef test_split_uneven_unique_likely():\n    a = te.placeholder(\n        (16, 16),\n    )\n    b = te.placeholder(\n        (16, 16),\n    )\n    c = te.compute((16, 16), lambda x, y: a[x, y] + b[x, y])\n\n    x, y = c.op.axis\n    sch = te.create_schedule(c.op)\n    xo, xi = sch[c].split(x, 5)\n    stmt = tvm.lower(sch, [a, b, c])[\"main\"].body\n    assert isinstance(stmt.body.body, tvm.tir.stmt.IfThenElse)\n\n\nif __name__ == \"__main__\":\n    test_lower_rfactor()\n    test_dependent_output_shape()\n    test_split_uneven_unique_likely()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_create_primfunc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir, topi\nfrom tvm.script import tir as T\n\n\ndef test_unique_name_complete_block():\n    A = te.placeholder((16, 16), name=\"A\")\n    B = te.compute((16, 16), lambda x, y: A[x, y] * 2, name=\"main\")\n    C = te.compute((16, 16), lambda x, y: B[x, y] + 1, name=\"main\")\n    func = te.create_prim_func([A, C])\n    s = tir.Schedule(func, debug_mask=\"all\")\n    assert isinstance(s.get_sref(s.get_block(\"main\")), tir.schedule.StmtSRef)\n    assert isinstance(s.get_sref(s.get_block(\"main_1\")), tir.schedule.StmtSRef)\n\n\ndef test_unique_name_reduction_block():\n    k1 = te.reduce_axis((0, 16), \"k1\")\n    k2 = te.reduce_axis((0, 16), \"k2\")\n    A = te.placeholder((16, 16), name=\"A\")\n    B = te.compute((16,), lambda i: te.sum(A[i, k1], axis=k1), name=\"sum\")\n    C = te.compute((), lambda: te.sum(B[k2], axis=k2), name=\"sum\")\n    func = te.create_prim_func([A, C])\n    s = tir.Schedule(func, debug_mask=\"all\")\n    assert isinstance(s.get_sref(s.get_block(\"sum\")), tir.schedule.StmtSRef)\n    assert isinstance(s.get_sref(s.get_block(\"sum_1\")), tir.schedule.StmtSRef)\n\n\ndef _check_workload(te_workload, tir_workload):\n    func = te.create_prim_func(te_workload())\n    tvm.ir.assert_structural_equal(func, tir_workload)\n    # make sure that we can create schedule from the func\n    s = tir.Schedule(func, debug_mask=\"all\")\n    assert s\n\n\ndef te_matmul():\n    k = te.reduce_axis((0, 128), \"k\")\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.placeholder((128, 128), name=\"B\")\n    C = te.compute((128, 128), lambda x, y: te.sum(A[x, k] * B[y, k], axis=k), name=\"C\")\n    return [A, B, C]\n\n\n@T.prim_func\ndef tir_matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i0, j0, k0 in T.grid(128, 128, 128):\n        with T.block():\n            i, j, k = T.axis.remap(\"SSR\", [i0, j0, k0])\n            with T.init():\n                C[i, j] = 0.0\n            C[i, j] += A[i, k] * B[j, k]\n\n\ndef test_matmul():\n    _check_workload(te_matmul, tir_matmul)\n\n\ndef te_element_wise():\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.compute((128, 128), lambda x, y: A[x, y] * 2, name=\"B\")\n    C = te.compute((128, 128), lambda x, y: B[x, y] + 1, name=\"C\")\n    return [A, C]\n\n\n@T.prim_func\ndef tir_element_wise(a: T.handle, c: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n\n    for i0, j0 in T.grid(128, 128):\n        with T.block():\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            B[i, j] = A[i, j] * 2.0\n    for i0, j0 in T.grid(128, 128):\n        with T.block():\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            C[i, j] = B[i, j] + 1.0\n\n\ndef test_element_wise():\n    _check_workload(te_element_wise, tir_element_wise)\n\n\ndef te_conv2d():\n    batch = 16\n    in_channel = 16\n    out_channel = 32\n    size = 14\n    kernel = 3\n\n    A = te.placeholder((batch, in_channel, size, size), name=\"A\")\n    W = te.placeholder((in_channel, kernel, kernel, out_channel), name=\"W\")\n    Apad = te.compute(\n        (batch, in_channel, size + 2, size + 2),\n        lambda nn, cc, yy, xx: tvm.tir.if_then_else(\n            tvm.tir.all(yy >= 1, yy - 1 < size, xx >= 1, xx - 1 < size),\n            A[nn, cc, yy - 1, xx - 1],\n            0.0,\n        ),\n        name=\"Apad\",\n    )\n    rc = te.reduce_axis((0, in_channel), name=\"rc\")\n    ry = te.reduce_axis((0, kernel), name=\"ry\")\n    rx = te.reduce_axis((0, kernel), name=\"rx\")\n    B = te.compute(\n        (batch, out_channel, size, size),\n        lambda nn, ff, yy, xx: te.sum(\n            Apad[nn, rc, yy + ry, xx + rx] * W[rc, ry, rx, ff], axis=[rc, ry, rx]\n        ),\n        name=\"B\",\n    )\n    return [A, W, B]\n\n\n@T.prim_func\ndef tir_conv2d(a: T.handle, w: T.handle, b: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16, 14, 14])\n    W = T.match_buffer(w, [16, 3, 3, 32])\n    B = T.match_buffer(b, [16, 32, 14, 14])\n    Apad = T.alloc_buffer([16, 16, 16, 16])\n\n    for n, c, y, x in T.grid(16, 16, 16, 16):\n        with T.block(\"Apad\"):\n            nn, cc, yy, xx = T.axis.remap(\"SSSS\", [n, c, y, x])\n            Apad[nn, cc, yy, xx] = T.if_then_else(\n                1 <= yy and yy < 15 and 1 <= xx and xx < 15,\n                A[nn, cc, yy - 1, xx - 1],\n                0.0,\n                dtype=\"float32\",\n            )\n    for n, f, y, x, kc, ky, kx in T.grid(16, 32, 14, 14, 16, 3, 3):\n        with T.block(\"B\"):\n            nn, ff, yy, xx, rc, ry, rx = T.axis.remap(\"SSSSRRR\", [n, f, y, x, kc, ky, kx])\n            with T.init():\n                B[nn, ff, yy, xx] = 0.0\n            B[nn, ff, yy, xx] += Apad[nn, rc, yy + ry, xx + rx] * W[rc, ry, rx, ff]\n\n\ndef test_conv2d():\n    _check_workload(te_conv2d, tir_conv2d)\n\n\ndef te_multi_output():\n    n = te.var(\"n\")\n    m = te.var(\"m\")\n    A0 = te.placeholder((m, n), name=\"A0\")\n    A1 = te.placeholder((m, n), name=\"A1\")\n    B0, B1 = te.compute((m, n), lambda i, j: (A0[i, j] + 2, A1[i, j] * 3), name=\"B\")\n    return [A0, A1, B0, B1]\n\n\n@T.prim_func\ndef tir_multi_output(a0: T.handle, a1: T.handle, b0: T.handle, b1: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    m = T.var(\"int32\")\n    n = T.var(\"int32\")\n    A0 = T.match_buffer(a0, (m, n))\n    A1 = T.match_buffer(a1, (m, n))\n    B0 = T.match_buffer(b0, (m, n))\n    B1 = T.match_buffer(b1, (m, n))\n\n    for i0, i1 in T.grid(m, n):\n        with T.block(\"B.v0\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            B0[i, j] = A0[i, j] + 2.0\n        with T.block(\"B.v1\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            B1[i, j] = A1[i, j] * 3.0\n\n\ndef test_multi_output():\n    _check_workload(te_multi_output, tir_multi_output)\n\n\ndef te_extern():\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.placeholder((128, 128), name=\"B\")\n    C = te.extern(\n        (128, 128),\n        [A, B],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.contrib.cblas.matmul\", ins[0], ins[1], outs[0], 0, 0\n        ),\n        name=\"C\",\n    )\n    return [A, B, C]\n\n\n@T.prim_func\ndef tir_extern(a: T.handle, b: T.handle, c: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    off1 = te.var(\"elem_offset\")\n    off2 = te.var(\"elem_offset_1\")\n    off3 = te.var(\"elem_offset_2\")\n    A = T.match_buffer(a, (128, 128), elem_offset=off1)\n    B = T.match_buffer(b, (128, 128), elem_offset=off2)\n    C = T.match_buffer(c, (128, 128), elem_offset=off3)\n    # body\n    with T.block(\"C\"):\n        T.reads([A[0:128, 0:128], B[0:128, 0:128]])\n        T.writes([C[0:128, 0:128]])\n        T.evaluate(\n            T.tvm_call_packed(\n                \"tvm.contrib.cblas.matmul\",\n                T.tvm_stack_make_array(\n                    A.data,\n                    T.tvm_stack_make_shape(128, 128, dtype=\"handle\"),\n                    0,\n                    2,\n                    0.0,\n                    off1,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    B.data,\n                    T.tvm_stack_make_shape(128, 128, dtype=\"handle\"),\n                    0,\n                    2,\n                    0.0,\n                    off2,\n                    dtype=\"handle\",\n                ),\n                T.tvm_stack_make_array(\n                    C.data,\n                    T.tvm_stack_make_shape(128, 128, dtype=\"handle\"),\n                    0,\n                    2,\n                    0.0,\n                    off3,\n                    dtype=\"handle\",\n                ),\n                0,\n                0,\n                dtype=\"int32\",\n            )\n        )\n\n\ndef test_extern():\n    _check_workload(te_extern, tir_extern)\n\n\ndef te_reordered_matmul():\n    k = te.reduce_axis((0, 128), \"k\")\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.placeholder((128, 128), name=\"B\")\n    C = te.compute((128, 128), lambda x, y: te.sum(A[x, k] * B[y, k], axis=k), name=\"C\")\n    return [C, A, B]\n\n\n@T.prim_func\ndef tir_reordered_matmul(c: T.handle, a: T.handle, b: T.handle) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i0, j0, k0 in T.grid(128, 128, 128):\n        with T.block():\n            i, j, k = T.axis.remap(\"SSR\", [i0, j0, k0])\n            with T.init():\n                C[i, j] = 0.0\n            C[i, j] += A[i, k] * B[j, k]\n\n\ndef test_arg_order():\n    _check_workload(te_reordered_matmul, tir_reordered_matmul)\n\n\ndef te_scan():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    X = te.placeholder((m, n), name=\"X\")\n    s_state = te.placeholder((m, n))\n    s_init = te.compute((1, n), lambda _, i: X[0, i])\n    s_update = te.compute((m, n), lambda t, i: s_state[t - 1, i] + X[t, i])\n    s_scan = tvm.te.scan(s_init, s_update, s_state, inputs=[X])\n    return [X, s_scan]\n\n\ndef test_error_reporting():\n    try:\n        te.create_prim_func(te_scan())\n        assert False\n    except TypeError as e:\n        error_message = str(e)\n        assert error_message.find(\"Unsupported Operation: ScanOp.\") != -1\n        return\n    assert False\n\n\ndef test_constant():\n    M = 11\n    A = te.placeholder((M,), name=\"A\")\n    B = te.compute(tuple(), lambda: 2, name=\"B\")\n    # Manually craft ProducerLoad because `B[]` is not allowed.\n    C = te.compute(\n        (M,), lambda x: A[x] + tvm.tir.expr.ProducerLoad(B, []), name=\"C\", tag=\"broadcast\"\n    )\n\n    func = te.create_prim_func([C, A])\n    func = tvm.build(func)\n    a_np = np.random.uniform(size=(M,)).astype(A.dtype)\n    c = tvm.nd.array(np.zeros(M, dtype=C.dtype))\n    x = func(c, tvm.nd.array(a_np))\n    tvm.testing.assert_allclose(a_np + 2, c.numpy())\n\n\ndef test_data_dependent_access():\n    A = te.placeholder((10,), name=\"A\")\n    B = te.placeholder((10,), name=\"B\", dtype=\"int32\")\n    C = te.compute((10,), lambda i: A[B[i]])\n\n    func = te.create_prim_func([C, A, B])\n    func = tvm.build(func)\n\n    a_np = np.random.uniform(size=(10,)).astype(A.dtype)\n    b_np = np.arange(10, dtype=B.dtype)\n    c = tvm.nd.array(np.zeros(10, dtype=C.dtype))\n    func(c, tvm.nd.array(a_np), tvm.nd.array(b_np))\n    tvm.testing.assert_allclose(a_np[b_np], c.numpy())\n\n\ndef test_select_simplify():\n    placeholder = te.placeholder([1, 128, 10, 10, 4], dtype=\"float32\")\n    tensor = topi.nn.adaptive_pool(placeholder, [1, 1], \"avg\", \"NCHW4c\")\n    result = te.create_prim_func([placeholder, tensor])\n    script_func = result.script()\n    # There should be no Select\n    assert script_func.find(\"Select\") == -1\n    # There should be no undefined vars\n    assert script_func.find(\"Var\") == -1\n\n\ndef test_tensor_attr():\n    k = te.reduce_axis((0, 128), \"k\")\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.placeholder((128, 128), name=\"B\")\n    C = te.compute(\n        (128, 128),\n        lambda x, y: te.sum(A[x, k] * B[y, k], axis=k),\n        name=\"C\",\n        attrs={\"layout_free_placeholders\": [B]},\n    )\n    func = te.create_prim_func([A, B, C])\n    rt_func = tvm.script.from_source(func.script())\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n\n@T.prim_func\ndef expected_layout_attr(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(128, 128), \"float32\"],\n    D: T.Buffer[(128, 128), \"float32\"],\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True, \"layout_free_buffers\": [1]})\n    C = T.alloc_buffer([128, 128], dtype=\"float32\")\n    for i0, i1, i2 in T.grid(128, 128, 128):\n        with T.block(\"C\"):\n            x, y, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            with T.init():\n                C[x, y] = T.float32(0)\n            C[x, y] = C[x, y] + A[x, k] * B[y, k]\n    for i0, i1 in T.grid(128, 128):\n        with T.block(\"D\"):\n            x, y = T.axis.remap(\"SS\", [i0, i1])\n            D[x, y] = C[x, y] + T.float32(1)\n\n\ndef test_tensor_layout_attr():\n    k = te.reduce_axis((0, 128), \"k\")\n    A = te.placeholder((128, 128), name=\"A\")\n    B = te.placeholder((128, 128), name=\"B\")\n    C = te.compute(\n        (128, 128),\n        lambda x, y: te.sum(A[x, k] * B[y, k], axis=k),\n        name=\"C\",\n        attrs={\"layout_free_placeholders\": [B]},\n    )\n    D = te.compute(\n        (128, 128),\n        lambda x, y: C[x, y] + 1,\n        name=\"D\",\n        attrs={\"layout_free_placeholders\": [C]},\n    )\n    func = te.create_prim_func([A, B, D])\n    tvm.ir.assert_structural_equal(func, expected_layout_attr)\n\n\ndef te_argmax_idx_val():\n    def f_combine(x, y):\n        lhs = tvm.tir.Select((x[1] >= y[1]), x[0], y[0])\n        rhs = tvm.tir.Select((x[1] >= y[1]), x[1], y[1])\n        return lhs, rhs\n\n    def f_identity(dtype0: tvm.DataType, dtype1: tvm.DataType):\n        return tvm.tir.const(-1, dtype0), tvm.te.min_value(dtype1)\n\n    argmax = te.comm_reducer(f_combine, f_identity, name=\"argmax\")\n\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    idx = te.placeholder((m, n), name=\"idx\", dtype=\"int32\")\n    val = te.placeholder((m, n), name=\"val\", dtype=\"float32\")\n    k = te.reduce_axis((0, n), \"k\")\n    max_idx, max_val = te.compute(\n        (m,), lambda i: argmax((idx[i, k], val[i, k]), axis=k), name=\"argmax\"\n    )\n    return [idx, val, max_idx, max_val]\n\n\n@T.prim_func\ndef tir_argmax_idx_val(\n    var_idx: T.handle, var_val: T.handle, var_argmax_v0: T.handle, var_argmax_v1: T.handle\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    m = T.var(\"int32\")\n    n = T.var(\"int32\")\n    idx = T.match_buffer(var_idx, [m, n], dtype=\"int32\")\n    val = T.match_buffer(var_val, [m, n], dtype=\"float32\")\n    argmax_v0 = T.match_buffer(var_argmax_v0, [m], dtype=\"int32\")\n    argmax_v1 = T.match_buffer(var_argmax_v1, [m], dtype=\"float32\")\n    for i0, i1 in T.grid(m, n):\n        with T.block(\"argmax\"):\n            i, k = T.axis.remap(\"SR\", [i0, i1])\n            T.reads(val[i, k], idx[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = T.int32(-1)\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\ndef te_argmax_val_idx():\n    def f_combine(x, y):\n        lhs = tvm.tir.Select((x[0] >= y[0]), x[0], y[0])\n        rhs = tvm.tir.Select((x[0] >= y[0]), x[1], y[1])\n        return lhs, rhs\n\n    def f_identity(dtype0: tvm.DataType, dtype1: tvm.DataType):\n        return tvm.te.min_value(dtype0), tvm.tir.const(-1, dtype1)\n\n    argmax = te.comm_reducer(f_combine, f_identity, name=\"argmax\")\n\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    val = te.placeholder((m, n), name=\"val\", dtype=\"float32\")\n    idx = te.placeholder((m, n), name=\"idx\", dtype=\"int32\")\n    k = te.reduce_axis((0, n), \"k\")\n    max_val, max_idx = te.compute(\n        (m,), lambda i: argmax((val[i, k], idx[i, k]), axis=k), name=\"argmax\"\n    )\n    return [val, idx, max_val, max_idx]\n\n\n@T.prim_func\ndef tir_argmax_val_idx(\n    var_val: T.handle, var_idx: T.handle, var_argmax_v0: T.handle, var_argmax_v1: T.handle\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    m = T.var(\"int32\")\n    n = T.var(\"int32\")\n    val = T.match_buffer(var_val, [m, n], dtype=\"float32\")\n    idx = T.match_buffer(var_idx, [m, n], dtype=\"int32\")\n    argmax_v0 = T.match_buffer(var_argmax_v0, [m], dtype=\"float32\")\n    argmax_v1 = T.match_buffer(var_argmax_v1, [m], dtype=\"int32\")\n    for i0, i1 in T.grid(m, n):\n        with T.block(\"argmax\"):\n            i, k = T.axis.remap(\"SR\", [i0, i1])\n            T.reads(val[i, k], idx[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = T.min_value(\"float32\")\n                argmax_v1[i] = T.int32(-1)\n            v_argmax_v0: T.float32 = T.Select(argmax_v0[i] >= val[i, k], argmax_v0[i], val[i, k])\n            v_argmax_v1: T.int32 = T.Select(argmax_v0[i] >= val[i, k], argmax_v1[i], idx[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\ndef test_argmax_idx_val():\n    _check_workload(te_argmax_idx_val, tir_argmax_idx_val)\n\n\ndef test_argmax_val_idx():\n    _check_workload(te_argmax_val_idx, tir_argmax_val_idx)\n\n\ndef test_int64_indices():\n    n = te.var(\"n\", \"int64\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1, name=\"B\")\n    prim_func = te.create_prim_func([A, B])\n    loop = prim_func.body.block.body\n    assert loop.loop_var.dtype == \"int64\"\n    assert loop.min.dtype == \"int64\"\n    assert loop.extent.dtype == \"int64\"\n\n\ndef test_zero_dim_add():\n    def te_func():\n        a = te.placeholder((), name=\"a\", dtype=\"int32\")\n        b = te.placeholder((), name=\"b\", dtype=\"int32\")\n        c = te.compute(a.shape, lambda *i: a(*i) + b(*i), name=\"c\")\n        return [a, b, c]\n\n    @T.prim_func\n    def expected(\n        a: T.Buffer[(), \"int32\"],\n        b: T.Buffer[(), \"int32\"],\n        c: T.Buffer[(), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            with T.block(\"c\"):\n                vi = T.axis.spatial(1, 0)\n                T.reads(a[()], b[()])\n                T.writes(c[()])\n                c[()] = a[()] + b[()]\n\n    _check_workload(te_func, expected)\n\n\nif __name__ == \"__main__\":\n    test_unique_name_complete_block()\n    test_unique_name_reduction_block()\n    test_matmul()\n    test_element_wise()\n    test_conv2d()\n    test_multi_output()\n    test_extern()\n    test_arg_order()\n    test_error_reporting()\n    test_constant()\n    test_select_simplify()\n    test_tensor_attr()\n    test_tensor_layout_attr()\n    test_argmax_idx_val()\n    test_argmax_val_idx()\n    test_int64_indices()\n    test_zero_dim_add()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_group.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test group effect\"\"\"\nimport tvm\nfrom tvm import te\n\n\ndef test_scan_group():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state = te.placeholder((m, n))\n    s_init = te.compute((1, n), lambda _, i: x[0, i])\n\n    s_update1 = te.compute((m, n), lambda t, i: s_state[t - 1, i] + x[t, i])\n    s_update2 = te.compute((m, n), lambda t, i: s_update1[t, i] + 1)\n    s_update3 = te.compute((m, n), lambda t, i: s_update2[t, i] + 1)\n    res = tvm.te.scan(s_init, s_update3, s_state, inputs=x)\n\n    s = te.create_schedule(res.op)\n    assert s[s_update1].group is not None\n    assert s[s_update2].group == s[s_update1].group\n    # Assign within group, is valid\n    s[s_update1].compute_at(s[s_update2], s_update2.op.axis[1])\n    # create a new group, for [s_update2 and s_update1]\n    g2 = s.create_group(outputs=s_update2, inputs=[s_state, x])\n    assert g2.group is not None\n    assert g2.group == s[s_update3].group\n    assert s[s_update2].group == g2\n    assert s[s_update1].group == g2\n    g2.compute_at(s[s_update3], s_update3.op.axis[1])\n    assert g2.attach_stage == s[s_update3]\n    try:\n        # compute outside group error.\n        s[s_update2].compute_at(s[s_init], s_init.op.axis[0])\n        assert False\n    except tvm.error.TVMError:\n        pass\n\n\ndef test_compute_group():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    x1 = te.compute(x.shape, lambda *i: x(*i) + 1, name=\"x1\")\n    x2 = te.compute(x.shape, lambda *i: x1(*i) + 2, name=\"x2\")\n    s = te.create_schedule(x2.op)\n    g = s.create_group(outputs=x1, inputs=x, include_inputs=True)\n    assert s[x1].group == g\n    assert s[x].group == g\n    g.compute_at(s[x2], x2.op.axis[1])\n    assert g.attach_stage == s[x2]\n    assert g.num_child_stages == 2\n\n\ndef test_nest_group():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    x1 = te.compute(x.shape, lambda *i: x(*i) + 1, name=\"x1\")\n    x2 = te.compute(x.shape, lambda *i: x1(*i) + 2, name=\"x2\")\n    s = te.create_schedule(x2.op)\n    g1 = s.create_group(outputs=x1, inputs=x)\n    g2 = s.create_group(outputs=x1, inputs=x, include_inputs=True)\n    assert set(s.groups) == set([g1, g2])\n    assert s[x].group == g2\n    assert s[x1].group == g1\n    assert g1.group == g2\n    assert g2.num_child_stages == 2\n    assert g1.num_child_stages == 1\n\n\nif __name__ == \"__main__\":\n    test_nest_group()\n    test_compute_group()\n    test_scan_group()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_hybrid_script.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm, inspect, sys, traceback, numpy, pytest, types, os\n\nfrom tvm import te\nfrom tvm.contrib import utils\nfrom tvm.te.hybrid import script\nfrom tvm.te.hybrid.runtime import HYBRID_GLOBALS\n\nimport tvm.testing\n\n\n@pytest.mark.skip\ndef run_and_check(func, args, var_dict={}, target=\"llvm\", sch=None, outs=None):\n    def tvm_val_2_py_val(val):\n        val = tvm.tir.stmt_functor.substitute(val, var_dict)\n        val = tvm.arith.Analyzer().simplify(val)\n        assert isinstance(val, (tvm.tir.IntImm,))\n        return val.value\n\n    dev = tvm.device(target, 0)\n    op = None\n\n    if sch is None:\n        outs = func(*tuple(tvm.runtime.convert(i) if isinstance(i, list) else i for i in args))\n        op = outs[0].op if isinstance(outs, list) else outs.op\n        sch = te.create_schedule(op)\n    else:\n        assert outs is not None\n        assert isinstance(outs, list)\n        op = outs[0].op\n\n    emu_args = []\n    nd_args = []\n    for i in args:\n        if isinstance(i, te.tensor.Tensor):\n            shape = [tvm_val_2_py_val(j) for j in i.shape]\n            emu_args.append(numpy.random.randn(*shape).astype(i.dtype))\n            nd_args.append(tvm.nd.array(emu_args[-1], dev))\n        elif isinstance(i, tvm.tir.Var):\n            emu_args.append(tvm_val_2_py_val(i))\n            nd_args.append(emu_args[-1])\n        else:\n            assert isinstance(i, list)\n            emu_args.append(numpy.array(i))\n\n    compile_args = [i for i in args if isinstance(i, (te.tensor.Tensor, tvm.tir.Var))] + (\n        outs if isinstance(outs, list) else [outs]\n    )\n    module = tvm.build(sch, compile_args, target=target)\n    assert module\n\n    out_tensors = []\n    for i in range(op.num_outputs):\n        output = op.output(i)\n        shape = [tvm_val_2_py_val(j) for j in output.shape]\n        nd_args.append(tvm.nd.array(numpy.zeros(shape).astype(output.dtype), dev))\n        out_tensors.append(nd_args[-1])\n\n    ref_data = func(*emu_args)\n    if isinstance(ref_data, numpy.ndarray):\n        ref_data = [ref_data]\n\n    module(*nd_args)\n\n    for nd, np in zip(out_tensors, ref_data):\n        tvm.testing.assert_allclose(nd.numpy(), np, rtol=1e-5, atol=1e-5)\n\n    module_args = [i for i in args if isinstance(i, (te.tensor.Tensor, tvm.tir.Var))]\n    module_outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    h_module = te.hybrid.build(sch, module_args, module_outs)\n\n    return h_module, module_args, module_outs\n\n\n@script\ndef outer_product(n, m, a, b):\n    \"\"\"This is a simple outer product.\n    Actually this function is not required to be documented.\n    I write this docstring to test skipping docstring functionality.\n    \"\"\"\n    c = output_tensor((n, m), a.dtype)\n    for i in range(n):\n        for j in range(m):\n            assert i < n and j < m, \"index out of range!\"\n            c[i, j] = a[i] * b[j]\n    return c\n\n\n@tvm.testing.skip_if_wheel_test\n# Test global function\n# Test bridge between frontend and backend\ndef test_outer_product():\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    a = te.placeholder((n,), name=\"a\")\n    b = te.placeholder((m,), name=\"b\")\n\n    try:\n        c = outer_product(n, m, a, b)\n        ir = c.op.body\n    except IOError as err:\n        assert sys.version_info[0] == 2 and str(err) == \"could not get source code\"\n        return\n\n    # Check for i in (0, n)\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"i\"\n    assert ir.min.value == 0\n    assert ir.extent.name == \"n\"\n    ibody = ir.body\n    assert isinstance(ibody, tvm.tir.For)\n    # Check for j in (0, m)\n    assert ibody.loop_var.name == \"j\"\n    assert ibody.min.value == 0\n    assert ibody.extent.name == \"m\"\n    # Check loop body\n    jblock = ibody.body\n    assert isinstance(jblock, tvm.tir.SeqStmt)\n    jbody = jblock[0]\n    assert isinstance(jbody, tvm.tir.AssertStmt)\n    assert isinstance(jbody.message, tvm.tir.StringImm)\n    assert jbody.message.value == \"index out of range!\"\n    jbody = jblock[1]\n    assert isinstance(jbody, tvm.tir.ProducerStore)\n    assert jbody.producer.op.name == \"c\"\n    assert len(jbody.indices) == 2\n    assert jbody.indices[0].name == \"i\"\n    assert jbody.indices[1].name == \"j\"\n    assert isinstance(jbody.value, tvm.tir.Mul)\n    mul = jbody.value\n    assert isinstance(mul.a, tvm.tir.ProducerLoad)\n    assert mul.a.producer.name == \"a\"\n    assert mul.b.producer.name == \"b\"\n\n    func, ins, outs = run_and_check(outer_product, [n, m, a, b], {n: 99, m: 101})\n    temp = utils.tempdir()\n    path = temp.relpath(\"%s.py\" % func.name)\n    func.save(path)\n    func_ = te.hybrid.HybridModule()\n    func_.load(path)\n    run_and_check(func_, ins, {n: 99, m: 101}, outs=outs)\n\n    for key, _ in HYBRID_GLOBALS.items():\n        assert key not in globals().keys()\n        assert key not in outer_product.__globals__.keys()\n\n\n@tvm.testing.skip_if_wheel_test\n# Test local function\n# Test allocation of local variable\ndef test_fanout():\n    @script\n    def fanout(n, a):\n        three = 3.0\n        b = output_tensor((a.shape[0] - 3,), a.dtype)\n        for i in range(a.shape[0] - 3):\n            sigma = 0.0\n            for j in range(3):\n                sigma += a[i + j]\n            sigma = sigma / three\n            b[i] = sigma\n        return b\n\n    n = te.size_var(\"n\")\n    a = te.placeholder((n,), \"float32\", name=\"a\")\n    try:\n        b = fanout(n, a)\n        ir = b.op.body\n    except IOError as err:\n        assert sys.version_info[0] == 2 and str(err) == \"could not get source code\"\n        return\n\n    # Check for i in (0, n-3)\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"i\"\n    assert ir.min.value == 0\n    assert tvm.ir.structural_equal(ir.extent, n - 3)\n    # Check loopbody\n    abody = ir.body\n    assert isinstance(abody, tvm.tir.ProducerRealize)\n    assert abody.bounds[0].min.value == 0\n    assert abody.bounds[0].extent.value == 1\n    assert abody.producer.op.name == \"sigma\"\n    # Check i loop body\n    rbody = abody.body\n    assert isinstance(rbody[0], tvm.tir.ProducerStore)\n    assert rbody[0].producer.op.name == \"sigma\"\n    assert len(rbody[0].indices) == 1\n    assert rbody[0].indices[0].value == 0\n    # Check fanout loop\n    jloop = rbody[1]\n    assert jloop.loop_var.name == \"j\"\n    assert jloop.min.value == 0\n    assert jloop.extent.value == 3\n    jbody = jloop.body\n    assert isinstance(jbody, tvm.tir.ProducerStore)\n    assert len(jbody.indices) == 1\n    assert jbody.indices[0].value == 0\n    assert jbody.producer.op.name == \"sigma\"\n    assert isinstance(jbody.value, tvm.tir.Add)\n    value = jbody.value\n    assert isinstance(value.a, tvm.tir.ProducerLoad)\n    assert value.a.producer.name == \"sigma\"\n    assert len(value.a.indices) == 1\n    assert value.a.indices[0].value == 0\n    assert value.b.producer.name == \"a\"\n    assert len(value.b.indices) == 1\n    assert tvm.ir.structural_equal(value.b.indices[0], ir.loop_var + jloop.loop_var)\n    divide = rbody[2]\n    assert isinstance(divide, tvm.tir.ProducerStore)\n    assert len(divide.indices) == 1\n    assert divide.indices[0].value == 0\n    value = divide.value\n    assert isinstance(value, tvm.tir.Mul)\n    assert value.a.producer.name == \"sigma\"\n    assert len(value.a.indices) == 1\n    assert value.a.indices[0].value == 0\n    assert abs(value.b.value - (1 / 3.0)) < 1e-5\n    write = rbody[3]\n    assert isinstance(write, tvm.tir.ProducerStore)\n    assert write.producer.op.name == \"b\"\n    assert write.value.producer.name == \"sigma\"\n    assert len(write.value.indices) == 1\n    assert write.value.indices[0].value == 0\n\n    func, ins, outs = run_and_check(fanout, [n, a], {n: 10})\n    run_and_check(func, ins, {n: 10}, outs=outs)\n\n\ndef test_looptype():\n    @script\n    def looptype(a, b, c):\n        d = output_tensor((16,), \"int32\")\n        e = output_tensor((16,), \"int32\")\n        f = output_tensor((16,), \"int32\")\n        for i in parallel(16):\n            d[i] = a[i]\n        for j in vectorize(16):\n            e[j] = b[j]\n        for k in unroll(16):\n            f[k] = c[k]\n        return d, e, f\n\n    a = te.placeholder((16,), name=\"a\", dtype=\"int32\")\n    b = te.placeholder((16,), name=\"b\", dtype=\"int32\")\n    c = te.placeholder((16,), name=\"c\", dtype=\"int32\")\n    try:\n        d, e, f = looptype(a, b, c)\n        ir = d.op.body\n    except:\n        return\n    iloop = ir[0]\n    jloop = ir[1]\n    kloop = ir[2]\n    assert iloop.kind == tvm.tir.ForKind.PARALLEL\n    assert jloop.kind == tvm.tir.ForKind.VECTORIZED\n    assert kloop.kind == tvm.tir.ForKind.UNROLLED\n\n    func, ins, outs = run_and_check(looptype, [a, b, c])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_if():\n    @script\n    def if_then_else(a):\n        b = output_tensor((10,), \"int32\")\n        c = output_tensor((10,), \"int32\")\n        for i in range(10):\n            if i % 2 == 0:\n                c[i] = a[i]\n            else:\n                c[i] = b[i]\n        for i in unroll(10):\n            b[i] = -1 if i % 2 == 0 else 1\n        return b, c\n\n    a = te.placeholder((10,), dtype=\"int32\", name=\"a\")\n\n    func, ins, outs = run_and_check(if_then_else, [a])\n    run_and_check(func, ins, outs=outs)\n\n    @script\n    def if_triple_condition(a):\n        b = output_tensor((10,), \"int32\")\n        for i in range(10):\n            if 0 <= i < 5:\n                b[i] = a[i]\n            else:\n                b[i] = a[i] + 1\n        return b\n\n    func, ins, outs = run_and_check(if_triple_condition, [a])\n    run_and_check(func, ins, outs=outs)\n\n    @script\n    def if_and(a):\n        b = output_tensor((10,), \"int32\")\n        for i in range(10):\n            if i >= 0 and i < 5:\n                b[i] = a[i]\n            else:\n                b[i] = a[i] + 1\n        return b\n\n    func, ins, outs = run_and_check(if_and, [a])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_bind():\n    @script\n    def vec_add(a, b):\n        c = output_tensor((1000,), \"float32\")\n        for tx in bind(\"threadIdx.x\", 1000):\n            c[tx] = a[tx] + b[tx]\n        return c\n\n    a = te.placeholder((1000,), dtype=\"float32\", name=\"a\")\n    b = te.placeholder((1000,), dtype=\"float32\", name=\"b\")\n    func, ins, outs = run_and_check(vec_add, [a, b], target=\"cuda\")\n    run_and_check(func, ins, outs=outs, target=\"cuda\")\n\n    @script\n    def raw(a, b):\n        c = output_tensor((1000,), \"float32\")\n        for i in range(1000):\n            c[i] = a[i] + b[i]\n        return c\n\n    c = raw(a, b)\n    sch = te.create_schedule(c.op)\n    x = te.thread_axis(\"threadIdx.x\")\n    sch[c].bind(c.op.axis[0], x)\n    func, ins, outs = run_and_check(raw, [a, b], sch=sch, outs=[c], target=\"cuda\")\n    run_and_check(func, ins, outs=outs, target=\"cuda\")\n\n    @te.hybrid.script\n    def foo(a):\n        c = output_tensor((a.shape[0],), a.dtype)\n        total = allocate((1,), a.dtype, \"local\")\n        len_i = a.shape[0]\n        len_j = a.shape[1]\n        for i in bind(\"threadIdx.x\", len_i):\n            total[0] = 0.0\n            for k in const_range(len_j):\n                total[0] += a[i, k]\n            c[i] = total[0]\n\n        return c\n\n    a = te.placeholder((8, 4), \"float32\")\n    c = foo(a)\n    s = te.create_schedule(c.op)\n    ir = tvm.lower(s, [a, c])\n\n    func, ins, outs = run_and_check(foo, [a], target=\"cuda\")\n    run_and_check(func, ins, outs=outs, target=\"cuda\")\n\n    @te.hybrid.script\n    def max_threads(a):\n        b = output_tensor(a.shape, a.dtype)\n        n = a.shape[0]\n        m = max_num_threads(True)\n        for i in bind(\"threadIdx.x\", m):\n            for j in bind(\"blockIdx.x\", ceil_div(n, m)):\n                if i * m + j < n:\n                    b[i * m + j] = a[i * m + j] + a[i * m + j]\n        return b\n\n    a = te.placeholder((10000,), \"float32\")\n    with tvm.target.Target(\"cuda\"):\n        func, ins, outs = run_and_check(max_threads, [a], target=\"cuda\")\n        run_and_check(func, ins, outs=outs, target=\"cuda\")\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_math_intrin():\n    @script\n    def intrin_real(a):\n        b = output_tensor((8,), \"float32\")\n        b[0] = sqrt(a[0])\n        b[1] = log(a[1])\n        b[2] = exp(a[2])\n        b[3] = sigmoid(a[3])\n        b[4] = power(a[4], a[5])\n        b[5] = tanh(a[5])\n        b[6] = min(a[4], a[5])\n        b[7] = max(a[5], a[6])\n        return b\n\n    a8 = te.placeholder((8,), dtype=\"float32\", name=\"a\")\n    b8 = intrin_real(a8)\n    sch = te.create_schedule(b8.op)\n    func = tvm.build(sch, [a8, b8])\n    assert func\n    a = numpy.arange(2, 10).astype(\"float32\")\n    tvm_a = tvm.nd.array(a)\n    tvm_b = tvm.nd.array(numpy.zeros((8,), dtype=\"float32\"))\n    b = intrin_real(a)\n    func(tvm_a, tvm_b)\n    tvm.testing.assert_allclose(b, tvm_b.numpy(), rtol=1e-5)\n\n    @script\n    def intrin_int(a):\n        b = output_tensor((1,), \"int32\")\n        b[0] = popcount(a[0])\n        return b\n\n    a1 = te.placeholder((1,), dtype=\"int32\")\n    b1 = intrin_int(a1)\n    sch = te.create_schedule(b1.op)\n    func = tvm.build(sch, [a1, b1])\n    assert func\n    a = numpy.array([114514]).astype(\"int32\")\n    tvm_a = tvm.nd.array(a)\n    tvm_b = tvm.nd.array(numpy.array([0]).astype(\"int32\"))\n    b = intrin_int(a)\n    func(tvm_a, tvm_b)\n    assert tvm_b.numpy()[0] == b[0]\n\n\n@tvm.testing.skip_if_wheel_test\n# test non caconical loops\ndef test_non_zero():\n    @te.hybrid.script\n    def blur(a):\n        b = output_tensor((30, 30), \"float32\")\n        for i in range(2, 32):\n            for j in range(2, 32):\n                s = 0.0\n                for di in range(3):\n                    for dj in range(3):\n                        s += a[i - di, j - dj]\n                b[i - 2, j - 2] = s / 9.0\n        return b\n\n    a = te.placeholder((32, 32), \"float32\", \"a\")\n    func, ins, outs = run_and_check(blur, [a])\n    run_and_check(func, ins, outs=outs)\n\n    @te.hybrid.script\n    def triangle(a, b):\n        c = output_tensor((10, 10), dtype=\"float32\")\n        for i in range(10):\n            for j in range(i, 10):\n                c[i, j] = a[i] * b[j]\n        return c\n\n    a = te.placeholder((10,), dtype=\"float32\", name=\"a\")\n    b = te.placeholder((10,), dtype=\"float32\", name=\"b\")\n\n    func, ins, outs = run_and_check(triangle, [a, b])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_allocate():\n    @te.hybrid.script\n    def blur2d(a):\n        b = output_tensor((30, 30), \"float32\")\n        for i in range(30):\n            ha = allocate((3, 30), \"float32\")\n            for j in range(3):\n                for k in range(30):\n                    ha[j, k] = a[i + j, k] + a[i + j, k + 1] + a[i + j, k + 2]\n            for j in range(30):\n                b[i, j] = (ha[0, j] + ha[1, j] + ha[2, j]) / 9.0\n        return b\n\n    a = te.placeholder((32, 32), \"float32\", \"a\")\n    b = blur2d(a)\n    sch = te.create_schedule(b.op)\n    func, ins, outs = run_and_check(blur2d, [a])\n    run_and_check(func, ins, outs=outs)\n\n    @te.hybrid.script\n    def share_vec_add(a, b):\n        c = output_tensor((256,), \"float32\")\n        shared = allocate((256,), \"float32\", \"shared\")\n        for i in bind(\"threadIdx.x\", 256):\n            shared[i] = a[i]\n        local = allocate((256,), \"float32\", \"local\")\n        for i in bind(\"threadIdx.x\", 256):\n            local[i] = b[i]\n        for i in bind(\"threadIdx.x\", 256):\n            c[i] = shared[i] + local[i]\n        return c\n\n    a = te.placeholder((256,), dtype=\"float32\", name=\"a\")\n    b = te.placeholder((256,), dtype=\"float32\", name=\"b\")\n    c = share_vec_add(a, b)\n    func, ins, outs = run_and_check(share_vec_add, [a, b], target=\"cuda\")\n    run_and_check(func, ins, outs=outs, target=\"cuda\")\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_upstream():\n    @te.hybrid.script\n    def upstream(a):\n        b = output_tensor((20,), \"float32\")\n        for i in range(20):\n            b[i] = a[i] * i\n        return b\n\n    a = te.placeholder((20,), \"float32\")\n    b = te.placeholder((20,), \"float32\")\n    c = te.compute((20,), lambda x: a[x] + b[x])\n    d = upstream(c)\n    sch = te.create_schedule([c.op, d.op])\n    ir = tvm.lower(sch, [a, b, d])\n    func = tvm.build(sch, [a, b, d])\n    assert func\n\n    a = numpy.random.randn(20).astype(\"float32\")\n    b = numpy.random.randn(20).astype(\"float32\")\n    ref = numpy.zeros((20,), \"float32\")\n    for i in range(20):\n        ref[i] = (a[i] + b[i]) * i\n\n    tvm_a = tvm.nd.array(a)\n    tvm_b = tvm.nd.array(b)\n    tvm_d = tvm.nd.array(numpy.zeros((20,)).astype(\"float32\"))\n\n    func(tvm_a, tvm_b, tvm_d)\n    tvm.testing.assert_allclose(tvm_d.numpy(), ref, 1e-5, 1e-5)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_downstream():\n    @te.hybrid.script\n    def downstream(a):\n        b = output_tensor((20,), \"float32\")\n        for i in range(20):\n            b[i] = a[i] * i\n        return b\n\n    a = te.placeholder((20,), \"float32\")\n    b = downstream(a)\n    c = te.compute((20,), lambda x: b[x] + 1.0)\n\n    sch = te.create_schedule(c.op)\n    module = tvm.build(sch, [a, c])\n    assert module\n\n    a = numpy.random.randn(20).astype(\"float32\")\n    ref = numpy.zeros((20,)).astype(\"float32\")\n    for i in range(20):\n        ref[i] = (a[i] * i) + 1.0\n\n    tvm_a = tvm.nd.array(a)\n    tvm_c = tvm.nd.array(numpy.zeros((20,)).astype(\"float32\"))\n    module(tvm_a, tvm_c)\n    tvm.testing.assert_allclose(tvm_c.numpy(), ref, 1e-5, 1e-5)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_const_param():\n    @te.hybrid.script\n    def add_something(a, b):\n        c = output_tensor((11,), \"int32\")\n        for i in range(11):\n            c[i] = a[i] + b\n        return c\n\n    a = te.placeholder((11,), dtype=\"int32\", name=\"a\")\n    b = tvm.tir.const(11, \"int32\")\n    c = add_something(a, b)\n    sch = te.create_schedule(c.op)\n    module = tvm.build(sch, [a, c], \"llvm\")\n    assert module\n\n    np_a = numpy.arange(11).astype(\"int32\")\n    np_b = 11\n    np_c = numpy.zeros((11,)).astype(\"int32\")\n\n    nd_a = tvm.nd.array(np_a)\n    nd_c = tvm.nd.array(numpy.zeros((11,)).astype(\"int32\"))\n    module(nd_a, nd_c)\n    ref = add_something(np_a, 11)\n\n    tvm.testing.assert_allclose(nd_c.numpy(), ref, 1e-5, 1e-5)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_value_index():\n    @te.hybrid.script\n    def kernel_a(a):\n        b = output_tensor((16,), \"int32\")\n        c = output_tensor((4, 4), \"int32\")\n        for i in range(16):\n            b[i] = a[i] + 2\n            c[i // 4, i % 4] = a[i] + 1\n        return b, c\n\n    @te.hybrid.script\n    def kernel_b(b, a):\n        c = output_tensor((4, 4), \"int32\")\n        for i in range(4):\n            for j in range(4):\n                c[i, j] = a[i * 4 + j] * b[i, j]\n        return c\n\n    a = te.placeholder((16,), \"int32\")\n    b, c = kernel_a(a)\n    d = kernel_b(c, b)\n    sch = te.create_schedule(d.op)\n    module = tvm.build(sch, [a, d])\n    assert module\n\n    np_a = numpy.arange(16).astype(\"int32\")\n    np_b, np_c = kernel_a(np_a)\n    ref = kernel_b(np_c, np_b)\n\n    res = tvm.nd.array(numpy.zeros((4, 4)).astype(\"int32\"))\n    module(tvm.nd.array(np_a), res)\n    tvm.testing.assert_allclose(res.numpy(), ref)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_func_call():\n    @te.hybrid.script\n    def foo(a, b):\n        for i in range(len(a)):\n            a[i] = i + 1.0\n        for i in range(len(a)):\n            b[i] = i + 1.0\n        c = outer_product(10, 10, a, b)\n        d = output_tensor(c.shape, c.dtype)\n        for i in range(10):\n            for j in range(10):\n                d[i, j] = c[i, j] + i * j\n        return d\n\n    a = te.placeholder((10,), name=\"a\")\n    b = te.placeholder((10,), name=\"b\")\n    func, ins, outs = run_and_check(foo, [a, b])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_bool():\n    @te.hybrid.script\n    def foo(a):\n        b = output_tensor(a.shape, a.dtype)\n        b[0] = 1.2\n        for i in range(1, a.shape[0] - 1):\n            if a[i] * a[i - 1] < a[i] or a[i] * a[i - 1] < a[i - 1] or i * a[i] == a[i]:\n                b[i] = a[i]\n            else:\n                b[i] = 0.0\n        return b\n\n    a = te.placeholder((10,), name=\"a\")\n    func, ins, outs = run_and_check(foo, [a])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_const_range():\n    @te.hybrid.script\n    def foo(a, b):\n        c = output_tensor(a.shape, a.dtype)\n        d = output_tensor(a.shape, \"int32\")\n\n        for i in const_range(2):\n            for j in const_range(5):\n                c[i, j] = float32(int32(a[i, j]) + b[i, j])\n\n        for i in const_range(len(b)):\n            for j in const_range(len(b[0])):\n                d[i, j] = int32(a[i, j] + b[i, j])\n\n        return c, d\n\n    a = te.placeholder((2, 5), name=\"a\", dtype=\"float32\")\n    b = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]\n    func, ins, outs = run_and_check(foo, [a, b])\n    run_and_check(func, ins, outs=outs)\n\n    @te.hybrid.script\n    def goo(a, b):\n        c = output_tensor(a.shape, a.dtype)\n        len_b = len(b)\n        for i in const_range(len_b * 2):\n            if i < len_b:\n                c[i] = a[i] + b[i]\n            else:\n                c[i - len_b] = a[i - len_b] + b[i - len_b]\n        return c\n\n    a = te.placeholder((5,), name=\"a\", dtype=\"int32\")\n    b = [1, 2, 3, 4, 5]\n    c = goo(a, tvm.runtime.convert(b))\n    sch = te.create_schedule(c.op)\n    func, ins, outs = run_and_check(goo, [a, b])\n    run_and_check(func, ins, outs=outs)\n\n    @te.hybrid.script\n    def hoo(a, b):\n        c = output_tensor(a.shape, a.dtype)\n        len_b = len(b)\n        for i in range(a.shape[0]):\n            for j in const_range(len(b)):\n                d = a[i] * b[j]\n                d += a[i] + b[j]\n                c[i] = d\n        return c\n\n    a = te.placeholder((5,), name=\"a\", dtype=\"int32\")\n    b = [1, 2, 3, 4, 5]\n    func, ins, outs = run_and_check(hoo, [a, b])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_schedule():\n    @script\n    def outer_product(a, b):\n        c = output_tensor((64, 64), a.dtype)\n        for i in range(64):\n            for j in range(64):\n                c[i, j] = a[i] * b[j]\n        return c\n\n    a = te.placeholder((64,), name=\"a\", dtype=\"float32\")\n    b = te.placeholder((64,), name=\"b\", dtype=\"float32\")\n    c = outer_product(a, b)\n\n    # Test perfect loop split\n    # Test loop reorder\n    # Test loop annotation\n    sch = te.create_schedule(c.op)\n    i, j = c.op.axis\n    io, ii = sch[c].split(i, 4)\n    sch[c].parallel(ii)\n    jo, ji = sch[c].split(j, 4)\n    joo, joi = sch[c].split(jo, 4)\n    sch[c].vectorize(ji)\n    sch[c].reorder(ii, io, joo, joi, ji)\n    ir = tvm.lower(sch, [a, b, c])[\"main\"].body\n    assert isinstance(ir, tvm.tir.AttrStmt)\n    ir = ir.body\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"i.inner\"\n    ir = ir.body\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"i.outer\"\n    ir = ir.body\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"j.outer.outer\"\n    ir = ir.body\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"j.outer.inner\"\n    ir = ir.body\n    func, ins, outs = run_and_check(outer_product, [a, b], sch=sch, outs=[c])\n    run_and_check(func, ins, outs=outs)\n\n    # Test fuse\n    sch = te.create_schedule(c.op)\n    sch[c].fuse(c.op.axis[0], c.op.axis[1])\n    ir = tvm.lower(sch, [a, b, c])[\"main\"].body\n    assert isinstance(ir, tvm.tir.AttrStmt)\n    ir = ir.body\n    assert isinstance(ir, tvm.tir.For)\n    assert ir.loop_var.name == \"i.j.fused\"\n    func, ins, outs = run_and_check(outer_product, [a, b], sch=sch, outs=[c])\n    run_and_check(func, ins, outs=outs)\n\n    # Test imperfect loop split\n    sch = te.create_schedule(c.op)\n    sch[c].split(c.op.axis[0], 3)\n    ir = tvm.lower(sch, [a, b, c], simple_mode=True)\n    func, ins, outs = run_and_check(outer_product, [a, b], sch=sch, outs=[c])\n    run_and_check(func, ins, outs=outs)\n\n    # Test loop binds\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_capture():\n    n = 8\n\n    constant_tuple = (10, n)\n    constant_list = [[1, 2], [3, n]]\n    const_value = 1\n\n    @te.hybrid.script\n    def add_something(a):\n        c = output_tensor((constant_tuple[1],), \"int32\")\n        for i in range(constant_tuple[1]):\n            c[i] = a[i] + constant_list[1][const_value]\n        return c\n\n    a = te.placeholder((n,), dtype=\"int32\", name=\"a\")\n\n    func, ins, outs = run_and_check(add_something, [a])\n    run_and_check(func, ins, outs=outs)\n\n\n@tvm.testing.skip_if_wheel_test\ndef test_array_inputs():\n    @script\n    def sum_array(inputs):\n        out = output_tensor((10,), inputs[0].dtype)\n        n = len(inputs)\n        for i in range(10):\n            for j in const_range(n):\n                out[i] += inputs[j][i]\n        return out\n\n    n = 5\n    inputs = []\n    for i in range(n):\n        inputs.append(te.placeholder((10,), name=\"t%s\" % i, dtype=\"float32\"))\n\n    out = sum_array(tvm.runtime.convert(inputs))\n    assert len(out.op.inputs) == n\n\n    sch = te.create_schedule(out.op)\n    mod = tvm.build(sch, inputs + [out], target=\"llvm\")\n    assert mod\n\n    input_nd = []\n    out_ref = numpy.zeros((10,))\n    for _ in range(n):\n        arr = numpy.random.uniform(size=(10,)).astype(\"float32\")\n        input_nd.append(tvm.nd.array(arr))\n        out_ref += arr\n    out_nd = tvm.nd.array(numpy.zeros((10,), \"float32\"))\n    mod(*input_nd, out_nd)\n    tvm.testing.assert_allclose(out_nd.numpy(), out_ref)\n\n\nif __name__ == \"__main__\":\n    test_outer_product()\n    test_fanout()\n    test_looptype()\n    test_if()\n    test_bind()\n    test_math_intrin()\n    test_non_zero()\n    test_allocate()\n    test_upstream()\n    test_downstream()\n    test_const_param()\n    test_value_index()\n    test_func_call()\n    test_bool()\n    test_const_range()\n    test_schedule()\n    test_capture()\n    test_array_inputs()\n    # TODO:\n    # test_inplace()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\nimport pickle as pkl\n\n\ndef test_schedule_create():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.placeholder((n, l), name=\"B\")\n    AA = te.compute((m, l), lambda i, j: A[i, j])\n    T = te.compute((m, n, l), lambda i, j, k: AA(i, k) * B(j, k))\n    s = te.create_schedule(T.op)\n    s[AA].set_scope(\"shared\")\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    xi1, xi2 = s[T].split(xi, factor=2)\n    s[AA].compute_at(s[T], xi1)\n    xo, xi = s[AA].split(AA.op.axis[0], factor=10)\n    s[T].reorder(xi2, xi1)\n    assert T.op.axis[1] in s[T].leaf_iter_vars\n\n    # save load json\n    json_str = tvm.ir.save_json(s)\n    s_loaded = tvm.ir.load_json(json_str)\n    assert isinstance(s_loaded, tvm.te.schedule.Schedule)\n    assert str(s_loaded.outputs[0].body) == str(s.outputs[0].body)\n\n    # pickle unpickle\n    dump = pkl.dumps(s)\n    s_loaded = pkl.loads(dump)\n    assert isinstance(s_loaded, tvm.te.schedule.Schedule)\n    assert str(s_loaded.outputs[0].body) == str(s.outputs[0].body)\n\n\ndef test_reorder():\n    m = te.size_var(\"m\")\n    A = te.placeholder((m,), name=\"A\")\n    T = te.compute(m, lambda i: A[i + 1])\n\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    xi1, xi2 = s[T].split(xi, factor=2)\n    order = (xi2, xi1, xo)\n    assert tuple(s[T].leaf_iter_vars) != order\n    s[T].reorder(*order)\n    assert tuple(s[T].leaf_iter_vars) == order\n    try:\n        # pass duplicate IterVar\n        # must raise an error\n        s[T].reorder(xi2, xi1, xi2)\n        assert False\n    except tvm.error.TVMError:\n        pass\n\n\ndef test_split():\n    m = te.size_var(\"m\")\n    A = te.placeholder((m,), name=\"A\")\n    T = te.compute((m,), lambda i: A[i])\n\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    assert tuple(s[T].leaf_iter_vars) == (xo, xi)\n\n\ndef test_tile():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    xo, yo, xi, yi = s[T].tile(T.op.axis[0], T.op.axis[1], x_factor=10, y_factor=5)\n    assert tuple(s[T].leaf_iter_vars) == (xo, yo, xi, yi)\n\n\ndef test_fuse():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    xo, yo, xi, yi = s[T].tile(T.op.axis[0], T.op.axis[1], x_factor=10, y_factor=5)\n    fused = s[T].fuse(xo, yo)\n    assert any(isinstance(x, tvm.te.schedule.Fuse) for x in s[T].relations)\n    assert tuple(s[T].leaf_iter_vars) == (fused, xi, yi)\n\n\ndef test_fuse_with_split():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    y = T.op.axis[1]\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    fused = s[T].fuse(xi, y)\n    assert any(isinstance(x, tvm.te.schedule.Fuse) for x in s[T].relations)\n    assert tuple(s[T].leaf_iter_vars) == (xo, fused)\n\n\ndef test_fuse_with_out_of_order_axis():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    y = T.op.axis[1]\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n\n    with pytest.raises(RuntimeError):\n        fused = s[T].fuse(xo, y)  # should throw here\n\n\ndef test_fuse_with_out_of_order_axis_with_reorder():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    y = T.op.axis[1]\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    s[T].reorder(y, xo, xi)\n    fused = s[T].fuse(y, xo)  # should be ok\n\n    s = te.create_schedule(T.op)\n    y = T.op.axis[1]\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    s[T].reorder(y, xo, xi)\n\n    with pytest.raises(RuntimeError):\n        fused = s[T].fuse(y, xi)  # should throw here\n\n\ndef test_singleton():\n    A = te.placeholder((), name=\"A\")\n    T = te.compute((), lambda: A() + 1)\n    s = te.create_schedule(T.op)\n    fused = s[T].fuse()\n    assert any(isinstance(x, tvm.te.schedule.Singleton) for x in s[T].relations)\n    assert tuple(s[T].leaf_iter_vars) == (fused,)\n    dump = pkl.dumps(s)\n    s_loaded = pkl.loads(dump)\n    assert isinstance(s_loaded, tvm.te.schedule.Schedule)\n\n\ndef test_vectorize():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    T = te.compute((m, n), lambda i, j: A[i, j])\n\n    s = te.create_schedule(T.op)\n    xo, yo, xi, yi = s[T].tile(T.op.axis[0], T.op.axis[1], x_factor=10, y_factor=5)\n    s[T].vectorize(yi)\n    s[T].unroll(xi)\n    UNROLL = tvm.te.schedule.IterVar.Unrolled\n    VECTORIZE = tvm.te.schedule.IterVar.Vectorized\n    assert s[T].iter_var_attrs[xi].iter_type == UNROLL\n    assert s[T].iter_var_attrs[yi].iter_type == VECTORIZE\n\n\ndef test_vectorize_commreduce():\n    V = te.placeholder((128,), name=\"V\")\n    ax = te.reduce_axis((0, 128), name=\"ax\")\n    O = te.compute((1,), lambda _: te.sum(V[ax], axis=[ax]))\n    s = te.create_schedule(O.op)\n    with pytest.raises(RuntimeError):\n        s[O].vectorize(ax)  # should throw here\n\n\ndef test_pragma():\n    m = 100\n    A = te.placeholder((m,), name=\"A\")\n    T = te.compute((m,), lambda i: A[i])\n\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=10)\n    s[T].pragma(xo, \"pragma1\")\n    s[T].pragma(xi, \"vectorize\")\n    VECTORIZE = tvm.te.schedule.IterVar.Vectorized\n    assert s[T].iter_var_attrs[xo].pragma_keys[0].value == \"pragma1\"\n    assert s[T].iter_var_attrs[xi].iter_type == VECTORIZE\n\n\ndef test_rfactor():\n    n = te.size_var(\"n\")\n    k1 = te.reduce_axis((0, n), name=\"k1\")\n    k2 = te.reduce_axis((0, n), name=\"k2\")\n    A = te.placeholder((n, n, n), name=\"A\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k1, k2], axis=[k1, k2]))\n    # normal schedule\n    s = te.create_schedule(B.op)\n    BF = s.rfactor(B, k1)\n    assert tuple(BF.shape) == (n, n)\n    assert set(BF.op.body[0].axis) == set([k2])\n    assert s[B].op.body[0].axis[0].dom.extent == n\n    assert len(s[B].all_iter_vars) == 2\n    # schedule with split\n    s = te.create_schedule(B.op)\n    ko, ki = s[B].split(k1, factor=4)\n    xo, xi = s[B].split(B.op.axis[0], factor=8)\n    BF = s.rfactor(B, ki)\n    assert BF.shape[0].value == 4\n    assert BF.shape[1] == n\n    assert BF.op.body[0].axis[0] == k2\n    assert BF.op.body[0].axis[1].var == ko.var\n    assert s[B].op.body[0].axis[0].dom.extent.value == 4\n    # schedule with factor_axis\n    s = te.create_schedule(B.op)\n    ko, ki = s[B].split(k1, factor=4)\n    xo, xi = s[B].split(B.op.axis[0], factor=8)\n    BF = s.rfactor(B, ki, 1)\n    assert n == BF.shape[0]\n    assert BF.shape[1].value == 4\n    assert BF.op.body[0].axis[0] == k2\n    assert BF.op.body[0].axis[1].var == ko.var\n    assert s[B].op.body[0].axis[0].dom.extent.value == 4\n\n\ndef test_tensor_intrin():\n    n = 16\n    x = te.placeholder((n,), name=\"x\")\n    y = te.placeholder((n,), name=\"y\")\n    z = te.compute(x.shape, lambda i: x[i] + y[i], name=\"z\")\n\n    def intrin_func(ins, outs):\n        assert isinstance(ins[0], tvm.te.schedule.Buffer)\n        assert ins[0].shape[0].value == n\n        return tvm.tir.call_packed(\"vadd\", ins[0].data, outs[0].data, ins[0].shape[0])\n\n    intrin = te.decl_tensor_intrin(z.op, intrin_func)\n    assert intrin.op == z.op\n    assert intrin.reduce_init is None\n    assert tuple(intrin.inputs) == tuple(z.op.input_tensors)\n    assert intrin.buffers[0].shape[0].value == n\n    m = 32\n    x = te.placeholder((m,), name=\"x\")\n    y = te.placeholder((m,), name=\"y\")\n    z = te.compute(x.shape, lambda i: x[i] + y[i], name=\"z\")\n    s = te.create_schedule(z.op)\n    xo, xi = s[z].split(z.op.axis[0], factor=n)\n    s[z].tensorize(xi, intrin)\n    assert s[z].iter_var_attrs[xi].tensor_intrin == intrin\n    assert s[z].iter_var_attrs[xi].iter_type == tvm.te.schedule.IterVar.Tensorized\n\n\ndef test_tensor_intrin_scalar_params():\n    n = te.size_var(\"n\")\n    x = te.placeholder((n,), name=\"x\")\n    v = te.size_var(\"v\")\n    w = te.size_var(\"w\")\n    z = te.compute((n,), lambda i: x[i] * v + w, name=\"z\")\n\n    def intrin_func(ins, outs, sp):\n        assert isinstance(ins[0], tvm.te.schedule.Buffer)\n        assert ins[0].shape[0] == n\n        assert sp[0] == v\n        assert sp[1] == w\n        return tvm.tir.call_packed(\"hw_func\", ins[0].data, outs[0].data, sp[0], sp[1])\n\n    intrin = te.decl_tensor_intrin(\n        z.op, intrin_func, scalar_params=[v, w], default_buffer_params={\"offset_factor\": 1}\n    )\n    assert intrin.op == z.op\n    assert intrin.reduce_init is None\n    assert tuple(intrin.inputs) == tuple(z.op.input_tensors)\n    assert intrin.buffers[0].shape[0] == n\n    assert tuple(intrin.scalar_params) == tuple((v, w))\n\n    A = te.placeholder((10, 10), name=\"A\")\n    # Pass scalar inputs to the TensorIntrin, interleaved with tensor inputs\n    C = te.compute((10, 10), lambda i, j: intrin(i * i, A[i, j], i + j), name=\"C\")\n    s = te.create_schedule(C.op)\n    stmt = tvm.lower(s, [A, C])[\"main\"].body\n    assert isinstance(stmt.body.body, tvm.tir.Evaluate)\n    assert len(stmt.body.body.value.args) == 5\n    assert str(stmt.body.body.value.args[3]) == \"(i: int32*i)\"\n    assert str(stmt.body.body.value.args[4]) == \"(i: int32 + j: int32)\"\n\n\ndef test_legalize_invalid_attach():\n    A = te.compute((10, 10), lambda i, j: 1.0, name=\"A\")\n    B = te.compute((10, 10), lambda i, j: A[i][j], name=\"B\")\n\n    # Case 1: Split an axis which is the target of a compute_at\n    s = te.create_schedule([B.op])\n    s[A].compute_at(s[B], B.op.axis[1])\n    s[B].split(B.op.axis[1], 2)\n\n    stmt = tvm.lower(s, [A, B], simple_mode=True)[\"main\"].body\n    assert isinstance(stmt.body.body, tvm.tir.stmt.For)\n\n    # Case 2: Fuse an axis which is the target of a compute_at\n    s = te.create_schedule([B.op])\n    s[A].compute_at(s[B], B.op.axis[1])\n    s[B].fuse(B.op.axis[0], B.op.axis[1])\n    stmt = tvm.lower(s, [A, B], simple_mode=True)[\"main\"].body\n    assert isinstance(stmt, tvm.tir.stmt.For)\n\n\ndef test_compute_at():\n    def add():\n        shape = (16, 16)\n        A = tvm.te.compute(shape, lambda *i: 1.0, name=\"A\")\n        B = tvm.te.compute(shape, lambda *i: 2.0, name=\"B\")\n        C = tvm.te.compute(shape, lambda *i: A(*i) + B(*i), name=\"C\")\n        return A, B, C\n\n    def invalid_compute_at_self():\n        A, B, C = add()\n        s = tvm.te.create_schedule(C.op)\n        s[C].compute_at(s[C], C.op.axis[0])\n        with pytest.raises(RuntimeError):\n            tvm.lower(s, [A, B], simple_mode=True)\n\n    def invalid_compute_at_loop():\n        A, B, C = add()\n        s = tvm.te.create_schedule(C.op)\n        s[A].compute_at(s[C], C.op.axis[0])\n        s[C].compute_at(s[A], A.op.axis[0])\n        with pytest.raises(RuntimeError):\n            tvm.lower(s, [C], simple_mode=True)\n\n    invalid_compute_at_self()\n    invalid_compute_at_loop()\n\n\nif __name__ == \"__main__\":\n    test_singleton()\n    test_pragma()\n    test_tensor_intrin()\n    test_tensor_intrin_scalar_params()\n    test_rfactor()\n    test_schedule_create()\n    test_reorder()\n    test_tile()\n    test_split()\n    test_fuse()\n    test_fuse_with_split()\n    test_fuse_with_out_of_order_axis()\n    test_fuse_with_out_of_order_axis_with_reorder()\n    test_vectorize()\n    test_vectorize_commreduce()\n    test_legalize_invalid_attach()\n    test_compute_at()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_bound_inference.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\ndef test_bound1():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule([A2.op])\n    xo, xi = s[A2].split(s[A2].op.axis[0], 8)\n    s[A1].compute_at(s[A2], xo)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[A1.op.axis[0]].extent.value == 8\n\n\ndef test_bound2():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n    s = te.create_schedule(A2.op)\n    xo, yo, xi, yi = s[A2].tile(A2.op.axis[0], A2.op.axis[1], 8, 8)\n    # test normalize not affecting schedule\n    _ = s.normalize()\n    s[A1].compute_at(s[A2], yo)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[A1.op.axis[0]].extent.value == 8\n    assert bounds[A1.op.axis[1]].extent.value == 8\n\n\ndef test_bound3():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    s[A1].set_scope(\"shared\")\n    xo, xi = s[A2].split(A2.op.axis[0], 32)\n    xi0, xi1 = s[A2].split(xi, nparts=16)\n    s[A2].bind(xi0, te.thread_axis(\"threadIdx.x\"))\n    yo, yi = s[A2].split(A2.op.axis[1], 16)\n    # test normalize not affecting schedule\n    _ = s.normalize()\n    s[A2].reorder(xo, xi0, yo, xi1, yi)\n    s[A1].compute_at(s[A2], yo)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[A1.op.axis[0]].extent.value == 32\n    assert bounds[A1.op.axis[1]].extent.value == 16\n\n\ndef test_bound_split_ext_less_than_factor():\n    m = 8\n    I = te.placeholder((m,), name=\"I\")\n    EF = te.compute((m,), lambda i: I[i] * 2, name=\"EF\")\n    E = te.compute((m,), lambda i: EF[i] * 2, name=\"E\")\n    s = te.create_schedule([E.op])\n    xo, xi = s[E].split(s[E].op.axis[0], factor=32)\n    s[EF].compute_at(s[E], xo)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[xi].extent.value == m\n\n\ndef test_bound_split_ext_less_than_naprts():\n    m = 8\n    I = te.placeholder((m,), name=\"I\")\n    EF = te.compute((m,), lambda i: I[i] * 2, name=\"EF\")\n    E = te.compute((m,), lambda i: EF[i] * 2, name=\"E\")\n    s = te.create_schedule([E.op])\n    xo, xi = s[E].split(s[E].op.axis[0], nparts=32)\n    s[EF].compute_at(s[E], xo)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[xo].extent.value == m\n\n\ndef test_bound_split_divisible():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((8 * m, l), name=\"A\")\n    B = te.compute((8 * m, l), lambda i, j: A[i, j], name=\"B\")\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], 8)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[xo].extent == m\n    assert bounds[xi].extent.value == 8\n\n\ndef test_bound_tile_divisible():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    shape = (8 * m, 32 * l)\n    A = te.placeholder(shape, name=\"A\")\n    B = te.compute(shape, lambda i, j: A[i, j], name=\"B\")\n    s = te.create_schedule(B.op)\n    xo, yo, xi, yi = s[B].tile(B.op.axis[0], B.op.axis[1], 8, 32)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[xo].extent == m\n    assert bounds[xi].extent.value == 8\n    assert bounds[yo].extent == l\n    assert bounds[yi].extent.value == 32\n\n\ndef test_bound_fusesplit1():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    split1 = te.var(\"s\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    fused_axes = s[A2].fuse(A2.op.axis[0], A2.op.axis[1])\n    xo, xi = s[A2].split(fused_axes, split1)\n    s[A1].compute_at(s[A2], xo)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    idxdiv = tvm.tir.indexdiv\n    tvm.testing.assert_prim_expr_equal(bounds[A1.op.axis[0]].min, idxdiv(xo * split1, l))\n\n    expected_extent = idxdiv((xo + 1) * split1 - 1, l) - idxdiv(xo * split1, l) + 1\n    for i in range(1, 6):\n        for j in range(1, 6):\n            for k in range(1, 6):\n                vars = tvm.runtime.convert(\n                    {\n                        split1: tvm.tir.const(i, \"int32\"),\n                        l: tvm.tir.const(j, \"int32\"),\n                        xo.var: tvm.tir.const(k, \"int32\"),\n                    }\n                )\n                tvm.testing.assert_prim_expr_equal(\n                    tvm.tir.stmt_functor.substitute(bounds[A1.op.axis[0]].extent, vars),\n                    tvm.tir.stmt_functor.substitute(expected_extent, vars),\n                )\n\n    tvm.testing.assert_prim_expr_equal(bounds[A1.op.axis[1]].extent, l)\n\n\ndef test_bound_fusesplit2():\n    m = te.var(\"m\")\n    l = tvm.runtime.convert(6)\n    split = tvm.runtime.convert(3)\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    fused_axes = s[A2].fuse(A2.op.axis[0], A2.op.axis[1])\n    xo, xi = s[A2].split(fused_axes, split)\n    s[A1].compute_at(s[A2], xo)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    vars = tvm.runtime.convert({xo.var: tvm.tir.const(5, \"int32\")})\n    tvm.testing.assert_prim_expr_equal(\n        tvm.tir.stmt_functor.substitute(bounds[A1.op.axis[0]].min, vars), 2\n    )\n    tvm.testing.assert_prim_expr_equal(\n        tvm.tir.stmt_functor.substitute(bounds[A1.op.axis[1]].min, vars), 3\n    )\n    tvm.testing.assert_prim_expr_equal(\n        tvm.tir.stmt_functor.substitute(bounds[A1.op.axis[0]].extent, vars), 1\n    )\n    tvm.testing.assert_prim_expr_equal(\n        tvm.tir.stmt_functor.substitute(bounds[A1.op.axis[1]].extent, vars), 3\n    )\n\n\ndef test_bound_warp():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    s[A1].set_scope(\"warp\")\n    xo, xi = s[A2].split(A2.op.axis[0], 32)\n    xi0, xi1 = s[A2].split(xi, factor=16)\n    tx = te.thread_axis(\"threadIdx.x\")\n    s[A2].bind(xi1, tx)\n    s[A2].bind(xi0, te.thread_axis(\"threadIdx.y\"))\n    y = s[A2].op.axis[1]\n    s[A1].compute_at(s[A2], y)\n    xo, xi = s[A1].split(s[A1].op.axis[0], factor=16)\n    s[A1].bind(xi, tx)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[A1.op.axis[0]].extent.value == 16\n\n\ndef test_bound_scan():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    X = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state = te.placeholder((m, n))\n    s_init = te.compute((1, n), lambda _, i: X[0, i])\n    s_update = te.compute((m, n), lambda t, i: s_state[t - 1, i] + X[t, i])\n    s_scan = tvm.te.scan(s_init, s_update, s_state)\n\n    assert tuple(s_scan.shape) == (m, n)\n    s = te.create_schedule(s_scan.op)\n    XX = s.cache_read(X, \"local\", s_update)\n    xo, xi = s[s_update].split(s_update.op.axis[1], factor=4)\n    s[XX].compute_at(s[s_update], xo)\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n    assert bounds[XX.op.axis[1]].extent.value == 4\n\n\ndef test_bound_conv1d():\n    n = te.var(\"n\")\n    A = te.compute((n + 2), lambda i: 1, name=\"A\")\n\n    def computeB(ii):\n        i = ii + 1\n        return A[i - 1] + A[i] + A[i + 1]\n\n    B = te.compute(n, computeB, name=\"B\")\n    s = te.create_schedule(B.op)\n    s[A].compute_at(s[B], B.op.axis[0])\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[A.op.axis[0]].extent.value == 3\n\n\ndef test_bound_blur():\n    n = tvm.runtime.convert(12)\n    A = te.compute((n, n), lambda i, j: 1, name=\"A\")\n\n    def computeB(ii, jj):\n        # set the correct center\n        i = ii + 1\n        j = jj + 1\n        return A[i][j] + A[i - 1][j] + A[i + 1][j] + A[i][j + 1] + A[i][j - 1]\n\n    B = te.compute((n - 2, n - 2), computeB, name=\"B\")\n    s = te.create_schedule(B.op)\n    s[A].compute_at(s[B], B.op.axis[1])\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[A.op.axis[0]].extent.value == 3\n    assert bounds[A.op.axis[1]].extent.value == 3\n\n\ndef test_bound_rfactor():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    k = te.reduce_axis((0, n))\n    B = te.compute((1,), lambda i: te.sum(A[k], axis=k, where=(i > 1)), name=\"B\")\n    # schedule\n    s = te.create_schedule(B.op)\n    kf, ki = s[B].split(k, nparts=4)\n    BF = s.rfactor(B, kf)\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n\n    assert bounds[BF.op.axis[0]].extent.value == 4\n    assert bounds[BF.op.axis[1]].extent.value == 1\n\n\ndef test_bound_group_schedule():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    x1 = te.compute(x.shape, lambda *i: x(*i) + 1, name=\"x1\")\n    x2 = te.compute(x.shape, lambda *i: x1(*i) + 2, name=\"x2\")\n    s = te.create_schedule(x2.op)\n    g = s.create_group(outputs=x1, inputs=x, include_inputs=True)\n    g.compute_at(s[x2], x2.op.axis[0])\n    assert s[x1].group == g\n    assert s[x].group == g\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[x.op.axis[0]].extent.value == 1\n    assert bounds[x.op.axis[1]].extent == n\n\n\ndef test_bound_nest_group():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    x1 = te.compute(x.shape, lambda *i: x(*i) + 1, name=\"x1\")\n    x2 = te.compute(x.shape, lambda *i: x1(*i) + 2, name=\"x2\")\n    s = te.create_schedule(x2.op)\n    g1 = s.create_group(outputs=x, inputs=x, include_inputs=True)\n    g2 = s.create_group(outputs=x1, inputs=x, include_inputs=True)\n    assert s[x].group == g1\n    assert s[x1].group == g2\n    g2.compute_at(s[x2], x2.op.axis[0])\n    g1.compute_at(s[x1], s[x1].op.axis[1])\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[x.op.axis[0]].extent.value == 1\n    assert bounds[x.op.axis[1]].extent.value == 1\n    assert bounds[x1.op.axis[0]].extent.value == 1\n    assert bounds[x1.op.axis[1]].extent == n\n\n\ndef test_bound_nest_thread():\n    m = te.var(\"m\")\n    A = te.placeholder((m), name=\"A\")\n    A1 = te.compute((m,), lambda i: A[i], name=\"A1\")\n    A2 = te.compute((m,), lambda i: A1[i] + 2, name=\"A2\")\n    A3 = te.compute((m,), lambda i: A2[i] + 3, name=\"A3\")\n\n    s = te.create_schedule(A3.op)\n    s[A2].set_scope(\"shared\")\n    s[A1].set_scope(\"local\")\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    bx, tx = s[A3].split(A3.op.axis[0], factor=32)\n    s[A3].bind(bx, block_x)\n    s[A3].bind(tx, thread_x)\n    s[A2].compute_at(s[A3], tx)\n    _, xi = s[A2].split(A2.op.axis[0], nparts=1)\n    s[A2].bind(xi, thread_x)\n    s[A1].compute_at(s[A3], tx)\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[A1.op.axis[0]].extent.value == 1\n    assert bounds[A2.op.axis[0]].extent.value == 32\n    assert bounds[A3.op.axis[0]].extent == m\n\n\ndef test_gemm_bound():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n, n), name=\"A\")\n    B = te.placeholder((n, n), name=\"B\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    C = te.compute((n, n), lambda ii, jj: te.sum(A[ii, k] * B[jj, k], axis=k), name=\"CC\")\n    # schedule\n    s = te.create_schedule(C.op)\n    xtile, ytile = 32, 32\n    scale = 8\n    num_thread = 8\n    block_factor = scale * num_thread\n    block_x = te.thread_axis(\"blockIdx.x\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n\n    CC = s.cache_write(C, \"local\")\n    AA = s.cache_read(A, \"shared\", [CC])\n    BB = s.cache_read(B, \"shared\", [CC])\n    by, yi = s[C].split(C.op.axis[0], factor=block_factor)\n    bx, xi = s[C].split(C.op.axis[1], factor=block_factor)\n    s[C].reorder(by, bx, yi, xi)\n    s[C].bind(by, block_y)\n    s[C].bind(bx, block_x)\n    ty, yi = s[C].split(yi, nparts=num_thread)\n    tx, xi = s[C].split(xi, nparts=num_thread)\n    s[C].reorder(ty, tx, yi, xi)\n    s[C].bind(ty, thread_y)\n    s[C].bind(tx, thread_x)\n    yo, xo = CC.op.axis\n    s[CC].reorder(k, yo, xo)\n\n    s[CC].compute_at(s[C], tx)\n    s[AA].compute_at(s[CC], k)\n    s[BB].compute_at(s[CC], k)\n\n    ty, xi = s[AA].split(s[AA].op.axis[0], nparts=num_thread)\n    tx, xi = s[AA].split(xi, nparts=num_thread)\n    s[AA].bind(ty, thread_y)\n    s[AA].bind(tx, thread_x)\n\n    ty, xi = s[BB].split(s[BB].op.axis[0], nparts=num_thread)\n    tx, xi = s[BB].split(xi, nparts=num_thread)\n    s[BB].bind(ty, thread_y)\n    s[BB].bind(tx, thread_x)\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[BB.op.axis[0]].extent.value == 64\n    assert bounds[AA.op.axis[0]].extent.value == 64\n    assert bounds[CC.op.axis[0]].extent.value == 8\n    assert bounds[CC.op.axis[1]].extent.value == 8\n\n\ndef test_bound_tensor_compute_op():\n    def intrin_test():\n        m1 = te.var(\"m1\")\n        n1 = te.var(\"n1\")\n        a = te.placeholder((m1, n1), name=\"a\")\n        c = te.compute((1, n1), lambda i, j: a[0, j] + a[1, j] + a[2, j], name=\"c\")\n\n        Ab = tvm.tir.decl_buffer(a.shape, name=\"Abuf\", offset_factor=1)\n        Cb = tvm.tir.decl_buffer(c.shape, name=\"Cbuf\", offset_factor=1)\n\n        def intrin_func(ins, outs):\n            aa = ins[0]\n            cc = outs[0]\n\n            def _body():\n                ib = tvm.tir.ir_builder.create()\n                ib.emit(\n                    tvm.tir.call_extern(\"int32\", \"test\", cc.access_ptr(\"w\"), aa.access_ptr(\"r\"))\n                )\n                return ib.get()\n\n            return _body()\n\n        return te.decl_tensor_intrin(c.op, intrin_func, binds={a: Ab, c: Cb})\n\n    test_func = intrin_test()\n    A = te.placeholder((20, 20), name=\"A\")\n    B = te.compute(A.shape, lambda i, j: A[i, j], name=\"B\")\n    C = te.compute((10, 20), lambda i: test_func(B[i:10, 0:20]), name=\"C\")\n    s = te.create_schedule(C.op)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    assert bounds[B.op.axis[0]].extent.value == 10\n\n\ndef test_bound_simplification_failure():\n    # Check that the bounds are not expanded\n    A = te.compute((2,), lambda j: j, \"A\")\n\n    def _check(B, A=A):\n        s = te.create_schedule(B.op)\n        s = s.normalize()\n        bounds = tvm.te.schedule.InferBound(s)\n        stmt = tvm.lower(s, [B, A], simple_mode=True)\n        if not bounds[A.op.axis[0]].extent.value <= 2:\n            print(stmt)\n            assert bounds[A.op.axis[0]].extent.value <= 2\n\n    tdiv = tvm.tir.truncdiv\n    # These are hard to simplify, moreover we don't simplify them\n    _check(te.compute((10,), lambda i: A[tvm.te.min(3 * i, 4 * i) + tvm.te.min(-3 * i, -2 * i)]))\n    _check(te.compute((10,), lambda i: A[tvm.te.min(3 * i, 4 * i) + tvm.te.max(-3 * i, -4 * i)]))\n    _check(te.compute((10,), lambda i: A[-2 * tdiv(i, 2) - tvm.te.min(i, 0 - i)]))\n    _check(te.compute((10,), lambda i: A[i + (0 - i)]))\n    # This would cause out of bounds, but we nevertheless include it\n    _check(te.compute((10,), lambda i: A[i]))\n\n\nif __name__ == \"__main__\":\n    test_bound_nest_thread()\n    test_bound1()\n    test_bound_nest_group()\n    test_bound_group_schedule()\n    test_bound_scan()\n    test_bound3()\n    test_bound_rfactor()\n    test_bound_blur()\n    test_bound_conv1d()\n    test_bound2()\n    test_gemm_bound()\n    test_bound_warp()\n    test_bound_tensor_compute_op()\n    test_bound_simplification_failure()\n    test_bound_fusesplit1()\n    test_bound_fusesplit2()\n    test_bound_split_divisible()\n    test_bound_tile_divisible()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_bound_inference_tiling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_bound_tile_mod():\n    def compute(M_tiles, N_tiles, factor, dtype):\n        # Algo\n        M = M_tiles * factor\n        N = N_tiles * factor\n\n        A = tvm.te.placeholder((N, M), name=\"A\", dtype=dtype)\n        C = tvm.te.compute((N, M), lambda n, m: A[n, m], name=\"C\")\n        s = tvm.te.create_schedule(C.op)\n\n        return s, A, C\n\n    def schedule(s, factor, padding, A, C):\n        C_local = s.cache_write(C, \"local\")\n\n        n, m = C.op.axis\n        bn, bm, ni, mi = s[C].tile(n, m, factor, factor)\n        nio, nii = s[C].split(ni, 2)\n        n = s[C].fuse(nii, mi)\n        C_shared = s.cache_write(C, \"shared\")\n        bn, bm, ni, mi = C_shared.op.axis\n        s[C_shared].storage_align(ni, factor * 2, padding)\n\n        n, m = s[C].op.axis\n        bn, bm, ni, mi = s[C].tile(n, m, factor, factor)\n        s[C].set_scope(\"global\")\n        niio, niii = s[C].split(ni, 32)\n        s[C_shared].compute_at(s[C], niio)\n\n        return s\n\n    s, A, C = compute(2, 2, 128, \"float16\")\n    s = schedule(s, 128, 8, A, C)\n    bounds = tvm.te.schedule.InferBound(s)\n    check = bounds[s.stages[2].op.axis[2]].extent == 16\n    if not check:\n        print(tvm.lower(s, [A, C], simple_mode=True))\n    assert check\n\n\nif __name__ == \"__main__\":\n    test_bound_tile_mod()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_graph.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_scan():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state = te.placeholder((m, n))\n    s_init = te.compute((1, n), lambda _, i: x[0, i], name=\"s_init\")\n    x_trans = te.compute((m, n), lambda i, j: x[i, j] + 1, name=\"x_trans\")\n    s_up1 = te.compute((m, n), lambda t, i: s_state[t - 1, i] + 1, name=\"up1\")\n    s_update = te.compute((m, n), lambda t, i: s_up1[t, i] + x_trans[t, i], name=\"update\")\n    s_scan = tvm.te.scan(s_init, s_update, s_state)\n\n    def test_getbody():\n        body = tvm.te.schedule.ScanGetBody(s_scan.op)\n        assert set(body) == set([s_scan.op, s_update.op, s_up1.op])\n\n    def test_attach_path():\n        s = te.create_schedule(s_scan.op)\n        s[x_trans].compute_at(s[s_update], s_update.op.axis[0])\n        apath = tvm.te.schedule.CreateAttachPath(s)\n        assert tuple(apath[s_update.op]) == tuple([s_scan.op.scan_axis])\n        assert tuple(apath[x_trans.op]) == tuple([s_update.op.axis[0], s_scan.op.scan_axis])\n\n    def test_fix_pt():\n        body = tvm.te.schedule.ScanGetBody(s_scan.op)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(s_scan.op)\n        assert fxpt[s_scan.spatial_axis_[0]].value != 0\n\n\ndef test_scan_fix_point():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    l = te.var(\"l\")\n    x = te.compute((l, m, n), lambda *i: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state = te.placeholder((l, m, n))\n    s_init = te.compute((1, m, n), lambda _, i, j: x[0, i, j], name=\"s_init\")\n\n    def test_scan0():\n        s_update = te.compute(\n            (l, m, n), lambda t, i, j: x[t, j, i] + s_state[t - 1, i, j], name=\"update\"\n        )\n        s_scan = tvm.te.scan(s_init, s_update, s_state)\n        body = tvm.te.schedule.ScanGetBody(s_scan.op)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(s_scan.op)\n        assert fxpt[s_scan.op.spatial_axis_[0]].value == 1\n        assert fxpt[s_scan.op.spatial_axis_[1]].value == 1\n\n    def test_scan1():\n        s_update = te.compute(\n            (l, m, n), lambda t, i, j: x[t, j, i] + s_state[t - 1, j, i], name=\"update\"\n        )\n        s_scan = tvm.te.scan(s_init, s_update, s_state)\n        body = tvm.te.schedule.ScanGetBody(s_scan.op)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(s_scan.op)\n        assert fxpt[s_scan.op.spatial_axis_[0]].value == 0\n        assert fxpt[s_scan.op.spatial_axis_[1]].value == 0\n\n    def test_scan3_not_exact_reach():\n        s_h1 = te.compute((l, n, m), lambda t, j, i: s_state[t - 1, i, j], name=\"h1\")\n        s_h2 = te.compute((l, m, n), lambda t, i, j: s_state[t - 1, i, 10] * 2, name=\"h1\")\n        s_update = te.compute(\n            (l, m, n), lambda t, i, j: s_h1[t, j, i] + s_h2[t, i, j], name=\"update\"\n        )\n        s_scan = tvm.te.scan(s_init, s_update, s_state)\n        body = tvm.te.schedule.ScanGetBody(s_scan.op)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(s_scan.op)\n        assert fxpt[s_scan.op.spatial_axis_[0]].value == 1\n        assert fxpt[s_scan.op.spatial_axis_[1]].value == 0\n\n    def test_scan4_reach_other():\n        s_h1 = te.compute((l, n, m), lambda t, j, i: s_state[t - 1, j, j], name=\"h1\")\n        s_h2 = te.compute((l, m, n), lambda t, i, j: s_state[t - 1, i, j] * 2, name=\"h1\")\n        s_update = te.compute(\n            (l, m, n), lambda t, i, j: s_h1[t, j, i] + s_h2[t, i, j], name=\"update\"\n        )\n        s_scan = tvm.te.scan(s_init, s_update, s_state)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(s_scan.op)\n        assert fxpt[s_scan.op.spatial_axis_[0]].value == 0\n        assert fxpt[s_scan.op.spatial_axis_[1]].value == 0\n\n    def test_scan5_multi_output():\n        m = te.var(\"m\")\n        n = te.var(\"n\")\n        x1 = te.placeholder((m, n))\n        s1 = te.placeholder((m, n))\n        x2 = te.placeholder((m, n))\n        s2 = te.placeholder((m, n))\n        s1_init = te.compute((1, n), lambda _, i: x1[0, i])\n        s2_init = te.compute((1, n), lambda _, i: x2[0, i])\n        s1_update = te.compute((m, n), lambda t, i: s1[t - 1, i] + x1[t, i])\n        s2_update = te.compute((m, n), lambda t, i: x2[t, i] + s2[t - 1, i])\n        r0, r1 = tvm.te.scan([s1_init, s2_init], [s1_update, s2_update], [s1, s2])\n        body = tvm.te.schedule.ScanGetBody(r0.op)\n        fxpt = tvm.te.schedule.ScanFixPointAnalysis(r0.op)\n        assert fxpt[r1.op.spatial_axis_[0]].value == 1\n\n    test_scan0()\n    test_scan1()\n    test_scan3_not_exact_reach()\n    test_scan4_reach_other()\n    test_scan5_multi_output()\n\n\ndef test_create_read_graph():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j])\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3)\n\n    g = tvm.te.schedule.CreateReadGraph([A2.op])\n\n    assert g[A2.op][0] == A1\n    assert g[A1.op][0] == A\n    post_order = tvm.te.schedule.PostDFSOrder([A2.op], g)\n    assert post_order[0] == A.op\n    assert post_order[1] == A1.op\n\n\nif __name__ == \"__main__\":\n    test_scan()\n    test_create_read_graph()\n    test_scan_fix_point()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_lstm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_lstm_cell_inline():\n    num_step = 128\n    num_input = 256\n    num_hidden = 1152\n    batch_size = 4\n    # Global transition matrix\n    X = te.placeholder((num_step - 1, batch_size, num_input), name=\"X\")\n    Wi2h = te.placeholder((4, num_hidden, num_input), name=\"Wi2h\")\n    Wh2h = te.placeholder((4, num_hidden, num_hidden), name=\"Wh2h\")\n    # h: output hidden state, c: cell state.\n    s_state_h = te.placeholder((num_step, batch_size, num_hidden))\n    s_state_c = te.placeholder((num_step, batch_size, num_hidden))\n    s_init_c = te.compute((1, batch_size, num_hidden), lambda *i: 0.0, name=\"init_c\")\n    s_init_h = te.compute((1, batch_size, num_hidden), lambda *i: 0.0, name=\"init_h\")\n    # LSTM transition\n    k = te.reduce_axis((0, num_input), name=\"ki2h\")\n    s_i2h = te.compute(\n        (num_step, 4, batch_size, num_hidden),\n        lambda t, x, i, j: te.sum(X[t - 1, i, k] * Wi2h[x, j, k], axis=k),\n        name=\"s_i2h\",\n    )\n    k = te.reduce_axis((0, num_hidden), name=\"ki2h\")\n    s_h2h = te.compute(\n        (num_step, 4, batch_size, num_hidden),\n        lambda t, x, i, j: te.sum(s_state_h[t - 1, i, k] * Wh2h[x, j, k], axis=k),\n        name=\"s_h2h\",\n    )\n    # Gate rules\n    gates = te.compute(s_i2h.shape, lambda *i: s_i2h(*i) + s_h2h(*i), name=\"gates\")\n    gshape = (num_step, batch_size, num_hidden)\n    in_gate = te.compute(gshape, lambda t, i, j: te.sigmoid(gates[t, 0, i, j]), name=\"in_gate\")\n    in_transform = te.compute(\n        gshape, lambda t, i, j: te.tanh(gates[t, 1, i, j]), name=\"in_transform\"\n    )\n    forget_gate = te.compute(\n        gshape, lambda t, i, j: te.sigmoid(gates[t, 2, i, j]), name=\"forget_gate\"\n    )\n    out_gate = te.compute(gshape, lambda t, i, j: te.sigmoid(gates[t, 3, i, j]), name=\"out_gate\")\n    next_c = te.compute(\n        gshape,\n        lambda t, i, j: forget_gate[t, i, j] * s_state_c[t - 1, i, j]\n        + in_gate[t, i, j] * in_transform[t, i, j],\n        name=\"next_c\",\n    )\n    next_h = te.compute(\n        gshape, lambda t, i, j: out_gate[t, i, j] * te.tanh(next_c[t, i, j]), name=\"next_h\"\n    )\n    update_c = te.compute(gshape, lambda *i: next_c(*i), name=\"update_c\")\n    update_h = te.compute(gshape, lambda *i: next_h(*i), name=\"update_h\")\n    # schedule\n    scan_h, scan_c = tvm.te.scan(\n        [s_init_h, s_init_c],\n        [update_h, update_c],\n        [s_state_h, s_state_c],\n        inputs=[X],\n        name=\"lstm_scan\",\n    )\n    # schedule\n    s = te.create_schedule(scan_h.op)\n    # Inline gate computations\n    s[gates].compute_inline()\n    s[in_gate].compute_inline()\n    s[in_transform].compute_inline()\n    s[forget_gate].compute_inline()\n    s[out_gate].compute_inline()\n    # verify we can lower correctly\n    tvm.lower(s, [X, Wi2h, Wh2h, scan_h, scan_c])\n\n\nif __name__ == \"__main__\":\n    test_lstm_cell_inline()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\n\n\ndef test_const():\n    x = tvm.te.const(1, \"int32\")\n    assert x.dtype == \"int32\"\n    assert isinstance(x, tvm.tir.IntImm)\n\n\ndef test_schedule0():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    s = te.create_schedule(A1.op)\n\n    mod = schedule_to_module(s, [A, A1])\n    assert isinstance(mod[\"main\"], tvm.tir.PrimFunc)\n\n\ndef test_schedule1():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n\n    s = te.create_schedule(A1.op)\n    xo, xi = s[A1].split(A1.op.axis[0], 8)\n    s[A1].pragma(xo, \"auto_unroll_max_step\", 10)\n\n    mod = schedule_to_module(s, [A, A1])\n    assert isinstance(mod[\"main\"], tvm.tir.PrimFunc)\n\n\ndef test_schedule2():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    xo, xi = s[A2].split(A2.op.axis[0], 8)\n    s[A1].compute_at(s[A2], xo)\n\n    mod = schedule_to_module(s, [A, A2])\n    assert isinstance(mod[\"main\"], tvm.tir.PrimFunc)\n\n\ndef test_schedule_scan():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state = te.placeholder((m, n))\n    s_init = te.compute((1, n), lambda _, i: x[0, i])\n    s_update = te.compute((m, n), lambda t, i: s_state[t - 1, i] + x[t, i])\n    res = tvm.te.scan(s_init, s_update, s_state)\n\n    assert tuple(res.shape) == (m, n)\n    s = te.create_schedule(res.op)\n    s = s.normalize()\n    ir = tvm.lower(s, [s_state], simple_mode=True)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert bounds[res.op.scan_axis].min.value == 1\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_inline_multi_reduce():\n    def argmax_comp(x, y):\n        idx = tvm.tir.Select((x[1] >= y[1]), x[0], y[0])\n        val = tvm.tir.Select((x[1] >= y[1]), x[1], y[1])\n        return idx, val\n\n    def argmax_init(idx_typ, val_typ):\n        return tvm.tir.const(-1, idx_typ), tvm.te.min_value(val_typ)\n\n    argmax = te.comm_reducer(argmax_comp, argmax_init, name=\"argmax\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    val = te.placeholder((m, n), name=\"val\", dtype=\"float32\")\n    val1 = te.compute((m, n), lambda i, j: val[i, j] + 1, name=\"val1\")\n    val2 = te.compute((m, n), lambda i, j: te.exp(val1[i, j]), name=\"val2\")\n    k = te.reduce_axis((0, n), \"k\")\n    T_idx, T_val = te.compute((m,), lambda i: argmax((k.var, val2[i, k]), axis=k), name=\"T\")\n    s = te.create_schedule(T_idx.op)\n    s[val1].compute_inline()\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_auto_inline():\n    def elemwise():\n        m = te.var(\"m\")\n        n = te.var(\"n\")\n        A = te.placeholder((m, n), name=\"A\")\n        B = te.placeholder((m, n), name=\"B\")\n        C = te.placeholder((m, n), name=\"C\")\n        T1 = te.compute((m, n), lambda i, j: A(i, j) * B(i, j), name=\"T1\")\n        T2 = te.compute((m, n), lambda i, j: T1(i, j) + C(i, j), name=\"T2\")\n\n        return te.create_schedule(T2.op), T1\n\n    def broadcast():\n        m = te.var(\"m\")\n        n = te.var(\"n\")\n        A = te.placeholder((1,), name=\"A\")\n        B = te.placeholder((m, n), name=\"B\")\n        C = te.placeholder((m, n), name=\"C\")\n        T1 = te.compute((m, n), lambda i, j: A(0) * B(i, j), name=\"T1\", tag=\"broadcast\")\n        T2 = te.compute((m, n), lambda i, j: T1(i, j) + C(i, j), name=\"T2\")\n\n        return te.create_schedule(T2.op), T1\n\n    def injective():\n        m = te.var(\"m\")\n        n = te.var(\"n\")\n        A = te.placeholder((m,), name=\"A\")\n        B = te.placeholder((m, n), name=\"B\")\n        C = te.placeholder((m, n), name=\"C\")\n        T1 = te.compute((m, n), lambda i, j: A(i) * B(i, j), name=\"T1\")\n        T2 = te.compute((m, n), lambda i, j: T1(i, j) + C(i, j), name=\"T2\")\n\n        return te.create_schedule(T2.op), T1\n\n    def check_auto_inline(schedule_func, auto_inline_func):\n        s, T1 = schedule_func()\n        # before auto inline the attach type is AttachType.kGroupRoot\n        assert s[T1].attach_type == 1\n        auto_inline_func(s)\n        # after auto inline the attach type is AttachType.kInline\n        assert s[T1].attach_type == 2\n        s = s.normalize()\n        bounds = tvm.te.schedule.InferBound(s)\n        stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    check_auto_inline(elemwise, tvm.te.schedule.AutoInlineElemWise)\n    check_auto_inline(broadcast, tvm.te.schedule.AutoInlineBroadcast)\n    check_auto_inline(injective, tvm.te.schedule.AutoInlineInjective)\n\n\ndef test_schedule_const_bound():\n    n = 128\n    A = te.placeholder((n,), name=\"A\")\n    A1 = te.compute((n,), lambda i: A[i] + 1, name=\"A1\")\n    s = te.create_schedule(A1.op)\n    xo, xi = s[A1].split(A1.op.axis[0], 8)\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_inline_mixed():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    A1 = te.compute(A.shape, lambda *i: A(*i) + 1, name=\"A1\")\n    A2 = te.compute(A.shape, lambda *i: A1(*i) + 2, name=\"A2\")\n    C = te.compute((n,), lambda i: A2[i] + A1[i], name=\"C\")\n\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=8)\n    s[A1].compute_at(s[C], xo)\n    s[A2].compute_inline()\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    def check(x):\n        if isinstance(x, tvm.tir.Call):\n            assert x.func != A2\n\n    tvm.tir.stmt_functor.post_order_visit(s[C].op.body[0], check)\n\n\ndef test_scan_inline1():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state1 = te.placeholder((m, n))\n    s_state2 = te.placeholder((m, n))\n    s_init1 = te.compute((1, n), lambda _, i: x[0, i])\n    s_init2 = te.compute((1, n), lambda _, i: x[0, i])\n    s_x1 = te.compute((m, n), lambda t, i: s_state1[t - 1, i] + x[t, i], name=\"x1\")\n    s_x2 = te.compute((m, n), lambda t, i: s_state2[t - 1, i] + 1, name=\"x2\")\n    s_update1 = te.compute((m, n), lambda t, i: s_x1[t, i], \"u1\")\n    s_update2 = te.compute((m, n), lambda t, i: s_x2[t, i], \"u2\")\n    res1, res2 = tvm.te.scan([s_init1, s_init2], [s_update1, s_update2], [s_state1, s_state2])\n    s = te.create_schedule(res1.op)\n    s[s_x1].compute_inline()\n    stmt = tvm.lower(s, [x, res1, res2])\n\n\ndef test_scan_inline2():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    x = te.compute((m, n), lambda i, j: tvm.tir.const(1, \"float32\"), name=\"x\")\n    s_state1 = te.placeholder((m, n))\n    s_state2 = te.placeholder((m, n))\n    s_init1 = te.compute((1, n), lambda _, i: x[0, i])\n    s_init2 = te.compute((1, n), lambda _, i: x[0, i])\n    s_xx = te.compute((m, n), lambda t, i: s_state1[t - 1, i] + x[t, i], name=\"xx\")\n    s_x1 = te.compute((m, n), lambda t, i: s_xx[t, i] + 1, name=\"x1\")\n    s_x2 = te.compute((m, n), lambda t, i: s_xx[t, i] + s_state2[t - 1, 2], name=\"x2\")\n    s_update1 = te.compute((m, n), lambda t, i: s_x1[t, i], \"u1\")\n    s_update2 = te.compute((m, n), lambda t, i: s_x2[t, i], \"u2\")\n    res1, res2 = tvm.te.scan([s_init1, s_init2], [s_update1, s_update2], [s_state1, s_state2])\n    s = te.create_schedule(res1.op)\n    s[s_xx].compute_inline()\n    s[s_x1].compute_inline()\n    s[s_x2].compute_inline()\n    stmt = tvm.lower(s, [x, res1, res2])\n\n\ndef test_schedule_cache():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    B = te.placeholder((m, n), name=\"B\")\n    C = te.compute((m, n), lambda i, j: A(i, j) * B(i, j), name=\"C\")\n\n    s = te.create_schedule(C.op)\n    AA = s.cache_read(A, \"shared\", readers=[C])\n    CC = s.cache_write(C, \"shared\")\n    s[AA].compute_at(s[CC], CC.op.axis[0])\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_middle_cache():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    B = te.placeholder((m, n), name=\"B\")\n\n    C = te.compute((m, n), lambda i, j: A(i, j) * B(i, j), name=\"C\")\n    D = te.compute((m, n), lambda i, j: C(i, j), name=\"D\")\n\n    s = te.create_schedule(D.op)\n    AA = s.cache_read(A, \"local\", readers=[C])\n    BB = s.cache_read(B, \"local\", readers=[C])\n    CC = s.cache_read(C, \"local\", readers=[D])\n    DD = s.cache_write(D, \"local\")\n    # s[AA].compute_at(s[CC], CC.op.axis[0])\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_cache_relayout1():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    B = te.placeholder((m, n), name=\"B\")\n    C = te.compute((m, n), lambda i, j: A(i, j) * B(i, j), name=\"C\")\n\n    s = te.create_schedule(C.op)\n    s[C].reorder(C.op.axis[1], C.op.axis[0])\n    CC = s.cache_write(C, \"global\")\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_cache_relayout2():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m * 4, n), name=\"A\")\n    B = te.placeholder((m * 4, n), name=\"B\")\n    C = te.compute(A.shape, lambda i, j: A(i, j) * B(i, j), name=\"C\")\n    s = te.create_schedule(C.op)\n    x, y = C.op.axis\n    xo, xi = s[C].split(x, factor=4)\n    s[C].reorder(xo, y, xi)\n    CC = s.cache_write(C, \"global\")\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_cache_relayout3():\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m * 4, n), name=\"A\")\n    B = te.placeholder((m * 4, n), name=\"B\")\n    k = te.reduce_axis((0, n), \"k\")\n    C = te.compute((A.shape[0],), lambda i: te.sum(A(i, k) * B(i, k), axis=k), name=\"C\")\n    s = te.create_schedule(C.op)\n    x = C.op.axis[0]\n    xo, xi = s[C].split(x, factor=4)\n    CC = s.cache_write(C, \"global\")\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_cache_relayout4():\n    def _compute(*indice):\n        return A(*indice) + 1, B(*indice) / 2\n\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    A = te.placeholder((m * 4, n), name=\"A\")\n    B = te.placeholder((m * 4, n), name=\"B\")\n    C1, C2 = te.compute(A.shape, _compute, name=\"C\")\n    s = te.create_schedule([C1.op, C2.op])\n    C1_cache, C2_cache = s.cache_write([C1, C2], \"local\")\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef intrin_gemv(m, n):\n    w = te.placeholder((m, n), name=\"w\")\n    x = te.placeholder((n,), name=\"x\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    z = te.compute((m,), lambda i: te.sum(w[i, k] * x[k], axis=k), name=\"z\")\n    Wb = tvm.tir.decl_buffer(\n        w.shape, w.dtype, name=\"W\", offset_factor=16, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def intrin_func(ins, outs):\n        ww, xx = ins\n        zz = outs[0]\n        ww_ptr = ww.access_ptr(\"r\")\n        xx_ptr = xx.access_ptr(\"r\")\n        zz_ptr = zz.access_ptr(\"w\")\n        body = tvm.tir.call_packed(\"gemm\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        reset = tvm.tir.call_packed(\"fill_zero\", zz_ptr, n)\n        update = tvm.tir.call_packed(\"gemv_add\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        return body, reset, update\n\n    buffer_params = {\"data_alignment\": 16, \"offset_factor\": 16}\n    return te.decl_tensor_intrin(\n        z.op, intrin_func, binds={w: Wb}, default_buffer_params=buffer_params\n    )\n\n\ndef test_schedule_tensor_compute1():\n    # basic: split, reorder, tile\n    M, N, L = 2048, 1024, 512\n    factor, rfactor = 16, 16\n    A = te.placeholder((N // factor, L // rfactor, factor, rfactor), name=\"A\")\n    B = te.placeholder((M, L // rfactor, rfactor), name=\"B\")\n    k = te.reduce_axis((0, L // rfactor), name=\"k\")\n\n    gemv = intrin_gemv(factor, rfactor)\n    C = te.compute(\n        (N, M // factor, factor),\n        lambda i, j: gemv(A[i, k, 0:factor, 0:factor], B[j, k, 0:rfactor], reduce_axis=k),\n        name=\"C\",\n    )\n\n    s = te.create_schedule(C.op)\n    ai, aj, ax = s[C].op.axis\n    aio, aii = s[C].split(ai, 16)\n    s[C].reorder(aio, aj, aii)\n    aioo, ajo, aioi, aji = s[C].tile(aio, aj, 16, 4)\n\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef intrin_vadd(n, cache_read=False, cache_write=False):\n    scope_ubuf = \"local\"\n    dtype = \"float32\"\n    x = te.placeholder((n,), dtype=dtype, name=\"vx\")\n    y = te.placeholder((n,), dtype=dtype, name=\"vy\")\n    z = te.compute(x.shape, lambda i: x[i] + y[i], name=\"z\")\n    s = te.create_schedule(z.op)\n\n    def create_buffer(t):\n        return tvm.tir.decl_buffer(\n            t.shape, t.dtype, name=\"W\" + t.name, scope=scope_ubuf, offset_factor=16\n        )\n\n    binds = {}\n    if cache_read:\n        binds[x] = create_buffer(x)\n        binds[y] = create_buffer(y)\n    if cache_write:\n        binds[z] = create_buffer(z)\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        ib.emit(\n            tvm.tir.call_extern(\n                outs[0].dtype,\n                \"vadd\",\n                ins[0].access_ptr(\"r\"),\n                ins[1].access_ptr(\"r\"),\n                outs[0].access_ptr(\"wr\"),\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(\n        z.op, intrin_func, binds=binds, default_buffer_params={\"offset_factor\": 16}\n    )\n\n\ndef test_schedule_tensor_compute2():\n    # cache_read, cache_write\n    M = 1024\n    factor = 16\n    dtype = \"float32\"\n    scope_ubuf = \"local\"\n\n    A = te.placeholder((M // factor, factor), name=\"A\", dtype=dtype)\n    B = te.placeholder((M // factor, factor), name=\"B\", dtype=dtype)\n\n    vadd = intrin_vadd(factor, True, True)\n    C = te.compute((M // factor, factor), lambda i: vadd(A[i, 0:factor], B[i, 0:factor]), name=\"C\")\n\n    s = te.create_schedule(C.op)\n    AL = s.cache_read(A, scope_ubuf, C)\n    BL = s.cache_read(B, scope_ubuf, C)\n    CL = s.cache_write(C, scope_ubuf)\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_schedule_tensor_compute3():\n    # compute_at\n    M = 1024\n    factor = 16\n    dtype = \"float32\"\n    A = te.placeholder((M // factor, factor), name=\"A\", dtype=dtype)\n    B = te.placeholder((M // factor, factor), name=\"B\", dtype=dtype)\n    Bi = te.compute((M // factor, factor), lambda i, j: B[i, j] + 5, name=\"Bi\")\n\n    vadd = intrin_vadd(factor)\n    C = te.compute((M // factor, factor), lambda i: vadd(A[i, 0:factor], Bi[i, 0:factor]), name=\"C\")\n    s = te.create_schedule(C.op)\n    s[Bi].compute_at(s[C], C.op.axis[0])\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_loop_dep_reduce():\n    X = te.placeholder(shape=(10,), name=\"x\")\n\n    def f(n):\n        rv = te.reduce_axis((0, n))\n        return te.sum(X[rv], axis=rv)\n\n    Y = te.compute(X.shape, f, name=\"y\")\n    s = te.create_schedule([Y.op])\n    f = tvm.build(s, [X, Y])\n\n\ndef test_loop_dep_reduce_cache_write():\n    X = te.placeholder(shape=(10,), name=\"x\")\n\n    def f(n):\n        rv = te.reduce_axis((0, n))\n        init = lambda dtype: tvm.tir.Select(n > 1, tvm.tir.const(0, dtype), n.astype(dtype))\n        sum = te.comm_reducer(lambda x, y: tvm.te.max(x + y, n.astype(\"float32\")), init, name=\"sum\")\n        return sum(X[rv], axis=rv)\n\n    Y = te.compute(X.shape, f, name=\"y\")\n    s = te.create_schedule([Y.op])\n    s.cache_write(Y, \"local\")\n    f = tvm.build(s, [X, Y])\n\n\ndef test_reduction_and_dummy_fuse_split():\n    n = 10\n    X = te.placeholder(shape=(n,), dtype=\"int32\", name=\"X\")\n    k = te.reduce_axis((0, n))\n    Y = te.compute((), lambda: te.sum(X[k], k), name=\"Y\")\n    s = te.create_schedule([Y.op])\n    ax = s[Y.op].fuse(*Y.op.axis)\n    axo, axi = s[Y.op].split(ax, nparts=20)\n    f = tvm.build(s, [Y, X])\n\n    args = [tvm.nd.empty((), \"int32\")] + [tvm.nd.array(np.ones((n,), dtype=\"int32\"))]\n    f(*args)\n    assert args[0].numpy() == n\n\n    n = 10\n    X = te.placeholder(shape=(n,), dtype=\"int32\", name=\"X\")\n    k = te.reduce_axis((0, n))\n    Y = te.compute((n,), lambda i: te.sum(X[k], k), name=\"Y\")\n    s = te.create_schedule([Y.op])\n    ax = s[Y.op].fuse(*(list(Y.op.axis) + list(Y.op.reduce_axis)))\n    f = tvm.build(s, [Y, X])\n\n    args = [tvm.nd.array(np.ones((n,), dtype=\"int32\"))] + [\n        tvm.nd.array(np.ones((n,), dtype=\"int32\"))\n    ]\n    f(*args)\n    assert np.all(args[0].numpy() == n)\n\n\ndef test_schedule_compute_inline():\n    shape = [10, 1024]\n    A = te.placeholder(shape, name=\"A\")\n    B = te.placeholder(shape, name=\"B\")\n    C = te.compute(shape, lambda *index: A(*index) + B(*index), name=\"C\")\n\n    def _compute(*index):\n        return C(*index), C(*index) * B(*index)\n\n    F, E = te.compute(shape, _compute, name=\"F\")\n\n    s = te.create_schedule([F.op, E.op])\n    AL = s.cache_read(A, \"local\", [C])\n    BL = s.cache_read(B, \"local\", [C, E])\n    CL = s.cache_write(C, \"local\")\n    FL, EL = s.cache_write([F, E], \"local\")\n    s[C].compute_inline()\n\n    s = s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n\ndef test_local_stage_predicate():\n    m = 1\n    n = 3\n    p = 2\n    A = tvm.te.placeholder((m, n, p), name=\"A\")\n    B = tvm.te.compute((m, n, p), lambda bi, bj, bk: A[bi, bj, bk], name=\"B\")\n    C = tvm.te.compute((m, n, p), lambda ci, cj, ck: B[ci, cj, ck], name=\"C\")\n    by = tvm.te.thread_axis(\"blockIdx.y\")\n    tx = tvm.te.thread_axis(\"threadIdx.x\")\n    vx = tvm.te.thread_axis(\"vthread\")\n\n    def schedule(thread_tag, mem_scope):\n        s = tvm.te.create_schedule(C.op)\n        s[B].compute_at(s[C], s[C].op.axis[0])\n        s[B].set_scope(mem_scope)\n        bno, bni = s[B].split(s[B].op.axis[1], n)\n        bx = tvm.te.thread_axis(\"blockIdx.x\")\n        s[C].bind(s[C].op.axis[0], bx)\n        s[C].bind(s[C].op.axis[1], thread_tag)\n        s[B].bind(bni, thread_tag)\n        return s\n\n    def collect_visit(stmt, f):\n        ret = []\n        tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x)))\n        return ret\n\n    # local vs. threadIdx\n    s = schedule(tx, \"local\")\n    lowered_body = tvm.lower(s, [A, C])[\"main\"].body\n    assert not any(collect_visit(lowered_body, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n    # local vs. vthread\n    s = schedule(vx, \"local\")\n    lowered_body = tvm.lower(s, [A, C])[\"main\"].body\n    assert not any(collect_visit(lowered_body, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n    # shared vs. blockIdx\n    s = schedule(by, \"shared\")\n    lowered_body = tvm.lower(s, [A, C])[\"main\"].body\n    assert not any(collect_visit(lowered_body, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_local_stage_predicate2():\n    A = tvm.te.placeholder((128,), name=\"A\")\n    B = tvm.te.compute((128,), lambda bi: A[bi] + 1, name=\"B\")\n    C = tvm.te.compute((128,), lambda ci: B[ci] + 2, name=\"C\")\n    s = tvm.te.create_schedule(C.op)\n    AA = s.cache_read(A, \"local\", [B])\n    s[B].set_scope(\"shared\")\n    block_x = tvm.te.thread_axis(\"blockIdx.x\")\n    thread_x = tvm.te.thread_axis((0, 32), \"threadIdx.x\")\n    oc, ic = s[C].split(s[C].op.axis[0], factor=64)\n    ooc, ioc = s[C].split(oc, factor=2)\n    oic, iic = s[C].split(ic, factor=32)\n    s[C].bind(ooc, block_x)\n    s[C].bind(iic, thread_x)\n    s[B].compute_at(s[C], ioc)\n    ob, ib = s[B].split(s[B].op.axis[0], factor=32)\n    s[B].bind(ib, thread_x)\n    s[AA].compute_root()\n    s[AA].compute_at(s[C], ooc)\n    oaa, iaa = s[AA].split(s[AA].op.axis[0], factor=32)\n    s[AA].bind(iaa, thread_x)\n    lowered_body = tvm.lower(s, [A, C])[\"main\"].body\n\n    def collect_visit(stmt, f):\n        ret = []\n        tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x)))\n        return ret\n\n    def visit_stmt(op):\n        if isinstance(op, tvm.tir.Allocate):\n            return op.extents[0].value == 97\n        return False\n\n    assert not any(collect_visit(lowered_body, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n    assert any(collect_visit(lowered_body, visit_stmt))\n\n\nif __name__ == \"__main__\":\n    test_loop_dep_reduce()\n    test_loop_dep_reduce_cache_write()\n    test_schedule_middle_cache()\n    test_inline_multi_reduce()\n    test_schedule_cache_relayout4()\n    test_schedule_cache_relayout3()\n    test_schedule_cache_relayout2()\n    test_schedule_cache_relayout1()\n    test_schedule_const_bound()\n    test_scan_inline1()\n    test_scan_inline2()\n    test_inline_mixed()\n    test_auto_inline()\n    test_schedule_scan()\n    test_schedule0()\n    test_schedule1()\n    test_schedule2()\n    test_schedule_cache()\n    test_schedule_tensor_compute1()\n    test_schedule_tensor_compute2()\n    test_schedule_tensor_compute3()\n    test_reduction_and_dummy_fuse_split()\n    test_schedule_compute_inline()\n    test_local_stage_predicate()\n    test_local_stage_predicate2()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_postproc_rewrite_for_tensor_core.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# 'License'); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport numpy as np\nimport tvm.testing\n\n\ndef tensor_core_matmul(warp_tile_m=16, m=64, n=32, l=96):\n    A = te.placeholder((n, l), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((l, m), name=\"B\", dtype=\"float16\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute(\n        (n, m), lambda i, j: te.sum(A[i, k].astype(\"float32\") * B[k, j].astype(\"float32\"), axis=k)\n    )\n    s = te.create_schedule(C.op)\n    y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    AA = s.cache_read(A, \"shared\", [C])\n    AL = s.cache_read(AA, \"local\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n    BL = s.cache_read(BB, \"local\", [C])\n    CL = s.cache_write(C, \"local\")\n\n    bx = 4\n    by = 32\n    step_k = 8\n    v = 4\n    TX = 8\n    TY = 1\n    tile_x = bx * TX\n    tile_y = by * TY\n    WX = min(warp_tile_m, tile_x)\n    tile_k = 16\n    vthread = 1\n\n    yo, ty = s[C].split(y, tile_y * vthread)\n    vy, ty = s[C].split(ty, tile_y)\n    ty, yi = s[C].split(ty, TY)\n\n    xo, xi = s[C].split(x, tile_x)\n    tz, xi = s[C].split(xi, WX)\n    tx, xi = s[C].split(xi, TX)\n    ko, ki = s[CL].split(k, step_k * tile_k)\n    kl, ki = s[CL].split(ki, tile_k)\n\n    s[C].reorder(yo, xo, tz, ty, tx, yi, xi)\n    s[C].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].bind(vy, te.thread_axis((0, vthread), \"vthread\", name=\"vy\"))\n    s[CL].compute_at(s[C], tx)\n    yo, xo = CL.op.axis\n    s[CL].reorder(ko, kl, ki, yo, xo)\n\n    s[AA].compute_at(s[CL], ko)\n    xo, xi = s[AA].split(s[AA].op.axis[1], factor=bx * v)\n    tz, tx = s[AA].split(xi, factor=(WX // TX) * v)\n    tx, vec = s[AA].split(tx, factor=v)\n    fused = s[AA].fuse(s[AA].op.axis[0], xo)\n    _, ty = s[AA].split(fused, factor=by)\n    s[AA].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[AA].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[AA].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[AA].vectorize(vec)\n\n    s[BB].compute_at(s[CL], ko)\n    xo, xi = s[BB].split(s[BB].op.axis[1], factor=bx * v)\n    tz, tx = s[BB].split(xi, factor=(WX // TX) * v)\n    tx, vec = s[BB].split(tx, factor=v)\n    fused = s[BB].fuse(s[BB].op.axis[0], xo)\n    _, ty = s[BB].split(fused, factor=by)\n    s[BB].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[BB].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[BB].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[BB].vectorize(vec)\n\n    s[AL].compute_at(s[CL], kl)\n    s[BL].compute_at(s[CL], kl)\n\n    s[CL].pragma(ko, \"tensor_core\")\n\n    func = tvm.build(s, [A, B, C], \"cuda\")\n\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=(n, l)).astype(A.dtype)\n    b_np = np.random.uniform(size=(l, m)).astype(B.dtype)\n    c_np = np.zeros((n, m), dtype=np.float32)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), dev)\n    func(a, b, c)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=3)\n    print(\"gemm m=%d n=%d k=%d: %f ms\" % (m, n, l, evaluator(a, b, c).mean * 1e3))\n\n    c_np = np.dot(a_np, b_np)\n    np.testing.assert_allclose(c_np, c.numpy(), rtol=1e-3)\n\n\ndef tensor_core_batch_matmul(warp_tile_m=16, m=64, n=32, l=96, batch=2):\n    A = te.placeholder((batch, n, l), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((batch, l, m), name=\"B\", dtype=\"float16\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute(\n        (batch, n, m), lambda b, i, j: te.sum((A[b, i, k] * B[b, k, j]).astype(\"float32\"), axis=k)\n    )\n    s = te.create_schedule(C.op)\n    z, y, x = s[C].op.axis\n    k = s[C].op.reduce_axis[0]\n\n    AA = s.cache_read(A, \"shared\", [C])\n    AL = s.cache_read(AA, \"local\", [C])\n    BB = s.cache_read(B, \"shared\", [C])\n    BL = s.cache_read(BB, \"local\", [C])\n    CL = s.cache_write(C, \"local\")\n\n    bx = 2\n    by = 32\n    step_k = 8\n    v = 4\n    TX = 8\n    TY = 1\n    tile_x = bx * TX\n    tile_y = by * TY\n    WX = min(warp_tile_m, tile_x)\n    tile_k = 16\n    vthread = 1\n\n    yo, ty = s[C].split(y, tile_y * vthread)\n    vy, ty = s[C].split(ty, tile_y)\n    ty, yi = s[C].split(ty, TY)\n\n    xo, xi = s[C].split(x, tile_x)\n    tz, xi = s[C].split(xi, WX)\n    tx, xi = s[C].split(xi, TX)\n    ko, ki = s[CL].split(k, step_k * tile_k)\n    kl, ki = s[CL].split(ki, tile_k)\n\n    s[C].reorder(z, yo, xo, tz, ty, tx, yi, xi)\n    s[C].bind(z, te.thread_axis(\"blockIdx.z\"))\n    s[C].bind(yo, te.thread_axis(\"blockIdx.y\"))\n    s[C].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[C].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].bind(vy, te.thread_axis((0, vthread), \"vthread\", name=\"vy\"))\n    s[CL].compute_at(s[C], tx)\n    zo, yo, xo = CL.op.axis\n    s[CL].reorder(ko, kl, ki, zo, yo, xo)\n\n    s[AA].compute_at(s[CL], ko)\n    xo, xi = s[AA].split(s[AA].op.axis[2], factor=bx * v)\n    tz, tx = s[AA].split(xi, factor=(WX // TX) * v)\n    tx, vec = s[AA].split(tx, factor=v)\n    fused = s[AA].fuse(s[AA].op.axis[1], xo)\n    _, ty = s[AA].split(fused, factor=by)\n    s[AA].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[AA].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[AA].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[AA].vectorize(vec)\n\n    s[BB].compute_at(s[CL], ko)\n    xo, xi = s[BB].split(s[BB].op.axis[2], factor=bx * v)\n    tz, tx = s[BB].split(xi, factor=(WX // TX) * v)\n    tx, vec = s[BB].split(tx, factor=v)\n    fused = s[BB].fuse(s[BB].op.axis[1], xo)\n    _, ty = s[BB].split(fused, factor=by)\n    s[BB].bind(ty, te.thread_axis(\"threadIdx.y\"))\n    s[BB].bind(tz, te.thread_axis(\"threadIdx.z\"))\n    s[BB].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[BB].vectorize(vec)\n\n    s[AL].compute_at(s[CL], kl)\n    s[BL].compute_at(s[CL], kl)\n\n    s[CL].pragma(ko, \"tensor_core\")\n\n    func = tvm.build(s, [A, B, C], \"cuda\")\n\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=(batch, n, l)).astype(A.dtype)\n    b_np = np.random.uniform(size=(batch, l, m)).astype(B.dtype)\n    c_np = np.zeros((batch, n, m), dtype=np.float32)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((batch, n, m), dtype=C.dtype), dev)\n    func(a, b, c)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=3)\n    print(\n        \"batch gemm m=%d n=%d k=%d batch=%d: %f ms\"\n        % (m, n, l, batch, evaluator(a, b, c).mean * 1e3)\n    )\n\n    for bs in range(batch):\n        c_np[bs, :, :] = np.dot(a_np[bs, :, :], b_np[bs, :, :])\n    np.testing.assert_allclose(c_np, c.numpy(), rtol=1e-3)\n\n\n@tvm.testing.requires_tensorcore\ndef test_tensor_core_matmul():\n    tensor_core_matmul(16)  # test with warp_tile 16x16x16\n    tensor_core_matmul(8)  # test with warp_tile 8x32x16\n    tensor_core_matmul(32)  # test with warp_tile 32x8x16\n\n\n@tvm.testing.requires_tensorcore\ndef test_tensor_core_batch_matmul():\n    tensor_core_batch_matmul()\n\n\nif __name__ == \"__main__\":\n    test_tensor_core_matmul()\n    test_tensor_core_batch_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_tensor_core.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# 'License'); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.topi.testing import conv2d_nhwc_python\nimport tvm.testing\n\nVERIFY = True\n\n\ndef intrin_wmma_load_matrix(shape, scope):\n    n, m, l = shape\n    if scope == \"wmma.matrix_a\":\n        row, col = n, l\n    elif scope == \"wmma.matrix_b\":\n        row, col = l, m\n    A = te.placeholder((row, col), name=\"A\", dtype=\"float16\")\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"shared\", data_alignment=32, offset_factor=row * col\n    )\n    C = te.compute((row, col), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(\n        C.shape, C.dtype, scope=scope, data_alignment=32, offset_factor=row * col\n    )\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_load_matrix_sync\",\n                BC.data,\n                n,\n                m,\n                l,\n                BC.elem_offset // (row * col),\n                BA.access_ptr(\"r\"),\n                col,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_gemm(shape):\n    n, m, l = shape\n    A = te.placeholder((n, l), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((l, m), name=\"B\", dtype=\"float16\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute(\n        (n, m),\n        lambda ii, jj: te.sum(A[ii, k].astype(\"float\") * B[k, jj].astype(\"float\"), axis=k),\n        name=\"C\",\n    )\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, name=\"BA\", scope=\"wmma.matrix_a\", data_alignment=32, offset_factor=n * l\n    )\n    BB = tvm.tir.decl_buffer(\n        B.shape, B.dtype, name=\"BB\", scope=\"wmma.matrix_b\", data_alignment=32, offset_factor=l * m\n    )\n    BC = tvm.tir.decl_buffer(\n        C.shape,\n        C.dtype,\n        name=\"BC\",\n        scope=\"wmma.accumulator\",\n        data_alignment=32,\n        offset_factor=n * m,\n    )\n\n    def intrin_func(ins, outs):\n        BA, BB = ins\n        (BC,) = outs\n\n        def init():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_fill_fragment\",\n                    BC.data,\n                    n,\n                    m,\n                    l,\n                    BC.elem_offset // (n * m),\n                    0.0,\n                )\n            )\n            return ib.get()\n\n        def update():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_mma_sync\",\n                    BC.data,\n                    BC.elem_offset // (n * m),\n                    BA.data,\n                    BA.elem_offset // (n * l),\n                    BB.data,\n                    BB.elem_offset // (l * m),\n                    BC.data,\n                    BC.elem_offset // (n * m),\n                )\n            )\n            return ib.get()\n\n        return update(), init(), update()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, B: BB, C: BC})\n\n\ndef intrin_wmma_store_matrix(shape):\n    n, m, l = shape\n    A = te.placeholder((n, m), name=\"A\", dtype=\"float32\")\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"wmma.accumulator\", data_alignment=32, offset_factor=n * m\n    )\n    C = te.compute((n, m), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(\n        C.shape, C.dtype, scope=\"global\", data_alignment=32, offset_factor=n * m\n    )\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_store_matrix_sync\",\n                BA.data,\n                n,\n                m,\n                l,\n                BA.elem_offset // (n * m),\n                BC.access_ptr(\"w\"),\n                m,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\n@tvm.testing.requires_tensorcore\ndef test_tensor_core_batch_matmal():\n    batch_size = 4\n    n = 512\n    m, l = n, n\n    assert n % 32 == 0\n    assert m % 8 == 0\n    assert l % 16 == 0\n    nn, mm, ll = n // 32, m // 8, l // 16\n    A = te.placeholder((batch_size, nn, ll, 32, 16), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((batch_size, ll, mm, 16, 8), name=\"B\", dtype=\"float16\")\n    k1 = te.reduce_axis((0, ll), name=\"k1\")\n    k2 = te.reduce_axis((0, 16), name=\"k2\")\n    C = te.compute(\n        (batch_size, nn, mm, 32, 8),\n        lambda b, i, j, ii, jj: te.sum(\n            A[b, i, k1, ii, k2].astype(\"float\") * B[b, k1, j, k2, jj].astype(\"float\"), axis=[k1, k2]\n        ),\n        name=\"Fragment_C\",\n    )\n    s = te.create_schedule(C.op)\n\n    warp_size = 32\n    kernel_size = 16\n    block_row_warps = 2\n    block_col_warps = 4\n    warp_row_tiles = 4\n    warp_col_tiles = 2\n    chunk = 4\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    AS = s.cache_read(A, \"shared\", [C])\n    BS = s.cache_read(B, \"shared\", [C])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [C])\n    BF = s.cache_read(BS, \"wmma.matrix_b\", [C])\n    CF = s.cache_write(C, \"wmma.accumulator\")\n\n    b, i, j, kernel_i, kernel_j = s[C].op.axis\n    i, ii = s[C].split(i, factor=warp_row_tiles)\n    block_i, i = s[C].split(i, factor=block_row_warps)\n    j, jj = s[C].split(j, factor=warp_col_tiles)\n    block_j, j = s[C].split(j, factor=block_col_warps)\n    s[C].reorder(block_i, block_j, i, j, ii, jj, kernel_i, kernel_j)\n    s[C].bind(b, block_z)\n    s[C].bind(block_i, block_x)\n    s[C].bind(block_j, block_y)\n    s[C].bind(i, thread_y)\n    s[C].bind(j, thread_z)\n\n    s[CF].compute_at(s[C], j)\n    b, warp_i, warp_j, _i, _j = s[CF].op.axis\n    k, _k = CF.op.reduce_axis\n    ko, ki = s[CF].split(k, factor=chunk)\n    s[CF].reorder(ko, ki, warp_i, warp_j, _i, _j, _k)\n\n    s[AF].compute_at(s[CF], ki)\n    s[BF].compute_at(s[CF], ki)\n\n    s[AS].compute_at(s[CF], ko)\n    b, xo, yo, xi, yi = AS.op.axis\n    tx, xo = s[AS].split(xo, nparts=block_row_warps)\n    ty, yo = s[AS].split(yo, nparts=block_col_warps)\n    t = s[AS].fuse(xi, yi)\n    to, ti = s[AS].split(t, nparts=warp_size)\n    s[AS].bind(tx, thread_y)\n    s[AS].bind(ty, thread_z)\n    s[AS].bind(to, thread_x)\n\n    s[BS].compute_at(s[CF], ko)\n    b, xo, yo, xi, yi = BS.op.axis\n    tx, xo = s[BS].split(xo, nparts=block_row_warps)\n    ty, yo = s[BS].split(yo, nparts=block_col_warps)\n    t = s[BS].fuse(xi, yi)\n    to, ti = s[BS].split(t, nparts=warp_size)\n    s[BS].bind(tx, thread_y)\n    s[BS].bind(ty, thread_z)\n    s[BS].bind(to, thread_x)\n\n    s[AF].tensorize(AF.op.axis[-2], intrin_wmma_load_matrix((32, 8, 16), \"wmma.matrix_a\"))\n    s[BF].tensorize(BF.op.axis[-2], intrin_wmma_load_matrix((32, 8, 16), \"wmma.matrix_b\"))\n    s[C].tensorize(kernel_i, intrin_wmma_store_matrix((32, 8, 16)))\n    s[CF].tensorize(_i, intrin_wmma_gemm((32, 8, 16)))\n\n    func = tvm.build(s, [A, B, C], \"cuda\")\n\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=(batch_size, nn, ll, 32, 16)).astype(A.dtype)\n    b_np = np.random.uniform(size=(batch_size, ll, mm, 16, 8)).astype(B.dtype)\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((batch_size, nn, mm, 32, 8), dtype=C.dtype), dev)\n    func(a, b, c)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=3)\n    print(\"gemm with tensor core: %f ms\" % (evaluator(a, b, c).mean * 1e3))\n\n    if VERIFY:\n        func(a, b, c)\n        a_np = a_np.transpose((0, 1, 3, 2, 4)).reshape(batch_size, n, n)\n        b_np = b_np.transpose((0, 1, 3, 2, 4)).reshape(batch_size, n, n)\n        c_np = c.numpy().transpose((0, 1, 3, 2, 4)).reshape(batch_size, n, n)\n        np.testing.assert_allclose(\n            c_np, np.matmul(a_np.astype(C.dtype), b_np.astype(C.dtype)), rtol=1e-4, atol=1e-4\n        )\n\n\n@tvm.testing.requires_tensorcore\ndef test_tensor_core_batch_conv():\n    # The sizes of inputs and filters\n    batch_size = 32\n    height = 14\n    width = 14\n    in_channels = 32\n    out_channels = 64\n    kernel_h = 3\n    kernel_w = 3\n    pad_h = 1\n    pad_w = 1\n    stride_h = 1\n    stride_w = 1\n    block_size = 16\n\n    block_row_warps = 2\n    block_col_warps = 4\n    warp_row_tiles = 4\n    warp_col_tiles = 2\n    warp_size = 32\n    chunk = 2\n\n    # Input feature map: (N, H, W, IC, n, ic)\n    data_shape = (\n        batch_size // block_size,\n        height,\n        width,\n        in_channels // block_size,\n        block_size,\n        block_size,\n    )\n    # Kernel: (H, W, IC, OC, ic, oc)\n    kernel_shape = (\n        kernel_h,\n        kernel_w,\n        in_channels // block_size,\n        out_channels // block_size,\n        block_size,\n        block_size,\n    )\n\n    # Output feature map: (N, H, W, OC, n, oc)\n    output_shape = (\n        batch_size // block_size,\n        height,\n        width,\n        out_channels // block_size,\n        block_size,\n        block_size,\n    )\n\n    assert batch_size % block_size == 0\n    assert in_channels % block_size == 0\n    assert out_channels % block_size == 0\n\n    kh = te.reduce_axis((0, kernel_h), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_w), name=\"kw\")\n    ic = te.reduce_axis((0, in_channels // block_size), name=\"ic\")\n    ii = te.reduce_axis((0, block_size), name=\"ii\")\n\n    # Algorithm\n    A = te.placeholder(data_shape, name=\"A\", dtype=\"float16\")\n    W = te.placeholder(kernel_shape, name=\"W\", dtype=\"float16\")\n    Apad = te.compute(\n        (\n            batch_size // block_size,\n            height + 2 * pad_h,\n            width + 2 * pad_w,\n            in_channels // block_size,\n            block_size,\n            block_size,\n        ),\n        lambda n, h, w, i, nn, ii: tvm.tir.if_then_else(\n            tvm.tir.all(h >= pad_h, h - pad_h < height, w >= pad_w, w - pad_w < width),\n            A[n, h - pad_h, w - pad_w, i, nn, ii],\n            tvm.tir.const(0.0, \"float16\"),\n        ),\n        name=\"Apad\",\n    )\n    Conv = te.compute(\n        output_shape,\n        lambda n, h, w, o, nn, oo: te.sum(\n            Apad[n, h * stride_h + kh, w * stride_w + kw, ic, nn, ii].astype(\"float32\")\n            * W[kh, kw, ic, o, ii, oo].astype(\"float32\"),\n            axis=[ic, kh, kw, ii],\n        ),\n        name=\"Conv\",\n    )\n\n    s = te.create_schedule(Conv.op)\n    s[Apad].compute_inline()\n\n    AS = s.cache_read(Apad, \"shared\", [Conv])\n    WS = s.cache_read(W, \"shared\", [Conv])\n    AF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\n    WF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\n    ConvF = s.cache_write(Conv, \"wmma.accumulator\")\n\n    block_x = te.thread_axis(\"blockIdx.x\")\n    block_y = te.thread_axis(\"blockIdx.y\")\n    block_z = te.thread_axis(\"blockIdx.z\")\n    thread_x = te.thread_axis(\"threadIdx.x\")\n    thread_y = te.thread_axis(\"threadIdx.y\")\n    thread_z = te.thread_axis(\"threadIdx.z\")\n\n    nc, hc, wc, oc, nnc, ooc = Conv.op.axis\n    block_k = s[Conv].fuse(hc, wc)\n    s[Conv].bind(block_k, block_z)\n    nc, nci = s[Conv].split(nc, factor=warp_row_tiles)\n    block_i, nc = s[Conv].split(nc, factor=block_row_warps)\n    oc, oci = s[Conv].split(oc, factor=warp_col_tiles)\n    block_j, oc = s[Conv].split(oc, factor=block_col_warps)\n    s[Conv].reorder(block_k, block_i, block_j, nc, oc, nci, oci, nnc, ooc)\n    s[Conv].bind(block_i, block_x)\n    s[Conv].bind(block_j, block_y)\n    s[Conv].bind(nc, thread_y)\n    s[Conv].bind(oc, thread_z)\n\n    s[ConvF].compute_at(s[Conv], oc)\n    n, h, w, o, nnf, oof = ConvF.op.axis\n    ko, ki = s[ConvF].split(ic, factor=chunk)\n    s[ConvF].reorder(ko, kh, ki, kw, n, o, nnf, oof, ii)\n\n    s[AF].compute_at(s[ConvF], kw)\n    s[WF].compute_at(s[ConvF], kw)\n\n    s[WS].compute_at(s[ConvF], kh)\n    s[AS].compute_at(s[ConvF], kh)\n\n    n, h, w, i, nn, ii = AS.op.axis\n    tx, xo = s[AS].split(n, nparts=block_row_warps)\n    ty, yo = s[AS].split(xo, nparts=block_col_warps)\n    t = s[AS].fuse(nn, ii)\n    to, ti = s[AS].split(t, factor=warp_size)\n    s[AS].bind(tx, thread_y)\n    s[AS].bind(ty, thread_z)\n    s[AS].bind(ti, thread_x)\n\n    kh, kw, ic, o, ii, oo = WS.op.axis\n    tx, xo = s[WS].split(o, nparts=block_row_warps)\n    ty, yo = s[WS].split(xo, nparts=block_col_warps)\n    t = s[WS].fuse(ii, oo)\n    to, ti = s[WS].split(t, nparts=warp_size)\n    s[WS].bind(tx, thread_y)\n    s[WS].bind(ty, thread_z)\n    s[WS].bind(to, thread_x)\n    s[WS].vectorize(ti)\n\n    s[AF].tensorize(AF.op.axis[-2], intrin_wmma_load_matrix((16, 16, 16), \"wmma.matrix_a\"))\n    s[WF].tensorize(WF.op.axis[-2], intrin_wmma_load_matrix((16, 16, 16), \"wmma.matrix_b\"))\n    s[Conv].tensorize(nnc, intrin_wmma_store_matrix((16, 16, 16)))\n    s[ConvF].tensorize(nnf, intrin_wmma_gemm((16, 16, 16)))\n\n    func = tvm.build(s, [A, W, Conv], \"cuda\")\n\n    dev = tvm.cuda(0)\n    a_np = np.random.uniform(size=data_shape).astype(A.dtype)\n    w_np = np.random.uniform(size=kernel_shape).astype(W.dtype)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    c = tvm.nd.array(np.zeros(output_shape, dtype=Conv.dtype), dev)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=3)\n    print(\"conv2d with tensor core: %f ms\" % (evaluator(a, w, c).mean * 1e3))\n\n    if VERIFY:\n        func(a, w, c)\n        a_np = a_np.transpose(0, 4, 1, 2, 3, 5).reshape(batch_size, height, width, in_channels)\n        w_np = w_np.transpose(0, 1, 2, 4, 3, 5).reshape(\n            kernel_h, kernel_w, in_channels, out_channels\n        )\n        c_np = (\n            c.numpy().transpose((0, 4, 1, 2, 3, 5)).reshape(batch_size, height, width, out_channels)\n        )\n        c_std = conv2d_nhwc_python(\n            a_np.astype(Conv.dtype), w_np.astype(Conv.dtype), (stride_h, stride_w), (pad_h, pad_w)\n        ).astype(Conv.dtype)\n        np.testing.assert_allclose(c_np, c_std, rtol=1e-4, atol=1e-4)\n\n\nif __name__ == \"__main__\":\n    test_tensor_core_batch_matmal()\n    test_tensor_core_batch_conv()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_schedule_tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef intrin_vadd(xo, m, n):\n    x = te.placeholder((n,), name=\"vx\")\n    y = te.placeholder((n,), name=\"vy\")\n    if m % n == 0:\n        body = lambda i: x[i] + y[i]\n    else:\n        body = lambda i: tvm.tir.Select(\n            xo * n + i < m, x[i] + y[i], tvm.tir.const(0, dtype=x.dtype)\n        )\n    z = te.compute(x.shape, body, name=\"z\")\n\n    def intrin_func(ins, outs):\n        xx, yy = ins\n        zz = outs[0]\n        # special handle needed to tackle tail loop part when m % n != 0\n        # here is tvm.min(n, m - xo * n)\n        return tvm.tir.call_packed(\"vadd\", xx, yy, zz)\n\n    buffer_params = {\"offset_factor\": 16}\n    return te.decl_tensor_intrin(z.op, intrin_func, default_buffer_params=buffer_params)\n\n\ndef intrin_gemv(m, n):\n    w = te.placeholder((m, n), name=\"w\")\n    x = te.placeholder((n,), name=\"x\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    z = te.compute((m,), lambda i: te.sum(w[i, k] * x[k], axis=k), name=\"z\")\n    Wb = tvm.tir.decl_buffer(\n        w.shape, w.dtype, name=\"W\", offset_factor=16, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def intrin_func(ins, outs):\n        ww, xx = ins\n        zz = outs[0]\n        ww_ptr = ww.access_ptr(\"r\")\n        xx_ptr = xx.access_ptr(\"r\")\n        zz_ptr = zz.access_ptr(\"w\")\n        body = tvm.tir.call_packed(\"gemv\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        reset = tvm.tir.call_packed(\"fill_zero\", zz_ptr, n)\n        update = tvm.tir.call_packed(\"gemv_add\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        return body, reset, update\n\n    buffer_params = {\"offset_factor\": 16, \"data_alignment\": 16}\n    return te.decl_tensor_intrin(\n        z.op, intrin_func, binds={w: Wb}, default_buffer_params=buffer_params\n    )\n\n\ndef intrin_gemv_no_reset(m, n):\n    w = te.placeholder((m, n), name=\"w\")\n    x = te.placeholder((n,), name=\"x\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    z = te.compute((m,), lambda i: te.sum(w[i, k] * x[k], axis=k), name=\"z\")\n    Wb = tvm.tir.decl_buffer(\n        w.shape, w.dtype, name=\"W\", offset_factor=16, strides=[te.var(\"ldw\"), 1]\n    )\n\n    def intrin_func(ins, outs):\n        ww, xx = ins\n        zz = outs[0]\n        ww_ptr = ww.access_ptr(\"r\")\n        xx_ptr = xx.access_ptr(\"r\")\n        zz_ptr = zz.access_ptr(\"w\")\n        body = tvm.tir.call_packed(\"gemv\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        update = tvm.tir.call_packed(\"gemv_add\", ww_ptr, xx_ptr, zz_ptr, n, ww.strides[0])\n        return body, None, update\n\n    buffer_params = {\"offset_factor\": 16, \"data_alignment\": 16}\n    return te.decl_tensor_intrin(\n        z.op, intrin_func, binds={w: Wb}, default_buffer_params=buffer_params\n    )\n\n\ndef test_tensorize_vadd():\n    def add(m):\n        x = te.placeholder((m,), name=\"x\")\n        y = te.placeholder((m,), name=\"y\")\n        z = te.compute(x.shape, lambda i: x[i] + y[i], name=\"z\")\n        return x, y, z\n\n    def check(m, factor):\n        x, y, z = add(m)\n        s = te.create_schedule(z.op)\n        xo, xi = s[z].split(z.op.axis[0], factor=factor)\n        vadd = intrin_vadd(xo, m, factor)\n        s[z].tensorize(xi, vadd)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[z], dom_map)\n        assert tvm.ir.structural_equal(out_dom[z.op.axis[0]].extent, factor)\n        assert tvm.ir.structural_equal(out_dom[z.op.axis[0]].min, xo * factor)\n        assert tvm.ir.structural_equal(in_dom.items()[0][1][0].extent, factor)\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[z], out_dom, in_dom, vadd)\n        ana = tvm.arith.Analyzer()\n        assert tvm.ir.structural_equal(ana.simplify(body[0]), ana.simplify(vadd.op.body[0]))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [x, y, z])\n\n    def check_cache_write(m, factor):\n        x, y, z = add(m)\n        s = te.create_schedule(z.op)\n        _, _ = s[z].split(z.op.axis[0], factor=factor)\n\n        z_global = s.cache_write(z, \"global\")\n        xo, xi = z_global.op.axis\n\n        vadd = intrin_vadd(xo, m, factor)\n        s[z_global].tensorize(xi, vadd)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[z_global], dom_map)\n        # outer loop var will be rebased, so min value is the new loop var and extent is 1\n        assert tvm.ir.structural_equal(out_dom[xo].extent, 1)\n        assert isinstance(out_dom[xo].min, tvm.tir.Var)\n        assert xo.var.name == out_dom[xo].min.name\n\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[z_global], out_dom, in_dom, vadd)[0]\n        ana = tvm.arith.Analyzer()\n        vars = tvm.runtime.convert({xo.var: out_dom[xo].min})\n        vadd_body = tvm.tir.stmt_functor.substitute(vadd.op.body[0], vars)\n        assert tvm.ir.structural_equal(ana.simplify(body), ana.simplify(vadd_body))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [x, y, z])\n\n    def check_compute_reuse():\n        x, y, z = add(32)\n\n        def _intrin_vadd():\n            def _intrin_func(ins, outs):\n                return tvm.tir.call_packed(\"vadd\", ins[0], ins[1], outs[0])\n\n            return tvm.te.decl_tensor_intrin(z.op, _intrin_func)\n\n        s = tvm.te.create_schedule(z.op)\n        s[z].tensorize(z.op.axis[0], _intrin_vadd())\n        tvm.lower(s, [x, y, z])\n\n    check(128, 16)\n    check_cache_write(129, 16)\n    check_compute_reuse()\n\n\ndef test_tensorize_matmul():\n    n = 1024\n    m = n\n    l = n\n    A = te.placeholder((n, l), name=\"A\")\n    B = te.placeholder((m, l), name=\"B\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    C = te.compute((n, m), lambda i, j: te.sum(B[j, k] * A[i, k], axis=k), name=\"C\")\n\n    def check(factor):\n        s = te.create_schedule(C.op)\n        x, y = C.op.axis\n        yo, yi = s[C].split(y, factor=factor)\n        gemv = intrin_gemv(factor, l)\n        s[C].tensorize(yi, gemv)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[C], dom_map)\n        assert tvm.ir.structural_equal(out_dom[x].extent, 1)\n        assert tvm.ir.structural_equal(out_dom[y].extent, factor)\n        assert tvm.ir.structural_equal(out_dom[y].min, yo * factor)\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[C], out_dom, in_dom, gemv)\n        ana = tvm.arith.Analyzer()\n\n        assert tvm.ir.structural_equal(ana.simplify(body[0]), ana.simplify(gemv.op.body[0]))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [A, B, C])\n\n    def check_rfactor(factor, rfactor):\n        s = te.create_schedule(C.op)\n        x, y = C.op.axis\n        rk = C.op.reduce_axis[0]\n        yo, yi = s[C].split(y, factor=factor)\n        ro, ri = s[C].split(rk, factor=rfactor)\n        s[C].reorder(yo, ro, yi, ri)\n        gemv = intrin_gemv(factor, rfactor)\n        s[C].tensorize(yi, gemv)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[C], dom_map)\n        assert tvm.ir.structural_equal(out_dom[x].extent, 1)\n        assert tvm.ir.structural_equal(out_dom[y].extent, factor)\n        assert tvm.ir.structural_equal(out_dom[y].min, yo * factor)\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[C], out_dom, in_dom, gemv)\n        ana = tvm.arith.Analyzer()\n        assert tvm.ir.structural_equal(ana.simplify(body[0]), ana.simplify(gemv.op.body[0]))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [A, B, C])\n\n    def check_rfactor_no_reset(factor, rfactor):\n        s = te.create_schedule(C.op)\n        x, y = C.op.axis\n        rk = C.op.reduce_axis[0]\n        yo, yi = s[C].split(y, factor=factor)\n        ro, ri = s[C].split(rk, factor=rfactor)\n        s[C].reorder(yo, ro, yi, ri)\n        gemv = intrin_gemv_no_reset(factor, rfactor)\n        s[C].tensorize(yi, gemv)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[C], dom_map)\n        assert tvm.ir.structural_equal(out_dom[x].extent, 1)\n        assert tvm.ir.structural_equal(out_dom[y].extent, factor)\n        assert tvm.ir.structural_equal(out_dom[y].min, yo * factor)\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[C], out_dom, in_dom, gemv)\n        ana = tvm.arith.Analyzer()\n        assert tvm.ir.structural_equal(ana.simplify(body[0]), ana.simplify(gemv.op.body[0]))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [A, B, C])\n\n    def check_rfactor_no_reset_multi_reduction(factor, rfactor):\n        s = te.create_schedule(C.op)\n        x, y = C.op.axis\n        rk = C.op.reduce_axis[0]\n        yo, yi = s[C].split(y, factor=factor)\n        ro, ri = s[C].split(rk, factor=rfactor)\n        roo, roi = s[C].split(ro, factor=2)\n        s[C].reorder(yo, roo, roi, yi, ri)\n        gemv = intrin_gemv_no_reset(factor, rfactor)\n        s[C].tensorize(yi, gemv)\n        s = s.normalize()\n        dom_map = tvm.te.schedule.InferBound(s)\n        finfer = tvm.get_global_func(\"test.op.InferTensorizeRegion\")\n        out_dom, in_dom = finfer(s[C], dom_map)\n        assert tvm.ir.structural_equal(out_dom[x].extent, 1)\n        assert tvm.ir.structural_equal(out_dom[y].extent, factor)\n        assert tvm.ir.structural_equal(out_dom[y].min, yo * factor)\n        fmatch = tvm.get_global_func(\"test.op.MatchTensorizeBody\")\n        body = fmatch(s[C], out_dom, in_dom, gemv)\n        ana = tvm.arith.Analyzer()\n        assert tvm.ir.structural_equal(ana.simplify(body[0]), ana.simplify(gemv.op.body[0]))\n        stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n        tvm.lower(s, [A, B, C])\n\n    check(16)\n    check_rfactor(16, 16)\n    check_rfactor_no_reset(16, 16)\n    check_rfactor_no_reset_multi_reduction(16, 16)\n\n\n# This tests whether algorithm and intrinsics expressions are simplified\n# as much as possible first and then checked for equality. See Issue #696\ndef test_tensorize_op():\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    def op_intrin():\n        bh = 9\n        bw = 9\n        x = te.placeholder((5, 5), name=\"A\")\n        y = te.compute((bh, bw), lambda i, j: x[idxd(j, 3) + idxm(i, 3), idxm(j, 3) + idxd(i, 3)])\n\n        def intrin_func(ins, outs):\n            (xx,) = ins\n            zz = outs[0]\n            return tvm.tir.call_packed(\"op\", xx, zz)\n\n        return te.decl_tensor_intrin(y.op, intrin_func, default_buffer_params={\"offset_factor\": 2})\n\n    A = te.placeholder((5, 5), name=\"A\")\n    B = te.compute((9, 9), lambda i, j: A[idxd(j, 3) + idxm(i, 3), idxm(j, 3) + idxd(i, 3)])\n    bt = op_intrin()\n    s = te.create_schedule(B.op)\n\n    x, y = B.op.axis\n    s[B].tensorize(x, bt)\n    s = s.normalize()\n    tvm.lower(s, [A, B])\n\n\n# This test asserts that tensorize does not have any effect on\n# TensorComputeOp operations\ndef test_tensorize_tensor_compute_op():\n    # an intrinsic called \"multivadd\" whose definition (pattern)\n    # is a loop of another intrinsic called \"vadd\"\n    def intrin_multivadd(n):\n        n_a = te.var(\"n_a\")\n        Ab = tvm.tir.decl_buffer((n,), \"float32\", strides=[n_a])\n\n        n_b = te.var(\"n_b\")\n        Bb = tvm.tir.decl_buffer((n,), \"float32\", strides=[n_b])\n\n        n_c = te.var(\"n_c\")\n        Cb = tvm.tir.decl_buffer((n,), \"float32\", strides=[n_c])\n\n        z = te.compute(\n            (n,),\n            lambda i: tvm.tir.call_extern(\n                \"float32\",\n                \"vadd\",\n                Ab.access_ptr(\"w\", offset=n_a * i),\n                Bb.access_ptr(\"r\", offset=n_b * i),\n                Cb.access_ptr(\"r\", offset=n_c * i),\n            ),\n        )\n\n        # replace the pattern with the multivadd call. I need to figure out\n        # how to pass it the right parameters.\n        def intrin_func(ins, outs):\n            return tvm.tir.call_packed(\"multivadd\")\n\n        return te.decl_tensor_intrin(z.op, intrin_func, name=\"multivadd\")\n\n    def intrin_vadd(n):\n        dtype = \"float32\"\n        x = te.placeholder((n,), dtype=dtype, name=\"vx\")\n        y = te.placeholder((n,), dtype=dtype, name=\"vy\")\n        z = te.compute(x.shape, lambda i: x[i] + y[i], name=\"z\")\n        s = te.create_schedule(z.op)\n\n        def create_buffer(t):\n            return tvm.tir.decl_buffer(t.shape, t.dtype, name=\"W\" + t.name, offset_factor=16)\n\n        def intrin_func(ins, outs):\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"float32\",\n                    \"vadd\",\n                    ins[0].access_ptr(\"r\"),\n                    ins[1].access_ptr(\"r\"),\n                    outs[0].access_ptr(\"wr\"),\n                )\n            )\n            return ib.get()\n\n        return te.decl_tensor_intrin(\n            z.op, intrin_func, binds={x: create_buffer(x), y: create_buffer(y), z: create_buffer(z)}\n        )\n\n    # cache_read, cache_write\n    M = 1024\n    factor = 16\n    dtype = \"float32\"\n\n    A = te.placeholder((M // factor, factor), name=\"A\", dtype=dtype)\n    B = te.placeholder((M // factor, factor), name=\"B\", dtype=dtype)\n\n    vadd = intrin_vadd(factor)\n    C = te.compute((M // factor, factor), lambda i: vadd(A[i, 0:factor], B[i, 0:factor]), name=\"C\")\n\n    s = te.create_schedule(C.op)\n    multivadd = intrin_multivadd(64)\n    s[C].tensorize(C.op.axis[0], multivadd)\n    s = s.normalize()\n    dom_map = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n    # The loop that we tried to tensorize still exists in the code\n    # That means tensorize didn't work as expected\n    assert isinstance(stmt.body, tvm.tir.For)\n    assert stmt.body.loop_var.name == C.op.axis[0].var.name\n\n\nif __name__ == \"__main__\":\n    test_tensorize_vadd()\n    test_tensorize_matmul()\n    test_tensorize_op()\n    test_tensorize_tensor_compute_op()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_tag.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport json\nimport tvm\nfrom tvm import te\nfrom tvm import te\n\n\n@tvm.te.tag_scope(tag=\"conv\")\ndef compute_conv(data, weight):\n    N, IC, H, W = data.shape\n    OC, IC, KH, KW = weight.shape\n    OH = H - KH + 1\n    OW = W - KW + 1\n\n    ic = te.reduce_axis((0, IC), name=\"ic\")\n    dh = te.reduce_axis((0, KH), name=\"dh\")\n    dw = te.reduce_axis((0, KW), name=\"dw\")\n\n    return te.compute(\n        (N, OC, OH, OW),\n        lambda i, oc, h, w: te.sum(\n            data[i, ic, h + dh, w + dw] * weight[oc, ic, dh, dw], axis=[ic, dh, dw]\n        ),\n    )\n\n\ndef test_with():\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    l = te.size_var(\"l\")\n\n    A = te.placeholder((n, l), name=\"A\")\n    B = te.placeholder((m, l), name=\"B\")\n    with tvm.te.tag_scope(tag=\"gemm\"):\n        k = te.reduce_axis((0, l), name=\"k\")\n        C = te.compute(\n            (n, m),\n            lambda i, j: te.sum(A[i, k] * B[j, k], axis=k),\n            attrs={\"hello\": 1, \"arr\": [10, 12]},\n        )\n\n    assert C.op.tag == \"gemm\"\n    assert \"hello\" in C.op.attrs\n    assert \"xx\" not in C.op.attrs\n    assert C.op.attrs[\"hello\"].value == 1\n    CC = tvm.ir.load_json(tvm.ir.save_json(C))\n    assert CC.op.attrs[\"hello\"].value == 1\n    assert CC.op.attrs[\"arr\"][0].value == 10\n    # str format happened to be json compatible\n    assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12\n\n\ndef test_decorator():\n    n = te.size_var(\"n\")\n    c = te.size_var(\"c\")\n    h = te.size_var(\"h\")\n    w = te.size_var(\"w\")\n    kh = te.size_var(\"kh\")\n    kw = te.size_var(\"kw\")\n\n    A = te.placeholder((n, c, h, w), name=\"A\")\n    B = te.placeholder((c, c, kh, kw), name=\"B\")\n    C = compute_conv(A, B)\n    assert C.op.tag == \"conv\"\n    assert len(C.op.attrs) == 0\n\n\ndef test_nested():\n    n = te.size_var(\"n\")\n    c = te.size_var(\"c\")\n    h = te.size_var(\"h\")\n    w = te.size_var(\"w\")\n    kh = te.size_var(\"kh\")\n    kw = te.size_var(\"kw\")\n\n    A = te.placeholder((n, c, h, w), name=\"A\")\n    B = te.placeholder((c, c, kh, kw), name=\"B\")\n    try:\n        with te.tag_scope(tag=\"conv\"):\n            C = compute_conv(A, B)\n        assert False\n    except ValueError:\n        pass\n\n\nif __name__ == \"__main__\":\n    test_with()\n    test_decorator()\n    test_nested()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_tensor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.topi.nn.pooling import pool2d\n\n\ndef test_tensor():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.placeholder((n, l), name=\"B\")\n    T = te.compute((m, n, l), lambda i, j, k: A[i, k] * B[j, k])\n    print(T)\n    print(T.op.body)\n    assert tuple(T.shape) == (m, n, l)\n    assert isinstance(A.op, tvm.te.PlaceholderOp)\n    assert A == A\n    assert T.op.output(0) == T\n    assert T.op.output(0).__hash__() == T.__hash__()\n    d = {T.op.output(0): 1}\n    assert d[T] == 1\n    assert T[0][0][0].astype(\"float16\").dtype == \"float16\"\n\n\ndef test_rank_zero():\n    m = te.size_var(\"m\")\n    A = te.placeholder((m,), name=\"A\")\n    scale = te.placeholder((), name=\"s\")\n    k = te.reduce_axis((0, m), name=\"k\")\n    T = te.compute((), lambda: te.sum(A[k] * scale(), axis=k))\n    print(T)\n    print(T.op.body)\n    assert tuple(T.shape) == ()\n\n\ndef test_conv1d():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n + 2), name=\"A\")\n\n    def computeB(ii):\n        i = ii + 1\n        return A[i - 1] + A[i] + A[i + 1]\n\n    B = te.compute(n, computeB)\n\n\ndef test_tensor_slice():\n    n = te.size_var(\"n\")\n    A = te.compute((n, n), lambda i, j: 1)\n    B = te.compute((n,), lambda i: A[0][i] + A[0][i])\n\n\ndef test_tensor_reduce_multi_axis():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    k1 = te.reduce_axis((0, n), \"k\")\n    k2 = te.reduce_axis((0, m), \"k\")\n    C = te.compute((1,), lambda _: te.sum(A[k1, k2], axis=(k1, k2)))\n    C = te.compute((1,), lambda _: te.sum(A[k1, k2], axis=[k1, k2]))\n\n\ndef test_tensor_comm_reducer():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A = te.placeholder((m, n), name=\"A\")\n    k = te.reduce_axis((0, n), \"k\")\n    mysum = te.comm_reducer(lambda x, y: x + y, lambda t: tvm.tir.const(0, dtype=t))\n    C = te.compute((m,), lambda i: mysum(A[i, k], axis=k))\n\n\ndef test_tensor_comm_reducer_overload():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    mysum = te.comm_reducer(lambda x, y: x + y, lambda t: tvm.tir.const(0, dtype=t))\n    sum_res = mysum(m, n)\n\n\ndef test_tensor_reduce():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.placeholder((n, l), name=\"B\")\n    T = te.compute((m, n, l), lambda i, j, k: A[i, k] * B[j, k])\n    rv = te.reduce_axis((0, A.shape[1]), \"k\")\n    C = te.compute((m, n), lambda i, j: te.sum(T(i, j, rv + 1), axis=rv))\n    # json load save\n    C_json = tvm.ir.save_json(C)\n    C_loaded = tvm.ir.load_json(C_json)\n    assert isinstance(C_loaded, te.tensor.Tensor)\n    assert str(C_loaded) == str(C)\n\n\ndef test_tensor_reduce_multiout_with_cond():\n    def fcombine(x, y):\n        return x[0] + y[0], x[1] + y[1]\n\n    def fidentity(t0, t1):\n        return tvm.tir.const(0, t0), tvm.tir.const(1, t1)\n\n    mysum = te.comm_reducer(fcombine, fidentity, name=\"mysum\")\n\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    idx = te.placeholder((m, n), name=\"idx\", dtype=\"int32\")\n    val = te.placeholder((m, n), name=\"val\", dtype=\"int32\")\n    k = te.reduce_axis((0, n), \"k\")\n    cond = te.floormod(k, 2) == 0\n    T0, T1 = te.compute((m,), lambda i: mysum((idx[i, k], val[i, k]), axis=k, where=cond), name=\"T\")\n\n\ndef test_tensor_compute1():\n    m = 1024\n    factor = 16\n    dtype = \"float32\"\n\n    def intrin_vadd(n):\n        x = te.placeholder((n,))\n        y = te.placeholder((n,))\n        z = te.compute(x.shape, lambda i: x[i] + y[i])\n\n        def intrin_func(ins, outs):\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    outs[0].dtype,\n                    \"vadd\",\n                    ins[0].access_ptr(\"r\"),\n                    ins[1].access_ptr(\"r\"),\n                    outs[0].access_ptr(\"wr\"),\n                )\n            )\n            return ib.get()\n\n        return te.decl_tensor_intrin(z.op, intrin_func, default_buffer_params={\"offset_factor\": n})\n\n    vadd = intrin_vadd(factor)\n\n    A = te.placeholder((m // factor, factor), name=\"A\", dtype=dtype)\n    B = te.placeholder((m // factor, factor), name=\"B\", dtype=dtype)\n    C = te.compute((m // factor, factor), lambda i: vadd(A[i, 0:factor], B[i, 0:factor]))\n\n    s = te.create_schedule(C.op)\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        stmt = tvm.lower(s, [A, B, C])[\"main\"].body\n    assert isinstance(stmt.body, tvm.tir.Evaluate)\n\n\ndef test_tensor_compute2():\n    M = 2048\n    N = 1024\n    L = 1024\n    factor = 16\n    factor1 = 32\n    factor2 = 32\n    dtype = \"float32\"\n\n    def intrin_gemm(m, n, l):\n        k = te.reduce_axis((0, l))\n        x = te.placeholder((m, l))\n        y = te.placeholder((n, l))\n        # in theory, no relation\n        z = te.compute((m, n), lambda i, j: te.sum(x[i][k] * y[j][k], axis=k))\n\n        def intrin_func(ins, outs):\n            x_ptr = ins[0].access_ptr(\"r\")\n            y_ptr = ins[1].access_ptr(\"r\")\n            z_ptr = outs[0].access_ptr(\"w\")\n            body = tvm.tir.call_packed(\"gemv\", x_ptr, y_ptr, z_ptr, m, n, l)\n            reset = tvm.tir.call_packed(\"fill_zero\", z_ptr, m, n)\n            update = tvm.tir.call_packed(\"gemv_add\", x_ptr, y_ptr, z_ptr, m, n, l)\n            return body, reset, update\n\n        return te.decl_tensor_intrin(z.op, intrin_func, default_buffer_params={\"offset_factor\": n})\n\n    vgemm = intrin_gemm(factor1, factor2, factor)\n\n    A = te.placeholder((M // factor1, L // factor, factor1, factor), name=\"A\", dtype=dtype)\n    B = te.placeholder((N // factor2, L // factor, factor2, factor), name=\"B\", dtype=dtype)\n    k = te.reduce_axis((0, L // factor), name=\"k\")\n    C = te.compute(\n        (M // factor1, N // factor2, factor1, factor2),\n        lambda i, j: vgemm(\n            A[i, k, 0:factor1, 0:factor], B[j, k, 0:factor2, 0:factor], reduce_axis=k\n        ),\n    )\n\n    s = te.create_schedule(C.op)\n    # check lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        stmt = tvm.lower(s, [A, B, C])[\"main\"].body\n    assert isinstance(stmt.body.body[0], tvm.tir.Evaluate)\n    assert isinstance(stmt.body.body[1].body, tvm.tir.Evaluate)\n\n\ndef test_tensor_scan():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    x = te.placeholder((m, n))\n    s = te.placeholder((m, n))\n    res = tvm.te.scan(\n        te.compute((1, n), lambda _, i: x[0, i]),\n        te.compute((m, n), lambda t, i: s[t - 1, i] + x[t, i]),\n        s,\n    )\n    assert tuple(res.shape) == (m, n)\n\n\ndef test_scan_multi_out():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    x1 = te.placeholder((m, n))\n    s1 = te.placeholder((m, n))\n    x2 = te.placeholder((m, n))\n    s2 = te.placeholder((m, n))\n    s1_init = te.compute((1, n), lambda _, i: x1[0, i])\n    s2_init = te.compute((1, n), lambda _, i: x2[0, i])\n    s1_update = te.compute((m, n), lambda t, i: s1[t - 1, i] + s2[t - 1, i] + x1[t, i])\n    s2_update = te.compute((m, n), lambda t, i: x2[t, i] + s2[t - 1, i])\n\n    r0, r1 = tvm.te.scan([s1_init, s2_init], [s1_update, s2_update], [s1, s2])\n    assert r0.value_index == 0\n    assert r1.value_index == 1\n    json_str = tvm.ir.save_json(r0.op)\n    zz = tvm.ir.load_json(json_str)\n    assert isinstance(zz, tvm.te.ScanOp)\n\n\ndef test_extern():\n    m = te.size_var(\"m\")\n    A = te.placeholder((m,), name=\"A\")\n\n    def extern_func(ins, outs):\n        assert isinstance(ins[0], tvm.te.schedule.Buffer)\n        return tvm.tir.call_packed(\"myadd\", ins[0].data, outs[0].data, m)\n\n    B = te.extern((m,), [A], extern_func)\n    assert tuple(B.shape) == (m,)\n\n\ndef test_extern_multi_out():\n    m = te.size_var(\"m\")\n    A = te.placeholder((m,), name=\"A\")\n    B = te.compute((m,), lambda i: A[i] * 10)\n\n    def extern_func(ins, outs):\n        assert isinstance(ins[0], tvm.te.schedule.Buffer)\n        return tvm.tir.call_packed(\"myadd\", ins[0].data, outs[0].data, outs[1].data, m)\n\n    res = te.extern([A.shape, A.shape], [A, B], extern_func)\n    assert len(res) == 2\n    assert res[1].value_index == 1\n\n\ndef test_tuple_inputs():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A0 = te.placeholder((m, n), name=\"A0\")\n    A1 = te.placeholder((m, n), name=\"A1\")\n    T0, T1 = te.compute((m, n), lambda i, j: (A0[i, j] * 2, A1[i, j] * 3), name=\"T\")\n    s = te.create_schedule(T0.op)\n\n    for i in range(len(T0.shape)):\n        assert T0.shape[i] == T1.shape[i]\n    assert T0.op == T1.op\n    assert T0.value_index == 0\n    assert T1.value_index == 1\n\n\ndef test_tuple_with_different_deps():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    A0 = te.placeholder((m, n), name=\"A1\")\n    A1 = te.placeholder((m, n), name=\"A2\")\n    B0, B1 = te.compute((m, n), lambda i, j: (A0[i, j] * 2, A1[i, j] * 3), name=\"B\")\n    C = te.compute((m, n), lambda i, j: B0[i, j] + 4, name=\"C\")\n\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=10)\n    s[B0.op].compute_at(s[C], xo)\n    sch = s.normalize()\n    bounds = tvm.te.schedule.InferBound(sch)\n    stmt = tvm.te.schedule.ScheduleOps(sch, bounds)\n\n    def get_B1_realize(x):\n        if (\n            isinstance(x, tvm.tir.ProducerRealize)\n            and x.producer.op == B1.op\n            and x.producer.value_index == 1\n        ):\n            ret.append(x)\n\n    ret = []\n    tvm.tir.stmt_functor.post_order_visit(stmt, get_B1_realize)\n\n    assert stmt.producer == C and len(ret) == 1\n\n\ndef test_tensor_inputs():\n    x = te.placeholder((1,), name=\"x\")\n    y = te.compute(x.shape, lambda i: x[i] + x[i])\n    assert tuple(y.op.input_tensors) == (x,)\n\n\ndef test_tensor_pool():\n    def intrin_pool():\n        A = te.placeholder((64, 16, 16), name=\"A\")\n        kh = te.reduce_axis((0, 3), name=\"kh\")\n        kw = te.reduce_axis((0, 3), name=\"kw\")\n        P = te.compute(\n            (64, 14, 14),\n            lambda c, oh, ow: tvm.te.max(A[c, oh + kh, ow + kw], axis=[kh, kw]),\n            name=\"p\",\n        )\n\n        def intrin_func(ins, outs):\n            dinp = ins[0]\n            dout = outs[0]\n            return tvm.tir.call_packed(\"op\", dinp, dout)\n\n        return te.decl_tensor_intrin(P.op, intrin_func, default_buffer_params={\"offset_factor\": 1})\n\n    A = te.placeholder((1, 64, 16, 16), name=\"A\")\n    P = pool2d(\n        data=A, kernel=(3, 3), stride=(1, 1), dilation=(1, 1), padding=(0, 0, 0, 0), pool_type=\"max\"\n    )\n    s = te.create_schedule(P.op)\n    _, oh, _, _ = P.op.axis\n    intrin = intrin_pool()\n    s[P].tensorize(oh, intrin)\n    tvm.lower(s, [A, P])\n\n\ndef test_tensor_scalar_mixed():\n    # test te with tensor and scalar\n    a = np.array(np.random.uniform(size=(10,)), \"float32\")\n    b = np.array(np.random.uniform(size=(1))[0], \"float32\")\n    c = np.array(np.random.uniform(size=(10,)), \"float32\")\n\n    @tvm.register_func(\"tvm.test_tensor_scalar_scale\")\n    def my_scale(tensor, scalar, out):\n        out_np = tensor.numpy() * scalar.numpy()\n        tvm.nd.array(out_np).copyto(out)\n\n    A = te.placeholder(a.shape, name=\"A\")\n    B = te.placeholder(b.shape, name=\"B\")\n    C = te.extern(\n        a.shape,\n        [A, B],\n        lambda ins, outs: tvm.tir.call_packed(\n            \"tvm.test_tensor_scalar_scale\", ins[0], ins[1], outs[0]\n        ),\n        name=\"C\",\n    )\n    s = te.create_schedule(C.op)\n    f = tvm.build(s, [A, B, C], \"llvm\")\n\n    ta = tvm.nd.array(a)\n    tb = tvm.nd.array(b)\n    tc = tvm.nd.array(c)\n    f(ta, tb, tc)\n    tvm.testing.assert_allclose(a * b, tc.numpy())\n\n\ndef test_tensor_scalar():\n    # test te with scalar shape\n    a = np.array(np.random.uniform(size=(1))[0], \"float32\")\n    b = np.array(0.0, \"float32\")\n\n    @tvm.register_func(\"tvm.test_tensor_scalar_copy\")\n    def mycopy(x, y):\n        x.copyto(y)\n\n    A = te.placeholder(a.shape, name=\"A\")\n    B = te.extern(\n        a.shape,\n        [A],\n        lambda ins, outs: tvm.tir.call_packed(\"tvm.test_tensor_scalar_copy\", ins[0], outs[0]),\n        name=\"B\",\n    )\n    s = te.create_schedule(B.op)\n    f = tvm.build(s, [A, B], \"llvm\")\n\n    ta = tvm.nd.array(a)\n    tb = tvm.nd.array(b)\n    f(ta, tb)\n    tvm.testing.assert_allclose(ta.numpy(), tb.numpy())\n\n\nif __name__ == \"__main__\":\n    test_tensor()\n    test_rank_zero()\n    test_conv1d()\n    test_tensor_slice()\n    test_tensor_reduce_multi_axis()\n    test_tensor_comm_reducer()\n    test_tensor_comm_reducer_overload()\n    test_tensor_reduce()\n    test_tensor_reduce_multiout_with_cond()\n    test_tensor_compute1()\n    test_tensor_compute2()\n    test_tensor_scan()\n    test_scan_multi_out()\n    test_extern()\n    test_extern_multi_out()\n    test_tuple_inputs()\n    test_tuple_with_different_deps()\n    test_tensor_inputs()\n    test_tensor_pool()\n    test_tensor_scalar_mixed()\n    test_tensor_scalar()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_tensor_overload.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.topi.testing\nfrom tvm.topi.utils import get_const_tuple\nimport tvm.testing\n\n\ndef test_operator_type_and_tags():\n    k = 1\n    n = te.var(\"n\")\n    A = te.placeholder((), name=\"A\")\n    B = te.placeholder((10, 5), name=\"B\")\n    B1 = B[0]\n    B2 = B[0, 0]\n\n    assert isinstance(k + n, tvm.tir.PrimExpr)\n    assert isinstance(n + n, tvm.tir.PrimExpr)\n    assert isinstance(k + A, te.tensor.Tensor)\n    assert isinstance(A + k, te.tensor.Tensor)\n    assert isinstance(n + A, te.tensor.Tensor)\n    assert isinstance(A + n, te.tensor.Tensor)\n    assert isinstance(A + A, te.tensor.Tensor)\n\n    assert isinstance(k + B, te.tensor.Tensor)\n    assert isinstance(B + k, te.tensor.Tensor)\n    assert isinstance(n + B, te.tensor.Tensor)\n    assert isinstance(B + n, te.tensor.Tensor)\n    assert isinstance(A + B, te.tensor.Tensor)\n    assert isinstance(B + A, te.tensor.Tensor)\n    assert isinstance(B + B, te.tensor.Tensor)\n\n    assert (k + B).op.tag == topi.tag.ELEMWISE\n    assert (B + k).op.tag == topi.tag.ELEMWISE\n    assert (n + B).op.tag == topi.tag.ELEMWISE\n    assert (B + n).op.tag == topi.tag.ELEMWISE\n    assert (A + B).op.tag == topi.tag.BROADCAST\n    assert (B + A).op.tag == topi.tag.BROADCAST\n    assert (B + B).op.tag == topi.tag.BROADCAST\n\n    assert isinstance(k + B2, tvm.tir.PrimExpr)\n    assert isinstance(B2 + k, tvm.tir.PrimExpr)\n    assert isinstance(n + B2, tvm.tir.PrimExpr)\n    assert isinstance(B2 + n, tvm.tir.PrimExpr)\n    assert isinstance(B2 + B2, tvm.tir.PrimExpr)\n    assert isinstance(B2 + A, te.tensor.Tensor)\n    assert isinstance(A + B2, te.tensor.Tensor)\n    assert isinstance(B2 + B, te.tensor.Tensor)\n    assert isinstance(B + B2, te.tensor.Tensor)\n\n\ndef test_combination():\n    k = 3\n    n = 5\n    m = 10\n    x = te.var(\"x\")\n    A = te.placeholder((n, m), name=\"A\")\n    B = te.placeholder((n, m), name=\"B\")\n    C = te.placeholder((n, m), name=\"C\")\n    D = k + A - B * C + x\n    s = te.create_schedule(D.op)\n    foo = tvm.build(s, [x, A, B, C, D], \"llvm\")\n    dev = tvm.cpu(0)\n    x = 2\n    a = tvm.nd.array(np.random.uniform(size=(n, m)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(n, m)).astype(B.dtype), dev)\n    c = tvm.nd.array(np.random.uniform(size=(n, m)).astype(C.dtype), dev)\n    d = tvm.nd.array(np.zeros((n, m), dtype=D.dtype), dev)\n    foo(x, a, b, c, d)\n    tvm.testing.assert_allclose(d.numpy(), k + a.numpy() - b.numpy() * c.numpy() + x)\n\n\ndef verify_tensor_scalar_bop(shape, typ=\"add\"):\n    \"\"\"Verify non-constant Tensor and scalar binary operations.\"\"\"\n    sh = [te.size_var(\"n%d\" % i) for i in range(0, len(shape))]\n    k = te.var(\"k\")\n    A = te.placeholder(sh, name=\"A\")\n    if typ == \"add\":\n        B = A + k\n    elif typ == \"sub\":\n        B = A - k\n    elif typ == \"mul\":\n        B = A * k\n    elif typ == \"div\":\n        B = A / k\n    else:\n        raise NotImplementedError()\n\n    def check_device(device):\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        dev = tvm.device(device, 0)\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s = tvm.topi.testing.get_elemwise_schedule(device)(B)\n\n        k_ = 2\n        foo = tvm.build(s, [A, B, k] + sh, device, name=\"tensor_scalar_\" + typ)\n        a_npy = np.random.uniform(size=shape).astype(A.dtype)\n        if typ == \"add\":\n            b_npy = a_npy + k_\n        elif typ == \"sub\":\n            b_npy = a_npy - k_\n        elif typ == \"mul\":\n            b_npy = a_npy * k_\n        elif typ == \"div\":\n            b_npy = a_npy / k_\n        else:\n            raise NotImplementedError()\n\n        a_nd = tvm.nd.array(a_npy, dev)\n        b_nd = tvm.nd.array(np.empty(b_npy.shape).astype(B.dtype), dev)\n        foo(a_nd, b_nd, k_, *shape)\n        tvm.testing.assert_allclose(b_nd.numpy(), b_npy, rtol=1e-5)\n\n    for device in [\"llvm\", \"cuda\", \"opencl\", \"metal\", \"rocm\", \"vulkan\"]:\n        check_device(device)\n\n\ndef verify_broadcast_bop(lhs_shape, rhs_shape, typ=\"add\"):\n    A = te.placeholder(shape=lhs_shape, name=\"A\")\n    B = te.placeholder(shape=rhs_shape, name=\"B\")\n    if typ == \"add\":\n        C = A + B\n    elif typ == \"sub\":\n        C = A - B\n    elif typ == \"mul\":\n        C = A * B\n    elif typ == \"div\":\n        C = A / B\n    else:\n        raise NotImplementedError()\n\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n        with tvm.target.Target(device):\n            s = tvm.topi.testing.get_broadcast_schedule(device)(C)\n\n        foo = tvm.build(s, [A, B, C], device, name=\"broadcast_binary\" + \"_\" + typ)\n        lhs_npy = np.random.uniform(size=lhs_shape).astype(A.dtype)\n        rhs_npy = np.random.uniform(size=rhs_shape).astype(A.dtype)\n        if typ == \"add\":\n            out_npy = lhs_npy + rhs_npy\n        elif typ == \"sub\":\n            out_npy = lhs_npy - rhs_npy\n        elif typ == \"mul\":\n            out_npy = lhs_npy * rhs_npy\n        elif typ == \"div\":\n            rhs_npy = np.abs(rhs_npy) + 0.001\n            out_npy = lhs_npy / rhs_npy\n        else:\n            raise NotImplementedError()\n\n        lhs_nd = tvm.nd.array(lhs_npy, dev)\n        rhs_nd = tvm.nd.array(rhs_npy, dev)\n        out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), dev)\n        for _ in range(1):\n            foo(lhs_nd, rhs_nd, out_nd)\n        tvm.testing.assert_allclose(out_nd.numpy(), out_npy, rtol=1e-4, atol=1e-4)\n\n    for device in [\"llvm\", \"cuda\", \"opencl\", \"metal\", \"rocm\", \"vulkan\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef verify_conv2d_scalar_bop(\n    batch, in_size, in_channel, num_filter, kernel, stride, padding, typ=\"add\"\n):\n    def check_device(device):\n        dev = tvm.device(device, 0)\n        if not tvm.testing.device_enabled(device):\n            print(\"Skip because %s is not enabled\" % device)\n            return\n        print(\"Running on target: %s\" % device)\n\n        conv2d_nchw, schedule_conv2d_nchw = tvm.topi.testing.get_conv2d_nchw_implement(device)\n\n        k = 10.0\n        dilation = (1, 1)\n        with tvm.target.Target(device):\n            A = te.placeholder((batch, in_channel, in_size, in_size), name=\"A\")\n            W = te.placeholder((num_filter, in_channel, kernel, kernel), name=\"W\")\n            B = conv2d_nchw(A, W, stride, padding, dilation, A.dtype)\n            if typ == \"add\":\n                C = B + k\n            elif typ == \"sub\":\n                C = B - k\n            elif typ == \"mul\":\n                C = B * k\n            elif typ == \"div\":\n                C = B / k\n            else:\n                raise NotImplementedError()\n            s = schedule_conv2d_nchw([C])\n\n        foo = tvm.build(s, [A, W, B, C], device, name=\"conv2d_scalar_\" + typ)\n\n        a_npy = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)\n        w_npy = np.random.uniform(size=get_const_tuple(W.shape)).astype(W.dtype)\n        b_npy = tvm.topi.testing.conv2d_nchw_python(a_npy, w_npy, stride, padding)\n        c_npy = np.random.uniform(size=get_const_tuple(B.shape)).astype(B.dtype)\n        if typ == \"add\":\n            c_npy = b_npy + k\n        elif typ == \"sub\":\n            c_npy = b_npy - k\n        elif typ == \"mul\":\n            c_npy = b_npy * k\n        elif typ == \"div\":\n            c_npy = b_npy / k\n        else:\n            raise NotImplementedError()\n\n        a_nd = tvm.nd.array(a_npy, dev)\n        w_nd = tvm.nd.array(w_npy, dev)\n        b_nd = tvm.nd.array(np.empty(b_npy.shape).astype(B.dtype), dev)\n        c_nd = tvm.nd.array(np.empty(c_npy.shape).astype(C.dtype), dev)\n        foo(a_nd, w_nd, b_nd, c_nd)\n        tvm.testing.assert_allclose(c_nd.numpy(), c_npy, rtol=1e-4, atol=1e-4)\n\n    for device in [\"llvm\", \"cuda\", \"opencl\", \"metal\", \"rocm\", \"vulkan\"]:\n        check_device(device)\n\n\n@tvm.testing.uses_gpu\ndef test_tensor_scalar_bop():\n    verify_tensor_scalar_bop((1,), typ=\"add\")\n    verify_tensor_scalar_bop((3, 5), typ=\"sub\")\n    verify_tensor_scalar_bop((1, 3, 5), typ=\"mul\")\n    verify_tensor_scalar_bop((2, 3, 1, 32), typ=\"div\")\n\n\n@tvm.testing.uses_gpu\ndef test_broadcast_bop():\n    verify_broadcast_bop((2, 3), (), typ=\"add\")\n    verify_broadcast_bop((5, 2, 3), (1,), typ=\"add\")\n    verify_broadcast_bop((1, 32), (64, 32), typ=\"sub\")\n    verify_broadcast_bop((5, 64, 128), (2, 5, 64, 1), typ=\"mul\")\n    verify_broadcast_bop((2, 3, 1, 32), (64, 32), typ=\"div\")\n\n\n@tvm.testing.uses_gpu\ndef test_conv2d_scalar_bop():\n    verify_conv2d_scalar_bop(1, 16, 4, 4, 3, 1, 1, typ=\"add\")\n    verify_conv2d_scalar_bop(1, 32, 2, 1, 3, 1, 1, typ=\"sub\")\n    verify_conv2d_scalar_bop(1, 32, 1, 1, 3, 1, 1, typ=\"mul\")\n    verify_conv2d_scalar_bop(1, 16, 2, 1, 3, 1, 1, typ=\"div\")\n\n\nif __name__ == \"__main__\":\n    test_operator_type_and_tags()\n    test_combination()\n    test_tensor_scalar_bop()\n    test_broadcast_bop()\n    test_conv2d_scalar_bop()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_te_verify_compute.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_verify_compute():\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"k\")\n    k_ = te.reduce_axis((0, m - 1), \"k_\")\n    f1 = lambda i: te.sum(A[i, k], axis=k)\n    f2 = lambda i: A[i, 0] + 1\n    f3 = lambda i: te.sum(A[i, k], axis=k) + 1\n    f4 = lambda i: A[i, 0] * (te.sum(A[i, k], axis=k) + 1)\n    f5 = lambda i: (te.sum(A[i, k], axis=k), A[i, 0] + 1)\n    f6 = lambda i: (te.sum(A[i, k], axis=k), te.sum(A[i, k_], axis=k_))\n\n    #\n    # Valid compute\n    try:\n        B = te.compute((n,), f1, name=\"B\")\n    except tvm._ffi.base.TVMError as ex:\n        assert False\n\n    #\n    # Valid compute\n    try:\n        B = te.compute((n,), f2, name=\"B\")\n    except tvm._ffi.base.TVMError as ex:\n        assert False\n\n    #\n    # Invalid compute with non top level reduction\n    try:\n        B = te.compute((n,), f3, name=\"B\")\n        assert False\n    except tvm._ffi.base.TVMError as ex:\n        pass\n\n    #\n    # Invalid compute with non top level reduction\n    try:\n        B = te.compute((n,), f4, name=\"B\")\n        assert False\n    except tvm._ffi.base.TVMError as ex:\n        pass\n\n    #\n    # Invalid compute with reduction and non-reduction batch ops\n    try:\n        B0, B1 = te.compute((n,), f5, name=\"B\")\n        assert False\n    except tvm._ffi.base.TVMError as ex:\n        pass\n\n    #\n    # Invalid compute with unequal batch reduction ops\n    try:\n        B0, B1 = te.compute((n,), f6, name=\"B\")\n        assert False\n    except tvm._ffi.base.TVMError as ex:\n        pass\n\n\nif __name__ == \"__main__\":\n    test_verify_compute()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_testing.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import te\nimport tvm.testing\n\n\ndef test_check_numerical_grads():\n    # Functions and their derivatives\n    functions = [\n        lambda x: (x * x * x, 3 * x * x),\n        lambda x: (x * x, 2 * x),\n        lambda x: (np.abs(x), np.sign(x)),\n        lambda x: (np.log(np.abs(x)), 1 / x),\n        lambda x: (np.sqrt(np.abs(x)), np.sign(x) / (2 * np.sqrt(np.abs(x)))),\n        lambda x: (1 / x, -1 / (x * x)),\n        lambda x: (np.sign(np.sin(1 / x)), np.zeros_like(x)),\n        lambda x: (x * np.sin(1 / x), np.sin(1 / x) - np.cos(1 / x) / x),\n        lambda x: (np.sin(1 / x), -np.cos(1 / x) / (x * x)),\n        lambda x: (np.tan(x), 1.0 / (np.cos(x) * np.cos(x))),\n    ]\n\n    np.random.seed(0)\n\n    # Avoid values too close to 0 since singularities of our functions are there\n    min_x = 0.5\n\n    for func in functions:\n        x_input = np.random.uniform(min_x, 10, size=(3, 4))\n\n        # We need a function returning a scalar, so sum the results\n        func_forw = lambda x: np.sum(func(x)[0])\n        grads = [func(x_input)[1]]\n\n        tvm.testing.check_numerical_grads(func_forw, [x_input], grads)\n\n    # Check functions with multiple arguments\n    for f1 in functions:\n        for f2 in functions:\n            x_input = np.random.uniform(min_x, 10, size=(3, 4))\n            y_input = np.random.uniform(min_x, 10, size=(3, 4))\n\n            func_forw = lambda x, y: np.sum(f1(x)[0] + f2(y)[0])\n            grads = [f1(x_input)[1], f2(y_input)[1]]\n\n            tvm.testing.check_numerical_grads(func_forw, [x_input, y_input], grads)\n\n            # Same thing but with keyword arguments\n            func_forw = lambda x, y: np.sum(f1(x)[0] + f2(y)[0])\n            grads = {\"x\": f1(x_input)[1], \"y\": f2(y_input)[1]}\n\n            tvm.testing.check_numerical_grads(func_forw, {\"x\": x_input, \"y\": y_input}, grads)\n\n    def _noise1(x, atol=1e-2, rtol=0.1):\n        # We go in random direction using twice the original tolerance to be sure this\n        # results in an error\n        sqrt_n = np.sqrt(float(np.prod(x.shape)))\n        tol = 2 * (np.linalg.norm(x) * rtol + atol * sqrt_n)\n        noise = np.random.normal(size=x.shape)\n        noise = tol * noise / np.linalg.norm(noise)\n        return x + noise\n\n    def _noise2(x, atol=1e-2, rtol=0.1):\n        # This noise affects just a single component\n        sqrt_n = np.sqrt(float(np.prod(x.shape)))\n        tol = 2 * (np.linalg.norm(x) * rtol + atol * sqrt_n)\n        n = np.random.randint(np.prod(x.shape))\n        noise = np.zeros_like(x)\n        noise.reshape(-1)[n] = tol\n        return x + noise\n\n    # Add noise to gradients and check that the function throws\n    for f1 in functions:\n        for f2 in functions:\n            x_input = np.random.uniform(min_x, 10, size=(3, 4))\n            y_input = np.random.uniform(min_x, 10, size=(3, 4))\n\n            func_forw = lambda x, y: np.sum(f1(x)[0] + f2(y)[0])\n            grads = [_noise1(f1(x_input)[1]), _noise1(f2(y_input)[1])]\n\n            try:\n                tvm.testing.check_numerical_grads(func_forw, [x_input, y_input], grads)\n            except AssertionError as e:\n                pass\n            else:\n                raise AssertionError(\"tvm.testing.check_numerical_grads didn't raise an exception\")\n\n            func_forw = lambda x, y: np.sum(f1(x)[0] + f2(y)[0])\n            grads = {\"x\": _noise2(f1(x_input)[1]), \"y\": _noise2(f2(y_input)[1])}\n\n            try:\n                tvm.testing.check_numerical_grads(func_forw, {\"x\": x_input, \"y\": y_input}, grads)\n            except AssertionError as e:\n                pass\n            else:\n                raise AssertionError(\"tvm.testing.check_numerical_grads didn't raise an exception\")\n\n\nif __name__ == \"__main__\":\n    test_tvm.testing.check_numerical_grads()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_calculate_workspace.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n\n# fmt: off\n@T.prim_func\ndef primfunc_global_allocates(placeholder_144: T.handle, placeholder_145: T.handle, placeholder_146: T.handle, T_cast_48: T.handle) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"fused_nn_conv2d_add_cast_fixed_point_multiply_clip_cast_cast_13\", \"tir.noalias\": True})\n    placeholder_147 = T.match_buffer(placeholder_144, [100352], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_148 = T.match_buffer(placeholder_145, [4608], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_149 = T.match_buffer(placeholder_146, [512], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n    T_cast_49 = T.match_buffer(T_cast_48, [100352], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    # body\n    PaddedInput_22 = T.decl_buffer([131072], \"int16\")\n    DepthwiseConv2d_9 = T.decl_buffer([100352], \"int32\")\n    for i1_29, i2_39, i3_40 in T.grid(16, 16, 512):\n        PaddedInput_22[(((i1_29*8192) + (i2_39*512)) + i3_40)] = T.if_then_else(((((1 <= i1_29) and (i1_29 < 15)) and (1 <= i2_39)) and (i2_39 < 15)), placeholder_147[((((i1_29*7168) + (i2_39*512)) + i3_40) - 7680)], T.int16(0), dtype=\"int16\")\n    for i_9, j_9, c_9 in T.grid(14, 14, 512):\n        DepthwiseConv2d_9[(((i_9*7168) + (j_9*512)) + c_9)] = 0\n        for di_9, dj_9 in T.grid(3, 3):\n            DepthwiseConv2d_9[(((i_9*7168) + (j_9*512)) + c_9)] = (DepthwiseConv2d_9[(((i_9*7168) + (j_9*512)) + c_9)] + (PaddedInput_22[(((((i_9*8192) + (di_9*8192)) + (j_9*512)) + (dj_9*512)) + c_9)].astype(\"int32\")*placeholder_148[(((di_9*1536) + (dj_9*512)) + c_9)].astype(\"int32\")))\n    for ax1_27, ax2_28, ax3_30 in T.grid(14, 14, 512):\n        DepthwiseConv2d_9[(((ax1_27*7168) + (ax2_28*512)) + ax3_30)] = (DepthwiseConv2d_9[(((ax1_27*7168) + (ax2_28*512)) + ax3_30)] + placeholder_149[ax3_30])\n    for i1_30, i2_40, i3_41 in T.grid(14, 14, 512):\n        DepthwiseConv2d_9[(((i1_30*7168) + (i2_40*512)) + i3_41)] = T.q_multiply_shift(DepthwiseConv2d_9[(((i1_30*7168) + (i2_40*512)) + i3_41)], 1269068532, 31, -4, dtype=\"int32\")\n    for i1_31, i2_41, i3_42 in T.grid(14, 14, 512):\n        DepthwiseConv2d_9[(((i1_31*7168) + (i2_41*512)) + i3_42)] = T.max(T.max(DepthwiseConv2d_9[(((i1_31*7168) + (i2_41*512)) + i3_42)], 255), 0)\n    for ax1_28, ax2_29, ax3_31 in T.grid(14, 14, 512):\n        PaddedInput_22[(((ax1_28*7168) + (ax2_29*512)) + ax3_31)] = DepthwiseConv2d_9[(((ax1_28*7168) + (ax2_29*512)) + ax3_31)].astype(\"uint8\")\n    for ax1_29, ax2_30, ax3_32 in T.grid(14, 14, 512):\n        T_cast_49[(((ax1_29*7168) + (ax2_30*512)) + ax3_32)] = PaddedInput_22[(((ax1_29*7168) + (ax2_30*512)) + ax3_32)].astype(\"int16\")\n# fmt: on\n\n\n# fmt: off\n@T.prim_func\ndef primfunc_local_allocates(placeholder_162: T.handle, placeholder_163: T.handle, placeholder_164: T.handle, T_cast_76: T.handle) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"fused_nn_conv2d_add_cast_fixed_point_multiply_clip_cast_cast_9\", \"tir.noalias\": True})\n    placeholder_165 = T.match_buffer(placeholder_162, [100352], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_166 = T.match_buffer(placeholder_163, [4608], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_167 = T.match_buffer(placeholder_164, [512], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n    T_cast_77 = T.match_buffer(T_cast_76, [100352], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    sid_21 = T.allocate_const([0,1,2,3,4,5,6,7], \"int8\", [8])\n    # body\n    PaddedInput_25 = T.decl_buffer([131072], \"int16\")\n    for i1_35, i2_46, i3_47 in T.grid(16, 16, 512):\n        PaddedInput_25[(((i1_35*8192) + (i2_46*512)) + i3_47)] = T.if_then_else(((((1 <= i1_35) and (i1_35 < 15)) and (1 <= i2_46)) and (i2_46 < 15)), placeholder_165[((((i1_35*7168) + (i2_46*512)) + i3_47) - 7680)], T.int16(0), dtype=\"int16\")\n    T_add_11 = T.decl_buffer([100352], \"int32\")\n    with T.decl_buffer([100352], \"int32\") as DepthwiseConv2d_11:\n        for i_11, j_11, c_11 in T.grid(14, 14, 512):\n            DepthwiseConv2d_11[(((i_11*7168) + (j_11*512)) + c_11)] = 0\n            for di_11, dj_11 in T.grid(3, 3):\n                DepthwiseConv2d_11[(((i_11*7168) + (j_11*512)) + c_11)] = (DepthwiseConv2d_11[(((i_11*7168) + (j_11*512)) + c_11)] + (PaddedInput_25[(((((i_11*8192) + (di_11*8192)) + (j_11*512)) + (dj_11*512)) + c_11)].astype(\"int32\")*placeholder_166[(((di_11*1536) + (dj_11*512)) + c_11)].astype(\"int32\")))\n        for ax1_44, ax2_45, ax3_47 in T.grid(14, 14, 512):\n            T_add_11[(((ax1_44*7168) + (ax2_45*512)) + ax3_47)] = (DepthwiseConv2d_11[(((ax1_44*7168) + (ax2_45*512)) + ax3_47)] + placeholder_167[ax3_47])\n    compute_22 = T.decl_buffer([100352], \"int32\")\n    with T.decl_buffer([100352], \"int32\") as T_cast_78:\n        for ax1_45, ax2_46, ax3_48 in T.grid(14, 14, 512):\n            T_cast_78[(((ax1_45*7168) + (ax2_46*512)) + ax3_48)] = T_add_11[(((ax1_45*7168) + (ax2_46*512)) + ax3_48)]\n        for i1_36, i2_47, i3_48 in T.grid(14, 14, 512):\n            compute_22[(((i1_36*7168) + (i2_47*512)) + i3_48)] = T.q_multiply_shift(T_cast_78[(((i1_36*7168) + (i2_47*512)) + i3_48)], 1948805937, 31, -5, dtype=\"int32\")\n    T_cast_79 = T.decl_buffer([100352], \"uint8\")\n    with T.decl_buffer([100352], \"int32\") as compute_23:\n        for i1_37, i2_48, i3_49 in T.grid(14, 14, 512):\n            compute_23[(((i1_37*7168) + (i2_48*512)) + i3_49)] = T.max(T.max(compute_22[(((i1_37*7168) + (i2_48*512)) + i3_49)], 255), 0)\n        for ax1_46, ax2_47, ax3_49 in T.grid(14, 14, 512):\n            T_cast_79[(((ax1_46*7168) + (ax2_47*512)) + ax3_49)] = compute_23[(((ax1_46*7168) + (ax2_47*512)) + ax3_49)].astype(\"uint8\")\n    for ax1_47, ax2_48, ax3_50 in T.grid(14, 14, 512):\n        T_cast_77[(((ax1_47*7168) + (ax2_48*512)) + ax3_50)] = T_cast_79[(((ax1_47*7168) + (ax2_48*512)) + ax3_50)].astype(\"int16\")\n# fmt: on\n\n\n@pytest.mark.parametrize(\"alignment,size,consts\", [(1, 663552, 0), (10, 663560, 0)])\ndef test_global_allocates(alignment, size, consts):\n    primfunc = primfunc_global_allocates\n    assert tvm.tir.analysis.calculate_constant_bytes(primfunc, alignment) == consts\n    assert tvm.tir.analysis.calculate_workspace_bytes(primfunc, alignment) == size\n\n\n@pytest.mark.parametrize(\"alignment,size,consts\", [(1, 1566720, 8), (100, 1567100, 100)])\ndef test_local_allocates(alignment, size, consts):\n    primfunc = primfunc_local_allocates\n    assert tvm.tir.analysis.calculate_constant_bytes(primfunc, alignment) == consts\n    assert tvm.tir.analysis.calculate_workspace_bytes(primfunc, alignment) == size\n\n\nif __name__ == \"__main__\":\n    test_global_allocates()\n    test_local_allocates()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_detect_buffer_access_lca.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef buffer_load_store_func(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.match_buffer(b, (128, 128), \"float32\")\n    C = T.alloc_buffer((128, 128), \"float32\")\n    D = T.alloc_buffer((128, 128), \"float32\")\n    for ii, jj in T.grid(128, 128):\n        with T.block():\n            i, j = T.axis.remap(\"SS\", [ii, jj])\n            A[i, j] = T.float32(0)\n    for i0, j0, k0 in T.grid(32, 32, 32):\n        with T.block():\n            i, j, k = T.axis.remap(\"SSR\", [i0, j0, k0])\n            with T.init():\n                for ii, jj in T.grid(4, 4):\n                    B[i * 4 + ii, j * 4 + jj] = A[i * 4 + ii, j * 4 + jj]\n            for ii, jj in T.grid(4, 4):\n                for kk in range(0, 4):\n                    B[i * 4 + ii, j * 4 + jj] += C[i * 4 + ii, k * 4 + kk]\n                for kk in range(0, 4):\n                    B[i * 4 + ii, j * 4 + jj] += (\n                        D[j * 4 + jj, k * 4 + kk] * C[i * 4 + ii, k * 4 + kk]\n                    )\n\n\n@T.prim_func\ndef buffer_opaque_access(b: T.handle, c: T.handle) -> None:\n    B = T.match_buffer(b, [16, 16], \"float32\")\n    C = T.match_buffer(c, [16, 16], \"float32\")\n\n    with T.block():\n        T.reads([])\n        T.writes(B[0:16, 0:16])\n        A = T.decl_buffer([256], \"float32\")\n        for i, j in T.grid(16, 16):\n            A[i * 16 + j] = 1\n        for i in range(0, 16):\n            for j in range(0, 16):\n                T.evaluate(A[i * 16 + j])\n            for j in range(0, 16):\n                T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, T.float32(0), dtype=\"handle\"))\n\n    for i, j in T.grid(16, 16):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj]\n\n\n@T.prim_func\ndef lca_is_func_root(a: T.handle) -> None:\n    A = T.match_buffer(a, [0, 0], \"float32\")\n    A[0, 0] = 1.0\n\n\n@T.prim_func\ndef match_buffer_func(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.match_buffer(b, (128, 128), \"float32\")\n    for i, j in T.grid(8, 8):\n        with T.block(\"block\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(B[vi * 16 + 2 : vi * 16 + 12, vj * 16 + 2 : vj * 16 + 16])\n            T.writes(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            B0 = T.match_buffer(B[vi * 16 + 2 : vi * 16 + 6, vj * 16 + 2 : vj * 16 + 6], (4, 4))\n            B1 = T.match_buffer(B[vi * 16 + 8 : vi * 16 + 12, vj * 16 + 8 : vj * 16 + 16], (4, 8))\n            for ii, jj in T.grid(16, 16):\n                with T.block(\"AAA\"):\n                    vii, vjj = T.axis.remap(\"SS\", [ii, jj])\n                    AA = T.match_buffer(A[vii, vjj], ())\n                    AA[()] = 1.0\n            T.evaluate(B0.data)\n            T.evaluate(B1.data)\n\n\n@T.prim_func\ndef global_buffer_with_blockidx(\n    a: T.Buffer[(1, 32), \"int32\"], b: T.Buffer[(1, 32), \"int32\"]\n) -> None:\n    for i0 in T.thread_binding(0, 1, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"copy\"):\n                i, j = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(a[i, j])\n                T.writes(b[i, j])\n                b[i, j] = a[i, j]\n\n\ndef test_buffer_load_store():\n    func = buffer_load_store_func\n    A, B = [func.buffer_map[x] for x in func.params]\n    C, D = func.body.block.alloc_buffers\n    lca = tir.analysis.detect_buffer_access_lca(func)\n\n    # LCA of Buffer A is root\n    root_block = func.body.block\n    assert lca[A] == func.body.block\n\n    # LCA of Buffer B is reduction block\n    reduce_block = root_block.body[1].body.body.body.block\n    assert lca[B] == reduce_block\n\n    # LCA of Buffer C is the second loop kk\n    loop_jj = reduce_block.body.body\n    assert lca[C] == loop_jj\n\n    # LCA of Buffer D is loop jj\n    loop_kk = loop_jj.body[1]\n    assert lca[D] == loop_kk\n\n\ndef test_opaque_access():\n    func = buffer_opaque_access\n    B, C = [func.buffer_map[x] for x in func.params]\n    lca = tir.analysis.detect_buffer_access_lca(func)\n\n    # Cannot detect buffer A since it is define by low-level Allocate\n\n    # LCA of Buffer B is root\n    root_block = func.body.block\n    assert lca[B] == func.body.block\n\n    # LCA of Buffer C is the correspond block\n    assert lca[C] == root_block.body[1].body.body.block\n\n\ndef test_lca_func_root():\n    func = lca_is_func_root\n    (A,) = [func.buffer_map[x] for x in func.params]\n    lca = tir.analysis.detect_buffer_access_lca(func)\n    assert lca[A] is None\n\n\ndef test_match_buffer():\n    func = match_buffer_func\n    A, B = [func.buffer_map[x] for x in func.params]\n    lca = tir.analysis.detect_buffer_access_lca(func)\n\n    root_block = func.body.block\n    block = root_block.body.body.body.block\n    block_inner = block.body[0].body.body.block\n\n    # LCA of Buffer C is the inner block\n    assert lca[A] == block_inner\n\n    # LCA of Buffer C is the main block\n    assert lca[B] == block\n\n\ndef test_global_buffer_with_blockidx():\n    func = global_buffer_with_blockidx\n    A, B = [func.buffer_map[x] for x in func.params]\n    lca = tir.analysis.detect_buffer_access_lca(func)\n\n    root_block = func.body.block\n    blockidx_loop = root_block.body\n    # LCA of both A and B should be the loop bound to `blockIdx`\n    assert lca[A] == blockidx_loop\n    assert lca[B] == blockidx_loop\n\n\nif __name__ == \"__main__\":\n    test_buffer_load_store()\n    test_opaque_access()\n    test_lca_func_root()\n    test_match_buffer()\n    test_global_buffer_with_blockidx()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_estimate_tir_flops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nimport pytest\n\nimport tvm.testing\nfrom tvm.ir import IRModule\nfrom tvm.meta_schedule.testing.te_workload import create_te_workload\nfrom tvm.script import tir as T\nfrom tvm.tir.analysis import estimate_tir_flops\n\n\n@pytest.mark.parametrize(\n    \"workload, flops\",\n    [\n        (\"C1D\", 6291456),\n        (\"C2D\", 236027904),\n        (\"C3D\", 13217562624),\n        (\"CAP\", 75497472),\n        (\"DEP\", 7225344),\n        (\"DIL\", 223552896),\n        (\"GMM\", 4194304),\n        (\"GRP\", 28901376),\n        (\"T2D\", 268435456),\n        (\"CBR\", 239239168),\n        (\"TBG\", 25165824),\n        (\"NRM\", 131072),\n        (\"SFM\", 262144),\n    ],\n)\ndef test_te_workload(workload, flops):\n    te_workload = create_te_workload(workload, 0)\n    mod = IRModule({\"main\": te_workload})\n    assert float(flops) == estimate_tir_flops(mod)\n\n\n@T.prim_func\ndef flops_with_let(a: T.Buffer[16, \"float32\"]):\n    for i in range(8):\n        j = i + 8\n        a[j] = a[i]\n\n\ndef test_flops_with_let():\n    flops = estimate_tir_flops(IRModule({\"main\": flops_with_let}))\n    assert flops == 8\n\n\n@T.prim_func\ndef flops_with_if(a: T.Buffer[16, \"float32\"], b: T.Buffer[16, \"float32\"]):\n    for i in range(16):\n        if i % 2 == 0:\n            a[i] = b[i]\n        else:\n            if i % 3 == 0:\n                a[i] = b[i - 1] + b[i - 2]\n\n\ndef test_flops_with_if():\n    flops = estimate_tir_flops(IRModule({\"main\": flops_with_if}))\n    assert flops == 16\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_expr_deep_equal.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_equal_expr():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n\n    def func1():\n        return x + y + 1\n\n    def func2():\n        return te.exp(tvm.tir.truncdiv((x + y + 1) * y, 4))\n\n    assert tvm.tir.analysis.expr_deep_equal(func1(), func1())\n    assert tvm.tir.analysis.expr_deep_equal(func2(), func2())\n    assert not tvm.tir.analysis.expr_deep_equal(func2(), func1())\n\n\nif __name__ == \"__main__\":\n    test_equal_expr()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_get_block_access_region.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.ir import Range\n\n\n@T.prim_func\ndef func() -> None:\n    A = T.alloc_buffer((128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.alloc_buffer((128, 128), \"float32\")\n    D = T.alloc_buffer((128, 128), \"float32\")\n    with T.block():\n        # Need add read/write region manually to avoid triggering block access region detector\n        T.reads([B[0, 0], C[0:16, 0:16], A[4:12, 4:12]])\n        T.writes([A[0:12, 0:12]])\n        for i, j in T.grid(8, 8):\n            A[i, j] = B[0, 0] + C[0, 0]\n        for i, j in T.grid(2, 2):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads([A[vi * 4 + 4 : vi * 4 + 8, vj * 4 + 4 : vj * 4 + 8], C[12:16, 12:16]])\n                T.writes([A[vi * 4 + 4 : vi * 4 + 8, vj * 4 + 4 : vj * 4 + 8]])\n                for i, j in T.grid(4, 4):\n                    A[vi * 4 + 4 + i, vj * 4 + 4 + j] += C[i + 12, j + 12]\n        T.evaluate(D.data)\n\n\n@T.prim_func\ndef match_buffer_func() -> None:\n    with T.block(\"root\"):\n        A = T.alloc_buffer((128, 128), \"float32\")\n        B = T.alloc_buffer((128, 128), \"float32\")\n        T.reads([])\n        T.writes([])\n        # Need add read/write region manually to avoid triggering block access region detector\n        for i, j in T.grid(8, 8):\n            with T.block(\"block\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(B[vi * 16 + 2 : vi * 16 + 12, vj * 16 + 2 : vj * 16 + 16])\n                T.writes(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                AA = T.match_buffer(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16], (16, 16))\n                B0 = T.match_buffer(B[vi * 16 + 2 : vi * 16 + 6, vj * 16 + 2 : vj * 16 + 6], (4, 4))\n                B1 = T.match_buffer(\n                    B[vi * 16 + 8 : vi * 16 + 12, vj * 16 + 8 : vj * 16 + 16], (4, 8)\n                )\n                for ii, jj in T.grid(16, 16):\n                    with T.block(\"AAA\"):\n                        vii, vjj = T.axis.remap(\"SS\", [ii, jj])\n                        T.reads([])\n                        T.writes(AA[vii, vjj])\n                        AAA = T.match_buffer(AA[vii, vjj], ())\n                        AAA[()] = 1.0\n                T.evaluate(B0.data)\n                T.evaluate(B1.data)\n\n\n@T.prim_func\ndef opaque_block_func() -> None:\n    with T.block(\"root\"):\n        A = T.alloc_buffer((16, 16), \"float32\")\n        B = T.alloc_buffer((16, 16), \"float32\")\n        T.reads([])\n        T.writes([])\n        # Need add read/write region manually to avoid triggering block access region detector\n        for i in range(0, 16):\n            with T.block():\n                T.reads(A[i, 0:16])\n                T.writes([B[i, 0:16]])\n                for j in range(0, 16):\n                    with T.block():\n                        T.reads(A[i, j])\n                        T.writes(B[i, j])\n                        B[i, j] = A[i, j] + 1.0\n\n\n@T.prim_func\ndef opaque_access_func() -> None:\n    A = T.alloc_buffer([1024])\n    B = T.alloc_buffer([1024])\n    for i in T.serial(0, 8):\n        with T.block():\n            v = T.axis.S(8, i)\n            T.reads([A[v * 128 : v * 128 + 128]])\n            T.writes([B[v * 128 : v * 128 + 128]])\n            T.evaluate(\n                T.call_extern(\"test\", B.data, v * 128, 128, A.data, v * 128, 128, dtype=\"float32\")\n            )\n\n\n@T.prim_func\ndef opaque_access_with_tvm_access_ptr_func() -> None:\n    A = T.alloc_buffer([1024])\n    B = T.alloc_buffer([1024])\n    C = T.alloc_buffer([1024])\n    with T.block(\"opaque\"):\n        T.reads(A[0:1024], C[0:1024])\n        T.writes(B[0:1024], C[0:1024])\n        T.evaluate(A.access_ptr(\"r\"))\n        T.evaluate(B.access_ptr(\"w\"))\n        T.evaluate(C.access_ptr(\"rw\"))\n\n\n@T.prim_func\ndef access_in_if_then_else_func() -> None:\n    A = T.alloc_buffer([8])\n    B = T.alloc_buffer([8])\n    with T.block():\n        T.reads([A[0:5]])\n        T.writes([B[0:8]])\n        for i in T.serial(0, 8):\n            B[i] = T.if_then_else(i < 5, A[i], 0.0, dtype=\"float32\")\n\n\n@T.prim_func\ndef access_in_branch_func() -> None:\n    A = T.alloc_buffer([8])\n    B = T.alloc_buffer([8])\n    with T.block():\n        T.reads([A[0:7]])\n        T.writes([B[0:8]])\n        for i in T.serial(0, 8):\n            if i < 5:\n                B[i] = A[i] + 1.0\n            else:\n                B[i] = A[i - 1]\n\n\n@T.prim_func\ndef gemm() -> None:\n    A = T.alloc_buffer([16, 16], \"float32\")\n    B = T.alloc_buffer([16, 16], \"float32\")\n    C = T.alloc_buffer([16, 16], \"float32\")\n    for i, j, k, ii, jj in T.grid(4, 4, 16, 4, 4):\n        with T.block(\"update\"):\n            vi = T.axis.S(16, i * 4 + ii)\n            vj = T.axis.S(16, j * 4 + jj)\n            vk = T.axis.R(16, k)\n            T.reads(A[vi, vk], B[vj, vk])\n            T.writes(C[vi, vj])\n            with T.init():\n                C[vi, vj] = 0\n            C[vi, vj] += A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef decomposed_gemm() -> None:\n    A = T.alloc_buffer([16, 16], \"float32\")\n    B = T.alloc_buffer([16, 16], \"float32\")\n    C = T.alloc_buffer([16, 16], \"float32\")\n    for i, j in T.grid(4, 4):\n        for ii, jj in T.grid(4, 4):\n            with T.block(\"init\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                T.reads([])\n                T.writes(C[vi, vj])\n                C[vi, vj] = 0\n        for k, ii, jj in T.grid(16, 4, 4):\n            with T.block(\"update\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                vk = T.axis.R(16, k)\n                T.reads(C[vi, vj], A[vi, vk], B[vj, vk])\n                T.writes(C[vi, vj])\n                C[vi, vj] += A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef access_of_padding_pattern() -> None:\n    X = T.alloc_buffer([28, 28])\n    X_pad = T.alloc_buffer([32, 32])\n    Y = T.alloc_buffer([28, 28])\n    for i, j in T.grid(32, 32):\n        with T.block(\"padding\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([X[vi - 2, vj - 2]])\n            T.writes([X_pad[vi, vj]])\n            X_pad[vi, vj] = T.if_then_else(\n                2 <= vi and vi < 30 and 2 <= vj and vj < 30, X[vi - 2, vj - 2], 0.0, dtype=\"float32\"\n            )\n        with T.block(\"padding_reverse\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([X_pad[vi, vj]])\n            T.writes([Y[vi - 2, vj - 2]])\n            if 2 <= vi and vi < 30 and 2 <= vj and vj < 30:\n                Y[vi - 2, vj - 2] = X_pad[vi, vj]\n\n\ndef test_block_access_region_detector():\n    block = func.body.block.body.block\n    alloc_buffers = func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n    ret = tir.analysis.get_block_access_region(block, buffer_var_map)\n\n    tvm.ir.assert_structural_equal(block.reads, ret[0])\n    tvm.ir.assert_structural_equal(block.writes, ret[1])\n    D = alloc_buffers[-1]\n    tvm.ir.assert_structural_equal(\n        [tvm.tir.BufferRegion(D, [Range(0, 128), Range(0, 128)])], ret[2]\n    )\n\n\ndef test_opaque_block():\n    alloc_buffers = opaque_block_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n\n    block0 = opaque_block_func.body.block.body.body.block\n    ret = tir.analysis.get_block_access_region(block0, buffer_var_map)\n    tvm.ir.assert_structural_equal(block0.reads, ret[0])\n    tvm.ir.assert_structural_equal(block0.writes, ret[1])\n\n    block1 = block0.body.body.block\n    ret = tir.analysis.get_block_access_region(block1, buffer_var_map)\n    tvm.ir.assert_structural_equal(block1.reads, ret[0])\n    tvm.ir.assert_structural_equal(block1.writes, ret[1])\n\n\ndef test_opaque_access():\n    block = opaque_access_func.body.block.body.body.block\n    alloc_buffers = opaque_access_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n\n    ret0 = tir.analysis.get_block_read_write_region(block, buffer_var_map)\n    ret1 = tir.analysis.get_block_access_region(block, buffer_var_map)\n    with pytest.raises(ValueError):\n        tvm.ir.assert_structural_equal(ret0[0], ret1[0])\n    with pytest.raises(ValueError):\n        tvm.ir.assert_structural_equal(ret0[1], ret1[1])\n\n\ndef test_opaque_access_with_tvm_access_ptr():\n    block = opaque_access_with_tvm_access_ptr_func.body.block.body.block\n    alloc_buffers = opaque_access_with_tvm_access_ptr_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n\n    ret0 = tir.analysis.get_block_read_write_region(block, buffer_var_map)\n    ret1 = tir.analysis.get_block_access_region(block, buffer_var_map)\n    tvm.ir.assert_structural_equal(block.reads, ret0[0])\n    tvm.ir.assert_structural_equal(block.writes, ret0[1])\n    with pytest.raises(ValueError):\n        tvm.ir.assert_structural_equal(ret0[0], ret1[0])\n    with pytest.raises(ValueError):\n        tvm.ir.assert_structural_equal(ret0[1], ret1[1])\n\n\ndef test_match_buffer():\n    root_block = match_buffer_func.body.block\n    block = root_block.body.body.body.block\n    block_inner = block.body[0].body.body.block\n    alloc_buffers = match_buffer_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n\n    # Check block\n    ret = tir.analysis.get_block_access_region(block, buffer_var_map)\n    tvm.ir.assert_structural_equal(block.writes, ret[1])\n    # B is opaque access\n    tvm.ir.assert_structural_equal(block.reads, ret[2])\n\n    # Check inner block AAA without updating buffer_var_map\n    ret = tir.analysis.get_block_access_region(block_inner, buffer_var_map)\n    # Since AA is not in the buffer_var_map, region of AA will not be collected.\n    tvm.ir.assert_structural_equal([], ret[1])\n\n    # Check inner block AAA\n    for match_buffer in block.match_buffers:\n        target_buffer = match_buffer.buffer\n        buffer_var_map[target_buffer.data] = target_buffer\n\n    ret = tir.analysis.get_block_access_region(block_inner, buffer_var_map)\n    tvm.ir.assert_structural_equal(block_inner.reads, ret[0])\n    tvm.ir.assert_structural_equal(block_inner.writes, ret[1])\n\n\ndef test_access_in_if_then_else_func():\n    block = access_in_if_then_else_func.body.block.body.block\n    alloc_buffers = access_in_if_then_else_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n    ret0 = tir.analysis.get_block_read_write_region(block, buffer_var_map)\n    ret1 = tir.analysis.get_block_access_region(block, buffer_var_map)\n    tvm.ir.assert_structural_equal(ret0[0], ret1[0])\n    tvm.ir.assert_structural_equal(ret0[1], ret1[1])\n\n\ndef test_access_in_branch_func():\n    block = access_in_branch_func.body.block.body.block\n    alloc_buffers = access_in_branch_func.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n    ret0 = tir.analysis.get_block_read_write_region(block, buffer_var_map)\n    ret1 = tir.analysis.get_block_access_region(block, buffer_var_map)\n    tvm.ir.assert_structural_equal(ret0[0], ret1[0])\n    tvm.ir.assert_structural_equal(ret0[1], ret1[1])\n\n\ndef test_access_of_padding_pattern():\n    s = tvm.tir.schedule.Schedule(access_of_padding_pattern)\n    alloc_buffers = s.get_sref(s.get_block(\"root\")).stmt.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n\n    def do_compare_buffer_region(region, expect):\n        assert region.buffer == expect.buffer\n        analyzer = tvm.arith.Analyzer()\n        for observed_range, expected_range in zip(region.region, expect.region):\n            analyzer.can_prove_equal(observed_range.min, expected_range.min)\n            analyzer.can_prove_equal(observed_range.extent, expected_range.extent)\n\n    def do_check_block(block_name):\n        block = s.get_sref(s.get_block(block_name)).stmt\n        expect_reads = block.reads\n        expect_writes = block.writes\n        ret = tir.analysis.get_block_access_region(block, buffer_var_map)\n        for i, read in enumerate(ret[0]):\n            do_compare_buffer_region(read, expect_reads[i])\n        for i, write in enumerate(ret[1]):\n            do_compare_buffer_region(write, expect_writes[i])\n\n    do_check_block(\"padding\")\n    do_check_block(\"padding_reverse\")\n\n\ndef test_access_of_reduction():\n    block = gemm.body.block.body.body.body.body.body.body.block\n    alloc_buffers = gemm.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n    ret = tir.analysis.get_block_access_region(block, buffer_var_map)\n    tvm.ir.assert_structural_equal(block.reads, ret[0])\n    tvm.ir.assert_structural_equal(block.writes, ret[1])\n\n\ndef test_access_of_decompose_reduction():\n    init = decomposed_gemm.body.block.body.body.body[0].body.body.block\n    update = decomposed_gemm.body.block.body.body.body[1].body.body.body.block\n    alloc_buffers = decomposed_gemm.body.block.alloc_buffers\n    buffer_var_map = {buf.data: buf for buf in alloc_buffers}\n    for block in [init, update]:\n        ret = tir.analysis.get_block_access_region(block, buffer_var_map)\n        tvm.ir.assert_structural_equal(block.reads, ret[0])\n        tvm.ir.assert_structural_equal(block.writes, ret[1])\n\n\nif __name__ == \"__main__\":\n    test_block_access_region_detector()\n    test_opaque_block()\n    test_opaque_access()\n    test_opaque_access_with_tvm_access_ptr()\n    test_match_buffer()\n    test_access_in_if_then_else_func()\n    test_access_in_branch_func()\n    test_access_of_padding_pattern()\n    test_access_of_reduction()\n    test_access_of_decompose_reduction()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_oob.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef bad_load(A: T.Buffer[(2, 3), \"float32\"], B: T.Buffer[(3, 2), \"float32\"]):\n    B[0, 0] = A[2, 2]\n\n\n@T.prim_func\ndef bad_load_loop(A: T.Buffer[(2, 3), \"float32\"], B: T.Buffer[(3, 2), \"float32\"]):\n    for i in range(3):\n        B[i, 0] = A[i, 2]\n\n\n@T.prim_func\ndef bad_store(A: T.Buffer[(2, 3), \"float32\"], B: T.Buffer[(3, 2), \"float32\"]):\n    B[0, 3] = A[1, 2]\n\n\n@T.prim_func\ndef bad_store_loop(A: T.Buffer[(2, 3), \"float32\"], B: T.Buffer[(3, 2), \"float32\"]):\n    for i in range(3):\n        B[0, i] = A[1, i]\n\n\n@T.prim_func\ndef unknown_bounds(A: T.Buffer[(2, 3), \"float32\"], B: T.Buffer[(3, 2), \"float32\"]):\n    N = T.var(\"int32\")\n    for i in range(3):\n        B[0, N] = A[1, i]\n\n\ndef test_oob_load():\n    with pytest.raises(tvm.tir.ScheduleError) as err:\n        tvm.tir.analysis.OOBChecker()(tvm.IRModule.from_expr(bad_load))\n    assert \"buffer A\" in err.value.args[0]\n\n    with pytest.raises(tvm.tir.ScheduleError) as err:\n        tvm.tir.analysis.OOBChecker()(tvm.IRModule.from_expr(bad_load_loop))\n    assert \"buffer A\" in err.value.args[0]\n\n\ndef test_oob_store():\n    with pytest.raises(tvm.tir.ScheduleError) as err:\n        tvm.tir.analysis.OOBChecker()(tvm.IRModule.from_expr(bad_store))\n    assert \"buffer B\" in err.value.args[0]\n\n    with pytest.raises(tvm.tir.ScheduleError) as err:\n        tvm.tir.analysis.OOBChecker()(tvm.IRModule.from_expr(bad_store_loop))\n    assert \"buffer B\" in err.value.args[0]\n\n\ndef test_unknown_bounds():\n    # This should not return an error as we can't probe that N goes out of bounds\n    tvm.tir.analysis.OOBChecker()(tvm.IRModule.from_expr(unknown_bounds))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_stmt_finding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te, topi\nfrom tvm.meta_schedule.testing.te_workload import conv2d_winograd_nhwc, matmul\nfrom tvm.tir.analysis import find_anchor_block\n\n\ndef test_matmul_add():\n    n = m = k = 128\n    A, B, C = matmul(n, m, k)\n    mod = tvm.IRModule()\n    mod[\"main\"] = te.create_prim_func([A, B, C + A])\n\n    block = find_anchor_block(mod)\n\n    assert block.name_hint == \"C\"\n\n\ndef test_winograd():\n    mod = tvm.IRModule()\n    mod[\"main\"] = te.create_prim_func(conv2d_winograd_nhwc(1, 14, 14, 128, 128, 6))\n\n    block = find_anchor_block(mod)\n\n    assert block.name_hint == \"bgemm\"\n\n\ndef test_no_anchor_block():\n    inp = te.placeholder((10,), name=\"input\")\n    out = topi.nn.relu(inp + 1.0)\n    mod = tvm.IRModule()\n    mod[\"main\"] = te.create_prim_func([inp, out])\n\n    assert find_anchor_block(mod) is None\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_usedef.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te\n\n\n@pytest.mark.xfail\ndef test_loop_dependent_allocate():\n    N = te.size_var(\"N\")\n    A = te.placeholder((2 * N,), \"float32\", \"A\")\n    C = te.compute((N,), lambda i: A[2 * i] + A[i + 1], name=\"C\")\n    s = te.create_schedule(C.op)\n    AA = s.cache_read(A, \"local\", [C])\n    s[AA].compute_at(s[C], s[C].op.axis[0])\n    # this line should fail due to IRUseDefAnalysis sees an allocate statement\n    # referencing undefined variable\n    tvm.lower(s, [A, C])\n\n\nif __name__ == \"__main__\":\n    test_loop_dependent_allocate()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_verify_gpu_code.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test gpu code verifier\"\"\"\nimport tvm\nfrom tvm import te\nfrom tvm import topi\nimport tvm.testing\nimport tvm.topi.testing\n\n\ndef get_verify_pass(valid, **kwargs):\n    def _fverify(f, *_):\n        valid[0] = tvm.tir.analysis.verify_gpu_code(f, kwargs)\n        return f\n\n    return tvm.tir.transform.prim_func_pass(_fverify, opt_level=0)\n\n\n@tvm.testing.requires_gpu\ndef test_shared_memory():\n    def check_shared_memory(storage_scope, dtype):\n        N = 1024\n        M = 128\n\n        tvm_type = tvm.runtime.DataType(dtype)\n        type_size = tvm_type.bits // 8 * tvm_type.lanes\n\n        A = te.placeholder((N,), name=\"A\", dtype=dtype)\n        B = te.compute((N,), lambda i: A[i], name=\"B\")\n\n        s = te.create_schedule([B.op])\n        AA = s.cache_read(A, storage_scope, [B])\n        o, i = s[B].split(s[B].op.axis[0], M)\n        s[AA].compute_at(s[B], o)\n        s[B].bind(o, te.thread_axis(\"blockIdx.x\"))\n        s[B].bind(i, te.thread_axis(\"threadIdx.x\"))\n\n        # shared memory usage: M * sizeof(dtype) Bytes\n        # thread usage: M\n\n        for target in [\"opencl\", \"cuda\"]:\n            if not tvm.testing.device_enabled(target):\n                continue\n            valid = [None]\n            with tvm.transform.PassContext(\n                config={\n                    \"tir.add_lower_pass\": [\n                        (\n                            2,\n                            get_verify_pass(\n                                valid,\n                                max_shared_memory_per_block=type_size * M - 1,\n                                max_threads_per_block=M,\n                            ),\n                        )\n                    ]\n                }\n            ):\n                tvm.build(s, [A, B], target)\n            assert not valid[0]\n\n            with tvm.transform.PassContext(\n                config={\n                    \"tir.add_lower_pass\": [\n                        (\n                            2,\n                            get_verify_pass(\n                                valid,\n                                max_shared_memory_per_block=type_size * M,\n                                max_threads_per_block=M,\n                            ),\n                        )\n                    ]\n                }\n            ):\n                tvm.build(s, [A, B], target)\n            assert valid[0]\n\n    check_shared_memory(\"shared\", \"float32\")\n    check_shared_memory(\"shared\", \"int8x4\")\n    check_shared_memory(\"shared.dyn\", \"float32\")\n\n\n@tvm.testing.requires_gpu\ndef test_local_memory():\n    N = 1024\n    M = 128\n\n    A = te.placeholder((N,), name=\"A\", dtype=\"float32\")\n    B = te.compute((N,), lambda i: A[i], name=\"B\")\n\n    s = te.create_schedule([B.op])\n    AA = s.cache_read(A, \"local\", [B])\n    o, i = s[B].split(s[B].op.axis[0], M)\n    s[AA].compute_at(s[B], o)\n    s[B].bind(o, te.thread_axis(\"blockIdx.x\"))\n\n    # local memory usage: M * 4B\n    # thread usage: M\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_local_memory_per_block=4 * M - 1, max_threads_per_block=1\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert not valid[0]\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_local_memory_per_block=4 * M, max_threads_per_block=1\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_num_thread():\n    N = 1024\n    M = 128\n\n    A = te.placeholder((N,), name=\"A\", dtype=\"float32\")\n    B = te.compute((N,), lambda i: A[i], name=\"B\")\n\n    s = te.create_schedule([B.op])\n    o, i = s[B].split(s[B].op.axis[0], M)\n\n    s[B].bind(o, te.thread_axis(\"threadIdx.x\"))\n    s[B].bind(i, te.thread_axis(\"threadIdx.y\"))\n\n    # shared memory usage: 0\n    # thread usage: N\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_shared_memory_per_block=0, max_threads_per_block=N - 1\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert not valid[0]\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_shared_memory_per_block=0, max_threads_per_block=N\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert valid[0]\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid,\n                            max_shared_memory_per_block=0,\n                            max_threads_per_block=N,\n                            max_thread_y=M - 1,\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert not valid[0]\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid,\n                            max_shared_memory_per_block=0,\n                            max_threads_per_block=N,\n                            max_thread_y=M,\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_multiple_kernels():\n    N = 1024\n\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.compute((N, N), lambda i, j: A[i, j])\n    C = te.compute((N, N), lambda i, j: B[i, j])\n\n    s = te.create_schedule([C.op])\n\n    s[C].bind(s[C].op.axis[1], te.thread_axis(\"threadIdx.x\"))\n    s[B].bind(s[B].op.axis[1], te.thread_axis(\"threadIdx.x\"))\n\n    # shared memory usage: 0\n    # thread usage: N\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_shared_memory_per_block=0, max_threads_per_block=N - 1\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, C], target)\n        assert not valid[0]\n\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [\n                    (\n                        2,\n                        get_verify_pass(\n                            valid, max_shared_memory_per_block=0, max_threads_per_block=N\n                        ),\n                    )\n                ]\n            }\n        ):\n            tvm.build(s, [A, C], target)\n        assert valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_wrong_bind():\n    N = 1024\n\n    A = te.placeholder((N, N - 1), name=\"A\")\n    B = te.compute((N, N - 1), lambda i, j: A[i, j])\n\n    s = te.create_schedule([B.op])\n\n    # bind a thread axis to two loop axes with different lengths\n    s[B].bind(s[B].op.axis[0], te.thread_axis(\"threadIdx.x\"))\n    s[B].bind(s[B].op.axis[1], te.thread_axis(\"threadIdx.x\"))\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\n                \"tir.add_lower_pass\": [(2, get_verify_pass(valid, max_threads_per_block=N * N))]\n            }\n        ):\n            tvm.build(s, [A, B], target)\n        assert not valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_vectorize():\n    N = 1024\n\n    A = te.placeholder((N, N), name=\"A\")\n    B = te.compute((N, N), lambda i, j: A[i, j])\n\n    s = te.create_schedule([B.op])\n\n    i, j = s[B].op.axis\n\n    s[B].bind(i, te.thread_axis(\"blockIdx.x\"))\n    jo, ji = s[B].split(j, factor=64)\n    s[B].bind(jo, te.thread_axis(\"threadIdx.x\"))\n    s[B].vectorize(ji)\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\"tir.add_lower_pass\": [(2, get_verify_pass(valid, max_vector_bytes=16))]}\n        ):\n            tvm.lower(s, [A, B])\n        assert not valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_vectorize_half():\n    N = 1024\n\n    A = te.placeholder((N, N), name=\"A\", dtype=\"float16\")\n    B = te.compute((N, N), lambda i, j: A[i, j])\n\n    s = te.create_schedule([B.op])\n\n    i, j = s[B].op.axis\n\n    s[B].bind(i, te.thread_axis(\"blockIdx.x\"))\n    jo, ji = s[B].split(j, factor=8)\n    s[B].bind(jo, te.thread_axis(\"threadIdx.x\"))\n    s[B].vectorize(ji)\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\"tir.add_lower_pass\": [(2, get_verify_pass(valid, max_vector_bytes=16))]}\n        ):\n            tvm.lower(s, [A, B])\n        assert valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_vectorize_strided():\n    N = 1024\n\n    A = te.placeholder((N, N), name=\"A\", dtype=\"float16\")\n    B = te.compute((N, N), lambda i, j: A[j, i])\n\n    s = te.create_schedule([B.op])\n\n    i, j = s[B].op.axis\n\n    s[B].bind(i, te.thread_axis(\"blockIdx.x\"))\n    jo, ji = s[B].split(j, factor=8)\n    s[B].vectorize(ji)\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n        with tvm.transform.PassContext(\n            config={\"tir.add_lower_pass\": [(2, get_verify_pass(valid, max_vector_bytes=16))]}\n        ):\n            tvm.lower(s, [A, B])\n        assert not valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_vthread():\n    N = 1024\n\n    A = te.placeholder((N, 16), name=\"A\")\n    B = te.compute((N, 16), lambda i, j: A[i, j])\n\n    s = te.create_schedule([B.op])\n\n    s[B].bind(s[B].op.axis[0], te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(s[B].op.axis[1], te.thread_axis(\"vthread\"))\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n\n        valid = [None]\n\n        for phase in [1, 2]:\n            with tvm.transform.PassContext(\n                config={\"tir.add_lower_pass\": [(phase, get_verify_pass(valid, max_vthread=16))]}\n            ):\n                tvm.build(s, [A, B], target)\n            assert valid[0]\n\n            with tvm.transform.PassContext(\n                config={\"tir.add_lower_pass\": [(phase, get_verify_pass(valid, max_vthread=15))]}\n            ):\n                tvm.build(s, [A, B], target)\n            assert not valid[0]\n\n\n@tvm.testing.requires_gpu\ndef test_redundant_kernels():\n    dtype = \"float32\"\n    A = te.placeholder(shape=(1,), name=\"A\", dtype=dtype)\n    B = te.placeholder(shape=(1,), name=\"B\", dtype=dtype)\n    C = te.placeholder(shape=(1,), name=\"C\", dtype=dtype)\n    D = topi.less(A, C)\n    E = topi.less(B, C)\n    F = topi.logical_or(D, E)\n    G = topi.identity(F)\n\n    for target in [\"opencl\", \"cuda\"]:\n        if not tvm.testing.device_enabled(target):\n            continue\n        print(\"Running on target: %s\" % target)\n        valid = [None]\n\n        with tvm.target.Target(target):\n            s = tvm.topi.testing.get_reduce_schedule(target)(G)\n\n        with tvm.transform.PassContext(\n            config={\"tir.add_lower_pass\": [(2, get_verify_pass(valid, max_kernels=1))]}\n        ):\n            tvm.build(s, [A, B, C, G], target)\n        assert valid[0]\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_verify_memory.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport pytest\nfrom tvm import te\nimport tvm.testing\n\n# The following DLDeviceType/TVMDeviceExtType values\n# are originally defined in dlpack.h and c_runtime_api.h.\ngpu_devices = [\"cuda\", \"opencl\", \"metal\", \"vulkan\"]\nother_devices = [\"llvm\", \"ext_dev\"]\n\n\n# All computations are bound.\n# So VerifyMemory pass is expected to succeed.\n#\n@tvm.testing.uses_gpu\ndef test_verify_memory_all_bind():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda i: A[i] + 1.0, name=\"B\")\n\n    # B is bound to threads.\n    s = te.create_schedule(B.op)\n    bx, tx = s[B].split(B.op.axis[0], factor=64)\n    s[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    mod = tvm.lower(s, [A, B])\n\n    for dev_type in gpu_devices + other_devices:\n        if tvm.testing.device_enabled(dev_type):\n            binded_mod = tvm.tir.transform.Apply(\n                lambda f: f.with_attr(\"target\", tvm.target.Target(dev_type))\n            )(mod)\n            tvm.tir.transform.VerifyMemory()(binded_mod)\n\n\n# Computations are not bound.\n# So VerifyMemory pass fails when device type is GPU.\n#\n@tvm.testing.uses_gpu\ndef test_verify_memory_not_bind():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda i: A[i] + 1.0, name=\"B\")\n\n    # B is not bound to threads.\n    s = te.create_schedule(B.op)\n\n    mod = tvm.lower(s, [A, B])\n\n    for dev_type in gpu_devices:\n        if tvm.testing.device_enabled(dev_type):\n            binded_mod = tvm.tir.transform.Apply(\n                lambda f: f.with_attr(\"target\", tvm.target.Target(dev_type))\n            )(mod)\n            with pytest.raises(RuntimeError):\n                tvm.tir.transform.VerifyMemory()(binded_mod)\n\n    for dev_type in other_devices:\n        if tvm.testing.device_enabled(dev_type):\n            binded_mod = tvm.tir.transform.Apply(\n                lambda f: f.with_attr(\"target\", tvm.target.Target(dev_type))\n            )(mod)\n            tvm.tir.transform.VerifyMemory()(binded_mod)\n\n\n# Computations are partially bound.\n# So VerifyMemory pass fails when device type is GPU.\n#\n@tvm.testing.uses_gpu\ndef test_verify_memory_partially_bind():\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda i: A[i] + 1.0, name=\"B\")\n    C = te.compute(B.shape, lambda i: B[i] + 2.0, name=\"C\")\n    D = te.compute(C.shape, lambda i: C[i] + 2.0, name=\"D\")\n\n    # C is bound to threads, but B and D are not.\n    s = te.create_schedule([B.op, C.op, D.op])\n    bx, tx = s[C].split(C.op.axis[0], factor=64)\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    mod = tvm.lower(s, [A, B, C, D])\n\n    for dev_type in gpu_devices:\n        if tvm.testing.device_enabled(dev_type):\n            binded_mod = tvm.tir.transform.Apply(\n                lambda f: f.with_attr(\"target\", tvm.target.Target(dev_type))\n            )(mod)\n            with pytest.raises(RuntimeError):\n                tvm.tir.transform.VerifyMemory()(binded_mod)\n\n    for dev_type in other_devices:\n        if tvm.testing.device_enabled(dev_type):\n            binded_mod = tvm.tir.transform.Apply(\n                lambda f: f.with_attr(\"target\", tvm.target.Target(dev_type))\n            )(mod)\n            tvm.tir.transform.VerifyMemory()(binded_mod)\n\n\nif __name__ == \"__main__\":\n    test_verify_memory_all_bind()\n    test_verify_memory_not_bind()\n    test_verify_memory_partially_bind()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_verify_ssa.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_verify_ssa():\n    x = te.var(\"x\")\n    y = te.var()\n    z = tvm.tir.Evaluate(x + y)\n    assert tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([x, y], z))\n\n    assert not tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([x, y], tvm.tir.LetStmt(x, 1, z)))\n\n\ndef test_verify_weak_let_ssa():\n    x = te.var(\"x\")\n    z1 = tvm.tir.Let(x, 1, x + 1)\n    z2 = tvm.tir.Let(x, 2, x + 2)\n\n    assert tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([], tvm.tir.Evaluate(z1 + z1)))\n    assert not tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([], tvm.tir.Evaluate(z1 * z2)))\n\n\nif __name__ == \"__main__\":\n    test_verify_ssa()\n    test_verify_weak_let_ssa()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_analysis_verify_well_formed.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\n\n\ndef test_pass_simple():\n    @T.prim_func\n    def element_wise(\n        A: T.Buffer[(128, 128), \"float32\"],\n        C: T.Buffer[(128, 128), \"float32\"],\n    ):\n        B = T.alloc_buffer((128, 128), \"float32\")\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for i, j in T.grid(128, 128):\n            with T.block(\"C\"):\n                # It's a opaque block , so it can use outside variables\n                C[i, j] = B[i, j] * 2.0\n\n    assert tvm.tir.analysis.verify_well_formed(element_wise)\n\n\ndef test_fail_use_out_loop_var():\n    @T.prim_func\n    def element_wise(\n        A: T.Buffer[(128, 128), \"float32\"],\n        B: T.Buffer[(128, 128), \"float32\"],\n    ):\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                # we cannot use `i` since it's defined outside the block\n                B[vi, vj] = A[i, vj] * 2.0\n\n    assert not tvm.tir.analysis.verify_well_formed(element_wise, assert_mode=False)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport pytest\nfrom tvm import tir\nfrom tvm._ffi.base import TVMError\nfrom tvm.ir.transform import PassContext\nimport itertools\nimport pytest\n\n\ndef build_tir_func(func):\n    func = func.with_attr(\"global_symbol\", \"main\")\n    pass_ctx = PassContext.current()\n    if pass_ctx.config.get(\"tir.noalias\", True):\n        func = func.with_attr(\"tir.noalias\", True)\n    mod = tvm.IRModule({\"main\": func})\n    func = tvm.build(mod)\n    return func\n\n\ndef test_scalar_add():\n    # All these types should be interchangeable with each other\n    # E.g. float16 + float32 upconverts the float16 --> float32\n    # Meanwhile if an int or float or together the int will be\n    # cast to the float type.\n    lhs_types = [\"float32\", \"float16\", \"int32\", \"int64\"]\n    rhs_types = [\"float32\", \"float16\"]\n    for lhs_type, rhs_type in itertools.product(lhs_types, rhs_types):\n        # Input vars should be float32, we will cast to test for upcasting between them\n        lhs_input = tir.Var(\"lhs\", \"float32\")\n        rhs_input = tir.Var(\"rhs\", \"float32\")\n        lhs = tir.Cast(lhs_type, lhs_input)\n        rhs = tir.Cast(rhs_type, rhs_input)\n        output = lhs + rhs\n        output = tir.ret(output)\n        output = tir.Evaluate(output)\n        func = tir.PrimFunc([lhs_input, rhs_input], output)\n        func = build_tir_func(func)\n        out = func(1.0, 2.0)\n        assert out == 3.0\n\n\ndef assignment_helper(store_dtype, value_dtype):\n    store = tir.Var(\"store\", dtype=store_dtype)\n    value = tir.Var(\"value\", dtype=value_dtype)\n    tir.Let(store, value, body=store)\n\n\ndef test_fail_implicit_downcasts_same_type():\n    # These lists should be sorted\n    bits = [8, 16, 32, 64]\n    for type in [\"float\", \"int\", \"uint\"]:\n        for i in range(len(bits) - 1):\n            with pytest.raises(TVMError):\n                assignment_helper(\n                    store_dtype=f\"{type}{bits[i]}\", value_dtype=f\"{type}{bits[i + 1]}\"\n                )\n\n\ndef test_cast_between_types():\n    # We should only be able to assign values with the same types\n    bits = [16, 32]\n    types = [\"float\", \"int\", \"uint\"]\n    for store_type, store_bits, value_type, value_bits in itertools.product(\n        types, bits, types, bits\n    ):\n        store_dtype = f\"{store_type}{store_bits}\"\n        value_dtype = f\"{value_type}{value_bits}\"\n        if store_dtype == value_dtype:\n            assignment_helper(store_dtype, value_dtype)\n        else:\n            # TODO: we might want to allow casts between uint and int types\n            with pytest.raises(TVMError):\n                assignment_helper(store_dtype, value_dtype)\n\n\ndef test_ret_const():\n    a = tir.const(0)\n    b = tir.ret(a)\n    b = tir.Evaluate(b)\n    func = tir.PrimFunc([], b)\n    func = build_tir_func(func)\n    out = func()\n    assert out == 0\n\n\ndef test_control_flow_jump():\n    ib = tvm.tir.ir_builder.create()\n    a = tir.Var(\"a\", \"float32\")\n    b = tir.Var(\"b\", \"float32\")\n    with ib.if_scope(True):\n        ib.emit(tir.Evaluate(tir.ret(a)))\n    ib.emit(tir.Evaluate(tir.ret(b)))\n    stmt = ib.get()\n    func = tir.PrimFunc([a, b], stmt)\n    func = build_tir_func(func)\n    out = func(1.0, 2.0)\n    assert out == 1.0\n\n\ndef test_exception():\n    with pytest.raises(tvm.TVMError):\n        x = tir.Var(name=1, dtype=\"int\")\n\n\ndef test_eq_ops():\n    a = tir.IntImm(\"int8\", 1)\n    with pytest.raises(ValueError):\n        assert a != None\n    with pytest.raises(ValueError):\n        assert not a == None\n    b = tir.StringImm(\"abc\")\n    assert b != None\n    assert not b == None\n\n\nif __name__ == \"__main__\":\n    test_scalar_add()\n    test_ret_const()\n    test_control_flow_jump()\n    test_exception()\n    test_eq_ops()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.tir import Buffer\nimport numpy as np\n\n\ndef test_buffer():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    l = te.size_var(\"l\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\")\n    Bb = tvm.tir.decl_buffer((n, l), \"float32\")\n\n    assert isinstance(Ab, tvm.tir.Buffer)\n    assert Ab.dtype == \"float32\"\n    assert tuple(Ab.shape) == (m, n)\n\n\ndef test_buffer_access_ptr():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\", strides=[n + 1, 1])\n    aptr = Ab.access_ptr(\"rw\")\n    assert tvm.ir.structural_equal(aptr.args[3], Ab.strides[0] * m)\n    assert aptr.args[0].dtype == Ab.dtype\n    assert aptr.args[4].value == Buffer.READ | Buffer.WRITE\n    aptr = Ab.access_ptr(\"w\")\n    assert aptr.args[4].value == Buffer.WRITE\n\n\ndef test_buffer_access_ptr_offset():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\")\n    aptr = Ab.access_ptr(\"rw\", offset=100)\n    tvm.testing.assert_prim_expr_equal(aptr.args[2], 100)\n    assert aptr.args[4].value == Buffer.READ | Buffer.WRITE\n    v = te.size_var(\"int32\")\n    aptr = Ab.access_ptr(\"rw\", offset=100 + 100 + v)\n    tvm.testing.assert_prim_expr_equal(aptr.args[2], 200 + v)\n    assert aptr.args[4].value == Buffer.READ | Buffer.WRITE\n    aptr = Ab.access_ptr(\"rw\", offset=tvm.tir.call_extern(\"int32\", \"test_call\", 100 + 100 + v))\n    tvm.testing.assert_prim_expr_equal(\n        aptr.args[2], tvm.tir.call_extern(\"int32\", \"test_call\", 200 + v)\n    )\n    assert aptr.args[4].value == Buffer.READ | Buffer.WRITE\n\n\ndef test_buffer_access_ptr_extent():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\")\n    aptr = Ab.access_ptr(\"rw\")\n    assert tvm.ir.structural_equal(aptr.args[3], m * n)\n    aptr = Ab.access_ptr(\"rw\", offset=100)\n    assert tvm.ir.structural_equal(aptr.args[3], m * n - 100)\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\", strides=[n + 1, 1])\n    aptr = Ab.access_ptr(\"rw\", offset=100)\n    assert tvm.ir.structural_equal(aptr.args[3], Ab.strides[0] * m - 100)\n\n    # Test extent from input params\n    aptr = Ab.access_ptr(\"rw\", extent=200)\n    assert tvm.ir.structural_equal(aptr.args[3], 200)\n    aptr = Ab.access_ptr(\"rw\", offset=100, extent=100)\n    assert tvm.ir.structural_equal(aptr.args[3], 100)\n\n\ndef test_buffer_vload():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\", elem_offset=100)\n    load = Ab.vload([2, 3])\n    tvm.ir.assert_structural_equal(load.indices, [2, 3])\n\n\ndef test_buffer_offset_of():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((m, n), \"float32\", elem_offset=100)\n    offset = Ab.offset_of([2, 3])\n    tvm.ir.assert_structural_equal(offset, [n * 2 + 103])\n\n\ndef test_buffer_vload_nullptr():\n    var = tvm.tir.Var(\"v\", dtype=\"int32\")\n    buf = tvm.tir.decl_buffer((1,), name=\"buf\")\n    buf_load = tvm.tir.expr.BufferLoad(buffer=buf, indices=tvm.runtime.convert([0]))\n    buf_load_stmt = tvm.tir.stmt.Evaluate(buf_load)\n    for_loop = tvm.tir.stmt.For(\n        loop_var=var, kind=0, min_val=0, extent=tvm.tir.Cast(\"int32\", buf_load), body=buf_load_stmt\n    )\n    buf_func = tvm.tir.PrimFunc(params={}, body=for_loop)\n    mod = tvm.IRModule({\"main\": buf_func})\n    # Trigger nullptr buffer bug by pass\n    with pytest.raises(tvm.error.TVMError) as cm:\n        mod = tvm.transform.Sequential(\n            [\n                tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(),\n                tvm.tir.transform.CompactBufferAllocation(),\n                tvm.tir.transform.LowerOpaqueBlock(),\n                tvm.tir.transform.FlattenBuffer(),\n            ]\n        )(mod)\n        assert \"(n != nullptr) is false\" in str(cm.execption)\n\n\ndef test_buffer_index_merge_mult_mod():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    s = te.size_var(\"s\")\n    k0 = te.size_var(\"k0\")\n    k1 = te.size_var(\"k1\")\n    A = tvm.tir.decl_buffer((m, n), \"float32\")\n    A_stride = tvm.tir.decl_buffer((m, n), \"float32\", strides=(s, 1))\n\n    def assert_simplified_equal(index_simplified, index_direct):\n        assert tvm.ir.structural_equal(\n            index_simplified, index_direct\n        ), \"index_simplified=%s, index_direct=%s\" % (index_simplified, index_direct)\n\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    # Test Case1\n    index_simplified = A_stride.offset_of(\n        (idxd(idxm(k0, k1), s), idxm(idxm(k0, k1), s) + idxd(k0, k1) * k1)\n    )\n    index_direct = A_stride.offset_of((0, k0))\n    assert_simplified_equal(index_simplified, index_direct)\n\n    # Test Case2\n    index_simplified = A.offset_of(\n        (idxd(idxm(k0, idxd(k1, s)), n), idxm(idxm(k0, idxd(k1, s)), n) + idxm(k0, k1))\n    )\n    index_direct = A.offset_of((0, idxm(k0, k1) + idxm(k0, idxd(k1, s))))\n    assert_simplified_equal(index_simplified, index_direct)\n    # Test Case3\n    index_simplified = A.offset_of(\n        (\n            idxd((idxd(k0, idxd(k1, s)) * idxd(k1, s)), n) + idxd(idxm(k0, idxd(k1, s)), n),\n            idxm((idxd(k0, idxd(k1, s)) * idxd(k1, s)), n) + idxm(idxm(k0, idxd(k1, s)), n),\n        )\n    )\n    index_direct = A.offset_of((0, k0))\n    assert_simplified_equal(index_simplified, index_direct)\n    # Test Case4 (not able to simplify)\n    index_simplified = A.offset_of(\n        (idxd(idxm(k0, idxd(k1, s)), n), idxm(idxm(k0, idxd(k1, n)), n) + idxm(k0, k1))\n    )\n    index_direct = A.offset_of(\n        (0, idxd(idxm(k0, idxd(k1, s)), n) * n + (idxm(idxm(k0, idxd(k1, n)), n) + idxm(k0, k1)))\n    )\n    assert_simplified_equal(index_simplified, index_direct)\n\n    # Test Case5\n    B = tvm.tir.decl_buffer((1, 14, 14, 1024))\n    i = te.size_var(\"i\")\n    j = te.size_var(\"j\")\n    k = te.size_var(\"k\")\n\n    index_simplified1 = B.offset_of(\n        (\n            idxd(idxd(idxd((i * 50176 + j * 28672 + k), 1024), 14), 14),\n            idxm(idxd(idxd((i * 50176 + j * 28672 + k), 1024), 14), 14),\n            idxm(idxd((i * 50176 + j * 28672 + k), 1024), 14),\n            idxm((i * 50176 + j * 28672 + k), 1024),\n        )\n    )\n    index_simplified2 = B.offset_of(\n        (\n            idxd(idxd(i * 49 + j * 28 + idxd(k, 1024), 14), 14),\n            idxm(idxd(i * 49 + j * 28 + idxd(k, 1024), 14), 14),\n            idxm(i * 7 + idxd(k, 1024), 14),\n            idxm(k, 1024),\n        )\n    )\n    index_direct = B.offset_of((0, 0, 0, (i * 50176 + j * 28672 + k)))\n    assert_simplified_equal(index_simplified1, index_direct)\n    assert_simplified_equal(index_simplified2, index_direct)\n\n\n@tvm.testing.requires_llvm\ndef test_buffer_broadcast():\n    m0, m1, m2 = te.size_var(\"m0\"), te.size_var(\"m1\"), te.size_var(\"m2\")\n    n0, n1, n2 = te.size_var(\"n0\"), te.size_var(\"n1\"), te.size_var(\"n2\")\n    o0, o1, o2 = te.size_var(\"o0\"), te.size_var(\"o1\"), te.size_var(\"o2\")\n\n    A = te.placeholder((m0, m1, m2), name=\"A\")\n    B = te.placeholder((n0, n1, n2), name=\"B\")\n\n    C = te.compute((o0, o1, o2), lambda i, j, k: A[i, j, k] + B[i, j, k], name=\"C\")\n\n    Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name=\"Ab\", buffer_type=\"auto_broadcast\")\n    Bb = tvm.tir.decl_buffer(B.shape, B.dtype, name=\"Bb\", buffer_type=\"auto_broadcast\")\n    s = te.create_schedule(C.op)\n\n    def check():\n        fadd = tvm.build(s, [A, B, C], target=\"llvm\", name=\"bcast_add\", binds={A: Ab, B: Bb})\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=(2, 4, 3)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(2, 1, 1)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((2, 4, 3), dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check()\n\n\n@tvm.testing.requires_llvm\ndef test_buffer_broadcast_expr():\n    n0, m0, x = te.size_var(\"n0\"), te.size_var(\"m0\"), te.size_var(\"x\")\n    n1, m1 = te.size_var(\"n1\"), te.size_var(\"m1\")\n    o0, o1 = te.size_var(\"o0\"), te.size_var(\"o1\")\n\n    A = te.placeholder((m0, n0), name=\"A\")\n    B = te.placeholder((m1, n1), name=\"B\")\n    C = te.compute((o0, o1 // x), lambda i, j: A[i, j] + B[i, j], name=\"C\")\n\n    Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name=\"Ab\", buffer_type=\"auto_broadcast\")\n    Bb = tvm.tir.decl_buffer(B.shape, B.dtype, name=\"Bb\", buffer_type=\"auto_broadcast\")\n    Cc = tvm.tir.decl_buffer(C.shape, C.dtype, name=\"Cc\", buffer_type=\"auto_broadcast\")\n    s = te.create_schedule(C.op)\n\n    def check_stride():\n        fadd = tvm.build(\n            s, [A, B, C, o1, x], target=\"llvm\", name=\"bcast_add\", binds={A: Ab, B: Bb, C: Cc}\n        )\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev)\n        fadd(a, b, c, 4, 1)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    def check_no_stride():\n        fadd = tvm.build(\n            s, [A, B, C, o1, x], target=\"llvm\", name=\"bcast_add\", binds={A: Ab, B: Bb, C: Cc}\n        )\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=(1, 4)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev)\n        fadd(a, b, c, 4, 1)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    def check_auto_bind():\n        # Let build bind buffers\n        fadd = tvm.build(s, [A, B, C, o1, x], target=\"llvm\", name=\"bcast_add\")\n        dev = tvm.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=(1, 4)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev)\n        fadd(a, b, c, 4, 1)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_stride()\n    check_no_stride()\n    check_auto_bind()\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_constructor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm\nfrom tvm import te\n\n\ndef test_expr_constructor():\n    x = tvm.tir.Var(\"xx\", \"float32\")\n    assert isinstance(x, tvm.tir.Var)\n    assert x.name == \"xx\"\n\n    x = tvm.tir.Reduce(None, [1], [tvm.tir.IterVar((0, 1), \"x\", 2)], None, 0)\n    assert isinstance(x, tvm.tir.Reduce)\n    assert x.combiner == None\n    assert x.value_index == 0\n\n    x = tvm.tir.FloatImm(\"float32\", 1.0)\n    assert isinstance(x, tvm.tir.FloatImm)\n    assert x.value == 1.0\n    assert x.dtype == \"float32\"\n\n    x = tvm.tir.IntImm(\"int64\", 2)\n    assert isinstance(x, tvm.tir.IntImm)\n    assert x.value == 2\n    assert x.dtype == \"int64\"\n\n    x = tvm.tir.StringImm(\"xyza\")\n    assert isinstance(x, tvm.tir.StringImm)\n    assert x.value == \"xyza\"\n\n    x = tvm.tir.Cast(\"float32\", tvm.tir.IntImm(\"uint32\", 1))\n    assert isinstance(x, tvm.tir.Cast)\n    assert x.dtype == \"float32\"\n    assert x.value.value == 1\n\n    a = tvm.tir.const(1.0, dtype=\"float32\")\n    b = te.var(\"x\", dtype=\"float32\")\n\n    for cls in [\n        tvm.tir.Add,\n        tvm.tir.Sub,\n        tvm.tir.Mul,\n        tvm.tir.Div,\n        tvm.tir.Mod,\n        tvm.tir.Min,\n        tvm.tir.Max,\n        tvm.tir.LT,\n        tvm.tir.LE,\n        tvm.tir.GT,\n        tvm.tir.GE,\n    ]:\n        x = cls(a, b)\n        assert isinstance(x, cls)\n        assert x.a == a\n        assert x.b.same_as(b)\n\n    a = tvm.runtime.convert(te.var(\"x\") > 1)\n    b = tvm.runtime.convert(te.var(\"x\") == 1)\n\n    for cls in [tvm.tir.And, tvm.tir.Or]:\n        x = cls(a, b)\n        assert isinstance(x, cls)\n        assert x.a == a\n        assert x.b.same_as(b)\n\n    x = tvm.tir.Not(a)\n    assert isinstance(x, tvm.tir.Not)\n    assert x.a == a\n\n    x = tvm.tir.Select(a, a, b)\n    assert isinstance(x, tvm.tir.Select)\n    assert x.true_value == a\n    assert x.false_value == b\n    assert x.condition == a\n\n    buffer_var = tvm.tir.Var(\"buf\", tvm.ir.PointerType(tvm.ir.PrimType(\"float32\")))\n    buffer = tvm.tir.decl_buffer([16], \"float32\", data=buffer_var)\n    x = tvm.tir.BufferLoad(buffer, [1])\n    assert isinstance(x, tvm.tir.BufferLoad)\n    assert x.dtype == \"float32\"\n    assert x.buffer == buffer\n    assert x.buffer.data == buffer_var\n    assert list(x.indices) == [1]\n\n    x = tvm.tir.Ramp(1, 2, 10)\n    assert isinstance(x, tvm.tir.Ramp)\n    assert x.base.value == 1\n    assert x.stride.value == 2\n    assert x.lanes == 10\n\n    x = tvm.tir.Broadcast(a, 10)\n    assert isinstance(x, tvm.tir.Broadcast)\n    assert x.value == a\n    assert x.lanes == 10\n\n    x = tvm.tir.Shuffle([a], [0])\n    assert isinstance(x, tvm.tir.Shuffle)\n    assert x.vectors[0] == a\n    assert x.indices[0].value == 0\n\n    x = tvm.tir.Call(\"float32\", \"tir.call_extern\", [tvm.tir.StringImm(\"xyz\"), a])\n    assert isinstance(x, tvm.tir.Call)\n    assert x.dtype == \"float32\"\n    assert x.op.name == \"tir.call_extern\"\n    assert x.args[1] == a\n\n    v = te.var(\"aa\")\n    x = tvm.tir.Let(v, 1, v)\n    assert x.var == v\n    assert x.value.value == 1\n    assert x.body == v\n\n\ndef test_stmt_constructor():\n    v = te.var(\"aa\")\n    nop = tvm.tir.Evaluate(1)\n    x = tvm.tir.LetStmt(v, 1, tvm.tir.Evaluate(1))\n    assert isinstance(x, tvm.tir.LetStmt)\n    assert x.var == v\n    assert x.value.value == 1\n    assert isinstance(x.body, tvm.tir.Evaluate)\n\n    x = tvm.tir.AttrStmt(v == 1, \"xx\", 1, tvm.tir.Evaluate(1))\n    assert isinstance(x, tvm.tir.AttrStmt)\n    assert x.value.value == 1\n\n    x = tvm.tir.AssertStmt(tvm.tir.const(1, \"uint1\"), tvm.runtime.convert(\"hellow\"), nop)\n    assert isinstance(x, tvm.tir.AssertStmt)\n    assert x.body == nop\n\n    x = tvm.tir.For(te.var(\"x\"), 0, 10, tvm.tir.ForKind.SERIAL, nop)\n    assert isinstance(x, tvm.tir.For)\n    assert x.min.value == 0\n    assert x.extent.value == 10\n    assert x.body == nop\n\n    buffer_var = tvm.tir.Var(\"buf\", tvm.ir.PointerType(tvm.ir.PrimType(\"uint1\")))\n    buffer = tvm.tir.decl_buffer([16], \"uint1\", data=buffer_var)\n    x = tvm.tir.BufferStore(buffer, 1, [10])\n    assert isinstance(x, tvm.tir.BufferStore)\n    assert x.buffer == buffer\n    assert x.buffer.data == buffer_var\n    assert list(x.indices) == [10]\n    assert x.value.value == 1\n\n    buffer_var = tvm.tir.Var(\"buf\", tvm.ir.PointerType(tvm.ir.PrimType(\"float32\")))\n    x = tvm.tir.Allocate(buffer_var, \"float32\", [10], tvm.tir.const(1, \"uint1\"), nop)\n    assert isinstance(x, tvm.tir.Allocate)\n    assert x.dtype == \"float32\"\n    assert x.buffer_var == buffer_var\n    assert x.body == nop\n\n    storage_scope = \"global.texture\"\n    buffer_var = tvm.tir.Var(\"buf\", tvm.ir.PointerType(tvm.ir.PrimType(\"float32\"), storage_scope))\n    x = tvm.tir.Allocate(buffer_var, \"float32\", [10], tvm.tir.const(1, \"uint1\"), nop)\n    assert isinstance(x, tvm.tir.Allocate)\n    assert x.dtype == \"float32\"\n    assert x.buffer_var == buffer_var\n    assert x.buffer_var.type_annotation.storage_scope == storage_scope\n    assert x.body == nop\n\n    x = tvm.tir.AttrStmt(buffer_var, \"xyz\", 1, nop)\n    assert isinstance(x, tvm.tir.AttrStmt)\n    assert x.node == buffer_var\n    assert x.attr_key == \"xyz\"\n    assert x.body == nop\n\n    x = tvm.tir.IfThenElse(tvm.tir.const(1, \"uint1\"), tvm.tir.Evaluate(11), nop)\n    assert isinstance(x, tvm.tir.IfThenElse)\n    assert x.then_case.value.value == 11\n    assert x.else_case == nop\n\n    b = tvm.tir.decl_buffer((1, 2))\n    x = tvm.tir.Prefetch(b, [])\n    assert isinstance(x, tvm.tir.Prefetch)\n\n\ndef test_float_constructor_requires_float_dtype():\n    with pytest.raises(tvm.TVMError):\n        tvm.tir.FloatImm(\"int32\", 1.0)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_data_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test layout and bijective-layout node\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm.topi.utils import get_const_tuple\n\n\ndef test_layout():\n    layout = tvm.tir.layout(\"NCHW16c\")\n    assert layout is not None\n    assert isinstance(layout, tvm.tir.Layout)\n\n    assert layout.factor_of(\"c\") == 16\n    assert layout.factor_of(\"C\") == 16\n    assert layout.factor_of(\"N\") == -1\n\n    assert layout.index_of(\"N\") == 0\n    assert layout.index_of(\"C\") == 1\n    assert layout.index_of(\"H\") == 2\n    assert layout.index_of(\"W\") == 3\n    assert layout.index_of(\"c\") == 4\n    assert layout.index_of(\"O\") == -1\n\n    assert \"N\" in layout\n    assert \"C\" in layout\n    assert \"H\" in layout\n    assert \"W\" in layout\n    assert \"c\" in layout\n    assert \"O\" not in layout\n\n    assert layout[0] == \"N\"\n    assert layout[1] == \"C\"\n    assert layout[2] == \"H\"\n    assert layout[3] == \"W\"\n    assert layout[4] == \"c\"\n    assert layout[-1] == \"c\"\n\n\ndef test_bilayout_convertible():\n    # not convertible\n    assert tvm.tir.bijective_layout(\"NCHW\", \"ABCD\") is None\n    assert tvm.tir.bijective_layout(\"__undef__\", \"NCHW\") is None\n    assert tvm.tir.bijective_layout(\"NCHW\", \"__undef__\") is None\n    assert tvm.tir.bijective_layout(\"__undef__\", \"__undef__\") is None\n    assert tvm.tir.bijective_layout(\"\", \"NCHW\") is None\n    assert tvm.tir.bijective_layout(\"NCHW\", \"\") is None\n    assert tvm.tir.bijective_layout(\"\", \"\") is None\n    # convertible\n    assert tvm.tir.bijective_layout(\"NCHW\", \"NCHW16c\") is not None\n\n\ndef test_bilayout_shape():\n    bilayout = tvm.tir.bijective_layout(\"NCHW\", \"NCHW16c\")\n    assert isinstance(bilayout, tvm.tir.BijectiveLayout)\n\n    dst_shape = bilayout.forward_shape((1, 32, 7, 7))\n    assert get_const_tuple(dst_shape) == (1, 2, 7, 7, 16)\n\n    src_shape = bilayout.backward_shape(dst_shape)\n    assert get_const_tuple(src_shape) == (1, 32, 7, 7)\n\n\ndef test_bilayout_index():\n    bilayout = tvm.tir.bijective_layout(\"NCHW\", \"NCHW16c\")\n\n    dst_index = bilayout.forward_index([0, 18, 6, 6])\n    assert get_const_tuple(dst_index) == (0, 1, 6, 6, 2)\n\n    src_index = bilayout.backward_index([0, 1, 6, 6, 2])\n    assert get_const_tuple(src_index) == (0, 18, 6, 6)\n\n\nif __name__ == \"__main__\":\n    test_layout()\n    test_bilayout_convertible()\n    test_bilayout_shape()\n    test_bilayout_index()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_imm_values.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport math\nimport random\nimport numpy as np\nimport tvm\nimport tvm.testing\nimport pytest\nfrom tvm import tir\nfrom tvm.script import tir as T\nimport pytest\n\n\n@pytest.mark.parametrize(\n    \"dtype, literals\",\n    [\n        [\"int8\", [-128, 0, 127]],\n        [\"uint8\", [0, 255]],\n        [\"int32\", [-2147483648, 2147483647]],\n        [\"uint32\", [0, 4294967295]],\n        [\"int64\", [-9223372036854775808, 9223372036854775807]],\n        [\"uint64\", [0, 9223372036854775807]],\n    ],\n)\ndef test_tir_make_intimm(dtype, literals):\n    for l in literals:\n        imm = tir.const(l, dtype)\n        assert imm.value == l, imm\n\n\n@pytest.mark.parametrize(\n    \"dtype, literals\",\n    [\n        [\"int8\", [-129, 128]],\n        [\"uint8\", [-1, 256]],\n        [\"int32\", [-2147483650, 2147483648]],\n        [\"uint32\", [-1, 4294967296]],\n        [\"uint64\", [-1, 18446744073709551616]],\n    ],\n)\ndef test_tir_invalid_intimm(dtype, literals):\n    for l in literals:\n        with pytest.raises(tvm.TVMError):\n            tir.const(l, dtype)\n\n\n@pytest.mark.parametrize(\n    \"dtype, literals\",\n    [\n        [\n            \"uint64\",\n            {\n                9223372036854775807: 9223372036854775807,\n                18446744073709551615: 18446744073709551615,\n            },\n        ],\n    ],\n)\ndef test_tir_large_py_int_literals(dtype, literals):\n    \"\"\"\n    For large uint value, use LargeUIntImm intrin,\n    \"\"\"\n    for l in literals:\n        x = tir.const(l, dtype)\n        if isinstance(x, (tir.IntImm, tir.FloatImm)):\n            assert x.value == literals[l]\n        else:\n            # LargeUIntImm(low32, hi32)\n            assert (int(x.args[1]) << 32) + int(x.args[0]) == literals[l]\n\n\ndef test_tir_intimm_overflow():\n    assert int(tir.const(255, \"uint8\") + tir.const(1, \"uint8\")) == 0\n    assert int(tir.const(2**31 - 1, \"int32\") + tir.const(1, \"int32\")) == -(2**31)\n    assert int(tir.const(2**32 - 1, \"uint32\") + tir.const(1, \"uint32\")) == 0\n    assert int(tir.const(2**63 - 1, \"int64\") + tir.const(1, \"int64\")) == -(2**63)\n    assert int(tir.const(2**32, \"uint64\") * tir.const(2**32, \"uint64\")) == 0\n    # customized int types\n    assert int(tir.const(7, \"int4\") + tir.const(1, \"int4\")) == -8\n    assert int(tir.const(2**39 - 1, \"int40\") + tir.const(1, \"int40\")) == -(2**39)\n\n\ndef compare_float_value(value, expect, msg):\n    if math.isfinite(value):\n        assert np.abs(value - expect) < 1e-5, f\"{value} vs {expect}, {msg}\"\n    elif math.isnan(value):\n        assert math.isnan(expect), f\"{value} vs {expect}, {msg}\"\n    elif math.isinf(value):\n        assert math.isinf(expect), f\"{value} vs {expect}, {msg}\"\n\n\n@pytest.mark.parametrize(\n    \"dtype, literals\",\n    [\n        [\"float16\", [-65504.0, 3.14, 65504.0, np.inf, np.nan]],\n        [\"bfloat16\", [-3.38953139e38, 3.38953139e38, 3.14]],\n        [\"float32\", [np.finfo(\"float32\").min, 3.14, np.finfo(\"float32\").max, np.inf, np.nan]],\n        [\"float64\", [np.finfo(\"float64\").min, 3.14, np.finfo(\"float64\").max, np.inf, np.nan]],\n    ],\n)\ndef test_tir_make_floatimm(dtype, literals):\n    for l in literals:\n        imm = tir.const(l, dtype)\n        compare_float_value(imm.value, l, \"imm value should match feed value\")\n\n\n@pytest.mark.parametrize(\n    \"dtype, literals\",\n    [\n        [\"float16\", [-65505.0, 65505.0]],\n        [\"float32\", [-3.402e39, 3.402e39]],\n    ],\n)\ndef test_tir_invalid_floatimm(dtype, literals):\n    \"\"\"Currently only fp16 and fp32 have range check.\"\"\"\n    for l in literals:\n        with pytest.raises(tvm.TVMError):\n            tir.const(l, dtype)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float16\", \"float32\", \"float64\"])\n@pytest.mark.parametrize(\"literal\", [3.14, np.nan, np.inf])\ndef test_tir_special_floatimms(dtype, literal):\n    x = tir.const(literal, dtype)\n    compare_float_value(x.value, literal, \"imm value should match feed value\")\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_too_large_literal_f64():\n    # Behavior check: if literal f64 value is out of dtype range, the\n    # object is still constructed, and eval to infinity.\n    @T.prim_func\n    def imm_overflow_fp64() -> T.float64:\n        T.evaluate(T.ret(T.float64(1.7976e309), dtype=\"float64\"))\n\n    f = tvm.build(imm_overflow_fp64, target=\"llvm\")\n    assert math.isinf(f())\n\n\n@pytest.mark.parametrize(\n    \"literal, expect_dtype\",\n    [\n        (256, \"int32\"),\n        (2147483647, \"int32\"),\n        (-2147483648, \"int32\"),\n        (2147483648, \"int64\"),\n        (-2147483649, \"int64\"),\n        (3.14159, \"float32\"),\n        (np.finfo(\"float32\").min, \"float32\"),\n        (np.finfo(\"float32\").max, \"float32\"),\n        (-3.402e39, \"float64\"),\n        (3.402e39, \"float64\"),\n    ],\n)\ndef test_tir_const_auto_dtype(literal, expect_dtype):\n    x = tir.const(literal, dtype=None)\n    assert x.dtype == expect_dtype\n    assert x.value == literal\n\n\ndef check_tir_const_fold(\n    dtype, foldf, calcf, x_range=None, y_range=None, expect=None, skip_overflow=False\n):\n    \"\"\"Helper to check constant folding behavior\n\n    Parameters\n    ----------\n    dtype: str\n        Datatype of constants\n\n    foldf: (x, y) -> z\n        Folding function to call\n\n    calcf: (x, y) -> z\n        Compiled calculation function to call\n\n    x_range: Union[int, float, tuple]\n        Single value or value range [min, max]\n\n    y_range: Union[int, float, tuple]\n        Single value or value range [min, max]\n\n    expect: Union[int, float]\n        Expected calculation result\n\n    skip_overflow: bool\n        Skip assertion if the overflow happens\n    \"\"\"\n    seed = random.randint(0, 2147483648)\n    np.random.seed(seed)\n    ninfo = np.finfo(dtype) if dtype.startswith(\"float\") else np.iinfo(dtype)\n\n    if x_range is None:\n        x_range = (ninfo.min, ninfo.max)\n    if isinstance(x_range, (int, float)):\n        x = x_range\n    elif dtype.startswith(\"int\") or dtype.startswith(\"uint\"):\n        x = np.random.randint(x_range[0], x_range[1] + 1, dtype=dtype)\n    else:\n        x = np.random.uniform(x_range[0], x_range[1])\n\n    if y_range is None:\n        y_range = (ninfo.min, ninfo.max)\n    if isinstance(y_range, (int, float)):\n        y = y_range\n    elif dtype.startswith(\"int\") or dtype.startswith(\"uint\"):\n        y = np.random.randint(y_range[0], y_range[1] + 1, dtype=dtype)\n    else:\n        y = np.random.uniform(y_range[0], y_range[1])\n\n    if skip_overflow:\n        py_res = foldf(x, y)\n        if isinstance(py_res, (tir.IntImm, tir.FloatImm)):\n            py_res = py_res.value\n        if not (ninfo.min <= py_res <= ninfo.max):\n            # If the result overflow, certain arithmetics is non-defined\n            # thus we intentionally do not make the test failed.\n            return\n\n    fold_res = foldf(tir.const(x, dtype), tir.const(y, dtype))\n    calc_res = calcf(x, y)\n\n    flaky_msg = (\n        f\"{dtype} ({x}, {y}, {expect}) const folding check failed.\\n\"\n        + \"This test is intentionally non-deterministic, \"\n        + f\"if it fails please report it in github issue together with this seed {seed}\\n\"\n    )\n    if dtype.startswith(\"float\"):\n        compare_float_value(calc_res, fold_res.value, flaky_msg)\n        if expect:\n            compare_float_value(expect, calc_res, flaky_msg)\n    else:\n        assert calc_res == fold_res.value, flaky_msg\n        if expect:\n            assert expect == calc_res, flaky_msg\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_floatimm_const_fold():\n    \"\"\"Behavior check: folding fp32 match platform f32 arithmetic\"\"\"\n\n    @T.prim_func\n    def float_imm_multiply(x: T.float32, y: T.float32, z: T.Buffer[(), \"float32\"]):\n        z[()] = x * y\n\n    @T.prim_func\n    def float_imm_add(x: T.float32, y: T.float32, z: T.Buffer[(), \"float32\"]):\n        z[()] = x + y\n\n    @T.prim_func\n    def float_imm_sub(x: T.float32, y: T.float32, z: T.Buffer[(), \"float32\"]):\n        z[()] = x - y\n\n    @T.prim_func\n    def float_imm_div(x: T.float32, y: T.float32, z: T.Buffer[(), \"float32\"]):\n        z[()] = x / y\n\n    def __wrap_build(f):\n        lib = tvm.build(f, target=\"llvm\")\n        z = tvm.nd.array(np.zeros([]).astype(\"float32\"))\n\n        def _func(x, y):\n            lib(x, y, z)\n            return z.numpy()\n\n        return _func\n\n    fmul = __wrap_build(float_imm_multiply)\n    fadd = __wrap_build(float_imm_add)\n    fsub = __wrap_build(float_imm_sub)\n    fdiv = __wrap_build(float_imm_div)\n\n    # overflow\n    check_tir_const_fold(\"float32\", lambda x, y: x * y, fmul, 3.0e30, 3.0e30, np.inf)\n    check_tir_const_fold(\"float32\", lambda x, y: x * y, fmul, 3.0e30, -3.0e30, -np.inf)\n    check_tir_const_fold(\"float32\", lambda x, y: x / y, fdiv, 3.0e30, 3.0e-30, np.inf)\n\n    # divide by zero\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"float32\", lambda x, y: x / y, fdiv, 1.0, 0.0)\n\n    # nan and inf\n    check_tir_const_fold(\"float32\", lambda x, y: x + y, fadd, 1.0, np.nan, np.nan)\n    check_tir_const_fold(\"float32\", lambda x, y: x + y, fadd, 1.0, np.inf, np.inf)\n    check_tir_const_fold(\"float32\", lambda x, y: x + y, fadd, 1.0, -np.inf, -np.inf)\n\n    # randomized check\n    check_tir_const_fold(\"float32\", lambda x, y: x * y, fmul)\n    check_tir_const_fold(\"float32\", lambda x, y: x + y, fadd)\n    check_tir_const_fold(\"float32\", lambda x, y: x - y, fsub)\n    check_tir_const_fold(\n        \"float32\", lambda x, y: x / y, fdiv, y_range=(0.01, np.finfo(\"float32\").max)\n    )\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_int8_const_fold():\n    \"\"\"Behavior check: folding i8 operation match platform i8 arithmetic\"\"\"\n\n    @T.prim_func\n    def imm_multiply(x: T.int8, y: T.int8) -> T.int8:\n        T.evaluate(T.ret(x * y, dtype=\"int8\"))\n\n    @T.prim_func\n    def imm_add(x: T.int8, y: T.int8) -> T.int8:\n        T.evaluate(T.ret(x + y, dtype=\"int8\"))\n\n    @T.prim_func\n    def imm_sub(x: T.int8, y: T.int8) -> T.int8:\n        T.evaluate(T.ret(x - y, dtype=\"int8\"))\n\n    @T.prim_func\n    def imm_truncdiv(x: T.int8, y: T.int8) -> T.int8:\n        T.evaluate(T.ret(T.truncdiv(x, y), dtype=\"int8\"))\n\n    @T.prim_func\n    def imm_floordiv(x: T.int8, y: T.int8) -> T.int8:\n        T.evaluate(T.ret(T.floordiv(x, y), dtype=\"int8\"))\n\n    fmul = tvm.build(imm_multiply, target=\"llvm\")\n    fadd = tvm.build(imm_add, target=\"llvm\")\n    fsub = tvm.build(imm_sub, target=\"llvm\")\n    ffloordiv = tvm.build(imm_floordiv, target=\"llvm\")\n    ftruncdiv = tvm.build(imm_truncdiv, target=\"llvm\")\n\n    # overflow\n    check_tir_const_fold(\"int8\", lambda x, y: x + y, fadd, 127, 1, -128)\n    check_tir_const_fold(\"int8\", lambda x, y: x * y, fmul, 127, 127, 1)\n\n    # divide by zero\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int8\", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int8\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0)\n\n    # i8 mod folding is not implemented\n    assert not isinstance(tir.floormod(tir.const(7, \"int8\"), tir.const(3, \"int8\")), tir.IntImm)\n    assert not isinstance(tir.truncmod(tir.const(7, \"int8\"), tir.const(3, \"int8\")), tir.IntImm)\n\n    # randomized check\n    check_tir_const_fold(\"int8\", lambda x, y: x * y, fmul)\n    check_tir_const_fold(\"int8\", lambda x, y: x + y, fadd)\n    check_tir_const_fold(\"int8\", lambda x, y: x - y, fsub)\n    check_tir_const_fold(\n        \"int8\", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo(\"int8\").max)\n    )\n    check_tir_const_fold(\n        \"int8\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo(\"int8\").max)\n    )\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_uint8_const_fold():\n    \"\"\"Behavior check: folding u8 operation match platform u8 arithmetic\"\"\"\n\n    @T.prim_func\n    def imm_multiply(x: T.uint8, y: T.uint8) -> T.uint8:\n        T.evaluate(T.ret(x * y, dtype=\"uint8\"))\n\n    @T.prim_func\n    def imm_add(x: T.uint8, y: T.uint8) -> T.uint8:\n        T.evaluate(T.ret(x + y, dtype=\"uint8\"))\n\n    @T.prim_func\n    def imm_sub(x: T.uint8, y: T.uint8) -> T.uint8:\n        T.evaluate(T.ret(x - y, dtype=\"uint8\"))\n\n    @T.prim_func\n    def imm_truncdiv(x: T.uint8, y: T.uint8) -> T.uint8:\n        T.evaluate(T.ret(T.truncdiv(x, y), dtype=\"uint8\"))\n\n    @T.prim_func\n    def imm_floordiv(x: T.uint8, y: T.uint8) -> T.uint8:\n        T.evaluate(T.ret(T.floordiv(x, y), dtype=\"uint8\"))\n\n    fmul = tvm.build(imm_multiply, target=\"llvm\")\n    fadd = tvm.build(imm_add, target=\"llvm\")\n    fsub = tvm.build(imm_sub, target=\"llvm\")\n    ffloordiv = tvm.build(imm_floordiv, target=\"llvm\")\n    ftruncdiv = tvm.build(imm_truncdiv, target=\"llvm\")\n\n    # overflow\n    check_tir_const_fold(\"uint8\", lambda x, y: x + y, fadd, 255, 1, 0)\n\n    # zero sub\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"uint8\", lambda x, y: x - y, fsub, 0, 10)\n\n    # divide by zero\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"uint8\", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"uint8\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0)\n\n    # u8 mod folding is not implemented\n    assert not isinstance(tir.floormod(tir.const(7, \"uint8\"), tir.const(3, \"uint8\")), tir.IntImm)\n    assert not isinstance(tir.truncmod(tir.const(7, \"uint8\"), tir.const(3, \"uint8\")), tir.IntImm)\n\n    # randomized check\n    check_tir_const_fold(\"uint8\", lambda x, y: x * y, fmul)\n    check_tir_const_fold(\"uint8\", lambda x, y: x + y, fadd)\n    check_tir_const_fold(\"uint8\", lambda x, y: x - y, fsub)\n    check_tir_const_fold(\n        \"uint8\", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo(\"uint8\").max)\n    )\n    check_tir_const_fold(\n        \"uint8\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo(\"uint8\").max)\n    )\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_int32_const_fold():\n    \"\"\"Behavior check: folding i32 operation match platform i32 arithmetic\"\"\"\n\n    @T.prim_func\n    def imm_multiply(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(x * y, dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_add(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(x + y, dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_sub(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(x - y, dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_truncdiv(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(T.truncdiv(x, y), dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_truncmod(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(T.truncmod(x, y), dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_floordiv(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(T.floordiv(x, y), dtype=\"int32\"))\n\n    @T.prim_func\n    def imm_floormod(x: T.int32, y: T.int32) -> T.int32:\n        T.evaluate(T.ret(T.floormod(x, y), dtype=\"int32\"))\n\n    fmul = tvm.build(imm_multiply, target=\"llvm\")\n    fadd = tvm.build(imm_add, target=\"llvm\")\n    fsub = tvm.build(imm_sub, target=\"llvm\")\n    ffloordiv = tvm.build(imm_floordiv, target=\"llvm\")\n    ffloormod = tvm.build(imm_floormod, target=\"llvm\")\n    ftruncdiv = tvm.build(imm_truncdiv, target=\"llvm\")\n    ftruncmod = tvm.build(imm_truncmod, target=\"llvm\")\n\n    # i32 overflow is not specified, only check for range\n    assert -(2**31) <= int(tir.const(2**31 - 1, \"int32\") + tir.const(1, \"int32\")) < 2**31\n    assert -(2**31) <= int(tir.const(-(2**31), \"int32\") - tir.const(1, \"int32\")) < 2**31\n\n    # divide by zero\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int32\", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int32\", lambda x, y: tir.floormod(x, y), ffloormod, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int32\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"int32\", lambda x, y: tir.truncmod(x, y), ftruncmod, 1, 0)\n\n    # randomized check\n    check_tir_const_fold(\"int32\", lambda x, y: x * y, fmul, skip_overflow=True)\n    check_tir_const_fold(\"int32\", lambda x, y: x + y, fadd, skip_overflow=True)\n    check_tir_const_fold(\"int32\", lambda x, y: x - y, fsub, skip_overflow=True)\n    check_tir_const_fold(\n        \"int32\",\n        lambda x, y: tir.floordiv(x, y),\n        ffloordiv,\n        y_range=(1, np.iinfo(\"int32\").max),\n        skip_overflow=True,\n    )\n    check_tir_const_fold(\n        \"int32\",\n        lambda x, y: tir.truncdiv(x, y),\n        ftruncdiv,\n        y_range=(1, np.iinfo(\"int32\").max),\n        skip_overflow=True,\n    )\n    check_tir_const_fold(\n        \"int32\",\n        lambda x, y: tir.floormod(x, y),\n        ffloormod,\n        y_range=(1, np.iinfo(\"int32\").max),\n        skip_overflow=False,\n    )\n    check_tir_const_fold(\n        \"int32\",\n        lambda x, y: tir.truncmod(x, y),\n        ftruncmod,\n        y_range=(1, np.iinfo(\"int32\").max),\n        skip_overflow=False,\n    )\n\n\n@tvm.testing.requires_llvm()\ndef test_tir_uint32_const_fold():\n    \"\"\"Behavior check: folding u32 operation match platform u32 arithmetic\"\"\"\n\n    @T.prim_func\n    def imm_multiply(x: T.uint32, y: T.uint32) -> T.uint32:\n        T.evaluate(T.ret(x * y, dtype=\"uint32\"))\n\n    @T.prim_func\n    def imm_add(x: T.uint32, y: T.uint32) -> T.uint32:\n        T.evaluate(T.ret(x + y, dtype=\"uint32\"))\n\n    @T.prim_func\n    def imm_sub(x: T.uint32, y: T.uint32) -> T.uint32:\n        T.evaluate(T.ret(x - y, dtype=\"uint32\"))\n\n    @T.prim_func\n    def imm_truncdiv(x: T.uint32, y: T.uint32) -> T.uint32:\n        T.evaluate(T.ret(T.truncdiv(x, y), dtype=\"uint32\"))\n\n    @T.prim_func\n    def imm_floordiv(x: T.uint32, y: T.uint32) -> T.uint32:\n        T.evaluate(T.ret(T.floordiv(x, y), dtype=\"uint32\"))\n\n    fmul = tvm.build(imm_multiply, target=\"llvm\")\n    fadd = tvm.build(imm_add, target=\"llvm\")\n    fsub = tvm.build(imm_sub, target=\"llvm\")\n    ffloordiv = tvm.build(imm_floordiv, target=\"llvm\")\n    ftruncdiv = tvm.build(imm_truncdiv, target=\"llvm\")\n\n    # u32 overflow is not specified, only check for range\n    assert 0 <= int(tir.const(2**32 - 1, \"uint32\") + tir.const(1, \"uint32\")) < 2**32\n\n    # divide by zero\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"uint32\", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0)\n    with pytest.raises(tvm.TVMError):\n        check_tir_const_fold(\"uint32\", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0)\n\n    # u8 mod folding is not implemented\n    assert not isinstance(tir.floormod(tir.const(7, \"uint32\"), tir.const(3, \"uint32\")), tir.IntImm)\n    assert not isinstance(tir.truncmod(tir.const(7, \"uint32\"), tir.const(3, \"uint32\")), tir.IntImm)\n\n    # randomized check\n    check_tir_const_fold(\"uint32\", lambda x, y: x * y, fmul, skip_overflow=True)\n    check_tir_const_fold(\"uint32\", lambda x, y: x + y, fadd, skip_overflow=True)\n    check_tir_const_fold(\"uint32\", lambda x, y: x - y, fsub, skip_overflow=True)\n    check_tir_const_fold(\n        \"uint32\",\n        lambda x, y: tir.floordiv(x, y),\n        ffloordiv,\n        y_range=(1, np.iinfo(\"uint32\").max),\n        skip_overflow=False,\n    )\n    check_tir_const_fold(\n        \"uint32\",\n        lambda x, y: tir.truncdiv(x, y),\n        ftruncdiv,\n        y_range=(1, np.iinfo(\"uint32\").max),\n        skip_overflow=False,\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm import topi\nfrom tvm.contrib import utils, clang\nfrom tvm.script import tir as T\nimport numpy as np\nimport ctypes\nimport math\n\n\ndef test_nearbyint():\n    m = te.var(\n        \"m\",\n    )\n    A = te.placeholder((m,), name=\"A\")\n    A_rounded = te.compute((m,), lambda *i: tvm.tir.nearbyint(A(*i)), name=\"A\")\n    s = te.create_schedule(A_rounded.op)\n    f = tvm.build(s, [A, A_rounded], \"llvm\")\n    dev = tvm.cpu(0)\n    n = 10\n    a = tvm.nd.array(np.random.uniform(high=100, size=n).astype(A.dtype), dev)\n    a_rounded = tvm.nd.array(np.random.uniform(size=n).astype(A_rounded.dtype), dev)\n    f(a, a_rounded)\n    # Note that numpys rint rounds to nearest integer with\n    # ties to halfway is broken by rounding to even.\n    # So that 1.5 and 2.5 will round 2.\n    # This is the default rounding mode with libc as well.\n    # However one can set a different rounding mode and in that\n    # case numpy result might differ.\n    tvm.testing.assert_allclose(a_rounded.numpy(), np.rint(a.numpy()))\n\n\ndef test_round_intrinsics_on_int():\n    i = tvm.te.var(\"i\", \"int32\")\n    for op in [tvm.tir.round, tvm.tir.trunc, tvm.tir.ceil, tvm.tir.floor, tvm.tir.nearbyint]:\n        assert op(tvm.tir.const(10, \"int32\")).value == 10\n        assert op(tvm.tir.const(True, \"bool\")).value == True\n        assert op(i).same_as(i)\n\n    assert tvm.tir.isnan(tvm.tir.const(10, \"int32\")).value == False\n\n\ndef test_unary_intrin():\n    test_funcs = [\n        (tvm.tir.exp10, lambda x: np.power(10, x)),\n        (tvm.tir.log2, lambda x: np.log2(x)),\n        (tvm.tir.log10, lambda x: np.log10(x)),\n        (tvm.tir.sinh, lambda x: np.sinh(x)),\n        (tvm.tir.cosh, lambda x: np.cosh(x)),\n        (tvm.tir.log1p, lambda x: np.log1p(x)),\n        (tvm.tir.asin, lambda x: np.arcsin(x)),\n        (tvm.tir.acos, lambda x: np.arccos(x)),\n        (tvm.tir.atan, lambda x: np.arctan(x)),\n        (tvm.tir.asinh, lambda x: np.arcsinh(x)),\n        (tvm.tir.acosh, lambda x: np.arccosh(x)),\n        (tvm.tir.atanh, lambda x: np.arctanh(x)),\n    ]\n\n    def run_test(tvm_intrin, np_func):\n        m = te.var(\n            \"m\",\n        )\n        A = te.placeholder((m,), name=\"A\")\n        B = te.compute((m,), lambda *i: tvm_intrin(A(*i)), name=\"B\")\n        s = te.create_schedule(B.op)\n        f = tvm.build(s, [A, B], \"llvm\")\n        dev = tvm.cpu(0)\n        n = 10\n        a = tvm.nd.array(np.random.uniform(0.1, 0.5, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        f(a, b)\n        tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-5, rtol=1e-5)\n\n    for func in test_funcs:\n        run_test(*func)\n\n\ndef test_binary_intrin():\n    test_funcs = [\n        (tvm.tir.atan2, lambda x1, x2: np.arctan2(x1, x2)),\n        (tvm.tir.nextafter, lambda x1, x2: np.nextafter(x1, x2)),\n        (tvm.tir.copysign, lambda x1, x2: np.copysign(x1, x2)),\n        (tvm.tir.hypot, lambda x1, x2: np.hypot(x1, x2)),\n    ]\n\n    def run_test(tvm_intrin, np_func):\n        m = te.var(\n            \"m\",\n        )\n        A = te.placeholder((m,), name=\"A\")\n        B = te.placeholder((m,), name=\"B\")\n        C = te.compute((m,), lambda *i: tvm_intrin(A(*i), B(*i)), name=\"C\")\n        s = te.create_schedule(C.op)\n        f = tvm.build(s, [A, B, C], \"llvm\")\n        dev = tvm.cpu(0)\n        n = 10\n        a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), np_func(a.numpy(), b.numpy()), atol=1e-5, rtol=1e-5)\n\n    for func in test_funcs:\n        run_test(*func)\n\n\ndef test_ldexp():\n    m = te.var(\n        \"m\",\n    )\n    A = te.placeholder((m,), name=\"A\")\n    B = te.placeholder((m,), name=\"B\", dtype=\"int32\")\n    C = te.compute((m,), lambda *i: tvm.tir.ldexp(A(*i), B(*i)), name=\"C\")\n    s = te.create_schedule(C.op)\n    f = tvm.build(s, [A, B, C], \"llvm\")\n    dev = tvm.cpu(0)\n    n = 10\n    a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.randint(0, 5, size=n).astype(B.dtype), dev)\n    c = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n    f(a, b, c)\n    tvm.testing.assert_allclose(c.numpy(), np.ldexp(a.numpy(), b.numpy()), atol=1e-5, rtol=1e-5)\n\n\ndtype = tvm.testing.parameter(\"int32\", \"int64\")\n\n\n@tvm.testing.parametrize_targets(\"llvm\", \"vulkan -from_device=0\")\ndef test_clz(target, dev, dtype):\n    target = tvm.target.Target(target)\n    if (\n        target.kind.name == \"vulkan\"\n        and dtype == \"int64\"\n        and not target.attrs.get(\"supports_int64\", False)\n    ):\n        pytest.xfail(\"Vulkan target does not support Int64 types\")\n\n    def clz_np(x, dtype):\n        ceil_log2 = np.ceil(np.log2(x)).astype(dtype)\n        bits = int(dtype[-2:])\n        clz = bits - ceil_log2\n        clz[np.bitwise_and(x, x - 1) == 0] -= 1\n        return clz\n\n    m = te.var(\"m\")\n    A = te.placeholder((m,), name=\"A\", dtype=dtype)\n    B = te.compute((m,), lambda *i: tvm.tir.clz(A(*i)), name=\"B\")\n    s = te.create_schedule(B.op)\n\n    if target.kind.name == \"vulkan\":\n        bx, tx = s[B].split(B.op.axis[0], factor=64)\n\n        s[B].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[B].bind(tx, te.thread_axis(\"threadIdx.x\"))\n\n    f = tvm.build(s, [A, B], target)\n    n = 10\n\n    highs = [10, 100, 1000, 10000, 100000, 1000000]\n\n    if dtype == \"int64\":\n        highs.append((1 << 63) - 1)\n\n    for high in highs:\n        a_np = np.random.randint(1, high=high, size=(n,), dtype=dtype)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(np.zeros((n,)).astype(\"int32\"), dev)\n        f(a, b)\n        ref = clz_np(a_np, dtype)\n        np.testing.assert_equal(b.numpy(), ref)\n\n\n@tvm.script.ir_module\nclass Module:\n    @T.prim_func\n    def test_tir_fma(A: T.handle, B: T.handle, C: T.handle, d: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"test_fma\", \"tir.noalias\": True})\n        n = T.var(\"int32\")\n        stride = T.var(\"int32\")\n        stride_1 = T.var(\"int32\")\n        stride_2 = T.var(\"int32\")\n        stride_3 = T.var(\"int32\")\n        A_1 = T.match_buffer(\n            A,\n            [n],\n            strides=[stride],\n            elem_offset=0,\n            align=64,\n            offset_factor=1,\n            buffer_type=\"auto\",\n        )\n        B_1 = T.match_buffer(\n            B,\n            [n],\n            strides=[stride_1],\n            elem_offset=0,\n            align=64,\n            offset_factor=1,\n            buffer_type=\"auto\",\n        )\n        C_1 = T.match_buffer(\n            C,\n            [n],\n            strides=[stride_2],\n            elem_offset=0,\n            align=64,\n            offset_factor=1,\n            buffer_type=\"auto\",\n        )\n        d_1 = T.match_buffer(\n            d,\n            [n],\n            strides=[stride_3],\n            elem_offset=0,\n            align=64,\n            offset_factor=1,\n            buffer_type=\"auto\",\n        )\n        # body\n        for i in T.serial(0, n):\n            d_1[(i * stride_3)] = (A_1[(i * stride)] * B_1[(i * stride_1)]) + C_1[(i * stride_2)]\n\n\ndef test_fma():\n    opt = tvm.transform.Sequential(\n        [\n            tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\"))),\n            tvm.tir.transform.LowerIntrin(),\n        ]\n    )\n    mod = opt(Module)\n    assert mod[\"test_tir_fma\"].body.body.value.op.name == \"tir.call_llvm_pure_intrin\"\n\n\nif __name__ == \"__main__\":\n    test_nearbyint()\n    test_unary_intrin()\n    test_round_intrinsics_on_int()\n    test_binary_intrin()\n    test_ldexp()\n    test_clz()\n    test_fma()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ir_builder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nimport tvm.testing\nfrom tvm.topi.math import cast\n\n\ndef test_for():\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n    A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        A[i] = A[i] + 1\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A[j] = A[j] + 2\n\n    body = ib.get()\n    assert isinstance(body, tvm.tir.Allocate)\n    body = body.body\n    assert isinstance(body, tvm.tir.For)\n    body = body.body\n    assert isinstance(body, tvm.tir.SeqStmt)\n    assert isinstance(body[1], tvm.tir.For)\n\n\ndef test_if():\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n    A = ib.pointer(\"float32\", name=\"A\")\n    tmod = tvm.tir.truncmod\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.if_scope(tmod(i, 2) == 0):\n            A[i] = A[i] + 1\n        with ib.else_scope():\n            A[0] = A[i] + 2\n\n    body = ib.get()\n    assert A == A\n    assert isinstance(body, tvm.tir.For)\n    body = body.body\n    assert isinstance(body, tvm.tir.IfThenElse)\n    assert isinstance(body.condition, tvm.tir.EQ)\n    assert isinstance(body.then_case.indices[0], tvm.tir.Var)\n    assert list(body.else_case.indices) == [0]\n\n\ndef test_prefetch():\n    A = tvm.tir.decl_buffer((10, 20), name=\"A\")\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n\n    with ib.for_range(0, n, name=\"i\") as i:\n        ib.emit(\n            tvm.tir.Prefetch(\n                A, [tvm.ir.Range.from_min_extent(i + 1, 2), tvm.ir.Range.from_min_extent(0, 20)]\n            )\n        )\n    body = ib.get()\n    assert body.body.bounds[0].extent.value == 2\n\n\ndef test_cpu():\n    n = 1024\n    dtype = \"float32\"\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    def test_device_ir(A, B, C):\n        n = A.shape[0]\n        max_threads = 8\n        ib = tvm.tir.ir_builder.create()\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n        with ib.for_range(0, n, name=\"i\") as i:\n            Cptr[i] = Aptr[i] + Bptr[i]\n        body = ib.get()\n        return body\n\n    C = te.extern(\n        A.shape,\n        [A, B],\n        lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]),\n        name=\"vector_add\",\n        dtype=dtype,\n    )\n    s = te.create_schedule(C.op)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n        # build and invoke the kernel.\n        fadd = tvm.build(s, [A, B, C], target)\n        dev = tvm.device(target, 0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_target(\"llvm\")\n\n\n@tvm.testing.requires_gpu\ndef test_gpu():\n    n = te.size_var(\"n\")\n    dtype = \"float32\"\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    idxd = tvm.tir.indexdiv\n\n    def test_device_ir(A, B, C):\n        n = A.shape[0]\n        max_threads = 32\n        ib = tvm.tir.ir_builder.create()\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", idxd(n + max_threads - 1, max_threads))\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        idx = bx.var * max_threads + tx.var\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n        with ib.if_scope(ib.likely(idx < n)):\n            Cptr[idx] = Aptr[idx] + Bptr[idx]\n        body = ib.get()\n        return body\n\n    C = te.extern(\n        A.shape,\n        [A, B],\n        lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]),\n        name=\"vector_add\",\n        dtype=dtype,\n    )\n    s = te.create_schedule(C.op)\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    def check_target(target):\n        n = 1024\n        if not tvm.testing.device_enabled(target):\n            return\n        # build and invoke the kernel.\n        fadd = tvm.build(s, [A, B, C], target)\n        dev = tvm.device(target, 0)\n        # launch the kernel.\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy())\n\n    check_target(\"opencl\")\n    check_target(\"cuda\")\n\n\ndef test_while_vectorize():\n    \"\"\"Test while loop + vectorized inner loop\"\"\"\n\n    n = 64\n    num_iter = 10\n\n    def test_ir(A, B, C):\n        ib = tvm.tir.ir_builder.create()\n        n = C.shape[0]\n        A = ib.buffer_ptr(A)\n        B = ib.buffer_ptr(B)\n        C = ib.buffer_ptr(C)\n        i = ib.allocate(\"int32\", (1,), name=\"i\", scope=\"local\")\n        i[0] = 0\n\n        with ib.for_range(0, n) as j:\n            C[j] = 0.0\n\n        with ib.while_loop(i[0] < num_iter):\n            with ib.for_range(0, n, kind=\"vectorize\") as j:\n                C[j] += A[j] + B[j]\n            i[0] += 1\n\n        return ib.get()\n\n    def check_target(target, ir):\n        dtype = \"float32\"\n        A = te.placeholder((n,), name=\"A\", dtype=dtype)\n        B = te.placeholder((n,), name=\"B\", dtype=dtype)\n\n        C = te.extern(\n            (n,),\n            [A, B],\n            lambda ins, outs: ir(ins[0], ins[1], outs[0]),\n            name=\"while_vectorize\",\n            dtype=dtype,\n        )\n        s = te.create_schedule(C.op)\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(s, [A, B, C], target)\n\n        dev = tvm.device(target, 0)\n        a_np = np.random.uniform(size=n).astype(A.dtype)\n        b_np = np.random.uniform(size=n).astype(B.dtype)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        func(a, b, c)\n        ref = num_iter * (a_np + b_np)\n        tvm.testing.assert_allclose(c.numpy(), ref, rtol=1e-5, atol=1e-5)\n\n    check_target(\"llvm\", test_ir)\n\n\ndef test_while_collatz():\n    \"\"\"Test while loop + if\"\"\"\n\n    def collatz_ref(n):\n        a = n\n        i = 0\n        while a > 1:\n            if a % 2 == 1:\n                a = 3 * a + 1\n            else:\n                a = a >> 1\n            i += 1\n        return i\n\n    def collatz(ib, n, C):\n        i = ib.allocate(\"int32\", (1,), name=\"i\", scope=\"local\")\n        a = ib.allocate(\"int32\", (1,), name=\"a\", scope=\"local\")\n        i[0] = 0\n        a[0] = n\n        with ib.while_loop(a[0] > 1):\n            with ib.if_scope(tvm.tir.floormod(a[0], 2) == 1):\n                a[0] = 3 * a[0] + 1\n            with ib.else_scope():\n                a[0] = a[0] >> 1\n            i[0] += 1\n\n        C[n] = i[0]\n\n    def collatz_ir_cpu(C):\n        ib = tvm.tir.ir_builder.create()\n        n = C.shape[0]\n        C = ib.buffer_ptr(C)\n\n        with ib.for_range(0, n, name=\"i\", kind=\"parallel\") as i:\n            collatz(ib, i, C)\n\n        body = ib.get()\n\n        return body\n\n    n = 30\n\n    def check_target(target, ir):\n        C = te.extern(\n            (n,),\n            [],\n            lambda ins, outs: ir(outs[0]),\n            name=\"collatz\",\n            dtype=\"int32\",\n        )\n        s = te.create_schedule(C.op)\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(s, [C], target)\n\n        dev = tvm.device(target, 0)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        func(c)\n        ref = np.array([collatz_ref(i) for i in range(n)])\n        tvm.testing.assert_allclose(c.numpy(), ref)\n\n    check_target(\"llvm\", collatz_ir_cpu)\n\n\ndef test_while_mandel():\n    n = 160\n    shape = (n * 2, n)\n    t = 300\n\n    def mandel_ref():\n        def complex_sqr(z):\n            return np.array([z[0] ** 2 - z[1] ** 2, z[1] * z[0] * 2])\n\n        pixels = np.zeros(shape)\n\n        for i in range(pixels.shape[0]):\n            for j in range(pixels.shape[1]):\n                c = np.array([-0.8, np.cos(t) * 0.2])\n                z = np.array([i / n - 1, j / n - 0.5]) * 2\n                iterations = 0\n\n                while np.linalg.norm(z) < 20 and iterations < 50:\n                    z = complex_sqr(z) + c\n                    iterations += 1\n\n                pixels[i, j] = 1 - iterations * 0.02\n\n        return pixels\n\n    def mandel(ib, i, j, pixels):\n        z = ib.allocate(\"float32\", (2,), name=\"z\", scope=\"local\")\n        tmp = ib.allocate(\"float32\", (1,), name=\"tmp\", scope=\"local\")\n        iterations = ib.allocate(\"int32\", (1,), name=\"iterations\", scope=\"local\")\n\n        z[0] = (i / float(n) - 1) * 2\n        z[1] = (j / float(n) - 0.5) * 2\n        iterations[0] = 0\n        c = [-0.8, float(np.cos(t)) * 0.2]\n\n        def norm(z):\n            return tvm.tir.sqrt(z[0] * z[0] + z[1] * z[1])\n\n        with ib.while_loop(tvm.tir.all(norm(z) < 20, iterations[0] < 50)):\n            tmp[0] = z[0]\n            z[0] = z[0] * z[0] - z[1] * z[1] + c[0]\n            z[1] = z[1] * tmp[0] * 2 + c[1]\n            iterations[0] += 1\n\n        pixels[i, j] = 1 - iterations[0] * 0.02\n\n    def mandel_ir_cpu(C):\n        ib = tvm.tir.ir_builder.create()\n        ny = C.shape[0]\n        nx = C.shape[1]\n        C = ib.buffer_ptr(C)\n\n        with ib.for_range(0, ny, name=\"i\", kind=\"parallel\") as i:\n            with ib.for_range(0, nx, name=\"j\") as j:\n                mandel(ib, i, j, C)\n\n        body = ib.get()\n\n        return body\n\n    def mandel_ir_gpu(C):\n        ib = tvm.tir.ir_builder.create()\n        ny = C.shape[0]\n        nx = C.shape[1]\n        C = ib.buffer_ptr(C)\n\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ty = te.thread_axis(\"threadIdx.y\")\n\n        max_threads = 16\n        ib.scope_attr(bx, \"thread_extent\", tvm.tir.indexdiv(nx + max_threads - 1, max_threads))\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        ib.scope_attr(by, \"thread_extent\", tvm.tir.indexdiv(ny + max_threads - 1, max_threads))\n        ib.scope_attr(ty, \"thread_extent\", max_threads)\n\n        tidx = bx * max_threads + tx\n        tidy = by * max_threads + ty\n\n        with ib.if_scope(tvm.tir.all(tidx < nx, tidy < ny)):\n            mandel(ib, tidy, tidx, C)\n\n        body = ib.get()\n\n        return body\n\n    ref = mandel_ref()\n\n    def check_target(target, ir):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        C = te.extern(\n            shape,\n            [],\n            lambda ins, outs: ir(outs[0]),\n            name=\"mandel_ir\",\n            dtype=\"float32\",\n        )\n        s = te.create_schedule(C.op)\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(s, [C], target)\n\n        dev = tvm.device(target, 0)\n        c = tvm.nd.array(np.zeros(shape, dtype=C.dtype), dev)\n        func(c)\n        tvm.testing.assert_allclose(c.numpy(), ref, rtol=1e-5, atol=1e-5)\n\n    check_target(\"llvm\", mandel_ir_cpu)\n    check_target(\"npvtx\", mandel_ir_gpu)\n    check_target(\"cuda\", mandel_ir_gpu)\n    check_target(\"vulkan\", mandel_ir_gpu)\n\n\ndef test_while_binary_search():\n    def binary_search(ib, n, i, Aptr, Bptr, Cptr):\n        lo = ib.allocate(\"int32\", (1,), name=\"lo\", scope=\"local\")\n        hi = ib.allocate(\"int32\", (1,), name=\"hi\", scope=\"local\")\n\n        lo[0] = 0\n        hi[0] = n\n        v = Bptr[i]\n\n        with ib.while_loop(lo[0] < hi[0]):\n            mid = lo[0] + (hi[0] - lo[0] >> 1)\n            with ib.if_scope(Aptr[mid] < v):\n                lo[0] = mid + 1\n            with ib.else_scope():\n                hi[0] = mid\n\n        Cptr[i] = lo[0]\n\n    def searchsorted_ir_cpu(A, B, C, n):\n        ib = tvm.tir.ir_builder.create()\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n\n        with ib.for_range(0, n, name=\"i\", kind=\"parallel\") as i:\n            binary_search(ib, n, i, Aptr, Bptr, Cptr)\n\n        body = ib.get()\n\n        return body\n\n    def searchsorted_ir_gpu(A, B, C, n):\n        ib = tvm.tir.ir_builder.create()\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        max_threads = 32\n        ib.scope_attr(bx, \"thread_extent\", tvm.tir.indexdiv(n + max_threads - 1, max_threads))\n        ib.scope_attr(tx, \"thread_extent\", max_threads)\n        tid = bx * max_threads + tx\n\n        with ib.if_scope(tid < n):\n            binary_search(ib, n, tid, Aptr, Bptr, Cptr)\n\n        body = ib.get()\n\n        return body\n\n    n = 1024\n    dtype = \"float32\"\n    A = te.placeholder((n,), name=\"A\", dtype=dtype)\n    B = te.placeholder((n,), name=\"B\", dtype=dtype)\n\n    def check_target(target, ir):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        C = te.extern(\n            A.shape,\n            [A, B],\n            lambda ins, outs: ir(ins[0], ins[1], outs[0], n),\n            name=\"searchsorted_ir\",\n            dtype=\"int32\",\n        )\n        s = te.create_schedule(C.op)\n\n        with tvm.transform.PassContext(opt_level=3):\n            func = tvm.build(s, [A, B, C], target)\n\n        dev = tvm.device(target, 0)\n        a_np = np.random.uniform(size=n).astype(A.dtype)\n        b_np = np.random.uniform(size=n).astype(B.dtype)\n        a_np = np.sort(a_np)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev)\n        func(a, b, c)\n        ref = np.searchsorted(a_np, b_np)\n        tvm.testing.assert_allclose(c.numpy(), ref)\n\n    check_target(\"llvm\", searchsorted_ir_cpu)\n    check_target(\"cuda\", searchsorted_ir_gpu)\n    check_target(\"nvptx\", searchsorted_ir_gpu)\n    check_target(\"vulkan\", searchsorted_ir_gpu)\n\n\n@tvm.testing.requires_gpu\ndef test_dyn_shared():\n    n = te.size_var(\"n\")\n    dtype = \"float32\"\n    A = te.placeholder((n,), name=\"A\")\n\n    def test_device_ir(A, B):\n        n = A.shape[0]\n        ib = tvm.tir.ir_builder.create()\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", n)\n\n        temp = ib.allocate(dtype, (n,), scope=\"shared.dyn\")  # n is symbolic size\n\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n\n        temp[tx] = Aptr[tx]\n        depth = tvm.tir.log2(cast(n, \"float32\"))\n\n        with ib.for_range(0, cast(tvm.tir.ceil(depth), n.dtype)) as i:\n            ib.emit(tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"])))\n            d = n >> (i + 1)\n            with ib.if_scope(tx < d):\n                temp[tx] += temp[tx + d]\n\n        Bptr[0] = temp[0]\n        return ib.get()\n\n    B = te.extern(\n        (1,),\n        [A],\n        lambda ins, outs: test_device_ir(ins[0], outs[0]),\n        name=\"reduce\",\n        dtype=dtype,\n    )\n    s = te.create_schedule(B.op)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        freduce = tvm.build(s, [A, B], target)\n        dev = tvm.device(target, 0)\n\n        for n in [512, 1024]:\n            a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n            b = tvm.nd.array(np.zeros(1, dtype=B.dtype), dev)\n            freduce(a, b)\n            tvm.testing.assert_allclose(b.numpy()[0], np.sum(a.numpy()), 1e-4, 1e-4)\n\n    for target in [\"cuda\", \"nvptx\"]:\n        check_target(target)\n\n\nif __name__ == \"__main__\":\n    test_prefetch()\n    test_if()\n    test_for()\n    test_cpu()\n    test_gpu()\n    test_while_vectorize()\n    test_while_collatz()\n    test_while_mandel()\n    test_while_binary_search()\n    test_dyn_shared()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_lower_match_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    mod = tvm.IRModule.from_expr(original)\n    mod = tvm.tir.transform.LowerMatchBuffer()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed)\n\n\ndef _check_fail(original):\n    mod = tvm.IRModule.from_expr(original)\n    with pytest.raises(tvm.TVMError):\n        mod = tvm.tir.transform.LowerMatchBuffer()(mod)\n\n\n@T.prim_func\ndef buffer_load_store(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16, 16))\n    C = T.match_buffer(c, (16, 16))\n    for i, j, k in T.grid(4, 16, 8):\n        with T.block():\n            T.reads(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2])\n            T.writes(A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2])\n            sub_A = T.match_buffer(\n                A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2], (4, 1, 2), offset_factor=1\n            )\n            sub_C = T.match_buffer(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2], (4, 2), offset_factor=1)\n            for ii, kk in T.grid(4, 2):\n                sub_A[ii, 0, kk] += sub_C[ii, kk]\n\n\n@T.prim_func\ndef transformed_buffer_load_store(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16, 16))\n    C = T.match_buffer(c, (16, 16))\n    for i, j, k in T.grid(4, 16, 8):\n        with T.block():\n            T.reads(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2])\n            T.writes(A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2])\n            for ii, kk in T.grid(4, 2):\n                A[i * 4 + ii, j, k * 2 + kk] += C[i * 4 + ii, k * 2 + kk]\n\n\n@tvm.ir.register_op_attr(\"tir.intrin_test\", \"\")\ndef intrin_test(data, elem_offset, stride_0, stride_1, shape_0, shape_1):\n    return 0\n\n\n@T.prim_func\ndef opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (32, 64, 128))\n    B = T.match_buffer(b, (64, 64, 64))\n    for i, j, k in T.grid(2, 64, 8):\n        with T.block():\n            T.reads([])\n            T.writes(A[i * 16 : i * 16 + 16, j, k * 16 : k * 16 + 16])\n            sub_A = T.match_buffer(\n                A[i * 16 : i * 16 + 16, j, k * 16 : k * 16 + 16],\n                (16, 1, 16),\n                strides=[8192, 128, 1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                intrin_test(\n                    sub_A.data,\n                    sub_A.elem_offset,\n                    sub_A.strides[0],\n                    sub_A.strides[1],\n                    sub_A.shape[0],\n                    sub_A.shape[1],\n                )\n            )\n    for i, j, k in T.grid(64, 2, 8):\n        with T.block():\n            Bs_0 = T.var(\"int32\")\n            Bs_1 = T.var(\"int32\")\n            T.reads([])\n            T.writes(B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8])\n            sub_B = T.match_buffer(\n                B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8],\n                (32, 8),\n                strides=[Bs_0, Bs_1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                intrin_test(\n                    sub_B.data,\n                    sub_B.elem_offset,\n                    sub_B.strides[0],\n                    sub_B.strides[1],\n                    sub_B.shape[0],\n                    sub_B.shape[1],\n                )\n            )\n\n\n@T.prim_func\ndef transformed_opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (32, 64, 128))\n    B = T.match_buffer(b, (64, 64, 64))\n    for i, j, k in T.grid(2, 64, 8):\n        with T.block():\n            T.reads([])\n            T.writes(A[i * 16 : i * 16 + 16, j, k * 16 : k * 16 + 16])\n            T.evaluate(\n                intrin_test(\n                    A.data,\n                    i * 131072 + j * 128 + k * 16,\n                    8192,\n                    128,\n                    16,\n                    1,\n                )\n            )\n    for i, j, k in T.grid(64, 2, 8):\n        with T.block():\n            T.reads([])\n            T.writes(B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8])\n            T.evaluate(\n                intrin_test(\n                    B.data,\n                    i * 4096 + j * 2048 + k * 8,\n                    64,\n                    1,\n                    32,\n                    8,\n                )\n            )\n\n\n@T.prim_func\ndef high_dim_opaque_access(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 32, 64))\n    for i, j, k in T.grid(16, 2, 4):\n        with T.block():\n            As_0 = T.var(\"int32\")\n            As_1 = T.var(\"int32\")\n            T.reads([])\n            T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16])\n            sub_A = T.match_buffer(\n                A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                (16, 16),\n                strides=[As_0, As_1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                intrin_test(\n                    sub_A.data,\n                    sub_A.elem_offset,\n                    sub_A.strides[0],\n                    sub_A.strides[1],\n                    sub_A.shape[0],\n                    sub_A.shape[1],\n                )\n            )\n\n\n@T.prim_func\ndef transformed_high_dim_opaque_access(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 32, 64))\n    for i, j, k in T.grid(16, 2, 4):\n        with T.block():\n            T.reads([])\n            T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16])\n            T.evaluate(\n                intrin_test(\n                    A.data,\n                    i * 2048 + j * 1024 + k * 16,\n                    64,\n                    1,\n                    16,\n                    16,\n                )\n            )\n\n\n@T.prim_func\ndef high_dim_opaque_access_with_source_strides(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 32, 64), strides=[2576, 80, 1])\n    for i, j, k in T.grid(16, 2, 4):\n        with T.block():\n            As_0 = T.var(\"int32\")\n            As_1 = T.var(\"int32\")\n            T.reads([])\n            T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16])\n            sub_A = T.match_buffer(\n                A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                (16, 16),\n                strides=[As_0, As_1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                intrin_test(\n                    sub_A.data,\n                    sub_A.elem_offset,\n                    sub_A.strides[0],\n                    sub_A.strides[1],\n                    sub_A.shape[0],\n                    sub_A.shape[1],\n                )\n            )\n\n\n@T.prim_func\ndef transformed_high_dim_opaque_access_with_source_strides(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 32, 64), strides=[2576, 80, 1])\n    for i, j, k in T.grid(16, 2, 4):\n        with T.block():\n            T.reads([])\n            T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16])\n            T.evaluate(\n                intrin_test(\n                    A.data,\n                    i * 2576 + j * 1280 + k * 16,\n                    80,\n                    1,\n                    16,\n                    16,\n                )\n            )\n\n\n@T.prim_func\ndef recursive_match(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (64, 64, 64))\n    B = T.match_buffer(b, (64, 64, 64))\n    for i, j, k in T.grid(64, 4, 4):\n        with T.block():\n            T.reads([])\n            T.writes(\n                [\n                    A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                    B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                ]\n            )\n            As_0 = T.var(\"int32\")\n            As_1 = T.var(\"int32\")\n            sub_A = T.match_buffer(\n                A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                (16, 16),\n                strides=[As_0, As_1],\n                offset_factor=1,\n            )\n            sub_B = T.match_buffer(\n                B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                (16, 16),\n                offset_factor=1,\n            )\n            for jj, kk in T.grid(4, 4):\n                with T.block():\n                    T.reads([])\n                    T.writes(\n                        [\n                            sub_A[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4],\n                            sub_B[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4],\n                        ]\n                    )\n                    Ass_0 = T.var(\"int32\")\n                    Ass_1 = T.var(\"int32\")\n                    sub_sub_A = T.match_buffer(\n                        sub_A[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4],\n                        (4, 4),\n                        strides=[Ass_0, Ass_1],\n                        offset_factor=1,\n                    )\n                    sub_sub_B = T.match_buffer(\n                        sub_B[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4],\n                        (4, 4),\n                        offset_factor=1,\n                    )\n                    T.evaluate(\n                        intrin_test(\n                            sub_sub_A.data,\n                            sub_sub_A.elem_offset,\n                            sub_sub_A.strides[0],\n                            sub_sub_A.strides[1],\n                            sub_sub_A.shape[0],\n                            sub_sub_A.shape[1],\n                        )\n                    )\n                    for jjj, kkk in T.grid(4, 4):\n                        sub_sub_B[jjj, kkk] = 1\n\n\n@T.prim_func\ndef transformed_recursive_match(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (64, 64, 64))\n    B = T.match_buffer(b, (64, 64, 64))\n    for i, j, k in T.grid(64, 4, 4):\n        with T.block():\n            T.reads([])\n            T.writes(\n                [\n                    A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                    B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16],\n                ]\n            )\n            for jj, kk in T.grid(4, 4):\n                with T.block():\n                    T.reads([])\n                    T.writes(\n                        [\n                            A[\n                                i,\n                                j * 16 + jj * 4 : j * 16 + jj * 4 + 4,\n                                k * 16 + kk * 4 : k * 16 + kk * 4 + 4,\n                            ],\n                            B[\n                                i,\n                                j * 16 + jj * 4 : j * 16 + jj * 4 + 4,\n                                k * 16 + kk * 4 : k * 16 + kk * 4 + 4,\n                            ],\n                        ]\n                    )\n                    T.evaluate(\n                        intrin_test(\n                            A.data,\n                            i * 4096 + j * 1024 + jj * 256 + k * 16 + kk * 4,\n                            64,\n                            1,\n                            4,\n                            4,\n                        )\n                    )\n                    for jjj, kkk in T.grid(4, 4):\n                        B[i, j * 16 + jj * 4 + jjj, k * 16 + kk * 4 + kkk] = 1\n\n\n@T.prim_func\ndef symbolic_match(a: T.handle, b: T.handle, n: T.int32, m: T.int32) -> None:\n    A = T.match_buffer(a, (n * m, m))\n    B = T.match_buffer(b, (n * 2, m * 4))\n    for i in range(0, n):\n        with T.block():\n            T.reads([])\n            T.writes([A[i * m : i * m + n, 0:m], B[i * n : i * n + 2, 0 : m * 4]])\n            Bs_0 = T.var(\"int32\")\n            Bs_1 = T.var(\"int32\")\n            sub_A = T.match_buffer(A[i * m : i * m + m, 0:m], (m, m), offset_factor=1)\n            sub_B = T.match_buffer(\n                B[i * n : i * n + 2, 0 : m * 4], (2, m * 4), strides=[Bs_0, Bs_1], offset_factor=1\n            )\n            for ii, jj in T.grid(m, m):\n                sub_A[ii, jj] = 1\n            for j in range(0, 4):\n                T.evaluate(\n                    intrin_test(\n                        sub_B.data,\n                        sub_B.elem_offset,\n                        sub_B.strides[0],\n                        sub_B.strides[1],\n                        sub_B.shape[0],\n                        sub_B.shape[1],\n                    )\n                )\n\n\n@T.prim_func\ndef transformed_symbolic_match(a: T.handle, b: T.handle, n: T.int32, m: T.int32) -> None:\n    A = T.match_buffer(a, (n * m, m))\n    B = T.match_buffer(b, (n * 2, m * 4))\n    for i in range(0, n):\n        with T.block():\n            T.reads([])\n            T.writes([A[i * m : i * m + n, 0:m], B[i * n : i * n + 2, 0 : m * 4]])\n            for ii, jj in T.grid(m, m):\n                A[i * m + ii, jj] = 1\n            for j in range(0, 4):\n                T.evaluate(\n                    intrin_test(\n                        B.data,\n                        i * n * (m * 4),\n                        m * 4,\n                        1,\n                        2,\n                        m * 4,\n                    )\n                )\n\n\n@T.prim_func\ndef rank0_buffer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    B = T.match_buffer(b, (8, 8))\n    for i, j in T.grid(8, 8):\n        with T.block():\n            T.reads([])\n            T.writes([A[i, j], B[i, j]])\n            sub_A = T.match_buffer(A[i, j], (), offset_factor=1)\n            sub_B = T.match_buffer(B[i, j], (), offset_factor=1)\n            sub_A[()] = 1\n            T.evaluate(\n                intrin_test(\n                    sub_B.data,\n                    sub_B.elem_offset,\n                    0,\n                    0,\n                    0,\n                    0,\n                )\n            )\n\n\n@T.prim_func\ndef transformed_rank0_buffer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    B = T.match_buffer(b, (8, 8))\n    for i, j in T.grid(8, 8):\n        with T.block():\n            T.reads([])\n            T.writes([A[i, j], B[i, j]])\n            A[i, j] = 1\n            T.evaluate(\n                intrin_test(\n                    B.data,\n                    i * 8 + j,\n                    0,\n                    0,\n                    0,\n                    0,\n                )\n            )\n\n\n@T.prim_func\ndef fail_match_load(a: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    for i, j in T.grid(8, 8):\n        with T.block():\n            T.reads(A[i, j])\n            T.writes([])\n            sub_A = T.match_buffer(A[i, j], (), elem_offset=0)\n            T.evaluate(sub_A[()])\n\n\n@T.prim_func\ndef fail_match_store(a: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    for i, j in T.grid(8, 8):\n        with T.block():\n            T.reads([])\n            T.writes(A[i, j])\n            sub_A = T.match_buffer(A[i, j], (), elem_offset=0)\n            sub_A[()] = 1\n\n\n@T.prim_func\ndef fail_buffer_bind(a: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    for i, j in T.grid(8, 2):\n        with T.block():\n            stride = T.var(\"int32\")\n            sub_A = T.match_buffer(\n                A[i, j * 4 : j * 4 + 4], (1, 4), strides=[stride, stride], offset_factor=1\n            )\n            for jj in range(0, 4):\n                sub_A[i, j * 4 + jj] = 1\n\n\n@T.prim_func\ndef fail_match_func_param(a: T.handle, m: T.handle, n: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8))\n    for i, j in T.grid(8, 2):\n        with T.block():\n            sub_A = T.match_buffer(A[i, j * 4 : j * 4 + 4], (1, 4), strides=[m, n], offset_factor=1)\n            for jj in range(0, 4):\n                sub_A[i, j * 4 + jj] = 1\n\n\ndef test_buffer_load_store():\n    _check(buffer_load_store, transformed_buffer_load_store)\n\n\ndef test_opaque_access():\n    _check(opaque_access, transformed_opaque_access)\n\n\ndef test_high_dim_opaque_access():\n    _check(high_dim_opaque_access, transformed_high_dim_opaque_access)\n    _check(\n        high_dim_opaque_access_with_source_strides,\n        transformed_high_dim_opaque_access_with_source_strides,\n    )\n\n\ndef test_recursive_match():\n    _check(recursive_match, transformed_recursive_match)\n\n\ndef test_symbolic_match():\n    _check(symbolic_match, transformed_symbolic_match)\n\n\ndef test_rank0_buffer():\n    _check(rank0_buffer, transformed_rank0_buffer)\n\n\ndef test_fail_load_store():\n    _check_fail(fail_match_load)\n    _check_fail(fail_match_store)\n\n\ndef test_fail_buffer_bind():\n    _check_fail(fail_buffer_bind)\n\n\ndef test_fail_match_func_param():\n    _check_fail(fail_match_func_param)\n\n\nif __name__ == \"__main__\":\n    test_buffer_load_store()\n    test_opaque_access()\n    test_high_dim_opaque_access()\n    test_recursive_match()\n    test_symbolic_match()\n    test_rank0_buffer()\n    test_fail_load_store()\n    test_fail_buffer_bind()\n    test_fail_match_func_param()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_nodes.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import te, ir\nimport numpy as np\n\n\ndef test_const():\n    x = tvm.tir.const(1, \"int32\")\n    assert x.dtype == \"int32\"\n    assert isinstance(x, tvm.tir.IntImm)\n\n\ndef test_te_const():\n    x = tvm.te.const(1, \"int32\")\n    assert x.dtype == \"int32\"\n    assert isinstance(x, tvm.tir.IntImm)\n\n\ndef test_scalar_dtype_inference():\n    for data in [\n        True,\n        bool(1),\n        np.uint8(1),\n        np.uint16(1),\n        np.uint32(1),\n        np.uint64(1),\n        np.int8(1),\n        np.int16(1),\n        np.int32(1),\n        np.int64(1),\n        np.float16(1),\n        np.float32(1),\n        np.float64(1),\n    ]:\n        assert tvm.tir.const(data).dtype == str(np.array(data).dtype)\n    assert tvm.tir.const(1).dtype == \"int32\"\n    assert tvm.tir.const(1.0).dtype == \"float32\"\n\n    for data in [\n        True,\n        bool(1),\n        np.uint8(1),\n        np.uint16(1),\n        np.uint32(1),\n        np.uint64(1),\n        np.int8(1),\n        np.int16(1),\n        np.int32(1),\n        np.int64(1),\n        np.float16(1),\n        np.float32(1),\n        np.float64(1),\n    ]:\n        assert tvm.runtime.convert(data).dtype == str(np.array(data).dtype)\n    assert tvm.runtime.convert(1).dtype == \"int32\"\n    assert tvm.runtime.convert(1.0).dtype == \"float32\"\n\n\ndef test_make():\n    x = tvm.tir.const(1, \"int32\")\n    y = te.var(\"x\")\n    z = x + y\n    assert isinstance(tvm.tir.max(x, y), tvm.tir.Max)\n    assert isinstance(tvm.tir.min(x, y), tvm.tir.Min)\n\n\ndef test_ir():\n    x = tvm.tir.const(1, \"int32\")\n    y = tvm.tir.IntImm(\"int32\", 1)\n    z = x + y\n    stmt = tvm.tir.Evaluate(z)\n    assert isinstance(stmt, tvm.tir.Evaluate)\n\n\ndef test_ir2():\n    buf_size = te.var(\"size\")\n    x = te.var(\"n\")\n\n    storage_type = ir.PrimType(\"int32\")\n    handle_type = ir.PointerType(storage_type)\n    array = te.var(\"array\", handle_type)\n    buf = tvm.tir.decl_buffer([buf_size], \"int32\", data=array)\n\n    st = tvm.tir.BufferStore(buf, x + 1, [1])\n    assert isinstance(st, tvm.tir.BufferStore)\n    assert st.buffer == buf\n    assert st.buffer.data == array\n\n\ndef test_let():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1))\n\n\ndef test_cast():\n    x = te.var(\"x\", dtype=\"float32\")\n    y = x.astype(\"int32\")\n    z = x.astype(\"float32x4\")\n    assert isinstance(y, tvm.tir.Cast)\n    assert isinstance(z, tvm.tir.Broadcast)\n    assert z.lanes == 4\n\n    s = tvm.tir.StringImm(\"s\")\n    with pytest.raises(tvm.error.TVMError) as cm:\n        s.astype(\"int\")\n        assert \"Can't cast a handle to other types\" in str(cm.execption)\n\n\ndef test_attr():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    stmt = tvm.tir.AttrStmt(y, \"stride\", 10, tvm.tir.Evaluate(x + 1))\n    assert stmt.node == y\n\n    a = tvm.runtime.convert(1)\n    assert a.value == 1\n    try:\n        a.no_field\n        assert False\n    except AttributeError:\n        pass\n\n\ndef test_basic():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = a + b\n    assert str(c) == \"(%s: int32 + %s: int32)\" % (a.name, b.name)\n\n\ndef test_stmt():\n    x = tvm.tir.Evaluate(0)\n    tvm.tir.For(te.var(\"i\"), 0, 1, tvm.tir.ForKind.SERIAL, x)\n\n\ndef test_dir():\n    x = te.var(\"x\")\n    dir(x)\n\n\ndef test_dtype():\n    x = te.var(\"x\")\n    assert x.dtype == \"int32\"\n    y = te.var(\"y\")\n    assert (x > y).dtype == \"bool\"\n\n\ndef test_any():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    try:\n        t = x or x\n        assert False\n    except ValueError:\n        pass\n    try:\n        tvm.tir.any()\n        assert False\n    except ValueError:\n        pass\n    assert str(tvm.tir.any(x < y)) == \"(%s: int32 < %s: int32)\" % (x.name, y.name)\n    assert str(tvm.tir.any(x < y, x > z)) == \"((%s: int32 < %s: int32) || (%s > %s: int32))\" % (\n        x.name,\n        y.name,\n        x.name,\n        z.name,\n    )\n    assert str(\n        tvm.tir.any(x < y, y > z + 1, x < z * 2)\n    ) == \"(((%s: int32 < %s: int32) || (%s > (%s: int32 + 1))) || (%s < (%s*2)))\" % (\n        x.name,\n        y.name,\n        y.name,\n        z.name,\n        x.name,\n        z.name,\n    )\n\n\ndef test_all():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    try:\n        t = x and x\n        assert False\n    except ValueError:\n        pass\n    try:\n        tvm.tir.all()\n        assert False\n    except ValueError:\n        pass\n    assert str(tvm.tir.all(x < y)) == \"(%s: int32 < %s: int32)\" % (x.name, y.name)\n    assert str(tvm.tir.all(x < y, x > z)) == \"((%s: int32 < %s: int32) && (%s > %s: int32))\" % (\n        x.name,\n        y.name,\n        x.name,\n        z.name,\n    )\n    assert str(\n        tvm.tir.all(x < y, y > z + 1, x < z * 2)\n    ) == \"(((%s: int32 < %s: int32) && (%s > (%s: int32 + 1))) && (%s < (%s*2)))\" % (\n        x.name,\n        y.name,\n        y.name,\n        z.name,\n        x.name,\n        z.name,\n    )\n\n\ndef test_bitwise():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    assert str(x << y) == \"@tir.shift_left(x: int32, y: int32, dtype=int32)\"\n    assert str(x >> y) == \"@tir.shift_right(x: int32, y: int32, dtype=int32)\"\n    assert str(x & y) == \"@tir.bitwise_and(x: int32, y: int32, dtype=int32)\"\n    assert str(x | y) == \"@tir.bitwise_or(x: int32, y: int32, dtype=int32)\"\n    assert str(x ^ y) == \"@tir.bitwise_xor(x: int32, y: int32, dtype=int32)\"\n    assert str(10 & x) == \"@tir.bitwise_and(10, x: int32, dtype=int32)\"\n    assert str(10 | x) == \"@tir.bitwise_or(10, x: int32, dtype=int32)\"\n    assert str(10 ^ x) == \"@tir.bitwise_xor(10, x: int32, dtype=int32)\"\n    assert str(10 >> x) == \"@tir.shift_right(10, x: int32, dtype=int32)\"\n    assert str(10 << x) == \"@tir.shift_left(10, x: int32, dtype=int32)\"\n    assert str(10 % x) == \"floormod(10, x: int32)\"\n\n    assert str(~x) == \"@tir.bitwise_not(x: int32, dtype=int32)\"\n    assert (tvm.tir.const(1, \"int8x2\") >> 1).dtype == \"int8x2\"\n    assert (x >> tvm.tir.const(1, \"int32x2\")).dtype == \"int32x2\"\n    assert (te.var(\"z\", \"int8x2\") << tvm.tir.const(1, \"int8x2\")).dtype == \"int8x2\"\n\n\ndef test_float_bitwise():\n    t = tvm.tir.const(1.5, dtype=\"float32\")\n    for test in [\n        lambda lhs, rhs: lhs << rhs,\n        lambda lhs, rhs: lhs >> rhs,\n        lambda lhs, rhs: lhs | rhs,\n        lambda lhs, rhs: lhs ^ rhs,\n        lambda lhs, rhs: lhs & rhs,\n    ]:\n        try:\n            test(t, 10.0)\n            assert False\n        except tvm.TVMError:\n            pass\n    try:\n        ~t\n        assert False\n    except RuntimeError:\n        pass\n\n\ndef test_shift_bounds():\n    x = te.var(\"x\")\n    for test in [lambda lhs, rhs: lhs << rhs, lambda lhs, rhs: lhs >> rhs]:\n        # negative case\n        for testcase in [(x, -1), (x, 32)]:\n            try:\n                test(*testcase)\n                assert False\n            except tvm.TVMError:\n                pass\n\n        # positive case\n        for testcase in [(x, 0), (x, 16), (x, 31)]:\n            test(*testcase)\n\n\ndef test_divide_by_zero():\n    for test in [\n        lambda lhs, rhs: tvm.tir.floormod(lhs, rhs),\n        lambda lhs, rhs: tvm.tir.floordiv(lhs, rhs),\n        lambda lhs, rhs: tvm.tir.truncmod(lhs, rhs),\n        lambda lhs, rhs: tvm.tir.truncdiv(lhs, rhs),\n        lambda lhs, rhs: tvm.tir.div(lhs, rhs),\n    ]:\n        try:\n            test(tvm.tir.const(5, \"int32\"), tvm.tir.const(0, \"int32\"))\n            assert False\n        except tvm.TVMError:\n            pass\n\n\ndef test_infinity():\n    assert str(tvm.tir.infinity(\"float16\")) == \"inff16\"\n    assert str(tvm.tir.infinity(\"float32\")) == \"inff32\"\n    assert str(tvm.tir.infinity(\"float64\")) == \"inff64\"\n\n\ndef test_isnan():\n    x = te.var(\"x\", \"float32\")\n    assert str(tvm.tir.isnan(x)) == \"@tir.isnan(x: float32, dtype=bool)\"\n    assert str(tvm.tir.isnan(x).dtype) == \"bool\"\n    y = te.var(\"y\", \"float16\")\n    assert str(tvm.tir.isnan(y)) == \"@tir.isnan(cast(float32, y: float16), dtype=bool)\"\n    z = te.var(\"z\", \"int32\")\n    assert str(tvm.tir.isnan(z)) == \"False\"\n    k = te.var(\"k\", \"int8x2\")\n    assert str(tvm.tir.isnan(k).dtype) == \"uint1x2\"\n\n\ndef test_equality():\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    c = a == b\n    assert not c\n    d = c != c\n    assert not d\n\n\ndef test_equality_string_imm():\n    x = \"a\"\n    y = tvm.tir.StringImm(x)\n    x == y.value\n    x == y\n\n\ndef test_prim_func():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    b = tvm.tir.decl_buffer((x,), \"float32\")\n    stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1))\n\n    func = tvm.tir.PrimFunc([x, y, b], stmt)\n    # make sure we can print\n    func.astext()\n    assert func.buffer_map[func.params[2]].same_as(b)\n\n    assert len(func.buffer_map) == 1\n    f2 = func.with_attr({\"calling_conv\": 1, \"tir.noalias\": True})\n    assert f2.attrs[\"calling_conv\"].value == 1\n    assert func.attrs is None\n\n\ndef test_vars():\n    x = tvm.tir.Var(\"xyz\", \"int8\")\n    assert x.dtype == \"int8\"\n    ptype = tvm.ir.PointerType(tvm.ir.PrimType(\"float\"))\n    x = tvm.tir.Var(\"xyz\", ptype)\n    assert x.dtype == \"handle\"\n    assert x.type_annotation == ptype\n    assert isinstance(ptype.element_type, tvm.ir.PrimType)\n\n\ndef test_scoped_storage_vars():\n    dtype = \"float\"\n    storage_scope = \"global.texture\"\n    ptype = tvm.ir.PointerType(tvm.ir.PrimType(dtype), storage_scope)\n    x = tvm.tir.Var(\"xyz\", ptype)\n    assert x.dtype == \"handle\"\n    assert x.type_annotation == ptype\n    assert x.type_annotation.storage_scope == storage_scope\n    assert isinstance(ptype.element_type, tvm.ir.PrimType)\n\n\ndef test_buffer_load_store():\n    b = tvm.tir.decl_buffer((10,), \"float32\")\n    x = tvm.tir.BufferLoad(b, [0])\n    assert isinstance(x, tvm.tir.BufferLoad)\n    assert x.dtype == \"float32\"\n    assert x.buffer == b\n    s = tvm.tir.BufferStore(b, 0.1, [0])\n    assert isinstance(s, tvm.tir.BufferStore)\n\n    s = tvm.tir.BufferRealize(b, [tvm.ir.Range(0, 1)], True, tvm.tir.Evaluate(0))\n    assert isinstance(s, tvm.tir.BufferRealize)\n\n\ndef test_intimm_cond():\n    x = tvm.runtime.convert(1)\n    y = tvm.runtime.convert(1)\n    s = {x}\n    assert y in s\n    assert x == y\n    assert x < 20\n    assert not (x >= 20)\n    assert x < 10 and y < 10\n    assert not tvm.runtime.convert(x != 1)\n    assert x == 1\n\n\ndef test_block_blockrealize():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    vx = tvm.tir.IterVar((16, 16), \"vx\", 0)\n    vx_var = vx.var\n    vy = tvm.tir.IterVar((16, 16), \"vy\", 2)\n    vy_var = vy.var\n    A = tvm.tir.decl_buffer((16), \"float32\")\n    B = tvm.tir.decl_buffer((16, 16), \"float32\")\n    alloc_buffer = tvm.tir.decl_buffer((16, 16), \"float32\")\n    match_buffer = tvm.tir.decl_buffer((16, 16), \"float32\")\n    init_body = tvm.tir.BufferStore(A, 0.0, [vx_var])\n    body = tvm.tir.BufferStore(\n        A,\n        tvm.tir.BufferLoad(A, [vx_var]) + tvm.tir.BufferLoad(B, [vx_var, vy_var]),\n        [vx_var],\n    )\n    reads = [\n        tvm.tir.BufferRegion(\n            B, [tvm.ir.Range.from_min_extent(vx_var, 1), tvm.ir.Range.from_min_extent(vy_var, 1)]\n        )\n    ]\n    writes = [tvm.tir.BufferRegion(A, [tvm.ir.Range.from_min_extent(vx_var, 1)])]\n    block_match_buffer = tvm.tir.MatchBufferRegion(\n        match_buffer, tvm.tir.BufferRegion(B, [tvm.ir.Range(0, 16), tvm.ir.Range(0, 16)])\n    )\n\n    block = tvm.tir.Block(\n        [vx, vy],\n        reads,\n        writes,\n        \"block\",\n        body,\n        init=init_body,\n        alloc_buffers=[alloc_buffer],\n        match_buffers=[block_match_buffer],\n        annotations={\"attr_key\": \"attr_value\"},\n    )\n\n    # Checking Block\n    assert isinstance(block, tvm.tir.Block)\n    # Checking iter_vars\n    assert block.iter_vars[0] == vx\n    assert block.iter_vars[1] == vy\n    # Checking reads/writes region\n    assert isinstance(block.reads[0], tvm.tir.BufferRegion)\n    assert block.reads[0].buffer == B\n    assert block.reads[0].region[0].min == vx_var\n    assert block.reads[0].region[1].min == vy_var\n    assert isinstance(block.writes[0], tvm.tir.BufferRegion)\n    assert block.writes[0].buffer == A\n    assert block.writes[0].region[0].min == vx_var\n    assert block.writes[0].region[0].extent == 1\n    # Checking name_hint\n    assert block.name_hint == \"block\"\n    # Checking body\n    assert block.body == body\n    # Checking init\n    assert block.init == init_body\n    # Checking alloc_buffers\n    assert block.alloc_buffers[0] == alloc_buffer\n    # Checking match_buffers\n    assert block.match_buffers[0].buffer == match_buffer\n    assert isinstance(block.match_buffers[0].source, tvm.tir.BufferRegion)\n    assert block.match_buffers[0].source.buffer == B\n    assert block.match_buffers[0].source.region[0].min == 0\n    assert block.match_buffers[0].source.region[0].extent == 16\n\n    # Checking BlockRealize\n    block_realize = tvm.tir.BlockRealize([x, y], tvm.tir.const(True, \"bool\"), block)\n    assert isinstance(block_realize, tvm.tir.BlockRealize)\n    assert block_realize.iter_values[0] == x\n    assert block_realize.iter_values[1] == y\n    assert block_realize.predicate == tvm.tir.const(True, \"bool\")\n    assert block_realize.block == block\n\n    # make sure we can print using ReprPrinter\n    str(block)\n    str(block_realize)\n    # make sure we can print using TIRTextPrinter\n    func = tvm.tir.PrimFunc([], block_realize)\n    output = func.astext()\n    assert output.find(\"meta[tir.BlockRealise]\") == -1\n    assert output.find(\"bind\") != -1\n    assert output.find(\"reads\") != -1\n    assert output.find(\"writes\") != -1\n    assert output.find(\"alloc_buffer\") != -1\n    assert output.find(\"match_buffer\") != -1\n    assert output.find(\"attr\") != -1\n    assert output.find(\"with init()\") != -1\n\n\ndef test_tir_allocate():\n    dtype = \"int8\"\n    storage_scope = \"global\"\n    ptype = tvm.ir.PointerType(tvm.ir.PrimType(dtype), storage_scope)\n    a = te.var(\"buffer\", ptype)\n    allocate = tvm.tir.Allocate(\n        buffer_var=a,\n        dtype=dtype,\n        extents=[2, 2],\n        condition=tvm.get_global_func(\"tir.const_true\")(dtype, None),\n        body=tvm.tir.Evaluate(2 + 1),\n        annotations={\n            \"attr1\": \"foo\",\n            \"attr2\": \"bar\",\n        },\n    )\n    assert allocate.buffer_var == a\n    assert allocate.dtype == \"int8\"\n    assert list(allocate.extents) == [2, 2]\n    assert allocate.annotations[\"attr1\"] == \"foo\"\n    assert allocate.annotations[\"attr2\"] == \"bar\"\n\n    # make sure we can print using TIRTextPrinter\n    func = tvm.tir.PrimFunc([], allocate)\n    output = func.astext()\n    assert (\n        output.find(\n            'allocate(buffer: Pointer(global int8), int8, [2, 2]), storage_scope = global, annotations = {\"attr2\": \"bar\", \"attr1\": \"foo\"})'\n        )\n        != -1\n    )\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_op_types.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport tvm\nimport tvm.testing\nfrom tvm import tir\n\n\ndef test_tir_op_tvm_tuple():\n    x = tir.Var(\"x\", dtype=\"float32\")\n    y = tir.Var(\"y\", dtype=\"float32\")\n    z = tir.Var(\"z\", dtype=\"float32\")\n    expr = tir.tvm_tuple(x, y, z, 1, 2, 3)\n    assert expr.op.name == \"tir.tvm_tuple\"\n\n\ndef test_tir_op_tvm_struct_get():\n    x = tir.Var(\"x\", dtype=\"handle\")\n    expr = tir.tvm_struct_get(x, 1, 2, dtype=\"int32\")\n    assert expr.op.name == \"tir.tvm_struct_get\"\n\n\ndef test_tir_op_tvm_struct_set():\n    x = tir.Var(\"x\", dtype=\"handle\")\n    expr = tir.tvm_struct_set(x, 1, 2, 3)\n    assert expr.op.name == \"tir.tvm_struct_set\"\n\n\ndef test_tir_op_address_of():\n    buffer = tir.decl_buffer((128), \"float32\")\n    expr = tir.address_of(buffer[0])\n    assert expr.op.name == \"tir.address_of\"\n\n\ndef test_tir_op_lookup_param():\n    expr = tir.lookup_param(\"p0\")\n    assert expr.op.name == \"tir.lookup_param\"\n\n\ndef test_tir_op_reinterpret():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.reinterpret(\"float32\", x)\n    assert expr.op.name == \"tir.reinterpret\"\n\n\ndef test_tir_op_isnullptr():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.isnullptr(x)\n    assert expr.op.name == \"tir.isnullptr\"\n\n\ndef test_tir_op_call_assume():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.assume(cond=x)\n    assert expr.op.name == \"tir.assume\"\n\n\ndef test_tir_op_call_undef():\n    expr = tir.undef()\n    assert expr.op.name == \"tir.undef\"\n\n\ndef test_tir_op_call_likely():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.likely(cond=x)\n    assert expr.op.name == \"tir.likely\"\n\n\ndef test_tir_op_tvm_thread_allreduce():\n    x = tir.Var(\"x\", \"int32\")\n    buffer = tir.decl_buffer((128), \"float32\")\n    y = tir.Var(\"y\", \"handle\")\n    z = tir.Var(\"z\", \"int32\")\n    expr = tir.tvm_thread_allreduce(x, buffer[0], True, y, z)\n    assert expr.op.name == \"tir.tvm_thread_allreduce\"\n\n\ndef test_tir_op_type_annotation():\n    expr = tir.type_annotation(\"int32\")\n    assert expr.op.name == \"tir.type_annotation\"\n\n\ndef test_tir_op_tvm_access_ptr():\n    buffer = tir.decl_buffer((128), \"float32\")\n    expr = tir.tvm_access_ptr(\"float32\", buffer.data, 0, 1, 2)\n    assert expr.op.name == \"tir.tvm_access_ptr\"\n\n\ndef test_tir_op_tvm_throw_last_error():\n    expr = tir.tvm_throw_last_error()\n    assert expr.op.name == \"tir.tvm_throw_last_error\"\n\n\ndef test_tir_op_tvm_load_matrix_sync():\n    buffer = tir.decl_buffer((16, 16), \"float32\")\n    x = tir.Var(\"x\", \"handle\")\n    expr = tir.tvm_load_matrix_sync(buffer.data, 16, 16, 16, 0, x, 128, \"row_major\")\n    assert expr.op.name == \"tir.tvm_load_matrix_sync\"\n\n\ndef test_tir_op_tvm_store_matrix_sync():\n    buffer = tir.decl_buffer((16, 16), \"float32\")\n    x = tir.Var(\"x\", \"handle\")\n    expr = tir.tvm_store_matrix_sync(buffer.data, 16, 16, 16, 0, x, 128, \"row_major\")\n    assert expr.op.name == \"tir.tvm_store_matrix_sync\"\n\n\ndef test_tir_op_tvm_mma_sync():\n    buffer_0 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_1 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_2 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_3 = tir.decl_buffer((16, 16), \"float32\")\n    expr = tir.tvm_mma_sync(buffer_0.data, 0, buffer_1.data, 0, buffer_2.data, 0, buffer_3.data, 0)\n    assert expr.op.name == \"tir.tvm_mma_sync\"\n\n\ndef test_tir_op_tvm_bmma_sync():\n    buffer_0 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_1 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_2 = tir.decl_buffer((16, 16), \"float32\")\n    buffer_3 = tir.decl_buffer((16, 16), \"float32\")\n    expr = tir.tvm_bmma_sync(buffer_0.data, 0, buffer_1.data, 0, buffer_2.data, 0, buffer_3.data, 0)\n    assert expr.op.name == \"tir.tvm_bmma_sync\"\n\n\ndef test_tir_op_tvm_fill_fragment():\n    buffer = tir.decl_buffer((16, 16), \"float32\")\n    expr = tir.tvm_fill_fragment(buffer.data, 16, 16, 16, 0, 0)\n    assert expr.op.name == \"tir.tvm_fill_fragment\"\n\n\ndef test_tir_op_ptx_mma():\n    buffer_a = tir.decl_buffer([32], \"int4\", scope=\"local\")\n    buffer_b = tir.decl_buffer([16], \"uint4\", scope=\"local\")\n    buffer_c = tir.decl_buffer([4], \"int32\", scope=\"local\")\n    expr = tir.ptx_mma(\n        \"int32\",\n        \"m8n8k32\",\n        \"row\",\n        \"col\",\n        \"int4\",\n        \"uint4\",\n        \"int32\",\n        buffer_a.data,\n        0,\n        buffer_b.data,\n        0,\n        buffer_c.data,\n        0,\n        False,\n    )\n    assert expr.op.name == \"tir.ptx_mma\"\n\n\ndef test_tir_op_ptx_mma_sp():\n    buffer_a = tir.decl_buffer([32], \"int4\", scope=\"local\")\n    buffer_b = tir.decl_buffer([16], \"uint4\", scope=\"local\")\n    buffer_c = tir.decl_buffer([4], \"int32\", scope=\"local\")\n    buffer_d = tir.decl_buffer([1], \"uint32\", scope=\"local\")\n    expr = tir.ptx_mma_sp(\n        \"int32\",\n        \"m8n8k32\",\n        \"row\",\n        \"col\",\n        \"int4\",\n        \"uint4\",\n        \"int32\",\n        buffer_a.data,\n        0,\n        buffer_b.data,\n        0,\n        buffer_c.data,\n        0,\n        buffer_d.data,\n        0,\n        0,\n        False,\n    )\n    assert expr.op.name == \"tir.ptx_mma_sp\"\n\n\ndef test_tir_op_mma_store():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    y = tir.Var(\"y\", dtype=\"int32\")\n    buffer_w = tir.decl_buffer([16, 8], dtype=\"int32\", scope=\"warp\", offset_factor=1)\n    buffer = tir.decl_buffer(\n        [16, 16], dtype=\"int32\", scope=\"global\", offset_factor=1, strides=[x, y]\n    )\n    expr = tir.mma_store(\n        \"int32\",\n        16,\n        16,\n        buffer.access_ptr(\"w\"),\n        buffer_w.data,\n        buffer_w.elem_offset,\n        x,\n    )\n    assert expr.op.name == \"tir.mma_store\"\n\n\ndef test_tir_op_mma_fill():\n    buffer_w = tir.decl_buffer([16, 8], dtype=\"int32\", scope=\"warp\", offset_factor=1)\n    expr = tir.mma_fill(\"int32\", 8, buffer_w.data, buffer_w.elem_offset)\n    assert expr.op.name == \"tir.mma_fill\"\n\n\ndef test_op_ptx_ldmatrix():\n    buffer_shared = tir.decl_buffer([16, 16], \"float16\", scope=\"shared\")\n    buffer_local = tir.decl_buffer([8], \"float16\", scope=\"local\")\n    expr = tir.ptx_ldmatrix(\n        \"float16\", False, 4, \".b16\", buffer_local.data, 0, buffer_shared.data, 0\n    )\n    assert expr.op.name == \"tir.ptx_ldmatrix\"\n\n\ndef test_op_ptx_cp_async():\n    buffer_shared = tir.decl_buffer([16, 16], \"float16\", scope=\"shared\")\n    buffer_local = tir.decl_buffer([8], \"float16\", scope=\"local\")\n    expr = tir.ptx_cp_async(\"float16\", buffer_shared.data, 0, buffer_local.data, 0, 16)\n    assert expr.op.name == \"tir.ptx_cp_async\"\n\n\ndef test_op_ptx_commit_group():\n    expr = tir.ptx_commit_group()\n    assert expr.op.name == \"tir.ptx_commit_group\"\n\n\ndef test_op_ptx_wait_group():\n    expr = tir.ptx_wait_group(8)\n    assert expr.op.name == \"tir.ptx_wait_group\"\n\n\ndef test_tir_op_vectorlow():\n    buffer = tir.decl_buffer((4, 4), \"int8\", offset_factor=1)\n    vec = buffer.vload([0, 0], dtype=\"int8x16\")\n    expr = tir.vectorlow(\"int8x8\", vec)\n    assert expr.op.name == \"tir.vectorlow\"\n\n\ndef test_tir_op_vectorhigh():\n    buffer = tir.decl_buffer((4, 4), \"int8\", offset_factor=1)\n    vec = buffer.vload([0, 0], dtype=\"int8x16\")\n    expr = tir.vectorhigh(\"int8x8\", vec)\n    assert expr.op.name == \"tir.vectorhigh\"\n\n\ndef test_tir_op_vectorcombine():\n    buffer = tir.decl_buffer((4, 4), \"int8\", offset_factor=1)\n    vec = buffer.vload([0, 0], dtype=\"int8x16\")\n    expr = tir.vectorcombine(\"int8x8\", vec, vec)\n    assert expr.op.name == \"tir.vectorcombine\"\n\n\ndef test_tir_op_shift_left():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    y = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.shift_left(x, y)\n    assert expr.op.name == \"tir.shift_left\"\n\n\ndef test_tir_op_shift_right():\n    x = tir.Var(\"x\", dtype=\"int32\")\n    y = tir.Var(\"x\", dtype=\"int32\")\n    expr = tir.shift_right(x, y)\n    assert expr.op.name == \"tir.shift_right\"\n\n\ndef test_tir_op_TVMBackendAllocWorkspace():\n    expr = tir.TVMBackendAllocWorkspace(0, 1, 2, 3, 4)\n    assert expr.op.name == \"tir.TVMBackendAllocWorkspace\"\n\n\ndef test_tir_op_TVMBackendFreeWorkspace():\n    buffer = tir.decl_buffer((128), \"float32\")\n    expr = tir.TVMBackendFreeWorkspace(0, 1, buffer.data)\n    assert expr.op.name == \"tir.TVMBackendFreeWorkspace\"\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef check_throws(f):\n    try:\n        f()\n    except tvm.error.TVMError:\n        pass\n    else:\n        raise AssertionError(\"Should have raised an exception but didn't.\")\n\n\ndef test_const_fold():\n    def check(f, *args):\n        x = f(*[tvm.tir.const(x, \"int32\") for x in args])\n        y = f(*args)\n        if not isinstance(x, (tvm.tir.IntImm,)) or x.value != int(y):\n            raise ValueError(\"check error: %s vs %s \" % (x, y))\n\n    tmod = tvm.tir.truncmod\n    check(lambda x, y: x + y, 3, 4)\n    check(lambda x, y: x * y, 3, 12)\n    check(lambda x, y: x * y - 10, 3, 12)\n    check(lambda x, y: x - tmod(y, 10), 3, 12)\n    check(lambda x, y: x // y + 10, 100, 12)\n    check(lambda x, y: x & y + 10, 112, 128)\n    check(lambda x, y: x > y, 112, 128)\n    check(lambda x, y: x < y, 112, 128)\n    check(lambda x, y: x <= y, 112, 128)\n    check(lambda x, y: x >= y, 112, 128)\n    check(lambda x, y: (x | y) ^ 10, 112, 128)\n\n\ndef test_const_fold2():\n    x = te.var(\"x\")\n    tmod = tvm.tir.truncmod\n    tdiv = tvm.tir.truncdiv\n    assert (x + 0).same_as(x)\n    assert (0 + x).same_as(x)\n    assert (x - 0).same_as(x)\n    assert tmod(x, 1).value == 0\n    assert (x * 1).same_as(x)\n    assert (1 * x).same_as(x)\n    assert isinstance(tdiv(1, x), tvm.tir.Div)\n\n\ndef test_const_fold3():\n    # Test that using ints with logic operations is forbidden\n    x = te.var(\"x\")\n    for val in [0, 1]:\n        for func in [tvm.tir.all, tvm.tir.any]:\n            check_throws(lambda: func(tvm.tir.const(val, \"uint1\"), x))\n            check_throws(lambda: func(x, tvm.tir.const(val, \"uint1\")))\n\n    # Test const folding when both arguments are const\n    for tvm_func, py_func in [\n        (tvm.tir.all, lambda a, b: a and b),\n        (tvm.tir.any, lambda a, b: a or b),\n    ]:\n        for v1 in [0, 1]:\n            for v2 in [0, 1]:\n                assert tvm.ir.structural_equal(\n                    tvm_func(tvm.tir.const(v1, \"uint1\"), tvm.tir.const(v2, \"uint1\")),\n                    tvm.tir.const(py_func(v1, v2), \"uint1\"),\n                )\n\n    x = te.var(\"x\", \"uint1\")\n    true = tvm.tir.const(1, \"uint1\")\n    false = tvm.tir.const(0, \"uint1\")\n\n    assert tvm.tir.all(x, true).same_as(x)\n    assert tvm.tir.all(true, x).same_as(x)\n    assert tvm.tir.any(x, false).same_as(x)\n    assert tvm.tir.any(false, x).same_as(x)\n\n    assert tvm.tir.all(x, false).same_as(false)\n    assert tvm.tir.all(false, x).same_as(false)\n    assert tvm.tir.any(x, true).same_as(true)\n    assert tvm.tir.any(true, x).same_as(true)\n\n\ndef test_const_fold4():\n    x1 = tvm.tir.const(4, \"int32\")\n    x2 = x1 + 5\n    tdiv = tvm.tir.truncdiv\n    assert isinstance(x2, tvm.tir.IntImm) and x2.value == 9\n    x3 = tdiv(x2, 3)\n    assert isinstance(x3, tvm.tir.IntImm) and x3.value == 3\n    x4 = x3 + 0.55\n    assert isinstance(x4, tvm.tir.FloatImm) and abs(x4.value - 3.55) < 1e-6\n    x5 = te.ceil(x4)\n    assert isinstance(x5, tvm.tir.FloatImm) and x5.value == 4\n    x6 = x5.astype(\"int\")\n    assert isinstance(x6, tvm.tir.IntImm) and x6.value == 4, \"x6={}\".format(x6)\n    y = (te.round((tvm.tir.const(6.5, \"float32\") - 1) / 1.5) + 2).astype(\"int\")\n    assert isinstance(y, tvm.tir.IntImm) and y.value == 6\n\n\ndef test_binary_dtype_match():\n    def verify_general_dtype_support(f, is_conditional=False):\n        rules = [\n            [(\"bool\", \"int32\"), \"int32\"],\n            [(\"int32\", \"float32\"), \"float32\"],\n            [(\"int32\", \"int64\"), \"int64\"],\n            [(\"uint32\", \"int8\"), \"uint32\"],\n            [(\"uint32\", \"int32\"), \"uint32\"],\n        ]\n        for (lhs_dtype, rhs_dtype), out_dtype in rules:\n            lhs = te.var(\"lhs\", dtype=lhs_dtype)\n            rhs = te.var(\"rhs\", dtype=rhs_dtype)\n            out = f(lhs, rhs)\n            if not is_conditional:\n                assert out.dtype == out_dtype\n            else:\n                assert out.dtype == \"bool\"\n            if hasattr(out, \"a\"):\n                assert out.a.dtype == out_dtype\n                assert out.b.dtype == out_dtype\n            elif hasattr(out, \"args\"):\n                # CallOp\n                assert out.args[0].dtype == out_dtype\n                assert out.args[1].dtype == out_dtype\n            else:\n                raise ValueError(\"Unknown binary op format!\")\n\n    def verify_callop_float_only(f):\n        for lhs_dtype in [\"int32\", \"float32\", \"float64\"]:\n            for rhs_dtype in [\"int32\", \"float32\", \"float64\"]:\n                lhs = te.var(\"lhs\", dtype=lhs_dtype)\n                rhs = te.var(\"rhs\", dtype=rhs_dtype)\n                if \"float\" not in lhs_dtype and \"float\" not in rhs_dtype:\n                    check_throws(lambda: f(lhs, rhs))\n                elif \"float\" in lhs_dtype:\n                    out = f(lhs, rhs)\n\n                    # Upcasting for floating point types\n                    dtypes = [lhs_dtype, rhs_dtype]\n                    if \"float64\" in dtypes:\n                        target_dtype = \"float64\"\n                    elif \"float32\" in dtypes:\n                        target_dtype = \"float32\"\n                    else:\n                        target_dtype = \"int32\"\n                    assert out.dtype == target_dtype\n\n                    # Final inputs are the right type\n                    assert out.args[0].dtype == target_dtype\n                    assert out.args[1].dtype == target_dtype\n                else:\n                    out = f(lhs, rhs)\n                    assert out.dtype == rhs_dtype\n                    assert out.args[0].dtype == rhs_dtype\n                    assert out.args[1].dtype == rhs_dtype\n\n    verify_general_dtype_support(lambda a, b: a + b)\n    verify_general_dtype_support(lambda a, b: a * b)\n    verify_general_dtype_support(lambda a, b: a >= b, is_conditional=True)\n    verify_general_dtype_support(lambda a, b: a <= b, is_conditional=True)\n    verify_callop_float_only(lambda a, b: te.power(a, b))\n\n    # verify bool & int32 constant folding\n    assert tvm.tir.const(1) == tvm.tir.const(True)\n    assert tvm.tir.const(2) != tvm.tir.const(True)\n\n\ndef test_if_then_else():\n    cases = [\n        [(te.var(\"cond\", dtype=\"bool\"), \"bool\", \"int32\"), \"int32\"],\n        [(True, \"int32\", \"float32\"), \"float32\"],\n        [(False, \"int32\", \"int64\"), \"int64\"],\n        [(te.var(\"cond\", dtype=\"bool\"), \"uint32\", \"int32\"), \"uint32\"],\n        [(te.var(\"cond\", dtype=\"int32\"), \"uint32\", \"int32\"), \"uint32\"],\n    ]\n    for (cond, lhs_dtype, rhs_dtype), out_dtype in cases:\n        lhs = te.var(\"lhs\", dtype=lhs_dtype)\n        rhs = te.var(\"rhs\", dtype=rhs_dtype)\n        if cond is True or cond is False:\n            out = tvm.tir.if_then_else(cond, lhs, rhs)\n            out2 = tvm.tir.if_then_else(not cond, rhs, lhs)\n            out3 = tvm.tir.if_then_else(not cond, lhs, rhs)\n            assert tvm.ir.structural_equal(out, out2) == 1\n            if cond:\n                assert tvm.ir.structural_equal(out, lhs.astype(out_dtype)) == 1\n                assert tvm.ir.structural_equal(out3, rhs.astype(out_dtype)) == 1\n            else:\n                assert tvm.ir.structural_equal(out, rhs.astype(out_dtype)) == 1\n                assert tvm.ir.structural_equal(out3, lhs.astype(out_dtype)) == 1\n        elif cond.dtype == \"bool\":\n            out = tvm.tir.if_then_else(cond, lhs, rhs)\n            assert out.dtype == out_dtype\n            assert out.args[1].dtype == out_dtype\n            assert out.args[2].dtype == out_dtype\n        elif cond.dtype != \"bool\":\n            check_throws(lambda: tvm.tir.if_then_else(cond, lhs, rhs))\n        else:\n            raise ValueError(\"Unknown combinations\")\n\n\nif __name__ == \"__main__\":\n    test_const_fold()\n    test_const_fold2()\n    test_const_fold3()\n    test_const_fold4()\n    test_binary_dtype_match()\n    test_if_then_else()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ptx_cp_async.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\n@T.prim_func\ndef ptx_cp_async(A: T.Buffer[(32, 128), \"float16\"], B: T.Buffer[(32, 128), \"float16\"]) -> None:\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    bx = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(bx, 1)\n    T.launch_thread(tx, 32)\n    with T.block():\n        A_shared = T.alloc_buffer([32, 128], \"float16\", scope=\"shared\")\n        T.reads(A[0:32, 0:128])\n        T.writes(B[0:32, 0:128])\n\n        for i in range(16):\n            T.evaluate(\n                T.ptx_cp_async(\n                    A_shared.data, tx * 128 + 8 * i, A.data, tx * 128 + 8 * i, 16, dtype=\"float16\"\n                )\n            )\n\n        # TODO(masahi): Remove dtype requirement from TVMScript parser\n        T.evaluate(T.ptx_commit_group(dtype=\"\"))\n        T.evaluate(T.ptx_wait_group(0, dtype=\"\"))\n\n        for i in range(128):\n            B[tx, i] = A_shared[tx, i]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_ptx_cp_async():\n    f = ptx_cp_async\n\n    mod = tvm.build(f, target=\"cuda\")\n    A_np = np.random.rand(32, 128).astype(\"float16\")\n    B_np = np.zeros((32, 128)).astype(\"float16\")\n    dev = tvm.cuda(0)\n    A_nd = tvm.nd.array(A_np, device=dev)\n    B_nd = tvm.nd.array(B_np, device=dev)\n    mod(A_nd, B_nd)\n    tvm.testing.assert_allclose(B_nd.numpy(), A_np)\n\n\nif __name__ == \"__main__\":\n    test_ptx_cp_async()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ptx_ldmatrix.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\n@T.prim_func\ndef ptx_ldmatrix(\n    A: T.Buffer[(16, 16), \"float16\"], B: T.Buffer[(16, 16), \"float16\"], num: T.int32, trans: T.uint8\n) -> None:\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    bx = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(bx, 1)\n    T.launch_thread(tx, 32)\n    with T.block():\n        A_shared = T.alloc_buffer([16, 16], \"float16\", scope=\"shared\")\n        A_local = T.alloc_buffer([8], \"float16\", scope=\"local\")\n\n        for i in range(8):\n            A_shared[i * 2 + tx // 16, tx % 16] = A[i * 2 + tx // 16, tx % 16]\n\n        T.evaluate(\n            T.ptx_ldmatrix(\n                trans,\n                num,\n                \".b16\",\n                A_local.data,\n                0,\n                A_shared.data,\n                16 * (tx % 16) + 8 * (tx // 16),\n                dtype=\"float16\",\n            )\n        )\n\n        for k in range(2):\n            for j in range(2):\n                for i in range(2):\n                    B[8 * j + tx // 4, 8 * k + (tx % 4) * 2 + i] = A_local[4 * k + 2 * j + i]\n\n\n@tvm.testing.requires_cuda_compute_version(7, 5)\ndef test_ptx_ldmatrix():\n    f = ptx_ldmatrix\n    _, _, param_num, param_trans = f.params\n\n    for num in [1, 2, 4]:\n        for trans in [False, True]:\n            mod = tvm.build(f.specialize({param_num: num, param_trans: trans}), target=\"cuda\")\n            A_np = np.random.rand(16, 16).astype(\"float16\")\n            A_mask_np = np.zeros_like(A_np)\n            if num == 1:\n                if trans:\n                    A_mask_np[:8, :8] = A_np[:8, :8].T\n                else:\n                    A_mask_np[:8, :8] = A_np[:8, :8]\n            elif num == 2:\n                if trans:\n                    A_mask_np[:8, :8] = A_np[:8, :8].T\n                    A_mask_np[8:16, :8] = A_np[8:16, :8].T\n                else:\n                    A_mask_np[:16, :8] = A_np[:16, :8]\n            else:  # num == 4\n                if trans:\n                    A_mask_np[:8, :8] = A_np[:8, :8].T\n                    A_mask_np[8:16, :8] = A_np[8:16, :8].T\n                    A_mask_np[:8, 8:16] = A_np[:8, 8:16].T\n                    A_mask_np[8:16, 8:16] = A_np[8:16, 8:16].T\n                else:\n                    A_mask_np[:16, :16] = A_np[:16, :16]\n            B_np = np.zeros((16, 16)).astype(\"float16\")\n            dev = tvm.cuda(0)\n            A_nd = tvm.nd.array(A_np, device=dev)\n            B_nd = tvm.nd.array(B_np, device=dev)\n            mod(A_nd, B_nd)\n            tvm.testing.assert_allclose(B_nd.numpy(), A_mask_np)\n\n\nif __name__ == \"__main__\":\n    test_ptx_ldmatrix()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ptx_mma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport pytest\n\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\n@T.prim_func\ndef gemm_mma_m8n8k4_row_col_fp64pf64fp64(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [8, 4], dtype=\"float64\")\n    B = T.match_buffer(b, [8, 4], dtype=\"float64\")\n    C = T.match_buffer(c, [8, 8], dtype=\"float64\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([1], \"float64\", scope=\"local\")\n    MultiB = T.decl_buffer([1], \"float64\", scope=\"local\")\n    Accum = T.decl_buffer([2], \"float64\", scope=\"local\")\n    for i in range(2):\n        Accum[i] = T.float64(0)\n\n    MultiA[0] = A[(tx % 32) // 4, (tx % 32) % 4]\n    MultiB[0] = B[(tx % 32) // 4, (tx % 32) % 4]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k4\",\n            \"row\",\n            \"col\",\n            \"fp64\",\n            \"fp64\",\n            \"fp64\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float64\",\n        )\n    )\n    for mma_accum_c_id in range(2):\n        C[(tx % 32) // 4, (tx % 32) % 4 * 2 + mma_accum_c_id] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m8n8k4_row_col_fp64pf64fp64():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k4_row_col_fp64pf64fp64)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [8, 4]).astype(\"float64\")\n    B_np = np.random.uniform(-1, 1, [8, 4]).astype(\"float64\")\n    C_np = np.zeros([8, 8]).astype(\"float64\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float64\"), B_np.astype(\"float64\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m8n8k4_row_row_fp16fp16fp16(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 4], dtype=\"float16\")\n    B = T.match_buffer(b, [4, 16], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 16], dtype=\"float16\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([4], \"float16\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"float16\", scope=\"local\")\n    Accum = T.decl_buffer([8], \"float16\", scope=\"local\")\n    for i in range(8):\n        Accum[i] = T.float32(0)\n\n    for mma_multi_a_col in T.vectorized(4):\n        MultiA[mma_multi_a_col] = A[\n            ((tx % 32) % 4) + (4 * ((((tx % 32) // 16 + (tx % 32) % 16 // 4 * 2)) % 4)),\n            mma_multi_a_col,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) % 4,\n            mma_multi_b_col + (4 * ((tx % 32) // 8)),\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k4\",\n            \"row\",\n            \"row\",\n            \"fp16\",\n            \"fp16\",\n            \"fp16\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float16\",\n        )\n    )\n    for mma_accum_c_id in range(8):\n        C[\n            ((tx % 32) % 4) + (4 * ((((tx % 32) // 16 + (tx % 32) % 16 // 4 * 2)) % 4)),\n            mma_accum_c_id % 4 + (4 * ((tx % 32) % 16 // 8)) + mma_accum_c_id // 4 * 8,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(7)\ndef test_gemm_mma_m8n8k4_row_row_fp16fp16fp16():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k4_row_row_fp16fp16fp16)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [16, 4]).astype(\"float16\")\n    B_np = np.random.uniform(-1, 1, [4, 16]).astype(\"float16\")\n    C_np = np.zeros([16, 16]).astype(\"float16\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float16\"), B_np.astype(\"float16\"))\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m8n8k4_row_row_fp16fp16fp32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 4], dtype=\"float16\")\n    B = T.match_buffer(b, [4, 16], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 16], dtype=\"float32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([4], \"float16\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"float16\", scope=\"local\")\n    Accum = T.decl_buffer([8], \"float32\", scope=\"local\")\n\n    for i in range(8):\n        Accum[i] = T.float32(0)\n\n    for mma_multi_a_col in T.vectorized(4):\n        MultiA[mma_multi_a_col] = A[\n            ((tx % 32) % 4) + (4 * ((((tx % 32) // 16 + (tx % 32) % 16 // 4 * 2)) % 4)),\n            mma_multi_a_col,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) % 4,\n            mma_multi_b_col + (4 * ((tx % 32) // 8)),\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k4\",\n            \"row\",\n            \"row\",\n            \"fp16\",\n            \"fp16\",\n            \"fp32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float32\",\n        )\n    )\n    for mma_accum_c_id in range(8):\n        C[\n            ((tx % 32) % 2)\n            + ((mma_accum_c_id // 2 % 2) * 2)\n            + 4 * ((tx % 32) // 16)\n            + ((tx % 32) % 16 // 4) % 2 * 8,\n            (tx % 32) % 4 // 2 * 2\n            + (tx % 32) % 16 // 8 * 4\n            + mma_accum_c_id % 2\n            + mma_accum_c_id // 4 * 8,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(7)\ndef test_gemm_mma_m8n8k4_row_row_fp16fp16fp32():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k4_row_row_fp16fp16fp32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [16, 4]).astype(\"float16\")\n    B_np = np.random.uniform(-1, 1, [4, 16]).astype(\"float16\")\n    C_np = np.zeros([16, 16]).astype(\"float32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float32\"), B_np.astype(\"float32\"))\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m8n8k16_row_col_s8s8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [8, 16], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 16], dtype=\"int8\")\n    C = T.match_buffer(c, [8, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([4], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"int8\", scope=\"local\")\n    Accum = T.decl_buffer([2], \"int32\", scope=\"local\")\n    for i in range(2):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in T.vectorized(4):\n        MultiA[mma_multi_a_col] = A[(tx % 32) // 4, mma_multi_a_col + (tx % 32) % 4 * 4]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[(tx % 32) // 4, mma_multi_b_col + (tx % 32) % 4 * 4]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k16\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"int8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(2):\n        C[(tx % 32) // 4, (tx % 32) % 4 * 2 + mma_accum_c_id] = Accum[mma_accum_c_id]\n\n\n# This test uses mma instructions that are not available on NVCC 10.1.\n# Failure occurs during the external call to nvcc, when attempting to\n# generate the .fatbin file.\n@tvm.testing.requires_nvcc_version(11)\n@tvm.testing.requires_cuda_compute_version(7, 5)\ndef test_gemm_mma_m8n8k16_row_col_s8s8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k16_row_col_s8s8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [8, 16]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 16]).astype(\"int8\")\n    C_np = np.zeros([8, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m8n8k16_row_col_s8u8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [8, 16], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 16], dtype=\"uint8\")\n    C = T.match_buffer(c, [8, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([4], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"uint8\", scope=\"local\")\n    Accum = T.decl_buffer([2], \"int32\", scope=\"local\")\n    for i in range(2):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in T.vectorized(4):\n        MultiA[mma_multi_a_col] = A[(tx % 32) // 4, mma_multi_a_col + (tx % 32) % 4 * 4]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[(tx % 32) // 4, mma_multi_b_col + (tx % 32) % 4 * 4]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k16\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"uint8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(2):\n        C[(tx % 32) // 4, (tx % 32) % 4 * 2 + mma_accum_c_id] = Accum[mma_accum_c_id]\n\n\n# This test uses mma instructions that are not available on NVCC 10.1.\n# Failure occurs during the external call to nvcc, when attempting to\n# generate the .fatbin file.\n@tvm.testing.requires_nvcc_version(11)\n@tvm.testing.requires_cuda_compute_version(7, 5)\ndef test_gemm_mma_m8n8k16_row_col_s8u8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k16_row_col_s8u8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [8, 16]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 16]).astype(\"uint8\")\n    C_np = np.zeros([8, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m8n8k32_row_col_s4s4s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [8, 32], dtype=\"int4\")\n    B = T.match_buffer(b, [8, 32], dtype=\"int4\")\n    C = T.match_buffer(c, [8, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"int4\", scope=\"local\")\n    MultiB = T.decl_buffer([8], \"int4\", scope=\"local\")\n    Accum = T.decl_buffer([2], \"int32\", scope=\"local\")\n    for i in range(2):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in T.vectorized(8):\n        MultiA[mma_multi_a_col] = A[(tx % 32) // 4, mma_multi_a_col + (tx % 32) % 4 * 8]\n    for mma_multi_b_col in T.vectorized(8):\n        MultiB[mma_multi_b_col] = B[(tx % 32) // 4, mma_multi_b_col + (tx % 32) % 4 * 8]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k32\",\n            \"row\",\n            \"col\",\n            \"int4\",\n            \"int4\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(2):\n        C[(tx % 32) // 4, (tx % 32) % 4 * 2 + mma_accum_c_id] = Accum[mma_accum_c_id]\n\n\n# This test uses mma instructions that are not available on NVCC 10.1.\n# Failure occurs during the external call to nvcc, when attempting to\n# generate the .fatbin file.\n@tvm.testing.requires_nvcc_version(11)\n@tvm.testing.requires_cuda_compute_version(7, 5)\ndef test_gemm_mma_m8n8k32_row_col_s4s4s32():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k32_row_col_s4s4s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.empty([8, 32], \"int4\", ctx)\n    B_tvm = tvm.nd.empty([8, 32], \"int4\", ctx)\n    C_tvm = tvm.nd.empty([8, 8], \"int32\", ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n    # Currently the correctness is not checked.\n    # TODO: add correctness checking here.\n\n\n@T.prim_func\ndef gemm_mma_m8n8k32_row_col_s4u4s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [8, 32], dtype=\"int4\")\n    B = T.match_buffer(b, [8, 32], dtype=\"uint4\")\n    C = T.match_buffer(c, [8, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"int4\", scope=\"local\")\n    MultiB = T.decl_buffer([8], \"uint4\", scope=\"local\")\n    Accum = T.decl_buffer([2], \"int32\", scope=\"local\")\n    for i in range(2):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in T.vectorized(8):\n        MultiA[mma_multi_a_col] = A[(tx % 32) // 4, mma_multi_a_col + (tx % 32) % 4 * 8]\n    for mma_multi_b_col in T.vectorized(8):\n        MultiB[mma_multi_b_col] = B[(tx % 32) // 4, mma_multi_b_col + (tx % 32) % 4 * 8]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k32\",\n            \"row\",\n            \"col\",\n            \"int4\",\n            \"uint4\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(2):\n        C[(tx % 32) // 4, (tx % 32) % 4 * 2 + mma_accum_c_id] = Accum[mma_accum_c_id]\n\n\n# This test uses mma instructions that are not available on NVCC 10.1.\n# Failure occurs during the external call to nvcc, when attempting to\n# generate the .fatbin file.\n@tvm.testing.requires_nvcc_version(11)\n@tvm.testing.requires_cuda_compute_version(7, 5)\ndef test_gemm_mma_m8n8k32_row_col_s4u4s32():\n    sch = tvm.tir.Schedule(gemm_mma_m8n8k32_row_col_s4u4s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.empty([8, 32], \"int4\", ctx)\n    B_tvm = tvm.nd.empty([8, 32], \"uint4\", ctx)\n    C_tvm = tvm.nd.empty([8, 8], \"int32\", ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n    # Currently the correctness is not checked.\n    # TODO: add correctness checking here.\n\n\n@T.prim_func\ndef gemm_mma_m16n8k8_row_col_fp16fp16fp32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 8], dtype=\"float16\")\n    B = T.match_buffer(b, [8, 8], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([4], \"float16\", scope=\"local\")\n    MultiB = T.decl_buffer([2], \"float16\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"float32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.float32(0)\n\n    for mma_multi_a_col in T.vectorized(4):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col // 2 * 8, (tx % 32) % 4 * 2 + mma_multi_a_col % 2\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4 + mma_multi_b_col // 2 * 8, (tx % 32) % 4 * 2 + mma_multi_b_col % 2\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k8\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[(tx % 32) // 4 + mma_accum_c_id // 2 * 8, (tx % 32) % 4 * 2 + mma_accum_c_id % 2] = Accum[\n            mma_accum_c_id\n        ]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k8_row_col_fp16fp16fp32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k8_row_col_fp16fp16fp32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [16, 8]).astype(\"float16\")\n    B_np = np.random.uniform(-1, 1, [8, 8]).astype(\"float16\")\n    C_np = np.zeros([16, 8]).astype(\"float32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float32\"), B_np.astype(\"float32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k16_row_col_fp16fp16fp16(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"float16\")\n    B = T.match_buffer(b, [8, 16], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float16\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"float16\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"float16\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"float16\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.float32(0)\n\n    for mma_multi_a_col in range(8):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 4 // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_multi_a_col % 2 + mma_multi_a_col // 4 * 8,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 2 + mma_multi_b_col % 2 + mma_multi_b_col // 2 * 8,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp16\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float16\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k16_row_col_fp16fp16fp16():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k16_row_col_fp16fp16fp16)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [16, 16]).astype(\"float16\")\n    B_np = np.random.uniform(-1, 1, [8, 16]).astype(\"float16\")\n    C_np = np.zeros([16, 8]).astype(\"float16\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float16\"), B_np.astype(\"float16\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k16_row_col_fp16fp16fp32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"float16\")\n    B = T.match_buffer(b, [8, 16], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"float16\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"float16\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"float32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.float32(0)\n\n    for mma_multi_a_col in range(8):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 4 // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_multi_a_col % 2 + mma_multi_a_col // 4 * 8,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 2 + mma_multi_b_col % 2 + mma_multi_b_col // 2 * 8,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"float32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k16_row_col_fp16fp16fp32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k16_row_col_fp16fp16fp32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-1, 1, [16, 16]).astype(\"float16\")\n    B_np = np.random.uniform(-1, 1, [8, 16]).astype(\"float16\")\n    C_np = np.zeros([16, 8]).astype(\"float32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"float32\"), B_np.astype(\"float32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k16_row_col_s8s8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 16], dtype=\"int8\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"int8\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(8):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col // 4 * 8,\n            (tx % 32) % 4 * 4 + mma_multi_a_col % 4,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 4 + mma_multi_b_col,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"int8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k16_row_col_s8s8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k16_row_col_s8s8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [16, 16]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 16]).astype(\"int8\")\n    C_np = np.zeros([16, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k16_row_col_s8u8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 16], dtype=\"uint8\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([8], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([4], \"uint8\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(8):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col // 4 * 8,\n            (tx % 32) % 4 * 4 + mma_multi_a_col % 4,\n        ]\n    for mma_multi_b_col in T.vectorized(4):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 4 + mma_multi_b_col,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"uint8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k16_row_col_s8u8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k16_row_col_s8u8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [16, 16]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 16]).astype(\"uint8\")\n    C_np = np.zeros([16, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k32_row_col_s8s8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 32], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 32], dtype=\"int8\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([16], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([8], \"int8\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(16):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 8 // 4 * 8,\n            (tx % 32) % 4 * 4 + mma_multi_a_col % 4 + mma_multi_a_col // 8 * 16,\n        ]\n    for mma_multi_b_col in range(8):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 4 + mma_multi_b_col % 4 + mma_multi_b_col // 4 * 16,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k32\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"int8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k32_row_col_s8s8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k32_row_col_s8s8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [16, 32]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 32]).astype(\"int8\")\n    C_np = np.zeros([16, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k32_row_col_s8u8s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 32], dtype=\"int8\")\n    B = T.match_buffer(b, [8, 32], dtype=\"uint8\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([16], \"int8\", scope=\"local\")\n    MultiB = T.decl_buffer([8], \"uint8\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(16):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 8 // 4 * 8,\n            (tx % 32) % 4 * 4 + mma_multi_a_col % 4 + mma_multi_a_col // 8 * 16,\n        ]\n    for mma_multi_b_col in range(8):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 4 + mma_multi_b_col % 4 + mma_multi_b_col // 4 * 16,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k32\",\n            \"row\",\n            \"col\",\n            \"int8\",\n            \"uint8\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k32_row_col_s8u8s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k32_row_col_s8u8s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    A_np = np.random.uniform(-10, 10, [16, 32]).astype(\"int8\")\n    B_np = np.random.uniform(-10, 10, [8, 32]).astype(\"uint8\")\n    C_np = np.zeros([16, 8]).astype(\"int32\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.array(A_np, ctx)\n    B_tvm = tvm.nd.array(B_np, ctx)\n    C_tvm = tvm.nd.array(C_np, ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n\n    golden = np.matmul(A_np.astype(\"int32\"), B_np.astype(\"int32\").T)\n\n    C_numpy = C_tvm.numpy()\n\n    tvm.testing.assert_allclose(golden, C_numpy, atol=1e-3, rtol=1e-3)\n\n\n@T.prim_func\ndef gemm_mma_m16n8k64_row_col_s4s4s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 64], dtype=\"int4\")\n    B = T.match_buffer(b, [8, 64], dtype=\"int4\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([32], \"int4\", scope=\"local\")\n    MultiB = T.decl_buffer([16], \"int4\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(32):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 16 // 8 * 8,\n            (tx % 32) % 4 * 8 + mma_multi_a_col % 8 + mma_multi_a_col // 16 * 32,\n        ]\n    for mma_multi_b_col in range(16):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 8 + mma_multi_b_col % 8 + mma_multi_b_col // 8 * 32,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k32\",\n            \"row\",\n            \"col\",\n            \"int4\",\n            \"int4\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k64_row_col_s4s4s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k64_row_col_s4s4s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.empty([16, 64], \"int4\", ctx)\n    B_tvm = tvm.nd.empty([8, 64], \"int4\", ctx)\n    C_tvm = tvm.nd.empty([16, 8], \"int32\", ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n    # Currently the correctness is not checked.\n    # TODO: add correctness checking here.\n\n\n@T.prim_func\ndef gemm_mma_m16n8k64_row_col_s4u4s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 64], dtype=\"int4\")\n    B = T.match_buffer(b, [8, 64], dtype=\"uint4\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([32], \"int4\", scope=\"local\")\n    MultiB = T.decl_buffer([16], \"uint4\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(32):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 16 // 8 * 8,\n            (tx % 32) % 4 * 8 + mma_multi_a_col % 8 + mma_multi_a_col // 16 * 32,\n        ]\n    for mma_multi_b_col in range(16):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 8 + mma_multi_b_col % 8 + mma_multi_b_col // 8 * 32,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m8n8k32\",\n            \"row\",\n            \"col\",\n            \"int4\",\n            \"uint4\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k64_row_col_s4u4s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k64_row_col_s4u4s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.empty([16, 64], \"int4\", ctx)\n    B_tvm = tvm.nd.empty([8, 64], \"uint4\", ctx)\n    C_tvm = tvm.nd.empty([16, 8], \"int32\", ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n    # Currently the correctness is not checked.\n    # TODO: add correctness checking here.\n\n\n@T.prim_func\ndef gemm_mma_m16n8k256_row_col_b1b1s32(a: T.handle, b: T.handle, c: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 256], dtype=\"int1\")\n    B = T.match_buffer(b, [8, 256], dtype=\"int1\")\n    C = T.match_buffer(c, [16, 8], dtype=\"int32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    MultiA = T.decl_buffer([128], \"int1\", scope=\"local\")\n    MultiB = T.decl_buffer([64], \"int1\", scope=\"local\")\n    Accum = T.decl_buffer([4], \"int32\", scope=\"local\")\n    for i in range(4):\n        Accum[i] = T.int32(0)\n\n    for mma_multi_a_col in range(128):\n        MultiA[mma_multi_a_col] = A[\n            (tx % 32) // 4 + mma_multi_a_col % 64 // 32 * 8,\n            (tx % 32) % 4 * 32 + mma_multi_a_col % 32 + mma_multi_a_col // 64 * 128,\n        ]\n    for mma_multi_b_col in range(16):\n        MultiB[mma_multi_b_col] = B[\n            (tx % 32) // 4,\n            (tx % 32) % 4 * 32 + mma_multi_b_col % 32 + mma_multi_b_col // 32 * 128,\n        ]\n    T.evaluate(\n        T.ptx_mma(\n            \"m16n8k256\",\n            \"row\",\n            \"col\",\n            \"int1\",\n            \"int1\",\n            \"int32\",\n            MultiA.data,\n            0,\n            MultiB.data,\n            0,\n            Accum.data,\n            0,\n            False,\n            \"xor\",\n            dtype=\"int32\",\n        )\n    )\n    for mma_accum_c_id in range(4):\n        C[\n            (tx % 32) // 4 + mma_accum_c_id // 2 * 8,\n            (tx % 32) % 4 * 2 + mma_accum_c_id % 2,\n        ] = Accum[mma_accum_c_id]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_gemm_mma_m16n8k256_row_col_b1b1s32():\n    sch = tvm.tir.Schedule(gemm_mma_m16n8k256_row_col_b1b1s32)\n    cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n    ctx = tvm.cuda()\n    A_tvm = tvm.nd.empty([16, 256], \"int1\", ctx)\n    B_tvm = tvm.nd.empty([8, 256], \"int1\", ctx)\n    C_tvm = tvm.nd.empty([16, 8], \"int32\", ctx)\n\n    cuda_mod(A_tvm, B_tvm, C_tvm)\n    # Currently the correctness is not checked.\n    # TODO: add correctness checking here.\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_ptx_mma_sp.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\ndef gen_2in4_mask(m: int, n: int):\n    assert n % 4 == 0\n    return np.array(\n        [[np.sort(np.random.choice(4, 2, replace=False)) for _ in range(n // 4)] for _ in range(m)]\n    ).astype(\"uint8\")\n\n\ndef get_dense_mat_by_mask(val, mask):\n    m, n_chunks, _ = mask.shape\n    val = val.reshape(m, n_chunks, 2)\n    ret = np.zeros((m, n_chunks, 4)).astype(val.dtype)\n    for i in range(m):\n        for j in range(n_chunks):\n            for k in range(2):\n                ret[i, j, mask[i, j, k]] = val[i, j, k]\n    return ret.reshape(m, n_chunks * 4)\n\n\n@T.prim_func\ndef mma_sp_m16n8k16_f16f16f16(a: T.handle, b: T.handle, c: T.handle, _metadata: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 8], dtype=\"float16\")\n    B = T.match_buffer(b, [16, 8], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float16\")\n    metadata = T.match_buffer(_metadata, [8], dtype=\"uint32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    multi_a = T.decl_buffer([4], \"float16\", scope=\"local\")\n    multi_b = T.decl_buffer([4], \"float16\", scope=\"local\")\n    accum = T.decl_buffer([4], \"float16\", scope=\"local\")\n    meta_local = T.decl_buffer([1], \"uint32\", scope=\"local\")\n    for i in range(4):\n        accum[i] = T.float16(0)\n\n    for i in range(4):\n        multi_a[i] = A[tx // 4 + i // 2 * 8, tx % 4 * 2 + i % 2]\n\n    for i in range(4):\n        multi_b[i] = B[tx % 4 * 2 + i % 2 + i // 2 * 8, tx // 4]\n\n    meta_local[0] = metadata[tx // 4]\n\n    T.evaluate(\n        T.ptx_mma_sp(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp16\",\n            multi_a.data,\n            0,\n            multi_b.data,\n            0,\n            accum.data,\n            0,\n            meta_local.data,\n            0,\n            0,\n            False,\n            dtype=\"float16\",\n        )\n    )\n\n    for i in range(4):\n        C[i // 2 * 8 + tx // 4, tx % 4 * 2 + i % 2] = accum[i]\n\n\n@T.prim_func\ndef mma_sp_m16n8k16_f16f16f32(a: T.handle, b: T.handle, c: T.handle, _metadata: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 8], dtype=\"float16\")\n    B = T.match_buffer(b, [16, 8], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float32\")\n    metadata = T.match_buffer(_metadata, [8], dtype=\"uint32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    multi_a = T.decl_buffer([4], \"float16\", scope=\"local\")\n    multi_b = T.decl_buffer([4], \"float16\", scope=\"local\")\n    accum = T.decl_buffer([4], \"float32\", scope=\"local\")\n    meta_local = T.decl_buffer([1], \"uint32\", scope=\"local\")\n    for i in range(4):\n        accum[i] = T.float16(0)\n\n    for i in range(4):\n        multi_a[i] = A[tx // 4 + i // 2 * 8, tx % 4 * 2 + i % 2]\n\n    for i in range(4):\n        multi_b[i] = B[tx % 4 * 2 + i % 2 + i // 2 * 8, tx // 4]\n\n    meta_local[0] = metadata[tx // 4]\n\n    T.evaluate(\n        T.ptx_mma_sp(\n            \"m16n8k16\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp32\",\n            multi_a.data,\n            0,\n            multi_b.data,\n            0,\n            accum.data,\n            0,\n            meta_local.data,\n            0,\n            0,\n            False,\n            dtype=\"float32\",\n        )\n    )\n\n    for i in range(4):\n        C[i // 2 * 8 + tx // 4, tx % 4 * 2 + i % 2] = accum[i]\n\n\n@T.prim_func\ndef mma_sp_m16n8k32_f16f16f16(a: T.handle, b: T.handle, c: T.handle, _metadata: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"float16\")\n    B = T.match_buffer(b, [32, 8], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float16\")\n    metadata = T.match_buffer(_metadata, [16], dtype=\"uint32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    multi_a = T.decl_buffer([8], \"float16\", scope=\"local\")\n    multi_b = T.decl_buffer([8], \"float16\", scope=\"local\")\n    accum = T.decl_buffer([4], \"float16\", scope=\"local\")\n    meta_local = T.decl_buffer([1], \"uint32\", scope=\"local\")\n    for i in range(4):\n        accum[i] = T.float16(0)\n\n    for i in range(8):\n        multi_a[i] = A[(i % 4) // 2 * 8 + tx // 4, i // 4 * 8 + tx % 4 * 2 + i % 2]\n\n    for i in range(8):\n        multi_b[i] = B[i // 2 * 8 + tx % 4 * 2 + i % 2, tx // 4]\n\n    meta_local[0] = metadata[tx // 4 * 2 + tx % 2]\n\n    T.evaluate(\n        T.ptx_mma_sp(\n            \"m16n8k32\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp16\",\n            multi_a.data,\n            0,\n            multi_b.data,\n            0,\n            accum.data,\n            0,\n            meta_local.data,\n            0,\n            0,\n            False,\n            dtype=\"float16\",\n        )\n    )\n\n    for i in range(4):\n        C[i // 2 * 8 + tx // 4, tx % 4 * 2 + i % 2] = accum[i]\n\n\n@T.prim_func\ndef mma_sp_m16n8k32_f16f16f32(a: T.handle, b: T.handle, c: T.handle, _metadata: T.handle):\n    T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n    A = T.match_buffer(a, [16, 16], dtype=\"float16\")\n    B = T.match_buffer(b, [32, 8], dtype=\"float16\")\n    C = T.match_buffer(c, [16, 8], dtype=\"float32\")\n    metadata = T.match_buffer(_metadata, [16], dtype=\"uint32\")\n    brow = T.env_thread(\"blockIdx.y\")\n    bcol = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(brow, 1)\n    T.launch_thread(bcol, 1)\n    T.launch_thread(tx, 32)\n    multi_a = T.decl_buffer([8], \"float16\", scope=\"local\")\n    multi_b = T.decl_buffer([8], \"float16\", scope=\"local\")\n    accum = T.decl_buffer([4], \"float32\", scope=\"local\")\n    meta_local = T.decl_buffer([1], \"uint32\", scope=\"local\")\n    for i in range(4):\n        accum[i] = T.float16(0)\n\n    for i in range(8):\n        multi_a[i] = A[(i % 4) // 2 * 8 + tx // 4, i // 4 * 8 + tx % 4 * 2 + i % 2]\n\n    for i in range(8):\n        multi_b[i] = B[i // 2 * 8 + tx % 4 * 2 + i % 2, tx // 4]\n\n    meta_local[0] = metadata[tx // 4 * 2 + tx % 2]\n\n    T.evaluate(\n        T.ptx_mma_sp(\n            \"m16n8k32\",\n            \"row\",\n            \"col\",\n            \"fp16\",\n            \"fp16\",\n            \"fp32\",\n            multi_a.data,\n            0,\n            multi_b.data,\n            0,\n            accum.data,\n            0,\n            meta_local.data,\n            0,\n            0,\n            False,\n            dtype=\"float32\",\n        )\n    )\n\n    for i in range(4):\n        C[i // 2 * 8 + tx // 4, tx % 4 * 2 + i % 2] = accum[i]\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_mma_sp_m16n8k16_f16():\n    def get_meta_m16n8k16_half(mask):\n        assert mask.shape == (16, 4, 2)\n        mask = mask.reshape(16, 8)\n        ret = np.zeros((8,)).astype(\"uint32\")\n\n        for i in range(8):\n            base = 1\n            for blk in range(2):\n                for j in range(8):\n                    ret[i] |= int(mask[blk * 8 + i, j]) * base\n                    base = base << 2\n        return ret\n\n    for out_dtype in [\"float16\", \"float32\"]:\n        func = mma_sp_m16n8k16_f16f16f16 if out_dtype == \"float16\" else mma_sp_m16n8k16_f16f16f32\n        sch = tvm.tir.Schedule(func)\n        cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n        A_np = np.random.uniform(-1, 1, [16, 8]).astype(\"float16\")\n        B_np = np.random.uniform(-1, 1, [16, 8]).astype(\"float16\")\n        mask = gen_2in4_mask(16, 16)\n        A_dense_np = get_dense_mat_by_mask(A_np, mask)\n        C_np = np.matmul(A_dense_np, B_np).astype(out_dtype)\n        meta = get_meta_m16n8k16_half(mask)\n\n        ctx = tvm.cuda()\n        A_tvm = tvm.nd.array(A_np, ctx)\n        B_tvm = tvm.nd.array(B_np, ctx)\n        C_tvm = tvm.nd.array(np.zeros_like(C_np), ctx)\n        meta_tvm = tvm.nd.array(meta, ctx)\n        cuda_mod(A_tvm, B_tvm, C_tvm, meta_tvm)\n\n        tvm.testing.assert_allclose(C_tvm.numpy(), C_np, atol=1e-3, rtol=1e-3)\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_mma_sp_m16n8k32_f16():\n    def get_meta_m16n8k32_half(mask):\n        assert mask.shape == (16, 8, 2)\n        mask = mask.reshape(16, 2, 8)\n        ret = np.zeros((8, 2)).astype(\"uint32\")\n\n        for i in range(8):\n            for k in range(2):\n                base = 1\n                for blk in range(2):\n                    for j in range(8):\n                        ret[i, k] |= int(mask[blk * 8 + i, k, j]) * base\n                        base = base << 2\n\n        return ret.reshape(16)\n\n    for out_dtype in [\"float16\", \"float32\"]:\n        func = mma_sp_m16n8k32_f16f16f16 if out_dtype == \"float16\" else mma_sp_m16n8k32_f16f16f32\n        sch = tvm.tir.Schedule(func)\n        cuda_mod = tvm.build(sch.mod, target=\"cuda\")\n\n        A_np = np.random.uniform(-1, 1, [16, 16]).astype(\"float16\")\n        B_np = np.random.uniform(-1, 1, [32, 8]).astype(\"float16\")\n        mask = gen_2in4_mask(16, 32)\n        A_dense_np = get_dense_mat_by_mask(A_np, mask)\n        C_np = np.matmul(A_dense_np, B_np).astype(out_dtype)\n        meta = get_meta_m16n8k32_half(mask)\n\n        ctx = tvm.cuda()\n        A_tvm = tvm.nd.array(A_np, ctx)\n        B_tvm = tvm.nd.array(B_np, ctx)\n        C_tvm = tvm.nd.array(np.zeros_like(C_np), ctx)\n        meta_tvm = tvm.nd.array(meta, ctx)\n        cuda_mod(A_tvm, B_tvm, C_tvm, meta_tvm)\n\n    tvm.testing.assert_allclose(C_tvm.numpy(), C_np, atol=1e-3, rtol=1e-3)\n\n\nif __name__ == \"__main__\":\n    test_mma_sp_m16n8k16_f16()\n    test_mma_sp_m16n8k32_f16()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_renew_defs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nimport sys\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nfrom tvm.tir.buffer import Buffer\nfrom tvm.tir.function import PrimFunc\nfrom tvm.tir.stmt import Block\n\n\ndef _check_func_signature_remap(lhs: PrimFunc, rhs: PrimFunc):\n    assert lhs != rhs\n    for x, y in zip(lhs.params, rhs.params):\n        assert x != y\n        assert lhs.buffer_map[x] != rhs.buffer_map[y]\n\n\ndef _check_buffer_decl(lhs: Buffer, rhs: Buffer):\n    assert lhs != rhs\n    assert lhs.data != rhs.data\n\n\ndef _check_block_signature_remap(lhs: Block, rhs: Block):\n    assert lhs != rhs\n    for x, y in zip(lhs.iter_vars, rhs.iter_vars):\n        assert x != y\n        assert x.var != y.var\n    for x, y in zip(lhs.alloc_buffers, rhs.alloc_buffers):\n        _check_buffer_decl(x, y)\n    for x, y in zip(lhs.match_buffers, rhs.match_buffers):\n        assert x != y\n        _check_buffer_decl(x.buffer, y.buffer)\n\n\ndef test_simple():\n    @T.prim_func\n    # Buffer A should be remapped\n    def elementwise(A: T.Buffer[(128, 128), \"float32\"]):\n        # Buffer B should be remapped\n        B = T.alloc_buffer((128, 128), \"float32\")\n        # i, j should be remapped\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                # vi, vj should be remapped\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[vi, vj])\n                T.writes(B[vi, vj])\n                B[vi, vj] = A[vi, vj] * 2.0\n\n    f1 = elementwise\n    f2 = tvm.tir.stmt_functor.renew_defs(f1)\n    tvm.ir.assert_structural_equal(f1, f2)\n\n    _check_func_signature_remap(f1, f2)\n    # check root block\n    _check_block_signature_remap(f1.body.block, f2.body.block)\n    # check remap of i\n    assert f1.body.block.body.loop_var != f2.body.block.body.loop_var\n    # check remap of j\n    assert f1.body.block.body.body.loop_var != f2.body.block.body.body.loop_var\n    # check inner block\n    def _get_block(f):\n        return f.body.block.body.body.body.block\n\n    _check_block_signature_remap(_get_block(f1), _get_block(f2))\n\n\ndef test_match_buffer():\n    @T.prim_func\n    # A and B should be remapped\n    def func_match_buffer(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]):\n        with T.block(\"root\"):\n            s = T.var(\"int32\")\n            e = T.var(\"int32\")\n            # A0 should be remapped\n            A0 = T.match_buffer(\n                A[0:128, 0:128],\n                shape=(128, 128),\n                dtype=\"float32\",\n                # s and e should be remapped\n                strides=[s, s],\n                elem_offset=e,\n            )\n            for i, j in T.grid(128, 128):\n                with T.block(\"B\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    B[vi, vj] = A0[vi, vj] * 2.0\n\n    f1 = func_match_buffer\n    f2 = tvm.tir.stmt_functor.renew_defs(f1)\n    tvm.ir.assert_structural_equal(f1, f2)\n\n    _check_func_signature_remap(f1, f2)\n    _check_block_signature_remap(f1.body.block, f2.body.block)\n    assert f1.body.block.body.loop_var != f2.body.block.body.loop_var\n\n    def _get_block(f):\n        return f.body.block\n\n    block1 = _get_block(f1)\n    block2 = _get_block(f2)\n    _check_block_signature_remap(block1, block2)\n\n    matched_buffer1 = block1.match_buffers[0].buffer\n    matched_buffer2 = block2.match_buffers[0].buffer\n    # Stride var s should be remapped\n    assert matched_buffer1.strides[0] != matched_buffer2.strides[0]\n    assert matched_buffer1.strides[1] != matched_buffer2.strides[1]\n    # s should be only remapped once\n    assert matched_buffer1.strides[0] == matched_buffer1.strides[1]\n    assert matched_buffer2.strides[0] == matched_buffer2.strides[1]\n    # Element-offset var e should be remapped\n    assert matched_buffer1.elem_offset != matched_buffer2.elem_offset\n\n\ndef test_undefined_buffer():\n    @T.prim_func\n    def access_alloc():\n        # Buffer A should be remapped\n        A_data = T.allocate([128], \"float16\", \"global\")\n        A = T.buffer_decl(shape=[128], dtype=\"float16\", data=A_data)\n        # check if buffer var also get remapped\n        T.evaluate(A.data)\n        for i in range(128):\n            A[i] = A[i] + T.float16(1.0)\n\n    f1 = access_alloc\n    f2 = tvm.tir.stmt_functor.renew_defs(f1)\n    tvm.ir.assert_structural_equal(f1, f2)\n\n    assert f1.body.buffer_var != f2.body.buffer_var\n\n    def _get_buffer_store_buffer(f):\n        return f.body.body[1].body.buffer\n\n    _check_buffer_decl(_get_buffer_store_buffer(f1), _get_buffer_store_buffer(f2))\n\n\ndef test_symbolic_func():\n    @T.prim_func\n    def symbolic_func(a: T.handle, b: T.handle, n: T.int32):\n        m = T.var(\"int32\")\n        A = T.match_buffer(a, (n, m))\n        B = T.match_buffer(b, (n, m * 2))\n        for i, j in T.grid(n, m):\n            B[i, j * 2] = A[i, j]\n            B[i, j * 2 + 1] = A[i, j]\n\n    f1 = symbolic_func\n    f2 = tvm.tir.stmt_functor.renew_defs(f1)\n    tvm.ir.assert_structural_equal(f1, f2)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_analysis.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nfrom typing import List\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm.tir.function import TensorIntrin\nfrom tvm.tir.tensor_intrin.x86 import dot_product_16x4_u8i8i32_desc\nfrom tvm.tir.tensor_intrin.cuda import (\n    WMMA_SYNC_16x16x16_f16f16f16_INTRIN,\n    WMMA_SYNC_16x16x16_f16f16f32_INTRIN,\n)\n\n\nfrom tvm.tir import Evaluate, For, ForKind, IndexMap, Var, decl_buffer, floordiv, floormod, Schedule\nfrom tvm.tir.analysis import expr_deep_equal\nfrom tvm.tir.schedule.analysis import (\n    get_auto_tensorize_mapping_info,\n    suggest_index_map,\n    get_tensorize_loop_mapping,\n    TensorizeInfo,\n)\nfrom tvm.script import tir as T\nfrom tvm.tir.stmt_functor import pre_order_visit\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.te import create_prim_func\n\n\ndef _make_vars(*args: str) -> List[Var]:\n    return [Var(arg, dtype=\"int32\") for arg in args]\n\n\ndef _make_loops(loop_vars: List[Var], extents: List[int]) -> List[For]:\n    assert len(loop_vars) == len(extents)\n    return [\n        For(\n            loop_var=loop_var,\n            min_val=0,\n            extent=extent,\n            kind=ForKind.SERIAL,\n            body=Evaluate(0),\n        )\n        for loop_var, extent in zip(loop_vars, extents)\n    ]\n\n\ndef test_suggest_index_map_simple():\n    i, j = _make_vars(\"i\", \"j\")\n    index_map = suggest_index_map(\n        buffer=decl_buffer(shape=[8, 256]),\n        indices=[\n            floordiv(i, 16) * 4 + floordiv(j, 16),\n            floormod(i, 16) * 16 + floormod(j, 16),\n        ],\n        loops=_make_loops(\n            loop_vars=[i, j],\n            extents=[32, 64],\n        ),\n        predicate=True,\n    )\n    expected_index_map = IndexMap.from_func(\n        lambda x, y: [\n            floordiv(x, 4),\n            floordiv(y, 16),\n            floormod(x, 4),\n            floormod(y, 16),\n        ],\n    )\n    assert index_map.is_equivalent_to(expected_index_map)\n\n\ndef test_suggest_index_map_bijective():\n    i, j = _make_vars(\"i\", \"j\")\n    index_map = suggest_index_map(\n        buffer=decl_buffer(shape=[8]),\n        indices=[floormod(j, 4) * 2 + i],\n        loops=_make_loops(\n            loop_vars=[i, j],\n            extents=[2, 32],\n        ),\n        predicate=True,\n    )\n    expected_index_map = IndexMap.from_func(\n        lambda x: [\n            floormod(x, 2),\n            floordiv(x, 2),\n        ],\n    )\n    assert index_map.is_equivalent_to(expected_index_map)\n\n\ndef test_suggest_index_map_winograd():\n    \"\"\"use case in winograd conv where the indices are complicated\"\"\"\n    fused_outer, i3_3_fused, i4_0, i4_1 = _make_vars(\"fused_outer\", \"i3_3_fused\", \"i4_0\", \"i4_1\")\n    eps = floordiv(fused_outer, 336) * 2 + floordiv(floormod(fused_outer, 16), 8)\n    nu = floordiv(floormod(fused_outer, 336), 112) * 2 + floordiv(floormod(fused_outer, 8), 4)\n    co = floormod(fused_outer, 4) * 32 + i3_3_fused\n    ci = (i4_0 * 32) + i4_1\n    buffer = decl_buffer(shape=[6, 6, 128, 128])\n    index_map = suggest_index_map(\n        buffer=buffer,\n        indices=[eps, nu, co, ci],\n        loops=_make_loops(\n            loop_vars=[fused_outer, i3_3_fused, i4_0, i4_1],\n            extents=[1008, 32, 4, 32],\n        ),\n        predicate=True,\n    )\n    expected_index_map = IndexMap.from_func(\n        lambda i0, i1, i2, i3: (\n            floordiv(i0, 2),\n            floordiv(i1, 2),\n            floormod(i0, 2),\n            floormod(((i1 * 4) + floordiv(i2, 32)), 8),\n            floormod(i2, 32),\n            floordiv(i3, 32),\n            floormod(i3, 32),\n        )\n    )\n    assert index_map.is_equivalent_to(expected_index_map)\n    inverse_index_map = index_map.inverse(buffer.shape)\n    expected_inverse_index_map = IndexMap.from_func(\n        lambda i0, i1, i2, i3, i4, i5, i6: (\n            ((i0 * 2) + i2),\n            ((i1 * 2) + floordiv(((i3 * 32) + i4), 128)),\n            floormod(((i3 * 32) + i4), 128),\n            ((i5 * 32) + i6),\n        )\n    )\n    assert inverse_index_map.is_equivalent_to(expected_inverse_index_map)\n\n\n@tvm.script.ir_module\nclass DenseVNNIModule:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1024, 1024), \"uint8\"],\n        placeholder_1: T.Buffer[(64, 256, 16, 4), \"int8\"],\n        compute: T.Buffer[(1024, 1024), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            for i0, i1, i2 in T.grid(1024, 1024, 1024):\n                with T.block(\"compute\"):\n                    i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                    T.reads(placeholder[i, k], placeholder_1[j // 16, k // 4, j % 16, k % 4])\n                    T.writes(compute[i, j])\n                    with T.init():\n                        compute[i, j] = 0\n                    compute[i, j] = compute[i, j] + T.cast(placeholder[i, k], \"int32\") * T.cast(\n                        placeholder_1[j // 16, k // 4, j % 16, k % 4], \"int32\"\n                    )\n\n\n@tvm.script.ir_module\nclass Conv2dNCHWcVNNIModule:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 16, 56, 56, 16, 1, 1, 4, 4, 4):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                (\n                    n,\n                    oc_chunk,\n                    oh,\n                    ow,\n                    oc_block,\n                    kh,\n                    kw,\n                    ic_outer,\n                    ic_f_inner,\n                    ic_s_inner,\n                ) = T.axis.remap(\"SSSSSRRRRR\", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9])\n                T.reads(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                )\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[\n                    n, oc_chunk, oh, ow, oc_block\n                ] + T.cast(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\"\n                ) * T.cast(\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                    \"int32\",\n                )\n\n\ndef collect_loops(prim_func):\n    loops = []\n\n    def callback(node):\n        if isinstance(node, tvm.tir.For):\n            loops.append(node)\n        return True\n\n    pre_order_visit(prim_func.body, callback)\n\n    return loops\n\n\ndef test_get_tensorize_loop_mapping_dense_vnni():\n    s = Schedule(DenseVNNIModule)\n    block = s.get_block(\"compute\")\n\n    info = get_tensorize_loop_mapping(s, block, dot_product_16x4_u8i8i32_desc)\n\n    assert isinstance(info, TensorizeInfo)\n\n    desc_loop_to_sref = dict((v, k) for k, v in info.loop_map.items())\n\n    desc_loops = collect_loops(dot_product_16x4_u8i8i32_desc)\n    _, loop_j, loop_k = s.get_loops(block)\n\n    assert desc_loops[0] in desc_loop_to_sref and desc_loops[1] in desc_loop_to_sref\n    assert s.get(desc_loop_to_sref[desc_loops[0]]) == s.get(loop_j)\n    assert s.get(desc_loop_to_sref[desc_loops[1]]) == s.get(loop_k)\n\n\ndef test_get_tensorize_loop_mapping_conv2d_nchwc_vnni():\n    s = Schedule(Conv2dNCHWcVNNIModule)\n    block = s.get_block(\"conv2d_NCHWc_int8\")\n\n    info = get_tensorize_loop_mapping(s, block, dot_product_16x4_u8i8i32_desc)\n\n    desc_loop_to_sref = dict((v, k) for k, v in info.loop_map.items())\n\n    desc_loops = collect_loops(dot_product_16x4_u8i8i32_desc)\n\n    # i4 corresonds to the inner output channel axis of the NCHWc output tensor\n    # for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 16, 56, 56, 16, 1, 1, 4, 4, 4):\n    _, _, _, _, i4, _, _, _, _, i9 = s.get_loops(block)\n\n    assert desc_loops[0] in desc_loop_to_sref and desc_loops[1] in desc_loop_to_sref\n    assert s.get(desc_loop_to_sref[desc_loops[0]]) == s.get(i4)\n    assert s.get(desc_loop_to_sref[desc_loops[1]]) == s.get(i9)\n\n\ndef test_get_tensorize_loop_mapping_matmul_mma():\n    @T.prim_func\n    def matmul_16x16x16xf16f16f16_desc(\n        A: T.Buffer((16, 16), \"float16\", align=64, offset_factor=1),\n        B: T.Buffer((16, 16), \"float16\", align=64, offset_factor=1),\n        C: T.Buffer((16, 16), \"float16\", align=64, offset_factor=1),\n    ) -> None:\n        with T.block(\"root\"):\n            T.reads(C[0:16, 0:16], A[0:16, 0:16], B[0:16, 0:16])\n            T.writes(C[0:16, 0:16])\n            for i, j, k in T.grid(16, 16, 16):\n                with T.block(\"update\"):\n                    vii, vjj, vkk = T.axis.remap(\"SSR\", [i, j, k])\n                    C[vii, vjj] = C[vii, vjj] + A[vii, vkk] * B[vjj, vkk]\n\n    matmul = create_prim_func(\n        te_workload.matmul_relu(\n            n=512,\n            m=512,\n            k=512,\n        )\n    )\n\n    s = Schedule(matmul)\n    block = s.get_block(\"C\")\n    i0, i1, i2 = s.get_loops(block)\n    desc_loops = collect_loops(matmul_16x16x16xf16f16f16_desc)\n\n    for do_reorder in [False, True]:\n        # Mapping should be invariant to the loop permutation\n        if do_reorder:\n            s.reorder(i2, i0, i1)\n\n        info = get_tensorize_loop_mapping(s, block, matmul_16x16x16xf16f16f16_desc)\n        assert info is not None\n        desc_loop_to_sref = dict((v, k) for k, v in info.loop_map.items())\n\n        for i in range(3):\n            assert desc_loops[i] in desc_loop_to_sref\n\n        assert s.get(desc_loop_to_sref[desc_loops[0]]) == s.get(i0)\n        assert s.get(desc_loop_to_sref[desc_loops[1]]) == s.get(i1)\n        assert s.get(desc_loop_to_sref[desc_loops[2]]) == s.get(i2)\n\n\ndef test_get_tensorize_loop_mapping_padding_matmul():\n    matmul = create_prim_func(\n        te_workload.matmul_relu(\n            n=127,\n            m=256,\n            k=65,\n            in_dtype=\"float16\",\n            out_dtype=\"float16\",\n        )\n    )\n    s = Schedule(matmul)\n    block = s.get_block(\"C\")\n\n    desc = TensorIntrin.get(WMMA_SYNC_16x16x16_f16f16f16_INTRIN).desc\n    info = get_tensorize_loop_mapping(s, block, desc, allow_padding=True)\n    assert info is not None\n    expected_padding = [1, 0, 15]\n    actual_padding = info.block_iter_paddings\n    assert actual_padding is not None\n    assert len(actual_padding) == len(expected_padding)\n    for actual, expected in zip(actual_padding, expected_padding):\n        assert actual == expected\n\n\ndef check_index_map(workload, block_name, intrin_name, expected_index_map):\n    s = Schedule(workload)\n    block = s.get_block(block_name)\n    desc_func = TensorIntrin.get(intrin_name).desc\n    info = get_auto_tensorize_mapping_info(s, block, desc_func)\n    if expected_index_map is None:\n        assert info is None\n        return\n    assert len(info.mappings) == 1\n    assert IndexMap.from_func(expected_index_map).is_equivalent_to(info.mappings[0])\n\n\ndef test_get_auto_tensorize_mapping_info_conv2d():\n    conv2d = create_prim_func(\n        te_workload.conv2d_nhwc(4, 16, 16, 64, 64, 3, 1, 1, in_dtype=\"float16\", out_dtype=\"float32\")\n    )\n    check_index_map(\n        conv2d,\n        \"conv2d_nhwc\",\n        WMMA_SYNC_16x16x16_f16f16f32_INTRIN,\n        lambda n, h, w, c, rh, rw, rc: (n * 256 + h * 16 + w, c, rh * 192 + rw * 64 + rc),\n    )\n\n\ndef test_get_auto_tensorize_mapping_info_conv2d_unit_batch():\n    conv2d = create_prim_func(\n        te_workload.conv2d_nhwc(1, 16, 16, 64, 64, 3, 1, 1, in_dtype=\"float16\", out_dtype=\"float32\")\n    )\n    check_index_map(\n        conv2d,\n        \"conv2d_nhwc\",\n        WMMA_SYNC_16x16x16_f16f16f32_INTRIN,\n        lambda n, h, w, c, rh, rw, rc: (n * 256 + h * 16 + w, c, rh * 192 + rw * 64 + rc),\n    )\n\n\n@pytest.mark.parametrize(\"b,m,n,k\", [(1, 512, 512, 512), (16, 32, 32, 32)])\ndef test_get_auto_tensorize_mapping_info_batch_matmul(b, m, n, k):\n    matmul = create_prim_func(\n        te_workload.batch_matmul_nkkm(b, m, n, k, in_dtype=\"float16\", out_dtype=\"float32\")\n    )\n    check_index_map(\n        matmul, \"Z\", WMMA_SYNC_16x16x16_f16f16f32_INTRIN, lambda b, m, n, k: (b, m, n, k)\n    )\n\n\n@pytest.mark.parametrize(\n    \"n,m,k,expected\",\n    [\n        (\n            512,\n            512,\n            512,\n            lambda n, m, k: (\n                n,\n                m,\n                k,\n            ),\n        ),\n        (1, 32, 32, lambda n, m, k: (n, m, k)),\n    ],\n)\ndef test_get_auto_tensorize_mapping_info_matmul(n, m, k, expected):\n    matmul = create_prim_func(te_workload.matmul(n, m, k, in_dtype=\"float16\", out_dtype=\"float32\"))\n    check_index_map(matmul, \"C\", WMMA_SYNC_16x16x16_f16f16f32_INTRIN, expected)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_block_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import DepKind\nfrom tvm.tir.stmt_functor import post_order_visit\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = T.float32(0)\n        for k in range(0, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef war_dependency(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n# pylint: disable=invalid-name\n\n\ndef _get_block(s: tir.ScheduleState, name_hint: str) -> tir.StmtSRef:\n    result = None\n\n    def f_visit(node):\n        nonlocal result\n        if isinstance(node, tvm.tir.Block) and node.name_hint == name_hint:\n            result = node\n\n    func = s.mod[\"main\"]\n    post_order_visit(func.body, f_visit)\n    assert result is not None and isinstance(result, tvm.tir.Block)\n    return s.get_sref(result)\n\n\ndef test_elementwise_dependency():\n    s = tir.ScheduleState(elementwise, debug_mask=\"all\")\n    root = _get_block(s, \"root\")\n    block_b = _get_block(s, \"B\")\n    block_c = _get_block(s, \"C\")\n    # Check get_deps_by_src\n    (dep,) = s.get_block_scope(root).get_deps_by_src(block_b)\n    assert dep.src.same_as(block_b)\n    assert dep.dst.same_as(block_c)\n    assert dep.kind == DepKind.RAW\n    # Check get_deps_by_dst\n    (dep,) = s.get_block_scope(root).get_deps_by_dst(block_c)\n    assert dep.src.same_as(block_b)\n    assert dep.dst.same_as(block_c)\n    assert dep.kind == DepKind.RAW\n\n\ndef test_matmul_dependency():\n    s = tir.ScheduleState(matmul, debug_mask=\"all\")\n    root = _get_block(s, \"root\")\n    init = _get_block(s, \"init\")\n    update = _get_block(s, \"update\")\n    # Check get_deps_by_src\n    p0, p1 = s.get_block_scope(root).get_deps_by_src(init)\n    assert p0.src.same_as(init)\n    assert p0.dst.same_as(update)\n    assert p1.src.same_as(init)\n    assert p1.dst.same_as(update)\n    assert (p0.kind == DepKind.RAW and p1.kind == DepKind.WAW) or (\n        p0.kind == DepKind.WAW and p1.kind == DepKind.RAW\n    )\n    # Check get_deps_by_dst\n    p0, p1 = s.get_block_scope(root).get_deps_by_dst(update)\n    assert p0.src.same_as(init)\n    assert p0.dst.same_as(update)\n    assert p1.src.same_as(init)\n    assert p1.dst.same_as(update)\n    assert (p0.kind == DepKind.RAW and p1.kind == DepKind.WAW) or (\n        p0.kind == DepKind.WAW and p1.kind == DepKind.RAW\n    )\n\n\ndef test_war_dependency():\n    s = tir.ScheduleState(war_dependency, debug_mask=\"all\")\n    root = _get_block(s, \"root\")\n    block_c = _get_block(s, \"C\")\n    block_b = _get_block(s, \"B\")\n    # Check get_deps_by_src\n    (dep,) = s.get_block_scope(root).get_deps_by_src(block_c)\n    assert dep.src.same_as(block_c)\n    assert dep.dst.same_as(block_b)\n    assert dep.kind == DepKind.WAR\n    # Check get_deps_by_dst\n    (dep,) = s.get_block_scope(root).get_deps_by_dst(block_b)\n    assert dep.src.same_as(block_c)\n    assert dep.dst.same_as(block_b)\n    assert dep.kind == DepKind.WAR\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_blockize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n@T.prim_func\ndef single_elementwise(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]):\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n# fmt: on\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n\ndef test_blockize_outer():\n    @T.prim_func\n    def after_blockize_outer(\n        A: T.Buffer[(128, 128), \"float32\"],\n        B: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        with T.block(\"blockized_B\"):\n            vio = T.axis.spatial(1, 0)\n            vjo = T.axis.spatial(1, 0)\n            for i, j in T.grid(128, 128):\n                with T.block(\"B\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    B[vi, vj] = A[vi, vj] * 2.0\n\n    func = single_elementwise\n    s = tir.Schedule(func, debug_mask=\"all\")\n    x, _ = s.get_loops(s.get_block(\"B\"))\n    s.blockize(x)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_blockize_outer)\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_blockize_inner():\n    @T.prim_func\n    def after_blockize_inner(\n        A: T.Buffer[(128, 128), \"float32\"],\n        B: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        for i in T.serial(128):\n            with T.block(\"blockized_B\"):\n                vi = T.axis.spatial(128, i)\n                vjo = T.axis.spatial(1, 0)\n                for j in T.serial(128):\n                    with T.block(\"B\"):\n                        vj = T.axis.remap(\"S\", [j])\n                        B[vi, vj] = A[vi, vj] * 2.0\n\n    func = single_elementwise\n    s = tir.Schedule(func, debug_mask=\"all\")\n    _, y = s.get_loops(s.get_block(\"B\"))\n    s.blockize(y)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_blockize_inner)\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_two_elementwise_blockize_reverse_compute_at():\n    @T.prim_func\n    def before_blockize_rca(\n        A: T.Buffer[(128, 128), \"float32\"],\n        C: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i, j in T.grid(8, 8):\n            with T.block(\"B_o\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                T.writes(B[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                for i_1, j_1 in T.grid(16, 16):\n                    with T.block(\"B\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [i_1, j_1])\n                        T.reads(A[vi * 16 + vi_i, vj * 16 + vj_i])\n                        T.writes(B[vi * 16 + vi_i, vj * 16 + vj_i])\n                        B[vi * 16 + vi_i, vj * 16 + vj_i] = A[vi * 16 + vi_i, vj * 16 + vj_i] * 2.0\n            for ax0, ax1 in T.grid(16, 16):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(128, i * 16 + ax0)\n                    vj = T.axis.spatial(128, j * 16 + ax1)\n                    T.reads(B[vi, vj])\n                    T.writes(C[vi, vj])\n                    C[vi, vj] = B[vi, vj] + 1.0\n\n    @T.prim_func\n    def after_blockize_rca(\n        A: T.Buffer[(128, 128), \"float32\"],\n        C: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i, j in T.grid(8, 8):\n            with T.block(\"B_o\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                T.writes(B[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                for i_1, j_1 in T.grid(16, 16):\n                    with T.block(\"B\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [i_1, j_1])\n                        T.reads(A[vi * 16 + vi_i, vj * 16 + vj_i])\n                        T.writes(B[vi * 16 + vi_i, vj * 16 + vj_i])\n                        B[vi * 16 + vi_i, vj * 16 + vj_i] = A[vi * 16 + vi_i, vj * 16 + vj_i] * 2.0\n            with T.block(\"C_o\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(B[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                T.writes(C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                for ax0, ax1 in T.grid(16, 16):\n                    with T.block(\"C\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [ax0, ax1])\n                        T.reads(B[vi * 16 + vi_i, vj * 16 + vj_i])\n                        T.writes(C[vi * 16 + vi_i, vj * 16 + vj_i])\n                        C[vi * 16 + vi_i, vj * 16 + vj_i] = B[vi * 16 + vi_i, vj * 16 + vj_i] + 1.0\n\n    func = before_blockize_rca\n    s = tir.Schedule(func, debug_mask=\"all\")\n    _, _, x, _ = s.get_loops(s.get_block(\"C\"))\n    s.blockize(x)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_blockize_rca)\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_two_elementwise_blockize_compute_at():\n    @T.prim_func\n    def before_blockize_compute_at(\n        A: T.Buffer[(128, 128), \"float32\"],\n        C: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        # body\n        # with T.block(\"root\")\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i_0, j_0 in T.grid(8, 8):\n            for ax0, ax1 in T.grid(16, 16):\n                with T.block(\"B\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + ax0)\n                    vj = T.axis.spatial(128, j_0 * 16 + ax1)\n                    T.reads(A[vi, vj])\n                    T.writes(B[vi, vj])\n                    B[vi, vj] = A[vi, vj] * 2.0\n            with T.block(\"C_o\"):\n                vi_o, vj_o = T.axis.remap(\"SS\", [i_0, j_0])\n                T.reads(B[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                T.writes(C[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                for i_1, j_1 in T.grid(16, 16):\n                    with T.block(\"C\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [i_1, j_1])\n                        T.reads(B[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        T.writes(C[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        C[vi_o * 16 + vi_i, vj_o * 16 + vj_i] = (\n                            B[vi_o * 16 + vi_i, vj_o * 16 + vj_i] + 1.0\n                        )\n\n    @T.prim_func\n    def after_blockize_compute_at(\n        A: T.Buffer[(128, 128), \"float32\"],\n        C: T.Buffer[(128, 128), \"float32\"],\n    ) -> None:\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i_0, j_0 in T.grid(8, 8):\n            with T.block(\"B_o\"):\n                vi_o, vj_o = T.axis.remap(\"SS\", [i_0, j_0])\n                T.reads(A[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                T.writes(B[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                for ax0, ax1 in T.grid(16, 16):\n                    with T.block(\"B\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [ax0, ax1])\n                        T.reads(A[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        T.writes(B[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        B[vi_o * 16 + vi_i, vj_o * 16 + vj_i] = (\n                            A[vi_o * 16 + vi_i, vj_o * 16 + vj_i] * 2.0\n                        )\n            with T.block(\"C_o\"):\n                vi_o, vj_o = T.axis.remap(\"SS\", [i_0, j_0])\n                T.reads(B[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                T.writes(C[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                for i_1, j_1 in T.grid(16, 16):\n                    with T.block(\"C\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [i_1, j_1])\n                        T.reads(B[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        T.writes(C[vi_o * 16 + vi_i, vj_o * 16 + vj_i])\n                        C[vi_o * 16 + vi_i, vj_o * 16 + vj_i] = (\n                            B[vi_o * 16 + vi_i, vj_o * 16 + vj_i] + 1.0\n                        )\n\n    func = before_blockize_compute_at\n    s = tir.Schedule(func, debug_mask=\"all\")\n    _, _, x, _ = s.get_loops(s.get_block(\"B\"))\n    s.blockize(x)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_blockize_compute_at)\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_blockize_init_loops():\n    @T.prim_func\n    def rowsum(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128,), \"float32\"]) -> None:\n        for k, i in T.grid(128, 128):\n            with T.block(\"B\"):\n                vk, vi = T.axis.remap(\"RS\", [k, i])\n                with T.init():\n                    B[vi] = 0.0\n                B[vi] = B[vi] + A[vi, vk]\n\n    @T.prim_func\n    def after_rowsum_blockize(\n        A: T.Buffer[(128, 128), \"float32\"],\n        B: T.Buffer[(128,), \"float32\"],\n    ) -> None:\n        with T.block(\"blockized_B\"):\n            vko = T.axis.R(1, 0)\n            vio = T.axis.S(1, 0)\n            with T.init():\n                for i1 in T.serial(0, 128):\n                    with T.block(\"B_init\"):\n                        vi_init = T.axis.S(128, i1)\n                        B[vi_init] = T.float32(0)\n            for i0, i1_1 in T.grid(128, 128):\n                with T.block(\"B\"):\n                    vk, vi = T.axis.remap(\"RS\", [i0, i1_1])\n                    B[vi] = B[vi] + A[vi, vk]\n\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    k, _ = s.get_loops(s.get_block(\"B\"))\n    s.blockize(k)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_rowsum_blockize)\n    verify_trace_roundtrip(sch=s, mod=rowsum)\n\n\ndef test_blockize_outer_int64_shape():\n    @T.prim_func\n    def single_elementwise_int64(\n        A: T.Buffer[(T.int64(16), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(16), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i0, j0, i1, j1 in T.grid(T.int64(1), T.int64(8), T.int64(16), T.int64(16)):\n            with T.block(\"B\"):\n                vi = T.axis.S(T.int64(16), i0 * T.int64(16) + i1)\n                vj = T.axis.S(T.int64(128), j0 * T.int64(16) + j1)\n                B[vi, vj] = A[vi, vj] + 1.0\n\n    @T.prim_func\n    def after_single_elementwise_int64_blockize(\n        A: T.Buffer[(T.int64(16), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(16), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i0, j0 in T.grid(T.int64(1), T.int64(8)):\n            with T.block(\"B_o\"):\n                vi_o = T.axis.spatial(T.int64(1), T.int64(0))\n                vj_o = T.axis.spatial(T.int64(8), j0)\n                for i1, j1 in T.grid(T.int64(16), T.int64(16)):\n                    with T.block(\"B\"):\n                        vi_i, vj_i = T.axis.remap(\"SS\", [i1, j1])\n                        B[vi_i, vj_o * T.int64(16) + vj_i] = A[\n                            vi_i, vj_o * T.int64(16) + vj_i\n                        ] + T.float32(1)\n\n    s = tir.Schedule(single_elementwise_int64, debug_mask=\"all\")\n    _, _, i1, _ = s.get_loops(s.get_block(\"B\"))\n    s.blockize(i1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], after_single_elementwise_int64_blockize)\n    verify_trace_roundtrip(sch=s, mod=single_elementwise_int64)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_cache_index.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n########## Function before schedule ##########\n\n\n@T.prim_func\ndef resize(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (1, 3, 40, 40))\n    B = T.match_buffer(b, (1, 3, 80, 80))\n    for i0, i1, i2, i3 in T.grid(1, 3, 80, 80):\n        with T.block(\"A\"):\n            n, c, vi, vj = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            B[n, c, vi, vj] = A[n, c, vi // 4 + vj // 4, vj // 2]\n\n\n@T.prim_func\ndef resize_cache_index(\n    A: T.Buffer[(1, 3, 40, 40), \"float32\"], B: T.Buffer[(1, 3, 80, 80), \"float32\"]\n) -> None:\n    index_var_0 = T.alloc_buffer([80, 80], dtype=\"int32\", strides=[1])\n    index_var_1 = T.alloc_buffer([80], dtype=\"int32\", strides=[1])\n    for ax0, ax1 in T.grid(80, 80):\n        with T.block(\"index_0\"):\n            v0 = T.axis.spatial(80, ax0)\n            v1 = T.axis.spatial(80, ax1)\n            T.reads()\n            T.writes(index_var_0[v0, v1])\n            index_var_0[v0, v1] = v0 // 4 + v1 // 4\n    for ax0 in T.serial(80):\n        with T.block(\"index_1\"):\n            v0 = T.axis.spatial(80, ax0)\n            T.reads()\n            T.writes(index_var_1[v0])\n            index_var_1[v0] = v0 // 2\n    for i0, i1, i2, i3 in T.grid(1, 3, 80, 80):\n        with T.block(\"A\"):\n            n, c, vi, vj = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            T.reads(A[n, c, vi // 4 + vj // 4, vj // 2])\n            T.writes(B[n, c, vi, vj])\n            B[n, c, vi, vj] = A[n, c, index_var_0[vi, vj], index_var_1[vj]]\n\n\ndef test_inplace_cache_read():\n    sch = tvm.tir.Schedule(resize, debug_mask=\"all\")\n    block = sch.get_block(\"A\")\n    sch.cache_index(block, 0)\n    tvm.ir.assert_structural_equal(resize_cache_index, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=resize)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_cache_read_write.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n########## Function before schedule ##########\n\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_shape_int64(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (T.int64(128), T.int64(128)))\n    B = T.alloc_buffer((T.int64(128), T.int64(128)))\n    C = T.match_buffer(c, (T.int64(128), T.int64(128)))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef func_nested_seq(b: T.handle, c: T.handle) -> None:\n    A = T.alloc_buffer((128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A[vi, vj] = 2.0\n    for i, j in T.grid(8, 8):\n        for x, y in T.grid(16, 16):\n            with T.block(\"B0\"):\n                vi = T.axis.S(128, i * 16 + x)\n                vj = T.axis.S(128, j * 16 + y)\n                B[vi, vj] = 1.0\n        for x, y in T.grid(16, 16):\n            with T.block(\"B1\"):\n                vi = T.axis.S(128, i * 16 + x)\n                vj = T.axis.S(128, j * 16 + y)\n                B[vi, vj] = A[vi, vj] + B[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef access_under_scope(b: T.handle, c: T.handle) -> None:\n    A = T.alloc_buffer((128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i0, j0 in T.grid(8, 8):\n        with T.block(\"scope\"):\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            for x, y in T.grid(16, 16):\n                with T.block(\"A\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    A[vi, vj] = 1.0\n            for x, y in T.grid(16, 16):\n                with T.block(\"B\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    B[vi, vj] = A[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef opaque_access(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), dtype=\"float16\")\n    B = T.match_buffer(b, (128, 128), dtype=\"float16\")\n    C = T.match_buffer(c, (128, 128), dtype=\"float16\")\n    D = T.match_buffer(d, (128, 128), dtype=\"float16\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"load_store\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi, vj])\n            T.writes(D[vi, vj])\n            D[vi, vj] = A[vi, vj]\n    for i, j in T.grid(8, 8):\n        with T.block(\"opaque\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(B[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    B.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A.data,\n                        vi * 2048 + vj * 16,\n                        128,\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n    for i, j in T.grid(8, 8):\n        with T.block(\"match_buffer\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            A0 = T.match_buffer(\n                A[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            C0 = T.match_buffer(\n                C[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    C0.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A0.data,\n                        A0.elem_offset,\n                        A0.strides[0],\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n\n\n@T.prim_func\ndef func_multi_consumer() -> None:\n    A = T.alloc_buffer((128))\n    B = T.alloc_buffer((128))\n    C = T.alloc_buffer((128))\n    for i in T.grid(8):\n        for j in T.grid(16):\n            with T.block(\"A\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A[vi] = 1.0\n        for j in T.grid(16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i * 16 + j)\n                B[vi] = A[vi] + 1.0\n    for i in T.grid(128):\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = A[vi]\n\n\n@T.prim_func\ndef func_multi_producer() -> None:\n    A = T.alloc_buffer((128))\n    B = T.alloc_buffer((128))\n    for i in range(128):\n        with T.block(\"A0\"):\n            vi = T.axis.S(128, i)\n            A[vi] = 1.0\n    for i in range(128):\n        with T.block(\"A1\"):\n            vi = T.axis.S(128, i)\n            A[vi] = 2.0\n    for i in range(128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            B[vi] = A[vi]\n\n\n@T.prim_func\ndef func_with_block_predicate() -> None:\n    A = T.alloc_buffer((120))\n    B = T.alloc_buffer((120))\n    for i, j in T.grid(16, 8):\n        with T.block(\"producer\"):\n            T.where(i * 8 + j < 120)\n            ax = T.axis.S(120, i * 8 + j)\n            A[ax] = 0.0\n    for i, j in T.grid(16, 8):\n        with T.block(\"consumer\"):\n            T.where(i * 8 + j < 120)\n            ax = T.axis.S(120, i * 8 + j)\n            B[ax] = A[ax] + 1.0\n\n\n@T.prim_func\ndef inplace_func(data_io: T.Buffer[(64), \"int32\"]):\n    data_1d = T.alloc_buffer([64], dtype=\"int32\")\n    for i0 in T.serial(64):\n        with T.block(\"copy_in\"):\n            v0 = T.axis.remap(\"S\", [i0])\n            data_1d[v0] = data_io[v0]\n    for i0 in T.serial(1):\n        with T.block(\"ext_call\"):\n            T.reads(data_1d[:64])\n            T.writes(data_1d[:64])\n            T.evaluate(T.call_extern(\"call_impl\", data_1d.data, dtype=\"\"))\n    for i0 in T.serial(64):\n        with T.block(\"copy_out\"):\n            v0 = T.axis.remap(\"S\", [i0])\n            data_io[v0] = data_1d[v0]\n\n\n@T.prim_func\ndef inplace_call(data_io: T.Buffer[(64), \"int32\"]):\n    for i0 in T.serial(1):\n        with T.block(\"ext_call\"):\n            T.reads(data_io[:64])\n            T.writes(data_io[:64])\n            T.evaluate(T.call_extern(\"call_impl\", data_io.data, dtype=\"\"))\n\n\n@T.prim_func\ndef cache_read_nested_seq_target(\n    B: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n) -> None:\n    A = T.alloc_buffer([128, 128], dtype=\"float32\")\n    A_global = T.alloc_buffer([128, 128], dtype=\"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads()\n            T.writes(A[vi, vj])\n            A[vi, vj] = T.float32(2)\n    for i, j in T.grid(8, 8):\n        for x, y in T.grid(16, 16):\n            with T.block(\"B0\"):\n                vi = T.axis.spatial(128, i * 16 + x)\n                vj = T.axis.spatial(128, j * 16 + y)\n                T.reads()\n                T.writes(B[vi, vj])\n                B[vi, vj] = T.float32(1)\n        for x, y in T.grid(16, 16):\n            with T.block(\"B1\"):\n                vi = T.axis.spatial(128, i * 16 + x)\n                vj = T.axis.spatial(128, j * 16 + y)\n                T.reads(A[vi, vj], B[vi, vj])\n                T.writes(B[vi, vj])\n                B[vi, vj] = A[vi, vj] + B[vi, vj]\n    for ax0, ax1 in T.grid(128, 128):\n        with T.block(\"A_global\"):\n            v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n            T.reads(A[v0, v1])\n            T.writes(A_global[v0, v1])\n            A_global[v0, v1] = A[v0, v1]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A_global[vi, vj])\n            T.writes(C[vi, vj])\n            C[vi, vj] = A_global[vi, vj] * T.float32(2)\n\n\n########## Expected function after cache_read ##########\n\n\n@T.prim_func\ndef cache_read_elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    A_global = T.alloc_buffer((128, 128))\n    B_local = T.alloc_buffer((128, 128), scope=\"local\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"A_global\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A_global[vi, vj] = A[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A_global[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"B_local\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_local[vi, vj] = B[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B_local[vi, vj] + 1.0\n\n\n@T.prim_func\ndef cache_read_under_scope(b: T.handle, c: T.handle) -> None:\n    A = T.alloc_buffer((128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    A_global = T.alloc_buffer((128, 128))\n\n    for i0, j0 in T.grid(8, 8):\n        with T.block(\"scope\"):\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            A_local = T.alloc_buffer((128, 128), scope=\"local\")\n            for x, y in T.grid(16, 16):\n                with T.block(\"A\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    A[vi, vj] = 1.0\n            for x, y in T.grid(16, 16):\n                with T.block(\"A_local\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    A_local[vi, vj] = A[vi, vj]\n            for x, y in T.grid(16, 16):\n                with T.block(\"B\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    B[vi, vj] = A_local[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"A_global\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A_global[vi, vj] = A[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A_global[vi, vj] * 2.0\n\n\n@T.prim_func\ndef cache_read_opaque_access(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), dtype=\"float16\")\n    B = T.match_buffer(b, (128, 128), dtype=\"float16\")\n    C = T.match_buffer(c, (128, 128), dtype=\"float16\")\n    D = T.match_buffer(d, (128, 128), dtype=\"float16\")\n    A_global = T.alloc_buffer((128, 128), dtype=\"float16\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"A_global\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A_global[vi, vj] = A[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"load_store\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A_global[vi, vj])\n            T.writes(D[vi, vj])\n            D[vi, vj] = A_global[vi, vj]\n    for i, j in T.grid(8, 8):\n        with T.block(\"opaque\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A_global[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(B[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    B.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A_global.data,\n                        vi * 2048 + vj * 16,\n                        128,\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n    for i, j in T.grid(8, 8):\n        with T.block(\"match_buffer\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A_global[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            A0 = T.match_buffer(\n                A_global[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            C0 = T.match_buffer(\n                C[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    C0.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A0.data,\n                        A0.elem_offset,\n                        A0.strides[0],\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n\n\n@T.prim_func\ndef cache_read_multi_consumer() -> None:\n    A = T.alloc_buffer((128))\n    B = T.alloc_buffer((128))\n    C = T.alloc_buffer((128))\n    A_global = T.alloc_buffer((128))\n    for i in T.grid(8):\n        for j in T.grid(16):\n            with T.block(\"A\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A[vi] = 1.0\n        for j in T.grid(16):\n            with T.block(\"A\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A_global[vi] = A[vi]\n        for j in T.grid(16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i * 16 + j)\n                B[vi] = A_global[vi] + 1.0\n\n    for i in T.grid(128):\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = A_global[vi]\n\n\n@T.prim_func\ndef cache_read_multi_consumer_target() -> None:\n    A = T.alloc_buffer((128))\n    B = T.alloc_buffer((128))\n    C = T.alloc_buffer((128))\n    A_global = T.alloc_buffer((128))\n    for i in T.grid(8):\n        for j in T.grid(16):\n            with T.block(\"A\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A[vi] = 1.0\n        for j in T.grid(16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i * 16 + j)\n                B[vi] = A[vi] + 1.0\n\n    for i in T.grid(128):\n        with T.block(\"A\"):\n            vi = T.axis.S(128, i)\n            A_global[vi] = A[vi]\n    for i in T.grid(128):\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = A_global[vi]\n\n\n@T.prim_func\ndef continuous_cache_read(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    B_shared = T.alloc_buffer((128, 128), scope=\"shared\")\n    B_local = T.alloc_buffer((128, 128), scope=\"local\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"B_shared\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_shared[vi, vj] = B[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B_local\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_local[vi, vj] = B_shared[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B_local[vi, vj] + 1.0\n\n\n@T.prim_func\ndef block_predicate_cache_read() -> None:\n    A = T.alloc_buffer([120], dtype=\"float32\")\n    B = T.alloc_buffer([120], dtype=\"float32\")\n    A_shared = T.alloc_buffer([120], dtype=\"float32\", scope=\"shared\")\n    for i, j in T.grid(16, 8):\n        with T.block(\"producer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            A[ax] = T.float32(0)\n    for ax0 in T.serial(120):\n        with T.block(\"A_shared\"):\n            v0 = T.axis.spatial(120, ax0)\n            A_shared[v0] = A[v0]\n    for i, j in T.grid(16, 8):\n        with T.block(\"consumer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            B[ax] = A_shared[ax] + T.float32(1)\n\n\n@T.prim_func\ndef cache_read_shape_int64(var_A: T.handle, var_C: T.handle) -> None:\n    A = T.match_buffer(var_A, (T.int64(128), T.int64(128)), dtype=\"float32\")\n    C = T.match_buffer(var_C, (T.int64(128), T.int64(128)), dtype=\"float32\")\n    B = T.alloc_buffer([T.int64(128), T.int64(128)], dtype=\"float32\")\n    A_global = T.alloc_buffer([T.int64(128), T.int64(128)], dtype=\"float32\")\n    for ax0, ax1 in T.grid(T.int64(128), T.int64(128)):\n        with T.block(\"A_global\"):\n            v0, v1 = T.axis.remap(\"SS\", [ax0, ax1])\n            T.reads(A[v0, v1])\n            T.writes(A_global[v0, v1])\n            A_global[v0, v1] = A[v0, v1]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A_global[vi, vj])\n            T.writes(B[vi, vj])\n            B[vi, vj] = A_global[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(B[vi, vj])\n            T.writes(C[vi, vj])\n            C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\n@T.prim_func\ndef cache_read_inplace(data_io: T.Buffer[64, \"int32\"]) -> None:\n    data_1d = T.alloc_buffer([64], dtype=\"int32\")\n    data_io_local = T.alloc_buffer([64], dtype=\"int32\", scope=\"local\")\n    for ax0 in T.serial(64):\n        with T.block(\"data_io_local\"):\n            v0 = T.axis.spatial(64, ax0)\n            T.reads(data_io[v0])\n            T.writes(data_io_local[v0])\n            data_io_local[v0] = data_io[v0]\n    for i0 in T.serial(64):\n        with T.block(\"copy_in\"):\n            v0 = T.axis.spatial(64, i0)\n            T.reads(data_io_local[v0])\n            T.writes(data_1d[v0])\n            data_1d[v0] = data_io_local[v0]\n    for i0 in T.serial(1):\n        with T.block(\"ext_call\"):\n            T.reads(data_1d[0:64])\n            T.writes(data_1d[0:64])\n            T.evaluate(T.call_extern(\"call_impl\", data_1d.data, dtype=\"\"))\n    for i0 in T.serial(64):\n        with T.block(\"copy_out\"):\n            v0 = T.axis.spatial(64, i0)\n            T.reads(data_1d[v0])\n            T.writes(data_io[v0])\n            data_io[v0] = data_1d[v0]\n\n\n@T.prim_func\ndef cache_inplace_buffer(data_io: T.Buffer[64, \"int32\"]) -> None:\n    data_io_local = T.alloc_buffer([64], dtype=\"int32\", scope=\"local\")\n    data_io_global = T.alloc_buffer([64], dtype=\"int32\")\n    data_io_global_1 = T.alloc_buffer([64], dtype=\"int32\")\n    for ax0 in T.serial(64):\n        with T.block(\"data_io_global\"):\n            v0 = T.axis.spatial(64, ax0)\n            T.reads(data_io[v0])\n            T.writes(data_io_global[v0])\n            data_io_global[v0] = data_io[v0]\n    for i0 in T.serial(1):\n        for ax0 in T.serial(64):\n            with T.block(\"data_io_local\"):\n                v0 = T.axis.spatial(64, ax0)\n                T.reads(data_io_global[v0])\n                T.writes(data_io_local[v0])\n                data_io_local[v0] = data_io_global[v0]\n        with T.block(\"ext_call\"):\n            T.reads(data_io_local[0:64])\n            T.writes(data_io_local[0:64])\n            T.evaluate(T.call_extern(\"call_impl\", data_io_local.data, dtype=\"\"))\n        for ax0 in T.serial(64):\n            with T.block(\"data_io_local\"):\n                v0 = T.axis.spatial(64, ax0)\n                T.reads(data_io_local[v0])\n                T.writes(data_io_global_1[v0])\n                data_io_global_1[v0] = data_io_local[v0]\n    for ax0 in T.serial(64):\n        with T.block(\"data_io_global\"):\n            v0 = T.axis.spatial(64, ax0)\n            T.reads(data_io_global_1[v0])\n            T.writes(data_io[v0])\n            data_io[v0] = data_io_global_1[v0]\n\n\n########## Expected function after cache_write ##########\n\n\n@T.prim_func\ndef cache_write_elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    B_global = T.alloc_buffer((128, 128), scope=\"local\")\n    C_local = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B_global\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_global[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = B_global[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C_local\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C_local[vi, vj] = B[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = C_local[vi, vj]\n\n\n@T.prim_func\ndef cache_write_under_scope(b: T.handle, c: T.handle) -> None:\n    A = T.alloc_buffer((128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    A_global = T.alloc_buffer((128, 128))\n\n    for i0, j0 in T.grid(8, 8):\n        with T.block(\"scope\"):\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            A_local = T.alloc_buffer((128, 128), scope=\"local\")\n            B_global = T.alloc_buffer((128, 128))\n            for x, y in T.grid(16, 16):\n                with T.block(\"A_local\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    A_local[vi, vj] = 1.0\n            for x, y in T.grid(16, 16):\n                with T.block(\"A\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    A_global[vi, vj] = A_local[vi, vj]\n            for x, y in T.grid(16, 16):\n                with T.block(\"B_global\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    B_global[vi, vj] = A_global[vi, vj] + 1.0\n            for x, y in T.grid(16, 16):\n                with T.block(\"B_global\"):\n                    vi = T.axis.S(128, i * 16 + x)\n                    vj = T.axis.S(128, j * 16 + y)\n                    B[vi, vj] = B_global[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"A_global\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A[vi, vj] = A_global[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef cache_write_opaque_access(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), dtype=\"float16\")\n    B = T.match_buffer(b, (128, 128), dtype=\"float16\")\n    C = T.match_buffer(c, (128, 128), dtype=\"float16\")\n    D = T.match_buffer(d, (128, 128), dtype=\"float16\")\n    D_global = T.alloc_buffer((128, 128), dtype=\"float16\")\n    B_global = T.alloc_buffer((128, 128), dtype=\"float16\")\n    C_global = T.alloc_buffer((128, 128), dtype=\"float16\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"load_store\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi, vj])\n            T.writes(D_global[vi, vj])\n            D_global[vi, vj] = A[vi, vj]\n    for i, j in T.grid(8, 8):\n        with T.block(\"opaque\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(B_global[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    B_global.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A.data,\n                        vi * 2048 + vj * 16,\n                        128,\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n    for i, j in T.grid(8, 8):\n        with T.block(\"match_buffer\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            T.writes(C_global[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n            A0 = T.match_buffer(\n                A[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            C0 = T.match_buffer(\n                C_global[\n                    vi * 16 : vi * 16 + 16,\n                    vj * 16 : vj * 16 + 16,\n                ],\n                (16, 16),\n                \"float16\",\n                strides=[128, 1],\n                offset_factor=1,\n            )\n            T.evaluate(\n                T.tvm_load_matrix_sync(\n                    C0.data,\n                    16,\n                    16,\n                    16,\n                    vi * 8 + vj,\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"float16\"),\n                        A0.data,\n                        A0.elem_offset,\n                        A0.strides[0],\n                        1,\n                        dtype=\"handle\",\n                    ),\n                    128,\n                    \"row_major\",\n                    dtype=\"handle\",\n                )\n            )\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = D_global[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = B_global[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = C_global[vi, vj]\n\n\n@T.prim_func\ndef cache_write_multi_consumer() -> None:\n    A = T.alloc_buffer((128))\n    B = T.alloc_buffer((128))\n    C = T.alloc_buffer((128))\n    A_global = T.alloc_buffer((128))\n    for i in T.grid(8):\n        for j in T.grid(16):\n            with T.block(\"A_global\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A_global[vi] = 1.0\n        for j in T.grid(16):\n            with T.block(\"A\"):\n                vi = T.axis.S(128, i * 16 + j)\n                A[vi] = A_global[vi]\n        for j in T.grid(16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i * 16 + j)\n                B[vi] = A[vi] + 1.0\n\n    for i in T.grid(128):\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = A[vi]\n\n\n@T.prim_func\ndef continuous_cache_write(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B_shared = T.alloc_buffer((128, 128), scope=\"shared\")\n    B_local = T.alloc_buffer((128, 128), scope=\"local\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_local[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_shared[vi, vj] = B_local[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = B_shared[vi, vj]\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef block_predicate_cache_write_intermediate_buf() -> None:\n    A = T.alloc_buffer([120], dtype=\"float32\")\n    B = T.alloc_buffer([120], dtype=\"float32\")\n    A_shared = T.alloc_buffer([120], dtype=\"float32\", scope=\"shared\")\n    for i, j in T.grid(16, 8):\n        with T.block(\"producer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            A_shared[ax] = T.float32(0)\n    for ax0 in T.serial(120):\n        with T.block(\"A_shared\"):\n            v0 = T.axis.spatial(120, ax0)\n            A[v0] = A_shared[v0]\n    for i, j in T.grid(16, 8):\n        with T.block(\"consumer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            B[ax] = A[ax] + 1.0\n\n\n@T.prim_func\ndef block_predicate_cache_write_output_buf() -> None:\n    A = T.alloc_buffer([120], dtype=\"float32\")\n    B = T.alloc_buffer([120], dtype=\"float32\")\n    B_shared = T.alloc_buffer([120], dtype=\"float32\", scope=\"shared\")\n    for i, j in T.grid(16, 8):\n        with T.block(\"producer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            A[ax] = T.float32(0)\n    for i, j in T.grid(16, 8):\n        with T.block(\"consumer\"):\n            ax = T.axis.spatial(120, i * 8 + j)\n            T.where(i * 8 + j < 120)\n            B_shared[ax] = A[ax] + T.float32(1)\n    for ax0 in T.serial(120):\n        with T.block(\"B_shared\"):\n            v0 = T.axis.spatial(120, ax0)\n            B[v0] = B_shared[v0]\n\n\n########## Testcases for cache_read ##########\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_cache_read_elementwise(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    if use_block_name:\n        cached_a = sch.cache_read(\"B\", \"A\", \"global\")\n        cached_b = sch.cache_read(\"C\", \"B\", \"local\")\n    else:\n        cached_a = sch.cache_read(block_b, 0, \"global\")\n        cached_b = sch.cache_read(block_c, 0, \"local\")\n    assert sch.get(cached_a) == sch.get(sch.get_block(\"A_global\"))\n    assert sch.get(cached_b) == sch.get(sch.get_block(\"B_local\"))\n    assert sch.get(block_b) == sch.get(sch.get_block(\"B\"))\n    assert sch.get(block_c) == sch.get(sch.get_block(\"C\"))\n    tvm.ir.assert_structural_equal(cache_read_elementwise, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_cache_read_under_scope(use_block_name):\n    sch = tir.Schedule(access_under_scope, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.cache_read(block_b, 0, \"local\")\n    sch.cache_read(block_c, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_read_under_scope, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=access_under_scope)\n\n\ndef test_cache_read_opaque_access(use_block_name):\n    sch = tir.Schedule(opaque_access, debug_mask=\"all\")\n    block = \"load_store\" if use_block_name else sch.get_block(\"load_store\")\n    sch.cache_read(block, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_read_opaque_access, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=opaque_access)\n\n\ndef test_cache_read_location(use_block_name):\n    sch = tir.Schedule(func_multi_consumer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.cache_read(block_b, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_read_multi_consumer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_multi_consumer)\n\n    # Test that specific consumer block targetting works.\n    sch = tir.Schedule(func_multi_consumer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.cache_read(block_b, 0, \"global\", consumer_blocks=[block_c])\n    tvm.ir.assert_structural_equal(cache_read_multi_consumer_target, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_multi_consumer)\n\n    # Also test setting multiple consumers yields same result as unspecified.\n    sch = tir.Schedule(func_multi_consumer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.cache_read(block_b, 0, \"global\", consumer_blocks=[block_b, block_c])\n    tvm.ir.assert_structural_equal(cache_read_multi_consumer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_multi_consumer)\n\n\ndef test_continuous_cache_read(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.cache_read(block_c, 0, \"shared\")\n    sch.cache_read(block_c, 0, \"local\")\n    tvm.ir.assert_structural_equal(continuous_cache_read, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_cache_read_with_block_predicate(use_block_name):\n    sch = tir.Schedule(func_with_block_predicate, debug_mask=\"all\")\n    block = \"consumer\" if use_block_name else sch.get_block(\"consumer\")\n    sch.cache_read(block, 0, \"shared\")\n    tvm.ir.assert_structural_equal(block_predicate_cache_read, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_with_block_predicate)\n\n\ndef test_cache_read_non_int32_shape(use_block_name):\n    sch = tir.Schedule(elementwise_shape_int64, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.cache_read(block_b, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_read_shape_int64, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_shape_int64)\n\n\ndef test_cache_read_fail_multi_producer(use_block_name):\n    sch = tir.Schedule(func_multi_producer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_read(block_b, 0, \"global\")\n\n\ndef test_cache_read_fail_index_out_of_bound(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_read(block_b, 1, \"global\")\n\n\ndef test_cache_read_fail_invalid_storage_scope(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_read(block_b, 0, \"test_scope\")\n\n\ndef test_inplace_cache_read():\n    sch = tvm.tir.Schedule(inplace_func, debug_mask=\"all\")\n    block = sch.get_block(\"copy_in\")\n    sch.cache_read(block, 0, \"local\", [block])\n    tvm.ir.assert_structural_equal(cache_read_inplace, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=inplace_func)\n\n\ndef test_cache_inplace():\n    # cache_inplace could introduce WAR, which is expected but stage pipeline property changes\n    debug_mask = tvm.tir.schedule.state.ScheduleDebugMask.VERIFY_SREF_TREE\n    sch = tvm.tir.Schedule(inplace_call, debug_mask=debug_mask)\n    block = sch.get_block(\"ext_call\")\n    blocks = sch.cache_inplace(block, 0, \"local\")\n    block = sch.cache_read(blocks[0], 0, \"global\", [blocks[0]])\n    block = sch.cache_write(blocks[1], 0, \"global\")\n\n    tvm.ir.assert_structural_equal(cache_inplace_buffer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=inplace_call, debug_mask=debug_mask)\n\n\ndef test_cache_read_nested_seq(use_block_name):\n    sch = tir.Schedule(func_nested_seq, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.cache_read(block_c, 0, \"global\", consumer_blocks=[block_c])\n    tvm.ir.assert_structural_equal(cache_read_nested_seq_target, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_nested_seq)\n\n\n########## Testcases for cache_write ##########\n\n\ndef test_cache_write_elementwise(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    cached_b = sch.cache_write(\"B\" if use_block_name else block_b, 0, \"local\")\n    cached_c = sch.cache_write(\"C\" if use_block_name else block_c, 0, \"global\")\n    assert sch.get(cached_b) == sch.get(sch.get_block(\"B_local\"))\n    assert sch.get(cached_c) == sch.get(sch.get_block(\"C_global\"))\n    assert sch.get(block_b) == sch.get(sch.get_block(\"B\"))\n    assert sch.get(block_c) == sch.get(sch.get_block(\"C\"))\n    tvm.ir.assert_structural_equal(cache_write_elementwise, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_cache_write_under_scope(use_block_name):\n    sch = tir.Schedule(access_under_scope, debug_mask=\"all\")\n    block_a = \"A\" if use_block_name else sch.get_block(\"A\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_scope = sch.get_block(\"scope\")\n    sch.cache_write(block_a, 0, \"local\")\n    sch.cache_write(block_b, 0, \"global\")\n    sch.cache_write(block_scope, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_write_under_scope, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=access_under_scope)\n\n\ndef test_cache_write_opaque_access(use_block_name):\n    sch = tir.Schedule(opaque_access, debug_mask=\"all\")\n    block_store = \"load_store\" if use_block_name else sch.get_block(\"load_store\")\n    block_opaque = \"opaque\" if use_block_name else sch.get_block(\"opaque\")\n    block_match_buffer = \"match_buffer\" if use_block_name else sch.get_block(\"match_buffer\")\n    sch.cache_write(block_store, 0, \"global\")\n    sch.cache_write(block_opaque, 0, \"global\")\n    sch.cache_write(block_match_buffer, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_write_opaque_access, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=opaque_access)\n\n\ndef test_cache_write_location(use_block_name):\n    sch = tir.Schedule(func_multi_consumer, debug_mask=\"all\")\n    block_a = \"A\" if use_block_name else sch.get_block(\"A\")\n    sch.cache_write(block_a, 0, \"global\")\n    tvm.ir.assert_structural_equal(cache_write_multi_consumer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_multi_consumer)\n\n\ndef test_continuous_cache_write(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.cache_write(block_b, 0, \"shared\")\n    sch.cache_write(block_b, 0, \"local\")\n    tvm.ir.assert_structural_equal(continuous_cache_write, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_cache_write_with_block_predicate(use_block_name):\n    # cache write for intermediate buffer\n    sch = tir.Schedule(func_with_block_predicate, debug_mask=\"all\")\n    block = \"producer\" if use_block_name else sch.get_block(\"producer\")\n    sch.cache_write(block, 0, \"shared\")\n    tvm.ir.assert_structural_equal(block_predicate_cache_write_intermediate_buf, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_with_block_predicate)\n    # cache write for external buffer\n    sch = tir.Schedule(func_with_block_predicate, debug_mask=\"all\")\n    block = \"consumer\" if use_block_name else sch.get_block(\"consumer\")\n    sch.cache_write(block, 0, \"shared\")\n    tvm.ir.assert_structural_equal(block_predicate_cache_write_output_buf, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=func_with_block_predicate)\n\n\ndef test_cache_write_fail_multi_producer(use_block_name):\n    sch = tir.Schedule(func_multi_producer, debug_mask=\"all\")\n    block_a0 = \"A0\" if use_block_name else sch.get_block(\"A0\")\n    block_a1 = \"A1\" if use_block_name else sch.get_block(\"A1\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_write(block_a0, 0, \"global\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_write(block_a1, 0, \"global\")\n\n\ndef test_cache_write_fail_index_out_of_bound(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_write(block_b, 1, \"global\")\n\n\ndef test_cache_write_fail_invalid_storage_scope(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.cache_write(block_b, 0, \"test_scope\")\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_compute_at.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n@T.prim_func\ndef two_elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef two_elementwise_after_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    for i in range(0, 128):\n        for ax0, ax1 in T.grid(1, 128):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i + ax0)\n                vj = T.axis.S(128, ax1)\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j in range(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef blockized_1(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(8, 8):\n        with T.block(\"C_outer\"):\n            vi_o, vj_o = T.axis.remap(\"SS\", [i, j])\n            T.reads([B[\n                vi_o * 16 : vi_o * 16 + 16,\n                vj_o * 16 : vj_o * 16 + 16,\n            ]])\n            T.writes([C[\n                vi_o * 16 : vi_o * 16 + 16,\n                vj_o * 16 : vj_o * 16 + 16\n            ]])\n            for i_i, j_i in T.grid(16, 16):\n                with T.block(\"C_inner\"):\n                    vi = T.axis.S(128, vi_o * 16 + i_i)\n                    vj = T.axis.S(128, vj_o * 16 + j_i)\n                    C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef blockized_after_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i0_0, i1_0 in T.grid(8, 8):\n        for ax0, ax1 in T.grid(16, 16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i0_0 * 16 + ax0)\n                vj = T.axis.S(128, i1_0 * 16 + ax1)\n                B[vi, vj] = A[vi, vj] * 2.0\n        with T.block(\"C_outer\"):\n            vi_o, vj_o = T.axis.remap(\"SS\", [i0_0, i1_0])\n            T.reads([B[\n                vi_o * 16 : vi_o * 16 + 16,\n                vj_o * 16 : vj_o * 16 + 16,\n            ]])\n            T.writes([C[\n                vi_o * 16 : vi_o * 16 + 16,\n                vj_o * 16 : vj_o * 16 + 16\n            ]])\n            for i0_1, i1_1 in T.grid(16, 16):\n                with T.block(\"C_inner\"):\n                    vi = T.axis.S(128, vi_o * 16 + i0_1)\n                    vj = T.axis.S(128, vj_o * 16 + i1_1)\n                    C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef blockized_2(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i_o, j_o in T.grid(8, 8):\n        with T.block(\"B_outer\"):\n            vio, vjo = T.axis.remap(\"SS\", [i_o, j_o])\n            T.reads([A[\n                vio * 16 : vio * 16 + 16,\n                vjo * 16 : vjo * 16 + 16,\n            ]])\n            T.writes([B[\n                vio * 16 : vio * 16 + 16,\n                vjo * 16 : vjo * 16 + 16\n            ]])\n            for i_i, j_i in T.grid(16, 16):\n                with T.block(\"B_inner\"):\n                    vi = T.axis.S(128, vio * 16 + i_i)\n                    vj = T.axis.S(128, vjo * 16 + j_i)\n                    B[vi, vj] = A[vi, vj] * 2.0\n    for i_o, j_o, i_i, j_i in T.grid(4, 4, 32, 32):\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i_o * 32 + i_i)\n            vj = T.axis.S(128, j_o * 32 + j_i)\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef blockized_2_after_reverse_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i_o, j_o in T.grid(8, 8):\n        with T.block(\"B_outer\"):\n            vio, vjo = T.axis.remap(\"SS\", [i_o, j_o])\n            T.reads([A[\n                vio * 16 : vio * 16 + 16,\n                vjo * 16 : vjo * 16 + 16,\n            ]])\n            T.writes([B[\n                vio * 16 : vio * 16 + 16,\n                vjo * 16 : vjo * 16 + 16\n            ]])\n            for i_i, j_i in T.grid(16, 16):\n                with T.block(\"B_inner\"):\n                    vi = T.axis.S(128, vio * 16 + i_i)\n                    vj = T.axis.S(128, vjo * 16 + j_i)\n                    B[vi, vj] = A[vi, vj] * 2.0\n        for ax0, ax1 in T.grid(16, 16):\n            with T.block(\"C\"):\n                vi = T.axis.S(128, i_o * 16 + ax0)\n                vj = T.axis.S(128, j_o * 16 + ax1)\n                T.reads([B[vi, vj]])\n                T.writes([C[vi, vj]])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef blockized_2_after_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i_o, j_o in T.grid(4, 4):\n        for ax0, ax1 in T.grid(2, 2):\n            with T.block(\"blockized_B\"):\n                vio = T.axis.S(8, i_o * 2 + ax0)\n                vjo = T.axis.S(8, j_o * 2 + ax1)\n                T.reads([A[\n                    vio * 16 : vio * 16 + 16,\n                    vjo * 16 : vjo * 16 + 16,\n                ]])\n                T.writes([B[\n                    vio * 16 : vio * 16 + 16,\n                    vjo * 16 : vjo * 16 + 16,\n                ]])\n                for i_i, j_i in T.grid(16, 16):\n                    with T.block(\"B\"):\n                        vi = T.axis.S(128, vio * 16 + i_i)\n                        vj = T.axis.S(128, vjo * 16 + j_i)\n                        B[vi, vj] = A[vi, vj] * 2.0\n        for i_i, j_i in T.grid(32, 32):\n            with T.block(\"C\"):\n                vi = T.axis.S(128, i_o * 32 + i_i)\n                vj = T.axis.S(128, j_o * 32 + j_i)\n                C[vi, vj] = B[vi, vj] + 1.0\n\n@T.prim_func\ndef cuda_matmul_0(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared[v0, v1] = A[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared_local[v0, v1] = A_shared[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared_local[v0, v1] = B_shared[v0, v1]\n    for i, j, k in T.grid(2048, 2048, 2048):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C_local[vi, vj] = 0.0\n            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    v0_4 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    v1_4 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[v0_4, v1_4] = C_local[v0_4, v1_4]\n\n\n@T.prim_func\ndef cuda_matmul_0_after_compute_at(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared[v0, v1] = A[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared_local[v0, v1] = A_shared[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared_local[v0, v1] = B_shared[v0, v1]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for i, j, k in T.grid(4, 4, 2048):\n                                with T.block(\"C\"):\n                                    vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    vk = T.axis.R(2048, k)\n                                    with T.init():\n                                        C_local[vi, vj] = 0.0\n                                    C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[vi, vj] = C_local[vi, vj]\n\n\n@T.prim_func\ndef cuda_matmul_1(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared[v0, v1] = A[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared_local[v0, v1] = A_shared[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared_local[v0, v1] = B_shared[v0, v1]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for k_0 in T.serial(0, 256):\n                                for k_1 in T.unroll(0, 8):\n                                    for _, i, j in T.grid(1, 4, 4):\n                                        with T.block(\"C\"):\n                                            vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                            vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            vk = T.axis.R(2048, k_0 * 8 + k_1)\n                                            with T.init():\n                                                C_local[vi, vj] = 0.0\n                                            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[vi, vj] = C_local[vi, vj]\n\n\n@T.prim_func\ndef cuda_matmul_2(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared[v0, v1] = A[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared_local\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared_local[v0, v1] = B_shared[v0, v1]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for k_0 in T.serial(0, 256):\n                                for k_1 in T.unroll(0, 8):\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"A_shared_local\"):\n                                            v0 = T.axis.S(2048, k_0 * 8 + k_1 + i)\n                                            v1 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + j)\n                                            A_shared_local[v0, v1] = A_shared[v0, v1]\n                                    for _, i, j in T.grid(1, 4, 4):\n                                        with T.block(\"C\"):\n                                            vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                            vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            vk = T.axis.R(2048, k_0 * 8 + k_1)\n                                            with T.init():\n                                                C_local[vi, vj] = T.float32(0)\n                                            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    v0 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[v0, v1] = C_local[v0, v1]\n\n\n@T.prim_func\ndef cuda_matmul_3(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"A_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            A_shared[v0, v1] = A[v0, v1]\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for k0 in T.serial(0, 256):\n                                for k1 in T.unroll(0, 8):\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"A_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + j)\n                                            A_shared_local[v0, v1] = A_shared[v0, v1]\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"B_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            B_shared_local[v0, v1] = B_shared[v0, v1]\n                                    for _, i, j in T.grid(1, 4, 4):\n                                        with T.block(\"C\"):\n                                            vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                            vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            vk = T.axis.R(2048, k0 * 8 + k1)\n                                            with T.init():\n                                                C_local[vi, vj] = T.float32(0)\n                                            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    v0 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[v0, v1] = C_local[v0, v1]\n\n\n@T.prim_func\ndef cuda_matmul_4(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for i, j in T.grid(2048, 2048):\n        with T.block(\"B_shared\"):\n            v0, v1 = T.axis.remap(\"SS\", [i, j])\n            B_shared[v0, v1] = B[v0, v1]\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for k0 in T.serial(0, 256):\n                                for i, j in T.grid(8, 64):\n                                    with T.block(\"A_shared\"):\n                                        v0 = T.axis.S(2048, k0 * 8 + i)\n                                        v1 = T.axis.S(2048, by * 64 + j)\n                                        A_shared[v0, v1] = A[v0, v1]\n                                for k1 in T.unroll(0, 8):\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"A_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + j)\n                                            A_shared_local[v0, v1] = A_shared[v0, v1]\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"B_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            B_shared_local[v0, v1] = B_shared[v0, v1]\n                                    for _, i, j in T.grid(1, 4, 4):\n                                        with T.block(\"C\"):\n                                            vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                            vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            vk = T.axis.R(2048, k0 * 8 + k1)\n                                            with T.init():\n                                                C_local[vi, vj] = 0.0\n                                            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    v0 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[v0, v1] = C_local[v0, v1]\n\n\n@T.prim_func\ndef cuda_matmul_5(a: T.handle, b: T.handle, c: T.handle) -> None:  # pylint: disable=undefined-loop-variable\n    A = T.match_buffer(a, [2048, 2048], \"float32\")\n    B = T.match_buffer(b, [2048, 2048], \"float32\")\n    C = T.match_buffer(c, [2048, 2048], \"float32\")\n    A_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer([2048, 2048], \"float32\", scope=\"shared\")\n    A_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    B_shared_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    C_local = T.alloc_buffer([2048, 2048], \"float32\", scope=\"local\")\n    for by in T.thread_binding(0, 32, thread = \"blockIdx.y\"):\n        for bx in T.thread_binding(0, 32, thread = \"blockIdx.x\"):\n            for vy in T.thread_binding(0, 2, thread = \"vthread.y\"):\n                for vx in T.thread_binding(0, 2, thread = \"vthread.x\"):\n                    for ty in T.thread_binding(0, 8, thread = \"threadIdx.y\"):\n                        for tx in T.thread_binding(0, 8, thread = \"threadIdx.x\"):\n                            for k0 in T.serial(0, 256):\n                                for i, j in T.grid(8, 64):\n                                    with T.block(\"A_shared\"):\n                                        v0 = T.axis.S(2048, k0 * 8 + i)\n                                        v1 = T.axis.S(2048, by * 64 + j)\n                                        A_shared[v0, v1] = A[v0, v1]\n                                for i, j in T.grid(8, 64):\n                                    with T.block(\"B_shared\"):\n                                        v0 = T.axis.S(2048, k0 * 8 + i)\n                                        v1 = T.axis.S(2048, bx * 64 + j)\n                                        B_shared[v0, v1] = B[v0, v1]\n                                for k1 in T.unroll(0, 8):\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"A_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + j)\n                                            A_shared_local[v0, v1] = A_shared[v0, v1]\n                                    for i, j in T.grid(1, 4):\n                                        with T.block(\"B_shared_local\"):\n                                            v0 = T.axis.S(2048, k0 * 8 + k1 + i)\n                                            v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            B_shared_local[v0, v1] = B_shared[v0, v1]\n                                    for _, i, j in T.grid(1, 4, 4):\n                                        with T.block(\"C\"):\n                                            vi = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                            vj = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                            vk = T.axis.R(2048, k0 * 8 + k1)\n                                            with T.init():\n                                                C_local[vi, vj] = 0.0\n                                            C_local[vi, vj] = C_local[vi, vj] + A_shared_local[vk, vi] * B_shared_local[vk, vj]\n                            for i, j in T.grid(4, 4):\n                                with T.block(\"C_local\"):\n                                    v0 = T.axis.S(2048, by * 64 + vy * 32 + ty * 4 + i)\n                                    v1 = T.axis.S(2048, bx * 64 + vx * 32 + tx * 4 + j)\n                                    C[v0, v1] = C_local[v0, v1]\n\n\n@T.prim_func\ndef tiled(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i_0, j_0, i_1, j_1 in T.grid(8, 8, 16, 16):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i_0 * 16 + i_1)\n            vj = T.axis.S(128, j_0 * 16 + j_1)\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef tiled_after_reverse_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], \"float32\")\n    B = T.alloc_buffer([128, 128], \"float32\")\n    C = T.match_buffer(c, [128, 128], \"float32\")\n    for i_0, j_0, i_1 in T.grid(8, 8, 16):\n        for j_1 in T.serial(0, 16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i_0 * 16 + i_1)\n                vj = T.axis.S(128, j_0 * 16 + j_1)\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j_1 in T.serial(0, 16):\n            with T.block(\"C\"):\n                vi = T.axis.S(128, i_0 * 16 + i_1)\n                vj = T.axis.S(128, j_0 * 16 + j_1)\n                C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef tiled_trivial_binding(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [1, 128, 128], \"float32\")\n    B = T.alloc_buffer([1, 128, 128], \"float32\")\n    C = T.match_buffer(c, [1, 128, 128], \"float32\")\n    for i_0, j_0, i_1, j_1 in T.grid(8, 8, 16, 16):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i_0 * 16 + i_1)\n            vj = T.axis.S(128, j_0 * 16 + j_1)\n            B[0, vi, vj] = A[0, vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[0, vi, vj] = B[0, vi, vj] + 1.0\n\n\n@T.prim_func\ndef tiled_trivial_binding_after_reverse_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [1, 128, 128], \"float32\")\n    B = T.alloc_buffer([1, 128, 128], \"float32\")\n    C = T.match_buffer(c, [1, 128, 128], \"float32\")\n    for i_0, j_0, i_1 in T.grid(8, 8, 16):\n        for j_1 in T.serial(0, 16):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i_0 * 16 + i_1)\n                vj = T.axis.S(128, j_0 * 16 + j_1)\n                B[0, vi, vj] = A[0, vi, vj] * 2.0\n        for j_1 in T.serial(0, 16):\n            with T.block(\"C\"):\n                vi = T.axis.S(128, i_0 * 16 + i_1)\n                vj = T.axis.S(128, j_0 * 16 + j_1)\n                C[0, vi, vj] = B[0, vi, vj] + 1.0\n\n\n@T.prim_func\ndef factorized(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16, 16], \"float32\")\n    B = T.match_buffer(b, [16], \"float32\")\n    B_rf_local = T.alloc_buffer([16, 16], \"float32\", scope=\"local\")\n    for j in T.thread_binding(0, 16, thread = \"blockIdx.x\"):\n        for i_o in T.thread_binding(0, 4, thread = \"threadIdx.x\"):\n            for i_i, k in T.grid(4, 16):\n                with T.block(\"B_rf\"):\n                    vi = T.axis.S(16, i_o * 4 + i_i)\n                    vj, vk = T.axis.remap(\"SR\", [j, k])\n                    with T.init():\n                        B_rf_local[vi, vj] = 0.0\n                    B_rf_local[vi, vj] = B_rf_local[vi, vj] + A[vj, vi, vk]\n    for i, k in T.grid(16, 16):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + B_rf_local[vk, vi]\n\n\n@T.prim_func\ndef factorized_after_reverse_compute_at(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16, 16], \"float32\")\n    B = T.match_buffer(b, [16], \"float32\")\n    B_rf_local = T.alloc_buffer([16, 16], \"float32\", scope=\"local\")\n    for j in T.thread_binding(0, 16, thread = \"blockIdx.x\"):\n        for i_o in T.thread_binding(0, 4, thread = \"threadIdx.x\"):\n            for i_i, k in T.grid(4, 16):\n                with T.block(\"B_rf\"):\n                    vi = T.axis.S(16, i_o * 4 + i_i)\n                    vj = T.axis.S(16, j)\n                    vk = T.axis.R(16, k)\n                    with T.init():\n                        B_rf_local[vi, vj] = 0.0\n                    B_rf_local[vi, vj] = B_rf_local[vi, vj] + A[vj, vi, vk]\n            for k in T.serial(0, 4):\n                with T.block(\"B\"):\n                    vi = T.axis.S(16, j)\n                    vk = T.axis.R(16, i_o * 4 + k)\n                    with T.init():\n                        B[vi] = 0.0\n                    B[vi] = B[vi] + B_rf_local[vk, vi]\n\n\n@T.prim_func\ndef not_all_compact_data_flow(a: T.handle, c: T.handle):\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj]\n    for i, j in T.grid(128, 64):\n        with T.block(\"C_1\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj * 2] = B[vi, vj * 2] + 1.0\n        with T.block(\"C_2\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj * 2 + 1] = B[vi, vj * 2 + 1] * 2.0\n\n\n@T.prim_func\ndef not_all_compact_data_flow_after_compute_at(a: T.handle, c: T.handle):\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    for i, j in T.grid(128, 64):\n        for t in range(2):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(128, j * 2 + t)\n                B[vi, vj] = A[vi, vj]\n        with T.block(\"C_1\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj * 2] = B[vi, vj * 2] + 1.0\n        with T.block(\"C_2\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj * 2 + 1] = B[vi, vj * 2 + 1] * 2.0\n\n\n@T.prim_func\ndef fail_subtree_compact_dataflow(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    for i in range(0, 128):\n        for j in range(0, 64):\n            with T.block(\"B_0\"):\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(128, j)\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j in range(0, 64):\n            with T.block(\"B_1\"):\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(128, j + 64)\n                B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef fail_all_consumers_under_loop(a: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    D = T.match_buffer(d, (128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef fail_all_producers_under_loop(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    C = T.alloc_buffer((128, 128), \"float32\")\n    D = T.match_buffer(d, (128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = B[vi, vj] + C[vi, vj]\n\n\n@T.prim_func\ndef read_out_of_bound(a: T.handle, c:T.handle) -> None:\n    A = T.match_buffer(a, [16], \"float32\")\n    B = T.alloc_buffer([16], \"float32\")\n    C = T.match_buffer(c, [16], \"float32\")\n    for i in T.serial(0, 16):\n        with T.block(\"B\"):\n            v = T.axis.S(16, i)\n            B[v] = A[v]\n    for j in T.serial(0, 16):\n        with T.block(\"C\"):\n            v = T.axis.S(16, j)\n            T.reads(B[v : v + 2])\n            C[v] = T.if_then_else(v < 15, T.max(B[v], B[v + 1]), B[v], dtype=\"float32\")\n\n\n@T.prim_func\ndef read_out_of_bound_after_compute_at(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16], \"float32\")\n    B = T.alloc_buffer([16], \"float32\")\n    C = T.match_buffer(c, [16], \"float32\")\n    for j in T.serial(0, 16):\n        for i in T.serial(0, 2):\n            with T.block(\"B\"):\n                v = T.axis.S(16, j + i)\n                T.where(j + i < 16)\n                B[v] = A[v]\n        with T.block(\"C\"):\n            v = T.axis.S(16, j)\n            T.reads([B[v : v + 2]])\n            C[v] = T.if_then_else(v < 15, T.max(B[v], B[v + 1]), B[v], dtype=\"float32\")\n\n\n@T.prim_func\ndef multi_reduction(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(), \"float32\"]):\n    B = T.alloc_buffer((16, ), dtype=\"float32\")\n    for i, k in T.grid(16, 16):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 0.0\n            B[vi] += A[vi, vk]\n    for k in T.grid(16):\n        with T.block(\"C\"):\n            vk = T.axis.remap(\"R\", [k])\n            with T.init():\n                C[()] = 0.0\n            C[()] += B[vk]\n\n\n@T.prim_func\ndef multi_reduction_after_compute_at(\n    A: T.Buffer[(16, 16), \"float32\"],\n    C:T.Buffer[(), \"float32\"],\n):\n    B = T.alloc_buffer((16, ), dtype=\"float32\")\n    for k in T.grid(16):\n        for kk in T.grid(16):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [k, kk])\n                with T.init():\n                    B[vi] = 0.0\n                B[vi] += A[vi, vk]\n        with T.block(\"C\"):\n            vk = T.axis.remap(\"R\", [k])\n            with T.init():\n                C[()] = 0.0\n            C[()] += B[vk]\n\n\n@T.prim_func\ndef tiled_pooling_read_cache(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [224, 224], dtype=\"float32\")\n    Y = T.match_buffer(b, [224, 224], dtype=\"float32\")\n    cache = T.alloc_buffer([224, 224], dtype=\"float32\")\n    for hh, ww in T.grid(224, 224):\n        with T.block(\"cache\"):\n            h, w = T.axis.remap(\"SS\", [hh, ww])\n            cache[h, w] = X[h, w]\n    for hh_0, ww_0, hh_1, ww_1, khh, kww in T.grid(28, 28, 8, 8, 3, 3):\n        with T.block(\"compute\"):\n            h = T.axis.spatial(224, hh_0 * 8 + hh_1)\n            w = T.axis.spatial(224, ww_0 * 8 + ww_1)\n            kh, kw = T.axis.remap(\"RR\", [khh, kww])\n            with T.init():\n                Y[h, w] = 0.0\n            Y[h, w] = T.max(Y[h, w], T.if_then_else(\n                T.likely(1 <= h + kh, dtype=\"bool\") and \\\n                T.likely(h + kh < 225, dtype=\"bool\") and \\\n                T.likely(1 <= w + kw, dtype=\"bool\") and \\\n                T.likely(w + kw < 225, dtype=\"bool\"),\n                cache[h + kh - 1, w + kw - 1], 0.0, dtype=\"float32\"))\n\n@T.prim_func\ndef tiled_pooling_read_cache_after_compute_at(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [224, 224], dtype=\"float32\")\n    Y = T.match_buffer(b, [224, 224], dtype=\"float32\")\n    cache = T.alloc_buffer([224, 224], dtype=\"float32\")\n    for hh_0, ww_0 in T.grid(28, 28):\n        for ax0, ax1 in T.grid(10, 10):\n            with T.block(\"cache\"):\n                h = T.axis.spatial(224, hh_0 * 8 - 1 + ax0)\n                w = T.axis.spatial(224, ww_0 * 8 - 1 + ax1)\n                T.where(1 <= hh_0 * 8 + ax0 and hh_0 * 8 + ax0 < 225 and 1 <= ww_0 * 8 + ax1 and ww_0 * 8 + ax1 < 225)\n                cache[h, w] = X[h, w]\n        for hh_1, ww_1, khh, kww in T.grid(8, 8, 3, 3):\n            with T.block(\"compute\"):\n                h = T.axis.spatial(224, hh_0 * 8 + hh_1)\n                w = T.axis.spatial(224, ww_0 * 8 + ww_1)\n                kh, kw = T.axis.remap(\"RR\", [khh, kww])\n                with T.init():\n                    Y[h, w] = 0.0\n                Y[h, w] = T.max(Y[h, w], T.if_then_else(\n                    T.likely(1 <= h + kh, dtype=\"bool\") and \\\n                    T.likely(h + kh < 225, dtype=\"bool\") and \\\n                    T.likely(1 <= w + kw, dtype=\"bool\") and \\\n                    T.likely(w + kw < 225, dtype=\"bool\"),\n                    cache[h + kh - 1, w + kw - 1], 0.0, dtype=\"float32\"))\n\n@T.prim_func\ndef non_uniform_tiled_conv(x: T.Buffer[(1, 3, 100, 100), \"float32\"],\n                           w: T.Buffer[(16, 3, 3, 3), \"float32\"],\n                           y: T.Buffer[(1, 16, 98, 98), \"float32\"]) -> None:\n    x_global = T.alloc_buffer([1, 3, 100, 100], dtype=\"float32\")\n    for ax0, ax1, ax2, ax3 in T.grid(1, 3, 100, 100):\n        with T.block(\"cache\"):\n            v0, v1, v2, v3 = T.axis.remap(\"SSSS\", [ax0, ax1, ax2, ax3])\n            x_global[v0, v1, v2, v3] = x[v0, v1, v2, v3]\n    for h_o, w_o, n, c_o, h_i, w_i, c_i, kh, kw in T.grid(7, 7, 1, 16, 15, 15, 3, 3, 3):\n        with T.block(\"compute\"):\n            nn = T.axis.spatial(1, 0)\n            cc = T.axis.spatial(16, c_o)\n            hh = T.axis.spatial(98, h_o * 15 + h_i)\n            ww = T.axis.spatial(98, w_o * 15 + w_i)\n            rc, rh, rw = T.axis.remap(\"RRR\", [c_i, kh, kw])\n            T.where(h_o * 15 + h_i < 98 and w_o * 15 + w_i < 98)\n            with T.init():\n                y[nn, cc, hh, ww] = T.float32(0)\n            y[nn, cc, hh, ww] = y[nn, cc, hh, ww] + \\\n                x_global[nn, cc // 16 * 3 + rc, hh + rh, ww + rw] * w[cc, rc, rh, rw]\n\n@T.prim_func\ndef non_uniform_tiled_conv_after_compute_at(x: T.Buffer[(1, 3, 100, 100), \"float32\"],\n                                            w: T.Buffer[(16, 3, 3, 3), \"float32\"],\n                                            y: T.Buffer[(1, 16, 98, 98), \"float32\"]) -> None:\n    x_global = T.alloc_buffer([1, 3, 100, 100], dtype=\"float32\")\n    for h_o, w_o in T.grid(7, 7):\n        for ax0, ax1, ax2 in T.grid(3, 17, 17):\n            with T.block(\"cache\"):\n                v0 = T.axis.spatial(1, 0)\n                v1 = T.axis.spatial(3, ax0)\n                v2 = T.axis.spatial(100, h_o * 15 + ax1)\n                v3 = T.axis.spatial(100, w_o * 15 + ax2)\n                T.where(h_o * 15 + ax1 < 100 and w_o * 15 + ax2 < 100)\n                x_global[v0, v1, v2, v3] = x[v0, v1, v2, v3]\n        for n, c_o, h_i, w_i, c_i, kh, kw in T.grid(1, 16, 15, 15, 3, 3, 3):\n            with T.block(\"compute\"):\n                nn = T.axis.spatial(1, 0)\n                cc = T.axis.spatial(16, c_o)\n                hh = T.axis.spatial(98, h_o * 15 + h_i)\n                ww = T.axis.spatial(98, w_o * 15 + w_i)\n                rc, rh, rw = T.axis.remap(\"RRR\", [c_i, kh, kw])\n                T.where(h_o * 15 + h_i < 98 and w_o * 15 + w_i < 98)\n                with T.init():\n                    y[nn, cc, hh, ww] = T.float32(0)\n                y[nn, cc, hh, ww] = y[nn, cc, hh, ww] + \\\n                    x_global[nn, cc // 16 * 3 + rc, hh + rh, ww + rw] * w[cc, rc, rh, rw]\n\n@T.prim_func\ndef concat_two_elemwise(x: T.Buffer[(16,), \"float32\"],\n                        y: T.Buffer[(8,), \"float32\"],\n                        T_concat: T.Buffer[(24,), \"float32\"]) -> None:\n    T_add_1 = T.alloc_buffer([16], dtype=\"float32\")\n    T_add_2 = T.alloc_buffer([8], dtype=\"float32\")\n    for i in T.serial(16):\n        with T.block(\"T_add_1\"):\n            ax = T.axis.spatial(16, i)\n            T_add_1[ax] = x[ax] + T.float32(1)\n    for i in T.serial(8):\n        with T.block(\"T_add_2\"):\n            ax = T.axis.spatial(8, i)\n            T_add_2[ax] = y[ax] + T.float32(2)\n    for i in T.serial(24):\n        with T.block(\"T_concat\"):\n            ax = T.axis.spatial(24, i)\n            T_concat[ax] = T.if_then_else(16 <= ax, T_add_2[ax - 16], T_add_1[ax], dtype=\"float32\")\n\n@T.prim_func\ndef concat_two_elemwise_after_compute_at(x: T.Buffer[(16,), \"float32\"],\n                                         y: T.Buffer[(8,), \"float32\"],\n                                         T_concat: T.Buffer[(24,), \"float32\"]) -> None:\n    T_add_1 = T.alloc_buffer([16], dtype=\"float32\")\n    T_add_2 = T.alloc_buffer([8], dtype=\"float32\")\n    for i in T.serial(24):\n        with T.block(\"T_add_1\"):\n            ax = T.axis.spatial(16, i)\n            T.where(i < 16)\n            T_add_1[ax] = x[ax] + T.float32(1)\n        with T.block(\"T_add_2\"):\n            ax = T.axis.spatial(8, i - 16)\n            T.where(16 <= i)\n            T_add_2[ax] = y[ax] + T.float32(2)\n        with T.block(\"T_concat\"):\n            ax = T.axis.spatial(24, i)\n            T_concat[ax] = T.if_then_else(16 <= ax, T_add_2[ax - 16], T_add_1[ax], dtype=\"float32\")\n\n@T.prim_func\ndef floordiv_and_floormod_indices(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [16, 16])\n    Y = T.match_buffer(b, [256])\n    temp = T.alloc_buffer([16, 16])\n    for i, j in T.grid(16, 16):\n        with T.block(\"A\"):\n            v_i, v_j = T.axis.remap(\"SS\", [i, j])\n            temp[v_i, v_j] = X[v_j, v_i] + 1.0\n    for i in T.serial(0, 256):\n        with T.block(\"B\"):\n            v_i = T.axis.remap(\"S\", [i])\n            Y[v_i] = temp[v_i // 16, v_i % 16]\n\n@T.prim_func\ndef floordiv_and_floormod_indices_after_reverse_compute_at(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [16, 16], dtype=\"float32\")\n    Y = T.match_buffer(b, [256], dtype=\"float32\")\n    temp = T.alloc_buffer([16, 16], dtype=\"float32\")\n    for i in T.serial(0, 16):\n        for j in T.serial(0, 16):\n            with T.block(\"A\"):\n                v_i, v_j = T.axis.remap(\"SS\", [i, j])\n                temp[v_i, v_j] = X[v_j, v_i] + T.float32(1)\n        for ax0 in T.serial(0, 16):\n            with T.block(\"B\"):\n                v_i = T.axis.spatial(256, i * 16 + ax0)\n                Y[v_i] = temp[v_i // 16, v_i % 16]\n\n\n@T.prim_func\ndef tiled_repeat_op(x: T.Buffer[(4,), \"float32\"], T_repeat: T.Buffer[(64,), \"float32\"]) -> None:\n    T_add = T.alloc_buffer([4], dtype=\"float32\")\n    for i0 in T.serial(4):\n        with T.block(\"T_add\"):\n            ax0 = T.axis.spatial(4, i0)\n            T_add[ax0] = x[ax0] + 1.0\n    for i0_0, i0_1 in T.grid(8, 8):\n        with T.block(\"T_repeat\"):\n            ax0 = T.axis.spatial(64, i0_0 * 8 + i0_1)\n            T_repeat[ax0] = T_add[ax0 // 16]\n\n@T.prim_func\ndef tiled_repeat_op_after_compute_at(x: T.Buffer[(4,), \"float32\"], T_repeat: T.Buffer[(64,), \"float32\"]) -> None:\n    T_add = T.alloc_buffer([4], dtype=\"float32\")\n    for i0_0 in T.serial(8):\n        with T.block(\"T_add\"):\n            ax0 = T.axis.spatial(4, i0_0 // 2)\n            T_add[ax0] = x[ax0] + T.float32(1)\n        for i0_1 in T.serial(8):\n            with T.block(\"T_repeat\"):\n                ax0 = T.axis.spatial(64, i0_0 * 8 + i0_1)\n                T_repeat[ax0] = T_add[ax0 // 16]\n\n@T.prim_func\ndef static_bound(A: T.Buffer[(32, 1), \"float32\"], C: T.Buffer[(32, 1), \"float32\"]) -> None:\n    B = T.alloc_buffer((32, 1), \"float32\")\n    for i, j in T.grid(32, 1):\n        with T.block(\"B\"):\n            vi = T.axis.spatial(32, i)\n            vj = T.axis.spatial(1, j)\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(32, 32):\n        with T.block(\"C\"):\n            vi = T.axis.spatial(32, i)\n            vj = T.axis.spatial(1, j)\n            T.where(j < 1)\n            C[vi, vj] = B[vi, vj] + 1.0\n\n@T.prim_func\ndef static_bound_after_compute_at(A: T.Buffer[(32, 1), \"float32\"], C: T.Buffer[(32, 1), \"float32\"]) -> None:\n    B = T.alloc_buffer((32, 1), \"float32\")\n    for i in range(32):\n        for ax0, ax1 in T.grid(1, 1):\n            with T.block(\"B\"):\n                vi = T.axis.spatial(32, i + ax0)\n                vj = T.axis.spatial(1, ax1)\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j in range(32):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(32, i)\n                vj = T.axis.spatial(1, j)\n                T.where(j < 1)\n                C[vi, vj] = B[vi, vj] + 1.0\n# pylint: enable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n# fmt: on\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_compute_at_two_elementwise(use_block_name):\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    loop, _ = sch.get_loops(\"C\" if use_block_name else sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(two_elementwise_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise)\n\n\ndef test_compute_at_blockized_1(use_block_name):\n    sch = tir.Schedule(blockized_1, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    _, loop = sch.get_loops(sch.get_block(\"C_outer\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(blockized_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=blockized_1)\n\n\ndef test_compute_at_blockized_2(use_block_name):\n    sch = tir.Schedule(blockized_2, debug_mask=\"all\")\n    block = sch.get_block(\"B_outer\")\n    _, loop, _, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(blockized_2_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=blockized_2)\n\n\ndef test_compute_at_cuda_matmul_0(use_block_name):\n    sch = tir.Schedule(cuda_matmul_0, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    _, _, _, _, _, loop, _, _ = sch.get_loops(sch.get_block(\"C_local\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(cuda_matmul_0_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=cuda_matmul_0)\n\n\ndef test_compute_at_cuda_matmul_1(use_block_name):\n    sch = tir.Schedule(cuda_matmul_1, debug_mask=\"all\")\n    block = sch.get_block(\"A_shared_local\")\n    _, _, _, _, _, _, _, loop, _, _, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(cuda_matmul_2, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=cuda_matmul_1)\n\n\ndef test_compute_at_cuda_matmul_2(use_block_name):\n    sch = tir.Schedule(cuda_matmul_2, debug_mask=\"all\")\n    block = sch.get_block(\"B_shared_local\")\n    _, _, _, _, _, _, _, loop, _, _, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(cuda_matmul_3, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=cuda_matmul_2)\n\n\ndef test_compute_at_cuda_matmul_3(use_block_name):\n    sch = tir.Schedule(cuda_matmul_3, debug_mask=\"all\")\n    block = sch.get_block(\"A_shared\")\n    _, _, _, _, _, _, loop, _, _, _, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(cuda_matmul_4, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=cuda_matmul_3)\n\n\ndef test_compute_at_cuda_matmul_4(use_block_name):\n    sch = tir.Schedule(cuda_matmul_4, debug_mask=\"all\")\n    block = sch.get_block(\"B_shared\")\n    _, _, _, _, _, _, loop, _, _, _, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(cuda_matmul_5, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=cuda_matmul_4)\n\n\ndef test_compute_at_reduction_block(use_block_name):\n    sch = tir.Schedule(multi_reduction, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    (loop,) = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=False)\n    tvm.ir.assert_structural_equal(multi_reduction_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=multi_reduction)\n\n\ndef test_compute_at_tiled_pooling_read_cache(use_block_name):\n    sch = tir.Schedule(tiled_pooling_read_cache, debug_mask=\"all\")\n    compute = sch.get_block(\"compute\")\n    _, w_o, _, _, _, _ = sch.get_loops(compute)\n    cache = sch.get_block(\"cache\")\n    sch.compute_at(cache, w_o)\n    tvm.ir.assert_structural_equal(tiled_pooling_read_cache_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=tiled_pooling_read_cache)\n\n\ndef test_compute_at_non_uniform_tiled_conv(use_block_name):\n    sch = tir.Schedule(non_uniform_tiled_conv, debug_mask=\"all\")\n    compute = sch.get_block(\"compute\")\n    sch.compute_at(sch.get_block(\"cache\"), sch.get_loops(compute)[1])\n    tvm.ir.assert_structural_equal(non_uniform_tiled_conv_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=non_uniform_tiled_conv)\n\n\ndef test_compute_at_concat(use_block_name):\n    sch = tir.Schedule(concat_two_elemwise, debug_mask=\"all\")\n    concat = sch.get_block(\"T_concat\")\n    add1 = sch.get_block(\"T_add_1\")\n    add2 = sch.get_block(\"T_add_2\")\n    axis = sch.get_loops(concat)[0]\n    sch.compute_at(add1, axis)\n    sch.compute_at(add2, axis)\n    tvm.ir.assert_structural_equal(concat_two_elemwise_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=concat_two_elemwise)\n\n\ndef test_compute_at_tiled_repeat_op(use_block_name):\n    sch = tir.Schedule(tiled_repeat_op, debug_mask=\"all\")\n    outer_ax, _ = sch.get_loops(sch.get_block(\"T_repeat\"))\n    sch.compute_at(sch.get_block(\"T_add\"), outer_ax)\n    tvm.ir.assert_structural_equal(tiled_repeat_op_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=tiled_repeat_op)\n\n\ndef test_reverse_compute_at_tiled(use_block_name):\n    sch = tir.Schedule(tiled, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    _, _, loop, _ = sch.get_loops(sch.get_block(\"B\"))\n    sch.reverse_compute_at(block, loop, preserve_unit_loops=False)\n    tvm.ir.assert_structural_equal(tiled_after_reverse_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=tiled)\n\n\ndef test_reverse_compute_at_tiled_trivial_binding(use_block_name):\n    sch = tir.Schedule(tiled_trivial_binding, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    _, _, loop, _ = sch.get_loops(sch.get_block(\"B\"))\n    sch.reverse_compute_at(block, loop, preserve_unit_loops=False)\n    tvm.ir.assert_structural_equal(tiled_trivial_binding_after_reverse_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=tiled_trivial_binding)\n\n\ndef test_reverse_compute_at_blockized_2(use_block_name):\n    sch = tir.Schedule(blockized_2, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    _, loop = sch.get_loops(sch.get_block(\"B_outer\"))\n    sch.reverse_compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(blockized_2_after_reverse_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=blockized_2)\n\n\ndef test_reverse_compute_at_factorized(use_block_name):\n    sch = tir.Schedule(factorized, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    _, loop, _, _ = sch.get_loops(sch.get_block(\"B_rf\"))\n    sch.reverse_compute_at(block, loop, preserve_unit_loops=False)\n    tvm.ir.assert_structural_equal(factorized_after_reverse_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=factorized)\n\n\ndef test_reverse_compute_at_floordiv_and_floormod_indices(use_block_name):\n    sch = tir.Schedule(floordiv_and_floormod_indices, debug_mask=\"all\")\n    A = sch.get_block(\"A\")\n    B = sch.get_block(\"B\")\n    sch.reverse_compute_at(B, sch.get_loops(A)[0])\n    tvm.ir.assert_structural_equal(\n        floordiv_and_floormod_indices_after_reverse_compute_at, sch.mod[\"main\"]\n    )\n    verify_trace_roundtrip(sch=sch, mod=floordiv_and_floormod_indices)\n\n\ndef test_read_out_of_bound(use_block_name):\n    sch = tir.Schedule(read_out_of_bound, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    (loop,) = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop)\n    tvm.ir.assert_structural_equal(read_out_of_bound_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=read_out_of_bound)\n\n\ndef test_compact_dataflow(use_block_name):\n    sch = tir.Schedule(not_all_compact_data_flow, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    _, loop = sch.get_loops(sch.get_block(\"C_1\"))\n    sch.compute_at(block, loop)\n    tvm.ir.assert_structural_equal(not_all_compact_data_flow_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=not_all_compact_data_flow)\n\n\ndef test_compute_at_simplify_static_bound(use_block_name):\n    sch = tir.Schedule(static_bound, debug_mask=\"all\")\n    block = sch.get_block(\"B\")\n    loop, _ = sch.get_loops(sch.get_block(\"C\"))\n    sch.compute_at(block, loop, preserve_unit_loops=True)\n    tvm.ir.assert_structural_equal(static_bound_after_compute_at, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=static_bound)\n\n\ndef test_compute_at_non_perfect_channel_group(use_block_name):\n    @T.prim_func\n    def grouped_channel_bias(\n        X: T.Buffer[(720, 8, 8), \"float32\"], Y: T.Buffer[(720, 8, 8), \"float32\"]\n    ):\n        B = T.alloc_buffer([45], dtype=\"float32\", scope=\"\")\n        for i in T.grid(45):\n            with T.block(\"init\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = vi\n        for c_o, h, w, c_i in T.grid(2, 8, 8, 360):\n            with T.block(\"compute\"):\n                hh, ww = T.axis.remap(\"SS\", [h, w])\n                cc = T.axis.spatial(720, c_o * 360 + c_i)\n                Y[cc, hh, ww] = X[cc, hh, ww] + B[cc // 16]\n\n    @T.prim_func\n    def grouped_channel_bias_non_perfect_tiled(\n        X: T.Buffer[(720, 8, 8), \"float32\"], Y: T.Buffer[(720, 8, 8), \"float32\"]\n    ):\n        B = T.alloc_buffer([45], dtype=\"float32\")\n        for c_o in range(2):\n            for ax0 in range(23):\n                with T.block(\"init\"):\n                    vi = T.axis.spatial(45, c_o * 22 + ax0)\n                    B[vi] = vi\n            for h, w, c_i in T.grid(8, 8, 360):\n                with T.block(\"compute\"):\n                    hh, ww = T.axis.remap(\"SS\", [h, w])\n                    cc = T.axis.spatial(720, c_o * 360 + c_i)\n                    Y[cc, hh, ww] = X[cc, hh, ww] + B[cc // 16]\n\n    sch = tir.Schedule(grouped_channel_bias, debug_mask=\"all\")\n    loop = sch.get_loops(sch.get_block(\"compute\"))[0]\n    sch.compute_at(sch.get_block(\"init\"), loop)\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], grouped_channel_bias_non_perfect_tiled)\n\n\ndef test_fail_subtree_complete_block(use_block_name):\n    sch = tir.Schedule(fail_subtree_compact_dataflow, debug_mask=\"all\")\n    block = sch.get_block(\"B_0\")\n    loop, _ = sch.get_loops(sch.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"complete block\"):\n        sch.compute_at(block, loop)\n\n\ndef test_fail_not_in_same_scope(use_block_name):\n    sch = tir.Schedule(blockized_1, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    loop, _ = sch.get_loops(sch.get_block(\"C_inner\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"same block scope\"):\n        sch.compute_at(block, loop)\n\n\ndef test_fail_loop_is_ancestor_of_block(use_block_name):\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    loop, _ = sch.get_loops(sch.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"ancestor of block\"):\n        sch.compute_at(block, loop)\n\n\ndef test_fail_output_block(use_block_name):\n    sch = tir.Schedule(tiled, debug_mask=\"all\")\n    block = \"C\" if use_block_name else sch.get_block(\"C\")\n    loop, _, _, _ = sch.get_loops(sch.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"output block\"):\n        sch.compute_at(block, loop)\n\n\ndef test_fail_all_consumers_under_loop(use_block_name):\n    sch = tir.Schedule(fail_all_consumers_under_loop, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    loop, _ = sch.get_loops(sch.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"requires all the consumer\"):\n        sch.compute_at(block, loop)\n\n\ndef test_fail_all_producers_under_loop(use_block_name):\n    sch = tir.Schedule(fail_all_producers_under_loop, debug_mask=\"all\")\n    block = \"D\" if use_block_name else sch.get_block(\"D\")\n    loop, _ = sch.get_loops(sch.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError, match=\"requires all the producer\"):\n        sch.reverse_compute_at(block, loop)\n\n\ndef test_compute_at_int64_loop(use_block_name):\n    def _create_prim_func():\n        n = te.var(\"n\", dtype=\"int64\")\n        m = te.var(\"m\", dtype=\"int64\")\n        A = te.placeholder((n, m), name=\"A\", dtype=\"float32\")\n        B = te.placeholder((n, m), name=\"B\", dtype=\"float32\")\n        C = te.compute((n, m), lambda i, j: A[i, j] + B[i, j], name=\"C\")\n        D = te.compute((n, m), lambda i, j: C[i, j] + 1.0, name=\"D\")\n        return te.create_prim_func([A, B, D])\n\n    mod = _create_prim_func()\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    block_d = \"D\" if use_block_name else sch.get_block(\"D\")\n    i, _ = sch.get_loops(block_d)\n    sch.compute_at(block_c, i)\n    verify_trace_roundtrip(sch=sch, mod=mod)\n\n\ndef test_compute_at_to_index():\n    @T.prim_func\n    def multi_producers_conv(\n        data: T.Buffer[(1, 3, 224, 224), \"int8\"],\n        w: T.Buffer[(16, 3, 7, 7), \"int8\"],\n        conv: T.Buffer[(1, 16, 112, 112), \"int32\"],\n    ) -> None:\n        pad = T.alloc_buffer([1, 3, 230, 230], dtype=\"int8\")\n        wbuf = T.alloc_buffer([16, 3, 7, 7], dtype=\"int8\")\n        for i0, i1, i2, i3 in T.grid(1, 3, 230, 230):\n            with T.block(\"pad\"):\n                i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                T.reads(data[i0_1, i1_1, i2_1 - 3, i3_1 - 3])\n                T.writes(pad[i0_1, i1_1, i2_1, i3_1])\n                pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                    3 <= i2_1 and i2_1 < 227 and 3 <= i3_1 and i3_1 < 227,\n                    data[i0_1, i1_1, i2_1 - 3, i3_1 - 3],\n                    T.int8(0),\n                    dtype=\"int8\",\n                )\n        for i0 in T.serial(1):\n            for ax0, ax1, ax2, ax3 in T.grid(16, 3, 7, 7):\n                with T.block(\"wbuf\"):\n                    v0, v1, v2, v3 = T.axis.remap(\"SSSS\", [ax0, ax1, ax2, ax3])\n                    T.reads(w[v0, v1, v2, v3])\n                    T.writes(wbuf[v0, v1, v2, v3])\n                    wbuf[v0, v1, v2, v3] = w[v0, v1, v2, v3]\n            for i1, i2, i3, i4, i5, i6 in T.grid(16, 112, 112, 3, 7, 7):\n                with T.block(\"conv\"):\n                    nn, ff, yy, xx, rc, ry, rx = T.axis.remap(\n                        \"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6]\n                    )\n                    T.reads(pad[nn, rc, yy * 2 + ry, xx * 2 + rx], wbuf[ff, rc, ry, rx])\n                    T.writes(conv[nn, ff, yy, xx])\n                    with T.init():\n                        conv[nn, ff, yy, xx] = 0\n                    conv[nn, ff, yy, xx] = conv[nn, ff, yy, xx] + T.cast(\n                        pad[nn, rc, yy * 2 + ry, xx * 2 + rx], \"int32\"\n                    ) * T.cast(wbuf[ff, rc, ry, rx], \"int32\")\n\n    @T.prim_func\n    def multi_producers_after_compute_at(\n        data: T.Buffer[(1, 3, 224, 224), \"int8\"],\n        w: T.Buffer[(16, 3, 7, 7), \"int8\"],\n        conv: T.Buffer[(1, 16, 112, 112), \"int32\"],\n    ) -> None:\n        pad = T.alloc_buffer([1, 3, 230, 230], dtype=\"int8\")\n        wbuf = T.alloc_buffer([16, 3, 7, 7], dtype=\"int8\")\n        for i0 in T.serial(1):\n            for ax0, ax1, ax2 in T.grid(3, 229, 229):\n                with T.block(\"pad\"):\n                    i0_1 = T.axis.spatial(1, 0)\n                    i1_1 = T.axis.spatial(3, ax0)\n                    i2_1 = T.axis.spatial(230, ax1)\n                    i3_1 = T.axis.spatial(230, ax2)\n                    T.reads(data[i0_1, i1_1, i2_1 - 3, i3_1 - 3])\n                    T.writes(pad[i0_1, i1_1, i2_1, i3_1])\n                    pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                        3 <= i2_1 and i2_1 < 227 and 3 <= i3_1 and i3_1 < 227,\n                        data[i0_1, i1_1, i2_1 - 3, i3_1 - 3],\n                        T.int8(0),\n                        dtype=\"int8\",\n                    )\n            for ax0, ax1, ax2, ax3 in T.grid(16, 3, 7, 7):\n                with T.block(\"wbuf\"):\n                    v0, v1, v2, v3 = T.axis.remap(\"SSSS\", [ax0, ax1, ax2, ax3])\n                    T.reads(w[v0, v1, v2, v3])\n                    T.writes(wbuf[v0, v1, v2, v3])\n                    wbuf[v0, v1, v2, v3] = w[v0, v1, v2, v3]\n            for i1, i2, i3, i4, i5, i6 in T.grid(16, 112, 112, 3, 7, 7):\n                with T.block(\"conv\"):\n                    nn, ff, yy, xx, rc, ry, rx = T.axis.remap(\n                        \"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6]\n                    )\n                    T.reads(pad[nn, rc, yy * 2 + ry, xx * 2 + rx], wbuf[ff, rc, ry, rx])\n                    T.writes(conv[nn, ff, yy, xx])\n                    with T.init():\n                        conv[nn, ff, yy, xx] = 0\n                    conv[nn, ff, yy, xx] = conv[nn, ff, yy, xx] + T.cast(\n                        pad[nn, rc, yy * 2 + ry, xx * 2 + rx], \"int32\"\n                    ) * T.cast(wbuf[ff, rc, ry, rx], \"int32\")\n\n    sch = tir.Schedule(multi_producers_conv, debug_mask=\"all\")\n    block_c = sch.get_block(\"pad\")\n    axis = sch.get_loops(\"conv\")[0]\n    sch.compute_at(block_c, axis, index=-2)\n    tvm.ir.assert_structural_equal(multi_producers_after_compute_at, sch.mod[\"main\"])\n\n\ndef test_reverse_compute_at_to_index():\n    @T.prim_func\n    def main(A: T.Buffer[(128, 128), \"float32\"], D: T.Buffer[(128, 128), \"float32\"]) -> None:\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        C = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i_0, j_0, i_1 in T.grid(8, 8, 16):\n            for j_1 in T.serial(16):\n                with T.block(\"B\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                    vj = T.axis.spatial(128, j_0 * 16 + j_1)\n                    T.reads(A[vi, vj])\n                    T.writes(B[vi, vj])\n                    B[vi, vj] = A[vi, vj] * T.float32(2)\n            for ax0 in T.serial(16):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                    vj = T.axis.spatial(128, j_0 * 16 + ax0)\n                    T.reads(B[vi, vj])\n                    T.writes(C[vi, vj])\n                    C[vi, vj] = B[vi, vj] + T.float32(1)\n        for i, j in T.grid(128, 128):\n            with T.block(\"D\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(B[vi, vj])\n                T.writes(D[vi, vj])\n                D[vi, vj] = B[vi, vj] + T.float32(1)\n\n    @T.prim_func\n    def main_reverse_compute_at(\n        A: T.Buffer[(128, 128), \"float32\"], D: T.Buffer[(128, 128), \"float32\"]\n    ) -> None:\n        B = T.alloc_buffer([128, 128], dtype=\"float32\")\n        C = T.alloc_buffer([128, 128], dtype=\"float32\")\n        for i_0, j_0, i_1 in T.grid(8, 8, 16):\n            for j_1 in T.serial(16):\n                with T.block(\"B\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                    vj = T.axis.spatial(128, j_0 * 16 + j_1)\n                    T.reads(A[vi, vj])\n                    T.writes(B[vi, vj])\n                    B[vi, vj] = A[vi, vj] * T.float32(2)\n            for ax0 in T.serial(16):\n                with T.block(\"D\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                    vj = T.axis.spatial(128, j_0 * 16 + ax0)\n                    T.reads(B[vi, vj])\n                    T.writes(D[vi, vj])\n                    D[vi, vj] = B[vi, vj] + T.float32(1)\n            for ax0 in T.serial(16):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(128, i_0 * 16 + i_1)\n                    vj = T.axis.spatial(128, j_0 * 16 + ax0)\n                    T.reads(B[vi, vj])\n                    T.writes(C[vi, vj])\n                    C[vi, vj] = B[vi, vj] + T.float32(1)\n\n    sch = tir.Schedule(main, debug_mask=\"all\")\n    block_c = sch.get_block(\"D\")\n    axis = sch.get_loops(\"B\")[2]\n    sch.reverse_compute_at(block_c, axis, index=1)\n    tvm.ir.assert_structural_equal(main_reverse_compute_at, sch.mod[\"main\"])\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_compute_inline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_multi_producer_consumer(a: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    D = T.match_buffer(d, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0  # B has two consumers\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = B[vi, vj] + 2.0 + C[vi, vj]  # D has two producers\n\n\n@T.prim_func\ndef elementwise_multi_consumer_inlined(a: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    D = T.match_buffer(d, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = A[vi, vj] * 2.0 + 2.0 + C[vi, vj]\n\n\n@T.prim_func\ndef elementwise_standalone(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_standalone_dce(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_under_loop(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    for i in T.serial(0, 128):\n        for j in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j in T.serial(0, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n\n@T.prim_func\ndef fail_multi_reader_writer(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.alloc_buffer((128, 128))\n    D = T.match_buffer(d, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n            C[vi, vj] = A[vi, vj] + 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = B[vi, vj] + C[vi, vj]\n\n\n@T.prim_func\ndef elementwise_multi_reverse_loads(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = (B[vi, vj] + 1.0) * (B[vi, vj] * 2.0) + 3.0\n\n\n@T.prim_func\ndef elementwise_multi_reverse_loads_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = (A[vi, vj] * 2.0 + 1.0) * (A[vi, vj] * 2.0 * 2.0) + 3.0\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(8, 32, 8, 8), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k, l in T.grid(8, 32, 8, 8):\n        with T.block(\"C\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            C[vi, vj, vk, vl] = B[\n                ((((vi * 32) + vj) * 8 + vk) * 8 + vl) // 128,\n                ((((vi * 32) + vj) * 8 + vk) * 8 + vl) % 128,\n            ]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load_inlined(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(8, 32, 8, 8), \"float32\"]\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[\n                (vj + vi * 128) // 2048,\n                (vj + vi * 128) // 64 % 32,\n                ((vj + vi * 128) // 8) % 8,\n                (vj + vi * 128) % 8,\n            ] = (\n                A[vi, vj] * 2.0\n            )\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load_unit_iter(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(8, 16, 1), \"float32\"],\n    D: T.Buffer[(1, 8, 16, 128), \"float32\"],\n) -> None:\n    C = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k, l in T.grid(1, 8, 16, 128):\n        with T.block(\"C\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            D[vi, vj, vk, vl] = C[vj * 16 + vk, vl] + B[vj, vk, vi]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load_unit_iter_inlined(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(8, 16, 1), \"float32\"],\n    D: T.Buffer[(1, 8, 16, 128), \"float32\"],\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[0, vi // 16, vi % 16, vj] = A[vi, vj] * 2.0 + B[vi // 16, vi % 16, 0]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load_unit_iter_simplified(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(8, 16, 1), \"float32\"],\n    D: T.Buffer[(1, 8, 16, 128), \"float32\"],\n) -> None:\n    C = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k in T.grid(8, 16, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            D[0, vi, vj, vk] = C[vi * 16 + vj, vk] + B[vi, vj, 0]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_load_unit_iter_simplified_inlined(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(8, 16, 1), \"float32\"],\n    D: T.Buffer[(1, 8, 16, 128), \"float32\"],\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[0, vi // 16, vi % 16, vj] = A[vi, vj] * 2.0 + B[vi // 16, vi % 16, 0]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_chain(\n    A: T.Buffer[(128, 128), \"float32\"], D: T.Buffer[(1, 8, 16, 128), \"float32\"]\n):\n    B = T.alloc_buffer((128, 128))\n    C = T.alloc_buffer((8, 16, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k in T.grid(8, 16, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            C[vi, vj, vk] = B[vi * 16 + vj, vk] + 1.0\n    for i, j, k, l in T.grid(1, 8, 16, 128):\n        with T.block(\"D\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            D[vi, vj, vk, vl] = C[vj, vk, vl]\n\n\n@T.prim_func\ndef elementwise_reverse_affine_chain_inlined(\n    A: T.Buffer[(128, 128), \"float32\"], D: T.Buffer[(1, 8, 16, 128), \"float32\"]\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[0, vi // 16, vi % 16, vj] = A[vi, vj] * 2.0 + 1.0\n\n\n@T.prim_func\ndef elementwise_multi_reverse_affine_load(\n    A: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(8, 16, 128), \"float32\"],\n) -> None:\n    B = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k in T.grid(8, 16, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            C[vi, vj, vk] = B[vi * 16 + vj, vk] + B[vi * 16 + vj, vk]\n\n\n@T.prim_func\ndef elementwise_multi_reverse_affine_load_inlined(\n    A: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(8, 16, 128), \"float32\"],\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi // 16, vi % 16, vj] = A[vi, vj] * 2.0 + A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef elementwise_reverse_non_affine_load(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(8, 16, 128), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j, k in T.grid(8, 16, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            C[vi, vj, vk] = B[vi * 16 + vj, vi * 16 + vj]\n\n\n@T.prim_func\ndef opaque_access_load(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(B[0:128, 0:128])\n            T.writes(C[0:128, 0:128])\n            T.evaluate(B.access_ptr(\"r\", extent=128))\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef opaque_access_store(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(B[0:128, 0:128])\n            T.writes(C[0:128, 0:128])\n            T.evaluate(B.access_ptr(\"r\", extent=128))\n            T.evaluate(C.access_ptr(\"w\", extent=128))\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef buffer_matched(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            Bb = T.match_buffer(B[vi : vi + 1, vj], (1, 1))\n            C[vi, vj] = Bb[0, 0] + 1.0\n\n\n@T.prim_func\ndef elementwise_predicate(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.where(B[i, j] < 10.0)\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_predicate_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.where(A[i, j] * 2.0 < 10.0)\n            C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n\n@T.prim_func\ndef elementwise_multi_loads(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + B[vi, vj + 1] + B[vi, vj + 2]\n\n\n@T.prim_func\ndef elementwise_multi_loads_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0 + A[vi, vj + 1] * 2.0 + A[vi, vj + 2] * 2.0\n\n\n@T.prim_func\ndef access_opaque_ptr_then_elemwise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [1024])\n    B = T.match_buffer(b, [1024])\n    A_cache = T.alloc_buffer([1024])\n    BB = T.alloc_buffer([1024])\n    with T.block(\"opaque\"):\n        # annotated opaque partial access\n        T.reads(A[0:512])\n        T.writes(A_cache[0:512])\n        T.evaluate(A.access_ptr(\"r\", extent=512))\n        T.evaluate(A_cache.access_ptr(\"w\", extent=512))\n    for i in range(512):\n        with T.block(\"BB\"):\n            vi = T.axis.remap(\"S\", [i])\n            BB[vi] = A_cache[vi] * 2.0\n    for i in range(512):\n        with T.block(\"B\"):\n            vi = T.axis.remap(\"S\", [i])\n            B[vi] = BB[vi] + 1.0\n\n\n@T.prim_func\ndef access_opaque_ptr_then_elemwise_inline(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [1024], dtype=\"float32\")\n    B = T.match_buffer(b, [1024], dtype=\"float32\")\n    A_cache = T.alloc_buffer([1024], dtype=\"float32\")\n    with T.block(\"opaque\"):\n        # annotated opaque partial access should be kept\n        T.reads(A[0:512])\n        T.writes([A_cache[0:512]])\n        T.evaluate(A.access_ptr(\"r\", extent=512))\n        T.evaluate(A_cache.access_ptr(\"w\", extent=512))\n    for i in T.serial(0, 512):\n        with T.block(\"B\"):\n            vi = T.axis.spatial(512, i)\n            T.reads([A_cache[vi]])\n            T.writes([B[vi]])\n            B[vi] = A_cache[vi] * 2.0 + 1.0\n\n\n@T.prim_func\ndef matmul_relu(var_A: T.handle, var_B: T.handle, var_compute: T.handle) -> None:\n    A = T.match_buffer(var_A, [512, 512], dtype=\"float32\")\n    B = T.match_buffer(var_B, [512, 512], dtype=\"float32\")\n    compute = T.match_buffer(var_compute, [512, 512], dtype=\"float32\")\n    C = T.alloc_buffer([512, 512], dtype=\"float32\")\n    for i0, i1, i2 in T.grid(512, 512, 512):\n        with T.block(\"C\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads([C[i, j], A[i, k], B[k, j]])\n            T.writes([C[i, j]])\n            with T.init():\n                C[i, j] = T.float32(0)\n            C[i, j] = C[i, j] + A[i, k] * B[k, j]\n    for i0, i1 in T.grid(512, 512):\n        with T.block(\"compute\"):\n            i0_1, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n            T.reads([C[i0_1, i1_1]])\n            T.writes([compute[i0_1, i1_1]])\n            compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0))\n\n\n@T.prim_func\ndef inline_block_with_init(\n    A: T.Buffer[(1, 512, 7, 7), \"float32\"],\n    B: T.Buffer[(1, 512, 1, 1), \"float32\"],\n) -> None:\n    B_rf = T.alloc_buffer([1, 512, 1, 1, 49], dtype=\"float32\")\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 512, 1, 1, 49, 1):\n        with T.block(\"tensor_rf\"):\n            vi4 = T.axis.spatial(49, i4)\n            ax0 = T.axis.spatial(1, 0)\n            ax1 = T.axis.spatial(512, i1)\n            ax2 = T.axis.spatial(1, 0)\n            ax3 = T.axis.spatial(1, 0)\n            with T.init():\n                B_rf[ax0, ax1, ax2, ax3, vi4] = T.float32(0)\n            B_rf[ax0, ax1, ax2, ax3, vi4] = (\n                B_rf[ax0, ax1, ax2, ax3, vi4]\n                + A[\n                    ax0,\n                    ax1,\n                    ax2 * 7 + vi4 // 7,\n                    ax3 * 7 + vi4 % 7,\n                ]\n            )\n    for i0, i1 in T.grid(1, 512):\n        for ax0, ax1, ax2, ax3, ax4 in T.grid(49, 1, 1, 1, 1):\n            with T.block(\"tensor\"):\n                vi4, ax0_1 = T.axis.remap(\"RS\", [ax0, ax1])\n                ax1_1 = T.axis.spatial(512, i1 + ax2)\n                ax2_1, ax3_1 = T.axis.remap(\"SS\", [ax3, ax4])\n                with T.init():\n                    B[ax0_1, ax1_1, ax2_1, ax3_1] = T.float32(0)\n                B[ax0_1, ax1_1, ax2_1, ax3_1] = (\n                    B[ax0_1, ax1_1, ax2_1, ax3_1] + B_rf[ax0_1, ax1_1, ax2_1, ax3_1, vi4]\n                )\n\n\n@T.prim_func\ndef exp_exp_opaque_access_with_tvm_access_ptr(\n    lookup_table: T.Buffer[(1024,), \"int8\"],\n    x: T.Buffer[(16,), \"float16\"],\n    compute: T.Buffer[(16,), \"float16\"],\n) -> None:\n    compute_1 = T.alloc_buffer([16], dtype=\"float16\")\n    for i0 in T.serial(16):\n        with T.block(\"compute\"):\n            i0_1 = T.axis.spatial(16, i0)\n            T.reads(x[i0_1])\n            T.writes(compute_1[i0_1])\n            compute_1[i0_1] = T.exp(x[i0_1], dtype=\"float16\")\n    for i0 in T.serial(16):\n        with T.block(\"compute_1\"):\n            i0_2 = T.axis.spatial(16, i0)\n            T.reads(lookup_table[0:1024], compute_1[i0_2])\n            T.writes(compute[i0_2])\n            T.evaluate(lookup_table.access_ptr(\"r\"))\n            compute[i0_2] = T.exp(\n                compute_1[i0_2],\n                dtype=\"float16\",\n            )\n\n\n@T.prim_func\ndef exp_exp_opaque_access_with_tvm_access_ptr_inlined(\n    lookup_table: T.Buffer[(1024,), \"int8\"],\n    x: T.Buffer[(16,), \"float16\"],\n    compute: T.Buffer[(16,), \"float16\"],\n) -> None:\n    for i0 in T.serial(16):\n        with T.block(\"compute_1\"):\n            i0_1 = T.axis.spatial(16, i0)\n            # Do not put the opaque access to new write region when opaque access\n            # wrapped with a tvm_access_ptr and the access mask set to \"read only\"\n            T.reads(lookup_table[0:1024], x[i0_1])\n            T.writes(compute[i0_1])\n            T.evaluate(lookup_table.access_ptr(\"r\"))\n            compute[i0_1] = T.exp(\n                T.exp(x[i0_1], dtype=\"float16\"),\n                dtype=\"float16\",\n            )\n\n\n@T.prim_func\ndef elementwise_overcomputed_producer(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(127, 127), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(127, 127):\n        with T.block(\"C\"):\n            cvi, cvj = T.axis.remap(\"SS\", [i, j])\n            C[cvi, cvj] = B[cvi, cvj] + 1.0\n\n\n@T.prim_func\ndef elementwise_overcomputed_producer_reverse_inlined(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(127, 127), \"float32\"]\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.where(i < 127 and j < 127)\n            C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n\n@T.prim_func\ndef elementwise_producer_not_cover_consumer(\n    A: T.Buffer[(128, 128), \"float32\"], D: T.Buffer[(256, 128), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(256, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = T.if_then_else(vi >= 128, B[vi - 128, vj], T.float32(0), dtype=\"float32\")\n\n\n@T.prim_func\ndef elementwise_predicate_producer(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((127, 128))\n    C = T.match_buffer(c, (127, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.where(i < 127)\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(127, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_predicate_producer_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (127, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            T.where(i < 127)\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads(A[vi, vj])\n            T.writes(C[vi, vj])\n            C[vi, vj] = A[vi, vj] * T.float32(2) + T.float32(1)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass Conv2dInt8_TensorCore_with_predicate:\n    @T.prim_func\n    def main(p0: T.Buffer[(16, 56, 56, 64), \"int8\"], p1: T.Buffer[(256, 1, 1, 64), \"int8\"], p2: T.Buffer[(1, 1, 1, 256), \"int32\"], p3: T.Buffer[(1, 1, 1, 256), \"int32\"], p4: T.Buffer[256, \"int32\"], p5: T.Buffer[256, \"int32\"], p6: T.Buffer[256, \"int32\"], p7: T.Buffer[(), \"int32\"], p8: T.Buffer[1, \"int32\"], p9: T.Buffer[(16, 56, 56, 256), \"int32\"], compute: T.Buffer[(16, 56, 56, 256), \"int32\"]):\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            T.block_attr({\"meta_schedule.unroll_explicit\":1024})\n            compute_3 = T.alloc_buffer([16, 56, 56, 256], dtype=\"int32\")\n            conv2d_nhwc_reindex_shared = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"shared\")\n            conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([50176, 256], dtype=\"int32\", scope=\"wmma.accumulator\")\n            pad_temp_reindex_shared = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"shared\")\n            p1_reindex_shared = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"shared\")\n            pad_temp_reindex_shared_wmma_matrix_a = T.alloc_buffer([50176, 64], dtype=\"int8\", scope=\"wmma.matrix_a\")\n            p1_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 256, 64], dtype=\"int8\", scope=\"wmma.matrix_b\")\n            for ax2_0_0_ax3_0_0_fused in T.thread_binding(32, thread=\"blockIdx.y\"):\n                for ax2_0_1_ax3_0_1_fused in T.thread_binding(196, thread=\"blockIdx.x\"):\n                    for ax2_0_2_ax3_0_2_fused in T.thread_binding(4, thread=\"threadIdx.y\"):\n                        for ax0_0, ax1_0, ax4_0_0 in T.grid(1, 1, 2):\n                            for ax0_ax1_fused in T.serial(1024):\n                                with T.block(\"pad_temp_reindex_shared\"):\n                                    v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0_ax1_fused // 32)\n                                    v1 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_fused % 32)\n                                    T.reads(p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                                    T.writes(pad_temp_reindex_shared[v0, v1])\n                                    T.block_attr({\"buffer_dim_align\":[[0, 0, 32, 16]], \"meta_schedule.cooperative_fetch\":4})\n                                    pad_temp_reindex_shared[v0, v1] = p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]\n                            for ax0_ax1_ax2_ax3_fused in T.serial(2048):\n                                with T.block(\"p1_reindex_shared\"):\n                                    v0 = T.axis.spatial(1, 0)\n                                    v1 = T.axis.spatial(1, 0)\n                                    v2 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + ax0_ax1_ax2_ax3_fused // 32)\n                                    v3 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_ax2_ax3_fused % 32)\n                                    T.reads(p1[v2, v0, v1, v3])\n                                    T.writes(p1_reindex_shared[v0, v1, v2, v3])\n                                    T.block_attr({\"buffer_dim_align\":[[0, 2, 32, 16]], \"meta_schedule.cooperative_fetch\":3})\n                                    p1_reindex_shared[v0, v1, v2, v3] = p1[v2, v0, v1, v3]\n                            for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 2):\n                                for ax0_0_1, ax1_0_1 in T.grid(1, 1):\n                                    with T.block(\"pad_temp_reindex_shared_wmma.matrix_a_o\"):\n                                        v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2)\n                                        v1_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1)\n                                        T.reads(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_s8_a\"})\n                                        for ax0_1_1, ax1_1_1 in T.grid(16, 16):\n                                            with T.block(\"pad_temp_reindex_shared_wmma.matrix_a\"):\n                                                v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1_1, ax1_1_1])\n                                                T.reads(pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                                T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                                pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                                for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 2, 1):\n                                    with T.block(\"p1_reindex_shared_wmma.matrix_b_o\"):\n                                        v0 = T.axis.spatial(1, 0)\n                                        v1 = T.axis.spatial(1, 0)\n                                        v2_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax2_0)\n                                        v3_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1)\n                                        T.reads(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_load_16x16x16_s8_b_trans\"})\n                                        for ax2_1, ax3_1 in T.grid(16, 16):\n                                            with T.block(\"p1_reindex_shared_wmma.matrix_b\"):\n                                                v2_i, v3_i = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                                T.reads(p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] = p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]\n                                for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 1, 1, 2):\n                                    with T.block(\"conv2d_nhwc_o\"):\n                                        v0 = T.axis.reduce(1, 0)\n                                        v1 = T.axis.reduce(1, 0)\n                                        v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3 + ax2_0_4)\n                                        v3_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax3_0_3 * 2 + ax3_0_4)\n                                        v4_o = T.axis.reduce(4, ax4_0_0 * 2 + ax4_0_1 + ax4_0_2)\n                                        T.reads(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16])\n                                        T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16])\n                                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_s8s8s32_trans\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_s32\", \"meta_schedule.thread_extent_high_inclusive\":1024, \"meta_schedule.thread_extent_low_inclusive\":32, \"warp_execution\":1})\n                                        with T.init():\n                                            for ax2_1, ax3_1 in T.grid(16, 16):\n                                                with T.block(\"conv2d_nhwc_init\"):\n                                                    v2_i_init, v3_i_init = T.axis.remap(\"SS\", [ax2_1, ax3_1])\n                                                    T.reads()\n                                                    T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init])\n                                                    conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init] = 0\n                                        for ax2_1, ax3_1, ax4_1 in T.grid(16, 16, 16):\n                                            with T.block(\"conv2d_nhwc\"):\n                                                v2_i, v3_i, v4_i = T.axis.remap(\"SSR\", [ax2_1, ax3_1, ax4_1])\n                                                T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i], pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i])\n                                                T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i])\n                                                T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                                conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] + T.cast(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], \"int32\") * T.cast(p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i], \"int32\")\n                        for ax0_0, ax1_0 in T.grid(1, 2):\n                            with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator_o\"):\n                                v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2)\n                                v1_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax1_0)\n                                T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                                T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_store_16x16x16_s32_shared\"})\n                                for ax0_1, ax1_1 in T.grid(16, 16):\n                                    with T.block(\"conv2d_nhwc_reindex_shared_wmma.accumulator\"):\n                                        v0_i, v1_i = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                        T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                        T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                        conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]\n                    for ax0, ax1_0, ax1_1, ax1_2, ax1_3 in T.grid(32, 1, 4, 32, 2):\n                        with T.block(\"conv2d_nhwc_reindex_shared\"):\n                            T.where(((ax1_0 * 4 + ax1_1) * 32 + ax1_2) * 2 + ax1_3 < 64)\n                            v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0)\n                            v1 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + (ax1_0 * 256 + ax1_1 * 64 + ax1_2 * 2 + ax1_3))\n                            T.reads(p7[()], conv2d_nhwc_reindex_shared[v0, v1], p2[0, 0, 0, v1], p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], p8[0])\n                            T.writes(compute_3[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1])\n                            compute_3[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] = T.q_multiply_shift(T.max(T.min(p7[()] + T.q_multiply_shift_per_axis(conv2d_nhwc_reindex_shared[v0, v1] - p2[0, 0, 0, v1] + p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], 31, False, True, dtype=\"int32\"), 255), 0) - p8[0], 1457846997, 31, 0, dtype=\"int32\")\n            for i0_12, i1_12, i2_12, i3_12 in T.grid(16, 56, 56, 256):\n                with T.block(\"compute_4\"):\n                    i0_13, i1_13, i2_13, i3_13 = T.axis.remap(\"SSSS\", [i0_12, i1_12, i2_12, i3_12])\n                    T.reads(compute_3[i0_13, i1_13, i2_13, i3_13], p9[i0_13, i1_13, i2_13, i3_13])\n                    T.writes(compute[i0_13, i1_13, i2_13, i3_13])\n                    compute[i0_13, i1_13, i2_13, i3_13] = T.max(T.min(compute_3[i0_13, i1_13, i2_13, i3_13] + T.q_multiply_shift(p9[i0_13, i1_13, i2_13, i3_13], 2101000910, 31, 0, dtype=\"int32\"), 255), 0)\n# fmt: on\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_compute_inline_elementwise(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n    assert sch.get(block_c).name_hint == \"C\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_compute_inline_under_loop(use_block_name):\n    sch = tir.Schedule(elementwise_under_loop, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n    assert sch.get(block_c).name_hint == \"C\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise_under_loop)\n\n\ndef test_compute_inline_as_dce(use_block_name):\n    sch = tir.Schedule(elementwise_standalone, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_standalone_dce, sch.mod[\"main\"])\n    assert sch.get(block_c).name_hint == \"C\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise_standalone)\n\n\ndef test_compute_inline_multi_consumer(use_block_name):\n    sch = tir.Schedule(elementwise_multi_producer_consumer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    block_d = sch.get_block(\"D\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_multi_consumer_inlined, sch.mod[\"main\"])\n    assert sch.get(block_c).name_hint == \"C\"\n    assert sch.get(block_d).name_hint == \"D\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise_multi_producer_consumer)\n\n\ndef test_compute_inline_fail_multi_writer(use_block_name):\n    sch = tir.Schedule(fail_multi_reader_writer, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block_b)\n\n\ndef test_reverse_compute_inline_elementwise(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n    assert sch.get(block_b).name_hint == \"B\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_reverse_compute_inline_under_loop(use_block_name):\n    sch = tir.Schedule(elementwise_under_loop, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n    assert sch.get(block_b).name_hint == \"B\"\n    verify_trace_roundtrip(sch=sch, mod=elementwise_under_loop)\n\n\ndef test_reverse_compute_inline_fail_as_dce(use_block_name):\n    sch = tir.Schedule(elementwise_standalone, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(block_b)\n\n\ndef test_reverse_compute_inline_fail_multi_producer(use_block_name):\n    sch = tir.Schedule(elementwise_multi_producer_consumer, debug_mask=\"all\")\n    block_d = \"D\" if use_block_name else sch.get_block(\"D\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(block_d)\n\n\ndef test_reverse_compute_inline_fail_multi_reader(use_block_name):\n    sch = tir.Schedule(fail_multi_reader_writer, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(block_c)\n\n\ndef test_reverse_compute_multi_reverse_loads(use_block_name):\n    sch = tir.Schedule(elementwise_multi_reverse_loads, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(elementwise_multi_reverse_loads_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_multi_reverse_loads)\n\n\ndef test_reverse_compute_inline_affine_load(use_block_name):\n    sch = tir.Schedule(elementwise_reverse_affine_load, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(elementwise_reverse_affine_load_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_reverse_affine_load)\n\n\ndef test_reverse_compute_inline_multi_affine_load(use_block_name):\n    sch = tir.Schedule(elementwise_multi_reverse_affine_load, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(elementwise_multi_reverse_affine_load_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_multi_reverse_affine_load)\n\n\ndef test_reverse_compute_inline_affine_load_unit_iter(use_block_name):\n    sch = tir.Schedule(elementwise_reverse_affine_load_unit_iter, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(\n        elementwise_reverse_affine_load_unit_iter_inlined, sch.mod[\"main\"]\n    )\n    verify_trace_roundtrip(sch=sch, mod=elementwise_reverse_affine_load_unit_iter)\n\n\ndef test_reverse_compute_inline_affine_load_unit_iter_simplified(use_block_name):\n    sch = tir.Schedule(elementwise_reverse_affine_load_unit_iter_simplified, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(block_c)\n    tvm.ir.assert_structural_equal(\n        elementwise_reverse_affine_load_unit_iter_simplified_inlined, sch.mod[\"main\"]\n    )\n    verify_trace_roundtrip(sch=sch, mod=elementwise_reverse_affine_load_unit_iter_simplified)\n\n\n@pytest.mark.parametrize(\"reverse_order\", [True, False])\ndef test_reverse_compute_inline_affine_chain(use_block_name, reverse_order):\n    sch = tir.Schedule(elementwise_reverse_affine_chain, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    block_d = \"D\" if use_block_name else sch.get_block(\"D\")\n    if reverse_order:\n        sch.reverse_compute_inline(block_d)\n        sch.reverse_compute_inline(block_c)\n    else:\n        sch.reverse_compute_inline(block_c)\n        sch.reverse_compute_inline(block_d)\n    tvm.ir.assert_structural_equal(elementwise_reverse_affine_chain_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_reverse_affine_chain)\n\n\ndef test_reverse_compute_fail_non_affine_load(use_block_name):\n    sch = tir.Schedule(elementwise_reverse_non_affine_load, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(block_c)\n\n\ndef test_reverse_compute_fail_multi_reverse_loads(use_block_name):\n    sch = tir.Schedule(elementwise_multi_loads, debug_mask=\"all\")\n    block_c = \"C\" if use_block_name else sch.get_block(\"C\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(block_c)\n\n\ndef test_opaque_access_load(use_block_name):\n    sch = tir.Schedule(opaque_access_load, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block_b)\n\n\ndef test_opaque_access_store(use_block_name):\n    sch = tir.Schedule(opaque_access_store, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block_b)\n\n\ndef test_buffer_matched(use_block_name):\n    sch = tir.Schedule(buffer_matched, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block_b)\n\n\ndef test_output_block(use_block_name):\n    sch = tir.Schedule(matmul_relu, debug_mask=\"all\")\n    block = sch.get_block(\"compute\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block)\n\n\ndef test_compute_inline_predicate(use_block_name):\n    sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_predicate_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_predicate)\n\n\ndef test_compute_inline_multi_loads(use_block_name):\n    sch = tir.Schedule(elementwise_multi_loads, debug_mask=\"all\")\n    block_b = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.compute_inline(block_b)\n    tvm.ir.assert_structural_equal(elementwise_multi_loads_inlined, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_multi_loads)\n\n\ndef test_compute_inline_with_opaque_access(use_block_name):\n    \"\"\"Test not rewrite opaque reads/writes after irrelavant compute inline\"\"\"\n    sch = tir.Schedule(access_opaque_ptr_then_elemwise, debug_mask=\"all\")\n    BB = \"BB\" if use_block_name else sch.get_block(\"BB\")\n    sch.compute_inline(BB)\n    tvm.ir.assert_structural_equal(access_opaque_ptr_then_elemwise_inline, sch.mod[\"main\"])\n\n\ndef test_inline_block_with_init():\n    sch = tir.Schedule(inline_block_with_init, debug_mask=\"all\")\n    block = sch.get_block(name=\"tensor_rf\", func_name=\"main\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.compute_inline(block=block)\n\n\ndef test_compute_inline_opaque_access_with_tvm_access_ptr(use_block_name):\n    \"\"\"Test opaque access with tvm_access_ptr after compute inline\"\"\"\n    sch = tir.Schedule(exp_exp_opaque_access_with_tvm_access_ptr, debug_mask=\"all\")\n    compute = \"compute\" if use_block_name else sch.get_block(\"compute\")\n    sch.compute_inline(compute)\n    tvm.ir.assert_structural_equal(\n        exp_exp_opaque_access_with_tvm_access_ptr_inlined, sch.mod[\"main\"]\n    )\n\n\ndef test_reverse_compute_inline_overcomputed_producer(use_block_name):\n    \"\"\"Test reverse compute inline overcomputed producer\"\"\"\n    sch = tir.Schedule(elementwise_overcomputed_producer, debug_mask=\"all\")\n    compute = \"C\" if use_block_name else sch.get_block(\"C\")\n    sch.reverse_compute_inline(compute)\n    tvm.ir.assert_structural_equal(\n        elementwise_overcomputed_producer_reverse_inlined, sch.mod[\"main\"]\n    )\n\n\ndef test_reverse_compute_inline_error_producer_not_cover_consumer(use_block_name):\n    \"\"\"Test reverse compute inline failure when the inlined block iter domains are not covered by\n    its producer\n    \"\"\"\n    sch = tir.Schedule(elementwise_producer_not_cover_consumer, debug_mask=\"all\")\n    compute = \"C\" if use_block_name else sch.get_block(\"C\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reverse_compute_inline(compute)\n\n\ndef test_reverse_compute_inline_producer_predicate_allowed():\n    \"\"\"Test a case where reverse compute inline is allowed even though the producer has a\n    non-trivial predicate.\n    \"\"\"\n\n    sch = tir.Schedule(elementwise_predicate_producer, debug_mask=\"all\")\n    sch.reverse_compute_inline(sch.get_block(\"C\"))\n    tvm.ir.assert_structural_equal(elementwise_predicate_producer_inlined, sch.mod[\"main\"])\n\n\ndef test_reverse_compute_inline_producer_predicate_disallowed():\n    \"\"\"Test reverse compute inline failure when the producer has a non-trivial predicate that cannot be\n    implied by the synthesized predicate of the new inlined block.\n    \"\"\"\n\n    sch = tir.Schedule(Conv2dInt8_TensorCore_with_predicate, debug_mask=\"all\")\n\n    with pytest.raises(tvm.tir.ScheduleError) as e:\n        sch.reverse_compute_inline(sch.get_block(\"compute_4\"))\n\n    assert (\n        \"that cannot be implied by the synthesized predicate True of the new inlined block\"\n        in str(e)\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_decompose_padding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\ndef check_decompose_padding(origin, scheduled, expected, check_run=False):\n    tvm.ir.assert_structural_equal(scheduled, expected)\n    if check_run:\n        in_buffer = origin.buffer_map[origin.params[0]]\n        out_buffer = origin.buffer_map[origin.params[1]]\n        in_shape = [int(_) for _ in in_buffer.shape]\n        out_shape = [int(_) for _ in out_buffer.shape]\n        x = tvm.nd.array(np.random.uniform(0, 64, in_shape).astype(in_buffer.dtype))\n        y0 = tvm.nd.array(np.zeros(out_shape).astype(out_buffer.dtype))\n        y1 = tvm.nd.array(np.zeros(out_shape).astype(out_buffer.dtype))\n        f_origin = tvm.build(origin)\n        f_scheduled = tvm.build(scheduled)\n        f_origin(x, y0)\n        f_scheduled(x, y1)\n        tvm.testing.assert_allclose(y0.numpy(), y1.numpy())\n\n\ndef test_1d_decompose_padding():\n    @T.prim_func\n    def before_decompose(x: T.Buffer[128, \"int32\"], y: T.Buffer[140, \"int32\"]):\n        for i in range(140):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                y[vi] = T.if_then_else(vi >= 6 and vi < 134, x[vi - 6], 0, dtype=\"int32\")\n\n    @T.prim_func\n    def after_decompose(x: T.Buffer[128, \"int32\"], y: T.Buffer[140, \"int32\"]):\n        for i in T.serial(140):\n            with T.block(\"block_pad_const\"):\n                vi = T.axis.spatial(140, i)\n                T.reads()\n                T.writes(y[vi])\n                y[vi] = 0\n        for i in T.serial(128):\n            with T.block(\"block\"):\n                vi = T.axis.spatial(128, i)\n                T.reads(x[vi])\n                T.writes(y[vi + 6])\n                y[vi + 6] = x[vi]\n\n    sch = tir.Schedule(before_decompose, debug_mask=\"all\")\n    block = sch.get_block(\"block\")\n    sch.decompose_padding(block, sch.get_loops(block)[0])\n    check_decompose_padding(before_decompose, sch.mod[\"main\"], after_decompose, check_run=False)\n\n\n@T.prim_func\ndef sum_pool_2d(\n    x: T.Buffer[(1, 16, 225, 225), \"int8\"], tensor: T.Buffer[(1, 16, 225, 225), \"int8\"]\n):\n    pad_temp = T.alloc_buffer([1, 16, 231, 231], dtype=\"int8\")\n    for i0, i1, i2, i3 in T.grid(1, 16, 231, 231):\n        with T.block(\"pad_temp\"):\n            ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            pad_temp[ax0, ax1, ax2, ax3] = T.if_then_else(\n                3 <= ax2 and ax2 < 228 and 3 <= ax3 and ax3 < 228,\n                x[ax0, ax1, ax2 - 3, ax3 - 3],\n                T.int8(0),\n                dtype=\"int8\",\n            )\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 16, 225, 225, 7, 7):\n        with T.block(\"tensor\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                tensor[ax0, ax1, ax2, ax3] = T.int8(0)\n            tensor[ax0, ax1, ax2, ax3] = (\n                tensor[ax0, ax1, ax2, ax3] + pad_temp[ax0, ax1, ax2 + rv0, ax3 + rv1]\n            )\n\n\ndef test_decompose_hw_padding_direct():\n    \"\"\"Case 0. direct decompose\"\"\"\n\n    @T.prim_func\n    def pooling_decompose_0(\n        x: T.Buffer[(1, 16, 225, 225), \"int8\"], tensor: T.Buffer[(1, 16, 225, 225), \"int8\"]\n    ):\n        pad_temp = T.alloc_buffer([1, 16, 231, 231], dtype=\"int8\")\n        for i0, i1, i2, i3 in T.grid(1, 16, 231, 231):\n            with T.block(\"pad_temp_pad_const\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                pad_temp[ax0, ax1, ax2, ax3] = T.int8(0)\n        for i0, i1, i2, i3 in T.grid(1, 16, 225, 225):\n            with T.block(\"pad_temp\"):\n                ax0, ax1, ax2, ax3 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                pad_temp[ax0, ax1, ax2 + 3, ax3 + 3] = x[ax0, ax1, ax2, ax3]\n        for i0, i1, i2, i3, i4, i5 in T.grid(1, 16, 225, 225, 7, 7):\n            with T.block(\"tensor\"):\n                ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n                with T.init():\n                    tensor[ax0, ax1, ax2, ax3] = T.int8(0)\n                tensor[ax0, ax1, ax2, ax3] = (\n                    tensor[ax0, ax1, ax2, ax3] + pad_temp[ax0, ax1, ax2 + rv0, ax3 + rv1]\n                )\n\n    sch = tir.Schedule(sum_pool_2d, debug_mask=\"all\")\n    pad = sch.get_block(\"pad_temp\")\n    sch.decompose_padding(pad, sch.get_loops(pad)[0])\n    check_decompose_padding(sum_pool_2d, sch.mod[\"main\"], pooling_decompose_0, check_run=True)\n\n\ndef test_decompose_hw_padding_tiled():\n    \"\"\"Case 1. tiling and then decompose\"\"\"\n\n    @T.prim_func\n    def pooling_decompose_1(\n        x: T.Buffer[(1, 16, 225, 225), \"int8\"], tensor: T.Buffer[(1, 16, 225, 225), \"int8\"]\n    ) -> None:\n        pad_temp = T.alloc_buffer([1, 16, 231, 231], dtype=\"int8\")\n        for i0, i2_0, i3_0 in T.grid(1, 3, 3):\n            for ax0, ax1, ax2 in T.grid(16, 81, 81):\n                with T.block(\"pad_temp_pad_const\"):\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(16, ax0)\n                    ax2_1 = T.axis.spatial(231, i2_0 * 75 + ax1)\n                    ax3 = T.axis.spatial(231, i3_0 * 75 + ax2)\n                    T.reads()\n                    T.writes(pad_temp[ax0_1, ax1_1, ax2_1, ax3])\n                    pad_temp[ax0_1, ax1_1, ax2_1, ax3] = T.int8(0)\n            for ax0, ax1, ax2 in T.grid(16, 81, 81):\n                with T.block(\"pad_temp\"):\n                    ax0_2 = T.axis.spatial(1, 0)\n                    ax1_2 = T.axis.spatial(16, ax0)\n                    ax2_2 = T.axis.spatial(225, i2_0 * 75 + ax1 - 3)\n                    ax3 = T.axis.spatial(225, i3_0 * 75 + ax2 - 3)\n                    T.where(\n                        3 <= i2_0 * 75 + ax1\n                        and i2_0 * 75 + ax1 < 228\n                        and 3 <= i3_0 * 75 + ax2\n                        and i3_0 * 75 + ax2 < 228\n                    )\n                    T.reads(x[ax0_2, ax1_2, ax2_2, ax3])\n                    T.writes(pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3])\n                    pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3] = x[ax0_2, ax1_2, ax2_2, ax3]\n            for i1, i2_1, i3_1, i4, i5 in T.grid(16, 75, 75, 7, 7):\n                with T.block(\"tensor\"):\n                    ax0_3, ax1_3 = T.axis.remap(\"SS\", [i0, i1])\n                    ax2_3 = T.axis.spatial(225, i2_0 * 75 + i2_1)\n                    ax3 = T.axis.spatial(225, i3_0 * 75 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1])\n                    T.writes(tensor[ax0_3, ax1_3, ax2_3, ax3])\n                    with T.init():\n                        tensor[ax0_3, ax1_3, ax2_3, ax3] = T.int8(0)\n                    tensor[ax0_3, ax1_3, ax2_3, ax3] = (\n                        tensor[ax0_3, ax1_3, ax2_3, ax3]\n                        + pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1]\n                    )\n\n    sch = tir.Schedule(sum_pool_2d, debug_mask=\"all\")\n    block = sch.get_block(\"tensor\")\n    pad = sch.get_block(\"pad_temp\")\n    n, c, h, w, kh, kw = sch.get_loops(block)\n    ho, hi = sch.split(h, [3, 75])\n    wo, wi = sch.split(w, [3, 75])\n    sch.reorder(n, ho, wo, c, hi, wi, kh, kw)\n    sch.compute_at(sch.get_block(\"pad_temp\"), wo)\n    sch.decompose_padding(pad, sch.get_loops(pad)[3])\n    check_decompose_padding(sum_pool_2d, sch.mod[\"main\"], pooling_decompose_1, check_run=True)\n\n\ndef test_decompose_hw_padding_tiled_and_lift_pad():\n    \"\"\"Case 2. tiling and then decompose, lift const pad values to outer loop\"\"\"\n\n    @T.prim_func\n    def pooling_decompose_2(\n        x: T.Buffer[(1, 16, 225, 225), \"int8\"], tensor: T.Buffer[(1, 16, 225, 225), \"int8\"]\n    ) -> None:\n        pad_temp = T.alloc_buffer([1, 16, 231, 231], dtype=\"int8\")\n        for i0, i2_0, i3_0, ax0, ax1, ax2 in T.grid(1, 3, 3, 16, 81, 81):\n            with T.block(\"pad_temp_pad_const\"):\n                ax0_1 = T.axis.spatial(1, 0)\n                ax1_1 = T.axis.spatial(16, ax0)\n                ax2_1 = T.axis.spatial(231, i2_0 * 75 + ax1)\n                ax3 = T.axis.spatial(231, i3_0 * 75 + ax2)\n                T.reads()\n                T.writes(pad_temp[ax0_1, ax1_1, ax2_1, ax3])\n                pad_temp[ax0_1, ax1_1, ax2_1, ax3] = T.int8(0)\n        for i0, i2_0, i3_0 in T.grid(1, 3, 3):\n            for ax0, ax1, ax2 in T.grid(16, 81, 81):\n                with T.block(\"pad_temp\"):\n                    ax0_2 = T.axis.spatial(1, 0)\n                    ax1_2 = T.axis.spatial(16, ax0)\n                    ax2_2 = T.axis.spatial(225, i2_0 * 75 + ax1 - 3)\n                    ax3 = T.axis.spatial(225, i3_0 * 75 + ax2 - 3)\n                    T.where(\n                        3 <= i2_0 * 75 + ax1\n                        and i2_0 * 75 + ax1 < 228\n                        and 3 <= i3_0 * 75 + ax2\n                        and i3_0 * 75 + ax2 < 228\n                    )\n                    T.reads(x[ax0_2, ax1_2, ax2_2, ax3])\n                    T.writes(pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3])\n                    pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3] = x[ax0_2, ax1_2, ax2_2, ax3]\n            for i1, i2_1, i3_1, i4, i5 in T.grid(16, 75, 75, 7, 7):\n                with T.block(\"tensor\"):\n                    ax0_3, ax1_3 = T.axis.remap(\"SS\", [i0, i1])\n                    ax2_3 = T.axis.spatial(225, i2_0 * 75 + i2_1)\n                    ax3 = T.axis.spatial(225, i3_0 * 75 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1])\n                    T.writes(tensor[ax0_3, ax1_3, ax2_3, ax3])\n                    with T.init():\n                        tensor[ax0_3, ax1_3, ax2_3, ax3] = T.int8(0)\n                    tensor[ax0_3, ax1_3, ax2_3, ax3] = (\n                        tensor[ax0_3, ax1_3, ax2_3, ax3]\n                        + pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1]\n                    )\n\n    sch = tir.Schedule(sum_pool_2d, debug_mask=\"all\")\n    block = sch.get_block(\"tensor\")\n    pad = sch.get_block(\"pad_temp\")\n    n, c, h, w, kh, kw = sch.get_loops(block)\n    ho, hi = sch.split(h, [3, 75])\n    wo, wi = sch.split(w, [3, 75])\n    sch.reorder(n, ho, wo, c, hi, wi, kh, kw)\n    sch.compute_at(sch.get_block(\"pad_temp\"), wo)\n    sch.decompose_padding(pad, sch.get_loops(pad)[0])\n    check_decompose_padding(sum_pool_2d, sch.mod[\"main\"], pooling_decompose_2, check_run=True)\n\n\ndef test_decompose_hw_padding_non_perfect_tiled():\n    \"\"\"Case 3. non-perfect tiling and then decompose\"\"\"\n\n    @T.prim_func\n    def pooling_decompose_3(\n        x: T.Buffer[(1, 16, 225, 225), \"int8\"], tensor: T.Buffer[(1, 16, 225, 225), \"int8\"]\n    ) -> None:\n        pad_temp = T.alloc_buffer([1, 16, 231, 231], dtype=\"int8\")\n        for i0, i2_0, i3_0 in T.grid(1, 3, 3):\n            for ax0, ax1, ax2 in T.grid(16, 86, 86):\n                with T.block(\"pad_temp_pad_const\"):\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(16, ax0)\n                    ax2_1 = T.axis.spatial(231, i2_0 * 80 + ax1)\n                    ax3 = T.axis.spatial(231, i3_0 * 80 + ax2)\n                    T.where(i2_0 * 80 + ax1 < 231 and i3_0 * 80 + ax2 < 231)\n                    T.reads()\n                    T.writes(pad_temp[ax0_1, ax1_1, ax2_1, ax3])\n                    pad_temp[ax0_1, ax1_1, ax2_1, ax3] = T.int8(0)\n            for ax0, ax1, ax2 in T.grid(16, 86, 86):\n                with T.block(\"pad_temp\"):\n                    ax0_2 = T.axis.spatial(1, 0)\n                    ax1_2 = T.axis.spatial(16, ax0)\n                    ax2_2 = T.axis.spatial(225, i2_0 * 80 + ax1 - 3)\n                    ax3 = T.axis.spatial(225, i3_0 * 80 + ax2 - 3)\n                    T.where(\n                        3 <= i2_0 * 80 + ax1\n                        and i2_0 * 80 + ax1 < 228\n                        and 3 <= i3_0 * 80 + ax2\n                        and i3_0 * 80 + ax2 < 228\n                        and i2_0 * 80 + ax1 < 231\n                        and i3_0 * 80 + ax2 < 231\n                    )\n                    T.reads(x[ax0_2, ax1_2, ax2_2, ax3])\n                    T.writes(pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3])\n                    pad_temp[ax0_2, ax1_2, ax2_2 + 3, ax3 + 3] = x[ax0_2, ax1_2, ax2_2, ax3]\n            for i1, i2_1, i3_1, i4, i5 in T.grid(16, 80, 80, 7, 7):\n                with T.block(\"tensor\"):\n                    ax0_3, ax1_3 = T.axis.remap(\"SS\", [i0, i1])\n                    ax2_3 = T.axis.spatial(225, i2_0 * 80 + i2_1)\n                    ax3 = T.axis.spatial(225, i3_0 * 80 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.where(i2_0 * 80 + i2_1 < 225 and i3_0 * 80 + i3_1 < 225)\n                    T.reads(pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1])\n                    T.writes(tensor[ax0_3, ax1_3, ax2_3, ax3])\n                    with T.init():\n                        tensor[ax0_3, ax1_3, ax2_3, ax3] = T.int8(0)\n                    tensor[ax0_3, ax1_3, ax2_3, ax3] = (\n                        tensor[ax0_3, ax1_3, ax2_3, ax3]\n                        + pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1]\n                    )\n\n    sch = tir.Schedule(sum_pool_2d, debug_mask=\"all\")\n    block = sch.get_block(\"tensor\")\n    pad = sch.get_block(\"pad_temp\")\n    n, c, h, w, kh, kw = sch.get_loops(block)\n    ho, hi = sch.split(h, [None, 80])\n    wo, wi = sch.split(w, [None, 80])\n    sch.reorder(n, ho, wo, c, hi, wi, kh, kw)\n    sch.compute_at(sch.get_block(\"pad_temp\"), wo)\n    sch.decompose_padding(pad, sch.get_loops(pad)[3])\n    check_decompose_padding(sum_pool_2d, sch.mod[\"main\"], pooling_decompose_3, check_run=True)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_error.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = T.float32(0)\n        for k in range(128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef test_tir_schedule_error_detail():\n    sch = tir.Schedule(matmul, debug_mask=\"all\", error_render_level=\"detail\")\n    with pytest.raises(tir.ScheduleError) as excinfo:\n        sch.get_block(\"wrong_name\")\n    (msg,) = excinfo.value.args\n    assert \"Cannot find a block with the name: wrong_name\" in msg\n\n\ndef test_tir_schedule_error_fast():\n    sch = tir.Schedule(matmul, debug_mask=\"all\", error_render_level=\"fast\")\n    with pytest.raises(tir.ScheduleError) as excinfo:\n        sch.get_block(\"wrong_name\")\n    (msg,) = excinfo.value.args\n    assert \"Cannot find a block with the specified name\" in msg\n\n\ndef test_tir_schedule_error_none():\n    sch = tir.Schedule(matmul, debug_mask=\"all\", error_render_level=\"none\")\n    with pytest.raises(tir.ScheduleError) as excinfo:\n        sch.get_block(\"wrong_name\")\n    (msg,) = excinfo.value.args\n    assert \"(not rendered)\" in msg\n\n\ndef test_tir_schedule_attribute_error():\n    sch = tir.Schedule(matmul)\n    with pytest.raises(AttributeError):\n        sch.non_existent_field()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_for_kind.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef element_wise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_parallelized(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    for i0 in T.parallel(0, 128):\n        for i1 in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i0, i1])\n                B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_i_bound(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    for i0 in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        for i1 in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i0, i1])\n                B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_compute_at_split(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    for i in T.serial(0, 128):\n        for j0 in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j0])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j1o, j1i in T.grid(32, 4):\n            with T.block(\"C\"):\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(128, j1o * 4 + j1i)\n                C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_compute_at_split_vectorized(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    for i in T.serial(0, 128):\n        for j0 in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j0])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j1o in T.serial(0, 32):\n            for j1i in T.vectorized(0, 4):\n                with T.block(\"C\"):\n                    vi = T.axis.S(128, i)\n                    vj = T.axis.S(128, j1o * 4 + j1i)\n                    C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_split_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    for i, j_0, j_1 in T.grid(128, 13, 10):\n        with T.block(\"B\"):\n            T.where(j_0 * 10 + j_1 < 128)\n            vi = T.axis.S(128, i)\n            vj = T.axis.S(128, j_0 * 10 + j_1)\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_split_predicate_parallelized(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    for i in T.serial(0, 128):\n        for j_0 in T.parallel(0, 13):\n            for j_1 in T.serial(0, 10):\n                with T.block(\"B\"):\n                    T.where(j_0 * 10 + j_1 < 128)\n                    vi = T.axis.S(128, i)\n                    vj = T.axis.S(128, j_0 * 10 + j_1)\n                    B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_split_predicate_vectorized(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    for i in T.vectorized(0, 128):\n        for j_0, j_1 in T.grid(13, 10):\n            with T.block(\"B\"):\n                T.where(j_0 * 10 + j_1 < 128)\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(128, j_0 * 10 + j_1)\n                B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef element_wise_compute_at_split_j0_j1o_bound(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    for i in T.serial(0, 128):\n        for j0 in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j0])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j1o in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            for j1i in T.serial(0, 4):\n                with T.block(\"C\"):\n                    vi = T.axis.S(128, i)\n                    vj = T.axis.S(128, j1o * 4 + j1i)\n                    C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef rowsum(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_unrolled(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n    for i0 in T.unroll(0, 128):\n        for i1 in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    B[vi] = 0.0\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_not_quasi_affine(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 16):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            vk = T.axis.R(128, T.floordiv(k * k, 2))\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_not_compact_data_flow(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 16):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vk] = 0.0\n            B[vk] = B[vk] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_cross_thread_reduction(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n    for i0 in T.serial(0, 128):\n        for i1 in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i0, i1])\n                with T.init():\n                    B[vi] = 0.0\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef opaque_block(a: T.handle) -> None:\n    A = T.match_buffer(a, (16,))\n    for i in T.serial(0, 15):\n        with T.block(\"opaque\"):\n            A[i + 1] = A[i + 1] + A[i]\n\n\n@T.prim_func\ndef block_inside_init(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        with T.block(\"outer\"):\n            vi = T.axis.S(128, i)\n            with T.init():\n                for j in T.serial(0, 128):\n                    with T.block(\"init\"):\n                        vj = T.axis.S(128, j)\n                        B[vi, vj] = 0.0\n            for k in T.serial(0, 128):\n                for j in T.serial(0, 128):\n                    with T.block(\"inner\"):\n                        vj, vk = T.axis.remap(\"SR\", [j, k])\n                        B[vi, vj] = B[vi, vj] + A[vi, vj, vk]\n\n\n@T.prim_func\ndef thread_bound_block_inside_init(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        with T.block(\"outer\"):\n            vi = T.axis.S(128, i)\n            with T.init():\n                for j in T.serial(0, 128):\n                    with T.block(\"init\"):\n                        vj = T.axis.S(128, j)\n                        B[vi, vj] = 0.0\n            for k in T.serial(0, 128):\n                for j in T.serial(0, 128):\n                    with T.block(\"inner\"):\n                        vj, vk = T.axis.remap(\"SR\", [j, k])\n                        B[vi, vj] = B[vi, vj] + A[vi, vj, vk]\n\n\n@T.prim_func\ndef decomposed_gemm(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n):\n    local = T.alloc_buffer((16, 16), \"float32\")\n    for i, j in T.grid(4, 4):\n        for ii, jj in T.grid(4, 4):\n            with T.block(\"init\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                local[vi, vj] = 0\n        for k, ii, jj in T.grid(16, 4, 4):\n            with T.block(\"update\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                vk = T.axis.R(16, k)\n                local[vi, vj] += A[vi, vk] * B[vj, vk]\n        for ii, jj in T.grid(4, 4):\n            with T.block(\"C\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                C[vi, vj] = local[vi, vj]\n\n\n@T.prim_func\ndef decomposed_gemm_after_vectorize(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n):\n    local = T.alloc_buffer((16, 16), \"float32\")\n    for i, j in T.grid(4, 4):\n        for ii, jj in T.grid(4, 4):\n            with T.block(\"init\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                local[vi, vj] = 0\n        for k, ii, jj in T.grid(16, 4, 4):\n            with T.block(\"update\"):\n                vi = T.axis.S(16, i * 4 + ii)\n                vj = T.axis.S(16, j * 4 + jj)\n                vk = T.axis.R(16, k)\n                local[vi, vj] += A[vi, vk] * B[vj, vk]\n        for ii in range(4):\n            for jj in T.vectorized(4):\n                with T.block(\"C\"):\n                    vi = T.axis.S(16, i * 4 + ii)\n                    vj = T.axis.S(16, j * 4 + jj)\n                    C[vi, vj] = local[vi, vj]\n\n\n@T.prim_func\ndef nested_block_bind(\n    A: T.Buffer[(16, 16, 16, 16), \"float32\"], B: T.Buffer[(16, 16, 16), \"float32\"]\n):\n    for i, j in T.grid(16, 16):\n        with T.block(\"outer\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            for k, l in T.grid(16, 16):\n                with T.block(\"inner\"):\n                    vk, vl = T.axis.remap(\"SR\", [k, l])\n                    with T.init():\n                        B[vi, vj, vk] = 0.0\n                    B[vi, vj, vk] = B[vi, vj, vk] + A[vi, vj, vk, vl]\n\n\n@T.prim_func\ndef thread_bound_nested_block(\n    A: T.Buffer[(16, 16, 16, 16), \"float32\"], B: T.Buffer[(16, 16, 16), \"float32\"]\n) -> None:\n    for i in T.serial(16):\n        for j in T.thread_binding(16, thread=\"blockIdx.x\"):\n            with T.block(\"outer\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                for k in T.serial(16):\n                    for l in T.thread_binding(16, thread=\"threadIdx.x\"):\n                        with T.block(\"inner\"):\n                            vk, vl = T.axis.remap(\"SR\", [k, l])\n                            with T.init():\n                                B[vi, vj, vk] = T.float32(0)\n                            B[vi, vj, vk] = B[vi, vj, vk] + A[vi, vj, vk, vl]\n\n\n@T.prim_func\ndef nested_block_bind_after_cache_read(\n    A: T.Buffer[(16, 16), \"float32\"], B: T.Buffer[(16,), \"float32\"]\n) -> None:\n    for i in T.serial(16):\n        with T.block(\"outer\"):\n            vi = T.axis.spatial(16, i)\n            A_shared = T.alloc_buffer([1, 16], dtype=\"float32\", scope=\"shared\")\n            for ax0, ax1 in T.grid(1, 16):\n                with T.block(\"A_shared\"):\n                    v0 = T.axis.spatial(16, vi + ax0)\n                    v1 = T.axis.spatial(16, ax1)\n                    A_shared[v0, v1] = A[v0, v1]\n            for j in T.serial(16):\n                with T.block(\"inner\"):\n                    vj = T.axis.reduce(16, j)\n                    with T.init():\n                        B[vi] = T.float32(0)\n                    B[vi] = B[vi] + A_shared[vi, vj]\n\n\n@T.prim_func\ndef thread_bound_nested_block_after_cache_read(\n    A: T.Buffer[(16, 16), \"float32\"], B: T.Buffer[(16,), \"float32\"]\n) -> None:\n    for i in T.thread_binding(16, thread=\"blockIdx.x\"):\n        with T.block(\"outer\"):\n            vi = T.axis.spatial(16, i)\n            A_shared = T.alloc_buffer([1, 16], dtype=\"float32\", scope=\"shared\")\n            for ax0, ax1 in T.grid(1, 16):\n                with T.block(\"A_shared\"):\n                    v0 = T.axis.spatial(16, vi + ax0)\n                    v1 = T.axis.spatial(16, ax1)\n                    A_shared[v0, v1] = A[v0, v1]\n            for j in T.thread_binding(16, thread=\"threadIdx.x\"):\n                with T.block(\"inner\"):\n                    vj = T.axis.reduce(16, j)\n                    with T.init():\n                        B[vi] = T.float32(0)\n                    B[vi] = B[vi] + A_shared[vi, vj]\n\n\n@T.prim_func\ndef decomposed_gemm_parallelize_init(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n) -> None:\n    local = T.alloc_buffer([16, 16], dtype=\"float32\")\n    for i, j in T.grid(4, 4):\n        for ii in T.serial(4):\n            for jj in T.vectorized(4):\n                with T.block(\"init\"):\n                    vi = T.axis.spatial(16, i * 4 + ii)\n                    vj = T.axis.spatial(16, j * 4 + jj)\n                    T.reads()\n                    T.writes(local[vi, vj])\n                    local[vi, vj] = 0\n        for k, ii, jj in T.grid(16, 4, 4):\n            with T.block(\"update\"):\n                vi = T.axis.spatial(16, i * 4 + ii)\n                vj = T.axis.spatial(16, j * 4 + jj)\n                vk = T.axis.reduce(16, k)\n                T.reads(local[vi, vj], A[vi, vk], B[vj, vk])\n                T.writes(local[vi, vj])\n                local[vi, vj] = local[vi, vj] + A[vi, vk] * B[vj, vk]\n        for ii, jj in T.grid(4, 4):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(16, i * 4 + ii)\n                vj = T.axis.spatial(16, j * 4 + jj)\n                T.reads(local[vi, vj])\n                T.writes(C[vi, vj])\n                C[vi, vj] = local[vi, vj]\n\n\n@T.prim_func\ndef scatter_compute(A: T.Buffer[(16,), \"float32\"], B: T.Buffer[(16,), \"float32\"]):\n    for i in T.grid(8):\n        with T.block(\"first_half\"):\n            vi = T.axis.spatial(16, 8 + i)\n            B[vi] = A[vi - 8]\n\n    for i in T.grid(8):\n        with T.block(\"last_half\"):\n            vi = T.axis.spatial(16, i)\n            B[vi] = A[vi + 8]\n\n\n@T.prim_func\ndef scatter_compute_parallelize(\n    A: T.Buffer[(16,), \"float32\"], B: T.Buffer[(16,), \"float32\"]\n) -> None:\n    # body\n    # with T.block(\"root\")\n    for i in T.parallel(8):\n        with T.block(\"first_half\"):\n            vi = T.axis.spatial(16, 8 + i)\n            T.reads(A[vi - 8])\n            T.writes(B[vi])\n            B[vi] = A[vi - 8]\n    for i in T.parallel(8):\n        with T.block(\"last_half\"):\n            vi = T.axis.spatial(16, i)\n            T.reads(A[vi + 8])\n            T.writes(B[vi])\n            B[vi] = A[vi + 8]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef test_parallel():\n    s = tir.Schedule(element_wise, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    s.parallel(i)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_parallelized)\n    verify_trace_roundtrip(s, mod=element_wise)\n\n\ndef test_parallel_predicate():\n    s = tir.Schedule(element_wise_split_predicate, debug_mask=\"all\")\n    _, j, _ = s.get_loops(s.get_block(\"B\"))\n    s.parallel(j)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_split_predicate_parallelized)\n    verify_trace_roundtrip(s, mod=element_wise_split_predicate)\n\n\ndef test_parallel_reduction_block_iter():\n    s = tir.Schedule(matmul, debug_mask=\"all\")\n    _, _, k = s.get_loops(s.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.parallel(k)\n\n\ndef test_parallel_not_quasi_affine():\n    s = tir.Schedule(rowsum_not_quasi_affine, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.parallel(i)\n\n\ndef test_parallel_not_compact_data_flow():\n    s = tir.Schedule(rowsum_not_compact_data_flow, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.parallel(i)\n\n\ndef test_vectorize():\n    s = tir.Schedule(element_wise_compute_at_split, debug_mask=\"all\")\n    _, _, j1i = s.get_loops(s.get_block(\"C\"))\n    s.vectorize(j1i)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_compute_at_split_vectorized)\n    verify_trace_roundtrip(s, mod=element_wise_compute_at_split)\n\n\ndef test_vectorize_predicate():\n    s = tir.Schedule(element_wise_split_predicate, debug_mask=\"all\")\n    i, _, _ = s.get_loops(s.get_block(\"B\"))\n    s.vectorize(i)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_split_predicate_vectorized)\n    verify_trace_roundtrip(s, mod=element_wise_split_predicate)\n\n\ndef test_vectorize_opaque_block():\n    s = tir.Schedule(opaque_block, debug_mask=\"all\")\n    (i,) = s.get_loops(s.get_block(\"opaque\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.vectorize(i)\n\n\ndef test_unroll():\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    s.unroll(i)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], rowsum_unrolled)\n    verify_trace_roundtrip(s, mod=rowsum)\n\n\ndef test_unroll_after_bind():\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    s.bind(i, \"blockIdx.x\")\n    s.unroll(i)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], rowsum_unrolled)\n    verify_trace_roundtrip(s, mod=rowsum)\n\n\ndef test_bind1():\n    s = tir.Schedule(element_wise, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    s.bind(i, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_i_bound)\n    verify_trace_roundtrip(s, mod=element_wise)\n\n\ndef test_bind2():\n    s = tir.Schedule(element_wise_compute_at_split, debug_mask=\"all\")\n    _, j0 = s.get_loops(s.get_block(\"B\"))\n    _, j1o, _ = s.get_loops(s.get_block(\"C\"))\n    s.bind(j0, \"threadIdx.x\")\n    s.bind(j1o, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_compute_at_split_j0_j1o_bound)\n    verify_trace_roundtrip(s, mod=element_wise_compute_at_split)\n\n\ndef test_bind_cross_thread_reduction():\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    s.bind(k, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], rowsum_cross_thread_reduction)\n    verify_trace_roundtrip(s, mod=rowsum)\n\n\ndef test_bind_not_cross_thread_reduction():\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.bind(k, \"blockIdx.x\")\n\n\ndef test_bind_after_bind():\n    s = tir.Schedule(element_wise, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    s.bind(i, \"blockIdx.x\")\n    s.bind(i, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], element_wise_i_bound)\n    verify_trace_roundtrip(s, mod=element_wise)\n\n\ndef test_block_inside_init():\n    s = tir.Schedule(block_inside_init, debug_mask=\"all\")\n    (i,) = s.get_loops(s.get_block(\"outer\"))\n    s.bind(i, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], thread_bound_block_inside_init)\n    verify_trace_roundtrip(s, mod=block_inside_init)\n\n\ndef test_vectorize_after_decompose():\n    s = tir.Schedule(decomposed_gemm, debug_mask=\"all\")\n    jj = s.get_loops(s.get_block(\"C\"))[-1]\n    s.vectorize(jj)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], decomposed_gemm_after_vectorize)\n    verify_trace_roundtrip(s, mod=decomposed_gemm)\n\n\ndef test_nested_block_bind():\n    s = tir.Schedule(nested_block_bind)\n    block_outer = s.get_block(\"outer\")\n    block_inner = s.get_block(\"inner\")\n    _, j = s.get_loops(block_outer)\n    _, l = s.get_loops(block_inner)\n    s.bind(l, \"threadIdx.x\")\n    s.bind(j, \"blockIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], thread_bound_nested_block)\n    verify_trace_roundtrip(s, mod=nested_block_bind)\n\n\ndef test_nexted_block_bind_after_cache_read():\n    s = tir.Schedule(nested_block_bind_after_cache_read)\n    block_outer = s.get_block(\"outer\")\n    block_inner = s.get_block(\"inner\")\n    (i,) = s.get_loops(block_outer)\n    (j,) = s.get_loops(block_inner)\n    s.bind(i, \"blockIdx.x\")\n    s.bind(j, \"threadIdx.x\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], thread_bound_nested_block_after_cache_read)\n    verify_trace_roundtrip(s, mod=nested_block_bind_after_cache_read)\n\n\ndef test_vectorize_init():\n    s = tir.Schedule(decomposed_gemm, debug_mask=\"all\")\n    init_blk = s.get_block(\"init\")\n    upd_blk = s.get_block(\"update\")\n    _, _, ii_0, jj_0 = s.get_loops(init_blk)\n    _, _, k_1, ii_1, jj_1 = s.get_loops(upd_blk)\n    s.vectorize(jj_0)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], decomposed_gemm_parallelize_init)\n    verify_trace_roundtrip(s, mod=decomposed_gemm)\n\n\ndef test_scatter_parallelize():\n    s = tir.Schedule(scatter_compute, debug_mask=\"all\")\n    first = s.get_block(\"first_half\")\n    last = s.get_block(\"last_half\")\n    (i_0,) = s.get_loops(first)\n    (i_1,) = s.get_loops(last)\n    s.parallel(i_0)\n    s.parallel(i_1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], scatter_compute_parallelize)\n    verify_trace_roundtrip(s, mod=scatter_compute)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_instruction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\n# mypy: ignore-errors\nimport sys\n\nimport pytest\nimport tvm.testing\nfrom tvm.tir.schedule import BlockRV, Instruction, InstructionKind, LoopRV\n\n\ndef test_inst_kind_get():\n    kind = InstructionKind.get(\"EnterPostproc\")\n    assert not kind.is_pure\n    assert kind.name == \"EnterPostproc\"\n\n\ndef test_inst_construct_1():\n    block = BlockRV()\n    loop0 = LoopRV()\n    loop1 = LoopRV()\n    inst = Instruction(\n        kind=InstructionKind.get(\"GetLoops\"),\n        inputs=[block],\n        attrs=[],\n        outputs=[loop0, loop1],\n    )\n    assert str(inst) == \"_, _ = sch.get_loops(block=_)\"\n    assert len(inst.inputs) == 1\n    assert len(inst.attrs) == 0\n    assert len(inst.outputs) == 2\n    assert inst.kind.same_as(InstructionKind.get(\"GetLoops\"))\n    assert inst.inputs[0].same_as(block)\n    assert inst.outputs[0].same_as(loop0)\n    assert inst.outputs[1].same_as(loop1)\n\n\ndef test_inst_construct_2():\n    block = BlockRV()\n    inst = Instruction(\n        kind=InstructionKind.get(\"ComputeInline\"),\n        inputs=[block],\n        attrs=[],\n        outputs=[],\n    )\n    assert str(inst) == \"sch.compute_inline(block=_)\"\n    assert len(inst.inputs) == 1\n    assert len(inst.attrs) == 0\n    assert len(inst.outputs) == 0\n    assert inst.kind.same_as(InstructionKind.get(\"ComputeInline\"))\n    assert inst.inputs[0].same_as(block)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_pad_einsum.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir, te\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.schedule import ScheduleError\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\nfrom tvm.meta_schedule.testing import te_workload\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\n@T.prim_func\ndef matmul_before(\n    A: T.Buffer[(128, 127), \"float32\"],\n    B: T.Buffer[(127, 127), \"float32\"],\n    C: T.Buffer[(128, 127), \"float32\"],\n) -> None:\n    A_shared = T.alloc_buffer((128, 127), \"float32\", scope=\"shared\")\n    B_shared = T.alloc_buffer((127, 127), \"float32\", scope=\"shared\")\n    C_shared = T.alloc_buffer((128, 127), \"float32\", scope=\"shared\")\n    for i0, i1 in T.grid(128, 127):\n        with T.block(\"A\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            A_shared[i, j] = A[i, j]\n    for i0, i1 in T.grid(127, 127):\n        with T.block(\"B\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            B_shared[i, j] = B[i, j]\n    for i0, i1, i2 in T.grid(128, 127, 127):\n        with T.block(\"C_shared\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            with T.init():\n                C_shared[i, j] = T.float32(0)\n            C_shared[i, j] = C_shared[i, j] + A_shared[i, k] * B_shared[k, j]\n    for i0, i1 in T.grid(128, 127):\n        with T.block(\"C\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            C[i, j] = C_shared[i, j]\n\n\n@T.prim_func\ndef matmul_expected(\n    A: T.Buffer[(128, 127), \"float32\"],\n    B: T.Buffer[(127, 127), \"float32\"],\n    C: T.Buffer[(128, 127), \"float32\"],\n) -> None:\n    A_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n    B_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n    C_shared_padded = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n    for i0, i1 in T.grid(128, 128):\n        with T.block(\"A\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(A[i, j])\n            T.writes(A_shared_padded[i, j])\n            A_shared_padded[i, j] = T.if_then_else(j < 127, A[i, j], T.float32(0), dtype=\"float32\")\n    for i0, i1 in T.grid(128, 128):\n        with T.block(\"B\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(B[i, j])\n            T.writes(B_shared_padded[i, j])\n            B_shared_padded[i, j] = T.if_then_else(\n                i < 127 and j < 127, B[i, j], T.float32(0), dtype=\"float32\"\n            )\n    for i0, i1, i2 in T.grid(128, 128, 128):\n        with T.block(\"C_shared\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(A_shared_padded[i, k], B_shared_padded[k, j])\n            T.writes(C_shared_padded[i, j])\n            with T.init():\n                C_shared_padded[i, j] = T.float32(0)\n            C_shared_padded[i, j] = (\n                C_shared_padded[i, j] + A_shared_padded[i, k] * B_shared_padded[k, j]\n            )\n    for i0, i1 in T.grid(128, 127):\n        with T.block(\"C\"):\n            i, j = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(C_shared_padded[i, j])\n            T.writes(C[i, j])\n            C[i, j] = C_shared_padded[i, j]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\ndef test_pad_matmul():\n    sch = tir.Schedule(matmul_before, debug_mask=\"all\")\n    C = sch.get_block(\"C_shared\")\n    sch.pad_einsum(C, [0, 1, 1])\n    tvm.ir.assert_structural_equal(matmul_expected, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch, mod=matmul_before)\n\n\ndef test_pad_matmul_error_non_intermediate_buffer():\n    func = te.create_prim_func(te_workload.matmul(128, 127, 127))\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    C = sch.get_block(\"C\")\n    with pytest.raises(ScheduleError):\n        sch.pad_einsum(C, [0, 1, 1])\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\n@T.prim_func\ndef rowsum_blockized(a: T.handle, b: T.handle) -> None:\n    B = T.match_buffer(b, [32, 4])\n    A = T.match_buffer(a, [32, 4, 128])\n    for i0, i2_0 in T.grid(32, 16):\n        with T.block(\"blockized_B\"):\n            io, ko = T.axis.remap(\"SR\", [i0, i2_0])\n            with T.init():\n                for i1 in T.serial(0, 4):\n                    with T.block(\"B_init\"):\n                        ii_init = T.axis.S(4, i1)\n                        B[io, ii_init] = 0.0\n            for i1_1, i2_1 in T.grid(4, 8):\n                with T.block(\"B\"):\n                    ii = T.axis.S(4, i1_1)\n                    k = T.axis.R(128, ko * 8 + i2_1)\n                    B[io, ii] = B[io, ii] + A[io, ii, k]\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_decompose0(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = 0.0\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_decompose1(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [32, 4, 128], elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [32, 4], elem_offset=0, align=64, offset_factor=1)\n\n    for i0 in T.serial(0, 32):\n        with T.block(\"blockized_B_init\"):\n            io = T.axis.S(32, i0)\n            for i1 in T.serial(0, 4):\n                with T.block(\"B_init\"):\n                    ii = T.axis.S(4, i1)\n                    B[io, ii] = T.float32(0)\n    for i0, i2_o in T.grid(32, 16):\n        with T.block(\"blockized_B_update\"):\n            io, ko = T.axis.remap(\"SR\", [i0, i2_o])\n            for i1, i2_i in T.grid(4, 8):\n                with T.block(\"B\"):\n                    ii = T.axis.S(4, i1)\n                    k = T.axis.R(128, ko * 8 + i2_i)\n                    B[io, ii] = B[io, ii] + A[io, ii, k]\n\n\n@T.prim_func\ndef matmul_decompose2(a: T.handle, b: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n\n    for i0, i1 in T.grid(128, 128):\n        with T.block(\"update_init\"):\n            vi_init, vj_init = T.axis.remap(\"SS\", [i0, i1])\n            C[vi_init, vj_init] = T.float32(0)\n        for i2 in T.serial(0, 128):\n            with T.block(\"update_update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i0, i1, i2])\n                C[vi, vj] = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n\n\n@T.prim_func\ndef matmul_decompose_fail3(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, k, j in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_decompose4(a: T.handle, b: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    # body\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        for i0_0 in T.serial(0, 16):\n            for i0_1_init, i1_init in T.grid(8, 128):\n                with T.block(\"update_init\"):\n                    vi_init = T.axis.S(128, i0_0 * 8 + i0_1_init)\n                    vj_init = T.axis.S(128, i1_init)\n                    C[vi_init, vj_init] = T.float32(0)\n            for i0_1, i1, i2_0, i2_1 in T.grid(8, 128, 19, 7):\n                with T.block(\"update_update\"):\n                    T.where((((i2_0 * 7) + i2_1) < 128))\n                    vi = T.axis.S(128, i0_0 * 8 + i0_1)\n                    vj = T.axis.S(128, i1)\n                    vk = T.axis.R(128, i2_0 * 7 + i2_1)\n                    C[vi, vj] = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n\n\n@T.prim_func\ndef matmul_with_annotation(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            T.block_attr({\"test_annotation\": 1})\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_decompose_with_annotation(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            T.block_attr({\"test_annotation\": 1})\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = 0.0\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            T.block_attr({\"test_annotation\": 1})\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef colsum_with_vectorization(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 32], dtype=\"float32\")\n    B = T.match_buffer(b, [32], dtype=\"float32\")\n    for k in T.serial(0, 128):\n        for i in T.vectorized(0, 32):\n            with T.block(\"B\"):\n                vk, vi = T.axis.remap(\"RS\", [k, i])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vk, vi]\n\n\n@T.prim_func\ndef colsum_decompose_with_vectorization(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 32], dtype=\"float32\")\n    B = T.match_buffer(b, [32], dtype=\"float32\")\n    for i in T.vectorized(0, 32):\n        with T.block(\"B_init\"):\n            vi = T.axis.S(32, i)\n            B[vi] = T.float32(0)\n    for k in T.serial(0, 128):\n        for i in T.vectorized(0, 32):\n            with T.block(\"B\"):\n                vk, vi = T.axis.remap(\"RS\", [k, i])\n                B[vi] = B[vi] + A[vk, vi]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_reduction_decompose0(use_block_name):\n    s = tir.Schedule(matmul, debug_mask=\"all\")\n    C = \"update\" if use_block_name else s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    s.decompose_reduction(C, i)\n    tvm.ir.assert_structural_equal(matmul_decompose0, s.mod[\"main\"])\n    verify_trace_roundtrip(s, mod=matmul)\n\n\ndef test_reduction_decompose1(use_block_name):\n    s = tir.Schedule(rowsum_blockized, debug_mask=\"all\")\n    blockized_B = \"blockized_B\" if use_block_name else s.get_block(\"blockized_B\")\n    io, ko = s.get_loops(blockized_B)\n    s.decompose_reduction(blockized_B, io)\n    tvm.ir.assert_structural_equal(matmul_decompose1, s.mod[\"main\"])\n    verify_trace_roundtrip(s, mod=rowsum_blockized)\n\n\ndef test_reduction_decompose2():\n    s = tir.Schedule(matmul, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    s.decompose_reduction(C, k)\n    tvm.ir.assert_structural_equal(matmul_decompose2, s.mod[\"main\"])\n    verify_trace_roundtrip(s, mod=matmul)\n\n\ndef test_reduction_decompose3():\n    s = tir.Schedule(matmul_decompose_fail3, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.decompose_reduction(C, k)\n\n\ndef test_reduction_decompose4():\n    s = tir.Schedule(matmul, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    io, ii = s.split(i, factors=[16, 8])\n    ko, ki = s.split(k, factors=[19, 7])\n    s.decompose_reduction(C, ii)\n    tvm.ir.assert_structural_equal(matmul_decompose4, s.mod[\"main\"])\n    verify_trace_roundtrip(s, mod=matmul)\n\n\ndef test_reduction_decompose_with_annotation():\n    s = tir.Schedule(matmul_with_annotation, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    s.decompose_reduction(C, i)\n    tvm.ir.assert_structural_equal(matmul_decompose_with_annotation, s.mod[\"main\"])\n    verify_trace_roundtrip(s, mod=matmul_with_annotation)\n\n\ndef test_reduction_decompose_with_different_for_kind():\n    s = tir.Schedule(colsum_with_vectorization, debug_mask=\"all\")\n    B = s.get_block(\"B\")\n    k, _ = s.get_loops(B)\n    B_init = s.decompose_reduction(B, k)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], colsum_decompose_with_vectorization)\n    assert s.get(B).same_as(s.get(s.get_block(\"B_update\")))\n    assert s.get(B_init).same_as(s.get(s.get_block(\"B_init\")))\n    verify_trace_roundtrip(s, mod=colsum_with_vectorization)\n\n\ndef test_decompose_reduction_ref_hash_check():\n    mod = tvm.IRModule.from_expr(matmul)\n    mod_bak = mod\n    hash_before = tvm.ir.structural_hash(mod_bak)\n    s = tir.Schedule(mod[\"main\"], debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    i, j, k = s.get_loops(C)\n    s.decompose_reduction(C, k)\n    hash_after = tvm.ir.structural_hash(mod_bak)\n    assert hash_before == hash_after\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_reindex.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.schedule import ScheduleError\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n\n@T.prim_func\ndef transpose_elementwise(\n    A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]\n) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vj, vi] * 2.0\n\n\n@T.prim_func\ndef transpose_elementwise_reindex_read(\n    A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]\n) -> None:\n    A_reindex = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"A_reindex\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            A_reindex[vi, vj] = A[vj, vi]\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A_reindex[vi, vj] * 2.0\n\n\n@T.prim_func\ndef conv2d_nhwc(\n    Input: T.Buffer[(1, 224, 224, 3), \"float32\"],\n    Weight: T.Buffer[(7, 7, 3, 64), \"float32\"],\n    Conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"],\n) -> None:\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                ((((i1_1 >= 3) and (i1_1 < 227)) and (i2_1 >= 3)) and (i2_1 < 227)),\n                Input[i0_1, (i1_1 - 3), (i2_1 - 3), i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 112, 112, 64, 7, 7, 3):\n        with T.block(\"conv2d_nhwc\"):\n            n, h, w, co, rh, rw, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n            with T.init():\n                Conv2d_nhwc[n, h, w, co] = T.float32(0)\n            Conv2d_nhwc[n, h, w, co] = Conv2d_nhwc[n, h, w, co] + (\n                PadInput[n, ((h * 2) + rh), ((w * 2) + rw), ((T.floordiv(co, 64) * 3) + rc)]\n                * Weight[rh, rw, rc, co]\n            )\n\n\n@T.prim_func\ndef conv2d_nhwc_reindex_data(\n    Input: T.Buffer[(1, 224, 224, 3), \"float32\"],\n    Weight: T.Buffer[(7, 7, 3, 64), \"float32\"],\n    Conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"],\n) -> None:\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    ReindexInput = T.alloc_buffer([1, 112, 112, 7, 7, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                ((((i1_1 >= 3) and (i1_1 < 227)) and (i2_1 >= 3)) and (i2_1 < 227)),\n                Input[i0_1, (i1_1 - 3), (i2_1 - 3), i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 112, 112, 7, 7, 3):\n        with T.block(\"ReindexInput\"):\n            n, h, w, rh, rw, rc = T.axis.remap(\"SSSSSS\", [i0, i1, i2, i3, i4, i5])\n            ReindexInput[n, h, w, rh, rw, rc] = PadInput[n, ((h * 2) + rh), ((w * 2) + rw), rc]\n    for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 112, 112, 64, 7, 7, 3):\n        with T.block(\"conv2d_nhwc\"):\n            n, h, w, co, rh, rw, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n            with T.init():\n                Conv2d_nhwc[n, h, w, co] = T.float32(0)\n            Conv2d_nhwc[n, h, w, co] = Conv2d_nhwc[n, h, w, co] + (\n                ReindexInput[n, h, w, rh, rw, rc] * Weight[rh, rw, rc, co]\n            )\n\n\n@T.prim_func\ndef conv2d_nhwc_reindex_weight(\n    var_inputs: T.handle, var_weight: T.handle, var_conv2d_nhwc: T.handle\n) -> None:\n    inputs = T.match_buffer(var_inputs, [1, 224, 224, 3], dtype=\"float32\")\n    weight = T.match_buffer(var_weight, [7, 7, 3, 64], dtype=\"float32\")\n    conv2d_nhwc = T.match_buffer(var_conv2d_nhwc, [1, 112, 112, 64], dtype=\"float32\")\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    weight_reindex = T.alloc_buffer([64, 7, 7, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            T.reads(inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1])\n            T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                i1_1 >= 3 and i1_1 < 227 and i2_1 >= 3 and i2_1 < 227,\n                inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for ax3, ax4, ax5, ax6 in T.grid(64, 7, 7, 3):\n        with T.block(\"weight_reindex\"):\n            v3, v4, v5, v6 = T.axis.remap(\"SSSS\", [ax3, ax4, ax5, ax6])\n            T.reads(weight[v4, v5, v6, v3])\n            T.writes(weight_reindex[v3, v4, v5, v6])\n            weight_reindex[v3, v4, v5, v6] = weight[v4, v5, v6, v3]\n    for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 112, 112, 64, 7, 7, 3):\n        with T.block(\"conv2d_nhwc\"):\n            n, h, w, co, rh, rw, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n            T.reads(\n                PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc],\n                weight_reindex[co, rh, rw, rc],\n            )\n            T.writes(conv2d_nhwc[n, h, w, co])\n            with T.init():\n                conv2d_nhwc[n, h, w, co] = T.float32(0)\n            conv2d_nhwc[n, h, w, co] = (\n                conv2d_nhwc[n, h, w, co]\n                + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc]\n                * weight_reindex[co, rh, rw, rc]\n            )\n\n\n@T.prim_func\ndef matmul(\n    A: T.Buffer[(512, 512), \"float32\"],\n    B: T.Buffer[(512, 512), \"float32\"],\n    C: T.Buffer[(512, 512), \"float32\"],\n) -> None:\n    for i0, i1, i2 in T.grid(512, 512, 512):\n        with T.block(\"matmul\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(C[i, j], A[i, k], B[k, j])\n            T.writes(C[i, j])\n            with T.init():\n                C[i, j] = T.float32(0)\n            C[i, j] = C[i, j] + A[i, k] * B[k, j]\n\n\n@T.prim_func\ndef matmul_reindex_write(\n    A: T.Buffer[(512, 512), \"float32\"],\n    B: T.Buffer[(512, 512), \"float32\"],\n    C: T.Buffer[(512, 512), \"float32\"],\n) -> None:\n    C_reindex = T.alloc_buffer([512, 512], dtype=\"float32\")\n    for i0, i1, i2 in T.grid(512, 512, 512):\n        with T.block(\"matmul\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(C_reindex[i, j], A[i, k], B[k, j])\n            T.writes(C_reindex[i, j])\n            with T.init():\n                C_reindex[i, j] = T.float32(0)\n            C_reindex[i, j] = C_reindex[i, j] + A[i, k] * B[k, j]\n    for i0, i1 in T.grid(512, 512):\n        with T.block(\"C_reindex\"):\n            v0, v1 = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(C_reindex[v0, v1])\n            T.writes(C[v0, v1])\n            C[v0, v1] = C_reindex[v0, v1]\n\n\n@T.prim_func\ndef multiple_read(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vj, vi] + A[vi, vj]\n\n\n@T.prim_func\ndef mixed_dtype(\n    p0: T.Buffer[(T.int64(2), 1280), \"float16\"],\n    p1: T.Buffer[(1280, 1280), \"float16\"],\n    T_matmul_NT: T.Buffer[(T.int64(2), 1280), \"float16\"],\n) -> None:\n    for i0, i1, i2 in T.grid(T.int64(2), 1280, 1280):\n        with T.block(\"T_matmul_NT\"):\n            i = T.axis.spatial(T.int64(2), i0)\n            j, k = T.axis.remap(\"SR\", [i1, i2])\n            T.reads(p0[i, k], p1[j, k])\n            T.writes(T_matmul_NT[i, j])\n            with T.init():\n                T_matmul_NT[i, j] = T.float16(0)\n            T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1[j, k]\n\n\n@T.prim_func\ndef mixed_dtype_reindex_write(\n    p0: T.Buffer[(T.int64(2), 1280), \"float16\"],\n    p1: T.Buffer[(1280, 1280), \"float16\"],\n    T_matmul_NT: T.Buffer[(T.int64(2), 1280), \"float16\"],\n) -> None:\n    T_matmul_NT_reindex = T.alloc_buffer([T.int64(2), 1280], dtype=\"float16\")\n    for i0, i1, i2 in T.grid(T.int64(2), 1280, 1280):\n        with T.block(\"T_matmul_NT\"):\n            i = T.axis.spatial(T.int64(2), i0)\n            j, k = T.axis.remap(\"SR\", [i1, i2])\n            T.reads(p0[i, k], p1[j, k])\n            T.writes(T_matmul_NT_reindex[i, j])\n            with T.init():\n                T_matmul_NT_reindex[i, j] = T.float16(0)\n            T_matmul_NT_reindex[i, j] = T_matmul_NT_reindex[i, j] + p0[i, k] * p1[j, k]\n    for ax0, ax1 in T.grid(T.int64(2), 1280):\n        with T.block(\"T_matmul_NT_reindex\"):\n            v0 = T.axis.spatial(T.int64(2), ax0)\n            v1 = T.axis.remap(\"S\", [ax1])\n            T.reads(T_matmul_NT_reindex[v0, v1])\n            T.writes(T_matmul_NT[v0, v1])\n            T_matmul_NT[v0, v1] = T_matmul_NT_reindex[v0, v1]\n\n\n@T.prim_func\ndef matmul_unit_dim(\n    A: T.Buffer[(1, 512), \"float32\"],\n    B: T.Buffer[(512, 1), \"float32\"],\n    C: T.Buffer[(1, 1), \"float32\"],\n) -> None:\n    for i0, i1, i2 in T.grid(1, 1, 512):\n        with T.block(\"matmul\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(C[i, j], A[i, k], B[k, j])\n            T.writes(C[i, j])\n            with T.init():\n                C[i, j] = T.float32(0)\n            C[i, j] = C[i, j] + A[i, k] * B[k, j]\n\n\n@T.prim_func\ndef matmul_unit_dim_reindex_write(\n    A: T.Buffer[(1, 512), \"float32\"],\n    B: T.Buffer[(512, 1), \"float32\"],\n    C: T.Buffer[(1, 1), \"float32\"],\n) -> None:\n    C_reindex = T.alloc_buffer([1, 1], dtype=\"float32\")\n    for i0, i1, i2 in T.grid(1, 1, 512):\n        with T.block(\"matmul\"):\n            i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n            T.reads(C_reindex[i, j], A[i, k], B[k, j])\n            T.writes(C_reindex[i, j])\n            with T.init():\n                C_reindex[i, j] = T.float32(0)\n            C_reindex[i, j] = C_reindex[i, j] + A[i, k] * B[k, j]\n    for i0, i1 in T.grid(1, 1):\n        with T.block(\"C_reindex\"):\n            v0, v1 = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(C_reindex[v0, v1])\n            T.writes(C[v0, v1])\n            C[v0, v1] = C_reindex[v0, v1]\n\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\nuse_buffer_name = tvm.testing.parameter(by_dict={\"buffer_index\": False, \"buffer_name\": True})\n\n\ndef test_reindex_read_basic(use_block_name, use_buffer_name):\n    sch = tir.Schedule(transpose_elementwise)\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    buf = \"A\" if use_buffer_name else (\"read\", 0)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(transpose_elementwise_reindex_read, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=transpose_elementwise)\n\n\ndef test_conv2d_reindex_weight(use_block_name, use_buffer_name):\n    sch = tir.Schedule(conv2d_nhwc)\n    block = \"conv2d_nhwc\" if use_block_name else sch.get_block(\"conv2d_nhwc\")\n    buf = \"Weight\" if use_buffer_name else (\"read\", 1)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(conv2d_nhwc_reindex_weight, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=conv2d_nhwc)\n\n\ndef test_conv2d_reindex_data(use_block_name, use_buffer_name):\n    sch = tir.Schedule(conv2d_nhwc)\n    block = \"conv2d_nhwc\" if use_block_name else sch.get_block(\"conv2d_nhwc\")\n    buf = \"PadInput\" if use_buffer_name else (\"read\", 0)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(conv2d_nhwc_reindex_data, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=conv2d_nhwc)\n\n\ndef test_matmul_reindex_write(use_block_name, use_buffer_name):\n    sch = tir.Schedule(matmul)\n    block = \"matmul\" if use_block_name else sch.get_block(\"matmul\")\n    buf = \"C\" if use_buffer_name else (\"write\", 0)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(matmul_reindex_write, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=matmul)\n\n\ndef test_reindex_fail_multiple_read(use_block_name, use_buffer_name):\n    sch = tir.Schedule(multiple_read)\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    buf = \"A\" if use_buffer_name else (\"read\", 0)\n    with pytest.raises(ScheduleError):\n        sch.reindex(block, buf)\n\n\ndef test_reindex_mixed_dtype(use_block_name, use_buffer_name):\n    sch = tir.Schedule(mixed_dtype)\n    block = \"T_matmul_NT\" if use_block_name else sch.get_block(\"T_matmul_NT\")\n    buf = \"T_matmul_NT\" if use_buffer_name else (\"write\", 0)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(mixed_dtype_reindex_write, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=mixed_dtype)\n\n\ndef test_matmul_unit_dim_reindex_write(use_block_name, use_buffer_name):\n    sch = tir.Schedule(matmul_unit_dim)\n    block = \"matmul\" if use_block_name else sch.get_block(\"matmul\")\n    buf = \"C\" if use_buffer_name else (\"write\", 0)\n    sch.reindex(block, buf)\n    tvm.ir.assert_structural_equal(matmul_unit_dim_reindex_write, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=matmul_unit_dim)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_reorder.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i, j, k, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_not_affine(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i, j, k, l in T.grid(128, 128, 128, 8):\n        with T.block(\"B\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            vl = T.axis.S(128, l * 16)\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_dependent_loop(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i in T.serial(0, 128):\n        for j, k, l in T.grid(128, i, 128):\n            with T.block(\"B\"):\n                vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i, j, k, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            T.where(i * 2097152 + j * 16384 + k * 128 + l < 100)\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_non_single_branch(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    C = T.alloc_buffer((128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.serial(0, 128):\n            with T.block(\"C\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                C[vi, vj, vk] = A[vi, vj, vk] * 2.0\n        for k in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                B[vi, vj, vk] = C[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_loops_not_same_scope(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            for k in T.serial(0, 128):\n                with T.block(\"B\"):\n                    vk = T.axis.S(128, k)\n                    T.reads([A[vi, vj, vk]])\n                    T.writes([B[vi, vj, vk]])\n                    B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_wrong_block_var_type(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            vk = T.axis.scan(128, k)\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_reordered(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for l, j, k, i in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_reordered2(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for k, j, i, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_reordered_with_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for l, j, k, i in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            T.where(i * 2097152 + j * 16384 + k * 128 + l < 100)\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16], \"float32\")\n    B = T.match_buffer(b, [16, 16], \"float32\")\n    for i, j in T.grid(16, 16):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([A[0:16, 0:16]])\n            A[vi, vj] = 1\n    for i, j in T.grid(16, 16):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([B[0:16, 0:16]])\n            T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\"))\n\n\n@T.prim_func\ndef opaque_access_reorder(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16], \"float32\")\n    B = T.match_buffer(b, [16, 16], \"float32\")\n    for j, i in T.grid(16, 16):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([A[0:16, 0:16]])\n            A[vi, vj] = 1\n    for j, i in T.grid(16, 16):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([B[0:16, 0:16]])\n            T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\"))\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef test_reorder():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    sch.reorder(l, i)\n    tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_reorder2():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    sch.reorder(k, i, l)\n    tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_reorder_with_opaque_access():\n    sch = tir.Schedule(opaque_access, debug_mask=\"all\")\n    block_a = sch.get_block(\"A\")\n    i, j = sch.get_loops(block_a)\n    sch.reorder(j, i)\n    block_b = sch.get_block(\"B\")\n    i, j = sch.get_loops(block_b)\n    sch.reorder(j, i)\n    tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=opaque_access)\n\n\ndef test_reorder_overlapped_access():\n    @T.prim_func\n    def overlapped_access(A: T.Buffer[(14, 4), \"float32\"], B: T.Buffer[(14, 4), \"float32\"]):\n        # example to write first axis multiple times\n        for v0, v1, v2 in T.grid(6, 4, 4):\n            with T.block(\"block\"):\n                i = T.axis.spatial(14, v0 * 2 + v1)\n                j = T.axis.spatial(4, v2)\n                B[i, j] = A[i, j] + 1.0\n\n    @T.prim_func\n    def overlapped_access_reorder(A: T.Buffer[(14, 4), \"float32\"], B: T.Buffer[(14, 4), \"float32\"]):\n        # example to write first axis multiple times\n        for v0, v2, v1 in T.grid(6, 4, 4):\n            with T.block(\"block\"):\n                i = T.axis.spatial(14, v0 * 2 + v1)\n                j = T.axis.spatial(4, v2)\n                B[i, j] = A[i, j] + 1.0\n\n    sch = tir.Schedule(overlapped_access, debug_mask=\"all\")\n    v0, v1, v2 = sch.get_loops(sch.get_block(\"block\"))\n    sch.reorder(v0, v2, v1)\n    tvm.ir.assert_structural_equal(overlapped_access_reorder, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=overlapped_access)\n\n\ndef test_reorder_with_partial_affineness():\n    @T.prim_func\n    def non_affine_func(A: T.Buffer[(14, 4), \"float32\"], B: T.Buffer[(14, 4), \"float32\"]):\n        for v0, v1, v2 in T.grid(6, 4, 4):\n            with T.block(\"block\"):\n                i = T.axis.spatial(14, v0 * v0 + v1)\n                j = T.axis.spatial(4, v2)\n                B[i, j] = A[i, j] + 1.0\n\n    @T.prim_func\n    def non_affine_func_reorder(A: T.Buffer[(14, 4), \"float32\"], B: T.Buffer[(14, 4), \"float32\"]):\n        for v0, v2, v1 in T.grid(6, 4, 4):\n            with T.block(\"block\"):\n                i = T.axis.spatial(14, v0 * v0 + v1)\n                j = T.axis.spatial(4, v2)\n                B[i, j] = A[i, j] + 1.0\n\n    sch = tir.Schedule(non_affine_func, debug_mask=\"all\")\n    v0, v1, v2 = sch.get_loops(sch.get_block(\"block\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(v0, v2, v1)\n\n    sch.reorder(v2, v1)\n    tvm.ir.assert_structural_equal(non_affine_func_reorder, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=non_affine_func)\n\n\ndef test_reorder_with_cascade_tiled_ops():\n    @T.prim_func\n    def cascade_pool_ops(\n        x: T.Buffer[(1, 16, 112, 112), \"float32\"], y2: T.Buffer[(1, 16, 108, 108), \"float32\"]\n    ) -> None:\n        y1 = T.alloc_buffer([1, 16, 110, 110], dtype=\"float32\")\n        for n, c, h, w, kh, kw in T.grid(1, 16, 110, 110, 3, 3):\n            with T.block(\"pool_0\"):\n                ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [n, c, h, w, kh, kw])\n                with T.init():\n                    y1[ax0, ax1, ax2, ax3] = 0.0\n                y1[ax0, ax1, ax2, ax3] = y1[ax0, ax1, ax2, ax3] + x[ax0, ax1, ax2 + rv0, ax3 + rv1]\n        for n, c, h, w, kh, kw in T.grid(1, 16, 108, 108, 3, 3):\n            with T.block(\"pool_1\"):\n                ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [n, c, h, w, kh, kw])\n                with T.init():\n                    y2[ax0, ax1, ax2, ax3] = 0.0\n                y2[ax0, ax1, ax2, ax3] = y2[ax0, ax1, ax2, ax3] + y1[ax0, ax1, ax2 + rv0, ax3 + rv1]\n\n    @T.prim_func\n    def cascade_pool_ops_tile_reordered(\n        x: T.Buffer[(1, 16, 112, 112), \"float32\"], y2: T.Buffer[(1, 16, 108, 108), \"float32\"]\n    ) -> None:\n        y1 = T.alloc_buffer([1, 16, 110, 110], dtype=\"float32\")\n        for n, c, h_o in T.grid(1, 16, 27):\n            for w, h_i, kh, kw in T.grid(110, 6, 3, 3):\n                with T.block(\"pool_0\"):\n                    ax0 = T.axis.spatial(1, 0)\n                    ax1 = T.axis.spatial(16, c)\n                    ax2 = T.axis.spatial(110, h_o * 4 + h_i)\n                    ax3, rv0, rv1 = T.axis.remap(\"SRR\", [w, kh, kw])\n                    with T.init():\n                        y1[ax0, ax1, ax2, ax3] = 0.0\n                    y1[ax0, ax1, ax2, ax3] = (\n                        y1[ax0, ax1, ax2, ax3] + x[ax0, ax1, ax2 + rv0, ax3 + rv1]\n                    )\n            for h_i, w, kh, kw in T.grid(4, 108, 3, 3):\n                with T.block(\"pool_1\"):\n                    ax0 = T.axis.spatial(1, n)\n                    ax1 = T.axis.spatial(16, c)\n                    ax2 = T.axis.spatial(108, h_o * 4 + h_i)\n                    ax3, rv0, rv1 = T.axis.remap(\"SRR\", [w, kh, kw])\n                    with T.init():\n                        y2[ax0, ax1, ax2, ax3] = 0.0\n                    y2[ax0, ax1, ax2, ax3] = (\n                        y2[ax0, ax1, ax2, ax3] + y1[ax0, ax1, ax2 + rv0, ax3 + rv1]\n                    )\n\n    sch = tvm.tir.schedule.Schedule(cascade_pool_ops)\n    pool_0 = sch.get_block(\"pool_0\")\n    pool_1 = sch.get_block(\"pool_1\")\n    _, _, h, w, _, _ = sch.get_loops(pool_1)\n    ho, _ = sch.split(h, factors=[None, 4])\n    sch.compute_at(pool_0, ho)\n    _, _, _, h_i, w, _, _ = sch.get_loops(pool_0)\n    sch.reorder(w, h_i)\n    tvm.ir.assert_structural_equal(cascade_pool_ops_tile_reordered, sch.mod[\"main\"], True)\n    verify_trace_roundtrip(sch=sch, mod=cascade_pool_ops)\n\n\ndef test_reorder_with_predicate():\n    sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(l, i)\n\n\ndef test_reorder_fail_with_multi_appearance_loops():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(k, i, i)\n\n\ndef test_reorder_fail_with_non_single_branch_loop():\n    sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(k, i)\n    sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_c = sch.get_block(\"C\")\n    i, j, k1 = sch.get_loops(block_b)\n    _, _, k2 = sch.get_loops(block_c)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(k1, i, k2)\n\n\ndef test_reorder_fail_with_loops_not_under_same_scope():\n    sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    block_a = sch.get_block(\"A\")\n    i, j = sch.get_loops(block_a)\n    k = sch.get_loops(block_b)[0]\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(k, i)\n\n\ndef test_reorder_fail_with_wrong_block_var_type():\n    sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(k, i)\n\n\ndef test_reorder_fail_with_dependent_loops():\n    sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(l, i)\n\n\ndef test_reorder_fail_not_affine_bindings():\n    sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.reorder(l, i)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_rfactor.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir, topi\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\n@T.prim_func\ndef transformed_matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    C = T.match_buffer(c, [128, 128], dtype=\"float32\")\n\n    for i0, i1, i2_outer, i2_inner_outer, i2_inner_inner in T.grid(128, 128, 4, 8, 4):\n        with T.block(\"update\"):\n            vi, vj = T.axis.remap(\"SS\", [i0, i1])\n            vk = T.axis.R(128, i2_outer * 32 + i2_inner_outer * 4 + i2_inner_inner)\n            T.reads([A[vi, vk], B[vj, vk]])\n            T.writes([C[vi, vj]])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n\n\n@T.prim_func\ndef transformed_matmul_with_let(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    C = T.match_buffer(c, [128, 128], dtype=\"float32\")\n\n    for i0, i1, i2_outer, i2_inner_outer, i2_inner_inner in T.grid(128, 128, 4, 8, 4):\n        with T.block(\"update\"):\n            vi, vj = T.axis.remap(\"SS\", [i0, i1])\n            vk = T.axis.R(128, i2_outer * 32 + i2_inner_outer * 4 + i2_inner_inner)\n            T.reads([A[vi, vk], B[vj, vk]])\n            T.writes([C[vi, vj]])\n            with T.init():\n                C[vi, vj] = 0.0\n            v_C: T.float32 = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n            C[vi, vj] = v_C\n\n\n@T.prim_func\ndef matmul_rfactor(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    C = T.match_buffer(c, [128, 128], dtype=\"float32\")\n    C_rf = T.alloc_buffer([4, 128, 128], dtype=\"float32\")\n\n    for i0, i1, i2_outer, i2_inner_outer, i2_inner_inner in T.grid(128, 128, 4, 8, 4):\n        with T.block(\"update_rf\"):\n            vi2_inner_inner = T.axis.S(4, i2_inner_inner)\n            vi = T.axis.S(128, i0)\n            vj = T.axis.S(128, i1)\n            vi2_outer = T.axis.R(4, i2_outer)\n            vi2_inner_outer = T.axis.R(8, i2_inner_outer)\n            with T.init():\n                C_rf[vi2_inner_inner, vi, vj] = 0.0\n            C_rf[vi2_inner_inner, vi, vj] = C_rf[vi2_inner_inner, vi, vj] + (\n                A[vi, (((vi2_outer * 32) + (vi2_inner_outer * 4)) + vi2_inner_inner)]\n                * B[vj, (((vi2_outer * 32) + (vi2_inner_outer * 4)) + vi2_inner_inner)]\n            )\n\n    for i0_1, i1_1, i2_inner_inner_1 in T.grid(128, 128, 4):\n        with T.block(\"update\"):\n            vi2_inner_inner_1, vi_1, vj_1 = T.axis.remap(\"RSS\", [i2_inner_inner_1, i0_1, i1_1])\n            with T.init():\n                C[vi_1, vj_1] = 0.0\n            C[vi_1, vj_1] = C[vi_1, vj_1] + C_rf[vi2_inner_inner_1, vi_1, vj_1]\n\n\n@T.prim_func\ndef matmul_not_stage_pipeline(a: T.handle, b: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [256, 256])\n    B = T.match_buffer(b, [256, 256])\n    D = T.match_buffer(d, [256, 256])\n    C = T.alloc_buffer([256, 256])\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n    for i, j in T.grid(256, 256):\n        with T.block(\"D\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = C[vi, vj]\n\n\n@T.prim_func\ndef matmul_not_same_buffer_access(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"C\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vj, vi] = C[vj, vi] + A[vi, vk] * B[vk, vj]\n\n\n@T.prim_func\ndef matmul_loop_multiple_children(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    D = T.match_buffer(d, [128, 128])\n\n    for k, i, j in T.grid(128, 128, 128):\n        with T.block(\"C\"):\n            ck, ci, cj = T.axis.remap(\"RSS\", [k, i, j])\n            with T.init():\n                C[ci, cj] = 0.0\n            C[ci, cj] = C[ci, cj] + A[ci, ck] * B[ck, cj]\n        with T.block(\"D\"):\n            dk, di, dj = T.axis.remap(\"RSS\", [k, i, j])\n            with T.init():\n                D[di, dj] = 0.0\n            D[di, dj] = D[di, dj] + B[di, dk] * A[dk, dj]\n\n\n@T.prim_func\ndef square_sum(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    C = T.match_buffer(c, [16])\n\n    for b0, i0, j0 in T.grid(16, 256, 256):\n        with T.block(\"C\"):\n            b, i, j = T.axis.remap(\"SRR\", [b0, i0, j0])\n            with T.init():\n                C[b] = 0.0\n            C[b] = C[b] + A[b, i, j] * A[b, i, j]\n\n\n@T.prim_func\ndef square_sum_rfactor(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    C = T.match_buffer(c, [16])\n    C_rf = T.alloc_buffer([16, 256])\n\n    for i0, i1, i2 in T.grid(16, 256, 256):\n        with T.block(\"C_rf\"):\n            vi2, b, i = T.axis.remap(\"SSR\", [i2, i0, i1])\n            with T.init():\n                C_rf[b, vi2] = 0.0\n            C_rf[b, vi2] = C_rf[b, vi2] + (A[b, i, vi2] * A[b, i, vi2])\n\n    for i0_1, i2_1 in T.grid(16, 256):\n        with T.block(\"C\"):\n            vi2_1, b_1 = T.axis.remap(\"RS\", [i2_1, i0_1])\n            with T.init():\n                C[b_1] = 0.0\n            C[b_1] = C[b_1] + C_rf[b_1, vi2_1]\n\n\n@T.prim_func\ndef transformed_square_sum_square_root(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    D = T.match_buffer(d, [16])\n    C = T.alloc_buffer([16])\n\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 65536, 1):\n        with T.block(\"C\"):\n            b = T.axis.S(16, i0)\n            i = T.axis.R(256, T.floordiv(i1_i2_fused_outer, 256))\n            j = T.axis.R(256, T.floormod(i1_i2_fused_outer, 256))\n            T.reads([A[b, i, j]])\n            T.writes([C[b]])\n            with T.init():\n                C[b] = 0.0\n            C[b] = C[b] + (A[b, i, j] * A[b, i, j])\n    for i0_1 in T.serial(0, 16):\n        with T.block(\"D\"):\n            b_1 = T.axis.S(16, i0_1)\n            T.reads([C[b_1]])\n            T.writes([D[b_1]])\n            D[b_1] = T.sqrt(C[b_1], dtype=\"float32\")\n\n\n@T.prim_func\ndef square_sum_square_root_rfactor(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    D = T.match_buffer(d, [16])\n    C = T.alloc_buffer([16])\n    C_rf = T.alloc_buffer([1, 16])\n\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 65536, 1):\n        with T.block(\"C_rf\"):\n            vi1_i2_fused_inner, b = T.axis.remap(\"SS\", [i1_i2_fused_inner, i0])\n            i = T.axis.R(256, T.floordiv(i1_i2_fused_outer, 256))\n            j = T.axis.R(256, T.floormod(i1_i2_fused_outer, 256))\n            with T.init():\n                C_rf[vi1_i2_fused_inner, b] = 0.0\n            C_rf[vi1_i2_fused_inner, b] = C_rf[vi1_i2_fused_inner, b] + (A[b, i, j] * A[b, i, j])\n\n    for i0_1, i1_i2_fused_inner_1 in T.grid(16, 1):\n        with T.block(\"C\"):\n            vi1_i2_fused_inner_1, b_1 = T.axis.remap(\"RS\", [i1_i2_fused_inner_1, i0_1])\n            with T.init():\n                C[b_1] = 0.0\n            C[b_1] = C[b_1] + C_rf[vi1_i2_fused_inner_1, b_1]\n\n    for i0_2 in T.serial(0, 16):\n        with T.block(\"D\"):\n            b_2 = T.axis.S(16, i0_2)\n            D[b_2] = T.sqrt(C[b_2], dtype=\"float32\")\n\n\n@T.prim_func\ndef transformed_square_sum_square_root_factor_one_1(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    D = T.match_buffer(d, [16])\n    C = T.alloc_buffer([16])\n\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 65536, 1):\n        with T.block(\"C\"):\n            b = T.axis.S(16, i0)\n            i = T.axis.R(256, T.floordiv(i1_i2_fused_outer, 256))\n            j = T.axis.R(256, T.floormod(i1_i2_fused_outer, 256))\n            with T.init():\n                C[b] = 0.0\n            C[b] = C[b] + (A[b, i, j] * A[b, i, j])\n    for i0_1 in T.serial(0, 16):\n        with T.block(\"D\"):\n            b_1 = T.axis.S(16, i0_1)\n            D[b_1] = T.sqrt(C[b_1], dtype=\"float32\")\n\n\n@T.prim_func\ndef square_sum_square_root_factor_one_1_rfactor(\n    A: T.Buffer[(16, 256, 256), \"float32\"], D: T.Buffer[(16,), \"float32\"]\n) -> None:\n    C = T.alloc_buffer([16], dtype=\"float32\")\n    C_rf = T.alloc_buffer([1, 16], dtype=\"float32\")\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 65536, 1):\n        with T.block(\"C_rf\"):\n            b = T.axis.spatial(16, i0)\n            i = T.axis.reduce(256, i1_i2_fused_outer // 256)\n            j = T.axis.reduce(256, i1_i2_fused_outer % 256)\n            vi1_i2_fused_inner = T.axis.spatial(1, i1_i2_fused_inner)\n            with T.init():\n                C_rf[vi1_i2_fused_inner, b] = T.float32(0)\n            C_rf[vi1_i2_fused_inner, b] = C_rf[vi1_i2_fused_inner, b] + A[b, i, j] * A[b, i, j]\n    for i0, i1_i2_fused_inner in T.grid(16, 1):\n        with T.block(\"C\"):\n            b, vi1_i2_fused_inner = T.axis.remap(\"SR\", [i0, i1_i2_fused_inner])\n            with T.init():\n                C[b] = T.float32(0)\n            C[b] = C[b] + C_rf[vi1_i2_fused_inner, b]\n    for i0_1 in T.serial(16):\n        with T.block(\"D\"):\n            b_1 = T.axis.spatial(16, i0_1)\n            D[b_1] = T.sqrt(C[b_1], dtype=\"float32\")\n\n\n@T.prim_func\ndef transformed_square_sum_square_root_factor_one_2(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    D = T.match_buffer(d, [16])\n    C = T.alloc_buffer([16])\n\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 1, 65536):\n        with T.block(\"C\"):\n            b = T.axis.S(16, i0)\n            i = T.axis.R(256, T.floordiv(i1_i2_fused_inner, 256))\n            j = T.axis.R(256, T.floormod(i1_i2_fused_inner, 256))\n            with T.init():\n                C[b] = 0.0\n            C[b] = C[b] + (A[b, i, j] * A[b, i, j])\n    for i0_1 in T.serial(0, 16):\n        with T.block(\"D\"):\n            b_1 = T.axis.S(16, i0_1)\n            D[b_1] = T.sqrt(C[b_1], dtype=\"float32\")\n\n\n@T.prim_func\ndef square_sum_square_root_factor_one_2_rfactor(\n    A: T.Buffer[(16, 256, 256), \"float32\"], D: T.Buffer[(16,), \"float32\"]\n) -> None:\n    C = T.alloc_buffer([16], dtype=\"float32\")\n    C_rf = T.alloc_buffer([16, 1], dtype=\"float32\")\n    for i0, i1_i2_fused_outer, i1_i2_fused_inner in T.grid(16, 1, 65536):\n        with T.block(\"C_rf\"):\n            b = T.axis.spatial(16, i0)\n            i = T.axis.reduce(256, i1_i2_fused_inner // 256)\n            j = T.axis.reduce(256, i1_i2_fused_inner % 256)\n            vi1_i2_fused_outer = T.axis.spatial(1, i1_i2_fused_outer)\n            with T.init():\n                C_rf[b, vi1_i2_fused_outer] = T.float32(0)\n            C_rf[b, vi1_i2_fused_outer] = C_rf[b, vi1_i2_fused_outer] + A[b, i, j] * A[b, i, j]\n    for i0, i1_i2_fused_outer in T.grid(16, 1):\n        with T.block(\"C\"):\n            b, vi1_i2_fused_outer = T.axis.remap(\"SR\", [i0, i1_i2_fused_outer])\n            with T.init():\n                C[b] = T.float32(0)\n            C[b] = C[b] + C_rf[b, vi1_i2_fused_outer]\n    for i0_1 in T.serial(16):\n        with T.block(\"D\"):\n            b_1 = T.axis.spatial(16, i0_1)\n            D[b_1] = T.sqrt(C[b_1], dtype=\"float32\")\n\n\n@T.prim_func\ndef square_sum_with_annotation(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    C = T.match_buffer(c, [16])\n\n    for b0, i0, j0 in T.grid(16, 256, 256):\n        with T.block(\"C\"):\n            T.block_attr({\"test_annotation\": 1})\n            b, i, j = T.axis.remap(\"SRR\", [b0, i0, j0])\n            with T.init():\n                C[b] = 0.0\n            C[b] = C[b] + A[b, i, j] * A[b, i, j]\n\n\n@T.prim_func\ndef square_sum_with_annotation_rfactor(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 256, 256])\n    C = T.match_buffer(c, [16])\n    C_rf = T.alloc_buffer([16, 256])\n\n    for i0, i1, i2 in T.grid(16, 256, 256):\n        with T.block(\"C_rf\"):\n            T.block_attr({\"test_annotation\": 1})\n            vi2, b, i = T.axis.remap(\"SSR\", [i2, i0, i1])\n            with T.init():\n                C_rf[b, vi2] = 0.0\n            C_rf[b, vi2] = C_rf[b, vi2] + (A[b, i, vi2] * A[b, i, vi2])\n\n    for i0_1, i2_1 in T.grid(16, 256):\n        with T.block(\"C\"):\n            T.block_attr({\"test_annotation\": 1})\n            vi2_1, b_1 = T.axis.remap(\"RS\", [i2_1, i0_1])\n            with T.init():\n                C[b_1] = 0.0\n            C[b_1] = C[b_1] + C_rf[b_1, vi2_1]\n\n\n@T.prim_func\ndef element_wise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef rowsum(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_not_quasi_affine(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 16):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            vk = T.axis.R(128, T.floordiv(k * k, 2))\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_not_dominant(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi, vk] = 0.0\n            B[vi, vk] = B[vi, vk] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_not_serial(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i in T.serial(0, 128):\n        for k in T.parallel(0, 128):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                with T.init():\n                    B[vi] = 0.0\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_wrong_reduce_pattern1(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 1.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_wrong_reduce_pattern2(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] - A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_init_not_bufferstore(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for i, k in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vk = T.axis.remap(\"SR\", [i, k])\n            with T.init():\n                v_init: T.float32 = T.float32(0)\n                B[vi] = v_init\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_transformed(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128,))\n\n    for io, ii_ko_fused, ki in T.grid(32, 128, 4):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, io * 4 + T.floordiv(ii_ko_fused, 32))\n            vk = T.axis.R(128, T.floormod(ii_ko_fused, 32) * 4 + ki)\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_zero_dim(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128])\n    B = T.match_buffer(b, [])\n\n    for k0 in range(128):\n        with T.block(\"B\"):\n            k = T.axis.R(128, k0)\n            with T.init():\n                B[()] = 0.0\n            B[()] = B[()] + A[k]\n\n\n@T.prim_func\ndef rowsum_zero_dim_rfactor(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128])\n    B = T.match_buffer(b, [])\n    B_rf = T.alloc_buffer([128])\n\n    for i in range(128):\n        with T.block(\"B_rf\"):\n            vi0 = T.axis.S(128, i)\n            B_rf[vi0] = A[vi0]\n\n    for i in range(128):\n        with T.block(\"B\"):\n            vi0_1 = T.axis.R(128, i)\n            with T.init():\n                B[()] = 0.0\n            B[()] = B[()] + B_rf[vi0_1]\n\n\n@T.prim_func\ndef rowsum_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i, k_0, k_1 in T.grid(128, 13, 10):\n        with T.block(\"B\"):\n            T.where(k_0 * 10 + k_1 < 128)\n            vi = T.axis.S(128, i)\n            vk = T.axis.R(128, k_0 * 10 + k_1)\n            with T.init():\n                B[vi] = 0.0\n            B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef rowsum_predicate_rfactor(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    B_rf = T.alloc_buffer([128, 13], dtype=\"float32\")\n    for i, k_0, k_1 in T.grid(128, 13, 10):\n        with T.block(\"B_rf\"):\n            vk_0, vi, vk_1 = T.axis.remap(\"SSR\", [k_0, i, k_1])\n            T.where(k_0 * 10 + k_1 < 128)\n            with T.init():\n                B_rf[vi, vk_0] = T.float32(0)\n            B_rf[vi, vk_0] = B_rf[vi, vk_0] + A[vi, vk_0 * 10 + vk_1]\n    for i, k_0 in T.grid(128, 13):\n        with T.block(\"B\"):\n            vk_0, vi = T.axis.remap(\"RS\", [k_0, i])\n            with T.init():\n                B[vi] = T.float32(0)\n            B[vi] = B[vi] + B_rf[vi, vk_0]\n\n\n@T.prim_func\ndef multiple_reduction_blocks(a: T.handle, f: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16, 16))\n    C = T.alloc_buffer((16, 16))\n    D = T.alloc_buffer((16, 16))\n    E = T.alloc_buffer((16, 16))\n    F = T.match_buffer(f, (16, 16))\n\n    for i in T.serial(0, 16):\n        for j1 in T.serial(0, 16):\n            for k1o, k1i in T.grid(4, 4):\n                with T.block(\"C\"):\n                    ci, cj = T.axis.remap(\"SS\", [i, j1])\n                    ck = T.axis.R(16, k1o * 4 + k1i)\n                    with T.init():\n                        C[ci, cj] = 0.0\n                    C[ci, cj] = C[ci, cj] + A[ci, cj, ck]\n            for k2o, k2i in T.grid(4, 4):\n                with T.block(\"D\"):\n                    di, dj = T.axis.remap(\"SS\", [i, j1])\n                    dk = T.axis.R(16, k2o * 4 + k2i)\n                    with T.init():\n                        D[di, dj] = 0.0\n                    D[di, dj] = D[di, dj] + A[di, dj, dk] + C[di, dj]\n        for j2 in T.serial(0, 16):\n            for k3o, k3i in T.grid(4, 4):\n                with T.block(\"E\"):\n                    ei, ej = T.axis.remap(\"SS\", [i, j2])\n                    ek = T.axis.R(16, k3o * 4 + k3i)\n                    with T.init():\n                        E[ei, ej] = 0.0\n                    E[ei, ej] = E[ei, ej] + A[ei, ej, ek] + D[ei, ej]\n            for k4o, k4i in T.grid(4, 4):\n                with T.block(\"F\"):\n                    fi, fj = T.axis.remap(\"SS\", [i, j2])\n                    fk = T.axis.R(16, k4o * 4 + k4i)\n                    with T.init():\n                        F[fi, fj] = 0.0\n                    F[fi, fj] = F[fi, fj] + A[fi, fj, fk] + E[fi, fj]\n\n\n@T.prim_func\ndef multiple_reduction_blocks_rfactor(a: T.handle, f: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16, 16])\n    C = T.alloc_buffer([16, 16])\n    D = T.alloc_buffer([16, 16])\n    E = T.alloc_buffer([16, 16])\n    F = T.match_buffer(f, [16, 16])\n    C_rf = T.alloc_buffer([16, 16, 4])\n\n    for i, j1, k1o, k1i in T.grid(16, 16, 4, 4):\n        with T.block(\"C_rf\"):\n            vk1o, ci, cj, vk1i = T.axis.remap(\"SSSR\", [k1o, i, j1, k1i])\n            with T.init():\n                C_rf[ci, cj, vk1o] = 0.0\n            C_rf[ci, cj, vk1o] = C_rf[ci, cj, vk1o] + A[ci, cj, ((vk1o * 4) + vk1i)]\n    for i_1 in T.serial(0, 16):\n        for j1_1 in T.serial(0, 16):\n            for k1o_1 in T.serial(0, 4):\n                with T.block(\"C\"):\n                    vk1o_1, ci_1, cj_1 = T.axis.remap(\"RSS\", [k1o_1, i_1, j1_1])\n                    with T.init():\n                        C[ci_1, cj_1] = 0.0\n                    C[ci_1, cj_1] = C[ci_1, cj_1] + C_rf[ci_1, cj_1, vk1o_1]\n            for k2o, k2i in T.grid(4, 4):\n                with T.block(\"D\"):\n                    di, dj = T.axis.remap(\"SS\", [i_1, j1_1])\n                    dk = T.axis.R(16, k2o * 4 + k2i)\n                    with T.init():\n                        D[di, dj] = 0.0\n                    D[di, dj] = (D[di, dj] + A[di, dj, dk]) + C[di, dj]\n        for j2 in T.serial(0, 16):\n            for k3o, k3i in T.grid(4, 4):\n                with T.block(\"E\"):\n                    ei, ej = T.axis.remap(\"SS\", [i_1, j2])\n                    ek = T.axis.R(16, k3o * 4 + k3i)\n                    with T.init():\n                        E[ei, ej] = 0.0\n                    E[ei, ej] = (E[ei, ej] + A[ei, ej, ek]) + D[ei, ej]\n            for k4o, k4i in T.grid(4, 4):\n                with T.block(\"F\"):\n                    fi, fj = T.axis.remap(\"SS\", [i_1, j2])\n                    fk = T.axis.R(16, k4o * 4 + k4i)\n                    with T.init():\n                        F[fi, fj] = 0.0\n                    F[fi, fj] = (F[fi, fj] + A[fi, fj, fk]) + E[fi, fj]\n\n\n@T.prim_func\ndef rfactor_spatial_only(\n    A: T.Buffer[(1, 512, 7, 7), \"float32\"],\n    B: T.Buffer[(1, 512, 1, 1), \"float32\"],\n) -> None:\n    for _i0, i1, _i2, _i3, i4, _i5 in T.grid(1, 512, 1, 1, 49, 1):\n        with T.block(\"acc\"):\n            ax0 = T.axis.spatial(1, 0)\n            ax1 = T.axis.spatial(512, i1)\n            ax2 = T.axis.spatial(1, 0)\n            ax3 = T.axis.spatial(1, 0)\n            rv0 = T.axis.reduce(7, i4 // 7)\n            rv1 = T.axis.reduce(7, i4 % 7)\n            T.reads(A[ax0, ax1, ax2 * 7 + rv0, ax3 * 7 + rv1])\n            T.writes(B[ax0, ax1, ax2, ax3])\n            with T.init():\n                B[ax0, ax1, ax2, ax3] = T.float32(0)\n            B[ax0, ax1, ax2, ax3] = (\n                B[ax0, ax1, ax2, ax3] + A[ax0, ax1, ax2 * 7 + rv0, ax3 * 7 + rv1]\n            )\n\n\n@T.prim_func\ndef rfactor_spatial_only_after(\n    A: T.Buffer[(1, 512, 7, 7), \"float32\"],\n    B: T.Buffer[(1, 512, 1, 1), \"float32\"],\n) -> None:\n    # body\n    # with T.block(\"root\")\n    B_rf = T.alloc_buffer([1, 512, 1, 1, 49], dtype=\"float32\")\n    for _i0, i1, _i2, _i3, i4, _i5 in T.grid(1, 512, 1, 1, 49, 1):\n        with T.block(\"acc_rf\"):\n            vi4 = T.axis.spatial(49, i4)\n            ax0 = T.axis.spatial(1, 0)\n            ax1 = T.axis.spatial(512, i1)\n            ax2 = T.axis.spatial(1, 0)\n            ax3 = T.axis.spatial(1, 0)\n            B_rf[ax0, ax1, ax2, ax3, vi4] = A[ax0, ax1, ax2 * 7 + vi4 // 7, ax3 * 7 + vi4 % 7]\n    for _i0, i1, _i2, _i3, i4, _i5 in T.grid(1, 512, 1, 1, 49, 1):\n        with T.block(\"acc\"):\n            vi4 = T.axis.reduce(49, i4)\n            ax0 = T.axis.spatial(1, 0)\n            ax1 = T.axis.spatial(512, i1)\n            ax2 = T.axis.spatial(1, 0)\n            ax3 = T.axis.spatial(1, 0)\n            with T.init():\n                B[ax0, ax1, ax2, ax3] = T.float32(0)\n            B[ax0, ax1, ax2, ax3] = B[ax0, ax1, ax2, ax3] + B_rf[ax0, ax1, ax2, ax3, vi4]\n\n\n@T.prim_func\ndef argmax_split(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmin_split_init_update_reordered(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmin_v0: T.Buffer[(128,), \"int32\"],\n    argmin_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmin\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmin_v0[i], argmin_v1[i])\n            with T.init():\n                argmin_v1[i] = T.max_value(\"float32\")\n                argmin_v0[i] = -1\n            v_argmin_v0: T.int32 = T.Select(argmin_v1[i] <= val[i, k], argmin_v0[i], idx[i, k])\n            v_argmin_v1: T.float32 = T.Select(argmin_v1[i] <= val[i, k], argmin_v1[i], val[i, k])\n            argmin_v1[i] = v_argmin_v1\n            argmin_v0[i] = v_argmin_v0\n\n\n@T.prim_func\ndef argmax_split_different_shape(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(256,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_different_indices(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i + 1] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i + 1] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_init_not_bufferstore(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                v1_init: T.float32 = T.min_value(\"float32\")\n                argmax_v1[i] = v1_init\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_init_buffer_duplicate(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v0[i] = -1\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_letstmt_fewer_than_init(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n\n\n@T.prim_func\ndef argmax_split_letstmt_more_than_init(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_let_body_neither_seqstmt_nor_bufferstore(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            T.evaluate(0)\n\n\n@T.prim_func\ndef argmax_split_init_update_inconsistent_bufferstore_number(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_body_seq_not_bufferstore(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            T.evaluate(0)\n\n\n@T.prim_func\ndef argmax_split_body_bufferstore_value_not_var(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_body_bufferstore_value_unbound_var(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    v_unbound = T.var(\"int32\")\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_unbound\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_one_let_var_used_multi_times(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"int32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"int32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"int32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v0\n\n\n@T.prim_func\ndef argmax_split_body_one_buffer_updated_multi_times(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"int32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"int32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"int32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v0[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_init_buffer_not_match(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v0_1: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax\"):\n            i = T.axis.spatial(128, i0)\n            k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n            T.reads(idx[i, k], val[i, k])\n            T.writes(argmax_v0[i], argmax_v0_1[i], argmax_v1[i])\n            with T.init():\n                argmax_v0_1[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n            v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k])\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmax_split_rfactor(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    argmax_v0_rf = T.alloc_buffer([128, 32], dtype=\"int32\")\n    argmax_v1_rf = T.alloc_buffer([128, 32], dtype=\"float32\")\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmax_rf\"):\n            vi1_1, i, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n            T.reads(idx[i, vi1_0 * 32 + vi1_1], val[i, vi1_0 * 32 + vi1_1])\n            T.writes(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1])\n            with T.init():\n                argmax_v0_rf[i, vi1_1] = -1\n                argmax_v1_rf[i, vi1_1] = T.min_value(\"float32\")\n            v_argmax_v0_rf: T.int32 = T.Select(\n                argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 32 + vi1_1],\n                argmax_v0_rf[i, vi1_1],\n                idx[i, vi1_0 * 32 + vi1_1],\n            )\n            v_argmax_v1_rf: T.float32 = T.Select(\n                argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 32 + vi1_1],\n                argmax_v1_rf[i, vi1_1],\n                val[i, vi1_0 * 32 + vi1_1],\n            )\n            argmax_v0_rf[i, vi1_1] = v_argmax_v0_rf\n            argmax_v1_rf[i, vi1_1] = v_argmax_v1_rf\n    for i0, i1_1 in T.grid(128, 32):\n        with T.block(\"argmax\"):\n            vi1_1, i = T.axis.remap(\"RS\", [i1_1, i0])\n            T.reads(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1])\n            T.writes(argmax_v0[i], argmax_v1[i])\n            with T.init():\n                argmax_v0[i] = -1\n                argmax_v1[i] = T.min_value(\"float32\")\n            v_argmax_v0: T.int32 = T.Select(\n                argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v0[i], argmax_v0_rf[i, vi1_1]\n            )\n            v_argmax_v1: T.float32 = T.Select(\n                argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v1[i], argmax_v1_rf[i, vi1_1]\n            )\n            argmax_v0[i] = v_argmax_v0\n            argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef argmin_split_rfactor(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmin_v0: T.Buffer[(128,), \"int32\"],\n    argmin_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    argmin_v0_rf = T.alloc_buffer([128, 32], dtype=\"int32\")\n    argmin_v1_rf = T.alloc_buffer([128, 32], dtype=\"float32\")\n    for i0, i1_0, i1_1 in T.grid(128, 4, 32):\n        with T.block(\"argmin_rf\"):\n            vi1_1, i, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n            T.reads(idx[i, vi1_0 * 32 + vi1_1], val[i, vi1_0 * 32 + vi1_1])\n            T.writes(argmin_v0_rf[i, vi1_1], argmin_v1_rf[i, vi1_1])\n            with T.init():\n                argmin_v0_rf[i, vi1_1] = -1\n                argmin_v1_rf[i, vi1_1] = T.max_value(\"float32\")\n            v_argmin_v0_rf: T.int32 = T.Select(\n                argmin_v1_rf[i, vi1_1] <= val[i, vi1_0 * 32 + vi1_1],\n                argmin_v0_rf[i, vi1_1],\n                idx[i, vi1_0 * 32 + vi1_1],\n            )\n            v_argmin_v1_rf: T.float32 = T.Select(\n                argmin_v1_rf[i, vi1_1] <= val[i, vi1_0 * 32 + vi1_1],\n                argmin_v1_rf[i, vi1_1],\n                val[i, vi1_0 * 32 + vi1_1],\n            )\n            argmin_v0_rf[i, vi1_1] = v_argmin_v0_rf\n            argmin_v1_rf[i, vi1_1] = v_argmin_v1_rf\n    for i0, i1_1 in T.grid(128, 32):\n        with T.block(\"argmin\"):\n            vi1_1, i = T.axis.remap(\"RS\", [i1_1, i0])\n            T.reads(argmin_v0_rf[i, vi1_1], argmin_v1_rf[i, vi1_1])\n            T.writes(argmin_v0[i], argmin_v1[i])\n            with T.init():\n                argmin_v0[i] = -1\n                argmin_v1[i] = T.max_value(\"float32\")\n            v_argmin_v0: T.int32 = T.Select(\n                argmin_v1[i] <= argmin_v1_rf[i, vi1_1], argmin_v0[i], argmin_v0_rf[i, vi1_1]\n            )\n            v_argmin_v1: T.float32 = T.Select(\n                argmin_v1[i] <= argmin_v1_rf[i, vi1_1], argmin_v1[i], argmin_v1_rf[i, vi1_1]\n            )\n            argmin_v0[i] = v_argmin_v0\n            argmin_v1[i] = v_argmin_v1\n\n\n@T.prim_func\ndef argmax_topi_rfactor(\n    placeholder: T.Buffer[(1, 32), \"int32\"], placeholder_red: T.Buffer[1, \"int32\"]\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    placeholder_red_temp_v0 = T.alloc_buffer([1], dtype=\"int32\")\n    placeholder_red_temp_v1 = T.alloc_buffer([1], dtype=\"int32\")\n    placeholder_red_temp_v0_rf = T.alloc_buffer([1, 8], dtype=\"int32\")\n    placeholder_red_temp_v1_rf = T.alloc_buffer([1, 8], dtype=\"int32\")\n    for i0, i1_0, i1_1 in T.grid(1, 4, 8):\n        with T.block(\"placeholder_red_temp_rf\"):\n            vi1_1, ax0, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n            T.reads(placeholder[ax0, vi1_0 * 8 + vi1_1])\n            T.writes(placeholder_red_temp_v0_rf[ax0, vi1_1], placeholder_red_temp_v1_rf[ax0, vi1_1])\n            with T.init():\n                placeholder_red_temp_v0_rf[ax0, vi1_1] = -1\n                placeholder_red_temp_v1_rf[ax0, vi1_1] = -2147483648\n            v_placeholder_red_temp_v0_rf: T.int32 = T.Select(\n                placeholder_red_temp_v1_rf[ax0, vi1_1] > placeholder[ax0, vi1_0 * 8 + vi1_1]\n                or placeholder_red_temp_v1_rf[ax0, vi1_1] == placeholder[ax0, vi1_0 * 8 + vi1_1]\n                and placeholder_red_temp_v0_rf[ax0, vi1_1] < vi1_0 * 8 + vi1_1,\n                placeholder_red_temp_v0_rf[ax0, vi1_1],\n                vi1_0 * 8 + vi1_1,\n            )\n            v_placeholder_red_temp_v1_rf: T.int32 = T.Select(\n                placeholder_red_temp_v1_rf[ax0, vi1_1] > placeholder[ax0, vi1_0 * 8 + vi1_1],\n                placeholder_red_temp_v1_rf[ax0, vi1_1],\n                placeholder[ax0, vi1_0 * 8 + vi1_1],\n            )\n            placeholder_red_temp_v0_rf[ax0, vi1_1] = v_placeholder_red_temp_v0_rf\n            placeholder_red_temp_v1_rf[ax0, vi1_1] = v_placeholder_red_temp_v1_rf\n    for i0, i1_1 in T.grid(1, 8):\n        with T.block(\"placeholder_red_temp\"):\n            vi1_1, ax0 = T.axis.remap(\"RS\", [i1_1, i0])\n            T.reads(placeholder_red_temp_v0_rf[ax0, vi1_1], placeholder_red_temp_v1_rf[ax0, vi1_1])\n            T.writes(placeholder_red_temp_v0[ax0], placeholder_red_temp_v1[ax0])\n            with T.init():\n                placeholder_red_temp_v0[ax0] = -1\n                placeholder_red_temp_v1[ax0] = -2147483648\n            v_placeholder_red_temp_v0: T.int32 = T.Select(\n                placeholder_red_temp_v1[ax0] > placeholder_red_temp_v1_rf[ax0, vi1_1]\n                or placeholder_red_temp_v1[ax0] == placeholder_red_temp_v1_rf[ax0, vi1_1]\n                and placeholder_red_temp_v0[ax0] < placeholder_red_temp_v0_rf[ax0, vi1_1],\n                placeholder_red_temp_v0[ax0],\n                placeholder_red_temp_v0_rf[ax0, vi1_1],\n            )\n            v_placeholder_red_temp_v1: T.int32 = T.Select(\n                placeholder_red_temp_v1[ax0] > placeholder_red_temp_v1_rf[ax0, vi1_1],\n                placeholder_red_temp_v1[ax0],\n                placeholder_red_temp_v1_rf[ax0, vi1_1],\n            )\n            placeholder_red_temp_v0[ax0] = v_placeholder_red_temp_v0\n            placeholder_red_temp_v1[ax0] = v_placeholder_red_temp_v1\n    for i0 in T.serial(1):\n        with T.block(\"placeholder_red\"):\n            ax0 = T.axis.spatial(1, i0)\n            T.reads(placeholder_red_temp_v0[ax0])\n            T.writes(placeholder_red[ax0])\n            placeholder_red[ax0] = placeholder_red_temp_v0[ax0]\n\n\n@T.prim_func\ndef argmin_topi_rfactor(\n    placeholder: T.Buffer[(1, 32), \"int32\"], placeholder_red: T.Buffer[1, \"int32\"]\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    placeholder_red_temp_v0 = T.alloc_buffer([1], dtype=\"int32\")\n    placeholder_red_temp_v1 = T.alloc_buffer([1], dtype=\"int32\")\n    placeholder_red_temp_v0_rf = T.alloc_buffer([1, 8], dtype=\"int32\")\n    placeholder_red_temp_v1_rf = T.alloc_buffer([1, 8], dtype=\"int32\")\n    for i0, i1_0, i1_1 in T.grid(1, 4, 8):\n        with T.block(\"placeholder_red_temp_rf\"):\n            vi1_1, ax0, vi1_0 = T.axis.remap(\"SSR\", [i1_1, i0, i1_0])\n            T.reads(placeholder[ax0, vi1_0 * 8 + vi1_1])\n            T.writes(placeholder_red_temp_v0_rf[ax0, vi1_1], placeholder_red_temp_v1_rf[ax0, vi1_1])\n            with T.init():\n                placeholder_red_temp_v0_rf[ax0, vi1_1] = -1\n                placeholder_red_temp_v1_rf[ax0, vi1_1] = 2147483647\n            v_placeholder_red_temp_v0_rf: T.int32 = T.Select(\n                placeholder_red_temp_v1_rf[ax0, vi1_1] < placeholder[ax0, vi1_0 * 8 + vi1_1]\n                or placeholder_red_temp_v1_rf[ax0, vi1_1] == placeholder[ax0, vi1_0 * 8 + vi1_1]\n                and placeholder_red_temp_v0_rf[ax0, vi1_1] < vi1_0 * 8 + vi1_1,\n                placeholder_red_temp_v0_rf[ax0, vi1_1],\n                vi1_0 * 8 + vi1_1,\n            )\n            v_placeholder_red_temp_v1_rf: T.int32 = T.Select(\n                placeholder_red_temp_v1_rf[ax0, vi1_1] < placeholder[ax0, vi1_0 * 8 + vi1_1],\n                placeholder_red_temp_v1_rf[ax0, vi1_1],\n                placeholder[ax0, vi1_0 * 8 + vi1_1],\n            )\n            placeholder_red_temp_v0_rf[ax0, vi1_1] = v_placeholder_red_temp_v0_rf\n            placeholder_red_temp_v1_rf[ax0, vi1_1] = v_placeholder_red_temp_v1_rf\n    for i0, i1_1 in T.grid(1, 8):\n        with T.block(\"placeholder_red_temp\"):\n            vi1_1, ax0 = T.axis.remap(\"RS\", [i1_1, i0])\n            T.reads(placeholder_red_temp_v0_rf[ax0, vi1_1], placeholder_red_temp_v1_rf[ax0, vi1_1])\n            T.writes(placeholder_red_temp_v0[ax0], placeholder_red_temp_v1[ax0])\n            with T.init():\n                placeholder_red_temp_v0[ax0] = -1\n                placeholder_red_temp_v1[ax0] = 2147483647\n            v_placeholder_red_temp_v0: T.int32 = T.Select(\n                placeholder_red_temp_v1[ax0] < placeholder_red_temp_v1_rf[ax0, vi1_1]\n                or placeholder_red_temp_v1[ax0] == placeholder_red_temp_v1_rf[ax0, vi1_1]\n                and placeholder_red_temp_v0[ax0] < placeholder_red_temp_v0_rf[ax0, vi1_1],\n                placeholder_red_temp_v0[ax0],\n                placeholder_red_temp_v0_rf[ax0, vi1_1],\n            )\n            v_placeholder_red_temp_v1: T.int32 = T.Select(\n                placeholder_red_temp_v1[ax0] < placeholder_red_temp_v1_rf[ax0, vi1_1],\n                placeholder_red_temp_v1[ax0],\n                placeholder_red_temp_v1_rf[ax0, vi1_1],\n            )\n            placeholder_red_temp_v0[ax0] = v_placeholder_red_temp_v0\n            placeholder_red_temp_v1[ax0] = v_placeholder_red_temp_v1\n    for i0 in T.serial(1):\n        with T.block(\"placeholder_red\"):\n            ax0 = T.axis.spatial(1, i0)\n            T.reads(placeholder_red_temp_v0[ax0])\n            T.writes(placeholder_red[ax0])\n            placeholder_red[ax0] = placeholder_red_temp_v0[ax0]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\ndef test_reduction_rfactor_matmul():\n    s = tir.Schedule(transformed_matmul, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    _, _, _, _, kii = s.get_loops(update)\n    rf_block = s.rfactor(kii, 0)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], matmul_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"update_rf\")))\n    assert s.get(update).same_as(s.get(s.get_block(\"update\")))\n    verify_trace_roundtrip(s, mod=transformed_matmul)\n\n\ndef test_reduction_rfactor_matmul_with_let():\n    s = tir.Schedule(transformed_matmul_with_let, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    _, _, _, _, kii = s.get_loops(update)\n    rf_block = s.rfactor(kii, 0)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], matmul_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"update_rf\")))\n    assert s.get(update).same_as(s.get(s.get_block(\"update\")))\n    verify_trace_roundtrip(s, mod=transformed_matmul_with_let)\n\n\ndef test_reduction_rfactor_square_sum():\n    s = tir.Schedule(square_sum, debug_mask=\"all\")\n    C = s.get_block(\"C\")\n    _, _, j = s.get_loops(C)\n    rf_block = s.rfactor(j, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], square_sum_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"C_rf\")))\n    assert s.get(C).same_as(s.get(s.get_block(\"C\")))\n    verify_trace_roundtrip(s, mod=square_sum)\n\n\ndef test_reduction_rfactor_square_sum_square_root():\n    s = tir.Schedule(transformed_square_sum_square_root, debug_mask=\"all\")\n    C = s.get_block(\"C\")\n    _, _, f_i = s.get_loops(C)\n    rf_block = s.rfactor(f_i, 0)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], square_sum_square_root_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"C_rf\")))\n    assert s.get(C).same_as(s.get(s.get_block(\"C\")))\n    verify_trace_roundtrip(s, mod=transformed_square_sum_square_root)\n\n\ndef test_reduction_rfactor_loop_multiple_children():\n    s = tir.Schedule(matmul_loop_multiple_children, debug_mask=\"all\")\n    k, _, _ = s.get_loops(s.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_not_stage_pipeline():\n    s = tir.Schedule(matmul_not_stage_pipeline, debug_mask=\"all\")\n    _, _, k = s.get_loops(s.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_not_reduction_block1():\n    s = tir.Schedule(element_wise, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(i, 0)\n\n\ndef test_reduction_rfactor_not_reduction_block2():\n    s = tir.Schedule(rowsum_not_quasi_affine, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_not_reduction_block3():\n    s = tir.Schedule(rowsum_not_dominant, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_not_serial_loop():\n    s = tir.Schedule(rowsum_not_serial, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_not_same_buffer_access():\n    s = tir.Schedule(matmul_not_same_buffer_access, debug_mask=\"all\")\n    _, _, k = s.get_loops(s.get_block(\"C\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_factor_axis_range_fail():\n    s = tir.Schedule(transformed_matmul, debug_mask=\"all\")\n    _, _, _, _, kii = s.get_loops(s.get_block(\"update\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(kii, 3)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(kii, -4)\n\n\ndef test_reduction_rfactor_factor_axis_range():\n    s = tir.Schedule(transformed_matmul, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    _, _, _, _, kii = s.get_loops(update)\n    rf_block = s.rfactor(kii, -3)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], matmul_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"update_rf\")))\n    assert s.get(update).same_as(s.get(s.get_block(\"update\")))\n    verify_trace_roundtrip(s, mod=transformed_matmul)\n\n\ndef test_reduction_rfactor_wrong_reduce_pattern1():\n    s = tir.Schedule(rowsum_wrong_reduce_pattern1, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_wrong_reduce_pattern2():\n    s = tir.Schedule(rowsum_wrong_reduce_pattern2, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_init_not_bufferstore():\n    s = tir.Schedule(rowsum_init_not_bufferstore, debug_mask=\"all\")\n    _, k = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k, 0)\n\n\ndef test_reduction_rfactor_wrong_loops1():\n    s = tir.Schedule(rowsum, debug_mask=\"all\")\n    i, _ = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(i, 0)\n\n\ndef test_reduction_rfactor_wrong_loops2():\n    s = tir.Schedule(rowsum_transformed, debug_mask=\"all\")\n    _, _, k_i = s.get_loops(s.get_block(\"B\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k_i, 0)\n\n\ndef test_reduction_rfactor_zero_dim():\n    s = tir.Schedule(rowsum_zero_dim, debug_mask=\"all\")\n    B = s.get_block(\"B\")\n    (k,) = s.get_loops(B)\n    rf_block = s.rfactor(k, 0)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], rowsum_zero_dim_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"B_rf\")))\n    assert s.get(B).same_as(s.get(s.get_block(\"B\")))\n    verify_trace_roundtrip(s, mod=rowsum_zero_dim)\n\n\ndef test_reduction_rfactor_outermost_loop_multiple_children_fail():  # pylint: disable=invalid-name\n    s = tir.Schedule(multiple_reduction_blocks, debug_mask=\"all\")\n    _, _, k2o, k2i = s.get_loops(s.get_block(\"D\"))\n    _, _, k3o, k3i = s.get_loops(s.get_block(\"E\"))\n    _, _, k4o, k4i = s.get_loops(s.get_block(\"F\"))\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k2o, 0)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k2i, 0)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k3o, 0)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k3i, 0)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k4o, 0)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(k4i, 0)\n\n\ndef test_reduction_rfactor_outermost_loop_multiple_children():  # pylint: disable=invalid-name\n    s = tir.Schedule(multiple_reduction_blocks, debug_mask=\"all\")\n    C = s.get_block(\"C\")\n    _, _, k1o, _ = s.get_loops(C)\n    rf_block = s.rfactor(k1o, 2)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], multiple_reduction_blocks_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"C_rf\")))\n    assert s.get(C).same_as(s.get(s.get_block(\"C\")))\n    verify_trace_roundtrip(s, mod=multiple_reduction_blocks)\n\n\ndef test_reduction_rfactor_predicate():  # pylint: disable=invalid-name\n    s = tir.Schedule(rowsum_predicate, debug_mask=\"all\")\n    B = s.get_block(\"B\")\n    _, ko, _ = s.get_loops(B)\n    # TODO: should be a tvm.tir.ScheduleError\n    with pytest.raises(tvm.TVMError):\n        rf_block = s.rfactor(ko, 1)\n\n\ndef test_reduction_rfactor_with_annotation():\n    s = tir.Schedule(square_sum_with_annotation, debug_mask=\"all\")\n    C = s.get_block(\"C\")\n    _, _, j = s.get_loops(C)\n    rf_block = s.rfactor(j, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], square_sum_with_annotation_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"C_rf\")))\n    assert s.get(C).same_as(s.get(s.get_block(\"C\")))\n    verify_trace_roundtrip(s, mod=square_sum_with_annotation)\n\n\ndef test_reduction_rfactor_spatial_only():\n    s = tir.Schedule(rfactor_spatial_only, debug_mask=\"all\")\n    block = s.get_block(name=\"acc\", func_name=\"main\")\n    _, _, _, _, loop, _ = s.get_loops(block)\n    rf_block = s.rfactor(loop=loop, factor_axis=4)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], rfactor_spatial_only_after)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"acc_rf\")))\n    assert s.get(block).same_as(s.get(s.get_block(\"acc\")))\n    verify_trace_roundtrip(s, mod=rfactor_spatial_only)\n\n\ndef test_reduction_rfactor_argmax():\n    s = tir.Schedule(argmax_split, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    rf_block = s.rfactor(ki, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], argmax_split_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"argmax_rf\")))\n    assert s.get(argmax).same_as(s.get(s.get_block(\"argmax\")))\n    verify_trace_roundtrip(s, mod=argmax_split)\n\n\ndef test_reduction_rfactor_argmin_init_update_reordeded():\n    s = tir.Schedule(argmin_split_init_update_reordered, debug_mask=\"all\")\n    argmin = s.get_block(\"argmin\")\n    _, _, ki = s.get_loops(argmin)\n    rf_block = s.rfactor(ki, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], argmin_split_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"argmin_rf\")))\n    assert s.get(argmin).same_as(s.get(s.get_block(\"argmin\")))\n    verify_trace_roundtrip(s, mod=argmin_split_init_update_reordered)\n\n\ndef test_reduction_rfactor_argmax_reduction_buffer_different_shape():\n    s = tir.Schedule(argmax_split_different_shape, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_different_access_indices():\n    s = tir.Schedule(argmax_split_different_indices, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_init_not_bufferstore():\n    s = tir.Schedule(argmax_split_init_not_bufferstore, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_init_buffer_duplicate():\n    s = tir.Schedule(argmax_split_init_buffer_duplicate, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_letstmt_fewer_than_init():\n    s = tir.Schedule(argmax_split_letstmt_fewer_than_init, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_letstmt_more_than_init():\n    s = tir.Schedule(argmax_split_letstmt_more_than_init, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_let_body_neither_seqstmt_nor_bufferstore():\n    s = tir.Schedule(argmax_split_let_body_neither_seqstmt_nor_bufferstore, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_init_update_inconsistent_bufferstore_number():\n    s = tir.Schedule(argmax_split_init_update_inconsistent_bufferstore_number, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_body_seq_not_bufferstore():\n    s = tir.Schedule(argmax_split_body_seq_not_bufferstore, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_body_bufferstore_value_not_var():\n    s = tir.Schedule(argmax_split_body_bufferstore_value_not_var, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_body_bufferstore_value_unbound_var():\n    s = tir.Schedule(argmax_split_body_bufferstore_value_unbound_var, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_one_let_var_used_multi_times():\n    s = tir.Schedule(argmax_split_one_let_var_used_multi_times, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_body_one_buffer_updated_multi_times():\n    s = tir.Schedule(argmax_split_body_one_buffer_updated_multi_times, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_argmax_init_buffer_not_match():\n    s = tir.Schedule(argmax_split_init_buffer_not_match, debug_mask=\"all\")\n    argmax = s.get_block(\"argmax\")\n    _, _, ki = s.get_loops(argmax)\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.rfactor(ki, 1)\n\n\ndef test_reduction_rfactor_topi_argmax():\n    A = te.placeholder((1, 32), dtype=\"int32\")\n    B = topi.argmax(A, axis=1)\n    argmax_topi = te.create_prim_func([A, B])\n    s = tir.Schedule(argmax_topi, debug_mask=\"all\")\n    argmax = s.get_block(\"placeholder_red_temp\")\n    _, k = s.get_loops(argmax)\n    _, ki = s.split(k, [None, 8])\n    rf_block = s.rfactor(ki, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], argmax_topi_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"placeholder_red_temp_rf\")))\n    assert s.get(argmax).same_as(s.get(s.get_block(\"placeholder_red_temp\")))\n    verify_trace_roundtrip(s, mod=argmax_topi)\n\n\ndef test_reduction_rfactor_topi_argmin():\n    A = te.placeholder((1, 32), dtype=\"int32\")\n    B = topi.argmin(A, axis=1)\n    argmin_topi = te.create_prim_func([A, B])\n    s = tir.Schedule(argmin_topi, debug_mask=\"all\")\n    argmin = s.get_block(\"placeholder_red_temp\")\n    _, k = s.get_loops(argmin)\n    _, ki = s.split(k, [None, 8])\n    rf_block = s.rfactor(ki, 1)\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], argmin_topi_rfactor)\n    assert s.get(rf_block).same_as(s.get(s.get_block(\"placeholder_red_temp_rf\")))\n    assert s.get(argmin).same_as(s.get(s.get_block(\"placeholder_red_temp\")))\n    verify_trace_roundtrip(s, mod=argmin_topi)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_rolling_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport numpy as np\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\nimport pytest\n\n\ndef check_rolling_buffer(\n    sch: tir.Schedule, origin: tir.PrimFunc, expected: tir.PrimFunc, check_run=False\n):\n    scheduled = sch.mod[\"main\"]\n    tvm.ir.assert_structural_equal(scheduled, expected)\n    verify_trace_roundtrip(sch, origin)\n    if check_run:\n        in_buffer = origin.buffer_map[origin.params[0]]\n        out_buffer = origin.buffer_map[origin.params[1]]\n        in_shape = [int(_) for _ in in_buffer.shape]\n        out_shape = [int(_) for _ in out_buffer.shape]\n        x = tvm.nd.array(np.random.uniform(0, 64, in_shape).astype(in_buffer.dtype))\n        y0 = tvm.nd.array(np.zeros(out_shape).astype(out_buffer.dtype))\n        y1 = tvm.nd.array(np.zeros(out_shape).astype(out_buffer.dtype))\n        f_origin = tvm.build(origin)\n        f_scheduled = tvm.build(scheduled)\n        f_origin(x, y0)\n        f_scheduled(x, y1)\n        tvm.testing.assert_allclose(y0.numpy(), y1.numpy())\n\n\ndef _tile_nd(s, tile, block_name):\n    outer_indices = []\n    inner_indices = []\n    block = s.get_block(block_name)\n    loops = s.get_loops(block)\n    for i, size in enumerate(tile):\n        outer, inner = s.split(loops[i], [None, size])\n        outer_indices.append(outer)\n        inner_indices.append(inner)\n\n    s.reorder(*outer_indices, *inner_indices)\n    return outer_indices, inner_indices\n\n\ndef test_1d_rolling_buffer():\n    @T.prim_func\n    def before(A: T.Buffer[(4, 12), \"int32\"], C: T.Buffer[(4, 8), \"int32\"]):\n        B = T.alloc_buffer((4, 10), \"int32\")\n        for c in T.serial(4):\n            for i in T.serial(0, 10):\n                for k in T.serial(3):\n                    with T.block(\"B\"):\n                        cc, vi, vk = T.axis.remap(\"SSR\", [c, i, k])\n                        with T.init():\n                            B[cc, vi] = 0\n                        B[cc, vi] = B[cc, vi] + A[cc, vi + vk]\n            for i in T.serial(0, 8):\n                for k in T.serial(3):\n                    with T.block(\"C\"):\n                        cc, vi, vk = T.axis.remap(\"SSR\", [c, i, k])\n                        with T.init():\n                            C[cc, vi] = 0\n                        C[cc, vi] = C[cc, vi] + B[cc, vi + vk]\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 12), \"int32\"], C: T.Buffer[(4, 8), \"int32\"]):\n        B = T.alloc_buffer([4, 6], dtype=\"int32\")\n        for c, i_0 in T.grid(4, 2):\n            for ax0, ax1 in T.grid(6, 3):\n                with T.block(\"B\"):\n                    T.where(i_0 < 1 or 2 <= ax0)\n                    cc = T.axis.spatial(4, c)\n                    vi = T.axis.opaque(10, i_0 * 4 + ax0)\n                    vk = T.axis.reduce(3, ax1)\n                    T.reads(A[cc, vi + vk])\n                    T.writes(B[cc, vi % 6])\n                    with T.init():\n                        B[cc, vi % 6] = 0\n                    B[cc, vi % 6] = B[cc, vi % 6] + A[cc, vi + vk]\n            for i_1, k in T.grid(4, 3):\n                with T.block(\"C\"):\n                    cc = T.axis.spatial(4, c)\n                    vi = T.axis.opaque(8, i_0 * 4 + i_1)\n                    vk = T.axis.reduce(3, k)\n                    T.reads(B[cc, (vi + vk) % 6])\n                    T.writes(C[cc, vi])\n                    with T.init():\n                        C[cc, vi] = 0\n                    C[cc, vi] = C[cc, vi] + B[cc, (vi + vk) % 6]\n\n    sch = tir.Schedule(before, debug_mask=\"all\")\n    _, i, _ = sch.get_loops(sch.get_block(\"C\"))\n    io, _ = sch.split(i, [2, 4])\n    sch.compute_at(sch.get_block(\"B\"), io)\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, before, expected, check_run=True)\n\n\n@T.prim_func\ndef cascade_2_max_pool2d(A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]):\n    B = T.alloc_buffer([1, 10, 10, 16], dtype=\"int8\")\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 10, 10, 16, 3, 3):\n        with T.block(\"B\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                B[ax0, ax1, ax2, ax3] = T.int8(-128)\n            B[ax0, ax1, ax2, ax3] = T.max(B[ax0, ax1, ax2, ax3], A[ax0, ax1 + rv0, ax2 + rv1, ax3])\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 8, 8, 16, 3, 3):\n        with T.block(\"C\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                C[ax0, ax1, ax2, ax3] = T.int8(-128)\n            C[ax0, ax1, ax2, ax3] = T.max(C[ax0, ax1, ax2, ax3], B[ax0, ax1 + rv0, ax2 + rv1, ax3])\n\n\n@T.prim_func\ndef cascade_3_max_pool2d_with_stride(\n    A: T.Buffer[(1, 24, 24, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]\n):\n    B_0 = T.alloc_buffer([1, 22, 22, 16], dtype=\"int8\")\n    B_1 = T.alloc_buffer([1, 10, 10, 16], dtype=\"int8\")\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 22, 22, 16, 3, 3):\n        with T.block(\"B_0\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                B_0[ax0, ax1, ax2, ax3] = T.int8(-128)\n            B_0[ax0, ax1, ax2, ax3] = T.max(\n                B_0[ax0, ax1, ax2, ax3], A[ax0, ax1 + rv0, ax2 + rv1, ax3]\n            )\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 10, 10, 16, 3, 3):\n        with T.block(\"B_1\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                B_1[ax0, ax1, ax2, ax3] = T.int8(-128)\n            B_1[ax0, ax1, ax2, ax3] = T.max(\n                B_1[ax0, ax1, ax2, ax3], B_0[ax0, ax1 * 2 + rv0, ax2 * 2 + rv1, ax3]\n            )\n    for i0, i1, i2, i3, i4, i5 in T.grid(1, 8, 8, 16, 3, 3):\n        with T.block(\"C\"):\n            ax0, ax1, ax2, ax3, rv0, rv1 = T.axis.remap(\"SSSSRR\", [i0, i1, i2, i3, i4, i5])\n            with T.init():\n                C[ax0, ax1, ax2, ax3] = T.int8(-128)\n            C[ax0, ax1, ax2, ax3] = T.max(\n                C[ax0, ax1, ax2, ax3], B_1[ax0, ax1 + rv0, ax2 + rv1, ax3]\n            )\n\n\ndef test_cascade_max_pool2d_w_tiled():\n    @T.prim_func\n    def expected(A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]):\n        B = T.alloc_buffer([1, 10, 6, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 2, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(10, 6, 16, 3, 3):\n                with T.block(\"B\"):\n                    T.where(i2_0 < 1 or 2 <= ax1)\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(10, ax0)\n                    ax2_1 = T.axis.opaque(10, i2_0 * 4 + ax1)\n                    ax3_1, rv0, rv1 = T.axis.remap(\"SRR\", [ax2, ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1, ax2_1 % 6, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1, ax2_1 % 6, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1, ax2_1 % 6, ax3_1] = T.max(\n                        B[ax0_1, ax1_1, ax2_1 % 6, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 8, 4, 16, 3, 3):\n                with T.block(\"C\"):\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.spatial(8, i1_0 * 8 + i1_1)\n                    ax2 = T.axis.opaque(8, i2_0 * 4 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, ax1 + rv0, (ax2 + rv1) % 6, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, ax1 + rv0, (ax2 + rv1) % 6, ax3]\n                    )\n\n    sch = tir.Schedule(cascade_2_max_pool2d, debug_mask=\"all\")\n    oi, _ = _tile_nd(sch, [1, 8, 4, 16], \"C\")\n    sch.compute_at(sch.get_block(\"B\"), oi[-1])\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, cascade_2_max_pool2d, expected, check_run=True)\n\n\ndef test_cascade_max_pool2d_h_tiled():\n    @T.prim_func\n    def expected(A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]):\n        B = T.alloc_buffer([1, 6, 10, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 2, 1, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(6, 10, 16, 3, 3):\n                with T.block(\"B\"):\n                    T.where(i1_0 < 1 or 2 <= ax0)\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.opaque(10, i1_0 * 4 + ax0)\n                    ax2_1 = T.axis.spatial(10, ax1)\n                    ax3_1, rv0, rv1 = T.axis.remap(\"SRR\", [ax2, ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1 % 6, ax2_1, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1 % 6, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1 % 6, ax2_1, ax3_1] = T.max(\n                        B[ax0_1, ax1_1 % 6, ax2_1, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 4, 8, 16, 3, 3):\n                with T.block(\"C\"):\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.opaque(8, i1_0 * 4 + i1_1)\n                    ax2 = T.axis.spatial(8, i2_0 * 8 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, (ax1 + rv0) % 6, ax2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, (ax1 + rv0) % 6, ax2 + rv1, ax3]\n                    )\n\n    sch = tir.Schedule(cascade_2_max_pool2d, debug_mask=\"all\")\n    io, _ = _tile_nd(sch, [1, 4, 8, 16], \"C\")\n    sch.compute_at(sch.get_block(\"B\"), io[-1])\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, cascade_2_max_pool2d, expected, check_run=True)\n\n\ndef test_cascade_max_pool2d_h_w_c_tiled():\n    @T.prim_func\n    def expected(A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]):\n        B = T.alloc_buffer([1, 6, 10, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 2, 2, 2):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(6, 6, 8, 3, 3):\n                with T.block(\"B\"):\n                    T.where((i1_0 < 1 or 2 <= ax0) and (i2_0 < 1 or 2 <= ax1))\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.opaque(10, i1_0 * 4 + ax0)\n                    ax2_1 = T.axis.spatial(10, i2_0 * 4 + ax1)\n                    ax3_1 = T.axis.spatial(16, i3_0 * 8 + ax2)\n                    rv0, rv1 = T.axis.remap(\"RR\", [ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1 % 6, ax2_1, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1 % 6, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1 % 6, ax2_1, ax3_1] = T.max(\n                        B[ax0_1, ax1_1 % 6, ax2_1, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 4, 4, 8, 3, 3):\n                with T.block(\"C\"):\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.opaque(8, i1_0 * 4 + i1_1)\n                    ax2 = T.axis.spatial(8, i2_0 * 4 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 8 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, (ax1 + rv0) % 6, ax2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, (ax1 + rv0) % 6, ax2 + rv1, ax3]\n                    )\n\n    sch = tir.Schedule(cascade_2_max_pool2d, debug_mask=\"all\")\n    io, _ = _tile_nd(sch, [1, 4, 4, 8], \"C\")\n    sch.compute_at(sch.get_block(\"B\"), io[-1])\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, cascade_2_max_pool2d, expected, check_run=True)\n\n\ndef test_cascade_max_pool2d_non_perfect_tiled():\n    @T.prim_func\n    def expected(A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]) -> None:\n        B = T.alloc_buffer([1, 8, 10, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 2, 2, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(8, 8, 16, 3, 3):\n                with T.block(\"B\"):\n                    T.where(\n                        i1_0 * 6 + ax0 < 10\n                        and i2_0 * 6 + ax1 < 10\n                        and (i1_0 < 1 or 2 <= ax0)\n                        and (i2_0 < 1 or 2 <= ax1)\n                    )\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.opaque(10, i1_0 * 6 + ax0)\n                    ax2_1 = T.axis.spatial(10, i2_0 * 6 + ax1)\n                    ax3_1, rv0, rv1 = T.axis.remap(\"SRR\", [ax2, ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1 % 8, ax2_1, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1 % 8, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1 % 8, ax2_1, ax3_1] = T.max(\n                        B[ax0_1, ax1_1 % 8, ax2_1, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 6, 6, 16, 3, 3):\n                with T.block(\"C\"):\n                    T.where(i1_0 * 6 + i1_1 < 8 and i2_0 * 6 + i2_1 < 8)\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.opaque(8, i1_0 * 6 + i1_1)\n                    ax2 = T.axis.spatial(8, i2_0 * 6 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, (ax1 + rv0) % 8, ax2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, (ax1 + rv0) % 8, ax2 + rv1, ax3]\n                    )\n\n    sch = tir.Schedule(cascade_2_max_pool2d, debug_mask=\"all\")\n    io, _ = _tile_nd(sch, [1, 6, 6, 16], \"C\")\n    sch.compute_at(sch.get_block(\"B\"), io[-1])\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, cascade_2_max_pool2d, expected, check_run=True)\n\n\ndef test_cascade_3_max_pool2d_with_stride():\n    @T.prim_func\n    def expected(A: T.Buffer[(1, 24, 24, 16), \"int8\"], C: T.Buffer[(1, 8, 8, 16), \"int8\"]) -> None:\n        B_0 = T.alloc_buffer([1, 13, 22, 16], dtype=\"int8\")\n        B_1 = T.alloc_buffer([1, 6, 10, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 2, 2, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(13, 13, 16, 3, 3):\n                with T.block(\"B_0\"):\n                    T.where((i1_0 < 1 or 5 <= ax0) and (i2_0 < 1 or 5 <= ax1))\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.opaque(22, i1_0 * 8 + ax0)\n                    ax2_1 = T.axis.spatial(22, i2_0 * 8 + ax1)\n                    ax3_1, rv0, rv1 = T.axis.remap(\"SRR\", [ax2, ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B_0[ax0_1, ax1_1 % 13, ax2_1, ax3_1])\n                    with T.init():\n                        B_0[ax0_1, ax1_1 % 13, ax2_1, ax3_1] = T.int8(-128)\n                    B_0[ax0_1, ax1_1 % 13, ax2_1, ax3_1] = T.max(\n                        B_0[ax0_1, ax1_1 % 13, ax2_1, ax3_1],\n                        A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1],\n                    )\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(6, 6, 16, 3, 3):\n                with T.block(\"B_1\"):\n                    T.where((i1_0 < 1 or 2 <= ax0) and (i2_0 < 1 or 2 <= ax1))\n                    ax0_2 = T.axis.spatial(1, 0)\n                    ax1_2 = T.axis.opaque(10, i1_0 * 4 + ax0)\n                    ax2_2 = T.axis.spatial(10, i2_0 * 4 + ax1)\n                    ax3_2, rv0, rv1 = T.axis.remap(\"SRR\", [ax2, ax3, ax4])\n                    T.reads(B_0[ax0_2, (ax1_2 * 2 + rv0) % 13, ax2_2 * 2 + rv1, ax3_2])\n                    T.writes(B_1[ax0_2, ax1_2 % 6, ax2_2, ax3_2])\n                    with T.init():\n                        B_1[ax0_2, ax1_2 % 6, ax2_2, ax3_2] = T.int8(-128)\n                    B_1[ax0_2, ax1_2 % 6, ax2_2, ax3_2] = T.max(\n                        B_1[ax0_2, ax1_2 % 6, ax2_2, ax3_2],\n                        B_0[ax0_2, (ax1_2 * 2 + rv0) % 13, ax2_2 * 2 + rv1, ax3_2],\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 4, 4, 16, 3, 3):\n                with T.block(\"C\"):\n                    ax0_3 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1_3 = T.axis.opaque(8, i1_0 * 4 + i1_1)\n                    ax2_3 = T.axis.spatial(8, i2_0 * 4 + i2_1)\n                    ax3_3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B_1[ax0_3, (ax1_3 + rv0) % 6, ax2_3 + rv1, ax3_3])\n                    T.writes(C[ax0_3, ax1_3, ax2_3, ax3_3])\n                    with T.init():\n                        C[ax0_3, ax1_3, ax2_3, ax3_3] = T.int8(-128)\n                    C[ax0_3, ax1_3, ax2_3, ax3_3] = T.max(\n                        C[ax0_3, ax1_3, ax2_3, ax3_3],\n                        B_1[ax0_3, (ax1_3 + rv0) % 6, ax2_3 + rv1, ax3_3],\n                    )\n\n    sch = tir.Schedule(cascade_3_max_pool2d_with_stride, debug_mask=\"all\")\n    io, _ = _tile_nd(sch, [1, 4, 4, 16], \"C\")\n    sch.compute_at(sch.get_block(\"B_1\"), io[-1])\n    sch.compute_at(sch.get_block(\"B_0\"), io[-1])\n    sch.rolling_buffer(sch.get_block(\"B_0\"), 0)\n    sch.rolling_buffer(sch.get_block(\"B_1\"), 0)\n    check_rolling_buffer(sch, cascade_3_max_pool2d_with_stride, expected, check_run=True)\n\n\ndef test_upscale():\n    @T.prim_func\n    def before(A: T.Buffer[(1, 16, 16, 16), \"int8\"], C: T.Buffer[(1, 24, 24, 16), \"int8\"]) -> None:\n        B = T.alloc_buffer([1, 14, 14, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 5, 5, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(5, 5, 16, 3, 3):\n                with T.block(\"B\"):\n                    T.where(i1_0 * 5 // 2 + ax0 < 14 and i2_0 * 5 // 2 + ax1 < 14)\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(14, i1_0 * 5 // 2 + ax0)\n                    ax2_1 = T.axis.spatial(14, i2_0 * 5 // 2 + ax1)\n                    ax3_1 = T.axis.spatial(16, ax2)\n                    rv0, rv1 = T.axis.remap(\"RR\", [ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1, ax2_1, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1, ax2_1, ax3_1] = T.max(\n                        B[ax0_1, ax1_1, ax2_1, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 5, 5, 16, 3, 3):\n                with T.block(\"C\"):\n                    T.where(i1_0 * 5 + i1_1 < 24 and i2_0 * 5 + i2_1 < 24)\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.spatial(24, i1_0 * 5 + i1_1)\n                    ax2 = T.axis.spatial(24, i2_0 * 5 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, ax1 // 2 + rv0, ax2 // 2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, ax1 // 2 + rv0, ax2 // 2 + rv1, ax3]\n                    )\n\n    @T.prim_func\n    def expected(\n        A: T.Buffer[(1, 16, 16, 16), \"int8\"], C: T.Buffer[(1, 24, 24, 16), \"int8\"]\n    ) -> None:\n        B = T.alloc_buffer([1, 5, 14, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 5, 5, 1):\n            for ax0, ax1, ax2, ax3, ax4 in T.grid(5, 5, 16, 3, 3):\n                with T.block(\"B\"):\n                    T.where(\n                        i1_0 * 5 // 2 + ax0 < 14\n                        and i2_0 * 5 // 2 + ax1 < 14\n                        and (i1_0 < 1 or 2 <= ax0)\n                        and (i2_0 < 1 or 2 <= ax1)\n                    )\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.opaque(14, i1_0 * 5 // 2 + ax0)\n                    ax2_1 = T.axis.spatial(14, i2_0 * 5 // 2 + ax1)\n                    ax3_1 = T.axis.spatial(16, ax2)\n                    rv0, rv1 = T.axis.remap(\"RR\", [ax3, ax4])\n                    T.reads(A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1])\n                    T.writes(B[ax0_1, ax1_1 % 5, ax2_1, ax3_1])\n                    with T.init():\n                        B[ax0_1, ax1_1 % 5, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1 % 5, ax2_1, ax3_1] = T.max(\n                        B[ax0_1, ax1_1 % 5, ax2_1, ax3_1], A[ax0_1, ax1_1 + rv0, ax2_1 + rv1, ax3_1]\n                    )\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 5, 5, 16, 3, 3):\n                with T.block(\"C\"):\n                    T.where(i1_0 * 5 + i1_1 < 24 and i2_0 * 5 + i2_1 < 24)\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.opaque(24, i1_0 * 5 + i1_1)\n                    ax2 = T.axis.spatial(24, i2_0 * 5 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, (ax1 // 2 + rv0) % 5, ax2 // 2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, (ax1 // 2 + rv0) % 5, ax2 // 2 + rv1, ax3]\n                    )\n\n    sch = tir.Schedule(before, debug_mask=\"all\")\n    sch.rolling_buffer(sch.get_block(\"B\"), 0)\n    check_rolling_buffer(sch, before, expected, check_run=True)\n\n\ndef test_fail_rolling_buffer_multi_writers():\n    @T.prim_func\n    def func_multi_writers(\n        A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 12, 12, 16), \"int8\"]\n    ):\n        B = T.alloc_buffer([1, 12, 12, 16], dtype=\"int8\")\n        for i0, i1, i2, i3 in T.grid(1, 3, 3, 1):\n            for ax0, ax1, ax2 in T.grid(6, 6, 16):\n                with T.block(\"B_writer_0\"):\n                    ax0_1 = T.axis.spatial(1, i0)\n                    ax1_1 = T.axis.spatial(12, i1 * 4 + ax0)\n                    ax2_1 = T.axis.spatial(12, i2 * 4 + ax1)\n                    ax3_1 = T.axis.spatial(16, ax2)\n                    with T.init():\n                        B[ax0_1, ax1_1, ax2_1, ax3_1] = T.int8(-128)\n                    B[ax0_1, ax1_1, ax2_1, ax3_1] = A[ax0_1, ax1_1, ax2_1, ax3_1] + T.int8(1)\n            for ax0, ax1, ax2 in T.grid(6, 6, 16):\n                with T.block(\"B_writer_1\"):\n                    ax0_2 = T.axis.spatial(1, i0)\n                    ax1_2 = T.axis.spatial(12, i1 * 4 + ax0)\n                    ax2_2 = T.axis.spatial(12, i2 * 4 + ax1)\n                    ax3_2 = T.axis.spatial(16, ax2)\n                    with T.init():\n                        B[ax0_2, ax1_2, ax2_2, ax3_2] = T.int8(-128)\n                    B[ax0_2, ax1_2, ax2_2, ax3_2] = B[ax0_2, ax1_2, ax2_2, ax3_2] + A[\n                        ax0_2, ax1_2, ax2_2, ax3_2\n                    ] * T.int8(2)\n            for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 4, 4, 16, 3, 3):\n                with T.block(\"C\"):\n                    ax0_3 = T.axis.spatial(1, i0 + ax0)\n                    ax1_3 = T.axis.spatial(12, i1 * 4 + ax1)\n                    ax2_3 = T.axis.spatial(12, i2 * 4 + ax2)\n                    ax3_3 = T.axis.spatial(16, i3 * 16 + ax3)\n                    rv0, rv1 = T.axis.remap(\"RR\", [ax4, ax5])\n                    with T.init():\n                        C[ax0_3, ax1_3, ax2_3, ax3_3] = T.int8(-128)\n                    C[ax0_3, ax1_3, ax2_3, ax3_3] = T.max(\n                        C[ax0_3, ax1_3, ax2_3, ax3_3], B[ax0_3, ax1_3 + rv0, ax2_3 + rv1, ax3_3]\n                    )\n\n    sch = tir.Schedule(func_multi_writers, debug_mask=\"all\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.rolling_buffer(sch.get_block(\"B_writer_0\"), 0)\n\n\ndef test_fail_rolling_buffer_not_match():\n    @T.prim_func\n    def func_non_overlap(\n        A: T.Buffer[(1, 12, 12, 16), \"int8\"], C: T.Buffer[(1, 12, 12, 16), \"int8\"]\n    ):\n        B = T.alloc_buffer([1, 12, 12, 16], dtype=\"int8\")\n        for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 3, 3, 1):\n            for ax0, ax1, ax2 in T.grid(4, 4, 16):\n                with T.block(\"B\"):\n                    ax0_1 = T.axis.spatial(1, 0)\n                    ax1_1 = T.axis.spatial(12, i1_0 * 4 + ax0)\n                    ax2_1 = T.axis.spatial(12, i2_0 * 4 + ax1)\n                    ax3 = T.axis.spatial(16, ax2)\n                    T.reads(A[ax0_1, ax1_1, ax2_1, ax3])\n                    T.writes(B[ax0_1, ax1_1, ax2_1, ax3])\n                    with T.init():\n                        B[ax0_1, ax1_1, ax2_1, ax3] = T.int8(-128)\n                    B[ax0_1, ax1_1, ax2_1, ax3] = A[ax0_1, ax1_1, ax2_1, ax3]\n            for i0_1, i1_1, i2_1, i3_1, i4, i5 in T.grid(1, 4, 4, 16, 1, 1):\n                with T.block(\"C\"):\n                    ax0 = T.axis.spatial(1, i0_0 + i0_1)\n                    ax1 = T.axis.spatial(12, i1_0 * 4 + i1_1)\n                    ax2 = T.axis.spatial(12, i2_0 * 4 + i2_1)\n                    ax3 = T.axis.spatial(16, i3_0 * 16 + i3_1)\n                    rv0, rv1 = T.axis.remap(\"RR\", [i4, i5])\n                    T.reads(B[ax0, ax1 + rv0, ax2 + rv1, ax3])\n                    T.writes(C[ax0, ax1, ax2, ax3])\n                    with T.init():\n                        C[ax0, ax1, ax2, ax3] = T.int8(-128)\n                    C[ax0, ax1, ax2, ax3] = T.max(\n                        C[ax0, ax1, ax2, ax3], B[ax0, ax1 + rv0, ax2 + rv1, ax3]\n                    )\n\n    sch = tir.Schedule(func_non_overlap, debug_mask=\"all\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.rolling_buffer(sch.get_block(\"B\"), 0)\n\n\ndef test_fail_rolling_buffer_injection_invalid():\n    sch = tir.Schedule(cascade_2_max_pool2d, debug_mask=\"all\")\n    # Block B is not compute_at to Block C, so rolling_buffer injection is invalid.\n    _, _ = _tile_nd(sch, [1, 4, 8, 16], \"C\")\n    _, _ = _tile_nd(sch, [1, 4, 8, 16], \"B\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.rolling_buffer(sch.get_block(\"B\"), 0)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_sampling.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom collections import defaultdict\nimport sys\n\nimport numpy\nimport pytest\nimport tvm.testing\n\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 257, 1470))\n    B = T.match_buffer(b, (128, 257, 1470))\n    for i, j, k in T.grid(128, 257, 1470):\n        with T.block(\"B\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef tiled_conv2d_with_padding(\n    inputs: T.Buffer[(1, 224, 224, 3), \"float32\"],\n    weight: T.Buffer[(7, 7, 3, 64), \"float32\"],\n    conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"],\n) -> None:\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            T.reads(inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1])\n            T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                3 <= i1_1 and i1_1 < 227 and 3 <= i2_1 and i2_1 < 227,\n                inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for (\n        i0_0,\n        i1_0,\n        i2_0,\n        i3_0,\n        i0_1_1,\n        i1_1_1,\n        i2_1_1,\n        i3_1_1,\n        i4_0,\n        i5_0,\n        i6_0,\n        i0_2,\n        i1_2,\n        i2_2,\n        i3_2,\n        i4_1,\n        i5_1,\n        i6_1,\n        i0_3,\n        i1_3,\n        i2_3,\n        i3_3,\n    ) in T.grid(1, 1, 4, 1, 1, 2, 4, 1, 7, 7, 1, 1, 1, 1, 1, 1, 1, 3, 1, 56, 7, 64):\n        with T.block(\"conv2d_nhwc\"):\n            n = T.axis.spatial(1, 0)\n            h = T.axis.spatial(112, i1_1_1 * 56 + i1_3)\n            w = T.axis.spatial(112, i2_0 * 28 + i2_1_1 * 7 + i2_3)\n            co, rh, rw, rc = T.axis.remap(\"SRRR\", [i3_3, i4_0, i5_0, i6_1])\n            T.reads(\n                conv2d_nhwc[n, h, w, co],\n                PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc],\n                weight[rh, rw, rc, co],\n            )\n            T.writes(conv2d_nhwc[n, h, w, co])\n            with T.init():\n                conv2d_nhwc[n, h, w, co] = T.float32(0)\n            conv2d_nhwc[n, h, w, co] = (\n                conv2d_nhwc[n, h, w, co]\n                + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co]\n            )\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef test_sample_categorical():\n    \"\"\"Test sample categorical sampling function\"\"\"\n    n = 1000\n    sch = tir.Schedule(elementwise, seed=42, debug_mask=\"all\")\n    counter = defaultdict(int)\n    candidates = [5, 2, 7, 1]\n    probs = [0.15, 0.55, 0.05, 0.25]\n    for _ in range(n):\n        v = sch.get(sch.sample_categorical(candidates, probs))\n        counter[v] += 1\n    for i, prob in enumerate(probs):\n        assert (prob - 0.07) * n <= counter[candidates[i]] <= (prob + 0.07) * n\n    verify_trace_roundtrip(sch, mod=elementwise)\n\n\ndef test_sample_categorical_copy():\n    \"\"\"Check the random variable sampling results after schedule copy\"\"\"\n    n = 100\n    sch = tir.Schedule(elementwise, seed=42, debug_mask=\"all\")\n    candidates = [1, 2, 3, 4]\n    probs = [0.1, 0.2, 0.3, 0.4]\n    rv_decisions = []\n    for _ in range(n):\n        rv = sch.sample_categorical(candidates, probs)  # pylint: disable=invalid-name\n        rv_decisions.append((rv, sch.get(rv)))\n    sch_copy = sch.copy()\n    for rv, decision in rv_decisions:  # pylint: disable=invalid-name\n        decision_copy = sch_copy.get(rv)\n        assert int(decision) == int(decision_copy)\n\n\ndef test_sample_categorical_serialize():\n    \"\"\"Check the random variable sampling results after schedule serialization\"\"\"\n    n = 100\n    sch = tir.Schedule(elementwise, seed=42, debug_mask=\"all\")\n    candidates = [5, 6, 7, 8]\n    probs = [0.23, 0.19, 0.37, 0.21]\n    decisions = []\n    for _ in range(n):\n        rv = sch.get(sch.sample_categorical(candidates, probs))  # pylint: disable=invalid-name\n        decisions.append(rv)\n    new_sch = verify_trace_roundtrip(sch, mod=elementwise)\n    for i, new_inst in enumerate(new_sch.trace.insts):\n        assert decisions[i] == candidates[new_sch.trace.decisions[new_inst].value]\n\n\ndef test_sample_perfect_tile_power_of_two():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    i, _, _ = sch.get_loops(sch.get_block(\"B\"))\n    factors = sch.sample_perfect_tile(i, n=4)\n    factors = [sch.get(i) for i in factors]\n    prod = factors[0] * factors[1] * factors[2] * factors[3]\n    assert prod == 128\n    verify_trace_roundtrip(sch, mod=elementwise)\n\n\ndef test_sample_perfect_tile_prime():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    _, i, _ = sch.get_loops(sch.get_block(\"B\"))\n    factors = sch.sample_perfect_tile(i, n=4)\n    factors = [sch.get(i) for i in factors]\n    prod = factors[0] * factors[1] * factors[2] * factors[3]\n    assert prod == 257\n    verify_trace_roundtrip(sch, mod=elementwise)\n\n\ndef test_sample_perfect_tile_composite():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    _, _, i = sch.get_loops(sch.get_block(\"B\"))\n    factors = sch.sample_perfect_tile(i, n=4)\n    factors = [sch.get(i) for i in factors]\n    prod = factors[0] * factors[1] * factors[2] * factors[3]\n    assert prod == 1470\n    verify_trace_roundtrip(sch, mod=elementwise)\n\n\nuse_sugared_block = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_sample_compute_location(use_sugared_block):\n    n = 100\n    sch = tir.Schedule(tiled_conv2d_with_padding, seed=42, debug_mask=\"all\")\n    if use_sugared_block:\n        pad_input = \"PadInput\"\n    else:\n        pad_input = sch.get_block(\"PadInput\")\n    decision_dict = dict()\n    for _ in range(n):\n        _ = sch.sample_compute_location(pad_input)  # pylint: disable=invalid-name\n        decision = sch.trace.decisions[sch.trace.insts[-1]]\n        decision_dict[decision] = decision_dict[decision] + 1 if decision in decision_dict else 1\n\n    n_candidates = 8\n    expected_rate = 1.0 / n_candidates\n    for _, cnt in decision_dict.items():\n        numpy.testing.assert_allclose(expected_rate, cnt / n, atol=0.04)\n\n\ndef test_sample_perfect_tile_after_copy():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    sch_copy = sch.copy()\n    _, _, i = sch.get_loops(sch.get_block(\"B\"))\n    sch.sample_perfect_tile(i, n=4)\n\n    _, _, i = sch_copy.get_loops(sch_copy.get_block(\"B\"))\n    # Hangs if ForkSeed is not invoked when copying a schedule\n    sch_copy.sample_perfect_tile(i, n=4)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_set_axis_separator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.tir import IndexMap\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n@T.prim_func\ndef element_wise(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_set_axis_separator(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer([128, 128], dtype=\"float32\", axis_separators=[1])\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\n@T.prim_func\ndef element_wise_set_axis_separator_input_buffer(A: T.Buffer(shape=(128, 128), dtype=\"float32\", axis_separators=(1,)), C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer([128, 128], dtype=\"float32\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\n@T.prim_func\ndef element_wise_subregion_match(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion0 = T.match_buffer(B[vi, vj], [], offset_factor=1)\n            B_subregion0[()] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion1 = T.match_buffer(B[vi, vj], [], offset_factor=1)\n            C[vi, vj] = B_subregion1[()] + 1.0\n\n\n@T.prim_func\ndef element_wise_subregion_match_set_axis_separator(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer([128, 128], dtype=\"float32\", axis_separators=[1])\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion0 = T.match_buffer(B[vi, vj], [], dtype=\"float32\", offset_factor=1, axis_separators=[1])\n            B_subregion0[()] = A[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion1 = T.match_buffer(B[vi, vj], [], dtype=\"float32\", offset_factor=1, axis_separators=[1])\n            C[vi, vj] = B_subregion1[()] + T.float32(1)\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\nargument_style = tvm.testing.parameter('set_axis_separators',\n                                      'transform_layout_named',\n                                      'transform_layout_buffer_object',\n                                      )\n\n\ndef test_set_axis_separator(argument_style):\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n\n    if argument_style=='set_axis_separators':\n        s.set_axis_separator(s.get_block(\"B\"), (\"write\",0), [1])\n    elif argument_style=='transform_layout_named':\n        s.transform_layout(block='B', buffer='B', index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    elif argument_style =='transform_layout_buffer_object':\n        B = s.get(s.get_block('B')).writes[0].buffer\n        s.transform_layout(block='B', buffer=B, index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    else:\n        raise ValueError(f'Unexpected argument_style: {argument_style}')\n\n    tvm.ir.assert_structural_equal(element_wise_set_axis_separator, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_set_scope_fail_on_index_out_of_bound():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    with pytest.raises(AssertionError):\n        s.set_axis_separator(s.get_block(\"B\"), (\"write\",1),[1])\n    with pytest.raises(AssertionError):\n        s.set_axis_separator(s.get_block(\"B\"), (\"read\",-1),[1])\n\n\ndef test_set_axis_separator_input_buffer(argument_style):\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n\n    if argument_style=='set_axis_separators':\n        s.set_axis_separator(s.get_block(\"B\"), (\"read\",0), [1])\n    elif argument_style=='transform_layout_named':\n        s.transform_layout(block='B', buffer='A', index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    elif argument_style =='transform_layout_buffer_object':\n        A = s.get(s.get_block('B')).reads[0].buffer\n        s.transform_layout(block='B', buffer=A, index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    else:\n        raise ValueError(f'Unexpected argument_style: {argument_style}')\n\n\n    tvm.ir.assert_structural_equal(element_wise_set_axis_separator_input_buffer, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_set_axis_separator_subregion(argument_style):\n    func = element_wise_subregion_match\n    s = tir.Schedule(func, debug_mask='all')\n\n    if argument_style=='set_axis_separators':\n        s.set_axis_separator(s.get_block(\"B\"), (\"write\",0), [1])\n    elif argument_style=='transform_layout_named':\n        s.transform_layout(block='B', buffer='B', index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    elif argument_style =='transform_layout_buffer_object':\n        B = s.get(s.get_block('B')).writes[0].buffer\n        s.transform_layout(block='B', buffer=B, index_map=lambda i,j: [i,IndexMap.AXIS_SEPARATOR,j])\n    else:\n        raise ValueError(f'Unexpected argument_style: {argument_style}')\n\n    tvm.ir.assert_structural_equal(element_wise_subregion_match_set_axis_separator, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\nclass TestIndexedLookup(tvm.testing.CompareBeforeAfter):\n    def transform(self):\n        def func(mod):\n            sch = tir.Schedule(mod)\n            sch.set_axis_separator('block', 'B', [1])\n            return sch.mod\n        return func\n\n    @T.prim_func\n    def before():\n        A = T.alloc_buffer([4,4], dtype=\"int32\")\n        B = T.alloc_buffer([1,1], dtype=\"int32\")\n        for j in T.serial(4):\n            with T.block('block'):\n                A[B[0,0],j] = 0\n\n    @T.prim_func\n    def expected():\n        A = T.alloc_buffer([4,4], dtype=\"int32\")\n        B = T.alloc_buffer([1,1], dtype=\"int32\", axis_separators=[1])\n        for j in T.serial(4):\n            with T.block('block'):\n                A[B[0,0],j] = 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_set_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n@T.prim_func\ndef element_wise(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_set_scope(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_shared[vi, vj] = A[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B_shared[vi, vj] + T.float32(1)\n\n\n@T.prim_func\ndef element_wise_subregion_match(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((128, 128), dtype=\"float32\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion0 = T.match_buffer(B[vi, vj], [], offset_factor=1)\n            B_subregion0[()] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion1 = T.match_buffer(B[vi, vj], [], offset_factor=1)\n            C[vi, vj] = B_subregion1[()] + 1.0\n\n\n@T.prim_func\ndef element_wise_subregion_match_set_scope(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion0_shared = T.match_buffer(B_shared[vi, vj], [], dtype=\"float32\", scope=\"shared\", offset_factor=1)\n            B_subregion0_shared[()] = A[vi, vj] * T.float32(2)\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B_subregion1_shared = T.match_buffer(B_shared[vi, vj], [], dtype=\"float32\", scope=\"shared\", offset_factor=1)\n            C[vi, vj] = B_subregion1_shared[()] + T.float32(1)\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\ndef test_set_scope(use_block_name):\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    s.set_scope('B' if use_block_name else s.get_block(\"B\"), 0, \"shared\")\n    tvm.ir.assert_structural_equal(element_wise_set_scope, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_set_scope_fail_on_output_buffer(use_block_name):\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.set_scope('C' if use_block_name else s.get_block(\"C\"), 0, \"shared\")\n\n\ndef test_set_scope_fail_on_index_out_of_bound():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.set_scope(s.get_block(\"B\"), 1, \"shared\")\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.set_scope(s.get_block(\"B\"), -1, \"shared\")\n\n\ndef test_set_scope_fail_on_invalid_scope():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    with pytest.raises(tvm.tir.ScheduleError):\n        s.set_scope(s.get_block(\"B\"), 0, \"test_scope\")\n\n\ndef test_set_scope_subregion():\n    func = element_wise_subregion_match\n    s = tir.Schedule(func, debug_mask='all')\n    s.set_scope(s.get_block(\"B\"), 0, \"shared\")\n    tvm.ir.assert_structural_equal(element_wise_subregion_match_set_scope, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_split_fuse.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm.script import tir as T\nfrom tvm.tir.expr import IntImm\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_dependent_loops(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i in T.serial(0, 128):\n        for j, k in T.grid(i, 128):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i)\n                vj = T.axis.S(i, j)\n                vk = T.axis.S(128, k)\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_symbolic(a: T.handle, b: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (128, 128, n))\n    B = T.match_buffer(b, (128, 128, n))\n    for i, j, k in T.grid(128, 128, n):\n        with T.block(\"B\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_symbolic_fused(a: T.handle, b: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (128, 128, n))\n    B = T.match_buffer(b, (128, 128, n))\n    for i_j_k_fused in T.serial(0, (n * 16384)):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, T.floordiv(i_j_k_fused, n * 128))\n            vj = T.axis.S(128, T.floordiv(T.floormod(i_j_k_fused, n * 128), n))\n            vk = T.axis.S(n, T.floormod(i_j_k_fused, n))\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_symbolic_split(a: T.handle, b: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (128, 128, n))\n    B = T.match_buffer(b, (128, 128, n))\n    for i, j, k0, k1 in T.grid(128, 128, 10, T.floordiv((n + 9), 10)):\n        with T.block(\"B\"):\n            T.where((((k0 * T.floordiv((n + 9), 10)) + k1) < n))\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            vk = T.axis.S(n, k0 * T.floordiv(n + 9, 10) + k1)\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_seq(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    C = T.alloc_buffer((128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.serial(0, 128):\n            with T.block(\"C\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                C[vi, vj, vk] = A[vi, vj, vk] * 2.0\n        for k in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                B[vi, vj, vk] = C[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_anno(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.serial(0, 128, annotations={\"useless_annotation\": True}):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_thread_binding(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_starting_point(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.serial(10, 128):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_with_opaque_block(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"opaque\"):\n            T.reads([A[i, j, k]])\n            T.writes([B[i, j, k]])\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_fused(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for fused in T.serial(0, 2097152):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, T.floordiv(fused, 16384))\n            vj = T.axis.S(128, T.floordiv(T.floormod(fused, 16384), 128))\n            vk = T.axis.S(128, T.floormod(fused, 128))\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_split_case0(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128])\n    B = T.match_buffer(b, [128, 128, 128])\n    for i1, i2, i3, j1, j2, k1, k2 in T.grid(2, 1, 64, 4, 32, 16, 8):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i1 * 64 + i2 * 64 + i3)\n            vj = T.axis.S(128, j1 * 32 + j2)\n            vk = T.axis.S(128, k1 * 8 + k2)\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_split_case1(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128])\n    B = T.match_buffer(b, [128, 128, 128])\n    for i1, i2, i3, j1, j2, j3, k1, k2, k3 in T.grid(2, 1, 64, 2, 1, 64, 2, 1, 64):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i1 * 64 + i2 * 64 + i3)\n            vj = T.axis.S(128, j1 * 64 + j2 * 64 + j3)\n            vk = T.axis.S(128, k1 * 64 + k2 * 64 + k3)\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_split_with_predicate(a: T.handle, b: T.handle) -> None:\n    B = T.match_buffer(b, [128, 128, 128])\n    A = T.match_buffer(a, [128, 128, 128])\n    for i0, i1, i2, j0, j1, k0, k1 in T.grid(1000, 2, 3, 1, 129, 3, 43):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i0 * 6 + i1 * 3 + i2)\n            vj = T.axis.S(128, j0 * 129 + j1)\n            vk = T.axis.S(128, k0 * 43 + k1)\n            T.where((i0 * 2 + i1) * 3 + i2 < 128 and j0 * 129 + j1 < 128 and k0 * 43 + k1 < 128)\n            T.reads([A[vi, vj, vk]])\n            T.writes([B[vi, vj, vk]])\n            B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_fuse_with_opaque_block(a: T.handle, b: T.handle) -> None:\n    B = T.match_buffer(b, [128, 128, 128])\n    A = T.match_buffer(a, [128, 128, 128])\n    for i_j_k_fused in T.serial(0, 2097152):\n        with T.block(\"opaque\"):\n            T.reads(\n                [\n                    A[\n                        T.floordiv(i_j_k_fused, 16384),\n                        T.floordiv(T.floormod(i_j_k_fused, 16384), 128),\n                        T.floormod(i_j_k_fused, 128),\n                    ]\n                ]\n            )\n            T.writes(\n                [\n                    B[\n                        T.floordiv(i_j_k_fused, 16384),\n                        T.floordiv(T.floormod(i_j_k_fused, 16384), 128),\n                        T.floormod(i_j_k_fused, 128),\n                    ]\n                ]\n            )\n            with T.block(\"B\"):\n                vi = T.axis.S(128, T.floordiv(i_j_k_fused, 16384))\n                vj = T.axis.S(128, T.floordiv(T.floormod(i_j_k_fused, 16384), 128))\n                vk = T.axis.S(128, T.floormod(i_j_k_fused, 128))\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef elementwise_split_with_opaque_block(a: T.handle, b: T.handle) -> None:\n    B = T.match_buffer(b, [128, 128, 128])\n    A = T.match_buffer(a, [128, 128, 128])\n\n    for i0, i1, j, k in T.grid(8, 16, 128, 128):\n        with T.block(\"opaque\"):\n            T.reads([A[i0 * 16 + i1, j, k]])\n            T.writes([B[i0 * 16 + i1, j, k]])\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i0 * 16 + i1)\n                vj, vk = T.axis.remap(\"SS\", [j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes([B[vi, vj, vk]])\n                B[vi, vj, vk] = A[vi, vj, vk] * 2.0\n\n\n@T.prim_func\ndef opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16], \"float32\")\n    B = T.match_buffer(b, [16, 16], \"float32\")\n    for i, j in T.grid(16, 16):\n        with T.block(\"A\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([A[0:16, 0:16]])\n            A[vi, vj] = 1\n    for i, j in T.grid(16, 16):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([])\n            T.writes([B[0:16, 0:16]])\n            T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\"))\n\n\n@T.prim_func\ndef opaque_access_fused(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16])\n    B = T.match_buffer(b, [16, 16])\n    for i_j_fused in T.serial(0, 256):\n        with T.block(\"A\"):\n            vi = T.axis.S(16, T.floordiv(i_j_fused, 16))\n            vj = T.axis.S(16, T.floormod(i_j_fused, 16))\n            T.reads([])\n            T.writes([A[0:16, 0:16]])\n            A[vi, vj] = 1\n    for i_j_fused in T.serial(0, 256):\n        with T.block(\"B\"):\n            vi = T.axis.S(16, T.floordiv(i_j_fused, 16))\n            vj = T.axis.S(16, T.floormod(i_j_fused, 16))\n            T.reads([])\n            T.writes([B[0:16, 0:16]])\n            T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, ((vi * 16) + vj), dtype=\"handle\"))\n\n\n@T.prim_func\ndef opaque_access_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    B = T.match_buffer(b, (16, 16))\n    for i, j0, j1 in T.grid(16, 4, 4):\n        with T.block(\"A\"):\n            vi = T.axis.S(16, i)\n            vj = T.axis.S(16, j0 * 4 + j1)\n            T.reads([])\n            T.writes([A[0:16, 0:16]])\n            A[vi, vj] = 1\n    for i, j0, j1 in T.grid(16, 4, 4):\n        with T.block(\"B\"):\n            vi = T.axis.S(16, i)\n            vj = T.axis.S(16, j0 * 4 + j1)\n            T.reads([])\n            T.writes([B[0:16, 0:16]])\n            T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, ((vi * 16) + vj), dtype=\"handle\"))\n\n\n@T.prim_func\ndef elementwise_not_affine(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (127, 128))\n    B = T.match_buffer(b, (127, 128))\n    for i in T.serial(0, 4):\n        for j, k in T.grid(T.min(31, 126 - i * 32) + 1, 128):\n            with T.block(\"B\"):\n                vi = T.axis.S(127, i * 32 + j)\n                vj = T.axis.S(128, k)\n                B[vi, vj] = A[vi, vj]\n\n\n@T.prim_func\ndef elementwise_not_affine_fused(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [127, 128])\n    B = T.match_buffer(b, [127, 128])\n    for i in T.grid(4):\n        for j_k_fused in T.serial(0, T.min(31, 126 - i * 32) * 128 + 128):\n            with T.block(\"B\"):\n                vi = T.axis.S(\n                    127,\n                    i * 32 + T.floordiv(j_k_fused, 128),\n                )\n                vj = T.axis.S(128, T.floormod(j_k_fused, 128))\n                T.reads([A[vi, vj]])\n                T.writes([B[vi, vj]])\n                B[vi, vj] = A[vi, vj]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef test_fuse():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    sch.fuse(i, j, k)\n    tvm.ir.assert_structural_equal(elementwise_fused, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_split():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    sch.split(i, factors=[2, 1, 64])\n    sch.split(j, factors=[4, 32])\n    sch.split(k, factors=[16, 8])\n    tvm.ir.assert_structural_equal(elementwise_split_case0, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_split_with_inferred_factor():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    sch.split(i, factors=[None, 1, 64])\n    sch.split(j, factors=[2, None, 64])\n    sch.split(k, factors=[2, 1, None])\n    tvm.ir.assert_structural_equal(elementwise_split_case1, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_split_with_predicate():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    sch.split(i, factors=[1000, 2, 3])\n    sch.split(j, factors=[None, 129])\n    sch.split(k, factors=[3, None])\n    tvm.ir.assert_structural_equal(elementwise_split_with_predicate, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_fuse_fail_not_only_child():\n    sch = tir.Schedule(elementwise_with_seq, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.fuse(j, k)\n\n\ndef test_fuse_split_fail_with_annotation():\n    sch = tir.Schedule(elementwise_with_anno, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.fuse(j, k)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(k, factors=[None, 10])\n\n\ndef test_fuse_split_fail_not_start_with_zero():\n    sch = tir.Schedule(elementwise_with_anno, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.fuse(j, k)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(k, factors=[None, 10])\n\n\ndef test_fuse_with_opaque_block():\n    sch = tir.Schedule(elementwise_with_opaque_block, debug_mask=\"all\")\n    block_opaque = sch.get_block(\"opaque\")\n    i, j, k = sch.get_loops(block_opaque)\n    sch.fuse(i, j, k)\n    tvm.ir.assert_structural_equal(elementwise_fuse_with_opaque_block, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_with_opaque_block)\n\n\ndef test_fuse_with_opaque_access():\n    sch = tir.Schedule(opaque_access, debug_mask=\"all\")\n    block_a = sch.get_block(\"A\")\n    i, j = sch.get_loops(block_a)\n    sch.fuse(i, j)\n    block_b = sch.get_block(\"B\")\n    i, j = sch.get_loops(block_b)\n    sch.fuse(i, j)\n    tvm.ir.assert_structural_equal(opaque_access_fused, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=opaque_access)\n\n\ndef test_split_with_opaque_block():\n    sch = tir.Schedule(elementwise_with_opaque_block, debug_mask=\"all\")\n    block_opaque = sch.get_block(\"opaque\")\n    i, _, _ = sch.get_loops(block_opaque)\n    sch.split(i, factors=[None, 16])\n    tvm.ir.assert_structural_equal(elementwise_split_with_opaque_block, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_with_opaque_block)\n\n\ndef test_split_with_opaque_access():\n    sch = tir.Schedule(opaque_access, debug_mask=\"all\")\n    block_a = sch.get_block(\"A\")\n    _, j = sch.get_loops(block_a)\n    sch.split(j, factors=[None, 4])\n    block_b = sch.get_block(\"B\")\n    _, j = sch.get_loops(block_b)\n    sch.split(j, factors=[None, 4])\n    tvm.ir.assert_structural_equal(opaque_access_split, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=opaque_access)\n\n\ndef test_split_with_non_positive_factors():\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(i, factors=[-2, -64])\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(j, factors=[0, None])\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(k, factors=[None, -16])\n\n\ndef test_fuse_split_fail_with_thread_binding():\n    sch = tir.Schedule(elementwise_with_thread_binding, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.fuse(j, k)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.split(k, factors=[None, 10])\n\n\ndef test_fuse_symbolic():\n    sch = tir.Schedule(elementwise_symbolic, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    sch.fuse(i, j, k)\n    tvm.ir.assert_structural_equal(elementwise_symbolic_fused, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_symbolic)\n\n\ndef test_split_symbolic():\n    sch = tir.Schedule(elementwise_symbolic, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, _, k = sch.get_loops(block_b)\n    sch.split(k, factors=[10, None])\n    tvm.ir.assert_structural_equal(elementwise_symbolic_split, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_symbolic)\n\n\ndef test_fuse_fail_with_dependent_loops():\n    sch = tir.Schedule(elementwise_dependent_loops, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, _ = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError):\n        sch.fuse(i, j)\n\n\ndef test_fuse_not_affine():\n    sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, j, k = sch.get_loops(block_b)\n    sch.fuse(j, k)\n    tvm.ir.assert_structural_equal(elementwise_not_affine_fused, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_not_affine)\n\n\ndef test_add_unit_loop_above_block():\n    @T.prim_func\n    def zero_dim(\n        A: T.Buffer[(), \"int32\"],\n        B: T.Buffer[(), \"int32\"],\n        C: T.Buffer[(), \"int32\"],\n    ) -> None:\n        with T.block(\"C\"):\n            vi = T.axis.spatial(1, 0)\n            C[()] = A[()] + B[()]\n\n    @T.prim_func\n    def zero_dim_added(\n        A: T.Buffer[(), \"int32\"],\n        B: T.Buffer[(), \"int32\"],\n        C: T.Buffer[(), \"int32\"],\n    ) -> None:\n        for u in range(1):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(1, 0)\n                C[()] = A[()] + B[()]\n\n    sch = tir.Schedule(zero_dim, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    sch.add_unit_loop(block)\n    tvm.ir.assert_structural_equal(zero_dim_added, sch.mod[\"main\"])\n\n\ndef test_add_unit_loop_above_loop():\n    @T.prim_func\n    def zero_dim(\n        A: T.Buffer[(), \"int32\"],\n        B: T.Buffer[(), \"int32\"],\n        C: T.Buffer[(), \"int32\"],\n    ) -> None:\n        for u in range(1):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(1, 0)\n                C[()] = A[()] + B[()]\n\n    @T.prim_func\n    def zero_dim_added(\n        A: T.Buffer[(), \"int32\"],\n        B: T.Buffer[(), \"int32\"],\n        C: T.Buffer[(), \"int32\"],\n    ) -> None:\n        for u1, u2 in T.grid(1, 1):\n            with T.block(\"C\"):\n                vi = T.axis.spatial(1, 0)\n                C[()] = A[()] + B[()]\n\n    sch = tir.Schedule(zero_dim, debug_mask=\"all\")\n    block = sch.get_block(\"C\")\n    (loop,) = sch.get_loops(block)\n    sch.add_unit_loop(loop)\n    tvm.ir.assert_structural_equal(zero_dim_added, sch.mod[\"main\"])\n\n\n@pytest.mark.skip(\"Pending fix in affine analysis\")\ndef test_fuse_int64():\n    def _create_prim_func():\n        n = te.const(16, \"int32\")\n        m = te.const(32, \"int64\")\n        A = te.placeholder((n, m), name=\"A\", dtype=\"int32\")\n        B = te.compute((n, m), lambda i, j: A[i, j] + 1, name=\"B\")\n        return te.create_prim_func([A, B])\n\n    mod = _create_prim_func()\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    i, j = sch.get_loops(sch.get_block(\"B\"))\n    sch.fuse(i, j)\n    verify_trace_roundtrip(sch=sch, mod=mod)\n\n\ndef test_split_int64_extent_with_mixed_factors():\n    def _create_prim_func():\n        m = te.const(384, \"int64\")\n        A = te.placeholder((m,), name=\"A\", dtype=\"float32\")\n        B = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\n        return te.create_prim_func([A, B])\n\n    mod = _create_prim_func()\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    (i,) = sch.get_loops(sch.get_block(\"B\"))\n    sch.split(\n        i,\n        factors=[\n            te.const(1, \"int64\"),\n            te.const(512, \"int32\"),\n        ],\n    )\n\n\ndef test_split_int64_extent_with_int32_factors():\n    def _create_prim_func():\n        m = te.const(12, \"int64\")\n        A = te.placeholder((m,), name=\"A\", dtype=\"float32\")\n        B = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\n        return te.create_prim_func([A, B])\n\n    mod = _create_prim_func()\n    sch = tir.Schedule(mod, debug_mask=\"all\")\n    (i,) = sch.get_loops(sch.get_block(\"B\"))\n    sch.split(\n        i,\n        factors=[\n            te.const(1, \"int32\"),\n            te.const(1, \"int32\"),\n            te.const(3, \"int32\"),\n            te.const(1, \"int32\"),\n            te.const(4, \"int32\"),\n        ],\n    )\n\n\ndef test_split_int64_factors():\n    sch = tir.Schedule(elementwise_symbolic, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    _, _, k = sch.get_loops(block_b)\n    sch.split(k, factors=[IntImm(dtype=\"int64\", value=10), None])\n    tvm.ir.assert_structural_equal(elementwise_symbolic_split, sch.mod[\"main\"])\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_state.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport gc\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.ir import IRModule\nfrom tvm.script import tir as T\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = T.float32(0)\n        for k in range(0, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef block_in_opaque_block(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.match_buffer(b, (128, 128), \"float32\")\n    for i in range(128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            T.reads([A[0:128, 0:128]])\n            T.writes([B[0:128, 0:128]])\n            B[vi, 0] = A[vi, 0]\n            if A[vi, 0] == 0.0:\n                with T.block(\"C\"):\n                    T.reads([A[0:128, 0:128]])\n                    T.writes([B[0:128, 0:128]])\n                    for j in range(128):\n                        with T.block(\"D\"):\n                            vj = T.axis.S(128, j)\n                            B[vi, vj] = A[vi, vj] * 3.0\n            else:\n                with T.block(\"E\"):\n                    T.reads([A[0:128, 0:128]])\n                    T.writes([B[0:128, 0:128]])\n                    for j in range(128):\n                        with T.block(\"F\"):\n                            vj = T.axis.S(128, j)\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef replace_ir_builder(deep_copy=False, realize=False):\n    new_func = tvm.script.from_source(elementwise.script())\n    s = tir.ScheduleState(new_func, debug_mask=\"all\")\n    target = tvm.tir.Block(\n        iter_vars=[],\n        reads=[],\n        writes=[],\n        name_hint=\"target\",\n        body=s.mod[\"main\"].body.block.body[1],\n        init=None,\n        alloc_buffers=None,\n        match_buffers=None,\n        annotations=None,\n    )\n    if realize:\n        target = tvm.tir.BlockRealize(\n            iter_values=[],\n            predicate=True,\n            block=target,\n        )\n    if deep_copy:\n        target.__setstate__(target.__getstate__())\n    gc.collect()\n    return s, target\n\n\ndef replace_ir_builder_module(deep_copy=False, realize=False):\n    new_func = tvm.script.from_source(elementwise.script())\n    other_func = tvm.script.from_source(elementwise.script())\n    mod = IRModule(functions={\"main\": new_func, \"other\": other_func})\n    s = tir.ScheduleState(mod, debug_mask=\"all\")\n    target = tvm.tir.Block(\n        iter_vars=[],\n        reads=[],\n        writes=[],\n        name_hint=\"target\",\n        body=s.mod[\"main\"].body.block.body[1],\n        init=None,\n        alloc_buffers=None,\n        match_buffers=None,\n        annotations=None,\n    )\n    if realize:\n        target = tvm.tir.BlockRealize(\n            iter_values=[],\n            predicate=True,\n            block=target,\n        )\n    if deep_copy:\n        target.__setstate__(target.__getstate__())\n    gc.collect()\n    return s, target\n\n\ndef replace_ir_builder_with_opaque():\n    func = tvm.script.from_source(block_in_opaque_block.script())\n    s = tir.ScheduleState(func, debug_mask=\"all\")\n    gc.collect()\n    return s\n\n\ndef test_replace_direct_write0():\n    s, target = replace_ir_builder(realize=True)\n    old_hash = s.mod[\"main\"].__hash__()\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[1])\n    s.replace(sref, target)\n    # There is no other reference so the AST node can be written directly\n    assert old_hash == s.mod[\"main\"].__hash__()\n    # Check the replaced part is equal to the target\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[1], target)\n    # The target reuse the stmt of the sref, so the sref won't be None\n    assert sref.stmt is not None\n\n\ndef test_replace_direct_write1():\n    s, target = replace_ir_builder(realize=True)\n    old_hash = s.mod[\"main\"].body.block.body.__hash__()\n    hold_ref = s.mod[\"main\"].body.block.body[1]\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[1])\n    s.replace(sref, target)\n    # There is no other reference so the AST node can be written directly\n    assert old_hash == s.mod[\"main\"].body.block.body.__hash__()\n    assert not tvm.ir.structural_equal(hold_ref.body, target)\n    # Check the replaced part is equal to the target\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[1], target)\n    # The target reuse `sref.stmt`, so the sref won't be None\n    assert sref.stmt is not None\n\n\ndef test_replace_copy():\n    s, target = replace_ir_builder(deep_copy=True, realize=True)\n    old_hash = s.mod[\"main\"].__hash__()\n    # We hold another reference of func\n    old_func = s.mod[\"main\"]\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[0])\n    s.replace(sref, target)\n    # We need to copy the whole func to remain the old_func unchanged\n    assert old_hash != s.mod[\"main\"].__hash__()\n    assert not tvm.ir.structural_equal(old_func.body, s.mod[\"main\"].body)\n    assert old_hash == old_func.__hash__()\n    # Check the replaced part is equal to the target\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[0], target)\n    # The replaced AST node will be deleted, so the ref will be None\n    assert sref.stmt is None\n\n\ndef test_replace_partial_copy0():\n    s, target = replace_ir_builder(deep_copy=True, realize=True)\n    func_old_hash = s.mod[\"main\"].__hash__()\n    hold_ref = s.mod[\"main\"].body.block.body[0]\n    ref_old_hash = hold_ref.__hash__()\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[0].body)\n    other_part_hash = s.mod[\"main\"].body.block.body[1].__hash__()\n    s.replace(sref, target)\n    # The stmt is held by `hold_sref`, so it will be coped in copy-on-write\n    # because the ref count is not unique\n    assert ref_old_hash != s.mod[\"main\"].body.block.body[0].__hash__()\n    assert not tvm.ir.structural_equal(hold_ref.body, target)\n    # The function and the other part stmt can be directly written\n    assert func_old_hash == s.mod[\"main\"].__hash__()\n    assert other_part_hash == s.mod[\"main\"].body.block.body[1].__hash__()\n    # Check the replaced part is equal to the target\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[0].body, target)\n    # The replaced AST node will be deleted, so the ref will be None\n    assert sref.stmt is None\n\n\ndef test_replace_partial_copy1():\n    s, target = replace_ir_builder(deep_copy=True)\n    func_old_hash = s.mod[\"main\"].__hash__()\n    hold_ref = s.mod[\"main\"].body.block.body[0].body\n    stmt_old_hash = s.mod[\"main\"].body.block.body[0].__hash__()\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[0].body.body.block)\n    other_part_hash = s.mod[\"main\"].body.block.body[1].__hash__()\n    s.replace(sref, target)\n    # The parent stmt will change since there is only one reference\n    assert stmt_old_hash == s.mod[\"main\"].body.block.body[0].__hash__()\n    assert not tvm.ir.structural_equal(hold_ref.body, target)\n    # The function and the other part stmt can be directly written\n    assert func_old_hash == s.mod[\"main\"].__hash__()\n    assert other_part_hash == s.mod[\"main\"].body.block.body[1].__hash__()\n    # Check the replaced part is equal to the target\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[0].body.body.block, target)\n    # The replaced AST node will be deleted, so the ref will be None\n    assert sref.stmt is None\n\n\ndef test_replace_root_write():\n    s, target = replace_ir_builder()\n    old_hash = s.mod[\"main\"].__hash__()\n    sref = s.get_sref(s.mod[\"main\"].body.block)\n    s.replace(sref, target)\n    # Check no copy and the new body equals to target\n    assert old_hash == s.mod[\"main\"].__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block, target)\n\n\ndef test_replace_root_copy0():\n    s, target = replace_ir_builder(deep_copy=True)\n    old_hash = s.mod[\"main\"].__hash__()\n    func_ref = s.mod[\"main\"]\n    sref = s.get_sref(s.mod[\"main\"].body.block)\n    s.replace(sref, target)\n    # Check the new body equals to target\n    assert old_hash != s.mod[\"main\"].__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block, target)\n    # Check the original func remains unchanged\n    assert old_hash == func_ref.__hash__()\n    assert not tvm.ir.structural_equal(func_ref.body, target)\n\n\ndef test_replace_root_copy1():\n    s, target = replace_ir_builder(deep_copy=True, realize=True)\n    old_hash = s.mod[\"main\"].body.block.__hash__()\n    func_ref = s.mod[\"main\"].body.block\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[0])\n    s.replace(sref, target)\n    # Check the new body equals to target\n    assert old_hash != s.mod[\"main\"].body.block.__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block.body[0], target)\n    # Check the original func remains unchanged\n    assert old_hash == func_ref.__hash__()\n    assert not tvm.ir.structural_equal(func_ref.body, target)\n\n\ndef test_replace_root_copy2():\n    s, target = replace_ir_builder(deep_copy=True)\n    old_hash = s.mod.functions.__hash__()\n    func_ref = s.mod.functions\n    sref = s.get_sref(s.mod[\"main\"].body.block)\n    s.replace(sref, target)\n    # Check the new body equals to target\n    assert old_hash != s.mod.functions.__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block, target)\n    # Check the original func remains unchanged\n    assert old_hash == func_ref.__hash__()\n    for _, v in func_ref.items():\n        assert not tvm.ir.structural_equal(v.body.block, target)\n\n\ndef test_replace_root_copy3():\n    s, target = replace_ir_builder(deep_copy=True)\n    old_hash = s.mod.__hash__()\n    func_ref = s.mod\n    sref = s.get_sref(s.mod[\"main\"].body.block)\n    s.replace(sref, target)\n    # Check the new body equals to target\n    assert old_hash != s.mod.__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block, target)\n    # Check the original func remains unchanged\n    assert old_hash == func_ref.__hash__()\n    assert not tvm.ir.structural_equal(func_ref[\"main\"].body.block, target)\n\n\ndef test_replace_block_remap():\n    func = elementwise\n    s = tir.ScheduleState(func, debug_mask=\"all\")\n    # The target stmt\n    target = matmul.body.block.body.body.body[0].block\n    sref = s.get_sref(s.mod[\"main\"].body.block.body[0].body.body.block)\n    s.replace(sref, target, {sref.stmt: target})\n    sref_new = s.get_sref(s.mod[\"main\"].body.block.body[0].body.body.block)\n    # Check the original sref has been remapped\n    assert sref.__hash__() == sref_new.__hash__()\n    tvm.ir.assert_structural_equal(sref.stmt, target)\n\n\ndef test_replace_block_in_opaque_block():\n    s = replace_ir_builder_with_opaque()\n    root_hash = s.mod[\"main\"].__hash__()\n    for_loop = s.mod[\"main\"].body.block.body.body.block.body[1].then_case.block.body\n    sref = s.get_sref(for_loop)\n    new_for_loop = tir.For(\n        loop_var=for_loop.loop_var,\n        min_val=0,\n        extent=128,\n        kind=tir.ForKind.SERIAL,\n        body=tir.Evaluate(0),\n        thread_binding=None,\n        annotations=None,\n    )\n    s.replace(sref, new_for_loop)\n    assert root_hash == s.mod[\"main\"].__hash__()\n    tvm.ir.assert_structural_equal(sref.stmt, new_for_loop)\n\n\ndef test_replace_ir_module():\n    s, target = replace_ir_builder_module(deep_copy=True)\n    old_hash = s.mod[\"main\"].__hash__()\n    other_func_hash = s.mod[\"other\"].__hash__()\n    func_ref = s.mod[\"main\"]\n    sref = s.get_sref(s.mod[\"main\"].body.block)\n    s.replace(sref, target)\n    # Check the new body equals to target\n    assert old_hash != s.mod[\"main\"].__hash__()\n    tvm.ir.assert_structural_equal(s.mod[\"main\"].body.block, target)\n    # Check the original func remains unchanged\n    assert old_hash == func_ref.__hash__()\n    assert not tvm.ir.structural_equal(func_ref.body, target)\n    assert other_func_hash == s.mod[\"other\"].__hash__()\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_state_cached_flags.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.state import CachedFlags\nfrom tvm.tir.stmt_functor import post_order_visit\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n# fmt: off\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = 0.0\n        for k in range(0, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef block_in_opaque_block(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    B = T.match_buffer(b, (128, 128), \"float32\")\n    for i in range(128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            T.reads([A[0:128, 0:128]])\n            T.writes([B[0:128, 0:128]])\n            B[vi, 0] = A[vi, 0]\n            if A[vi, 0] == 0.0:\n                with T.block(\"C\"):\n                    T.reads([A[0:128, 0:128]])\n                    T.writes([B[0:128, 0:128]])\n                    for j in range(128):\n                        with T.block(\"D\"):\n                            vj = T.axis.S(128, j)\n                            B[vi, vj] = A[vi, vj] * 3.0\n            else:\n                with T.block(\"E\"):\n                    T.reads([A[0:128, 0:128]])\n                    T.writes([B[0:128, 0:128]])\n                    for j in range(128):\n                        with T.block(\"F\"):\n                            vj = T.axis.S(128, j)\n                            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef write_after_read(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.match_buffer(b, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef loop_carried_dependency(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128,))\n    B = T.match_buffer(b, (128,))\n    C = T.match_buffer(c, (128,))\n    for i in range(0, 128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            B[vi] = A[vi] * 2.0\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = T.if_then_else(vi >= 1, B[vi - 1] + 1.0, 0.0, dtype=\"float32\")\n\n\n@T.prim_func\ndef concatenate_multi_producer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128,))\n    B = T.match_buffer(b, (128,))\n    for i in range(0, 64):\n        with T.block(\"A_0\"):\n            vi = T.axis.S(64, i)\n            A[vi] = vi + 1\n    for i in range(0, 64):\n        with T.block(\"A_1\"):\n            vi = T.axis.S(64, i + 64)\n            A[vi] = vi + 2\n    for i in range(0, 128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            B[vi] = A[vi] * 2.0\n\n\n@T.prim_func\ndef concatenate_multi_producer_uncovered(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128,))\n    B = T.match_buffer(b, (128,))\n    for i in range(0, 63):\n        with T.block(\"A_0\"):\n            vi = T.axis.S(63, i)\n            A[vi] = vi + 1\n    for i in range(0, 64):\n        with T.block(\"A_1\"):\n            vi = T.axis.S(64, i + 64)\n            A[vi] = vi + 2\n    for i in range(0, 128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            B[vi] = A[vi] * 2.0\n\n\n@T.prim_func\ndef lca_at_loop(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128,))\n    B = T.match_buffer(b, (128,))\n    C = T.match_buffer(c, (128,))\n    for i in range(0, 128):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i)\n            B[vi] = A[vi] * 2.0\n        with T.block(\"C\"):\n            vi = T.axis.S(128, i)\n            C[vi] = B[vi] + 1.0\n\n\n@T.prim_func\ndef multi_producer_consumer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128,))\n    B = T.match_buffer(b, (128,))\n    for i in range(0, 64):\n        with T.block(\"A_0\"):\n            vi = T.axis.S(64, i)\n            A[vi] = vi + 1\n    for i in range(0, 64):\n        with T.block(\"A_1\"):\n            vi = T.axis.S(64, i + 64)\n            A[vi] = vi + 2\n    for i in range(0, 64):\n        with T.block(\"B_0\"):\n            vi = T.axis.S(64, i)\n            B[vi] = A[vi] + 2.0\n    for i in range(0, 64):\n        with T.block(\"B_1\"):\n            vi = T.axis.S(64, i + 64)\n            B[vi] = A[vi] + 3.0\n\n\n@T.prim_func\ndef elementwise_affine_producer(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j, k, l in T.grid(16, 2, 32, 16):\n        with T.block(\"B\"):\n            vi = T.axis.S(128, i * 8 + j * 4 + k // 8)\n            vj = T.axis.S(128, k % 8 * 16 + l)\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_subblock(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(32, 32):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([A[vi * 4 : vi * 4 + 4, vj * 4 : vj * 4 + 4]])\n            T.writes([B[vi * 4 : vi * 4 + 4, vj * 4 : vj * 4 + 4]])\n            for ii, jj in T.grid(4, 4):\n                with T.block(\"B_sub\"):\n                    vi_i, vj_i = T.axis.remap(\"SS\", [ii, jj])\n                    B[vi * 4 + vi_i, vj * 4 + vj_i] = A[vi * 4 + vi_i, vj * 4 + vj_i] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_subblock_uncovered(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128), \"float32\")\n    C = T.match_buffer(c, (128, 128), \"float32\")\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(32, 32):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.reads([A[vi * 4 : vi * 4 + 2, vj * 4 : vj * 4 + 2]])\n            T.writes([B[vi * 4 : vi * 4 + 2, vj * 4 : vj * 4 + 2]])\n            for ii, jj in T.grid(2, 2):\n                with T.block(\"B_sub\"):\n                    vi_i, vj_i = T.axis.remap(\"SS\", [ii, jj])\n                    B[vi * 4 + vi_i, vj * 4 + vj_i] = A[vi * 4 + vi_i, vj * 4 + vj_i] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef bound_to_thread(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    B = T.alloc_buffer([128, 128], scope=\"shared\")\n    for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        for j in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for j in T.serial(0, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vj, vi] = B[vj, vi] + 1.0\n\n\n@T.prim_func\ndef equal_ranked_threads(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    B = T.alloc_buffer([128, 128], scope=\"shared\")\n    for i_o in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i_i in T.thread_binding(0, 8, thread=\"threadIdx.y\"):\n            for j in T.serial(0, 128):\n                with T.block(\"B\"):\n                    vi = T.axis.S(128, i_o * 8 + i_i)\n                    vj = T.axis.S(128, j)\n                    B[vi, vj] = A[vi, vj] * 2.0\n            for j in T.serial(0, 128):\n                with T.block(\"C\"):\n                    vi = T.axis.S(128, i_o * 8 + i_i)\n                    vj = T.axis.S(128, j)\n                    C[vj, vi] = B[vj, vi] + 1.0\n\n\n@T.prim_func\ndef warp_memory(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    B = T.alloc_buffer([128, 4, 32], scope=\"warp\")\n    for i_o in T.thread_binding(0, 4, thread=\"threadIdx.y\"):\n        for i_i in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            for j in T.serial(0, 128):\n                with T.block(\"B\"):\n                    warp_id, lane_id, vj = T.axis.remap(\"SSS\", [i_o, i_i, j])\n                    B[vj, warp_id, lane_id] = A[warp_id * 32 + lane_id, vj] * 2.0\n            for j in T.serial(0, 128):\n                with T.block(\"C\"):\n                    warp_id, lane_id, vj = T.axis.remap(\"SSS\", [i_o, i_i, j])\n                    C[warp_id * 32 + lane_id, vj] = B[vj, warp_id, lane_id] + 1.0\n\n\n@T.prim_func\ndef warp_memory_negative(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    B = T.alloc_buffer([128, 4, 32], scope=\"warp\")\n    for i_o in T.thread_binding(0, 4, thread=\"threadIdx.y\"):\n        for i_i in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            for j in T.serial(0, 128):\n                with T.block(\"B\"):\n                    warp_id, lane_id, vj = T.axis.remap(\"SSS\", [i_o, i_i, j])\n                    B[vj, warp_id, lane_id] = A[warp_id * 32 + lane_id, vj] * 2.0\n            for i_o_prime in T.thread_binding(0, 4, thread=\"threadIdx.y\"):\n                for j in T.serial(0, 128):\n                    with T.block(\"C\"):\n                        _warp_id, warp_id, lane_id, vj = T.axis.remap(\n                            \"SSSS\", [i_o, i_i, i_o_prime, j]\n                        )\n                        C[warp_id * 32 + lane_id, vj] = B[vj, warp_id, lane_id] + 1.0\n\n\n@T.prim_func\ndef non_perfect_tiling_cache(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [224, 224], dtype=\"float32\")\n    Y = T.match_buffer(b, [224, 224], dtype=\"float32\")\n    cache = T.alloc_buffer([224, 224], dtype=\"float32\")\n    for hh_0, ww_0 in T.grid(28, 28):\n        for ax0 in T.serial(0, 10):\n            for ax1 in T.serial(0, 10):\n                with T.block(\"cache\"):\n                    h = T.axis.spatial(224, hh_0 * 8 - 1 + ax0)\n                    w = T.axis.spatial(224, ww_0 * 8 - 1 + ax1)\n                    T.where(\n                        1 <= hh_0 * 8 + ax0\n                        and hh_0 * 8 + ax0 < 225\n                        and 1 <= ww_0 * 8 + ax1\n                        and ww_0 * 8 + ax1 < 225\n                    )\n                    cache[h, w] = X[h, w]\n        for hh_1, ww_1, khh, kww in T.grid(8, 8, 3, 3):\n            with T.block(\"compute\"):\n                h = T.axis.spatial(224, hh_0 * 8 + hh_1)\n                w = T.axis.spatial(224, ww_0 * 8 + ww_1)\n                kh, kw = T.axis.remap(\"RR\", [khh, kww])\n                with T.init():\n                    Y[h, w] = 0.0\n                Y[h, w] = T.max(\n                    Y[h, w],\n                    T.if_then_else(\n                        T.likely(1 <= h + kh, dtype=\"bool\")\n                        and T.likely(h + kh < 225, dtype=\"bool\")\n                        and T.likely(1 <= w + kw, dtype=\"bool\")\n                        and T.likely(w + kw < 225, dtype=\"bool\"),\n                        cache[h + kh - 1, w + kw - 1],\n                        0.0,\n                        dtype=\"float32\",\n                    ),\n                )\n\n\n@T.prim_func\ndef uncovered_producer_region(A: T.Buffer[(128,), \"float32\"], B: T.Buffer[(128,), \"float32\"]):\n    for i in range(120):\n        with T.block(\"producer\"):\n            vi = T.axis.S((0, 120), i)\n            A[vi] = 1.0\n    for i in range(120):\n        with T.block(\"consumer\"):\n            vi = T.axis.S((8, 128), i + 8)\n            B[vi] = A[vi]\n\n\n@T.prim_func\ndef matmul_relu_padding(A: T.Buffer[(127, 127), \"float16\"], B: T.Buffer[(127, 127), \"float16\"], compute: T.Buffer[(127, 127), \"float32\"]) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    # body\n    # with T.block(\"root\")\n    C = T.alloc_buffer([127, 127], dtype=\"float32\")\n    A_reindex = T.alloc_buffer([128, 128], dtype=\"float16\")\n    B_reindex = T.alloc_buffer([128, 128], dtype=\"float16\")\n    C_reindex_shared = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"shared\")\n    C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype=\"float32\", scope=\"wmma.accumulator\")\n    for ax0, ax1, ax2 in T.grid(128, 1, 128):\n        with T.block(\"A_reindex\"):\n            v0, v1, v2 = T.axis.remap(\"SSS\", [ax0, ax1, ax2])\n            T.reads(A[v0, v2])\n            T.writes(A_reindex[v0, v2])\n            A_reindex[v0, v2] = T.if_then_else(v0 < 127 and v2 < 127, A[v0, v2], T.float16(0), dtype=\"float16\")\n    for ax0, ax1, ax2 in T.grid(1, 128, 128):\n        with T.block(\"B_reindex\"):\n            v0, v1, v2 = T.axis.remap(\"SSS\", [ax0, ax1, ax2])\n            T.reads(B[v2, v1])\n            T.writes(B_reindex[v2, v1])\n            B_reindex[v2, v1] = T.if_then_else(v2 < 127 and v1 < 127, B[v2, v1], T.float16(0), dtype=\"float16\")\n    for ax0_0_0_ax1_0_0_fused in T.thread_binding(2, thread=\"blockIdx.y\"):\n        for ax0_0_1_ax1_0_1_fused in T.thread_binding(1, thread=\"blockIdx.x\"):\n            for ax0_0_2_ax1_0_2_fused in T.thread_binding(16, thread=\"threadIdx.y\"):\n                for ax2_0_0, ax2_0_1, ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(2, 2, 1, 2, 2, 1, 1):\n                    with T.block(\"C_o\"):\n                        v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2 + ax0_0_3 + ax0_0_4)\n                        v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_0_ax1_0_0_fused * 4 + ax0_0_2_ax1_0_2_fused % 2 * 2 + ax1_0_3)\n                        v2_o = T.axis.reduce(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax2_0_2)\n                        T.reads(A_reindex[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                        T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16])\n                        T.block_attr({\"meta_schedule.auto_tensorize\":\"wmma_sync_16x16x16_f16f16f32\", \"meta_schedule.auto_tensorize_init\":\"wmma_fill_16x16x16_f32\", \"warp_execution\":1})\n                        with T.init():\n                            for ax0_1, ax1_1 in T.grid(16, 16):\n                                with T.block(\"C_init\"):\n                                    v0_i_init, v1_i_init = T.axis.remap(\"SS\", [ax0_1, ax1_1])\n                                    T.reads()\n                                    T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init])\n                                    C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0)\n                        for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16):\n                            with T.block(\"C\"):\n                                v0_i, v1_i, v2_i = T.axis.remap(\"SSR\", [ax0_1, ax1_1, ax2_1])\n                                T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex[v2_o * 16 + v2_i, v1_o * 16 + v1_i])\n                                T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i])\n                                T.block_attr({\"meta_schedule.tiling_structure\":\"SSSRRSRS\"})\n                                C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex[v0_o * 16 + v0_i, v2_o * 16 + v2_i], \"float32\") * T.cast(B_reindex[v2_o * 16 + v2_i, v1_o * 16 + v1_i], \"float32\")\n                for ax0, ax1 in T.grid(16, 32):\n                    with T.block(\"C_reindex_shared_wmma.accumulator\"):\n                        v0 = T.axis.spatial(128, ax0_0_2_ax1_0_2_fused // 2 * 16 + ax0)\n                        v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax0_0_2_ax1_0_2_fused % 2 * 32 + ax1)\n                        T.reads(C_reindex_shared_wmma_accumulator[v0, v1])\n                        T.writes(C_reindex_shared[v0, v1])\n                        C_reindex_shared[v0, v1] = C_reindex_shared_wmma_accumulator[v0, v1]\n            for ax0, ax1 in T.grid(128, 64):\n                with T.block(\"C_reindex_shared\"):\n                    v0 = T.axis.spatial(128, ax0)\n                    v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax1)\n                    T.where(ax0 < 127 and ax0_0_0_ax1_0_0_fused * 64 + ax1 < 127)\n                    T.reads(C_reindex_shared[v0, v1])\n                    T.writes(C[v0, v1])\n                    T.block_attr({\"meta_schedule.cooperative_fetch\":3})\n                    C[v0, v1] = C_reindex_shared[v0, v1]\n    for i0, i1 in T.grid(127, 127):\n        with T.block(\"compute\"):\n            i0_1, i1_1 = T.axis.remap(\"SS\", [i0, i1])\n            T.reads(C[i0_1, i1_1])\n            T.writes(compute[i0_1, i1_1])\n            compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0))\n\n\n@T.prim_func\ndef splitted_square_sum_with_predicate(\n    A: T.Buffer[(1, 7, 7, 512), \"float32\"], B: T.Buffer[(1, 1, 1, 512), \"float32\"]\n) -> None:\n    for i0_i1_i2_i3_0_fused, ax0, ax1, ax2, ax3 in T.grid(2, 1, 1, 1, 256):\n        for ax4_ax5_fused_0, ax4_ax5_fused_1 in T.grid(1, 256):\n            with T.block(\"B\"):\n                T.where(ax4_ax5_fused_0 * 256 + ax4_ax5_fused_1 < 49)\n                ax0_1, ax1_1, ax2_1 = T.axis.remap(\"SSS\", [ax0, ax1, ax2])\n                ax3_1 = T.axis.spatial(512, i0_i1_i2_i3_0_fused * 256 + ax3)\n                rv0 = T.axis.reduce(7, (ax4_ax5_fused_0 * 256 + ax4_ax5_fused_1) // 7)\n                rv1 = T.axis.reduce(7, (ax4_ax5_fused_0 * 256 + ax4_ax5_fused_1) % 7)\n                T.reads(A[ax0_1, ax1_1 * 7 + rv0, ax2_1 * 7 + rv1, ax3_1])\n                T.writes(B[ax0_1, ax1_1, ax2_1, ax3_1])\n                with T.init():\n                    B[ax0_1, ax1_1, ax2_1, ax3_1] = T.float32(0)\n                B[ax0_1, ax1_1, ax2_1, ax3_1] += A[ax0_1, ax1_1 * 7 + rv0, ax2_1 * 7 + rv1, ax3_1]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n# fmt: on\n\n\ndef _get_block(s: tir.ScheduleState, name_hint: str) -> tir.StmtSRef:\n    result = None\n\n    def f_visit(node):\n        nonlocal result\n        if isinstance(node, tvm.tir.Block) and node.name_hint == name_hint:\n            result = node\n\n    func = s.mod[\"main\"]\n    post_order_visit(func.body, f_visit)\n    assert result is not None and isinstance(result, tvm.tir.Block)\n    return s.get_sref(result)\n\n\ndef test_elementwise():\n    s = tir.ScheduleState(elementwise, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_matmul():\n    s = tir.ScheduleState(matmul, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"init\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"update\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_block_in_opaque_block():\n    s = tir.ScheduleState(block_in_opaque_block, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"E\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"F\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_write_after_read():\n    s = tir.ScheduleState(write_after_read, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=False,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_loop_carried_dependency():\n    s = tir.ScheduleState(loop_carried_dependency, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=False,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=False,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_concatenate_multi_producer_covered():  # pylint: disable=invalid-name\n    s = tir.ScheduleState(concatenate_multi_producer, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"A_0\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"A_1\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_concatenate_multi_producer_uncovered():  # pylint: disable=invalid-name\n    s = tir.ScheduleState(concatenate_multi_producer_uncovered, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"A_0\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"A_1\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=False,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=False,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_lca_at_loop():\n    s = tir.ScheduleState(lca_at_loop, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_multi_producer_consumer():\n    s = tir.ScheduleState(multi_producer_consumer, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"A_0\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"A_1\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B_0\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B_1\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_elementwise_affine_producer():\n    s = tir.ScheduleState(elementwise_affine_producer, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_subblock():\n    s = tir.ScheduleState(elementwise_subblock, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B_sub\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_subblock_uncovered():\n    s = tir.ScheduleState(elementwise_subblock_uncovered, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=False,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B_sub\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=False,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_thread_binding():\n    s = tir.ScheduleState(bound_to_thread, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_equal_ranked_threads():\n    s = tir.ScheduleState(equal_ranked_threads, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_warp_memory():\n    s = tir.ScheduleState(warp_memory, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_warp_memory_negative():\n    s = tir.ScheduleState(warp_memory_negative, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"root\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=False,\n    )\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"C\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=False,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_non_perfect_tiling_cache():\n    s = tir.ScheduleState(non_perfect_tiling_cache, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"cache\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    assert s._get_cached_flags(_get_block(s, \"compute\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_uncovered_producer_region():\n    s = tir.ScheduleState(uncovered_producer_region, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"consumer\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=False,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_matmul_relu_padding():\n    s = tir.ScheduleState(matmul_relu_padding, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"C_reindex_shared\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\ndef test_splitted_square_sum_with_predicate():\n    s = tir.ScheduleState(splitted_square_sum_with_predicate, debug_mask=\"all\")\n    # pylint: disable=protected-access\n    assert s._get_cached_flags(_get_block(s, \"B\")) == CachedFlags(\n        affine_binding=True,\n        region_cover=True,\n        stage_pipeline=True,\n    )\n    # pylint: enable=protected-access\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_storage_align.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport pytest\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name\n\n@T.prim_func\ndef element_wise(a: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    # body\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        B = T.alloc_buffer([128, 128], elem_offset=0, align=64, offset_factor=1)\n        for i0 in T.serial(0, 128):\n            for ax1 in T.serial(0, 128):\n                with T.block(\"B\"):\n                    vi, vj = T.axis.remap(\"SS\", [i0, ax1])\n                    T.reads([A[vi, vj]])\n                    T.writes([B[vi, vj]])\n                    B[vi, vj] = (A[vi, vj]*T.float32(2))\n            for i1 in T.serial(0, 128):\n                with T.block(\"C\"):\n                    vi_1, vj_1 = T.axis.remap(\"SS\", [i0, i1])\n                    T.reads([B[vi_1, vj_1]])\n                    T.writes([C[vi_1, vj_1]])\n                    C[vi_1, vj_1] = (B[vi_1, vj_1] + T.float32(1))\n\n\n@T.prim_func\ndef element_wise_storage_align(a: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    # body\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        B = T.alloc_buffer([128, 128], elem_offset=0, align=64, offset_factor=1)\n        for i0 in T.serial(0, 128):\n            for ax1 in T.serial(0, 128):\n                with T.block(\"B\"):\n                    vi, vj = T.axis.remap(\"SS\", [i0, ax1])\n                    T.reads([A[vi, vj]])\n                    T.writes([B[vi, vj]])\n                    T.block_attr({\"buffer_dim_align\":[[0, 0, 128, 127]]})\n                    B[vi, vj] = (A[vi, vj]*T.float32(2))\n            for i1 in T.serial(0, 128):\n                with T.block(\"C\"):\n                    vi_1, vj_1 = T.axis.remap(\"SS\", [i0, i1])\n                    T.reads([B[vi_1, vj_1]])\n                    T.writes([C[vi_1, vj_1]])\n                    C[vi_1, vj_1] = (B[vi_1, vj_1] + T.float32(1))\n\n\n@T.prim_func\ndef element_wise_invalid_annotation(a: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    # body\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        B = T.alloc_buffer([128, 128], elem_offset=0, align=64, offset_factor=1)\n        for i0 in T.serial(0, 128):\n            for ax1 in T.serial(0, 128):\n                with T.block(\"B\"):\n                    T.block_attr({\"buffer_dim_align\": [0]})\n                    vi, vj = T.axis.remap(\"SS\", [i0, ax1])\n                    T.reads([A[vi, vj]])\n                    T.writes([B[vi, vj]])\n                    B[vi, vj] = (A[vi, vj]*T.float32(2))\n            for i1 in T.serial(0, 128):\n                with T.block(\"C\"):\n                    vi_1, vj_1 = T.axis.remap(\"SS\", [i0, i1])\n                    T.reads([B[vi_1, vj_1]])\n                    T.writes([C[vi_1, vj_1]])\n                    C[vi_1, vj_1] = (B[vi_1, vj_1] + T.float32(1))\n\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\ndef test_storage_align(use_block_name):\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = 'B' if use_block_name else s.get_block(\"B\")\n    s.storage_align(B, 0, axis=0, factor=128, offset=127)\n    tvm.ir.assert_structural_equal(element_wise_storage_align, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_storage_align_update():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    s.storage_align(B, 0, axis=0, factor=128, offset=0)\n    s.storage_align(B, 0, axis=0, factor=128, offset=127)\n    tvm.ir.assert_structural_equal(element_wise_storage_align, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_storage_align_invalid_factor1():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(B, 0, axis=0, factor=0, offset=127)\n\n\ndef test_storage_align_invalid_factor2():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(B, 0, axis=0, factor=-1, offset=127)\n\n\ndef test_storage_align_invalid_buffer():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    C = s.get_block(\"C\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(C, 0, axis=0, factor=128, offset=127)\n\n\ndef test_storage_align_invalid_buffer_index():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(B, 2, axis=0, factor=128, offset=127)\n\n\ndef test_storage_align_invalid_axis():\n    func = element_wise\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(B, 0, axis=2, factor=128, offset=127)\n\n\ndef test_storage_align_invalid_annotation():\n    func = element_wise_invalid_annotation\n    s = tir.Schedule(func, debug_mask='all')\n    B = s.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        s.storage_align(B, 0, axis=2, factor=128, offset=127)\n\n\nif __name__ == \"__main__\":\n    test_storage_align()\n    test_storage_align_update()\n    test_storage_align_invalid_factor1()\n    test_storage_align_invalid_factor2()\n    test_storage_align_invalid_buffer()\n    test_storage_align_invalid_buffer_index()\n    test_storage_align_invalid_axis()\n    test_storage_align_invalid_annotation()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_tensorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\nfrom tvm.tir.tensor_intrin.arm_cpu import (\n    DP4A_INTRIN,\n    ARM_DOT_4x4_i8_NEON_INTRIN,\n    ARM_DOT_4x4_i8_SDOT_INTRIN,\n)\nfrom tvm.tir.tensor_intrin.rocm import AMDGPU_SDOT4_INTRIN\nfrom tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n@T.prim_func\ndef mma_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), align=64, offset_factor=1)\n    B = T.match_buffer(b, (16, 16), align=64, offset_factor=1)\n    C = T.match_buffer(c, (16, 16), align=64, offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(C[0 : 16, 0 : 16], A[0 : 16, 0 : 16], B[0 : 16, 0 : 16])\n        T.writes(C[0 : 16, 0 : 16])\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"update\"):\n                vii, vjj, vkk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vii, vjj] = C[vii, vjj] + A[vii, vkk] * B[vjj, vkk]\n\n\n@T.prim_func\ndef mma_intrin(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), align=64, offset_factor=1)\n    B = T.match_buffer(b, (16, 16), align=64, offset_factor=1)\n    C = T.match_buffer(c, (16, 16), align=64, offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(C[0 : 16, 0 : 16], A[0 : 16, 0 : 16], B[0 : 16, 0 : 16])\n        T.writes(C[0 : 16, 0 : 16])\n        T.evaluate(\n            T.tvm_mma_sync(\n                C.data,\n                C.elem_offset // 256,\n                A.data,\n                A.elem_offset // 256,\n                B.data,\n                B.elem_offset // 256,\n                C.data,\n                C.elem_offset // 256,\n                dtype=\"handle\",\n            )\n        )\n\n\n@T.prim_func\ndef dot_product_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (4,))\n    B = T.match_buffer(b, (4,))\n    C = T.match_buffer(c, ())\n\n    with T.block(\"root\"):\n        T.reads(C[()], A[0 : 4], B[0 : 4])\n        T.writes(C[()])\n        for i in range(0, 4):\n            with T.block(\"update\"):\n                vi = T.axis.remap(\"R\", [i])\n                C[()] = C[()] + A[vi] * B[vi]\n\n\n@T.prim_func\ndef dot_product_intrin(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (4,), offset_factor=1)\n    B = T.match_buffer(b, (4,), offset_factor=1)\n    C = T.match_buffer(c, (), offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(C[()], A[0 : 4], B[0 : 4])\n        T.writes(C[()])\n        T.evaluate(\n            T.call_extern(\n                \"vec4add\",\n                C.data,\n                C.elem_offset,\n                A.data,\n                A.elem_offset,\n                B.data,\n                B.elem_offset,\n                dtype=\"int32\",\n            )\n        )\n\n\n@T.prim_func\ndef outer_product_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 1), offset_factor=1)\n    B = T.match_buffer(b, (16, 1), offset_factor=1)\n    C = T.match_buffer(c, (16, 16), offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(\n            C[0 : 16, 0 : 16],\n            A[0 : 16, 0 : 1],\n            B[0 : 16, 0 : 1],\n        )\n        T.writes(C[0 : 16, 0 : 16])\n        for i, j in T.grid(16, 16):\n            with T.block(\"update\"):\n                vii, vjj = T.axis.remap(\"SS\", [i, j])\n                C[vii, vjj] = C[vii, vjj] + A[vii, 0] * B[vjj, 0]\n\n\n@T.prim_func\ndef outer_product_intrin(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 1), offset_factor=1)\n    B = T.match_buffer(b, (16, 1), offset_factor=1)\n    C = T.match_buffer(c, (16, 16), offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(\n            C[0 : 16, 0 : 16],\n            A[0 : 16, 0 : 1],\n            B[0 : 16, 0 : 1],\n        )\n        T.writes(C[0 : 16, 0 : 16])\n        T.evaluate(\n            T.call_extern(\n                \"outer_product\",\n                C.data,\n                C.elem_offset,\n                A.data,\n                A.elem_offset,\n                B.data,\n                B.elem_offset,\n                dtype=\"int32\",\n            )\n        )\n\n\n@T.prim_func\ndef matmul(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(128, 128), \"float32\"],\n) -> None:\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef tensorized_matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n\n    for i_outer, j_outer in T.grid(8, 8):\n        for i_inner_init, j_inner_init in T.grid(16, 16):\n            with T.block(\"init\"):\n                vi_init = T.axis.S(128, ((i_outer * 16) + i_inner_init))\n                vj_init = T.axis.S(128, ((j_outer * 16) + j_inner_init))\n                C[vi_init, vj_init] = T.float32(0)\n        for k_outer in T.grid(8):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i_outer, j_outer, k_outer])\n                T.reads(\n                    [\n                        C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                        A[vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                        B[vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                    ]\n                )\n                T.writes(C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                A_elem_offset = T.var(\"int32\")\n                B_elem_offset = T.var(\"int32\")\n                C_elem_offset = T.var(\"int32\")\n                A_sub = T.match_buffer(\n                    A[vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                    [16, 16],\n                    elem_offset=A_elem_offset,\n                )\n                B_sub = T.match_buffer(\n                    B[vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                    [16, 16],\n                    elem_offset=B_elem_offset,\n                )\n                C_sub = T.match_buffer(\n                    C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                    [16, 16],\n                    elem_offset=C_elem_offset,\n                )\n                T.evaluate(\n                    T.tvm_mma_sync(\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        A_sub.data,\n                        T.floordiv(A_sub.elem_offset, 256),\n                        B_sub.data,\n                        T.floordiv(B_sub.elem_offset, 256),\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        dtype=\"handle\",\n                    )\n                )\n\n\n@T.prim_func\ndef batch_matmul(\n    A: T.Buffer[(16, 128, 128), \"float32\"],\n    B: T.Buffer[(16, 128, 128), \"float32\"],\n    C: T.Buffer[(16, 128, 128), \"float32\"],\n) -> None:\n    for n, i, j in T.grid(16, 128, 128):\n        with T.block(\"init\"):\n            vn, vi, vj = T.axis.remap(\"SSS\", [n, i, j])\n            C[vn, vi, vj] = T.float32(0)\n\n    for n, i, j, k in T.grid(16, 128, 128, 128):\n        with T.block(\"update\"):\n            vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n            C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk]\n\n\n@T.prim_func\ndef tensorized_batch_matmul_mma(\n    A: T.Buffer[(16, 128, 128), \"float32\"],\n    B: T.Buffer[(16, 128, 128), \"float32\"],\n    C: T.Buffer[(16, 128, 128), \"float32\"],\n) -> None:\n    for n, i, j in T.grid(16, 128, 128):\n        with T.block(\"init\"):\n            vn, vi, vj = T.axis.remap(\"SSS\", [n, i, j])\n            T.reads()\n            T.writes(C[vn, vi, vj])\n            C[vn, vi, vj] = T.float32(0)\n    for n in range(0, 16):\n        for i, j, k in T.grid(8, 8, 8):\n            with T.block(\"update\"):\n                vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n                T.reads(\n                    C[vn : vn + 1, vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                    A[vn : vn + 1, vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                    B[vn : vn + 1, vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                )\n                T.writes(C[vn : vn + 1, vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                A_elem_offset = T.var(\"int32\")\n                B_elem_offset = T.var(\"int32\")\n                C_elem_offset = T.var(\"int32\")\n                A_sub = T.match_buffer(\n                    A[vn : vn + 1, vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                    (16, 16),\n                    elem_offset=A_elem_offset,\n                )\n                B_sub = T.match_buffer(\n                    B[vn : vn + 1, vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                    (16, 16),\n                    elem_offset=B_elem_offset,\n                )\n                C_sub = T.match_buffer(\n                    C[vn : vn + 1, vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                    (16, 16),\n                    elem_offset=C_elem_offset,\n                )\n                T.evaluate(\n                    T.tvm_mma_sync(\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        A_sub.data,\n                        T.floordiv(A_sub.elem_offset, 256),\n                        B_sub.data,\n                        T.floordiv(B_sub.elem_offset, 256),\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        dtype=\"handle\",\n                    )\n                )\n\n\n@T.prim_func\ndef tensorized_batch_matmul_dot_product(\n    A: T.Buffer[(16, 128, 128), \"float32\"],\n    B: T.Buffer[(16, 128, 128), \"float32\"],\n    C: T.Buffer[(16, 128, 128), \"float32\"],\n) -> None:\n    for n, i, j in T.grid(16, 128, 128):\n        with T.block(\"init\"):\n            vn, vi, vj = T.axis.remap(\"SSS\", [n, i, j])\n            T.reads()\n            T.writes(C[vn, vi, vj])\n            C[vn, vi, vj] = T.float32(0)\n    for n, i, j, k_0 in T.grid(16, 128, 128, 32):\n        with T.block(\"blockized_update\"):\n            vn, vi, vj, vko = T.axis.remap(\"SSSR\", [n, i, j, k_0])\n            T.reads(\n                C[vn, vi, vj], A[vn, vi, vko * 4 : vko * 4 + 4], B[vn, vj, vko * 4 : vko * 4 + 4]\n            )\n            T.writes(C[vn, vi, vj])\n            A_1 = T.match_buffer(\n                A[vn, vi, vko * 4 : vko * 4 + 4], [4], dtype=\"float32\", offset_factor=1\n            )\n            B_1 = T.match_buffer(\n                B[vn, vj, vko * 4 : vko * 4 + 4], [4], dtype=\"float32\", offset_factor=1\n            )\n            C_1 = T.match_buffer(C[vn, vi, vj], [], dtype=\"float32\", offset_factor=1)\n            T.evaluate(\n                T.call_extern(\n                    \"vec4add\",\n                    C_1.data,\n                    C_1.elem_offset,\n                    A_1.data,\n                    A_1.elem_offset,\n                    B_1.data,\n                    B_1.elem_offset,\n                    dtype=\"int32\",\n                )\n            )\n\n\n@T.prim_func\ndef tensorized_batch_matmul_outer_product(\n    A: T.Buffer[(16, 128, 128), \"float32\"],\n    B: T.Buffer[(16, 128, 128), \"float32\"],\n    C: T.Buffer[(16, 128, 128), \"float32\"],\n) -> None:\n    for n, i, j in T.grid(16, 128, 128):\n        with T.block(\"init\"):\n            vn, vi, vj = T.axis.remap(\"SSS\", [n, i, j])\n            T.reads()\n            T.writes(C[vn, vi, vj])\n            C[vn, vi, vj] = T.float32(0)\n    for n, i_0, j_0, k in T.grid(16, 8, 8, 128):\n        with T.block(\"blockized_update\"):\n            vn, vio, vjo, vk = T.axis.remap(\"SSSR\", [n, i_0, j_0, k])\n            T.reads(\n                C[vn, vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16],\n                A[vn, vio * 16 : vio * 16 + 16, vk],\n                B[vn, vjo * 16 : vjo * 16 + 16, vk],\n            )\n            T.writes(C[vn, vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16])\n            A_1 = T.match_buffer(A[vn, vio * 16 : vio * 16 + 16, vk], [16, 1], dtype=\"float32\", offset_factor=1)\n            B_1 = T.match_buffer(B[vn, vjo * 16 : vjo * 16 + 16, vk], [16, 1], dtype=\"float32\", offset_factor=1\n            )\n            C_1 = T.match_buffer(\n                C[vn, vio * 16 : vio * 16 + 16, vjo * 16 : vjo * 16 + 16], [16, 16], dtype=\"float32\", offset_factor=1\n            )\n            T.evaluate(\n                T.call_extern(\"outer_product\", C_1.data, C_1.elem_offset, A_1.data, A_1.elem_offset,\n                              B_1.data, B_1.elem_offset, dtype=\"int32\"\n                )\n            )\n\n\n@T.prim_func\ndef annotated_mma_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), align=64, offset_factor=1)\n    B = T.match_buffer(b, (16, 16), align=64, offset_factor=1)\n    C = T.match_buffer(c, (16, 16), align=64, offset_factor=1)\n\n    with T.block(\"root\"):\n        T.reads(C[0 : 16, 0 : 16], A[0 : 16, 0 : 16], B[0 : 16, 0 : 16])\n        T.writes(C[0 : 16, 0 : 16])\n        for i, j, k in T.grid(16, 16, 16):\n            with T.block(\"update\"):\n                T.block_attr({\"test_annotation\": True})\n                vii, vjj, vkk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vii, vjj] = C[vii, vjj] + A[vii, vkk] * B[vjj, vkk]\n\n\n@T.prim_func\ndef annotated_matmul(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(128, 128), \"float32\"],\n) -> None:\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            T.block_attr({\"test_annotation\": True})\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef annotated_tensorized_matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n\n    for i_outer, j_outer in T.grid(8, 8):\n        for i_inner_init, j_inner_init in T.grid(16, 16):\n            with T.block(\"init\"):\n                vi_init = T.axis.S(128, ((i_outer * 16) + i_inner_init))\n                vj_init = T.axis.S(128, ((j_outer * 16) + j_inner_init))\n                T.block_attr({\"test_annotation\": True})\n                C[vi_init, vj_init] = T.float32(0)\n        for k_outer in T.grid(8):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i_outer, j_outer, k_outer])\n                T.reads(\n                    [\n                        C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                        A[vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                        B[vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                    ]\n                )\n                T.writes(C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16])\n                A_elem_offset = T.var(\"int32\")\n                B_elem_offset = T.var(\"int32\")\n                C_elem_offset = T.var(\"int32\")\n                A_sub = T.match_buffer(\n                    A[vi * 16 : vi * 16 + 16, vk * 16 : vk * 16 + 16],\n                    [16, 16],\n                    elem_offset=A_elem_offset,\n                )\n                B_sub = T.match_buffer(\n                    B[vj * 16 : vj * 16 + 16, vk * 16 : vk * 16 + 16],\n                    [16, 16],\n                    elem_offset=B_elem_offset,\n                )\n                C_sub = T.match_buffer(\n                    C[vi * 16 : vi * 16 + 16, vj * 16 : vj * 16 + 16],\n                    [16, 16],\n                    elem_offset=C_elem_offset,\n                )\n                T.evaluate(\n                    T.tvm_mma_sync(\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        A_sub.data,\n                        T.floordiv(A_sub.elem_offset, 256),\n                        B_sub.data,\n                        T.floordiv(B_sub.elem_offset, 256),\n                        C_sub.data,\n                        T.floordiv(C_sub.elem_offset, 256),\n                        dtype=\"handle\",\n                    )\n                )\n\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\ntir.TensorIntrin.register(\"test_mma_intrin\", mma_desc, mma_intrin)\ntir.TensorIntrin.register(\"test_annotated_mma_intrin\", annotated_mma_desc, mma_intrin)\ntir.TensorIntrin.register(\"test_dot_product_intrin\", dot_product_desc, dot_product_intrin)\ntir.TensorIntrin.register(\"test_outer_product_intrin\", outer_product_desc, outer_product_intrin)\n\n\ndef test_tensorize_matmul():\n    func = matmul\n    # schedule\n    s = tir.Schedule(func, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    i, j, k = s.get_loops(update)\n    io, ii = s.split(i, factors=[None, 16])\n    jo, ji = s.split(j, factors=[None, 16])\n    ko, ki = s.split(k, factors=[None, 16])\n    s.reorder(io, jo, ko, ii, ji, ki)\n    s.decompose_reduction(update, ko)\n    s.tensorize(ii, \"test_mma_intrin\")\n    tvm.ir.assert_structural_equal(tensorized_matmul, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_tensorize_batch_matmul():\n    func = batch_matmul\n    s = tir.Schedule(func, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    _, i, j, k = s.get_loops(update)\n    io, ii = s.split(i, factors=[None, 16])\n    jo, ji = s.split(j, factors=[None, 16])\n    ko, ki = s.split(k, factors=[None, 16])\n    s.reorder(io, jo, ko, ii, ji, ki)\n    s.tensorize(ii, \"test_mma_intrin\")\n    tvm.ir.assert_structural_equal(tensorized_batch_matmul_mma, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=batch_matmul)\n\n\ndef test_tensorize_dot_product():\n    func = batch_matmul\n    s = tir.Schedule(func, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    _, _, _, k = s.get_loops(C)\n    _, ki = s.split(k, factors=[None, 4])\n    s.tensorize(ki, \"test_dot_product_intrin\")\n    tvm.ir.assert_structural_equal(tensorized_batch_matmul_dot_product, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_tensorize_outer_product():\n    func = batch_matmul\n    s = tir.Schedule(func, debug_mask=\"all\")\n    C = s.get_block(\"update\")\n    _, i, j, k = s.get_loops(C)\n    io, ii = s.split(i, factors=[None, 16])\n    jo, ji = s.split(j, factors=[None, 16])\n    s.reorder(io, jo, k, ii, ji)\n    s.tensorize(ii, \"test_outer_product_intrin\")\n    tvm.ir.assert_structural_equal(tensorized_batch_matmul_outer_product, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef test_tensorize_with_annotation():\n    func = annotated_matmul\n    s = tir.Schedule(func, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    i, j, k = s.get_loops(update)\n    io, ii = s.split(i, factors=[None, 16])\n    jo, ji = s.split(j, factors=[None, 16])\n    ko, ki = s.split(k, factors=[None, 16])\n    s.reorder(io, jo, ko, ii, ji, ki)\n    s.decompose_reduction(update, ko)\n    s.tensorize(ii, \"test_annotated_mma_intrin\")\n    tvm.ir.assert_structural_equal(annotated_tensorized_matmul, s.mod[\"main\"])\n    verify_trace_roundtrip(sch=s, mod=func)\n\n\ndef get_matmul_packed(m, n, k, lhs_type, int32_lanes):\n    X = te.placeholder((m, k), name=\"X\", dtype=lhs_type)\n    packed_W = te.placeholder((n // int32_lanes, k // 4, int32_lanes, 4), name=\"packedW\", dtype=\"int8\")\n\n    ak = te.reduce_axis((0, k), name=\"k\")\n    matmul = te.compute(\n        (m, n),\n        lambda i, j: te.sum(\n            X[i, ak].astype(\"int32\")\n            * packed_W[\n                tvm.tir.indexdiv(j, 16), tvm.tir.indexdiv(ak, 4), j % 16, ak % 4\n            ].astype(\"int32\"),\n            axis=ak,\n        ),\n        name=\"compute\",\n    )\n\n    return te.create_prim_func([X, packed_W, matmul])\n\n\ndef test_tensorize_vnni():\n    m, n, k = 128, 128, 128\n\n    func = get_matmul_packed(m, n, k, \"uint8\", 16)\n\n    sch = tir.Schedule(func, debug_mask=\"all\")\n    block = sch.get_block(\"compute\")\n    _, j, k = sch.get_loops(block)\n\n    _, ji = sch.split(j, factors=[None, 16])\n    ko, ki = sch.split(k, factors=[None, 4])\n    sch.reorder(ko, ji, ki)\n\n    sch.decompose_reduction(block, ko)\n    sch.tensorize(ji, VNNI_DOT_16x4_INTRIN)\n\n    verify_trace_roundtrip(sch=sch, mod=func)\n\n\ndef test_tensorize_arm_dot():\n    m, n, k = 128, 128, 128\n\n    func = get_matmul_packed(m, n, k, \"int8\", 4)\n\n    for intrin in [ARM_DOT_4x4_i8_SDOT_INTRIN, ARM_DOT_4x4_i8_NEON_INTRIN]:\n        sch = tir.Schedule(func, debug_mask=\"all\")\n        block = sch.get_block(\"compute\")\n        _, j, k = sch.get_loops(block)\n\n        _, ji = sch.split(j, factors=[None, 4])\n        ko, ki = sch.split(k, factors=[None, 4])\n        sch.reorder(ko, ji, ki)\n\n        sch.decompose_reduction(block, ko)\n        sch.tensorize(ji, intrin)\n\n        verify_trace_roundtrip(sch=sch, mod=func)\n\n\ndef test_tensorize_dpa4():\n    m, n, k = 128, 128, 128\n\n    X = te.placeholder((m, k), name=\"X\", dtype=\"int8\")\n    W = te.placeholder((n, k), name=\"W\", dtype=\"int8\")\n    ak = te.reduce_axis((0, k), name=\"k\")\n\n    matmul = te.compute(\n        (m, n),\n        lambda i, j: te.sum(\n            X[i, ak].astype(\"int32\")\n            * W[j, ak].astype(\"int32\"),\n            axis=ak,\n        ),\n        name=\"compute\",\n    )\n\n    func = te.create_prim_func([X, W, matmul])\n\n    for intrin in [AMDGPU_SDOT4_INTRIN, DP4A_INTRIN]:\n        sch = tir.Schedule(func, debug_mask=\"all\")\n        block = sch.get_block(\"compute\")\n        i, j, k = sch.get_loops(block)\n\n        by, ty, yi = sch.split(i, factors=sch.sample_perfect_tile(i, n=3))\n        bx, tx, xi = sch.split(j, factors=sch.sample_perfect_tile(j, n=3))\n        ko, ki = sch.split(k, [None, 4])\n        ko, kt = sch.split(ko, factors=sch.sample_perfect_tile(ko, n=2))\n\n        sch.reorder(by, bx, ty, tx, yi, xi)\n\n        CC = sch.cache_write(block, 0, \"local\")\n        sch.reverse_compute_at(CC, tx)\n\n        def fetch_to_shared(block, idx):\n            block_read = sch.cache_read(block, idx, \"shared\")\n            sch.compute_at(block_read, ko, True)\n            return block_read\n\n        fetch_to_shared(block, 0)\n        fetch_to_shared(block, 1)\n\n        sch.decompose_reduction(block, ko)\n        sch.tensorize(ki, intrin)\n\n        verify_trace_roundtrip(sch=sch, mod=func)\n\n\ndef test_tensor_intrin_look_up():\n    intrin_name = 'non_existent_intrin'\n    assert tir.TensorIntrin.get(intrin_name, allow_missing=True) is None\n    with pytest.raises(ValueError):\n        tir.TensorIntrin.get(intrin_name)\n\n\ndef test_tensorize_matmul_mixed_dtype():\n    # fmt: off\n    @T.prim_func\n    def matmul_int64_shape(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        C: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"]\n    ) -> None:\n        for i_0, j_0 in T.grid(T.int64(8), T.int64(8)):\n            for i_1_init, j_1_init in T.grid(T.int64(16), T.int64(16)):\n                with T.block(\"init\"):\n                    vi = T.axis.spatial(T.int64(128), i_0 * T.int64(16) + i_1_init)\n                    vj = T.axis.spatial(T.int64(128), j_0 * T.int64(16) + j_1_init)\n                    C[vi, vj] = T.float32(0)\n            for k_0, i_1, j_1, k_1 in T.grid(T.int64(8), T.int64(16), T.int64(16), T.int64(16)):\n                with T.block(\"update\"):\n                    vi = T.axis.spatial(T.int64(128), i_0 * T.int64(16) + i_1)\n                    vj = T.axis.spatial(T.int64(128), j_0 * T.int64(16) + j_1)\n                    vk = T.axis.reduce(T.int64(128), k_0 * T.int64(16) + k_1)\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    @T.prim_func\n    def tensorized_matmul_int64_shape(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        C: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"]\n    ) -> None:\n        for i_outer, j_outer in T.grid(T.int64(8), T.int64(8)):\n            for i_inner_init, j_inner_init in T.grid(T.int64(16), T.int64(16)):\n                with T.block(\"init\"):\n                    vi = T.axis.spatial(T.int64(128), i_outer * T.int64(16) + i_inner_init)\n                    vj = T.axis.spatial(T.int64(128), j_outer * T.int64(16) + j_inner_init)\n                    C[vi, vj] = T.float32(0)\n            for k_outer in T.grid(T.int64(8)):\n                with T.block(\"update\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i_outer, j_outer, k_outer])\n                    T.reads(\n                        [\n                            C[vi * T.int64(16) : vi * T.int64(16) + T.int64(16), vj * T.int64(16) : vj * T.int64(16) + T.int64(16)],\n                            A[vi * T.int64(16) : vi * T.int64(16) + T.int64(16), vk * T.int64(16) : vk * T.int64(16) + T.int64(16)],\n                            B[vj * T.int64(16) : vj * T.int64(16) + T.int64(16), vk * T.int64(16) : vk * T.int64(16) + T.int64(16)],\n                        ]\n                    )\n                    T.writes(C[vi * T.int64(16) : vi * T.int64(16) + T.int64(16), vj * T.int64(16) : vj * T.int64(16) + T.int64(16)])\n                    A_elem_offset = T.var(\"int32\")\n                    B_elem_offset = T.var(\"int32\")\n                    C_elem_offset = T.var(\"int32\")\n                    A_sub = T.match_buffer(\n                        A[vi * T.int64(16) : vi * T.int64(16) + T.int64(16), vk * T.int64(16) : vk * T.int64(16) + T.int64(16)],\n                        [16, 16],\n                        elem_offset=A_elem_offset,\n                    )\n                    B_sub = T.match_buffer(\n                        B[vj * T.int64(16) : vj * T.int64(16) + T.int64(16), vk * T.int64(16) : vk * T.int64(16) + T.int64(16)],\n                        [16, 16],\n                        elem_offset=B_elem_offset,\n                    )\n                    C_sub = T.match_buffer(\n                        C[vi * T.int64(16) : vi * T.int64(16) + T.int64(16), vj * T.int64(16) : vj * T.int64(16) + T.int64(16)],\n                        [16, 16],\n                        elem_offset=C_elem_offset,\n                    )\n                    T.evaluate(\n                        T.tvm_mma_sync(\n                            C_sub.data,\n                            T.floordiv(C_sub.elem_offset, 256),\n                            A_sub.data,\n                            T.floordiv(A_sub.elem_offset, 256),\n                            B_sub.data,\n                            T.floordiv(B_sub.elem_offset, 256),\n                            C_sub.data,\n                            T.floordiv(C_sub.elem_offset, 256),\n                            dtype=\"handle\",\n                        )\n                    )\n    # fmt: on\n\n    s = tir.Schedule(matmul_int64_shape, debug_mask=\"all\")\n    update = s.get_block(\"update\")\n    ii = s.get_loops(update)[-3]\n    s.tensorize(ii, \"test_mma_intrin\")\n    tvm.ir.assert_structural_equal(s.mod[\"main\"], tensorized_matmul_int64_shape)\n    verify_trace_roundtrip(sch=s, mod=matmul_int64_shape)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_tensorize_ldmatrix_mma.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-docstring\nimport tvm\nfrom tvm import te\nfrom tvm.tir.tensor_intrin.cuda import (\n    LDMATRIX_16x16_A_INTRIN,\n    LDMATRIX_16x16_B_INTRIN,\n    LDMATRIX_16x16_B_TRANS_INTRIN,\n    LDMATRIX_16x32_A_INTRIN,\n    LDMATRIX_32x16_B_INTRIN,\n    LDMATRIX_16x32_B_TRANS_INTRIN,\n    MMA_f16f16f32_INTRIN,\n    MMA_f16f16f32_TRANS_INTRIN,\n    MMA_f16f16f16_INTRIN,\n    MMA_f16f16f16_TRANS_INTRIN,\n    MMA_i8i8i32_INTRIN,\n    MMA_i8i8i32_TRANS_INTRIN,\n    MMA_fill_16x16_f32_INTRIN,\n    MMA_fill_16x16_f16_INTRIN,\n    MMA_fill_16x16_i32_INTRIN,\n    MMA_store_16x16_f32_global_INTRIN,\n    MMA_store_16x16_f16_global_INTRIN,\n    MMA_store_16x16_i32_global_INTRIN,\n    shared_16x16_to_ldmatrix_32x8_layout,\n    shared_32x16_to_ldmatrix_32x16_layout,\n    shared_16x32_to_ldmatrix_32x16_layout,\n)\nimport tvm.testing\nimport numpy as np\nfrom tvm.testing.tir import mma_schedule\n\n\nM = 4096\nN = 4096\nK = 4096\nmeasure_perf = False\ngflops = (N * M * K) * 2 / 1e9\n\n\ndef matmul(m, n, k, in_dtype, out_dtype, b_transposed):\n    b_shape = (n, k) if b_transposed else (k, n)\n    a = te.placeholder((m, k), name=\"A\", dtype=in_dtype)\n    b = te.placeholder(b_shape, name=\"B\", dtype=in_dtype)\n    k = te.reduce_axis((0, k), name=\"k\")\n\n    def maybe_cast(v):\n        if in_dtype != out_dtype:\n            return tvm.tir.Cast(out_dtype, v)\n        return v\n\n    def maybe_swap(i, j):\n        if b_transposed:\n            return j, i\n        return i, j\n\n    c = te.compute(\n        (m, n),\n        lambda i, j: te.sum(maybe_cast(a[i, k]) * maybe_cast(b[maybe_swap(k, j)]), axis=[k]),\n        name=\"C\",\n    )\n    return (a, b, c)\n\n\ndef run_test(\n    k_inner,\n    in_dtype,\n    out_dtype,\n    b_transposed,\n    i_factors,\n    j_factors,\n    k_factors,\n    index_map_A,\n    index_map_B,\n    index_map_C,\n    ldmatrix_a_intrin,\n    ldmatrix_b_intrin,\n    mma_intrin,\n    mma_fill_intrin,\n    mma_store_intrin,\n):\n    sch = mma_schedule(\n        te.create_prim_func(matmul(M, N, K, in_dtype, out_dtype, b_transposed)),\n        k_inner,\n        in_dtype,\n        b_transposed,\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map_A,\n        index_map_B,\n        index_map_C,\n        ldmatrix_a_intrin,\n        ldmatrix_b_intrin,\n        mma_intrin,\n        mma_fill_intrin,\n        mma_store_intrin,\n    )\n\n    f = tvm.build(sch.mod[\"main\"], target=\"cuda\", name=\"dense\")\n\n    dev = tvm.device(\"cuda\", 0)\n\n    if in_dtype == \"float16\":\n        a_np = np.random.uniform(size=(M, K)).astype(\"float16\")\n\n        if b_transposed:\n            b_np = np.random.uniform(size=(N, K)).astype(\"float16\")\n            c_np = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\").transpose()).astype(\n                out_dtype\n            )\n        else:\n            b_np = np.random.uniform(size=(K, N)).astype(\"float16\")\n            c_np = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\")).astype(out_dtype)\n    else:\n        a_np = np.random.randint(-128, 128, (M, K)).astype(\"int8\")\n\n        if b_transposed:\n            b_np = np.random.randint(-128, 128, (N, K)).astype(\"int8\")\n            c_np = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\").transpose()).astype(\n                \"int32\"\n            )\n        else:\n            b_np = np.random.randint(-128, 128, (K, N)).astype(\"int8\")\n            c_np = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\")).astype(\"int32\")\n\n    a = tvm.nd.array(a_np, dev)\n    b = tvm.nd.array(b_np, dev)\n    c = tvm.nd.array(np.zeros((M, N), dtype=out_dtype), dev)\n\n    f(a, b, c)\n\n    if out_dtype != \"float16\":\n        # The numpy reference is computed with fp32 precision (otherwise too slow).\n        # So there is non-trivial accuracy difference if TVM result is computed with fp16 accumulation.\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3)\n\n    return lambda: f.time_evaluator(f.entry_name, dev, number=500)(a, b, c)\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_f16f16f32_m16n16k16():\n    def index_map(i, j):\n        return (\n            i // 16,\n            j // 16,\n            *shared_16x16_to_ldmatrix_32x8_layout(i % 16, j % 16),\n        )\n\n    k_inner = 16\n    in_dtype = \"float16\"\n    out_dtype = \"float32\"\n    i_factors, j_factors, k_factors = [4, 8, 2, 4, 1], [1, 64, 2, 1, 2], [128, 2, 1]\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        False,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map,\n        index_map,\n        index_map,\n        LDMATRIX_16x16_A_INTRIN,\n        LDMATRIX_16x16_B_INTRIN,\n        MMA_f16f16f32_INTRIN,\n        MMA_fill_16x16_f32_INTRIN,\n        MMA_store_16x16_f32_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"f16f16f32_m16n16k16: %f GFLOPS\" % (gflops / (timer().mean)))\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        True,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map,\n        index_map,\n        index_map,\n        LDMATRIX_16x16_A_INTRIN,\n        LDMATRIX_16x16_B_TRANS_INTRIN,\n        MMA_f16f16f32_TRANS_INTRIN,\n        MMA_fill_16x16_f32_INTRIN,\n        MMA_store_16x16_f32_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"f16f16f32_m16n16k16_trans: %f GFLOPS\" % (gflops / (timer().mean)))\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_f16f16f16_m16n16k16():\n    def index_map(i, j):\n        return (\n            i // 16,\n            j // 16,\n            *shared_16x16_to_ldmatrix_32x8_layout(i % 16, j % 16),\n        )\n\n    k_inner = 16\n    in_dtype = \"float16\"\n    out_dtype = \"float16\"\n    i_factors, j_factors, k_factors = [16, 2, 1, 4, 2], [16, 2, 2, 1, 4], [128, 2, 1]\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        False,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map,\n        index_map,\n        index_map,\n        LDMATRIX_16x16_A_INTRIN,\n        LDMATRIX_16x16_B_INTRIN,\n        MMA_f16f16f16_INTRIN,\n        MMA_fill_16x16_f16_INTRIN,\n        MMA_store_16x16_f16_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"f16f16f16_m16n16k16: %f GFLOPS\" % (gflops / (timer().mean)))\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        True,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map,\n        index_map,\n        index_map,\n        LDMATRIX_16x16_A_INTRIN,\n        LDMATRIX_16x16_B_TRANS_INTRIN,\n        MMA_f16f16f16_TRANS_INTRIN,\n        MMA_fill_16x16_f16_INTRIN,\n        MMA_store_16x16_f16_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"f16f16f16_m16n16k16_trans: %f GFLOPS\" % (gflops / (timer().mean)))\n\n\n@tvm.testing.requires_cuda_compute_version(8)\ndef test_i8i8i32_m16n16k32():\n    def index_map_A(i, j):\n        return (\n            i // 16,\n            j // 32,\n            *shared_16x32_to_ldmatrix_32x16_layout(i % 16, j % 32),\n        )\n\n    def index_map_B(i, j):\n        return (\n            i // 32,\n            j // 16,\n            *shared_32x16_to_ldmatrix_32x16_layout(i % 32, j % 16),\n        )\n\n    def index_map_C(i, j):\n        return (\n            i // 16,\n            j // 16,\n            *shared_16x16_to_ldmatrix_32x8_layout(i % 16, j % 16),\n        )\n\n    k_inner = 32\n    in_dtype = \"int8\"\n    out_dtype = \"int32\"\n    i_factors, j_factors, k_factors = [1, 32, 1, 4, 2], [8, 4, 4, 2, 1], [32, 2, 2]\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        False,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map_A,\n        index_map_B,\n        index_map_C,\n        LDMATRIX_16x32_A_INTRIN,\n        LDMATRIX_32x16_B_INTRIN,\n        MMA_i8i8i32_INTRIN,\n        MMA_fill_16x16_i32_INTRIN,\n        MMA_store_16x16_i32_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"i8i8i32_m16n16k32: %f GOPS\" % (gflops / (timer().mean)))\n\n    timer = run_test(\n        k_inner,\n        in_dtype,\n        out_dtype,\n        True,  # b_transposed\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map_A,\n        index_map_A,\n        index_map_C,\n        LDMATRIX_16x32_A_INTRIN,\n        LDMATRIX_16x32_B_TRANS_INTRIN,\n        MMA_i8i8i32_TRANS_INTRIN,\n        MMA_fill_16x16_i32_INTRIN,\n        MMA_store_16x16_i32_global_INTRIN,\n    )\n\n    if measure_perf and timer:\n        print(\"i8i8i32_m16n16k32_trans: %f GOPS\" % (gflops / (timer().mean)))\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_trace.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\n# mypy: ignore-errors\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule import BlockRV, Instruction, InstructionKind, LoopRV, Trace\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef elementwise(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    B = T.alloc_buffer((128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise_inlined(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128))\n    C = T.match_buffer(c, (128, 128))\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = A[vi, vj] * 2.0 + 1.0\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\n\ndef _make_get_block(name, output):\n    return Instruction(\n        kind=InstructionKind.get(\"GetBlock\"),\n        inputs=[],\n        attrs=[name, \"main\"],\n        outputs=[output],\n    )\n\n\ndef _make_get_loops(input, outputs):  # pylint: disable=redefined-builtin\n    return Instruction(\n        kind=InstructionKind.get(\"GetLoops\"),\n        inputs=[input],\n        attrs=[],\n        outputs=outputs,\n    )\n\n\ndef _make_compute_inline(input):  # pylint: disable=redefined-builtin\n    return Instruction(\n        kind=InstructionKind.get(\"ComputeInline\"),\n        inputs=[input],\n        attrs=[],\n        outputs=[],\n    )\n\n\ndef _make_split(inputs, outputs):  # pylint: disable=redefined-builtin\n    return Instruction(\n        kind=InstructionKind.get(\"Split\"),\n        inputs=inputs,\n        attrs=[True],\n        outputs=outputs,\n    )\n\n\ndef _make_enter_postproc():\n    return Instruction(\n        kind=InstructionKind.get(\"EnterPostproc\"),\n        inputs=[],\n        attrs=[],\n        outputs=[],\n    )\n\n\ndef _make_annotate(block: BlockRV, annotation: str):\n    return Instruction(\n        kind=InstructionKind.get(\"Annotate\"),\n        inputs=[block, annotation],\n        attrs=[\"meta_schedule.auto_tensorize\"],\n        outputs=[],\n    )\n\n\ndef _make_trace_1(b0, l1, l2):  # pylint: disable=invalid-name\n    return Trace(\n        insts=[\n            _make_get_block(name=\"block\", output=b0),\n            _make_get_loops(input=b0, outputs=[l1, l2]),\n        ],\n        decisions={},\n    )\n\n\ndef _make_trace_2(b0):  # pylint: disable=invalid-name\n    return Trace(\n        insts=[\n            _make_get_block(name=\"B\", output=b0),\n            _make_compute_inline(input=b0),\n        ],\n        decisions={},\n    )\n\n\ndef _make_trace_3(b0, b1, add_postproc):  # pylint: disable=invalid-name\n    if add_postproc:\n        insts = [\n            _make_get_block(name=\"B\", output=b0),\n            _make_compute_inline(input=b0),\n            _make_get_block(name=\"C\", output=b1),\n            _make_enter_postproc(),\n            _make_compute_inline(input=b1),\n        ]\n    else:\n        insts = [\n            _make_get_block(name=\"B\", output=b0),\n            _make_compute_inline(input=b0),\n            _make_get_block(name=\"C\", output=b1),\n        ]\n    return Trace(insts=insts, decisions={})\n\n\ndef _make_trace_4(b0, l1, l2, l3):  # pylint: disable=invalid-name\n    return Trace(\n        insts=[\n            _make_get_block(name=\"B\", output=b0),\n            _make_get_loops(input=b0, outputs=[l1]),\n            _make_split([l1, None, 32], [l2, l3]),\n        ],\n        decisions={},\n    )\n\n\ndef test_trace_construct_1():\n    trace = _make_trace_1(BlockRV(), LoopRV(), LoopRV())\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"block\", func_name=\"main\")',\n            \"  l1, l2 = sch.get_loops(block=b0)\",\n        )\n    )\n    assert len(trace.insts) == 2\n    assert len(trace.decisions) == 0\n\n\ndef test_trace_construct_get_decision_1():\n    trace = _make_trace_1(BlockRV(), LoopRV(), LoopRV())\n    assert trace.get_decision(trace.insts[0]) is None\n    assert trace.get_decision(trace.insts[1]) is None\n\n\ndef test_trace_construct_append_1():\n    trace = _make_trace_1(BlockRV(), LoopRV(), LoopRV())\n    trace.append(inst=_make_get_block(\"block2\", BlockRV()))\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"block\", func_name=\"main\")',\n            \"  l1, l2 = sch.get_loops(block=b0)\",\n            '  b3 = sch.get_block(name=\"block2\", func_name=\"main\")',\n        )\n    )\n\n\ndef test_trace_construct_pop_1():\n    trace = _make_trace_1(BlockRV(), LoopRV(), LoopRV())\n    last_inst = trace.insts[-1]\n    assert trace.pop().same_as(last_inst)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"block\", func_name=\"main\")',\n        )\n    )\n\n\ndef test_trace_construct_pop_2():\n    trace = Trace([], {})\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            \"  pass\",\n        )\n    )\n    assert trace.pop() is None\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            \"  pass\",\n        )\n    )\n\n\ndef test_trace_apply_to_schedule():\n    trace = _make_trace_2(BlockRV())\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    trace.apply_to_schedule(sch, remove_postproc=False, decision_provider=None)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n\n\ndef test_trace_as_json_1():\n    trace = _make_trace_1(BlockRV(), LoopRV(), LoopRV())\n    obj = trace.as_json()\n    assert obj == [\n        [\n            [\"GetBlock\", [], [\"block\", \"main\"], [\"b0\"]],\n            [\"GetLoops\", [\"b0\"], [], [\"l1\", \"l2\"]],\n        ],\n        [],\n    ]\n\n\ndef test_trace_simplified_1():\n    trace = _make_trace_3(BlockRV(), BlockRV(), add_postproc=True)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"B\", func_name=\"main\")',\n            \"  sch.compute_inline(block=b0)\",\n            '  b1 = sch.get_block(name=\"C\", func_name=\"main\")',\n            \"  sch.enter_postproc()\",\n            \"  sch.compute_inline(block=b1)\",\n        )\n    )\n    trace = trace.simplified(remove_postproc=True)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"B\", func_name=\"main\")',\n            \"  sch.compute_inline(block=b0)\",\n        )\n    )\n\n\ndef test_trace_simplified_2():\n    trace = _make_trace_3(BlockRV(), BlockRV(), add_postproc=True)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"B\", func_name=\"main\")',\n            \"  sch.compute_inline(block=b0)\",\n            '  b1 = sch.get_block(name=\"C\", func_name=\"main\")',\n            \"  sch.enter_postproc()\",\n            \"  sch.compute_inline(block=b1)\",\n        )\n    )\n    trace = trace.simplified(remove_postproc=False)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"B\", func_name=\"main\")',\n            \"  sch.compute_inline(block=b0)\",\n            '  b1 = sch.get_block(name=\"C\", func_name=\"main\")',\n            \"  sch.enter_postproc()\",\n            \"  sch.compute_inline(block=b1)\",\n        )\n    )\n\n\ndef test_trace_simplified_3():\n    trace = _make_trace_4(BlockRV(), LoopRV(), LoopRV(), LoopRV()).simplified(remove_postproc=False)\n    assert str(trace) == \"\\n\".join(\n        (\n            \"# from tvm import tir\",\n            \"def apply_trace(sch: tir.Schedule) -> None:\",\n            '  b0 = sch.get_block(name=\"B\", func_name=\"main\")',\n            \"  l1, = sch.get_loops(block=b0)\",\n            \"  l2, l3 = sch.split(loop=l1, factors=[None, 32], preserve_unit_iters=True)\",\n        )\n    )\n\n\ndef test_apply_json_to_schedule_1():\n    trace = _make_trace_2(BlockRV())\n    json_obj = trace.as_json()\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    Trace.apply_json_to_schedule(json_obj, sch)\n    tvm.ir.assert_structural_equal(elementwise_inlined, sch.mod[\"main\"])\n\n\ndef _test_apply_annotation_trace_from_json(annotation: str):\n    \"\"\"Test applying an annotation works without crashing.\n\n    Designed to handle some previously failing edge cases like the\n    empty string.\n    \"\"\"\n    b0 = BlockRV()\n    trace = Trace(\n        insts=[\n            _make_get_block(name=\"B\", output=b0),\n            _make_annotate(block=b0, annotation=annotation),\n        ],\n        decisions={},\n    )\n    json_obj = trace.as_json()\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    Trace.apply_json_to_schedule(json_obj, sch)\n\n    @T.prim_func\n    def elementwise_expected(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (128, 128))\n        B = T.alloc_buffer((128, 128))\n        C = T.match_buffer(c, (128, 128))\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                T.block_attr({\"meta_schedule.auto_tensorize\": annotation})\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for i, j in T.grid(128, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n    tvm.ir.assert_structural_equal(elementwise_expected, sch.mod[\"main\"])\n\n\ndef test_apply_annotation_from_json():\n    # Something reasonable\n    _test_apply_annotation_trace_from_json(\"SSRSSR\")\n\n    # The empty string\n    _test_apply_annotation_trace_from_json(\"\")\n\n    # A string of two quotation marks\n    _test_apply_annotation_trace_from_json('\"\"')\n\n    # A string of one quotation mark\n    _test_apply_annotation_trace_from_json('\"')\n\n\nif __name__ == \"__main__\":\n    test_trace_simplified_2()\n    # tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.tir import Schedule\nfrom tvm.tir.schedule.transform import tile_with_tensor_intrin\nfrom tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN\n\n\n@tvm.script.ir_module\nclass DenseVNNIModule:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1024, 1024), \"uint8\"],\n        placeholder_1: T.Buffer[(64, 256, 16, 4), \"int8\"],\n        compute: T.Buffer[(1024, 1024), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            for i0, i1, i2 in T.grid(1024, 1024, 1024):\n                with T.block(\"compute\"):\n                    i, j, k = T.axis.remap(\"SSR\", [i0, i1, i2])\n                    T.reads(placeholder[i, k], placeholder_1[j // 16, k // 4, j % 16, k % 4])\n                    T.writes(compute[i, j])\n                    with T.init():\n                        compute[i, j] = 0\n                    compute[i, j] = compute[i, j] + T.cast(placeholder[i, k], \"int32\") * T.cast(\n                        placeholder_1[j // 16, k // 4, j % 16, k % 4], \"int32\"\n                    )\n\n\n@tvm.script.ir_module\nclass DenseVNNIModuleTiled:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1024, 1024), \"uint8\"],\n        placeholder_1: T.Buffer[(64, 256, 16, 4), \"int8\"],\n        compute: T.Buffer[(1024, 1024), \"int32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1_0, i2_0, i1_1, i2_1 in T.grid(1024, 64, 256, 16, 4):\n            with T.block(\"compute\"):\n                i = T.axis.spatial(1024, i0)\n                j = T.axis.spatial(1024, i1_0 * 16 + i1_1)\n                k = T.axis.reduce(1024, i2_0 * 4 + i2_1)\n                T.reads(placeholder[i, k], placeholder_1[j // 16, k // 4, j % 16, k % 4])\n                T.writes(compute[i, j])\n                with T.init():\n                    compute[i, j] = 0\n                compute[i, j] = compute[i, j] + T.cast(placeholder[i, k], \"int32\") * T.cast(\n                    placeholder_1[j // 16, k // 4, j % 16, k % 4], \"int32\"\n                )\n\n\n@tvm.script.ir_module\nclass Conv2dNCHWcVNNIModule:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 16, 56, 56, 16, 1, 1, 4, 4, 4):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                (\n                    n,\n                    oc_chunk,\n                    oh,\n                    ow,\n                    oc_block,\n                    kh,\n                    kw,\n                    ic_outer,\n                    ic_f_inner,\n                    ic_s_inner,\n                ) = T.axis.remap(\"SSSSSRRRRR\", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9])\n                T.reads(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                )\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[\n                    n, oc_chunk, oh, ow, oc_block\n                ] + T.cast(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\"\n                ) * T.cast(\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                    \"int32\",\n                )\n\n\n@tvm.script.ir_module\nclass Conv2dNCHWcVNNIModuleTiled:\n    @T.prim_func\n    def main(\n        placeholder: T.Buffer[(1, 4, 56, 56, 16), \"uint8\"],\n        placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), \"int8\"],\n        conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), \"int32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2, i3, i4_0, i5, i6, i7, i8, i9_0, i4_1, i9_1 in T.grid(\n            1, 16, 56, 56, 1, 1, 1, 4, 4, 1, 16, 4\n        ):\n            with T.block(\"conv2d_NCHWc_int8\"):\n                n, oc_chunk, oh, ow = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n                oc_block = T.axis.spatial(16, i4_0 * 16 + i4_1)\n                kh, kw, ic_outer, ic_f_inner = T.axis.remap(\"RRRR\", [i5, i6, i7, i8])\n                ic_s_inner = T.axis.reduce(4, i9_0 * 4 + i9_1)\n                T.reads(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner],\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                )\n                T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block])\n                with T.init():\n                    conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0\n                conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[\n                    n, oc_chunk, oh, ow, oc_block\n                ] + T.cast(\n                    placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], \"int32\"\n                ) * T.cast(\n                    placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner],\n                    \"int32\",\n                )\n\n\ndef test_tile_with_tensor_intrin_dense_vnni():\n    s = Schedule(DenseVNNIModule)\n    block = s.get_block(\"compute\")\n\n    tiled_loop = tile_with_tensor_intrin(s, block, VNNI_DOT_16x4_INTRIN)\n\n    _, _, _, i1_1, _ = s.get_loops(block)\n\n    assert s.get(tiled_loop) == s.get(i1_1)\n    tvm.ir.assert_structural_equal(s.mod, DenseVNNIModuleTiled)\n\n\ndef test_tile_with_tensor_intrin_conv2d_nchwc_vnni():\n    s = Schedule(Conv2dNCHWcVNNIModule)\n    block = s.get_block(\"conv2d_NCHWc_int8\")\n    tiled_loop = tile_with_tensor_intrin(s, block, VNNI_DOT_16x4_INTRIN)\n    tiled_loops = s.get_loops(block)\n    assert len(tiled_loops) == 12\n    assert s.get(tiled_loop) == s.get(tiled_loops[-2])\n    tvm.ir.assert_structural_equal(s.mod, Conv2dNCHWcVNNIModuleTiled)\n\n\nif __name__ == \"__main__\":\n    test_tile_with_tensor_intrin_dense_vnni()\n    test_tile_with_tensor_intrin_conv2d_nchwc_vnni()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_transform_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n\ndef packed_index_map_func(m, n):\n    return m // 16, n // 16, m % 16, n % 16\n\n\n@T.prim_func\ndef two_elementwise(A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef two_elementwise_transformed_intermediate_buffer(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((8, 8, 16, 16), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi // 16, vj // 16, vi % 16, vj % 16] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi // 16, vj // 16, vi % 16, vj % 16] + 1.0\n\n\n@T.prim_func\ndef two_elementwise_transformed_input_buffer(\n    A: T.Buffer[(8, 8, 16, 16), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi // 16, vj // 16, vi % 16, vj % 16] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef two_elementwise_transformed_output_buffer(\n    A: T.Buffer[(128, 128), \"float32\"], C: T.Buffer[(8, 8, 16, 16), \"float32\"]\n) -> None:\n    B = T.alloc_buffer((128, 128), \"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(128, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi // 16, vj // 16, vi % 16, vj % 16] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef elementwise(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]) -> None:\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n\n@T.prim_func\ndef elementwise_transformed(A: T.Buffer[(128, 128), \"float32\"], B: T.Buffer[(128, 128), \"float32\"]) -> None:\n    for i in range(16384):\n        with T.block(\"B\"):\n            vi = T.axis.remap(\"S\", [i])\n            B[vi // 128, vi % 128] = A[vi // 128, vi % 128] * 2.0\n\n\n@T.prim_func\ndef conv2d_nhwc(\n    Input: T.Buffer[(1, 224, 224, 3), \"float32\"],\n    Weight: T.Buffer[(7, 7, 3, 64), \"float32\"],\n    Conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"],\n) -> None:\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                ((((i1_1 >= 3) and (i1_1 < 227)) and (i2_1 >= 3)) and (i2_1 < 227)),\n                Input[i0_1, (i1_1 - 3), (i2_1 - 3), i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 112, 112, 64, 7, 7, 3):\n        with T.block(\"conv2d_nhwc\"):\n            n, h, w, co, rh, rw, rc = T.axis.remap(\"SSSSRRR\", [i0, i1, i2, i3, i4, i5, i6])\n            with T.init():\n                Conv2d_nhwc[n, h, w, co] = T.float32(0)\n            Conv2d_nhwc[n, h, w, co] = Conv2d_nhwc[n, h, w, co] + (\n                PadInput[n, ((h * 2) + rh), ((w * 2) + rw), ((T.floordiv(co, 64) * 3) + rc)]\n                * Weight[rh, rw, rc, co]\n            )\n\n\n@T.prim_func\ndef conv2d_nhwc_transformed(\n    Input: T.Buffer[(1, 224, 224, 3), \"float32\"],\n    Weight: T.Buffer[(7, 7, 3, 64), \"float32\"],\n    Conv2d_nhwc: T.Buffer[(1, 112, 112, 64), \"float32\"],\n) -> None:\n    PadInput = T.alloc_buffer([1, 230, 230, 3], dtype=\"float32\")\n    for i0, i1, i2, i3 in T.grid(1, 230, 230, 3):\n        with T.block(\"PadInput\"):\n            i0_1, i1_1, i2_1, i3_1 = T.axis.remap(\"SSSS\", [i0, i1, i2, i3])\n            T.reads(Input[i0_1, i1_1 - 3, i2_1 - 3, i3_1])\n            T.writes(PadInput[i0_1, i1_1, i2_1, i3_1])\n            PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(\n                i1_1 >= 3 and i1_1 < 227 and i2_1 >= 3 and i2_1 < 227,\n                Input[i0_1, i1_1 - 3, i2_1 - 3, i3_1],\n                T.float32(0),\n                dtype=\"float32\",\n            )\n    for ax0, ax1, ax2 in T.grid(12544, 64, 147):\n        with T.block(\"conv2d_nhwc\"):\n            v0, v1, v2 = T.axis.remap(\"SSR\", [ax0, ax1, ax2])\n            T.reads(PadInput[v0 // 12544, v0 // 112 * 2 + v2 // 21, v0 % 112 * 2 + v2 % 21 // 3, v2 % 3], Weight[v2 // 21, v2 % 21 // 3, v2 % 3, v1])\n            T.writes(Conv2d_nhwc[v0 // 12544, v0 // 112, v0 % 112, v1])\n            with T.init():\n                Conv2d_nhwc[v0 // 12544, v0 // 112, v0 % 112, v1] = T.float32(0)\n            Conv2d_nhwc[v0 // 12544, v0 // 112, v0 % 112, v1] = Conv2d_nhwc[v0 // 12544, v0 // 112, v0 % 112, v1] + PadInput[v0 // 12544, v0 // 112 * 2 + v2 // 21, v0 % 112 * 2 + v2 % 21 // 3, v2 % 3] * Weight[v2 // 21, v2 % 21 // 3, v2 % 3, v1]\n\n\n@T.prim_func\ndef two_elementwise_unit_dim(A: T.Buffer[(1, 128), \"float32\"], C: T.Buffer[(1, 128), \"float32\"]) -> None:\n    B = T.alloc_buffer((1, 128), \"float32\")\n    for i, j in T.grid(1, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(1, 128):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n# pylint: enable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n# fmt: on\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_two_elementwise_transform_intermediate_buffer(use_block_name):\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n\n    if use_block_name:\n        sch.transform_layout(\n            block=\"B\",\n            buffer=\"B\",\n            index_map=packed_index_map_func,\n        )\n    else:\n        block = sch.get_block(\"B\")\n        sch.transform_layout(block, (\"write\", 0), packed_index_map_func)\n\n    tvm.ir.assert_structural_equal(two_elementwise_transformed_intermediate_buffer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise)\n\n\ndef test_two_elementwise_transform_input_buffer(use_block_name):\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n\n    if use_block_name:\n        sch.transform_layout(\n            index_map=packed_index_map_func,\n            block=\"B\",\n            buffer=\"A\",\n        )\n    else:\n        block = sch.get_block(\"B\")\n        sch.transform_layout(block, (\"read\", 0), packed_index_map_func)\n\n    tvm.ir.assert_structural_equal(two_elementwise_transformed_input_buffer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise)\n\n\ndef test_two_elementwise_transform_output_buffer(use_block_name):\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n\n    if use_block_name:\n        sch.transform_layout(\n            index_map=packed_index_map_func,\n            block=\"C\",\n            buffer=\"C\",\n        )\n    else:\n        block = sch.get_block(\"C\")\n        sch.transform_layout(block, (\"write\", 0), packed_index_map_func)\n\n    tvm.ir.assert_structural_equal(two_elementwise_transformed_output_buffer, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise)\n\n\ndef test_two_elementwise_unit_dim(use_block_name):\n    sch = tir.Schedule(two_elementwise_unit_dim, debug_mask=\"all\")\n    index_map = lambda i, j: (i, j)\n\n    if use_block_name:\n        sch.transform_layout(\n            index_map=index_map,\n            block=\"B\",\n            buffer=\"B\",\n        )\n    else:\n        block = sch.get_block(\"B\")\n        sch.transform_layout(block, (\"write\", 0), index_map)\n\n    tvm.ir.assert_structural_equal(two_elementwise_unit_dim, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise_unit_dim)\n\n\ndef test_simplify():\n    sch = tir.Schedule(two_elementwise, debug_mask=\"all\")\n\n    i, j = sch.get_loops(sch.get_block(\"C\"))\n    i, i_inner = sch.split(i, factors=[None, 16])\n    j, j_inner = sch.split(j, factors=[None, 16])\n\n    sch.reorder(\n        i,\n        j,\n        i_inner,\n        j_inner,\n    )\n\n    block_outer = sch.blockize(i_inner)\n\n    B = sch.cache_read(block_outer, 0, \"global\")\n    sch.transform_layout(B, (\"write\", 0), lambda i, j: (i // 16, j // 16, i % 16, j % 16))\n\n    @T.prim_func\n    def ref(B: T.Buffer[(8, 8, 16, 16), \"float32\"], C: T.Buffer[(128, 128), \"float32\"]):\n        for i_0, j_0 in T.grid(8, 8):\n            with T.block(\"C_o\"):\n                vi_o, vj_o = T.axis.remap(\"SS\", [i_0, j_0])\n                T.reads(B[vi_o, vj_o, 0:16, 0:16])\n                T.writes(C[vi_o * 16 : vi_o * 16 + 16, vj_o * 16 : vj_o * 16 + 16])\n                for i_1, j_1 in T.grid(16, 16):\n                    with T.block(\"C\"):\n                        vi, vj = T.axis.remap(\"SS\", [i_1, j_1])\n                        T.reads(B[vi_o, vj_o, vi, vj])\n                        T.writes(C[vi_o * 16 + vi, vj_o * 16 + vj])\n                        C[vi_o * 16 + vi, vj_o * 16 + vj] = B[vi_o, vj_o, vi, vj] + T.float32(1)\n\n                        # Without simplification\n                        # T.reads(B[vi // 16 + vi_o, vj // 16 + vj_o, vi % 16, vj % 16])\n                        # C[...] = B[vi // 16 + vi_o, vj // 16 + vj_o, vi % 16, vj % 16] + T.float32(1)\n\n    tvm.ir.assert_structural_equal(ref.body.block.body, sch.get(sch.get_loops(block_outer)[0]))\n\n\ndef test_var_args_sugar():\n    @T.prim_func\n    def summation_3d(\n        A: T.Buffer[(1024, 1024, 32), \"float32\"], B: T.Buffer[(1,), \"float32\"]\n    ) -> None:\n        B[0] = 0\n        for i, j, k in T.grid(1024, 1024, 32):\n            with T.block(\"compute\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                B[0] = B[0] + A[vi, vj, vk]\n\n    @T.prim_func\n    def summation_3d_split(\n        A: T.Buffer[(1024, 1024, 8, 4), \"float32\"], B: T.Buffer[(1,), \"float32\"]\n    ) -> None:\n        B[0] = 0\n        for i, j, k in T.grid(1024, 1024, 32):\n            with T.block(\"compute\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                B[0] = B[0] + A[vi, vj, vk // 4, vk % 4]\n\n    sch = tir.Schedule(summation_3d, debug_mask=\"all\")\n    sch.transform_layout(\n        index_map=lambda *indices, k: [*indices, k // 4, k % 4], block=\"compute\", buffer=\"A\"\n    )\n    tvm.ir.assert_structural_equal(summation_3d_split, sch.mod[\"main\"])\n\n\ndef test_transform_block_layout_basic(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.transform_block_layout(block, lambda i, j: (i * 128 + j,))\n    tvm.ir.assert_structural_equal(elementwise_transformed, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise)\n\n\ndef test_transform_block_layout_conv2d_nhwc(use_block_name):\n    sch = tir.Schedule(conv2d_nhwc, debug_mask=\"all\")\n    block = \"conv2d_nhwc\" if use_block_name else sch.get_block(\"conv2d_nhwc\")\n    sch.transform_block_layout(\n        block,\n        lambda n, h, w, co, rh, rw, rc: (n * 112 * 112 + h * 112 + w, co, rh * 7 * 3 + rw * 3 + rc),\n    )\n    tvm.ir.assert_structural_equal(conv2d_nhwc_transformed, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=conv2d_nhwc)\n\n\ndef test_transform_block_layout_unit_dim(use_block_name):\n    sch = tir.Schedule(two_elementwise_unit_dim, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.transform_block_layout(block, lambda i, j: (j, i))\n\n    @T.prim_func\n    def two_elementwise_unit_dim_transformed(\n        A: T.Buffer[(1, 128), \"float32\"], C: T.Buffer[(1, 128), \"float32\"]\n    ) -> None:\n        B = T.alloc_buffer((1, 128), \"float32\")\n        for j, i in T.grid(128, 1):\n            with T.block(\"B\"):\n                vj, vi = T.axis.remap(\"SS\", [j, i])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for i, j in T.grid(1, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n    tvm.ir.assert_structural_equal(two_elementwise_unit_dim_transformed, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=two_elementwise_unit_dim)\n\n\ndef test_transform_block_layout_fail_non_affine(use_block_name):\n    sch = tir.Schedule(elementwise, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    with pytest.raises(tir.ScheduleError):\n        sch.transform_block_layout(block, lambda i, j: (i + j,))\n\n\ndef test_transform_block_layout_fail_mixed_iter_type(use_block_name):\n    sch = tir.Schedule(conv2d_nhwc, debug_mask=\"all\")\n    block = \"conv2d_nhwc\" if use_block_name else sch.get_block(\"conv2d_nhwc\")\n    with pytest.raises(tir.ScheduleError):\n        sch.transform_block_layout(\n            block,\n            lambda n, h, w, co, rh, rw, rc: (n * 112 * 112 + h * 112 + w, co * 7 + rh, rw * 3 + rc),\n        )\n\n\ndef test_transform_block_layout_int64_extent(use_block_name):\n    @T.prim_func\n    def elementwise_int64_extent(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i, j in T.grid(T.int64(128), T.int64(128)):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n\n    @T.prim_func\n    def elementwise_int64_extent_transformed(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i in range(T.int64(16384)):\n            with T.block(\"B\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi // T.int64(128), vi % T.int64(128)] = (\n                    A[vi // T.int64(128), vi % T.int64(128)] * 2.0\n                )\n\n    sch = tir.Schedule(elementwise_int64_extent, debug_mask=\"all\")\n    block = \"B\" if use_block_name else sch.get_block(\"B\")\n    sch.transform_block_layout(block, lambda i, j: (i * 128 + j,))\n    print(\n        tvm.ir.base.get_first_structural_mismatch(\n            elementwise_int64_extent_transformed, sch.mod[\"main\"]\n        )\n    )\n    tvm.ir.assert_structural_equal(elementwise_int64_extent_transformed, sch.mod[\"main\"])\n    verify_trace_roundtrip(sch=sch, mod=elementwise_int64_extent)\n\n\nclass BasePaddingCompare(tvm.testing.CompareBeforeAfter):\n    pad_value = tvm.testing.parameter(None)\n\n    transformed_buffer = tvm.testing.parameter(\"A\")\n\n    @pytest.fixture\n    def transform(self, pad_value, transformed_buffer):\n        def transform(mod):\n            sch = tir.Schedule(mod)\n            sch.transform_layout(\n                \"block\", transformed_buffer, lambda i: [i // 4, i % 4], pad_value=pad_value\n            )\n            return sch.mod\n\n        return transform\n\n\nclass TestNoPadding(BasePaddingCompare):\n    \"\"\"Transformations without padding do not depend on pad_value.\"\"\"\n\n    pad_value = tvm.testing.parameter(None, 42)\n\n    def before():\n        A = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi] = 0\n\n    def expected():\n        A = T.alloc_buffer([4, 4], \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi // 4, vi % 4] = 0\n\n\nclass TestNoPaddingMultipleUsage(BasePaddingCompare):\n    \"\"\"Transformations without padding do not depend on pad_value.\n\n    Like TestNoPadding, but the buffer A shows up in multiple\n    locations.  To remain internally consistent, all instances of the\n    buffer should be rewritten.\n    \"\"\"\n\n    pad_value = tvm.testing.parameter(None, 42)\n\n    def before():\n        A = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi] = 0\n\n        B = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"other\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    def expected():\n        A = T.alloc_buffer([4, 4], \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi // 4, vi % 4] = 0\n\n        B = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"other\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi // 4, vi % 4]\n\n\nclass TestNoPaddingOpaqueBlock(BasePaddingCompare):\n    \"\"\"Transformations without padding do not depend on pad_value.\n\n    Like TestNoPadding, but buffer access is done in an opaque block.\n    \"\"\"\n\n    pad_value = tvm.testing.parameter(None, 42)\n\n    def before():\n        A = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                A[i] = 0\n\n    def expected():\n        A = T.alloc_buffer([4, 4], \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                A[i // 4, i % 4] = 0\n\n\nclass TestErrorIfPaddingForbidden(BasePaddingCompare):\n    \"\"\"Unless padding is explicitly enabled, should raise error\"\"\"\n\n    def before():\n        A = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi] = 0\n\n    expected = tvm.tir.schedule.schedule.ScheduleError\n\n\nclass TestErrorOnWrongPaddingType(BasePaddingCompare):\n    \"\"\"The padding must have the same dtype as the buffer\"\"\"\n\n    pad_value = tvm.testing.parameter(tir.IntImm(\"int8\", 0))\n\n    def before():\n        A = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                A[vi] = 0\n\n    expected = tvm.tir.schedule.schedule.ScheduleError\n\n\nclass TestPaddedTransformIfThenElse(BasePaddingCompare):\n    \"\"\"Use if_then_else to represent padding, if possible.\n\n    For a block that is a producer of the pre-transformation buffer,\n    which visits all indices according to a row-major traversal, and\n    which has no effect other than producing the transformed buffer,\n    transform the loop iterators to be a row-major traversal of the\n    post-transformation buffer, with padding represented by\n    `T.if_then_else`.\n    \"\"\"\n\n    pad_value = tvm.testing.parameter(0)\n    transformed_buffer = tvm.testing.parameter(\"B\")\n    dtype = tvm.testing.parameter(\"int32\", \"int8\")\n\n    @tvm.testing.fixture\n    def before(self, dtype):\n        @T.prim_func\n        def func(A: T.Buffer[14, dtype]):\n            B = T.alloc_buffer(14, dtype)\n            for i in T.serial(14):\n                with T.block(\"block\"):\n                    vi = T.axis.remap(\"S\", [i])\n                    B[vi] = A[vi]\n\n        return func\n\n    @tvm.testing.fixture\n    def expected(self, dtype, pad_value):\n        pad_value = tir.IntImm(dtype, pad_value)\n\n        @T.prim_func\n        def func(A: T.Buffer[14, dtype]):\n            B = T.alloc_buffer([4, 4], dtype)\n            for i, j in T.grid(4, 4):\n                with T.block(\"block\"):\n                    vi, vj = T.axis.remap(\"SS\", [i, j])\n                    B[vi, vj] = T.if_then_else(\n                        vi == 3 and 2 <= vj, pad_value, A[vi * 4 + vj], dtype=dtype\n                    )\n\n        return func\n\n\nclass TestPaddedTransformWithoutLoop(BasePaddingCompare):\n    \"\"\"Handle padded writes without a loop\n\n    The statement being replaced may be something other than a\n    for-loop, such as if a loop has already been unrolled.\n    \"\"\"\n\n    pad_value = tvm.testing.parameter(0)\n\n    def before(A: T.Buffer[14, \"int32\"]):\n        with T.block(\"root\"):\n            T.reads()\n            T.writes()\n            with T.block(\"block\"):\n                A[0] = 0\n\n    def expected(A: T.Buffer[(4, 4), \"int32\"]):\n        with T.block(\"block\"):\n            A[0, 0] = 0\n\n        for i, j in T.grid(4, 4):\n            with T.block(\"buffer_A_padding\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.where(i == 3 and 2 <= j)\n                A[vi, vj] = 0\n\n\nclass TestPaddedTransformIfThenElseReduction(BasePaddingCompare):\n    \"\"\"Like TestPaddedTransformIfThenElse, but with a reduction axis\"\"\"\n\n    pad_value = tvm.testing.parameter(0)\n    transformed_buffer = tvm.testing.parameter(\"B\")\n\n    def before(A: T.Buffer[(14, 32), \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        for i, k in T.grid(14, 32):\n            with T.block(\"block\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                with T.init():\n                    B[vi] = 0\n                B[vi] = B[vi] + A[vi, vk]\n\n    def expected(A: T.Buffer[(14, 32), \"int32\"]):\n        B = T.alloc_buffer([4, 4], \"int32\")\n        for i, j, k in T.grid(4, 4, 32):\n            with T.block(\"block\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    B[vi, vj] = T.if_then_else(vi == 3 and 2 <= vj, 0, 0, dtype=\"int32\")\n                B[vi, vj] = T.if_then_else(\n                    vi == 3 and 2 <= vj, 0, B[vi, vj] + A[vi * 4 + vj, vk], dtype=\"int32\"\n                )\n\n\nclass TestPaddedTransformIfThenElseReductionOpaque(BasePaddingCompare):\n    \"\"\"Like TestPaddedTransformIfThenElseReduction, but with opaque blocks\"\"\"\n\n    pad_value = tvm.testing.parameter(0)\n    transformed_buffer = tvm.testing.parameter(\"B\")\n\n    def before(A: T.Buffer[(14, 32), \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            B[i] = 0\n            for k in T.serial(32):\n                with T.block(\"block\"):\n                    B[i] = B[i] + A[i, k]\n\n    def expected(A: T.Buffer[(14, 32), \"int32\"]):\n        B = T.alloc_buffer([4, 4], \"int32\")\n        for i, j in T.grid(4, 4):\n            B[i, j] = T.if_then_else(i == 3 and 2 <= j, 0, 0, dtype=\"int32\")\n            for k in T.serial(32):\n                with T.block(\"block\"):\n                    B[i, j] = T.if_then_else(\n                        i == 3 and 2 <= j, 0, B[i, j] + A[i * 4 + j, k], dtype=\"int32\"\n                    )\n\n\nclass TestPaddedTransformPostProcIfRequiredDueToSideEffects(BasePaddingCompare):\n    \"\"\"Set the transformation padding in a post-processing block.\n\n    Like TestPaddedTransformIfThenElse, but the block that produces B\n    also has the effect of setting `C`.\n    \"\"\"\n\n    pad_value = tvm.testing.parameter(0)\n    transformed_buffer = tvm.testing.parameter(\"B\")\n\n    def before(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        C = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n                C[vi] = 0\n\n    def expected(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer([4, 4], \"int32\")\n        C = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi // 4, vi % 4] = A[vi]\n                C[vi] = 0\n\n        for i, j in T.grid(4, 4):\n            with T.block(\"block_pad_B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.where(i == 3 and 2 <= j)\n                B[vi, vj] = 0\n\n\nclass TestPaddedTransformOfInputCreatesAssumption(BasePaddingCompare):\n    \"\"\"Transformation of an input buffer places T.assume locally\"\"\"\n\n    pad_value = tvm.testing.parameter(42)\n\n    def before(A: T.Buffer[14, \"int32\"], B: T.Buffer[14, \"int32\"]):\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    def expected(A: T.Buffer[(4, 4), \"int32\"], B: T.Buffer[14, \"int32\"]):\n        for i, j in T.grid(4, 4):\n            with T.block(\"buffer_A_assumption\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.evaluate(T.assume(not (vi == 3 and 2 <= vj) or A[vi, vj] == 42))\n\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi // 4, vi % 4]\n\n\nclass TestPaddedTransformNonConstantValue(tvm.testing.CompareBeforeAfter):\n    \"\"\"Allow an expression to specify the pad value.\n\n    Like TestPaddedTransformIfThenElse, but the pad value depends on\n    the indices.\n    \"\"\"\n\n    @pytest.fixture\n    def transform(self):\n        def transform(mod):\n            sch = tir.Schedule(mod)\n            sch.transform_layout(\n                \"block\",\n                \"B\",\n                lambda i: [i // 4, i % 4],\n                pad_value=lambda i, j: i + j,\n            )\n            return sch.mod\n\n        return transform\n\n    def before(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    def expected(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer([4, 4], \"int32\")\n        for i, j in T.grid(4, 4):\n            with T.block(\"block\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = T.if_then_else(\n                    vi == 3 and 2 <= vj, vi + vj, A[vi * 4 + vj], dtype=\"int32\"\n                )\n\n\n@pytest.mark.xfail(reason=\"Not yet implemented\")\nclass TestPaddedTransformRepeatedBufferElement(tvm.testing.CompareBeforeAfter):\n    \"\"\"Allow an expression to specify the pad value.\n\n    Like TestPaddedTransformOfInputCreatesAssumption, but the pad\n    value depends on another portion of the buffer.  In this case, the\n    padding at the end of A contains repeated elements from the\n    beginning of A.\n    \"\"\"\n\n    @pytest.fixture\n    def transform(self):\n        def transform(mod):\n            sch = tir.Schedule(mod)\n\n            A = sch.get(sch.get_block(\"block\")).reads[0].buffer\n            sch.transform_layout(\n                \"block\",\n                \"A\",\n                lambda i: [i // 4, i % 4],\n                pad_value=lambda i, j: A[(4 * i + j) % 14],\n            )\n            return sch.mod\n\n        return transform\n\n    def before(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    def expected(A: T.Buffer[(4, 4), \"int32\"]):\n        for i, j in T.grid(4, 4):\n            with T.block(\"buffer_A_assumption\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.evaluate(\n                    T.assume(\n                        not (vi == 3 and 2 <= vj)\n                        or A[vi, vj] == A[((4 * vi + j) % 14) // 4, ((4 * vi + j) % 14) % 4]\n                    )\n                )\n\n        B = T.alloc_buffer(14, \"int32\")\n        for i in T.grid(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi // 4, vi % 4]\n\n\nclass TestPadValueMayNotReferenceOtherBuffer(tvm.testing.CompareBeforeAfter):\n    \"\"\"Allow an expression to specify the pad value.\n\n    Like TestPaddedTransformRepeatedBufferElement, but the pad value depends on\n    a different buffer, which is not allowed.\n    \"\"\"\n\n    @pytest.fixture\n    def transform(self):\n        def transform(mod):\n            sch = tir.Schedule(mod)\n\n            A = sch.get(sch.get_block(\"block\")).reads[0].buffer\n            other = tir.decl_buffer(1, A.dtype, name=\"other\")\n            sch.transform_layout(\n                \"block\",\n                \"A\",\n                lambda i: [i // 4, i % 4],\n                pad_value=lambda i, j: other[0],\n            )\n            return sch.mod\n\n        return transform\n\n    def before(A: T.Buffer[14, \"int32\"]):\n        B = T.alloc_buffer(14, \"int32\")\n        for i in T.serial(14):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    expected = tvm.tir.schedule.schedule.ScheduleError\n\n\nclass TestTransformLayoutWithVar(tvm.testing.CompareBeforeAfter):\n    \"\"\"Layout transform with dynamic parameter in transform\"\"\"\n\n    @pytest.fixture\n    def transform(self):\n        def transform(mod):\n            sch = tir.Schedule(mod)\n\n            n = sch.mod[\"main\"].params[1]\n\n            sch.transform_layout(\n                \"block\",\n                \"B\",\n                lambda i: [i // n, i % n],\n                pad_value=0,\n            )\n            return sch.mod\n\n        return transform\n\n    def before(A: T.Buffer[16, \"int32\"], n: T.int32):\n        B = T.alloc_buffer(16, \"int32\")\n        for i in T.serial(16):\n            with T.block(\"block\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    def expected(A: T.Buffer[16, \"int32\"], n: T.int32):\n        B = T.alloc_buffer([(-16 % n + 16) // n, n], dtype=\"int32\")\n        for i, j in T.grid((-16 % n + 16) // n, n):\n            with T.block(\"block\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = T.if_then_else(\n                    # Checks if the transform introduced padding\n                    -16 % n != 0\n                    and (\n                        # If so, is vi in the last group (which may\n                        # include padding).\n                        (vj + vi * n) // n == 16 // n\n                        # And is vj within the padding\n                        and 16 % n <= (vj + vi * n) % n\n                    ),\n                    0,\n                    A[vj + vi * n],\n                    dtype=\"int32\",\n                )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_schedule_utilities.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.ir import IRModule\nfrom tvm.script import tir as T\nfrom tvm.tir.schedule.testing import verify_trace_roundtrip\n\n# pylint: disable=no-member,invalid-name,unused-variable\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j in T.grid(128, 128):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = 0.0\n        for k in range(0, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_relu(a: T.handle, b: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (1024, 1024))\n    B = T.match_buffer(b, (1024, 1024))\n    C = T.alloc_buffer((1024, 1024))\n    D = T.match_buffer(d, (1024, 1024))\n    for i, j, k in T.grid(1024, 1024, 1024):\n        with T.block(\"matmul\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n    for i, j in T.grid(1024, 1024):\n        with T.block(\"relu\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n@T.prim_func\ndef matmul_relu_ann1(a: T.handle, b: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (1024, 1024))\n    B = T.match_buffer(b, (1024, 1024))\n    C = T.alloc_buffer((1024, 1024))\n    D = T.match_buffer(d, (1024, 1024))\n    for i in T.serial(0, 1024, annotations={\"test1\": \"aaa\", \"test4\": {\"arr\": [0, 0], \"key\": 3}}):\n        for j in T.serial(0, 1024, annotations={\"test2\": 612, \"test3\": [\"aa\", 1]}):\n            for k in T.serial(0, 1024):\n                with T.block(\"matmul\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    with T.init():\n                        C[vi, vj] = 0.0\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n    for i, j in T.grid(1024, 1024):\n        with T.block(\"relu\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n@T.prim_func\ndef matmul_relu_ann2(a: T.handle, b: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (1024, 1024))\n    B = T.match_buffer(b, (1024, 1024))\n    C = T.alloc_buffer((1024, 1024))\n    D = T.match_buffer(d, (1024, 1024))\n    for i, j, k in T.grid(1024, 1024, 1024):\n        with T.block(\"matmul\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            T.block_attr({\"test1\": \"aaa\", \"test4\": {\"arr\": [0, 0], \"key\": 3}})\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n    for i, j in T.grid(1024, 1024):\n        with T.block(\"relu\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            T.block_attr({\"test2\": 0.22, \"test3\": [\"aa\", 1]})\n            D[vi, vj] = T.max(C[vi, vj], 0.0)\n\n\n@tvm.script.ir_module\nclass ModuleWithMultipleFuncs:\n    @T.prim_func\n    def vector_add(\n        A: T.Buffer[128, \"float32\"],\n        B: T.Buffer[128, \"float32\"],\n    ) -> None:\n        for i in range(128):\n            with T.block(\"init\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n    @T.prim_func\n    def vector_add_2(\n        A: T.Buffer[128, \"float32\"],\n        B: T.Buffer[128, \"float32\"],\n    ) -> None:\n        for i in range(128):\n            with T.block(\"init\"):\n                vi = T.axis.remap(\"S\", [i])\n                B[vi] = A[vi]\n\n\n@T.prim_func\ndef tuple_reduction(data: T.Buffer[(4, 32), \"float32\"], T_add: T.Buffer[(4,), \"float32\"]) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    # body\n    with T.block(\"root\"):\n        T.reads()\n        T.writes()\n        data_red_temp_v0 = T.alloc_buffer([4], dtype=\"float32\")\n        data_red_temp_v1 = T.alloc_buffer([4], dtype=\"float32\")\n        for i0, i1 in T.grid(4, 32):\n            with T.block(\"data_red_temp\"):\n                ax0, k1 = T.axis.remap(\"SR\", [i0, i1])\n                T.reads(data[ax0, k1])\n                T.writes(data_red_temp_v0[ax0], data_red_temp_v1[ax0])\n                with T.init():\n                    data_red_temp_v0[ax0] = T.float32(0)\n                    data_red_temp_v1[ax0] = T.float32(0)\n                v_data_red_temp_v0: T.float32 = data_red_temp_v0[ax0] + data[ax0, k1]\n                v_data_red_temp_v1: T.float32 = (\n                    data_red_temp_v1[ax0] + data[ax0, k1] * data[ax0, k1]\n                )\n                data_red_temp_v0[ax0] = v_data_red_temp_v0\n                data_red_temp_v1[ax0] = v_data_red_temp_v1\n        for i0 in range(4):\n            with T.block(\"T_add\"):\n                ax0 = T.axis.remap(\"S\", [i0])\n                T.reads(data_red_temp_v0[ax0], data_red_temp_v1[ax0])\n                T.writes(T_add[ax0])\n                T_add[ax0] = data_red_temp_v0[ax0] + data_red_temp_v1[ax0]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable\n\nuse_block_name = tvm.testing.parameter(by_dict={\"block_obj\": False, \"block_name\": True})\n\n\ndef test_tir_schedule_creation():\n    # Tests:\n    # - Schedule.__init__ for PrimFunc and IRModule\n    # - Schedule.mod\n    # - Schedule.state\n    sch_1 = tir.Schedule(matmul, debug_mask=\"all\")\n    sch_2 = tir.Schedule(IRModule({\"main\": matmul}), debug_mask=\"all\")\n    assert sch_1.mod[\"main\"].same_as(sch_2.mod[\"main\"])\n    assert sch_1.state.mod[\"main\"].same_as(sch_2.state.mod[\"main\"])\n\n\ndef test_tir_schedule_get_block():\n    # Tests:\n    # - Schedule.get_block\n    # - Schedule.get_sref\n    # - Schedule.get\n    sch = tir.Schedule(matmul, debug_mask=\"all\")\n    block_rv = sch.get_block(name=\"update\")\n    block_sref = sch.get_sref(block_rv)\n    block = sch.get(block_rv)\n    assert block.name_hint == \"update\"\n    assert block_sref.stmt.same_as(block)\n    assert sch.state.get_sref(block).same_as(block_sref)\n    assert block.same_as(matmul.body.block.body.body.body[1].body.block)\n\n\ndef test_tir_schedule_work_on():\n    sch = tir.Schedule(ModuleWithMultipleFuncs, debug_mask=\"all\")\n    with pytest.raises(ValueError, match=\"does not know which function to be working on\"):\n        sch.get_block(name=\"init\")\n    sch.work_on(func_name=\"vector_add\")\n    sch.get_block(name=\"init\")\n\n\ndef test_tir_schedule_get_loops(use_block_name):\n    # Tests:\n    # - Schedule.get_loops\n    # - Schedule.get\n    sch = tir.Schedule(matmul, debug_mask=\"all\")\n    block = \"update\" if use_block_name else sch.get_block(name=\"update\")\n    i, j, k = sch.get_loops(block)\n    assert sch.get(i).loop_var.name == \"i\"\n    assert sch.get(j).loop_var.name == \"j\"\n    assert sch.get(k).loop_var.name == \"k\"\n\n\ndef test_tir_schedule_copy_1(use_block_name):\n    # Tests:\n    # - Schedule.copy\n    sch_1 = tir.Schedule(matmul, debug_mask=\"all\")\n    block_rv = sch_1.get_block(name=\"update\")\n    i, j, k = sch_1.get_loops(block=\"update\" if use_block_name else block_rv)\n    assert sch_1.get(i).loop_var.name == \"i\"\n    assert sch_1.get(j).loop_var.name == \"j\"\n    assert sch_1.get(k).loop_var.name == \"k\"\n\n    sch_2 = sch_1.copy()\n    assert sch_2.get(block_rv).name_hint == \"update\"\n    assert sch_2.get(i).loop_var.name == \"i\"\n    assert sch_2.get(j).loop_var.name == \"j\"\n    assert sch_2.get(k).loop_var.name == \"k\"\n\n\ndef test_tir_schedule_copy_2():\n    sch = tir.Schedule(mod=matmul, debug_mask=\"all\")\n    i, j, k = sch.get_loops(sch.get_block(\"update\"))\n    sch_copy = sch.copy()\n    assert not sch.get_sref(i).same_as(sch_copy.get_sref(i))\n    assert not sch.get_sref(j).same_as(sch_copy.get_sref(j))\n    assert not sch.get_sref(k).same_as(sch_copy.get_sref(k))\n    assert sch.get_sref(i).stmt.same_as(sch_copy.get_sref(i).stmt)\n    assert sch.get_sref(j).stmt.same_as(sch_copy.get_sref(j).stmt)\n    assert sch.get_sref(k).stmt.same_as(sch_copy.get_sref(k).stmt)\n    i_0, i_1 = sch.split(i, factors=[None, 64])\n    j_0, j_1 = sch_copy.split(j, factors=[None, 32])\n\n    assert sch.get_sref(i_0).stmt.extent == 2\n    assert sch.get_sref(i_1).stmt.extent == 64\n    with pytest.raises(IndexError):\n        sch_copy.get_sref(i_0)\n    with pytest.raises(IndexError):\n        sch_copy.get_sref(i_1)\n\n    with pytest.raises(IndexError):\n        sch.get_sref(j_0)\n    with pytest.raises(IndexError):\n        sch.get_sref(j_1)\n    assert sch_copy.get_sref(j_0).stmt.extent == 4\n    assert sch_copy.get_sref(j_1).stmt.extent == 32\n    verify_trace_roundtrip(sch, mod=matmul)\n    verify_trace_roundtrip(sch_copy, mod=matmul)\n\n\ndef test_tir_schedule_remove_rv():\n    # Tests:\n    # - Schedule.remove_rv\n    sch = tir.Schedule(matmul, debug_mask=\"all\")\n    block_rv = sch.get_block(name=\"update\")\n    assert sch.get(block_rv).name_hint == \"update\"\n    sch.remove_rv(block_rv)\n    with pytest.raises(IndexError):\n        sch.get(block_rv)\n\n\ndef test_get_child_blocks():\n    s = tir.Schedule(matmul, debug_mask=\"all\")\n    init = s.get_block(\"init\")\n    update = s.get_block(\"update\")\n    # loop\n    blocks = s.get_child_blocks(s.get_loops(init)[0])\n    assert len(blocks) == 2\n    assert s.get(init) == s.get(blocks[0])\n    assert s.get(update) == s.get(blocks[1])\n    # block\n    root = s.get_block(\"root\")\n    blocks = s.get_child_blocks(root)\n    assert len(blocks) == 2\n    assert s.get(init) == s.get(blocks[0])\n    assert s.get(update) == s.get(blocks[1])\n\n\ndef test_get_producers(use_block_name):\n    sch = tir.Schedule(mod=matmul_relu, debug_mask=\"all\")\n    block = \"relu\" if use_block_name else sch.get_block(\"relu\")\n    (producer,) = sch.get_producers(block)\n    assert tvm.ir.structural_equal(\n        sch.get_sref(producer).stmt,\n        sch.get_sref(sch.get_block(\"matmul\")).stmt,\n    )\n    verify_trace_roundtrip(sch, mod=matmul_relu)\n\n\ndef test_get_producers_multiple_buffer_depdencies(use_block_name):\n    sch = tir.Schedule(mod=tuple_reduction, debug_mask=\"all\")\n    block = \"T_add\" if use_block_name else sch.get_block(\"T_add\")\n    (producer,) = sch.get_producers(block)\n    assert tvm.ir.structural_equal(\n        sch.get_sref(producer).stmt,\n        sch.get_sref(sch.get_block(\"data_red_temp\")).stmt,\n    )\n\n\ndef test_get_consumers(use_block_name):\n    sch = tir.Schedule(mod=matmul_relu, debug_mask=\"all\")\n    block = \"matmul\" if use_block_name else sch.get_block(\"matmul\")\n    (consumer,) = sch.get_consumers(block)\n    assert tvm.ir.structural_equal(\n        sch.get_sref(consumer).stmt,\n        sch.get_sref(sch.get_block(\"relu\")).stmt,\n    )\n    verify_trace_roundtrip(sch, mod=matmul_relu)\n\n\ndef test_get_consumers_multiple_buffer_depdencies(use_block_name):\n    sch = tir.Schedule(mod=tuple_reduction, debug_mask=\"all\")\n    block = \"data_red_temp\" if use_block_name else sch.get_block(\"data_red_temp\")\n    (consumer,) = sch.get_consumers(block)\n    assert tvm.ir.structural_equal(\n        sch.get_sref(consumer).stmt,\n        sch.get_sref(sch.get_block(\"T_add\")).stmt,\n    )\n\n\ndef test_annotate_unannotate_loop():\n    sch = tir.Schedule(mod=matmul_relu, debug_mask=\"all\")\n    matmul = sch.get_block(\"matmul\")\n    relu = sch.get_block(\"relu\")\n    sch.annotate(sch.get_loops(matmul)[0], \"test1\", \"aaa\")\n    sch.annotate(sch.get_loops(matmul)[1], \"test2\", 612)\n    sch.annotate(sch.get_loops(matmul)[1], \"test3\", [\"aa\", 1])\n    sch.annotate(sch.get_loops(matmul)[0], \"test4\", {\"arr\": [0, 0], \"key\": 3})\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], matmul_relu_ann1)\n    verify_trace_roundtrip(sch=sch, mod=matmul_relu)\n    sch.unannotate(sch.get_loops(matmul)[0], \"test1\")\n    sch.unannotate(sch.get_loops(matmul)[1], \"test2\")\n    sch.unannotate(sch.get_loops(matmul)[1], \"test3\")\n    sch.unannotate(sch.get_loops(matmul)[0], \"test4\")\n    verify_trace_roundtrip(sch=sch, mod=matmul_relu)\n\n\ndef test_annotate_unannotate_block():\n    sch = tir.Schedule(mod=matmul_relu, debug_mask=\"all\")\n    matmul = sch.get_block(\"matmul\")\n    relu = sch.get_block(\"relu\")\n    sch.annotate(matmul, \"test1\", \"aaa\")\n    sch.annotate(relu, \"test2\", 0.22)\n    sch.annotate(relu, \"test3\", [\"aa\", 1])\n    sch.annotate(matmul, \"test4\", {\"arr\": [0, 0], \"key\": 3})\n    tvm.ir.assert_structural_equal(sch.mod[\"main\"], matmul_relu_ann2)\n    verify_trace_roundtrip(sch=sch, mod=matmul_relu)\n    sch.unannotate(matmul, \"test1\")\n    sch.unannotate(relu, \"test2\")\n    sch.unannotate(relu, \"test3\")\n    sch.unannotate(matmul, \"test4\")\n    verify_trace_roundtrip(sch=sch, mod=matmul_relu)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_specialize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring, missing-module-docstring\n\nimport tvm\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle, n: T.int32) -> None:\n    m = T.var(\"int32\")\n    A = T.match_buffer(a, [m, n])\n    B = T.match_buffer(b, [m, n])\n    C = T.match_buffer(c, [m, m])\n\n    for i, j, k in T.grid(m, m, n):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_128(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_m_128(a: T.handle, b: T.handle, c: T.handle) -> None:\n    m = T.var(\"int32\")\n    A = T.match_buffer(a, [m, 128])\n    B = T.match_buffer(b, [m, 128])\n    C = T.match_buffer(c, [m, m])\n\n    for i, j, k in T.grid(m, m, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_m_8x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    x = T.var(\"int32\")\n    m = T.var(\"int32\")\n    A = T.match_buffer(a, [m, x * 8])\n    B = T.match_buffer(b, [m, x * 8])\n    C = T.match_buffer(c, [m, m])\n\n    for i, j, k in T.grid(m, m, x * 8):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef element_wise(a: T.handle, c: T.handle) -> None:\n    m = T.var(\"int32\")\n    n = T.var(\"int32\")\n    A = T.match_buffer(a, (m, n), \"float32\")\n    C = T.match_buffer(c, (m, n), \"float32\")\n\n    B = T.alloc_buffer((m, n), \"float32\")\n\n    for i, j in T.grid(m, n):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n    for i, j in T.grid(m, n):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_128_64(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (128, 64), \"float32\")\n    C = T.match_buffer(c, (128, 64), \"float32\")\n    B = T.alloc_buffer((128, 64), \"float32\")\n\n    for i, j in T.grid(128, 64):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n    for i, j in T.grid(128, 64):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef element_wise_128_n(a: T.handle, c: T.handle) -> None:\n    n = T.var(\"int32\")\n    A = T.match_buffer(a, (128, n), \"float32\")\n    C = T.match_buffer(c, (128, n), \"float32\")\n    B = T.alloc_buffer((128, n), \"float32\")\n\n    for i, j in T.grid(128, n):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n\n    for i, j in T.grid(128, n):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef mem_copy(a: T.handle, b: T.handle, m: T.int32, n: T.int32, p: T.int32, q: T.int32) -> None:\n    A = T.match_buffer(a, (m, n), \"float32\", strides=[p, 1], elem_offset=q)\n    B = T.match_buffer(b, (m, n), \"float32\", strides=[p, 1], elem_offset=q)\n\n    for i, j in T.grid(m, n):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj]\n\n\n@T.prim_func\ndef mem_copy_16_16_8_4(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\", strides=[8, 1], elem_offset=4)\n    B = T.match_buffer(b, (16, 16), \"float32\", strides=[8, 1], elem_offset=4)\n\n    for i, j in T.grid(16, 16):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj]\n\n\n@T.prim_func\ndef mem_copy_m_n_p_n(a: T.handle, b: T.handle, m: T.int32, n: T.int32, p: T.int32) -> None:\n    A = T.match_buffer(a, (m, n), \"float32\", strides=[p, 1], elem_offset=n)\n    B = T.match_buffer(b, (m, n), \"float32\", strides=[p, 1], elem_offset=n)\n\n    for i, j in T.grid(m, n):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj]\n\n\n@T.prim_func\ndef param_in_arith_exprs(a: T.handle, b: T.handle) -> None:\n    n = T.var(\"int32\")\n    A = T.match_buffer(a, [n // 8, 8], \"int32\")\n    B = T.match_buffer(b, [n], \"int32\")\n    for i in range(n - 1):\n        with T.block():\n            vi = T.axis.S(n - 1, i)\n            B[vi] = A[vi // 8, vi % 8] + (n + 1) * 42\n\n\n@T.prim_func\ndef param_in_arith_exprs_n_16(a: T.handle, b: T.handle) -> None:\n    n = T.var(\"int32\")\n    A = T.match_buffer(a, [2, 8], \"int32\")\n    B = T.match_buffer(b, [16], \"int32\")\n    for i in range(15):\n        with T.block():\n            vi = T.axis.S(15, i)\n            B[vi] = A[vi // 8, vi % 8] + 714\n\n\ndef test_specialize_nothing():\n    func = matmul.specialize({})\n    assert func.same_as(matmul)  # Pointer the same\n\n\ndef test_specialize_matmul():\n    a, _, _, n = matmul.params\n    # fully specialized\n    func = matmul.specialize({a: tvm.tir.decl_buffer((128, 128))})\n    tvm.ir.assert_structural_equal(func, matmul_128)\n    # partially specialized\n    func = matmul.specialize({n: 128})\n    tvm.ir.assert_structural_equal(func, matmul_m_128)\n    # symbolic specialized\n    func = matmul.specialize({n: tvm.tir.Var(\"x\", \"int32\") * 8})\n    tvm.ir.assert_structural_equal(func, matmul_m_8x)\n\n\ndef test_specialize_elemwise():\n    a, c = element_wise.params\n    C = element_wise.buffer_map[c]\n    # fully specialized\n    func = element_wise.specialize({a: tvm.tir.decl_buffer((128, 64))})\n    tvm.ir.assert_structural_equal(func, element_wise_128_64)\n    # partially specialized\n    func = element_wise.specialize({c: tvm.tir.decl_buffer((128, C.shape[1]))})\n    tvm.ir.assert_structural_equal(func, element_wise_128_n)\n\n\ndef test_specialize_mem_copy():\n    a, _, m, n, p, q = mem_copy.params\n    # fully specialized\n    func = mem_copy.specialize({a: tvm.tir.decl_buffer((16, 16), strides=[8, 1], elem_offset=4)})\n    tvm.ir.assert_structural_equal(func, mem_copy_16_16_8_4)\n    func = mem_copy.specialize({n: 16, m: 16, p: 8, q: 4})\n    tvm.ir.assert_structural_equal(func, mem_copy_16_16_8_4)\n    # partially specialized\n    func = mem_copy.specialize({q: n})\n    tvm.ir.assert_structural_equal(func, mem_copy_m_n_p_n)\n\n\ndef test_specialize_recursive_load():\n    # TODO(Siyuan): add recursive Load testcase, e.g. A[C[i]]\n    pass\n\n\ndef test_specialize_with_const_folding():\n    b = param_in_arith_exprs.params[1]\n    func = param_in_arith_exprs.specialize({b: tvm.tir.decl_buffer([16])})\n    tvm.ir.assert_structural_equal(func, param_in_arith_exprs_n_16)\n\n\nif __name__ == \"__main__\":\n    test_specialize_nothing()\n    test_specialize_matmul()\n    test_specialize_elemwise()\n    test_specialize_mem_copy()\n    test_specialize_recursive_load()\n    test_specialize_with_const_folding()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_stmt_functor_ir_transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_ir_transform():\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            x = tvm.tir.call_extern(\"int32\", \"TestA\", i * 3 + j * 1)\n            ib.emit(tvm.tir.call_extern(\"int32\", \"TestB\", x))\n            ib.emit(tvm.tir.call_extern(\"int32\", \"TestC\", x))\n    body = ib.get()\n    builtin_call_extern = tvm.ir.Op.get(\"tir.call_extern\")\n\n    def preorder(op):\n        if op.op.same_as(builtin_call_extern) and op.args[0].value == \"TestC\":\n            return tvm.tir.const(0, \"int32\")\n        return None\n\n    def postorder(op):\n        assert isinstance(op, tvm.tir.Call)\n        if op.op.same_as(builtin_call_extern) and op.args[0].value == \"TestA\":\n            return tvm.tir.call_extern(\"int32\", \"TestB\", op.args[1] + 1)\n        return op\n\n    body = tvm.tir.stmt_functor.ir_transform(body, preorder, postorder, [\"tir.Call\"])\n    stmt_list = tvm.tir.stmt_list(body.body.body)\n    assert stmt_list[0].value.args[1].args[0].value == \"TestB\"\n    assert stmt_list[1].value.value == 0\n\n\nif __name__ == \"__main__\":\n    test_ir_transform()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_structural_equal_hash.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport numpy as np\nimport pytest\nfrom tvm import te\nfrom tvm.runtime import ObjectPath\n\n\ndef consistent_equal(x, y, map_free_vars=False):\n    struct_equal0 = tvm.ir.structural_equal(x, y, map_free_vars)\n    struct_equal1 = tvm.ir.structural_equal(y, x, map_free_vars)\n\n    xhash = tvm.ir.structural_hash(x, map_free_vars)\n    yhash = tvm.ir.structural_hash(y, map_free_vars)\n\n    if struct_equal0 != struct_equal1:\n        raise ValueError(\n            \"Non-commutative {} vs {}, sequal0={}, sequal1={}\".format(\n                x, y, struct_equal0, struct_equal1\n            )\n        )\n\n    # NOTE: hash colision can happen but should be rare.\n    # we can confirm that hash colison doesn't happen for our testcases\n    if struct_equal0 != (xhash == yhash):\n        raise ValueError(\n            \"Inconsistent {} vs {}, sequal={}, xhash={}, yhash={}\".format(\n                x, y, struct_equal0, xhash, yhash\n            )\n        )\n    return struct_equal0\n\n\ndef get_sequal_mismatch(x, y, map_free_vars=False):\n    mismatch_0 = tvm.ir.base.get_first_structural_mismatch(x, y, map_free_vars)\n    mismatch_1 = tvm.ir.base.get_first_structural_mismatch(y, x, map_free_vars)\n\n    if mismatch_0 is None and mismatch_1 is None:\n        return None\n\n    if (\n        mismatch_0 is None\n        or mismatch_1 is None\n        or mismatch_0[0] != mismatch_1[1]\n        or mismatch_0[1] != mismatch_1[0]\n    ):\n        raise ValueError(\n            \"Non-commutative {} vs {}, mismatch_0={}, mismatch_1={}\".format(\n                x, y, mismatch_0, mismatch_1\n            )\n        )\n\n    return mismatch_0\n\n\ndef test_exprs():\n    # save load json\n    x = tvm.tir.const(1, \"int32\")\n    y = tvm.tir.const(10, \"int32\")\n    vx = te.var(\"x\")\n    vy = te.var(\"y\")\n    vz = te.var(\"z\")\n    zx = vx + vx\n    zy = vy + vy\n\n    assert consistent_equal(zx * zx, (vx + vx) * (vx + vx), map_free_vars=False)\n\n    # test assert trigger.\n    with pytest.raises(ValueError):\n        tvm.ir.assert_structural_equal(x, y)\n\n    assert not consistent_equal(vx, vy)\n    assert consistent_equal(vx, vy, map_free_vars=True)\n    # corner case lhs:vx == rhs:vy, but cannot map it iteslf\n    assert not consistent_equal(vx + vx, vy + vx, map_free_vars=True)\n    # corner case lhs:vx == rhs:vy, lhs:vy == rhs:vx\n    assert consistent_equal(vx + vy, vy + vx, map_free_vars=True)\n    # corner case2: rolling remap.\n    assert consistent_equal(vx + vy + vz, vy + vz + vx, map_free_vars=True)\n    assert not consistent_equal(vx + 1, vy + 1, map_free_vars=False)\n    # Defintition remap\n    assert consistent_equal(tvm.tir.Let(vx, 1, vx - 1), tvm.tir.Let(vy, 1, vy - 1))\n    # Default same address free var remap\n    assert consistent_equal(tvm.tir.Let(vx, 1, vx // vz), tvm.tir.Let(vy, 1, vy // vz))\n\n    assert consistent_equal(zx * zx, zx * zx)\n    assert consistent_equal(zx * zx, zy * zy, map_free_vars=True)\n    assert not consistent_equal(zx * zx, zy * zy, map_free_vars=False)\n\n\ndef test_prim_func():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    # counter example of same equality\n    func0 = tvm.tir.PrimFunc([x, y], tvm.tir.Evaluate(x + y))\n    func1 = tvm.tir.PrimFunc([x, y], tvm.tir.Evaluate(y + x))\n    assert not consistent_equal(func0, func1)\n\n    # new cases\n    b = tvm.tir.decl_buffer((x,), \"float32\")\n    stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1))\n    func0 = tvm.tir.PrimFunc([x, y, b], stmt)\n    # easiest way to deep copy is via save/load\n    func1 = tvm.ir.load_json(tvm.ir.save_json(func0))\n    tvm.ir.assert_structural_equal(func0, func1)\n\n    data0 = tvm.nd.array([1, 2, 3])\n    data1 = tvm.nd.array([1, 2, 3])\n    # attributes and ndarrays\n    func0 = func0.with_attr(\"data\", data0)\n    func1 = func1.with_attr(\"data\", data1)\n    # IRModules\n    mod0 = tvm.IRModule.from_expr(func0)\n    mod1 = tvm.IRModule.from_expr(func1)\n    tvm.ir.assert_structural_equal(mod0, mod1)\n\n\ndef test_prim_func_param_count_mismatch():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    # counter example of same equality\n    func0 = tvm.tir.PrimFunc([x, y], tvm.tir.Evaluate(x))\n    func1 = tvm.tir.PrimFunc([x, y, z], tvm.tir.Evaluate(x))\n    lhs_path, rhs_path = get_sequal_mismatch(func0, func1)\n    expected_lhs_path = ObjectPath.root().attr(\"params\").missing_array_element(2)\n    expected_rhs_path = ObjectPath.root().attr(\"params\").array_index(2)\n    assert lhs_path == expected_lhs_path\n    assert rhs_path == expected_rhs_path\n\n\ndef test_prim_func_param_dtype_mismatch():\n    x = te.var(\"x\")\n    y_0 = te.var(\"y\", dtype=\"int32\")\n    y_1 = te.var(\"z\", dtype=\"float32\")\n    # counter example of same equality\n    func0 = tvm.tir.PrimFunc([x, y_0], tvm.tir.Evaluate(x))\n    func1 = tvm.tir.PrimFunc([x, y_1], tvm.tir.Evaluate(x))\n    lhs_path, rhs_path = get_sequal_mismatch(func0, func1)\n    expected_path = ObjectPath.root().attr(\"params\").array_index(1).attr(\"dtype\")\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_prim_func_body_mismatch():\n    x_0 = te.var(\"x\")\n    y_0 = te.var(\"y\")\n    x_1 = te.var(\"x\")\n    y_1 = te.var(\"y\")\n    # counter example of same equality\n    func0 = tvm.tir.PrimFunc([x_0, y_0], tvm.tir.Evaluate(x_0 + x_0))\n    func1 = tvm.tir.PrimFunc([x_1, y_1], tvm.tir.Evaluate(x_1 + y_1))\n    lhs_path, rhs_path = get_sequal_mismatch(func0, func1)\n    expected_path = ObjectPath.root().attr(\"body\").attr(\"value\").attr(\"b\")\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_array():\n    x = np.arange(10)\n    nx = tvm.nd.array(x)\n    ny = tvm.nd.array(x)\n    nz = tvm.nd.array(x.reshape(2, 5))\n    assert consistent_equal(nx, ny)\n    assert not consistent_equal(nx, nz)\n\n\ndef test_env_func():\n    @tvm.register_func(\"test.sequal.env_func\")\n    def test(x):\n        return x + 1\n\n    x = tvm.ir.EnvFunc.get(\"test.sequal.env_func\")\n    y = tvm.ir.EnvFunc.get(\"test.sequal.env_func\")\n    assert consistent_equal(y, x)\n\n\ndef test_attrs():\n    x = tvm.ir.make_node(\"attrs.TestAttrs\", axis=1, name=\"xx\")\n    y = tvm.ir.make_node(\"attrs.TestAttrs\", axis=1, name=\"xx\")\n    z = tvm.ir.make_node(\"attrs.TestAttrs\", axis=2, name=\"xx\")\n    tvm.ir.assert_structural_equal(y, x)\n    assert not consistent_equal(y, z)\n\n    x = tvm.runtime.convert({\"x\": [1, 2, 3], \"y\": 2})\n    y = tvm.runtime.convert({\"y\": 2, \"x\": [1, 2, 3]})\n    z = tvm.runtime.convert({\"y\": 2, \"x\": [1, 2, 3, 4]})\n    assert consistent_equal(y, x)\n    assert not consistent_equal(y, z)\n\n\ndef test_stmt():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    n = 128\n    A = te.placeholder((n, n), name=\"A\")\n    B = te.placeholder((n, n), name=\"B\")\n    ii = te.var(\"i\")\n    jj = te.var(\"j\")\n\n    Ab = tvm.tir.decl_buffer((n,), name=\"A\")\n    n = te.var(\"n\")\n\n    def func2():\n        ib = tvm.tir.ir_builder.create()\n        A = ib.buffer_ptr(Ab)\n        with ib.for_range(0, n, name=\"i\") as i:\n            A[i] = A[i] + 1\n            with ib.for_range(0, 10, name=\"j\") as j:\n                A[j] = A[j] + 2\n                A[j] = A[j] + 2\n        return ib.get()\n\n    assert consistent_equal(func2(), func2())\n\n\ndef test_buffer_storage_scope():\n    x = te.var(\"x\", dtype=\"handle\")\n\n    buffer_local_0 = tvm.tir.decl_buffer((10, 10), \"float32\", scope=\"local\")\n    buffer_local_1 = tvm.tir.decl_buffer((10, 10), \"float32\", scope=\"local\")\n    buffer_global = tvm.tir.decl_buffer((10, 10), \"float32\")\n    buffer_empty = tvm.tir.decl_buffer((10, 10), \"float32\", scope=\"\")\n\n    func0 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_local_0})\n    func1 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_local_1})\n    func2 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_global})\n    func3 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_empty})\n\n    assert consistent_equal(func0, func1)\n    assert consistent_equal(func2, func3)\n    assert not consistent_equal(func0, func2)\n\n\ndef test_buffer_map_mismatch():\n    x = te.var(\"x\")\n    buffer_0 = tvm.tir.decl_buffer((10, 10))\n    buffer_0_clone = tvm.tir.decl_buffer((10, 10))\n    buffer_1 = tvm.tir.decl_buffer((10, 20))\n\n    func_0 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_0})\n    func_0_clone = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_0_clone})\n    func_1 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_1})\n\n    lhs_path, rhs_path = get_sequal_mismatch(func_0, func_1)\n    expected_path = (\n        ObjectPath.root().attr(\"buffer_map\").map_value(x).attr(\"shape\").array_index(1).attr(\"value\")\n    )\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n    assert get_sequal_mismatch(func_0, func_0_clone) is None\n\n\ndef test_buffer_map_length_mismatch():\n    x = te.var(\"x\")\n    y = te.var(\"x\")\n\n    buffer_0 = tvm.tir.decl_buffer((10, 10))\n    buffer_1 = tvm.tir.decl_buffer((10, 20))\n\n    func_0 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_0})\n    func_1 = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x), buffer_map={x: buffer_0, y: buffer_1})\n\n    lhs_path, rhs_path = get_sequal_mismatch(func_0, func_1)\n\n    expected_lhs_path = ObjectPath.root().attr(\"buffer_map\").missing_map_entry()\n    assert lhs_path == expected_lhs_path\n    expected_rhs_path = ObjectPath.root().attr(\"buffer_map\").map_value(y)\n    assert rhs_path == expected_rhs_path\n\n\ndef test_buffer_load_store():\n    b = tvm.tir.decl_buffer((10, 10), \"float32\")\n    x = tvm.tir.BufferLoad(b, [0, 1])\n    y = tvm.tir.BufferLoad(b, [0, 1])\n    z = tvm.tir.BufferLoad(b, [1, 2])\n    assert consistent_equal(y, x)\n    assert not consistent_equal(y, z)\n\n    i = tvm.tir.Var(\"x\", \"int32\")\n    sx = tvm.tir.BufferStore(b, 0.1, [0, i])\n    sy = tvm.tir.BufferStore(b, 0.1, [0, i])\n    sz = tvm.tir.BufferStore(b, 0.1, [1, i])\n    assert consistent_equal(sy, sx)\n    assert not consistent_equal(sy, sz)\n\n\ndef test_while():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    y = tvm.tir.Var(\"y\", \"int32\")\n    wx = tvm.tir.While(x > 0, tvm.tir.Evaluate(x))\n    wy = tvm.tir.While(y > 0, tvm.tir.Evaluate(y))\n    assert not consistent_equal(wx, wy)\n    assert consistent_equal(wx, wy, map_free_vars=True)\n\n\ndef test_while_condition_mismatch():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    w_0 = tvm.tir.While(x > 0, tvm.tir.Evaluate(x))\n    w_1 = tvm.tir.While(x < 0, tvm.tir.Evaluate(x))\n    lhs_path, rhs_path = get_sequal_mismatch(w_0, w_1)\n    expected_path = ObjectPath.root().attr(\"condition\")\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_while_body_mismatch():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    w_0 = tvm.tir.While(x > 0, tvm.tir.Evaluate(x))\n    w_1 = tvm.tir.While(x > 0, tvm.tir.Evaluate(x + 1))\n    lhs_path, rhs_path = get_sequal_mismatch(w_0, w_1)\n    expected_path = ObjectPath.root().attr(\"body\").attr(\"value\")\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_seq_mismatch():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    seq_0 = tvm.tir.SeqStmt(\n        [\n            tvm.tir.Evaluate(x),\n            tvm.tir.Evaluate(x + 1),\n            tvm.tir.Evaluate(x + 2),\n            tvm.tir.Evaluate(x + 3),\n        ]\n    )\n    seq_1 = tvm.tir.SeqStmt(\n        [\n            tvm.tir.Evaluate(x),\n            tvm.tir.Evaluate(x + 1),\n            tvm.tir.Evaluate(x + 99),\n            tvm.tir.Evaluate(x + 3),\n        ]\n    )\n    lhs_path, rhs_path = get_sequal_mismatch(seq_0, seq_1)\n    expected_path = (\n        ObjectPath.root().attr(\"seq\").array_index(2).attr(\"value\").attr(\"b\").attr(\"value\")\n    )\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_seq_mismatch_different_lengths():\n    # Make sure we report a difference inside the array first, rather than the difference in length\n    x = tvm.tir.Var(\"x\", \"int32\")\n    seq_0 = tvm.tir.SeqStmt(\n        [\n            tvm.tir.Evaluate(x),\n            tvm.tir.Evaluate(x + 1),\n            tvm.tir.Evaluate(x + 2),\n            tvm.tir.Evaluate(x + 3),\n        ]\n    )\n    seq_1 = tvm.tir.SeqStmt([tvm.tir.Evaluate(x), tvm.tir.Evaluate(x + 1), tvm.tir.Evaluate(x + 3)])\n    lhs_path, rhs_path = get_sequal_mismatch(seq_0, seq_1)\n    expected_path = (\n        ObjectPath.root().attr(\"seq\").array_index(2).attr(\"value\").attr(\"b\").attr(\"value\")\n    )\n    assert lhs_path == expected_path\n    assert rhs_path == expected_path\n\n\ndef test_seq_length_mismatch():\n    x = tvm.tir.Var(\"x\", \"int32\")\n    seq_0 = tvm.tir.SeqStmt(\n        [\n            tvm.tir.Evaluate(x),\n            tvm.tir.Evaluate(x + 1),\n            tvm.tir.Evaluate(x + 2),\n            tvm.tir.Evaluate(x + 3),\n        ]\n    )\n    seq_1 = tvm.tir.SeqStmt([tvm.tir.Evaluate(x), tvm.tir.Evaluate(x + 1), tvm.tir.Evaluate(x + 2)])\n    lhs_path, rhs_path = get_sequal_mismatch(seq_0, seq_1)\n    expected_lhs_path = ObjectPath.root().attr(\"seq\").array_index(3)\n    expected_rhs_path = ObjectPath.root().attr(\"seq\").missing_array_element(3)\n    assert lhs_path == expected_lhs_path\n    assert rhs_path == expected_rhs_path\n\n\nif __name__ == \"__main__\":\n    test_exprs()\n    test_prim_func()\n    test_attrs()\n    test_array()\n    test_env_func()\n    test_stmt()\n    test_buffer_storage_scope()\n    test_buffer_load_store()\n    test_while()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_te_extern_primfunc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport pytest\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import tir, te, TVMError\nfrom tvm.script import tir as T\nfrom tvm.arith import _ffi_api as _ffi_arith_api\nfrom tvm.tir.schedule import _ffi_api as _ffi_schedule_api\n\n\n# TODO(csullivan): Additional tests cases needed:\n# - PrimFunc with 1 arg, inplace update\n# - PrimFunc with buffer that uses custom storage_scope\n\n\n@T.prim_func\ndef func_1(A: T.Buffer[(16,), \"float32\"], C: T.Buffer[(1,), \"float32\"]):\n    for i in T.serial(\n        0,\n        16,\n    ):\n        with T.block():\n            B = T.alloc_buffer((1,), dtype=\"float32\")\n            with T.block():\n                B[0] = A[i] * T.float32(2)\n            with T.block():\n                C[0] = C[0] + A[i] + B[0] + T.float32(1)\n                A[i] = B[0] + T.float32(1)\n\n\ndef verify_func_1(module):\n    a_np = np.random.randint(low=-128, high=127, size=(16,)).astype(np.float32)\n    c_np = np.zeros((1,), dtype=np.float32)\n    a = tvm.nd.array(a_np, device=tvm.cpu(0))\n    c = tvm.nd.array(c_np, device=tvm.cpu(0))\n\n    module(a, c)\n    tvm.testing.assert_allclose(c_np + np.sum(3 * a_np + 1), c.numpy(), rtol=1e-4)\n    # also test in place update\n    tvm.testing.assert_allclose(a_np * 2 + 1, a.numpy(), rtol=1e-4)\n\n\n@T.prim_func\ndef func_2(\n    C: T.Buffer[(1,), \"float32\"], A: T.Buffer[(16,), \"float32\"], D: T.Buffer[(2,), \"float32\"]\n):\n    for i in T.serial(\n        0,\n        16,\n    ):\n        with T.block():\n            B = T.alloc_buffer((1,), dtype=\"float32\")\n            with T.block():\n                B[0] = A[i] * T.float32(2)\n            with T.block():\n                C[0] = C[0] + A[i] + B[0] + T.float32(1) + D[0]\n                A[i] = B[0] + T.float32(1) + D[1]\n\n\ndef verify_func_2(module):\n    a_np = np.random.randint(low=-128, high=127, size=(16,)).astype(np.float32)\n    d_np = np.random.randint(low=-128, high=127, size=(2,)).astype(np.float32)\n    c_np = np.zeros((1,), dtype=np.float32)\n    a = tvm.nd.array(a_np, device=tvm.cpu(0))\n    d = tvm.nd.array(d_np, device=tvm.cpu(0))\n    c = tvm.nd.array(c_np, device=tvm.cpu(0))\n\n    module(c, a, d)\n    tvm.testing.assert_allclose(c_np + np.sum(3 * a_np + 1 + d_np[0]), c.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np * 2 + 1 + d_np[1], a.numpy(), rtol=1e-4)\n\n\n@T.prim_func\ndef func_3(\n    C: T.Buffer[(1,), \"float32\"],\n    A: T.Buffer[(16,), \"float32\"],\n    D: T.Buffer[(2,), \"float32\"],\n    E: T.Buffer[(16,), \"float32\"],\n    F: T.Buffer[(16,), \"float32\"],\n):\n    for i in T.serial(\n        0,\n        16,\n    ):\n        with T.block():\n            B = T.alloc_buffer((1,), dtype=\"float32\")\n            with T.block():\n                B[0] = A[i] * T.float32(2)\n            with T.block():\n                E[i] = A[i]\n                F[i] = E[i] + 1.0\n                C[0] = C[0] + A[i] + B[0] + T.float32(1) + D[0]\n                A[i] = B[0] + T.float32(1) + D[1]\n\n\ndef verify_func_3(module):\n    a_np = np.random.randint(low=-128, high=127, size=(16,)).astype(np.float32)\n    d_np = np.random.randint(low=-128, high=127, size=(2,)).astype(np.float32)\n    c_np = np.zeros((1,), dtype=np.float32)\n    e_np = np.zeros((16,), dtype=np.float32)\n    f_np = np.zeros((16,), dtype=np.float32)\n    a = tvm.nd.array(a_np, device=tvm.cpu(0))\n    d = tvm.nd.array(d_np, device=tvm.cpu(0))\n    c = tvm.nd.array(c_np, device=tvm.cpu(0))\n    e = tvm.nd.array(e_np, device=tvm.cpu(0))\n    f = tvm.nd.array(f_np, device=tvm.cpu(0))\n\n    module(c, a, d, e, f)\n    tvm.testing.assert_allclose(c_np + np.sum(3 * a_np + 1 + d_np[0]), c.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np * 2 + 1 + d_np[1], a.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np, e.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np + 1, f.numpy(), rtol=1e-4)\n\n\n@T.prim_func\ndef func_4(\n    C: T.Buffer[(1,), \"float32\"],\n    A: T.Buffer[(16,), \"float32\"],\n    F: T.Buffer[(16,), \"float32\"],\n    D: T.Buffer[(2,), \"float32\"],\n    E: T.Buffer[(16,), \"float32\"],\n):\n    for i in T.serial(\n        0,\n        16,\n    ):\n        with T.block():\n            B = T.alloc_buffer((1,), dtype=\"float32\")\n            with T.block():\n                B[0] = A[i] * T.float32(2)\n            with T.block():\n                E[i] = A[i]\n                F[i] = E[i] + 1.0\n                C[0] = C[0] + A[i] + B[0] + T.float32(1) + D[0]\n                A[i] = B[0] + T.float32(1) + D[1]\n\n\ndef verify_func_4(module):\n    a_np = np.random.randint(low=-128, high=127, size=(16,)).astype(np.float32)\n    d_np = np.random.randint(low=-128, high=127, size=(2,)).astype(np.float32)\n    c_np = np.zeros((1,), dtype=np.float32)\n    e_np = np.zeros((16,), dtype=np.float32)\n    f_np = np.zeros((16,), dtype=np.float32)\n    a = tvm.nd.array(a_np, device=tvm.cpu(0))\n    d = tvm.nd.array(d_np, device=tvm.cpu(0))\n    c = tvm.nd.array(c_np, device=tvm.cpu(0))\n    e = tvm.nd.array(e_np, device=tvm.cpu(0))\n    f = tvm.nd.array(f_np, device=tvm.cpu(0))\n\n    module(c, a, f, d, e)\n    tvm.testing.assert_allclose(c_np + np.sum(3 * a_np + 1 + d_np[0]), c.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np * 2 + 1 + d_np[1], a.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np, e.numpy(), rtol=1e-4)\n    tvm.testing.assert_allclose(a_np + 1, f.numpy(), rtol=1e-4)\n\n\nclass TestPrimFuncs:\n    func, verify = tvm.testing.parameters(\n        [func_1, verify_func_1],\n        [func_2, verify_func_2],\n        [func_3, verify_func_3],\n        [func_4, verify_func_4],\n    )\n\n    def test_primfunc_call(self, func, verify):\n        target = tvm.target.Target(\"llvm\")\n        func = tvm.build(func, target=target)\n        verify(func)\n\n    def test_te_extern_call(self, func, verify):\n        ir_mod = tvm.IRModule.from_expr(func.with_attr(\"global_symbol\", \"main\"))\n        prim_func = ir_mod[\"main\"]\n\n        input_tensors = create_input_tensors_for_primfunc(prim_func)\n        output = te.extern_primfunc(input_tensors, prim_func)\n        rt_prim_func = te.create_prim_func(tensors_from_extern_op(output, prim_func))\n        tvm.ir.assert_structural_equal(tvm.lower(prim_func), tvm.lower(rt_prim_func))\n\n        target = tvm.target.Target(\"llvm\")\n        func = tvm.build(rt_prim_func, target=target)\n        verify(func)\n\n\ndef tensors_from_extern_op(extern, func):\n    if isinstance(extern, list):\n        output_tensors = extern\n    else:\n        output_tensors = [extern]\n    output_buffers = []\n    input_buffers = []\n    input_tensors = []\n    for ext in output_tensors:\n        output_buffers.extend(ext.op.output_placeholders)\n        input_buffers.extend(ext.op.input_placeholders)\n        input_tensors.extend(ext.op.input_tensors)\n    input_binds = dict(zip(input_buffers, input_tensors))\n    output_binds = dict(zip(output_buffers, output_tensors))\n    buffer_to_tensor = {**input_binds, **output_binds}\n    ordered_tensors = []\n    for var in func.params:\n        buf = func.buffer_map[var]\n        ordered_tensors.append(buffer_to_tensor[buf])\n    return ordered_tensors\n\n\ndef create_input_tensors_for_primfunc(primfunc):\n    access_map = {k: tuple(v) for k, v in _ffi_arith_api.DomainTouchedAccessMap(primfunc).items()}\n    in_buffers = [buf for buf, access in access_map.items() if len(access[0])]\n    out_buffers = [buf for buf, access in access_map.items() if len(access[1])]\n    assert in_buffers, \"PrimFunc has no input buffers\"\n    assert out_buffers, \"PrimFunc has no output buffers\"\n\n    outputs = []\n    inplace = []\n    inputs = in_buffers\n    for obuf in out_buffers:\n        if obuf in in_buffers:\n            inplace.append(obuf)\n        else:\n            outputs.append(obuf)\n\n    if not outputs:\n        iobuf = inplace.pop()\n        inputs.remove(iobuf)\n        outputs = [iobuf]\n\n    def create_tensors(input_buffers):\n        tensors = []\n        for buf in input_buffers:\n            t = te.placeholder(buf.shape, dtype=buf.dtype, name=buf.name + \"_placeholder\")\n            tensors.append(t)\n        return tensors\n\n    return create_tensors(inputs)\n\n\nif __name__ == \"__main__\":\n    sys.exit(pytest.main(sys.argv))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_texture_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm.ir.module import IRModule\nfrom tvm import tir\nfrom tvm.script import tir as T\n\n\ndef test_texture_scope():\n    @tvm.script.ir_module\n    class PlusOneMultTwo:\n        @T.prim_func\n        def main(a: T.handle, b: T.handle) -> None:\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            A = T.match_buffer(a, (128, 128, 4), dtype=\"float32\", scope=\"global.texture\")\n            B = T.alloc_buffer((128, 128, 4), dtype=\"float32\", scope=\"global.texture\")\n            C = T.match_buffer(b, (128, 128, 4), dtype=\"float32\", scope=\"global.texture\")\n            for block_idx in T.thread_binding(0, 128, thread=\"blockIdx.x\"):\n                for thread_idx in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                    for k in T.serial(4):\n                        with T.block(\"B\"):\n                            vb, vt, vk = T.axis.remap(\"SSS\", [block_idx, thread_idx, k])\n                            B[vb, vt, vk] = A[vb, vt, vk] + T.float32(1)\n            for block_idx in T.thread_binding(0, 128, thread=\"blockIdx.x\"):\n                for thread_idx in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                    for k in T.serial(4):\n                        with T.block(\"C\"):\n                            vb, vt, vk = T.axis.remap(\"SSS\", [block_idx, thread_idx, k])\n                            C[vb, vt, vk] = B[vb, vt, vk] * T.float32(2)\n\n    sch = tir.Schedule(PlusOneMultTwo, debug_mask=\"all\")\n\n    def schedule_block(block):\n        _, _, inner = sch.get_loops(block)\n        sch.vectorize(inner)\n\n    schedule_block(sch.get_block(\"B\"))\n    schedule_block(sch.get_block(\"C\"))\n\n    target = tvm.target.Target(\"opencl\")\n    mod = tvm.build(sch.mod[\"main\"], target=target)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_bf16_legalize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import topi\nfrom tvm import te\n\n\ndef lower_stmt(sche, params, passfunc):\n    func = tvm.driver.build_module.schedule_to_module(sche, params, \"main\", None)[\"main\"]\n    func = passfunc()(tvm.IRModule.from_expr(func))[\"main\"]\n    stmt = func.body\n    return stmt\n\n\ndef test_promote():\n    def runpass(op, passfunc):\n        a = te.placeholder((100,), dtype=\"bfloat16\")\n        b = te.placeholder((100,), dtype=\"bfloat16\")\n        c = te.compute((100,), lambda i: op(a[i], b[i]))\n        s = te.create_schedule(c.op)\n        return lower_stmt(s, [a, b, c], passfunc)\n\n    def get_promoted(op):\n        a = te.placeholder((100,), dtype=\"bfloat16\")\n        b = te.placeholder((100,), dtype=\"bfloat16\")\n        c = te.compute(\n            (100,),\n            lambda i: topi.cast(op(topi.cast(a[i], \"float\"), topi.cast(b[i], \"float\")), \"bfloat16\"),\n        )\n        s = te.create_schedule(c.op)\n        func = tvm.driver.build_module.schedule_to_module(s, [a, b, c], \"main\", None)[\"main\"]\n        return func.body\n\n    def test_promoted(op):\n        stmt = runpass(op, tvm.tir.transform.BF16Promote)\n        tvm.ir.assert_structural_equal(stmt, get_promoted(op))\n\n    test_promoted(topi.add)\n    test_promoted(topi.subtract)\n    test_promoted(topi.multiply)\n    test_promoted(topi.divide)\n\n\ndef test_eliminate():\n    def to32(v):\n        return topi.cast(v, \"float\")\n\n    def to16(v):\n        return topi.cast(v, \"bfloat16\")\n\n    def get_eliminated():\n        a = te.placeholder((100,), dtype=\"bfloat16\")\n        b = te.placeholder((100,), dtype=\"bfloat16\")\n        c = te.compute(\n            (100,),\n            lambda i: to16(\n                topi.add(\n                    to32(\n                        to16(\n                            topi.add(\n                                to32(a[i]),\n                                to32(b[i]),\n                            )\n                        )\n                    ),\n                    to32(\n                        to16(\n                            topi.add(\n                                to32(a[i]),\n                                to32(b[i]),\n                            )\n                        )\n                    ),\n                )\n            ),\n        )\n        s = te.create_schedule(c.op)\n        stmt = lower_stmt(s, [a, b, c], tvm.tir.transform.BF16CastElimination)\n        return stmt\n\n    def get_target():\n        a = te.placeholder((100,), dtype=\"bfloat16\")\n        b = te.placeholder((100,), dtype=\"bfloat16\")\n        c = te.compute(\n            (100,),\n            lambda i: to16(\n                topi.add(\n                    topi.add(\n                        to32(a[i]),\n                        to32(b[i]),\n                    ),\n                    topi.add(\n                        to32(a[i]),\n                        to32(b[i]),\n                    ),\n                )\n            ),\n        )\n        s = te.create_schedule(c.op)\n        func = tvm.driver.build_module.schedule_to_module(s, [a, b, c], \"main\", None)[\"main\"]\n        return func.body\n\n    tvm.ir.assert_structural_equal(get_eliminated(), get_target())\n\n\ndef test_legalize():\n    def to32(v):\n        uint32_v = topi.cast(v, \"uint32\")\n        uint32_v = tvm.tir.call_intrin(\n            \"uint32\", \"tir.shift_left\", uint32_v, tvm.tir.const(16, \"uint32\")\n        )\n        return tvm.tir.call_intrin(\"float32\", \"tir.reinterpret\", uint32_v)\n\n    def to16(v):\n        uint32_v = tvm.tir.call_intrin(\"uint32\", \"tir.reinterpret\", v)\n        rounding_bias = tvm.tir.call_intrin(\n            \"uint32\", \"tir.shift_right\", uint32_v, tvm.tir.const(16, \"uint32\")\n        )\n        rounding_bias = tvm.tir.call_intrin(\n            \"uint32\", \"tir.bitwise_and\", rounding_bias, tvm.tir.const(1, \"uint32\")\n        )\n        rounding_bias = rounding_bias + tvm.tir.const(0x7FFF, \"uint16\")\n        uint32_v = uint32_v + rounding_bias\n        uint32_v = tvm.tir.call_intrin(\n            \"uint32\", \"tir.shift_right\", uint32_v, tvm.tir.const(16, \"uint32\")\n        )\n        return topi.cast(uint32_v, \"uint16\")\n\n    def check(fcompute_before, fcompute_after):\n        a = te.placeholder((100,), dtype=\"bfloat16\", name=\"A\")\n        b = te.placeholder((100,), dtype=\"bfloat16\", name=\"B\")\n        c = te.compute((100,), fcompute_before(a, b), name=\"C\")\n        s = te.create_schedule(c.op)\n        stmt = lower_stmt(s, [a, b, c], tvm.tir.transform.BF16Legalize)\n\n        a = te.placeholder((100,), dtype=\"uint16\", name=\"A\")\n        b = te.placeholder((100,), dtype=\"uint16\", name=\"B\")\n        c = te.compute((100,), fcompute_after(a, b), name=\"C\")\n        s = te.create_schedule(c.op)\n        func = tvm.driver.build_module.schedule_to_module(s, [a, b, c], \"main\", None)[\"main\"]\n        tvm.ir.assert_structural_equal(stmt, func.body)\n\n    def orig1(a, b):\n        return lambda i: a[i] + b[i] + a[99 - i] + b[99 - i]\n\n    def after1(a, b):\n        return lambda i: to16(to32(a[i]) + to32(b[i]) + to32(a[99 - i]) + to32(b[99 - i]))\n\n    def orig2(a, b):\n        return lambda i: a[i] * b[i] + a[99 - i] * b[99 - i] + a[i]\n\n    def after2(a, b):\n        return lambda i: to16(\n            to32(a[i]) * to32(b[i]) + to32(a[99 - i]) * to32(b[99 - i]) + to32(a[i])\n        )\n\n    check(orig1, after1)\n    check(orig2, after2)\n\n\nif __name__ == \"__main__\":\n    test_promote()\n    test_eliminate()\n    test_legalize()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_combine_context_call.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_for():\n    dev_type = te.var(\"dev_type\")\n\n    def device_context(dev_id):\n        ctx = tvm.tir.call_extern(\"handle\", \"device_context\", dev_type, dev_id)\n        return tvm.tir.Call(\"handle\", \"tir.tvm_thread_context\", [ctx])\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        ib.emit(tvm.tir.call_extern(\"int32\", \"fadd\", device_context(0), A.asobject().data))\n        with ib.for_range(0, 10, name=\"j\") as j:\n            ib.emit(tvm.tir.call_extern(\"int32\", \"fadd\", device_context(1), A.asobject().data))\n            ib.emit(tvm.tir.call_extern(\"int32\", \"fadd\", device_context(0), A.asobject().data))\n    body = ib.get()\n    mod = tvm.IRModule({\"func\": tvm.tir.PrimFunc([dev_type, n], body)})\n\n    mod = tvm.tir.transform.CombineContextCall()(mod)\n\n    assert mod[\"func\"].body.value.dtype == \"handle\"\n    assert mod[\"func\"].body.body.value.dtype == \"handle\"\n\n\nif __name__ == \"__main__\":\n    test_for()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_common_subexpr_elim.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport hashlib\n\nimport tvm\nfrom tvm import auto_scheduler, te, topi\nfrom tvm.ir.base import save_json\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\n\n# -----------------------------------------------------\n# Basic test for the expected Behavior of the CSE pass\n# -----------------------------------------------------\n# A test program which gives the opportunity for the CSE pass to introduce two new variables,\n# at two different levels\ndef test_cse():\n    z1 = te.var(\"z1\")\n    z2 = te.var(\"z2\")\n    z3 = te.var(\"z3\")\n    i1 = te.var(\"i1\")\n    i2 = te.var(\"i2\")\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    a = te.var(\"a\")\n    b = te.var(\"b\")\n    dtype = \"int32\"\n    buffer = tvm.tir.decl_buffer((50,), dtype)\n    # Test prog :\n    # let z1=1 in let z2=2 in\n    #   Mem[i1] = z1+z2;\n    #   let x = 1 in let y = 1 in\n    #     let a = (x+y) + (z1+z2) in\n    #       let b = (x+y) + z3 in\n    #         Mem[i2] = a+b;\n    body = tvm.tir.LetStmt(\n        z1,\n        1,\n        tvm.tir.LetStmt(\n            z2,\n            2,\n            tvm.tir.SeqStmt(\n                [\n                    tvm.tir.BufferStore(buffer, z1 + z2, [i1]),\n                    tvm.tir.LetStmt(\n                        x,\n                        1,\n                        tvm.tir.LetStmt(\n                            y,\n                            1,\n                            tvm.tir.LetStmt(\n                                a,\n                                (x + y) + (z1 + z2),\n                                tvm.tir.LetStmt(\n                                    b, (x + y) + z3, tvm.tir.BufferStore(buffer, a + b, [i2])\n                                ),\n                            ),\n                        ),\n                    ),\n                ]\n            ),\n        ),\n    )\n    # This test program gives the opportunity to introduce two new variables, at two different\n    # levels and to perform replacements in the value of \"a\" and \"b\", using these new variables.\n    # We will check all of that underneath and more, making also sure that nothing else has changed\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i1, i2, z3], body))\n    body = tvm.tir.transform.CommonSubexprElimTIR()(mod)\n\n    tvm.transform.PrintIR()(body)\n\n    body = body[\"main\"].body  # Gets the body of the main, i.e. the full statement\n\n    assert body.var.name == \"z1\"\n    assert body.value == 1\n\n    body = body.body\n\n    assert body.var.name == \"z2\"\n    assert body.value == 2\n    # This is the let-in for the first variable generated cse_var_1\n    assert isinstance(body.body, tvm.tir.LetStmt)\n\n    body = body.body\n\n    # And this is the name and value of this variable\n    cse_var_1 = body.var  # Keep the variable accessible for later checking the replacements\n    assert body.var.name == \"cse_var_1\"\n    assert tvm.ir.structural_equal(body.value, z1 + z2)\n    assert isinstance(body.body, tvm.tir.SeqStmt)\n\n    body = body.body\n\n    assert isinstance(body[0], tvm.tir.BufferStore)\n    assert isinstance(body[1], tvm.tir.LetStmt)\n\n    body = body[1]\n\n    assert body.var.name == \"x\"\n    assert body.value == 1\n\n    body = body.body\n\n    assert body.var.name == \"y\"\n    assert body.value == 1\n    # This is the let-in for the second variable generated cse_var_2\n    assert isinstance(body.body, tvm.tir.LetStmt)\n\n    body = body.body\n\n    # And this is the name and value of this variable\n    cse_var_2 = body.var  # Keep the variable accessible for later checking the replacements\n    assert body.var.name == \"cse_var_2\"\n    assert tvm.ir.structural_equal(body.value, x + y)\n\n    body = body.body\n\n    body.var.name == \"a\"\n    # Check that the replacement has been done correctly!\n    assert tvm.ir.structural_equal(body.value, cse_var_2 + cse_var_1)\n\n    body = body.body\n\n    body.var.name == \"b\"\n    # Check that the replacement has been done correctly!\n    assert tvm.ir.structural_equal(body.value, cse_var_2 + z3)\n\n    assert isinstance(body.body, tvm.tir.BufferStore)\n\n\n# -----------------------------------------------------\n# Tests related to If nodes\n# -----------------------------------------------------\n# First specific test for if nodes : Some duplicated computations appear only in one branch (here\n# the Then branch), not in both branches.\n# In this case, the CSE pass should introduce the redundant computation at the top of the Then\n# branch, not before the whole If (otherwise that would lead to some computations being computed\n# for nothing when it is the Else branch that is executed).\ndef test_cse_ifNode_1():\n    b = te.var(\"b\")\n    i1 = te.var(\"i1\")\n    i2 = te.var(\"i2\")\n    i3 = te.var(\"i3\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    dtype = \"int32\"\n    buffer = tvm.tir.decl_buffer((50,), dtype)\n    # Test prog :\n    # let b=1 in\n    #   if(b) {\n    #      Mem[i1] = y+z\n    #     Mem[i2] = y+z\n    #   }\n    #   else {\n    #     Mem[i3] = y\n    #   }\n    body = tvm.tir.LetStmt(\n        b,\n        1,\n        tvm.tir.IfThenElse(\n            b,\n            tvm.tir.SeqStmt(\n                [tvm.tir.BufferStore(buffer, y + z, [i1]), tvm.tir.BufferStore(buffer, y + z, [i2])]\n            ),\n            tvm.tir.BufferStore(buffer, y, [i3]),\n        ),\n    )\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i1, i2, i3, y, z], body))\n    body = tvm.tir.transform.CommonSubexprElimTIR()(mod)\n\n    tvm.transform.PrintIR()(body)\n\n    body = body[\"main\"].body  # Gets the body of the main, i.e. the full statement\n\n    assert body.var.name == \"b\"\n    assert body.value == 1\n    assert isinstance(body.body, tvm.tir.IfThenElse)\n\n    body = body.body\n\n    assert isinstance(body.then_case, tvm.tir.LetStmt)\n\n    body = body.then_case\n\n    # The let-in introduced by the CSE should appear now, inside the Then branch of the If node\n    assert body.var.name == \"cse_var_1\"\n    # and it should contain the expression (y+z) that was redundant\n    assert tvm.ir.structural_equal(body.value, y + z)\n\n\n# Second test for if nodes : Some duplicated computations appear in both the Then and Else branch.\n# In this case, the CSE pass should introduce the redundant computation before the whole If node,\n# because regardless of the execution path, it is going to be computed.\ndef test_cse_ifNode_2():\n    b = te.var(\"b\")\n    i1 = te.var(\"i1\")\n    i2 = te.var(\"i2\")\n    i3 = te.var(\"i3\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    dtype = \"int32\"\n    buffer = tvm.tir.decl_buffer((50,), dtype)\n    # Test prog :\n    # let b=1 in\n    #   if(b) {\n    #     Mem[i1] = y+z\n    #      Mem[i2] = y\n    #   }\n    #   else {\n    #     Mem[i3] = y+z\n    #   }\n    body = tvm.tir.LetStmt(\n        b,\n        1,\n        tvm.tir.IfThenElse(\n            b,\n            tvm.tir.SeqStmt(\n                [\n                    tvm.tir.BufferStore(buffer, y + z, [i1]),  # (y+z) is present in Then branch\n                    tvm.tir.BufferStore(buffer, y, [i2]),\n                ]\n            ),\n            tvm.tir.BufferStore(buffer, y + z, [i3]),  # and also present in the Else branch\n        ),\n    )\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i1, i2, i3, y, z], body))\n    body = tvm.tir.transform.CommonSubexprElimTIR()(mod)\n\n    tvm.transform.PrintIR()(body)\n\n    body = body[\"main\"].body  # Gets the body of the main, i.e. the full statement\n\n    assert isinstance(body, tvm.tir.LetStmt)\n\n    # The let-in introduced by the CSE should appear now, at the toplevel (i.e. before the If)\n    assert body.var.name == \"cse_var_1\"\n    # and it should contain the expression (y+z) that was redundant\n    assert tvm.ir.structural_equal(body.value, y + z)\n\n\n# -------------------------------------------------------------------------------------------------\n# Test commoning in cascade : after having introduced a big exp ((x+y)+z) into a new variable,\n# it will become possible to do another commoning for (x+y) which appears both in the new variable\n# and in the rest of the program.\n# -------------------------------------------------------------------------------------------------\ndef test_cse_cascade():\n    i1 = te.var(\"i1\")\n    i2 = te.var(\"i2\")\n    i3 = te.var(\"i3\")\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    dtype = \"int32\"\n    buffer = tvm.tir.decl_buffer((50,), dtype)\n    # Test prog :\n    # Mem[i1] = (x+y)+z;\n    # Mem[i2] = (x+y)+z;\n    # Mem[i3] = x+y\n    body = tvm.tir.SeqStmt(\n        [\n            tvm.tir.BufferStore(buffer, (x + y) + z, [i1]),\n            tvm.tir.BufferStore(buffer, (x + y) + z, [i2]),\n            tvm.tir.BufferStore(buffer, (x + y), [i3]),\n        ]\n    )\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i1, i2, i3, x, y, z], body))\n    body = tvm.tir.transform.CommonSubexprElimTIR()(mod)\n\n    tvm.transform.PrintIR()(body)\n\n    body = body[\"main\"].body  # Gets the body of the main, i.e. the full statement\n\n    assert isinstance(body, tvm.tir.LetStmt)\n\n    # The second let-in (by order introduced) introduced by the CSE should appear first\n    cse_var_2 = body.var  # Keep the variable accessible for later checking the replacements\n    assert body.var.name == \"cse_var_2\"\n    # and it should contain the expression (x+y)\n    assert tvm.ir.structural_equal(body.value, (x + y))\n\n    body = body.body\n\n    assert isinstance(body, tvm.tir.LetStmt)\n\n    # The first let-in (by order introduced) introduced by the CSE should appear now, after the 2nd\n    cse_var_1 = body.var  # Keep the variable accessible for later checking the replacements\n    assert body.var.name == \"cse_var_1\"\n    # and it should contain the expression cse_var_2+z\n    assert tvm.ir.structural_equal(body.value, cse_var_2 + z)\n\n    body = body.body\n\n    assert isinstance(body, tvm.tir.SeqStmt)\n    assert isinstance(body[0], tvm.tir.BufferStore)\n    assert isinstance(body[1], tvm.tir.BufferStore)\n    assert isinstance(body[2], tvm.tir.BufferStore)\n\n    store1 = body[0]\n    store2 = body[1]\n    store3 = body[2]\n\n    assert tvm.ir.structural_equal(store1.value, cse_var_1)\n    assert tvm.ir.structural_equal(store2.value, cse_var_1)\n    assert tvm.ir.structural_equal(store3.value, cse_var_2)\n\n\n# -----------------------------------------------------------------------------------------\n# A test which ensures that we don't perform normalizations outside of introduced variables\n# -----------------------------------------------------------------------------------------\ndef test_no_normalization_without_commoning():\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    z = te.var(\"z\")\n    a = te.var(\"a\")\n    # Test prog :\n    # let a = x + (y + z) in a\n    body = tvm.tir.LetStmt(a, x + (y + z), tvm.tir.Evaluate(a))\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([x, y, z], body))\n    body = tvm.tir.transform.CommonSubexprElimTIR(identify_equiv_terms=True)(mod)\n\n    tvm.transform.PrintIR()(body)\n\n    body = body[\"main\"].body  # Gets the body of the main, i.e. the full statement\n\n    assert body.var.name == \"a\"\n    assert tvm.ir.structural_equal(body.value, x + (y + z))\n\n\n# -------------------------------------------------\n# Part for testing the commoning with equivalences\n# -------------------------------------------------\n@T.prim_func\ndef func_distributivity(i1: T.int32, i2: T.int32, x: T.int32, y: T.int32, z: T.int32) -> None:\n    B = T.buffer_decl((50,), \"int32\")\n    B[i1] = x * (y + z)\n    B[i2] = x * y + x * z\n\n\n@T.prim_func\ndef func_distributivity_expected(\n    i1: T.int32, i2: T.int32, x: T.int32, y: T.int32, z: T.int32\n) -> None:\n    B = T.buffer_decl((50,), \"int32\")\n    cse_var_1 = T.var(\"int32\")\n    with T.let(cse_var_1, x * y + x * z):\n        B[i1] = cse_var_1\n        B[i2] = cse_var_1\n\n\n@T.prim_func\ndef func_associativity(i1: T.int32, i2: T.int32, x: T.int32, y: T.int32, z: T.int32) -> None:\n    B = T.buffer_decl((50,), \"int32\")\n    B[i1] = (x + y) + z\n    B[i2] = x + (y + z)\n\n\n@T.prim_func\ndef func_associativity_expected(\n    i1: T.int32, i2: T.int32, x: T.int32, y: T.int32, z: T.int32\n) -> None:\n    B = T.buffer_decl((50,), \"int32\")\n    cse_var_1 = T.var(\"int32\")\n    with T.let(cse_var_1, (x + y) + z):\n        B[i1] = cse_var_1\n        B[i2] = cse_var_1\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    body = tvm.tir.transform.CommonSubexprElimTIR(identify_equiv_terms=True)(mod)\n    tvm.transform.PrintIR()(body)\n    tvm.ir.assert_structural_equal(body[\"main\"], transformed)\n\n\ndef test_semantic_equiv_distributivity():\n    _check(func_distributivity, func_distributivity_expected)\n\n\ndef test_semantic_equiv_associativity():\n    _check(func_associativity, func_associativity_expected)\n\n\n# -----------------------------------------------------\n# Tests that verify the determinism of the pass\n# -----------------------------------------------------\ndef test_deterministic_cse():\n    import random\n\n    \"\"\"Test deterministic allocation of CSE vars\n\n    We expect something like\n\n        result = (x + 1) + (x + 2) + (x + 3) + (x + 1) + (x + 2) + (x + 3)\n            -->\n        cse_var_3 = (x + 1)\n        cse_var_2 = (x + 2)\n        cse_var_1 = (x + 3)\n        result = cse_var_3 + cse_var_2 + cse_var_1 + cse_var_3 + cse_var_2 + cse_var_1\n    \"\"\"\n    NUM_TERMS = 10\n    REPEATS = 10\n\n    x = te.var(\"x\")\n    result = te.var(\"result\")\n\n    offsets = sorted([i + 1 for i in range(NUM_TERMS)])\n    inc1 = [(x + offsets[i]) for i in range(NUM_TERMS)]\n    inc2 = [(x + offsets[i]) for i in range(NUM_TERMS)]\n\n    expression = x\n    for add in inc1 + inc2:\n        expression = expression + add\n    let_stmt = tvm.tir.LetStmt(result, expression, tvm.tir.Evaluate(result))\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([x], let_stmt))\n\n    initial_hash = None\n    for _ in range(REPEATS):\n        body = tvm.tir.transform.CommonSubexprElimTIR()(mod)\n\n        body = body[\"main\"]\n\n        # Hash and ensure serialize json is the same every time\n        json_val = save_json(body)\n        json_hash = hashlib.sha256(json_val.encode()).hexdigest()\n\n        if initial_hash is None:\n            initial_hash = json_hash\n        assert json_hash == initial_hash\n\n\n# Needed for the second test on determinism\nLOG_LINE = '{\"i\": [[\"[\\\\\"conv2d_layer\\\\\", 1, 7, 7, 512, 512, 3, 3, [1, 1], [1, 1]]\", \\\n            \"llvm -keys=cpu -mcpu=broadwell -num-cores=2\", \\\n            [8, 64, 64, 0, 0, 0, 0, 0], \"\", 1, []], [[], [[\"CI\", 5], \\\n            [\"SP\", 3, 0, 1, [1, 1, 1], 1], [\"SP\", 3, 4, 512, [1, 32, 16], 1], \\\n            [\"SP\", 3, 8, 7, [7, 1, 1], 1], [\"SP\", 3, 12, 7, [1, 1, 1], 1], \\\n            [\"SP\", 3, 16, 512, [1], 1], [\"SP\", 3, 18, 3, [1], 1], [\"SP\", 3, 20, 3, [3], 1], \\\n            [\"RE\", 3, [0, 4, 8, 12, 1, 5, 9, 13, 16, 18, 20, 2, 6, 10, 14, 17, 19, 21, 3, 7, \\\n            11, 15]], [\"FSP\", 6, 0, 1, 2], [\"FSP\", 6, 3, 2, 2], [\"FSP\", 6, 6, 3, 2], \\\n            [\"FSP\", 6, 9, 4, 2], [\"RE\", 6, [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11]], \\\n            [\"CA\", 3, 6, 7], [\"CA\", 1, 6, 5], [\"FU\", 6, [0, 1, 2, 3, 4, 5]], [\"AN\", 6, 0, 3], \\\n            [\"PR\", 3, 0, \"auto_unroll_max_step$512\"], [\"AN\", 1, 3, 2], [\"AN\", 3, 21, 2], \\\n            [\"AN\", 6, 6, 2]]]], \"r\": [[0.0331129], 0, 0.900362, 1647464342], \"v\": \"v0.6\"}\\n'\n\n# The workload associated with the log\n@auto_scheduler.register_workload\ndef conv2d_layer(N, H, W, CO, CI, KH, KW, stride, padding):\n    data = te.placeholder((N, CI, H, W), name=\"data\")\n    kernel = te.placeholder((CO, CI, KH, KW), name=\"kernel\")\n    bias = te.placeholder((1, CO, 1, 1), name=\"bias\")\n    conv = topi.nn.conv2d_nchw(data, kernel, stride, padding, dilation=1, out_dtype=\"float32\")\n    out = topi.nn.relu(conv + bias)\n    return [data, kernel, bias, out]\n\n\ndef test_deterministic_cse_2():\n    inp, inr = auto_scheduler.measure_record.load_record_from_string(LOG_LINE)\n    inp = auto_scheduler.measure.recover_measure_input(inp, rebuild_state=True)\n\n    initial_hash = None\n\n    for _ in range(10):\n        sch, args = inp.task.compute_dag.apply_steps_from_state(inp.state)\n        ir_module = tvm.lower(sch, args)\n        primfunc = ir_module[\"main\"]\n        json_str = save_json(primfunc)\n        new_hash = hashlib.sha256(json_str.encode(\"utf-8\")).hexdigest()\n        # Make sure that all the hashes are going to be the same\n        if initial_hash is None:\n            initial_hash = new_hash\n        assert new_hash == initial_hash\n\n\nif __name__ == \"__main__\":\n    # Basic test:\n    test_cse()\n    # Tests related to If nodes:\n    test_cse_ifNode_1()\n    test_cse_ifNode_2()\n    # Test performing a commoning on a commoning:\n    test_cse_cascade()\n    # Test that verifies that the input program itself is not being normalized by the pass:\n    test_no_normalization_without_commoning()\n    # Tests that turn on the equivalence of terms and verify the commoning with equivalences:\n    test_semantic_equiv_distributivity()\n    test_semantic_equiv_associativity()\n    # Tests that verify the determinism of the pass:\n    test_deterministic_cse()\n    test_deterministic_cse_2()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_compact_buffer_region.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.CompactBufferAllocation()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    transformed = tvm.tir.transform.Simplify()(tvm.IRModule.from_expr(transformed))[\"main\"]\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed)\n\n\n@T.prim_func\ndef elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((16, 16), \"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[i, j])\n                    B[i, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(B[i, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[i, j] * 2.0\n\n\n@T.prim_func\ndef compacted_elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((1, 16), \"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[0, j])\n                    B[0, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(B[0, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[0, j] * 2.0\n\n\n@T.prim_func\ndef unschedulable_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((16, 16), \"float32\")\n            for j in range(0, 16):\n                T.evaluate(T.call_extern(\"dummy_extern_function\", B.data, dtype=\"int32\"))\n                B[i, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                C[i, j] = B[i, j] * 2.0\n\n\n@T.prim_func\ndef param_buffer_access_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (20, 20), \"float32\")\n    B = T.match_buffer(c, (20, 20), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(B[i, 0:16])\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[i, j])\n                    B[i, j] = A[i, j] + 1.0\n\n\n@T.prim_func\ndef shared_mem_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in T.thread_binding(0, 2, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 2, thread=\"vthread\"):\n            for i2 in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n                with T.block():\n                    T.reads(A[i0 * 8 + i1 * 4 + i2, 0:16])\n                    T.writes(C[i0 * 8 + i1 * 4 + i2, 0:16])\n                    B = T.alloc_buffer((16, 16), \"float32\", scope=\"shared\")\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(A[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(B[i0 * 8 + i1 * 4 + i2, j])\n                            B[i0 * 8 + i1 * 4 + i2, j] = A[i0 * 8 + i1 * 4 + i2, j] + 1.0\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(B[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(C[i0 * 8 + i1 * 4 + i2, j])\n                            C[i0 * 8 + i1 * 4 + i2, j] = B[i0 * 8 + i1 * 4 + i2, j] * 2.0\n\n\n@T.prim_func\ndef compacted_shared_mem_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in T.thread_binding(0, 2, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 2, thread=\"vthread\"):\n            for i2 in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n                with T.block():\n                    T.reads(A[i0 * 8 + i1 * 4 + i2, 0:16])\n                    T.writes(C[i0 * 8 + i1 * 4 + i2, 0:16])\n                    B = T.alloc_buffer((8, 16), \"float32\", scope=\"shared\")\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(A[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(B[i1 * 4 + i2, j])\n                            B[i1 * 4 + i2, j] = A[i0 * 8 + i1 * 4 + i2, j] + 1.0\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(B[i1 * 4 + i2, j])\n                            T.writes(C[i0 * 8 + i1 * 4 + i2, j])\n                            C[i0 * 8 + i1 * 4 + i2, j] = B[i1 * 4 + i2, j] * 2.0\n\n\n@T.prim_func\ndef warp_mem_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in T.thread_binding(0, 2, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 2, thread=\"vthread\"):\n            for i2 in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n                with T.block():\n                    T.reads(A[i0 * 8 + i1 * 4 + i2, 0:16])\n                    T.writes(C[i0 * 8 + i1 * 4 + i2, 0:16])\n                    B = T.alloc_buffer((16, 16), \"float32\", scope=\"warp\")\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(A[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(B[i0 * 8 + i1 * 4 + i2, j])\n                            B[i0 * 8 + i1 * 4 + i2, j] = A[i0 * 8 + i1 * 4 + i2, j] + 1.0\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(B[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(C[i0 * 8 + i1 * 4 + i2, j])\n                            C[i0 * 8 + i1 * 4 + i2, j] = B[i0 * 8 + i1 * 4 + i2, j] * 2.0\n\n\n@T.prim_func\ndef compacted_warp_mem_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in T.thread_binding(0, 2, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 2, thread=\"vthread\"):\n            for i2 in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n                with T.block():\n                    T.reads(A[i0 * 8 + i1 * 4 + i2, 0:16])\n                    T.writes(C[i0 * 8 + i1 * 4 + i2, 0:16])\n                    B = T.alloc_buffer((4, 16), \"float32\", scope=\"warp\")\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(A[i0 * 8 + i1 * 4 + i2, j])\n                            T.writes(B[i2, j])\n                            B[i2, j] = A[i0 * 8 + i1 * 4 + i2, j] + 1.0\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(B[i2, j])\n                            T.writes(C[i0 * 8 + i1 * 4 + i2, j])\n                            C[i0 * 8 + i1 * 4 + i2, j] = B[i2, j] * 2.0\n\n\n@T.prim_func\ndef symbolic_func(a: T.handle, c: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (n * 8,), \"float32\")\n    C = T.match_buffer(c, (n * 8,), \"float32\")\n    for i in range(0, n):\n        with T.block():\n            T.reads(A[i * 8 : i * 8 + 8])\n            T.writes(C[i * 8 : i * 8 + 8])\n            B = T.alloc_buffer((n * 8,), \"float32\")\n            for j in range(0, 8):\n                with T.block():\n                    T.reads(A[i * 8 + j])\n                    T.writes(B[i * 8 + j])\n                    B[i * 8 + j] = A[i * 8 + j] + 1.0\n            for j in range(0, 8):\n                with T.block():\n                    T.reads(B[i * 8 + j])\n                    T.writes(C[i * 8 + j])\n                    C[i * 8 + j] = B[i * 8 + j] * 2.0\n\n\n@T.prim_func\ndef compacted_symbolic_func(a: T.handle, c: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (n * 8,), \"float32\")\n    C = T.match_buffer(c, (n * 8,), \"float32\")\n    for i in range(0, n):\n        with T.block():\n            T.reads(A[i * 8 : i * 8 + 8])\n            T.writes(C[i * 8 : i * 8 + 8])\n            B = T.alloc_buffer((T.min(n, 1) * 8,), \"float32\")\n            for j in range(0, 8):\n                with T.block():\n                    T.reads(A[i * 8 + j])\n                    T.writes(B[j])\n                    B[j] = A[i * 8 + j] + 1.0\n            for j in range(0, 8):\n                with T.block():\n                    T.reads(B[j])\n                    T.writes(C[i * 8 + j])\n                    C[i * 8 + j] = B[j] * 2.0\n\n\n@T.prim_func\ndef complex_func(a: T.handle, c: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (8, 8), \"float32\")\n    C = T.match_buffer(c, (8, 8), \"float32\")\n    for i in range(0, 8):\n        with T.block():\n            T.reads(A[0, 8])\n            T.writes(C[0, 8])\n            B = T.alloc_buffer((8, 8), \"float32\")\n            for j in range(0, 4):\n                with T.block():\n                    D = T.alloc_buffer((8, 8), \"float32\")\n                    T.reads(A[i, j])\n                    T.writes(B[i, j])\n                    for k in range(4, 8):\n                        D[k, j] = 1.0\n                    for k in range(2, 4):\n                        B[i, j] = A[i, j] + D[k, j]\n            for j in range(3, 5):\n                with T.block():\n                    T.reads(B[i, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[i, j]\n            for j in range(6, 8):\n                with T.block():\n                    T.reads(B[i, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[i, j]\n\n\n@T.prim_func\ndef compacted_complex_func(a: T.handle, c: T.handle, n: T.int32) -> None:\n    A = T.match_buffer(a, (8, 8), \"float32\")\n    C = T.match_buffer(c, (8, 8), \"float32\")\n    for i in range(0, 8):\n        with T.block():\n            T.reads(A[0, 8])\n            T.writes(C[0, 8])\n            B = T.alloc_buffer((1, 8), \"float32\")\n            for j in range(0, 4):\n                with T.block():\n                    D = T.alloc_buffer((6, 1), \"float32\")\n                    T.reads(A[i, j])\n                    T.writes(B[0, j])\n                    for k in range(4, 8):\n                        D[k - 2, 0] = 1.0\n                    for k in range(2, 4):\n                        B[0, j] = A[i, j] + D[k - 2, 0]\n            for j in range(3, 5):\n                with T.block():\n                    T.reads(B[0, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[0, j]\n            for j in range(6, 8):\n                with T.block():\n                    T.reads(B[0, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[0, j]\n\n\n@T.prim_func\ndef match_buffer_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    C = T.match_buffer(c, (16, 16))\n    for i in range(0, 16):\n        with T.block():\n            A0 = T.match_buffer(A[i, 0:16], (16))\n            C0 = T.match_buffer(C[i, 0:16], (16))\n            B = T.alloc_buffer((16, 16))\n            with T.block():\n                B0 = T.match_buffer(B[i, 0:16], (16))\n                for j in range(0, 16):\n                    with T.block():\n                        A1 = T.match_buffer(A0[j], ())\n                        B1 = T.match_buffer(B0[j], ())\n                        B1[()] = A1[()] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    C1 = T.match_buffer(C0[j], ())\n                    B2 = T.match_buffer(B[i, j], ())\n                    C1[()] = B2[()] * 2.0\n\n\n@T.prim_func\ndef compacted_match_buffer_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    C = T.match_buffer(c, (16, 16))\n    for i in range(0, 16):\n        with T.block():\n            A0 = T.match_buffer(A[i, 0:16], (16))\n            C0 = T.match_buffer(C[i, 0:16], (16))\n            B = T.alloc_buffer((1, 16))\n            with T.block():\n                B0 = T.match_buffer(B[0, 0:16], (16))\n                for j in range(0, 16):\n                    with T.block():\n                        A1 = T.match_buffer(A0[j], ())\n                        B1 = T.match_buffer(B0[j], ())\n                        B1[()] = A1[()] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    C1 = T.match_buffer(C0[j], ())\n                    B2 = T.match_buffer(B[0, j], ())\n                    C1[()] = B2[()] * 2.0\n\n\n@T.prim_func\ndef storage_align_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((16, 16), \"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[i, j])\n                    T.block_attr({\"buffer_dim_align\": [[0, 0, 16, 15]]})\n                    B[i, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(B[i, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[i, j] * 2.0\n\n\n@T.prim_func\ndef compacted_storage_align_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((1, 16), strides=(31, 1), dtype=\"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[0, j])\n                    T.block_attr({\"buffer_dim_align\": [[0, 0, 16, 15]]})\n                    B[0, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(B[0, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[0, j] * 2.0\n\n\n@T.prim_func\ndef padding_pattern_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (20, 20), \"float32\")\n    with T.block():\n        B = T.alloc_buffer((20, 20), dtype=\"float32\")\n        for i, j in T.grid(16, 16):\n            with T.block():\n                B[i, j] = A[i, j]\n        for i, j in T.grid(20, 20):\n            with T.block():\n                C[i, j] = T.if_then_else(\n                    2 <= i and i < 18 and 2 <= j and j < 18,\n                    B[i - 2, j - 2],\n                    0.0,\n                    dtype=\"float32\",\n                )\n\n\n@T.prim_func\ndef compacted_padding_pattern_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16], dtype=\"float32\")\n    C = T.match_buffer(c, [20, 20], dtype=\"float32\")\n    with T.block():\n        B = T.alloc_buffer([16, 16], dtype=\"float32\")\n        for i, j in T.grid(16, 16):\n            with T.block():\n                B[i, j] = A[i, j]\n        for i, j in T.grid(20, 20):\n            with T.block():\n                C[i, j] = T.if_then_else(\n                    2 <= i and i < 18 and 2 <= j and j < 18, B[i - 2, j - 2], 0.0, dtype=\"float32\"\n                )\n\n\n@T.prim_func\ndef padding_pattern_inlined(a: T.handle, b: T.handle) -> None:\n    X = T.match_buffer(a, [224, 224], dtype=\"float32\")\n    Y = T.match_buffer(b, [224, 224], dtype=\"float32\")\n    cache = T.alloc_buffer([224, 224], dtype=\"float32\")\n    for h, w in T.grid(224, 224):\n        with T.block(\"cache\"):\n            cache[h, w] = X[h, w]\n    for h, w, kh, kw in T.grid(224, 224, 3, 3):\n        with T.block(\"compute\"):\n            Y[h, w] = T.max(\n                Y[h, w],\n                T.if_then_else(\n                    T.likely(1 <= h + kh, dtype=\"bool\")\n                    and T.likely(h + kh < 225, dtype=\"bool\")\n                    and T.likely(1 <= w + kw, dtype=\"bool\")\n                    and T.likely(w + kw < 225, dtype=\"bool\"),\n                    cache[h + kh - 1, w + kw - 1],\n                    0.0,\n                    dtype=\"float32\",\n                ),\n            )\n\n\n@T.prim_func\ndef compacted_padding_pattern_inlined(\n    X: T.Buffer[(224, 224), \"float32\"], Y: T.Buffer[(224, 224), \"float32\"]\n) -> None:\n    cache = T.alloc_buffer([224, 224], dtype=\"float32\")\n    for h, w in T.grid(224, 224):\n        with T.block(\"cache\"):\n            cache[h, w] = X[h, w]\n    for h, w, kh, kw in T.grid(224, 224, 3, 3):\n        with T.block(\"compute\"):\n            Y[h, w] = T.max(\n                Y[h, w],\n                T.if_then_else(\n                    T.likely(1 <= h + kh, dtype=\"bool\")\n                    and T.likely(h + kh < 225, dtype=\"bool\")\n                    and T.likely(1 <= w + kw, dtype=\"bool\")\n                    and T.likely(w + kw < 225, dtype=\"bool\"),\n                    cache[h + kh - 1, w + kw - 1],\n                    0.0,\n                    dtype=\"float32\",\n                ),\n            )\n\n\n@T.prim_func\ndef mem_access_in_branch_func(a: T.handle) -> None:\n    A = T.match_buffer(a, (224, 224), \"float32\")\n    with T.block():\n        B1 = T.alloc_buffer((224, 224), dtype=\"float32\")\n        B2 = T.alloc_buffer((224, 224), dtype=\"float32\")\n        B3 = T.alloc_buffer((224, 224), dtype=\"float32\")\n        B4 = T.alloc_buffer((224, 224), dtype=\"float32\")\n        for i in range(0, 224):\n            for j in range(0, 224):\n                with T.block():\n                    if i < 112 and j < 112:\n                        B1[i, j] = A[i, j] * 2.0\n                    else:\n                        B2[i, j] = A[i, j] + 3.0\n        for i in range(0, 224):\n            for j in range(0, 224):\n                with T.block():\n                    if i < 112 or j < 112:\n                        B3[i, j] = A[i, j] * 2.0\n                    else:\n                        B4[i, j] = A[i, j] + 3.0\n\n\n@T.prim_func\ndef compacted_mem_access_in_branch_func(a: T.handle) -> None:\n    A = T.match_buffer(a, [224, 224], dtype=\"float32\")\n    with T.block():\n        B1 = T.alloc_buffer([112, 112], dtype=\"float32\")\n        B2 = T.alloc_buffer([224, 224], dtype=\"float32\")\n        B3 = T.alloc_buffer([224, 224], dtype=\"float32\")\n        B4 = T.alloc_buffer([112, 112], dtype=\"float32\")\n        for i, j in T.grid(224, 224):\n            with T.block():\n                if i < 112 and j < 112:\n                    B1[i, j] = A[i, j] * 2.0\n                else:\n                    B2[i, j] = A[i, j] + 3.0\n        for i, j in T.grid(224, 224):\n            with T.block():\n                if i < 112 or j < 112:\n                    B3[i, j] = A[i, j] * 2.0\n                else:\n                    B4[i - 112, j - 112] = A[i, j] + 3.0\n\n\n@T.prim_func\ndef opaque_access_annotated_func(a: T.handle) -> None:\n    A = T.match_buffer(a, (1024,), \"float32\")\n    with T.block():\n        B = T.alloc_buffer((1024,), dtype=\"float32\")\n        C = T.alloc_buffer((1024,), dtype=\"float32\")\n        for i in range(0, 512):\n            with T.block():\n                # no annotation, opaque access will cover full region\n                T.reads([])\n                T.writes([])\n                T.evaluate(T.call_extern(\"opaque_extern_function\", A.data, B.data, dtype=\"int32\"))\n                B[i] = A[i]\n            with T.block():\n                # treat opaque access only access annotated regions, even if\n                # they are not compatible with actual buffer accesses.\n                T.reads([B[i]])\n                T.writes([C[i : i + 9]])\n                T.evaluate(T.call_extern(\"opaque_extern_function\", B.data, C.data, dtype=\"int32\"))\n                C[i] = B[i]\n\n\n@T.prim_func\ndef compacted_opaque_access_annotated_func(a: T.handle) -> None:\n    A = T.match_buffer(a, (1024,), \"float32\")\n    with T.block():\n        B = T.alloc_buffer((1024,), dtype=\"float32\")\n        C = T.alloc_buffer((520,), dtype=\"float32\")\n        for i in range(0, 512):\n            with T.block():\n                # no annotation, opaque access will cover full region\n                T.reads([])\n                T.writes([])\n                T.evaluate(T.call_extern(\"opaque_extern_function\", A.data, B.data, dtype=\"int32\"))\n                B[i] = A[i]\n            with T.block():\n                # treat opaque access only access annotated regions, even if\n                # they are not compatible with actual buffer accesses.\n                T.reads([B[i]])\n                T.writes([C[i : i + 9]])\n                T.evaluate(T.call_extern(\"opaque_extern_function\", B.data, C.data, dtype=\"int32\"))\n                C[i] = B[i]\n\n\n@T.prim_func\ndef sparse_read_cache(\n    A_data: T.Buffer[(819,), \"float32\"],\n    B: T.Buffer[(128,), \"float32\"],\n    A_indptr: T.Buffer[(129,), \"int32\"],\n    A_indices: T.Buffer[(819,), \"int32\"],\n) -> None:\n    for i in T.serial(128):\n        with T.block(\"rowsum_outer\"):\n            T.reads(\n                A_indptr[i : i + 1],\n                A_data[A_indptr[i] + 0 : A_indptr[i] + (A_indptr[i + 1] - A_indptr[i])],\n            )\n            T.writes(B[i])\n            with T.block(\"rowsum_init\"):\n                T.reads()\n                T.writes(B[i])\n                B[i] = T.float32(0)\n            for k in T.serial(A_indptr[i + 1] - A_indptr[i]):\n                with T.block():\n                    T.reads(A_indptr[i], A_data[A_indptr[i] + k], B[i])\n                    T.writes(B[i])\n                    A_data_local = T.alloc_buffer([819], dtype=\"float32\", scope=\"local\")\n                    with T.block(\"A_data_cache_read\"):\n                        T.reads(A_indptr[i], A_data[A_indptr[i] + k])\n                        T.writes(A_data_local[A_indptr[i] + k])\n                        A_data_local[A_indptr[i] + k] = A_data[A_indptr[i] + k]\n                    with T.block(\"rowsum_inner\"):\n                        T.reads(B[i], A_indptr[i], A_data[A_indptr[i] + k])\n                        T.writes(B[i])\n                        B[i] = B[i] + A_data_local[A_indptr[i] + k]\n\n\n@T.prim_func\ndef compacted_sparse_read_cache(\n    A_data: T.Buffer[(819,), \"float32\"],\n    B: T.Buffer[(128,), \"float32\"],\n    A_indptr: T.Buffer[(129,), \"int32\"],\n    A_indices: T.Buffer[(819,), \"int32\"],\n) -> None:\n    for i in T.serial(128):\n        with T.block(\"rowsum_outer\"):\n            T.reads(\n                A_indptr[i : i + 1],\n                A_data[A_indptr[i] + 0 : A_indptr[i] + 0 + (A_indptr[i + 1] - A_indptr[i])],\n            )\n            T.writes(B[i])\n            with T.block(\"rowsum_init\"):\n                T.reads()\n                T.writes(B[i])\n                B[i] = T.float32(0)\n            for k in T.serial(A_indptr[i + 1] - A_indptr[i]):\n                with T.block():\n                    T.reads(A_indptr[i], A_data[A_indptr[i] + k], B[i])\n                    T.writes(B[i])\n                    A_data_local = T.alloc_buffer([1], dtype=\"float32\", scope=\"local\")\n                    with T.block(\"A_data_cache_read\"):\n                        T.reads(A_indptr[i], A_data[A_indptr[i] + k])\n                        T.writes(A_data_local[T.min(A_indptr[i] + k, 0)])\n                        A_data_local[T.min(A_indptr[i] + k, 0)] = A_data[A_indptr[i] + k]\n                    with T.block(\"rowsum_inner\"):\n                        T.reads(B[i], A_indptr[i], A_data[A_indptr[i] + k])\n                        T.writes(B[i])\n                        B[i] = B[i] + A_data_local[T.min(A_indptr[i] + k, 0)]\n\n\n@T.prim_func\ndef narrow_shape(A: T.Buffer[(10,), \"float32\"], B: T.Buffer[(10,), \"float32\"]) -> None:\n    B_cache = T.alloc_buffer(10, \"float32\")\n    for j in T.serial(3):\n        for k in T.serial(4):\n            with T.block(\"B_cache\"):\n                T.where(j * 4 + k < 10)\n                B_cache[j * 4 + k] = B[j]\n    for i in T.serial(10):\n        A[i] = B_cache[i] + T.float32(1)\n\n\n@T.prim_func\ndef compacted_narrow_shape(A: T.Buffer[(10,), \"float32\"], B: T.Buffer[(10,), \"float32\"]) -> None:\n    # body\n    # with T.block(\"root\")\n    B_cache = T.alloc_buffer([10], dtype=\"float32\")\n    for j, k in T.grid(3, 4):\n        with T.block(\"B_cache\"):\n            T.where(j * 4 + k < 10)\n            T.reads(B[j])\n            T.writes(B_cache[j * 4 + k])\n            B_cache[j * 4 + k] = B[j]\n    for i in T.serial(10):\n        A[i] = B_cache[i] + T.float32(1)\n\n\ndef test_elementwise():\n    _check(elementwise_func, compacted_elementwise_func)\n\n\ndef test_unschedulable_block():\n    _check(unschedulable_func, unschedulable_func)  # changes nothing\n\n\ndef test_param_access():\n    _check(param_buffer_access_func, param_buffer_access_func)  # changes nothing\n\n\ndef test_shared_mem():\n    _check(shared_mem_func, compacted_shared_mem_func)\n\n\ndef test_warp_mem():\n    _check(warp_mem_func, compacted_warp_mem_func)\n\n\ndef test_symbolic():\n    _check(symbolic_func, compacted_symbolic_func)\n\n\ndef test_complex():\n    _check(complex_func, compacted_complex_func)\n\n\ndef test_match_buffer():\n    _check(match_buffer_func, compacted_match_buffer_func)\n\n\ndef test_lower_te():\n    x = te.placeholder((1,))\n    y = te.compute((1,), lambda i: x[i] + 2)\n    s = te.create_schedule(y.op)\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n    mod = tvm.tir.transform.CompactBufferAllocation()(orig_mod)\n    tvm.ir.assert_structural_equal(mod, orig_mod)  # CompactBufferAllocation should do nothing on TE\n\n\ndef test_storage_align():\n    _check(storage_align_func, compacted_storage_align_func)\n\n\ndef test_padding_pattern():\n    _check(padding_pattern_func, compacted_padding_pattern_func)\n\n\ndef test_padding_pattern_inlined():\n    _check(padding_pattern_inlined, compacted_padding_pattern_inlined)\n\n\ndef test_mem_access_in_branch_func():\n    _check(mem_access_in_branch_func, compacted_mem_access_in_branch_func)\n\n\ndef test_opaque_access_annotated_func():\n    _check(opaque_access_annotated_func, compacted_opaque_access_annotated_func)\n\n\ndef test_sparse_read_cache():\n    _check(sparse_read_cache, compacted_sparse_read_cache)\n\n\ndef test_narrow_shape():\n    _check(narrow_shape, compacted_narrow_shape)\n\n\ndef test_compact_with_let_binding():\n    @T.prim_func\n    def func_with_let_binding():\n        A = T.alloc_buffer((64, 8), \"float32\")\n        B = T.alloc_buffer((64, 8), \"float32\")\n        C = T.alloc_buffer((8, 8), \"float32\")\n        for rk in range(64):\n            for rii, rjj in T.grid(8, 8):\n                C[rii, rjj] = T.float32(0)\n            for riijj in T.serial(8 * 8):\n                rii: T.int32 = riijj // 8\n                rjj: T.int32 = riijj % 8\n                C[rii, rjj] += A[rk, rii] * B[rk, rjj]\n\n    _check(func_with_let_binding, func_with_let_binding)\n\n    @T.prim_func\n    def func_with_non_index_let_binding():\n        A = T.alloc_buffer((64), \"float32\")\n        x1 = T.call_extern(\"get\", dtype=\"float16\")\n        x2 = T.call_extern(\"get\", dtype=\"float32\")\n        x3 = T.call_extern(\"get\", dtype=\"float64\")\n        x4 = T.call_extern(\"get\", dtype=\"uint8\")\n        x5 = T.call_extern(\"get\", dtype=\"int32x16\")\n        x6 = T.call_extern(\"get\", dtype=\"handle\")\n        x7 = T.call_extern(\"get\", dtype=\"\")\n        for rk in range(64):\n            A[rk] = T.call_extern(\"load_ptr\", x1, x2, x3, x4, x5, x6, x7, dtype=\"float32\")\n\n    _check(func_with_non_index_let_binding, func_with_non_index_let_binding)\n\n\ndef test_compact_spatial_tiled_pad_and_pooling():\n    @T.prim_func\n    def spatial_tiled_pad_and_pooling(\n        X: T.Buffer[(64, 112, 112), \"int32\"], Y: T.Buffer[(64, 56, 56), \"int32\"]\n    ) -> None:\n        for h_o, w_o in T.grid(14, 14):\n            with T.block():\n                X_cache = T.alloc_buffer([112, 112, 64], dtype=\"int32\")\n                for ax0, ax1, ax2 in T.grid(64, 9, 9):\n                    with T.block(\"cache\"):\n                        T.where(1 <= h_o * 8 + ax1 and 1 <= w_o * 8 + ax2)\n                        T.reads(X[ax0, h_o * 8 - 1 + ax1, w_o * 8 - 1 + ax2])\n                        T.writes(X_cache[h_o * 8 - 1 + ax1, w_o * 8 - 1 + ax2, ax0])\n                        X_cache[h_o * 8 - 1 + ax1, w_o * 8 - 1 + ax2, ax0] = X[\n                            ax0, h_o * 8 - 1 + ax1, w_o * 8 - 1 + ax2\n                        ]\n                for h_i, w_i, kh, kw, c in T.grid(4, 4, 3, 3, 64):\n                    with T.block(\"compute\"):\n                        T.reads(\n                            X_cache[(h_o * 4 + h_i) * 2 + kh - 1, (w_o * 4 + w_i) * 2 + kw - 1, c]\n                        )\n                        T.writes(Y[h_o * 4 + h_i, w_o * 4 + w_i, c])\n                        if kh == 0 and kw == 0:\n                            Y[h_o * 4 + h_i, w_o * 4 + w_i, c] = 0\n                        Y[h_o * 4 + h_i, w_o * 4 + w_i, c] = T.max(\n                            Y[h_o * 4 + h_i, w_o * 4 + w_i, c],\n                            T.if_then_else(\n                                T.likely(1 <= (h_o * 4 + h_i) * 2 + kh, dtype=\"bool\")\n                                and T.likely((h_o * 4 + h_i) * 2 + kh < 113, dtype=\"bool\")\n                                and T.likely(1 <= (w_o * 4 + w_i) * 2 + kw, dtype=\"bool\")\n                                and T.likely((w_o * 4 + w_i) * 2 + kw < 113, dtype=\"bool\"),\n                                X_cache[\n                                    (h_o * 4 + h_i) * 2 + kh - 1,\n                                    (w_o * 4 + w_i) * 2 + kw - 1,\n                                    c,\n                                ],\n                                0,\n                                dtype=\"int32\",\n                            ),\n                        )\n\n    @T.prim_func\n    def compacted_spatial_tiled_pad_and_pooling(\n        X: T.Buffer[(64, 112, 112), \"int32\"], Y: T.Buffer[(64, 56, 56), \"int32\"]\n    ) -> None:\n        for h_o, w_o in T.grid(14, 14):\n            with T.block():\n                T.reads(X[0:64, h_o * 8 - 1 : h_o * 8 + 8, w_o * 8 - 1 : w_o * 8 + 8])\n                T.writes(Y[h_o * 4 : h_o * 4 + 4, w_o * 4 : w_o * 4 + 4, 0:64])\n                X_cache = T.alloc_buffer([9, 9, 64], dtype=\"int32\")\n                for ax0, ax1, ax2 in T.grid(64, 9, 9):\n                    with T.block(\"cache\"):\n                        T.where(1 <= h_o * 8 + ax1 and 1 <= w_o * 8 + ax2)\n                        T.reads(X[ax0, h_o * 8 + ax1 - 1, w_o * 8 + ax2 - 1])\n                        T.writes(\n                            X_cache[\n                                h_o * 8 + ax1 - T.max(0, h_o * 8 - 1) - 1,\n                                w_o * 8 + ax2 - T.max(0, w_o * 8 - 1) - 1,\n                                ax0,\n                            ]\n                        )\n                        X_cache[\n                            h_o * 8 + ax1 - T.max(0, h_o * 8 - 1) - 1,\n                            w_o * 8 + ax2 - T.max(0, w_o * 8 - 1) - 1,\n                            ax0,\n                        ] = X[ax0, h_o * 8 + ax1 - 1, w_o * 8 + ax2 - 1]\n                for h_i, w_i, kh, kw, c in T.grid(4, 4, 3, 3, 64):\n                    with T.block(\"compute\"):\n                        T.reads(\n                            X_cache[\n                                h_o * 8 + h_i * 2 + kh - T.max(0, h_o * 8 - 1) - 1,\n                                w_o * 8 + w_i * 2 + kw - T.max(0, w_o * 8 - 1) - 1,\n                                c,\n                            ]\n                        )\n                        T.writes(Y[h_o * 4 + h_i, w_o * 4 + w_i, c])\n                        if kh == 0 and kw == 0:\n                            Y[h_o * 4 + h_i, w_o * 4 + w_i, c] = 0\n                        Y[h_o * 4 + h_i, w_o * 4 + w_i, c] = T.max(\n                            Y[h_o * 4 + h_i, w_o * 4 + w_i, c],\n                            T.if_then_else(\n                                T.likely(1 <= h_o * 8 + h_i * 2 + kh, dtype=\"bool\")\n                                and T.likely(1 <= w_o * 8 + w_i * 2 + kw, dtype=\"bool\"),\n                                X_cache[\n                                    h_o * 8 + h_i * 2 + kh - T.max(0, h_o * 8 - 1) - 1,\n                                    w_o * 8 + w_i * 2 + kw - T.max(0, w_o * 8 - 1) - 1,\n                                    c,\n                                ],\n                                0,\n                                dtype=\"int32\",\n                            ),\n                        )\n\n    _check(spatial_tiled_pad_and_pooling, compacted_spatial_tiled_pad_and_pooling)\n\n\ndef test_complex_case_1():\n    \"\"\"Meta-schedule matmul case for compact shared A, B matrix\"\"\"\n\n    # fmt: off\n    @T.prim_func\n    def func(A: T.Buffer[(960, 770), \"float32\"], B: T.Buffer[(770, 2304), \"float32\"], C: T.Buffer[(960, 2304), \"float32\"]) -> None:\n        for bx in T.thread_binding(144, thread=\"blockIdx.x\"):\n            for vx in T.thread_binding(2, thread=\"vthread.x\"):\n                for tx_p in T.thread_binding(256, thread=\"threadIdx.x\"):\n                    with T.block():\n                        for k_0 in T.serial(193):\n                            with T.block():\n                                A_shared = T.alloc_buffer([960, 770], dtype=\"float32\", scope=\"shared\")\n                                B_shared = T.alloc_buffer([770, 2304], dtype=\"float32\", scope=\"shared\")\n                                for _u in T.serial(1):\n                                    for tx in T.thread_binding(256, thread=\"threadIdx.x\"):\n                                        for vec in T.vectorized(3):\n                                            with T.block(\"A_shared\"):\n                                                T.where(bx // 18 * 128 + ((_u * 256 + tx) * 3 + vec) // 4 < 960 and k_0 * 4 + ((_u * 256 + tx) * 3 + vec) % 4 < 770 and (_u * 256 + tx) * 3 + vec < 512)\n                                                A_shared[bx // 18 * 128 + (_u * 768 + tx * 3 + vec) // 4, k_0 * 4 + (_u * 768 + tx * 3 + vec) % 4] = A[bx // 18 * 128 + (_u * 768 + tx * 3 + vec) // 4, k_0 * 4 + (_u * 768 + tx * 3 + vec) % 4]\n                                for _u in T.serial(1):\n                                    for tx in T.thread_binding(256, thread=\"threadIdx.x\"):\n                                        for vec in T.vectorized(4):\n                                            with T.block(\"B_shared\"):\n                                                T.where(k_0 * 4 + ((_u * 256 + tx) * 4 + vec) // 128 < 770 and (_u * 256 + tx) * 4 + vec < 512)\n                                                B_shared[k_0 * 4 + (_u * 1024 + tx * 4 + vec) // 128, bx % 18 * 128 + (_u * 1024 + tx * 4 + vec) % 128] = B[k_0 * 4 + (_u * 1024 + tx * 4 + vec) // 128, bx % 18 * 128 + (_u * 1024 + tx * 4 + vec) % 128]\n                                for k_1, i_3, j_3, k_2, i_4, j_4 in T.grid(1, 8, 1, 4, 2, 2):\n                                    with T.block(\"update_update\"):\n                                        C[(((bx // 18 + 0) * 8 + tx_p // 32) * 8 + i_3) * 2 + i_4, ((bx % 18 * 2 + vx % 2) * 32 + tx_p % 32 + j_3) * 2 + j_4] = C[(((bx // 18 + 0) * 8 + tx_p // 32) * 8 + i_3) * 2 + i_4, ((bx % 18 * 2 + vx % 2) * 32 + tx_p % 32 + j_3) * 2 + j_4] + A_shared[(((bx // 18 + 0) * 8 + tx_p // 32) * 8 + i_3) * 2 + i_4, (k_0 + k_1) * 4 + k_2] * B_shared[(k_0 + k_1) * 4 + k_2, ((bx % 18 * 2 + vx % 2) * 32 + tx_p % 32 + j_3) * 2 + j_4]\n\n    @T.prim_func\n    def compacted_func(A: T.Buffer[(960, 770), \"float32\"], B: T.Buffer[(770, 2304), \"float32\"], C: T.Buffer[(960, 2304), \"float32\"]) -> None:\n        for bx in T.thread_binding(144, thread=\"blockIdx.x\"):\n            for vx in T.thread_binding(2, thread=\"vthread.x\"):\n                for tx_p in T.thread_binding(256, thread=\"threadIdx.x\"):\n                    with T.block():\n                        for k_0 in T.serial(193):\n                            with T.block():\n                                A_shared = T.alloc_buffer([128, 4], dtype=\"float32\", scope=\"shared\")\n                                B_shared = T.alloc_buffer([4, 128], dtype=\"float32\", scope=\"shared\")\n                                for v_u in T.serial(1):\n                                    for tx in T.thread_binding(256, thread=\"threadIdx.x\"):\n                                        for vec in T.vectorized(3):\n                                            with T.block(\"A_shared\"):\n                                                T.where(bx // 18 * 128 + (tx * 3 + vec) // 4 < 960 and k_0 * 4 + (tx * 3 + vec) % 4 < 770 and tx * 3 + vec < 512)\n                                                A_shared[(tx * 3 + vec) // 4, (tx * 3 + vec) % 4] = A[bx // 18 * 128 + (tx * 3 + vec) // 4, k_0 * 4 + (tx * 3 + vec) % 4]\n                                for v_u in T.serial(1):\n                                    for tx in T.thread_binding(256, thread=\"threadIdx.x\"):\n                                        for vec in T.vectorized(4):\n                                            with T.block(\"B_shared\"):\n                                                T.where(k_0 * 4 + tx // 32 < 770 and tx * 4 + vec < 512)\n                                                B_shared[tx // 32, tx % 32 * 4 + vec] = B[k_0 * 4 + tx // 32, bx % 18 * 128 + tx % 32 * 4 + vec]\n                                for k_1, i_3, j_3, k_2, i_4, j_4 in T.grid(1, 8, 1, 4, 2, 2):\n                                    with T.block(\"update_update\"):\n                                        C[bx // 18 * 128 + tx_p // 32 * 16 + i_3 * 2 + i_4, bx % 18 * 128 + vx * 64 + tx_p % 32 * 2 + j_4] = C[bx // 18 * 128 + tx_p // 32 * 16 + i_3 * 2 + i_4, bx % 18 * 128 + vx * 64 + tx_p % 32 * 2 + j_4] + A_shared[tx_p // 32 * 16 + i_3 * 2 + i_4, k_2] * B_shared[k_2, vx * 64 + tx_p % 32 * 2 + j_4]\n    # fmt: on\n\n    _check(func, compacted_func)\n\n\ndef test_compact_dependent_buffer_indices():\n    \"\"\"Check the upper bound on different indices could be independently estimated.\"\"\"\n\n    @T.prim_func\n    def diagonal_access():\n        for i in range(8):\n            with T.block():\n                A = T.alloc_buffer((256, 256), \"float32\")\n                for j, k in T.grid(8, 8):\n                    with T.block():\n                        T.where(j * 8 + k < 60)\n                        A[i * 64 + j * 8 + k, i * 64 + j * 8 + k] = 1.0\n\n    @T.prim_func\n    def diagonal_access_compacted() -> None:\n        for i in T.serial(8):\n            with T.block():\n                A = T.alloc_buffer([60, 60], dtype=\"float32\")\n                for j, k in T.grid(8, 8):\n                    with T.block():\n                        T.where(j * 8 + k < 60)\n                        A[j * 8 + k, j * 8 + k] = 1.0\n\n    _check(diagonal_access, diagonal_access_compacted)\n\n\ndef test_compact_dependent_buffer_indices_of_packed_matmul():\n    \"\"\"Check the outer dimension of the packed M-dim should be compacted to 1 wrt split condition.\"\"\"\n\n    @T.prim_func\n    def nonuniform_packed_matmul_write_cache(\n        A: T.Buffer[(1020, 64), \"float32\"],\n        B: T.Buffer[(1000, 64), \"float32\"],\n        C: T.Buffer[(1020, 1000), \"float32\"],\n    ):\n        for i0, i1 in T.grid(4, 1):\n            with T.block():\n                C_local2 = T.alloc_buffer([4, 1, 16, 1000, 16], dtype=\"float32\", scope=\"local\")\n                C_local1 = T.alloc_buffer([1020, 1000], dtype=\"float32\", scope=\"local\")\n                for ax0, ax1, ax2 in T.grid(255, 1000, 64):\n                    with T.block(\"matmul\"):\n                        if ax2 == 0:\n                            C_local1[i0 * 255 + ax0, ax1] = 0\n                        C_local1[i0 * 255 + ax0, ax1] = (\n                            C_local1[i0 * 255 + ax0, ax1] + A[i0 * 255 + ax0, ax2] * B[ax1, ax2]\n                        )\n                for ax0, ax1 in T.grid(255, 1000):\n                    with T.block(\"st1\"):\n                        C_local2[\n                            (i0 * 255 + ax0) // 255,\n                            0,\n                            (i0 * 255 + ax0) % 255 // 16,\n                            ax1,\n                            (i0 * 255 + ax0) % 255 % 16,\n                        ] = C_local1[i0 * 255 + ax0, ax1]\n                for ax0, ax1, ax2 in T.grid(16, 16, 1000):\n                    with T.block(\"st2\"):\n                        T.where(ax0 * 16 + ax1 < 255)\n                        C[i0 * 255 + (ax0 * 16 + ax1), i1 * 1000 + ax2] = C_local2[\n                            (i0 * 255 + ax0 * 16 + ax1) // 255,\n                            0,\n                            (i0 * 255 + ax0 * 16 + ax1) % 255 // 16,\n                            i1 * 1000 + ax2,\n                            (i0 * 255 + ax0 * 16 + ax1) % 255 % 16,\n                        ]\n\n    @T.prim_func\n    def nonuniform_packed_matmul_write_cache_compacted(\n        A: T.Buffer[(1020, 64), \"float32\"],\n        B: T.Buffer[(1000, 64), \"float32\"],\n        C: T.Buffer[(1020, 1000), \"float32\"],\n    ) -> None:\n        for i0, i1 in T.grid(4, 1):\n            with T.block():\n                C_local2 = T.alloc_buffer([1, 1, 15, 1000, 16], dtype=\"float32\", scope=\"local\")\n                C_local1 = T.alloc_buffer([255, 1000], dtype=\"float32\", scope=\"local\")\n                for ax0, ax1, ax2 in T.grid(255, 1000, 64):\n                    with T.block(\"matmul\"):\n                        if ax2 == 0:\n                            C_local1[ax0, ax1] = 0\n                        C_local1[ax0, ax1] = (\n                            C_local1[ax0, ax1] + A[i0 * 255 + ax0, ax2] * B[ax1, ax2]\n                        )\n                for ax0, ax1 in T.grid(255, 1000):\n                    with T.block(\"st1\"):\n                        C_local2[0, 0, ax0 // 16, ax1, ax0 % 16] = C_local1[ax0, ax1]\n                for ax0, ax1, ax2 in T.grid(16, 16, 1000):\n                    with T.block(\"st2\"):\n                        T.where(ax0 * 16 + ax1 < 255)\n                        C[i0 * 255 + ax0 * 16 + ax1, ax2] = C_local2[\n                            (ax0 * 16 + ax1) // 255,\n                            0,\n                            (ax0 * 16 + ax1) % 255 // 16,\n                            ax2,\n                            (ax0 * 16 + ax1) % 255 % 16,\n                        ]\n\n    _check(nonuniform_packed_matmul_write_cache, nonuniform_packed_matmul_write_cache_compacted)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_convert_blocks_to_opaque.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import tir, te\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.ConvertBlocksToOpaque()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed)\n\n\n@T.prim_func\ndef elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer((16, 16), \"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    vi = T.axis.S(16, i)\n                    vj = T.axis.S(16, j)\n                    B[vi, vj] = A[vi, vj] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    vi = T.axis.S(16, i)\n                    vj = T.axis.S(16, j)\n                    C[vi, vj] = B[vi, vj] * 2.0\n\n\n@T.prim_func\ndef substituted_elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer([16, 16], \"float32\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads([A[i, j]])\n                    T.writes([B[i, j]])\n                    B[i, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads([B[i, j]])\n                    T.writes([C[i, j]])\n                    C[i, j] = B[i, j] * 2.0\n\n\ndef test_elementwise():\n    _check(elementwise_func, substituted_elementwise_func)\n\n\ndef test_lower_te():\n    x = te.placeholder((1,))\n    y = te.compute((1,), lambda i: x[i] + 2)\n    s = te.create_schedule(y.op)\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n    mod = tvm.tir.transform.ConvertBlocksToOpaque()(orig_mod)\n    tvm.ir.assert_structural_equal(mod, orig_mod)  # ConvertBlocksToOpaque should do nothing on TE\n\n\nclass TestErrorIfPredicateUsesBlockVariables(tvm.testing.CompareBeforeAfter):\n    transform = tvm.tir.transform.ConvertBlocksToOpaque()\n\n    def before(A: T.Buffer[8, \"int32\"]):\n        for i in T.serial(8):\n            with T.block():\n                vi = T.axis.remap(\"S\", [i])\n                T.where(vi < 6)\n                T.evaluate(0)\n\n    expected = tvm.TVMError\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_convert_for_loops_serial.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\n\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\n\n# fmt: off\n@T.prim_func\ndef fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2(placeholder_30: T.handle, placeholder_31: T.handle, placeholder_32: T.handle, T_cast_8: T.handle) -> None:\n    # function attr dict\n    T.func_attr({\"global_symbol\": \"fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2\", \"tir.noalias\": True})\n    placeholder_33 = T.match_buffer(placeholder_30, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_34 = T.match_buffer(placeholder_31, [3072], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    placeholder_35 = T.match_buffer(placeholder_32, [16], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n    T_cast_9 = T.match_buffer(T_cast_8, [12544], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n    # body\n    PaddedInput_3 = T.decl_buffer([150528], \"int16\")\n    for i0_i1_fused_3 in T.parallel(0, 28):\n        for i2_3, i3_3 in T.grid(28, 192):\n            PaddedInput_3[(((i0_i1_fused_3*5376) + (i2_3*192)) + i3_3) ] = placeholder_33[(((i0_i1_fused_3*5376) + (i2_3*192)) + i3_3)]\n    for ax0_ax1_fused_ax2_fused_3 in T.parallel(0, 784):\n        for ax3_2 in T.serial(0, 16):\n            Conv2dOutput_3 = T.decl_buffer([1], \"int32\")\n            Conv2dOutput_3[0] = 0\n            for rc_3 in T.serial(0, 192):\n                Conv2dOutput_3[0] = (Conv2dOutput_3[0] + (T.cast(PaddedInput_3[((ax0_ax1_fused_ax2_fused_3*192) + rc_3)], \"int32\")*T.cast(placeholder_34[((rc_3*16) + ax3_2)], \"int32\")))\n            T_cast_9[((ax0_ax1_fused_ax2_fused_3*16) + ax3_2)] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_3[0] + placeholder_35[ax3_2]), 1764006585, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n# fmt: on\n\n\ndef test_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2():\n    primfunc = fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2\n    mod = tvm.IRModule.from_expr(primfunc)\n    mod = tvm.tir.transform.ConvertForLoopsToSerial()(mod)\n\n    def verify_serial_loops(stmt):\n        if isinstance(stmt, tvm.tir.For):\n            assert stmt.kind == tvm.tir.ForKind.SERIAL\n\n    for _, primfunc in mod.functions.items():\n        stmt_functor.post_order_visit(primfunc.body, verify_serial_loops)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_coproc_sync.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n# register the ops\ntvm.ir.register_op_attr(\"tir.cop.coproc_sync\", \"TGlobalSymbol\", \"coproc_sync\")\ntvm.ir.register_op_attr(\"tir.cop.coproc_read_barrier\", \"TGlobalSymbol\", \"coproc_readb\")\ntvm.ir.register_op_attr(\"tir.cop.coproc_write_barrier\", \"TGlobalSymbol\", \"coproc_writeb\")\ntvm.ir.register_op_attr(\"tir.cop.coproc_dep_push\", \"TGlobalSymbol\", \"coproc_dep_push\")\ntvm.ir.register_op_attr(\"tir.cop.coproc_dep_pop\", \"TGlobalSymbol\", \"coproc_dep_pop\")\n\n\ndef test_coproc_sync():\n    @tvm.register_func(\"tvm.info.mem.global.cache\")\n    def meminfo_cache():\n        return tvm.ir.make_node(\n            \"MemoryInfo\",\n            unit_bits=8,\n            max_simd_bits=32,\n            max_num_bits=128,\n            head_address=tvm.tir.call_extern(\"handle\", \"global_cache\"),\n        )\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n    cp = te.thread_axis((0, 1), \"cop\")\n    A = ib.allocate(\"float32\", 128, name=\"A\", scope=\"global.cache\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        A[i] = A[i] + 1\n        with ib.for_range(0, 8, name=\"k\") as k:\n            with ib.for_range(0, 10, name=\"j\") as j:\n                ib.scope_attr(cp, \"coproc_scope\", 1)\n                A[j] = A[j + k * 10] + 2\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], stmt))\n    stmt = tvm.tir.transform.CoProcSync()(mod)[\"main\"].body\n\n    body = stmt.body.body\n    blist = tvm.tir.stmt_list(body)\n\n    assert blist[1].value.op.same_as(tvm.ir.Op.get(\"tir.cop.coproc_read_barrier\"))\n    assert blist[1].value.args[3].value == 80\n    assert blist[-2].value.op.same_as(tvm.ir.Op.get(\"tir.cop.coproc_sync\"))\n    assert blist[-1].value.op.same_as(tvm.ir.Op.get(\"tir.cop.coproc_write_barrier\"))\n    assert blist[-1].value.args[3].value == 10\n\n\ndef test_coproc_sync2():\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n    cp = te.thread_axis((0, 1), \"cop\")\n    ty = te.thread_axis(\"cthread\")\n    A = ib.allocate(\"float32\", 128, name=\"A\")\n    ib.scope_attr(ty, \"virtual_thread\", 2)\n    with ib.new_scope():\n        ib.scope_attr(cp, \"coproc_scope\", 2)\n        A[ty] = 0.0\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.new_scope():\n            ib.scope_attr(cp, \"coproc_scope\", 1)\n            A[ty] = 1.0\n        with ib.new_scope():\n            ib.scope_attr(cp, \"coproc_scope\", 2)\n            A[ty] = 1.0\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], stmt))\n    stmt = tvm.tir.transform.CoProcSync()(mod)[\"main\"].body\n\n\ndef test_coproc_sync3():\n    def __check_list(tvm_array, py_list):\n        for ti, li in zip(tvm_array, py_list):\n            if ti.value != li:\n                return False\n        return True\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.size_var(\"n\")\n    cp = te.thread_axis((0, 1), \"cop\")\n    A = ib.allocate(\"float32\", 128, name=\"A\", scope=\"global.cache\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, n, name=\"i\") as j:\n            with ib.new_scope():\n                ib.scope_attr(cp, \"coproc_scope\", 1)\n                A[i] = 1.0\n            with ib.new_scope():\n                ib.scope_attr(cp, \"coproc_scope\", 2)\n                A[i] = 1.0\n    with ib.new_scope():\n        ib.scope_attr(cp, \"coproc_scope\", 3)\n        A[0] = 0.0\n\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], stmt))\n    stmt = tvm.tir.transform.CoProcSync()(mod)[\"main\"].body\n\n    slist = tvm.tir.stmt_list(stmt[0].body)\n    push_st = slist[2]\n    slist = tvm.tir.stmt_list(slist[-1])\n    pop_st = slist[0].body[0]\n\n    assert push_st.value.op.same_as(tvm.ir.Op.get(\"tir.cop.coproc_dep_push\"))\n    assert __check_list(push_st.value.args, [2, 3])\n    assert pop_st.value.op.same_as(tvm.ir.Op.get(\"tir.cop.coproc_dep_pop\"))\n    assert __check_list(pop_st.value.args, [2, 3])\n\n\nif __name__ == \"__main__\":\n    test_coproc_sync()\n    test_coproc_sync2()\n    test_coproc_sync3()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_decorate_device_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_decorate_device():\n    x = te.var(\"x\")\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x)))\n\n    stmt = tvm.tir.transform.DecorateDeviceScope()(mod)[\"main\"].body\n    assert stmt.attr_key == \"device_scope\"\n\n\nif __name__ == \"__main__\":\n    test_decorate_device()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_extract_constants.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\nimport tvm\nfrom tvm import tir\nfrom tvm.script import tir as T\nimport tvm.testing\n\n\n@tvm.script.ir_module\nclass Module4:\n    @T.prim_func\n    def constant1(a: T.handle) -> None:\n        A = T.match_buffer(a, (10), \"int32\")\n        B = T.alloc_buffer((10), \"int32\")\n        K_data = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n        K = T.buffer_decl(shape=(10), dtype=\"int32\", data=K_data)\n        for x in T.serial(0, 10):\n            B[x] = A[x] + K[x]\n\n    @T.prim_func\n    def constant2(a: T.handle) -> None:\n        A = T.match_buffer(a, (10), \"int32\")\n        B = T.alloc_buffer((10), \"int32\")\n        K_data = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n        K = T.buffer_decl(shape=(10), dtype=\"int32\", data=K_data)\n        for x in T.serial(0, 10):\n            B[x] = A[x] + K[x]\n\n    @T.prim_func\n    def constant3(a: T.handle) -> None:\n        A = T.match_buffer(a, (10), \"int32\")\n        B = T.alloc_buffer((10), \"int32\")\n        K_data = T.allocate_const([1, 2, 3, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n        K = T.buffer_decl(shape=(10), dtype=\"int32\", data=K_data)\n        for x in T.serial(0, 10):\n            B[x] = A[x] + K[x]\n\n\ndef test_const_extraction():\n    mod = tvm.tir.transform.ExtractPrimFuncConstants()(Module4)\n    constants = mod.attrs[\"constants\"]\n    assert len(constants) == 2\n\n    def _visit(stmt):\n        if isinstance(stmt, tvm.tir.AllocateConst):\n            assert np.array_equal(stmt.data.numpy(), constants[int(stmt.irmod_storage_idx)].numpy())\n\n    for n, f in mod.functions.items():\n        tvm.tir.stmt_functor.post_order_visit(f.body, _visit)\n\n    tvm.lower(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_flatten_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\nclass BaseCompare(tvm.testing.CompareBeforeAfter):\n    transform = tvm.transform.Sequential(\n        [\n            tvm.tir.transform.FlattenBuffer(),\n            tvm.tir.transform.Simplify(),\n        ]\n    )\n\n\nclass TestElementwise(BaseCompare):\n    \"\"\"2-d buffers are flattened to 1-d\"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        for i in T.serial(0, 16):\n            B_new = T.decl_buffer([1, 16], \"float32\")\n            for j in T.serial(0, 16):\n                B_new[0, j] = A[i, j] + 1.0\n            for j in T.serial(0, 16):\n                C[i, j] = B_new[0, j] * 2.0\n\n    def expected(A: T.Buffer[256, \"float32\"], C: T.Buffer[256, \"float32\"]):\n        T.preflattened_buffer(A, (16, 16), dtype=\"float32\", data=A.data)\n        T.preflattened_buffer(C, (16, 16), dtype=\"float32\", data=C.data)\n        for i in T.serial(0, 16):\n            B_new_data = T.allocate([16], \"float32\", scope=\"global\")\n            B_new = T.buffer_decl([16], \"float32\", scope=\"global\", data=B_new_data)\n            for j in T.serial(0, 16):\n                B_new[j] = A[((i * 16) + j)] + 1.0\n            for j in T.serial(0, 16):\n                C[((i * 16) + j)] = B_new[j] * 2.0\n\n\nclass TestElementwiseWithoutDeclBuffer(BaseCompare):\n    \"\"\"2-d buffers are flattened to 1-d\n\n    Like TestElementwise, but the TIR doesn't have the DeclBuffer\n    node.  The T.buffer_decl declaration applies only during the\n    parsing the TVMScript, and doesn't occur in the TIR itself.  In\n    this case, the allocation should be assumed to be targeting flat\n    memory, and should be flattened to a 1-d allocation.\n    \"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        for i in T.serial(0, 16):\n            B_new_data = T.allocate([1, 16], \"float32\", \"global\")\n            B_new = T.buffer_decl([1, 16], \"float32\", data=B_new_data)\n            for j in T.serial(0, 16):\n                B_new[0, j] = A[i, j] + 1.0\n            for j in T.serial(0, 16):\n                C[i, j] = B_new[0, j] * 2.0\n\n    def expected(A: T.Buffer[256, \"float32\"], C: T.Buffer[256, \"float32\"]):\n        T.preflattened_buffer(A, (16, 16), dtype=\"float32\", data=A.data)\n        T.preflattened_buffer(C, (16, 16), dtype=\"float32\", data=C.data)\n        for i in T.serial(0, 16):\n            B_new_data = T.allocate([16], \"float32\", \"global\")\n            B_new = T.buffer_decl(16, \"float32\", data=B_new_data)\n            for j in T.serial(0, 16):\n                B_new[j] = A[((i * 16) + j)] + 1.0\n            for j in T.serial(0, 16):\n                C[((i * 16) + j)] = B_new[j] * 2.0\n\n\nclass TestGPU(BaseCompare):\n    \"\"\"Buffer flattening may have indices based on GPU thread vars\"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        i0 = T.env_thread(\"blockIdx.x\")\n        i1 = T.env_thread(\"threadIdx.x\")\n        i2 = T.env_thread(\"vthread\")\n\n        T.launch_thread(i0, 4)\n        T.launch_thread(i1, 2)\n        T.launch_thread(i2, 2)\n        B = T.decl_buffer([1, 16], \"float32\", scope=\"local\")\n        for j in range(0, 16):\n            B[0, j] = A[i0 * 4 + i1 * 2 + i2, j] + 1.0\n        for j in range(0, 16):\n            C[i0 * 4 + i1 * 2 + i2, j] = B[0, j] * 2.0\n\n    def expected(A: T.Buffer[256, \"float32\"], C: T.Buffer[256, \"float32\"]):\n        T.preflattened_buffer(A, (16, 16), dtype=\"float32\", data=A.data)\n        T.preflattened_buffer(C, (16, 16), dtype=\"float32\", data=C.data)\n\n        i0 = T.env_thread(\"blockIdx.x\")\n        i1 = T.env_thread(\"threadIdx.x\")\n        i2 = T.env_thread(\"vthread\")\n\n        T.launch_thread(i0, 4)\n        T.launch_thread(i1, 2)\n        T.launch_thread(i2, 2)\n        B_data = T.allocate([16], \"float32\", scope=\"local\")\n        B = T.buffer_decl([16], \"float32\", scope=\"local\", data=B_data)\n        for j in range(0, 16):\n            B[j] = A[i0 * 64 + i1 * 32 + i2 * 16 + j] + 1.0\n        for j in range(0, 16):\n            C[i0 * 64 + i1 * 32 + i2 * 16 + j] = B[j] * 2.0\n\n\nclass TestSymbolic(BaseCompare):\n    \"\"\"Dynamically-sized arrrays are flattened\"\"\"\n\n    def before(a: T.handle, c: T.handle, n: T.int32, m: T.int32) -> None:\n        A = T.match_buffer(a, (n, m), \"float32\")\n        C = T.match_buffer(c, (n, m), \"float32\")\n\n        for i in range(0, n):\n            B = T.decl_buffer([m], \"float32\")\n            for j in range(0, m):\n                B[j] = A[i, j] + 1.0\n            for j in range(0, m):\n                C[i, j] = B[j] * 2.0\n\n    def expected(a: T.handle, c: T.handle, n: T.int32, m: T.int32) -> None:\n        A = T.match_buffer(a, n * m, \"float32\")\n        C = T.match_buffer(c, n * m, \"float32\")\n        T.preflattened_buffer(A, (n, m), \"float32\", data=A.data)\n        T.preflattened_buffer(C, (n, m), \"float32\", data=C.data)\n\n        for i in range(0, n):\n            B_data = T.allocate([m], \"float32\", scope=\"global\")\n            B = T.buffer_decl([m], \"float32\", scope=\"global\", data=B_data)\n            for j in range(0, m):\n                B[j] = A[i * m + j] + 1.0\n            for j in range(0, m):\n                C[i * m + j] = B[j] * 2.0\n\n\nclass TestMultiAlloc(BaseCompare):\n    \"\"\"If multiple allocations occur, all are flattened.\"\"\"\n\n    def before(A: T.Buffer[(4, 32), \"float32\"], D: T.Buffer[(4, 32), \"float32\"]):\n        for i, j in T.grid(4, 32):\n            B = T.decl_buffer((4, 32), \"float32\", scope=\"global\")\n            C = T.decl_buffer((4, 32), \"float32\", scope=\"global\")\n            B[i, j] = A[i, j] + 1.0\n            C[i, j] = A[i, j] + B[i, j]\n            D[i, j] = C[i, j] * 2.0\n\n    def expected(A: T.Buffer[128, \"float32\"], D: T.Buffer[128, \"float32\"]):\n        T.preflattened_buffer(A, (4, 32), \"float32\", data=A.data)\n        T.preflattened_buffer(D, (4, 32), \"float32\", data=D.data)\n\n        for i, j in T.grid(4, 32):\n            B_data = T.allocate([128], \"float32\", scope=\"global\")\n            B = T.buffer_decl([128], \"float32\", scope=\"global\", data=B_data)\n            C_data = T.allocate([128], \"float32\", scope=\"global\")\n            C = T.buffer_decl([128], \"float32\", scope=\"global\", data=C_data)\n            B[i * 32 + j] = A[i * 32 + j] + 1.0\n            C[i * 32 + j] = A[i * 32 + j] + B[i * 32 + j]\n            D[i * 32 + j] = C[i * 32 + j] * 2.0\n\n\nclass TestStrided(BaseCompare):\n    \"\"\"Indices for flattened buffers use the specified striding.\"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        for i0 in T.serial(4):\n            B = T.decl_buffer([4, 17], \"float32\")\n            B_1 = T.buffer_decl([4, 16], dtype=\"float32\", data=B.data, strides=[17, 1])\n            for i1, j in T.grid(4, 16):\n                B_1[i1, j] = A[i0 * 4 + i1, j] + 1.0\n            for i1, j in T.grid(4, 16):\n                C[i0 * 4 + i1, j] = B_1[i1, j] * 2.0\n\n    def expected(A: T.Buffer[256, \"float32\"], C: T.Buffer[256, \"float32\"]):\n        T.preflattened_buffer(A, [16, 16], dtype=\"float32\", data=A.data)\n        T.preflattened_buffer(C, [16, 16], dtype=\"float32\", data=C.data)\n        for i0 in T.serial(0, 4):\n            B_new_data = T.allocate([68], \"float32\", scope=\"global\")\n            B_new = T.buffer_decl([68], \"float32\", scope=\"global\", data=B_new_data)\n            for i1 in T.serial(0, 4):\n                for j in T.serial(0, 16):\n                    B_new[i1 * 17 + j] = A[i0 * 64 + i1 * 16 + j] + 1.0\n            for i1 in T.serial(0, 4):\n                for j in T.serial(0, 16):\n                    C[i0 * 64 + i1 * 16 + j] = B_new[i1 * 17 + j] * 2.0\n\n\nclass TestBoolean(BaseCompare):\n    \"\"\"Boolean buffers should be replaced by a backing int8 array\"\"\"\n\n    def before(A: T.Buffer[10, \"bool\"], B: T.Buffer[10, \"bool\"]) -> None:\n        for i0 in T.serial(10):\n            B[i0] = A[i0]\n\n    def expected(A: T.Buffer[10, \"int8\"], B: T.Buffer[10, \"int8\"]) -> None:\n        T.preflattened_buffer(A, [10], dtype=\"bool\", data=A.data)\n        T.preflattened_buffer(B, [10], dtype=\"bool\", data=B.data)\n        # body\n        for i0 in T.serial(10):\n            B[i0] = T.cast(T.cast(A[i0], \"bool\"), \"int8\")\n\n\nclass TestLowerTE(BaseCompare):\n    \"\"\"FlattenBuffer should do nothing on TE-based functions\"\"\"\n\n    def before(self):\n        x = te.placeholder((1,))\n        y = te.compute((1,), lambda i: x[i] + 2)\n        s = te.create_schedule(y.op)\n        mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n        return mod[\"main\"]\n\n    expected = before\n\n\nclass TestFlattenInsideBlock(BaseCompare):\n    \"\"\"Flattening access inside a block flattens the accessed region.\"\"\"\n\n    def before():\n        A = T.alloc_buffer([32, 32])\n        for i, j in T.grid(32, 32):\n            with T.block(\"block\"):\n                T.reads(A[i, j])\n                T.evaluate(A[i, j])\n\n    def expected():\n        A = T.alloc_buffer([1024])\n        for i, j in T.grid(32, 32):\n            with T.block(\"block\"):\n                T.reads(A[i * 32 + j])\n                T.evaluate(A[i * 32 + j])\n\n\nclass TestNoChangeTo2DPhysicalBuffer(BaseCompare):\n    \"\"\"Flattening preserves axis separators.\"\"\"\n\n    def before():\n        A = T.alloc_buffer([32, 32], axis_separators=[1])\n        for i, j in T.grid(32, 32):\n            T.evaluate(A[i, j])\n\n    expected = before\n\n\nclass TestFlattenAllocBufferWithAxisSeparators(BaseCompare):\n    \"\"\"Flattening preserves axis separators\"\"\"\n\n    def before():\n        A = T.alloc_buffer([2, 3, 5, 7, 11, 13], axis_separators=[3])\n        for i0, i1, i2, i3, i4, i5 in T.grid(2, 3, 5, 7, 11, 13):\n            T.evaluate(A[i0, i1, i2, i3, i4, i5])\n\n    def expected():\n        A = T.alloc_buffer([30, 1001], axis_separators=[1])\n        for i0, i1, i2, i3, i4, i5 in T.grid(2, 3, 5, 7, 11, 13):\n            T.evaluate(A[i0 * 15 + i1 * 5 + i2, i3 * 143 + i4 * 13 + i5])\n\n\nclass TestFlattenDeclBufferWithAxisSeparators(BaseCompare):\n    \"\"\"Flattening preserves axis separators\n\n    Like TestFlattenAllocBufferWithAxisSeparators, but the allocations\n    is done using Allocate/DeclBuffer, rather than through\n    BlockNode::alloc_buffers.\n    \"\"\"\n\n    def before():\n        A = T.decl_buffer([2, 3, 5, 7, 11, 13], axis_separators=[3])\n        for i0, i1, i2, i3, i4, i5 in T.grid(2, 3, 5, 7, 11, 13):\n            T.evaluate(A[i0, i1, i2, i3, i4, i5])\n\n    def expected():\n        A_data = T.allocate([30, 1001], dtype=\"float32\", scope=\"global\")\n        A = T.buffer_decl(\n            [30, 1001], dtype=\"float32\", scope=\"global\", axis_separators=[1], data=A_data\n        )\n        for i0, i1, i2, i3, i4, i5 in T.grid(2, 3, 5, 7, 11, 13):\n            T.evaluate(A[i0 * 15 + i1 * 5 + i2, i3 * 143 + i4 * 13 + i5])\n\n\ndef test_lower_2d_physical_memory():\n    \"\"\"Axis separators should preserve 2-d buffers through lowering.\n\n    A catch-all test to ensure that defining axis_separators is\n    sufficient to maintain non-flat buffer descriptions through all\n    lowering steps.\n    \"\"\"\n\n    # This test doesn't use CompareBeforeAfter, because the after step\n    # is not currently expressible in TVMScript.  This test can be\n    # re-written after https://github.com/apache/tvm/pull/12412.\n\n    @T.prim_func\n    def func():\n        buf = T.alloc_buffer(\n            [1, 1],\n            dtype=\"int32\",\n            scope=\"global\",\n            axis_separators=[1],\n        )\n        buf[0, 0] = 0\n\n    lowered = tvm.lower(func)[\"main\"]\n    assert isinstance(lowered.body, tvm.tir.Allocate)\n    assert list(lowered.body.extents) == [1, 1], (\n        \"Non-flat buffer allocations, \"\n        \"marked by axis_separators, \"\n        \"flattened to flat memory allocation.\"\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_helpers.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm.script import tir as T\nimport tvm.testing\n\n\ndef test_annotate_entry_func_single_primfunc():\n    @tvm.script.ir_module\n    class MockModule:\n        @T.prim_func\n        def func1(A: T.Buffer[(16,), \"float32\"]):\n            for i in T.serial(16):\n                if i == 5:\n                    if i == 5:\n                        A[i] = 0.0\n\n    mod = MockModule\n    assert mod\n    assert mod[\"func1\"].attrs is None\n    after = tvm.tir.transform.AnnotateEntryFunc()(mod)\n    assert (\n        after[\"func1\"].attrs\n        and \"tir.is_entry_func\" in after[\"func1\"].attrs\n        and after[\"func1\"].attrs[\"tir.is_entry_func\"]\n    )\n\n\n# Test module\n@tvm.script.ir_module\nclass MockModule:\n    @T.prim_func\n    def func1(A: T.Buffer[(16,), \"float32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                if i == 5:\n                    A[i] = 0.0\n\n    @T.prim_func\n    def func2(A: T.Buffer[(32,), \"float32\"]):\n        for i in T.serial(32):\n            if i == 15:\n                if i == 15:\n                    A[i] = 0.0\n\n\n@pytest.mark.xfail\ndef test_annotate_entry_func_multiple_primfunc():\n    mod = MockModule\n    assert mod\n    assert mod[\"func1\"].attrs is None\n    assert mod[\"func2\"].attrs is None\n    # This should fail\n    after = tvm.tir.transform.AnnotateEntryFunc()(mod)\n\n\ndef test_bind_target():\n    mod = MockModule\n    assert mod\n\n    target = tvm.target.Target(\"cuda\")\n    assert mod[\"func1\"].attrs is None\n    assert mod[\"func2\"].attrs is None\n    after = tvm.tir.transform.BindTarget(target)(mod)\n\n    assert after[\"func1\"].attrs and \"target\" in after[\"func1\"].attrs\n    assert after[\"func1\"].attrs[\"target\"] == target\n    assert after[\"func2\"].attrs and \"target\" in after[\"func2\"].attrs\n    assert after[\"func2\"].attrs[\"target\"] == target\n\n\ndef test_filter_primfunc():\n    mod = MockModule\n    assert mod\n    # Annotate each function for testing\n    mod[\"func1\"] = mod[\"func1\"].with_attr(\"temp\", \"test1\")\n    mod[\"func2\"] = mod[\"func2\"].with_attr(\"temp\", \"test2\")\n\n    # Test condition that does not filter out anything\n    def checker_filter_out_none(func: tvm.tir.PrimFunc):\n        return (func.attrs is not None) and (\"temp\" in func.attrs)\n\n    after = tvm.tir.transform.Filter(checker_filter_out_none)(mod)\n    assert len(after.functions) == 2\n    # Filtered functions should satisfy the given condition.\n    assert checker_filter_out_none(after[\"func1\"])\n    assert checker_filter_out_none(after[\"func2\"])\n\n    # Test condition that selectively filters out primfuncs\n    def checker_filter_out_one(func: tvm.tir.PrimFunc):\n        return (func.attrs is not None) and (\"temp\" in func.attrs) and func.attrs[\"temp\"] == \"test1\"\n\n    after = tvm.tir.transform.Filter(checker_filter_out_one)(mod)\n    assert len(after.functions) == 1\n    # Filtered functions should satisfy the given condition.\n    assert checker_filter_out_one(after[\"func1\"])\n\n    # Test condition that filters out everything\n    def checker_filter_out_both(func: tvm.tir.PrimFunc):\n        return (func.attrs is not None) and (\"invalid_attr\" in func.attrs)\n\n    after = tvm.tir.transform.Filter(checker_filter_out_both)(mod)\n    assert len(after.functions) == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_hoist_expression.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import tir\nimport tvm.testing\n\nfrom tvm.script import tir as T\nfrom tvm.tir.transform import HoistExpression, HoistedConditionals, HoistedLetBindings\n\n\nclass BaseBeforeAfter:\n    hoisted_conditionals = tvm.testing.parameter(HoistedConditionals.All)\n    hoisted_let_bindings = tvm.testing.parameter(HoistedLetBindings.All)\n\n    def test_hoist(self, hoisted_conditionals, hoisted_let_bindings):\n        before = self.before\n        before_mod = tvm.IRModule.from_expr(before)\n\n        config = {\n            \"tir.HoistExpression\": {\n                \"hoisted_conditionals\": hoisted_conditionals.value,\n                \"hoisted_let_bindings\": hoisted_let_bindings.value,\n            }\n        }\n\n        with tvm.transform.PassContext(config=config):\n            after_mod = tvm.tir.transform.HoistExpression()(before_mod)\n\n        after = after_mod[\"main\"]\n        expected = self.expected\n\n        try:\n            tvm.ir.assert_structural_equal(after, expected)\n        except ValueError as err:\n            script = tvm.IRModule({\"expected\": expected, \"after\": after, \"before\": before}).script()\n            raise ValueError(\n                f\"Function after simplification did not match expected:\\n{script}\"\n            ) from err\n\n\nclass TestHoistToTop(BaseBeforeAfter):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.IfElseStmt,\n        HoistedConditionals.All,\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(16,), \"float32\"], n: T.int32):\n        for i in T.serial(16):\n            if n != 0:\n                A[i] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(16,), \"float32\"], n: T.int32):\n        if n != 0:\n            for i in T.serial(16):\n                A[i] = 0.0\n\n\nclass TestSuppressHoistIfElse(BaseBeforeAfter):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.Never,\n        HoistedConditionals.IfElseExpr,\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(16,), \"float32\"], n: T.int32):\n        for i in T.serial(16):\n            if n != 0:\n                A[i] = 0.0\n\n    expected = before\n\n\nclass TestHoistBlockVar(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        i = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(i, 128)\n\n        for j in T.serial(16):\n            if i < 32:\n                A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        i = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(i, 128)\n\n        if i < 32:\n            for j in T.serial(16):\n                A[i, j] = 0.0\n\n\nclass TestSuppressHoistBlockVar(BaseBeforeAfter):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.All & ~HoistedConditionals.UsingBlockVar\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        thread_x = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(thread_x, 128)\n\n        for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            if i < 32:\n                for j in T.serial(16):\n                    A[i, j] = 0.0\n\n    expected = before\n\n\nclass TestHoistAcrossBlockVar(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        thread_x = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(thread_x, 128)\n\n        for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            if n == 0:\n                for j in T.serial(16):\n                    A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        thread_x = T.env_thread(\"threadIdx.x\")\n\n        if n == 0:\n            T.launch_thread(thread_x, 128)\n            for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                for j in T.serial(16):\n                    A[i, j] = 0.0\n\n\nclass TestSuppressHoistAcrossBlockVar(BaseBeforeAfter):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.All & ~HoistedConditionals.UsingBlockVar\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        thread_x = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(thread_x, 128)\n\n        for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            for j in T.serial(16):\n                if n == 0:\n                    A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(128, 16), \"float32\"], n: T.int32):\n        thread_x = T.env_thread(\"threadIdx.x\")\n\n        T.launch_thread(thread_x, 128)\n        if n == 0:\n            for i in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                for j in T.serial(16):\n                    A[i, j] = 0.0\n\n\nclass TestHoistToMiddle(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                if i < 3:\n                    A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 3:\n                for j in T.serial(4):\n                    A[i, j] = 0.0\n\n\nclass TestHoistWithLet(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                condition = i < 3\n                if condition:\n                    A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if condition:\n                for j in T.serial(4):\n                    A[i, j] = 0.0\n\n\nclass TestHoistDisableLet(BaseBeforeAfter):\n    \"\"\"As TestHoistWithLet, but forbid hoisting of LetStmt\n\n    Because the condition depends on the let binding, it should no\n    longer be hoisted.\n    \"\"\"\n\n    hoisted_let_bindings = tvm.testing.parameter(HoistedLetBindings.Never)\n\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                condition = i < 3\n                if condition:\n                    A[i, j] = 0.0\n\n    expected = before\n\n\nclass TestHoistIfElse(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                if i < 3:\n                    A[i, j] = 0.0\n                else:\n                    A[i, j] = 1.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 3:\n                for j in T.serial(4):\n                    A[i, j] = 0.0\n            else:\n                for j in T.serial(4):\n                    A[i, j] = 1.0\n\n\nclass TestHoistSequentialAssign(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"], B: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                if i < 3:\n                    A[i, j] = 0.0\n                    B[i, j] = 0.0\n                else:\n                    A[i, j] = 1.0\n                    B[i, j] = 1.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"], B: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 3:\n                for j in T.serial(4):\n                    A[i, j] = 0.0\n                    B[i, j] = 0.0\n            else:\n                for j in T.serial(4):\n                    A[i, j] = 1.0\n                    B[i, j] = 1.0\n\n\nclass TestHoistMultiIf(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                for k in T.serial(4):\n                    if j < 3:\n                        if i < 2:\n                            A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 2:\n                for j in T.serial(4):\n                    if j < 3:\n                        for k in T.serial(4):\n                            A[i, j] = 0.0\n\n\nclass TestHoistComplexConditional(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j, k in T.grid(4, 4, 4):\n            if j < 3 and i < 2:\n                A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 2:\n                for j in T.serial(4):\n                    if j < 3:\n                        for k in T.serial(4):\n                            A[i, j] = 0.0\n\n\nclass TestSuppressSplittingConditional(BaseBeforeAfter):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.All & ~HoistedConditionals.BooleanExpression\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j, k in T.grid(4, 4, 4):\n            if j < 3 and i < 2:\n                A[i, j] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j in T.grid(4, 4):\n            if j < 3 and i < 2:\n                for k in T.serial(4):\n                    A[i, j] = 0.0\n\n\nclass TestHoistMultiIfElse(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                for k in T.serial(4):\n                    if j < 3:\n                        if i < 2:\n                            A[i, j] = 0.0\n                        else:\n                            A[i, j] = 1.0\n                    else:\n                        if i < 2:\n                            A[i, j] = 2.0\n                        else:\n                            A[i, j] = 3.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 2:\n                for j in T.serial(4):\n                    if j < 3:\n                        for k in T.serial(4):\n                            A[i, j] = 0.0\n                    else:\n                        for k in T.serial(4):\n                            A[i, j] = 2.0\n            else:\n                for j in T.serial(4):\n                    if j < 3:\n                        for k in T.serial(4):\n                            A[i, j] = 1.0\n                    else:\n                        for k in T.serial(4):\n                            A[i, j] = 3.0\n\n\nclass TestHoistMultiIfElseDifferentBranches(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            for j in T.serial(4):\n                for k in T.serial(4):\n                    if j < 3:\n                        if i < 2:\n                            A[i, j] = 0.0\n                        else:\n                            A[i, j] = 1.0\n                    else:\n                        if i < 1:\n                            A[i, j] = 2.0\n                        else:\n                            A[i, j] = 3.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 2:\n                if i < 1:\n                    for j in T.serial(4):\n                        if j < 3:\n                            for k in T.serial(4):\n                                A[i, j] = 0.0\n                        else:\n                            for k in T.serial(4):\n                                A[i, j] = 2.0\n                else:\n                    for j in T.serial(4):\n                        if j < 3:\n                            for k in T.serial(4):\n                                A[i, j] = 0.0\n                        else:\n                            for k in T.serial(4):\n                                A[i, j] = 3.0\n            else:\n                for j in T.serial(4):\n                    if j < 3:\n                        for k in T.serial(4):\n                            A[i, j] = 1.0\n                    else:\n                        for k in T.serial(4):\n                            A[i, j] = 3.0\n\n\nclass TestHoistIfElseExpr(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j in T.grid(4, 4):\n            A[i, j] = T.if_then_else(i < 2, 1.0, 2.0, dtype=\"float32\")\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            if i < 2:\n                for j in T.serial(4):\n                    A[i, j] = 1.0\n            else:\n                for j in T.serial(4):\n                    A[i, j] = 2.0\n\n\nclass TestSuppressHoistIfElseExpr(TestHoistIfElseExpr):\n    hoisted_conditionals = tvm.testing.parameter(\n        HoistedConditionals.All & ~HoistedConditionals.IfElseExpr\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j in T.grid(4, 4):\n            A[i, j] = T.if_then_else(i < 2, 1.0, 2.0, dtype=\"float32\")\n\n    expected = before\n\n\nclass TestHoistLetExpr(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j in T.grid(4, 4):\n            x = T.var(\"float32\")\n            A[i, j] = T.Let(x, T.cast(i + 1, \"float32\"), 5.0 * x + T.cast(j, \"float32\"))\n\n    @T.prim_func\n    def expected(A: T.Buffer[(4, 4), \"float32\"]):\n        for i in T.serial(4):\n            x = T.cast(i + 1, \"float32\")\n            for j in T.serial(4):\n                A[i, j] = 5.0 * x + T.cast(j, \"float32\")\n\n\nclass TestSuppressHoistLetExpr(BaseBeforeAfter):\n    hoisted_let_bindings = tvm.testing.parameter(\n        HoistedLetBindings.All & ~HoistedLetBindings.LetExpr\n    )\n\n    @T.prim_func\n    def before(A: T.Buffer[(4, 4), \"float32\"]):\n        for i, j in T.grid(4, 4):\n            x = T.var(\"float32\")\n            A[i, j] = T.Let(x, T.cast(i + 1, \"float32\"), 5.0 * x + T.cast(j, \"float32\"))\n\n    expected = before\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_hoist_if.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nimport numpy as np\nimport pytest\nfrom tvm.testing import enabled_targets\n\nvar_list = []\n\n\ndef verify_structure(stmt, expected_struct):\n    node_dict = {}\n    struct = {}\n\n    def _extract_vars(op):\n        global var_list\n        if isinstance(op, tvm.tir.Var):\n            var_list.append(op.name)\n\n    def _visit(op):\n        key = op\n        if isinstance(op, tvm.tir.IfThenElse):\n            global var_list\n            tvm.tir.stmt_functor.post_order_visit(op.condition, _extract_vars)\n            val = [(op.then_case, op.else_case), (\"tir.IfThenElse\", tuple(var_list))]\n            var_list.clear()\n        elif isinstance(op, tvm.tir.For):\n            val = [(op.body,), (\"tir.For\", op.loop_var.name)]\n        elif isinstance(op, tvm.tir.AttrStmt):\n            val = [(op.body,), (\"tir.AttrStmt\", op.attr_key, int(op.value))]\n        else:\n            return\n        node_dict[key] = val\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, _visit)\n    for key, val in node_dict.items():\n        struct[val[1]] = tuple(\n            node_dict[child][1] if child in node_dict else None for child in val[0]\n        )\n\n    assert struct == expected_struct, \"Structure mismatch: expect %s but got %s\" % (\n        expected_struct,\n        struct,\n    )\n    var_list.clear()\n\n\ndef _opaque_eval(var):\n    return tvm.tir.Evaluate(tvm.tir.call_extern(\"int32\", \"dummy\", var))\n\n\ndef test_hoist_top_for():\n    ib = tvm.tir.ir_builder.create()\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    data = ib.pointer(\"float32\", name=\"data\")\n\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(ib.likely(i < 2)):\n                    ib.emit(_opaque_eval(m))\n                with ib.else_scope():\n                    ib.emit(_opaque_eval(n))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.For\", \"j\"): ((\"tir.For\", \"k\"),),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"j\"), (\"tir.For\", \"j\")),\n        (\"tir.For\", \"i\"): ((\"tir.IfThenElse\", (\"i\",)),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_hoist_multi_var_if():\n    ib = tvm.tir.ir_builder.create()\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    data = ib.pointer(\"float32\", name=\"data\")\n\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(ib.likely(i + j < 2)):\n                    ib.emit(_opaque_eval(m))\n                with ib.else_scope():\n                    ib.emit(_opaque_eval(n))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_mod = tvm.tir.transform.HoistIfThenElse()(mod)\n    new_stmt = new_mod[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.IfThenElse\", (\"i\", \"j\")): ((\"tir.For\", \"k\"), (\"tir.For\", \"k\")),\n        (\"tir.For\", \"j\"): ((\"tir.IfThenElse\", (\"i\", \"j\")),),\n        (\"tir.For\", \"i\"): ((\"tir.For\", \"j\"),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_hoist_no_match_for():\n    ib = tvm.tir.ir_builder.create()\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    data = ib.pointer(\"float32\", name=\"data\")\n\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            data[i * 3 + j] = data[i * 3 + j] + 0.5\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(ib.likely(i < 2)):\n                    ib.emit(_opaque_eval(m))\n                with ib.else_scope():\n                    ib.emit(_opaque_eval(n))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"k\"), (\"tir.For\", \"k\")),\n        (\"tir.For\", \"j\"): (None,),\n        (\"tir.For\", \"i\"): ((\"tir.For\", \"j\"),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_no_else():\n    ib = tvm.tir.ir_builder.create()\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(ib.likely(i < 2)):\n                    ib.emit(_opaque_eval(m))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.For\", \"j\"): ((\"tir.For\", \"k\"),),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"j\"), None),\n        (\"tir.For\", \"i\"): ((\"tir.IfThenElse\", (\"i\",)),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_attr_stmt():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(tvm.tir.any(i < 4, j >= 8)):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.5\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.0\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.IfThenElse\", (\"i\", \"j\")): ((\"tir.For\", \"k\"), (\"tir.For\", \"k\")),\n        (\"tir.For\", \"j\"): ((\"tir.IfThenElse\", (\"i\", \"j\")),),\n        (\"tir.For\", \"i\"): ((\"tir.For\", \"j\"),),\n        (\"tir.AttrStmt\", \"thread_extent\", 64): ((\"tir.For\", \"i\"),),\n        (\"tir.AttrStmt\", \"thread_extent\", 32): ((\"tir.AttrStmt\", \"thread_extent\", 64),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_nested_for():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\")\n\n    with ib.for_range(0, 5, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.if_scope(i >= 3):\n                data[i * 3 + j] = data[i * 3 + j] + 0.5\n                with ib.for_range(0, 15, \"k\") as k:\n                    with ib.for_range(0, 20, \"l\") as l:\n                        with ib.if_scope(tvm.tir.any(i < 4, j >= 8)):\n                            data[i * 3 + j + k + l] = data[i * 3 + j + k + l] * 2\n                        with ib.else_scope():\n                            data[i * 3 + j + k + l] = data[i * 3 + j + k + l] * 1.5\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"l\"): (None,),\n        (\"tir.For\", \"k\"): ((\"tir.For\", \"l\"),),\n        (\"tir.IfThenElse\", (\"i\", \"j\")): ((\"tir.For\", \"k\"), (\"tir.For\", \"k\")),\n        (\"tir.For\", \"j\"): (None,),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"j\"), None),\n        (\"tir.For\", \"i\"): ((\"tir.IfThenElse\", (\"i\",)),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_if_block():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\")\n    n = te.var(\"n\")\n\n    with ib.for_range(0, 5, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.if_scope(i >= 3):\n                data[i * 3 + j] = data[i * 3 + j] + 0.5\n                with ib.for_range(0, 15, \"k\") as k:\n                    with ib.for_range(0, 20, \"l\") as l:\n                        with ib.if_scope(tvm.tir.any(i < 4, j >= 8)):\n                            data[i * 3 + j + k + l] = data[i * 3 + j + k + l] * 2\n                        with ib.else_scope():\n                            data[i * 3 + j + k + l] = data[i * 3 + j + k + l] * 1.5\n                        with ib.if_scope(j < 5):\n                            data[i * 3 + j + k + l] = data[i * 3 + j + k + l] - 1\n\n    with ib.for_range(0, 5, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.for_range(0, 15, \"k\") as k:\n                with ib.if_scope(n >= 3):\n                    data[i * 3 + j + k] = data[i * 3 + j + k] + 0.6\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    expected_struct = {\n        (\"tir.IfThenElse\", (\"i\", \"j\")): (None, None),\n        (\"tir.IfThenElse\", (\"j\",)): (None, None),\n        (\"tir.For\", \"l\"): (None,),\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.For\", \"j\"): ((\"tir.For\", \"j\"),),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"j\"), None),\n        (\"tir.For\", \"i\"): ((\"tir.IfThenElse\", (\"i\",)),),\n        (\"tir.IfThenElse\", (\"n\",)): ((\"tir.For\", \"j\"), None),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_multi_if():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\")\n\n    with ib.for_range(0, 10, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.for_range(0, 10, \"k\") as k:\n                with ib.if_scope(3 <= i):\n                    with ib.if_scope(3 <= j):\n                        data[i * 100 + j * 10 + k] = data[i * 100 + j * 10 + k] + 0.5\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_mod = tvm.tir.transform.HoistIfThenElse()(mod)\n    new_stmt = new_mod[\"main\"].body\n    expected_struct = {\n        (\"tir.For\", \"k\"): (None,),\n        (\"tir.IfThenElse\", (\"j\",)): ((\"tir.For\", \"k\"), None),\n        (\"tir.For\", \"j\"): ((\"tir.IfThenElse\", (\"j\",)),),\n        (\"tir.IfThenElse\", (\"i\",)): ((\"tir.For\", \"j\"), None),\n        (\"tir.For\", \"i\"): ((\"tir.IfThenElse\", (\"i\",)),),\n    }\n    verify_structure(new_stmt, expected_struct)\n\n\ndef test_no_hoisting_1():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\")\n    n = te.var(\"n\")\n\n    with ib.for_range(0, 10, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.for_range(0, 10, \"k\") as k:\n                with ib.if_scope(k <= 3):\n                    data[i * 100 + j * 10 + k] = data[i * 100 + j * 10 + k] + 0.5\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_no_hoisting_2():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\")\n    n = te.var(\"n\")\n    x = te.var(\"x\")\n\n    with ib.for_range(0, 10, \"i\") as i:\n        with ib.for_range(0, 10, \"j\") as j:\n            with ib.for_range(0, 10, \"k\") as k:\n                with ib.if_scope(i <= 3):\n                    data[i * 100 + j * 10 + k] = data[i * 100 + j * 10 + k] + 0.3\n                data[i * 100 + j * 10 + k] = data[i * 100 + j * 10 + k] + 0.5\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\n@pytest.mark.xfail(reason=\"Inconsistent thread_extent\", strict=True)\ndef test_no_hoisting_3():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    dshape_inner = (33, 63)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                ib.scope_attr(tx, \"thread_extent\", dshape_inner[0])\n                ib.scope_attr(bx, \"thread_extent\", dshape_inner[1])\n                with ib.if_scope(tx < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_no_hoisting_4():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    dshape_inner = (33, 63)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                ib.scope_attr(tx, \"thread_extent\", dshape_inner[0])\n                with ib.if_scope(tx < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\n@pytest.mark.xfail(reason=\"Inconsistent thread_extent\", strict=True)\ndef test_no_hoisting_5():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    dshape_inner = (33, 63)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            ib.scope_attr(bx, \"thread_extent\", dshape_inner[1])\n            with ib.for_range(0, n, \"k\") as k:\n                ib.scope_attr(tx, \"thread_extent\", dshape_inner[0])\n                with ib.if_scope(tx < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_no_hoisting_6():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope((tx + k) < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_no_hoisting_7():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.if_scope((tx + j) < 9):\n                with ib.for_range(0, n, \"k\") as k:\n                    with ib.if_scope((tx + k) < 3):\n                        data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_1():\n    n = te.size_var(\"n\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, m), name=\"A\")\n    k = te.reduce_axis((0, m), \"k\")\n    B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name=\"B\")\n    s = te.create_schedule(B.op)\n    ko, ki = s[B].split(B.op.reduce_axis[0], factor=16)\n    BF = s.rfactor(B, ki)\n    xo, xi = s[B].split(s[B].op.axis[0], factor=32)\n    s[B.op].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[B.op].bind(xi, te.thread_axis(\"threadIdx.y\"))\n    s[B].bind(s[B].op.reduce_axis[0], te.thread_axis(\"threadIdx.x\"))\n    s[BF].compute_at(s[B], s[B].op.reduce_axis[0])\n    mod = tvm.driver.build_module.schedule_to_module(s, [A, B], \"main\", None)\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.RemoveNoOp()(mod)\n    stmt = mod[\"main\"].body\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_2():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    dshape_inner = (33, 63)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    # ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                ib.scope_attr(bx, \"thread_extent\", dshape[1])\n                with ib.if_scope(tx < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.RemoveNoOp()(mod)\n    stmt = mod[\"main\"].body\n\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\n@pytest.mark.xfail(reason=\"Inconsistent thread_extent\", strict=True)\ndef test_hoisting_block_scope_3():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    dshape_inner = (33, 63)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            ib.scope_attr(tx, \"thread_extent\", dshape_inner[0])\n            ib.scope_attr(bx, \"thread_extent\", dshape_inner[1])\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(tx < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_4():\n    nn = 1024\n    n = tvm.runtime.convert(nn)\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    AA = te.compute((n,), lambda *i: A(*i), name=\"A\")\n    BB = te.compute((n,), lambda *i: B(*i), name=\"B\")\n    T = te.compute(A.shape, lambda *i: AA(*i) + BB(*i), name=\"T\")\n    C = te.compute(A.shape, lambda *i: T(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], factor=4)\n    xo1, xo2 = s[C].split(xo, factor=13)\n    s[C].parallel(xo2)\n    s[C].pragma(xo1, \"parallel_launch_point\")\n    s[C].pragma(xo2, \"parallel_stride_pattern\")\n    s[C].pragma(xo2, \"parallel_barrier_when_finish\")\n    s[C].vectorize(xi)\n    mod = tvm.driver.build_module.schedule_to_module(s, [A, B, C], \"main\", None)\n    mod = tvm.tir.transform.Simplify()(mod)\n\n    stmt = mod[\"main\"].body\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_5():\n    ib = tvm.tir.ir_builder.create()\n    data = ib.pointer(\"float32\", name=\"data\", scope=\"global\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    g = te.var(\"g\")\n\n    ib.scope_attr(data, \"storage_scope\", \"global\")\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope(data[g] < 3):\n                    data[9 * j + 3 * j * k] = data[9 * j + 3 * j * k] + 0.3\n                with ib.else_scope():\n                    data[9 * j + 3 * j * k] = data[9 * j + 3 * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n    stmt = new_stmt\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_6():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope((tx + n) < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\ndef test_hoisting_block_scope_7():\n    ib = tvm.tir.ir_builder.create()\n    dshape = (32, 64)\n    data = ib.pointer(\"float32\", name=\"data\")\n    l = te.var(\"l\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n\n    tx = te.thread_axis(\"threadIdx.x\")\n    bx = te.thread_axis(\"blockIdx.x\")\n    ib.scope_attr(tx, \"thread_extent\", dshape[0])\n    ib.scope_attr(bx, \"thread_extent\", dshape[1])\n    with ib.for_range(0, l, \"i\") as i:\n        with ib.for_range(0, m, \"j\") as j:\n            with ib.for_range(0, n, \"k\") as k:\n                with ib.if_scope((tx + i) < 3):\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 0.3\n                with ib.else_scope():\n                    data[bx * j + tx * j * k] = data[bx * j + tx * j * k] + 1.3\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    tvm.ir.assert_structural_equal(new_stmt, stmt)\n\n    with tvm.transform.PassContext(\n        config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n    ):\n        new_stmt = tvm.tir.transform.HoistIfThenElse()(mod)[\"main\"].body\n    assert not tvm.ir.structural_equal(new_stmt, stmt)\n\n\n@pytest.mark.skip()\ndef test_hoisting_op_conv():\n    dtype = \"float32\"\n    dshape = (1, 80, 73, 73)\n    kshape = (192, 80, 3, 3)\n    padding = (1, 1)\n    groups = 1\n    dilation = (1, 1)\n    kernel_size = (3, 3)\n    channels = 192\n    scale = 1\n    x = relay.var(\"x\", shape=dshape, dtype=dtype)\n    w = relay.var(\"w\", shape=kshape, dtype=dtype)\n    y = relay.nn.conv2d(\n        x,\n        w,\n        padding=padding,\n        dilation=dilation,\n        groups=groups,\n        channels=channels,\n        kernel_size=kernel_size,\n    )\n\n    func = relay.Function([x, w], y)\n    mod = tvm.IRModule()\n    mod[\"main\"] = func\n    mod = relay.transform.InferType()(mod)\n\n    data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)\n    kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)\n\n    params = {\"w\": tvm.nd.array(kernel)}\n    for target, dev in enabled_targets():\n        with tvm.transform.PassContext(opt_level=3):\n            lib = relay.build_module.build(mod, target=target, params=params)\n            m = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n            x = np.random.uniform(size=dshape)\n            data_tvm = tvm.nd.array(data)\n            m.set_input(\"x\", data_tvm)\n            m.run()\n            e = m.module.time_evaluator(\"run\", dev, number=300, repeat=3)\n            t1 = e(data_tvm).results\n            t1 = np.array(t1) * 1000\n            print(\"{} ms\".format(t1.mean()))\n\n        with tvm.transform.PassContext(\n            opt_level=3, config={\"tir.HoistIfThenElse\": {\"support_block_scope_hosting\": True}}\n        ):\n            lib = relay.build_module.build(mod, target=target, params=params)\n            m = tvm.contrib.graph_executor.GraphModule(lib[\"default\"](dev))\n            x = np.random.uniform(size=dshape)\n            data_tvm = tvm.nd.array(data)\n            m.set_input(\"x\", data_tvm)\n            m.set_input(**params)\n            m.run()\n            e = m.module.time_evaluator(\"run\", dev, number=300, repeat=3)\n            t2 = e(data_tvm).results\n            t2 = np.array(t2) * 1000\n\n            print(\"{} ms\".format(t2.mean()))\n        tvm.testing.assert_allclose(t1.mean(), t2.mean(), atol=1, rtol=1e-1)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_copy_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\n\n\ndef test_copy2d():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.compute((m, l), lambda i, j: A[i, j], name=\"B\")\n    s = te.create_schedule(B.op)\n    s[B].pragma(B.op.axis[0], \"memcpy\")\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n    func = tvm.te.schedule.SchedulePostProcToPrimFunc([A, B], stmt, None)\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    def cb(src, dst, pad_before, pad_after, pad_value):\n        assert dst.strides[0] == l\n        assert dst.strides[1].value == 1\n        assert src.strides[0] == l\n        assert tuple(src.shape) == (m, l)\n        return tvm.tir.Evaluate(0)\n\n    stmt = tvm.tir.transform.InjectCopyIntrin(\"memcpy\", cb)(mod)[\"main\"].body\n\n\ndef test_copy_pad():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.compute(\n        (m + 2, l),\n        lambda i, j: tvm.tir.if_then_else(tvm.tir.all(i >= 1, i < m + 1), A[i - 1, j], 1.0),\n        name=\"B\",\n    )\n    s = te.create_schedule(B.op)\n    s[B].pragma(B.op.axis[0], \"memcpy\")\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    def cb(src, dst, pad_before, pad_after, pad_value):\n        tvm.testing.assert_prim_expr_equal(src.elem_offset, 0)\n        assert pad_before[0].value == 1\n        assert pad_before[1].value == 0\n        assert pad_after[0].value == 1\n        assert pad_after[1].value == 0\n        assert pad_value.value == 1.0\n        return tvm.tir.Evaluate(0)\n\n    stmt = tvm.tir.transform.InjectCopyIntrin(\"memcpy\", cb)(mod)[\"main\"].body\n\n\ndef test_single_point_test():\n    A = te.placeholder((1,), name=\"A\")\n    B = te.compute((1,), lambda i: A[i], name=\"B\")\n    s = te.create_schedule(B.op)\n    s[B].pragma(B.op.axis[0], \"memcpy\")\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    def cb(src, dst, pad_before, pad_after, pad_value):\n        tvm.testing.assert_prim_expr_equal(src.elem_offset, 0)\n        tvm.testing.assert_prim_expr_equal(dst.elem_offset, 0)\n        tvm.testing.assert_prim_expr_equal(src.strides[0], 1)\n        tvm.testing.assert_prim_expr_equal(dst.strides[0], 1)\n        return tvm.tir.Evaluate(0)\n\n    stmt = tvm.tir.transform.InjectCopyIntrin(\"memcpy\", cb)(mod)[\"main\"].body\n\n\ndef test_copy_pad_split():\n    m = 4 * 3\n    A = te.placeholder((m,), name=\"A\")\n    Apad = te.compute(\n        (m + 2,), lambda i: tvm.tir.if_then_else(tvm.tir.all(i >= 1, i <= m), A[i - 1], 0.0), \"Apad\"\n    )\n    B = te.compute((m,), lambda i: Apad[i] + Apad[i + 1] + Apad[i + 2])\n    s = te.create_schedule(B.op)\n    xo, xi = s[B].split(B.op.axis[0], factor=4)\n    s[Apad].compute_at(s[B], xo)\n    s[Apad].pragma(s[Apad].op.axis[0], \"memcpy\")\n\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod._move())\n    mod = tvm.tir.transform.Simplify()(mod._move())\n\n    def cb(src, dst, pad_before, pad_after, pad_value):\n        assert dst.elem_offset.value == 0\n        tvm.testing.assert_prim_expr_equal(src.elem_offset, tvm.te.max(xo * 4, 1) - 1)\n\n        rpad_before = tvm.te.max(1 - xo * 4, 0)\n        rpad_after = tvm.te.max(xo * 4 - 7, 0)\n        tvm.testing.assert_prim_expr_equal(pad_before[0], rpad_before)\n        tvm.testing.assert_prim_expr_equal(pad_after[0], rpad_after)\n        tvm.testing.assert_prim_expr_equal(src.shape[0], 6 - rpad_before - rpad_after)\n        return tvm.tir.Evaluate(0)\n\n    stmt = tvm.tir.transform.InjectCopyIntrin(\"memcpy\", cb)(mod)[\"main\"].body\n\n\nif __name__ == \"__main__\":\n    test_copy2d()\n    test_copy_pad()\n    test_copy_pad_split()\n    test_single_point_test()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_double_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_double_buffer():\n    dtype = \"int64\"\n    n = 100\n    m = 4\n    tx = te.thread_axis(\"threadIdx.x\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    C = ib.pointer(\"float32\", name=\"C\")\n    ib.scope_attr(tx, \"thread_extent\", 1)\n    with ib.for_range(0, n) as i:\n        B = ib.allocate(\"float32\", m, name=\"B\", scope=\"shared\")\n        with ib.new_scope():\n            ib.scope_attr(B.asobject().data, \"double_buffer_scope\", 1)\n            with ib.for_range(0, m) as j:\n                B[j] = A[i * 4 + j]\n        with ib.for_range(0, m) as j:\n            C[j] = B[j] + 1\n\n    stmt = ib.get()\n    mod = tvm.IRModule({\"db\": tvm.tir.PrimFunc([A.asobject(), C.asobject()], stmt)})\n\n    opt = tvm.transform.Sequential(\n        [tvm.tir.transform.InjectDoubleBuffer(), tvm.tir.transform.Simplify()]\n    )\n\n    with tvm.transform.PassContext(config={\"tir.InjectDoubleBuffer\": {\"split_loop\": 2}}):\n        mod = opt(mod)\n    stmt = mod[\"db\"].body\n\n    assert isinstance(stmt.body, tvm.tir.Allocate)\n    assert list(stmt.body.extents) == [m * 2]\n\n    f = tvm.tir.transform.ThreadSync(\"shared\")(mod)[\"db\"]\n    count = [0]\n\n    def count_sync(op):\n        if isinstance(op, tvm.tir.Call) and op.op.same_as(tvm.ir.Op.get(\"tir.tvm_storage_sync\")):\n            count[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(f.body, count_sync)\n    assert count[0] == 4\n\n\nif __name__ == \"__main__\":\n    test_double_buffer()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_ptx_async_copy.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\ndef count_cp_async(stmt):\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Call) and str(n.op) == \"tir.ptx_cp_async\":\n            num_alloc[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    return num_alloc[0]\n\n\ndef generate_global_to_shared_vectorized_copy(dtype, vector_size):\n    num_iters = 128 // vector_size\n    vector_size_expr = tvm.runtime.convert(vector_size)\n\n    @T.prim_func\n    def ptx_global_to_shared_copy(\n        A: T.Buffer[(32, 128), dtype], B: T.Buffer[(32, 128), dtype]\n    ) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        bx = T.env_thread(\"blockIdx.x\")\n        tx = T.env_thread(\"threadIdx.x\")\n        T.launch_thread(bx, 1)\n        T.launch_thread(tx, 32)\n        with T.block():\n            A_shared = T.alloc_buffer([32, 128], dtype, scope=\"shared\")\n            T.reads(A[0:32, 0:128])\n            T.writes(B[0:32, 0:128])\n\n            T.attr(\"default\", \"async_scope\", 1)\n            for i in T.serial(num_iters):\n                for j in T.vectorized(vector_size):\n                    A_shared[tx, i * vector_size_expr + j] = A[tx, i * vector_size_expr + j]\n\n            T.evaluate(T.ptx_commit_group(dtype=\"\"))\n            T.evaluate(T.ptx_wait_group(0, dtype=\"\"))\n\n            for i in range(128):\n                B[tx, i] = A_shared[tx, i]\n\n    return ptx_global_to_shared_copy\n\n\n@T.prim_func\ndef ptx_global_to_shared_copy_fp32x1(\n    A: T.Buffer[(32, 128), \"float32\"], B: T.Buffer[(32, 128), \"float32\"]\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    bx = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(bx, 1)\n    T.launch_thread(tx, 32)\n    with T.block():\n        A_shared = T.alloc_buffer([32, 128], \"float32\", scope=\"shared\")\n        T.reads(A[0:32, 0:128])\n        T.writes(B[0:32, 0:128])\n\n        T.attr(\"default\", \"async_scope\", 1)\n        for i in T.serial(128):\n            A_shared[tx, i] = A[tx, i]\n\n        T.evaluate(T.ptx_commit_group(dtype=\"\"))\n        T.evaluate(T.ptx_wait_group(0, dtype=\"\"))\n\n        for i in range(128):\n            B[tx, i] = A_shared[tx, i]\n\n\n@T.prim_func\ndef ptx_global_to_shared_dyn_copy_fp16x8(\n    A: T.Buffer[(32, 128), \"float16\"],\n    B: T.Buffer[(32, 128), \"float16\"],\n    C: T.Buffer[(32, 128), \"float16\"],\n) -> None:\n    T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n    bx = T.env_thread(\"blockIdx.x\")\n    tx = T.env_thread(\"threadIdx.x\")\n    T.launch_thread(bx, 1)\n    T.launch_thread(tx, 32)\n    with T.block():\n        A_shared = T.alloc_buffer([32, 128], \"float16\", scope=\"shared.dyn\")\n        B_shared = T.alloc_buffer([32, 128], \"float16\", scope=\"shared.dyn\")\n        T.reads(A[0:32, 0:128], B[0:32, 0:128])\n        T.writes(C[0:32, 0:128])\n\n        T.attr(\"default\", \"async_scope\", 1)\n        for i in T.serial(16):\n            for j in T.vectorized(8):\n                A_shared[tx, i * 8 + j] = A[tx, i * 8 + j]\n                B_shared[tx, i * 8 + j] = B[tx, i * 8 + j]\n\n        T.evaluate(T.ptx_commit_group(dtype=\"\"))\n        T.evaluate(T.ptx_wait_group(0, dtype=\"\"))\n\n        for i in range(128):\n            C[tx, i] = A_shared[tx, i] + B_shared[tx, i]\n\n\n@tvm.testing.requires_cuda\ndef test_inject_async_copy():\n    for dtype, vec_size in [(\"float16\", 8), (\"float16\", 4), (\"float32\", 4), (\"float32\", 1)]:\n        if vec_size == 1:\n            f = ptx_global_to_shared_copy_fp32x1\n        else:\n            f = generate_global_to_shared_vectorized_copy(dtype, vec_size)\n\n        mod = tvm.IRModule.from_expr(f)\n        mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n        mod = tvm.tir.transform.FlattenBuffer()(mod)\n        if vec_size > 1:\n            mod = tvm.tir.transform.VectorizeLoop()(mod)\n        mod = tvm.tir.transform.InjectPTXAsyncCopy()(mod)\n\n        assert count_cp_async(mod[\"main\"].body) == 1\n\n        if not tvm.testing.is_ampere_or_newer():\n            continue\n\n        with tvm.transform.PassContext(config={\"tir.use_async_copy\": 1}):\n            mod = tvm.build(tvm.IRModule.from_expr(f), target=\"cuda\")\n\n        A_np = np.random.rand(32, 128).astype(dtype)\n        B_np = np.zeros((32, 128)).astype(dtype)\n        dev = tvm.cuda(0)\n        A_nd = tvm.nd.array(A_np, device=dev)\n        B_nd = tvm.nd.array(B_np, device=dev)\n        mod(A_nd, B_nd)\n        tvm.testing.assert_allclose(B_nd.numpy(), A_np)\n\n\n@tvm.testing.requires_cuda\ndef test_inject_async_copy_shared_dyn():\n    f = ptx_global_to_shared_dyn_copy_fp16x8\n\n    mod = tvm.IRModule.from_expr(f)\n    mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n    mod = tvm.tir.transform.FlattenBuffer()(mod)\n    mod = tvm.tir.transform.VectorizeLoop()(mod)\n    mod = tvm.tir.transform.MergeDynamicSharedMemoryAllocations()(mod)\n    mod = tvm.tir.transform.InjectPTXAsyncCopy()(mod)\n\n    assert count_cp_async(mod[\"main\"].body) == 2\n\n    if not tvm.testing.is_ampere_or_newer():\n        return\n\n    with tvm.transform.PassContext(config={\"tir.use_async_copy\": 1}):\n        mod = tvm.build(tvm.IRModule.from_expr(f), target=\"cuda\")\n\n    A_np = np.random.rand(32, 128).astype(\"float16\")\n    B_np = np.random.rand(32, 128).astype(\"float16\")\n    C_np = np.zeros((32, 128)).astype(\"float16\")\n    dev = tvm.cuda(0)\n    A_nd = tvm.nd.array(A_np, device=dev)\n    B_nd = tvm.nd.array(B_np, device=dev)\n    C_nd = tvm.nd.array(C_np, device=dev)\n    mod(A_nd, B_nd, C_nd)\n    tvm.testing.assert_allclose(C_nd.numpy(), A_np + B_np)\n\n\nif __name__ == \"__main__\":\n    test_inject_async_copy()\n    test_inject_async_copy_shared_dyn()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_rolling_buffer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.script\nfrom tvm.script import tir as T\nfrom tvm import te\nfrom tvm import topi\nfrom tvm.driver.build_module import get_binds\nimport numpy as np\n\nimport pytest\n\n\ndef _tile_nd(s, tensor, tile):\n    outer_indices = []\n    inner_indices = []\n    for i, size in enumerate(tile):\n        outer, inner = s[tensor].split(tensor.op.axis[i], size)\n        outer_indices.append(outer)\n        inner_indices.append(inner)\n\n    s[tensor].reorder(*outer_indices, *inner_indices)\n    return outer_indices, inner_indices\n\n\n@tvm.tir.transform.prim_func_pass(opt_level=0)\ndef remove_rolling_buffer_attr(func, mod, ctx):\n    def unwrap(node):\n        if isinstance(node, tvm.tir.AttrStmt) and node.attr_key == \"rolling_buffer_scope\":\n            return node.body\n        else:\n            return node\n\n    return func.with_body(\n        tvm.tir.stmt_functor.ir_transform(\n            func.body, None, postorder=unwrap, only_enable=[\"tir.AttrStmt\"]\n        )\n    )\n\n\n@tvm.tir.transform.prim_func_pass(opt_level=0)\ndef verify_no_rolling_buffer_attr(func, mod, ctx):\n    def verify(node):\n        if isinstance(node, tvm.tir.AttrStmt):\n            assert node.attr_key != \"rolling_buffer_scope\", \"Failed to lower rolling buffers\"\n\n    tvm.tir.stmt_functor.post_order_visit(func.body, verify)\n\n    return func\n\n\ndef _verify_schedule(sch, inputs, output):\n    user_pass_lists = [\n        [(0, remove_rolling_buffer_attr), (0, verify_no_rolling_buffer_attr)],\n        [(0, tvm.tir.transform.InjectRollingBuffer()), (0, verify_no_rolling_buffer_attr)],\n    ]\n    built_funcs = []\n    for user_pass_list in user_pass_lists:\n        with tvm.transform.PassContext(config={\"tir.add_lower_pass\": user_pass_list}):\n            built_funcs.append(tvm.build(sch, inputs + [output]))\n\n    outputs = []\n    ctx = tvm.cpu(0)\n    input_data = []\n    for tensor in inputs:\n        shape = [i.value for i in tensor.shape]\n        input_data.append(\n            tvm.nd.array(np.random.randint(low=-100, high=100, size=shape).astype(\"int8\"), ctx)\n        )\n    shape = [i.value for i in output.shape]\n    out = tvm.nd.array(np.zeros(shape, dtype=\"int8\"), ctx)\n    for func in built_funcs:\n        func(*input_data, out)\n        outputs.append(out.numpy())\n\n    np.testing.assert_equal(outputs[0], outputs[1])\n\n\n@pytest.mark.parametrize(\"tile_shape\", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)])\ndef test_tile_shapes(tile_shape):\n    A = te.placeholder((1, 12, 14, 16), name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(pool_a, (3, 5), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n\n    sch = tvm.te.create_schedule([pool_b.op])\n    oi, ii = _tile_nd(sch, pool_b, tile_shape)\n    sch[pool_a].compute_at(sch[pool_b], oi[-1])\n    sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A], pool_b)\n\n\ndef test_implied_split():\n    A = te.placeholder((1, 12, 12, 16), name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n\n    sch = tvm.te.create_schedule([pool_b.op])\n    n, h, w, c = pool_b.op.axis\n    oi, ii = sch[pool_b].split(w, 4)\n    sch[pool_a].compute_at(sch[pool_b], oi)\n    sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A], pool_b)\n\n\n@pytest.mark.parametrize(\"kernel_shape\", [(1, 1), (3, 3)])\ndef test_upscale(kernel_shape):\n    output_shape = (1, 24, 24, 16)\n    input_shape = (\n        output_shape[0],\n        output_shape[1] // 2 + 2 * (kernel_shape[0] - 1),\n        output_shape[2] // 2 + 2 * (kernel_shape[1] - 1),\n        output_shape[3],\n    )\n    A = te.placeholder(input_shape, name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, kernel_shape, (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(\n        pool_a, kernel_shape, (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\"\n    )\n    upscale = te.compute((1, 24, 24, 16), lambda nn, hh, ww, cc: pool_b[nn, hh // 2, ww // 2, cc])\n\n    sch = tvm.te.create_schedule([upscale.op])\n    oi, ii = _tile_nd(sch, upscale, (1, 5, 5, 16))\n    sch[pool_b].compute_at(sch[upscale], oi[-1])\n    sch[pool_b].rolling_buffer()\n    sch[pool_a].compute_at(sch[upscale], oi[-1])\n    sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A], upscale)\n\n\n@pytest.mark.parametrize(\"tile_shape\", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)])\ndef test_3_tiled_poolings(tile_shape):\n    A = te.placeholder((1, 14, 14, 16), name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_c = topi.nn.pool2d(pool_b, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n\n    sch = tvm.te.create_schedule([pool_c.op])\n    oi, ii = _tile_nd(sch, pool_c, tile_shape)\n    sch[pool_b].compute_at(sch[pool_c], oi[-1])\n    sch[pool_b].rolling_buffer()\n    sch[pool_a].compute_at(sch[pool_c], oi[-1])\n    sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A], pool_c)\n\n\n@pytest.mark.parametrize(\"tile_shape\", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)])\ndef test_tiled_added_poolings(tile_shape):\n    A = te.placeholder((1, 12, 12, 16), name=\"A\", dtype=\"int8\")\n    B = te.placeholder((1, 14, 14, 16), name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(B, (5, 5), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    add = topi.add(pool_a, pool_b)\n    pool_c = topi.nn.pool2d(add, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n\n    sch = tvm.te.create_schedule([pool_c.op])\n    oi, ii = _tile_nd(sch, pool_c, tile_shape)\n    sch[add].compute_at(sch[pool_c], oi[-1])\n    sch[add].rolling_buffer()\n    sch[pool_b].compute_at(sch[pool_c], oi[-1])\n    sch[pool_b].rolling_buffer()\n    sch[pool_a].compute_at(sch[pool_c], oi[-1])\n    sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A, B], pool_c)\n\n\n@pytest.mark.parametrize(\"make_rolling\", [(0, 0), (1, 0), (0, 1), (1, 1)])\ndef test_mixed_buffers(make_rolling):\n    A = te.placeholder((1, 14, 14, 16), name=\"A\", dtype=\"int8\")\n    pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n    pool_c = topi.nn.pool2d(pool_b, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), \"max\", layout=\"NHWC\")\n\n    sch = tvm.te.create_schedule([pool_c.op])\n    oi, ii = _tile_nd(sch, pool_c, (1, 4, 8, 16))\n    sch[pool_b].compute_at(sch[pool_c], oi[-1])\n    if make_rolling[0]:\n        sch[pool_b].rolling_buffer()\n    sch[pool_a].compute_at(sch[pool_c], oi[-1])\n    if make_rolling[1]:\n        sch[pool_a].rolling_buffer()\n\n    _verify_schedule(sch, [A], pool_c)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass PreRollingBuffer:\n    @T.prim_func\n    def main(A: T.handle, tensor: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        # buffer definition\n        tensor_2 = T.buffer_decl([1, 10, 12, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        A_1 = T.match_buffer(A, [1, 12, 14, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        tensor_1 = T.match_buffer(tensor, [1, 8, 8, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.realize(tensor_1[0:1, 0:8, 0:8, 0:16], \"\")\n        for ax1_outer in T.serial(0, 2):\n            T.realize(tensor_2[0:1, (ax1_outer*4):((ax1_outer*4) + 6), 0:12, 0:16], \"\")\n            T.attr(tensor_2, \"rolling_buffer_scope\", True)\n            for ax1 in T.serial(0, 6):\n                for ax2 in T.serial(0, 12):\n                    for ax3 in T.serial(0, 16):\n                        tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3] = T.int8(0)\n                        for dh in T.serial(0, 3):\n                            for dw in T.serial(0, 3):\n                                tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3] = T.max(tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3], A_1[0, ((ax1 + (ax1_outer*4)) + dh), (ax2 + dw), ax3])\n            for ax1_inner in T.serial(0, 4):\n                for ax2_inner in T.serial(0, 8):\n                    for ax3_inner in T.serial(0, 16):\n                        tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.int8(0)\n                        for dh_1 in T.serial(0, 3):\n                            for dw_1 in T.serial(0, 5):\n                                tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.max(tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner], tensor_2[0, ((ax1_inner + (ax1_outer*4)) + dh_1), (ax2_inner + dw_1), ax3_inner])\n    __tvm_meta__ = None\n\n\n@tvm.script.ir_module\nclass PostRollingBuffer:\n    @T.prim_func\n    def main(A: T.handle, tensor: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n        # buffer definition\n        tensor_2 = T.buffer_decl([1, 10, 12, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        A_1 = T.match_buffer(A, [1, 12, 14, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        tensor_1 = T.match_buffer(tensor, [1, 8, 8, 16], dtype=\"int8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.realize(tensor_1[0:1, 0:8, 0:8, 0:16], \"\")\n        T.realize(tensor_2[0:1, 0:6, 0:12, 0:16], \"\")\n        for ax1_outer in T.serial(0, 2):\n            for ax1 in T.serial(0, 6):\n                for ax2 in T.serial(0, 12):\n                    for ax3 in T.serial(0, 16):\n                        if T.likely(((ax1_outer < 1) or (ax1 >= 2)), dtype='bool') :\n                            tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3] = T.int8(0)\n                        for dh in T.serial(0, 3):\n                            for dw in T.serial(0, 3):\n                                if T.likely(((ax1_outer < 1) or (ax1 >= 2)), dtype='bool'):\n                                    tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3] = T.max(tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3], A_1[0, ((ax1 + (ax1_outer*4)) + dh), (ax2 + dw), ax3])\n            for ax1_inner in T.serial(0, 4):\n                for ax2_inner in T.serial(0, 8):\n                    for ax3_inner in T.serial(0, 16):\n                        tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.int8(0)\n                        for dh_1 in T.serial(0, 3):\n                            for dw_1 in T.serial(0, 5):\n                                tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.max(tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner], tensor_2[0, T.floormod(((ax1_inner + (ax1_outer*4)) + dh_1), 6), (ax2_inner + dw_1), ax3_inner])\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_rolling_buffer_ir_transform():\n    mod = PreRollingBuffer\n    mod = tvm.tir.transform.InjectRollingBuffer()(mod)\n    script = mod.script(show_meta=True)\n    mod = tvm.script.from_source(script)\n    tvm.ir.assert_structural_equal(mod[\"main\"], PostRollingBuffer[\"main\"], True)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_software_pipeline.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.tir.tensor_intrin.cuda\nfrom tvm import TVMError, te, tir\nfrom tvm.meta_schedule.testing import te_workload\nfrom tvm.script import tir as T\nfrom tvm.testing.tir import mma_schedule\nfrom tvm.tir.tensor_intrin.cuda import (\n    LDMATRIX_16x16_A_DYN_INTRIN,\n    LDMATRIX_16x16_B_DYN_INTRIN,\n    MMA_f16f16f32_INTRIN,\n    MMA_fill_16x16_f32_INTRIN,\n    MMA_store_16x16_f32_global_INTRIN,\n    shared_16x16_to_ldmatrix_32x8_layout,\n)\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.InjectSoftwarePipeline()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed, True)\n\n\ndef _check_error(func):\n    mod = tvm.IRModule.from_expr(func)\n    with pytest.raises(ValueError):\n        tvm.tir.transform.InjectSoftwarePipeline()(mod)\n\n\n@T.prim_func\ndef trivial_pipeline(A: T.Buffer[(16, 1), \"float32\"], C: T.Buffer[(16, 1), \"float32\"]):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0, 1, annotations={\"software_pipeline_stage\": [0, 1], \"software_pipeline_order\": [0, 1]}\n        ):\n            with T.block():\n                T.reads(A[tx, i])\n                T.writes(C[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, i])\n                    C[tx, i] = B[tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_trivial_pipeline(\n    A: T.Buffer[(16, 1), \"float32\"], C: T.Buffer[(16, 1), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads(A[tx, 0])\n            T.writes(C[tx, 0])\n            B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads(A[tx, 0])\n                T.writes(B[0, tx, 0])\n                B[0, tx, 0] = A[tx, 0] * T.float32(2)\n            with T.block():\n                T.reads()\n                T.writes()\n                T.evaluate(0)\n            with T.block():\n                T.reads(B[0, tx, 0])\n                T.writes(C[tx, 0])\n                C[tx, 0] = B[0, tx, 0] + T.float32(1)\n\n\ndef gen_simple_compute(num_stages):\n    @T.prim_func\n    def simple_compute(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n            for i in T.serial(\n                0,\n                16,\n                annotations={\n                    \"software_pipeline_stage\": [0, num_stages],\n                    \"software_pipeline_order\": [0, 1],\n                },\n            ):\n                with T.block(\"compute\"):\n                    T.reads(A[tx, i])\n                    T.writes(C[tx, i])\n                    B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                    with T.block():\n                        T.reads(A[tx, i])\n                        T.writes(B[tx, 0])\n                        B[tx, 0] = A[tx, i] * T.float32(2)\n                    with T.block():\n                        T.reads(B[tx, 0])\n                        T.writes(C[tx, i])\n                        C[tx, i] = B[tx, 0] + T.float32(1)\n\n    return simple_compute\n\n\n@T.prim_func\ndef transformed_simple_compute(\n    A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16]])\n            T.writes([C[tx, 0:16]])\n            B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0]])\n                T.writes([B[0, tx, 0]])\n                B[0, tx, 0] = A[tx, 0] * T.float32(2)\n            with T.block():\n                T.reads([A[tx, 1:16], B[0:2, tx, 0]])\n                T.writes([B[0:2, tx, 0], C[tx, 0:15]])\n                for i in T.serial(0, 15):\n                    with T.block():\n                        T.reads([A[tx, i + 1]])\n                        T.writes([B[(i + 1) % 2, tx, 0]])\n                        B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2)\n                    with T.block():\n                        T.reads([B[i % 2, tx, 0]])\n                        T.writes([C[tx, i]])\n                        C[tx, i] = B[i % 2, tx, 0] + T.float32(1)\n            with T.block():\n                T.reads([B[1, tx, 0]])\n                T.writes([C[tx, 15]])\n                C[tx, 15] = B[1, tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef simple_compute_with_other_annotation(\n    A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 1],\n                \"software_pipeline_order\": [0, 1],\n                \"pragma_loop_partition_hint\": True,\n            },\n        ):\n            with T.block(\"compute\"):\n                T.reads(A[tx, i])\n                T.writes(C[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, i])\n                    C[tx, i] = B[tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_simple_compute_with_other_annotation(\n    A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16]])\n            T.writes([C[tx, 0:16]])\n            B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0]])\n                T.writes([B[0, tx, 0]])\n                B[0, tx, 0] = A[tx, 0] * T.float32(2)\n            with T.block():\n                T.reads([A[tx, 1:16], B[0:2, tx, 0]])\n                T.writes([B[0:2, tx, 0], C[tx, 0:15]])\n                for i in T.serial(\n                    0,\n                    15,\n                    annotations={\"pragma_loop_partition_hint\": True},\n                ):\n                    with T.block():\n                        T.reads([A[tx, i + 1]])\n                        T.writes([B[(i + 1) % 2, tx, 0]])\n                        B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2)\n                    with T.block():\n                        T.reads([B[i % 2, tx, 0]])\n                        T.writes([C[tx, i]])\n                        C[tx, i] = B[i % 2, tx, 0] + T.float32(1)\n            with T.block():\n                T.reads([B[1, tx, 0]])\n                T.writes([C[tx, 15]])\n                C[tx, 15] = B[1, tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef three_stage_compute(A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 1, 2],\n                \"software_pipeline_order\": [0, 1, 2],\n            },\n        ):\n            with T.block(\"compute\"):\n                T.reads(A[tx, i])\n                T.writes(D[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                C = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, 0])\n                    C[tx, 0] = B[tx, 0] + T.float32(2)\n                with T.block():\n                    T.reads(C[tx, 0])\n                    T.writes(D[tx, i])\n                    D[tx, i] = C[tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_three_stage_compute(\n    A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads(A[tx, 0:16])\n            T.writes(D[tx, 0:16])\n            B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n            C = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads(A[tx, 0:2], B[0:2, tx, 0])\n                T.writes(B[0:2, tx, 0], C[0:2, tx, 0])\n                for i in T.unroll(2):\n                    with T.block():\n                        T.reads(A[tx, i])\n                        T.writes(B[0:2, tx, 0])\n                        B[i, tx, 0] = A[tx, i] * T.float32(2)\n                    with T.block():\n                        T.where(i == 1)\n                        T.reads(B[0:2, tx, 0])\n                        T.writes(C[0:2, tx, 0])\n                        C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2)\n            with T.block():\n                T.reads(A[tx, 2:16], B[0:2, tx, 0], C[0:2, tx, 0])\n                T.writes(B[0:2, tx, 0], C[0:2, tx, 0], D[tx, 0:14])\n                for i in T.serial(14):\n                    with T.block():\n                        T.reads(A[tx, i + 2])\n                        T.writes(B[0:2, tx, 0])\n                        B[i % 2, tx, 0] = A[tx, i + 2] * T.float32(2)\n                    with T.block():\n                        T.reads(B[0:2, tx, 0])\n                        T.writes(C[0:2, tx, 0])\n                        C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2)\n                    with T.block():\n                        T.reads(C[0:2, tx, 0])\n                        T.writes(D[tx, i])\n                        D[tx, i] = C[i % 2, tx, 0] + T.float32(1)\n            with T.block():\n                T.reads(B[0:2, tx, 0], C[0:2, tx, 0])\n                T.writes(C[0:2, tx, 0], D[tx, 14:16])\n                for i in T.unroll(2):\n                    with T.block():\n                        T.where(i < 1)\n                        T.reads(B[0:2, tx, 0])\n                        T.writes(C[0:2, tx, 0])\n                        C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2)\n                    with T.block():\n                        T.reads(C[0:2, tx, 0])\n                        T.writes(D[tx, i + 14])\n                        D[tx, i + 14] = C[i, tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef dag_interleaving(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 0, 0, 0, 1],\n                \"software_pipeline_order\": [0, 2, 1, 3, 4],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i])\n                T.writes(C[tx, i])\n                AS = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                BS = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                AL = T.alloc_buffer((1, 1), dtype=\"float32\", scope=\"local\")\n                BL = T.alloc_buffer((1, 1), dtype=\"float32\", scope=\"local\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(AS[tx, 0])\n                    AS[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(AS[tx, 0])\n                    T.writes(AL[0, 0])\n                    AL[0, 0] = AS[tx, 0]\n                with T.block():\n                    T.reads(B[tx, i])\n                    T.writes(BS[tx, 0])\n                    BS[tx, 0] = B[tx, i] + T.float32(2)\n                with T.block():\n                    T.reads(BS[tx, 0])\n                    T.writes(BL[0, 0])\n                    BL[0, 0] = BS[tx, 0]\n                with T.block():\n                    T.reads(AL[0, 0], BL[0, 0])\n                    T.writes(C[tx, i])\n                    C[tx, i] = AL[0, 0] * BL[0, 0]\n\n\n@T.prim_func\ndef transformed_dag_interleaving(\n    A: T.Buffer[(16, 16), \"float32\"],\n    B: T.Buffer[(16, 16), \"float32\"],\n    C: T.Buffer[(16, 16), \"float32\"],\n) -> None:\n    for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads(A[tx, 0:16], B[tx, 0:16])\n            T.writes(C[tx, 0:16])\n            AS = T.alloc_buffer([16, 1], dtype=\"float32\", scope=\"shared\")\n            BS = T.alloc_buffer([16, 1], dtype=\"float32\", scope=\"shared\")\n            AL = T.alloc_buffer([2, 1, 1], dtype=\"float32\", scope=\"local\")\n            BL = T.alloc_buffer([2, 1, 1], dtype=\"float32\", scope=\"local\")\n            with T.block():\n                T.reads(A[tx, 0], B[tx, 0], AS[tx, 0], BS[tx, 0])\n                T.writes(AS[tx, 0], BS[tx, 0], AL[0, 0, 0], BL[0, 0, 0])\n                with T.block():\n                    T.reads(A[tx, 0])\n                    T.writes(AS[tx, 0])\n                    AS[tx, 0] = A[tx, 0] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(BS[tx, 0])\n                    BS[tx, 0] = B[tx, 0] + T.float32(2)\n                with T.block():\n                    T.reads(AS[tx, 0])\n                    T.writes(AL[0, 0, 0])\n                    AL[0, 0, 0] = AS[tx, 0]\n                with T.block():\n                    T.reads(BS[tx, 0])\n                    T.writes(BL[0, 0, 0])\n                    BL[0, 0, 0] = BS[tx, 0]\n            with T.block():\n                T.reads(\n                    A[tx, 1:16], B[tx, 1:16], AS[tx, 0], BS[tx, 0], AL[0:2, 0, 0], BL[0:2, 0, 0]\n                )\n                T.writes(AS[tx, 0], BS[tx, 0], AL[0:2, 0, 0], BL[0:2, 0, 0], C[tx, 0:15])\n                for i in T.serial(15):\n                    with T.block():\n                        T.reads(A[tx, i + 1])\n                        T.writes(AS[tx, 0])\n                        AS[tx, 0] = A[tx, i + 1] * T.float32(2)\n                    with T.block():\n                        T.reads(B[tx, i + 1])\n                        T.writes(BS[tx, 0])\n                        BS[tx, 0] = B[tx, i + 1] + T.float32(2)\n                    with T.block():\n                        T.reads(AS[tx, 0])\n                        T.writes(AL[(i + 1) % 2, 0, 0])\n                        AL[(i + 1) % 2, 0, 0] = AS[tx, 0]\n                    with T.block():\n                        T.reads(BS[tx, 0])\n                        T.writes(BL[(i + 1) % 2, 0, 0])\n                        BL[(i + 1) % 2, 0, 0] = BS[tx, 0]\n                    with T.block():\n                        T.reads(AL[i % 2, 0, 0], BL[i % 2, 0, 0])\n                        T.writes(C[tx, i])\n                        C[tx, i] = AL[i % 2, 0, 0] * BL[i % 2, 0, 0]\n            with T.block():\n                T.reads(AL[1, 0, 0], BL[1, 0, 0])\n                T.writes(C[tx, 15])\n                C[tx, 15] = AL[1, 0, 0] * BL[1, 0, 0]\n\n\n@T.prim_func\ndef nested_pipeline_simple(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 1, 1, 1],\n                \"software_pipeline_order\": [0, 1, 2, 3],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i, 0:16])\n                T.writes(C[tx, i, 0:16])\n                A_shared = T.alloc_buffer((16, 1, 16), dtype=\"float32\", scope=\"shared\")\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads(A[tx, i, j])\n                        T.writes(A_shared[tx, 0, j])\n                        A_shared[tx, 0, j] = A[tx, i, j]\n                for j in T.serial(\n                    0,\n                    16,\n                    annotations={\n                        \"software_pipeline_stage\": [0, 1],\n                        \"software_pipeline_order\": [0, 1],\n                    },\n                ):\n                    with T.block():\n                        T.reads(A_shared[tx, 0, j])\n                        T.writes(C[tx, i, j])\n                        B = T.alloc_buffer((16, 1, 1), dtype=\"float32\", scope=\"shared\")\n                        with T.block():\n                            T.reads(A_shared[tx, i, j])\n                            T.writes(B[tx, i, 0])\n                            B[tx, i, 0] = A_shared[tx, 0, j] * T.float32(2)\n                        with T.block():\n                            T.reads(B[tx, i, 0])\n                            T.writes(C[tx, i, j])\n                            C[tx, i, j] = B[tx, i, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_nested_pipeline_simple(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16, 0:16]])\n            T.writes([C[tx, 0:16, 0:16]])\n            A_shared = T.alloc_buffer([2, 16, 1, 16], dtype=\"float32\", scope=\"shared\")\n            B = T.alloc_buffer([2, 16, 1, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0, 0:16]])\n                T.writes([A_shared[0, tx, 0, 0:16]])\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads([A[tx, 0, j]])\n                        T.writes([A_shared[0, tx, 0, j]])\n                        A_shared[0, tx, 0, j] = A[tx, 0, j]\n            with T.block():\n                T.reads([A[tx, 1:16, 0:16], A_shared[0:2, tx, 0:15, 0:16], B[0:2, tx, 0:15, 0]])\n                T.writes([A_shared[0:2, tx, 0, 0:16], B[0:2, tx, 0:15, 0], C[tx, 0:15, 0:16]])\n                for i in T.serial(0, 15):\n                    with T.block():\n                        T.reads([A[tx, i + 1, 0:16]])\n                        T.writes([A_shared[(i + 1) % 2, tx, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A[tx, i + 1, j]])\n                                T.writes([A_shared[(i + 1) % 2, tx, 0, j]])\n                                A_shared[(i + 1) % 2, tx, 0, j] = A[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_shared[i % 2, tx, i, 0]])\n                        T.writes([B[0, tx, i, 0]])\n                        B[0, tx, i, 0] = A_shared[i % 2, tx, 0, 0] * T.float32(2)\n                    with T.block():\n                        T.reads([A_shared[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]])\n                        T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]])\n                        for j in T.serial(0, 15):\n                            with T.block():\n                                T.reads([A_shared[i % 2, tx, i, j + 1]])\n                                T.writes([B[(j + 1) % 2, tx, i, 0]])\n                                B[(j + 1) % 2, tx, i, 0] = A_shared[\n                                    i % 2, tx, 0, j + 1\n                                ] * T.float32(2)\n                            with T.block():\n                                T.reads([B[j % 2, tx, i, 0]])\n                                T.writes([C[tx, i, j]])\n                                C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1)\n                    with T.block():\n                        T.reads([B[1, tx, i, 0]])\n                        T.writes([C[tx, i, 15]])\n                        C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1)\n            with T.block():\n                T.reads([A_shared[1, tx, 15, 0:16], B[0:2, tx, 15, 0]])\n                T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]])\n                with T.block():\n                    T.reads([A_shared[1, tx, 15, 0]])\n                    T.writes([B[0, tx, 15, 0]])\n                    B[0, tx, 15, 0] = A_shared[1, tx, 0, 0] * T.float32(2)\n                with T.block():\n                    T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                    T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]])\n                    for j in T.serial(0, 15):\n                        with T.block():\n                            T.reads([A_shared[1, tx, 15, j + 1]])\n                            T.writes([B[(j + 1) % 2, tx, 15, 0]])\n                            B[(j + 1) % 2, tx, 15, 0] = A_shared[1, tx, 0, j + 1] * T.float32(2)\n                        with T.block():\n                            T.reads([B[j % 2, tx, 15, 0]])\n                            T.writes([C[tx, 15, j]])\n                            C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1)\n                with T.block():\n                    T.reads([B[1, tx, 15, 0]])\n                    T.writes([C[tx, 15, 15]])\n                    C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1)\n\n\n@T.prim_func\ndef nested_pipeline_prefetch_inner(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 0, 1, 1],\n                \"software_pipeline_order\": [0, 2, 1, 3],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i, 0:16])\n                T.writes(C[tx, i, 0:16])\n                A_shared = T.alloc_buffer((16, 1, 16), dtype=\"float32\", scope=\"shared\")\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads(A[tx, i, j])\n                        T.writes(A_shared[tx, 0, j])\n                        A_shared[tx, 0, j] = A[tx, i, j]\n                for j in T.serial(\n                    0,\n                    16,\n                    annotations={\n                        \"software_pipeline_stage\": [0, 1],\n                        \"software_pipeline_order\": [0, 1],\n                    },\n                ):\n                    with T.block():\n                        T.reads(A_shared[tx, 0, j])\n                        T.writes(C[tx, i, j])\n                        B = T.alloc_buffer((16, 1, 1), dtype=\"float32\", scope=\"shared\")\n                        with T.block():\n                            T.reads(A_shared[tx, i, j])\n                            T.writes(B[tx, i, 0])\n                            B[tx, i, 0] = A_shared[tx, 0, j] * T.float32(2)\n                        with T.block():\n                            T.reads(B[tx, i, 0])\n                            T.writes(C[tx, i, j])\n                            C[tx, i, j] = B[tx, i, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_nested_pipeline_prefetch_inner(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16, 0:16]])\n            T.writes([C[tx, 0:16, 0:16]])\n            A_shared = T.alloc_buffer([2, 16, 1, 16], dtype=\"float32\", scope=\"shared\")\n            B = T.alloc_buffer([2, 16, 1, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0, 0:16], A_shared[0, tx, 0, 0]])\n                T.writes([A_shared[0, tx, 0, 0:16], B[0, tx, 0, 0]])\n                with T.block():\n                    T.reads([A[tx, 0, 0:16]])\n                    T.writes([A_shared[0, tx, 0, 0:16]])\n                    for j in T.serial(0, 16):\n                        with T.block():\n                            T.reads([A[tx, 0, j]])\n                            T.writes([A_shared[0, tx, 0, j]])\n                            A_shared[0, tx, 0, j] = A[tx, 0, j]\n                with T.block():\n                    T.reads([A_shared[0, tx, 0, 0]])\n                    T.writes([B[0, tx, 0, 0]])\n                    B[0, tx, 0, 0] = A_shared[0, tx, 0, 0] * T.float32(2)\n            with T.block():\n                T.reads([A[tx, 1:16, 0:16], A_shared[0:2, tx, 0:16, 0:16], B[0:2, tx, 0:15, 0]])\n                T.writes([A_shared[0:2, tx, 0, 0:16], B[0:2, tx, 0:16, 0], C[tx, 0:15, 0:16]])\n                for i in T.serial(0, 15):\n                    with T.block():\n                        T.reads([A[tx, i + 1, 0:16]])\n                        T.writes([A_shared[(i + 1) % 2, tx, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A[tx, i + 1, j]])\n                                T.writes([A_shared[(i + 1) % 2, tx, 0, j]])\n                                A_shared[(i + 1) % 2, tx, 0, j] = A[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_shared[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]])\n                        T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]])\n                        for j in T.serial(0, 15):\n                            with T.block():\n                                T.reads([A_shared[i % 2, tx, i, j + 1]])\n                                T.writes([B[(j + 1) % 2, tx, i, 0]])\n                                B[(j + 1) % 2, tx, i, 0] = A_shared[\n                                    i % 2, tx, 0, j + 1\n                                ] * T.float32(2)\n                            with T.block():\n                                T.reads([B[j % 2, tx, i, 0]])\n                                T.writes([C[tx, i, j]])\n                                C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1)\n                    with T.block():\n                        T.reads([A_shared[(i + 1) % 2, tx, i + 1, 0]])\n                        T.writes([B[0, tx, i + 1, 0]])\n                        B[0, tx, i + 1, 0] = A_shared[(i + 1) % 2, tx, 0, 0] * T.float32(2)\n                    with T.block():\n                        T.reads([B[1, tx, i, 0]])\n                        T.writes([C[tx, i, 15]])\n                        C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1)\n            with T.block():\n                T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]])\n                with T.block():\n                    T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                    T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]])\n                    for j in T.serial(0, 15):\n                        with T.block():\n                            T.reads([A_shared[1, tx, 15, j + 1]])\n                            T.writes([B[(j + 1) % 2, tx, 15, 0]])\n                            B[(j + 1) % 2, tx, 15, 0] = A_shared[1, tx, 0, j + 1] * T.float32(2)\n                        with T.block():\n                            T.reads([B[j % 2, tx, 15, 0]])\n                            T.writes([C[tx, 15, j]])\n                            C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1)\n                with T.block():\n                    T.reads([B[1, tx, 15, 0]])\n                    T.writes([C[tx, 15, 15]])\n                    C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1)\n\n\n@T.prim_func\ndef nested_pipeline_interleaving(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 0, 0, 1, 1],\n                \"software_pipeline_order\": [0, 2, 3, 1, 4],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i, 0:16])\n                T.writes(C[tx, i, 0:16])\n                A_shared = T.alloc_buffer((16, 1, 16), dtype=\"float32\", scope=\"shared\")\n                A_local = T.alloc_buffer((1, 1, 16), dtype=\"float32\", scope=\"local\")\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads(A[tx, i, j])\n                        T.writes(A_shared[tx, 0, j])\n                        A_shared[tx, 0, j] = A[tx, i, j]\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads(A_shared[tx, 0, j])\n                        T.writes(A_local[0, 0, j])\n                        A_local[0, 0, j] = A_shared[tx, i, j]\n                for j in T.serial(\n                    0,\n                    16,\n                    annotations={\n                        \"software_pipeline_stage\": [0, 1],\n                        \"software_pipeline_order\": [0, 1],\n                    },\n                ):\n                    with T.block():\n                        T.reads(A_local[0, 0, j])\n                        T.writes(C[tx, i, j])\n                        B = T.alloc_buffer((16, 1, 1), dtype=\"float32\", scope=\"shared\")\n                        with T.block():\n                            T.reads(A_local[tx, i, j])\n                            T.writes(B[tx, i, 0])\n                            B[tx, i, 0] = A_local[0, 0, j] * T.float32(2)\n                        with T.block():\n                            T.reads(B[tx, i, 0])\n                            T.writes(C[tx, i, j])\n                            C[tx, i, j] = B[tx, i, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_nested_pipeline_interleaving(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16, 0:16]])\n            T.writes([C[tx, 0:16, 0:16]])\n            A_shared = T.alloc_buffer([16, 1, 16], dtype=\"float32\", scope=\"shared\")\n            A_local = T.alloc_buffer([1, 1, 16], dtype=\"float32\", scope=\"local\")\n            B = T.alloc_buffer([2, 16, 1, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0, 0:16], A_shared[tx, 0, 0:16], A_local[tx, 0, 0]])\n                T.writes([A_shared[tx, 0, 0:16], A_local[0, 0, 0:16], B[0, tx, 0, 0]])\n                with T.block():\n                    T.reads([A[tx, 0, 0:16]])\n                    T.writes([A_shared[tx, 0, 0:16]])\n                    for j in T.serial(0, 16):\n                        with T.block():\n                            T.reads([A[tx, 0, j]])\n                            T.writes([A_shared[tx, 0, j]])\n                            A_shared[tx, 0, j] = A[tx, 0, j]\n                with T.block():\n                    T.reads([A_shared[tx, 0, 0:16]])\n                    T.writes([A_local[0, 0, 0:16]])\n                    for j in T.serial(0, 16):\n                        with T.block():\n                            T.reads([A_shared[tx, 0, j]])\n                            T.writes([A_local[0, 0, j]])\n                            A_local[0, 0, j] = A_shared[tx, 0, j]\n                with T.block():\n                    T.reads([A_local[tx, 0, 0]])\n                    T.writes([B[0, tx, 0, 0]])\n                    B[0, tx, 0, 0] = A_local[0, 0, 0] * T.float32(2)\n            with T.block():\n                T.reads(\n                    [\n                        A[tx, 1:16, 0:16],\n                        A_local[tx, 0:16, 0:16],\n                        B[0:2, tx, 0:15, 0],\n                        A_shared[tx, 0, 0:16],\n                    ]\n                )\n                T.writes(\n                    [\n                        A_shared[tx, 0, 0:16],\n                        B[0:2, tx, 0:16, 0],\n                        C[tx, 0:15, 0:16],\n                        A_local[0, 0, 0:16],\n                    ]\n                )\n                for i in T.serial(0, 15):\n                    with T.block():\n                        T.reads([A[tx, i + 1, 0:16]])\n                        T.writes([A_shared[tx, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A[tx, i + 1, j]])\n                                T.writes([A_shared[tx, 0, j]])\n                                A_shared[tx, 0, j] = A[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_local[tx, i, 1:16], B[0:2, tx, i, 0]])\n                        T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]])\n                        for j in T.serial(0, 15):\n                            with T.block():\n                                T.reads([A_local[tx, i, j + 1]])\n                                T.writes([B[(j + 1) % 2, tx, i, 0]])\n                                B[(j + 1) % 2, tx, i, 0] = A_local[0, 0, j + 1] * T.float32(2)\n                            with T.block():\n                                T.reads([B[j % 2, tx, i, 0]])\n                                T.writes([C[tx, i, j]])\n                                C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1)\n                    with T.block():\n                        T.reads([A_shared[tx, 0, 0:16]])\n                        T.writes([A_local[0, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A_shared[tx, 0, j]])\n                                T.writes([A_local[0, 0, j]])\n                                A_local[0, 0, j] = A_shared[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_local[tx, i + 1, 0]])\n                        T.writes([B[0, tx, i + 1, 0]])\n                        B[0, tx, i + 1, 0] = A_local[0, 0, 0] * T.float32(2)\n                    with T.block():\n                        T.reads([B[1, tx, i, 0]])\n                        T.writes([C[tx, i, 15]])\n                        C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1)\n            with T.block():\n                T.reads([A_local[tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]])\n                with T.block():\n                    T.reads([A_local[tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                    T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]])\n                    for j in T.serial(0, 15):\n                        with T.block():\n                            T.reads([A_local[tx, 15, j + 1]])\n                            T.writes([B[(j + 1) % 2, tx, 15, 0]])\n                            B[(j + 1) % 2, tx, 15, 0] = A_local[0, 0, j + 1] * T.float32(2)\n                        with T.block():\n                            T.reads([B[j % 2, tx, 15, 0]])\n                            T.writes([C[tx, 15, j]])\n                            C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1)\n                with T.block():\n                    T.reads([B[1, tx, 15, 0]])\n                    T.writes([C[tx, 15, 15]])\n                    C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1)\n\n\n@T.prim_func\ndef nested_pipeline_double_buffer(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 0, 0, 1, 1],\n                \"software_pipeline_order\": [0, 2, 3, 1, 4],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i, 0:16])\n                T.writes(C[tx, i, 0:16])\n                A_shared = T.alloc_buffer((16, 1, 16), dtype=\"float32\", scope=\"shared\")\n                A_local = T.alloc_buffer((1, 1, 16), dtype=\"float32\", scope=\"local\")\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.reads(A[tx, i, j])\n                        T.writes(A_shared[tx, 0, j])\n                        A_shared[tx, 0, j] = A[tx, i, j]\n                for j in T.serial(0, 16):\n                    with T.block():\n                        T.block_attr({\"double_buffer_scope\": 0})\n                        T.reads(A_shared[tx, 0, j])\n                        T.writes(A_local[0, 0, j])\n                        A_local[0, 0, j] = A_shared[tx, i, j]\n                for j in T.serial(\n                    0,\n                    16,\n                    annotations={\n                        \"software_pipeline_stage\": [0, 1],\n                        \"software_pipeline_order\": [0, 1],\n                    },\n                ):\n                    with T.block():\n                        T.reads(A_local[0, 0, j])\n                        T.writes(C[tx, i, j])\n                        B = T.alloc_buffer((16, 1, 1), dtype=\"float32\", scope=\"shared\")\n                        with T.block():\n                            T.reads(A_local[tx, i, j])\n                            T.writes(B[tx, i, 0])\n                            B[tx, i, 0] = A_local[0, 0, j] * T.float32(2)\n                        with T.block():\n                            T.reads(B[tx, i, 0])\n                            T.writes(C[tx, i, j])\n                            C[tx, i, j] = B[tx, i, 0] + T.float32(1)\n\n\n@T.prim_func\ndef transformed_nested_pipeline_double_buffer(\n    A: T.Buffer[(16, 16, 16), \"float32\"], C: T.Buffer[(16, 16, 16), \"float32\"]\n) -> None:\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        with T.block():\n            T.reads([A[tx, 0:16, 0:16]])\n            T.writes([C[tx, 0:16, 0:16]])\n            A_shared = T.alloc_buffer([16, 1, 16], dtype=\"float32\", scope=\"shared\")\n            A_local = T.alloc_buffer([2, 1, 1, 16], dtype=\"float32\", scope=\"local\")\n            B = T.alloc_buffer([2, 16, 1, 1], dtype=\"float32\", scope=\"shared\")\n            with T.block():\n                T.reads([A[tx, 0, 0:16], A_shared[tx, 0, 0:16], A_local[0, tx, 0, 0]])\n                T.writes([A_shared[tx, 0, 0:16], A_local[0, 0, 0, 0:16], B[0, tx, 0, 0]])\n                with T.block():\n                    T.reads([A[tx, 0, 0:16]])\n                    T.writes([A_shared[tx, 0, 0:16]])\n                    for j in T.serial(0, 16):\n                        with T.block():\n                            T.reads([A[tx, 0, j]])\n                            T.writes([A_shared[tx, 0, j]])\n                            A_shared[tx, 0, j] = A[tx, 0, j]\n                with T.block():\n                    T.reads([A_shared[tx, 0, 0:16]])\n                    T.writes([A_local[0, 0, 0, 0:16]])\n                    for j in T.serial(0, 16):\n                        with T.block():\n                            T.reads([A_shared[tx, 0, j]])\n                            T.writes([A_local[0, 0, 0, j]])\n                            T.block_attr({\"double_buffer_scope\": 0})\n                            A_local[0, 0, 0, j] = A_shared[tx, 0, j]\n                with T.block():\n                    T.reads([A_local[0, tx, 0, 0]])\n                    T.writes([B[0, tx, 0, 0]])\n                    B[0, tx, 0, 0] = A_local[0, 0, 0, 0] * T.float32(2)\n            with T.block():\n                T.reads(\n                    [\n                        A[tx, 1:16, 0:16],\n                        A_local[0:2, tx, 0:16, 0:16],\n                        B[0:2, tx, 0:15, 0],\n                        A_shared[tx, 0, 0:16],\n                    ]\n                )\n                T.writes(\n                    [\n                        A_shared[tx, 0, 0:16],\n                        B[0:2, tx, 0:16, 0],\n                        C[tx, 0:15, 0:16],\n                        A_local[0:2, 0, 0, 0:16],\n                    ]\n                )\n                for i in T.serial(0, 15):\n                    with T.block():\n                        T.reads([A[tx, i + 1, 0:16]])\n                        T.writes([A_shared[tx, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A[tx, i + 1, j]])\n                                T.writes([A_shared[tx, 0, j]])\n                                A_shared[tx, 0, j] = A[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_local[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]])\n                        T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]])\n                        for j in T.serial(0, 15):\n                            with T.block():\n                                T.reads([A_local[i % 2, tx, i, j + 1]])\n                                T.writes([B[(j + 1) % 2, tx, i, 0]])\n                                B[(j + 1) % 2, tx, i, 0] = A_local[i % 2, 0, 0, j + 1] * T.float32(\n                                    2\n                                )\n                            with T.block():\n                                T.reads([B[j % 2, tx, i, 0]])\n                                T.writes([C[tx, i, j]])\n                                C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1)\n                    with T.block():\n                        T.reads([A_shared[tx, 0, 0:16]])\n                        T.writes([A_local[(i + 1) % 2, 0, 0, 0:16]])\n                        for j in T.serial(0, 16):\n                            with T.block():\n                                T.reads([A_shared[tx, 0, j]])\n                                T.writes([A_local[(i + 1) % 2, 0, 0, j]])\n                                T.block_attr({\"double_buffer_scope\": 0})\n                                A_local[(i + 1) % 2, 0, 0, j] = A_shared[tx, i + 1, j]\n                    with T.block():\n                        T.reads([A_local[(i + 1) % 2, tx, i + 1, 0]])\n                        T.writes([B[0, tx, i + 1, 0]])\n                        B[0, tx, i + 1, 0] = A_local[(i + 1) % 2, 0, 0, 0] * T.float32(2)\n                    with T.block():\n                        T.reads([B[1, tx, i, 0]])\n                        T.writes([C[tx, i, 15]])\n                        C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1)\n            with T.block():\n                T.reads([A_local[1, tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]])\n                with T.block():\n                    T.reads([A_local[1, tx, 15, 1:16], B[0:2, tx, 15, 0]])\n                    T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]])\n                    for j in T.serial(0, 15):\n                        with T.block():\n                            T.reads([A_local[1, tx, 15, j + 1]])\n                            T.writes([B[(j + 1) % 2, tx, 15, 0]])\n                            B[(j + 1) % 2, tx, 15, 0] = A_local[1, 0, 0, j + 1] * T.float32(2)\n                        with T.block():\n                            T.reads([B[j % 2, tx, 15, 0]])\n                            T.writes([C[tx, 15, j]])\n                            C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1)\n                with T.block():\n                    T.reads([B[1, tx, 15, 0]])\n                    T.writes([C[tx, 15, 15]])\n                    C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1)\n\n\n@T.prim_func\ndef simple_compute_incorrect_reorder(\n    A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 1, 1],\n                \"software_pipeline_order\": [0, 2, 1],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i])\n                T.writes(D[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                C = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, 0])\n                    C[tx, 0] = B[tx, 0] + T.float32(2)\n                with T.block():\n                    T.reads(C[tx, 0])\n                    T.writes(D[tx, i])\n                    D[tx, i] = C[tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef simple_compute_conflicting_order(\n    A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(\n            0,\n            16,\n            annotations={\n                \"software_pipeline_stage\": [0, 1, 1],\n                \"software_pipeline_order\": [0, 1, 1],\n            },\n        ):\n            with T.block():\n                T.reads(A[tx, i])\n                T.writes(D[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                C = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, 0])\n                    C[tx, 0] = B[tx, 0] + T.float32(2)\n                with T.block():\n                    T.reads(C[tx, 0])\n                    T.writes(D[tx, i])\n                    D[tx, i] = C[tx, 0] + T.float32(1)\n\n\n@T.prim_func\ndef simple_compute_missing_annotation(\n    A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]\n):\n    for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n        for i in T.serial(0, 16, annotations={\"software_pipeline_stage\": [0, 1]}):\n            with T.block():\n                T.reads(A[tx, i])\n                T.writes(C[tx, i])\n                B = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, i])\n                    T.writes(B[tx, 0])\n                    B[tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(B[tx, 0])\n                    T.writes(C[tx, i])\n                    C[tx, i] = B[tx, 0] + T.float32(1)\n\n\ndef test_simple_compute():\n    _check(gen_simple_compute(1), transformed_simple_compute)\n\n\ndef test_simple_compute_with_other_annotation():\n    _check(simple_compute_with_other_annotation, transformed_simple_compute_with_other_annotation)\n\n\ndef test_trivial_pipeline():\n    _check(trivial_pipeline, transformed_trivial_pipeline)\n\n\ndef test_three_stage_compute():\n    _check(three_stage_compute, transformed_three_stage_compute)\n\n\ndef test_dag_interleaving():\n    _check(dag_interleaving, transformed_dag_interleaving)\n\n\ndef test_nest_pipeline_simple():\n    _check(nested_pipeline_simple, transformed_nested_pipeline_simple)\n\n\ndef test_nest_pipeline_prefetch_inner():\n    _check(nested_pipeline_prefetch_inner, transformed_nested_pipeline_prefetch_inner)\n\n\ndef test_nest_pipeline_interleaving():\n    _check(nested_pipeline_interleaving, transformed_nested_pipeline_interleaving)\n\n\ndef test_nest_pipeline_double_buffer():\n    _check(nested_pipeline_double_buffer, transformed_nested_pipeline_double_buffer)\n\n\ndef test_error_reorder():\n    _check_error(simple_compute_incorrect_reorder)\n\n\ndef test_error_conflicting_order():\n    _check_error(simple_compute_conflicting_order)\n\n\ndef test_error_missing_annotation():\n    _check_error(simple_compute_missing_annotation)\n\n\ndef test_simple_compute_async():\n    mod = tvm.IRModule.from_expr(gen_simple_compute(1))\n    sch = tvm.tir.Schedule(mod)\n\n    _, loop = sch.get_loops(sch.get_block(\"compute\"))\n    sch.annotate(loop, ann_key=\"software_pipeline_async_stages\", ann_val=[0])\n    mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod)\n\n    @T.prim_func\n    def ref(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]):\n        for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n            with T.block():\n                T.reads(A[tx, 0:16])\n                T.writes(C[tx, 0:16])\n                B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, 0])\n                    T.writes(B[0, tx, 0])\n                    with T.attr(0, \"async_commit_queue_scope\", 0):\n                        with T.attr(0, \"async_scope\", 1):\n                            B[T.FloorMod(0, 2), tx, 0] = A[tx, 0] * T.float32(2)\n                with T.block():\n                    T.reads(A[tx, 1:16], B[0:2, tx, 0])\n                    T.writes(B[0:2, tx, 0], C[tx, 0:15])\n                    for i in T.serial(15):\n                        with T.block():\n                            T.where(i + 1 < 16)\n                            T.reads(A[tx, i + 1])\n                            T.writes(B[(i + 1) % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2)\n                        with T.block():\n                            T.where(i + 1 - 1 < 16)\n                            T.reads(B[(i - 1 + 1) % 2, tx, 0])\n                            T.writes(C[tx, i - 1 + 1])\n                            with T.attr(0, \"async_wait_queue_scope\", 0):\n                                with T.attr(0, \"async_wait_inflight_count\", 1):\n                                    C[tx, i - 1 + 1] = B[(i - 1 + 1) % 2, tx, 0] + T.float32(1)\n                with T.block():\n                    T.reads(B[T.FloorMod(15, 2), tx, 0])\n                    T.writes(C[tx, 15])\n                    with T.attr(0, \"async_wait_queue_scope\", 0):\n                        with T.attr(0, \"async_wait_inflight_count\", 0):\n                            C[tx, 15] = B[T.FloorMod(15, 2), tx, 0] + T.float32(1)\n\n    tvm.ir.assert_structural_equal(mod[\"main\"], ref, True)\n\n    mod = tvm.IRModule.from_expr(gen_simple_compute(3))\n    sch = tvm.tir.Schedule(mod)\n\n    _, loop = sch.get_loops(sch.get_block(\"compute\"))\n    sch.annotate(loop, ann_key=\"software_pipeline_async_stages\", ann_val=[0])\n    mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod)\n\n    @T.prim_func\n    def ref(A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]) -> None:\n        for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n            with T.block():\n                T.reads(A[tx, 0:16])\n                T.writes(C[tx, 0:16])\n                B = T.alloc_buffer([4, 16, 1], dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, 0:3])\n                    T.writes(B[0:3, tx, 0])\n                    for i in T.unroll(3):\n                        with T.block():\n                            T.where(i < 16)\n                            T.reads(A[tx, i])\n                            T.writes(B[i % 4, tx, 0])\n                            T.attr(0, \"async_commit_queue_scope\", 0)\n                            T.attr(0, \"async_scope\", 1)\n                            B[i % 4, tx, 0] = A[tx, i] * T.float32(2)\n                with T.block():\n                    T.reads(A[tx, 3:16], B[0:4, tx, 0])\n                    T.writes(B[0:4, tx, 0], C[tx, 0:13])\n                    for i in T.serial(13):\n                        with T.block():\n                            T.where(i + 3 < 16)\n                            T.reads(A[tx, i + 3])\n                            T.writes(B[(i + 3) % 4, tx, 0])\n                            T.attr(0, \"async_commit_queue_scope\", 0)\n                            T.attr(0, \"async_scope\", 1)\n                            B[(i + 3) % 4, tx, 0] = A[tx, i + 3] * T.float32(2)\n                        with T.block():\n                            T.where(i + 3 - 3 < 16)\n                            T.reads(B[0:4, tx, 0])\n                            T.writes(C[tx, i - 3 + 3])\n                            with T.attr(0, \"async_wait_queue_scope\", 0):\n                                with T.attr(0, \"async_wait_inflight_count\", 3):\n                                    C[tx, i - 3 + 3] = B[(i - 3 + 3) % 4, tx, 0] + T.float32(1)\n                with T.block():\n                    T.reads(B[0:4, tx, 0])\n                    T.writes(C[tx, 13:16])\n                    for i in T.unroll(3):\n                        with T.block():\n                            T.where(i + 16 - 3 < 16)\n                            T.reads(B[0:4, tx, 0])\n                            T.writes(C[tx, i - 3 + 16])\n                            with T.attr(0, \"async_wait_queue_scope\", 0):\n                                with T.attr(0, \"async_wait_inflight_count\", 2 - i):\n                                    C[tx, i - 3 + 16] = B[(i - 3 + 16) % 4, tx, 0] + T.float32(1)\n\n    tvm.ir.assert_structural_equal(mod[\"main\"], ref, True)\n\n\ndef test_async_producer_interleaving():\n    @T.prim_func\n    def simple_compute(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 16), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ):\n        for tx in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n            for i in range(16):\n                with T.block(\"compute\"):\n                    T.reads(A[tx, i])\n                    T.writes(C[tx, i])\n                    A_shared = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                    B_shared = T.alloc_buffer((16, 1), dtype=\"float32\", scope=\"shared\")\n                    with T.block():\n                        T.reads(A[tx, i])\n                        T.writes(A_shared[tx, 0])\n                        A_shared[tx, 0] = A[tx, i]\n                    with T.block():\n                        T.reads(B[tx, i])\n                        T.writes(B_shared[tx, 0])\n                        B_shared[tx, 0] = B[tx, i]\n                    with T.block():\n                        T.reads(A_shared[tx, 0], B_shared[tx, 0])\n                        T.writes(C[tx, i])\n                        C[tx, i] = A_shared[tx, 0] + B_shared[tx, 0]\n\n    mod = tvm.IRModule.from_expr(simple_compute)\n    sch = tvm.tir.Schedule(mod)\n\n    _, loop = sch.get_loops(sch.get_block(\"compute\"))\n    sch.annotate(loop, ann_key=\"software_pipeline_stage\", ann_val=[0, 0, 3])\n    sch.annotate(loop, ann_key=\"software_pipeline_order\", ann_val=[0, 2, 1])\n    sch.annotate(loop, ann_key=\"software_pipeline_async_stages\", ann_val=[0])\n    mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod)\n\n    @T.prim_func\n    def ref(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 16), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n            with T.block():\n                T.reads(A[tx, 0:16], B[tx, 0:16])\n                T.writes(C[tx, 0:16])\n                A_shared = T.alloc_buffer([4, 16, 1], dtype=\"float32\", scope=\"shared\")\n                B_shared = T.alloc_buffer([4, 16, 1], dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, 0:3], B[tx, 0:3])\n                    T.writes(A_shared[0:3, tx, 0], B_shared[0:3, tx, 0])\n                    for i in T.unroll(3):\n                        with T.block():\n                            T.where(i < 16)\n                            T.reads(A[tx, i], B[tx, i])\n                            T.writes(A_shared[i % 4, tx, 0], B_shared[i % 4, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    A_shared[i % 4, tx, 0] = A[tx, i]\n                                with T.attr(0, \"async_scope\", 1):\n                                    B_shared[i % 4, tx, 0] = B[tx, i]\n                with T.block():\n                    T.reads(A[tx, 3:16], A_shared[0:4, tx, 0], B_shared[0:4, tx, 0], B[tx, 3:16])\n                    T.writes(A_shared[0:4, tx, 0], C[tx, 0:13], B_shared[0:4, tx, 0])\n                    for i in T.serial(13):\n                        with T.block():\n                            T.where(i + 3 < 16)\n                            T.reads(A[tx, i + 3])\n                            T.writes(A_shared[(i + 3) % 4, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    A_shared[(i + 3) % 4, tx, 0] = A[tx, i + 3]\n                        with T.block():\n                            T.where(i + 3 - 3 < 16)\n                            T.reads(A_shared[0:4, tx, 0], B_shared[0:4, tx, 0])\n                            T.writes(C[tx, i - 3 + 3])\n                            with T.attr(0, \"async_wait_queue_scope\", 0):\n                                with T.attr(0, \"async_wait_inflight_count\", 5):\n                                    C[tx, i - 3 + 3] = (\n                                        A_shared[(i - 3 + 3) % 4, tx, 0]\n                                        + B_shared[(i - 3 + 3) % 4, tx, 0]\n                                    )\n                        with T.block():\n                            T.where(i + 3 < 16)\n                            T.reads(B[tx, i + 3])\n                            T.writes(B_shared[(i + 3) % 4, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    B_shared[(i + 3) % 4, tx, 0] = B[tx, i + 3]\n                with T.block():\n                    T.reads(A_shared[0:4, tx, 0], B_shared[0:4, tx, 0])\n                    T.writes(C[tx, 13:16])\n                    for i in T.unroll(3):\n                        with T.block():\n                            T.where(i + 16 - 3 < 16)\n                            T.reads(A_shared[0:4, tx, 0], B_shared[0:4, tx, 0])\n                            T.writes(C[tx, i - 3 + 16])\n                            with T.attr(0, \"async_wait_queue_scope\", 0):\n                                with T.attr(0, \"async_wait_inflight_count\", 2 - i):\n                                    C[tx, i - 3 + 16] = (\n                                        A_shared[(i - 3 + 16) % 4, tx, 0]\n                                        + B_shared[(i - 3 + 16) % 4, tx, 0]\n                                    )\n\n    tvm.ir.assert_structural_equal(mod[\"main\"], ref, True)\n\n\ndef test_three_stage_compute_two_stage_async():\n    mod = tvm.IRModule.from_expr(three_stage_compute)\n    sch = tvm.tir.Schedule(mod)\n\n    _, loop = sch.get_loops(sch.get_block(\"compute\"))\n    sch.annotate(loop, ann_key=\"software_pipeline_async_stages\", ann_val=[0, 1])\n\n    mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod)\n\n    @T.prim_func\n    def ref(A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]) -> None:\n        for tx in T.thread_binding(16, thread=\"threadIdx.x\"):\n            with T.block():\n                T.reads(A[tx, 0:16])\n                T.writes(D[tx, 0:16])\n                B = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n                C = T.alloc_buffer([2, 16, 1], dtype=\"float32\", scope=\"shared\")\n                with T.block():\n                    T.reads(A[tx, 0:2], B[0:2, tx, 0])\n                    T.writes(B[0:2, tx, 0], C[0:2, tx, 0])\n                    for i in T.unroll(2):\n                        with T.block():\n                            T.where(i < 16)\n                            T.reads(A[tx, i])\n                            T.writes(B[i % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    B[i % 2, tx, 0] = A[tx, i] * T.float32(2)\n                        with T.block():\n                            T.where(i == 1 and i - 1 < 16)\n                            T.reads(B[(i + 1) % 2, tx, 0])\n                            T.writes(C[(i + 1) % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 1):\n                                with T.attr(0, \"async_wait_queue_scope\", 0):\n                                    with T.attr(0, \"async_wait_inflight_count\", 1):\n                                        with T.attr(0, \"async_scope\", 1):\n                                            C[(i - 1) % 2, tx, 0] = B[\n                                                (i - 1) % 2, tx, 0\n                                            ] + T.float32(2)\n                with T.block():\n                    T.reads(A[tx, 2:16], B[0:2, tx, 0], C[0:2, tx, 0])\n                    T.writes(B[0:2, tx, 0], C[0:2, tx, 0], D[tx, 0:14])\n                    for i in T.serial(14):\n                        with T.block():\n                            T.where(i + 2 < 16)\n                            T.reads(A[tx, i + 2])\n                            T.writes(B[i % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 0):\n                                with T.attr(0, \"async_scope\", 1):\n                                    B[(i + 2) % 2, tx, 0] = A[tx, i + 2] * T.float32(2)\n                        with T.block():\n                            T.where(i + 2 - 1 < 16)\n                            T.reads(B[(i + 1) % 2, tx, 0])\n                            T.writes(C[(i + 1) % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 1):\n                                with T.attr(0, \"async_wait_queue_scope\", 0):\n                                    with T.attr(0, \"async_wait_inflight_count\", 1):\n                                        with T.attr(0, \"async_scope\", 1):\n                                            C[(i - 1 + 2) % 2, tx, 0] = B[\n                                                (i - 1 + 2) % 2, tx, 0\n                                            ] + T.float32(2)\n                        with T.block():\n                            T.where(i + 2 - 2 < 16)\n                            T.reads(C[0:2, tx, 0])\n                            T.writes(D[tx, i - 2 + 2])\n                            with T.attr(0, \"async_wait_queue_scope\", 1):\n                                with T.attr(0, \"async_wait_inflight_count\", 1):\n                                    D[tx, i - 2 + 2] = C[(i - 2 + 2) % 2, tx, 0] + T.float32(1)\n                with T.block():\n                    T.reads(B[0:2, tx, 0], C[0:2, tx, 0])\n                    T.writes(C[0:2, tx, 0], D[tx, 14:16])\n                    for i in T.unroll(2):\n                        with T.block():\n                            T.where(i + 16 - 1 < 16)\n                            T.reads(B[(i + 1) % 2, tx, 0])\n                            T.writes(C[(i + 1) % 2, tx, 0])\n                            with T.attr(0, \"async_commit_queue_scope\", 1):\n                                with T.attr(0, \"async_wait_queue_scope\", 0):\n                                    with T.attr(0, \"async_wait_inflight_count\", 0 - i):\n                                        with T.attr(0, \"async_scope\", 1):\n                                            C[(i - 1 + 16) % 2, tx, 0] = B[\n                                                (i - 1 + 16) % 2, tx, 0\n                                            ] + T.float32(2)\n                        with T.block():\n                            T.where(i + 16 - 2 < 16)\n                            T.reads(C[0:2, tx, 0])\n                            T.writes(D[tx, i - 2 + 16])\n                            with T.attr(0, \"async_wait_queue_scope\", 1):\n                                with T.attr(\n                                    0,\n                                    \"async_wait_inflight_count\",\n                                    T.if_then_else(i + 16 - 1 < 16, 1, 0, dtype=\"int32\"),\n                                ):\n                                    D[tx, i - 2 + 16] = C[(i - 2 + 16) % 2, tx, 0] + T.float32(1)\n\n    tvm.ir.assert_structural_equal(mod[\"main\"], ref, True)\n\n\nN = K = M = 4096\n\n\ndef get_mma_schedule():\n    i_factors, j_factors, k_factors = [1, 32, 1, 4, 2], [16, 2, 4, 1, 2], [128, 2, 1]\n\n    def index_map(i, j):\n        return (\n            i // 16,\n            j // 16,\n            *shared_16x16_to_ldmatrix_32x8_layout(i % 16, j % 16),\n        )\n\n    workload = te.create_prim_func(\n        te_workload.matmul(N, M, K, in_dtype=\"float16\", out_dtype=\"float32\")\n    )\n\n    return mma_schedule(\n        workload,\n        16,\n        \"float16\",\n        False,\n        i_factors,\n        j_factors,\n        k_factors,\n        index_map,\n        index_map,\n        index_map,\n        LDMATRIX_16x16_A_DYN_INTRIN,\n        LDMATRIX_16x16_B_DYN_INTRIN,\n        MMA_f16f16f32_INTRIN,\n        MMA_fill_16x16_f32_INTRIN,\n        MMA_store_16x16_f32_global_INTRIN,\n        \"shared.dyn\",\n    )\n\n\ndef build_and_run(sch):\n    if tvm.testing.is_ampere_or_newer():\n        with tvm.transform.PassContext(config={\"tir.use_async_copy\": 1}):\n            f = tvm.build(sch.mod[\"main\"], target=\"cuda\")\n\n        dev = tvm.device(\"cuda\", 0)\n        a_np = np.random.uniform(size=(N, K)).astype(\"float16\")\n        b_np = np.random.uniform(size=(K, M)).astype(\"float16\")\n        c_np = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\"))\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros((N, M), dtype=\"float32\"), dev)\n        f(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3)\n\n\n@tvm.testing.requires_cuda\ndef test_async_pipelined_mma_gemm_simple():\n    sch = get_mma_schedule()\n\n    k0 = sch.get_loops(sch.get_block(\"C_o_update\"))[3]\n\n    sch.annotate(k0, ann_key=\"software_pipeline_stage\", ann_val=[0, 0, 3])\n    sch.annotate(k0, ann_key=\"software_pipeline_order\", ann_val=[0, 1, 2])\n    sch.annotate(k0, ann_key=\"software_pipeline_async_stages\", ann_val=[0])\n\n    seq = tvm.transform.Sequential(\n        [\n            tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(),\n            tvm.tir.transform.ConvertBlocksToOpaque(),\n            tvm.tir.transform.UnifyThreadBinding(),\n            tvm.tir.transform.LowerMatchBuffer(),\n            tvm.tir.transform.InjectSoftwarePipeline(),\n        ]\n    )\n    mod = seq(sch.mod)\n\n    pipeline = mod[\"main\"].body.block.body.body.body.body.body.block.body[1].block.body\n    prologue, body, epilogue = pipeline\n\n    commit_queue_scope = prologue.block.body.body.block.body\n    assert len(commit_queue_scope.body) == 2\n    assert commit_queue_scope.value == 0\n\n    commit_queue_scope = body.block.body.body[0].block.body\n    assert len(commit_queue_scope.body) == 2\n    assert commit_queue_scope.value == 0\n\n    assert body.block.body.body[1].block.body.body.attr_key == \"async_wait_inflight_count\"\n    assert body.block.body.body[1].block.body.body.value == 3\n\n    assert epilogue.block.body.body.block.body.body.attr_key == \"async_wait_inflight_count\"\n    assert str(epilogue.block.body.body.block.body.body.value) == \"(2 - i2_0_0: int32)\"\n\n    build_and_run(sch)\n\n\n@tvm.testing.requires_cuda\ndef test_async_nested_pipeline_mma_gemm_ideal_annotation():\n    sch = get_mma_schedule()\n\n    k0 = sch.get_loops(sch.get_block(\"C_o_update\"))[3]\n    k1 = sch.get_loops(sch.get_block(\"C_o_update\"))[4]\n\n    sch.annotate(k0, ann_key=\"software_pipeline_stage\", ann_val=[0, 0, 2, 3, 3])\n    sch.annotate(k0, ann_key=\"software_pipeline_order\", ann_val=[0, 1, 3, 2, 4])\n    sch.annotate(k0, ann_key=\"software_pipeline_async_stages\", ann_val=[0])\n\n    sch.annotate(k1, ann_key=\"software_pipeline_stage\", ann_val=[0, 0, 1])\n    sch.annotate(k1, ann_key=\"software_pipeline_order\", ann_val=[0, 1, 2])\n\n    seq = tvm.transform.Sequential(\n        [\n            tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(),\n            tvm.tir.transform.ConvertBlocksToOpaque(),\n            tvm.tir.transform.UnifyThreadBinding(),\n            tvm.tir.transform.LowerMatchBuffer(),\n            tvm.tir.transform.InjectSoftwarePipeline(),\n        ]\n    )\n    mod = seq(sch.mod)\n\n    pipeline = mod[\"main\"].body.block.body.body.body.body.body.block.body[1].block.body\n    prologue, body, epilogue = pipeline\n\n    commit_queue_scope = prologue.block.body.body[0].block.body\n    assert len(commit_queue_scope.body) == 2\n    assert commit_queue_scope.value == 0\n\n    assert prologue.block.body.body[1].block.body.body.attr_key == \"async_wait_inflight_count\"\n    assert prologue.block.body.body[1].block.body.body.value == 2\n\n    commit_queue_scope = body.block.body.body[0].block.body\n    assert len(commit_queue_scope.body) == 2\n    assert commit_queue_scope.value == 0\n\n    assert body.block.body.body[1].block.body.body.attr_key == \"async_wait_inflight_count\"\n    assert body.block.body.body[1].block.body.body.value == 2\n\n    assert str(epilogue.block.body.body[0].block.body.body.value) == \"(1 - i2_0_0: int32)\"\n\n    build_and_run(sch)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_inject_virtual_thread.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\nvthread_name = tvm.testing.parameter(\"vthread\", \"cthread\")\n\n\ndef test_vthread(vthread_name):\n    dtype = \"int64\"\n    n = 100\n    m = 4\n    nthread = 2\n\n    def get_vthread(name):\n        tx = te.thread_axis(name)\n        ty = te.thread_axis(name)\n        ib = tvm.tir.ir_builder.create()\n        A = ib.pointer(\"float32\", name=\"A\")\n        C = ib.pointer(\"float32\", name=\"C\")\n        with ib.for_range(0, n) as i:\n            ib.scope_attr(tx, \"virtual_thread\", nthread)\n            ib.scope_attr(ty, \"virtual_thread\", nthread)\n            B = ib.allocate(\"float32\", m, name=\"B\", scope=\"shared\")\n            B[i] = A[i * nthread + tx]\n            bbuffer = B.asobject()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"Run\",\n                    bbuffer.access_ptr(\"r\"),\n                    tvm.tir.call_intrin(\"int32\", \"tir.tvm_context_id\"),\n                )\n            )\n            C[i * nthread + tx] = B[i] + 1\n        return ib.get()\n\n    if vthread_name == \"vthread\":\n        B_expected_alloc = m * nthread\n    elif vthread_name == \"cthread\":\n        B_expected_alloc = m * nthread * nthread\n\n    stmt = tvm.tir.transform.InjectVirtualThread()(\n        tvm.IRModule.from_expr(tvm.tir.PrimFunc([], get_vthread(vthread_name)))\n    )[\"main\"]\n\n    assert list(stmt.body.body.extents) == [B_expected_alloc]\n\n\ndef test_vthread_extern(vthread_name):\n    dtype = \"int64\"\n    n = 100\n    m = 4\n    nthread = 2\n\n    def get_vthread(name):\n        tx = te.thread_axis(name)\n        ty = te.thread_axis(name)\n        ib = tvm.tir.ir_builder.create()\n        with ib.for_range(0, n) as i:\n            ib.scope_attr(tx, \"virtual_thread\", nthread)\n            ib.scope_attr(ty, \"virtual_thread\", nthread)\n            A = ib.allocate(\"float32\", m, name=\"A\", scope=\"shared\")\n            B = ib.allocate(\"float32\", m, name=\"B\", scope=\"shared\")\n            C = ib.allocate(\"float32\", m, name=\"C\", scope=\"shared\")\n            abuffer = A.asobject()\n            bbuffer = B.asobject()\n            cbuffer = C.asobject()\n            A[tx] = tx + 1.0\n            B[ty] = ty + 1.0\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"Run\",\n                    abuffer.access_ptr(\"r\"),\n                    bbuffer.access_ptr(\"r\"),\n                    cbuffer.access_ptr(\"rw\"),\n                )\n            )\n        return ib.get()\n\n    if vthread_name == \"vthread\":\n        A_expected_alloc = m * nthread\n    elif vthread_name == \"cthread\":\n        A_expected_alloc = m * nthread * nthread\n\n    C_expected_alloc = m * nthread * nthread\n\n    stmt = tvm.tir.transform.InjectVirtualThread()(\n        tvm.IRModule.from_expr(tvm.tir.PrimFunc([], get_vthread(vthread_name)))\n    )[\"main\"]\n\n    assert list(stmt.body.body.extents) == [A_expected_alloc]\n    assert list(stmt.body.body.body.body.extents) == [C_expected_alloc]\n\n\ndef test_vthread_if_then_else():\n    nthread = 2\n    tx = te.thread_axis(\"vthread\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 100) as i:\n        ib.scope_attr(tx, \"virtual_thread\", nthread)\n        B = ib.allocate(\"float32\", 128, name=\"B\", scope=\"shared\")\n        with ib.if_scope(i == 0):\n            B[i] = A[i * nthread + tx]\n        with ib.else_scope():\n            B[i] = A[i * nthread + tx] + 1\n        with ib.if_scope(i == 0):\n            B[i] = A[i * nthread + tx] + 2\n    stmt = ib.get()\n\n    stmt = tvm.tir.transform.InjectVirtualThread()(\n        tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    )[\"main\"]\n\n    assert stmt.body.body.body[0].else_case != None\n    assert stmt.body.body.body[1].else_case == None\n\n\ndef test_vthread_simplified():\n    \"\"\"Indices resulting from vthread injection should simplified\n\n    This ensures that downstream passes that check for Ramp nodes do\n    not need to each simplify the indices.\n    \"\"\"\n\n    @T.prim_func\n    def before_func():\n        vthread = T.env_thread(\"vthread\")\n        T.launch_thread(vthread, 4)\n        B_data = T.allocate([4], \"int32\", scope=\"shared\")\n        B = T.buffer_decl([4], \"int32\", data=B_data, scope=\"shared\")\n        B[0:4] = T.broadcast(vthread, 4)\n\n    @T.prim_func\n    def expected_func():\n        B_data = T.allocate([16], \"int32\", scope=\"shared\")\n        B = T.buffer_decl([16], \"int32\", data=B_data, scope=\"shared\")\n        # The indices for B should each be a single Ramp node, and\n        # should not be the sum of a Ramp and Broadcast node.\n        B[T.Mul(0, 4) : T.Mul(0, 4) + 4] = T.broadcast(0, 4)\n        B[T.Mul(1, 4) : T.Mul(1, 4) + 4] = T.broadcast(1, 4)\n        B[T.Mul(2, 4) : T.Mul(2, 4) + 4] = T.broadcast(2, 4)\n        B[T.Mul(3, 4) : T.Mul(3, 4) + 4] = T.broadcast(3, 4)\n\n    before_mod = tvm.IRModule.from_expr(before_func)\n    after_mod = tvm.tir.transform.InjectVirtualThread()(before_mod)\n    after_func = after_mod[\"main\"]\n\n    tvm.ir.assert_structural_equal(after_func, expected_func)\n\n\ndef test_vthread_vectorized():\n    \"\"\"Use of vthread is compatible with vector allocations\"\"\"\n\n    @T.prim_func\n    def before_func():\n        vthread = T.env_thread(\"vthread\")\n        T.launch_thread(vthread, 4)\n        B_data = T.allocate([4], \"int32\", \"shared\")\n        B = T.buffer_decl([4], \"int32\", data=B_data, scope=\"shared\")\n        B[0:4] = T.broadcast(vthread, 4)\n\n    @T.prim_func\n    def expected_func():\n        B_data = T.allocate([4], \"int32x4\", \"shared\")\n        B = T.buffer_decl([4], \"int32x4\", data=B_data, scope=\"shared\")\n        B[T.Mul(0, 4) / 4] = T.broadcast(0, 4)\n        B[T.Mul(1, 4) / 4] = T.broadcast(1, 4)\n        B[T.Mul(2, 4) / 4] = T.broadcast(2, 4)\n        B[T.Mul(3, 4) / 4] = T.broadcast(3, 4)\n\n    before_mod = tvm.IRModule.from_expr(before_func)\n    intermediate_mod = tvm.tir.transform.InjectVirtualThread()(before_mod)\n    after_mod = tvm.tir.transform.StorageRewrite()(intermediate_mod)\n    after_func = after_mod[\"main\"]\n\n    tvm.ir.assert_structural_equal(after_func, expected_func)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_instrument_bound_checkers.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n\ndef collect_visit(stmt, f):\n    ret = []\n    tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x)))\n    return ret\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_llvm(index_a, index_b):\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i + index_a] + B[i + index_b], name=\"C\")\n    s = te.create_schedule(C.op)\n    tgt = \"llvm\"\n    tgt_host = \"llvm\"\n    stmt = tvm.lower(s, [A, B, C], simple_mode=True)\n    print(stmt)\n    tgt = tvm.target.Target(tgt, tgt_host)\n    fadd = tvm.build(s, [A, B, C], target=tgt, name=\"myadd\")\n    dev = tvm.device(tgt.kind.name, 0)\n    a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=1024).astype(B.dtype), dev)\n    c = tvm.nd.array(np.zeros(1024, dtype=C.dtype), dev)\n    fadd(a, b, c)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_llvm():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n    tgt = \"llvm\"\n    tgt_host = \"llvm\"\n    stmt = tvm.lower(s, [A, B, C], simple_mode=True)\n    tgt = tvm.target.Target(tgt, tgt_host)\n    fadd = tvm.build(s, [A, B, C], target=tgt, name=\"myadd\")\n    dev = tvm.device(tgt.kind.name, 0)\n    a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=1024).astype(B.dtype), dev)\n    c = tvm.nd.array(np.zeros(1024, dtype=C.dtype), dev)\n    fadd(a, b, c)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_vectorize_llvm(nn, index_a, index_b):\n    n = tvm.runtime.convert(nn)\n    a = te.placeholder((n), name=\"a\")\n    b = te.placeholder((n), name=\"b\")\n    c = te.compute((n,), lambda i: a[i + index_a] + b[i + index_b], name=\"c\")\n    s = te.create_schedule(c.op)\n    xo, xi = s[c].split(c.op.axis[0], factor=8)\n    s[c].parallel(xo)\n    s[c].vectorize(xi)\n    tgt = \"llvm\"\n    tgt_host = \"llvm\"\n    stmt = tvm.lower(s, [a, b, c], simple_mode=True)\n    tgt = tvm.target.Target(tgt, tgt_host)\n    f = tvm.build(s, [a, b, c], target=tgt, name=\"myaddvec\")\n    dev = tvm.cpu(0)\n    n = nn\n    a = tvm.nd.array(np.random.uniform(size=(n)).astype(a.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(n)).astype(a.dtype), dev)\n    c = tvm.nd.array(np.zeros(n, dtype=c.dtype), dev)\n    f(a, b, c)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_vectorize_llvm():\n    n = 512\n    lanes = 2\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32x%d\" % lanes)\n    B = te.compute((n,), lambda i: A[i], name=\"B\")\n    C = te.compute((n,), lambda i: B[i] + tvm.tir.const(1, A.dtype), name=\"C\")\n    s = te.create_schedule(C.op)\n    xo, xi = s[C].split(C.op.axis[0], nparts=2)\n    _, xi = s[C].split(xi, factor=2)\n    s[C].parallel(xo)\n    s[C].vectorize(xi)\n    s[B].compute_at(s[C], xo)\n    xo, xi = s[B].split(B.op.axis[0], factor=2)\n    s[B].vectorize(xi)\n    # build and invoke the kernel.\n    lowered_func = tvm.lower(s, [A, C], \"llvm\", simple_mode=False)\n    f = tvm.build(s, [A, C], \"llvm\")\n    dev = tvm.cpu(0)\n    # launch the kernel.\n    a = tvm.nd.empty((n,), A.dtype).copyfrom(\n        np.random.uniform(size=[n] + ([] if lanes == 1 else [lanes]))\n    )\n    c = tvm.nd.empty((n,), C.dtype, dev)\n    f(a, c)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_loop_partition_basic_llvm():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype), dev)\n    t = tvm.nd.empty((32,), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_loop_partition_basic_llvm(index_a, index_b):\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i + index_a] + B[i + index_b])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype), dev)\n    t = tvm.nd.empty((32,), T.dtype, dev)\n    f(a, b, t)\n\n\ndef test_in_bounds_const_loop_partition_ir():\n    def check_attr_stmt(x):\n        if (\n            isinstance(x, tvm.tir.AttrStmt)\n            and x.attr_key == \"buffer_bound\"\n            and tvm.ir.structural_equal(x.value.args, [n])\n        ):\n            return True\n        return False\n\n    def check_branch_stmt(x):\n        if isinstance(x, tvm.tir.IfThenElse):\n            return True\n        return False\n\n    def assert_bound_instrumentation(stmt, f, nums):\n        count = 0\n        for i in collect_visit(stmt, f):\n            if i is True:\n                count = count + 1\n        assert count == nums\n\n    def collect_branch_stmt(x):\n        if isinstance(x, tvm.tir.IfThenElse):\n            branch_collector.append(x)\n\n    n = 21\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n\n    with tvm.transform.PassContext(\n        config={\n            \"tir.instrument_bound_checkers\": True,\n            \"tir.LoopPartition\": {\"partition_const_loop\": True},\n        }\n    ):\n        mod = tvm.driver.lower(s, [A, B, T], name=\"main\")\n\n    stmt = mod[\"main\"].body\n    # after instrumentation\n    assert_bound_instrumentation(stmt, check_attr_stmt, 2 * 3)\n    assert_bound_instrumentation(stmt, check_branch_stmt, 2)\n\n    branch_collector = list()\n    collect_visit(stmt, collect_branch_stmt)\n    assert len(branch_collector) == 2\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_const_loop_partition_llvm():\n    with tvm.transform.PassContext(\n        config={\n            \"tir.instrument_bound_checkers\": True,\n            \"tir.LoopPartition\": {\"partition_const_loop\": True},\n        }\n    ):\n        n = 21\n        A = te.placeholder((n,), name=\"A\")\n        B = te.placeholder((n,), name=\"B\")\n\n        T = te.compute((n,), lambda i: A[i] + B[i])\n        s = te.create_schedule(T.op)\n        xo, xi = s[T].split(T.op.axis[0], factor=4)\n        lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n        dev = tvm.cpu(0)\n\n        f = tvm.build(s, [A, B, T], \"llvm\")\n        a = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(n,)).astype(B.dtype), dev)\n        t = tvm.nd.empty((n,), T.dtype, dev)\n        f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_const_loop_partition_llvm(index_a, index_b):\n    with tvm.transform.PassContext(\n        config={\n            \"tir.instrument_bound_checkers\": True,\n            \"tir.LoopPartition\": {\"partition_const_loop\": True},\n        }\n    ):\n        n = 21\n        A = te.placeholder((n,), name=\"A\")\n        B = te.placeholder((n,), name=\"B\")\n\n        T = te.compute((n,), lambda i: A[i + index_a] + B[i + index_b])\n        s = te.create_schedule(T.op)\n        xo, xi = s[T].split(T.op.axis[0], factor=4)\n        lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n        dev = tvm.cpu(0)\n\n        f = tvm.build(s, [A, B, T], \"llvm\")\n        a = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=(n,)).astype(B.dtype), dev)\n        t = tvm.nd.empty((n,), T.dtype, dev)\n        f(a, b, t)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_conv_llvm(loop_tiling=False):\n    HSTR = WSTR = 1\n    in_channel = 128\n    kernel_height = kernel_width = 3\n    out_channel = 64\n    batch_size = 1\n    in_height = in_width = 64\n    out_height = out_width = in_height - kernel_height + 1\n    data = te.placeholder((batch_size, in_channel, in_height, in_width), name=\"data\")\n    kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name=\"kernel\")\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n    conv = te.compute(\n        (batch_size, out_channel, out_height, out_width),\n        lambda n, oc, oh, ow: te.sum(\n            data[n, ic, oh * HSTR + kh, ow * WSTR + kw] * kernel[kh, kw, ic, oc], axis=[ic, kh, kw]\n        ),\n        name=\"conv2d\",\n    )\n    s = te.create_schedule(conv.op)\n\n    n, oc, oh, ow = conv.op.axis\n    if loop_tiling:\n        oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16)\n    lowered_func = tvm.lower(s, [data, kernel, conv], simple_mode=True)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [data, kernel, conv], \"llvm\")\n    data_input = tvm.nd.array(\n        np.random.uniform(size=(batch_size, in_channel, in_height, in_width)).astype(\"float32\"), dev\n    )\n    kernel_input = tvm.nd.array(\n        np.random.uniform(size=(kernel_height, kernel_width, in_channel, out_channel)).astype(\n            \"float32\"\n        ),\n        dev,\n    )\n    conv_out = tvm.nd.empty((batch_size, out_channel, out_height, out_width), \"float32\", dev)\n    f(data_input, kernel_input, conv_out)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_conv_llvm(data_offsets, kernel_offsets, loop_tiling=False):\n    HSTR = WSTR = 1\n    in_channel = 128\n    kernel_height = kernel_width = 3\n    out_channel = 64\n    batch_size = 1\n    in_height = in_width = 64\n    out_height = out_width = in_height - kernel_height + 1\n    data = te.placeholder((batch_size, in_channel, in_height, in_width), name=\"data\")\n    kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name=\"kernel\")\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n    conv = te.compute(\n        (batch_size, out_channel, out_height, out_width),\n        lambda n, oc, oh, ow: te.sum(\n            data[\n                n + data_offsets[0],\n                ic + data_offsets[1],\n                oh * HSTR + kh + data_offsets[2],\n                ow * WSTR + kw + data_offsets[3],\n            ]\n            * kernel[\n                kh + kernel_offsets[0],\n                kw + kernel_offsets[1],\n                ic + kernel_offsets[2],\n                oc + kernel_offsets[3],\n            ],\n            axis=[ic, kh, kw],\n        ),\n        name=\"conv2d\",\n    )\n    s = te.create_schedule(conv.op)\n\n    n, oc, oh, ow = conv.op.axis\n    if loop_tiling:\n        oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16)\n    lowered_func = tvm.lower(s, [data, kernel, conv], simple_mode=True)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [data, kernel, conv], \"llvm\")\n    data_input = tvm.nd.array(\n        np.random.uniform(size=(batch_size, in_channel, in_height, in_width)).astype(\"float32\"), dev\n    )\n    kernel_input = tvm.nd.array(\n        np.random.uniform(size=(kernel_height, kernel_width, in_channel, out_channel)).astype(\n            \"float32\"\n        ),\n        dev,\n    )\n    conv_out = tvm.nd.empty((batch_size, out_channel, out_height, out_width), \"float32\", dev)\n    f(data_input, kernel_input, conv_out)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_tensors_with_same_shapes1D_llvm():\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((k,), name=\"B\")\n\n    T = te.compute((m,), lambda i: A[i] * B[i])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype), dev)\n    t = tvm.nd.empty((32,), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_tensors_with_diff_shapes1D_llvm(a_shape, b_shape, c_shape):\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((k,), name=\"B\")\n\n    T = te.compute((m,), lambda i: A[i] * B[i])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(a_shape,)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(b_shape,)).astype(B.dtype), dev)\n    t = tvm.nd.empty((c_shape,), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_tensors_with_same_shapes2D_llvm():\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, n), name=\"A\")\n    B = te.placeholder((k, k), name=\"B\")\n\n    T = te.compute((m, m), lambda i, j: A[i][j] * B[i][j])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(32, 32)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(32, 32)).astype(B.dtype), dev)\n    t = tvm.nd.empty((32, 32), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_tensors_with_diff_shapes2D_llvm(a_shape, b_shape, c_shape):\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, n), name=\"A\")\n    B = te.placeholder((k, k), name=\"B\")\n\n    T = te.compute((m, m), lambda i, j: A[i][j] * B[i][j])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(a_shape[0], a_shape[1])).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(b_shape[0], b_shape[1])).astype(B.dtype), dev)\n    t = tvm.nd.empty((c_shape[0], c_shape[1]), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\ndef test_in_bounds_tensors_with_same_shapes3D_llvm():\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, n, n), name=\"A\")\n    B = te.placeholder((k, k, k), name=\"B\")\n\n    T = te.compute((m, m, m), lambda i, j, p: A[i][j][p] * B[i][j][p])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(np.random.uniform(size=(32, 32, 32)).astype(A.dtype), dev)\n    b = tvm.nd.array(np.random.uniform(size=(32, 32, 32)).astype(B.dtype), dev)\n    t = tvm.nd.empty((32, 32, 32), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_tensors_with_diff_shapes3D_llvm(a_shape, b_shape, c_shape):\n    n = te.size_var(\"n\")\n    k = te.size_var(\"k\")\n    m = te.size_var(\"m\")\n    A = te.placeholder((n, n, n), name=\"A\")\n    B = te.placeholder((k, k, k), name=\"B\")\n\n    T = te.compute((m, m, m), lambda i, j, p: A[i][j][p] * B[i][j][p])\n    s = te.create_schedule(T.op)\n    lowered_func = tvm.lower(s, [A, B, T], \"llvm\", simple_mode=False)\n\n    dev = tvm.cpu(0)\n\n    f = tvm.build(s, [A, B, T], \"llvm\")\n    a = tvm.nd.array(\n        np.random.uniform(size=(a_shape[0], a_shape[1], c_shape[2])).astype(A.dtype), dev\n    )\n    b = tvm.nd.array(\n        np.random.uniform(size=(b_shape[0], b_shape[1], b_shape[2])).astype(B.dtype), dev\n    )\n    t = tvm.nd.empty((c_shape[0], c_shape[1], c_shape[2]), T.dtype, dev)\n    f(a, b, t)\n\n\n@tvm.testing.requires_llvm\n@pytest.mark.xfail\ndef test_out_of_bounds_tensors_with_zero_shape_op_with_not_zero_shape_llvm():\n    n = 64\n    A = te.placeholder((n,), name=\"A\")\n    scale = te.placeholder((), name=\"scale\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    C = te.compute((), lambda: te.sum(A[k + k + k] * scale, axis=k), name=\"C\")\n    D = te.compute((), lambda: C + 1)\n    s = te.create_schedule(D.op)\n    stmt = tvm.lower(s, [A, scale, D], simple_mode=True)\n\n    # build and invoke the kernel.\n    f = tvm.build(s, [A, scale, D], \"llvm\")\n    dev = tvm.cpu(0)\n    # launch the kernel.\n    a = tvm.nd.array(np.random.randint(0, 2, size=(n,)).astype(A.dtype), dev)\n    sc = tvm.nd.array(np.random.randint(0, 2, size=()).astype(scale.dtype), dev)\n    d = tvm.nd.empty((), D.dtype, dev)\n    f(a, sc, d)\n    d_np = np.sum(a.numpy()) * sc.numpy() + 1\n    tvm.testing.assert_allclose(d.numpy(), d_np)\n\n\nif __name__ == \"__main__\":\n    with tvm.transform.PassContext(\n        config={\n            \"tir.instrument_bound_checkers\": True,\n        }\n    ):\n        # zero scale\n        test_out_of_bounds_tensors_with_zero_shape_op_with_not_zero_shape_llvm()\n        # in bound\n        test_in_bounds_llvm()\n        # upper bound\n        test_out_of_bounds_llvm(1, 0)\n        test_out_of_bounds_llvm(0, 1)\n        test_out_of_bounds_llvm(1, 1)\n        test_out_of_bounds_llvm(10000, 0)\n        test_out_of_bounds_llvm(0, 10000)\n        test_out_of_bounds_llvm(10000, 10000)\n        # lower bound\n        test_out_of_bounds_llvm(-1, 0)\n        test_out_of_bounds_llvm(0, -1)\n        test_out_of_bounds_llvm(-1, -1)\n        test_out_of_bounds_llvm(-10000, 0)\n        test_out_of_bounds_llvm(0, -10000)\n        test_out_of_bounds_llvm(-10000, -10000)\n        # vectorize in bound\n        test_in_bounds_vectorize_llvm()\n        # vectorization upper bound\n        test_out_of_bounds_vectorize_llvm(1024, 1000, 0)\n        test_out_of_bounds_vectorize_llvm(1024, 0, 10000)\n        # vectorization lower bound\n        test_out_of_bounds_vectorize_llvm(1024, -1000, 0)\n        test_out_of_bounds_vectorize_llvm(1024, 0, -10000)\n        test_in_bounds_const_loop_partition_llvm()\n        test_out_of_bounds_const_loop_partition_llvm(1, 0)\n        test_out_of_bounds_const_loop_partition_llvm(0, 1)\n        test_out_of_bounds_const_loop_partition_llvm(-1, 0)\n        test_out_of_bounds_const_loop_partition_llvm(0, -1)\n        test_in_bounds_loop_partition_basic_llvm()\n        test_out_of_bounds_loop_partition_basic_llvm(32, 0)\n        test_out_of_bounds_loop_partition_basic_llvm(0, 32)\n        test_out_of_bounds_loop_partition_basic_llvm(-32, 0)\n        test_out_of_bounds_loop_partition_basic_llvm(0, -32)\n        # conv\n        test_in_bounds_conv_llvm()\n        test_out_of_bounds_conv_llvm([1, 0, 0, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 1, 0, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 1, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 1], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([-1, 0, 0, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, -1, 0, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, -1, 0], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, -1], [0, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [1, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 1, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 1, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, 1])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [-1, 0, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, -1, 0, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, -1, 0])\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, -1])\n        # loop tiling\n        test_in_bounds_conv_llvm(True)\n        test_out_of_bounds_conv_llvm([1, 0, 0, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 1, 0, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 1, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 1], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([-1, 0, 0, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, -1, 0, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, -1, 0], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, -1], [0, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [1, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 1, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 1, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, 1], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [-1, 0, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, -1, 0, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, -1, 0], True)\n        test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, -1], True)\n        # tensors with diff shapes basic operation such as mul\n        test_out_of_bounds_tensors_with_diff_shapes1D_llvm(32, 64, 64)\n        test_out_of_bounds_tensors_with_diff_shapes1D_llvm(64, 32, 64)\n        test_out_of_bounds_tensors_with_diff_shapes2D_llvm([64, 64], [32, 32], [64, 64])\n        test_out_of_bounds_tensors_with_diff_shapes2D_llvm([32, 32], [64, 64], [64, 64])\n        test_out_of_bounds_tensors_with_diff_shapes3D_llvm([64, 64, 64], [32, 32, 32], [64, 64, 64])\n        test_out_of_bounds_tensors_with_diff_shapes3D_llvm([32, 32, 32], [64, 64, 64], [64, 64, 64])\n        # check tensors with the same shapes\n        test_in_bounds_tensors_with_same_shapes1D_llvm()\n        test_in_bounds_tensors_with_same_shapes2D_llvm()\n        test_in_bounds_tensors_with_same_shapes3D_llvm()\n        # ir tests\n        test_in_bounds_const_loop_partition_ir()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_ir_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport tvm\nfrom tvm import tir, ir\n\n\ndef test_convert_ssa():\n    dtype = \"int32\"\n    zero = tir.const(0)\n    nop = tir.Evaluate(zero)\n    var_type = ir.PointerType(ir.PrimType(dtype))\n    v = tir.Var(\"i1\", var_type)\n    buf = tir.decl_buffer([16], dtype=dtype, data=v)\n    let = tir.LetStmt(v, v, nop)\n    load = tir.Evaluate(tir.BufferLoad(buf, [zero]))\n    seq = tir.SeqStmt([let, let, load])\n    func = tir.PrimFunc([], seq)\n    mod = tvm.IRModule({\"main\": func})\n    mod = tir.transform.InjectVirtualThread()(\n        mod\n    )  # Use pass InjectVirtualThread to invoke ConvertSSA\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lift_attr_scope.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_coproc_lift():\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    cp = te.thread_axis((0, 1), \"cop\")\n    value = tvm.tir.StringImm(\"xxx\")\n\n    A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            ib.scope_attr(cp, \"coproc_uop_scope\", value)\n            A[i] = A[i] + 1\n        with ib.if_scope(i.equal(0)):\n            with ib.for_range(0, 10, name=\"j\") as j:\n                ib.scope_attr(cp, \"coproc_uop_scope\", value)\n                A[j] = A[j] + 2\n                A[j] = A[j] + 3\n                A[j] = A[j] + 3\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.LiftAttrScope(\"coproc_uop_scope\")(mod)[\"main\"]\n\n    assert body.body.body.node == cp\n\n    # only able to lift to the common pattern of the last two fors.\n    ib = tvm.tir.ir_builder.create()\n    A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A[j] = A[j] + 1\n        with ib.for_range(0, 10, name=\"j\") as j:\n            ib.scope_attr(cp, \"coproc_uop_scope\", value)\n            A[i] = A[i] + 1\n        with ib.for_range(0, 10, name=\"j\") as j:\n            ib.scope_attr(cp, \"coproc_uop_scope\", value)\n            A[i] = A[i] + 2\n\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.LiftAttrScope(\"coproc_uop_scope\")(mod)[\"main\"]\n\n    assert body.body.body.body[1].node == cp\n    assert len(body.body.body.body) == 2\n\n\nif __name__ == \"__main__\":\n    test_coproc_lift()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_loop_partition.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nimport numpy\n\n\ndef collect_visit(stmt, f):\n    ret = []\n    tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x)))\n    return ret\n\n\ndef test_basic():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"]\n\n    assert not any(collect_visit(stmt.body.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse)))\n    assert any(collect_visit(stmt.body.body[1], lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_const_loop():\n    n = 21\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_no_unroll_loop():\n    n = 21\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    xo, xi = s[T].split(T.op.axis[0], factor=4)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    with tvm.transform.PassContext(\n        config={\n            \"tir.LoopPartition\": {\n                \"partition_const_loop\": True,\n                \"no_unroll_loop_with_extent_one\": True,\n            }\n        }\n    ):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        mod = tvm.tir.transform.Simplify()(mod)\n        stmt = tvm.tir.transform.RemoveNoOp()(mod)[\"main\"].body\n\n    assert sum(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.For))) == 4\n\n\ndef test_multi_loop():\n    ib = tvm.tir.ir_builder.create()\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    with ib.for_range(0, 4, \"i\") as i:\n        with ib.for_range(0, n, \"j\") as j:\n            with ib.for_range(0, m, \"k\") as k:\n                with ib.if_scope(ib.likely(i * m + j + k < n)):\n                    ib.emit(tvm.tir.Evaluate(m))\n                with ib.else_scope():\n                    ib.emit(tvm.tir.Evaluate(n))\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n, m], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_multi_if():\n    ib = tvm.tir.ir_builder.create()\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    with ib.for_range(0, 4, \"i\") as i:\n        with ib.for_range(0, n, \"j\") as j:\n            with ib.for_range(0, m, \"k\") as k:\n                with ib.if_scope(ib.likely(i * m + j + k < n)):\n                    ib.emit(tvm.tir.Evaluate(m))\n                with ib.else_scope():\n                    ib.emit(tvm.tir.Evaluate(n))\n                with ib.if_scope(ib.likely(i * m + j - k < n)):\n                    ib.emit(tvm.tir.Evaluate(m))\n                with ib.else_scope():\n                    ib.emit(tvm.tir.Evaluate(n))\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_thread_axis():\n    m = te.size_var(\"m\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    B = te.compute((m, l), lambda i, j: A[i, j] + 3, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    s[B].set_scope(\"shared\")\n    num_thread = 16\n    xo, xi = s[B].split(B.op.axis[0], 32)\n    xi0, xi1 = s[B].split(xi, nparts=num_thread)\n    s[B].bind(xi0, te.thread_axis(\"threadIdx.x\"))\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"]\n\n    assert not any(collect_visit(stmt.body.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_vectorize():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    bias = te.size_var(\"bias\", dtype=\"float32\")\n    scale = te.size_var(\"scale\", dtype=\"float32\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i) * scale + bias, name=\"C\")\n    # schedule\n    s = te.create_schedule(C.op)\n    # create iter var and assign them tags.\n    num_thread = 32\n    bx, x = s[C].split(C.op.axis[0], factor=num_thread * 4)\n    tx, x = s[C].split(x, nparts=num_thread)\n    _, x = s[C].split(x, factor=4)\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    s[C].vectorize(x)\n    stmt = tvm.lower(s, [A, B], name=\"main\")[\"main\"]\n    body = stmt.body.body.body.body\n    assert x.var.name not in str(body.condition)\n    assert any(collect_visit(body.then_case, lambda x: isinstance(x, tvm.tir.Ramp)))\n\n\ndef test_condition():\n    ib = tvm.tir.ir_builder.create()\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    with ib.for_range(0, tvm.tir.truncdiv(n + 3, 4), \"i\") as i:\n        with ib.for_range(0, 4, \"j\") as j:\n            ib.emit(tvm.tir.Evaluate(tvm.tir.Select(ib.likely(i * 4 + j < n), m, n)))\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt[0], lambda x: isinstance(x, tvm.tir.Select)))\n\n\ndef test_condition_EQ():\n    ib = tvm.tir.ir_builder.create()\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    with ib.for_range(0, 10, \"i\") as i:\n        ib.emit(tvm.tir.Evaluate(tvm.tir.Select(ib.likely(tvm.tir.EQ(i, 5)), m, n)))\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt))\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt[0], lambda x: isinstance(x, tvm.tir.Select)))\n\n\ndef test_thread_axis2():\n    n = tvm.runtime.convert(4096)\n    m = te.size_var(\"m\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n    num_thread = 32\n    bx, x = s[C].split(C.op.axis[0], factor=32)\n    tx, x = s[C].split(x, nparts=num_thread)\n    _, x = s[C].split(x, factor=m)\n    s[C].bind(bx, te.thread_axis(\"blockIdx.x\"))\n    s[C].bind(tx, te.thread_axis(\"threadIdx.x\"))\n    stmt = tvm.lower(s, [A, B], name=\"main\")[\"main\"]\n    for_body = stmt.body.body.body.body[0]\n    assert \"threadIdx\" not in str(for_body.extent)\n\n\ndef test_everything_during_deduction():\n    m = te.size_var(\"m\")\n    n = te.size_var(\"n\")\n    ib = tvm.tir.ir_builder.create()\n    with ib.for_range(0, n, \"i\") as i:\n        with ib.for_range(0, 32, \"j\") as j:\n            with ib.if_scope(ib.likely(tvm.tir.truncdiv(i, j) < m)):\n                # this guard will produce everything during deduction\n                ib.emit(tvm.tir.Evaluate(m))\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt))\n    mod = tvm.tir.transform.LoopPartition()(mod)\n    stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert isinstance(stmt.body.body, tvm.tir.IfThenElse)\n\n\ndef test_single_likely():\n    n = 60\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n\n    T = te.compute((n,), lambda i: A[i] + B[i])\n    s = te.create_schedule(T.op)\n    x = T.op.axis[0]\n    xo, xi = s[T].split(x, factor=16)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_multi_likely():\n    n = 94\n    m = 62\n    A = te.placeholder((n, m), name=\"A\")\n    B = te.placeholder((n, m), name=\"B\")\n\n    T = te.compute((n, m), lambda i, j: A[i, j] + B[i, j])\n    s = te.create_schedule(T.op)\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n    x, y = T.op.axis\n    xo, xi = s[T].split(x, factor=16)\n    yo, yi = s[T].split(y, factor=16)\n    s[T].reorder(xo, yo, xi, yi)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_oneD_pool():\n    m = te.size_var(\"m\")\n    ib = tvm.tir.ir_builder.create()\n    # data = te.placeholder((16,), name = 'data')\n    data = ib.pointer(\"float32\", name=\"A\")\n    out = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 16, \"ow\") as ow:\n        with ib.for_range(0, 3, \"kw\") as kw:\n            with ib.if_scope(ib.likely(ow > 0)):\n                with ib.if_scope(ib.likely(ow < 15)):\n                    out[ow] = tvm.te.max(out[ow], data[ow + kw - 1])\n    with ib.for_range(0, 16, \"ow\") as ow:\n        with ib.for_range(0, 3, \"kw\") as kw:\n            with ib.if_scope(ib.likely(ow < 1)):\n                with ib.if_scope(ib.likely(kw > 0)):\n                    out[ow] = tvm.te.max(out[ow], data[ow + kw - 1])\n    with ib.for_range(0, 16, \"ow\") as ow:\n        with ib.for_range(0, 3, \"kw\") as kw:\n            with ib.if_scope(ib.likely(ow > 14)):\n                with ib.if_scope(ib.likely(kw < 2)):\n                    out[ow] = tvm.te.max(out[ow], data[ow + kw - 1])\n\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, data, out], stmt))\n\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_cce_loop_1():\n    ib = tvm.tir.ir_builder.create()\n    dtype = \"float16\"\n    n = 514\n    m = 514\n    _A = te.placeholder((n * m,), name=\"A\")\n    Ab = tvm.tir.decl_buffer((n * m,), dtype, name=\"A\")\n    A = ib.buffer_ptr(Ab)\n    _B = te.placeholder((n * m,), name=\"B\")\n    Bb = tvm.tir.decl_buffer((n * m,), dtype, name=\"B\")\n    B = ib.buffer_ptr(Bb)\n    # for i in 0 to n-1:\n    with ib.for_range(0, 11, name=\"i\") as i:\n        with ib.for_range(0, 160, name=\"j\") as j:\n            with ib.if_scope(ib.likely(((i * 160) + j) < 1600)):\n                A[(i + 1) * m + j + 1] = (\n                    B[(i) * m + j + 1] + B[(i + 1) * m + j + 1] + B[(i + 2) * m + j + 1]\n                )\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab, Bb], stmt))\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_cce_loop_2():\n    ib = tvm.tir.ir_builder.create()\n    len = 112\n    tile = 32\n    loop = (len + tile - 1) // tile\n    with ib.for_range(0, loop, \"i\") as i:\n        head = i * tile\n        with ib.if_scope(ib.likely(head + tile > len)):\n            tail = len\n            ib.emit(tvm.tir.call_extern(\"float32\", \"cce_intrisic\", head, tail))\n        with ib.else_scope():\n            tail = head + tile\n            ib.emit(tvm.tir.call_extern(\"float32\", \"cce_intrisic\", head, tail))\n\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_cce_loop_3():\n    ib = tvm.tir.ir_builder.create()\n    loop1 = 4\n    loop2 = 9998\n    tile = 39991\n    with ib.for_range(0, loop2, \"i\") as i:\n        with ib.for_range(0, loop1, \"j\") as j:\n            head1 = i\n            head2 = j\n            with ib.if_scope(ib.likely(head1 * loop1 + head2 < tile)):\n                ib.emit(tvm.tir.call_extern(\"float16\", \"cce_intrisic\", head1))\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_conv_tiling():\n    HSTR = WSTR = 1\n    in_channel = 128\n    kernel_height = kernel_width = 3\n    out_channel = 64\n    batch_size = 1\n    in_height = in_width = 64\n    out_height = out_width = in_height - kernel_height + 1\n    data = te.placeholder((batch_size, in_channel, in_height, in_width), name=\"data\")\n    kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name=\"kernel\")\n    ic = te.reduce_axis((0, in_channel), name=\"ic\")\n    kh = te.reduce_axis((0, kernel_height), name=\"kh\")\n    kw = te.reduce_axis((0, kernel_width), name=\"kw\")\n    conv = te.compute(\n        (batch_size, out_channel, out_height, out_width),\n        lambda n, oc, oh, ow: te.sum(\n            data[n, ic, oh * HSTR + kh, ow * WSTR + kw] * kernel[kh, kw, ic, oc], axis=[ic, kh, kw]\n        ),\n        name=\"conv2d\",\n    )\n    s = te.create_schedule(conv.op)\n\n    n, oc, oh, ow = conv.op.axis\n    oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16)\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        stmt = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n\n    assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n\ndef test_multilevel_splitting_with_indivisble_factors():\n    from tvm import topi\n\n    A = te.placeholder((130,), dtype=\"float32\")\n    B = topi.nn.relu(A)\n    s = te.create_schedule(B.op)\n    (y,) = s[B].op.axis\n    (yo, yi) = s[B].split(y, factor=8)\n    (yoo, yoi) = s[B].split(yo, factor=16)\n    s[B].reorder(yoo, yoi, yi)\n    s[B].unroll(yi)\n\n    ## But this does the right thing.\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        lowered_body = tvm.lower(s, [A, B], name=\"x\")[\"x\"].body\n\n        def visit_stmt(op):\n            return isinstance(op, tvm.tir.Max)\n\n        num_max = collect_visit(lowered_body, visit_stmt)\n        assert num_max.count(True) == 10\n\n\ndef test_double_splitting_with_indivisible_factors():\n    m = 48\n    dtype = \"float32\"\n    A = te.placeholder((m,), name=\"A\", dtype=dtype)\n    C = te.compute((m,), lambda i: A[i], name=\"C\")\n    D = te.compute((m,), lambda i: C[i], name=\"D\")\n\n    s = te.create_schedule(D.op)\n    co, ci = s[C].split(C.op.axis[0], factor=10)\n    do, di = s[D].split(D.op.axis[0], 32)\n    s[C].compute_at(s[D], do)\n\n    target = \"llvm\"\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        f = tvm.lower(s, [A, C, D], name=\"fadd1\", simple_mode=False)\n        func = tvm.build(f, target=target)\n\n    top_produce = f[\"fadd1\"].body\n    assert not any(collect_visit(top_produce, lambda x: isinstance(x, tvm.tir.IfThenElse)))\n\n    # check functional correctness of generated code\n    dev = tvm.device(target, 0)\n    a = tvm.nd.array(\n        numpy.ones(\n            m,\n        ).astype(dtype),\n        dev,\n    )\n    c = tvm.nd.array(\n        numpy.zeros(\n            m,\n        ).astype(dtype),\n        dev,\n    )\n    d = tvm.nd.array(\n        numpy.zeros(\n            m,\n        ).astype(dtype),\n        dev,\n    )\n    func(a, c, d)\n    tvm.testing.assert_allclose(c.numpy(), a.numpy(), rtol=1e-5)\n    tvm.testing.assert_allclose(d.numpy(), a.numpy(), rtol=1e-5)\n\n\ndef test_simple_rfactor():\n    K = 16 * 4 + 4\n    k = te.reduce_axis((0, K), \"k\")\n\n    A = te.placeholder((1, K), name=\"A\")\n\n    B = te.compute((1,), lambda b: te.sum(A[b, k], axis=k), name=\"B\")\n\n    s = te.create_schedule(B.op)\n    ko, _ = s[B].split(s[B].op.reduce_axis[0], 16)\n    BF = s.rfactor(B, ko, 0)\n\n    s.normalize()\n    bounds = tvm.te.schedule.InferBound(s)\n    stmt1 = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    mod1 = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt1))\n    stmt1 = tvm.tir.transform.Simplify()(mod1)[\"main\"].body\n\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod2 = tvm.tir.transform.LoopPartition()(mod1)\n        stmt2 = tvm.tir.transform.Simplify()(mod2)[\"main\"].body\n\n    # make sure loop partition actually did something\n    assert not tvm.ir.structural_equal(stmt1.body, stmt2.body)\n\n\n@T.prim_func\ndef partitioned_concat(\n    A: T.Buffer[(16,), \"float32\"], B: T.Buffer[(16,), \"float32\"], C: T.Buffer[(32,), \"float32\"]\n) -> None:\n    T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"main\", \"tir.noalias\": True})\n    T.preflattened_buffer(A, [16], data=A.data)\n    T.preflattened_buffer(B, [16], data=B.data)\n    T.preflattened_buffer(C, [32], data=C.data)\n    for i in T.serial(0, 16):\n        C[i] = A[i]\n    for i in T.serial(0, 16):\n        C[i + 16] = B[i + 16]\n\n\ndef test_explicit_partition_hint():\n    A = te.placeholder((16,), name=\"A\")\n    B = te.placeholder((16,), name=\"B\")\n    C = te.compute((32,), lambda i: te.if_then_else(i < 16, A[i], B[i]), name=\"C\")\n    s = te.create_schedule(C.op)\n    s.normalize()\n    s[C].pragma(s[C].op.axis[0], \"loop_partition_hint\", True)\n    mod = tvm.driver.build_module.schedule_to_module(s, [A, B, C], \"main\", None)\n    with tvm.transform.PassContext(config={\"tir.LoopPartition\": {\"partition_const_loop\": True}}):\n        mod = tvm.tir.transform.StorageFlatten(64)(mod)\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        mod = tvm.tir.transform.Simplify()(mod)\n    assert tvm.ir.structural_equal(mod[\"main\"], partitioned_concat)\n\n\ndef partition_from_scheduled_tir(prim_func, pass_cfg):\n    with tvm.transform.PassContext(config=pass_cfg):\n        mod = IRModule.from_expr(prim_func)\n        mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n        mod = tvm.tir.transform.FlattenBuffer()(mod)\n        mod = tvm.tir.transform.LoopPartition()(mod)\n        mod = tvm.tir.transform.Simplify()(mod)\n        mod = tvm.tir.transform.RemoveNoOp()(mod)\n        return mod\n\n\n@T.prim_func\ndef partitioned_concat_3(\n    placeholder: T.Buffer[(50176,), \"int8\"],\n    placeholder_1: T.Buffer[(25088,), \"int8\"],\n    placeholder_2: T.Buffer[(25088,), \"int8\"],\n    T_concat: T.Buffer[(100352,), \"int8\"],\n) -> None:\n    T.preflattened_buffer(placeholder, [1, 64, 28, 28], \"int8\", data=placeholder.data)\n    T.preflattened_buffer(placeholder_1, [1, 32, 28, 28], \"int8\", data=placeholder_1.data)\n    T.preflattened_buffer(placeholder_2, [1, 32, 28, 28], \"int8\", data=placeholder_2.data)\n    T.preflattened_buffer(T_concat, [1, 128, 28, 28], \"int8\", data=T_concat.data)\n    for i1, i2, i3 in T.grid(64, 28, 28):\n        T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3]\n    for i1, i2, i3 in T.grid(32, 28, 28):\n        T_concat[i1 * 784 + i2 * 28 + i3 + 50176] = placeholder_1[i1 * 784 + i2 * 28 + i3]\n    for i1, i2, i3 in T.grid(32, 28, 28):\n        T_concat[i1 * 784 + i2 * 28 + i3 + 75264] = placeholder_2[i1 * 784 + i2 * 28 + i3]\n\n\n@T.prim_func\ndef concat_func_3(\n    placeholder: T.Buffer[(50176,), \"int8\"],\n    placeholder_1: T.Buffer[(25088,), \"int8\"],\n    placeholder_2: T.Buffer[(25088,), \"int8\"],\n    T_concat: T.Buffer[(100352,), \"int8\"],\n) -> None:\n    T.preflattened_buffer(placeholder, (1, 64, 28, 28), \"int8\", data=placeholder.data)\n    T.preflattened_buffer(placeholder_1, (1, 32, 28, 28), \"int8\", data=placeholder_1.data)\n    T.preflattened_buffer(placeholder_2, (1, 32, 28, 28), \"int8\", data=placeholder_2.data)\n    T.preflattened_buffer(T_concat, (1, 128, 28, 28), \"int8\", data=T_concat.data)\n    for i1 in T.serial(128, annotations={\"pragma_loop_partition_hint\": 1}):\n        for i2, i3 in T.grid(28, 28):\n            if 96 <= i1:\n                T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_2[i1 * 784 + i2 * 28 + i3 - 75264]\n            if 64 <= i1 and i1 < 96:\n                T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_1[i1 * 784 + i2 * 28 + i3 - 50176]\n            if i1 < 64:\n                T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3]\n\n\ndef test_condition_mutually_exclusive():\n    mod = partition_from_scheduled_tir(\n        concat_func_3, {\"tir.LoopPartition\": {\"partition_const_loop\": True}}\n    )\n    assert tvm.ir.structural_equal(mod[\"main\"], partitioned_concat_3)\n\n\ndef test_loop_partition_unroll_hint():\n    @T.prim_func\n    def main(A: T.Buffer[150528, \"int8\"], B: T.Buffer[25088, \"int8\"]) -> None:\n        T.preflattened_buffer(A, [1, 3, 224, 224], \"int8\", data=A.data)\n        T.preflattened_buffer(B, [1, 224, 7, 16], \"int8\", data=B.data)\n        for ax0 in T.serial(\n            112,\n            annotations={\"pragma_loop_partition_hint\": True},\n        ):\n            for ax1, ax2, ax3 in T.grid(224, 7, 16):\n                if 3 <= ax0 * 2 + ax2 and ax0 * 2 + ax2 < 227 and ax3 < 3:\n                    B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax0 * 2 + ax2 - 3]\n\n    @T.prim_func\n    def partitioned_main(A: T.Buffer[150528, \"int8\"], B: T.Buffer[25088, \"int8\"]) -> None:\n        T.preflattened_buffer(A, [1, 3, 224, 224], dtype=\"int8\", data=A.data)\n        T.preflattened_buffer(B, [1, 224, 7, 16], dtype=\"int8\", data=B.data)\n        # body\n        for ax1, ax2, ax3 in T.grid(224, 7, 16):\n            if 3 <= ax2 and ax3 < 3:\n                B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax2 - 3]\n        for ax1, ax2, ax3 in T.grid(224, 7, 16):\n            if 1 <= ax2 and ax3 < 3:\n                B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax2 - 1]\n        for ax0, ax1, ax2, ax3 in T.grid(109, 224, 7, 16):\n            if ax3 < 3:\n                B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax0 * 2 + ax2 + 1]\n        for ax1, ax2, ax3 in T.grid(224, 7, 16):\n            if ax2 < 5 and ax3 < 3:\n                B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax2 + 219]\n\n    mod = partition_from_scheduled_tir(\n        main,\n        {\n            \"tir.LoopPartition\": {\n                \"partition_const_loop\": True,\n                \"unroll_loop_with_partition_hint_no_interval\": True,\n            }\n        },\n    )\n    mod = tvm.tir.transform.UnrollLoop()(mod)\n    mod = tvm.tir.transform.RemoveNoOp()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    assert tvm.ir.structural_equal(mod[\"main\"], partitioned_main)\n\n\ndef test_loop_partition_keep_loop_annotations():\n    @T.prim_func\n    def before(A: T.Buffer[160, \"int32\"], B: T.Buffer[160, \"int32\"]) -> None:\n        for i in T.serial(\n            160,\n            annotations={\"pragma_loop_partition_hint\": True, \"key\": \"value\"},\n        ):\n            if i < 10:\n                B[i] = A[i] + 1\n            elif 10 <= i and i < 150:\n                B[i] = A[i] + 2\n            else:\n                B[i] = A[i] + 3\n\n    @T.prim_func\n    def after(A: T.Buffer[160, \"int32\"], B: T.Buffer[160, \"int32\"]) -> None:\n        T.preflattened_buffer(A, [160], dtype=\"int32\", data=A.data)\n        T.preflattened_buffer(B, [160], dtype=\"int32\", data=B.data)\n        for i in T.serial(10, annotations={\"key\": \"value\"}):\n            B[i] = A[i] + 1\n        for i in T.serial(140, annotations={\"key\": \"value\"}):\n            B[i + 10] = A[i + 10] + 2\n        for i in T.serial(10, annotations={\"key\": \"value\"}):\n            B[i + 150] = A[i + 150] + 3\n\n    mod = partition_from_scheduled_tir(\n        before,\n        {\n            \"tir.LoopPartition\": {\n                \"partition_const_loop\": True,\n            }\n        },\n    )\n    assert tvm.ir.structural_equal(mod[\"main\"], after)\n\n\ndef test_loop_partition_with_unit_loop_in_condition():\n    @T.prim_func\n    def before(\n        placeholder: T.Buffer[(50176,), \"int8\"],\n        placeholder_1: T.Buffer[(25088,), \"int8\"],\n        placeholder_2: T.Buffer[(25088,), \"int8\"],\n        T_concat: T.Buffer[(100352,), \"int8\"],\n    ) -> None:\n        for k in range(1, annotations={\"preserve_unit_loop\": True}):\n            for i1 in T.serial(128, annotations={\"pragma_loop_partition_hint\": 1}):\n                for i2, i3 in T.grid(28, 28):\n                    if 96 <= k * 128 + i1:\n                        T_concat[k * i1 * 784 + i2 * 28 + i3] = placeholder_2[\n                            i1 * 784 + i2 * 28 + i3 - 75264\n                        ]\n                    if 64 <= k * 128 + i1 and k * 128 + i1 < 96:\n                        T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_1[\n                            i1 * 784 + i2 * 28 + i3 - 50176\n                        ]\n                    if k * 128 + i1 < 64:\n                        T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3]\n\n    @T.prim_func\n    def after(\n        placeholder: T.Buffer[50176, \"int8\"],\n        placeholder_1: T.Buffer[25088, \"int8\"],\n        placeholder_2: T.Buffer[25088, \"int8\"],\n        T_concat: T.Buffer[100352, \"int8\"],\n    ) -> None:\n        T.preflattened_buffer(placeholder, [50176], dtype=\"int8\", data=placeholder.data)\n        T.preflattened_buffer(placeholder_1, [25088], dtype=\"int8\", data=placeholder_1.data)\n        T.preflattened_buffer(placeholder_2, [25088], dtype=\"int8\", data=placeholder_2.data)\n        T.preflattened_buffer(T_concat, [100352], dtype=\"int8\", data=T_concat.data)\n        for _ in T.serial(1, annotations={\"preserve_unit_loop\": True}):\n            for i1, i2, i3 in T.grid(64, 28, 28):\n                T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3]\n            for i1, i2, i3 in T.grid(32, 28, 28):\n                T_concat[i1 * 784 + i2 * 28 + i3 + 50176] = placeholder_1[i1 * 784 + i2 * 28 + i3]\n            for i1, i2, i3 in T.grid(32, 28, 28):\n                T_concat[i2 * 28 + i3] = placeholder_2[i1 * 784 + i2 * 28 + i3]\n\n    mod = partition_from_scheduled_tir(\n        before,\n        {\n            \"tir.LoopPartition\": {\n                \"partition_const_loop\": True,\n            }\n        },\n    )\n    assert tvm.ir.structural_equal(mod[\"main\"], after)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_cross_thread_reduction.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring\nimport sys\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\ndef _check(original, transformed):\n    mod = tvm.IRModule.from_expr(original)\n    mod = tvm.tir.transform.LowerCrossThreadReduction()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed, True)\n\n\ndef _check_fail(original):\n    mod = tvm.IRModule.from_expr(original)\n    with pytest.raises(ValueError):\n        tvm.tir.transform.LowerCrossThreadReduction()(mod)\n\n\n@T.prim_func\ndef loop_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i, ko in T.grid(128, 4):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i)\n                vk = T.axis.R(128, ko * 32 + ki)\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef lowered_loop_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B_in_thread_init\"):\n                T.reads([])\n                T.writes([normal_reduce_temp0[0]])\n                normal_reduce_temp0[0] = T.float32(0)\n            for ko in T.serial(0, 4):\n                with T.block(\"B_normal_reduction\"):\n                    vi = T.axis.S(128, i)\n                    vk = T.axis.R(128, ko * 32 + ki)\n                    T.reads([A[vi, vk]])\n                    T.writes([normal_reduce_temp0[0]])\n                    normal_reduce_temp0[0] = normal_reduce_temp0[0] + A[vi, vk]\n            with T.block(\"B_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp0[0]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp0[0],\n                        True,\n                        reduce_temp0[0],\n                        ki,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.S(128, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef no_normal_reduction(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef lowered_no_normal_reduction(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B_cross_thread_reduction\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1), A[vi, vk], True, reduce_temp0[0], k, dtype=\"handle\"\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.spatial(128, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef two_bound_loops(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for ko in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n            for ki in T.thread_binding(0, 32, thread=\"threadIdx.y\"):\n                with T.block(\"B\"):\n                    vi = T.axis.spatial(128, i)\n                    vk = T.axis.reduce(128, ko * 32 + ki)\n                    T.reads([A[vi, vk]])\n                    T.writes([B[vi]])\n                    with T.init():\n                        B[vi] = T.float32(0)\n                    B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef lowered_two_bound_loops(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for ko in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n            for ki in T.thread_binding(0, 32, thread=\"threadIdx.y\"):\n                with T.block(\"B_cross_thread_reduction\"):\n                    vi = T.axis.spatial(128, i)\n                    vk = T.axis.reduce(128, ko * 32 + ki)\n                    T.reads([A[vi, vk]])\n                    T.writes([reduce_temp0[0]])\n                    T.attr(\n                        T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                        \"reduce_scope\",\n                        T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    )\n                    T.evaluate(\n                        T.tvm_thread_allreduce(\n                            T.uint32(1), A[vi, vk], True, reduce_temp0[0], ko, ki, dtype=\"handle\"\n                        )\n                    )\n                with T.block(\"B_write_back\"):\n                    vi = T.axis.spatial(128, i)\n                    T.reads([reduce_temp0[0]])\n                    T.writes([B[vi]])\n                    B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef multiple_blocks_under_reduction_loop(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16, 16], dtype=\"float32\")\n    B = T.match_buffer(b, [16], dtype=\"float32\")\n    B_rf_local = T.alloc_buffer([16, 16], dtype=\"float32\", scope=\"local\")\n    for i in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n        for k0o in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n            for k0i0, k1 in T.grid(4, 16):\n                with T.block(\"B_rf\"):\n                    vk0 = T.axis.spatial(16, k0o * 4 + k0i0)\n                    vi, vk1 = T.axis.remap(\"SR\", [i, k1])\n                    T.reads([A[vi, vk0, vk1]])\n                    T.writes([B_rf_local[vk0, vi]])\n                    with T.init():\n                        B_rf_local[vk0, vi] = T.float32(0)\n                    B_rf_local[vk0, vi] = B_rf_local[vk0, vi] + A[vi, vk0, vk1]\n            for k0i1 in T.serial(0, 4):\n                with T.block(\"B\"):\n                    vk0 = T.axis.reduce(16, k0o * 4 + k0i1)\n                    vi = T.axis.spatial(16, i)\n                    T.reads([B_rf_local[vk0, vi]])\n                    T.writes([B[vi]])\n                    with T.init():\n                        B[vi] = T.float32(0)\n                    B[vi] = B[vi] + B_rf_local[vk0, vi]\n\n\n@T.prim_func\ndef lowered_multiple_blocks_under_reduction_loop(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16, 16], dtype=\"float32\")\n    B = T.match_buffer(b, [16], dtype=\"float32\")\n    B_rf_local = T.alloc_buffer([16, 16], dtype=\"float32\", scope=\"local\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.thread_binding(0, 16, thread=\"blockIdx.x\"):\n        for k0o in T.thread_binding(0, 4, thread=\"threadIdx.x\"):\n            with T.block(\"B_in_thread_init\"):\n                T.reads([])\n                T.writes([normal_reduce_temp0[0]])\n                normal_reduce_temp0[0] = T.float32(0)\n            for k0i0, k1 in T.grid(4, 16):\n                with T.block(\"B_rf\"):\n                    vk0 = T.axis.spatial(16, k0o * 4 + k0i0)\n                    vi, vk1 = T.axis.remap(\"SR\", [i, k1])\n                    T.reads([A[vi, vk0, vk1]])\n                    T.writes([B_rf_local[vk0, vi]])\n                    with T.init():\n                        B_rf_local[vk0, vi] = T.float32(0)\n                    B_rf_local[vk0, vi] = B_rf_local[vk0, vi] + A[vi, vk0, vk1]\n            for k0i1 in T.serial(0, 4):\n                with T.block(\"B_normal_reduction\"):\n                    vk0 = T.axis.reduce(16, k0o * 4 + k0i1)\n                    vi = T.axis.spatial(16, i)\n                    T.reads([B_rf_local[vk0, vi]])\n                    T.writes([normal_reduce_temp0[0]])\n                    normal_reduce_temp0[0] = normal_reduce_temp0[0] + B_rf_local[vk0, vi]\n            with T.block(\"B_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp0[0]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp0[0],\n                        True,\n                        reduce_temp0[0],\n                        k0o,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.spatial(16, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef with_block_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 120], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i, ko in T.grid(128, 4):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi = T.axis.spatial(128, i)\n                vk = T.axis.reduce(120, ko * 32 + ki)\n                T.where(ko * 32 + ki < 120)\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef lowered_with_block_predicate(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 120], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B_in_thread_init\"):\n                T.reads([])\n                T.writes([normal_reduce_temp0[0]])\n                normal_reduce_temp0[0] = T.float32(0)\n            for ko in T.serial(0, 4):\n                with T.block(\"B_normal_reduction\"):\n                    vi = T.axis.spatial(128, i)\n                    vk = T.axis.reduce(120, ko * 32 + ki)\n                    T.where(ko * 32 + ki < 120)\n                    T.reads([A[vi, vk]])\n                    T.writes([normal_reduce_temp0[0]])\n                    normal_reduce_temp0[0] = normal_reduce_temp0[0] + A[vi, vk]\n            with T.block(\"B_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp0[0]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp0[0],\n                        True,\n                        reduce_temp0[0],\n                        ki,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.spatial(128, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef single_reduction_loop_with_block_predicate(\n    A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n) -> None:\n    T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    for i0 in T.serial(256):\n        for ax0, ax1_0 in T.grid(1, 1):\n            for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_maxelem\"):\n                    i0_1 = T.axis.spatial(256, i0 + ax0)\n                    k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                    T.where(ax1_0 * 512 + ax1_1 < 256)\n                    T.reads(A[i0_1, k])\n                    T.writes(T_softmax_maxelem_shared[i0_1])\n                    with T.init():\n                        T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38)\n                    T_softmax_maxelem_shared[i0_1] = T.max(\n                        T_softmax_maxelem_shared[i0_1], A[i0_1, k]\n                    )\n        for ax0, ax1_0 in T.grid(1, 1):\n            for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_expsum\"):\n                    i0_2 = T.axis.spatial(256, i0 + ax0)\n                    k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                    T.where(ax1_0 * 512 + ax1_1 < 256)\n                    T.reads(A[i0_2, k], T_softmax_maxelem_shared[i0_2])\n                    T.writes(T_softmax_expsum_shared[i0_2])\n                    with T.init():\n                        T_softmax_expsum_shared[i0_2] = T.float32(0)\n                    T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(\n                        A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\"\n                    )\n        for i1_0 in T.serial(1):\n            for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_norm\"):\n                    i0_3 = T.axis.spatial(256, i0)\n                    i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                    T.where(i1_0 * 512 + i1_1 < 256)\n                    T.reads(\n                        A[i0_3, i1], T_softmax_maxelem_shared[i0_3], T_softmax_expsum_shared[i0_3]\n                    )\n                    T.writes(T_softmax_norm[i0_3, i1])\n                    T.block_attr({\"axis\": 1})\n                    T_softmax_norm[i0_3, i1] = (\n                        T.exp(A[i0_3, i1] - T_softmax_maxelem_shared[i0_3], dtype=\"float32\")\n                        / T_softmax_expsum_shared[i0_3]\n                    )\n\n\n@T.prim_func\ndef lowered_single_reduction_loop_with_block_predicate(\n    A: T.Buffer[(256, 256), \"float32\"], T_softmax_norm: T.Buffer[(256, 256), \"float32\"]\n) -> None:\n    T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    cross_thread_0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    cross_thread_1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i0 in T.serial(256):\n        for ax0 in T.serial(1):\n            for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_maxelem_in_thread_init\"):\n                    T.reads()\n                    T.writes(in_thread_0[0])\n                    in_thread_0[0] = T.float32(-3.4028234663852886e38)\n                for ax1_0 in T.serial(1):\n                    with T.block(\"T_softmax_maxelem_in_thread\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_1 = T.axis.spatial(256, i0 + ax0)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_1, k])\n                        T.writes(in_thread_0[0])\n                        in_thread_0[0] = T.max(in_thread_0[0], A[i0_1, k])\n                with T.block(\"T_softmax_maxelem_cross_thread\"):\n                    T.reads(in_thread_0[0])\n                    T.writes(cross_thread_0[0])\n                    T.attr(\n                        T.comm_reducer(\n                            lambda x, y: T.max(x, y), [T.float32(-3.4028234663852886e38)]\n                        ),\n                        \"reduce_scope\",\n                        T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    )\n                    T.evaluate(\n                        T.tvm_thread_allreduce(\n                            T.uint32(1),\n                            in_thread_0[0],\n                            True,\n                            cross_thread_0[0],\n                            ax1_1,\n                            dtype=\"handle\",\n                        )\n                    )\n                with T.block(\"T_softmax_maxelem_write_back\"):\n                    i0_2 = T.axis.spatial(256, i0 + ax0)\n                    T.reads(cross_thread_0[0])\n                    T.writes(T_softmax_maxelem_shared[i0_2])\n                    T_softmax_maxelem_shared[i0_2] = cross_thread_0[0]\n        for ax0 in T.serial(1):\n            for ax1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_expsum_in_thread_init\"):\n                    T.reads()\n                    T.writes(in_thread_1[0])\n                    in_thread_1[0] = T.float32(0)\n                for ax1_0 in T.serial(1):\n                    with T.block(\"T_softmax_expsum_in_thread\"):\n                        T.where(ax1_0 * 512 + ax1_1 < 256)\n                        i0_3 = T.axis.spatial(256, i0 + ax0)\n                        k = T.axis.reduce(256, ax1_0 * 512 + ax1_1)\n                        T.reads(A[i0_3, k], T_softmax_maxelem_shared[i0_3])\n                        T.writes(in_thread_1[0])\n                        in_thread_1[0] = in_thread_1[0] + T.exp(\n                            A[i0_3, k] - T_softmax_maxelem_shared[i0_3], dtype=\"float32\"\n                        )\n                with T.block(\"T_softmax_expsum_cross_thread\"):\n                    T.reads(in_thread_1[0])\n                    T.writes(cross_thread_1[0])\n                    T.attr(\n                        T.comm_reducer(lambda x_1, y_1: x_1 + y_1, [T.float32(0)]),\n                        \"reduce_scope\",\n                        T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                    )\n                    T.evaluate(\n                        T.tvm_thread_allreduce(\n                            T.uint32(1),\n                            in_thread_1[0],\n                            True,\n                            cross_thread_1[0],\n                            ax1_1,\n                            dtype=\"handle\",\n                        )\n                    )\n                with T.block(\"T_softmax_expsum_write_back\"):\n                    i0_4 = T.axis.spatial(256, i0 + ax0)\n                    T.reads(cross_thread_1[0])\n                    T.writes(T_softmax_expsum_shared[i0_4])\n                    T_softmax_expsum_shared[i0_4] = cross_thread_1[0]\n        for i1_0 in T.serial(1):\n            for i1_1 in T.thread_binding(512, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_norm\"):\n                    i0_5 = T.axis.spatial(256, i0)\n                    i1 = T.axis.spatial(256, i1_0 * 512 + i1_1)\n                    T.where(i1_0 * 512 + i1_1 < 256)\n                    T.reads(\n                        A[i0_5, i1], T_softmax_maxelem_shared[i0_5], T_softmax_expsum_shared[i0_5]\n                    )\n                    T.writes(T_softmax_norm[i0_5, i1])\n                    T.block_attr({\"axis\": 1})\n                    T_softmax_norm[i0_5, i1] = (\n                        T.exp(A[i0_5, i1] - T_softmax_maxelem_shared[i0_5], dtype=\"float32\")\n                        / T_softmax_expsum_shared[i0_5]\n                    )\n\n\n@T.prim_func\ndef single_reduction_loop_with_tensorize(\n    input_A: T.Buffer[(1, 64, 7, 7, 32), \"uint8\"],\n    input_B: T.Buffer[(16, 64, 1, 1, 8, 32, 4), \"int8\"],\n    output: T.Buffer[(1, 16, 7, 7, 32), \"int32\"],\n) -> None:\n    # body\n    # with T.block(\"root\")\n    for i1, i2, i3, i4, i5 in T.grid(16, 4, 98, 2, 32):\n        with T.block(\"compute_o\"):\n            n = T.axis.spatial(1, 0)\n            oc_chunk = T.axis.spatial(16, i1)\n            oh = T.axis.spatial(7, (i2 * 6272 + i3 * 64 + i4 * 32 + i5) // 3584)\n            ow = T.axis.spatial(7, (i2 * 6272 + i3 * 64 + i4 * 32 + i5) % 3584 // 512)\n            kh = T.axis.reduce(1, 0)\n            kw = T.axis.reduce(1, 0)\n            ic_outer = T.axis.reduce(64, (i2 * 6272 + i3 * 64 + i4 * 32 + i5) % 512 // 8)\n            ic_f_inner = T.axis.reduce(8, (i2 * 6272 + i3 * 64 + i4 * 32 + i5) % 8)\n            T.reads(\n                input_A[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4],\n                input_B[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:32, 0:4],\n            )\n            T.writes(output[n, oc_chunk, oh, ow, 0:32])\n            with T.init():\n                for x in T.serial(32):\n                    with T.block(\"compute_init\"):\n                        oc_block_i_init = T.axis.spatial(32, x)\n                        T.reads()\n                        T.writes(output[n, oc_chunk, oh, ow, oc_block_i_init])\n                        output[n, oc_chunk, oh, ow, oc_block_i_init] = 0\n            with T.block(\"compute_o\"):\n                T.reads(\n                    output[n, oc_chunk, oh, ow, 0:32],\n                    input_A[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4],\n                    input_B[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:32, 0:4],\n                )\n                T.writes(output[n, oc_chunk, oh, ow, 0:32])\n                A = T.match_buffer(\n                    input_A[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4],\n                    [4],\n                    dtype=\"uint8\",\n                    offset_factor=1,\n                )\n                B = T.match_buffer(\n                    input_B[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:32, 0:4],\n                    [32, 4],\n                    dtype=\"int8\",\n                    offset_factor=1,\n                )\n                C = T.match_buffer(\n                    output[n, oc_chunk, oh, ow, 0:32], [32], dtype=\"int32\", offset_factor=1\n                )\n                A_u8x4: T.uint8x4 = A[0:4]\n                A_i32: T.int32 = T.reinterpret(A_u8x4, dtype=\"int32\")\n                B_i8x128 = B[0, 0:128]\n                B_i32x32: T.int32x32 = T.reinterpret(B_i8x128, dtype=\"int32x32\")\n                C[0:32] = T.call_llvm_pure_intrin(\n                    4217, T.uint32(3), C[0:32], T.broadcast(A_i32, 32), B_i32x32, dtype=\"int32x32\"\n                )\n\n\n@T.prim_func\ndef reducer_max(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.min_value(\"float32\")\n                B[vi] = T.max(B[vi], A[vi, vk])\n\n\n@T.prim_func\ndef lowered_reducer_max(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B_cross_thread_reduction\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: T.max(x, y), [T.min_value(\"float32\")]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1), A[vi, vk], True, reduce_temp0[0], k, dtype=\"handle\"\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.spatial(128, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n@T.prim_func\ndef zero_rank_buffer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128], dtype=\"float32\")\n    B = T.match_buffer(b, [], dtype=\"float32\")\n    for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        with T.block(\"B\"):\n            vk = T.axis.reduce(128, k)\n            T.reads([A[vk]])\n            T.writes([B[()]])\n            with T.init():\n                B[()] = T.float32(0)\n            B[()] = B[()] + A[vk]\n\n\n@T.prim_func\ndef lowered_zero_rank_buffer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128], dtype=\"float32\")\n    B = T.match_buffer(b, [], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        with T.block(\"B_cross_thread_reduction\"):\n            vk = T.axis.reduce(128, k)\n            T.reads([A[vk]])\n            T.writes([reduce_temp0[0]])\n            T.attr(\n                T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                \"reduce_scope\",\n                T.reinterpret(T.uint64(0), dtype=\"handle\"),\n            )\n            T.evaluate(\n                T.tvm_thread_allreduce(T.uint32(1), A[vk], True, reduce_temp0[0], k, dtype=\"handle\")\n            )\n        with T.block(\"B_write_back\"):\n            T.reads([reduce_temp0[0]])\n            T.writes([B[()]])\n            B[()] = reduce_temp0[0]\n\n\n@T.prim_func\ndef multiple_bufferstore(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    C = T.alloc_buffer([], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk], B[vi], C[()]])\n                T.writes([B[vi], C[()]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                C[()] = A[vi, vk]\n                B[vi] = B[vi] + C[()]\n\n\n@T.prim_func\ndef reduction_loop_not_deepest(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n        for i in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef reduction_loop_bound_to_blockidx(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"blockIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n@T.prim_func\ndef different_access_indices(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    for i, j in T.grid(128, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                T.reads([A[vi, vj, vk]])\n                T.writes(\n                    [\n                        B[\n                            T.min(vj, vi) : T.min(vj, vi) + (T.max(vj, vi) + 1 - T.min(vj, vi)),\n                            T.min(vi, vj) : T.min(vi, vj) + (T.max(vi, vj) + 1 - T.min(vi, vj)),\n                        ]\n                    ]\n                )\n                with T.init():\n                    B[vj, vi] = T.float32(0)\n                B[vi, vj] = B[vi, vj] + A[vi, vj, vk]\n\n\n@T.prim_func\ndef invalid_reducer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i in T.serial(0, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vk = T.axis.remap(\"SR\", [i, k])\n                T.reads([A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] - A[vi, vk]\n\n\n@T.prim_func\ndef softmax(var_A: T.handle, var_T_softmax_norm: T.handle) -> None:\n    A = T.match_buffer(var_A, [256, 256], dtype=\"float32\")\n    T_softmax_norm = T.match_buffer(var_T_softmax_norm, [256, 256], dtype=\"float32\")\n    T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    for i0 in T.thread_binding(0, 256, thread=\"blockIdx.x\"):\n        for ax0_0 in T.serial(0, 8):\n            for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_maxelem\"):\n                    i0_1 = T.axis.spatial(256, i0)\n                    k = T.axis.reduce(256, ax0_0 * 32 + ax0_1)\n                    T.reads([A[i0_1, k]])\n                    T.writes([T_softmax_maxelem_shared[i0_1]])\n                    with T.init():\n                        T_softmax_maxelem_shared[i0_1] = T.min_value(\"float32\")\n                    T_softmax_maxelem_shared[i0_1] = T.max(\n                        T_softmax_maxelem_shared[i0_1], A[i0_1, k]\n                    )\n        for ax0_0 in T.serial(0, 8):\n            for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_expsum\"):\n                    i0_2 = T.axis.spatial(256, i0)\n                    k = T.axis.reduce(256, ax0_0 * 32 + ax0_1)\n                    T.reads(\n                        [\n                            A[i0_2, k],\n                            T_softmax_maxelem_shared[i0_2],\n                        ]\n                    )\n                    T.writes([T_softmax_expsum_shared[i0_2]])\n                    with T.init():\n                        T_softmax_expsum_shared[i0_2] = T.float32(0)\n                    T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(\n                        A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype=\"float32\"\n                    )\n        for i1_0 in T.serial(0, 8):\n            for i1_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_norm\"):\n                    i0_3 = T.axis.spatial(256, i0)\n                    i1 = T.axis.spatial(256, i1_0 * 32 + i1_1)\n                    T.reads(\n                        [\n                            A[i0_3, i1],\n                            T_softmax_maxelem_shared[i0_3],\n                            T_softmax_expsum_shared[i0_3],\n                        ]\n                    )\n                    T.writes([T_softmax_norm[i0_3, i1]])\n                    T.block_attr({\"axis\": 1})\n                    T_softmax_norm[i0_3, i1] = (\n                        T.exp(\n                            A[i0_3, i1] - T_softmax_maxelem_shared[i0_3],\n                            dtype=\"float32\",\n                        )\n                        / T_softmax_expsum_shared[i0_3]\n                    )\n\n\n@T.prim_func\ndef lowered_softmax(var_A: T.handle, var_T_softmax_norm: T.handle) -> None:\n    A = T.match_buffer(var_A, [256, 256], dtype=\"float32\")\n    T_softmax_norm = T.match_buffer(var_T_softmax_norm, [256, 256], dtype=\"float32\")\n    T_softmax_maxelem_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    T_softmax_expsum_shared = T.alloc_buffer([256], dtype=\"float32\", scope=\"shared\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    reduce_temp1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i0 in T.thread_binding(0, 256, thread=\"blockIdx.x\"):\n        for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"T_softmax_maxelem_normal_reduction_init\"):\n                T.reads([])\n                T.writes([normal_reduce_temp0[0]])\n                normal_reduce_temp0[0] = T.min_value(\"float32\")\n            for ax0_0 in T.serial(0, 8):\n                with T.block(\"T_softmax_maxelem_normal_reduction\"):\n                    i0_1 = T.axis.spatial(256, i0)\n                    k = T.axis.reduce(256, ax0_0 * 32 + ax0_1)\n                    T.reads([A[i0_1, k]])\n                    T.writes([normal_reduce_temp0[0]])\n                    normal_reduce_temp0[0] = T.max(normal_reduce_temp0[0], A[i0_1, k])\n            with T.block(\"T_softmax_maxelem_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp0[0]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: T.max(x, y), [T.min_value(\"float32\")]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp0[0],\n                        True,\n                        reduce_temp0[0],\n                        ax0_1,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"T_softmax_maxelem_write_back\"):\n                i0_2 = T.axis.spatial(256, i0)\n                T.reads([reduce_temp0[0]])\n                T.writes([T_softmax_maxelem_shared[i0_2]])\n                T_softmax_maxelem_shared[i0_2] = reduce_temp0[0]\n        for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"T_softmax_expsum_normal_reduction_init\"):\n                T.reads([])\n                T.writes([normal_reduce_temp1[0]])\n                normal_reduce_temp1[0] = T.float32(0)\n            for ax0_0 in T.serial(0, 8):\n                with T.block(\"T_softmax_expsum_normal_reduction\"):\n                    i0_3 = T.axis.spatial(256, i0)\n                    k = T.axis.reduce(256, ax0_0 * 32 + ax0_1)\n                    T.reads(\n                        [\n                            A[i0_3, k],\n                            T_softmax_maxelem_shared[i0_3],\n                        ]\n                    )\n                    T.writes([normal_reduce_temp1[0]])\n                    normal_reduce_temp1[0] = normal_reduce_temp1[0] + T.exp(\n                        A[i0_3, k] - T_softmax_maxelem_shared[i0_3], dtype=\"float32\"\n                    )\n            with T.block(\"T_softmax_expsum_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp1[0]])\n                T.writes([reduce_temp1[0]])\n                T.attr(\n                    T.comm_reducer(lambda x_1, y_1: x_1 + y_1, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp1[0],\n                        True,\n                        reduce_temp1[0],\n                        ax0_1,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"T_softmax_expsum_write_back\"):\n                i0_4 = T.axis.spatial(256, i0)\n                T.reads([reduce_temp1[0]])\n                T.writes([T_softmax_expsum_shared[i0_4]])\n                T_softmax_expsum_shared[i0_4] = reduce_temp1[0]\n        for i1_0 in T.serial(0, 8):\n            for i1_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n                with T.block(\"T_softmax_norm\"):\n                    i0_5 = T.axis.spatial(256, i0)\n                    i1 = T.axis.spatial(256, i1_0 * 32 + i1_1)\n                    T.reads(\n                        [\n                            A[i0_5, i1],\n                            T_softmax_maxelem_shared[i0_5],\n                            T_softmax_expsum_shared[i0_5],\n                        ]\n                    )\n                    T.writes([T_softmax_norm[i0_5, i1]])\n                    T.block_attr({\"axis\": 1})\n                    T_softmax_norm[i0_5, i1] = (\n                        T.exp(\n                            A[i0_5, i1] - T_softmax_maxelem_shared[i0_5],\n                            dtype=\"float32\",\n                        )\n                        / T_softmax_expsum_shared[i0_5]\n                    )\n\n\n@T.prim_func\ndef argmax_split(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0 in T.grid(128, 4):\n        for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n            with T.block(\"argmax\"):\n                i = T.axis.spatial(128, i0)\n                k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                with T.init():\n                    argmax_v0[i] = -1\n                    argmax_v1[i] = T.float32(-3.4028234663852886e38)\n                v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k])\n                v_argmax_v1: T.float32 = T.Select(\n                    argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]\n                )\n                argmax_v0[i] = v_argmax_v0\n                argmax_v1[i] = v_argmax_v1\n\n\n@T.prim_func\ndef lowered_argmax_split(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmax_v0: T.Buffer[(128,), \"int32\"],\n    argmax_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    cross_thread_argmax_v0 = T.alloc_buffer([1], dtype=\"int32\", strides=[1], scope=\"local\")\n    cross_thread_argmax_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_argmax_v0 = T.alloc_buffer([1], dtype=\"int32\", strides=[1], scope=\"local\")\n    in_thread_argmax_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i0 in T.serial(128):\n        for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n            with T.block(\"argmax_in_thread_init\"):\n                T.reads()\n                T.writes(in_thread_argmax_v0[0], in_thread_argmax_v1[0])\n                in_thread_argmax_v0[0] = -1\n                in_thread_argmax_v1[0] = T.float32(-3.4028234663852886e38)\n            for i1_0 in T.serial(4):\n                with T.block(\"argmax_in_thread\"):\n                    i = T.axis.spatial(128, i0)\n                    k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n                    T.reads(idx[i, k], val[i, k])\n                    T.writes(in_thread_argmax_v0[0], in_thread_argmax_v1[0])\n                    v_argmax_v0: T.int32 = T.Select(\n                        in_thread_argmax_v1[0] >= val[i, k], in_thread_argmax_v0[0], idx[i, k]\n                    )\n                    v_argmax_v1: T.float32 = T.Select(\n                        in_thread_argmax_v1[0] >= val[i, k], in_thread_argmax_v1[0], val[i, k]\n                    )\n                    in_thread_argmax_v0[0] = v_argmax_v0\n                    in_thread_argmax_v1[0] = v_argmax_v1\n            with T.block(\"argmax_cross_thread\"):\n                T.reads(in_thread_argmax_v0[0], in_thread_argmax_v1[0])\n                T.writes(cross_thread_argmax_v0[0], cross_thread_argmax_v1[0])\n                T.attr(\n                    T.comm_reducer(\n                        lambda x0, x1, y0, y1: (\n                            T.Select(x1 >= y1, x0, y0),\n                            T.Select(x1 >= y1, x1, y1),\n                        ),\n                        [-1, T.float32(-3.4028234663852886e38)],\n                    ),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(2),\n                        in_thread_argmax_v0[0],\n                        in_thread_argmax_v1[0],\n                        True,\n                        cross_thread_argmax_v0[0],\n                        cross_thread_argmax_v1[0],\n                        i1_1,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"argmax_write_back\"):\n                i = T.axis.spatial(128, i0)\n                T.reads(cross_thread_argmax_v0[0], cross_thread_argmax_v1[0])\n                T.writes(argmax_v0[i], argmax_v1[i])\n                argmax_v0[i] = cross_thread_argmax_v0[0]\n                argmax_v1[i] = cross_thread_argmax_v1[0]\n\n\n@T.prim_func\ndef argmin_split_init_update_reordered(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmin_v0: T.Buffer[(128,), \"int32\"],\n    argmin_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    for i0, i1_0 in T.grid(128, 4):\n        for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n            with T.block(\"argmin\"):\n                i = T.axis.spatial(128, i0)\n                k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n                T.reads(idx[i, k], val[i, k])\n                T.writes(argmin_v0[i], argmin_v1[i])\n                with T.init():\n                    argmin_v1[i] = T.float32(3.4028234663852886e38)\n                    argmin_v0[i] = -1\n                v_argmin_v0: T.int32 = T.Select(argmin_v1[i] <= val[i, k], argmin_v0[i], idx[i, k])\n                v_argmin_v1: T.float32 = T.Select(\n                    argmin_v1[i] <= val[i, k], argmin_v1[i], val[i, k]\n                )\n                argmin_v1[i] = v_argmin_v1\n                argmin_v0[i] = v_argmin_v0\n\n\n@T.prim_func\ndef lowered_argmin_split_init_update_reordered(\n    idx: T.Buffer[(128, 128), \"int32\"],\n    val: T.Buffer[(128, 128), \"float32\"],\n    argmin_v0: T.Buffer[(128,), \"int32\"],\n    argmin_v1: T.Buffer[(128,), \"float32\"],\n) -> None:\n    cross_thread_argmin_v0 = T.alloc_buffer([1], dtype=\"int32\", strides=[1], scope=\"local\")\n    cross_thread_argmin_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_argmin_v0 = T.alloc_buffer([1], dtype=\"int32\", strides=[1], scope=\"local\")\n    in_thread_argmin_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i0 in T.serial(128):\n        for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n            with T.block(\"argmin_in_thread_init\"):\n                T.reads()\n                T.writes(in_thread_argmin_v0[0], in_thread_argmin_v1[0])\n                in_thread_argmin_v0[0] = -1\n                in_thread_argmin_v1[0] = T.float32(3.4028234663852886e38)\n            for i1_0 in T.serial(4):\n                with T.block(\"argmin_in_thread\"):\n                    i = T.axis.spatial(128, i0)\n                    k = T.axis.reduce(128, i1_0 * 32 + i1_1)\n                    T.reads(idx[i, k], val[i, k])\n                    T.writes(in_thread_argmin_v0[0], in_thread_argmin_v1[0])\n                    v_argmin_v0: T.int32 = T.Select(\n                        in_thread_argmin_v1[0] <= val[i, k], in_thread_argmin_v0[0], idx[i, k]\n                    )\n                    v_argmin_v1: T.float32 = T.Select(\n                        in_thread_argmin_v1[0] <= val[i, k], in_thread_argmin_v1[0], val[i, k]\n                    )\n                    in_thread_argmin_v1[0] = v_argmin_v1\n                    in_thread_argmin_v0[0] = v_argmin_v0\n            with T.block(\"argmin_cross_thread\"):\n                T.reads(in_thread_argmin_v0[0], in_thread_argmin_v1[0])\n                T.writes(cross_thread_argmin_v0[0], cross_thread_argmin_v1[0])\n                T.attr(\n                    T.comm_reducer(\n                        lambda x0, x1, y0, y1: (\n                            T.Select(x1 <= y1, x0, y0),\n                            T.Select(x1 <= y1, x1, y1),\n                        ),\n                        [-1, T.float32(3.4028234663852886e38)],\n                    ),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(2),\n                        in_thread_argmin_v0[0],\n                        in_thread_argmin_v1[0],\n                        True,\n                        cross_thread_argmin_v0[0],\n                        cross_thread_argmin_v1[0],\n                        i1_1,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"argmin_write_back\"):\n                i = T.axis.spatial(128, i0)\n                T.reads(cross_thread_argmin_v0[0], cross_thread_argmin_v1[0])\n                T.writes(argmin_v0[i], argmin_v1[i])\n                argmin_v0[i] = cross_thread_argmin_v0[0]\n                argmin_v1[i] = cross_thread_argmin_v1[0]\n\n\n@T.prim_func\ndef layer_norm_tuple_sum(\n    data: T.Buffer[(128, 768), \"float32\"],\n    gamma: T.Buffer[768, \"float32\"],\n    bias: T.Buffer[768, \"float32\"],\n    T_layer_norm: T.Buffer[(128, 768), \"float32\"],\n) -> None:\n    data_red_temp_v0 = T.alloc_buffer([128], dtype=\"float32\")\n    data_red_temp_v1 = T.alloc_buffer([128], dtype=\"float32\")\n    for i0_fused in T.thread_binding(128, thread=\"blockIdx.x\"):\n        for i1_0 in T.serial(24):\n            for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n                with T.block(\"data_red_temp\"):\n                    ax0 = T.axis.spatial(128, i0_fused)\n                    k1 = T.axis.reduce(768, i1_0 * 32 + i1_1)\n                    T.reads(data[ax0, k1])\n                    T.writes(data_red_temp_v0[ax0], data_red_temp_v1[ax0])\n                    with T.init():\n                        data_red_temp_v0[ax0] = T.float32(0)\n                        data_red_temp_v1[ax0] = T.float32(0)\n                    v_data_red_temp_v0: T.float32 = data_red_temp_v0[ax0] + data[ax0, k1]\n                    v_data_red_temp_v1: T.float32 = (\n                        data_red_temp_v1[ax0] + data[ax0, k1] * data[ax0, k1]\n                    )\n                    data_red_temp_v0[ax0] = v_data_red_temp_v0\n                    data_red_temp_v1[ax0] = v_data_red_temp_v1\n    for i0_i1_fused_0 in T.thread_binding(384, thread=\"blockIdx.x\"):\n        for i0_i1_fused_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n            with T.block(\"T_layer_norm\"):\n                ax0 = T.axis.spatial(128, (i0_i1_fused_0 * 256 + i0_i1_fused_1) // 768)\n                ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 256 + i0_i1_fused_1) % 768)\n                T.reads(\n                    data[ax0, ax1],\n                    data_red_temp_v0[ax0],\n                    data_red_temp_v1[ax0],\n                    gamma[ax1],\n                    bias[ax1],\n                )\n                T.writes(T_layer_norm[ax0, ax1])\n                T_layer_norm[ax0, ax1] = (\n                    data[ax0, ax1] - data_red_temp_v0[ax0] * T.float32(0.0013020833333333333)\n                ) * T.rsqrt(\n                    data_red_temp_v1[ax0] * T.float32(0.0013020833333333333)\n                    - data_red_temp_v0[ax0]\n                    * T.float32(0.0013020833333333333)\n                    * (data_red_temp_v0[ax0] * T.float32(0.0013020833333333333))\n                    + T.float32(1.0000000000000001e-05),\n                    dtype=\"float32\",\n                ) * gamma[\n                    ax1\n                ] + bias[\n                    ax1\n                ]\n\n\n@T.prim_func\ndef lowered_layer_norm_tuple_sum(\n    data: T.Buffer[(128, 768), \"float32\"],\n    gamma: T.Buffer[768, \"float32\"],\n    bias: T.Buffer[768, \"float32\"],\n    T_layer_norm: T.Buffer[(128, 768), \"float32\"],\n) -> None:\n    # with T.block(\"root\")\n    data_red_temp_v0 = T.alloc_buffer([128], dtype=\"float32\")\n    data_red_temp_v1 = T.alloc_buffer([128], dtype=\"float32\")\n    cross_thread_data_red_temp_v0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    cross_thread_data_red_temp_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_data_red_temp_v0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    in_thread_data_red_temp_v1 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i0_fused in T.thread_binding(128, thread=\"blockIdx.x\"):\n        for i1_1 in T.thread_binding(32, thread=\"threadIdx.x\"):\n            with T.block(\"data_red_temp_in_thread_init\"):\n                T.reads()\n                T.writes(in_thread_data_red_temp_v0[0], in_thread_data_red_temp_v1[0])\n                in_thread_data_red_temp_v0[0] = T.float32(0)\n                in_thread_data_red_temp_v1[0] = T.float32(0)\n            for i1_0 in T.serial(24):\n                with T.block(\"data_red_temp_in_thread\"):\n                    ax0 = T.axis.spatial(128, i0_fused)\n                    k1 = T.axis.reduce(768, i1_0 * 32 + i1_1)\n                    T.reads(data[ax0, k1])\n                    T.writes(in_thread_data_red_temp_v0[0], in_thread_data_red_temp_v1[0])\n                    v_data_red_temp_v0: T.float32 = in_thread_data_red_temp_v0[0] + data[ax0, k1]\n                    v_data_red_temp_v1: T.float32 = (\n                        in_thread_data_red_temp_v1[0] + data[ax0, k1] * data[ax0, k1]\n                    )\n                    in_thread_data_red_temp_v0[0] = v_data_red_temp_v0\n                    in_thread_data_red_temp_v1[0] = v_data_red_temp_v1\n            with T.block(\"data_red_temp_cross_thread\"):\n                T.reads(in_thread_data_red_temp_v0[0], in_thread_data_red_temp_v1[0])\n                T.writes(cross_thread_data_red_temp_v0[0], cross_thread_data_red_temp_v1[0])\n                T.attr(\n                    T.comm_reducer(\n                        lambda x0, x1, y0, y1: (x0 + y0, x1 + y1), [T.float32(0), T.float32(0)]\n                    ),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(2),\n                        in_thread_data_red_temp_v0[0],\n                        in_thread_data_red_temp_v1[0],\n                        True,\n                        cross_thread_data_red_temp_v0[0],\n                        cross_thread_data_red_temp_v1[0],\n                        i1_1,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"data_red_temp_write_back\"):\n                ax0 = T.axis.spatial(128, i0_fused)\n                T.reads(cross_thread_data_red_temp_v0[0], cross_thread_data_red_temp_v1[0])\n                T.writes(data_red_temp_v0[ax0], data_red_temp_v1[ax0])\n                data_red_temp_v0[ax0] = cross_thread_data_red_temp_v0[0]\n                data_red_temp_v1[ax0] = cross_thread_data_red_temp_v1[0]\n    for i0_i1_fused_0 in T.thread_binding(384, thread=\"blockIdx.x\"):\n        for i0_i1_fused_1 in T.thread_binding(256, thread=\"threadIdx.x\"):\n            with T.block(\"T_layer_norm\"):\n                ax0 = T.axis.spatial(128, (i0_i1_fused_0 * 256 + i0_i1_fused_1) // 768)\n                ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 256 + i0_i1_fused_1) % 768)\n                T.reads(\n                    data[ax0, ax1],\n                    data_red_temp_v0[ax0],\n                    data_red_temp_v1[ax0],\n                    gamma[ax1],\n                    bias[ax1],\n                )\n                T.writes(T_layer_norm[ax0, ax1])\n                T_layer_norm[ax0, ax1] = (\n                    data[ax0, ax1] - data_red_temp_v0[ax0] * T.float32(0.0013020833333333333)\n                ) * T.rsqrt(\n                    data_red_temp_v1[ax0] * T.float32(0.0013020833333333333)\n                    - data_red_temp_v0[ax0]\n                    * T.float32(0.0013020833333333333)\n                    * (data_red_temp_v0[ax0] * T.float32(0.0013020833333333333))\n                    + T.float32(1.0000000000000001e-05),\n                    dtype=\"float32\",\n                ) * gamma[\n                    ax1\n                ] + bias[\n                    ax1\n                ]\n\n\n# pylint: enable=no-member,invalid-name,unused-variable,unexpected-keyword-arg\n\n\ndef test_loop_split():\n    _check(loop_split, lowered_loop_split)\n\n\ndef test_no_normal_reduction():\n    _check(no_normal_reduction, lowered_no_normal_reduction)\n\n\ndef test_two_bound_loops():\n    _check(two_bound_loops, lowered_two_bound_loops)\n\n\ndef test_multiple_blocks_under_reduction_loop():\n    _check(multiple_blocks_under_reduction_loop, lowered_multiple_blocks_under_reduction_loop)\n\n\ndef test_with_block_predicate():\n    _check(with_block_predicate, lowered_with_block_predicate)\n\n\ndef test_single_reduction_loop_with_block_predicate():\n    _check(\n        single_reduction_loop_with_block_predicate,\n        lowered_single_reduction_loop_with_block_predicate,\n    )\n\n\ndef test_single_reduction_loop_with_tensorize():\n    _check(\n        single_reduction_loop_with_tensorize,\n        single_reduction_loop_with_tensorize,\n    )\n\n\ndef test_reducer_max():\n    _check(reducer_max, lowered_reducer_max)\n\n\ndef test_zero_rank_buffer():\n    _check(zero_rank_buffer, lowered_zero_rank_buffer)\n\n\ndef test_multiple_bufferstore():\n    _check_fail(multiple_bufferstore)\n\n\ndef test_reduction_block_not_deepest():\n    _check_fail(reduction_loop_not_deepest)\n\n\ndef test_reduction_loop_bound_to_blockidx():\n    _check_fail(reduction_loop_bound_to_blockidx)\n\n\ndef test_different_access_indices():\n    _check_fail(different_access_indices)\n\n\ndef test_invalid_reducer():\n    _check_fail(invalid_reducer)\n\n\ndef test_softmax():\n    _check(softmax, lowered_softmax)\n\n\ndef test_argmax_split():\n    _check(argmax_split, lowered_argmax_split)\n\n\ndef test_argmin_split_init_update_reordered():\n    _check(argmin_split_init_update_reordered, lowered_argmin_split_init_update_reordered)\n\n\ndef test_lower_te():\n    a = te.placeholder((32, 2, 2))\n    k1 = te.reduce_axis((0, 2), \"k1\")\n    k2 = te.reduce_axis((0, 2), \"k2\")\n    b = te.compute((32,), lambda i: te.sum(a[i, k1, k2], axis=[k1, k2]))\n    s = te.create_schedule(b.op)\n    s[b].bind(k1, te.thread_axis(\"threadIdx.x\"))\n    s[b].bind(k2, te.thread_axis(\"threadIdx.y\"))\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [a, b])\n    mod = tvm.tir.transform.LowerCrossThreadReduction()(orig_mod)\n    tvm.ir.assert_structural_equal(\n        mod, orig_mod\n    )  # LowerCrossThreadReduction should do nothing on TE\n\n\ndef test_layer_norm_tuple_sum():\n    _check(layer_norm_tuple_sum, lowered_layer_norm_tuple_sum)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_init_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.script import tir as T\n\n# pylint: disable=no-self-argument\n\n\n@tvm.script.ir_module\nclass WithInit:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, [64, 64, 64])\n        B = T.match_buffer(b, [64])\n\n        for i0, j0 in T.grid(64, 64):\n            for k0 in T.serial(32, 64):\n                with T.block():\n                    i, j, k = T.axis.remap(\"SRR\", [i0, j0, k0])\n                    with T.init():\n                        B[i] = T.float32(0)\n                    B[i] += A[i, j, k]\n\n\n@tvm.script.ir_module\nclass WithBranch:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, [64, 64, 64])\n        B = T.match_buffer(b, [64])\n\n        for i0, j0 in T.grid(64, 64):\n            for k0 in T.serial(32, 64):\n                with T.block():\n                    i, j, k = T.axis.remap(\"SRR\", [i0, j0, k0])\n                    T.reads(A[i, j, k])\n                    T.writes(B[i])\n                    if (j == 0) and (k == 32):\n                        B[i] = T.float32(0)\n                    B[i] += A[i, j, k]\n\n\n@tvm.script.ir_module\nclass InitWithMatchBuffer:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, [64, 64, 64])\n        B = T.match_buffer(b, [64])\n\n        for i0, j0 in T.grid(64, 64):\n            for k0 in T.serial(32, 64):\n                with T.block():\n                    i, j, k = T.axis.remap(\"SRR\", [i0, j0, k0])\n                    BB = T.match_buffer(B[i], ())\n                    AA = T.match_buffer(A[i, 0:64, 0:64], (64, 64))\n                    with T.init():\n                        BB[()] = T.float32(0)\n                    BB[()] += AA[j, k]\n\n\n@tvm.script.ir_module\nclass BranchWithMatchBuffer:\n    @T.prim_func\n    def main(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, [64, 64, 64])\n        B = T.match_buffer(b, [64])\n\n        for i0, j0 in T.grid(64, 64):\n            for k0 in T.serial(32, 64):\n                with T.block():\n                    i, j, k = T.axis.remap(\"SRR\", [i0, j0, k0])\n                    T.reads(A[i, j, k])\n                    T.writes(B[i])\n                    BB = T.match_buffer(B[i], ())\n                    AA = T.match_buffer(A[i, 0:64, 0:64], (64, 64))\n                    if (j == 0) and (k == 32):\n                        BB[()] = T.float32(0)\n                    BB[()] += AA[j, k]\n\n\ndef test_lower_reduction():\n    origin_mod = WithInit\n    mod = tvm.tir.transform.LowerInitBlock()(origin_mod)\n    tvm.ir.assert_structural_equal(mod, WithBranch, True)\n\n\ndef test_lower_match_buffer():\n    origin_mod = InitWithMatchBuffer\n    mod = tvm.tir.transform.LowerInitBlock()(origin_mod)\n    tvm.ir.assert_structural_equal(mod, BranchWithMatchBuffer, True)\n\n\ndef test_lower_te():\n    x = te.placeholder((1,))\n    y = te.compute((1,), lambda i: x[i] + 2)\n    s = te.create_schedule(y.op)\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n    mod = tvm.tir.transform.LowerInitBlock()(orig_mod)\n    tvm.ir.assert_structural_equal(mod, orig_mod)  # LowerInitBlock should do nothing on TE\n\n\nif __name__ == \"__main__\":\n    test_lower_reduction()\n    test_lower_match_buffer()\n    test_lower_te()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\n\n\ndef lower_intrin(params, stmt):\n    \"\"\"wrapper to call transformation in stmt\"\"\"\n    lower_expr = isinstance(stmt, tvm.tir.PrimExpr)\n    stmt = tvm.tir.Evaluate(stmt) if lower_expr else stmt\n    mod = tvm.IRModule.from_expr(\n        tvm.tir.PrimFunc(params, stmt).with_attr(\"target\", tvm.target.Target(\"llvm\"))\n    )\n    mod = tvm.transform.Sequential([tvm.tir.transform.Simplify(), tvm.tir.transform.LowerIntrin()])(\n        mod\n    )\n    func = mod[\"main\"]\n    stmt = func.body\n    return stmt.value if lower_expr else stmt.body\n\n\ndef check_value(expr, vx, vy, data, fref):\n    n = len(data)\n    A = te.placeholder((n,), name=\"A\", dtype=expr.dtype)\n    B = te.placeholder((n,), name=\"B\", dtype=expr.dtype)\n\n    def make_binds(i):\n        x = expr\n        x = tvm.tir.Let(vx, A[i], x)\n        x = tvm.tir.Let(vy, B[i], x)\n        return x\n\n    C = te.compute((n,), make_binds)\n    s = te.create_schedule([C.op])\n\n    f = tvm.build(s, [A, B, C], \"llvm\")\n    a = tvm.nd.array(np.array([x for x, y in data], dtype=expr.dtype))\n    b = tvm.nd.array(np.array([y for x, y in data], dtype=expr.dtype))\n    c = tvm.nd.array(np.zeros(len(data), dtype=expr.dtype))\n    f(a, b, c)\n    cref = np.array([fref(x, y) for x, y in data])\n    np.testing.assert_equal(c.numpy(), cref)\n\n\ndef get_ref_data():\n    \"\"\"Get reference data for every pairs\"\"\"\n    import itertools\n\n    x = range(-10, 10)\n    y = list(range(-10, 10))\n    y.remove(0)\n    return list(itertools.product(x, y))\n\n\n@tvm.testing.requires_llvm\ndef test_lower_floordiv():\n    data = get_ref_data()\n    for dtype in [\"int32\", \"int64\", \"int16\"]:\n        x = te.var(\"x\", dtype=dtype)\n        y = te.var(\"y\", dtype=dtype)\n        zero = tvm.tir.const(0, dtype)\n        # no constraints\n        res = lower_intrin([x, y], tvm.te.floordiv(x, y))\n        check_value(res, x, y, data, lambda a, b: a // b)\n        # rhs >= 0\n        res = lower_intrin([x, y], tvm.tir.Select(y >= 0, tvm.te.floordiv(x, y), zero))\n        check_value(res, x, y, data, lambda a, b: a // b if b > 0 else 0)\n        # involves max\n        res = lower_intrin(\n            [x, y], tvm.tir.Select(y >= 0, tvm.te.max(tvm.te.floordiv(x, y), zero), zero)\n        )\n        check_value(res, x, y, data, lambda a, b: max(a // b, 0) if b > 0 else 0)\n        # lhs >= 0\n        res = lower_intrin(\n            [x, y], tvm.tir.Select(tvm.tir.all(y >= 0, x >= 0), tvm.te.floordiv(x, y), zero)\n        )\n        check_value(res, x, y, data, lambda a, b: a // b if b > 0 and a >= 0 else 0)\n        # const power of two\n        res = lower_intrin([x, y], tvm.te.floordiv(x, tvm.tir.const(8, dtype=dtype)))\n        check_value(res, x, y, [(a, b) for a, b in data if b == 8], lambda a, b: a // b)\n\n\n@tvm.testing.requires_llvm\ndef test_lower_floormod():\n    data = get_ref_data()\n    for dtype in [\"int32\", \"int64\", \"int16\"]:\n        x = te.var(\"x\", dtype=dtype)\n        y = te.var(\"y\", dtype=dtype)\n        zero = tvm.tir.const(0, dtype)\n        # no constraints\n        res = lower_intrin([x, y], tvm.te.floormod(x, y))\n        check_value(res, x, y, data, lambda a, b: a % b)\n        # rhs >= 0\n        res = lower_intrin([x, y], tvm.tir.Select(y >= 0, tvm.te.floormod(x, y), zero))\n        check_value(res, x, y, data, lambda a, b: a % b if b > 0 else 0)\n        # lhs >= 0\n        res = lower_intrin(\n            [x, y], tvm.tir.Select(tvm.tir.all(y >= 0, x >= 0), tvm.te.floormod(x, y), zero)\n        )\n        check_value(res, x, y, data, lambda a, b: a % b if b > 0 and a >= 0 else 0)\n        # const power of two\n        res = lower_intrin([x, y], tvm.te.floormod(x, tvm.tir.const(8, dtype=dtype)))\n        check_value(res, x, y, [(a, b) for a, b in data if b == 8], lambda a, b: a % b)\n\n\nif __name__ == \"__main__\":\n    test_lower_floordiv()\n    test_lower_floormod()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_opaque_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed, True)\n\n\n@T.prim_func\ndef compacted_elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in range(0, 16):\n        with T.block():\n            T.reads(A[i, 0:16])\n            T.writes(C[i, 0:16])\n            B = T.alloc_buffer([1, 16], \"float32\", scope=\"global\")\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[0, j])\n                    B[0, j] = A[i, j] + 1.0\n            for j in range(0, 16):\n                with T.block():\n                    T.reads(B[0, j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[0, j] * 2.0\n\n\n@T.prim_func\ndef transformed_elementwise_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i in T.serial(0, 16):\n        B_new = T.decl_buffer(shape=[1, 16], dtype=\"float32\")\n        for j in T.serial(0, 16):\n            B_new[0, j] = A[i, j] + 1.0\n        for j in T.serial(0, 16):\n            C[i, j] = B_new[0, j] * 2.0\n\n\n@T.prim_func\ndef compacted_gpu_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in T.thread_binding(0, 4, thread=\"blockIdx.x\"):\n        for i1 in T.thread_binding(0, 2, thread=\"threadIdx.x\"):\n            for i2 in T.thread_binding(0, 2, thread=\"vthread\"):\n                with T.block():\n                    T.reads(A[i0 * 4 + i1 * 2 + i2, 0:16])\n                    T.writes(C[i0 * 4 + i1 * 2 + i2, 0:16])\n                    B = T.alloc_buffer([1, 16], \"float32\", scope=\"local\")\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(A[i0 * 4 + i1 * 2 + i2, j])\n                            T.writes(B[0, j])\n                            B[0, j] = A[i0 * 4 + i1 * 2 + i2, j] + 1.0\n                    for j in range(0, 16):\n                        with T.block():\n                            T.reads(B[0, j])\n                            T.writes(C[i0 * 4 + i1 * 2 + i2, j])\n                            C[i0 * 4 + i1 * 2 + i2, j] = B[0, j] * 2.0\n\n\n@T.prim_func\ndef transformed_gpu_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n\n    i0 = T.env_thread(\"blockIdx.x\")\n    i1 = T.env_thread(\"threadIdx.x\")\n    i2 = T.env_thread(\"vthread\")\n\n    T.launch_thread(i0, 4)\n    T.launch_thread(i1, 2)\n    T.launch_thread(i2, 2)\n    B = T.decl_buffer(shape=[1, 16], dtype=\"float32\", scope=\"local\")\n    for j in range(0, 16):\n        B[0, j] = A[i0 * 4 + i1 * 2 + i2, j] + 1.0\n    for j in range(0, 16):\n        C[i0 * 4 + i1 * 2 + i2, j] = B[0, j] * 2.0\n\n\n@T.prim_func\ndef compacted_symbolic_func(a: T.handle, c: T.handle, n: T.int32, m: T.int32) -> None:\n    A = T.match_buffer(a, (n, m), \"float32\")\n    C = T.match_buffer(c, (n, m), \"float32\")\n\n    for i in range(0, n):\n        with T.block():\n            T.reads(A[i, m])\n            T.writes(C[i, m])\n            B = T.alloc_buffer((m,), \"float32\", scope=\"global\")\n            for j in range(0, m):\n                with T.block():\n                    T.reads(A[i, j])\n                    T.writes(B[j])\n                    B[j] = A[i, j] + 1.0\n            for j in range(0, m):\n                with T.block():\n                    T.reads(B[j])\n                    T.writes(C[i, j])\n                    C[i, j] = B[j] * 2.0\n\n\n@T.prim_func\ndef transformed_symbolic_func(a: T.handle, c: T.handle, n: T.int32, m: T.int32) -> None:\n    A = T.match_buffer(a, (n, m), \"float32\")\n    C = T.match_buffer(c, (n, m), \"float32\")\n\n    for i in range(0, n):\n        B = T.decl_buffer(shape=[m], dtype=\"float32\")\n        for j in range(0, m):\n            B[j] = A[i, j] + 1.0\n        for j in range(0, m):\n            C[i, j] = B[j] * 2.0\n\n\n@T.prim_func\ndef compacted_predicate_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    C = T.match_buffer(c, (32), \"float32\")\n\n    for i, j in T.grid(5, 7):\n        with T.block():\n            T.reads(A[i * 7 + j])\n            T.writes(C[i * 7 + j])\n            T.where(i * 7 + j < 32)\n            C[i * 7 + j] = A[i * 7 + j] + 1.0\n\n\n@T.prim_func\ndef transformed_predicate_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    C = T.match_buffer(c, (32), \"float32\")\n\n    for i, j in T.grid(5, 7):\n        if i * 7 + j < 32:\n            C[i * 7 + j] = A[i * 7 + j] + 1.0\n\n\n@T.prim_func\ndef compacted_unit_loop_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    C = T.match_buffer(c, (32), \"float32\")\n\n    for x, y, z in T.grid(4, 1, 8):\n        with T.block():\n            T.reads(A[x * 8 + y * 8 + z])\n            T.writes(C[x * 8 + y * 8 + z])\n            C[x * 8 + y * 8 + z] = A[x * 8 + y * 8 + z] + 1.0\n\n\n@T.prim_func\ndef transformed_unit_loop_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    C = T.match_buffer(c, (32), \"float32\")\n\n    for x, z in T.grid(4, 8):\n        C[x * 8 + z] = A[x * 8 + z] + 1.0\n\n\n@T.prim_func\ndef compacted_multi_alloc_func(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    D = T.match_buffer(d, (32), \"float32\")\n\n    for i in range(0, 32):\n        with T.block():\n            T.reads(A[i])\n            T.writes(D[i])\n            B = T.alloc_buffer((32,), scope=\"global\")\n            C = T.alloc_buffer((32,), scope=\"global\")\n            B[i] = A[i] + 1.0\n            C[i] = A[i] + B[i]\n            D[i] = C[i] * 2.0\n\n\n@T.prim_func\ndef transformed_multi_alloc_func(a: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (32), \"float32\")\n    D = T.match_buffer(d, (32), \"float32\")\n\n    for i in range(0, 32):\n        B = T.decl_buffer(shape=(32,), dtype=\"float32\")\n        C = T.decl_buffer(shape=(32,), dtype=\"float32\")\n        B[i] = A[i] + 1.0\n        C[i] = A[i] + B[i]\n        D[i] = C[i] * 2.0\n\n\n@T.prim_func\ndef compacted_strided_buffer_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16), \"float32\")\n    C = T.match_buffer(c, (16, 16), \"float32\")\n    for i0 in range(0, 4):\n        with T.block():\n            T.reads(A[i0 * 4 : i0 * 4 + 4, 0:16])\n            T.writes(C[i0 * 4 : i0 * 4 + 4, 0:16])\n            B = T.alloc_buffer([4, 16], \"float32\", strides=[17, 1], scope=\"global\")\n            for i1 in range(0, 4):\n                for j in range(0, 16):\n                    with T.block():\n                        T.reads(A[i0 * 4 + i1, j])\n                        T.writes(B[i1, j])\n                        B[i1, j] = A[i0 * 4 + i1, j] + 1.0\n            for i1 in range(0, 4):\n                for j in range(0, 16):\n                    with T.block():\n                        T.reads(B[i1, j])\n                        T.writes(C[i0 * 4 + i1, j])\n                        C[i0 * 4 + i1, j] = B[i1, j] * 2.0\n\n\n@T.prim_func\ndef transformed_strided_buffer_func(\n    A: T.Buffer[(16, 16), \"float32\"], C: T.Buffer[(16, 16), \"float32\"]\n) -> None:\n    # body\n    for i0 in T.serial(4):\n        B_data = T.allocate([4, 17], \"float32\", \"global\")\n        B = T.decl_buffer(shape=[4, 16], dtype=\"float32\", strides=[17, 1], data=B_data)\n        for i1, j in T.grid(4, 16):\n            B[i1, j] = A[i0 * 4 + i1, j] + T.float32(1)\n        for i1, j in T.grid(4, 16):\n            C[i0 * 4 + i1, j] = B[i1, j] * T.float32(2)\n\n\n@T.prim_func\ndef annotated_loops(a: T.handle) -> None:\n    A = T.match_buffer(a, (16,), \"float32\")\n    for i in range(0, 16, annotations={\"pragma_1\": \"str_value\", \"pragma_2\": 1, \"pragma_3\": 0.0}):\n        A[i] = 0.0\n\n\n@T.prim_func\ndef boolean_handling_before(a: T.Buffer[10, \"bool\"], b: T.Buffer[10, \"bool\"]) -> None:\n    for i0 in T.serial(10):\n        with T.block(\"b\"):\n            T.reads(a[i0])\n            T.writes(b[i0])\n            b[i0] = a[i0]\n\n\n@T.prim_func\ndef boolean_handling_after(a: T.Buffer[10, \"bool\"], b: T.Buffer[10, \"bool\"]) -> None:\n    # body\n    for i0 in T.serial(10):\n        b[i0] = a[i0]\n\n\ndef test_elementwise():\n    _check(compacted_elementwise_func, transformed_elementwise_func)\n\n\ndef test_gpu_workload():\n    _check(compacted_gpu_func, transformed_gpu_func)\n\n\ndef test_symbolic_shape():\n    _check(compacted_symbolic_func, transformed_symbolic_func)\n\n\ndef test_predicate():\n    _check(compacted_predicate_func, transformed_predicate_func)\n\n\ndef test_unit_loops():\n    _check(compacted_unit_loop_func, transformed_unit_loop_func)\n\n\ndef test_multi_alloc():\n    _check(compacted_multi_alloc_func, transformed_multi_alloc_func)\n\n\ndef test_strided_buffer():\n    _check(compacted_strided_buffer_func, transformed_strided_buffer_func)\n\n\ndef test_lower_te():\n    x = te.placeholder((1,))\n    y = te.compute((1,), lambda i: x[i] + 2)\n    s = te.create_schedule(y.op)\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n    mod = tvm.tir.transform.LowerOpaqueBlock()(orig_mod)\n    tvm.ir.assert_structural_equal(mod, orig_mod)  # LowerOpaqueBlock should do nothing on TE\n\n\ndef test_annotated_loops():\n    mod = tvm.IRModule.from_expr(annotated_loops)\n    mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n    attr1 = mod[\"main\"].body\n    attr2 = attr1.body\n    attr3 = attr2.body\n    assert attr1.attr_key == \"pragma_1\" and attr1.value == \"str_value\"\n    assert attr2.attr_key == \"pragma_2\"\n    tvm.ir.assert_structural_equal(attr2.value, tvm.tir.IntImm(\"int32\", 1))\n    assert attr3.attr_key == \"pragma_3\"\n    tvm.ir.assert_structural_equal(attr3.value, tvm.tir.FloatImm(\"float32\", 0.0))\n\n\ndef test_annotated_block():\n    @T.prim_func\n    def annotated_block() -> None:\n        with T.block():\n            T.block_attr({\"pragma_1\": \"str_value\", \"pragma_2\": 1, \"pragma_3\": 0.0})\n            T.evaluate(0)\n\n    mod = tvm.IRModule.from_expr(annotated_block)\n    mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n    attr1 = mod[\"main\"].body\n    attr2 = attr1.body\n    attr3 = attr2.body\n    assert attr1.attr_key == \"pragma_1\" and attr1.value == \"str_value\"\n    assert attr2.attr_key == \"pragma_2\"\n    tvm.ir.assert_structural_equal(attr2.value, tvm.tir.IntImm(\"int32\", 1))\n    assert attr3.attr_key == \"pragma_3\"\n    tvm.ir.assert_structural_equal(attr3.value, tvm.tir.FloatImm(\"float32\", 0.0))\n\n\ndef test_preserved_annotations():\n    @T.prim_func\n    def before(A: T.Buffer[8, \"float32\"], B: T.Buffer[8, \"float32\"]):\n        for i in T.serial(8, annotations={\"k_0\": 1, \"k_1\": [2, 3], \"k_2\": 3.14}):\n            with T.block(\"block\"):\n                T.block_attr({\"k_3\": \"oops\"})\n                B[i] = A[i] + 1.0\n\n    @T.prim_func\n    def after(A: T.Buffer[8, \"float32\"], B: T.Buffer[8, \"float32\"]):\n        for i in T.serial(8, annotations={\"k_0\": 1, \"k_1\": [2, 3], \"k_2\": 3.14}):\n            B[i] = A[i] + 1.0\n\n    mod = tvm.IRModule.from_expr(before)\n    mod = tvm.tir.transform.LowerOpaqueBlock()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], after)\n\n\ndef test_boolean_handling():\n    _check(boolean_handling_before, boolean_handling_after)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_tvm_builtin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import testing\n\n\n@tvm.register_func(\"tvm.test_matmul\")\ndef my_matmul(a, b, c):\n    c.copyfrom(np.dot(a.numpy(), b.numpy()))\n\n\ndef check_packed_func(target=\"llvm\"):\n    ib = tvm.tir.ir_builder.create()\n\n    m = n = k = 16\n\n    #\n    # Prepare buffer for a, b and c:\n    #\n    a = te.placeholder((m, k), name=\"a\", dtype=\"float64\")\n    b = te.placeholder((k, n), name=\"b\", dtype=\"float64\")\n    k = te.reduce_axis((0, k), name=\"k\")\n    c = te.compute((m, n), lambda i, j: te.sum(a[i, k] * b[k, j], axis=k), name=\"c\")\n\n    a_buffer = tvm.tir.decl_buffer(\n        a.shape, a.dtype, name=\"a_buffer\", offset_factor=1, strides=[te.var(\"s1\"), 1]\n    )\n    b_buffer = tvm.tir.decl_buffer(\n        b.shape, b.dtype, name=\"b_buffer\", offset_factor=1, strides=[te.var(\"s2\"), 1]\n    )\n    c_buffer = tvm.tir.decl_buffer(\n        c.shape, c.dtype, name=\"c_buffer\", offset_factor=1, strides=[te.var(\"s3\"), 1]\n    )\n\n    with ib.for_range(0, 10, \"i\", kind=\"parallel\"):\n        ib.emit(tvm.tir.call_packed(\"tvm.test_matmul\", a_buffer, b_buffer, c_buffer))\n\n    stmt = ib.get()\n\n    # Construct a valid IRModule to be lowered:\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([a_buffer, b_buffer, c_buffer], stmt))\n\n    target = tvm.target.Target(target)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", target))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n    mod = tvm.tir.transform.MakePackedAPI()(mod)\n\n    # Do the lowering:\n    mod = tvm.tir.transform.LowerTVMBuiltin()(mod)\n\n    # Get the PrimFunc from module:\n    prim_func = mod.functions.items()[0][1]\n\n    node = prim_func.body\n\n    # Recursively visit PrimFunc until we meet the for-loop:\n    while isinstance(node, (tvm.tir.AssertStmt, tvm.tir.LetStmt, tvm.tir.AttrStmt)):\n        node = node.body\n\n    # For-loop:\n    assert isinstance(node, tvm.tir.stmt.For)\n\n    #\n    # let stack_tcode = tir.tvm_stack_alloca(\"arg_tcode\", 4)\n    #\n    alloca_tcode = node.body\n    assert isinstance(alloca_tcode, tvm.tir.LetStmt)\n\n    expected_value = tvm.tir.call_intrin(\n        \"handle\", tvm.ir.Op.get(\"tir.tvm_stack_alloca\"), \"arg_tcode\", 4\n    )\n    expected_var = alloca_tcode.var\n    expected_stmt = tvm.tir.LetStmt(expected_var, expected_value, alloca_tcode.body)\n\n    tvm.ir.assert_structural_equal(alloca_tcode, expected_stmt, map_free_vars=True)\n\n    #\n    # let stack_value = tir.tvm_stack_alloca(\"arg_value\", 4)\n    #\n    alloca_value = alloca_tcode.body\n    assert isinstance(alloca_value, tvm.tir.LetStmt)\n\n    expected_value = tvm.tir.call_intrin(\n        \"handle\", tvm.ir.Op.get(\"tir.tvm_stack_alloca\"), \"arg_value\", 4\n    )\n    expected_var = alloca_value.var\n    expected_stmt = tvm.tir.LetStmt(expected_var, expected_value, alloca_value.body)\n\n    tvm.ir.assert_structural_equal(alloca_value, expected_stmt, map_free_vars=True)\n\n    #\n    # let stack_array = tir.tvm_stack_alloca(\"array\", 3)\n    #\n    alloca_array = alloca_value.body\n    assert isinstance(alloca_array, tvm.tir.LetStmt)\n\n    expected_value = tvm.tir.call_intrin(\n        \"handle\", tvm.ir.Op.get(\"tir.tvm_stack_alloca\"), \"array\", 3\n    )\n    expected_var = alloca_array.var\n    expected_stmt = tvm.tir.LetStmt(expected_var, expected_value, alloca_array.body)\n\n    tvm.ir.assert_structural_equal(alloca_array, expected_stmt, map_free_vars=True)\n\n    #\n    # let stack_shape = tir.tvm_stack_alloca(\"shape\", 12)\n    #\n    alloca_shape = alloca_array.body\n    assert isinstance(alloca_shape, tvm.tir.LetStmt)\n\n    expected_value = tvm.tir.call_intrin(\n        \"handle\", tvm.ir.Op.get(\"tir.tvm_stack_alloca\"), \"shape\", 12\n    )\n    expected_var = alloca_shape.var\n    expected_stmt = tvm.tir.LetStmt(expected_var, expected_value, alloca_shape.body)\n\n    tvm.ir.assert_structural_equal(alloca_shape, expected_stmt, map_free_vars=True)\n\n\ndef test_lower_packed_func():\n    check_packed_func(\"llvm\")\n    check_packed_func(\"stackvm\")\n\n\n@tvm.testing.requires_llvm\ndef test_call_packed_return_non_i32():\n    # This call packed that return non i32 types\n    expected_value = np.array([1.2, 1.4], dtype=\"float32\")\n\n    def packed_echo(value):\n        return tvm.tir.call_intrin(\n            value.dtype, tvm.ir.Op.get(\"tir.tvm_call_packed\"), \"testing.echo\", value\n        )\n\n    def build_tir():\n        Ab = tvm.tir.decl_buffer((2,), \"float32\")\n        ib = tvm.tir.ir_builder.create()\n        Aptr = ib.buffer_ptr(Ab)\n        # return f32\n        # Aptr[0] = testing.echo(expected_value[0])\n        Aptr[0] = packed_echo(tvm.tir.const(expected_value[0], \"float32\"))\n        # return handle\n        # let Aptr_var = testing.echo(Aptr) in Aptr_var[1] = expected_value[1]\n        Aptr_var = ib.let(\"Aptr_dup\", packed_echo(Aptr.asobject().data))\n        ib.emit(tvm.tir.BufferStore(Aptr, tvm.tir.const(expected_value[1], \"float32\"), [1]))\n\n        stmt = ib.get()\n        return tvm.IRModule.from_expr(\n            tvm.tir.PrimFunc([Ab], stmt).with_attr(\"global_symbol\", \"packed_test\")\n        )\n\n    mod = build_tir()\n    f = tvm.build(mod, None, \"llvm\")\n    a = tvm.nd.array(np.zeros(2, dtype=\"float32\"))\n    f(a)\n    tvm.testing.assert_allclose(a.numpy(), expected_value)\n\n\nif __name__ == \"__main__\":\n    test_call_packed_return_non_i32()\n    test_lower_packed_func()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_lower_warp_memory.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.contrib.nvcc import have_fp16\n\nimport numpy as np\nimport tvm.testing\nimport pytest\n\n\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_local_scope():\n    m = 128\n    A = te.placeholder((m,), name=\"A\")\n    B = te.compute((m,), lambda i: A[i] + 3, name=\"B\")\n\n    s = te.create_schedule(B.op)\n    AA = s.cache_read(A, \"warp\", [B])\n    xo, xi = s[B].split(B.op.axis[0], 64)\n    xi0, xi1 = s[B].split(xi, factor=32)\n    tx = te.thread_axis(\"threadIdx.x\")\n    s[B].bind(xi1, tx)\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[AA].compute_at(s[B], xo)\n    xo, xi = s[AA].split(s[AA].op.axis[0], 32)\n    s[AA].bind(xi, tx)\n\n    cuda_target = tvm.target.Target(\"cuda\")\n    assert cuda_target.thread_warp_size == 32\n    # lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        mod = tvm.lower(s, [A, B], name=\"f\")\n\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", cuda_target))(mod)\n    fdevice = tvm.tir.transform.SplitHostDevice()(mod)[\"f_kernel0\"]\n    mod = tvm.IRModule.from_expr(fdevice)\n    fdevice = tvm.tir.transform.LowerWarpMemory()(mod)[\"f_kernel0\"]\n    allocate = fdevice.body.body\n    assert allocate.buffer_var.type_annotation.storage_scope == \"local\"\n    assert fdevice.body.body.extents[0].value == 2\n\n\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_correct_indices():\n    n = 32\n    A = te.placeholder((2, n, n), name=\"A\", dtype=\"float32\")\n    C = te.compute((2, n, n), lambda x, i, j: A(x, i, (j + 1) % n), name=\"C\")\n\n    s = te.create_schedule(C.op)\n    bk_x = te.thread_axis(\"blockIdx.x\")\n    th_y = te.thread_axis(\"threadIdx.y\")\n    th_x = te.thread_axis(\"threadIdx.x\")\n    B = s.cache_read(A, \"warp\", [C])\n    cx, ci, cj = C.op.axis\n    bx, bi, bj = B.op.axis\n    s[C].bind(cj, th_x)\n    s[C].bind(cx, bk_x)\n    s[B].compute_at(s[C], cx)\n    s[B].bind(bi, th_y)\n    s[B].bind(bj, th_x)\n\n    bounds = tvm.te.schedule.InferBound(s)\n    ir = tvm.te.schedule.ScheduleOps(s, bounds)\n    inner_func = ir.body.body.body\n    store_A_warp = inner_func.seq[0].body.body\n    indices = list(store_A_warp.indices)\n\n    # A.warp is actually many buffers, one for each warp, although they are all called A.warp\n    # 1. If we are accessing from different threads within a same warp (different\n    #    threadIdx.x), we need to distinguish between each elements using threadIdx.x,\n    #    so threadIdx.x is one if the indices.\n    # 2. If we are accessing from different warps (different threadIdx.y), we are actually\n    #    assessing different buffers, so there is no need to distinguish from elements,\n    #    and therefore threadIdx.y is NOT a index.\n    idx_names = map(lambda x: x.name, filter(lambda x: type(x) is tvm.tir.expr.Var, indices))\n    assert \"threadIdx.x\" in idx_names\n    assert \"threadIdx.y\" not in idx_names\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_cuda_end_to_end():\n    def check_cuda(dtype):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        m = 128\n        A = te.placeholder((m,), name=\"A\", dtype=dtype)\n        B = te.compute((m,), lambda i: A[i // 32 * 32 + (i + 1) % 32], name=\"B\")\n\n        cuda_target = tvm.target.Target(\"cuda\")\n        assert cuda_target.thread_warp_size == 32\n        with cuda_target:\n            s = te.create_schedule(B.op)\n            AA = s.cache_read(A, \"warp\", [B])\n            xo, xi = s[B].split(B.op.axis[0], 64)\n            xi0, xi1 = s[B].split(xi, factor=32)\n            tx = te.thread_axis(\"threadIdx.x\")\n            s[B].bind(xi1, tx)\n            s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n            s[AA].compute_at(s[B], xo)\n            xo, xi = s[AA].split(s[AA].op.axis[0], 32)\n            s[AA].bind(xi, tx)\n\n            dev = tvm.cuda(0)\n            # building with the CSE pass disabled as otherwise it would do some commoning\n            with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n                func = tvm.build(s, [A, B], \"cuda\")\n            A_np = np.array(list(range(m)), dtype=dtype)\n            B_np = np.array(\n                list(range(1, 32))\n                + [0]\n                + list(range(33, 64))\n                + [32]\n                + list(range(65, 96))\n                + [64]\n                + list(range(97, 128))\n                + [96],\n                dtype=dtype,\n            )\n            A_nd = tvm.nd.array(A_np, dev)\n            B_nd = tvm.nd.array(np.zeros(B_np.shape, dtype=B_np.dtype), dev)\n            func(A_nd, B_nd)\n            tvm.testing.assert_allclose(B_nd.numpy(), B_np, rtol=1e-3)\n\n    check_cuda(\"float32\")\n    check_cuda(\"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_cuda_half_a_warp():\n    def check_cuda(dtype):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        n, m = 16, 16\n        A = te.placeholder(\n            (\n                n,\n                m,\n            ),\n            name=\"A\",\n            dtype=dtype,\n        )\n        B = te.compute(\n            (\n                n,\n                m,\n            ),\n            lambda j, i: A[j, (i + 1) % m],\n            name=\"B\",\n        )\n\n        cuda_target = tvm.target.Target(\"cuda\")\n        assert cuda_target.thread_warp_size == 2 * m\n        with cuda_target:\n            s = te.create_schedule(B.op)\n            tx = te.thread_axis(\"threadIdx.x\")\n            ty = te.thread_axis(\"threadIdx.y\")\n            bx = te.thread_axis(\"blockIdx.x\")\n\n            AA = s.cache_read(A, \"warp\", [B])\n            y, x = B.op.axis\n            z, y = s[B].split(y, nparts=2)\n            s[B].bind(x, tx)\n            s[B].bind(y, ty)\n            s[B].bind(z, bx)\n            s[AA].compute_at(s[B], y)\n            _, x = AA.op.axis\n            s[AA].bind(x, tx)\n\n            dev = tvm.cuda(0)\n            # building with the CSE pass disabled as otherwise it would do some commoning\n            with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n                func = tvm.build(s, [A, B], \"cuda\")\n            A_np = np.array([list(range(i, m + i)) for i in range(n)], dtype=dtype)\n            B_np = np.array([list(range(1 + i, m + i)) + [i] for i in range(n)], dtype=dtype)\n            A_nd = tvm.nd.array(A_np, dev)\n            B_nd = tvm.nd.array(np.zeros(B_np.shape, dtype=B_np.dtype), dev)\n            func(A_nd, B_nd)\n            tvm.testing.assert_allclose(B_nd.numpy(), B_np, rtol=1e-3)\n\n    check_cuda(\"float32\")\n    check_cuda(\"float16\")\n\n\n@tvm.testing.requires_gpu\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_cuda_2_buffers():\n    def check_cuda(dtype):\n        if dtype == \"float16\" and not have_fp16(tvm.cuda(0).compute_version):\n            print(\"Skip because gpu does not have fp16 support\")\n            return\n\n        m = 32\n        A = te.placeholder((m,), name=\"A\", dtype=dtype)\n        B = te.placeholder((m,), name=\"B\", dtype=dtype)\n        C = te.compute((m,), lambda i: A[(i + 1) % m] + B[(i + 1) % m], name=\"C\")\n\n        cuda_target = tvm.target.Target(\"cuda\")\n        assert m <= cuda_target.thread_warp_size\n        with cuda_target:\n            s = te.create_schedule(C.op)\n            tx = te.thread_axis(\"threadIdx.x\")\n            bx = te.thread_axis(\"blockIdx.x\")\n\n            AA = s.cache_read(A, \"warp\", [C])\n            BB = s.cache_read(B, \"warp\", [C])\n            xo, xi = s[C].split(C.op.axis[0], nparts=1)\n            s[C].bind(xi, tx)\n            s[C].bind(xo, bx)\n            s[AA].compute_at(s[C], xo)\n            s[BB].compute_at(s[C], xo)\n            xo, xi = s[AA].split(s[AA].op.axis[0], nparts=1)\n            s[AA].bind(xo, bx)\n            s[AA].bind(xi, tx)\n            xo, xi = s[BB].split(s[BB].op.axis[0], nparts=1)\n            s[BB].bind(xo, bx)\n            s[BB].bind(xi, tx)\n\n            dev = tvm.cuda(0)\n            # building with the CSE pass disabled as otherwise it would do some commoning\n            with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n                func = tvm.build(s, [A, B, C], \"cuda\")\n            AB_np = np.array(list(range(m)), dtype=dtype)\n            C_np = np.array(list(range(1, m)) + [0], dtype=dtype) * 2\n            A_nd = tvm.nd.array(AB_np, dev)\n            B_nd = tvm.nd.array(AB_np, dev)\n            C_nd = tvm.nd.array(np.zeros(C_np.shape, dtype=C_np.dtype), dev)\n            func(A_nd, B_nd, C_nd)\n            tvm.testing.assert_allclose(C_nd.numpy(), C_np, rtol=1e-3)\n\n    check_cuda(\"float32\")\n    check_cuda(\"float16\")\n\n\n@tvm.testing.requires_gpu\ndef test_lower_warp_memory_roundup():\n    def check(device, m):\n        A = te.placeholder((m,), name=\"A\")\n        B = te.compute((m,), lambda i: A[i] + 1, name=\"B\")\n\n        with tvm.target.Target(device):\n            s = te.create_schedule(B.op)\n            xo, xi = s[B].split(B.op.axis[0], factor=32)\n            tx = te.thread_axis(\"threadIdx.x\")\n            s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n            s[B].bind(xi, tx)\n\n            AA = s.cache_read(A, \"warp\", [B])\n            _, yi = s[AA].split(s[AA].op.axis[0], factor=32)\n            s[AA].bind(yi, tx)\n            s[AA].compute_at(s[B], xo)\n\n            dev = tvm.device(device, 0)\n            # building with the CSE pass disabled as otherwise it would do some commoning\n            with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n                func = tvm.build(s, [A, B], device)\n            A_np = np.random.uniform(size=(m,)).astype(A.dtype)\n            B_np = np.zeros(shape=(m,)).astype(B.dtype)\n            A_nd = tvm.nd.array(A_np, dev)\n            B_nd = tvm.nd.array(B_np, dev)\n            func(A_nd, B_nd)\n            B_np = A_np + 1\n            tvm.testing.assert_allclose(B_nd.numpy(), B_np)\n\n    for device in [\"cuda\", \"rocm\"]:\n        if not tvm.testing.device_enabled(device):\n            print(\"skip because\", device, \"is not enabled..\")\n            continue\n        check(device, m=31)\n        check(device, m=32)\n        check(device, m=33)\n        check(device, m=63)\n        check(device, m=64)\n        check(device, m=65)\n\n\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_same_thread():\n    m = n = 128\n    A = te.placeholder((m, n), name=\"A\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    B = te.compute((m,), lambda i: te.sum(A[i, k], axis=[k]))\n\n    s = te.create_schedule(B.op)\n    BB = s.cache_write(B, \"warp\")\n    tx = te.thread_axis(\"threadIdx.x\")\n    xo, xi = s[B].split(B.op.axis[0], factor=32)\n    s[B].bind(xi, tx)\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[BB].compute_at(s[B], xo)\n    xo, xi = s[BB].split(s[BB].op.axis[0], factor=32)\n    s[BB].bind(xi, tx)\n\n    cuda_target = tvm.target.Target(\"cuda\")\n    assert cuda_target.thread_warp_size == 32\n    # lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        mod = tvm.lower(s, [A, B], name=\"f\")\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", cuda_target))(mod)\n    fdevice = tvm.tir.transform.SplitHostDevice()(mod)[\"f_kernel0\"]\n    mod = tvm.IRModule.from_expr(fdevice)\n    fdevice = tvm.tir.transform.LowerWarpMemory()(mod)[\"f_kernel0\"]\n    assert \"tvm_warp_shuffle\" not in fdevice.astext()\n\n\n@tvm.testing.requires_cuda\ndef test_lower_warp_memory_divide_by_factor():\n    ib = tvm.tir.ir_builder.IRBuilder()\n    bx = te.thread_axis(\"blockIdx.x\")\n    tx = te.thread_axis(\"threadIdx.x\")\n\n    with ib.new_scope():\n        ib.scope_attr(bx, \"thread_extent\", 32)\n        ib.scope_attr(tx, \"thread_extent\", 32)\n        t = ib.allocate(\"float32\", 16, name=\"t\", scope=\"warp\")\n        n = ib.allocate(\"float32\", 16, name=\"n\", scope=\"local\")\n        n[0] = t[0]\n\n    stmt = ib.get()\n    func = tvm.tir.PrimFunc([], stmt)\n    func = func.with_attr(\"from_legacy_te_schedule\", True)\n    cuda_target = tvm.target.Target(\"cuda\")\n    # lowering with the CSE pass disabled as otherwise it would do some commoning\n    with tvm.transform.PassContext(opt_level=3, disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n        mod = tvm.lower(func, name=\"f\")\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", cuda_target))(mod)\n    with pytest.raises(tvm.error.TVMError, match=\"Divide by zero\") as cm:\n        tvm.tir.transform.LowerWarpMemory()(mod)[\"f_kernel0\"]\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_make_packed_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\n\n\ndef test_makeapi():\n    \"\"\"Not yet working, mock design\"\"\"\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name=\"C\")\n    s = te.create_schedule(C.op)\n\n    mod = schedule_to_module(s, [n, A, B, C])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n    mod = tvm.tir.transform.Apply(\n        lambda f: f.with_attr(\n            {\n                \"target\": tvm.target.Target(\"llvm\"),\n                \"global_symbol\": \"main\",\n            }\n        )\n    )(mod)\n\n    f = tvm.tir.transform.MakePackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 6\n\n\ndef _find_assignment(stmt, var_name):\n    while not isinstance(stmt, tvm.tir.LetStmt):\n        stmt = stmt.body\n\n    if stmt.var.name != var_name:\n        return _find_assignment(stmt.body, var_name)\n\n    return stmt\n\n\ndef _find_next(stmt, type):\n    while not isinstance(stmt, type):\n        stmt = stmt.body\n    return stmt\n\n\ndef test_variable_passed_from_args():\n    ib = tvm.tir.ir_builder.create()\n\n    input_buffer = tvm.tir.decl_buffer(name=\"input_buffer\", shape=[1])\n    not_device_context = tvm.tir.Var(\"not_device_context\", dtype=\"handle\")\n\n    ib.emit(\n        tvm.tir.call_extern(\"float32\", \"some_external_call\", input_buffer.data, not_device_context),\n    )\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([input_buffer, not_device_context], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n    func = tvm.tir.transform.MakePackedAPI()(mod)[\"main\"]\n\n    num_args = func.params[2]\n\n    # num_args assertion\n    assert func.body.condition.a == num_args\n    assert func.body.condition.b == 2\n\n    # Arguments unpacking\n    assignment = _find_assignment(func.body, \"arg.input_buffer\")\n    assert str(assignment.value) == \"@tir.tvm_struct_get(args: handle, 0, 12, dtype=handle)\"\n\n    assignment = _find_assignment(func.body, \"arg.not_device_context\")\n    assert str(assignment.value) == \"@tir.tvm_struct_get(args: handle, 1, 12, dtype=handle)\"\n\n    assignment = _find_assignment(func.body, \"input_buffer\")\n    assert (\n        str(assignment.value) == \"@tir.tvm_struct_get(arg.input_buffer: handle, 0, 1, dtype=handle)\"\n    )\n    unpacked_input_buffer = assignment.var\n\n    assignment = _find_assignment(func.body, \"not_device_context\")\n    assert str(assignment.value) == \"arg.not_device_context: handle\"\n    unpacked_not_device_context = assignment.var\n\n    seq_stmt = _find_next(assignment, tvm.tir.SeqStmt)\n    call = _find_next(seq_stmt[1], tvm.tir.Evaluate)\n    call_extern = call.value\n\n    assert call_extern.args[1] == unpacked_input_buffer\n    assert call_extern.args[2] == unpacked_not_device_context\n\n\ndef test_device_api_context_implicit_resource_handle():\n    ib = tvm.tir.ir_builder.create()\n\n    input_buffer = tvm.tir.decl_buffer(name=\"input_buffer\", shape=[1])\n    device_context = tvm.tir.Var(\"device_api_context\", dtype=\"handle\")\n\n    ib.emit(\n        tvm.tir.call_extern(\"float32\", \"some_external_call\", input_buffer.data, device_context),\n    )\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([input_buffer, device_context], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n    func = tvm.tir.transform.MakePackedAPI()(mod)[\"main\"]\n\n    num_args = func.params[2]\n    device_context_in_resource_handle = func.params[5]\n\n    # num_args assertion\n    assert func.body.condition.a == num_args\n    assert func.body.condition.b == 1\n\n    # Arguments unpacking\n    assignment = _find_assignment(func.body, \"arg.input_buffer\")\n    assert str(assignment.value) == \"@tir.tvm_struct_get(args: handle, 0, 12, dtype=handle)\"\n\n    assignment = _find_assignment(func.body, \"input_buffer\")\n    assert (\n        str(assignment.value) == \"@tir.tvm_struct_get(arg.input_buffer: handle, 0, 1, dtype=handle)\"\n    )\n    unpacked_input_buffer = assignment.var\n\n    seq_stmt = _find_next(assignment, tvm.tir.SeqStmt)\n    call = _find_next(seq_stmt[1], tvm.tir.Evaluate)\n    call_extern = call.value\n\n    assert call_extern.args[1] == unpacked_input_buffer\n    assert call_extern.args[2] == device_context_in_resource_handle\n\n\nif __name__ == \"__main__\":\n    test_makeapi()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_make_unpacked_api.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm import te\nimport numpy\n\n\n@pytest.fixture\ndef mod_without_attrs():\n    ib = tvm.tir.ir_builder.create()\n    A = tvm.tir.decl_buffer(name=\"A\", shape=[1])\n    stmt = ib.get()\n    return tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], stmt))\n\n\n@pytest.fixture\ndef mod(mod_without_attrs):\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(\n        mod_without_attrs\n    )\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n\n    return mod\n\n\ndef test_fails_if_not_global_symbol(mod_without_attrs):\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(\n        mod_without_attrs\n    )\n    with pytest.raises(tvm.TVMError, match=\"Expect PrimFunc to have the global_symbol attribute\"):\n        f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n\n\ndef test_fails_if_no_target(mod_without_attrs):\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod_without_attrs)\n    with pytest.raises(tvm.TVMError, match=\"Require the target attribute\"):\n        f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n\n\n@tvm.testing.parametrize_targets(\"c\", \"llvm\", \"cuda\")\ndef test_device_setup(mod, target, dev):\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(target)))(mod)\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 1\n    assert f.params[0].name == \"A\"\n    assert f.body.node == \"default\"\n    assert f.body.attr_key == \"device_id\"\n    assert f.body.value == 0\n    assert f.body.body.node == \"default\"\n    assert f.body.body.attr_key == \"device_type\"\n    assert f.body.body.value == dev.device_type\n\n\ndef test_no_buffers_no_device_setup():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 1\n    assert f.params[0].name == \"A\"\n\n\ndef test_argument_mapping(mod):\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 1\n    assert f.params[0].name == \"A\"\n\n\ndef test_argument_mapping_multiple():\n    ib = tvm.tir.ir_builder.create()\n    A = tvm.tir.decl_buffer(name=\"A\", shape=[1])\n    B = tvm.tir.decl_buffer(name=\"B\", shape=[1])\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, B], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 2\n    assert f.params[0].name == \"A\"\n    assert f.params[1].name == \"B\"\n\n\ndef test_argument_mapping_multiple_matching():\n    ib = tvm.tir.ir_builder.create()\n    A = tvm.tir.decl_buffer(name=\"A\", shape=[1])\n    B = tvm.tir.decl_buffer(name=\"B\", shape=[1])\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, A], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 2\n    assert f.params[0].name == \"A\"\n    assert f.params[1].name == \"A\"\n\n\ndef test_body():\n    ib = tvm.tir.ir_builder.create()\n    A = tvm.tir.decl_buffer(name=\"A\", shape=[1])\n    B = tvm.tir.decl_buffer(name=\"B\", shape=[1])\n    C = ib.buffer_ptr(A)\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, B, C], stmt))\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"target\", tvm.target.Target(\"llvm\")))(mod)\n    mod = tvm.tir.transform.Apply(lambda f: f.with_attr(\"global_symbol\", \"main\"))(mod)\n    f = tvm.tir.transform.MakeUnpackedAPI()(mod)[\"main\"]\n    assert len(f.params) == 3\n    assert f.params[0].name == \"A\"\n    assert f.params[1].name == \"B\"\n    assert f.params[2].name == \"A\"\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_manifest_shared_memory_local_stage.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\n\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n\n@tvm.script.ir_module\nclass MatmulBefore:\n    @T.prim_func\n    def main(A: T.Buffer[(1024, 1024), \"float32\"], B: T.Buffer[(1024, 1024), \"float32\"], C: T.Buffer[(1024, 1024), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for blockIdx_y in T.thread_binding(32, thread=\"blockIdx.y\"):\n            for blockIdx_x in T.thread_binding(32, thread=\"blockIdx.x\"):\n                for threadIdx_y in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for threadIdx_x in T.thread_binding(2, thread=\"threadIdx.x\"):\n                        for k_0 in T.serial(32):\n                            with T.block():\n                                T.reads(A[blockIdx_y * 32 : blockIdx_y * 32 + 32, k_0 * 32 : k_0 * 32 + 32], B[k_0 * 32 : k_0 * 32 + 32, blockIdx_x * 32 : blockIdx_x * 32 + 32])\n                                T.writes(C[blockIdx_y * 32 : blockIdx_y * 32 + 32, blockIdx_x * 32 : blockIdx_x * 32 + 32])\n                                A_shared = T.alloc_buffer([1024, 1024], dtype=\"float32\", scope=\"shared\")\n                                B_shared = T.alloc_buffer([1024, 1024], dtype=\"float32\", scope=\"shared\")\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block(\"A_shared\"):\n                                            T.reads(A[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(A_shared[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.block_attr({\"tir.manifest_shared_memory_local_stage\":1})\n                                            A_shared[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32] = A[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32]\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block(\"B_shared\"):\n                                            T.reads(B[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(B_shared[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.block_attr({\"tir.manifest_shared_memory_local_stage\":1})\n                                            B_shared[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32] = B[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32]\n                                for k_1, i_2, j_2, k_2 in T.grid(2, 16, 16, 16):\n                                    with T.block(\"C\"):\n                                        T.reads(A_shared[blockIdx_y * 32 + threadIdx_y * 16 + i_2, k_0 * 32 + k_1 * 16 + k_2], B_shared[k_0 * 32 + k_1 * 16 + k_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2])\n                                        T.writes(C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2])\n                                        if k_0 * 32 + k_1 * 16 + k_2 == 0:\n                                            C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] = T.float32(0)\n                                        C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] = C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] + A_shared[blockIdx_y * 32 + threadIdx_y * 16 + i_2, k_0 * 32 + k_1 * 16 + k_2] * B_shared[k_0 * 32 + k_1 * 16 + k_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2]\n\n\n@tvm.script.ir_module\nclass MatmulAfter:\n    @T.prim_func\n    def main(A: T.Buffer[(1024, 1024), \"float32\"], B: T.Buffer[(1024, 1024), \"float32\"], C: T.Buffer[(1024, 1024), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for blockIdx_y in T.thread_binding(32, thread=\"blockIdx.y\"):\n            for blockIdx_x in T.thread_binding(32, thread=\"blockIdx.x\"):\n                for threadIdx_y in T.thread_binding(2, thread=\"threadIdx.y\"):\n                    for threadIdx_x in T.thread_binding(2, thread=\"threadIdx.x\"):\n                        for k_0 in T.serial(32):\n                            with T.block():\n                                T.reads(A[blockIdx_y * 32 : blockIdx_y * 32 + 32, k_0 * 32 : k_0 * 32 + 32], B[k_0 * 32 : k_0 * 32 + 32, blockIdx_x * 32 : blockIdx_x * 32 + 32])\n                                T.writes(C[blockIdx_y * 32 : blockIdx_y * 32 + 32, blockIdx_x * 32 : blockIdx_x * 32 + 32])\n                                A_shared = T.alloc_buffer([1024, 1024], dtype=\"float32\", scope=\"shared\")\n                                B_shared = T.alloc_buffer([1024, 1024], dtype=\"float32\", scope=\"shared\")\n                                A_shared_local = T.alloc_buffer([64, 4], dtype=\"float32\", scope=\"local\")\n                                B_shared_local = T.alloc_buffer([64, 4], dtype=\"float32\", scope=\"local\")\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block():\n                                            T.reads(A[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(A_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3])\n                                            A_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3] = A[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32]\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block(\"A_shared\"):\n                                            T.reads(A[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(A_shared[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            A_shared[blockIdx_y * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32] = A_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3]\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block():\n                                            T.reads(B[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(B_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3])\n                                            B_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3] = B[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32]\n                                for ax0_ax1_fused_0 in T.serial(64):\n                                    for ax0_ax1_fused_3 in T.vectorized(4):\n                                        with T.block(\"B_shared\"):\n                                            T.reads(B[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            T.writes(B_shared[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32])\n                                            B_shared[k_0 * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) // 32, blockIdx_x * 32 + (ax0_ax1_fused_0 * 16 + threadIdx_y * 8 + threadIdx_x * 4 + ax0_ax1_fused_3) % 32] = B_shared_local[ax0_ax1_fused_0, ax0_ax1_fused_3]\n                                for k_1, i_2, j_2, k_2 in T.grid(2, 16, 16, 16):\n                                    with T.block(\"C\"):\n                                        T.reads(A_shared[blockIdx_y * 32 + threadIdx_y * 16 + i_2, k_0 * 32 + k_1 * 16 + k_2], B_shared[k_0 * 32 + k_1 * 16 + k_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2])\n                                        T.writes(C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2])\n                                        if k_0 * 32 + k_1 * 16 + k_2 == 0:\n                                            C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] = T.float32(0)\n                                        C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] = C[blockIdx_y * 32 + threadIdx_y * 16 + i_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2] + A_shared[blockIdx_y * 32 + threadIdx_y * 16 + i_2, k_0 * 32 + k_1 * 16 + k_2] * B_shared[k_0 * 32 + k_1 * 16 + k_2, blockIdx_x * 32 + threadIdx_x * 16 + j_2]\n\n\n# fmt: on\n# pylint: enable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,unexpected-keyword-arg,too-many-nested-blocks\n\n\ndef _check(before, expected):\n    after = tvm.tir.transform.ManifestSharedMemoryLocalStage()(before)\n    tvm.ir.assert_structural_equal(after, expected)\n\n\ndef test_transform_matmul():\n    _check(MatmulBefore, MatmulAfter)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_merge_dynamic_shared_memory_allocations.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\nfrom tvm.topi.math import cast\n\n\ndef run_passes(sch, args):\n    mod = schedule_to_module(sch, args)\n    return tvm.transform.Sequential(\n        [\n            tvm.tir.transform.StorageFlatten(64),\n            tvm.tir.transform.Simplify(),\n            tvm.tir.transform.VectorizeLoop(),\n            tvm.tir.transform.StorageRewrite(),\n            tvm.tir.transform.MergeDynamicSharedMemoryAllocations(),\n        ]\n    )(mod)\n\n\ndef verify_single_allocation(stmt, alloc_size=None):\n    num_alloc = [0]\n    alloc_extents = []\n\n    def verify(n):\n        if (\n            isinstance(n, tvm.tir.Allocate)\n            and n.buffer_var.type_annotation.storage_scope == \"shared.dyn\"\n        ):\n            num_alloc[0] += 1\n            alloc_extents.append(n.extents[0])\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 1\n\n    if alloc_size:\n        assert alloc_extents[0] == alloc_size\n\n\n@tvm.testing.requires_gpu\ndef test_matmul_dyn_shared():\n    n = 1024\n    block = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((n, n), name=\"B\", dtype=\"float16\")\n\n    def syncthread():\n        return tvm.tir.Call(None, \"tir.tvm_storage_sync\", tvm.runtime.convert([\"shared\"]))\n\n    def test_matmul_ir(A, B, C):\n        ib = tvm.tir.ir_builder.create()\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        ty = te.thread_axis(\"threadIdx.y\")\n        bx = te.thread_axis(\"blockIdx.x\")\n        by = te.thread_axis(\"blockIdx.y\")\n        ib.scope_attr(tx, \"thread_extent\", block)\n        ib.scope_attr(ty, \"thread_extent\", block)\n        ib.scope_attr(bx, \"thread_extent\", n // block)\n        ib.scope_attr(by, \"thread_extent\", n // block)\n\n        A_sh = ib.allocate(A.dtype, (block, block), scope=\"shared.dyn\", name=\"A_sh\")  # fp16\n        B_sh = ib.allocate(B.dtype, (block, block), scope=\"shared.dyn\", name=\"B_sh\")  # fp16\n        # Create a dynamic shared memory for the accumulation.\n        # This is for testing merging dynamic shared memory alloctions with different data type.\n        # In practice, there is no need to allocate a shared memory for C.\n        C_local = ib.allocate(C.dtype, (1,), scope=\"local\", name=\"C_local\")\n        C_sh = ib.allocate(C.dtype, (block, block), scope=\"shared.dyn\", name=\"C_sh\")  # fp32\n\n        A_ptr = ib.buffer_ptr(A)\n        B_ptr = ib.buffer_ptr(B)\n        C_ptr = ib.buffer_ptr(C)\n\n        C_local[0] = 0.0\n\n        with ib.for_range(0, n // block, name=\"i\") as i:\n            A_sh[ty, tx] = A_ptr[by * block + ty, i * block + tx]\n            B_sh[ty, tx] = B_ptr[i * block + ty, bx * block + tx]\n            ib.emit(syncthread())\n\n            with ib.for_range(0, block, name=\"k\") as k:\n                C_local[0] += cast(A_sh[ty, k] * B_sh[k, tx], \"float32\")\n            ib.emit(syncthread())\n\n        C_sh[ty, tx] = C_local[0]\n        C_ptr[by * block + ty, bx * block + tx] = C_sh[ty, tx]\n\n        return ib.get()\n\n    C = te.extern(\n        A.shape,\n        [A, B],\n        lambda ins, outs: test_matmul_ir(ins[0], ins[1], outs[0]),\n        name=\"matmul\",\n        dtype=\"float32\",\n    )\n    s = te.create_schedule(C.op)\n    mod = run_passes(s, [A, B, C])\n    # C can be allocated at the start of A, so we only need to allocate 2 block * block memory with dtype = float16\n    expected_alloc_size = block * block * 4\n    verify_single_allocation(mod[\"main\"].body, expected_alloc_size)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        fmatmul = tvm.build(s, [A, B, C], target)\n        dev = tvm.device(target, 0)\n\n        size = (n, n)\n        a_np = np.random.uniform(size=size).astype(A.dtype)\n        b_np = np.random.uniform(size=size).astype(B.dtype)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.array(b_np, dev)\n        c = tvm.nd.array(np.zeros(size, dtype=C.dtype), dev)\n        fmatmul(a, b, c)\n        np_ref = np.dot(a_np.astype(\"float32\"), b_np.astype(\"float32\"))\n        tvm.testing.assert_allclose(c.numpy(), np_ref, 1e-4, 1e-4)\n\n    for target in [\"cuda\", \"nvptx\"]:\n        check_target(target)\n\n\n@tvm.testing.requires_gpu\ndef test_dyn_shared_vectorized_store():\n    \"\"\"Test vectorized store into dynamic shared memory\"\"\"\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((n,), name=\"B\", dtype=\"float32\")\n\n    def test_device_ir(A, B, C):\n        n = A.shape[0]\n        ib = tvm.tir.ir_builder.create()\n\n        values_per_thread = 4\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", tvm.tir.indexdiv(n, values_per_thread))\n\n        A_sh = ib.allocate(A.dtype, (n,), scope=\"shared.dyn\")  # fp16\n        B_sh = ib.allocate(B.dtype, (n,), scope=\"shared.dyn\")  # fp32\n\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n\n        with ib.for_range(0, values_per_thread, kind=\"vectorize\") as i:\n            A_sh[tx * values_per_thread + i] = Aptr[tx * values_per_thread + i]\n            B_sh[tx * values_per_thread + i] = Bptr[tx * values_per_thread + i]\n\n        with ib.for_range(0, values_per_thread) as i:\n            Cptr[tx * values_per_thread + i] = (\n                cast(A_sh[tx * values_per_thread + i], \"float32\") + B_sh[tx * values_per_thread + i]\n            )\n\n        return ib.get()\n\n    C = te.extern(\n        (n,),\n        [A, B],\n        lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]),\n        name=\"vadd\",\n        dtype=\"float32\",\n    )\n    s = te.create_schedule(C.op)\n\n    mod = run_passes(s, [A, B, C])\n    verify_single_allocation(mod[\"main\"].body)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        fadd = tvm.build(s, [A, B, C], target)\n        dev = tvm.device(target, 0)\n\n        for n in [512, 1024]:\n            a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n            b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n            c = tvm.nd.array(np.zeros((n,), dtype=C.dtype), dev)\n            fadd(a, b, c)\n            tvm.testing.assert_allclose(\n                c.numpy(), a.numpy().astype(\"float32\") + b.numpy(), 1e-4, 1e-4\n            )\n\n    for target in [\"cuda\", \"nvptx\"]:\n        check_target(target)\n\n\n@tvm.testing.requires_gpu\ndef test_dyn_shared_reuse_and_merge():\n    n = 64\n    A = te.placeholder((n,), name=\"A\", dtype=\"float32\")\n    B = te.placeholder((n,), name=\"B\", dtype=\"float32\")\n    C = te.placeholder((te.size_var(\"n_dyn\"),), name=\"C\", dtype=\"float32\")\n\n    def test_device_ir(A, B, C, D):\n        ib = tvm.tir.ir_builder.create()\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", n)\n\n        A_sh = ib.allocate(A.dtype, (n,), scope=\"shared.dyn\", name=\"A_sh\")\n        B_sh = ib.allocate(B.dtype, (n,), scope=\"shared.dyn\", name=\"B_sh\")\n        C_sh = ib.allocate(C.dtype, (C.shape[0],), scope=\"shared.dyn\", name=\"C_sh\")\n\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n        Dptr = ib.buffer_ptr(D)\n\n        A_sh[tx] = Aptr[tx]\n        Dptr[tx] = A_sh[tx]\n\n        B_sh[tx] = Bptr[tx]\n        Dptr[tx] += B_sh[tx]\n\n        C_sh[tx] = Cptr[tx]  # C cannot reuse other buffers since it size is dynamic\n        Dptr[tx] += C_sh[tx]\n\n        return ib.get()\n\n    D = te.extern(\n        (n,),\n        [A, B, C],\n        lambda ins, outs: test_device_ir(ins[0], ins[1], ins[2], outs[0]),\n        name=\"vadd\",\n        dtype=\"float32\",\n    )\n    s = te.create_schedule(D.op)\n\n    mod = run_passes(s, [A, B, C, D])\n    # merged allocation\n    # allocate(buf_dyn_shmem: Pointer(shared.dyn uint8), uint8, [((n_dyn*4) + 256)]);\n    verify_single_allocation(mod[\"main\"].body)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        fadd = tvm.build(s, [A, B, C, D], target)\n        dev = tvm.device(target, 0)\n\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.random.uniform(size=n).astype(C.dtype), dev)\n        d = tvm.nd.array(np.zeros((n,), dtype=D.dtype), dev)\n        fadd(a, b, c, d)\n        tvm.testing.assert_allclose(d.numpy(), a.numpy() + b.numpy() + c.numpy(), 1e-4, 1e-4)\n\n    for target in [\"cuda\", \"nvptx\"]:\n        check_target(target)\n\n\ndef test_dyn_shared_more_dtype():\n    \"\"\"Test vectorized store into dynamic shared memory\"\"\"\n    n = 512\n    A = te.placeholder((n,), name=\"A\", dtype=\"int8\")\n    B = te.placeholder((n,), name=\"B\", dtype=\"int16\")\n\n    def test_device_ir(A, B, C):\n        n = A.shape[0]\n        ib = tvm.tir.ir_builder.create()\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", n)\n\n        A_sh = ib.allocate(A.dtype, (n,), scope=\"shared.dyn\")  # i8\n        B_sh = ib.allocate(B.dtype, (n,), scope=\"shared.dyn\")  # i16\n        C_sh = ib.allocate(C.dtype, (n,), scope=\"shared.dyn\")  # i32\n\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n        Cptr = ib.buffer_ptr(C)\n\n        A_sh[tx] = Aptr[tx]\n        B_sh[tx] = Bptr[tx]\n\n        C_sh[tx] = cast(A_sh[tx], \"int32\") + cast(B_sh[tx], \"int32\")\n        Cptr[tx] = C_sh[tx]\n        return ib.get()\n\n    C = te.extern(\n        (n,),\n        [A, B],\n        lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]),\n        name=\"vadd\",\n        dtype=\"int32\",\n    )\n    s = te.create_schedule(C.op)\n\n    mod = run_passes(s, [A, B, C])\n    verify_single_allocation(mod[\"main\"].body, n * 4)\n\n    def check_target(target):\n        if not tvm.testing.device_enabled(target):\n            return\n\n        fadd = tvm.build(s, [A, B, C], target)\n        dev = tvm.device(target, 0)\n\n        a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev)\n        b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev)\n        c = tvm.nd.array(np.zeros((n,), dtype=C.dtype), dev)\n        fadd(a, b, c)\n        tvm.testing.assert_allclose(c.numpy(), a.numpy().astype(\"float32\") + b.numpy(), 1e-4, 1e-4)\n\n    for target in [\"cuda\", \"nvptx\"]:\n        check_target(target)\n\n\nif __name__ == \"__main__\":\n    test_matmul_dyn_shared()\n    test_dyn_shared_vectorized_store()\n    test_dyn_shared_reuse_and_merge()\n    test_dyn_shared_more_dtype()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_narrow_datatype.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import relay, te\nfrom tvm.driver.build_module import schedule_to_module\nfrom tvm.script import tir as T\nfrom tvm.tir import const\n\n\ndef lower_stmt(params, stmt, target_bits):\n    func = tvm.tir.PrimFunc(params, stmt)\n    func = tvm.tir.transform.NarrowDataType(target_bits)(tvm.IRModule.from_expr(func))[\"main\"]\n    stmt = func.body\n    return stmt\n\n\ndef lower_sch(sch, args, target_bits, extra_passes=None):\n    binds = {}\n    arg_list = []\n    for x in args:\n        if isinstance(x, te.tensor.Tensor):\n            buf = tvm.tir.decl_buffer(x.shape, dtype=x.dtype, name=x.name)\n            assert x not in binds\n            binds[x] = buf\n            arg_list.append(buf)\n        else:\n            raise ValueError(\"args must be Tensor, Buffer or Var\")\n    sch = sch.normalize()\n\n    mod = schedule_to_module(sch, args)\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n    if extra_passes:\n        for p in extra_passes:\n            mod = p(mod)\n    return tvm.tir.transform.NarrowDataType(target_bits)(mod)[\"main\"].body\n\n\ndef test_basic():\n    def check(m, n, target_bits, target_dtype):\n        ib = tvm.tir.ir_builder.create()\n        Ab = tvm.tir.decl_buffer([m * n], name=\"A\")\n        A = ib.buffer_ptr(Ab)\n        Bb = tvm.tir.decl_buffer([m * n], name=\"B\")\n        B = ib.buffer_ptr(Bb)\n        with ib.for_range(0, m, name=\"i\") as i:\n            with ib.for_range(0, n, name=\"j\") as j:\n                B[i * n + j] = A[i * n + j] + 1\n        stmt = ib.get()\n        stmt = lower_stmt([Ab, Bb], stmt, target_bits)\n        assert stmt.loop_var.dtype == target_dtype\n        assert stmt.body.loop_var.dtype == target_dtype\n\n    # const shape\n    # i32 -> i32\n    check(2, 2, 32, \"int32\")\n    # i64 -> i32\n    check(const(2, dtype=\"int64\"), const(2, dtype=\"int64\"), 32, \"int32\")\n    check(const(2**16, dtype=\"int64\"), const(2**16, dtype=\"int64\"), 32, \"int64\")\n    # i32 -> i16\n    check(2, 2, 16, \"int16\")\n    check(2**10, 2**10, 16, \"int32\")\n\n    # symbolic shape\n    check(te.size_var(name=\"m\", dtype=\"int32\"), te.size_var(name=\"n\", dtype=\"int32\"), 32, \"int32\")\n    check(te.size_var(name=\"m\", dtype=\"int64\"), te.size_var(name=\"n\", dtype=\"int64\"), 32, \"int64\")\n\n\ndef test_thread_axis():\n    def check(m, n, target_bits, target_dtype):\n        ib = tvm.tir.ir_builder.create()\n        Ab = tvm.tir.decl_buffer([m * n], name=\"A\")\n        A = ib.buffer_ptr(Ab)\n        Bb = tvm.tir.decl_buffer([m * n], name=\"B\")\n        B = ib.buffer_ptr(Bb)\n        bx = te.thread_axis(\"blockIdx.x\")\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(bx, \"thread_extent\", m)\n        ib.scope_attr(tx, \"thread_extent\", n)\n        B[bx * n + tx] = A[bx * n + tx] + 1\n        stmt = ib.get()\n        stmt = lower_stmt([Ab, Bb], stmt, target_bits)\n        assert stmt.node.var.dtype == target_dtype\n        assert stmt.body.node.var.dtype == target_dtype\n\n    # i32 -> i32\n    check(2, 32, target_bits=32, target_dtype=\"int32\")\n    # i64 -> i32\n    check(const(2, dtype=\"int64\"), const(32, dtype=\"int64\"), target_bits=32, target_dtype=\"int32\")\n    check(\n        const(2**30, dtype=\"int64\"),\n        const(32, dtype=\"int64\"),\n        target_bits=32,\n        target_dtype=\"int64\",\n    )\n    # i32 -> i16\n    check(2, 32, target_bits=16, target_dtype=\"int16\")\n    check(2**14, 32, target_bits=16, target_dtype=\"int32\")\n\n\ndef test_thread_axis_2():\n    # fmt: off\n    @tvm.script.ir_module\n    class Before:\n        @T.prim_func\n        def main(T_reshape: T.Buffer[(1, 12, 384, 384), \"float32\"], placeholder_1: T.Buffer[(T.int64(1), T.int64(12), T.int64(384), 384), \"bool\"], T_where: T.Buffer[(T.int64(1), T.int64(12), T.int64(384), 384), \"float32\"]) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            # body\n            # with T.block(\"root\")\n            for i0_i1_i2_i3_fused_1 in T.thread_binding(T.int64(256), thread=\"blockIdx.x\"):\n                for i0_i1_i2_i3_fused_2 in T.thread_binding(T.int64(1024), thread=\"threadIdx.x\"):\n                    for i0_i1_i2_i3_fused_0 in T.serial(T.int64(7)):\n                        with T.block(\"T_where\"):\n                            ax0 = T.axis.spatial(T.int64(1), T.int64(0))\n                            ax1 = T.axis.spatial(T.int64(12), ((i0_i1_i2_i3_fused_0 * T.int64(256) + i0_i1_i2_i3_fused_1) * T.int64(1024) + i0_i1_i2_i3_fused_2) % T.int64(1769472) // T.int64(147456))\n                            ax2 = T.axis.spatial(T.int64(384), ((i0_i1_i2_i3_fused_0 * T.int64(256) + i0_i1_i2_i3_fused_1) * T.int64(1024) + i0_i1_i2_i3_fused_2) % T.int64(147456) // T.int64(384))\n                            ax3 = T.axis.spatial(384, T.cast(((i0_i1_i2_i3_fused_0 * T.int64(256) + i0_i1_i2_i3_fused_1) * T.int64(1024) + i0_i1_i2_i3_fused_2) % T.int64(384), \"int32\"))\n                            T.where((i0_i1_i2_i3_fused_0 * T.int64(256) + i0_i1_i2_i3_fused_1) * T.int64(1024) + i0_i1_i2_i3_fused_2 < T.int64(1769472))\n                            T.reads(placeholder_1[ax0, ax1, ax2, ax3], T_reshape[ax0, ax1, ax2, ax3])\n                            T.writes(T_where[ax0, ax1, ax2, ax3])\n                            T_where[ax0, ax1, ax2, ax3] = T.Select(T.cast(placeholder_1[ax0, ax1, ax2, ax3], \"int32\") != 0, T.float32(-1000000000), T_reshape[ax0, ax1, ax2, ax3])\n    # fmt: on\n    # TODO(@junrushao1994): make this test more \"unit\" after the new TVMScript printer/parser lands\n    tvm.lower(Before)\n\n\ndef test_multilanes():\n    def check(m, lanes, target_bits, target_dtype):\n        ib = tvm.tir.ir_builder.create()\n        Ab = tvm.tir.decl_buffer((m,), dtype=\"float32x{}\".format(lanes), name=\"A\")\n        A = ib.buffer_ptr(Ab)\n        Bb = tvm.tir.decl_buffer((m,), dtype=\"float32x{}\".format(lanes), name=\"B\")\n        B = ib.buffer_ptr(Bb)\n        with ib.for_range(0, m, name=\"i\", dtype=m.dtype) as i:\n            B[i] = A[i] + 1\n        A[0] = B[1]\n        stmt = ib.get()\n        stmt = lower_stmt([Ab, Bb], stmt, target_bits)\n        assert stmt.seq[0].loop_var.dtype == target_dtype\n\n    # i32 -> i32\n    check(const(2**10, dtype=\"int32\"), 2, target_bits=32, target_dtype=\"int32\")\n    # i64 -> i32\n    check(const(2**10, dtype=\"int64\"), 2, target_bits=32, target_dtype=\"int32\")\n    check(const(2**32, dtype=\"int64\"), 2, target_bits=32, target_dtype=\"int64\")\n    # i32 -> i16\n    check(const(2**10, dtype=\"int32\"), 2, target_bits=16, target_dtype=\"int16\")\n    check(const(2**16, dtype=\"int32\"), 2, target_bits=16, target_dtype=\"int32\")\n\n\ndef test_reduce():\n    def check(m, target_bits, target_dtype):\n        A = te.placeholder((m,), name=\"A\", dtype=\"float32\")\n        k = te.reduce_axis((0, m), \"k\")\n        B = te.compute((), lambda *idx: te.sum(A[k], axis=k), name=\"B\")\n        s = te.create_schedule(B.op)\n        stmt = lower_sch(s, [A, B], target_bits)\n        assert stmt[1].loop_var.dtype == target_dtype\n\n    # i32 -> i32\n    check(const(64, dtype=\"int32\"), 32, \"int32\")\n    # i64 -> i32\n    check(const(64, dtype=\"int64\"), 32, \"int32\")\n    # i32 -> i16\n    check(const(64, dtype=\"int32\"), 16, \"int16\")\n    check(const(2**16, dtype=\"int32\"), 16, \"int32\")\n    # symbolic\n    check(te.var(\"n\", dtype=\"int32\"), 32, \"int32\")\n    check(te.var(\"n\", dtype=\"int64\"), 32, \"int64\")\n\n\ndef test_slice():\n    def check(m, n, target_bits, target_dtype):\n        # The index may overflow in B, while not in A\n        ib = tvm.tir.ir_builder.create()\n        Ab = tvm.tir.decl_buffer([m * n], name=\"A\")\n        A = ib.buffer_ptr(Ab)\n        Bb = tvm.tir.decl_buffer([m * n * 2], name=\"B\")\n        B = ib.buffer_ptr(Bb)\n        with ib.for_range(0, m, name=\"i\") as i:\n            with ib.for_range(0, n, name=\"j\") as j:\n                A[i * n + j] = B[i * 2 * n + 2 * j] + 1\n        stmt = ib.get()\n        stmt = lower_stmt([Ab, Bb], stmt, target_bits)\n        assert stmt.loop_var.dtype == target_dtype\n        assert stmt.body.loop_var.dtype == target_dtype\n\n    # The maximum index is (2**15 * 2**15 - 1) * 2 <= 2**31 - 1\n    check(const(2**15, \"int64\"), const(2**15, \"int64\"), target_bits=32, target_dtype=\"int32\")\n    # The maximum index is (2**15 * 2**15 - 1 + 2**15) * 2 > 2**31 - 1\n    check(\n        const(2**15, \"int64\"), const((2**15 + 1), \"int64\"), target_bits=32, target_dtype=\"int64\"\n    )\n\n\ndef test_relay_basic():\n    engine = relay.backend.te_compiler.get()\n\n    def check(shapex, shapey, target_bits, target_dtype):\n        x = relay.var(\"x\", shape=shapex)\n        y = relay.var(\"y\", shape=shapey)\n        z = relay.add(x, y)\n        func = relay.Function([x, y], z)\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        func = mod[\"main\"]\n        z = engine.lower(func, \"llvm\")\n        stmt = lower_sch(z.schedule, tuple(z.inputs) + tuple(z.outputs), 32)\n        # outer loop\n        assert stmt.loop_var.dtype == target_dtype\n        # inner loop\n        if len(shapex) > 1 or len(shapey) > 1:\n            assert stmt.body.loop_var.dtype == target_dtype\n\n    check(\n        (const(2**16, \"int64\"), const(2**15 + 1, \"int64\")),\n        (1, const(2**15 + 1, \"int64\")),\n        target_bits=32,\n        target_dtype=\"int64\",\n    )\n    check(\n        (const(2**16, \"int64\"), const(2**15, \"int64\")),\n        (1, const(2**15, \"int64\")),\n        target_bits=32,\n        target_dtype=\"int32\",\n    )\n    check(\n        (const(2**31, \"int64\"),), (const(2**31, \"int64\"),), target_bits=32, target_dtype=\"int32\"\n    )\n    check(\n        (const(2**31 + 1, \"int64\"),),\n        (const(2**31 + 1, \"int64\"),),\n        target_bits=32,\n        target_dtype=\"int64\",\n    )\n\n\ndef test_relay_take():\n    engine = relay.backend.te_compiler.get()\n\n    def check(shape, index, target_bits, target_dtype):\n        x = relay.var(\"x\", shape=shape)\n        y = relay.op.take(x, indices=index)\n        func = relay.Function([x], y)\n        mod = tvm.IRModule.from_expr(func)\n        mod = relay.transform.InferType()(mod)\n        func = mod[\"main\"]\n        z = engine.lower(func, \"llvm\")\n        stmt = lower_sch(z.schedule, tuple(z.inputs) + tuple(z.outputs), 32)\n        assert stmt.value.indices[0].dtype == target_dtype\n\n    check(\n        (const(2**16, \"int64\"), const(2**15 + 1, \"int64\")),\n        relay.const(0, dtype=\"int64\"),\n        target_bits=32,\n        target_dtype=\"int32\",\n    )\n    check(\n        (const(2**16, \"int64\"), const(2**15 + 1, \"int64\")),\n        relay.const(2**31, dtype=\"int64\"),\n        target_bits=32,\n        target_dtype=\"int64\",\n    )\n\n\ndef test_ramp_dtype_consistency():\n    \"\"\"\n    for (i :int64, (int64)0, (int64)4) {\n        A[ramp(i*(int64)2, (int64)1, 2)] = cast(int64, 2 ** 31 - 1) * i;\n    }\n    The infer result:\n        base:   int64 -> int64 (since i is involved in another int64 expr)\n        stride: int64 -> int32\n\n    Thus ramp should still use int64 for both stride and base after rewrite.\n    \"\"\"\n    n = tvm.tir.IntImm(\"int64\", 4)\n    m = tvm.tir.IntImm(\"int64\", 2)\n    A = te.compute((n, m), lambda i, j: tvm.tir.Cast(\"int64\", 2**31 - 1) * i, name=\"A\")\n    s = te.create_schedule(A.op)\n    s[A].vectorize(A.op.axis[1])\n    lower_sch(s, [A], 32, extra_passes=[tvm.tir.transform.VectorizeLoop()])\n\n\ndef test_condition():\n    @T.prim_func\n    def before(A: T.Buffer[(128,), \"float32\"], B: T.Buffer[(130,), \"float32\"]):\n        for i, j in T.grid(T.int64(2), T.int64(65)):\n            if i * T.int64(65) + j >= T.int64(0) and i * T.int64(65) + j < T.int64(128):\n                A[i * T.int64(65) + j] = 0.0\n        for i, j in T.grid(T.int64(2), T.int64(65)):\n            B[i * T.int64(65) + j] = T.if_then_else(\n                i * T.int64(65) + j >= T.int64(0) and i * T.int64(65) + j < T.int64(128),\n                A[i * T.int64(65) + j],\n                0.0,\n                dtype=\"float32\",\n            )\n\n    @T.prim_func\n    def expected_after(A: T.Buffer[128, \"float32\"], B: T.Buffer[130, \"float32\"]):\n        for i, j in T.grid(2, 65):\n            if i * 65 + j >= 0 and i * 65 + j < 128:\n                A[i * 65 + j] = T.float32(0)\n        for i, j in T.grid(2, 65):\n            B[i * 65 + j] = T.if_then_else(\n                i * 65 + j >= 0 and i * 65 + j < 128, A[i * 65 + j], T.float32(0), dtype=\"float32\"\n            )\n\n    after = tvm.tir.transform.NarrowDataType(32)(tvm.IRModule.from_expr(before))[\"main\"]\n    tvm.ir.assert_structural_equal(after, expected_after)\n\n\nif __name__ == \"__main__\":\n    test_basic()\n    test_thread_axis()\n    test_thread_axis_2()\n    test_multilanes()\n    test_reduce()\n    test_slice()\n    test_relay_basic()\n    test_relay_take()\n    test_ramp_dtype_consistency()\n    test_condition()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_plan_update_buffer_allocation_location.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    func = original\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.PlanAndUpdateBufferAllocationLocation()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed)\n\n\n@T.prim_func\ndef element_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    C = T.match_buffer(c, (16, 16))\n    B = T.alloc_buffer((16, 16))\n    for i0 in range(0, 16):\n        for j0 in range(0, 16):\n            with T.block():\n                i, j = T.axis.remap(\"SS\", [i0, j0])\n                B[i, j] = A[i, j] + 1.0\n        for j0 in range(0, 16):\n            with T.block():\n                i, j = T.axis.remap(\"SS\", [i0, j0])\n                C[i, j] = B[i, j] * 2.0\n\n\n@T.prim_func\ndef transformed_element_func(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [16, 16])\n    C = T.match_buffer(c, [16, 16])\n\n    for i_0 in range(0, 16):\n        with T.block():\n            T.reads([A[i_0, 0:16]])\n            T.writes([C[i_0, 0:16]])\n            B = T.alloc_buffer([16, 16])\n            for j_0 in T.serial(0, 16):\n                with T.block():\n                    i, j = T.axis.remap(\"SS\", [i_0, j_0])\n                    B[i, j] = A[i, j] + 1.0\n            for j_0 in T.serial(0, 16):\n                with T.block():\n                    i, j = T.axis.remap(\"SS\", [i_0, j_0])\n                    C[i, j] = B[i, j] * 2.0\n\n\n@T.prim_func\ndef original_func() -> None:\n    A = T.alloc_buffer((128, 128), \"float32\")\n    for i0, j0 in T.grid(128, 128):\n        with T.block():\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            A[i, j] = T.float32(0)\n    for i0, j0, k0 in T.grid(32, 32, 32):\n        with T.block():\n            i, j, k = T.axis.remap(\"SSR\", [i0, j0, k0])\n            B = T.alloc_buffer((128, 128), \"float32\")\n            C = T.alloc_buffer((128, 128), \"float32\")\n            D = T.alloc_buffer((128, 128), \"float32\")\n            if k == 0:\n                for ii, jj in T.grid(4, 4):\n                    B[i * 4 + ii, j * 4 + jj] = A[i * 4 + ii, j * 4 + jj]\n            for ii, jj in T.grid(4, 4):\n                for kk in range(0, 4):\n                    B[i * 4 + ii, j * 4 + jj] += C[i * 4 + ii, k * 4 + kk]\n                for kk in range(0, 4):\n                    B[i * 4 + ii, j * 4 + jj] += (\n                        D[j * 4 + jj, k * 4 + kk] * C[i * 4 + ii, k * 4 + kk]\n                    )\n\n\n@T.prim_func\ndef transformed_func() -> None:\n    A = T.alloc_buffer([128, 128])\n    for i0, j0 in T.grid(128, 128):\n        with T.block():\n            i, j = T.axis.remap(\"SS\", [i0, j0])\n            A[i, j] = T.float32(0)\n    for i0, j0, k0 in T.grid(32, 32, 32):\n        with T.block():\n            i, j, k = T.axis.remap(\"SSR\", [i0, j0, k0])\n            B = T.alloc_buffer([128, 128])\n            if k == 0:\n                for ii, jj in T.grid(4, 4):\n                    B[i * 4 + ii, j * 4 + jj] = A[i * 4 + ii, j * 4 + jj]\n            for ii, jj in T.grid(4, 4):\n                with T.block(\"\"):\n                    T.reads([B[((i * 4) + ii), ((j * 4) + jj)]])\n                    T.writes([B[((i * 4) + ii), ((j * 4) + jj)]])\n                    C = T.alloc_buffer([128, 128])\n                    for kk in T.serial(0, 4):\n                        B[((i * 4) + ii), ((j * 4) + jj)] = (\n                            B[((i * 4) + ii), ((j * 4) + jj)] + C[((i * 4) + ii), ((k * 4) + kk)]\n                        )\n                    for kk in T.serial(0, 4):\n                        with T.block(\"\"):\n                            T.reads(\n                                [\n                                    B[((i * 4) + ii), ((j * 4) + jj)],\n                                    C[((i * 4) + ii), ((k * 4) + kk)],\n                                ]\n                            )\n                            T.writes([B[((i * 4) + ii), ((j * 4) + jj)]])\n                            D = T.alloc_buffer([128, 128])\n                            B[((i * 4) + ii), ((j * 4) + jj)] = B[\n                                ((i * 4) + ii), ((j * 4) + jj)\n                            ] + (\n                                D[((j * 4) + jj), ((k * 4) + kk)]\n                                * C[((i * 4) + ii), ((k * 4) + kk)]\n                            )\n\n\n@T.prim_func\ndef match_buffer_func() -> None:\n    C = T.alloc_buffer((128, 128))\n    for i in range(128):\n        with T.block():\n            vi = T.axis.S(128, i)\n            C0 = T.match_buffer(C[vi, 0:128], (128))\n            for j in range(128):\n                with T.block():\n                    jj = T.axis.S(128, j)\n                    C1 = T.match_buffer(C0[jj], ())\n                    C1[()] = 0\n\n\n@T.prim_func\ndef transformed_match_buffer_func() -> None:\n    for i in range(0, 128):\n        with T.block():\n            vi = T.axis.S(128, i)\n            C = T.alloc_buffer((128, 128))\n            C0 = T.match_buffer(C[vi, 0:128], (128))\n            for j in range(128):\n                with T.block():\n                    jj = T.axis.S(128, j)\n                    C1 = T.match_buffer(C0[jj], ())\n                    C1[()] = 0\n\n\n@T.prim_func\ndef opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [1024])\n    B = T.match_buffer(b, [1024])\n    A_cache = T.alloc_buffer([1024])\n    for i in T.serial(0, 8):\n        with T.block():\n            vi = T.axis.S(8, i)\n            with T.block():\n                v = T.axis.S(8, vi)\n                T.reads([A[(v * 128) : ((v * 128) + 128)]])\n                T.writes([A_cache[(v * 128) : ((v * 128) + 128)]])\n                T.evaluate(\n                    T.call_extern(\n                        \"test\",\n                        A_cache.data,\n                        (v * 128),\n                        128,\n                        A.data,\n                        (v * 128),\n                        128,\n                        dtype=\"float32\",\n                    )\n                )\n            for j in T.serial(0, 128):\n                with T.block():\n                    v = T.axis.S(1024, vi * 128 + j)\n                    T.reads([A_cache[v]])\n                    T.writes([B[v]])\n                    B[v] = A_cache[v]\n\n\n@T.prim_func\ndef transformed_opaque_access(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [1024])\n    B = T.match_buffer(b, [1024])\n    for i in T.serial(0, 8):\n        with T.block():\n            vi = T.axis.S(8, i)\n            T.reads(A[vi * 128 : vi * 128 + 128])\n            T.writes(B[vi * 128 : vi * 128 + 128])\n            A_cache = T.alloc_buffer([1024])\n            with T.block():\n                v = T.axis.S(8, vi)\n                T.reads([A[v * 128 : v * 128 + 128]])\n                T.writes([A_cache[v * 128 : v * 128 + 128]])\n                T.evaluate(\n                    T.call_extern(\n                        \"test\", A_cache.data, v * 128, 128, A.data, v * 128, 128, dtype=\"float32\"\n                    )\n                )\n            for j in T.serial(0, 128):\n                with T.block():\n                    v = T.axis.S(1024, vi * 128 + j)\n                    T.reads([A_cache[v]])\n                    T.writes([B[v]])\n                    B[v] = A_cache[v]\n\n\ndef test_elementwise():\n    _check(element_func, transformed_element_func)\n\n\ndef test_locate_buffer_allocation():\n    _check(original_func, transformed_func)\n\n\ndef test_match_buffer_allocation():\n    _check(match_buffer_func, transformed_match_buffer_func)\n\n\ndef test_opaque_access():\n    _check(opaque_access, transformed_opaque_access)\n\n\ndef test_lower_te():\n    x = te.placeholder((1,))\n    y = te.compute((1,), lambda i: x[i] + 2)\n    s = te.create_schedule(y.op)\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])\n    mod = tvm.tir.transform.PlanAndUpdateBufferAllocationLocation()(orig_mod)\n    tvm.ir.assert_structural_equal(\n        mod, orig_mod\n    )  # PlanAndUpdateBufferAllocationLocation should do nothing on TE\n\n\ndef test_loop_carried_dependency():\n    \"\"\"The buffer allocation should be above opaque iter var's loop scopes\n    such that buffer accesses with loop carried dependencies are covered.\"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[(8, 8, 8), \"int32\"], B: T.Buffer[(8, 8, 8), \"int32\"]):\n        C = T.alloc_buffer([8, 8, 8], dtype=\"int32\")\n        for i in T.serial(8):\n            for j in T.serial(8):\n                for k in T.serial(8):\n                    with T.block(\"b0\"):\n                        vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                        C[vi, vj, vk] = A[vi, vj, vk] + 1\n                for k in T.serial(8):\n                    with T.block(\"b1\"):\n                        vi, vk = T.axis.remap(\"SS\", [i, k])\n                        vj = T.axis.opaque(8, j)\n                        B[vi, vj, vk] = C[vi, vj, vk] + T.if_then_else(\n                            0 < vj, C[vi, vj - 1, vk], 0, dtype=\"int32\"\n                        )\n\n    @T.prim_func\n    def after(A: T.Buffer[(8, 8, 8), \"int32\"], B: T.Buffer[(8, 8, 8), \"int32\"]) -> None:\n        for i in T.serial(8):\n            with T.block():\n                T.reads(A[i, 0:8, 0:8])\n                T.writes(B[i, 0:8, 0:8])\n                C = T.alloc_buffer([8, 8, 8], dtype=\"int32\")\n                for j in T.serial(8):\n                    for k in T.serial(8):\n                        with T.block(\"b0\"):\n                            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                            C[vi, vj, vk] = A[vi, vj, vk] + 1\n                    for k in T.serial(8):\n                        with T.block(\"b1\"):\n                            vi, vk = T.axis.remap(\"SS\", [i, k])\n                            vj = T.axis.opaque(8, j)\n                            B[vi, vj, vk] = C[vi, vj, vk] + T.if_then_else(\n                                0 < vj, C[vi, vj - 1, vk], 0, dtype=\"int32\"\n                            )\n\n    _check(before, after)\n\n\ndef test_1D_cascade_op_rolling_buffer():\n    \"\"\"The intermediate buffer must be allocated above rolling buffer's rolling loop,\n    which is marked as opaque in consumer block's iter mappings.\"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[(4, 16), \"int32\"], C: T.Buffer[(4, 8), \"int32\"]):\n        B = T.alloc_buffer((4, 6), \"int32\")\n        for c in T.serial(4):\n            for i in T.serial(0, 2):\n                for j in T.serial(0, 6):\n                    for k in T.serial(3):\n                        with T.block(\"P1\"):\n                            T.where(i < 1 or j >= 2)\n                            cc, vi, vj, vk = T.axis.remap(\"SSSR\", [c, i, j, k])\n                            if vk == 0:\n                                B[cc, T.floormod(vi * 4 + vj, 6)] = 0\n                            B[cc, T.floormod(vi * 4 + vj, 6)] = (\n                                B[cc, T.floormod(vi * 4 + vj, 6)] + A[cc, vi * 4 + vj + vk]\n                            )\n                for j in T.serial(0, 4):\n                    for k in T.serial(3):\n                        with T.block(\"P2\"):\n                            vi = T.axis.opaque(2, i)\n                            cc, vj, vk = T.axis.remap(\"SSR\", [c, j, k])\n                            if vk == 0:\n                                C[cc, vi * 4 + vj] = 0\n                            C[cc, vi * 4 + vj] = (\n                                C[cc, vi * 4 + vj] + B[cc, T.floormod(vi * 4 + vj + vk, 6)]\n                            )\n\n    @T.prim_func\n    def after(A: T.Buffer[(4, 16), \"int32\"], C: T.Buffer[(4, 8), \"int32\"]):\n        for c in T.serial(4):\n            with T.block():\n                T.reads(A[c, 0:12], C[c, 0:8])\n                T.writes(C[c, 0:8])\n                B = T.alloc_buffer([4, 6], dtype=\"int32\")\n                for i in T.serial(2):\n                    for j, k in T.grid(6, 3):\n                        with T.block(\"P1\"):\n                            T.where(i < 1 or j >= 2)\n                            cc, vi, vj, vk = T.axis.remap(\"SSSR\", [c, i, j, k])\n                            if vk == 0:\n                                B[cc, (vi * 4 + vj) % 6] = 0\n                            B[cc, (vi * 4 + vj) % 6] = (\n                                B[cc, (vi * 4 + vj) % 6] + A[cc, vi * 4 + vj + vk]\n                            )\n                    for j, k in T.grid(4, 3):\n                        with T.block(\"P2\"):\n                            vi = T.axis.opaque(2, i)\n                            cc, vj, vk = T.axis.remap(\"SSR\", [c, j, k])\n                            if vk == 0:\n                                C[cc, vi * 4 + vj] = 0\n                            C[cc, vi * 4 + vj] = C[cc, vi * 4 + vj] + B[cc, (vi * 4 + vj + vk) % 6]\n\n    _check(before, after)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_prim_func_pass.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\n\n\ndef test_prim_func_pass():\n    @tvm.tir.transform.prim_func_pass(opt_level=1)\n    class TestReplaceFunc:\n        \"\"\"Simple test function to replace one argument to another.\"\"\"\n\n        def __init__(self, new_func):\n            self.new_func = new_func\n\n        def transform_function(self, func, mod, ctx):\n            return self.new_func\n\n    x = te.var(\"x\")\n    y = te.var(\"y\")\n    b = tvm.tir.decl_buffer((x,), \"float32\")\n    stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1))\n\n    func = tvm.tir.PrimFunc([x, y, b], stmt)\n\n    new_func = tvm.tir.PrimFunc([x, y, b], tvm.tir.Evaluate(0))\n\n    mod = tvm.IRModule({\"main\": func})\n    mod = TestReplaceFunc(new_func)(mod)\n\n    assert tvm.ir.structural_equal(mod[\"main\"].body, new_func.body)\n\n\ndef test_cow_pass():\n    def fapply(f):\n        assert tvm.testing.object_use_count(f) == 1\n        return f\n\n    pidentity = tvm.tir.transform.Apply(fapply)\n    x = te.var(\"x\")\n    func = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x)).with_attr(\"target_bits\", 32)\n    func_hash = func.__hash__()\n    mod = tvm.IRModule({\"main\": func})\n    del func\n    # copy on write\n    mod_hash = mod.__hash__()\n    mod = tvm.transform.Sequential([pidentity, tvm.tir.transform.NarrowDataType(32)])(mod._move())\n    assert mod_hash == mod.__hash__()\n    assert func_hash == mod[\"main\"].__hash__()\n\n\nif __name__ == \"__main__\":\n    test_cow_pass()\n    test_prim_func_pass()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_profiling_instr.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nimport numpy\n\ndefault_lwp_test_config = {\n    \"tir.instrument_lwp\": True,\n    \"tir.lwp_disable_func_prof\": True,\n    \"tir.reset_start_id\": True,\n}\n\n\n@T.prim_func\ndef input1(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    for i, j in T.grid(8, 8):\n        for k, l in T.grid(8, 16):\n            with T.block(\"B\"):\n                vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n        for k, l in T.grid(8, 16):\n            with T.block(\"C\"):\n                vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2\n\n\n@T.prim_func\ndef input2(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    D = T.match_buffer(d, (8, 8, 128), dtype=\"int32\")\n    for i in T.serial(0, 8):\n        for j in T.serial(0, 8):\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n        for j in T.serial(0, 8):\n            for k, l in T.grid(8, 16):\n                with T.block(\"C\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n\n\n@T.prim_func\ndef input3(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    D = T.match_buffer(d, (8, 8, 128), dtype=\"int32\")\n    for i in T.serial(0, 8):\n        for j in T.parallel(0, 8):\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n        for j in T.serial(0, 8):\n            for k in T.parallel(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"C\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2\n            for k in T.parallel(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n\n\n@T.prim_func\ndef test1_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    for i, j in T.grid(8, 8):\n        T.evaluate(T.start_profile_intrinsic(3, dtype=\"handle\"))\n        for k, l in T.grid(8, 16):\n            with T.block(\"B\"):\n                vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n        T.evaluate(T.end_profile_intrinsic(3, dtype=\"handle\"))\n        T.evaluate(T.start_profile_intrinsic(5, dtype=\"handle\"))\n        for k, l in T.grid(8, 16):\n            with T.block(\"C\"):\n                vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2\n        T.evaluate(T.end_profile_intrinsic(5, dtype=\"handle\"))\n\n\n@T.prim_func\ndef test2_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    T.evaluate(T.start_profile_intrinsic(1, dtype=\"handle\"))\n    for i in T.serial(0, 8):\n        T.evaluate(T.start_profile_intrinsic(2, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"C\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2\n        T.evaluate(T.end_profile_intrinsic(2, dtype=\"handle\"))\n    T.evaluate(T.end_profile_intrinsic(1, dtype=\"handle\"))\n\n\n@T.prim_func\ndef test3_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    T.evaluate(T.start_profile_intrinsic(1, dtype=\"handle\"))\n    for i in T.serial(0, 8):\n        T.evaluate(T.start_profile_intrinsic(2, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            T.evaluate(T.start_profile_intrinsic(3, dtype=\"handle\"))\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            T.evaluate(T.end_profile_intrinsic(3, dtype=\"handle\"))\n            T.evaluate(T.start_profile_intrinsic(5, dtype=\"handle\"))\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"C\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2\n            T.evaluate(T.end_profile_intrinsic(5, dtype=\"handle\"))\n        T.evaluate(T.end_profile_intrinsic(2, dtype=\"handle\"))\n    T.evaluate(T.end_profile_intrinsic(1, dtype=\"handle\"))\n\n\n@T.prim_func\ndef test4_expected_output(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    D = T.match_buffer(d, (8, 8, 128), dtype=\"int32\")\n    for i in T.serial(0, 8):\n        T.evaluate(T.start_profile_intrinsic(2, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            T.evaluate(T.start_profile_intrinsic(3, dtype=\"handle\"))\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            T.evaluate(T.end_profile_intrinsic(3, dtype=\"handle\"))\n            T.evaluate(T.start_profile_intrinsic(5, dtype=\"handle\"))\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n            T.evaluate(T.end_profile_intrinsic(5, dtype=\"handle\"))\n        T.evaluate(T.end_profile_intrinsic(2, dtype=\"handle\"))\n        T.evaluate(T.start_profile_intrinsic(7, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            T.evaluate(T.start_profile_intrinsic(8, dtype=\"handle\"))\n            for k, l in T.grid(8, 16):\n                with T.block(\"C\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2\n            T.evaluate(T.end_profile_intrinsic(8, dtype=\"handle\"))\n            T.evaluate(T.start_profile_intrinsic(10, dtype=\"handle\"))\n            for k, l in T.grid(8, 16):\n                with T.block(\"B\"):\n                    vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                    C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n            T.evaluate(T.end_profile_intrinsic(10, dtype=\"handle\"))\n        T.evaluate(T.end_profile_intrinsic(7, dtype=\"handle\"))\n\n\n@T.prim_func\ndef test5_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    T.evaluate(T.start_profile_intrinsic(1, dtype=\"handle\"))\n    for i in T.serial(0, 8):\n        T.evaluate(T.start_profile_intrinsic(2, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"C\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2\n        T.evaluate(T.end_profile_intrinsic(2, dtype=\"handle\"))\n    T.evaluate(T.end_profile_intrinsic(1, dtype=\"handle\"))\n\n\n@T.prim_func\ndef test6_expected_output(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:\n    A = T.match_buffer(a, (8, 8, 128), dtype=\"int32\")\n    B = T.match_buffer(b, (8, 8, 128), dtype=\"int32\")\n    C = T.match_buffer(c, (8, 8, 128), dtype=\"int32\")\n    D = T.match_buffer(d, (8, 8, 128), dtype=\"int32\")\n    for i in T.serial(0, 8):\n        T.evaluate(T.start_profile_intrinsic(2, dtype=\"handle\"))\n        for j in T.parallel(0, 8):\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2\n            for k in T.serial(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n        T.evaluate(T.end_profile_intrinsic(2, dtype=\"handle\"))\n        T.evaluate(T.start_profile_intrinsic(7, dtype=\"handle\"))\n        for j in T.serial(0, 8):\n            T.evaluate(T.start_profile_intrinsic(8, dtype=\"handle\"))\n            for k in T.parallel(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"C\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2\n            T.evaluate(T.end_profile_intrinsic(8, dtype=\"handle\"))\n            T.evaluate(T.start_profile_intrinsic(10, dtype=\"handle\"))\n            for k in T.parallel(0, 8):\n                for l in T.serial(0, 16):\n                    with T.block(\"B\"):\n                        vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n                        C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]\n            T.evaluate(T.end_profile_intrinsic(10, dtype=\"handle\"))\n        T.evaluate(T.end_profile_intrinsic(7, dtype=\"handle\"))\n\n\n# By default, only loops with siblings are instrumented.\ndef test1():\n    with tvm.transform.PassContext(config=default_lwp_test_config):\n        mod = tvm.IRModule.from_expr(input1)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test1_expected_output)\n\n\n# By default, only loops with siblings are instrumented. Here, 'lwp_max_depth'\n# doesn't have any effect unless 'instr_siblings' is set to False (ex: test3).\ndef test2():\n    test2_config = default_lwp_test_config.copy()\n    test2_config.update({\"tir.lwp_max_depth\": 3})\n    with tvm.transform.PassContext(config=test2_config):\n        mod = tvm.IRModule.from_expr(input1)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test1_expected_output)\n\n\n# test3: Use 'lwp_max_depth' to instrument loops upto a certain depth. This flag\n# is effective only when 'instr_siblings' is disabled. Also, note that inner-most\n# loops are always excluded from instrumentation unless overwritten using\n# 'lwp_min_height' (ex: test5)\ndef test3():\n    test3_config = default_lwp_test_config.copy()\n    test3_config.update({\"tir.lwp_max_depth\": 3, \"tir.instr_siblings\": False})\n    with tvm.transform.PassContext(config=test3_config):\n        mod = tvm.IRModule.from_expr(input1)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test3_expected_output)\n\n\n# test4: Use 'lwp_min_height' to exclude inner loops upto a certain height from\n# instrumentation.\ndef test4():\n    with tvm.transform.PassContext(config=default_lwp_test_config):\n        mod = tvm.IRModule.from_expr(input2)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test4_expected_output)\n\n\n# test5: Use both 'lwp_min_height' and 'lwp_max_depth'.\n# instrumentation.\ndef test5():\n    test5_config = default_lwp_test_config.copy()\n    test5_config.update(\n        {\"tir.lwp_max_depth\": 3, \"tir.instr_siblings\": False, \"tir.lwp_min_height\": 2}\n    )\n    with tvm.transform.PassContext(config=test5_config):\n        mod = tvm.IRModule.from_expr(input1)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test5_expected_output)\n\n\n# test6: Tests instrumentation for the parallel loops\ndef test6():\n    with tvm.transform.PassContext(config=default_lwp_test_config):\n        mod = tvm.IRModule.from_expr(input3)\n        mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], test6_expected_output)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_remove_assume.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nfrom tvm import TVMError\nfrom tvm.script import tir as T\n\n\nclass BaseBeforeAfter(tvm.testing.CompareBeforeAfter):\n    @tvm.testing.fixture\n    def transform(self):\n        return tvm.tir.transform.RemoveAssume()\n\n\nclass TestRemoveAssume(BaseBeforeAfter):\n    \"\"\"Remove any instance of T.assume\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"]):\n        T.evaluate(T.assume(A[0] == 5))\n        A[0] = 10\n\n    def expected(A: T.Buffer[1, \"int32\"]):\n        A[0] = 10\n\n\nclass TestRemoveAssumeLoop(BaseBeforeAfter):\n    \"\"\"Loops containing only T.assume should be removed\"\"\"\n\n    def before(A: T.Buffer[16, \"int32\"]):\n        for i in T.serial(16):\n            T.evaluate(T.assume(A[i] == 0))\n\n        for i in T.serial(16):\n            A[i] = 10\n\n    def expected(A: T.Buffer[16, \"int32\"]):\n        for i in T.serial(16):\n            A[i] = 10\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_remove_no_op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.script import tir as T\nimport tvm.testing\n\n\ndef nop():\n    return tvm.tir.Evaluate(0)\n\n\ndef test_remove_no_op():\n    i = te.var(\"i\")\n    j = te.var(\"j\")\n    k = te.var(\"k\")\n    m = te.var(\"m\")\n    n = te.var(\"n\")\n    dtype = \"int64\"\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    stmt = tvm.tir.For(\n        i,\n        0,\n        4,\n        tvm.tir.ForKind.SERIAL,\n        tvm.tir.For(\n            j,\n            0,\n            n,\n            tvm.tir.ForKind.SERIAL,\n            tvm.tir.For(\n                k,\n                0,\n                m,\n                tvm.tir.ForKind.SERIAL,\n                tvm.tir.IfThenElse((i * m + j + k < n), tvm.tir.Evaluate(m), tvm.tir.Evaluate(n)),\n            ),\n        ),\n    )\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt))\n    ret = tvm.tir.transform.RemoveNoOp()(mod)[\"main\"].body\n\n    assert isinstance(ret, tvm.tir.Evaluate)\n    store = tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1])\n    stmt2 = tvm.tir.SeqStmt([nop(), tvm.tir.SeqStmt([store, nop()])])\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt2))\n    ret = tvm.tir.transform.RemoveNoOp()(mod)[\"main\"].body\n    assert ret == store\n\n    # remove zero extent loop\n    stmt3 = tvm.tir.For(i, 0, 0, tvm.tir.ForKind.SERIAL, store)\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt3))\n    ret = tvm.tir.transform.RemoveNoOp()(mod)[\"main\"].body\n    assert isinstance(ret, tvm.tir.Evaluate)\n\n\ndef test_remove_no_op_with_invalid_extent():\n    @T.prim_func\n    def main(A: T.Buffer[(16), \"int32\"], B: T.Buffer[(16), \"int32\"]) -> None:\n        for i in T.serial(16):\n            for j in T.serial(i - 20):\n                B[i] = A[i] + j\n\n    mod = tvm.ir.module.IRModule.from_expr(main)\n    ret = tvm.tir.transform.RemoveNoOp()(mod)[\"main\"].body\n    assert isinstance(ret, tvm.tir.Evaluate)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_remove_undef.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\nfrom tvm import TVMError\n\n\nclass BaseBeforeAfter(tvm.testing.CompareBeforeAfter):\n    @tvm.testing.fixture\n    def transform(self):\n        return tvm.tir.transform.RemoveStoreUndef()\n\n\nclass TestRemoveStoreUndef(BaseBeforeAfter):\n    \"\"\"Remove a store whose value is T.undef()\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"]):\n        A[0] = T.undef(dtype=\"int32\")\n\n    def expected(A: T.Buffer[1, \"int32\"]):\n        T.evaluate(0)\n\n\nclass TestRemoveStoreUndefExpression(BaseBeforeAfter):\n    \"\"\"Expressions containing T.undef() are removed\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"]):\n        A[0] = 1 + T.undef(dtype=\"int32\")\n\n    def expected(A: T.Buffer[1, \"int32\"]):\n        T.evaluate(0)\n\n\nclass TestKeepOtherCallNodes(BaseBeforeAfter):\n    \"\"\"Expressions containing other CallNodes are not removed\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"], n: T.int32):\n        A[0] = T.shift_left(n, 1, dtype=\"int32\")\n\n    expected = before\n\n\nclass TestRemoveLetUndef(BaseBeforeAfter):\n    \"\"\"Remove a store whose value is bound to T.undef()\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"]):\n        val = T.undef(dtype=\"int32\")\n        A[0] = val\n\n    def expected(A: T.Buffer[1, \"int32\"]):\n        T.evaluate(0)\n\n\nclass TestRaiseErrorForUndefAsStoreIndices(BaseBeforeAfter):\n    \"\"\"Use of T.undef() as buffer indices is an error\"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"]):\n        val = T.undef(dtype=\"int32\")\n        A[val] = 5\n\n    expected = TVMError\n\n\nclass TestRaiseErrorForUndefAsLoadIndices(BaseBeforeAfter):\n    \"\"\"Use of T.undef() as buffer indices is an error\n\n    Even though this occurs as part of the BufferStore's value, the\n    T.undef() may not appear in a buffer's indices.\n    \"\"\"\n\n    def before(A: T.Buffer[1, \"int32\"], B: T.Buffer[1, \"int32\"]):\n        B[0] = A[T.undef(dtype=\"int32\")]\n\n    expected = TVMError\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_remove_weight_layout_rewrite_block.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\n\nimport tvm\nfrom tvm.ir.module import IRModule\nfrom tvm.script import tir as T\nfrom tvm.tir.function import PrimFunc\n\n\ndef _check(before, expect):\n    if isinstance(before, PrimFunc):\n        before = IRModule({\"main\": before})\n    if isinstance(expect, PrimFunc):\n        expect = IRModule({\"main\": expect})\n\n    mod = tvm.tir.transform.RemoveWeightLayoutRewriteBlock()(before)\n    tvm.ir.assert_structural_equal(mod, expect)\n\n\ndef test_matmul():\n    @T.prim_func\n    def before(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 16), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [1]})\n        B_ = T.alloc_buffer([16, 4, 4], dtype=\"float32\")\n        for i0_o, i1_o in T.grid(16, 16):\n            with T.block(\"layout_rewrite\"):\n                i0, i1 = T.axis.remap(\"SS\", [i0_o, i1_o])\n                T.reads(B[i0, i1])\n                T.writes(B_[i1, i0 // 4, i0 % 4])\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\": True})\n                B_[i1, i0 // 4, i0 % 4] = B[i0, i1]\n        for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n            with T.block(\"matmul\"):\n                vi = T.axis.spatial(16, i0 * 4 + i1)\n                vj = T.axis.spatial(16, j)\n                vk = T.axis.reduce(16, k0 * 4 + k1)\n                T.reads(A[vi, vk], B_[vj, vk // 4, vk % 4])\n                T.writes(C[vi, vj])\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B_[vj, vk // 4, vk % 4]\n\n    @T.prim_func\n    def after(\n        A: T.Buffer[(16, 16), \"float32\"],\n        B: T.Buffer[(16, 4, 4), \"float32\"],\n        C: T.Buffer[(16, 16), \"float32\"],\n    ) -> None:\n        T.func_attr({\"layout_free_buffers\": [1]})\n        for i0_o, i1_o in T.grid(16, 16):\n            with T.block(\"layout_rewrite\"):\n                i0, i1 = T.axis.remap(\"SS\", [i0_o, i1_o])\n                T.reads()\n                T.writes()\n                T.block_attr({\"meta_schedule.layout_rewrite_preproc\": True})\n                T.evaluate(0)\n        for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):\n            with T.block(\"matmul\"):\n                vi = T.axis.spatial(16, i0 * 4 + i1)\n                vj = T.axis.spatial(16, j)\n                vk = T.axis.reduce(16, k0 * 4 + k1)\n                T.reads(A[vi, vk], B[vj, vk // 4, vk % 4])\n                T.writes(C[vi, vj])\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk // 4, vk % 4]\n\n    _check(before, after)\n\n\nif __name__ == \"__main__\":\n    test_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_renormalize_split_pattern.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T\n\n# fmt: off\n# pylint: disable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,redundant-keyword-arg\n\n@tvm.script.ir_module\nclass Before:\n    @T.prim_func\n    def main(inputs: T.Buffer[(8192,), \"float32\"], weight: T.Buffer[(2097152,), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(16384,), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype=\"float32\", data=inputs.data)\n        T.preflattened_buffer(weight, [4, 4, 512, 256], dtype=\"float32\", data=weight.data)\n        T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype=\"float32\", data=conv2d_transpose_nhwc.data)\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        # body\n        T.launch_thread(blockIdx_x, 64)\n        conv2d_transpose_nhwc_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        PadInput_shared = T.decl_buffer([768], \"float32\", scope=\"shared\")\n        weight_shared = T.decl_buffer([4096], \"float32\", scope=\"shared\")\n        T.launch_thread(threadIdx_x, 32)\n        for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):\n            conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)\n        for i6_0 in T.serial(16):\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):\n                PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(128 <= ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x and ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x < 640 and 1 <= blockIdx_x // 32 * 2 + (ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x) % 128 // 32 and blockIdx_x // 32 * 2 + (ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x) % 128 // 32 < 5, inputs[blockIdx_x // 32 * 1024 + ax0_ax1_ax2_ax3_fused_0 * 512 + i6_0 * 32 + threadIdx_x - 2560], T.float32(0), dtype=\"float32\")\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):\n                weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp((ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4) // 256 * 131072 + i6_0 * 8192 + (ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4) % 256 // 8 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 2 * 4, 1, 4)]\n            for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):\n                conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x // 8 * 128 + (i1_4 + i4_2) // 2 * 128 + (i2_4 + i5_2) // 2 * 32 + i2_3 * 32 + i6_1 * 8 + i6_2], T.float32(0), dtype=\"float32\") * weight_shared[i6_1 * 64 + i6_2 * 8 + threadIdx_x % 8 + 3840 - i5_2 * 256 - i4_2 * 1024]\n        for ax1, ax2 in T.grid(2, 4):\n            conv2d_transpose_nhwc[threadIdx_x // 8 * 4096 + ax1 * 2048 + blockIdx_x // 32 * 1024 + ax2 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 8] = conv2d_transpose_nhwc_local[ax1 * 4 + ax2]\n\n\n@tvm.script.ir_module\nclass After:\n    @T.prim_func\n    def main(inputs: T.Buffer[(8192,), \"float32\"], weight: T.Buffer[(2097152,), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(16384,), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype=\"float32\", data=inputs.data)\n        T.preflattened_buffer(weight, [4, 4, 512, 256], dtype=\"float32\", data=weight.data)\n        T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype=\"float32\", data=conv2d_transpose_nhwc.data)\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        # body\n        T.launch_thread(blockIdx_x, 64)\n        conv2d_transpose_nhwc_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        PadInput_shared = T.decl_buffer([768], \"float32\", scope=\"shared\")\n        weight_shared = T.decl_buffer([4096], \"float32\", scope=\"shared\")\n        T.launch_thread(threadIdx_x, 32)\n        for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):\n            conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)\n        for i6_0 in T.serial(16):\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):\n                PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(1 <= (ax0_ax1_ax2_ax3_fused_0 + threadIdx_x // 32) // 4 and (ax0_ax1_ax2_ax3_fused_0 + threadIdx_x // 32) // 20 < 1 and 1 <= blockIdx_x // 32 * 2 + (ax0_ax1_ax2_ax3_fused_0 + threadIdx_x // 32) % 4 and (blockIdx_x // 32 * 2 + (ax0_ax1_ax2_ax3_fused_0 + threadIdx_x // 32) % 4) // 5 < 1, inputs[blockIdx_x // 32 * 1024 + ax0_ax1_ax2_ax3_fused_0 * 512 + i6_0 * 32 + threadIdx_x - 2560], T.float32(0), dtype=\"float32\")\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):\n                weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp((ax0_ax1_ax2_ax3_fused_0 + threadIdx_x * 4 // 128) // 2 * 131072 + i6_0 * 8192 + (ax0_ax1_ax2_ax3_fused_0 * 16 + threadIdx_x * 4 // 8) % 32 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 2 * 4, 1, 4)]\n            for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):\n                conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x // 8 * 128 + (i1_4 + i4_2) // 2 * 128 + (i2_4 + i5_2) // 2 * 32 + i2_3 * 32 + i6_1 * 8 + i6_2], T.float32(0), dtype=\"float32\") * weight_shared[i6_1 * 64 + i6_2 * 8 + threadIdx_x % 8 + 3840 - i5_2 * 256 - i4_2 * 1024]\n        for ax1, ax2 in T.grid(2, 4):\n            conv2d_transpose_nhwc[threadIdx_x // 8 * 4096 + ax1 * 2048 + blockIdx_x // 32 * 1024 + ax2 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 8] = conv2d_transpose_nhwc_local[ax1 * 4 + ax2]\n\n\n@tvm.script.ir_module\nclass After_simplified:\n    @T.prim_func\n    def main(inputs: T.Buffer[(8192,), \"float32\"], weight: T.Buffer[(2097152,), \"float32\"], conv2d_transpose_nhwc: T.Buffer[(16384,), \"float32\"]) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # var definition\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype=\"float32\", data=inputs.data)\n        T.preflattened_buffer(weight, [4, 4, 512, 256], dtype=\"float32\", data=weight.data)\n        T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype=\"float32\", data=conv2d_transpose_nhwc.data)\n        # body\n        T.launch_thread(blockIdx_x, 64)\n        conv2d_transpose_nhwc_local = T.decl_buffer([8], \"float32\", scope=\"local\")\n        PadInput_shared = T.decl_buffer([768], \"float32\", scope=\"shared\")\n        weight_shared = T.decl_buffer([4096], \"float32\", scope=\"shared\")\n        T.launch_thread(threadIdx_x, 32)\n        for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):\n            conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)\n        for i6_0 in T.serial(16):\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):\n                PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(4 <= ax0_ax1_ax2_ax3_fused_0 and ax0_ax1_ax2_ax3_fused_0 < 20 and 1 <= blockIdx_x // 32 * 2 + ax0_ax1_ax2_ax3_fused_0 % 4 and blockIdx_x // 32 * 2 + ax0_ax1_ax2_ax3_fused_0 % 4 < 5, inputs[blockIdx_x // 32 * 1024 + ax0_ax1_ax2_ax3_fused_0 * 512 + i6_0 * 32 + threadIdx_x - 2560], T.float32(0), dtype=\"float32\")\n            for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):\n                weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp(ax0_ax1_ax2_ax3_fused_0 // 2 * 131072 + i6_0 * 8192 + ax0_ax1_ax2_ax3_fused_0 % 2 * 4096 + threadIdx_x // 2 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 2 * 4, 1, 4)]\n            for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):\n                conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x // 8 * 128 + (i1_4 + i4_2) // 2 * 128 + (i2_4 + i5_2) // 2 * 32 + i2_3 * 32 + i6_1 * 8 + i6_2], T.float32(0), dtype=\"float32\") * weight_shared[i6_1 * 64 + i6_2 * 8 + threadIdx_x % 8 + 3840 - i5_2 * 256 - i4_2 * 1024]\n        for ax1, ax2 in T.grid(2, 4):\n            conv2d_transpose_nhwc[threadIdx_x // 8 * 4096 + ax1 * 2048 + blockIdx_x // 32 * 1024 + ax2 * 256 + blockIdx_x % 32 * 8 + threadIdx_x % 8] = conv2d_transpose_nhwc_local[ax1 * 4 + ax2]\n\n# pylint: enable=no-member,invalid-name,unused-variable,line-too-long,redefined-outer-name,redundant-keyword-arg\n# fmt: on\n\n\ndef test_renormalize_split_pattern():\n    after = tvm.tir.transform.RenormalizeSplitPattern()(Before)\n    tvm.ir.assert_structural_equal(after, After)\n    after = tvm.tir.transform.Simplify()(after)\n    tvm.ir.assert_structural_equal(after, After_simplified)\n\n\n@T.prim_func\ndef impossible_equality(n: T.int32):\n    # Prior to bugfix, this conditional defined the expression \"2\" as\n    # equal to zero within the then_case. [min_value=2, max_value=0]\n    if 2 == 0:\n        # Then this expression evaluates n/2, using the min/max values\n        # of \"2\", which is caught as a divide by zero error.\n        if n // 2 >= 16:\n            T.evaluate(0)\n\n\n@T.prim_func\ndef impossible_inequality(n: T.int32):\n    # Prior to bugfix, this conditional set up a range of possible\n    # values for the expression \"-2\" as [0, kPosInf].\n    if -1 < -2:\n        if n // (-2) >= 16:\n            T.evaluate(0)\n\n\ninteger_condition = tvm.testing.parameter(\n    impossible_equality,\n    impossible_inequality,\n)\n\n\ndef test_analyze_inside_integer_conditional(integer_condition):\n    \"\"\"Avoid crash occurring in ConstIntBoundAnalyzer.\n\n    Crash occurred when simplifying some expressions with provably\n    false integer expressions.  If the expressions were renormalized\n    before calling Simplify, conditional statements could assign a\n    range of possible values to integers, as if they were variables.\n    This would result in divide by zero throwing an exception,\n    followed by a second exception during stack unwinding causing the\n    program to crash.\n    \"\"\"\n\n    # Similar issue would occur in most transformations that subclass\n    # IRMutatorWithAnalyzer.  tir.transform.Simplify() is an\n    # exception, as it rewrites the integer conditionals first.  These\n    # tests are written using RenormalizeSplitPattern as it is the\n    # first case identified.\n    transform = tvm.tir.transform.RenormalizeSplitPattern()\n\n    # Issue would result in an error through while applying the transformation.\n    mod = tvm.IRModule.from_expr(integer_condition)\n    transform(mod)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_rewrite_unsafe_select.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_rewrite_Select():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.allocate(\"float32\", 100, name=\"A\", scope=\"global\")\n    i = te.var(\"i\")\n    y = tvm.tir.Select(i > 1, A[i - 1], 1.0)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(y)))\n    yy = tvm.tir.transform.RewriteUnsafeSelect()(mod)[\"main\"].body.value\n\n    z = tvm.tir.Select(tvm.tir.Select(i > 1, A[i - 1], 1.0) > 0.0, A[i], 0.1)\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(z)))\n    zz = tvm.tir.transform.RewriteUnsafeSelect()(mod)[\"main\"].body.value\n\n    a = tvm.tir.Select(tvm.tir.floordiv(i, 4) > 10, y, z)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(a)))\n    aa = tvm.tir.transform.RewriteUnsafeSelect()(mod)[\"main\"].body.value\n    builtin_if_then_else = tvm.ir.Op.get(\"tir.if_then_else\")\n\n    assert yy.op.same_as(builtin_if_then_else)\n    assert yy.op.same_as(builtin_if_then_else)\n    assert isinstance(aa, tvm.tir.Select)\n\n\nif __name__ == \"__main__\":\n    test_rewrite_Select()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_simplify.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\n\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef test_stmt_simplify():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    C = ib.pointer(\"float32\", name=\"C\")\n    n = te.size_var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.if_scope(i < 12):\n            A[i] = C[i]\n\n    body = tvm.tir.LetStmt(n, 10, ib.get())\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))\n    body = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n    assert isinstance(body.body, tvm.tir.BufferStore)\n\n\ndef test_thread_extent_simplify():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    C = ib.pointer(\"float32\", name=\"C\")\n    n = te.size_var(\"n\")\n    tx = te.thread_axis(\"threadIdx.x\")\n    ty = te.thread_axis(\"threadIdx.y\")\n    ib.scope_attr(tx, \"thread_extent\", n)\n    ib.scope_attr(tx, \"thread_extent\", n)\n    ib.scope_attr(ty, \"thread_extent\", 1)\n    with ib.if_scope(tx + ty < 12):\n        A[tx] = C[tx + ty]\n    body = tvm.tir.LetStmt(n, 10, ib.get())\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))\n    body = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n    assert isinstance(body.body.body.body, tvm.tir.BufferStore)\n\n\ndef test_if_likely():\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    C = ib.pointer(\"float32\", name=\"C\")\n    n = te.size_var(\"n\")\n    tx = te.thread_axis(\"threadIdx.x\")\n    ty = te.thread_axis(\"threadIdx.y\")\n    ib.scope_attr(tx, \"thread_extent\", 32)\n    ib.scope_attr(ty, \"thread_extent\", 32)\n    with ib.if_scope(ib.likely(tx * 32 + ty < n)):\n        with ib.if_scope(ib.likely(tx * 32 + ty < n)):\n            A[tx] = C[tx * 32 + ty]\n    body = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))\n    body = tvm.tir.transform.Simplify()(mod)[\"main\"].body\n    assert isinstance(body.body.body, tvm.tir.IfThenElse)\n    assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)\n\n\ndef test_basic_likely_elimination():\n    n = te.size_var(\"n\")\n    X = te.placeholder(shape=(n,), name=\"x\")\n    W = te.placeholder(shape=(n + 1,), dtype=\"int32\", name=\"w\")\n\n    def f(i):\n        start = W[i]\n        extent = W[i + 1] - W[i]\n        rv = te.reduce_axis((0, extent))\n        return te.sum(X[rv + start], axis=rv)\n\n    Y = te.compute(X.shape, f, name=\"y\")\n    s = te.create_schedule([Y.op])\n    stmt = tvm.lower(s, [X, W, Y], simple_mode=True)\n    assert \"if\" not in str(stmt)\n\n\ndef test_complex_likely_elimination():\n    def cumsum(X):\n        \"\"\"\n        Y[i] = sum(X[:i])\n        \"\"\"\n        (m,) = X.shape\n        s_state = te.placeholder((m + 1,), dtype=\"int32\", name=\"state\")\n        s_init = te.compute((1,), lambda _: tvm.tir.const(0, \"int32\"))\n        s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])\n        return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name=\"cumsum\")\n\n    def sparse_lengths_sum(data, indices, lengths):\n        oshape = list(data.shape)\n        oshape[0] = lengths.shape[0]\n        length_offsets = cumsum(lengths)\n\n        def sls(n, d):\n            gg = te.reduce_axis((0, lengths[n]))\n            indices_idx = length_offsets[n] + gg\n            data_idx = indices[indices_idx]\n            data_val = data[data_idx, d]\n            return te.sum(data_val, axis=gg)\n\n        return te.compute(oshape, sls)\n\n    m, n, d, i, l = (\n        te.size_var(\"m\"),\n        te.size_var(\"n\"),\n        te.size_var(\"d\"),\n        te.size_var(\"i\"),\n        te.size_var(\"l\"),\n    )\n    data_ph = te.placeholder((m, d * 32), name=\"data\")\n    indices_ph = te.placeholder((i,), name=\"indices\", dtype=\"int32\")\n    lengths_ph = te.placeholder((n,), name=\"lengths\", dtype=\"int32\")\n    Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)\n    s = te.create_schedule([Y.op])\n    (n, d) = s[Y].op.axis\n    (do, di) = s[Y].split(d, factor=32)\n    (gg,) = s[Y].op.reduce_axis\n    s[Y].reorder(n, do, gg, di)\n    s[Y].vectorize(di)\n    stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)\n    assert \"if\" not in str(stmt)\n\n\nclass BaseBeforeAfter(tvm.testing.CompareBeforeAfter):\n    transitively_prove_inequalities = False\n    convert_boolean_to_and_of_ors = False\n    apply_constraints_to_boolean_branches = False\n\n    def transform(self):\n        def inner(mod):\n            config = {\n                \"tir.Simplify\": {\n                    \"transitively_prove_inequalities\": self.transitively_prove_inequalities,\n                    \"convert_boolean_to_and_of_ors\": self.convert_boolean_to_and_of_ors,\n                    \"apply_constraints_to_boolean_branches\": self.apply_constraints_to_boolean_branches,\n                }\n            }\n            with tvm.transform.PassContext(config=config):\n                mod = tvm.tir.transform.Simplify()(mod)\n            return mod\n\n        return inner\n\n\nclass TestLoadStoreNoop(BaseBeforeAfter):\n    \"\"\"Store of a value that was just read from the same location is a no-op.\"\"\"\n\n    def before(A: T.Buffer[(1,), \"float32\"]):\n        A[0] = A[0]\n\n    def expected(A: T.Buffer[(1,), \"float32\"]):\n        T.evaluate(0)\n\n\nclass TestLoadStoreNoopAfterSimplify(BaseBeforeAfter):\n    \"\"\"As test_load_store_noop, but requiring simplification to identify.\n\n    Previously, a bug caused the self-assignment of a buffer to\n    checked based on the pre-simplification assignment, not the\n    post-simplification.  This test is to identify any similar\n    regression.\n    \"\"\"\n\n    def before(A: T.Buffer[(1,), \"float32\"]):\n        A[0] = A[0] + (5.0 - 5.0)\n\n    def expected(A: T.Buffer[(1,), \"float32\"]):\n        T.evaluate(0)\n\n\nclass TestNestedCondition(BaseBeforeAfter):\n    \"\"\"Nested IfThenElse with the same condition can be simplified.\n\n    Requires const_int_bound to narrow scope of i within the\n    conditional, or for rewrite_simplify to recognize the literal\n    constraint.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"float32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                if i == 5:\n                    A[i] = 0.0\n\n    def expected(A: T.Buffer[(16,), \"float32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                A[i] = 0.0\n\n\nclass TestNestedProvableCondition(BaseBeforeAfter):\n    \"\"\"Simplify inner conditional using constraint from outer.\n\n    Requires const_int_bound to narrow scope of i within the\n    conditional.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"float32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                if i < 7:\n                    A[i] = 0.0\n\n    def expected(A: T.Buffer[(16,), \"float32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                A[i] = 0.0\n\n\nclass TestNestedVarCondition(BaseBeforeAfter):\n    \"\"\"Simplify inner conditional using constraint from outer.\n\n    Requires for rewrite_simplify to recognize the repeated\n    constraint.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"float32\"], n: T.int32):\n        for i in T.serial(16):\n            if i == n:\n                if i == n:\n                    A[i] = 0.0\n\n    def expected(A: T.Buffer[(16,), \"float32\"], n: T.int32):\n        for i in T.serial(16):\n            if i == n:\n                A[i] = 0.0\n\n\nclass TestAlteredBufferContents(BaseBeforeAfter):\n    \"\"\"No simplification of data-dependent conditionals.\n\n    A literal constraint must not be propagated if the values\n    referenced may change.  TIR requires single assignment of\n    variables, so Var objects may be assumed constant, but BufferLoad\n    may not.\n    \"\"\"\n\n    def before(A: T.Buffer[(1,), \"int32\"], n: T.int32):\n        if A[0] == n:\n            A[0] = A[0] + 1\n            if A[0] == n:\n                A[0] = 0\n\n    expected = before\n\n\nclass TestNegationOfCondition(BaseBeforeAfter):\n    \"\"\"Use negation of outer condition to simplify innner.\n\n    Within the body of an if statement, the negation of the\n    condition is known to be false.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"int32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                if i != 5:\n                    A[i] = 0\n                else:\n                    A[i] = 1\n\n    def expected(A: T.Buffer[(16,), \"int32\"]):\n        for i in T.serial(16):\n            if i == 5:\n                A[i] = 1\n\n\nclass TestNegationOfNotEqual(BaseBeforeAfter):\n    \"\"\"As TestNegationOfVarCondition, but with a != outer condition.\n\n    Because ConstIntBoundAnalyzer only tracks the min and max allowed\n    values, the outer i!=5 condition does provide a constraint on the\n    bounds.  This test relies on RewriteSimplifier to recognize\n    ``i==5`` as the negation of a literal constraint.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"int32\"]):\n        for i in T.serial(16):\n            if i != 5:\n                if i == 5:\n                    A[i] = 0\n                else:\n                    A[i] = 1\n\n    def expected(A: T.Buffer[(16,), \"int32\"]):\n        for i in T.serial(16):\n            if i != 5:\n                A[i] = 1\n\n\nclass TestNegationOfVarCondition(BaseBeforeAfter):\n    \"\"\"As TestNegationOfVarCondition, but with a dynamic condition.\n\n    This simplification cannot be done with ConstIntBoundAnalyzer, and\n    must rely on RewriteSimplifier recognizing the repeated literal.\n    \"\"\"\n\n    def before(A: T.Buffer[(16,), \"int32\"], n: T.int32):\n        for i in T.serial(16):\n            if i == n:\n                if i != n:\n                    A[i] = 0\n                else:\n                    A[i] = 1\n\n    def expected(A: T.Buffer[(16,), \"int32\"], n: T.int32):\n        for i in T.serial(16):\n            if i == n:\n                A[i] = 1\n\n\nclass TestLiteralConstraintSplitBooleanAnd(BaseBeforeAfter):\n    \"\"\"Split a boolean AND into independent constraints\n\n    A single if condition may impose multiple literal constraints.\n    Each constraint that is ANDed together to form the condition\n    should be treated as an independent constraint.  The use of n in\n    the condition is to ensure we exercise RewriteSimplifier.\n    \"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"int32\"], n: T.int32):\n        for i, j in T.grid(16, 16):\n            if i == n and j == n:\n                if i == n:\n                    A[i, j] = 0\n\n    def expected(A: T.Buffer[(16, 16), \"int32\"], n: T.int32):\n        for i, j in T.grid(16, 16):\n            if i == n and j == n:\n                A[i, j] = 0\n\n\nclass TestLiteralConstraintSplitBooleanOr(BaseBeforeAfter):\n    \"\"\"Split a boolean OR into independent constraints\n\n    Similar to TestLiteralConstraintSplitBooleanAnd, but splitting a\n    boolean OR into independent conditions.  This uses the\n    simplification that ``!(x || y) == !x && !y``.\n\n    The use of ``n`` in the condition is to ensure we exercise\n    RewriteSimplifier.\n    \"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"int32\"], n: T.int32):\n        for i, j in T.grid(16, 16):\n            if i == n or j == n:\n                A[i, j] = 0\n            else:\n                if i == n:\n                    A[i, j] = 1\n                else:\n                    A[i, j] = 2\n\n    def expected(A: T.Buffer[(16, 16), \"int32\"], n: T.int32):\n        for i, j in T.grid(16, 16):\n            if i == n or j == n:\n                A[i, j] = 0\n            else:\n                A[i, j] = 2\n\n\nclass TestProveConditionUsingLet(BaseBeforeAfter):\n    \"\"\"Simplify conditions using non-inlined let bindings\n\n    Not all let bindings are inlined when they occur in later\n    expressions.  However, even if they are not inlined, they may be\n    used to prove the value of a condition.\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if condition or i >= 3:\n                A[i] = condition\n\n    @T.prim_func\n    def expected(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            A[i] = condition\n\n\nclass TestProveLetCondition(BaseBeforeAfter):\n    \"\"\"Simplify conditions using non-inlined let bindings\n\n    Not all let bindings are inlined when they occur in later\n    expressions.  However, even if they are not inlined, they may be\n    used to prove the value of a condition.\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if i < 3:\n                if condition:\n                    A[i] = condition\n\n    @T.prim_func\n    def expected(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if i < 3:\n                A[i] = condition\n\n\nclass TestProveRepeatedLetCondition(BaseBeforeAfter):\n    \"\"\"Simplify conditions using non-inlined let bindings\n\n    A variable may be used as a literal constraint, and be recognized\n    as being True within the context of the constraint.\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if condition:\n                if condition:\n                    A[i] = condition\n\n    @T.prim_func\n    def expected(A: T.Buffer[4, \"bool\"]):\n        for i in T.serial(4):\n            condition = i < 3\n            if condition:\n                A[i] = True\n\n\nclass TestIfThenElseExpr(BaseBeforeAfter):\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if i < 12:\n                A[i] = T.if_then_else(i < 12, 1.0, 2.0, dtype=\"float32\")\n\n    @T.prim_func\n    def expected(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if i < 12:\n                A[i] = 1.0\n\n\nclass TestCeilLog2Int(BaseBeforeAfter):\n    \"\"\"Simplify expressions resulting from topi.math.ceil_log2\"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[1, \"int32\"]):\n        A[0] = T.cast(\n            T.ceil(T.log2(T.cast(14, \"float64\"), dtype=\"float64\"), dtype=\"float64\"), dtype=\"int32\"\n        )\n\n    @T.prim_func\n    def expected(A: T.Buffer[1, \"int32\"]):\n        A[0] = 4\n\n\nclass TestLeftCeilLog2LowerBound(BaseBeforeAfter):\n    \"\"\"Integer bounds are propagated through topi.math.ceil_log2\"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            x = T.cast(\n                T.ceil(T.log2(T.cast(i + 1024 + 1, \"float64\"), dtype=\"float64\"), dtype=\"float64\"),\n                dtype=\"int32\",\n            )\n            if x == 11:\n                A[i] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            A[i] = 0.0\n\n\nclass TestLeftShiftLowerBound(BaseBeforeAfter):\n    \"\"\"Integer bounds are propagated through left shift\n\n    min(1 << i) = 1 << min(i)\n                = 1 << 0\n                = 1\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if T.shift_left(1, i, dtype=\"int32\") >= 1:\n                A[i] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            A[i] = 0.0\n\n\nclass TestLeftShiftUpperBound(BaseBeforeAfter):\n    \"\"\"Integer bounds are propagated through left shift\n\n    max(31 << i) = 31 << max(i)\n                 = 31 << 15\n                 = 1015808\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if T.shift_left(31, i, dtype=\"int32\") <= 1015808:\n                A[i] = 0.0\n\n    @T.prim_func\n    def expected(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            A[i] = 0.0\n\n\nclass TestLeftShiftOfNegativeValue(BaseBeforeAfter):\n    \"\"\"No const int bounds of left shift of negative value.\n\n    This is target dependent, and does not currently have a specified\n    behavior in TIR.  For example, in CodeGenC, this generates C code\n    with undefined behavior.\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if -64 <= T.shift_left(-i, 4, dtype=\"int32\"):\n                A[i] = 0.0\n\n    expected = before\n\n\nclass TestLeftShiftByNegativeValue(BaseBeforeAfter):\n    \"\"\"No const int bounds of left shift by negative bit count.\n\n    This is target dependent, and does not currently have a specified\n    behavior in TIR.  For example, in CodeGenC, this generates C code\n    with undefined behavior.\n    \"\"\"\n\n    @T.prim_func\n    def before(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            if T.shift_left(16, -i, dtype=\"int32\") <= 16:\n                A[i] = 0.0\n\n    expected = before\n\n\nclass TestRemoveTransitivelyProvableCondition(BaseBeforeAfter):\n    \"\"\"Remove comparisons that may be proven using multiple others\n\n    For example, the `0 < i` and `i <= j` conditions can be used to prove\n    that `0 < j`.\n    \"\"\"\n\n    transitively_prove_inequalities = True\n\n    i, j, k = [tvm.tir.Var(name, \"int32\") for name in \"ijk\"]\n    zero = tvm.tir.IntImm(\"int32\", 0)\n\n    test_case = tvm.testing.parameter(\n        (tvm.tir.all(zero < i, i <= j), zero < j, True),\n        # Transitive comparisons from LT\n        (tvm.tir.all(i < j, j < k), i < k, True),\n        (tvm.tir.all(i < j, j == k), i < k, True),\n        (tvm.tir.all(i < j, j <= k), i < k, True),\n        (tvm.tir.all(i < j, j > k), i < k, False),\n        (tvm.tir.all(i < j, j >= k), i < k, False),\n        (tvm.tir.all(i < j, j != k), i < k, False),\n        # Transitive comparisons from LE\n        (tvm.tir.all(i <= j, j < k), i < k, True),\n        (tvm.tir.all(i <= j, j == k), i == k, False),\n        (tvm.tir.all(i <= j, j == k), i <= k, True),\n        (tvm.tir.all(i <= j, j <= k), i <= k, True),\n        (tvm.tir.all(i <= j, j <= k), i < k, False),\n        (tvm.tir.all(i <= j, j > k), i < k, False),\n        (tvm.tir.all(i <= j, j >= k), i < k, False),\n        (tvm.tir.all(i <= j, j != k), i < k, False),\n        # Transitive comparisons from GT\n        (tvm.tir.all(i > j, j > k), i > k, True),\n        (tvm.tir.all(i > j, j == k), i > k, True),\n        (tvm.tir.all(i > j, j >= k), i > k, True),\n        (tvm.tir.all(i > j, j < k), i > k, False),\n        (tvm.tir.all(i > j, j <= k), i > k, False),\n        (tvm.tir.all(i > j, j != k), i > k, False),\n        # Transitive comparisons from GE\n        (tvm.tir.all(i >= j, j > k), i > k, True),\n        (tvm.tir.all(i >= j, j == k), i == k, False),\n        (tvm.tir.all(i >= j, j == k), i >= k, True),\n        (tvm.tir.all(i >= j, j >= k), i >= k, True),\n        (tvm.tir.all(i >= j, j >= k), i > k, False),\n        (tvm.tir.all(i >= j, j < k), i > k, False),\n        (tvm.tir.all(i >= j, j <= k), i > k, False),\n        (tvm.tir.all(i >= j, j != k), i > k, False),\n        # GT or LT may be used to prove NE\n        (tvm.tir.all(i == j, j != k), i != k, True),\n        (tvm.tir.all(i == j, j < k), i != k, True),\n        (tvm.tir.all(i == j, j > k), i != k, True),\n        (tvm.tir.all(i == j, j != k), i < k, False),\n        (tvm.tir.all(i == j, j != k), i > k, False),\n        # Because these are integers, x<y is equivalent to x <= y-1,\n        # and may be used in equivalent simplifications.\n        (tvm.tir.all(i <= j - 1, j < k), i < k, True),\n        (tvm.tir.all(i <= j - 1, j == k), i < k, True),\n        (tvm.tir.all(i <= j - 1, j <= k), i < k, True),\n        (tvm.tir.all(i <= j - 1, j > k), i < k, False),\n        (tvm.tir.all(i <= j - 1, j >= k), i < k, False),\n        (tvm.tir.all(i <= j - 1, j != k), i < k, False),\n        # Either or both inequalities may have an additive offset.\n        (tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 12, True),\n        (tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 11, False),\n        # For floats, x < y + c1 and y < z + c2 implies that x < z + (c1 + c2).\n        # Because this simplification applies to integers, transitive\n        # application of LT or GT can give a tighter constraint.\n        #\n        # i < j + c1, j < k + c2\n        # i <= j + c1 - 1, j <= k + c2 - 1\n        # i + 1 - c1 <= j, j <= k + c2 - 1\n        # i + 1 - c1 <= k + c2 - 1\n        # i <= k + c1 + c2 - 2\n        # i < k + (c1 + c2 - 1)\n        #\n        (tvm.tir.all(i < j + 5, j < k + 7), i < k + 11, True),\n        (tvm.tir.all(i < j + 5, j < k + 7), i < k + 10, False),\n    )\n\n    @tvm.testing.fixture\n    def before(self, test_case):\n        priors, postulate, _ = test_case\n\n        @T.prim_func\n        def func(A: T.Buffer[1, \"bool\"]):\n            if priors:\n                A[0] = postulate\n\n        return func\n\n    @tvm.testing.fixture\n    def expected(self, test_case):\n        priors, postulate, provable = test_case\n\n        analyzer = tvm.arith.Analyzer()\n        priors = analyzer.canonical_simplify(priors)\n\n        if provable:\n\n            @T.prim_func\n            def func(A: T.Buffer[1, \"bool\"]):\n                if priors:\n                    A[0] = True\n\n            return func\n\n        else:\n            postulate = analyzer.canonical_simplify(postulate)\n\n            @T.prim_func\n            def func(A: T.Buffer[1, \"bool\"]):\n                if priors:\n                    A[0] = postulate\n\n            return func\n\n\nclass TestSuppressTransitivelyProvableCondition(BaseBeforeAfter):\n    transitively_prove_inequalities = False\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        if i < j and j < k:\n            A[0] = i < k\n\n    expected = before\n\n\nclass TestRewriteAsAndOfOrs(BaseBeforeAfter):\n    \"\"\"If enabled, rewrite boolean expressions into AND of OR\"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[3, \"bool\"]):\n        T.evaluate(A[0] or (A[1] and A[2]))\n\n    def expected(A: T.Buffer[3, \"bool\"]):\n        T.evaluate((A[0] or A[1]) and (A[0] or A[2]))\n\n\nclass TestSuppressRewriteAsAndOfOrs(BaseBeforeAfter):\n    \"\"\"Only rewrite into AND of OR when allowed\"\"\"\n\n    convert_boolean_to_and_of_ors = False\n\n    def before(A: T.Buffer[3, \"bool\"]):\n        T.evaluate(A[0] or (A[1] and A[2]))\n\n    expected = before\n\n\nclass TestRewriteAsAndOfOrsWithTopLevelAnd(BaseBeforeAfter):\n    \"\"\"The expression being rewritten may start with an AND\n\n    Like TestRewriteAsAndOfOrs, but with an AndNode as the outermost\n    booelan operator.  Even though it is primarily OR nodes that are\n    being rewritten, the call to SimplifyAsAndOfOrs should apply to\n    the outermost AndNode or OrNode in order to enable better\n    simplification.\n    \"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[4, \"bool\"]):\n        T.evaluate((A[0] or A[1]) and (A[1] or (A[0] and A[2] and A[3])))\n\n    def expected(A: T.Buffer[4, \"bool\"]):\n        # If the simplification is applied to the OrNode, then a\n        # redundant `(A[1] or A[0])` would't be canceled out.  When\n        # applying SimplifyAsAndOfOrs to the top-level AndNode, the\n        # internal representation is `[[0,1], [1,0], [1,2], [1,3]]`, and\n        # the redundant `[1,0]` can be removed.\n        #\n        # If the simplification were only applied when encountering an\n        # OrNode, the internal representation would be `[[0,1]]` during\n        # the first call and `[[1,0], [1,2], [1,3]]` during the second\n        # call.  As a result, the `[0,1]` and `[1,0]` representations\n        # wouldn't occur within the same call, and the redundant `[1,0]`\n        # wouldn't be removed.\n        T.evaluate((A[0] or A[1]) and (A[1] or A[2]) and (A[1] or A[3]))\n\n\nclass TestRewriteAsAndOfOrsWithSimplificationBetweenGroups(BaseBeforeAfter):\n    \"\"\"Apply rewrite rules between OR groups that differ by a single element\n\n    The expression `(k==20 and k!=30)` could be rewritten into `(k==20)`.\n    However, by default these two terms must appear as part of an explict part\n    of the simplified expression.  The AndOfOr simplification checks for\n    rewrite patterns of the form `(A or B) and (A or C)`, where `(B and C)` can\n    simplify to a single expression `D`.  These can be rewritten to `(A or D)`.\n    \"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (i == 0 or j == 10 or k == 20) and (i == 0 or j == 10 or k != 30)\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = i == 0 or j == 10 or k == 20\n\n\nclass TestRewriteAsAndOfOrsWithSimplificationBetweenReorderedGroups(BaseBeforeAfter):\n    \"\"\"Rewrite rules between OR groups do not depend on order\n\n    Like TestRewriteAsAndOfOrsWithSimplificationBetweenGroups, but the groups\n    are ordered differently.  If this removes a group entirely, the result is\n    ordered according to the first group in the expression.\n    \"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (i == 0 or j == 10 or k == 20) and (j == 10 or k != 30 or i == 0)\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = i == 0 or j == 10 or k == 20\n\n\nclass TestRewriteAsAndOfOrUsingSimplificationAcrossAnd(BaseBeforeAfter):\n    \"\"\"Apply AndNode rewrites to non-adjacent expressions\n\n    The RewriteSimplifier rules only check for simplifications between\n    left/right branches of an And/Or node.  Simplifications that would require\n    rearranging components in a chain of And/Or nodes are not performed.\n    \"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (k == 20) and ((i == 0 or j == 10) and (k != 30))\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (k == 20) and (i == 0 or j == 10)\n\n\nclass TestRewriteAsAndOfOrUsingSimplificationWithinOr(BaseBeforeAfter):\n    \"\"\"Rewrite rules between OR groups do not depend on order\n\n    The RewriteSimplifier rules only check for simplifications between\n    left/right branches of an And/Or node.  Simplifications that would require\n    rearranging components in a chain of And/Or nodes are not performed.\n\n    This test validates that `(i == 20) or (i != 30)` can be rewritten to\n    `(i != 30)`, even when there's an intervening clause between the\n    clauses being simplified.\n    \"\"\"\n\n    convert_boolean_to_and_of_ors = True\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (i == 20) or (j == 0) or (i != 30)\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32, k: T.int32):\n        A[0] = (i != 30) or (j == 0)\n\n\nclass TestConditionalFloorMod(BaseBeforeAfter):\n    \"\"\"A regression test for negative floormod denominator\n\n    Previously, simplifying this function could throw an error.  First, the\n    `canonical_simplify` would rewrite `floormod(0-i,2)` to the equivalent\n    `floormod(i,-2)`.  Then, the rewrite_simplifier would enter a\n    constrained context in which `floormod(i,-2)==1`.  Passing this\n    expression to `ModularSet::EnterConstraint`, which previously did not\n    support a negative value for the second argument, threw an error.\n\n    The analogous failure mode never occurred for `truncmod`, because\n    `truncmod(0-i,2)` would be canonicalized to `truncmod(i, -2) * -1`, and\n    the pattern matching in `ModularSet` didn't recognize the constant\n    factor.\n\n    This failure mode was resolved by supporting negative arguments in\n    `ModularSet`, using the same sign convention as is used by\n    `canonical_simplify`.\n    \"\"\"\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32):\n        if T.floormod(0 - i, 2) == 0:\n            A[0] = T.floormod(i, 2) == 0\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32):\n        if T.floormod(i, -2) == 0:\n            A[0] = True\n\n\nclass TestSimplifyRHSOfBooleanAndUsingLHS(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts.\n\n    In `A and B`, the result of `B` only matters when `A` is\n    true, and can be simplified under that context.  This test\n    simplifies `n < 10` under the assumption that `n < 5`.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 5 and n < 10\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 5\n\n\nclass TestSimplifyLHSOfBooleanAndUsingRHS(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts for their arguments.\n\n    Like TestSimplifyRHSOfBooleanAndUsingLHS, but using the RHS to\n    simplify the LHS.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 10 and n < 5\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 5\n\n\nclass TestSimplifyRHSOfBooleanOrUsingLHS(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts.\n\n    In `A or B`, the result of `B` only matters when `A` is false, so\n    `B` can be simplified under the assumption that `A` is false.\n    This test simplifies `n < 5` under the assumption that `!(n < 10)`\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 10 or n < 5\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 10\n\n\nclass TestSimplifyLHSOfBooleanOrUsingRHS(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts for their arguments.\n\n    Like TestSimplifyRHSOfBooleanOrUsingLHS, but using the RHS to\n    simplify the LHS.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 5 or n < 10\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32):\n        A[0] = n < 10\n\n\nclass TestSimplifyRHSOfBooleanAndUsingLHSWithoutConst(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts.\n\n    Like TestSimplifyRHSOfBooleanAndUsingLHS, but with variables in\n    the conditions, preventing ConstIntBoundAnalyzer from handling it.\n    This proof requires the extension to transitively prove\n    inequalities.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n    transitively_prove_inequalities = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 5 and n < m + 10\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 5\n\n\nclass TestSimplifyLHSOfBooleanAndUsingRHSWithoutConst(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts for their arguments.\n\n    Like TestSimplifyLHSOfBooleanAndUsingRHS, but with variables in\n    the conditions, preventing ConstIntBoundAnalyzer from handling it.\n    This proof requires the extension to transitively prove\n    inequalities.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n    transitively_prove_inequalities = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 10 and n < m + 5\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 5\n\n\nclass TestSimplifyRHSOfBooleanOrUsingLHSWithoutConst(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts.\n\n    Like TestSimplifyRHSOfBooleanOrUsingLHS, but with variables in the\n    conditions, preventing ConstIntBoundAnalyzer from handling it.\n    This proof requires the extension to transitively prove\n    inequalities.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n    transitively_prove_inequalities = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 10 or n < m + 5\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 10\n\n\nclass TestSimplifyLHSOfBooleanOrUsingRHSWithoutConst(BaseBeforeAfter):\n    \"\"\"Boolean expressions can introduce contexts for their arguments.\n\n    Like TestSimplifyLHSOfBooleanOrUsingRHS, but with variables in the\n    conditions, preventing ConstIntBoundAnalyzer from handling it.\n    This proof requires the extension to transitively prove\n    inequalities.\n    \"\"\"\n\n    apply_constraints_to_boolean_branches = True\n    transitively_prove_inequalities = True\n\n    def before(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 5 or n < m + 10\n\n    def expected(A: T.Buffer[1, \"bool\"], n: T.int32, m: T.int32):\n        A[0] = n < m + 10\n\n\nclass TestProvableConditionWithOffset(BaseBeforeAfter):\n    \"\"\"Use scoped-constraint to prove inequalities\"\"\"\n\n    transitively_prove_inequalities = False\n\n    def before(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32):\n        if i < j:\n            A[0] = i < j + 1\n\n    def expected(A: T.Buffer[1, \"bool\"], i: T.int32, j: T.int32):\n        if i < j:\n            A[0] = True\n\n\nclass TestMostRestrictiveConditional(BaseBeforeAfter):\n    \"\"\"Preferentially prove part of a compound conditional.\n\n    Even if we cannot prove a conditional as true or false on its own,\n    proving that a conditional must satisfy a stronger condition may\n    allow for later rewrites.  For example, if it is known that `a <= b`,\n    then `a >= b` cannot be proven, but can be reduced to `a == b`.\n    \"\"\"\n\n    i, j, k = [tvm.tir.Var(name, \"int32\") for name in \"ijk\"]\n    tir_int = tvm.tir.IntImm(\"int32\", 0)\n\n    test_case = tvm.testing.parameter(\n        (i <= tir_int, tir_int <= i, i == tir_int),\n        (i <= tir_int, i != tir_int, i < tir_int),\n        (i != tir_int, i <= tir_int, i < tir_int),\n        (i != tir_int, tir_int <= i, tir_int < i),\n        (i <= j, j <= i, j == i),\n        (i <= j, i != j, i < j),\n        (i != j, i <= j, i < j),\n        (i != j, j <= i, j < i),\n    )\n\n    @tvm.testing.fixture\n    def before(self, test_case):\n        priors, expr_before, _ = test_case\n\n        @T.prim_func\n        def func(A: T.Buffer[1, \"bool\"]):\n            if priors:\n                A[0] = expr_before\n\n        return func\n\n    @tvm.testing.fixture\n    def expected(self, test_case):\n        priors, _, expr_after = test_case\n\n        @T.prim_func\n        def func(A: T.Buffer[1, \"bool\"]):\n            if priors:\n                A[0] = expr_after\n\n        return func\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_split_host_device.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nimport tvm.testing\n\n\n@tvm.testing.requires_cuda\ndef test_split_host_device_func_attr():\n    m = te.size_var(\"m\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    xo, xi = s[A2].split(A2.op.axis[0], factor=8)\n    s[A2].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[A1].compute_at(s[A2], xo)\n    s[A1].set_scope(\"shared\")\n\n    mod = tvm.lower(s, [A, A2], name=\"f\")\n\n    cuda_target = tvm.target.Target(\"cuda\")\n    mod = tvm.tir.transform.Apply(\n        lambda f: f.with_attr({\"global_symbol\": \"test\", \"target\": cuda_target})\n    )(mod)\n    fdevice = tvm.tir.transform.SplitHostDevice()(mod)[\"test_kernel0\"]\n\n    assert fdevice.attrs[\"global_symbol\"] == \"test_kernel0\"\n    assert fdevice.attrs[\"calling_conv\"].value == 2\n    assert fdevice.attrs[\"target\"] == cuda_target\n    assert fdevice.attrs[\"tir.is_global_func\"].value\n\n\nif __name__ == \"__main__\":\n    test_split_host_device_func_attr()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_storage_flatten.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\nfrom tvm.script import tir as T\nfrom tvm.relay import GlobalVar\n\n\ndef test_flatten2():\n    m = te.size_var(\"m\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    xo, xi = s[A2].split(A2.op.axis[0], 8)\n    s[A1].compute_at(s[A2], xo)\n    Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name=\"A\")\n    A2b = tvm.tir.decl_buffer(A2.shape, A2.dtype, name=\"A2\")\n\n    mod = schedule_to_module(s, [Ab, A2b], binds={A: Ab, A2: A2b})\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n\ndef test_flatten_prefetch():\n    A = te.placeholder((25, 100, 4), name=\"A\")\n    _A = tvm.tir.decl_buffer(A.shape, A.dtype, name=\"A\")\n    i = te.size_var(\"i\")\n    j = te.size_var(\"j\")\n    region = [tvm.ir.Range.from_min_extent(i[0], i[1]) for i in [(i, 2), (j, 8), (0, 4)]]\n    stmt = tvm.tir.Prefetch(_A, region)\n\n    func = tvm.te.schedule.SchedulePostProcToPrimFunc([_A], stmt, {A: _A})\n\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.transform.Sequential(\n        [tvm.tir.transform.StorageFlatten(64), tvm.tir.transform.Simplify()]\n    )(mod)\n    stmt = mod[\"main\"].body\n    assert stmt.extent.value == 2\n    assert isinstance(stmt.body, tvm.tir.For)\n    assert stmt.body.extent.value == 2\n\n    def assert_flat_loads(stmt):\n        if isinstance(stmt, tvm.tir.BufferLoad):\n            assert len(stmt.indices) == 1, \"All prefetch indices should be flattened\"\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, assert_flat_loads)\n\n\ndef test_flatten_storage_align():\n    m = 8\n    l = 16\n    A = te.placeholder((m, l), name=\"A\")\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    s[A1].storage_align(A1.op.axis[0], 2, 1)\n\n    mod = schedule_to_module(s, [A, A2])\n    mod = tvm.transform.Sequential(\n        [tvm.tir.transform.StorageFlatten(64), tvm.tir.transform.Simplify()]\n    )(mod)\n\n    stmt = mod[\"main\"].body\n    assert stmt.extents[0].value == 17 * 8\n\n\ndef test_flatten_double_buffer():\n    @tvm.script.ir_module\n    class ModFromScript:\n        @T.prim_func\n        def main(A_param: T.handle, C_param: T.handle):\n            A = T.match_buffer(A_param, (400,), \"float32\", strides=[1])\n            C = T.match_buffer(C_param, (4,), \"float32\", strides=[1])\n            T.func_attr({\"from_legacy_te_schedule\": True})\n            threadIdx_x = T.env_thread(\"threadIdx.x\")\n            T.launch_thread(threadIdx_x, 1)\n            for i in T.serial(0, 100):\n                B = T.decl_buffer([4], \"float32\", scope=\"shared\")\n                with T.attr(B.data, \"double_buffer_scope\", 1):\n                    for j in T.serial(0, 4):\n                        B[j] = A[4 * i + j]\n\n                for j in T.serial(0, 4):\n                    C[j] = B[j] + 1.0\n\n    mod = ModFromScript\n\n    with tvm.transform.PassContext(config={\"tir.InjectDoubleBuffer\": {\"split_loop\": 2}}):\n        mod = tvm.transform.Sequential(\n            [\n                tvm.tir.transform.StorageFlatten(64),\n                tvm.tir.transform.InjectDoubleBuffer(),\n                tvm.tir.transform.Simplify(),\n            ]\n        )(mod)\n\n    stmt = mod[\"main\"].body\n    assert isinstance(stmt.body, tvm.tir.Allocate)\n    assert list(stmt.body.extents) == [8]\n\n    mod = tvm.tir.transform.ThreadSync(\"shared\")(mod)\n    f = mod[\"main\"]\n\n    count = [0]\n\n    def count_sync(op):\n        if isinstance(op, tvm.tir.Call) and op.op.same_as(tvm.ir.Op.get(\"tir.tvm_storage_sync\")):\n            count[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(f.body, count_sync)\n    assert count[0] == 4\n\n\ndef test_flatten_let_buffer():\n    @tvm.script.ir_module\n    class module:\n        @T.prim_func\n        def main():\n            T.func_attr({\"from_legacy_te_schedule\": True})\n\n            # If a pointer defined using a LetStmt,\n            A_data: T.Ptr[T.int32] = T.call_extern(\"dummy_extern_function\", dtype=\"handle\")\n\n            # and a buffer is backed by that pointer,\n            A = T.decl_buffer([1], dtype=\"float32\", data=A_data)\n            T.evaluate(A[0])\n\n    # then the call to StorageFlatten would result in an exception\n    # being thrown.\n    tvm.tir.transform.StorageFlatten(64)(module)\n\n\n@T.prim_func\ndef tir_func(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [2, 2])\n    B = T.match_buffer(a, [2, 2])\n    A[0, 1] = B[1, 1]\n\n\ndef test_flatten_tir():\n    orig_mod = tvm.IRModule({GlobalVar(\"main\"): tir_func})\n    mod = tvm.tir.transform.StorageFlatten(64)(orig_mod)\n    tvm.ir.assert_structural_equal(\n        orig_mod, mod\n    )  # StorageFlatten should do nothing to TIR functions\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_storage_rewrite.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.driver.build_module import schedule_to_module\nfrom tvm.script import tir as T\n\n\ndef test_storage_share():\n    m = te.var(\"m\")\n    l = te.var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n    num_stage = 5\n    B = A\n    for t in range(num_stage):\n        B = te.compute((m, l), lambda i, j: B[i, j] + (t + 1), name=\"A%d\" % t)\n\n    s = te.create_schedule(B.op)\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    # verify only have one allocations.\n    # verify inplace folding works\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 1\n\n\ndef register_mem(scope_tb, max_bits):\n    # Register mem\n    @tvm.register_func(\"tvm.info.mem.%s\" % scope_tb)\n    def mem_info_inp_buffer():\n        return tvm.ir.make_node(\n            \"MemoryInfo\", unit_bits=16, max_simd_bits=32, max_num_bits=max_bits, head_address=None\n        )\n\n\ndef test_alloc_seq():\n    scope_tb = \"local.L0A\"\n    max_bits = 1024 * 1024 * 1024\n\n    register_mem(scope_tb, max_bits)\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"float32\", 200, name=\"A\", scope=scope_tb)\n            A[j] = 1.2\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"float32\", 200, name=\"B\", scope=scope_tb)\n            A[j] = 1.3\n\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"].body\n\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n            assert n.extents[0].value == 200\n\n    tvm.tir.stmt_functor.post_order_visit(body, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_alloc_different_dtypes():\n    def stmt_generater(dtype_list, length):\n        ib = tvm.tir.ir_builder.create()\n        base_dtype = dtype_list[0]\n        global_a = te.placeholder((length,), name=\"global_a\", dtype=base_dtype)\n        assert len(dtype_list) == 4\n        with ib.for_range(0, length, name=\"j\") as j:\n            dtype = dtype_list[0]\n            A = ib.allocate(dtype, length, name=\"A\", scope=\"local.L0A\")\n            A[j] = tvm.tir.const(1, dtype=dtype)\n        with ib.for_range(0, length, name=\"j\") as j:\n            dtype = dtype_list[1]\n            B = ib.allocate(dtype, length, name=\"B\", scope=\"local.L0A\")\n            B[j] = tvm.tir.const(1, dtype=dtype)\n        with ib.for_range(0, length, name=\"j\") as j:\n            dtype = dtype_list[2]\n            C = ib.allocate(dtype, length, name=\"C\", scope=\"local.L0A\")\n            C[j] = tvm.tir.const(1, dtype=dtype)\n        with ib.for_range(0, length, name=\"j\") as j:\n            dtype = dtype_list[3]\n            D = ib.allocate(dtype, length, name=\"D\", scope=\"local.L0A\")\n            D[j] = tvm.tir.const(1, dtype=dtype)\n        with ib.for_range(0, length, name=\"j\") as j:\n            dtype = \"int8\"\n            E = ib.allocate(dtype, length, name=\"E\", scope=\"local.L0A\")\n            E[j] = A[j].astype(dtype) + B[j].astype(dtype) + C[j].astype(dtype) + D[j].astype(dtype)\n        return ib.get()\n\n    def dtype_bit_len(dtype):\n        index = 0\n        for i in dtype:\n            if i.isdigit():\n                break\n            index += 1\n        return int(dtype[index:])\n\n    def offset_generater(dtype_list, length):\n        dtype_len_list = [dtype_bit_len(i) for i in dtype_list]\n        base_len = dtype_len_list[0]\n        return sum([i * length / base_len for i in dtype_len_list])\n\n    def dtype_test(dtype_list, length):\n        def verify(n):\n            if isinstance(n, tvm.tir.Allocate):\n                assert n.extents[0].value == offset\n\n        body = stmt_generater(dtype_list, length)\n        offset = offset_generater(dtype_list, length)\n\n        mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], body))\n        body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"].body\n\n        tvm.tir.stmt_functor.post_order_visit(body, verify)\n\n    length = 1024\n    dtype_list = [\"float16\", \"int32\", \"uint16\", \"int8\"]\n    dtype_test(dtype_list, length)\n\n    dtype_list = [\"float32\", \"int32\", \"uint16\", \"int8\"]\n    dtype_test(dtype_list, length)\n\n    dtype_list = [\"float64\", \"int32\", \"uint16\", \"int8\"]\n    dtype_test(dtype_list, length)\n\n    dtype_list = [\"int8\", \"int32\", \"uint16\", \"uint8\"]\n    dtype_test(dtype_list, length)\n\n\ndef test_inplace_rule():\n    m = 10\n    A = te.placeholder((m,), name=\"A\")\n    A0 = te.compute((m,), lambda i: A[i], name=\"A0\")\n    A1 = te.compute((m,), lambda i: A[i] + 1, name=\"A1\")\n    AA = te.compute((m,), lambda i: A0[i] + A1[i] + A1[0], name=\"AA\")\n    B = te.compute((m,), lambda i: AA[i] + 1, name=\"B\")\n    s = te.create_schedule(B.op)\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    # verify only have one allocations.\n    # verify inplace folding works\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 2\n\n\ndef test_storage_combine():\n    n = 8\n    A = te.placeholder((4,), name=\"A\")\n    num_stage = 5\n    B = A\n    stages = []\n    for t in range(num_stage):\n        B = te.compute((n,), lambda i: B[i] + B[0] + (t + 1), name=\"A%d\" % t)\n        stages.append(B)\n\n    s = te.create_schedule(B.op)\n    for S in stages[:-1]:\n        s[S].set_scope(\"global:tag\")\n\n    mod = schedule_to_module(s, [A, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n            assert n.extents[0].value == 16\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_storage_combine_with_vectorization():\n    n = 1024\n    A = te.placeholder((n,), name=\"A\")\n    B = te.placeholder((n,), name=\"B\")\n    C = te.compute((n,), lambda i: A[i] + B[i], name=\"C\")\n    s = te.create_schedule(C.op)\n    AA = s.cache_read(A, \"global:tag\", readers=[C])\n    BB = s.cache_read(B, \"global:tag\", readers=[C])\n    CC = s.cache_write(C, \"global:tag\")\n    s[CC].vectorize(s[CC].op.axis[0])\n    mod = schedule_to_module(s, [A, B, C])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n    mod = tvm.tir.transform.VectorizeLoop()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    stmt = mod[\"main\"].body\n    num_alloc = [0]\n\n    def verify(v):\n        # find add op\n        if (\n            isinstance(v, tvm.tir.Add)\n            and isinstance(v.a, tvm.tir.Load)\n            and isinstance(v.b, tvm.tir.Load)\n        ):\n            lhs_ramp = v.a.index\n            rhs_ramp = v.b.index\n            # these two ramp load should not overlap\n            assert lhs_ramp.lanes == n\n            assert rhs_ramp.lanes == n\n            assert lhs_ramp.base >= rhs_ramp.base + n or rhs_ramp.base >= lhs_ramp.base + n\n        elif isinstance(v, tvm.tir.Allocate):\n            num_alloc[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_storage_share_gpu():\n    m = te.var(\"m\")\n    A = [te.placeholder((m), name=\"A\")]\n    num_stage = 5\n    for t in range(num_stage):\n        A.append(te.compute((m,), lambda i: A[-1][i] + (t + 1), name=\"A%d_s\" % t))\n        A.append(te.compute((m,), lambda i: A[-1][i], name=\"A%d\" % t))\n    s = te.create_schedule(A[-1].op)\n    for t in range(num_stage):\n        x = A[2 * t + 2].op.axis[0]\n        bx, tx = s[A[2 * t + 2]].split(x, factor=32)\n        s[A[2 * t + 2]].bind(bx, te.thread_axis(\"blockIdx.x\"))\n        s[A[2 * t + 2]].bind(tx, te.thread_axis(\"threadIdx.x\"))\n        s[A[2 * t + 1]].compute_at(s[A[2 * t + 2]], tx)\n        s[A[2 * t + 1]].set_scope(\"shared\")\n\n    mod = schedule_to_module(s, [A[0], A[-1]])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    alloc_stats = {\"global\": 0, \"shared\": 0}\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            scope = n.buffer_var.type_annotation.storage_scope\n            alloc_stats[scope] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert alloc_stats[\"global\"] == 2\n    assert alloc_stats[\"shared\"] == num_stage\n\n\ndef test_parallel_alloc():\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\", kind=\"parallel\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n            A[j] = A[j] + 2\n\n    body = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"]\n\n    assert isinstance(body.body.body, tvm.tir.Allocate)\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"t\") as i:\n        ib.scope_attr(\n            tvm.tir.const(1, \"int32\"), \"pragma_scope\", tvm.tir.StringImm(\"parallel_launch_point\")\n        )\n        with ib.for_range(0, n, name=\"i\", kind=\"parallel\") as i:\n            with ib.for_range(0, 10, name=\"j\") as j:\n                A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n                A[j] = A[j] + 2\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"]\n\n    assert isinstance(body.body.body.body.body, tvm.tir.Allocate)\n\n\ndef test_while_alloc():\n    def get_mod(kind=\"serial\"):\n        ib = tvm.tir.ir_builder.create()\n        n = te.var(\"n\")\n        with ib.for_range(0, n, name=\"i\", kind=kind) as i:\n            j = ib.allocate(\"int32\", 1, name=\"j\", scope=\"global\")\n            j[0] = 0\n            with ib.while_loop(j[0] < 10):\n                A = ib.allocate(\"float32\", n, name=\"A\", scope=\"global\")\n                A[j[0]] = A[j[0]] + 2\n                j[0] += j[0] + 1\n\n        body = ib.get()\n        return tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n\n    mod = get_mod(kind=\"parallel\")\n    # parallel (i, 0, n) {\n    #   allocate j[int32 * 1]\n    #   j[0] = 0\n    #   while((j[0] < 10)){\n    #     // attr [A] storage_scope = \"global\"\n    #     allocate A[float32 * n]\n    #     A[j[0]] = (A[j[0]] + 2f)\n    #     j[0] = (j[0] + (j[0] + 1))\n    #   }\n    # }\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"]\n    # parallel (i, 0, n) {\n    #   allocate j[int32 * 1]\n    #   allocate A[float32 * n]\n    #   j[0] = 0\n    #   while((j[0] < 10)){\n    #     A[j[0]] = (A[j[0]] + 2f)\n    #     j[0] = (j[0] + (j[0] + 1))\n    #   }\n    # }\n    assert isinstance(body.body.body, tvm.tir.Allocate)  # j\n    assert isinstance(body.body.body.body, tvm.tir.Allocate)  # A\n\n    mod = get_mod(kind=\"serial\")\n    # for (i, 0, n) {\n    #   allocate j[int32 * 1]\n    #   j[0] = 0\n    #   while((j[0] < 10)){\n    #     // attr [A] storage_scope = \"global\"\n    #     allocate A[float32 * n]\n    #     A[j[0]] = (A[j[0]] + 2f)\n    #     j[0] = (j[0] + (j[0] + 1))\n    #   }\n    # }\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"]\n    # allocate j[int32 * 1]\n    # allocate A[float32 * n]\n    # for (i, 0, n) {\n    #   j[0] = 0\n    #   while((j[0] < 10)){\n    #     A[j[0]] = (A[j[0]] + 2f)\n    #     j[0] = (j[0] + (j[0] + 1))\n    #   }\n    # }\n    assert isinstance(body.body, tvm.tir.Allocate)  # j\n    assert isinstance(body.body.body, tvm.tir.Allocate)  # A\n\n\ndef test_inplace_rule2(scope_tb=\"local_TB2\", max_bits=1024 * 1024 * 1024):\n    # Test Buffer\n    register_mem(scope_tb, max_bits)\n    m = 10\n    A = te.placeholder((m,), name=\"A\")\n    C = te.placeholder((m,), name=\"C\")\n    D = te.placeholder((m,), name=\"D\")\n    A0 = te.compute((m,), lambda i: A[i] + C[i], name=\"A0\")\n    A1 = te.compute((m,), lambda i: D[i] * D[i], name=\"A1\")\n    A2 = te.compute((m,), lambda i: A0[i] + A1[i], name=\"A2\")\n    B = te.compute((m,), lambda i: A2[i], name=\"B\")\n    s = te.create_schedule(B.op)\n    A0L = s.cache_read(A0, scope_tb, [A2])\n    A1L = s.cache_read(A1, scope_tb, [A2])\n    A2L = s.cache_read(A2, scope_tb, [B])\n    mod = schedule_to_module(s, [A, B, C, D])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    # verify only have one allocations.\n    # verify inplace folding works\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n    assert num_alloc[0] == 2\n\n\ndef test_exceed_mem():\n    max_bits = 639\n    # The critical max_num_bits is between 639 and 640\n    loc = -1\n    try:\n        test_inplace_rule2(\"local_TEM\", max_bits)\n    except Exception as e:\n        estr = str(e)\n        loc = estr.find(\"Allocation exceed bound of memory\")\n        assert loc != -1\n\n\ndef test_inplace_rule3():\n    # Test Buffer\n    scope_tb = \"local_TB3\"\n    max_bits = 1024 * 1024 * 1024\n\n    register_mem(scope_tb, max_bits)\n    m = 10\n    B0 = te.placeholder((m,), name=\"B0\")\n    B1 = te.placeholder((m,), name=\"B1\")\n    B2 = te.placeholder((m,), name=\"B2\")\n    B3 = te.placeholder((m,), name=\"B3\")\n    B4 = te.placeholder((m,), name=\"B4\")\n    B5 = te.placeholder((m,), name=\"B5\")\n\n    B6 = te.compute((m,), lambda i: B1[i] * B5[i], name=\"B6\")\n    B7 = te.compute((m,), lambda i: B2[i] * B4[i], name=\"B7\")\n    B8 = te.compute((m,), lambda i: B6[i] - B7[i], name=\"B8\")\n\n    B9 = te.compute((m,), lambda i: B2[i] * B3[i], name=\"B9\")\n    B10 = te.compute((m,), lambda i: B0[i] * B5[i], name=\"B10\")\n    B11 = te.compute((m,), lambda i: B9[i] - B10[i], name=\"B11\")\n\n    B12 = te.compute((m,), lambda i: B0[i] * B4[i], name=\"B12\")\n    B13 = te.compute((m,), lambda i: B1[i] * B3[i], name=\"B13\")\n    B14 = te.compute((m,), lambda i: B12[i] - B13[i], name=\"B14\")\n\n    B = te.compute((m,), lambda i: B8[i] * B11[i] + B14[i], name=\"B\")\n    s = te.create_schedule(B.op)\n\n    B1L = s.cache_read(B1, scope_tb, [B6, B13])\n    B5L = s.cache_read(B5, scope_tb, [B6, B10])\n    B2L = s.cache_read(B2, scope_tb, [B7, B9])\n    B4L = s.cache_read(B4, scope_tb, [B7, B12])\n    B3L = s.cache_read(B3, scope_tb, [B9, B13])\n    B0L = s.cache_read(B0, scope_tb, [B10, B12])\n\n    B8L = s.cache_write(B8, scope_tb)\n    B11L = s.cache_write(B11, scope_tb)\n    B14L = s.cache_write(B14, scope_tb)\n    B6L = s.cache_write(B6, scope_tb)\n    B7L = s.cache_write(B7, scope_tb)\n    B9L = s.cache_write(B9, scope_tb)\n    B10L = s.cache_write(B10, scope_tb)\n    B12L = s.cache_write(B12, scope_tb)\n    B13L = s.cache_write(B13, scope_tb)\n\n    s[B12].compute_inline()\n    s[B13].compute_inline()\n    s[B8].compute_inline()\n    s[B11].compute_inline()\n    s[B14].compute_inline()\n    s[B6].compute_inline()\n    s[B7].compute_inline()\n    s[B9].compute_inline()\n    s[B10].compute_inline()\n\n    s = s.normalize()\n    mod = schedule_to_module(s, [B0, B1, B2, B3, B4, B5, B])\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    mod = tvm.tir.transform.Simplify()(mod)\n    mod = tvm.tir.transform.StorageRewrite()(mod)\n    stmt = mod[\"main\"].body\n\n    # verify only have one allocations.\n    # verify inplace folding works\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            assert n.extents[0].value == 70\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n\n\ndef test_alloc_seq_type():\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"float32\", 200, name=\"A\", scope=\"local.L0A\")\n            A1 = ib.allocate(\"float32\", 200, name=\"A1\", scope=\"local.L0A\")\n            A[j] = 1.2\n            A1[j] = 1.3\n            B = ib.allocate(\"int16\", 200, name=\"B\", scope=\"local.L0A\")\n            B[j] = tvm.tir.const(1, \"int16\")\n            C = ib.allocate(\"int16\", 200, name=\"C\", scope=\"local.L0A\")\n            C[j] = tvm.tir.const(1, \"int16\")\n            D = ib.allocate(\"int16\", 200, name=\"D\", scope=\"local.L0A\")\n            D[j] = B[j] + C[j]\n            A2 = ib.allocate(\"float32\", 200, name=\"A2\", scope=\"local.L0A\")\n            A2[j] = A[j]\n\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"].body\n\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n            assert n.extents[0].value == 500\n\n    tvm.tir.stmt_functor.post_order_visit(body, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_alloc_seq_type2():\n    scope_tb = \"local.L0A2\"\n    max_bits = 1024 * 1024 * 1024\n\n    register_mem(scope_tb, max_bits)\n\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"float32\", 200, name=\"A\", scope=scope_tb)\n            A[j] = 1.2\n        with ib.for_range(0, 20, name=\"j\") as j:\n            B = ib.allocate(\"int16\", 400, name=\"B\", scope=scope_tb)\n            B[j] = tvm.tir.const(1, \"int16\")\n        with ib.for_range(0, 10, name=\"j\") as j:\n            C = ib.allocate(\"float32\", 200, name=\"C\", scope=scope_tb)\n            C[j] = 1.2\n\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"].body\n\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n            assert n.extents[0].value == 200\n\n    tvm.tir.stmt_functor.post_order_visit(body, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_reuse_small_buffer():\n    ib = tvm.tir.ir_builder.create()\n    n = te.var(\"n\")\n    with ib.for_range(0, n, name=\"i\") as i:\n        with ib.for_range(0, 10, name=\"j\") as j:\n            A = ib.allocate(\"int16\", 200, name=\"A\", scope=\"local.L0A\")\n            A[j] = tvm.tir.const(1, \"int16\")\n            B = ib.allocate(\"int16\", 200, name=\"B\", scope=\"local.L0A\")\n            B[j] = tvm.tir.const(1, \"int16\")\n            B1 = ib.allocate(\"int16\", 200, name=\"B1\", scope=\"local.L0A\")\n            B1[j] = A[j] + B[j]\n            C = ib.allocate(\"int16\", 400, name=\"C\", scope=\"local.L0A\")\n            C[j] = tvm.tir.const(1, \"int16\")\n            D = ib.allocate(\"int16\", 400, name=\"D\", scope=\"local.L0A\")\n            D[j] = tvm.tir.const(1, \"int16\")\n            E = ib.allocate(\"int16\", 400, name=\"E\", scope=\"local.L0A\")\n            E[j] = C[j]\n\n    body = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body))\n    body = tvm.tir.transform.StorageRewrite()(mod)[\"main\"].body\n\n    num_alloc = [0]\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            num_alloc[0] += 1\n            assert n.extents[0].value == 800\n\n    tvm.tir.stmt_functor.post_order_visit(body, verify)\n    assert num_alloc[0] == 1\n\n\ndef test_replace_dataflow():\n    shape = (255,)\n    A = te.placeholder(shape, name=\"A\")\n    B = te.compute(shape, lambda i: A[i] + A[i], name=\"B\")\n    C = te.compute(shape, lambda i: A[i] + B[i], name=\"C\")\n    D = te.compute(shape, lambda i: A[i] + C[i], name=\"D\")\n    E = te.compute(shape, lambda i: A[i] + D[i], name=\"E\")\n\n    s = te.create_schedule(E.op)\n    s.cache_read(A, \"local\", [B, C, D, E])\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n\n\ndef test_large_input():\n    @te.hybrid.script\n    def compute(a, b):\n        n = 16384\n        c = output_tensor((n, n), \"int32\")\n        for i in range(n):\n            for j in range(n):\n                c[i, j] = a[i, j] - b[i, j]\n        return c\n\n    n = 16384\n    shape = (n, n)\n    a = te.placeholder(shape, name=\"a\", dtype=\"int32\")\n    b = te.placeholder(shape, name=\"b\", dtype=\"int32\")\n    c = te.compute(shape, lambda i, j: compute(a, b)[i, j])\n    c = te.compute(shape, lambda i, j: 1 + c[i, j])\n    s = te.create_schedule(c.op)\n    stmt = tvm.lower(s, [a, b, c])[\"main\"].body\n\n    def verify(n):\n        if isinstance(n, tvm.tir.Allocate):\n            assert n.extents[0].value == 268435456\n\n    tvm.tir.stmt_functor.post_order_visit(stmt, verify)\n\n\ndef test_access_in_let_value():\n    @T.prim_func\n    def func(A: T.Buffer[(8,), \"float32\"]):\n        for i in range(8):\n            B_data = T.allocate((1,), \"float32\", \"global\")\n            B = T.buffer_decl(shape=[1], dtype=\"float32\", data=B_data)\n            B[0] = 3.14\n            x: T.float32 = T.exp(B[0], dtype=\"float32\")\n            A[i] = (x + 1.0) / (x - 1.0)\n\n    @T.prim_func\n    def func_rewritten(A: T.Buffer[(8,), \"float32\"]) -> None:\n        B_data = T.allocate((1,), \"float32\", \"global\")\n        B = T.buffer_decl(shape=[1], dtype=\"float32\", data=B_data)\n        for i in range(8):\n            B[0] = 3.14\n            x: T.float32 = T.exp(B[0], dtype=\"float32\")\n            A[i] = (x + 1.0) / (x - 1.0)\n\n    mod = tvm.tir.transform.StorageRewrite()(tvm.IRModule.from_expr(func))\n    tvm.ir.assert_structural_equal(mod[\"main\"], func_rewritten)\n\n\nclass BaseCompare(tvm.testing.CompareBeforeAfter):\n    transform = tvm.tir.transform.StorageRewrite()\n\n\nclass TestLetBufferRewrite(BaseCompare):\n    \"\"\"StorageRewrite replaces the bound var of backing allocations\n\n    If StorageRewrite replaces the backing variable of an array, such\n    as when vectorizing the storage type, the variable must be\n    replaced in the LetStmt that defines it.  Currently, StmtMutator\n    only visits usage of variables, and does not visit definitions of\n    variables, so the definition in a LetStmt must be explicitly\n    handled.\n    \"\"\"\n\n    def before() -> None:\n        A_data: T.Ptr[T.int32] = T.call_extern(\"dummy_func\", dtype=\"handle\")\n        A = T.buffer_decl([8], \"int32\", data=A_data)\n        A[0:8] = T.broadcast(42, 8)\n\n    def expected() -> None:\n        A_data: T.Ptr[T.int32x8] = T.call_extern(\"dummy_func\", dtype=\"handle\")\n        A = T.buffer_decl([1], \"int32x8\", data=A_data)\n        A[0] = T.broadcast(42, 8)\n\n\nclass TestRewriteInPlaceUseOfNonFlatBuffer(BaseCompare):\n    \"\"\"A non-flat buffer may be re-used for in-place operations\"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]):\n        B_data = T.allocate(\n            [16, 16],\n            dtype=\"float32\",\n            scope=\"global\",\n        )\n        B = T.buffer_decl(\n            [16, 16],\n            dtype=\"float32\",\n            axis_separators=[1],\n            data=B_data,\n        )\n        C_data = T.allocate(\n            [16, 16],\n            dtype=\"float32\",\n            scope=\"global\",\n        )\n        C = T.buffer_decl(\n            [16, 16],\n            dtype=\"float32\",\n            axis_separators=[1],\n            data=C_data,\n        )\n\n        for i, j in T.grid(16, 16):\n            B[i, j] = A[i, j]\n\n        for i, j in T.grid(16, 16):\n            C[i, j] = 2.0 * B[i, j]\n\n        for i, j in T.grid(16, 16):\n            D[i, j] = C[i, j]\n\n    def expected(A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]):\n        B_data = T.allocate(\n            [16, 16],\n            dtype=\"float32\",\n            scope=\"global\",\n        )\n        B = T.buffer_decl([16, 16], dtype=\"float32\", axis_separators=[1], data=B_data)\n        C = T.buffer_decl(\n            [16, 16],\n            dtype=\"float32\",\n            axis_separators=[1],\n            data=B.data,\n        )\n\n        for i, j in T.grid(16, 16):\n            B[i, j] = A[i, j]\n\n        for i, j in T.grid(16, 16):\n            C[i, j] = 2.0 * B[i, j]\n\n        for i, j in T.grid(16, 16):\n            D[i, j] = C[i, j]\n\n\nclass TestNoRewriteOfSharedNonFlatBuffer(BaseCompare):\n    \"\"\"In general, sharing of non-flat buffer isn't supported\n\n    The current packing algorithms in StorageRewrite assume a flat\n    memory space, and do not support packing of N-d buffers.  For\n    buffers with axis separators, normal buffer sharing should be\n    disabled.\n\n    Like TestRewriteInPlaceUseOfNonFlatBuffer, except that B and C do\n    not have matching shapes.\n    \"\"\"\n\n    def before(A: T.Buffer[(16, 16), \"float32\"], D: T.Buffer[(16, 16), \"float32\"]):\n        B_data = T.allocate(\n            [16, 16],\n            dtype=\"float32\",\n            scope=\"global\",\n        )\n        B = T.buffer_decl(\n            [16, 16],\n            dtype=\"float32\",\n            axis_separators=[1],\n            data=B_data,\n        )\n        C_data = T.allocate(\n            [20, 20],\n            dtype=\"float32\",\n            scope=\"global\",\n        )\n        C = T.buffer_decl(\n            [20, 20],\n            dtype=\"float32\",\n            axis_separators=[1],\n            data=C_data,\n        )\n\n        for i, j in T.grid(16, 16):\n            B[i, j] = A[i, j]\n\n        for i, j in T.grid(16, 16):\n            C[i, j] = 2.0 * B[i, j]\n\n        for i, j in T.grid(16, 16):\n            D[i, j] = C[i, j]\n\n    expected = before\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_thread_sync.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef run_passes(func: tvm.tir.PrimFunc):\n    mod = tvm.IRModule.from_expr(func)\n    mod = tvm.tir.transform.StorageFlatten(64)(mod)\n\n    cuda_target = tvm.target.Target(\"cuda\")\n\n    mod = tvm.tir.transform.Apply(\n        lambda f: f.with_attr({\"global_symbol\": \"test\", \"target\": cuda_target})\n    )(mod)\n\n    mod = tvm.tir.transform.SplitHostDevice()(mod)\n    return tvm.tir.transform.ThreadSync(\"shared\")(mod)\n\n\n@tvm.testing.requires_cuda\ndef test_thread_storage_sync():\n    m = te.size_var(\"m\")\n    l = te.size_var(\"l\")\n    A = te.placeholder((m, l), name=\"A\")\n\n    A1 = te.compute((m, l), lambda i, j: A[i, j], name=\"A1\")\n    A2 = te.compute((m, l), lambda i, j: A1[i, j] + 3, name=\"A2\")\n\n    s = te.create_schedule(A2.op)\n    xo, xi = s[A2].split(A2.op.axis[0], factor=8)\n    s[A2].bind(xo, te.thread_axis(\"blockIdx.x\"))\n    s[A1].compute_at(s[A2], xo)\n    s[A1].set_scope(\"shared\")\n\n    bounds = tvm.te.schedule.InferBound(s)\n    assert isinstance(bounds, tvm.container.Map)\n    stmt = tvm.te.schedule.ScheduleOps(s, bounds)\n\n    func = tvm.te.schedule.SchedulePostProcToPrimFunc([A, A2], stmt, None)\n    mod = run_passes(func)\n    f = mod[\"test_kernel0\"]\n    body_list = tvm.tir.stmt_list(f.body.body.body)\n    assert body_list[1].value.op.same_as(tvm.ir.Op.get(\"tir.tvm_storage_sync\"))\n\n\n@tvm.testing.requires_cuda\ndef test_sync_else_branch():\n    def ir(A, B):\n        ib = tvm.tir.ir_builder.create()\n        Aptr = ib.buffer_ptr(A)\n        Bptr = ib.buffer_ptr(B)\n\n        tx = te.thread_axis(\"threadIdx.x\")\n        ib.scope_attr(tx, \"thread_extent\", 1)\n\n        local = ib.allocate(A.dtype, (8,), name=\"buf_local\", scope=\"local\")\n        shared = ib.allocate(A.dtype, (8,), name=\"buf_shared\", scope=\"shared\")\n\n        with ib.for_range(0, 8) as i:\n            with ib.if_scope(Aptr[i] < 0):\n                local[i] = Aptr[i]\n            with ib.else_scope():\n                shared[i] = Aptr[i]\n\n        with ib.for_range(0, 8) as i:\n            with ib.if_scope(Aptr[i] < 0):\n                Bptr[i] = local[i]\n            with ib.else_scope():\n                Bptr[i] = shared[i]\n\n        return ib.get()\n\n    A = tvm.tir.decl_buffer((8,), \"float32\")\n    B = tvm.tir.decl_buffer((8,), \"float32\")\n    stmt = ir(A, B)\n    func = tvm.te.schedule.SchedulePostProcToPrimFunc([A, B], stmt, None)\n    mod = run_passes(func)\n    assert \"@tir.tvm_storage_sync\" in str(mod)\n\n\n@tvm.testing.requires_cuda\ndef test_sync_read_thread_id_independent_location():\n    @T.prim_func\n    def func(p0: T.Buffer[2, \"float32\"], p1: T.Buffer[2, \"float32\"]) -> None:\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        blockIdx_x = T.env_thread(\"blockIdx.x\")\n        T.preflattened_buffer(p0, [1, 2, 1, 1], dtype=\"float32\", data=p0.data)\n        result_local = T.alloc_buffer([1], dtype=\"float32\", scope=\"local\")\n        temp_shared = T.alloc_buffer([1], dtype=\"float32\", scope=\"shared\")\n        T.launch_thread(blockIdx_x, 8)\n        T.launch_thread(threadIdx_x, 4)\n        result_local[0] = T.float32(0)\n        if threadIdx_x < 1:\n            temp_shared[0] = p0[0]\n        result_local[0] = result_local[0] + temp_shared[0] * p1[0]\n        if threadIdx_x < 1:\n            temp_shared[0] = p0[1]\n        result_local[0] = result_local[0] + temp_shared[0] * p1[1]\n\n    mod = run_passes(func)\n    assert \"@tir.tvm_storage_sync\" in str(mod)\n\n\nif __name__ == \"__main__\":\n    test_thread_storage_sync()\n    test_sync_else_branch()\n    test_sync_read_thread_id_independent_location()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_unify_thread_binding.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport sys\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.script import tir as T\n\n\ndef _check(original, transformed):\n    mod = tvm.IRModule.from_expr(original)\n    mod = tvm.tir.transform.UnifyThreadBinding()(mod)\n    mod = tvm.tir.transform.Simplify()(mod)\n    tvm.ir.assert_structural_equal(mod[\"main\"], transformed, True)\n\n\ndef _check_fail(original):\n    mod = tvm.IRModule.from_expr(original)\n    with pytest.raises(ValueError):\n        tvm.tir.transform.UnifyThreadBinding()(mod)\n\n\n@T.prim_func\ndef element_wise_thread_x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for j0_0 in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[i, j0_0 * 32 + j0_1] = A[i, j0_0 * 32 + j0_1] * 2.0\n        for j1_0 in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[i, j1_0 * 32 + j1_1] = B[i, j1_0 * 32 + j1_1] + 1.0\n\n\n@T.prim_func\ndef unified_element_wise_thread_x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for blockIdx_x in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[blockIdx_x, threadIdx_x * 32 + j0_1] = (\n                        A[blockIdx_x, threadIdx_x * 32 + j0_1] * 2.0\n                    )\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[blockIdx_x, threadIdx_x * 32 + j1_1] = (\n                        B[blockIdx_x, threadIdx_x * 32 + j1_1] + 1.0\n                    )\n\n\n@T.prim_func\ndef element_wise_thread_x_different_dtype(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(128, 128), \"float32\"],\n) -> None:\n    for i in T.thread_binding(128, \"blockIdx.x\"):\n        for j0_0 in T.thread_binding(4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[i, j0_0 * 32 + j0_1] = A[i, j0_0 * 32 + j0_1] * 2.0\n        for j1_0 in T.thread_binding(T.int64(4), \"threadIdx.x\"):\n            for j1_1 in T.serial(T.int64(32)):\n                with T.block(\"\"):\n                    C[i, j1_0 * T.int64(32) + j1_1] = B[i, j1_0 * T.int64(32) + j1_1] + 1.0\n\n\n@T.prim_func\ndef unified_element_wise_thread_x_different_dtype(\n    A: T.Buffer[(128, 128), \"float32\"],\n    B: T.Buffer[(128, 128), \"float32\"],\n    C: T.Buffer[(128, 128), \"float32\"],\n) -> None:\n    for blockIdx_x in T.thread_binding(128, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[blockIdx_x, threadIdx_x * 32 + j0_1] = (\n                        A[blockIdx_x, threadIdx_x * 32 + j0_1] * 2.0\n                    )\n            for j1_1 in T.serial(T.int64(32)):\n                with T.block(\"\"):\n                    C[blockIdx_x, T.cast(threadIdx_x, \"int64\") * T.int64(32) + j1_1] = (\n                        B[blockIdx_x, T.cast(threadIdx_x, \"int64\") * T.int64(32) + j1_1] + 1.0\n                    )\n\n\n@T.prim_func\ndef element_wise_env_thread_x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    j1_0 = T.env_thread(\"threadIdx.x\")\n    j0_0 = T.env_thread(\"threadIdx.x\")\n    i = T.env_thread(\"blockIdx.x\")\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    T.launch_thread(i, 128)\n    T.launch_thread(j0_0, 4)\n    T.launch_thread(j1_0, 4)\n\n    for j0_1 in T.serial(0, 32):\n        with T.block(\"\"):\n            B[i, j0_0 * 32 + j0_1] = A[i, j0_0 * 32 + j0_1] * 2.0\n    for j1_1 in T.serial(0, 32):\n        with T.block(\"\"):\n            C[i, j1_0 * 32 + j1_1] = B[i, j1_0 * 32 + j1_1] + 1.0\n\n\n@T.prim_func\ndef unified_element_wise_env_thread_x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for blockIdx_x in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[blockIdx_x, threadIdx_x * 32 + j0_1] = (\n                        A[blockIdx_x, threadIdx_x * 32 + j0_1] * 2.0\n                    )\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[blockIdx_x, threadIdx_x * 32 + j1_1] = (\n                        B[blockIdx_x, threadIdx_x * 32 + j1_1] + 1.0\n                    )\n\n\n@T.prim_func\ndef element_wise_vthread_x(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    for i_0 in T.thread_binding(0, 2, \"vthread.x\"):\n        for i_1 in T.thread_binding(0, 64, \"threadIdx.x\"):\n            for j_0 in T.thread_binding(0, 2, \"vthread.x\"):\n                for j_1 in T.serial(0, 64):\n                    with T.block(\"\"):\n                        B[i_0 * 64 + i_1, j_0 * 64 + j_1] = A[i_0 * 64 + i_1, j_0 * 64 + j_1] * 2.0\n\n\n@T.prim_func\ndef unified_element_wise_vthread_x(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    for vthread_x in T.thread_binding(0, 2, \"vthread.x\"):\n        for threadIdx_x in T.thread_binding(0, 64, \"threadIdx.x\"):\n            for j_1 in T.serial(0, 64):\n                with T.block(\"\"):\n                    B[vthread_x * 64 + threadIdx_x, vthread_x * 64 + j_1] = (\n                        A[vthread_x * 64 + threadIdx_x, vthread_x * 64 + j_1] * 2.0\n                    )\n\n\n@T.prim_func\ndef element_wise_two_thread_x_in_same_kernel_not_equal(\n    a: T.handle, b: T.handle, c: T.handle\n) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 64])\n    for i in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for j0 in T.thread_binding(0, 128, \"threadIdx.x\"):\n            B[i, j0] = A[i, j0] * 2.0\n        for j1 in T.thread_binding(0, 64, \"threadIdx.x\"):\n            C[i, j1] = A[i, j1] + 1.0\n\n\n@T.prim_func\ndef element_wise_kernels_with_different_size(\n    a: T.handle, b: T.handle, c: T.handle, d: T.handle\n) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [256, 256])\n    D = T.match_buffer(d, [256, 256])\n    for i0 in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for j0 in T.thread_binding(0, 128, \"threadIdx.x\"):\n            B[i0, j0] = A[i0, j0] * 2.0\n    for i1 in T.thread_binding(0, 256, \"blockIdx.x\"):\n        for j1 in T.thread_binding(0, 256, \"threadIdx.x\"):\n            D[i1, j1] = C[i1, j1] + 1.0\n\n\n@T.prim_func\ndef unified_element_wise_kernels_with_different_size(\n    a: T.handle, b: T.handle, c: T.handle, d: T.handle\n) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [256, 256])\n    D = T.match_buffer(d, [256, 256])\n    for blockIdx_x in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(0, 128, \"threadIdx.x\"):\n            B[blockIdx_x, threadIdx_x] = A[blockIdx_x, threadIdx_x] * 2.0\n    for blockIdx_x in T.thread_binding(0, 256, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(0, 256, \"threadIdx.x\"):\n            D[blockIdx_x, threadIdx_x] = C[blockIdx_x, threadIdx_x] + 1.0\n\n\n@T.prim_func\ndef element_wise_implicit_block(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i in T.thread_binding(0, 128, \"threadIdx.y\"):\n        for j0_0 in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[i, j0_0 * 32 + j0_1] = A[i, j0_0 * 32 + j0_1] * 2.0\n        for j1_0 in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[i, j1_0 * 32 + j1_1] = B[i, j1_0 * 32 + j1_1] + 1.0\n\n\n@T.prim_func\ndef unified_element_wise_implicit_block(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for blockIdx_x in T.thread_binding(0, 128, \"threadIdx.y\"):\n        for threadIdx_x in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[blockIdx_x, threadIdx_x * 32 + j0_1] = (\n                        A[blockIdx_x, threadIdx_x * 32 + j0_1] * 2.0\n                    )\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[blockIdx_x, threadIdx_x * 32 + j1_1] = (\n                        B[blockIdx_x, threadIdx_x * 32 + j1_1] + 1.0\n                    )\n\n\ndef test_thread_x():\n    _check(element_wise_thread_x, unified_element_wise_thread_x)\n\n\ndef test_thread_x_different_dtype():\n    _check(element_wise_thread_x_different_dtype, unified_element_wise_thread_x_different_dtype)\n\n\ndef test_env_thread_x():\n    _check(element_wise_env_thread_x, unified_element_wise_env_thread_x)\n\n\ndef test_vthread_x():\n    _check(element_wise_vthread_x, unified_element_wise_vthread_x)\n\n\ndef test_two_thread_x_in_same_kernel_not_equal():\n    _check_fail(element_wise_two_thread_x_in_same_kernel_not_equal)\n\n\ndef test_kernels_with_different_size():\n    _check(\n        element_wise_kernels_with_different_size, unified_element_wise_kernels_with_different_size\n    )\n\n\ndef test_implicit_block():\n    _check(element_wise_implicit_block, unified_element_wise_implicit_block)\n\n\ndef test_lower_te():\n    a = te.placeholder((32, 2, 2))\n    b = te.compute((32, 2, 2), lambda i, j, k: a[i, j, k] * 2.0)\n    s = te.create_schedule(b.op)\n    s[b].bind(b.op.axis[1], te.thread_axis(\"threadIdx.x\"))\n    s[b].bind(b.op.axis[2], te.thread_axis(\"threadIdx.x\"))\n    orig_mod = tvm.driver.build_module.schedule_to_module(s, [a, b])\n    mod = tvm.tir.transform.UnifyThreadBinding()(orig_mod)\n    tvm.ir.assert_structural_equal(mod, orig_mod)  # UnifyThreadBinding should do nothing on TE\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_unroll_loop.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\nfrom tvm.script import tir as T\nimport os\n\n\ndef test_unroll_loop():\n    ib = tvm.tir.ir_builder.create()\n    dtype = \"int64\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    Aptr = ib.buffer_ptr(Ab)\n    # for i in 0 to n-1:\n    with ib.for_range(n, n + 2, name=\"i\") as i:\n        with ib.for_range(0, 8, name=\"i\", kind=\"unroll\") as j:\n            Aptr[j + 1] = Aptr[i] + 1\n\n    stmt = ib.get()\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt))\n\n    assert isinstance(stmt, tvm.tir.For)\n\n    with tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"auto_max_step\": 16}}):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert not isinstance(ret, tvm.tir.For)\n\n    with tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"auto_max_step\": 15}}):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert isinstance(ret, tvm.tir.For)\n\n    with tvm.transform.PassContext(\n        config={\"tir.UnrollLoop\": {\"auto_max_step\": 16, \"explicit_unroll\": False}}\n    ):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert isinstance(ret, tvm.tir.For)\n        assert ret.kind == tvm.tir.ForKind.UNROLLED\n\n    ib = tvm.tir.ir_builder.create()\n    ib.scope_attr(tvm.tir.const(0, \"int32\"), \"pragma_auto_unroll_max_step\", 16)\n    ib.emit(stmt)\n    wrapped = ib.get()\n    wrapped = tvm.tir.SeqStmt([wrapped, stmt])\n    assert isinstance(ret, tvm.tir.For)\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], wrapped))\n\n    with tvm.transform.PassContext(\n        config={\"tir.UnrollLoop\": {\"auto_max_depth\": 8, \"explicit_unroll\": False}}\n    ):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert isinstance(ret[0], tvm.tir.For)\n        assert ret[0].kind == tvm.tir.ForKind.UNROLLED\n        assert isinstance(ret[1], tvm.tir.For)\n        assert ret[1].kind != tvm.tir.ForKind.UNROLLED\n\n\ndef test_unroll_fake_loop():\n    ib = tvm.tir.ir_builder.create()\n    dtype = \"int32\"\n    n = te.size_var(\"n\")\n    Ab = tvm.tir.decl_buffer((n,), dtype)\n    Aptr = ib.buffer_ptr(Ab)\n    # for i in 0 to n-1:\n    with ib.for_range(0, 1, name=\"i\") as i:\n        Aptr[i * 2] = 3\n        with ib.for_range(0, 10, name=\"j\") as j:\n            Aptr[j + 1] = Aptr[i] + 1\n\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt))\n\n    with tvm.transform.PassContext(\n        config={\n            \"tir.UnrollLoop\": {\"auto_max_depth\": 8, \"auto_max_extent\": 1, \"explicit_unroll\": False}\n        }\n    ):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert isinstance(ret[0], tvm.tir.BufferStore)\n\n\ndef test_unroll_single_count_loops():\n    n = te.size_var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute((n,), lambda *i: A(*i), name=\"B\")\n    s = te.create_schedule(B.op)\n    s = s.normalize()\n    dom_map = tvm.te.schedule.InferBound(s)\n    stmt = tvm.te.schedule.ScheduleOps(s, dom_map)\n    # all parameters to UnrolLoops are default values except for\n    # auto_unroll_max_extent which has been set to 1 (default:0)\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt))\n\n    with tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"auto_max_step\": 1}}):\n        ret = tvm.tir.transform.UnrollLoop()(mod)[\"main\"].body\n        assert ret == stmt\n\n\ndef test_unroll_allocations():\n    @tvm.script.ir_module\n    class before:\n        @T.prim_func\n        def main():\n            for i in T.unroll(2):\n                with T.decl_buffer([16], \"float32\") as buf:\n                    buf[0] = 0.0\n\n    @tvm.script.ir_module\n    class expected:\n        @T.prim_func\n        def main():\n            with T.decl_buffer([16], \"float32\") as buf1:\n                buf1[0] = 0.0\n            with T.decl_buffer([16], \"float32\") as buf2:\n                buf2[0] = 0.0\n\n    after = tvm.tir.transform.UnrollLoop()(before)\n\n    tvm.ir.assert_structural_equal(after, expected)\n\n\nif __name__ == \"__main__\":\n    test_unroll_loop()\n    test_unroll_fake_loop()\n    test_unroll_single_count_loops()\n    test_unroll_allocations()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_transform_vectorize.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nfrom tvm import te\n\n\ndef test_vectorize_loop():\n    dtype = \"int64\"\n    n = te.var(\"n\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, n) as i:\n        with ib.for_range(0, 4, kind=\"vectorize\") as j:\n            A[j] = tvm.tir.const(1, A.dtype)\n    stmt = ib.get()\n\n    assert isinstance(stmt.body, tvm.tir.For)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.For)\n    assert not isinstance(stmt.body, tvm.tir.For)\n    assert len(stmt.body.indices) == 1\n    assert isinstance(stmt.body.indices[0], tvm.tir.Ramp)\n    assert isinstance(stmt.body.value, tvm.tir.Broadcast)\n\n\ndef test_vectorize_vector():\n    dtype = \"int64\"\n    n = te.var(\"n\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32x4\", name=\"A\")\n    with ib.for_range(0, n) as i:\n        with ib.for_range(0, 4, kind=\"vectorize\") as j:\n            A[j] = tvm.tir.const(1, A.dtype)\n    stmt = ib.get()\n    assert isinstance(stmt.body, tvm.tir.For)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.For)\n    assert not isinstance(stmt.body, tvm.tir.For)\n    assert len(stmt.body.indices) == 1\n    assert isinstance(stmt.body.indices[0], tvm.tir.Ramp)\n    assert isinstance(stmt.body.value, tvm.tir.Broadcast)\n\n\ndef test_vectorize_with_if():\n    n = te.var(\"n\")\n    x = te.var(\"x\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 4, kind=\"vectorize\") as i:\n        with ib.if_scope(x < n):\n            A[i] = A[i] + 1\n        with ib.else_scope():\n            with ib.if_scope(i < n):\n                A[i] = 2.0\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n, x], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.IfThenElse)\n    assert len(stmt.then_case.indices) == 1\n    assert isinstance(stmt.then_case.indices[0], tvm.tir.Ramp)\n    assert isinstance(stmt.then_case.value, tvm.tir.Add)\n    assert stmt.then_case.value.dtype == \"float32x4\"\n    assert isinstance(stmt.else_case, tvm.tir.For)\n\n\ndef test_vectorize_with_if_cond_int64():\n    m = te.size_var(\"m\", dtype=\"int64\")\n    A = te.placeholder((m,), name=\"A\", dtype=\"float32\")\n    B = te.compute((m,), lambda i: te.if_then_else(i < 2, A[i], A[i] * 2), name=\"B\")\n    s = te.create_schedule(B.op)\n    x, y = s[B].split(B.op.axis[0], factor=4)\n    s[B].vectorize(y)\n    f = tvm.build(s, [A, B], \"llvm\")\n\n\ndef test_vectorize_let():\n    v = tvm.tir.Var(\"v\", \"float32\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 4, kind=\"vectorize\") as i:\n        ib.emit(lambda body: tvm.tir.LetStmt(v, A[i] + 1, body))\n        A[i] = v + 2\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A], ib.get()))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n    assert isinstance(stmt, tvm.tir.LetStmt)\n    assert stmt.value.dtype == \"float32x4\"\n\n\ndef test_vectorize_with_le_cond():\n    n = te.var(\"n\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 4, kind=\"vectorize\") as i:\n        with ib.if_scope(i <= n):\n            A[i] = A[i] + 1\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.For)\n\n\ndef test_vectorize_with_ge_cond():\n    n = te.var(\"n\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 4, kind=\"vectorize\") as i:\n        with ib.if_scope(i >= n):\n            A[i] = A[i] + 1\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.For)\n\n\ndef test_vectorize_if_then_else():\n    n = te.var(\"n\")\n    x = te.var(\"x\")\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, 4, kind=\"vectorize\") as i:\n        A[i] = tvm.tir.call_intrin(\"float32\", \"tir.if_then_else\", i > 0, A[i] + 1, A[i])\n    stmt = ib.get()\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n, x], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert isinstance(stmt, tvm.tir.For)\n\n    ib = tvm.tir.ir_builder.create()\n    A = ib.pointer(\"float32\", name=\"A\")\n    with ib.for_range(0, n) as k:\n        with ib.for_range(0, 4, kind=\"vectorize\") as i:\n            A[k * 4 + i] = tvm.tir.call_intrin(\n                \"float32\", \"tir.if_then_else\", k > 0, A[k * 4 + i], 0\n            )\n    stmt = ib.get()\n\n    assert isinstance(stmt.body, tvm.tir.For)\n\n    mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, n], stmt))\n    stmt = tvm.tir.transform.VectorizeLoop()(mod)[\"main\"].body\n\n    assert not isinstance(stmt.body, tvm.tir.For)\n    assert isinstance(stmt.body.value.args[2], tvm.tir.Broadcast)\n\n\ndef test_vectorize_while_fail():\n    \"\"\"A while loop inside a vectorized loop should fail.\"\"\"\n\n    n = 64\n    num_iter = 10\n\n    def test_ir(A, B, C):\n        ib = tvm.tir.ir_builder.create()\n        n = C.shape[0]\n        A = ib.buffer_ptr(A)\n        B = ib.buffer_ptr(B)\n        C = ib.buffer_ptr(C)\n        i = ib.allocate(\"int32\", (1,), name=\"i\", scope=\"local\")\n        i[0] = 0\n\n        with ib.for_range(0, n) as j:\n            C[j] = 0.0\n\n        with ib.for_range(0, n, kind=\"vectorize\") as j:\n            with ib.while_loop(i[0] < num_iter):\n                C[j] += A[j] + B[j]\n                i[0] += 1\n\n        return ib.get()\n\n    dtype = \"float32\"\n    A = te.placeholder((n,), name=\"A\", dtype=dtype)\n    B = te.placeholder((n,), name=\"B\", dtype=dtype)\n\n    C = te.extern(\n        (n,),\n        [A, B],\n        lambda ins, outs: test_ir(ins[0], ins[1], outs[0]),\n        name=\"while_vectorize\",\n        dtype=dtype,\n    )\n    s = te.create_schedule(C.op)\n\n    try:\n        tvm.lower(s, [A, B, C], \"llvm\")\n        assert False\n    except tvm.error.TVMError as e:\n        error_msg = str(e).split(\"\\n\")[-1]\n        expected = \"A while loop inside a vectorized loop not supported\"\n        assert expected in error_msg\n\n\ndef test_vectorize_dtype_mismatch():\n    n = tvm.tir.IntImm(\"int64\", 4)\n    A = te.compute((n,), lambda i: tvm.tir.IntImm(\"int64\", 2**31 - 1) + i, name=\"A\")\n    s = te.create_schedule(A.op)\n    s[A].vectorize(A.op.axis[0])\n    tvm.lower(s, [A], \"llvm\", simple_mode=True)\n\n\nif __name__ == \"__main__\":\n    test_vectorize_vector()\n    test_vectorize_with_if()\n    test_vectorize_loop()\n    test_vectorize_if_then_else()\n    test_vectorize_with_le_cond()\n    test_vectorize_with_ge_cond()\n    test_vectorize_let()\n    test_vectorize_while_fail()\n    test_vectorize_dtype_mismatch()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_algo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm import tir, script\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\nfrom tvm.tir.usmp import utils as usmp_utils\nfrom tvm.target import Target\nfrom tvm import WorkspacePoolInfo, PoolInfoProperties\n\n\ndef _replace_stmt_with_buf_var_names(buffer_info_map):\n    \"\"\"helper to replace tir.allocates with buffer names\"\"\"\n    new_buffer_info_map = dict()\n    for k, v in buffer_info_map.items():\n        new_buffer_info_map[v.buffer_var.name] = k\n    return new_buffer_info_map\n\n\ndef _verify_conflicts(main_buf_name, conflicting_buf_names, buffer_info_map):\n    \"\"\"helper to check expected liveness conflicts\"\"\"\n    buf_info = buffer_info_map[main_buf_name]\n    for conflict in buf_info.conflicts:\n        assert conflict.name_hint in conflicting_buf_names\n\n\ndef _get_allocates(primfunc):\n    \"\"\"helper to extract all allocate nodes by name\"\"\"\n    allocates = dict()\n\n    def get_allocate(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            allocates[str(stmt.buffer_var.name)] = stmt\n\n    stmt_functor.post_order_visit(primfunc.body, get_allocate)\n    return allocates\n\n\ndef _assign_poolinfos_to_allocates_in_primfunc(primfunc, pool_infos):\n    \"\"\"helper to assing poolinfos to allocate nodes in a tir.PrimFunc\"\"\"\n\n    def set_poolinfos(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            return tvm.tir.Allocate(\n                buffer_var=stmt.buffer_var,\n                dtype=stmt.dtype,\n                extents=stmt.extents,\n                condition=stmt.condition,\n                body=stmt.body,\n                annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: pool_infos},\n            )\n\n    return primfunc.with_body(stmt_functor.ir_transform(primfunc.body, None, set_poolinfos))\n\n\ndef _assign_poolinfos_to_allocates_in_irmodule(mod, pool_infos):\n    \"\"\"helper to assing poolinfos to allocate nodes in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = _assign_poolinfos_to_allocates_in_primfunc(basefunc, pool_infos)\n    return ret\n\n\ndef _assign_targets_to_primfuncs_irmodule(mod, target):\n    \"\"\"helper to assign target for PrimFunc in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = basefunc.with_attr(\"target\", target)\n    return ret\n\n\ndef _check_max_workspace_size(buffer_pool_allocations, pool_info, size):\n    max_workspace_size = 0\n    for buffer_info, pool_allocation in buffer_pool_allocations.items():\n        if pool_allocation.pool_info == pool_info:\n            size_candidate = pool_allocation.byte_offset + buffer_info.size_bytes\n            if size_candidate > max_workspace_size:\n                max_workspace_size = size_candidate\n    assert max_workspace_size == size\n\n\ndef test_no_pool_error():\n    target = Target(\"c\")\n    tiny_workspace_pool = WorkspacePoolInfo(\n        \"tiny_workspace\",\n        [target],\n        PoolInfoProperties(size_hint_bytes=10),\n    )\n    bi_a = usmp_utils.BufferInfo(\n        name_hint=\"bi_a\", size_bytes=10, pool_candidates=[tiny_workspace_pool]\n    )\n    bi_b = usmp_utils.BufferInfo(\n        name_hint=\"bi_b\", size_bytes=10, pool_candidates=[tiny_workspace_pool]\n    )\n    bi_c = usmp_utils.BufferInfo(\n        name_hint=\"bi_c\", size_bytes=10, pool_candidates=[tiny_workspace_pool]\n    )\n    bi_a.set_conflicts([bi_b])\n    bi_b.set_conflicts([bi_c])\n    bi_c.set_conflicts([bi_a])\n    buffer_info_arr = [bi_a, bi_b, bi_c]\n    fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.greedy_by_size\")\n    with pytest.raises(\n        tvm.TVMError, match=\"TVM USMP Error: the space available in the provided pools exceeded\"\n    ):\n        buffer_pool_allocations = fusmp_algo(buffer_info_arr, 0)\n\n\n@pytest.mark.parametrize(\"algorithm\", [\"greedy_by_size\", \"greedy_by_conflicts\", \"hill_climb\"])\ndef test_name_based_ordering(algorithm):\n    \"\"\"This checks when the size and conlicts are same a stable result is generated\"\"\"\n\n    def _test():\n        target = Target(\"c\")\n        global_workspace_pool = WorkspacePoolInfo(\n            \"global_workspace\",\n            [target],\n        )\n        bi_a = usmp_utils.BufferInfo(\n            name_hint=\"bi_a\", size_bytes=10, pool_candidates=[global_workspace_pool]\n        )\n        bi_b = usmp_utils.BufferInfo(\n            name_hint=\"bi_b\", size_bytes=10, pool_candidates=[global_workspace_pool]\n        )\n        bi_c = usmp_utils.BufferInfo(\n            name_hint=\"bi_c\", size_bytes=10, pool_candidates=[global_workspace_pool]\n        )\n        bi_a.set_conflicts([bi_b, bi_c])\n        bi_b.set_conflicts([bi_c, bi_a])\n        bi_c.set_conflicts([bi_a, bi_b])\n\n        buffer_info_arr = [bi_a, bi_b, bi_c]\n        fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.{algorithm}\")\n        buffer_pool_allocations = fusmp_algo(buffer_info_arr, 0)\n        assert buffer_pool_allocations[bi_a].byte_offset == 20\n        assert buffer_pool_allocations[bi_b].byte_offset == 10\n        assert buffer_pool_allocations[bi_c].byte_offset == 0\n\n    # This is tested for several times to check stability\n    for x in range(0, 10):\n        _test()\n\n\n@pytest.mark.parametrize(\n    [\"algorithm\", \"workspace_size\"],\n    [(\"greedy_by_size\", 140), (\"greedy_by_conflicts\", 140), (\"hill_climb\", 140)],\n)\ndef test_linear(algorithm, workspace_size):\n    \"\"\"\n    The test case here represent BufferInfo objects\n    that could get generated for a linear sequence\n    such as :\n    (Op A)\n    |\n    bi_a\n    |\n    (Op B)\n    |\n    bi_b\n    |\n    .\n    .\n    .\n    (Op F)\n    |\n    bi_f\n    \"\"\"\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n    bi_a = usmp_utils.BufferInfo(\n        name_hint=\"bi_a\", size_bytes=10, pool_candidates=[global_workspace_pool]\n    )\n    bi_b = usmp_utils.BufferInfo(\n        name_hint=\"bi_b\", size_bytes=20, pool_candidates=[global_workspace_pool]\n    )\n    bi_c = usmp_utils.BufferInfo(\n        name_hint=\"bi_c\", size_bytes=100, pool_candidates=[global_workspace_pool]\n    )\n    bi_d = usmp_utils.BufferInfo(\n        name_hint=\"bi_d\", size_bytes=40, pool_candidates=[global_workspace_pool]\n    )\n    bi_e = usmp_utils.BufferInfo(\n        name_hint=\"bi_e\", size_bytes=50, pool_candidates=[global_workspace_pool]\n    )\n    bi_f = usmp_utils.BufferInfo(\n        name_hint=\"bi_f\", size_bytes=50, pool_candidates=[global_workspace_pool]\n    )\n\n    # Creating conflicts for a linear graph\n    bi_a.set_conflicts([bi_b])\n    bi_b.set_conflicts([bi_a, bi_c])\n    bi_c.set_conflicts([bi_b, bi_d])\n    bi_d.set_conflicts([bi_c, bi_e])\n    bi_e.set_conflicts([bi_d, bi_f])\n    bi_f.set_conflicts([bi_e])\n\n    buffer_info_arr = [bi_a, bi_b, bi_c, bi_d, bi_e, bi_f]\n    fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.{algorithm}\")\n    buffer_pool_allocations = fusmp_algo(buffer_info_arr, 0)\n    _check_max_workspace_size(buffer_pool_allocations, global_workspace_pool, workspace_size)\n\n\n@pytest.mark.parametrize(\n    [\"algorithm\", \"workspace_size\"],\n    [(\"greedy_by_size\", 190), (\"greedy_by_conflicts\", 320), (\"hill_climb\", 190)],\n)\ndef test_fanout(algorithm, workspace_size):\n    \"\"\"\n    The test case here represent BufferInfo objects\n    that could get generated for a fanout topology\n    such as :\n    (Op A)\n    |\n    bi_a ---------\n    |            |\n    (Op B)     (Op C)\n    |            |\n    bi_b        bi_c\n    |            |\n    (Op D)     (Op E)\n    |            |\n    bi_d        bi_e\n    |            |\n    (Op F) ------\n    |\n    bi_f\n    |\n    (Op G)\n    |\n    bi_g\n    \"\"\"\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        targets=[target],\n    )\n    bi_a = usmp_utils.BufferInfo(\n        name_hint=\"bi_a\", size_bytes=10, pool_candidates=[global_workspace_pool]\n    )\n    bi_b = usmp_utils.BufferInfo(\n        name_hint=\"bi_b\", size_bytes=20, pool_candidates=[global_workspace_pool]\n    )\n    bi_c = usmp_utils.BufferInfo(\n        name_hint=\"bi_c\", size_bytes=100, pool_candidates=[global_workspace_pool]\n    )\n    bi_d = usmp_utils.BufferInfo(\n        name_hint=\"bi_d\", size_bytes=40, pool_candidates=[global_workspace_pool]\n    )\n    bi_e = usmp_utils.BufferInfo(\n        name_hint=\"bi_e\", size_bytes=50, pool_candidates=[global_workspace_pool]\n    )\n    bi_f = usmp_utils.BufferInfo(\n        name_hint=\"bi_f\", size_bytes=60, pool_candidates=[global_workspace_pool]\n    )\n    bi_g = usmp_utils.BufferInfo(\n        name_hint=\"bi_g\", size_bytes=70, pool_candidates=[global_workspace_pool]\n    )\n\n    # Creating conflicts for a linear graph\n    bi_a.set_conflicts([bi_b, bi_c])\n    bi_b.set_conflicts([bi_a, bi_c, bi_e])\n    bi_c.set_conflicts([bi_e, bi_a, bi_b, bi_d])\n    bi_d.set_conflicts([bi_b, bi_f, bi_c, bi_e])\n    bi_e.set_conflicts([bi_c, bi_f, bi_b, bi_d])\n    bi_f.set_conflicts([bi_d, bi_e, bi_f])\n    bi_g.set_conflicts([bi_f])\n\n    buffer_info_arr = [bi_a, bi_b, bi_c, bi_d, bi_e, bi_f, bi_g]\n    fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.{algorithm}\")\n    buffer_pool_allocations = fusmp_algo(buffer_info_arr, 0)\n    _check_max_workspace_size(buffer_pool_allocations, global_workspace_pool, workspace_size)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass MobilenetStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", \"tir.noalias\": True})\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_21 = T.match_buffer(T_cast_20, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_7 = T.decl_buffer([157323], \"int16\")\n        for i0_i1_fused_7 in T.serial(0, 229):\n            for i2_7, i3_7 in T.grid(229, 3):\n                PaddedInput_7[(((i0_i1_fused_7*687) + (i2_7*3)) + i3_7)] = T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), placeholder_65[((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n            Conv2dOutput_7 = T.decl_buffer([64], \"int32\")\n            for ff_3 in T.serial(0, 64):\n                Conv2dOutput_7[ff_3] = 0\n                for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                    Conv2dOutput_7[ff_3] = (Conv2dOutput_7[ff_3] + (T.cast(PaddedInput_7[(((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)], \"int32\")*T.cast(placeholder_66[((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)], \"int32\")))\n            for ax3_inner_7 in T.serial(0, 64):\n                T_cast_21[((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_7[ax3_inner_7] + placeholder_67[ax3_inner_7]), 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2 = T.decl_buffer([200704], \"uint8\")\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    @T.prim_func\n    def run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_9 = T.allocate([301056], \"int8\", \"global\")\n        sid_8 = T.allocate([802816], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8, output, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    [\"algorithm\", \"fast_memory_size\", \"slow_memory_size\"],\n    [\n        (\"greedy_by_size\", 200704, 1418528),\n        (\"greedy_by_conflicts\", 200704, 1418528),\n        (\"hill_climb\", 200704, 1117462),\n    ],\n)\ndef test_mobilenet_subgraph(algorithm, fast_memory_size, slow_memory_size):\n    target = Target(\"c\")\n    fast_memory_pool = WorkspacePoolInfo(\n        \"fast_memory\",\n        [target],\n        PoolInfoProperties(size_hint_bytes=200704),\n    )\n    slow_memory_pool = WorkspacePoolInfo(\n        \"slow_memory\",\n        [target],\n    )\n    tir_mod = MobilenetStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(\n        tir_mod, [fast_memory_pool, slow_memory_pool]\n    )\n    main_func = tir_mod[\"run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    assert buffer_info_analysis.memory_pressure == 1117718\n\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    buffer_info_arr = fcreate_array_bi(buffer_info_analysis.buffer_info_stmts)\n    fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.{algorithm}\")\n    buffer_pool_allocations = fusmp_algo(buffer_info_arr, buffer_info_analysis.memory_pressure)\n\n    buffer_info_map_names = dict()\n    for buf_info in buffer_info_arr:\n        buffer_info_map_names[buf_info.name_hint] = buf_info\n\n    # check conflicts\n    _verify_conflicts(\"PaddedInput_7\", [\"sid_9\", \"sid_8\", \"Conv2dOutput_7\"], buffer_info_map_names)\n    _verify_conflicts(\"tensor_2\", [\"sid_8\"], buffer_info_map_names)\n    _verify_conflicts(\"sid_9\", [\"PaddedInput_7\"], buffer_info_map_names)\n    _verify_conflicts(\n        \"sid_8\", [\"PaddedInput_7\", \"Conv2dOutput_7\", \"tensor_2\"], buffer_info_map_names\n    )\n    _verify_conflicts(\"Conv2dOutput_7\", [\"sid_8\", \"PaddedInput_7\"], buffer_info_map_names)\n\n    _check_max_workspace_size(buffer_pool_allocations, slow_memory_pool, slow_memory_size)\n    _check_max_workspace_size(buffer_pool_allocations, fast_memory_pool, fast_memory_size)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ResnetStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast(placeholder: T.handle, placeholder_1: T.handle, T_cast: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [360000], dtype=\"uint8\")\n        placeholder_3 = T.match_buffer(placeholder_1, [64], dtype=\"int32\")\n        T_cast_1 = T.match_buffer(T_cast, [360000], dtype=\"int16\")\n        # body\n        for ax0_ax1_fused, ax2, ax3_outer, ax3_inner in T.grid(75, 75, 4, 16):\n            T_cast_1[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(T.cast(placeholder_2[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner], \"int32\") - 94, 1843157232, 31, 1, dtype=\"int32\") + placeholder_3[ax3_outer * 16 + ax3_inner], 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1(placeholder_10: T.handle, placeholder_11: T.handle, placeholder_12: T.handle, T_cast_4: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", \"tir.noalias\": True})\n        placeholder_13 = T.match_buffer(placeholder_10, [360000], dtype=\"int16\")\n        placeholder_14 = T.match_buffer(placeholder_11, [36864], dtype=\"int16\")\n        placeholder_15 = T.match_buffer(placeholder_12, [64], dtype=\"int32\")\n        T_cast_5 = T.match_buffer(T_cast_4, [360000], dtype=\"int16\")\n        # body\n        PaddedInput_1 = T.decl_buffer([379456], \"int16\")\n        for i0_i1_fused_1, i2_1, i3_1 in T.grid(77, 77, 64):\n            PaddedInput_1[i0_i1_fused_1 * 4928 + i2_1 * 64 + i3_1] = T.if_then_else(1 <= i0_i1_fused_1 and i0_i1_fused_1 < 76 and 1 <= i2_1 and i2_1 < 76, placeholder_13[i0_i1_fused_1 * 4800 + i2_1 * 64 + i3_1 - 4864], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_1 in T.serial(0, 5625):\n            Conv2dOutput_1 = T.decl_buffer([64], \"int32\")\n            for ff_1 in T.serial(0, 64):\n                Conv2dOutput_1[ff_1] = 0\n                for ry, rx, rc_1 in T.grid(3, 3, 64):\n                    Conv2dOutput_1[ff_1] = Conv2dOutput_1[ff_1] + T.cast(PaddedInput_1[T.floordiv(ax0_ax1_fused_ax2_fused_1, 75) * 4928 + ry * 4928 + rx * 64 + T.floormod(ax0_ax1_fused_ax2_fused_1, 75) * 64 + rc_1], \"int32\") * T.cast(placeholder_14[ry * 12288 + rx * 4096 + rc_1 * 64 + ff_1], \"int32\")\n            for ax3_inner_2 in T.serial(0, 64):\n                T_cast_5[ax0_ax1_fused_ax2_fused_1 * 64 + ax3_inner_2] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_1[ax3_inner_2] + placeholder_15[ax3_inner_2], 1608879842, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_(placeholder_16: T.handle, placeholder_17: T.handle, placeholder_18: T.handle, T_add: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_\", \"tir.noalias\": True})\n        placeholder_19 = T.match_buffer(placeholder_16, [360000], dtype=\"int16\")\n        placeholder_20 = T.match_buffer(placeholder_17, [16384], dtype=\"int16\")\n        placeholder_21 = T.match_buffer(placeholder_18, [256], dtype=\"int32\")\n        T_add_1 = T.match_buffer(T_add, [1440000], dtype=\"int32\")\n        # body\n        PaddedInput_2 = T.decl_buffer([360000], \"int16\")\n        for i0_i1_fused_2, i2_2, i3_2 in T.grid(75, 75, 64):\n            PaddedInput_2[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2] = placeholder_19[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2]\n        for ax0_ax1_fused_ax2_fused_2 in T.serial(0, 5625):\n            Conv2dOutput_2 = T.decl_buffer([64], \"int32\")\n            for ax3_outer_1 in T.serial(0, 4):\n                for ff_2 in T.serial(0, 64):\n                    Conv2dOutput_2[ff_2] = 0\n                    for rc_2 in T.serial(0, 64):\n                        Conv2dOutput_2[ff_2] = Conv2dOutput_2[ff_2] + T.cast(PaddedInput_2[ax0_ax1_fused_ax2_fused_2 * 64 + rc_2], \"int32\") * T.cast(placeholder_20[rc_2 * 256 + ax3_outer_1 * 64 + ff_2], \"int32\")\n                for ax3_inner_3 in T.serial(0, 64):\n                    T_add_1[ax0_ax1_fused_ax2_fused_2 * 256 + ax3_outer_1 * 64 + ax3_inner_3] = T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_2[ax3_inner_3] + placeholder_21[ax3_outer_1 * 64 + ax3_inner_3], 1711626602, 31, -8, dtype=\"int32\") + 132, 255), 0), \"uint8\"), \"int32\") - 132, 2094289803, 31, -2, dtype=\"int32\") + 136\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_(placeholder_22: T.handle, placeholder_23: T.handle, placeholder_24: T.handle, placeholder_25: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_22, [360000], dtype=\"int16\")\n        placeholder_27 = T.match_buffer(placeholder_23, [16384], dtype=\"int16\")\n        placeholder_26 = T.match_buffer(placeholder_24, [256], dtype=\"int32\")\n        placeholder_28 = T.match_buffer(placeholder_25, [1440000], dtype=\"int32\")\n        T_cast_7 = T.match_buffer(T_cast_6, [1440000], dtype=\"uint8\")\n        # body\n        PaddedInput_3 = T.decl_buffer([360000], \"int16\")\n        for i0_i1_fused_3, i2_3, i3_3 in T.grid(75, 75, 64):\n            PaddedInput_3[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3] = placeholder_29[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3]\n        for ax0_ax1_fused_ax2_fused_3 in T.serial(0, 5625):\n            Conv2dOutput_3 = T.decl_buffer([64], \"int32\")\n            for ax3_outer_2 in T.serial(0, 4):\n                for ff_3 in T.serial(0, 64):\n                    Conv2dOutput_3[ff_3] = 0\n                    for rc_3 in T.serial(0, 64):\n                        Conv2dOutput_3[ff_3] = Conv2dOutput_3[ff_3] + T.cast(PaddedInput_3[ax0_ax1_fused_ax2_fused_3 * 64 + rc_3], \"int32\") * T.cast(placeholder_27[rc_3 * 256 + ax3_outer_2 * 64 + ff_3], \"int32\")\n                for ax3_inner_4 in T.serial(0, 64):\n                    T_cast_7[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_3[ax3_inner_4] + placeholder_26[ax3_outer_2 * 64 + ax3_inner_4], 1343014664, 31, -8, dtype=\"int32\") + 136, 255), 0), \"uint8\"), \"int32\") - 136, 1073903788, 31, 1, dtype=\"int32\") + placeholder_28[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4], 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_2 = T.allocate([720000], \"int8\", \"global\")\n        sid_6 = T.allocate([5760000], \"int8\", \"global\")\n        sid_7 = T.allocate([720000], \"int8\", \"global\")\n        sid_8 = T.allocate([720000], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_2, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", sid_2, T.lookup_param(\"p3\", dtype=\"handle\"), T.lookup_param(\"p4\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", sid_8, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), sid_7, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_\", sid_7, T.lookup_param(\"p7\", dtype=\"handle\"), T.lookup_param(\"p8\", dtype=\"handle\"), sid_6, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_\", sid_2, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_6, output, dtype=\"int32\"))\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast(placeholder_4: T.handle, placeholder_5: T.handle, placeholder_6: T.handle, T_cast_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", \"tir.noalias\": True})\n        placeholder_7 = T.match_buffer(placeholder_4, [360000], dtype=\"int16\")\n        placeholder_8 = T.match_buffer(placeholder_5, [4096], dtype=\"int16\")\n        placeholder_9 = T.match_buffer(placeholder_6, [64], dtype=\"int32\")\n        T_cast_3 = T.match_buffer(T_cast_2, [360000], dtype=\"int16\")\n        # body\n        PaddedInput = T.decl_buffer([360000], \"int16\")\n        for i0_i1_fused, i2, i3 in T.grid(75, 75, 64):\n            PaddedInput[i0_i1_fused * 4800 + i2 * 64 + i3] = placeholder_7[i0_i1_fused * 4800 + i2 * 64 + i3]\n        for ax0_ax1_fused_ax2_fused in T.serial(0, 5625):\n            Conv2dOutput = T.decl_buffer([64], \"int32\")\n            for ff in T.serial(0, 64):\n                Conv2dOutput[ff] = 0\n                for rc in T.serial(0, 64):\n                    Conv2dOutput[ff] = Conv2dOutput[ff] + T.cast(PaddedInput[ax0_ax1_fused_ax2_fused * 64 + rc], \"int32\") * T.cast(placeholder_8[rc * 64 + ff], \"int32\")\n            for ax3_inner_1 in T.serial(0, 64):\n                T_cast_3[ax0_ax1_fused_ax2_fused * 64 + ax3_inner_1] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput[ax3_inner_1] + placeholder_9[ax3_inner_1], 1843106743, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n    __tvm_meta__ = None\n# fmt: on\n\n\n@pytest.mark.parametrize(\n    [\"algorithm\", \"workspace_size\"],\n    [(\"greedy_by_size\", 7920256), (\"greedy_by_conflicts\", 7200256), (\"hill_climb\", 7200256)],\n)\ndef test_resnet_subgraph(algorithm, workspace_size):\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n    tir_mod = ResnetStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_workspace_pool])\n    main_func = tir_mod[\"tvmgen_default_run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    assert buffer_info_analysis.memory_pressure == 7200256\n\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    buffer_info_arr = fcreate_array_bi(buffer_info_analysis.buffer_info_stmts)\n    fusmp_algo = tvm.get_global_func(f\"tir.usmp.algo.{algorithm}\")\n    buffer_pool_allocations = fusmp_algo(buffer_info_arr, buffer_info_analysis.memory_pressure)\n\n    buffer_info_map_names = dict()\n    for buf_info in buffer_info_arr:\n        buffer_info_map_names[buf_info.name_hint] = buf_info\n\n    # check conflicts\n    _verify_conflicts(\n        \"sid_7\",\n        [\n            \"PaddedInput_1\",\n            \"sid_2\",\n            \"Conv2dOutput_1\",\n            \"PaddedInput_2\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_3\",\n        [\n            \"PaddedInput_3\",\n            \"sid_6\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"sid_6\",\n        [\n            \"Conv2dOutput_2\",\n            \"PaddedInput_2\",\n            \"sid_2\",\n            \"PaddedInput_3\",\n            \"Conv2dOutput_3\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput\",\n        [\n            \"sid_8\",\n            \"sid_2\",\n            \"PaddedInput\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"PaddedInput_3\",\n        [\n            \"sid_6\",\n            \"sid_2\",\n            \"Conv2dOutput_3\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_2\",\n        [\n            \"PaddedInput_2\",\n            \"sid_2\",\n            \"sid_6\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"PaddedInput_1\",\n        [\n            \"sid_8\",\n            \"sid_2\",\n            \"sid_7\",\n            \"Conv2dOutput_1\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_1\",\n        [\n            \"sid_7\",\n            \"PaddedInput_1\",\n            \"sid_2\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"PaddedInput\",\n        [\n            \"sid_2\",\n            \"sid_8\",\n            \"Conv2dOutput\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"sid_8\",\n        [\n            \"PaddedInput\",\n            \"sid_2\",\n            \"Conv2dOutput\",\n            \"PaddedInput_1\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"sid_2\",\n        [\n            \"PaddedInput\",\n            \"sid_8\",\n            \"Conv2dOutput\",\n            \"PaddedInput_1\",\n            \"sid_7\",\n            \"Conv2dOutput_1\",\n            \"PaddedInput_2\",\n            \"Conv2dOutput_2\",\n            \"sid_6\",\n            \"PaddedInput_3\",\n        ],\n        buffer_info_map_names,\n    )\n    _verify_conflicts(\n        \"PaddedInput_2\",\n        [\n            \"sid_7\",\n            \"sid_2\",\n            \"Conv2dOutput_2\",\n            \"sid_6\",\n        ],\n        buffer_info_map_names,\n    )\n\n    _check_max_workspace_size(buffer_pool_allocations, global_workspace_pool, workspace_size)\n\n\ndef test_custom_algo():\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n    tir_mod = ResnetStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_workspace_pool])\n    tir_mod = tir_mod.with_attr(\"executor\", tvm.relay.backend.Executor(\"aot\"))\n    tir_mod = tir_mod.with_attr(\"runtime\", tvm.relay.backend.Runtime(\"crt\"))\n    tir_mod[\"__tvm_main__\"] = tir_mod[\n        \"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\"\n    ]\n\n    algo_called = False\n\n    @tvm.register_func(\"tir.usmp.algo.trivial\")\n    def _trivial_algo(buf_infos, mem_pressure):\n        nonlocal algo_called\n        algo_called = True\n        out_layout = {}\n        offset = 0\n        for buf_info in buf_infos:\n            pool_info = buf_info.pool_candidates[0]\n            out_layout[buf_info] = usmp_utils.PoolAllocation(pool_info, offset)\n            offset += buf_info.size_bytes\n        return out_layout\n\n    usmp_pass = tvm.get_global_func(\"tir.transform.UnifiedStaticMemoryPlanner\")\n    usmp_pass()(tir_mod)\n    assert not algo_called\n\n    with tvm.transform.PassContext(config={\"tir.usmp.custom_algorithm\": \"trivial\"}):\n        usmp_pass()(tir_mod)\n\n    assert algo_called\n\n    with pytest.raises(\n        tvm.TVMError, match=\"The selected custom USMP algorithm : invalid is not defined\"\n    ):\n        with tvm.transform.PassContext(config={\"tir.usmp.custom_algorithm\": \"invalid\"}):\n            usmp_pass()(tir_mod)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_algo_hill_climb.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys\nimport pytest\nimport random\nimport tvm\nimport tvm.testing\nfrom tvm.tir.usmp.utils import BufferInfo\nfrom tvm import WorkspacePoolInfo, PoolInfoProperties\n\n\ndef _check_max_workspace_size(buffer_pool_allocations, pool_info, size, tolerance=0):\n    \"\"\"Helper to check maximum allocated memory size\"\"\"\n    max_workspace_size = 0\n    for buffer_info, pool_allocation in buffer_pool_allocations.items():\n        if pool_allocation.pool_info == pool_info:\n            size_candidate = pool_allocation.byte_offset + buffer_info.size_bytes\n            if size_candidate > max_workspace_size:\n                max_workspace_size = size_candidate\n    _diff = max_workspace_size.value - size\n    return (\n        (max_workspace_size.value == size if tolerance == 0 else tolerance > 100 * _diff / size),\n        \"'{}': expected {} got {}, diff {:0.2f}% ({} bytes)\".format(\n            pool_info.pool_name, size, max_workspace_size, 100 * _diff / size, _diff\n        ),\n    )\n\n\ndef _verify_conflicts(buffer_info, pool_allocation, buffer_info_map):\n    \"\"\"Helper to check expected liveness conflicts\"\"\"\n    for conflict in buffer_info.conflicts:\n        conflict_pool_allocation = buffer_info_map[conflict]\n\n        if conflict_pool_allocation.pool_info == pool_allocation.pool_info:\n            assert conflict_pool_allocation.byte_offset != pool_allocation.byte_offset\n            l2 = max(\n                conflict_pool_allocation.byte_offset + conflict.size_bytes,\n                pool_allocation.byte_offset + buffer_info.size_bytes,\n            ) - min(conflict_pool_allocation.byte_offset, pool_allocation.byte_offset)\n            assert (\n                conflict.size_bytes + buffer_info.size_bytes <= l2\n            ), 'Conflicting: \\n\"{} @{}\"\\n\"{} @{}\"'.format(\n                conflict, conflict_pool_allocation, buffer_info, pool_allocation\n            )\n\n\ndef _verify_all_conflicts(buffer_pool_allocations):\n    \"\"\"Helper to verify liveness conflicts\"\"\"\n    for buffer_info, pool_allocation in buffer_pool_allocations.items():\n        _verify_conflicts(buffer_info, pool_allocation, buffer_pool_allocations)\n\n\ndef test_bounded(\n    random_len=150,\n    pools=[\n        WorkspacePoolInfo(\"default\", [], PoolInfoProperties(65535)),\n        WorkspacePoolInfo(\"slow\", []),\n    ],\n):\n    \"\"\"Tests two pools, one is bounded and one is not limited\"\"\"\n    random.seed(0)\n    mem_range = [BufferInfo(str(i), random.randrange(1, 65535), pools) for i in range(random_len)]\n    for mr in mem_range:\n        pr = random.choice(mem_range)\n        while pr in (*mr.conflicts, mr):\n            pr = random.choice(mem_range)\n\n        mr.set_conflicts([*mr.conflicts, pr])\n        pr.set_conflicts([*pr.conflicts, mr])\n\n    fusmp_algo = tvm.get_global_func(\"tir.usmp.algo.hill_climb\")\n    result_map = fusmp_algo(mem_range, 0)\n    _verify_all_conflicts(result_map)\n\n\ndef __test_data_alloc_max():\n    \"\"\"Test data\"\"\"\n    intervals = [\n        (0, 159, 2048),\n        (0, 13, 7904),\n        (4, 35, 16),\n        (12, 17, 32768),\n        (16, 21, 32768),\n    ]\n    return intervals\n\n\ndef __test_data_deep_speech():\n    \"\"\"Test data\"\"\"\n    intervals = [\n        (0, 159, 2048),\n        (0, 151, 2048),\n        (0, 13, 7904),\n        (2, 49, 16),\n        (4, 35, 16),\n        (6, 21, 16),\n        (12, 17, 32768),\n        (16, 21, 32768),\n        (20, 27, 32768),\n        (26, 31, 32768),\n        (30, 35, 32768),\n        (34, 41, 32768),\n        (40, 45, 32768),\n        (44, 49, 32768),\n        (48, 145, 32768),\n        (54, 59, 2048),\n        (58, 483, 4096),\n        (60, 65, 2048),\n        (64, 461, 4096),\n        (66, 71, 2048),\n        (70, 439, 4096),\n        (72, 77, 2048),\n        (76, 417, 4096),\n        (78, 83, 2048),\n        (82, 395, 4096),\n        (84, 89, 2048),\n        (88, 373, 4096),\n        (90, 95, 2048),\n        (94, 351, 4096),\n        (96, 101, 2048),\n        (100, 329, 4096),\n        (102, 107, 2048),\n        (106, 307, 4096),\n        (108, 113, 2048),\n        (112, 285, 4096),\n        (114, 119, 2048),\n        (118, 263, 4096),\n        (120, 125, 2048),\n        (124, 241, 4096),\n        (126, 131, 2048),\n        (130, 219, 4096),\n        (132, 137, 2048),\n        (136, 197, 4096),\n        (138, 143, 2048),\n        (142, 175, 4096),\n        (144, 149, 2048),\n        (148, 153, 4096),\n        (152, 163, 8192),\n        (154, 171, 2048),\n        (156, 181, 2048),\n        (160, 167, 2048),\n        (162, 165, 2048),\n        (168, 171, 2048),\n        (170, 509, 2048),\n        (174, 185, 8192),\n        (176, 193, 2048),\n        (178, 203, 2048),\n        (182, 189, 2048),\n        (184, 187, 2048),\n        (190, 193, 2048),\n        (192, 511, 2048),\n        (196, 207, 8192),\n        (198, 215, 2048),\n        (200, 225, 2048),\n        (204, 211, 2048),\n        (206, 209, 2048),\n        (212, 215, 2048),\n        (214, 513, 2048),\n        (218, 229, 8192),\n        (220, 237, 2048),\n        (222, 247, 2048),\n        (226, 233, 2048),\n        (228, 231, 2048),\n        (234, 237, 2048),\n        (236, 515, 2048),\n        (240, 251, 8192),\n        (242, 259, 2048),\n        (244, 269, 2048),\n        (248, 255, 2048),\n        (250, 253, 2048),\n        (256, 259, 2048),\n        (258, 517, 2048),\n        (262, 273, 8192),\n        (264, 281, 2048),\n        (266, 291, 2048),\n        (270, 277, 2048),\n        (272, 275, 2048),\n        (278, 281, 2048),\n        (280, 519, 2048),\n        (284, 295, 8192),\n        (286, 303, 2048),\n        (288, 313, 2048),\n        (292, 299, 2048),\n        (294, 297, 2048),\n        (300, 303, 2048),\n        (302, 521, 2048),\n        (306, 317, 8192),\n        (308, 325, 2048),\n        (310, 335, 2048),\n        (314, 321, 2048),\n        (316, 319, 2048),\n        (322, 325, 2048),\n        (324, 523, 2048),\n        (328, 339, 8192),\n        (330, 347, 2048),\n        (332, 357, 2048),\n        (336, 343, 2048),\n        (338, 341, 2048),\n        (344, 347, 2048),\n        (346, 525, 2048),\n        (350, 361, 8192),\n        (352, 369, 2048),\n        (354, 379, 2048),\n        (358, 365, 2048),\n        (360, 363, 2048),\n        (366, 369, 2048),\n        (368, 527, 2048),\n        (372, 383, 8192),\n        (374, 391, 2048),\n        (376, 401, 2048),\n        (380, 387, 2048),\n        (382, 385, 2048),\n        (388, 391, 2048),\n        (390, 529, 2048),\n        (394, 405, 8192),\n        (396, 413, 2048),\n        (398, 423, 2048),\n        (402, 409, 2048),\n        (404, 407, 2048),\n        (410, 413, 2048),\n        (412, 531, 2048),\n        (416, 427, 8192),\n        (418, 435, 2048),\n        (420, 445, 2048),\n        (424, 431, 2048),\n        (426, 429, 2048),\n        (432, 435, 2048),\n        (434, 533, 2048),\n        (438, 449, 8192),\n        (440, 457, 2048),\n        (442, 467, 2048),\n        (446, 453, 2048),\n        (448, 451, 2048),\n        (454, 457, 2048),\n        (456, 535, 2048),\n        (460, 471, 8192),\n        (462, 479, 2048),\n        (464, 489, 2048),\n        (468, 475, 2048),\n        (470, 473, 2048),\n        (476, 479, 2048),\n        (478, 537, 2048),\n        (482, 493, 8192),\n        (484, 501, 2048),\n        (486, 497, 2048),\n        (490, 497, 2048),\n        (492, 495, 2048),\n        (496, 626, 2048),\n        (498, 501, 2048),\n        (500, 626, 2048),\n        (504, 549, 16),\n        (508, 543, 32768),\n        (542, 549, 32768),\n        (548, 555, 32768),\n        (554, 563, 464),\n        (560, 563, 256),\n        (562, 617, 2048),\n        (564, 567, 1856),\n        (566, 573, 1024),\n        (568, 619, 1024),\n        (570, 573, 1024),\n        (572, 577, 1024),\n        (576, 579, 1024),\n        (578, 605, 1024),\n        (580, 593, 1024),\n        (584, 587, 1024),\n        (586, 603, 1024),\n        (594, 597, 1024),\n        (596, 613, 1024),\n        (604, 607, 1024),\n        (606, 617, 1024),\n        (616, 621, 2048),\n        (618, 621, 1024),\n        (620, 626, 464),\n    ]\n    return intervals\n\n\ndef __test_data_five():\n    \"\"\"Test data\"\"\"\n    return [\n        (4, 5, 95),\n        (1, 4, 52135),\n        (3, 4, 12136),\n        (3, 5, 62099),\n        (4, 5, 50458),\n    ]\n\n\ndef __test_data_simple():\n    \"\"\"Test data\"\"\"\n    return [\n        (0, 23, 131072),  # 0\n        (4, 5, 65568),  # 1\n        (4, 9, 8192),  # 2\n        (8, 30, 15360),  # 3\n        (10, 11, 65568),  # 4\n        (10, 15, 4096),  # 5\n        (16, 17, 65552),  # 6\n        (16, 21, 2048),  # 7\n        (22, 23, 32784),  # 8\n        (22, 27, 1024),  # 9\n    ]\n\n\ndef find_maximum_from_intervals(intervals):\n    \"\"\"Expected list of intervals of (start, end, size)\"\"\"\n    sorted_list = sorted(intervals, key=lambda _: _[0])\n    max_mem = 0\n    for t in range(sorted_list[0][0], sorted_list[-1][1] + 1):\n        max_mem = max(\n            max_mem, sum([size for (start, end, size) in sorted_list if t >= start and t <= end])\n        )\n    return max_mem\n\n\n@pytest.mark.parametrize(\n    \"intervals\",\n    [__test_data_alloc_max(), __test_data_simple(), __test_data_deep_speech(), __test_data_five()],\n)\ndef test_intervals(intervals):\n    \"\"\"Tests supplied intervals\"\"\"\n    random.seed(0)\n    result = run_intervals(intervals, 5)\n    assert result[\"tir.usmp.algo.hill_climb\"] == True, f\" {result}\"\n\n\ndef generate_range(sz, max_segment_sz=65535):\n    \"\"\"Helper func to generate list of size sz of ranges of random size max_segment_sz\"\"\"\n    for i in range(0, sz):\n        start = random.randrange(i, sz)\n        stop = random.randrange(start + 1, start + 2 + ((sz - start) // 2))\n        assert stop - start > 0\n        yield (start, stop, random.randrange(1, max_segment_sz))\n\n\ndef test_random_intervals(interval_len=16):\n    \"\"\"Tests randomly generated interval of length interval_len\"\"\"\n    random.seed(0)\n    intervals = list(generate_range(interval_len))\n    return run_intervals(intervals)\n\n\ndef run_intervals(intervals, tolerance=0):\n    \"\"\"Helper to run intervals\"\"\"\n    expected_mem = find_maximum_from_intervals(intervals)\n    pools = [WorkspacePoolInfo(\"default\", [])]\n    buffers = []\n    # populate\n    for i, (start, stop, size) in enumerate(intervals):\n        buf = BufferInfo(str(i), size, pools)\n        # buf.set_pool_candidates( [\"default\"] )\n        buffers.append(buf)\n\n    # intersect\n    for i, (i_start, i_stop, _) in enumerate(intervals):\n        conflicts = set()\n        for j, (j_start, j_stop, _) in enumerate(intervals):\n            start = min(i_start, j_start)\n            stop = max(i_stop, j_stop)\n            i_dur = i_stop - i_start + 1\n            j_dur = j_stop - j_start + 1\n\n            if i != j and (stop - start + 1 < i_dur + j_dur):\n                conflicts.add(buffers[j])\n\n        buffers[i].set_conflicts([c for c in sorted(conflicts, key=lambda c: c.name_hint)])\n\n    result = {}\n    for (alg, params) in [\n        (\"tir.usmp.algo.hill_climb\", (expected_mem,)),\n        (\"tir.usmp.algo.greedy_by_size\", (expected_mem,)),\n    ]:\n        fusmp_algo = tvm.get_global_func(alg)\n        print(\"\\n\", \"started\", alg)\n        buffer_info_arr = fusmp_algo(buffers, *params)\n        print()\n\n        _verify_all_conflicts(buffer_info_arr)\n        result[alg], msg = _check_max_workspace_size(\n            buffer_info_arr, pools[0], expected_mem, tolerance\n        )\n        if not result[alg]:\n            print(alg, msg)\n\n    return result\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_analysis_extract_bufferinfo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport sys\n\nimport tvm\nfrom tvm import tir, script\nfrom tvm.ir import Range\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\nfrom tvm.tir import PrimFunc\nfrom tvm.tir.usmp import utils as usmp_utils\nfrom tvm.target import Target\nfrom tvm import WorkspacePoolInfo, ConstantPoolInfo\n\n\ndef _replace_stmt_with_buf_var_names(buffer_info_map):\n    \"\"\"helper to replace tir.allocates with buffer names\"\"\"\n    new_buffer_info_map = dict()\n    for k, v in buffer_info_map.items():\n        new_buffer_info_map[k.name_hint] = k\n    return new_buffer_info_map\n\n\ndef _verify_conflicts(main_buf_name, conflicting_buf_names, buffer_info_map):\n    \"\"\"helper to check expected liveness conflicts\"\"\"\n    buf_info = buffer_info_map[main_buf_name]\n    for conflict in buf_info.conflicts:\n        assert conflict.name_hint in conflicting_buf_names\n\n\ndef _get_allocates(primfunc):\n    \"\"\"helper to extract all allocate nodes by name\"\"\"\n    allocates = dict()\n\n    def get_allocate(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            allocates[str(stmt.buffer_var.name)] = stmt\n\n    stmt_functor.post_order_visit(primfunc.body, get_allocate)\n    return allocates\n\n\ndef _assign_poolinfos_to_allocates_in_primfunc(primfunc, pool_infos, constant_pool_infos):\n    \"\"\"helper to assing poolinfos to allocate nodes in a tir.PrimFunc\"\"\"\n\n    def set_poolinfos(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            return tvm.tir.Allocate(\n                buffer_var=stmt.buffer_var,\n                dtype=stmt.dtype,\n                extents=stmt.extents,\n                condition=stmt.condition,\n                body=stmt.body,\n                annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: pool_infos},\n            )\n        elif isinstance(stmt, tvm.tir.AllocateConst):\n            return tvm.tir.AllocateConst(\n                buffer_var=stmt.buffer_var,\n                dtype=stmt.dtype,\n                extents=stmt.extents,\n                data_or_idx=stmt.data,\n                body=stmt.body,\n                annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: constant_pool_infos},\n            )\n\n    return primfunc.with_body(stmt_functor.ir_transform(primfunc.body, None, set_poolinfos))\n\n\ndef _assign_poolinfos_to_allocates_in_irmodule(mod, pool_infos, constant_pool_infos=None):\n    \"\"\"helper to assign poolinfos to allocate nodes in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = _assign_poolinfos_to_allocates_in_primfunc(\n                basefunc, pool_infos, constant_pool_infos\n            )\n    return ret\n\n\ndef _assign_targets_to_primfuncs_irmodule(mod, target):\n    \"\"\"helper to assign target for PrimFunc in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = basefunc.with_attr(\"target\", target)\n    return ret\n\n\n# These are test IRModules that contains varied topologies of operator graphs\n# that includes a main TIR function that includes call to such operators.\n\n# fmt: off\n@tvm.script.ir_module\nclass LinearStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", \"tir.noalias\": True})\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_21 = T.match_buffer(T_cast_20, [289], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_7 = T.decl_buffer([157323], \"int16\")\n        for i0_i1_fused_7 in T.serial(0, 229):\n            for i2_7, i3_7 in T.grid(229, 3):\n                PaddedInput_7[(((i0_i1_fused_7*687) + (i2_7*3)) + i3_7)] = T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), placeholder_65[((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n            Conv2dOutput_7 = T.decl_buffer([64], \"int32\")\n            for ff_3 in T.serial(0, 64):\n                Conv2dOutput_7[ff_3] = 0\n                for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                    Conv2dOutput_7[ff_3] = (Conv2dOutput_7[ff_3] + (T.cast(PaddedInput_7[(((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)], \"int32\")*T.cast(placeholder_66[((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)], \"int32\")))\n            for ax3_inner_7 in T.serial(0, 64):\n                T_cast_21[((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_7[ax3_inner_7] + placeholder_67[ax3_inner_7]), 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2 = T.decl_buffer([200704], \"uint8\")\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    @T.prim_func\n    def run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_9 = T.allocate([301056], \"int8\", \"global\")\n        sid_8 = T.allocate([802816], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8, output, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_linear():\n    target = Target(\"c\")\n    fast_memory_pool = WorkspacePoolInfo(pool_name=\"fast_memory\", targets=[target])\n    slow_memory_pool = WorkspacePoolInfo(pool_name=\"slow_memory\", targets=[target])\n    tir_mod = LinearStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(\n        tir_mod, [fast_memory_pool, slow_memory_pool]\n    )\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(tir_mod[\"run_model\"], tir_mod)\n    assert buffer_info_analysis.memory_pressure == 1117718\n    buffer_info_map = _replace_stmt_with_buf_var_names(buffer_info_analysis.buffer_info_stmts)\n\n    # check conflicts\n    _verify_conflicts(\"PaddedInput_7\", [\"sid_9\", \"sid_8\", \"Conv2dOutput_7\"], buffer_info_map)\n    _verify_conflicts(\"tensor_2\", [\"sid_8\"], buffer_info_map)\n    _verify_conflicts(\"sid_9\", [\"PaddedInput_7\"], buffer_info_map)\n    _verify_conflicts(\"sid_8\", [\"PaddedInput_7\", \"Conv2dOutput_7\", \"tensor_2\"], buffer_info_map)\n    _verify_conflicts(\"Conv2dOutput_7\", [\"sid_8\", \"PaddedInput_7\"], buffer_info_map)\n\n    # check sizes\n    assert buffer_info_map[\"sid_8\"].size_bytes == 802816\n    assert buffer_info_map[\"Conv2dOutput_7\"].size_bytes == 256\n    assert buffer_info_map[\"PaddedInput_7\"].size_bytes == 314646\n    assert buffer_info_map[\"tensor_2\"].size_bytes == 200704\n    assert buffer_info_map[\"sid_9\"].size_bytes == 301056\n\n    # check_pool_candidates\n    assert [\n        pool_info.pool_name for pool_info in list(buffer_info_map[\"sid_8\"].pool_candidates)\n    ] == [\"fast_memory\", \"slow_memory\"]\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ParallelSerialMixedForLoops:\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1(placeholder_68: T.handle, placeholder_69: T.handle, placeholder_70: T.handle, T_cast_22: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", \"tir.noalias\": True})\n        placeholder_71 = T.match_buffer(placeholder_68, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_72 = T.match_buffer(placeholder_69, [110592], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_73 = T.match_buffer(placeholder_70, [192], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_23 = T.match_buffer(T_cast_22, [305], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_8 = T.decl_buffer([215296], \"int16\")\n        for i0_i1_fused_8 in T.serial(0, 58):\n            for i2_8, i3_8 in T.grid(58, 64):\n                PaddedInput_8[(((i0_i1_fused_8*3712) + (i2_8*64)) + i3_8)] = T.if_then_else(((((1 <= i0_i1_fused_8) and (i0_i1_fused_8 < 57)) and (1 <= i2_8)) and (i2_8 < 57)), placeholder_71[((((i0_i1_fused_8*3584) + (i2_8*64)) + i3_8) - 3648)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_8 in T.parallel(0, 3136):\n            dummy_allocate = T.decl_buffer([1], \"int32\")\n            for ax3_outer_4 in T.serial(0, 3):\n                Conv2dOutput_8 = T.decl_buffer([64], \"int32\")\n                for ff_4 in T.serial(0, 64):\n                    Conv2dOutput_8[ff_4] = 0\n                    for ry_3, rx_3, rc_8 in T.grid(3, 3, 64):\n                        Conv2dOutput_8[ff_4] = (Conv2dOutput_8[ff_4] + (T.cast(PaddedInput_8[(((((T.floordiv(ax0_ax1_fused_ax2_fused_8, 56)*3712) + (ry_3*3712)) + (rx_3*64)) + (T.floormod(ax0_ax1_fused_ax2_fused_8, 56)*64)) + rc_8)], \"int32\")*T.cast(placeholder_72[(((((ry_3*36864) + (rx_3*12288)) + (rc_8*192)) + (ax3_outer_4*64)) + ff_4)], \"int32\")))\n                for ax3_inner_8 in T.serial(0, 64):\n                    T_cast_23[(((ax0_ax1_fused_ax2_fused_8*192) + (ax3_outer_4*64)) + ax3_inner_8)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_8[ax3_inner_8] + placeholder_73[((ax3_outer_4*64) + ax3_inner_8)]), 1139793473, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", input, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), output, dtype=\"int32\"))\n\n\n__tvm_meta__ = None\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass AllSerialForLoops:\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1(placeholder_68: T.handle, placeholder_69: T.handle, placeholder_70: T.handle, T_cast_22: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", \"tir.noalias\": True})\n        placeholder_71 = T.match_buffer(placeholder_68, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_72 = T.match_buffer(placeholder_69, [110592], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_73 = T.match_buffer(placeholder_70, [192], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_23 = T.match_buffer(T_cast_22, [305], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_8 = T.decl_buffer([215296], \"int16\")\n        for i0_i1_fused_8 in T.serial(0, 58):\n            for i2_8, i3_8 in T.grid(58, 64):\n                PaddedInput_8[(((i0_i1_fused_8*3712) + (i2_8*64)) + i3_8)] = T.if_then_else(((((1 <= i0_i1_fused_8) and (i0_i1_fused_8 < 57)) and (1 <= i2_8)) and (i2_8 < 57)), placeholder_71[((((i0_i1_fused_8*3584) + (i2_8*64)) + i3_8) - 3648)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_8 in T.serial(0, 3136):\n            dummy_allocate = T.decl_buffer([1], \"int32\")\n            for ax3_outer_4 in T.serial(0, 3):\n                Conv2dOutput_8 = T.decl_buffer([64], \"int32\")\n                for ff_4 in T.serial(0, 64):\n                    Conv2dOutput_8[ff_4] = 0\n                    for ry_3, rx_3, rc_8 in T.grid(3, 3, 64):\n                        Conv2dOutput_8[ff_4] = (Conv2dOutput_8[ff_4] + (T.cast(PaddedInput_8[(((((T.floordiv(ax0_ax1_fused_ax2_fused_8, 56)*3712) + (ry_3*3712)) + (rx_3*64)) + (T.floormod(ax0_ax1_fused_ax2_fused_8, 56)*64)) + rc_8)], \"int32\")*T.cast(placeholder_72[(((((ry_3*36864) + (rx_3*12288)) + (rc_8*192)) + (ax3_outer_4*64)) + ff_4)], \"int32\")))\n                for ax3_inner_8 in T.serial(0, 64):\n                    T_cast_23[(((ax0_ax1_fused_ax2_fused_8*192) + (ax3_outer_4*64)) + ax3_inner_8)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_8[ax3_inner_8] + placeholder_73[((ax3_outer_4*64) + ax3_inner_8)]), 1139793473, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", input, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), output, dtype=\"int32\"))\n\n\n__tvm_meta__ = None\n# fmt: on\n\n\ndef test_parallel_serial_mixed_for_loops():\n    target = Target(\"c\")\n    global_ws_pool = WorkspacePoolInfo(\n        pool_name=\"global_workspace\",\n        targets=[target],\n    )\n    all_serial_tir_mod = AllSerialForLoops\n    all_serial_tir_mod = _assign_targets_to_primfuncs_irmodule(all_serial_tir_mod, target)\n    all_serial_tir_mod = _assign_poolinfos_to_allocates_in_irmodule(\n        all_serial_tir_mod, [global_ws_pool]\n    )\n    main_func = all_serial_tir_mod[\"run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, all_serial_tir_mod)\n    assert buffer_info_analysis.memory_pressure == 430848\n    buffer_info_map = _replace_stmt_with_buf_var_names(buffer_info_analysis.buffer_info_stmts)\n\n    # When all loops are serial all allocates are touched by USMP\n    assert len(buffer_info_map) == 3\n    for name, _ in buffer_info_map.items():\n        assert name in [\"dummy_allocate\", \"Conv2dOutput_8\", \"PaddedInput_8\"]\n\n    parallel_serial_mixed_tir_mod = ParallelSerialMixedForLoops\n    parallel_serial_mixed_tir_mod = _assign_targets_to_primfuncs_irmodule(\n        parallel_serial_mixed_tir_mod, target\n    )\n    parallel_serial_mixed_tir_mod = _assign_poolinfos_to_allocates_in_irmodule(\n        parallel_serial_mixed_tir_mod, [global_ws_pool]\n    )\n    main_func = parallel_serial_mixed_tir_mod[\"run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(\n        main_func, parallel_serial_mixed_tir_mod\n    )\n    assert buffer_info_analysis.memory_pressure == 430848\n    buffer_info_map = _replace_stmt_with_buf_var_names(buffer_info_analysis.buffer_info_stmts)\n\n    # USMP will not touch (yet) the allocates inside parallel for loops\n    assert len(buffer_info_map) == 2\n    for name, _ in buffer_info_map.items():\n        assert name in [\"Conv2dOutput_8\", \"PaddedInput_8\"]\n\n\n# fmt: off\n@tvm.script.ir_module\nclass InceptionStructure:\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d(placeholder: T.handle, tensor: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d\", \"tir.noalias\": True})\n        placeholder_1 = T.match_buffer(placeholder, [602112], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        tensor_1 = T.match_buffer(tensor, [249], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused in T.serial(0, 28):\n            for ax2 in T.serial(0, 28):\n                for ax3_outer_init, ax3_inner_init in T.grid(3, 64):\n                    tensor_1[((((ax0_ax1_fused*5376) + (ax2*192)) + (ax3_outer_init*64)) + ax3_inner_init)] = T.uint8(0)\n                for rv0_rv1_fused, ax3_outer, ax3_inner in T.grid(9, 3, 64):\n                    tensor_1[((((ax0_ax1_fused*5376) + (ax2*192)) + (ax3_outer*64)) + ax3_inner)] = T.max(tensor_1[((((ax0_ax1_fused*5376) + (ax2*192)) + (ax3_outer*64)) + ax3_inner)], T.if_then_else(((((ax0_ax1_fused*2) + T.floordiv(rv0_rv1_fused, 3)) < 56) and (((ax2*2) + T.floormod(rv0_rv1_fused, 3)) < 56)), placeholder_1[((((((ax0_ax1_fused*21504) + (T.floordiv(rv0_rv1_fused, 3)*10752)) + (ax2*384)) + (T.floormod(rv0_rv1_fused, 3)*192)) + (ax3_outer*64)) + ax3_inner)], T.uint8(0), dtype=\"uint8\"))\n\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def tvmgen_default_fused_cast(placeholder_6: T.handle, T_cast: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast\", \"tir.noalias\": True})\n        placeholder_7 = T.match_buffer(placeholder_6, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_1 = T.match_buffer(T_cast, [249], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_2 in T.serial(0, 28):\n            for ax2_2, ax3_outer_1, ax3_inner_2 in T.grid(28, 12, 16):\n                T_cast_1[((((ax0_ax1_fused_2*5376) + (ax2_2*192)) + (ax3_outer_1*16)) + ax3_inner_2)] = T.cast(placeholder_7[((((ax0_ax1_fused_2*5376) + (ax2_2*192)) + (ax3_outer_1*16)) + ax3_inner_2)], \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_concatenate(placeholder_8: T.handle, placeholder_9: T.handle, placeholder_10: T.handle, placeholder_11: T.handle, T_concat: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_concatenate\", \"tir.noalias\": True})\n        placeholder_12 = T.match_buffer(placeholder_8, [50176], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_concat_1 = T.match_buffer(T_concat, [313], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_13 = T.match_buffer(placeholder_9, [100352], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_14 = T.match_buffer(placeholder_11, [25088], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_15 = T.match_buffer(placeholder_10, [25088], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_3 in T.serial(0, 28):\n            for ax2_3, ax3 in T.grid(28, 256):\n                T_concat_1[(((ax0_ax1_fused_3*7168) + (ax2_3*256)) + ax3)] = T.if_then_else((224 <= ax3), placeholder_14[((((ax0_ax1_fused_3*896) + (ax2_3*32)) + ax3) - 224)], T.if_then_else((192 <= ax3), placeholder_15[((((ax0_ax1_fused_3*896) + (ax2_3*32)) + ax3) - 192)], T.if_then_else((64 <= ax3), placeholder_13[((((ax0_ax1_fused_3*3584) + (ax2_3*128)) + ax3) - 64)], placeholder_12[(((ax0_ax1_fused_3*1792) + (ax2_3*64)) + ax3)], dtype=\"uint8\"), dtype=\"uint8\"), dtype=\"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast(placeholder_16: T.handle, placeholder_17: T.handle, placeholder_18: T.handle, T_cast_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", \"tir.noalias\": True})\n        placeholder_19 = T.match_buffer(placeholder_16, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_20 = T.match_buffer(placeholder_17, [4096], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_21 = T.match_buffer(placeholder_18, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_3 = T.match_buffer(T_cast_2, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput = T.decl_buffer([200704], \"int16\")\n        for i0_i1_fused in T.serial(0, 56):\n            for i2, i3 in T.grid(56, 64):\n                PaddedInput[(((i0_i1_fused*3584) + (i2*64)) + i3)] = placeholder_19[(((i0_i1_fused*3584) + (i2*64)) + i3)]\n        for ax0_ax1_fused_ax2_fused in T.serial(0, 3136):\n            Conv2dOutput = T.decl_buffer([64], \"int32\")\n            for ff in T.serial(0, 64):\n                Conv2dOutput[ff] = 0\n                for rc in T.serial(0, 64):\n                    Conv2dOutput[ff] = (Conv2dOutput[ff] + (T.cast(PaddedInput[((ax0_ax1_fused_ax2_fused*64) + rc)], \"int32\")*T.cast(placeholder_20[((rc*64) + ff)], \"int32\")))\n            for ax3_inner_3 in T.serial(0, 64):\n                T_cast_3[((ax0_ax1_fused_ax2_fused*64) + ax3_inner_3)] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput[ax3_inner_3] + placeholder_21[ax3_inner_3]), 1191576922, 31, -4, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1(placeholder_22: T.handle, placeholder_23: T.handle, placeholder_24: T.handle, T_cast_4: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", \"tir.noalias\": True})\n        placeholder_25 = T.match_buffer(placeholder_22, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_26 = T.match_buffer(placeholder_23, [18432], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_27 = T.match_buffer(placeholder_24, [96], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_5 = T.match_buffer(T_cast_4, [153], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_1 = T.decl_buffer([150528], \"int16\")\n        for i0_i1_fused_1 in T.serial(0, 28):\n            for i2_1, i3_1 in T.grid(28, 192):\n                PaddedInput_1[(((i0_i1_fused_1*5376) + (i2_1*192)) + i3_1)] = placeholder_25[(((i0_i1_fused_1*5376) + (i2_1*192)) + i3_1)]\n        for ax0_ax1_fused_ax2_fused_1 in T.serial(0, 784):\n            Conv2dOutput_1 = T.decl_buffer([1], \"int32\")\n            for ax3_1 in T.serial(0, 96):\n                Conv2dOutput_1[0] = 0\n                for rc_1 in T.serial(0, 192):\n                    Conv2dOutput_1[0] = (Conv2dOutput_1[0] + (T.cast(PaddedInput_1[((ax0_ax1_fused_ax2_fused_1*192) + rc_1)], \"int32\")*T.cast(placeholder_26[((rc_1*96) + ax3_1)], \"int32\")))\n                T_cast_5[((ax0_ax1_fused_ax2_fused_1*96) + ax3_1)] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_1[0] + placeholder_27[ax3_1]), 1201322342, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2 = T.decl_buffer([200704], \"uint8\")\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_2(placeholder_30: T.handle, placeholder_31: T.handle, placeholder_32: T.handle, T_cast_8: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_2\", \"tir.noalias\": True})\n        placeholder_33 = T.match_buffer(placeholder_30, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_34 = T.match_buffer(placeholder_31, [12288], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_35 = T.match_buffer(placeholder_32, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_9 = T.match_buffer(T_cast_8, [121], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_2 = T.decl_buffer([150528], \"int16\")\n        for i0_i1_fused_2 in T.serial(0, 28):\n            for i2_2, i3_2 in T.grid(28, 192):\n                PaddedInput_2[(((i0_i1_fused_2*5376) + (i2_2*192)) + i3_2)] = placeholder_33[(((i0_i1_fused_2*5376) + (i2_2*192)) + i3_2)]\n        for ax0_ax1_fused_ax2_fused_2 in T.serial(0, 784):\n            Conv2dOutput_2 = T.decl_buffer([64], \"int32\")\n            for ff_1 in T.serial(0, 64):\n                Conv2dOutput_2[ff_1] = 0\n                for rc_2 in T.serial(0, 192):\n                    Conv2dOutput_2[ff_1] = (Conv2dOutput_2[ff_1] + (T.cast(PaddedInput_2[((ax0_ax1_fused_ax2_fused_2*192) + rc_2)], \"int32\")*T.cast(placeholder_34[((rc_2*64) + ff_1)], \"int32\")))\n            for ax3_inner_4 in T.serial(0, 64):\n                T_cast_9[((ax0_ax1_fused_ax2_fused_2*64) + ax3_inner_4)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_2[ax3_inner_4] + placeholder_35[ax3_inner_4]), 1663316467, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast_1(placeholder_36: T.handle, T_cast_10: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast_1\", \"tir.noalias\": True})\n        placeholder_37 = T.match_buffer(placeholder_36, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_11 = T.match_buffer(T_cast_10, [249], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_3 = T.decl_buffer([150528], \"uint8\")\n        for ax0_ax1_fused_6 in T.serial(0, 28):\n            for ax2_6 in T.serial(0, 28):\n                for ax3_outer_init_1, ax3_inner_init_1 in T.grid(3, 64):\n                    tensor_3[((((ax0_ax1_fused_6*5376) + (ax2_6*192)) + (ax3_outer_init_1*64)) + ax3_inner_init_1)] = T.uint8(0)\n                for rv0_rv1_fused_2, ax3_outer_2, ax3_inner_5 in T.grid(9, 3, 64):\n                    tensor_3[((((ax0_ax1_fused_6*5376) + (ax2_6*192)) + (ax3_outer_2*64)) + ax3_inner_5)] = T.max(tensor_3[((((ax0_ax1_fused_6*5376) + (ax2_6*192)) + (ax3_outer_2*64)) + ax3_inner_5)], T.if_then_else(((((1 <= (T.floordiv(rv0_rv1_fused_2, 3) + ax0_ax1_fused_6)) and ((T.floordiv(rv0_rv1_fused_2, 3) + ax0_ax1_fused_6) < 29)) and (1 <= (ax2_6 + T.floormod(rv0_rv1_fused_2, 3)))) and ((ax2_6 + T.floormod(rv0_rv1_fused_2, 3)) < 29)), placeholder_37[(((((((T.floordiv(rv0_rv1_fused_2, 3)*5376) + (ax0_ax1_fused_6*5376)) + (ax2_6*192)) + (T.floormod(rv0_rv1_fused_2, 3)*192)) + (ax3_outer_2*64)) + ax3_inner_5) - 5568)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_7 in T.serial(0, 28):\n            for ax2_7, ax3_4 in T.grid(28, 192):\n                T_cast_11[(((ax0_ax1_fused_7*5376) + (ax2_7*192)) + ax3_4)] = T.cast(tensor_3[(((ax0_ax1_fused_7*5376) + (ax2_7*192)) + ax3_4)], \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__2(placeholder_38: T.handle, placeholder_39: T.handle, placeholder_40: T.handle, T_cast_12: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__2\", \"tir.noalias\": True})\n        placeholder_41 = T.match_buffer(placeholder_38, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_42 = T.match_buffer(placeholder_39, [6144], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_43 = T.match_buffer(placeholder_40, [32], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_13 = T.match_buffer(T_cast_12, [89], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_3 = T.decl_buffer([150528], \"int16\")\n        for i0_i1_fused_3 in T.serial(0, 28):\n            for i2_3, i3_3 in T.grid(28, 192):\n                PaddedInput_3[(((i0_i1_fused_3*5376) + (i2_3*192)) + i3_3)] = placeholder_41[(((i0_i1_fused_3*5376) + (i2_3*192)) + i3_3)]\n        for ax0_ax1_fused_ax2_fused_3 in T.serial(0, 784):\n            Conv2dOutput_3 = T.decl_buffer([1], \"int32\")\n            for ax3_5 in T.serial(0, 32):\n                Conv2dOutput_3[0] = 0\n                for rc_3 in T.serial(0, 192):\n                    Conv2dOutput_3[0] = (Conv2dOutput_3[0] + (T.cast(PaddedInput_3[((ax0_ax1_fused_ax2_fused_3*192) + rc_3)], \"int32\")*T.cast(placeholder_42[((rc_3*32) + ax3_5)], \"int32\")))\n                T_cast_13[((ax0_ax1_fused_ax2_fused_3*32) + ax3_5)] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_3[0] + placeholder_43[ax3_5]), 1811141736, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int32\"), 1136333842, 31, 0, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2(placeholder_44: T.handle, placeholder_45: T.handle, placeholder_46: T.handle, T_cast_14: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2\", \"tir.noalias\": True})\n        placeholder_47 = T.match_buffer(placeholder_44, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_48 = T.match_buffer(placeholder_45, [3072], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_49 = T.match_buffer(placeholder_46, [16], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_15 = T.match_buffer(T_cast_14, [73], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_4 = T.decl_buffer([150528], \"int16\")\n        for i0_i1_fused_4 in T.serial(0, 28):\n            for i2_4, i3_4 in T.grid(28, 192):\n                PaddedInput_4[(((i0_i1_fused_4*5376) + (i2_4*192)) + i3_4)] = placeholder_47[(((i0_i1_fused_4*5376) + (i2_4*192)) + i3_4)]\n        for ax0_ax1_fused_ax2_fused_4 in T.serial(0, 784):\n            Conv2dOutput_4 = T.decl_buffer([1], \"int32\")\n            for ax3_6 in T.serial(0, 16):\n                Conv2dOutput_4[0] = 0\n                for rc_4 in T.serial(0, 192):\n                    Conv2dOutput_4[0] = (Conv2dOutput_4[0] + (T.cast(PaddedInput_4[((ax0_ax1_fused_ax2_fused_4*192) + rc_4)], \"int32\")*T.cast(placeholder_48[((rc_4*16) + ax3_6)], \"int32\")))\n                T_cast_15[((ax0_ax1_fused_ax2_fused_4*16) + ax3_6)] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_4[0] + placeholder_49[ax3_6]), 1764006585, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__1(placeholder_50: T.handle, placeholder_51: T.handle, placeholder_52: T.handle, T_cast_16: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__1\", \"tir.noalias\": True})\n        placeholder_53 = T.match_buffer(placeholder_50, [12544], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_54 = T.match_buffer(placeholder_51, [4608], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_55 = T.match_buffer(placeholder_52, [32], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_17 = T.match_buffer(T_cast_16, [89], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_5 = T.decl_buffer([14400], \"int16\")\n        for i0_i1_fused_5 in T.serial(0, 30):\n            for i2_5, i3_5 in T.grid(30, 16):\n                PaddedInput_5[(((i0_i1_fused_5*480) + (i2_5*16)) + i3_5)] = T.if_then_else(((((1 <= i0_i1_fused_5) and (i0_i1_fused_5 < 29)) and (1 <= i2_5)) and (i2_5 < 29)), placeholder_53[((((i0_i1_fused_5*448) + (i2_5*16)) + i3_5) - 464)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_5 in T.serial(0, 784):\n            Conv2dOutput_5 = T.decl_buffer([1], \"int32\")\n            for ax3_7 in T.serial(0, 32):\n                Conv2dOutput_5[0] = 0\n                for ry, rx, rc_5 in T.grid(3, 3, 16):\n                    Conv2dOutput_5[0] = (Conv2dOutput_5[0] + (T.cast(PaddedInput_5[(((((T.floordiv(ax0_ax1_fused_ax2_fused_5, 28)*480) + (ry*480)) + (rx*16)) + (T.floormod(ax0_ax1_fused_ax2_fused_5, 28)*16)) + rc_5)], \"int32\")*T.cast(placeholder_54[((((ry*1536) + (rx*512)) + (rc_5*32)) + ax3_7)], \"int32\")))\n                T_cast_17[((ax0_ax1_fused_ax2_fused_5*32) + ax3_7)] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_5[0] + placeholder_55[ax3_7]), 1131968888, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int32\"), 1900719667, 31, 0, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320_(placeholder_56: T.handle, placeholder_57: T.handle, placeholder_58: T.handle, T_cast_18: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320_\", \"tir.noalias\": True})\n        placeholder_59 = T.match_buffer(placeholder_56, [75264], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_60 = T.match_buffer(placeholder_57, [110592], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_61 = T.match_buffer(placeholder_58, [128], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_19 = T.match_buffer(T_cast_18, [185], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_6 = T.decl_buffer([86400], \"int16\")\n        for i0_i1_fused_6 in T.serial(0, 30):\n            for i2_6, i3_6 in T.grid(30, 96):\n                PaddedInput_6[(((i0_i1_fused_6*2880) + (i2_6*96)) + i3_6)] = T.if_then_else(((((1 <= i0_i1_fused_6) and (i0_i1_fused_6 < 29)) and (1 <= i2_6)) and (i2_6 < 29)), placeholder_59[((((i0_i1_fused_6*2688) + (i2_6*96)) + i3_6) - 2784)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_6 in T.serial(0, 784):\n            Conv2dOutput_6 = T.decl_buffer([64], \"int32\")\n            for ax3_outer_3 in T.serial(0, 2):\n                for ff_2 in T.serial(0, 64):\n                    Conv2dOutput_6[ff_2] = 0\n                    for ry_1, rx_1, rc_6 in T.grid(3, 3, 96):\n                        Conv2dOutput_6[ff_2] = (Conv2dOutput_6[ff_2] + (T.cast(PaddedInput_6[(((((T.floordiv(ax0_ax1_fused_ax2_fused_6, 28)*2880) + (ry_1*2880)) + (rx_1*96)) + (T.floormod(ax0_ax1_fused_ax2_fused_6, 28)*96)) + rc_6)], \"int32\")*T.cast(placeholder_60[(((((ry_1*36864) + (rx_1*12288)) + (rc_6*128)) + (ax3_outer_3*64)) + ff_2)], \"int32\")))\n                for ax3_inner_6 in T.serial(0, 64):\n                    T_cast_19[(((ax0_ax1_fused_ax2_fused_6*128) + (ax3_outer_3*64)) + ax3_inner_6)] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_6[ax3_inner_6] + placeholder_61[((ax3_outer_3*64) + ax3_inner_6)]), 1374050734, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int32\"), 1544713713, 31, 0, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", \"T.noalias\": True})\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_21 = T.match_buffer(T_cast_20, [289], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_7 = T.decl_buffer([157323], \"int16\")\n        for i0_i1_fused_7 in T.serial(0, 229):\n            for i2_7, i3_7 in T.grid(229, 3):\n                PaddedInput_7[(((i0_i1_fused_7*687) + (i2_7*3)) + i3_7)] = T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), placeholder_65[((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n            Conv2dOutput_7 = T.decl_buffer([64], \"int32\")\n            for ff_3 in T.serial(0, 64):\n                Conv2dOutput_7[ff_3] = 0\n                for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                    Conv2dOutput_7[ff_3] = (Conv2dOutput_7[ff_3] + (T.cast(PaddedInput_7[(((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)], \"int32\")*T.cast(placeholder_66[((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)], \"int32\")))\n            for ax3_inner_7 in T.serial(0, 64):\n                T_cast_21[((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_7[ax3_inner_7] + placeholder_67[ax3_inner_7]), 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1(placeholder_68: T.handle, placeholder_69: T.handle, placeholder_70: T.handle, T_cast_22: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", \"tir.noalias\": True})\n        placeholder_71 = T.match_buffer(placeholder_68, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_72 = T.match_buffer(placeholder_69, [110592], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_73 = T.match_buffer(placeholder_70, [192], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_23 = T.match_buffer(T_cast_22, [305], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_8 = T.decl_buffer([215296], \"int16\")\n        for i0_i1_fused_8 in T.serial(0, 58):\n            for i2_8, i3_8 in T.grid(58, 64):\n                PaddedInput_8[(((i0_i1_fused_8*3712) + (i2_8*64)) + i3_8)] = T.if_then_else(((((1 <= i0_i1_fused_8) and (i0_i1_fused_8 < 57)) and (1 <= i2_8)) and (i2_8 < 57)), placeholder_71[((((i0_i1_fused_8*3584) + (i2_8*64)) + i3_8) - 3648)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_8 in T.serial(0, 3136):\n            Conv2dOutput_8 = T.decl_buffer([64], \"int32\")\n            for ax3_outer_4 in T.serial(0, 3):\n                for ff_4 in T.serial(0, 64):\n                    Conv2dOutput_8[ff_4] = 0\n                    for ry_3, rx_3, rc_8 in T.grid(3, 3, 64):\n                        Conv2dOutput_8[ff_4] = (Conv2dOutput_8[ff_4] + (T.cast(PaddedInput_8[(((((T.floordiv(ax0_ax1_fused_ax2_fused_8, 56)*3712) + (ry_3*3712)) + (rx_3*64)) + (T.floormod(ax0_ax1_fused_ax2_fused_8, 56)*64)) + rc_8)], \"int32\")*T.cast(placeholder_72[(((((ry_3*36864) + (rx_3*12288)) + (rc_8*192)) + (ax3_outer_4*64)) + ff_4)], \"int32\")))\n                for ax3_inner_8 in T.serial(0, 64):\n                    T_cast_23[(((ax0_ax1_fused_ax2_fused_8*192) + (ax3_outer_4*64)) + ax3_inner_8)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_8[ax3_inner_8] + placeholder_73[((ax3_outer_4*64) + ax3_inner_8)]), 1139793473, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_32 = T.allocate([301056], \"int8\", \"global\")\n        sid_20 = T.allocate([150528], \"int8\", \"global\")\n        sid_6 = T.allocate([401408], \"int8\", \"global\")\n        sid_9 = T.allocate([301056], \"int8\", \"global\")\n        sid_7 = T.allocate([401408], \"int8\", \"global\")\n        sid_8 = T.allocate([802816], \"int8\", \"global\")\n        sid_2 = T.allocate([50176], \"int8\", \"global\")\n        sid_3 = T.allocate([301056], \"int8\", \"global\")\n        sid_19 = T.allocate([100352], \"int8\", \"global\")\n        sid_4 = T.allocate([150528], \"int8\", \"global\")\n        sid_5 = T.allocate([602112], \"int8\", \"global\")\n        sid_25 = T.allocate([25088], \"int8\", \"global\")\n        sid_26 = T.allocate([25088], \"int8\", \"global\")\n        sid_31 = T.allocate([25088], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8, sid_7, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", sid_7, T.lookup_param(\"p3\", dtype=\"handle\"), T.lookup_param(\"p4\", dtype=\"handle\"), sid_6, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_1\", sid_6, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), sid_5, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d\", sid_5, sid_4, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast\", sid_4, sid_3, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_2\", sid_3, T.lookup_param(\"p7\", dtype=\"handle\"), T.lookup_param(\"p8\", dtype=\"handle\"), sid_2, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", sid_3, T.lookup_param(\"p9\", dtype=\"handle\"), T.lookup_param(\"p10\", dtype=\"handle\"), sid_20, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320_\", sid_20, T.lookup_param(\"p11\", dtype=\"handle\"), T.lookup_param(\"p12\", dtype=\"handle\"), sid_19, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_2\", sid_3, T.lookup_param(\"p13\", dtype=\"handle\"), T.lookup_param(\"p14\", dtype=\"handle\"), sid_26, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__1\", sid_26, T.lookup_param(\"p15\", dtype=\"handle\"), T.lookup_param(\"p16\", dtype=\"handle\"), sid_25, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast_1\", sid_4, sid_32, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_fixed_point_multiply_cli_4464294615199028320__2\", sid_32, T.lookup_param(\"p17\", dtype=\"handle\"), T.lookup_param(\"p18\", dtype=\"handle\"), sid_31, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_concatenate\", sid_2, sid_19, sid_25, sid_31, output, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_inception_structure():\n    target = Target(\"c\")\n    global_ws_pool = WorkspacePoolInfo(\n        pool_name=\"global_workspace\",\n        targets=[target],\n    )\n    tir_mod = InceptionStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_ws_pool])\n    main_func = tir_mod[\"run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    assert buffer_info_analysis.memory_pressure == 1117718\n    buffer_info_map = _replace_stmt_with_buf_var_names(buffer_info_analysis.buffer_info_stmts)\n\n    # check conflicts\n    _verify_conflicts(\n        \"sid_3\",\n        [\n            \"sid_4\",\n            \"PaddedInput_2\",\n            \"sid_2\",\n            \"Conv2dOutput_2\",\n            \"PaddedInput_1\",\n            \"Conv2dOutput_1\",\n            \"sid_20\",\n            \"PaddedInput_6\",\n            \"Conv2dOutput_6\",\n            \"sid_19\",\n            \"PaddedInput_4\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput\",\n        [\n            \"sid_6\",\n            \"PaddedInput\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_7\",\n        [\n            \"PaddedInput_7\",\n            \"sid_8\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_4\",\n        [\n            \"sid_5\",\n            \"sid_3\",\n            \"PaddedInput_2\",\n            \"sid_2\",\n            \"Conv2dOutput_2\",\n            \"PaddedInput_1\",\n            \"Conv2dOutput_1\",\n            \"sid_20\",\n            \"PaddedInput_6\",\n            \"Conv2dOutput_6\",\n            \"sid_19\",\n            \"PaddedInput_4\",\n            \"Conv2dOutput_4\",\n            \"sid_26\",\n            \"PaddedInput_5\",\n            \"Conv2dOutput_5\",\n            \"sid_25\",\n            \"tensor_3\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_2\",\n        [\n            \"PaddedInput_2\",\n            \"sid_3\",\n            \"sid_4\",\n            \"Conv2dOutput_2\",\n            \"PaddedInput_1\",\n            \"Conv2dOutput_1\",\n            \"sid_20\",\n            \"PaddedInput_6\",\n            \"Conv2dOutput_6\",\n            \"sid_19\",\n            \"PaddedInput_4\",\n            \"Conv2dOutput_4\",\n            \"sid_26\",\n            \"PaddedInput_5\",\n            \"Conv2dOutput_5\",\n            \"sid_25\",\n            \"tensor_3\",\n            \"sid_32\",\n            \"PaddedInput_3\",\n            \"Conv2dOutput_3\",\n            \"sid_31\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_19\",\n        [\n            \"Conv2dOutput_6\",\n            \"sid_2\",\n            \"PaddedInput_6\",\n            \"sid_3\",\n            \"sid_4\",\n            \"PaddedInput_4\",\n            \"Conv2dOutput_4\",\n            \"sid_26\",\n            \"PaddedInput_5\",\n            \"Conv2dOutput_5\",\n            \"sid_25\",\n            \"tensor_3\",\n            \"sid_32\",\n            \"PaddedInput_3\",\n            \"Conv2dOutput_3\",\n            \"sid_31\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_2\",\n        [\n            \"sid_3\",\n            \"sid_4\",\n            \"sid_2\",\n            \"Conv2dOutput_2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_6\",\n        [\n            \"sid_2\",\n            \"PaddedInput_6\",\n            \"sid_3\",\n            \"sid_4\",\n            \"sid_19\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_9\",\n        [\n            \"PaddedInput_7\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_7\",\n        [\n            \"tensor_2\",\n            \"PaddedInput\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_4\",\n        [\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_3\",\n            \"sid_4\",\n            \"Conv2dOutput_4\",\n            \"sid_26\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_3\",\n        [\n            \"sid_2\",\n            \"sid_32\",\n            \"sid_25\",\n            \"sid_19\",\n            \"Conv2dOutput_3\",\n            \"sid_31\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_5\",\n        [\n            \"PaddedInput_8\",\n            \"Conv2dOutput_8\",\n            \"sid_4\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_31\",\n        [\n            \"Conv2dOutput_3\",\n            \"PaddedInput_3\",\n            \"sid_2\",\n            \"sid_25\",\n            \"sid_19\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput\",\n        [\n            \"sid_7\",\n            \"sid_6\",\n            \"Conv2dOutput\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_2\",\n        [\n            \"sid_2\",\n            \"PaddedInput_2\",\n            \"sid_3\",\n            \"sid_4\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_32\",\n        [\n            \"tensor_3\",\n            \"sid_2\",\n            \"sid_25\",\n            \"sid_19\",\n            \"PaddedInput_3\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"tensor_2\",\n        [\n            \"sid_8\",\n            \"sid_7\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_26\",\n        [\n            \"Conv2dOutput_4\",\n            \"PaddedInput_4\",\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_4\",\n            \"PaddedInput_5\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_3\",\n        [\n            \"PaddedInput_3\",\n            \"sid_2\",\n            \"sid_25\",\n            \"sid_19\",\n            \"sid_31\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_6\",\n        [\n            \"sid_2\",\n            \"sid_3\",\n            \"sid_20\",\n            \"sid_4\",\n            \"Conv2dOutput_6\",\n            \"sid_19\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_6\",\n        [\n            \"PaddedInput\",\n            \"Conv2dOutput\",\n            \"PaddedInput_8\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_8\",\n        [\n            \"sid_6\",\n            \"sid_5\",\n            \"Conv2dOutput_8\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_5\",\n        [\n            \"PaddedInput_5\",\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_4\",\n            \"sid_25\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_1\",\n        [\n            \"PaddedInput_1\",\n            \"sid_2\",\n            \"sid_3\",\n            \"sid_4\",\n            \"sid_20\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"tensor_3\",\n        [\n            \"sid_2\",\n            \"sid_25\",\n            \"sid_19\",\n            \"sid_4\",\n            \"sid_32\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_8\",\n        [\n            \"Conv2dOutput_7\",\n            \"PaddedInput_7\",\n            \"tensor_2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_20\",\n        [\n            \"Conv2dOutput_1\",\n            \"PaddedInput_1\",\n            \"sid_2\",\n            \"sid_3\",\n            \"sid_4\",\n            \"PaddedInput_6\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_8\",\n        [\n            \"sid_5\",\n            \"PaddedInput_8\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_1\",\n        [\n            \"sid_2\",\n            \"sid_3\",\n            \"sid_4\",\n            \"Conv2dOutput_1\",\n            \"sid_20\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"Conv2dOutput_4\",\n        [\n            \"PaddedInput_4\",\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_4\",\n            \"sid_26\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_25\",\n        [\n            \"PaddedInput_5\",\n            \"Conv2dOutput_5\",\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_4\",\n            \"tensor_3\",\n            \"sid_32\",\n            \"PaddedInput_3\",\n            \"Conv2dOutput_3\",\n            \"sid_31\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_7\",\n        [\n            \"sid_9\",\n            \"Conv2dOutput_7\",\n            \"sid_8\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"PaddedInput_5\",\n        [\n            \"sid_2\",\n            \"sid_19\",\n            \"sid_26\",\n            \"sid_4\",\n            \"Conv2dOutput_5\",\n            \"sid_25\",\n        ],\n        buffer_info_map,\n    )\n\n    # check sizes\n    assert buffer_info_map[\"sid_20\"].size_bytes == 150528\n    assert buffer_info_map[\"tensor_2\"].size_bytes == 200704\n    assert buffer_info_map[\"sid_5\"].size_bytes == 602112\n    assert buffer_info_map[\"sid_9\"].size_bytes == 301056\n    assert buffer_info_map[\"Conv2dOutput_3\"].size_bytes == 4\n    assert buffer_info_map[\"sid_26\"].size_bytes == 25088\n    assert buffer_info_map[\"Conv2dOutput_2\"].size_bytes == 256\n    assert buffer_info_map[\"PaddedInput_5\"].size_bytes == 28800\n    assert buffer_info_map[\"sid_8\"].size_bytes == 802816\n    assert buffer_info_map[\"Conv2dOutput_5\"].size_bytes == 4\n    assert buffer_info_map[\"sid_3\"].size_bytes == 301056\n    assert buffer_info_map[\"Conv2dOutput\"].size_bytes == 256\n    assert buffer_info_map[\"PaddedInput_3\"].size_bytes == 301056\n    assert buffer_info_map[\"sid_32\"].size_bytes == 301056\n    assert buffer_info_map[\"PaddedInput_8\"].size_bytes == 430592\n    assert buffer_info_map[\"sid_4\"].size_bytes == 150528\n    assert buffer_info_map[\"PaddedInput_7\"].size_bytes == 314646\n    assert buffer_info_map[\"sid_6\"].size_bytes == 401408\n    assert buffer_info_map[\"Conv2dOutput_8\"].size_bytes == 256\n    assert buffer_info_map[\"sid_25\"].size_bytes == 25088\n    assert buffer_info_map[\"PaddedInput\"].size_bytes == 401408\n    assert buffer_info_map[\"sid_7\"].size_bytes == 401408\n    assert buffer_info_map[\"Conv2dOutput_1\"].size_bytes == 4\n    assert buffer_info_map[\"Conv2dOutput_4\"].size_bytes == 4\n    assert buffer_info_map[\"PaddedInput_2\"].size_bytes == 301056\n    assert buffer_info_map[\"sid_31\"].size_bytes == 25088\n    assert buffer_info_map[\"PaddedInput_1\"].size_bytes == 301056\n    assert buffer_info_map[\"Conv2dOutput_6\"].size_bytes == 256\n    assert buffer_info_map[\"PaddedInput_4\"].size_bytes == 301056\n    assert buffer_info_map[\"sid_2\"].size_bytes == 50176\n    assert buffer_info_map[\"tensor_3\"].size_bytes == 150528\n    assert buffer_info_map[\"Conv2dOutput_7\"].size_bytes == 256\n    assert buffer_info_map[\"sid_19\"].size_bytes == 100352\n    assert buffer_info_map[\"PaddedInput_6\"].size_bytes == 172800\n\n\n# fmt: off\n@tvm.script.ir_module\nclass MultipleCallsToSamePrimFuncModule:\n    @T.prim_func\n    def tvmgen_default_fused_layout_transform_1(placeholder: T.handle, T_layout_trans: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_layout_transform_1\", \"tir.noalias\": True})\n        placeholder_1 = T.match_buffer(placeholder, [864], dtype=\"float32\")\n        T_layout_trans_1 = T.match_buffer(T_layout_trans, [41], dtype=\"float32\")\n        # body\n        for ax0_ax1_fused_ax2_fused, ax3, ax4_inner in T.grid(24, 12, 3):\n            T_layout_trans_1[ax0_ax1_fused_ax2_fused * 36 + ax3 * 3 + ax4_inner] = placeholder_1[ax4_inner * 288 + ax0_ax1_fused_ax2_fused * 12 + ax3]\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_contrib_conv2d_NCHWc(placeholder_2: T.handle, placeholder_3: T.handle, conv2d_NCHWc: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_nn_contrib_conv2d_NCHWc\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [864], dtype=\"float32\")\n        placeholder_5 = T.match_buffer(placeholder_3, [81], dtype=\"float32\")\n        conv2d_NCHWc_1 = T.match_buffer(conv2d_NCHWc, [41], dtype=\"float32\")\n        # body\n        data_pad = T.decl_buffer([1092], \"float32\")\n        for i0_i1_fused_i2_fused, i3, i4 in T.grid(26, 14, 3):\n            data_pad[i0_i1_fused_i2_fused * 42 + i3 * 3 + i4] = T.if_then_else(1 <= i0_i1_fused_i2_fused and i0_i1_fused_i2_fused < 25 and 1 <= i3 and i3 < 13, placeholder_4[i0_i1_fused_i2_fused * 36 + i3 * 3 + i4 - 39], T.float32(0), dtype=\"float32\")\n        for n_oc_chunk_fused_oh_fused in T.serial(0, 24):\n            conv2d_NCHWc_global = T.decl_buffer([36], \"float32\")\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 3] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 6] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 9] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 12] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 15] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 18] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 21] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 24] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 27] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 30] = T.float32(0)\n            for oc_block_c_init in T.serial(0, 3):\n                conv2d_NCHWc_global[oc_block_c_init + 33] = T.float32(0)\n            for kh, kw, ic_inner in T.grid(3, 3, 3):\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c] = conv2d_NCHWc_global[oc_block_c] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 3] = conv2d_NCHWc_global[oc_block_c + 3] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 3] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 6] = conv2d_NCHWc_global[oc_block_c + 6] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 6] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 9] = conv2d_NCHWc_global[oc_block_c + 9] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 9] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 12] = conv2d_NCHWc_global[oc_block_c + 12] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 12] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 15] = conv2d_NCHWc_global[oc_block_c + 15] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 15] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 18] = conv2d_NCHWc_global[oc_block_c + 18] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 18] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 21] = conv2d_NCHWc_global[oc_block_c + 21] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 21] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 24] = conv2d_NCHWc_global[oc_block_c + 24] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 24] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 27] = conv2d_NCHWc_global[oc_block_c + 27] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 27] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 30] = conv2d_NCHWc_global[oc_block_c + 30] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 30] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n                for oc_block_c in T.serial(0, 3):\n                    conv2d_NCHWc_global[oc_block_c + 33] = conv2d_NCHWc_global[oc_block_c + 33] + data_pad[kh * 42 + n_oc_chunk_fused_oh_fused * 42 + kw * 3 + ic_inner + 33] * placeholder_5[kh * 27 + kw * 9 + ic_inner * 3 + oc_block_c]\n            for ow_inner, oc_block in T.grid(12, 3):\n                conv2d_NCHWc_1[n_oc_chunk_fused_oh_fused * 36 + ow_inner * 3 + oc_block] = conv2d_NCHWc_global[ow_inner * 3 + oc_block]\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_softmax_add_add_multiply_add(placeholder_6: T.handle, placeholder_7: T.handle, placeholder_8: T.handle, placeholder_9: T.handle, placeholder_10: T.handle, T_add: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_nn_softmax_add_add_multiply_add\", \"tir.noalias\": True})\n        placeholder_11 = T.match_buffer(placeholder_6, [864], dtype=\"float32\")\n        placeholder_12 = T.match_buffer(placeholder_7, [864], dtype=\"float32\")\n        placeholder_13 = T.match_buffer(placeholder_8, [3], dtype=\"float32\")\n        placeholder_14 = T.match_buffer(placeholder_9, [3], dtype=\"float32\")\n        placeholder_15 = T.match_buffer(placeholder_10, [3], dtype=\"float32\")\n        T_add_1 = T.match_buffer(T_add, [864], dtype=\"float32\")\n        # body\n        for ax0_ax1_fused_ax2_fused in T.serial(0, 72):\n            T_softmax_norm = T.decl_buffer([12], \"float32\")\n            with T.decl_buffer([1], \"float32\") as T_softmax_maxelem:\n                T_softmax_maxelem[0] = T.float32(-3.4028234663852886e+38)\n                for k in T.serial(0, 12):\n                    T_softmax_maxelem[0] = T.max(T_softmax_maxelem[0], placeholder_11[ax0_ax1_fused_ax2_fused * 12 + k])\n                T_softmax_exp = T.decl_buffer([12], \"float32\")\n                for i3 in T.serial(0, 12):\n                    T_softmax_exp[i3] = T.exp(placeholder_11[ax0_ax1_fused_ax2_fused * 12 + i3] - T_softmax_maxelem[0], dtype=\"float32\")\n                T_softmax_expsum = T.decl_buffer([1], \"float32\")\n                T_softmax_expsum[0] = T.float32(0)\n                for k in T.serial(0, 12):\n                    T_softmax_expsum[0] = T_softmax_expsum[0] + T_softmax_exp[k]\n                for i3 in T.serial(0, 12):\n                    T_softmax_norm[i3] = T_softmax_exp[i3] / T_softmax_expsum[0]\n            for ax3 in T.serial(0, 12):\n                T_add_1[ax0_ax1_fused_ax2_fused * 12 + ax3] = (placeholder_12[ax0_ax1_fused_ax2_fused * 12 + ax3] + T_softmax_norm[ax3] + placeholder_13[T.floordiv(ax0_ax1_fused_ax2_fused, 24)]) * placeholder_14[T.floordiv(ax0_ax1_fused_ax2_fused, 24)] + placeholder_15[T.floordiv(ax0_ax1_fused_ax2_fused, 24)]\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_contrib_dense_pack_nn_relu(placeholder_16: T.handle, placeholder_17: T.handle, T_relu: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_nn_contrib_dense_pack_nn_relu\", \"tir.noalias\": True})\n        placeholder_18 = T.match_buffer(placeholder_16, [864], dtype=\"float32\")\n        placeholder_19 = T.match_buffer(placeholder_17, [144], dtype=\"float32\")\n        T_relu_1 = T.match_buffer(T_relu, [864], dtype=\"float32\")\n        # body\n        for ax1_outer_ax0_outer_fused in T.serial(0, 18):\n            compute = T.decl_buffer([48], \"float32\")\n            with T.decl_buffer([48], \"float32\") as compute_global:\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 6] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 12] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 18] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 24] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 30] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 36] = T.float32(0)\n                for x_c_init in T.serial(0, 6):\n                    compute_global[x_c_init + 42] = T.float32(0)\n                for k_outer in T.serial(0, 12):\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c] = compute_global[x_c] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 6] = compute_global[x_c + 6] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 12] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 12] = compute_global[x_c + 12] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 24] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 18] = compute_global[x_c + 18] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 36] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 24] = compute_global[x_c + 24] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 48] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 30] = compute_global[x_c + 30] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 60] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 36] = compute_global[x_c + 36] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 72] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                    for x_c in T.serial(0, 6):\n                        compute_global[x_c + 42] = compute_global[x_c + 42] + placeholder_18[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + k_outer + 84] * placeholder_19[T.floordiv(ax1_outer_ax0_outer_fused, 9) * 72 + k_outer * 6 + x_c]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner] = compute_global[x_inner_inner]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 6] = compute_global[x_inner_inner + 6]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 12] = compute_global[x_inner_inner + 12]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 18] = compute_global[x_inner_inner + 18]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 24] = compute_global[x_inner_inner + 24]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 30] = compute_global[x_inner_inner + 30]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 36] = compute_global[x_inner_inner + 36]\n                for x_inner_inner in T.serial(0, 6):\n                    compute[x_inner_inner + 42] = compute_global[x_inner_inner + 42]\n            for ax0_inner_inner, ax1_inner_inner in T.grid(8, 6):\n                T_relu_1[T.floormod(ax1_outer_ax0_outer_fused, 9) * 96 + ax0_inner_inner * 12 + T.floordiv(ax1_outer_ax0_outer_fused, 9) * 6 + ax1_inner_inner] = T.max(compute[ax0_inner_inner * 6 + ax1_inner_inner], T.float32(0))\n\n    @T.prim_func\n    def tvmgen_default_fused_reshape_1(placeholder_20: T.handle, T_reshape: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_reshape_1\", \"tir.noalias\": True})\n        placeholder_21 = T.match_buffer(placeholder_20, [864], dtype=\"float32\")\n        T_reshape_1 = T.match_buffer(T_reshape, [864], dtype=\"float32\")\n        # body\n        for ax0, ax1_inner in T.grid(72, 12):\n            T_reshape_1[ax0 * 12 + ax1_inner] = placeholder_21[ax0 * 12 + ax1_inner]\n\n    @T.prim_func\n    def tvmgen_default_fused_layout_transform(placeholder_22: T.handle, T_layout_trans_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_layout_transform\", \"tir.noalias\": True})\n        placeholder_23 = T.match_buffer(placeholder_22, [864], dtype=\"float32\")\n        T_layout_trans_3 = T.match_buffer(T_layout_trans_2, [864], dtype=\"float32\")\n        # body\n        for ax0_ax1_fused, ax2, ax3_inner in T.grid(3, 24, 12):\n            T_layout_trans_3[ax0_ax1_fused * 288 + ax2 * 12 + ax3_inner] = placeholder_23[ax2 * 36 + ax3_inner * 3 + ax0_ax1_fused]\n\n    @T.prim_func\n    def tvmgen_default_fused_reshape(placeholder_24: T.handle, T_reshape_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_reshape\", \"tir.noalias\": True})\n        placeholder_25 = T.match_buffer(placeholder_24, [864], dtype=\"float32\")\n        T_reshape_3 = T.match_buffer(T_reshape_2, [864], dtype=\"float32\")\n        # body\n        for ax0_ax1_fused, ax2, ax3_inner in T.grid(3, 24, 12):\n            T_reshape_3[ax0_ax1_fused * 288 + ax2 * 12 + ax3_inner] = placeholder_25[ax0_ax1_fused * 288 + ax2 * 12 + ax3_inner]\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_softmax_add(placeholder_26: T.handle, placeholder_27: T.handle, T_add_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"from_legacy_te_schedule\": True, \"global_symbol\": \"tvmgen_default_fused_nn_softmax_add\", \"tir.noalias\": True})\n        placeholder_28 = T.match_buffer(placeholder_26, [864], dtype=\"float32\")\n        placeholder_29 = T.match_buffer(placeholder_27, [864], dtype=\"float32\")\n        T_add_3 = T.match_buffer(T_add_2, [864], dtype=\"float32\")\n        # body\n        for ax0_ax1_fused_ax2_fused in T.serial(0, 72):\n            T_softmax_norm = T.decl_buffer([12], \"float32\")\n            with T.decl_buffer([1], \"float32\") as T_softmax_maxelem:\n                T_softmax_maxelem[0] = T.float32(-3.4028234663852886e+38)\n                for k in T.serial(0, 12):\n                    T_softmax_maxelem[0] = T.max(T_softmax_maxelem[0], placeholder_28[ax0_ax1_fused_ax2_fused * 12 + k])\n                T_softmax_exp= T.decl_buffer([12], \"float32\")\n                for i3 in T.serial(0, 12):\n                    T_softmax_exp[i3] = T.exp(placeholder_28[ax0_ax1_fused_ax2_fused * 12 + i3] - T_softmax_maxelem[0], dtype=\"float32\")\n                T_softmax_expsum = T.decl_buffer([1], \"float32\")\n                T_softmax_expsum[0] = T.float32(0)\n                for k in T.serial(0, 12):\n                    T_softmax_expsum[0] = T_softmax_expsum[0] + T_softmax_exp[k]\n                for i3 in T.serial(0, 12):\n                    T_softmax_norm[i3] = T_softmax_exp[i3] / T_softmax_expsum[0]\n            for ax3 in T.serial(0, 12):\n                T_add_3[ax0_ax1_fused_ax2_fused * 12 + ax3] = placeholder_29[ax0_ax1_fused_ax2_fused * 12 + ax3] + T_softmax_norm[ax3]\n\n    @T.prim_func\n    def run_model(data: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        data_buffer = T.match_buffer(data, [864], dtype=\"float32\", align=16)\n        output_buffer = T.match_buffer(output, [864], dtype=\"float32\", align=16)\n        # body\n        sid_11 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_5 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_10 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_6 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_8 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_2 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_7 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_3 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_12 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_4 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_18 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_19 = T.allocate([3456], \"int8\", \"global.workspace\")\n        sid_20 = T.allocate([3456], \"int8\", \"global.workspace\")\n\n        sid_21 = T.allocate_const([0,1,2,3,4,5,6,7,8,9], \"int8\", [10])\n        sid_22 = T.allocate_const([1], \"int8\", [1])\n        sid_23 = T.allocate_const([2,1], \"int8\", [3456])\n\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_layout_transform_1\", data_buffer.data, sid_23, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_contrib_conv2d_NCHWc\", sid_8, T.cast(T.lookup_param(\"p0\", dtype=\"handle\"), \"handle\"), sid_7, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_layout_transform\", sid_7, sid_6, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_reshape_1\", data_buffer.data, sid_12, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_contrib_dense_pack_nn_relu\", sid_12, T.cast(T.lookup_param(\"p1\", dtype=\"handle\"), \"handle\"), sid_11, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_reshape\", sid_11, sid_10, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_softmax_add_add_multiply_add\", sid_6, sid_10, T.cast(T.lookup_param(\"p2\", dtype=\"handle\"), \"handle\"), T.cast(T.lookup_param(\"p3\", dtype=\"handle\"), \"handle\"), T.cast(T.lookup_param(\"p4\", dtype=\"handle\"), \"handle\"), sid_5, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_layout_transform_1\", sid_5, sid_4, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_contrib_conv2d_NCHWc\", sid_4, T.cast(T.lookup_param(\"p5\", dtype=\"handle\"), \"handle\"), sid_3, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_layout_transform\", sid_3, sid_2, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_reshape_1\", sid_5, sid_20, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_contrib_dense_pack_nn_relu\", sid_20, T.cast(T.lookup_param(\"p6\", dtype=\"handle\"), \"handle\"), sid_19, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_reshape\", sid_19, sid_18, dtype=\"int32\"))\n        T.evaluate(T.tvm_call_cpacked(\"tvmgen_default_fused_nn_softmax_add\", sid_2, sid_18, output_buffer.data, dtype=\"int32\"))\n# fmt: on\n\n\ndef test_multiple_calls_to_same_primfunc():\n    target = Target(\"c\")\n    global_ws_pool = WorkspacePoolInfo(\n        pool_name=\"global_workspace\",\n        targets=[target],\n    )\n    global_const_pool = ConstantPoolInfo(\n        pool_name=\"global_constants\",\n        targets=[target],\n    )\n\n    tir_mod = MultipleCallsToSamePrimFuncModule\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(\n        tir_mod, [global_ws_pool], [global_const_pool]\n    )\n    main_func = tir_mod[\"run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    assert buffer_info_analysis.memory_pressure == 11424\n    buffer_info_map = _replace_stmt_with_buf_var_names(buffer_info_analysis.buffer_info_stmts)\n\n    # check conflicts\n    _verify_conflicts(\"sid_23\", [\"sid_22\", \"sid_21\"], buffer_info_map)\n    _verify_conflicts(\n        \"sid_6\",\n        [\n            \"sid_7\",\n            \"sid_12\",\n            \"compute\",\n            \"compute_global\",\n            \"sid_11\",\n            \"sid_10\",\n            \"T_softmax_exp\",\n            \"T_softmax_maxelem\",\n            \"sid_5\",\n            \"T_softmax_norm\",\n            \"T_softmax_expsum\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_exp\",\n        [\n            \"sid_10\",\n            \"sid_6\",\n            \"T_softmax_maxelem\",\n            \"sid_5\",\n            \"T_softmax_norm\",\n            \"T_softmax_expsum\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_expsum2\",\n        [\n            \"T_softmax_exp2\",\n            \"T_softmax_norm2\",\n            \"sid_18\",\n            \"T_softmax_maxelem2\",\n            \"sid_2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"compute\",\n        [\n            \"sid_12\",\n            \"sid_6\",\n            \"compute_global\",\n            \"sid_11\",\n            \"sid_19\",\n            \"sid_20\",\n            \"sid_2\",\n            \"compute_global\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"compute_global\",\n        [\n            \"compute\",\n            \"sid_12\",\n            \"sid_6\",\n            \"sid_11\",\n            \"compute\",\n            \"sid_19\",\n            \"sid_20\",\n            \"sid_2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_10\",\n        [\n            \"sid_11\",\n            \"sid_6\",\n            \"T_softmax_exp\",\n            \"T_softmax_maxelem\",\n            \"sid_5\",\n            \"T_softmax_norm\",\n            \"T_softmax_expsum\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_2\",\n        [\n            \"sid_3\",\n            \"sid_5\",\n            \"sid_20\",\n            \"sid_19\",\n            \"compute\",\n            \"compute_global\",\n            \"sid_18\",\n            \"T_softmax_norm2\",\n            \"T_softmax_exp2\",\n            \"T_softmax_maxelem2\",\n            \"T_softmax_expsum2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_5\",\n        [\n            \"T_softmax_maxelem\",\n            \"sid_10\",\n            \"T_softmax_exp\",\n            \"sid_6\",\n            \"T_softmax_norm\",\n            \"T_softmax_expsum\",\n            \"sid_4\",\n            \"data_pad\",\n            \"sid_3\",\n            \"conv2d_NCHWc_global\",\n            \"sid_2\",\n            \"sid_20\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_norm2\",\n        [\n            \"sid_18\",\n            \"sid_2\",\n            \"T_softmax_exp2\",\n            \"T_softmax_maxelem2\",\n            \"T_softmax_expsum2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_20\",\n        [\n            \"sid_2\",\n            \"sid_5\",\n            \"sid_19\",\n            \"compute\",\n            \"compute_global\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_expsum\",\n        [\n            \"sid_5\",\n            \"T_softmax_norm\",\n            \"T_softmax_maxelem\",\n            \"sid_10\",\n            \"T_softmax_exp\",\n            \"sid_6\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"data_pad\",\n        [\n            \"sid_8\",\n            \"conv2d_NCHWc_global\",\n            \"sid_7\",\n            \"sid_4\",\n            \"sid_5\",\n            \"sid_3\",\n            \"conv2d_NCHWc_global\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_19\",\n        [\n            \"sid_20\",\n            \"sid_2\",\n            \"compute\",\n            \"compute_global\",\n            \"sid_18\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"conv2d_NCHWc_global\",\n        [\n            \"data_pad\",\n            \"sid_7\",\n            \"sid_3\",\n            \"data_pad\",\n            \"sid_5\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_18\",\n        [\n            \"sid_19\",\n            \"sid_2\",\n            \"T_softmax_norm2\",\n            \"T_softmax_exp2\",\n            \"T_softmax_maxelem2\",\n            \"T_softmax_expsum2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_7\",\n        [\n            \"conv2d_NCHWc_global\",\n            \"data_pad\",\n            \"sid_6\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_exp2\",\n        [\n            \"T_softmax_norm2\",\n            \"sid_18\",\n            \"sid_2\",\n            \"T_softmax_maxelem2\",\n            \"T_softmax_expsum2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_4\",\n        [\n            \"sid_5\",\n            \"data_pad\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_maxelem\",\n        [\n            \"sid_10\",\n            \"T_softmax_exp\",\n            \"sid_6\",\n            \"sid_5\",\n            \"T_softmax_norm\",\n            \"T_softmax_expsum\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_maxelem2\",\n        [\n            \"T_softmax_exp2\",\n            \"T_softmax_norm2\",\n            \"sid_18\",\n            \"sid_2\",\n            \"T_softmax_expsum2\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_11\",\n        [\n            \"compute\",\n            \"sid_12\",\n            \"compute_global\",\n            \"sid_6\",\n            \"sid_10\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_12\",\n        [\n            \"sid_6\",\n            \"compute\",\n            \"compute_global\",\n            \"sid_11\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"T_softmax_norm\",\n        [\n            \"sid_5\",\n            \"T_softmax_maxelem\",\n            \"sid_10\",\n            \"T_softmax_exp\",\n            \"sid_6\",\n            \"T_softmax_expsum\",\n        ],\n        buffer_info_map,\n    )\n    _verify_conflicts(\n        \"sid_8\",\n        [\n            \"data_pad\",\n        ],\n        buffer_info_map,\n    )\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__] + sys.argv[1:])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_transform_convert_pool_allocations_to_offsets.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport sys\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\nfrom tvm.tir.usmp import utils as usmp_utils\nfrom tvm.target import Target\nfrom tvm import WorkspacePoolInfo, PoolInfoProperties\n\n\ndef _get_primfuncs_from_module(module):\n    primfuncs = list()\n    for gv, primfunc in module.functions.items():\n        primfuncs.append(primfunc)\n    return primfuncs\n\n\ndef assign_poolinfos_to_allocates_in_primfunc(primfunc, pool_infos):\n    \"\"\"Helper to assign poolinfos to allocate nodes in a tir.PrimFunc\"\"\"\n\n    def set_poolinfos(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            return tvm.tir.Allocate(\n                buffer_var=stmt.buffer_var,\n                dtype=stmt.dtype,\n                extents=stmt.extents,\n                condition=stmt.condition,\n                body=stmt.body,\n                annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: pool_infos},\n            )\n\n    return primfunc.with_body(stmt_functor.ir_transform(primfunc.body, None, set_poolinfos))\n\n\ndef assign_poolinfos_to_allocates_in_irmodule(mod, pool_infos):\n    \"\"\"Helper to assign poolinfos to allocate nodes in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = assign_poolinfos_to_allocates_in_primfunc(basefunc, pool_infos)\n    return ret\n\n\ndef _assign_targets_to_primfuncs_irmodule(mod, target):\n    \"\"\"Helper to assign target for PrimFunc in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = basefunc.with_attr(\"target\", target)\n    return ret\n\n\n# fmt: off\n@tvm.script.ir_module\nclass LinearStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_4, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_5, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(T_subtract_1, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", \"tir.noalias\": True})\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_65, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_66, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_67, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_21 = T.match_buffer(T_cast_20, [289], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(T_cast_21, [289], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_7_data = T.allocate([157323], \"int16\", \"global\")\n        PaddedInput_7 = T.buffer_decl(shape=[157323], dtype=\"int16\", data=PaddedInput_7_data)\n        for i0_i1_fused_7 in T.serial(0, 229):\n            for i2_7, i3_7 in T.grid(229, 3):\n                PaddedInput_7[(((i0_i1_fused_7*687) + (i2_7*3)) + i3_7)] = T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), placeholder_65[((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n            Conv2dOutput_7_data = T.allocate([64], \"int32\", \"global\")\n            Conv2dOutput_7 = T.buffer_decl(shape=[64], dtype=\"int32\", data=Conv2dOutput_7_data)\n            for ff_3 in T.serial(0, 64):\n                Conv2dOutput_7[ff_3] = 0\n                for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                    Conv2dOutput_7[ff_3] = (Conv2dOutput_7[ff_3] + (T.cast(PaddedInput_7[(((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)], \"int32\")*T.cast(placeholder_66[((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)], \"int32\")))\n            for ax3_inner_7 in T.serial(0, 64):\n                T_cast_21[((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_7[ax3_inner_7] + placeholder_67[ax3_inner_7]), 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(placeholder_29, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T.preflattened_buffer(T_cast_7, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2_data = T.allocate([200704], \"uint8\", \"global\")\n        tensor_2 = T.buffer_decl(shape=[200704], dtype=\"uint8\", data=tensor_2_data)\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_9 = T.allocate([301056], \"int8\", \"global\")\n        sid_8 = T.allocate([802816], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8, output, dtype=\"int32\"))\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass LinearStructurePlanned:\n    @T.prim_func\n    def __tvm_main__(input: T.handle, fast_memory_0_var: T.Ptr[T.uint8], slow_memory_1_var: T.Ptr[T.uint8], output: T.handle) -> None:\n        fast_memory_0_buffer_var = T.match_buffer(fast_memory_0_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        slow_memory_1_buffer_var = T.match_buffer(slow_memory_1_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_9_let: T.Ptr[T.int8] = T.address_of(slow_memory_1_buffer_var[1117472], dtype=\"handle\")\n        sid_8_let: T.Ptr[T.int8] = T.address_of(slow_memory_1_buffer_var[0], dtype=\"handle\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9_let, fast_memory_0_buffer_var.data, slow_memory_1_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9_let, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8_let, fast_memory_0_buffer_var.data, slow_memory_1_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8_let, output, fast_memory_0_buffer_var.data, slow_memory_1_buffer_var.data, dtype=\"int32\"))\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle, fast_memory_6_var: T.Ptr[T.uint8], slow_memory_7_var: T.Ptr[T.uint8]) -> None:\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\")\n        T.preflattened_buffer(placeholder_29, [802816], dtype=\"uint8\")\n        T_cast_7 = T.match_buffer(T_cast_6, [177], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_7, [177], dtype=\"int16\")\n        fast_memory_6_buffer_var = T.match_buffer(fast_memory_6_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(fast_memory_6_buffer_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        slow_memory_7_buffer_var = T.match_buffer(slow_memory_7_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(slow_memory_7_buffer_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        tensor_2_let = T.buffer_decl([200704], dtype=\"uint8\")\n        with T.let(tensor_2_let.data, T.address_of(fast_memory_6_buffer_var[0], dtype=\"handle\")):\n            for ax0_ax1_fused_4, ax2_4 in T.grid(56, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2_let[ax0_ax1_fused_4 * 3584 + ax2_4 * 64 + ax3_init] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2_let[ax0_ax1_fused_4 * 3584 + ax2_4 * 64 + ax3_2] = T.max(tensor_2_let[ax0_ax1_fused_4 * 3584 + ax2_4 * 64 + ax3_2], T.if_then_else(ax0_ax1_fused_4 * 2 + rv0_rv1_fused_1 // 3 < 112 and ax2_4 * 2 + rv0_rv1_fused_1 % 3 < 112, placeholder_29[ax0_ax1_fused_4 * 14336 + rv0_rv1_fused_1 // 3 * 7168 + ax2_4 * 128 + rv0_rv1_fused_1 % 3 * 64 + ax3_2], T.uint8(0), dtype=\"uint8\"))\n            for ax0_ax1_fused_5, ax2_5, ax3_3 in T.grid(56, 56, 64):\n                T_cast_7[ax0_ax1_fused_5 * 3584 + ax2_5 * 64 + ax3_3] = T.cast(tensor_2_let[ax0_ax1_fused_5 * 3584 + ax2_5 * 64 + ax3_3], \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle, fast_memory_2_var: T.Ptr[T.uint8], slow_memory_3_var: T.Ptr[T.uint8]) -> None:\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\")\n        T.preflattened_buffer(placeholder_4, [150528], dtype=\"uint8\")\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_5, [1], dtype=\"int16\")\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\")\n        T.preflattened_buffer(T_subtract_1, [452], dtype=\"int16\")\n        fast_memory_2_buffer_var = T.match_buffer(fast_memory_2_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(fast_memory_2_buffer_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        slow_memory_3_buffer_var = T.match_buffer(slow_memory_3_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(slow_memory_3_buffer_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        for ax0_ax1_fused_1, ax2_1, ax3_inner_1 in T.grid(224, 224, 3):\n            T_subtract_1[ax0_ax1_fused_1 * 672 + ax2_1 * 3 + ax3_inner_1] = T.cast(placeholder_4[ax0_ax1_fused_1 * 672 + ax2_1 * 3 + ax3_inner_1], \"int16\") - placeholder_5[0]\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle, fast_memory_4_var: T.Ptr[T.uint8], slow_memory_5_var: T.Ptr[T.uint8]) -> None:\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_65, [150528], dtype=\"int16\")\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_66, [9408], dtype=\"int16\")\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_67, [64], dtype=\"int32\")\n        T_cast_21 = T.match_buffer(T_cast_20, [289], dtype=\"uint8\")\n        T.preflattened_buffer(T_cast_21, [289], dtype=\"uint8\")\n        fast_memory_4_buffer_var = T.match_buffer(fast_memory_4_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(fast_memory_4_buffer_var, [200704], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        slow_memory_5_buffer_var = T.match_buffer(slow_memory_5_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(slow_memory_5_buffer_var, [1418528], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        PaddedInput_7_let = T.buffer_decl([157323], \"int16\")\n        with T.let(PaddedInput_7_let.data, T.address_of(slow_memory_5_buffer_var[802816], dtype=\"handle\")):\n            for i0_i1_fused_7, i2_7, i3_7 in T.grid(229, 229, 3):\n                PaddedInput_7_let[i0_i1_fused_7 * 687 + i2_7 * 3 + i3_7] = T.if_then_else(2 <= i0_i1_fused_7 and i0_i1_fused_7 < 226 and 2 <= i2_7 and i2_7 < 226, placeholder_65[i0_i1_fused_7 * 672 + i2_7 * 3 + i3_7 - 1350], T.int16(0), dtype=\"int16\")\n            for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n                Conv2dOutput_7_let = T.buffer_decl([64], \"int32\")\n                with T.let(Conv2dOutput_7_let.data, T.address_of(fast_memory_4_buffer_var[0], dtype=\"handle\")):\n                    for ff_3 in T.serial(0, 64):\n                        Conv2dOutput_7_let[ff_3] = 0\n                        for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                            Conv2dOutput_7_let[ff_3] = Conv2dOutput_7_let[ff_3] + T.cast(PaddedInput_7_let[ax0_ax1_fused_ax2_fused_7 // 112 * 1374 + ry_2 * 687 + ax0_ax1_fused_ax2_fused_7 % 112 * 6 + rx_2 * 3 + rc_7], \"int32\") * T.cast(placeholder_66[ry_2 * 1344 + rx_2 * 192 + rc_7 * 64 + ff_3], \"int32\")\n                    for ax3_inner_7 in T.serial(0, 64):\n                        T_cast_21[ax0_ax1_fused_ax2_fused_7 * 64 + ax3_inner_7] = T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_7_let[ax3_inner_7] + placeholder_67[ax3_inner_7], 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n# fmt: on\n\n\ndef test_mobilenet_subgraph():\n    target = Target(\"c\")\n    fast_memory_pool = WorkspacePoolInfo(\n        \"fast_memory\",\n        [target],\n        PoolInfoProperties(size_hint_bytes=200704),\n    )\n    slow_memory_pool = WorkspacePoolInfo(\n        \"slow_memory\",\n        [target],\n    )\n    tir_mod = LinearStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = assign_poolinfos_to_allocates_in_irmodule(\n        tir_mod, [fast_memory_pool, slow_memory_pool]\n    )\n    main_func = tir_mod[\"__tvm_main__\"]\n    buffer_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    buffer_info_map = buffer_analysis.buffer_info_stmts\n\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    buffer_info_arr = fcreate_array_bi(buffer_info_map)\n    fusmp_algo_greedy_by_size = tvm.get_global_func(\"tir.usmp.algo.greedy_by_size\")\n    buffer_pool_allocations = fusmp_algo_greedy_by_size(\n        buffer_info_arr, buffer_analysis.memory_pressure\n    )\n    fassign_stmt_pool_allocations = tvm.get_global_func(\"tir.usmp.AssignStmtPoolAllocations\")\n    pool_allocations = fassign_stmt_pool_allocations(buffer_info_map, buffer_pool_allocations)\n    tir_mod_with_offsets = tvm.tir.usmp.transform.convert_pool_allocations_to_offsets(\n        pool_allocations, emit_tvmscript_printable=True\n    )(tir_mod)\n\n    tir_mod_with_offsets_ref = LinearStructurePlanned\n\n    for gv, ref_func in tir_mod_with_offsets_ref.functions.items():\n        actual_func = tir_mod_with_offsets[gv.name_hint]\n        tvm.ir.assert_structural_equal(actual_func, ref_func)\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ResnetStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast(placeholder: T.handle, placeholder_1: T.handle, T_cast: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\", \"tir.noalias\": True})\n        placeholder_2 = T.match_buffer(placeholder, [360000], dtype=\"uint8\")\n        T.preflattened_buffer(placeholder_2, [360000], dtype=\"uint8\")\n        placeholder_3 = T.match_buffer(placeholder_1, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_3, [64], dtype=\"int32\")\n        T_cast_1 = T.match_buffer(T_cast, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_1, [215], dtype=\"int16\")\n        # body\n        for ax0_ax1_fused, ax2, ax3_outer, ax3_inner in T.grid(75, 75, 4, 16):\n            T_cast_1[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(T.cast(placeholder_2[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner], \"int32\") - 94, 1843157232, 31, 1, dtype=\"int32\") + placeholder_3[ax3_outer * 16 + ax3_inner], 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1(placeholder_10: T.handle, placeholder_11: T.handle, placeholder_12: T.handle, T_cast_4: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", \"tir.noalias\": True})\n        placeholder_13 = T.match_buffer(placeholder_10, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_13, [360000], dtype=\"int16\")\n        placeholder_14 = T.match_buffer(placeholder_11, [36864], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_14, [36864], dtype=\"int16\")\n        placeholder_15 = T.match_buffer(placeholder_12, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_15, [64], dtype=\"int32\")\n        T_cast_5 = T.match_buffer(T_cast_4, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_5, [215], dtype=\"int16\")\n        # body\n        PaddedInput_1_data = T.allocate([379456], \"int16\", \"global\")\n        PaddedInput_1 = T.buffer_decl(shape=[379456], dtype=\"int16\", data=PaddedInput_1_data)\n        for i0_i1_fused_1, i2_1, i3_1 in T.grid(77, 77, 64):\n            PaddedInput_1[i0_i1_fused_1 * 4928 + i2_1 * 64 + i3_1] = T.if_then_else(1 <= i0_i1_fused_1 and i0_i1_fused_1 < 76 and 1 <= i2_1 and i2_1 < 76, placeholder_13[i0_i1_fused_1 * 4800 + i2_1 * 64 + i3_1 - 4864], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_1 in T.serial(0, 5625):\n            Conv2dOutput_1_data = T.allocate([64], \"int32\", \"global\")\n            Conv2dOutput_1 = T.buffer_decl(shape=[64], dtype=\"int32\", data=Conv2dOutput_1_data)\n            for ff_1 in T.serial(0, 64):\n                Conv2dOutput_1[ff_1] = 0\n                for ry, rx, rc_1 in T.grid(3, 3, 64):\n                    Conv2dOutput_1[ff_1] = Conv2dOutput_1[ff_1] + T.cast(PaddedInput_1[T.floordiv(ax0_ax1_fused_ax2_fused_1, 75) * 4928 + ry * 4928 + rx * 64 + T.floormod(ax0_ax1_fused_ax2_fused_1, 75) * 64 + rc_1], \"int32\") * T.cast(placeholder_14[ry * 12288 + rx * 4096 + rc_1 * 64 + ff_1], \"int32\")\n            for ax3_inner_2 in T.serial(0, 64):\n                T_cast_5[ax0_ax1_fused_ax2_fused_1 * 64 + ax3_inner_2] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_1[ax3_inner_2] + placeholder_15[ax3_inner_2], 1608879842, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_(placeholder_16: T.handle, placeholder_17: T.handle, placeholder_18: T.handle, T_add: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_\", \"tir.noalias\": True})\n        placeholder_19 = T.match_buffer(placeholder_16, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_19, [360000], dtype=\"int16\")\n        placeholder_20 = T.match_buffer(placeholder_17, [16384], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_20, [16384], dtype=\"int16\")\n        placeholder_21 = T.match_buffer(placeholder_18, [256], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_21, [256], dtype=\"int32\")\n        T_add_1 = T.match_buffer(T_add, [407], dtype=\"int32\")\n        T.preflattened_buffer(T_add_1, [407], dtype=\"int32\")\n        # body\n        PaddedInput_2_data = T.allocate([360000], \"int16\", \"global\")\n        PaddedInput_2 = T.buffer_decl(shape=[360000], dtype=\"int16\", data=PaddedInput_2_data)\n        for i0_i1_fused_2, i2_2, i3_2 in T.grid(75, 75, 64):\n            PaddedInput_2[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2] = placeholder_19[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2]\n        for ax0_ax1_fused_ax2_fused_2 in T.serial(0, 5625):\n            Conv2dOutput_2_data = T.allocate([64], \"int32\", \"global\")\n            Conv2dOutput_2 = T.buffer_decl(shape=[64], dtype=\"int32\", data=Conv2dOutput_2_data)\n            for ax3_outer_1 in T.serial(0, 4):\n                for ff_2 in T.serial(0, 64):\n                    Conv2dOutput_2[ff_2] = 0\n                    for rc_2 in T.serial(0, 64):\n                        Conv2dOutput_2[ff_2] = Conv2dOutput_2[ff_2] + T.cast(PaddedInput_2[ax0_ax1_fused_ax2_fused_2 * 64 + rc_2], \"int32\") * T.cast(placeholder_20[rc_2 * 256 + ax3_outer_1 * 64 + ff_2], \"int32\")\n                for ax3_inner_3 in T.serial(0, 64):\n                    T_add_1[ax0_ax1_fused_ax2_fused_2 * 256 + ax3_outer_1 * 64 + ax3_inner_3] = T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_2[ax3_inner_3] + placeholder_21[ax3_outer_1 * 64 + ax3_inner_3], 1711626602, 31, -8, dtype=\"int32\") + 132, 255), 0), \"uint8\"), \"int32\") - 132, 2094289803, 31, -2, dtype=\"int32\") + 136\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_(placeholder_22: T.handle, placeholder_23: T.handle, placeholder_24: T.handle, placeholder_25: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_22, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_29, [360000], dtype=\"int16\")\n        placeholder_27 = T.match_buffer(placeholder_23, [16384], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_27, [16384], dtype=\"int16\")\n        placeholder_26 = T.match_buffer(placeholder_24, [256], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_26, [256], dtype=\"int32\")\n        placeholder_28 = T.match_buffer(placeholder_25, [1440000], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_28, [1440000], dtype=\"int32\")\n        T_cast_7 = T.match_buffer(T_cast_6, [407], dtype=\"uint8\")\n        T.preflattened_buffer(T_cast_7, [407], dtype=\"uint8\")\n        # body\n        PaddedInput_3_data = T.allocate([360000], \"int16\", \"global\")\n        PaddedInput_3 = T.buffer_decl(shape=[360000], dtype=\"int16\", data=PaddedInput_3_data)\n        for i0_i1_fused_3, i2_3, i3_3 in T.grid(75, 75, 64):\n            PaddedInput_3[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3] = placeholder_29[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3]\n        for ax0_ax1_fused_ax2_fused_3 in T.serial(0, 5625):\n            Conv2dOutput_3_data = T.allocate([64], \"int32\", \"global\")\n            Conv2dOutput_3 = T.buffer_decl(shape=[64], dtype=\"int32\", data=Conv2dOutput_3_data)\n            for ax3_outer_2 in T.serial(0, 4):\n                for ff_3 in T.serial(0, 64):\n                    Conv2dOutput_3[ff_3] = 0\n                    for rc_3 in T.serial(0, 64):\n                        Conv2dOutput_3[ff_3] = Conv2dOutput_3[ff_3] + T.cast(PaddedInput_3[ax0_ax1_fused_ax2_fused_3 * 64 + rc_3], \"int32\") * T.cast(placeholder_27[rc_3 * 256 + ax3_outer_2 * 64 + ff_3], \"int32\")\n                for ax3_inner_4 in T.serial(0, 64):\n                    T_cast_7[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_3[ax3_inner_4] + placeholder_26[ax3_outer_2 * 64 + ax3_inner_4], 1343014664, 31, -8, dtype=\"int32\") + 136, 255), 0), \"uint8\"), \"int32\") - 136, 1073903788, 31, 1, dtype=\"int32\") + placeholder_28[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4], 255), 0), \"uint8\")\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_2 = T.allocate([720000], \"int8\", \"global\")\n        sid_6 = T.allocate([5760000], \"int8\", \"global\")\n        sid_7 = T.allocate([720000], \"int8\", \"global\")\n        sid_8 = T.allocate([720000], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_2, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", sid_2, T.lookup_param(\"p3\", dtype=\"handle\"), T.lookup_param(\"p4\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", sid_8, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), sid_7, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_\", sid_7, T.lookup_param(\"p7\", dtype=\"handle\"), T.lookup_param(\"p8\", dtype=\"handle\"), sid_6, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_\", sid_2, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_6, output, dtype=\"int32\"))\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast(placeholder_4: T.handle, placeholder_5: T.handle, placeholder_6: T.handle, T_cast_2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", \"tir.noalias\": True})\n        placeholder_7 = T.match_buffer(placeholder_4, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_7, [360000], dtype=\"int16\")\n        placeholder_8 = T.match_buffer(placeholder_5, [4096], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_8, [4096], dtype=\"int16\")\n        placeholder_9 = T.match_buffer(placeholder_6, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_9, [64], dtype=\"int32\")\n        T_cast_3 = T.match_buffer(T_cast_2, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_3, [215], dtype=\"int16\")\n        # body\n        PaddedInput_data = T.allocate([360000], \"int16\", \"global\")\n        PaddedInput = T.buffer_decl([360000], \"int16\", data=PaddedInput_data)\n        for i0_i1_fused, i2, i3 in T.grid(75, 75, 64):\n            PaddedInput[i0_i1_fused * 4800 + i2 * 64 + i3] = placeholder_7[i0_i1_fused * 4800 + i2 * 64 + i3]\n        for ax0_ax1_fused_ax2_fused in T.serial(0, 5625):\n            Conv2dOutput_data = T.allocate([64], \"int32\", \"global\")\n            Conv2dOutput = T.buffer_decl([64], \"int32\", data=Conv2dOutput_data)\n            for ff in T.serial(0, 64):\n                Conv2dOutput[ff] = 0\n                for rc in T.serial(0, 64):\n                    Conv2dOutput[ff] = Conv2dOutput[ff] + T.cast(PaddedInput[ax0_ax1_fused_ax2_fused * 64 + rc], \"int32\") * T.cast(placeholder_8[rc * 64 + ff], \"int32\")\n            for ax3_inner_1 in T.serial(0, 64):\n                T_cast_3[ax0_ax1_fused_ax2_fused * 64 + ax3_inner_1] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput[ax3_inner_1] + placeholder_9[ax3_inner_1], 1843106743, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass ResnetStructurePlanned:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast(placeholder: T.handle, placeholder_1: T.handle, T_cast: T.handle, global_workspace_1_var: T.Ptr[T.uint8]) -> None:\n        placeholder_2 = T.match_buffer(placeholder, [360000], dtype=\"uint8\")\n        T.preflattened_buffer(placeholder_2, [360000], dtype=\"uint8\")\n        placeholder_3 = T.match_buffer(placeholder_1, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_3, [64], dtype=\"int32\")\n        T_cast_1 = T.match_buffer(T_cast, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_1, [215], dtype=\"int16\")\n        global_workspace_1_buffer_var = T.match_buffer(global_workspace_1_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(global_workspace_1_buffer_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        for ax0_ax1_fused, ax2, ax3_outer, ax3_inner in T.grid(75, 75, 4, 16):\n            T_cast_1[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(T.cast(placeholder_2[ax0_ax1_fused * 4800 + ax2 * 64 + ax3_outer * 16 + ax3_inner], \"int32\") - 94, 1843157232, 31, 1, dtype=\"int32\") + placeholder_3[ax3_outer * 16 + ax3_inner], 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_(placeholder_22: T.handle, placeholder_23: T.handle, placeholder_24: T.handle, placeholder_25: T.handle, T_cast_6: T.handle, global_workspace_5_var: T.Ptr[T.uint8]) -> None:\n        placeholder_29 = T.match_buffer(placeholder_22, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_29, [360000], dtype=\"int16\")\n        placeholder_27 = T.match_buffer(placeholder_23, [16384], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_27, [16384], dtype=\"int16\")\n        placeholder_26 = T.match_buffer(placeholder_24, [256], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_26, [256], dtype=\"int32\")\n        placeholder_28 = T.match_buffer(placeholder_25, [1440000], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_28, [1440000], dtype=\"int32\")\n        T_cast_7 = T.match_buffer(T_cast_6, [407], dtype=\"uint8\")\n        T.preflattened_buffer(T_cast_7, [407], dtype=\"uint8\")\n        global_workspace_5_buffer_var = T.match_buffer(global_workspace_5_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(global_workspace_5_buffer_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        PaddedInput_3_let = T.buffer_decl([360000], 'int16')\n        with T.let(PaddedInput_3_let.data, T.address_of(global_workspace_5_buffer_var[6480000], dtype=\"handle\")):\n            for i0_i1_fused_3, i2_3, i3_3 in T.grid(75, 75, 64):\n                PaddedInput_3_let[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3] = placeholder_29[i0_i1_fused_3 * 4800 + i2_3 * 64 + i3_3]\n            for ax0_ax1_fused_ax2_fused_3 in T.serial(0, 5625):\n                Conv2dOutput_3_let = T.buffer_decl([64], 'int32')\n                with T.let(Conv2dOutput_3_let.data, T.address_of(global_workspace_5_buffer_var[7200000], dtype=\"handle\")):\n                    for ax3_outer_2 in T.serial(0, 4):\n                        for ff_3 in T.serial(0, 64):\n                            Conv2dOutput_3_let[ff_3] = 0\n                            for rc_3 in T.serial(0, 64):\n                                Conv2dOutput_3_let[ff_3] = Conv2dOutput_3_let[ff_3] + T.cast(PaddedInput_3_let[ax0_ax1_fused_ax2_fused_3 * 64 + rc_3], \"int32\") * T.cast(placeholder_27[rc_3 * 256 + ax3_outer_2 * 64 + ff_3], \"int32\")\n                        for ax3_inner_4 in T.serial(0, 64):\n                            T_cast_7[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4] = T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_3_let[ax3_inner_4] + placeholder_26[ax3_outer_2 * 64 + ax3_inner_4], 1343014664, 31, -8, dtype=\"int32\") + 136, 255), 0), \"uint8\"), \"int32\") - 136, 1073903788, 31, 1, dtype=\"int32\") + placeholder_28[ax0_ax1_fused_ax2_fused_3 * 256 + ax3_outer_2 * 64 + ax3_inner_4], 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_(placeholder_16: T.handle, placeholder_17: T.handle, placeholder_18: T.handle, T_add: T.handle, global_workspace_4_var: T.Ptr[T.uint8]) -> None:\n        placeholder_19 = T.match_buffer(placeholder_16, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_19, [360000], dtype=\"int16\")\n        placeholder_20 = T.match_buffer(placeholder_17, [16384], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_20, [16384], dtype=\"int16\")\n        placeholder_21 = T.match_buffer(placeholder_18, [256], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_21, [256], dtype=\"int32\")\n        T_add_1 = T.match_buffer(T_add, [407], dtype=\"int32\")\n        T.preflattened_buffer(T_add_1, [407], dtype=\"int32\")\n        global_workspace_4_buffer_var = T.match_buffer(global_workspace_4_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(global_workspace_4_buffer_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        PaddedInput_2_let = T.buffer_decl([360000], \"int16\")\n        with T.let(PaddedInput_2_let.data, T.address_of(global_workspace_4_buffer_var[7200000], dtype=\"handle\")):\n            for i0_i1_fused_2, i2_2, i3_2 in T.grid(75, 75, 64):\n                PaddedInput_2_let[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2] = placeholder_19[i0_i1_fused_2 * 4800 + i2_2 * 64 + i3_2]\n            for ax0_ax1_fused_ax2_fused_2 in T.serial(0, 5625):\n                Conv2dOutput_2_let = T.buffer_decl([64], 'int32')\n                with T.let(Conv2dOutput_2_let.data, T.address_of(global_workspace_4_buffer_var[7920000], dtype=\"handle\")):\n                    for ax3_outer_1 in T.serial(0, 4):\n                        for ff_2 in T.serial(0, 64):\n                            Conv2dOutput_2_let[ff_2] = 0\n                            for rc_2 in T.serial(0, 64):\n                                Conv2dOutput_2_let[ff_2] = Conv2dOutput_2_let[ff_2] + T.cast(PaddedInput_2_let[ax0_ax1_fused_ax2_fused_2 * 64 + rc_2], \"int32\") * T.cast(placeholder_20[rc_2 * 256 + ax3_outer_1 * 64 + ff_2], \"int32\")\n                        for ax3_inner_3 in T.serial(0, 64):\n                            T_add_1[ax0_ax1_fused_ax2_fused_2 * 256 + ax3_outer_1 * 64 + ax3_inner_3] = T.q_multiply_shift(T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_2_let[ax3_inner_3] + placeholder_21[ax3_outer_1 * 64 + ax3_inner_3], 1711626602, 31, -8, dtype=\"int32\") + 132, 255), 0), \"uint8\"), \"int32\") - 132, 2094289803, 31, -2, dtype=\"int32\") + 136\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast(placeholder_4: T.handle, placeholder_5: T.handle, placeholder_6: T.handle, T_cast_2: T.handle, global_workspace_2_var: T.Ptr[T.uint8]) -> None:\n        placeholder_7 = T.match_buffer(placeholder_4, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_7, [360000], dtype=\"int16\")\n        placeholder_8 = T.match_buffer(placeholder_5, [4096], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_8, [4096], dtype=\"int16\")\n        placeholder_9 = T.match_buffer(placeholder_6, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_9, [64], dtype=\"int32\")\n        T_cast_3 = T.match_buffer(T_cast_2, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_3, [215], dtype=\"int16\")\n        global_workspace_2_buffer_var = T.match_buffer(global_workspace_2_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(global_workspace_2_buffer_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        PaddedInput_let = T.buffer_decl([360000], \"int16\")\n        with T.let(PaddedInput_let.data, T.address_of(global_workspace_2_buffer_var[7200000], dtype=\"handle\")):\n            for i0_i1_fused, i2, i3 in T.grid(75, 75, 64):\n                PaddedInput_let[i0_i1_fused * 4800 + i2 * 64 + i3] = placeholder_7[i0_i1_fused * 4800 + i2 * 64 + i3]\n            for ax0_ax1_fused_ax2_fused in T.serial(0, 5625):\n                Conv2dOutput_let = T.buffer_decl([64], \"int32\")\n                with T.let(Conv2dOutput_let.data, T.address_of(global_workspace_2_buffer_var[7920000], dtype=\"handle\")):\n                    for ff in T.serial(0, 64):\n                        Conv2dOutput_let[ff] = 0\n                        for rc in T.serial(0, 64):\n                            Conv2dOutput_let[ff] = Conv2dOutput_let[ff] + T.cast(PaddedInput_let[ax0_ax1_fused_ax2_fused * 64 + rc], \"int32\") * T.cast(placeholder_8[rc * 64 + ff], \"int32\")\n                    for ax3_inner_1 in T.serial(0, 64):\n                        T_cast_3[ax0_ax1_fused_ax2_fused * 64 + ax3_inner_1] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_let[ax3_inner_1] + placeholder_9[ax3_inner_1], 1843106743, 31, -6, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1(placeholder_10: T.handle, placeholder_11: T.handle, placeholder_12: T.handle, T_cast_4: T.handle, global_workspace_3_var: T.Ptr[T.uint8]) -> None:\n        placeholder_13 = T.match_buffer(placeholder_10, [360000], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_13, [360000], dtype=\"int16\")\n        placeholder_14 = T.match_buffer(placeholder_11, [36864], dtype=\"int16\")\n        T.preflattened_buffer(placeholder_14, [36864], dtype=\"int16\")\n        placeholder_15 = T.match_buffer(placeholder_12, [64], dtype=\"int32\")\n        T.preflattened_buffer(placeholder_15, [64], dtype=\"int32\")\n        T_cast_5 = T.match_buffer(T_cast_4, [215], dtype=\"int16\")\n        T.preflattened_buffer(T_cast_5, [215], dtype=\"int16\")\n        global_workspace_3_buffer_var = T.match_buffer(global_workspace_3_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        T.preflattened_buffer(global_workspace_3_buffer_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        PaddedInput_1_let = T.buffer_decl([379456], \"int16\")\n        with T.let(PaddedInput_1_let.data, T.address_of(global_workspace_3_buffer_var[0], dtype=\"handle\")):\n            for i0_i1_fused_1, i2_1, i3_1 in T.grid(77, 77, 64):\n                PaddedInput_1_let[i0_i1_fused_1 * 4928 + i2_1 * 64 + i3_1] = T.if_then_else(1 <= i0_i1_fused_1 and i0_i1_fused_1 < 76 and 1 <= i2_1 and i2_1 < 76, placeholder_13[i0_i1_fused_1 * 4800 + i2_1 * 64 + i3_1 - 4864], T.int16(0), dtype=\"int16\")\n            for ax0_ax1_fused_ax2_fused_1 in T.serial(0, 5625):\n                Conv2dOutput_1_let = T.buffer_decl([64], \"int32\")\n                with T.let(Conv2dOutput_1_let.data, T.address_of(global_workspace_3_buffer_var[7200000], dtype=\"handle\")):\n                    for ff_1 in T.serial(0, 64):\n                        Conv2dOutput_1_let[ff_1] = 0\n                        for ry, rx, rc_1 in T.grid(3, 3, 64):\n                            Conv2dOutput_1_let[ff_1] = Conv2dOutput_1_let[ff_1] + T.cast(PaddedInput_1_let[ax0_ax1_fused_ax2_fused_1 // 75 * 4928 + ry * 4928 + rx * 64 + ax0_ax1_fused_ax2_fused_1 % 75 * 64 + rc_1], \"int32\") * T.cast(placeholder_14[ry * 12288 + rx * 4096 + rc_1 * 64 + ff_1], \"int32\")\n                    for ax3_inner_2 in T.serial(0, 64):\n                        T_cast_5[ax0_ax1_fused_ax2_fused_1 * 64 + ax3_inner_2] = T.cast(T.cast(T.max(T.min(T.q_multiply_shift(Conv2dOutput_1_let[ax3_inner_2] + placeholder_15[ax3_inner_2], 1608879842, 31, -7, dtype=\"int32\"), 255), 0), \"uint8\"), \"int16\")\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, global_workspace_0_var: T.Ptr[T.uint8], output: T.handle) -> None:\n        global_workspace_0_buffer_var = T.match_buffer(global_workspace_0_var, [7920256], dtype=\"uint8\", strides=[1], elem_offset=0, align=16)\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_2_let: T.Ptr[T.int8] = T.address_of(global_workspace_0_buffer_var[5760000], dtype=\"handle\")\n        sid_6_let: T.Ptr[T.int8] = T.address_of(global_workspace_0_buffer_var[0], dtype=\"handle\")\n        sid_7_let: T.Ptr[T.int8] = T.address_of(global_workspace_0_buffer_var[6480000], dtype=\"handle\")\n        sid_8_let: T.Ptr[T.int8] = T.address_of(global_workspace_0_buffer_var[6480000], dtype=\"handle\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract_fixed_point_multiply_add_clip_cast_cast\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_2_let, global_workspace_0_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast\", sid_2_let, T.lookup_param(\"p3\", dtype=\"handle\"), T.lookup_param(\"p4\", dtype=\"handle\"), sid_8_let, global_workspace_0_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast_cast_1\", sid_8_let, T.lookup_param(\"p5\", dtype=\"handle\"), T.lookup_param(\"p6\", dtype=\"handle\"), sid_7_let, global_workspace_0_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_15934180698220515269_\", sid_7_let, T.lookup_param(\"p7\", dtype=\"handle\"), T.lookup_param(\"p8\", dtype=\"handle\"), sid_6_let, global_workspace_0_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_add_clip_cast_cast_subtract_fixed_point_4200876283395191415_\", sid_2_let, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_6_let, output, global_workspace_0_buffer_var.data, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_resnet_subgraph():\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n    tir_mod = ResnetStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_workspace_pool])\n    main_func = tir_mod[\"__tvm_main__\"]\n    buffer_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    buffer_info_map = buffer_analysis.buffer_info_stmts\n\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    buffer_info_arr = fcreate_array_bi(buffer_info_map)\n    fusmp_algo_greedy_by_size = tvm.get_global_func(\"tir.usmp.algo.greedy_by_size\")\n    buffer_pool_allocations = fusmp_algo_greedy_by_size(\n        buffer_info_arr, buffer_analysis.memory_pressure\n    )\n    fassign_stmt_pool_allocations = tvm.get_global_func(\"tir.usmp.AssignStmtPoolAllocations\")\n    pool_allocations = fassign_stmt_pool_allocations(buffer_info_map, buffer_pool_allocations)\n    tir_mod_with_offsets = tvm.tir.usmp.transform.convert_pool_allocations_to_offsets(\n        pool_allocations, emit_tvmscript_printable=True\n    )(tir_mod)\n\n    tir_mod_with_offsets_ref = ResnetStructurePlanned\n\n    for gv, ref_func in tir_mod_with_offsets_ref.functions.items():\n        actual_func = tir_mod_with_offsets[gv.name_hint]\n        tvm.ir.assert_structural_equal(actual_func, ref_func)\n\n\n@tvm.script.ir_module\nclass TensorIntrinStructure:\n    @T.prim_func\n    def tensor_intrin_primfunc() -> None:\n        dense_data = T.allocate([10], \"int32\", \"global\")\n        T.evaluate(\n            T.call_extern(\n                \"intrin_function\",\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"int32\"), dense_data, 0, 1, 2, dtype=\"handle\"\n                ),\n                dtype=\"int32\",\n            )\n        )\n\n        dense = T.buffer_decl([10], \"int32\", data=dense_data)\n        dense[0] = T.q_multiply_shift(dense[0], 1608879842, 31, -7, dtype=\"int32\")\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, output: T.handle) -> None:\n        T.evaluate(T.call_extern(\"tensor_intrin_primfunc\", dtype=\"int32\"))\n\n\n@tvm.script.ir_module\nclass TensorIntrinStructurePlanned:\n    @T.prim_func\n    def tensor_intrin_primfunc(global_workspace_1_var: T.Ptr[T.uint8]) -> None:\n        global_workspace_1_buffer_var = T.match_buffer(\n            global_workspace_1_var, [40], dtype=\"uint8\", strides=[1], elem_offset=0, align=16\n        )\n        T.preflattened_buffer(\n            global_workspace_1_buffer_var, [40], dtype=\"uint8\", strides=[1], elem_offset=0, align=16\n        )\n        dense_let = T.buffer_decl([10], \"int32\")\n        with T.let(dense_let.data, T.address_of(global_workspace_1_buffer_var[0], dtype=\"handle\")):\n            T.evaluate(\n                T.call_extern(\n                    \"intrin_function\",\n                    T.tvm_access_ptr(\n                        T.type_annotation(dtype=\"int32\"), dense_let.data, 0, 1, 2, dtype=\"handle\"\n                    ),\n                    dtype=\"int32\",\n                )\n            )\n            dense_let[0] = T.q_multiply_shift(dense_let[0], 1608879842, 31, -7, dtype=\"int32\")\n\n    @T.prim_func\n    def __tvm_main__(\n        input: T.handle, global_workspace_1_var: T.Ptr[T.uint8], output: T.handle\n    ) -> None:\n        global_workspace_1_buffer_var = T.match_buffer(\n            global_workspace_1_var, [40], dtype=\"uint8\", strides=[1], elem_offset=0, align=16\n        )\n        T.evaluate(\n            T.call_extern(\n                \"tensor_intrin_primfunc\", global_workspace_1_buffer_var.data, dtype=\"int32\"\n            )\n        )\n\n\ndef test_tensor_intrin():\n    target = Target(\"c\")\n    global_workspace_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n\n    tir_mod = TensorIntrinStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_workspace_pool])\n    main_func = tir_mod[\"__tvm_main__\"]\n    buffer_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    buffer_info_map = buffer_analysis.buffer_info_stmts\n\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    buffer_info_arr = fcreate_array_bi(buffer_info_map)\n    fusmp_algo_greedy_by_size = tvm.get_global_func(\"tir.usmp.algo.greedy_by_size\")\n    buffer_pool_allocations = fusmp_algo_greedy_by_size(\n        buffer_info_arr, buffer_analysis.memory_pressure\n    )\n    fassign_stmt_pool_allocations = tvm.get_global_func(\"tir.usmp.AssignStmtPoolAllocations\")\n    pool_allocations = fassign_stmt_pool_allocations(buffer_info_map, buffer_pool_allocations)\n    tir_mod_with_offsets = tvm.tir.usmp.transform.convert_pool_allocations_to_offsets(\n        pool_allocations, emit_tvmscript_printable=True\n    )(tir_mod)\n\n    expected = TensorIntrinStructurePlanned\n\n    for gv, ref_func in expected.functions.items():\n        actual_func = tir_mod_with_offsets[gv.name_hint]\n        tvm.ir.assert_structural_equal(actual_func, ref_func)\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__] + sys.argv[1:])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_transform_create_io_allocates.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nfrom typing import NamedTuple, List\n\nimport tvm\nfrom tvm.script import tir as T\n\n\n# fmt: off\n@tvm.script.ir_module\nclass SingleInputSingleOutput:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        input_buffer_var = T.match_buffer(input, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        output_buffer_var = T.match_buffer(output, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input_buffer_var.data, T.lookup_param(\"p0\", dtype=\"handle\"), output_buffer_var.data, dtype=\"int32\"))\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass TwoInputSingleOutput:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def __tvm_main__(input1: T.handle, input2: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        input1_buffer_var = T.match_buffer(input1, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        input2_buffer_var = T.match_buffer(input2, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        output_buffer_var = T.match_buffer(output, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input1_buffer_var.data, input2_buffer_var.data, output_buffer_var.data, dtype=\"int32\"))\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass TwoInputTwoOutput:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def __tvm_main__(input1: T.handle, input2: T.handle, output1: T.handle, output2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        input1_buffer_var = T.match_buffer(input1, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        input2_buffer_var = T.match_buffer(input2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        output1_buffer_var = T.match_buffer(output1, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        output2_buffer_var = T.match_buffer(output2, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input1_buffer_var.data, T.lookup_param(\"p0\", dtype=\"handle\"), output1_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input2_buffer_var.data, T.lookup_param(\"p1\", dtype=\"handle\"), output2_buffer_var.data, dtype=\"int32\"))\n# fmt: on\n\n\n# fmt: off\n@tvm.script.ir_module\nclass SingleInputTwoOutput:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def __tvm_main__(input: T.handle, output1: T.handle, output2: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"__tvm_main__\", \"runner_function\": True})\n        input_buffer_var = T.match_buffer(input, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        output1_buffer_var = T.match_buffer(output1, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        output2_buffer_var = T.match_buffer(output2, [452], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input_buffer_var.data, T.lookup_param(\"p0\", dtype=\"handle\"), output1_buffer_var.data, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input_buffer_var.data, T.lookup_param(\"p1\", dtype=\"handle\"), output2_buffer_var.data, dtype=\"int32\"))\n# fmt: on\n\n\nclass IOInfo(NamedTuple):\n    \"\"\"A data structure to hold test outputs per I/O tensor\"\"\"\n\n    name: str\n    shape: list\n    dtype: str\n\n\ndef check_io_allocations(mod: tvm.IRModule, inputs: List[IOInfo], outputs: List[IOInfo]):\n    \"\"\"This function checks whether outer most allocates correspond to I/O tensors\"\"\"\n    found_non_io_allocate_node = False\n\n    input_name_to_info = {}\n    for input in inputs:\n        input_name_to_info[input.name] = input\n    output_name_to_info = {}\n    for output in outputs:\n        output_name_to_info[output.name] = output\n\n    def _visit(stmt):\n        nonlocal found_non_io_allocate_node\n        if isinstance(stmt, tvm.tir.Allocate) and not found_non_io_allocate_node:\n            allocate = stmt\n            if dict(allocate.annotations).get(\"input_tensor\"):\n                input_tensor_name = str(dict(allocate.annotations).get(\"input_tensor\"))\n                assert input_tensor_name in input_name_to_info.keys()\n                assert input_name_to_info[input_tensor_name].shape == list(allocate.extents)\n                assert input_name_to_info[input_tensor_name].dtype == str(allocate.dtype)\n                del input_name_to_info[input_tensor_name]\n            if dict(allocate.annotations).get(\"output_tensor\"):\n                output_tensor_name = str(dict(allocate.annotations).get(\"output_tensor\"))\n                assert output_tensor_name in output_name_to_info.keys()\n                assert output_name_to_info[output_tensor_name].shape == list(allocate.extents)\n                assert output_name_to_info[output_tensor_name].dtype == str(allocate.dtype)\n                del output_name_to_info[output_tensor_name]\n        else:\n            found_non_io_allocate_node = True\n\n    main = mod[\"__tvm_main__\"]\n    tvm.tir.stmt_functor.ir_transform(main.body, _visit, None, [\"tir.Allocate\", \"tir.Call\"])\n    assert len(input_name_to_info) == 0\n    assert len(output_name_to_info) == 0\n\n\n@pytest.mark.parametrize(\n    \"test_mod, input_names, output_names\",\n    [\n        (\n            SingleInputSingleOutput,\n            [IOInfo(\"input\", [150528], \"uint8\")],\n            [IOInfo(\"output\", [452], \"int16\")],\n        ),\n        (\n            SingleInputTwoOutput,\n            [IOInfo(\"input\", [150528], \"uint8\")],\n            [IOInfo(\"output1\", [452], \"int16\"), IOInfo(\"output2\", [452], \"int16\")],\n        ),\n        (\n            TwoInputSingleOutput,\n            [IOInfo(\"input1\", [150528], \"uint8\"), IOInfo(\"input2\", [1], \"int16\")],\n            [IOInfo(\"output\", [452], \"int16\")],\n        ),\n        (\n            TwoInputTwoOutput,\n            [IOInfo(\"input1\", [150528], \"uint8\"), IOInfo(\"input2\", [150528], \"uint8\")],\n            [IOInfo(\"output1\", [452], \"int16\"), IOInfo(\"output2\", [452], \"int16\")],\n        ),\n    ],\n)\ndef test_mobilenet_subgraph(test_mod, input_names, output_names):\n    CreateAllocatesForIO = tvm.get_global_func(\"tir.usmp.transform.CreateAllocatesForIO\")\n    test_mod = CreateAllocatesForIO()(test_mod)\n    check_io_allocations(test_mod, input_names, output_names)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tir_usmp_utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nimport sys\n\nimport tvm\nfrom tvm.script import tir as T\nfrom tvm.tir import stmt_functor\nfrom tvm.tir.usmp import utils as usmp_utils\nfrom tvm.target import Target\nfrom tvm import WorkspacePoolInfo, PoolInfoProperties\n\n# fmt: off\n@tvm.script.ir_module\nclass LinearStructure:\n    @T.prim_func\n    def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_cast_subtract\", \"tir.noalias\": True})\n        placeholder_4 = T.match_buffer(placeholder_2, [150528], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_5 = T.match_buffer(placeholder_3, [1], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        T_subtract_1 = T.match_buffer(T_subtract, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        for ax0_ax1_fused_1 in T.serial(0, 224):\n            for ax2_1, ax3_inner_1 in T.grid(224, 3):\n                T_subtract_1[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)] = (T.cast(placeholder_4[(((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)], \"int16\") - placeholder_5[0])\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", \"tir.noalias\": True})\n        placeholder_65 = T.match_buffer(placeholder_62, [150528], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_66 = T.match_buffer(placeholder_63, [9408], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        placeholder_67 = T.match_buffer(placeholder_64, [64], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_21 = T.match_buffer(T_cast_20, [289], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        PaddedInput_7 = T.decl_buffer([157323], \"int16\")\n        for i0_i1_fused_7 in T.serial(0, 229):\n            for i2_7, i3_7 in T.grid(229, 3):\n                PaddedInput_7[(((i0_i1_fused_7*687) + (i2_7*3)) + i3_7)] = T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), placeholder_65[((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)], T.int16(0), dtype=\"int16\")\n        for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):\n            Conv2dOutput_7 = T.decl_buffer([64], \"int32\")\n            for ff_3 in T.serial(0, 64):\n                Conv2dOutput_7[ff_3] = 0\n                for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):\n                    Conv2dOutput_7[ff_3] = (Conv2dOutput_7[ff_3] + (T.cast(PaddedInput_7[(((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)], \"int32\")*T.cast(placeholder_66[((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)], \"int32\")))\n            for ax3_inner_7 in T.serial(0, 64):\n                T_cast_21[((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7)] = T.cast(T.max(T.min(T.q_multiply_shift((Conv2dOutput_7[ax3_inner_7] + placeholder_67[ax3_inner_7]), 1939887962, 31, -9, dtype=\"int32\"), 255), 0), \"uint8\")\n\n    @T.prim_func\n    def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [177], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2 = T.decl_buffer([200704], \"uint8\")\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    @T.prim_func\n    def tvmgen_default_run_model(input: T.handle, output: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_run_model\", \"runner_function\": True})\n        # body\n        T.attr(\"default\", \"device_id\", 0)\n        T.attr(\"default\", \"device_type\", 1)\n        sid_9 = T.allocate([301056], \"int8\", \"global\")\n        sid_8 = T.allocate([802816], \"int8\", \"global\")\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_cast_subtract\", input, T.lookup_param(\"p0\", dtype=\"handle\"), sid_9, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast\", sid_9, T.lookup_param(\"p1\", dtype=\"handle\"), T.lookup_param(\"p2\", dtype=\"handle\"), sid_8, dtype=\"int32\"))\n        T.evaluate(T.call_extern(\"tvmgen_default_fused_nn_max_pool2d_cast\", sid_8, output, dtype=\"int32\"))\n    __tvm_meta__ = None\n# fmt: on\n\n\ndef test_create_pool_info():\n    target = Target(\"c\")\n    pool_info = WorkspacePoolInfo(\n        \"foo_workspace\",\n        [target],\n    )\n    assert pool_info.pool_name == \"foo_workspace\"\n    # default pool size constraint\n    assert pool_info.size_hint_bytes == -1\n\n    pool_info = WorkspacePoolInfo(\n        \"bar_workspace\",\n        [target],\n        PoolInfoProperties(size_hint_bytes=1425),\n    )\n    assert pool_info.pool_name == \"bar_workspace\"\n    assert pool_info.size_hint_bytes == 1425\n\n\ndef test_create_buffer_info():\n    global_ws_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [Target(\"c\")],\n    )\n    buffer_info_obj = tvm.tir.usmp.BufferInfo(\n        name_hint=\"buf1\", size_bytes=256, pool_candidates=[global_ws_pool]\n    )\n    assert buffer_info_obj.name_hint == \"buf1\"\n    assert buffer_info_obj.size_bytes == 256\n    assert list(buffer_info_obj.pool_candidates) == [global_ws_pool]\n    # default workspace alignment\n    assert buffer_info_obj.alignment == 1\n\n    buffer_info_obj = tvm.tir.usmp.BufferInfo(\"buf2\", 512, [global_ws_pool], 8)\n    assert buffer_info_obj.name_hint == \"buf2\"\n    assert buffer_info_obj.size_bytes == 512\n    assert list(buffer_info_obj.pool_candidates) == [global_ws_pool]\n    assert buffer_info_obj.alignment == 8\n\n\ndef test_create_pool_allocation():\n    pool_info = WorkspacePoolInfo(\n        \"foo_workspace\",\n        [Target(\"c\")],\n    )\n    pool_allocation = usmp_utils.PoolAllocation(pool_info=pool_info, byte_offset=64)\n    assert pool_allocation.pool_info == pool_info\n    assert pool_allocation.byte_offset == 64\n\n\ndef _assign_poolinfos_to_allocates_in_primfunc(primfunc, pool_infos):\n    \"\"\"helper to assing poolinfos to allocate nodes in a tir.PrimFunc\"\"\"\n\n    def set_poolinfos(stmt):\n        if isinstance(stmt, tvm.tir.Allocate):\n            return tvm.tir.Allocate(\n                buffer_var=stmt.buffer_var,\n                dtype=stmt.dtype,\n                extents=stmt.extents,\n                condition=stmt.condition,\n                body=stmt.body,\n                annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: pool_infos},\n            )\n\n    return primfunc.with_body(stmt_functor.ir_transform(primfunc.body, None, set_poolinfos))\n\n\ndef _assign_poolinfos_to_allocates_in_irmodule(mod, pool_infos):\n    \"\"\"helper to assing poolinfos to allocate nodes in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = _assign_poolinfos_to_allocates_in_primfunc(basefunc, pool_infos)\n    return ret\n\n\ndef _assign_targets_to_primfuncs_irmodule(mod, target):\n    \"\"\"helper to assign target for PrimFunc in a IRModule\"\"\"\n    ret = tvm.IRModule()\n    for global_var, basefunc in mod.functions.items():\n        if isinstance(basefunc, tvm.tir.PrimFunc):\n            ret[global_var] = basefunc.with_attr(\"target\", target)\n    return ret\n\n\ndef test_create_array_buffer_info():\n    target = Target(\"c\")\n    global_ws_pool = WorkspacePoolInfo(\n        \"global_workspace\",\n        [target],\n    )\n    fcreate_array_bi = tvm.get_global_func(\"tir.usmp.CreateArrayBufferInfo\")\n    tir_mod = LinearStructure\n    tir_mod = _assign_targets_to_primfuncs_irmodule(tir_mod, target)\n    tir_mod = _assign_poolinfos_to_allocates_in_irmodule(tir_mod, [global_ws_pool])\n    main_func = tir_mod[\"tvmgen_default_run_model\"]\n    buffer_info_analysis = tvm.tir.usmp.analysis.extract_buffer_info(main_func, tir_mod)\n    buffer_info_array = fcreate_array_bi(buffer_info_analysis.buffer_info_stmts)\n    for buffer_info in buffer_info_array:\n        assert buffer_info in buffer_info_analysis.buffer_info_stmts.keys()\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__] + sys.argv[1:])\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_transform_layout.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport functools\nimport sys\nimport pytest\n\nimport numpy as np\n\nimport tvm\nimport tvm.testing\nfrom tvm import te\nfrom tvm.tir.stmt_functor import post_order_visit\nfrom tvm.driver.build_module import schedule_to_module\n\ndtype = tvm.testing.parameter(\"int32\")\n\n\ndef flatten_all_indices(preflatten_shape):\n    def mapping(*indices):\n        output = 0\n        for index, size in zip(indices, preflatten_shape):\n            output = output * size + index\n        return [output]\n\n    return mapping\n\n\ndef unpack_flattened_indices(preflatten_shape):\n    def mapping(i):\n        output = []\n        for dim in reversed(preflatten_shape):\n            output.append(i % dim)\n            i //= dim\n        return output[::-1]\n\n    return mapping\n\n\ndef traverse(s, op, callback):\n    visited = set()\n\n    def _traverse(op):\n        if op in visited:\n            return\n        visited.add(op)\n        for tensor in op.input_tensors:\n            _traverse(tensor.op)\n        callback(op)\n\n    _traverse(op)\n\n\nclass TestCompareAgainstExplicitReshape:\n    A_definition_style = tvm.testing.parameter(\n        \"explicit_reshape\",\n        \"transform_layout\",\n    )\n    B_definition_style = tvm.testing.parameter(\n        \"explicit_reshape\",\n        \"transform_layout\",\n    )\n\n    reordered_shape = tvm.testing.parameter((2, 3, 4))\n\n    @tvm.testing.fixture\n    def n_items(self, reordered_shape):\n        return functools.reduce(lambda x, y: x * y, reordered_shape, 1)\n\n    @tvm.testing.fixture\n    def fphysical_layout(self, reordered_shape):\n        return unpack_flattened_indices(reordered_shape)\n\n    @tvm.testing.fixture\n    def fcompute(self, A_definition_style, B_definition_style, reordered_shape, n_items, dtype):\n        assert A_definition_style in [\"explicit_reshape\", \"transform_layout\"]\n        assert B_definition_style in [\"explicit_reshape\", \"transform_layout\"]\n\n        def func():\n            if A_definition_style == \"explicit_reshape\":\n                A_input = te.placeholder(shape=reordered_shape, name=\"A_input\", dtype=dtype)\n                A = te.compute(\n                    shape=(n_items,),\n                    fcompute=lambda i: A_input[\n                        i // (reordered_shape[1] * reordered_shape[2]),\n                        (i // reordered_shape[2]) % reordered_shape[1],\n                        i % reordered_shape[2],\n                    ],\n                    name=\"A\",\n                )\n\n            elif A_definition_style == \"transform_layout\":\n                A = te.placeholder(shape=(n_items,), name=\"A\", dtype=dtype)\n                A_input = A\n\n            B = te.compute(shape=A.shape, fcompute=lambda i: A[i], name=\"B\")\n\n            if B_definition_style == \"explicit_reshape\":\n                B_output = te.compute(\n                    shape=reordered_shape,\n                    fcompute=lambda i, j, k: B[\n                        i * reordered_shape[1] * reordered_shape[2] + j * reordered_shape[2] + k\n                    ],\n                    name=\"B_output\",\n                )\n            elif B_definition_style == \"transform_layout\":\n                B_output = B\n\n            return A_input, B_output\n\n        return func\n\n    @tvm.testing.fixture\n    def fschedule(self, A_definition_style, B_definition_style, fphysical_layout):\n        def func(outs):\n            outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n            s = te.create_schedule([x.op for x in outs])\n\n            def callback(op):\n                if (op.name == \"A\" and A_definition_style == \"transform_layout\") or (\n                    op.name == \"B\" and B_definition_style == \"transform_layout\"\n                ):\n                    s[op].transform_layout(fphysical_layout)\n\n            traverse(s, outs[0].op, callback)\n            return s\n\n        return func\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_external_reshape(\n        self, target, dev, fcompute, fschedule, n_items, reordered_shape, dtype\n    ):\n        A, B = fcompute()\n        s = fschedule(B)\n\n        func = tvm.build(s, [A, B], target=target, name=\"copy_reshape\")\n\n        a_np = np.arange(n_items).reshape(reordered_shape).astype(dtype)\n        b_np = np.arange(n_items).reshape(reordered_shape).astype(dtype)\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.empty(b_np.shape, dtype=dtype, device=dev)\n\n        func(a, b)\n\n        tvm.testing.assert_allclose(b.numpy(), b_np)\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_internal_reshape(self, target, dev, n_items, reordered_shape, dtype, fphysical_layout):\n        # The reshaping of the buffer gets flattened away in\n        # StorageFlatten.  Therefore, testing the behavior by running only\n        # ApplyLayoutTransforms.\n        logical_shape = (n_items,)\n        A = te.placeholder(logical_shape, name=\"A\", dtype=dtype)\n        B = te.compute(shape=logical_shape, fcompute=lambda i: A[i], name=\"B\")\n        C = te.compute(shape=logical_shape, fcompute=lambda i: B[i], name=\"C\")\n\n        s = te.create_schedule(C.op)\n        s[B].transform_layout(fphysical_layout)\n\n        mod = schedule_to_module(s, [A, C])\n        body = mod[\"main\"].body\n\n        def walk_buffer_interactions(stmt, callback):\n            buffer_classes = [\n                tvm.tir.BufferLoad,\n                tvm.tir.BufferStore,\n                tvm.tir.BufferRealize,\n            ]\n\n            def inner(node):\n                if (type(node) in buffer_classes) and node.buffer.name == \"B\":\n                    callback(node)\n\n            post_order_visit(stmt, inner)\n\n        # All references to the buffer are the same object\n        def check_references():\n            buffer_object = None\n\n            def inner(node):\n                nonlocal buffer_object\n                if buffer_object is None:\n                    buffer_object = node.buffer\n                else:\n                    assert node.buffer.same_as(buffer_object)\n\n            return inner\n\n        # The buffer has the expected shape.\n        def check_shape(expected_shape):\n            def inner(node):\n                assert tuple(node.buffer.shape) == expected_shape\n\n            return inner\n\n        # Before the transform, the buffer should be in the logical shape.\n        walk_buffer_interactions(body, check_references())\n        walk_buffer_interactions(body, check_shape(logical_shape))\n\n        mod = tvm.tir.transform.ApplyLayoutTransforms()(mod)\n        body = mod[\"main\"].body\n\n        # After the transform, the buffer should be in the physical shape.\n        walk_buffer_interactions(body, check_references())\n        walk_buffer_interactions(body, check_shape(reordered_shape))\n\n\nclass Test2DPhysicalLayout:\n    transform_A = tvm.testing.parameter(\n        \"1d_A\",\n        \"2d_A\",\n        \"2d_rev_A\",\n        \"3d_A\",\n    )\n    transform_B = tvm.testing.parameter(\n        \"1d_B\",\n        \"2d_B\",\n        \"2d_rev_B\",\n        \"3d_B\",\n    )\n\n    @staticmethod\n    def extract_logical_indices(stmt):\n        output = {}\n\n        # Since the for loops can be reordered by the layout\n        # transformation, identify the loop corresponding to each\n        # pre-transformation axis based on the iteration extent.\n        def callback(node):\n            if isinstance(node, tvm.tir.For):\n                output[node.loop_var] = node.extent.value\n\n        post_order_visit(stmt, callback)\n        return sorted(output, key=output.get)\n\n    def get_transform(self, name):\n        name = name[:-2]\n        if name == \"1d\":\n            return None\n        elif name == \"2d\":\n            return lambda i, j, k: [i, j, te.AXIS_SEPARATOR, k]\n        elif name == \"2d_rev\":\n            return lambda i, j, k: [k, j, te.AXIS_SEPARATOR, i]\n        elif name == \"3d\":\n            return lambda i, j, k: [i, te.AXIS_SEPARATOR, j, te.AXIS_SEPARATOR, k]\n        else:\n            raise ValueError(f\"Unknown transformation: {name}\")\n\n    def transform_indices(self, name, logical_shape, logical_index_vars):\n        name = name[:-2]\n\n        i, j, k = logical_index_vars\n\n        if name == \"1d\":\n            return [i * (logical_shape[1] * logical_shape[2]) + j * logical_shape[2] + k]\n        elif name == \"2d\":\n            return [i * logical_shape[1] + j, k]\n        elif name == \"2d_rev\":\n            return [k * logical_shape[1] + j, i]\n        elif name == \"3d\":\n            return [i, j, k]\n        else:\n            raise ValueError(f\"Unknown transformation: {name}\")\n\n    def test_2d_physical(self, dtype, transform_A, transform_B):\n        logical_shape = (2, 3, 4)\n        A = te.placeholder(shape=logical_shape, dtype=dtype, name=\"A\")\n        B = te.compute(shape=A.shape, fcompute=lambda i, j, k: A[i, j, k], name=\"B\")\n\n        s = te.create_schedule(B.op)\n\n        func = self.get_transform(transform_A)\n        if func:\n            s[A].transform_layout(func)\n\n        func = self.get_transform(transform_B)\n        if func:\n            s[B].transform_layout(func)\n\n        # If the two buffers are accessed with the same indices, CSE\n        # will replace them with a Let binding.  Since this makes it\n        # harder to test what the transformed indices are, disabling\n        # the CSE pass for this test.\n        with tvm.transform.PassContext(disabled_pass=[\"tir.CommonSubexprElimTIR\"]):\n            mod = tvm.lower(s, [A, B])\n\n        logical_index_vars = self.extract_logical_indices(mod[\"main\"].body)\n        expected_indices_A = self.transform_indices(transform_A, logical_shape, logical_index_vars)\n        expected_indices_B = self.transform_indices(transform_B, logical_shape, logical_index_vars)\n\n        def callback(node):\n            if type(node) in [tvm.tir.BufferLoad, tvm.tir.BufferStore]:\n                name = node.buffer.name\n                if name == \"A\":\n                    expected_indices = expected_indices_A\n                elif name == \"B\":\n                    expected_indices = expected_indices_B\n                else:\n                    raise RuntimeError(f\"Unexpected buffer: {name}\")\n\n                tvm.ir.assert_structural_equal(expected_indices, node.indices)\n\n        post_order_visit(mod[\"main\"].body, callback)\n\n\nclass TestTransformedSchedules:\n    logical_shape = tvm.testing.parameter((4, 6, 40))\n\n    transform_names = [\n        None,\n        \"reverse\",\n        \"flatten_all\",\n        \"factor_last_by_4\",\n    ]\n\n    transform_A = tvm.testing.parameter(by_dict={f\"A_{t}\": t for t in transform_names})\n    transform_B = tvm.testing.parameter(\n        by_dict={f\"B_{t}\": t for t in transform_names if t is not None}\n    )\n\n    after_transform = tvm.testing.parameter(None)\n\n    def make_transform(self, logical_shape, transform_name):\n        if transform_name is None:\n            return lambda *indices: indices\n        elif transform_name == \"reverse\":\n            return lambda *indices: indices[::-1]\n        elif transform_name == \"flatten_all\":\n            return flatten_all_indices(logical_shape)\n        elif transform_name == \"factor_last_by_4\":\n            return lambda *indices, n: [*indices, n // 4, n % 4]\n        else:\n            raise NotImplementedError(f\"Unknown transformation {transform_name}\")\n\n    def make_transformed_shape(self, logical_shape, transform_name):\n        if transform_name is None:\n            return logical_shape\n        elif transform_name == \"reverse\":\n            return logical_shape[::-1]\n        elif transform_name == \"flatten_all\":\n            num_elements = functools.reduce(lambda x, y: x * y, logical_shape, 1)\n            return [num_elements]\n        elif transform_name == \"factor_last_by_4\":\n            *indices, n = logical_shape\n            return [*indices, n // 4, 4]\n        else:\n            raise NotImplementedError(f\"Unknown transformation {transform_name}\")\n\n    @tvm.testing.fixture\n    def expected_loop_order(self, logical_shape, transform_B, after_transform):\n        shape = self.make_transformed_shape(logical_shape, transform_B)\n\n        if after_transform == \"reorder\":\n            shape = shape[::-1]\n\n        elif after_transform == \"split\":\n            shape = [\n                *shape[:-1],\n                2,\n                shape[-1] // 2,\n            ]\n\n        elif after_transform == \"fuse\":\n            fused_size = shape[0] if transform_B == \"flatten_all\" else shape[0] * shape[1]\n            shape = [fused_size, *shape[2:]]\n\n        return shape\n\n    @tvm.testing.fixture\n    def schedule(self, logical_shape, dtype, transform_A, transform_B, after_transform):\n        A = te.placeholder(shape=logical_shape, dtype=dtype, name=\"A\")\n        B = te.compute(shape=A.shape, fcompute=lambda i, j, k: A[i, j, k], name=\"B\")\n\n        s = te.create_schedule(B.op)\n\n        if transform_A:\n            s[A].transform_layout(self.make_transform(logical_shape, transform_A))\n\n        iter_vars = s[B].transform_layout(self.make_transform(logical_shape, transform_B))\n        iter_vars = list(iter_vars)\n\n        if after_transform == \"reorder\":\n            s[B].reorder(*iter_vars[::-1])\n\n        elif after_transform == \"split\":\n            s[B].split(iter_vars[-1], nparts=2)\n\n        elif after_transform == \"fuse\":\n            to_fuse = iter_vars[:2]\n            s[B].fuse(*iter_vars[:2])\n\n        return {\n            \"schedule\": s,\n            \"tensors\": [A, B],\n            \"iter_vars\": iter_vars,\n        }\n\n    def compare_tir_loop_order(self, stmt, expected_loop_order):\n        def collect_loops(node):\n            output = []\n\n            def callback(node):\n                if isinstance(node, tvm.tir.For):\n                    output.append(node)\n\n            post_order_visit(node, callback)\n            return output[::-1]\n\n        loops = collect_loops(stmt)\n        loop_order = [loop.extent for loop in loops]\n\n        np.testing.assert_array_equal(loop_order, expected_loop_order)\n\n    def test_tir_loop_order(self, schedule, expected_loop_order):\n        func = tvm.lower(schedule[\"schedule\"], schedule[\"tensors\"])[\"main\"]\n        self.compare_tir_loop_order(func.body, expected_loop_order)\n\n    def test_te_loop_order(self, schedule, expected_loop_order):\n        s = schedule[\"schedule\"]\n        A, B = schedule[\"tensors\"]\n        iter_vars = schedule[\"iter_vars\"]\n\n        # No reduction axis, so all leaf_iter_vars are over the data\n        # array, and should have the new iteration variables.\n        extents = [int(iter_var.dom.extent) for iter_var in s[B].leaf_iter_vars]\n        np.testing.assert_array_equal(extents, expected_loop_order)\n\n        # layout_transform should return the new iteration variables.\n        extents = [int(iter_var.dom.extent) for iter_var in iter_vars]\n        np.testing.assert_array_equal(extents, expected_loop_order)\n\n    @pytest.mark.parametrize(\"after_transform\", [\"reorder\", \"split\", \"fuse\"])\n    def test_use_transformed_axes(\n        self, schedule, expected_loop_order, transform_A, transform_B, after_transform\n    ):\n        s = schedule[\"schedule\"]\n        A, B = schedule[\"tensors\"]\n\n        func = tvm.lower(s, [A, B])[\"main\"]\n        self.compare_tir_loop_order(func.body, expected_loop_order)\n\n\nclass TestTransformCache:\n    A_size = tvm.testing.parameter(16)\n\n    transform_A = tvm.testing.parameter(by_dict={\"transformA\": True, \"\": False})\n    transform_B = tvm.testing.parameter(by_dict={\"transformB\": True, \"\": False})\n    cache_A = tvm.testing.parameter(by_dict={\"cacheA\": True, \"\": False})\n    cache_B = tvm.testing.parameter(by_dict={\"cacheB\": True, \"\": False})\n\n    @tvm.testing.fixture\n    def schedule_args(self, target, A_size, transform_A, transform_B, cache_A, cache_B, dtype):\n        A = te.placeholder(shape=[A_size], dtype=dtype, name=\"A\")\n        B = te.compute(A.shape, lambda i: A[i], name=\"B\")\n        s = te.create_schedule(B.op)\n\n        requires_thread_bind = \"gpu\" in tvm.target.Target(target).keys\n        thread_x = te.thread_axis(\"threadIdx.x\")\n        thread_y = te.thread_axis(\"threadIdx.y\")\n        thread_z = te.thread_axis(\"threadIdx.z\")\n\n        if cache_A:\n            AA = s.cache_read(A, \"shared\", [B])\n            if requires_thread_bind:\n                s[AA].bind(AA.op.axis[0], thread_x)\n\n        if cache_B:\n            BB = s.cache_write(B, \"shared\")\n            if requires_thread_bind:\n                s[BB].bind(BB.op.axis[0], thread_y)\n\n        if transform_A:\n            A_axis = s[A].transform_layout(lambda i: [i // 4, i % 4])\n\n        if transform_B:\n            B_axis = s[B].transform_layout(lambda i: [i // 4, i % 4])\n        else:\n            B_axis = B.op.axis\n\n        if requires_thread_bind:\n            s[B].bind(B_axis[0], thread_z)\n\n        return [s, [A, B]]\n\n    @tvm.testing.fixture\n    def ref_data(self, A_size, dtype, transform_A, transform_B):\n        a_np = (100 * np.random.uniform(size=A_size)).astype(dtype)\n        b_np = a_np\n\n        if transform_A:\n            a_np = a_np.reshape((-1, 4))\n\n        if transform_B:\n            b_np = b_np.reshape((-1, 4))\n\n        return a_np, b_np\n\n    def test_lower(self, schedule_args):\n        tvm.lower(*schedule_args)\n\n    def test_execute(self, target, dev, schedule_args, ref_data, dtype):\n        func = tvm.build(*schedule_args, target=target)\n\n        a_np, b_np = ref_data\n        a = tvm.nd.array(a_np, dev)\n        b = tvm.nd.empty(b_np.shape, dtype=dtype, device=dev)\n\n        func(a, b)\n\n        if \"int\" in dtype:\n            np.testing.assert_equal(b.numpy(), b_np)\n        else:\n            tvm.testing.assert_allclose(b.numpy(), b_np)\n\n\ndef test_transform_with_reduction():\n    # To trigger this failure mode, the computation must use a\n    # reduction axis,\n    A = te.placeholder([16, 32, 64], dtype=\"float32\", name=\"A\")\n    k = te.reduce_axis((0, A.shape[-1]), name=\"k\")\n    B = te.compute(A.shape[:-1], lambda i, j: te.sum(A[i, j, k], axis=[k]))\n    s = te.create_schedule(B.op)\n\n    # And the output of the computation must have a layout\n    # transformation applied.\n    s[B].transform_layout(lambda i, j: [j, i])\n\n    # When present, the failure occurred during tvm.lower, during the\n    # call to `tvm::te::PassDownBitMaskOr`.\n    tvm.lower(s, [A, B])\n\n\nshape, transform = tvm.testing.parameters(\n    ([1, 8], lambda n, i: [i, n]),\n    ([1, 1, 8], lambda i, j, k: [j, te.AXIS_SEPARATOR, i, k]),\n    ([1, 1, 8], lambda i, j, k: [i, te.AXIS_SEPARATOR, j, k]),\n)\n\n\ndef test_size_one_buffer(shape, transform):\n    # This test is to catch a failure mode that occurred if a\n    # transformation were applied to a te.compute buffer, and one of\n    # the dimensions of the buffer was 1.  Prior to bugfix,\n    # arith::DetectIterMap would fold the variable as a constant,\n    # causing an error when attempting to solve for the variable using\n    # arith::InverseAffineIterMap.\n\n    dtype = \"int8\"\n    A = te.placeholder(shape, dtype, name=\"A\")\n    B = te.compute(\n        shape=A.shape,\n        fcompute=lambda *indices: A[indices].astype(dtype),\n        name=\"B\",\n    )\n    s = te.create_schedule(B.op)\n\n    # If layout transformation is on the output buffer, and any\n    # dimension of the output buffer is 1, failure occurs in\n    # CheckFusePattern.\n    s[B].transform_layout(transform)\n\n\ndef test_non_divisible_transform_raises_error():\n    A = te.placeholder([1, 3, 8, 8])\n    B = te.compute(A.shape, lambda *indices: A[indices])\n    s = te.create_schedule(B.op)\n\n    transform = lambda n, c, h, w: [n, c // 4, h, w, c % 4]\n    # Error occurs here, because the transformation would introduce\n    # padding.  Padded transforms are supported in TIR-based\n    # schedules.\n    with pytest.raises(tvm.TVMError):\n        s[B].transform_layout(transform)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvm_testing_before_after.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport tvm\nimport tvm.testing\nfrom tvm.script import tir as T, ir_module\n\n\nclass BaseBeforeAfter(tvm.testing.CompareBeforeAfter):\n    def transform(self):\n        return lambda x: x\n\n\nclass TestBeforeAfterPrimFunc(BaseBeforeAfter):\n    @T.prim_func\n    def before():\n        T.evaluate(0)\n\n    expected = before\n\n\nclass TestBeforeAfterMethod(BaseBeforeAfter):\n    def before(self):\n        @T.prim_func\n        def func():\n            T.evaluate(0)\n\n        return func\n\n    expected = before\n\n\nclass TestBeforeAfterFixture(BaseBeforeAfter):\n    @tvm.testing.fixture\n    def before(self):\n        @T.prim_func\n        def func():\n            T.evaluate(0)\n\n        return func\n\n    expected = before\n\n\nclass TestBeforeAfterDelayedPrimFunc(BaseBeforeAfter):\n    def before():\n        T.evaluate(0)\n\n    expected = before\n\n\nclass TestBeforeAfterParametrizedFixture(BaseBeforeAfter):\n    n = tvm.testing.parameter(1, 8, 16)\n\n    @tvm.testing.fixture\n    def before(self, n):\n        @T.prim_func\n        def func(A: T.Buffer[n, \"float32\"]):\n            for i in T.serial(n):\n                A[i] = 0.0\n\n        return func\n\n    expected = before\n\n\nclass TestBeforeAfterIRModule(BaseBeforeAfter):\n    \"\"\"The preferred form for writing TIR unit tests\n\n    All evaluation is done at test-time, with the minimal amount of\n    additional lines.  The `@tvm.testing.fixture`, `@ir_module`, and\n    `@T.prim_func` annotations are handled by\n    `tvm.testing.CompareBeforeAfter`.\n    \"\"\"\n\n    class before:\n        def func_A(A: T.Buffer[16, \"float32\"]):\n            for i in T.serial(16):\n                A[i] = 0.0\n\n        def func_B(A: T.Buffer[16, \"int32\"]):\n            for i in T.serial(16):\n                A[i] = 42\n\n    expected = before\n\n\nclass TestBeforeAfterIRModuleExplicitFixture(BaseBeforeAfter):\n    \"\"\"Like TestBeforeAfterIRModule, but with an explicit fixture\n\n    If the IRModule depends on additional fixtures, this form can be\n    used.\n    \"\"\"\n\n    @tvm.testing.fixture\n    def before(self):\n        @ir_module\n        class mod:\n            @T.prim_func\n            def func_A(A: T.Buffer[16, \"float32\"]):\n                for i in T.serial(16):\n                    A[i] = 0.0\n\n            @T.prim_func\n            def func_B(A: T.Buffer[16, \"int32\"]):\n                for i in T.serial(16):\n                    A[i] = 42\n\n        return mod\n\n    expected = before\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvm_testing_features.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport sys\n\nimport pytest\n\nimport tvm.testing\n\n# This file tests features in tvm.testing, such as verifying that\n# cached fixtures are run an appropriate number of times.  As a\n# result, the order of the tests is important.  Use of --last-failed\n# or --failed-first while debugging this file is not advised.  If\n# these tests are distributed/parallelized using pytest-xdist or\n# similar, all tests in this file should run sequentially on the same\n# node.  (See https://stackoverflow.com/a/59504228)\n\n\nclass TestTargetAutoParametrization:\n    targets_used = []\n    devices_used = []\n    enabled_targets = [target for target, dev in tvm.testing.enabled_targets()]\n    enabled_devices = [dev for target, dev in tvm.testing.enabled_targets()]\n\n    def test_target_parametrization(self, target):\n        assert target in self.enabled_targets\n        self.targets_used.append(target)\n\n    def test_device_parametrization(self, dev):\n        assert dev in self.enabled_devices\n        self.devices_used.append(dev)\n\n    def test_all_targets_used(self):\n        assert sorted(self.targets_used) == sorted(self.enabled_targets)\n\n    def test_all_devices_used(self):\n        sort_key = lambda dev: (dev.device_type, dev.device_id)\n        assert sorted(self.devices_used, key=sort_key) == sorted(self.enabled_devices, key=sort_key)\n\n    targets_with_explicit_list = []\n\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_explicit_list(self, target):\n        assert target == \"llvm\"\n        self.targets_with_explicit_list.append(target)\n\n    def test_no_repeats_in_explicit_list(self):\n        if tvm.testing.device_enabled(\"llvm\"):\n            assert self.targets_with_explicit_list == [\"llvm\"]\n        else:\n            assert self.targets_with_explicit_list == []\n\n    targets_with_exclusion = []\n\n    @tvm.testing.exclude_targets(\"llvm\")\n    def test_exclude_target(self, target):\n        assert \"llvm\" not in target\n        self.targets_with_exclusion.append(target)\n\n    def test_all_nonexcluded_targets_ran(self):\n        assert sorted(self.targets_with_exclusion) == sorted(\n            [target for target in self.enabled_targets if not target.startswith(\"llvm\")]\n        )\n\n    run_targets_with_known_failure = []\n\n    @tvm.testing.known_failing_targets(\"llvm\")\n    def test_known_failing_target(self, target):\n        # This test runs for all targets, but intentionally fails for\n        # llvm.  The behavior is working correctly if this test shows\n        # up as an expected failure, xfail.\n        self.run_targets_with_known_failure.append(target)\n        assert \"llvm\" not in target\n\n    def test_all_targets_ran(self):\n        assert sorted(self.run_targets_with_known_failure) == sorted(self.enabled_targets)\n\n    @tvm.testing.known_failing_targets(\"llvm\")\n    @tvm.testing.parametrize_targets(\"llvm\")\n    def test_known_failing_explicit_list(self, target):\n        assert target != \"llvm\"\n\n\nclass TestJointParameter:\n    param1_vals = [1, 2, 3]\n    param2_vals = [\"a\", \"b\", \"c\"]\n\n    independent_usages = 0\n    param1 = tvm.testing.parameter(*param1_vals)\n    param2 = tvm.testing.parameter(*param2_vals)\n\n    joint_usages = 0\n    joint_param_vals = list(zip(param1_vals, param2_vals))\n    joint_param_ids = [\"apple\", \"pear\", \"banana\"]\n    joint_param1, joint_param2 = tvm.testing.parameters(*joint_param_vals, ids=joint_param_ids)\n\n    def test_using_independent(self, param1, param2):\n        type(self).independent_usages += 1\n\n    def test_independent(self):\n        assert self.independent_usages == len(self.param1_vals) * len(self.param2_vals)\n\n    def test_using_joint(self, joint_param1, joint_param2):\n        type(self).joint_usages += 1\n        assert (joint_param1, joint_param2) in self.joint_param_vals\n\n    def test_joint(self):\n        assert self.joint_usages == len(self.joint_param_vals)\n\n    def test_joint_test_id(self, joint_param1, joint_param2, request):\n        param_string = (\n            request.node.name.replace(request.node.originalname, \"\")\n            .replace(\"[\", \"\")\n            .replace(\"]\", \"\")\n        )\n        assert param_string in self.joint_param_ids\n\n\nclass TestFixtureCaching:\n    param1_vals = [1, 2, 3]\n    param2_vals = [\"a\", \"b\", \"c\"]\n\n    param1 = tvm.testing.parameter(*param1_vals)\n    param2 = tvm.testing.parameter(*param2_vals)\n\n    uncached_calls = 0\n    cached_calls = 0\n\n    @tvm.testing.fixture\n    def uncached_fixture(self, param1):\n        type(self).uncached_calls += 1\n        return 2 * param1\n\n    def test_use_uncached(self, param1, param2, uncached_fixture):\n        assert 2 * param1 == uncached_fixture\n\n    def test_uncached_count(self):\n        assert self.uncached_calls == len(self.param1_vals) * len(self.param2_vals)\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def cached_fixture(self, param1):\n        type(self).cached_calls += 1\n        return 3 * param1\n\n    def test_use_cached(self, param1, param2, cached_fixture):\n        assert 3 * param1 == cached_fixture\n\n    def test_cached_count(self):\n        cache_disabled = bool(int(os.environ.get(\"TVM_TEST_DISABLE_CACHE\", \"0\")))\n        if cache_disabled:\n            assert self.cached_calls == len(self.param1_vals) * len(self.param2_vals)\n        else:\n            assert self.cached_calls == len(self.param1_vals)\n\n\nclass TestCachedFixtureIsCopy:\n    param = tvm.testing.parameter(1, 2, 3, 4)\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def cached_mutable_fixture(self):\n        return {\"val\": 0}\n\n    def test_modifies_fixture(self, param, cached_mutable_fixture):\n        assert cached_mutable_fixture[\"val\"] == 0\n\n        # The tests should receive a copy of the fixture value.  If\n        # the test receives the original and not a copy, then this\n        # will cause the next parametrization to fail.\n        cached_mutable_fixture[\"val\"] = param\n\n\nclass TestBrokenFixture:\n    # Tests that use a fixture that throws an exception fail, and are\n    # marked as setup failures.  The tests themselves are never run.\n    # This behavior should be the same whether or not the fixture\n    # results are cached.\n\n    num_uses_broken_uncached_fixture = 0\n    num_uses_broken_cached_fixture = 0\n\n    @tvm.testing.fixture\n    def broken_uncached_fixture(self):\n        raise RuntimeError(\"Intentionally broken fixture\")\n\n    @pytest.mark.xfail(True, reason=\"Broken fixtures should result in a failing setup\", strict=True)\n    def test_uses_broken_uncached_fixture(self, broken_uncached_fixture):\n        type(self).num_uses_broken_fixture += 1\n\n    def test_num_uses_uncached(self):\n        assert self.num_uses_broken_uncached_fixture == 0\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def broken_cached_fixture(self):\n        raise RuntimeError(\"Intentionally broken fixture\")\n\n    @pytest.mark.xfail(True, reason=\"Broken fixtures should result in a failing setup\", strict=True)\n    def test_uses_broken_cached_fixture(self, broken_cached_fixture):\n        type(self).num_uses_broken_cached_fixture += 1\n\n    def test_num_uses_cached(self):\n        assert self.num_uses_broken_cached_fixture == 0\n\n\nclass TestAutomaticMarks:\n    @staticmethod\n    def check_marks(request, target):\n        decorators = tvm.testing.plugin._target_to_requirement(target)\n        required_marks = [decorator.mark for decorator in decorators]\n        applied_marks = list(request.node.iter_markers())\n\n        for required_mark in required_marks:\n            assert required_mark in applied_marks\n\n    def test_automatic_fixture(self, request, target):\n        self.check_marks(request, target)\n\n    @tvm.testing.parametrize_targets\n    def test_bare_parametrize(self, request, target):\n        self.check_marks(request, target)\n\n    @tvm.testing.parametrize_targets(\"llvm\", \"cuda\", \"vulkan\")\n    def test_explicit_parametrize(self, request, target):\n        self.check_marks(request, target)\n\n    @pytest.mark.parametrize(\"target\", [\"llvm\", \"cuda\", \"vulkan\"])\n    def test_pytest_mark(self, request, target):\n        self.check_marks(request, target)\n\n    @pytest.mark.parametrize(\"target,other_param\", [(\"llvm\", 0), (\"cuda\", 1), (\"vulkan\", 2)])\n    def test_pytest_mark_covariant(self, request, target, other_param):\n        self.check_marks(request, target)\n\n\n@pytest.mark.skipif(\n    bool(int(os.environ.get(\"TVM_TEST_DISABLE_CACHE\", \"0\"))),\n    reason=\"Cannot test cache behavior while caching is disabled\",\n)\nclass TestCacheableTypes:\n    class EmptyClass:\n        pass\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def uncacheable_fixture(self):\n        return self.EmptyClass()\n\n    def test_uses_uncacheable(self, request):\n        # Normally the num_tests_use_this_fixture would be set before\n        # anything runs.  For this test case only, because we are\n        # delaying the use of the fixture, we need to manually\n        # increment it.\n        self.uncacheable_fixture.num_tests_use_this_fixture[0] += 1\n        with pytest.raises(TypeError):\n            request.getfixturevalue(\"uncacheable_fixture\")\n\n    class ImplementsReduce:\n        def __reduce__(self):\n            return super().__reduce__()\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def fixture_with_reduce(self):\n        return self.ImplementsReduce()\n\n    def test_uses_reduce(self, fixture_with_reduce):\n        pass\n\n    class ImplementsDeepcopy:\n        def __deepcopy__(self, memo):\n            return type(self)()\n\n    @tvm.testing.fixture(cache_return_value=True)\n    def fixture_with_deepcopy(self):\n        return self.ImplementsDeepcopy()\n\n    def test_uses_deepcopy(self, fixture_with_deepcopy):\n        pass\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_complete.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.ir import Range\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\n@T.prim_func\ndef matmul_original(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j in T.grid(32, 32):\n        with T.block(\"init\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            for ii, jj in T.grid(4, 4):\n                C[vi * 4 + ii, vj * 4 + jj] = T.float32(0)\n\n        for k in range(0, 32):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                for ii, jj, kk in T.grid(4, 4, 4):\n                    C[vi * 4 + ii, vj * 4 + jj] = (\n                        C[vi * 4 + ii, vj * 4 + jj]\n                        + A[vi * 4 + ii, vk * 4 + kk] * B[vj * 4 + jj, vk * 4 + kk]\n                    )\n\n\n@T.prim_func\ndef elementwise_with_root(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    with T.block():\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] + T.float32(1)\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\ndef func_with_opaque_block(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    with T.block():\n        with T.block():\n            B[0, 0] = A[0, 0] + T.float32(1)\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\n@T.prim_func\ndef func_with_part_access_region(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    with T.block():\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[vi, vj])\n                B[vi, vj] = A[vi, vj] + T.float32(1)\n\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.writes(C[vi, vj])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n\ndef test_complete_matmul():\n    func = matmul\n    A, B, C = [func.buffer_map[x] for x in func.params]\n\n    block = func.body.block.body.body.body.body.block\n    assert isinstance(block, tvm.tir.Block)\n    vi, vj, vk = [x.var for x in block.iter_vars]\n    access_A = tvm.tir.BufferRegion(A, [Range.from_min_extent(vi, 1), Range.from_min_extent(vk, 1)])\n    access_B = tvm.tir.BufferRegion(B, [Range.from_min_extent(vj, 1), Range.from_min_extent(vk, 1)])\n    access_C = tvm.tir.BufferRegion(C, [Range.from_min_extent(vi, 1), Range.from_min_extent(vj, 1)])\n    tvm.ir.assert_structural_equal(block.reads, [access_A, access_B])\n    tvm.ir.assert_structural_equal(block.writes, [access_C])\n\n\ndef test_complete_matmul_original():\n    func = matmul_original\n    A, B, C = [func.buffer_map[x] for x in func.params]\n\n    block1 = func.body.block.body.body.body[0].block\n    assert isinstance(block1, tvm.tir.Block)\n    vi, vj = [x.var for x in block1.iter_vars]\n    access_C = tvm.tir.BufferRegion(\n        C, [Range.from_min_extent(vi * 4, 4), Range.from_min_extent(vj * 4, 4)]\n    )\n    tvm.ir.assert_structural_equal(block1.reads, [])\n    tvm.ir.assert_structural_equal(block1.writes, [access_C])\n\n    block2 = func.body.block.body.body.body[1].body.block\n    assert isinstance(block2, tvm.tir.Block)\n    vi, vj, vk = [x.var for x in block2.iter_vars]\n    access_A = tvm.tir.BufferRegion(\n        A, [Range.from_min_extent(vi * 4, 4), Range.from_min_extent(vk * 4, 4)]\n    )\n    access_B = tvm.tir.BufferRegion(\n        B, [Range.from_min_extent(vj * 4, 4), Range.from_min_extent(vk * 4, 4)]\n    )\n    access_C = tvm.tir.BufferRegion(\n        C, [Range.from_min_extent(vi * 4, 4), Range.from_min_extent(vj * 4, 4)]\n    )\n    tvm.ir.assert_structural_equal(block2.reads, [access_C, access_A, access_B])\n    tvm.ir.assert_structural_equal(block2.writes, [access_C])\n\n\ndef _check_elementwise(func):\n    A, B, C = [func.buffer_map[x] for x in func.params]\n\n    block1 = func.body.block.body[0].body.body.block\n    assert isinstance(block1, tvm.tir.Block)\n    vi, vj = [x.var for x in block1.iter_vars]\n\n    tvm.ir.assert_structural_equal(\n        block1.reads,\n        [tvm.tir.BufferRegion(A, [Range.from_min_extent(vi, 1), Range.from_min_extent(vj, 1)])],\n    )\n    tvm.ir.assert_structural_equal(\n        block1.writes,\n        [tvm.tir.BufferRegion(B, [Range.from_min_extent(vi, 1), Range.from_min_extent(vj, 1)])],\n    )\n\n    block2 = func.body.block.body[1].body.body.block\n    assert isinstance(block2, tvm.tir.Block)\n    vi, vj = [x.var for x in block2.iter_vars]\n    tvm.ir.assert_structural_equal(\n        block2.reads,\n        [tvm.tir.BufferRegion(B, [Range.from_min_extent(vi, 1), Range.from_min_extent(vj, 1)])],\n    )\n    tvm.ir.assert_structural_equal(\n        block2.writes,\n        [tvm.tir.BufferRegion(C, [Range.from_min_extent(vi, 1), Range.from_min_extent(vj, 1)])],\n    )\n\n\ndef test_complete_with_root():\n    _check_elementwise(elementwise_with_root)\n\n\ndef test_complete_part_region():\n    _check_elementwise(func_with_part_access_region)\n\n\n@T.prim_func\ndef func_with_bufferslice_indices(data: T.handle, index: T.handle) -> None:\n    data_buf = T.match_buffer(data, (16, 16), \"float32\")\n    index_buf = T.match_buffer(index, (1,), \"int32\")\n    out_buf = T.alloc_buffer((16, 16), \"float32\")\n\n    for i, j in T.grid(16, 16):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            out_buf[vi, vj] = data_buf[vi, index_buf[0]]\n\n\n@T.prim_func\ndef expected_bufferslice_indices(data: T.handle, index: T.handle) -> None:\n    index_buf = T.match_buffer(index, [1], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n    data_buf = T.match_buffer(data, [16, 16], elem_offset=0, align=64, offset_factor=1)\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        out_buf = T.alloc_buffer([16, 16], elem_offset=0, align=64, offset_factor=1)\n        for i0, i1 in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i0, i1])\n                T.reads([data_buf[vi, index_buf[0]], index_buf[0]])\n                T.writes([out_buf[vi, vj]])\n                out_buf[vi, vj] = data_buf[vi, index_buf[0]]\n\n\n@T.prim_func\ndef func_with_recursive_bufferslice_indices(data: T.handle, index: T.handle) -> None:\n    data_buf = T.match_buffer(data, (16, 16), \"float32\")\n    index_buf = T.match_buffer(index, (1,), \"int32\")\n    out_buf = T.alloc_buffer((16, 16), \"float32\")\n\n    for i, j in T.grid(16, 16):\n        with T.block():\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            out_buf[vi, vj] = data_buf[index_buf[index_buf[0]], index_buf[0]]\n\n\n@T.prim_func\ndef expected_recursive_bufferslice_indices(data: T.handle, index: T.handle) -> None:\n    index_buf = T.match_buffer(index, [1], dtype=\"int32\", elem_offset=0, align=64, offset_factor=1)\n    data_buf = T.match_buffer(data, [16, 16], elem_offset=0, align=64, offset_factor=1)\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        out_buf = T.alloc_buffer([16, 16], elem_offset=0, align=64, offset_factor=1)\n        for i0, i1 in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i0, i1])\n                T.reads(\n                    [\n                        data_buf[index_buf[index_buf[0]], index_buf[0]],\n                        index_buf[T.min(index_buf[0], 0) : T.max(index_buf[0], 0) + 1],\n                    ]\n                )\n                T.writes([out_buf[vi, vj]])\n                out_buf[vi, vj] = data_buf[index_buf[index_buf[0]], index_buf[0]]\n\n\ndef test_complete_buffer_indices():\n    new_func = tvm.script.from_source(func_with_bufferslice_indices.script())\n    tvm.ir.assert_structural_equal(new_func, expected_bufferslice_indices)\n    new_func = tvm.script.from_source(func_with_recursive_bufferslice_indices.script())\n    tvm.ir.assert_structural_equal(new_func, expected_recursive_bufferslice_indices)\n\n\n@T.prim_func\ndef match_buffer_func(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    for i in range(0, 16):\n        with T.block():\n            A0 = T.match_buffer(A[i, 0:16], (16))\n            with T.block():\n                for j in range(0, 16):\n                    with T.block():\n                        A1 = T.match_buffer(A0[j], ())\n                        A1[()] = 1.0\n\n\n@T.prim_func\ndef expected_match_buffer_func(a: T.handle) -> None:\n    A = T.match_buffer(a, (16, 16))\n    for i in range(0, 16):\n        with T.block():\n            T.reads([])\n            T.writes(A[i, 0:16])\n            A0 = T.match_buffer(A[i, 0:16], (16))\n            with T.block():\n                T.reads([])\n                T.writes(A0[0:16])\n                for j in range(0, 16):\n                    with T.block():\n                        T.reads([])\n                        T.writes(A0[j])\n                        A1 = T.match_buffer(A0[j], ())\n                        A1[()] = 1.0\n\n\ndef test_complete_match_buffer():\n    tvm.ir.assert_structural_equal(match_buffer_func, expected_match_buffer_func)\n\n\n@T.prim_func\ndef alloc_buffer_func(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [2, 2], dtype=\"float32\")\n    B = T.match_buffer(b, [2, 2], dtype=\"float32\")\n    C = T.alloc_buffer([2, 2], dtype=\"float32\")\n    A[(0, 0)] = T.float32(2)\n    C[(0, 0)] = A[(0, 0)] + B[(0, 0)]\n    B[(0, 0)] = C[(0, 0)]\n\n\n@T.prim_func\ndef expect_alloc_buffer_func(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [2, 2], dtype=\"float32\", elem_offset=0, align=64, offset_factor=1)\n    B = T.match_buffer(b, [2, 2], dtype=\"float32\", elem_offset=0, align=64, offset_factor=1)\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        C = T.alloc_buffer([2, 2], dtype=\"float32\", elem_offset=0, align=64, offset_factor=1)\n        A[(0, 0)] = T.float32(2)\n        C[(0, 0)] = A[(0, 0)] + B[(0, 0)]\n        B[(0, 0)] = C[(0, 0)]\n\n\ndef test_complete_alloc_buffer():\n    rt_func = tvm.script.from_source(alloc_buffer_func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(alloc_buffer_func, expect_alloc_buffer_func)\n\n\nif __name__ == \"__main__\":\n    test_complete_matmul()\n    test_complete_matmul_original()\n    test_complete_with_root()\n    test_complete_part_region()\n    test_complete_buffer_indices()\n    test_complete_match_buffer()\n    test_complete_alloc_buffer()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_error_report.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport inspect\nimport re\n\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.ir.diagnostics import override_renderer\nfrom tvm.script import from_source\nfrom tvm.script import tir as T\n\n\ndef check_error(func, rel_lineno):\n    check_error_re = re.compile(r\"^.*# check_error: (.+)$\")\n    \"\"\"check if TIR script throws error\"\"\"\n    # Override the default renderer to accumulate errors\n    errors = []\n\n    def render(e):\n        for d in e.diagnostics:\n            errors.append(d)\n\n    override_renderer(render)\n    # The diagnostic context throws an exception when it gets an error\n    try:\n        source_code = inspect.getsource(func)\n        indent = len(re.match(r\"^\\s*\", source_code).group(0))\n        source_code = \"@T.prim_func\\n\" + \"\\n\".join(\n            line[indent:] for line in source_code.splitlines()\n        )\n        from_source(source_code)\n    except tvm.error.DiagnosticError as e:\n        pass\n    assert len(errors) == 1, errors\n    if rel_lineno is None:\n        return\n    error = errors[0]\n    assert (\n        error.span.line - 1 == rel_lineno or error.span.line == rel_lineno\n    ), f\"Expected error to be on line {rel_lineno}, but it was on {error.span.line - 1}\"\n\n    error_line = source_code.split(\"\\n\")[rel_lineno]\n    m = check_error_re.match(error_line)\n    if m:\n        expected_error_text = m.group(1)\n        error = error.message\n        assert (\n            expected_error_text == error\n        ), f'check_error expects \"{expected_error_text} in str(errors): {error}'\n\n\ndef test_buffer_bind():\n    def buffer_bind_missing_args(a: T.handle) -> None:\n        A = T.match_buffer((16, 16), \"float32\")  # error\n\n    check_error(buffer_bind_missing_args, 2)\n\n\ndef test_undefined_buffer():\n    def undefined_buffer(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n\n        T.attr(A, \"realize_scope\", \"\")\n        T.realize(C[0:16, 0:16], \"\")  # error\n        for i in T.serial(16):\n            for j in T.serial(0, 16):\n                A[i, j] = 0.0\n\n    check_error(undefined_buffer, 5)\n\n\ndef test_unsupported_stmt():\n    def unsupported_stmt(a: T.int32) -> None:\n        if a > 0:\n            print(\"I love tvm\")  # error\n\n    check_error(unsupported_stmt, 3)\n\n\ndef test_unsupported_function_call():\n    def unsupported_function_call(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n\n        T.attr(A, \"realize_scope\", \"\")\n        T.realize(A[0:16, 0:16], \"\")\n        for i in T.const_range(16):  # error\n            for j in T.serial(0, 16):\n                A[i, j] = 0.0\n\n    check_error(unsupported_function_call, 6)\n\n\ndef test_missing_type_annotation():\n    def missing_type_annotation(a) -> None:  # error\n        T.evaluate(0.0)\n\n    check_error(missing_type_annotation, 1)\n\n\ndef test_invalid_for_function():\n    def invalid_for_function(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        for i in T.evaluate(0.0):  # error\n            for j in T.serial(0, 16):\n                A[i, j] = 0.0\n\n    check_error(invalid_for_function, 4)\n\n\ndef test_invalid_block_function():\n    def invalid_block_function(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n\n        with T.evaluate(0.0):  # error\n            T.evaluate(1.0)\n\n    check_error(invalid_block_function, 4)\n\n\ndef test_return_not_allowed():\n    def return_not_allowed(a: T.handle) -> None:\n        return T.evaluate(0)  # error\n\n    check_error(return_not_allowed, 2)\n\n\ndef test_no_body():\n    def no_body(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        T.realize(A, \"\")  # error\n\n    check_error(no_body, 3)\n\n\ndef test_allocate_with_buffers():\n    def allocate_with_buffers() -> None:\n        with T.allocate([1], \"float32\", \"\") as [A, B]:  # error\n            T.evaluate(1.0)\n\n    check_error(allocate_with_buffers, 2)\n\n\ndef test_inconsistent_binding():\n    def inconsistent_binding_value() -> None:\n        for i, j in T.grid(16, 16):\n            vi, vj = T.axis.remap(\"SS\", [i])  # error\n            T.evaluate(1.0)\n\n    def inconsistent_binding_type() -> None:\n        for i, j in T.grid(16, 16):\n            vi, vj = T.axis.remap(\"S\", [i, j])  # error\n            T.evaluate(1.0)\n\n    check_error(inconsistent_binding_value, 3)\n    check_error(inconsistent_binding_type, 3)\n\n\ndef test_error_remap_args():\n    def error_remap_type() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"TT\", [i, j])  # error\n                T.evaluate(1.0)\n\n    def error_remap_value() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i + j, j])  # error\n                T.evaluate(1.0)\n\n    check_error(error_remap_type, 4)\n    check_error(error_remap_value, 4)\n\n\ndef test_invalid_block_axes():\n    def invalid_block_axes(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi = T.axis.S(i, A)  # error\n                T.evaluate(1.0)\n\n    check_error(invalid_block_axes, 5)\n\n\ndef test_duplicate_block_axes():\n    def duplicate_block_axes() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi = T.axis.S(16, i)\n                vi = T.axis.S(16, j)  # error\n                T.evaluate(1.0)\n\n    def duplicate_block_axes_remap() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vi = T.axis.remap(\"SS\", [i, j])  # error\n                T.evaluate(1.0)\n\n    check_error(duplicate_block_axes, 5)\n    check_error(duplicate_block_axes_remap, 4)\n\n\ndef test_miss_block_bind():\n    def miss_block_bind_value() -> None:\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi = T.axis.S(i)  # error\n                T.evaluate(1.0)\n\n    check_error(miss_block_bind_value, 4)\n\n\ndef test_invalid_loop_var():\n    def invalid_loop_var() -> None:\n        for i, j in range(0, 16):  # error\n            T.evaluate(1.0)\n\n    check_error(invalid_loop_var, 2)\n\n\ndef test_inconsistent_grid():\n    def inconsistent_grid() -> None:\n        for i in T.grid(16, 16):  # error\n            T.evaluate(1.0)\n\n    check_error(inconsistent_grid, 2)\n\n\ndef test_invalid_match_buffer_region():\n    def invalid_match_buffer_region() -> None:\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                A = T.match_buffer(vi)  # error\n                T.evaluate(1.0)\n\n    check_error(invalid_match_buffer_region, 5)\n\n\ndef test_duplicate_buffer():\n    def duplicate_buffer() -> None:\n        A = T.alloc_buffer((128, 128), \"float32\")\n        A = T.alloc_buffer((128, 128), \"float32\")  # error\n\n    check_error(duplicate_buffer, 3)\n\n\ndef test_duplicate_block_signature():\n    def duplicate_reads() -> None:\n        A = T.alloc_buffer((128, 128), \"float32\")\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.reads(A[0:8, 0:8])\n                T.reads(A[0:16, 0:16])  # error\n                T.evaluate(1.0)\n\n    def duplicate_writes() -> None:\n        A = T.alloc_buffer((128, 128), \"float32\")\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.writes(A[0:8, 0:8])\n                T.writes(A[0:16, 0:16])  # error\n                T.evaluate(1.0)\n\n    def duplicate_predicate() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.where(1)\n                T.where(0)  # error\n\n    def duplicate_annotations() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                T.block_attr({})\n                T.block_attr({})  # error\n\n    def duplicate_init() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                with T.init():\n                    T.evaluate(1.0)\n                with T.init():  # error\n                    T.evaluate(1.0)\n\n    def duplicate_axes() -> None:\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                vi = T.axis.S(i, 16)  # error\n                T.evaluate(1.0)\n\n    check_error(duplicate_reads, 7)\n    check_error(duplicate_writes, 7)\n    check_error(duplicate_predicate, 6)\n    check_error(duplicate_annotations, 6)\n    check_error(duplicate_init, 7)\n    check_error(duplicate_axes, 5)\n\n\ndef test_opaque_access_during_complete():\n    def opaque_access_during_complete(a: T.handle) -> None:  # error\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        for i, j in T.grid(16, 16):\n            with T.block():\n                T.evaluate(T.call_extern(\"dummy_extern_function\", A.data, dtype=\"int32\"))\n\n    check_error(opaque_access_during_complete, None)\n\n\ndef test_convert_slice_to_bufferload():\n    def convert_slice_to_bufferload() -> None:\n        A = T.alloc_buffer((128, 128), \"float32\")\n        for i, j in T.grid(128, 128):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                A[vi, vj] = A[vi : vi + 2, vj] + 1  # error\n\n    check_error(convert_slice_to_bufferload, 6)\n\n\ndef test_tvm_exception_catch():\n    def special_stmt_except() -> None:\n        A = T.alloc_buffer(\"(128, 128)\", \"float32\")  # error\n        T.evaluate(1.0)\n\n    def scope_handler_except() -> None:\n        for i in T.serial(\"1\", \"1\"):  # error\n            T.evaluate(1)\n\n    def intrin_except_unassign(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        T.evaluate(A)  # error\n\n    def intrin_except_assign(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        A[0, 0] = A[A]  # error\n\n    check_error(special_stmt_except, 2)\n    check_error(scope_handler_except, 2)\n    check_error(intrin_except_unassign, 3)\n    check_error(intrin_except_assign, 3)\n\n\ndef test_match_buffer_shape_mismatch():\n    def buffer_shape_mismatch(a: T.handle) -> None:\n        A = T.match_buffer(a, (8, 8))\n        for i, j in T.grid(8, 2):\n            with T.block():\n                T.reads([])\n                T.writes([A[i, j * 4 : j * 4 + 4]])\n                sub_A = T.match_buffer(\n                    A[i, j * 4 : j * 4 + 4], (5)\n                )  # error: shape mismatched between 4 and 5\n                for jj in range(0, 4):\n                    sub_A[i, j * 4 + jj] = 1\n\n    check_error(buffer_shape_mismatch, 7)\n\n\ndef test_high_dim_store():\n    def high_dim_store() -> None:\n        with T.block(\"root\"):\n            B = T.allocate([256], \"float32\", \"global\")\n            for i, j in T.grid(16, 16):\n                B[i, j] = 1.0  # error: Store is only allowed with one index\n\n    check_error(high_dim_store, 5)\n\n\ndef test_block_has_option_vars():\n    def block_has_option_vars() -> None:\n        with T.block(\"root\") as x:  # error: block does not support option_vars\n            T.evaluate(0.0)\n\n    check_error(block_has_option_vars, 2)\n\n\ndef test_implicit_root_has_attrs():\n    def implicit_root_has_read():\n        T.reads([])  # error: implicit root does not support reads\n        T.evaluate(0.0)\n\n    def implicit_root_has_write():\n        T.writes([])  # error: implicit root does not support writes\n        T.evaluate(0.0)\n\n    def implicit_root_has_attrs():\n        T.block_attr({})  # error: implicit root does not support block_attr\n        T.evaluate(0.0)\n\n    def implicit_root_has_predicate():\n        T.where(True)  # error: implicit root does not support predicate\n        T.evaluate(0.0)\n\n    def implicit_root_has_axes():\n        v = T.axis.S(0, 0)  # error: implicit root does not support axis define\n        T.evaluate(0.0)\n\n    check_error(implicit_root_has_read, 2)\n    check_error(implicit_root_has_write, 2)\n    check_error(implicit_root_has_attrs, 2)\n    check_error(implicit_root_has_predicate, 2)\n    check_error(implicit_root_has_axes, 2)\n\n\n@T.prim_func\ndef elementwise_not_affine(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i, j, k, l in T.grid(128, 128, 128, 8):\n        with T.block(\"B\"):\n            vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n            vl = T.axis.S(128, l * 16)\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n@T.prim_func\ndef elementwise_non_single_branch(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128))\n    C = T.alloc_buffer((128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128))\n    for i, j in T.grid(128, 128):\n        for k in T.serial(0, 128):\n            with T.block(\"C\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                C[vi, vj, vk] = A[vi, vj, vk] * 2.0\n        for k in T.serial(0, 128):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSS\", [i, j, k])\n                B[vi, vj, vk] = C[vi, vj, vk] * 2.0\n\n\ndef test_reorder_fail_block():\n    sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k, l = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError) as execinfo:\n        sch.reorder(l, i)\n    expected_sub_error_message = (\n        \"            # tir.Block#0\\n\"\n        '            with T.block(\"B\"):\\n'\n        \"            ^^^^^^^^^^^^^^^^^^\\n\"\n    )\n    assert expected_sub_error_message in str(execinfo.value)\n\n\ndef test_reorder_fail_nested_loop_inner():\n    sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError) as execinfo:\n        sch.reorder(k, i)\n    expected_sub_error_message = (\n        \"        for i in T.serial(128):\\n\"\n        \"            # tir.For#0\\n\"\n        \"            for j in T.serial(128):\\n\"\n        \"            ^^^^^^^^^^^^^^^^^^^^^^^\\n\"\n    )\n    assert expected_sub_error_message in str(execinfo.value)\n\n\ndef test_fuse_fail_nested_loop_outer():\n    sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")\n    block_b = sch.get_block(\"B\")\n    i, j, k = sch.get_loops(block_b)\n    with pytest.raises(tvm.tir.ScheduleError) as execinfo:\n        sch.fuse(k, i)\n    expected_sub_error_message = (\n        \"        # tir.For#1\\n\"\n        \"        for i in T.serial(128):\\n\"\n        \"        ^^^^^^^^^^^^^^^^^^^^^^^\\n\"\n        \"            for j in T.serial(128):\\n\"\n    )\n    assert expected_sub_error_message in str(execinfo.value)\n\n\ndef test_report_error_root_block():\n    sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")\n    root = sch.get_block(\"root\")\n    with pytest.raises(tvm.tir.ScheduleError) as execinfo:\n        sch.compute_inline(root)\n    expected_sub_error_message = (\n        \"        # tir.Block#0\\n\"\n        '        with T.block(\"root\"):\\n'\n        \"        ^^^^^^^^^^^^^^^^^^^^^\\n\"\n    )\n    assert expected_sub_error_message in str(execinfo.value)\n\n\ndef test_load_var():\n    def load_var_multiple() -> None:\n        d = T.var(\"float32\")\n        d[2] = d[2, 1]  # error cannot provide two indices to load\n\n    check_error(load_var_multiple, 3)\n\n\ndef test_store_var():\n    def store_var_multiple() -> None:\n        d = T.var(\"float32\")\n        d[2, 1] = d[1]  # error cannot provide two indices to store\n\n    check_error(store_var_multiple, 3)\n\n\ndef test_load_handle():\n    def load_handle(h: T.handle) -> None:\n        h_ = T.match_buffer(h, [1])\n        h_[0] = h[0]  # error cannot load from handle\n\n    check_error(load_handle, 3)\n\n\ndef test_store_handle():\n    def store_handle(h: T.handle) -> None:\n        h_ = T.match_buffer(h, [1])\n        h[0] = h_[0]  # error cannot store to handle\n\n    check_error(store_handle, 3)\n\n\ndef test_binop_bad_ast_type():\n    def binop_bad_ast_type(h: T.handle):\n        h_ = T.match_buffer(h, [1])\n        h_[0] = h + [2]  # error rhs should be a primexpr\n\n    check_error(binop_bad_ast_type, 3)\n\n\ndef test_binop_bad_type():\n    def binop_bad_type(h: T.handle):\n        h_ = T.match_buffer(h, [1])\n        h_[0] = h + 2  # error lhs and rhs should be the same type\n\n    check_error(binop_bad_type, 3)\n\n\ndef test_non_integer_typed_block_iter():\n    def non_integer_typed_block_iter():\n        with T.block():\n            i = T.axis.S(0.1, 0.1)  # error IterVar requires an integer dtype\n\n    check_error(non_integer_typed_block_iter, 3)\n\n\ndef test_preflattened_buffer_map_align():\n    def preflattened_buffer_map_align_nonint(foo: T.handle):\n        foo_1 = T.match_buffer(foo, [1])\n        T.preflattened_buffer(\n            foo_1, [1], align=\"bar\"\n        )  # check_error: align: want int or IntImm, got 'bar'\n\n    check_error(preflattened_buffer_map_align_nonint, 3)\n\n\ndef test_preflattened_buffer_map_offset_factor():\n    def preflattened_buffer_map_offset_factor_nonint(foo: T.handle):\n        foo_1 = T.match_buffer(foo, [1])\n        T.preflattened_buffer(\n            foo_1, [1], offset_factor=\"bar\"\n        )  # check_error: offset_factor: want int or IntImm, got 'bar'\n\n    check_error(preflattened_buffer_map_offset_factor_nonint, 3)\n\n\ndef test_illegal_buffer_slice():\n    def strided_buffer_region(A: T.handle):\n        # do not allow stride in buffer region\n        A = T.match_buffer((128, 128), \"int32\")\n        with T.block():\n            T.reads([])\n            T.writes([A[0:128:2, 0:128:3]])  # error\n            T.evaluate(T.call_extern(\"strided_compute\", dtype=\"\"))\n\n    def access_reversed_slice(A: T.handle):\n        # do not allow reversed slice step\n        A = T.match_buffer((128,), \"int32\")\n        A[0:128:-1] = T.broadcast(1, 128)  # error\n\n    def access_non_const_slice_length(A: T.handle):\n        # do not allow non-constant slice length\n        A = T.match_buffer((128,), \"int32\")\n        for i in range(4):\n            T.evaluate(A[0:i:1])  # error\n\n    check_error(strided_buffer_region, 3)\n    check_error(access_reversed_slice, 3)\n    check_error(access_non_const_slice_length, 3)\n\n\ndef test_syntax_sugar_fail():\n    def loop_syntax_sugar_fail(a: T.handle) -> None:\n        A = T.match_buffer(a, (128,))\n        for i in T.thread_binding(128, 128):\n            A[i] = A[i] * 2.0\n\n    check_error(loop_syntax_sugar_fail, 3)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_ir_builder_base.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.ir_builder.base\"\"\"\nimport pytest\nfrom tvm.script.ir_builder import IRBuilder\n\n\ndef test_ir_builder_scope():\n    with IRBuilder() as ib:  # pylint: disable=invalid-name\n        assert IRBuilder.current() == ib\n\n\ndef test_ir_builder_multi_scope():\n    with IRBuilder() as ib:  # pylint: disable=invalid-name\n        with IRBuilder() as ib2:  # pylint: disable=invalid-name\n            assert IRBuilder.current() == ib2\n        assert IRBuilder.current() == ib\n\n\ndef test_ir_builder_no_scope():\n    with pytest.raises(ValueError):\n        IRBuilder.current()\n\n\nif __name__ == \"__main__\":\n    test_ir_builder_scope()\n    test_ir_builder_multi_scope()\n    test_ir_builder_no_scope()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_ir_builder_irmodule.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.ir_builder.ir\"\"\"\nimport pytest\nimport tvm.testing\nfrom tvm.script.ir_builder import IRBuilder\nfrom tvm.script.ir_builder import ir as I\nfrom tvm import ir\nfrom tvm.ir.base import assert_structural_equal\n\n\ndef test_ir_builder_irmodule():\n    with IRBuilder() as ib:  # pylint: disable=invalid-name\n        with I.ir_module():\n            pass\n\n    # the ir_module generated by IRBuilder\n    ir_module_actual = ib.get()\n\n    # the expected prim_func\n    ir_module_expected = ir.IRModule(None, None)\n\n    assert_structural_equal(ir_module_actual, ir_module_expected, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_ir_builder_tir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, missing-docstring\n\"\"\"Unittests for tvm.script.ir_builder.tir\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.ir.base import assert_structural_equal\nfrom tvm.runtime import ndarray\nfrom tvm.script.ir_builder import IRBuilder\nfrom tvm.script.ir_builder import tir as T\n\n\ndef test_ir_builder_tir_primfunc_base():\n    with IRBuilder() as ib:\n        with T.prim_func():\n            T.evaluate(0)\n\n    # the prim_func generated by IRBuilder\n    prim_func_actual = ib.get()\n\n    # the expected prim_func\n    prim_func_expected = tir.PrimFunc(\n        params=[],\n        body=tir.Evaluate(0),\n        ret_type=None,\n        buffer_map=None,\n        preflattened_buffer_map=None,\n        attrs=None,\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(prim_func_actual, prim_func_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_primfunc_complete():\n    with IRBuilder() as ib:\n        with T.prim_func():\n            T.arg(\"a\", T.handle())\n            T.arg(\"b\", T.var(\"int64\"))\n            T.arg(\"c\", T.buffer_decl((128, 128), \"float32\"))\n            d = T.arg(\"d\", T.handle())\n            e = T.arg(\"e\", T.buffer_decl((1024,), \"int8\"))\n            T.func_attr({\"key\": \"value\"})\n            T.func_ret(tvm.ir.PrimType(\"int64\"))\n            buffer_d = T.match_buffer(d, (64, 64), \"int64\")\n            T.preflattened_buffer(e, (32, 32), \"int8\", data=e.data)\n            T.evaluate(0)\n\n    # the prim_func generated by IRBuilder\n    prim_func_actual = ib.get()\n\n    # the expected prim_func\n    c_handle, c_buffer = tir.Var(\"c_handle\", \"handle\"), tir.decl_buffer(\n        (128, 128), \"float32\", name=\"c\"\n    )\n    d_handle, d_buffer = tir.Var(\"d\", \"handle\"), tir.decl_buffer((64, 64), \"int64\", name=\"d\")\n    e_handle, e_buffer = tir.Var(\"e_handle\", \"handle\"), tir.decl_buffer((1024,), \"int8\", name=\"e\")\n    prim_func_expected = tir.PrimFunc(\n        params=[\n            tir.Var(\"a\", \"handle\"),\n            tir.Var(\"b\", \"int64\"),\n            c_handle,\n            d_handle,\n            e_handle,\n        ],\n        body=tir.Evaluate(0),\n        ret_type=tvm.ir.PrimType(\"int64\"),\n        buffer_map={c_handle: c_buffer, d_handle: d_buffer, e_handle: e_buffer},\n        preflattened_buffer_map={\n            e_handle: tir.decl_buffer((32, 32), \"int8\", name=\"e_preflatten\", data=e_buffer.data)\n        },\n        attrs=tvm.ir.make_node(\"DictAttrs\", key=\"value\"),\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(prim_func_actual, prim_func_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_block_base():\n    with IRBuilder() as ib:\n        with T.block(\"block\"):\n            T.evaluate(0)\n\n    # the block generated by IRBuilder\n    block_realize_actual = ib.get()\n\n    # the expected block\n    block_expected = tir.Block(\n        iter_vars=[],\n        reads=[],\n        writes=[],\n        name_hint=\"block\",\n        body=tir.Evaluate(0),\n        alloc_buffers=None,\n        match_buffers=None,\n        annotations={\"tir.script_parsing_detect_access\": tir.IntImm(\"int64\", 3)},\n    )\n    block_realize_expected = tir.BlockRealize(\n        iter_values=[],\n        predicate=True,\n        block=block_expected,\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(block_realize_actual, block_realize_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_block_complete():\n    with IRBuilder() as ib:\n        a = T.var(\"int64\", \"a\")\n        b = T.buffer_decl((128, 128), \"float32\")\n        c = T.buffer_decl((128, 128), \"float32\")\n        d = T.var(\"int32\", \"d\")\n        e = T.buffer_decl((128, 128), \"float32\")\n        f = T.var(\"int32\", \"f\")\n        with T.block(\"block\"):\n            T.where(a > 1)\n            T.reads(b[0:16, 0:16])\n            T.writes(c[d:128, d:128])\n            T.block_attr({\"key\": \"value\"})\n            T.alloc_buffer((128, 128), \"float32\")\n            T.match_buffer(e[0:32, 0:32], (32, 32), \"float32\")\n            T.axis.spatial(128, f)\n            T.evaluate(0)\n\n    # the block generated by IRBuilder\n    block_realize_actual = ib.get()\n\n    # the expected block\n    var_a = tir.Var(\"a\", \"int64\")\n    buffer_b = tir.decl_buffer((128, 128), \"float32\", name=\"b\")\n    buffer_c = tir.decl_buffer((128, 128), \"float32\", name=\"c\")\n    var_d = tir.Var(\"d\", \"int32\")\n    buffer_e = tir.decl_buffer((128, 128), \"float32\", name=\"c\")\n    var_f = tir.Var(\"f\", \"int32\")\n    block_expected = tir.Block(\n        iter_vars=[tir.IterVar((0, 128), tir.Var(\"\", \"int32\"), iter_type=tir.IterVar.DataPar)],\n        reads=[buffer_b[0:16, 0:16]],\n        writes=[buffer_c[var_d:128, var_d:128]],\n        name_hint=\"block\",\n        body=tir.Evaluate(0),\n        alloc_buffers=[tir.decl_buffer((128, 128), \"float32\")],\n        match_buffers=[\n            tir.MatchBufferRegion(tir.decl_buffer((32, 32), \"float32\"), buffer_e[0:32, 0:32])\n        ],\n        annotations={\"key\": \"value\"},\n    )\n    block_realize_expected = tir.BlockRealize(\n        iter_values=[var_f],\n        predicate=var_a > 1,\n        block=block_expected,\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(block_realize_actual, block_realize_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_axis():\n    with IRBuilder() as ib:\n        a = T.var(\"int32\", \"a\")\n        b = T.var(\"int32\", \"b\")\n        c = T.var(\"int32\", \"c\")\n        d = T.var(\"int32\", \"d\")\n        with T.block(\"block\"):\n            T.axis.spatial(8, a)\n            T.axis.reduce(16, b)\n            T.axis.scan(32, c)\n            T.axis.opaque(64, d)\n            T.evaluate(0)\n\n    # the block generated by IRBuilder\n    block_realize_actual = ib.get()\n\n    # the expected block\n    var_a = tir.Var(\"a\", \"int32\")\n    var_b = tir.Var(\"b\", \"int32\")\n    var_c = tir.Var(\"c\", \"int32\")\n    var_d = tir.Var(\"d\", \"int32\")\n    block_expected = tir.Block(\n        iter_vars=[\n            tir.IterVar((0, 8), tir.Var(\"\", \"int32\"), iter_type=tir.IterVar.DataPar),\n            tir.IterVar((0, 16), tir.Var(\"\", \"int32\"), iter_type=tir.IterVar.CommReduce),\n            tir.IterVar((0, 32), tir.Var(\"\", \"int32\"), iter_type=tir.IterVar.Ordered),\n            tir.IterVar((0, 64), tir.Var(\"\", \"int32\"), iter_type=tir.IterVar.DimInfo),\n        ],\n        reads=[],\n        writes=[],\n        name_hint=\"block\",\n        body=tir.Evaluate(0),\n        annotations={\"tir.script_parsing_detect_access\": tir.IntImm(\"int64\", 3)},\n    )\n    block_realize_expected = tir.BlockRealize(\n        iter_values=[var_a, var_b, var_c, var_d],\n        predicate=True,\n        block=block_expected,\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(block_realize_actual, block_realize_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_for():\n    with IRBuilder() as ib:\n        with T.serial(128) as a:\n            with T.parallel(64) as b:\n                with T.vectorized(32) as c:\n                    with T.unroll(16) as d:\n                        with T.thread_binding(8, thread=\"threadIdx.x\") as e:\n                            T.evaluate(0)\n\n    # the for generated by IRBuilder\n    for_actual = ib.get()\n\n    # the expected for\n    thread_binding_expected = tir.For(\n        loop_var=tir.Var(\"\", \"int32\"),\n        min_val=0,\n        extent=8,\n        kind=tir.ForKind.THREAD_BINDING,\n        body=tir.Evaluate(0),\n        thread_binding=tir.IterVar(\n            None, tir.Var(\"\", \"int32\"), tir.IterVar.ThreadIndex, \"threadIdx.x\"\n        ),\n    )\n    unroll_expected = tir.For(\n        loop_var=tir.Var(\"\", \"int32\"),\n        min_val=0,\n        extent=16,\n        kind=tir.ForKind.UNROLLED,\n        body=thread_binding_expected,\n    )\n    vectorized_expected = tir.For(\n        loop_var=tir.Var(\"\", \"int32\"),\n        min_val=0,\n        extent=32,\n        kind=tir.ForKind.VECTORIZED,\n        body=unroll_expected,\n    )\n    parallel_expected = tir.For(\n        loop_var=tir.Var(\"\", \"int32\"),\n        min_val=0,\n        extent=64,\n        kind=tir.ForKind.PARALLEL,\n        body=vectorized_expected,\n    )\n    for_expected = tir.For(\n        loop_var=tir.Var(\"\", \"int32\"),\n        min_val=0,\n        extent=128,\n        kind=tir.ForKind.SERIAL,\n        body=parallel_expected,\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(for_actual, for_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_assert():\n    with IRBuilder() as ib:\n        with T.Assert(T.var(\"int32\", name=\"a\") == 0, message=\"a is 0\"):\n            T.evaluate(0)\n    # the assert generated by IRBuilder\n    assert_actual = ib.get()\n\n    # the expected assert statement\n    assert_expected = tir.AssertStmt(\n        T.var(\"int32\", name=\"a\") == 0, tir.StringImm(\"a is 0\"), tir.Evaluate(0)\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(assert_actual, assert_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_let():\n    with IRBuilder() as ib:\n        with T.let(T.var(\"int32\", name=\"a\"), tir.IntImm(\"int32\", 2)):\n            T.evaluate(0)\n    # the let binding generated by IRBuilder\n    let_actual = ib.get()\n\n    # the expected Let statement\n    let_expected = tir.LetStmt(T.var(\"int32\", name=\"a\"), tir.IntImm(\"int32\", 2), tir.Evaluate(0))\n\n    # Check if the generated ir is expected\n    assert_structural_equal(let_actual, let_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_realize():\n    buffer_a = T.buffer_decl((128, 128), \"float32\")\n    with IRBuilder() as ib:\n        with T.realize(buffer_a[0:128, 0:128], \"test_storage_scope\", True):\n            T.evaluate(0)\n\n    # the buffer realization generated by IRBuilder\n    realize_actual = ib.get()\n\n    # the expected buffer realization\n    buffer_realize = tir.BufferRealize(\n        buffer_a, [tvm.ir.Range(0, 128), tvm.ir.Range(0, 128)], True, tir.Evaluate(0)\n    )\n    expected_realize = tir.AttrStmt(\n        buffer_a, \"realize_scope\", tir.StringImm(\"test_storage_scope\"), buffer_realize\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(realize_actual, expected_realize, map_free_vars=True)\n\n\ndef test_ir_builder_tir_thread():\n    with IRBuilder() as ib:\n        with T.prim_func():\n            brow = T.env_thread(\"blockIdx.y\")\n            with T.launch_thread(brow, 1):\n                T.evaluate(0)\n\n    # the prim_func generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected prim_func\n    iter_var = tir.IterVar((0, 1), \"v\", iter_type=1, thread_tag=\"blockIdx.y\")\n    attr_stmt = tir.AttrStmt(iter_var, \"thread_extent\", 1, tir.Evaluate(0))\n    func = tir.PrimFunc([], attr_stmt)\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, func, map_free_vars=True)\n\n\ndef test_ir_builder_tir_allocate():\n    with IRBuilder() as ib:\n        with T.allocate([10], \"float32\", scope=\"local\"):\n            T.evaluate(1)\n\n    # the allocate generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected allocate\n    buffer_var = tir.Var(\"v\", tvm.ir.PointerType(tvm.ir.PrimType(\"float32\"), \"local\"))\n    ir_expected = tir.Allocate(\n        buffer_var, \"float32\", [10], tvm.tir.const(1, \"uint1\"), tir.Evaluate(1)\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_allocate_const():\n    data = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n    with IRBuilder() as ib:\n        with T.allocate_const(data, \"int32\", [10]):\n            T.evaluate(1)\n\n    # the allocate const generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected allocate const\n    buffer_var = tir.Var(\"v\", tvm.ir.PointerType(tvm.ir.PrimType(\"int32\")))\n    ir_expected = tir.AllocateConst(\n        buffer_var,\n        \"int32\",\n        [10],\n        ndarray.array(np.asarray(data, \"int32\")),\n        tir.Evaluate(1),\n        annotations={},\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_while():\n    with IRBuilder() as ib:\n        with T.While(T.var(\"int32\", \"x\") > 0):\n            T.evaluate(0)\n\n    # the while generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected while\n    ir_expected = tir.While(tir.Var(\"x\", \"int32\") > 0, tir.Evaluate(0))\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_if_then_else():\n    with IRBuilder() as ib:\n        with T.If(T.var(\"int32\", \"c\") < 12):\n            with T.Then():\n                T.evaluate(T.int32(0))\n            with T.Else():\n                T.evaluate(T.int32(1))\n\n    # the if_then_else generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected if_then_else\n    ir_expected = tir.IfThenElse(\n        tir.Var(\"c\", \"int32\") < 12,\n        tir.Evaluate(tir.IntImm(\"int32\", 0)),\n        tir.Evaluate(tir.IntImm(\"int32\", 1)),\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_buffer_store():\n    buffer_a = T.buffer_decl((10, 10), \"float32\")\n    i = T.var(\"int32\", \"x\")\n    with IRBuilder() as ib:\n        T.buffer_store(buffer_a, 0.1, [0, i])\n\n    # the buffer store generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected buffer store\n    ir_expected = tir.BufferStore(buffer_a, 0.1, [0, i])\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_prefetch():\n    with IRBuilder() as ib:\n        buffer_a = T.buffer_decl((128, 128), \"float32\")\n        T.prefetch(buffer_a, [])\n\n    # the prefetch generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected prefetch\n    ir_expected = tir.Prefetch(buffer_a, [])\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_evaluate():\n    with IRBuilder() as ib:\n        T.evaluate(0)\n    # the evaluate generated by IRBuilder\n    eval_actual = ib.get()\n\n    # the expected evaluate\n    eval_expected = tir.Evaluate(0)\n\n    # Check if the generated ir is expected\n    assert_structural_equal(eval_actual, eval_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_decl_buffer():\n    with IRBuilder() as ib:\n        with T.decl_buffer([128, 128], \"float32\"):\n            T.evaluate(0)\n\n    # the decl_buffer generated by IRBuilder\n    ir_actual = ib.get()\n\n    # the expected decl_buffer\n    buffer = T.buffer_decl((128, 128), \"float32\")\n    ir_expected = tir.Allocate(\n        buffer.data,\n        \"float32\",\n        (128, 128),\n        tir.IntImm(\"bool\", True),\n        tir.DeclBuffer(buffer, tir.Evaluate(0)),\n    )\n\n    # Check if the generated ir is expected\n    assert_structural_equal(ir_actual, ir_expected, map_free_vars=True)\n\n\ndef test_ir_builder_tir_inline():\n    with IRBuilder() as ib:\n        m, n = T.meta_var(1), T.meta_var(2)\n        a, b = T.meta_var([3, 4])\n        T.evaluate(m.value + n.value + a.value + b.value)\n    # the evaluate generated by IRBuilder\n    eval_actual = ib.get()\n\n    # the expected evaluate\n    eval_expected = tir.Evaluate(10)\n\n    # Check if the generated ir is expected\n    assert_structural_equal(eval_actual, eval_expected, map_free_vars=True)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_meta_programming.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.script import tir as T\n\n\ndef matmul_generator(M: int, N: int, K: int, dtype: str):\n    @T.prim_func\n    def matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [M, K], dtype=dtype)\n        B = T.match_buffer(b, [N, K], dtype=dtype)\n        C = T.match_buffer(c, [M, N], dtype=dtype)\n\n        for i, j, k in T.grid(M, N, K):\n            with T.block():\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    return matmul\n\n\n@T.prim_func\ndef matmul_128_128_128_fp16(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float16\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float16\")\n    C = T.match_buffer(c, [128, 128], dtype=\"float16\")\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block():\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\ndef test_meta_programming_matmul():\n    f = matmul_generator(128, 128, 128, \"float16\")\n    tvm.ir.assert_structural_equal(f, matmul_128_128_128_fp16)\n\n\nif __name__ == \"__main__\":\n    test_meta_programming_matmul()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_ops.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.script import tir as T\nimport numpy as np\nimport tvm.testing\n\n\n@T.prim_func\ndef get_valid_counts(\n    data: T.handle,\n    valid_count: T.handle,\n    out: T.handle,\n    out_indices: T.handle,\n    score_threshold: T.float32,\n    id_index: T.int32,\n    score_index: T.int32,\n) -> None:\n\n    data_buf = T.match_buffer(data, (1, 2500, 6), \"float32\")\n    valid_count_buf = T.match_buffer(valid_count, (1,), \"int32\")\n    out_buf = T.match_buffer(out, (1, 2500, 6), \"float32\")\n    out_indices_buf = T.match_buffer(out_indices, (1, 2500), \"int32\")\n\n    with T.block(\"init\"):\n        vi = T.axis.S(1, 0)\n        valid_count_buf[vi] = T.int32(0)\n        for j in range(2500):\n            with T.block(\"update\"):\n                vj = T.axis.S(2500, j)\n                T.reads([data_buf[vi, vj, 6]])\n                T.writes([valid_count_buf[vi], out_indices_buf[vi, vj], out_buf[vi, vj, 6]])\n                if (data_buf[vi, vj, score_index] > score_threshold) and (\n                    (id_index < 0) or (data_buf[vi, vj, id_index] >= T.float32(0))\n                ):\n                    for k in T.serial(0, 6):\n                        out_buf[vi, valid_count_buf[vi], k] = data_buf[vi, vj, k]\n                    out_indices_buf[vi, valid_count_buf[vi]] = vj\n                    valid_count_buf[vi] = valid_count_buf[vi] + 1\n                if vj >= valid_count_buf[vi]:\n                    for k in T.serial(0, 6):\n                        out_buf[vi, vj, k] = T.float32(-1)\n                    out_indices_buf[vi, vj] = T.int32(-1)\n\n\ndef _check_get_valid_counts_with_numpy(f, dshape, score_threshold, id_index, score_index):\n    dtype = \"float32\"\n    ctx = tvm.cpu()\n    batch_size, num_anchor, elem_length = dshape\n    np_data = np.random.uniform(low=-2, high=2, size=dshape).astype(dtype)\n    np_out1 = np.zeros(shape=(batch_size,), dtype=\"int32\")\n    np_out2 = np.zeros(shape=dshape).astype(dtype)\n    np_out3 = np.zeros(shape=(batch_size, num_anchor), dtype=\"int32\")\n    for i in range(batch_size):\n        np_out1[i] = 0\n        inter_idx = 0\n        for j in range(num_anchor):\n            score = np_data[i, j, score_index]\n            if score > score_threshold and (id_index < 0 or np_data[i, j, id_index] >= 0):\n                for k in range(elem_length):\n                    np_out2[i, inter_idx, k] = np_data[i, j, k]\n                np_out1[i] += 1\n                np_out3[i, inter_idx] = j\n                inter_idx += 1\n            if j >= np_out1[i]:\n                for k in range(elem_length):\n                    np_out2[i, j, k] = -1.0\n                np_out3[i, j] = -1\n\n    in_data = tvm.nd.array(np_data, ctx)\n    out1 = tvm.nd.array(np_out1, ctx)\n    out2 = tvm.nd.array(np_out2, ctx)\n    out3 = tvm.nd.array(np_out3, ctx)\n    f(in_data, out1, out2, out3, score_threshold, id_index, score_index)\n    tvm.testing.assert_allclose(out1.numpy(), np_out1, rtol=1e-5)\n    tvm.testing.assert_allclose(out2.numpy(), np_out2, rtol=1e-5)\n    tvm.testing.assert_allclose(out3.numpy(), np_out3, rtol=1e-5)\n    print(\"test get_valid_counts end\")\n\n\ndef test_get_valid_counts_script_func():\n    device = \"llvm\"\n    # check lowering\n    print(get_valid_counts.script())\n    mod = tvm.ir.IRModule({\"get_valid_counts\": get_valid_counts})\n    print(mod.script())\n    # check building\n    f = tvm.build(mod[\"get_valid_counts\"], target=device)\n    _check_get_valid_counts_with_numpy(f, (1, 2500, 6), 0.0, 0, 1)\n\n\n@T.prim_func\ndef alloc_zero_dim_buffer(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [], dtype=\"float32\")\n    B = T.match_buffer(b, [], dtype=\"float32\")\n    # body\n    # tir.with block(\"root\")\n    C = T.alloc_buffer([], dtype=\"float32\")\n    A[()] = T.float32(2)\n    C[()] = A[()] + B[()]\n    B[()] = C[()]\n\n\n@T.prim_func\ndef alloc_zero_dim_buffer_block(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, (), \"float32\")\n    B = T.match_buffer(b, (), \"float32\")\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        C = T.alloc_buffer((), \"float32\")\n        A[()] = T.float32(2)\n        C[()] = A[()] + B[()]\n        B[()] = C[()]\n\n\ndef _check_alloc_zero_dim_buffer(f):\n    dtype = \"float32\"\n    ctx = tvm.cpu()\n\n    np_data = np.zeros(shape=()).astype(dtype)\n    np_out = np.zeros(shape=()).astype(dtype)\n    tvm_data = tvm.nd.array(np_data, ctx)\n    tvm_out = tvm.nd.array(np_out, ctx)\n\n    # np func exection\n    np_inter = np.array(1)\n    np_data[()] = 2.0\n    np_inter[()] = np_data[()] + np_out[()]\n    np_out[()] = np_inter[()]\n\n    # tvm func execution\n    f(tvm_data, tvm_out)\n    tvm.testing.assert_allclose(tvm_out.numpy(), np_out, rtol=1e-5)\n\n\ndef test_alloc_zero_dim_buffer_round_trip():\n    func = alloc_zero_dim_buffer\n    func_with_block = alloc_zero_dim_buffer_block\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    rt_func_with_block = tvm.script.from_source(func_with_block.script(show_meta=True))\n    rt_mod = tvm.build(rt_func, \"llvm\")\n    rt_mod_with_block = tvm.build(rt_func_with_block, \"llvm\")\n    tvm.ir.assert_structural_equal(func, func_with_block)\n    tvm.ir.assert_structural_equal(rt_func, rt_func_with_block)\n    _check_alloc_zero_dim_buffer(rt_mod)\n    _check_alloc_zero_dim_buffer(rt_mod_with_block)\n\n\n@T.prim_func\ndef ceildiv_test(A: T.Buffer[16, \"int32\"]):\n    for i in range(16):\n        A[i] = T.ceildiv(A[i], 4)\n\n\n@tvm.testing.requires_llvm\ndef test_ceildiv():\n    f = tvm.build(ceildiv_test, \"llvm\")\n    a = tvm.nd.array(np.arange(16).astype(\"int32\"))\n    f(a)\n    ref = (np.arange(16) + 3) // 4\n    tvm.testing.assert_allclose(a.numpy(), ref)\n\n\nif __name__ == \"__main__\":\n    test_get_valid_counts_script_func()\n    test_alloc_zero_dim_buffer_round_trip()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_parser_evaluator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.parser.evaluator\"\"\"\nimport pytest\nimport tvm.testing\nfrom tvm.script.parser.core.diagnostics import Source\nfrom tvm.script.parser.core.evaluator import ExprEvaluator\n\n\ndef _calc(expr, extra_vars=None):\n    if extra_vars is None:\n        extra_vars = {}\n    source = Source(expr)\n    mod_ast = source.as_ast()\n    mod_body_ast = mod_ast.body\n    expr_stmt_ast = mod_body_ast[0]\n    expr_ast = expr_stmt_ast.value\n    return ExprEvaluator.eval(None, extra_vars, expr_ast)\n\n\ndef test_evaluator_basic():\n    assert _calc(\"1, 3.14, True, 'str'\") == (1, 3.14, True, \"str\")\n\n\ndef test_evaluator_op():\n    assert _calc(\"1 + 2, 1 - 2, 1 * 2, 1 / 2\") == (3, -1, 2, 0.5)\n\n\ndef test_evaluator_value_table():\n    res = _calc(\"a + b, a - b, a * b, a / b\", {\"a\": 1, \"b\": 2})\n    a, b = 1, 2\n    assert res == (a + b, a - b, a * b, a / b)\n\n\ndef test_evaluator_func_call():\n    def func(a, b):\n        return a + b, a - b, a * b, a / b\n\n    assert _calc(\"func(1, 2)\", {\"func\": func}) == func(1, 2)\n\n\ndef test_evaluator_slice():\n    res = _calc(\"a, a[1:], a[:5], a[1: 5], a[1: 5: 2]\", {\"a\": [1, 2, 3, 4, 5, 6]})\n    a = [1, 2, 3, 4, 5, 6]\n    assert res == (a, a[1:], a[:5], a[1:5], a[1:5:2])\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_parser_ir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.parser.ir\"\"\"\n\nimport pytest\nimport inspect\nimport tvm.testing\nfrom tvm.script.parser import ir_module\nfrom tvm.ir import IRModule\n\n\ndef test_ir_base():\n    @ir_module\n    class BlankIRModule:\n        pass\n\n    assert isinstance(BlankIRModule, IRModule) and len(BlankIRModule.functions.items()) == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_parser_source.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.parser.core\"\"\"\nimport pytest\nimport inspect\nimport tvm.testing\nfrom tvm.script.parser.core.diagnostics import Source\nfrom tvm.script.parser.core import doc_core as doc\nfrom tvm.script import tir as T\n\n\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\ndef test_source_base():\n    source = Source(matmul)\n    assert (\n        source.source_name == inspect.getsourcefile(matmul)\n        and source.start_line is not None\n        and source.start_column == 0\n        and source.source == inspect.getsource(matmul)\n        and source.full_source == inspect.getsource(inspect.getmodule(matmul))\n    )\n\n\ndef test_source_ast():\n    source = Source(matmul)\n    mod = source.as_ast()\n    assert isinstance(mod, doc.Module)\n    func_def = mod.body[0]\n    assert isinstance(func_def, doc.FunctionDef)\n    assert func_def.name == \"matmul\"\n    func_args = func_def.args\n    assert (\n        len(func_args.args) == 3\n        and func_args.args[0].arg == \"a\"\n        and func_args.args[1].arg == \"b\"\n        and func_args.args[2].arg == \"c\"\n    )\n    func_body = func_def.body\n    assert len(func_body) == 4\n    func_assigns = func_body[:3]\n    assert (\n        isinstance(func_assigns[0], doc.Assign)\n        and func_assigns[0].targets[0].id == \"A\"\n        and isinstance(func_assigns[1], doc.Assign)\n        and func_assigns[1].targets[0].id == \"B\"\n        and isinstance(func_assigns[2], doc.Assign)\n        and func_assigns[2].targets[0].id == \"C\"\n    )\n    func_for = func_body[3]\n    assert (\n        len(func_for.target.elts) == 3\n        and func_for.target.elts[0].id == \"i\"\n        and func_for.target.elts[1].id == \"j\"\n        and func_for.target.elts[2].id == \"k\"\n    )\n    for_body = func_for.body\n    assert len(for_body) == 1\n    for_block = for_body[0]\n    assert isinstance(for_block, doc.With) and len(for_block.body) == 2\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_parser_tir.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unittests for tvm.script.parser.tir\"\"\"\n\nimport pytest\nimport inspect\nimport tvm.testing\nfrom tvm.script.parser import tir as T\nfrom tvm import ir, tir\n\n\ndef test_tir_buffer_proxy():\n    buffer_0 = T.Buffer((128, 128), \"float32\")\n    assert (\n        isinstance(buffer_0, tir.Buffer)\n        and list(buffer_0.shape) == [128, 128]\n        and buffer_0.dtype == \"float32\"\n    )\n\n    buffer_1 = T.Buffer[(64, 64, 64), \"int32\"]\n    assert (\n        isinstance(buffer_1, tir.Buffer)\n        and list(buffer_1.shape) == [64, 64, 64]\n        and buffer_1.dtype == \"int32\"\n    )\n\n\ndef test_tir_ptr_proxy():\n    ptr_0 = T.Ptr(\"int32\", \"global\")\n    assert (\n        isinstance(ptr_0, tir.Var)\n        and ptr_0.dtype == \"handle\"\n        and isinstance(ptr_0.type_annotation, ir.PointerType)\n        and ptr_0.type_annotation.element_type == ir.PrimType(\"int32\")\n        and ptr_0.type_annotation.storage_scope == \"global\"\n    )\n\n    ptr_1 = T.Ptr[\"float32\", \"shared\"]\n    assert (\n        isinstance(ptr_1, tir.Var)\n        and ptr_1.dtype == \"handle\"\n        and isinstance(ptr_1.type_annotation, ir.PointerType)\n        and ptr_1.type_annotation.element_type == ir.PrimType(\"float32\")\n        and ptr_1.type_annotation.storage_scope == \"shared\"\n    )\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_doc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nIn this test file, we want to make sure the Python code can construct\nDoc objects, then access and modify their attributes correctly.\n\"\"\"\n\nimport pytest\n\nimport tvm\nfrom tvm.runtime import ObjectPath\nfrom tvm.script.printer.doc import (\n    AssertDoc,\n    AssignDoc,\n    AttrAccessDoc,\n    CallDoc,\n    ClassDoc,\n    DictDoc,\n    ExprStmtDoc,\n    ForDoc,\n    FunctionDoc,\n    IdDoc,\n    IfDoc,\n    IndexDoc,\n    LambdaDoc,\n    ListDoc,\n    LiteralDoc,\n    OperationDoc,\n    OperationKind,\n    ReturnDoc,\n    ScopeDoc,\n    SliceDoc,\n    StmtBlockDoc,\n    TupleDoc,\n    WhileDoc,\n)\n\n\n@pytest.mark.parametrize(\n    \"value\",\n    [None, \"test\", 0, 1, -2, 0.0, 1.5, -1.3, True, False],\n)\ndef test_literal_doc_construction(value):\n    doc = LiteralDoc(value)\n\n    if isinstance(value, float):\n        # FloatImm cannot be compared with Python's float directly\n        assert float(doc.value) == pytest.approx(value)\n    else:\n        assert doc.value == value\n\n\ndef test_id_doc():\n    doc = IdDoc(\"name\")\n\n    assert doc.name == \"name\"\n\n\ndef test_attr_access_doc():\n    target = IdDoc(\"x\")\n\n    doc = AttrAccessDoc(target, \"attribute\")\n\n    assert doc.value == target\n    assert doc.name == \"attribute\"\n\n\n@pytest.mark.parametrize(\n    \"indices\",\n    [\n        [],\n        [LiteralDoc(1)],\n        [LiteralDoc(2), IdDoc(\"x\")],\n        [SliceDoc(LiteralDoc(1), LiteralDoc(2))],\n        [SliceDoc(LiteralDoc(1)), IdDoc(\"y\")],\n    ],\n)\ndef test_index_doc(indices):\n    target = IdDoc(\"x\")\n\n    doc = IndexDoc(target, indices)\n\n    assert doc.value == target\n    assert list(doc.indices) == indices\n\n\n@pytest.mark.parametrize(\n    \"args, kwargs\",\n    [\n        ([], {}),\n        ([LiteralDoc(\"arg\")], {}),\n        ([LiteralDoc(\"arg\"), IdDoc(\"x\")], {}),\n        ([], {\"x\": LiteralDoc(\"x\")}),\n        ([], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n        ([LiteralDoc(\"arg\")], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n        ([LiteralDoc(\"arg\"), IdDoc(\"x\")], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n    ],\n)\ndef test_call_doc(args, kwargs):\n    target = IdDoc(\"x\")\n\n    doc = CallDoc(target, *args, **kwargs)\n\n    assert doc.callee == target\n    assert list(doc.args) == args\n    assert dict(zip(doc.kwargs_keys, doc.kwargs_values)) == kwargs\n\n\n@pytest.mark.parametrize(\n    \"operands\",\n    [\n        [],\n        [LiteralDoc(1)],\n        [LiteralDoc(2), IdDoc(\"x\")],\n        [LiteralDoc(2), IdDoc(\"x\"), LiteralDoc(\"y\")],\n    ],\n)\ndef test_operation_doc(operands):\n    # Here we just test the contructor and attr visitor of OperationDoc\n    # so the choice of OperationKind doesn't matter\n    operator = OperationKind.Add\n\n    doc = OperationDoc(OperationKind.Add, operands)\n\n    assert doc.kind == operator\n    assert list(doc.operands) == operands\n\n\n@pytest.mark.parametrize(\n    \"args\",\n    [\n        [],\n        [IdDoc(\"x\")],\n        [IdDoc(\"x\"), IdDoc(\"y\")],\n    ],\n)\ndef test_lambda_doc(args):\n    body = LiteralDoc(1)\n\n    doc = LambdaDoc(args, body)\n\n    assert doc.body == body\n    assert list(doc.args) == args\n\n\n@pytest.mark.parametrize(\n    \"elements\",\n    [\n        [],\n        [IdDoc(\"x\")],\n        [IdDoc(\"x\"), IdDoc(\"y\")],\n    ],\n)\ndef test_tuple_doc(elements):\n    doc = TupleDoc(elements)\n\n    assert list(doc.elements) == elements\n\n\n@pytest.mark.parametrize(\n    \"elements\",\n    [\n        [],\n        [IdDoc(\"x\")],\n        [IdDoc(\"x\"), IdDoc(\"y\")],\n    ],\n)\ndef test_list_doc(elements):\n    doc = ListDoc(elements)\n\n    assert list(doc.elements) == elements\n\n\n@pytest.mark.parametrize(\n    \"content\",\n    [\n        {},\n        {LiteralDoc(\"k\"): IdDoc(\"v\")},\n        {LiteralDoc(\"k\"): IdDoc(\"v\"), LiteralDoc(\"k2\"): IdDoc(\"v2\")},\n    ],\n)\ndef test_dict_doc(content):\n    doc = DictDoc(content)\n\n    assert dict(zip(doc.keys, doc.values)) == content\n\n\n@pytest.mark.parametrize(\"start\", [LiteralDoc(1), None])\n@pytest.mark.parametrize(\"stop\", [LiteralDoc(2), None])\n@pytest.mark.parametrize(\"step\", [LiteralDoc(3), None])\ndef test_slice_doc(start, stop, step):\n    doc = SliceDoc(start, stop)\n\n    assert doc.start == start\n    assert doc.stop == stop\n\n\ndef test_expr_doc_attr_access():\n    target = IdDoc(\"x\")\n    attr = \"test\"\n\n    doc = target.attr(attr)\n\n    assert doc.value == target\n    assert doc.name == attr\n\n\n@pytest.mark.parametrize(\n    \"indices\",\n    [\n        (),\n        LiteralDoc(1),\n        SliceDoc(LiteralDoc(1), LiteralDoc(2)),\n        (LiteralDoc(1),),\n        (LiteralDoc(2), IdDoc(\"x\")),\n        (SliceDoc(LiteralDoc(1), LiteralDoc(2)),),\n        (SliceDoc(LiteralDoc(1)), IdDoc(\"y\")),\n    ],\n)\ndef test_expr_doc_get_item(indices):\n    target = IdDoc(\"x\")\n\n    doc = target[indices]\n\n    assert doc.value == target\n    if not isinstance(indices, tuple):\n        indices = (indices,)\n    assert tuple(doc.indices) == indices\n\n\n@pytest.mark.parametrize(\n    \"args, kwargs\",\n    [\n        ([], {}),\n        ([LiteralDoc(\"arg\")], {}),\n        ([LiteralDoc(\"arg\"), IdDoc(\"x\")], {}),\n        ([], {\"x\": LiteralDoc(\"x\")}),\n        ([], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n        ([LiteralDoc(\"arg\")], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n        ([LiteralDoc(\"arg\"), IdDoc(\"x\")], {\"x\": LiteralDoc(\"x\"), \"y\": LiteralDoc(\"y\")}),\n    ],\n)\ndef test_expr_doc_call_with(args, kwargs):\n    target = IdDoc(\"x\")\n\n    doc = target.call(*args, **kwargs)\n\n    assert doc.callee == target\n    assert list(doc.args) == args\n    assert dict(zip(doc.kwargs_keys, doc.kwargs_values)) == kwargs\n\n\n@pytest.mark.parametrize(\n    \"stmts\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_stmt_block_doc(stmts):\n    doc = StmtBlockDoc(stmts)\n\n    assert list(doc.stmts) == stmts\n\n\n@pytest.mark.parametrize(\n    \"lhs, rhs, annotation\",\n    [\n        (IdDoc(\"x\"), IdDoc(\"y\"), None),\n        (IdDoc(\"x\"), None, IdDoc(\"int\")),\n        (IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"int\")),\n    ],\n)\ndef test_assign_doc(lhs, rhs, annotation):\n    doc = AssignDoc(lhs, rhs, annotation)\n\n    assert doc.lhs == lhs\n    assert doc.rhs == rhs\n    assert doc.annotation == annotation\n\n\n@pytest.mark.parametrize(\n    \"lhs, rhs, annotation\",\n    [\n        (IdDoc(\"x\"), None, None),\n        (TupleDoc([IdDoc(\"x\"), IdDoc(\"y\")]), None, IdDoc(\"int\")),\n        (TupleDoc([IdDoc(\"x\"), IdDoc(\"y\")]), IdDoc(\"u\"), IdDoc(\"int\")),\n    ],\n)\ndef test_invalid_assign_doc(lhs, rhs, annotation):\n    with pytest.raises(ValueError) as e:\n        AssignDoc(lhs, rhs, annotation)\n    assert \"AssignDoc\" in str(e.value)\n\n\n@pytest.mark.parametrize(\n    \"else_branch\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\n@pytest.mark.parametrize(\n    \"then_branch\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_if_doc(then_branch, else_branch):\n    predicate = IdDoc(\"x\")\n\n    if not then_branch and not else_branch:\n        with pytest.raises(ValueError) as e:\n            IfDoc(predicate, then_branch, else_branch)\n        assert \"IfDoc\" in str(e.value)\n        return\n    else:\n        doc = IfDoc(predicate, then_branch, else_branch)\n\n    assert doc.predicate == predicate\n    assert list(doc.then_branch) == then_branch\n    assert list(doc.else_branch) == else_branch\n\n\n@pytest.mark.parametrize(\n    \"body\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_while_doc(body):\n    predicate = IdDoc(\"x\")\n\n    doc = WhileDoc(predicate, body)\n\n    assert doc.predicate == predicate\n    assert list(doc.body) == body\n\n\n@pytest.mark.parametrize(\n    \"body\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_for_doc(body):\n    lhs = IdDoc(\"x\")\n    rhs = IdDoc(\"y\")\n\n    doc = ForDoc(lhs, rhs, body)\n\n    assert doc.lhs == lhs\n    assert doc.rhs == rhs\n    assert list(doc.body) == body\n\n\n@pytest.mark.parametrize(\n    \"lhs\",\n    [\n        None,\n        IdDoc(\"x\"),\n    ],\n)\n@pytest.mark.parametrize(\n    \"body\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_scope_doc(lhs, body):\n    rhs = IdDoc(\"y\")\n\n    doc = ScopeDoc(lhs, rhs, body)\n\n    assert doc.lhs == lhs\n    assert doc.rhs == rhs\n    assert list(doc.body) == body\n\n\ndef test_expr_stmt_doc():\n    expr = IdDoc(\"x\")\n\n    doc = ExprStmtDoc(expr)\n\n    assert doc.expr == expr\n\n\n@pytest.mark.parametrize(\n    \"msg\",\n    [\n        None,\n        LiteralDoc(\"msg\"),\n    ],\n)\ndef test_assert_doc(msg):\n    test = IdDoc(\"x\")\n\n    doc = AssertDoc(test, msg)\n\n    assert doc.test == test\n    assert doc.msg == msg\n\n\ndef test_return_doc():\n    value = IdDoc(\"x\")\n\n    doc = ReturnDoc(value)\n\n    assert doc.value == value\n\n\n@pytest.mark.parametrize(\n    \"args\",\n    [\n        [],\n        [AssignDoc(IdDoc(\"x\"), None, IdDoc(\"int\"))],\n        [\n            AssignDoc(IdDoc(\"x\"), None, IdDoc(\"int\")),\n            AssignDoc(IdDoc(\"y\"), LiteralDoc(1), IdDoc(\"int\")),\n        ],\n    ],\n)\n@pytest.mark.parametrize(\n    \"decorators\",\n    [\n        [],\n        [IdDoc(\"test\")],\n        [IdDoc(\"test\"), IdDoc(\"test2\")],\n    ],\n)\n@pytest.mark.parametrize(\n    \"return_type\",\n    [\n        None,\n        LiteralDoc(None),\n    ],\n)\n@pytest.mark.parametrize(\n    \"body\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_function_doc(args, decorators, return_type, body):\n    name = IdDoc(\"name\")\n\n    doc = FunctionDoc(name, args, decorators, return_type, body)\n\n    assert doc.name == name\n    assert list(doc.args) == args\n    assert list(doc.decorators) == decorators\n    assert doc.return_type == return_type\n    assert list(doc.body) == body\n\n\n@pytest.mark.parametrize(\n    \"decorators\",\n    [\n        [],\n        [IdDoc(\"test\")],\n        [IdDoc(\"test\"), IdDoc(\"test2\")],\n    ],\n)\n@pytest.mark.parametrize(\n    \"body\",\n    [\n        [],\n        [ExprStmtDoc(IdDoc(\"x\"))],\n        [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n    ],\n)\ndef test_class_doc(decorators, body):\n    name = IdDoc(\"name\")\n\n    doc = ClassDoc(name, decorators, body)\n\n    assert doc.name == name\n    assert list(doc.decorators) == decorators\n    assert list(doc.body) == body\n\n\ndef test_stmt_doc_comment():\n    doc = ExprStmtDoc(IdDoc(\"x\"))\n    assert doc.comment is None\n\n    comment = \"test comment\"\n    doc.comment = comment\n    # Make sure the previous statement doesn't set attribute\n    # as if it's an ordinary Python object.\n    assert \"comment\" not in doc.__dict__\n    assert doc.comment == comment\n\n\ndef test_doc_source_paths():\n    doc = IdDoc(\"x\")\n    assert len(doc.source_paths) == 0\n\n    source_paths = [ObjectPath.root(), ObjectPath.root().attr(\"x\")]\n\n    doc.source_paths = source_paths\n    # This should triggers the __getattr__ and gets a tvm.ir.container.Array\n    assert not isinstance(doc.source_paths, list)\n    assert list(doc.source_paths) == source_paths\n\n    doc.source_paths = []\n    assert len(doc.source_paths) == 0\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_entry_point.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nfrom tvm.error import TVMError\nfrom tvm.script.printer import script\nfrom tvm.tir import FloatImm\n\n\ndef test_as_script_unknown_ir():\n    ir_node = FloatImm(\"float32\", 1.0)\n\n    with pytest.raises(TVMError) as e:\n        script(ir_node, \"test_xyz\", {})\n\n    assert \"test_xyz\" in str(e.value)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_frame.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom tvm.script.printer.frame import MetadataFrame\n\n\ndef test_frame_add_callback():\n    frame = MetadataFrame()\n\n    flag = 0\n\n    def callback1():\n        nonlocal flag\n        flag += 1\n\n    def callback2():\n        nonlocal flag\n        flag += 5\n\n    frame.add_exit_callback(callback1)\n    with frame:\n        frame.add_exit_callback(callback2)\n        assert flag == 0\n\n    assert flag == 6\n\n\ndef test_frame_clear_callbacks_after_exit():\n    frame = MetadataFrame()\n\n    flag = 0\n\n    def callback():\n        nonlocal flag\n        flag += 1\n\n    frame.add_exit_callback(callback)\n\n    with frame:\n        pass\n\n    assert flag == 1\n\n    with frame:\n        pass\n\n    assert flag == 1\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_highlight.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nimport tvm\nfrom tvm.script import tir as T\n\n\ndef test_highlight_script():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def main(  # type: ignore\n            a: T.handle,\n            b: T.handle,\n            c: T.handle,\n        ) -> None:  # pylint: disable=no-self-argument\n            T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n            A = T.match_buffer(a, [16, 128, 128])\n            B = T.match_buffer(b, [16, 128, 128])\n            C = T.match_buffer(c, [16, 128, 128])\n            for n, i, j, k in T.grid(16, 128, 128, 128):\n                with T.block(\"matmul\"):\n                    vn, vi, vj, vk = T.axis.remap(\"SSSR\", [n, i, j, k])\n                    with T.init():\n                        C[vn, vi, vj] = 0.0  # type: ignore\n                    C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk]\n\n    Module.show()\n    Module[\"main\"].show()\n    Module[\"main\"].show(style=\"light\")\n    Module[\"main\"].show(style=\"dark\")\n    Module[\"main\"].show(style=\"ansi\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_irdocsifier.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\n\nfrom tvm.runtime import ObjectPath\nfrom tvm.script.printer.doc import IdDoc\nfrom tvm.script.printer.frame import MetadataFrame, VarDefFrame\nfrom tvm.script.printer.ir_docsifier import IRDocsifier, RootNodeContainer\nfrom tvm.tir import Var\n\n\n@pytest.fixture\ndef ir_docsifier():\n    \"\"\"\n    Creates an IRDocsifier instance with a special dispatch token.\n    \"\"\"\n    _ir_docsifier = IRDocsifier({})\n    with _ir_docsifier.dispatch_token(f\"{__file__}\"):\n        yield _ir_docsifier\n\n\ndef _get_id_doc_printer(id_name):\n    def printer(obj, object_path, ir_docsifier):  # pylint: disable=unused-argument\n        return IdDoc(id_name)\n\n    return printer\n\n\ndef _root_dispatch_function(obj, ir_docsifier):\n    doc = ir_docsifier.as_doc(obj, ObjectPath.root())\n    doc.source_paths = [ObjectPath.root().attr(\"irdocsifier_test\")]\n    return doc\n\n\n# Because the dispatch table is global, tests should only set dispatch function under\n# unique dispatch token.\nIRDocsifier.set_dispatch(Var, _get_id_doc_printer(\"x\"), f\"{__file__}\")\nIRDocsifier.set_root_dispatch(f\"{__file__}\", _root_dispatch_function)\n\n\ndef test_set_dispatch(ir_docsifier):\n    IRDocsifier.set_dispatch(Var, _get_id_doc_printer(\"x2\"), f\"{__file__}-2\")\n    with ir_docsifier.dispatch_token(f\"{__file__}-2\"):\n        doc = ir_docsifier.as_doc(Var(\"x\", dtype=\"int8\"), ObjectPath.root())\n        assert doc.name == \"x2\"\n\n    doc = ir_docsifier.as_doc(Var(\"x\", dtype=\"int8\"), ObjectPath.root())\n    assert doc.name == \"x\"\n\n\ndef test_set_root_dispatch(ir_docsifier):\n    doc = ir_docsifier.as_doc(RootNodeContainer(Var(\"x\", dtype=\"int8\")), ObjectPath.root())\n    assert ObjectPath.root().attr(\"irdocsifier_test\") in doc.source_paths\n\n\ndef test_as_doc(ir_docsifier):\n    object_path = ObjectPath.root()\n    doc = ir_docsifier.as_doc(Var(\"x\", \"int8\"), ObjectPath.root())\n    assert doc.name == \"x\"\n    assert list(doc.source_paths) == [object_path]\n\n\ndef test_with_dispatch_token(ir_docsifier):\n    initial_token_count = len(ir_docsifier.dispatch_tokens)\n\n    with ir_docsifier.dispatch_token(\"tir\"):\n        assert len(ir_docsifier.dispatch_tokens) == initial_token_count + 1\n\n    assert len(ir_docsifier.dispatch_tokens) == initial_token_count\n\n\ndef test_with_frame(ir_docsifier):\n    initial_frame_count = len(ir_docsifier.frames)\n\n    frame = VarDefFrame()\n    is_callback_called = False\n\n    def callback():\n        nonlocal is_callback_called\n        is_callback_called = True\n\n    frame.add_exit_callback(callback)\n\n    with ir_docsifier.frame(frame):\n        assert len(ir_docsifier.frames) == initial_frame_count + 1\n        assert not is_callback_called\n\n    assert len(ir_docsifier.frames) == initial_frame_count\n    assert is_callback_called\n\n\ndef test_get_frame(ir_docsifier):\n    with ir_docsifier.frame(VarDefFrame()) as frame_a:\n        assert ir_docsifier.get_frame(MetadataFrame) is None\n        assert ir_docsifier.get_frame(VarDefFrame) == frame_a\n\n        with ir_docsifier.frame(VarDefFrame()) as frame_b:\n            assert ir_docsifier.get_frame(MetadataFrame) is None\n            assert ir_docsifier.get_frame(VarDefFrame) == frame_b\n\n            with ir_docsifier.frame(MetadataFrame()) as frame_c:\n                assert ir_docsifier.get_frame(MetadataFrame) == frame_c\n                assert ir_docsifier.get_frame(VarDefFrame) == frame_b\n\n            assert ir_docsifier.get_frame(MetadataFrame) is None\n            assert ir_docsifier.get_frame(VarDefFrame) == frame_b\n\n        assert ir_docsifier.get_frame(MetadataFrame) is None\n        assert ir_docsifier.get_frame(VarDefFrame) == frame_a\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_python_doc_printer.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport itertools\n\nimport pytest\n\nimport tvm\nfrom tvm.script.printer.doc import (\n    AssertDoc,\n    AssignDoc,\n    CallDoc,\n    ClassDoc,\n    DictDoc,\n    ExprStmtDoc,\n    ForDoc,\n    FunctionDoc,\n    IdDoc,\n    IfDoc,\n    LambdaDoc,\n    ListDoc,\n    LiteralDoc,\n    OperationDoc,\n    OperationKind,\n    ReturnDoc,\n    ScopeDoc,\n    SliceDoc,\n    StmtBlockDoc,\n    TupleDoc,\n    WhileDoc,\n)\nfrom tvm.script.printer.doc_printer import to_python_script\n\n\ndef format_script(s: str) -> str:\n    \"\"\"\n    Remove leading and trailing blank lines, and make the minimum idention 0\n    \"\"\"\n    s = s.strip(\"\\n\")\n\n    non_empty_lines = [line for line in s.splitlines() if line and not line.isspace()]\n    if not non_empty_lines:\n        # no actual content\n        return \"\\n\"\n\n    line_indents = [len(line) - len(line.lstrip(\" \")) for line in non_empty_lines]\n    spaces_to_remove = min(line_indents)\n\n    cleaned_lines = \"\\n\".join(line[spaces_to_remove:] for line in s.splitlines())\n    if not cleaned_lines.endswith(\"\\n\"):\n        cleaned_lines += \"\\n\"\n    return cleaned_lines\n\n\n@pytest.mark.parametrize(\n    \"doc,expected\",\n    [\n        (LiteralDoc(None), \"None\"),\n        (LiteralDoc(True), \"True\"),\n        (LiteralDoc(False), \"False\"),\n        (LiteralDoc(\"test\"), '\"test\"'),\n        (LiteralDoc(\"\"), '\"\"'),\n        (LiteralDoc('\"\"'), r'\"\\\"\\\"\"'),\n        (LiteralDoc(\"\\n\\t\\\\test\\r\"), r'\"\\n\\t\\\\test\\r\"'),\n        # TODO: fix the roundatrippable problem caused by utf8\n        pytest.param(LiteralDoc(\"\\x88\"), r'\"\\x88\"', marks=pytest.mark.xfail),\n        (LiteralDoc(0), \"0\"),\n        (LiteralDoc(-1), \"-1\"),\n        (LiteralDoc(3.25), \"3.25\"),\n        (LiteralDoc(-0.5), \"-0.5\"),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_literal_doc(doc, expected):\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"name\",\n    [\n        \"test\",\n        \"_test\",\n        \"TestCase\",\n        \"test_case\",\n        \"test123\",\n    ],\n    ids=itertools.count(),\n)\ndef test_print_id_doc(name):\n    doc = IdDoc(name)\n    assert to_python_script(doc) == format_script(name)\n\n\n@pytest.mark.parametrize(\n    \"attr\",\n    [\n        \"attr\",\n        \"_attr\",\n        \"Attr\",\n        \"attr_1\",\n    ],\n    ids=itertools.count(),\n)\ndef test_print_attr_doc(attr):\n    doc = IdDoc(\"x\").attr(attr)\n    assert to_python_script(doc) == format_script(f\"x.{attr}\")\n\n\n@pytest.mark.parametrize(\n    \"indices, expected\",\n    [\n        (\n            (),\n            \"[()]\",\n        ),\n        (\n            (LiteralDoc(1),),\n            \"[1]\",\n        ),\n        (\n            (LiteralDoc(2), IdDoc(\"x\")),\n            \"[2, x]\",\n        ),\n        (\n            (SliceDoc(LiteralDoc(1), LiteralDoc(2)),),\n            \"[1:2]\",\n        ),\n        (\n            (SliceDoc(LiteralDoc(1)), IdDoc(\"y\")),\n            \"[1:, y]\",\n        ),\n        (\n            (SliceDoc(), IdDoc(\"y\")),\n            \"[:, y]\",\n        ),\n        (\n            (IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"z\")),\n            \"[x, y, z]\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_index_doc(indices, expected):\n    doc = IdDoc(\"x\")[indices]\n    assert to_python_script(doc) == format_script(f\"x{expected}\")\n\n\nUNARY_OP_TOKENS = {\n    OperationKind.USub: \"-\",\n    OperationKind.Invert: \"~\",\n    OperationKind.Not: \"not \",\n}\n\n\n@pytest.mark.parametrize(\n    \"op_kind, expected_token\",\n    list(UNARY_OP_TOKENS.items()),\n    ids=UNARY_OP_TOKENS.keys(),\n)\ndef test_print_unary_operation_doc(op_kind, expected_token):\n    doc = OperationDoc(op_kind, [IdDoc(\"x\")])\n    assert to_python_script(doc) == format_script(f\"{expected_token}x\")\n\n\nBINARY_OP_TOKENS = {\n    OperationKind.Add: \"+\",\n    OperationKind.Sub: \"-\",\n    OperationKind.Mult: \"*\",\n    OperationKind.Div: \"/\",\n    OperationKind.FloorDiv: \"//\",\n    OperationKind.Mod: \"%\",\n    OperationKind.Pow: \"**\",\n    OperationKind.LShift: \"<<\",\n    OperationKind.RShift: \">>\",\n    OperationKind.BitAnd: \"&\",\n    OperationKind.BitOr: \"|\",\n    OperationKind.BitXor: \"^\",\n    OperationKind.Lt: \"<\",\n    OperationKind.LtE: \"<=\",\n    OperationKind.Eq: \"==\",\n    OperationKind.NotEq: \"!=\",\n    OperationKind.Gt: \">\",\n    OperationKind.GtE: \">=\",\n    OperationKind.And: \"and\",\n    OperationKind.Or: \"or\",\n}\n\n\n@pytest.mark.parametrize(\n    \"op_kind, expected_token\",\n    list(BINARY_OP_TOKENS.items()),\n    ids=BINARY_OP_TOKENS.keys(),\n)\ndef test_print_binary_operation_doc(op_kind, expected_token):\n    doc = OperationDoc(op_kind, [IdDoc(\"x\"), IdDoc(\"y\")])\n    assert to_python_script(doc) == format_script(f\"x {expected_token} y\")\n\n\nSPECIAL_OP_CASES = [\n    (\n        OperationKind.IfThenElse,\n        [LiteralDoc(True), LiteralDoc(\"true\"), LiteralDoc(\"false\")],\n        '\"true\" if True else \"false\"',\n    ),\n    (\n        OperationKind.IfThenElse,\n        [IdDoc(\"x\"), LiteralDoc(None), LiteralDoc(1)],\n        \"None if x else 1\",\n    ),\n]\n\n\n@pytest.mark.parametrize(\n    \"op_kind, operands, expected\", SPECIAL_OP_CASES, ids=[kind for (kind, *_) in SPECIAL_OP_CASES]\n)\ndef test_print_special_operation_doc(op_kind, operands, expected):\n    doc = OperationDoc(op_kind, operands)\n    assert to_python_script(doc) == format_script(expected)\n\n\ndef test_operation_doc_test_exhaustive():\n    special_op_covered = {k for k, *_ in SPECIAL_OP_CASES}\n    for op_kind in OperationKind:\n        if OperationKind._UnaryStart < op_kind < OperationKind._UnaryEnd:\n            assert op_kind in UNARY_OP_TOKENS, (\n                f\"{op_kind.name} not covered in test_print_unary_operation_doc. \"\n                f\"Please add the expected token to UNARY_OP_TOKENS\"\n            )\n        elif OperationKind._BinaryStart < op_kind < OperationKind._BinaryEnd:\n            assert op_kind in BINARY_OP_TOKENS, (\n                f\"{op_kind.name} not covered in test_print_binary_operation_doc. \"\n                f\"Please add the expected token to BINARY_OP_TOKENS\"\n            )\n        elif not op_kind.name.startswith(\"_\"):\n            # Special Op\n            assert op_kind in special_op_covered, (\n                f\"{op_kind.name} not covered in test_print_special_operation_doc. \"\n                f\"Please add the test cases for it to SPECIAL_OP_CASES\"\n            )\n\n\n@pytest.mark.parametrize(\n    \"args, kwargs, expected\",\n    [\n        (\n            (),\n            {},\n            \"()\",\n        ),\n        (\n            (),\n            {\"key0\": IdDoc(\"u\")},\n            \"(key0=u)\",\n        ),\n        (\n            (),\n            {\"key0\": IdDoc(\"u\"), \"key1\": IdDoc(\"v\")},\n            \"(key0=u, key1=v)\",\n        ),\n        (\n            (IdDoc(\"x\"),),\n            {},\n            \"(x)\",\n        ),\n        (\n            (IdDoc(\"x\"),),\n            {\"key0\": IdDoc(\"u\")},\n            \"(x, key0=u)\",\n        ),\n        (\n            (IdDoc(\"x\"),),\n            {\"key0\": IdDoc(\"u\"), \"key1\": IdDoc(\"v\")},\n            \"(x, key0=u, key1=v)\",\n        ),\n        (\n            (IdDoc(\"x\"), (IdDoc(\"y\"))),\n            {},\n            \"(x, y)\",\n        ),\n        (\n            (IdDoc(\"x\"), (IdDoc(\"y\"))),\n            {\"key0\": IdDoc(\"u\")},\n            \"(x, y, key0=u)\",\n        ),\n        (\n            (IdDoc(\"x\"), (IdDoc(\"y\"))),\n            {\"key0\": IdDoc(\"u\"), \"key1\": IdDoc(\"v\")},\n            \"(x, y, key0=u, key1=v)\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_call_doc(args, kwargs, expected):\n    doc = CallDoc(IdDoc(\"f\"), *args, **kwargs)\n    assert to_python_script(doc) == format_script(f\"f{expected}\")\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        (\n            (),\n            \"lambda : 0\",\n        ),\n        (\n            (IdDoc(\"x\"),),\n            \"lambda x: 0\",\n        ),\n        (\n            (IdDoc(\"x\"), IdDoc(\"y\")),\n            \"lambda x, y: 0\",\n        ),\n        (\n            (IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"z\")),\n            \"lambda x, y, z: 0\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_lambda_doc(args, expected):\n    doc = LambdaDoc(args, body=LiteralDoc(0))\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"elements, expected\",\n    [\n        (\n            (),\n            \"[]\",\n        ),\n        (\n            [IdDoc(\"x\")],\n            \"[x]\",\n        ),\n        (\n            [IdDoc(\"x\"), IdDoc(\"y\")],\n            \"[x, y]\",\n        ),\n        (\n            [IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"z\")],\n            \"[x, y, z]\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_list_doc(elements, expected):\n    doc = ListDoc(elements)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"elements, expected\",\n    [\n        (\n            (),\n            \"()\",\n        ),\n        (\n            [IdDoc(\"x\")],\n            \"(x,)\",\n        ),\n        (\n            [IdDoc(\"x\"), IdDoc(\"y\")],\n            \"(x, y)\",\n        ),\n        (\n            [IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"z\")],\n            \"(x, y, z)\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_tuple_doc(elements, expected):\n    doc = TupleDoc(elements)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"content, expected\",\n    [\n        (\n            {},\n            \"{}\",\n        ),\n        (\n            {LiteralDoc(\"key_x\"): IdDoc(\"x\")},\n            '{\"key_x\": x}',\n        ),\n        (\n            {LiteralDoc(\"key_x\"): IdDoc(\"x\"), LiteralDoc(\"key_y\"): IdDoc(\"y\")},\n            '{\"key_x\": x, \"key_y\": y}',\n        ),\n        (\n            {\n                LiteralDoc(\"key_x\"): IdDoc(\"x\"),\n                LiteralDoc(\"key_y\"): IdDoc(\"y\"),\n                LiteralDoc(\"key_z\"): IdDoc(\"z\"),\n            },\n            '{\"key_x\": x, \"key_y\": y, \"key_z\": z}',\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_dict_doc(content, expected):\n    doc = DictDoc(content)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"slice_doc, expected\",\n    [\n        (\n            SliceDoc(),\n            \":\",\n        ),\n        (\n            SliceDoc(LiteralDoc(1)),\n            \"1:\",\n        ),\n        (\n            SliceDoc(None, LiteralDoc(2)),\n            \":2\",\n        ),\n        (\n            SliceDoc(LiteralDoc(1), LiteralDoc(2)),\n            \"1:2\",\n        ),\n        (\n            SliceDoc(None, None, LiteralDoc(3)),\n            \"::3\",\n        ),\n        (\n            SliceDoc(LiteralDoc(1), None, LiteralDoc(3)),\n            \"1::3\",\n        ),\n        (\n            SliceDoc(None, LiteralDoc(2), LiteralDoc(3)),\n            \":2:3\",\n        ),\n        (\n            SliceDoc(LiteralDoc(1), LiteralDoc(2), LiteralDoc(3)),\n            \"1:2:3\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_slice_doc(slice_doc, expected):\n    doc = IdDoc(\"x\")[slice_doc]\n    assert to_python_script(doc) == format_script(f\"x[{expected}]\")\n\n\n@pytest.mark.parametrize(\n    \"stmts, expected\",\n    [\n        (\n            [],\n            \"\",\n        ),\n        (\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            \"x\",\n        ),\n        (\n            [ExprStmtDoc(IdDoc(\"x\")), ExprStmtDoc(IdDoc(\"y\"))],\n            \"\"\"\n            x\n            y\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_stmt_block_doc(stmts, expected):\n    doc = StmtBlockDoc(stmts)\n    assert to_python_script(doc).strip() == format_script(expected).strip()\n\n\n@pytest.mark.parametrize(\n    \"doc, expected\",\n    [\n        (\n            AssignDoc(IdDoc(\"x\"), IdDoc(\"y\"), None),\n            \"x = y\",\n        ),\n        (\n            AssignDoc(IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"int\")),\n            \"x: int = y\",\n        ),\n        (\n            AssignDoc(IdDoc(\"x\"), None, IdDoc(\"int\")),\n            \"x: int\",\n        ),\n        (\n            AssignDoc(TupleDoc([IdDoc(\"x\"), IdDoc(\"y\")]), IdDoc(\"z\"), None),\n            \"x, y = z\",\n        ),\n        (\n            AssignDoc(TupleDoc([IdDoc(\"x\"), TupleDoc([IdDoc(\"y\"), IdDoc(\"z\")])]), IdDoc(\"z\"), None),\n            \"x, (y, z) = z\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_assign_doc(doc, expected):\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"then_branch, else_branch, expected\",\n    [\n        (\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            [],\n            \"\"\"\n            if pred:\n                x\n            \"\"\",\n        ),\n        (\n            [],\n            [ExprStmtDoc(IdDoc(\"y\"))],\n            \"\"\"\n            if pred:\n                pass\n            else:\n                y\n            \"\"\",\n        ),\n        (\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            [ExprStmtDoc(IdDoc(\"y\"))],\n            \"\"\"\n            if pred:\n                x\n            else:\n                y\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_if_doc(then_branch, else_branch, expected):\n    doc = IfDoc(IdDoc(\"pred\"), then_branch, else_branch)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"body, expected\",\n    [\n        (\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            \"\"\"\n            while pred:\n                x\n            \"\"\",\n        ),\n        (\n            [],\n            \"\"\"\n            while pred:\n                pass\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_while_doc(body, expected):\n    doc = WhileDoc(IdDoc(\"pred\"), body)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"body, expected\",\n    [\n        (\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            \"\"\"\n            for x in y:\n                x\n            \"\"\",\n        ),\n        (\n            [],\n            \"\"\"\n            for x in y:\n                pass\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_for_doc(body, expected):\n    doc = ForDoc(IdDoc(\"x\"), IdDoc(\"y\"), body)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"lhs, body, expected\",\n    [\n        (\n            IdDoc(\"c\"),\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            \"\"\"\n            with context() as c:\n                x\n            \"\"\",\n        ),\n        (\n            IdDoc(\"c\"),\n            [],\n            \"\"\"\n            with context() as c:\n                pass\n            \"\"\",\n        ),\n        (\n            None,\n            [],\n            \"\"\"\n            with context():\n                pass\n            \"\"\",\n        ),\n        (\n            None,\n            [ExprStmtDoc(IdDoc(\"x\"))],\n            \"\"\"\n            with context():\n                x\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_scope_doc(lhs, body, expected):\n    doc = ScopeDoc(lhs, CallDoc(IdDoc(\"context\")), body)\n    assert to_python_script(doc) == format_script(expected)\n\n\ndef test_print_expr_stmt_doc():\n    doc = ExprStmtDoc(CallDoc(IdDoc(\"f\"), IdDoc(\"x\")))\n    assert to_python_script(doc) == format_script(\"f(x)\")\n\n\n@pytest.mark.parametrize(\n    \"msg, expected\",\n    [\n        (\n            None,\n            \"\"\"\n            assert True\n            \"\"\",\n        ),\n        (\n            LiteralDoc(\"test message\"),\n            \"\"\"\n            assert True, \"test message\"\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_assert_doc(msg, expected):\n    test = LiteralDoc(True)\n\n    doc = AssertDoc(test, msg)\n\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"value, expected\",\n    [\n        (\n            LiteralDoc(None),\n            \"\"\"\n            return None\n            \"\"\",\n        ),\n        (\n            IdDoc(\"x\"),\n            \"\"\"\n            return x\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_return_doc(value, expected):\n    doc = ReturnDoc(value)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"args, decorators, return_type, body, expected\",\n    [\n        (\n            [],\n            [],\n            None,\n            [],\n            \"\"\"\n            def func():\n                pass\n            \"\"\",\n        ),\n        (\n            [AssignDoc(IdDoc(\"x\"), rhs=None, annotation=IdDoc(\"int\"))],\n            [],\n            IdDoc(\"int\"),\n            [],\n            \"\"\"\n            def func(x: int) -> int:\n                pass\n            \"\"\",\n        ),\n        (\n            [AssignDoc(IdDoc(\"x\"), rhs=LiteralDoc(1), annotation=IdDoc(\"int\"))],\n            [],\n            LiteralDoc(None),\n            [],\n            \"\"\"\n            def func(x: int = 1) -> None:\n                pass\n            \"\"\",\n        ),\n        (\n            [],\n            [IdDoc(\"wrap\")],\n            LiteralDoc(None),\n            [],\n            \"\"\"\n            @wrap\n            def func() -> None:\n                pass\n            \"\"\",\n        ),\n        (\n            [],\n            [IdDoc(\"wrap_outter\"), IdDoc(\"wrap_inner\")],\n            LiteralDoc(None),\n            [],\n            \"\"\"\n            @wrap_outter\n            @wrap_inner\n            def func() -> None:\n                pass\n            \"\"\",\n        ),\n        (\n            [\n                AssignDoc(IdDoc(\"x\"), rhs=None, annotation=IdDoc(\"int\")),\n                AssignDoc(IdDoc(\"y\"), rhs=LiteralDoc(1), annotation=IdDoc(\"int\")),\n            ],\n            [IdDoc(\"wrap\")],\n            LiteralDoc(None),\n            [],\n            \"\"\"\n            @wrap\n            def func(x: int, y: int = 1) -> None:\n                pass\n            \"\"\",\n        ),\n        (\n            [\n                AssignDoc(IdDoc(\"x\"), rhs=None, annotation=IdDoc(\"int\")),\n                AssignDoc(IdDoc(\"y\"), rhs=LiteralDoc(1), annotation=IdDoc(\"int\")),\n            ],\n            [IdDoc(\"wrap\")],\n            LiteralDoc(None),\n            [\n                AssignDoc(IdDoc(\"y\"), OperationDoc(OperationKind.Add, [IdDoc(\"x\"), LiteralDoc(1)])),\n                AssignDoc(IdDoc(\"y\"), OperationDoc(OperationKind.Sub, [IdDoc(\"y\"), LiteralDoc(1)])),\n            ],\n            \"\"\"\n            @wrap\n            def func(x: int, y: int = 1) -> None:\n                y = x + 1\n                y = y - 1\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_function_doc(args, decorators, body, return_type, expected):\n    doc = FunctionDoc(IdDoc(\"func\"), args, decorators, return_type, body)\n    assert to_python_script(doc) == format_script(expected)  # test\n\n\ndef get_func_doc_for_class(name):\n    args = [\n        AssignDoc(IdDoc(\"x\"), rhs=None, annotation=IdDoc(\"int\")),\n        AssignDoc(IdDoc(\"y\"), rhs=LiteralDoc(1), annotation=IdDoc(\"int\")),\n    ]\n    body = [\n        AssignDoc(IdDoc(\"y\"), OperationDoc(OperationKind.Add, [IdDoc(\"x\"), LiteralDoc(1)])),\n        AssignDoc(IdDoc(\"y\"), OperationDoc(OperationKind.Sub, [IdDoc(\"y\"), LiteralDoc(1)])),\n    ]\n    return FunctionDoc(\n        name=IdDoc(name),\n        args=args,\n        decorators=[IdDoc(\"wrap\")],\n        return_type=LiteralDoc(None),\n        body=body,\n    )\n\n\n@pytest.mark.parametrize(\n    \"decorators, body, expected\",\n    [\n        (\n            [],\n            [],\n            \"\"\"\n            class TestClass:\n                pass\n            \"\"\",\n        ),\n        (\n            [IdDoc(\"wrap\")],\n            [],\n            \"\"\"\n            @wrap\n            class TestClass:\n                pass\n            \"\"\",\n        ),\n        (\n            [IdDoc(\"wrap_outter\"), IdDoc(\"wrap_inner\")],\n            [],\n            \"\"\"\n            @wrap_outter\n            @wrap_inner\n            class TestClass:\n                pass\n            \"\"\",\n        ),\n        (\n            [IdDoc(\"wrap\")],\n            [get_func_doc_for_class(\"f1\")],\n            \"\"\"\n            @wrap\n            class TestClass:\n                @wrap\n                def f1(x: int, y: int = 1) -> None:\n                    y = x + 1\n                    y = y - 1\n\n            \"\"\",\n        ),\n        (\n            [IdDoc(\"wrap\")],\n            [get_func_doc_for_class(\"f1\"), get_func_doc_for_class(\"f2\")],\n            \"\"\"\n            @wrap\n            class TestClass:\n                @wrap\n                def f1(x: int, y: int = 1) -> None:\n                    y = x + 1\n                    y = y - 1\n\n                @wrap\n                def f2(x: int, y: int = 1) -> None:\n                    y = x + 1\n                    y = y - 1\n\n            \"\"\",\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_class_doc(decorators, body, expected):\n    doc = ClassDoc(IdDoc(\"TestClass\"), decorators, body)\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"doc, comment, expected\",\n    [\n        (\n            AssignDoc(IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"int\")),\n            \"comment\",\n            \"\"\"\n            x: int = y  # comment\n            \"\"\",\n        ),\n        (\n            IfDoc(IdDoc(\"x\"), [ExprStmtDoc(IdDoc(\"y\"))], [ExprStmtDoc(IdDoc(\"z\"))]),\n            \"comment\",\n            \"\"\"\n            # comment\n            if x:\n                y\n            else:\n                z\n            \"\"\",\n        ),\n        (\n            IfDoc(IdDoc(\"x\"), [ExprStmtDoc(IdDoc(\"y\"))], [ExprStmtDoc(IdDoc(\"z\"))]),\n            \"comment line 1\\ncomment line 2\",\n            \"\"\"\n            # comment line 1\n            # comment line 2\n            if x:\n                y\n            else:\n                z\n            \"\"\",\n        ),\n        (\n            WhileDoc(\n                LiteralDoc(True),\n                [\n                    AssignDoc(IdDoc(\"x\"), IdDoc(\"y\")),\n                ],\n            ),\n            \"comment\",\n            \"\"\"\n            # comment\n            while True:\n                x = y\n            \"\"\",\n        ),\n        (\n            ForDoc(IdDoc(\"x\"), IdDoc(\"y\"), []),\n            \"comment\",\n            \"\"\"\n            # comment\n            for x in y:\n                pass\n            \"\"\",\n        ),\n        (\n            ScopeDoc(IdDoc(\"x\"), IdDoc(\"y\"), []),\n            \"comment\",\n            \"\"\"\n            # comment\n            with y as x:\n                pass\n            \"\"\",\n        ),\n        (\n            ExprStmtDoc(IdDoc(\"x\")),\n            \"comment\",\n            \"\"\"\n            x  # comment\n            \"\"\",\n        ),\n        (\n            AssertDoc(LiteralDoc(True)),\n            \"comment\",\n            \"\"\"\n            assert True  # comment\n            \"\"\",\n        ),\n        (\n            ReturnDoc(LiteralDoc(1)),\n            \"comment\",\n            \"\"\"\n            return 1  # comment\n            \"\"\",\n        ),\n        (\n            get_func_doc_for_class(\"f\"),\n            \"comment\",\n            '''\n            @wrap\n            def f(x: int, y: int = 1) -> None:\n                \"\"\"\n                comment\n                \"\"\"\n                y = x + 1\n                y = y - 1\n            ''',\n        ),\n        (\n            get_func_doc_for_class(\"f\"),\n            \"comment line 1\\n\\ncomment line 3\",\n            '''\n            @wrap\n            def f(x: int, y: int = 1) -> None:\n                \"\"\"\n                comment line 1\n\n                comment line 3\n                \"\"\"\n                y = x + 1\n                y = y - 1\n            ''',\n        ),\n        (\n            ClassDoc(IdDoc(\"TestClass\"), decorators=[IdDoc(\"wrap\")], body=[]),\n            \"comment\",\n            '''\n            @wrap\n            class TestClass:\n                \"\"\"\n                comment\n                \"\"\"\n                pass\n            ''',\n        ),\n        (\n            ClassDoc(IdDoc(\"TestClass\"), decorators=[IdDoc(\"wrap\")], body=[]),\n            \"comment line 1\\n\\ncomment line 3\",\n            '''\n            @wrap\n            class TestClass:\n                \"\"\"\n                comment line 1\n\n                comment line 3\n                \"\"\"\n                pass\n            ''',\n        ),\n    ],\n    ids=itertools.count(),\n)\ndef test_print_doc_comment(doc, comment, expected):\n    doc.comment = comment\n    assert to_python_script(doc) == format_script(expected)\n\n\n@pytest.mark.parametrize(\n    \"doc\",\n    [\n        AssignDoc(IdDoc(\"x\"), IdDoc(\"y\"), IdDoc(\"int\")),\n        ExprStmtDoc(IdDoc(\"x\")),\n        AssertDoc(IdDoc(\"x\")),\n        ReturnDoc(IdDoc(\"x\")),\n    ],\n)\ndef test_print_invalid_multiline_doc_comment(doc):\n    doc.comment = \"1\\n2\"\n    with pytest.raises(ValueError) as e:\n        to_python_script(doc)\n    assert \"cannot have newline\" in str(e.value)\n\n\ndef generate_expr_precedence_test_cases():\n    x = IdDoc(\"x\")\n    y = IdDoc(\"y\")\n    z = IdDoc(\"z\")\n\n    def negative(a):\n        return OperationDoc(OperationKind.USub, [a])\n\n    def invert(a):\n        return OperationDoc(OperationKind.Invert, [a])\n\n    def not_(a):\n        return OperationDoc(OperationKind.Not, [a])\n\n    def add(a, b):\n        return OperationDoc(OperationKind.Add, [a, b])\n\n    def sub(a, b):\n        return OperationDoc(OperationKind.Sub, [a, b])\n\n    def mult(a, b):\n        return OperationDoc(OperationKind.Mult, [a, b])\n\n    def div(a, b):\n        return OperationDoc(OperationKind.Div, [a, b])\n\n    def mod(a, b):\n        return OperationDoc(OperationKind.Mod, [a, b])\n\n    def pow(a, b):\n        return OperationDoc(OperationKind.Pow, [a, b])\n\n    def lshift(a, b):\n        return OperationDoc(OperationKind.LShift, [a, b])\n\n    def bit_and(a, b):\n        return OperationDoc(OperationKind.BitAnd, [a, b])\n\n    def bit_or(a, b):\n        return OperationDoc(OperationKind.BitOr, [a, b])\n\n    def bit_xor(a, b):\n        return OperationDoc(OperationKind.BitXor, [a, b])\n\n    def lt(a, b):\n        return OperationDoc(OperationKind.Lt, [a, b])\n\n    def eq(a, b):\n        return OperationDoc(OperationKind.Eq, [a, b])\n\n    def not_eq(a, b):\n        return OperationDoc(OperationKind.NotEq, [a, b])\n\n    def and_(a, b):\n        return OperationDoc(OperationKind.And, [a, b])\n\n    def or_(a, b):\n        return OperationDoc(OperationKind.Or, [a, b])\n\n    def if_then_else(a, b, c):\n        return OperationDoc(OperationKind.IfThenElse, [a, b, c])\n\n    test_cases = {\n        \"attr-call-index\": [\n            (\n                add(x, y).attr(\"test\"),\n                \"(x + y).test\",\n            ),\n            (\n                add(x, y.attr(\"test\")),\n                \"x + y.test\",\n            ),\n            (\n                x[z].call(y),\n                \"x[z](y)\",\n            ),\n            (\n                x.call(y)[z],\n                \"x(y)[z]\",\n            ),\n            (\n                x.call(y).call(z),\n                \"x(y)(z)\",\n            ),\n            (\n                x.call(y).attr(\"test\"),\n                \"x(y).test\",\n            ),\n            (\n                x.attr(\"test\").call(y),\n                \"x.test(y)\",\n            ),\n            (\n                x.attr(\"test\").attr(\"test2\"),\n                \"x.test.test2\",\n            ),\n            (\n                LambdaDoc([x], x).call(y),\n                \"(lambda x: x)(y)\",\n            ),\n            (\n                add(x, y)[z][add(z, z)].attr(\"name\"),\n                \"(x + y)[z][z + z].name\",\n            ),\n        ],\n        \"power\": [\n            (\n                pow(pow(x, y), z),\n                \"(x ** y) ** z\",\n            ),\n            (\n                pow(x, pow(y, z)),\n                \"x ** y ** z\",\n            ),\n            (\n                pow(negative(x), negative(y)),\n                \"(-x) ** -y\",\n            ),\n            (\n                pow(add(x, y), add(y, z)),\n                \"(x + y) ** (y + z)\",\n            ),\n        ],\n        \"unary\": [\n            (\n                invert(negative(y)),\n                \"~-y\",\n            ),\n            (\n                negative(y).attr(\"test\"),\n                \"(-y).test\",\n            ),\n            (\n                negative(y.attr(\"test\")),\n                \"-y.test\",\n            ),\n            (\n                mult(negative(x), negative(y)),\n                \"-x * -y\",\n            ),\n            (\n                negative(add(invert(x), negative(y))),\n                \"-(~x + -y)\",\n            ),\n        ],\n        \"add-mult\": [\n            (\n                mult(x, mult(y, z)),\n                \"x * (y * z)\",\n            ),\n            (\n                mult(mult(x, y), z),\n                \"x * y * z\",\n            ),\n            (\n                mult(x, add(y, z)),\n                \"x * (y + z)\",\n            ),\n            (\n                mult(add(y, z), x),\n                \"(y + z) * x\",\n            ),\n            (\n                add(x, mod(y, z)),\n                \"x + y % z\",\n            ),\n            (\n                add(mult(y, z), x),\n                \"y * z + x\",\n            ),\n            (\n                add(add(x, y), add(y, z)),\n                \"x + y + (y + z)\",\n            ),\n            (\n                div(add(x, y), add(y, z)),\n                \"(x + y) / (y + z)\",\n            ),\n        ],\n        \"shift\": [\n            (\n                div(x, lshift(y, z)),\n                \"x / (y << z)\",\n            ),\n            (\n                mult(lshift(y, z), x),\n                \"(y << z) * x\",\n            ),\n            (\n                lshift(x, mult(y, z)),\n                \"x << y * z\",\n            ),\n            (\n                lshift(mult(x, y), z),\n                \"x * y << z\",\n            ),\n            (\n                lshift(mult(x, y), z),\n                \"x * y << z\",\n            ),\n            (\n                lshift(lshift(x, y), z),\n                \"x << y << z\",\n            ),\n            (\n                lshift(x, lshift(y, z)),\n                \"x << (y << z)\",\n            ),\n        ],\n        \"bitwise\": [\n            (\n                add(bit_or(x, y), bit_or(y, z)),\n                \"(x | y) + (y | z)\",\n            ),\n            (\n                bit_and(bit_or(x, y), bit_or(y, z)),\n                \"(x | y) & (y | z)\",\n            ),\n            (\n                bit_or(bit_and(x, y), bit_and(y, z)),\n                \"x & y | y & z\",\n            ),\n            (\n                bit_and(bit_xor(x, bit_or(y, z)), z),\n                \"(x ^ (y | z)) & z\",\n            ),\n        ],\n        \"comparison\": [\n            (\n                not_eq(add(x, y), z),\n                \"x + y != z\",\n            ),\n            (\n                eq(pow(x, y), z),\n                \"x ** y == z\",\n            ),\n            (\n                lt(x, div(y, z)),\n                \"x < y / z\",\n            ),\n            (\n                lt(x, if_then_else(y, y, y)),\n                \"x < (y if y else y)\",\n            ),\n        ],\n        \"boolean\": [\n            (\n                not_(and_(x, y)),\n                \"not (x and y)\",\n            ),\n            (\n                and_(not_(x), y),\n                \"not x and y\",\n            ),\n            (\n                and_(or_(x, y), z),\n                \"(x or y) and z\",\n            ),\n            (\n                or_(x, or_(y, z)),\n                \"x or (y or z)\",\n            ),\n            (\n                or_(or_(x, y), z),\n                \"x or y or z\",\n            ),\n            (\n                or_(and_(x, y), z),\n                # Maybe we should consider adding parentheses here\n                # for readability, even though it's not necessary.\n                \"x and y or z\",\n            ),\n            (\n                and_(or_(not_(x), y), z),\n                \"(not x or y) and z\",\n            ),\n            (\n                and_(lt(x, y), lt(y, z)),\n                \"x < y and y < z\",\n            ),\n            (\n                or_(not_(eq(x, y)), lt(y, z)),\n                # Same as the previous one, the code here is not\n                # readable without parentheses.\n                \"not x == y or y < z\",\n            ),\n            (\n                and_(if_then_else(x, y, z), x),\n                \"(y if x else z) and x\",\n            ),\n            (\n                not_(if_then_else(x, y, z)),\n                \"not (y if x else z)\",\n            ),\n        ],\n        \"if-then-else\": [\n            (\n                if_then_else(x, if_then_else(y, y, y), z),\n                \"y if y else y if x else z\",\n            ),\n            (\n                if_then_else(if_then_else(x, x, x), y, z),\n                \"y if (x if x else x) else z\",\n            ),\n            (\n                if_then_else(x, y, if_then_else(z, z, z)),\n                \"y if x else (z if z else z)\",\n            ),\n            (\n                if_then_else(lt(x, x), add(y, y), mult(z, z)),\n                \"y + y if x < x else z * z\",\n            ),\n            (\n                if_then_else(LambdaDoc([x], x), LambdaDoc([y], y), LambdaDoc([z], z)),\n                \"(lambda y: y) if (lambda x: x) else (lambda z: z)\",\n            ),\n        ],\n        \"lambda\": [\n            (\n                LambdaDoc([x, y], add(z, z)),\n                \"lambda x, y: z + z\",\n            ),\n            (\n                add(LambdaDoc([x, y], z), z),\n                \"(lambda x, y: z) + z\",\n            ),\n            (\n                LambdaDoc([x, y], add(z, z)).call(x, y),\n                \"(lambda x, y: z + z)(x, y)\",\n            ),\n            (\n                LambdaDoc([x], LambdaDoc([y], z)),\n                \"lambda x: lambda y: z\",\n            ),\n        ],\n    }\n\n    return [\n        pytest.param(*args, id=f\"{group_name}-{i}\")\n        for group_name, cases in test_cases.items()\n        for i, args in enumerate(cases)\n    ]\n\n\n@pytest.mark.parametrize(\"doc, expected\", generate_expr_precedence_test_cases())\ndef test_expr_precedence(doc, expected):\n    assert to_python_script(doc) == format_script(expected)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_underlining.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom typing import Optional\n\nimport pytest\n\nfrom tvm.runtime import ObjectPath\nfrom tvm.script.printer.doc import (\n    StmtBlockDoc,\n    ExprStmtDoc,\n    IdDoc,\n    OperationDoc,\n    OperationKind,\n)\nfrom tvm.script.printer.doc_printer import to_python_script\n\n\ndef make_path(name: str) -> ObjectPath:\n    return ObjectPath.root().attr(name)\n\n\ndef make_id_doc(name: str, path_name: Optional[str] = None) -> IdDoc:\n    if path_name is None:\n        path_name = name\n    doc = IdDoc(name)\n    doc.source_paths = [make_path(path_name)]\n    return doc\n\n\ndef format_script(s: str) -> str:\n    \"\"\"\n    Remove leading and trailing blank lines, and make the minimum idention 0\n    \"\"\"\n    s = s.strip(\"\\n\")\n\n    non_empty_lines = [line for line in s.splitlines() if line and not line.isspace()]\n    if not non_empty_lines:\n        # no actual content\n        return \"\\n\"\n\n    line_indents = [len(line) - len(line.lstrip(\" \")) for line in non_empty_lines]\n    spaces_to_remove = min(line_indents)\n\n    cleaned_lines = \"\\n\".join(line[spaces_to_remove:] for line in s.splitlines())\n    if not cleaned_lines.endswith(\"\\n\"):\n        cleaned_lines += \"\\n\"\n    return cleaned_lines\n\n\ndef test_underline_basic():\n    doc = StmtBlockDoc(\n        [\n            ExprStmtDoc(make_id_doc(\"foo\")),\n            ExprStmtDoc(OperationDoc(OperationKind.Add, [make_id_doc(\"bar\"), make_id_doc(\"baz\")])),\n            ExprStmtDoc(make_id_doc(\"qux\")),\n        ]\n    )\n    assert to_python_script(doc, path_to_underline=make_path(\"baz\")) == format_script(\n        \"\"\"\n        foo\n        bar + baz\n              ^^^\n        qux\n    \"\"\"\n    )\n\n\ndef test_underline_multiple_spans():\n    doc = StmtBlockDoc(\n        [\n            ExprStmtDoc(make_id_doc(\"foo\")),\n            ExprStmtDoc(make_id_doc(\"bar\")),\n            ExprStmtDoc(OperationDoc(OperationKind.Add, [make_id_doc(\"foo\"), make_id_doc(\"foo\")])),\n        ]\n    )\n    assert to_python_script(doc, path_to_underline=make_path(\"foo\")) == format_script(\n        \"\"\"\n        foo\n        ^^^\n        bar\n        foo + foo\n        ^^^   ^^^\n    \"\"\"\n    )\n\n\ndef test_underline_multiple_spans_with_line_numbers():\n    doc = StmtBlockDoc(\n        [\n            ExprStmtDoc(make_id_doc(\"foo\")),\n            ExprStmtDoc(make_id_doc(\"bar\")),\n            ExprStmtDoc(OperationDoc(OperationKind.Add, [make_id_doc(\"foo\"), make_id_doc(\"foo\")])),\n        ]\n    )\n    assert to_python_script(\n        doc, print_line_numbers=True, path_to_underline=make_path(\"foo\")\n    ) == format_script(\n        \"\"\"\n        1 foo\n          ^^^\n        2 bar\n        3 foo + foo\n          ^^^   ^^^\n    \"\"\"\n    )\n\n\ndef test_underline_multiline():\n    doc = StmtBlockDoc(\n        [\n            ExprStmtDoc(IdDoc(\"foo\")),\n            ExprStmtDoc(IdDoc(\"bar\")),\n        ]\n    )\n    doc.source_paths = [make_path(\"whole_doc\")]\n\n    assert to_python_script(doc, path_to_underline=make_path(\"whole_doc\")) == format_script(\n        \"\"\"\n        foo\n        ^^^\n        bar\n        ^^^\n    \"\"\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"to_underline, expected_text\",\n    [\n        (\n            [0],\n            \"\"\"\n                x0\n                ^^\n                x1\n                x2\n                (... 7 lines skipped ...)\n            \"\"\",\n        ),\n        (\n            [1],\n            \"\"\"\n                x0\n                x1\n                ^^\n                x2\n                x3\n                (... 6 lines skipped ...)\n            \"\"\",\n        ),\n        (\n            [3],\n            \"\"\"\n                x0\n                x1\n                x2\n                x3\n                ^^\n                x4\n                x5\n                (... 4 lines skipped ...)\n            \"\"\",\n        ),\n        (\n            [4],\n            \"\"\"\n                (... 2 lines skipped ...)\n                x2\n                x3\n                x4\n                ^^\n                x5\n                x6\n                (... 3 lines skipped ...)\n            \"\"\",\n        ),\n        (\n            [6],\n            \"\"\"\n                (... 4 lines skipped ...)\n                x4\n                x5\n                x6\n                ^^\n                x7\n                x8\n                x9\n            \"\"\",\n        ),\n        (\n            [9],\n            \"\"\"\n                (... 7 lines skipped ...)\n                x7\n                x8\n                x9\n                ^^\n            \"\"\",\n        ),\n        (\n            [0, 9],\n            \"\"\"\n                x0\n                ^^\n                x1\n                x2\n                (... 4 lines skipped ...)\n                x7\n                x8\n                x9\n                ^^\n            \"\"\",\n        ),\n        (\n            [0, 3, 9],\n            \"\"\"\n                x0\n                ^^\n                x1\n                x2\n                x3\n                ^^\n                x4\n                x5\n                x6\n                x7\n                x8\n                x9\n                ^^\n            \"\"\",\n        ),\n        (\n            [0, 6, 9],\n            \"\"\"\n                x0\n                ^^\n                x1\n                x2\n                x3\n                x4\n                x5\n                x6\n                ^^\n                x7\n                x8\n                x9\n                ^^\n            \"\"\",\n        ),\n        (\n            [33],\n            \"\"\"\n                x0\n                x1\n                x2\n                x3\n                x4\n                x5\n                x6\n                x7\n                x8\n                x9\n            \"\"\",\n        ),\n    ],\n)\ndef test_print_two_context_lines(to_underline, expected_text):\n    doc = StmtBlockDoc(\n        [ExprStmtDoc(make_id_doc(f\"x{i}\", \"yes\" if i in to_underline else \"no\")) for i in range(10)]\n    )\n    result = to_python_script(doc, num_context_lines=2, path_to_underline=make_path(\"yes\"))\n    assert result == format_script(expected_text)\n\n\ndef test_underline_and_print_line_numbers():\n    doc = StmtBlockDoc([ExprStmtDoc(make_id_doc(f\"line{i + 1}\")) for i in range(12)])\n    result = to_python_script(doc, print_line_numbers=True, path_to_underline=make_path(\"line6\"))\n    assert result == format_script(\n        \"\"\"\n            1 line1\n            2 line2\n            3 line3\n            4 line4\n            5 line5\n            6 line6\n              ^^^^^\n            7 line7\n            8 line8\n            9 line9\n           10 line10\n           11 line11\n           12 line12\n    \"\"\"\n    )\n\n\ndef test_underline_and_print_line_numbers_with_context():\n    doc = StmtBlockDoc([ExprStmtDoc(make_id_doc(f\"line{i + 1}\")) for i in range(12)])\n    result = to_python_script(\n        doc, print_line_numbers=True, num_context_lines=2, path_to_underline=make_path(\"line8\")\n    )\n    assert result == format_script(\n        \"\"\"\n           (... 5 lines skipped ...)\n            6 line6\n            7 line7\n            8 line8\n              ^^^^^\n            9 line9\n           10 line10\n           (... 2 lines skipped ...)\n    \"\"\"\n    )\n\n\ndef test_underline_based_on_path_prefix():\n    doc = StmtBlockDoc([ExprStmtDoc(make_id_doc(\"foo\")), ExprStmtDoc(make_id_doc(\"bar\"))])\n    result = to_python_script(doc, path_to_underline=make_path(\"foo\").attr(\"x\").attr(\"y\"))\n    # There is no document that matches the desired path exactly,\n    # but path of \"foo\" is a prefix of the desired path, and thus should be underlined.\n    assert result == format_script(\n        \"\"\"\n        foo\n        ^^^\n        bar\n    \"\"\"\n    )\n\n\ndef test_longer_prefix_must_win():\n    foo_x = IdDoc(\"foo_x\")\n    foo_x.source_paths = [make_path(\"foo\").attr(\"x\")]\n\n    doc = StmtBlockDoc(\n        [ExprStmtDoc(make_id_doc(\"foo\")), ExprStmtDoc(make_id_doc(\"bar\")), ExprStmtDoc(foo_x)]\n    )\n    result = to_python_script(doc, path_to_underline=make_path(\"foo\").attr(\"x\").attr(\"y\"))\n    # \"foo\" should not be underlined because there is a document with a more specific path prefix\n    assert result == format_script(\n        \"\"\"\n        foo\n        bar\n        foo_x\n        ^^^^^\n    \"\"\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_printer_var_table.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nThis file tests the FFI binding of script.printer.VarTable.\nThese only make sure parameter can be passed to the C++ functions\ncorrectly. The test for the functionality of VarTable is in C++.\n\"\"\"\n\nfrom tvm.runtime import ObjectPath\nfrom tvm.script.printer.doc import LiteralDoc\nfrom tvm.script.printer.frame import VarDefFrame\nfrom tvm.script.printer.var_table import VarTable\nfrom tvm.tir import Var\n\n\ndef test_define():\n    var_table = VarTable()\n    var_name = \"a\"\n    var_obj = Var(var_name, dtype=\"int32\")\n    object_path = ObjectPath.root().attr(\"a\")\n    frame = VarDefFrame()\n\n    id_doc = var_table.define(var_obj, var_name, object_path, frame)\n\n    assert id_doc.name == \"a\"\n    assert list(id_doc.source_paths) == [object_path]\n\n    id_doc = var_table.get_var_doc(var_obj, object_path)\n\n    assert id_doc.name == \"a\"\n    assert list(id_doc.source_paths) == [object_path]\n\n\ndef test_define_by_doc():\n    var_table = VarTable()\n    var_name = \"a\"\n    var_obj = Var(var_name, dtype=\"int32\")\n    object_path = ObjectPath.root().attr(\"a\")\n    frame = VarDefFrame()\n\n    var_table.define_by_doc(var_obj, lambda: LiteralDoc(var_name), frame)\n\n    var_doc = var_table.get_var_doc(var_obj, object_path)\n\n    assert isinstance(var_doc, LiteralDoc)\n    assert var_doc.value == var_name\n    assert list(var_doc.source_paths) == [object_path]\n\n\ndef test_is_var_defined():\n    var_table = VarTable()\n    a = Var(\"a\", dtype=\"int32\")\n    object_path = ObjectPath.root().attr(\"a\")\n    frame = VarDefFrame()\n\n    var_table.define(a, \"a\", object_path, frame)\n\n    assert var_table.is_var_defined(a)\n    assert a in var_table\n\n\ndef test_var_out_of_scope():\n    var_table = VarTable()\n    var_name = \"a\"\n    var_obj = Var(var_name, dtype=\"int32\")\n    object_path = ObjectPath.root().attr(\"a\")\n    frame = VarDefFrame()\n\n    var_table.define(var_obj, var_name, object_path, frame)\n\n    with frame:\n        assert var_obj in var_table\n\n    assert var_obj not in var_table\n    assert var_table.get_var_doc(var_obj, object_path) is None\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_regression.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport numpy\n\nimport tvm\nfrom tvm.script import tir as T\n\n\n# This numpy array is used to test the comparison between the global objects and the\n# `tvm.script.tir` submodule.\nnp_array = numpy.array([0, 1, 2, 3])\n\n\n@T.prim_func\ndef matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i, j, k in T.grid(128, 128, 128):\n        with T.block(\"update\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = T.float32(0)\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n\ndef test_multi_element_array_in_outmost_namespace():\n    func = matmul\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n\nif __name__ == \"__main__\":\n    test_multi_element_array_in_outmost_namespace()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_roundtrip.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport pytest\n\nimport tvm\nimport tvm.testing\nfrom tvm import tir\nfrom tvm.script import tir as T\n\nimport numpy as np\n\n\ndef opt_gemm_normalize():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def mmult(A: T.handle, B: T.handle, C: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"mmult\", \"tir.noalias\": True})\n            # buffer definition\n            C_global = T.buffer_decl([1024, 1024], elem_offset=0, align=64, offset_factor=1)\n            packedB = T.buffer_decl([32, 1024, 32], elem_offset=0, align=64, offset_factor=1)\n            A_1 = T.match_buffer(A, [1024, 1024], elem_offset=0, align=64, offset_factor=1)\n            B_1 = T.match_buffer(B, [1024, 1024], elem_offset=0, align=64, offset_factor=1)\n            C_1 = T.match_buffer(C, [1024, 1024], elem_offset=0, align=64, offset_factor=1)\n            # body\n            T.realize(packedB[0:32, 0:1024, 0:32], \"\")\n            for x in T.parallel(0, 32):\n                for y in T.serial(0, 1024):\n                    for z in T.vectorized(0, 32):\n                        packedB[x, y, z] = B_1[y, ((x * 32) + z)]\n            T.realize(C_1[0:1024, 0:1024], \"\")\n            for x_outer in T.parallel(0, 32):\n                for y_outer in T.serial(0, 32):\n                    T.realize(\n                        C_global[\n                            (x_outer * 32) : ((x_outer * 32) + 32),\n                            (y_outer * 32) : ((y_outer * 32) + 32),\n                        ],\n                        \"global\",\n                    )\n                    for x_c_init in T.serial(0, 32):\n                        for y_c_init in T.vectorized(0, 32):\n                            C_global[\n                                (x_c_init + (x_outer * 32)), (y_c_init + (y_outer * 32))\n                            ] = T.float32(0)\n                    for k_outer in T.serial(0, 256):\n                        for x_c in T.serial(0, 32):\n                            for k_inner in T.unroll(0, 4):\n                                for y_c in T.vectorized(0, 32):\n                                    C_global[\n                                        (x_c + (x_outer * 32)), (y_c + (y_outer * 32))\n                                    ] = C_global[(x_c + (x_outer * 32)), (y_c + (y_outer * 32))] + (\n                                        A_1[(x_c + (x_outer * 32)), (k_inner + (k_outer * 4))]\n                                        * packedB[\n                                            T.floordiv((y_c + (y_outer * 32)), 32),\n                                            (k_inner + (k_outer * 4)),\n                                            T.floormod((y_c + (y_outer * 32)), 32),\n                                        ]\n                                    )\n                    for x_inner in T.serial(0, 32):\n                        for y_inner in T.serial(0, 32):\n                            C_1[(x_inner + (x_outer * 32)), (y_inner + (y_outer * 32))] = C_global[\n                                (x_inner + (x_outer * 32)), (y_inner + (y_outer * 32))\n                            ]\n\n    return Module\n\n\ndef opt_gemm_lower():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def mmult(A: T.handle, B: T.handle, C: T.handle) -> None:\n            # function attr dict\n            T.func_attr({\"global_symbol\": \"mmult\", \"tir.noalias\": True})\n            A_1 = T.match_buffer(A, [16384], elem_offset=0, align=64, offset_factor=1)\n            B_1 = T.match_buffer(B, [1024, 1024], elem_offset=0, align=64, offset_factor=1)\n            C_1 = T.match_buffer(C, [16384], elem_offset=0, align=64, offset_factor=1)\n            # body\n            packedB_data = T.allocate([32768], \"float32\", \"global\")\n            packedB = T.buffer_decl(\n                shape=[32768], dtype=\"float32\", scope=\"global\", data=packedB_data\n            )\n            for x in T.parallel(0, 32):\n                for y in T.serial(0, 1024):\n                    packedB[T.ramp(((x * 32768) + (y * 32)), 1, 32)] = B_1[y, T.ramp(x * 32, 1, 32)]\n            for x_outer in T.parallel(0, 32):\n                C_global_data = T.allocate([1024], \"float32\", \"global\")\n                C_global = T.buffer_decl(\n                    shape=[1024], dtype=\"float32\", scope=\"global\", data=C_global_data\n                )\n                for y_outer in T.serial(0, 32):\n                    for x_c_init in T.serial(0, 32):\n                        C_global[T.ramp((x_c_init * 32), 1, 32)] = T.broadcast(T.float32(0), 32)\n                    for k_outer in T.serial(0, 256):\n                        for x_c in T.serial(0, 32):\n                            C_global[T.ramp((x_c * 32), 1, 32)] = C_global[\n                                T.ramp((x_c * 32), 1, 32)\n                            ] + (\n                                T.broadcast(\n                                    A_1[\n                                        (((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)),\n                                    ],\n                                    32,\n                                )\n                                * packedB[T.ramp(((y_outer * 32768) + (k_outer * 128)), 1, 32)]\n                            )\n                            C_global[T.ramp((x_c * 32), 1, 32)] = C_global[\n                                T.ramp((x_c * 32), 1, 32)\n                            ] + (\n                                T.broadcast(\n                                    A_1[\n                                        ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 1),\n                                    ],\n                                    32,\n                                )\n                                * packedB[\n                                    T.ramp((((y_outer * 32768) + (k_outer * 128)) + 32), 1, 32)\n                                ]\n                            )\n                            C_global[T.ramp((x_c * 32), 1, 32)] = C_global[\n                                T.ramp((x_c * 32), 1, 32)\n                            ] + (\n                                T.broadcast(\n                                    A_1[\n                                        ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 2),\n                                    ],\n                                    32,\n                                )\n                                * packedB[\n                                    T.ramp((((y_outer * 32768) + (k_outer * 128)) + 64), 1, 32)\n                                ]\n                            )\n                            C_global[T.ramp((x_c * 32), 1, 32)] = C_global[\n                                T.ramp((x_c * 32), 1, 32)\n                            ] + (\n                                T.broadcast(\n                                    A_1[\n                                        ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 3),\n                                    ],\n                                    32,\n                                )\n                                * packedB[\n                                    T.ramp((((y_outer * 32768) + (k_outer * 128)) + 96), 1, 32)\n                                ]\n                            )\n                    for x_inner in T.serial(0, 32):\n                        for y_inner in T.serial(0, 32):\n                            C_1[\n                                (\n                                    (((x_outer * 32768) + (x_inner * 1024)) + (y_outer * 32))\n                                    + y_inner\n                                )\n                            ] = C_global[((x_inner * 32) + y_inner)]\n\n    return Module\n\n\ndef opt_gemm_mod_host():\n    @tvm.script.ir_module\n    class Module:\n        @T.prim_func\n        def mmult(\n            args: T.handle,\n            arg_type_ids: T.handle,\n            num_args: T.int32,\n            out_ret_value: T.handle,\n            out_ret_tcode: T.handle,\n        ) -> T.int32:\n            # function attr dict\n            T.func_attr(\n                {\n                    \"tir.noalias\": True,\n                    \"global_symbol\": \"mmult\",\n                    \"tir.is_entry_func\": True,\n                    \"calling_conv\": 1,\n                }\n            )\n            # buffer definition\n            buf_type_ids = T.match_buffer(arg_type_ids, [3], dtype=\"int32\")\n\n            packedB = T.buffer_decl([32768], dtype=\"float32\")\n            C_global = T.buffer_decl([1024], dtype=\"float32\")\n            # var definition\n            # C_global = T.buffer_var(\"float32\", \"global\")\n            # packedB = T.buffer_var(\"float32\", \"global\")\n            # body\n            assert num_args == 3, \"mmult: num_args should be 3\"\n            arg0: T.handle = T.tvm_struct_get(args, 0, 12, dtype=\"handle\")\n            arg0_code: T.int32 = buf_type_ids[0]\n            arg1: T.handle = T.tvm_struct_get(args, 1, 12, dtype=\"handle\")\n            arg1_code: T.int32 = buf_type_ids[1]\n            arg2: T.handle = T.tvm_struct_get(args, 2, 12, dtype=\"handle\")\n            arg2_code: T.int32 = buf_type_ids[2]\n\n            A_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 1, dtype=\"handle\")\n            T.attr(A_data, \"storage_alignment\", 128)\n            A = T.buffer_decl([1024 * 1024], dtype=\"int32\", data=A_data)\n            buf0_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 2, dtype=\"handle\")\n            buf0_shape = T.buffer_decl([2], dtype=\"int32\", data=buf0_shape_data)\n            buf0_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 3, dtype=\"handle\")\n            buf0_strides = T.buffer_decl([2], dtype=\"int32\", data=buf0_strides_data)\n\n            dev_id: T.int32 = T.tvm_struct_get(arg0, 0, 9, dtype=\"int32\")\n\n            B_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 1, dtype=\"handle\")\n            T.attr(B_data, \"storage_alignment\", 128)\n            B = T.buffer_decl([1024 * 1024], dtype=\"int32\", data=B_data)\n            buf1_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 2, dtype=\"handle\")\n            buf1_shape = T.buffer_decl([2], dtype=\"int32\", data=buf1_shape_data)\n            buf1_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 3, dtype=\"handle\")\n            buf1_strides = T.buffer_decl([2], dtype=\"int32\", data=buf1_strides_data)\n\n            C_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 1, dtype=\"handle\")\n            T.attr(C_data, \"storage_alignment\", 128)\n            C = T.buffer_decl([1024 * 1024], dtype=\"int32\", data=C_data)\n            buf2_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 2, dtype=\"handle\")\n            buf2_shape = T.buffer_decl([2], dtype=\"int32\", data=buf2_shape_data)\n            buf2_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 3, dtype=\"handle\")\n            buf2_strides = T.buffer_decl([2], dtype=\"int32\", data=buf2_strides_data)\n\n            assert (((arg0_code == 3) or (arg0_code == 13)) or (arg0_code == 7)) or (\n                arg0_code == 4\n            ), \"mmult: Expect arg[0] to be pointer\"\n            assert (((arg1_code == 3) or (arg1_code == 13)) or (arg1_code == 7)) or (\n                arg1_code == 4\n            ), \"mmult: Expect arg[1] to be pointer\"\n            assert (((arg2_code == 3) or (arg2_code == 13)) or (arg2_code == 7)) or (\n                arg2_code == 4\n            ), \"mmult: Expect arg[2] to be pointer\"\n            assert 2 == T.tvm_struct_get(\n                arg0, 0, 4, dtype=\"int32\"\n            ), \"arg0.ndim is expected to equal 2\"\n            assert 2 == T.tvm_struct_get(\n                arg0, 0, 4, dtype=\"int32\"\n            ), \"arg0.ndim is expected to equal 2\"\n            assert (\n                (T.tvm_struct_get(arg0, 0, 5, dtype=\"uint8\") == T.uint8(2))\n                and (T.tvm_struct_get(arg0, 0, 6, dtype=\"uint8\") == T.uint8(32))\n            ) and (\n                T.tvm_struct_get(arg0, 0, 7, dtype=\"uint16\") == T.uint16(1)\n            ), \"arg0.dtype is expected to be float32\"\n            assert 1024 == T.cast(\n                buf0_shape[0], \"int32\"\n            ), \"Argument arg0.shape[0] has an unsatisfied constraint\"\n            assert 1024 == T.cast(\n                buf0_shape[1], \"int32\"\n            ), \"Argument arg0.shape[1] has an unsatisfied constraint\"\n            if not (T.isnullptr(buf0_strides.data, dtype=\"bool\")):\n                assert (1 == T.cast(buf0_strides[1], \"int32\")) and (\n                    1024 == T.cast(buf0_strides[0], \"int32\")\n                ), \"arg0.strides: expected to be compact array\"\n                T.evaluate(0)\n            assert T.uint64(0) == T.tvm_struct_get(\n                arg0, 0, 8, dtype=\"uint64\"\n            ), \"Argument arg0.byte_offset has an unsatisfied constraint\"\n            assert 1 == T.tvm_struct_get(\n                arg0, 0, 10, dtype=\"int32\"\n            ), \"Argument arg0.device_type has an unsatisfied constraint\"\n            assert 2 == T.tvm_struct_get(\n                arg1, 0, 4, dtype=\"int32\"\n            ), \"arg1.ndim is expected to equal 2\"\n            assert 2 == T.tvm_struct_get(\n                arg1, 0, 4, dtype=\"int32\"\n            ), \"arg1.ndim is expected to equal 2\"\n            assert (\n                (T.tvm_struct_get(arg1, 0, 5, dtype=\"uint8\") == T.uint8(2))\n                and (T.tvm_struct_get(arg1, 0, 6, dtype=\"uint8\") == T.uint8(32))\n            ) and (\n                T.tvm_struct_get(arg1, 0, 7, dtype=\"uint16\") == T.uint16(1)\n            ), \"arg1.dtype is expected to be float32\"\n            assert 1024 == T.cast(\n                buf1_shape[0], \"int32\"\n            ), \"Argument arg1.shape[0] has an unsatisfied constraint\"\n            assert 1024 == T.cast(\n                buf1_shape[1], \"int32\"\n            ), \"Argument arg1.shape[1] has an unsatisfied constraint\"\n            if not (T.isnullptr(buf1_strides.data, dtype=\"bool\")):\n                assert (1 == T.cast(buf1_strides[1], \"int32\")) and (\n                    1024 == T.cast(buf1_strides[0], \"int32\")\n                ), \"arg1.strides: expected to be compact array\"\n                T.evaluate(0)\n            assert T.uint64(0) == T.tvm_struct_get(\n                arg1, 0, 8, dtype=\"uint64\"\n            ), \"Argument arg1.byte_offset has an unsatisfied constraint\"\n            assert 1 == T.tvm_struct_get(\n                arg1, 0, 10, dtype=\"int32\"\n            ), \"Argument arg1.device_type has an unsatisfied constraint\"\n            assert dev_id == T.tvm_struct_get(\n                arg1, 0, 9, dtype=\"int32\"\n            ), \"Argument arg1.device_id has an unsatisfied constraint\"\n            assert 2 == T.tvm_struct_get(\n                arg2, 0, 4, dtype=\"int32\"\n            ), \"arg2.ndim is expected to equal 2\"\n            assert 2 == T.tvm_struct_get(\n                arg2, 0, 4, dtype=\"int32\"\n            ), \"arg2.ndim is expected to equal 2\"\n            assert (\n                (T.tvm_struct_get(arg2, 0, 5, dtype=\"uint8\") == T.uint8(2))\n                and (T.tvm_struct_get(arg2, 0, 6, dtype=\"uint8\") == T.uint8(32))\n            ) and (\n                T.tvm_struct_get(arg2, 0, 7, dtype=\"uint16\") == T.uint16(1)\n            ), \"arg2.dtype is expected to be float32\"\n            assert 1024 == T.cast(\n                buf2_shape[0], \"int32\"\n            ), \"Argument arg2.shape[0] has an unsatisfied constraint\"\n            assert 1024 == T.cast(\n                buf2_shape[1], \"int32\"\n            ), \"Argument arg2.shape[1] has an unsatisfied constraint\"\n            if not (T.isnullptr(buf2_strides.data, dtype=\"bool\")):\n                assert (1 == T.cast(buf2_strides[1], \"int32\")) and (\n                    1024 == T.cast(buf2_strides[0], \"int32\")\n                ), \"arg2.strides: expected to be compact array\"\n                T.evaluate(0)\n            assert T.uint64(0) == T.tvm_struct_get(\n                arg2, 0, 8, dtype=\"uint64\"\n            ), \"Argument arg2.byte_offset has an unsatisfied constraint\"\n            assert 1 == T.tvm_struct_get(\n                arg2, 0, 10, dtype=\"int32\"\n            ), \"Argument arg2.device_type has an unsatisfied constraint\"\n            assert dev_id == T.tvm_struct_get(\n                arg2, 0, 9, dtype=\"int32\"\n            ), \"Argument arg2.device_id has an unsatisfied constraint\"\n            T.attr(0, \"compute_scope\", \"mmult_compute_\")\n            T.attr(packedB.data, \"storage_scope\", \"global\")\n            T.attr(packedB.data, \"storage_alignment\", 128)\n            with T.let(\n                packedB.data,\n                T.TVMBackendAllocWorkspace(1, dev_id, T.uint64(4194304), 2, 32, dtype=\"handle\"),\n            ):\n                if T.isnullptr(packedB.data, dtype=\"bool\"):\n                    T.evaluate(T.tvm_throw_last_error(dtype=\"int32\"))\n                for x in T.parallel(0, 32):\n                    for y in T.serial(0, 1024):\n                        packedB[T.ramp(((x * 32768) + (y * 32)), 1, 32)] = B[\n                            T.ramp(((y * 1024) + (x * 32)), 1, 32)\n                        ]\n                for x_outer in T.parallel(0, 32):\n                    T.attr(C_global.data, \"storage_scope\", \"global\")\n                    T.attr(C_global.data, \"storage_alignment\", 128)\n                    with T.let(\n                        C_global.data,\n                        T.TVMBackendAllocWorkspace(\n                            1, dev_id, T.uint64(4096), 2, 32, dtype=\"handle\"\n                        ),\n                    ):\n                        if T.isnullptr(C_global.data, dtype=\"bool\"):\n                            T.evaluate(T.tvm_throw_last_error(dtype=\"int32\"))\n                        for y_outer in T.serial(0, 32):\n                            for x_c_init in T.serial(0, 32):\n                                C_global[T.ramp((x_c_init * 32), 1, 32)] = T.broadcast(\n                                    T.float32(0), 32\n                                )\n                            for k_outer in T.serial(0, 256):\n                                for x_c in T.serial(0, 32):\n                                    C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin(\n                                        T.uint32(97),\n                                        T.uint32(3),\n                                        T.broadcast(\n                                            A[\n                                                (\n                                                    ((x_outer * 32768) + (x_c * 1024))\n                                                    + (k_outer * 4)\n                                                ),\n                                            ],\n                                            32,\n                                        ),\n                                        packedB[\n                                            T.ramp(((y_outer * 32768) + (k_outer * 128)), 1, 32)\n                                        ],\n                                        C_global[T.ramp((x_c * 32), 1, 32)],\n                                        dtype=\"float32x32\",\n                                    )\n                                    C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin(\n                                        T.uint32(97),\n                                        T.uint32(3),\n                                        T.broadcast(\n                                            A[\n                                                (\n                                                    (\n                                                        ((x_outer * 32768) + (x_c * 1024))\n                                                        + (k_outer * 4)\n                                                    )\n                                                    + 1\n                                                ),\n                                            ],\n                                            32,\n                                        ),\n                                        packedB[\n                                            T.ramp(\n                                                (((y_outer * 32768) + (k_outer * 128)) + 32), 1, 32\n                                            )\n                                        ],\n                                        C_global[T.ramp((x_c * 32), 1, 32)],\n                                        dtype=\"float32x32\",\n                                    )\n                                    C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin(\n                                        T.uint32(97),\n                                        T.uint32(3),\n                                        T.broadcast(\n                                            A[\n                                                (\n                                                    (\n                                                        ((x_outer * 32768) + (x_c * 1024))\n                                                        + (k_outer * 4)\n                                                    )\n                                                    + 2\n                                                ),\n                                            ],\n                                            32,\n                                        ),\n                                        packedB[\n                                            T.ramp(\n                                                (((y_outer * 32768) + (k_outer * 128)) + 64), 1, 32\n                                            )\n                                        ],\n                                        C_global[T.ramp((x_c * 32), 1, 32)],\n                                        dtype=\"float32x32\",\n                                    )\n                                    C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin(\n                                        T.uint32(97),\n                                        T.uint32(3),\n                                        T.broadcast(\n                                            A[\n                                                (\n                                                    (\n                                                        ((x_outer * 32768) + (x_c * 1024))\n                                                        + (k_outer * 4)\n                                                    )\n                                                    + 3\n                                                ),\n                                            ],\n                                            32,\n                                        ),\n                                        packedB[\n                                            T.ramp(\n                                                (((y_outer * 32768) + (k_outer * 128)) + 96), 1, 32\n                                            )\n                                        ],\n                                        C_global[T.ramp((x_c * 32), 1, 32)],\n                                        dtype=\"float32x32\",\n                                    )\n                            for x_inner in T.serial(0, 32):\n                                for y_inner in T.serial(0, 32):\n                                    C[\n                                        (\n                                            (\n                                                ((x_outer * 32768) + (x_inner * 1024))\n                                                + (y_outer * 32)\n                                            )\n                                            + y_inner\n                                        )\n                                    ] = C_global[((x_inner * 32) + y_inner)]\n                    if T.TVMBackendFreeWorkspace(1, dev_id, C_global.data, dtype=\"int32\") != 0:\n                        T.evaluate(T.tvm_throw_last_error(dtype=\"int32\"))\n            if T.TVMBackendFreeWorkspace(1, dev_id, packedB.data, dtype=\"int32\") != 0:\n                T.evaluate(T.tvm_throw_last_error(dtype=\"int32\"))\n\n    return Module\n\n\ndef opt_conv_tensorcore_normalize():\n    @T.prim_func\n    def func(A: T.handle, W: T.handle, Conv: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n        # var definition\n        bx = T.env_thread(\"blockIdx.x\")\n        by = T.env_thread(\"blockIdx.y\")\n        bz = T.env_thread(\"blockIdx.z\")\n        tx = T.env_thread(\"threadIdx.x\")\n        ty = T.env_thread(\"threadIdx.y\")\n        tz = T.env_thread(\"threadIdx.z\")\n        # buffer definition\n        Apad_shared = T.buffer_decl(\n            [16, 16, 16, 16, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        Apad_shared_wmma_matrix_a = T.buffer_decl(\n            [16, 16, 16, 16, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        BA = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"wmma.matrix_a\", align=32, offset_factor=256\n        )\n        BB = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"wmma.matrix_b\", align=32, offset_factor=256\n        )\n        BC = T.buffer_decl([16, 16], scope=\"wmma.accumulator\", align=32, offset_factor=256)\n        Conv_wmma_accumulator = T.buffer_decl(\n            [16, 14, 14, 32, 16, 16], elem_offset=0, align=64, offset_factor=1\n        )\n        W_shared = T.buffer_decl(\n            [3, 3, 16, 32, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        W_shared_wmma_matrix_b = T.buffer_decl(\n            [3, 3, 16, 32, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        buffer = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"shared\", align=32, offset_factor=256\n        )\n        buffer_1 = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"wmma.matrix_a\", align=32, offset_factor=256\n        )\n        buffer_2 = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"shared\", align=32, offset_factor=256\n        )\n        buffer_3 = T.buffer_decl(\n            [16, 16], dtype=\"float16\", scope=\"wmma.matrix_b\", align=32, offset_factor=256\n        )\n        buffer_4 = T.buffer_decl([16, 16], scope=\"wmma.accumulator\", align=32, offset_factor=256)\n        buffer_5 = T.buffer_decl([16, 16], align=32, offset_factor=256)\n        A_1 = T.match_buffer(\n            A, [16, 14, 14, 16, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        W_1 = T.match_buffer(\n            W, [3, 3, 16, 32, 16, 16], dtype=\"float16\", elem_offset=0, align=64, offset_factor=1\n        )\n        Conv_1 = T.match_buffer(\n            Conv, [16, 14, 14, 32, 16, 16], elem_offset=0, align=64, offset_factor=1\n        )\n        # body\n        T.realize(Conv_1[0:16, 0:14, 0:14, 0:32, 0:16, 0:16], \"\")\n        T.launch_thread(bz, 196)\n        T.launch_thread(bx, 2)\n        T.launch_thread(by, 4)\n        T.launch_thread(ty, 4)\n        T.launch_thread(tz, 2)\n        T.realize(\n            Conv_wmma_accumulator[\n                ((bx * 8) + (ty * 2)) : (((bx * 8) + (ty * 2)) + 2),\n                T.floordiv(bz, 14) : (T.floordiv(bz, 14) + 1),\n                T.floormod(bz, 14) : (T.floormod(bz, 14) + 1),\n                ((by * 8) + (tz * 4)) : (((by * 8) + (tz * 4)) + 4),\n                0:16,\n                0:16,\n            ],\n            \"wmma.accumulator\",\n        )\n        for n_c_init in T.serial(0, 2):\n            for o_c_init in T.serial(0, 4):\n                T.attr(\n                    [BC, Conv_wmma_accumulator],\n                    \"buffer_bind_scope\",\n                    T.tvm_tuple(\n                        (n_c_init + ((bx * 8) + (ty * 2))),\n                        1,\n                        T.floordiv(bz, 14),\n                        1,\n                        T.floormod(bz, 14),\n                        1,\n                        (o_c_init + ((by * 8) + (tz * 4))),\n                        1,\n                        0,\n                        16,\n                        0,\n                        16,\n                        dtype=\"handle\",\n                    ),\n                )\n                T.evaluate(\n                    T.tvm_fill_fragment(\n                        BC.data,\n                        16,\n                        16,\n                        16,\n                        T.floordiv(BC.elem_offset, 256),\n                        T.float32(0),\n                        dtype=\"handle\",\n                    )\n                )\n\n        for ic_outer in T.serial(0, 8):\n            for kh in T.serial(0, 3):\n                T.realize(\n                    Apad_shared[\n                        (bx * 8) : ((bx * 8) + 8),\n                        (T.floordiv(bz, 14) + kh) : ((T.floordiv(bz, 14) + kh) + 1),\n                        T.floormod(bz, 14) : (T.floormod(bz, 14) + 3),\n                        (ic_outer * 2) : ((ic_outer * 2) + 2),\n                        0:16,\n                        0:16,\n                    ],\n                    \"shared\",\n                )\n                for ax2 in T.serial(0, 3):\n                    for ax3 in T.serial(0, 2):\n                        for ax4_ax5_fused_outer in T.serial(0, 8):\n                            T.launch_thread(tx, 32)\n                            Apad_shared[\n                                ((tz + (ty * 2)) + (bx * 8)),\n                                (T.floordiv(bz, 14) + kh),\n                                (ax2 + T.floormod(bz, 14)),\n                                (ax3 + (ic_outer * 2)),\n                                T.floordiv((tx + (ax4_ax5_fused_outer * 32)), 16),\n                                T.floormod((tx + (ax4_ax5_fused_outer * 32)), 16),\n                            ] = T.if_then_else(\n                                (\n                                    (\n                                        (\n                                            ((T.floordiv(bz, 14) + kh) >= 1)\n                                            and (((T.floordiv(bz, 14) + kh) - 1) < 14)\n                                        )\n                                        and ((ax2 + T.floormod(bz, 14)) >= 1)\n                                    )\n                                    and (((ax2 + T.floormod(bz, 14)) - 1) < 14)\n                                ),\n                                A_1[\n                                    ((tz + (ty * 2)) + (bx * 8)),\n                                    ((T.floordiv(bz, 14) + kh) - 1),\n                                    ((ax2 + T.floormod(bz, 14)) - 1),\n                                    (ax3 + (ic_outer * 2)),\n                                    T.floordiv((tx + (ax4_ax5_fused_outer * 32)), 16),\n                                    T.floormod((tx + (ax4_ax5_fused_outer * 32)), 16),\n                                ],\n                                T.float16(0),\n                                dtype=\"float16\",\n                            )\n                T.realize(\n                    W_shared[\n                        kh : (kh + 1),\n                        0:3,\n                        (ic_outer * 2) : ((ic_outer * 2) + 2),\n                        (by * 8) : ((by * 8) + 8),\n                        0:16,\n                        0:16,\n                    ],\n                    \"shared\",\n                )\n                for ax1 in T.serial(0, 3):\n                    for ax2_1 in T.serial(0, 2):\n                        T.launch_thread(tx, 32)\n                        for ax4_ax5_fused_inner in T.vectorized(0, 8):\n                            W_shared[\n                                kh,\n                                ax1,\n                                (ax2_1 + (ic_outer * 2)),\n                                ((tz + (ty * 2)) + (by * 8)),\n                                T.floordiv((ax4_ax5_fused_inner + (tx * 8)), 16),\n                                T.floormod((ax4_ax5_fused_inner + (tx * 8)), 16),\n                            ] = W_1[\n                                kh,\n                                ax1,\n                                (ax2_1 + (ic_outer * 2)),\n                                ((tz + (ty * 2)) + (by * 8)),\n                                T.floordiv((ax4_ax5_fused_inner + (tx * 8)), 16),\n                                T.floormod((ax4_ax5_fused_inner + (tx * 8)), 16),\n                            ]\n                for ic_inner in T.serial(0, 2):\n                    for kw in T.serial(0, 3):\n                        T.realize(\n                            Apad_shared_wmma_matrix_a[\n                                ((bx * 8) + (ty * 2)) : (((bx * 8) + (ty * 2)) + 2),\n                                (T.floordiv(bz, 14) + kh) : ((T.floordiv(bz, 14) + kh) + 1),\n                                (kw + T.floormod(bz, 14)) : ((kw + T.floormod(bz, 14)) + 1),\n                                ((ic_outer * 2) + ic_inner) : (((ic_outer * 2) + ic_inner) + 1),\n                                0:16,\n                                0:16,\n                            ],\n                            \"wmma.matrix_a\",\n                        )\n                        for ax0 in T.serial(0, 2):\n                            T.attr(\n                                [buffer, Apad_shared],\n                                \"buffer_bind_scope\",\n                                T.tvm_tuple(\n                                    (ax0 + ((bx * 8) + (ty * 2))),\n                                    1,\n                                    (T.floordiv(bz, 14) + kh),\n                                    1,\n                                    (kw + T.floormod(bz, 14)),\n                                    1,\n                                    ((ic_outer * 2) + ic_inner),\n                                    1,\n                                    0,\n                                    16,\n                                    0,\n                                    16,\n                                    dtype=\"handle\",\n                                ),\n                            )\n                            T.attr(\n                                [buffer_1, Apad_shared_wmma_matrix_a],\n                                \"buffer_bind_scope\",\n                                T.tvm_tuple(\n                                    (ax0 + ((bx * 8) + (ty * 2))),\n                                    1,\n                                    (T.floordiv(bz, 14) + kh),\n                                    1,\n                                    (kw + T.floormod(bz, 14)),\n                                    1,\n                                    ((ic_outer * 2) + ic_inner),\n                                    1,\n                                    0,\n                                    16,\n                                    0,\n                                    16,\n                                    dtype=\"handle\",\n                                ),\n                            )\n                            T.evaluate(\n                                T.tvm_load_matrix_sync(\n                                    buffer_1.data,\n                                    16,\n                                    16,\n                                    16,\n                                    T.floordiv(buffer_1.elem_offset, 256),\n                                    T.tvm_access_ptr(\n                                        T.type_annotation(dtype=\"float16\"),\n                                        buffer.data,\n                                        buffer.elem_offset,\n                                        256,\n                                        1,\n                                        dtype=\"handle\",\n                                    ),\n                                    16,\n                                    \"row_major\",\n                                    dtype=\"handle\",\n                                )\n                            )\n                        T.realize(\n                            W_shared_wmma_matrix_b[\n                                kh : (kh + 1),\n                                kw : (kw + 1),\n                                ((ic_outer * 2) + ic_inner) : (((ic_outer * 2) + ic_inner) + 1),\n                                ((by * 8) + (tz * 4)) : (((by * 8) + (tz * 4)) + 4),\n                                0:16,\n                                0:16,\n                            ],\n                            \"wmma.matrix_b\",\n                        )\n                        for ax3_1 in T.serial(0, 4):\n                            T.attr(\n                                [buffer_2, W_shared],\n                                \"buffer_bind_scope\",\n                                T.tvm_tuple(\n                                    kh,\n                                    1,\n                                    kw,\n                                    1,\n                                    ((ic_outer * 2) + ic_inner),\n                                    1,\n                                    (ax3_1 + ((by * 8) + (tz * 4))),\n                                    1,\n                                    0,\n                                    16,\n                                    0,\n                                    16,\n                                    dtype=\"handle\",\n                                ),\n                            )\n                            T.attr(\n                                [buffer_3, W_shared_wmma_matrix_b],\n                                \"buffer_bind_scope\",\n                                T.tvm_tuple(\n                                    kh,\n                                    1,\n                                    kw,\n                                    1,\n                                    ((ic_outer * 2) + ic_inner),\n                                    1,\n                                    (ax3_1 + ((by * 8) + (tz * 4))),\n                                    1,\n                                    0,\n                                    16,\n                                    0,\n                                    16,\n                                    dtype=\"handle\",\n                                ),\n                            )\n                            T.evaluate(\n                                T.tvm_load_matrix_sync(\n                                    buffer_3.data,\n                                    16,\n                                    16,\n                                    16,\n                                    T.floordiv(buffer_3.elem_offset, 256),\n                                    T.tvm_access_ptr(\n                                        T.type_annotation(dtype=\"float16\"),\n                                        buffer_2.data,\n                                        buffer_2.elem_offset,\n                                        256,\n                                        1,\n                                        dtype=\"handle\",\n                                    ),\n                                    16,\n                                    \"row_major\",\n                                    dtype=\"handle\",\n                                )\n                            )\n                        for n_c in T.serial(0, 2):\n                            for o_c in T.serial(0, 4):\n                                T.attr(\n                                    [BA, Apad_shared_wmma_matrix_a],\n                                    \"buffer_bind_scope\",\n                                    T.tvm_tuple(\n                                        (n_c + ((bx * 8) + (ty * 2))),\n                                        1,\n                                        (T.floordiv(bz, 14) + kh),\n                                        1,\n                                        (T.floormod(bz, 14) + kw),\n                                        1,\n                                        ((ic_outer * 2) + ic_inner),\n                                        1,\n                                        0,\n                                        16,\n                                        0,\n                                        16,\n                                        dtype=\"handle\",\n                                    ),\n                                )\n                                T.attr(\n                                    [BB, W_shared_wmma_matrix_b],\n                                    \"buffer_bind_scope\",\n                                    T.tvm_tuple(\n                                        kh,\n                                        1,\n                                        kw,\n                                        1,\n                                        ((ic_outer * 2) + ic_inner),\n                                        1,\n                                        (o_c + ((by * 8) + (tz * 4))),\n                                        1,\n                                        0,\n                                        16,\n                                        0,\n                                        16,\n                                        dtype=\"handle\",\n                                    ),\n                                )\n                                T.attr(\n                                    [BC, Conv_wmma_accumulator],\n                                    \"buffer_bind_scope\",\n                                    T.tvm_tuple(\n                                        (n_c + ((bx * 8) + (ty * 2))),\n                                        1,\n                                        T.floordiv(bz, 14),\n                                        1,\n                                        T.floormod(bz, 14),\n                                        1,\n                                        (o_c + ((by * 8) + (tz * 4))),\n                                        1,\n                                        0,\n                                        16,\n                                        0,\n                                        16,\n                                        dtype=\"handle\",\n                                    ),\n                                )\n                                T.evaluate(\n                                    T.tvm_mma_sync(\n                                        BC.data,\n                                        T.floordiv(BC.elem_offset, 256),\n                                        BA.data,\n                                        T.floordiv(BA.elem_offset, 256),\n                                        BB.data,\n                                        T.floordiv(BB.elem_offset, 256),\n                                        BC.data,\n                                        T.floordiv(BC.elem_offset, 256),\n                                        dtype=\"handle\",\n                                    )\n                                )\n        for n_inner in T.serial(0, 2):\n            for o_inner in T.serial(0, 4):\n                T.attr(\n                    [buffer_4, Conv_wmma_accumulator],\n                    \"buffer_bind_scope\",\n                    T.tvm_tuple(\n                        ((((bx * 4) + ty) * 2) + n_inner),\n                        1,\n                        T.floordiv(bz, 14),\n                        1,\n                        T.floormod(bz, 14),\n                        1,\n                        ((((by * 2) + tz) * 4) + o_inner),\n                        1,\n                        0,\n                        16,\n                        0,\n                        16,\n                        dtype=\"handle\",\n                    ),\n                )\n                T.attr(\n                    [buffer_5, Conv_1],\n                    \"buffer_bind_scope\",\n                    T.tvm_tuple(\n                        ((((bx * 4) + ty) * 2) + n_inner),\n                        1,\n                        T.floordiv(bz, 14),\n                        1,\n                        T.floormod(bz, 14),\n                        1,\n                        ((((by * 2) + tz) * 4) + o_inner),\n                        1,\n                        0,\n                        16,\n                        0,\n                        16,\n                        dtype=\"handle\",\n                    ),\n                )\n                T.evaluate(\n                    T.tvm_store_matrix_sync(\n                        buffer_4.data,\n                        16,\n                        16,\n                        16,\n                        T.floordiv(buffer_4.elem_offset, 256),\n                        T.tvm_access_ptr(\n                            T.type_annotation(dtype=\"float32\"),\n                            buffer_5.data,\n                            buffer_5.elem_offset,\n                            256,\n                            2,\n                            dtype=\"handle\",\n                        ),\n                        16,\n                        \"row_major\",\n                        dtype=\"handle\",\n                    )\n                )\n\n    return func\n\n\ndef opt_conv_tensorcore_lower():\n    @T.prim_func\n    def func(\n        A: T.Buffer[(16, 14, 14, 16, 16, 16), \"float16\"],\n        W: T.Buffer[(3, 3, 16, 32, 16, 16), \"float16\"],\n        Conv: T.Buffer[(16, 14, 14, 32, 16, 16), \"float32\"],\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"default_function\", \"tir.noalias\": True})\n        # body\n        A_1 = T.buffer_decl([12845056], dtype=\"float16\", data=A.data)\n        W_1 = T.buffer_decl([1179648], dtype=\"float16\", data=W.data)\n        Conv_1 = T.buffer_decl([25690112], data=Conv.data)\n        bx = T.env_thread(\"blockIdx.x\")\n        by = T.env_thread(\"blockIdx.y\")\n        bz = T.env_thread(\"blockIdx.z\")\n        tx = T.env_thread(\"threadIdx.x\")\n        ty = T.env_thread(\"threadIdx.y\")\n        tz = T.env_thread(\"threadIdx.z\")\n        T.launch_thread(bz, 196)\n        Conv_wmma_accumulator_data = T.allocate([2048], \"float32\", \"wmma.accumulator\")\n        Conv_wmma_accumulator = T.buffer_decl(\n            shape=[2048], dtype=\"float32\", scope=\"wmma.accumulator\", data=Conv_wmma_accumulator_data\n        )\n        Apad_shared_data = T.allocate([12288], \"float16\", \"shared\")\n        Apad_shared = T.buffer_decl(\n            shape=[12288], dtype=\"float16\", scope=\"shared\", data=Apad_shared_data\n        )\n        W_shared_data = T.allocate([12288], \"float16\", \"shared\")\n        W_shared = T.buffer_decl(shape=[12288], dtype=\"float16\", scope=\"shared\", data=W_shared_data)\n        Apad_shared_wmma_matrix_a_data = T.allocate([512], \"float16\", \"wmma.matrix_a\")\n        Apad_shared_wmma_matrix_a = T.buffer_decl(\n            shape=[512], dtype=\"float16\", scope=\"wmma.matrix_a\", data=Apad_shared_wmma_matrix_a_data\n        )\n        W_shared_wmma_matrix_b_data = T.allocate([1024], \"float16\", \"wmma.matrix_b\")\n        W_shared_wmma_matrix_b = T.buffer_decl(\n            shape=[1024], dtype=\"float16\", scope=\"wmma.matrix_b\", data=W_shared_wmma_matrix_b_data\n        )\n        T.launch_thread(bx, 2)\n        T.launch_thread(by, 4)\n        T.launch_thread(ty, 4)\n        T.launch_thread(tz, 2)\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 0, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 1, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 2, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 3, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 4, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 5, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 6, T.float32(0), dtype=\"handle\"\n            )\n        )\n        T.evaluate(\n            T.tvm_fill_fragment(\n                Conv_wmma_accumulator.data, 16, 16, 16, 7, T.float32(0), dtype=\"handle\"\n            )\n        )\n        for ic_outer in T.serial(0, 8):\n            for kh in T.serial(0, 3):\n                for ax2 in T.serial(0, 3):\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            ((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61440\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 32)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61408\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 64)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61376\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 96)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61344\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 128)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61312\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 160)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61280\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 192)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61248\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 224)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61216\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 256)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61184\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 288)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61152\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 320)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61120\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 352)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61088\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 384)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61056\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 416)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 61024\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    with T.launch_thread(tx, 32):\n                        Apad_shared[\n                            (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 448)\n                        ] = T.if_then_else(\n                            (\n                                (\n                                    (\n                                        (1 <= (T.floordiv(bz, 14) + kh))\n                                        and ((T.floordiv(bz, 14) + kh) < 15)\n                                    )\n                                    and (1 <= (ax2 + T.floormod(bz, 14)))\n                                )\n                                and ((ax2 + T.floormod(bz, 14)) < 15)\n                            ),\n                            A_1[\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        (\n                                                            ((bx * 6422528) + (ty * 1605632))\n                                                            + (tz * 802816)\n                                                        )\n                                                        + (kh * 57344)\n                                                    )\n                                                    + (bz * 4096)\n                                                )\n                                                + (ax2 * 4096)\n                                            )\n                                            + (ic_outer * 512)\n                                        )\n                                        + tx\n                                    )\n                                    - 60992\n                                ),\n                            ],\n                            T.float16(0),\n                            dtype=\"float16\",\n                        )\n                    T.launch_thread(tx, 32)\n                    Apad_shared[\n                        (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 480)\n                    ] = T.if_then_else(\n                        (\n                            (\n                                (\n                                    (1 <= (T.floordiv(bz, 14) + kh))\n                                    and ((T.floordiv(bz, 14) + kh) < 15)\n                                )\n                                and (1 <= (ax2 + T.floormod(bz, 14)))\n                            )\n                            and ((ax2 + T.floormod(bz, 14)) < 15)\n                        ),\n                        A_1[\n                            (\n                                (\n                                    (\n                                        (\n                                            (\n                                                (\n                                                    (\n                                                        ((bx * 6422528) + (ty * 1605632))\n                                                        + (tz * 802816)\n                                                    )\n                                                    + (kh * 57344)\n                                                )\n                                                + (bz * 4096)\n                                            )\n                                            + (ax2 * 4096)\n                                        )\n                                        + (ic_outer * 512)\n                                    )\n                                    + tx\n                                )\n                                - 60960\n                            ),\n                        ],\n                        T.float16(0),\n                        dtype=\"float16\",\n                    )\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp((((ty * 512) + (tz * 256)) + (tx * 8)), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                        + (ty * 512)\n                                    )\n                                    + (tz * 256)\n                                )\n                                + (tx * 8)\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp(((((ty * 512) + (tz * 256)) + (tx * 8)) + 2048), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (\n                                            (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                            + (ty * 512)\n                                        )\n                                        + (tz * 256)\n                                    )\n                                    + (tx * 8)\n                                )\n                                + 8192\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp(((((ty * 512) + (tz * 256)) + (tx * 8)) + 4096), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (\n                                            (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                            + (ty * 512)\n                                        )\n                                        + (tz * 256)\n                                    )\n                                    + (tx * 8)\n                                )\n                                + 131072\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp(((((ty * 512) + (tz * 256)) + (tx * 8)) + 6144), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (\n                                            (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                            + (ty * 512)\n                                        )\n                                        + (tz * 256)\n                                    )\n                                    + (tx * 8)\n                                )\n                                + 139264\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp(((((ty * 512) + (tz * 256)) + (tx * 8)) + 8192), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (\n                                            (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                            + (ty * 512)\n                                        )\n                                        + (tz * 256)\n                                    )\n                                    + (tx * 8)\n                                )\n                                + 262144\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                with T.launch_thread(tx, 32):\n                    W_shared[T.ramp(((((ty * 512) + (tz * 256)) + (tx * 8)) + 10240), 1, 8)] = W_1[\n                        T.ramp(\n                            (\n                                (\n                                    (\n                                        (\n                                            (((kh * 393216) + (ic_outer * 16384)) + (by * 2048))\n                                            + (ty * 512)\n                                        )\n                                        + (tz * 256)\n                                    )\n                                    + (tx * 8)\n                                )\n                                + 270336\n                            ),\n                            1,\n                            8,\n                        )\n                    ]\n                for ic_inner in T.serial(0, 2):\n                    for kw in T.serial(0, 3):\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                Apad_shared_wmma_matrix_a.data,\n                                16,\n                                16,\n                                16,\n                                0,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    Apad_shared.data,\n                                    (((ty * 3072) + (kw * 512)) + (ic_inner * 256)),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                Apad_shared_wmma_matrix_a.data,\n                                16,\n                                16,\n                                16,\n                                1,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    Apad_shared.data,\n                                    ((((ty * 3072) + (kw * 512)) + (ic_inner * 256)) + 1536),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                W_shared_wmma_matrix_b.data,\n                                16,\n                                16,\n                                16,\n                                0,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    W_shared.data,\n                                    (((kw * 4096) + (ic_inner * 2048)) + (tz * 1024)),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                W_shared_wmma_matrix_b.data,\n                                16,\n                                16,\n                                16,\n                                1,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    W_shared.data,\n                                    ((((kw * 4096) + (ic_inner * 2048)) + (tz * 1024)) + 256),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                W_shared_wmma_matrix_b.data,\n                                16,\n                                16,\n                                16,\n                                2,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    W_shared.data,\n                                    ((((kw * 4096) + (ic_inner * 2048)) + (tz * 1024)) + 512),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_load_matrix_sync(\n                                W_shared_wmma_matrix_b.data,\n                                16,\n                                16,\n                                16,\n                                3,\n                                T.tvm_access_ptr(\n                                    T.type_annotation(dtype=\"float16\"),\n                                    W_shared.data,\n                                    ((((kw * 4096) + (ic_inner * 2048)) + (tz * 1024)) + 768),\n                                    256,\n                                    1,\n                                    dtype=\"handle\",\n                                ),\n                                16,\n                                \"row_major\",\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                0,\n                                Apad_shared_wmma_matrix_a.data,\n                                0,\n                                W_shared_wmma_matrix_b.data,\n                                0,\n                                Conv_wmma_accumulator.data,\n                                0,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                1,\n                                Apad_shared_wmma_matrix_a.data,\n                                0,\n                                W_shared_wmma_matrix_b.data,\n                                1,\n                                Conv_wmma_accumulator.data,\n                                1,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                2,\n                                Apad_shared_wmma_matrix_a.data,\n                                0,\n                                W_shared_wmma_matrix_b.data,\n                                2,\n                                Conv_wmma_accumulator.data,\n                                2,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                3,\n                                Apad_shared_wmma_matrix_a.data,\n                                0,\n                                W_shared_wmma_matrix_b.data,\n                                3,\n                                Conv_wmma_accumulator.data,\n                                3,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                4,\n                                Apad_shared_wmma_matrix_a.data,\n                                1,\n                                W_shared_wmma_matrix_b.data,\n                                0,\n                                Conv_wmma_accumulator.data,\n                                4,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                5,\n                                Apad_shared_wmma_matrix_a.data,\n                                1,\n                                W_shared_wmma_matrix_b.data,\n                                1,\n                                Conv_wmma_accumulator.data,\n                                5,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                6,\n                                Apad_shared_wmma_matrix_a.data,\n                                1,\n                                W_shared_wmma_matrix_b.data,\n                                2,\n                                Conv_wmma_accumulator.data,\n                                6,\n                                dtype=\"handle\",\n                            )\n                        )\n                        T.evaluate(\n                            T.tvm_mma_sync(\n                                Conv_wmma_accumulator.data,\n                                7,\n                                Apad_shared_wmma_matrix_a.data,\n                                1,\n                                W_shared_wmma_matrix_b.data,\n                                3,\n                                Conv_wmma_accumulator.data,\n                                7,\n                                dtype=\"handle\",\n                            )\n                        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                0,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                        + (tz * 1024)\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                1,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 256\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                2,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 512\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                3,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 768\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                4,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 1605632\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                5,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 1605888\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                6,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 1606144\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n        T.evaluate(\n            T.tvm_store_matrix_sync(\n                Conv_wmma_accumulator.data,\n                16,\n                16,\n                16,\n                7,\n                T.tvm_access_ptr(\n                    T.type_annotation(dtype=\"float32\"),\n                    Conv_1.data,\n                    (\n                        (\n                            ((((bx * 12845056) + (ty * 3211264)) + (bz * 8192)) + (by * 2048))\n                            + (tz * 1024)\n                        )\n                        + 1606400\n                    ),\n                    256,\n                    2,\n                    dtype=\"handle\",\n                ),\n                16,\n                \"row_major\",\n                dtype=\"handle\",\n            )\n        )\n\n    return func\n\n\ndef opt_conv_tensorcore_mod_host():\n    @T.prim_func\n    def opt_conv_tensorcore_mod_host(\n        args: T.handle,\n        arg_type_ids: T.Buffer[(3,), \"int32\"],\n        num_args: T.int32,\n        out_ret_value: T.handle,\n        out_ret_tcode: T.handle,\n        resource_handle: T.handle,\n    ) -> T.int32:\n        # function attr dict\n        T.func_attr(\n            {\n                \"tir.noalias\": True,\n                \"global_symbol\": \"default_function\",\n                \"tir.is_entry_func\": True,\n                \"calling_conv\": 1,\n            }\n        )\n        # body\n        stack_tcode_data: T.Ptr[T.int32] = T.tvm_stack_alloca(\"arg_tcode\", 10, dtype=\"handle\")\n        stack_tcode = T.buffer_decl([9], \"int32\", data=stack_tcode_data)\n        stack_value: T.handle = T.tvm_stack_alloca(\"arg_value\", 10, dtype=\"handle\")\n        assert num_args == 3, \"default_function: num_args should be 3\"\n        arg0: T.handle = T.tvm_struct_get(args, 0, 12, dtype=\"handle\")\n        arg0_code: T.int32 = arg_type_ids[0]\n        arg1: T.handle = T.tvm_struct_get(args, 1, 12, dtype=\"handle\")\n        arg1_code: T.int32 = arg_type_ids[1]\n        arg2: T.handle = T.tvm_struct_get(args, 2, 12, dtype=\"handle\")\n        arg2_code: T.int32 = arg_type_ids[2]\n\n        A: T.handle = T.tvm_struct_get(arg0, 0, 1, dtype=\"handle\")\n        T.attr(A, \"storage_alignment\", 128)\n        arg0_shape_data: T.Ptr[T.int64] = T.tvm_struct_get(arg0, 0, 2, dtype=\"handle\")\n        arg0_shape = T.buffer_decl([6], \"int64\", data=arg0_shape_data)\n        arg0_strides_data: T.Ptr[T.int64] = T.tvm_struct_get(arg0, 0, 3, dtype=\"handle\")\n        arg0_strides = T.buffer_decl([6], \"int64\", data=arg0_strides_data)\n\n        dev_id: T.int32 = T.tvm_struct_get(arg0, 0, 9, dtype=\"int32\")\n\n        W: T.handle = T.tvm_struct_get(arg1, 0, 1, dtype=\"handle\")\n        T.attr(W, \"storage_alignment\", 128)\n        arg1_shape_data: T.Ptr[T.int64] = T.tvm_struct_get(arg1, 0, 2, dtype=\"handle\")\n        arg1_shape = T.buffer_decl([6], \"int64\", data=arg1_shape_data)\n        arg1_strides_data: T.Ptr[T.int64] = T.tvm_struct_get(arg1, 0, 3, dtype=\"handle\")\n        arg1_strides = T.buffer_decl([6], \"int64\", data=arg1_strides_data)\n\n        Conv: T.handle = T.tvm_struct_get(arg2, 0, 1, dtype=\"handle\")\n        T.attr(Conv, \"storage_alignment\", 128)\n        arg2_shape_data: T.Ptr[T.int64] = T.tvm_struct_get(arg2, 0, 2, dtype=\"handle\")\n        arg2_shape = T.buffer_decl([6], \"int64\", data=arg2_shape_data)\n        arg2_strides_data: T.Ptr[T.int64] = T.tvm_struct_get(arg2, 0, 3, dtype=\"handle\")\n        arg2_strides = T.buffer_decl([6], \"int64\", data=arg2_strides_data)\n\n        assert (((arg0_code == 3) or (arg0_code == 13)) or (arg0_code == 7)) or (\n            arg0_code == 4\n        ), \"default_function: Expect arg[0] to be pointer\"\n        assert (((arg1_code == 3) or (arg1_code == 13)) or (arg1_code == 7)) or (\n            arg1_code == 4\n        ), \"default_function: Expect arg[1] to be pointer\"\n        assert (((arg2_code == 3) or (arg2_code == 13)) or (arg2_code == 7)) or (\n            arg2_code == 4\n        ), \"default_function: Expect arg[2] to be pointer\"\n        assert 6 == T.tvm_struct_get(arg0, 0, 4, dtype=\"int32\"), \"arg0.ndim is expected to equal 6\"\n        assert 6 == T.tvm_struct_get(arg0, 0, 4, dtype=\"int32\"), \"arg0.ndim is expected to equal 6\"\n        assert (\n            (T.tvm_struct_get(arg0, 0, 5, dtype=\"uint8\") == T.uint8(2))\n            and (T.tvm_struct_get(arg0, 0, 6, dtype=\"uint8\") == T.uint8(16))\n        ) and (\n            T.tvm_struct_get(arg0, 0, 7, dtype=\"uint16\") == T.uint16(1)\n        ), \"arg0.dtype is expected to be float16\"\n        assert 16 == T.cast(\n            arg0_shape[0], \"int32\"\n        ), \"Argument arg0.shape[0] has an unsatisfied constraint\"\n        assert 14 == T.cast(\n            arg0_shape[1], \"int32\"\n        ), \"Argument arg0.shape[1] has an unsatisfied constraint\"\n        assert 14 == T.cast(\n            arg0_shape[2], \"int32\"\n        ), \"Argument arg0.shape[2] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg0_shape[3], \"int32\"\n        ), \"Argument arg0.shape[3] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg0_shape[4], \"int32\"\n        ), \"Argument arg0.shape[4] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg0_shape[5], \"int32\"\n        ), \"Argument arg0.shape[5] has an unsatisfied constraint\"\n        if not (T.isnullptr(arg0_strides.data, dtype=\"bool\")):\n            assert (\n                (\n                    (\n                        (\n                            (1 == T.cast(arg0_strides[5], \"int32\"))\n                            and (16 == T.cast(arg0_strides[4], \"int32\"))\n                        )\n                        and (256 == T.cast(arg0_strides[3], \"int32\"))\n                    )\n                    and (4096 == T.cast(arg0_strides[2], \"int32\"))\n                )\n                and (57344 == T.cast(arg0_strides[1], \"int32\"))\n            ) and (\n                802816 == T.cast(arg0_strides[0], \"int32\")\n            ), \"arg0.strides: expected to be compact array\"\n            T.evaluate(0)\n        assert T.uint64(0) == T.tvm_struct_get(\n            arg0, 0, 8, dtype=\"uint64\"\n        ), \"Argument arg0.byte_offset has an unsatisfied constraint\"\n        assert 2 == T.tvm_struct_get(\n            arg0, 0, 10, dtype=\"int32\"\n        ), \"Argument arg0.device_type has an unsatisfied constraint\"\n        assert 6 == T.tvm_struct_get(arg1, 0, 4, dtype=\"int32\"), \"arg1.ndim is expected to equal 6\"\n        assert 6 == T.tvm_struct_get(arg1, 0, 4, dtype=\"int32\"), \"arg1.ndim is expected to equal 6\"\n        assert (\n            (T.tvm_struct_get(arg1, 0, 5, dtype=\"uint8\") == T.uint8(2))\n            and (T.tvm_struct_get(arg1, 0, 6, dtype=\"uint8\") == T.uint8(16))\n        ) and (\n            T.tvm_struct_get(arg1, 0, 7, dtype=\"uint16\") == T.uint16(1)\n        ), \"arg1.dtype is expected to be float16\"\n        assert 3 == T.cast(\n            arg1_shape[0], \"int32\"\n        ), \"Argument arg1.shape[0] has an unsatisfied constraint\"\n        assert 3 == T.cast(\n            arg1_shape[1], \"int32\"\n        ), \"Argument arg1.shape[1] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg1_shape[2], \"int32\"\n        ), \"Argument arg1.shape[2] has an unsatisfied constraint\"\n        assert 32 == T.cast(\n            arg1_shape[3], \"int32\"\n        ), \"Argument arg1.shape[3] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg1_shape[4], \"int32\"\n        ), \"Argument arg1.shape[4] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg1_shape[5], \"int32\"\n        ), \"Argument arg1.shape[5] has an unsatisfied constraint\"\n        if not (T.isnullptr(arg1_strides.data, dtype=\"bool\")):\n            assert (\n                (\n                    (\n                        (\n                            (1 == T.cast(arg1_strides[5], \"int32\"))\n                            and (16 == T.cast(arg1_strides[4], \"int32\"))\n                        )\n                        and (256 == T.cast(arg1_strides[3], \"int32\"))\n                    )\n                    and (8192 == T.cast(arg1_strides[2], \"int32\"))\n                )\n                and (131072 == T.cast(arg1_strides[1], \"int32\"))\n            ) and (\n                393216 == T.cast(arg1_strides[0], \"int32\")\n            ), \"arg1.strides: expected to be compact array\"\n            T.evaluate(0)\n        assert T.uint64(0) == T.tvm_struct_get(\n            arg1, 0, 8, dtype=\"uint64\"\n        ), \"Argument arg1.byte_offset has an unsatisfied constraint\"\n        assert 2 == T.tvm_struct_get(\n            arg1, 0, 10, dtype=\"int32\"\n        ), \"Argument arg1.device_type has an unsatisfied constraint\"\n        assert dev_id == T.tvm_struct_get(\n            arg1, 0, 9, dtype=\"int32\"\n        ), \"Argument arg1.device_id has an unsatisfied constraint\"\n        assert 6 == T.tvm_struct_get(arg2, 0, 4, dtype=\"int32\"), \"arg2.ndim is expected to equal 6\"\n        assert 6 == T.tvm_struct_get(arg2, 0, 4, dtype=\"int32\"), \"arg2.ndim is expected to equal 6\"\n        assert (\n            (T.tvm_struct_get(arg2, 0, 5, dtype=\"uint8\") == T.uint8(2))\n            and (T.tvm_struct_get(arg2, 0, 6, dtype=\"uint8\") == T.uint8(32))\n        ) and (\n            T.tvm_struct_get(arg2, 0, 7, dtype=\"uint16\") == T.uint16(1)\n        ), \"arg2.dtype is expected to be float32\"\n        assert 16 == T.cast(\n            arg2_shape[0], \"int32\"\n        ), \"Argument arg2.shape[0] has an unsatisfied constraint\"\n        assert 14 == T.cast(\n            arg2_shape[1], \"int32\"\n        ), \"Argument arg2.shape[1] has an unsatisfied constraint\"\n        assert 14 == T.cast(\n            arg2_shape[2], \"int32\"\n        ), \"Argument arg2.shape[2] has an unsatisfied constraint\"\n        assert 32 == T.cast(\n            arg2_shape[3], \"int32\"\n        ), \"Argument arg2.shape[3] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg2_shape[4], \"int32\"\n        ), \"Argument arg2.shape[4] has an unsatisfied constraint\"\n        assert 16 == T.cast(\n            arg2_shape[5], \"int32\"\n        ), \"Argument arg2.shape[5] has an unsatisfied constraint\"\n        if not (T.isnullptr(arg2_strides.data, dtype=\"bool\")):\n            assert (\n                (\n                    (\n                        (\n                            (1 == T.cast(arg2_strides[5], \"int32\"))\n                            and (16 == T.cast(arg2_strides[4], \"int32\"))\n                        )\n                        and (256 == T.cast(arg2_strides[3], \"int32\"))\n                    )\n                    and (8192 == T.cast(arg2_strides[2], \"int32\"))\n                )\n                and (114688 == T.cast(arg2_strides[1], \"int32\"))\n            ) and (\n                1605632 == T.cast(arg2_strides[0], \"int32\")\n            ), \"arg2.strides: expected to be compact array\"\n            T.evaluate(0)\n        assert T.uint64(0) == T.tvm_struct_get(\n            arg2, 0, 8, dtype=\"uint64\"\n        ), \"Argument arg2.byte_offset has an unsatisfied constraint\"\n        assert 2 == T.tvm_struct_get(\n            arg2, 0, 10, dtype=\"int32\"\n        ), \"Argument arg2.device_type has an unsatisfied constraint\"\n        assert dev_id == T.tvm_struct_get(\n            arg2, 0, 9, dtype=\"int32\"\n        ), \"Argument arg2.device_id has an unsatisfied constraint\"\n        T.evaluate(T.tvm_struct_set(stack_value, 0, 12, T.cast(2, \"int64\"), dtype=\"int32\"))\n        stack_tcode[0] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 1, 12, T.cast(dev_id, \"int64\"), dtype=\"int32\"))\n        stack_tcode[1] = 0\n        T.evaluate(\n            T.tvm_call_packed_lowered(\n                \"__tvm_set_device\", stack_value, stack_tcode.data, 0, 2, dtype=\"int32\"\n            )\n        )\n        T.attr(0, \"compute_scope\", \"default_function_compute_\")\n        T.evaluate(T.tvm_struct_set(stack_value, 0, 12, A, dtype=\"int32\"))\n        stack_tcode[0] = 3\n        T.evaluate(T.tvm_struct_set(stack_value, 1, 12, W, dtype=\"int32\"))\n        stack_tcode[1] = 3\n        T.evaluate(T.tvm_struct_set(stack_value, 2, 12, Conv, dtype=\"int32\"))\n        stack_tcode[2] = 3\n        T.evaluate(T.tvm_struct_set(stack_value, 3, 12, T.cast(196, \"int64\"), dtype=\"int32\"))\n        stack_tcode[3] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 4, 12, T.cast(2, \"int64\"), dtype=\"int32\"))\n        stack_tcode[4] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 5, 12, T.cast(4, \"int64\"), dtype=\"int32\"))\n        stack_tcode[5] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 6, 12, T.cast(4, \"int64\"), dtype=\"int32\"))\n        stack_tcode[6] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 7, 12, T.cast(2, \"int64\"), dtype=\"int32\"))\n        stack_tcode[7] = 0\n        T.evaluate(T.tvm_struct_set(stack_value, 8, 12, T.cast(32, \"int64\"), dtype=\"int32\"))\n        stack_tcode[8] = 0\n        T.evaluate(\n            T.tvm_call_packed_lowered(\n                \"default_function_kernel0\", stack_value, stack_tcode.data, 0, 9, dtype=\"int32\"\n            )\n        )\n\n    return opt_conv_tensorcore_mod_host\n\n\ndef vthread_func():\n    @T.prim_func\n    def vthread_func(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [256], \"float32\")\n        C = T.match_buffer(c, [256], \"float32\")\n\n        i0 = T.env_thread(\"blockIdx.x\")\n        i1 = T.env_thread(\"threadIdx.x\")\n        i2 = T.env_thread(\"vthread\")\n\n        T.launch_thread(i0, 4)\n        T.launch_thread(i1, 2)\n        T.launch_thread(i2, 2)\n        B_data = T.allocate([16], \"float32\", \"local\")\n        B = T.buffer_decl(shape=[16], dtype=\"float32\", scope=\"local\", data=B_data)\n        for j in range(16):\n            B[j] = A[i0 * 64 + i1 * 32 + i2 * 16 + j] + T.float32(1)\n        for j in range(16):\n            C[i0 * 64 + i1 * 32 + i2 * 16 + j] = B[j] * T.float32(2)\n\n    return vthread_func\n\n\ndef matmul():\n    @T.prim_func\n    def matmul(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        B = T.match_buffer(b, [128, 128])\n        C = T.match_buffer(c, [128, 128])\n\n        for i, j, k in T.grid(128, 128, 128):\n            with T.block(\"update\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                with T.init():\n                    C[vi, vj] = T.float32(0)\n                C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    return matmul\n\n\ndef matmul_original():\n    @T.prim_func\n    def matmul_original(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, [128, 128])\n        B = T.match_buffer(b, [128, 128])\n        C = T.match_buffer(c, [128, 128])\n\n        for i, j in T.grid(128, 128):\n            with T.block(\"init\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = T.float32(0)\n\n            for k in range(128):\n                with T.block(\"update\"):\n                    vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                    C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk]\n\n    return matmul_original\n\n\ndef element_wise():\n    @T.prim_func\n    def element_wise(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (128, 128), \"float32\")\n        C = T.match_buffer(c, (128, 128), \"float32\")\n        B = T.alloc_buffer((128, 128), \"float32\")\n\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * T.float32(2)\n        for i, j in T.grid(128, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n    return element_wise\n\n\ndef predicate():\n    @T.prim_func\n    def predicate(b: T.handle, c: T.handle) -> None:\n        B = T.match_buffer(b, (16, 16), \"float32\")\n        C = T.match_buffer(c, (16, 16), \"float32\")\n\n        for i, jo, ji in T.grid(16, 4, 5):\n            with T.block(\"update\"):\n                vi = T.axis.S(16, i)\n                vj = T.axis.S(16, jo * 4 + ji)\n                T.where(jo * 4 + ji < 16)\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n    return predicate\n\n\ndef test_module_define():\n    func1 = tvm.ir.IRModule({\"matmul\": matmul()})[\"matmul\"]\n    func2 = tvm.ir.IRModule({\"element_wise\": element_wise()})[\"element_wise\"]\n    func3 = tvm.ir.IRModule({\"predicate\": predicate()})[\"predicate\"]\n    mod1 = tvm.ir.IRModule({\"func1\": func1, \"func2\": func2, \"func3\": func3})\n    mod2 = tvm.ir.IRModule({\"func1\": matmul(), \"func2\": element_wise(), \"func3\": predicate()})\n    tvm.ir.assert_structural_equal(mod1, mod2)\n\n\ndef test_matmul_original():\n    func = matmul_original()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body.block, tir.stmt.Block)\n    assert isinstance(rt_func.body.block.body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body.body, tir.stmt.SeqStmt)\n    assert isinstance(rt_func.body.block.body.body.body[0].block, tir.stmt.Block)\n    assert isinstance(rt_func.body.block.body.body.body[1], tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body.body[1].body.block, tir.stmt.Block)\n\n\ndef test_element_wise():\n    func = element_wise()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body.block, tir.stmt.Block)\n    assert isinstance(rt_func.body.block.body, tir.stmt.SeqStmt)\n    assert isinstance(rt_func.body.block.body[0], tir.stmt.For)\n    assert isinstance(rt_func.body.block.body[0].body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body[0].body.body.block, tir.stmt.Block)\n\n    assert isinstance(rt_func.body.block.body[1], tir.stmt.For)\n    assert isinstance(rt_func.body.block.body[1].body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body[1].body.body.block, tir.stmt.Block)\n\n\ndef test_predicate():\n    func = predicate()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body.block, tir.stmt.Block)\n    assert isinstance(rt_func.body.block.body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body.body, tir.stmt.For)\n    assert isinstance(rt_func.body.block.body.body.body.body.block, tir.stmt.Block)\n\n\ndef for_thread_binding():\n    @T.prim_func\n    def for_thread_binding(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (16, 16), \"float32\")\n\n        for i in T.thread_binding(0, 16, thread=\"threadIdx.x\"):\n            for j in T.thread_binding(\n                0, 16, thread=\"threadIdx.y\", annotations={\"attr_key\": \"attr_value\"}\n            ):\n                A[i, j] = B[i, j] + T.float32(1)\n\n    return for_thread_binding\n\n\ndef test_for_thread_binding():\n    func = for_thread_binding()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body, tir.stmt.For)\n    assert rt_func.body.kind == 4\n    assert rt_func.body.thread_binding.thread_tag == \"threadIdx.x\"\n    assert isinstance(rt_func.body.body, tir.stmt.For)\n    assert rt_func.body.body.kind == 4\n    assert rt_func.body.body.thread_binding.thread_tag == \"threadIdx.y\"\n    assert rt_func.body.body.annotations[\"attr_key\"] == \"attr_value\"\n\n\ndef match_buffer_region():\n    @T.prim_func\n    def match_buffer_region(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16, 16), \"float32\")\n        B = T.match_buffer(b, (1), \"float32\")\n\n        for i, j in T.grid(16, 4):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C = T.match_buffer(A[0:16, vi, vj * 4 : vj * 4 + 4], (16, 1, 4))\n                for ii in range(4):\n                    with T.block():\n                        vii = T.axis.S(4, ii)\n                        D = T.match_buffer(C[vii * 4 : vii * 4 + 4, 0, 0:4], (4, 1, 4))\n                        for i, j in T.grid(4, 4):\n                            B[0] += D[i, 0, j]\n\n    return match_buffer_region\n\n\ndef test_match_buffer_region():\n    func = match_buffer_region()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body, tir.stmt.BlockRealize)\n    root = rt_func.body.block\n\n    assert isinstance(root.body, tir.stmt.For)\n    assert isinstance(root.body.body, tir.stmt.For)\n    assert isinstance(root.body.body.body, tir.stmt.BlockRealize)\n    outer_block = root.body.body.body.block\n    assert len(outer_block.match_buffers) == 1\n    buffer_C = outer_block.match_buffers[0].buffer\n    tvm.ir.assert_structural_equal(buffer_C.shape, [16, 1, 4])\n\n    assert isinstance(outer_block.body, tir.stmt.For)\n    assert isinstance(outer_block.body.body, tir.stmt.BlockRealize)\n    inner_block = outer_block.body.body.block\n    assert len(inner_block.match_buffers) == 1\n    buffer_D = inner_block.match_buffers[0].buffer\n    tvm.ir.assert_structural_equal(buffer_D.shape, [4, 1, 4])\n\n\ndef block_elements():\n    @T.prim_func\n    def block_elements(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (1, 1), \"float32\")\n\n        with T.block(\"update\"):\n            vi = T.axis.S(1, 0)\n            T.where(True)\n            T.reads(A[0:16, 0:16])\n            T.writes(B[0, 0])\n            T.block_attr({\"attr_key\": \"attr_value\"})\n            C = T.alloc_buffer((4, 4), dtype=\"float32\")\n            D = T.match_buffer(A[0:4, 0], (4, 1))\n            with T.init():\n                B[0, 0] = T.float32(0)\n            B[0, 0] = A[0, 0] + B[0, 0] + C[1, 1] + D[2, 0]\n\n    return block_elements\n\n\ndef test_block_elements():\n    func = block_elements()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert isinstance(rt_func.body.block, tir.stmt.Block)\n    assert isinstance(rt_func.body.block.body, tir.stmt.BlockRealize)\n    assert isinstance(rt_func.body.block.body.block, tir.stmt.Block)\n    block = rt_func.body.block.body.block\n    assert isinstance(block.body, tir.stmt.BufferStore)\n    assert isinstance(block.init, tir.stmt.BufferStore)\n    assert len(block.annotations) == 1\n    assert block.annotations[\"attr_key\"] == \"attr_value\"\n\n\ndef opaque_block():\n    @T.prim_func\n    def opaque_block(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        B = T.match_buffer(b, (16, 16), \"float32\")\n\n        for i in range(16):\n            for j in range(16):\n                with T.block():\n                    T.reads([])\n                    T.writes(A[i, j])\n                    A[i, j] = T.float32(0)\n            with T.block():\n                T.reads([A[i, 0:16]])\n                T.writes([B[i, 0:16]])\n                for j in range(16):\n                    B[i, j] = A[i, j]\n\n    return opaque_block\n\n\ndef test_opaque_block():\n    func = opaque_block()\n    rt_func = tvm.script.from_source(func.script(show_meta=True))\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    root_block = rt_func.body.block\n    assert isinstance(root_block, tir.stmt.Block)\n    assert isinstance(root_block.body, tir.stmt.For)\n    assert isinstance(root_block.body.body[0], tir.stmt.For)\n    assert isinstance(root_block.body.body[0].body, tir.stmt.BlockRealize)\n    assert isinstance(root_block.body.body[0].body.block, tir.stmt.Block)\n    assert len(root_block.body.body[0].body.block.iter_vars) == 0\n    assert isinstance(root_block.body.body[1], tir.stmt.BlockRealize)\n    assert isinstance(root_block.body.body[1].block, tir.stmt.Block)\n    assert len(root_block.body.body[1].block.iter_vars) == 0\n\n\ndef module_const():\n    @tvm.script.ir_module\n    class Module4:\n        # There is an ongoing (python)dict->(c++)Map->(python)dict issue which potentially\n        # changes order of the items in dict after roundtrip due to map not support order\n        # of insertion while dict does. Hence func 'def A(a: T.handle, c: T.handle) -> None'\n        # is commented\n        #\n        #  test:\n        #  d = {\"B\": 1, \"A\": 2}\n        #  m = tvm.runtime.convert(d)\n        #  assert d.keys() == m.keys(), f\"Order changed from {list(d.keys())} to {list(m.keys())}\"\n\n        \"\"\"\n        @T.prim_func\n        def A(a: T.handle, c: T.handle) -> None:\n            A = T.match_buffer(a, (10), \"int32\")\n            C = T.match_buffer(c, (10), \"int32\")\n            B = T.alloc_buffer((10), \"int32\")\n\n            K1 = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n            for x in T.serial(0, 10):\n                B[x] = A[x] + T.load(\"int32\", K1, x)\n\n            for x in T.serial(0, 10):\n                C[x] = B[x]\n        \"\"\"\n\n        @T.prim_func\n        def B(a: T.handle, c: T.handle) -> None:\n            A = T.match_buffer(a, (10), \"int32\")\n            C = T.match_buffer(c, (10), \"int32\")\n            B = T.alloc_buffer((10), \"int32\")\n\n            K1_data = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n            K1 = T.buffer_decl(shape=[10], dtype=\"int32\", data=K1_data)\n            for x in T.serial(0, 10):\n                B[x] = A[x] + K1[x]\n\n            K2_data = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n            K2 = T.buffer_decl(shape=[10], dtype=\"int32\", data=K2_data)\n            for x in T.serial(0, 10):\n                B[x] = B[x] + K2[x]\n\n            for x in T.serial(0, 10):\n                C[x] = B[x]\n\n    return Module4\n\n\ndef constant():\n    @T.prim_func\n    def constant(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (10), \"int32\")\n        C = T.match_buffer(c, (10), \"int32\")\n        B = T.alloc_buffer((10), \"int32\")\n        K_data = T.allocate_const([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \"int32\", [10])\n        K = T.buffer_decl(shape=[10], dtype=\"int32\", data=K_data)\n        for x in T.serial(0, 10):\n            B[x] = A[x] + K[x]\n\n        for x in T.serial(0, 10):\n            C[x] = B[x]\n\n    return constant\n\n\ndef rank0():\n    @T.prim_func\n    def rank0(a: T.handle) -> None:\n        A = T.match_buffer(a, (), \"float32\")\n        B = T.alloc_buffer((), \"float32\")\n        A[()] = 2\n        B[()] = A[()]\n\n    return rank0\n\n\ndef rank0_block():\n    @T.prim_func\n    def rank0_block(a: T.handle) -> None:\n        A = T.match_buffer(a, (), \"float32\")\n        B = T.alloc_buffer((), \"float32\")\n        B[()] = A[()]\n\n        with T.block(\"update\"):\n            T.reads([A[()]])\n            T.writes([B[()]])\n            for i in range(1):\n                B[()] = A[()]\n\n    return rank0_block\n\n\ndef select():\n    @T.prim_func\n    def select(a: T.handle) -> None:\n        A = T.match_buffer(a, (), \"float32\")\n        A[()] = T.Select(True, 1, 2)\n\n    return select\n\n\ndef minmax():\n    @T.prim_func\n    def minmax(a: T.handle) -> None:\n        A = T.match_buffer(a, (), \"float32\")\n        A[()] = T.min(1, 2)\n        A[()] = T.max(1, 2)\n\n    return minmax\n\n\ndef abs():\n    @T.prim_func\n    def abs(a: T.handle) -> None:\n        A = T.match_buffer(a, (128, 128), \"float32\")\n\n        for i, j in T.grid(128, 128):\n            with T.block(\"A\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                A[vi, vj] = T.abs(A[vi, vj])\n\n    return abs\n\n\ndef constant_folding():\n    @T.prim_func\n    def constant_folding(a: T.handle) -> None:\n        A = T.match_buffer(a, (), \"float32\")\n        A[()] = T.min(2.2, 5.2)\n        A[()] = T.max(T.float32(2.2), T.float32(T.float32(5.2)))\n        A[()] = T.min(2.2, 5.0)\n\n    return constant_folding\n\n\ndef simplify_bracket():\n    @T.prim_func\n    def simplify_bracket() -> None:\n        a = T.var(\"int32\")\n        b = T.var(\"int32\")\n        c = T.var(\"int32\")\n        d = T.var(\"int32\")\n        T.evaluate(a + b * (c + d))\n\n    return simplify_bracket\n\n\ndef var_with_same_name():\n    @T.prim_func\n    def var_with_same_name(a: T.handle) -> None:\n        A = T.match_buffer(a, (16, 16), \"float32\")\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                A[vi, vj] = 0\n        for i, j in T.grid(16, 16):\n            with T.block():\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                A[vi, vj] = 0\n\n    return var_with_same_name\n\n\ndef test_same_name_var():\n    func = var_with_same_name()\n    out_str = func.script(tir_prefix=\"T\", show_meta=True)\n    rt_func = tvm.script.from_source(out_str)\n    tvm.ir.assert_structural_equal(func, rt_func)\n\n    assert out_str.count('vi, vj = T.axis.remap(\"SS\", [i, j])') == 2\n    assert out_str.find(\"vi_\") == -1\n    assert out_str.find(\"vj_\") == -1\n\n    assert out_str.count(\"for i, j in T.grid(16, 16)\") == 2\n    assert out_str.find(\"i_\") == -1\n    assert out_str.find(\"i_\") == -1\n\n\ndef while_loop():\n    @T.prim_func\n    def while_loop(a: T.handle, b: T.handle) -> None:\n        A = T.match_buffer(a, (16,), \"float32\")\n        B = T.match_buffer(b, (16,), \"float32\")\n        i = T.alloc_buffer((), \"int32\", scope=\"local\")\n        for ii in range(16):\n            with T.block():\n                vi = T.axis.S(16, ii)\n                B[vi] = 0\n            while i[()] < 10:\n                for j in range(16):\n                    B[j] += A[j]\n\n    return while_loop\n\n\n# fmt: off\ndef primfunc_with_allocate_annotations():\n    @T.prim_func\n    def primfunc_with_allocate_annotations(placeholder_28: T.handle, T_cast_6: T.handle) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"tvmgen_default_fused_nn_max_pool2d_cast\", \"tir.noalias\": True})\n        placeholder_29 = T.match_buffer(placeholder_28, [802816], dtype=\"uint8\", elem_offset=0, align=64, offset_factor=1)\n        T_cast_7 = T.match_buffer(T_cast_6, [200704], dtype=\"int16\", elem_offset=0, align=64, offset_factor=1)\n        # body\n        tensor_2_data = T.allocate([200704], \"uint8\", \"global\", annotations={\"attr1_key\": \"attr1_value\"})\n        tensor_2 = T.buffer_decl(shape=[200704], dtype=\"uint8\", scope=\"global\", data=tensor_2_data)\n        for ax0_ax1_fused_4 in T.serial(0, 56):\n            for ax2_4 in T.serial(0, 56):\n                for ax3_init in T.serial(0, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init)] = T.uint8(0)\n                for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):\n                    tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)] = T.max(tensor_2[(((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)], T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), placeholder_29[(((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)], T.uint8(0), dtype=\"uint8\"))\n        for ax0_ax1_fused_5 in T.serial(0, 56):\n            for ax2_5, ax3_3 in T.grid(56, 64):\n                T_cast_7[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)] = T.cast(tensor_2[(((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)], \"int16\")\n\n    return primfunc_with_allocate_annotations\n# fmt: on\n\n\n\n\n# fmt: off\ndef comm_reducer_single_reduce_group():\n    @T.prim_func\n    def comm_reducer_single_reduce_group(a: T.handle, b: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        A = T.match_buffer(a, [16384], dtype=\"float32\")\n        for i in T.serial(0, 128):\n            T.launch_thread(threadIdx_x, 128)\n            reduce_temp0_data = T.allocate([1], \"float32\", \"local\")\n            reduce_temp0 = T.buffer_decl(shape=[1], dtype=\"float32\", scope=\"local\", data=reduce_temp0_data)\n            with T.attr(T.comm_reducer(lambda x, y: x + y, [T.float32(0)]), \"reduce_scope\", T.reinterpret(T.uint64(0), dtype=\"handle\")):\n                T.evaluate(T.tvm_thread_allreduce(T.uint32(1), A[i * 128 + threadIdx_x], True, reduce_temp0.data, threadIdx_x, dtype=\"handle\"))\n\n    return comm_reducer_single_reduce_group\n\n\ndef comm_reducer_multiple_reduce_groups():\n    @T.prim_func\n    def comm_reducer_multiple_reduce_groups(a: T.handle, b: T.handle) -> None:\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        threadIdx_x = T.env_thread(\"threadIdx.x\")\n        A = T.match_buffer(a, [16384], dtype=\"float32\")\n        for i in T.serial(0, 128):\n            T.launch_thread(threadIdx_x, 128)\n            reduce_temp0_data = T.allocate([1], \"float32\", \"local\")\n            reduce_temp0 = T.buffer_decl(shape=[1], dtype=\"float32\", scope=\"local\", data=reduce_temp0_data)\n            with T.attr(T.comm_reducer(lambda x0, x1, y0, y1: (T.Select((x1 >= y1), x0, y0), T.Select((x1 >= y1), x1, y1)), [T.int32(-1), T.min_value(\"float32\")]), \"reduce_scope\", T.reinterpret(T.uint64(0), dtype=\"handle\")):\n                T.evaluate(T.tvm_thread_allreduce(T.uint32(1), A[i * 128 + threadIdx_x], True, reduce_temp0.data, threadIdx_x, dtype=\"handle\"))\n\n    return comm_reducer_multiple_reduce_groups\n\n\ndef multiple_commreducer():\n    @T.prim_func\n    def multiple_commreducer() -> None:\n        normal_reduce_temp0 = T.buffer_decl([1], dtype=\"float32\", strides=[1], scope=\"local\")\n        normal_reduce_temp1 = T.buffer_decl([1], dtype=\"float32\", strides=[1], scope=\"local\")\n        reduce_temp0 = T.buffer_decl([1], dtype=\"float32\", strides=[1], scope=\"local\")\n        reduce_temp1 = T.buffer_decl([1], dtype=\"float32\", strides=[1], scope=\"local\")\n        for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"T_softmax_maxelem_cross_thread_reduction\"):\n                T.attr(T.comm_reducer(lambda x, y: T.max(x, y), [T.min_value(\"float32\")]), \"reduce_scope\", T.reinterpret(T.uint64(0), dtype=\"handle\"))\n                T.evaluate(T.tvm_thread_allreduce(T.uint32(1), normal_reduce_temp0[0], True, reduce_temp0.data, ax0_1, dtype=\"handle\"))\n        for ax0_1 in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"T_softmax_expsum_cross_thread_reduction\"):\n                T.attr(T.comm_reducer(lambda x, y: x + y, [T.float32(0)]), \"reduce_scope\", T.reinterpret(T.uint64(0), dtype=\"handle\"))\n                T.evaluate(T.tvm_thread_allreduce(T.uint32(1), normal_reduce_temp1[0], True, reduce_temp1.data, ax0_1, dtype=\"handle\"))\n\n    return multiple_commreducer\n# fmt: on\n\n\ndef func_div_mod():\n    @T.prim_func\n    def func_div_mod():\n        a = T.var(\"int32\")\n        b = T.var(\"int32\")\n        T.evaluate(a // b)\n        T.evaluate(a % b)\n        T.evaluate(T.truncmod(a, b))\n\n    return func_div_mod\n\n\ndef test_div_mod():\n    func = func_div_mod()\n    rt_func = tvm.script.from_source(func.script())\n    tvm.ir.assert_structural_equal(func, rt_func, True)\n\n    assert isinstance(func.body[0].value, tvm.tir.FloorDiv)\n    assert isinstance(func.body[1].value, tvm.tir.FloorMod)\n    assert isinstance(func.body[2].value, tvm.tir.Mod)\n\n\ndef loop_extent_dependent():\n    @T.prim_func\n    def loop_extent_dependent(a: T.handle) -> None:\n        A = T.match_buffer(a, [], dtype=\"int32\")\n        for i in T.serial(0, 128):\n            for j in T.serial(0, i):\n                A[()] = A[()] + j\n\n    return loop_extent_dependent\n\n\ndef nontrivial_range_axis():\n    @T.prim_func\n    def nontrivial_range_axis(a: T.handle) -> None:\n        A = T.match_buffer(a, (10), \"float32\")\n        for i in range(10):\n            with T.block(\"block\"):\n                vi = T.axis.spatial((1, 11), i + 1)\n                A[vi - 1] = A[vi - 1] + 1.0\n\n    return nontrivial_range_axis\n\n\ndef func_with_target_spec_by_config():\n    @T.prim_func\n    def func_with_target_spec_by_config() -> None:\n        T.func_attr(\n            {\n                \"kTarget\": T.target(\n                    {\n                        \"max_num_threads\": 1024,\n                        \"arch\": \"sm_70\",\n                        \"thread_warp_size\": 32,\n                        \"kind\": \"cuda\",\n                        \"tag\": \"\",\n                        \"keys\": [\"cuda\", \"gpu\"],\n                        \"host\": T.target({\"kind\": \"llvm\", \"tag\": \"\", \"keys\": [\"cpu\"]}),\n                    }\n                )\n            }\n        )\n        T.evaluate(0)\n\n    return func_with_target_spec_by_config\n\n\ndef func_with_target_spec_by_str():\n    @T.prim_func\n    def func_with_target_spec_by_str() -> None:\n        T.func_attr({\"kTarget\": T.target(\"nvidia/nvidia-a100\")})\n        T.evaluate(0)\n\n    return func_with_target_spec_by_str\n\n\ndef func_root_attr():\n    @T.prim_func\n    def func_root_attr():\n        with T.block(\"root\"):\n            T.block_attr({\"a\": \"0\"})\n            T.evaluate(0)\n\n    return func_root_attr\n\n\ndef func_trivial_root_block():\n    @T.prim_func\n    def func(A: T.Buffer[1, \"int32\"]):\n        with T.block(\"root\"):\n            A[0] = 0\n\n    return func\n\n\ndef func_nested_root_block():\n    @T.prim_func\n    def func(A: T.Buffer[1, \"int32\"]):\n        with T.block(\"root\"):\n            with T.block(\"block\"):\n                A[0] = 0\n\n    return func\n\n\ndef func_T_ptr_let_statement():\n    @T.prim_func\n    def func_T_ptr_let_statement(\n        args: T.handle, arg_type_ids_handle: T.Ptr[T.int32], num_args: T.int32\n    ) -> None:\n        # The T.Ptr declaration in the parameter list should parse\n        # correctly, and should be usable as the data pointer in a buffer.\n        arg_type_ids = T.buffer_decl([2], dtype=\"int32\", data=arg_type_ids_handle)\n\n        arg0: T.handle = T.tvm_struct_get(args, 0, 12, dtype=\"handle\")\n        arg1: T.handle = T.tvm_struct_get(args, 1, 12, dtype=\"handle\")\n\n        # Functions that return a \"handle\" can be assigned to a T.Ptr\n        # variable.  A variable annotated with T.Ptr still has dtype of\n        # T.handle, but has type annotation as a pointer type.\n        A_data: T.Ptr[T.float32] = T.tvm_struct_get(arg0, 0, 1, dtype=\"handle\")\n\n        # The buffer declaration has a data pointer defined earlier in\n        # this function.  It should only be defined after the data pointer\n        # has been defined, and should not be hoisted into the header of\n        # the function as other buffer_decl statements can be.\n        A = T.buffer_decl([1024], dtype=\"float32\", data=A_data)\n        B_data: T.Ptr[T.float32] = T.tvm_struct_get(arg1, 0, 1, dtype=\"handle\")\n        B = T.buffer_decl([1024], dtype=\"float32\", data=B_data)\n\n        B[0] = A[0]\n\n    return func_T_ptr_let_statement\n\n\ndef func_T_ptr_allocate():\n    @T.prim_func\n    def func_T_ptr_allocate() -> None:\n        A_data = T.allocate([1024], \"float32\", \"global\")\n        A = T.buffer_decl(shape=[1024], dtype=\"float32\", scope=\"global\", data=A_data)\n        A[0] = 0.0\n\n    return func_T_ptr_allocate\n\n\ndef llvm_intrin_call():\n    @T.prim_func\n    def ctpop(A: T.Buffer[(16,), \"uint8\"], B: T.Buffer[(16,), \"uint8\"]) -> None:\n        for i in range(0, 16):\n            with T.block(\"A\"):\n                vi = T.axis.remap(\n                    \"S\",\n                    [\n                        i,\n                    ],\n                )\n                B[vi] = T.call_llvm_pure_intrin(\n                    T.llvm_lookup_intrinsic_id(\"llvm.ctpop.i8\"),\n                    T.uint32(1),\n                    A[vi],\n                    dtype=\"uint8\",\n                )\n\n    return ctpop\n\n\ndef parse_bufferslice_as_range_bound():\n    @T.prim_func\n    def segment_sum(\n        A_ptr: T.handle, B_ptr: T.handle, indptr_ptr: T.handle, n: T.int32, m: T.int32\n    ) -> None:\n        A = T.match_buffer(A_ptr, [m], dtype=\"float32\")\n        B = T.match_buffer(B_ptr, [n], dtype=\"float32\")\n        indptr = T.match_buffer(indptr_ptr, [n + 1], dtype=\"int32\")\n        for i in T.serial(n):\n            with T.block(\"outer\"):\n                vi = T.axis.spatial(n, i)\n                T.reads(indptr[i : i + 2], B[vi], A[indptr[i] : indptr[i + 1]])\n                T.writes(B[vi])\n                for j in T.serial(indptr[i], indptr[i + 1]):\n                    with T.block(\"inner\"):\n                        vj = T.axis.reduce(m, j)\n                        T.reads(B[vi], A[vj])\n                        T.writes(B[vi])\n                        with T.init():\n                            B[vi] = T.float32(0)\n                        B[vi] = B[vi] + A[vj]\n\n    return segment_sum\n\n\ndef int64_support():\n    @T.prim_func\n    def elementwise_shape_int64(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (T.int64(128), T.int64(128)), dtype=\"float32\")\n        B = T.alloc_buffer((T.int64(128), T.int64(128)), dtype=\"float32\")\n        C = T.match_buffer(c, (T.int64(128), T.int64(128)), dtype=\"float32\")\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * 2.0\n        for i, j in T.grid(T.int64(128), T.int64(128)):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + 1.0\n\n    return elementwise_shape_int64\n\n\ndef string_annotation_escaping():\n    @T.prim_func\n    def string_annotation_of_special_chars():\n        T.func_attr(\n            {\n                \"key1\": '\"\\'hello\\t\\r\"',\n                \"key2\": \"\"\"\n            %1 = add i32 %0, %0\n            %2 = add i32 %0, %1\n            %3 = add i32 %1, %2\n            \"\"\",\n            }\n        )\n        T.evaluate(0)\n\n    return string_annotation_of_special_chars\n\n\ndef pointer_type():\n    @T.prim_func\n    def func_with_ptr_type_annotations(x: T.Ptr[T.int32], y: T.Ptr[T.int32, \"shared\"]):\n        xx_data = T.allocate([16], \"int32\", \"global\")\n        xx = T.buffer_decl(shape=[16], dtype=\"int32\", scope=\"global\", data=xx_data)\n        yy_data = T.allocate([16], \"int32\", \"shared\")\n        yy = T.buffer_decl(shape=[16], dtype=\"int32\", scope=\"shared\", data=yy_data)\n        a: T.Ptr[T.int32] = T.address_of(xx[0], dtype=\"handle\")\n        b: T.Ptr[T.int32, \"shared\"] = T.address_of(yy[0], dtype=\"handle\")\n        T.evaluate(T.call_extern(\"copy\", a, b, dtype=\"\"))\n\n    return func_with_ptr_type_annotations\n\n\ndef buffer_axis_separator():\n    @T.prim_func\n    def element_wise(a: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (128, 128), \"float32\", axis_separators=[1])\n        C = T.match_buffer(c, (128, 128), \"float32\")\n        B = T.alloc_buffer((128, 128), \"float32\", axis_separators=[1])\n\n        for i, j in T.grid(128, 128):\n            with T.block(\"B\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] * T.float32(2)\n        for i, j in T.grid(128, 128):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                C[vi, vj] = B[vi, vj] + T.float32(1)\n\n    return element_wise\n\n\ndef buffer_ramp_access_as_slice_index():\n    @T.prim_func\n    def buffer_ramp_access(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (128,), \"float32\")\n        B = T.match_buffer(b, (128,), \"float32\")\n        C = T.match_buffer(c, (128,), \"float32\")\n        for i in range(128):\n            A[i : i + 1 : 1] = i\n        for i in range(4):\n            B[i * 32 : i * 32 + 32] = A[i * 32 : i * 32 + 32 : 1] + T.broadcast(1.0, 32)\n        for i in range(4):\n            C[i : i + 128 : 4] = B[i : i + 128 : 4] + T.broadcast(1.0, 32)\n\n    return buffer_ramp_access\n\n\ndef let_expression():\n    @T.prim_func\n    def func():\n        x = T.var(\"int32\")\n        T.evaluate(T.let(x, 1, x + 1))\n\n    return func\n\n\ndef void_ptr():\n    @T.prim_func\n    def func(out_ret_value: T.Ptr[T.void]):\n        T.evaluate(out_ret_value)\n\n    return func\n\n\ndef decl_buffer():\n    @T.prim_func\n    def func(A: T.Buffer[(16, 16), \"float32\"], B: T.Buffer[(16, 16), \"float32\"]) -> None:\n        A_flattened = T.decl_buffer(data=A.data, shape=(256,), dtype=\"float32\")\n        B_flattened = T.decl_buffer(data=B.data, shape=(256,), dtype=\"float32\")\n        C_alias = T.decl_buffer(data=A_flattened.data, shape=(256,), dtype=\"float32\")\n        for i in range(256):\n            B_flattened[i] = A_flattened[i] + C_alias[i] + T.float32(1.0)\n\n    return func\n\n\ndef allocate_and_decl_buffer():\n    @T.prim_func\n    def func(A: T.Buffer[(16,), \"float32\"], B: T.Buffer[(16,), \"float32\"]) -> None:\n        D_data = T.allocate((16,), \"float32\", \"global\")\n        D = T.decl_buffer((16,), \"float32\", data=D_data)\n        for i in range(4):\n            with T.allocate((4,), \"float32\", \"global\") as C_data:\n                C = T.decl_buffer((4,), \"float32\", data=C_data)\n                for j in range(4):\n                    C[j] = A[i * 4 + j] + T.float32(1.0)\n                for j in range(4):\n                    D[j] = C[j]\n            for j in range(4):\n                B[i * 4 + j] = D[j]\n\n    return func\n\n\ndef float_infinity():\n    @T.prim_func\n    def func(\n        placeholder: T.Buffer[(1, 512, 768), \"float32\"], T_isinf: T.Buffer[(1, 512, 768), \"bool\"]\n    ) -> None:\n        # function attr dict\n        T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n        # body\n        # with T.block(\"root\")\n        for i0, i1, i2 in T.grid(1, 512, 768):\n            with T.block(\"T_isinf\"):\n                ax0, ax1, ax2 = T.axis.remap(\"SSS\", [i0, i1, i2])\n                T.reads(placeholder[ax0, ax1, ax2])\n                T.writes(T_isinf[ax0, ax1, ax2])\n                T_isinf[ax0, ax1, ax2] = T.fabs(\n                    placeholder[ax0, ax1, ax2], dtype=\"float32\"\n                ) == T.float32(\"inf\") and not (T.isnan(placeholder[ax0, ax1, ax2], dtype=\"bool\"))\n\n    return func\n\n\ndef minimal_i32_literal():\n    @T.prim_func\n    def func() -> None:\n        T.evaluate(T.int32(-2147483648))\n        T.evaluate(-T.int64(2147483648))\n\n    return func\n\n\ndef boolean_argument():\n    @T.prim_func\n    def func(a: T.boolean) -> None:\n        T.evaluate(a)\n\n    return func\n\n\ndef bool_argument():\n    @T.prim_func\n    def func(a: T.bool) -> None:\n        T.evaluate(a)\n\n    return func\n\n\ndef bool_variable_annotation():\n    @T.prim_func\n    def func() -> None:\n        a: T.bool = T.call_extern(\"dummy\", dtype=\"bool\")\n        T.evaluate(0)\n\n    return func\n\n\ndef return_none():\n    @T.prim_func\n    def func():\n        T.evaluate(0)\n\n    return func\n\n\ndef bool_primitive():\n    @T.prim_func\n    def func() -> None:\n        T.evaluate(T.bool(True))\n\n    return func\n\n\ndef bool_cast():\n    @T.prim_func\n    def func() -> None:\n        T.evaluate(T.bool(T.int32(0)))\n\n    return func\n\n\nir_generator = tvm.testing.parameter(\n    opt_gemm_normalize,\n    opt_gemm_lower,\n    opt_gemm_mod_host,\n    opt_conv_tensorcore_normalize,\n    opt_conv_tensorcore_lower,\n    opt_conv_tensorcore_mod_host,\n    vthread_func,\n    matmul,\n    module_const,\n    constant,\n    rank0,\n    rank0_block,\n    select,\n    minmax,\n    abs,\n    constant_folding,\n    simplify_bracket,\n    while_loop,\n    primfunc_with_allocate_annotations,\n    comm_reducer_single_reduce_group,\n    comm_reducer_multiple_reduce_groups,\n    multiple_commreducer,\n    loop_extent_dependent,\n    nontrivial_range_axis,\n    func_with_target_spec_by_config,\n    func_with_target_spec_by_str,\n    func_root_attr,\n    func_trivial_root_block,\n    func_nested_root_block,\n    func_T_ptr_let_statement,\n    func_T_ptr_allocate,\n    llvm_intrin_call,\n    parse_bufferslice_as_range_bound,\n    int64_support,\n    string_annotation_escaping,\n    pointer_type,\n    buffer_axis_separator,\n    buffer_ramp_access_as_slice_index,\n    let_expression,\n    void_ptr,\n    decl_buffer,\n    allocate_and_decl_buffer,\n    float_infinity,\n    minimal_i32_literal,\n    boolean_argument,\n    bool_argument,\n    bool_variable_annotation,\n    bool_primitive,\n    bool_cast,\n    return_none,\n)\n\n\ndef test_roundtrip(ir_generator):\n    original = ir_generator()\n    after_roundtrip = tvm.script.from_source(original.script(show_meta=True))\n    tvm.ir.assert_structural_equal(original, after_roundtrip, True)\n\n\ndef test_return_none_no_trailing_type():\n    func = return_none()\n    script = func.script()\n    assert \"-> None\" not in script\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_spans.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nfrom tvm.script.parser_v1 import tir as T\n\n\n@T.prim_func\ndef loops() -> None:\n    for i in T.parallel(0, 2):\n        for j in T.serial(0, 1):\n            for z in T.vectorized(3, 4):\n                T.evaluate(0)\n\n\ndef test_loops():\n    start_line = 23\n    parsed = loops\n\n    assert parsed.span.line == start_line\n\n    assert parsed.body.span.line == start_line + 1\n    assert parsed.body.min.span.column == 25\n    assert parsed.body.extent.span.column == 28\n    assert parsed.body.extent.span.line == start_line + 1\n\n    assert parsed.body.body.span.line == start_line + 2\n    assert parsed.body.body.loop_var.span.line == start_line + 2\n    assert parsed.body.body.loop_var.span.column == 13\n\n    assert parsed.body.body.body.span.line == start_line + 3\n    assert parsed.body.body.body.span.column == 22\n\n    assert parsed.body.body.body.body.span.line == start_line + 4\n    assert parsed.body.body.body.body.span.column == 17\n\n\n@T.prim_func\ndef statements() -> None:\n    T.evaluate(1)\n    T.evaluate(\"test\")\n\n\ndef test_statements():\n    start_line = 53\n    parsed = statements\n\n    assert parsed.body.span.line == start_line + 1\n\n    assert parsed.body[0].span.line == start_line + 1\n    assert parsed.body[0].span.column == 5\n\n    assert parsed.body[0].span.line == start_line + 1\n    assert parsed.body[0].span.column == 5\n\n\nif __name__ == \"__main__\":\n    test_loops()\n    test_statements()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_syntax_sugar.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring,invalid-name,pointless-string-statement\nimport sys\n\nimport pytest\nimport tvm.testing\nfrom tvm.ir import assert_structural_equal\nfrom tvm.script import from_source\nfrom tvm.script import tir as T\n\n\n@T.prim_func\ndef transformed_matmul_no_syntax_sugar(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i0, i1, i2_outer, i2_inner_outer, i2_inner_inner in T.grid(128, 128, 4, 8, 4):\n        with T.block(\"update\"):\n            vi, vj = T.axis.remap(\"SS\", [i0, i1])\n            vk = T.axis.R(128, i2_outer * 32 + i2_inner_outer * 4 + i2_inner_inner)\n            T.reads([C[vi, vj], A[vi, vk], B[vj, vk]])\n            T.writes([C[vi, vj], A[vi, vk]])\n            with T.init():\n                C[vi, vj] = 0.0\n            A[vi, vk] = A[vi, vk] + B[vj, vk]\n            C[vi, vj] = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n\n\n@T.prim_func\ndef transformed_matmul_syntax_sugar(a: T.handle, b: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n\n    for i0, i1, i2_outer, i2_inner_outer, i2_inner_inner in T.grid(128, 128, 4, 8, 4):\n        with T.block(\"update\"):\n            vi, vj = T.axis.remap(\"SS\", [i0, i1])\n            vk = T.axis.R(128, i2_outer * 32 + i2_inner_outer * 4 + i2_inner_inner)\n            T.reads(C[vi, vj], A[vi, vk], B[vj, vk])\n            T.writes(C[vi, vj], A[vi, vk])\n            with T.init():\n                C[vi, vj] = 0.0\n            A[vi, vk] = A[vi, vk] + B[vj, vk]\n            C[vi, vj] = C[vi, vj] + (A[vi, vk] * B[vj, vk])\n\n\ndef test_reads_writes_syntax_sugar():\n    assert_structural_equal(transformed_matmul_no_syntax_sugar, transformed_matmul_syntax_sugar)\n\n\n@T.prim_func\ndef loop_no_syntax_sugar(a: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    for i in T.serial(0, 128):\n        for j in T.parallel(0, 128):\n            for k in T.vectorized(0, 128):\n                for x in T.unroll(0, 128):\n                    for y in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                        for z in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n                            A[i, j, k, x] = A[i, j, k, x] * 2.0\n\n\n@T.prim_func\ndef loop_syntax_sugar(a: T.handle) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    for i in T.serial(128):\n        for j in T.parallel(128):\n            for k in T.vectorized(128):\n                for x in T.unroll(128):\n                    for y in T.thread_binding(128, \"threadIdx.x\"):\n                        for z in T.thread_binding(128, thread=\"threadIdx.x\"):\n                            A[i, j, k, x] = A[i, j, k, x] * 2.0\n\n\ndef test_loop_syntax_sugar():\n    assert_structural_equal(loop_no_syntax_sugar, loop_syntax_sugar)\n\n\n# match buffer - use kwargs\n@T.prim_func\ndef elementwise_handle(\n    a: T.handle,\n    b: T.handle,\n) -> None:\n    A = T.match_buffer(a, (128, 128, 128, 128))\n    B = T.match_buffer(b, (128, 128, 128, 128))\n    for i, j, k, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n\n\n# match buffer - use buffer with kwargs\n@T.prim_func\ndef elementwise_buffer_kwargs(\n    a: T.Buffer(shape=(128, 128, 128, 128), dtype=\"float32\"),\n    b: T.Buffer(shape=(128, 128, 128, 128), dtype=\"float32\"),\n) -> None:\n    for i, j, k, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            b[vi, vj, vk, vl] = a[vi, vj, vk, vl] * 2.0\n\n\n# match buffer - use buffer without kwargs\n@T.prim_func\ndef elementwise_buffer_no_kwargs(\n    a: T.Buffer[(128, 128, 128, 128), \"float32\"],\n    b: T.Buffer[(128, 128, 128, 128), \"float32\"],\n) -> None:\n    for i, j, k, l in T.grid(128, 128, 128, 128):\n        with T.block(\"B\"):\n            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n            b[vi, vj, vk, vl] = a[vi, vj, vk, vl] * 2.0\n\n\ndef test_match_buffer_syntax_sugar():\n    # with kwargs\n    assert_structural_equal(elementwise_handle, elementwise_buffer_kwargs)\n    # without kwargs\n    assert_structural_equal(elementwise_handle, elementwise_buffer_no_kwargs)\n\n\ndef test_match_buffer_1d():\n    @T.prim_func\n    def func_no_sugar(a: T.handle):\n        A = T.match_buffer(a, shape=(16,))\n        for i in T.serial(16):\n            A[i] = 0.0\n\n    @T.prim_func\n    def func_with_sugar(A: T.Buffer[16, \"float32\"]):\n        for i in T.serial(16):\n            A[i] = 0.0\n\n    assert_structural_equal(func_no_sugar, func_with_sugar)\n\n\n# match buffer failed case\ndef test_match_buffer_no_kwargs_failed():\n    with pytest.raises(ValueError) as e:\n\n        @T.prim_func\n        def elementwise_buffer_no_kwargs_failed(\n            a: T.Buffer[(128, 128, 128, 128)],\n            b: T.Buffer[(128, 128, 128, 128)],\n        ) -> None:\n            pass\n\n\n# dynamic shape gemm\n@T.prim_func\ndef gemm_dyn_shape(a: T.handle, b: T.handle, c: T.handle):\n    N = T.var(\"int32\")\n    M = T.var(\"int32\")\n    K = T.var(\"int32\")\n    A = T.match_buffer(a, (N, K), \"float32\")\n    B = T.match_buffer(b, (K, M), \"float32\")\n    C = T.match_buffer(c, (N, M), \"float32\")\n    for i, j, k in T.grid(N, M, K):\n        with T.block(\"gemm\"):\n            vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n            with T.init():\n                C[vi, vj] = 0.0\n            C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj]\n\n\ndef test_dynamic_shape_gemm():\n    gemm_dyn_shape_roundtrip = from_source(gemm_dyn_shape.script())\n    assert_structural_equal(gemm_dyn_shape, gemm_dyn_shape_roundtrip)\n\n\n@T.prim_func\ndef preflattened_buffer_map(A: T.handle, B: T.handle):\n    A_1 = T.match_buffer(A, [1])\n    T.preflattened_buffer(A_1, [1], align=1, offset_factor=2)\n    B_1 = T.match_buffer(B, [1])\n    T.preflattened_buffer(B_1, [1])\n    B_1[0] = A_1[0]\n\n\ndef test_preflattened_buffer_map():\n    A_var = [\n        k for k, _ in preflattened_buffer_map.preflattened_buffer_map.items() if k.name == \"A\"\n    ][0]\n    assert preflattened_buffer_map.preflattened_buffer_map[A_var].data_alignment == 1\n    assert preflattened_buffer_map.preflattened_buffer_map[A_var].offset_factor == 2\n\n\n@T.prim_func\ndef match_buffer_int64(a: T.handle, c: T.handle) -> None:\n    A = T.match_buffer(a, (T.int64(128), T.int64(128)), dtype=\"float32\")\n    B = T.alloc_buffer((T.int64(128), T.int64(128)), dtype=\"float32\")\n    C = T.match_buffer(c, (T.int64(128), T.int64(128)), dtype=\"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(T.int64(128), T.int64(128)):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\n@T.prim_func\ndef match_buffer_int64_after_roundtrip(\n    A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n    C: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n) -> None:\n    B = T.alloc_buffer((T.int64(128), T.int64(128)), dtype=\"float32\")\n    for i, j in T.grid(128, 128):\n        with T.block(\"B\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            B[vi, vj] = A[vi, vj] * 2.0\n    for i, j in T.grid(T.int64(128), T.int64(128)):\n        with T.block(\"C\"):\n            vi, vj = T.axis.remap(\"SS\", [i, j])\n            C[vi, vj] = B[vi, vj] + 1.0\n\n\ndef test_match_buffer_int64():\n    original = match_buffer_int64\n    after_roundtrip = match_buffer_int64_after_roundtrip\n    assert_structural_equal(original, after_roundtrip, True)\n\n\ndef test_match_buffer_region_has_implicit_shape_dtype():\n    @T.prim_func\n    def explicit_shape_dtype(A: T.Buffer[(16, 64), \"int32\"]):\n        with T.block():\n            B = T.match_buffer(A[8:16, 32:64], shape=(8, 32), dtype=\"int32\")\n            T.evaluate(0)\n\n    @T.prim_func\n    def implicit_shape_dtype(A: T.Buffer[(16, 64), \"int32\"]):\n        with T.block():\n            B = T.match_buffer(A[8:16, 32:64])\n            T.evaluate(0)\n\n    assert_structural_equal(explicit_shape_dtype, implicit_shape_dtype)\n\n\ndef test_match_buffer_input_requires_shape_arg():\n    with pytest.raises(tvm.error.DiagnosticError):\n\n        @T.prim_func\n        def func(a: T.handle):\n            A = T.match_buffer(a, dtype=\"int32\")\n            T.evaluate(0)\n\n\ndef test_letstmt_bufferload_without_type_annotation():\n    # Variable assignment of PrimExpr types uses the dtype of the\n    # PrimExpr to determine the variable's dtype.  Parsing of\n    # buf[indices] is done by generating a BufferSlice object, which\n    # handles both store and load cases.  BufferSlice is not a\n    # PrimExpr, and implements BufferSlice.dtype explicitly.\n\n    # Failure occurred during parsing of the tvmscript.\n    @T.prim_func\n    def func_without_type_annotation(A: T.Buffer[(1,), \"int32\"]):\n        x = A[0]\n        T.evaluate(x)\n\n\ndef test_letstmt_bind_with_constant():\n    @T.prim_func\n    def constant_binds():\n        x = 1\n        y = 42.0\n        T.evaluate(T.cast(x, \"float32\") + y)\n\n    @T.prim_func\n    def constant_binds_wrapped():\n        x = T.meta_var(T.int32(1))\n        y = T.meta_var(T.float32(42.0))\n        T.evaluate(T.cast(x, \"float32\") + y)\n\n    assert_structural_equal(constant_binds, constant_binds_wrapped)\n\n\ndef test_func_call():\n    def shared_16x16_to_ldmatrix_32x8_layout(i, j):\n        thread_id = (i % 8) * 4 + (j % 8) // 2\n        return T.meta_var((thread_id, (j // 8) * 4 + (i // 8) * 2 + (j % 2)))\n\n    @T.prim_func\n    def mma_sync_m16n16k16_desc(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n        B = T.match_buffer(b, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n        C = T.match_buffer(c, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n\n        with T.block(\"root\"):\n            T.reads(C[0:32, 0:8], A[0:32, 0:8], B[0:32, 0:8])\n            T.writes(C[0:32, 0:8])\n            for i, j, k in T.grid(16, 16, 16):\n                with T.block(\"C\"):\n                    i, j, k = T.axis.remap(\"SSR\", [i, j, k])\n                    thread_id_C, local_id_C = shared_16x16_to_ldmatrix_32x8_layout(i, j)\n                    thread_id_A, local_id_A = shared_16x16_to_ldmatrix_32x8_layout(i, k)\n                    thread_id_B, local_id_B = shared_16x16_to_ldmatrix_32x8_layout(k, j)\n\n                    T.reads(\n                        C[thread_id_C, local_id_C],\n                        A[thread_id_A, local_id_A],\n                        B[thread_id_B, local_id_B],\n                    )\n                    T.writes(C[thread_id_C, local_id_C])\n\n                    C[thread_id_C, local_id_C] += (\n                        A[thread_id_A, local_id_A] * B[thread_id_B, local_id_B]\n                    )\n\n    @T.prim_func\n    def mma_sync_m16n16k16_desc_manual(a: T.handle, b: T.handle, c: T.handle) -> None:\n        A = T.match_buffer(a, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n        B = T.match_buffer(b, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n        C = T.match_buffer(c, (32, 8), \"float16\", align=64, offset_factor=16, scope=\"warp\")\n\n        with T.block(\"root\"):\n            T.reads(C[0:32, 0:8], A[0:32, 0:8], B[0:32, 0:8])\n            T.writes(C[0:32, 0:8])\n            for i, j, k in T.grid(16, 16, 16):\n                with T.block(\"C\"):\n                    i, j, k = T.axis.remap(\"SSR\", [i, j, k])\n                    T.reads(\n                        C[i % 8 * 4 + j % 8 // 2, j // 8 * 4 + i // 8 * 2 + j % 2],\n                        A[i % 8 * 4 + k % 8 // 2, k // 8 * 4 + i // 8 * 2 + k % 2],\n                        B[k % 8 * 4 + j % 8 // 2, j // 8 * 4 + k // 8 * 2 + j % 2],\n                    )\n                    T.writes(C[i % 8 * 4 + j % 8 // 2, j // 8 * 4 + i // 8 * 2 + j % 2])\n                    C[i % 8 * 4 + j % 8 // 2, j // 8 * 4 + i // 8 * 2 + j % 2] = (\n                        C[i % 8 * 4 + j % 8 // 2, j // 8 * 4 + i // 8 * 2 + j % 2]\n                        + A[i % 8 * 4 + k % 8 // 2, k // 8 * 4 + i // 8 * 2 + k % 2]\n                        * B[k % 8 * 4 + j % 8 // 2, j // 8 * 4 + k // 8 * 2 + j % 2]\n                    )\n\n    assert_structural_equal(mma_sync_m16n16k16_desc, mma_sync_m16n16k16_desc_manual)\n\n    # The following is an example of an error message from calling an invalid function\n\n    # error: Error occurred when invoking the function sqrt:\n    # loop of ufunc does not support argument 0 of type Var which has no callable sqrt method\n    #  --> test_tvmscript_syntax_sugar.py:334:19\n    #      |\n    #  334 |              ind = sqrt(i)\n    #      |                    ^^^^^^^\n    # note: run with `TVM_BACKTRACE=1` environment variable to display a backtrace.\n\n    # Uncomment to see the error above.\n    # def sqrt(x):\n    #     import numpy as np\n    #     return np.sqrt(x)\n\n    # @T.prim_func\n    # def loop(a: T.handle) -> None:\n    #     A = T.match_buffer(a, (128,))\n    #     for i in T.serial(128):\n    #         ind = sqrt(i)\n    #         A[i] = A[ind]\n\n\ndef test_int64_loop():\n    @T.prim_func\n    def int64_grid(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i, j in T.grid(T.int64(128), T.int64(128)):\n            with T.block(\"C\"):\n                vi, vj = T.axis.remap(\"SS\", [i, j])\n                B[vi, vj] = A[vi, vj] + 1.0\n\n    @T.prim_func\n    def int64_grid_expanded(\n        A: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n        B: T.Buffer[(T.int64(128), T.int64(128)), \"float32\"],\n    ) -> None:\n        for i in range(T.int64(0), T.int64(128)):\n            for j in range(T.int64(0), T.int64(128)):\n                with T.block(\"C\"):\n                    vi = T.axis.spatial(T.int64(128), i)\n                    vj = T.axis.spatial(T.int64(128), j)\n                    B[vi, vj] = A[vi, vj] + 1.0\n\n    assert_structural_equal(int64_grid, int64_grid_expanded)\n\n\nif __name__ == \"__main__\":\n    tvm.testing.main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_tvmscript_type.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=missing-function-docstring,missing-module-docstring,invalid-name,pointless-string-statement\nfrom tvm.script import tir as T\n\n\"\"\"\nThis prim func include necessary buffer types that need to be checked\ne.g. reads/writes, match_buffer/alloc_buffer, serial/block etc.\n\"\"\"\n\n\n@T.prim_func\ndef element_wise_storage_align(a: T.handle, c: T.handle) -> None:\n    C = T.match_buffer(c, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    A = T.match_buffer(a, [128, 128], elem_offset=0, align=64, offset_factor=1)\n    # body\n    with T.block(\"root\"):\n        T.reads([])\n        T.writes([])\n        B = T.alloc_buffer([128, 128], elem_offset=0, align=64, offset_factor=1)\n        for i0 in T.serial(0, 128):\n            for ax1 in T.serial(0, 128):\n                with T.block(\"B\"):\n                    vi = T.axis.S(128, i0)\n                    vj = T.axis.S(128, ax1)\n                    T.reads([A[vi, vj]])\n                    T.writes([B[vi, vj]])\n                    T.block_attr({\"buffer_dim_align\": [[0, 0, 128, 127]]})\n                    B[vi, vj] = A[vi, vj] * T.float32(2)\n            for i1 in T.serial(0, 128):\n                with T.block(\"C\"):\n                    vi_1, vj_1 = T.axis.remap(\"SS\", [i0, i1])\n                    T.reads([B[vi_1, vj_1]])\n                    T.writes([C[vi_1, vj_1]])\n                    C[vi_1, vj_1] = B[vi_1, vj_1] + T.float32(1)\n\n\n\"\"\"\nThis prim func include necessary thread types that need to be checked\ne.g. env_thread, launch_thread, thread_binding etc.\n\"\"\"\n\n\n@T.prim_func\ndef element_wise_env_thread_x(a: T.handle, b: T.handle, c: T.handle) -> None:\n    j1_0 = T.env_thread(\"threadIdx.x\")\n    j0_0 = T.env_thread(\"threadIdx.x\")\n    i = T.env_thread(\"blockIdx.x\")\n    A = T.match_buffer(a, [128, 128])\n    B = T.match_buffer(b, [128, 128])\n    C = T.match_buffer(c, [128, 128])\n    T.launch_thread(i, 128)\n    T.launch_thread(j0_0, 4)\n    T.launch_thread(j1_0, 4)\n\n    for blockIdx_x in T.thread_binding(0, 128, \"blockIdx.x\"):\n        for threadIdx_x in T.thread_binding(0, 4, \"threadIdx.x\"):\n            for j0_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    B[blockIdx_x, threadIdx_x * 32 + j0_1] = (\n                        A[blockIdx_x, threadIdx_x * 32 + j0_1] * 2.0\n                    )\n            for j1_1 in T.serial(0, 32):\n                with T.block(\"\"):\n                    C[blockIdx_x, threadIdx_x * 32 + j1_1] = (\n                        B[blockIdx_x, threadIdx_x * 32 + j1_1] + 1.0\n                    )\n\n\n\"\"\"\nThis test case is added to test T.grid\n\"\"\"\n\n\n@T.prim_func\ndef loop_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    for i, ko in T.grid(128, 4):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi = T.axis.S(128, i)\n                vk = T.axis.R(128, ko * 32 + ki)\n                T.reads([B[vi], A[vi, vk]])\n                T.writes([B[vi]])\n                with T.init():\n                    B[vi] = T.float32(0)\n                B[vi] = B[vi] + A[vi, vk]\n\n\n\"\"\"\nThis test case is added to test T.comm_reducer, T.reinterpret, T.tvm_thread_allreduce\n\"\"\"\n\n\n@T.prim_func\ndef lowered_loop_split(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128], dtype=\"float32\")\n    reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    normal_reduce_temp0 = T.alloc_buffer([1], dtype=\"float32\", strides=[1], scope=\"local\")\n    for i in T.serial(0, 128):\n        for ki in T.thread_binding(0, 32, thread=\"threadIdx.x\"):\n            normal_reduce_temp0[0] = T.float32(0)\n            for ko in T.serial(0, 4):\n                with T.block(\"B_normal_reduction\"):\n                    vi = T.axis.S(128, i)\n                    vk = T.axis.R(128, ko * 32 + ki)\n                    T.reads([A[vi, vk], normal_reduce_temp0[0]])\n                    T.writes([normal_reduce_temp0[0]])\n                    normal_reduce_temp0[0] = normal_reduce_temp0[0] + A[vi, vk]\n            with T.block(\"B_cross_thread_reduction\"):\n                T.reads([normal_reduce_temp0[0]])\n                T.writes([reduce_temp0[0]])\n                T.attr(\n                    T.comm_reducer(lambda x, y: x + y, [T.float32(0)]),\n                    \"reduce_scope\",\n                    T.reinterpret(T.uint64(0), dtype=\"handle\"),\n                )\n                T.evaluate(\n                    T.tvm_thread_allreduce(\n                        T.uint32(1),\n                        normal_reduce_temp0[0],\n                        True,\n                        reduce_temp0.data,\n                        ki,\n                        dtype=\"handle\",\n                    )\n                )\n            with T.block(\"B_write_back\"):\n                vi = T.axis.S(128, i)\n                T.reads([reduce_temp0[0]])\n                T.writes([B[vi]])\n                B[vi] = reduce_temp0[0]\n\n\n\"\"\"\nThis test case is added to test T.Buffer with slice as argument and T.exp\n\"\"\"\n\n\n@T.prim_func\ndef different_access_indices(a: T.handle, b: T.handle) -> None:\n    A = T.match_buffer(a, [128, 128, 128], dtype=\"float32\")\n    B = T.match_buffer(b, [128, 128], dtype=\"float32\")\n    for i, j in T.grid(128, 128):\n        for k in T.thread_binding(0, 128, thread=\"threadIdx.x\"):\n            with T.block(\"B\"):\n                vi, vj, vk = T.axis.remap(\"SSR\", [i, j, k])\n                T.reads([B[vi, vj], A[vi, vj, vk]])\n                T.writes(\n                    [\n                        B[\n                            T.min(vj, vi) : T.min(vj, vi)  # type: ignore[misc]\n                            + (T.max(vj, vi) + 1 - T.min(vj, vi)),\n                            T.min(vi, vj) : T.min(vi, vj)  # type: ignore[misc]\n                            + (T.max(vi, vj) + 1 - T.min(vi, vj)),\n                        ]\n                    ]\n                )\n                with T.init():\n                    B[vj, vi] = T.exp(B[vj, vi], dtype=\"float32\")\n                B[vi, vj] = B[vi, vj] + A[vi, vj, vk]\n\n\n# Not running any test as we only want to type-check here\nif __name__ == \"__main__\":\n    pass\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/python/unittest/test_type_annotation_checker.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test type checker based on python's type annotations\"\"\"\n\nimport sys\nfrom typing import Dict, List, Tuple, Union, Callable\n\nimport pytest\nimport _pytest\n\nfrom tvm.tir.schedule._type_checker import type_checked\n\n\ndef int_func(x: int) -> int:\n    return 2 * x\n\n\ndef str_func(x: str) -> str:\n    return 2 * x\n\n\ntest_cases = [\n    {\n        \"type_annotation\": int,\n        \"positive_cases\": [5],\n        \"negative_cases\": [\"5\"],\n    },\n    {\n        \"type_annotation\": List[int],\n        \"positive_cases\": [\n            [5],\n            [],\n            # Tuples are allowed to be used as lists, because both are\n            # represented in FFI as tvm::runtime::Array.\n            (1, 2, 3),\n        ],\n        \"negative_cases\": [\n            None,\n            5,\n            [\"5\"],\n        ],\n    },\n    {\n        \"type_annotation\": Dict[str, int],\n        \"positive_cases\": [\n            {\"key1\": 0, \"key2\": 1, \"key3\": -1},\n        ],\n        \"negative_cases\": [None, [1], {1: \"1\"}],\n    },\n    {\n        \"type_annotation\": Tuple[int],\n        \"positive_cases\": [\n            (5,),\n        ],\n        \"negative_cases\": [\n            None,\n            (1, 2, 3),\n            [1],\n            5,\n            [\"5\"],\n        ],\n    },\n    {\n        \"type_annotation\": Tuple[str, int],\n        \"positive_cases\": [\n            (\"x\", 5),\n        ],\n        \"negative_cases\": [\n            42,\n            (\"x\", 5, 6),\n            (\"x\", 5, \"y\"),\n            (\"x\", 5.0),\n            (None, 5),\n        ],\n    },\n    {\n        \"type_annotation\": Union[str, int],\n        \"positive_cases\": [\n            \"x\",\n            5,\n        ],\n        \"negative_cases\": [\n            5.0,\n            (\"x\", 5, 6),\n            None,\n        ],\n    },\n    {\n        \"type_annotation\": Callable,\n        \"positive_cases\": [str_func, int_func],\n        \"negative_cases\": [\n            None,\n            \"x\",\n            42,\n        ],\n    },\n    {\n        \"type_annotation\": Callable[[int], int],\n        \"positive_cases\": [int_func],\n        \"negative_cases\": [\n            None,\n            \"x\",\n            42,\n            pytest.param(\n                str_func,\n                marks=pytest.mark.xfail(\n                    reason=\"Signature of Callable arguments not currently checked\"\n                ),\n            ),\n        ],\n    },\n]\n\n\ndef make_parametrization(type_annotation, case):\n    if isinstance(case, _pytest.mark.structures.ParameterSet):\n        marks = case.marks\n        (case,) = case.values\n    else:\n        marks = []\n\n    try:\n        annotation_name = type_annotation.__name__\n    except AttributeError:\n        annotation_name = str(type_annotation).replace(\"typing.\", \"\")\n\n    if hasattr(case, \"__name__\"):\n        case_name = case.__name__\n    else:\n        case_name = str(case)\n\n    name = f\"{annotation_name}, {case_name}\"\n\n    return pytest.param(type_annotation, case, marks=marks, id=name)\n\n\npositive_cases = [\n    make_parametrization(config[\"type_annotation\"], case)\n    for config in test_cases\n    for case in config[\"positive_cases\"]\n]\n\nnegative_cases = [\n    make_parametrization(config[\"type_annotation\"], case)\n    for config in test_cases\n    for case in config[\"negative_cases\"]\n]\n\n\n@pytest.mark.parametrize(\n    [\"type_annotation\", \"case\"],\n    positive_cases,\n)\ndef test_matches_type(type_annotation, case):\n    @type_checked\n    def func(_: type_annotation):\n        pass\n\n    func(case)\n\n\n@pytest.mark.parametrize(\n    [\"type_annotation\", \"case\"],\n    negative_cases,\n)\ndef test_not_matches(type_annotation, case):\n    @type_checked\n    def func(_: type_annotation):\n        pass\n\n    with pytest.raises(TypeError):\n        func(case)\n\n\nif __name__ == \"__main__\":\n    sys.exit(pytest.main(sys.argv))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/ci.py",
        "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport multiprocessing\nimport os\nimport getpass\nimport inspect\nimport argparse\nimport json\nimport shutil\nimport grp\nimport string\nimport random\nimport subprocess\nimport platform\nimport textwrap\nimport typing\n\nfrom pathlib import Path\nfrom typing import List, Dict, Any, Optional, Tuple, Callable, Union\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\nSCRIPT_DIR = REPO_ROOT / \".ci-py-scripts\"\nNPROC = multiprocessing.cpu_count()\n\n\nclass col:\n    BLUE = \"\\033[94m\"\n    CYAN = \"\\033[96m\"\n    GREEN = \"\\033[92m\"\n    YELLOW = \"\\033[93m\"\n    RED = \"\\033[91m\"\n    RESET = \"\\033[0m\"\n    BOLD = \"\\033[1m\"\n    UNDERLINE = \"\\033[4m\"\n\n\ndef print_color(color: str, msg: str, bold: bool, **kwargs: Any) -> None:\n    if hasattr(sys.stdout, \"isatty\") and sys.stdout.isatty():\n        bold_code = col.BOLD if bold else \"\"\n        print(bold_code + color + msg + col.RESET, **kwargs)\n    else:\n        print(msg, **kwargs)\n\n\nwarnings: List[str] = []\n\n\ndef clean_exit(msg: str) -> None:\n    print_color(col.RED, msg, bold=True, file=sys.stderr)\n\n    for warning in warnings:\n        print_color(col.YELLOW, warning, bold=False, file=sys.stderr)\n\n    exit(1)\n\n\ndef cmd(commands: List[Any], **kwargs: Any):\n    commands = [str(s) for s in commands]\n    command_str = \" \".join(commands)\n    print_color(col.BLUE, command_str, bold=True)\n    proc = subprocess.run(commands, **kwargs)\n    if proc.returncode != 0:\n        raise RuntimeError(f\"Command failed: '{command_str}'\")\n    return proc\n\n\ndef get_build_dir(name: str) -> str:\n    build_dir = REPO_ROOT / f\"build-{name}\"\n    return str(build_dir.relative_to(REPO_ROOT))\n\n\ndef check_docker():\n    executable = shutil.which(\"docker\")\n    if executable is None:\n        clean_exit(\"'docker' executable not found, install it first (e.g. 'apt install docker.io')\")\n\n    if sys.platform == \"linux\":\n        # Check that the user is in the docker group before running\n        try:\n            group = grp.getgrnam(\"docker\")\n            if getpass.getuser() not in group.gr_mem:\n                warnings.append(\n                    f\"Note: User '{getpass.getuser()}' is not in the 'docker' group, either:\\n\"\n                    \" * run with 'sudo'\\n\"\n                    \" * add user to 'docker': sudo usermod -aG docker $(whoami), then log out and back in\",\n                )\n        except KeyError:\n            warnings.append(\"Note: 'docker' group does not exist\")\n\n\ndef check_gpu():\n    if not (sys.platform == \"linux\" and shutil.which(\"lshw\")):\n        # Can't check GPU on non-Linux platforms\n        return\n\n    # See if we can check if a GPU is present in case of later failures,\n    # but don't block on execution since this isn't critical\n    try:\n        proc = cmd(\n            [\"lshw\", \"-json\", \"-C\", \"display\"],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            encoding=\"utf-8\",\n        )\n        stdout = proc.stdout.strip().strip(\",\")\n        stdout = json.loads(stdout)\n    except (subprocess.CalledProcessError, json.decoder.JSONDecodeError):\n        # Do nothing if any step failed\n        return\n\n    if isinstance(stdout, dict):\n        # Sometimes lshw outputs a single item as a dict instead of a list of\n        # dicts, so wrap it up if necessary\n        stdout = [stdout]\n    if not isinstance(stdout, list):\n        return\n\n    vendors = [s.get(\"vendor\", \"\").lower() for s in stdout]\n    if not any(\"nvidia\" in vendor for vendor in vendors):\n        warnings.append(\n            \"nvidia GPU not found in 'lshw', maybe use --cpu flag when running 'docs' command?\"\n        )\n\n\ndef gen_name(s: str) -> str:\n    # random 4 letters\n    suffix = \"\".join([random.choice(string.ascii_lowercase) for i in range(5)])\n    return f\"{s}-{suffix}\"\n\n\ndef docker(\n    name: str,\n    image: str,\n    scripts: List[str],\n    env: Dict[str, str],\n    interactive: bool,\n    additional_flags: Optional[Dict[str, str]] = None,\n):\n    \"\"\"\n    Invoke a set of bash scripts through docker/bash.sh\n\n    name: container name\n    image: docker image name\n    scripts: list of bash commands to run\n    env: environment to set\n    \"\"\"\n    check_docker()\n\n    # As sccache is added to these images these can be uncommented\n    sccache_images = {\n        # \"ci_lint\",\n        \"ci_gpu\",\n        \"ci_cpu\",\n        # \"ci_wasm\",\n        # \"ci_i386\",\n        \"ci_cortexm\",\n        \"ci_arm\",\n        \"ci_hexagon\",\n        \"ci_riscv\",\n        \"ci_adreno\",\n    }\n\n    if image in sccache_images and os.getenv(\"USE_SCCACHE\", \"1\") == \"1\":\n        scripts = [\n            \"sccache --start-server\",\n        ] + scripts\n        # Set the C/C++ compiler so CMake picks them up in the build\n        env[\"CC\"] = \"/opt/sccache/cc\"\n        env[\"CXX\"] = \"/opt/sccache/c++\"\n        env[\"SCCACHE_CACHE_SIZE\"] = os.getenv(\"SCCACHE_CACHE_SIZE\", \"50G\")\n\n    docker_bash = REPO_ROOT / \"docker\" / \"bash.sh\"\n\n    command = [docker_bash]\n    if sys.stdout.isatty():\n        command.append(\"-t\")\n\n    command.append(\"--name\")\n    command.append(name)\n    if interactive:\n        command.append(\"-i\")\n        scripts = [\"interact() {\", \"  bash\", \"}\", \"trap interact 0\", \"\"] + scripts\n\n    for key, value in env.items():\n        command.append(\"--env\")\n        command.append(f\"{key}={value}\")\n\n    if additional_flags is not None:\n        for key, value in additional_flags.items():\n            command.append(key)\n            command.append(value)\n\n    SCRIPT_DIR.mkdir(exist_ok=True)\n\n    script_file = SCRIPT_DIR / f\"{name}.sh\"\n    with open(script_file, \"w\") as f:\n        f.write(\"set -eux\\n\\n\")\n        f.write(\"\\n\".join(scripts))\n        f.write(\"\\n\")\n\n    command += [image, \"bash\", str(script_file.relative_to(REPO_ROOT))]\n\n    try:\n        cmd(command)\n    except RuntimeError as e:\n        clean_exit(f\"Error invoking Docker: {e}\")\n    except KeyboardInterrupt:\n        cmd([\"docker\", \"stop\", \"--time\", \"1\", name])\n    finally:\n        if os.getenv(\"DEBUG\", \"0\") != \"1\":\n            script_file.unlink()\n\n\ndef docs(\n    tutorial_pattern: Optional[str] = None,\n    full: bool = False,\n    interactive: bool = False,\n    skip_build: bool = False,\n    docker_image: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Build the documentation from gallery/ and docs/. By default this builds only\n    the Python docs without any tutorials.\n\n    arguments:\n    full -- Build all language docs, not just Python (this will use the 'ci_gpu' Docker image)\n    tutorial-pattern -- Regex for which tutorials to execute when building docs (this will use the 'ci_gpu' Docker image)\n    skip_build -- skip build and setup scripts\n    interactive -- start a shell after running build / test scripts\n    docker-image -- manually specify the docker image to use\n    \"\"\"\n    build_dir = get_build_dir(\"gpu\")\n\n    extra_setup = []\n    image = \"ci_gpu\" if docker_image is None else docker_image\n    if not full and tutorial_pattern is None:\n        # TODO: Change this to tlcpack/docs once that is uploaded\n        image = \"ci_cpu\" if docker_image is None else docker_image\n        build_dir = get_build_dir(\"cpu\")\n        config_script = \" && \".join(\n            [\n                f\"mkdir -p {build_dir}\",\n                f\"pushd {build_dir}\",\n                \"cp ../cmake/config.cmake .\",\n                # The docs import tvm.micro, so it has to be enabled in the build\n                \"echo set\\(USE_MICRO ON\\) >> config.cmake\",\n                \"popd\",\n            ]\n        )\n\n        # These are taken from the ci-gpu image via pip freeze, consult that\n        # if there are any changes: https://github.com/apache/tvm/tree/main/docs#native\n        requirements = [\n            \"Sphinx==4.2.0\",\n            \"tlcpack-sphinx-addon==0.2.1\",\n            \"synr==0.5.0\",\n            \"image==1.5.33\",\n            # Temporary git link until a release is published\n            \"git+https://github.com/sphinx-gallery/sphinx-gallery.git@6142f1791151849b5bec4bf3959f75697ba226cd\",\n            \"sphinx-rtd-theme==1.0.0\",\n            \"matplotlib==3.3.4\",\n            \"commonmark==0.9.1\",\n            \"Pillow==8.3.2\",\n            \"autodocsumm==0.2.7\",\n            \"docutils==0.16\",\n        ]\n\n        extra_setup = [\n            \"python3 -m pip install --user \" + \" \".join(requirements),\n        ]\n    else:\n        check_gpu()\n        config_script = f\"./tests/scripts/task_config_build_gpu.sh {build_dir}\"\n\n    scripts = extra_setup + [\n        config_script,\n        f\"./tests/scripts/task_build.py --build-dir {build_dir}\",\n    ]\n\n    if skip_build:\n        scripts = []\n\n    scripts.append(\"./tests/scripts/task_python_docs.sh\")\n\n    if tutorial_pattern is None:\n        tutorial_pattern = os.getenv(\"TVM_TUTORIAL_EXEC_PATTERN\", \".py\" if full else \"none\")\n\n    env = {\n        \"TVM_TUTORIAL_EXEC_PATTERN\": tutorial_pattern,\n        \"PYTHON_DOCS_ONLY\": \"0\" if full else \"1\",\n        \"IS_LOCAL\": \"1\",\n        \"TVM_LIBRARY_PATH\": str(REPO_ROOT / build_dir),\n    }\n    docker(name=gen_name(\"docs\"), image=image, scripts=scripts, env=env, interactive=interactive)\n\n\ndef serve_docs(directory: str = \"_docs\") -> None:\n    \"\"\"\n    Serve the docs using Python's http server\n\n    arguments:\n    directory -- Directory to serve from\n    \"\"\"\n    directory_path = Path(directory)\n    if not directory_path.exists():\n        clean_exit(\"Docs have not been built, run 'ci.py docs' first\")\n    cmd([sys.executable, \"-m\", \"http.server\"], cwd=directory_path)\n\n\ndef lint(interactive: bool = False, fix: bool = False, docker_image: Optional[str] = None) -> None:\n    \"\"\"\n    Run CI's Sanity Check step\n\n    arguments:\n    interactive -- start a shell after running build / test scripts\n    fix -- where possible (currently black and clang-format) edit files in place with formatting fixes\n    docker-image -- manually specify the docker image to use\n    \"\"\"\n    env = {}\n    if fix:\n        env[\"IS_LOCAL\"] = \"true\"\n        env[\"INPLACE_FORMAT\"] = \"true\"\n\n    docker(\n        name=gen_name(f\"ci-lint\"),\n        image=\"ci_lint\" if docker_image is None else docker_image,\n        scripts=[\"./tests/scripts/task_lint.sh\"],\n        env=env,\n        interactive=interactive,\n    )\n\n\nOption = Tuple[str, List[str]]\n\n\ndef generate_command(\n    name: str,\n    options: Dict[str, Option],\n    help: str,\n    precheck: Optional[Callable[[], None]] = None,\n    post_build: Optional[List[str]] = None,\n    additional_flags: Optional[Dict[str, str]] = None,\n):\n    \"\"\"\n    Helper to generate CLIs that:\n    1. Build a with a config matching a specific CI Docker image (e.g. 'cpu')\n    2. Run tests (either a pre-defined set from scripts or manually via invoking\n       pytest)\n    3. (optional) Drop down into a terminal into the Docker container\n    \"\"\"\n\n    def fn(\n        tests: Optional[List[str]],\n        skip_build: bool = False,\n        interactive: bool = False,\n        docker_image: Optional[str] = None,\n        verbose: bool = False,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        arguments:\n        tests -- pytest test IDs (e.g. tests/python or tests/python/a_file.py::a_test[param=1])\n        skip_build -- skip build and setup scripts\n        interactive -- start a shell after running build / test scripts\n        docker-image -- manually specify the docker image to use\n        verbose -- run verbose build\n        \"\"\"\n        if precheck is not None:\n            precheck()\n\n        build_dir = get_build_dir(name)\n\n        if skip_build:\n            scripts = []\n        else:\n            scripts = [\n                f\"./tests/scripts/task_config_build_{name}.sh {build_dir}\",\n                f\"./tests/scripts/task_build.py --build-dir {build_dir}\",\n            ]\n\n        if post_build is not None:\n            scripts += post_build\n\n        # Check that a test suite was not used alongside specific test names\n        if any(v for v in kwargs.values()) and tests is not None:\n            option_flags = \", \".join([f\"--{k}\" for k in options.keys()])\n            clean_exit(f\"{option_flags} cannot be used with --tests\")\n\n        if tests is not None:\n            scripts.append(f\"python3 -m pytest {' '.join(tests)}\")\n\n        # Add named test suites\n        for option_name, (_, extra_scripts) in options.items():\n            if kwargs.get(option_name, False):\n                scripts.extend(script.format(build_dir=build_dir) for script in extra_scripts)\n\n        docker(\n            name=gen_name(f\"ci-{name}\"),\n            image=f\"ci_{name}\" if docker_image is None else docker_image,\n            scripts=scripts,\n            env={\n                # Need to specify the library path manually or else TVM can't\n                # determine which build directory to use (i.e. if there are\n                # multiple copies of libtvm.so laying around)\n                \"TVM_LIBRARY_PATH\": str(REPO_ROOT / get_build_dir(name)),\n                \"VERBOSE\": \"true\" if verbose else \"false\",\n            },\n            interactive=interactive,\n            additional_flags=additional_flags,\n        )\n\n    fn.__name__ = name\n\n    return fn, options, help\n\n\ndef check_arm_qemu() -> None:\n    \"\"\"\n    Check if a machine is ready to run an ARM Docker image\n    \"\"\"\n    machine = platform.machine().lower()\n    if \"arm\" in machine or \"aarch64\" in machine:\n        # No need to check anything if the machine runs ARM\n        return\n\n    binfmt = Path(\"/proc/sys/fs/binfmt_misc\")\n    if not binfmt.exists() or len(list(binfmt.glob(\"qemu-*\"))) == 0:\n        clean_exit(\n            textwrap.dedent(\n                \"\"\"\n        You must run a one-time setup to use ARM containers on x86 via QEMU:\n\n            sudo apt install -y qemu binfmt-support qemu-user-static\n            docker run --rm --privileged multiarch/qemu-user-static --reset -p yes\n\n        See https://www.stereolabs.com/docs/docker/building-arm-container-on-x86/ for details\"\"\".strip(\n                    \"\\n\"\n                )\n            )\n        )\n\n\ndef cli_name(s: str) -> str:\n    return s.replace(\"_\", \"-\")\n\n\ndef typing_get_origin(annotation):\n    if sys.version_info >= (3, 8):\n        return typing.get_origin(annotation)\n    else:\n        return annotation.__origin__\n\n\ndef typing_get_args(annotation):\n    if sys.version_info >= (3, 8):\n        return typing.get_args(annotation)\n    else:\n        return annotation.__args__\n\n\ndef is_optional_type(annotation):\n    return (\n        hasattr(annotation, \"__origin__\")\n        and (typing_get_origin(annotation) == typing.Union)\n        and (type(None) in typing_get_args(annotation))\n    )\n\n\ndef add_subparser(\n    func: Callable,\n    subparsers: Any,\n    options: Optional[Dict[str, Option]] = None,\n    help: Optional[str] = None,\n) -> Any:\n    \"\"\"\n    Utility function to make it so subparser commands can be defined locally\n    as a function rather than directly via argparse and manually dispatched\n    out.\n    \"\"\"\n\n    # Each function is intended follow the example for arguments in PEP257, so\n    # split apart the function documentation from the arguments\n    split = [s.strip() for s in func.__doc__.split(\"arguments:\\n\")]\n    if len(split) == 1:\n        args_help = None\n        command_help = split[0]\n    else:\n        command_help, args_help = split\n\n    if help is not None:\n        command_help = help\n\n    # Parse out the help text for each argument if present\n    arg_help_texts = {}\n    if args_help is not None:\n        for line in args_help.split(\"\\n\"):\n            line = line.strip()\n            name, help_text = [t.strip() for t in line.split(\" -- \")]\n            arg_help_texts[cli_name(name)] = help_text\n\n    subparser = subparsers.add_parser(cli_name(func.__name__), help=command_help)\n\n    seen_prefixes = set()\n\n    # Add each parameter to the subparser\n    signature = inspect.signature(func)\n    for name, value in signature.parameters.items():\n        if name == \"kwargs\":\n            continue\n\n        arg_cli_name = cli_name(name)\n        kwargs: Dict[str, Union[str, bool]] = {\"help\": arg_help_texts[arg_cli_name]}\n\n        is_optional = is_optional_type(value.annotation)\n        if is_optional:\n            arg_type = typing_get_args(value.annotation)[0]\n        else:\n            arg_type = value.annotation\n\n        # Grab the default value if present\n        has_default = False\n        if value.default is not value.empty:\n            kwargs[\"default\"] = value.default\n            has_default = True\n\n        # Check if it should be a flag\n        if arg_type is bool:\n            kwargs[\"action\"] = \"store_true\"\n        else:\n            kwargs[\"required\"] = not is_optional and not has_default\n\n        if str(arg_type).startswith(\"typing.List\"):\n            kwargs[\"action\"] = \"append\"\n\n        if arg_cli_name[0] not in seen_prefixes:\n            subparser.add_argument(f\"-{arg_cli_name[0]}\", f\"--{arg_cli_name}\", **kwargs)\n            seen_prefixes.add(arg_cli_name[0])\n        else:\n            subparser.add_argument(f\"--{arg_cli_name}\", **kwargs)\n\n    if options is not None:\n        for option_name, (help, _) in options.items():\n            option_cli_name = cli_name(option_name)\n            if option_cli_name[0] not in seen_prefixes:\n                subparser.add_argument(\n                    f\"-{option_cli_name[0]}\", f\"--{option_cli_name}\", action=\"store_true\", help=help\n                )\n                seen_prefixes.add(option_cli_name[0])\n            else:\n                subparser.add_argument(f\"--{option_cli_name}\", action=\"store_true\", help=help)\n\n    return subparser\n\n\nCPP_UNITTEST = (\"run c++ unitests\", [\"./tests/scripts/task_cpp_unittest.sh {build_dir}\"])\n\ngenerated = [\n    generate_command(\n        name=\"gpu\",\n        help=\"Run GPU build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"topi\": (\"run topi tests\", [\"./tests/scripts/task_python_topi.sh\"]),\n            \"unittest\": (\n                \"run unit tests\",\n                [\n                    \"./tests/scripts/task_java_unittest.sh\",\n                    \"./tests/scripts/task_python_unittest_gpuonly.sh\",\n                    \"./tests/scripts/task_python_integration_gpuonly.sh\",\n                ],\n            ),\n            \"frontend\": (\"run frontend tests\", [\"./tests/scripts/task_python_frontend.sh\"]),\n        },\n    ),\n    generate_command(\n        name=\"cpu\",\n        help=\"Run CPU build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"integration\": (\n                \"run integration tests\",\n                [\"./tests/scripts/task_python_integration.sh\"],\n            ),\n            \"unittest\": (\n                \"run unit tests\",\n                [\n                    \"./tests/scripts/task_python_unittest.sh\",\n                    \"./tests/scripts/task_python_vta_fsim.sh\",\n                    \"./tests/scripts/task_python_vta_tsim.sh\",\n                ],\n            ),\n            \"frontend\": (\"run frontend tests\", [\"./tests/scripts/task_python_frontend_cpu.sh\"]),\n        },\n    ),\n    generate_command(\n        name=\"minimal\",\n        help=\"Run minimal CPU build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"unittest\": (\n                \"run unit tests\",\n                [\n                    \"./tests/scripts/task_python_unittest.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"i386\",\n        help=\"Run i386 build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"integration\": (\n                \"run integration tests\",\n                [\n                    \"./tests/scripts/task_python_unittest.sh\",\n                    \"./tests/scripts/task_python_integration_i386only.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"wasm\",\n        help=\"Run WASM build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"test\": (\"run WASM tests\", [\"./tests/scripts/task_web_wasm.sh\"]),\n        },\n    ),\n    generate_command(\n        name=\"cortexm\",\n        help=\"Run Cortex-M build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"test\": (\n                \"run microTVM tests\",\n                [\n                    \"./tests/scripts/task_python_microtvm.sh\",\n                    \"./tests/scripts/task_demo_microtvm.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"hexagon\",\n        help=\"Run Hexagon build and test(s)\",\n        post_build=[\"./tests/scripts/task_build_hexagon_api.sh --output build-hexagon\"],\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"test\": (\n                \"run Hexagon API/Python tests\",\n                [\n                    \"./tests/scripts/task_python_hexagon.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"arm\",\n        help=\"Run ARM build and test(s) (native or via QEMU on x86)\",\n        precheck=check_arm_qemu,\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"python\": (\n                \"run full Python tests\",\n                [\n                    \"./tests/scripts/task_python_unittest.sh\",\n                    \"./tests/scripts/task_python_arm_compute_library.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"riscv\",\n        help=\"Run RISC-V build and test(s)\",\n        options={\n            \"cpp\": CPP_UNITTEST,\n            \"python\": (\n                \"run full Python tests\",\n                [\n                    \"./tests/scripts/task_riscv_microtvm.sh\",\n                ],\n            ),\n        },\n    ),\n    generate_command(\n        name=\"adreno\",\n        help=\"Run Adreno build and test(s)\",\n        post_build=[\"./tests/scripts/task_build_adreno_bins.sh\"],\n        additional_flags={\n            \"--volume\": os.environ.get(\"ADRENO_OPENCL\", \"\") + \":/adreno-opencl\",\n            \"--env\": \"ADRENO_OPENCL=/adreno-opencl\",\n            \"--net\": \"host\",\n        },\n        options={\n            \"test\": (\n                \"run Adreno API/Python tests\",\n                [\n                    \"./tests/scripts/task_python_adreno.sh \" + os.environ.get(\"ANDROID_SERIAL\", \"\"),\n                ],\n            ),\n        },\n    ),\n]\n\n\ndef main():\n    description = \"\"\"\n    Run CI jobs locally via Docker. This facilitates reproducing CI failures for\n    fast iteration. Note that many of the Docker images required are large (the\n    CPU and GPU images are both over 25GB) and may take some time to download on first use.\n    \"\"\"\n    parser = argparse.ArgumentParser(description=description)\n    subparsers = parser.add_subparsers(dest=\"command\")\n\n    commands = {}\n\n    # Add manually defined commands\n    for func in [docs, serve_docs, lint]:\n        add_subparser(func, subparsers)\n        commands[cli_name(func.__name__)] = func\n\n    # Add generated commands\n    for func, options, help in generated:\n        add_subparser(func, subparsers, options, help)\n        commands[cli_name(func.__name__)] = func\n\n    args = parser.parse_args()\n\n    if args.command is None:\n        # Command not found in list, error out\n        parser.print_help()\n        exit(1)\n\n    func = commands[args.command]\n\n    # Extract out the parsed args and invoke the relevant function\n    kwargs = {k: getattr(args, k) for k in dir(args) if not k.startswith(\"_\") and k != \"command\"}\n    func(**kwargs)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/release/gather_prs.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport os\nimport pickle\nfrom pathlib import Path\nimport csv\nimport sys\nfrom typing import Callable, Dict, List, Any\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent\nsys.path.append(str(REPO_ROOT / \"ci\" / \"scripts\"))\n\nfrom git_utils import git, GitHubRepo\nfrom github_tag_teams import tags_from_title\n\n\nGITHUB_TOKEN = os.environ[\"GITHUB_TOKEN\"]\n\n\nPRS_QUERY = \"\"\"\nquery ($owner: String!, $name: String!, $after: String, $pageSize: Int!) {\n  repository(owner: $owner, name: $name) {\n    defaultBranchRef {\n      name\n      target {\n        ... on Commit {\n          oid\n          history(after: $after, first: $pageSize) {\n            pageInfo {\n              hasNextPage\n              endCursor\n            }\n            nodes {\n              oid\n              committedDate\n              associatedPullRequests(first: 1) {\n                nodes {\n                  number\n                  additions\n                  changedFiles\n                  deletions\n                  author {\n                    login\n                  }\n                  title\n                  body\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\"\"\"\n\n\ndef append_and_save(items, file):\n    if not file.exists():\n        data = []\n    else:\n        with open(file, \"rb\") as f:\n            data = pickle.load(f)\n\n    data += items\n    with open(file, \"wb\") as f:\n        pickle.dump(data, f)\n\n\ndef fetch_pr_data(args, cache):\n    github = GitHubRepo(user=user, repo=repo, token=GITHUB_TOKEN)\n\n    if args.from_commit is None or args.to_commit is None:\n        print(\"--from-commit and --to-commit must be specified if --skip-query is not used\")\n        exit(1)\n\n    i = 0\n    page_size = 80\n    cursor = f\"{args.from_commit} {i}\"\n\n    while True:\n        r = github.graphql(\n            query=PRS_QUERY,\n            variables={\n                \"owner\": user,\n                \"name\": repo,\n                \"after\": cursor,\n                \"pageSize\": page_size,\n            },\n        )\n        data = r[\"data\"][\"repository\"][\"defaultBranchRef\"][\"target\"][\"history\"]\n        if not data[\"pageInfo\"][\"hasNextPage\"]:\n            break\n        cursor = data[\"pageInfo\"][\"endCursor\"]\n        results = data[\"nodes\"]\n\n        to_add = []\n        stop = False\n        for r in results:\n            if r[\"oid\"] == args.to_commit:\n                print(f\"Found {r['oid']}, stopping\")\n                stop = True\n                break\n            else:\n                to_add.append(r)\n\n        oids = [r[\"oid\"] for r in to_add]\n        print(oids)\n        append_and_save(to_add, cache)\n        if stop:\n            break\n        print(i)\n        i += page_size\n\n\ndef write_csv(\n    filename: str, data: List[Dict[str, Any]], filter: Callable[[Dict[str, Any]], bool]\n) -> None:\n    with open(filename, \"w\", newline=\"\") as csvfile:\n        writer = csv.writer(csvfile, quotechar='\"')\n        writer.writerow(\n            (\n                \"category\",\n                \"description\",\n                \"date\",\n                \"number\",\n                \"author\",\n                \"tags\",\n                \"title\",\n                \"additions\",\n                \"deletions\",\n                \"changed files\",\n            )\n        )\n        for item in data:\n            pr = item[\"associatedPullRequests\"][\"nodes\"][0]\n            if not filter(pr):\n                continue\n            tags = tags_from_title(pr[\"title\"])\n            actual_tags = []\n            for t in tags:\n                items = [x.strip() for x in t.split(\",\")]\n                actual_tags += items\n            tags = actual_tags\n            tags = [t.lower() for t in tags]\n            category = \"\"\n            if len(tags) == 1:\n                category = tags[0]\n            writer.writerow(\n                (\n                    category,\n                    \"\",\n                    item[\"committedDate\"],\n                    f'https://github.com/apache/tvm/pull/{pr[\"number\"]}',\n                    pr[\"author\"][\"login\"],\n                    \", \".join(tags),\n                    pr[\"title\"],\n                    pr[\"additions\"],\n                    pr[\"deletions\"],\n                    pr[\"changedFiles\"],\n                )\n            )\n\n\nif __name__ == \"__main__\":\n    help = \"List out commits with attached PRs since a certain commit\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--from-commit\", help=\"commit to start checking PRs from\")\n    parser.add_argument(\"--to-commit\", help=\"commit to stop checking PRs from\")\n    parser.add_argument(\n        \"--threshold\", default=150, help=\"sum of additions + deletions to consider large\"\n    )\n    parser.add_argument(\n        \"--skip-query\", action=\"store_true\", help=\"don't query GitHub and instead use cache file\"\n    )\n    args = parser.parse_args()\n    user = \"apache\"\n    repo = \"tvm\"\n    threshold = int(args.threshold)\n\n    cache = Path(\"out.pkl\")\n    if not args.skip_query:\n        fetch_pr_data(args, cache)\n\n    with open(cache, \"rb\") as f:\n        data = pickle.load(f)\n\n    print(f\"Found {len(data)} PRs\")\n\n    write_csv(\n        filename=\"out-large.csv\",\n        data=data,\n        filter=lambda pr: pr[\"additions\"] + pr[\"deletions\"] > threshold,\n    )\n    write_csv(\n        filename=\"out-small.csv\",\n        data=data,\n        filter=lambda pr: pr[\"additions\"] + pr[\"deletions\"] <= threshold,\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/release/list_rfcs.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport subprocess\nimport sys\n\nLINK_BASE = \"https://github.com/apache/tvm-rfcs/blob/main/\"\nCOMMIT_BASE = \"https://github.com/apache/tvm-rfcs/commit/\"\n\n\ndef sprint(*args):\n    print(*args, file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n    help = \"List out RFCs since a commit\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--since-commit\", required=True, help=\"last commit to include\")\n    parser.add_argument(\"--rfcs-repo\", required=True, help=\"path to checkout of apache/tvm-rfcs\")\n    args = parser.parse_args()\n    user = \"apache\"\n    repo = \"tvm\"\n    rfc_repo = args.rfcs_repo\n    subprocess.run(\"git fetch origin main\", cwd=rfc_repo, shell=True)\n    subprocess.run(\"git checkout main\", cwd=rfc_repo, shell=True)\n    subprocess.run(\"git reset --hard origin/main\", cwd=rfc_repo, shell=True)\n    r = subprocess.run(\n        f\"git log {args.since_commit}..HEAD --format='%H %s'\",\n        cwd=rfc_repo,\n        shell=True,\n        stdout=subprocess.PIPE,\n        encoding=\"utf-8\",\n    )\n    commits = r.stdout.strip().split(\"\\n\")\n    for commit in commits:\n        parts = commit.split()\n        commit = parts[0]\n        subject = \" \".join(parts[1:])\n\n        r2 = subprocess.run(\n            f\"git diff-tree --no-commit-id --name-only -r {commit}\",\n            cwd=rfc_repo,\n            shell=True,\n            stdout=subprocess.PIPE,\n            encoding=\"utf-8\",\n        )\n        files = r2.stdout.strip().split(\"\\n\")\n        rfc_file = None\n        for file in files:\n            if file.startswith(\"rfcs/\") and file.endswith(\".md\"):\n                if rfc_file is not None:\n                    sprint(f\"error on {commit} {subject}\")\n                rfc_file = file\n\n        if rfc_file is None:\n            sprint(f\"error on {commit} {subject}\")\n            continue\n\n        print(f\" * [{subject}]({LINK_BASE + rfc_file}) ([`{commit[:7]}`]({COMMIT_BASE + commit}))\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/release/make_notes.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport os\nimport pickle\nfrom pathlib import Path\nimport csv\nimport sys\nfrom collections import defaultdict\nfrom typing import Callable, Dict, List, Any\n\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent\nsys.path.append(str(REPO_ROOT / \"tests\" / \"scripts\"))\n\n\ndef strip_header(title: str, header: str) -> str:\n    pos = title.lower().find(header.lower())\n    if pos == -1:\n        return title\n\n    return title[0:pos] + title[pos + len(header) :].strip()\n\n\ndef sprint(*args):\n    print(*args, file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n    help = \"List out commits with attached PRs since a certain commit\"\n    parser = argparse.ArgumentParser(description=help)\n    parser.add_argument(\"--notes-csv\", required=True, help=\"csv file of categorized PRs in order\")\n    args = parser.parse_args()\n    user = \"apache\"\n    repo = \"tvm\"\n\n    cache = Path(\"out.pkl\")\n    if not cache.exists():\n        sprint(\"run gather_prs.py first to generate out.pkl\")\n        exit(1)\n\n    with open(cache, \"rb\") as f:\n        data = pickle.load(f)\n\n    sprint(data[1])\n    reverse = {}\n    for item in data:\n        prs = item[\"associatedPullRequests\"][\"nodes\"]\n        if len(prs) != 1:\n            continue\n\n        pr = prs[0]\n        reverse[pr[\"number\"]] = pr\n\n    def pr_title(number, heading):\n        title = reverse[int(number)][\"title\"]\n        title = strip_header(title, heading)\n        return title\n\n    headings = defaultdict(lambda: defaultdict(list))\n    output = \"\"\n\n    sprint(\"Opening CSV\")\n    with open(args.notes_csv) as f:\n        # Skip header stuff\n        f.readline()\n        f.readline()\n        f.readline()\n\n        input_file = csv.DictReader(f)\n\n        i = 0\n        for row in input_file:\n            category = row[\"category\"].strip()\n            subject = row[\"subject\"].strip()\n            pr_number = row[\"url\"].split(\"/\")[-1]\n            if category == \"\" or subject == \"\":\n                sprint(f\"Skipping {pr_number}\")\n                continue\n\n            headings[category][subject].append(pr_number)\n            i += 1\n            # if i > 30:\n            #     break\n\n    def sorter(x):\n        if x == \"Misc\":\n            return 10\n        return 0\n\n    keys = list(headings.keys())\n    keys = list(sorted(keys))\n    keys = list(sorted(keys, key=sorter))\n    for key in keys:\n        value = headings[key]\n        if key == \"DO NOT INCLUDE\":\n            continue\n        value = dict(value)\n        output += f\"### {key}\\n\"\n\n        misc = []\n        misc += value.get(\"n/a\", [])\n        misc += value.get(\"Misc\", [])\n        for pr_number in misc:\n            output += f\" * #{pr_number} - {pr_title(pr_number, '[' + key + ']')}\\n\"\n\n        for subheading, pr_numbers in value.items():\n            if subheading == \"DO NOT INCLUDE\":\n                continue\n            if subheading == \"n/a\" or subheading == \"Misc\":\n                continue\n            else:\n                output += f\" * {subheading} - \" + \", \".join([f\"#{n}\" for n in pr_numbers]) + \"\\n\"\n            # print(value)\n\n        output += \"\\n\"\n\n    print(output)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/request_hook/request_hook.py",
        "content": "#!/usr/bin/env bash\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport urllib.request\nimport logging\n\nLOGGER = None\n\n\n# To update this list, run the workflow <HERE> with the URL to download and the SHA512 of the file\nBASE = \"https://tvm-ci-resources.s3.us-west-2.amazonaws.com\"\nURL_MAP = {\n    \"http://data.mxnet.io.s3-website-us-west-1.amazonaws.com/data/val_256_q90.rec\": f\"{BASE}/mxnet-val_256_q90.rec\",\n    \"http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel\": f\"{BASE}/bvlc_alexnet.caffemodel\",\n    \"http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel\": f\"{BASE}/bvlc_googlenet.caffemodel\",\n    \"http://download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz\": f\"{BASE}/tf-mobilenet_v1_1.0_224.tgz\",\n    \"http://images.cocodataset.org/zips/val2017.zip\": f\"{BASE}/cocodataset-val2017.zip\",\n    \"https://bj.bcebos.com/x2paddle/models/paddle_resnet50.tar\": f\"{BASE}/bcebos-paddle_resnet50.tar\",\n    \"https://data.deepai.org/stanfordcars.zip\": f\"{BASE}/deepai-stanfordcars.zip\",\n    \"https://docs-assets.developer.apple.com/coreml/models/MobileNet.mlmodel\": f\"{BASE}/2022-10-05/MobileNet.mlmodel\",\n    \"https://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth\": f\"{BASE}/2022-10-05/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth\",\n    \"https://download.pytorch.org/models/mobilenet_v2-b0353104.pth\": f\"{BASE}/2022-10-05/mobilenet_v2-b0353104.pth\",\n    \"https://download.pytorch.org/models/resnet18-f37072fd.pth\": f\"{BASE}/2022-10-05/resnet18-f37072fd.pth\",\n    \"https://gist.github.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/93672b029103648953c4e5ad3ac3aadf346a4cdc/super_resolution_0.2.onnx\": f\"{BASE}/2022-10-05/super_resolution_0.2.onnx\",\n    \"https://gist.githubusercontent.com/zhreshold/4d0b62f3d01426887599d4f7ede23ee5/raw/596b27d23537e5a1b5751d2b0481ef172f58b539/imagenet1000_clsid_to_human.txt\": f\"{BASE}/2022-10-05/imagenet1000_clsid_to_human.txt\",\n    \"https://github.com/dmlc/web-data/blob/main/darknet/data/dog.jpg\": f\"{BASE}/dog.jpg\",\n    \"https://github.com/dmlc/web-data/blob/main/gluoncv/detection/street_small.jpg?raw=true\": f\"{BASE}/2022-10-05/small_street_raw.jpg\",\n    \"https://github.com/dmlc/web-data/raw/main/gluoncv/detection/street_small.jpg\": f\"{BASE}/2022-10-05/gluon-small-stree.jpg\",\n    \"https://github.com/JonathanCMitchell/mobilenet_v2_keras/releases/download/v1.1/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5\": f\"{BASE}/2022-10-05/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5\",\n    \"https://github.com/onnx/models/raw/bd206494e8b6a27b25e5cf7199dbcdbfe9d05d1c/vision/classification/mnist/model/mnist-1.onnx\": f\"{BASE}/onnx/mnist-1.onnx\",\n    \"https://github.com/onnx/models/raw/main/vision/classification/resnet/model/resnet50-v2-7.onnx\": f\"{BASE}/2022-10-05/resnet50-v2-7.onnx\",\n    \"https://github.com/pjreddie/darknet/blob/master/cfg/yolov3-tiny.cfg?raw=true\": f\"{BASE}/2022-10-05/yolov3-tiny-raw.cfg\",\n    \"https://github.com/uwsampl/web-data/raw/main/vta/models/synset.txt\": f\"{BASE}/2022-10-05/synset.txt\",\n    \"https://homes.cs.washington.edu/~cyulin/media/gnn_model/gcn_cora.torch\": f\"{BASE}/gcn_cora.torch\",\n    \"https://homes.cs.washington.edu/~moreau/media/vta/cat.jpg\": f\"{BASE}/vta_cat.jpg\",\n    \"https://objects.githubusercontent.com/github-production-release-asset-2e65be/130932608/4b196a8a-4e2d-11e8-9a11-be3c41846711?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20221004%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221004T170456Z&X-Amz-Expires=300&X-Amz-Signature=0602b68e8864b9b01c9142eee22aed3543fe98a5482686eec33d98e2617a2295&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=130932608&response-content-disposition=attachment%3B%20filename%3Dmobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5&response-content-type=application%2Foctet-stream\": f\"{BASE}/2022-10-05/aws-mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5\",\n    \"https://oneflow-public.oss-cn-beijing.aliyuncs.com/model_zoo/flowvision/classification/ResNet/resnet18.zip\": f\"{BASE}/oneflow/resnet18.zip\",\n    \"https://people.linaro.org/~tom.gall/sine_model.tflite\": f\"{BASE}/sine_model.tflite\",\n    \"https://pjreddie.com/media/files/yolov3-tiny.weights?raw=true\": f\"{BASE}/yolov3-tiny.weights\",\n    \"https://pjreddie.com/media/files/yolov3.weights\": f\"{BASE}/yolov3.weights\",\n    \"https://raw.githubusercontent.com/Cadene/pretrained-models.pytorch/master/data/imagenet_classes.txt\": f\"{BASE}/2022-10-05/imagenet_classes.txt\",\n    \"https://raw.githubusercontent.com/Cadene/pretrained-models.pytorch/master/data/imagenet_synsets.txt\": f\"{BASE}/2022-10-05/imagenet_synsets.txt\",\n    \"https://raw.githubusercontent.com/dmlc/web-data/main/gluoncv/detection/street_small.jpg\": f\"{BASE}/2022-10-05/small_street.jpg\",\n    \"https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/detection/street_small.jpg\": f\"{BASE}/2022-10-05/street_small.jpg\",\n    \"https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/lite/java/demo/app/src/main/assets/labels_mobilenet_quant_v1_224.txt\": f\"{BASE}/2022-10-05/labels_mobilenet_quant_v1_224.txt\",\n    \"https://raw.githubusercontent.com/tlc-pack/tophub/main/tophub/mali_v0.06.log\": f\"{BASE}/2022-10-05/mali_v0.06.log\",\n    \"https://s3.amazonaws.com/model-server/inputs/kitten.jpg\": f\"{BASE}/2022-10-05/kitten.jpg\",\n    \"https://s3.amazonaws.com/onnx-model-zoo/synset.txt\": f\"{BASE}/2022-10-05/synset-s3.txt\",\n    \"https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz\": f\"{BASE}/2022-10-05/mobilenet_v2_1.0_224_quant.tgz\",\n    \"https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/mobilenet_2_5_128_tf.h5\": f\"{BASE}/2022-10-05/mobilenet_2_5_128_tf.h5\",\n    \"https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels.h5\": f\"{BASE}/2022-10-05/resnet50_weights_tf_dim_ordering_tf_kernels.h5\",\n}\n\n\nclass TvmRequestHook(urllib.request.Request):\n    def __init__(self, url, *args, **kwargs):\n        LOGGER.info(f\"Caught access to {url}\")\n        if url in URL_MAP:\n            new_url = URL_MAP[url]\n            LOGGER.info(f\"Mapped URL {url} to {new_url}\")\n        else:\n            new_url = url\n        super().__init__(new_url, *args, **kwargs)\n\n\ndef init():\n    global LOGGER\n    urllib.request.Request = TvmRequestHook\n    LOGGER = logging.getLogger(\"tvm_request_hook\")\n    LOGGER.setLevel(logging.DEBUG)\n    fh = logging.FileHandler(\"redirected_urls.log\")\n    fh.setLevel(logging.DEBUG)\n    LOGGER.addHandler(fh)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "tests/scripts/task_build.py",
        "content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport shutil\nimport os\nimport logging\nimport sys\nimport multiprocessing\n\nfrom pathlib import Path\n\n# Hackery to enable importing of utils from ci/scripts\nREPO_ROOT = Path(__file__).resolve().parent.parent.parent\nsys.path.append(str(REPO_ROOT / \"ci\" / \"scripts\"))\nfrom cmd_utils import Sh, init_log, REPO_ROOT\n\n\nif __name__ == \"__main__\":\n    init_log()\n\n    parser = argparse.ArgumentParser(description=\"List pytest nodeids for a folder\")\n    parser.add_argument(\"--sccache-bucket\", required=False, help=\"sccache bucket name\")\n    parser.add_argument(\"--build-dir\", default=\"build\", help=\"build folder\")\n    parser.add_argument(\"--cmake-target\", help=\"optional build target\")\n    args = parser.parse_args()\n\n    env = {\"VTA_HW_PATH\": str(Path(os.getcwd()) / \"3rdparty\" / \"vta-hw\")}\n    sccache_exe = shutil.which(\"sccache\")\n\n    use_sccache = sccache_exe is not None\n    build_dir = Path(os.getcwd()) / args.build_dir\n    build_dir = build_dir.relative_to(REPO_ROOT)\n\n    if use_sccache:\n        if args.sccache_bucket:\n            env[\"SCCACHE_BUCKET\"] = args.sccache_bucket\n            logging.info(f\"Using sccache bucket: {args.sccache_bucket}\")\n        else:\n            logging.info(f\"No sccache bucket set, using local cache\")\n        env[\"CXX\"] = \"/opt/sccache/c++\"\n        env[\"CC\"] = \"/opt/sccache/cc\"\n\n    else:\n        if sccache_exe is None:\n            reason = \"'sccache' executable not found\"\n        else:\n            reason = \"<unknown>\"\n        logging.info(f\"Not using sccache, reason: {reason}\")\n\n    sh = Sh(env)\n\n    if use_sccache:\n        sh.run(\"sccache --start-server\", check=False)\n        logging.info(\"===== sccache stats =====\")\n        sh.run(\"sccache --show-stats\")\n\n    executors = int(os.environ.get(\"CI_NUM_EXECUTORS\", 1))\n\n    nproc = multiprocessing.cpu_count()\n\n    available_cpus = nproc // executors\n    num_cpus = max(available_cpus, 1)\n\n    sh.run(\"cmake -GNinja -DCMAKE_BUILD_TYPE=RelWithDebInfo ..\", cwd=build_dir)\n\n    target = \"\"\n    if args.cmake_target:\n        target = args.cmake_target\n\n    verbose = os.environ.get(\"VERBOSE\", \"true\").lower() in {\"1\", \"true\", \"yes\"}\n    ninja_args = [target, f\"-j{num_cpus}\"]\n    if verbose:\n        ninja_args.append(\"-v\")\n    sh.run(f\"cmake --build . -- \" + \" \".join(ninja_args), cwd=build_dir)\n\n    if use_sccache:\n        logging.info(\"===== sccache stats =====\")\n        sh.run(\"sccache --show-stats\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "version.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nThis is the global script that set the version information of TVM.\nThis script runs and update all the locations that related to versions\n\nList of affected files:\n- tvm-root/python/tvm/_ffi/libinfo.py\n- tvm-root/include/tvm/runtime/c_runtime_api.h\n- tvm-root/conda/recipe/meta.yaml\n- tvm-root/web/package.json\n\"\"\"\nimport os\nimport re\nimport argparse\nimport logging\nimport subprocess\n\n# Modify the following value during release\n# ---------------------------------------------------\n# Current version:\n# We use the version of the incoming release for code\n# that is under development.\n#\n# It is also fallback version to be used when --git-describe\n# is not invoked, or when the repository does not present the\n# git tags in a format that this script can use.\n#\n# Two tag formats are supported:\n# - vMAJ.MIN.PATCH (e.g. v0.8.0) or\n# - vMAJ.MIN.devN (e.g. v0.8.dev0)\n__version__ = \"0.11.dev0\"\n\n# ---------------------------------------------------\n\nPROJ_ROOT = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n\n\ndef py_str(cstr):\n    return cstr.decode(\"utf-8\")\n\n\ndef git_describe_version():\n    \"\"\"Get PEP-440 compatible public and local version using git describe.\n\n    Returns\n    -------\n    pub_ver: str\n        Public version.\n\n    local_ver: str\n        Local version (with additional label appended to pub_ver).\n\n    Notes\n    -----\n    - We follow PEP 440's convention of public version\n      and local versions.\n    - Only tags conforming to vMAJOR.MINOR.REV (e.g. \"v0.7.0\")\n      are considered in order to generate the version string.\n      See the use of `--match` in the `git` command below.\n\n    Here are some examples:\n\n    - pub_ver = '0.7.0', local_ver = '0.7.0':\n      We are at the 0.7.0 release.\n    - pub_ver =  '0.8.dev94', local_ver = '0.8.dev94+g0d07a329e':\n      We are at the 0.8 development cycle.\n      The current source contains 94 additional commits\n      after the most recent tag(v0.7.0),\n      the git short hash tag of the current commit is 0d07a329e.\n    \"\"\"\n    cmd = [\n        \"git\",\n        \"describe\",\n        \"--tags\",\n        \"--match\",\n        \"v[0-9]*.[0-9]*.[0-9]*\",\n        \"--match\",\n        \"v[0-9]*.[0-9]*.dev[0-9]*\",\n    ]\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=PROJ_ROOT)\n    (out, _) = proc.communicate()\n\n    if proc.returncode != 0:\n        msg = py_str(out)\n        if msg.find(\"not a git repository\") != -1:\n            return __version__, __version__\n        logging.warning(\"git describe: %s, use %s\", msg, __version__)\n        return __version__, __version__\n    describe = py_str(out).strip()\n    arr_info = describe.split(\"-\")\n\n    # Remove the v prefix, mainly to be robust\n    # to the case where v is not presented as well.\n    if arr_info[0].startswith(\"v\"):\n        arr_info[0] = arr_info[0][1:]\n\n    # hit the exact tag\n    if len(arr_info) == 1:\n        return arr_info[0], arr_info[0]\n\n    if len(arr_info) != 3:\n        logging.warning(\"Invalid output from git describe %s\", describe)\n        return __version__, __version__\n\n    dev_pos = arr_info[0].find(\".dev\")\n\n    # Development versions:\n    # The code will reach this point in case it can't match a full release version, such as v0.7.0.\n    #\n    # 1. in case the last known label looks like vMAJ.MIN.devN e.g. v0.8.dev0, we use\n    # the current behaviour of just using vMAJ.MIN.devNNNN+gGIT_REV\n    if dev_pos != -1:\n        dev_version = arr_info[0][: arr_info[0].find(\".dev\")]\n    # 2. in case the last known label looks like vMAJ.MIN.PATCH e.g. v0.8.0\n    # then we just carry on with a similar version to what git describe provides, which is\n    # vMAJ.MIN.PATCH.devNNNN+gGIT_REV\n    else:\n        dev_version = arr_info[0]\n\n    pub_ver = \"%s.dev%s\" % (dev_version, arr_info[1])\n    local_ver = \"%s+%s\" % (pub_ver, arr_info[2])\n    return pub_ver, local_ver\n\n\n# Implementations\ndef update(file_name, pattern, repl, dry_run=False):\n    update = []\n    hit_counter = 0\n    need_update = False\n    with open(file_name) as file:\n        for l in file:\n            result = re.findall(pattern, l)\n            if result:\n                assert len(result) == 1\n                hit_counter += 1\n                if result[0] != repl:\n                    l = re.sub(pattern, repl, l)\n                    need_update = True\n                    print(\"%s: %s -> %s\" % (file_name, result[0], repl))\n                else:\n                    print(\"%s: version is already %s\" % (file_name, repl))\n\n            update.append(l)\n    if hit_counter != 1:\n        raise RuntimeError(\"Cannot find version in %s\" % file_name)\n\n    if need_update and not dry_run:\n        with open(file_name, \"w\") as output_file:\n            for l in update:\n                output_file.write(l)\n\n\ndef sync_version(pub_ver, local_ver, dry_run):\n    \"\"\"Synchronize version.\"\"\"\n    # python uses the PEP-440: local version\n    update(\n        os.path.join(PROJ_ROOT, \"python\", \"tvm\", \"_ffi\", \"libinfo.py\"),\n        r\"(?<=__version__ = \\\")[.0-9a-z\\+]+\",\n        local_ver,\n        dry_run,\n    )\n    # Use public version for other parts for now\n    # Note that full git hash is already available in libtvm\n    # C++ header\n    update(\n        os.path.join(PROJ_ROOT, \"include\", \"tvm\", \"runtime\", \"c_runtime_api.h\"),\n        r'(?<=TVM_VERSION \")[.0-9a-z\\+]+',\n        pub_ver,\n        dry_run,\n    )\n    # conda\n    update(\n        os.path.join(PROJ_ROOT, \"conda\", \"recipe\", \"meta.yaml\"),\n        r\"(?<=version = ')[.0-9a-z\\+]+\",\n        pub_ver,\n        dry_run,\n    )\n    # web\n    # change to pre-release convention by npm\n    dev_pos = pub_ver.find(\".dev\")\n    npm_ver = pub_ver if dev_pos == -1 else \"%s.0-%s\" % (pub_ver[:dev_pos], pub_ver[dev_pos + 1 :])\n    update(\n        os.path.join(PROJ_ROOT, \"web\", \"package.json\"),\n        r'(?<=\"version\": \")[.0-9a-z\\-\\+]+',\n        npm_ver,\n        dry_run,\n    )\n\n\ndef main():\n    logging.basicConfig(level=logging.INFO)\n    parser = argparse.ArgumentParser(description=\"Detect and synchronize version.\")\n    parser.add_argument(\n        \"--print-version\",\n        action=\"store_true\",\n        help=\"Print version to the command line. No changes is applied to files.\",\n    )\n    parser.add_argument(\n        \"--git-describe\",\n        action=\"store_true\",\n        help=\"Use git describe to generate development version.\",\n    )\n    parser.add_argument(\"--dry-run\", action=\"store_true\")\n\n    opt = parser.parse_args()\n    pub_ver, local_ver = __version__, __version__\n    if opt.git_describe:\n        pub_ver, local_ver = git_describe_version()\n    if opt.print_version:\n        print(local_ver)\n    else:\n        sync_version(pub_ver, local_ver, opt.dry_run)\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"VTA Package is a TVM backend extension to support VTA hardware.\n\nBesides the compiler toolchain, it also includes utility functions to\nconfigure the hardware environment and access remote device through RPC.\n\"\"\"\nimport sys\nimport tvm._ffi.base\n\nfrom .autotvm import module_loader\nfrom .bitstream import get_bitstream_path, download_bitstream\nfrom .environment import get_env, Environment\nfrom .rpc_client import reconfig_runtime, program_fpga\n\n__version__ = \"0.1.0\"\n\n\n# do not from tvm import topi when running vta.exec.rpc_server\n# in lib tvm runtime only mode\nif not tvm._ffi.base._RUNTIME_ONLY:\n    from . import top\n    from .build_module import build_config, lower, build\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/autotvm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Defines AutoTVM components used with VTA.\"\"\"\n\nfrom tvm.autotvm.measure import default_module_loader\nfrom . import rpc_client\n\n\ndef module_loader(bitstream=None):\n    \"\"\"Construct a ModuleLoader implementation specialized for VTA.\n\n    Parameters\n    ----------\n    bitsream : Optional[str]\n        Path to the bitstream to write prior to uploading code.\n\n    Returns\n    -------\n    ModuleLoader :\n        The ModuleLoader instance.\n    \"\"\"\n\n    def reprogram_fpga(remote, _build_result):\n        \"\"\"default_module_loader callback which reprograms the FPGA.\n\n        Parameters\n        ----------\n        remote : tvm.rpc.RPCSession\n            RPC session established to the remote device.\n\n        _build_result : tvm.autotvm.measure.measure_methods.BuildResult\n            Artifact from the build phase, unused here.\n        \"\"\"\n        rpc_client.program_fpga(remote, bitstream)\n        rpc_client.reconfig_runtime(remote)\n\n    return default_module_loader(reprogram_fpga)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/bitstream.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA specific bitstream management library.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport os\nimport sys\n\nfrom tvm.contrib.download import download\nfrom .environment import get_env\n\nif sys.version_info >= (3,):\n    import urllib.error as urllib2\nelse:\n    import urllib2\n\n# bitstream repo\nBITSTREAM_URL = \"https://github.com/uwsampl/vta-distro/raw/master/bitstreams/\"\n\n\ndef get_bitstream_path():\n    \"\"\"Returns the path to the cached bitstream corresponding to the current config\n\n    Returns\n    -------\n    bit_path: str\n        Corresponding to the filepath of the bitstream\n    \"\"\"\n\n    env = get_env()\n\n    # Derive destination path\n    cache_dir = os.getenv(\"VTA_CACHE_PATH\", os.path.join(os.getenv(\"HOME\"), \".vta_cache/\"))\n    cache_dir = os.path.join(cache_dir, env.TARGET)\n    cache_dir = os.path.join(cache_dir, env.HW_VER.replace(\".\", \"_\"))\n    # Create the directory if it didn't exist\n    if not os.path.exists(cache_dir):\n        os.makedirs(cache_dir)\n    bit_path = os.path.join(cache_dir, env.BITSTREAM) + \".bit\"\n\n    return bit_path\n\n\ndef download_bitstream():\n    \"\"\"Downloads a cached bitstream corresponding to the current config\"\"\"\n\n    env = get_env()\n\n    success = False\n    bit = get_bitstream_path()\n    url = os.path.join(BITSTREAM_URL, env.TARGET)\n    url = os.path.join(url, env.HW_VER)\n    url = os.path.join(url, env.BITSTREAM + \".bit\")\n\n    try:\n        download(url, bit)\n    except urllib2.HTTPError as err:\n        if err.code == 404:\n            raise RuntimeError(\n                # Raise error - the solution when this happens it to build your\n                # own bitstream and add it to your $VTA_CACHE_PATH\n                \"{} is not available. It appears that this configuration \\\nbistream has not been cached. Please compile your own bitstream (see hardware \\\ncompilation guide to get Xilinx toolchains setup) and add it to your \\\n$VTA_CACHE_PATH. Alternatively edit your config.json back to its default \\\nsettings. You can see the list of available bitstreams under {}\".format(\n                    url, BITSTREAM_URL\n                )\n            )\n        raise RuntimeError(\n            # This could happen when trying to access the URL behind a proxy\n            \"Something went wrong when trying to access {}. Check your \\\ninternet connection or proxy settings.\".format(\n                url\n            )\n        )\n\n    return success\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/build_module.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, invalid-name\n\"\"\"VTA specific buildin for runtime.\"\"\"\nimport tvm\nfrom tvm.ir import register_intrin_lowering\nfrom . import transform\nfrom .environment import get_env, Environment\n\n\ndef EarlyRewrite():\n    \"\"\"Try to do storage rewrite in early pass.\"\"\"\n\n    def _transform(mod, ctx):\n        try:\n            return tvm.tir.transform.StorageRewrite()(mod)\n        except tvm.error.TVMError:\n            return mod\n\n    return tvm.transform.module_pass(_transform, opt_level=0, name=\"tir.vta.EarlyRewrite\")\n\n\ndef build_config(debug_flag=0, **kwargs):\n    \"\"\"Build a build config for VTA.\n\n    Parameters\n    ----------\n    debug_flag : int\n        The dbeug flag to be passed.\n\n    kwargs : dict\n        Additional configurations.\n\n    Returns\n    -------\n    build_config: tvm.transform.PassContext\n        The build config that can be used in TVM.\n\n    Example\n    --------\n    .. code-block:: python\n\n      # build a vta module.\n      with vta.build_config():\n          vta_module = tvm.build(s, ...)\n    \"\"\"\n    env = get_env()\n\n    @tvm.tir.transform.prim_func_pass(opt_level=0)\n    def add_debug(f, *_):\n        debug = tvm.tir.call_extern(\"int32\", \"VTASetDebugMode\", env.dev.command_handle, debug_flag)\n\n        return f.with_body(tvm.tir.stmt_seq(debug, f.body))\n\n    pass_list = [\n        (0, transform.InjectConv2DTransposeSkip()),\n        (1, transform.InjectDMAIntrin()),\n        (1, transform.InjectSkipCopy()),\n        (1, transform.AnnotateALUCoProcScope()),\n        (1, tvm.tir.transform.LiftAttrScope(\"coproc_uop_scope\")),\n        (1, transform.LiftAllocToScopeBegin()),\n        (1, tvm.tir.transform.LiftAttrScope(\"coproc_scope\")),\n        (1, transform.InjectCoProcSync()),\n        (1, EarlyRewrite()),\n    ]\n    if debug_flag:\n        pass_list.append((1, add_debug))\n    pass_list.append((2, transform.InjectALUIntrin()))\n    pass_list.append((3, tvm.tir.transform.LowerDeviceStorageAccessInfo()))\n    pass_list.append((3, transform.FoldUopLoop()))\n    pass_list.append((3, transform.CPUAccessRewrite()))\n    config = {\"tir.add_lower_pass\": pass_list}\n    if kwargs.get(\"config\"):\n        config.update(kwargs[config])\n        del kwargs[\"config\"]\n\n    return tvm.transform.PassContext(config=config, **kwargs)\n\n\ndef lower(*args, **kwargs):\n    \"\"\"Thin wrapper of tvm.lower\n\n    This wrapper automatically applies VTA's build_config\n    if there is no user specified build_config in context.\n\n    See Also\n    --------\n    tvm.lower : The original TVM's lower function\n    \"\"\"\n    pass_ctx = tvm.transform.PassContext.current()\n    if not pass_ctx.config.get(\"add_lower_pass\"):\n        with build_config():\n            return tvm.lower(*args, **kwargs)\n    return tvm.lower(*args, **kwargs)\n\n\ndef build(*args, **kwargs):\n    \"\"\"Thin wrapper of tvm.build\n\n    This wrapper automatically applies VTA's build_config\n    if there is no user specified build_config in context.\n\n    See Also\n    --------\n    tvm.build : The original TVM's build function\n    \"\"\"\n    pass_ctx = tvm.transform.PassContext.current()\n    if not pass_ctx.config.get(\"tir.add_lower_pass\"):\n        with build_config():\n            return tvm.build(*args, **kwargs)\n    return tvm.build(*args, **kwargs)\n\n\n# Register key ops\ntvm.ir.register_op_attr(\"tir.vta.coproc_sync\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Opaque)\ntvm.ir.register_op_attr(\"tir.vta.coproc_dep_push\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Opaque)\ntvm.ir.register_op_attr(\"tir.vta.coproc_dep_pop\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Opaque)\n\ntvm.ir.register_op_attr(\"tir.vta.uop_push\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Opaque)\ntvm.ir.register_op_attr(\"tir.vta.uop_push\", \"TGlobalSymbol\", \"VTAUopPush\")\n\ntvm.ir.register_op_attr(\"tir.vta.command_handle\", \"TGlobalSymbol\", \"VTATLSCommandHandle\")\ntvm.ir.register_op_attr(\"tir.vta.command_handle\", \"TCallEffectKind\", tvm.tir.CallEffectKind.Opaque)\n\n# The memory information for the compiler\n@tvm.register_func(\"tvm.info.mem.%s\" % Environment.inp_scope)\ndef mem_info_inp_buffer():\n    spec = get_env()\n    return tvm.ir.make_node(\n        \"MemoryInfo\",\n        unit_bits=spec.INP_ELEM_BITS,\n        max_simd_bits=spec.INP_ELEM_BITS,\n        max_num_bits=spec.INP_BUFF_SIZE * 8,\n        head_address=None,\n    )\n\n\n@tvm.register_func(\"tvm.info.mem.%s\" % Environment.wgt_scope)\ndef mem_info_wgt_buffer():\n    spec = get_env()\n    return tvm.ir.make_node(\n        \"MemoryInfo\",\n        unit_bits=spec.WGT_ELEM_BITS,\n        max_simd_bits=spec.WGT_ELEM_BITS,\n        max_num_bits=spec.WGT_BUFF_SIZE * 8,\n        head_address=None,\n    )\n\n\n@tvm.register_func(\"tvm.info.mem.%s\" % Environment.acc_scope)\ndef mem_info_acc_buffer():\n    spec = get_env()\n    return tvm.ir.make_node(\n        \"MemoryInfo\",\n        unit_bits=spec.ACC_ELEM_BITS,\n        max_simd_bits=spec.ACC_ELEM_BITS,\n        max_num_bits=spec.ACC_BUFF_SIZE * 8,\n        head_address=None,\n    )\n\n\n# TVM Op related registration\n@register_intrin_lowering(\"tir.vta.coproc_sync\", \"default\")\ndef coproc_sync(op):\n    _ = op\n    return tvm.tir.call_extern(\n        \"int32\",\n        \"VTASynchronize\",\n        get_env().dev.command_handle,\n        tvm.runtime.const(1 << 31, dtype=\"uint32\"),\n    )\n\n\n@register_intrin_lowering(\"tir.vta.coproc_dep_push\", \"default\")\ndef coproc_dep_push(op):\n    return tvm.tir.call_extern(\n        \"int32\", \"VTADepPush\", get_env().dev.command_handle, op.args[0], op.args[1]\n    )\n\n\n@register_intrin_lowering(\"tir.vta.coproc_dep_pop\", \"default\")\ndef coproc_dep_pop(op):\n    return tvm.tir.call_extern(\n        \"int32\", \"VTADepPop\", get_env().dev.command_handle, op.args[0], op.args[1]\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/environment.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Configurable VTA Hareware Environment scope.\"\"\"\n# pylint: disable=invalid-name, exec-used\nfrom __future__ import absolute_import as _abs\n\nimport os\nimport json\nimport copy\nimport tvm\nfrom tvm import te\nfrom . import intrin\n\n\ndef get_vta_hw_path():\n    \"\"\"Get the VTA HW path.\"\"\"\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    vta_hw_default = os.path.abspath(os.path.join(curr_path, \"../../../3rdparty/vta-hw\"))\n    VTA_HW_PATH = os.getenv(\"VTA_HW_PATH\", vta_hw_default)\n    return os.path.abspath(VTA_HW_PATH)\n\n\ndef pkg_config(cfg):\n    \"\"\"Returns PkgConfig pkg config object.\"\"\"\n    pkg_config_py = os.path.join(get_vta_hw_path(), \"config/pkg_config.py\")\n    libpkg = {\"__file__\": pkg_config_py}\n    exec(compile(open(pkg_config_py, \"rb\").read(), pkg_config_py, \"exec\"), libpkg, libpkg)\n    PkgConfig = libpkg[\"PkgConfig\"]\n    return PkgConfig(cfg)\n\n\nclass DevContext(object):\n    \"\"\"Internal development context\n\n    This contains all the non-user facing compiler\n    internal context that is hold by the Environment.\n\n    Parameters\n    ----------\n    env : Environment\n        The environment hosting the DevContext\n\n    Note\n    ----\n    This class is introduced so we have a clear separation\n    of developer related, and user facing attributes.\n    \"\"\"\n\n    # Memory id for DMA\n    MEM_ID_UOP = 0\n    MEM_ID_WGT = 1\n    MEM_ID_INP = 2\n    MEM_ID_ACC = 3\n    MEM_ID_OUT = 4\n    MEM_ID_ACC_8BIT = 5\n    # VTA ALU Opcodes\n    ALU_OPCODE_MIN = 0\n    ALU_OPCODE_MAX = 1\n    ALU_OPCODE_ADD = 2\n    ALU_OPCODE_SHR = 3\n    ALU_OPCODE_MUL = 4\n    # Task queue id (pipeline stage)\n    QID_LOAD_INP = 1\n    QID_LOAD_WGT = 1\n    QID_LOAD_OUT = 2\n    QID_STORE_OUT = 3\n    QID_COMPUTE = 2\n\n    def __init__(self, env):\n        self.vta_axis = te.thread_axis(\"vta\")\n        self.vta_push_uop = tvm.tir.StringImm(\"VTAPushGEMMOp\")\n        ctx = tvm.tir.call_intrin(\"handle\", \"tir.vta.command_handle\")\n        self.command_handle = tvm.tir.Call(\"handle\", \"tir.tvm_thread_context\", [ctx])\n        self.DEBUG_NO_SYNC = False\n        env._dev_ctx = self\n        self.gemm = intrin.gemm(env, env.mock_mode)\n\n    def get_task_qid(self, qid):\n        \"\"\"Get transformed queue index.\"\"\"\n        return 1 if self.DEBUG_NO_SYNC else qid\n\n\nclass Environment(object):\n    \"\"\"Hardware configuration object.\n\n    This object contains all the information\n    needed for compiling to a specific VTA backend.\n\n    Parameters\n    ----------\n    cfg : dict of str to value.\n        The configuration parameters.\n\n    Example\n    --------\n    .. code-block:: python\n\n      # the following code reconfigures the environment\n      # temporarily to attributes specified in new_cfg.json\n      new_cfg = json.load(json.load(open(\"new_cfg.json\")))\n      with vta.Environment(new_cfg):\n          # env works on the new environment\n          env = vta.get_env()\n    \"\"\"\n\n    current = None\n    # constants\n    MAX_XFER = 1 << 22\n    # debug flags\n    DEBUG_DUMP_INSN = 1 << 1\n    DEBUG_DUMP_UOP = 1 << 2\n    DEBUG_SKIP_READ_BARRIER = 1 << 3\n    DEBUG_SKIP_WRITE_BARRIER = 1 << 4\n    # memory scopes\n    inp_scope = \"local.inp_buffer\"\n    wgt_scope = \"local.wgt_buffer\"\n    acc_scope = \"local.acc_buffer\"\n\n    # initialization function\n    def __init__(self, cfg):\n        # Produce the derived parameters and update dict\n        self.pkg = pkg_config(cfg)\n        self.__dict__.update(self.pkg.cfg_dict)\n        # data type width\n        self.INP_WIDTH = 1 << self.LOG_INP_WIDTH\n        self.WGT_WIDTH = 1 << self.LOG_WGT_WIDTH\n        self.ACC_WIDTH = 1 << self.LOG_ACC_WIDTH\n        self.OUT_WIDTH = 1 << self.LOG_OUT_WIDTH\n        # tensor intrinsic shape\n        self.BATCH = 1 << self.LOG_BATCH\n        self.BLOCK_IN = 1 << self.LOG_BLOCK_IN\n        self.BLOCK_OUT = 1 << self.LOG_BLOCK_OUT\n        # buffer size\n        self.UOP_BUFF_SIZE = 1 << self.LOG_UOP_BUFF_SIZE\n        self.INP_BUFF_SIZE = 1 << self.LOG_INP_BUFF_SIZE\n        self.WGT_BUFF_SIZE = 1 << self.LOG_WGT_BUFF_SIZE\n        self.ACC_BUFF_SIZE = 1 << self.LOG_ACC_BUFF_SIZE\n        self.OUT_BUFF_SIZE = 1 << self.LOG_OUT_BUFF_SIZE\n        # bytes per buffer\n        self.INP_ELEM_BITS = self.BATCH * self.BLOCK_IN * self.INP_WIDTH\n        self.WGT_ELEM_BITS = self.BLOCK_OUT * self.BLOCK_IN * self.WGT_WIDTH\n        self.ACC_ELEM_BITS = self.BATCH * self.BLOCK_OUT * self.ACC_WIDTH\n        self.OUT_ELEM_BITS = self.BATCH * self.BLOCK_OUT * self.OUT_WIDTH\n        self.INP_ELEM_BYTES = self.INP_ELEM_BITS // 8\n        self.WGT_ELEM_BYTES = self.WGT_ELEM_BITS // 8\n        self.ACC_ELEM_BYTES = self.ACC_ELEM_BITS // 8\n        self.OUT_ELEM_BYTES = self.OUT_ELEM_BITS // 8\n        # dtypes\n        self.acc_dtype = \"int%d\" % self.ACC_WIDTH\n        self.inp_dtype = \"int%d\" % self.INP_WIDTH\n        self.wgt_dtype = \"int%d\" % self.WGT_WIDTH\n        self.out_dtype = \"int%d\" % self.OUT_WIDTH\n        # bistream name\n        self.BITSTREAM = self.pkg.bitstream\n        # model string\n        self.MODEL = self.TARGET + \"_\" + self.BITSTREAM\n        # lazy cached members\n        self.mock_mode = False\n        self._mock_env = None\n        self._dev_ctx = None\n        self._last_env = None\n\n    def __enter__(self):\n        self._last_env = Environment.current\n        Environment.current = self\n        return self\n\n    def __exit__(self, ptype, value, trace):\n        Environment.current = self._last_env\n\n    @property\n    def cfg_dict(self):\n        return self.pkg.cfg_dict\n\n    @property\n    def dev(self):\n        \"\"\"Developer context\"\"\"\n        if self._dev_ctx is None:\n            self._dev_ctx = DevContext(self)\n        return self._dev_ctx\n\n    @property\n    def mock(self):\n        \"\"\"A mock version of the Environment\n\n        The ALU, dma_copy and intrinsics will be\n        mocked to be nop.\n        \"\"\"\n        if self.mock_mode:\n            return self\n        if self._mock_env is None:\n            self._mock_env = copy.copy(self)\n            self._mock_env._dev_ctx = None\n            self._mock_env.mock_mode = True\n        return self._mock_env\n\n    @property\n    def dma_copy(self):\n        \"\"\"DMA copy pragma\"\"\"\n        return \"dma_copy\" if not self.mock_mode else \"skip_dma_copy\"\n\n    @property\n    def alu(self):\n        \"\"\"ALU pragma\"\"\"\n        return \"alu\" if not self.mock_mode else \"skip_alu\"\n\n    @property\n    def gemm(self):\n        \"\"\"GEMM intrinsic\"\"\"\n        return self.dev.gemm\n\n    @property\n    def target(self):\n        return tvm.target.vta(model=self.MODEL)\n\n    @property\n    def target_host(self):\n        \"\"\"The target host\"\"\"\n        if self.TARGET in [\"pynq\", \"de10nano\"]:\n            return \"llvm -mtriple=armv7-none-linux-gnueabihf\"\n        if self.TARGET == \"ultra96\":\n            return \"llvm -mtriple=aarch64-linux-gnu\"\n        if self.TARGET in [\"sim\", \"tsim\", \"intelfocl\"]:\n            return \"llvm\"\n        raise ValueError(\"Unknown target %s\" % self.TARGET)\n\n    @property\n    def target_vta_cpu(self):\n        return tvm.target.arm_cpu(model=self.TARGET)\n\n\ndef get_env():\n    \"\"\"Get the current VTA Environment.\n\n    Returns\n    -------\n    env : Environment\n        The current environment.\n    \"\"\"\n    return Environment.current\n\n\ndef _init_env():\n    \"\"\"Initialize the default global env\"\"\"\n    config_path = os.path.join(get_vta_hw_path(), \"config/vta_config.json\")\n    if not os.path.exists(config_path):\n        raise RuntimeError(\"Cannot find config in %s\" % str(config_path))\n    cfg = json.load(open(config_path))\n    return Environment(cfg)\n\n\nEnvironment.current = _init_env()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/exec/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"VTA Command line utils.\"\"\"\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/exec/rpc_server.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA customized TVM RPC Server\n\nProvides additional runtime function and library loading.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport argparse\nimport os\nimport ctypes\nimport json\nimport tvm\nfrom tvm import rpc\nfrom tvm.contrib import cc\nfrom vta import program_bitstream\n\nfrom ..environment import get_env, pkg_config\nfrom ..libinfo import find_libvta\n\n\ndef server_start():\n    \"\"\"VTA RPC server extension.\"\"\"\n    # pylint: disable=unused-variable\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    proj_root = os.path.abspath(os.path.join(curr_path, \"../../../../\"))\n    dll_path = find_libvta(\"libvta\")[0]\n    cfg_path = os.path.abspath(os.path.join(proj_root, \"3rdparty/vta-hw/config/vta_config.json\"))\n    runtime_dll = []\n    _load_module = tvm.get_global_func(\"tvm.rpc.server.load_module\")\n\n    def load_vta_dll():\n        \"\"\"Try to load vta dll\"\"\"\n        if not runtime_dll:\n            runtime_dll.append(ctypes.CDLL(dll_path, ctypes.RTLD_GLOBAL))\n        logging.info(\"Loading VTA library: %s\", dll_path)\n        return runtime_dll[0]\n\n    @tvm.register_func(\"tvm.rpc.server.load_module\", override=True)\n    def load_module(file_name):\n        load_vta_dll()\n        return _load_module(file_name)\n\n    @tvm.register_func(\"device_api.ext_dev\")\n    def ext_dev_callback():\n        load_vta_dll()\n        return tvm.get_global_func(\"device_api.ext_dev\")()\n\n    @tvm.register_func(\"tvm.contrib.vta.init\", override=True)\n    def program_fpga(file_name):\n        # pylint: disable=import-outside-toplevel\n        env = get_env()\n        if env.TARGET == \"pynq\":\n            from pynq import xlnk\n\n            # Reset xilinx driver\n            xlnk.Xlnk().xlnk_reset()\n        elif env.TARGET == \"de10nano\":\n            # Load the de10nano program function.\n            load_vta_dll()\n        path = tvm.get_global_func(\"tvm.rpc.server.workpath\")(file_name)\n        program_bitstream.bitstream_program(env.TARGET, path)\n        logging.info(\"Program FPGA with %s \", file_name)\n\n    @tvm.register_func(\"tvm.rpc.server.shutdown\", override=True)\n    def server_shutdown():\n        if runtime_dll:\n            runtime_dll[0].VTARuntimeShutdown()\n            runtime_dll.pop()\n\n    @tvm.register_func(\"tvm.contrib.vta.reconfig_runtime\", override=True)\n    def reconfig_runtime(cfg_json):\n        \"\"\"Rebuild and reload runtime with new configuration.\n\n        Parameters\n        ----------\n        cfg_json : str\n            JSON string used for configurations.\n        \"\"\"\n        env = get_env()\n        if runtime_dll:\n            if env.TARGET == \"de10nano\":\n                print(\"Please reconfigure the runtime AFTER programming a bitstream.\")\n            raise RuntimeError(\"Can only reconfig in the beginning of session...\")\n        cfg = json.loads(cfg_json)\n        cfg[\"TARGET\"] = env.TARGET\n        pkg = pkg_config(cfg)\n        # check if the configuration is already the same\n        if os.path.isfile(cfg_path):\n            old_cfg = json.loads(open(cfg_path, \"r\").read())\n            if pkg.same_config(old_cfg):\n                logging.info(\"Skip reconfig_runtime due to same config.\")\n                return\n        cflags = [\"-O2\", \"-std=c++17\"]\n        cflags += pkg.cflags\n        ldflags = pkg.ldflags\n        lib_name = dll_path\n        source = pkg.lib_source\n        logging.info(\n            \"Rebuild runtime:\\n output=%s,\\n cflags=%s,\\n source=%s,\\n ldflags=%s\",\n            dll_path,\n            \"\\n\\t\".join(cflags),\n            \"\\n\\t\".join(source),\n            \"\\n\\t\".join(ldflags),\n        )\n        cc.create_shared(lib_name, source, cflags + ldflags)\n        with open(cfg_path, \"w\") as outputfile:\n            outputfile.write(pkg.cfg_json)\n\n\ndef main():\n    \"\"\"Main funciton\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--host\", type=str, default=\"0.0.0.0\", help=\"The host IP address the server binds to\"\n    )\n    parser.add_argument(\"--port\", type=int, default=9091, help=\"The port of the RPC\")\n    parser.add_argument(\"--port-end\", type=int, default=9199, help=\"The end search port of the RPC\")\n    parser.add_argument(\n        \"--key\", type=str, default=\"\", help=\"RPC key used to identify the connection type.\"\n    )\n    parser.add_argument(\"--tracker\", type=str, default=\"\", help=\"Report to RPC tracker\")\n    args = parser.parse_args()\n    logging.basicConfig(level=logging.INFO)\n\n    if args.tracker:\n        url, port = args.tracker.split(\":\")\n        port = int(port)\n        tracker_addr = (url, port)\n        if not args.key:\n            raise RuntimeError(\"Need key to present type of resource when tracker is available\")\n    else:\n        tracker_addr = None\n\n    # register the initialization callback\n    def server_init_callback():\n        # pylint: disable=redefined-outer-name, reimported, import-outside-toplevel, import-self\n        import tvm\n        import vta.exec.rpc_server\n\n        tvm.register_func(\"tvm.rpc.server.start\", vta.exec.rpc_server.server_start, override=True)\n\n    server = rpc.Server(\n        args.host,\n        args.port,\n        args.port_end,\n        key=args.key,\n        tracker_addr=tracker_addr,\n        server_init_callback=server_init_callback,\n    )\n    server.proc.join()\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/intrin.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA related intrinsics\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\n\n\ndef gemm(env, mock=False):\n    \"\"\"Matrix-matrix multiply intrinsic\n\n    Parameters\n    ----------\n    env : Environment\n        The Environment\n\n    mock : bool\n        Whether create a mock version.\n    \"\"\"\n    wgt_lanes = env.WGT_ELEM_BITS // env.WGT_WIDTH\n    assert wgt_lanes == env.BLOCK_OUT * env.BLOCK_IN\n    wgt_shape = (env.BLOCK_OUT, env.BLOCK_IN)\n    assert wgt_shape[0] * wgt_shape[1] == wgt_lanes\n\n    inp_lanes = env.INP_ELEM_BITS // env.INP_WIDTH\n    assert inp_lanes == env.BATCH * env.BLOCK_IN\n    inp_shape = (env.BATCH, env.BLOCK_IN)\n    assert inp_shape[0] * inp_shape[1] == inp_lanes\n\n    out_lanes = env.ACC_ELEM_BITS // env.ACC_WIDTH\n    assert out_lanes == env.BATCH * env.BLOCK_OUT\n    out_shape = (env.BATCH, env.BLOCK_OUT)\n    assert out_shape[0] * out_shape[1] == out_lanes\n\n    wgt = te.placeholder(\n        (wgt_shape[0], wgt_shape[1]), dtype=\"int%d\" % env.WGT_WIDTH, name=env.wgt_scope\n    )\n    inp = te.placeholder(\n        (inp_shape[0], inp_shape[1]), dtype=\"int%d\" % env.INP_WIDTH, name=env.inp_scope\n    )\n    k = te.reduce_axis((0, wgt_shape[1]), name=\"k\")\n    out_dtype = \"int%d\" % env.ACC_WIDTH\n    out = te.compute(\n        (out_shape[0], out_shape[1]),\n        lambda i, j: te.sum(inp[i, k].astype(out_dtype) * wgt[j, k].astype(out_dtype), axis=[k]),\n        name=\"out\",\n    )\n    wgt_layout = tvm.tir.decl_buffer(\n        wgt.shape,\n        wgt.dtype,\n        env.wgt_scope,\n        scope=env.wgt_scope,\n        offset_factor=wgt_lanes,\n        data_alignment=wgt_lanes,\n    )\n    inp_layout = tvm.tir.decl_buffer(\n        inp.shape,\n        inp.dtype,\n        env.inp_scope,\n        scope=env.inp_scope,\n        offset_factor=inp_lanes,\n        data_alignment=inp_lanes,\n    )\n    out_layout = tvm.tir.decl_buffer(\n        out.shape,\n        out.dtype,\n        env.acc_scope,\n        scope=env.acc_scope,\n        offset_factor=out_lanes,\n        data_alignment=out_lanes,\n    )\n\n    def intrin_func(ins, outs):\n        \"\"\"Matrix-matrix multiply intrinsic function\"\"\"\n        dinp, dwgt = ins\n        dout = outs[0]\n\n        def instr(index):\n            \"\"\"Generate matrix-matrix multiply VTA instruction\"\"\"\n            irb = tvm.tir.ir_builder.create()\n            dev = env.dev\n            irb.scope_attr(dev.vta_axis, \"coproc_scope\", dev.get_task_qid(dev.QID_COMPUTE))\n            irb.scope_attr(dev.vta_axis, \"coproc_uop_scope\", dev.vta_push_uop)\n            if index in (0, 2):\n                irb.emit(\n                    tvm.tir.call_intrin(\n                        \"int32\",\n                        \"tir.vta.uop_push\",\n                        0,\n                        0,\n                        dout.access_ptr(\"rw\", \"int32\"),\n                        dinp.access_ptr(\"r\", \"int32\"),\n                        dwgt.access_ptr(\"r\", \"int32\"),\n                        0,\n                        0,\n                        0,\n                    )\n                )\n            else:\n                irb.emit(\n                    tvm.tir.call_intrin(\n                        \"int32\",\n                        \"tir.vta.uop_push\",\n                        0,\n                        1,\n                        dout.access_ptr(\"rw\", \"int32\"),\n                        0,\n                        0,\n                        0,\n                        0,\n                        0,\n                    )\n                )\n            return irb.get()\n\n        # return a triple of normal-set, reset, update\n        nop = tvm.tir.Evaluate(0)\n        if mock:\n            return (nop, nop, nop)\n        return (instr(0), instr(1), instr(2))\n\n    return te.decl_tensor_intrin(\n        out.op, intrin_func, name=\"GEMM\", binds={inp: inp_layout, wgt: wgt_layout, out: out_layout}\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/libinfo.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Library information.\"\"\"\nfrom __future__ import absolute_import\nimport sys\nimport os\n\nfrom .environment import get_vta_hw_path\n\n\ndef _get_lib_name(lib_name):\n    \"\"\"Get lib name with extension\n\n    Returns\n    -------\n    lib_name_ext : str\n        Name of VTA shared library with extension\n\n    Parameters\n    ------------\n    lib_name : str\n        Name of VTA shared library\n    \"\"\"\n    if sys.platform.startswith(\"win32\"):\n        return lib_name + \".dll\"\n    if sys.platform.startswith(\"darwin\"):\n        return lib_name + \".dylib\"\n    return lib_name + \".so\"\n\n\ndef find_libvta(lib_vta, optional=False):\n    \"\"\"Find VTA Chisel-based library\n\n    Returns\n    -------\n    lib_found : str\n        Library path\n\n    Parameters\n    ------------\n    lib_vta : str\n        Name of VTA shared library\n\n    optional : bool\n        Enable error check\n    \"\"\"\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    tvm_library_path = os.environ.get(\"TVM_LIBRARY_PATH\", None)\n    if tvm_library_path is None:\n        tvm_library_path = os.path.join(\n            curr_path,\n            os.pardir,\n            os.pardir,\n            os.pardir,\n            \"build\",\n        )\n\n    lib_search = [tvm_library_path, os.path.join(get_vta_hw_path(), \"build\")]\n    lib_name = _get_lib_name(lib_vta)\n    lib_path = [os.path.join(x, lib_name) for x in lib_search]\n    lib_found = [x for x in lib_path if os.path.exists(x)]\n    if not lib_found and not optional:\n        raise RuntimeError(\n            \"Cannot find the files.\\n\" + \"List of candidates:\\n\" + str(\"\\n\".join(lib_path))\n        )\n    return lib_found\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/program_bitstream.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA specific bitstream program library.\"\"\"\nimport os\nimport argparse\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"target\", type=str, default=\"\", help=\"target\")\n    parser.add_argument(\"bitstream\", type=str, default=\"\", help=\"bitstream path\")\n    args = parser.parse_args()\n\n    if args.target not in (\"pynq\", \"ultra96\", \"de10nano\", \"sim\", \"tsim\"):\n        raise RuntimeError(\"Unknown target {}\".format(args.target))\n\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    path_list = [\n        os.path.join(curr_path, \"/{}\".format(args.bitstream)),\n        os.path.join(\"./\", \"{}\".format(args.bitstream)),\n    ]\n    ok_path_list = [p for p in path_list if os.path.exists(p)]\n    if not ok_path_list:\n        raise RuntimeError(\"Cannot find bitstream file in %s\" % str(path_list))\n\n    bitstream_program(args.target, args.bitstream)\n\n\ndef pynq_bitstream_program(bitstream_path):\n    # pylint: disable=import-outside-toplevel\n    from pynq import Bitstream\n\n    bitstream = Bitstream(bitstream_path)\n    bitstream.download()\n\n\ndef de10nano_bitstream_program(bitstream_path):\n    # pylint: disable=import-outside-toplevel\n    from tvm import get_global_func\n\n    program = get_global_func(\"vta.de10nano.program\")\n    program(bitstream_path)\n\n\ndef intelfocl_bitstream_program(bitstream_path, mem_size=4 * 1024 * 1024 * 1024):\n    # pylint: disable=import-outside-toplevel\n    from tvm import get_global_func\n\n    program = get_global_func(\"vta.oclfpga.program\")\n    program(bitstream_path, mem_size)\n\n\ndef bitstream_program(target, bitstream, *args):\n    \"\"\"program bitstream to devices\"\"\"\n\n    if target in [\"pynq\", \"ultra96\"]:\n        pynq_bitstream_program(bitstream)\n    elif target in [\"de10nano\"]:\n        de10nano_bitstream_program(bitstream)\n    elif target in [\"sim\", \"tsim\"]:\n        # In simulation, bit stream programming is a no-op\n        return\n    elif target in [\"intelfocl\"]:\n        intelfocl_bitstream_program(bitstream, *args)\n    else:\n        raise RuntimeError(\"Unknown target {}\".format(target))\n\n\nif __name__ == \"__main__\":\n    main()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/rpc_client.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA RPC client function\"\"\"\nimport os\n\nfrom tvm import rpc\nfrom vta import program_bitstream\nfrom .environment import get_env\nfrom .bitstream import download_bitstream, get_bitstream_path\n\n\ndef reconfig_runtime(remote):\n    \"\"\"Reconfigure remote runtime based on current hardware spec.\n\n    Parameters\n    ----------\n    remote : RPCSession\n        The TVM RPC session\n    \"\"\"\n    env = get_env()\n    freconfig = remote.get_function(\"tvm.contrib.vta.reconfig_runtime\")\n    freconfig(env.pkg.cfg_json)\n\n\ndef program_fpga(remote, bitstream=None):\n    \"\"\"Upload and program bistream\n\n    Parameters\n    ----------\n    remote : RPCSession\n        The TVM RPC session\n\n    bitstream : str, optional\n        Path to a local bistream file. If unset, tries to download from cache server.\n    \"\"\"\n    env = get_env()\n\n    if bitstream:\n        assert os.path.isfile(bitstream)\n    else:\n        bitstream = get_bitstream_path()\n        if not os.path.isfile(bitstream):\n            if env.TARGET == \"de10nano\":\n                return\n            download_bitstream()\n\n    if isinstance(remote, rpc.LocalSession):\n        program_bitstream.bitstream_program(env.TARGET, bitstream)\n    else:\n        fprogram = remote.get_function(\"tvm.contrib.vta.init\")\n        remote.upload(bitstream)\n        fprogram(os.path.basename(bitstream))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/testing/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Testing utilities, this namespace is not imported by default.\"\"\"\n\nfrom .utils import run\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/testing/simulator.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities to start simulator.\"\"\"\nimport ctypes\nimport json\nimport warnings\nimport tvm\nfrom ..environment import get_env\nfrom ..libinfo import find_libvta\n\n\ndef _load_sw():\n    \"\"\"Load hardware library for simulator.\"\"\"\n\n    env = get_env()\n    lib_driver_name = (\n        \"libvta_tsim\"\n        if env.TARGET == \"tsim\"\n        else \"libvta\"\n        if env.TARGET == \"intelfocl\"\n        else \"libvta_fsim\"\n    )\n    require_sim = env.TARGET in (\"sim\", \"tsim\")\n    libs = []\n\n    # Load driver library\n    lib_driver = find_libvta(lib_driver_name, optional=(not require_sim))\n\n    if not lib_driver:\n        return []\n\n    try:\n        libs = [ctypes.CDLL(lib_driver[0], ctypes.RTLD_GLOBAL)]\n    except OSError as err:\n        if require_sim:\n            raise err\n        warnings.warn(\"Error when loading VTA driver {}: {}\".format(lib_driver[0], err))\n        return []\n\n    if env.TARGET == \"tsim\":\n        lib_hw = find_libvta(\"libvta_hw\", optional=True)\n        assert lib_hw  # make sure to make in ${VTA_HW_PATH}/hardware/chisel\n        f = tvm.get_global_func(\"vta.tsim.init\")\n        m = tvm.runtime.load_module(lib_hw[0], \"vta-tsim\")\n        f(m)\n        return lib_hw\n\n    return libs\n\n\ndef enabled():\n    \"\"\"Check if simulator is enabled.\"\"\"\n    f = tvm.get_global_func(\"vta.simulator.profiler_clear\", True)\n    return f is not None\n\n\ndef clear_stats():\n    \"\"\"Clear profiler statistics.\"\"\"\n    env = get_env()\n    if env.TARGET == \"sim\":\n        f = tvm.get_global_func(\"vta.simulator.profiler_clear\", True)\n    else:\n        f = tvm.get_global_func(\"vta.tsim.profiler_clear\", True)\n    if f:\n        f()\n\n\ndef stats():\n    \"\"\"Get profiler statistics\n\n    Returns\n    -------\n    stats : dict\n        Current profiler statistics\n    \"\"\"\n    env = get_env()\n    if env.TARGET == \"sim\":\n        x = tvm.get_global_func(\"vta.simulator.profiler_status\")()\n    else:\n        x = tvm.get_global_func(\"vta.tsim.profiler_status\")()\n    return json.loads(x)\n\n\n# debug flag to skip execution.\nDEBUG_SKIP_EXEC = 1\n\n\ndef debug_mode(flag):\n    \"\"\"Set debug mode\n    Paramaters\n    ----------\n    flag : int\n        The debug flag, 0 means clear all flags.\n    \"\"\"\n    tvm.get_global_func(\"vta.simulator.profiler_debug_mode\")(flag)\n\n\nLIBS = _load_sw()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/testing/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test Utilities\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport os\nfrom tvm import rpc, autotvm\nfrom ..environment import get_env\nfrom . import simulator\n\n\ndef run(run_func):\n    \"\"\"Run test function on all available env.\n\n    Parameters\n    ----------\n    run_func : function(env, remote)\n    \"\"\"\n    env = get_env()\n\n    if env.TARGET in [\"sim\", \"tsim\", \"intelfocl\"]:\n        # Talk to local RPC if necessary to debug RPC server.\n        # Compile vta on your host with make at the root.\n        # Make sure TARGET is set to \"sim\" in the config.json file.\n        # Then launch the RPC server on the host machine\n        # with ./apps/vta_rpc/start_rpc_server.sh\n        # Set your VTA_LOCAL_SIM_RPC environment variable to\n        # the port it's listening to, e.g. 9090\n        local_rpc = int(os.environ.get(\"VTA_LOCAL_SIM_RPC\", \"0\"))\n        if local_rpc:\n            remote = rpc.connect(\"127.0.0.1\", local_rpc)\n            run_func(env, remote)\n        else:\n            # Make sure simulation library exists\n            # If this fails, build vta on host (make)\n            # with TARGET=\"sim\" in the json.config file.\n            if env.TARGET == \"sim\":\n                assert simulator.enabled()\n            run_func(env, rpc.LocalSession())\n\n    elif env.TARGET in [\"pynq\", \"ultra96\", \"de10nano\"]:\n        # The environment variables below should be set if we are using\n        # a tracker to obtain a remote for a test device\n        tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n        tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n        # Otherwise, we can set the variables below to directly\n        # obtain a remote from a test device\n        pynq_host = os.environ.get(\"VTA_RPC_HOST\", None)\n        pynq_port = os.environ.get(\"VTA_RPC_PORT\", None)\n        # Run device from fleet node if env variables are defined\n        if tracker_host and tracker_port:\n            remote = autotvm.measure.request_remote(\n                env.TARGET, tracker_host, int(tracker_port), timeout=10000\n            )\n            run_func(env, remote)\n        else:\n            # Next, run on PYNQ if env variables are defined\n            if pynq_host and pynq_port:\n                remote = rpc.connect(pynq_host, int(pynq_port))\n                run_func(env, remote)\n            else:\n                raise RuntimeError(\n                    \"Please set the VTA_RPC_HOST and VTA_RPC_PORT environment variables\"\n                )\n\n    else:\n        raise RuntimeError(\"Unknown target %s\" % env.TARGET)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/__init__.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"TVM TOPI connector, eventually most of these should go to TVM repo\"\"\"\n\nfrom . import bitpack\nfrom .graphpack import graph_pack\nfrom . import op\nfrom .vta_conv2d import conv2d_packed, schedule_conv2d_packed\nfrom .vta_conv2d_transpose import conv2d_transpose_packed, schedule_conv2d_transpose_packed\nfrom .vta_group_conv2d import group_conv2d_packed, schedule_group_conv2d_packed\nfrom .vta_dense import dense_packed, schedule_dense_packed\nfrom . import utils\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/bitpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=ungrouped-imports\n\n\"\"\"Bit packing operators\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom tvm.topi import utils\n\nfrom tvm.relay.op.op import register_compute, register_injective_schedule\nfrom tvm.relay.op.op import register_pattern, OpPattern\n\n\ndef bitpack(data, bits, pack_type=\"int8\", name=\"bitpack\"):\n    \"\"\"Packs lowest dimension into format needed by VTA\n\n    Parameters\n    ----------\n    pack_axis : int\n        index of the axis to pack in data\n    bit_axis : int\n        index of axis to place bit axis in resulting packed data\n\n    Returns\n    -------\n    packed : Tensor\n        The packed tensor.\n    \"\"\"\n    shape_vec = list(data.shape)\n    if pack_type == \"int8\":\n        data_width = 8\n    elif pack_type == \"int16\":\n        data_width = 16\n    elif pack_type == \"int32\":\n        data_width = 32\n    else:\n        raise RuntimeError(\"Unknown pack type %s\" % pack_type)\n    assert data_width % bits == 0\n    lanes = data_width // bits\n\n    # Data must be in multiples of the data_width\n    assert utils.get_const_int(shape_vec[-1]) % lanes == 0, \"Not a multiple of word size\"\n    shape_vec[-1] = shape_vec[-1] // lanes\n    oshape = tuple(shape_vec)\n\n    def _bitpack(*indices):\n        ret = None\n        mask = tvm.tir.const((1 << bits) - 1, pack_type)\n        for k in range(lanes):\n            idx = list(indices)\n            idx[-1] = idx[-1] * lanes + k\n            elem = data(*idx).astype(pack_type)\n            if k == 0:\n                ret = elem & mask\n            else:\n                val = (elem & mask) << tvm.tir.const(k * bits, pack_type)\n                ret = ret | val\n        return ret\n\n    return te.compute(oshape, _bitpack, name=name, tag=\"bitpack\")\n\n\n@register_compute(\"bitpack\", level=15)\ndef compute_bitpack(attrs, inputs):\n    lanes = attrs.lanes\n    dtype = inputs[0].dtype\n    assert dtype == \"int8\"\n    width = 8\n    assert width % lanes == 0\n    bits = 8 // lanes\n    return bitpack(inputs[0], bits, dtype)\n\n\nregister_injective_schedule(\"bitpack\")\nregister_pattern(\"bitpack\", OpPattern.INJECTIVE)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/graphpack.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"A Relay implementation of graph packing.\"\"\"\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import op, transform\nfrom tvm.relay import ExprMutator\n\n\ndef run_opt_pass(expr, opt_pass):\n    \"\"\"Exectue a relay pass.\"\"\"\n    assert isinstance(opt_pass, tvm.transform.Pass)\n    mod = tvm.IRModule.from_expr(expr)\n    mod = opt_pass(mod)\n    entry = mod[\"main\"]\n    return entry if isinstance(expr, relay.Function) else entry.body\n\n\ndef _to_shape(shape):\n    \"\"\"convert shape into tuple.\"\"\"\n    return tuple(int(sh) for sh in shape)\n\n\ndef _pack_batch_channel(data, dshape, bfactor, cfactor):\n    \"\"\"Pack the data channel dimension.\"\"\"\n    assert int(dshape[0]) % bfactor == 0\n    assert int(dshape[1]) % cfactor == 0\n    data = op.reshape(\n        data,\n        newshape=(\n            int(dshape[0]) // bfactor,\n            bfactor,\n            int(dshape[1]) // cfactor,\n            cfactor,\n            int(dshape[2]),\n            int(dshape[3]),\n        ),\n    )\n    data = op.transpose(data, axes=(0, 2, 4, 5, 1, 3))\n    return data\n\n\ndef _unpack_batch_channel(data, old_shape, unpack_transpose=False):\n    \"\"\"Unpack the data channel dimension.\"\"\"\n    if unpack_transpose:\n        data = op.transpose(data, axes=(0, 4, 1, 5, 2, 3))\n    data = op.reshape(data, newshape=old_shape)\n    return data\n\n\ndef _channel_const_match(channel_length, cfactor_out):\n    \"\"\"Round the channel const variant if the value not divisible by cfactor_out\"\"\"\n    diff = int(channel_length) % cfactor_out\n    if diff != 0:\n        diff = cfactor_out - diff\n        channel_length = channel_length + diff\n\n    return diff, channel_length\n\n\ndef _const_shape_match(data, dshape, cfactor_out):\n    \"\"\"Pad the constant if the shape[0] not divisible by cfactor_out.\"\"\"\n    assert len(dshape) == 3\n    pad_width = int(dshape[0]) % cfactor_out\n    if pad_width != 0:\n        pad_width = cfactor_out - pad_width\n        data = op.nn.pad(data, [[0, pad_width], [0, 0], [0, 0]])\n        dshape = tuple([dshape[0] + pad_width, dshape[1], dshape[2]])\n    return data, dshape\n\n\ndef _weight_shape_match(data, dshape, channels, cfactor_out, transpose=False):\n    \"\"\"Pad the weight if the shape[0] not divisible by cfactor_out.\"\"\"\n    assert len(dshape) == 4\n    pad_width = int(dshape[0]) % cfactor_out\n    channels_pad = int(channels) % cfactor_out\n    if pad_width != 0:\n        pad_width = cfactor_out - pad_width\n        data = op.nn.pad(data, [[0, pad_width], [0, 0], [0, 0], [0, 0]])\n        dshape = tuple([dshape[0] + pad_width, dshape[1], dshape[2], dshape[3]])\n\n    if channels_pad != 0:\n        channels = channels + (cfactor_out - channels_pad)\n\n    return data, dshape, channels\n\n\ndef _weight_shape_match_transpose(data, dshape, channels, cfactor_out):\n    \"\"\"Pad the weight if the shape[1] not divisible by cfactor_out.\"\"\"\n    assert len(dshape) == 4\n    pad_width = int(dshape[1]) % cfactor_out\n    channels_pad = int(channels) % cfactor_out\n    if pad_width != 0:\n        pad_width = cfactor_out - pad_width\n        data = op.nn.pad(data, [[0, 0], [0, pad_width], [0, 0], [0, 0]])\n        dshape = tuple(dshape[0], [dshape[1] + pad_width, dshape[2], dshape[3]])\n\n    if channels_pad != 0:\n        channels = channels + (cfactor_out - channels_pad)\n\n    return data, dshape, channels\n\n\ndef _pack_weight(data, dshape, cfactor):\n    \"\"\"Pack the weight into packed format.\"\"\"\n    assert len(dshape) == 4\n    assert int(dshape[0]) % cfactor == 0\n    assert int(dshape[1]) % cfactor == 0\n    data = op.reshape(\n        data,\n        newshape=(\n            int(dshape[0]) // cfactor,\n            cfactor,\n            int(dshape[1]) // cfactor,\n            cfactor,\n            int(dshape[2]),\n            int(dshape[3]),\n        ),\n    )\n    data = op.transpose(data, axes=(0, 2, 4, 5, 1, 3))\n    return data\n\n\ndef _pack_weight_conv2d_transpose(data, dshape, cfactor):\n    \"\"\"Pack the weight into packed format.\"\"\"\n    dshape = _to_shape(dshape)\n    assert len(dshape) == 4\n    assert dshape[0] % cfactor == 0\n    assert dshape[1] % cfactor == 0\n    data = op.reshape(\n        data,\n        newshape=(\n            dshape[0] // cfactor,\n            cfactor,\n            dshape[1] // cfactor,\n            cfactor,\n            dshape[2],\n            dshape[3],\n        ),\n    )\n    data = op.transpose(data, axes=(2, 0, 4, 5, 3, 1))\n    return data\n\n\ndef _pack_const(data, dshape, dtype, bfactor, cfactor):\n    \"\"\"Pack a constant parameter.\"\"\"\n    dshape = _to_shape(dshape)\n    assert len(dshape) == 3\n    assert dshape[0] % cfactor == 0\n    data = op.reshape(data, newshape=(dshape[0] // cfactor, cfactor, dshape[1], dshape[2], 1))\n    data = op.transpose(data, axes=(0, 2, 3, 4, 1))\n\n    # broadcast batch dimension to bfactor\n    data = op.broadcast_to(\n        data, shape=(dshape[0] // cfactor, dshape[1], dshape[2], bfactor, cfactor)\n    )\n    return data\n\n\ndef _get_tensor_shape(node):\n    \"\"\"Get node shape.\"\"\"\n    if isinstance(node.checked_type, relay.ty.TensorType):\n        return _to_shape(node.checked_type.shape)\n    return []\n\n\ndef _get_tensor_type(node):\n    \"\"\"Get node type.\"\"\"\n    if isinstance(node.checked_type, relay.ty.TensorType):\n        return node.checked_type.dtype\n    return \"float32\"\n\n\ndef _operator_idx_inc(expr, count_meta, operator_current_idx):\n    \"\"\"Increase operator index\"\"\"\n    if isinstance(expr, relay.expr.Constant):\n        operator_current_idx = operator_current_idx + 1 if count_meta else operator_current_idx\n    else:\n        operator_current_idx = operator_current_idx + 1\n    return operator_current_idx\n\n\nclass ExprDeviceAnnot(ExprMutator):\n    \"\"\"Visitor to perform graph annotation on an AST.\n\n    Parameters\n    ----------\n    start: int\n        the start location to mark run on vta (inclusive)\n    end: int\n        the end location to mark run on vta (exclusive)\n\n    Returns\n    ---------\n    None\n    \"\"\"\n\n    def __init__(self, start=-1, end=-1):\n        self.ext_dev = tvm.device(\"ext_dev\")\n        self.cpu_dev = tvm.device(\"cpu\")\n        self.cast = op.op.get(\"cast\")\n        self.counter = -1\n        self.start = start\n        self.end = end\n        super().__init__()\n\n    def visit_call(self, call):\n        \"\"\"Visit the children.\"\"\"\n        # First visit the children.\n        args = [self.visit(arg) for arg in call.args]\n\n        self.counter += 1\n        if self.counter == self.start:\n            ret = relay.Call(call.op, args, call.attrs)\n            ret = relay.annotation.on_device(ret, self.ext_dev)\n            return ret\n\n        if self.counter == self.end:\n            ret = relay.Call(call.op, args, call.attrs)\n            ret = relay.annotation.on_device(ret, self.cpu_dev)\n            return ret\n\n        if self.counter > self.start and self.counter < self.end:\n            ret = relay.Call(call.op, args, call.attrs)\n\n            # skip the float op, i.e., float->int cast\n            if self.is_float_op(call):\n                return ret\n\n            return relay.annotation.on_device(ret, self.ext_dev)\n\n        return relay.Call(self.visit(call.op), args, call.attrs)\n\n    def is_float_op(self, call):\n        \"\"\"check if this op belongs to a float op\n        in general, float op's odtype is float;\n        a special case is float->int cast, which follow this op sequence:\n        multiply(float) -> round(float) -> clip(float) -> cast(int);\n        \"\"\"\n        args = call.args\n        odtype = _get_tensor_type(call)\n\n        if odtype == \"float32\":\n            return True\n\n        if call.op == self.cast:\n            idtype = _get_tensor_type(args[0])\n            if idtype == \"float32\":\n                return True\n\n        return False\n\n\nclass ExprLocator(ExprMutator):\n    \"\"\"Visitor to locate op on an AST.\"\"\"\n\n    def __init__(self):\n        self.counter = -1\n        self.op2nodes = {}\n        super().__init__()\n\n    def visit_call(self, call):\n        \"\"\"Visit the children.\"\"\"\n        # First visit the children.\n        args = [self.visit(arg) for arg in call.args]\n\n        odtype = _get_tensor_type(call)\n        self.counter += 1\n        if (call.op, odtype) in self.op2nodes:\n            self.op2nodes[(call.op, odtype)].append(self.counter)\n        else:\n            self.op2nodes[(call.op, odtype)] = [self.counter]\n\n        return relay.Call(self.visit(call.op), args, call.attrs)\n\n\nclass ExprPack(ExprMutator):\n    \"\"\"Visitor to perform graph packing on an AST.\"\"\"\n\n    def __init__(self, bfactor, cfactor, weight_bits):\n        self.bfactor = bfactor\n        self.cfactor = cfactor\n        self.weight_bits = weight_bits\n        self.start_pack = False\n        # Cache Operator the algorithm matches against.\n        self.bitpack_start = op.op.get(\"annotation.bitpack_start\")\n        self.bitpack_end = op.op.get(\"annotation.bitpack_end\")\n        self.conv2d = op.op.get(\"nn.conv2d\")\n        self.conv2d_transpose = op.op.get(\"nn.conv2d_transpose\")\n        self.add = op.op.get(\"add\")\n        self.multiply = op.op.get(\"multiply\")\n        self.bias_add = op.op.get(\"nn.bias_add\")\n        self.pad = op.op.get(\"nn.pad\")\n        self.upsampling = op.op.get(\"nn.upsampling\")\n        self.reshape = op.op.get(\"reshape\")\n        self.number_of_conv2d = 0\n        self.unpack_transpose = True\n        super().__init__()\n\n    def visit_call(self, call):\n        \"\"\"Visit the children.\"\"\"\n        # First visit the children.\n        oshape = _get_tensor_shape(call)\n        odtype = _get_tensor_type(call)\n        input_types = [arg.checked_type for arg in call.args]\n        args = [self.visit(arg) for arg in call.args]\n\n        # Start and stop cases.\n        if call.op == self.bitpack_start:\n            assert not self.start_pack\n            self.start_pack = True\n            return _pack_batch_channel(args[0], oshape, self.bfactor, self.cfactor)\n        if call.op == self.bitpack_end:\n            if self.start_pack:\n                self.start_pack = False\n                data = args[0]\n                data_shape = _get_tensor_shape(call.args[0])\n                return _unpack_batch_channel(data, data_shape, self.unpack_transpose)\n        if self.start_pack:\n            # Operator cases\n            if call.op == self.conv2d and odtype == \"int32\":\n                self.number_of_conv2d += 1\n                assert 8 % self.weight_bits == 0\n                w_lanes = 8 // self.weight_bits\n                data_layout = \"NCHW%dn%dc\" % (self.bfactor, self.cfactor)\n                kernel_layout = \"OIHW%do%di\" % (self.cfactor, self.cfactor)\n                data, weight = args\n                data_shape = _to_shape(input_types[0].shape)\n                kernel_shape = _to_shape(input_types[1].shape)\n                channels = call.attrs.channels\n                weight, kernel_shape, channels = _weight_shape_match(\n                    weight, kernel_shape, channels, self.cfactor\n                )\n                kernel = _pack_weight(weight, kernel_shape, self.cfactor)\n                # insert bit packing when necessary\n                if w_lanes != 1:\n                    assert 8 % w_lanes == 0\n                    kernel = op.bitpack(kernel, lanes=w_lanes)\n\n                conv2d = op.nn.conv2d(\n                    data,\n                    kernel,\n                    strides=call.attrs.strides,\n                    padding=call.attrs.padding,\n                    dilation=call.attrs.dilation,\n                    groups=call.attrs.groups,\n                    channels=channels,\n                    kernel_size=call.attrs.kernel_size,\n                    data_layout=data_layout,\n                    kernel_layout=kernel_layout,\n                    out_dtype=call.attrs.out_dtype,\n                )\n                return conv2d\n\n            if call.op == self.conv2d_transpose and odtype == \"int32\":\n                self.number_of_conv2d += 1\n                assert 8 % self.weight_bits == 0\n                w_lanes = 8 // self.weight_bits\n                if self.start_pack:\n                    data_layout = \"NCHW%dn%dc\" % (self.bfactor, self.cfactor)\n                    kernel_layout = \"IOHW%di%do\" % (self.cfactor, self.cfactor)\n                    data, weight = args\n                    data_shape = _to_shape(input_types[0].shape)\n                    kernel_shape = _to_shape(input_types[1].shape)\n                    channels = call.attrs.channels\n                    weight, kernel_shape, channels = _weight_shape_match_transpose(\n                        weight, kernel_shape, channels, self.cfactor\n                    )\n                    kernel = _pack_weight_conv2d_transpose(weight, kernel_shape, self.cfactor)\n                    conv2d = op.nn.conv2d_transpose(\n                        data,\n                        kernel,\n                        strides=call.attrs.strides,\n                        padding=call.attrs.padding,\n                        dilation=call.attrs.dilation,\n                        groups=call.attrs.groups,\n                        channels=call.attrs.channels,\n                        kernel_size=call.attrs.kernel_size,\n                        data_layout=data_layout,\n                        kernel_layout=kernel_layout,\n                        output_padding=call.attrs.output_padding,\n                        out_dtype=call.attrs.out_dtype,\n                    )\n                return conv2d\n            if call.op == self.add and tuple(input_types[0].shape) == tuple(input_types[1].shape):\n                pass\n            elif call.op == self.add and len(input_types[1].shape) == 3:\n                data, const = args\n                const, input_shape = _const_shape_match(const, input_types[1].shape, self.cfactor)\n                const = _pack_const(\n                    const, _to_shape(input_shape), input_types[1].dtype, self.bfactor, self.cfactor\n                )\n                return relay.Call(self.add, [data, const])\n            elif call.op == self.multiply and tuple(input_types[0].shape) == tuple(\n                input_types[1].shape\n            ):\n                pass\n            elif call.op == self.multiply and len(input_types[1].shape) == 3:\n                data, const = args\n                const = _pack_const(\n                    const,\n                    _to_shape(input_types[1].shape),\n                    input_types[1].dtype,\n                    self.bfactor,\n                    self.cfactor,\n                )\n                return relay.Call(self.multiply, [data, const])\n            elif self.start_pack and call.op == self.bias_add:\n                data, bias = args\n                bias = _pack_const(\n                    bias,\n                    _to_shape(input_types[1].shape),\n                    input_types[1].dtype,\n                    self.bfactor,\n                    self.cfactor,\n                )\n                return relay.Call(self.add, [data, bias])\n            elif (\n                self.start_pack and call.op == op.op.get(\"cast\") and input_types[0].dtype == \"int32\"\n            ):\n                cast = relay.Call(op.op.get(\"cast\"), [args[0]], call.attrs)\n                return cast\n            elif call.op == self.pad:\n                pad_width = call.attrs.pad_width\n                if len(pad_width) == 6:\n                    pass\n                elif len(pad_width) == 4:\n                    (data, pad_value) = args\n                    new_pad_width = []\n                    new_pad_width.extend(pad_width)\n                    for _ in range(2):\n                        new_pad_width.append([0, 0])\n                    return op.nn.pad(data, pad_value=pad_value, pad_width=new_pad_width)\n            elif call.op == self.upsampling:\n                (data,) = args\n                scale_h = call.attrs.scale_h\n                scale_w = call.attrs.scale_w\n                data_layout = \"NCHW%dn%dc\" % (self.bfactor, self.cfactor)\n                method = call.attrs.method\n                align_corners = call.attrs.align_corners\n                return op.nn.upsampling(data, scale_h, scale_w, data_layout, method, align_corners)\n            elif call.op == self.reshape and len(input_types[0].shape) == 4:\n                (data,) = args\n                self.unpack_transpose = False\n                data = op.transpose(data, axes=(0, 4, 1, 5, 2, 3))\n                new_shape = [int(x) for x in input_types[0].shape]\n                # Check if the reshape match with such shape after pad\n                pad, new_shape[1] = _channel_const_match(new_shape[1], self.cfactor)\n                data = op.reshape(data, new_shape)\n                # remove pad data\n                if pad != 0:\n                    new_pad_width = [[0, 0], [0, -pad], [0, 0], [0, 0]]\n                    data = op.nn.pad(data, pad_width=new_pad_width)\n                return data\n\n        return relay.Call(self.visit(call.op), args, call.attrs)\n\n\nclass BT(Exception):\n    pass\n\n\ndef get_subgraph(expr, start_name, stop_name, start_name_idx, stop_name_idx, count_meta):\n    \"\"\"We assume stop_name only appears once for simplicity.\n    This constraint will be lifted in the future.\n    bitpack_start and bitpack_end are both inclusive.\n    \"\"\"\n    bitpack_start = op.op.get(\"annotation.bitpack_start\")\n    bitpack_end = op.op.get(\"annotation.bitpack_end\")\n    anf = run_opt_pass(expr, transform.ToANormalForm())\n    operator_current_idx = 0\n\n    def _recursion(anf, start_found, stop_found, operator_current_idx):\n        \"\"\"Helper to obtain the subgraph.\"\"\"\n        if isinstance(anf, relay.Function):\n            return relay.Function(\n                anf.params,\n                _recursion(anf.body, start_found, stop_found, operator_current_idx),\n                anf.ret_type,\n                anf.type_params,\n                anf.attrs,\n            )\n        if isinstance(anf, relay.expr.Let):\n            value = anf.value\n            if isinstance(value, relay.expr.Call):\n                if isinstance(value.op, tvm.ir.Op):\n                    if value.op.name == start_name and not start_found:\n                        if operator_current_idx == start_name_idx or start_name_idx is None:\n                            value = relay.expr.Call(bitpack_start, [value])\n                            start_found = True\n                    elif value.op.name == stop_name:\n                        if operator_current_idx == stop_name_idx or stop_name_idx is None:\n                            raise BT()\n\n            operator_current_idx = _operator_idx_inc(value, count_meta, operator_current_idx)\n\n            try:\n                return relay.expr.Let(\n                    anf.var,\n                    value,\n                    _recursion(anf.body, start_found, stop_found, operator_current_idx),\n                )\n            except BT:\n                assert start_found\n                assert not stop_found\n                stop_found = True\n                value = relay.expr.Call(bitpack_end, [value])\n                # todo: check anf.body has no more stop_name beside that one\n                return relay.expr.Let(anf.var, value, anf.body)\n        else:\n            assert start_found\n            assert stop_found\n            return anf\n\n    annotated = _recursion(anf, False, False, operator_current_idx)\n    return run_opt_pass(annotated, transform.ToGraphNormalForm())\n\n\ndef graph_pack(\n    expr,\n    bfactor,\n    cfactor,\n    weight_bits,\n    start_name=\"nn.max_pool2d\",\n    stop_name=\"nn.global_avg_pool2d\",\n    start_name_idx=None,\n    stop_name_idx=None,\n    count_meta=False,\n    device_annot=False,\n    annot_start_name=\"nn.conv2d\",\n    annot_end_name=\"annotation.stop_fusion\",\n):\n    \"\"\"Pack the graph into batch&channel packed format.\n\n    Parameters\n    ----------\n    expr : relay.Expr\n       The input program.\n\n    bfactor : int\n       The packing factor in batch\n\n    cfactor : int\n       The packing factor in channel\n\n    weight_bits: int\n        The bit-width of the weights.\n\n    start_name: str, optional\n       Start packing from certain known node when start_name_idx is None.\n\n    stop_name: str, optional\n       Stop packing from certain known node when stop_name_idx is None.\n\n    start_name_idx: int, optional\n        When start_name_idx not None, start packing only when node name equal start_name\n        and node idx equals start_name_idx.\n\n    stop_name_idx: int, optional\n        When stop_name_idx not None, stop packing only when node name equal stop_name\n        and node index equals stop_name_idx.\n\n    count_meta:boolean, optional\n        When count_meta is False, the operator increase logic would not count the meta that have\n        the type 'relay.expr.Constant', start_name_idx and stop_name_idx follow the index from\n        'expr.astext(show_meta_data=False)'. When count_meta is True, the operator increase\n        logic would count the meta.\n\n    device_annot: boolean, optional\n        if we want to annoate the device_type\n\n    annot_start_name: str, optional\n        device annotation start node, from which we mark the nodes as `ext_dev`\n\n    annot_end_name: str, optional\n        device annotation end node, after which we mark the nodes as 'cpu'\n\n    Returns\n    -------\n    expr : Expr\n        The transformed expression.\n    \"\"\"\n    assert isinstance(expr, relay.Function)\n    assert (\n        (start_name != stop_name)\n        or (start_name_idx is None != stop_name_idx is None)\n        or (not (start_name_idx is None and stop_name_idx is None))\n        or (start_name_idx < stop_name_idx)\n    )\n    expr = get_subgraph(expr, start_name, stop_name, start_name_idx, stop_name_idx, count_meta)\n    expr = run_opt_pass(expr, transform.InferType())\n    packer = ExprPack(bfactor, cfactor, weight_bits)\n    expr = packer.visit(expr)\n    assert not packer.start_pack\n    expr = run_opt_pass(expr, transform.InferType())\n\n    if device_annot:\n        expr_locator = ExprLocator()\n        expr_locator.visit(expr)\n\n        annot_start = op.op.get(annot_start_name)\n        start = expr_locator.op2nodes[(annot_start, \"int32\")][0]\n\n        annot_end = op.op.get(annot_end_name)\n        # we mark the next op to the last stop_fusion on cpu device\n        end = expr_locator.op2nodes[(annot_end, \"int8\")][-1] + 1\n\n        device_annot = ExprDeviceAnnot(start=start, end=end)\n        expr = device_annot.visit(expr)\n        return run_opt_pass(expr, transform.InferType())\n\n    return expr\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/op.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, ungrouped-imports\n\"\"\"Namespace for supporting Relay operators on VTA.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\n\nfrom tvm.relay.op import op as reg\nfrom tvm.relay.op import strategy as _strategy\nfrom tvm.relay.op.op import OpPattern, OpStrategy\n\nfrom .utils import is_packed_layout\nfrom .vta_conv2d import conv2d_packed, schedule_conv2d_packed\nfrom .vta_conv2d_transpose import conv2d_transpose_packed, schedule_conv2d_transpose_packed\nfrom .vta_group_conv2d import group_conv2d_packed, schedule_group_conv2d_packed\nfrom .vta_dense import dense_packed, schedule_dense_packed\nfrom ..environment import get_env\n\nENV = get_env()\n\n# override to force partition at copy\nreg.register_pattern(\"copy\", OpPattern.INJECTIVE, level=15)\n\n# add clip vta strategy\ndef compute_clip_vta(attrs, inputs, output_type):\n    \"\"\"Clip operator.\"\"\"\n    x = inputs[0]\n    a_min = attrs.a_min\n    a_max = attrs.a_max\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    with tvm.te.tag_scope(topi.tag.ELEMWISE):\n        x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n        x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return [x]\n\n\ndef clip_strategy_vta(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        compute_clip_vta,\n        _strategy.wrap_topi_schedule(topi.generic.schedule_injective),\n        name=\"clip.vta\",\n    )\n    return strategy\n\n\nreg.get(\"clip\").get_attr(\"FTVMStrategy\").register(clip_strategy_vta, \"vta\")\n\n\n@autotvm.register_topi_compute(\"add.vta\")\ndef add_packed(cfg, lhs, rhs):\n    return topi.add(lhs, rhs)\n\n\n@autotvm.register_topi_compute(\"multiply.vta\")\ndef multiply_packed(cfg, lhs, rhs):\n    return topi.multiply(lhs, rhs)\n\n\ndef schedule_alu_packed(cfg, outs):\n    \"\"\"alu packed schedule\"\"\"\n    assert len(outs) == 1\n\n    def is_cast_op(op):\n        return op.name == \"T_cast\"\n\n    outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs\n    output = outs[0]\n    s = te.create_schedule([x.op for x in outs])\n    te.schedule.AutoInlineInjective(s)\n\n    # other target does not support alu-only ops\n    if not (ENV.TARGET in [\"sim\", \"tsim\", \"intelfocl\"]):\n        return s\n\n    # only put the int-related ops to vta\n    if \"int\" in output.dtype and len(output.shape) == 6:\n        ewise_inputs = []\n        ewise_ops = []\n        const_ops = []\n\n        def _traverse(op):\n            if topi.tag.is_broadcast(op.tag):\n                if not op.same_as(output.op):\n                    if not op.axis:\n                        const_ops.append(op)\n                    elif not is_cast_op(op):\n                        ewise_ops.append(op)\n\n                for tensor in op.input_tensors:\n                    if isinstance(tensor.op, tvm.te.PlaceholderOp):\n                        ewise_inputs.append((op, tensor))\n                    elif is_cast_op(tensor.op) and not op.same_as(output.op):\n                        ewise_inputs.append((op, tensor))\n                    else:\n                        _traverse(tensor.op)\n            else:\n                for tensor in op.input_tensors:\n                    if (not isinstance(tensor.op, tvm.te.PlaceholderOp)) and (\n                        not is_cast_op(tensor.op)\n                    ):\n                        _traverse(tensor.op)\n\n        op = output.op\n        _traverse(op)\n        for _, t in ewise_inputs:\n            if t.dtype == \"float32\":\n                return s\n\n        x_bo, x_co, x_i, x_j, x_bi, x_ci = s[output].op.axis\n\n        cfg.define_split(\"tile_co\", x_co, num_outputs=2)\n        cfg.define_split(\"tile_h\", x_i, num_outputs=2)\n        cfg.define_split(\"tile_w\", x_j, num_outputs=2)\n\n        x_co0, x_co1 = cfg[\"tile_co\"].apply(s, output, x_co)\n        x_i0, x_i1 = cfg[\"tile_h\"].apply(s, output, x_i)\n        x_j0, x_j1 = cfg[\"tile_w\"].apply(s, output, x_j)\n        s[output].reorder(x_bo, x_i0, x_co0, x_j0, x_co1, x_i1, x_j1, x_bi, x_ci)\n        store_pt = x_j0\n\n        for e_o in ewise_ops:\n            s[e_o].set_scope(ENV.acc_scope)\n            s[e_o].pragma(s[e_o].op.axis[0], ENV.alu)\n            s[e_o].compute_at(s[output], store_pt)\n\n        # cache read input\n        cache_read_ewise = []\n        for consumer, tensor in ewise_inputs:\n            cache_read_ewise.append(s.cache_read(tensor, ENV.acc_scope, [consumer]))\n\n        for tensor in cache_read_ewise:\n            if s[tensor].op.axis:\n                s[tensor].pragma(s[tensor].op.axis[0], ENV.dma_copy)\n            s[tensor].compute_at(s[output], store_pt)\n\n        for op in const_ops:\n            s[op].compute_inline()\n\n        s[output].pragma(x_co1, ENV.dma_copy)\n\n    return s\n\n\n@autotvm.register_topi_schedule(\"add.vta\")\ndef schedule_add_packed(cfg, outs):\n    return schedule_alu_packed(cfg, outs)\n\n\n@autotvm.register_topi_schedule(\"multiply.vta\")\ndef schedule_multiply_packed(cfg, outs):\n    return schedule_alu_packed(cfg, outs)\n\n\ndef add_strategy_vta(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        _strategy.wrap_topi_compute(add_packed),\n        _strategy.wrap_topi_schedule(schedule_add_packed),\n        name=\"add.vta\",\n    )\n    return strategy\n\n\ndef multiply_strategy_vta(attrs, inputs, out_type, target):\n    strategy = OpStrategy()\n    strategy.add_implementation(\n        _strategy.wrap_topi_compute(multiply_packed),\n        _strategy.wrap_topi_schedule(schedule_multiply_packed),\n        name=\"multiply.vta\",\n    )\n    return strategy\n\n\n# other target does not support alu-only ops\nif ENV.TARGET in [\"sim\", \"intelfocl\"]:\n    reg.get(\"add\").get_attr(\"FTVMStrategy\").register(add_strategy_vta, \"vta\")\n    reg.get(\"multiply\").get_attr(\"FTVMStrategy\").register(multiply_strategy_vta, \"vta\")\n\n\n@_strategy.conv2d_strategy.register(\"vta\")\ndef conv2d_strategy_vta(attrs, inputs, out_type, target):\n    \"\"\"conv2d vta strategy\"\"\"\n    strategy = OpStrategy()\n    kernel = inputs[1]\n    dilation = topi.utils.get_const_tuple(attrs.dilation)\n    groups = attrs.groups\n    layout = attrs.data_layout\n\n    assert dilation == (1, 1), \"support for dilation limited to (1, 1)\"\n    if is_packed_layout(layout):\n        if groups == 1:\n            assert ENV.LOG_INP_WIDTH == 3, \"only support 8bit inp for now\"\n            assert ENV.LOG_WGT_WIDTH == 3, \"only support 8bit wgt for now\"\n            assert kernel.dtype == \"int8\"\n\n            strategy.add_implementation(\n                _strategy.wrap_compute_conv2d(conv2d_packed, need_data_layout=True),\n                _strategy.wrap_topi_schedule(schedule_conv2d_packed),\n                name=\"conv2d_packed.vta\",\n            )\n        else:  # group_conv2d\n            strategy.add_implementation(\n                _strategy.wrap_compute_conv2d(group_conv2d_packed, has_groups=True),\n                _strategy.wrap_topi_schedule(schedule_group_conv2d_packed),\n                name=\"group_conv2d_packed.vta\",\n            )\n        return strategy\n\n    # If it's not packed, run on ARM CPU\n    arm_tgt = tvm.target.arm_cpu(target.model)\n    return _strategy.arm_cpu.conv2d_strategy_arm_cpu(attrs, inputs, out_type, arm_tgt)\n\n\n@_strategy.conv2d_transpose_strategy.register(\"vta\")\ndef conv2d_transpose_strategy_vta(attrs, inputs, out_type, target):\n    \"\"\"conv2d_transpose vta strategy\"\"\"\n    dilation = topi.utils.get_const_tuple(attrs.dilation)\n    layout = attrs.data_layout\n    assert dilation == (1, 1), \"support for dilation limited to (1, 1)\"\n\n    if is_packed_layout(layout):\n        strategy = OpStrategy()\n        strategy.add_implementation(\n            _strategy.wrap_compute_conv2d_transpose(conv2d_transpose_packed),\n            _strategy.wrap_topi_schedule(schedule_conv2d_transpose_packed),\n            name=\"conv2d_transpose_packed.vta\",\n        )\n        return strategy\n\n    # If it's not packed, run on ARM CPU\n    arm_tgt = tvm.target.arm_cpu(target.model)\n    return _strategy.arm_cpu.conv2d_transpose_strategy_arm_cpu(attrs, inputs, out_type, arm_tgt)\n\n\n@_strategy.dense_strategy.register(\"vta\")\ndef dense_strategy_vta(attrs, inputs, out_type, target):\n    \"\"\"dense vta strategy\"\"\"\n    if len(inputs[0].shape) == 4:  # this implies the layout is packed\n        strategy = OpStrategy()\n        strategy.add_implementation(\n            _strategy.wrap_compute_dense(dense_packed),\n            _strategy.wrap_topi_schedule(schedule_dense_packed),\n            name=\"dense_packed.vta\",\n        )\n        return strategy\n    # If it's not packed, run on ARM CPU\n    arm_tgt = tvm.target.arm_cpu(target.model)\n    return _strategy.x86.dense_strategy_cpu(attrs, inputs, out_type, arm_tgt)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/utils.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"VTA TOPI Utils.\"\"\"\n\n\ndef is_packed_layout(layout):\n    \"\"\"Check if layout is packed layout\"\"\"\n    if layout == \"NCHW\":\n        return False\n    if \"n\" in layout and \"c\" in layout:\n        return True\n    return False\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/vta_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Conv2D operator declaration and schedule registration for VTA.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\n\nfrom .utils import is_packed_layout\nfrom ..environment import get_env\n\n\n@autotvm.register_topi_compute(\"conv2d_packed.vta\")\ndef conv2d_packed(cfg, data, kernel, strides, padding, dilation, layout, out_dtype):\n    \"\"\"Packed conv2d function.\"\"\"\n    if not is_packed_layout(layout):\n        raise topi.InvalidShapeError()\n    assert dilation == (1, 1)\n\n    if padding[0]:\n        pad_data = topi.nn.pad(data, [0, 0, padding[0], padding[1], 0, 0], name=\"pad_data\")\n    else:\n        pad_data = data\n    assert len(data.shape) == 6\n    assert len(kernel.shape) == 6\n    oheight = topi.utils.get_const_int((pad_data.shape[2] - kernel.shape[2]) // strides[0] + 1)\n    owidth = topi.utils.get_const_int((pad_data.shape[3] - kernel.shape[3]) // strides[1] + 1)\n    oshape = (data.shape[0], kernel.shape[0], oheight, owidth, data.shape[4], kernel.shape[4])\n\n    ishape = topi.utils.get_const_tuple(data.shape)\n    kshape = topi.utils.get_const_tuple(kernel.shape)\n    d_i = te.reduce_axis((0, kshape[2]), name=\"d_i\")\n    d_j = te.reduce_axis((0, kshape[3]), name=\"d_j\")\n    k_o = te.reduce_axis((0, ishape[1]), name=\"k_o\")\n    k_i = te.reduce_axis((0, ishape[-1]), name=\"k_i\")\n    hstride, wstride = strides\n    res = te.compute(\n        oshape,\n        lambda b_o, c_o, i, j, b_i, c_i: te.sum(\n            pad_data[b_o, k_o, i * hstride + d_i, j * wstride + d_j, b_i, k_i].astype(out_dtype)\n            * kernel[c_o, k_o, d_i, d_j, c_i, k_i].astype(out_dtype),\n            axis=[k_o, d_i, d_j, k_i],\n        ),\n        name=\"res\",\n        tag=\"conv2d_dense\",\n    )\n\n    cfg.add_flop(\n        2\n        * np.prod(topi.utils.get_const_tuple(oshape))\n        * kshape[2]\n        * kshape[3]\n        * ishape[1]\n        * ishape[-1]\n    )\n\n    return res\n\n\n@autotvm.register_topi_schedule(\"conv2d_packed.vta\")\ndef schedule_conv2d_packed(cfg, outs):\n    \"\"\"Schedule packed conv2d\"\"\"\n    assert len(outs) == 1\n    output = outs[0]\n    const_ops = []\n    ewise_inputs = []\n    ewise_ops = []\n    conv2d_res = []\n    assert \"int\" in output.op.input_tensors[0].dtype\n\n    def _traverse(op):\n        if topi.tag.is_broadcast(op.tag):\n            if not op.same_as(output.op):\n                if not op.axis:\n                    const_ops.append(op)\n                else:\n                    ewise_ops.append(op)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.PlaceholderOp):\n                    ewise_inputs.append((op, tensor))\n                else:\n                    _traverse(tensor.op)\n        else:\n            assert op.tag == \"conv2d_dense\"\n            conv2d_res.append(op)\n\n    _traverse(output.op)\n    assert len(conv2d_res) == 1\n    conv2d_stage = conv2d_res[0].output(0)\n    s = te.create_schedule(output.op)\n\n    ##### space definition begin #####\n    b, c_o, x_i, x_j, _, _ = s[conv2d_stage].op.axis\n    c_i, _, _, _ = s[conv2d_stage].op.reduce_axis\n    cfg.define_split(\"tile_b\", b, num_outputs=2)\n    cfg.define_split(\"tile_h\", x_i, num_outputs=2)\n    cfg.define_split(\"tile_w\", x_j, num_outputs=2)\n    cfg.define_split(\"tile_ci\", c_i, num_outputs=2)\n    cfg.define_split(\"tile_co\", c_o, num_outputs=2)\n    cfg.define_knob(\"oc_nthread\", [1, 2])\n    cfg.define_knob(\"h_nthread\", [1, 2])\n    ###### space definition end ######\n\n    data, kernel = conv2d_stage.op.input_tensors\n    if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n        temp = data.op.input_tensors[0]\n        pad_data = data\n        data = temp\n    else:\n        pad_data = None\n\n    env = get_env()\n\n    # setup pad\n    if pad_data is not None:\n        cdata = pad_data\n        s[pad_data].set_scope(env.inp_scope)\n    else:\n        cdata = s.cache_read(data, env.inp_scope, [conv2d_stage])\n    ckernel = s.cache_read(kernel, env.wgt_scope, [conv2d_stage])\n    s[conv2d_stage].set_scope(env.acc_scope)\n\n    # cache read input\n    cache_read_ewise = []\n    for consumer, tensor in ewise_inputs:\n        cache_read_ewise.append(s.cache_read(tensor, env.acc_scope, [consumer]))\n\n    # set ewise scope\n    for op in ewise_ops:\n        s[op].set_scope(env.acc_scope)\n        s[op].pragma(s[op].op.axis[0], env.alu)\n\n    for op in const_ops:\n        s[op].compute_inline()\n\n    # tile\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[output].op.axis\n    x_co0, x_co1 = cfg[\"tile_co\"].apply(s, output, x_co)\n    x_i0, x_i1 = cfg[\"tile_h\"].apply(s, output, x_i)\n    x_j0, x_j1 = cfg[\"tile_w\"].apply(s, output, x_j)\n    s[output].reorder(x_bo, x_i0, x_co0, x_j0, x_co1, x_i1, x_j1, x_bi, x_ci)\n    store_pt = x_j0\n\n    # set all compute scopes\n    s[conv2d_stage].compute_at(s[output], store_pt)\n    for op in ewise_ops:\n        s[op].compute_at(s[output], store_pt)\n\n    for tensor in cache_read_ewise:\n        s[tensor].compute_at(s[output], store_pt)\n        s[tensor].pragma(s[tensor].op.axis[0], env.dma_copy)\n\n    # virtual threading along output channel axes\n    if cfg[\"oc_nthread\"].val > 1:\n        _, v_t = s[output].split(x_co0, factor=cfg[\"oc_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    # virtual threading along spatial rows\n    if cfg[\"h_nthread\"].val > 1:\n        _, v_t = s[output].split(x_i0, factor=cfg[\"h_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[conv2d_stage].op.axis\n    k_o, d_i, d_j, k_i = s[conv2d_stage].op.reduce_axis\n    s[conv2d_stage].reorder(x_bo, k_o, x_j, d_j, d_i, x_co, x_i, x_bi, x_ci, k_i)\n\n    k_o, _ = cfg[\"tile_ci\"].apply(s, conv2d_stage, k_o)\n    s[cdata].compute_at(s[conv2d_stage], k_o)\n    s[ckernel].compute_at(s[conv2d_stage], k_o)\n\n    # Use VTA instructions\n    s[cdata].pragma(s[cdata].op.axis[0], env.dma_copy)\n    s[ckernel].pragma(s[ckernel].op.axis[0], env.dma_copy)\n    s[conv2d_stage].tensorize(x_bi, env.gemm)\n    s[output].pragma(x_co1, env.dma_copy)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/vta_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Conv2D_transpose operator declaration and schedule registration for VTA.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nfrom tvm.topi.utils import get_const_tuple\nfrom tvm.topi.nn.utils import get_pad_tuple\n\nfrom ..environment import get_env\n\n\n@autotvm.register_topi_compute(\"conv2d_transpose_packed.vta\")\ndef conv2d_transpose_packed(cfg, data, kernel, strides, padding, out_dtype, output_padding=(0, 0)):\n    \"\"\"Packed conv2d_transpose compute\"\"\"\n    ishape = get_const_tuple(data.shape)\n    kshape = get_const_tuple(kernel.shape)\n    b, c_i, i_h, i_w, t_b, t_ci = ishape\n    c_o, _, k_h, k_w, t_co, t_ci = kshape\n    stride_h, stride_w = strides\n    opad_h, opad_w = output_padding\n    # FIXME(tmoreau89): currently IR pass breaks when output padding != (0,0)\n    assert opad_h == 0 and opad_w == 0, \"VTA does not support output padding for now\"\n\n    # derive padding parameters\n    fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (k_h, k_w))\n    bpad_top = k_h - 1 - fpad_top\n    bpad_bottom = k_h - 1 - fpad_bottom + opad_h\n    bpad_left = k_w - 1 - fpad_left\n    bpad_right = k_w - 1 - fpad_right + opad_w\n\n    # padding stage\n    dilated_input = topi.nn.dilate(data, [1, 1, stride_h, stride_w, 1, 1])\n    data_pad = topi.nn.pad(\n        dilated_input, [0, 0, bpad_top, bpad_left, 0, 0], [0, 0, bpad_bottom, bpad_right, 0, 0]\n    )\n\n    # convolution transpose stage\n    out_h = (i_h - 1) * stride_h - fpad_top - fpad_bottom + k_h + opad_h\n    out_w = (i_w - 1) * stride_w - fpad_left - fpad_right + k_w + opad_w\n    oshape = (b, c_o, out_h, out_w, t_b, t_co)\n    d_c = te.reduce_axis((0, c_i), name=\"d_c\")\n    d_h = te.reduce_axis((0, k_h), name=\"d_h\")\n    d_w = te.reduce_axis((0, k_w), name=\"d_w\")\n    d_ci = te.reduce_axis((0, t_ci), name=\"d_ci\")\n\n    out = te.compute(\n        oshape,\n        lambda i_n, i_c, i_h, i_w, j_n, j_c: te.sum(\n            data_pad(i_n, d_c, i_h + d_h, i_w + d_w, j_n, d_ci).astype(out_dtype)\n            * kernel[i_c, d_c, d_h, d_w, j_c, d_ci].astype(out_dtype),\n            axis=[d_c, d_h, d_w, d_ci],\n        ),\n        tag=\"packed_conv2d_transpose\",\n        name=\"res\",\n    )\n\n    cfg.add_flop(\n        2\n        * np.prod(topi.utils.get_const_tuple(oshape))\n        * kshape[2]\n        * kshape[3]\n        * ishape[1]\n        * ishape[-1]\n    )\n\n    return out\n\n\n@autotvm.register_topi_schedule(\"conv2d_transpose_packed.vta\")\ndef schedule_conv2d_transpose_packed(cfg, outs):\n    \"\"\"Schedule packed conv2d_transpose\"\"\"\n    assert len(outs) == 1\n    output = outs[0]\n    ewise_inputs = []\n    ewise_ops = []\n    conv2d_res = []\n    assert output.dtype == \"int8\"\n    assert output.op.input_tensors[0].dtype == \"int32\"\n\n    def _traverse(op):\n        if topi.tag.is_broadcast(op.tag):\n            if not op.same_as(output.op):\n                ewise_ops.append(op)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.PlaceholderOp):\n                    ewise_inputs.append((op, tensor))\n                else:\n                    _traverse(tensor.op)\n        else:\n            assert op.tag == \"packed_conv2d_transpose\"\n            conv2d_res.append(op)\n\n    _traverse(output.op)\n    assert len(conv2d_res) == 1\n    conv2d_stage = conv2d_res[0].output(0)\n    s = te.create_schedule(output.op)\n\n    ##### space definition begin #####\n    b, c_o, x_i, x_j, _, c_i = s[conv2d_stage].op.axis\n    c_i, _, _, _ = s[conv2d_stage].op.reduce_axis\n    cfg.define_split(\"tile_b\", b, num_outputs=2)\n    cfg.define_split(\"tile_h\", x_i, num_outputs=2)\n    cfg.define_split(\"tile_w\", x_j, num_outputs=2)\n    cfg.define_split(\"tile_ci\", c_i, num_outputs=2)\n    cfg.define_split(\"tile_co\", c_o, num_outputs=2)\n    cfg.define_knob(\"oc_nthread\", [1, 2])\n    cfg.define_knob(\"h_nthread\", [1, 2])\n    ###### space definition end ######\n\n    data, kernel = conv2d_stage.op.input_tensors\n    if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n        temp = data.op.input_tensors[0]\n        pad_data = data\n        data = temp\n    else:\n        pad_data = None\n\n    env = get_env()\n\n    # setup pad\n    if pad_data is not None:\n        cdata = pad_data\n        s[pad_data].set_scope(env.inp_scope)\n    else:\n        cdata = s.cache_read(data, env.inp_scope, [conv2d_stage])\n    ckernel = s.cache_read(kernel, env.wgt_scope, [conv2d_stage])\n    s[conv2d_stage].set_scope(env.acc_scope)\n\n    # cache read input\n    cache_read_ewise = []\n    for consumer, tensor in ewise_inputs:\n        cache_read_ewise.append(s.cache_read(tensor, env.acc_scope, [consumer]))\n    # set ewise scope\n    for op in ewise_ops:\n        s[op].set_scope(env.acc_scope)\n        s[op].pragma(s[op].op.axis[0], env.alu)\n\n    # tile\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[output].op.axis\n    x_co0, x_co1 = cfg[\"tile_co\"].apply(s, output, x_co)\n    x_i0, x_i1 = cfg[\"tile_h\"].apply(s, output, x_i)\n    x_j0, x_j1 = cfg[\"tile_w\"].apply(s, output, x_j)\n    s[output].reorder(x_bo, x_i0, x_co0, x_j0, x_co1, x_i1, x_j1, x_bi, x_ci)\n    store_pt = x_j0\n\n    # set all compute scopes\n    s[conv2d_stage].compute_at(s[output], store_pt)\n    for op in ewise_ops:\n        s[op].compute_at(s[output], store_pt)\n\n    for tensor in cache_read_ewise:\n        s[tensor].compute_at(s[output], store_pt)\n        s[tensor].pragma(s[tensor].op.axis[0], env.dma_copy)\n\n    # virtual threading along output channel axes\n    if cfg[\"oc_nthread\"].val > 1:\n        _, v_t = s[output].split(x_co0, factor=cfg[\"oc_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    # virtual threading along spatial rows\n    if cfg[\"h_nthread\"].val > 1:\n        _, v_t = s[output].split(x_i0, factor=cfg[\"h_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[conv2d_stage].op.axis\n    k_o, d_i, d_j, k_i = s[conv2d_stage].op.reduce_axis\n    x_i, x_ii = s[conv2d_stage].split(x_i, 4)\n    x_j, x_jj = s[conv2d_stage].split(x_j, 2)\n    s[conv2d_stage].reorder(x_bo, k_o, x_j, x_co, x_i, x_jj, d_j, d_i, x_ii, x_bi, x_ci, k_i)\n\n    for axis in [d_j, d_i, x_ii, x_jj]:\n        s[conv2d_stage].unroll(axis)\n\n    k_o, _ = cfg[\"tile_ci\"].apply(s, conv2d_stage, k_o)\n    s[cdata].compute_at(s[conv2d_stage], k_o)\n    s[ckernel].compute_at(s[conv2d_stage], k_o)\n\n    # Use VTA instructions\n    s[cdata].pragma(s[cdata].op.axis[0], env.dma_copy)\n    s[ckernel].pragma(s[ckernel].op.axis[0], env.dma_copy)\n    s[conv2d_stage].pragma(x_bi, \"conv2d_transpose_gemm\")\n    s[output].pragma(x_co1, env.dma_copy)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/vta_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument\n\"\"\"Dense operator declaration and schedule registration for VTA.\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\n\nfrom ..environment import get_env\n\n\ndef is_packed_layout(layout):\n    \"\"\"Check if layout is packed layout\"\"\"\n    if layout == \"NCHW\":\n        return False\n    if \"n\" in layout and \"c\" in layout:\n        return True\n    return False\n\n\n@autotvm.register_topi_compute(\"dense_packed.vta\")\ndef dense_packed(cfg, data, weight, bias=None, out_dtype=None):\n    \"\"\"Dense function declaration.\"\"\"\n\n    # Make sure that the dense operator is packed\n    if len(data.shape) != 4 or len(weight.shape) != 4:\n        raise topi.InvalidShapeError()\n\n    # Derive shapes\n    ishape = topi.utils.get_const_tuple(data.shape)\n    wshape = topi.utils.get_const_tuple(weight.shape)\n    oshape = (data.shape[0], weight.shape[0], data.shape[2], weight.shape[2])\n\n    # Reduction axes (input channel)\n    assert ishape[1] == wshape[1]\n    assert ishape[3] == wshape[3]\n    k_o = te.reduce_axis((0, ishape[1]), name=\"k_o\")\n    k_i = te.reduce_axis((0, ishape[3]), name=\"k_i\")\n    res = te.compute(\n        oshape,\n        lambda b_o, c_o, b_i, c_i: te.sum(\n            data[b_o, k_o, b_i, k_i].astype(out_dtype)\n            * weight[c_o, k_o, c_i, k_i].astype(out_dtype),\n            axis=[k_o, k_i],\n        ),\n        name=\"res\",\n        tag=\"dense_pack\",\n    )\n\n    cfg.add_flop(2 * np.prod(topi.utils.get_const_tuple(oshape)) * ishape[1] * ishape[3])\n\n    return res\n\n\n@autotvm.register_topi_schedule(\"dense_packed.vta\")\ndef schedule_dense_packed(cfg, outs):\n    \"\"\"Packed dense schedule.\"\"\"\n\n    assert len(outs) == 1\n    output = outs[0]\n    const_ops = []\n    ewise_inputs = []\n    ewise_ops = []\n    dense_res = []\n    assert \"int\" in output.op.input_tensors[0].dtype\n\n    def _traverse(op):\n        if topi.tag.is_broadcast(op.tag):\n            if not op.same_as(output.op):\n                if not op.axis:\n                    const_ops.append(op)\n                else:\n                    ewise_ops.append(op)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.PlaceholderOp):\n                    ewise_inputs.append((op, tensor))\n                else:\n                    _traverse(tensor.op)\n        else:\n            assert op.tag == \"dense_pack\"\n            dense_res.append(op)\n\n    _traverse(output.op)\n    assert len(dense_res) == 1\n    dense_stage = dense_res[0].output(0)\n    s = te.create_schedule(output.op)\n\n    ##### space definition begin #####\n    b, c_o, _, _ = s[dense_stage].op.axis\n    c_i, _ = s[dense_stage].op.reduce_axis\n    cfg.define_split(\"tile_b\", b, num_outputs=2)\n    cfg.define_split(\"tile_ci\", c_i, num_outputs=2)\n    cfg.define_split(\"tile_co\", c_o, num_outputs=2)\n    cfg.define_knob(\"oc_nthread\", [1, 2])\n    ###### space definition end ######\n\n    data, weight = dense_stage.op.input_tensors\n\n    env = get_env()\n\n    cdata = s.cache_read(data, env.inp_scope, [dense_stage])\n    cweight = s.cache_read(weight, env.wgt_scope, [dense_stage])\n    s[dense_stage].set_scope(env.acc_scope)\n\n    # cache read input\n    cache_read_ewise = []\n    for consumer, tensor in ewise_inputs:\n        cache_read_ewise.append(s.cache_read(tensor, env.acc_scope, [consumer]))\n\n    # set ewise scope\n    for op in ewise_ops:\n        s[op].set_scope(env.acc_scope)\n        s[op].pragma(s[op].op.axis[0], env.alu)\n\n    for op in const_ops:\n        s[op].compute_inline()\n\n    # apply tiling for SRAM reuse\n    x_b, x_c, _, _ = s[output].op.axis\n    x_bo, x_bi = cfg[\"tile_b\"].apply(s, output, x_b)\n    x_co, x_ci = cfg[\"tile_co\"].apply(s, output, x_c)\n    s[output].reorder(x_bo, x_co, x_bi, x_ci)\n    store_pt = x_co\n\n    # set all compute scopes\n    s[dense_stage].compute_at(s[output], store_pt)\n    for op in ewise_ops:\n        s[op].compute_at(s[output], store_pt)\n\n    for tensor in cache_read_ewise:\n        s[tensor].compute_at(s[output], store_pt)\n        s[tensor].pragma(s[tensor].op.axis[0], env.dma_copy)\n\n    # virtual threading along output channel axes\n    if cfg[\"oc_nthread\"].val > 1:\n        _, v_t = s[output].split(x_co, factor=cfg[\"oc_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    x_bo, x_co, x_bi, _ = s[dense_stage].op.axis\n    k_o, _ = s[dense_stage].op.reduce_axis\n    s[dense_stage].reorder(x_bo, k_o, x_co)\n\n    k_o, _ = cfg[\"tile_ci\"].apply(s, dense_stage, k_o)\n    s[cdata].compute_at(s[dense_stage], k_o)\n    s[cweight].compute_at(s[dense_stage], k_o)\n\n    # Use VTA instructions\n    s[cdata].pragma(s[cdata].op.axis[0], env.dma_copy)\n    s[cweight].pragma(s[cweight].op.axis[0], env.dma_copy)\n    s[dense_stage].tensorize(x_bi, env.gemm)\n    s[output].pragma(x_ci, env.dma_copy)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/top/vta_group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Group conv2D operator declaration and schedule registration for VTA.\"\"\"\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\n\nfrom ..environment import get_env\n\n\n@autotvm.register_topi_compute(\"group_conv2d_packed.vta\")\ndef group_conv2d_packed(cfg, data, kernel, strides, padding, dilation, group, out_dtype):\n    \"\"\"Packed group conv2d nchw function.\"\"\"\n    assert dilation == (1, 1)\n\n    if padding[0]:\n        pad_data = topi.nn.pad(data, [0, 0, padding[0], padding[1], 0, 0], name=\"pad_data\")\n    else:\n        pad_data = data\n    assert len(data.shape) == 6\n    assert len(kernel.shape) == 6\n    assert data.dtype == \"int8\", data.dtype\n    assert kernel.dtype == \"int8\", kernel.dtype\n    assert out_dtype == \"int32\", out_dtype\n\n    oheight = topi.utils.get_const_int((pad_data.shape[2] - kernel.shape[2]) // strides[0] + 1)\n    owidth = topi.utils.get_const_int((pad_data.shape[3] - kernel.shape[3]) // strides[1] + 1)\n    oshape = (data.shape[0], kernel.shape[0], oheight, owidth, data.shape[4], kernel.shape[4])\n\n    ishape = topi.utils.get_const_tuple(data.shape)\n    kshape = topi.utils.get_const_tuple(kernel.shape)\n    assert group * kshape[1] == ishape[1]\n    assert kshape[0] % group == 0\n    d_i = te.reduce_axis((0, kshape[2]), name=\"d_i\")\n    d_j = te.reduce_axis((0, kshape[3]), name=\"d_j\")\n    k_o = te.reduce_axis((0, kshape[1]), name=\"k_o\")\n    k_i = te.reduce_axis((0, kshape[-1]), name=\"k_i\")\n    hstride, wstride = strides\n    out = te.compute(\n        oshape,\n        lambda b_o, c_o, i, j, b_i, c_i: te.sum(\n            pad_data[\n                b_o,\n                c_o // (kshape[0] // group) * kshape[1] + k_o,\n                i * hstride + d_i,\n                j * wstride + d_j,\n                b_i,\n                k_i,\n            ].astype(out_dtype)\n            * kernel[c_o, k_o, d_i, d_j, c_i, k_i].astype(out_dtype),\n            axis=[k_o, d_i, d_j, k_i],\n        ),\n        name=\"res\",\n        tag=\"packed_group_conv2d\",\n    )\n\n    cfg.add_flop(\n        2\n        * np.prod(topi.utils.get_const_tuple(oshape))\n        * kshape[2]\n        * kshape[3]\n        * ishape[1]\n        * kshape[-1]\n    )\n\n    return out\n\n\n@autotvm.register_topi_schedule(\"group_conv2d_packed.vta\")\ndef schedule_group_conv2d_packed(cfg, outs):\n    \"\"\"Schedule the packed conv2d.\"\"\"\n    assert len(outs) == 1\n    output = outs[0]\n    const_ops = []\n    ewise_inputs = []\n    ewise_ops = []\n    conv2d_res = []\n    assert output.dtype == \"int8\"\n    assert output.op.input_tensors[0].dtype == \"int32\"\n\n    def _traverse(op):\n        if topi.tag.is_broadcast(op.tag):\n            if not op.same_as(output.op):\n                if not op.axis:\n                    const_ops.append(op)\n                else:\n                    ewise_ops.append(op)\n            for tensor in op.input_tensors:\n                if isinstance(tensor.op, tvm.te.PlaceholderOp):\n                    ewise_inputs.append((op, tensor))\n                else:\n                    _traverse(tensor.op)\n        else:\n            assert op.tag == \"packed_group_conv2d\"\n            conv2d_res.append(op)\n\n    _traverse(output.op)\n    assert len(conv2d_res) == 1\n    conv2d_stage = conv2d_res[0].output(0)\n    s = te.create_schedule(output.op)\n\n    ##### space definition begin #####\n    b, c_o, x_i, x_j, _, _ = s[conv2d_stage].op.axis\n    c_i, _, _, _ = s[conv2d_stage].op.reduce_axis\n    cfg.define_split(\"tile_b\", b, num_outputs=2)\n    cfg.define_split(\"tile_h\", x_i, num_outputs=2)\n    cfg.define_split(\"tile_w\", x_j, num_outputs=2)\n    cfg.define_split(\"tile_ci\", c_i, num_outputs=2)\n    cfg.define_split(\"tile_co\", c_o, num_outputs=2)\n    cfg.define_knob(\"oc_nthread\", [1, 2])\n    cfg.define_knob(\"h_nthread\", [1, 2])\n    ###### space definition end ######\n\n    data, kernel = conv2d_stage.op.input_tensors\n    if isinstance(data.op, tvm.te.ComputeOp) and \"pad\" in data.op.tag:\n        temp = data.op.input_tensors[0]\n        pad_data = data\n        data = temp\n    else:\n        pad_data = None\n\n    env = get_env()\n\n    # setup pad\n    if pad_data is not None:\n        cdata = pad_data\n        s[pad_data].set_scope(env.inp_scope)\n    else:\n        cdata = s.cache_read(data, env.inp_scope, [conv2d_stage])\n    ckernel = s.cache_read(kernel, env.wgt_scope, [conv2d_stage])\n    s[conv2d_stage].set_scope(env.acc_scope)\n\n    # cache read input\n    cache_read_ewise = []\n    for consumer, tensor in ewise_inputs:\n        cache_read_ewise.append(s.cache_read(tensor, env.acc_scope, [consumer]))\n\n    # set ewise scope\n    for op in ewise_ops:\n        s[op].set_scope(env.acc_scope)\n        s[op].pragma(s[op].op.axis[0], env.alu)\n\n    for op in const_ops:\n        s[op].compute_inline()\n\n    # tile\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[output].op.axis\n    x_co0, x_co1 = cfg[\"tile_co\"].apply(s, output, x_co)\n    x_i0, x_i1 = cfg[\"tile_h\"].apply(s, output, x_i)\n    x_j0, x_j1 = cfg[\"tile_w\"].apply(s, output, x_j)\n    s[output].reorder(x_bo, x_i0, x_co0, x_j0, x_co1, x_i1, x_j1, x_bi, x_ci)\n    store_pt = x_j0\n\n    # set all compute scopes\n    s[conv2d_stage].compute_at(s[output], store_pt)\n    for op in ewise_ops:\n        s[op].compute_at(s[output], store_pt)\n\n    for tensor in cache_read_ewise:\n        s[tensor].compute_at(s[output], store_pt)\n        s[tensor].pragma(s[tensor].op.axis[0], env.dma_copy)\n\n    # virtual threading along output channel axes\n    if cfg[\"oc_nthread\"].val > 1:\n        _, v_t = s[output].split(x_co0, factor=cfg[\"oc_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    # virtual threading along spatial rows\n    if cfg[\"h_nthread\"].val > 1:\n        _, v_t = s[output].split(x_i0, factor=cfg[\"h_nthread\"].val)\n        s[output].reorder(v_t, x_bo)\n        s[output].bind(v_t, te.thread_axis(\"cthread\"))\n\n    x_bo, x_co, x_i, x_j, x_bi, x_ci = s[conv2d_stage].op.axis\n    k_o, d_i, d_j, k_i = s[conv2d_stage].op.reduce_axis\n    s[conv2d_stage].reorder(x_bo, k_o, x_j, d_j, d_i, x_co, x_i, x_bi, x_ci, k_i)\n\n    k_o, _ = cfg[\"tile_ci\"].apply(s, conv2d_stage, k_o)\n    s[cdata].compute_at(s[conv2d_stage], k_o)\n    s[ckernel].compute_at(s[conv2d_stage], k_o)\n\n    # Use VTA instructions\n    s[cdata].pragma(s[cdata].op.axis[0], env.dma_copy)\n    s[ckernel].pragma(s[ckernel].op.axis[0], env.dma_copy)\n    s[conv2d_stage].tensorize(x_bi, env.gemm)\n    s[output].pragma(x_co1, env.dma_copy)\n\n    return s\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/python/vta/transform.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Additional Transformation Passes. for VTA\"\"\"\n# pylint: disable=len-as-condition, no-else-return, unused-argument, invalid-name\nimport tvm\nfrom tvm import te\nfrom tvm.topi import utils\n\nfrom .environment import get_env\n\n\ndef _match_pragma(stmt, key):\n    \"\"\"Internal helper to match stmt to pragma stmt.\n\n    Parameters\n    ----------\n    stmt : Stmt\n        The AttrStmt\n\n    key : str\n        The pragma key\n    \"\"\"\n    return (stmt.attr_key == \"pragma_\" + key) or (\n        stmt.attr_key == \"pragma_scope\" and stmt.value.value == key\n    )\n\n\ndef FoldUopLoop():\n    \"\"\"Detect and fold uop loop.\n\n    VTA support uop programming model\n    that recognizes loop structure.\n    This pass detect the loop structure\n    and extract that into uop loop AST.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _fold_outermost_loop(body):\n        stmt = body\n        if not isinstance(stmt, tvm.tir.For):\n            return None, body, None\n\n        loop_var = stmt.loop_var\n        gemm_offsets = [None, None, None]\n        fail = [False]\n        builtin_uop_push = tvm.ir.Op.get(\"tir.vta.uop_push\")\n\n        def _post_order(op):\n            assert isinstance(op, tvm.tir.Call)\n            base_args = 2\n            if op.op.same_as(builtin_uop_push):\n                args = []\n                args += op.args[:base_args]\n                for i in range(3):\n                    m = tvm.arith.detect_linear_equation(op.args[i + base_args], [loop_var])\n                    if not m:\n                        fail[0] = True\n                        return op\n                    if gemm_offsets[i] is not None:\n                        if not tvm.ir.structural_equal(m[0], gemm_offsets[i]):\n                            fail[0] = True\n                            return op\n                        args.append(m[1])\n                    else:\n                        gemm_offsets[i] = m[0]\n                        args.append(m[1])\n                args += op.args[base_args + 3 :]\n                return tvm.tir.call_intrin(\"int32\", builtin_uop_push, *args)\n            if op.op.name not in (\"tir.vta.command_handle\", \"tir.tvm_thread_context\"):\n                raise RuntimeError(\"unexpected op %s\" % op)\n            return op\n\n        ret = tvm.tir.stmt_functor.ir_transform(stmt.body, None, _post_order, [\"tir.Call\"])\n\n        if not fail[0] and all(x is not None for x in gemm_offsets):\n\n            def _visit(op):\n                if op.same_as(loop_var):\n                    fail[0] = True\n\n            tvm.tir.stmt_functor.post_order_visit(ret, _visit)\n            if not fail[0]:\n                begin = tvm.tir.call_extern(\"int32\", \"VTAUopLoopBegin\", stmt.extent, *gemm_offsets)\n                end = tvm.tir.call_extern(\"int32\", \"VTAUopLoopEnd\")\n                return [begin, ret, end]\n        raise ValueError(\"Failed to fold the GEMM instructions..\")\n\n    def _do_fold(stmt):\n        env = get_env()\n        if (\n            stmt.attr_key == \"coproc_uop_scope\"\n            and isinstance(stmt.value, tvm.tir.StringImm)\n            and stmt.value.value == env.dev.vta_push_uop.value\n        ):\n            body = stmt.body\n            begins = []\n            ends = []\n            try:\n                begin, body, end = _fold_outermost_loop(body)\n                if begin is not None:\n                    begins.append(begin)\n                if end is not None:\n                    ends.append(end)\n                begin, body, end = _fold_outermost_loop(body)\n                if begin is not None:\n                    begins.append(begin)\n                if end is not None:\n                    ends.append(end)\n            except ValueError:\n                pass\n            if body == stmt.body:\n                return stmt\n            ends = list(reversed(ends))\n            body = tvm.tir.stmt_seq(*(begins + [body] + ends))\n            return tvm.tir.AttrStmt(stmt.node, stmt.attr_key, stmt.value, body)\n        return None\n\n    def _ftransform(f, mod, ctx):\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(f.body, _do_fold, None, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(_ftransform, opt_level=0, name=\"tir.vta.FoldUopLoop\")\n\n\ndef CPUAccessRewrite():\n    \"\"\"Detect CPU access to VTA buffer and get address correctly.\n\n    VTA's buffer is an opaque handle that do not\n    correspond to address in CPU.\n    This pass detect CPU access and rewrite to use pointer\n    returned VTABufferCPUPtr for CPU access.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(f, mod, ctx):\n        env = get_env()\n\n        var_remap = {}\n        buf_remap = {}\n\n        def find_var_remap(old_var):\n            if old_var in var_remap:\n                return var_remap[old_var]\n\n            new_var = tvm.tir.Var(old_var.name + \"_ptr\", dtype=old_var.type_annotation)\n            var_remap[old_var] = new_var\n            return new_var\n\n        def find_buf_remap(old_buf):\n            if old_buf in buf_remap:\n                return buf_remap[old_buf]\n\n            new_var = find_var_remap(old_buf.data)\n            new_buf = tvm.tir.decl_buffer(\n                shape=old_buf.shape,\n                dtype=old_buf.dtype,\n                data=new_var,\n                strides=old_buf.strides,\n                elem_offset=old_buf.elem_offset,\n                scope=old_buf.scope,\n                data_alignment=old_buf.data_alignment,\n                offset_factor=old_buf.offset_factor,\n                buffer_type=\"auto_broadcast\" if (old_buf.buffer_type == 2) else \"\",\n                axis_separators=old_buf.axis_separators,\n            )\n            buf_remap[old_buf] = new_buf\n            return new_buf\n\n        def _post_order(op):\n            if isinstance(op, tvm.tir.Allocate):\n                buffer_var = op.buffer_var\n                if buffer_var not in var_remap:\n                    return None\n                new_var = var_remap[buffer_var]\n                let_stmt = tvm.tir.LetStmt(\n                    new_var,\n                    tvm.tir.call_extern(\n                        \"handle\", \"VTABufferCPUPtr\", env.dev.command_handle, buffer_var\n                    ),\n                    op.body,\n                )\n                alloc = tvm.tir.Allocate(buffer_var, op.dtype, op.extents, op.condition, let_stmt)\n                del var_remap[buffer_var]\n                bufs_to_delete = [\n                    old_buf for old_buf in buf_remap if old_buf.data.same_as(buffer_var)\n                ]\n                for buf in bufs_to_delete:\n                    del buf_remap[buf]\n                return alloc\n\n            if isinstance(op, tvm.tir.BufferLoad):\n                return tvm.tir.BufferLoad(find_buf_remap(op.buffer), op.indices)\n\n            if isinstance(op, tvm.tir.BufferStore):\n                return tvm.tir.BufferStore(find_buf_remap(op.buffer), op.value, op.indices)\n\n            raise RuntimeError(\"not reached\")\n\n        stmt_in = f.body\n        stmt = tvm.tir.stmt_functor.ir_transform(\n            stmt_in, None, _post_order, [\"tir.Allocate\", \"tir.BufferLoad\", \"tir.BufferStore\"]\n        )\n\n        for old_var, new_var in var_remap.items():\n            stmt = tvm.tir.LetStmt(\n                new_var,\n                tvm.tir.call_extern(\"handle\", \"VTABufferCPUPtr\", env.dev.command_handle, old_var),\n                stmt,\n            )\n        return f.with_body(stmt)\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.vta.CPUAccessRewrite\"\n    )\n\n\ndef LiftAllocToScopeBegin():\n    \"\"\"Lift allocate to beginning of the current scope.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(f, mod, ctx):\n        lift_stmt = [[]]\n\n        def _merge_block(slist, body):\n            for op in slist:\n                if op.body == body:\n                    body = op\n                elif isinstance(op, tvm.tir.Allocate):\n                    body = tvm.tir.Allocate(op.buffer_var, op.dtype, op.extents, op.condition, body)\n                elif isinstance(op, tvm.tir.AttrStmt):\n                    body = tvm.tir.AttrStmt(op.node, op.attr_key, op.value, body)\n                elif isinstance(op, tvm.tir.For):\n                    body = tvm.tir.For(\n                        op.loop_var,\n                        op.min,\n                        op.extent,\n                        op.kind,\n                        body,\n                        op.thread_binding,\n                        op.annotations,\n                    )\n                else:\n                    raise RuntimeError(\"unexpected op\")\n            del slist[:]\n            return body\n\n        def _pre_order(op):\n            if isinstance(op, tvm.tir.For):\n                lift_stmt.append([])\n            elif isinstance(op, tvm.tir.AttrStmt):\n                if op.attr_key == \"virtual_thread\":\n                    lift_stmt.append([])\n\n        def _post_order(op):\n            if isinstance(op, tvm.tir.Allocate):\n                lift_stmt[-1].append(op)\n                return op.body\n            if isinstance(op, tvm.tir.AttrStmt):\n                if op.attr_key == \"storage_scope\":\n                    lift_stmt[-1].append(op)\n                    return op.body\n                if op.attr_key == \"virtual_thread\":\n                    return _merge_block(lift_stmt.pop() + [op], op.body)\n                return op\n            if isinstance(op, tvm.tir.For):\n                return _merge_block(lift_stmt.pop() + [op], op.body)\n            raise RuntimeError(\"not reached\")\n\n        stmt_in = f.body\n        stmt = tvm.tir.stmt_functor.ir_transform(\n            stmt_in, _pre_order, _post_order, [\"tir.Allocate\", \"tir.AttrStmt\", \"tir.For\"]\n        )\n        assert len(lift_stmt) == 1\n        return f.with_body(_merge_block(lift_stmt[0], stmt))\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.vta.LiftAllocToScopeBegin\"\n    )\n\n\ndef InjectSkipCopy():\n    \"\"\"Pass to inject skip copy stmt, used for debug purpose.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _do_fold(stmt):\n        if _match_pragma(stmt, \"skip_dma_copy\"):\n            return tvm.tir.Evaluate(0)\n        return None\n\n    def _ftransform(f, mod, ctx):\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(f.body, _do_fold, None, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(_ftransform, opt_level=0, name=\"tir.vta.InjectSkipCopy\")\n\n\ndef InjectCoProcSync():\n    \"\"\"Pass inject coproc sync\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(f, *_):\n        success = [False]\n\n        def _do_fold(stmt):\n            if _match_pragma(stmt, \"coproc_sync\"):\n                success[0] = True\n                sync = tvm.tir.Call(\"int32\", \"vta.coproc_sync\", [])\n                return tvm.tir.SeqStmt([stmt.body, tvm.tir.Evaluate(sync)])\n            if _match_pragma(stmt, \"trim_loop\"):\n                op = stmt.body\n                assert isinstance(op, tvm.tir.For)\n                return tvm.tir.For(\n                    op.loop_var, op.min, 2, op.kind, op.body, op.thread_binding, op.annotations\n                )\n            return None\n\n        return f.with_body(\n            tvm.tir.stmt_functor.ir_transform(f.body, None, _do_fold, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.transform.Sequential(\n        [\n            tvm.tir.transform.prim_func_pass(_ftransform, 0, \"tir.vta.InjectCoProcSync\"),\n            tvm.tir.transform.CoProcSync(),\n        ],\n        opt_level=0,\n        name=\"tir.vta.InjectCoProcSync\",\n    )\n\n\ndef InjectDMAIntrin():\n    \"\"\"Pass to inject DMA copy intrinsics.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n    idxd = tvm.tir.indexdiv\n    idxm = tvm.tir.indexmod\n\n    def _check_compact(buf):\n        ndim = len(buf.shape)\n        size = tvm.tir.const(1, buf.shape[0].dtype)\n        for i in reversed(range(ndim)):\n            if not utils.equal_const_int(size - buf.strides[i], 0):\n                raise RuntimeError(\n                    \"Cannot prove compact: shape=%s, strides=%s\" % (buf.shape, buf.strides)\n                )\n            size = size * buf.shape[i]\n\n    def _fold_buffer_dim(buf, scope, elem_block):\n        ndim = len(buf.shape)\n        x_size = 1\n        base = 0\n        for i in range(1, ndim + 1):\n            if not utils.equal_const_int(buf.strides[ndim - i] - x_size, 0):\n                raise RuntimeError(\"scope %s needs to have block=%d\" % (scope, elem_block))\n            x_size = x_size * buf.shape[ndim - i]\n            if utils.equal_const_int(x_size - elem_block, 0):\n                base = i + 1\n                break\n        if base == 0:\n            raise RuntimeError(\n                \"scope %s need to have block=%d, shape=%s\" % (scope, elem_block, buf.shape)\n            )\n        shape = [elem_block]\n        strides = [1]\n\n        if base < ndim + 1 and not utils.equal_const_int(buf.strides[ndim - base], elem_block):\n            shape.append(1)\n            strides.append(elem_block)\n\n        analyzer = tvm.arith.Analyzer()\n        while base < ndim + 1:\n            x_size = 1\n            x_stride = buf.strides[ndim - base]\n            next_base = base\n            if not utils.equal_const_int(idxm(x_stride, elem_block), 0):\n                raise RuntimeError(\n                    \"scope %s need to have block=%d, shape=%s, strides=%s\"\n                    % (scope, elem_block, buf.shape, buf.strides)\n                )\n            for i in range(base, ndim + 1):\n                k = ndim - i\n                if not utils.equal_const_int(x_size * x_stride - buf.strides[k], 0):\n                    break\n                x_size = x_size * buf.shape[k]\n                next_base = i + 1\n            shape.append(analyzer.simplify(x_size))\n            strides.append(x_stride)\n            assert next_base != base\n            base = next_base\n\n        strides = list(reversed(strides))\n        shape = list(reversed(shape))\n        return shape, strides\n\n    def _get_2d_pattern(buf, elem_width, elem_bytes, dtype, scope, allow_fold):\n        elem_block = elem_bytes * 8 // elem_width\n        shape, strides = buf.shape, buf.strides\n        if not utils.equal_const_int(idxm(buf.elem_offset, elem_block), 0):\n            raise RuntimeError(\"scope %s need to have block=%d\" % (scope, elem_block))\n        if allow_fold:\n            shape, strides = _fold_buffer_dim(buf, scope, elem_block)\n        else:\n            shape = list(x for x in shape)\n            strides = list(x for x in strides)\n\n        def raise_error():\n            \"\"\"Internal function to raise error\"\"\"\n            raise RuntimeError(\n                (\n                    \"Scope[%s]: cannot detect 2d pattern with elem_block=%d:\"\n                    + \" shape=%s, strides=%s\"\n                )\n                % (scope, elem_block, buf.shape, buf.strides)\n            )\n\n        ndim = len(shape)\n\n        # Check if the inner-tensor is already flat\n        flat = utils.equal_const_int(shape[-1], elem_block)\n\n        if flat:\n            if not utils.equal_const_int(strides[-1], 1):\n                raise_error()\n\n            if ndim == 1:\n                x_size = 1\n                x_stride = 1\n                y_size = 1\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n            if not utils.equal_const_int(strides[-2] - elem_block, 0):\n                raise_error()\n\n            if ndim == 2:\n                x_size = shape[-2]\n                x_stride = shape[-2]\n                y_size = 1\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n            if not utils.equal_const_int(idxm(strides[-3], elem_block), 0):\n                raise_error()\n\n            if ndim == 3:\n                x_size = shape[-2]\n                x_stride = idxd(strides[-3], elem_block)\n                y_size = shape[-3]\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n\n        else:\n            if not utils.equal_const_int(strides[-1], 1):\n                raise_error()\n            if not utils.equal_const_int(strides[-2] - shape[-1], 0):\n                raise_error()\n            if not utils.equal_const_int(shape[-1] * shape[-2], elem_block):\n                raise_error()\n\n            if ndim == 2:\n                x_size = 1\n                x_stride = 1\n                y_size = 1\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n            if not utils.equal_const_int(strides[-3], elem_block):\n                raise_error()\n\n            if ndim == 3:\n                x_size = shape[-3]\n                x_stride = shape[-3]\n                y_size = 1\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n            if not utils.equal_const_int(idxm(strides[-4], elem_block), 0):\n                raise_error()\n\n            if ndim == 4:\n                x_size = shape[-3]\n                x_stride = idxd(strides[-4], elem_block)\n                y_size = shape[-4]\n                return x_size, y_size, x_stride, idxd(buf.elem_offset, elem_block)\n\n        raise_error()\n\n    def _inject_copy(src, dst, pad_before, pad_after, pad_value):\n        # FIXME: pad_value is ignored...\n        env = get_env()\n        _ = pad_value\n        if dst.scope() == \"global\":\n            # Store\n            if pad_before or pad_after:\n                raise RuntimeError(\"Do not support copy into DRAM with pad\")\n            if src.scope() == env.acc_scope:\n                elem_width = env.OUT_WIDTH\n                elem_bytes = env.OUT_ELEM_BYTES\n                mem_type = env.dev.MEM_ID_OUT\n                data_type = \"int%d\" % env.OUT_WIDTH\n                task_qid = env.dev.QID_STORE_OUT\n            else:\n                raise RuntimeError(\"Do not support copy %s->dram\" % (src.scope()))\n            _check_compact(src)\n            x_size, y_size, x_stride, offset = _get_2d_pattern(\n                dst, elem_width, elem_bytes, data_type, src.scope(), allow_fold=True\n            )\n            irb = tvm.tir.ir_builder.create()\n            irb.scope_attr(env.dev.vta_axis, \"coproc_scope\", env.dev.get_task_qid(task_qid))\n            irb.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"VTAStoreBuffer2D\",\n                    env.dev.command_handle,\n                    src.access_ptr(\"r\", \"int32\"),\n                    mem_type,\n                    dst.data,\n                    offset,\n                    x_size,\n                    y_size,\n                    x_stride,\n                )\n            )\n            return irb.get()\n        elif src.scope() == \"global\":\n            if dst.scope() == env.acc_scope:\n                elem_width = env.ACC_WIDTH\n                elem_bytes = env.ACC_ELEM_BYTES\n                mem_type = env.dev.MEM_ID_ACC\n                data_type = \"int%d\" % env.ACC_WIDTH\n                task_qid = env.dev.QID_LOAD_OUT\n            elif dst.scope() == env.inp_scope:\n                elem_width = env.INP_WIDTH\n                elem_bytes = env.INP_ELEM_BYTES\n                mem_type = env.dev.MEM_ID_INP\n                data_type = \"int%d\" % env.INP_WIDTH\n                task_qid = env.dev.QID_LOAD_INP\n            elif dst.scope() == env.wgt_scope:\n                elem_width = env.WGT_WIDTH\n                elem_bytes = env.WGT_ELEM_BYTES\n                mem_type = env.dev.MEM_ID_WGT\n                data_type = \"int%d\" % env.WGT_WIDTH\n                task_qid = env.dev.QID_LOAD_WGT\n            else:\n                raise RuntimeError(\"Do not support copy dram->%s\" % (dst.scope()))\n            # collect pad statistics\n            if pad_before:\n                assert pad_after\n                ndim = len(pad_before)\n                if ndim <= 2 or ndim > 5:\n                    raise ValueError(\"Limitation of 2D pad load forbid ndim=%d\" % ndim)\n                if ndim == 5:\n                    # This case occurs when batch size N > 1\n                    y_pad_before = pad_before[1]\n                    x_pad_before = pad_before[2]\n                    y_pad_after = pad_after[1]\n                    x_pad_after = pad_after[2]\n                    for dim in range(3, ndim):\n                        if not utils.equal_const_int(pad_before[dim], 0):\n                            raise ValueError(\"Do not support pad on the innermost block\")\n                        if not utils.equal_const_int(pad_after[dim], 0):\n                            raise ValueError(\"Do not support pad on the innermost block\")\n                else:\n                    y_pad_before = pad_before[0]\n                    x_pad_before = pad_before[1]\n                    y_pad_after = pad_after[0]\n                    x_pad_after = pad_after[1]\n                    for dim in range(2, ndim):\n                        if not utils.equal_const_int(pad_before[dim], 0):\n                            raise ValueError(\"Do not support pad on the innermost block\")\n                        if not utils.equal_const_int(pad_after[dim], 0):\n                            raise ValueError(\"Do not support pad on the innermost block\")\n                allow_fold = False\n            else:\n                x_pad_before = 0\n                y_pad_before = 0\n                x_pad_after = 0\n                y_pad_after = 0\n                allow_fold = True\n\n            _check_compact(dst)\n            x_size, y_size, x_stride, offset = _get_2d_pattern(\n                src, elem_width, elem_bytes, data_type, dst.scope(), allow_fold=allow_fold\n            )\n\n            if data_type != src.dtype:\n                assert data_type == \"int%d\" % env.ACC_WIDTH and src.dtype == \"int%d\" % env.INP_WIDTH\n                mem_type = env.dev.MEM_ID_ACC_8BIT\n\n            irb = tvm.tir.ir_builder.create()\n            irb.scope_attr(env.dev.vta_axis, \"coproc_scope\", env.dev.get_task_qid(task_qid))\n\n            irb.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"VTALoadBuffer2D\",\n                    env.dev.command_handle,\n                    src.data,\n                    offset,\n                    x_size,\n                    y_size,\n                    x_stride,\n                    x_pad_before,\n                    y_pad_before,\n                    x_pad_after,\n                    y_pad_after,\n                    dst.access_ptr(\"r\", \"int32\"),\n                    mem_type,\n                )\n            )\n            return irb.get()\n\n        else:\n            raise RuntimeError(\"Do not support copy %s->%s\" % (src.scope(), dst.scope()))\n\n    return tvm.tir.transform.InjectCopyIntrin(\"dma_copy\", _inject_copy)\n\n\ndef _get_gemm_intrin_buffer():\n    env = get_env()\n    wgt_lanes = env.WGT_ELEM_BITS // env.WGT_WIDTH\n    assert wgt_lanes == env.BLOCK_OUT * env.BLOCK_IN\n    wgt_shape = (env.BLOCK_OUT, env.BLOCK_IN)\n    assert wgt_shape[0] * wgt_shape[1] == wgt_lanes\n    inp_lanes = env.INP_ELEM_BITS // env.INP_WIDTH\n    assert inp_lanes == env.BATCH * env.BLOCK_IN\n    inp_shape = (env.BATCH, env.BLOCK_IN)\n    assert inp_shape[0] * inp_shape[1] == inp_lanes\n    out_lanes = env.ACC_ELEM_BITS // env.ACC_WIDTH\n    assert out_lanes == env.BATCH * env.BLOCK_OUT\n    out_shape = (env.BATCH, env.BLOCK_OUT)\n    assert out_shape[0] * out_shape[1] == out_lanes\n    wgt = te.placeholder(\n        (wgt_shape[0], wgt_shape[1]), dtype=\"int%d\" % env.WGT_WIDTH, name=env.wgt_scope\n    )\n    inp = te.placeholder(\n        (inp_shape[0], inp_shape[1]), dtype=\"int%d\" % env.INP_WIDTH, name=env.inp_scope\n    )\n    k = te.reduce_axis((0, wgt_shape[1]), name=\"k\")\n    out_dtype = \"int%d\" % env.ACC_WIDTH\n    out = te.compute(\n        (out_shape[0], out_shape[1]),\n        lambda i, j: te.sum(inp[i, k].astype(out_dtype) * wgt[j, k].astype(out_dtype), axis=[k]),\n        name=\"out\",\n    )\n    wgt_layout = tvm.tir.decl_buffer(\n        wgt.shape,\n        wgt.dtype,\n        env.wgt_scope,\n        scope=env.wgt_scope,\n        offset_factor=wgt_lanes,\n        data_alignment=wgt_lanes,\n    )\n    inp_layout = tvm.tir.decl_buffer(\n        inp.shape,\n        inp.dtype,\n        env.inp_scope,\n        scope=env.inp_scope,\n        offset_factor=inp_lanes,\n        data_alignment=inp_lanes,\n    )\n    out_layout = tvm.tir.decl_buffer(\n        out.shape,\n        out.dtype,\n        env.acc_scope,\n        scope=env.acc_scope,\n        offset_factor=out_lanes,\n        data_alignment=out_lanes,\n    )\n\n    return wgt_layout, inp_layout, out_layout\n\n\ndef InjectConv2DTransposeSkip():\n    \"\"\"Pass to skip 0-weights in conv2d transpose with stride > 1.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(func, mod, ctx):\n        env = get_env()\n        dwgt, dinp, dout = _get_gemm_intrin_buffer()\n\n        calls = []\n        selects = []\n\n        def _find_basics(op):\n            if isinstance(op, tvm.tir.BufferLoad):\n                calls.append(op)\n            elif isinstance(op, tvm.tir.Select):\n                selects.append(op)\n\n        def _do_fold(op):\n            if _match_pragma(op, \"conv2d_transpose_gemm\"):\n                is_init = \".init\" in str(op)\n                tvm.tir.stmt_functor.post_order_visit(op, _find_basics)\n\n                if is_init:\n                    # create inner most block\n                    irb = tvm.tir.ir_builder.create()\n                    dev = env.dev\n                    irb.scope_attr(dev.vta_axis, \"coproc_scope\", dev.get_task_qid(dev.QID_COMPUTE))\n                    irb.scope_attr(dev.vta_axis, \"coproc_uop_scope\", dev.vta_push_uop)\n                    irb.emit(\n                        tvm.tir.call_intrin(\n                            \"int32\",\n                            \"tir.vta.uop_push\",\n                            0,\n                            1,\n                            dout.access_ptr(\"rw\", \"int32\"),\n                            0,\n                            0,\n                            0,\n                            0,\n                            0,\n                        )\n                    )\n                    inner = irb.get()\n                    # TODO(@tmoreau89): This is only a temporary fix, please take a look.\n                    body = op.body.body\n                    while isinstance(body, tvm.tir.IfThenElse):\n                        body = body.then_case\n                    args = body.indices\n                    res_buffer = body.buffer\n                    tpl = (args[0], 1, args[1], 1, args[2], 1, args[3], 1, 0, 1, 0, env.BLOCK_OUT)\n                    inner = tvm.tir.AttrStmt(\n                        [dout, res_buffer],\n                        \"buffer_bind_scope\",\n                        tvm.tir.call_intrin(\"handle\", \"tir.tvm_tuple\", *tpl),\n                        inner,\n                    )\n                    return inner\n                else:\n                    conv_call, data_call, kernel_call = calls[-3:]\n                    pad_data_tensor = data_call.buffer\n                    kernel_tensor = kernel_call.buffer\n                    res_tensor = conv_call.buffer\n\n                    if selects:\n                        condition = selects[0].condition\n                    else:\n                        condition = tvm.tir.const(1, \"int\")\n\n                    # create inner most block\n                    irb = tvm.tir.ir_builder.create()\n                    with irb.if_scope(condition):\n                        dev = env.dev\n                        irb.scope_attr(\n                            dev.vta_axis, \"coproc_scope\", dev.get_task_qid(dev.QID_COMPUTE)\n                        )\n                        irb.scope_attr(dev.vta_axis, \"coproc_uop_scope\", dev.vta_push_uop)\n                        irb.emit(\n                            tvm.tir.call_intrin(\n                                \"int32\",\n                                \"tir.vta.uop_push\",\n                                0,\n                                0,\n                                dout.access_ptr(\"rw\", \"int32\"),\n                                dinp.access_ptr(\"r\", \"int32\"),\n                                dwgt.access_ptr(\"r\", \"int32\"),\n                                0,\n                                0,\n                                0,\n                            )\n                        )\n                    inner = irb.get()\n\n                    args = conv_call.indices\n                    tpl = (args[0], 1, args[1], 1, args[2], 1, args[3], 1, 0, 1, 0, env.BLOCK_OUT)\n                    inner = tvm.tir.AttrStmt(\n                        [dout, res_tensor],\n                        \"buffer_bind_scope\",\n                        tvm.tir.call_intrin(\"handle\", \"tir.tvm_tuple\", *tpl),\n                        inner,\n                    )\n                    args = kernel_call.indices\n                    tpl = (\n                        args[0],\n                        1,\n                        args[1],\n                        1,\n                        args[2],\n                        1,\n                        args[3],\n                        1,\n                        0,\n                        env.BLOCK_OUT,\n                        0,\n                        env.BLOCK_IN,\n                    )\n                    inner = tvm.tir.AttrStmt(\n                        [dwgt, kernel_tensor],\n                        \"buffer_bind_scope\",\n                        tvm.tir.call_intrin(\"handle\", \"tir.tvm_tuple\", *tpl),\n                        inner,\n                    )\n                    args = data_call.indices\n                    tpl = (args[0], 1, args[1], 1, args[2], 1, args[3], 1, 0, 1, 0, env.BLOCK_IN)\n                    inner = tvm.tir.AttrStmt(\n                        [dinp, pad_data_tensor],\n                        \"buffer_bind_scope\",\n                        tvm.tir.call_intrin(\"handle\", \"tir.tvm_tuple\", *tpl),\n                        inner,\n                    )\n                    return inner\n            return None\n\n        return func.with_body(\n            tvm.tir.stmt_functor.ir_transform(func.body, _do_fold, None, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.vta.InjectConv2DTrasnposeSkip\"\n    )\n\n\ndef AnnotateALUCoProcScope():\n    \"\"\"Pass to insert ALU instruction.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(func, mod, ctx):\n        env = get_env()\n\n        def _do_fold(stmt):\n            if _match_pragma(stmt, \"alu\"):\n                irb = tvm.tir.ir_builder.create()\n                irb.scope_attr(\n                    env.dev.vta_axis, \"coproc_scope\", env.dev.get_task_qid(env.dev.QID_COMPUTE)\n                )\n                irb.scope_attr(\n                    env.dev.vta_axis, \"coproc_uop_scope\", tvm.tir.StringImm(\"VTAPushALUOp\")\n                )\n                irb.emit(stmt)\n                return irb.get()\n            if _match_pragma(stmt, \"skip_alu\"):\n                return tvm.tir.Evaluate(0)\n            return stmt\n\n        return func.with_body(\n            tvm.tir.stmt_functor.ir_transform(func.body, None, _do_fold, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.vta.AnnotateALUCoProcScope\"\n    )\n\n\ndef InjectALUIntrin():\n    \"\"\"Pass to inject ALU micro-ops.\n\n    Returns\n    -------\n    fpass : tvm.transform.Pass\n        The pass\n    \"\"\"\n\n    def _ftransform(func, mod, ctx):\n        env = get_env()\n        idxm = tvm.tir.indexmod\n        analyzer = tvm.arith.Analyzer()\n\n        def _do_fold(stmt):\n            def _flatten_loop(src_coeff, dst_coeff, extents):\n                src_coeff = list(src_coeff)\n                dst_coeff = list(dst_coeff)\n                extents = list(extents)\n                rev_src_coeff = [src_coeff.pop()]\n                rev_dst_coeff = [dst_coeff.pop()]\n                rev_extents = []\n                assert src_coeff\n                vsrc = src_coeff.pop()\n                vdst = dst_coeff.pop()\n                vext = extents.pop()\n                while src_coeff:\n                    next_src = src_coeff.pop()\n                    next_dst = dst_coeff.pop()\n                    next_ext = extents.pop()\n\n                    if analyzer.can_prove_equal(next_src, vsrc * vext) and analyzer.can_prove_equal(\n                        next_dst, vdst * vext\n                    ):\n                        vext = analyzer.simplify(vext * next_ext)\n                    else:\n                        rev_src_coeff.append(vsrc)\n                        rev_dst_coeff.append(vdst)\n                        rev_extents.append(vext)\n                        vsrc = next_src\n                        vdst = next_dst\n                        vext = next_ext\n                rev_src_coeff.append(vsrc)\n                rev_dst_coeff.append(vdst)\n                rev_extents.append(vext)\n                rev_src_coeff.reverse()\n                rev_dst_coeff.reverse()\n                rev_extents.reverse()\n\n                return rev_src_coeff, rev_dst_coeff, rev_extents\n\n            if _match_pragma(stmt, \"alu\"):\n                # Get to the innermost loop body\n                loop_body = stmt.body\n                nest_size = 0\n                while isinstance(loop_body, tvm.tir.For):\n                    loop_body = loop_body.body\n                    nest_size += 1\n                # Get the src/dst arguments\n                dst_var = loop_body.buffer.data\n                dst_idx = loop_body.indices[0]\n                # Derive loop variables and extents\n                tmp_body = stmt.body\n                indices = []\n                extents = []\n                for _ in range(nest_size):\n                    indices.append(tmp_body.loop_var)\n                    extents.append(tmp_body.extent)\n                    tmp_body = tmp_body.body\n                # Derive opcode\n                if isinstance(loop_body.value, tvm.tir.Add):\n                    alu_opcode = env.dev.ALU_OPCODE_ADD\n                    lhs = loop_body.value.a\n                    rhs = loop_body.value.b\n                elif isinstance(loop_body.value, tvm.tir.Sub):\n                    alu_opcode = env.dev.ALU_OPCODE_SUB\n                    lhs = loop_body.value.a\n                    rhs = loop_body.value.b\n                elif isinstance(loop_body.value, tvm.tir.Mul):\n                    alu_opcode = env.dev.ALU_OPCODE_MUL\n                    lhs = loop_body.value.a\n                    rhs = loop_body.value.b\n                elif isinstance(loop_body.value, tvm.tir.Min):\n                    alu_opcode = env.dev.ALU_OPCODE_MIN\n                    lhs = loop_body.value.a\n                    rhs = loop_body.value.b\n                elif isinstance(loop_body.value, tvm.tir.Max):\n                    alu_opcode = env.dev.ALU_OPCODE_MAX\n                    lhs = loop_body.value.a\n                    rhs = loop_body.value.b\n                elif isinstance(loop_body.value, tvm.tir.Call):\n                    if loop_body.value.op.name == \"tir.shift_left\":\n                        alu_opcode = env.dev.ALU_OPCODE_SHR\n                        lhs = loop_body.value.args[0]\n                        rhs = analyzer.simplify(-loop_body.value.args[1])\n                    elif loop_body.value.op.name == \"tir.shift_right\":\n                        alu_opcode = env.dev.ALU_OPCODE_SHR\n                        lhs = loop_body.value.args[0]\n                        rhs = loop_body.value.args[1]\n                    else:\n                        raise RuntimeError(\n                            \"Function call not recognized %s\" % (loop_body.value.name)\n                        )\n                elif isinstance(loop_body.value, tvm.tir.BufferLoad):\n                    alu_opcode = env.dev.ALU_OPCODE_SHR\n                    lhs = loop_body.value\n                    rhs = tvm.tir.const(0, \"int32\")\n                else:\n                    raise RuntimeError(\n                        \"Expression not recognized %s, %s, %s\"\n                        % (type(loop_body.value), str(loop_body.value), str(stmt))\n                    )\n\n                # Derive array index coefficients\n                dst_coeff = tvm.arith.detect_linear_equation(dst_idx, indices)\n                # Check if lhs/rhs is immediate\n                use_imm = False\n                imm_val = None\n                if isinstance(rhs, tvm.tir.IntImm):\n                    assert lhs.buffer.data.same_as(dst_var)\n                    src_coeff = tvm.arith.detect_linear_equation(lhs.indices[0], indices)\n                    use_imm = True\n                    imm_val = rhs\n                if isinstance(lhs, tvm.tir.IntImm):\n                    assert rhs.buffer.data.same_as(dst_var)\n                    src_coeff = tvm.arith.detect_linear_equation(rhs.indices[0], indices)\n                    use_imm = True\n                    imm_val = lhs\n                if imm_val is None:\n                    imm_val = 0\n                    assert lhs.buffer.data.same_as(dst_var) and rhs.buffer.data.same_as(dst_var)\n                    src_lhs_coeff = tvm.arith.detect_linear_equation(lhs.indices[0], indices)\n                    src_rhs_coeff = tvm.arith.detect_linear_equation(rhs.indices[0], indices)\n                    # Determine which side has the same coefficients\n                    lhs_equal = True\n                    rhs_equal = True\n                    for i, coef in enumerate(dst_coeff):\n                        if not tvm.ir.structural_equal(coef, src_lhs_coeff[i]):\n                            lhs_equal = False\n                        if not tvm.ir.structural_equal(coef, src_rhs_coeff[i]):\n                            rhs_equal = False\n                    # Make sure at least one of the source is identical to the\n                    # destination (in-place computation)\n                    assert lhs_equal or rhs_equal\n                    # Assign the source coefficients\n                    if lhs_equal:\n                        src_coeff = src_rhs_coeff\n                    else:\n                        src_coeff = src_lhs_coeff\n\n                # Ensure that we have the proper tensor dimensions in the\n                # innermost loop (pattern match)\n                src_coeff = list(src_coeff)\n                dst_coeff = list(dst_coeff)\n                extents = list(extents)\n                assert len(src_coeff) > 1\n                assert len(dst_coeff) > 1\n                assert len(extents) != 0\n                assert tvm.ir.structural_equal(\n                    analyzer.simplify(idxm(src_coeff[-1], env.BATCH * env.BLOCK_OUT)), 0\n                )\n                assert tvm.ir.structural_equal(\n                    analyzer.simplify(idxm(dst_coeff[-1], env.BATCH * env.BLOCK_OUT)), 0\n                )\n                assert tvm.ir.structural_equal(src_coeff[-2], 1)\n                assert tvm.ir.structural_equal(dst_coeff[-2], 1)\n                if env.BATCH > 1:\n                    assert len(src_coeff) > 2\n                    assert len(dst_coeff) > 2\n                    assert len(extents) > 1\n                    assert tvm.ir.structural_equal(src_coeff[-3], env.BLOCK_OUT)\n                    assert tvm.ir.structural_equal(dst_coeff[-3], env.BLOCK_OUT)\n\n                # Apply tensorization of the loop coefficients\n                src_offset = src_coeff[-1]\n                dst_offset = dst_coeff[-1]\n                if env.BATCH == 1:\n                    src_coeff = src_coeff[:-2]\n                    dst_coeff = dst_coeff[:-2]\n                    extents = extents[:-1]\n                else:\n                    src_coeff = src_coeff[:-3]\n                    dst_coeff = dst_coeff[:-3]\n                    extents = extents[:-2]\n                src_coeff.append(src_offset)\n                dst_coeff.append(dst_offset)\n                src_coeff = [analyzer.simplify(c // (env.BATCH * env.BLOCK_OUT)) for c in src_coeff]\n                dst_coeff = [analyzer.simplify(c // (env.BATCH * env.BLOCK_OUT)) for c in dst_coeff]\n\n                # Flatten the outer loops\n                if extents:\n                    src_coeff, dst_coeff, extents = _flatten_loop(src_coeff, dst_coeff, extents)\n\n                # Insert ALU micro-ops\n                irb = tvm.tir.ir_builder.create()\n                for idx, extent in enumerate(extents):\n                    irb.emit(\n                        tvm.tir.call_extern(\n                            \"int32\",\n                            \"VTAUopLoopBegin\",\n                            extent,\n                            dst_coeff[idx],\n                            src_coeff[idx],\n                            0,\n                        )\n                    )\n                use_imm = int(use_imm)\n                irb.emit(\n                    tvm.tir.call_intrin(\n                        \"int32\",\n                        \"tir.vta.uop_push\",\n                        1,\n                        0,\n                        dst_coeff[len(dst_coeff) - 1],\n                        src_coeff[len(src_coeff) - 1],\n                        0,\n                        alu_opcode,\n                        use_imm,\n                        imm_val,\n                    )\n                )\n                for extent in extents:\n                    irb.emit(tvm.tir.call_extern(\"int32\", \"VTAUopLoopEnd\"))\n                return irb.get()\n            return stmt\n\n        return func.with_body(\n            tvm.tir.stmt_functor.ir_transform(func.body, None, _do_fold, [\"tir.AttrStmt\"])\n        )\n\n    return tvm.tir.transform.prim_func_pass(\n        _ftransform, opt_level=0, name=\"tir.vta.InjectALUIntrin\"\n    )\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/runtime/runtime.h",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/*!\n * \\file runtime.h\n * \\brief VTA runtime library.\n */\n\n#ifndef VTA_RUNTIME_RUNTIME_H_\n#define VTA_RUNTIME_RUNTIME_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <tvm/runtime/c_runtime_api.h>\n#include <vta/driver.h>\n\n#define VTA_MEMCPY_H2D 1\n#define VTA_MEMCPY_D2H 2\n#define VTA_MEMCPY_D2D 3\n\n#define VTA_DEBUG_DUMP_INSN (1 << 1)\n#define VTA_DEBUG_DUMP_UOP (1 << 2)\n#define VTA_DEBUG_SKIP_READ_BARRIER (1 << 3)\n#define VTA_DEBUG_SKIP_WRITE_BARRIER (1 << 4)\n#define VTA_DEBUG_FORCE_SERIAL (1 << 5)\n\n#define ALLOC_ALIGNMENT 64\n\n/*!\n * \\brief Allocate data buffer.\n * \\param size Buffer size.\n * \\return A pointer to the allocated buffer.\n */\nTVM_DLL void* VTABufferAlloc(size_t size);\n\n/*!\n * \\brief Free data buffer.\n * \\param buffer The data buffer to be freed.\n */\nTVM_DLL void VTABufferFree(void* buffer);\n\n/*!\n * \\brief Copy data buffer from one location to another.\n * \\param from The source buffer base address.\n * \\param from_offset The offset of the source buffer.\n * \\param to The target buffer base address.\n * \\param to_offset The offset of the target buffer.\n * \\param size Size of copy.\n * \\param kind_mask The memory copy kind.\n */\nTVM_DLL void VTABufferCopy(const void* from, size_t from_offset, void* to, size_t to_offset,\n                           size_t size, int kind_mask);\n\n/*! \\brief VTA command handle */\ntypedef void* VTACommandHandle;\n\n/*! \\brief Shutdown hook of VTA to cleanup resources */\nTVM_DLL void VTARuntimeShutdown();\n\n/*!\n * \\brief Get thread local command handle.\n * \\return A thread local command handle.\n */\nTVM_DLL VTACommandHandle VTATLSCommandHandle();\n\n/*!\n * \\brief Get the buffer access pointer on CPU.\n * \\param cmd The VTA command handle.\n * \\param buffer The data buffer.\n * \\return The pointer that can be accessed by the CPU.\n */\nTVM_DLL void* VTABufferCPUPtr(VTACommandHandle cmd, void* buffer);\n\n/*!\n * \\brief Perform a write barrier to make a memory region visible to the CPU.\n * \\param cmd The VTA command handle.\n * \\param buffer The head buffer pointer.\n * \\param elem_bits The size in bits of each element.\n * \\param start The start of the region (in elements).\n * \\param extent The end of the region (in elements).\n */\nTVM_DLL void VTAWriteBarrier(VTACommandHandle cmd, void* buffer, uint32_t elem_bits, uint32_t start,\n                             uint32_t extent);\n\n/*!\n * \\brief Perform a read barrier to a memory region visible to VTA.\n * \\param cmd The VTA command handle.\n * \\param buffer The head buffer pointer.\n * \\param elem_bits The unit bits of each elements.\n * \\param start The start of the region (in elements).\n * \\param extent The end of the region (in elements).\n */\nTVM_DLL void VTAReadBarrier(VTACommandHandle cmd, void* buffer, uint32_t elem_bits, uint32_t start,\n                            uint32_t extent);\n\n/*!\n * \\brief Set debug mode on the command handle.\n * \\param cmd The VTA command handle.\n * \\param debug_flag The debug flag.\n */\nTVM_DLL void VTASetDebugMode(VTACommandHandle cmd, int debug_flag);\n\n/*!\n * \\brief Perform a 2D data load from DRAM.\n *  Sizes are measured in units of vector elements.\n * \\param cmd The VTA command handle.\n * \\param src_dram_addr Source DRAM address.\n * \\param src_elem_offset The source DRAM offset in number of unit elements.\n * \\param x_size The lowest dimension (x axis) size in number of unit elements.\n * \\param y_size The number of rows (y axis).\n * \\param x_stride The x axis stride.\n * \\param x_pad_before The start padding on x axis.\n * \\param y_pad_before The start padding on y axis.\n * \\param x_pad_after The end padding on x axis.\n * \\param y_pad_after The end padding of y axis.\n * \\param dst_sram_index Destination SRAM index.\n * \\param dst_memory_type Destination memory type.\n */\nTVM_DLL void VTALoadBuffer2D(VTACommandHandle cmd, void* src_dram_addr, uint32_t src_elem_offset,\n                             uint32_t x_size, uint32_t y_size, uint32_t x_stride,\n                             uint32_t x_pad_before, uint32_t y_pad_before, uint32_t x_pad_after,\n                             uint32_t y_pad_after, uint32_t dst_sram_index,\n                             uint32_t dst_memory_type);\n\n/*!\n * \\brief Perform a 2D data store into DRAM\n *  Sizes are measured in units of vector elements.\n * \\param cmd The VTA command handle.\n * \\param src_sram_index Source SRAM index.\n * \\param src_memory_type Source memory type.\n * \\param dst_dram_addr Destination DRAM address.\n * \\param dst_elem_offset The destination DRAM offset in number of unit elements.\n * \\param x_size The lowest dimension (x axis) size in number of unit elements.\n * \\param y_size The number of rows.\n * \\param x_stride The x axis stride.\n */\nTVM_DLL void VTAStoreBuffer2D(VTACommandHandle cmd, uint32_t src_sram_index,\n                              uint32_t src_memory_type, void* dst_dram_addr,\n                              uint32_t dst_elem_offset, uint32_t x_size, uint32_t y_size,\n                              uint32_t x_stride);\n\n/*!\n * \\brief Push uop into kernel buffer.\n * In GEMM mode, do a blocked GEMM with 2d access pattern.\n * In ALU mode, do a vectorized ALU operation with 2d access pattern.\n *\n *  \\code\n *\n *   DType accum[INP_BUFF_DEPTH][l][n];\n *   DType weight[WGT_BUFF_DEPTH][n][m];\n *   DType input[INP_BUFF_DEPTH][l][m];\n *   if reset_out == 1\n *    accum[dst_index] = 0\n *   elif mode == 0\n *    accum[dst_index] += GEMM(input[src_index], weight[wgt_index]);\n *   else\n *    if (use_imm)\n *      accum[dst_index] = opcode(accum[dst_index], imm_val);\n *    else\n *      accum[dst_index] = opcode(accum[dst_index], accum[src_index]);\n *\n *  \\endcode\n *\n * \\param mode Set to GEMM mode if set to 0, ALU mode is set to 1.\n * \\param reset_out Resets the accum to 0.\n * \\param dst_index The accum memory index.\n * \\param src_index The input memory (gemm) / accum memory (alu) index.\n * \\param wgt_index The weight memory index.\n * \\param opcode The ALU opcode.\n * \\param use_imm Use immediate in ALU mode if set to true.\n * \\param imm_val Immediate value in ALU mode.\n */\nTVM_DLL void VTAUopPush(uint32_t mode, uint32_t reset_out, uint32_t dst_index, uint32_t src_index,\n                        uint32_t wgt_index, uint32_t opcode, uint32_t use_imm, int32_t imm_val);\n\n/*!\n * \\brief Mark start of a micro op loop.\n * \\param extent The extent of the loop.\n * \\param dst_factor The accum factor.\n * \\param src_factor The input factor.\n * \\param wgt_factor The weight factor.\n */\nTVM_DLL void VTAUopLoopBegin(uint32_t extent, uint32_t dst_factor, uint32_t src_factor,\n                             uint32_t wgt_factor);\n\n/*!\n * \\brief Mark end of a micro op loop.\n */\nTVM_DLL void VTAUopLoopEnd();\n\n/*!\n * \\brief Push GEMM uop kernel into the command handle.\n * \\param uop_handle The uop cache handle.\n * \\param finit The initalization function to initialize uop.\n * \\param signature The closure arguments of the finit.\n * \\param nbytes Number of bytes to in the closure arguments.\n * \\return 0 if success.\n */\nTVM_DLL int VTAPushGEMMOp(void** uop_handle, int (*finit)(void*), void* signature, int nbytes);\n\n/*!\n * \\brief Push ALU uop kernel into the command handle.\n * \\param uop_handle The uop cache handle.\n * \\param finit The initalization function to initialize uop.\n * \\param signature The closure arguments of the finit.\n * \\param nbytes Number of bytes to in the closure arguments.\n * \\return 0 if success.\n */\nTVM_DLL int VTAPushALUOp(void** uop_handle, int (*finit)(void*), void* signature, int nbytes);\n\n/*!\n * \\brief Push dependence token.\n * \\param cmd The VTA command handle.\n * \\param from_qid The source queue.\n * \\param to_qid The destination queue.\n * \\return 0 if success.\n */\nTVM_DLL int VTADepPush(VTACommandHandle cmd, int from_qid, int to_qid);\n\n/*!\n * \\brief Pop dependence signal.\n * \\param cmd The VTA command handle.\n * \\param from_qid The source queue.\n * \\param to_qid The destination queue.\n * \\return 0 if success.\n */\nTVM_DLL int VTADepPop(VTACommandHandle cmd, int from_qid, int to_qid);\n\n/*!\n * \\brief Synchronize the command handle.\n *  Commit all the instructions to VTA and wait until\n *  the accelerator finishes its job.\n *  Perform all of the out-of-order DRAM stores.\n * \\param cmd The VTA command handle.\n * \\param wait_cycles The limit of poll cycles.\n *\n */\nTVM_DLL void VTASynchronize(VTACommandHandle cmd, uint32_t wait_cycles);\n\n#ifdef __cplusplus\n}\n#endif\n#endif  // VTA_RUNTIME_RUNTIME_H_\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/scripts/tune_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tuning a single conv2d operator\"\"\"\n\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport vta\nimport vta.testing\n\nenv = vta.get_env()\n\nWorkload = namedtuple(\n    \"Conv2DWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n    ],\n)\n\nresnet_wkls = [\n    # Workloads of resnet18 on imagenet\n    # ('resnet-18.C1',  Workload(env.BATCH, 224, 224, 3,   64,  7, 7, 3, 3, 2, 2)),\n    (\"resnet-18.C2\", Workload(env.BATCH, 56, 56, 64, 64, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C3\", Workload(env.BATCH, 56, 56, 64, 128, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C4\", Workload(env.BATCH, 56, 56, 64, 128, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C5\", Workload(env.BATCH, 28, 28, 128, 128, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C6\", Workload(env.BATCH, 28, 28, 128, 256, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C7\", Workload(env.BATCH, 28, 28, 128, 256, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C8\", Workload(env.BATCH, 14, 14, 256, 256, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C9\", Workload(env.BATCH, 14, 14, 256, 512, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C10\", Workload(env.BATCH, 14, 14, 256, 512, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C11\", Workload(env.BATCH, 7, 7, 512, 512, 3, 3, 1, 1, 1, 1)),\n]\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef conv2d(N, CI, H, W, CO, KH, KW, strides, padding, dilation):\n    data_shape = (N // env.BATCH, CI // env.BLOCK_IN, H, W, env.BATCH, env.BLOCK_IN)\n    kernel_shape = (CO // env.BLOCK_OUT, CI // env.BLOCK_IN, KH, KW, env.BLOCK_OUT, env.BLOCK_IN)\n    bias_shape = (N // env.BATCH, CO // env.BLOCK_OUT, 1, 1, env.BATCH, env.BLOCK_OUT)\n\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n    bias = te.placeholder(bias_shape, name=\"bias\", dtype=env.acc_dtype)\n\n    with tvm.target.vta():\n        res = topi.nn.conv2d(\n            input=data,\n            filter=kernel,\n            padding=padding,\n            strides=strides,\n            dilation=dilation,\n            layout=\"NCHW%dn%dc\" % (env.BATCH, env.BLOCK_IN),\n            out_dtype=env.acc_dtype,\n        )\n        res = topi.right_shift(res, env.WGT_WIDTH)\n        res = topi.add(res, bias)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n\n    if tvm.target.Target.current().device_name == \"vta\":\n        s = topi.generic.schedule_conv2d_nchw([res])\n    else:\n        s = te.create_schedule([res.op])\n\n    return s, [data, kernel, bias, res]\n\n\nif __name__ == \"__main__\":\n\n    # Logging config (for printing tuning log to the screen)\n    logging.basicConfig()\n    # logging.getLogger('autotvm').setLevel(logging.DEBUG)\n\n    # Tuning log files\n    log_file = \"%s.conv2d.log\" % (env.TARGET)\n    # create tmp log file\n    tmp_log_file = log_file + \".tmp\"\n    if os.path.exists(log_file):\n        os.remove(log_file)\n\n    # Get tracker info from env\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    if not tracker_host or not tracker_port:\n        print(\"Set your AutoTVM tracker node host and port variables to run the autotuner\")\n        exit()\n\n    for idx, (wl_name, wl) in enumerate(resnet_wkls):\n        prefix = \"[Task %2d/%2d] \" % (idx, len(resnet_wkls))\n\n        # Read in workload parameters\n        N = wl.batch\n        CI = wl.in_filter\n        H = wl.height\n        W = wl.width\n        CO = wl.out_filter\n        KH = wl.hkernel\n        KW = wl.wkernel\n        strides = (wl.hstride, wl.wstride)\n        padding = (wl.hpad, wl.wpad)\n        dilation = (1, 1)\n\n        # Create task\n        task = autotvm.task.create(\n            conv2d,\n            args=(N, CI, H, W, CO, KH, KW, strides, padding, dilation),\n            target=tvm.target.vta(),\n            target_host=env.target_host,\n            template_key=\"direct\",\n        )\n        print(task.config_space)\n\n        # Tune\n        measure_option = autotvm.measure_option(\n            builder=autotvm.LocalBuilder(),\n            runner=autotvm.RPCRunner(\n                env.TARGET,\n                host=tracker_host,\n                port=int(tracker_port),\n                number=5,\n                timeout=60,\n                # check_correctness=True, # TODO: re-enable when check_correctness works again.\n            ),\n        )\n\n        # Run Tuner\n        tuner = autotvm.tuner.RandomTuner(task)\n        tuner.tune(\n            n_trial=len(task.config_space),\n            early_stopping=None,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(len(task.config_space), prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # Pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_file)\n    os.remove(tmp_log_file)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/scripts/tune_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tuning a single conv2d transpose operator\"\"\"\n\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport vta\nimport vta.testing\n\n# Get batch info from env\nenv = vta.get_env()\n\nWorkload = namedtuple(\n    \"Conv2DTransposeWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n        \"o_hpad\",\n        \"o_wpad\",\n    ],\n)\n\n# DCGAN workloads\ndcgan_wkls = [\n    # dcgan\n    (\"DCGAN.CT1\", Workload(env.BATCH, 4, 4, 1024, 512, 4, 4, 1, 1, 2, 2, 0, 0)),\n    (\"DCGAN.CT2\", Workload(env.BATCH, 8, 8, 512, 256, 4, 4, 1, 1, 2, 2, 0, 0)),\n    (\"DCGAN.CT3\", Workload(env.BATCH, 16, 16, 256, 128, 4, 4, 1, 1, 2, 2, 0, 0)),\n]\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef conv2d_transpose(N, CI, H, W, CO, KH, KW, strides, padding, opadding):\n    data_shape = (N // env.BATCH, CI // env.BLOCK_IN, H, W, env.BATCH, env.BLOCK_IN)\n    kernel_shape = (CO // env.BLOCK_OUT, CI // env.BLOCK_IN, KH, KW, env.BLOCK_OUT, env.BLOCK_IN)\n\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n\n    with tvm.target.vta():\n        res = topi.nn.conv2d_transpose_nchw(\n            Input=data,\n            Filter=kernel,\n            strides=strides,\n            padding=padding,\n            out_dtype=env.acc_dtype,\n            output_padding=opadding,\n        )\n        res = topi.right_shift(res, env.WGT_WIDTH)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n\n    if tvm.target.Target.current().device_name == \"vta\":\n        s = topi.generic.schedule_conv2d_transpose_nchw([res])\n    else:\n        s = te.create_schedule([res.op])\n\n    return s, [data, kernel, res]\n\n\nif __name__ == \"__main__\":\n\n    # Logging config (for printing tuning log to the screen)\n    logging.basicConfig()\n    # logging.getLogger('autotvm').setLevel(logging.DEBUG)\n\n    # Tuning log files\n    log_file = \"%s.conv2d_transpose.log\" % (env.TARGET)\n    # create tmp log file\n    tmp_log_file = log_file + \".tmp\"\n    if os.path.exists(log_file):\n        os.remove(log_file)\n\n    # Get tracker info from env\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    if not tracker_host or not tracker_port:\n        print(\"Set your AutoTVM tracker node host and port variables to run the autotuner\")\n        exit()\n\n    for idx, (wl_name, wl) in enumerate(dcgan_wkls):\n        prefix = \"[Task %2d/%2d] \" % (idx, len(dcgan_wkls))\n\n        # Read in workload parameters\n        N = wl.batch\n        H = wl.height\n        W = wl.width\n        CI = wl.in_filter\n        CO = wl.out_filter\n        KH = wl.hkernel\n        KW = wl.wkernel\n        strides = (wl.hstride, wl.wstride)\n        padding = (wl.hpad, wl.wpad)\n        opadding = (wl.o_hpad, wl.o_wpad)\n\n        # Create task\n        task = autotvm.task.create(\n            conv2d_transpose,\n            args=(N, CI, H, W, CO, KH, KW, strides, padding, opadding),\n            target=tvm.target.Target(tvm.target.vta(), host=env.target_host),\n            template_key=\"direct\",\n        )\n        print(task.config_space)\n\n        # Tune\n        measure_option = autotvm.measure_option(\n            builder=autotvm.LocalBuilder(),\n            runner=autotvm.RPCRunner(\n                env.TARGET,\n                host=tracker_host,\n                port=int(tracker_port),\n                number=5,\n                timeout=60,\n                # check_correctness=True, # TODO: re-enable when check_correctness works again.\n            ),\n        )\n\n        # Run Tuner\n        tuner = autotvm.tuner.RandomTuner(task)\n        tuner.tune(\n            n_trial=len(task.config_space),\n            early_stopping=None,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(len(task.config_space), prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # Pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_file)\n    os.remove(tmp_log_file)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/scripts/tune_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tuning a single dense operator\"\"\"\n\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport vta\nimport vta.testing\n\nenv = vta.get_env()\n\nWorkload = namedtuple(\"DenseWorkload\", [\"batch\", \"in_filter\", \"out_filter\"])\n\ndense_wkls = [\n    (\"lstm.dense.1\", Workload(1, 256, 128)),\n    (\"lstm.dense.4\", Workload(4, 256, 128)),\n]\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef dense(N, CI, CO):\n    data_shape = (N // env.BATCH, CI // env.BLOCK_IN, env.BATCH, env.BLOCK_IN)\n    kernel_shape = (CO // env.BLOCK_OUT, CI // env.BLOCK_IN, env.BLOCK_OUT, env.BLOCK_IN)\n\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n\n    with tvm.target.vta():\n        res = topi.nn.dense(data, kernel, None, \"int32\")\n        res = topi.right_shift(res, 8)\n        res = my_clip(res, 0, 127)\n        res = topi.cast(res, \"int8\")\n\n    if tvm.target.Target.current().device_name == \"vta\":\n        s = topi.generic.schedule_dense([res])\n    else:\n        s = te.create_schedule([res.op])\n\n    return s, [data, kernel, res]\n\n\nif __name__ == \"__main__\":\n\n    # Logging config (for printing tuning log to the screen)\n    logging.basicConfig()\n    # logging.getLogger('autotvm').setLevel(logging.DEBUG)\n\n    # Tuning log files\n    log_file = \"%s.dense.log\" % (env.TARGET)\n    # create tmp log file\n    tmp_log_file = log_file + \".tmp\"\n    if os.path.exists(log_file):\n        os.remove(log_file)\n\n    # Get tracker info from env\n    tracket_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracket_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    if not tracket_host or not tracket_port:\n        print(\"Set your AutoTVM tracker node host and port variables to run the autotuner\")\n        exit()\n\n    for idx, (wl_name, wl) in enumerate(dense_wkls):\n\n        prefix = \"[Task %2d/%2d] \" % (idx, len(dense_wkls))\n\n        # Workload parameters\n        N = wl.batch\n        CI = wl.in_filter\n        CO = wl.out_filter\n\n        task = autotvm.task.create(\n            dense,\n            args=(N, CI, CO),\n            target=tvm.target.vta(),\n            target_host=env.target_host,\n            template_key=\"direct\",\n        )\n        print(task.config_space)\n\n        # Tune\n        measure_option = autotvm.measure_option(\n            builder=autotvm.LocalBuilder(),\n            runner=autotvm.RPCRunner(\n                env.TARGET,\n                host=tracket_host,\n                port=int(tracket_port),\n                number=5,\n                timeout=60,\n                # check_correctness=True, # TODO: re-enable when check_correctness works again.\n            ),\n        )\n\n        # Run Tuner\n        tuner = autotvm.tuner.RandomTuner(task)\n        tuner.tune(\n            n_trial=len(task.config_space),\n            early_stopping=None,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(len(task.config_space), prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # Pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_file)\n    os.remove(tmp_log_file)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/scripts/tune_group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tuning a single group conv2d operator\"\"\"\n\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm import topi\nimport vta\nimport vta.testing\n\nenv = vta.get_env()\n\nWorkload = namedtuple(\n    \"GroupConv2DWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"groups\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n    ],\n)\n\n# Mobilenet (grouped variant) workloads\nmobilenet_wkls = [\n    (\"mobilenet.D1\", Workload(env.BATCH, 112, 112, 32, 32, 2, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D2\", Workload(env.BATCH, 112, 112, 64, 64, 4, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D3\", Workload(env.BATCH, 56, 56, 128, 128, 8, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D4\", Workload(env.BATCH, 56, 56, 128, 128, 8, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D5\", Workload(env.BATCH, 28, 28, 256, 256, 16, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D6\", Workload(env.BATCH, 28, 28, 256, 256, 16, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D7\", Workload(env.BATCH, 14, 14, 512, 512, 32, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D8\", Workload(env.BATCH, 14, 14, 512, 512, 32, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D9\", Workload(env.BATCH, 7, 7, 1024, 1024, 64, 3, 3, 1, 1, 1, 1)),\n]\n\n\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef group_conv2d(N, CI, H, W, CO, KH, KW, strides, padding, dilation, group):\n\n    CI_G = CI // groups\n    data_shape = (N // env.BATCH, CI // env.BLOCK_IN, H, W, env.BATCH, env.BLOCK_IN)\n    kernel_shape = (CO // env.BLOCK_OUT, CI_G // env.BLOCK_IN, KH, KW, env.BLOCK_OUT, env.BLOCK_IN)\n    bias_shape = (N // env.BATCH, CO // env.BLOCK_OUT, 1, 1, env.BATCH, env.BLOCK_OUT)\n\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n    bias = te.placeholder(bias_shape, name=\"bias\", dtype=env.acc_dtype)\n\n    with tvm.target.vta():\n        res = topi.nn.group_conv2d_nchw(\n            data, kernel, strides, padding, dilation, groups, env.acc_dtype\n        )\n        res = topi.right_shift(res, env.WGT_WIDTH)\n        res = topi.add(res, bias)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n\n    if tvm.target.Target.current().device_name == \"vta\":\n        s = topi.generic.schedule_group_conv2d_nchw([res])\n    else:\n        s = te.create_schedule([res.op])\n\n    return s, [data, kernel, bias, res]\n\n\nif __name__ == \"__main__\":\n\n    # Logging config (for printing tuning log to the screen)\n    logging.basicConfig()\n\n    # Tuning log files\n    log_file = \"%s.group_conv2d.log\" % (env.TARGET)\n    # create tmp log file\n    tmp_log_file = log_file + \".tmp\"\n    if os.path.exists(log_file):\n        os.remove(log_file)\n\n    # Get tracker info from env\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    if not tracker_host or not tracker_port:\n        print(\"Set your AutoTVM tracker node host and port variables to run the autotuner\")\n        exit()\n\n    for idx, (wl_name, wl) in enumerate(mobilenet_wkls):\n        prefix = \"[Task %2d/%2d] \" % (idx, len(mobilenet_wkls))\n\n        # Read in workload parameters\n        N = wl.batch\n        CI = wl.in_filter\n        H = wl.height\n        W = wl.width\n        CO = wl.out_filter\n        KH = wl.hkernel\n        KW = wl.wkernel\n        strides = (wl.hstride, wl.wstride)\n        padding = (wl.hpad, wl.wpad)\n        dilation = (1, 1)\n        groups = wl.groups\n\n        # Create task\n        task = autotvm.task.create(\n            group_conv2d,\n            args=(N, CI, H, W, CO, KH, KW, strides, padding, dilation, groups),\n            target=tvm.target.vta(),\n            target_host=env.target_host,\n            template_key=\"direct\",\n        )\n        print(task.config_space)\n\n        # Tune\n        measure_option = autotvm.measure_option(\n            builder=autotvm.LocalBuilder(),\n            runner=autotvm.RPCRunner(\n                env.TARGET,\n                host=tracker_host,\n                port=int(tracker_port),\n                number=5,\n                timeout=60,\n                # check_correctness=True, # TODO: re-enable when check_correctness works again.\n            ),\n        )\n\n        # Run Tuner\n        tuner = autotvm.tuner.RandomTuner(task)\n        tuner.tune(\n            n_trial=len(task.config_space),\n            early_stopping=None,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(len(task.config_space), prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # Pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_file)\n    os.remove(tmp_log_file)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/scripts/tune_resnet.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Perform ResNet autoTVM tuning on VTA using Relay.\"\"\"\n\nimport argparse, os, time\nfrom mxnet.gluon.model_zoo import vision\nimport numpy as np\nfrom PIL import Image\n\nfrom tvm import topi\nimport tvm\nfrom tvm import te\nfrom tvm import rpc, autotvm, relay\nfrom tvm.autotvm.measure.measure_methods import request_remote\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.contrib import graph_executor, utils, download\nfrom tvm.contrib.debugger import debug_executor\nimport vta\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\nfrom tvm.autotvm.task import extract_from_program\n\n\ndef parse_arguments():\n\n    parser = argparse.ArgumentParser(description=\"Train a model for image classification.\")\n    parser.add_argument(\n        \"--model\",\n        type=str,\n        default=\"resnet18_v1\",\n        choices=[\"resnet18_v1\"],\n        help=\"Input model name.\",\n    )\n    parser.add_argument(\n        \"--start-name\",\n        type=str,\n        default=\"nn.max_pool2d\",\n        help=\"The name of the node where packing starts\",\n    )\n    parser.add_argument(\n        \"--stop-name\",\n        type=str,\n        default=\"nn.global_avg_pool2d\",\n        help=\"The name of the node where packing stops\",\n    )\n    parser.add_argument(\n        \"--debug-profile\", action=\"store_true\", help=\"Show layer-wise time cost profiling results\"\n    )\n    parser.add_argument(\n        \"--device\", default=\"vta\", choices=[\"vta\", \"arm_cpu\"], help=\"Select device target\"\n    )\n    parser.add_argument(\n        \"--measurements\", type=int, default=1, help=\"Number of measurements during AutoTVM search\"\n    )\n    parser.add_argument(\"--tuner\", type=str, default=\"random\", help=\"AutoTVM search strategy\")\n    parser.add_argument(\n        \"--log-filename\", type=str, default=\"resnet-18.log\", help=\"AutoTVM log file name\"\n    )\n\n    return parser.parse_args()\n\n\ndef register_vta_tuning_tasks():\n    from tvm.autotvm.task.topi_integration import TaskExtractEnv, deserialize_args\n\n    @tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\n    def my_clip(x, a_min, a_max):\n        \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n        const_min = tvm.tir.const(a_min, x.dtype)\n        const_max = tvm.tir.const(a_max, x.dtype)\n        x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n        x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n        return x\n\n    # init autotvm env to register VTA operator\n    TaskExtractEnv()\n\n    @autotvm.task.register(\"topi_nn_conv2d\", override=True)\n    def _topi_nn_conv2d(*args, **kwargs):\n        assert not kwargs, \"Do not support kwargs in template function call\"\n        args = deserialize_args(args)\n        A, W = args[:2]\n\n        with tvm.target.vta():\n            res = topi.nn.conv2d(*args, **kwargs)\n            res = topi.right_shift(res, 8)\n            res = my_clip(res, 0, 127)\n            res = topi.cast(res, \"int8\")\n\n        if tvm.target.Target.current().device_name == \"vta\":\n            s = topi.generic.schedule_conv2d_nchw([res])\n        else:\n            s = te.create_schedule([res.op])\n        return s, [A, W, res]\n\n    @autotvm.task.register(\"topi_nn_dense\", override=True)\n    def _topi_nn_dense(*args, **kwargs):\n        assert not kwargs, \"Do not support kwargs in template function call\"\n        args = deserialize_args(args)\n        A, W = args[:2]\n\n        with tvm.target.vta():\n            res = topi.nn.dense(*args, **kwargs)\n            res = topi.right_shift(res, 8)\n            res = my_clip(res, 0, 127)\n            res = topi.cast(res, \"int8\")\n\n        if tvm.target.Target.current().device_name == \"vta\":\n            s = topi.generic.schedule_dense([res])\n        else:\n            s = te.create_schedule([res.op])\n\n        return s, [A, W, res]\n\n\ndef compile_network(opt, env, target):\n\n    # Populate the shape and data type dictionary\n    dtype_dict = {\"data\": \"float32\"}\n    shape_dict = {\"data\": (env.BATCH, 3, 224, 224)}\n\n    # Get off the shelf gluon model, and convert to relay\n    gluon_model = vision.get_model(opt.model, pretrained=True)\n    mod, params = relay.frontend.from_mxnet(gluon_model, shape_dict)\n\n    # Update shape and type dictionary\n    shape_dict.update({k: v.shape for k, v in params.items()})\n    dtype_dict.update({k: str(v.dtype) for k, v in params.items()})\n\n    # Perform quantization in Relay\n    # Note: We set opt_level to 3 in order to fold batch norm\n    with tvm.transform.PassContext(opt_level=3):\n        with relay.quantize.qconfig(global_scale=8.0, skip_conv_layers=[0]):\n            relay_prog = relay.quantize.quantize(mod[\"main\"], params=params)\n\n    # Perform graph packing and constant folding for VTA target\n    if target.device_name == \"vta\":\n        assert env.BLOCK_IN == env.BLOCK_OUT\n        relay_prog = graph_pack(\n            relay_prog,\n            env.BATCH,\n            env.BLOCK_OUT,\n            env.WGT_WIDTH,\n            start_name=opt.start_name,\n            stop_name=opt.stop_name,\n        )\n\n    return relay_prog, params\n\n\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n    try_winograd=True,\n):\n\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        n_trial_ = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial_,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(n_trial_, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\nif __name__ == \"__main__\":\n\n    opt = parse_arguments()\n\n    # Make sure that TVM was compiled with RPC=1\n    assert tvm.runtime.enabled(\"rpc\")\n\n    # Read in VTA environment\n    env = vta.get_env()\n\n    # Get remote from fleet node\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    if not tracker_host or not tracker_port:\n        print(\"Set your AutoTVM tracker node host and port variables to run the autotuner\")\n        exit()\n\n    # Get remote\n    if env.TARGET != \"sim\":\n\n        # Measure build start time\n        reconfig_start = time.time()\n\n        # Get remote from fleet node\n        remote = autotvm.measure.request_remote(\n            env.TARGET, tracker_host, int(tracker_port), timeout=10000\n        )\n\n        # Reconfigure the JIT runtime and FPGA.\n        # You can program the FPGA with your own custom bitstream\n        # by passing the path to the bitstream file instead of None.\n        vta.reconfig_runtime(remote)\n        vta.program_fpga(remote, bitstream=None)\n\n        # Report on reconfiguration time\n        reconfig_time = time.time() - reconfig_start\n        print(\"Reconfigured FPGA and RPC runtime in {0:.2f}s!\".format(reconfig_time))\n\n    # In simulation mode, host the RPC server locally.\n    else:\n        remote = rpc.LocalSession()\n\n    # VTA target and execution context\n    target = env.target if opt.device == \"vta\" else env.target_vta_cpu\n    ctx = remote.ext_dev(0) if opt.device == \"vta\" else remote.cpu(0)\n\n    # Compile Relay program\n    print(\"Initial compile...\")\n    relay_prog, params = compile_network(opt, env, target)\n\n    # Register VTA tuning tasks\n    register_vta_tuning_tasks()\n\n    # Perform task extraction on Relay program\n    print(\"Extracting tasks...\")\n    tasks = extract_from_program(\n        func=relay_prog,\n        params=params,\n        ops=(relay.op.get(\"nn.conv2d\"),),\n        target=tvm.target.Target(target, host=env.target_host),\n    )\n\n    # Perform Autotuning\n    print(\"Tuning...\")\n    tuning_opt = {\n        \"log_filename\": opt.log_filename,\n        \"tuner\": opt.tuner,\n        \"n_trial\": 1e9,\n        \"early_stopping\": None,\n        \"measure_option\": autotvm.measure_option(\n            builder=autotvm.LocalBuilder(build_func=vta.vta_autotvm_build_func),\n            runner=autotvm.RPCRunner(\n                env.TARGET,\n                tracker_host,\n                tracker_port,\n                number=4,\n                min_repeat_ms=150,\n                repeat=opt.measurements,\n                timeout=60,\n                # check_correctness=True, # TODO: re-enable when check_correctness works again.\n            ),\n        ),\n    }\n    tune_tasks(tasks, **tuning_opt)\n\n    # Compile kernels with history best records\n    with autotvm.tophub.context(target, extra_files=[opt.log_filename]):\n\n        # Compile network\n        print(\"Compiling network with best tuning parameters...\")\n        if target.device_name != \"vta\":\n            with tvm.transform.PassContext(opt_level=3, disabled_pass={\"AlterOpLayout\"}):\n                graph, lib, params = relay.build(\n                    relay_prog,\n                    target=tvm.target.Target(target, host=env.target_host),\n                    params=params,\n                )\n        else:\n            with vta.build_config(opt_level=3, disabled_pass={\"AlterOpLayout\"}):\n                graph, lib, params = relay.build(\n                    relay_prog,\n                    target=tvm.target.Target(target, host=env.target_host),\n                    params=params,\n                )\n\n        # Export library\n        temp = utils.tempdir()\n        lib.save(temp.relpath(\"graphlib.o\"))\n        remote.upload(temp.relpath(\"graphlib.o\"))\n        lib = remote.load_module(\"graphlib.o\")\n\n        # If detailed runtime info is needed build with debug runtime\n        if opt.debug_profile:\n            m = debug_executor.create(graph, lib, ctx)\n        else:\n            m = graph_executor.create(graph, lib, ctx)\n\n        # Set the network parameters and synthetic input\n        image = tvm.nd.array((np.random.uniform(size=(1, 3, 224, 224))).astype(\"float32\"))\n        m.set_input(**params)\n        m.set_input(\"data\", image)\n\n        # Perform inference\n        timer = m.module.time_evaluator(\"run\", ctx, number=4, repeat=opt.measurements)\n        tcost = timer()\n        prof_res = np.array(tcost.results) * 1000  # convert to millisecond\n        print(\n            \"Mean inference time (std dev): %.2f ms (%.2f ms)\"\n            % (np.mean(prof_res), np.std(prof_res))\n        )\n\n        # Display profile information\n        if opt.debug_profile:\n            m.run()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/de10nano/test_program_rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport sys, os\nimport tvm\nfrom tvm import rpc\nfrom vta import get_bitstream_path, download_bitstream, program_fpga, reconfig_runtime\n\nhost = os.environ.get(\"VTA_RPC_HOST\", \"de10nano\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n\ndef program_rpc_bitstream(path=None):\n    \"\"\"Program the FPGA on the RPC server\n\n    Parameters\n    ----------\n    path : path to bitstream (optional)\n    \"\"\"\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n    program_fpga(remote, path)\n\n\ndef reconfig_rpc_runtime():\n    \"\"\"Reconfig the RPC server runtime\"\"\"\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n    reconfig_runtime(remote)\n\n\nbitstream = sys.argv[1] if len(sys.argv) == 2 else None\nprogram_rpc_bitstream(bitstream)\nreconfig_rpc_runtime()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/integration/test_benchmark_gemm.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import utils\nimport vta.testing\nfrom vta.testing import simulator\n\n\ndef test_gemm():\n    def run_gemm_packed(env, remote, batch_size, channel, block):\n        data_shape = (batch_size // env.BATCH, channel // env.BLOCK_IN, env.BATCH, env.BLOCK_IN)\n        weight_shape = (\n            channel // env.BLOCK_OUT,\n            channel // env.BLOCK_IN,\n            env.BLOCK_OUT,\n            env.BLOCK_IN,\n        )\n        res_shape = (batch_size // env.BATCH, channel // env.BLOCK_OUT, env.BATCH, env.BLOCK_OUT)\n        # To compute number of ops, use a x2 factor for FMA\n        num_ops = 2 * channel * channel * batch_size\n\n        ko = te.reduce_axis((0, channel // env.BLOCK_IN), name=\"ko\")\n        ki = te.reduce_axis((0, env.BLOCK_IN), name=\"ki\")\n\n        data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n        weight = te.placeholder(weight_shape, name=\"weight\", dtype=env.wgt_dtype)\n        data_buf = te.compute(data_shape, lambda *i: data(*i), \"data_buf\")\n        weight_buf = te.compute(weight_shape, lambda *i: weight(*i), \"weight_buf\")\n        res_gem = te.compute(\n            res_shape,\n            lambda bo, co, bi, ci: te.sum(\n                data_buf[bo, ko, bi, ki].astype(env.acc_dtype)\n                * weight_buf[co, ko, ci, ki].astype(env.acc_dtype),\n                axis=[ko, ki],\n            ),\n            name=\"res_gem\",\n        )\n        res_shf = te.compute(res_shape, lambda *i: res_gem(*i) >> 8, name=\"res_shf\")\n        res_max = te.compute(res_shape, lambda *i: tvm.te.max(res_shf(*i), 0), \"res_max\")  # relu\n        res_min = te.compute(\n            res_shape, lambda *i: tvm.te.min(res_max(*i), (1 << (env.INP_WIDTH - 1)) - 1), \"res_min\"\n        )  # relu\n        res = te.compute(res_shape, lambda *i: res_min(*i).astype(env.inp_dtype), name=\"res\")\n\n        def verify(s):\n            mod = vta.build(\n                s,\n                [data, weight, res],\n                tvm.target.Target(\"ext_dev\", host=env.target_host),\n                name=\"gemm\",\n            )\n            temp = utils.tempdir()\n            mod.save(temp.relpath(\"gemm.o\"))\n            remote.upload(temp.relpath(\"gemm.o\"))\n            f = remote.load_module(\"gemm.o\")\n            # verify\n            dev = remote.ext_dev(0)\n            # Data in original format\n            data_orig = np.random.randint(-128, 128, size=(batch_size, channel)).astype(data.dtype)\n            weight_orig = np.random.randint(-128, 128, size=(channel, channel)).astype(weight.dtype)\n            data_packed = data_orig.reshape(\n                batch_size // env.BATCH, env.BATCH, channel // env.BLOCK_IN, env.BLOCK_IN\n            ).transpose((0, 2, 1, 3))\n            weight_packed = weight_orig.reshape(\n                channel // env.BLOCK_OUT, env.BLOCK_OUT, channel // env.BLOCK_IN, env.BLOCK_IN\n            ).transpose((0, 2, 1, 3))\n            res_np = np.zeros(res_shape).astype(res.dtype)\n            data_arr = tvm.nd.array(data_packed, dev)\n            weight_arr = tvm.nd.array(weight_packed, dev)\n            res_arr = tvm.nd.array(res_np, dev)\n            res_ref = np.zeros(res_shape).astype(env.acc_dtype)\n            for b in range(batch_size // env.BATCH):\n                for i in range(channel // env.BLOCK_OUT):\n                    for j in range(channel // env.BLOCK_IN):\n                        res_ref[b, i, :] += np.dot(\n                            data_packed[b, j, :].astype(env.acc_dtype),\n                            weight_packed[i, j].T.astype(env.acc_dtype),\n                        )\n            res_ref = np.right_shift(res_ref, 8)\n            res_ref = np.clip(res_ref, 0, (1 << (env.INP_WIDTH - 1)) - 1).astype(res.dtype)\n            time_f = f.time_evaluator(\"gemm\", dev, number=20)\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                simulator.clear_stats()\n            cost = time_f(data_arr, weight_arr, res_arr)\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                stats = simulator.stats()\n                print(\"Execution statistics:\")\n                for k, v in stats.items():\n                    print(\"\\t{:<16}: {:>16}\".format(k, v))\n            res_unpack = res_arr.numpy().reshape(\n                batch_size // env.BATCH, channel // env.BLOCK_OUT, env.BATCH, env.BLOCK_OUT\n            )\n            return cost\n\n        def run_schedule(load_inp, load_wgt, gemm, alu, store_out, print_ir):\n            s = te.create_schedule(res.op)\n            s[data_buf].set_scope(env.inp_scope)\n            s[weight_buf].set_scope(env.wgt_scope)\n            s[res_gem].set_scope(env.acc_scope)\n            s[res_shf].set_scope(env.acc_scope)\n            s[res_min].set_scope(env.acc_scope)\n            s[res_max].set_scope(env.acc_scope)\n\n            if block:\n                bblock = block // env.BATCH\n                iblock = block // env.BLOCK_IN\n                oblock = block // env.BLOCK_OUT\n                xbo, xco, xbi, xci = s[res].op.axis\n                xb1, xco1, xb2, xco2 = s[res].tile(xbo, xco, bblock, oblock)\n                store_pt = xb2\n\n                s[res_gem].compute_at(s[res], xco1)\n                s[res_shf].compute_at(s[res], xco1)\n                s[res_min].compute_at(s[res], xco1)\n                s[res_max].compute_at(s[res], xco1)\n\n                xbo, xco, xbi, xci = s[res_gem].op.axis\n                # Compute one line at a time\n                ko1, ko2 = s[res_gem].split(ko, iblock)\n                s[res_gem].reorder(ko1, ko2, xbo, xco, xbi, xci, ki)\n                s[data_buf].compute_at(s[res_gem], ko1)\n                s[weight_buf].compute_at(s[res_gem], ko1)\n                # Use VTA instructions\n                s[data_buf].pragma(s[data_buf].op.axis[0], load_inp)\n                s[weight_buf].pragma(s[weight_buf].op.axis[0], load_wgt)\n                s[res_gem].tensorize(xbi, gemm)\n                s[res_shf].pragma(s[res_shf].op.axis[0], alu)\n                s[res_min].pragma(s[res_min].op.axis[0], alu)\n                s[res_max].pragma(s[res_max].op.axis[0], alu)\n                s[res].pragma(store_pt, store_out)\n            else:\n                xbo, xco, xbi, xci = s[res_gem].op.axis\n                s[res_gem].reorder(ko, xbo, xco, xbi, xci, ki)\n                # Use VTA instructions\n                s[data_buf].pragma(s[data_buf].op.axis[0], load_inp)\n                s[weight_buf].pragma(s[weight_buf].op.axis[0], load_wgt)\n                s[res_gem].tensorize(xbi, gemm)\n                s[res_shf].pragma(s[res_shf].op.axis[0], alu)\n                s[res_min].pragma(s[res_min].op.axis[0], alu)\n                s[res_max].pragma(s[res_max].op.axis[0], alu)\n                s[res].pragma(s[res].op.axis[0], store_out)\n\n            if print_ir:\n                print(tvm.lower(s, [data, weight, res], simple_mode=True))\n            return verify(s)\n\n        def gemm_normal(print_ir):\n            mock = env.mock\n            print(\"----- GEMM GOPS End-to-End Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    env.dma_copy,\n                    env.dma_copy,\n                    env.gemm,\n                    env.alu,\n                    env.dma_copy,\n                    print_ir,\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                print(header)\n                print(\"\\tTime cost = %g sec/op, %g GOPS\" % (cost.mean, gops))\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n\n        def gemm_unittest(print_ir):\n            mock = env.mock\n            print(\"----- GEMM Unit Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    mock.dma_copy, mock.dma_copy, env.gemm, mock.alu, mock.dma_copy, print_ir\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                print(header)\n                print(\"\\tTime cost = %g sec/op, %g GOPS\" % (cost.mean, gops))\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n\n        def alu_unittest(print_ir):\n            mock = env.mock\n            print(\"----- ALU Unit Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    mock.dma_copy, mock.dma_copy, mock.gemm, env.alu, mock.dma_copy, print_ir\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                print(header)\n                print(\"\\tTime cost = %g sec/op, %g GOPS\" % (cost.mean, gops))\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n            print(\"\")\n\n        def load_inp_unittest(print_ir):\n            mock = env.mock\n            print(\"----- LoadInp Unit Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    env.dma_copy, mock.dma_copy, mock.gemm, mock.alu, mock.dma_copy, print_ir\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                bandwith = (batch_size * channel * env.INP_WIDTH / cost.mean) / float(10**9)\n                print(header)\n                print(\n                    \"\\tTime cost = %g sec/op, %g GOPS, bandwidth=%g Gbits\"\n                    % (cost.mean, gops, bandwith)\n                )\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n            print(\"\")\n\n        def load_wgt_unittest(print_ir):\n            mock = env.mock\n            print(\"----- LoadWgt Unit Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    mock.dma_copy, env.dma_copy, mock.gemm, mock.alu, mock.dma_copy, print_ir\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                bandwith = (channel * channel * env.WGT_WIDTH / cost.mean) / float(10**9)\n                print(header)\n                print(\n                    \"\\tTime cost = %g sec/op, %g GOPS, bandwidth=%g Gbits\"\n                    % (cost.mean, gops, bandwith)\n                )\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n            print(\"\")\n\n        def store_out_unittest(print_ir):\n            mock = env.mock\n            print(\"----- StoreOut Unit Test-------\")\n\n            def run_test(header, print_ir):\n                cost = run_schedule(\n                    mock.dma_copy, mock.dma_copy, mock.gemm, mock.alu, env.dma_copy, print_ir\n                )\n                gops = (num_ops / cost.mean) / float(10**9)\n                bandwith = (batch_size * channel * env.OUT_WIDTH / cost.mean) / float(10**9)\n                print(header)\n                print(\n                    \"\\tTime cost = %g sec/op, %g GOPS, bandwidth=%g Gbits\"\n                    % (cost.mean, gops, bandwith)\n                )\n\n            with vta.build_config():\n                run_test(\"NORMAL\", print_ir)\n            print(\"\")\n\n        gemm_normal(False)\n        gemm_unittest(False)\n        alu_unittest(False)\n\n    def _run(env, remote):\n        print(\"========GEMM 128=========\")\n        run_gemm_packed(env, remote, 128, 128, 128)\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_gemm()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/integration/test_benchmark_topi_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Testing topi conv2d operator for VTA\"\"\"\n\nimport json\nimport os\n\nimport pytest\nimport numpy as np\nfrom collections import namedtuple\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.contrib import utils\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm import topi\nimport tvm.topi.testing\nimport vta\nfrom vta import program_fpga, reconfig_runtime\nimport vta.testing\nfrom vta.testing import simulator\n\n\nWorkload = namedtuple(\n    \"Conv2DWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n    ],\n)\n\n# Get batch info from env\nenv = vta.get_env()\n\n# ResNet18 workloads\nresnet_wkls = [\n    # Workloads of resnet18 on imagenet\n    # ('resnet-18.C1',  Workload(env.BATCH, 224, 224, 3,   64,  7, 7, 3, 3, 2, 2)),\n    (\"resnet-18.C2\", Workload(env.BATCH, 56, 56, 64, 64, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C3\", Workload(env.BATCH, 56, 56, 64, 128, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C4\", Workload(env.BATCH, 56, 56, 64, 128, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C5\", Workload(env.BATCH, 28, 28, 128, 128, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C6\", Workload(env.BATCH, 28, 28, 128, 256, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C7\", Workload(env.BATCH, 28, 28, 128, 256, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C8\", Workload(env.BATCH, 14, 14, 256, 256, 3, 3, 1, 1, 1, 1)),\n    (\"resnet-18.C9\", Workload(env.BATCH, 14, 14, 256, 512, 3, 3, 1, 1, 2, 2)),\n    (\"resnet-18.C10\", Workload(env.BATCH, 14, 14, 256, 512, 1, 1, 0, 0, 2, 2)),\n    (\"resnet-18.C11\", Workload(env.BATCH, 7, 7, 512, 512, 3, 3, 1, 1, 1, 1)),\n]\n\n# FIXME: we need a custom clip operator to circumvent a pattern detection limitation\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef run_conv2d(env, remote, wl, target, check_correctness=True, print_ir=False, samples=4):\n\n    # Workload assertions\n    assert wl.hpad == wl.wpad\n\n    # Perform packing only if we are targeting the accelerator\n    if \"arm_cpu\" in target.keys:\n        data_pack = False\n        layout = \"NCHW\"\n        conv2d_fcompute = topi.arm_cpu.conv2d_nchw_spatial_pack\n        conv2d_fschedule = topi.arm_cpu.schedule_conv2d_nchw_spatial_pack\n    elif \"vta\" in target.keys:\n        data_pack = True\n        layout = \"NCHW%dn%dc\" % (env.BATCH, env.BLOCK_IN)\n        conv2d_fcompute = vta.top.conv2d_packed\n        conv2d_fschedule = vta.top.schedule_conv2d_packed\n\n    # Derive shapes depending upon packing\n    a_shape = (wl.batch, wl.in_filter, wl.height, wl.width)\n    w_shape = (wl.out_filter, wl.in_filter, wl.hkernel, wl.wkernel)\n    b_shape = (wl.batch, wl.out_filter, 1, 1)\n    if data_pack:\n        data_shape = (\n            wl.batch // env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            wl.height,\n            wl.width,\n            env.BATCH,\n            env.BLOCK_IN,\n        )\n        kernel_shape = (\n            wl.out_filter // env.BLOCK_OUT,\n            wl.in_filter // env.BLOCK_IN,\n            wl.hkernel,\n            wl.wkernel,\n            env.BLOCK_OUT,\n            env.BLOCK_IN,\n        )\n        bias_shape = (\n            wl.batch // env.BATCH,\n            wl.out_filter // env.BLOCK_OUT,\n            1,\n            1,\n            env.BATCH,\n            env.BLOCK_OUT,\n        )\n    else:\n        data_shape = a_shape\n        kernel_shape = w_shape\n        bias_shape = b_shape\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n    bias = te.placeholder(bias_shape, name=\"bias\", dtype=env.acc_dtype)\n    padding = relay.nn.get_pad_tuple2d((wl.hpad, wl.wpad))\n\n    # Define base computation schedule\n    with target:\n        if data_pack:\n            res = conv2d_fcompute(\n                data, kernel, (wl.hstride, wl.wstride), padding, (1, 1), layout, env.acc_dtype\n            )\n        else:\n            res = conv2d_fcompute(\n                data, kernel, (wl.hstride, wl.wstride), padding, (1, 1), env.acc_dtype\n            )\n        res = topi.right_shift(res, 8)\n        res = topi.add(res, bias)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n        # Derive base schedule\n        s = conv2d_fschedule([res])\n        if print_ir:\n            print(vta.lower(s, [data, kernel, bias, res], simple_mode=True))\n\n    # Derive number of ops\n    fout_height = (wl.height + 2 * wl.hpad - wl.hkernel) // wl.hstride + 1\n    fout_width = (wl.width + 2 * wl.wpad - wl.wkernel) // wl.wstride + 1\n    num_ops = (\n        2\n        * wl.batch\n        * fout_height\n        * fout_width\n        * wl.hkernel\n        * wl.wkernel\n        * wl.out_filter\n        * wl.in_filter\n    )\n\n    # @memoize(\"vta.tests.test_benchmark_topi.conv2d.verify_nhwc\")\n    def get_ref_data():\n        # derive min max for act, wgt, and bias types (max non inclusive)\n        a_min, a_max = 0 - (1 << (env.INP_WIDTH - 1)), (1 << (env.INP_WIDTH - 1))\n        w_min, w_max = 0 - (1 << (env.WGT_WIDTH - 1)), (1 << (env.WGT_WIDTH - 1))\n        b_min, b_max = 0 - 1 << (env.INP_WIDTH + env.WGT_WIDTH - 2), 1 << (\n            env.INP_WIDTH + env.WGT_WIDTH - 2\n        )\n        a_np = np.random.randint(a_min, a_max, size=a_shape).astype(data.dtype)\n        w_np = np.random.randint(w_min, w_max, size=w_shape).astype(kernel.dtype)\n        b_np = np.random.randint(b_min, b_max, size=b_shape).astype(env.acc_dtype)\n        r_np = tvm.topi.testing.conv2d_nchw_python(\n            a_np.astype(env.acc_dtype),\n            w_np.astype(env.acc_dtype),\n            (wl.hstride, wl.wstride),\n            wl.hpad,\n        ).astype(env.acc_dtype)\n        return a_np, w_np, b_np, r_np\n\n    # Data in original format\n    data_np, kernel_np, bias_np, res_ref = get_ref_data()\n    if data_pack:\n        data_np = data_np.reshape(\n            wl.batch // env.BATCH,\n            env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.height,\n            wl.width,\n        ).transpose((0, 2, 4, 5, 1, 3))\n        kernel_np = kernel_np.reshape(\n            wl.out_filter // env.BLOCK_OUT,\n            env.BLOCK_OUT,\n            wl.in_filter // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.hkernel,\n            wl.wkernel,\n        ).transpose((0, 2, 4, 5, 1, 3))\n        bias_np = bias_np.reshape(\n            wl.batch // env.BATCH, wl.out_filter // env.BLOCK_OUT, 1, 1, env.BATCH, env.BLOCK_OUT\n        )\n\n    # Build\n    if \"vta\" in target.keys:\n        with vta.build_config(disabled_pass={\"tir.CommonSubexprElimTIR\"}):\n            mod = vta.build(\n                s,\n                [data, kernel, bias, res],\n                target=tvm.target.Target(target, host=env.target_host),\n                name=\"conv2d\",\n            )\n    else:\n        mod = tvm.build(\n            s,\n            [data, kernel, bias, res],\n            target=tvm.target.Target(target, host=env.target_host),\n            name=\"conv2d\",\n        )\n    temp = utils.tempdir()\n    mod.save(temp.relpath(\"conv2d.o\"))\n    remote.upload(temp.relpath(\"conv2d.o\"))\n    f = remote.load_module(\"conv2d.o\")\n    dev = remote.device(str(target))\n\n    res_np = np.zeros(topi.utils.get_const_tuple(res.shape)).astype(res.dtype)\n    data_arr = tvm.nd.array(data_np, dev)\n    kernel_arr = tvm.nd.array(kernel_np, dev)\n    bias_arr = tvm.nd.array(bias_np, dev)\n    res_arr = tvm.nd.array(res_np, dev)\n    time_f = f.time_evaluator(\"conv2d\", dev, number=samples)\n\n    # In vta sim mode, collect simulator runtime statistics\n    stats = {}\n    cost = None\n    if env.TARGET in [\"sim\", \"tsim\"]:\n        # Check if we're in local RPC mode (allows us to rebuild the\n        # runtime on the fly when varying the VTA designs)\n        local_rpc = int(os.environ.get(\"VTA_LOCAL_SIM_RPC\", \"0\"))\n        if local_rpc:\n            if env.TARGET == \"sim\":\n                remote.get_function(\"vta.simulator.profiler_clear\")()\n            else:\n                remote.get_function(\"vta.tsim.profiler_clear\")()\n            cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n            if env.TARGET == \"sim\":\n                stats = json.loads(remote.get_function(\"vta.simulator.profiler_status\")())\n            else:\n                stats = json.loads(remote.get_function(\"vta.tsim.profiler_status\")())\n        else:\n            simulator.clear_stats()\n            cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n            stats = simulator.stats()\n    else:\n        cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n\n    # Check correctness\n    correct = False\n    if check_correctness:\n        res_orig = res_arr.numpy()\n        if data_pack:\n            res_orig = res_orig.transpose((0, 4, 1, 5, 2, 3)).reshape(\n                wl.batch, wl.out_filter, fout_height, fout_width\n            )\n            bias_np = bias_np.transpose((0, 4, 1, 5, 2, 3)).reshape(wl.batch, wl.out_filter, 1, 1)\n        res_ref = res_ref >> env.WGT_WIDTH\n        res_ref += bias_np\n        res_ref = np.clip(res_ref, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res_ref = res_ref.astype(env.out_dtype)\n        correct = np.allclose(res_orig, res_ref)\n\n    gops = (num_ops / cost.mean) / float(10**9)\n    status = \"PASSED\" if correct else \"FAILED\"\n    if \"arm_cpu\" in target.keys:\n        device = \"CPU\"\n    elif \"vta\" in target.keys:\n        device = \"VTA\"\n    print(\"%s CONV2D TEST %s: Time cost = %g sec/op, %g GOPS\" % (device, status, cost.mean, gops))\n\n    return correct, cost, stats\n\n\n@pytest.mark.parametrize(\"device\", [\"vta\", \"arm_cpu\"])\ndef test_conv2d(device):\n    def _run(env, remote):\n        if device == \"vta\":\n            target = env.target\n            if env.TARGET not in [\"sim\", \"tsim\", \"intelfocl\"]:\n                assert tvm.runtime.enabled(\"rpc\")\n                program_fpga(remote, bitstream=None)\n                reconfig_runtime(remote)\n        elif device == \"arm_cpu\":\n            target = env.target_vta_cpu\n        with autotvm.tophub.context(target):  # load pre-tuned schedule parameters\n            for _, wl in resnet_wkls:\n                print(wl)\n                run_conv2d(env, remote, wl, target)\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_conv2d(device=\"arm_cpu\")\n    test_conv2d(device=\"vta\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/integration/test_benchmark_topi_conv2d_transpose.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Testing topi conv2d_transpose operator for VTA\"\"\"\n\nimport json\nimport os\n\nimport pytest\nimport numpy as np\nfrom collections import namedtuple\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.contrib import utils\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm import topi\nimport tvm.topi.testing\nimport vta\nfrom vta import program_fpga, reconfig_runtime\nimport vta.testing\nfrom vta.testing import simulator\n\n\nWorkload = namedtuple(\n    \"Conv2DTransposeWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n        \"o_hpad\",\n        \"o_wpad\",\n    ],\n)\n\n# Get batch info from env\nenv = vta.get_env()\n\n# DCGAN workloads\ndcgan_wklds = [\n    # dcgan\n    (\"DCGAN.CT1\", Workload(env.BATCH, 4, 4, 1024, 512, 4, 4, 1, 1, 2, 2, 0, 0)),\n    (\"DCGAN.CT2\", Workload(env.BATCH, 8, 8, 512, 256, 4, 4, 1, 1, 2, 2, 0, 0)),\n    (\"DCGAN.CT3\", Workload(env.BATCH, 16, 16, 256, 128, 4, 4, 1, 1, 2, 2, 0, 0)),\n]\n\n# FIXME: we need a custom clip operator to circumvent a pattern detection limitation\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\n# Helper function to get factors\ndef _find_factors(n):\n    factors = []\n    for f in range(1, n + 1):\n        if n % f == 0:\n            factors.append(f)\n    return factors\n\n\ndef run_conv2d_transpose(\n    env, remote, wl, target, check_correctness=True, print_ir=False, samples=4\n):\n\n    # Workload assertions\n    assert wl.hpad == wl.wpad\n\n    # Perform packing only if we are targeting the accelerator\n    if \"arm_cpu\" in target.keys:\n        data_pack = False\n        layout = \"NCHW\"\n        fcompute = topi.arm_cpu.conv2d_transpose_nchw\n        fschedule = topi.arm_cpu.schedule_conv2d_transpose_nchw\n    elif \"vta\" in target.keys:\n        data_pack = True\n        layout = \"NCHW%dn%dc\" % (env.BATCH, env.BLOCK_IN)\n        fcompute = vta.top.conv2d_transpose_packed\n        fschedule = vta.top.schedule_conv2d_transpose_packed\n\n    # Derive shapes depending upon packing\n\n    a_shape = (wl.batch, wl.in_filter, wl.height, wl.width)\n    w_shape = (wl.in_filter, wl.out_filter, wl.hkernel, wl.wkernel)\n    if data_pack:\n        data_shape = (\n            wl.batch // env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            wl.height,\n            wl.width,\n            env.BATCH,\n            env.BLOCK_IN,\n        )\n        kernel_shape = (\n            wl.out_filter // env.BLOCK_OUT,\n            wl.in_filter // env.BLOCK_IN,\n            wl.hkernel,\n            wl.wkernel,\n            env.BLOCK_OUT,\n            env.BLOCK_IN,\n        )\n    else:\n        data_shape = a_shape\n        kernel_shape = w_shape\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n    padding = relay.nn.get_pad_tuple2d((wl.hpad, wl.wpad))\n\n    # Define base computation schedule\n    with target:\n\n        res = fcompute(\n            data, kernel, (wl.hstride, wl.wstride), padding, env.acc_dtype, (wl.o_hpad, wl.o_wpad)\n        )\n        res = topi.right_shift(res, env.WGT_WIDTH)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n        # Derive base schedule\n        s = fschedule([res])\n        if print_ir:\n            print(vta.lower(s, [data, kernel, res], simple_mode=True))\n\n    # Derive number of ops\n    fout_height = (wl.height - 1) * wl.hstride - 2 * wl.hpad + wl.hkernel + wl.o_hpad\n    fout_width = (wl.width - 1) * wl.wstride - 2 * wl.wpad + wl.wkernel + wl.o_wpad\n    num_ops = (\n        2\n        * wl.batch\n        * fout_height\n        * fout_width\n        * wl.hkernel\n        * wl.wkernel\n        * wl.out_filter\n        * wl.in_filter\n    )\n\n    # @memoize(\"vta.tests.test_benchmark_topi.conv2d.verify_nhwc\")\n    def get_ref_data():\n        # derive min max for act and wgt types (max non inclusive)\n        a_min, a_max = 0 - (1 << (env.INP_WIDTH - 1)), (1 << (env.INP_WIDTH - 1))\n        w_min, w_max = 0 - (1 << (env.WGT_WIDTH - 1)), (1 << (env.WGT_WIDTH - 1))\n        a_np = np.random.randint(a_min, a_max, size=a_shape).astype(data.dtype)\n        w_np = np.random.randint(\n            w_min, w_max, size=(wl.in_filter, wl.out_filter, wl.hkernel, wl.wkernel)\n        ).astype(kernel.dtype)\n        r_np = tvm.topi.testing.conv2d_transpose_nchw_python(\n            a_np.astype(env.acc_dtype),\n            w_np.astype(env.acc_dtype),\n            (wl.hstride, wl.wstride),\n            wl.hpad,\n            (wl.o_hpad, wl.o_wpad),\n        ).astype(env.acc_dtype)\n        return a_np, w_np, r_np\n\n    # Data in original format\n    data_np, kernel_np, res_ref = get_ref_data()\n    if data_pack:\n        data_np = data_np.reshape(\n            wl.batch // env.BATCH,\n            env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.height,\n            wl.width,\n        ).transpose((0, 2, 4, 5, 1, 3))\n        kernel_np = kernel_np.reshape(\n            wl.in_filter // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.out_filter // env.BLOCK_OUT,\n            env.BLOCK_OUT,\n            wl.hkernel,\n            wl.wkernel,\n        ).transpose((2, 0, 4, 5, 3, 1))\n        kernel_np = np.flip(kernel_np, 2)\n        kernel_np = np.flip(kernel_np, 3)\n\n    # Build\n    if \"vta\" in target.keys:\n        with vta.build_config(disabled_pass={\"tir.CommonSubexprElimTIR\"}):\n            mod = vta.build(\n                s,\n                [data, kernel, res],\n                target=target,\n                target_host=env.target_host,\n                name=\"conv2d_transpose\",\n            )\n    else:\n        mod = tvm.build(\n            s,\n            [data, kernel, res],\n            target=target,\n            target_host=env.target_host,\n            name=\"conv2d_transpose\",\n        )\n    temp = utils.tempdir()\n    mod.save(temp.relpath(\"conv2d_transpose.o\"))\n    remote.upload(temp.relpath(\"conv2d_transpose.o\"))\n    f = remote.load_module(\"conv2d_transpose.o\")\n    dev = remote.device(str(target))\n\n    res_np = np.zeros(topi.utils.get_const_tuple(res.shape)).astype(res.dtype)\n    data_arr = tvm.nd.array(data_np, dev)\n    kernel_arr = tvm.nd.array(kernel_np, dev)\n    res_arr = tvm.nd.array(res_np, dev)\n    time_f = f.time_evaluator(\"conv2d_transpose\", dev, number=samples)\n\n    # In vta sim mode, collect simulator runtime statistics\n    stats = {}\n    cost = None\n    if env.TARGET in [\"sim\", \"tsim\"]:\n        # Check if we're in local RPC mode (allows us to rebuild the\n        # runtime on the fly when varying the VTA designs)\n        local_rpc = int(os.environ.get(\"VTA_LOCAL_SIM_RPC\", \"0\"))\n        if local_rpc:\n            if env.TARGET == \"sim\":\n                remote.get_function(\"vta.simulator.profiler_clear\")()\n            else:\n                remote.get_function(\"vta.tsim.profiler_clear\")()\n            cost = time_f(data_arr, kernel_arr, res_arr)\n            if env.TARGET == \"sim\":\n                stats = json.loads(remote.get_function(\"vta.simulator.profiler_status\")())\n            else:\n                stats = json.loads(remote.get_function(\"vta.tsim.profiler_status\")())\n        else:\n            simulator.clear_stats()\n            cost = time_f(data_arr, kernel_arr, res_arr)\n            stats = simulator.stats()\n    else:\n        cost = time_f(data_arr, kernel_arr, res_arr)\n\n    # Check correctness\n    correct = False\n    if check_correctness:\n        res_orig = res_arr.numpy()\n        if data_pack:\n            res_orig = res_orig.transpose((0, 4, 1, 5, 2, 3)).reshape(\n                wl.batch, wl.out_filter, fout_height, fout_width\n            )\n        res_ref = res_ref >> env.WGT_WIDTH\n        res_ref = np.clip(res_ref, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res_ref = res_ref.astype(env.out_dtype)\n        correct = np.allclose(res_orig, res_ref)\n\n    gops = (num_ops / cost.mean) / float(10**9)\n    status = \"PASSED\" if correct else \"FAILED\"\n    if \"arm_cpu\" in target.keys:\n        device = \"CPU\"\n    elif \"vta\" in target.keys:\n        device = \"VTA\"\n    print(\"%s CONV2D TEST %s: Time cost = %g sec/op, %g GOPS\" % (device, status, cost.mean, gops))\n\n    return correct, cost, stats\n\n\n@pytest.mark.parametrize(\"device\", [\"vta\", \"arm_cpu\"])\ndef test_conv2d_transpose(device):\n    def _run(env, remote):\n        if device == \"vta\":\n            target = env.target\n            if env.TARGET not in [\"sim\", \"tsim\"]:\n                assert tvm.runtime.enabled(\"rpc\")\n                program_fpga(remote, bitstream=None)\n                reconfig_runtime(remote)\n        elif device == \"arm_cpu\":\n            target = env.target_vta_cpu\n        with autotvm.tophub.context(target):  # load pre-tuned schedule parameters\n            for _, wl in dcgan_wklds:\n                print(wl)\n                run_conv2d_transpose(env, remote, wl, target)\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_conv2d_transpose(device=\"arm_cpu\")\n    test_conv2d_transpose(device=\"vta\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/integration/test_benchmark_topi_dense.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Testing topi gemm operator for VTA\"\"\"\n\nimport os\nimport json\nfrom collections import namedtuple\n\nimport numpy as np\n\nimport tvm\nfrom tvm import te\nfrom tvm import autotvm\nfrom tvm.contrib import utils\nfrom tvm.contrib.pickle_memoize import memoize\nfrom tvm import topi\nimport tvm.topi.testing\nimport vta\nfrom vta import program_fpga, reconfig_runtime\nimport vta.testing\nfrom vta.testing import simulator\n\n# FIXME: we need a custom clip operator to circumvent a pattern detection limitation\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef run_gemm(\n    env,\n    remote,\n    target,\n    batch_size,\n    in_feat,\n    out_feat,\n    check_correctness=True,\n    print_ir=True,\n    samples=4,\n):\n\n    # Perform packing only if we are targeting the accelerator\n    if \"arm_cpu\" in target.keys:\n        data_pack = False\n    elif \"vta\" in target.keys:\n        data_pack = True\n\n    # Derive shapes depending upon packing\n    a_shape = (batch_size, in_feat)\n    w_shape = (out_feat, in_feat)\n    if data_pack:\n        data_shape = (batch_size // env.BATCH, in_feat // env.BLOCK_IN, env.BATCH, env.BLOCK_IN)\n        kernel_shape = (\n            out_feat // env.BLOCK_OUT,\n            in_feat // env.BLOCK_IN,\n            env.BLOCK_OUT,\n            env.BLOCK_IN,\n        )\n        fcompute = vta.top.dense_packed\n        fschedule = vta.top.schedule_dense_packed\n    else:\n        data_shape = a_shape\n        kernel_shape = w_shape\n        fcompute = topi.x86.dense_nopack\n        fschedule = topi.x86.schedule_dense_nopack\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n\n    # Define base computation schedule\n    with target:\n        res = fcompute(data, kernel, None, env.acc_dtype)\n        res = topi.right_shift(res, 8)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n        # Derive base schedule\n        s = fschedule([res])\n        if print_ir:\n            print(vta.lower(s, [data, kernel, res], simple_mode=True))\n\n    # Derive number of ops\n    num_ops = 2 * batch_size * in_feat * out_feat\n\n    # @memoize(\"vta.tests.test_benchmark_topi.dense.verify\")\n    def get_ref_data():\n        # derive min max for act, wgt types (max non inclusive)\n        a_min, a_max = 0 - (1 << (env.INP_WIDTH - 1)), (1 << (env.INP_WIDTH - 1))\n        w_min, w_max = 0 - (1 << (env.WGT_WIDTH - 1)), (1 << (env.WGT_WIDTH - 1))\n        a_np = np.random.randint(a_min, a_max, size=a_shape).astype(data.dtype)\n        w_np = np.random.randint(w_min, w_max, size=w_shape).astype(kernel.dtype)\n\n        r_np = np.dot(a_np.astype(env.acc_dtype), w_np.T.astype(env.acc_dtype)).astype(\n            env.acc_dtype\n        )\n        return a_np, w_np, r_np\n\n    # Data in original format\n    data_np, kernel_np, res_ref = get_ref_data()\n    if data_pack:\n        data_np = data_np.reshape(\n            batch_size // env.BATCH, env.BATCH, in_feat // env.BLOCK_IN, env.BLOCK_IN\n        ).transpose((0, 2, 1, 3))\n        kernel_np = kernel_np.reshape(\n            out_feat // env.BLOCK_OUT, env.BLOCK_OUT, in_feat // env.BLOCK_IN, env.BLOCK_IN\n        ).transpose((0, 2, 1, 3))\n\n    # Build\n    if \"vta\" in target.keys:\n        mod = vta.build(\n            s,\n            [data, kernel, res],\n            target=tvm.target.Target(target, host=env.target_host),\n            name=\"dense\",\n        )\n    else:\n        mod = tvm.build(\n            s,\n            [data, kernel, res],\n            target=tvm.target.Target(target, host=env.target_host),\n            name=\"dense\",\n        )\n    temp = utils.tempdir()\n    mod.save(temp.relpath(\"dense.o\"))\n    remote.upload(temp.relpath(\"dense.o\"))\n    f = remote.load_module(\"dense.o\")\n    dev = remote.device(str(target))\n\n    res_np = np.zeros(topi.utils.get_const_tuple(res.shape)).astype(res.dtype)\n    data_arr = tvm.nd.array(data_np, dev)\n    kernel_arr = tvm.nd.array(kernel_np, dev)\n    res_arr = tvm.nd.array(res_np, dev)\n    time_f = f.time_evaluator(\"dense\", dev, number=samples)\n\n    # In vta sim mode, collect simulator runtime statistics\n    stats = {}\n    cost = None\n    if env.TARGET in [\"sim\", \"tsim\"]:\n        # Check if we're in local RPC mode (allows us to rebuild the\n        # runtime on the fly when varying the VTA designs)\n        local_rpc = int(os.environ.get(\"VTA_LOCAL_SIM_RPC\", \"0\"))\n        if local_rpc:\n            if env.TARGET == \"sim\":\n                remote.get_function(\"vta.simulator.profiler_clear\")()\n            else:\n                remote.get_function(\"vta.tsim.profiler_clear\")()\n            cost = time_f(data_arr, kernel_arr, res_arr)\n            if env.TARGET == \"sim\":\n                stats = json.loads(remote.get_function(\"vta.simulator.profiler_status\")())\n            else:\n                stats = json.loads(remote.get_function(\"vta.tsim.profiler_status\")())\n        else:\n            simulator.clear_stats()\n            cost = time_f(data_arr, kernel_arr, res_arr)\n            stats = simulator.stats()\n    else:\n        cost = time_f(data_arr, kernel_arr, res_arr)\n\n    # Check correctness\n    correct = False\n    if check_correctness:\n        res_orig = res_arr.numpy()\n        if data_pack:\n            res_orig = res_orig.reshape(batch_size, out_feat)\n        res_ref = res_ref >> 8\n        res_ref = np.clip(res_ref, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res_ref = res_ref.astype(env.out_dtype)\n        correct = np.allclose(res_orig, res_ref)\n\n    gops = (num_ops / cost.mean) / float(10**9)\n    status = \"PASSED\" if correct else \"FAILED\"\n    if \"arm_cpu\" in target.keys:\n        device = \"CPU\"\n    elif \"vta\" in target.keys:\n        device = \"VTA\"\n    print(\"%s DENSE TEST %s: Time cost = %g sec/op, %g GOPS\" % (device, status, cost.mean, gops))\n\n    return correct, cost, stats\n\n\ndef test_gemm(device=\"vta\", batch=128, in_feat=128, out_feat=128):\n    def _run(env, remote):\n        if device == \"vta\":\n            target = env.target\n            if env.TARGET not in [\"sim\", \"tsim\"]:\n                assert tvm.runtime.enabled(\"rpc\")\n                program_fpga(remote, bitstream=None)\n                reconfig_runtime(remote)\n        elif device == \"arm_cpu\":\n            target = env.target_vta_cpu\n        with autotvm.tophub.context(target):  # load pre-tuned schedule parameters\n            run_gemm(env, remote, target, batch, in_feat, out_feat)\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_gemm(\"vta\", 16, 512, 1008)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/integration/test_benchmark_topi_group_conv2d.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Testing topi group conv2d operator for VTA\"\"\"\n\nimport json\nimport os\n\nimport pytest\nimport numpy as np\nfrom collections import namedtuple\n\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm import autotvm\nfrom tvm.contrib import utils\nfrom tvm import topi\nimport tvm.topi.testing\nimport vta\nfrom vta import program_fpga, reconfig_runtime\nimport vta.testing\nfrom vta.testing import simulator\n\n\nWorkload = namedtuple(\n    \"GroupConv2DWorkload\",\n    [\n        \"batch\",\n        \"height\",\n        \"width\",\n        \"in_filter\",\n        \"out_filter\",\n        \"groups\",\n        \"hkernel\",\n        \"wkernel\",\n        \"hpad\",\n        \"wpad\",\n        \"hstride\",\n        \"wstride\",\n    ],\n)\n\n# Get batch info from env\nenv = vta.get_env()\n\n# Mobilenet (grouped variant) workloads\nmobilenet_wkls = [\n    (\"mobilenet.D1\", Workload(env.BATCH, 112, 112, 32, 32, 2, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D2\", Workload(env.BATCH, 112, 112, 64, 64, 4, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D3\", Workload(env.BATCH, 56, 56, 128, 128, 8, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D4\", Workload(env.BATCH, 56, 56, 128, 128, 8, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D5\", Workload(env.BATCH, 28, 28, 256, 256, 16, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D6\", Workload(env.BATCH, 28, 28, 256, 256, 16, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D7\", Workload(env.BATCH, 14, 14, 512, 512, 32, 3, 3, 1, 1, 1, 1)),\n    (\"mobilenet.D8\", Workload(env.BATCH, 14, 14, 512, 512, 32, 3, 3, 1, 1, 2, 2)),\n    (\"mobilenet.D9\", Workload(env.BATCH, 7, 7, 1024, 1024, 64, 3, 3, 1, 1, 1, 1)),\n]\n\n# FIXME: we need a custom clip operator to circumvent a pattern detection limitation\n@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\ndef my_clip(x, a_min, a_max):\n    \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n    const_min = tvm.tir.const(a_min, x.dtype)\n    const_max = tvm.tir.const(a_max, x.dtype)\n    x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n    x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n    return x\n\n\ndef run_group_conv2d(env, remote, wl, target, check_correctness=True, print_ir=False, samples=4):\n\n    # Workload assertions\n    assert wl.hpad == wl.wpad\n\n    # Perform packing only if we are targeting the accelerator\n    if \"arm_cpu\" in target.keys:\n        data_pack = False\n        layout = \"NCHW\"\n        fcompute = topi.nn.group_conv2d_nchw\n        fschedule = topi.generic.schedule_group_conv2d_nchw\n    elif \"vta\" in target.keys:\n        data_pack = True\n        layout = \"NCHW%dn%dc\" % (env.BATCH, env.BLOCK_IN)\n        fcompute = vta.top.group_conv2d_packed\n        fschedule = vta.top.schedule_group_conv2d_packed\n\n    # Derive shapes depending upon packing\n    CI_G = wl.in_filter // wl.groups\n    a_shape = (wl.batch, wl.in_filter, wl.height, wl.width)\n    w_shape = (wl.out_filter, CI_G, wl.hkernel, wl.wkernel)\n    b_shape = (wl.batch, wl.out_filter, 1, 1)\n    if data_pack:\n        data_shape = (\n            wl.batch // env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            wl.height,\n            wl.width,\n            env.BATCH,\n            env.BLOCK_IN,\n        )\n        kernel_shape = (\n            wl.out_filter // env.BLOCK_OUT,\n            CI_G // env.BLOCK_IN,\n            wl.hkernel,\n            wl.wkernel,\n            env.BLOCK_OUT,\n            env.BLOCK_IN,\n        )\n        bias_shape = (\n            wl.batch // env.BATCH,\n            wl.out_filter // env.BLOCK_OUT,\n            1,\n            1,\n            env.BATCH,\n            env.BLOCK_OUT,\n        )\n    else:\n        data_shape = a_shape\n        kernel_shape = w_shape\n        bias_shape = b_shape\n    data = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\n    kernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n    bias = te.placeholder(bias_shape, name=\"bias\", dtype=env.acc_dtype)\n    padding = relay.nn.get_pad_tuple2d((wl.hpad, wl.wpad))\n\n    # Define base computation schedule\n    with target:\n        res = fcompute(\n            data, kernel, (wl.hstride, wl.wstride), padding, (1, 1), wl.groups, env.acc_dtype\n        )\n        res = topi.right_shift(res, 8)\n        res = topi.add(res, bias)\n        res = my_clip(res, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res = topi.cast(res, env.out_dtype)\n        # Derive base schedule\n        s = fschedule([res])\n        if print_ir:\n            print(vta.lower(s, [data, kernel, bias, res], simple_mode=True))\n\n    # Derive number of ops\n    fout_height = (wl.height + 2 * wl.hpad - wl.hkernel) // wl.hstride + 1\n    fout_width = (wl.width + 2 * wl.wpad - wl.wkernel) // wl.wstride + 1\n    num_ops = (\n        2\n        * wl.batch\n        * fout_height\n        * fout_width\n        * wl.hkernel\n        * wl.wkernel\n        * wl.out_filter\n        * wl.in_filter\n        // wl.groups\n    )\n\n    def get_ref_data():\n        # derive min max for act, wgt, and bias types (max non inclusive)\n        a_min, a_max = 0 - (1 << (env.INP_WIDTH - 1)), (1 << (env.INP_WIDTH - 1))\n        w_min, w_max = 0 - (1 << (env.WGT_WIDTH - 1)), (1 << (env.WGT_WIDTH - 1))\n        b_min, b_max = 0 - 1 << (env.INP_WIDTH + env.WGT_WIDTH - 2), 1 << (\n            env.INP_WIDTH + env.WGT_WIDTH - 2\n        )\n        a_np = np.random.randint(a_min, a_max, size=a_shape).astype(data.dtype)\n        w_np = np.random.randint(w_min, w_max, size=w_shape).astype(kernel.dtype)\n        b_np = np.random.randint(b_min, b_max, size=b_shape).astype(env.acc_dtype)\n        r_np = tvm.topi.testing.conv2d_nchw_python(\n            a_np.astype(env.acc_dtype),\n            w_np.astype(env.acc_dtype),\n            (wl.hstride, wl.wstride),\n            wl.hpad,\n            wl.groups,\n        ).astype(env.acc_dtype)\n        return a_np, w_np, b_np, r_np\n\n    # Data in original format\n    data_np, kernel_np, bias_np, res_ref = get_ref_data()\n    if data_pack:\n        data_np = data_np.reshape(\n            wl.batch // env.BATCH,\n            env.BATCH,\n            wl.in_filter // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.height,\n            wl.width,\n        ).transpose((0, 2, 4, 5, 1, 3))\n        kernel_np = kernel_np.reshape(\n            wl.out_filter // env.BLOCK_OUT,\n            env.BLOCK_OUT,\n            CI_G // env.BLOCK_IN,\n            env.BLOCK_IN,\n            wl.hkernel,\n            wl.wkernel,\n        ).transpose((0, 2, 4, 5, 1, 3))\n        bias_np = bias_np.reshape(\n            wl.batch // env.BATCH, wl.out_filter // env.BLOCK_OUT, 1, 1, env.BATCH, env.BLOCK_OUT\n        )\n\n    # Build\n    if \"vta\" in target.keys:\n        with vta.build_config(disabled_pass={\"tir.CommonSubexprElimTIR\"}):\n            mod = vta.build(\n                s,\n                [data, kernel, bias, res],\n                target=tvm.target.Target(target, host=env.target_host),\n                name=\"conv2d\",\n            )\n    else:\n        mod = tvm.build(\n            s,\n            [data, kernel, bias, res],\n            target=tvm.target.Target(target, host=env.target_host),\n            name=\"conv2d\",\n        )\n    temp = utils.tempdir()\n    mod.save(temp.relpath(\"conv2d.o\"))\n    remote.upload(temp.relpath(\"conv2d.o\"))\n    f = remote.load_module(\"conv2d.o\")\n    dev = remote.device(str(target))\n\n    res_np = np.zeros(topi.utils.get_const_tuple(res.shape)).astype(res.dtype)\n    data_arr = tvm.nd.array(data_np, dev)\n    kernel_arr = tvm.nd.array(kernel_np, dev)\n    bias_arr = tvm.nd.array(bias_np, dev)\n    res_arr = tvm.nd.array(res_np, dev)\n    time_f = f.time_evaluator(\"conv2d\", dev, number=samples)\n\n    # In vta sim mode, collect simulator runtime statistics\n    stats = {}\n    cost = None\n    if env.TARGET in [\"sim\", \"tsim\"]:\n        # Check if we're in local RPC mode (allows us to rebuild the\n        # runtime on the fly when varying the VTA designs)\n        local_rpc = int(os.environ.get(\"VTA_LOCAL_SIM_RPC\", \"0\"))\n        if local_rpc:\n            if env.TARGET == \"sim\":\n                remote.get_function(\"vta.simulator.profiler_clear\")()\n            else:\n                remote.get_function(\"vta.tsim.profiler_clear\")()\n            cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n            if env.TARGET == \"sim\":\n                stats = json.loads(remote.get_function(\"vta.simulator.profiler_status\")())\n            else:\n                stats = json.loads(remote.get_function(\"vta.tsim.profiler_status\")())\n        else:\n            simulator.clear_stats()\n            cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n            stats = simulator.stats()\n    else:\n        cost = time_f(data_arr, kernel_arr, bias_arr, res_arr)\n\n    # Check correctness\n    correct = False\n    if check_correctness:\n        res_orig = res_arr.numpy()\n        if data_pack:\n            res_orig = res_orig.transpose((0, 4, 1, 5, 2, 3)).reshape(\n                wl.batch, wl.out_filter, fout_height, fout_width\n            )\n            bias_np = bias_np.transpose((0, 4, 1, 5, 2, 3)).reshape(wl.batch, wl.out_filter, 1, 1)\n        res_ref = res_ref >> env.WGT_WIDTH\n        res_ref += bias_np\n        res_ref = np.clip(res_ref, 0, (1 << env.OUT_WIDTH - 1) - 1)\n        res_ref = res_ref.astype(env.out_dtype)\n        correct = np.allclose(res_orig, res_ref)\n\n    gops = (num_ops / cost.mean) / float(10**9)\n    status = \"PASSED\" if correct else \"FAILED\"\n    if \"arm_cpu\" in target.keys:\n        device = \"CPU\"\n    elif \"vta\" in target.keys:\n        device = \"VTA\"\n    print(\n        \"%s GROUP CONV2D TEST %s: Time cost = %g sec/op, %g GOPS\"\n        % (device, status, cost.mean, gops)\n    )\n\n    return correct, cost, stats\n\n\n@pytest.mark.parametrize(\"device\", [\"vta\", \"arm_cpu\"])\ndef test_conv2d(device):\n    def _run(env, remote):\n        if device == \"vta\":\n            target = env.target\n            if env.TARGET not in [\"sim\", \"tsim\"]:\n                assert tvm.runtime.enabled(\"rpc\")\n                program_fpga(remote, bitstream=None)\n                reconfig_runtime(remote)\n        elif device == \"arm_cpu\":\n            target = env.target_vta_cpu\n        with autotvm.tophub.context(target):  # load pre-tuned schedule parameters\n            for _, wl in mobilenet_wkls:\n                print(wl)\n                run_group_conv2d(env, remote, wl, target)\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_conv2d(device=\"arm_cpu\")\n    test_conv2d(device=\"vta\")\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/pynq/test_program_rpc.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport os\nimport tvm\nfrom tvm import te\nfrom tvm import rpc\nfrom vta import get_bitstream_path, download_bitstream, program_fpga, reconfig_runtime\n\nhost = os.environ.get(\"VTA_RPC_HOST\", \"pynq\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n\ndef program_rpc_bitstream(path=None):\n    \"\"\"Program the FPGA on the RPC server\n\n    Parameters\n    ----------\n    path : path to bitstream (optional)\n    \"\"\"\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n    program_fpga(remote, path)\n\n\ndef reconfig_rpc_runtime():\n    \"\"\"Reconfig the RPC server runtime\"\"\"\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n    reconfig_runtime(remote)\n\n\nprogram_rpc_bitstream()\nreconfig_rpc_runtime()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/unittest/test_environment.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport vta\n\n\ndef test_env():\n    env = vta.get_env()\n    mock = env.mock\n    assert mock.alu == \"skip_alu\"\n\n\ndef test_env_scope():\n    env = vta.get_env()\n    cfg = env.cfg_dict\n    cfg[\"TARGET\"] = \"xyz\"\n    with vta.Environment(cfg):\n        assert vta.get_env().TARGET == \"xyz\"\n    assert vta.get_env().TARGET == env.TARGET\n\n\nif __name__ == \"__main__\":\n    test_env()\n    test_env_scope()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tests/python/unittest/test_vta_insn.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Unit test VTA's instructions \"\"\"\nimport tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm import topi\nfrom tvm.contrib import utils\n\nimport vta\nimport vta.testing\nfrom vta.testing import simulator\n\nnp.random.seed(0xDEADB)\n\n\ndef test_save_load_out():\n    \"\"\"Test save/store output command\"\"\"\n\n    def _run(env, remote):\n        n = 6\n        x = te.placeholder((n, n, env.BATCH, env.BLOCK_OUT), name=\"x\", dtype=env.acc_dtype)\n        x_buf = te.compute((n, n, env.BATCH, env.BLOCK_OUT), lambda *i: x(*i), \"x_buf\")\n        # insert no-op that won't be optimized away\n        y_buf = te.compute((n, n, env.BATCH, env.BLOCK_OUT), lambda *i: x_buf(*i) >> 0, \"y_buf\")\n        y = te.compute(\n            (n, n, env.BATCH, env.BLOCK_OUT), lambda *i: y_buf(*i).astype(env.inp_dtype), \"y\"\n        )\n        # schedule\n        s = te.create_schedule(y.op)\n        s[x_buf].set_scope(env.acc_scope)\n        s[x_buf].pragma(x_buf.op.axis[0], env.dma_copy)\n        s[y_buf].set_scope(env.acc_scope)\n        s[y_buf].pragma(y_buf.op.axis[0], env.alu)\n        s[y].pragma(y.op.axis[0], env.dma_copy)\n\n        # verification\n        with vta.build_config():\n            m = vta.build(s, [x, y], tvm.target.Target(\"ext_dev\", host=env.target_host))\n\n        if not remote:\n            return\n        temp = utils.tempdir()\n        m.save(temp.relpath(\"load_act.o\"))\n        remote.upload(temp.relpath(\"load_act.o\"))\n        f = remote.load_module(\"load_act.o\")\n        # verify\n        dev = remote.ext_dev(0)\n        x_np = np.random.randint(1, 10, size=(n, n, env.BATCH, env.BLOCK_OUT)).astype(x.dtype)\n        y_np = x_np.astype(y.dtype)\n        x_nd = tvm.nd.array(x_np, dev)\n        y_nd = tvm.nd.empty(y_np.shape, device=dev, dtype=y_np.dtype)\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            simulator.clear_stats()\n\n        f(x_nd, y_nd)\n\n        np.testing.assert_equal(y_np, y_nd.numpy())\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            sim_stats = simulator.stats()\n            print(\"Save load execution statistics:\")\n            for k, v in sim_stats.items():\n                print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n    vta.testing.run(_run)\n\n\ndef test_padded_load():\n    \"\"\"Test padded load.\"\"\"\n\n    def _run(env, remote):\n        def check_padded_load(pad_before, pad_after, test_name=None):\n            # declare\n            n = 3\n            m = 5\n            x = te.placeholder((n, m, env.BATCH, env.BLOCK_OUT), name=\"x\", dtype=env.acc_dtype)\n            x_buf = topi.nn.pad(x, pad_before, pad_after, name=\"y\")\n            # insert no-op that won't be optimized away\n            y_buf = te.compute(\n                (\n                    n + pad_before[0] + pad_after[0],\n                    m + pad_before[1] + pad_after[1],\n                    env.BATCH,\n                    env.BLOCK_OUT,\n                ),\n                lambda *i: x_buf(*i) >> 0,\n                \"y_buf\",\n            )\n            y = te.compute(\n                (\n                    n + pad_before[0] + pad_after[0],\n                    m + pad_before[1] + pad_after[1],\n                    env.BATCH,\n                    env.BLOCK_OUT,\n                ),\n                lambda *i: y_buf(*i).astype(env.inp_dtype),\n                \"y\",\n            )\n            # schedule\n            s = te.create_schedule(y.op)\n            s[x_buf].set_scope(env.acc_scope)\n            s[x_buf].pragma(x_buf.op.axis[0], env.dma_copy)\n            s[y_buf].set_scope(env.acc_scope)\n            s[y_buf].pragma(y_buf.op.axis[0], env.alu)\n            s[y].pragma(y.op.axis[0], env.dma_copy)\n            # build\n            with vta.build_config():\n                mod = vta.build(s, [x, y], tvm.target.Target(\"ext_dev\", host=env.target_host))\n\n            if not remote:\n                return\n            temp = utils.tempdir()\n            mod.save(temp.relpath(\"padded_load.o\"))\n            remote.upload(temp.relpath(\"padded_load.o\"))\n            f = remote.load_module(\"padded_load.o\")\n            # verify\n            dev = remote.ext_dev(0)\n            x_np = np.random.randint(0, 10, size=(n, m, env.BATCH, env.BLOCK_OUT)).astype(x.dtype)\n            y_np = np.zeros(\n                (\n                    n + pad_before[0] + pad_after[0],\n                    m + pad_before[1] + pad_after[1],\n                    env.BATCH,\n                    env.BLOCK_OUT,\n                )\n            ).astype(y.dtype)\n            y_np[pad_before[0] : pad_before[0] + n, pad_before[1] : pad_before[1] + m, :] = x_np\n            x_nd = tvm.nd.array(x_np, dev)\n            y_nd = tvm.nd.empty(y_np.shape, device=dev, dtype=y_np.dtype)\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                simulator.clear_stats()\n\n            f(x_nd, y_nd)\n\n            np.testing.assert_equal(y_np, y_nd.numpy())\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                sim_stats = simulator.stats()\n                print(\"Padded {} load execution statistics:\".format(test_name))\n                for k, v in sim_stats.items():\n                    print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n        check_padded_load([2, 0, 0, 0], [0, 0, 0, 0], test_name=\"Y0\")\n        check_padded_load([0, 2, 0, 0], [0, 0, 0, 0], test_name=\"Y1\")\n        check_padded_load([0, 0, 0, 0], [2, 0, 0, 0], test_name=\"X0\")\n        check_padded_load([0, 0, 0, 0], [0, 2, 0, 0], test_name=\"X1\")\n        check_padded_load([1, 1, 0, 0], [1, 1, 0, 0], test_name=\"all\")\n\n    vta.testing.run(_run)\n\n\ndef test_gemm():\n    \"\"\"Test GEMM.\"\"\"\n\n    def _run(env, remote):\n        # declare\n        o = 4\n        n = 1\n        m = 4\n        x = te.placeholder((o, n, env.BATCH, env.BLOCK_IN), name=\"x\", dtype=env.inp_dtype)\n        w = te.placeholder((m, n, env.BLOCK_OUT, env.BLOCK_IN), name=\"w\", dtype=env.wgt_dtype)\n        x_buf = te.compute((o, n, env.BATCH, env.BLOCK_IN), lambda *i: x(*i), \"x_buf\")\n        w_buf = te.compute((m, n, env.BLOCK_OUT, env.BLOCK_IN), lambda *i: w(*i), \"w_buf\")\n        ko = te.reduce_axis((0, n), name=\"ko\")\n        ki = te.reduce_axis((0, env.BLOCK_IN), name=\"ki\")\n        y_gem = te.compute(\n            (o, m, env.BATCH, env.BLOCK_OUT),\n            lambda bo, co, bi, ci: te.sum(\n                x_buf[bo, ko, bi, ki].astype(env.acc_dtype)\n                * w_buf[co, ko, ci, ki].astype(env.acc_dtype),\n                axis=[ko, ki],\n            ),\n            name=\"y_gem\",\n        )\n        y_shf = te.compute(\n            (o, m, env.BATCH, env.BLOCK_OUT), lambda *i: y_gem(*i) >> 8, name=\"y_shf\"\n        )\n        y_max = te.compute(\n            (o, m, env.BATCH, env.BLOCK_OUT), lambda *i: tvm.te.max(y_shf(*i), 0), \"y_max\"\n        )  # relu\n        y_min = te.compute(\n            (o, m, env.BATCH, env.BLOCK_OUT),\n            lambda *i: tvm.te.min(y_max(*i), (1 << (env.INP_WIDTH - 1)) - 1),\n            \"y_min\",\n        )  # relu\n        y = te.compute(\n            (o, m, env.BATCH, env.BLOCK_OUT), lambda *i: y_min(*i).astype(env.inp_dtype), name=\"y\"\n        )\n\n        if not remote:\n            return\n\n        def verify(s, name=None):\n            # Build with the CSE pass disabled as otherwise it would complicate the test\n            with vta.build_config(disabled_pass={\"tir.CommonSubexprElimTIR\"}):\n                mod = vta.build(s, [x, w, y], tvm.target.Target(\"ext_dev\", host=env.target_host))\n            temp = utils.tempdir()\n            mod.save(temp.relpath(\"gemm.o\"))\n            remote.upload(temp.relpath(\"gemm.o\"))\n            f = remote.load_module(\"gemm.o\")\n            # verify\n            dev = remote.ext_dev(0)\n            x_np = np.random.randint(-128, 128, size=(o, n, env.BATCH, env.BLOCK_IN)).astype(\n                x.dtype\n            )\n            w_np = np.random.randint(-128, 128, size=(m, n, env.BLOCK_OUT, env.BLOCK_IN)).astype(\n                w.dtype\n            )\n            y_np = np.zeros((o, m, env.BATCH, env.BLOCK_OUT)).astype(y.dtype)\n            x_nd = tvm.nd.array(x_np, dev)\n            w_nd = tvm.nd.array(w_np, dev)\n            y_nd = tvm.nd.array(y_np, dev)\n            y_np = y_np.astype(env.acc_dtype)\n            for b in range(o):\n                for i in range(m):\n                    for j in range(n):\n                        y_np[b, i, :] += np.dot(\n                            x_np[b, j, :].astype(env.acc_dtype), w_np[i, j].T.astype(env.acc_dtype)\n                        )\n            y_np = np.right_shift(y_np, 8)\n            y_np = np.clip(y_np, 0, (1 << (env.INP_WIDTH - 1)) - 1).astype(y.dtype)\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                simulator.clear_stats()\n\n            f(x_nd, w_nd, y_nd)\n\n            np.testing.assert_equal(y_np, y_nd.numpy())\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                sim_stats = simulator.stats()\n                print(\"GEMM schedule:{} execution statistics:\".format(name))\n                for k, v in sim_stats.items():\n                    print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n        def test_schedule1():\n            # default schedule with no smt\n            s = te.create_schedule(y.op)\n            # set the scope of the SRAM buffers\n            s[x_buf].set_scope(env.inp_scope)\n            s[w_buf].set_scope(env.wgt_scope)\n            s[y_gem].set_scope(env.acc_scope)\n            s[y_shf].set_scope(env.acc_scope)\n            s[y_max].set_scope(env.acc_scope)\n            s[y_min].set_scope(env.acc_scope)\n            # set pragmas for DMA transfer and ALU ops\n            s[x_buf].compute_at(s[y_gem], ko)\n            s[x_buf].pragma(s[x_buf].op.axis[0], env.dma_copy)\n            s[w_buf].compute_at(s[y_gem], ko)\n            s[w_buf].pragma(s[w_buf].op.axis[0], env.dma_copy)\n            s[y_shf].pragma(s[y_shf].op.axis[0], env.alu)\n            s[y_max].pragma(s[y_max].op.axis[0], env.alu)\n            s[y_min].pragma(s[y_min].op.axis[0], env.alu)\n            s[y].pragma(s[y].op.axis[0], env.dma_copy)\n            # tensorization\n            s[y_gem].reorder(\n                ko,\n                s[y_gem].op.axis[0],\n                s[y_gem].op.axis[1],\n                s[y_gem].op.axis[2],\n                s[y_gem].op.axis[3],\n                ki,\n            )\n            s[y_gem].tensorize(s[y_gem].op.axis[2], env.gemm)\n            verify(s, name=\"default\")\n\n        def test_smt():\n            # test smt schedule\n            s = te.create_schedule(y.op)\n            s[x_buf].set_scope(env.inp_scope)\n            s[w_buf].set_scope(env.wgt_scope)\n            s[y_gem].set_scope(env.acc_scope)\n            s[y_shf].set_scope(env.acc_scope)\n            s[y_max].set_scope(env.acc_scope)\n            s[y_min].set_scope(env.acc_scope)\n            abo, aco, abi, aci = s[y].op.axis\n            abo1, abo2 = s[y].split(abo, nparts=2)\n            s[y].bind(abo1, te.thread_axis(\"cthread\"))\n            s[y_gem].compute_at(s[y], abo1)\n            s[y_shf].compute_at(s[y], abo1)\n            s[y_max].compute_at(s[y], abo1)\n            s[y_min].compute_at(s[y], abo1)\n            s[y_gem].reorder(\n                ko,\n                s[y_gem].op.axis[0],\n                s[y_gem].op.axis[1],\n                s[y_gem].op.axis[2],\n                s[y_gem].op.axis[3],\n                ki,\n            )\n            s[y_gem].tensorize(s[y_gem].op.axis[2], env.gemm)\n            s[y_shf].pragma(s[y_shf].op.axis[0], env.alu)\n            s[y_max].pragma(s[y_max].op.axis[0], env.alu)\n            s[y_min].pragma(s[y_min].op.axis[0], env.alu)\n            s[x_buf].compute_at(s[y_gem], ko)\n            s[x_buf].pragma(s[x_buf].op.axis[0], env.dma_copy)\n            s[w_buf].compute_at(s[y_gem], ko)\n            s[w_buf].pragma(s[w_buf].op.axis[0], env.dma_copy)\n            s[y].pragma(abo2, env.dma_copy)\n            verify(s, name=\"smt\")\n\n        test_schedule1()\n        test_smt()\n\n    vta.testing.run(_run)\n\n\ndef test_alu():\n    def _run(env, remote):\n        def check_alu(tvm_op, np_op=None, use_imm=False, test_name=None):\n            \"\"\"Test ALU\"\"\"\n            m = 8\n            n = 8\n            imm = np.random.randint(1, 5)\n            # compute\n            a = te.placeholder((m, n, env.BATCH, env.BLOCK_OUT), name=\"a\", dtype=env.acc_dtype)\n            a_buf = te.compute(\n                (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: a(*i), \"a_buf\"\n            )  # DRAM->SRAM\n            if use_imm:\n                res_buf = te.compute(\n                    (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: tvm_op(a_buf(*i), imm), \"res_buf\"\n                )  # compute\n            else:\n                b = te.placeholder((m, n, env.BATCH, env.BLOCK_OUT), name=\"b\", dtype=env.acc_dtype)\n                b_buf = te.compute(\n                    (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: b(*i), \"b_buf\"\n                )  # DRAM->SRAM\n                res_buf = te.compute(\n                    (m, n, env.BATCH, env.BLOCK_OUT),\n                    lambda *i: tvm_op(a_buf(*i), b_buf(*i)),\n                    \"res_buf\",\n                )  # compute5B\n            res = te.compute(\n                (m, n, env.BATCH, env.BLOCK_OUT),\n                lambda *i: res_buf(*i).astype(env.inp_dtype),\n                \"res\",\n            )  # SRAM->DRAM\n            # schedule\n            s = te.create_schedule(res.op)\n            s[a_buf].set_scope(env.acc_scope)  # SRAM\n            s[a_buf].pragma(a_buf.op.axis[0], env.dma_copy)  # DRAM->SRAM\n            s[res_buf].set_scope(env.acc_scope)  # SRAM\n            s[res_buf].pragma(res_buf.op.axis[0], env.alu)  # compute\n            s[res].pragma(res.op.axis[0], env.dma_copy)  # SRAM->DRAM\n            if not use_imm:\n                s[b_buf].set_scope(env.acc_scope)  # SRAM\n                s[b_buf].pragma(b_buf.op.axis[0], env.dma_copy)  # DRAM->SRAM\n\n            if not remote:\n                return\n\n            # build\n            with vta.build_config():\n                if use_imm:\n                    mod = vta.build(s, [a, res], tvm.target.Target(\"ext_dev\", host=env.target_host))\n                else:\n                    mod = vta.build(\n                        s, [a, b, res], tvm.target.Target(\"ext_dev\", host=env.target_host)\n                    )\n            temp = utils.tempdir()\n            mod.save(temp.relpath(\"load_act.o\"))\n            remote.upload(temp.relpath(\"load_act.o\"))\n            f = remote.load_module(\"load_act.o\")\n            # verify\n            dev = remote.ext_dev(0)\n            a_np = np.random.randint(-16, 16, size=(m, n, env.BATCH, env.BLOCK_OUT)).astype(a.dtype)\n            if use_imm:\n                res_np = np_op(a_np, imm) if np_op else tvm_op(a_np, imm)\n            else:\n                b_np = np.random.randint(-16, 16, size=(m, n, env.BATCH, env.BLOCK_OUT)).astype(\n                    b.dtype\n                )\n                res_np = np_op(a_np, b_np) if np_op else tvm_op(a_np, b_np)\n            res_np = res_np.astype(res.dtype)\n            a_nd = tvm.nd.array(a_np, dev)\n            res_nd = tvm.nd.array(np.zeros((m, n, env.BATCH, env.BLOCK_OUT)).astype(res.dtype), dev)\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                simulator.clear_stats()\n\n            if use_imm:\n                f(a_nd, res_nd)\n            else:\n                b_nd = tvm.nd.array(b_np, dev)\n                f(a_nd, b_nd, res_nd)\n\n            np.testing.assert_equal(res_np, res_nd.numpy())\n\n            if env.TARGET in [\"sim\", \"tsim\"]:\n                sim_stats = simulator.stats()\n                print(\"ALU {} execution statistics:\".format(test_name))\n                for k, v in sim_stats.items():\n                    print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n        check_alu(lambda x, y: x << y, np.left_shift, use_imm=True, test_name=\"SHL\")\n        check_alu(tvm.te.max, np.maximum, use_imm=True, test_name=\"MAX\")\n        check_alu(tvm.te.max, np.maximum, test_name=\"MAX\")\n        check_alu(lambda x, y: x + y, use_imm=True, test_name=\"ADD\")\n        check_alu(lambda x, y: x + y, test_name=\"ADD\")\n        check_alu(lambda x, y: x >> y, np.right_shift, use_imm=True, test_name=\"SHR\")\n\n    vta.testing.run(_run)\n\n\ndef test_relu():\n    \"\"\"Test RELU on ALU\"\"\"\n\n    def _run(env, remote):\n        m = 8\n        n = 10\n        # compute\n        a = te.placeholder((m, n, env.BATCH, env.BLOCK_OUT), name=\"a\", dtype=env.acc_dtype)\n        a_buf = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: a(*i), \"a_buf\"\n        )  # DRAM->SRAM\n        max_buf = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: tvm.te.max(a_buf(*i), 0), \"res_buf\"\n        )  # relu\n        min_buf = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT),\n            lambda *i: tvm.te.min(max_buf(*i), (1 << (env.INP_WIDTH - 1)) - 1),\n            \"max_buf\",\n        )  # relu\n        res = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT),\n            lambda *i: min_buf(*i).astype(env.inp_dtype),\n            \"min_buf\",\n        )  # SRAM->DRAM\n        # schedule\n        s = te.create_schedule(res.op)\n        s[a_buf].set_scope(env.acc_scope)  # SRAM\n        s[a_buf].pragma(a_buf.op.axis[0], env.dma_copy)  # DRAM->SRAM\n        s[max_buf].set_scope(env.acc_scope)  # SRAM\n        s[min_buf].set_scope(env.acc_scope)  # SRAM\n        s[max_buf].pragma(max_buf.op.axis[0], env.alu)  # compute\n        s[min_buf].pragma(min_buf.op.axis[0], env.alu)  # compute\n        s[res].pragma(res.op.axis[0], env.dma_copy)  # SRAM->DRAM\n        # build\n        with vta.build_config():\n            mod = vta.build(s, [a, res], tvm.target.Target(\"ext_dev\", host=env.target_host))\n        if not remote:\n            return\n        temp = utils.tempdir()\n        mod.save(temp.relpath(\"load_act.o\"))\n        remote.upload(temp.relpath(\"load_act.o\"))\n        f = remote.load_module(\"load_act.o\")\n        # verify\n        dev = remote.ext_dev(0)\n        a_np = np.random.randint(-256, 256, size=(m, n, env.BATCH, env.BLOCK_OUT)).astype(a.dtype)\n        res_np = np.clip(a_np, 0, (1 << (env.INP_WIDTH - 1)) - 1).astype(res.dtype)\n        a_nd = tvm.nd.array(a_np, dev)\n        res_nd = tvm.nd.array(np.zeros((m, n, env.BATCH, env.BLOCK_OUT)).astype(res.dtype), dev)\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            simulator.clear_stats()\n\n        f(a_nd, res_nd)\n\n        np.testing.assert_equal(res_np, res_nd.numpy())\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            sim_stats = simulator.stats()\n            print(\"Relu execution statistics:\")\n            for k, v in sim_stats.items():\n                print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n    vta.testing.run(_run)\n\n\ndef test_shift_and_scale():\n    \"\"\"Test shift and scale on ALU\"\"\"\n\n    def _run(env, remote):\n        m = 2\n        n = 8\n        imm_shift = np.random.randint(0, 8)\n        imm_scale = np.random.randint(1, 5)\n        # compute\n        a = te.placeholder((m, n, env.BATCH, env.BLOCK_OUT), name=\"a\", dtype=env.acc_dtype)\n        a_buf = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: a(*i), \"a_buf\"\n        )  # DRAM->SRAM\n        res_shift = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: a_buf(*i) + imm_shift, \"res_shift\"\n        )  # compute\n        res_scale = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: res_shift(*i) >> imm_scale, \"res_scale\"\n        )  # compute\n        res = te.compute(\n            (m, n, env.BATCH, env.BLOCK_OUT), lambda *i: res_scale(*i).astype(env.inp_dtype), \"res\"\n        )  # SRAM->DRAM\n        # schedule\n        s = te.create_schedule(res.op)\n        s[a_buf].set_scope(env.acc_scope)  # SRAM\n        s[res_shift].set_scope(env.acc_scope)  # SRAM\n        s[res_scale].set_scope(env.acc_scope)  # SRAM\n        s[a_buf].pragma(a_buf.op.axis[0], env.dma_copy)  # DRAM->SRAM\n        s[res_shift].pragma(res_shift.op.axis[0], env.alu)  # compute\n        s[res_scale].pragma(res_scale.op.axis[0], env.alu)  # compute\n        s[res].pragma(res.op.axis[0], env.dma_copy)  # SRAM->DRAM\n        # build\n        mod = vta.build(s, [a, res], tvm.target.Target(\"ext_dev\", host=env.target_host))\n        if not remote:\n            return\n        temp = utils.tempdir()\n        mod.save(temp.relpath(\"load_act.o\"))\n        remote.upload(temp.relpath(\"load_act.o\"))\n        f = remote.load_module(\"load_act.o\")\n        # verify\n        dev = remote.ext_dev(0)\n        a_np = np.random.randint(-10, 10, size=(m, n, env.BATCH, env.BLOCK_OUT)).astype(a.dtype)\n        res_np = np.right_shift((a_np + imm_shift), imm_scale)\n        res_np = res_np.astype(res.dtype)\n        a_nd = tvm.nd.array(a_np, dev)\n        res_nd = tvm.nd.array(np.zeros((m, n, env.BATCH, env.BLOCK_OUT)).astype(res.dtype), dev)\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            simulator.clear_stats()\n\n        f(a_nd, res_nd)\n\n        np.testing.assert_equal(res_np, res_nd.numpy())\n\n        if env.TARGET in [\"sim\", \"tsim\"]:\n            sim_stats = simulator.stats()\n            print(\"Shift and scale execution statistics:\")\n            for k, v in sim_stats.items():\n                print(\"\\t{:<16}: {:>16}\".format(k, v))\n\n    vta.testing.run(_run)\n\n\ndef test_runtime_array():\n    def _run(env, remote):\n        n = 100\n        dev = remote.ext_dev(0)\n        x_np = np.random.randint(1, 10, size=(n, n, env.BATCH, env.BLOCK_OUT)).astype(\"int8\")\n        x_nd = tvm.nd.array(x_np, dev)\n        np.testing.assert_equal(x_np, x_nd.numpy())\n\n    vta.testing.run(_run)\n\n\nif __name__ == \"__main__\":\n    test_runtime_array()\n    test_save_load_out()\n    test_padded_load()\n    test_gemm()\n    test_alu()\n    test_relu()\n    test_shift_and_scale()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/autotvm/tune_alu_vta.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-tuning a ALU fused op on VTA\n---------------------------------\n\"\"\"\n\nimport os\nfrom mxnet.gluon.model_zoo import vision\nimport numpy as np\nfrom PIL import Image\n\nfrom tvm import topi\nimport tvm\nfrom tvm import te\nfrom tvm import rpc, autotvm, relay\nfrom tvm.contrib import download\nfrom tvm.autotvm.measure.measure_methods import request_remote\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.autotvm import record\n\nimport vta\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\nimport copy\n\n\n#################################################################\n# Compile network\n# ---------------\n# Perform vta-specific compilation with Relay from a Gluon model\ndef compile_network(env, target, model, start_pack, stop_pack):\n\n    # Populate the shape and data type dictionary\n    dtype_dict = {\"data\": \"float32\"}\n    shape_dict = {\"data\": (env.BATCH, 3, 224, 224)}\n\n    # Get off the shelf gluon model, and convert to relay\n    gluon_model = vision.get_model(model, pretrained=True)\n    mod, params = relay.frontend.from_mxnet(gluon_model, shape_dict)\n\n    # Update shape and type dictionary\n    shape_dict.update({k: v.shape for k, v in params.items()})\n    dtype_dict.update({k: str(v.dtype) for k, v in params.items()})\n\n    # Perform quantization in Relay\n    # Note: We set opt_level to 3 in order to fold batch norm\n    with relay.build_config(opt_level=3):\n        with relay.quantize.qconfig(global_scale=8.0, skip_conv_layers=[0]):\n            mod = relay.quantize.quantize(mod, params=params)\n\n    # Perform graph packing and constant folding for VTA target\n    if target.device_name == \"vta\":\n        assert env.BLOCK_IN == env.BLOCK_OUT\n        relay_prog = graph_pack(\n            mod[\"main\"],\n            env.BATCH,\n            env.BLOCK_OUT,\n            env.WGT_WIDTH,\n            start_name=start_pack,\n            stop_name=stop_pack,\n        )\n\n    return relay_prog, params\n\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we should apply some configurations.\n# Here we use an Pynq-Z1 board as an example.\n\n# Tracker host and port can be set by your environment\ntracker_host = os.environ.get(\"TVM_TRACKER_HOST\", \"0.0.0.0\")\ntracker_port = int(os.environ.get(\"TVM_TRACKER_PORT\", 9190))\n\n# Load VTA parameters from the vta/config/vta_config.json file\nenv = vta.get_env()\n\n# This target is used for cross compilation. You can query it by :code:`gcc -v` on your device.\n# Set ``device=arm_cpu`` to run inference on the CPU\n# or ``device=vta`` to run inference on the FPGA.\ndevice = \"vta\"\ntarget = env.target if device == \"vta\" else env.target_vta_cpu\n\n# Name of Gluon model to compile\n# The ``start_pack`` and ``stop_pack`` labels indicate where\n# to start and end the graph packing relay pass: in other words\n# where to start and finish offloading to VTA.\nnetwork = \"resnet50_v2\"\nstart_pack = \"nn.max_pool2d\"\nstop_pack = \"nn.global_avg_pool2d\"\n\n# Tuning option\nlog_file = \"%s.alu.%s.log\" % (device, network)\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"random\",\n    \"n_trial\": 1000,\n    \"early_stopping\": None,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(n_parallel=1),\n        runner=autotvm.RPCRunner(\n            env.TARGET,\n            host=tracker_host,\n            port=tracker_port,\n            number=5,\n            timeout=60,\n            # check_correctness=True, # TODO: re-enable when check_correctness works again.\n        ),\n    ),\n}\n\n\ndef log_to_file(file_out, protocol=\"json\"):\n    \"\"\"Log the tuning records into file.\n    The rows of the log are stored in the format of autotvm.record.encode.\n    for lhs == rhs, we add an extra rhs = [] record\n\n    Parameters\n    ----------\n    file_out : str\n        The file to log to.\n    protocol: str, optional\n        The log protocol. Can be 'json' or 'pickle'\n\n    Returns\n    -------\n    callback : callable\n        Callback function to do the logging.\n    \"\"\"\n\n    def _callback(_, inputs, results):\n        with open(file_out, \"a\") as f:\n            for inp, result in zip(inputs, results):\n                f.write(record.encode(inp, result, protocol) + \"\\n\")\n\n                # we only consider task with same lhs and rhs\n                if inp.task.args[0] == inp.task.args[1]:\n                    args = list(inp.task.args)\n                    args[1] = (args[0][0], (), args[0][2])\n                    inp_copy = copy.deepcopy(inp)\n                    inp_copy.task.args = tuple(args)\n                    f.write(record.encode(inp_copy, result, protocol) + \"\\n\")\n\n    return _callback\n\n\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=10,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"xgb_knob\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"knob\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n########################################################################\n# Register VTA-specific tuning tasks\ndef register_vta_tuning_tasks():\n    from tvm.autotvm.task import TaskExtractEnv\n\n    @tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\n    def my_clip(x, a_min, a_max):\n        \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n        const_min = tvm.tir.const(a_min, x.dtype)\n        const_max = tvm.tir.const(a_max, x.dtype)\n        x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n        x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n        return x\n\n    # init autotvm env to register VTA operator\n    TaskExtractEnv()\n\n    @autotvm.template(\"add.vta\")\n    def _topi_add(*args, **kwargs):\n        assert not kwargs, \"Do not support kwargs in template function call\"\n        A, B = args[:2]\n\n        with tvm.target.vta():\n            res = vta.top.op.add_packed(*args, **kwargs)\n            res = my_clip(res, 0, 127)\n            res = topi.cast(res, \"int8\")\n\n        if tvm.target.Target.current().device_name == \"vta\":\n            s = vta.top.op.schedule_add_packed([res])\n        else:\n            s = te.create_schedule([res.op])\n        return s, [A, B, res]\n\n    @autotvm.template(\"multiply.vta\")\n    def _topi_multiply(*args, **kwargs):\n        assert not kwargs, \"Do not support kwargs in template function call\"\n        A, B = args[:2]\n\n        with tvm.target.vta():\n            res = vta.top.op.multiply_packed(*args, **kwargs)\n            res = my_clip(res, 0, 127)\n            res = topi.cast(res, \"int8\")\n\n        if tvm.target.Target.current().device_name == \"vta\":\n            s = vta.top.op.schedule_multiply_packed([res])\n        else:\n            s = te.create_schedule([res.op])\n        return s, [A, B, res]\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\ndef tune_and_evaluate(tuning_opt):\n\n    if env.TARGET != \"intelfocl\":\n        print(\"ALU only op only available for intelfocl target\")\n        return\n\n    # Register VTA tuning tasks\n    register_vta_tuning_tasks()\n\n    # Perform task extraction on Relay program\n    print(\"Extract tasks...\")\n    relay_prog, params = compile_network(env, target, network, start_pack, stop_pack)\n    mod = tvm.IRModule.from_expr(relay_prog)\n    tasks = autotvm.task.extract_from_program(\n        mod,\n        params=params,\n        ops=(\n            relay.op.get(\"add\"),\n            relay.op.get(\"multiply\"),\n        ),\n        target=tvm.target.Target(target, host=env.target_host),\n    )\n\n    # filter out non-packed alu task\n    tasks = list(filter(lambda t: len(t.args[0][1]) > 4, tasks))\n    # filter out float alu task\n    tasks = list(filter(lambda t: t.args[0][2] != \"float32\", tasks))\n\n    # We should have extracted 10 convolution tasks\n    tasks_set = {}\n    print(\"Extracted {} alu tasks:\".format(len(tasks)))\n    for tsk in tasks:\n        print(\"tsk = \", tsk)\n\n        if len(tsk.args[1][1]) == 0:\n            args = list(tsk.args)\n            args[1] = args[0]\n            tsk.args = tuple(args)\n\n        if (tsk.name, tsk.args) in tasks_set:\n            print(\"task {} already exists\".format(tsk))\n        tasks_set[(tsk.name, tsk.args)] = tsk\n\n    tasks = list(tasks_set.values())\n    print(\"After merged, final #tasks={}, tasks = {}\".format(len(tasks), tasks))\n\n    # run tuning tasks\n    print(\"Tuning...\")\n    tune_tasks(tasks, **tuning_opt)\n\n\n# Run the tuning and evaluate the results\ntune_and_evaluate(tuning_option)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/autotvm/tune_relay_vta.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-tuning a convolutional network on VTA\n==========================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nAuto-tuning for a specific accelerator design is critical for getting the best\nperformance for any given operator. This is a tutorial showcases how to tune a\nwhole convolutional network on VTA.\n\nThe operator implementation for VTA in TVM is written in template form.\nThe template has many tunable knobs (tile factor, virtual threads, etc).\nWe will tune all convolution operators in the neural network. After tuning,\nwe produce a log file which stores the best schedule parameters for all tuned\noperators. When the TVM compiler compiles these operators, it will query this\nlog file to get the best knob parameters.\n\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado mxnet requests \"Pillow<7\" cloudpickle\n#\n# To make TVM run faster during tuning, it is recommended to use cython\n# as FFI of TVM. In the root directory of TVM, execute\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\nimport os\nfrom mxnet.gluon.model_zoo import vision\nimport numpy as np\nfrom PIL import Image\n\nfrom tvm import topi\nimport tvm\nfrom tvm import te\nfrom tvm import rpc, autotvm, relay\nfrom tvm.contrib import graph_executor, utils, download\nfrom tvm.autotvm.measure.measure_methods import request_remote\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\n\nimport vta\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\n\n#################################################################\n# Compile network\n# ---------------\n# Perform vta-specific compilation with Relay from a Gluon model\n\n\ndef compile_network(env, target, model, start_pack, stop_pack):\n\n    # Populate the shape and data type dictionary\n    dtype_dict = {\"data\": \"float32\"}\n    shape_dict = {\"data\": (env.BATCH, 3, 224, 224)}\n\n    # Get off the shelf gluon model, and convert to relay\n    gluon_model = vision.get_model(model, pretrained=True)\n    mod, params = relay.frontend.from_mxnet(gluon_model, shape_dict)\n\n    # Update shape and type dictionary\n    shape_dict.update({k: v.shape for k, v in params.items()})\n    dtype_dict.update({k: str(v.dtype) for k, v in params.items()})\n\n    # Perform quantization in Relay\n    # Note: We set opt_level to 3 in order to fold batch norm\n    with tvm.transform.PassContext(opt_level=3):\n        with relay.quantize.qconfig(global_scale=8.0, skip_conv_layers=[0]):\n            mod = relay.quantize.quantize(mod, params=params)\n\n    # Perform graph packing and constant folding for VTA target\n    if target.device_name == \"vta\":\n        assert env.BLOCK_IN == env.BLOCK_OUT\n        relay_prog = graph_pack(\n            mod[\"main\"],\n            env.BATCH,\n            env.BLOCK_OUT,\n            env.WGT_WIDTH,\n            start_name=start_pack,\n            stop_name=stop_pack,\n        )\n\n    return relay_prog, params\n\n\n#################################################################\n# Start RPC Tracker\n# -----------------\n# TVM uses an RPC session to communicate with Pynq boards.\n# During tuning, the tuner will send the generated code to the board and\n# measure the speed of code on the board.\n#\n# To scale up tuning, TVM uses an RPC Tracker to manage multiple devices.\n# The RPC Tracker is a centralized controller node. We can register all devices to\n# the tracker. For example, if we have 10 Pynq boards, we can register all of them\n# to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n#\n# To start an RPC tracker, run this command on the host machine. The tracker is\n# required during the whole tuning process, so we need to open a new terminal for\n# this command:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n#\n# The expected output is:\n#\n# .. code-block:: bash\n#\n#   INFO:RPCTracker:bind to 0.0.0.0:9190\n\n#################################################################\n# Register devices to RPC Tracker\n# -----------------------------------\n# Now we can register our devices to the tracker. The first step is to\n# build the TVM runtime for the Pynq devices.\n#\n# Follow :ref:`vta-index`\n# to build the TVM runtime on the device. Then register the device to the tracker with:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.rpc_server --tracker=[HOST_IP]:9190 --key=pynq\n#\n# (replace :code:`[HOST_IP]` with the IP address of your host machine)\n#\n# After registering devices, we can confirm it by querying the rpc_tracker:\n#\n# .. code-block:: bash\n#\n#   python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n#\n# For example, if we have 6 Pynq boards and 11 Raspberry Pi 3B,\n# the output can be\n#\n# .. code-block:: bash\n#\n#    Queue Status\n#    ----------------------------------\n#    key          total  free  pending\n#    ----------------------------------\n#    pynq         6      6     0\n#    rpi3b        11     11    0\n#    ----------------------------------\n#\n# You can register multiple devices to the tracker to accelerate tuning.\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we should apply some configurations.\n# Here we use an Pynq-Z1 board as an example.\n\n# Tracker host and port can be set by your environment\ntracker_host = os.environ.get(\"TVM_TRACKER_HOST\", \"127.0.0.1\")\ntracker_port = int(os.environ.get(\"TVM_TRACKER_PORT\", 9190))\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n\n# This target is used for cross compilation. You can query it by :code:`gcc -v` on your device.\n# Set ``device=arm_cpu`` to run inference on the CPU\n# or ``device=vta`` to run inference on the FPGA.\ndevice = \"vta\"\ntarget = env.target if device == \"vta\" else env.target_vta_cpu\n\n# Name of Gluon model to compile\n# The ``start_pack`` and ``stop_pack`` labels indicate where\n# to start and end the graph packing relay pass: in other words\n# where to start and finish offloading to VTA.\nnetwork = \"resnet18_v1\"\nstart_pack = \"nn.max_pool2d\"\nstop_pack = \"nn.global_avg_pool2d\"\n\n# Tuning option\nlog_file = \"%s.%s.log\" % (device, network)\ntuning_option = {\n    \"log_filename\": log_file,\n    \"tuner\": \"random\",\n    \"n_trial\": 1000,\n    \"early_stopping\": None,\n    \"measure_option\": autotvm.measure_option(\n        builder=autotvm.LocalBuilder(),\n        runner=autotvm.RPCRunner(\n            env.TARGET,\n            host=tracker_host,\n            port=tracker_port,\n            number=5,\n            timeout=60,\n            module_loader=vta.module_loader(),\n            # check_correctness=True, # TODO: re-enable when check_correctness works again.\n        ),\n    ),\n}\n\n####################################################################\n#\n# .. note:: How to set tuning options\n#\n#   In general, the default values provided here work well.\n#   If you have enough time budget, you can set :code:`n_trial`, :code:`early_stopping`\n#   to larger values, makes the tuning run for longer.\n#   If your device is under-powered or your conv2d operators are large, consider\n#   setting a longer timeout.\n#\n\n###################################################################\n# Begin Tuning\n# ------------\n# Now we can extract tuning tasks from the network and begin tuning.\n# Here, we provide a simple utility function to tune a list of tasks.\n# This function is just an initial implementation which tunes them in sequential order.\n# We will introduce a more sophisticated tuning scheduler in the future.\n#\n# Given that the tuning will be done on Pynq FPGA boards, make sure that\n# the ```TARGET`` entry in the ``vta_config.json`` file is set to ``pynq``.\n\n\n# You can skip the implementation of this function for this tutorial.\ndef tune_tasks(\n    tasks,\n    measure_option,\n    tuner=\"xgb\",\n    n_trial=1000,\n    early_stopping=None,\n    log_filename=\"tuning.log\",\n    use_transfer_learning=True,\n):\n\n    # create tmp log file\n    tmp_log_file = log_filename + \".tmp\"\n    if os.path.exists(tmp_log_file):\n        os.remove(tmp_log_file)\n\n    for i, tsk in enumerate(reversed(tasks)):\n        prefix = \"[Task %2d/%2d] \" % (i + 1, len(tasks))\n\n        # create tuner\n        if tuner == \"xgb\" or tuner == \"xgb-rank\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\")\n        elif tuner == \"xgb_knob\":\n            tuner_obj = XGBTuner(tsk, loss_type=\"rank\", feature_type=\"knob\")\n        elif tuner == \"ga\":\n            tuner_obj = GATuner(tsk, pop_size=50)\n        elif tuner == \"random\":\n            tuner_obj = RandomTuner(tsk)\n        elif tuner == \"gridsearch\":\n            tuner_obj = GridSearchTuner(tsk)\n        else:\n            raise ValueError(\"Invalid tuner: \" + tuner)\n\n        if use_transfer_learning:\n            if os.path.isfile(tmp_log_file):\n                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n        # do tuning\n        tsk_trial = min(n_trial, len(tsk.config_space))\n        tuner_obj.tune(\n            n_trial=tsk_trial,\n            early_stopping=early_stopping,\n            measure_option=measure_option,\n            callbacks=[\n                autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n                autotvm.callback.log_to_file(tmp_log_file),\n            ],\n        )\n\n    # pick best records to a cache file\n    autotvm.record.pick_best(tmp_log_file, log_filename)\n    os.remove(tmp_log_file)\n\n\n########################################################################\n# Register VTA-specific tuning tasks\n\n\ndef register_vta_tuning_tasks():\n    from tvm.autotvm.task import TaskExtractEnv\n\n    @tvm.te.tag_scope(tag=topi.tag.ELEMWISE)\n    def my_clip(x, a_min, a_max):\n        \"\"\"Unlike topi's current clip, put min and max into two stages.\"\"\"\n        const_min = tvm.tir.const(a_min, x.dtype)\n        const_max = tvm.tir.const(a_max, x.dtype)\n        x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name=\"clipA\")\n        x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name=\"clipB\")\n        return x\n\n    # init autotvm env to register VTA operator\n    TaskExtractEnv()\n\n    @autotvm.template(\"conv2d_packed.vta\")\n    def _topi_nn_conv2d(*args, **kwargs):\n        assert not kwargs, \"Do not support kwargs in template function call\"\n        A, W = args[:2]\n\n        with tvm.target.vta():\n            res = vta.top.conv2d_packed(*args, **kwargs)\n            res = topi.right_shift(res, 8)\n            res = my_clip(res, 0, 127)\n            res = topi.cast(res, \"int8\")\n\n        if tvm.target.Target.current().device_name == \"vta\":\n            s = vta.top.schedule_conv2d_packed([res])\n        else:\n            s = te.create_schedule([res.op])\n        return s, [A, W, res]\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n\n\ndef tune_and_evaluate(tuning_opt):\n\n    # Register VTA tuning tasks\n    register_vta_tuning_tasks()\n\n    # Perform task extraction on Relay program\n    print(\"Extract tasks...\")\n    relay_prog, params = compile_network(env, target, network, start_pack, stop_pack)\n    mod = tvm.IRModule.from_expr(relay_prog)\n    tasks = autotvm.task.extract_from_program(\n        mod,\n        params=params,\n        ops=(relay.op.get(\"nn.conv2d\"),),\n        target=target,\n        target_host=env.target_host,\n    )\n\n    # filter out non-packed conv2d task\n    tasks = list(filter(lambda t: len(t.args[0][1]) > 4 and \"conv\" in t.name, tasks))\n\n    # We should have extracted 10 convolution tasks\n    assert len(tasks) == 10\n    print(\"Extracted {} conv2d tasks:\".format(len(tasks)))\n    for tsk in tasks:\n        inp = tsk.args[0][1]\n        wgt = tsk.args[1][1]\n        batch = inp[0] * inp[4]\n        in_filter = inp[1] * inp[5]\n        out_filter = wgt[0] * wgt[4]\n        height, width = inp[2], inp[3]\n        hkernel, wkernel = wgt[2], wgt[3]\n        hstride, wstride = tsk.args[2][0], tsk.args[2][1]\n        hpad, wpad = tsk.args[3][0], tsk.args[3][1]\n        print(\n            \"({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})\".format(\n                batch,\n                height,\n                width,\n                in_filter,\n                out_filter,\n                hkernel,\n                wkernel,\n                hpad,\n                wpad,\n                hstride,\n                wstride,\n            )\n        )\n\n    # We do not run the tuning in our webpage server since it takes too long.\n    # Comment the following line to run it by yourself.\n    return\n\n    # run tuning tasks\n    print(\"Tuning...\")\n    tune_tasks(tasks, **tuning_opt)\n\n    # evaluate with tuning history\n    if env.TARGET != \"sim\":\n        # Get remote from fleet node\n        remote = autotvm.measure.request_remote(\n            env.TARGET, tracker_host, tracker_port, timeout=10000\n        )\n        # Reconfigure the JIT runtime and FPGA.\n        vta.reconfig_runtime(remote)\n        vta.program_fpga(remote, bitstream=None)\n    else:\n        # In simulation mode, host the RPC server locally.\n        remote = rpc.LocalSession()\n\n    # compile kernels with history best records\n    with autotvm.tophub.context(target, extra_files=[log_file]):\n        # Compile network\n        print(\"Compile...\")\n        if target.device_name != \"vta\":\n            with tvm.transform.PassContext(opt_level=3, disabled_pass={\"AlterOpLayout\"}):\n                lib = relay.build(\n                    relay_prog, target=target, params=params, target_host=env.target_host\n                )\n        else:\n            with vta.build_config(opt_level=3, disabled_pass={\"AlterOpLayout\"}):\n                lib = relay.build(\n                    relay_prog, target=target, params=params, target_host=env.target_host\n                )\n\n        # Export library\n        print(\"Upload...\")\n        temp = utils.tempdir()\n        lib.export_library(temp.relpath(\"graphlib.tar\"))\n        remote.upload(temp.relpath(\"graphlib.tar\"))\n        lib = remote.load_module(\"graphlib.tar\")\n\n        # Generate the graph executor\n        ctx = remote.ext_dev(0) if device == \"vta\" else remote.cpu(0)\n        m = graph_executor.GraphModule(lib[\"default\"](ctx))\n\n        # upload parameters to device\n        image = tvm.nd.array((np.random.uniform(size=(1, 3, 224, 224))).astype(\"float32\"))\n        m.set_input(\"data\", image)\n\n        # evaluate\n        print(\"Evaluate inference time cost...\")\n        timer = m.module.time_evaluator(\"run\", ctx, number=1, repeat=10)\n        tcost = timer()\n        prof_res = np.array(tcost.results) * 1000  # convert to millisecond\n        print(\n            \"Mean inference time (std dev): %.2f ms (%.2f ms)\"\n            % (np.mean(prof_res), np.std(prof_res))\n        )\n\n\n# Run the tuning and evaluate the results\ntune_and_evaluate(tuning_option)\n\n######################################################################\n# Sample Output\n# -------------\n# The tuning needs to compile many programs and extract feature from them.\n# So a high performance CPU is recommended.\n# One sample output is listed below.\n# It takes about 2 hours on a 16T CPU, and 6 Pynq boards.\n#\n# .. code-block:: bash\n#\n#    Extract tasks...\n#    [Warning] Invalid shape during AutoTVM task creation\n#    Extracted 10 conv2d tasks:\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 16, 14, 14, 1, 16), 'int8'), ('TENSOR', (32, 16, 1, 1, 16, 16), 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 16, 14, 14, 1, 16, 'int8'), (32, 16, 1, 1, 16, 16, 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 8, 28, 28, 1, 16), 'int8'), ('TENSOR', (16, 8, 1, 1, 16, 16), 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 8, 28, 28, 1, 16, 'int8'), (16, 8, 1, 1, 16, 16, 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 4, 56, 56, 1, 16), 'int8'), ('TENSOR', (8, 4, 1, 1, 16, 16), 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 4, 56, 56, 1, 16, 'int8'), (8, 4, 1, 1, 16, 16, 'int8'), (2, 2), (0, 0), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 4, 56, 56, 1, 16), 'int8'), ('TENSOR', (4, 4, 3, 3, 16, 16), 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 4, 56, 56, 1, 16, 'int8'), (4, 4, 3, 3, 16, 16, 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 8, 28, 28, 1, 16), 'int8'), ('TENSOR', (8, 8, 3, 3, 16, 16), 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 8, 28, 28, 1, 16, 'int8'), (8, 8, 3, 3, 16, 16, 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 4, 56, 56, 1, 16), 'int8'), ('TENSOR', (8, 4, 3, 3, 16, 16), 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 4, 56, 56, 1, 16, 'int8'), (8, 4, 3, 3, 16, 16, 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 16, 14, 14, 1, 16), 'int8'), ('TENSOR', (16, 16, 3, 3, 16, 16), 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 16, 14, 14, 1, 16, 'int8'), (16, 16, 3, 3, 16, 16, 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 8, 28, 28, 1, 16), 'int8'), ('TENSOR', (16, 8, 3, 3, 16, 16), 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 8, 28, 28, 1, 16, 'int8'), (16, 8, 3, 3, 16, 16, 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 32, 7, 7, 1, 16), 'int8'), ('TENSOR', (32, 32, 3, 3, 16, 16), 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 32, 7, 7, 1, 16, 'int8'), (32, 32, 3, 3, 16, 16, 'int8'), (1, 1), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#        Task(func_name=topi_nn_conv2d, args=(('TENSOR', (1, 16, 14, 14, 1, 16), 'int8'), ('TENSOR', (32, 16, 3, 3, 16, 16), 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'), kwargs={}, workload=('conv2d', (1, 16, 14, 14, 1, 16, 'int8'), (32, 16, 3, 3, 16, 16, 'int8'), (2, 2), (1, 1), (1, 1), 'NCHW1n16c', 'int32'))\n#    Tuning...\n#    [Task  1/10]  Current/Best:    0.72/  23.24 GFLOPS | Progress: (480/1000) | 640.31 s Done.\n#    [Task  2/10]  Current/Best:    0.00/  27.69 GFLOPS | Progress: (576/1000) | 810.09 s Done.\n#    [Task  3/10]  Current/Best:    0.00/  22.97 GFLOPS | Progress: (1000/1000) | 1125.37 s Done.\n#    [Task  4/10]  Current/Best:    0.00/  31.26 GFLOPS | Progress: (1000/1000) | 1025.52 s Done.\n#    [Task  5/10]  Current/Best:    0.00/  15.15 GFLOPS | Progress: (1000/1000) | 1236.58 s Done.\n#    [Task  6/10]  Current/Best:    0.00/  22.74 GFLOPS | Progress: (1000/1000) | 906.60 s Done.\n#    [Task  7/10]  Current/Best:    0.00/  15.27 GFLOPS | Progress: (1000/1000) | 1056.25 s Done.\n#    [Task  8/10]  Current/Best:    0.00/   2.18 GFLOPS | Progress: (1000/1000) | 2275.29 s Done.\n#    [Task  9/10]  Current/Best:    2.23/   3.99 GFLOPS | Progress: (1000/1000) | 2527.25 s Done.\n#    [Task 10/10]  Current/Best:    1.56/   6.32 GFLOPS | Progress: (480/1000) | 1304.84 s Done.\n#    Compile...\n#    Upload...\n#    Evaluate inference time cost...\n#    Mean inference time (std dev): 621.79 ms (0.14 ms)\n\n######################################################################\n#\n# .. note:: **Experiencing Difficulties?**\n#\n#   The auto tuning module is error-prone. If you always see \" 0.00/ 0.00 GFLOPS\",\n#   then there must be something wrong.\n#\n#   First, make sure you set the correct configuration of your device.\n#   Then, you can print debug information by adding these lines in the beginning\n#   of the script. It will print every measurement result, where you can find useful\n#   error messages.\n#\n#   .. code-block:: python\n#\n#      import logging\n#      logging.getLogger('autotvm').setLevel(logging.DEBUG)\n#\n#   Finally, always feel free to ask our community for help on https://discuss.tvm.apache.org\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/frontend/deploy_classification.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy Pretrained Vision Model from MxNet on VTA\n================================================\n**Author**: `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nThis tutorial provides an end-to-end demo, on how to run ImageNet classification\ninference onto the VTA accelerator design to perform ImageNet classification tasks.\nIt showcases Relay as a front end compiler that can perform quantization (VTA\nonly supports int8/32 inference) as well as graph packing (in order to enable\ntensorization in the core) to massage the compute graph for the hardware target.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user mxnet requests \"Pillow<7\"\n#\n# Now return to the python code. Import packages.\n\nfrom __future__ import absolute_import, print_function\n\nimport argparse, json, os, requests, sys, time\nfrom io import BytesIO\nfrom os.path import join, isfile\nfrom PIL import Image\n\nfrom mxnet.gluon.model_zoo import vision\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimport tvm\nfrom tvm import te\nfrom tvm import rpc, autotvm, relay\nfrom tvm.contrib import graph_executor, utils, download\nfrom tvm.contrib.debugger import debug_executor\nfrom tvm.relay import transform\n\nimport vta\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\n\n\n# Make sure that TVM was compiled with RPC=1\nassert tvm.runtime.enabled(\"rpc\")\n\n######################################################################\n# Define the platform and model targets\n# -------------------------------------\n# Execute on CPU vs. VTA, and define the model.\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n\n# Set ``device=arm_cpu`` to run inference on the CPU\n# or ``device=vta`` to run inference on the FPGA.\ndevice = \"vta\"\ntarget = env.target if device == \"vta\" else env.target_vta_cpu\n\n# Dictionary lookup for when to start/end bit packing\npack_dict = {\n    \"resnet18_v1\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n    \"resnet34_v1\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n    \"resnet18_v2\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n    \"resnet34_v2\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n    \"resnet50_v2\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n    \"resnet101_v2\": [\"nn.max_pool2d\", \"nn.global_avg_pool2d\"],\n}\n\n# Name of Gluon model to compile\n# The ``start_pack`` and ``stop_pack`` labels indicate where\n# to start and end the graph packing relay pass: in other words\n# where to start and finish offloading to VTA.\nmodel = \"resnet18_v1\"\nassert model in pack_dict\n\n######################################################################\n# Obtain an execution remote\n# --------------------------\n# When target is 'pynq', reconfigure FPGA and runtime.\n# Otherwise, if target is 'sim', execute locally.\n\nif env.TARGET not in [\"sim\", \"tsim\", \"intelfocl\"]:\n\n    # Get remote from tracker node if environment variable is set.\n    # To set up the tracker, you'll need to follow the \"Auto-tuning\n    # a convolutional network for VTA\" tutorial.\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    # Otherwise if you have a device you want to program directly from\n    # the host, make sure you've set the variables below to the IP of\n    # your board.\n    device_host = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\n    device_port = os.environ.get(\"VTA_RPC_PORT\", \"9091\")\n    if not tracker_host or not tracker_port:\n        remote = rpc.connect(device_host, int(device_port))\n    else:\n        remote = autotvm.measure.request_remote(\n            env.TARGET, tracker_host, int(tracker_port), timeout=10000\n        )\n\n    # Reconfigure the JIT runtime and FPGA.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    reconfig_start = time.time()\n    vta.reconfig_runtime(remote)\n    vta.program_fpga(remote, bitstream=None)\n    reconfig_time = time.time() - reconfig_start\n    print(\"Reconfigured FPGA and RPC runtime in {0:.2f}s!\".format(reconfig_time))\n\n# In simulation mode, host the RPC server locally.\nelse:\n    remote = rpc.LocalSession()\n\n    if env.TARGET in [\"intelfocl\"]:\n        # program intelfocl aocx\n        vta.program_fpga(remote, bitstream=\"vta.bitstream\")\n\n# Get execution context from remote\nctx = remote.ext_dev(0) if device == \"vta\" else remote.cpu(0)\n\n######################################################################\n# Build the inference graph executor\n# ----------------------------------\n# Grab vision model from Gluon model zoo and compile with Relay.\n# The compilation steps are:\n#\n# 1. Front end translation from MxNet into Relay module.\n# 2. Apply 8-bit quantization: here we skip the first conv layer,\n#    and dense layer which will both be executed in fp32 on the CPU.\n# 3. Perform graph packing to alter the data layout for tensorization.\n# 4. Perform constant folding to reduce number of operators (e.g. eliminate batch norm multiply).\n# 5. Perform relay build to object file.\n# 6. Load the object file onto remote (FPGA device).\n# 7. Generate graph executor, `m`.\n#\n\n# Load pre-configured AutoTVM schedules\nwith autotvm.tophub.context(target):\n\n    # Populate the shape and data type dictionary for ImageNet classifier input\n    dtype_dict = {\"data\": \"float32\"}\n    shape_dict = {\"data\": (env.BATCH, 3, 224, 224)}\n\n    # Get off the shelf gluon model, and convert to relay\n    gluon_model = vision.get_model(model, pretrained=True)\n\n    # Measure build start time\n    build_start = time.time()\n\n    # Start front end compilation\n    mod, params = relay.frontend.from_mxnet(gluon_model, shape_dict)\n\n    # Update shape and type dictionary\n    shape_dict.update({k: v.shape for k, v in params.items()})\n    dtype_dict.update({k: str(v.dtype) for k, v in params.items()})\n\n    if target.device_name == \"vta\":\n        # Perform quantization in Relay\n        # Note: We set opt_level to 3 in order to fold batch norm\n        with tvm.transform.PassContext(opt_level=3):\n            with relay.quantize.qconfig(global_scale=8.0, skip_conv_layers=[0]):\n                mod = relay.quantize.quantize(mod, params=params)\n            # Perform graph packing and constant folding for VTA target\n            assert env.BLOCK_IN == env.BLOCK_OUT\n            # do device annotation if target is intelfocl or sim\n            relay_prog = graph_pack(\n                mod[\"main\"],\n                env.BATCH,\n                env.BLOCK_OUT,\n                env.WGT_WIDTH,\n                start_name=pack_dict[model][0],\n                stop_name=pack_dict[model][1],\n                device_annot=(env.TARGET == \"intelfocl\"),\n            )\n    else:\n        relay_prog = mod[\"main\"]\n\n    # Compile Relay program with AlterOpLayout disabled\n    if target.device_name != \"vta\":\n        with tvm.transform.PassContext(opt_level=3, disabled_pass={\"AlterOpLayout\"}):\n            graph, lib, params = relay.build(\n                relay_prog, target=tvm.target.Target(target, host=env.target_host), params=params\n            )\n    else:\n        if env.TARGET == \"intelfocl\":\n            # multiple targets to run both on cpu and vta\n            target = {\"cpu\": env.target_vta_cpu, \"ext_dev\": target}\n        with vta.build_config(\n            opt_level=3, disabled_pass={\"AlterOpLayout\", \"tir.CommonSubexprElimTIR\"}\n        ):\n            graph, lib, params = relay.build(\n                relay_prog, target=tvm.target.Target(target, host=env.target_host), params=params\n            )\n\n    # Measure Relay build time\n    build_time = time.time() - build_start\n    print(model + \" inference graph built in {0:.2f}s!\".format(build_time))\n\n    # Send the inference library over to the remote RPC server\n    temp = utils.tempdir()\n    lib.export_library(temp.relpath(\"graphlib.tar\"))\n    remote.upload(temp.relpath(\"graphlib.tar\"))\n    lib = remote.load_module(\"graphlib.tar\")\n\n    if env.TARGET == \"intelfocl\":\n        ctxes = [remote.ext_dev(0), remote.cpu(0)]\n        m = graph_executor.create(graph, lib, ctxes)\n    else:\n        # Graph runtime\n        m = graph_executor.create(graph, lib, ctx)\n\n######################################################################\n# Perform image classification inference\n# --------------------------------------\n# We run classification on an image sample from ImageNet\n# We just need to download the categories files, `synset.txt`\n# and an input test image.\n\n# Download ImageNet categories\ncateg_url = \"https://github.com/uwsampl/web-data/raw/main/vta/models/\"\ncateg_fn = \"synset.txt\"\ndownload.download(join(categ_url, categ_fn), categ_fn)\nsynset = eval(open(categ_fn).read())\n\n# Download test image\nimage_url = \"https://homes.cs.washington.edu/~moreau/media/vta/cat.jpg\"\nimage_fn = \"cat.png\"\ndownload.download(image_url, image_fn)\n\n# Prepare test image for inference\nimage = Image.open(image_fn).resize((224, 224))\nplt.imshow(image)\nplt.show()\nimage = np.array(image) - np.array([123.0, 117.0, 104.0])\nimage /= np.array([58.395, 57.12, 57.375])\nimage = image.transpose((2, 0, 1))\nimage = image[np.newaxis, :]\nimage = np.repeat(image, env.BATCH, axis=0)\n\n# Set the network parameters and inputs\nm.set_input(**params)\nm.set_input(\"data\", image)\n\n# Perform inference and gather execution statistics\n# More on: :py:method:`tvm.runtime.Module.time_evaluator`\nnum = 4  # number of times we run module for a single measurement\nrep = 3  # number of measurements (we derive std dev from this)\ntimer = m.module.time_evaluator(\"run\", ctx, number=num, repeat=rep)\n\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n    timer()\n    sim_stats = simulator.stats()\n    print(\"\\nExecution statistics:\")\n    for k, v in sim_stats.items():\n        # Since we execute the workload many times, we need to normalize stats\n        # Note that there is always one warm up run\n        # Therefore we divide the overall stats by (num * rep + 1)\n        print(\"\\t{:<16}: {:>16}\".format(k, v // (num * rep + 1)))\nelse:\n    tcost = timer()\n    std = np.std(tcost.results) * 1000\n    mean = tcost.mean * 1000\n    print(\"\\nPerformed inference in %.2fms (std = %.2f) for %d samples\" % (mean, std, env.BATCH))\n    print(\"Average per sample inference time: %.2fms\" % (mean / env.BATCH))\n\n# Get classification results\ntvm_output = m.get_output(0, tvm.nd.empty((env.BATCH, 1000), \"float32\", remote.cpu(0)))\nfor b in range(env.BATCH):\n    top_categories = np.argsort(tvm_output.numpy()[b])\n    # Report top-5 classification results\n    print(\"\\n{} prediction for sample {}\".format(model, b))\n    print(\"\\t#1:\", synset[top_categories[-1]])\n    print(\"\\t#2:\", synset[top_categories[-2]])\n    print(\"\\t#3:\", synset[top_categories[-3]])\n    print(\"\\t#4:\", synset[top_categories[-4]])\n    print(\"\\t#5:\", synset[top_categories[-5]])\n    # This just checks that one of the 5 top categories\n    # is one variety of cat; this is by no means an accurate\n    # assessment of how quantization affects classification\n    # accuracy but is meant to catch changes to the\n    # quantization pass that would accuracy in the CI.\n    cat_detected = False\n    for k in top_categories[-5:]:\n        if \"cat\" in synset[k]:\n            cat_detected = True\n    assert cat_detected\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/frontend/deploy_detection.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDeploy Pretrained Vision Detection Model from Darknet on VTA\n============================================================\n**Author**: `Hua Jiang <https://github.com/huajsj>`_\n\nThis tutorial provides an end-to-end demo, on how to run Darknet YoloV3-tiny\ninference onto the VTA accelerator design to perform Image detection tasks.\nIt showcases Relay as a front end compiler that can perform quantization (VTA\nonly supports int8/32 inference) as well as graph packing (in order to enable\ntensorization in the core) to massage the compute graph for the hardware target.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install \"Pillow<7\"\n#\n# YOLO-V3-tiny Model with Darknet parsing have dependancy with CFFI and CV2 library,\n# we need to install CFFI and CV2 before executing this script.\n#\n# .. code-block:: bash\n#\n#   pip3 install cffi\n#   pip3 install opencv-python\n#\n# Now return to the python code. Import packages.\n\nfrom __future__ import absolute_import, print_function\n\nimport sys\nimport os\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tvm\nimport vta\nfrom tvm import rpc, autotvm, relay\nfrom tvm.relay.testing import yolo_detection, darknet\nfrom tvm.relay.testing.darknet import __darknetffi__\nfrom tvm.contrib import graph_executor, utils\nfrom tvm.contrib.download import download_testdata\nfrom vta.testing import simulator\nfrom vta.top import graph_pack\n\n# Make sure that TVM was compiled with RPC=1\nassert tvm.runtime.enabled(\"rpc\")\n\n##############################################################################\n# Download yolo net configure file, weight file, darknet library file based on\n# Model Name\n# ----------------------------------------------------------------------------\nMODEL_NAME = \"yolov3-tiny\"\nREPO_URL = \"https://github.com/dmlc/web-data/blob/main/darknet/\"\n\ncfg_path = download_testdata(\n    \"https://github.com/pjreddie/darknet/blob/master/cfg/\" + MODEL_NAME + \".cfg\" + \"?raw=true\",\n    MODEL_NAME + \".cfg\",\n    module=\"darknet\",\n)\nweights_path = download_testdata(\n    \"https://pjreddie.com/media/files/\" + MODEL_NAME + \".weights\" + \"?raw=true\",\n    MODEL_NAME + \".weights\",\n    module=\"darknet\",\n)\n\nif sys.platform in [\"linux\", \"linux2\"]:\n    darknet_lib_path = download_testdata(\n        REPO_URL + \"lib/\" + \"libdarknet2.0.so\" + \"?raw=true\", \"libdarknet2.0.so\", module=\"darknet\"\n    )\nelif sys.platform == \"darwin\":\n    darknet_lib_path = download_testdata(\n        REPO_URL + \"lib_osx/\" + \"libdarknet_mac2.0.so\" + \"?raw=true\",\n        \"libdarknet_mac2.0.so\",\n        module=\"darknet\",\n    )\nelse:\n    raise NotImplementedError(\"Darknet lib is not supported on {} platform\".format(sys.platform))\n\n##################################################\n# Download yolo categories and illustration front.\n# ------------------------------------------------\ncoco_path = download_testdata(\n    REPO_URL + \"data/\" + \"coco.names\" + \"?raw=true\", \"coco.names\", module=\"data\"\n)\nfont_path = download_testdata(\n    REPO_URL + \"data/\" + \"arial.ttf\" + \"?raw=true\", \"arial.ttf\", module=\"data\"\n)\nwith open(coco_path) as f:\n    content = f.readlines()\nnames = [x.strip() for x in content]\n\n########################################\n# Define the platform and model targets.\n# --------------------------------------\n# Execute on CPU vs. VTA, and define the model.\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n# Set ``device=arm_cpu`` to run inference on the CPU\n# or ``device=vta`` to run inference on the FPGA.\ndevice = \"vta\"\ntarget = env.target if device == \"vta\" else env.target_vta_cpu\n\npack_dict = {\n    \"yolov3-tiny\": [\"nn.max_pool2d\", \"cast\", 4, 186],\n}\n\n# Name of Darknet model to compile\n# The ``start_pack`` and ``stop_pack`` labels indicate where\n# to start and end the graph packing relay pass: in other words\n# where to start and finish offloading to VTA.\n# the number 4 indicate the ``start_pack`` index is 4, the\n# number 186 indicate the ``stop_pack index`` is 186, by using\n# name and index number, here we can located to correct place\n# where to start/end when there are multiple ``nn.max_pool2d``\n# or ``cast``, print(mod.astext(show_meta_data=False)) can help\n# to find operator name and index information.\nassert MODEL_NAME in pack_dict\n\n#############################\n# Obtain an execution remote.\n# ---------------------------\n# When target is 'pynq' or other FPGA backend, reconfigure FPGA and runtime.\n# Otherwise, if target is 'sim', execute locally.\n\nif env.TARGET not in [\"sim\", \"tsim\"]:\n    # Get remote from tracker node if environment variable is set.\n    # To set up the tracker, you'll need to follow the \"Auto-tuning\n    # a convolutional network for VTA\" tutorial.\n    tracker_host = os.environ.get(\"TVM_TRACKER_HOST\", None)\n    tracker_port = os.environ.get(\"TVM_TRACKER_PORT\", None)\n    # Otherwise if you have a device you want to program directly from\n    # the host, make sure you've set the variables below to the IP of\n    # your board.\n    device_host = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\n    device_port = os.environ.get(\"VTA_RPC_PORT\", \"9091\")\n    if not tracker_host or not tracker_port:\n        remote = rpc.connect(device_host, int(device_port))\n    else:\n        remote = autotvm.measure.request_remote(\n            env.TARGET, tracker_host, int(tracker_port), timeout=10000\n        )\n    # Reconfigure the JIT runtime and FPGA.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    reconfig_start = time.time()\n    vta.reconfig_runtime(remote)\n    vta.program_fpga(remote, bitstream=None)\n    reconfig_time = time.time() - reconfig_start\n    print(\"Reconfigured FPGA and RPC runtime in {0:.2f}s!\".format(reconfig_time))\n\n# In simulation mode, host the RPC server locally.\nelse:\n    remote = rpc.LocalSession()\n\n# Get execution context from remote\nctx = remote.ext_dev(0) if device == \"vta\" else remote.cpu(0)\n\n#####################################\n# Build the inference graph executor.\n# -----------------------------------\n# Using Darknet library load downloaded vision model and compile with Relay.\n# The compilation steps are:\n#\n# 1. Front end translation from Darknet into Relay module.\n# 2. Apply 8-bit quantization: here we skip the first conv layer,\n#    and dense layer which will both be executed in fp32 on the CPU.\n# 3. Perform graph packing to alter the data layout for tensorization.\n# 4. Perform constant folding to reduce number of operators (e.g. eliminate batch norm multiply).\n# 5. Perform relay build to object file.\n# 6. Load the object file onto remote (FPGA device).\n# 7. Generate graph executor, `m`.\n\n# Load pre-configured AutoTVM schedules\nwith autotvm.tophub.context(target):\n    net = __darknetffi__.dlopen(darknet_lib_path).load_network(\n        cfg_path.encode(\"utf-8\"), weights_path.encode(\"utf-8\"), 0\n    )\n    dshape = (env.BATCH, net.c, net.h, net.w)\n    dtype = \"float32\"\n\n    # Measure build start time\n    build_start = time.time()\n\n    # Start front end compilation\n    mod, params = relay.frontend.from_darknet(net, dtype=dtype, shape=dshape)\n\n    if target.device_name == \"vta\":\n        # Perform quantization in Relay\n        # Note: We set opt_level to 3 in order to fold batch norm\n        with tvm.transform.PassContext(opt_level=3):\n            with relay.quantize.qconfig(\n                global_scale=23.0,\n                skip_conv_layers=[0],\n                store_lowbit_output=True,\n                round_for_shift=True,\n            ):\n                mod = relay.quantize.quantize(mod, params=params)\n            # Perform graph packing and constant folding for VTA target\n            mod = graph_pack(\n                mod[\"main\"],\n                env.BATCH,\n                env.BLOCK_OUT,\n                env.WGT_WIDTH,\n                start_name=pack_dict[MODEL_NAME][0],\n                stop_name=pack_dict[MODEL_NAME][1],\n                start_name_idx=pack_dict[MODEL_NAME][2],\n                stop_name_idx=pack_dict[MODEL_NAME][3],\n            )\n    else:\n        mod = mod[\"main\"]\n\n    # Compile Relay program with AlterOpLayout disabled\n    with vta.build_config(disabled_pass={\"AlterOpLayout\", \"tir.CommonSubexprElimTIR\"}):\n        lib = relay.build(\n            mod, target=tvm.target.Target(target, host=env.target_host), params=params\n        )\n\n    # Measure Relay build time\n    build_time = time.time() - build_start\n    print(MODEL_NAME + \" inference graph built in {0:.2f}s!\".format(build_time))\n\n    # Send the inference library over to the remote RPC server\n    temp = utils.tempdir()\n    lib.export_library(temp.relpath(\"graphlib.tar\"))\n    remote.upload(temp.relpath(\"graphlib.tar\"))\n    lib = remote.load_module(\"graphlib.tar\")\n\n    # Graph executor\n    m = graph_executor.GraphModule(lib[\"default\"](ctx))\n\n####################################\n# Perform image detection inference.\n# ----------------------------------\n# We run detect on an downloaded image\n# Download test image\n[neth, netw] = dshape[2:]\ntest_image = \"person.jpg\"\nimg_url = REPO_URL + \"data/\" + test_image + \"?raw=true\"\nimg_path = download_testdata(img_url, test_image, \"data\")\ndata = darknet.load_image(img_path, neth, netw).transpose(1, 2, 0)\n\n# Prepare test image for inference\nplt.imshow(data)\nplt.show()\ndata = data.transpose((2, 0, 1))\ndata = data[np.newaxis, :]\ndata = np.repeat(data, env.BATCH, axis=0)\n\n# Set the network parameters and inputs\nm.set_input(\"data\", data)\n\n# Perform inference and gather execution statistics\n# More on: :py:method:`tvm.runtime.Module.time_evaluator`\nnum = 4  # number of times we run module for a single measurement\nrep = 3  # number of measurements (we derive std dev from this)\ntimer = m.module.time_evaluator(\"run\", ctx, number=num, repeat=rep)\n\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n    timer()\n    sim_stats = simulator.stats()\n    print(\"\\nExecution statistics:\")\n    for k, v in sim_stats.items():\n        # Since we execute the workload many times, we need to normalize stats\n        # Note that there is always one warm up run\n        # Therefore we divide the overall stats by (num * rep + 1)\n        print(\"\\t{:<16}: {:>16}\".format(k, v // (num * rep + 1)))\nelse:\n    tcost = timer()\n    std = np.std(tcost.results) * 1000\n    mean = tcost.mean * 1000\n    print(\"\\nPerformed inference in %.2fms (std = %.2f) for %d samples\" % (mean, std, env.BATCH))\n    print(\"Average per sample inference time: %.2fms\" % (mean / env.BATCH))\n\n# Get detection results from out\nthresh = 0.5\nnms_thresh = 0.45\ntvm_out = []\nfor i in range(2):\n    layer_out = {}\n    layer_out[\"type\"] = \"Yolo\"\n    # Get the yolo layer attributes (n, out_c, out_h, out_w, classes, total)\n    layer_attr = m.get_output(i * 4 + 3).numpy()\n    layer_out[\"biases\"] = m.get_output(i * 4 + 2).numpy()\n    layer_out[\"mask\"] = m.get_output(i * 4 + 1).numpy()\n    out_shape = (layer_attr[0], layer_attr[1] // layer_attr[0], layer_attr[2], layer_attr[3])\n    layer_out[\"output\"] = m.get_output(i * 4).numpy().reshape(out_shape)\n    layer_out[\"classes\"] = layer_attr[4]\n    tvm_out.append(layer_out)\n    thresh = 0.560\n\n# Show detection results\nimg = darknet.load_image_color(img_path)\n_, im_h, im_w = img.shape\ndets = yolo_detection.fill_network_boxes((netw, neth), (im_w, im_h), thresh, 1, tvm_out)\nlast_layer = net.layers[net.n - 1]\nyolo_detection.do_nms_sort(dets, last_layer.classes, nms_thresh)\nyolo_detection.draw_detections(font_path, img, dets, thresh, names, last_layer.classes)\nplt.imshow(img.transpose(1, 2, 0))\nplt.show()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/matrix_multiply.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _basic-mat-mult:\n\nSimple Matrix Multiply\n======================\n**Author**: `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nIn this tutorial, we will build on top of the :ref:`vta-get-started` tutorial\nand introduce additional concepts required to implement matrix multiplication\non VTA with the TVM workflow.\n\"\"\"\n\n######################################################################\n# RPC Setup\n# ---------\n# We start by programming the Pynq's FPGA and building its RPC runtime\n# as we did in the VTA introductory tutorial.\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport tvm\nfrom tvm import te\nimport vta\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.contrib import utils\nfrom vta.testing import simulator\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n\n# We read the Pynq RPC host IP address and port number from the OS environment\nhost = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n# We configure both the bitstream and the runtime system on the Pynq\n# to match the VTA configuration specified by the vta_config.json file.\nif env.TARGET == \"pynq\" or env.TARGET == \"de10nano\":\n\n    # Make sure that TVM was compiled with RPC=1\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n\n    # Reconfigure the JIT runtime\n    vta.reconfig_runtime(remote)\n\n    # Program the FPGA with a pre-compiled VTA bitstream.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    vta.program_fpga(remote, bitstream=None)\n\n# In simulation mode, host the RPC server locally.\nelif env.TARGET in [\"sim\", \"tsim\"]:\n    remote = rpc.LocalSession()\n\n######################################################################\n# Computation Declaration\n# -----------------------\n# In this example we describe a simple matrix multiplication addition, which\n# requires multiple computation stages, as shown in the dataflow diagram below.\n# First we describe the input tensors :code:`A` and :code:`B` that are living\n# in main memory.\n# Second, we need to declare intermediate tensors :code:`A_buf` and\n# :code:`B_buf`, which will live in VTA's on-chip buffers.\n# Having this extra computational stage allows us to explicitly\n# stage cached reads and writes.\n# Third, we describe the matrix multiplication computation over\n# :code:`A_buf` and :code:`B_buf` to produce the product matrix :code:`C_buf`.\n# The last operation is a cast and copy back to DRAM, into results tensor\n# :code:`C`.\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/gemm_dataflow.png\n#      :align: center\n\n######################################################################\n# Data Layout\n# ~~~~~~~~~~~\n# We describe the placeholder tensors :code:`A`, and :code:`B` in a tiled data\n# format to match the data layout requirements imposed by the VTA tensor core.\n\n######################################################################\n# .. note::\n#\n#   **Data Tiling**\n#\n#   One source of complexity when targeting accelerators is to make sure\n#   that the data layout matches the layout imposed by the accelerator design.\n#   VTA is designed around a *tensor core* that performs, one matrix-matrix\n#   operation per cycle between an activation matrix and a weight matrix,\n#   adding the result matrix to an accumulator matrix, as shown in the\n#   figure below.\n#\n#   .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/tensor_core.png\n#        :align: center\n#        :width: 480px\n#\n#   The dimensions of that matrix-matrix multiplication are specified in\n#   the :code:`vta_config.json` configuration file.\n#   The activation matrix has a :code:`(BATCH, BLOCK_IN)` shape\n#   and the transposed weight matrix has a :code:`(BLOCK_OUT, BLOCK_IN)` shape,\n#   thus inferring that the resulting output matrix has a\n#   :code:`(BATCH, BLOCK_OUT)` shape.\n#   Consequently input and output tensors processed by VTA need to be\n#   tiled according to these aforementioned dimension.\n#\n#   The diagram below shows the impact of data tiling on a matrix that is\n#   originally of shape (4, 8).\n#   Tiling by a (2, 2) tile shape ensures that data within each tile is\n#   contiguous.\n#   The resulting tiled tensor has a shape of (2, 4, 2, 2).\n#\n#   .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/data_tiling.png\n#        :align: center\n#        :width: 480px\n#\n# We first define the variables :code:`m`, :code:`n`, :code:`o` to represent\n# the shape of the matrix multiplication. These variables are multiplicative\n# factors over the :code:`BLOCK_OUT`, :code:`BLOCK_IN`, and :code:`BATCH`\n# tensor dimensions respectively.\n# By default, the configuration file sets :code:`BATCH`, :code:`BLOCK_IN`, and\n# :code:`BLOCK_OUT` to be 1, 16 and 16 respectively (:code:`BATCH` being set to\n# 1 implies that our compute building block is vector-matrix multiply).\n#\n\n######################################################################\n# .. note::\n#\n#   **Data Types**\n#\n#   It's important to not only match the inner-tile\n#   dimension of VTA's tensor core, but also to match the specific data types\n#   expected by VTA.\n#   VTA for now only supports fixed point data types, which integer width is\n#   specified in the :code:`vta_config.json` file by :code:`INP_WIDTH` and\n#   :code:`WGT_WIDTH` for the activations and weights data types respectively.\n#   In addition, the accumulator data type integer width is specified by\n#   :code:`ACC_WIDTH`.\n#\n# By default, the configuration file sets :code:`INP_WIDTH`\n# and :code:`WGT_WIDTH` to 8.\n# The accumulator width :code:`ACC_WIDTH` is set to 32, in order to avoid\n# overflow during accumulation.\n# As a result, :code:`env.inp_dtype` and :code:`env.wgt_dtype` are all\n# narrow 8-bit integers, while :code:`env.acc_dtype` is a standard 32-bit\n# integer.\n\n# Output channel factor m - total 16x16=256 output channels\nm = 16\n# Input channel factor n - total 16x16=256 input channels\nn = 16\n# Batch factor o (we use single batch inference)\no = 1\n# A placeholder tensor in tiled data format\nA = te.placeholder((o, n, env.BATCH, env.BLOCK_IN), name=\"A\", dtype=env.inp_dtype)\n# B placeholder tensor in tiled data format\nB = te.placeholder((m, n, env.BLOCK_OUT, env.BLOCK_IN), name=\"B\", dtype=env.wgt_dtype)\n# A copy buffer\nA_buf = te.compute((o, n, env.BATCH, env.BLOCK_IN), lambda *i: A(*i), \"A_buf\")\n# B copy buffer\nB_buf = te.compute((m, n, env.BLOCK_OUT, env.BLOCK_IN), lambda *i: B(*i), \"B_buf\")\n\n######################################################################\n# Matrix Multiplication\n# ~~~~~~~~~~~~~~~~~~~~~\n# Now we're ready to describe the matrix multiplication result tensor :code:`C`,\n# with another compute operation.\n# The compute function takes the shape of the tensor, as well as a lambda\n# function that describes the computation rule for each position of the tensor.\n#\n# In order to implement matrix multiplication, the lambda function needs to\n# include a reduction formula over the input channel dimension axes.\n# To create a reduction formula, we can declare a reduction axis using\n# :code:`te.reduce_axis`, which takes in the range of reductions.\n# :code:`te.sum` takes in the expression to be reduced as well as\n# the reduction axes to compute the sum of value over all k in the declared\n# ranges.\n#\n# Note that the reduction needs to be performed over 32-bit :code:`env.acc_dtype`\n# accumulator data types.\n#\n# No computation happens during this phase, as we are only declaring how\n# the computation should be done.\n\n# Outer input feature reduction axis\nko = te.reduce_axis((0, n), name=\"ko\")\n# Inner input feature reduction axis\nki = te.reduce_axis((0, env.BLOCK_IN), name=\"ki\")\n# Describe the in-VTA matrix multiplication\nC_buf = te.compute(\n    (o, m, env.BATCH, env.BLOCK_OUT),\n    lambda bo, co, bi, ci: te.sum(\n        A_buf[bo, ko, bi, ki].astype(env.acc_dtype) * B_buf[co, ko, ci, ki].astype(env.acc_dtype),\n        axis=[ko, ki],\n    ),\n    name=\"C_buf\",\n)\n\n######################################################################\n# Casting the Results\n# ~~~~~~~~~~~~~~~~~~~\n# After the computation is done, we'll need to send the results computed by VTA\n# back to main memory.\n\n######################################################################\n# .. note::\n#\n#   **Memory Store Restrictions**\n#\n#   One specificity of VTA is that it only supports DRAM stores in the narrow\n#   :code:`env.inp_dtype` data type format.\n#   This lets us reduce the data footprint for memory transfers, but also lets\n#   us quantize the wide accumulator data type down to a data format that\n#   matches the input activation data type.\n#   This means that in the context of neural network inference, the outputs\n#   of a given layer after activation can be consumed directly by the next\n#   layer.\n#\n# We perform one last typecast operation to the narrow\n# input activation data format.\n\n# Cast to output type, and send to main memory\nC = te.compute(\n    (o, m, env.BATCH, env.BLOCK_OUT), lambda *i: C_buf(*i).astype(env.inp_dtype), name=\"C\"\n)\n\n######################################################################\n# This concludes the computation declaration part of this tutorial.\n\n######################################################################\n# Scheduling the Computation\n# --------------------------\n# While the above lines describes the computation rule, we can obtain\n# :code:`C` in many ways.\n# TVM asks the user to provide an implementation of the computation called\n# *schedule*.\n#\n# A schedule is a set of transformations to an original computation that\n# transforms the implementation of the computation without affecting\n# correctness.\n# This simple VTA programming tutorial aims to demonstrate basic schedule\n# transformations that will map the original schedule down to VTA hardware\n# primitives.\n\n\n######################################################################\n# Default Schedule\n# ~~~~~~~~~~~~~~~~\n# After we construct the schedule, by default the schedule computes\n# :code:`C` in the following way:\n\n# Let's take a look at the generated schedule\ns = te.create_schedule(C.op)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Although this schedule makes sense, it won't compile to VTA.\n# In order to obtain correct code generation, we need to apply scheduling\n# primitives and code annotation that will transform the schedule into\n# one that can be directly lowered onto VTA hardware intrinsics.\n# Those include:\n#\n#  - DMA copy operations which will take globally-scoped tensors and copy\n#    those into locally-scoped tensors.\n#  - Tensor operations that will perform the matrix multiplication.\n\n######################################################################\n# Buffer Scopes\n# ~~~~~~~~~~~~~\n# First, we set the scope of the buffers to tell TVM that these buffers\n# will be living in the VTA's on-chip SRAM caches.\n# Below, we tell TVM that :code:`A_buf`, :code:`B_buf`, :code:`C_buf`\n# will respectively live in VTA's on-chip input, weight and accumulator\n# memory.\n\n######################################################################\n# .. note::\n#\n#   **VTA's On-Chip SRAMs**\n#\n#   VTA has three different memory scopes, each corresponding to different\n#   on-chip SRAM buffers.\n#\n#    - :code:`env.inp_scope`: Input buffer, which is a read-only SRAM buffer\n#      that stores input matrices of shape :code:`(env.BATCH, env.BLOCK_IN)`\n#      of type :code:`env.inp_dtype`. The input buffer contains\n#      `2 ^ LOG_INP_BUFF_SIZE` matrix elements (as specified in the\n#      :code:`vta_config.json` file).\n#    - :code:`env.wgt_scope`: Weight buffer, which is a read-only SRAM buffer\n#      that stores weight matrices of shape :code:`(env.BLOCK_OUT, env.BLOCK_IN)`\n#      of type :code:`env.wgt_dtype`. The weight buffer contains\n#      `2 ^ LOG_WGT_BUFF_SIZE` matrix elements.\n#    - :code:`env.acc_scope`: Accumulator buffer, which is a read/write SRAM\n#      buffer that stores accumulator matrices of shape\n#      :code:`(env.BATCH, env.BLOCK_OUT)` of type :code:`env.acc_dtype`.\n#      The accumulator buffer is VTA's general purpose register file: it holds\n#      both intermediate results of convolutions and matrix multiplications\n#      as well as intermediate results of pooling, batch normalization, and\n#      activation layers. The accumulator buffer contains\n#      `2 ^ LOG_ACC_BUFF_SIZE` matrix elements.\n\n# Set the intermediate tensor's scope to VTA's on-chip buffers\ns[A_buf].set_scope(env.inp_scope)\ns[B_buf].set_scope(env.wgt_scope)\ns[C_buf].set_scope(env.acc_scope)\n\n######################################################################\n# DMA Transfers\n# ~~~~~~~~~~~~~\n# We need to schedule DMA transfers to move data living in DRAM to\n# and from the VTA on-chip buffers.\n# This can be achieved using the :code:`compute_at` schedule primitive\n# which nests the copying of the buffers into the computation loop\n# that performs the matrix multiplication.\n#\n# We insert :code:`dma_copy` pragmas to indicate to the compiler\n# that the copy operations will be performed in bulk via DMA,\n# which is common in hardware accelerators.\n# Finally, we print the temporary schedule to observe the effects of\n# moving the copy operations into the matrix multiplication loop.\n\n# Move buffer copy into matrix multiply loop\ns[A_buf].compute_at(s[C_buf], ko)\ns[B_buf].compute_at(s[C_buf], ko)\n\n# Tag the buffer copies with the DMA pragma to insert a DMA transfer\ns[A_buf].pragma(s[A_buf].op.axis[0], env.dma_copy)\ns[B_buf].pragma(s[B_buf].op.axis[0], env.dma_copy)\ns[C].pragma(s[C].op.axis[0], env.dma_copy)\n\n# Let's take a look at the transformed schedule\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Tensorization\n# ~~~~~~~~~~~~~\n# The last step of the schedule transformation consists in applying\n# *tensorization* to our schedule.\n# Tensorization is analogous to vectorization, but extends the concept\n# to a higher-dimensional unit of computation.\n# Consequently, tensorization imposes data layout constraints as discussed\n# earlier when declaring the data layout input placeholders.\n# We've already arranged our tensors in a tiled format, so the next thing\n# we need to perform is loop reordering to accommodate for tensorization.\n#\n# Here we choose to move the outermost reduction axis all the way out.\n# This dictates that we first iterate over input channels, then batch\n# dimensions, and finally output channels.\n# Lastly, we apply the tensorization scheduling primitive :code:`tensorize`\n# along the outer axis of the inner-most matrix matrix multiplication tensor\n# block.\n# We print the finalized schedule that is ready for code-generation\n# by the VTA runtime JIT compiler.\n\ns[C_buf].reorder(\n    ko, s[C_buf].op.axis[0], s[C_buf].op.axis[1], s[C_buf].op.axis[2], s[C_buf].op.axis[3], ki\n)\ns[C_buf].tensorize(s[C_buf].op.axis[2], env.gemm)\n\n# Let's take a look at the finalized schedule\nprint(vta.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# This concludes the scheduling portion of this tutorial.\n\n######################################################################\n# TVM Compilation\n# ---------------\n# After we have finished specifying the schedule, we can compile it\n# into a TVM function.\n\n# Build GEMM VTA kernel\nmy_gemm = vta.build(\n    s, [A, B, C], tvm.target.Target(\"ext_dev\", host=env.target_host), name=\"my_gemm\"\n)\n\n# Write the compiled module into an object file.\ntemp = utils.tempdir()\nmy_gemm.save(temp.relpath(\"gemm.o\"))\n\n# Send the executable over RPC\nremote.upload(temp.relpath(\"gemm.o\"))\n\n# Load the compiled module\nf = remote.load_module(\"gemm.o\")\n\n######################################################################\n# Running the Function\n# --------------------\n# The compiled TVM function uses a concise C API and can be invoked from\n# code language.\n#\n# TVM provides an array API in python to aid quick testing and prototyping.\n# The array API is based on `DLPack <https://github.com/dmlc/dlpack>`_ standard.\n#\n# - We first create a remote context (for remote execution on the Pynq).\n# - Then :code:`tvm.nd.array` formats the data accordingly.\n# - :code:`f()` runs the actual computation.\n# - :code:`numpy()` copies the result array back in a format that can be\n#   interpreted.\n#\n\n# Get the remote device context\nctx = remote.ext_dev(0)\n\n# Initialize the A and B arrays randomly in the int range of (-128, 128]\nA_orig = np.random.randint(-128, 128, size=(o * env.BATCH, n * env.BLOCK_IN)).astype(A.dtype)\nB_orig = np.random.randint(-128, 128, size=(m * env.BLOCK_OUT, n * env.BLOCK_IN)).astype(B.dtype)\n\n# Apply packing to the A and B arrays from a 2D to a 4D packed layout\nA_packed = A_orig.reshape(o, env.BATCH, n, env.BLOCK_IN).transpose((0, 2, 1, 3))\nB_packed = B_orig.reshape(m, env.BLOCK_OUT, n, env.BLOCK_IN).transpose((0, 2, 1, 3))\n\n# Format the input/output arrays with tvm.nd.array to the DLPack standard\nA_nd = tvm.nd.array(A_packed, ctx)\nB_nd = tvm.nd.array(B_packed, ctx)\nC_nd = tvm.nd.array(np.zeros((o, m, env.BATCH, env.BLOCK_OUT)).astype(C.dtype), ctx)\n\n# Clear stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n\n# Invoke the module to perform the computation\nf(A_nd, B_nd, C_nd)\n\n######################################################################\n# Verifying Correctness\n# ---------------------\n# Compute the reference result with numpy and assert that the output of the\n# matrix multiplication indeed is correct\n\n# Compute reference result with numpy\nC_ref = np.dot(A_orig.astype(env.acc_dtype), B_orig.T.astype(env.acc_dtype)).astype(C.dtype)\nC_ref = C_ref.reshape(o, env.BATCH, m, env.BLOCK_OUT).transpose((0, 2, 1, 3))\nnp.testing.assert_equal(C_ref, C_nd.numpy())\n\n# Print stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    sim_stats = simulator.stats()\n    print(\"Execution statistics:\")\n    for k, v in sim_stats.items():\n        print(\"\\t{:<16}: {:>16}\".format(k, v))\n\nprint(\"Successful matrix multiply test!\")\n\n######################################################################\n# Summary\n# -------\n# This tutorial showcases the TVM workflow to implement a simple matrix\n# multiplication example on VTA.\n# The general workflow includes:\n#\n# - Programming the FPGA with the VTA bitstream over RPC.\n# - Describing matrix multiplication via a series of computations.\n# - Describing how we want to perform the computation using schedule primitives.\n# - Compiling the function to the VTA target.\n# - Running the compiled module and verifying it against a numpy implementation.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/optimize/convolution_opt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n2D Convolution Optimization\n===========================\n**Author**: `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nThis tutorial provides an overview on how to use TVM to map a 2D convolution\nworkload efficiently on the VTA design.\nWe recommend covering the :ref:`vta-mat-mult-opt` tutorial first.\n\n2D convolution is dominant in most computer vision deep neural networks.\nIn this tutorial, we will demonstrate TVM schedule optimizations to map\n2D convolution operators in NCHW layout onto VTA.\nWe also introduce the notion of latency hiding, which allows us to\nmaximize VTA's compute and memory resource utilization.\n\"\"\"\n\n######################################################################\n# RPC Setup\n# ---------\n# We start by programming the Pynq's FPGA and building its RPC runtime.\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport tvm\nimport tvm.testing\nfrom tvm import te\nimport vta\nimport numpy as np\n\nfrom tvm import rpc\nfrom tvm.contrib import utils\nfrom vta.testing import simulator\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n\n# We read the Pynq RPC host IP address and port number from the OS environment\nhost = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n# We configure both the bitstream and the runtime system on the Pynq\n# to match the VTA configuration specified by the vta_config.json file.\nif env.TARGET == \"pynq\":\n\n    # Make sure that TVM was compiled with RPC=1\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n\n    # Reconfigure the JIT runtime\n    vta.reconfig_runtime(remote)\n\n    # Program the FPGA with a pre-compiled VTA bitstream.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    vta.program_fpga(remote, bitstream=None)\n\n# In simulation mode, host the RPC server locally.\nelif env.TARGET in [\"sim\", \"tsim\"]:\n    remote = rpc.LocalSession()\n\n######################################################################\n# Computation Declaration\n# -----------------------\n# As a first step, we need to describe our 2D convolution computation\n# in NCHW format.\n#\n# We define the 2D convolution shape by the batch size,\n# spatial dimensions, input channels, output channels, kernel dimensions,\n# kernel dimensions, padding dimensions, and stride dimensions.\n#\n# We pick the shape of the 9th convolutional layer of the ResNet-18\n# architecture as our convolution workload parameters.\n#\n# We've added extra operators to the 2D convolution that apply\n# shifting and clipping to the output in order to mimic a fixed-point\n# convolution followed by a rectified linear activation.\n# We describe the TVM dataflow graph of the 2D convolution layer below:\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/conv2d_dataflow.png\n#      :align: center\n#\n# This computation is intentionally too large to fit onto VTA's on-chip\n# buffers all at once. Therefore in the scheduling phase we'll\n# rely on computation blocking strategies to break the computation down into\n# manageable chunks.\n#\n# .. note::\n#\n#   *Spatial padding*\n#\n#   Note that we'll need to import the TOPI library to apply spatial padding\n#   on the input feature map tensor.\n#   Spatial padding facilitates blocking in the context of 2D convolutions\n#   due to the fact that the same (x, y) spatial location of the input\n#   feature map of any given layer is read more than once if the convolution\n#   kernel window size is greater than one.\n#   On CPUs, and GPUs, one way to increase efficiency of memory accesses\n#   when parallelizing work is spatial packing, which requires data re-layout.\n#   VTA load DMA engine can insert padding automatically so that the original\n#   input feature map does not have to be re-packed in memory.\n#\n#   We show the effect of VTA's on the fly spatial padding when data is being\n#   loaded from DRAM into VTA's SRAM, following a 2D strided and padded memory\n#   read.\n#\n#   .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/padding.png\n#        :align: center\n#        :width: 480px\n\nfrom tvm import topi\n\n# 2D convolution layer dimensions taken from ResNet-18 architecture\n# (9th convolutional layer)\nbatch_size = 1\nheight = 14\nwidth = 14\nin_channels = 256\nout_channels = 256\nkernel_h = 3\nkernel_w = 3\npad_h = 1\npad_w = 1\nstride_h = 1\nstride_w = 1\nassert batch_size % env.BATCH == 0\nassert in_channels % env.BLOCK_IN == 0\nassert out_channels % env.BLOCK_OUT == 0\n\n# Input feature map: (N, IC, H, W, n, ic)\ndata_shape = (\n    batch_size // env.BATCH,\n    in_channels // env.BLOCK_IN,\n    height,\n    width,\n    env.BATCH,\n    env.BLOCK_IN,\n)\n# Kernel: (OC, IC, H, W, oc, ic)\nkernel_shape = (\n    out_channels // env.BLOCK_OUT,\n    in_channels // env.BLOCK_IN,\n    kernel_h,\n    kernel_w,\n    env.BLOCK_OUT,\n    env.BLOCK_IN,\n)\n# Derive output feature map dimensions\nfout_height = (height + 2 * pad_h - kernel_h) // stride_h + 1\nfout_width = (width + 2 * pad_w - kernel_w) // stride_w + 1\n# Output feature map: (N, OC, H, W, n, oc)\noutput_shape = (\n    batch_size // env.BATCH,\n    out_channels // env.BLOCK_OUT,\n    fout_height,\n    fout_width,\n    env.BATCH,\n    env.BLOCK_OUT,\n)\n\n# Convolution reduction axes\ndy = te.reduce_axis((0, kernel_h), name=\"dy\")\ndx = te.reduce_axis((0, kernel_w), name=\"dx\")\nic = te.reduce_axis((0, in_channels // env.BLOCK_IN), name=\"ic\")\nic_tns = te.reduce_axis((0, env.BLOCK_IN), name=\"ic_tns\")\n\n# Input placeholder tensors\ndata = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\nkernel = te.placeholder(kernel_shape, name=\"kernel\", dtype=env.wgt_dtype)\n\n# Copy buffers:\n#   Apply spatial padding to input feature map\ndata_buf = topi.nn.pad(data, [0, 0, pad_h, pad_w, 0, 0], name=\"data_buf\")\nkernel_buf = te.compute(kernel_shape, lambda *i: kernel(*i), \"kernel_buf\")\n\n# Declare 2D convolution\nres_conv = te.compute(\n    output_shape,\n    lambda bo, co, i, j, bi, ci: te.sum(\n        data_buf[bo, ic, i * stride_h + dy, j * stride_w + dx, bi, ic_tns].astype(env.acc_dtype)\n        * kernel_buf[co, ic, dy, dx, ci, ic_tns].astype(env.acc_dtype),\n        axis=[ic, dy, dx, ic_tns],\n    ),\n    name=\"res_conv\",\n)\n\n# Add shift stage for fix-point normalization\nres_shr = te.compute(output_shape, lambda *i: res_conv(*i) >> 8, name=\"res_shr\")\n\n# Apply clipping between (0, input max value)\ninp_max = (1 << (env.INP_WIDTH - 1)) - 1\nres_max = te.compute(output_shape, lambda *i: tvm.te.max(res_shr(*i), 0), \"res_max\")\nres_min = te.compute(output_shape, lambda *i: tvm.te.min(res_max(*i), inp_max), \"res_min\")\n\n# Result Tensor\nres = te.compute(output_shape, lambda *i: res_min(*i).astype(env.inp_dtype), name=\"res\")\n\n\n######################################################################\n# Scheduling the Computation\n# --------------------------\n# We'll look at a set of schedule transformations necessary to map the\n# 2D convolution onto VTA in an efficient fashion.\n# Those include:\n#\n# - Computation blocking\n# - Virtual threading to increase compute utilization\n# - Lowering to VTA hardware intrinsics\n\n# Create TVM schedule\ns = te.create_schedule(res.op)\n# Let's look at the default TVM schedule\nprint(tvm.lower(s, [data, kernel, res], simple_mode=True))\n\n######################################################################\n# Blocking the Computation\n# ~~~~~~~~~~~~~~~~~~~~~~~~\n# The 2D convolution is by default too large for activations or kernel weights\n# to fit on VTA's on-chip buffers all at once.\n# We apply blocking along input channels, output channels, and along\n# the height spatial dimensions.\n# We don't apply blocking along the width spatial dimension since it's\n# the innermost dimension in the NCHW layout (and consequently to increase\n# locality, it's best not to block along the innermost dimension).\n\n# Let's define tiling sizes\nb_block = 1 // env.BATCH\noc_block = 128 // env.BLOCK_OUT\nic_block = 16 // env.BLOCK_IN\nh_block = 7\nw_block = 14\n\n# Tile the output tensor along the spatial and output channel dimensions\n# (since by default we are doing single batch inference, the split along\n#  the batch dimension has no effect)\nb, oc, y, x, b_tns, oc_tns = s[res].op.axis\nb_out, b_inn = s[res].split(b, factor=b_block)\noc_out, oc_inn = s[res].split(oc, factor=oc_block)\ny_out, y_inn = s[res].split(y, factor=h_block)\nx_out, x_inn = s[res].split(x, factor=w_block)\ns[res].reorder(b_out, oc_out, y_out, x_out, b_inn, oc_inn, y_inn, x_inn, b_tns, oc_tns)\n\n# Move intermediate computation into each output compute tile\ns[res_conv].compute_at(s[res], x_out)\ns[res_shr].compute_at(s[res], x_out)\ns[res_max].compute_at(s[res], x_out)\ns[res_min].compute_at(s[res], x_out)\n\n# Apply additional loop split along reduction axis (input channel)\nb_inn, oc_inn, y_inn, x_inn, b_tns, oc_tns = s[res_conv].op.axis\nic_out, ic_inn = s[res_conv].split(ic, factor=ic_block)\n\n# Reorder axes.\n# 1) Group the VTA tensor axes in the inner most position: b_tns, oc_tns, ic_tns\n#    to allow TVM to tensorize.\n# 2) We move the ic_out axis all the way out of the convolution loop to block\n#    along the reduction axis.\n# 3) Now we re-order the block axes: b_inn, oc_inn, y_inn, x_inn, ic_inn, dy, dx.\n#    VTA runtime/hardware requires us to write to a different output feature map\n#    location for every VTA tensor operation.\n#    This restriction requires us to order one of oc_inn, y_inn or x_inn right\n#    before b_tns, since they all affect output feature map indexing.\n#    Therefore, we choose to bring x_inn inside as shown below.\ns[res_conv].reorder(ic_out, b_inn, oc_inn, y_inn, ic_inn, dy, dx, x_inn, b_tns, oc_tns, ic_tns)\n\n######################################################################\n# Virtual Threading\n# ~~~~~~~~~~~~~~~~~\n# Virtual threading is a mechanism that increases task-level pipeline\n# parallelism in the VTA hardware design.\n# Put it another way, it increases compute resource utilization by hiding\n# memory access latency.\n#\n# In the implementation below, virtual threading distributes work across two\n# threads split along the output channel axis.\n# We show how work is split when computing the 2D convolution in the figure\n# below.\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/virtual_threading.png\n#      :align: center\n#      :width: 480px\n\n# VTA only supports 2 virtual threads\nv_threads = 2\n\n# Perform virtual thread split along output channel outer axis\n_, tx = s[res].split(oc_out, factor=v_threads)\ns[res].reorder(tx, b_out)\ns[res].bind(tx, te.thread_axis(\"cthread\"))\n\n# Let's look at the current TVM schedule after blocking and virtual threading\nprint(tvm.lower(s, [data, kernel, res], simple_mode=True))\n\n######################################################################\n# Lowering Copies to DMA Transfers\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Next we set the buffer scopes to the corresponding on-chip VTA SRAM buffers.\n# We move the load loops into the 2D convolution computation loop to stage\n# memory loads such that they fit in the on-chip SRAM buffers.\n# Finally we annotate the load/store loop outer axes with the DMA copy pragma\n# to perform bulk memory transfers on VTA.\n\n# Set scope of SRAM buffers\ns[data_buf].set_scope(env.inp_scope)\ns[kernel_buf].set_scope(env.wgt_scope)\ns[res_conv].set_scope(env.acc_scope)\ns[res_shr].set_scope(env.acc_scope)\ns[res_min].set_scope(env.acc_scope)\ns[res_max].set_scope(env.acc_scope)\n\n# Block data and kernel cache reads\ns[data_buf].compute_at(s[res_conv], ic_out)\ns[kernel_buf].compute_at(s[res_conv], ic_out)\n\n# Use DMA copy pragma on DRAM->SRAM operations\ns[data_buf].pragma(s[data_buf].op.axis[0], env.dma_copy)\ns[kernel_buf].pragma(s[kernel_buf].op.axis[0], env.dma_copy)\n\n# Use DMA copy pragma on SRAM->DRAM operation in each result block\n# (this implies that these copies should be performed along b_inn,\n# or result axis 4)\ns[res].pragma(s[res].op.axis[4], env.dma_copy)\n\n######################################################################\n# Lowering Computation to VTA Compute Intrinsics\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# The last phase is to lower the computation loops down to VTA hardware\n# intrinsics by mapping the 2D convolution to tensor intrinsics,\n# and mapping the shift, and clipping computation to the vector ALU.\n\n# Apply tensorization over the batch tensor tile axis\ns[res_conv].tensorize(b_tns, env.gemm)\n\n# Add an ALU pragma over the shift and clipping operations\ns[res_shr].pragma(s[res_shr].op.axis[0], env.alu)\ns[res_min].pragma(s[res_min].op.axis[0], env.alu)\ns[res_max].pragma(s[res_max].op.axis[0], env.alu)\n\n# Let's look at the final lowered TVM schedule after lowering memory\n# loads/stores down to DMA copy intrinsics, and the computation down to\n# VTA compute intrinsics.\nprint(vta.lower(s, [data, kernel, res], simple_mode=True))\n\n######################################################################\n# TVM Compilation and Verification\n# --------------------------------\n# After specifying the schedule, we can compile it into a TVM function.\n# We save the module so we can send it over RPC.\n# We run the function and verify it against a numpy implementation to\n# ensure correctness.\n\n# This library facilitates 2D convolution testing\nfrom tvm.topi.testing import conv2d_nchw_python\n\n# Compile the TVM module\nwith vta.build_config(disabled_pass={\"tir.CommonSubexprElimTIR\"}):\n    my_conv = vta.build(\n        s, [data, kernel, res], tvm.target.Target(\"ext_dev\", host=env.target_host), name=\"my_conv\"\n    )\ntemp = utils.tempdir()\nmy_conv.save(temp.relpath(\"conv2d.o\"))\nremote.upload(temp.relpath(\"conv2d.o\"))\nf = remote.load_module(\"conv2d.o\")\n\n# Get the remote device context\nctx = remote.ext_dev(0)\n\n# Initialize the data and kernel arrays randomly in the int range\n# of (-128, 128] in NCHW layout\ndata_np = np.random.randint(-128, 128, size=(batch_size, in_channels, height, width)).astype(\n    data.dtype\n)\nkernel_np = np.random.randint(\n    -128, 128, size=(out_channels, in_channels, kernel_h, kernel_w)\n).astype(kernel.dtype)\n\n# Apply packing to the data and kernel arrays from a 2D NCHW\n# to a 4D NCHWnc packed layout\ndata_packed = data_np.reshape(\n    batch_size // env.BATCH, env.BATCH, in_channels // env.BLOCK_IN, env.BLOCK_IN, height, width\n).transpose((0, 2, 4, 5, 1, 3))\n\nkernel_packed = kernel_np.reshape(\n    out_channels // env.BLOCK_OUT,\n    env.BLOCK_OUT,\n    in_channels // env.BLOCK_IN,\n    env.BLOCK_IN,\n    kernel_h,\n    kernel_w,\n).transpose((0, 2, 4, 5, 1, 3))\n\n# Format the input/output arrays with tvm.nd.array to the DLPack standard\ndata_nd = tvm.nd.array(data_packed, ctx)\nkernel_nd = tvm.nd.array(kernel_packed, ctx)\nres_nd = tvm.nd.array(np.zeros(output_shape).astype(res.dtype), ctx)\n\n# Clear stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n\n# Invoke the module to perform the computation\nf(data_nd, kernel_nd, res_nd)\n\n# Verify against numpy implementation\nres_ref = conv2d_nchw_python(\n    data_np.astype(env.acc_dtype),\n    kernel_np.astype(env.acc_dtype),\n    (stride_h, stride_w),\n    (pad_h, pad_w),\n).astype(env.acc_dtype)\nres_ref = res_ref >> env.INP_WIDTH\nres_ref = np.clip(res_ref, 0, inp_max)\nres_ref = res_ref.astype(res.dtype)\nres_ref = res_ref.reshape(\n    (\n        batch_size // env.BATCH,\n        env.BATCH,\n        out_channels // env.BLOCK_OUT,\n        env.BLOCK_OUT,\n        fout_height,\n        fout_width,\n    )\n).transpose((0, 2, 4, 5, 1, 3))\ntvm.testing.assert_allclose(res_ref, res_nd.numpy())\n\n# Print stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    sim_stats = simulator.stats()\n    print(\"Execution statistics:\")\n    for k, v in sim_stats.items():\n        print(\"\\t{:<16}: {:>16}\".format(k, v))\n\nprint(\"Successful 2D convolution test!\")\n\n######################################################################\n# Summary\n# -------\n# This tutorial demonstrates how TVM scheduling primitives can be used to\n# lower 2D convolution onto hardware accelerator intrinsics, making\n# use of hardware specific optimizations, such as latency hiding with\n# virtual threading.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/optimize/matrix_multiply_opt.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _vta-mat-mult-opt:\n\nMatrix Multiply Blocking\n========================\n**Author**: `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nThis tutorial provides an overview on how to use TVM to map matrix\nmultiplication efficiently on the VTA design.\nWe recommend covering the :ref:`basic-mat-mult` tutorial first.\n\nIn this tutorial, we will demonstrate TVM schedule optimizations to break large\nneural network operators down onto smaller blocks to achieve computation within\nlimited hardware accelerator resources.\n\"\"\"\n\n######################################################################\n# RPC Setup\n# ---------\n# We start by programming the Pynq's FPGA and building its RPC runtime.\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport tvm\nfrom tvm import te\nimport vta\nimport numpy as np\nfrom tvm import rpc\nfrom tvm.contrib import utils\nfrom vta.testing import simulator\n\n# Load VTA parameters from the 3rdparty/vta-hw/config/vta_config.json file\nenv = vta.get_env()\n\n# We read the Pynq RPC host IP address and port number from the OS environment\nhost = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n# We configure both the bitstream and the runtime system on the Pynq\n# to match the VTA configuration specified by the vta_config.json file.\nif env.TARGET == \"pynq\":\n\n    # Make sure that TVM was compiled with RPC=1\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n\n    # Reconfigure the JIT runtime\n    vta.reconfig_runtime(remote)\n\n    # Program the FPGA with a pre-compiled VTA bitstream.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    vta.program_fpga(remote, bitstream=None)\n\n# In simulation mode, host the RPC server locally.\nelif env.TARGET in [\"sim\", \"tsim\"]:\n    remote = rpc.LocalSession()\n\n######################################################################\n# Computation Declaration\n# -----------------------\n# As a first step, we need to describe our matrix multiplication computation.\n# We define the matrix multiplication as the computation one would find in a\n# fully connected layer, defined by its batch size, input channels, and output\n# channels.\n# These have to be integer multiples of the VTA tensor shape:\n# :code:`BATCH`, :code:`BLOCK_IN`, and :code:`BLOCK_OUT` respectively.\n#\n# We've added extra operators to the matrix multiplication that apply\n# shifting and clipping to the output in order to mimic a fixed-point\n# matrix multiplication followed by a rectified linear activation.\n# We describe the TVM dataflow graph of the fully connected layer below:\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/fc_dataflow.png\n#      :align: center\n#\n# This computation is intentionally too large to fit onto VTA's on-chip\n# buffers all at once. Therefore in the scheduling phase we'll\n# rely on computation blocking strategies to break the computation down into\n# manageable chunks.\n\n# Fully connected layer dimensions: 1024 x 1024\nbatch_size = 1\nin_channels = 1024\nout_channels = 1024\nassert batch_size % env.BATCH == 0\nassert in_channels % env.BLOCK_IN == 0\nassert out_channels % env.BLOCK_OUT == 0\n\n# Let's derive the tiled input tensor shapes\ndata_shape = (batch_size // env.BATCH, in_channels // env.BLOCK_IN, env.BATCH, env.BLOCK_IN)\nweight_shape = (\n    out_channels // env.BLOCK_OUT,\n    in_channels // env.BLOCK_IN,\n    env.BLOCK_OUT,\n    env.BLOCK_IN,\n)\noutput_shape = (batch_size // env.BATCH, out_channels // env.BLOCK_OUT, env.BATCH, env.BLOCK_OUT)\nnum_ops = in_channels * out_channels * batch_size * 2\n\n# Reduction axes\nic = te.reduce_axis((0, in_channels // env.BLOCK_IN), name=\"ic\")\nic_tns = te.reduce_axis((0, env.BLOCK_IN), name=\"ic_tns\")\n\n# Input placeholder tensors\ndata = te.placeholder(data_shape, name=\"data\", dtype=env.inp_dtype)\nweight = te.placeholder(weight_shape, name=\"weight\", dtype=env.wgt_dtype)\n\n# Copy buffers\ndata_buf = te.compute(data_shape, lambda *i: data(*i), \"data_buf\")\nweight_buf = te.compute(weight_shape, lambda *i: weight(*i), \"weight_buf\")\n\n# Declare matrix multiply computation\nres_gemm = te.compute(\n    output_shape,\n    lambda bo, co, bi, ci: te.sum(\n        data_buf[bo, ic, bi, ic_tns].astype(env.acc_dtype)\n        * weight_buf[co, ic, ci, ic_tns].astype(env.acc_dtype),\n        axis=[ic, ic_tns],\n    ),\n    name=\"res_gem\",\n)\n\n# Add shift stage for fix-point normalization\nres_shr = te.compute(output_shape, lambda *i: res_gemm(*i) >> env.INP_WIDTH, name=\"res_shr\")\n\n# Apply clipping between (0, input max value)\ninp_max = (1 << (env.INP_WIDTH - 1)) - 1\nres_max = te.compute(output_shape, lambda *i: tvm.te.max(res_shr(*i), 0), \"res_max\")\nres_min = te.compute(output_shape, lambda *i: tvm.te.min(res_max(*i), inp_max), \"res_min\")\n\n# Apply typecast to input data type before sending results back\nres = te.compute(output_shape, lambda *i: res_min(*i).astype(env.inp_dtype), name=\"res\")\n\n######################################################################\n# Scheduling the Computation\n# --------------------------\n# We'll look at a set of schedule transformations necessary to map the\n# matrix multiplications onto VTA in an efficient fashion.\n# Those include:\n#\n# - Computation blocking\n# - Lowering to VTA hardware intrinsics\n\n\n# Create TVM schedule\ns = te.create_schedule(res.op)\n# Let's look at the default TVM schedule\nprint(tvm.lower(s, [data, weight, res], simple_mode=True))\n\n######################################################################\n# Blocking the Computation\n# ~~~~~~~~~~~~~~~~~~~~~~~~\n# The matrix multiplication is by default too large for activations or weights\n# to fit on VTA's on-chip buffers all at once.\n# We block the (1, 1024) by (1024, 1024) matrix multiplication into\n# smaller (1, 256) by (256, 256) matrix multiplications so the intermediate\n# tensors can fit on the accelerator's on-chip SRAM.\n# This approach is similar to blocking techniques applied to CPUs and GPUs in\n# order to increase cache hit rate.\n#\n# We perform blocking along each axes (the batch axis being untouched since\n# we are performing singe-batch inference).\n# We also leave the inner-most tensorization axes as-is in order to allow\n# TVM to pattern-match tensorization.\n# We show the outcome of blocking on the computation schedule in the diagram\n# below:\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/blocking.png\n#      :align: center\n#      :width: 480px\n#\n# .. note::\n#\n#   The code after loop splitting and reordering is equivalent to the following\n#   pseudo-code. We ignore the batch axis since we are only performing single-batch\n#   inference in this example:\n#\n#   .. code-block:: c\n#\n#      for (int oc_out = 0; oc_out < 4; ++oc_out) {\n#        // Initialization loop\n#        for (int oc_inn = 0; oc_inn < 16; ++oc_inn) {\n#         for (int oc_tns = 0; oc_tns < 16; ++oc_tns) {\n#          int j = (oc_out * 16 + oc_inn) * 16 + oc_tns;\n#          C[0][j] = 0;\n#         }\n#        }\n#        for (int ic_out = 0; ic_out < 4; ++ic_out) {\n#         // Block loop\n#         for (int oc_inn = 0; oc_inn < 16; ++oc_inn) {\n#          for (int ic_inn = 0; ic_inn < 16; ++ic_inn) {\n#           // Tensorization loop\n#           for (int oc_tns = 0; oc_tns < 16; ++oc_tns) {\n#            for (int ic_tns = 0; ic_tns < 16; ++ic_tns) {\n#             int i = (ic_out * 16 + ic_inn) * 16 + ic_tns;\n#             int j = (oc_out * 16 + oc_inn) * 16 + oc_tns;\n#             C[0][i] = C[0][i] + A[0][i] * B[j][i];\n#            }\n#           }\n#          }\n#         }\n#        }\n#       }\n#      }\n\n# Let's define tiling sizes (expressed in multiples of VTA tensor shape size)\nb_block = 1 // env.BATCH\ni_block = 256 // env.BLOCK_IN\no_block = 256 // env.BLOCK_OUT\n\n# Tile the output tensor along the batch and output channel dimensions\n# (since by default we are doing single batch inference, the split along\n#  the batch dimension has no effect)\nb, oc, b_tns, oc_tns = s[res].op.axis\nb_out, b_inn = s[res].split(b, b_block)\noc_out, oc_inn = s[res].split(oc, o_block)\ns[res].reorder(b_out, oc_out, b_inn, oc_inn)\n\n# Move intermediate computation into each output compute tile\ns[res_gemm].compute_at(s[res], oc_out)\ns[res_shr].compute_at(s[res], oc_out)\ns[res_max].compute_at(s[res], oc_out)\ns[res_min].compute_at(s[res], oc_out)\n\n# Apply additional loop split along reduction axis (input channel)\nb_inn, oc_inn, b_tns, oc_tns = s[res_gemm].op.axis\nic_out, ic_inn = s[res_gemm].split(ic, i_block)\n\n# Reorder axes. We move the ic_out axis all the way out of the GEMM\n# loop to block along the reduction axis\ns[res_gemm].reorder(ic_out, b_inn, oc_inn, ic_inn, b_tns, oc_tns, ic_tns)\n\n# Let's look at the current TVM schedule after blocking\nprint(tvm.lower(s, [data, weight, res], simple_mode=True))\n\n######################################################################\n# Lowering Copies to DMA Transfers\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Next we set the buffer scopes to the corresponding on-chip VTA SRAM buffers.\n# We move the load loops into the matrix multiply computation loop to stage\n# memory loads such that they fit in the on-chip SRAM buffers.\n# Finally we annotate the load/store loop outer axes with the DMA copy pragma\n# to perform bulk memory transfers on VTA.\n\n# Set scope of SRAM buffers\ns[data_buf].set_scope(env.inp_scope)\ns[weight_buf].set_scope(env.wgt_scope)\ns[res_gemm].set_scope(env.acc_scope)\ns[res_shr].set_scope(env.acc_scope)\ns[res_min].set_scope(env.acc_scope)\ns[res_max].set_scope(env.acc_scope)\n\n# Block data and weight cache reads\ns[data_buf].compute_at(s[res_gemm], ic_out)\ns[weight_buf].compute_at(s[res_gemm], ic_out)\n\n# Use DMA copy pragma on DRAM->SRAM operations\ns[data_buf].pragma(s[data_buf].op.axis[0], env.dma_copy)\ns[weight_buf].pragma(s[weight_buf].op.axis[0], env.dma_copy)\n\n# Use DMA copy pragma on SRAM->DRAM operation\n# (this implies that these copies should be performed along b_inn,\n# or result axis 2)\ns[res].pragma(s[res].op.axis[2], env.dma_copy)\n\n######################################################################\n# Lowering Computation to VTA Compute Intrinsics\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# The last phase is to lower the computation loops down to VTA hardware\n# intrinsics by mapping the matrix multiplication to tensor intrinsics,\n# and mapping the shift, and clipping computation to the vector ALU.\n\n# Apply tensorization over the batch tensor tile axis\ns[res_gemm].tensorize(b_tns, env.gemm)\n\n# Add an ALU pragma over the shift and clipping operations\ns[res_shr].pragma(s[res_shr].op.axis[0], env.alu)\ns[res_min].pragma(s[res_min].op.axis[0], env.alu)\ns[res_max].pragma(s[res_max].op.axis[0], env.alu)\n\n# Let's look at the final lowered TVM schedule after lowering memory\n# loads/stores down to DMA copy intrinsics, and the computation down to\n# VTA compute intrinsics.\nprint(vta.lower(s, [data, weight, res], simple_mode=True))\n\n######################################################################\n# TVM Compilation and Verification\n# --------------------------------\n# After specifying the schedule, we can compile it into a TVM function.\n# We save the module so we can send it over RPC.\n# We run the function and verify it against a numpy implementation to\n# ensure correctness.\n\n# Compile the TVM module\nmy_gemm = vta.build(\n    s, [data, weight, res], tvm.target.Target(\"ext_dev\", host=env.target_host), name=\"my_gemm\"\n)\ntemp = utils.tempdir()\nmy_gemm.save(temp.relpath(\"gemm.o\"))\nremote.upload(temp.relpath(\"gemm.o\"))\nf = remote.load_module(\"gemm.o\")\n\n# Get the remote device context\nctx = remote.ext_dev(0)\n\n# Initialize the data and weight arrays randomly in the int range of (-128, 128]\ndata_np = np.random.randint(-128, 128, size=(batch_size, in_channels)).astype(data.dtype)\nweight_np = np.random.randint(-128, 128, size=(out_channels, in_channels)).astype(weight.dtype)\n\n# Apply packing to the data and weight arrays from a 2D to a 4D packed layout\ndata_packed = data_np.reshape(\n    batch_size // env.BATCH, env.BATCH, in_channels // env.BLOCK_IN, env.BLOCK_IN\n).transpose((0, 2, 1, 3))\nweight_packed = weight_np.reshape(\n    out_channels // env.BLOCK_OUT, env.BLOCK_OUT, in_channels // env.BLOCK_IN, env.BLOCK_IN\n).transpose((0, 2, 1, 3))\n\n# Format the input/output arrays with tvm.nd.array to the DLPack standard\ndata_nd = tvm.nd.array(data_packed, ctx)\nweight_nd = tvm.nd.array(weight_packed, ctx)\nres_nd = tvm.nd.array(np.zeros(output_shape).astype(res.dtype), ctx)\n\n# Clear stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    simulator.clear_stats()\n\n# Invoke the module to perform the computation\nf(data_nd, weight_nd, res_nd)\n\n# Verify against numpy implementation\nres_ref = np.dot(data_np.astype(env.acc_dtype), weight_np.T.astype(env.acc_dtype))\nres_ref = res_ref >> env.INP_WIDTH\nres_ref = np.clip(res_ref, 0, inp_max)\nres_ref = res_ref.astype(res.dtype)\nres_ref = res_ref.reshape(\n    batch_size // env.BATCH, env.BATCH, out_channels // env.BLOCK_OUT, env.BLOCK_OUT\n).transpose((0, 2, 1, 3))\nnp.testing.assert_equal(res_ref, res_nd.numpy())\n\n# Print stats\nif env.TARGET in [\"sim\", \"tsim\"]:\n    sim_stats = simulator.stats()\n    print(\"Execution statistics:\")\n    for k, v in sim_stats.items():\n        print(\"\\t{:<16}: {:>16}\".format(k, v))\n\nprint(\"Successful blocked matrix multiply test!\")\n\n######################################################################\n# Summary\n# -------\n# This tutorial demonstrates how TVM scheduling primitives can achieve\n# computation blocking for a matrix multiplication example.\n# This allows us to map arbitrarily large computation onto limited\n# hardware accelerator resources.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "vta/tutorials/vta_get_started.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\n.. _vta-get-started:\n\nGet Started with VTA\n====================\n**Author**: `Thierry Moreau <https://homes.cs.washington.edu/~moreau/>`_\n\nThis is an introduction tutorial on how to use TVM to program the VTA design.\n\nIn this tutorial, we will demonstrate the basic TVM workflow to implement\na vector addition on the VTA design's vector ALU.\nThis process includes specific scheduling transformations necessary to lower\ncomputation down to low-level accelerator operations.\n\nTo begin, we need to import TVM which is our deep learning optimizing compiler.\nWe also need to import the VTA python package which contains VTA specific\nextensions for TVM to target the VTA design.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport tvm\nfrom tvm import te\nimport vta\nimport numpy as np\n\n######################################################################\n# Loading in VTA Parameters\n# ~~~~~~~~~~~~~~~~~~~~~~~~~\n# VTA is a modular and customizable design. Consequently, the user\n# is free to modify high-level hardware parameters that affect\n# the hardware design layout.\n# These parameters are specified in the :code:`vta_config.json` file by their\n# :code:`log2` values.\n# These VTA parameters can be loaded with the :code:`vta.get_env`\n# function.\n#\n# Finally, the TVM target is also specified in the :code:`vta_config.json` file.\n# When set to *sim*, execution will take place inside of a behavioral\n# VTA simulator.\n# If you want to run this tutorial on the Pynq FPGA development platform,\n# follow the *VTA Pynq-Based Testing Setup* guide.\n\nenv = vta.get_env()\n\n######################################################################\n# FPGA Programming\n# ----------------\n# When targeting the Pynq FPGA development board, we need to configure\n# the board with a VTA bitstream.\n\n# We'll need the TVM RPC module and the VTA simulator module\nfrom tvm import rpc\nfrom tvm.contrib import utils\nfrom vta.testing import simulator\n\n# We read the Pynq RPC host IP address and port number from the OS environment\nhost = os.environ.get(\"VTA_RPC_HOST\", \"192.168.2.99\")\nport = int(os.environ.get(\"VTA_RPC_PORT\", \"9091\"))\n\n# We configure both the bitstream and the runtime system on the Pynq\n# to match the VTA configuration specified by the vta_config.json file.\nif env.TARGET == \"pynq\" or env.TARGET == \"de10nano\":\n\n    # Make sure that TVM was compiled with RPC=1\n    assert tvm.runtime.enabled(\"rpc\")\n    remote = rpc.connect(host, port)\n\n    # Reconfigure the JIT runtime\n    vta.reconfig_runtime(remote)\n\n    # Program the FPGA with a pre-compiled VTA bitstream.\n    # You can program the FPGA with your own custom bitstream\n    # by passing the path to the bitstream file instead of None.\n    vta.program_fpga(remote, bitstream=None)\n\n# In simulation mode, host the RPC server locally.\nelif env.TARGET in (\"sim\", \"tsim\", \"intelfocl\"):\n    remote = rpc.LocalSession()\n\n    if env.TARGET in [\"intelfocl\"]:\n        # program intelfocl aocx\n        vta.program_fpga(remote, bitstream=\"vta.bitstream\")\n\n######################################################################\n# Computation Declaration\n# -----------------------\n# As a first step, we need to describe our computation.\n# TVM adopts tensor semantics, with each intermediate result\n# represented as multi-dimensional array. The user needs to describe\n# the computation rule that generates the output tensors.\n#\n# In this example we describe a vector addition, which requires multiple\n# computation stages, as shown in the dataflow diagram below.\n# First we describe the input tensors :code:`A` and :code:`B` that are living\n# in main memory.\n# Second, we need to declare intermediate tensors :code:`A_buf` and\n# :code:`B_buf`, which will live in VTA's on-chip buffers.\n# Having this extra computational stage allows us to explicitly\n# stage cached reads and writes.\n# Third, we describe the vector addition computation which will\n# add :code:`A_buf` to :code:`B_buf` to produce :code:`C_buf`.\n# The last operation is a cast and copy back to DRAM, into results tensor\n# :code:`C`.\n#\n# .. image:: https://raw.githubusercontent.com/uwsampl/web-data/main/vta/tutorial/vadd_dataflow.png\n#      :align: center\n\n######################################################################\n# Input Placeholders\n# ~~~~~~~~~~~~~~~~~~\n# We describe the placeholder tensors :code:`A`, and :code:`B` in a tiled data\n# format to match the data layout requirements imposed by the VTA vector ALU.\n#\n# For VTA's general purpose operations such as vector adds, the tile size is\n# :code:`(env.BATCH, env.BLOCK_OUT)`.\n# The dimensions are specified in\n# the :code:`vta_config.json` configuration file and are set by default to\n# a (1, 16) vector.\n#\n# In addition, A and B's data types also needs to match the :code:`env.acc_dtype`\n# which is set by the :code:`vta_config.json` file to be a 32-bit integer.\n\n# Output channel factor m - total 64 x 16 = 1024 output channels\nm = 64\n# Batch factor o - total 1 x 1 = 1\no = 1\n# A placeholder tensor in tiled data format\nA = te.placeholder((o, m, env.BATCH, env.BLOCK_OUT), name=\"A\", dtype=env.acc_dtype)\n# B placeholder tensor in tiled data format\nB = te.placeholder((o, m, env.BATCH, env.BLOCK_OUT), name=\"B\", dtype=env.acc_dtype)\n\n######################################################################\n# Copy Buffers\n# ~~~~~~~~~~~~\n# One specificity of hardware accelerators, is that on-chip memory has to be\n# explicitly managed.\n# This means that we'll need to describe intermediate tensors :code:`A_buf`\n# and :code:`B_buf` that can have a different memory scope than the original\n# placeholder tensors :code:`A` and :code:`B`.\n#\n# Later in the scheduling phase, we can tell the compiler that :code:`A_buf`\n# and :code:`B_buf` will live in the VTA's on-chip buffers (SRAM), while\n# :code:`A` and :code:`B` will live in main memory (DRAM).\n# We describe A_buf and B_buf as the result of a compute\n# operation that is the identity function.\n# This can later be interpreted by the compiler as a cached read operation.\n\n# A copy buffer\nA_buf = te.compute((o, m, env.BATCH, env.BLOCK_OUT), lambda *i: A(*i), \"A_buf\")\n# B copy buffer\nB_buf = te.compute((o, m, env.BATCH, env.BLOCK_OUT), lambda *i: B(*i), \"B_buf\")\n\n######################################################################\n# Vector Addition\n# ~~~~~~~~~~~~~~~\n# Now we're ready to describe the vector addition result tensor :code:`C`,\n# with another compute operation.\n# The compute function takes the shape of the tensor, as well as a lambda\n# function that describes the computation rule for each position of the tensor.\n#\n# No computation happens during this phase, as we are only declaring how\n# the computation should be done.\n\n# Describe the in-VTA vector addition\nC_buf = te.compute(\n    (o, m, env.BATCH, env.BLOCK_OUT),\n    lambda *i: A_buf(*i).astype(env.acc_dtype) + B_buf(*i).astype(env.acc_dtype),\n    name=\"C_buf\",\n)\n\n######################################################################\n# Casting the Results\n# ~~~~~~~~~~~~~~~~~~~\n# After the computation is done, we'll need to send the results computed by VTA\n# back to main memory.\n\n######################################################################\n# .. note::\n#\n#   **Memory Store Restrictions**\n#\n#   One specificity of VTA is that it only supports DRAM stores in the narrow\n#   :code:`env.inp_dtype` data type format.\n#   This lets us reduce the data footprint for memory transfers (more on this\n#   in the basic matrix multiply example).\n#\n# We perform one last typecast operation to the narrow\n# input activation data format.\n\n# Cast to output type, and send to main memory\nC = te.compute(\n    (o, m, env.BATCH, env.BLOCK_OUT), lambda *i: C_buf(*i).astype(env.inp_dtype), name=\"C\"\n)\n\n######################################################################\n# This concludes the computation declaration part of this tutorial.\n\n\n######################################################################\n# Scheduling the Computation\n# --------------------------\n# While the above lines describes the computation rule, we can obtain\n# :code:`C` in many ways.\n# TVM asks the user to provide an implementation of the computation called\n# *schedule*.\n#\n# A schedule is a set of transformations to an original computation that\n# transforms the implementation of the computation without affecting\n# correctness.\n# This simple VTA programming tutorial aims to demonstrate basic schedule\n# transformations that will map the original schedule down to VTA hardware\n# primitives.\n\n\n######################################################################\n# Default Schedule\n# ~~~~~~~~~~~~~~~~\n# After we construct the schedule, by default the schedule computes\n# :code:`C` in the following way:\n\n# Let's take a look at the generated schedule\ns = te.create_schedule(C.op)\n\nprint(tvm.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# Although this schedule makes sense, it won't compile to VTA.\n# In order to obtain correct code generation, we need to apply scheduling\n# primitives and code annotation that will transform the schedule into\n# one that can be directly lowered onto VTA hardware intrinsics.\n# Those include:\n#\n#  - DMA copy operations which will take globally-scoped tensors and copy\n#    those into locally-scoped tensors.\n#  - Vector ALU operations that will perform the vector add.\n\n######################################################################\n# Buffer Scopes\n# ~~~~~~~~~~~~~\n# First, we set the scope of the copy buffers to indicate to TVM that these\n# intermediate tensors will be stored in the VTA's on-chip SRAM buffers.\n# Below, we tell TVM that :code:`A_buf`, :code:`B_buf`, :code:`C_buf`\n# will live in VTA's on-chip *accumulator buffer* which serves as\n# VTA's general purpose register file.\n#\n# Set the intermediate tensors' scope to VTA's on-chip accumulator buffer\ns[A_buf].set_scope(env.acc_scope)\ns[B_buf].set_scope(env.acc_scope)\ns[C_buf].set_scope(env.acc_scope)\n\n######################################################################\n# DMA Transfers\n# ~~~~~~~~~~~~~\n# We need to schedule DMA transfers to move data living in DRAM to\n# and from the VTA on-chip buffers.\n# We insert :code:`dma_copy` pragmas to indicate to the compiler\n# that the copy operations will be performed in bulk via DMA,\n# which is common in hardware accelerators.\n\n# Tag the buffer copies with the DMA pragma to map a copy loop to a\n# DMA transfer operation\ns[A_buf].pragma(s[A_buf].op.axis[0], env.dma_copy)\ns[B_buf].pragma(s[B_buf].op.axis[0], env.dma_copy)\ns[C].pragma(s[C].op.axis[0], env.dma_copy)\n\n######################################################################\n# ALU Operations\n# ~~~~~~~~~~~~~~\n# VTA has a vector ALU that can perform vector operations on tensors\n# in the accumulator buffer.\n# In order to tell TVM that a given operation needs to be mapped to the\n# VTA's vector ALU, we need to explicitly tag the vector addition loop\n# with an :code:`env.alu` pragma.\n\n# Tell TVM that the computation needs to be performed\n# on VTA's vector ALU\ns[C_buf].pragma(C_buf.op.axis[0], env.alu)\n\n# Let's take a look at the finalized schedule\nprint(vta.lower(s, [A, B, C], simple_mode=True))\n\n######################################################################\n# This concludes the scheduling portion of this tutorial.\n\n######################################################################\n# TVM Compilation\n# ---------------\n# After we have finished specifying the schedule, we can compile it\n# into a TVM function. By default TVM compiles into a type-erased\n# function that can be directly called from python side.\n#\n# In the following line, we use :code:`tvm.build` to create a function.\n# The build function takes the schedule, the desired signature of the\n# function(including the inputs and outputs) as well as target language\n# we want to compile to.\n#\nmy_vadd = vta.build(\n    s, [A, B, C], tvm.target.Target(\"ext_dev\", host=env.target_host), name=\"my_vadd\"\n)\n\n######################################################################\n# Saving the Module\n# ~~~~~~~~~~~~~~~~~\n# TVM lets us save our module into a file so it can loaded back later. This\n# is called ahead-of-time compilation and allows us to save some compilation\n# time.\n# More importantly, this allows us to cross-compile the executable on our\n# development machine and send it over to the Pynq FPGA board over RPC for\n# execution.\n\n# Write the compiled module into an object file.\ntemp = utils.tempdir()\nmy_vadd.save(temp.relpath(\"vadd.o\"))\n\n# Send the executable over RPC\nremote.upload(temp.relpath(\"vadd.o\"))\n\n######################################################################\n# Loading the Module\n# ~~~~~~~~~~~~~~~~~~\n# We can load the compiled module from the file system to run the code.\n\nf = remote.load_module(\"vadd.o\")\n\n######################################################################\n# Running the Function\n# --------------------\n# The compiled TVM function uses a concise C API and can be invoked from\n# any language.\n#\n# TVM provides an array API in python to aid quick testing and prototyping.\n# The array API is based on `DLPack <https://github.com/dmlc/dlpack>`_ standard.\n#\n# - We first create a remote context (for remote execution on the Pynq).\n# - Then :code:`tvm.nd.array` formats the data accordingly.\n# - :code:`f()` runs the actual computation.\n# - :code:`numpy()` copies the result array back in a format that can be\n#   interpreted.\n#\n\n# Get the remote device context\nctx = remote.ext_dev(0)\n\n# Initialize the A and B arrays randomly in the int range of (-128, 128]\nA_orig = np.random.randint(-128, 128, size=(o * env.BATCH, m * env.BLOCK_OUT)).astype(A.dtype)\nB_orig = np.random.randint(-128, 128, size=(o * env.BATCH, m * env.BLOCK_OUT)).astype(B.dtype)\n\n# Apply packing to the A and B arrays from a 2D to a 4D packed layout\nA_packed = A_orig.reshape(o, env.BATCH, m, env.BLOCK_OUT).transpose((0, 2, 1, 3))\nB_packed = B_orig.reshape(o, env.BATCH, m, env.BLOCK_OUT).transpose((0, 2, 1, 3))\n\n# Format the input/output arrays with tvm.nd.array to the DLPack standard\nA_nd = tvm.nd.array(A_packed, ctx)\nB_nd = tvm.nd.array(B_packed, ctx)\nC_nd = tvm.nd.array(np.zeros((o, m, env.BATCH, env.BLOCK_OUT)).astype(C.dtype), ctx)\n\n# Invoke the module to perform the computation\nf(A_nd, B_nd, C_nd)\n\n######################################################################\n# Verifying Correctness\n# ---------------------\n# Compute the reference result with numpy and assert that the output of the\n# matrix multiplication indeed is correct\n\n# Compute reference result with numpy\nC_ref = (A_orig.astype(env.acc_dtype) + B_orig.astype(env.acc_dtype)).astype(C.dtype)\nC_ref = C_ref.reshape(o, env.BATCH, m, env.BLOCK_OUT).transpose((0, 2, 1, 3))\nnp.testing.assert_equal(C_ref, C_nd.numpy())\nprint(\"Successful vector add test!\")\n\n######################################################################\n# Summary\n# -------\n# This tutorial provides a walk-through of TVM for programming the\n# deep learning accelerator VTA with a simple vector addition example.\n# The general workflow includes:\n#\n# - Programming the FPGA with the VTA bitstream over RPC.\n# - Describing the vector add computation via a series of computations.\n# - Describing how we want to perform the computation using schedule primitives.\n# - Compiling the function to the VTA target.\n# - Running the compiled module and verifying it against a numpy implementation.\n#\n# You are more than welcome to check other examples out and tutorials\n# to learn more about the supported operations, schedule primitives\n# and other features supported by TVM to program VTA.\n#\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/apps/node/example.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/**\n * Example code to start the runtime.\n */\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst tvmjs = require(\"../../dist\");\n\nconst wasmPath = tvmjs.wasmPath();\nconst EmccWASI = require(path.join(wasmPath, \"tvmjs_runtime.wasi.js\"));\nconst wasmSource = fs.readFileSync(path.join(wasmPath, \"tvmjs_runtime.wasm\"));\n// Here we pass the javascript module generated by emscripten as the\n// LibraryProvider to provide WASI related libraries.\n// the async version of the API.\ntvmjs.instantiate(wasmSource, new EmccWASI())\n.then((tvm) => {\n    const log_info = tvm.getGlobalFunc(\"testing.log_info_str\");\n    log_info(\"hello world\");\n    // List all the global functions from the runtime.\n    console.log(\"Runtime functions using EmccWASI\\n\", tvm.listGlobalFuncNames());\n});\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/apps/node/wasi_example.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/**\n * Example code to start the runtime.\n */\nconst { WASI } = require('wasi');\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst tvmjs = require(\"../../dist\");\n\nconst wasmPath = tvmjs.wasmPath();\nconst wasmSource = fs.readFileSync(path.join(wasmPath, \"tvmjs_runtime.wasm\"));\n\nconst wasi = new WASI({ args: process.argv, env: process.env });\n// Here we pass the javascript module generated by emscripten as the\n// LibraryProvider to provide WASI related libraries.\nconst tvm = new tvmjs.Instance(new WebAssembly.Module(wasmSource), wasi);\n\n// List all the global functions from the runtime.\nconsole.log(\"Runtime using WASI\\n\", tvm.listGlobalFuncNames());\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/apps/node/wasi_rpc_server.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/**\n * Example code to start the RPC server on nodejs using WASI\n */\nconst { WASI } = require(\"wasi\");\nconst tvmjs = require(\"../../dist\");\n\n// Get import returns a fresh library in each call.\nconst getImports = () => {\n  return new WASI({\n    args: process.argv,\n    env: process.env\n  });\n};\n\nconst proxyUrl = \"ws://localhost:8888/ws\";\n\nnew tvmjs.RPCServer(proxyUrl, \"wasm\", getImports, console.log);\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/emcc/decorate_as_wasi.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Decorate emcc generated js to a WASI compatible API.\"\"\"\n\nimport sys\n\ntemplate_head = \"\"\"\nfunction EmccWASI() {\n\"\"\"\n\ntemplate_tail = \"\"\"\n    this.Module = Module;\n    this.start = Module.wasmLibraryProvider.start;\n    this.imports = Module.wasmLibraryProvider.imports;\n    this.wasiImport = this.imports[\"wasi_snapshot_preview1\"];\n}\n\nif (typeof module !== \"undefined\" && module.exports) {\n  module.exports = EmccWASI;\n}\n\"\"\"\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 3:\n        print(\"Usage <file-in> <file-out>\")\n    result = template_head + open(sys.argv[1]).read() + template_tail\n    with open(sys.argv[2], \"w\") as fo:\n        fo.write(result)\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/emcc/preload.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/* eslint-disable no-unused-vars */\n/**\n * JS config used by --pre-js in emcc.\n * Wrap module as a LibraryProvider.\n */\n\nvar __wasmLib = {};\n\nfunction __wasmLibInstantiateWasm(imports, successCallback) {\n    __wasmLib.imports = imports;\n    __wasmLib.successCallback = successCallback;\n}\n\nfunction __wasmLibStart(wasmInstance) {\n    __wasmLib.successCallback(wasmInstance);\n}\n\n__wasmLib.start = __wasmLibStart;\n\nvar Module = {\n    \"instantiateWasm\": __wasmLibInstantiateWasm,\n    \"wasmLibraryProvider\": __wasmLib\n};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/jest.config.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n/* eslint-disable no-undef */\nmodule.exports = {\n  testEnvironment: \"node\",\n\n  testMatch: [\n     \"**/tests/node/*.js\"\n  ],\n};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/rollup.config.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport commonjs from '@rollup/plugin-commonjs';\nimport resolve from '@rollup/plugin-node-resolve';\n\nexport default {\n  input: 'dist/index.js',\n  output: {\n    file: 'dist/tvmjs.bundle.js',\n    format: 'umd',\n    name: 'tvmjs',\n    exports: 'named',\n    globals: {'ws': 'ws',\n              'perf_hooks': 'perf_hooks',\n              '@webgpu/types': 'webgputypes'}\n  },\n  plugins: [commonjs(), resolve()],\n  external: ['ws', 'perf_hooks', '@webgpu/types']\n};\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/node/test_module_load.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/* eslint-disable no-undef */\n// Load Emscripten Module, need to change path to root/lib\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst assert = require(\"assert\");\nconst tvmjs = require(\"../../dist\");\n\nconst wasmPath = tvmjs.wasmPath();\nconst EmccWASI = require(path.join(wasmPath, \"tvmjs_runtime.wasi.js\"));\nconst wasmSource = fs.readFileSync(path.join(wasmPath, \"test_addone.wasm\"));\n\nconst tvm = new tvmjs.Instance(\n  new WebAssembly.Module(wasmSource),\n  new EmccWASI()\n);\n\n// Load system library\nconst sysLib = tvm.systemLib();\n\nfunction randomArray(length, max) {\n  return Array.apply(null, Array(length)).map(function () {\n    return Math.random() * max;\n  });\n}\n\ntest(\"add one\", () => {\n  // grab pre-loaded function\n  const faddOne = sysLib.getFunction(\"add_one\");\n  assert(tvm.isPackedFunc(faddOne));\n  const n = 124;\n  const A = tvm.empty(n).copyFrom(randomArray(n, 1));\n  const B = tvm.empty(n);\n  // call the function.\n  faddOne(A, B);\n  const AA = A.toArray(); // retrieve values in js array\n  const BB = B.toArray(); // retrieve values in js array\n  // verify\n  for (var i = 0; i < BB.length; ++i) {\n    assert(Math.abs(BB[i] - (AA[i] + 1)) < 1e-5);\n  }\n  faddOne.dispose();\n});\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/node/test_ndarray.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/* eslint-disable no-undef */\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst assert = require(\"assert\");\nconst tvmjs = require(\"../../dist/tvmjs.bundle\")\n\nconst wasmPath = tvmjs.wasmPath();\nconst EmccWASI = require(path.join(wasmPath, \"tvmjs_runtime.wasi.js\"));\nconst wasmSource = fs.readFileSync(path.join(wasmPath, \"tvmjs_runtime.wasm\"));\n\nlet tvm = new tvmjs.Instance(new WebAssembly.Module(wasmSource), new EmccWASI());\n\n// Basic fields.\nassert(tvm.listGlobalFuncNames() !== undefined);\n\n// Test ndarray\nfunction testArrayCopy(dtype, arrayType) {\n  let data = [1, 2, 3, 4, 5, 6];\n  let a = tvm.empty([2, 3], dtype).copyFrom(data);\n\n  assert(a.device.toString() == \"cpu(0)\");\n  assert(a.shape[0] == 2 && a.shape[1] == 3);\n\n  let ret = a.toArray();\n  assert(ret instanceof arrayType);\n  assert(ret.toString() == arrayType.from(data).toString());\n  // test multiple dispose.\n  a.dispose();\n  a.dispose();\n}\n\ntest(\"array copy\", () => {\n  testArrayCopy(\"float32\", Float32Array);\n  testArrayCopy(\"int\", Int32Array);\n  testArrayCopy(\"int8\", Int8Array);\n  testArrayCopy(\"uint8\", Uint8Array);\n  testArrayCopy(\"float64\", Float64Array);\n});\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/node/test_packed_func.js",
        "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/* eslint-disable no-undef */\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst assert = require(\"assert\");\nconst tvmjs = require(\"../../dist\");\n\nconst wasmPath = tvmjs.wasmPath();\nconst EmccWASI = require(path.join(wasmPath, \"tvmjs_runtime.wasi.js\"));\nconst wasmSource = fs.readFileSync(path.join(wasmPath, \"tvmjs_runtime.wasm\"));\n\nlet tvm = new tvmjs.Instance(\n  new WebAssembly.Module(wasmSource),\n  new EmccWASI()\n);\n\ntest(\"GetGlobal\", () => {\n  let flist = tvm.listGlobalFuncNames();\n  let faddOne = tvm.getGlobalFunc(\"testing.add_one\");\n  let fecho = tvm.getGlobalFunc(\"testing.echo\");\n\n  assert(faddOne(tvm.scalar(1, \"int\")) == 2);\n  // check function argument with different types.\n  assert(fecho(1123) == 1123);\n  assert(fecho(\"xyz\") == \"xyz\");\n\n  let bytes = new Uint8Array([1, 2, 3]);\n  let rbytes = fecho(bytes);\n  assert(rbytes.length == bytes.length);\n\n  for (let i = 0; i < bytes.length; ++i) {\n    assert(rbytes[i] == bytes[i]);\n  }\n\n  assert(fecho(undefined) == undefined);\n\n  let arr = tvm.empty([2, 2]).copyFrom([1, 2, 3, 4]);\n  let arr2 = fecho(arr);\n  assert(arr.handle == arr2.handle);\n  assert(arr2.toArray().toString() == arr.toArray().toString());\n\n  let mod = tvm.systemLib();\n  let ret = fecho(mod);\n  assert(ret.handle == mod.handle);\n  assert(flist.length != 0);\n\n  mod.dispose();\n  ret.dispose();\n  arr.dispose();\n  arr2.dispose();\n  fecho.dispose();\n  faddOne.dispose();\n});\n\ntest(\"ReturnFunc\", () => {\n  function addy(y) {\n    function add(x, z) {\n      return x + y + z;\n    }\n    return add;\n  }\n\n  let fecho = tvm.getGlobalFunc(\"testing.echo\");\n  let myf = tvm.toPackedFunc(addy);\n  assert(tvm.isPackedFunc(myf));\n  let myf2 = tvm.toPackedFunc(myf);\n  assert(myf2._tvmPackedCell.handle === myf._tvmPackedCell.handle);\n  let f = myf(10);\n\n  assert(tvm.isPackedFunc(f));\n  assert(f(11, 0) == 21);\n  assert(f(\"x\", 1) == \"x101\");\n  assert(f(\"x\", \"yz\") == \"x10yz\");\n\n  fecho.dispose();\n  myf.dispose();\n  myf2.dispose();\n  // test multiple dispose.\n  f.dispose();\n  f.dispose();\n});\n\ntest(\"RegisterGlobal\", () => {\n  tvm.registerFunc(\"xyz\", function (x, y) {\n    return x + y;\n  });\n\n  let f = tvm.getGlobalFunc(\"xyz\");\n  assert(f(1, 2) == 3);\n  f.dispose();\n\n  let syslib = tvm.systemLib();\n  syslib.dispose();\n});\n\ntest(\"NDArrayCbArg\", () => {\n  let use_count = tvm.getGlobalFunc(\"testing.object_use_count\");\n\n  let fcheck = tvm.toPackedFunc(function (x) {\n    assert(use_count(x) == 2);\n    x.dispose();\n  });\n  let x = tvm.empty([2], \"float32\").copyFrom([1, 2]);\n  assert(use_count(x) == 1);\n  fcheck(x);\n  assert(use_count(x) == 1);\n});\n\ntest(\"Logging\", () => {\n  const log_info = tvm.getGlobalFunc(\"testing.log_info_str\");\n  log_info(\"helow world\")\n  log_info.dispose();\n});\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/python/prepare_test_libs.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# Prepare test library for standalone wasm runtime test.\n\nimport tvm\nfrom tvm import te\nfrom tvm.contrib import emcc\nfrom tvm.relay.backend import Runtime\nimport os\n\n\ndef prepare_test_libs(base_path):\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    target = \"llvm -mtriple=wasm32-unknown-unknown-wasm\"\n    if not tvm.runtime.enabled(target):\n        raise RuntimeError(\"Target %s is not enbaled\" % target)\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n    fadd = tvm.build(s, [A, B], target, runtime=runtime, name=\"add_one\")\n\n    wasm_path = os.path.join(base_path, \"test_addone.wasm\")\n    fadd.export_library(wasm_path, emcc.create_tvmjs_wasm)\n\n\nif __name__ == \"__main__\":\n    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n    prepare_test_libs(os.path.join(curr_path, \"../../dist/wasm\"))\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/python/webgpu_rpc_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Simple testcode to test Javascript RPC\n\nTo use it, start a rpc proxy with \"python -m tvm.exec.rpc_proxy\".\nConnect javascript end to the websocket port and connect to the RPC.\n\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import rpc\nfrom tvm.contrib import utils, emcc\nfrom tvm.relay.backend import Runtime\nimport numpy as np\n\nproxy_host = \"127.0.0.1\"\nproxy_port = 9090\n\n\ndef test_rpc():\n    if not tvm.runtime.enabled(\"rpc\"):\n        return\n    # generate the wasm library\n    target = tvm.target.Target(\"webgpu\", host=\"llvm -mtriple=wasm32-unknown-unknown-wasm\")\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    if not tvm.runtime.enabled(target_host):\n        raise RuntimeError(\"Target %s is not enbaled\" % target_host)\n\n    n = 2048\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    num_thread = 2\n    xo, xi = s[B].split(B.op.axis[0], factor=num_thread)\n    s[B].bind(xi, te.thread_axis(\"threadIdx.x\"))\n    s[B].bind(xo, te.thread_axis(\"blockIdx.x\"))\n\n    fadd = tvm.build(s, [A, B], target, runtime=runtime, name=\"addone\")\n    temp = utils.tempdir()\n\n    wasm_path = temp.relpath(\"addone_gpu.wasm\")\n    fadd.export_library(wasm_path, emcc.create_tvmjs_wasm)\n\n    wasm_binary = open(wasm_path, \"rb\").read()\n    remote = rpc.connect(\n        proxy_host,\n        proxy_port,\n        key=\"wasm\",\n        session_constructor_args=[\"rpc.WasmSession\", wasm_binary],\n    )\n\n    def check(remote):\n        # basic function checks.\n        dev = remote.webgpu(0)\n        adata = np.random.uniform(size=n).astype(A.dtype)\n        a = tvm.nd.array(adata, dev)\n        b = tvm.nd.array(np.zeros(n, dtype=A.dtype), dev)\n\n        np.testing.assert_equal(a.numpy(), adata)\n        f1 = remote.system_lib()\n        addone = f1.get_function(\"addone\")\n        addone(a, b)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n        print(\"Test pass..\")\n\n    check(remote)\n\n\ntest_rpc()\n"
    },
    {
        "repo": "https://github.com/zk-ml/tachikoma",
        "file_path": "web/tests/python/websock_rpc_test.py",
        "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Simple testcode to test Javascript RPC\n\nTo use it, start a rpc proxy with \"python -m tvm.exec.rpc_proxy\".\nConnect javascript end to the websocket port and connect to the RPC.\n\"\"\"\n\nimport tvm\nfrom tvm import te\nfrom tvm import rpc\nfrom tvm.contrib import utils, emcc\nfrom tvm.relay.backend import Runtime\nimport numpy as np\n\nproxy_host = \"127.0.0.1\"\nproxy_port = 9090\n\n\ndef test_rpc():\n    if not tvm.runtime.enabled(\"rpc\"):\n        return\n    # generate the wasm library\n    runtime = Runtime(\"cpp\", {\"system-lib\": True})\n    target = \"llvm -mtriple=wasm32-unknown-unknown-wasm\"\n    if not tvm.runtime.enabled(target):\n        raise RuntimeError(\"Target %s is not enbaled\" % target)\n    n = te.var(\"n\")\n    A = te.placeholder((n,), name=\"A\")\n    B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name=\"B\")\n    s = te.create_schedule(B.op)\n\n    fadd = tvm.build(s, [A, B], target, runtime=runtime, name=\"addone\")\n    temp = utils.tempdir()\n\n    wasm_path = temp.relpath(\"addone.wasm\")\n    fadd.export_library(wasm_path, emcc.create_tvmjs_wasm)\n\n    wasm_binary = open(wasm_path, \"rb\").read()\n\n    remote = rpc.connect(\n        proxy_host,\n        proxy_port,\n        key=\"wasm\",\n        session_constructor_args=[\"rpc.WasmSession\", wasm_binary],\n    )\n\n    def check(remote):\n        # basic function checks.\n        faddone = remote.get_function(\"testing.asyncAddOne\")\n        fecho = remote.get_function(\"testing.echo\")\n        assert faddone(100) == 101\n        assert fecho(1, 2, 3) == 1\n        assert fecho(1, 2, 3) == 1\n        assert fecho(100, 2, 3) == 100\n        assert fecho(\"xyz\") == \"xyz\"\n        assert bytes(fecho(bytearray(b\"123\"))) == b\"123\"\n\n        # run the generated library.\n        f1 = remote.system_lib()\n        dev = remote.cpu(0)\n        a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev)\n        b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev)\n        # invoke the function\n        addone = f1.get_function(\"addone\")\n        addone(a, b)\n\n        # time evaluator\n        time_f = f1.time_evaluator(\"addone\", dev, number=100, repeat=10)\n        time_f(a, b)\n        cost = time_f(a, b).mean\n        print(\"%g secs/op\" % cost)\n        np.testing.assert_equal(b.numpy(), a.numpy() + 1)\n\n    check(remote)\n\n\ntest_rpc()\n"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "host/src/main.rs",
        "content": "use methods::{PREDICTION_ELF, PREDICTION_ID};\nuse risc0_zkvm::Prover;\nuse risc0_zkvm::serde::{from_slice, to_vec};\nuse std::io;\n\n\nfn main() {\n    // Make the prover.\n    let mut prover =\n        Prover::new(PREDICTION_ELF).expect(\"Prover should be constructed from valid ELF binary\");\n\n    // TODO: Implement communication with the guest here\n    println!(\"Please input the sepal length, sepal width, petal length, petal width.\");\n\n    let mut input = String::new();\n    io::stdin().read_line(&mut input).unwrap();\n    let mut s = input.split_whitespace();\n\n\n    let sepal_length: u32 = s.next().unwrap().parse().unwrap(); \n    let sepal_width: u32 = s.next().unwrap().parse().unwrap();\n    let petal_length: u32 = s.next().unwrap().parse().unwrap();\n    let petal_width :u32 = s.next().unwrap().parse().unwrap();\n\n    prover.add_input_u32_slice(&to_vec(&sepal_length).unwrap());\n    prover.add_input_u32_slice(&to_vec(&sepal_width).unwrap());\n    prover.add_input_u32_slice(&to_vec(&petal_length).unwrap());\n    prover.add_input_u32_slice(&to_vec(&petal_width).unwrap());\n\n\n    // Run prover & generate receipt\n    let receipt = prover.run().expect(\n        \"Code should be provable unless it had an error or exceeded the maximum cycle limit\",\n    );\n\n    // TODO: Implement code for transmitting or serializing the receipt for\n    // other parties to verify here\n\n    // Optional: Verify receipt to confirm that recipients will also be able to\n    // verify your receipt\n    receipt.verify(&PREDICTION_ID).expect(\n        \"Code you have proven should successfully verify; did you specify the correct method ID?\",\n    );\n\n        // Extract journal of receipt\n        let c: u32 = from_slice(&receipt.journal).unwrap();\n\n        let dic = [\"setosa\", \"versicolor\", \"virginica\"];\n\n\n        // Print an assertion\n        println!(\"This is the {} flower, and I can prove it!\", dic[c as usize]);\n}\n"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "methods/build.rs",
        "content": "fn main() {\n    risc0_build::embed_methods();\n}\n"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "methods/guest/src/bin/prediction.rs",
        "content": "// TODO: Rename this file to change the name of this method from METHOD_NAME\n\n#![no_main]\n// If you want to try std support, also update the guest Cargo.toml file\n#![no_std]  // std support is experimental\nuse risc0_zkvm::guest::env;\n\nrisc0_zkvm::guest::entry!(main);\n\npub fn main() {\n    // TODO: Implement your guest code here\n    let sepal_length: u32 = env::read();\n    let sepal_width: u32 = env::read();\n    let petal_length: u32 = env::read();\n    let petal_width: u32 = env::read();\n\n    let prediction: u32 = predict(sepal_length, sepal_width, petal_length, petal_width);\n\n    env::commit(&prediction);\n}\n\nfn predict(sepal_length: u32, sepal_width: u32, petal_length: u32, petal_width :u32) -> u32 {\n    if petal_width <= 80 {\n        return 0\n     }\n    else {\n        if petal_width <= 175 {\n            if petal_length <= 495 {\n                if petal_width <= 165 {\n                    return 1\n                 }\n                else {\n                    return 2\n                 }\n             }\n            else {\n                if petal_width <= 155 {\n                    return 2\n                 }\n                else {\n                    if sepal_length <= 695 {\n                        return 1\n                     }\n                    else {\n                        return 2\n                     }\n                 }\n             }\n         }\n        else{ \n            if petal_length <= 485 {\n                if sepal_length <= 595 {\n                    return 1\n                 }\n                else {\n                    return 2\n                 }\n             }\n            else {\n                return 2\n             }\n         }\n     }\n}"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "methods/src/lib.rs",
        "content": "include!(concat!(env!(\"OUT_DIR\"), \"/methods.rs\"));\n"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "plot_iris_dataset.ipynb",
        "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 5,\n      \"metadata\": {\n        \"collapsed\": false\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"%matplotlib inline\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {},\n      \"source\": [\n        \"\\n\",\n        \"# The Iris Dataset\\n\",\n        \"This data sets consists of 3 different types of irises'\\n\",\n        \"(Setosa, Versicolour, and Virginica) petal and sepal\\n\",\n        \"length, stored in a 150x4 numpy.ndarray\\n\",\n        \"\\n\",\n        \"The rows being the samples and the columns being:\\n\",\n        \"Sepal Length, Sepal Width, Petal Length and Petal Width.\\n\",\n        \"\\n\",\n        \"The below plot uses the first two features.\\n\",\n        \"See [here](https://en.wikipedia.org/wiki/Iris_flower_data_set) for more\\n\",\n        \"information on this dataset.\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": 6,\n      \"metadata\": {\n        \"collapsed\": false\n      },\n      \"outputs\": [\n        {\n          \"data\": {\n            \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAApMAAAH1CAYAAACqU3UnAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAACgpElEQVR4nOzdd1RU1xYH4N80ptBBuqDYBVHB3ns3FmLsvcSSqtFE00w1xjRNjL2XmFhjYg323ntFESuKdBiYPvv9gfAcZ0ZxGBjR/a3lei/3cNj7DnDZ3LlnHwERERhjjDHGGLOB0NEJMMYYY4yxkouLScYYY4wxZjMuJhljjDHGmM24mGSMMcYYYzbjYpIxxhhjjNmMi0nGGGOMMWYzLiYZY4wxxpjNxI4IajQakZCQAFdXVwgEAkekwBhjjDHGnoKIkJWVhcDAQAiF1u8/OqSYTEhIQHBwsCNCM8YYY4yx53Dnzh2ULl3a6rhDiklXV1cAucm5ubk5IgXGGGOMMfYUmZmZCA4Ozq/brHFIMZn31rabmxsXk4wxxhhjL7BnPZLIC3AYY4wxxpjNuJhkjDHGGGM242KSMcYYY4zZjItJxhhjjDFmMy4mGWOMMcaYzbiYZIwxxhhjNuNikjHGGGOM2YyLScYYY4wxZ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9vLy8ZLfbTfcKAJXBx9wAqq2MjAzdfffdWrx4sQ4cOKCkpCQtXbpUb7zxhoYNGyZJuueeexQVFaXhw4drzZo1OnXqlLZt26Zp06Zp9+7dJcfy8fFRdHS09u/fr82bN2vSpEkaNWqUGjVqJElq2bKlFi1apKNHj+rbb7/VmDFjVKdOHdO9t2rVSmPGjNG4ceP0j3/8Q0lJSdq5c6dee+01rVix4oaP8/TTT+u1117TP//5Tx07dkzPPPOMMjMzS84ySlLTpk317bff6tSpU0pPT+fMIwCnIkwCqLb8/PzUtWtX/elPf1KvXr10++23a/r06YqJidF7770n6dpHtytXrlSvXr306KOPqlWrVnrooYd0+vRphYaGlhyrRYsWeuCBBzR48GANGDBAd9xxh95///2S8Xnz5ikzM1ORkZF65JFHNGnSJIWEhFSq/7i4OI0bN07PPfecWrdureHDh2vXrl2KiIi44WPExsbq17/+tcaNG6eoqCj5+flp4MCB8vHxKdlnypQpslqtatu2rYKDg03P8wQAMyxGVU7OAYBq6KWXXtLy5cu1b98+V7dSaQ6HQ23atNGoUaM0Y8YMV7cDAMyZBIDq7PTp01qzZo169+6twsJCvffee0pKStLDDz/s6tYAQBIfcwNAtebh4aH58+erS5cu6t69uw4ePKi1a9eqTZs2rm4NACTxMTcAAAAqgTOTAAAAMI0wCQAAANMIkwAAADCNMAkAAADTCJMAAAAwjTAJAAAA0wiTAAAAMI0wCQAAANP+D1wbEHLwDuLiAAAAAElFTkSuQmCC\",\n            \"text/plain\": [\n              \"<Figure size 800x600 with 1 Axes>\"\n            ]\n          },\n          \"metadata\": {},\n          \"output_type\": \"display_data\"\n        },\n        {\n          \"data\": {\n            \"image/png\": \"iVBORw0KGgoAAAANSUhEUgAAAeIAAAH4CAYAAACWpO5eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOydd3hU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q6u+PTTT9VOnSSYAsDatWvR1NSECxcu4PLly3j99dfx22+/oaWlBYsWLcKff/455s8k40LajE6xsEwX2NQ0CwuLRkiAnTdvHn788Uf09fXRgbi3txcnT56EUCiEubk5zp49i9raWuzYsQPAcIfzm2++ifXr18PX1xdeXl5a/0y2kYrlnwZ7ImZhYbkif/31F2699VZ8+OGHEIlEcHR0xIoVK/Df//4XBw4cgEgkQmRkJNauXYtrr72WDaQsLOOEDcQsLCwaqa2txYsvvoisrCwUFxeDy+XCw8MDTz75JB599FFIpVKYmJhc8TWUU9csLCyaYVPTLCwsGunv78fQ0BDuuece3HTTTQgODlb5PgnCo83qAmCDMAuLFrAnYhYWFq0hes1s+pmFRXewgZiFhWVUFAoFbebAnm5ZWPQDG4hZWFhYWFimEHZQj4WFhYWFZQphAzELCwsLC8sUwgZiFhYWFhaWKYQNxCwsLCwsLFMIG4hZWFhYWFimEDYQs7CwsLCwTCFsIGZhYWFhYZlC/g+rzS+2WwwvqgAAAABJRU5ErkJggg==\",\n            \"text/plain\": [\n              \"<Figure size 800x600 with 1 Axes>\"\n            ]\n          },\n          \"metadata\": {},\n          \"output_type\": \"display_data\"\n        }\n      ],\n      \"source\": [\n        \"# Code source: Ga\u00ebl Varoquaux\\n\",\n        \"# Modified for documentation by Jaques Grobler\\n\",\n        \"# License: BSD 3 clause\\n\",\n        \"\\n\",\n        \"import matplotlib.pyplot as plt\\n\",\n        \"\\n\",\n        \"# unused but required import for doing 3d projections with matplotlib < 3.2\\n\",\n        \"import mpl_toolkits.mplot3d  # noqa: F401\\n\",\n        \"\\n\",\n        \"from sklearn import datasets\\n\",\n        \"from sklearn.decomposition import PCA\\n\",\n        \"\\n\",\n        \"# import some data to play with\\n\",\n        \"iris = datasets.load_iris()\\n\",\n        \"X = iris.data[:, :2]  # we only take the first two features.\\n\",\n        \"y = iris.target\\n\",\n        \"\\n\",\n        \"x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5\\n\",\n        \"y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5\\n\",\n        \"\\n\",\n        \"plt.figure(2, figsize=(8, 6))\\n\",\n        \"plt.clf()\\n\",\n        \"\\n\",\n        \"# Plot the training points\\n\",\n        \"plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1, edgecolor=\\\"k\\\")\\n\",\n        \"plt.xlabel(\\\"Sepal length\\\")\\n\",\n        \"plt.ylabel(\\\"Sepal width\\\")\\n\",\n        \"\\n\",\n        \"plt.xlim(x_min, x_max)\\n\",\n        \"plt.ylim(y_min, y_max)\\n\",\n        \"plt.xticks(())\\n\",\n        \"plt.yticks(())\\n\",\n        \"\\n\",\n        \"# To getter a better understanding of interaction of the dimensions\\n\",\n        \"# plot the first three PCA dimensions\\n\",\n        \"fig = plt.figure(1, figsize=(8, 6))\\n\",\n        \"ax = fig.add_subplot(111, projection=\\\"3d\\\", elev=-150, azim=110)\\n\",\n        \"\\n\",\n        \"X_reduced = PCA(n_components=3).fit_transform(iris.data)\\n\",\n        \"ax.scatter(\\n\",\n        \"    X_reduced[:, 0],\\n\",\n        \"    X_reduced[:, 1],\\n\",\n        \"    X_reduced[:, 2],\\n\",\n        \"    c=y,\\n\",\n        \"    cmap=plt.cm.Set1,\\n\",\n        \"    edgecolor=\\\"k\\\",\\n\",\n        \"    s=40,\\n\",\n        \")\\n\",\n        \"\\n\",\n        \"ax.set_title(\\\"First three PCA directions\\\")\\n\",\n        \"ax.set_xlabel(\\\"1st eigenvector\\\")\\n\",\n        \"ax.xaxis.set_ticklabels([])\\n\",\n        \"ax.set_ylabel(\\\"2nd eigenvector\\\")\\n\",\n        \"ax.yaxis.set_ticklabels([])\\n\",\n        \"ax.set_zlabel(\\\"3rd eigenvector\\\")\\n\",\n        \"ax.zaxis.set_ticklabels([])\\n\",\n        \"\\n\",\n        \"plt.savefig(\\\"iris_dataset.png\\\")\\n\",\n        \"plt.show()\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"language\": \"python\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"codemirror_mode\": {\n        \"name\": \"ipython\",\n        \"version\": 3\n      },\n      \"file_extension\": \".py\",\n      \"mimetype\": \"text/x-python\",\n      \"name\": \"python\",\n      \"nbconvert_exporter\": \"python\",\n      \"pygments_lexer\": \"ipython3\",\n      \"version\": \"3.10.9\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
    },
    {
        "repo": "https://github.com/only4sim/ZK-DTP",
        "file_path": "plot_iris_dtc.ipynb",
        "content": "{\"cells\":[{\"cell_type\":\"code\",\"execution_count\":44,\"metadata\":{\"collapsed\":false,\"jupyter\":{\"outputs_hidden\":false},\"trusted\":true},\"outputs\":[],\"source\":[\"%matplotlib inline\"]},{\"cell_type\":\"markdown\",\"metadata\":{},\"source\":[\"\\n\",\"# Plot the decision surface of decision trees trained on the iris dataset\\n\",\"\\n\",\"Plot the decision surface of a decision tree trained on pairs\\n\",\"of features of the iris dataset.\\n\",\"\\n\",\"See `decision tree <tree>` for more information on the estimator.\\n\",\"\\n\",\"For each pair of iris features, the decision tree learns decision\\n\",\"boundaries made of combinations of simple thresholding rules inferred from\\n\",\"the training samples.\\n\",\"\\n\",\"We also show the tree structure of a model built on all of the features.\\n\"]},{\"cell_type\":\"markdown\",\"metadata\":{},\"source\":[\"First load the copy of the Iris dataset shipped with scikit-learn:\\n\",\"\\n\"]},{\"cell_type\":\"code\",\"execution_count\":45,\"metadata\":{\"collapsed\":false,\"jupyter\":{\"outputs_hidden\":false},\"trusted\":true},\"outputs\":[],\"source\":[\"from sklearn.datasets import load_iris\\n\",\"\\n\",\"iris = load_iris()\"]},{\"cell_type\":\"markdown\",\"metadata\":{},\"source\":[\"Display the decision functions of trees trained on all pairs of features.\\n\",\"\\n\"]},{\"cell_type\":\"code\",\"execution_count\":46,\"metadata\":{\"collapsed\":false,\"jupyter\":{\"outputs_hidden\":false},\"trusted\":true},\"outputs\":[{\"name\":\"stderr\",\"output_type\":\"stream\",\"text\":[\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\",\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\",\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\",\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\",\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\",\"/var/folders/4v/hb_2qz1d4knbrvsjqc0skwrm0000gn/T/ipykernel_1670/3884067348.py:39: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\\n\",\"  plt.scatter(\\n\"]},{\"data\":{\"image/png\":\"iVBORw0KGgoAAAANSUhEUgAAAkMAAAHHCAYAAAC88FzIAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOydd3gU1deA3930XoDQIRBqCL0T6R2UIhYQaRYQ6VgQVBDp8omASLMAgopU4af0roihiZTQISHUUJKQXnbv98dkN9nsJtkNSTblvs+zT9g7M3fODndmzj33FJUQQ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P39hZOTk/D09BSNGzcWP/30U2aXPE8p9NOTQYMGMWXKFPbs2cPbb78NwIULFwgMDKR8+fJ89NFHuLi4sGHDBvr06cPmzZvp27cvADExMbRu3ZqLFy/yxhtv0KhRIx49esT27du5ffs2JUuWNHnOfv36ceHCBcaMGYOvry/h4eHs3buXW7du4evra/KY+Ph42rVrx7Vr1xg9ejRVqlRh48aNDB06lMjISMaNG2ew/88//0x0dDQjRoxApVLxxRdf8OKLL3Ljxg3s7OwyvR6fffYZc+bM4a233qJZs2Y8ffqUkydPcvr0aTp37pyDKwyrVq0iISGB4cOH4+DgQKNGjVi7di2DBg2ic+fODB48WL/vjRs3+O2333j55ZepUqUKDx48YMWKFbRt25bg4GDKlSsHgEaj4fnnn2f//v3079+fcePGER0dzd69ezl//jx+fn4AjBgxQu83NnbsWG7evMmSJUv4999/OXr0aJbXYt++fXTv3p2qVavy2WefER8fz9dff01gYCCnT5/G19eXESNGUL58eWbPns3YsWNp2rQppUuXzrTP+/fv0759e1JSUvRja+XKlSatkmvXrmXIkCF07dqVefPmERcXx7Jly3juuef4999/9WPl7NmztG7dGjs7O4YPH46vry/Xr1/nf//7H7NmzTIpR3h4OF26dKFUqVJ89NFHeHp6EhISwpYtW7L8v7xw4QKtW7fG3d2dDz/8EDs7O1asWEG7du04fPgwzZs3N9h/zJgxeHl5MW3aNEJCQli4cCGjR4/m119/zfQcI0aM4O7du+zdu5e1a9ea3CfjmPL29jb7vo2Li6Nt27bcuXOHESNGUKlSJf7++28mT57MvXv39E6ne/fuZcCAAXTs2JF58+YBcPHiRY4ePWp0v+koVaoUy5YtY+TIkfTt25cXX3wRgHr16un3SUlJoWvXrjz33HP83//9H87OzgBs3LiRuLg4Ro4cSYkSJTh+/Dhff/01t2/fZuPGjVn+vwD89ddfbNmyhXfffRc3NzcWL15Mv379uHXrFiVKlAAUB9sWLVqgUqkYPXo0pUqVYufOnbz55ps8ffqU8ePHA8rzpmPHjty6dYuxY8dSrlw51q5dy4EDB7KVA/Jn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DO3cuZNLly6RkpLCgwcPOHDgAHv37qVy5cps377dQIv85ptveO6556hbty5vv/02VatW5cGDBxw7dozbt2/z33//AfDBBx+wadMmXn75Zd544w0aN27MkydP2L59O8uXL6d+/fpGcly5coWOHTvyyiuv4O/vj62tLVu3buXBgwf0798/U/mHDx/OihUrGDp0KKdOncLX15dNmzZx9OhRFi5cmGslRfz9/WnXrh2NGzfG29ubkydP6kNHdbzxxhssWLCArl278uabbxIeHs7y5cupU6fOMzv+Pf/883z++ecMGzaMVq1ace7cOX766SejNfjBgwfz448/MnHiRI4fP07r1q2JjY1l3759vPvuu/Tu3Zu2bdsyYsQI5syZw5kzZ+jSpQt2dnZcvXqVjRs3smjRIgMH0YzMnz+f7t2707JlS9588019aL2Hh0eOy0R8+OGHrF27lm7dujFu3Dh9aL3O8qfD3d2dZcuWMWjQIBo1akT//v0pVaoUt27d4o8//iAwMFD/Ali8eDHPPfccjRo1Yvjw4VSpUoWQkBD++OOPTGukrVmzhqVLl9K3b1/8/PyIjo7m22+/xd3dPUtFb+bMmezdu5fnnnuOd999F1tbW1asWEFiYiJffPFFjq6JKRo3bgzA2LFj6dq1KzY2NlneH2DZfbt9+3aef/55hg4dSuPGjYmNjeXcuXNs2rSJkJAQSpYsyVtvvcWTJ0/o0KEDFSpUIDQ0lK+//poGDRroffVM4eTkhL+/P7/++is1atTA29ubgICALP26atWqhZ+fH++//z537tzB3d2dzZs3P7NvVUbmzp3LwYMHad68OW+//Tb+/v48efKE06dPs2/fPp48eQIozsJLlixh8ODBnDp1irJly7J27Vq9opcd+TVOQEkMumvXLoYMGULz5s3ZuXMnf/zxB1OmTNEvhffs2ZMFCxbQrVs3XnvtNcLDw/nmm2+oVq2awX1nCdHR0VSoUIGXXnqJ+vXr4+rqyr59+zhx4gRffvlllsfm5/Uxd7xbco0aN27Mvn37WLBgAeXKlaNKlSo0b96c/v37M2nSJPr27cvYsWP16UBq1KhhthO2uWO0S5culClThsDAQEqXLs3FixdZsmQJPXv2tE6Jr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4x17537x6enp4PHd/SEDpffITOV0yEzhcfS9Z5iwugVigUhIWFMX36dI4fP46trS3r16/H29ubmjVrcvHiRerXr6/34+/vrzfGoUOHdP9XqVQcPXqUgIAAAPbv30+7du14++23adGiBfXr19cFjhWXli1bEhMTU0iu+vXr61nXD6JRo0YcOXJEb1tkZKTea1tbW9Rq9SPJqqVFixZER0frbQsODubff/8lJyenRK6Rn6ioKFq0aFHi41YGhM7nIXTeMhA6n4fQeeOwKGMoIiKCmTNncuTIEeLi4li3bh23b9/WKfj06dMJDw9n0aJFnDt3jlOnTrF8+XLmzZunN87ixYtZv349Z8+eZeTIkSQmJvLmm28C0KBBA44cOcLWrVs5d+4cH330USFlNJUpU6bw448/Mn36dE6fPs2ZM2dYtWoVkydPNnqMYcOGcfbsWSZMmMC5c+dYvXo1K1asAOQvDpCLbqWmprJjxw7u3LnzSO7Ibt26cfr0ab2nhlGjRpGcnMwrr7zCkSNHOH/+PD/99BMxMTHFvg7IGRBHjx6la9eujzROZUTovNB5S0PovND54mBRxpCLiwt79+7lmWeeoWHDhkyePJm5c+fSvXt3AN566y2+/fZbli9fTlBQEB06dGDFihWFnhhmzZrFrFmzaNasGfv27WPjxo14eHgAsjL26dOHvn37Ehoayt27d3n77bcfSe5u3brx119/8c8//9C6dWsee+wx5s+fT506dYwew9/fnzVr1rBu3TqCg4NZsmQJH374IQB2dnYAtGvXjuHDh9O3b188PT357LPPii1zUFAQLVu2ZPXq1bpt1apVY+fOnaSmptKhQwdatWrFN99888C1ZWP4448/qF27Nu3bt3+kcSojQueFzlsaQueFzheLUgnLrqRoswyOHz9ublFKhBkzZkg+Pj6lNv5ff/0lBQQE6GUNlAahoaHSL7/8UqrXsFSEzpuG0PmKj9B506gsOm9RAdSWzldffUXr1q2pVq0a+/fvZ86cOYwaNarUrtejRw/Onz/PtWvX8PX1LZVr3Llzhz59+tCvX79SGV9QsRE6L7A0hM4XD4UkSVKpjV7JuHz5Mv7+/hw/fvyRUijNxdixY/ntt9+4d+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Kqlatam4xSpSSNML+++8/Nm3axLvvvlsi4xXF5MmT+fTTT0lKSiq1awhjqJJRvXp17OzszHJtSZL48ssvGTx4cKlfa8CAAezbt4/Tp0+X+rUE5Ruh8wKBefjiiy946aWXqFKlSqleJzAwkHr16vHzzz+X2jUs2hhas2YNQUFBODg4UK1aNbp06UJaWppu/7fffktAQAD29vY0btyYr776SrdP63pftWoV7dq1w97ensDAQPbs2aM7Rq1WM3jwYPz9/XFwcKBRo0YsXLjQaPkkScLT05M1a9botjVv3pwaNWroXu/btw87OzvS09OBwlb/4cOHadGiBfb29oSEhHD8+HG99/Dkk08C4ObmhkKh0Gu6qdFo+N///oe7uzvVq1dn2rRpD5T36NGjxMbG0qNHD73t2kaA7u7uODk5ERISQkREBJDnnv3++++pXbs2VapU4e2330atVvPZZ59RvXp1vLy8+PTTT/XGdHNzIywsjFWrVj38DynQIXRe6Lyl0LFjR0aNGsWoUaNwdXXFw8ODjz76iPztOLOyshg/fjy1atXCycmJ0NBQdu/eDcgexEGDBpGUlIRCoUChUOj04aeffiIkJARnZ2eqV69O//79SUhIeCR54+Pjefnll6latSru7u707NmTy5cv6/Zrl5c///xzatSoQbVq1Rg5ciQ5OTm6Y27cuEGPHj1wcHDA39+flStX4ufnx4IFCwDw8/MDoHfv3igUCt1rLT/99BN+fn64urryyiuvkJKSUqS8arWaNWvW8Nxzz+ltz8rKYsKECfj6+mJnZ0f9+vX57rvvgDyv7NatW2nRogUODg506tSJhIQENm/eTEBAAC4uLvTv3183v7U899xzpav7koVy/fp1ydraWpo3b5506dIl6eTJk9LixYullJQUSZIk6eeff5Zq1KghrV27Vrp48aK0du1ayd3dXVqxYoUkSZJ06dIlCZB8fHykNWvWSNHR0dJbb70lOTs7S3fu3JEkSZKys7OlKVOmSJGRkdLFixeln3/+WXJ0dJR+++03nRwDBw6UevbsWaScffr0kUaOHClJkiTdu3dPsrW1lVxdXaUzZ85IkiRJM2bMkMLCwnTHA9L69eslSZKklJQUydPTU+rfv78UFRUl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WSJHne1KlTR1KpVLpjXnrpJalv376SJEnSmTNnJECKjIzU7T9//rwE6IyhgtfVYkgn33//fSk0NLRI+devXy9ZWVnpyRwTEyMB0rZt2wyeo/27bN++XbctPDxcAqTY2FjdtmHDhkndunXTO/e///574PfXo2Kxy2TNmjWjc+fOBAUF8dJLL/HNN9+QmJgIQFpaGrGxsQwePJgqVarofmbMmEFsbKzeOG3bttX939rampCQEM6cOaPbtnjxYlq1aoWnpydVqlTh66+/Ji4uzmg5O3ToQHR0NLdv32bPnj107NiRjh07snv3bnJycjhw4AAdO3Y0eO6ZM2cIDg7G3t7eoLwPIzg4WO91jRo1HugKzsjI0LsWwIkTJ2jRogXu7u5Fnufn54ezs7Putbe3N02aNEGpVOptK3htBweHQq5UQdEInX84QucrF4899hgKhUL3um3btpw/fx61Ws2pU6dQq9U0bNhQT+f37NlTSOcLcvToUZ577jlq166Ns7MzHTp0ADBJz/Pz33//ceHCBZydnXVyuLu7k5mZqSdL06ZNsbKy0r3Or58xMTFYW1vTsmVL3f769evj5uZmlAwFddIY3bezs9P7+544cQIrKyvd36Mo8s8zb29vHB0dqVu3rt42Q7oPlJr+W5fKqBUAKysrtm3bxoEDB/jnn3/44osv+PDDD4mIiMDR0RGAb775htDQ0ELnGcuqVasYP348c+fOpW3btjg7OzNnzhxd7IAxBAUF4e7uzp49e9izZw+ffvop1atXZ/bs2URGRpKTk1NqWSw2NjZ6rxUKBRqNpsjjPTw8OHXqlN42rQKbeh1jrn3v3j08PT0fOr5ARuj8wxE6bzmkpqZiZWXF0aNHC+n4gwKC09LS6NatG926deOXX37B09OTuLg4unXrRnZ2drFladWqFb/88kuhffk/b1P10xSKo/vp6elkZ2dja2sLGKf7Ba9liu4Dpab/FusZAvkPHhYWxvTp0zl+/Di2trasX78eb29vatasycWLF6lfv77ej7+/v94Yhw4d0v1fpVJx9OhRAgICANi/fz/t2rXj7bffpkWLFtSvX/+hTxyGZGzfvj1//PEHp0+f5vHHHyc4OJisrCyWLVtGSEgIT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XQxw8eJCkpCRefPHFRxrHkhA6LyN03nJ4/fXXycjIoE2bNowcOZLRo0czdOhQ3f7ly5fz+uuv895779GoUSN69epFZGQktWvXBqBdu3YMHz6cvn374unpyWeffYanpycrVqzg999/p0mTJsyaNauQwW0qjo6O7N27l9q1a9OnTx8CAgIYPHgwmZmZuLi4GD3Ojz/+iLe3N0888QS9e/dmyJAhODs768W1zZ07l23btuHr6/vIXsa33nqr0NLekiVLePHFF3n77bdp3LgxQ4YM0SvfURwyMzPZsGEDQ4YMeaRxHoRCyu/fFRjN5cuX8ff35/jx48UuY14ZOXnyJE899RSxsbGlWoirb9++NGvWjEmTJpXaNQT6CJ03jND58knHjh1p3ry5rsaOJXL16lV8fX3Zvn07nTt3LvHxMzIyaNSoEb/99ptJiQqmsmTJEtavX88///xTatewWM+QoHQIDg5m9uzZXLp0qdSukZ2dTVBQEGPHji21awgExiJ0XlBe2LlzJxs3buTSpUscOHCAV155BT8/P5544olSuZ6DgwM//vgjd+7cKZXxtdjY2PDFF1+U6jUsNptMUHrkr+hbGtja2jJ58uRSvYZAYApC5wXlgZycHCZNmsTFixdxdnamXbt2/PLLL4WytUqSBy1blxRvvfVWqV9DLJMJBAKBQCCwaMQymUAgEAgEAotGGEMCgUAgEAgsGmEMCQQCgUAgsGiEMSQQCAQCgcCiEcaQQCAQCAQCi0YYQwKBQCAQCCwaYQwJBAKBQCCwaIQxJBAIBAKBwKL5P3zNmSO6hndVAAAAAElFTkSuQmCC\",\"text/plain\":[\"<Figure size 640x480 with 6 Axes>\"]},\"metadata\":{},\"output_type\":\"display_data\"}],\"source\":[\"import numpy as np\\n\",\"import matplotlib.pyplot as plt\\n\",\"\\n\",\"from sklearn.datasets import load_iris\\n\",\"from sklearn.tree import DecisionTreeClassifier\\n\",\"from sklearn.inspection import DecisionBoundaryDisplay\\n\",\"\\n\",\"\\n\",\"# Parameters\\n\",\"n_classes = 3\\n\",\"plot_colors = \\\"ryb\\\"\\n\",\"plot_step = 0.02\\n\",\"\\n\",\"\\n\",\"for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]):\\n\",\"    # We only take the two corresponding features\\n\",\"    X = iris.data[:, pair]\\n\",\"    y = iris.target\\n\",\"\\n\",\"    # Train\\n\",\"    clf = DecisionTreeClassifier().fit(X, y)\\n\",\"\\n\",\"    # Plot the decision boundary\\n\",\"    ax = plt.subplot(2, 3, pairidx + 1)\\n\",\"    plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5)\\n\",\"    DecisionBoundaryDisplay.from_estimator(\\n\",\"        clf,\\n\",\"        X,\\n\",\"        cmap=plt.cm.RdYlBu,\\n\",\"        response_method=\\\"predict\\\",\\n\",\"        ax=ax,\\n\",\"        xlabel=iris.feature_names[pair[0]],\\n\",\"        ylabel=iris.feature_names[pair[1]],\\n\",\"    )\\n\",\"\\n\",\"    # Plot the training points\\n\",\"    for i, color in zip(range(n_classes), plot_colors):\\n\",\"        idx = np.where(y == i)\\n\",\"        plt.scatter(\\n\",\"            X[idx, 0],\\n\",\"            X[idx, 1],\\n\",\"            c=color,\\n\",\"            label=iris.target_names[i],\\n\",\"            cmap=plt.cm.RdYlBu,\\n\",\"            edgecolor=\\\"black\\\",\\n\",\"            s=15,\\n\",\"        )\\n\",\"\\n\",\"plt.suptitle(\\\"Decision surface of decision trees trained on pairs of features\\\")\\n\",\"plt.legend(loc=\\\"lower right\\\", borderpad=0, handletextpad=0)\\n\",\"_ = plt.axis(\\\"tight\\\")\"]},{\"cell_type\":\"markdown\",\"metadata\":{},\"source\":[\"Display the structure of a single decision tree trained on all the features\\n\",\"together.\\n\",\"\\n\"]},{\"cell_type\":\"code\",\"execution_count\":47,\"metadata\":{\"collapsed\":false,\"jupyter\":{\"outputs_hidden\":false},\"trusted\":true},\"outputs\":[{\"data\":{\"image/png\":\"iVBORw0KGgoAAAANSUhEUgAAAgMAAAGbCAYAAABZBpPkAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIH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IUQ/J8GAEEII0c9JMCCEEEL0cxIMCCGEEP2cBANCCCFEPyfBgBBCCNHPSTAghBBC9HMSDAghhBD9nAQDQgghRD8nwYAQQgjRz0kwIIQQQvRzEgwIIYQQ/ZwEA0IIIUQ/J8GAEEII0c9JMCCEEEL0cxIMCCGEEP2cBANCCCFEPyfBgBBCCNHPSTAghBBC9HMSDAghhBD93P8HoZ5cpab9tMYAAAAASUVORK5CYII=\",\"text/plain\":[\"<Figure size 640x480 with 1 Axes>\"]},\"metadata\":{},\"output_type\":\"display_data\"}],\"source\":[\"from sklearn.tree import plot_tree\\n\",\"\\n\",\"plt.figure()\\n\",\"clf = DecisionTreeClassifier().fit(iris.data, iris.target)\\n\",\"plot_tree(clf, filled=True)\\n\",\"plt.title(\\\"Decision tree trained on all the iris features\\\")\\n\",\"plt.show()\"]},{\"cell_type\":\"code\",\"execution_count\":48,\"metadata\":{\"trusted\":true},\"outputs\":[],\"source\":[\"from sklearn.tree import export_text\"]},{\"cell_type\":\"code\",\"execution_count\":49,\"metadata\":{\"trusted\":true},\"outputs\":[{\"name\":\"stdout\",\"output_type\":\"stream\",\"text\":[\"|--- petal length (cm) <= 2.45\\n\",\"|   |--- class: 0\\n\",\"|--- petal length (cm) >  2.45\\n\",\"|   |--- petal width (cm) <= 1.75\\n\",\"|   |   |--- petal length (cm) <= 4.95\\n\",\"|   |   |   |--- petal width (cm) <= 1.65\\n\",\"|   |   |   |   |--- class: 1\\n\",\"|   |   |   |--- petal width (cm) >  1.65\\n\",\"|   |   |   |   |--- class: 2\\n\",\"|   |   |--- petal length (cm) >  4.95\\n\",\"|   |   |   |--- petal width (cm) <= 1.55\\n\",\"|   |   |   |   |--- class: 2\\n\",\"|   |   |   |--- petal width (cm) >  1.55\\n\",\"|   |   |   |   |--- petal length (cm) <= 5.45\\n\",\"|   |   |   |   |   |--- class: 1\\n\",\"|   |   |   |   |--- petal length (cm) >  5.45\\n\",\"|   |   |   |   |   |--- class: 2\\n\",\"|   |--- petal width (cm) >  1.75\\n\",\"|   |   |--- petal length (cm) <= 4.85\\n\",\"|   |   |   |--- sepal length (cm) <= 5.95\\n\",\"|   |   |   |   |--- class: 1\\n\",\"|   |   |   |--- sepal length (cm) >  5.95\\n\",\"|   |   |   |   |--- class: 2\\n\",\"|   |   |--- petal length (cm) >  4.85\\n\",\"|   |   |   |--- class: 2\\n\",\"\\n\"]}],\"source\":[\"r = export_text(clf, feature_names=iris['feature_names'])\\n\",\"print(r)\"]},{\"cell_type\":\"code\",\"execution_count\":50,\"metadata\":{\"trusted\":true},\"outputs\":[],\"source\":[\"from sklearn.tree import _tree\\n\",\"\\n\",\"def tree_to_code(tree, feature_names):\\n\",\"    tree_ = tree.tree_\\n\",\"    feature_name = [\\n\",\"        feature_names[i] if i != _tree.TREE_UNDEFINED else \\\"undefined!\\\"\\n\",\"        for i in tree_.feature\\n\",\"    ]\\n\",\"    feature_names = [f.replace(\\\" \\\", \\\"_\\\")[:-5] for f in feature_names]\\n\",\"    print(\\\"fn predict({} :u32) -> u32 {{\\\".format(\\\": u32, \\\".join(feature_names)))\\n\",\"\\n\",\"    def recurse(node, depth):\\n\",\"        indent = \\\"    \\\" * depth\\n\",\"        if tree_.feature[node] != _tree.TREE_UNDEFINED:\\n\",\"            name = feature_name[node].replace(\\\" \\\", \\\"_\\\")[:-5]\\n\",\"            threshold = tree_.threshold[node]\\n\",\"            print(\\\"{}if {} <= {} {{\\\".format(indent, name, np.round(threshold,2)))\\n\",\"            recurse(tree_.children_left[node], depth + 1)\\n\",\"            print(\\\"{} }}\\\".format(indent))\\n\",\"            print(\\\"{}else if {{\\\".format(indent, name, np.round(threshold,2)))\\n\",\"            recurse(tree_.children_right[node], depth + 1)\\n\",\"            print(\\\"{} }}\\\".format(indent))\\n\",\"        else:\\n\",\"            print(\\\"{}return {}\\\".format(indent, np.argmax(tree_.value[node][0])))\\n\",\"\\n\",\"    recurse(0, 1)\\n\",\"    print(\\\"}\\\")\"]},{\"cell_type\":\"code\",\"execution_count\":51,\"metadata\":{\"trusted\":true},\"outputs\":[{\"name\":\"stdout\",\"output_type\":\"stream\",\"text\":[\"fn predict(sepal_length: u32, sepal_width: u32, petal_length: u32, petal_width :u32) -> u32 {\\n\",\"    if petal_length <= 2.45 {\\n\",\"        return 0\\n\",\"     }\\n\",\"    else if {\\n\",\"        if petal_width <= 1.75 {\\n\",\"            if petal_length <= 4.95 {\\n\",\"                if petal_width <= 1.65 {\\n\",\"                    return 1\\n\",\"                 }\\n\",\"                else if {\\n\",\"                    return 2\\n\",\"                 }\\n\",\"             }\\n\",\"            else if {\\n\",\"                if petal_width <= 1.55 {\\n\",\"                    return 2\\n\",\"                 }\\n\",\"                else if {\\n\",\"                    if petal_length <= 5.45 {\\n\",\"                        return 1\\n\",\"                     }\\n\",\"                    else if {\\n\",\"                        return 2\\n\",\"                     }\\n\",\"                 }\\n\",\"             }\\n\",\"         }\\n\",\"        else if {\\n\",\"            if petal_length <= 4.85 {\\n\",\"                if sepal_length <= 5.95 {\\n\",\"                    return 1\\n\",\"                 }\\n\",\"                else if {\\n\",\"                    return 2\\n\",\"                 }\\n\",\"             }\\n\",\"            else if {\\n\",\"                return 2\\n\",\"             }\\n\",\"         }\\n\",\"     }\\n\",\"}\\n\",\"None\\n\"]}],\"source\":[\"c = tree_to_code(clf, feature_names=iris['feature_names']);\\n\",\"print(c)\"]}],\"metadata\":{\"kernelspec\":{\"display_name\":\"Python 3 (ipykernel)\",\"language\":\"python\",\"name\":\"python3\"},\"language_info\":{\"codemirror_mode\":{\"name\":\"ipython\",\"version\":3},\"file_extension\":\".py\",\"mimetype\":\"text/x-python\",\"name\":\"python\",\"nbconvert_exporter\":\"python\",\"pygments_lexer\":\"ipython3\",\"version\":\"3.10.9\"}},\"nbformat\":4,\"nbformat_minor\":4}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "backwards/backward.py",
        "content": "#\n# A script for generating a backprop computational graph from forward\n#\n\nimport argparse\nimport ast\nfrom typing import Literal, Union\nimport msgpack\nimport numpy as np\n\nclass CircuitConfig():\n    def __init__(self, starting_index):\n        self.next_index = starting_index\n        self.outp_to_grad = {}\n        self.label_tensor_idx = None\n        self.weights_update = None\n\n    # Allocates an index for a gradient tensor and returns\n    def new_gradient_tensor(self, tensor_idx):\n        if tensor_idx in self.outp_to_grad:\n            raise Exception(\"Tensor already allocated\")\n        self.outp_to_grad[tensor_idx] = self.next_index\n        self.next_index += 1\n        return self.outp_to_grad[tensor_idx]\n\n    # Allocates an index for a tensor\n    def new_tensor(self):\n        new_index = self.next_index\n        self.next_index += 1\n        return new_index\n\n    def new_label_tensor(self):\n        if self.label_tensor_idx is not None:\n            raise Exception(\"Label tensor already allocated\")\n        self.label_tensor_idx = self.next_index\n        self.next_index += 1\n        return self.label_tensor_idx\n\n    # Allocates an index for a gradient tensor and returns\n    def gradient_tensor_idx(self, tensor_idx):\n        return self.outp_to_grad[tensor_idx]\n\n# TODO: Put these in enums\nNO_ACTIVATION = 0\n\nSAME = 0\nVALID = 1\n\nCONV2D = 0\nCONV2D_DEPTHWISE = 1\n\nclass Conv2D():\n    def __init__(self, layer):\n        params = layer['params']\n        self.padding = params[1]\n        self.activation_type = params[2]\n        self.stride_h = params[3]\n        self.stride_w = params[4]\n\n    def backward(self, layer, transcript, config):\n        inputs_idx, inputs_shape = layer['inp_idxes'][0], layer['inp_shapes'][0]\n        weights_idx, weights_shape = layer['inp_idxes'][1], layer['inp_shapes'][1]\n        bias_idx, bias_shape = layer['inp_idxes'][2], layer['inp_shapes'][2]\n        output_idx, output_shape = layer['out_idxes'][0], layer['out_shapes'][0]\n\n        permuted_inputs_idx = config.new_tensor()\n        permutation = [3, 1, 2, 0]\n        permuted_inputs_shape = [inputs_shape[p] for p in permutation]\n        inputs_permute_layer = {\n            'layer_type': 'Permute',\n            'params': permutation,\n            'inp_idxes': [inputs_idx],\n            'out_idxes': [permuted_inputs_idx],\n            'inp_shapes': [inputs_shape],\n            'out_shapes': [permuted_inputs_shape],\n            'mask': [],\n        }\n        transcript.append(inputs_permute_layer)\n\n        permuted_outputs_idx = config.new_tensor()\n        permuted_outputs_shape = [output_shape[p] for p in permutation]\n        inputs_permute_layer = {\n            'layer_type': 'Permute',\n            'params': permutation,\n            'inp_idxes': [config.gradient_tensor_idx(output_idx)],\n            'out_idxes': [permuted_outputs_idx],\n            'inp_shapes': [output_shape],\n            'out_shapes': [permuted_outputs_shape],\n            'mask': [],\n        }\n        transcript.append(inputs_permute_layer)\n\n\n        dw_idx, dw_shape = config.new_tensor(), weights_shape\n        dw_conv = {\n            'layer_type': 'Conv2D',\n            'params': [CONV2D, VALID, NO_ACTIVATION, self.stride_h, self.stride_w],\n            'inp_idxes': [permuted_inputs_idx, permuted_outputs_idx],\n            'out_idxes': [dw_idx],\n            'inp_shapes': [permuted_inputs_shape, permuted_outputs_shape],\n            'out_shapes': [dw_shape],\n            'mask': [],\n        }\n        transcript.append(dw_conv)\n        config.weights_update = dw_idx\n\n        permutation = [3, 1, 2, 0]\n        permutation_weights_idx = config.new_tensor()\n        permutation_weights_shape = [weights_shape[p] for p in permutation]\n\n        permute_weights = {\n            'layer_type': 'Permute',\n            'params': permutation,\n            'inp_idxes': [weights_idx],\n            'out_idxes': [permutation_weights_idx],\n            'inp_shapes': [weights_shape],\n            'out_shapes': [permutation_weights_shape],\n            'mask': [],\n        }\n        transcript.append(permute_weights)\n\n        rotated_weights_idx, rotated_weights_shape = config.new_tensor(), permutation_weights_shape\n        rotate_layer = {\n            'layer_type': 'Rotate',\n            'params': [1, 2],\n            'inp_idxes': [permutation_weights_idx],\n            'out_idxes': [rotated_weights_idx],\n            'inp_shapes': [permutation_weights_shape],\n            'out_shapes': [rotated_weights_shape],\n            'mask': [],\n        }\n        transcript.append(rotate_layer)\n\n        padded_gradients_idx, padded_gradients_shape = config.new_tensor(), output_shape\n        padded_gradients_shape[1] += (rotated_weights_shape[1] - 1) * 2 \n        padded_gradients_shape[2] += (rotated_weights_shape[2] - 1) * 2\n        pad_layer = {\n            'layer_type': 'Pad',\n            'params': [\n                0, 0,\n                rotated_weights_shape[1] - 1, rotated_weights_shape[1] - 1,\n                rotated_weights_shape[2] - 1, rotated_weights_shape[2] - 1,\n                0, 0\n            ],\n            'inp_idxes': [config.gradient_tensor_idx(output_idx)],\n            'out_idxes': [padded_gradients_idx],\n            'inp_shapes': [],\n            'out_shapes': [],\n            'mask': [],\n        }\n        transcript.append(pad_layer)\n\n        dx_idx, dx_shape = config.new_gradient_tensor(inputs_idx), inputs_shape\n        input_conv_layer = {\n            'layer_type': 'Conv2D',\n            'params': [CONV2D, VALID, NO_ACTIVATION, self.stride_h, self.stride_w],\n            'inp_idxes': [padded_gradients_idx, rotated_weights_idx],\n            'out_idxes': [dx_idx],\n            'inp_shapes': [padded_gradients_shape, rotated_weights_shape],\n            'out_shapes': [dx_shape],\n            'mask': [],\n        }\n        transcript.append(input_conv_layer)\n\n        permutation = [3, 1, 2, 0]\n        permuted_dw_idx = config.new_tensor()\n        permuted_dw_shape = [dw_shape[p] for p in permutation]\n\n        permute_dw = {\n            'layer_type': 'Permute',\n            'params': permutation,\n            'inp_idxes': [dw_idx],\n            'out_idxes': [permuted_dw_idx],\n            'inp_shapes': [dw_shape],\n            'out_shapes': [permuted_dw_shape],\n            'mask': [],\n        }\n        transcript.append(permute_dw)\n\n        updated_weights_idx, updated_weights_shape = config.new_tensor(), dw_shape\n        # Call a layer to update the outputs of the convolution\n        update_weights_layer = {\n            'layer_type': 'Update',\n            'params': [],\n            'inp_idxes': [weights_idx, permuted_dw_idx],\n            'out_idxes': [updated_weights_idx],\n            'inp_shapes': [weights_shape, permuted_dw_shape],\n            'out_shapes': [updated_weights_shape],\n            'mask': [],\n        }\n        # transcript.append(update_weights_layer)\n\nclass Softmax():\n    def __init__(self, layer):\n        return\n\n    # TODO: Make this generalizable to all neural networks\n    # (do not assume that softmax is the last layer, fused with CE-loss)\n    def backward(self, layer, transcript, config):\n        sub_layer = {\n            'layer_type': 'Sub',\n            'params': [],\n            # y_hat - y\n            'inp_idxes': [layer['out_idxes'][0], config.label_tensor_idx],\n            'out_idxes': [config.new_gradient_tensor(layer['inp_idxes'][0])],\n            'inp_shapes': [layer['out_shapes'][0], layer['out_shapes'][0]],\n            'out_shapes': [layer['out_shapes'][0]],\n            'mask': [],\n        }\n        transcript.append(sub_layer)\n\nclass AveragePool2D():\n    def __init__(self, layer):\n        return\n\n    def backward(self, layer, transcript, config):\n        # TODO: This is very model specific, must rewrite to be accurate\n        # We just broadcast dx across 3 axes\n        # 1 x 3 x 3 x 1 -> 1 x 1 x 1 x 1280\n\n        div_idx = config.new_tensor()\n        reshape_layer = {\n            'layer_type': 'Broadcast',\n            'params': [],\n            'inp_idxes': [config.gradient_tensor_idx(layer['out_idxes'][0])],\n            'out_idxes': [div_idx],\n            'inp_shapes': [layer['out_shapes'][0]],\n            'out_shapes': [layer['inp_shapes'][0]],\n            'mask': [],\n        }\n        transcript.append(reshape_layer)\n\n        out_idx = config.new_gradient_tensor(layer['inp_idxes'][0])\n        out_shape = layer['inp_shapes'][0]\n\n        div = {\n            'layer_type': 'Div',\n            'params': [layer['inp_shapes'][0][1] * layer['inp_shapes'][0][2]],\n            'inp_idxes': [div_idx],\n            'out_idxes': [out_idx],\n            'inp_shapes': [out_shape],\n            'out_shapes': [out_shape],\n            'mask': [],\n        }\n        transcript.append(div)\n\n\nclass Reshape():\n    def __init__(self, layer):\n        return\n\n    def backward(self, layer, transcript, config):\n        reshape_layer = {\n            'layer_type': 'Reshape',\n            'params': [],\n            'inp_idxes': [config.gradient_tensor_idx(layer['out_idxes'][0])],\n            'out_idxes': [config.new_gradient_tensor(layer['inp_idxes'][0])],\n            'inp_shapes': [layer['out_shapes'][0]],\n            'out_shapes': [layer['inp_shapes'][0]],\n            'mask': [],\n        }\n        transcript.append(reshape_layer)\n\n\ndef produce_graph():\n    # Read msgpack file\n    with open(\"examples/v2_1.0_224_truncated/model.msgpack\", \"rb\") as data_file:\n        byte_data = data_file.read()\n    model = msgpack.unpackb(byte_data)\n\n    # TODO: I'm unsure whether the circuit output is always the last indexed tensor\n    softmax_output_index = int(np.max(\n            [[out for out in layer['out_idxes']] for layer in model['layers']] + \n            [[inp for inp in layer['inp_idxes']] for layer in model['layers']]\n    )[0])\n    circuit_config = CircuitConfig(softmax_output_index + 1)\n    circuit_config.new_label_tensor()\n\n    transcript = []\n    for layer in reversed(model['layers']):\n        fetched_layer = None\n        match layer['layer_type']:\n            case \"Conv2D\":\n                fetched_layer = Conv2D(layer)\n            case \"AveragePool2D\":\n                fetched_layer = AveragePool2D(layer)\n            case \"Softmax\":\n                fetched_layer = Softmax(layer)\n            case _:\n                fetched_layer = Reshape(layer)\n        print(layer['layer_type'])\n        fetched_layer.backward(layer, transcript, circuit_config)\n        print('----------------')\n\n    model['layers'] += transcript\n    model['inp_idxes'].append(circuit_config.label_tensor_idx)\n    model['out_idxes'] = [31]\n\n    packed = msgpack.packb(model, use_bin_type=True)\n    with open(\"./examples/train_graph/train.msgpack\", 'wb') as f:\n        f.write(packed)\n    print(model.keys())\n    return model\n\nmodel = produce_graph()\n\nprint(model.keys())\nmodel['tensors'] = \"\"\nprint(model['inp_idxes'], model['out_idxes'])\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "examples/mnist/data_to_npy.py",
        "content": "import tensorflow as tf\nimport numpy as np\nimport msgpack\nfrom tensorflow import keras\n\nmnist = tf.keras.datasets.mnist\n(images_train, labels_train), (images_test, labels_test) = mnist.load_data()\n\nx = images_test[0]\ny = labels_test[0]\nprint(y)\nx = x.flatten() / 255.\nx = x.astype(np.float32)\n\nprint(x.dtype, x.shape)\nnp.save('5.npy', x)\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "python/converter.py",
        "content": "import argparse\nimport ast\nfrom typing import Literal, Union\nimport tensorflow as tf\nimport numpy as np\nimport tflite\nimport msgpack\n\ndef get_shape(interpreter: tf.lite.Interpreter, tensor_idx):\n  if tensor_idx == -1:\n    return []\n  tensor = interpreter.get_tensor(tensor_idx)\n  return list(tensor.shape)\n\ndef handle_numpy_or_literal(inp: Union[np.ndarray, Literal[0]]):\n  if isinstance(inp, int):\n    return np.array([inp])\n  return inp\n\ndef get_inputs(op: tflite.Operator):\n  idxes = handle_numpy_or_literal(op.InputsAsNumpy())\n  idxes = idxes.tolist()\n  idxes = list(filter(lambda x: x != -1, idxes))\n  return idxes\n\nclass Converter:\n  def __init__(\n      self, model_path, scale_factor, k, num_cols, num_randoms, use_selectors, commit,\n      expose_output\n    ):\n    self.model_path = model_path\n    self.scale_factor = scale_factor\n    self.k = k\n    self.num_cols = num_cols\n    self.num_randoms = num_randoms\n    self.use_selectors = use_selectors\n    self.commit = commit\n    self.expose_output = expose_output\n\n    self.interpreter = tf.lite.Interpreter(\n      model_path=self.model_path,\n      experimental_preserve_all_tensors=True\n    )\n    self.interpreter.allocate_tensors()\n\n    with open(self.model_path, 'rb') as f:\n      buf = f.read()\n      self.model = tflite.Model.GetRootAsModel(buf, 0)\n    self.graph = self.model.Subgraphs(0)\n\n\n  def valid_activations(self):\n    return [\n      tflite.ActivationFunctionType.NONE,\n      tflite.ActivationFunctionType.RELU,\n      tflite.ActivationFunctionType.RELU6,\n    ]\n\n  def _convert_add(self, op: tflite.Operator, generated_tensors: set):\n    # Get params\n    op_opt = op.BuiltinOptions()\n    if op_opt is None:\n      raise RuntimeError('Add options is None')\n    opt = tflite.AddOptions()\n    opt.Init(op_opt.Bytes, op_opt.Pos)\n    params = [opt.FusedActivationFunction()]\n\n    # Get inputs\n    inputs = get_inputs(op)\n    print(generated_tensors)\n    print('Add inputs: ', inputs)\n    if len(inputs) != 2:\n      raise RuntimeError('Add must have 2 inputs')\n\n    # If both tensors are generated, do nothing\n    print(inputs[0] in generated_tensors, inputs[1] in generated_tensors)\n    if (inputs[0] in generated_tensors) and (inputs[1] in generated_tensors):\n      return ('Add', params)\n\n    nb_generated = (inputs[0] in generated_tensors) + (inputs[1] in generated_tensors)\n    if nb_generated != 1:\n      raise RuntimeError('Add must have 1 generated tensor')\n\n    # Check if there are any negative infinities\n    const_tensor = self.interpreter.get_tensor(inputs[0]) if inputs[0] not in generated_tensors else self.interpreter.get_tensor(inputs[1])\n    if np.any(const_tensor == -np.inf):\n      # Ensure that the constant tensor is all -inf and 0\n      if not np.all(np.logical_or(np.isneginf(const_tensor), const_tensor == 0)):\n        raise RuntimeError('Add constant tensor must be -inf and 0 only')\n      mask = (const_tensor == -np.inf).astype(np.int64)\n      params = [len(mask.shape)] + list(mask.shape)\n      params += mask.flatten().tolist()\n      return ('MaskNegInf', params)\n    else:\n      return ('Add', params)\n\n\n  def to_dict(self, start_layer, end_layer):\n    interpreter = self.interpreter\n    model = self.model\n    graph = self.graph\n    if graph is None:\n      raise RuntimeError('Graph is None')\n\n    input_details = interpreter.get_input_details()\n    output_details = interpreter.get_output_details()\n\n    for inp_detail in input_details:\n      inp = np.zeros(inp_detail['shape'], dtype=inp_detail['dtype'])\n      interpreter.set_tensor(inp_detail['index'], inp)\n    # for i, inp in enumerate(inps):\n    #   interpreter.set_tensor(input_details[i]['index'], inp)\n    interpreter.invoke()\n\n    # Get layers\n    generated_tensor_idxes = set()\n    for inp in input_details:\n      generated_tensor_idxes.add(inp['index'])\n\n    layers = []\n    keep_tensors = set()\n    adjusted_tensors = {}\n    for op_idx in range(graph.OperatorsLength()):\n      op = graph.Operators(op_idx)\n      if op is None:\n        raise RuntimeError('Operator is None')\n      model_opcode = model.OperatorCodes(op.OpcodeIndex())\n      if model_opcode is None:\n        raise RuntimeError('Operator code is None')\n      op_code = model_opcode.BuiltinCode()\n\n      # Skip generated tensors\n      for output in handle_numpy_or_literal(op.OutputsAsNumpy()):\n        generated_tensor_idxes.add(output)\n\n      if op_idx < start_layer:\n        continue\n      if op_idx > end_layer:\n        break\n\n      # Keep the input tensors\n      for input in handle_numpy_or_literal(op.InputsAsNumpy()):\n        keep_tensors.add(input)\n\n      # AvgPool2D\n      if op_code == tflite.BuiltinOperator.AVERAGE_POOL_2D:\n        layer_type = 'AveragePool2D'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('AvgPool2D options is None')\n        opt = tflite.Pool2DOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        params = [opt.FilterHeight(), opt.FilterWidth(), opt.StrideH(), opt.StrideW()]\n      elif op_code == tflite.BuiltinOperator.MAX_POOL_2D:\n        layer_type = 'MaxPool2D'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('MaxPool2D options is None')\n        opt = tflite.Pool2DOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.Padding() == tflite.Padding.SAME:\n          raise NotImplementedError('SAME padding is not supported')\n        if opt.FusedActivationFunction() != tflite.ActivationFunctionType.NONE:\n          raise NotImplementedError('Fused activation is not supported')\n        params = [opt.FilterHeight(), opt.FilterWidth(), opt.StrideH(), opt.StrideW()]\n      # FIXME: hack for Keras... not sure why this isn't being converted properly\n      elif op_code == tflite.BuiltinOperator.CUSTOM:\n        layer_type = 'Conv2D'\n        activation = 0\n        weights = self.interpreter.get_tensor(op.Inputs(1))\n        weights = np.transpose(weights, (3, 0, 1, 2))\n        weights = (weights * self.scale_factor).round().astype(np.int64)\n        adjusted_tensors[op.Inputs(1)] = weights\n        params = [0, 1, activation, 1, 1]\n      # Conv2D\n      elif op_code == tflite.BuiltinOperator.CONV_2D:\n        layer_type = 'Conv2D'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('Conv2D options is None')\n        opt = tflite.Conv2DOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.DilationHFactor() != 1 or opt.DilationWFactor() != 1:\n          raise NotImplementedError('Dilation is not supported')\n        if opt.FusedActivationFunction() not in self.valid_activations():\n          raise NotImplementedError('Unsupported activation function at layer {op_idx}')\n        # 0 is Conv2D\n        params = \\\n          [0] + \\\n          [opt.Padding()] + \\\n          [opt.FusedActivationFunction()] + \\\n          [opt.StrideH(), opt.StrideW()]\n      # DepthwiseConv2D\n      elif op_code == tflite.BuiltinOperator.DEPTHWISE_CONV_2D:\n        layer_type = 'Conv2D'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('DepthwiseConv2D options is None')\n        opt = tflite.DepthwiseConv2DOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.DilationHFactor() != 1 or opt.DilationWFactor() != 1:\n          raise NotImplementedError('Dilation is not supported')\n        if opt.FusedActivationFunction() not in self.valid_activations():\n          raise NotImplementedError('Unsupported activation function at layer {op_idx}')\n        # 1 is DepthwiseConv2D\n        params = \\\n          [1] + \\\n          [opt.Padding()] + \\\n          [opt.FusedActivationFunction()] + \\\n          [opt.StrideH(), opt.StrideW()]\n      # Fully connected\n      elif op_code == tflite.BuiltinOperator.FULLY_CONNECTED:\n        layer_type = 'FullyConnected'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('Fully connected options is None')\n        opt = tflite.FullyConnectedOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.FusedActivationFunction() not in self.valid_activations():\n          raise NotImplementedError(f'Unsupported activation function at layer {op_idx}')\n        params = [opt.FusedActivationFunction()]\n      elif op_code == tflite.BuiltinOperator.BATCH_MATMUL:\n        layer_type = 'BatchMatMul'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('BatchMatMul options is None')\n        opt = tflite.BatchMatMulOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.AdjX() is True: raise NotImplementedError('AdjX is not supported')\n        params = [int(opt.AdjX()), int(opt.AdjY())]\n\n      ## Arithmetic\n      # Add\n      elif op_code == tflite.BuiltinOperator.ADD:\n        layer_type, params = self._convert_add(op, generated_tensor_idxes)\n      # Mul\n      elif op_code == tflite.BuiltinOperator.MUL:\n        layer_type = 'Mul'\n        params = []\n      # Sub\n      elif op_code == tflite.BuiltinOperator.SUB:\n        sub_val = interpreter.get_tensor(op.Inputs(1))\n        # TODO: this is a bit of a hack\n        if np.any(np.isin(sub_val, 10000)):\n          layer_type = 'MaskNegInf'\n          mask = (sub_val == 10000).astype(np.int64)\n          params = [len(mask.shape)] + list(mask.shape)\n          params += mask.flatten().tolist()\n        else:\n          layer_type = 'Sub'\n          params = []\n      # Div\n      elif op_code == tflite.BuiltinOperator.DIV:\n        # Implement division as multiplication by the inverse\n        layer_type = 'Mul'\n        div_val = interpreter.get_tensor(op.Inputs(1))\n        if type(div_val) != np.float32: raise NotImplementedError('Only support one divisor')\n        adjusted_tensors[op.Inputs(1)] = np.array([(self.scale_factor / div_val).round().astype(np.int64)])\n        params = []\n      # Pad\n      elif op_code == tflite.BuiltinOperator.PAD:\n        layer_type = 'Pad'\n        tensor_idx = op.Inputs(1)\n        tensor = interpreter.get_tensor(tensor_idx).flatten().astype(np.int64)\n        params = tensor.tolist()\n      # Softmax\n      elif op_code == tflite.BuiltinOperator.SOFTMAX:\n        layer_type = 'Softmax'\n        # TODO: conditionally determine whether or not to subtract the max\n        # It should depend on the input to the softmax\n        if layers[-1]['layer_type'] == 'MaskNegInf':\n          params = layers[-1]['params']\n        elif layers[-2]['layer_type'] == 'MaskNegInf':\n          params = layers[-2]['params']\n          params = [params[0] - 1] + params[2:]\n        else:\n          params = []\n      # Mean\n      elif op_code == tflite.BuiltinOperator.MEAN:\n        layer_type = 'Mean'\n        inp_shape = interpreter.get_tensor(op.Inputs(0)).shape\n        mean_idxes = interpreter.get_tensor(op.Inputs(1)).flatten().astype(np.int64)\n        if len(mean_idxes) + 2 != len(inp_shape):\n          raise NotImplementedError(f'Only mean over all but one axis is supported: {op_idx}')\n        params = mean_idxes.tolist()\n      elif op_code == tflite.BuiltinOperator.SQUARE:\n        layer_type = 'Square'\n        params = []\n      # Squared difference\n      elif op_code == tflite.BuiltinOperator.SQUARED_DIFFERENCE:\n        layer_type = 'SquaredDifference'\n        params = []\n\n      # Pointwise\n      elif op_code == tflite.BuiltinOperator.RSQRT:\n        layer_type = 'Rsqrt'\n        params = []\n      elif op_code == tflite.BuiltinOperator.LOGISTIC:\n        layer_type = 'Logistic'\n        params = []\n      elif op_code == tflite.BuiltinOperator.TANH:\n        layer_type = 'Tanh'\n        params = []\n      elif op_code == tflite.BuiltinOperator.POW:\n        layer_type = 'Pow'\n        power = interpreter.get_tensor(op.Inputs(1)).flatten().astype(np.float32)\n        if power != 3.: raise NotImplementedError(f'Only support power 3')\n        power = power.round().astype(np.int64)\n        if len(power) != 1: raise NotImplementedError(f'Only scalar power is supported: {op_idx}')\n        params = power.tolist()\n\n      # The following are no-ops in the sense that they don't change the tensor\n      # However, we need to pass along the right tensors\n      # The param says which input to pass along\n      elif op_code == tflite.BuiltinOperator.SHAPE:\n        layer_type = 'Noop'\n        params = [0]\n      elif op_code == tflite.BuiltinOperator.GATHER:\n        layer_type = 'Noop'\n        params = [0]\n      elif op_code == tflite.BuiltinOperator.REDUCE_PROD:\n        # TODO: not sure if this is in general a no-op\n        layer_type = 'Noop'\n        params = [0]\n      elif op_code == tflite.BuiltinOperator.STRIDED_SLICE:\n        # FIXME: this is not in general a no-op\n        layer_type = 'Noop'\n        params = [0]\n      elif op_code == tflite.BuiltinOperator.BROADCAST_ARGS:\n        layer_type = 'Noop'\n        params = [0]\n      elif op_code == tflite.BuiltinOperator.BROADCAST_TO:\n        layer_type = 'Noop'\n        params = [0]\n\n      ## Shape\n      elif op_code == tflite.BuiltinOperator.RESHAPE:\n        layer_type = 'Reshape'\n        params = []\n      elif op_code == tflite.BuiltinOperator.TRANSPOSE:\n        layer_type = 'Transpose'\n        params = get_shape(interpreter, op.Inputs(0)) + interpreter.get_tensor(op.Inputs(1)).flatten().astype(np.int64).tolist()\n      elif op_code == tflite.BuiltinOperator.CONCATENATION:\n        # FIXME: This is not in general a no-op\n        layer_type = 'Concatenation'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('Concatenation options is None')\n        opt = tflite.ConcatenationOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        params = [opt.Axis()]\n      elif op_code == tflite.BuiltinOperator.PACK:\n        layer_type = 'Pack'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('Pack options is None')\n        opt = tflite.PackOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        params = [opt.Axis()]\n        if params[0] > 1: raise NotImplementedError(f'Only axis=0,1 supported at layer {op_idx}')\n      elif op_code == tflite.BuiltinOperator.SPLIT:\n        layer_type = 'Split'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('Split options is None')\n        opt = tflite.SplitOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        axis = interpreter.get_tensor(op.Inputs(0)).flatten().astype(np.int64)[0]\n        num_splits = opt.NumSplits()\n        inp = interpreter.get_tensor(op.Inputs(1))\n        if inp.shape[axis] % num_splits != 0:\n          raise NotImplementedError(f'Only equal splits supported at layer {op_idx}')\n        params = [int(axis), num_splits]\n      elif op_code == tflite.BuiltinOperator.SLICE:\n        layer_type = 'Slice'\n        begin = interpreter.get_tensor(op.Inputs(1)).flatten().astype(np.int64).tolist()\n        size = interpreter.get_tensor(op.Inputs(2)).flatten().astype(np.int64).tolist()\n        params = begin + size\n      elif op_code == tflite.BuiltinOperator.RESIZE_NEAREST_NEIGHBOR:\n        layer_type = 'ResizeNearestNeighbor'\n        op_opt = op.BuiltinOptions()\n        if op_opt is None:\n          raise RuntimeError('ResizeNearestNeighbor options is None')\n        opt = tflite.ResizeNearestNeighborOptions()\n        opt.Init(op_opt.Bytes, op_opt.Pos)\n        if opt.AlignCorners():\n          raise NotImplementedError(f'Align corners not supported at layer {op_idx}')\n        if not opt.HalfPixelCenters():\n          raise NotImplementedError(f'Half pixel centers not supported at layer {op_idx}')\n        # Can take the out shape directly from the tensor\n        params = [int(opt.AlignCorners()), int(opt.HalfPixelCenters())]\n\n      # Not implemented\n      else:\n        op_name = None\n        for attr in dir(tflite.BuiltinOperator):\n          if not attr.startswith('__'):\n            if getattr(tflite.BuiltinOperator, attr) == op_code:\n              op_name = attr\n        raise NotImplementedError('Unsupported operator at layer {}: {}, {}'.format(op_idx, op_code, op_name))\n\n      inp_idxes = get_inputs(op)\n      # FIXME: hack for testing\n      rsqrt_overflows = [99, 158, 194, 253, 289, 348]\n      if op_idx in rsqrt_overflows:\n        if op_code == tflite.BuiltinOperator.RSQRT:\n          mask = [0, 1]\n        else:\n          mask = []\n      else:\n        mask = []\n      layers.append({\n        'layer_type': layer_type,\n        'inp_idxes': inp_idxes,\n        'inp_shapes': [get_shape(interpreter, inp_idx) for inp_idx in inp_idxes],\n        'out_idxes': [op.Outputs(i) for i in range(op.OutputsLength())],\n        'out_shapes': [get_shape(interpreter, op.Outputs(i)) for i in range(op.OutputsLength())],\n        'params': params,\n        'mask': mask,\n      })\n    print(layers)\n    print()\n\n\n    # Get tensors\n    print('keep tensors:', keep_tensors)\n    tensors = []\n    for tensor_idx in range(graph.TensorsLength()):\n      if tensor_idx not in keep_tensors:\n        continue\n\n      tensor = graph.Tensors(tensor_idx)\n      if tensor is None:\n        raise NotImplementedError('Tensor is None')\n\n      if tensor_idx in generated_tensor_idxes:\n        print(f'skipping generated tensor: {format(tensor_idx)}, {tensor.Name()}')\n        continue\n\n      shape = []\n      for i in range(tensor.ShapeLength()):\n        shape.append(int(tensor.Shape(i)))\n      if shape == []:\n        shape = [1]\n\n      tensor_data = interpreter.get_tensor(tensor_idx)\n      if tensor.Type() == tflite.TensorType.FLOAT32:\n        tensor_data = (tensor_data * self.scale_factor).round().astype(np.int64)\n      elif tensor.Type() == tflite.TensorType.INT32:\n        tensor_data = tensor_data.astype(np.int64)\n      elif tensor.Type() == tflite.TensorType.INT64:\n        continue\n      else:\n        raise NotImplementedError('Unsupported tensor type: {}'.format(tensor.Type()))\n\n      if tensor_idx in adjusted_tensors:\n        tensor_data = adjusted_tensors[tensor_idx]\n        shape = tensor_data.shape\n\n      tensors.append({\n        'idx': tensor_idx,\n        'shape': shape,\n        'data': tensor_data.flatten().tolist(),\n      })\n      # print(tensor_idx, tensor.Type(), tensor.Name(), tensors[-1]['shape'])\n      # print(np.abs(tensor_data).max())\n\n    commit_before = []\n    commit_after = []\n    if self.commit:\n      input_tensors = [inp['index'] for inp in input_details]\n      weight_tensors = [tensor['idx'] for tensor in tensors if tensor['idx'] not in input_tensors]\n      commit_before = [weight_tensors, input_tensors]\n\n      output_tensors = [out['index'] for out in output_details]\n      commit_after = [output_tensors]\n\n    out_idxes = layers[-1]['out_idxes'] if self.expose_output else []\n    d = {\n      'global_sf': self.scale_factor,\n      'k': self.k,\n      'num_cols': self.num_cols,\n      'num_random': self.num_randoms,\n      'inp_idxes': [inp['index'] for inp in input_details],\n      # 'out_idxes': [out['index'] for out in output_details],\n      'out_idxes': out_idxes,\n      'layers': layers,\n      'tensors': tensors,\n      'use_selectors': self.use_selectors,\n      'commit_before': commit_before,\n      'commit_after': commit_after,\n    }\n    print()\n    print(d['layers'][-1])\n    # d['out_idxes'] = [14]\n    print(d.keys())\n    print(d['out_idxes'])\n    return d\n\n  def to_msgpack(self, start_layer, end_layer, use_selectors=True):\n    d = self.to_dict(start_layer, end_layer)\n    model_packed = msgpack.packb(d, use_bin_type=True)\n    d['tensors'] = []\n    config_packed = msgpack.packb(d, use_bin_type=True)\n    return model_packed, config_packed\n\n\ndef main():\n  parser = argparse.ArgumentParser()\n  parser.add_argument('--model', type=str, required=True)\n  parser.add_argument('--model_output', type=str, required=True)\n  parser.add_argument('--config_output', type=str, required=True)\n  parser.add_argument('--scale_factor', type=int, default=2**16)\n  parser.add_argument('--k', type=int, default=19)\n  parser.add_argument('--eta', type=float, default=0.001)\n  parser.add_argument('--num_cols', type=int, default=6)\n  parser.add_argument('--use_selectors', action=argparse.BooleanOptionalAction, required=False, default=True)\n  parser.add_argument('--commit', action=argparse.BooleanOptionalAction, required=False, default=False)\n  parser.add_argument('--expose_output', action=argparse.BooleanOptionalAction, required=False, default=True)\n  parser.add_argument('--start_layer', type=int, default=0)\n  parser.add_argument('--end_layer', type=int, default=10000)\n  parser.add_argument('--num_randoms', type=int, default=20001)\n  args = parser.parse_args()\n\n  converter = Converter(\n    args.model,\n    args.scale_factor,\n    args.k,\n    args.num_cols,\n    args.num_randoms,\n    args.use_selectors,\n    args.commit,\n    args.expose_output,\n  )\n\n  model_packed, config_packed = converter.to_msgpack(\n    start_layer=args.start_layer,\n    end_layer=args.end_layer,\n  )\n  if model_packed is None:\n    raise Exception('Failed to convert model')\n\n  with open(args.model_output, 'wb') as f:\n    f.write(model_packed)\n  with open(args.config_output, 'wb') as f:\n    f.write(config_packed)\n\nif __name__ == '__main__':\n  main()\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "python/input_converter.py",
        "content": "import argparse\nimport ast\nimport numpy as np\nimport msgpack\n\ndef main():\n  parser = argparse.ArgumentParser()\n  parser.add_argument('--model_config', type=str, required=True)\n  parser.add_argument('--inputs', type=str, required=True)\n  parser.add_argument('--output', type=str, required=True)\n  args = parser.parse_args()\n\n  inputs = args.inputs.split(',')\n  with open(args.model_config, 'rb') as f:\n    model_config = msgpack.unpackb(f.read())\n  input_idxes = model_config['inp_idxes']\n  scale_factor = model_config['global_sf']\n\n  # Get the input shapes from the layers\n  input_shapes = [[0] for _ in input_idxes]\n  for layer in model_config['layers']:\n    for layer_inp_idx, layer_shape in zip(layer['inp_idxes'], layer['inp_shapes']):\n      for index, inp_idx in enumerate(input_idxes):\n        if layer_inp_idx == inp_idx:\n          input_shapes[index] = layer_shape\n\n  tensors = []\n  for inp, shape, idx in zip(inputs, input_shapes, input_idxes):\n    tensor = np.load(inp).reshape(shape)\n    tensor = (tensor * scale_factor).round().astype(np.int64)\n    tensors.append({\n      'idx': idx,\n      'shape': shape,\n      'data': tensor.flatten().tolist(),\n    })\n\n  packed = msgpack.packb(tensors, use_bin_type=True)\n\n  with open(args.output, 'wb') as f:\n    f.write(packed)\n\n\nif __name__ == '__main__':\n  main()"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "python/training_converter.py",
        "content": "# A converter for training data\n# Performs the conversion npy -> msgpack\n# TODO: Ensure that training works with models that take in multiple input shapes\n# \n# Shortcut: \n# `python3 python/training_converter.py --input_shapes 7,7,320 --input_idxes 1,0 --output training_data/inputs.msgpack --labels_output training_data/labels.msgpack`\n#\n\nimport argparse\nimport ast\nimport numpy as np\nimport msgpack\nimport os\n\nNUM_LOADS = 1\nSF = 1 << 17\n\ndef main():\n  parser = argparse.ArgumentParser()\n  parser.add_argument('--input_shapes', type=str, required=True)\n  parser.add_argument('--output', type=str, required=True)\n\n  TRAINING_DIRECTORY = './testing/data/pre_last_conv/flowers/train'\n  args = parser.parse_args()\n\n  input_shapes = ast.literal_eval(args.input_shapes)\n\n  loaded = 0\n  tensors = []\n  num_classes = os.listdir(TRAINING_DIRECTORY)\n\n  first_file = \"0.npy\"\n  for file_name in os.listdir(TRAINING_DIRECTORY):\n    if loaded == NUM_LOADS:\n      break\n\n    label = int(first_file[:-4])\n    data_array = np.load(TRAINING_DIRECTORY + '/' + first_file)\n\n    input_shape = input_shapes\n\n    for idx in range(data_array.shape[0]):\n      print(SF)\n      print((np.vstack(data_array) * SF).round().astype(np.int64))\n      tensors.append({\n        'idx': 0,\n        'shape': input_shape,\n        'data': list(map(lambda x: int(x), list((data_array[idx] * SF).round().astype(np.int64).flatten()))),\n      })\n      # represent the label as a one hot encoding\n      one_hot = np.zeros(102)\n      one_hot[label] = SF\n      print(\"IMPORTANT LABEL\", label)\n      print(\"IMPORTANT LABEL\", data_array[idx].flatten()[:500])\n      # print(one_hot.shape())\n      tensors.append({\n        'idx': 11,\n        'shape': (1, 102),\n        'data': list(map(lambda x: int(x), one_hot)),\n      })\n      loaded += 1\n\n      if loaded == NUM_LOADS:\n        break\n\n  packed_inputs = msgpack.packb(tensors, use_bin_type=True)\n\n  # print(tensors)\n  with open(args.output, 'wb') as f:\n    f.write(packed_inputs)\n\nif __name__ == '__main__':\n  main()\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/bin/test_circuit.rs",
        "content": "use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr};\nuse zkml::{\n  model::ModelCircuit,\n  utils::{\n    helpers::get_public_values,\n    loader::{load_model_msgpack, ModelMsgpack},\n  },\n};\n\nfn main() {\n  let config_fname = std::env::args().nth(1).expect(\"config file path\");\n  let inp_fname = std::env::args().nth(2).expect(\"input file path\");\n\n  let config: ModelMsgpack = load_model_msgpack(&config_fname, &inp_fname);\n\n  let circuit = ModelCircuit::<Fr>::generate_from_file(&config_fname, &inp_fname);\n\n  let _prover = MockProver::run(config.k.try_into().unwrap(), &circuit, vec![vec![]]).unwrap();\n  let public_vals = get_public_values();\n\n  let prover = MockProver::run(config.k.try_into().unwrap(), &circuit, vec![public_vals]).unwrap();\n  assert_eq!(prover.verify(), Ok(()));\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/bin/time_circuit.rs",
        "content": "use halo2_proofs::halo2curves::{bn256::Fr, pasta::Fp};\nuse zkml::{\n  model::ModelCircuit,\n  utils::{proving_ipa::time_circuit_ipa, proving_kzg::time_circuit_kzg},\n};\n\nfn main() {\n  let config_fname = std::env::args().nth(1).expect(\"config file path\");\n  let inp_fname = std::env::args().nth(2).expect(\"input file path\");\n  let kzg_or_ipa = std::env::args().nth(3).expect(\"kzg or ipa\");\n\n  if kzg_or_ipa != \"kzg\" && kzg_or_ipa != \"ipa\" {\n    panic!(\"Must specify kzg or ipa\");\n  }\n\n  if kzg_or_ipa == \"kzg\" {\n    let circuit = ModelCircuit::<Fr>::generate_from_file(&config_fname, &inp_fname);\n    time_circuit_kzg(circuit);\n  } else {\n    let circuit = ModelCircuit::<Fp>::generate_from_file(&config_fname, &inp_fname);\n    time_circuit_ipa(circuit);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/bin/verify_circuit.rs",
        "content": "use halo2_proofs::halo2curves::bn256::Fr;\nuse zkml::{\n  model::ModelCircuit,\n  utils::{loader::load_config_msgpack, proving_kzg::verify_circuit_kzg},\n};\n\nfn main() {\n  let config_fname = std::env::args().nth(1).expect(\"config file path\");\n  let vkey_fname = std::env::args().nth(2).expect(\"verification key file path\");\n  let proof_fname = std::env::args().nth(3).expect(\"proof file path\");\n  let public_vals_fname = std::env::args().nth(4).expect(\"public values file path\");\n  let kzg_or_ipa = std::env::args().nth(5).expect(\"kzg or ipa\");\n\n  if kzg_or_ipa != \"kzg\" && kzg_or_ipa != \"ipa\" {\n    panic!(\"Must specify kzg or ipa\");\n  }\n\n  if kzg_or_ipa == \"kzg\" {\n    let config = load_config_msgpack(&config_fname);\n    let circuit = ModelCircuit::<Fr>::generate_from_msgpack(config, false);\n    println!(\"Loaded configuration\");\n    verify_circuit_kzg(circuit, &vkey_fname, &proof_fname, &public_vals_fname);\n  } else {\n    // Serialization of the verification key doesn't seem to be supported for IPA\n    panic!(\"Not implemented\");\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/bin/verify_wav.rs",
        "content": "use std::fs::File;\n\nuse halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr};\nuse zkml::{\n  model::ModelCircuit,\n  utils::{\n    helpers::get_public_values,\n    loader::{load_config_msgpack, ModelMsgpack, TensorMsgpack},\n  },\n};\n\nfn main() {\n  let config_fname = std::env::args().nth(1).expect(\"config file path\");\n  let wav_fname = std::env::args().nth(2).expect(\"wav file path\");\n\n  let mut wav_file = File::open(wav_fname).unwrap();\n  let (_header, data) = wav::read(&mut wav_file).unwrap();\n  let data = match data {\n    wav::BitDepth::Sixteen(data) => data,\n    _ => panic!(\"Unsupported bit depth\"),\n  };\n  let data: Vec<i64> = data.iter().map(|x| *x as i64).collect();\n\n  let base_config = load_config_msgpack(&config_fname);\n\n  let config = ModelMsgpack {\n    tensors: vec![TensorMsgpack {\n      idx: 0,\n      shape: vec![1, data.len().try_into().unwrap()],\n      data: data,\n    }],\n    inp_idxes: vec![0],\n    out_idxes: vec![],\n    layers: vec![],\n    commit_before: Some(vec![]),\n    commit_after: Some(vec![vec![0]]),\n    ..base_config\n  };\n  println!(\"Config: {:?}\", config);\n  let k = config.k;\n  let circuit = ModelCircuit::<Fr>::generate_from_msgpack(config, false);\n\n  let _prover = MockProver::run(k.try_into().unwrap(), &circuit, vec![vec![]]).unwrap();\n  let public_vals: Vec<Fr> = get_public_values();\n  println!(\"Public values: {:?}\", public_vals);\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/commitments.rs",
        "content": "pub mod commit;\npub mod packer;\npub mod poseidon_commit;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/commitments/commit.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\n\nuse crate::{gadgets::gadget::GadgetConfig, layers::layer::CellRc};\n\npub trait Commit<F: PrimeField> {\n  fn commit(\n    &self,\n    layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    constants: &HashMap<i64, CellRc<F>>,\n    values: &Vec<CellRc<F>>,\n    blinding: CellRc<F>,\n  ) -> Result<Vec<CellRc<F>>, Error>;\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/commitments/packer.rs",
        "content": "use std::{\n  cmp::{max, min},\n  collections::{BTreeMap, HashMap},\n  marker::PhantomData,\n  rc::Rc,\n};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::layer::{AssignedTensor, CellRc},\n};\n\nconst NUM_BITS_PER_FIELD_ELEM: usize = 254;\n\npub struct PackerConfig<F: PrimeField> {\n  pub num_bits_per_elem: usize,\n  pub num_elem_per_packed: usize,\n  pub num_packed_per_row: usize,\n  pub exponents: Vec<F>,\n  _marker: PhantomData<F>,\n}\n\npub struct PackerChip<F: PrimeField> {\n  pub config: PackerConfig<F>,\n}\n\nimpl<F: PrimeField> PackerChip<F> {\n  pub fn get_exponents(num_bits_per_elem: usize, num_exponents: usize) -> Vec<F> {\n    let mul_val = F::from(1 << num_bits_per_elem);\n    let mut exponents = vec![F::ONE];\n    for _ in 1..num_exponents {\n      exponents.push(exponents[exponents.len() - 1] * mul_val);\n    }\n    exponents\n  }\n\n  pub fn construct(num_bits_per_elem: usize, gadget_config: &GadgetConfig) -> PackerConfig<F> {\n    let columns = &gadget_config.columns;\n\n    let num_elem_per_packed = if NUM_BITS_PER_FIELD_ELEM / num_bits_per_elem > columns.len() - 1 {\n      columns.len() - 1\n    } else {\n      // TODO: for many columns, pack many in a single row\n      NUM_BITS_PER_FIELD_ELEM / num_bits_per_elem\n    };\n    println!(\"column len: {}\", columns.len());\n    println!(\"num_bits_per_elem: {}\", num_bits_per_elem);\n    println!(\"NUM_BITS_PER_FIELD_ELEM: {}\", NUM_BITS_PER_FIELD_ELEM);\n    println!(\"num_elem_per_packed: {}\", num_elem_per_packed);\n\n    let num_packed_per_row = max(\n      1,\n      columns.len() / (num_elem_per_packed * (num_bits_per_elem + 1)),\n    );\n    println!(\"num_packed_per_row: {}\", num_packed_per_row);\n\n    let exponents = Self::get_exponents(num_bits_per_elem, num_elem_per_packed);\n\n    let config = PackerConfig {\n      num_bits_per_elem,\n      num_elem_per_packed,\n      num_packed_per_row,\n      exponents,\n      _marker: PhantomData,\n    };\n    config\n  }\n\n  pub fn configure(\n    meta: &mut ConstraintSystem<F>,\n    packer_config: PackerConfig<F>,\n    gadget_config: GadgetConfig,\n  ) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let columns = gadget_config.columns;\n    let lookup = gadget_config.tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    let exponents = &packer_config.exponents;\n\n    let num_bits_per_elem = packer_config.num_bits_per_elem;\n    let shift_val = 1 << (num_bits_per_elem - 1);\n    let shift_val = Expression::Constant(F::from(shift_val as u64));\n\n    meta.create_gate(\"packer\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..packer_config.num_packed_per_row {\n        let offset = i * (packer_config.num_elem_per_packed + 1);\n        let inps = columns[offset..offset + packer_config.num_elem_per_packed]\n          .iter()\n          .map(|col| meta.query_advice(*col, Rotation::cur()))\n          .collect::<Vec<_>>();\n\n        let outp = meta.query_advice(\n          columns[offset + packer_config.num_elem_per_packed],\n          Rotation::cur(),\n        );\n\n        let res = inps\n          .into_iter()\n          .zip(exponents.iter())\n          .map(|(inp, exp)| (inp + shift_val.clone()) * (*exp))\n          .fold(Expression::Constant(F::ZERO), |acc, prod| acc + prod);\n        constraints.push(s.clone() * (res - outp));\n        // constraints.push(s.clone() * Expression::Constant(F::zero()));\n      }\n\n      constraints\n    });\n\n    // Ensure that the weights/inputs are in the correct range\n    for i in 0..packer_config.num_packed_per_row {\n      let offset = i * (packer_config.num_elem_per_packed + 1);\n      for j in 0..packer_config.num_elem_per_packed {\n        meta.lookup(\"packer lookup\", |meta| {\n          let s = meta.query_selector(selector);\n          let inp = meta.query_advice(columns[offset + j], Rotation::cur());\n\n          vec![(s * (inp + shift_val.clone()), lookup)]\n        });\n      }\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::Packer, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n\n  pub fn copy_and_pack_row(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    cells: Vec<CellRc<F>>,\n    zero: &AssignedCell<F, F>,\n  ) -> Result<Vec<CellRc<F>>, Error> {\n    let columns = &gadget_config.columns;\n    let selector = gadget_config.selectors.get(&GadgetType::Packer).unwrap()[0];\n\n    let num_bits_per_elem = gadget_config.num_bits_per_elem;\n    let shift_val = 1 << (num_bits_per_elem - 1);\n    let shift_val = F::from(shift_val as u64);\n\n    let outp = layouter.assign_region(\n      || \"pack row\",\n      |mut region| {\n        if gadget_config.use_selectors {\n          selector.enable(&mut region, 0)?;\n        }\n\n        let mut packed = vec![];\n        for i in 0..self.config.num_packed_per_row {\n          let val_offset = i * self.config.num_elem_per_packed;\n          let col_offset = i * (self.config.num_elem_per_packed + 1);\n\n          let mut vals = cells\n            [val_offset..min(val_offset + self.config.num_elem_per_packed, cells.len())]\n            .iter()\n            .enumerate()\n            .map(|(i, x)| {\n              x.copy_advice(|| \"\", &mut region, columns[col_offset + i], 0)\n                .unwrap();\n              x.value().copied()\n            })\n            .collect::<Vec<_>>();\n\n          let zero_copied = (cells.len()..self.config.num_elem_per_packed)\n            .map(|i| {\n              zero\n                .copy_advice(|| \"\", &mut region, columns[col_offset + i], 0)\n                .unwrap();\n              zero.value().copied()\n            })\n            .collect::<Vec<_>>();\n          vals.extend(zero_copied);\n\n          let res = vals.iter().zip(self.config.exponents.iter()).fold(\n            Value::known(F::ZERO),\n            |acc, (inp, exp)| {\n              let res = acc + (*inp + Value::known(shift_val)) * Value::known(*exp);\n              res\n            },\n          );\n\n          let outp = region.assign_advice(\n            || \"\",\n            columns[col_offset + self.config.num_elem_per_packed],\n            0,\n            || res,\n          )?;\n          packed.push(Rc::new(outp));\n        }\n\n        Ok(packed)\n      },\n    )?;\n\n    Ok(outp)\n  }\n\n  pub fn assign_and_pack_row(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    values: Vec<&F>,\n    zero: &AssignedCell<F, F>,\n  ) -> Result<(Vec<CellRc<F>>, Vec<CellRc<F>>), Error> {\n    let columns = &gadget_config.columns;\n    let selector = gadget_config.selectors.get(&GadgetType::Packer).unwrap()[0];\n\n    let num_bits_per_elem = gadget_config.num_bits_per_elem;\n    let shift_val = 1 << (num_bits_per_elem - 1);\n    let shift_val = F::from(shift_val as u64);\n\n    let outp = layouter.assign_region(\n      || \"pack row\",\n      |mut region| {\n        if gadget_config.use_selectors {\n          selector.enable(&mut region, 0)?;\n        }\n\n        let mut packed = vec![];\n        let mut assigned = vec![];\n        for i in 0..self.config.num_packed_per_row {\n          let val_offset = i * self.config.num_elem_per_packed;\n          let col_offset = i * (self.config.num_elem_per_packed + 1);\n\n          let mut values = values\n            [val_offset..min(val_offset + self.config.num_elem_per_packed, values.len())]\n            .iter()\n            .map(|x| **x)\n            .collect::<Vec<_>>();\n          let vals = values\n            .iter()\n            .enumerate()\n            .map(|(i, x)| {\n              let tmp = region\n                .assign_advice(|| \"\", columns[col_offset + i], 0, || Value::known(*x))\n                .unwrap();\n              Rc::new(tmp)\n            })\n            .collect::<Vec<_>>();\n          assigned.extend(vals);\n\n          let zero_vals = (values.len()..self.config.num_elem_per_packed)\n            .map(|i| {\n              zero\n                .copy_advice(|| \"\", &mut region, columns[col_offset + i], 0)\n                .unwrap();\n              F::ZERO\n            })\n            .collect::<Vec<_>>();\n          values.extend(zero_vals);\n\n          let res =\n            values\n              .iter()\n              .zip(self.config.exponents.iter())\n              .fold(F::ZERO, |acc, (inp, exp)| {\n                let res = acc + (*inp + shift_val) * (*exp);\n                res\n              });\n\n          let outp = region.assign_advice(\n            || \"\",\n            columns[col_offset + self.config.num_elem_per_packed],\n            0,\n            || Value::known(res),\n          )?;\n          packed.push(Rc::new(outp));\n        }\n\n        Ok((packed, assigned))\n      },\n    )?;\n\n    Ok(outp)\n  }\n\n  pub fn assign_and_pack(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    constants: &HashMap<i64, CellRc<F>>,\n    tensors: &BTreeMap<i64, Array<F, IxDyn>>,\n  ) -> Result<(BTreeMap<i64, AssignedTensor<F>>, Vec<CellRc<F>>), Error> {\n    let mut values = vec![];\n    for (_, tensor) in tensors {\n      for value in tensor.iter() {\n        values.push(value);\n      }\n    }\n\n    let mut packed = vec![];\n    let mut assigned = vec![];\n    let zero = constants.get(&0).unwrap().clone();\n\n    let num_elems_per_row = self.config.num_packed_per_row * self.config.num_elem_per_packed;\n    for i in 0..(values.len().div_ceil(num_elems_per_row)) {\n      let row =\n        values[i * num_elems_per_row..min((i + 1) * num_elems_per_row, values.len())].to_vec();\n      let (row_packed, row_assigned) = self\n        .assign_and_pack_row(\n          layouter.namespace(|| \"pack row\"),\n          gadget_config.clone(),\n          row,\n          zero.as_ref(),\n        )\n        .unwrap();\n      packed.extend(row_packed);\n      assigned.extend(row_assigned);\n    }\n\n    let mut assigned_tensors = BTreeMap::new();\n    let mut start_idx = 0;\n    for (tensor_id, tensor) in tensors {\n      let num_el = tensor.len();\n      let v = assigned[start_idx..start_idx + num_el].to_vec();\n      let new_tensor = Array::from_shape_vec(tensor.raw_dim(), v).unwrap();\n      assigned_tensors.insert(*tensor_id, new_tensor);\n      start_idx += num_el;\n    }\n\n    Ok((assigned_tensors, packed))\n  }\n\n  pub fn copy_and_pack(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    constants: &HashMap<i64, CellRc<F>>,\n    tensors: &BTreeMap<i64, AssignedTensor<F>>,\n  ) -> Result<Vec<CellRc<F>>, Error> {\n    let mut values = vec![];\n    for (_, tensor) in tensors {\n      for value in tensor.iter() {\n        values.push(value.clone());\n      }\n    }\n\n    let mut packed = vec![];\n    let zero = constants.get(&0).unwrap().clone();\n\n    let num_elems_per_row = self.config.num_packed_per_row * self.config.num_elem_per_packed;\n    for i in 0..(values.len().div_ceil(num_elems_per_row)) {\n      let row =\n        values[i * num_elems_per_row..min((i + 1) * num_elems_per_row, values.len())].to_vec();\n      let row_packed = self\n        .copy_and_pack_row(\n          layouter.namespace(|| \"pack row\"),\n          gadget_config.clone(),\n          row,\n          zero.as_ref(),\n        )\n        .unwrap();\n      packed.extend(row_packed);\n    }\n\n    Ok(packed)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/commitments/poseidon_commit.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_gadgets::poseidon::{\n  primitives::{generate_constants, Absorbing, ConstantLength, Domain, Mds, Spec},\n  PaddedWord, PoseidonSpongeInstructions, Pow5Chip, Pow5Config, Sponge,\n};\nuse halo2_proofs::{\n  circuit::Layouter,\n  halo2curves::ff::{FromUniformBytes, PrimeField},\n  plonk::{Advice, Column, ConstraintSystem, Error},\n};\n\nuse crate::{gadgets::gadget::GadgetConfig, layers::layer::CellRc};\n\nuse super::commit::Commit;\n\npub const WIDTH: usize = 3;\npub const RATE: usize = 2;\npub const L: usize = 8 - WIDTH - 1;\n\n#[derive(Clone, Debug)]\n\npub struct PoseidonCommitChip<\n  F: PrimeField + Ord + FromUniformBytes<64>,\n  const WIDTH: usize,\n  const RATE: usize,\n  const L: usize,\n> {\n  pub poseidon_config: Pow5Config<F, WIDTH, RATE>,\n}\n\n#[derive(Debug)]\npub struct P128Pow5T3Gen<F: PrimeField, const SECURE_MDS: usize>(PhantomData<F>);\n\nimpl<F: PrimeField, const SECURE_MDS: usize> P128Pow5T3Gen<F, SECURE_MDS> {\n  pub fn new() -> Self {\n    P128Pow5T3Gen(PhantomData::default())\n  }\n}\n\nimpl<F: FromUniformBytes<64> + Ord, const SECURE_MDS: usize> Spec<F, 3, 2>\n  for P128Pow5T3Gen<F, SECURE_MDS>\n{\n  fn full_rounds() -> usize {\n    8\n  }\n\n  fn partial_rounds() -> usize {\n    56\n  }\n\n  fn sbox(val: F) -> F {\n    val.pow_vartime([5])\n  }\n\n  fn secure_mds() -> usize {\n    SECURE_MDS\n  }\n\n  fn constants() -> (Vec<[F; 3]>, Mds<F, 3>, Mds<F, 3>) {\n    generate_constants::<_, Self, 3, 2>()\n  }\n}\n\n/// A Poseidon hash function, built around a sponge.\n#[derive(Debug)]\npub struct MyHash<\n  F: PrimeField,\n  PoseidonChip: PoseidonSpongeInstructions<F, S, D, T, RATE>,\n  S: Spec<F, T, RATE>,\n  D: Domain<F, RATE>,\n  const T: usize,\n  const RATE: usize,\n> {\n  pub sponge: Sponge<F, PoseidonChip, S, Absorbing<PaddedWord<F>, RATE>, D, T, RATE>,\n}\n\nimpl<F: PrimeField + Ord + FromUniformBytes<64>> PoseidonCommitChip<F, WIDTH, RATE, L> {\n  pub fn configure(\n    meta: &mut ConstraintSystem<F>,\n    // TODO: ??\n    _input: [Column<Advice>; L],\n    state: [Column<Advice>; WIDTH],\n    partial_sbox: Column<Advice>,\n  ) -> PoseidonCommitChip<F, WIDTH, RATE, L> {\n    let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n    let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>();\n\n    meta.enable_constant(rc_b[0]);\n\n    PoseidonCommitChip {\n      poseidon_config: Pow5Chip::configure::<P128Pow5T3Gen<F, 0>>(\n        meta,\n        state.try_into().unwrap(),\n        partial_sbox,\n        rc_a.try_into().unwrap(),\n        rc_b.try_into().unwrap(),\n      ),\n    }\n  }\n}\n\nimpl<F: PrimeField + Ord + FromUniformBytes<64>> Commit<F>\n  for PoseidonCommitChip<F, WIDTH, RATE, L>\n{\n  fn commit(\n    &self,\n    mut layouter: impl Layouter<F>,\n    _gadget_config: Rc<GadgetConfig>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    values: &Vec<CellRc<F>>,\n    blinding: CellRc<F>,\n  ) -> Result<Vec<CellRc<F>>, Error> {\n    let chip = Pow5Chip::construct(self.poseidon_config.clone());\n    let mut hasher: MyHash<F, Pow5Chip<F, 3, 2>, P128Pow5T3Gen<F, 0>, ConstantLength<L>, 3, 2> =\n      Sponge::new(chip, layouter.namespace(|| \"sponge\"))\n        .map(|sponge| MyHash { sponge })\n        .unwrap();\n\n    let mut new_vals = values\n      .iter()\n      .map(|x| x.clone())\n      .chain(vec![blinding.clone()])\n      .collect::<Vec<_>>();\n    while new_vals.len() % L != 0 {\n      new_vals.push(blinding.clone());\n    }\n    for (i, value) in new_vals\n      .iter()\n      .map(|x| PaddedWord::Message((**x).clone()))\n      .chain(<ConstantLength<L> as Domain<F, RATE>>::padding(L).map(PaddedWord::Padding))\n      .enumerate()\n    {\n      hasher\n        .sponge\n        .absorb(layouter.namespace(|| format!(\"absorb {}\", i)), value)\n        .unwrap();\n    }\n    let outp = hasher\n      .sponge\n      .finish_absorbing(layouter.namespace(|| \"finish absorbing\"))\n      .unwrap()\n      .squeeze(layouter.namespace(|| \"squeeze\"))\n      .unwrap();\n    let outp = Rc::new(outp);\n\n    Ok(vec![outp])\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets.rs",
        "content": "pub mod add_pairs;\npub mod adder;\npub mod bias_div_floor_relu6;\npub mod bias_div_round_relu6;\npub mod dot_prod;\npub mod gadget;\npub mod input_lookup;\npub mod max;\npub mod mul_pairs;\npub mod sqrt_big;\npub mod square;\npub mod squared_diff;\npub mod sub_pairs;\npub mod update;\npub mod var_div;\npub mod var_div_big;\npub mod var_div_big3;\n\n// Generics\npub mod nonlinear;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/add_pairs.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype AddPairsConfig = GadgetConfig;\n\npub struct AddPairsChip<F: PrimeField> {\n  config: Rc<AddPairsConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> AddPairsChip<F> {\n  pub fn construct(config: Rc<AddPairsConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"add pair\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let res = inp1 + inp2;\n        constraints.append(&mut vec![s.clone() * (res - outp)])\n      }\n\n      constraints\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::AddPairs, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for AddPairsChip<F> {\n  fn name(&self) -> String {\n    \"add pairs chip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let inp1 = &vec_inputs[0];\n    let inp2 = &vec_inputs[1];\n    assert_eq!(inp1.len(), inp2.len());\n\n    let columns = &self.config.columns;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::AddPairs).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outps = vec![];\n    for i in 0..inp1.len() {\n      let offset = i * self.num_cols_per_op();\n      let inp1 = inp1[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let inp2 = inp2[i].copy_advice(|| \"\", region, columns[offset + 1], row_offset)?;\n      let outp = inp1.value().map(|x: &F| x.to_owned()) + inp2.value().map(|x: &F| x.to_owned());\n\n      let outp = region.assign_advice(|| \"\", columns[offset + 2], row_offset, || outp)?;\n      outps.push(outp);\n    }\n    Ok(outps)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp1 = vec_inputs[0].clone();\n    let mut inp2 = vec_inputs[1].clone();\n    let initial_len = inp1.len();\n    while inp1.len() % self.num_inputs_per_row() != 0 {\n      inp1.push(zero);\n      inp2.push(zero);\n    }\n\n    let vec_inputs = vec![inp1, inp2];\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/adder.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype AdderConfig = GadgetConfig;\n\npub struct AdderChip<F: PrimeField> {\n  config: Rc<AdderConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> AdderChip<F> {\n  pub fn construct(config: Rc<AdderConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"adder gate\", |meta| {\n      let s = meta.query_selector(selector);\n      let gate_inp = columns[0..columns.len() - 1]\n        .iter()\n        .map(|col| meta.query_advice(*col, Rotation::cur()))\n        .collect::<Vec<_>>();\n      let gate_output = meta.query_advice(*columns.last().unwrap(), Rotation::cur());\n\n      let res = gate_inp\n        .iter()\n        .fold(Expression::Constant(F::ZERO), |a, b| a + b.clone());\n\n      vec![s * (res - gate_output)]\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::Adder, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\n// NOTE: The forward pass of the adder adds _everything_ into one cell\nimpl<F: PrimeField> Gadget<F> for AdderChip<F> {\n  fn name(&self) -> String {\n    \"adder\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    self.config.columns.len()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() - 1\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    1\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(vec_inputs.len(), 1);\n    let inp = &vec_inputs[0];\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::Adder).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    inp\n      .iter()\n      .enumerate()\n      .map(|(i, cell)| cell.copy_advice(|| \"\", region, self.config.columns[i], row_offset))\n      .collect::<Result<Vec<_>, _>>()?;\n\n    let e = inp.iter().fold(Value::known(F::ZERO), |a, b| {\n      a + b.value().map(|x: &F| x.to_owned())\n    });\n    let res = region.assign_advice(\n      || \"\",\n      *self.config.columns.last().unwrap(),\n      row_offset,\n      || e,\n    )?;\n\n    Ok(vec![res])\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(single_inputs.len(), 1);\n\n    let mut inputs = vec_inputs[0].clone();\n    let zero = single_inputs[0].clone();\n\n    while inputs.len() % self.num_inputs_per_row() != 0 {\n      inputs.push(&zero);\n    }\n\n    let mut outputs = self.op_aligned_rows(\n      layouter.namespace(|| \"adder forward\"),\n      &vec![inputs],\n      single_inputs,\n    )?;\n    while outputs.len() != 1 {\n      while outputs.len() % self.num_inputs_per_row() != 0 {\n        outputs.push(zero.clone());\n      }\n      let tmp = outputs.iter().map(|x| x).collect::<Vec<_>>();\n      outputs = self.op_aligned_rows(\n        layouter.namespace(|| \"adder forward\"),\n        &vec![tmp],\n        single_inputs,\n      )?;\n    }\n\n    Ok(outputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/bias_div_floor_relu6.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::convert_to_u64;\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype BiasDivFloorRelu6Config = GadgetConfig;\n\nconst SHIFT_MIN_VAL: i64 = -(1 << 30);\n\npub struct BiasDivFloorRelu6Chip<F: PrimeField> {\n  config: BiasDivFloorRelu6Config,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> BiasDivFloorRelu6Chip<F> {\n  pub fn construct(config: BiasDivFloorRelu6Config) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn get_map(scale_factor: u64, num_rows: i64, div_outp_min_val: i64) -> HashMap<i64, i64> {\n    let div_val = scale_factor;\n    let div_outp_min_val = div_outp_min_val;\n\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + div_outp_min_val;\n      let val = shifted.clamp(0, 6 * div_val as i64);\n      map.insert(i as i64, val);\n    }\n    map\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    5\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let sf = Expression::Constant(F::from(gadget_config.scale_factor));\n    let columns = gadget_config.columns;\n\n    let mod_lookup = meta.lookup_table_column();\n    let relu_lookup = meta.lookup_table_column();\n    let div_lookup = meta.lookup_table_column();\n\n    meta.create_gate(\"bias_mul\", |meta| {\n      let s = meta.query_selector(selector);\n\n      let mut constraints = vec![];\n      for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = op_idx * Self::num_cols_per_op();\n        let inp = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let bias = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let div_res = meta.query_advice(columns[offset + 2], Rotation::cur());\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        constraints.push(s.clone() * (inp - (sf.clone() * (div_res - bias) + mod_res)));\n      }\n\n      constraints\n    });\n\n    for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n      let offset = op_idx * Self::num_cols_per_op();\n      meta.lookup(\"bias_div_relu6 lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        // Constrains that the modulus \\in [0, DIV_VAL)\n        vec![(s.clone() * mod_res.clone(), mod_lookup)]\n      });\n      meta.lookup(\"bias_div_relu6 lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let div = meta.query_advice(columns[offset + 2], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 4], Rotation::cur());\n        let div_outp_min_val = Expression::Constant(F::from((-SHIFT_MIN_VAL) as u64));\n\n        // Constrains that output \\in [0, 6 * SF]\n        vec![\n          (s.clone() * outp, relu_lookup),\n          (s * (div + div_outp_min_val), div_lookup),\n        ]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::BiasDivFloorRelu6, vec![selector]);\n\n    let mut tables = gadget_config.tables;\n    tables.insert(\n      GadgetType::BiasDivFloorRelu6,\n      vec![mod_lookup, relu_lookup, div_lookup],\n    );\n\n    let mut maps = gadget_config.maps;\n    let relu_map = Self::get_map(\n      gadget_config.scale_factor,\n      gadget_config.num_rows as i64,\n      gadget_config.div_outp_min_val,\n    );\n    maps.insert(GadgetType::BiasDivFloorRelu6, vec![relu_map]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      tables,\n      maps,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for BiasDivFloorRelu6Chip<F> {\n  fn name(&self) -> String {\n    \"BiasDivRelu6\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let div_val = self.config.scale_factor as i64;\n\n    let div_outp_min_val_i64 = -self.config.div_outp_min_val;\n\n    let div_inp_min_val_pos_i64 = -SHIFT_MIN_VAL;\n    let div_inp_min_val_pos = F::from(div_inp_min_val_pos_i64 as u64);\n\n    let inp = &vec_inputs[0];\n    let bias = &vec_inputs[1];\n    assert_eq!(inp.len(), bias.len());\n    assert_eq!(inp.len() % self.num_inputs_per_row(), 0);\n\n    let relu_map = &self\n      .config\n      .maps\n      .get(&GadgetType::BiasDivFloorRelu6)\n      .unwrap()[0];\n\n    if self.config.use_selectors {\n      let selector = self\n        .config\n        .selectors\n        .get(&GadgetType::BiasDivFloorRelu6)\n        .unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outp_cells = vec![];\n    for (i, (inp, bias)) in inp.iter().zip(bias.iter()).enumerate() {\n      let offset = i * self.num_cols_per_op();\n\n      let inp_f = inp.value().map(|x: &F| x.to_owned());\n      let bias_f = bias.value().map(|x: &F| {\n        let a = *x + div_inp_min_val_pos;\n        let a = convert_to_u64(&a) as i64 - div_inp_min_val_pos_i64;\n        a\n      });\n      let div_mod_res = inp_f.map(|x: F| {\n        let x_pos = x + div_inp_min_val_pos;\n        let inp = convert_to_u64(&x_pos);\n        // println!(\"inp: {:?}, bias: {:?}, x_pos: {:?}\", inp, bias, x_pos);\n        let div_res = inp as i64 / div_val - (div_inp_min_val_pos_i64 / div_val);\n        let mod_res = inp as i64 % div_val;\n        // println!(\"div_res: {:?}, mod_res: {:?}\", div_res, mod_res);\n        (div_res, mod_res)\n      });\n      let div_res = div_mod_res.map(|x: (i64, i64)| x.0) + bias_f;\n      let mod_res = div_mod_res.map(|x: (i64, i64)| x.1);\n\n      let outp = div_res.map(|x: i64| {\n        let mut x_pos = x - div_outp_min_val_i64;\n        if !relu_map.contains_key(&(x_pos)) {\n          println!(\"x: {}, x_pos: {}\", x, x_pos);\n          x_pos = 0;\n        }\n        let outp_val = relu_map.get(&(x_pos)).unwrap();\n        // println!(\"x: {}, x_pos: {}, outp_val: {}\", x, x_pos, outp_val);\n        F::from(*outp_val as u64)\n      });\n\n      // Assign inp, bias\n      inp.copy_advice(|| \"\", region, self.config.columns[offset + 0], row_offset)?;\n      bias.copy_advice(|| \"\", region, self.config.columns[offset + 1], row_offset)?;\n\n      // Assign div_res, mod_res\n      let div_res_cell = region\n        .assign_advice(\n          || \"div_res\",\n          self.config.columns[offset + 2],\n          row_offset,\n          || {\n            div_res.map(|x: i64| {\n              F::from((x - div_outp_min_val_i64) as u64) - F::from(-div_outp_min_val_i64 as u64)\n            })\n          },\n        )\n        .unwrap();\n      let _mod_res_cell = region\n        .assign_advice(\n          || \"mod_res\",\n          self.config.columns[offset + 3],\n          row_offset,\n          || mod_res.map(|x: i64| F::from(x as u64)),\n        )\n        .unwrap();\n\n      let outp_cell = region\n        .assign_advice(\n          || \"outp\",\n          self.config.columns[offset + 4],\n          row_offset,\n          || outp.map(|x: F| x.to_owned()),\n        )\n        .unwrap();\n\n      // outp_cells.push((outp_cell, div_res_cell));\n      outp_cells.push(outp_cell);\n      outp_cells.push(div_res_cell);\n    }\n\n    Ok(outp_cells)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inps = vec_inputs[0].clone();\n    let mut biases = vec_inputs[1].clone();\n\n    // Needed to pad: bias - bias = 0\n    let default = biases[0].clone();\n    while inps.len() % self.num_inputs_per_row() != 0 {\n      inps.push(&default);\n      biases.push(&default);\n    }\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| \"bias_div_relu6\"),\n      &vec![inps, biases],\n      single_inputs,\n    )?;\n    Ok(res)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/bias_div_round_relu6.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::convert_to_u64;\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype BiasDivRoundRelu6Config = GadgetConfig;\n\nconst NUM_COLS_PER_OP: usize = 5;\n\npub struct BiasDivRoundRelu6Chip<F: PrimeField> {\n  config: Rc<BiasDivRoundRelu6Config>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> BiasDivRoundRelu6Chip<F> {\n  pub fn construct(config: Rc<BiasDivRoundRelu6Config>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn get_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let div_val = scale_factor;\n\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let val = shifted.clamp(0, 6 * div_val as i64);\n      map.insert(i as i64, val);\n    }\n    map\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let sf = Expression::Constant(F::from(gadget_config.scale_factor));\n    let two = Expression::Constant(F::from(2));\n    let columns = gadget_config.columns;\n\n    let mut tables = gadget_config.tables;\n    let div_lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n    let relu_lookup = meta.lookup_table_column();\n\n    meta.create_gate(\"bias_mul\", |meta| {\n      let s = meta.query_selector(selector);\n\n      let mut constraints = vec![];\n      for op_idx in 0..columns.len() / NUM_COLS_PER_OP {\n        let offset = op_idx * NUM_COLS_PER_OP;\n        let inp = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let bias = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let div_res = meta.query_advice(columns[offset + 2], Rotation::cur());\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        // ((div - bias) * 2 + mod) * sf = 2 * inp + sf\n        constraints.push(\n          s.clone()\n            * (two.clone() * inp + sf.clone()\n              - (sf.clone() * two.clone() * (div_res - bias) + mod_res)),\n        );\n      }\n\n      constraints\n    });\n\n    for op_idx in 0..columns.len() / NUM_COLS_PER_OP {\n      let offset = op_idx * NUM_COLS_PER_OP;\n      meta.lookup(\"bias_div_relu6 lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        // Constrains that the modulus \\in [0, DIV_VAL)\n        // div_val - mod_res \\in [0, max_val)\n        vec![(s.clone() * (two.clone() * sf.clone() - mod_res), div_lookup)]\n      });\n      meta.lookup(\"bias_div_relu6 lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let div = meta.query_advice(columns[offset + 2], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 4], Rotation::cur());\n        let div_outp_min_val = gadget_config.div_outp_min_val;\n        let div_outp_min_val = Expression::Constant(F::from((-div_outp_min_val) as u64));\n\n        // Constrains that output \\in [0, 6 * SF]\n        vec![\n          (s.clone() * (div + div_outp_min_val), div_lookup),\n          (s.clone() * outp, relu_lookup),\n        ]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::BiasDivRoundRelu6, vec![selector]);\n\n    tables.insert(GadgetType::BiasDivRoundRelu6, vec![relu_lookup]);\n\n    let mut maps = gadget_config.maps;\n    let relu_map = Self::get_map(\n      gadget_config.scale_factor,\n      gadget_config.min_val,\n      gadget_config.num_rows as i64,\n    );\n    maps.insert(GadgetType::BiasDivRoundRelu6, vec![relu_map]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      tables,\n      maps,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for BiasDivRoundRelu6Chip<F> {\n  fn name(&self) -> String {\n    \"BiasDivRelu6\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    NUM_COLS_PER_OP\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / NUM_COLS_PER_OP\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row() * 2\n  }\n\n  fn load_lookups(&self, mut layouter: impl Layouter<F>) -> Result<(), Error> {\n    let map = &self.config.maps[&GadgetType::BiasDivRoundRelu6][0];\n\n    let relu_lookup = self.config.tables[&GadgetType::BiasDivRoundRelu6][0];\n\n    layouter\n      .assign_table(\n        || \"bdr round div/relu lookup\",\n        |mut table| {\n          for i in 0..self.config.num_rows {\n            let i = i as i64;\n            let val = map.get(&i).unwrap();\n            table\n              .assign_cell(\n                || \"relu lookup\",\n                relu_lookup,\n                i as usize,\n                || Value::known(F::from(*val as u64)),\n              )\n              .unwrap();\n          }\n          Ok(())\n        },\n      )\n      .unwrap();\n\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let div_val = self.config.scale_factor as i64;\n\n    let div_outp_min_val_i64 = self.config.div_outp_min_val;\n\n    let div_inp_min_val_pos_i64 = -self.config.shift_min_val;\n    let div_inp_min_val_pos = F::from(div_inp_min_val_pos_i64 as u64);\n\n    let inp = &vec_inputs[0];\n    let bias = &vec_inputs[1];\n    assert_eq!(inp.len(), bias.len());\n    assert_eq!(inp.len() % self.num_inputs_per_row(), 0);\n\n    let relu_map = &self\n      .config\n      .maps\n      .get(&GadgetType::BiasDivRoundRelu6)\n      .unwrap()[0];\n\n    if self.config.use_selectors {\n      let selector = self\n        .config\n        .selectors\n        .get(&GadgetType::BiasDivRoundRelu6)\n        .unwrap()[0];\n      selector.enable(region, row_offset).unwrap();\n    }\n\n    let mut outp_cells = vec![];\n    for (i, (inp, bias)) in inp.iter().zip(bias.iter()).enumerate() {\n      let offset = i * NUM_COLS_PER_OP;\n\n      let inp_f = inp.value().map(|x: &F| x.to_owned());\n      let bias_f = bias.value().map(|x: &F| {\n        let a = *x + div_inp_min_val_pos;\n        let a = convert_to_u64(&a) as i64 - div_inp_min_val_pos_i64;\n        a\n      });\n      let div_mod_res = inp_f.map(|x: F| {\n        let x_pos = x + div_inp_min_val_pos;\n        let inp = convert_to_u64(&x_pos) as i64;\n        let div_inp = 2 * inp + div_val;\n        let div_res = div_inp / (2 * div_val) - div_inp_min_val_pos_i64 / div_val;\n        let mod_res = div_inp % (2 * div_val);\n        (div_res, mod_res)\n      });\n      let div_res = div_mod_res.map(|x: (i64, i64)| x.0) + bias_f;\n      let mod_res = div_mod_res.map(|x: (i64, i64)| x.1);\n\n      let outp = div_res.map(|x: i64| {\n        let mut x_pos = x - div_outp_min_val_i64;\n        if !relu_map.contains_key(&(x_pos)) {\n          println!(\"x: {}, x_pos: {}\", x, x_pos);\n          x_pos = 0;\n        }\n        let outp_val = relu_map.get(&(x_pos)).unwrap();\n        F::from(*outp_val as u64)\n      });\n\n      // Assign inp, bias\n      inp\n        .copy_advice(|| \"\", region, self.config.columns[offset + 0], row_offset)\n        .unwrap();\n      bias\n        .copy_advice(|| \"\", region, self.config.columns[offset + 1], row_offset)\n        .unwrap();\n\n      // Assign div_res, mod_res\n      let div_res_cell = region\n        .assign_advice(\n          || \"div_res\",\n          self.config.columns[offset + 2],\n          row_offset,\n          || {\n            div_res.map(|x: i64| {\n              F::from((x - div_outp_min_val_i64) as u64) - F::from(-div_outp_min_val_i64 as u64)\n            })\n          },\n        )\n        .unwrap();\n      let _mod_res_cell = region\n        .assign_advice(\n          || \"mod_res\",\n          self.config.columns[offset + 3],\n          row_offset,\n          || mod_res.map(|x: i64| F::from(x as u64)),\n        )\n        .unwrap();\n\n      let outp_cell = region\n        .assign_advice(\n          || \"outp\",\n          self.config.columns[offset + 4],\n          row_offset,\n          || outp.map(|x: F| x.to_owned()),\n        )\n        .unwrap();\n\n      // outp_cells.push((outp_cell, div_res_cell));\n      outp_cells.push(outp_cell);\n      outp_cells.push(div_res_cell);\n    }\n\n    Ok(outp_cells)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inps = vec_inputs[0].clone();\n    let mut biases = vec_inputs[1].clone();\n    let initial_len = inps.len();\n\n    // Needed to pad: bias - bias = 0\n    let default = biases[0].clone();\n    while inps.len() % self.num_inputs_per_row() != 0 {\n      inps.push(&default);\n      biases.push(&default);\n    }\n\n    let res = self\n      .op_aligned_rows(\n        layouter.namespace(|| \"bias_div_relu6\"),\n        &vec![inps, biases],\n        single_inputs,\n      )\n      .unwrap();\n    Ok(res[0..initial_len * 2].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/dot_prod.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{Advice, Column, ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse crate::gadgets::adder::AdderChip;\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype DotProductConfig = GadgetConfig;\n\npub struct DotProductChip<F: PrimeField> {\n  config: Rc<DotProductConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> DotProductChip<F> {\n  pub fn construct(config: Rc<DotProductConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn get_input_columns(config: &GadgetConfig) -> Vec<Column<Advice>> {\n    let num_inputs = (config.columns.len() - 1) / 2;\n    config.columns[0..num_inputs].to_vec()\n  }\n\n  pub fn get_weight_columns(config: &GadgetConfig) -> Vec<Column<Advice>> {\n    let num_inputs = (config.columns.len() - 1) / 2;\n    config.columns[num_inputs..config.columns.len() - 1].to_vec()\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = &gadget_config.columns;\n\n    meta.create_gate(\"dot product gate\", |meta| {\n      let s = meta.query_selector(selector);\n      let gate_inp = DotProductChip::<F>::get_input_columns(&gadget_config)\n        .iter()\n        .map(|col| meta.query_advice(*col, Rotation::cur()))\n        .collect::<Vec<_>>();\n      let gate_weights = DotProductChip::<F>::get_weight_columns(&gadget_config)\n        .iter()\n        .map(|col| meta.query_advice(*col, Rotation::cur()))\n        .collect::<Vec<_>>();\n      let gate_output = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n\n      let res = gate_inp\n        .iter()\n        .zip(gate_weights)\n        .map(|(a, b)| a.clone() * b.clone())\n        .fold(Expression::Constant(F::ZERO), |a, b| a + b);\n\n      vec![s * (res - gate_output)]\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::DotProduct, vec![selector]);\n\n    GadgetConfig {\n      columns: gadget_config.columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for DotProductChip<F> {\n  fn name(&self) -> String {\n    \"dot product\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    self.config.columns.len()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    (self.config.columns.len() - 1) / 2\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    1\n  }\n\n  // The caller is expected to pad the inputs\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(vec_inputs.len(), 2);\n\n    let inp = &vec_inputs[0];\n    let weights = &vec_inputs[1];\n    assert_eq!(inp.len(), weights.len());\n    assert_eq!(inp.len(), self.num_inputs_per_row());\n\n    let zero = &single_inputs[0];\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::DotProduct).unwrap()[0];\n      selector.enable(region, row_offset).unwrap();\n    }\n\n    let inp_cols = DotProductChip::<F>::get_input_columns(&self.config);\n    inp\n      .iter()\n      .enumerate()\n      .map(|(i, cell)| cell.copy_advice(|| \"\", region, inp_cols[i], row_offset))\n      .collect::<Result<Vec<_>, _>>()\n      .unwrap();\n\n    let weight_cols = DotProductChip::<F>::get_weight_columns(&self.config);\n    weights\n      .iter()\n      .enumerate()\n      .map(|(i, cell)| cell.copy_advice(|| \"\", region, weight_cols[i], row_offset))\n      .collect::<Result<Vec<_>, _>>()\n      .unwrap();\n\n    // All columns need to be assigned\n    if self.config.columns.len() % 2 == 0 {\n      zero\n        .copy_advice(\n          || \"\",\n          region,\n          self.config.columns[self.config.columns.len() - 2],\n          row_offset,\n        )\n        .unwrap();\n    }\n\n    let e = inp\n      .iter()\n      .zip(weights.iter())\n      .map(|(a, b)| a.value().map(|x: &F| *x) * b.value())\n      .reduce(|a, b| a + b)\n      .unwrap();\n\n    let res = region\n      .assign_advice(\n        || \"\",\n        self.config.columns[self.config.columns.len() - 1],\n        row_offset,\n        || e,\n      )\n      .unwrap();\n\n    Ok(vec![res])\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(vec_inputs.len(), 2);\n    assert_eq!(single_inputs.len(), 1);\n    let zero = &single_inputs[0];\n\n    let mut inputs = vec_inputs[0].clone();\n    let mut weights = vec_inputs[1].clone();\n    while inputs.len() % self.num_inputs_per_row() != 0 {\n      inputs.push(&zero);\n      weights.push(&zero);\n    }\n\n    let outputs = layouter\n      .assign_region(\n        || \"dot prod rows\",\n        |mut region| {\n          let mut outputs = vec![];\n          for i in 0..inputs.len() / self.num_inputs_per_row() {\n            let inp =\n              inputs[i * self.num_inputs_per_row()..(i + 1) * self.num_inputs_per_row()].to_vec();\n            let weights =\n              weights[i * self.num_inputs_per_row()..(i + 1) * self.num_inputs_per_row()].to_vec();\n            let res = self\n              .op_row_region(&mut region, i, &vec![inp, weights], &vec![zero.clone()])\n              .unwrap();\n            outputs.push(res[0].clone());\n          }\n          Ok(outputs)\n        },\n      )\n      .unwrap();\n\n    let adder_chip = AdderChip::<F>::construct(self.config.clone());\n    let tmp = outputs.iter().map(|x| x).collect::<Vec<_>>();\n    Ok(\n      adder_chip\n        .forward(\n          layouter.namespace(|| \"dot prod adder\"),\n          &vec![tmp],\n          single_inputs,\n        )\n        .unwrap(),\n    )\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/gadget.rs",
        "content": "use std::{\n  collections::{BTreeSet, HashMap},\n  sync::Arc,\n};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::group::ff::PrimeField,\n  plonk::{Advice, Column, Error, Fixed, Selector, TableColumn},\n};\nuse num_bigint::{BigUint, ToBigUint};\nuse num_traits::cast::ToPrimitive;\n\n#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]\npub enum GadgetType {\n  AddPairs,\n  Adder,\n  BiasDivRoundRelu6,\n  BiasDivFloorRelu6,\n  DotProduct,\n  Exp,\n  Logistic,\n  Max,\n  Pow,\n  Relu,\n  Rsqrt,\n  Sqrt,\n  SqrtBig,\n  Square,\n  SquaredDiff,\n  SubPairs,\n  Tanh,\n  MulPairs,\n  VarDivRound,\n  VarDivRoundBig,\n  VarDivRoundBig3,\n  Packer,      // This is a special case\n  InputLookup, // Dummy placeholder for the input lookup\n  Update,\n}\n\n#[derive(Clone, Debug, Default)]\npub struct GadgetConfig {\n  pub used_gadgets: Arc<BTreeSet<GadgetType>>,\n  pub columns: Vec<Column<Advice>>,\n  pub fixed_columns: Vec<Column<Fixed>>,\n  pub selectors: HashMap<GadgetType, Vec<Selector>>,\n  pub tables: HashMap<GadgetType, Vec<TableColumn>>,\n  pub maps: HashMap<GadgetType, Vec<HashMap<i64, i64>>>,\n  pub scale_factor: u64,\n  pub shift_min_val: i64, // MUST be divisible by 2 * scale_factor\n  pub num_rows: usize,\n  pub num_cols: usize,\n  pub k: usize,\n  pub eta: f64,\n  pub min_val: i64,\n  pub max_val: i64,\n  pub div_outp_min_val: i64,\n  pub use_selectors: bool,\n  pub commit_before: Vec<Vec<i64>>,\n  pub commit_after: Vec<Vec<i64>>,\n  pub num_bits_per_elem: i64,\n}\n\n// TODO: refactor\npub fn convert_to_u64<F: PrimeField>(x: &F) -> u64 {\n  let big = BigUint::from_bytes_le(x.to_repr().as_ref());\n  let big_digits = big.to_u64_digits();\n  if big_digits.len() > 2 {\n    println!(\"big_digits: {:?}\", big_digits);\n  }\n  if big_digits.len() == 1 {\n    big_digits[0] as u64\n  } else if big_digits.len() == 0 {\n    0\n  } else {\n    panic!();\n  }\n}\n\npub fn convert_to_u128<F: PrimeField>(x: &F) -> u128 {\n  let big = BigUint::from_bytes_le(x.to_repr().as_ref());\n  big.to_biguint().unwrap().to_u128().unwrap()\n}\n\npub trait Gadget<F: PrimeField> {\n  fn name(&self) -> String;\n\n  fn num_cols_per_op(&self) -> usize;\n\n  fn num_inputs_per_row(&self) -> usize;\n\n  fn num_outputs_per_row(&self) -> usize;\n\n  fn load_lookups(&self, _layouter: impl Layouter<F>) -> Result<(), Error> {\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error>;\n\n  // The caller is required to ensure that the inputs are of the correct length.\n  fn op_aligned_rows(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    // Sanity check inputs\n    for inp in vec_inputs.iter() {\n      assert_eq!(inp.len() % self.num_inputs_per_row(), 0);\n    }\n\n    let outputs = layouter.assign_region(\n      || format!(\"gadget {}\", self.name()),\n      |mut region| {\n        let mut outputs = vec![];\n        for i in 0..vec_inputs[0].len() / self.num_inputs_per_row() {\n          let mut vec_inputs_row = vec![];\n          for inp in vec_inputs.iter() {\n            vec_inputs_row.push(\n              inp[i * self.num_inputs_per_row()..(i + 1) * self.num_inputs_per_row()].to_vec(),\n            );\n          }\n          let row_outputs = self.op_row_region(&mut region, i, &vec_inputs_row, &single_inputs)?;\n          assert_eq!(row_outputs.len(), self.num_outputs_per_row());\n          outputs.extend(row_outputs);\n        }\n        Ok(outputs)\n      },\n    )?;\n\n    Ok(outputs)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      vec_inputs,\n      single_inputs,\n    )\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/input_lookup.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\npub struct InputLookupChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> InputLookupChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let lookup = meta.lookup_table_column();\n    let mut tables = gadget_config.tables;\n    tables.insert(GadgetType::InputLookup, vec![lookup]);\n\n    GadgetConfig {\n      tables,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for InputLookupChip<F> {\n  fn load_lookups(&self, mut layouter: impl Layouter<F>) -> Result<(), Error> {\n    let lookup = self.config.tables[&GadgetType::InputLookup][0];\n\n    layouter\n      .assign_table(\n        || \"input lookup\",\n        |mut table| {\n          for i in 0..self.config.num_rows as i64 {\n            table\n              .assign_cell(\n                || \"mod lookup\",\n                lookup,\n                i as usize,\n                || Value::known(F::from(i as u64)),\n              )\n              .unwrap();\n          }\n          Ok(())\n        },\n      )\n      .unwrap();\n\n    Ok(())\n  }\n\n  fn name(&self) -> String {\n    panic!(\"InputLookupChip should not be called directly\")\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    panic!(\"InputLookupChip should not be called directly\")\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    panic!(\"InputLookupChip should not be called directly\")\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    panic!(\"InputLookupChip should not be called directly\")\n  }\n\n  fn op_row_region(\n    &self,\n    _region: &mut Region<F>,\n    _row_offset: usize,\n    _vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    panic!(\"InputLookupChip should not be called directly\")\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/max.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::convert_to_u64;\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\npub struct MaxChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> MaxChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let columns = gadget_config.columns;\n    let tables = gadget_config.tables;\n\n    let inp_lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    meta.create_gate(\"max arithmetic\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        constraints.push(s.clone() * (inp1 - outp.clone()) * (inp2 - outp))\n      }\n      constraints\n    });\n\n    for idx in 0..columns.len() / Self::num_cols_per_op() {\n      meta.lookup(\"max inp1\", |meta| {\n        let s = meta.query_selector(selector);\n        let offset = idx * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s * (outp - inp1), inp_lookup)]\n      });\n      meta.lookup(\"max inp2\", |meta| {\n        let s = meta.query_selector(selector);\n        let offset = idx * Self::num_cols_per_op();\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s * (outp - inp2), inp_lookup)]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::Max, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      tables,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for MaxChip<F> {\n  fn name(&self) -> String {\n    \"max\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    3\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op() * 2\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(vec_inputs.len(), 1);\n    let inp = &vec_inputs[0];\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::Max).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let min_val_pos = F::from((-self.config.shift_min_val) as u64);\n\n    let mut outp = vec![];\n\n    let chunks: Vec<&[&AssignedCell<F, F>]> = inp.chunks(self.num_outputs_per_row()).collect();\n    let i1 = chunks[0];\n    let i2 = chunks[1];\n    for (idx, (inp1, inp2)) in i1.iter().zip(i2.iter()).enumerate() {\n      let offset = idx * self.num_cols_per_op();\n      inp1\n        .copy_advice(|| \"\", region, self.config.columns[offset + 0], row_offset)\n        .unwrap();\n      inp2\n        .copy_advice(|| \"\", region, self.config.columns[offset + 1], row_offset)\n        .unwrap();\n\n      let max = inp1.value().zip(inp2.value()).map(|(a, b)| {\n        let a = convert_to_u64(&(*a + min_val_pos));\n        let b = convert_to_u64(&(*b + min_val_pos));\n        let max = a.max(b);\n        let max = F::from(max) - min_val_pos;\n        max\n      });\n\n      let res = region\n        .assign_advice(|| \"\", self.config.columns[offset + 2], row_offset, || max)\n        .unwrap();\n      outp.push(res);\n    }\n\n    Ok(outp)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inputs = vec_inputs[0].clone();\n    let first = inputs[0];\n\n    while inputs.len() % self.num_inputs_per_row() != 0 {\n      inputs.push(first);\n    }\n\n    // TODO: pretty sure this is correct but check\n    let num_iters = inputs.len().div_ceil(self.num_inputs_per_row()) + self.num_inputs_per_row();\n\n    let mut outputs = self.op_aligned_rows(\n      layouter.namespace(|| \"max forward\"),\n      &vec![inputs],\n      single_inputs,\n    )?;\n    for _ in 0..num_iters {\n      while outputs.len() % self.num_inputs_per_row() != 0 {\n        outputs.push(first.clone());\n      }\n      let tmp = outputs.iter().map(|x| x).collect::<Vec<_>>();\n      outputs = self.op_aligned_rows(\n        layouter.namespace(|| \"max forward\"),\n        &vec![tmp],\n        single_inputs,\n      )?;\n    }\n\n    outputs = vec![outputs.into_iter().next().unwrap()];\n\n    Ok(outputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/mul_pairs.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype MulPairsConfig = GadgetConfig;\n\npub struct MulPairsChip<F: PrimeField> {\n  config: Rc<MulPairsConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> MulPairsChip<F> {\n  pub fn construct(config: Rc<MulPairsConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"mul pair\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let res = inp1 * inp2;\n        constraints.append(&mut vec![s.clone() * (res - outp)])\n      }\n\n      constraints\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::MulPairs, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for MulPairsChip<F> {\n  fn name(&self) -> String {\n    \"MulPairs\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  // TODO: This + below is basically copied from add pairs - make arithmetic generic\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let inp1 = &vec_inputs[0];\n    let inp2 = &vec_inputs[1];\n    assert_eq!(inp1.len(), inp2.len());\n\n    let columns = &self.config.columns;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::MulPairs).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outps = vec![];\n    for i in 0..inp1.len() {\n      let offset = i * self.num_cols_per_op();\n      let inp1 = inp1[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let inp2 = inp2[i].copy_advice(|| \"\", region, columns[offset + 1], row_offset)?;\n      let outp = inp1.value().map(|x: &F| x.to_owned()) * inp2.value().map(|x: &F| x.to_owned());\n\n      let outp = region.assign_advice(|| \"\", columns[offset + 2], row_offset, || outp)?;\n      outps.push(outp);\n    }\n    Ok(outps)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp1 = vec_inputs[0].clone();\n    let mut inp2 = vec_inputs[1].clone();\n    let initial_len = inp1.len();\n    while inp1.len() % self.num_inputs_per_row() != 0 {\n      inp1.push(zero);\n      inp2.push(zero);\n    }\n\n    let vec_inputs = vec![inp1, inp2];\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear.rs",
        "content": "pub mod exp;\npub mod logistic;\npub mod non_linearity;\npub mod pow;\npub mod relu;\npub mod rsqrt;\npub mod sqrt;\npub mod tanh;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/exp.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\ntype ExpGadgetConfig = GadgetConfig;\n\n// IMPORTANT: this return exp(x) * SF\npub struct ExpGadgetChip<F: PrimeField> {\n  config: Rc<ExpGadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> ExpGadgetChip<F> {\n  pub fn construct(config: Rc<ExpGadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <ExpGadgetChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Exp)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for ExpGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / (scale_factor as f64);\n      let exp = x.exp();\n      let exp = (exp * ((scale_factor * scale_factor) as f64)).round() as i64;\n      map.insert(i as i64, exp);\n    }\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Exp).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Exp).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for ExpGadgetChip<F> {\n  fn name(&self) -> String {\n    \"Exp\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <ExpGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Exp)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/logistic.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\npub struct LogisticGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> LogisticGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <LogisticGadgetChip<F> as NonLinearGadget<F>>::configure(\n      meta,\n      gadget_config,\n      GadgetType::Logistic,\n    )\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for LogisticGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / (scale_factor as f64);\n      let logistic = 1. / (1. + (-x).exp());\n      let logistic = (logistic * ((scale_factor) as f64)).round() as i64;\n      map.insert(i as i64, logistic);\n    }\n\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Logistic).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Logistic).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for LogisticGadgetChip<F> {\n  fn name(&self) -> String {\n    \"LogisticChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <LogisticGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Logistic)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/non_linearity.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression, Selector},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::convert_to_u128;\n\nuse super::super::gadget::Gadget;\nuse super::super::gadget::{GadgetConfig, GadgetType};\n\nconst NUM_COLS_PER_OP: usize = 2;\n\npub trait NonLinearGadget<F: PrimeField>: Gadget<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64>;\n\n  fn get_map(&self) -> &HashMap<i64, i64>;\n\n  fn get_selector(&self) -> Selector;\n\n  fn num_cols_per_op() -> usize {\n    NUM_COLS_PER_OP\n  }\n\n  fn configure(\n    meta: &mut ConstraintSystem<F>,\n    gadget_config: GadgetConfig,\n    gadget_type: GadgetType,\n  ) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let columns = gadget_config.columns;\n\n    let mut tables = gadget_config.tables;\n    let inp_lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n    let outp_lookup = meta.lookup_table_column();\n\n    for op_idx in 0..columns.len() / NUM_COLS_PER_OP {\n      let offset = op_idx * NUM_COLS_PER_OP;\n      meta.lookup(\"non-linear lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let inp = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let shift_val = gadget_config.min_val;\n        let shift_val_pos = Expression::Constant(F::from((-shift_val) as u64));\n\n        vec![\n          (s.clone() * (inp + shift_val_pos), inp_lookup),\n          (s.clone() * outp, outp_lookup),\n        ]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(gadget_type, vec![selector]);\n\n    tables.insert(gadget_type, vec![inp_lookup, outp_lookup]);\n\n    let mut maps = gadget_config.maps;\n    let non_linear_map = Self::generate_map(\n      gadget_config.scale_factor,\n      gadget_config.min_val,\n      gadget_config.num_rows as i64,\n    );\n    maps.insert(gadget_type, vec![non_linear_map]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      tables,\n      maps,\n      ..gadget_config\n    }\n  }\n\n  fn load_lookups(\n    &self,\n    mut layouter: impl Layouter<F>,\n    config: Rc<GadgetConfig>,\n    gadget_type: GadgetType,\n  ) -> Result<(), Error> {\n    let map = self.get_map();\n    let table_col = config.tables.get(&gadget_type).unwrap()[1];\n\n    let shift_pos_i64 = -config.shift_min_val;\n    let shift_pos = F::from(shift_pos_i64 as u64);\n    layouter.assign_table(\n      || \"non linear table\",\n      |mut table| {\n        for i in 0..config.num_rows {\n          let i = i as i64;\n          // FIXME: refactor this\n          let tmp = *map.get(&i).unwrap();\n          let val = if i == 0 {\n            F::ZERO\n          } else {\n            if tmp >= 0 {\n              F::from(tmp as u64)\n            } else {\n              let tmp = tmp + shift_pos_i64;\n              F::from(tmp as u64) - shift_pos\n            }\n          };\n          table.assign_cell(\n            || \"non linear cell\",\n            table_col,\n            i as usize,\n            || Value::known(val),\n          )?;\n        }\n        Ok(())\n      },\n    )?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let columns = &gadget_config.columns;\n    let inp = &vec_inputs[0];\n    let map = self.get_map();\n    let shift_val_pos_i64 = -gadget_config.shift_min_val;\n    let shift_val_pos = F::from(shift_val_pos_i64 as u64);\n    let min_val = gadget_config.min_val;\n\n    if gadget_config.use_selectors {\n      let selector = self.get_selector();\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outps = vec![];\n    for i in 0..inp.len() {\n      let offset = i * 2;\n      inp[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let outp = inp[i].value().map(|x: &F| {\n        let pos = convert_to_u128(&(*x + shift_val_pos)) as i128 - shift_val_pos_i64 as i128;\n        let x = pos as i64 - min_val;\n        let val = *map.get(&x).unwrap();\n        if x == 0 {\n          F::ZERO\n        } else {\n          if val >= 0 {\n            F::from(val as u64)\n          } else {\n            let val_pos = val + shift_val_pos_i64;\n            F::from(val_pos as u64) - F::from(shift_val_pos_i64 as u64)\n          }\n        }\n      });\n\n      let outp =\n        region.assign_advice(|| \"nonlinearity\", columns[offset + 1], row_offset, || outp)?;\n      outps.push(outp);\n    }\n\n    Ok(outps)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n    let inp_len = vec_inputs[0].len();\n    let mut inp = vec_inputs[0].clone();\n\n    while inp.len() % self.num_inputs_per_row() != 0 {\n      inp.push(zero);\n    }\n\n    let vec_inputs = vec![inp];\n    let outp = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      &single_inputs,\n    )?;\n\n    Ok(outp[0..inp_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/pow.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\n// IMPORTANT: PowGadget assumes a single power across the entire DAG\npub struct PowGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> PowGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <PowGadgetChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Pow)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for PowGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let power = 3.; // FIXME: need to make this variable somehow...\n\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / (scale_factor as f64);\n      let y = x.powf(power);\n      let y = (y * ((scale_factor) as f64)).round() as i64;\n      map.insert(i as i64, y);\n    }\n\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Pow).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Pow).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for PowGadgetChip<F> {\n  fn name(&self) -> String {\n    \"PowGadgetChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <PowGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Pow)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/relu.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\npub struct ReluChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> ReluChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <ReluChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Relu)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for ReluChip<F> {\n  fn generate_map(_scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let relu = shifted.max(0);\n      map.insert(i as i64, relu);\n    }\n\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Relu).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Relu).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for ReluChip<F> {\n  fn name(&self) -> String {\n    \"Relu\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <ReluChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Relu)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/rsqrt.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\npub struct RsqrtGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> RsqrtGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <RsqrtGadgetChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Rsqrt)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for RsqrtGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / (scale_factor as f64);\n      let sqrt = x.sqrt();\n      let rsqrt = 1.0 / sqrt;\n      let rsqrt = (rsqrt * (scale_factor as f64)).round() as i64;\n      map.insert(i as i64, rsqrt);\n    }\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Rsqrt).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Rsqrt).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for RsqrtGadgetChip<F> {\n  fn name(&self) -> String {\n    \"RsqrtGadget\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <RsqrtGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Rsqrt)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/sqrt.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\npub struct SqrtGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SqrtGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <SqrtGadgetChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Sqrt)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for SqrtGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / (scale_factor as f64);\n      let sqrt = x.sqrt();\n      let sqrt = (sqrt * (scale_factor as f64)).round() as i64;\n      map.insert(i as i64, sqrt);\n    }\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Sqrt).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Sqrt).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for SqrtGadgetChip<F> {\n  fn name(&self) -> String {\n    \"SqrtGadget\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <SqrtGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Sqrt)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/nonlinear/tanh.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n};\n\nuse super::{\n  super::gadget::{Gadget, GadgetConfig, GadgetType},\n  non_linearity::NonLinearGadget,\n};\n\npub struct TanhGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> TanhGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    <TanhGadgetChip<F> as NonLinearGadget<F>>::configure(meta, gadget_config, GadgetType::Tanh)\n  }\n}\n\nimpl<F: PrimeField> NonLinearGadget<F> for TanhGadgetChip<F> {\n  fn generate_map(scale_factor: u64, min_val: i64, num_rows: i64) -> HashMap<i64, i64> {\n    let scale_factor = scale_factor as f64;\n\n    let mut map = HashMap::new();\n    for i in 0..num_rows {\n      let shifted = i + min_val;\n      let x = (shifted as f64) / scale_factor;\n      let y = x.tanh();\n      let y = (y * scale_factor).round() as i64;\n      map.insert(i as i64, y);\n    }\n\n    map\n  }\n\n  fn get_map(&self) -> &HashMap<i64, i64> {\n    &self.config.maps.get(&GadgetType::Tanh).unwrap()[0]\n  }\n\n  fn get_selector(&self) -> halo2_proofs::plonk::Selector {\n    self.config.selectors.get(&GadgetType::Tanh).unwrap()[0]\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for TanhGadgetChip<F> {\n  fn name(&self) -> String {\n    \"TanhGadgetChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    <TanhGadgetChip<F> as NonLinearGadget<F>>::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn load_lookups(&self, layouter: impl Layouter<F>) -> Result<(), Error> {\n    NonLinearGadget::load_lookups(self, layouter, self.config.clone(), GadgetType::Tanh)?;\n    Ok(())\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::op_row_region(\n      self,\n      region,\n      row_offset,\n      vec_inputs,\n      single_inputs,\n      self.config.clone(),\n    )\n  }\n\n  fn forward(\n    &self,\n    layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    NonLinearGadget::forward(self, layouter, vec_inputs, single_inputs)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/sqrt_big.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::convert_to_u64;\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype SqrtBigConfig = GadgetConfig;\n\npub struct SqrtBigChip<F: PrimeField> {\n  config: Rc<SqrtBigConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SqrtBigChip<F> {\n  pub fn construct(config: Rc<SqrtBigConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.complex_selector();\n    let two = Expression::Constant(F::from(2));\n    let columns = gadget_config.columns;\n\n    let tables = gadget_config.tables;\n\n    let inp_lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    // TODO: prove that these constraints work\n    meta.create_gate(\"sqrt_big arithm\", |meta| {\n      let s = meta.query_selector(selector);\n\n      let mut constraints = vec![];\n      for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = op_idx * Self::num_cols_per_op();\n        let inp = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let sqrt = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let rem = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let lhs = inp.clone();\n        let rhs = sqrt.clone() * sqrt.clone() + rem.clone();\n        constraints.push(s.clone() * (lhs - rhs));\n      }\n      constraints\n    });\n\n    for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n      let offset = op_idx * Self::num_cols_per_op();\n      meta.lookup(\"sqrt_big sqrt lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let sqrt = meta.query_advice(columns[offset + 1], Rotation::cur());\n\n        vec![(s.clone() * sqrt, inp_lookup)]\n      });\n\n      meta.lookup(\"sqrt_big rem lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let sqrt = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let rem = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s.clone() * (rem + sqrt), inp_lookup)]\n      });\n\n      meta.lookup(\"sqrt_big sqrt - rem lookup\", |meta| {\n        let s = meta.query_selector(selector);\n        let sqrt = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let rem = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s.clone() * (two.clone() * sqrt - rem), inp_lookup)]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::SqrtBig, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      tables,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for SqrtBigChip<F> {\n  fn name(&self) -> String {\n    \"sqrt_big\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let inps = &vec_inputs[0];\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::SqrtBig).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outp_cells = vec![];\n    for (i, inp) in inps.iter().enumerate() {\n      let offset = i * self.num_cols_per_op();\n      inp.copy_advice(\n        || \"sqrt_big\",\n        region,\n        self.config.columns[offset],\n        row_offset,\n      )?;\n\n      let outp = inp.value().map(|x: &F| {\n        let inp_val = convert_to_u64(x) as i64;\n        let fsqrt = (inp_val as f64).sqrt();\n        let sqrt = fsqrt.round() as i64;\n        let rem = inp_val - sqrt * sqrt;\n        (sqrt, rem)\n      });\n\n      let sqrt_cell = region.assign_advice(\n        || \"sqrt_big\",\n        self.config.columns[offset + 1],\n        row_offset,\n        || outp.map(|x| F::from(x.0 as u64)),\n      )?;\n\n      let _rem_cell = region.assign_advice(\n        || \"sqrt_big\",\n        self.config.columns[offset + 2],\n        row_offset,\n        || {\n          outp.map(|x| {\n            let rem_pos = x.1 + x.0;\n            F::from(rem_pos as u64) - F::from(x.0 as u64)\n          })\n        },\n      )?;\n      outp_cells.push(sqrt_cell);\n    }\n\n    Ok(outp_cells)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp = vec_inputs[0].clone();\n    let inp_len = inp.len();\n    while inp.len() % self.num_inputs_per_row() != 0 {\n      inp.push(zero);\n    }\n\n    let vec_inputs = vec![inp];\n    let outp = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n\n    Ok(outp[0..inp_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/square.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\npub struct SquareGadgetChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SquareGadgetChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  // TODO: it would be more efficient to do the division here directly\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"square gate\", |meta| {\n      let s = meta.query_selector(selector);\n      let gate_inp = meta.query_advice(columns[0], Rotation::cur());\n      let gate_output = meta.query_advice(columns[1], Rotation::cur());\n\n      let res = gate_inp.clone() * gate_inp;\n\n      vec![s * (res - gate_output)]\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::Square, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for SquareGadgetChip<F> {\n  fn name(&self) -> String {\n    \"SquareChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    2\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    assert_eq!(vec_inputs.len(), 1);\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::Square).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let inps = &vec_inputs[0];\n    let mut outp = vec![];\n    for (i, inp) in inps.iter().enumerate() {\n      let offset = i * self.num_cols_per_op();\n      inp.copy_advice(|| \"\", region, self.config.columns[offset], row_offset)?;\n      let outp_val = inp.value().map(|x: &F| x.to_owned() * x.to_owned());\n      let outp_cell = region.assign_advice(\n        || \"square output\",\n        self.config.columns[offset + 1],\n        row_offset,\n        || outp_val,\n      )?;\n      outp.push(outp_cell);\n    }\n\n    Ok(outp)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl halo2_proofs::circuit::Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp = vec_inputs[0].clone();\n    let initial_len = inp.len();\n    while inp.len() % self.num_inputs_per_row() != 0 {\n      inp.push(zero);\n    }\n\n    let vec_inputs = vec![inp];\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/squared_diff.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype SquaredDiffConfig = GadgetConfig;\n\npub struct SquaredDiffGadgetChip<F: PrimeField> {\n  config: Rc<SquaredDiffConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SquaredDiffGadgetChip<F> {\n  pub fn construct(config: Rc<SquaredDiffConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"squared diff\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let res = (inp1 - inp2).square();\n        constraints.append(&mut vec![s.clone() * (res - outp)])\n      }\n\n      constraints\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::SquaredDiff, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for SquaredDiffGadgetChip<F> {\n  fn name(&self) -> String {\n    \"SquaredDiff\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let inp1 = &vec_inputs[0];\n    let inp2 = &vec_inputs[1];\n    assert_eq!(inp1.len(), inp2.len());\n\n    let columns = &self.config.columns;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::SquaredDiff).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outps = vec![];\n    for i in 0..inp1.len() {\n      let offset = i * self.num_cols_per_op();\n      let inp1 = inp1[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let inp2 = inp2[i].copy_advice(|| \"\", region, columns[offset + 1], row_offset)?;\n      let outp = inp1.value().map(|x: &F| x.to_owned()) - inp2.value().map(|x: &F| x.to_owned());\n      let outp = outp * outp;\n\n      let outp = region.assign_advice(|| \"\", columns[offset + 2], row_offset, || outp)?;\n      outps.push(outp);\n    }\n    Ok(outps)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp1 = vec_inputs[0].clone();\n    let mut inp2 = vec_inputs[1].clone();\n    let initial_len = inp1.len();\n    while inp1.len() % self.num_inputs_per_row() != 0 {\n      inp1.push(zero);\n      inp2.push(zero);\n    }\n\n    let vec_inputs = vec![inp1, inp2];\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/sub_pairs.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error},\n  poly::Rotation,\n};\n\nuse super::gadget::{Gadget, GadgetConfig, GadgetType};\n\ntype SubPairsConfig = GadgetConfig;\n\npub struct SubPairsChip<F: PrimeField> {\n  config: Rc<SubPairsConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> SubPairsChip<F> {\n  pub fn construct(config: Rc<SubPairsConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let selector = meta.selector();\n    let columns = gadget_config.columns;\n\n    meta.create_gate(\"sub pair\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n      for i in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let inp1 = meta.query_advice(columns[offset + 0], Rotation::cur());\n        let inp2 = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let outp = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let res = inp1 - inp2;\n        constraints.append(&mut vec![s.clone() * (res - outp)])\n      }\n\n      constraints\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::SubPairs, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for SubPairsChip<F> {\n  fn name(&self) -> String {\n    \"sub pairs chip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let inp1 = &vec_inputs[0];\n    let inp2 = &vec_inputs[1];\n    assert_eq!(inp1.len(), inp2.len());\n\n    let columns = &self.config.columns;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::SubPairs).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let mut outps = vec![];\n    for i in 0..inp1.len() {\n      let offset = i * self.num_cols_per_op();\n      let inp1 = inp1[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let inp2 = inp2[i].copy_advice(|| \"\", region, columns[offset + 1], row_offset)?;\n      let outp = inp1.value().map(|x: &F| x.to_owned()) - inp2.value().map(|x: &F| x.to_owned());\n\n      let outp = region.assign_advice(|| \"\", columns[offset + 2], row_offset, || outp)?;\n      outps.push(outp);\n    }\n    Ok(outps)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n\n    let mut inp1 = vec_inputs[0].clone();\n    let mut inp2 = vec_inputs[1].clone();\n    let initial_len = inp1.len();\n    while inp1.len() % self.num_inputs_per_row() != 0 {\n      inp1.push(zero);\n      inp2.push(zero);\n    }\n\n    let vec_inputs = vec![inp1, inp2];\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec_inputs,\n      single_inputs,\n    )?;\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/update.rs",
        "content": "use std::marker::PhantomData;\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\n\nuse crate::gadgets::gadget::{convert_to_u64, GadgetConfig};\n\nuse super::gadget::{Gadget, GadgetType};\n\ntype UpdateConfig = GadgetConfig;\n\n#[derive(Clone, Debug)]\npub struct UpdateGadgetChip<F: PrimeField> {\n  config: UpdateConfig,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> UpdateGadgetChip<F> {\n  pub fn construct(config: UpdateConfig) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    4\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> UpdateConfig {\n    let tables = &gadget_config.tables;\n    let mod_lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    let columns = gadget_config.columns;\n    let selector = meta.complex_selector();\n\n    let div_val = gadget_config.scale_factor;\n    let eta: u64 = (gadget_config.scale_factor as f64 * gadget_config.eta) as u64;\n\n    meta.create_gate(\"updater_arith\", |meta| {\n      let s = meta.query_selector(selector);\n\n      let sf = Expression::Constant(F::from(div_val as u64));\n      let eta = Expression::Constant(F::from(eta as u64));\n\n      let mut constraints = vec![];\n      for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n        let offset = op_idx * Self::num_cols_per_op();\n        let w = meta.query_advice(columns[offset], Rotation::cur());\n        let dw = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let div = meta.query_advice(columns[offset + 2], Rotation::cur());\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        let expr = (w * sf.clone() - dw * eta.clone()) - (div * sf.clone() + mod_res);\n        constraints.push(s.clone() * expr);\n      }\n      constraints\n    });\n\n    for op_idx in 0..columns.len() / Self::num_cols_per_op() {\n      let offset = op_idx * Self::num_cols_per_op();\n\n      // Check that mod is smaller than SF\n      meta.lookup(\"max inp1\", |meta| {\n        let s = meta.query_selector(selector);\n        let mod_res = meta.query_advice(columns[offset + 3], Rotation::cur());\n\n        // Constrains that the modulus \\in [0, DIV_VAL)\n        vec![(s.clone() * mod_res.clone(), mod_lookup)]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::Update, vec![selector]);\n\n    UpdateConfig {\n      columns,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField + Ord> Gadget<F> for UpdateGadgetChip<F> {\n  fn name(&self) -> String {\n    \"updater chip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.config.columns.len() / self.num_cols_per_op()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    _single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let div_val = self.config.scale_factor as i64;\n    let div_val_f = F::from(div_val as u64);\n    let eta = div_val / 1000;\n    let eta = F::from(eta as u64);\n\n    let div_outp_min_val = self.config.div_outp_min_val;\n    let div_inp_min_val_pos_i64 = -self.config.shift_min_val;\n    let div_inp_min_val_pos = F::from(div_inp_min_val_pos_i64 as u64);\n\n    let columns = &self.config.columns;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::Update).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    let w = &vec_inputs[0];\n    let dw = &vec_inputs[1];\n\n    let mut output_cells = vec![];\n\n    for i in 0..w.len() {\n      let offset = i * self.num_cols_per_op();\n      let _w_cell = w[i].copy_advice(|| \"\", region, columns[offset + 0], row_offset)?;\n      let _dw_cell = dw[i].copy_advice(|| \"\", region, columns[offset + 1], row_offset)?;\n\n      let w_val = w[i].value().map(|x: &F| x.to_owned());\n      let dw_val = dw[i].value().map(|x: &F| x.to_owned());\n      let out_scaled = w_val.zip(dw_val).map(|(w, dw)| w * div_val_f - dw * eta);\n\n      let div_mod = out_scaled.map(|x| {\n        let x_pos = x + div_inp_min_val_pos;\n        let x_pos = if x_pos > F::ZERO {\n          x_pos\n        } else {\n          x_pos + div_val_f\n        };\n        let inp = convert_to_u64(&x_pos);\n\n        let div_res = inp as i64 / div_val - (div_inp_min_val_pos_i64 as i64 / div_val);\n        let mod_res = inp as i64 % div_val;\n        (div_res, mod_res)\n      });\n\n      let div_res_cell = region\n        .assign_advice(\n          || \"div_res\",\n          self.config.columns[offset + 2],\n          row_offset,\n          || {\n            div_mod.map(|(x, _): (i64, i64)| {\n              F::from((x - div_outp_min_val as i64) as u64) - F::from(-div_outp_min_val as u64)\n            })\n          },\n        )\n        .unwrap();\n\n      let _mod_res_cell = region\n        .assign_advice(\n          || \"mod_res\",\n          self.config.columns[offset + 3],\n          row_offset,\n          || div_mod.map(|(_, x): (i64, i64)| F::from(x as u64)),\n        )\n        .unwrap();\n\n      output_cells.push(div_res_cell);\n    }\n    Ok(output_cells)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let zero = &single_inputs[0];\n    let mut w = vec_inputs[0].clone();\n    let mut dw = vec_inputs[1].clone();\n\n    let initial_len = w.len();\n    while !w.len() % self.num_cols_per_op() == 0 {\n      w.push(zero);\n    }\n    while !dw.len() % self.num_cols_per_op() == 0 {\n      dw.push(zero);\n    }\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| format!(\"forward row {}\", self.name())),\n      &vec![w, dw],\n      single_inputs,\n    )?;\n\n    Ok(res[0..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/var_div.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\nuse rounded_div::RoundedDiv;\n\nuse super::gadget::{convert_to_u128, Gadget, GadgetConfig, GadgetType};\n\ntype VarDivRoundConfig = GadgetConfig;\n\npub struct VarDivRoundChip<F: PrimeField> {\n  config: Rc<VarDivRoundConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> VarDivRoundChip<F> {\n  pub fn construct(config: Rc<VarDivRoundConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    3\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let columns = gadget_config.columns;\n    let selector = meta.complex_selector();\n    let two = Expression::Constant(F::from(2));\n\n    let tables = gadget_config.tables;\n    let lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    // a | c | r | ... | b\n    // (2 * a + b) = (2 * b) * c + r\n    // b - r \\in [0, 2^N) <-- forces b > r\n    meta.create_gate(\"var_div_arithm\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n\n      let b = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n      for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        let a = meta.query_advice(columns[offset], Rotation::cur());\n        let c = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let r = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let lhs = a.clone() * two.clone() + b.clone();\n        let rhs = b.clone() * two.clone() * c + r;\n        constraints.push(s.clone() * (lhs - rhs));\n      }\n\n      constraints\n    });\n\n    for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n      let offset = i * Self::num_cols_per_op();\n      // r \\in [0, 2^N)\n      meta.lookup(\"var div range checks r\", |meta| {\n        let s = meta.query_selector(selector);\n        let r = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s.clone() * r, lookup)]\n      });\n\n      // 2 * b - r \\in [0, 2^N)\n      meta.lookup(\"var div range checks 2b-r\", |meta| {\n        let s = meta.query_selector(selector);\n        let b = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n        let r = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        vec![(s.clone() * (two.clone() * b - r), lookup)]\n      });\n    }\n    // b \\in [0, 2^N)\n    meta.lookup(\"var div range checks b\", |meta| {\n      let s = meta.query_selector(selector);\n      let b = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n\n      vec![(s.clone() * b, lookup)]\n    });\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::VarDivRound, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      tables,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for VarDivRoundChip<F> {\n  fn name(&self) -> String {\n    \"VarDivRoundChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    (self.config.columns.len() - 1) / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let a_vec = &vec_inputs[0];\n    // let zero = single_inputs[0].clone();\n    let b = &single_inputs[1];\n\n    let div_outp_min_val_i64 = self.config.div_outp_min_val;\n    let div_inp_min_val_pos_i64 = -self.config.shift_min_val;\n\n    if self.config.use_selectors {\n      let selector = self.config.selectors.get(&GadgetType::VarDivRound).unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    b.copy_advice(\n      || \"\",\n      region,\n      self.config.columns[self.config.columns.len() - 1],\n      row_offset,\n    )?;\n\n    let mut div_out = vec![];\n    for (i, a) in a_vec.iter().enumerate() {\n      let offset = i * self.num_cols_per_op();\n      a.copy_advice(|| \"\", region, self.config.columns[offset], row_offset)?;\n\n      let div_mod = a.value().zip(b.value()).map(|(a, b)| {\n        let b = convert_to_u128(b);\n        // Needs to be divisible by b\n        let div_inp_min_val_pos_i64 = div_inp_min_val_pos_i64 / (b as i64) * (b as i64);\n        let div_inp_min_val_pos = F::from(div_inp_min_val_pos_i64 as u64);\n\n        let a_pos = *a + div_inp_min_val_pos;\n        let a = convert_to_u128(&a_pos);\n        // c = (2 * a + b) / (2 * b)\n        let c_pos = a.rounded_div(b);\n        let c = (c_pos as i128 - (div_inp_min_val_pos_i64 as u128 / b) as i128) as i64;\n\n        // r = (2 * a + b) % (2 * b)\n        let rem_floor = (a as i128) - (c_pos * b) as i128;\n        let r = 2 * rem_floor + (b as i128);\n        let r = r as i64;\n        (c, r)\n      });\n\n      let div_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 1],\n        row_offset,\n        || {\n          div_mod.map(|(c, _)| {\n            let offset = F::from(-div_outp_min_val_i64 as u64);\n            let c = F::from((c - div_outp_min_val_i64) as u64);\n            c - offset\n          })\n        },\n      )?;\n      let _mod_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 2],\n        row_offset,\n        || div_mod.map(|(_, r)| F::from(r as u64)),\n      )?;\n      div_out.push(div_cell);\n    }\n\n    Ok(div_out)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inps = vec_inputs[0].clone();\n    let initial_len = inps.len();\n\n    // Needed to pad: bias - bias = 0\n    let default = &single_inputs[0];\n    while inps.len() % self.num_inputs_per_row() != 0 {\n      inps.push(&default);\n    }\n\n    let res = self.op_aligned_rows(layouter.namespace(|| \"var_div\"), &vec![inps], single_inputs)?;\n    Ok(res[..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/var_div_big.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\nuse rounded_div::RoundedDiv;\n\nuse super::gadget::{convert_to_u128, Gadget, GadgetConfig, GadgetType};\n\npub struct VarDivRoundBigChip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> VarDivRoundBigChip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    7\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let columns = gadget_config.columns;\n    let selector = meta.complex_selector();\n    let two = Expression::Constant(F::from(2));\n    let range = Expression::Constant(F::from(gadget_config.num_rows as u64));\n\n    let tables = gadget_config.tables;\n    let lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    // a | c | r | (2 b - r)_1 | (2 b - r)_0 | r_1 | r_0 | ... | b\n    // a / b = c\n    meta.create_gate(\"var_div_arithm\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n\n      let b = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n      for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        // Constrain that (2 * a + b) = (2 * b) * c + r\n        let a = meta.query_advice(columns[offset], Rotation::cur());\n        let c = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let r = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let lhs = a.clone() * two.clone() + b.clone();\n        let rhs = b.clone() * two.clone() * c + r.clone();\n        constraints.push(s.clone() * (lhs - rhs));\n\n        // Constrain that (2 * b - r) = br1 * max_val + br0\n        let br1 = meta.query_advice(columns[offset + 3], Rotation::cur());\n        let br0 = meta.query_advice(columns[offset + 4], Rotation::cur());\n        let lhs = b.clone() * two.clone() - r.clone();\n        let rhs = br1 * range.clone() + br0;\n        constraints.push(s.clone() * (lhs - rhs));\n\n        // Constrains that r = r1 * max_val + r0\n        let r1 = meta.query_advice(columns[offset + 5], Rotation::cur());\n        let r0 = meta.query_advice(columns[offset + 6], Rotation::cur());\n        let lhs = r.clone();\n        let rhs = r1 * range.clone() + r0;\n        constraints.push(s.clone() * (lhs - rhs));\n      }\n\n      constraints\n    });\n\n    // For var div big, we assume that a, b > 0 and are outputs of the previous layer\n    // r must be constrained to be in [0, b)\n    for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n      let offset = i * Self::num_cols_per_op();\n\n      // (2 * b - r)_{1, 0} \\in [0, 2^N)\n      meta.lookup(\"var div big br1\", |meta| {\n        let s = meta.query_selector(selector);\n        let br1 = meta.query_advice(columns[offset + 3], Rotation::cur());\n        vec![(s * br1, lookup)]\n      });\n      meta.lookup(\"var div big br0\", |meta| {\n        let s = meta.query_selector(selector);\n        let br0 = meta.query_advice(columns[offset + 4], Rotation::cur());\n        vec![(s * br0, lookup)]\n      });\n      // r_{1, 0} \\in [0, 2^N)\n      meta.lookup(\"var div big r1\", |meta| {\n        let s = meta.query_selector(selector);\n        let r1 = meta.query_advice(columns[offset + 5], Rotation::cur());\n        vec![(s * r1, lookup)]\n      });\n      meta.lookup(\"var div big r0\", |meta| {\n        let s = meta.query_selector(selector);\n        let r0 = meta.query_advice(columns[offset + 6], Rotation::cur());\n        vec![(s * r0, lookup)]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::VarDivRoundBig, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      tables,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for VarDivRoundBigChip<F> {\n  fn name(&self) -> String {\n    \"VarDivBigRoundChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    (self.config.columns.len() - 1) / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let a_vec = &vec_inputs[0];\n    // let zero = single_inputs[0].clone();\n    let b = &single_inputs[1];\n\n    let div_outp_min_val_i64 = self.config.div_outp_min_val;\n    let div_inp_min_val_pos_i64 = -self.config.shift_min_val;\n    let num_rows = self.config.num_rows as i64;\n\n    if self.config.use_selectors {\n      let selector = self\n        .config\n        .selectors\n        .get(&GadgetType::VarDivRoundBig)\n        .unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    b.copy_advice(\n      || \"\",\n      region,\n      self.config.columns[self.config.columns.len() - 1],\n      row_offset,\n    )?;\n\n    let mut div_out = vec![];\n    for (i, a) in a_vec.iter().enumerate() {\n      let offset = i * self.num_cols_per_op();\n      a.copy_advice(|| \"\", region, self.config.columns[offset], row_offset)\n        .unwrap();\n\n      let div_mod = a.value().zip(b.value()).map(|(a, b)| {\n        let b = convert_to_u128(b);\n        // Needs to be divisible by b\n        let div_inp_min_val_pos_i64 = div_inp_min_val_pos_i64 / (b as i64) * (b as i64);\n        let div_inp_min_val_pos = F::from(div_inp_min_val_pos_i64 as u64);\n\n        let a_pos = *a + div_inp_min_val_pos;\n        let a = convert_to_u128(&a_pos);\n        // c = (2 * a + b) / (2 * b)\n        let c_pos = a.rounded_div(b);\n        let c = (c_pos as i128 - (div_inp_min_val_pos_i64 as u128 / b) as i128) as i64;\n\n        // r = (2 * a + b) % (2 * b)\n        let rem_floor = (a as i128) - (c_pos * b) as i128;\n        let r = 2 * rem_floor + (b as i128);\n        let r = r as i64;\n        (c, r)\n      });\n\n      let br_split = div_mod.zip(b.value()).map(|((_, r), b)| {\n        let b = convert_to_u128(b) as i64;\n        let val = 2 * b - r;\n        let p1 = val / num_rows;\n        let p0 = val % num_rows;\n        // val = p1 * max_val + p0\n        (p1, p0)\n      });\n\n      let r_split = div_mod.map(|(_, r)| {\n        let p1 = r / num_rows;\n        let p0 = r % num_rows;\n        // val = p1 * max_val + p0\n        (p1, p0)\n      });\n\n      let div_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 1],\n        row_offset,\n        || {\n          div_mod.map(|(c, _)| {\n            let offset = F::from(-div_outp_min_val_i64 as u64);\n            let c = F::from((c - div_outp_min_val_i64) as u64);\n            c - offset\n          })\n        },\n      )?;\n      let _mod_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 2],\n        row_offset,\n        || div_mod.map(|(_, r)| F::from(r as u64)),\n      )?;\n      // Assign 2 * b - r to the next 2 columns\n      let _br_split_cell_1 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 3],\n        row_offset,\n        || br_split.map(|(p1, _)| F::from(p1 as u64)),\n      )?;\n      let _br_split_cell_2 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 4],\n        row_offset,\n        || br_split.map(|(_, p0)| F::from(p0 as u64)),\n      )?;\n      // Assign r to the next 2 columns\n      let _r_split_cell_1 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 5],\n        row_offset,\n        || r_split.map(|(p1, _)| F::from(p1 as u64)),\n      )?;\n      let _r_split_cell_2 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 6],\n        row_offset,\n        || r_split.map(|(_, p0)| F::from(p0 as u64)),\n      )?;\n\n      div_out.push(div_cell);\n    }\n\n    Ok(div_out)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inps = vec_inputs[0].clone();\n    let initial_len = inps.len();\n\n    // Needed to pad\n    let default = &single_inputs[0];\n    while inps.len() % self.num_inputs_per_row() != 0 {\n      inps.push(&default);\n    }\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| \"var_div_big\"),\n      &vec![inps],\n      single_inputs,\n    )?;\n    Ok(res[..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/gadgets/var_div_big3.rs",
        "content": "use std::{marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region},\n  halo2curves::ff::PrimeField,\n  plonk::{ConstraintSystem, Error, Expression},\n  poly::Rotation,\n};\nuse rounded_div::RoundedDiv;\n\nuse super::gadget::{convert_to_u128, Gadget, GadgetConfig, GadgetType};\n\npub struct VarDivRoundBig3Chip<F: PrimeField> {\n  config: Rc<GadgetConfig>,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> VarDivRoundBig3Chip<F> {\n  pub fn construct(config: Rc<GadgetConfig>) -> Self {\n    Self {\n      config,\n      _marker: PhantomData,\n    }\n  }\n\n  pub fn num_cols_per_op() -> usize {\n    9\n  }\n\n  pub fn configure(meta: &mut ConstraintSystem<F>, gadget_config: GadgetConfig) -> GadgetConfig {\n    let columns = gadget_config.columns;\n    let selector = meta.complex_selector();\n    let two = Expression::Constant(F::from(2));\n    let range = Expression::Constant(F::from(gadget_config.num_rows as u64));\n    let range_sq = range.clone() * range.clone();\n\n    let tables = gadget_config.tables;\n    let lookup = tables.get(&GadgetType::InputLookup).unwrap()[0];\n\n    // a | c | r | (2b - r)_2 | (2 b - r)_1 | (2 b - r)_0 | r_2 | r_1 | r_0 | ... | b\n    // a / b = c\n    meta.create_gate(\"var_div_big3_arithm\", |meta| {\n      let s = meta.query_selector(selector);\n      let mut constraints = vec![];\n\n      let b = meta.query_advice(columns[columns.len() - 1], Rotation::cur());\n      for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n        let offset = i * Self::num_cols_per_op();\n        // Constrain that (2 * a + b) = (2 * b) * c + r\n        let a = meta.query_advice(columns[offset], Rotation::cur());\n        let c = meta.query_advice(columns[offset + 1], Rotation::cur());\n        let r = meta.query_advice(columns[offset + 2], Rotation::cur());\n\n        let lhs = a.clone() * two.clone() + b.clone();\n        let rhs = b.clone() * two.clone() * c + r.clone();\n        constraints.push(s.clone() * (lhs - rhs));\n\n        // Constrain that (2 * b - r) = br1 * max_val + br0\n        let br2 = meta.query_advice(columns[offset + 3], Rotation::cur());\n        let br1 = meta.query_advice(columns[offset + 4], Rotation::cur());\n        let br0 = meta.query_advice(columns[offset + 5], Rotation::cur());\n        let lhs = b.clone() * two.clone() - r.clone();\n        let rhs = br2 * range_sq.clone() + br1 * range.clone() + br0;\n        constraints.push(s.clone() * (lhs - rhs));\n\n        // Constrains that r = r1 * max_val + r0\n        let r2 = meta.query_advice(columns[offset + 6], Rotation::cur());\n        let r1 = meta.query_advice(columns[offset + 7], Rotation::cur());\n        let r0 = meta.query_advice(columns[offset + 8], Rotation::cur());\n        let lhs = r.clone();\n        let rhs = r2 * range_sq.clone() + r1 * range.clone() + r0;\n        constraints.push(s.clone() * (lhs - rhs));\n      }\n\n      constraints\n    });\n\n    // For var div big, we assume that a, b > 0 and are outputs of the previous layer\n    // r must be constrained to be in [0, b)\n    for i in 0..(columns.len() - 1) / Self::num_cols_per_op() {\n      let offset = i * Self::num_cols_per_op();\n\n      // (2 * b - r)_{1, 0} \\in [0, 2^N)\n      meta.lookup(\"var div big br2\", |meta| {\n        let s = meta.query_selector(selector);\n        let br2 = meta.query_advice(columns[offset + 3], Rotation::cur());\n        vec![(s * br2, lookup)]\n      });\n      meta.lookup(\"var div big br1\", |meta| {\n        let s = meta.query_selector(selector);\n        let br1 = meta.query_advice(columns[offset + 4], Rotation::cur());\n        vec![(s * br1, lookup)]\n      });\n      meta.lookup(\"var div big br0\", |meta| {\n        let s = meta.query_selector(selector);\n        let br0 = meta.query_advice(columns[offset + 5], Rotation::cur());\n        vec![(s * br0, lookup)]\n      });\n      // r_{1, 0} \\in [0, 2^N)\n      meta.lookup(\"var div big r2\", |meta| {\n        let s = meta.query_selector(selector);\n        let r2 = meta.query_advice(columns[offset + 6], Rotation::cur());\n        vec![(s * r2, lookup)]\n      });\n      meta.lookup(\"var div big r1\", |meta| {\n        let s = meta.query_selector(selector);\n        let r1 = meta.query_advice(columns[offset + 7], Rotation::cur());\n        vec![(s * r1, lookup)]\n      });\n      meta.lookup(\"var div big r0\", |meta| {\n        let s = meta.query_selector(selector);\n        let r0 = meta.query_advice(columns[offset + 8], Rotation::cur());\n        vec![(s * r0, lookup)]\n      });\n    }\n\n    let mut selectors = gadget_config.selectors;\n    selectors.insert(GadgetType::VarDivRoundBig3, vec![selector]);\n\n    GadgetConfig {\n      columns,\n      tables,\n      selectors,\n      ..gadget_config\n    }\n  }\n}\n\nimpl<F: PrimeField> Gadget<F> for VarDivRoundBig3Chip<F> {\n  fn name(&self) -> String {\n    \"VarDivBig3RoundChip\".to_string()\n  }\n\n  fn num_cols_per_op(&self) -> usize {\n    Self::num_cols_per_op()\n  }\n\n  fn num_inputs_per_row(&self) -> usize {\n    (self.config.columns.len() - 1) / self.num_cols_per_op()\n  }\n\n  fn num_outputs_per_row(&self) -> usize {\n    self.num_inputs_per_row()\n  }\n\n  fn op_row_region(\n    &self,\n    region: &mut Region<F>,\n    row_offset: usize,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let a_vec = &vec_inputs[0];\n    // let zero = single_inputs[0].clone();\n    let b = &single_inputs[1];\n\n    let c_shift_base = (-(1_i64 << 62)) as i128;\n    let num_rows = self.config.num_rows as i128;\n\n    if self.config.use_selectors {\n      let selector = self\n        .config\n        .selectors\n        .get(&GadgetType::VarDivRoundBig3)\n        .unwrap()[0];\n      selector.enable(region, row_offset)?;\n    }\n\n    b.copy_advice(\n      || \"\",\n      region,\n      self.config.columns[self.config.columns.len() - 1],\n      row_offset,\n    )?;\n\n    let mut div_out = vec![];\n    for (i, a) in a_vec.iter().enumerate() {\n      let offset = i * self.num_cols_per_op();\n      a.copy_advice(|| \"\", region, self.config.columns[offset], row_offset)\n        .unwrap();\n\n      let div_mod = a.value().zip(b.value()).map(|(a, b)| {\n        let b = convert_to_u128(b);\n        let c_shift = (-c_shift_base) as u128 / b * b;\n        let div_inp_min_val_pos = F::from(c_shift as u64);\n\n        let a_pos = *a + div_inp_min_val_pos;\n        let a = convert_to_u128(&a_pos);\n        // c = (2 * a + b) / (2 * b)\n        let c_pos = a.rounded_div(b);\n        let c = c_pos as i128 - (c_shift / b) as i128;\n\n        // r = (2 * a + b) % (2 * b)\n        let rem_floor = (a as i128) - (c_pos * b) as i128;\n        let r = 2 * rem_floor + (b as i128);\n        (c, r)\n      });\n\n      let br_split = div_mod.zip(b.value()).map(|((_, r), b)| {\n        let b = convert_to_u128(b) as i128;\n        let val = 2 * b - r;\n        let p2 = val / (num_rows * num_rows);\n        let p1 = (val % (num_rows * num_rows)) / num_rows;\n        let p0 = val % num_rows;\n        // val = p2 * max_val^2 + p1 * max_val + p0\n        (p2, p1, p0)\n      });\n\n      let r_split = div_mod.map(|(_, r)| {\n        let p2 = r / (num_rows * num_rows);\n        let p1 = (r % (num_rows * num_rows)) / num_rows;\n        let p0 = r % num_rows;\n        // val = p1 * max_val + p0\n        (p2, p1, p0)\n      });\n\n      let div_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 1],\n        row_offset,\n        || {\n          div_mod.map(|(c, _)| {\n            let offset = F::from(-c_shift_base as u64);\n            let c = F::from((c - c_shift_base) as u64);\n            c - offset\n          })\n        },\n      )?;\n      let _mod_cell = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 2],\n        row_offset,\n        || div_mod.map(|(_, r)| F::from(r as u64)),\n      )?;\n      // Assign 2 * b - r to the next 3 columns\n      let _br_split_cell_2 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 3],\n        row_offset,\n        || br_split.map(|(p2, _, _)| F::from(p2 as u64)),\n      )?;\n      let _br_split_cell_1 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 4],\n        row_offset,\n        || br_split.map(|(_, p1, _)| F::from(p1 as u64)),\n      )?;\n      let _br_split_cell_0 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 5],\n        row_offset,\n        || br_split.map(|(_, _, p0)| F::from(p0 as u64)),\n      )?;\n      // Assign r to the next 3 columns\n      let _r_split_cell_2 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 6],\n        row_offset,\n        || r_split.map(|(p2, _, _)| F::from(p2 as u64)),\n      )?;\n      let _r_split_cell_1 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 7],\n        row_offset,\n        || r_split.map(|(_, p1, _)| F::from(p1 as u64)),\n      )?;\n      let _r_split_cell_0 = region.assign_advice(\n        || \"\",\n        self.config.columns[offset + 8],\n        row_offset,\n        || r_split.map(|(_, _, p0)| F::from(p0 as u64)),\n      )?;\n\n      div_out.push(div_cell);\n    }\n\n    Ok(div_out)\n  }\n\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    single_inputs: &Vec<&AssignedCell<F, F>>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mut inps = vec_inputs[0].clone();\n    let initial_len = inps.len();\n\n    // Needed to pad\n    let default = &single_inputs[0];\n    while inps.len() % self.num_inputs_per_row() != 0 {\n      inps.push(&default);\n    }\n\n    let res = self.op_aligned_rows(\n      layouter.namespace(|| \"var_div_big3\"),\n      &vec![inps],\n      single_inputs,\n    )?;\n    Ok(res[..initial_len].to_vec())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers.rs",
        "content": "// Generics\npub mod averager;\n\npub mod arithmetic;\npub mod shape;\n\n// Concrete implementations\npub mod avg_pool_2d;\npub mod batch_mat_mul;\npub mod conv2d;\npub mod div_fixed;\npub mod fully_connected;\npub mod logistic;\npub mod max_pool_2d;\npub mod mean;\npub mod noop;\npub mod pow;\npub mod rsqrt;\npub mod softmax;\npub mod sqrt;\npub mod square;\npub mod squared_diff;\npub mod tanh;\npub mod update;\n\n// Special: dag\npub mod dag;\n\n// Special: layer\npub mod layer;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/arithmetic.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\n\nuse crate::{gadgets::gadget::GadgetConfig, utils::helpers::broadcast};\n\nuse super::layer::{AssignedTensor, CellRc};\n\npub mod add;\npub mod div_var;\npub mod mul;\npub mod sub;\n\npub trait Arithmetic<F: PrimeField> {\n  fn gadget_forward(\n    &self,\n    layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    constants: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error>;\n\n  fn arithmetic_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<(Vec<CellRc<F>>, Vec<usize>), Error> {\n    assert_eq!(tensors.len(), 2);\n    // println!(\"tensors: {:?} {:?}\", tensors[0].shape(), tensors[1].shape());\n    let (inp1, inp2) = broadcast(&tensors[0], &tensors[1]);\n    let out_shape = inp1.shape().clone();\n    assert_eq!(inp1.shape(), inp2.shape());\n\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let inp1_vec = inp1.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let inp2_vec = inp2.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let vec_inputs = vec![inp1_vec, inp2_vec];\n    let constants = vec![zero];\n    let out = self.gadget_forward(\n      layouter.namespace(|| \"\"),\n      &vec_inputs,\n      &constants,\n      gadget_config.clone(),\n    )?;\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    Ok((out, out_shape.to_vec()))\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/arithmetic/add.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    add_pairs::AddPairsChip,\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    nonlinear::relu::ReluChip,\n  },\n  layers::layer::{ActivationType, AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::{\n  super::layer::{Layer, LayerConfig},\n  Arithmetic,\n};\n\n#[derive(Clone, Debug)]\npub struct AddChip {}\n\nimpl AddChip {\n  fn get_activation(&self, layer_params: &Vec<i64>) -> ActivationType {\n    let activation = layer_params[0];\n    match activation {\n      0 => ActivationType::None,\n      1 => ActivationType::Relu,\n      _ => panic!(\"Unsupported activation type for add\"),\n    }\n  }\n}\n\nimpl<F: PrimeField> Arithmetic<F> for AddChip {\n  fn gadget_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    constants: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let add_pairs_chip = AddPairsChip::<F>::construct(gadget_config);\n    let out = add_pairs_chip.forward(layouter.namespace(|| \"add chip\"), &vec_inputs, constants)?;\n    Ok(out)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for AddChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let activation = self.get_activation(&layer_config.layer_params);\n\n    // Do the addition\n    let (out, out_shape) = self.arithmetic_forward(\n      layouter.namespace(|| \"\"),\n      tensors,\n      constants,\n      gadget_config.clone(),\n    )?;\n\n    // Do the fused activation\n    let out = if activation == ActivationType::Relu {\n      let zero = constants.get(&0).unwrap();\n      let single_inps = vec![zero.as_ref()];\n\n      let out = out.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n\n      let relu_chip = ReluChip::<F>::construct(gadget_config);\n      let out = relu_chip.forward(layouter.namespace(|| \"relu\"), &vec![out], &single_inps)?;\n      let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n      out\n    } else if activation == ActivationType::None {\n      out\n    } else {\n      panic!(\"Unsupported activation type for add\");\n    };\n\n    let out = Array::from_shape_vec(IxDyn(out_shape.as_slice()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for AddChip {\n  fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    let activation = self.get_activation(&layer_params);\n    let mut outp = vec![GadgetType::AddPairs];\n\n    match activation {\n      ActivationType::Relu => outp.push(GadgetType::Relu),\n      ActivationType::None => (),\n      _ => panic!(\"Unsupported activation type for add\"),\n    }\n    outp\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/arithmetic/div_var.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    mul_pairs::MulPairsChip,\n    var_div::VarDivRoundChip,\n  },\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer},\n};\n\nuse super::Arithmetic;\n\npub struct DivVarChip {}\n\n// TODO: hack. Used for multiplying by the scale factor\nimpl<F: PrimeField> Arithmetic<F> for DivVarChip {\n  fn gadget_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    constants: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mul_pairs_chip = MulPairsChip::<F>::construct(gadget_config.clone());\n\n    let out = mul_pairs_chip.forward(\n      layouter.namespace(|| \"mul pairs chip\"),\n      &vec_inputs,\n      constants,\n    )?;\n    Ok(out)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for DivVarChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &crate::layers::layer::LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    assert_eq!(tensors.len(), 2);\n    // TODO: We only support dividing by a single number for now\n    assert_eq!(tensors[1].shape().len(), 1);\n    assert_eq!(tensors[1].shape()[0], 1);\n\n    let sf = constants\n      .get(&(gadget_config.scale_factor as i64))\n      .unwrap()\n      .as_ref();\n\n    let sf_tensor = Array::from_shape_vec(IxDyn(&[1]), vec![Rc::new(sf.clone())]).unwrap();\n\n    // out = inp * SF\n    let (out, out_shape) = self.arithmetic_forward(\n      layouter.namespace(|| \"\"),\n      &vec![tensors[0].clone(), sf_tensor],\n      constants,\n      gadget_config.clone(),\n    )?;\n\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n    let div = tensors[1].iter().next().unwrap().as_ref();\n    let zero = constants.get(&0).unwrap().as_ref();\n    let single_inputs = vec![zero, div];\n    let out = out.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let out = var_div_chip.forward(layouter.namespace(|| \"mul div\"), &vec![out], &single_inputs)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(out_shape.as_slice()), out).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for DivVarChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::MulPairs,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/arithmetic/mul.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    mul_pairs::MulPairsChip,\n    var_div::VarDivRoundChip,\n  },\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::{\n  super::layer::{Layer, LayerConfig},\n  Arithmetic,\n};\n\n#[derive(Clone, Debug)]\npub struct MulChip {}\n\nimpl<F: PrimeField> Arithmetic<F> for MulChip {\n  fn gadget_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    constants: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let mul_pairs_chip = MulPairsChip::<F>::construct(gadget_config.clone());\n\n    let out = mul_pairs_chip.forward(\n      layouter.namespace(|| \"mul pairs chip\"),\n      &vec_inputs,\n      constants,\n    )?;\n    Ok(out)\n  }\n}\n\n// FIXME: move this + add to an arithmetic layer\nimpl<F: PrimeField> Layer<F> for MulChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let (out, out_shape) = self.arithmetic_forward(\n      layouter.namespace(|| \"\"),\n      tensors,\n      constants,\n      gadget_config.clone(),\n    )?;\n\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n    let div = constants\n      .get(&(gadget_config.scale_factor as i64))\n      .unwrap()\n      .as_ref();\n    let zero = constants.get(&0).unwrap().as_ref();\n    let single_inputs = vec![zero, div];\n    let out = out.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let out = var_div_chip.forward(layouter.namespace(|| \"mul div\"), &vec![out], &single_inputs)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(out_shape.as_slice()), out).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for MulChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::MulPairs,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/arithmetic/sub.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    sub_pairs::SubPairsChip,\n  },\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::{\n  super::layer::{Layer, LayerConfig},\n  Arithmetic,\n};\n\n#[derive(Clone, Debug)]\npub struct SubChip {}\n\nimpl<F: PrimeField> Arithmetic<F> for SubChip {\n  fn gadget_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    vec_inputs: &Vec<Vec<&AssignedCell<F, F>>>,\n    constants: &Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let sub_pairs_chip = SubPairsChip::<F>::construct(gadget_config);\n    let out = sub_pairs_chip.forward(layouter.namespace(|| \"sub chip\"), &vec_inputs, constants)?;\n    Ok(out)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for SubChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let (out, out_shape) = self.arithmetic_forward(\n      layouter.namespace(|| \"\"),\n      tensors,\n      constants,\n      gadget_config.clone(),\n    )?;\n    let out = Array::from_shape_vec(IxDyn(out_shape.as_slice()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for SubChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::SubPairs]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/averager.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\n\nuse crate::gadgets::gadget::Gadget;\nuse crate::gadgets::{adder::AdderChip, gadget::GadgetConfig, var_div::VarDivRoundChip};\n\nuse super::layer::{AssignedTensor, CellRc, LayerConfig};\n\npub trait Averager<F: PrimeField> {\n  fn splat(&self, input: &AssignedTensor<F>, layer_config: &LayerConfig) -> Vec<Vec<CellRc<F>>>;\n\n  fn get_div_val(\n    &self,\n    layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<AssignedCell<F, F>, Error>;\n\n  fn avg_forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<CellRc<F>>, Error> {\n    // Due to Mean BS\n    // assert_eq!(tensors.len(), 1);\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let inp = &tensors[0];\n    let splat_inp = self.splat(inp, layer_config);\n\n    let adder_chip = AdderChip::<F>::construct(gadget_config.clone());\n    let single_inputs = vec![zero];\n    let mut added = vec![];\n    for i in 0..splat_inp.len() {\n      let tmp = splat_inp[i].iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n      let tmp = adder_chip.forward(\n        layouter.namespace(|| format!(\"average {}\", i)),\n        &vec![tmp],\n        &single_inputs,\n      )?;\n      added.push(tmp[0].clone());\n    }\n\n    let div = self.get_div_val(\n      layouter.namespace(|| \"average div\"),\n      tensors,\n      gadget_config.clone(),\n      layer_config,\n    )?;\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n\n    let single_inputs = vec![zero, &div];\n    let added = added.iter().map(|x| x).collect::<Vec<_>>();\n    let dived = var_div_chip.forward(\n      layouter.namespace(|| \"average div\"),\n      &vec![added],\n      &single_inputs,\n    )?;\n    let dived = dived.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n\n    Ok(dived)\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/avg_pool_2d.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Value},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::max_pool_2d::MaxPool2DChip,\n};\n\nuse super::{\n  averager::Averager,\n  layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig},\n};\n\npub struct AvgPool2DChip {}\n\nimpl<F: PrimeField> Averager<F> for AvgPool2DChip {\n  fn splat(&self, input: &AssignedTensor<F>, layer_config: &LayerConfig) -> Vec<Vec<CellRc<F>>> {\n    assert_eq!(input.shape().len(), 4);\n    // Don't support batch size > 1 yet\n    assert_eq!(input.shape()[0], 1);\n\n    // TODO: refactor this\n    MaxPool2DChip::splat(input, layer_config).unwrap()\n  }\n\n  fn get_div_val(\n    &self,\n    mut layouter: impl Layouter<F>,\n    _tensors: &Vec<AssignedTensor<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<AssignedCell<F, F>, Error> {\n    // FIXME: this needs to be revealed\n    let div = layer_config.layer_params[0] * layer_config.layer_params[1];\n    let div = F::from(div as u64);\n    let div = layouter\n      .assign_region(\n        || \"avg pool 2d div\",\n        |mut region| {\n          let div = region\n            .assign_advice(\n              || \"avg pool 2d div\",\n              gadget_config.columns[0],\n              0,\n              || Value::known(div),\n            )\n            .unwrap();\n          Ok(div)\n        },\n      )\n      .unwrap();\n\n    Ok(div)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for AvgPool2DChip {\n  fn forward(\n    &self,\n    layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let dived = self\n      .avg_forward(layouter, tensors, constants, gadget_config, layer_config)\n      .unwrap();\n\n    let inp = &tensors[0];\n    // TODO: refactor this\n    let out_xy = MaxPool2DChip::shape(inp, layer_config);\n    let out_shape = vec![1, out_xy.0, out_xy.1, inp.shape()[3]];\n    println!(\"out_shape: {:?}\", out_shape);\n\n    let out = Array::from_shape_vec(IxDyn(&out_shape), dived).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for AvgPool2DChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::Adder,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/batch_mat_mul.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, Axis, IxDyn};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::fully_connected::FullyConnectedConfig,\n};\n\nuse super::{\n  fully_connected::FullyConnectedChip,\n  layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig},\n};\n\npub struct BatchMatMulChip {}\n\nimpl<F: PrimeField> Layer<F> for BatchMatMulChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp1 = &tensors[0];\n    let inp2 = &tensors[1];\n    println!(\"inp1: {:?}\", inp1.shape());\n    println!(\"inp2: {:?}\", inp2.shape());\n\n    assert_eq!(inp1.ndim(), 3);\n    assert_eq!(inp2.ndim(), 3);\n    assert_eq!(inp1.shape()[0], inp2.shape()[0]);\n\n    let adj_y = layer_config.layer_params[1] == 1;\n    if adj_y {\n      assert_eq!(inp1.shape()[2], inp2.shape()[2]);\n    } else {\n      assert_eq!(inp1.shape()[2], inp2.shape()[1]);\n    }\n\n    let out_shape = if adj_y {\n      vec![inp1.shape()[0], inp1.shape()[1], inp2.shape()[1]]\n    } else {\n      vec![inp1.shape()[0], inp1.shape()[1], inp2.shape()[2]]\n    };\n\n    let fc_chip = FullyConnectedChip::<F> {\n      _marker: PhantomData,\n      config: FullyConnectedConfig::construct(true),\n    };\n\n    let mut outp: Vec<CellRc<F>> = vec![];\n    for i in 0..inp1.shape()[0] {\n      let inp1_slice = inp1.index_axis(Axis(0), i).to_owned();\n      // Due to tensorflow BS, transpose the \"weights\"\n      let inp2_slice = if adj_y {\n        inp2.index_axis(Axis(0), i).to_owned()\n      } else {\n        inp2.index_axis(Axis(0), i).t().to_owned()\n      };\n      println!(\"inp1_slice: {:?}\", inp1_slice.shape());\n      println!(\"inp2_slice: {:?}\", inp2_slice.shape());\n      // Batch MM doesn't have a fused activation, so insert it here\n      // TODO: consider putting this in the converter?\n      let tmp_config = LayerConfig {\n        layer_params: vec![0],\n        ..layer_config.clone()\n      };\n      let outp_slice = fc_chip.forward(\n        layouter.namespace(|| \"\"),\n        &vec![inp1_slice, inp2_slice],\n        constants,\n        gadget_config.clone(),\n        &tmp_config,\n      )?;\n      outp.extend(outp_slice[0].iter().map(|x| x.clone()).collect::<Vec<_>>());\n    }\n\n    let outp = Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap();\n    Ok(vec![outp])\n  }\n}\n\nimpl GadgetConsumer for BatchMatMulChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::Adder,\n      GadgetType::DotProduct,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/conv2d.rs",
        "content": "// TODO: Speed up Depthwise operations with Freivald's algorithm\n\nuse std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    bias_div_round_relu6::BiasDivRoundRelu6Chip,\n    dot_prod::DotProductChip,\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    nonlinear::relu::ReluChip,\n  },\n  layers::{\n    fully_connected::{FullyConnectedChip, FullyConnectedConfig},\n    shape::pad::pad,\n  },\n};\n\nuse super::layer::{ActivationType, AssignedTensor, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Default, Clone, Copy, Eq, PartialEq)]\npub enum PaddingEnum {\n  #[default]\n  Same,\n  Valid,\n}\n\n#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]\npub enum ConvLayerEnum {\n  #[default]\n  Conv2D,\n  DepthwiseConv2D,\n}\n\npub struct Conv2DConfig {\n  pub conv_type: ConvLayerEnum,\n  pub padding: PaddingEnum,\n  pub activation: ActivationType,\n  pub stride: (usize, usize),\n}\n\npub struct Conv2DChip<F: PrimeField> {\n  pub config: LayerConfig,\n  pub _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField> Conv2DChip<F> {\n  // TODO: this is horrible. What's the best way to fix this?\n  pub fn param_vec_to_config(layer_params: Vec<i64>) -> Conv2DConfig {\n    let conv_type = match layer_params[0] {\n      0 => ConvLayerEnum::Conv2D,\n      1 => ConvLayerEnum::DepthwiseConv2D,\n      _ => panic!(\"Invalid conv type\"),\n    };\n    let padding = match layer_params[1] {\n      0 => PaddingEnum::Same,\n      1 => PaddingEnum::Valid,\n      _ => panic!(\"Invalid padding\"),\n    };\n    let activation = match layer_params[2] {\n      0 => ActivationType::None,\n      1 => ActivationType::Relu,\n      3 => ActivationType::Relu6,\n      _ => panic!(\"Invalid activation type\"),\n    };\n    let stride = (layer_params[3] as usize, layer_params[4] as usize);\n    Conv2DConfig {\n      conv_type,\n      padding,\n      activation,\n      stride,\n    }\n  }\n\n  pub fn get_padding(\n    h: usize,\n    w: usize,\n    si: usize,\n    sj: usize,\n    ci: usize,\n    cj: usize,\n  ) -> ((usize, usize), (usize, usize)) {\n    let ph = if h % si == 0 {\n      (ci as i64 - sj as i64).max(0)\n    } else {\n      (ci as i64 - (h % si) as i64).max(0)\n    } as usize;\n    let pw = if w % sj == 0 {\n      (cj as i64 - sj as i64).max(0)\n    } else {\n      (cj as i64 - (w % sj) as i64).max(0)\n    } as usize;\n    ((ph / 2, ph - ph / 2), (pw / 2, pw - pw / 2))\n  }\n\n  pub fn out_hw(\n    h: usize,\n    w: usize,\n    si: usize,\n    sj: usize,\n    ch: usize,\n    cw: usize,\n    padding: PaddingEnum,\n  ) -> (usize, usize) {\n    /*\n    println!(\n      \"H: {}, W: {}, SI: {}, SJ: {}, CH: {}, CW: {}\",\n      h, w, si, sj, ch, cw\n    );\n    */\n    // https://iq.opengenus.org/same-and-valid-padding/\n    match padding {\n      PaddingEnum::Same => ((h + si - 1) / si, (w + sj - 1) / sj),\n      // TODO: the above is probably correct, but we always have valid paddings\n      // PaddingEnum::Same => (h / si, w / sj),\n      PaddingEnum::Valid => ((h - ch) / si + 1, (w - cw) / sj + 1),\n    }\n  }\n\n  pub fn splat<G: Clone>(\n    &self,\n    tensors: &Vec<Array<Rc<G>, IxDyn>>,\n    zero: Rc<G>,\n  ) -> (Vec<Vec<Rc<G>>>, Vec<Vec<Rc<G>>>, Vec<Rc<G>>) {\n    // assert_eq!(tensors.len(), 3);\n    assert!(tensors.len() <= 3);\n\n    let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone());\n\n    let inp = &tensors[0];\n    let weights = &tensors[1];\n    let zero_arr = Array::from_elem(IxDyn(&vec![1]), zero.clone());\n    let biases = if tensors.len() == 3 {\n      &tensors[2]\n    } else {\n      &zero_arr\n    };\n\n    let h: usize = inp.shape()[1];\n    let w: usize = inp.shape()[2];\n\n    let ch: usize = weights.shape()[1];\n    let cw: usize = weights.shape()[2];\n\n    let (si, sj) = conv_config.stride;\n\n    // B, H, W, C\n    assert_eq!(inp.shape().len(), 4);\n\n    let (ph, pw) = if conv_config.padding == PaddingEnum::Same {\n      Self::get_padding(h, w, si, sj, ch, cw)\n    } else {\n      ((0, 0), (0, 0))\n    };\n    // println!(\"Padding: {:?}\", (ph, pw));\n    let padding = vec![[0, 0], [ph.0, ph.1], [pw.0, pw.1], [0, 0]];\n\n    let inp_pad = pad(&inp, padding, &zero);\n\n    let (oh, ow) = Self::out_hw(h, w, si, sj, ch, cw, conv_config.padding);\n\n    let mut inp_cells = vec![];\n    let mut weights_cells = vec![];\n    let mut biases_cells = vec![];\n    let mut input_row_idx = 0;\n    let mut weight_row_idx = 0;\n\n    // (output_channels x inp_channels * C_H * C_W)\n    for chan_out in 0..weights.shape()[0] {\n      weights_cells.push(vec![]);\n      for ci in 0..weights.shape()[1] {\n        for cj in 0..weights.shape()[2] {\n          for ck in 0..weights.shape()[3] {\n            weights_cells[weight_row_idx].push(weights[[chan_out, ci, cj, ck]].clone());\n          }\n        }\n      }\n      weight_row_idx += 1;\n    }\n\n    // (O_H * O_W x inp_channels * C_H * C_W)\n    for batch in 0..inp.shape()[0] {\n      for i in 0..oh {\n        for j in 0..ow {\n          inp_cells.push(vec![]);\n          for ci in 0..weights.shape()[1] {\n            for cj in 0..weights.shape()[2] {\n              for ck in 0..weights.shape()[3] {\n                let idx_i = i * si + ci;\n                let idx_j = j * sj + cj;\n                inp_cells[input_row_idx].push(inp_pad[[batch, idx_i, idx_j, ck]].clone());\n              }\n            }\n          }\n          input_row_idx += 1;\n        }\n      }\n    }\n\n    for _batch in 0..inp.shape()[0] {\n      for _ in 0..oh {\n        for _ in 0..ow {\n          for chan_out in 0..weights.shape()[0] {\n            if tensors.len() == 3 {\n              biases_cells.push(biases[chan_out].clone());\n            } else {\n              biases_cells.push(zero.clone());\n            }\n          }\n        }\n      }\n    }\n\n    (inp_cells, weights_cells, biases_cells)\n  }\n\n  pub fn splat_depthwise<G: Clone>(\n    &self,\n    tensors: &Vec<Array<Rc<G>, IxDyn>>,\n    zero: Rc<G>,\n  ) -> (Vec<Vec<Rc<G>>>, Vec<Vec<Rc<G>>>, Vec<Rc<G>>) {\n    let input = &tensors[0];\n    let weights = &tensors[1];\n    let biases = &tensors[2];\n\n    assert_eq!(tensors.len(), 3);\n    assert_eq!(input.shape().len(), 4);\n    assert_eq!(weights.shape().len(), 4);\n    assert_eq!(input.shape()[0], 1);\n\n    let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone());\n    let strides = conv_config.stride;\n\n    let h: usize = input.shape()[1];\n    let w: usize = input.shape()[2];\n    let ch: usize = weights.shape()[1];\n    let cw: usize = weights.shape()[2];\n    let (si, sj) = conv_config.stride;\n    let (oh, ow) = Self::out_hw(h, w, si, sj, ch, cw, conv_config.padding);\n\n    let (ph, pw) = if conv_config.padding == PaddingEnum::Same {\n      Self::get_padding(h, w, si, sj, ch, cw)\n    } else {\n      ((0, 0), (0, 0))\n    };\n\n    let padding = vec![[0, 0], [ph.0, ph.1], [pw.0, pw.1], [0, 0]];\n\n    let inp_pad = pad(&input, padding, &zero);\n\n    let mut inp_cells = vec![];\n    let mut weight_cells = vec![];\n    let mut biases_cells = vec![];\n    let mut row_idx = 0;\n\n    for i in 0..oh {\n      for j in 0..ow {\n        for chan_out in 0..weights.shape()[3] {\n          inp_cells.push(vec![]);\n          weight_cells.push(vec![]);\n          biases_cells.push(biases[[chan_out]].clone());\n\n          for ci in 0..weights.shape()[1] {\n            for cj in 0..weights.shape()[2] {\n              let idx_i = i * strides.0 + ci;\n              let idx_j = j * strides.1 + cj;\n\n              inp_cells[row_idx].push(inp_pad[[0, idx_i, idx_j, chan_out]].clone());\n              weight_cells[row_idx].push(weights[[0, ci, cj, chan_out]].clone());\n            }\n          }\n\n          row_idx += 1;\n        }\n      }\n    }\n\n    (inp_cells, weight_cells, biases_cells)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for Conv2DChip<F> {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, Rc<AssignedCell<F, F>>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone());\n    let zero = constants.get(&0).unwrap();\n\n    let inp = &tensors[0];\n    let weights = &tensors[1];\n\n    let (oh, ow) = Self::out_hw(\n      inp.shape()[1],\n      inp.shape()[2],\n      conv_config.stride.0,\n      conv_config.stride.1,\n      weights.shape()[1],\n      weights.shape()[2],\n      conv_config.padding,\n    );\n    let batch_size = inp.shape()[0];\n\n    let (splat_inp, splat_weights, splat_biases) = match conv_config.conv_type {\n      ConvLayerEnum::Conv2D => self.splat(tensors, zero.clone()),\n      ConvLayerEnum::DepthwiseConv2D => self.splat_depthwise(tensors, zero.clone()),\n    };\n\n    let outp_flat: Vec<AssignedCell<F, F>> = match conv_config.conv_type {\n      ConvLayerEnum::Conv2D => {\n        let fc_chip = FullyConnectedChip::<F> {\n          _marker: PhantomData,\n          config: FullyConnectedConfig::construct(false),\n        };\n\n        let conv_size = splat_inp[0].len();\n        let flattened_inp: Vec<_> = splat_inp.into_iter().flat_map(|x| x.into_iter()).collect();\n        let flattened_weights = splat_weights\n          .into_iter()\n          .flat_map(|x| x.into_iter())\n          .collect::<Vec<_>>();\n\n        let out_channels = weights.shape()[0];\n        let inp_array =\n          Array::from_shape_vec(IxDyn(&vec![batch_size * oh * ow, conv_size]), flattened_inp)\n            .unwrap();\n        let weights_array =\n          Array::from_shape_vec(IxDyn(&vec![out_channels, conv_size]), flattened_weights).unwrap();\n\n        let outp_slice = fc_chip\n          .forward(\n            layouter.namespace(|| \"\"),\n            &vec![weights_array, inp_array],\n            constants,\n            gadget_config.clone(),\n            layer_config,\n          )\n          .unwrap();\n\n        let outp_flat = outp_slice[0]\n          .t()\n          .into_iter()\n          .map(|x| (**x).clone())\n          .collect::<Vec<_>>();\n        outp_flat\n      }\n      ConvLayerEnum::DepthwiseConv2D => {\n        // Do the dot products\n        let dot_prod_chip = DotProductChip::<F>::construct(gadget_config.clone());\n        let mut outp_flat = vec![];\n        for (inp_vec, weight_vec) in splat_inp.iter().zip(splat_weights.iter()) {\n          let inp_vec = inp_vec.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n          let weight_vec = weight_vec.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n          let vec_inputs = vec![inp_vec, weight_vec];\n          let constants = vec![zero.as_ref()];\n          let outp = dot_prod_chip\n            .forward(layouter.namespace(|| \"dot_prod\"), &vec_inputs, &constants)\n            .unwrap();\n          outp_flat.push(outp[0].clone());\n        }\n        // println!(\"outp_flat: {:?}\", outp_flat.len());\n\n        outp_flat\n      }\n    };\n\n    let mut biases = vec![];\n    for bias in splat_biases.iter() {\n      biases.push(bias.as_ref());\n    }\n\n    // Compute the bias + div + relu\n    let bdr_chip = BiasDivRoundRelu6Chip::<F>::construct(gadget_config.clone());\n    let tmp = vec![zero.as_ref()];\n    let outp_flat = outp_flat.iter().map(|x| x).collect::<Vec<_>>();\n    let outp = bdr_chip\n      .forward(\n        layouter.namespace(|| \"bias_div_relu\"),\n        &vec![outp_flat, biases],\n        &tmp,\n      )\n      .unwrap();\n\n    // TODO: this is also horrible. The bdr chip outputs interleaved [(relu'd, div'd), (relu'd, div'd), ...]\n    // Uninterleave depending on whether or not we're doing the relu\n    let outp = if conv_config.activation == ActivationType::Relu6 {\n      outp\n        .into_iter()\n        .step_by(2)\n        .map(|x| Rc::new(x))\n        .collect::<Vec<_>>()\n    } else if conv_config.activation == ActivationType::None {\n      outp\n        .into_iter()\n        .skip(1)\n        .step_by(2)\n        .map(|x| Rc::new(x))\n        .collect::<Vec<_>>()\n    } else if conv_config.activation == ActivationType::Relu {\n      let dived = outp.iter().skip(1).step_by(2).collect::<Vec<_>>();\n      let relu_chip = ReluChip::<F>::construct(gadget_config.clone());\n      let relu_outp = relu_chip\n        .forward(layouter.namespace(|| \"relu\"), &vec![dived], &tmp)\n        .unwrap();\n      let relu_outp = relu_outp\n        .into_iter()\n        .map(|x| Rc::new(x))\n        .collect::<Vec<_>>();\n      relu_outp\n    } else {\n      panic!(\"Unsupported activation type\");\n    };\n\n    let oc = match conv_config.conv_type {\n      ConvLayerEnum::Conv2D => weights.shape()[0],\n      ConvLayerEnum::DepthwiseConv2D => weights.shape()[3],\n    };\n\n    let out_shape = vec![batch_size, oh, ow, oc];\n    let outp = Array::from_shape_vec(IxDyn(&out_shape), outp).unwrap();\n\n    Ok(vec![outp])\n  }\n}\n\nimpl<F: PrimeField> GadgetConsumer for Conv2DChip<F> {\n  fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    let conv_config = &Self::param_vec_to_config(layer_params.clone());\n    let mut outp = vec![\n      GadgetType::Adder,\n      GadgetType::DotProduct,\n      GadgetType::InputLookup,\n      GadgetType::BiasDivRoundRelu6,\n    ];\n\n    if conv_config.activation == ActivationType::Relu {\n      outp.push(GadgetType::Relu);\n    }\n\n    outp\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/dag.rs",
        "content": "use std::{collections::HashMap, fs::File, io::BufWriter, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\n\nuse crate::{\n  gadgets::gadget::{convert_to_u64, GadgetConfig},\n  layers::{\n    arithmetic::{add::AddChip, div_var::DivVarChip, mul::MulChip, sub::SubChip},\n    batch_mat_mul::BatchMatMulChip,\n    div_fixed::DivFixedChip,\n    fully_connected::{FullyConnectedChip, FullyConnectedConfig},\n    logistic::LogisticChip,\n    max_pool_2d::MaxPool2DChip,\n    mean::MeanChip,\n    noop::NoopChip,\n    pow::PowChip,\n    rsqrt::RsqrtChip,\n    shape::{\n      broadcast::BroadcastChip, concatenation::ConcatenationChip, mask_neg_inf::MaskNegInfChip,\n      pack::PackChip, pad::PadChip, permute::PermuteChip, reshape::ReshapeChip,\n      resize_nn::ResizeNNChip, rotate::RotateChip, slice::SliceChip, split::SplitChip,\n      transpose::TransposeChip,\n    },\n    softmax::SoftmaxChip,\n    sqrt::SqrtChip,\n    square::SquareChip,\n    squared_diff::SquaredDiffChip,\n    tanh::TanhChip,\n    update::UpdateChip,\n  },\n  utils::helpers::print_assigned_arr,\n};\n\nuse super::{\n  avg_pool_2d::AvgPool2DChip,\n  conv2d::Conv2DChip,\n  layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig, LayerType},\n};\n\n#[derive(Clone, Debug, Default)]\npub struct DAGLayerConfig {\n  pub ops: Vec<LayerConfig>,\n  pub inp_idxes: Vec<Vec<usize>>,\n  pub out_idxes: Vec<Vec<usize>>,\n  pub final_out_idxes: Vec<usize>,\n}\n\npub struct DAGLayerChip<F: PrimeField + Ord> {\n  dag_config: DAGLayerConfig,\n  _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField + Ord> DAGLayerChip<F> {\n  pub fn construct(dag_config: DAGLayerConfig) -> Self {\n    Self {\n      dag_config,\n      _marker: PhantomData,\n    }\n  }\n\n  // IMPORTANT: Assumes input tensors are in order. Output tensors can be in any order.\n  pub fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<(HashMap<usize, AssignedTensor<F>>, Vec<AssignedTensor<F>>), Error> {\n    // Tensor map\n    let mut tensor_map = HashMap::new();\n    for (idx, tensor) in tensors.iter().enumerate() {\n      tensor_map.insert(idx, tensor.clone());\n    }\n\n    // Compute the dag\n    for (layer_idx, layer_config) in self.dag_config.ops.iter().enumerate() {\n      let layer_type = &layer_config.layer_type;\n      let inp_idxes = &self.dag_config.inp_idxes[layer_idx];\n      let out_idxes = &self.dag_config.out_idxes[layer_idx];\n      println!(\n        \"Processing layer {}, type: {:?}, inp_idxes: {:?}, out_idxes: {:?}, layer_params: {:?}\",\n        layer_idx, layer_type, inp_idxes, out_idxes, layer_config.layer_params\n      );\n      let vec_inps = inp_idxes\n        .iter()\n        .map(|idx| tensor_map.get(idx).unwrap().clone())\n        .collect::<Vec<_>>();\n\n      let out = match layer_type {\n        LayerType::Add => {\n          let add_chip = AddChip {};\n          add_chip.forward(\n            layouter.namespace(|| \"dag add\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::AvgPool2D => {\n          let avg_pool_2d_chip = AvgPool2DChip {};\n          avg_pool_2d_chip.forward(\n            layouter.namespace(|| \"dag avg pool 2d\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::MaxPool2D => {\n          let max_pool_2d_chip = MaxPool2DChip {\n            marker: PhantomData::<F>,\n          };\n          max_pool_2d_chip.forward(\n            layouter.namespace(|| \"dag max pool 2d\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::BatchMatMul => {\n          let batch_mat_mul_chip = BatchMatMulChip {};\n          batch_mat_mul_chip.forward(\n            layouter.namespace(|| \"dag batch mat mul\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Broadcast => {\n          let broadcast_chip = BroadcastChip {};\n          broadcast_chip.forward(\n            layouter.namespace(|| \"dag batch mat mul\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Conv2D => {\n          let conv_2d_chip = Conv2DChip {\n            config: layer_config.clone(),\n            _marker: PhantomData,\n          };\n          conv_2d_chip.forward(\n            layouter.namespace(|| \"dag conv 2d\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::DivFixed => {\n          let div_fixed_chip = DivFixedChip {};\n          div_fixed_chip.forward(\n            layouter.namespace(|| \"dag div\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::DivVar => {\n          let div_var_chip = DivVarChip {};\n          div_var_chip.forward(\n            layouter.namespace(|| \"dag div\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::FullyConnected => {\n          let fc_chip = FullyConnectedChip {\n            _marker: PhantomData,\n            config: FullyConnectedConfig::construct(true),\n          };\n          fc_chip.forward(\n            layouter.namespace(|| \"dag fully connected\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Softmax => {\n          let softmax_chip = SoftmaxChip {};\n          softmax_chip.forward(\n            layouter.namespace(|| \"dag softmax\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Mean => {\n          let mean_chip = MeanChip {};\n          mean_chip.forward(\n            layouter.namespace(|| \"dag mean\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Pad => {\n          let pad_chip = PadChip {};\n          pad_chip.forward(\n            layouter.namespace(|| \"dag pad\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Permute => {\n          let pad_chip = PermuteChip {};\n          pad_chip.forward(\n            layouter.namespace(|| \"dag permute\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::SquaredDifference => {\n          let squared_diff_chip = SquaredDiffChip {};\n          squared_diff_chip.forward(\n            layouter.namespace(|| \"dag squared diff\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Rsqrt => {\n          let rsqrt_chip = RsqrtChip {};\n          rsqrt_chip.forward(\n            layouter.namespace(|| \"dag rsqrt\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Sqrt => {\n          let sqrt_chip = SqrtChip {};\n          sqrt_chip.forward(\n            layouter.namespace(|| \"dag sqrt\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Logistic => {\n          let logistic_chip = LogisticChip {};\n          logistic_chip.forward(\n            layouter.namespace(|| \"dag logistic\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Pow => {\n          let pow_chip = PowChip {};\n          pow_chip.forward(\n            layouter.namespace(|| \"dag logistic\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Tanh => {\n          let tanh_chip = TanhChip {};\n          tanh_chip.forward(\n            layouter.namespace(|| \"dag tanh\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Mul => {\n          let mul_chip = MulChip {};\n          mul_chip.forward(\n            layouter.namespace(|| \"dag mul\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Sub => {\n          let sub_chip = SubChip {};\n          sub_chip.forward(\n            layouter.namespace(|| \"dag sub\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Noop => {\n          let noop_chip = NoopChip {};\n          noop_chip.forward(\n            layouter.namespace(|| \"dag noop\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Transpose => {\n          let transpose_chip = TransposeChip {};\n          transpose_chip.forward(\n            layouter.namespace(|| \"dag transpose\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Reshape => {\n          let reshape_chip = ReshapeChip {};\n          reshape_chip.forward(\n            layouter.namespace(|| \"dag reshape\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::ResizeNN => {\n          let resize_nn_chip = ResizeNNChip {};\n          resize_nn_chip.forward(\n            layouter.namespace(|| \"dag resize nn\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Rotate => {\n          let rotate_chip = RotateChip {};\n          rotate_chip.forward(\n            layouter.namespace(|| \"dag rotate\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Concatenation => {\n          let concat_chip = ConcatenationChip {};\n          concat_chip.forward(\n            layouter.namespace(|| \"dag concatenation\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Pack => {\n          let pack_chip = PackChip {};\n          pack_chip.forward(\n            layouter.namespace(|| \"dag pack\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Split => {\n          let split_chip = SplitChip {};\n          split_chip.forward(\n            layouter.namespace(|| \"dag split\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Update => {\n          let split_chip = UpdateChip {};\n          split_chip.forward(\n            layouter.namespace(|| \"dag update\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Slice => {\n          let slice_chip = SliceChip {};\n          slice_chip.forward(\n            layouter.namespace(|| \"dag slice\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::MaskNegInf => {\n          let mask_neg_inf_chip = MaskNegInfChip {};\n          mask_neg_inf_chip.forward(\n            layouter.namespace(|| \"dag mask neg inf\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n        LayerType::Square => {\n          let square_chip = SquareChip {};\n          square_chip.forward(\n            layouter.namespace(|| \"dag square\"),\n            &vec_inps,\n            constants,\n            gadget_config.clone(),\n            &layer_config,\n          )?\n        }\n      };\n\n      for (idx, tensor_idx) in out_idxes.iter().enumerate() {\n        println!(\"Out {} shape: {:?}\", idx, out[idx].shape());\n        tensor_map.insert(*tensor_idx, out[idx].clone());\n      }\n      println!();\n    }\n\n    let mut final_out = vec![];\n    for idx in self.dag_config.final_out_idxes.iter() {\n      final_out.push(tensor_map.get(idx).unwrap().clone());\n    }\n\n    let print_arr = if final_out.len() > 0 {\n      &final_out[0]\n    } else {\n      if self.dag_config.ops.len() > 0 {\n        let last_layer_idx = self.dag_config.ops.len() - 1;\n        let out_idx = self.dag_config.out_idxes[last_layer_idx][0];\n        tensor_map.get(&out_idx).unwrap()\n      } else {\n        tensor_map.get(&0).unwrap()\n      }\n    };\n\n    let tmp = print_arr.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    print_assigned_arr(\"final out\", &tmp.to_vec(), gadget_config.scale_factor);\n    println!(\"final out idxes: {:?}\", self.dag_config.final_out_idxes);\n\n    let mut x = vec![];\n    for cell in print_arr.iter() {\n      cell.value().map(|v| {\n        let bias = 1 << 60 as i64;\n        let v_pos = *v + F::from(bias as u64);\n        let v = convert_to_u64(&v_pos) as i64 - bias;\n        x.push(v);\n      });\n    }\n    if x.len() > 0 {\n      let out_fname = \"out.msgpack\";\n      let f = File::create(out_fname).unwrap();\n      let mut buf = BufWriter::new(f);\n      rmp_serde::encode::write_named(&mut buf, &x).unwrap();\n    }\n\n    Ok((tensor_map, final_out))\n  }\n}\n\nimpl<F: PrimeField + Ord> GadgetConsumer for DAGLayerChip<F> {\n  // Special case: DAG doesn't do anything\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/div_fixed.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Value},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  var_div::VarDivRoundChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct DivFixedChip {}\n\nimpl DivFixedChip {\n  fn get_div_val<F: PrimeField>(\n    &self,\n    mut layouter: impl Layouter<F>,\n    _tensors: &Vec<AssignedTensor<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<AssignedCell<F, F>, Error> {\n    // FIXME: this needs to be revealed\n    let div = layer_config.layer_params[0];\n    let div = F::from(div as u64);\n\n    let div = layouter\n      .assign_region(\n        || \"division\",\n        |mut region| {\n          let div = region\n            .assign_advice(\n              || \"avg pool 2d div\",\n              gadget_config.columns[0],\n              0,\n              || Value::known(div),\n            )\n            .unwrap();\n          Ok(div)\n        },\n      )\n      .unwrap();\n\n    Ok(div)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for DivFixedChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let inp_flat = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n\n    let zero = constants.get(&0).unwrap().as_ref();\n    let shape = inp.shape();\n\n    let div = self.get_div_val(\n      layouter.namespace(|| \"average div\"),\n      tensors,\n      gadget_config.clone(),\n      layer_config,\n    )?;\n\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n\n    let dived = var_div_chip.forward(\n      layouter.namespace(|| \"average div\"),\n      &vec![inp_flat],\n      &vec![zero, &div],\n    )?;\n    let dived = dived.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(shape), dived).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for DivFixedChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::VarDivRound]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/fully_connected.rs",
        "content": "use std::{collections::HashMap, marker::PhantomData, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Region, Value},\n  halo2curves::ff::PrimeField,\n  plonk::{Advice, Column, Error},\n};\nuse ndarray::{Array, ArrayView, Axis, IxDyn};\n\nuse crate::{\n  gadgets::{\n    add_pairs::AddPairsChip,\n    dot_prod::DotProductChip,\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    nonlinear::relu::ReluChip,\n    var_div::VarDivRoundChip,\n  },\n  layers::layer::ActivationType,\n  utils::helpers::RAND_START_IDX,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\npub struct FullyConnectedConfig {\n  pub normalize: bool, // Should be true\n}\n\nimpl FullyConnectedConfig {\n  pub fn construct(normalize: bool) -> Self {\n    Self { normalize }\n  }\n}\n\npub struct FullyConnectedChip<F: PrimeField> {\n  pub _marker: PhantomData<F>,\n  pub config: FullyConnectedConfig,\n}\n\nimpl<F: PrimeField> FullyConnectedChip<F> {\n  pub fn compute_mm(\n    // input: &AssignedTensor<F>,\n    input: &ArrayView<CellRc<F>, IxDyn>,\n    weight: &AssignedTensor<F>,\n  ) -> Array<Value<F>, IxDyn> {\n    assert_eq!(input.ndim(), 2);\n    assert_eq!(weight.ndim(), 2);\n    assert_eq!(input.shape()[1], weight.shape()[0]);\n\n    let mut outp = vec![];\n    for i in 0..input.shape()[0] {\n      for j in 0..weight.shape()[1] {\n        let mut sum = input[[i, 0]].value().map(|x: &F| *x) * weight[[0, j]].value();\n        for k in 1..input.shape()[1] {\n          sum = sum + input[[i, k]].value().map(|x: &F| *x) * weight[[k, j]].value();\n        }\n        outp.push(sum);\n      }\n    }\n\n    let out_shape = [input.shape()[0], weight.shape()[1]];\n    Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap()\n  }\n\n  pub fn assign_array(\n    columns: &Vec<Column<Advice>>,\n    region: &mut Region<F>,\n    array: &Array<Value<F>, IxDyn>,\n  ) -> Result<Array<AssignedCell<F, F>, IxDyn>, Error> {\n    assert_eq!(array.ndim(), 2);\n\n    let mut outp = vec![];\n    for (idx, val) in array.iter().enumerate() {\n      let row_idx = idx / columns.len();\n      let col_idx = idx % columns.len();\n      let cell = region\n        .assign_advice(|| \"assign array\", columns[col_idx], row_idx, || *val)\n        .unwrap();\n      outp.push(cell);\n    }\n\n    let out_shape = [array.shape()[0], array.shape()[1]];\n    Ok(Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap())\n  }\n\n  pub fn random_vector(\n    constants: &HashMap<i64, CellRc<F>>,\n    size: usize,\n  ) -> Result<Vec<CellRc<F>>, Error> {\n    let mut outp = vec![];\n    for idx in 0..size {\n      let idx = RAND_START_IDX + (idx as i64);\n      if !constants.contains_key(&idx) {\n        println!(\"Random vector is too small: {:?}\", size);\n      }\n      let cell = constants.get(&idx).unwrap().clone();\n      outp.push(cell);\n    }\n\n    Ok(outp)\n  }\n\n  fn get_activation(&self, layer_params: &Vec<i64>) -> ActivationType {\n    let activation = layer_params[0];\n    match activation {\n      0 => ActivationType::None,\n      1 => ActivationType::Relu,\n      _ => panic!(\"Unsupported activation type for fully connected\"),\n    }\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for FullyConnectedChip<F> {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    assert!(tensors.len() <= 3);\n    let activation = self.get_activation(&layer_config.layer_params);\n\n    let input = &tensors[0];\n    let ndim = input.ndim();\n    let input = if ndim == 2 {\n      ArrayView::from(input)\n    } else {\n      input.index_axis(Axis(0), 0)\n    };\n    let weight = &tensors[1].t().into_owned();\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    // Compute and assign the result\n    let mm_result = layouter\n      .assign_region(\n        || \"compute and assign mm\",\n        |mut region| {\n          let mm_result = Self::compute_mm(&input, weight);\n          let mm_result =\n            Self::assign_array(&gadget_config.columns, &mut region, &mm_result).unwrap();\n\n          Ok(mm_result)\n        },\n      )\n      .unwrap();\n\n    // Generate random vectors\n    let r1 = Self::random_vector(constants, mm_result.shape()[0]).unwrap();\n    let r2 = Self::random_vector(constants, mm_result.shape()[1]).unwrap();\n\n    let dot_prod_chip = DotProductChip::<F>::construct(gadget_config.clone());\n    let r1_ref = r1.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let r2_ref = r2.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n\n    // Compute r1 * result\n    let mut r1_res = vec![];\n    // println!(\"r1_ref: {:?}\", r1_ref.len());\n    // println!(\"r2_ref: {:?}\", r2_ref.len());\n    // println!(\"mm_result: {:?}\", mm_result.shape());\n    for i in 0..mm_result.shape()[1] {\n      let tmp = mm_result.index_axis(Axis(1), i);\n      let mm_ci = tmp.iter().collect::<Vec<_>>();\n      let r1_res_i = dot_prod_chip\n        .forward(\n          layouter.namespace(|| format!(\"r1_res_{}\", i)),\n          &vec![mm_ci, r1_ref.clone()],\n          &vec![zero],\n        )\n        .unwrap();\n      r1_res.push(r1_res_i[0].clone());\n    }\n\n    // Compute r1 * result * r2\n    let r1_res_ref = r1_res.iter().collect::<Vec<_>>();\n    let r1_res_r2 = dot_prod_chip\n      .forward(\n        layouter.namespace(|| \"r1_res_r2\"),\n        &vec![r1_res_ref, r2_ref.clone()],\n        &vec![zero],\n      )\n      .unwrap();\n    let r1_res_r2 = r1_res_r2[0].clone();\n    // println!(\"r1_res_r2: {:?}\", r1_res_r2);\n\n    // Compute r1 * input\n    let mut r1_input = vec![];\n    // println!(\"input: {:?}\", input.shape());\n    // println!(\"r1_ref: {:?}\", r1_ref.len());\n    for i in 0..input.shape()[1] {\n      let tmp = input.index_axis(Axis(1), i);\n      let input_ci = tmp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n      let r1_input_i = dot_prod_chip\n        .forward(\n          layouter.namespace(|| format!(\"r1_input_{}\", i)),\n          &vec![input_ci, r1_ref.clone()],\n          &vec![zero],\n        )\n        .unwrap();\n      r1_input.push(r1_input_i[0].clone());\n    }\n\n    // Compute weight * r2\n    let mut weight_r2 = vec![];\n    for i in 0..weight.shape()[0] {\n      let tmp = weight.index_axis(Axis(0), i);\n      let weight_ci = tmp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n      let weight_r2_i = dot_prod_chip\n        .forward(\n          layouter.namespace(|| format!(\"weight_r2_{}\", i)),\n          &vec![weight_ci, r2_ref.clone()],\n          &vec![zero],\n        )\n        .unwrap();\n      weight_r2.push(weight_r2_i[0].clone());\n    }\n\n    // Compute (r1 * input) * (weight * r2)\n    let r1_input_ref = r1_input.iter().collect::<Vec<_>>();\n    let weight_r2_ref = weight_r2.iter().collect::<Vec<_>>();\n    let r1_inp_weight_r2 = dot_prod_chip\n      .forward(\n        layouter.namespace(|| \"r1_inp_weight_r2\"),\n        &vec![r1_input_ref, weight_r2_ref],\n        &vec![zero],\n      )\n      .unwrap();\n\n    let r1_inp_weight_r2 = r1_inp_weight_r2[0].clone();\n    // println!(\"r1_inp_weight_r2: {:?}\", r1_inp_weight_r2);\n\n    layouter\n      .assign_region(\n        || \"fc equality check\",\n        |mut region| {\n          let t1 = r1_res_r2\n            .copy_advice(|| \"\", &mut region, gadget_config.columns[0], 0)\n            .unwrap();\n          let t2 = r1_inp_weight_r2\n            .copy_advice(|| \"\", &mut region, gadget_config.columns[0], 1)\n            .unwrap();\n\n          region.constrain_equal(t1.cell(), t2.cell()).unwrap();\n\n          Ok(())\n        },\n      )\n      .unwrap();\n\n    let shape = [mm_result.shape()[0], mm_result.shape()[1]];\n    let final_result_flat = if self.config.normalize {\n      let mm_flat = mm_result.iter().collect::<Vec<_>>();\n      let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n      let sf = constants\n        .get(&(gadget_config.scale_factor as i64))\n        .unwrap()\n        .as_ref();\n      let mm_div = var_div_chip\n        .forward(\n          layouter.namespace(|| \"mm_div\"),\n          &vec![mm_flat],\n          &vec![zero, sf],\n        )\n        .unwrap();\n\n      let mm_div = if tensors.len() == 3 {\n        let bias = tensors[2].broadcast(shape.clone()).unwrap();\n        let bias = bias.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n        let mm_div = mm_div.iter().collect::<Vec<_>>();\n        let adder_chip = AddPairsChip::<F>::construct(gadget_config.clone());\n        let mm_bias = adder_chip\n          .forward(\n            layouter.namespace(|| \"mm_bias\"),\n            &vec![mm_div, bias],\n            &vec![zero],\n          )\n          .unwrap();\n        mm_bias\n      } else {\n        mm_div\n      };\n\n      let mm_div = if activation == ActivationType::Relu {\n        let relu_chip = ReluChip::<F>::construct(gadget_config.clone());\n        let mm_div = mm_div.iter().collect::<Vec<_>>();\n        let vec_inputs = vec![mm_div];\n        relu_chip\n          .forward(layouter.namespace(|| \"relu\"), &vec_inputs, &vec![zero])\n          .unwrap()\n      } else if activation == ActivationType::None {\n        mm_div\n      } else {\n        panic!(\"Unsupported activation type\");\n      };\n\n      mm_div.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>()\n    } else {\n      mm_result\n        .into_iter()\n        .map(|x| Rc::new(x))\n        .collect::<Vec<_>>()\n    };\n    let final_result = Array::from_shape_vec(IxDyn(&shape), final_result_flat).unwrap();\n\n    Ok(vec![final_result])\n  }\n}\n\nimpl<F: PrimeField> GadgetConsumer for FullyConnectedChip<F> {\n  fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    let activation = self.get_activation(&layer_params);\n    let mut outp = vec![\n      GadgetType::Adder,\n      GadgetType::AddPairs,\n      GadgetType::DotProduct,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ];\n    match activation {\n      ActivationType::Relu => outp.push(GadgetType::Relu),\n      ActivationType::None => (),\n      _ => panic!(\"Unsupported activation type\"),\n    }\n    outp\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/layer.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::gadget::{GadgetConfig, GadgetType};\n\n#[derive(Clone, Copy, Debug, Default, Hash, Eq, PartialEq)]\npub enum LayerType {\n  Add,\n  AvgPool2D,\n  BatchMatMul,\n  Broadcast,\n  Concatenation,\n  Conv2D,\n  DivVar,\n  DivFixed,\n  FullyConnected,\n  Logistic,\n  MaskNegInf,\n  MaxPool2D,\n  Mean,\n  Mul,\n  #[default]\n  Noop,\n  Pack,\n  Pad,\n  Pow,\n  Permute,\n  Reshape,\n  ResizeNN,\n  Rotate,\n  Rsqrt,\n  Slice,\n  Softmax,\n  Split,\n  Sqrt,\n  Square,\n  SquaredDifference,\n  Sub,\n  Tanh,\n  Transpose,\n  Update,\n}\n\n// NOTE: This is the same order as the TFLite schema\n// Must not be changed\n#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)]\npub enum ActivationType {\n  #[default]\n  None,\n  Relu,\n  ReluN1To1,\n  Relu6,\n  Tanh,\n  SignBit,\n}\n\n#[derive(Clone, Debug, Default)]\npub struct LayerConfig {\n  pub layer_type: LayerType,\n  pub layer_params: Vec<i64>, // This is turned into layer specific configurations at runtime\n  pub inp_shapes: Vec<Vec<usize>>,\n  pub out_shapes: Vec<Vec<usize>>,\n  pub mask: Vec<i64>,\n}\n\npub type CellRc<F> = Rc<AssignedCell<F, F>>;\npub type AssignedTensor<F> = Array<CellRc<F>, IxDyn>;\n// General issue with rust: I'm not sure how to pass named arguments to a trait...\n// Currently, the caller must be aware of the order of the tensors and results\npub trait Layer<F: PrimeField> {\n  fn forward(\n    &self,\n    layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error>;\n}\n\npub trait GadgetConsumer {\n  fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<GadgetType>;\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/logistic.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  nonlinear::logistic::LogisticGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct LogisticChip {}\n\nimpl<F: PrimeField> Layer<F> for LogisticChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let logistic_chip = LogisticGadgetChip::<F>::construct(gadget_config.clone());\n    let vec_inps = vec![inp_vec];\n    let constants = vec![zero];\n    let out = logistic_chip.forward(\n      layouter.namespace(|| \"logistic chip\"),\n      &vec_inps,\n      &constants,\n    )?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for LogisticChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Logistic, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/max_pool_2d.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    max::MaxChip,\n  },\n  layers::conv2d::{Conv2DChip, PaddingEnum},\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\npub struct MaxPool2DChip<F: PrimeField> {\n  pub marker: std::marker::PhantomData<F>,\n}\n\nimpl<F: PrimeField> MaxPool2DChip<F> {\n  pub fn shape(inp: &AssignedTensor<F>, layer_config: &LayerConfig) -> (usize, usize) {\n    let params = &layer_config.layer_params;\n    let (fx, fy) = (params[0], params[1]);\n    let (fx, fy) = (fx as usize, fy as usize);\n    let (sx, sy) = (params[2], params[3]);\n    let (sx, sy) = (sx as usize, sy as usize);\n\n    // Only support batch size 1 for now\n    assert_eq!(inp.shape()[0], 1);\n\n    let out_shape = Conv2DChip::<F>::out_hw(\n      inp.shape()[1],\n      inp.shape()[2],\n      sx,\n      sy,\n      fx,\n      fy,\n      PaddingEnum::Valid,\n    );\n\n    out_shape\n  }\n\n  pub fn splat(\n    inp: &AssignedTensor<F>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<Vec<CellRc<F>>>, Error> {\n    let params = &layer_config.layer_params;\n    let (fx, fy) = (params[0], params[1]);\n    let (fx, fy) = (fx as usize, fy as usize);\n    let (sx, sy) = (params[2], params[3]);\n    let (sx, sy) = (sx as usize, sy as usize);\n\n    // Only support batch size 1 for now\n    assert_eq!(inp.shape()[0], 1);\n\n    let out_shape = Self::shape(inp, layer_config);\n\n    let mut splat = vec![];\n    for i in 0..out_shape.0 {\n      for j in 0..out_shape.1 {\n        for k in 0..inp.shape()[3] {\n          let mut tmp = vec![];\n          for x in 0..fx {\n            for y in 0..fy {\n              let x = i * sx + x;\n              let y = j * sy + y;\n              if x < inp.shape()[1] && y < inp.shape()[2] {\n                tmp.push(inp[[0, x, y, k]].clone());\n              }\n            }\n          }\n          splat.push(tmp);\n        }\n      }\n    }\n\n    Ok(splat)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for MaxPool2DChip<F> {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let splat = Self::splat(inp, layer_config).unwrap();\n\n    let max_chip = MaxChip::<F>::construct(gadget_config.clone());\n    let mut out = vec![];\n    for i in 0..splat.len() {\n      let inps = &splat[i];\n      let inps = inps.iter().map(|x| x.as_ref()).collect();\n      let max = max_chip\n        .forward(\n          layouter.namespace(|| format!(\"max {}\", i)),\n          &vec![inps],\n          &vec![],\n        )\n        .unwrap();\n      out.push(max[0].clone());\n    }\n    let out = out.into_iter().map(|x| Rc::new(x)).collect();\n\n    // TODO: refactor this\n    let out_xy = Self::shape(inp, layer_config);\n    let out_shape = vec![1, out_xy.0, out_xy.1, inp.shape()[3]];\n\n    let out = Array::from_shape_vec(IxDyn(&out_shape), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl<F: PrimeField> GadgetConsumer for MaxPool2DChip<F> {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> {\n    vec![GadgetType::Max, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/mean.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter, Value},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, Axis, IxDyn};\n\nuse crate::gadgets::gadget::{GadgetConfig, GadgetType};\n\nuse super::{\n  averager::Averager,\n  layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig},\n};\n\npub struct MeanChip {}\n\nimpl MeanChip {\n  pub fn get_keep_axis(&self, layer_config: &LayerConfig) -> usize {\n    let inp_shape = &layer_config.inp_shapes[0];\n    let out_shape = &layer_config.out_shapes[0];\n    assert_eq!(inp_shape[0], 1);\n    assert_eq!(out_shape[0], 1);\n\n    // Skip the batch axis\n    let mut keep_axes = (1..inp_shape.len()).collect::<Vec<_>>();\n    for mean_axis in layer_config.layer_params.iter() {\n      keep_axes.retain(|&x| x != *mean_axis as usize);\n    }\n    assert_eq!(keep_axes.len(), 1);\n    keep_axes[0]\n\n    /*\n    let mut num_same = 0;\n    let mut keep_axis: i64 = -1;\n    for i in 1..inp_shape.len() {\n      if inp_shape[i] == out_shape[i] {\n        keep_axis = i as i64;\n        num_same += 1;\n      }\n    }\n\n    if keep_axis == -1 {\n      panic!(\"All axes are different\");\n    }\n    if num_same > 1 {\n      panic!(\"More than one axis is the same\");\n    }\n    keep_axis as usize\n    */\n  }\n}\n\nimpl<F: PrimeField> Averager<F> for MeanChip {\n  fn splat(&self, input: &AssignedTensor<F>, layer_config: &LayerConfig) -> Vec<Vec<CellRc<F>>> {\n    // Only support batch size = 1\n    assert_eq!(input.shape()[0], 1);\n    // Only support batch + 2D, summing over one axis\n    // assert_eq!(input.shape().len(), 3);\n    let keep_axis = self.get_keep_axis(layer_config);\n\n    let mut splat = vec![];\n    for i in 0..input.shape()[keep_axis] {\n      let mut tmp = vec![];\n      for x in input.index_axis(Axis(keep_axis), i).iter() {\n        tmp.push(x.clone());\n      }\n      splat.push(tmp);\n    }\n\n    splat\n  }\n\n  fn get_div_val(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<AssignedCell<F, F>, Error> {\n    let inp = &tensors[0];\n    let keep_axis = self.get_keep_axis(layer_config);\n    let mut div = 1;\n    for i in 0..inp.shape().len() {\n      if i != keep_axis {\n        div *= inp.shape()[i];\n      }\n    }\n\n    let div = F::from(div as u64);\n    // FIXME: put this in the fixed column\n    let div = layouter.assign_region(\n      || \"mean div\",\n      |mut region| {\n        let div = region.assign_advice(\n          || \"mean div\",\n          gadget_config.columns[0],\n          0,\n          || Value::known(div),\n        )?;\n        Ok(div)\n      },\n    )?;\n\n    Ok(div)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for MeanChip {\n  fn forward(\n    &self,\n    layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let dived = self.avg_forward(layouter, tensors, constants, gadget_config, layer_config)?;\n\n    let out_shape = layer_config.out_shapes[0]\n      .iter()\n      .map(|x| *x as usize)\n      .collect::<Vec<_>>();\n\n    let out = Array::from_shape_vec(IxDyn(&out_shape), dived).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for MeanChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::Adder,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/noop.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\n\nuse crate::gadgets::gadget::GadgetConfig;\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\npub struct NoopChip {}\n\nimpl<F: PrimeField> Layer<F> for NoopChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let ret_idx = layer_config.layer_params[0] as usize;\n    Ok(vec![tensors[ret_idx].clone()])\n  }\n}\n\nimpl GadgetConsumer for NoopChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/pow.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  nonlinear::pow::PowGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct PowChip {}\n\nimpl<F: PrimeField> Layer<F> for PowChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let pow_chip = PowGadgetChip::<F>::construct(gadget_config.clone());\n    let vec_inps = vec![inp_vec];\n    let constants = vec![zero];\n    let out = pow_chip.forward(layouter.namespace(|| \"pow chip\"), &vec_inps, &constants)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for PowChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Pow, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/rsqrt.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  nonlinear::rsqrt::RsqrtGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct RsqrtChip {}\n\nimpl<F: PrimeField> Layer<F> for RsqrtChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let mut inp_vec = vec![];\n\n    let mask = &layer_config.mask;\n    let mut mask_map = HashMap::new();\n    for i in 0..mask.len() / 2 {\n      mask_map.insert(mask[2 * i], mask[2 * i + 1]);\n    }\n\n    let min_val = gadget_config.min_val;\n    let min_val = constants.get(&min_val).unwrap().as_ref();\n    let max_val = gadget_config.max_val;\n    let max_val = constants.get(&max_val).unwrap().as_ref();\n    for (i, val) in inp.iter().enumerate() {\n      let i = i as i64;\n      if mask_map.contains_key(&i) {\n        let mask_val = *mask_map.get(&i).unwrap();\n        if mask_val == 1 {\n          inp_vec.push(max_val);\n        } else if mask_val == -1 {\n          inp_vec.push(min_val);\n        } else {\n          panic!();\n        }\n      } else {\n        inp_vec.push(val.as_ref());\n      }\n    }\n\n    let zero = constants.get(&0).unwrap().as_ref();\n    let rsqrt_chip = RsqrtGadgetChip::<F>::construct(gadget_config.clone());\n    let vec_inps = vec![inp_vec];\n    let constants = vec![zero, min_val, max_val];\n    let out = rsqrt_chip.forward(layouter.namespace(|| \"rsqrt chip\"), &vec_inps, &constants)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for RsqrtChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Rsqrt, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape.rs",
        "content": "pub mod broadcast;\npub mod concatenation;\npub mod mask_neg_inf;\npub mod pack;\npub mod pad;\npub mod permute;\npub mod reshape;\npub mod resize_nn;\npub mod rotate;\npub mod slice;\npub mod split;\npub mod transpose;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/broadcast.rs",
        "content": "//\n// Broadcast is used as a temporary measure to represent a the backprop\n// of a full-kernel AvgPool2D\n//\n\nuse std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::Array;\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct BroadcastChip {}\n\n// TODO: Fix this after demo\nimpl<F: PrimeField> Layer<F> for BroadcastChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let shape = inp.shape();\n    let output_shape = layer_config.out_shapes[0].clone();\n\n    // Check that we only broadcast dimensions with shape 1\n    assert!(shape.len() == output_shape.len());\n    assert!(shape.len() == 4);\n\n    for (inp, outp) in shape.iter().zip(output_shape.iter()) {\n      if *inp != *outp && !(*inp == 1) {\n        panic!();\n      }\n    }\n\n    let mut output_flat = vec![];\n\n    for i in 0..output_shape[0] {\n      for j in 0..output_shape[1] {\n        for k in 0..output_shape[2] {\n          for l in 0..output_shape[3] {\n            let indexes = [i, j, k, l]\n              .iter()\n              .enumerate()\n              .map(|(idx, x)| if shape[idx] == 1 { 0 } else { *x })\n              .collect::<Vec<_>>();\n            output_flat.push(inp[[indexes[0], indexes[1], indexes[2], indexes[3]]].clone());\n          }\n        }\n      }\n    }\n\n    println!(\"Broadcast : {:?} -> {:?}\", inp.shape(), output_shape);\n    let out = Array::from_shape_vec(output_shape, output_flat).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for BroadcastChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/concatenation.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{concatenate, Axis};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct ConcatenationChip {}\n\nimpl<F: PrimeField> Layer<F> for ConcatenationChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let axis = layer_config.layer_params[0] as usize;\n    let views = tensors.iter().map(|x| x.view()).collect::<Vec<_>>();\n    // TODO: this is a bit of a hack\n    let out = concatenate(Axis(axis), views.as_slice()).unwrap_or(tensors[0].clone());\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for ConcatenationChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/mask_neg_inf.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct MaskNegInfChip {}\n\nimpl<F: PrimeField> Layer<F> for MaskNegInfChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let mask_ndim = layer_config.layer_params[0] as usize;\n    let mask_shape = layer_config.layer_params[1..mask_ndim + 1]\n      .iter()\n      .map(|x| *x as usize)\n      .collect::<Vec<_>>();\n\n    let mask_vec = layer_config.layer_params[mask_ndim + 1..].to_vec();\n    let mask = Array::from_shape_vec(IxDyn(&mask_shape), mask_vec).unwrap();\n    let mask = mask.broadcast(inp.raw_dim()).unwrap();\n\n    let min_val = gadget_config.min_val;\n    let min_val = constants.get(&min_val).unwrap().clone();\n    let mut out_vec = vec![];\n    for (val, to_mask) in inp.iter().zip(mask.iter()) {\n      if *to_mask == 0 {\n        out_vec.push(val.clone());\n      } else {\n        out_vec.push(min_val.clone());\n      }\n    }\n\n    let outp = Array::from_shape_vec(inp.raw_dim(), out_vec).unwrap();\n    Ok(vec![outp])\n  }\n}\n\nimpl GadgetConsumer for MaskNegInfChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/pack.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{concatenate, Axis};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct PackChip {}\n\nimpl<F: PrimeField> Layer<F> for PackChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let axis = layer_config.layer_params[0] as usize;\n    if axis > 1 {\n      panic!(\"Pack only supports axis=0 or axis=1\");\n    }\n\n    let expanded = tensors\n      .into_iter()\n      .map(|x| x.clone().insert_axis(Axis(axis)))\n      .collect::<Vec<_>>();\n    let views = expanded.iter().map(|x| x.view()).collect::<Vec<_>>();\n\n    // TODO: in some cases, the pack is unnecessary. Simply return the first tensor in this case\n    let out = concatenate(Axis(axis), views.as_slice()).unwrap_or(tensors[0].clone());\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for PackChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/pad.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{Array, Axis, IxDyn, Slice};\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\n// TODO: figure out where to put this\npub fn pad<G: Clone>(\n  input: &Array<Rc<G>, IxDyn>,\n  padding: Vec<[usize; 2]>,\n  pad_val: &Rc<G>,\n) -> Array<Rc<G>, IxDyn> {\n  let tmp = input.iter().collect();\n  let input = Array::from_shape_vec(input.raw_dim(), tmp).unwrap();\n  assert_eq!(input.ndim(), padding.len());\n  let mut padded_shape = input.raw_dim();\n  for (ax, (&ax_len, &[pad_lo, pad_hi])) in input.shape().iter().zip(&padding).enumerate() {\n    padded_shape[ax] = ax_len + pad_lo + pad_hi;\n  }\n\n  let mut padded = Array::from_elem(padded_shape, pad_val);\n  let padded_dim = padded.raw_dim();\n  {\n    // Select portion of padded array that needs to be copied from the\n    // original array.\n    let mut orig_portion = padded.view_mut();\n    for (ax, &[pad_lo, pad_hi]) in padding.iter().enumerate() {\n      orig_portion.slice_axis_inplace(\n        Axis(ax),\n        Slice::from(pad_lo as isize..padded_dim[ax] as isize - (pad_hi as isize)),\n      );\n    }\n    // Copy the data from the original array.\n    orig_portion.assign(&input.view());\n  }\n\n  let dim = padded.raw_dim();\n  let tmp = padded.into_iter().map(|x| x.clone()).collect();\n  let padded = Array::from_shape_vec(dim, tmp).unwrap();\n\n  padded\n}\n\npub struct PadChip {}\n\npub struct PadConfig {\n  pub padding: Vec<[usize; 2]>,\n}\n\nimpl PadChip {\n  pub fn param_vec_to_config(layer_params: Vec<i64>) -> PadConfig {\n    assert!(layer_params.len() % 2 == 0);\n\n    let padding = layer_params\n      .chunks(2)\n      .map(|chunk| [chunk[0] as usize, chunk[1] as usize])\n      .collect();\n    PadConfig { padding }\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for PadChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, Rc<AssignedCell<F, F>>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    // FIXME: the pad from tflite is actually two, but mine is one\n    // assert_eq!(tensors.len(), 1);\n    let input = &tensors[0];\n\n    let zero = constants.get(&0).unwrap().clone();\n    let padding = PadChip::param_vec_to_config(layer_config.layer_params.clone());\n    let padded = pad(input, padding.padding, &zero);\n\n    Ok(vec![padded])\n  }\n}\n\nimpl GadgetConsumer for PadChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/permute.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::IxDyn;\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct PermuteChip {}\n\nimpl<F: PrimeField> Layer<F> for PermuteChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let params = &layer_config\n      .layer_params\n      .iter()\n      .map(|x| *x as usize)\n      .collect::<Vec<_>>()[..];\n\n    assert!(inp.ndim() == params.len());\n\n    let out = inp.clone();\n    let out = out.permuted_axes(IxDyn(params));\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for PermuteChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/reshape.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::Array;\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct ReshapeChip {}\n\nimpl<F: PrimeField> Layer<F> for ReshapeChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let shape = layer_config.out_shapes[0].clone();\n\n    println!(\"Reshape: {:?} -> {:?}\", inp.shape(), shape);\n    let flat = inp.iter().map(|x| x.clone()).collect();\n    let out = Array::from_shape_vec(shape, flat).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for ReshapeChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/resize_nn.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct ResizeNNChip {}\n\n// TODO: this does not work in general\nimpl<F: PrimeField> Layer<F> for ResizeNNChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let output_shape = layer_config.out_shapes[0].clone();\n\n    assert_eq!(inp.ndim(), 4);\n    assert_eq!(inp.shape()[0], 1);\n    assert_eq!(inp.shape()[3], output_shape[3]);\n\n    let mut flat = vec![];\n    // Do nearest neighbor interpolation over batch, h, w, c\n    // The interpolation is over h and w\n    for b in 0..inp.shape()[0] {\n      for h in 0..output_shape[1] {\n        let h_in = (h as f64 * (inp.shape()[1] as f64 / output_shape[1] as f64)) as usize;\n        for w in 0..output_shape[2] {\n          let w_in = (w as f64 * (inp.shape()[2] as f64 / output_shape[2] as f64)) as usize;\n          for c in 0..inp.shape()[3] {\n            flat.push(inp[[b, h_in, w_in, c]].clone());\n          }\n        }\n      }\n    }\n\n    let outp = Array::from_shape_vec(IxDyn(&output_shape), flat).unwrap();\n    Ok(vec![outp])\n  }\n}\n\nimpl GadgetConsumer for ResizeNNChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/rotate.rs",
        "content": "// TODO: The implementation is not ideal.\n\nuse std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct RotateChip {}\n\n// Example:\n// input:\n// [1 2 3 4]\n// [5 6 7 8]\n//\n// params: [1] -- flip axis 1 only\n// output:\n// [4 3 2 1]\n// [8 7 6 5]\nimpl<F: PrimeField> Layer<F> for RotateChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let params = &layer_config.layer_params;\n\n    assert!(inp.shape().len() == 4);\n\n    let mut flip = vec![false; 4];\n    for p in params {\n      flip[*p as usize] = true;\n    }\n    let shape = inp.shape();\n\n    println!(\"Rotate: {:?} -> {:?}\", inp.shape(), shape);\n\n    let mut out = inp.clone();\n\n    for i in 0..shape[0] {\n      for j in 0..shape[1] {\n        for k in 0..shape[2] {\n          for l in 0..shape[3] {\n            let [ix, jx, kx, lx]: [usize; 4] = [i, j, k, l]\n              .iter()\n              .enumerate()\n              .map(|(idx, x)| if flip[idx] { shape[idx] - 1 - *x } else { *x })\n              .collect::<Vec<_>>()\n              .try_into()\n              .unwrap();\n            out[[ix, jx, kx, lx]] = inp[[i, j, k, l]].clone();\n          }\n        }\n      }\n    }\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for RotateChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/slice.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::Slice;\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct SliceChip {}\n\nimpl<F: PrimeField> Layer<F> for SliceChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let params = &layer_config.layer_params;\n    assert_eq!(params.len() % 2, 0);\n    let num_axes = params.len() / 2;\n    let starts = &params[0..num_axes];\n    let sizes = &params[num_axes..];\n\n    let inp = &tensors[0];\n    let outp = inp.slice_each_axis(|ax| {\n      let start = starts[ax.axis.0] as usize;\n      let size = sizes[ax.axis.0];\n      if size == -1 {\n        Slice::from(start..)\n      } else {\n        Slice::from(start..(start + size as usize))\n      }\n    });\n    Ok(vec![outp.to_owned()])\n  }\n}\n\nimpl GadgetConsumer for SliceChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/split.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Axis, Slice};\n\nuse crate::{\n  gadgets::gadget::{GadgetConfig, GadgetType},\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct SplitChip {}\n\nimpl<F: PrimeField> Layer<F> for SplitChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let axis = layer_config.layer_params[0] as usize;\n    let num_splits = layer_config.layer_params[1] as usize;\n    let inp = &tensors[1];\n\n    let mut out = vec![];\n    let split_len = inp.shape()[axis] / num_splits;\n    for i in 0..num_splits {\n      let slice = inp\n        .slice_axis(\n          Axis(axis),\n          Slice::from((i * split_len)..((i + 1) * split_len)),\n        )\n        .to_owned();\n      out.push(slice.to_owned());\n    }\n    Ok(out)\n  }\n}\n\nimpl GadgetConsumer for SplitChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/shape/transpose.rs",
        "content": "use std::{collections::HashMap, rc::Rc};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::gadget::GadgetConfig,\n  layers::layer::{AssignedTensor, CellRc, GadgetConsumer},\n};\n\nuse super::super::layer::{Layer, LayerConfig};\n\npub struct TransposeChip {}\n\nimpl<F: PrimeField> Layer<F> for TransposeChip {\n  fn forward(\n    &self,\n    _layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    _constants: &HashMap<i64, CellRc<F>>,\n    _gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    assert_eq!(layer_config.layer_params.len() % 2, 0);\n    let ndim = layer_config.layer_params.len() / 2;\n    let inp_shape = layer_config.layer_params[0..ndim]\n      .to_vec()\n      .iter()\n      .map(|x| *x as usize)\n      .collect::<Vec<_>>();\n    let permutation = layer_config.layer_params[ndim..]\n      .to_vec()\n      .iter()\n      .map(|x| *x as usize)\n      .collect::<Vec<_>>();\n\n    let inp = &tensors[0];\n    // Required because of memory layout issues\n    let inp_flat = inp.iter().cloned().collect::<Vec<_>>();\n    let inp = Array::from_shape_vec(IxDyn(&inp_shape), inp_flat).unwrap();\n\n    let inp = inp.permuted_axes(IxDyn(&permutation));\n\n    Ok(vec![inp])\n  }\n}\n\nimpl GadgetConsumer for TransposeChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/softmax.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{\n  circuit::{AssignedCell, Layouter},\n  halo2curves::ff::PrimeField,\n  plonk::Error,\n};\nuse ndarray::{s, Array, IxDyn};\n\nuse crate::gadgets::{\n  adder::AdderChip,\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  max::MaxChip,\n  nonlinear::exp::ExpGadgetChip,\n  sub_pairs::SubPairsChip,\n  var_div_big3::VarDivRoundBig3Chip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct SoftmaxChip {}\n\nimpl SoftmaxChip {\n  pub fn softmax_flat<F: PrimeField>(\n    mut layouter: impl Layouter<F>,\n    constants: &HashMap<i64, CellRc<F>>,\n    inp_flat: Vec<&AssignedCell<F, F>>,\n    gadget_config: Rc<GadgetConfig>,\n    mask: &Vec<i64>,\n  ) -> Result<Vec<AssignedCell<F, F>>, Error> {\n    let exp_chip = ExpGadgetChip::<F>::construct(gadget_config.clone());\n    let adder_chip = AdderChip::<F>::construct(gadget_config.clone());\n    let sub_pairs_chip = SubPairsChip::<F>::construct(gadget_config.clone());\n    let max_chip = MaxChip::<F>::construct(gadget_config.clone());\n    let var_div_big_chip = VarDivRoundBig3Chip::<F>::construct(gadget_config.clone());\n\n    let zero = constants.get(&0).unwrap().as_ref();\n    let sf = constants\n      .get(&(gadget_config.scale_factor as i64))\n      .unwrap()\n      .as_ref();\n\n    // Mask the input for max computation and subtraction\n    let inp_take = inp_flat\n      .iter()\n      .enumerate()\n      .filter(|(i, _)| mask[*i] == 0) // Awkwardly, 1 = take negative infinity\n      .map(|(_, x)| *x)\n      .collect::<Vec<_>>();\n\n    // Compute the max\n    let max = max_chip\n      .forward(\n        layouter.namespace(|| format!(\"max\")),\n        &vec![inp_take.clone()],\n        &vec![zero],\n      )\n      .unwrap();\n    let max = &max[0];\n\n    // Subtract the max\n    let max_flat = vec![max; inp_take.len()];\n    let sub = sub_pairs_chip.forward(\n      layouter.namespace(|| format!(\"sub\")),\n      &vec![inp_take, max_flat],\n      &vec![zero],\n    )?;\n\n    let sub = sub.iter().collect::<Vec<_>>();\n\n    // Compute the exp\n    let exp_slice = exp_chip.forward(\n      layouter.namespace(|| format!(\"exp\")),\n      &vec![sub],\n      &vec![zero],\n    )?;\n\n    // Compute the sum\n    let sum = adder_chip.forward(\n      layouter.namespace(|| format!(\"sum\")),\n      &vec![exp_slice.iter().collect()],\n      &vec![zero],\n    )?;\n    let sum = sum[0].clone();\n    let sum_div_sf = var_div_big_chip.forward(\n      layouter.namespace(|| format!(\"sum div sf\")),\n      &vec![vec![&sum]],\n      &vec![zero, sf],\n    )?;\n    let sum_div_sf = sum_div_sf[0].clone();\n\n    let dived = var_div_big_chip.forward(\n      layouter.namespace(|| format!(\"div\")),\n      &vec![exp_slice.iter().collect()],\n      &vec![zero, &sum_div_sf],\n    )?;\n\n    // Take either zero (softmax(-inf)) or the result\n    let mut div_idx = 0;\n    let dived = mask\n      .iter()\n      .map(|x| {\n        if *x == 1 {\n          zero.clone()\n        } else {\n          let tmp = dived[div_idx].clone();\n          div_idx = div_idx + 1;\n          tmp\n        }\n      })\n      .collect();\n\n    Ok(dived)\n  }\n}\n\nimpl<F: PrimeField> Layer<F> for SoftmaxChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    assert!(inp.ndim() == 2 || inp.ndim() == 3 || inp.ndim() == 4);\n    if inp.ndim() == 4 {\n      assert_eq!(inp.shape()[0], 1);\n    }\n\n    let inp_shape = inp.shape().iter().map(|x| *x).collect::<Vec<_>>();\n    let mask = if layer_config.layer_params.len() == 0 {\n      Array::from_shape_fn(IxDyn(&inp_shape), |_| 0)\n    } else {\n      let mask_shape_len = layer_config.layer_params[0] as usize;\n      let mask_shape = layer_config.layer_params[1..(1 + mask_shape_len)]\n        .iter()\n        .map(|x| *x as usize)\n        .collect::<Vec<_>>();\n      let mask = layer_config.layer_params[(1 + mask_shape_len)..].to_vec();\n      let mask = Array::from_shape_vec(IxDyn(&mask_shape), mask).unwrap();\n      let mask = mask.broadcast(IxDyn(&inp_shape)).unwrap().to_owned();\n      mask\n    };\n\n    let shape = if inp.ndim() == 2 || inp.ndim() == 3 {\n      inp.shape().iter().map(|x| *x).collect::<Vec<_>>()\n    } else {\n      vec![inp.shape()[1], inp.shape()[2], inp.shape()[3]]\n    };\n    let inp = inp.to_owned().into_shape(shape.clone()).unwrap();\n    let mask = mask.into_shape(shape.clone()).unwrap();\n\n    let mut outp = vec![];\n    if inp.ndim() == 2 {\n      for i in 0..shape[0] {\n        let inp_slice = inp.slice(s![i, ..]);\n        let inp_flat = inp_slice.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n        let mask_slice = mask.slice(s![i, ..]);\n        let mask_flat = mask_slice.iter().map(|x| *x as i64).collect::<Vec<_>>();\n        let dived = Self::softmax_flat(\n          layouter.namespace(|| format!(\"softmax {}\", i)),\n          constants,\n          inp_flat,\n          gadget_config.clone(),\n          &mask_flat,\n        )\n        .unwrap();\n        outp.extend(dived);\n      }\n    } else if inp.ndim() == 3 {\n      for i in 0..shape[0] {\n        for j in 0..shape[1] {\n          let inp_slice = inp.slice(s![i, j, ..]);\n          let inp_flat = inp_slice.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n          let mask_slice = mask.slice(s![i, j, ..]);\n          let mask_flat = mask_slice.iter().map(|x| *x as i64).collect::<Vec<_>>();\n          let dived = Self::softmax_flat(\n            layouter.namespace(|| format!(\"softmax {} {}\", i, j)),\n            constants,\n            inp_flat,\n            gadget_config.clone(),\n            &mask_flat,\n          )\n          .unwrap();\n          outp.extend(dived);\n        }\n      }\n    } else {\n      panic!(\"Not implemented\");\n    }\n\n    let outp = outp.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let outp = Array::from_shape_vec(IxDyn(inp.shape()), outp).unwrap();\n    Ok(vec![outp])\n  }\n}\n\nimpl GadgetConsumer for SoftmaxChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::Exp,\n      GadgetType::Adder,\n      GadgetType::VarDivRoundBig3,\n      GadgetType::Max,\n      GadgetType::SubPairs,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/sqrt.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  nonlinear::sqrt::SqrtGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct SqrtChip {}\n\nimpl<F: PrimeField> Layer<F> for SqrtChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let mut inp_vec = vec![];\n\n    let mask = &layer_config.mask;\n    let mut mask_map = HashMap::new();\n    for i in 0..mask.len() / 2 {\n      mask_map.insert(mask[2 * i], mask[2 * i + 1]);\n    }\n\n    let min_val = gadget_config.min_val;\n    let min_val = constants.get(&min_val).unwrap().as_ref();\n    let max_val = gadget_config.max_val;\n    let max_val = constants.get(&max_val).unwrap().as_ref();\n    for (i, val) in inp.iter().enumerate() {\n      let i = i as i64;\n      if mask_map.contains_key(&i) {\n        let mask_val = *mask_map.get(&i).unwrap();\n        if mask_val == 1 {\n          inp_vec.push(max_val);\n        } else if mask_val == -1 {\n          inp_vec.push(min_val);\n        } else {\n          panic!();\n        }\n      } else {\n        inp_vec.push(val.as_ref());\n      }\n    }\n\n    let zero = constants.get(&0).unwrap().as_ref();\n    let sqrt_chip = SqrtGadgetChip::<F>::construct(gadget_config.clone());\n    let vec_inps = vec![inp_vec];\n    let constants = vec![zero, min_val, max_val];\n    let out = sqrt_chip.forward(layouter.namespace(|| \"sqrt chip\"), &vec_inps, &constants)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for SqrtChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Sqrt, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/square.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  square::SquareGadgetChip,\n  var_div::VarDivRoundChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct SquareChip {}\n\nimpl<F: PrimeField> Layer<F> for SquareChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    assert_eq!(tensors.len(), 1);\n\n    let inp = &tensors[0];\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let square_chip = SquareGadgetChip::<F>::construct(gadget_config.clone());\n    let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let vec_inputs = vec![inp_vec];\n    let single_inps = vec![zero];\n    let out = square_chip.forward(\n      layouter.namespace(|| \"square chip\"),\n      &vec_inputs,\n      &single_inps,\n    )?;\n\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n    let div = constants\n      .get(&(gadget_config.scale_factor as i64))\n      .unwrap()\n      .as_ref();\n    let single_inps = vec![zero, div];\n    let out = out.iter().collect::<Vec<_>>();\n    let vec_inputs = vec![out];\n    let out = var_div_chip.forward(\n      layouter.namespace(|| \"var div chip\"),\n      &vec_inputs,\n      &single_inps,\n    )?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for SquareChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::Square,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/squared_diff.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::{\n  gadgets::{\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    squared_diff::SquaredDiffGadgetChip,\n    var_div::VarDivRoundChip,\n  },\n  utils::helpers::broadcast,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct SquaredDiffChip {}\n\nimpl<F: PrimeField> Layer<F> for SquaredDiffChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    assert_eq!(tensors.len(), 2);\n    let inp1 = &tensors[0];\n    let inp2 = &tensors[1];\n    // Broadcoasting allowed... can't check shapes easily\n    let (inp1, inp2) = broadcast(inp1, inp2);\n\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let sq_diff_chip = SquaredDiffGadgetChip::<F>::construct(gadget_config.clone());\n    let inp1_vec = inp1.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let inp2_vec = inp2.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let vec_inputs = vec![inp1_vec, inp2_vec];\n    let tmp_constants = vec![zero];\n    let out = sq_diff_chip.forward(\n      layouter.namespace(|| \"sq diff chip\"),\n      &vec_inputs,\n      &tmp_constants,\n    )?;\n\n    let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone());\n    let div = constants\n      .get(&(gadget_config.scale_factor as i64))\n      .unwrap()\n      .as_ref();\n\n    let single_inputs = vec![zero, div];\n    let out = out.iter().map(|x| x).collect::<Vec<_>>();\n    let out = var_div_chip.forward(\n      layouter.namespace(|| \"sq diff div\"),\n      &vec![out],\n      &single_inputs,\n    )?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp1.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for SquaredDiffChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![\n      GadgetType::SquaredDiff,\n      GadgetType::VarDivRound,\n      GadgetType::InputLookup,\n    ]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/tanh.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  nonlinear::tanh::TanhGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct TanhChip {}\n\nimpl<F: PrimeField> Layer<F> for TanhChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let inp = &tensors[0];\n    let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>();\n    let zero = constants.get(&0).unwrap().as_ref();\n\n    let tanh_chip = TanhGadgetChip::<F>::construct(gadget_config.clone());\n    let vec_inps = vec![inp_vec];\n    let constants = vec![zero];\n    let out = tanh_chip.forward(layouter.namespace(|| \"tanh chip\"), &vec_inps, &constants)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for TanhChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Tanh, GadgetType::InputLookup]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/layers/update.rs",
        "content": "use std::{collections::HashMap, rc::Rc, vec};\n\nuse halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error};\nuse ndarray::{Array, IxDyn};\n\nuse crate::gadgets::{\n  gadget::{Gadget, GadgetConfig, GadgetType},\n  update::UpdateGadgetChip,\n};\n\nuse super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig};\n\n#[derive(Clone, Debug)]\npub struct UpdateChip {}\n\nimpl<F: PrimeField + Ord> Layer<F> for UpdateChip {\n  fn forward(\n    &self,\n    mut layouter: impl Layouter<F>,\n    tensors: &Vec<AssignedTensor<F>>,\n    constants: &HashMap<i64, CellRc<F>>,\n    gadget_config: Rc<GadgetConfig>,\n    _layer_config: &LayerConfig,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let w = &tensors[0];\n    let dw = &tensors[1];\n\n    let zero = constants.get(&0).unwrap().as_ref();\n    let update_chip = UpdateGadgetChip::<F>::construct((*gadget_config).clone());\n\n    let flattened_w = w.into_iter().map(|x| (**x).clone()).collect::<Vec<_>>();\n    let flattened_dw = dw.into_iter().map(|x| (**x).clone()).collect::<Vec<_>>();\n    let flattened_w_ref = flattened_w.iter().collect::<Vec<_>>();\n    let flattened_dw_ref = flattened_dw.iter().collect::<Vec<_>>();\n\n    let vec_inps = vec![flattened_w_ref, flattened_dw_ref];\n    let constants = vec![zero];\n    let out = update_chip.forward(layouter.namespace(|| \"update chip\"), &vec_inps, &constants)?;\n\n    let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>();\n    let out = Array::from_shape_vec(IxDyn(w.shape()), out).unwrap();\n\n    Ok(vec![out])\n  }\n}\n\nimpl GadgetConsumer for UpdateChip {\n  fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> {\n    vec![GadgetType::Update]\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/lib.rs",
        "content": "#![feature(int_roundings)]\n\npub mod commitments;\npub mod gadgets;\npub mod layers;\npub mod model;\npub mod utils;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/model.rs",
        "content": "use std::{\n  collections::{BTreeMap, BTreeSet, HashMap},\n  marker::PhantomData,\n  rc::Rc,\n  sync::{Arc, Mutex},\n};\n\nuse halo2_proofs::{\n  circuit::{Layouter, SimpleFloorPlanner, Value},\n  halo2curves::ff::{FromUniformBytes, PrimeField},\n  plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance},\n};\nuse lazy_static::lazy_static;\nuse ndarray::{Array, IxDyn};\nuse num_bigint::BigUint;\n\nuse crate::{\n  commitments::{\n    commit::Commit,\n    packer::PackerChip,\n    poseidon_commit::{PoseidonCommitChip, L, RATE, WIDTH},\n  },\n  gadgets::{\n    add_pairs::AddPairsChip,\n    adder::AdderChip,\n    bias_div_round_relu6::BiasDivRoundRelu6Chip,\n    dot_prod::DotProductChip,\n    gadget::{Gadget, GadgetConfig, GadgetType},\n    input_lookup::InputLookupChip,\n    max::MaxChip,\n    mul_pairs::MulPairsChip,\n    nonlinear::{exp::ExpGadgetChip, pow::PowGadgetChip, relu::ReluChip, tanh::TanhGadgetChip},\n    nonlinear::{logistic::LogisticGadgetChip, rsqrt::RsqrtGadgetChip, sqrt::SqrtGadgetChip},\n    sqrt_big::SqrtBigChip,\n    square::SquareGadgetChip,\n    squared_diff::SquaredDiffGadgetChip,\n    sub_pairs::SubPairsChip,\n    update::UpdateGadgetChip,\n    var_div::VarDivRoundChip,\n    var_div_big::VarDivRoundBigChip,\n    var_div_big3::VarDivRoundBig3Chip,\n  },\n  layers::{\n    arithmetic::{add::AddChip, div_var::DivVarChip, mul::MulChip, sub::SubChip},\n    avg_pool_2d::AvgPool2DChip,\n    batch_mat_mul::BatchMatMulChip,\n    conv2d::Conv2DChip,\n    dag::{DAGLayerChip, DAGLayerConfig},\n    fully_connected::{FullyConnectedChip, FullyConnectedConfig},\n    layer::{AssignedTensor, CellRc, GadgetConsumer, LayerConfig, LayerType},\n    logistic::LogisticChip,\n    max_pool_2d::MaxPool2DChip,\n    mean::MeanChip,\n    noop::NoopChip,\n    pow::PowChip,\n    rsqrt::RsqrtChip,\n    shape::{\n      broadcast::BroadcastChip, concatenation::ConcatenationChip, mask_neg_inf::MaskNegInfChip,\n      pack::PackChip, pad::PadChip, permute::PermuteChip, reshape::ReshapeChip,\n      resize_nn::ResizeNNChip, rotate::RotateChip, slice::SliceChip, split::SplitChip,\n      transpose::TransposeChip,\n    },\n    softmax::SoftmaxChip,\n    sqrt::SqrtChip,\n    square::SquareChip,\n    squared_diff::SquaredDiffChip,\n    tanh::TanhChip,\n    update::UpdateChip,\n  },\n  utils::{\n    helpers::{convert_to_bigint, RAND_START_IDX},\n    loader::{load_model_msgpack, ModelMsgpack},\n  },\n};\n\nlazy_static! {\n  pub static ref GADGET_CONFIG: Mutex<GadgetConfig> = Mutex::new(GadgetConfig::default());\n  pub static ref PUBLIC_VALS: Mutex<Vec<BigUint>> = Mutex::new(vec![]);\n}\n\n#[derive(Clone, Debug, Default)]\npub struct ModelCircuit<F: PrimeField> {\n  pub used_gadgets: Arc<BTreeSet<GadgetType>>,\n  pub dag_config: DAGLayerConfig,\n  pub tensors: BTreeMap<i64, Array<F, IxDyn>>,\n  pub commit_before: Vec<Vec<i64>>,\n  pub commit_after: Vec<Vec<i64>>,\n  pub k: usize,\n  pub bits_per_elem: usize,\n  pub inp_idxes: Vec<i64>,\n  pub num_random: i64,\n}\n\n#[derive(Clone, Debug)]\npub struct ModelConfig<F: PrimeField + Ord + FromUniformBytes<64>> {\n  pub gadget_config: Rc<GadgetConfig>,\n  pub public_col: Column<Instance>,\n  pub hasher: Option<PoseidonCommitChip<F, WIDTH, RATE, L>>,\n  pub _marker: PhantomData<F>,\n}\n\nimpl<F: PrimeField + Ord + FromUniformBytes<64>> ModelCircuit<F> {\n  pub fn assign_tensors_map(\n    &self,\n    mut layouter: impl Layouter<F>,\n    columns: &Vec<Column<Advice>>,\n    tensors: &BTreeMap<i64, Array<F, IxDyn>>,\n  ) -> Result<BTreeMap<i64, AssignedTensor<F>>, Error> {\n    let tensors = layouter.assign_region(\n      || \"asssignment\",\n      |mut region| {\n        let mut cell_idx = 0;\n        let mut assigned_tensors = BTreeMap::new();\n\n        for (tensor_idx, tensor) in tensors.iter() {\n          let mut flat = vec![];\n          for val in tensor.iter() {\n            let row_idx = cell_idx / columns.len();\n            let col_idx = cell_idx % columns.len();\n            let cell = region\n              .assign_advice(\n                || \"assignment\",\n                columns[col_idx],\n                row_idx,\n                || Value::known(*val),\n              )\n              .unwrap();\n            flat.push(Rc::new(cell));\n            cell_idx += 1;\n          }\n          let tensor = Array::from_shape_vec(tensor.shape(), flat).unwrap();\n          assigned_tensors.insert(*tensor_idx, tensor);\n        }\n\n        Ok(assigned_tensors)\n      },\n    )?;\n\n    Ok(tensors)\n  }\n\n  pub fn tensor_map_to_vec(\n    &self,\n    tensor_map: &BTreeMap<i64, Array<CellRc<F>, IxDyn>>,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let smallest_tensor = tensor_map\n      .iter()\n      .min_by_key(|(_, tensor)| tensor.len())\n      .unwrap()\n      .1;\n    let max_tensor_key = tensor_map\n      .iter()\n      .max_by_key(|(key, _)| *key)\n      .unwrap()\n      .0\n      .clone();\n    let mut tensors = vec![];\n    for i in 0..max_tensor_key + 1 {\n      let tensor = tensor_map.get(&i).unwrap_or(smallest_tensor);\n      tensors.push(tensor.clone());\n    }\n\n    Ok(tensors)\n  }\n\n  pub fn assign_tensors_vec(\n    &self,\n    mut layouter: impl Layouter<F>,\n    columns: &Vec<Column<Advice>>,\n    tensors: &BTreeMap<i64, Array<F, IxDyn>>,\n  ) -> Result<Vec<AssignedTensor<F>>, Error> {\n    let tensor_map = self\n      .assign_tensors_map(\n        layouter.namespace(|| \"assign_tensors_map\"),\n        columns,\n        tensors,\n      )\n      .unwrap();\n    self.tensor_map_to_vec(&tensor_map)\n  }\n\n  pub fn assign_constants(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n  ) -> Result<HashMap<i64, CellRc<F>>, Error> {\n    let sf = gadget_config.scale_factor;\n    let min_val = gadget_config.min_val;\n    let max_val = gadget_config.max_val;\n\n    let constants = layouter.assign_region(\n      || \"constants\",\n      |mut region| {\n        let mut constants: HashMap<i64, CellRc<F>> = HashMap::new();\n\n        let vals = vec![0 as i64, 1, sf as i64, min_val, max_val];\n        let shift_val_i64 = -min_val * 2; // FIXME\n        let shift_val_f = F::from(shift_val_i64 as u64);\n        for (i, val) in vals.iter().enumerate() {\n          let cell = region.assign_fixed(\n            || format!(\"constant_{}\", i),\n            gadget_config.fixed_columns[0],\n            i,\n            || Value::known(F::from((val + shift_val_i64) as u64) - shift_val_f),\n          )?;\n          constants.insert(*val, Rc::new(cell));\n        }\n\n        // TODO: I've made some very bad life decisions\n        // TOOD: this needs to be a random oracle\n        let r_base = F::from(0x123456789abcdef);\n        let mut r = r_base.clone();\n        for i in 0..self.num_random {\n          let rand = region.assign_fixed(\n            || format!(\"rand_{}\", i),\n            gadget_config.fixed_columns[0],\n            constants.len(),\n            || Value::known(r),\n          )?;\n          r = r * r_base;\n          constants.insert(RAND_START_IDX + (i as i64), Rc::new(rand));\n        }\n\n        Ok(constants)\n      },\n    )?;\n    Ok(constants)\n  }\n\n  // TODO: for some horrifying reason, assigning to fixed columns causes everything to blow up\n  // Currently get around this by assigning to advice columns\n  // This is secure because of the equality checks but EXTREMELY STUPID\n  pub fn assign_constants2(\n    &self,\n    mut layouter: impl Layouter<F>,\n    gadget_config: Rc<GadgetConfig>,\n    fixed_constants: &HashMap<i64, CellRc<F>>,\n  ) -> Result<HashMap<i64, CellRc<F>>, Error> {\n    let sf = gadget_config.scale_factor;\n    let min_val = gadget_config.min_val;\n    let max_val = gadget_config.max_val;\n\n    let constants = layouter.assign_region(\n      || \"constants\",\n      |mut region| {\n        let mut constants: HashMap<i64, CellRc<F>> = HashMap::new();\n\n        let vals = vec![0 as i64, 1, sf as i64, min_val, max_val];\n        let shift_val_i64 = -min_val * 2; // FIXME\n        let shift_val_f = F::from(shift_val_i64 as u64);\n        for (i, val) in vals.iter().enumerate() {\n          let assignment_idx = i as usize;\n          let row_idx = assignment_idx / gadget_config.columns.len();\n          let col_idx = assignment_idx % gadget_config.columns.len();\n          let cell = region.assign_advice(\n            || format!(\"constant_{}\", i),\n            gadget_config.columns[col_idx],\n            row_idx,\n            || Value::known(F::from((val + shift_val_i64) as u64) - shift_val_f),\n          )?;\n          constants.insert(*val, Rc::new(cell));\n        }\n\n        // TODO: I've made some very bad life decisions\n        // TOOD: this needs to be a random oracle\n        let r_base = F::from(0x123456789abcdef);\n        let mut r = r_base.clone();\n        for i in 0..self.num_random {\n          let assignment_idx = constants.len();\n          let row_idx = assignment_idx / gadget_config.columns.len();\n          let col_idx = assignment_idx % gadget_config.columns.len();\n          let rand = region.assign_advice(\n            || format!(\"rand_{}\", i),\n            gadget_config.columns[col_idx],\n            row_idx,\n            || Value::known(r),\n          )?;\n          r = r * r_base;\n          constants.insert(RAND_START_IDX + (i as i64), Rc::new(rand));\n        }\n\n        for (k, v) in fixed_constants.iter() {\n          let v2 = constants.get(k).unwrap();\n          region.constrain_equal(v.cell(), v2.cell()).unwrap();\n        }\n        Ok(constants)\n      },\n    )?;\n    Ok(constants)\n  }\n\n  pub fn generate_from_file(config_file: &str, inp_file: &str) -> ModelCircuit<F> {\n    let config = load_model_msgpack(config_file, inp_file);\n    Self::generate_from_msgpack(config, true)\n  }\n\n  pub fn generate_from_msgpack(config: ModelMsgpack, panic_empty_tensor: bool) -> ModelCircuit<F> {\n    let to_field = |x: i64| {\n      let bias = 1 << 31;\n      let x_pos = x + bias;\n      F::from(x_pos as u64) - F::from(bias as u64)\n    };\n\n    let match_layer = |x: &str| match x {\n      \"AveragePool2D\" => LayerType::AvgPool2D,\n      \"Add\" => LayerType::Add,\n      \"BatchMatMul\" => LayerType::BatchMatMul,\n      \"Broadcast\" => LayerType::Broadcast,\n      \"Concatenation\" => LayerType::Concatenation,\n      \"Conv2D\" => LayerType::Conv2D,\n      \"Div\" => LayerType::DivFixed, // TODO: rename to DivFixed\n      \"DivVar\" => LayerType::DivVar,\n      \"FullyConnected\" => LayerType::FullyConnected,\n      \"Logistic\" => LayerType::Logistic,\n      \"MaskNegInf\" => LayerType::MaskNegInf,\n      \"MaxPool2D\" => LayerType::MaxPool2D,\n      \"Mean\" => LayerType::Mean,\n      \"Mul\" => LayerType::Mul,\n      \"Noop\" => LayerType::Noop,\n      \"Pack\" => LayerType::Pack,\n      \"Pad\" => LayerType::Pad,\n      \"Pow\" => LayerType::Pow,\n      \"Permute\" => LayerType::Permute,\n      \"Reshape\" => LayerType::Reshape,\n      \"ResizeNearestNeighbor\" => LayerType::ResizeNN,\n      \"Rotate\" => LayerType::Rotate,\n      \"Rsqrt\" => LayerType::Rsqrt,\n      \"Slice\" => LayerType::Slice,\n      \"Softmax\" => LayerType::Softmax,\n      \"Split\" => LayerType::Split,\n      \"Sqrt\" => LayerType::Sqrt,\n      \"Square\" => LayerType::Square,\n      \"SquaredDifference\" => LayerType::SquaredDifference,\n      \"Sub\" => LayerType::Sub,\n      \"Tanh\" => LayerType::Tanh,\n      \"Transpose\" => LayerType::Transpose,\n      \"Update\" => LayerType::Update,\n      _ => panic!(\"unknown op: {}\", x),\n    };\n\n    let mut tensors = BTreeMap::new();\n    for flat in config.tensors {\n      let value_flat = flat.data.iter().map(|x| to_field(*x)).collect::<Vec<_>>();\n      let shape = flat.shape.iter().map(|x| *x as usize).collect::<Vec<_>>();\n      let num_el: usize = shape.iter().product();\n      if panic_empty_tensor && num_el != value_flat.len() {\n        panic!(\"tensor shape and data length mismatch\");\n      }\n      if num_el == value_flat.len() {\n        let tensor = Array::from_shape_vec(IxDyn(&shape), value_flat).unwrap();\n        tensors.insert(flat.idx, tensor);\n      } else {\n        // Do nothing here since we're loading the config\n      };\n    }\n\n    let i64_to_usize = |x: &Vec<i64>| x.iter().map(|x| *x as usize).collect::<Vec<_>>();\n\n    let mut used_gadgets = BTreeSet::new();\n\n    let dag_config = {\n      let ops = config\n        .layers\n        .iter()\n        .map(|layer| {\n          let layer_type = match_layer(&layer.layer_type);\n          let layer_gadgets = match layer_type {\n            LayerType::Add => Box::new(AddChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::AvgPool2D => Box::new(AvgPool2DChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::BatchMatMul => Box::new(BatchMatMulChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Broadcast => Box::new(BroadcastChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Concatenation => Box::new(ConcatenationChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::DivFixed => Box::new(ConcatenationChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::DivVar => Box::new(DivVarChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Conv2D => Box::new(Conv2DChip {\n              config: LayerConfig::default(),\n              _marker: PhantomData::<F>,\n            }) as Box<dyn GadgetConsumer>,\n            LayerType::FullyConnected => Box::new(FullyConnectedChip {\n              config: FullyConnectedConfig { normalize: true },\n              _marker: PhantomData::<F>,\n            }) as Box<dyn GadgetConsumer>,\n            LayerType::Logistic => Box::new(LogisticChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::MaskNegInf => Box::new(MaskNegInfChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::MaxPool2D => Box::new(MaxPool2DChip {\n              marker: PhantomData::<F>,\n            }) as Box<dyn GadgetConsumer>,\n            LayerType::Mean => Box::new(MeanChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Mul => Box::new(MulChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Noop => Box::new(NoopChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Pack => Box::new(PackChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Pad => Box::new(PadChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Pow => Box::new(PowChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Permute => Box::new(PermuteChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Reshape => Box::new(ReshapeChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::ResizeNN => Box::new(ResizeNNChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Rotate => Box::new(RotateChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Rsqrt => Box::new(RsqrtChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Slice => Box::new(SliceChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Softmax => Box::new(SoftmaxChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Split => Box::new(SplitChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Sqrt => Box::new(SqrtChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Square => Box::new(SquareChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::SquaredDifference => Box::new(SquaredDiffChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Sub => Box::new(SubChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Tanh => Box::new(TanhChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Transpose => Box::new(TransposeChip {}) as Box<dyn GadgetConsumer>,\n            LayerType::Update => Box::new(UpdateChip {}) as Box<dyn GadgetConsumer>,\n          }\n          .used_gadgets(layer.params.clone());\n          for gadget in layer_gadgets {\n            used_gadgets.insert(gadget);\n          }\n\n          LayerConfig {\n            layer_type,\n            layer_params: layer.params.clone(),\n            inp_shapes: layer.inp_shapes.iter().map(|x| i64_to_usize(x)).collect(),\n            out_shapes: layer.out_shapes.iter().map(|x| i64_to_usize(x)).collect(),\n            mask: layer.mask.clone(),\n          }\n        })\n        .collect::<Vec<_>>();\n      let inp_idxes = config\n        .layers\n        .iter()\n        .map(|layer| i64_to_usize(&layer.inp_idxes))\n        .collect::<Vec<_>>();\n      let out_idxes = config\n        .layers\n        .iter()\n        .map(|layer| i64_to_usize(&layer.out_idxes))\n        .collect::<Vec<_>>();\n      let final_out_idxes = config\n        .out_idxes\n        .iter()\n        .map(|x| *x as usize)\n        .collect::<Vec<_>>();\n      DAGLayerConfig {\n        inp_idxes,\n        out_idxes,\n        ops,\n        final_out_idxes,\n      }\n    };\n\n    // The input lookup is always used\n    used_gadgets.insert(GadgetType::InputLookup);\n    let used_gadgets = Arc::new(used_gadgets);\n    let gadget = &GADGET_CONFIG;\n    let cloned_gadget = gadget.lock().unwrap().clone();\n    *gadget.lock().unwrap() = GadgetConfig {\n      scale_factor: config.global_sf as u64,\n      shift_min_val: -(config.global_sf * config.global_sf * (1 << 17)),\n      div_outp_min_val: -(1 << (config.k - 1)),\n      min_val: -(1 << (config.k - 1)),\n      max_val: (1 << (config.k - 1)) - 10,\n      k: config.k as usize,\n      num_rows: (1 << config.k) - 10 + 1,\n      num_cols: config.num_cols as usize,\n      used_gadgets: used_gadgets.clone(),\n      commit_before: config.commit_before.clone().unwrap_or(vec![]),\n      commit_after: config.commit_after.clone().unwrap_or(vec![]),\n      use_selectors: config.use_selectors.unwrap_or(true),\n      num_bits_per_elem: config.bits_per_elem.unwrap_or(config.k),\n      ..cloned_gadget\n    };\n\n    ModelCircuit {\n      tensors,\n      dag_config,\n      used_gadgets,\n      k: config.k as usize,\n      bits_per_elem: config.bits_per_elem.unwrap_or(config.k) as usize,\n      inp_idxes: config.inp_idxes.clone(),\n      commit_after: config.commit_after.unwrap_or(vec![]),\n      commit_before: config.commit_before.unwrap_or(vec![]),\n      num_random: config.num_random.unwrap_or(0),\n    }\n  }\n\n  pub fn assign_and_commit(\n    &self,\n    mut layouter: impl Layouter<F>,\n    constants: &HashMap<i64, CellRc<F>>,\n    config: &ModelConfig<F>,\n    tensors: &BTreeMap<i64, Array<F, IxDyn>>,\n  ) -> (BTreeMap<i64, AssignedTensor<F>>, CellRc<F>) {\n    let num_bits = self.bits_per_elem;\n    let packer_config = PackerChip::<F>::construct(num_bits, config.gadget_config.as_ref());\n    let packer_chip = PackerChip::<F> {\n      config: packer_config,\n    };\n    let (tensor_map, packed) = packer_chip\n      .assign_and_pack(\n        layouter.namespace(|| \"packer\"),\n        config.gadget_config.clone(),\n        constants,\n        tensors,\n      )\n      .unwrap();\n\n    let zero = constants.get(&0).unwrap().clone();\n    let commit_chip = config.hasher.clone().unwrap();\n\n    let commitments = commit_chip\n      .commit(\n        layouter.namespace(|| \"commit\"),\n        config.gadget_config.clone(),\n        constants,\n        &packed,\n        zero.clone(),\n      )\n      .unwrap();\n    assert_eq!(commitments.len(), 1);\n\n    (tensor_map, commitments[0].clone())\n  }\n\n  pub fn copy_and_commit(\n    &self,\n    mut layouter: impl Layouter<F>,\n    constants: &HashMap<i64, CellRc<F>>,\n    config: &ModelConfig<F>,\n    tensors: &BTreeMap<i64, AssignedTensor<F>>,\n  ) -> CellRc<F> {\n    let num_bits = self.bits_per_elem;\n    let packer_config = PackerChip::<F>::construct(num_bits, config.gadget_config.as_ref());\n    let packer_chip = PackerChip::<F> {\n      config: packer_config,\n    };\n    let packed = packer_chip\n      .copy_and_pack(\n        layouter.namespace(|| \"packer\"),\n        config.gadget_config.clone(),\n        constants,\n        tensors,\n      )\n      .unwrap();\n\n    let zero = constants.get(&0).unwrap().clone();\n    let commit_chip = config.hasher.clone().unwrap();\n\n    let commitments = commit_chip\n      .commit(\n        layouter.namespace(|| \"commit\"),\n        config.gadget_config.clone(),\n        constants,\n        &packed,\n        zero.clone(),\n      )\n      .unwrap();\n    assert_eq!(commitments.len(), 1);\n\n    commitments[0].clone()\n  }\n}\n\nimpl<F: PrimeField + Ord + FromUniformBytes<64>> Circuit<F> for ModelCircuit<F> {\n  type Config = ModelConfig<F>;\n  type FloorPlanner = SimpleFloorPlanner;\n  type Params = ();\n\n  fn without_witnesses(&self) -> Self {\n    todo!()\n  }\n\n  fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {\n    let mut gadget_config = crate::model::GADGET_CONFIG.lock().unwrap().clone();\n    let columns = (0..gadget_config.num_cols)\n      .map(|_| meta.advice_column())\n      .collect::<Vec<_>>();\n    for col in columns.iter() {\n      meta.enable_equality(*col);\n    }\n    gadget_config.columns = columns;\n\n    let public_col = meta.instance_column();\n    meta.enable_equality(public_col);\n\n    gadget_config.fixed_columns = vec![meta.fixed_column()];\n    meta.enable_equality(gadget_config.fixed_columns[0]);\n\n    // The input lookup is always loaded\n    gadget_config = InputLookupChip::<F>::configure(meta, gadget_config);\n\n    let used_gadgets = gadget_config.used_gadgets.clone();\n    for gadget_type in used_gadgets.iter() {\n      gadget_config = match gadget_type {\n        GadgetType::AddPairs => AddPairsChip::<F>::configure(meta, gadget_config),\n        GadgetType::Adder => AdderChip::<F>::configure(meta, gadget_config),\n        GadgetType::BiasDivRoundRelu6 => BiasDivRoundRelu6Chip::<F>::configure(meta, gadget_config),\n        GadgetType::BiasDivFloorRelu6 => panic!(),\n        GadgetType::DotProduct => DotProductChip::<F>::configure(meta, gadget_config),\n        GadgetType::Exp => ExpGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::Logistic => LogisticGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::Max => MaxChip::<F>::configure(meta, gadget_config),\n        GadgetType::MulPairs => MulPairsChip::<F>::configure(meta, gadget_config),\n        GadgetType::Pow => PowGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::Relu => ReluChip::<F>::configure(meta, gadget_config),\n        GadgetType::Rsqrt => RsqrtGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::Sqrt => SqrtGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::SqrtBig => SqrtBigChip::<F>::configure(meta, gadget_config),\n        GadgetType::Square => SquareGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::SquaredDiff => SquaredDiffGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::SubPairs => SubPairsChip::<F>::configure(meta, gadget_config),\n        GadgetType::Tanh => TanhGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::VarDivRound => VarDivRoundChip::<F>::configure(meta, gadget_config),\n        GadgetType::VarDivRoundBig => VarDivRoundBigChip::<F>::configure(meta, gadget_config),\n        GadgetType::VarDivRoundBig3 => VarDivRoundBig3Chip::<F>::configure(meta, gadget_config),\n        GadgetType::InputLookup => gadget_config, // This is always loaded\n        GadgetType::Update => UpdateGadgetChip::<F>::configure(meta, gadget_config),\n        GadgetType::Packer => panic!(),\n      };\n    }\n\n    let hasher = if gadget_config.commit_before.len() + gadget_config.commit_after.len() > 0 {\n      let packer_config =\n        PackerChip::<F>::construct(gadget_config.num_bits_per_elem as usize, &gadget_config);\n      gadget_config = PackerChip::<F>::configure(meta, packer_config, gadget_config);\n\n      // TODO\n      let input = gadget_config.columns[0..L].try_into().unwrap();\n      let state = gadget_config.columns[L..L + WIDTH].try_into().unwrap();\n      let partial_sbox = gadget_config.columns[L + WIDTH].into();\n      Some(PoseidonCommitChip::<F, WIDTH, RATE, L>::configure(\n        meta,\n        input,\n        state,\n        partial_sbox,\n      ))\n    } else {\n      None\n    };\n\n    ModelConfig {\n      gadget_config: gadget_config.into(),\n      public_col,\n      hasher,\n      _marker: PhantomData,\n    }\n  }\n\n  fn synthesize(&self, config: Self::Config, mut layouter: impl Layouter<F>) -> Result<(), Error> {\n    // Assign tables\n    let gadget_rc: Rc<GadgetConfig> = config.gadget_config.clone().into();\n    for gadget in self.used_gadgets.iter() {\n      match gadget {\n        GadgetType::AddPairs => {\n          let chip = AddPairsChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"add pairs lookup\"))?;\n        }\n        GadgetType::Adder => {\n          let chip = AdderChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"adder lookup\"))?;\n        }\n        GadgetType::BiasDivRoundRelu6 => {\n          let chip = BiasDivRoundRelu6Chip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"bias div round relu6 lookup\"))?;\n        }\n        GadgetType::DotProduct => {\n          let chip = DotProductChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"dot product lookup\"))?;\n        }\n        GadgetType::VarDivRound => {\n          let chip = VarDivRoundChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"var div lookup\"))?;\n        }\n        GadgetType::Pow => {\n          let chip = PowGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"pow lookup\"))?;\n        }\n        GadgetType::Relu => {\n          let chip = ReluChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"relu lookup\"))?;\n        }\n        GadgetType::Rsqrt => {\n          let chip = RsqrtGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"rsqrt lookup\"))?;\n        }\n        GadgetType::Sqrt => {\n          let chip = SqrtGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"sqrt lookup\"))?;\n        }\n        GadgetType::Tanh => {\n          let chip = TanhGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"tanh lookup\"))?;\n        }\n        GadgetType::Exp => {\n          let chip = ExpGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"exp lookup\"))?;\n        }\n        GadgetType::Logistic => {\n          let chip = LogisticGadgetChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"logistic lookup\"))?;\n        }\n        GadgetType::InputLookup => {\n          let chip = InputLookupChip::<F>::construct(gadget_rc.clone());\n          chip.load_lookups(layouter.namespace(|| \"input lookup\"))?;\n        }\n        GadgetType::VarDivRoundBig => {}\n        GadgetType::VarDivRoundBig3 => {}\n        GadgetType::Max => {}\n        GadgetType::MulPairs => {}\n        GadgetType::SqrtBig => {}\n        GadgetType::Square => {}\n        GadgetType::SquaredDiff => {}\n        GadgetType::SubPairs => {}\n        GadgetType::Update => {}\n        _ => panic!(\"unsupported gadget {:?}\", gadget),\n      }\n    }\n\n    // Assign weights and constants\n    let constants_base = self\n      .assign_constants(\n        layouter.namespace(|| \"constants\"),\n        config.gadget_config.clone(),\n      )\n      .unwrap();\n    // Some halo2 cancer\n    let constants = self\n      .assign_constants2(\n        layouter.namespace(|| \"constants 2\"),\n        config.gadget_config.clone(),\n        &constants_base,\n      )\n      .unwrap();\n\n    let mut commitments = vec![];\n    let tensors = if self.commit_before.len() > 0 {\n      // Commit to the tensors before the DAG\n      let mut tensor_map = BTreeMap::new();\n      let mut ignore_idxes: Vec<i64> = vec![];\n      for commit_idxes in self.commit_before.iter() {\n        let to_commit = BTreeMap::from_iter(\n          commit_idxes\n            .iter()\n            .map(|idx| (*idx, self.tensors.get(idx).unwrap().clone())),\n        );\n        let (mut committed_tensors, commitment) = self.assign_and_commit(\n          layouter.namespace(|| \"commit\"),\n          &constants,\n          &config,\n          &to_commit,\n        );\n        commitments.push(commitment);\n        tensor_map.append(&mut committed_tensors);\n        ignore_idxes.extend(commit_idxes.iter());\n      }\n\n      // Assign the remainder of the tensors\n      let mut assign_map = BTreeMap::new();\n      for (idx, tensor) in self.tensors.iter() {\n        if ignore_idxes.contains(idx) {\n          continue;\n        }\n        assign_map.insert(*idx, tensor.clone());\n      }\n      let mut remainder_tensor_map = self\n        .assign_tensors_map(\n          layouter.namespace(|| \"assignment\"),\n          &config.gadget_config.columns,\n          &assign_map,\n        )\n        .unwrap();\n\n      // Merge the two maps\n      tensor_map.append(&mut remainder_tensor_map);\n\n      // Return the tensors\n      self.tensor_map_to_vec(&tensor_map).unwrap()\n    } else {\n      self\n        .assign_tensors_vec(\n          layouter.namespace(|| \"assignment\"),\n          &config.gadget_config.columns,\n          &self.tensors,\n        )\n        .unwrap()\n    };\n\n    // Perform the dag\n    let dag_chip = DAGLayerChip::<F>::construct(self.dag_config.clone());\n    let (final_tensor_map, result) = dag_chip.forward(\n      layouter.namespace(|| \"dag\"),\n      &tensors,\n      &constants,\n      config.gadget_config.clone(),\n      &LayerConfig::default(),\n    )?;\n\n    if self.commit_after.len() > 0 {\n      for commit_idxes in self.commit_after.iter() {\n        let to_commit = BTreeMap::from_iter(commit_idxes.iter().map(|idx| {\n          (\n            *idx,\n            final_tensor_map.get(&(*idx as usize)).unwrap().clone(),\n          )\n        }));\n        let commitment = self.copy_and_commit(\n          layouter.namespace(|| \"commit\"),\n          &constants,\n          &config,\n          &to_commit,\n        );\n        commitments.push(commitment);\n      }\n    }\n\n    let mut pub_layouter = layouter.namespace(|| \"public\");\n    let mut total_idx = 0;\n    let mut new_public_vals = vec![];\n    for cell in commitments.iter() {\n      pub_layouter\n        .constrain_instance(cell.as_ref().cell(), config.public_col, total_idx)\n        .unwrap();\n      let val = convert_to_bigint(cell.value().map(|x| x.to_owned()));\n      new_public_vals.push(val);\n      total_idx += 1;\n    }\n    for tensor in result {\n      for cell in tensor.iter() {\n        pub_layouter\n          .constrain_instance(cell.as_ref().cell(), config.public_col, total_idx)\n          .unwrap();\n        let val = convert_to_bigint(cell.value().map(|x| x.to_owned()));\n        new_public_vals.push(val);\n        total_idx += 1;\n      }\n    }\n    *PUBLIC_VALS.lock().unwrap() = new_public_vals;\n\n    Ok(())\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/utils.rs",
        "content": "pub mod helpers;\npub mod loader;\npub mod proving_ipa;\npub mod proving_kzg;\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/utils/helpers.rs",
        "content": "use halo2_proofs::{\n  circuit::{AssignedCell, Value},\n  halo2curves::ff::PrimeField,\n};\nuse ndarray::{Array, IxDyn};\nuse num_bigint::BigUint;\n\nuse crate::{gadgets::gadget::convert_to_u128, model::PUBLIC_VALS};\n\n// TODO: this is very bad\npub const RAND_START_IDX: i64 = i64::MIN;\npub const NUM_RANDOMS: i64 = 20001;\n\n// Conversion / printing functions\npub fn convert_to_bigint<F: PrimeField>(x: Value<F>) -> BigUint {\n  let mut big = Default::default();\n  x.map(|x| {\n    big = BigUint::from_bytes_le(x.to_repr().as_ref());\n  });\n  big\n}\n\npub fn convert_pos_int<F: PrimeField>(x: Value<F>) -> i128 {\n  let bias = 1 << 60;\n  let x_pos = x + Value::known(F::from(bias as u64));\n  let mut outp: i128 = 0;\n  x_pos.map(|x| {\n    let x_pos = convert_to_u128(&x);\n    let tmp = x_pos as i128 - bias;\n    outp = tmp;\n  });\n  return outp;\n}\n\npub fn print_pos_int<F: PrimeField>(prefix: &str, x: Value<F>, scale_factor: u64) {\n  let tmp = convert_pos_int(x);\n  let tmp_float = tmp as f64 / scale_factor as f64;\n  println!(\"{} x: {} ({})\", prefix, tmp, tmp_float);\n}\n\npub fn print_assigned_arr<F: PrimeField>(\n  prefix: &str,\n  arr: &Vec<&AssignedCell<F, F>>,\n  scale_factor: u64,\n) {\n  for (idx, x) in arr.iter().enumerate() {\n    print_pos_int(\n      &format!(\"{}[{}]\", prefix, idx),\n      x.value().map(|x: &F| x.to_owned()),\n      scale_factor,\n    );\n  }\n}\n\n// Get the public values\npub fn get_public_values<F: PrimeField>() -> Vec<F> {\n  let mut public_vals = vec![];\n  for val in PUBLIC_VALS.lock().unwrap().iter() {\n    let val = F::from_str_vartime(&val.to_str_radix(10));\n    public_vals.push(val.unwrap());\n  }\n  public_vals\n}\n\n// Broadcast\nfn shape_dominates(s1: &[usize], s2: &[usize]) -> bool {\n  if s1.len() != s2.len() {\n    return false;\n  }\n\n  for (x1, x2) in s1.iter().zip(s2.iter()) {\n    if x1 < x2 {\n      return false;\n    }\n  }\n\n  true\n}\n\n// Precondition: s1.len() < s2.len()\nfn intermediate_shape(s1: &[usize], s2: &[usize]) -> Vec<usize> {\n  let mut res = vec![1; s2.len() - s1.len()];\n  for s in s1.iter() {\n    res.push(*s);\n  }\n  res\n}\n\nfn final_shape(s1: &[usize], s2: &[usize]) -> Vec<usize> {\n  let mut res = vec![];\n  for (x1, x2) in s1.iter().zip(s2.iter()) {\n    res.push(std::cmp::max(*x1, *x2));\n  }\n  res\n}\n\npub fn broadcast<G: Clone>(\n  x1: &Array<G, IxDyn>,\n  x2: &Array<G, IxDyn>,\n) -> (Array<G, IxDyn>, Array<G, IxDyn>) {\n  if x1.shape() == x2.shape() {\n    return (x1.clone(), x2.clone());\n  }\n\n  if x1.ndim() == x2.ndim() {\n    let s1 = x1.shape();\n    let s2 = x2.shape();\n    if shape_dominates(s1, s2) {\n      return (x1.clone(), x2.broadcast(s1).unwrap().into_owned());\n    } else if shape_dominates(x2.shape(), x1.shape()) {\n      return (x1.broadcast(s2).unwrap().into_owned(), x2.clone());\n    }\n  }\n\n  let (tmp1, tmp2) = if x1.ndim() < x2.ndim() {\n    (x1, x2)\n  } else {\n    (x2, x1)\n  };\n\n  // tmp1.ndim() < tmp2.ndim()\n  let s1 = tmp1.shape();\n  let s2 = tmp2.shape();\n  let s = intermediate_shape(s1, s2);\n  let final_shape = final_shape(s2, s.as_slice());\n\n  let tmp1 = tmp1.broadcast(s.clone()).unwrap().into_owned();\n  let tmp1 = tmp1.broadcast(final_shape.as_slice()).unwrap().into_owned();\n  let tmp2 = tmp2.broadcast(final_shape.as_slice()).unwrap().into_owned();\n  // println!(\"x1: {:?} x2: {:?}\", x1.shape(), x2.shape());\n  // println!(\"s1: {:?} s2: {:?} s: {:?}\", s1, s2, s);\n  // println!(\"tmp1 shape: {:?}\", tmp1.shape());\n  // println!(\"tmp2 shape: {:?}\", tmp2.shape());\n\n  if x1.ndim() < x2.ndim() {\n    return (tmp1, tmp2);\n  } else {\n    return (tmp2, tmp1);\n  }\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/utils/loader.rs",
        "content": "use std::{fs::File, io::BufReader};\n\nuse serde_derive::{Deserialize, Serialize};\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct TensorMsgpack {\n  pub idx: i64,\n  pub shape: Vec<i64>,\n  pub data: Vec<i64>,\n}\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct LayerMsgpack {\n  pub layer_type: String,\n  pub params: Vec<i64>,\n  pub inp_idxes: Vec<i64>,\n  pub inp_shapes: Vec<Vec<i64>>,\n  pub out_idxes: Vec<i64>,\n  pub out_shapes: Vec<Vec<i64>>,\n  pub mask: Vec<i64>,\n}\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct ModelMsgpack {\n  pub global_sf: i64,\n  pub k: i64,\n  pub num_cols: i64,\n  pub inp_idxes: Vec<i64>,\n  pub out_idxes: Vec<i64>,\n  pub tensors: Vec<TensorMsgpack>,\n  pub layers: Vec<LayerMsgpack>,\n  pub use_selectors: Option<bool>,\n  pub commit_before: Option<Vec<Vec<i64>>>,\n  pub commit_after: Option<Vec<Vec<i64>>>,\n  pub bits_per_elem: Option<i64>, // Specifically for packing for the commitments\n  pub num_random: Option<i64>,\n}\n\npub fn load_config_msgpack(config_path: &str) -> ModelMsgpack {\n  let model: ModelMsgpack = {\n    let file = File::open(config_path).unwrap();\n    let mut reader = BufReader::new(file);\n    rmp_serde::from_read(&mut reader).unwrap()\n  };\n  model\n}\n\npub fn load_model_msgpack(config_path: &str, inp_path: &str) -> ModelMsgpack {\n  let mut model = load_config_msgpack(config_path);\n  let inp: Vec<TensorMsgpack> = {\n    let file = File::open(inp_path).unwrap();\n    let mut reader = BufReader::new(file);\n    rmp_serde::from_read(&mut reader).unwrap()\n  };\n  for tensor in inp {\n    model.tensors.push(tensor);\n  }\n\n  // Default to using selectors, commit if use_selectors is not specified\n  if model.use_selectors.is_none() {\n    model.use_selectors = Some(true)\n  };\n  if model.commit_before.is_none() {\n    model.commit_before = Some(vec![])\n  };\n  if model.commit_after.is_none() {\n    model.commit_after = Some(vec![])\n  };\n  if model.bits_per_elem.is_none() {\n    model.bits_per_elem = Some(model.k)\n  };\n  if model.num_random.is_none() {\n    model.num_random = Some(20001)\n  };\n\n  model\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/utils/proving_ipa.rs",
        "content": "use std::{\n  fs::File,\n  io::{BufReader, Write},\n  path::Path,\n  time::Instant,\n};\n\nuse halo2_proofs::{\n  dev::MockProver,\n  halo2curves::pasta::{EqAffine, Fp},\n  plonk::{create_proof, keygen_pk, keygen_vk, verify_proof},\n  poly::{\n    commitment::{Params, ParamsProver},\n    ipa::{\n      commitment::{IPACommitmentScheme, ParamsIPA},\n      multiopen::ProverIPA,\n      strategy::SingleStrategy,\n    },\n    VerificationStrategy,\n  },\n  transcript::{\n    Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,\n  },\n};\n\nuse crate::{model::ModelCircuit, utils::helpers::get_public_values};\n\npub fn get_ipa_params(params_dir: &str, degree: u32) -> ParamsIPA<EqAffine> {\n  let path = format!(\"{}/{}.params\", params_dir, degree);\n  let params_path = Path::new(&path);\n  if File::open(&params_path).is_err() {\n    let params: ParamsIPA<EqAffine> = ParamsIPA::new(degree);\n    let mut buf = Vec::new();\n\n    params.write(&mut buf).expect(\"Failed to write params\");\n    let mut file = File::create(&params_path).expect(\"Failed to create params file\");\n    file\n      .write_all(&buf[..])\n      .expect(\"Failed to write params to file\");\n  }\n\n  let params_fs = File::open(&params_path).expect(\"couldn't load params\");\n  let params: ParamsIPA<EqAffine> =\n    Params::read::<_>(&mut BufReader::new(params_fs)).expect(\"Failed to read params\");\n  params\n}\n\npub fn time_circuit_ipa(circuit: ModelCircuit<Fp>) {\n  let rng = rand::thread_rng();\n  let start = Instant::now();\n\n  let degree = circuit.k as u32;\n  let empty_circuit = circuit.clone();\n  let proof_circuit = circuit;\n\n  let params = get_ipa_params(\"./params_ipa\", degree);\n\n  let circuit_duration = start.elapsed();\n  println!(\n    \"Time elapsed in params construction: {:?}\",\n    circuit_duration\n  );\n\n  let vk = keygen_vk(&params, &empty_circuit).unwrap();\n  let vk_duration = start.elapsed();\n  println!(\n    \"Time elapsed in generating vkey: {:?}\",\n    vk_duration - circuit_duration\n  );\n\n  let pk = keygen_pk(&params, vk, &empty_circuit).unwrap();\n  let pk_duration = start.elapsed();\n  println!(\n    \"Time elapsed in generating pkey: {:?}\",\n    pk_duration - vk_duration\n  );\n  drop(empty_circuit);\n\n  let fill_duration = start.elapsed();\n  let _prover = MockProver::run(degree, &proof_circuit, vec![vec![]]).unwrap();\n  let public_vals = get_public_values();\n  println!(\n    \"Time elapsed in filling circuit: {:?}\",\n    fill_duration - pk_duration\n  );\n\n  let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]);\n  create_proof::<IPACommitmentScheme<EqAffine>, ProverIPA<EqAffine>, _, _, _, _>(\n    &params,\n    &pk,\n    &[proof_circuit],\n    &[&[&public_vals]],\n    rng,\n    &mut transcript,\n  )\n  .unwrap();\n  let proof = transcript.finalize();\n  let proof_duration = start.elapsed();\n  println!(\"Proving time: {:?}\", proof_duration - fill_duration);\n\n  let proof_size = {\n    let mut folder = std::path::PathBuf::new();\n    folder.push(\"proof\");\n    let mut fd = std::fs::File::create(folder.as_path()).unwrap();\n    folder.pop();\n    fd.write_all(&proof).unwrap();\n    fd.metadata().unwrap().len()\n  };\n  println!(\"Proof size: {} bytes\", proof_size);\n\n  let strategy = SingleStrategy::new(&params);\n  let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]);\n  assert!(\n    verify_proof(\n      &params,\n      pk.get_vk(),\n      strategy,\n      &[&[&public_vals]],\n      &mut transcript\n    )\n    .is_ok(),\n    \"proof did not verify\"\n  );\n  let verify_duration = start.elapsed();\n  println!(\"Verifying time: {:?}\", verify_duration - proof_duration);\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "src/utils/proving_kzg.rs",
        "content": "use std::{\n  fs::File,\n  io::{BufReader, Write},\n  path::Path,\n  time::Instant,\n};\n\nuse halo2_proofs::{\n  dev::MockProver,\n  halo2curves::bn256::{Bn256, Fr, G1Affine},\n  plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, VerifyingKey},\n  poly::{\n    commitment::Params,\n    kzg::{\n      commitment::{KZGCommitmentScheme, ParamsKZG},\n      multiopen::{ProverSHPLONK, VerifierSHPLONK},\n      strategy::SingleStrategy,\n    },\n  },\n  transcript::{\n    Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,\n  },\n  SerdeFormat,\n};\n\nuse crate::{model::ModelCircuit, utils::helpers::get_public_values};\n\npub fn get_kzg_params(params_dir: &str, degree: u32) -> ParamsKZG<Bn256> {\n  let rng = rand::thread_rng();\n  let path = format!(\"{}/{}.params\", params_dir, degree);\n  let params_path = Path::new(&path);\n  if File::open(&params_path).is_err() {\n    let params = ParamsKZG::<Bn256>::setup(degree, rng);\n    let mut buf = Vec::new();\n\n    params.write(&mut buf).expect(\"Failed to write params\");\n    let mut file = File::create(&params_path).expect(\"Failed to create params file\");\n    file\n      .write_all(&buf[..])\n      .expect(\"Failed to write params to file\");\n  }\n\n  let mut params_fs = File::open(&params_path).expect(\"couldn't load params\");\n  let params = ParamsKZG::<Bn256>::read(&mut params_fs).expect(\"Failed to read params\");\n  params\n}\n\npub fn serialize(data: &Vec<u8>, path: &str) -> u64 {\n  let mut file = File::create(path).unwrap();\n  file.write_all(data).unwrap();\n  file.metadata().unwrap().len()\n}\n\npub fn verify_kzg(\n  params: &ParamsKZG<Bn256>,\n  vk: &VerifyingKey<G1Affine>,\n  strategy: SingleStrategy<Bn256>,\n  public_vals: &Vec<Fr>,\n  mut transcript: Blake2bRead<&[u8], G1Affine, Challenge255<G1Affine>>,\n) {\n  assert!(\n    verify_proof::<\n      KZGCommitmentScheme<Bn256>,\n      VerifierSHPLONK<'_, Bn256>,\n      Challenge255<G1Affine>,\n      Blake2bRead<&[u8], G1Affine, Challenge255<G1Affine>>,\n      halo2_proofs::poly::kzg::strategy::SingleStrategy<'_, Bn256>,\n    >(&params, &vk, strategy, &[&[&public_vals]], &mut transcript)\n    .is_ok(),\n    \"proof did not verify\"\n  );\n}\n\npub fn time_circuit_kzg(circuit: ModelCircuit<Fr>) {\n  let rng = rand::thread_rng();\n  let start = Instant::now();\n\n  let degree = circuit.k as u32;\n  let params = get_kzg_params(\"./params_kzg\", degree);\n\n  let circuit_duration = start.elapsed();\n  println!(\n    \"Time elapsed in params construction: {:?}\",\n    circuit_duration\n  );\n\n  let vk_circuit = circuit.clone();\n  let vk = keygen_vk(&params, &vk_circuit).unwrap();\n  drop(vk_circuit);\n  let vk_duration = start.elapsed();\n  println!(\n    \"Time elapsed in generating vkey: {:?}\",\n    vk_duration - circuit_duration\n  );\n\n  let vkey_size = serialize(&vk.to_bytes(SerdeFormat::RawBytes), \"vkey\");\n  println!(\"vkey size: {} bytes\", vkey_size);\n\n  let pk_circuit = circuit.clone();\n  let pk = keygen_pk(&params, vk, &pk_circuit).unwrap();\n  let pk_duration = start.elapsed();\n  println!(\n    \"Time elapsed in generating pkey: {:?}\",\n    pk_duration - vk_duration\n  );\n  drop(pk_circuit);\n\n  let pkey_size = serialize(&pk.to_bytes(SerdeFormat::RawBytes), \"pkey\");\n  println!(\"pkey size: {} bytes\", pkey_size);\n\n  let fill_duration = start.elapsed();\n  let proof_circuit = circuit.clone();\n  let _prover = MockProver::run(degree, &proof_circuit, vec![vec![]]).unwrap();\n  let public_vals = get_public_values();\n  println!(\n    \"Time elapsed in filling circuit: {:?}\",\n    fill_duration - pk_duration\n  );\n\n  // Convert public vals to serializable format\n  let public_vals_u8: Vec<u8> = public_vals\n    .iter()\n    .map(|v: &Fr| v.to_bytes().to_vec())\n    .flatten()\n    .collect();\n  let public_vals_u8_size = serialize(&public_vals_u8, \"public_vals\");\n  println!(\"Public vals size: {} bytes\", public_vals_u8_size);\n\n  let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]);\n  create_proof::<\n    KZGCommitmentScheme<Bn256>,\n    ProverSHPLONK<'_, Bn256>,\n    Challenge255<G1Affine>,\n    _,\n    Blake2bWrite<Vec<u8>, G1Affine, Challenge255<G1Affine>>,\n    ModelCircuit<Fr>,\n  >(\n    &params,\n    &pk,\n    &[proof_circuit],\n    &[&[&public_vals]],\n    rng,\n    &mut transcript,\n  )\n  .unwrap();\n  let proof = transcript.finalize();\n  let proof_duration = start.elapsed();\n  println!(\"Proving time: {:?}\", proof_duration - fill_duration);\n\n  let proof_size = serialize(&proof, \"proof\");\n  let proof = std::fs::read(\"proof\").unwrap();\n\n  println!(\"Proof size: {} bytes\", proof_size);\n\n  let strategy = SingleStrategy::new(&params);\n  let transcript_read = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]);\n\n  println!(\"public vals: {:?}\", public_vals);\n  verify_kzg(\n    &params,\n    &pk.get_vk(),\n    strategy,\n    &public_vals,\n    transcript_read,\n  );\n  let verify_duration = start.elapsed();\n  println!(\"Verifying time: {:?}\", verify_duration - proof_duration);\n}\n\n// Standalone verification\npub fn verify_circuit_kzg(\n  circuit: ModelCircuit<Fr>,\n  vkey_fname: &str,\n  proof_fname: &str,\n  public_vals_fname: &str,\n) {\n  let degree = circuit.k as u32;\n  let params = get_kzg_params(\"./params_kzg\", degree);\n  println!(\"Loaded the parameters\");\n\n  let vk = VerifyingKey::read::<BufReader<File>, ModelCircuit<Fr>>(\n    &mut BufReader::new(File::open(vkey_fname).unwrap()),\n    SerdeFormat::RawBytes,\n    (),\n  )\n  .unwrap();\n  println!(\"Loaded vkey\");\n\n  let proof = std::fs::read(proof_fname).unwrap();\n\n  let public_vals_u8 = std::fs::read(&public_vals_fname).unwrap();\n  let public_vals: Vec<Fr> = public_vals_u8\n    .chunks(32)\n    .map(|chunk| Fr::from_bytes(chunk.try_into().expect(\"conversion failed\")).unwrap())\n    .collect();\n\n  let strategy = SingleStrategy::new(&params);\n  let transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]);\n\n  let start = Instant::now();\n  let verify_start = start.elapsed();\n  verify_kzg(&params, &vk, strategy, &public_vals, transcript);\n  let verify_duration = start.elapsed();\n  println!(\"Verifying time: {:?}\", verify_duration - verify_start);\n  println!(\"Proof verified!\")\n}\n"
    },
    {
        "repo": "https://github.com/ddkang/zkml",
        "file_path": "testing/circuits/last_two_layers.py",
        "content": "import tensorflow as tf\nimport os \nimport numpy as np\n\ninterpreter = tf.lite.Interpreter(\n    model_path=f'./testing/circuits/v2_1.0_224.tflite'\n)\ninterpreter.allocate_tensors()\n\nNAME_TO_TENSOR = {}\nfor tensor_details in interpreter.get_tensor_details():\n    NAME_TO_TENSOR[tensor_details['name']] = tensor_details\nWc = interpreter.get_tensor(NAME_TO_TENSOR['Const_71']['index'])\nBc = interpreter.get_tensor(NAME_TO_TENSOR['MobilenetV2/Conv_1/Conv2D_bias']['index'])\n\nclass LastTwoLayers(tf.keras.Model):\n    def __init__(self, name=None):\n        super().__init__(name = name)\n        self.a_variable = tf.Variable(5.0, name=\"train_me\")\n        self.conv1 = tf.keras.layers.Conv2D(\n            1280,\n            (1, 1),\n            activation='relu6',\n            padding='same',\n            input_shape=(1, 7, 7, 320)\n        )\n        self.avg_pool = tf.keras.layers.AveragePooling2D(\n            pool_size=(7, 7),\n            padding='valid',\n            strides=(1, 1)\n        )\n        self.conv2 = tf.keras.layers.Conv2D(\n            102,\n            (1, 1),\n            padding='valid',\n            input_shape=(1, 1, 1, 1280)\n        )\n        self.softmax = tf.keras.layers.Softmax()\n\n    def call(self, x):\n        x = self.conv1(x)\n        x = self.avg_pool(x)\n        x = self.conv2(x)\n        x = tf.reshape(x, [1, 102])\n        x = self.softmax(x)\n        return x\n\nmy_sequential_model = LastTwoLayers(name=\"the_model\")\nmy_sequential_model.compile(optimizer='sgd', loss='categorical_crossentropy')\n\nx = np.random.random((1, 7, 7, 320))\n\nmy_sequential_model.predict(x)\n\nmy_sequential_model.conv1.set_weights([np.transpose(Wc, [1,2,3,0]), Bc])\n# x, y, chan_in, chan_out\n\n# 1 batch, 7 height, 320 width, 7 channels\n# 7 height, 1 width, 7 channels, 1280 out channels\n# 1 height, 320 width, 1280 out channels\n\n# 1 Batch, 7 height, 7 width, 320 channels () [This is the input to the layer]\n# 1 Batch, 7 height, 7 width, 1280 channels (dout) [This is the output of another layer]\n\n# We want to transform this so that we rotate the input by 90 degrees\n\nW = np.zeros([1, 1, 1280, 102])\n\nmy_sequential_model.conv2.set_weights([\n    W,\n    np.zeros([102])\n])\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(my_sequential_model)\ntflite_model = converter.convert()\n\nwith open('./examples/v2_1.0_224_truncated/v2_1.0_224_truncated.tflite', 'wb') as f:\n  f.write(tflite_model)\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "frontend/vite.config.js",
        "content": "import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/circuit.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./model.circom\";\ninclude \"./utils/cid.circom\";\ninclude \"./utils/encrypt.circom\";\n\ntemplate Main(n) {\n    // private inputs\n    signal input in[n][797*8];\n    signal input conv2d_weights[3][3][1][4];\n    signal input conv2d_bias[4];\n    signal input batch_normalization_a[4];\n    signal input batch_normalization_b[4];\n    signal input conv2d_1_weights[3][3][4][16];\n    signal input conv2d_1_bias[16];\n    signal input batch_normalization_1_a[16];\n    signal input batch_normalization_1_b[16];\n    signal input dense_weights[16][10];\n    signal input dense_bias[10];\n\n    // outputs\n    signal output out[n];\n    signal output cids[n*2];\n    signal output hash;\n\n    // recurring components\n    component pixel[n];\n    component model[n];\n    component cid[n];\n\n    for (var i = 0; i < n; i++) {\n        model[i] = Model();\n        pixel[i] = getPixels();\n        cid[i] = getCid();\n\n        for (var i0 = 0; i0 < 797*8; i0++) {\n            pixel[i].in[i0] <== in[i][i0];\n            cid[i].in[i0] <== in[i][i0];\n        }\n\n        // get cid\n        for (var i0 = 0; i0 < 2; i0++) {\n            cids[i*2+i0] <== cid[i].out[i0];\n        }\n\n        for (var i0 = 0; i0 < 28; i0++) {\n            for (var i1 = 0; i1 < 28; i1++) {\n                for (var i2 = 0; i2 < 1; i2++) {\n                    model[i].in[i0][i1][i2] <== pixel[i].out[i0][i1][i2];\n        }}}\n\n        for (var i0 = 0; i0 < 3; i0++) {\n            for (var i1 = 0; i1 < 3; i1++) {\n                for (var i2 = 0; i2 < 1; i2++) {\n                    for (var i3 = 0; i3 < 4; i3++) {\n                        model[i].conv2d_weights[i0][i1][i2][i3] <== conv2d_weights[i0][i1][i2][i3];\n        }}}}\n        for (var i0 = 0; i0 < 4; i0++) {\n            model[i].conv2d_bias[i0] <== conv2d_bias[i0];\n        }\n\n        for (var i0 = 0; i0 < 4; i0++) {\n            model[i].batch_normalization_a[i0] <== batch_normalization_a[i0];\n        }\n        for (var i0 = 0; i0 < 4; i0++) {\n            model[i].batch_normalization_b[i0] <== batch_normalization_b[i0];\n        }\n\n        for (var i0 = 0; i0 < 3; i0++) {\n            for (var i1 = 0; i1 < 3; i1++) {\n                for (var i2 = 0; i2 < 4; i2++) {\n                    for (var i3 = 0; i3 < 16; i3++) {\n                        model[i].conv2d_1_weights[i0][i1][i2][i3] <== conv2d_1_weights[i0][i1][i2][i3];\n        }}}}\n        for (var i0 = 0; i0 < 16; i0++) {\n            model[i].conv2d_1_bias[i0] <== conv2d_1_bias[i0];\n        }\n\n        for (var i0 = 0; i0 < 16; i0++) {\n            model[i].batch_normalization_1_a[i0] <== batch_normalization_1_a[i0];\n        }\n        for (var i0 = 0; i0 < 16; i0++) {\n            model[i].batch_normalization_1_b[i0] <== batch_normalization_1_b[i0];\n        }\n\n        for (var i0 = 0; i0 < 16; i0++) {\n            for (var i1 = 0; i1 < 10; i1++) {\n                model[i].dense_weights[i0][i1] <== dense_weights[i0][i1];\n        }}\n        for (var i0 = 0; i0 < 10; i0++) {\n            model[i].dense_bias[i0] <== dense_bias[i0];\n        }\n\n        out[i] <== model[i].out[0];\n    }\n\n    // hash model weights\n\n    component mimc = hash1000();\n    var idx = 0;\n\n    for (var i0 = 0; i0 < 3; i0++) {\n        for (var i1 = 0; i1 < 3; i1++) {\n            for (var i2 = 0; i2 < 1; i2++) {\n                for (var i3 = 0; i3 < 4; i3++) {\n                    mimc.in[idx] <== conv2d_weights[i0][i1][i2][i3];\n                    idx++;\n    }}}}\n\n    for (var i0 = 0; i0 < 4; i0++) {\n        mimc.in[idx] <== conv2d_bias[i0];\n        idx++;\n    }\n\n    for (var i0 = 0; i0 < 4; i0++) {\n            mimc.in[idx] <== batch_normalization_a[i0];\n            idx++;\n    }\n    for (var i0 = 0; i0 < 4; i0++) {\n        mimc.in[idx] <== batch_normalization_b[i0];\n        idx++;\n    }\n\n    for (var i0 = 0; i0 < 3; i0++) {\n        for (var i1 = 0; i1 < 3; i1++) {\n            for (var i2 = 0; i2 < 4; i2++) {\n                for (var i3 = 0; i3 < 16; i3++) {\n                    mimc.in[idx] <== conv2d_1_weights[i0][i1][i2][i3];\n                    idx++;\n    }}}}\n    for (var i0 = 0; i0 < 16; i0++) {\n        mimc.in[idx] <== conv2d_1_bias[i0];\n        idx++;\n    }\n\n    for (var i0 = 0; i0 < 16; i0++) {\n        mimc.in[idx] <== batch_normalization_1_a[i0];\n        idx++;\n    }\n    for (var i0 = 0; i0 < 16; i0++) {\n        mimc.in[idx] <== batch_normalization_1_b[i0];\n        idx++;\n    }\n\n    for (var i0 = 0; i0 < 16; i0++) {\n        for (var i1 = 0; i1 < 10; i1++) {\n            mimc.in[idx] <== dense_weights[i0][i1];\n            idx++;\n    }}\n    for (var i0 = 0; i0 < 10; i0++) {\n        mimc.in[idx] <== dense_bias[i0];\n        idx++;\n    }\n\n    // padding\n    for (var i = idx; i < 1000; i++) {\n        mimc.in[i] <== 0;\n    }\n\n    hash <== mimc.out;\n}\n\ncomponent main = Main(10);"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/encryption.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"./utils/encrypt.circom\";\n\ntemplate Main() {\n    // public inputs\n    signal input public_key[2];\n\n    // private inputs\n    signal input in[1000]; // zero-padded at the end\n    signal input private_key;\n\n    // outputs\n    signal output hash;\n    signal output shared_key;\n    signal output out[1001];\n\n    component hasher = hash1000();\n    component enc = encrypt1000();\n\n    enc.public_key[0] <== public_key[0];\n    enc.public_key[1] <== public_key[1];\n    enc.private_key <== private_key;\n\n    for (var i = 0; i < 1000; i++) {\n        hasher.in[i] <== in[i];\n        enc.in[i] <== in[i];\n    }\n\n    hash <== hasher.out;\n    shared_key <== enc.shared_key;\n\n    for (var i = 0; i < 1001; i++) {\n        out[i] <== enc.out[i];\n    }\n}\n\ncomponent main { public [ public_key ] } = Main();"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/model.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../node_modules/circomlib-ml/circuits/BatchNormalization2D.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/Dense.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/Conv2D.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/AveragePooling2D.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/ArgMax.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/Poly.circom\";\ninclude \"../node_modules/circomlib-ml/circuits/GlobalAveragePooling2D.circom\";\n\ntemplate Model() {\nsignal input in[28][28][1];\nsignal input conv2d_weights[3][3][1][4];\nsignal input conv2d_bias[4];\nsignal input batch_normalization_a[4];\nsignal input batch_normalization_b[4];\nsignal input conv2d_1_weights[3][3][4][16];\nsignal input conv2d_1_bias[16];\nsignal input batch_normalization_1_a[16];\nsignal input batch_normalization_1_b[16];\nsignal input dense_weights[16][10];\nsignal input dense_bias[10];\nsignal output out[1];\n\ncomponent conv2d = Conv2D(28, 28, 1, 4, 3, 1);\ncomponent batch_normalization = BatchNormalization2D(26, 26, 4);\ncomponent lambda[26][26][4];\nfor (var i0 = 0; i0 < 26; i0++) {\n    for (var i1 = 0; i1 < 26; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            lambda[i0][i1][i2] = Poly(1000000);\n}}}\ncomponent average_pooling2d = AveragePooling2D(26, 26, 4, 2, 2, 250);\ncomponent conv2d_1 = Conv2D(13, 13, 4, 16, 3, 1);\ncomponent batch_normalization_1 = BatchNormalization2D(11, 11, 16);\ncomponent lambda_1[11][11][16];\nfor (var i0 = 0; i0 < 11; i0++) {\n    for (var i1 = 0; i1 < 11; i1++) {\n        for (var i2 = 0; i2 < 16; i2++) {\n            lambda_1[i0][i1][i2] = Poly(1000000000000000000000);\n}}}\ncomponent average_pooling2d_1 = AveragePooling2D(11, 11, 16, 2, 2, 250);\ncomponent global_average_pooling2d = GlobalAveragePooling2D(5, 5, 16, 40);\ncomponent dense = Dense(16, 10);\ncomponent softmax = ArgMax(10);\n\nfor (var i0 = 0; i0 < 28; i0++) {\n    for (var i1 = 0; i1 < 28; i1++) {\n        for (var i2 = 0; i2 < 1; i2++) {\n            conv2d.in[i0][i1][i2] <== in[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 3; i0++) {\n    for (var i1 = 0; i1 < 3; i1++) {\n        for (var i2 = 0; i2 < 1; i2++) {\n            for (var i3 = 0; i3 < 4; i3++) {\n                conv2d.weights[i0][i1][i2][i3] <== conv2d_weights[i0][i1][i2][i3];\n}}}}\nfor (var i0 = 0; i0 < 4; i0++) {\n    conv2d.bias[i0] <== conv2d_bias[i0];\n}\nfor (var i0 = 0; i0 < 26; i0++) {\n    for (var i1 = 0; i1 < 26; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            batch_normalization.in[i0][i1][i2] <== conv2d.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 4; i0++) {\n    batch_normalization.a[i0] <== batch_normalization_a[i0];\n}\nfor (var i0 = 0; i0 < 4; i0++) {\n    batch_normalization.b[i0] <== batch_normalization_b[i0];\n}\nfor (var i0 = 0; i0 < 26; i0++) {\n    for (var i1 = 0; i1 < 26; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            lambda[i0][i1][i2].in <== batch_normalization.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 26; i0++) {\n    for (var i1 = 0; i1 < 26; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            average_pooling2d.in[i0][i1][i2] <== lambda[i0][i1][i2].out;\n}}}\nfor (var i0 = 0; i0 < 13; i0++) {\n    for (var i1 = 0; i1 < 13; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            conv2d_1.in[i0][i1][i2] <== average_pooling2d.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 3; i0++) {\n    for (var i1 = 0; i1 < 3; i1++) {\n        for (var i2 = 0; i2 < 4; i2++) {\n            for (var i3 = 0; i3 < 16; i3++) {\n                conv2d_1.weights[i0][i1][i2][i3] <== conv2d_1_weights[i0][i1][i2][i3];\n}}}}\nfor (var i0 = 0; i0 < 16; i0++) {\n    conv2d_1.bias[i0] <== conv2d_1_bias[i0];\n}\nfor (var i0 = 0; i0 < 11; i0++) {\n    for (var i1 = 0; i1 < 11; i1++) {\n        for (var i2 = 0; i2 < 16; i2++) {\n            batch_normalization_1.in[i0][i1][i2] <== conv2d_1.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 16; i0++) {\n    batch_normalization_1.a[i0] <== batch_normalization_1_a[i0];\n}\nfor (var i0 = 0; i0 < 16; i0++) {\n    batch_normalization_1.b[i0] <== batch_normalization_1_b[i0];\n}\nfor (var i0 = 0; i0 < 11; i0++) {\n    for (var i1 = 0; i1 < 11; i1++) {\n        for (var i2 = 0; i2 < 16; i2++) {\n            lambda_1[i0][i1][i2].in <== batch_normalization_1.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 11; i0++) {\n    for (var i1 = 0; i1 < 11; i1++) {\n        for (var i2 = 0; i2 < 16; i2++) {\n            average_pooling2d_1.in[i0][i1][i2] <== lambda_1[i0][i1][i2].out;\n}}}\nfor (var i0 = 0; i0 < 5; i0++) {\n    for (var i1 = 0; i1 < 5; i1++) {\n        for (var i2 = 0; i2 < 16; i2++) {\n            global_average_pooling2d.in[i0][i1][i2] <== average_pooling2d_1.out[i0][i1][i2];\n}}}\nfor (var i0 = 0; i0 < 16; i0++) {\n    dense.in[i0] <== global_average_pooling2d.out[i0];\n}\nfor (var i0 = 0; i0 < 16; i0++) {\n    for (var i1 = 0; i1 < 10; i1++) {\n        dense.weights[i0][i1] <== dense_weights[i0][i1];\n}}\nfor (var i0 = 0; i0 < 10; i0++) {\n    dense.bias[i0] <== dense_bias[i0];\n}\nfor (var i0 = 0; i0 < 10; i0++) {\n    softmax.in[i0] <== dense.out[i0];\n}\nout[0] <== softmax.out;\n\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/ch.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/* Ch\n\n000 0\n001 1\n010 0\n011 1\n100 0\n101 0\n110 1\n111 1\n\nout = a&b ^ (!a)&c =>\n\nout = a*(b-c) + c\n\n*/\npragma circom 2.0.0;\n\ntemplate Ch_t(n) {\n    signal input a[n];\n    signal input b[n];\n    signal input c[n];\n    signal output out[n];\n\n    for (var k=0; k<n; k++) {\n        out[k] <== a[k] * (b[k]-c[k]) + c[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/constants.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ntemplate H(x) {\n    signal output out[32];\n    var c[8] = [0x6a09e667,\n             0xbb67ae85,\n             0x3c6ef372,\n             0xa54ff53a,\n             0x510e527f,\n             0x9b05688c,\n             0x1f83d9ab,\n             0x5be0cd19];\n\n    for (var i=0; i<32; i++) {\n        out[i] <== (c[x] >> i) & 1;\n    }\n}\n\ntemplate K(x) {\n    signal output out[32];\n    var c[64] = [\n        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n    ];\n\n    for (var i=0; i<32; i++) {\n        out[i] <== (c[x] >> i) & 1;\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/main.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"sha256_2.circom\";\n\ntemplate Main() {\n    signal input a;\n    signal input b;\n    signal output out;\n\n    component sha256_2 = Sha256_2();\n\n    sha256_2.a <== a;\n    sha256_2.b <== a;\n    out <== sha256_2.out;\n}\n\ncomponent main = Main();\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/maj.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/* Maj function for sha256\n\nout = a&b ^ a&c ^ b&c  =>\n\nout = a*b   +  a*c  +  b*c  -  2*a*b*c  =>\n\nout = a*( b + c - 2*b*c ) + b*c =>\n\nmid = b*c\nout = a*( b + c - 2*mid ) + mid\n\n*/\npragma circom 2.0.0;\n\ntemplate Maj_t(n) {\n    signal input a[n];\n    signal input b[n];\n    signal input c[n];\n    signal output out[n];\n    signal mid[n];\n\n    for (var k=0; k<n; k++) {\n        mid[k] <== b[k]*c[k];\n        out[k] <== a[k] * (b[k]+c[k]-2*mid[k]) + mid[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/rotate.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ntemplate RotR(n, r) {\n    signal input in[n];\n    signal output out[n];\n\n    for (var i=0; i<n; i++) {\n        out[i] <== in[ (i+r)%n ];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sha256.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"constants.circom\";\ninclude \"sha256compression.circom\";\n\ntemplate Sha256(nBits) {\n    signal input in[nBits];\n    signal output out[256];\n\n    var i;\n    var k;\n    var nBlocks;\n    var bitsLastBlock;\n\n\n    nBlocks = ((nBits + 64)\\512)+1;\n\n    signal paddedIn[nBlocks*512];\n\n    for (k=0; k<nBits; k++) {\n        paddedIn[k] <== in[k];\n    }\n    paddedIn[nBits] <== 1;\n\n    for (k=nBits+1; k<nBlocks*512-64; k++) {\n        paddedIn[k] <== 0;\n    }\n\n    for (k = 0; k< 64; k++) {\n        paddedIn[nBlocks*512 - k -1] <== (nBits >> k)&1;\n    }\n\n    component ha0 = H(0);\n    component hb0 = H(1);\n    component hc0 = H(2);\n    component hd0 = H(3);\n    component he0 = H(4);\n    component hf0 = H(5);\n    component hg0 = H(6);\n    component hh0 = H(7);\n\n    component sha256compression[nBlocks];\n\n    for (i=0; i<nBlocks; i++) {\n\n        sha256compression[i] = Sha256compression() ;\n\n        if (i==0) {\n            for (k=0; k<32; k++ ) {\n                sha256compression[i].hin[0*32+k] <== ha0.out[k];\n                sha256compression[i].hin[1*32+k] <== hb0.out[k];\n                sha256compression[i].hin[2*32+k] <== hc0.out[k];\n                sha256compression[i].hin[3*32+k] <== hd0.out[k];\n                sha256compression[i].hin[4*32+k] <== he0.out[k];\n                sha256compression[i].hin[5*32+k] <== hf0.out[k];\n                sha256compression[i].hin[6*32+k] <== hg0.out[k];\n                sha256compression[i].hin[7*32+k] <== hh0.out[k];\n            }\n        } else {\n            for (k=0; k<32; k++ ) {\n                sha256compression[i].hin[32*0+k] <== sha256compression[i-1].out[32*0+31-k];\n                sha256compression[i].hin[32*1+k] <== sha256compression[i-1].out[32*1+31-k];\n                sha256compression[i].hin[32*2+k] <== sha256compression[i-1].out[32*2+31-k];\n                sha256compression[i].hin[32*3+k] <== sha256compression[i-1].out[32*3+31-k];\n                sha256compression[i].hin[32*4+k] <== sha256compression[i-1].out[32*4+31-k];\n                sha256compression[i].hin[32*5+k] <== sha256compression[i-1].out[32*5+31-k];\n                sha256compression[i].hin[32*6+k] <== sha256compression[i-1].out[32*6+31-k];\n                sha256compression[i].hin[32*7+k] <== sha256compression[i-1].out[32*7+31-k];\n            }\n        }\n\n        for (k=0; k<512; k++) {\n            sha256compression[i].inp[k] <== paddedIn[i*512+k];\n        }\n    }\n\n    for (k=0; k<256; k++) {\n        out[k] <== sha256compression[nBlocks-1].out[k];\n    }\n\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sha256_2.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"constants.circom\";\ninclude \"sha256compression.circom\";\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/bitify.circom\";\n\ntemplate Sha256_2() {\n    signal input a;\n    signal input b;\n    signal output out;\n\n    var i;\n    var k;\n\n    component bits2num = Bits2Num(216);\n    component num2bits[2];\n\n    num2bits[0] = Num2Bits(216);\n    num2bits[1] = Num2Bits(216);\n\n    num2bits[0].in <== a;\n    num2bits[1].in <== b;\n\n\n    component sha256compression = Sha256compression() ;\n\n    component ha0 = H(0);\n    component hb0 = H(1);\n    component hc0 = H(2);\n    component hd0 = H(3);\n    component he0 = H(4);\n    component hf0 = H(5);\n    component hg0 = H(6);\n    component hh0 = H(7);\n\n    for (k=0; k<32; k++ ) {\n        sha256compression.hin[0*32+k] <== ha0.out[k];\n        sha256compression.hin[1*32+k] <== hb0.out[k];\n        sha256compression.hin[2*32+k] <== hc0.out[k];\n        sha256compression.hin[3*32+k] <== hd0.out[k];\n        sha256compression.hin[4*32+k] <== he0.out[k];\n        sha256compression.hin[5*32+k] <== hf0.out[k];\n        sha256compression.hin[6*32+k] <== hg0.out[k];\n        sha256compression.hin[7*32+k] <== hh0.out[k];\n    }\n\n    for (i=0; i<216; i++) {\n        sha256compression.inp[i] <== num2bits[0].out[215-i];\n        sha256compression.inp[i+216] <== num2bits[1].out[215-i];\n    }\n\n    sha256compression.inp[432] <== 1;\n\n    for (i=433; i<503; i++) {\n        sha256compression.inp[i] <== 0;\n    }\n\n    sha256compression.inp[503] <== 1;\n    sha256compression.inp[504] <== 1;\n    sha256compression.inp[505] <== 0;\n    sha256compression.inp[506] <== 1;\n    sha256compression.inp[507] <== 1;\n    sha256compression.inp[508] <== 0;\n    sha256compression.inp[509] <== 0;\n    sha256compression.inp[510] <== 0;\n    sha256compression.inp[511] <== 0;\n\n    for (i=0; i<216; i++) {\n        bits2num.in[i] <== sha256compression.out[255-i];\n    }\n\n    out <== bits2num.out;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sha256compression.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"constants.circom\";\ninclude \"t1.circom\";\ninclude \"t2.circom\";\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom\";\ninclude \"sigmaplus.circom\";\ninclude \"sha256compression_function.circom\";\n\n\ntemplate Sha256compression() {\n    signal input hin[256];\n    signal input inp[512];\n    signal output out[256];\n    signal a[65][32];\n    signal b[65][32];\n    signal c[65][32];\n    signal d[65][32];\n    signal e[65][32];\n    signal f[65][32];\n    signal g[65][32];\n    signal h[65][32];\n    signal w[64][32];\n\n\n    var outCalc[256] = sha256compression(hin, inp);\n\n    var i;\n    for (i=0; i<256; i++) out[i] <-- outCalc[i];\n\n    component sigmaPlus[48];\n    for (i=0; i<48; i++) sigmaPlus[i] = SigmaPlus();\n\n    component ct_k[64];\n    for (i=0; i<64; i++) ct_k[i] = K(i);\n\n    component t1[64];\n    for (i=0; i<64; i++) t1[i] = T1();\n\n    component t2[64];\n    for (i=0; i<64; i++) t2[i] = T2();\n\n    component suma[64];\n    for (i=0; i<64; i++) suma[i] = BinSum(32, 2);\n\n    component sume[64];\n    for (i=0; i<64; i++) sume[i] = BinSum(32, 2);\n\n    component fsum[8];\n    for (i=0; i<8; i++) fsum[i] = BinSum(32, 2);\n\n    var k;\n    var t;\n\n    for (t=0; t<64; t++) {\n        if (t<16) {\n            for (k=0; k<32; k++) {\n                w[t][k] <== inp[t*32+31-k];\n            }\n        } else {\n            for (k=0; k<32; k++) {\n                sigmaPlus[t-16].in2[k] <== w[t-2][k];\n                sigmaPlus[t-16].in7[k] <== w[t-7][k];\n                sigmaPlus[t-16].in15[k] <== w[t-15][k];\n                sigmaPlus[t-16].in16[k] <== w[t-16][k];\n            }\n\n            for (k=0; k<32; k++) {\n                w[t][k] <== sigmaPlus[t-16].out[k];\n            }\n        }\n    }\n\n    for (k=0; k<32; k++ ) {\n        a[0][k] <== hin[k];\n        b[0][k] <== hin[32*1 + k];\n        c[0][k] <== hin[32*2 + k];\n        d[0][k] <== hin[32*3 + k];\n        e[0][k] <== hin[32*4 + k];\n        f[0][k] <== hin[32*5 + k];\n        g[0][k] <== hin[32*6 + k];\n        h[0][k] <== hin[32*7 + k];\n    }\n\n    for (t = 0; t<64; t++) {\n        for (k=0; k<32; k++) {\n            t1[t].h[k] <== h[t][k];\n            t1[t].e[k] <== e[t][k];\n            t1[t].f[k] <== f[t][k];\n            t1[t].g[k] <== g[t][k];\n            t1[t].k[k] <== ct_k[t].out[k];\n            t1[t].w[k] <== w[t][k];\n\n            t2[t].a[k] <== a[t][k];\n            t2[t].b[k] <== b[t][k];\n            t2[t].c[k] <== c[t][k];\n        }\n\n        for (k=0; k<32; k++) {\n            sume[t].in[0][k] <== d[t][k];\n            sume[t].in[1][k] <== t1[t].out[k];\n\n            suma[t].in[0][k] <== t1[t].out[k];\n            suma[t].in[1][k] <== t2[t].out[k];\n        }\n\n        for (k=0; k<32; k++) {\n            h[t+1][k] <== g[t][k];\n            g[t+1][k] <== f[t][k];\n            f[t+1][k] <== e[t][k];\n            e[t+1][k] <== sume[t].out[k];\n            d[t+1][k] <== c[t][k];\n            c[t+1][k] <== b[t][k];\n            b[t+1][k] <== a[t][k];\n            a[t+1][k] <== suma[t].out[k];\n        }\n    }\n\n    for (k=0; k<32; k++) {\n        fsum[0].in[0][k] <==  hin[32*0+k];\n        fsum[0].in[1][k] <==  a[64][k];\n        fsum[1].in[0][k] <==  hin[32*1+k];\n        fsum[1].in[1][k] <==  b[64][k];\n        fsum[2].in[0][k] <==  hin[32*2+k];\n        fsum[2].in[1][k] <==  c[64][k];\n        fsum[3].in[0][k] <==  hin[32*3+k];\n        fsum[3].in[1][k] <==  d[64][k];\n        fsum[4].in[0][k] <==  hin[32*4+k];\n        fsum[4].in[1][k] <==  e[64][k];\n        fsum[5].in[0][k] <==  hin[32*5+k];\n        fsum[5].in[1][k] <==  f[64][k];\n        fsum[6].in[0][k] <==  hin[32*6+k];\n        fsum[6].in[1][k] <==  g[64][k];\n        fsum[7].in[0][k] <==  hin[32*7+k];\n        fsum[7].in[1][k] <==  h[64][k];\n    }\n\n    for (k=0; k<32; k++) {\n        out[31-k]     === fsum[0].out[k];\n        out[32+31-k]  === fsum[1].out[k];\n        out[64+31-k]  === fsum[2].out[k];\n        out[96+31-k]  === fsum[3].out[k];\n        out[128+31-k] === fsum[4].out[k];\n        out[160+31-k] === fsum[5].out[k];\n        out[192+31-k] === fsum[6].out[k];\n        out[224+31-k] === fsum[7].out[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sha256compression_function.circom",
        "content": "//    signal input hin[256];\n//    signal input inp[512];\n//    signal output out[256];\npragma circom 2.0.0;\n\nfunction rrot(x, n) {\n    return ((x >> n) | (x << (32-n))) & 0xFFFFFFFF;\n}\n\nfunction bsigma0(x) {\n    return rrot(x,2) ^ rrot(x,13) ^ rrot(x,22);\n}\n\nfunction bsigma1(x) {\n    return rrot(x,6) ^ rrot(x,11) ^ rrot(x,25);\n}\n\nfunction ssigma0(x) {\n    return rrot(x,7) ^ rrot(x,18) ^ (x >> 3);\n}\n\nfunction ssigma1(x) {\n    return rrot(x,17) ^ rrot(x,19) ^ (x >> 10);\n}\n\nfunction Maj(x, y, z) {\n    return (x&y) ^ (x&z) ^ (y&z);\n}\n\nfunction Ch(x, y, z) {\n    return (x & y) ^ ((0xFFFFFFFF ^x) & z);\n}\n\nfunction sha256K(i) {\n    var k[64] = [\n        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n    ];\n    return k[i];\n}\n\nfunction sha256compression(hin, inp) {\n    var H[8];\n    var a;\n    var b;\n    var c;\n    var d;\n    var e;\n    var f;\n    var g;\n    var h;\n    var out[256];\n    for (var i=0; i<8; i++) {\n        H[i] = 0;\n        for (var j=0; j<32; j++) {\n            H[i] += hin[i*32+j] << j;\n        }\n    }\n    a=H[0];\n    b=H[1];\n    c=H[2];\n    d=H[3];\n    e=H[4];\n    f=H[5];\n    g=H[6];\n    h=H[7];\n    var w[64];\n    var T1;\n    var T2;\n    for (var i=0; i<64; i++) {\n        if (i<16) {\n            w[i]=0;\n            for (var j=0; j<32; j++) {\n                w[i] +=  inp[i*32+31-j]<<j;\n            }\n        } else {\n            w[i] = (ssigma1(w[i-2]) + w[i-7] + ssigma0(w[i-15]) + w[i-16]) & 0xFFFFFFFF;\n        }\n        T1 = (h + bsigma1(e) + Ch(e,f,g) + sha256K(i) + w[i]) & 0xFFFFFFFF;\n        T2 = (bsigma0(a) + Maj(a,b,c)) & 0xFFFFFFFF;\n\n        h=g;\n        g=f;\n        f=e;\n        e=(d+T1) & 0xFFFFFFFF;\n        d=c;\n        c=b;\n        b=a;\n        a=(T1+T2) & 0xFFFFFFFF;\n\n    }\n    H[0] = H[0] + a;\n    H[1] = H[1] + b;\n    H[2] = H[2] + c;\n    H[3] = H[3] + d;\n    H[4] = H[4] + e;\n    H[5] = H[5] + f;\n    H[6] = H[6] + g;\n    H[7] = H[7] + h;\n    for (var i=0; i<8; i++) {\n        for (var j=0; j<32; j++) {\n            out[i*32+31-j] = (H[i] >> j) & 1;\n        }\n    }\n    return out;\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/shift.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ntemplate ShR(n, r) {\n    signal input in[n];\n    signal output out[n];\n\n    for (var i=0; i<n; i++) {\n        if (i+r >= n) {\n            out[i] <== 0;\n        } else {\n            out[i] <== in[ i+r ];\n        }\n    }\n}\n\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sigma.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"xor3.circom\";\ninclude \"rotate.circom\";\ninclude \"shift.circom\";\n\ntemplate SmallSigma(ra, rb, rc) {\n    signal input in[32];\n    signal output out[32];\n    var k;\n\n    component rota = RotR(32, ra);\n    component rotb = RotR(32, rb);\n    component shrc = ShR(32, rc);\n\n    for (k=0; k<32; k++) {\n        rota.in[k] <== in[k];\n        rotb.in[k] <== in[k];\n        shrc.in[k] <== in[k];\n    }\n\n    component xor3 = Xor3(32);\n    for (k=0; k<32; k++) {\n        xor3.a[k] <== rota.out[k];\n        xor3.b[k] <== rotb.out[k];\n        xor3.c[k] <== shrc.out[k];\n    }\n\n    for (k=0; k<32; k++) {\n        out[k] <== xor3.out[k];\n    }\n}\n\ntemplate BigSigma(ra, rb, rc) {\n    signal input in[32];\n    signal output out[32];\n    var k;\n\n    component rota = RotR(32, ra);\n    component rotb = RotR(32, rb);\n    component rotc = RotR(32, rc);\n    for (k=0; k<32; k++) {\n        rota.in[k] <== in[k];\n        rotb.in[k] <== in[k];\n        rotc.in[k] <== in[k];\n    }\n\n    component xor3 = Xor3(32);\n\n    for (k=0; k<32; k++) {\n        xor3.a[k] <== rota.out[k];\n        xor3.b[k] <== rotb.out[k];\n        xor3.c[k] <== rotc.out[k];\n    }\n\n    for (k=0; k<32; k++) {\n        out[k] <== xor3.out[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/sigmaplus.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom\";\ninclude \"sigma.circom\";\n\ntemplate SigmaPlus() {\n    signal input in2[32];\n    signal input in7[32];\n    signal input in15[32];\n    signal input in16[32];\n    signal output out[32];\n    var k;\n\n    component sigma1 = SmallSigma(17,19,10);\n    component sigma0 = SmallSigma(7, 18, 3);\n    for (k=0; k<32; k++) {\n        sigma1.in[k] <== in2[k];\n        sigma0.in[k] <== in15[k];\n    }\n\n    component sum = BinSum(32, 4);\n    for (k=0; k<32; k++) {\n        sum.in[0][k] <== sigma1.out[k];\n        sum.in[1][k] <== in7[k];\n        sum.in[2][k] <== sigma0.out[k];\n        sum.in[3][k] <== in16[k];\n    }\n\n    for (k=0; k<32; k++) {\n        out[k] <== sum.out[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/t1.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom\";\ninclude \"sigma.circom\";\ninclude \"ch.circom\";\n\ntemplate T1() {\n    signal input h[32];\n    signal input e[32];\n    signal input f[32];\n    signal input g[32];\n    signal input k[32];\n    signal input w[32];\n    signal output out[32];\n\n    var ki;\n\n    component ch = Ch_t(32);\n    component bigsigma1 = BigSigma(6, 11, 25);\n\n    for (ki=0; ki<32; ki++) {\n        bigsigma1.in[ki] <== e[ki];\n        ch.a[ki] <== e[ki];\n        ch.b[ki] <== f[ki];\n        ch.c[ki] <== g[ki];\n    }\n\n    component sum = BinSum(32, 5);\n    for (ki=0; ki<32; ki++) {\n        sum.in[0][ki] <== h[ki];\n        sum.in[1][ki] <== bigsigma1.out[ki];\n        sum.in[2][ki] <== ch.out[ki];\n        sum.in[3][ki] <== k[ki];\n        sum.in[4][ki] <== w[ki];\n    }\n\n    for (ki=0; ki<32; ki++) {\n        out[ki] <== sum.out[ki];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/t2.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\npragma circom 2.0.0;\n\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom\";\ninclude \"sigma.circom\";\ninclude \"maj.circom\";\n\ntemplate T2() {\n    signal input a[32];\n    signal input b[32];\n    signal input c[32];\n    signal output out[32];\n    var k;\n\n    component bigsigma0 = BigSigma(2, 13, 22);\n    component maj = Maj_t(32);\n    for (k=0; k<32; k++) {\n        bigsigma0.in[k] <== a[k];\n        maj.a[k] <== a[k];\n        maj.b[k] <== b[k];\n        maj.c[k] <== c[k];\n    }\n\n    component sum = BinSum(32, 2);\n\n    for (k=0; k<32; k++) {\n        sum.in[0][k] <== bigsigma0.out[k];\n        sum.in[1][k] <== maj.out[k];\n    }\n\n    for (k=0; k<32; k++) {\n        out[k] <== sum.out[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/sha256/xor3.circom",
        "content": "/*\n    Copyright 2018 0KIMS association.\n\n    This file is part of circom (Zero Knowledge Circuit Compiler).\n\n    circom is a free software: you can redistribute it and/or modify it\n    under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    circom is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n    License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with circom. If not, see <https://www.gnu.org/licenses/>.\n*/\n\n/* Xor3 function for sha256\n\nout = a ^ b ^ c  =>\n\nout = a+b+c - 2*a*b - 2*a*c - 2*b*c + 4*a*b*c   =>\n\nout = a*( 1 - 2*b - 2*c + 4*b*c ) + b + c - 2*b*c =>\n\nmid = b*c\nout = a*( 1 - 2*b -2*c + 4*mid ) + b + c - 2 * mid\n\n*/\npragma circom 2.0.0;\n\ntemplate Xor3(n) {\n    signal input a[n];\n    signal input b[n];\n    signal input c[n];\n    signal output out[n];\n    signal mid[n];\n\n    for (var k=0; k<n; k++) {\n        mid[k] <== b[k]*c[k];\n        out[k] <== a[k] * (1 -2*b[k]  -2*c[k] +4*mid[k]) + b[k] + c[k] -2*mid[k];\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/utils/cid.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../sha256/sha256.circom\";\ninclude \"../../node_modules/circomlib-ml/circuits/circomlib/bitify.circom\";\n\n// convert a 797x8 bit array (pgm) to 28x28x1 array (pixels)\ntemplate getPixels() {\n    signal input in[797*8];\n    signal output out[28][28][1];\n\n    component pixels[28][28][1];\n\n    for (var i=0; i<28; i++) {\n        for (var j=0; j<28; j++) {\n            pixels[i][j][0] = Bits2Num(8);\n            for (var k=0; k<8; k++) {\n                pixels[i][j][0].in[k] <== in[13*8+i*28*8+j*8+k]; // the pgm header is 13 bytes\n            }\n            out[i][j][0] <== pixels[i][j][0].out;\n        }\n    }\n}\n\n// convert a 797x8 bit array (pgm) to the corresponding CID (in two parts)\ntemplate getCid() {\n    signal input in[797*8];\n    signal output out[2];\n\n    component sha = Sha256(797*8);\n    for (var i=0; i<797*8; i++) {\n        sha.in[i] <== in[i];\n    }\n    \n    component b2n[2];\n\n    for (var i=1; i>=0; i--) {\n        b2n[i] = Bits2Num(128);\n        for (var j=127; j>=0; j--) {\n            b2n[i].in[127-j] <== sha.out[i*128+j];\n        }\n        out[i] <== b2n[i].out;\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/circuits/utils/encrypt.circom",
        "content": "pragma circom 2.0.0;\n\ninclude \"../../node_modules/circomlib-ml/circuits/crypto/encrypt.circom\";\ninclude \"../../node_modules/circomlib-ml/circuits/crypto/ecdh.circom\";\n\n// encrypt 1000 inputs\ntemplate encrypt1000() {\n    // public inputs\n    signal input public_key[2];\n\n    // private inputs\n    signal input in[1000];\n    signal input private_key;\n\n    // outputs\n    signal output shared_key;\n    signal output out[1001];\n\n    component ecdh = Ecdh();\n\n    ecdh.private_key <== private_key;\n    ecdh.public_key[0] <== public_key[0];\n    ecdh.public_key[1] <== public_key[1];\n\n    component enc = EncryptBits(1000);\n    enc.shared_key <== ecdh.shared_key;\n\n    for (var i = 0; i < 1000; i++) {\n        enc.plaintext[i] <== in[i];\n    }\n\n    for (var i = 0; i < 1001; i++) {\n        out[i] <== enc.out[i];\n    }\n\n    shared_key <== ecdh.shared_key;\n}\n\n// fixed MultiMiMC7 with 1000 inputs\ntemplate hash1000() {\n    signal input in[1000];\n    signal output out;\n\n    component mimc = MultiMiMC7(1000, 91);\n    mimc.k <== 0;\n\n    for (var i = 0; i < 1000; i++) {\n        mimc.in[i] <== in[i];\n    }\n\n    out <== mimc.out;\n}"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Bounty.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"./ICircuitVerifier.sol\";\nimport \"./IEncryptionVerifier.sol\";\n\ncontract Bounty is Initializable, OwnableUpgradeable {\n    uint public completedStep;\n    IEncryptionVerifier public encryptionVerifier;\n\n    // variables set by bounty provier at Tx 1 (constructor)\n    string public name;\n    string public description;\n    bytes[] public dataCIDs;\n    uint[] public labels;\n    uint public accuracyThreshold; // in percentage\n    // reward amount is not stored, use contract balance instead\n\n    // variables set by bounty hunter at Tx 2\n    address public bountyHunter;\n    bytes public zkeyCID;\n    bytes public circomCID;\n    bytes public verifierCID;\n    ICircuitVerifier public verifier;\n    uint[2] public a;\n    uint[2][2] public b;\n    uint[2] public c;\n    uint public modelHash;\n\n    // variables set by bounty provider at Tx 3\n    bool public isComplete;\n    uint[2] public publicKeys;\n\n    // variables set by bounty hunter at Tx 4\n    uint[1005] public input;\n\n    uint8 public constant CID_VERSION = 1;\n    uint8 public constant CID_CODEC = 0x55; // for raw buffer\n    uint8 public constant CID_HASH = 0x12; // for sha256\n    uint8 public constant CID_LENGTH = 32; // for sha256\n\n    // ! current design only allows one bounty hunter to submit proof\n    // TODO: allow multiple bounty hunters to submit proof\n\n    event BountyUpdated(uint step);\n\n    /*\n        Tx 1\n        * take owner address from factory\n        * set bounty details\n        * receive native tokens as bounty reward\n    */\n    function initialize(\n        address _owner,\n        string memory _name,\n        string memory _description,\n        bytes[] memory _dataCIDs,\n        uint[] memory _labels,\n        uint _accuracyThreshold,\n        address _encryptionVerifier\n    ) public payable initializer {\n        require(msg.value > 0, \"Bounty reward must be greater than 0\");\n        // length of dataCIDs and labels should be the same\n        require(\n            _dataCIDs.length == _labels.length,\n            \"Invalid dataCIDs or labels length\"\n        );\n        __Ownable_init();\n        transferOwnership(_owner);\n        name = _name;\n        description = _description;\n        dataCIDs = _dataCIDs;\n        labels = _labels;\n        accuracyThreshold = _accuracyThreshold;\n        encryptionVerifier = IEncryptionVerifier(_encryptionVerifier);\n\n        completedStep = 1;\n    }\n\n    /*\n        Tx 2: submit bounty\n        * submit CID of zkey, circom\n        * submit verifier address\n        * submit proof\n    */\n    function submitBounty(\n        bytes memory _zkeyCID,\n        bytes memory _circomCID,\n        bytes memory _verifierCID,\n        address _verifier,\n        uint[2] memory _a,\n        uint[2][2] memory _b,\n        uint[2] memory _c,\n        uint[] memory _input\n    ) public /*\n     * n = dataCIDs.length\n     * first n elements of input should be the model output\n     * the next 2n elements of input should be the splitted dataCIDs\n     * the last element is the model hash\n     */\n    {\n        require(bountyHunter == address(0), \"Bounty already submitted\");\n        // verifier address should not be 0x0\n        require(_verifier != address(0), \"Invalid verifier address\");\n\n        uint n = dataCIDs.length;\n        require(_input.length == 3 * n + 1, \"Invalid input length\");\n\n        // check if accuracy threshold is met\n        uint numCorrect = 0;\n        for (uint i = 0; i < n; i++) {\n            if (_input[i] == labels[i]) {\n                numCorrect++;\n            }\n        }\n        require(\n            (numCorrect * 100) / n >= accuracyThreshold,\n            \"Accuracy threshold not met\"\n        );\n\n        for (uint i = 0; i < dataCIDs.length; i++) {\n            require(\n                keccak256(dataCIDs[i]) ==\n                    keccak256(\n                        abi.encodePacked(\n                            CID_VERSION,\n                            CID_CODEC,\n                            CID_HASH,\n                            CID_LENGTH,\n                            concatDigest(\n                                _input[n + i * 2],\n                                _input[n + i * 2 + 1]\n                            )\n                        )\n                    ),\n                \"Data CID mismatch\"\n            );\n        }\n\n        verifier = ICircuitVerifier(_verifier);\n        require(verifier.verifyProof(_a, _b, _c, _input), \"Invalid proof\");\n        a = _a;\n        b = _b;\n        c = _c;\n        modelHash = _input[3 * n];\n\n        zkeyCID = _zkeyCID;\n        circomCID = _circomCID;\n        verifierCID = _verifierCID;\n\n        bountyHunter = msg.sender;\n\n        emit BountyUpdated(2);\n        completedStep = 2;\n    }\n\n    /*\n        Tx 3: release bounty\n        * only callable by bounty provider\n        * only callable if bounty is not complete\n        * only callable if bounty hunter has submitted proof\n    */\n    function releaseBounty(uint[2] memory _publicKeys) public onlyOwner {\n        require(!isComplete, \"Bounty is already complete\");\n        require(a[0] != 0, \"Bounty hunter has not submitted proof\");\n\n        publicKeys = _publicKeys;\n        isComplete = true;\n\n        emit BountyUpdated(3);\n        completedStep = 3;\n    }\n\n    /*\n        Tx 4: claim bounty\n        * function to submit preimage of hashed input\n        * only callable if SHA256 of preimage matched hashed input\n        * only callable if bounty is complete\n        * _input\n    */\n    function claimBounty(\n        uint[2] memory _a,\n        uint[2][2] memory _b,\n        uint[2] memory _c,\n        uint[1005] memory _input\n        /*\n            * first element is the model hash\n            * the next element is the shared key\n            * the next 1001 elements are the encrypted input\n            * the last 2 elements are the public keys\n        */\n    ) public {\n        require(\n            msg.sender == bountyHunter,\n            \"Only bounty hunter can claim bounty\"\n        );\n        require(isComplete, \"Bounty is not complete\");\n        require(address(this).balance > 0, \"Bounty already claimed\");\n\n        // verify model hash\n        require(\n            modelHash == _input[0],\n            \"Model hash does not match submitted proof\"\n        );\n\n        // verify public keys\n        require(\n            publicKeys[0] == _input[1003] && publicKeys[1] == _input[1004],\n            \"Public keys do not match\"\n        );\n\n        // verify encryption\n        require(\n            encryptionVerifier.verifyProof(_a, _b, _c, _input),\n            \"Invalid encryption\"\n        );\n        input = _input;\n        payable(msg.sender).transfer(address(this).balance);\n\n        emit BountyUpdated(4);\n        completedStep = 4;\n    }\n\n    // function to concat input into digest\n    function concatDigest(\n        uint input1,\n        uint input2\n    ) public pure returns (bytes32) {\n        return bytes32((input1 << 128) + input2);\n    }\n\n    // view function to verify proof\n    function verifyProof(\n        uint[2] memory _a,\n        uint[2][2] memory _b,\n        uint[2] memory _c,\n        uint[] memory _input\n    ) public view returns (bool) {\n        return verifier.verifyProof(_a, _b, _c, _input);\n    }\n\n    // view function to verify encryption\n    function verifyEncryption(\n        uint[2] memory _a,\n        uint[2][2] memory _b,\n        uint[2] memory _c,\n        uint[1005] memory _input\n    ) public view returns (bool) {\n        return encryptionVerifier.verifyProof(_a, _b, _c, _input);\n    }\n    \n    // TODO: function to cancel bounty and withdraw reward\n\n    // TODO: function to edit bounty details\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/BountyFactory.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\nimport \"./Bounty.sol\";\nimport \"@openzeppelin/contracts/proxy/Clones.sol\";\n\ncontract BountyFactory {\n    address public immutable encryptionVerifier;\n    address public immutable bountyTemplate;\n    address[] public bounties;\n    uint public bountyCount;\n\n    event BountyCreated(address indexed bounty);\n\n    constructor(address _encryptionVerifier) {\n        encryptionVerifier = _encryptionVerifier;\n        bountyTemplate = address(new Bounty());\n    }\n\n    function createBounty(\n        string memory _name,\n        string memory _description,\n        bytes[] memory _dataCIDs,\n        uint[] memory _labels,\n        uint _accuracyThreshold\n    ) public payable returns (address) {\n        require(msg.value > 0, \"BountyFactory: must send more than 0 wei to create bounty\");\n        address clone = Clones.clone(bountyTemplate);\n        Bounty(clone).initialize{value: msg.value}(\n            msg.sender,\n            _name,\n            _description,\n            _dataCIDs,\n            _labels,\n            _accuracyThreshold,\n            encryptionVerifier\n        );\n        bounties.push(clone);\n        emit BountyCreated(clone);\n        bountyCount++;\n        return clone;\n    }\n}"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/ICircuitVerifier.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ninterface ICircuitVerifier {\n    function verifyProof(\n        uint[2] memory a,\n        uint[2][2] memory b,\n        uint[2] memory c,\n        uint[] memory input\n    ) external view returns (bool);\n}"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/IEncryptionVerifier.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ninterface IEncryptionVerifier {\n    function verifyProof(\n        uint[2] memory a,\n        uint[2][2] memory b,\n        uint[2] memory c,\n        uint[1005] memory input\n    ) external view returns (bool);\n}"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing100.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing100 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(0,0);\n\n        vk[1] = G1Point(\n            3066949056198555590635621162084363174762527476622332118327842035011606793952,\n            2162571409210902214336812509672057078658587427403012932644293527850387519156\n        );\n\n        vk[2] = G1Point(\n            8488790424014158852808006439223343295226971170088490706045068147193001550599,\n            15533262107732603341702625683247434142241321708314454154455671678191112358883\n        );\n\n        vk[3] = G1Point(\n            15498356887658237969202350156895359735754782519547024837768823850341320383276,\n            18043358128034609114248819170759582834297009296355155153256975697104654277482\n        );\n\n        vk[4] = G1Point(\n            6567029474530677569488194734194250250570285395463850727851121497011576634627,\n            1952169722727701625695211431819915372584015014098667009341874426445277275409\n        );\n\n        vk[5] = G1Point(\n            7983094460044061917184665751343846528917223973727668540609481601054516669380,\n            13073411943223982722608981931194140929654969432838450821822380279373205694540\n        );\n\n        vk[6] = G1Point(\n            6235254487603623311509594370074069771036715566675668423360562477653321213694,\n            16348146029413394893095677470763579440263315501392573505110251361786086111748\n        );\n\n        vk[7] = G1Point(\n            12126230703813379196905492399911032289157141882681249791742262746221956435664,\n            21824357088719214382926551780637722669585190256191017503396653466603977666160\n        );\n\n        vk[8] = G1Point(\n            10613712952540031218381119319419543617541815295229336208011689530011199688535,\n            4592079294597931003139600470582401940650194077066693677222963213001984771652\n        );\n\n        vk[9] = G1Point(\n            3911255295243246572381650626618017989180793092410038772879346029962164371222,\n            20707153197739152432912301139550552920520579590641272006246634774964843219027\n        );\n\n        vk[10] = G1Point(\n            11892500116628810223727210540182406632392016834847116628237108078905657482121,\n            14711114067180791500399151644962712269552453743799493074158273490185336020392\n        );\n\n        vk[11] = G1Point(\n            9183014413227020895002734499598490676394098841236386025615160839774137140858,\n            9582865320358157815924266045220199184707642207541576610273447728638869402848\n        );\n\n        vk[12] = G1Point(\n            13892435818247230557011116927971479775033781875296602336601976433383564563228,\n            14733448935712935443414454397165120382231825236729361587040978447025752552981\n        );\n\n        vk[13] = G1Point(\n            17401712645354510672876078146418383500681865058306486281552878566762375427257,\n            20486073793183479284747068769667013438227637945205924637833865634902153972807\n        );\n\n        vk[14] = G1Point(\n            12542945177566110147515483264178913219335969620393213829679296068703471654263,\n            14507302716493402635132650456910109213791510706246873554623739152933578354782\n        );\n\n        vk[15] = G1Point(\n            17262671835229452055040768758779568490937342065764654420598847161477754030825,\n            8902971187566518627682001128928050354700036485645478563285262811824680312795\n        );\n\n        vk[16] = G1Point(\n            2517092168115592419226866474026532297002849402135262172105829244870031873767,\n            5441677800156144741677796942852428248886812324716256833812586939545360386553\n        );\n\n        vk[17] = G1Point(\n            16352603512600688738155061629075068863201450829351196946082637536789820772324,\n            18927273847130979134794259223289142814361248364229652488443571874192685947616\n        );\n\n        vk[18] = G1Point(\n            2180973227235578788710927545110613481031038894649648025035535210348330223155,\n            3507425497681887054666522686927478472275561239370715484736685279835745443493\n        );\n\n        vk[19] = G1Point(\n            21060865790233599822231133344591416589146418696172581714008599651157654485577,\n            11445704792629508009509530745672449871152458786577656651399880869793578183538\n        );\n\n        vk[20] = G1Point(\n            14962922779924834333807088380732268106533627899319967840459394518301601944902,\n            12641115320963479719774006201733593283460207791235448771211717531831128631986\n        );\n\n        vk[21] = G1Point(\n            4186981001816470806980748781585918132583910335167314696545999009872429264973,\n            17565855649932537025068269231075491026770085614015983747359821562568883706223\n        );\n\n        vk[22] = G1Point(\n            16312170887333793475640777226722750017815511399203573224417188753987361268062,\n            14942299556601867394310962262283413205020816495555982640061951999926073906170\n        );\n\n        vk[23] = G1Point(\n            11116982558963830693347282315846967801531679296436746818272732121331724415720,\n            5873619496054897441797349224362529314197498237479985364281745701741828890223\n        );\n\n        vk[24] = G1Point(\n            7022610961304395808415740511844195116328680518742785550228915385939858023878,\n            3136892863857862871481332688425068826979796665029750363309374645841360217432\n        );\n\n        vk[25] = G1Point(\n            8157557205265774407360029054875726935492541606165132860923411819480266205728,\n            81012924889287601351558230557166415960328857029602316655253741163216562264\n        );\n\n        vk[26] = G1Point(\n            21387183076392014337790811106800278834050500139493358334136872383128902568974,\n            7314778968936160478301679546290108816508132795495073939210992055620514882950\n        );\n\n        vk[27] = G1Point(\n            17445370062398000783311321822998675262681592534816043788545673331055581981338,\n            4675382597784294729649795567482785231305950693131859255309513051178177175147\n        );\n\n        vk[28] = G1Point(\n            2098486770907856191452018054264372066670081881036141132191766235747034517957,\n            1815216053155211776578165772337605223514474799477706574780357340295527292101\n        );\n\n        vk[29] = G1Point(\n            7247597047636474744927667131995247170347121112158565895891458041517309296389,\n            192163179728062470503970372632568808101844243963511753219985601280107313588\n        );\n\n        vk[30] = G1Point(\n            9501203604906811513710929504005271216818701558451549918406058132625156622140,\n            13415551798489062914081927666384545099868303281595275344663896205914217872078\n        );\n\n        vk[31] = G1Point(\n            8034595547439438515257075919781050926864947386461328816426271763205695561810,\n            3642829052524533022920002316425451318885679003862750085869559319724420881642\n        );\n\n        vk[32] = G1Point(\n            7389684095037929207631024101452345138987391705473424971516979116156341370031,\n            20579346475224820747653673571292546222054464762132703448050660242437987760856\n        );\n\n        vk[33] = G1Point(\n            1099064042522969917142691337028490131971642761995798870015264529977810129874,\n            4136739376632161133724827833970087000788767831702190026854456646968400813758\n        );\n\n        vk[34] = G1Point(\n            15902640373161477583518974310718417505509060791924961343157477459642931778416,\n            1762478943943949736546872517381831620025398511173518621074233342446251355911\n        );\n\n        vk[35] = G1Point(\n            9487596420461016268451980893550096361069347323138723495572679418046046688516,\n            21544892836467812510793690303334485681390117717928076905731274778121908775623\n        );\n\n        vk[36] = G1Point(\n            5820742566388270780628696340911428355864552004252479310278041095949430795376,\n            7641545445878583943991373750714475758318324289158901278777701540735262273286\n        );\n\n        vk[37] = G1Point(\n            12251320072812281522145414395832737970348394787433255591714150097089431407791,\n            1532779231870484091585282548681946168911463262567902797320995702737440600730\n        );\n\n        vk[38] = G1Point(\n            10101613659948566217818739071435123184975710593253921139345225712243031098260,\n            2640636367314325922533248149727739621985364283675597424474610904727340867587\n        );\n\n        vk[39] = G1Point(\n            5274085047519363354811875262114176759943519780130758450894988285688729358933,\n            16937296383981904953674801963392439007888700172373626045529133960039399617263\n        );\n\n        vk[40] = G1Point(\n            3188599184332565193899369748973079401161586075804055427027494260172731823565,\n            12968148658083523222968587586141447230993399408675687327780669641109440554181\n        );\n\n        vk[41] = G1Point(\n            6458679214833537132762167352491386830890325825067568504280547744045616578060,\n            18468430467927738997242809956404712244666634410317213833141099954108019752365\n        );\n\n        vk[42] = G1Point(\n            20623060804426468927294862308817315019265876115430041233840695215686630451173,\n            17087264238689414062897963203925434079076282890481053770322544570572170791084\n        );\n\n        vk[43] = G1Point(\n            13325627203350085472814451732459661888038862533482320269567426702823739329985,\n            15776877746534956413446522278166863682458481282527146558228748205100102572752\n        );\n\n        vk[44] = G1Point(\n            21668441582737826762284872544546266101011979954395973562059583274610785704512,\n            8277583852037002978546735597203532757285123793571816105035644796689659489126\n        );\n\n        vk[45] = G1Point(\n            8536734248796214979017755496101738844563999731454217385048880639936148506055,\n            20050543179037705575872012681412619075809416420502779193387785187983159802429\n        );\n\n        vk[46] = G1Point(\n            11953986823633174213575339280604577641359038793605491295923798560589727371956,\n            13147634485185373963488944552653926289625401157498385879547759582230194995039\n        );\n\n        vk[47] = G1Point(\n            1550712004197774641075033256835604628352158352713007226217725635275012226118,\n            11203299551088982147798422942849790450362141843828509216540844403325585105151\n        );\n\n        vk[48] = G1Point(\n            18196271432499014695041842961836011055301353978784919923839413819261319730858,\n            17098246883967118308242007705459913729702320623322185243317557342538873073008\n        );\n\n        vk[49] = G1Point(\n            11531116823867493145527748839530207312938155107914319337102872641313100242222,\n            2697631011753785502387459101482062165916413038880404121649035963091673433064\n        );\n\n        vk[50] = G1Point(\n            19631156064522474229619641610560117574796667466539324323824988031144145984381,\n            8937425392860060539170803423572257992722753021855554898593023194915230583803\n        );\n\n        vk[51] = G1Point(\n            18051666508329012801246216448195697328672943604860514259327889529692653255003,\n            9776962899569029336118636701542682706337611353719012721741705378235920461022\n        );\n\n        vk[52] = G1Point(\n            11475939723265162413789647159385731316378041455196431353866586443244485875960,\n            19711286708431892260060507102028877127791309206835055077147368871237918812844\n        );\n\n        vk[53] = G1Point(\n            11026344553624187160806030841924275695941597805136178910833830083155671710696,\n            17162259106859976824562173306587249703506336000572176722780992931150003382282\n        );\n\n        vk[54] = G1Point(\n            18072014661614829050905335947561719081371194373328681685188989976710752519958,\n            1048774928195049223435951979787210247304656815367952815402170340291203327793\n        );\n\n        vk[55] = G1Point(\n            3221143767918066976906625234268647838438505710085915094550693082136124954378,\n            10609209382910755371095430847148428568017844178029295267934890570954490604373\n        );\n\n        vk[56] = G1Point(\n            18603265763099527508808162560935573442394246009812715067853557618675227114718,\n            11587922405411678536596695952166816873905254266295729425002776504155871866385\n        );\n\n        vk[57] = G1Point(\n            10114761011080890155283117352096466322084587359113823233655131129809908439285,\n            5508807755576750114007448677480215198205054512071101691922034235838061098992\n        );\n\n        vk[58] = G1Point(\n            9473224577697192182393997942482349654852015982345608217160238854137662694850,\n            5232619463453481364828566196626075235351370331947090314816487540777930815749\n        );\n\n        vk[59] = G1Point(\n            5828405670751893034234121115192004049259338974472201883856438484025352454589,\n            3633323324079227154005083110521782808490892738558883105373813514476535351512\n        );\n\n        vk[60] = G1Point(\n            9481001625234164910092417433822014284864981517603152850384837599413333732088,\n            18386678173060928637493215959625252441776561544797402448843069753038309706398\n        );\n\n        vk[61] = G1Point(\n            364501025358600818780755326403010729029463316682362019677778479288396511819,\n            10921245151415767613656441640218247912049165999046837003614440575555392502991\n        );\n\n        vk[62] = G1Point(\n            7412432117223787136546267187474701163839580784868897752482245004405373487816,\n            14421834339860903299006524733412603591618190844451037914060151606872119869654\n        );\n\n        vk[63] = G1Point(\n            6758356448748273679612068112965369625648505132685375942552567389525551794313,\n            18898694627951555492949080550455672542650697400113643917079813065361088117351\n        );\n\n        vk[64] = G1Point(\n            2232426915296748097728380112764112830256664229981443467879391402850835961005,\n            17886990959858849028776727028779317010658807731479716471554709099443198391877\n        );\n\n        vk[65] = G1Point(\n            19386684389754528007206697728725486021492582825389320018808101756896486223763,\n            5387944841171208361896631485654248835440117619070885391004123093753703767533\n        );\n\n        vk[66] = G1Point(\n            12647065993168520043526182937209775921405750220974685444664551951358272974493,\n            13366972599313287188896739755647120252951756955470758833728145978865191885332\n        );\n\n        vk[67] = G1Point(\n            18787943133831207667822354828276073727409268368355483818755165180933524613843,\n            14157388513572656930506703772013995574294570155316280419904839453909945513212\n        );\n\n        vk[68] = G1Point(\n            21524068563373174125502750466662633697416975469194703149213549758771064143806,\n            19330633973479566265383470717707159202647232323953472749583165647656210689772\n        );\n\n        vk[69] = G1Point(\n            18382902852942323899973219125400009598490102054273518026407333530852107135564,\n            5587556133767484044476916396039091505022130703765554879534031897599284695340\n        );\n\n        vk[70] = G1Point(\n            9606930799644572048804158116652707177514237680732063560098981656270261037968,\n            5136249659645845922930624684319684098674157523379969261653636459876902241146\n        );\n\n        vk[71] = G1Point(\n            13552542113314993893290710085750912895320123663026256826131125947307038096408,\n            709273112699884026311409013166059830376072517342412739277236776866334978888\n        );\n\n        vk[72] = G1Point(\n            4877695026492837904576447514487946170274766503110664007065051006317417028911,\n            9446076080426295446536293256688999725548133948518312450170562478729416816073\n        );\n\n        vk[73] = G1Point(\n            7745407439919264073462666166103574869059650004645099967253653215503500518730,\n            8958000654601464310040236040720076000298815451674171928370656192395821571291\n        );\n\n        vk[74] = G1Point(\n            18666320048773366090983312937110187453777592458193442257099376708416358364469,\n            5539513286001813732779693880109891933912857627313433936315887072372257898800\n        );\n\n        vk[75] = G1Point(\n            17762000693904052174149226238971528607238820505142737089093305569141218095604,\n            21813189192876658164580671884381389056637414147229002438166607672106061685075\n        );\n\n        vk[76] = G1Point(\n            10620403668573083681678811832492214395842703160132031753632193443445132940858,\n            9287214924394327270674892448424295944430582227602780738386553108169870248604\n        );\n\n        vk[77] = G1Point(\n            3225723314799122490693549255900886936628936604463053909144327405767083517367,\n            13296795156783832061321769403471090730204694557283869635175430523261252422880\n        );\n\n        vk[78] = G1Point(\n            19394283269851765166190520453710260933464736369229146491483414402572036649235,\n            8886347394143457971098959915862183096606640244332501467928584161268657741540\n        );\n\n        vk[79] = G1Point(\n            11211101631546988901713127520653099409246632641328196192389635621453268719604,\n            7533450628229590941864952327666728681554006380658922550113985739199255638676\n        );\n\n        vk[80] = G1Point(\n            20281375053270705107000390143308705274685813353750898370539071869251555616918,\n            4191504470134081448832429650265903916036318956937686405591767766612018536246\n        );\n\n        vk[81] = G1Point(\n            21730429297217903457297617624317163698633779108372279268294203214963841239599,\n            3455168649241599958364434680402533707717293629319160914142901270957667623322\n        );\n\n        vk[82] = G1Point(\n            3733487430670068762717150810067800653321114341709315796018436370189955345854,\n            16993516290835476757984075812093517551647545212347461054793061694546089118405\n        );\n\n        vk[83] = G1Point(\n            4069347453305835841899489561884027971507987034637139177752057964697523071884,\n            1956678427081338497880770997396896779466225278969197692269889397339747587977\n        );\n\n        vk[84] = G1Point(\n            12688563169962246380429505363810909719278960011517597178276847596058759674530,\n            2927641600345355068914853681494591852216028218422911788003225244122043842764\n        );\n\n        vk[85] = G1Point(\n            4455557144275882809490589083576310491054371424484637119621439376441819761829,\n            9731487948258565288497893143140566785594886936141150696674322531881129525085\n        );\n\n        vk[86] = G1Point(\n            2619477629022801354541827825039395847140273659251589045546247153678969401001,\n            17836540777608540858002712754656630392833096079100756487601556239085848528635\n        );\n\n        vk[87] = G1Point(\n            17062191534864932254047439130752387946329235277076184342923625213771678836935,\n            12069527596907551270256200398919523423277992112424100276678513119084727281716\n        );\n\n        vk[88] = G1Point(\n            16805402258218753489165124144746360879274608960953677668700957483879628729815,\n            10410789682524022432691807145340097146023648177608444718821101447661767567785\n        );\n\n        vk[89] = G1Point(\n            8008007635828919944721498889155253916141351807179483997112773450223661089031,\n            3056216602318722957626231548277738119817129937156384969718806681210818813385\n        );\n\n        vk[90] = G1Point(\n            17667744232917991611151306720567572212556922769873510455013405323308378680476,\n            2890516289406621384766044747643579791042650014890801167964314867977213603626\n        );\n\n        vk[91] = G1Point(\n            3143780756554946361446807874127330304332880216504691698401282667783892825765,\n            5028022739746074390415051300734944677415023517308139648614267686230087830490\n        );\n\n        vk[92] = G1Point(\n            4441632139452511774754687310993428522463840333562308532916275348517874568273,\n            3805657638938374125360055067937180653723886063939263403849322700999001648464\n        );\n\n        vk[93] = G1Point(\n            3013746618735534923159878225091501634239528953276121826823488677950608530535,\n            13303028874453780721063879979526033805375485792805017809758536559366914354384\n        );\n\n        vk[94] = G1Point(\n            147897481815608548178330421825812162733090109575127779417863797051852392003,\n            8640707092187677945028587417279452926189344446161983387648630388517595059973\n        );\n\n        vk[95] = G1Point(\n            2577256613690079498068095765293720593058588557523481248270938666627067239265,\n            557967286957109878996836148405729465277762109969903801336199294077387543421\n        );\n\n        vk[96] = G1Point(\n            8686488647634619838672230770846132946046686268388456771190560796889050807187,\n            9655938106080828371789874989347293139151622023273311610492266716485237742652\n        );\n\n        vk[97] = G1Point(\n            16599968643048917866313339039047045832907766174850659964114094763810732985169,\n            12352676869643809540552538084233558931904841866746829566346313116816615110547\n        );\n\n        vk[98] = G1Point(\n            9267573706827759556576977525684723234253097476251745496874796559184732114237,\n            19587468868070611863092114139198146359967042685205673652032650844827081496187\n        );\n\n        vk[99] = G1Point(\n            11705191676975146315944183303161754911767575431964910047638549236413625571714,\n            8095106176974497014713170771085910822558210350216200986553411154835804708953\n        );\n\n        vk[100] = G1Point(\n            5280447958522165271753443781707956962932493679043298614057258828764744713115,\n            2950965016195187402652016874997101060634411125365212216271760448064603541692\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing1000.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing1000 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[106] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            19391891390609481429849774145579503985374912055370046060106347963180567737648,\n            7728129834219170358551601609946089408272789276196019291377633982082964264714\n        );\n\n        vk[1] = G1Point(\n            228181717483219631881657075204725935385048273455808643893243197164559350421,\n            15508572652012038327422985835367154161109393774231544670603904898987703339046\n        );\n\n        vk[2] = G1Point(\n            16754121749542176817018561144730772493675261004204649097804584067550029429764,\n            17198634116191727394680940996772782519853632044920636906274502553914565398533\n        );\n\n        vk[3] = G1Point(\n            17957826624334676365790727934855184468288134758298197553821849563875784518295,\n            11406944883794382503312535656888338714736169159186960939240866611040057953907\n        );\n\n        vk[4] = G1Point(\n            4430494423928001497300523686255609706462362613573142892959836577073966586667,\n            13162682470663696321459107672743862398804392623617041025907097398229531565530\n        );\n\n        vk[5] = G1Point(\n            14257009587274680131434329887478603228568836644077894222628586460501309457074,\n            11646274224080018681410242920703798265921447377022922965379193380569262526301\n        );\n\n        vk[6] = G1Point(\n            9705958142725732334171292951895582262453103495226515030924122300318445171445,\n            13694782303955607160992526693851231852459773108619276337185038380591985756496\n        );\n\n        vk[7] = G1Point(\n            17144012643506768456362242707497029877693906598559317669357981307632003015152,\n            11530719059110160059659430237719853818953715174794303473948058261774712009985\n        );\n\n        vk[8] = G1Point(\n            14483890631953705848041353681278392175692989931587713018682235387322135726786,\n            17427021586348812404499081252639576599520587094666536022623220701285350530468\n        );\n\n        vk[9] = G1Point(\n            17889382316777192599293408639688887991696476616460947563545460888753944231405,\n            20352775334017958538073502200757565414898846974625645781257112656447740307043\n        );\n\n        vk[10] = G1Point(\n            5951262494284676135349496221747578090299959473645061787220637810949004073376,\n            14922032753898924330673643869866676805069688661209194494635965419171158760589\n        );\n\n        vk[11] = G1Point(\n            14157110821921252447764389098290770100004176856427647780277344609571231620687,\n            20709704698226862108207042948311273224238835582484024370305399265471877818695\n        );\n\n        vk[12] = G1Point(\n            7728759661843518063486549138063376271515204045617668507188211998990686355923,\n            10711743748251684178249009586963144563210034088884838210857401639959975316833\n        );\n\n        vk[13] = G1Point(\n            2651390927031831475551158402902979685807224853052037975527524295438342728413,\n            11004334363823378697748692777964374325632053561615011779936484804038418721791\n        );\n\n        vk[14] = G1Point(\n            8246811305647017907134069673379285161957161889986106809441259650967328678244,\n            20494711448810555007005264172937271620975611130788125438879019136802800991047\n        );\n\n        vk[15] = G1Point(\n            9227237815575743955536388616372607676700984624496162638091113803457981055424,\n            7490146127910565474405078546634898959685582216342077796995152448422625084147\n        );\n\n        vk[16] = G1Point(\n            14988255449888576466983686333725846498816266130898987208151466403609279975637,\n            171153654716536684403810039714768984905610497645997537317020641135452111030\n        );\n\n        vk[17] = G1Point(\n            4313051815878873447335298243871896526283302009812695687199895781635541219892,\n            18022206114946361755183429638924181803457754841419074711392713576527324416177\n        );\n\n        vk[18] = G1Point(\n            12596501053628393984644163774187853284269767174172592557301269012245428487146,\n            21204447263079063745466366206201043101439752606465213007704313903164357344632\n        );\n\n        vk[19] = G1Point(\n            4130034343055488361685767779382955857974023520998228920193364089842314664441,\n            8542303792250873618267744068827215642358232542234575387855251882269356769896\n        );\n\n        vk[20] = G1Point(\n            6874451393411262130192832783491921955806954538787269105471079063336949779335,\n            6461933848170403547021264180029668962878963209941514169961510428223244909955\n        );\n\n        vk[21] = G1Point(\n            14446083874196363503105045557966370866184469389586599702851903416345637521014,\n            3794939657763066492124405264096579882646447937001202207430292939220594903055\n        );\n\n        vk[22] = G1Point(\n            12619429072171004657585865286806128551255324771581379374115006053003312336296,\n            19034585709515568979275882623176869138315316932867345905842355860246882800271\n        );\n\n        vk[23] = G1Point(\n            9587228225561280563242073506877752354490385404177352841706335890979927900938,\n            13956343537392811329003855132730055606205214193873442646494391935942884829436\n        );\n\n        vk[24] = G1Point(\n            20101337934907004002377597083705994838193569275135806876517069383194438778874,\n            11932388712951261352094258210650491031751658096692447547561800199948408982592\n        );\n\n        vk[25] = G1Point(\n            4864969763814313389538966758485110878780529318576302874540654995999903361786,\n            21172133458608732300887989383427281965171394293400317363673505108237404173045\n        );\n\n        vk[26] = G1Point(\n            5598686200209475726801826209869416677931202133322427961462147150076924987454,\n            12622619536843741987254461244719750638031901625031570099275218121269742818251\n        );\n\n        vk[27] = G1Point(\n            14751187683369284974807198981066190747232275415561207627517237286483560910232,\n            7370796989413051296003280586660709473139474321751039074813372431405031731783\n        );\n\n        vk[28] = G1Point(\n            13373281139229644325143068039438096279917013863338833314623078167728933486768,\n            18183063850705378508093406636734075337683851672731923707148837425651461022765\n        );\n\n        vk[29] = G1Point(\n            14756358962228304251158891920353940748816049525067429607888240490682964727051,\n            20018100238418134474422914328691582505033804481193180797273235391424655852304\n        );\n\n        vk[30] = G1Point(\n            15050376363683056331420166772246738225621521672827061638572803333762939171137,\n            6692324624851091562518331948429504853563070333909916418627744242683838734585\n        );\n\n        vk[31] = G1Point(\n            14613643419505957778895147639592351129371688663085961967252736252082421938049,\n            13492467422136441255221235571918205307022431482664045250662874767261956568072\n        );\n\n        vk[32] = G1Point(\n            19272459865926252510534687364159235945661180836599787066322921201698318795509,\n            16068412419077751339494815562144240543858490922842578066695430530869706287406\n        );\n\n        vk[33] = G1Point(\n            14217590080649035438270780473813500271147838186437137302772374368155325056231,\n            16845218990033720012206713315597881577890180135341475875645585510779182583901\n        );\n\n        vk[34] = G1Point(\n            12766219689999522508596366817447705524383432762899487116849913496852028403974,\n            4442617591051747505650488338566434480312793816520262764041789007779179988292\n        );\n\n        vk[35] = G1Point(\n            2934784815494397384351742089802347731790762336685129985935528071559993822490,\n            17880874099099888607726520043741004359341385182615919072159716670997697418122\n        );\n\n        vk[36] = G1Point(\n            3091792813862966591589586900310729719569763521242154412799763578943493346092,\n            12290890978553676777434435615322571862215959293936331080984908465327888047012\n        );\n\n        vk[37] = G1Point(\n            13349543775207628424618511926556727231899969609146526061238742368888352486720,\n            5003445500192377637035596053952244157270587264435908525609473486606154214324\n        );\n\n        vk[38] = G1Point(\n            13632797795153659929604438391125254473547917060153457450906928983123223191377,\n            5708656200864299430493302357901484790017620521269743632664850438879166816962\n        );\n\n        vk[39] = G1Point(\n            21516403793437117639030947980477132855009778094943037156716379075978787390280,\n            7868436334373748638648374668468765846000853203993087329280199600531049528370\n        );\n\n        vk[40] = G1Point(\n            6770897784781928031867397130583859969297957667075284038692545903252609202431,\n            12046473195834772553947525821743025778710598381179496030496587998620473788606\n        );\n\n        vk[41] = G1Point(\n            5926176049559574560260760825415608508897247818185031118363669095436999505577,\n            1284235126934163425152880230217201535104165367449041665405825230750579143459\n        );\n\n        vk[42] = G1Point(\n            9814794488139713091910995228789191065371188268827695780345623170960847122387,\n            15870155803409128348333957775616624227522281868352860278925895373376838711032\n        );\n\n        vk[43] = G1Point(\n            630137277498399446981091669581474261039009945706701335506763273366672636179,\n            13952577276779470095201114655417544637344887436927155806431990890918153197048\n        );\n\n        vk[44] = G1Point(\n            15192807545573808832740581991479347066357485231283136831234600432486788338824,\n            13336740193212789758417221190944155324475645844938488994636724314418921395651\n        );\n\n        vk[45] = G1Point(\n            7607024848915044030666118805238957943725471764468897335573065792589070610525,\n            18828486222218564947599361272642509130365988231349565397145165726730105380985\n        );\n\n        vk[46] = G1Point(\n            19219088923309135511331143862756584023260991705388547107879751789238398902932,\n            11840728000909187450200302908706078675043705326472195449253543077443288770765\n        );\n\n        vk[47] = G1Point(\n            8198110311046717662168615086746414716008488843642178474166696280798054527609,\n            18391623548971096033174898388145095550422306181038552191664535695479873494861\n        );\n\n        vk[48] = G1Point(\n            20473324992097053080214599560787533368765381847626731312973518541012228935407,\n            15139100058797500577596377412753454591078218415414562312861822286326595328626\n        );\n\n        vk[49] = G1Point(\n            16690152730829129171363650035011230427014461803054035287014395891043858902305,\n            5326966792817389284869617519600725784611480553007555807761966918896487799007\n        );\n\n        vk[50] = G1Point(\n            18586810049419201902021421770909981604979205904450207333004106074319375484261,\n            3000873763528382823704879922058832571060952569141847371705147067254092754708\n        );\n\n        vk[51] = G1Point(\n            6160362872509440327488675888373254687689061222210050599850135296059225220090,\n            11955733398559263911071101838295129900857283000260075168171477297818776773094\n        );\n\n        vk[52] = G1Point(\n            14492156678394742115002689633313558714055091005636725204386661729651842287960,\n            2980665139814186575079397395460047714146959917489383503315814677932929076799\n        );\n\n        vk[53] = G1Point(\n            4437942380909227322513410180060012980958045771284745269897449720247874839689,\n            7150494348880348053541326495332743092604904626956271535314626613514430993283\n        );\n\n        vk[54] = G1Point(\n            10001482437609468168905690425834276810547626250526078900702957349563018037572,\n            17014991335060100931663517391092589109560972962613182089256344856852776456399\n        );\n\n        vk[55] = G1Point(\n            1146270991420408915157883757671063620180145253802196811286398183158315238637,\n            6595381571366057179191301477376853660703424082291020709647253315873432708642\n        );\n\n        vk[56] = G1Point(\n            2295778711541749139331688618938654319774844488123355539010336352804404868225,\n            9038534441289298754730651091717232113184375524170344329410952166419901016636\n        );\n\n        vk[57] = G1Point(\n            18030946263552418600342891101501630584358154999129913737473179136306653430480,\n            10094754102441716302333922040785128796851364870659094529989236043049046754330\n        );\n\n        vk[58] = G1Point(\n            20515540872993825885735721479173249600098405292336704804023475489580401026065,\n            12815186508201140451186217899334134254620120042158973516233694480916914696934\n        );\n\n        vk[59] = G1Point(\n            1804891765707908198689064720256107365408735953357075069394624098415344430470,\n            4312888158987705375771863918381406338922739182806784141939327753721205636124\n        );\n\n        vk[60] = G1Point(\n            16877448648938629336455970504682822004466354494832925338785741819796014329831,\n            9004801518342253672610622229304283273598061572445418279279029358986672673\n        );\n\n        vk[61] = G1Point(\n            11684773357441616204473407127066407940187405235118841266149422930304904671101,\n            4601212052624124091208177291565916707049495386831211638013106687568736240760\n        );\n\n        vk[62] = G1Point(\n            9200780553406884834747928192666944108171558035410990678489962416081866969139,\n            245355479222183059321071080146375836278832602529335915498668060326748169409\n        );\n\n        vk[63] = G1Point(\n            17193390511345077394677912937415581020324899967030747109811423759826062775250,\n            14696937504671569536105740730959339419173196545590013576300751730484773918342\n        );\n\n        vk[64] = G1Point(\n            8297139883987906366044974400932874460526844353137077214534106934254464947529,\n            14639909594931070175367464867880176626775875179760782510898942522291894584639\n        );\n\n        vk[65] = G1Point(\n            3609661837891552736040452521070929765605206776804107786039109126252989056239,\n            10853920482510922842280129089725351153170312759841380539906217565931367896137\n        );\n\n        vk[66] = G1Point(\n            7048912278298591433696726716891346726989208866324514786372956956644445635212,\n            12157714004316966786418194782795130754506250999436816297735513634950158089609\n        );\n\n        vk[67] = G1Point(\n            7237253195546107369268020076523471861310952350764543603629859106621717737743,\n            19116693017681209184478944674814040872992816925296619469639887753314093264028\n        );\n\n        vk[68] = G1Point(\n            820625138379551054125244647280563550681344648876046036596370519279935595980,\n            15390303712492827323530771631892852471365986110637908851116363235496682208149\n        );\n\n        vk[69] = G1Point(\n            8469123334208791102121090147866917462036787879068918118100650044571085670556,\n            985411289560761222426587701260531417696603744604459001958487372203239838614\n        );\n\n        vk[70] = G1Point(\n            13489859579431512566327338972385537701090240862822503025335968374670729750179,\n            15995490443153950629132783532642148356156923684608642055029435450417126828716\n        );\n\n        vk[71] = G1Point(\n            5025068258170967584974704925088363304406401089212153750732215881376591257673,\n            246161595180469439871964180140987057585752496762790101427696426737962631903\n        );\n\n        vk[72] = G1Point(\n            18624725444473222776113747225616131120503456023323493209399495423851291344464,\n            9092973913660288900922543673887769243869708135622690978610355029219090242011\n        );\n\n        vk[73] = G1Point(\n            21061649267559242832401893079341589206002708787277690534085280507837218231993,\n            1900216925036373287933306987274284611233495151280539379320118154386310400384\n        );\n\n        vk[74] = G1Point(\n            5693819266837633730481574793993745768266196474943094326515211680080687275556,\n            8001442935407932010447890827128680450594583042442977582211611638286748616423\n        );\n\n        vk[75] = G1Point(\n            9771493922794336654550195000151837133645846617865062117671322834447274876162,\n            20138988792268648395724831202845132235993313594369643169024085972293417381258\n        );\n\n        vk[76] = G1Point(\n            20562331451062703893881754168627416099192602113158327030049126971276681495286,\n            9922952610656157940491441913447469115396311761440205415203273517602781900330\n        );\n\n        vk[77] = G1Point(\n            1498434369431250451487086928778526427184171624524365632160766332094635168365,\n            10944624617277440037922758627002938245363946650386133795299870996528247641094\n        );\n\n        vk[78] = G1Point(\n            10832377128347608519203756448849245101957725856901326194321191013438270941056,\n            7576992144586346969235891142502318009466716130788201106309475932341748663598\n        );\n\n        vk[79] = G1Point(\n            5404747453972409299405410409234055146842412072217069882583020025356846653559,\n            3428836275574699574063363434174092703696554190928235534549184825651458251596\n        );\n\n        vk[80] = G1Point(\n            7255017254601736382654669268816814947260432488086305071618299686058285162223,\n            388230518794721608401893790016913578404082517791606318989885831955879795517\n        );\n\n        vk[81] = G1Point(\n            4274998285745241118487495635569318784037872516843008992484936039849104436969,\n            14443139989460339019339671111544342047053107908892353590183300190419623712419\n        );\n\n        vk[82] = G1Point(\n            21634128749231115557689347711533942752321658258117687994986298238533176713309,\n            10098417356594951025541196814774222751252911748634174773868142001516047077280\n        );\n\n        vk[83] = G1Point(\n            4046156447368671967831159377498153821361453924530371493710822968609325137996,\n            18017858974683766542167316686978896501129877893451827180444219136119997531276\n        );\n\n        vk[84] = G1Point(\n            21576662739301169631034067114295524106324010408122737616899507736956659368082,\n            15549928284767128044386306983641879983650007657189247282820571281896321376047\n        );\n\n        vk[85] = G1Point(\n            1406769679588655346791608544853221495318169507694271345467605886427526915690,\n            3409297043583054603125408386307169121805510872604185290967931750429507053754\n        );\n\n        vk[86] = G1Point(\n            18106931570945502786841144602374292011476307636057752946308260680847654343704,\n            9791468742662328594521401814684679988434087939060398459565194697721566045579\n        );\n\n        vk[87] = G1Point(\n            7380005378468683252627012582609447422016826052174902627743382133360819693854,\n            20633054862281771907537793266045250094730636508212325524072161612808367803506\n        );\n\n        vk[88] = G1Point(\n            21816007361916942614683383057256332048576032449298996257144182426645723007,\n            10912910615005771985596617300532268853511005944312259503708390682977924203283\n        );\n\n        vk[89] = G1Point(\n            12001517725790823506681311268316938140899443303693221917009913892717505376340,\n            18733366505580458632546585000773545702151172407556419331157287281777465198385\n        );\n\n        vk[90] = G1Point(\n            13038529351805911780242589893720599224800897313574636339730140424280318086809,\n            604867398672054997877704956089885545998912635452415333991349902105952235548\n        );\n\n        vk[91] = G1Point(\n            6965452184674160535858129493567304283978585666567675983356581787165057162793,\n            8188904991803284378320034233479215172581458071883536673427260453562983768793\n        );\n\n        vk[92] = G1Point(\n            7323426258562249761902177855323941542869198991480596258992292026005765690196,\n            7734116018069009730025562122809887507597980452974169334081864598385477997973\n        );\n\n        vk[93] = G1Point(\n            3572211610711428000486113151838078977403731645172584972748286662113382514432,\n            18711593891651314440023504352017778245051448086570991878012325473969331338616\n        );\n\n        vk[94] = G1Point(\n            7677036601374967423052162698241883162849333096754182212479474495752708964837,\n            13798545013798901163002915143037261535691350570216409435910452728915409359004\n        );\n\n        vk[95] = G1Point(\n            11732505988352344596120544927115732305075423591163239480525667528602339935516,\n            4069380080273191891307429136149700368963445073424053925195989656180249274574\n        );\n\n        vk[96] = G1Point(\n            12775129330581327799943466193674752419999697177743962446788076996471746889946,\n            9836399901287341215772290431451579844703774446363508350054750538806344363660\n        );\n\n        vk[97] = G1Point(\n            13659216341517969142512653259655976972352364397892462114225201467730133607513,\n            10152067278164672036207642045055219013398144777524244506209490093573651971267\n        );\n\n        vk[98] = G1Point(\n            14068442030322336486683798451946234901532576912811507447671823028446914239553,\n            16568587289510253032355455503323159426432639802135247941810760160977485677894\n        );\n\n        vk[99] = G1Point(\n            16069986319801270730475863882303863352160415869709497383777418777645617330791,\n            18994036875310789539672950667776067654503953865260933343246227010190649423581\n        );\n\n        vk[100] = G1Point(\n            753591038799143596501465994871794478010410947327974571148528957768253266557,\n            19133326316177193676715715513949481761943512145445692809255783400361270511862\n        );\n\n        vk[101] = G1Point(\n            20744899546338442536314141733271698486308282549096184473846493749354078388224,\n            4296266412857756742059317568058584688284189539295482749514608463273525098549\n        );\n\n        vk[102] = G1Point(\n            18226236009407355395043840129255719097063313226082147037867677763163875120405,\n            10480138883576441496958501474305678339976728704402016351929843304239062870190\n        );\n\n        vk[103] = G1Point(\n            6016937058970533393408421385433942222637329271011067359924898855046257306066,\n            21798492581267253332996483281434717216343667863651530012929767232461027926817\n        );\n\n        vk[104] = G1Point(\n            14397923115246358515482163360065372202753987754986190144191814556562824064782,\n            7082562522891172147798139223080980137320210766135394997285006899994054366468\n        );\n\n        vk[105] = G1Point(\n            10697108852644867098412544109976683532155204204159776614254134730959863833867,\n            11994867655637815554743636701788514532539361892162110783826887964019001033958\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing200.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing200 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            5280447958522165271753443781707956962932493679043298614057258828764744713115,\n            2950965016195187402652016874997101060634411125365212216271760448064603541692\n        );\n\n        vk[1] = G1Point(\n            21171113376957878345034662378962277283829747463293532071719928512190671638083,\n            4805865026742957868954457705535118582692000448362768205304665457685300251605\n        );\n\n        vk[2] = G1Point(\n            5948188885156296094989198479533447429951534547013344174562478255913477773579,\n            15032470709573822420914716859455319025910550193812232842748017612741827359467\n        );\n\n        vk[3] = G1Point(\n            9263852489462342603186337411676045041929248025161376275553876894962863430550,\n            4863067836782397359634422149128116283913942236114436840608384730993137319432\n        );\n\n        vk[4] = G1Point(\n            926514064074676681222187110134871296458850595623702907310835724388441736011,\n            4350423020275254247296522807208833729157693481780274708357059336830695514309\n        );\n\n        vk[5] = G1Point(\n            14277495816440045423208292967620768290327323010711987232012357921824168022805,\n            452813406831923392679918618950711804908492322691474669411098750481388360332\n        );\n\n        vk[6] = G1Point(\n            21160955607465349068877290977785733431510401371411241133134595167149307628387,\n            21463368050659345551623808905518351596176456104821817707497547918238653733221\n        );\n\n        vk[7] = G1Point(\n            11183002294006692676638067716768786690162735498453824969473098484064283574745,\n            21103893027159017522776018105004263486725234249615792521024970644554353834042\n        );\n\n        vk[8] = G1Point(\n            6418211983475451443013895060380495589190337894004739494517415311641307017083,\n            19836012302297744923444257568581960487323032696963795456773227561104319792565\n        );\n\n        vk[9] = G1Point(\n            14671538512368058396179183735665161733543089904313973202465398007941240258821,\n            9592087156754080309406223247428155890413490914730088426530050927752526693517\n        );\n\n        vk[10] = G1Point(\n            13286980494255572219962987476569793213337102009906377320669926269537021252215,\n            3830280696443604677777330555569777642339004031957458355124146714865284291243\n        );\n\n        vk[11] = G1Point(\n            12493977647977285968818168103715924975419190113667040069597912354234466381993,\n            17172386031189148645340319582531462049789845775987692452634195419590805547745\n        );\n\n        vk[12] = G1Point(\n            16866171673489955011148882795394419753508047449368621656003942887805239600594,\n            4909406224635805270725209167819046708849065048979889396978549845539556317061\n        );\n\n        vk[13] = G1Point(\n            21549447761498791801993161159982221152603709088751648367126627583554195510992,\n            19711291914440575810236914432028417340372176108499568040277546145356647512990\n        );\n\n        vk[14] = G1Point(\n            1722005977130280243783223482577807467329473359104220018892945354984630591817,\n            10750976379923118030562322138895757591242488366665840197454520203110283314586\n        );\n\n        vk[15] = G1Point(\n            15330221355422948866378358337302707326804133979111505396813792043700753283152,\n            9102211923949548182062227220028001245297657315611122269679998204315190981093\n        );\n\n        vk[16] = G1Point(\n            4266038004610457914557137313288648553992474529741119152251106296746825565775,\n            11380051686902264120053500481574951946293847546664416180991902246140890052682\n        );\n\n        vk[17] = G1Point(\n            21802104294986801437165734877814061831768929348457115729908524813655682812688,\n            4208646051256363722549041860639692308328727768529411623898442602237418228012\n        );\n\n        vk[18] = G1Point(\n            15550115518156193685814844693713265707931773460490869326408884426922378659401,\n            6332521871459969520603167336897081588610887316032228531976589188039625036008\n        );\n\n        vk[19] = G1Point(\n            1303701498786427432624213189517333456026196687778684587615633707365956142288,\n            15326210099125045196188489368234616376937316575684215785813966064605757886304\n        );\n\n        vk[20] = G1Point(\n            11298549315792122324272483152810241861261708055490267786567948679289118442793,\n            14412918880563079612319230428775565566389031996134521852053875295153539716296\n        );\n\n        vk[21] = G1Point(\n            14252920552827302724502112078148217830072146787137722672010700163285570377137,\n            17854271046972339797757144990705140996994989276908719939831343397078263897545\n        );\n\n        vk[22] = G1Point(\n            1843094137434880333976956915871745512068073113685598160750909697695707488144,\n            20548700663903421631258345406957604165245295201542374338551344788952063295932\n        );\n\n        vk[23] = G1Point(\n            19364586690399038014037746251979121371907920337930850601445543044430470725740,\n            3108996770995638962680876404150700020595387634345913637458940693651680405608\n        );\n\n        vk[24] = G1Point(\n            9711017046111473882147086987926433013327239665642002251154101434458519839035,\n            3295323532668500836651451275248252398137920959089010096627246479705187668456\n        );\n\n        vk[25] = G1Point(\n            7662956193333494172807125530006713818381359462891213536299567570648294708688,\n            10207879831342435320532650361985240869453949315604762398981439620059531155358\n        );\n\n        vk[26] = G1Point(\n            9593585369128848356113503913814696650954054312728624743764805640196319923539,\n            6675510683796064694030104451849925190686159386032755390565362955088506529379\n        );\n\n        vk[27] = G1Point(\n            10179958790781748374921171427096757119084579730536503041739965978096018378257,\n            11232333648524497390763027902469925331911307765091878433918608574649072092797\n        );\n\n        vk[28] = G1Point(\n            16384803781987486822646497737990801684306159912726502052380401788180913159906,\n            10280968134467693352238095218313412653891312838364378109731337009866570875580\n        );\n\n        vk[29] = G1Point(\n            20570722625415916681896412049272090396062124333889274062182326922388788790808,\n            4455676676760779998740130483720349824201654140993164028307484456258256736410\n        );\n\n        vk[30] = G1Point(\n            5550506948556552901948843312893446930792310199685385438117015178909484933291,\n            20080040338186483946019930996109575302331436627802093735518514375897849507642\n        );\n\n        vk[31] = G1Point(\n            8932320587099199334914206696790297795863594026737016815581892467078663352797,\n            4904040155254252133930146814940091630089369828937724021888325552672549445583\n        );\n\n        vk[32] = G1Point(\n            16876757973528875672548369351866199604759959167883965557938102022970644966871,\n            5261794650570734697642238547488896647278172159405262373012912488438149948863\n        );\n\n        vk[33] = G1Point(\n            6901580155303724917730429446205029578595792208881319012511949919656713225530,\n            3620718364937741509622855726183328770204054697132802578321581257425180870012\n        );\n\n        vk[34] = G1Point(\n            2438193835863778319994212875367336120619620198060329005605157170435685297043,\n            19797569917816521293670012507779751046300848041522098441121212450640856760764\n        );\n\n        vk[35] = G1Point(\n            18438672985542835582912637634772724064134100870696238185111168292385587530437,\n            21371554437142409054827324698888723001251126425981672070131934491364164997497\n        );\n\n        vk[36] = G1Point(\n            762620888538686084704185100882201582440423775422592689676720906017011348815,\n            6260451229513081642642173861311769068163374082576870984158698429303863945102\n        );\n\n        vk[37] = G1Point(\n            11046703858637605917091865533729604922584219782712638582381178600080923753528,\n            6862646922304806637513131774162584712954115485111020460746741510910598236283\n        );\n\n        vk[38] = G1Point(\n            6513333700361514532830060598249782774309152149725332800264309939766223252497,\n            18344588134244350665718641824247235350690182484263173836385356112222141773774\n        );\n\n        vk[39] = G1Point(\n            11112064110026980209706715339616548786983441925520567893081786258758800515414,\n            13100990600709210263230702134750728274893461281219110332648563658632703351355\n        );\n\n        vk[40] = G1Point(\n            9115936119265507852632015599904409887273187946574057681407028353185510663176,\n            10790812275128753048378969398626027891082478469357327769985322724010063657211\n        );\n\n        vk[41] = G1Point(\n            3277173731630511585974410003276679371095981356589614653578085190285929153248,\n            2364615376255977999605586884815130116862623552230767065712043432315182299750\n        );\n\n        vk[42] = G1Point(\n            21596987938180582726591334411997526089311434056582966215023525311155704746136,\n            13331184165697234076499648063859864083707991590733720966441634893517002024490\n        );\n\n        vk[43] = G1Point(\n            6135088057065872775349305728864433386895394242230358402063744078862948279332,\n            3141400768544823864088188020891684624944304018601163459825273901533512030175\n        );\n\n        vk[44] = G1Point(\n            6709417955682056897580374547558594445532554071657252391353021655805070606878,\n            20818451539617670837857148151613589445144894488442692962771786710131430455547\n        );\n\n        vk[45] = G1Point(\n            8079954719200519433852355847775839450755775022909846570611933624904541077076,\n            15874867612163234564271208461324374039826507422867032902739126347420668791450\n        );\n\n        vk[46] = G1Point(\n            13311623291078916851186159123706983946160227289099890075366773929889079509305,\n            2451033782492685669321011879211968324176155937238407577989985480793072696452\n        );\n\n        vk[47] = G1Point(\n            522101543498610259930608600962877079665623748315800114519820231965211030576,\n            18293630363124950041511623868747866673942288087160063075036300106859213751216\n        );\n\n        vk[48] = G1Point(\n            13679255030543816984847453129327836253576400280805914075594283496481681511380,\n            9764397508766904948588123093024507548808281268461765561476055566665837937952\n        );\n\n        vk[49] = G1Point(\n            4288320468357868549409514400135040476935963129543905468211523257801011897041,\n            8861800418111510525964031124474575711010404864900428849434864398153132311926\n        );\n\n        vk[50] = G1Point(\n            13901936880993204616062156488432060305725374998518913130438138989624262562949,\n            2309744924723778897110793804534539866197179316754873531772172690026815183889\n        );\n\n        vk[51] = G1Point(\n            17289451806345222086593228086336707095560294277254534579608350911383533013967,\n            12625539384720474294698327787370638455010179205956288774966107376719580141980\n        );\n\n        vk[52] = G1Point(\n            653146760409554023605798923465544685519620253038665691036896276890935632296,\n            20230867730501174333554256563265775915807232296274225577398981473377026870241\n        );\n\n        vk[53] = G1Point(\n            434047786224928981529079789971059073416808060049887902361195639448111131924,\n            1260023257336638024914016653169882787694286669579955973336384372976578620516\n        );\n\n        vk[54] = G1Point(\n            4151709862273797318705125461467982281875369001362723593864260065863297768574,\n            20825517818521394542181715986848612441290034068657796158139476509001980777226\n        );\n\n        vk[55] = G1Point(\n            2170999160538069209783573322275917771071941748970677049765182535879015962617,\n            19047092533825952202813423989937632969784708177794028957062135497207814516494\n        );\n\n        vk[56] = G1Point(\n            18586980296273630695923799094551395963508492495624917579250443877638622193173,\n            1709156378361177185000608769033266268057873175646287678680359014267758791\n        );\n\n        vk[57] = G1Point(\n            13474235397479336187575666791286102482820502173180984429789420757511711768202,\n            1899556591042274113075720644859592124085178547322001450227597751240226472279\n        );\n\n        vk[58] = G1Point(\n            2005812720184289353646250827051865819046057496780017994550946832101036204731,\n            4486611559083460939084460919657379697407050418143224670954667190800447618341\n        );\n\n        vk[59] = G1Point(\n            13830760675794381365940771985940594932334799156645328968036894870042921431336,\n            1654030180088395240266425821239410265015443634266723166016811684398610935718\n        );\n\n        vk[60] = G1Point(\n            11579978283114397499695582131089869431862857390810611299943778812341734377983,\n            2088896203294635288168945001060414317422876469033393790480894661530158610251\n        );\n\n        vk[61] = G1Point(\n            13460789588949740582545770689525773986146557994869273871801294802838367032709,\n            4533837923316941654628238822908514380971930536150069690036861111395921090875\n        );\n\n        vk[62] = G1Point(\n            21519667628362663736912438946150343030988124386514259212902742582085635854200,\n            2324434635155020515934794624673453341130922736349633256447432008665670779202\n        );\n\n        vk[63] = G1Point(\n            9056381623036940123588068171657304614796813515585580409969954923872596245078,\n            17704933343380515642783846926266523916896932418862540925517302198449341110544\n        );\n\n        vk[64] = G1Point(\n            7695322306033856409958491547173662966143040668580954550947680468366769035406,\n            2877193723212967713584922515651828930001713261444528430098244609437057370249\n        );\n\n        vk[65] = G1Point(\n            13766997127557531982245756335640213754237977839668230567498129922964100688978,\n            10510699595009615977639335460287871100884854325152001080440087358399681175692\n        );\n\n        vk[66] = G1Point(\n            14278176010098537699437351946422929138980189970350014914133087132936120929371,\n            13912352960574404351344999885170158139741892583704676576576975451727730306966\n        );\n\n        vk[67] = G1Point(\n            978361915002936038941871838840511129506245705526976647023981791112658267376,\n            19584061077552483611861218662390804555239290680386434604511721142236963193696\n        );\n\n        vk[68] = G1Point(\n            16134720346064768029627434495793576702843591325706626475200224722736249788044,\n            7880123762104004353642668788113224608171777803602347205953465297556295711809\n        );\n\n        vk[69] = G1Point(\n            10883377423534796544175029771036761047650410216663358759968196966972278142571,\n            14446979927255311432588838171393862554565267760324454060386824540856265575070\n        );\n\n        vk[70] = G1Point(\n            698147910733838025973111475792431250859708923182673712455836941974961609340,\n            18140234725528800177535379626583637103030488020915541527527572174148999840442\n        );\n\n        vk[71] = G1Point(\n            13035289178003051936670555261010714243125509220713271357200655975100245790402,\n            7889909909807545727653655718720413499719033808361280159819513784841549772116\n        );\n\n        vk[72] = G1Point(\n            5528581497193346768322150735305590448086775952305100710423803184705388579838,\n            20021405129330638359565856856376743388452017589539437915207081049767491314478\n        );\n\n        vk[73] = G1Point(\n            21183721626390872979349180705913033539826780583465743209063732292874735572245,\n            12183110134915814793504636483874676037895256058938828980469944941241704348911\n        );\n\n        vk[74] = G1Point(\n            15152473084639958281790797561783856098748593452461905592230821570969564642685,\n            10005252360549204901228967105774563537457101093205163122979751644618921286256\n        );\n\n        vk[75] = G1Point(\n            16792072314993010874173160673170409940615676603448165046761658210770879227669,\n            8873027547444816706870371023608255374817168874255395771545132350966165712312\n        );\n\n        vk[76] = G1Point(\n            21469589968231462706507455414437771936820724176048742749784146365991008156366,\n            19102676951961090701198962800517135323468904732435884872398444828133163236867\n        );\n\n        vk[77] = G1Point(\n            19312887425424676941956404333899533051195982135915073444323038894059796015933,\n            18901418620724824545584734768831886152743453111896842185464706958514642877496\n        );\n\n        vk[78] = G1Point(\n            21000488752741561863732693069500217809660570826941056844300525996313238855265,\n            20424037077286200203520665683096808467028776314394259359070163304104222809003\n        );\n\n        vk[79] = G1Point(\n            11076178207947960049121274327623286643237936579536668355904540314532786868236,\n            20372717596038592483882727235354691894426829382240016625806823518575333866399\n        );\n\n        vk[80] = G1Point(\n            1655378702913447157100270752071609217872726200521046701260356551274657027960,\n            28967284103668229696181193628850132729139592127642027139325097191177852130\n        );\n\n        vk[81] = G1Point(\n            18199177513049801651712297443643312553536413112695479395719241094305171418375,\n            3859860445414768796951669518130669988482548212654373739251748503771012045342\n        );\n\n        vk[82] = G1Point(\n            7870140345557008634306780520253793397024030639260767811138928662203082400400,\n            11699624309903026999605564730157309776348571110029711744066071004655661300003\n        );\n\n        vk[83] = G1Point(\n            18124020071144189152643151997625695986888708792226493330082318087156247093029,\n            14512216904003607653530801392651366282622291889311608844548507371848354970816\n        );\n\n        vk[84] = G1Point(\n            10761009456263382772794867246455953971744843949442057865476852836748326631914,\n            9581712976976789128471522266191455763964114170321263116402077750496677562371\n        );\n\n        vk[85] = G1Point(\n            21292703428084255769949416076493027590035214578497191239948302029207503223127,\n            5452128082602780177548790349920977727875188092984116935147350703247979588103\n        );\n\n        vk[86] = G1Point(\n            19154438377872090186309242377341917565103669099495510833828536427180773379060,\n            4306818512358352710283997743757941975997271910152506169214110958062894540805\n        );\n\n        vk[87] = G1Point(\n            3527755320367884710433847836524488324096346170406403589418229268848779341562,\n            15119647369703275335590153565183790934827857992897342136219743840996149733493\n        );\n\n        vk[88] = G1Point(\n            13233999056832897449155061235406098031232200012370041234246498105574334427252,\n            571655669070670499014998080105125235406682739254874487403474094656196983999\n        );\n\n        vk[89] = G1Point(\n            10875809454343129205416373351261482192600203250051512622387838514201272729359,\n            3846148216089728272475676822940829787766663698186552908769871343545410787065\n        );\n\n        vk[90] = G1Point(\n            13523502310925486518618136933704615461787388754091806271994994819638044731535,\n            13113960307281636606592225514637424603619516326349413709355017397697897159922\n        );\n\n        vk[91] = G1Point(\n            13265097320177305674600522452940514248121677412354227192856875392753932922874,\n            18167197366853042263821638004797564633757661249779421455063781655524127665073\n        );\n\n        vk[92] = G1Point(\n            19681771096820908081089688679931445112134797287633896753737927599356874850421,\n            16431495911327956876117796860233103062506699511223144116532588704609279115116\n        );\n\n        vk[93] = G1Point(\n            11344889289070436114978632966578268618959709830378466207099840942185314165983,\n            8516164251069482640075809123739469886512373857184494272907647308106434456809\n        );\n\n        vk[94] = G1Point(\n            4866117775684624511095180462924093195763665414329214924605146523256145359964,\n            4968153995686455206553823328923395188863867299096290331853025273582678720550\n        );\n\n        vk[95] = G1Point(\n            3302314613912759328010966217888131713893080427027535422827668352799763481599,\n            8627340542034964868449361015649147101961241319801566753538248082279285454184\n        );\n\n        vk[96] = G1Point(\n            1385496866542133781136354939130789771283685272635189675502307913581255510706,\n            10312146981466068905019661463122703802687327505428124254376827225993793224344\n        );\n\n        vk[97] = G1Point(\n            5866738265868087598970822982183327076713018156854702754274333773717239196129,\n            20290318502219504323257799207869867067255337146915013406656574857668356684267\n        );\n\n        vk[98] = G1Point(\n            2946041693840769923426378146465947192756502256020579142482489956259202542492,\n            3276664474083413183930116859992183320496198005234426831498567432118208718551\n        );\n\n        vk[99] = G1Point(\n            11872653154234352823865278198226687229259175564408213976433960935388389192307,\n            972080949564172292336265138288331655554084404799297196880901801416518551020\n        );\n\n        vk[100] = G1Point( \n            4152372711129164001388267322213971146957149153241123267759240469268693995296,\n            16544571539237149819430538843718282290150295061723346781981793915262107306295\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing300.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing300 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            4152372711129164001388267322213971146957149153241123267759240469268693995296,\n            16544571539237149819430538843718282290150295061723346781981793915262107306295\n        );\n\n        vk[1] = G1Point(\n            17038417056061139659946137807051559581737390662259548808156355476974535703438,\n            13616219462714789817701991847069545873099739203918157796963388700686845410995\n        );\n\n        vk[2] = G1Point(\n            4269909203941431923700848525155320937917893882736437838404466611318865110777,\n            17781972087881019433854115516884071053590028501700109054624827919936423967694\n        );\n\n        vk[3] = G1Point(\n            4199434400061411542729865554425189405602683929509632298821370991550866166174,\n            2237511483831004857489507549058387223943887825731749819176744496900522260837\n        );\n\n        vk[4] = G1Point(\n            21222163696400322268272970842972800302179969277992812675694958769997610642033,\n            895339814933848106648192758199091169823229390061569651896785756515492224174\n        );\n\n        vk[5] = G1Point(\n            14092397124169615746291174275860732269702769718330125416394432619096139140296,\n            17534833916820410130577528243444581473366375675553503522815046746401619109758\n        );\n\n        vk[6] = G1Point(\n            499166961015769431842410240361838028853434717057615901128533168397581825376,\n            17854820724625378211228691637064441523966178302797193519176862986339310615386\n        );\n\n        vk[7] = G1Point(\n            21774196242455472804185121040099030674961114748012722059361757445531923979522,\n            12663785045585488513875897884976145462456305059639486918913665845484989561431\n        );\n\n        vk[8] = G1Point(\n            5379080663562103928899985704308449514648369722847835806581765968556006461540,\n            13583896217355105802162268359907593912371300023118655312960615850662155435942\n        );\n\n        vk[9] = G1Point(\n            3702550142156082827870350690985489389190301923731779513856385272965628579980,\n            6681799128731339306259152204812929417605866614187466486540534116962244572500\n        );\n\n        vk[10] = G1Point(\n            16103740944043750938998127192387210497602868817465718427893006337421624150845,\n            19025275943365157212370147806969111870676146586152504692331226730021117797121\n        );\n\n        vk[11] = G1Point(\n            21559751585204501645281671262686256862270871137067847377287705207245712015332,\n            12068343131530084919410024627441941188127429402996117845481073952717145523465\n        );\n\n        vk[12] = G1Point(\n            20095552964511053177683819908649881168241093142850479056628959561224389426035,\n            21835512972466395501457904881939746961531487267417263847868688931619508664034\n        );\n\n        vk[13] = G1Point(\n            13633506580973903430759224393705455612216044620691146649886666064763353266741,\n            11823825990552450135533148920645558265826888076310767413895214958666594512581\n        );\n\n        vk[14] = G1Point(\n            6331087831598555852653272698278929340326784507360045768214096636920945436737,\n            16240667664436296998523323743240250683783240895337209190031585497845992966159\n        );\n\n        vk[15] = G1Point(\n            12944771810676742667559706856109246499901761289501926375246861304192283488192,\n            19969967268101772693947699246945492003535686124911069745092859113985388820300\n        );\n\n        vk[16] = G1Point(\n            3029745854421152621137421314822716120710909759915137376432525003315223490717,\n            14327734199676433406189129949899218213491335249316761237447075073981015200873\n        );\n\n        vk[17] = G1Point(\n            21048156346913508694012102010212192581020289295805108400102048530406644429209,\n            8259688367314383325264901424014443381935686348919885813397723010641328395991\n        );\n\n        vk[18] = G1Point(\n            12305683190657652202127061329008429966615019099445183364280917925733830718475,\n            21223812980988918837543009119841694556404608059057714935147626491413780742489\n        );\n\n        vk[19] = G1Point(\n            799701881759318683138216913967700652752702597365764352106390996686004435831,\n            5579707131919908928417007159582724709634829584455899344486569307179282085340\n        );\n\n        vk[20] = G1Point(\n            18405542777295480901591581991276170910527284694330155375610438004450040804136,\n            15993697792405075833830813747839938952708398813187627514593367927598530046019\n        );\n\n        vk[21] = G1Point(\n            5338776963846592706034019420367446697985072684253532725105621087545399045480,\n            3577459043584933085081300684841071150364712449683406921646039132671746468854\n        );\n\n        vk[22] = G1Point(\n            8233788397833521439534370899272930111768999074632287396548417035483934484405,\n            16371747182928497533346882723075345553447759797770441676571910322328305141078\n        );\n\n        vk[23] = G1Point(\n            8723839283777053042589014778220812221378474117826378718090556799361107817903,\n            13447757731856769640891536261475508390700613747296636549091688530160892572414\n        );\n\n        vk[24] = G1Point(\n            4267982150783233195799104290475002481024114461188413962698554103157481481398,\n            19109008882215122234846410828687653078198336526181849579098299412357115795360\n        );\n\n        vk[25] = G1Point(\n            19915693664676382178334397456424522547534255156685812190161269072695799584426,\n            3672241588207226988638709871579349749280416826940434324475705909886919872986\n        );\n\n        vk[26] = G1Point(\n            4836171243863222682433759841603155085951767299206113515586298419607073316417,\n            4692200367008919258921051575379951593207541454066402985161521490873706741207\n        );\n\n        vk[27] = G1Point(\n            3773174909760358993477627847123999387763512808550374064108184698403392246087,\n            577808157649967349359487692527673747611142937132981352253677073360946253998\n        );\n\n        vk[28] = G1Point(\n            6347879848005997688525621664043055297892721110145230897570943214028469401510,\n            1834237462623077490164279275291575410254477713297848497248085235015183905671\n        );\n\n        vk[29] = G1Point(\n            577333949872234615601778989709656874782865026325672764577584878390941419054,\n            19274890401019868622366723491960187428441203246838870403491504842532477677453\n        );\n\n        vk[30] = G1Point(\n            20981278288825532109848887707567500808416535769804128127326883656521247745191,\n            18568816906491361942949485634367620652174037921789749873715931009713007257209\n        );\n\n        vk[31] = G1Point(\n            19134835691455969062338160462263922137789276911205952137498263112942903647334,\n            20803000896257375586973248631549382884634892514368351405434307293085922446551\n        );\n\n        vk[32] = G1Point(\n            2386091113744479468735834388301459360679107908853389497382218972984735025753,\n            7287765893724150160048148641054010761895808662194311875270320643590683966947\n        );\n\n        vk[33] = G1Point(\n            5717426629987168024451171200780910738683284769914161907691298691413939343031,\n            16862323618196447090567093488108348731384560318105657055503872073025964748121\n        );\n\n        vk[34] = G1Point(\n            622606515070173892284721704690140706775442041333730391539319908694933912337,\n            13799861397479139835250657218639627330688875648890590045687888986736016908825\n        );\n\n        vk[35] = G1Point(\n            9842680516355971330241366645923888730853547061410360379680518405604799859376,\n            9980749832468692247312366115751388566648148269000433893956180017086446193063\n        );\n\n        vk[36] = G1Point(\n            6811209919444938032279299517001156642980698211627370571343779662029351187530,\n            8218065660579195254203557946637215582995417237003286067010276389275883124164\n        );\n\n        vk[37] = G1Point(\n            14349029785162711704830361221087492756691192007758648765142963718432370791106,\n            1578928192324053669917431169722016011578725016097957570143229924084132081593\n        );\n\n        vk[38] = G1Point(\n            13363221761826444632090617604586311720473092676761747267436985612574033863983,\n            898432232155731811867810440359206092840929165360666103748001056621201115412\n        );\n\n        vk[39] = G1Point(\n            7298418886179423495415953171303089663122214902295724336460826663538154155331,\n            19681585187525295997974679346477246564750774542706239783533743773327233629523\n        );\n\n        vk[40] = G1Point(\n            9716096799754609708598158471466918104966918100192029299574262613191954542027,\n            1756189004106833078491026111200879193191002036755061417708738243369996970392\n        );\n\n        vk[41] = G1Point(\n            723222355493487324413471583122396313118588605558210374614924275036440232532,\n            10432839125250845800994334838711778885732683657402922416223676730607519779513\n        );\n\n        vk[42] = G1Point(\n            9097186880320535289851902427711788879578660373030033051791726128326732113207,\n            227486243260739890340367073063026695543801086348010057319623142893967086785\n        );\n\n        vk[43] = G1Point(\n            7124473055375980453052603771330073197687251505239791288810662577878594077000,\n            18336324245669414299425070000301650422382132428496391419354104096267643724764\n        );\n\n        vk[44] = G1Point(\n            14598165119473152942483454635139757386186418153066879576312114035192830608005,\n            18753330316944530476100826982257654169401857745336535391572749276504919385428\n        );\n\n        vk[45] = G1Point(\n            7564899514389140949018343889291820550456020433348479415651939408554300885302,\n            1887406313968190396448309972836751633355487692902560363325487489591291151066\n        );\n\n        vk[46] = G1Point(\n            18840668968813526768730733205656949046327758483739358264182284417128445061467,\n            18330554368137985987105276843207959670617755506405336871770751327864953978288\n        );\n\n        vk[47] = G1Point(\n            1557113104695364533820543960324101262598617119492957388434734885030252352619,\n            2158432394009375034975469985613930272228493215064473099679297970383068736415\n        );\n\n        vk[48] = G1Point(\n            8868356795570323044596001785707849850290410342127804343117579049619342344228,\n            18769341574140884193344217189200188860398558849281572915446062514180689022580\n        );\n\n        vk[49] = G1Point(\n            3106413094037772213448230399685812272106096579686010255614552006807976377745,\n            3205603704435607621146354334387443983507644913030528214203911894050581039366\n        );\n\n        vk[50] = G1Point(\n            11431380560098875869979945572370386310260418535514543050251639734518993323090,\n            12082409209708274970603018682378209832753459972356121878248394788242362882759\n        );\n\n        vk[51] = G1Point(\n            21458690769522232957938057902747228453530623533537262100178682457575087147238,\n            17963641186508177946483845027530205032429536184577523287517156393606197318086\n        );\n\n        vk[52] = G1Point(\n            4488320309958710414236644732507887094278337425614302115893716258052763583371,\n            6585219425596487297642287533555773789149564468412163948920835498197653236604\n        );\n\n        vk[53] = G1Point(\n            13054214903558455016181058750362123296972156252705036285835985923950283627707,\n            4411107936900254386402486933734668565215842855304737716567274357851605660786\n        );\n\n        vk[54] = G1Point(\n            8836134442110749891260027958113780934568567624029534254772310601340222660816,\n            18516389664043483924067448895526978451456423078763558084923672906138738079017\n        );\n\n        vk[55] = G1Point(\n            9427796744161838557396890063039726968797021444813612022384740383801819989904,\n            18477937289954441422247094311301450612547267080947201294106847253700552578540\n        );\n\n        vk[56] = G1Point(\n            19490399503064730506057573086139651474697470573155887279868462147318297312800,\n            4756059465842000709504190216871661004910187360887996732846200456511697763953\n        );\n\n        vk[57] = G1Point(\n            11690907006402402602940271394686080614941650673001935420180283057992765908992,\n            8979697205541636606084683945312289558559894268565474813292245851597812669362\n        );\n\n        vk[58] = G1Point(\n            3426026434219517317699701512472579005505992532036942158668660280919905751142,\n            19400363881258690583839965183765461206380385659462687297148365229142471127569\n        );\n\n        vk[59] = G1Point(\n            19960789857885281119567625767403801975322900649972961873828399544446633017265,\n            19223811125245954497003767738749566307891332076209097538016312768027164779367\n        );\n\n        vk[60] = G1Point(\n            2624878593350277693961360192440714296597321410876016904826103870847106153709,\n            13734431351081306809663415655332401971927381205188533230979078223863157181217\n        );\n\n        vk[61] = G1Point(\n            21059274093612914423015944733347643181714430953567551678349933664165609964283,\n            12567004863158726451177888157935448676097077494460826446944024661947547535776\n        );\n\n        vk[62] = G1Point(\n            4173391547982352888996258489739295463441940961276797122807963754763048736369,\n            5166337359503674349720042404447515774181375480957279620971464186779642146361\n        );\n\n        vk[63] = G1Point(\n            11510700586909040437017322407979240620564288248825103375857213733086815727719,\n            564711694063950686928455159175501482830655098085761819029978237586718131027\n        );\n\n        vk[64] = G1Point(\n            2172753768311809877443925569263943534378645867950393427708322942379233838449,\n            1494049539045389209000024708327252071321590758861469946940102610661865113735\n        );\n\n        vk[65] = G1Point(\n            8927270648187351337740084245888055989091755350197739111019174799276805533894,\n            3493874889219644701503765587283050418696879562656829327821087390901428985285\n        );\n\n        vk[66] = G1Point(\n            58610388859575517650061285604793105936493869439721127206330009663936187477,\n            297731796160519780046341464076073452229414177827451864926070334755819543510\n        );\n\n        vk[67] = G1Point(\n            29893500787040215766822107446507628389417705754394324429751442162985741177,\n            3573665914249491735292726220283480172934692956202031875808732961197968285384\n        );\n\n        vk[68] = G1Point(\n            15493371030217856879778475496458003180317830948927781067107235223980611216821,\n            7628246489532069627711702089908466598461190727156559798501081012567852691665\n        );\n\n        vk[69] = G1Point(\n            7833811725191265685163572005631595747815074000880424195656578442664865394816,\n            7365576755871418731434890184649709279510310938451664766773384634175384087711\n        );\n\n        vk[70] = G1Point(\n            4682147553912642882524157919813508037475773424914942220667230332607417002641,\n            3062450747701760491341058528916267452925200635393200111592240141108748032804\n        );\n\n        vk[71] = G1Point(\n            19385671750706494995341678694281380805425293373838336348056703276496811579034,\n            20831767245729944442260265107123599385541777009588140080235172799678245434460\n        );\n\n        vk[72] = G1Point(\n            10172964330651928451500393052790728477262488654695734257652326626258241437854,\n            16591595746933707766919464938463853905197602409951249390957918811090317909268\n        );\n\n        vk[73] = G1Point(\n            2262943521925428685299635620687677751022579265165360729886809352018095872731,\n            8769819618868254433334570902644304340678046698188999940403584135715620779710\n        );\n\n        vk[74] = G1Point(\n            1821098122072480146266422501921518062901901365725568587488921063370472064044,\n            11801655264023087683764388011821037539566438251995329018552420306883041694722\n        );\n\n        vk[75] = G1Point(\n            4081810338956661295955795576306603968364291689187026175662224423041752425078,\n            18921697477105431652081353097690961141366918336719466416587506450308824052599\n        );\n\n        vk[76] = G1Point(\n            16831871209946948249581038738634171095446265903177751413932899799260460622516,\n            4272054428904520777349788679201160432474565635088931034413189153770116600587\n        );\n\n        vk[77] = G1Point(\n            14755251609957523819939823995278236991853529733227909489191791480315239830462,\n            17483530475599239520475007650762084338354992077213033826376091993847101749917\n        );\n\n        vk[78] = G1Point(\n            6775350076464163365143783783063226377459228847662055718181198611224152286541,\n            6119567521590517968827694650385579018849037015008875680722123474018615678527\n        );\n\n        vk[79] = G1Point(\n            13375034798572176431108896785731181544015017913616958815938790189583036069846,\n            16259717178749794717828845353678865201285741914852341390110237490875279553756\n        );\n\n        vk[80] = G1Point(\n            13728965549730907767079538145281659939987539944830605642434868357260143490361,\n            14798998650859844325566254178550347586057629646703078189328883634376015314187\n        );\n\n        vk[81] = G1Point(\n            4698522418630758112331681081076732281064460170018097113472844113505246512295,\n            8704463612916923973854623481657465541719020524526433613314286630383159577537\n        );\n\n        vk[82] = G1Point(\n            3629022607241282611588252761960646825165921382897786199633842838244988789824,\n            8611416691899977777194186735743129014260457304231254148048884163751373546260\n        );\n\n        vk[83] = G1Point(\n            14370296357865692571543921061398049146298892063408032612731229638487286555234,\n            19585462677681820948685148536635736435862989209643998990766138877551024630535\n        );\n\n        vk[84] = G1Point(\n            7531490164301608007554814093942451249551554987003973573643214564031557620536,\n            4668759071165760113288496351814203548987523101302355216154444016283655262376\n        );\n\n        vk[85] = G1Point(\n            17013138372243739206631693703418019166212891323661487697080423533095178904867,\n            6101863081275571038923912495964353526372181698975784673438470104166782438192\n        );\n\n        vk[86] = G1Point(\n            18786778055303766775773041889605889068883655536442862586624768868789727513662,\n            16500190526423617753931342459058054581094121746358372191990168937301376877591\n        );\n\n        vk[87] = G1Point(\n            6004406011795428552176406258823605954453277690417628597607077111485251662557,\n            13188878794168406990832097833587032519415213055954942829134554913718932648734\n        );\n\n        vk[88] = G1Point(\n            11249444568163448906997847437109940397200779936617923901856898755110299548203,\n            10744185631568280526784896867770708586433802192619823660664809458707149975163\n        );\n\n        vk[89] = G1Point(\n            3873858257867761549678429848625608705901951097008729473590302827940083501638,\n            18146187639909605014358510925714566747500206889191421889496958892244601622931\n        );\n\n        vk[90] = G1Point(\n            993180406634623466110619757221141381061429597639840244137001796620500690070,\n            7723483020640454361337709771638680864203094223026031073822710726080098724214\n        );\n\n        vk[91] = G1Point(\n            783935753826513215536158573601546886282135474051116480282462996780213065878,\n            4974660699716417686712668227107728230165087678501722328158808291247539130062\n        );\n\n        vk[92] = G1Point(\n            2973250549957961593646296453115104992218845833336843613866076948557794407754,\n            21554989633296110453004057526404268854659986759537607955567982494153232662985\n        );\n\n        vk[93] = G1Point(\n            5657200549875120461499630029283901906870333656453973294749744847924589373365,\n            6385062108652097685872641309364239635240421158756359788377929871155395223842\n        );\n\n        vk[94] = G1Point(\n            11356022547485536330665218419684939396636820284906022389283085739333596441177,\n            14764566569185456296830786123198427123972269858076568890982969153117841934520\n        );\n\n        vk[95] = G1Point(\n            9496243455909597583063123634278935007088051646697126490324866540258229469320,\n            21056743422453544822990375399902341614831132168787235671314845442921839143040\n        );\n\n        vk[96] = G1Point(\n            11832387138043885725618453163322593474081424480298521160068214815726714665724,\n            8833645982686354129319989489832582428923914023223925737513274223223059724075\n        );\n\n        vk[97] = G1Point(\n            9569755942881006472020793362256013379799877346565384556147952877238199479593,\n            7914468044048702662043958879447100143768447093405900232023273351480836533712\n        );\n\n        vk[98] = G1Point(\n            13246488610358887691124332065461183364219714906137036584375508160882317839454,\n            14397706757203631307654887327939104246412343869671744077678856208341086399885\n        );\n\n        vk[99] = G1Point(\n            3404188911357037676895293427628074904767235375519989554652734459966851646422,\n            8523281169623467264167162469354721430284809524469661063465406198599965720328\n        );\n\n        vk[100] = G1Point( \n            8449608423833037886689363696679598002380977316690731686317181458570600648998,\n            10807090869929946241660711363842162694574415385963956639862188261492004518103\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing400.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing400 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            8449608423833037886689363696679598002380977316690731686317181458570600648998,\n            10807090869929946241660711363842162694574415385963956639862188261492004518103\n        );\n\n        vk[1] = G1Point(\n            4987765922000699190000063413890656698626699992395323520393633298944715902200,\n            7410420611558777613408270988353971533741699207577718941542056333299104867720\n        );\n\n        vk[2] = G1Point(\n            1802653648709708124383489889152016910896669090085798558022103491017340007553,\n            2433672591796689948389406085908308807146200077324925589783263455356345025063\n        );\n\n        vk[3] = G1Point(\n            18941021601181825974922197419395584561279014464626780008228688283754398727028,\n            15433879371645053381009391707804385780893228704046932160942999493457563000749\n        );\n\n        vk[4] = G1Point(\n            11457775978138386475204907544878541216648431984579174292666440067667928346022,\n            255774361505180617857690702080724230358362609517985738525141899487942911072\n        );\n\n        vk[5] = G1Point(\n            11048392709951074627164768214827729752987966021965260962292499245205166008152,\n            560975369669197740307643998141729359043021046869617341037545263648219657039\n        );\n\n        vk[6] = G1Point(\n            6430293402446310585377447781231648068815362442406274173887569721607656288230,\n            7389049400195623386440176728692839163517320032667370664428162192427073962167\n        );\n\n        vk[7] = G1Point(\n            6096138228068865135419920243894536618452195675928731099735760296380930718666,\n            7864691007806755644240289120076212753306715600850031359282177669679813804240\n        );\n\n        vk[8] = G1Point(\n            10061144809842725269004929612810137143015517306919216606904196446374676852114,\n            18547423842557521528708501650703634601817338905175857670553206549299435567669\n        );\n\n        vk[9] = G1Point(\n            7435455837336027629935299085062133545341679335022352370742749657784206957589,\n            6272704894798957816397072816101055404111578352125888509436748954299804213379\n        );\n\n        vk[10] = G1Point(\n            2386020472098105782576266763385435029488285324637819784490968077596868237890,\n            21296610687648731216804387735352008130999874174045407290690839746651304214512\n        );\n\n        vk[11] = G1Point(\n            17432508287385017129581246821702055209639492370142007277647290652614655011010,\n            15855276585163875713755407882944288405425983053894666648469336739669377166344\n        );\n\n        vk[12] = G1Point(\n            14427995829186694340633534838418145707313555591614730554546232113202149072143,\n            11353761225635785458881081698882986617023470822836738182059193560991512992699\n        );\n\n        vk[13] = G1Point(\n            8613251830821230918936112899289877565969148299743731328295728641184637276281,\n            3982170053930105127235322494560682806129646103465483713577557669373302890646\n        );\n\n        vk[14] = G1Point(\n            14159729379012631856794168122360757555393560833907294192139043378542924231647,\n            7363475676741632075890684625424591979687971681092217627417354747808176276324\n        );\n\n        vk[15] = G1Point(\n            3279983063400017405735313785097543836538107570092341731243895291793319185472,\n            7880664673837807824440326388862443176268900843545221780705164994920244447475\n        );\n\n        vk[16] = G1Point(\n            17096112271275632479023105803104446910483368237441393024147484993287722471677,\n            810087113047178113304849768721565905285531304778526553406712872125967939827\n        );\n\n        vk[17] = G1Point(\n            35383858622035015563725178884319245318207027840331169949837618929497890739,\n            2596040529268805952866621347460424158090867956078366940551518683875351195277\n        );\n\n        vk[18] = G1Point(\n            20224037787024713195385754517802049613158501882723651652267838446939195770843,\n            5734082904078263841934306572375236128755848566424133369891018070232828840587\n        );\n\n        vk[19] = G1Point(\n            2996648358063385090866021159838956854832626167238485125787865063256911142904,\n            662070874276227889269808565071845841402992931039585203536019139066265971388\n        );\n\n        vk[20] = G1Point(\n            19730148428979769372988346988921260131345545840380314784853334341866664908522,\n            4269473481277255391429512789903257745383375746622387546144387282321237846486\n        );\n\n        vk[21] = G1Point(\n            17329610706992780272483606640421515197052841442776861245994579852600101592315,\n            9116016805793630060316582858790543878045242519451651144226502022455632235336\n        );\n\n        vk[22] = G1Point(\n            8354396765301249782999984119848628124576415904266727005799482098327927801162,\n            6121534207911972598732948174628911093401363362488309876965038312497114173011\n        );\n\n        vk[23] = G1Point(\n            7951113906019293031699965282775777796020748591422773107112446554619168708601,\n            19620661709414554339737650629362365657510478334127431647887471137663524037650\n        );\n\n        vk[24] = G1Point(\n            11765703121011506149184724151214389791629712714140165211688109292101183441640,\n            20306409547205813657755557754036448492195877817121280028535528654308427271768\n        );\n\n        vk[25] = G1Point(\n            10228409433828672929602682833675675538708379279862799648108466697417806708964,\n            12689477760567413734768039508181173839349984992738298589205968945496073336538\n        );\n\n        vk[26] = G1Point(\n            12871779950493435185460843553930420469667713920767546147662189455247917045027,\n            9462776584491542624950041615661199302988994479116593675280718113064472870036\n        );\n\n        vk[27] = G1Point(\n            3223948815332722572107175547339640387231983407781575143157664997781768102308,\n            2002619842439935097482277826964962341945494360267530738785066751396995379961\n        );\n\n        vk[28] = G1Point(\n            21143380169976828881126300695673140344827025223515609749419394043633020917730,\n            2546921069673914933587743151951823146654805306564591391648831882347028789561\n        );\n\n        vk[29] = G1Point(\n            14450365776853588347258351872169381001258599289753328045145814601873377302248,\n            10422172621693811955606932762570380095411462532869197793645121257200425078445\n        );\n\n        vk[30] = G1Point(\n            19605307124982622949796381001357586067060714678543991843016079970385667233523,\n            15644406365529307086919369468493544924385506439057878553640495186080540709271\n        );\n\n        vk[31] = G1Point(\n            11329643008042969975594461233426884332472238402541569122639612015354895118510,\n            19699215675370267958563534727947063397370486858910888943120833673708918781723\n        );\n\n        vk[32] = G1Point(\n            18365389383236403767320629408356898333972538901513733495345228149289905259527,\n            7989273494142015042620942731157057238239302288960717520358492226812016172084\n        );\n\n        vk[33] = G1Point(\n            4614112284145655014901089094661816780306033497654586693574012366603324476366,\n            16569328845479938406636547248607899731697801951873041181838139520833598182850\n        );\n\n        vk[34] = G1Point(\n            12342247249632202192441042583121642363985491029072376940760539534722920923735,\n            1374366446564205401715568086580906539335444732202590282556811502363806146878\n        );\n\n        vk[35] = G1Point(\n            9613951534860347468983102297892171258047786259034573533629537990593802034429,\n            5017916395614386736421167587362805334230708932204782376684055079258274308907\n        );\n\n        vk[36] = G1Point(\n            5156296361370818381372949438625754095093880179513944472262356238645573054954,\n            11725613468584979128797511733333435062714447055200024275744354689670244587672\n        );\n\n        vk[37] = G1Point(\n            19446318516095762146091962598437802216093999685651408646272183466481978105904,\n            8014994869922185832300513089921433872593128433366885391169675005365828145062\n        );\n\n        vk[38] = G1Point(\n            10166923625325146113988468575839588329284508621615657868760410351370045293376,\n            13356512692649553147904384712029075783311086786634281473334812941261470643599\n        );\n\n        vk[39] = G1Point(\n            332711170693751806204040327431929534554511979004852800360623449774593001272,\n            18643846335020111082423002331118112902777107739977353084772579789856974444637\n        );\n\n        vk[40] = G1Point(\n            6353645237359683243162622767348926052074119370412615263140289005452046769480,\n            8431304765053116019876638291169055381456237438935586129374370851383480310247\n        );\n\n        vk[41] = G1Point(\n            14585403543525157505170475975080056091389588731267981271270741011811632180391,\n            1385155099043255532542186069321534538199668394049330862372739759898812818511\n        );\n\n        vk[42] = G1Point(\n            10920250089204683945356978745792997085730991831121395462594979949265131925809,\n            738356690358462897210980636319428269335251520808727376309159448185529823886\n        );\n\n        vk[43] = G1Point(\n            5359796294178227766350187440852284111613029671423600270420206544024244593990,\n            18397241835381474165518677163436112836628369716206932990747112553138477669517\n        );\n\n        vk[44] = G1Point(\n            16799510291820157919828834722411097154617374581129485093170344599747993750769,\n            9661919173327372074459103818050676268933211291292047052074661282309143408721\n        );\n\n        vk[45] = G1Point(\n            18438489468003777826897223912294939691758692985497580162023869638529098020646,\n            17881046364395827595175165589330551402966974326647015216299208245816742828158\n        );\n\n        vk[46] = G1Point(\n            16279213099530715664259892968085635123242455316178864549158245948885033332327,\n            21586054225696587157070750835564642450428479720413172231165499681673590437271\n        );\n\n        vk[47] = G1Point(\n            8775439012123442033538247130849642392232016149268521496886229402237188125664,\n            10552364397777053240992149749669182329615223593621749403483441227526777877718\n        );\n\n        vk[48] = G1Point(\n            3188890041729243073452124109727986742765291303666491291539528677620744145065,\n            13628718900323921745975233220630860619893136816274789122033183054712293180696\n        );\n\n        vk[49] = G1Point(\n            6568875555326414291178029843365172701961197514168796830625825125393527831624,\n            14131180648964585729576469036683179776338491230781688682191822590508825283143\n        );\n\n        vk[50] = G1Point(\n            10100121706663465502617239737015505073463035987864459437119469133515729521068,\n            20366863750342029329309523287815402998128640825501206619886588928481564435605\n        );\n\n        vk[51] = G1Point(\n            10684218576194997338347165011089291183297909289859719249436935449945007389732,\n            2449918211266528051738802329103297878685804172313094060166323741740991833554\n        );\n\n        vk[52] = G1Point(\n            4397421326625556921353187456160779959148606085541852542520478171990805386796,\n            6230636981232197475584558125388589717640075310646176507800681827089834717085\n        );\n\n        vk[53] = G1Point(\n            4582604747687380973883209652453624670466202968827909920797627101641726031979,\n            9705952646733450955892254571638174286528353789069518565663238059965361642569\n        );\n\n        vk[54] = G1Point(\n            8672877768551250884561695763275165099535870728648689896823482354161184979934,\n            7726718631417251661552617294896073236154716443477088792269538249079756256638\n        );\n\n        vk[55] = G1Point(\n            8213906827594662218180491261261473215507181749839771951179822981092105079453,\n            11457149547499442524968386969402373902851770177718259175281312467929757984056\n        );\n\n        vk[56] = G1Point(\n            2844020653836293086652981862356601554090509693295618836220178373671336532419,\n            14510714631986501053230843146584206886649096906164352574233140890971527321128\n        );\n\n        vk[57] = G1Point(\n            14332375285118889727108851698647970923336740089196281082123945711353882627567,\n            141101594605112898649615232940311850542065168276818672418149449584649065746\n        );\n\n        vk[58] = G1Point(\n            6778217226054814753185272910629306797482333853238929211961815419762432390443,\n            10408226612722620504114668017787041358599032789336815570881467241673138873676\n        );\n\n        vk[59] = G1Point(\n            89441093670790953673601974405086017935032772663206117686556260149276709770,\n            10690565936441277048504791623425380690014596630779626173568511573076598769007\n        );\n\n        vk[60] = G1Point(\n            5236890323725248981654769061114364912801464296868592373976692992169702294991,\n            1778276842665667036817991703342176410202300441391300430093074501197189434348\n        );\n\n        vk[61] = G1Point(\n            1866319676550943812624739915211933596690355201885557660595702445021724742539,\n            6161679080514980207158892191062490747777737910618482656764433289217396026232\n        );\n\n        vk[62] = G1Point(\n            10201942094420469114208410146674447564314510280185244425177559397414094367955,\n            19052097980151008820786500049668079393808905538072772761626175225953996543579\n        );\n\n        vk[63] = G1Point(\n            7138586575609003945240737716938852641780240591037552032470610043469823862870,\n            11647207245481215047657228542920199218812840646465591052187336744304096010497\n        );\n\n        vk[64] = G1Point(\n            20552284598490957432008885212885583206717915771060786259184178445798940012668,\n            19832738077102857981590711708606808711162714946654805592483071520355161986867\n        );\n\n        vk[65] = G1Point(\n            13903577686905114305530217779680162558769808824948170165162883124416092755071,\n            672653457272505284187781077792946857967117084751557783978550746933917600446\n        );\n\n        vk[66] = G1Point(\n            21688738498632521035376921762008468685908127957761472977561623009030992476258,\n            6779417367788642410285534703682756185511976721022534857632441353131807123348\n        );\n\n        vk[67] = G1Point(\n            21656664465367532133705268771109250447017666548180241319162864409963657711101,\n            10332155612726708017195525436228080547592515902202189329930986671458546696350\n        );\n\n        vk[68] = G1Point(\n            14295708433010906286964074775251568607875665250824110041338222639511797118767,\n            5154707604695900834140427940169227919578086626500371519406059423507415550512\n        );\n\n        vk[69] = G1Point(\n            2914518828148204055727355584005465355276369016592785679203722916925202199464,\n            10909262175560433173253729334724003245502381534415092702521594942069474572292\n        );\n\n        vk[70] = G1Point(\n            17472569531675171891662140366852415726090693885530364920137324852510798504372,\n            2590654498940902209085100183100133217484824927601941674226238250097877448977\n        );\n\n        vk[71] = G1Point(\n            10187642669485047575977474740586552961607573483563160525829349172379620977959,\n            6345248219451008558331817528241766475084388697501976890729136761751007577505\n        );\n\n        vk[72] = G1Point(\n            8880558251698981660922693791555157247069786904229059346902102749430691649113,\n            19620160588629666666542068978921841365246366449457136939802699147143527506603\n        );\n\n        vk[73] = G1Point(\n            18214751821864117593426915951422025119575773784215150977220605790624601235144,\n            10398341434125134453837660080020614619483210263401380182807147347953687756242\n        );\n\n        vk[74] = G1Point(\n            18189853426550924856315297380280808204034244026893390438869923304743944184329,\n            19025340377336259124998168739307756753221006118290296080988270008087283324221\n        );\n\n        vk[75] = G1Point(\n            5980500223012554823262940821241606026511250114550019853136407507382556765396,\n            7847823219951471354583810510393400356227929512707225046491122942269925850002\n        );\n\n        vk[76] = G1Point(\n            5596082606828625689072484011432902673290631421377124137839415510591660767516,\n            19386660529754816764112012103402145177322409237436741400428274713556163024202\n        );\n\n        vk[77] = G1Point(\n            2783613922687357879263610061751946341047461386062195812590022220432350450208,\n            5430184091405389593946417054690796725802250813819547095000245553024963572762\n        );\n\n        vk[78] = G1Point(\n            4780969013598657747647981789846435446281356429410644112840026727401926222300,\n            6284350962906963220386750105134869521697338380480289944897649435701332636649\n        );\n\n        vk[79] = G1Point(\n            11962779575503510483597150376051804357184531176597675070683336290631100621307,\n            5101749612787732948149289339649586413852268791000599175114086239787196323269\n        );\n\n        vk[80] = G1Point(\n            5836973732384512570782151282373157790645678929169932713737601365905798158513,\n            11596520216875868121547404923873921743370220694573484566345675452102577190422\n        );\n\n        vk[81] = G1Point(\n            93393188275131897581960226426815725856047809100611278842100658084057419822,\n            20619216115545839346769044639288339437935496282798331372536699333632679662536\n        );\n\n        vk[82] = G1Point(\n            3330491471137810039807672797278064380143151557789143940615821448800453454492,\n            1897773942513623315132563850901471350278928397369463684030164536253372104529\n        );\n\n        vk[83] = G1Point(\n            17005674546107867956717355342613130801406510462483167276888316107593577221184,\n            3231973652564434859290933691096432438909499990419405767637832244423288966436\n        );\n\n        vk[84] = G1Point(\n            18398555417963705526725737510817589600227288777039473144469996215239679070090,\n            18271967216244409000131529673824355924981600272105938369737926161294095083019\n        );\n\n        vk[85] = G1Point(\n            6352471206325505611304995680664589415462615528549772601551124622094105237843,\n            8073597395498210389236649273951828199060281845366055134225874386675607912204\n        );\n\n        vk[86] = G1Point(\n            18866077979002977810333336351423177776031273512921088460638118580551244879729,\n            20232353325373794304805349496845297250641971426115820795531162326507964936614\n        );\n\n        vk[87] = G1Point(\n            14897152370281609491816309264907721123188095515605969368639344601050920107956,\n            13262343506326908273902941353565033594030523843240176497478574813524737797903\n        );\n\n        vk[88] = G1Point(\n            4401431034035759336736839023076592364748177166828823906331550535109834369966,\n            9447035062696599319200255681823184509926708542648163760300892055504494669163\n        );\n\n        vk[89] = G1Point(\n            14543609177558237166802777311129026704326225046877517520431707467448363577040,\n            9424998598105541398810489088095671238916456321148059431958195743607929822552\n        );\n\n        vk[90] = G1Point(\n            12898623315038343825636569615819167848172238074244307067401266411716135818359,\n            3588427241218337170994478408422573431546676488360120458010013213999711817027\n        );\n\n        vk[91] = G1Point(\n            518937046525276211778371652925879483348671390002122590124910715654165846704,\n            1141938371388755563263875210687647896134314651286035247555520995872202756196\n        );\n\n        vk[92] = G1Point(\n            4253048248648086040696109348680511050880683474989387902899434441429490275435,\n            13546825276329134671004677398198078213623377301175547751656873116722167291557\n        );\n\n        vk[93] = G1Point(\n            15152226943193161359565834327538035085049041608610392006372521873727054889112,\n            18550559272594384204837092162931193787479996271679746751666344624228370905099\n        );\n\n        vk[94] = G1Point(\n            20948478496654755700572016220222770216080476124791109554658295053757515953267,\n            7151274204478540650608167974409303763864374097868423288352505735281920372372\n        );\n\n        vk[95] = G1Point(\n            14054962623979136522307857763270334893612312296908528830302497613053817969613,\n            20230818551283838636089720810383176973331565582502954541147513339852152390696\n        );\n\n        vk[96] = G1Point(\n            154348804010340961196965216979396802746977053903829485798076339066027394911,\n            6431301766201778630821024131901162740690024477962919383203572886160553051321\n        );\n\n        vk[97] = G1Point(\n            14012796410695096067182746756572819882384906319438888341570421462970023590753,\n            20517227714863091510549878199372549875920248215540831397018781271270013623770\n        );\n\n        vk[98] = G1Point(\n            20766299270928257646113077603787157792358846532570742888352155118864030222461,\n            10918697045349257395383669284623546940583509560885731346899664842500323418280\n        );\n\n        vk[99] = G1Point(\n            14455210311838864373095335824390341276735646827311008937241631049425236172472,\n            400916631010122523401252840520982744259403053940486500918914563008431123345\n        );\n\n        vk[100] = G1Point( \n            8017365071475770317213092030893590918235912283489212360180207554216851342282,\n            18361965916130157491790771350159694594438800327133458430459013762768733021874\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing500.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing500 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n        \n        vk[0] = G1Point(\n            8017365071475770317213092030893590918235912283489212360180207554216851342282,\n            18361965916130157491790771350159694594438800327133458430459013762768733021874\n        );\n\n        vk[1] = G1Point(\n            4304541759568974579397697901807178453851097495141972366526924038313141810366,\n            20473318768831611269613865608279812716455270667665805296498157284268197301834\n        );\n\n        vk[2] = G1Point(\n            19977510012501255851301050671950976219374372724623527011309695992378684216756,\n            2932816899919789764861350628765939797041808102436282693252727236369960112781\n        );\n\n        vk[3] = G1Point(\n            20916820388690744608110831513816270386890933063962859080657292680583483973080,\n            16552958872040127216456500093852475650244363631348724291065018493317178959236\n        );\n\n        vk[4] = G1Point(\n            11212497791300709312516900965813650516709679249800853595246740963024446655806,\n            14530630388365248990953862059440701080162391348828005098673520994854132099527\n        );\n\n        vk[5] = G1Point(\n            4053511950851511138965733630031315144392821152858873224877953550608316967381,\n            21168578858116906637712541523579778123034833564035820747014015413071032248056\n        );\n\n        vk[6] = G1Point(\n            9632883385651725660184603727856015192489807675961023493198124711243547460969,\n            11502483789102687532495205566510319709321669852085031867356553739610776861262\n        );\n\n        vk[7] = G1Point(\n            15676736871994215377464176099736925120119909051392441725206751354518439240524,\n            10132415200779039829225818585902743413989455419680204706258695955737402214775\n        );\n\n        vk[8] = G1Point(\n            15334783173261988389463969077014180405086683790265063688235529517270533917650,\n            6045319531376190352921001410233498604477568462072089798490790164317293239042\n        );\n\n        vk[9] = G1Point(\n            5027880290341270639780401819770605011057391318752943921761231981849291907167,\n            9455773520497435064893985903531981876847254598458306642123762765525579940354\n        );\n\n        vk[10] = G1Point(\n            11623895108365338332058212771695693052388671542313528283198418991782161317522,\n            8612390934786872972087732070099851647164812338527643399323966316903442983116\n        );\n\n        vk[11] = G1Point(\n            17690084826846586567369933468826638642072562397827987841518529268821674110556,\n            2143421304787954398507327382496985482847450255265617088968923511513791319820\n        );\n\n        vk[12] = G1Point(\n            251573095417040816145539283548271406945582781658210597938203607049972925798,\n            1308725489856719976523794342919326269901565812502890549950054839060572631683\n        );\n\n        vk[13] = G1Point(\n            16830452782001446823755158250451335883584938162123377826895416142299931113717,\n            8771579442638668396946407059819976627306853140878292363230618059312876803274\n        );\n\n        vk[14] = G1Point(\n            20827278204029883608707386169501515934481198080023344205330983555110284654656,\n            18269441903333686294621165418630478375224866698587261112953072452720860186667\n        );\n\n        vk[15] = G1Point(\n            2420957522841539751387302364212636658550448186699327792243676485467872409994,\n            3193575641239653682368897288495980170510432329845353222172746000782745882775\n        );\n\n        vk[16] = G1Point(\n            322228733479907168599504150389724041874273401068355463549199965740281460866,\n            9861924660528696947121810492424883726243721359877143111623957215369520231504\n        );\n\n        vk[17] = G1Point(\n            860254308465449875214779626178957122211651961540905260030261602356064385535,\n            4771787247608554576556436553355513875571994318432669121409906571586359635202\n        );\n\n        vk[18] = G1Point(\n            14959009550015287896764679815745175095914315507644345182798459913554440014939,\n            6447870883355261693897664051041598089546904228271032852584765352456201760778\n        );\n\n        vk[19] = G1Point(\n            19259807411501095131679362488634773335720710378668732819030450480104709910859,\n            13677965295722918609008807643976138705725372154155708020124210311402832096218\n        );\n\n        vk[20] = G1Point(\n            10557836196714597989147881604222431789546090829144238667115539648305967044859,\n            15734451144483764675960118105535536565723127372080261772701886003118691800565\n        );\n\n        vk[21] = G1Point(\n            1274078832688816787011764186163247480174482720548885644187547347294615340847,\n            13040296641622853767839633277627933969605088270498898558896558134114092301703\n        );\n\n        vk[22] = G1Point(\n            11030713120140765023740049644148188674497076030818764667201964107526549030084,\n            21561997324060279345481943505875922463401585748520734580229099361119970524949\n        );\n\n        vk[23] = G1Point(\n            10957907988981022170770412828999965823403381519601320383943238154651207208794,\n            6917156101863130549772588825284337491947791547591138906201280056585418517289\n        );\n\n        vk[24] = G1Point(\n            5967235622407153336281081838611390686315322708505627293526403861614788012341,\n            488752902265956237380217834951233726199708956710230281140504346717636260818\n        );\n\n        vk[25] = G1Point(\n            7120522859090406150558246990569909219984492227600388694919687704944945535448,\n            1425279918749742383315620516634101875196994011868787984960526309149066809608\n        );\n\n        vk[26] = G1Point(\n            11330219186932024729497941960575430970087737336151055719283698481955230597935,\n            307409105388812270622985511943675493307105630889652373578592699133354769341\n        );\n\n        vk[27] = G1Point(\n            10426004155516183371415252544554940188086639338075404987385486939661163762241,\n            2179193041800174831356027078521986654351659413110915578400026602952033324654\n        );\n\n        vk[28] = G1Point(\n            19543618116735863451016836074199454712227340647542812749779702366077347190720,\n            10601471825755589489788694809165065411678638279194900097766487627324933841363\n        );\n\n        vk[29] = G1Point(\n            14347632846876948086160464689927442355894905036130935388910520699696969055655,\n            18886967905325516387807035941378846166492972570045452201584998346152932154392\n        );\n\n        vk[30] = G1Point(\n            1214148960185412539030852911621974057823856030267124005771366380080346599085,\n            21394623962133714508569626309917281370813300092705062355109929436230089766262\n        );\n\n        vk[31] = G1Point(\n            9189866194048437667734042256456452877122643790399537277821142783786339796857,\n            20255038441547858389579834644988181537456268667344166862512034907912862204467\n        );\n\n        vk[32] = G1Point(\n            6050216815783430694237721203316440654896098233584267913014322242408902022767,\n            13698340089802624124341000751242586549910367822213610082073953146846983975987\n        );\n\n        vk[33] = G1Point(\n            20001319643855117433320662280052043500625157005095612332776087889464442337562,\n            10022968087695317932288060187275198194284742120311978572562118715817573692026\n        );\n\n        vk[34] = G1Point(\n            9971727375949556007825462737262815059852484519704711166313646771352960271672,\n            17454859994701552955361863890214553891648302684771171772123210715750909065285\n        );\n\n        vk[35] = G1Point(\n            10105413709221335950755692623212357614135301304369245454776158035829572174485,\n            21172279033777729856876600607120700939495705981557864941267821256499196508615\n        );\n\n        vk[36] = G1Point(\n            6030398850693938437690529800809038290427089356752000751433240213950860214325,\n            18158389634635690702573860844534140854538087102886816391504545272966544179763\n        );\n\n        vk[37] = G1Point(\n            11899525799889897503454671223216130387323051617906381840532773243711259088919,\n            12721955986337670624083494028151230637887399790018187292815389811907468899079\n        );\n\n        vk[38] = G1Point(\n            18025182099212312759869460085610864638012054109400098580538718756340226789759,\n            17157170406292621064396140565017687100876332313530590228651597529072670395249\n        );\n\n        vk[39] = G1Point(\n            7584521350325988890138926941315327206948987740017524631658765390392667221826,\n            14809651019432757586501707231785874057509503052025842485310649390742738480477\n        );\n\n        vk[40] = G1Point(\n            15619429371780263056639941808419692828269076759454566387324330214447135740664,\n            5372299157725707029488376841984469079563476940269589835685995410769370918072\n        );\n\n        vk[41] = G1Point(\n            10308782984982099559743978574049657251840186030114688266705112866332453762706,\n            17838298368200063258611116955435229324352584225138221778904760139315004996732\n        );\n\n        vk[42] = G1Point(\n            11251741559393487831824165431364888260786542801656734079551071976040135197401,\n            21778319640750718716270457454625892708460851686892742938470621747038304701982\n        );\n\n        vk[43] = G1Point(\n            19602676074170334263525684949376274816125885222571700775815916124759964664892,\n            16819099975440257881525901801687754508991500789530040932572540825537511199160\n        );\n\n        vk[44] = G1Point(\n            1529225456473461005617776610533291209017137980474704473729666838695388825766,\n            13862398306554383107920126493798270016130151808631321020027477725558589148614\n        );\n\n        vk[45] = G1Point(\n            32576370183836840827080341831540294408226466974611282317172044096308651478,\n            3875900519874394709096604345967386383756427166468282754128300888706899564508\n        );\n\n        vk[46] = G1Point(\n            16640452001187292982538303567053094101514427451081482565823882009720823774759,\n            7776285599047977882116099247229100826174316609142052559218452971255686412353\n        );\n\n        vk[47] = G1Point(\n            9305065517620518455485027895752411284816493120084039451538120454718234394025,\n            17198944018437778924300981515521717553272008056606734923163391332835576718653\n        );\n\n        vk[48] = G1Point(\n            14412028755337164165033715825349348886350764234653004635916810778452200464081,\n            1405333300816604257051980556789151898456790069017388590311037858519044866363\n        );\n\n        vk[49] = G1Point(\n            15039579999810797824832563119564858570880439423551436278192245355465644922174,\n            9176516284138881995495257518240106331887692360718158497892205380503024356121\n        );\n\n        vk[50] = G1Point(\n            17766653600667195700794928713783883691770891896186795607025320112795370437593,\n            21337585719353361396876788435974083098037207436334914880996236225834831321466\n        );\n\n        vk[51] = G1Point(\n            6892825894581615070083666655767179521829330473221054727853932908076068978081,\n            9672762645046177427171226165882750825354516138623061816335061323822292821723\n        );\n\n        vk[52] = G1Point(\n            17095401404866415110660735909127829704083037415762918404669493842280305179843,\n            15519659126125875181391173753009773984560255699907538476618121381387736669571\n        );\n\n        vk[53] = G1Point(\n            14989793488156664077667465772478745061698755672972964143529612399572584867044,\n            1109347563468930715592230246483233726430804047108598541934735395433648521097\n        );\n\n        vk[54] = G1Point(\n            2830869257820824577179774831677075646263556894687167053704713986875189172804,\n            11751309471174596046620333559302631634224248167548896399639249518518195540141\n        );\n\n        vk[55] = G1Point(\n            9011333166511907466547746211170598318088591569389940173642787939139557295057,\n            20692837883069422632920826286484643204807897585898235525967846700227697742215\n        );\n\n        vk[56] = G1Point(\n            10464939685382257671960065048290356147978505671558858661913471206754440091806,\n            460800390255171296341171509286862603267870783596679888201946216147240923431\n        );\n\n        vk[57] = G1Point(\n            11807364425214749910653767367049462276096076607198023193761897187873318641525,\n            10061677853638446402941615937867801407734269029510398013109394457439497228158\n        );\n\n        vk[58] = G1Point(\n            3048442861577026403302708158556540647742844992145191892005589103636216528684,\n            4386578736456336812430191885928412576096888394657056132057844115468403404787\n        );\n\n        vk[59] = G1Point(\n            2171131638663563549688360475663147299547320568892704263412028561944413174627,\n            15695449925490771688186528970086472813265643589396611657251258950852390004540\n        );\n\n        vk[60] = G1Point(\n            13844277162379382124046630666559332811371952716216866883463032017440714519850,\n            8871107789374732988101979858993543701904162888800897828405730948757111878404\n        );\n\n        vk[61] = G1Point(\n            4944729404118963656989644757107419941307271410534011537412653419362519559640,\n            7783395987198177612134088768531737626842371999090521621751925759265341720256\n        );\n\n        vk[62] = G1Point(\n            17432533308258302574033611616267297017302773466067840071484822176786118807409,\n            18060058553859543677568724241303817152189469811590602180147038523604083737949\n        );\n\n        vk[63] = G1Point(\n            8475972340087985662835423171222759138291630932988635149820496803631342113688,\n            56745213394092780761418739663962213382078843059473421372358886250150788592\n        );\n\n        vk[64] = G1Point(\n            10950013690031098204797801327854301687112415784114979969451055689625962012803,\n            5647448449831630583872972964783802169968456083626290798502140085636840189797\n        );\n\n        vk[65] = G1Point(\n            18099895133003870125291623007368130054171417501457074333371458037503805636431,\n            7982980102743421386368288143030048629134941894063855547800083781626854234328\n        );\n\n        vk[66] = G1Point(\n            8079643377279602042351661158270431474599657170980994490616597334466782255014,\n            2191628368126823712550733728191572744523183623233049596299065439843828742998\n        );\n\n        vk[67] = G1Point(\n            1231239166346782351357142480901385927683590654156904192739889193066021313465,\n            19579888168949670090450503432830245032533441749968894573071999407890058486002\n        );\n\n        vk[68] = G1Point(\n            5483752993002838253336034386972948990721359372861940543561655937664297548631,\n            7880109076325538631547972692846717513194330080778047892536073397367429862567\n        );\n\n        vk[69] = G1Point(\n            14483818733625569269688511296761613491451595854550788207780465329180190991134,\n            1382581360372289179762659583446011743499641586010083209678015629188051620900\n        );\n\n        vk[70] = G1Point(\n            2189203511059681768032946711738953978985080610126290835181299384951155312388,\n            5453796065897797463745819197774272815949802121653618928262165928958111269759\n        );\n\n        vk[71] = G1Point(\n            9878018968419610405792938671097943794401877177275777517255777098755727467901,\n            5271185102096819273957380819511286366721730784796911474238168450614569533020\n        );\n\n        vk[72] = G1Point(\n            15153387253976062002851064123272166908062676188772220475542071592052297414879,\n            2489413700616444525448917580209826850315048566175599692952656255597542674988\n        );\n\n        vk[73] = G1Point(\n            18836727376210128825986557814922998373788331013776168458511869391552129093598,\n            14021484929037784062841092273730557404379129756854637028356927016191156155748\n        );\n\n        vk[74] = G1Point(\n            19824800727768679417792199615475669918070985553350705667997424475077146761643,\n            20496903905733813256129001257145672166630983706847495563264595758036424194511\n        );\n\n        vk[75] = G1Point(\n            11626547214072693792039212654917745064251209998931404214531785445530369795689,\n            12807190011325995013999855931011599393314899498819859425956647659505590918681\n        );\n\n        vk[76] = G1Point(\n            20329863600999721916713284695813851927618492960654319317044700075496313502660,\n            4455330829456852703023585206699537379807763877537594593077772482454063980701\n        );\n\n        vk[77] = G1Point(\n            17169830810561474698394911390100087715372449946985182152491045822981507766170,\n            19468466011592483696513838734457009474660068317023294110857901135683597818100\n        );\n\n        vk[78] = G1Point(\n            9582564960117170576542119356097019749177381387670861109781261269530322386941,\n            10219397096907331450513625907078435812983407719051951804565619502934298971337\n        );\n\n        vk[79] = G1Point(\n            14624060747661387865272243569280245949391969706031557098789087058195115943044,\n            988807413298681846680933465860775732215645476486696298221161565038956446247\n        );\n\n        vk[80] = G1Point(\n            21499667593226149433528714174415346756014312544321485513020213493872841182223,\n            9586593363407050940335731074785997002526934853717960374174770784071830545543\n        );\n\n        vk[81] = G1Point(\n            810985959226505714621969607339055538096455101657721248414246059813700142219,\n            12189918519277150176345981737854523859422969781197993266697461970435960340720\n        );\n\n        vk[82] = G1Point(\n            8615544661771555677220302662061866175737345024975435368483410445448569412551,\n            9405960595317296921280967247319798060322673705216299254348300935752996055008\n        );\n\n        vk[83] = G1Point(\n            4280301489727095826077982107809413319505845332657021649972229400165304218670,\n            21480825210386939758288203605441860004898337556150726945413494985511917415473\n        );\n\n        vk[84] = G1Point(\n            16842901410684551017570200017797525805377888665197655130869623363657403562420,\n            15294397613571528009150500927563532670976987401813618415729110378783332664837\n        );\n\n        vk[85] = G1Point(\n            12131557098392449686213860931489122527525352964063730210906000929708810001219,\n            16961883255862597368549267796324983290399723472917922968879430506674345098848\n        );\n\n        vk[86] = G1Point(\n            16847910718087706614516497788539664564691499899122428448454988072834179884325,\n            3629673865324284869457013992823172244154937507734771866915770360107554640035\n        );\n\n        vk[87] = G1Point(\n            521569922024683695920270223097281425510922901020088505098990305721718044915,\n            965345204929449930659350727589541563870107260393467199799652465062523583874\n        );\n\n        vk[88] = G1Point(\n            19645340885332488791269558029730204810443084055301126302505377632928658624488,\n            626957721766640656925296248809628295895635439199016731086204609937776279305\n        );\n\n        vk[89] = G1Point(\n            18233617445389259073307389213961649913740609062866793979424822501533045562317,\n            5554786298613718646684722304734812879813310042703446369498443800844226944897\n        );\n\n        vk[90] = G1Point(\n            16101646201577482930804060370512628762700427160294952906256357381438096226172,\n            1530887537564539684444604473601199243010348818320710689274106410555701574515\n        );\n\n        vk[91] = G1Point(\n            14136768936121243042127261505679756849661355983109509666277684580170607461657,\n            16108637360648622511491853251316727527602870031735432044730131741601907324448\n        );\n\n        vk[92] = G1Point(\n            7003469698345441904076185805526143590208587023894417588608223277874404663667,\n            7266867566897666394170979687613209882755314980857792207814626620750472739330\n        );\n\n        vk[93] = G1Point(\n            4954231303652339042819599246489124170356991531849173264454143891251842415758,\n            11214024807763816521895788743871044483911190832305467538408487071942212150046\n        );\n\n        vk[94] = G1Point(\n            4459704569271538878801649436116999783934841734064032796211420662534299721761,\n            13732339054560805129169178700490151207715315687871478228254091336429191316963\n        );\n\n        vk[95] = G1Point(\n            1526324267932589544057651500728643910342855251675543938112908960620922615919,\n            681877795824366995767477732042618567155652356001930676721633427631580230413\n        );\n\n        vk[96] = G1Point(\n            7237090428010808996589749162835348315253475844323403672420685527758563908618,\n            4322657802145556608298543787964912964025095373931809147860227387890554813386\n        );\n\n        vk[97] = G1Point(\n            21214482533793195992633882109665005062406891258155310928387424967886525716219,\n            18043875730819678190519200780114577282769928152878007165537113773823454024705\n        );\n\n        vk[98] = G1Point(\n            16445762844845134682806754201581003759800111995178451655668646850974479397506,\n            6237975651557433441092458979993459087090010651508183748485404734528160411299\n        );\n\n        vk[99] = G1Point(\n            20159657021183988462777681624609956627325857198133480756925819692572589388384,\n            6292446742374209026035617577735782556313590110835153313910418666066612616376\n        );\n\n        vk[100] = G1Point( \n            1991890746054979274067153105515635741980863425728522437606931770461856188116,\n            8709422218507846640659975799179145473931881987299362740089298566508329577577\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing600.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing600 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            1991890746054979274067153105515635741980863425728522437606931770461856188116,\n            8709422218507846640659975799179145473931881987299362740089298566508329577577\n        );\n\n        vk[1] = G1Point(\n            10676337987962840629938904937899033313777170974569020296692141515203754866877,\n            4440587844409383944912945767414852123696465798075028348577377558092377018066\n        );\n\n        vk[2] = G1Point(\n            14955757575612589382481659410686993501833216620315306817474546651573700600453,\n            10370006855950664890995775526934220356746402355041610048337834194799172546317\n        );\n\n        vk[3] = G1Point(\n            17101563548693945779621991722050262129128380219651176287567962538930496816847,\n            17229091562189629196247628978774557304526239646048366065617724974799900339234\n        );\n\n        vk[4] = G1Point(\n            18137988582456323383331773713189020252705583308705720180232789119638922985821,\n            12948123280335487278510834211390074799078390249789736860220667772417653547423\n        );\n\n        vk[5] = G1Point(\n            11478737979110458280583755338461427549984571575809702945406892317987885384685,\n            9358257392993554500199971375049186893232008648130970658899179127211874411453\n        );\n\n        vk[6] = G1Point(\n            14870682997037439942844026254508603801985911115761607897123828155085440937231,\n            13112625382249266006030576511593176644228310943813474197089761057758129502826\n        );\n\n        vk[7] = G1Point(\n            21676549701756573822169999055367466401429556936543592685348653155360389457262,\n            7591723833513147615575827559044178806079643113655428178782712405304780598876\n        );\n\n        vk[8] = G1Point(\n            3774442616415136377202191065432272794982237040951528739188372054353005076121,\n            19774878005079678358711377650806309205672488257633808812644341064915607957878\n        );\n\n        vk[9] = G1Point(\n            6673933870509987854027529424100431769979840440636733864536859741818140434826,\n            1089683040083836709437101415304294024366466922974850793464780944710018614571\n        );\n\n        vk[10] = G1Point(\n            9173170029535526242627026784713148787522898863261830114195268833519033268749,\n            7183938295050547179781962356413331745319234138793085302715934145167168611387\n        );\n\n        vk[11] = G1Point(\n            12304420366469338196605591707552140792500464438957410571365408321713750547680,\n            16228076526598527247814383196122867567160657271006903218459608548948257020149\n        );\n\n        vk[12] = G1Point(\n            11494174416777704005111533700422796165646373156163696396238301565657533145268,\n            202199277775470997689025820856192182083225391624115712582022492054167204850\n        );\n\n        vk[13] = G1Point(\n            16265039846382212305395386427972838126443866673491510721276074764166535370846,\n            9567393972623453030960032016763056441951464639574229841313299388871047130590\n        );\n\n        vk[14] = G1Point(\n            18795871325757064601344228490399231883000824898541741137712069305709857221641,\n            3422919360548875796213514847670369598705363528643105910943109052346067229970\n        );\n\n        vk[15] = G1Point(\n            19205466540019019701706186697837456307698224428424967349066803164626195337449,\n            6149245098872623479249285658312345625732987920747632430249091196171265785871\n        );\n\n        vk[16] = G1Point(\n            5384940027043954752082216976340006228599083005099311795354436970857412309620,\n            19590565228159052299115965487060979002341582865688874287311183335492203397647\n        );\n\n        vk[17] = G1Point(\n            3857079719229114024075647208934399441180701749080383675517314615278669341511,\n            13280985502593575271905876866097810531466295707560754884889094249833961841174\n        );\n\n        vk[18] = G1Point(\n            17638169986651884779943537330115548699215338425380569535652550562457824198966,\n            2119478312877586204509892734934244109857983898208082169257426012024104718711\n        );\n\n        vk[19] = G1Point(\n            3210942036679245762099261328968962896245017378154043898829923603930417014103,\n            11733871118752652170150134843618035115367952125006342389966644022622283334990\n        );\n\n        vk[20] = G1Point(\n            2639976868298760643032429720204521406045309223625840213900129914349013356003,\n            19566188772309183558708621171466254844006168935682484179932109913899313817558\n        );\n\n        vk[21] = G1Point(\n            2139270971166084064142886322493582668557568654518354506706091668657606649918,\n            18406686326141760590291039417022029691447522007039299672030865643232638868719\n        );\n\n        vk[22] = G1Point(\n            1927237659163942945517797802170050024654598093492303166151832821870949168436,\n            20696170542122237206323397701908829601416564790029348177046784235621549791818\n        );\n\n        vk[23] = G1Point(\n            14317543828849607859431449048908241632948157957160799908685822418541613863794,\n            2940949782798759409740642151149106325741967669791538128787772556942818080647\n        );\n\n        vk[24] = G1Point(\n            2637598738352507870882611179779267654732690768918012223693931967035502868003,\n            11289944597077752071412885596022974894446205242845940737182086248751501548093\n        );\n\n        vk[25] = G1Point(\n            1532439963276695166946548130479308531965180057559001520948007948566867871158,\n            11824176127819503941733147236373404081814469566040241036455678683958197807227\n        );\n\n        vk[26] = G1Point(\n            112212498393499599623002286431778522543358321687659804681358238387337096968,\n            12710489464988264182572574589743934391298101509654758972707572637820834678496\n        );\n\n        vk[27] = G1Point(\n            84450175545802156729674504891337638126050791302274715412374170783053180606,\n            3026835677602920375948901368579062784474771534672645085750548846318505805771\n        );\n\n        vk[28] = G1Point(\n            794276541260633883806602022295855713524587963925343681019534063196659431285,\n            17046821864895129122284070341138756294391938054588473989432903697052161639917\n        );\n\n        vk[29] = G1Point(\n            15312264798413059191308409616928541635648964494240760673193913260156126804097,\n            4131000634862162170599562269507094430364609903491238140287970791640467783642\n        );\n\n        vk[30] = G1Point(\n            6748077842713937770983358852717490406273997438343165720559438615408726825030,\n            18665832756351907536862209013635594167488823176241740762323398077929991759394\n        );\n\n        vk[31] = G1Point(\n            5814676701960652148941910036019955703806289995364250418398122986165817511281,\n            18448532455341544719666423124457037239427632862417060029369281762292398707615\n        );\n\n        vk[32] = G1Point(\n            1508464233029183382869327031022734606654596728837292774260830083084812375558,\n            6923955608879999364226182621014358660309505574611219450186197273402940534964\n        );\n\n        vk[33] = G1Point(\n            10947337562348086381867493348186290521522963819183546520228115369698642712435,\n            19593894807941204549151973608086579659760153909926221200653845801569084290366\n        );\n\n        vk[34] = G1Point(\n            19583632207375328540633670298937602951206748364602491105862114536318291640485,\n            5160613053570362431336986768430425145438210518458073443144269007734801206051\n        );\n\n        vk[35] = G1Point(\n            8775514004428794000199171534882502338993132879243551032306611712536771741164,\n            5981406504575102067259862605124706837568952033690832502278052885191394509629\n        );\n\n        vk[36] = G1Point(\n            19114249651450145081860826564198295282995391429371905996649311568438228657115,\n            11476526482772414410179901625755346397129144926116141606476468524737144276246\n        );\n\n        vk[37] = G1Point(\n            15536839644249293583940314834031420069505460303668929415399089419462129069686,\n            19462533063638600336482773384806310884406032123240091161958679238548518386279\n        );\n\n        vk[38] = G1Point(\n            20861728658946711486234810805795882096668089311734956466930219635929769011727,\n            4451208153369907230016200840872204260300683891068410655879493670234295919678\n        );\n\n        vk[39] = G1Point(\n            10476505588399690248736596313698901455885560083318560703361252735291192502475,\n            7062241275811484601355698381254679955026977908868968606139703050337629302464\n        );\n\n        vk[40] = G1Point(\n            10242416938628865623217497984941042540200987372871767293213065276620528731287,\n            7766852977209102503334933616139359057913477024217486701562210293206658457000\n        );\n\n        vk[41] = G1Point(\n            19290757574473847832704449017098595519063611101513560256328257990295935875029,\n            4762892452062341395947156253733004605479015629354094465744116682319206334674\n        );\n\n        vk[42] = G1Point(\n            3685480043944652090210241852876453878305139778852404219173159179617599199992,\n            19206490327539556285676670248094425255457119088662368423821634839985795472739\n        );\n\n        vk[43] = G1Point(\n            18994365877798343676152521756565538575817566967535130828183148992481484742132,\n            8990587450249403175033796195945793792649230401779271349686447311683886003940\n        );\n\n        vk[44] = G1Point(\n            2876040824910135159605209469977609004493536925522309192531914227169576267620,\n            7387352974280493358172485824256789808637131412907860755257309465866240851584\n        );\n\n        vk[45] = G1Point(\n            15794021595631576516193599476747719363818112371084745376457357538854822951115,\n            11915599846917807815856091863868625704507923844628525889673419185304535728840\n        );\n\n        vk[46] = G1Point(\n            19214783225418795080452701267238415262313286563678267644075398068217130704141,\n            12599422867498856343868011576407836967848344004000670821803236425864873629455\n        );\n\n        vk[47] = G1Point(\n            19227571667118399512097025453184919778555437782510534053711316257405486673096,\n            13439970680786385721287285887210216814531201339465405619441060894600930722901\n        );\n\n        vk[48] = G1Point(\n            4327652468635959864443834599341897531942999355851828953397677497598767889283,\n            9689928434264636932003920986563191237774203599535812013045114384049763095941\n        );\n\n        vk[49] = G1Point(\n            18941295447766462691698964792870544680587811979613105599513120582778626794835,\n            19683314222292010416126375172425891332112317953464767912269660927323799601962\n        );\n\n        vk[50] = G1Point(\n            12120739014746050219611392444648484874022921397895819512219878173150988028285,\n            19652166490499132354945392468684977565982799909662176404224654744745265852814\n        );\n\n        vk[51] = G1Point(\n            237881758234402446954222664497950338546953329230595214464932154014857259810,\n            14719281298519154581527278689846993887182633656982669338984391792071854460746\n        );\n\n        vk[52] = G1Point(\n            18632829073150434079184078062978158310281561663108318750482322761901608350237,\n            11585829267653250865583840264784434968947377312801084021909677935331542058208\n        );\n\n        vk[53] = G1Point(\n            18303318649200728066996385537355144797366276444827867523233113090431856991553,\n            4235365151761839575889104844093205347192161976241651275273138734693062995174\n        );\n\n        vk[54] = G1Point(\n            18890090581021735966617325787828444397230266865321792718532056454143571062087,\n            20751383109075825084584433957728678864553476389090513256294990631370296966775\n        );\n\n        vk[55] = G1Point(\n            5836615824430432412845469850217993853363468809169064321161133777224314288956,\n            18422497239304973494488132787029234164544624132653818065513104257814941620467\n        );\n\n        vk[56] = G1Point(\n            7589733185782733030323901830971785796043933038412074379542529348116452542009,\n            11766715718260192175108225030457579337570056102827555057628090049751698952022\n        );\n\n        vk[57] = G1Point(\n            9284002794021089888237792563919371858561248534111396518056613715339013981764,\n            14569887250662968688765556238228545429572928572890143209313693988047486877496\n        );\n\n        vk[58] = G1Point(\n            17043323778763938388540520294617087030687188857752301527180701122590597611931,\n            10687906490560375541701187007132402841508713771263911096811375502990430583018\n        );\n\n        vk[59] = G1Point(\n            14221826038609378315287998724283726864362972417471724680789462121102436203348,\n            11071071433361222743085391621348661563213999443606119289162965962287706907836\n        );\n\n        vk[60] = G1Point(\n            21594925826229515150079929921599290167488506281953995378516085711794455729443,\n            5393732559578356519195188735302243112586009982291959247850928095427075449890\n        );\n\n        vk[61] = G1Point(\n            9774156241709987158891288027242901095420496179841233927400219817441767372464,\n            19697221154608740394452383204841289366110396368029185754578596937584487958413\n        );\n\n        vk[62] = G1Point(\n            2026354360306987153408567164279210760409544375767131224724100185674338618404,\n            8746417320997349034385886335700462185669911108823134667924817847148915347336\n        );\n\n        vk[63] = G1Point(\n            17167153551489355723201214959310738579634959967962102363751469276595426325816,\n            7086167752714749227416869760155950483135682524075087259439165981028401935098\n        );\n\n        vk[64] = G1Point(\n            20198554763097394806891164526885569506992705241828569342283518901388886689377,\n            11732875265789693726327424337714782234369043179920143122245587061180599568408\n        );\n\n        vk[65] = G1Point(\n            16936441275108174415382871279660936212816694584217127749435800314024955424778,\n            17712031854234440871150465658509554958651335591201262736993565954299881246703\n        );\n\n        vk[66] = G1Point(\n            15541343147993528013387748692192873710549767789832939967293222115709175048396,\n            18286138647636648933297481758054510371887066590343183750200834396802507054369\n        );\n\n        vk[67] = G1Point(\n            4887467579260161831622592235842366325990329894086791954002498853086577667766,\n            12599768813323827579422011820617161718857444906285658311114907962458144374532\n        );\n\n        vk[68] = G1Point(\n            19036077848419410583506840133132192761572961289384983089968935194354088235629,\n            16577018619671019046267068634097969598059462253425555669069639463243100747842\n        );\n\n        vk[69] = G1Point(\n            10589323327496365317781367964937866604015045840960285135061986283790113793435,\n            9087103423518135119255769906481473722886482025596605541813895320137396749268\n        );\n\n        vk[70] = G1Point(\n            18842003045251709036119479696528229150303241019822364177083819961595015141039,\n            15517974467180247095855112596633809292752186132955233504113145394325906048303\n        );\n\n        vk[71] = G1Point(\n            621470047133153418230065055370325218853405067301277632672729706863610783441,\n            1699954733295783108415731174577278311520551644294951750020243242549676148951\n        );\n\n        vk[72] = G1Point(\n            12928066978673525302795425934191228055792821510296155990559686241811730551641,\n            5687435392608315219617372224692722371478970971680686161675289016966600332002\n        );\n\n        vk[73] = G1Point(\n            21014891738649053731694722109777721710061025605415518551868045485194157100556,\n            295697799079964412603322994909430562800635535065837839046710594350095884180\n        );\n\n        vk[74] = G1Point(\n            14704185573980033596322225212495167180934670683712882419604079607794373927142,\n            18104955373363843217389791810697933643646368703752062999806939389422664090054\n        );\n\n        vk[75] = G1Point(\n            21150973253828352776506019175585137583645522531321080474110129101144005266050,\n            15476352930072943147678403588042480548592566921699068205245617259310442412473\n        );\n\n        vk[76] = G1Point(\n            2069224127534729711554035166684958165682850879697786311864180623747546377725,\n            2942484374038376348218498685981841570693477989265484890640673881576399582099\n        );\n\n        vk[77] = G1Point(\n            15315859492637248346967659903609382952207241383665855249360263323781447030710,\n            3696246630678696300750866833898715093304100970169309096993212030719240900629\n        );\n\n        vk[78] = G1Point(\n            1974763047654268386498873454955400277206653866752705515364588990390156023003,\n            925645981327722971702707136794891600674361676163218764117832492815387764224\n        );\n\n        vk[79] = G1Point(\n            17884622877944795733031665179693292871714857266199154976848024379706970146638,\n            5469345949238498948003812109193099731978410786063261781003175974704362558977\n        );\n\n        vk[80] = G1Point(\n            9181885799005901158707642150087847099905452825385637432860280517016988363569,\n            15441249842491998626306150762025474856762607708256540486012234479945381928910\n        );\n\n        vk[81] = G1Point(\n            3759496225362224577248002160411962955814565360065050276980645082402055641627,\n            5935011984113464681402587154865188867731699601364798939705631309428001462144\n        );\n\n        vk[82] = G1Point(\n            15097192620507267169986959120043804749683071138365521559349178132037151885051,\n            17908485359988852043093067898430122752351850455891892934093055401762858197782\n        );\n\n        vk[83] = G1Point(\n            15537437755033882412101966933599612638981426715605249481930785499739867489224,\n            20942305010995021647597860020096936003762840210415503625798362396318490275895\n        );\n\n        vk[84] = G1Point(\n            12119146910409640628091721585894849575650886562946220453779720616519243016436,\n            13410305235683987603382394290067039930111537434367577245064020179921354302606\n        );\n\n        vk[85] = G1Point(\n            5249185184085883593078033297186849185311283122318950973375008737958380453429,\n            1626841357719962040949458263266786940209896969477409173090841052704933529313\n        );\n\n        vk[86] = G1Point(\n            18464630000378045703134180305927360433848432412796960962363823275154893708775,\n            7360217317730581401998264706795345661025902785795378266490779940627539852201\n        );\n\n        vk[87] = G1Point(\n            16918326974254658559854411558404483456103216340170335119692491971223658767572,\n            13490476801873930080683649088043389957382208134286149325344516629835643752037\n        );\n\n        vk[88] = G1Point(\n            1459559921851603078766076256163673534939391742779580351772404215873020743579,\n            20629905480218711853211687273505769648091531837560664940379555357138192831734\n        );\n\n        vk[89] = G1Point(\n            1558372353523032867054307913585710549511994902648270632889827438756138651460,\n            9986740180963607562153690897459301965262512228428614018065362803904509691380\n        );\n\n        vk[90] = G1Point(\n            2506832722024435312827768092615914632599562047480687199337429204780529581070,\n            10287890505908806279671106644144072406099044994496371048524403968455410854257\n        );\n\n        vk[91] = G1Point(\n            14817809635479489699641585124944383474153667178766062902712365353514652137164,\n            14591833902142153814139517258758666620558640323654065675364323604219009464728\n        );\n\n        vk[92] = G1Point(\n            14292409416184877463021912194087926206835165773003412670633271179704817620161,\n            351067241732773766932092439700887767467427558258551864929360212248928456114\n        );\n\n        vk[93] = G1Point(\n            19063353678932378910493336081610845032566166386130909067953996633938909496909,\n            7433759626972816518131687051012442019608737789459058109109351160296472585652\n        );\n\n        vk[94] = G1Point(\n            7517486242670988843062885219720937925657930582413962007972135680057733486865,\n            3949405456060790882720362221650479561334414465835124090168809195243690734025\n        );\n\n        vk[95] = G1Point(\n            6343077278985446235408248671043126134842272406134312725212438417156826246943,\n            15103115808567544137964446320105282845532540456536372599538816208782651118557\n        );\n\n        vk[96] = G1Point(\n            21010047052528842357960005037205410504230955968543846891413421823590037454316,\n            14549062331351581189899472044923757849425561391976728737079707752355140037982\n        );\n\n        vk[97] = G1Point(\n            11318303814606514209912371311378864942495474734090319362631534371086598296020,\n            8244860275937944937356574568939169936401433747206816258183002842802971991032\n        );\n\n        vk[98] = G1Point(\n            20547861403802667568241638035695757278477295848067410809458249366655752593788,\n            8022350497062802110338499652086545468597343443366418956216931289823247948618\n        );\n\n        vk[99] = G1Point(\n            8156483969709513955102273330333281930346892331162458754170897082812221943140,\n            9559677424494695953773620967422275392896264293969335546549769746568450163841\n        );\n\n        vk[100] = G1Point( \n            9440809148011862556974623395734247470581005158317701517995290948210647853666,\n            2369573725572999683063330590312439537535671140222943207639379654947331629112\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing700.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing700 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            9440809148011862556974623395734247470581005158317701517995290948210647853666,\n            2369573725572999683063330590312439537535671140222943207639379654947331629112\n        );\n\n        vk[1] = G1Point(\n            15318075028679836795452153842860929890016302398392628783129457890273570934487,\n            6906947448238486597875378661481336160713677511969082375414289173694733965656\n        );\n\n        vk[2] = G1Point(\n            10232724436155922649395198778712549217665840026298273212843357670274128849176,\n            16263424411784684658203088908775423557688610856569232734372680115303672658510\n        );\n\n        vk[3] = G1Point(\n            1665830057909672810829770362814179438938699491220919656214066905371213445470,\n            2243152354682578176076884939986624863362958181872418838647707880017878562553\n        );\n\n        vk[4] = G1Point(\n            2736950133174905282810330597718364690869847241891841818631676618288916551505,\n            2337688783171283155243884169326878511095527547732076243378971300114747490862\n        );\n\n        vk[5] = G1Point(\n            13556510704376139199626168188675775603460810796407930379490522536905731836294,\n            15919924705706642804061711676843725449067165094431524794440078218945990108334\n        );\n\n        vk[6] = G1Point(\n            14640468552519220641136124401086122771188593469934705143936804630076393333597,\n            1935843002072423197646660058342977272189131140140513884479434649004258548460\n        );\n\n        vk[7] = G1Point(\n            2196505794822363312427947391802721034682135051475015219495116010458463800735,\n            6326017855562636768476254250393912677771655624807307911890576808255727989947\n        );\n\n        vk[8] = G1Point(\n            7984942812854300319489165441380382505934021580459104700582685800596015956131,\n            3439088260851596304731676827434104438883162676025196961735933714664576910296\n        );\n\n        vk[9] = G1Point(\n            13646785144913893288514407575480231707781904647426216519867978350750156234246,\n            2264066216485377730055438779510705111152670759048258400373442050761359364491\n        );\n\n        vk[10] = G1Point(\n            14652962885171555262102420520822001313650877109646126312563882076647674349484,\n            10083759214641473438450804798428485640149966640763745307148928748425610394557\n        );\n\n        vk[11] = G1Point(\n            21744460526132667767687476597625507953835491210624582536418863451658050926245,\n            15324313694384227589543794247717458321905285040657658012624474963019283039043\n        );\n\n        vk[12] = G1Point(\n            20087735637033362500699235459774783804678503279569454520777493263320480566651,\n            4044845098657295152540372208420039082602525260726267312358400323121099101975\n        );\n\n        vk[13] = G1Point(\n            18468286038775384817453954050843144883017234706115687542389148416203833428154,\n            1346353683108704894340189284039844693934663232919262270708931938870662445028\n        );\n\n        vk[14] = G1Point(\n            11955540328636282717797218964642792954477197172256711050605177437240982850121,\n            1802816533219466412053079762248904783055925068920743406885954839843830259028\n        );\n\n        vk[15] = G1Point(\n            2324906646254228170059185370672163039701489245850868481717857919533031689139,\n            17889320468169194961000111033428458781231566473874088294077735025054363646333\n        );\n\n        vk[16] = G1Point(\n            21530094141565602955128692423806771635835772727037482080901706020938494245053,\n            12417085588577798931784586299010724179364597473301366716911339929947975718529\n        );\n\n        vk[17] = G1Point(\n            10839055874712898092844718786794913539625642087879039364516847991478742942662,\n            9495509572666530034054587362494460037139501416251853898883027026733863446116\n        );\n\n        vk[18] = G1Point(\n            13737753549448063721497106257624560388939617486326687733428043657018874658062,\n            18344496113152595829617176049578796514225730499789576343973662736670642504358\n        );\n\n        vk[19] = G1Point(\n            6454046004836841251988354699311799564400790339156958272645380729957151051861,\n            7334775708641941775372475268384270433610842559125214162984315356831492034812\n        );\n\n        vk[20] = G1Point(\n            4985832960599073480917747957463910298045424101068341974358144613129998927929,\n            15252816997994888008062976409248056483599915347400280731923091723619564412028\n        );\n\n        vk[21] = G1Point(\n            14304667593420070100606836248166339383790333989468824143039342868768707464368,\n            369133312246633003904179335285634175029180886023440782195533370236046419339\n        );\n\n        vk[22] = G1Point(\n            10638050340835437483582284153850558919662538285107039444833944166526052396996,\n            2416326854948723911020041951744088388170538771642548548511089770080543321563\n        );\n\n        vk[23] = G1Point(\n            1184576113094836674053974418747252670730632245327780912804003777807008737779,\n            492589508170803219174060296713985007665453381290523700606395452549066898417\n        );\n\n        vk[24] = G1Point(\n            139045435506154294305482137647494596325104324063724744065402213944486809494,\n            190167081571836916600349514520491156169308361044747901097253822629402816714\n        );\n\n        vk[25] = G1Point(\n            20011817101672486002762129096244368410450976165871542972419461150024114511462,\n            2268754177645246617760603232154016135005591683438470858703261231650697607414\n        );\n\n        vk[26] = G1Point(\n            8126676026642507020784966084610609603051746012006143152165739725036116438162,\n            16301460636769933596924297639691099123279032066830201397997036814854708411234\n        );\n\n        vk[27] = G1Point(\n            15182371140434545734919976399096156513200344170862705790028451933899990088750,\n            14886137234879191276754321218771210844645087220883691066177751630733980544858\n        );\n\n        vk[28] = G1Point(\n            9482105089608262545795941488575944982828037660370638560171572400163063909646,\n            2478936322789256219800807804480361936040667208279214722379594110551344692030\n        );\n\n        vk[29] = G1Point(\n            3526858519483000909925080586712720004943102679738469025151963130491726474118,\n            4221816626308591756087962828353317483319775685411137598790228350928597261585\n        );\n\n        vk[30] = G1Point(\n            21009385654466261656575466339985816290472884172459452725544957676016658174244,\n            6940606392732842500906992731432385152348952335194742200111037243366833841029\n        );\n\n        vk[31] = G1Point(\n            21487289791185583317219560880873212024175148668062626671194632227015133222199,\n            4678176459822177673341929134380007205388373015951336180858949061095169770339\n        );\n\n        vk[32] = G1Point(\n            4846338358430393484718989420778440439884942924712160292136034811973321170391,\n            9276065995362350098493913667710556869028989375939284218506887145545531906308\n        );\n\n        vk[33] = G1Point(\n            19807352861051076128323371895420679622584824587669303851839822984925468433635,\n            2819338108717818835966750401327263034769854678308154772288224264666915554500\n        );\n\n        vk[34] = G1Point(\n            18442821910672854271372135076414665543447027388950355144793274885854570278356,\n            16110897164840125885115184924229888192957820657963124150253545635057798271182\n        );\n\n        vk[35] = G1Point(\n            9845196253801508627991031814739337169565915679719272798146816453280317613511,\n            12217225066674011044197462813174071395493307134207346036288752443912591910240\n        );\n\n        vk[36] = G1Point(\n            3923991577928869560407118448271935218211526781929533551653244675654424987399,\n            10670233863120436333851986400321650576317964760778020746262978262519720523467\n        );\n\n        vk[37] = G1Point(\n            8336898532627120252759686863720369395168904730360098007835038795036150945342,\n            3378619508622787403718694602199093220355649059515345767006084234536150499983\n        );\n\n        vk[38] = G1Point(\n            897285997625370664078917573668630146198661974767673900066084547895943597017,\n            15524491895767300928092219966671572144578566329524261304882078288153471456094\n        );\n\n        vk[39] = G1Point(\n            13384461114315229634398048586053811915933365986154711031203551918662012281832,\n            11448176211085735151424618883362500388640800134188666775561558945685832848059\n        );\n\n        vk[40] = G1Point(\n            18189127221978188942884755581833475186131611253432190657741855375911166761225,\n            10685515718448251366474366179042702996077788924970477576224012421474733557897\n        );\n\n        vk[41] = G1Point(\n            17669878833580716738820657576530163660678305606018319861039036613211928620817,\n            21133146172609391048774366251950682288362049186851806207513109688734317755680\n        );\n\n        vk[42] = G1Point(\n            20777601464794113064251759589763308438467593962518402398283855435229682299107,\n            15679067851644842089735396247563945891271816010012252610910185557788361880019\n        );\n\n        vk[43] = G1Point(\n            14966983593274047863845710067241688224129354842974476374337241633874466579607,\n            19234292190779201725109147651168659414383152620598049382341940844817018622934\n        );\n\n        vk[44] = G1Point(\n            1665611100149892926010508881688633103296428822802069109700887727171335246092,\n            18579787392035344373237138556720281016993504135836210646427065033360300740258\n        );\n\n        vk[45] = G1Point(\n            21621139916842523940151904650736372715765507445980637564264669378213138587342,\n            10656936236721347997226972505595642672700344736491654571580898227517267642586\n        );\n\n        vk[46] = G1Point(\n            3445992935168360957003203982661175892765389403990727161650356622172301618604,\n            17096344067479737500782690015515577319540076944697298975198589510970212389805\n        );\n\n        vk[47] = G1Point(\n            8808337981493967708532504567464514716947731837557762493699692522903731420361,\n            11777725522778475464811091473323155511025217479759858596574036472535468933552\n        );\n\n        vk[48] = G1Point(\n            10820947876086700990878342770240846363511844052492888606666956824734174582218,\n            8150867701962639232510639843118886617301614731650697537642292104962218907218\n        );\n\n        vk[49] = G1Point(\n            20470215736082110876225466023279552718086261383391207857735359415463230727032,\n            2085842957061910436375271746525475684433040972939319674967459622731274166749\n        );\n\n        vk[50] = G1Point(\n            11337639513314171351013256585824613676915673825335326239260711580255879801115,\n            6256085984540539085615027987075404359248123195304523024202811604406467604564\n        );\n\n        vk[51] = G1Point(\n            21288595457655546321539521842425301747350852589772625480852585020902604902426,\n            1249843466883315098591086470818121767556973311849681925182351439164834696484\n        );\n\n        vk[52] = G1Point(\n            19899217332602315880773423298215810052418460371844166790042861464687941166547,\n            1378572146164806219595743244678836248431567305813489349742760245969238797992\n        );\n\n        vk[53] = G1Point(\n            21697354656000870693304791510097370069383968646624608868607124771843409088617,\n            11876413319300247267059440651346949825880735244477435155007039913725655766588\n        );\n\n        vk[54] = G1Point(\n            17481120850448742286325898054004677716934852008094860216743190813696103743241,\n            8201297043617640378371278524187651053623476160344124146426957226429953015199\n        );\n\n        vk[55] = G1Point(\n            3005289924198481738469386520618340385365691375464779190742383298716766106992,\n            3798750761552265556656507688179605560744908100854758185662716950349458325432\n        );\n\n        vk[56] = G1Point(\n            12080339691736120532643853171181267931152090956831962914675099644407011242413,\n            7679216576322951837469485160860080246434668790644856087664310774786340219603\n        );\n\n        vk[57] = G1Point(\n            3017707941288367829088052277266228335338233603570677991113493444241851347547,\n            3137876190344429636984844767438201549784097665589492331513832717477830949575\n        );\n\n        vk[58] = G1Point(\n            3314419641758595753659230864962853929657302210615955058347565360331432842511,\n            370657694674824888793668707329582442550590401526016252710800442854034822073\n        );\n\n        vk[59] = G1Point(\n            12531360081127348520803889885893430887143447034660271653024546125313920625041,\n            3706773617610711184566457860651115015047587714843050105191055901056951123775\n        );\n\n        vk[60] = G1Point(\n            13273282411973793607861784434723413044950529229053165751072541737431617592633,\n            2933824629529588293040887033169631059354313042236996327457876788602236178666\n        );\n\n        vk[61] = G1Point(\n            11454211545482193794268334706906672453070160000425255303478169225799785056171,\n            4701866737494737667848752430048064790393723029982177174760459025647415493343\n        );\n\n        vk[62] = G1Point(\n            3226876539587975824253734883494657032240164911972140710515864979983826807576,\n            18885227222812885519565693818826301632514351665843638955834614001238551664720\n        );\n\n        vk[63] = G1Point(\n            21256377426860772429157054343932985892905698998661980237211382204396470638714,\n            20700712575510158621998808888489798414949519986488584579416259248995522851418\n        );\n\n        vk[64] = G1Point(\n            21861786267281721340727261768960462407333067918067989326447913212770592842276,\n            591001657621564141201681807588662398350263007914462125203875613968150437657\n        );\n\n        vk[65] = G1Point(\n            13247142825778829724328102956320331554023905306148180876995955166386182533181,\n            3617736073023964052562169840230836224459626149212725300135757231277487473772\n        );\n\n        vk[66] = G1Point(\n            18571408620760464675900058729447123565097914393074749086337801426155531357818,\n            13743756586552373252834608181468885899640079575730745687516486866135863903645\n        );\n\n        vk[67] = G1Point(\n            3720980971604229890264847046378487782638291162470091687602731478085296467,\n            6084172665846193442582973123440713896205228741433466091669997885291480207028\n        );\n\n        vk[68] = G1Point(\n            18573763810245517418639262092434980232325583684581527263357319084944570213450,\n            8653273277742119666913461937453761328280502598771865810060367232987628034250\n        );\n\n        vk[69] = G1Point(\n            17771082345997588650824796512379585216955210531516942698595993660809245269232,\n            16629893348030263842237883724070855345464922671711466998275130688743450612346\n        );\n\n        vk[70] = G1Point(\n            7338691400992204970014165784957357668161159776651147037555821666761126907380,\n            3705924992700866020534892130549475719146989962914702725416258691087385371190\n        );\n\n        vk[71] = G1Point(\n            2052355044216434821564052981111343609375679060336427387512859984022224044874,\n            15268326926563766258839885139280714077759092305121832482198777135003010414903\n        );\n\n        vk[72] = G1Point(\n            18064152787981239149606586028411770599646851087777099175341453985635891048974,\n            5758261233895935495648223633806227190778857865361754803237621075864794922557\n        );\n\n        vk[73] = G1Point(\n            19111174614243915368909621978011942943947696253907134871326185228263166811463,\n            55479280864981829453785909945499596585934663637540490352091218262790817807\n        );\n\n        vk[74] = G1Point(\n            21572198467165252889522351352380841583977427216856964479483251269372946010366,\n            2345827745074569280774155697329343452443815213012561331801321306363603342898\n        );\n\n        vk[75] = G1Point(\n            15941834803493886134336711593614605107429239589267432817886895398197185549212,\n            3947709907544948327644041953329373960515540515572778616814282410080395508832\n        );\n\n        vk[76] = G1Point(\n            4633123534127190347827193753807476588202800485371180568344594379882767409472,\n            449532263245413245826291253249966920449070741031176517806362079985429699204\n        );\n\n        vk[77] = G1Point(\n            10268447195073622715137083952769200116950216441153401816017144348827097981644,\n            11014519154992952585639434973281546235674068382469609940982060669012254625049\n        );\n\n        vk[78] = G1Point(\n            10929521602517897709850629137285162565906147508132403521696170594109080701944,\n            21509909425895040573950674106120782000241158919930204131530559382950838998391\n        );\n\n        vk[79] = G1Point(\n            15100619628435171593543850901640490209866254607928075153538760713990045850303,\n            10442892609047996498519806259742624382008709260868724454066808175184715514873\n        );\n\n        vk[80] = G1Point(\n            21843959294108881062590024710421326129806024810700259156439039031593999701643,\n            3172495648177936540367468274822347136571308354704236044741558883273231646525\n        );\n\n        vk[81] = G1Point(\n            1159965505725043849921965815010783448947155232300987681835997103232694347481,\n            17895771558635391086993801372767923731437665193374586297480961769145647137160\n        );\n\n        vk[82] = G1Point(\n            6507616620793362158142805457368779151039507583917257718825202495364366512771,\n            15681488580781287762163534693440431743803367357345151854182776562998569208980\n        );\n\n        vk[83] = G1Point(\n            12814039407411091293859374060045673589466191829420083574399940707751465761225,\n            9921363265528964171864400023090100733610301136126390954832628789086307360330\n        );\n\n        vk[84] = G1Point(\n            15006028241180564287322274819018849976566235200309642600445049768087552688588,\n            14361253381523713031854227412596864494866188906783060963450351948055547793422\n        );\n\n        vk[85] = G1Point(\n            8756721339492266735713698899407035226934130919921494557180936772641389932137,\n            3548415476667864206509977837524249204352483242015728861933739872119268812336\n        );\n\n        vk[86] = G1Point(\n            6230313188217542780422481357959556867195597265162307208386521999420475922554,\n            12851754457568807033120245152349042004417001439091683959351522506453268129018\n        );\n\n        vk[87] = G1Point(\n            21771047292298211615870361795649989045841286446573616035285681334849994642792,\n            14661525648026380124158975239185394052839523320557698240566443363101483984706\n        );\n\n        vk[88] = G1Point(\n            5452997622770127402704007841410646483824633269304350008222506428808016149352,\n            15964772002156686217844177582357873408670879571833339501331743013322376177413\n        );\n\n        vk[89] = G1Point(\n            19418627841332101860244780132548095221604204548711828994979491672674661101186,\n            18641817276522447942931176882796528922352915530694097337534100417837378090505\n        );\n\n        vk[90] = G1Point(\n            5170178768764059003465306465862923505721180092357892642067482111376422462560,\n            16292075720542416258281919877302226890334681177149723464984043692849198938515\n        );\n\n        vk[91] = G1Point(\n            21428458772825703056643431938043979656975497408178147162702507818606254637112,\n            12669252472492383503929166513607086634606571727926148034366726753377604132130\n        );\n\n        vk[92] = G1Point(\n            11511741412661577053334100231545519781542601225911626010001773570941781521973,\n            1922508687221278919615308146316092898338385014957534362889216743475722386874\n        );\n\n        vk[93] = G1Point(\n            14619278216684346430481470847265257256536064659065561539422115183392054064375,\n            4923864138475225113538825583664123279747028999618317879907718283379102732160\n        );\n\n        vk[94] = G1Point(\n            8189555561052452582428870381320959534677546020283223689489980283591445785575,\n            5683666798184731981996415590358687978684473547462253523588605793555562472541\n        );\n\n        vk[95] = G1Point(\n            8897957337103869663087162380105747076714883391199581662621194554976044780584,\n            6927678115923034019960143700173902535965892695901056423853498118708237353848\n        );\n\n        vk[96] = G1Point(\n            4118147152554157650952803163670081114994515119149218879659651529875426582434,\n            19521776423474340073081384962305127452679641989910491209025946663191129399856\n        );\n\n        vk[97] = G1Point(\n            8199369164715592391163039840824830201238287690146271134520067390345622199716,\n            19049749255599225169445818183746192203784970578733702608166333799300917468408\n        );\n\n        vk[98] = G1Point(\n            2621331616746047342119107296268526819659807420993801509193016057772588459587,\n            3714747974293459317220483876903845314809250288107020652709574106317772888105\n        );\n\n        vk[99] = G1Point(\n            1708215042304182557442018546363952961772236357429287076004515766114579471031,\n            2425075910704693171603894505443381911930289510088402398879713274371959189682\n        );\n\n        vk[100] = G1Point( \n            559294184750664917430341870656604694071008897392190220192116267892035169297,\n            14243148295708619851230110866382409248552700930031870832819191159537034402444\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing800.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing800 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            559294184750664917430341870656604694071008897392190220192116267892035169297,\n            14243148295708619851230110866382409248552700930031870832819191159537034402444\n        );\n\n        vk[1] = G1Point(\n            4641363513109937726320639129538123435956871701621121784383882099053889085064,\n            20015785064628801009980544726216690068400827250235677109113321502136446155777\n        );\n\n        vk[2] = G1Point(\n            16761303904856298299723450063499263261483454775470104686716380205610936215117,\n            13937501019878575606690787479765559875950982439900898526707819920574210396914\n        );\n\n        vk[3] = G1Point(\n            4125021621530671520299368135350154138496853482199634065524307735783221506172,\n            16190459597315725346983317532130332429646848590679639631247767437744875471313\n        );\n\n        vk[4] = G1Point(\n            19849240995130280756599784958846981127053605278814133448560169288281337309250,\n            11675912751007343793104404365503374415961442385969482964253099999374794062521\n        );\n\n        vk[5] = G1Point(\n            9320713791229663102095773152315323259617878871788417932186351427686255118215,\n            5031819995598549568272731745469059436781312050331635201450144235923913819165\n        );\n\n        vk[6] = G1Point(\n            13435400523688401353033714173705698526346444283986384351204468887236374243491,\n            16366291887622641881341748933283220710973724541093918051192758943031982016569\n        );\n\n        vk[7] = G1Point(\n            6394497756473108680268412783622560947673573875638773476223377474748359340482,\n            16847378050049511773766978935578345782128941539265621623649163971493855796381\n        );\n\n        vk[8] = G1Point(\n            20572347536123228112123222354601623030650448134336711995034494364795021967029,\n            2935563205635769425595140333141174534691698868963874628523314077352096362604\n        );\n\n        vk[9] = G1Point(\n            8567295467469849108524564940259882891955372381347517958712448925853589665433,\n            17126506123625180127332158056979074978461293945877981144093438061603200266523\n        );\n\n        vk[10] = G1Point(\n            8385757135462166537324267186029549888285610930656993261385036491140747602783,\n            11755922478946920908937886748961603502459105346299168752518518469779230835019\n        );\n\n        vk[11] = G1Point(\n            11580532764627946652657666049062989910060745795643217021469313338866339876586,\n            18631367422511443614204583369307231334442077623145794064741115894921611169838\n        );\n\n        vk[12] = G1Point(\n            14041857815642320602115178041614139704000973370587887995705039985955763424431,\n            5864590125302963475551411622473450335621230404557783931673319724478240755591\n        );\n\n        vk[13] = G1Point(\n            13003078901866419565251336650095929315677623453524699304544704118146032693899,\n            7434577392922660618913874742370426348845330053880326049141102509615656510130\n        );\n\n        vk[14] = G1Point(\n            8523168013225288039668369351202506283884748730101503095849677161696861727061,\n            17296927326456089985786458745213007430778604788585175602980164813117398171445\n        );\n\n        vk[15] = G1Point(\n            9660850928841930392943855243257513271614052667226722573101334729223191871508,\n            18459663369741235469869910647511028564490332634725235477357676802479305538572\n        );\n\n        vk[16] = G1Point(\n            16615855050907391851217631456166011888450049810710832615364270265670650659733,\n            10457433051932657549358211606983093776526347686143076624149865303715361727213\n        );\n\n        vk[17] = G1Point(\n            17240450537953206327013842785080512909236045058183966403673631770301676553751,\n            5053117934145447407837524379435256152358093853705164607685296653679303508184\n        );\n\n        vk[18] = G1Point(\n            15159147874382495636095537308753383252505234063484926711720521810564064894868,\n            2730602936727665764041791998668828945466088714809904804925269747736936895637\n        );\n\n        vk[19] = G1Point(\n            11971237997442160578398107588396043422709167969653731697964024015671062484127,\n            18624368115293893912794901974305653099199554892112368530201890203151889033029\n        );\n\n        vk[20] = G1Point(\n            14148171926714710541421151615058634067868424745873533826286459021369774822941,\n            1217293042425251216903486900481475344968197904075908396477749058366360904927\n        );\n\n        vk[21] = G1Point(\n            3648756337515485492319000929910620903716386323701507924771679882925736405459,\n            5752358590308137856835442824755986983599641197902351138051053971602974431317\n        );\n\n        vk[22] = G1Point(\n            209381891984727257109125768588386411146419455690232216153158232964413132704,\n            7089417592738436341300719490729326354690820629043685201220453351997684142737\n        );\n\n        vk[23] = G1Point(\n            1764994832824116059592766737448710839428842779486436562970822565609476627624,\n            10977618615351529441603716772834209463266792823084661596055923061356525574307\n        );\n\n        vk[24] = G1Point(\n            19369648758696782516645573375916583073152491921276410048538210813076080246665,\n            11175317312200664742329805582772532883722779774480052491328184169495063673169\n        );\n\n        vk[25] = G1Point(\n            8984208076995628696275920884394615848732859203175750037018539325125893905015,\n            18213554000898869653960568096579370168313137924243505286749801854857943405320\n        );\n\n        vk[26] = G1Point(\n            3064852110349989722997878092689993597406379162130146067448574736107935975509,\n            10137622525579865627368848743060347355377869324168749065310183578344158294521\n        );\n\n        vk[27] = G1Point(\n            19889968145673137197340044172321694214792967568470672362854336017322946357118,\n            16570474991766989094289705454015227878425908060295684975204210736405191583930\n        );\n\n        vk[28] = G1Point(\n            11130463074147383690697360174461268228037898050713131099737593897262701893800,\n            1991726988028369955660605485821152006597430781905214903499537837199235078781\n        );\n\n        vk[29] = G1Point(\n            8557290206677740692987545995107170043268650781450157988800207193128419550641,\n            19399364359027378002105314683426149972036136696799210863065824006912471534463\n        );\n\n        vk[30] = G1Point(\n            14813845139854454170967063491974548636206374766806645984427229914816971890269,\n            8469630046298368462578736674514224373144384794555108842480672376772618857780\n        );\n\n        vk[31] = G1Point(\n            19696272297318277446148974219367795785176160925123080658796096682846947839099,\n            15601963952865177248796595795980656131768830043411373657795642680197644125633\n        );\n\n        vk[32] = G1Point(\n            19321325379329825681586926473146524150458336855530772882422144951457158646184,\n            17714280203077819102671830011373187991072073433404289632305952140567085223439\n        );\n\n        vk[33] = G1Point(\n            18229404129763550527789836682419669078651778151302870909023013484829101923277,\n            8316675992106316482631479790103021816365102565331244485521069234240710542227\n        );\n\n        vk[34] = G1Point(\n            16983462463988543679912134597738024367927321056405749672110279517034684120756,\n            3469059523319362523686907070815620464956956429746076771987477696878455818075\n        );\n\n        vk[35] = G1Point(\n            19463552252930414441780190749485646212691510632079363337460642878403342603781,\n            10209355483663589165733776069811081154722152222970718843912999345077275964987\n        );\n\n        vk[36] = G1Point(\n            17486291268496844685353759747743132018398829324074988098634886021666829526120,\n            7847921824687487315247853200034459813397001655237720587439395103825842477633\n        );\n\n        vk[37] = G1Point(\n            17722651172175517076018389341863710965250262813407492884009326305220829065046,\n            10487691456526659835471612235752560625692013273489396243202859376295776923558\n        );\n\n        vk[38] = G1Point(\n            12744820202486174413654630704075648277206967652161891634716443809645980148619,\n            9716994079134748793498039006424003304274943924035623988851638295300650726442\n        );\n\n        vk[39] = G1Point(\n            4261706872562368220521815494673429540987867440678498451594051054386399994855,\n            20186486428381910208029689089989935515564108102146971834924129763478010008589\n        );\n\n        vk[40] = G1Point(\n            15454549474124431277518191134193380988246851564390984114008701287659103488738,\n            5874701094313451297086254207832084969795768666547183008624506347933551613982\n        );\n\n        vk[41] = G1Point(\n            1676058046629490551051162125725983133518221611201713246164689759687811777230,\n            17565379092534989417079550071289175809180626496723020798655229615017755897783\n        );\n\n        vk[42] = G1Point(\n            5746917482619697189210947156745304514304784446541318475379352595515120538103,\n            20817733075396732890981148463534404853694746012881282255940208250049223546349\n        );\n\n        vk[43] = G1Point(\n            18793517338798557027747585024866085274494902660297229291689721509348767740905,\n            21544111236563968882169095579878601719958652484044645551232479643013159573704\n        );\n\n        vk[44] = G1Point(\n            2050459469015547658107090915715746131330177395869605527888554280113497217464,\n            13619288754540054083009299344410666963144385746438742435132541338142087254705\n        );\n\n        vk[45] = G1Point(\n            3649972772852790099909430799691395764313064728266332656591035905877494470290,\n            13880535846267644520244990301361207558045362873058999463704228357037261536384\n        );\n\n        vk[46] = G1Point(\n            8709530849166942343432753194071887233880928487708567842014440249006022409104,\n            5284828882766470867313223435942045546259032415963895813171706958667394056063\n        );\n\n        vk[47] = G1Point(\n            2135424078714565208896467689927136192173996886982424807286133483392901352846,\n            14130115279577774334133855529552836877996808719240021869901068967804325838910\n        );\n\n        vk[48] = G1Point(\n            6022520093976878629503498248026375976407894828309455065335894190022147190220,\n            11403104453086832749695950325884963130345687536029692444804018665944668604279\n        );\n\n        vk[49] = G1Point(\n            6949610571741072245423378777184041385742746581345060770731129218528069168691,\n            2481754069589639819477314027612972874952154233746246533449159092761521799354\n        );\n\n        vk[50] = G1Point(\n            11262554196517517734273152603768911534102980853976228956329832125031878464588,\n            11450115278732766246844196258072595414789004372699549092481177190180936235753\n        );\n\n        vk[51] = G1Point(\n            10655401840334114227397353696707877117940436643479939754864658902040786398751,\n            12645898306281364802807566563450978718582354145577554431572920212633275587645\n        );\n\n        vk[52] = G1Point(\n            1451637035525156346691694147408873582423855961904315712768968671379206354579,\n            21481920505757867684258998732762528712052137268344163677762414259360195551645\n        );\n\n        vk[53] = G1Point(\n            10729013981785314184824036054045624524903840797211684434083483677275979346326,\n            18325540548040172388617780552337336329335075502659868916464299784397352071744\n        );\n\n        vk[54] = G1Point(\n            11786217925076316095415633210734166731161609633336590843883624367476419154373,\n            17211338965652619543010123190127646262981485090623247613241044905333218441058\n        );\n\n        vk[55] = G1Point(\n            15340468123188282974305874781885789172768416613401328588469042343942414848136,\n            13007501387512083390255667518665849815976255590034759546444519357038091395702\n        );\n\n        vk[56] = G1Point(\n            8927307275862985057176968900862057966277124769034733067746526923706021016947,\n            1081518948268686012535894079888410190507916582839951366832611407877289978690\n        );\n\n        vk[57] = G1Point(\n            7293043962612016174753419145270515422879993844018007730285031245876245473202,\n            4191796304669615611124052242140262221049847889202390246191590368840320602370\n        );\n\n        vk[58] = G1Point(\n            13968064702532109429288299716872067513610938231338108945584393326307786414315,\n            5373582137274400082389095358511060894456212114692218467991237813007975689694\n        );\n\n        vk[59] = G1Point(\n            3758596226285051408983226491469599292571492379629611804571761178033520453320,\n            2454883224459892089575304907655611952745787207648145654621470832587360531703\n        );\n\n        vk[60] = G1Point(\n            21555824398889026700599110374151173645106507912479669718559466232214642175824,\n            12352685420281837674248286258618309863574119337875382535028388183453411756107\n        );\n\n        vk[61] = G1Point(\n            18049730062183079846403584949671353912918246408147951579960074499070416762114,\n            17536696467554203271932033732303984353450059074571099901758028703199867702447\n        );\n\n        vk[62] = G1Point(\n            3630933607012987235630819891456307466800940035904035975747221111257046368475,\n            13051596363701423220490238974162290343812415144186756556299878322198334040607\n        );\n\n        vk[63] = G1Point(\n            1839454200491531954187260396212125337005712457038159453201056093307925615085,\n            19016655735355712552866432640664697526672311891779991552019770538297116297078\n        );\n\n        vk[64] = G1Point(\n            8211064545860586641177910635560247297250779479724407132339977574519271723024,\n            1739669868104933659011243756220419911357136446325311819646929275406373361150\n        );\n\n        vk[65] = G1Point(\n            16724148941054764472568062824771629523364628514117508074493692512209331954096,\n            10711331414381032858699792577024498842588505914841228834618117127702045196990\n        );\n\n        vk[66] = G1Point(\n            2194570388763316179703402657245159003043315677123788315625713243440893688296,\n            671995470696736912416128688819430220033820747604662863380695834045477855300\n        );\n\n        vk[67] = G1Point(\n            18135805027299617087626828261590661783855335318757338646066300829214463553137,\n            19269082181857927423577474838734260863386955067923590440578662513729477546006\n        );\n\n        vk[68] = G1Point(\n            268116089608704424478479959989990433050410604994258150035332274187094677620,\n            14388240870199792936320046199970508821482397995221901305955222626961729873052\n        );\n\n        vk[69] = G1Point(\n            9334449454521630198822434918214680333551400653280065117677887979118231345187,\n            7439337143774043976403427326032167679094189499196247106663000510387774376830\n        );\n\n        vk[70] = G1Point(\n            17768550841203576351356232018850993428168649072771599775813701984974217201111,\n            7556553618419178560762378484819183949938378097461705888703375887447514648134\n        );\n\n        vk[71] = G1Point(\n            8441869719841147118575505423141017970813522129056651387343929851596443769431,\n            14879817316364942991964690079688034113057179186163077128615378086809422064409\n        );\n\n        vk[72] = G1Point(\n            9579443613395526712253172774200189648220870485724921908657265599500527230702,\n            17459261788873286383523148509354868615393377986954158440628411246737714705866\n        );\n\n        vk[73] = G1Point(\n            3390608244460855862258301402695038218510879083584641774443989208329720854259,\n            15834689492458317163430784079175232292921792345153915531655165792654771449279\n        );\n\n        vk[74] = G1Point(\n            6849679790997705865253692203555364267187495003347506687946124126477919577999,\n            17723145278192624788286311121498707441093870502530696174835981364501571342802\n        );\n\n        vk[75] = G1Point(\n            6503937712237310286881191786078185358704601190277978724791091353124759909432,\n            3800106775896939434292500137825778490395899251340705032969163231893271649340\n        );\n\n        vk[76] = G1Point(\n            7668989545382110621659412264165965219146559678740588857155577104808202010420,\n            7851305784133474266336683776279120533590472641003892804965525502340233394532\n        );\n\n        vk[77] = G1Point(\n            13291830509644203463733678098410480652709477228950512322251300735490471954650,\n            15020179339114286405114478208879350729983076254079657989313891689671534538913\n        );\n\n        vk[78] = G1Point(\n            5685272599604926199513123830849826918087592171335590110941948947213830053144,\n            17615123813299894952272327324757312899166667209507365170871678818715172985174\n        );\n\n        vk[79] = G1Point(\n            18099379234782311553131736224577569089877940478140780901969663647196580452384,\n            11956537138834467747733645605582822324942100218357110410909453608102744630521\n        );\n\n        vk[80] = G1Point(\n            21472994645061004459217960142508521848798168027792849518928084754756911165234,\n            13833779338438939727410219270850047667099739611285602255489077320814672408187\n        );\n\n        vk[81] = G1Point(\n            18277752520724119196344224874834407736802701621981138444003817990899568097759,\n            17135166935029497016961989546843127186562328356176611056299322156144253716701\n        );\n\n        vk[82] = G1Point(\n            18452824877373808637009422245788749152632901131218946908057548736994122850921,\n            8887308176495410852946052122465737385408206700328538021316204271045231675672\n        );\n\n        vk[83] = G1Point(\n            17153142649650814620553905208982188194307219068658132877963137610185955164372,\n            5144376829226231038740423705829695865217266800074682814359546508134586040839\n        );\n\n        vk[84] = G1Point(\n            6811676667384533421124200000525337648506560026302498757961443070626296021797,\n            12043662332794120237007270233943229217944539492634173472358516349504738514206\n        );\n\n        vk[85] = G1Point(\n            4590024033678062432942300426566452319360585320139898170588841545004845486797,\n            7915368968859514901989049052281653979872587436352607310214929948368777612273\n        );\n\n        vk[86] = G1Point(\n            13889102698962298748579764030115401457198260073830896894848730619766719570027,\n            19972577516618214248068764159630002660227918567337219464894216520898915185828\n        );\n\n        vk[87] = G1Point(\n            8535846098238172710889398519351743014181040376590643741479576724836291257416,\n            13792938032259236288532655790424501005467444692312851880982730549545400793926\n        );\n\n        vk[88] = G1Point(\n            13884200005489381505949292637923382303278728967183693544807323421986072573998,\n            20633312090376438491418509172364924582961994703988641825016545586980028465499\n        );\n\n        vk[89] = G1Point(\n            9216497959991890827793204543148936197274865975784801593823649820012858451325,\n            10988946369884624320650856755368018419213866654737020241093840956651324758155\n        );\n\n        vk[90] = G1Point(\n            14526742690456549362825528413182630955767323179314960371140352305995115852982,\n            17392982062902854369742163833771298777324128247472361534614968867970755644238\n        );\n\n        vk[91] = G1Point(\n            3756320054919982438216137458737529701833032294584811638907769165142106244018,\n            2026317655790277032971780133109928039873859104788708251331308966220057525006\n        );\n\n        vk[92] = G1Point(\n            18168746196925277957122530070640119923133368120665608227468033990319250683064,\n            15928004968287655034554779403187356702388373717859559208859559211198530489722\n        );\n\n        vk[93] = G1Point(\n            2350321360596025017311272098274681869364130774559357167455020174355078296922,\n            20821466240739658313846666434562490119890440414170796738934298410307994029923\n        );\n\n        vk[94] = G1Point(\n            7576016952097329337545599688696447948485267660955972370906978561349485435624,\n            14878628859755697611190819836957201473919004645611944282806804220809238724014\n        );\n\n        vk[95] = G1Point(\n            11597217674039119094596835611344844946425996403240066224460426561457802713862,\n            8007511838822340285474996205910408034891631673920084208199667457768934693878\n        );\n\n        vk[96] = G1Point(\n            13458131216735552749252745527447893400632285346761162408552123571290380935022,\n            18569250196249321686100757901020499704270976462291506106734664138328832308000\n        );\n\n        vk[97] = G1Point(\n            19880546657682223881549963383452654370983331362963681408248722144655667884976,\n            1222970444335859511430541942120238521707626872145745468699182644946185157079\n        );\n\n        vk[98] = G1Point(\n            15118012150205245414285454420783423739054649341973803838107194785809110289124,\n            17047026265044764935090336242521610457394983294856036893253394185761254316130\n        );\n\n        vk[99] = G1Point(\n            8223451871709830052117882645338758668088262575931923010898854132730047969200,\n            6042153099574221150323639542394054393208297275054855891452516636729575050382\n        );\n\n        vk[100] = G1Point( \n            18307463072870674736741132489299673350923024551765424057435422228540653970783,\n            16792651768640733615873201158696903896357564953934877895980220834108412218261\n        );\n\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/Pairing900.sol",
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.17;\n\ncontract Pairing900 {\n\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n\n    G1Point[101] public vk;\n\n    constructor() {\n\n        vk[0] = G1Point(\n            18307463072870674736741132489299673350923024551765424057435422228540653970783,\n            16792651768640733615873201158696903896357564953934877895980220834108412218261\n        );\n\n        vk[1] = G1Point(\n            4789000056073433326156153267653182197217802322824905811327056766712647642695,\n            14338620651847854558910662138949844057308591460208480064151185711964689436764\n        );\n\n        vk[2] = G1Point(\n            6578255280609706555177082788663940665339411973700750212075972380156339755679,\n            3228433145782450591319507897804150771347753627571273489631777898164366613828\n        );\n\n        vk[3] = G1Point(\n            16574758236366827634585777329773423293106114653923548049318719013559242870759,\n            19252886055231017922404681227981950440625207824828387687697067340297655941000\n        );\n\n        vk[4] = G1Point(\n            16555574432268249297072225173376580829558643100562043994673519690907023706670,\n            11620593188774162183301925169968005830479913657062396204565732720039590002171\n        );\n\n        vk[5] = G1Point(\n            16764727018082953742300073572884323444567504913343988076904979389682093093412,\n            16008183983701872668470252826323709319273386261752919872762484660725950394195\n        );\n\n        vk[6] = G1Point(\n            5829440659715387228077080706469101044615777998393525030381841227827471157950,\n            1367426294365201074200856383125954244404307990038206824279208969635811867380\n        );\n\n        vk[7] = G1Point(\n            10695369958073696359464925785121093422900833909569756953880374725937593010335,\n            12194125366218696157176225816036508850316861213011691830569742976115711054191\n        );\n\n        vk[8] = G1Point(\n            10809435843739366421210343030371796222421462273177875570148654509477502723134,\n            16204473949102958684617595152565392925725892190721955438532533184706485673957\n        );\n\n        vk[9] = G1Point(\n            11149001652463019404634197181059667092708275322411960247876227974825361909533,\n            19870085536849253778425365050845411527056646581744594552136174435626261992873\n        );\n\n        vk[10] = G1Point(\n            21633495322331699108936102943984938289871967694225787699478955567855577076277,\n            8841675697657058186837199897272199281241125039540749760749866366853345250117\n        );\n\n        vk[11] = G1Point(\n            19458527598824582144696509161993158481600392423740684090731972416543620378918,\n            5098098442650960828566152174489938600015509615678418748929319316696520456089\n        );\n\n        vk[12] = G1Point(\n            18163051065276756604410981379630170745584099868080700795597207422977310031694,\n            12891925540785917799829995466575120813509928365034086816025226811708475680771\n        );\n\n        vk[13] = G1Point(\n            18148915448457607307771805309124949164252733216024480445767547616596773695423,\n            15024451534977886278031386395541612474752413190466983004653113166385208262867\n        );\n\n        vk[14] = G1Point(\n            13567542556403632068871157024019274875365845880663215895985301267051220449915,\n            21147351992392629598077997073140386368208187323806250865054727635615189480341\n        );\n\n        vk[15] = G1Point(\n            3709429933279009443013299688619554554278934214896761775054082931305509883920,\n            2922475459789324154701677654774350903673561145307732452781748450024692439758\n        );\n\n        vk[16] = G1Point(\n            6207459015420283879112268812206460637912243134090208488981683983479929219501,\n            19464341533921121379177980354234107647138267823174115114993718278700616243646\n        );\n\n        vk[17] = G1Point(\n            12573137276608811604660919456417437099900707375770181038105448039923040372508,\n            4785339390439933486900025669326782829059719078601883112714925799020869250529\n        );\n\n        vk[18] = G1Point(\n            14495687129759553815385878441596882565883140518530797787341292110068724755317,\n            9908837939579790533939906238849352722553567333775647475719066660646812631898\n        );\n\n        vk[19] = G1Point(\n            14624553409362174155284506115343329475954034470871981231712041948820897505806,\n            4055566348780842984111507965436956949863329573748796703898964573434150896399\n        );\n\n        vk[20] = G1Point(\n            6336358054678702430512128514698663338467145073234753741670943409016988611841,\n            21081078821483650976369657459489737716748751238003798448442854876556764583522\n        );\n\n        vk[21] = G1Point(\n            21778077693541311800764526912528062763820059986333103084626823048120825681154,\n            178498528808053513655731208200912794633728479503731840846443012602506264472\n        );\n\n        vk[22] = G1Point(\n            20092784212323459111197432710178189818364277499363354820976672666571117766206,\n            14039021393890444890907150965357887601333454050225753134347061410201835959266\n        );\n\n        vk[23] = G1Point(\n            9678747076652075890061941140866585027854061921320841107956049148587077873135,\n            2405418275493353548325615341270358381792281291370535642128255313696482905433\n        );\n\n        vk[24] = G1Point(\n            10914160332386626846208296155883803838354007531580988096649426593027349429229,\n            19513308958140914107981840749041884510898897036102081855133159065505135942235\n        );\n\n        vk[25] = G1Point(\n            17013325442123840982265270425988582276060365493502071138812002548136449285581,\n            1528380922305877276691998106216016470833147721725826901333846614237555013029\n        );\n\n        vk[26] = G1Point(\n            8634434257131053802002335855918396412553878060677568439612339441966650140494,\n            9500478088969708576493467850662801175479925729547585947874419667731523903091\n        );\n\n        vk[27] = G1Point(\n            15874050365719980884900984059383308130277935906735474135906824024543309805590,\n            20311355082892144868040731557861367194417539765824516344987436596022294566783\n        );\n\n        vk[28] = G1Point(\n            11478929466911074817172552699536282906669073535366530139560666323127010399333,\n            6187455832101099195081186717967290103059680388511864648852686571948653409720\n        );\n\n        vk[29] = G1Point(\n            18658619504087916022952320913628967164216879673289502801175356389245791265554,\n            19249597434406947187138753077277100946837797326096977775126772518933394896670\n        );\n\n        vk[30] = G1Point(\n            5740756148239604917163046043012671325129790556077681062372536905708358133086,\n            21028690370455549304306083807333498793551725365830845930784580120332405576477\n        );\n\n        vk[31] = G1Point(\n            4556922182497280298677997968846941727072154818139992180400736761367731801989,\n            12033144730059861061132643937799827866054364406801503559178480496934921889439\n        );\n\n        vk[32] = G1Point(\n            14055239035142027464855790090606515663950909158034746078251721932545422080777,\n            5816418890251425996741426379519127484058094882188692730692009994088752123536\n        );\n\n        vk[33] = G1Point(\n            8440252168545611898385538536782138915182984781092035856645867408799623219945,\n            20215684322588953445964435803266534090301879489606942443191234122940297295959\n        );\n\n        vk[34] = G1Point(\n            8004299504263995281044671228404062964772071092198761056902501295382499264949,\n            8917524383385219833361205068674587307943386640835650529127394723762498700226\n        );\n\n        vk[35] = G1Point(\n            1266405593449423959342654272499280830160858534000134805902964572882344176221,\n            14730592399119971599629413081858596242827050785353383949532548065719090424424\n        );\n\n        vk[36] = G1Point(\n            6460184856566866496717666629334954003238728679896696393431936681715938557215,\n            9385837251352049607599726479064380714009328250815226579236639044132003833296\n        );\n\n        vk[37] = G1Point(\n            20038397597280131387130908291235300525757777116207925500763680256362215974747,\n            15789596710921114511299708815137972347824423103633995892189007477008098682432\n        );\n\n        vk[38] = G1Point(\n            14977179620342361639560323155039295964094393575784932521067001547403571821207,\n            5084005921095794070371447644223490185437079433157259001224747718163583496249\n        );\n\n        vk[39] = G1Point(\n            2603608960494030254533242254550209204811718913459550203153417054211926196085,\n            20119491317779083596649069648139084330079659707307191837443353139378496632282\n        );\n\n        vk[40] = G1Point(\n            13352417765385861239236882043377637081462713751488001524039994647924371861376,\n            10015867720858427500714887833930578841810954157407438967793778359200481367291\n        );\n\n        vk[41] = G1Point(\n            6824208548856181471475405533428069959877933928322938168866360738005352043359,\n            1275625707509651085224214735614595576100112913199144201028659347523921702370\n        );\n\n        vk[42] = G1Point(\n            11783915381165086342800153453189512171843728741798456469061325661227546377683,\n            17643698391422121657405091664637900437348679627693357153186100886852580927218\n        );\n\n        vk[43] = G1Point(\n            15498853058593810390094130334176163433565242197455892921729693543144628995999,\n            7060915310104824129452602167671744856523661600092559992144747898417292665502\n        );\n\n        vk[44] = G1Point(\n            3578042896557087484763665838416273537654955839278877802149275463634617135451,\n            15952757771847059361682987493826508725813536465705463434405274726476414853004\n        );\n\n        vk[45] = G1Point(\n            19791464989780891502197175931771002698056138679399576148709306135281737634890,\n            15038584235951650586061390113144838928579407621791780231316260808529893403257\n        );\n\n        vk[46] = G1Point(\n            10504829652002152043411151075198760792757001391754005595721909036516222701986,\n            7314612109070465487349496145479494813591752194581192585198492401872670355966\n        );\n\n        vk[47] = G1Point(\n            2263316314388115275462133346878405653703830076122312027240177769924172615403,\n            7490505571851696457669172475943134833535988792530797024799787749858114767755\n        );\n\n        vk[48] = G1Point(\n            10824830403977863762868621470892898296459194613964026019303248114011021606931,\n            6777560176089231246097636040358537422207547690759158064840513258627985056199\n        );\n\n        vk[49] = G1Point(\n            1395192242344963362944606483746632116836878423702653273368795762257222879845,\n            11627352300493465821659955604463687363663152813305154916480067138740798978572\n        );\n\n        vk[50] = G1Point(\n            20410354526728405099922418044096022279822051030184592082263557341145140341675,\n            16916755959160798742301876648201040933226101487533205008998132931358182938726\n        );\n\n        vk[51] = G1Point(\n            16510714617781504242550648994585448849646561015009575604004828856610715483912,\n            1341388561114315792903281737313302108483662874950358892151607710070453464146\n        );\n\n        vk[52] = G1Point(\n            3792245266609657761019054922431751667764747002986596796683598374795088228579,\n            6775015157835179633382495509949523442589741513527726694611078016648860920225\n        );\n\n        vk[53] = G1Point(\n            4295977217411094712258561527694095952819350227393933691896387148232696054234,\n            14315355631172786687124343322135945430381374913409927454788876962534807510067\n        );\n\n        vk[54] = G1Point(\n            5672678382423505287391236760904297810818696587596372367831733912405629636076,\n            11750138886868058438573361005095594512750409074576018601290870001421090732139\n        );\n\n        vk[55] = G1Point(\n            673987209207186917951408319988539910634528601243533215726279312983075853718,\n            3127460697691845217206582481603431538500064200369814611470300550024183147628\n        );\n\n        vk[56] = G1Point(\n            9090845515311106600436846379065946318058952289413948072431786810720329894277,\n            1722460393286107233579238876508677840936009861747420874009138738174760258850\n        );\n\n        vk[57] = G1Point(\n            2213889945202636137630217627265100992986775825571420924028508761827862915086,\n            1141968364604334451889887522589191128529733915583920463787937023339932630842\n        );\n\n        vk[58] = G1Point(\n            20456251219609929297591094856316762598797449654417795771607076592173119770834,\n            8505554830751982244469586969491963764193166354899055209208744116625949769223\n        );\n\n        vk[59] = G1Point(\n            20764552363708182108437044609302144079216651782533258856357771881993888180849,\n            5921191061717335495895332279770326686451945894157952000771270982128757623433\n        );\n\n        vk[60] = G1Point(\n            15200491309187033689701632744609921588687822717049972773860607965049839358498,\n            963174101797405264376426772342024356994744317274258835260867706713519099190\n        );\n\n        vk[61] = G1Point(\n            16907409359263295645490014611417427808286586585673567545549370374423687270932,\n            19965738920935732212165618198627456481706426962709668717428158398175019622633\n        );\n\n        vk[62] = G1Point(\n            8525733762824884009931940933269975990468556742128693668478069420206268288958,\n            17680957562382256477839242533381992422893557640970411982748854729672918653339\n        );\n\n        vk[63] = G1Point(\n            11543924252775971085638087262239886261896444790986575032898538165024986094767,\n            18295533857221598255085058623508918462384641096084692938748885507727999045589\n        );\n\n        vk[64] = G1Point(\n            7650073211562746195287504984432880599500134080888190390185023908018545159212,\n            8926007449865916826503243560207850774231542132502497737708140518754674515195\n        );\n\n        vk[65] = G1Point(\n            10910030114197534600661564768248291622559208820070544459540583031788280438050,\n            2161200733196553722076963828666276486998396660698119820390811182345471844390\n        );\n\n        vk[66] = G1Point(\n            5619991943329231023586342563071292156848936940252243397784818979776452294394,\n            17086471386430636827044781369055262728948850562979233008000676670453119931905\n        );\n\n        vk[67] = G1Point(\n            20029721922638353437616765565750954147967465635811408466336662374931690558864,\n            12157045576250721417202657406507371059403669196756053696479579894919277155409\n        );\n\n        vk[68] = G1Point(\n            21135518903999037687700383159674705128503559373593305877591081795645434677800,\n            14826149418250868867665516729312927912183357232820965249219250101690877051719\n        );\n\n        vk[69] = G1Point(\n            12716235266612547965522432659702796588728652520165953576885109254764760946605,\n            1502656029161667595612192784104946048748456206287753606896784110697937038273\n        );\n\n        vk[70] = G1Point(\n            1049220917141553398666899775374455498324054642642897994229873531044866400312,\n            20769086632475471411761783937841264352491499614880433868847982280973141672413\n        );\n\n        vk[71] = G1Point(\n            3614350552551352780806550106639402451345056206997206243944277215031513049373,\n            5206057445524765927002106886059500476391837098700968541446631114025985784910\n        );\n\n        vk[72] = G1Point(\n            8055783365824181166702825600356820312061099690523284725576656663176679044116,\n            1638222926585075350767574412771496589388909043259378375319066944648316994837\n        );\n\n        vk[73] = G1Point(\n            4057792612019156099527886469601168926861003507392647059213084047169560834646,\n            6594931307015609958146395288390214967001676005571978717602974701376929545008\n        );\n\n        vk[74] = G1Point(\n            9950382393274396072720404713158345851200057195628611055661986956843175756293,\n            7282922667960477094585696814153673802022441822983967842678841595733604007174\n        );\n\n        vk[75] = G1Point(\n            4586216621225205252031099476870849094841015192052367266638267710491870499101,\n            4604017147526254722438115051976438786550914352568100746360878795783694704167\n        );\n\n        vk[76] = G1Point(\n            16799214131908640765084658268392840479345866505817700863114604240164943164257,\n            15354212741684672046178028260202360583039504621090458373615159126939692802706\n        );\n\n        vk[77] = G1Point(\n            13138609772016813027991609032179065209970990415242714114775376639090712079350,\n            15380517677991831032858870866819856499419492092909311846600193251951859042321\n        );\n\n        vk[78] = G1Point(\n            12681723977387824731895989023500526405308466858542903103055928573501887506887,\n            11370573709343602505230460979583593651754855121852100216138643349056073782952\n        );\n\n        vk[79] = G1Point(\n            4200058302555642333283692750835107019807983821991387347796012866346514302605,\n            14357085568398294016842996105655116738370071081936618062005085850396798772802\n        );\n\n        vk[80] = G1Point(\n            14137699264377957975776528918800596987631257455548836008761386515677706582563,\n            2877943046106495432464489171942097254021067591451481943864022445799990140117\n        );\n\n        vk[81] = G1Point(\n            7480145966790209514588805951103723897773954176759764819231387108562986050867,\n            12404751866229336820648708250938384384013582100169058004847207735622575043993\n        );\n\n        vk[82] = G1Point(\n            12970817937144745309785994864230789483629807994776973410040274401977769841052,\n            5825762304110705990197138035992052772838196210579994473399600004016677423488\n        );\n\n        vk[83] = G1Point(\n            14988453290426221989095533870965847942554723567967755183069083157996373748616,\n            8648840510009197738716543586800373429604948580372256694893314143136379863664\n        );\n\n        vk[84] = G1Point(\n            15145542077656252793870557125161247488411025860428855768932504599780138755577,\n            2178169336494538462372002990799200948579620951049701898691482757493703042642\n        );\n\n        vk[85] = G1Point(\n            11135789569088525124827536278606171249701996905898972803869975950803968697579,\n            3104837136515107621506029430582483708481393523526438371726824112484239803581\n        );\n\n        vk[86] = G1Point(\n            17066149863746730614554018679517110986144152654411463722880426514835413500149,\n            11885136744232152755409190843781868227764042786753547405780615738418310637923\n        );\n\n        vk[87] = G1Point(\n            8848015573236418075663743497372404662739214749989826392286123012148059889680,\n            1972243942447596180922716596695612444433272877968270983679827686933514965206\n        );\n\n        vk[88] = G1Point(\n            14865752525354582126252517599134593966808867282046342796694614702712521564336,\n            18116025354261037812375363008053160294289201308729119292420655212966763428629\n        );\n\n        vk[89] = G1Point(\n            20008653757824978308869797085409493811497783305061398226809054512392049926827,\n            2023221323067464241928858421807576285617952900431861729331205253026094553028\n        );\n\n        vk[90] = G1Point(\n            9427479375857197202287179331720188202666358779957538977247547218804648021559,\n            13103256830144414831969119769186006894217432078739958285698595391380496268010\n        );\n\n        vk[91] = G1Point(\n            3022753493095593546667513964979418729795168926723981739728213991436890865173,\n            15651100209468844976455723098156772118319496522347044594278603917566715835964\n        );\n\n        vk[92] = G1Point(\n            11863153566289362104600364540490616631416480033499697509671034253106023069686,\n            6263106079901584198635057982958449515247366171335121668407272647131625665359\n        );\n\n        vk[93] = G1Point(\n            1632268454934283210866357082989656996613161609804593296738987685077804217796,\n            8943206385844065158715717104595797380028345892524924749292670404417492092532\n        );\n\n        vk[94] = G1Point(\n            2514580143298917949844157611116376945011648866679103488807951227637293425228,\n            1570539622709169759643018064245830768717632289525346051035788970161633534650\n        );\n\n        vk[95] = G1Point(\n            14995127663646685519705792243009870088473684011447124089592875697835776461681,\n            10011280883107051614601335912182178771718155707859435453848946557263718614275\n        );\n\n        vk[96] = G1Point(\n            10837864859142056917623769978173380007817338460373139706119502408994471525015,\n            5688212466311380080002109574884673535981843432406127069039894776083240717165\n        );\n\n        vk[97] = G1Point(\n            8184241099722337872655100621160316867350497097484481073516270737365644965184,\n            8370899682353048184295715026039653844162707028675185918829983378235273090579\n        );\n\n        vk[98] = G1Point(\n            14336699639296594061188773829570477118517654937378475865402690828519678655979,\n            18962321517991296846137966567405441567624457545084441947313953041676115679070\n        );\n\n        vk[99] = G1Point(\n            9460029977525714962867496691244424070473524798482965710433684902814580254803,\n            13773860226345636507739066933383044706264742752335080543835025360890117637789\n        );\n\n        vk[100] = G1Point( \n            19391891390609481429849774145579503985374912055370046060106347963180567737648,\n            7728129834219170358551601609946089408272789276196019291377633982082964264714\n        );\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/circuitVerifier.sol",
        "content": "//\n// Copyright 2017 Christian Reitwiessner\n// 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:\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n// 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.\n//\n// 2019 OKIMS\n//      ported to solidity 0.6\n//      fixed linter warnings\n//      added requiere error messages\n//\n//\n// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.17;\nlibrary Pairing {\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n    // Encoding of field elements is: X[0] * z + X[1]\n    struct G2Point {\n        uint[2] X;\n        uint[2] Y;\n    }\n    /// @return the generator of G1\n    function P1() internal pure returns (G1Point memory) {\n        return G1Point(1, 2);\n    }\n    /// @return the generator of G2\n    function P2() internal pure returns (G2Point memory) {\n        // Original code point\n        return G2Point(\n            [11559732032986387107991004021392285783925812861821192530917403151452391805634,\n             10857046999023057135944570762232829481370756359578518086990519993285655852781],\n            [4082367875863433681332203403145435568316851327593401208105741076214120093531,\n             8495653923123431417604973247489272438418190587263600148770280649306958101930]\n        );\n\n/*\n        // Changed by Jordi point\n        return G2Point(\n            [10857046999023057135944570762232829481370756359578518086990519993285655852781,\n             11559732032986387107991004021392285783925812861821192530917403151452391805634],\n            [8495653923123431417604973247489272438418190587263600148770280649306958101930,\n             4082367875863433681332203403145435568316851327593401208105741076214120093531]\n        );\n*/\n    }\n    /// @return r the negation of p, i.e. p.addition(p.negate()) should be zero.\n    function negate(G1Point memory p) internal pure returns (G1Point memory r) {\n        // The prime q in the base field F_q for G1\n        uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;\n        if (p.X == 0 && p.Y == 0)\n            return G1Point(0, 0);\n        return G1Point(p.X, q - (p.Y % q));\n    }\n    /// @return r the sum of two points of G1\n    function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {\n        uint[4] memory input;\n        input[0] = p1.X;\n        input[1] = p1.Y;\n        input[2] = p2.X;\n        input[3] = p2.Y;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require(success,\"pairing-add-failed\");\n    }\n    /// @return r the product of a point on G1 and a scalar, i.e.\n    /// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.\n    function scalar_mul(G1Point memory p, uint s) internal view returns (G1Point memory r) {\n        uint[3] memory input;\n        input[0] = p.X;\n        input[1] = p.Y;\n        input[2] = s;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require (success,\"pairing-mul-failed\");\n    }\n    /// @return the result of computing the pairing check\n    /// e(p1[0], p2[0]) *  .... * e(p1[n], p2[n]) == 1\n    /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should\n    /// return true.\n    function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {\n        require(p1.length == p2.length,\"pairing-lengths-failed\");\n        uint elements = p1.length;\n        uint inputSize = elements * 6;\n        uint[] memory input = new uint[](inputSize);\n        for (uint i = 0; i < elements; i++)\n        {\n            input[i * 6 + 0] = p1[i].X;\n            input[i * 6 + 1] = p1[i].Y;\n            input[i * 6 + 2] = p2[i].X[0];\n            input[i * 6 + 3] = p2[i].X[1];\n            input[i * 6 + 4] = p2[i].Y[0];\n            input[i * 6 + 5] = p2[i].Y[1];\n        }\n        uint[1] memory out;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require(success,\"pairing-opcode-failed\");\n        return out[0] != 0;\n    }\n    /// Convenience method for a pairing check for two pairs.\n    function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](2);\n        G2Point[] memory p2 = new G2Point[](2);\n        p1[0] = a1;\n        p1[1] = b1;\n        p2[0] = a2;\n        p2[1] = b2;\n        return pairing(p1, p2);\n    }\n    /// Convenience method for a pairing check for three pairs.\n    function pairingProd3(\n            G1Point memory a1, G2Point memory a2,\n            G1Point memory b1, G2Point memory b2,\n            G1Point memory c1, G2Point memory c2\n    ) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](3);\n        G2Point[] memory p2 = new G2Point[](3);\n        p1[0] = a1;\n        p1[1] = b1;\n        p1[2] = c1;\n        p2[0] = a2;\n        p2[1] = b2;\n        p2[2] = c2;\n        return pairing(p1, p2);\n    }\n    /// Convenience method for a pairing check for four pairs.\n    function pairingProd4(\n            G1Point memory a1, G2Point memory a2,\n            G1Point memory b1, G2Point memory b2,\n            G1Point memory c1, G2Point memory c2,\n            G1Point memory d1, G2Point memory d2\n    ) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](4);\n        G2Point[] memory p2 = new G2Point[](4);\n        p1[0] = a1;\n        p1[1] = b1;\n        p1[2] = c1;\n        p1[3] = d1;\n        p2[0] = a2;\n        p2[1] = b2;\n        p2[2] = c2;\n        p2[3] = d2;\n        return pairing(p1, p2);\n    }\n}\ncontract CircuitVerifier {\n    using Pairing for *;\n    struct VerifyingKey {\n        Pairing.G1Point alfa1;\n        Pairing.G2Point beta2;\n        Pairing.G2Point gamma2;\n        Pairing.G2Point delta2;\n        Pairing.G1Point[] IC;\n    }\n    struct Proof {\n        Pairing.G1Point A;\n        Pairing.G2Point B;\n        Pairing.G1Point C;\n    }\n    function verifyingKey() internal pure returns (VerifyingKey memory vk) {\n        vk.alfa1 = Pairing.G1Point(\n            20491192805390485299153009773594534940189261866228447918068658471970481763042,\n            9383485363053290200918347156157836566562967994039712273449902621266178545958\n        );\n\n        vk.beta2 = Pairing.G2Point(\n            [4252822878758300859123897981450591353533073413197771768651442665752259397132,\n             6375614351688725206403948262868962793625744043794305715222011528459656738731],\n            [21847035105528745403288232691147584728191162732299865338377159692350059136679,\n             10505242626370262277552901082094356697409835680220590971873171140371331206856]\n        );\n        vk.gamma2 = Pairing.G2Point(\n            [11559732032986387107991004021392285783925812861821192530917403151452391805634,\n             10857046999023057135944570762232829481370756359578518086990519993285655852781],\n            [4082367875863433681332203403145435568316851327593401208105741076214120093531,\n             8495653923123431417604973247489272438418190587263600148770280649306958101930]\n        );\n        vk.delta2 = Pairing.G2Point(\n            [21223509572149436009383842546644857332549415106982951130166482247313305552407,\n             3651919070680602585131326454611744313033427008208909328852558006475401815457],\n            [18868338637417310549300806688818271707183649362616203659593245255731372694149,\n             12639385737564052598655546142232001975674170132048529941115373366821228560987]\n        );\n        vk.IC = new Pairing.G1Point[](32);\n        \n        vk.IC[0] = Pairing.G1Point( \n            19285368940731314812277377326380883472569493771921601523645257990686666718389,\n            1372693327773405640347273163919379519555169290873089668969290615157317568035\n        );                                      \n        \n        vk.IC[1] = Pairing.G1Point( \n            20563536359277927673211382785955880671029020113525488954738694785575739831195,\n            11622487325429485635036204798963062119327899165409993719814798109467539711521\n        );                                      \n        \n        vk.IC[2] = Pairing.G1Point( \n            8875816761637054206953475440341751666786638952753385218037925061132134808360,\n            10670771010820437935149234172619692113592674470313124621792870855604924174724\n        );                                      \n        \n        vk.IC[3] = Pairing.G1Point( \n            16310041769337439549216324037724832358058235392896021682362617270538374194950,\n            19324449383987862762752536963119465502812921099286174351059525673474911225532\n        );                                      \n        \n        vk.IC[4] = Pairing.G1Point( \n            5783563821028270213576609919720027429769938502424460091302825153121542109354,\n            1470669597353590816746365817778990659877634944571654698518112762825899872953\n        );                                      \n        \n        vk.IC[5] = Pairing.G1Point( \n            914937451350736032348203387680959396512999207088712230002930452486647275486,\n            13278992517431057944065874304895401817561900836300928790090187392043172986310\n        );                                      \n        \n        vk.IC[6] = Pairing.G1Point( \n            18097596007339529406692800143852776601000937260850591264898128684789643908212,\n            9153937710318033405384133751664845960297229722568264885716854633955663625536\n        );                                      \n        \n        vk.IC[7] = Pairing.G1Point( \n            6193249348722695043944500703095878319595334835001600074904795240215318098962,\n            7853680886918860231577585366958076401174476205187153074482747182486269572453\n        );                                      \n        \n        vk.IC[8] = Pairing.G1Point( \n            15270422438445823922593250494709654463789987296743911250277775444865091824612,\n            4102182906941581233304729176391766141314683070891114801586417028043961885657\n        );                                      \n        \n        vk.IC[9] = Pairing.G1Point( \n            1302681630257233329077408872587714433119006291453962064536810133248742069768,\n            16311982814639644121944335458064770134173125251073766459777997299727849450385\n        );                                      \n        \n        vk.IC[10] = Pairing.G1Point( \n            2547973719675613033586687516381437235939306144752695939764438305531826924266,\n            18707555548721531003785445481648633019475010768441520378552149383179479150717\n        );                                      \n        \n        vk.IC[11] = Pairing.G1Point( \n            4428496179622071166051755585560830941147382314141057626874137147454947858555,\n            20313942796395280130218843132871495899105990153866314823037951753327298389440\n        );                                      \n        \n        vk.IC[12] = Pairing.G1Point( \n            21090886813683041019220427702428409885856117842016306648411480480763064485622,\n            2904286936290379856261715681207382922806286474730092451626811072360471392706\n        );                                      \n        \n        vk.IC[13] = Pairing.G1Point( \n            16953207110836848412348418809752737780820855895491067079125814117205539343156,\n            1818176631812756401799820926733888831130235415626052739389592258254689714069\n        );                                      \n        \n        vk.IC[14] = Pairing.G1Point( \n            14275611219479745388903161313834529621377028751523300114715470306855103627468,\n            11395634342520831379817961559538472855919256807836266605671005070285381756811\n        );                                      \n        \n        vk.IC[15] = Pairing.G1Point( \n            9309985145070020350527688966527437090410653959124451822044308620974043195469,\n            5088783600811643090890999487942869959512873512301353706146318021257882291855\n        );                                      \n        \n        vk.IC[16] = Pairing.G1Point( \n            13845291475527603009053139388380092079280298146548334122387682777257704819701,\n            19983427718412885469630659039041222500384101588665734536304699212006998692472\n        );                                      \n        \n        vk.IC[17] = Pairing.G1Point( \n            13231858176024723276494898879866156922615784394666546818166548789657182161333,\n            11199542500735857507253092815482494011222825605932956765796942807430804932442\n        );                                      \n        \n        vk.IC[18] = Pairing.G1Point( \n            15155380983211082488641924827916379578962497681571449333022148252969777764037,\n            4146224505674490292116190239156754729027337668003337499925105327877886686419\n        );                                      \n        \n        vk.IC[19] = Pairing.G1Point( \n            8169038537569741399573329096561615641148655375190982634441976478639056198693,\n            11963650259756467569328883816276529262045940085129455596849074710225723789976\n        );                                      \n        \n        vk.IC[20] = Pairing.G1Point( \n            5768155153658025058286442157394530016577292835139355355291835326382757604073,\n            20084350319318171708307617210896946548033127857641151424695801209275721178484\n        );                                      \n        \n        vk.IC[21] = Pairing.G1Point( \n            12703197821467744408272824365427240188730432752459024271595948028914355362762,\n            10123119830081479418463659963407526854356320634595089810637209343214392456651\n        );                                      \n        \n        vk.IC[22] = Pairing.G1Point( \n            18202154060412128906014642267610638621848197350141370475801967787541536447902,\n            7172856910555396735982105446089210786857646719326360443646152381651817923139\n        );                                      \n        \n        vk.IC[23] = Pairing.G1Point( \n            17170777702061064354926492758896433985012177585871248144609849735893537428237,\n            412998423308992625938675915107301585996363349849877844235609364273086873580\n        );                                      \n        \n        vk.IC[24] = Pairing.G1Point( \n            3545350639001990923140538415427584236524735576470412437640669325012183149004,\n            20188177885143613106665205433040400257378338431586890569517744733352415194844\n        );                                      \n        \n        vk.IC[25] = Pairing.G1Point( \n            21431297364806809809353204501967336223370018667834067200289961618421550463576,\n            6224434139824781014957254620472227483320631913991355808517618408479036778646\n        );                                      \n        \n        vk.IC[26] = Pairing.G1Point( \n            20280682591691563582384585973340321812285845652705934582770347952936885495314,\n            12208275392540746880779008886418423836514168579437691486870715982767835559268\n        );                                      \n        \n        vk.IC[27] = Pairing.G1Point( \n            10015165244416857193592336278992467819961744116081081647783642516266955540912,\n            20130961332116514755984061027376120975717399625907757330731812572615020936707\n        );                                      \n        \n        vk.IC[28] = Pairing.G1Point( \n            8336371214105638859634154554031929460603615856662424524205559804248139721705,\n            15877135363481174608851919525400781895600679056573072501733758948126246943151\n        );                                      \n        \n        vk.IC[29] = Pairing.G1Point( \n            14076177816885665971918033670006882703355155560752256957969673368434759377466,\n            4110228092353627263550493253063698850130425422586685028497387964159506802444\n        );                                      \n        \n        vk.IC[30] = Pairing.G1Point( \n            21779324301473364824100454032265775775351274040721207181034336488931253729090,\n            501953779072995894027107266033339049457352284371355668744583435564783383240\n        );                                      \n        \n        vk.IC[31] = Pairing.G1Point( \n            17060488929845011250862811192805763333332019172161699169052857724884424599208,\n            8629028379209702408634728188414144519665064163607186328886948451932454722462\n        );                                      \n        \n    }\n    function verify(uint[] memory input, Proof memory proof) internal view returns (uint) {\n        uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;\n        VerifyingKey memory vk = verifyingKey();\n        require(input.length + 1 == vk.IC.length,\"verifier-bad-input\");\n        // Compute the linear combination vk_x\n        Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);\n        for (uint i = 0; i < input.length; i++) {\n            require(input[i] < snark_scalar_field,\"verifier-gte-snark-scalar-field\");\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));\n        }\n        vk_x = Pairing.addition(vk_x, vk.IC[0]);\n        if (!Pairing.pairingProd4(\n            Pairing.negate(proof.A), proof.B,\n            vk.alfa1, vk.beta2,\n            vk_x, vk.gamma2,\n            proof.C, vk.delta2\n        )) return 1;\n        return 0;\n    }\n    /// @return r  bool true if proof is valid\n    function verifyProof(\n            uint[2] memory a,\n            uint[2][2] memory b,\n            uint[2] memory c,\n            uint[] memory input\n        ) public view returns (bool r) {\n        Proof memory proof;\n        proof.A = Pairing.G1Point(a[0], a[1]);\n        proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);\n        proof.C = Pairing.G1Point(c[0], c[1]);\n\n        if (verify(input, proof) == 0) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/contracts/encryptionVerifier.sol",
        "content": "//\n// Copyright 2017 Christian Reitwiessner\n// 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:\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n// 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.\n//\n// 2019 OKIMS\n//      ported to solidity 0.6\n//      fixed linter warnings\n//      added requiere error messages\n//\n//\n// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.17;\n\nimport \"./Pairing100.sol\";\nimport \"./Pairing200.sol\";\nimport \"./Pairing300.sol\";\nimport \"./Pairing400.sol\";\nimport \"./Pairing500.sol\";\nimport \"./Pairing600.sol\";\nimport \"./Pairing700.sol\";\nimport \"./Pairing800.sol\";\nimport \"./Pairing900.sol\";\nimport \"./Pairing1000.sol\";\n\nlibrary Pairing {\n    struct G1Point {\n        uint X;\n        uint Y;\n    }\n    // Encoding of field elements is: X[0] * z + X[1]\n    struct G2Point {\n        uint[2] X;\n        uint[2] Y;\n    }\n    /// @return the generator of G1\n    function P1() internal pure returns (G1Point memory) {\n        return G1Point(1, 2);\n    }\n    /// @return the generator of G2\n    function P2() internal pure returns (G2Point memory) {\n        // Original code point\n        return G2Point(\n            [11559732032986387107991004021392285783925812861821192530917403151452391805634,\n             10857046999023057135944570762232829481370756359578518086990519993285655852781],\n            [4082367875863433681332203403145435568316851327593401208105741076214120093531,\n             8495653923123431417604973247489272438418190587263600148770280649306958101930]\n        );\n\n/*\n        // Changed by Jordi point\n        return G2Point(\n            [10857046999023057135944570762232829481370756359578518086990519993285655852781,\n             11559732032986387107991004021392285783925812861821192530917403151452391805634],\n            [8495653923123431417604973247489272438418190587263600148770280649306958101930,\n             4082367875863433681332203403145435568316851327593401208105741076214120093531]\n        );\n*/\n    }\n    /// @return r the negation of p, i.e. p.addition(p.negate()) should be zero.\n    function negate(G1Point memory p) internal pure returns (G1Point memory r) {\n        // The prime q in the base field F_q for G1\n        uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;\n        if (p.X == 0 && p.Y == 0)\n            return G1Point(0, 0);\n        return G1Point(p.X, q - (p.Y % q));\n    }\n    /// @return r the sum of two points of G1\n    function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {\n        uint[4] memory input;\n        input[0] = p1.X;\n        input[1] = p1.Y;\n        input[2] = p2.X;\n        input[3] = p2.Y;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require(success,\"pairing-add-failed\");\n    }\n    /// @return r the product of a point on G1 and a scalar, i.e.\n    /// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.\n    function scalar_mul(G1Point memory p, uint s) internal view returns (G1Point memory r) {\n        uint[3] memory input;\n        input[0] = p.X;\n        input[1] = p.Y;\n        input[2] = s;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require (success,\"pairing-mul-failed\");\n    }\n    /// @return the result of computing the pairing check\n    /// e(p1[0], p2[0]) *  .... * e(p1[n], p2[n]) == 1\n    /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should\n    /// return true.\n    function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {\n        require(p1.length == p2.length,\"pairing-lengths-failed\");\n        uint elements = p1.length;\n        uint inputSize = elements * 6;\n        uint[] memory input = new uint[](inputSize);\n        for (uint i = 0; i < elements; i++)\n        {\n            input[i * 6 + 0] = p1[i].X;\n            input[i * 6 + 1] = p1[i].Y;\n            input[i * 6 + 2] = p2[i].X[0];\n            input[i * 6 + 3] = p2[i].X[1];\n            input[i * 6 + 4] = p2[i].Y[0];\n            input[i * 6 + 5] = p2[i].Y[1];\n        }\n        uint[1] memory out;\n        bool success;\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)\n            // Use \"invalid\" to make gas estimation work\n            switch success case 0 { invalid() }\n        }\n        require(success,\"pairing-opcode-failed\");\n        return out[0] != 0;\n    }\n    /// Convenience method for a pairing check for two pairs.\n    function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](2);\n        G2Point[] memory p2 = new G2Point[](2);\n        p1[0] = a1;\n        p1[1] = b1;\n        p2[0] = a2;\n        p2[1] = b2;\n        return pairing(p1, p2);\n    }\n    /// Convenience method for a pairing check for three pairs.\n    function pairingProd3(\n            G1Point memory a1, G2Point memory a2,\n            G1Point memory b1, G2Point memory b2,\n            G1Point memory c1, G2Point memory c2\n    ) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](3);\n        G2Point[] memory p2 = new G2Point[](3);\n        p1[0] = a1;\n        p1[1] = b1;\n        p1[2] = c1;\n        p2[0] = a2;\n        p2[1] = b2;\n        p2[2] = c2;\n        return pairing(p1, p2);\n    }\n    /// Convenience method for a pairing check for four pairs.\n    function pairingProd4(\n            G1Point memory a1, G2Point memory a2,\n            G1Point memory b1, G2Point memory b2,\n            G1Point memory c1, G2Point memory c2,\n            G1Point memory d1, G2Point memory d2\n    ) internal view returns (bool) {\n        G1Point[] memory p1 = new G1Point[](4);\n        G2Point[] memory p2 = new G2Point[](4);\n        p1[0] = a1;\n        p1[1] = b1;\n        p1[2] = c1;\n        p1[3] = d1;\n        p2[0] = a2;\n        p2[1] = b2;\n        p2[2] = c2;\n        p2[3] = d2;\n        return pairing(p1, p2);\n    }\n}\ncontract EncryptionVerifier {\n    using Pairing for *;\n\n    address private pairing100;\n    address private pairing200;\n    address private pairing300;\n    address private pairing400;\n    address private pairing500;\n    address private pairing600;\n    address private pairing700;\n    address private pairing800;\n    address private pairing900;\n    address private pairing1000;\n\n    struct VerifyingKey {\n        Pairing.G1Point alfa1;\n        Pairing.G2Point beta2;\n        Pairing.G2Point gamma2;\n        Pairing.G2Point delta2;\n        Pairing.G1Point[] IC;\n    }\n    struct Proof {\n        Pairing.G1Point A;\n        Pairing.G2Point B;\n        Pairing.G1Point C;\n    }\n\n    constructor(\n        address add100,\n        address add200,\n        address add300,\n        address add400,\n        address add500,\n        address add600,\n        address add700,\n        address add800, \n        address add900,\n        address add1000\n    ) {\n        pairing100 = add100;\n        pairing200 = add200;\n        pairing300 = add300;\n        pairing400 = add400;\n        pairing500 = add500;\n        pairing600 = add600;\n        pairing700 = add700;\n        pairing800 = add800;\n        pairing900 = add900;\n        pairing1000 = add1000;\n    }\n\n    function verifyingKey() internal pure returns (VerifyingKey memory vk) {\n        vk.alfa1 = Pairing.G1Point(\n            20491192805390485299153009773594534940189261866228447918068658471970481763042,\n            9383485363053290200918347156157836566562967994039712273449902621266178545958\n        );\n\n        vk.beta2 = Pairing.G2Point(\n            [4252822878758300859123897981450591353533073413197771768651442665752259397132,\n             6375614351688725206403948262868962793625744043794305715222011528459656738731],\n            [21847035105528745403288232691147584728191162732299865338377159692350059136679,\n             10505242626370262277552901082094356697409835680220590971873171140371331206856]\n        );\n        vk.gamma2 = Pairing.G2Point(\n            [11559732032986387107991004021392285783925812861821192530917403151452391805634,\n             10857046999023057135944570762232829481370756359578518086990519993285655852781],\n            [4082367875863433681332203403145435568316851327593401208105741076214120093531,\n             8495653923123431417604973247489272438418190587263600148770280649306958101930]\n        );\n        vk.delta2 = Pairing.G2Point(\n            [6653259084928985759212025249045143654297075953578382745064964143441455343356,\n             8160999132074616195727858211272521546858233416802944087099739007663370791684],\n            [5005417252240310256132733574742221180631042236600616922722331817516271580377,\n             535375283190531279782443189967329266724259036468032022432462508232591886570]\n        );    \n        vk.IC = new Pairing.G1Point[](1006);\n        \n        vk.IC[0] = Pairing.G1Point( \n            3913146479250333998622309518342179854776388675763500448325061276047871385028,\n            185902641878167853786013541387769876019822308496137446718496175008088134965\n        );                                \n        \n    }\n    function verify(uint[] memory input, Proof memory proof) internal view returns (uint) {\n        uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;\n        VerifyingKey memory vk = verifyingKey();\n        require(input.length + 1 == 1006,\"verifier-bad-input\");\n        // Compute the linear combination vk_x\n        Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);\n        for (uint i = 0; i < 100; i++) {\n            require(input[i] < snark_scalar_field,\"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing100(pairing100).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 100] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing200(pairing200).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 100]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 200] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing300(pairing300).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 200]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 300] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing400(pairing400).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 300]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 400] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing500(pairing500).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 400]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 500] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing600(pairing600).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 500]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 600] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing700(pairing700).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 600]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 700] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing800(pairing800).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 700]));\n        }\n        for (uint i = 0; i < 100; i++) {\n            require(input[i + 800] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing900(pairing900).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 800]));\n        }\n        for (uint i = 0; i < 105; i++) {\n            require(input[i + 900] < snark_scalar_field, \"verifier-gte-snark-scalar-field\");\n            (uint X, uint Y) = Pairing1000(pairing1000).vk(i + 1);\n            vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 900]));\n        }\n        vk_x = Pairing.addition(vk_x, vk.IC[0]);\n        if (!Pairing.pairingProd4(\n            Pairing.negate(proof.A), proof.B,\n            vk.alfa1, vk.beta2,\n            vk_x, vk.gamma2,\n            proof.C, vk.delta2\n        )) return 1;\n        return 0;\n    }\n    /// @return r  bool true if proof is valid\n    function verifyProof(\n            uint[2] memory a,\n            uint[2][2] memory b,\n            uint[2] memory c,\n            uint[1005] memory input\n        ) public view returns (bool r) {\n        Proof memory proof;\n        proof.A = Pairing.G1Point(a[0], a[1]);\n        proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);\n        proof.C = Pairing.G1Point(c[0], c[1]);\n        uint[] memory inputValues = new uint[](input.length);\n        for(uint i = 0; i < input.length; i++){\n            inputValues[i] = input[i];\n        }\n        if (verify(inputValues, proof) == 0) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/deploy/deploy.js",
        "content": "module.exports = async ({ getNamedAccounts, deployments }) => {\n    const { deploy } = deployments;\n    const { deployer } = await getNamedAccounts();\n\n    const pairing100 = await deploy('Pairing100', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing200 = await deploy('Pairing200', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing300 = await deploy('Pairing300', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing400 = await deploy('Pairing400', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing500 = await deploy('Pairing500', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing600 = await deploy('Pairing600', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing700 = await deploy('Pairing700', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing800 = await deploy('Pairing800', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing900 = await deploy('Pairing900', {\n        from: deployer,\n        log: true\n    });\n\n    const pairing1000 = await deploy('Pairing1000', {\n        from: deployer,\n        log: true\n    });\n\n    const encryptionVerifier = await deploy('EncryptionVerifier', {\n        from: deployer,\n        log: true,\n        args: [pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address]\n    });\n\n    await deploy('BountyFactory', {\n        from: deployer,\n        log: true,\n        args: [encryptionVerifier.address]\n    });\n\n    await deploy('CircuitVerifier', {\n        from: deployer,\n        log: true\n    });\n};\nmodule.exports.tags = ['complete'];\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/hardhat.config.js",
        "content": "require(\"@nomicfoundation/hardhat-toolbox\");\nrequire(\"@nomiclabs/hardhat-ethers\");\nrequire(\"hardhat-deploy\");\nrequire(\"hardhat-contract-sizer\");\nrequire(\"hardhat-gas-reporter\");\nrequire(\"dotenv\").config();\n\n// const { PRIVATE_KEY: GOERLI_PRIVATE_KEY, ALCHEMY_API_KEY } = process.env;\n\nmodule.exports = {\n    solidity: {\n        version: \"0.8.17\",\n        optimizer: {\n            enabled: true,\n            runs: 1000,\n        }\n    },\n    networks: {\n        hardhat: {\n            chainId: 1337,\n            allowUnlimitedContractSize: true,\n            gas: 100000000,\n            blockGasLimit: 0x1fffffffffffff,\n        },\n        // goerli: {\n        //     allowUnlimitedContractSize: true,\n        //     gas: 100000000,\n        //     blockGasLimit: 0x1fffffffffffff,\n        //     url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,\n        //     accounts: [`${GOERLI_PRIVATE_KEY}`],\n        // },\n    },\n    namedAccounts: {\n        deployer: 0,\n    },\n    paths: {\n        deploy: \"deploy\",\n        deployments: \"deployments\",\n    },\n    mocha: {\n        timeout: 1000000\n    }\n};\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/scripts/bump-solidity.js",
        "content": "const fs = require(\"fs\");\nconst solidityRegex = /pragma solidity \\^\\d+\\.\\d+\\.\\d+/\nconst inputRegex = /uint\\[\\d+\\] memory input(?!;)/\nconst contentRegex = /proof\\.C = Pairing\\.G1Point\\(c\\[0\\], c\\[1\\]\\);([\\s\\S]*?)if \\(verify\\(inputValues, proof\\) == 0\\)/\nconst verifierRegex = /contract Verifier/\n\nlet content = fs.readFileSync(\"./contracts/circuitVerifier.sol\", { encoding: 'utf-8' });\nlet bumped = content.replace(solidityRegex, 'pragma solidity ^0.8.17');\nbumped = bumped.replace(inputRegex, 'uint[] memory input');\nbumped = bumped.replace(contentRegex, 'proof.C = Pairing.G1Point(c[0], c[1]);\\n\\n        if (verify(input, proof) == 0)');\nlet renamed = bumped.replace(verifierRegex, 'contract CircuitVerifier');\n\nfs.writeFileSync(\"./contracts/circuitVerifier.sol\", renamed);\n\ncontent = fs.readFileSync(\"./contracts/encryptionVerifier.sol\", { encoding: 'utf-8' });\nbumped = content.replace(solidityRegex, 'pragma solidity ^0.8.17');\n// bumped = bumped.replace(inputRegex, 'uint[] memory input');\n// bumped = bumped.replace(contentRegex, 'proof.C = Pairing.G1Point(c[0], c[1]);\\n\\n        if (verify(input, proof) == 0)');\nrenamed = bumped.replace(verifierRegex, 'contract EncryptionVerifier');\n\nfs.writeFileSync(\"./contracts/encryptionVerifier.sol\", renamed);\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/scripts/upload-data.js",
        "content": "require(\"dotenv\").config();\nconst lighthouse = require('@lighthouse-web3/sdk');\nconst fs = require('fs');\n\nconst apiKey = process.env.API_KEY;\n\nasync function main() {\n    const hashes = [];\n\n    for (let i = 0; i < 1000; i++) {\n        const path = \"assets/\" + i + \".pgm\"; //Give path to the file\n        const response = await lighthouse.uploadFileRaw(path, apiKey);\n        console.log(response.data.Hash);\n        hashes.push(response.data.Hash);\n        if (i == 0) {\n            console.assert(response.data.Hash == \"bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje\");\n        }\n        console.assert(response.data.Size == \"797\");\n    }\n\n    fs.writeFileSync(\"assets/cid.txt\", hashes.join(\"\\r\"));\n}\n\nmain().then(() => process.exit(0)).catch(error => {\n    console.error(error);\n    process.exit(1);\n});"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/test/0.lighthouse.test.js",
        "content": "const { expect } = require(\"chai\");\nconst { ethers } = require(\"hardhat\");\n\nrequire(\"dotenv\").config();\nconst lighthouse = require('@lighthouse-web3/sdk');\nconst { recoverShards } = require(\"@lighthouse-web3/kavach\");\nconst fs = require(\"fs\");\n\nconst privateKey = process.env.PRIVATE_KEY;\nconst publicKey = process.env.PUBLIC_KEY;\nconst privateKeyBob = process.env.PRIVATE_KEY_BOB;\nconst publicKeyBob = process.env.PUBLIC_KEY_BOB;\n\nconst apiKey = process.env.API_KEY;\nconst path = \"assets/0.pgm\"; //Give path to the file\n\nconst sign_auth_message = async (publicKey, privateKey) => {\n    const provider = new ethers.providers.JsonRpcProvider();\n    const signer = new ethers.Wallet(privateKey, provider);\n    const messageRequested = (await lighthouse.getAuthMessage(publicKey)).data.message;\n    const signedMessage = await signer.signMessage(messageRequested);\n    return (signedMessage)\n}\n\ndescribe(\"Lighthouse SDK test\", function () {\n\n    it(\"Should upload file in raw to lighthouse\", async function () {\n        const response = await lighthouse.uploadFileRaw(path, apiKey);\n        expect(response.data.Name).equal(\"0.pgm\");\n        expect(response.data.Hash).equal(\"bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje\");\n        expect(response.data.Size).equal(\"797\")\n    });\n\n    it(\"Should upload file to lighthouse\", async function () {\n        const response = await lighthouse.upload(path, apiKey);\n        expect(response.data.Name).equal(\"0.pgm\");\n        expect(response.data.Hash).equal(\"QmevD3vQfg6Nf9RYWGCrNdfmT49BhLS714sxGkVifqmYg9\");\n        expect(response.data.Size).equal(\"808\")\n    });\n\n    let cid;\n\n    it(\"Should upload encrypted file to lighthouse\", async function () {\n        const signed_message = await sign_auth_message(publicKey, privateKey);\n\n        const response = await lighthouse.uploadEncrypted(\n            path,\n            apiKey,\n            publicKey,\n            signed_message,\n        );\n\n        expect(response.data.Name).equal(\"0.pgm\");\n        // expect(response.data.Hash).equal(\"QmeakAMwVmYerw8DgZ5jyNHMV8G1fe6cNMvViezzM6bRqt\");\n        expect(response.data.Size).equal(\"852\");\n\n        cid = response.data.Hash;\n    });\n\n    it(\"Should download decrypted file from lighthouse\", async function () {\n        const signed_message = await sign_auth_message(publicKey, privateKey);\n        const fileEncryptionKey = await lighthouse.fetchEncryptionKey(\n            cid,\n            publicKey,\n            signed_message\n        );\n        const decrypted = await lighthouse.decryptFile(\n            cid,\n            fileEncryptionKey.data.key\n        );\n        expect(decrypted.byteLength).equal(797);\n    });\n\n    it(\"Should share private file with another user\", async function () {\n        const signed_message = await sign_auth_message(publicKey, privateKey);\n\n        const response = await lighthouse.shareFile(\n            publicKey,\n            [publicKeyBob],\n            cid,\n            signed_message,\n        );\n\n        expect(response.data.cid).equal(cid);\n        expect(response.data.status).equal(\"Success\");\n        expect(response.data.shareTo[0]).equal(publicKeyBob);\n    });\n\n    it(\"Should download decrypted file from lighthouse shared with another user\", async function () {\n        const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob);\n        const fileEncryptionKey = await lighthouse.fetchEncryptionKey(\n            cid,\n            publicKeyBob,\n            signed_message\n        );\n        const decrypted = await lighthouse.decryptFile(\n            cid,\n            fileEncryptionKey.data.key\n        );\n        expect(decrypted.byteLength).equal(797);\n    });\n\n    it(\"Should revoke access to private file from another user\", async function () {\n        const signed_message = await sign_auth_message(publicKey, privateKey);\n\n        const response = await lighthouse.revokeFileAccess(\n            publicKey,\n            [publicKeyBob],\n            cid,\n            signed_message,\n        );\n\n        expect(response.data.cid).equal(cid);\n        expect(response.data.status).equal(\"Success\");\n        expect(response.data.revokeTo[0]).equal(publicKeyBob);\n\n    });\n\n    it(\"Should not be able to download decrypted file from lighthouse shared with another user\", async function () {\n        const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob);\n\n        const { error, shards } = await recoverShards(\n            publicKeyBob,\n            cid,\n            signed_message,\n            5\n        );\n\n        expect(shards.length).equal(0);\n        expect(error?.message).equal(\"you don't have access\");\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/test/1.circuit.test.js",
        "content": "const { expect, assert } = require(\"chai\");\nconst { ethers } = require(\"hardhat\");\nconst { groth16 } = require(\"snarkjs\");\n\nconst fs = require(\"fs\");\nconst crypto = require(\"crypto\");\nconst base32 = require(\"base32.js\");\n\nconst F1Field = require(\"ffjavascript\").F1Field;\nconst Scalar = require(\"ffjavascript\").Scalar;\nexports.p = Scalar.fromString(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\nconst Fr = new F1Field(exports.p);\n\nconst { Keypair } = require(\"circomlib-ml/test/modules/maci-domainobjs\");\nconst { decrypt } = require(\"circomlib-ml/test/modules/maci-crypto\");\n\nconst json = require(\"./circuit.json\");\nconst labels = require(\"../assets/labels.json\");\n\n// read ../assets/cid.txt into an array of strings\nconst cids = fs.readFileSync(\"assets/cid.txt\").toString().split(\"\\r\");\n// console.log(cids);\n\nconst idx = 567;\n\nlet modelHash;\n\ndescribe(\"circuit.circom test\", function () {\n    let INPUT = {};\n\n    for (const [key, value] of Object.entries(json)) {\n        if (Array.isArray(value)) {\n            let tmpArray = [];\n            for (let i = 0; i < value.flat().length; i++) {\n                tmpArray.push(Fr.e(value.flat()[i]));\n            }\n            INPUT[key] = tmpArray;\n        } else {\n            INPUT[key] = Fr.e(value);\n        }\n    }\n\n    let Verifier;\n    let verifier;\n\n    let a, b, c, Input;\n\n    const digests = [];\n\n    before(async function () {\n        Verifier = await ethers.getContractFactory(\"CircuitVerifier\");\n        verifier = await Verifier.deploy();\n        await verifier.deployed();\n\n        const input = [];\n\n        for (let i = 0; i < 10; i++) {\n            const bytes = fs.readFileSync(\"assets/\" + (idx + i) + \".pgm\");\n            const binary = [...bytes].map((b) => b.toString(2).padStart(8, \"0\").split(\"\")).flat();\n            input.push(binary);\n\n            const hash = crypto.createHash('sha256');\n            hash.update(bytes);\n            digests.push(hash.digest('hex'));\n        }\n        // console.log(input.flat().length);\n\n        INPUT[\"in\"] = input.flat();\n\n        const { proof, publicSignals } = await groth16.fullProve(INPUT, \"circuits/build/circuit_js/circuit.wasm\", \"circuits/build/circuit_final.zkey\");\n\n        const calldata = await groth16.exportSolidityCallData(proof, publicSignals);\n\n        const argv = calldata.replace(/[\"[\\]\\s]/g, \"\").split(',').map(x => BigInt(x).toString());\n\n        a = [argv[0], argv[1]];\n        b = [[argv[2], argv[3]], [argv[4], argv[5]]];\n        c = [argv[6], argv[7]];\n        Input = argv.slice(8);\n        console.log(labels.slice(idx, idx + 10));\n        console.log(Input.slice(0,10));\n\n        const calldataJson = {\n            \"a\": a,\n            \"b\": b,\n            \"c\": c,\n            \"input\": Input,\n        }\n\n        // save calldata to json file\n        fs.writeFileSync(\"./test/circuitCalldata.json\", JSON.stringify(calldataJson));\n\n        modelHash = Input[30];\n    });\n\n    it(\"Check circuit output\", async () => {\n        for (let i = 0; i < 10; i++) {\n            const digest1 = Fr.e(digests[i].slice(0,32), 16);\n            const digest2 = Fr.e(digests[i].slice(32,64), 16);\n\n            assert(Fr.eq(Fr.e(Input[i*2+10]),Fr.e(digest1)));\n            assert(Fr.eq(Fr.e(Input[i*2+11]),Fr.e(digest2)));\n        }\n    });\n\n    it(\"Verifier should return true for correct proofs\", async function () {\n        expect(await verifier.verifyProof(a, b, c, Input)).to.be.true;\n    });\n\n    it(\"Verifier should return false for invalid proof\", async function () {\n        let a = [0, 0];\n        let b = [[0, 0], [0, 0]];\n        let c = [0, 0];\n        expect(await verifier.verifyProof(a, b, c, Input)).to.be.false;\n    });\n\n    it(\"CIDv1 should match that from IPFS\", async function () {\n        const cid_version = 1;\n        const cid_codec = 85; // raw 0x55\n        const hash_function_code = 18; // SHA-256 0x12\n        const length = 32;\n\n        for (let i = 0; i < 10; i++) {\n            const cidraw = cid_version.toString(16).padStart(2, \"0\") + cid_codec.toString(16).padStart(2, \"0\") + hash_function_code.toString(16).padStart(2, \"0\") + length.toString(16).padStart(2, \"0\") + digests[i];\n            const buf = Buffer.from(cidraw, 'hex');\n\n            const encoder = new base32.Encoder();\n            const cid = encoder.write(buf).finalize().toLowerCase();\n            expect(\"b\" + cid).equal(cids[idx + i]);\n        }\n    });\n});\n\ndescribe(\"encryption.circom test\", function () {\n    let input = [];\n\n    for (const [key, value] of Object.entries(json)) {\n        // console.log(key);\n        if (Array.isArray(value)) {\n            let tmpArray = [];\n            for (let i = 0; i < value.flat().length; i++) {\n                tmpArray.push(Fr.e(value.flat()[i]));\n            }\n            input = [...input, ...tmpArray];\n        } else {\n            input.push(value);\n        }\n    }\n\n    for (let i = input.length; i< 1000; i++) {\n        input.push(0);\n    }\n\n    let Verifier;\n    let verifier;\n\n    let a, b, c, Input;\n\n    let keypair;\n    let keypair2;\n\n    let ecdhSharedKey;\n\n    let INPUT = {};\n\n    before(async function () {\n        keypair = new Keypair();\n        keypair2 = new Keypair();\n\n        ecdhSharedKey = Keypair.genEcdhSharedKey(\n            keypair.privKey,\n            keypair2.pubKey,\n        );\n\n        INPUT = {\n            'private_key': keypair.privKey.asCircuitInputs(),\n            'public_key': keypair2.pubKey.asCircuitInputs(),\n            'in': input,\n        }\n\n        // console.log(INPUT);\n        // console.log(INPUT['public_key']);\n\n        // deploy pairing contracts from pairing100 to pairing1000\n        const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n        const pairing100 = await Pairing100.deploy();\n        await pairing100.deployed();\n\n        const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n        const pairing200 = await Pairing200.deploy();\n        await pairing200.deployed();\n\n        const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n        const pairing300 = await Pairing300.deploy();\n        await pairing300.deployed();\n\n        const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n        const pairing400 = await Pairing400.deploy();\n        await pairing400.deployed();\n\n        const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n        const pairing500 = await Pairing500.deploy();\n        await pairing500.deployed();\n\n        const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n        const pairing600 = await Pairing600.deploy();\n        await pairing600.deployed();\n\n        const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n        const pairing700 = await Pairing700.deploy();\n        await pairing700.deployed();\n\n        const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n        const pairing800 = await Pairing800.deploy();\n        await pairing800.deployed();\n\n        const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n        const pairing900 = await Pairing900.deploy();\n        await pairing900.deployed();\n\n        const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n        const pairing1000 = await Pairing1000.deploy();\n        await pairing1000.deployed();\n\n        Verifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n        verifier = await Verifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n        await verifier.deployed();\n\n        const { proof, publicSignals } = await groth16.fullProve(INPUT, \"circuits/build/encryption_js/encryption.wasm\", \"circuits/build/encryption_final.zkey\");\n\n        const calldata = await groth16.exportSolidityCallData(proof, publicSignals);\n\n        const argv = calldata.replace(/[\"[\\]\\s]/g, \"\").split(',').map(x => BigInt(x).toString());\n\n        a = [argv[0], argv[1]];\n        b = [[argv[2], argv[3]], [argv[4], argv[5]]];\n        c = [argv[6], argv[7]];\n        Input = argv.slice(8);\n        // console.log(Input.slice(1000));\n\n        const calldataJson = {\n            \"a\": a,\n            \"b\": b,\n            \"c\": c,\n            \"input\": Input,\n        }\n        \n        const keysJson = [\n            {\n                \"private_key\": keypair.privKey.asCircuitInputs(),\n                \"public_key\": keypair.pubKey.asCircuitInputs(),\n            },\n            {\n                \"private_key\": keypair2.privKey.asCircuitInputs(),\n                \"public_key\": keypair2.pubKey.asCircuitInputs(),\n            },\n        ]\n        // save calldata to json file\n        fs.writeFileSync(\"./test/keys.json\", JSON.stringify(keysJson));\n        fs.writeFileSync(\"./test/encryptionCalldata.json\", JSON.stringify(calldataJson));\n    });\n\n    it(\"Check circuit output\", async () => {\n        assert(Fr.eq(Fr.e(Input[0]),Fr.e(modelHash)));\n        assert(Fr.eq(Fr.e(Input[1]),Fr.e(ecdhSharedKey)));\n        assert(Fr.eq(Fr.e(Input[1003]),Fr.e(INPUT['public_key'][0])));\n        assert(Fr.eq(Fr.e(Input[1004]),Fr.e(INPUT['public_key'][1])));\n    });\n\n    it(\"Verifier should return true for correct proofs\", async function () {\n        expect(await verifier.verifyProof(a, b, c, Input)).to.be.true;\n    });\n\n    it(\"Verifier should return false for invalid proof\", async function () {\n        let a = [0, 0];\n        let b = [[0, 0], [0, 0]];\n        let c = [0, 0];\n        expect(await verifier.verifyProof(a, b, c, Input)).to.be.false;\n    });\n\n    it(\"Decryption should match\", async function () {\n        const ciphertext = {\n            iv: Input[2],\n            data: Input.slice(3,1004),\n        }\n\n        const decrypted = decrypt(ciphertext, ecdhSharedKey);\n\n        for (let i = 0; i < 1000; i++) {\n            assert(Fr.eq(Fr.e(decrypted[i]), Fr.e(input[i])));\n        }\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/test/2.bounty.test.js",
        "content": "const { expect } = require(\"chai\");\nconst { ethers } = require(\"hardhat\");\n\nconst fs = require(\"fs\");\nconst base32 = require(\"base32.js\");\n\nconst labels = require(\"../assets/labels.json\");\n\nconst circuitCalldata = require(\"./circuitCalldata.json\");\nconst encryptionCalldata = require(\"./encryptionCalldata.json\");\n\n// read ../assets/cid.txt into an array of strings\nconst cids = fs.readFileSync(\"assets/cid.txt\").toString().split(\"\\r\");\n\nconst idx = 567;\n\nconst _labels = [];\n\ndescribe(\"Bounty contract test\", function () {\n    const cidraw = []; // raw CIDs of the uploaded files\n    let encryptionVerifierAddress;\n\n    describe(\"Tx 1: Creating a bounty\", function () {\n\n        before(async function () {\n            // deploy pairing contracts from pairing100 to pairing1000\n            const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n            const pairing100 = await Pairing100.deploy();\n            await pairing100.deployed();\n    \n            const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n            const pairing200 = await Pairing200.deploy();\n            await pairing200.deployed();\n    \n            const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n            const pairing300 = await Pairing300.deploy();\n            await pairing300.deployed();\n    \n            const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n            const pairing400 = await Pairing400.deploy();\n            await pairing400.deployed();\n    \n            const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n            const pairing500 = await Pairing500.deploy();\n            await pairing500.deployed();\n    \n            const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n            const pairing600 = await Pairing600.deploy();\n            await pairing600.deployed();\n    \n            const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n            const pairing700 = await Pairing700.deploy();\n            await pairing700.deployed();\n    \n            const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n            const pairing800 = await Pairing800.deploy();\n            await pairing800.deployed();\n    \n            const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n            const pairing900 = await Pairing900.deploy();\n            await pairing900.deployed();\n    \n            const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n            const pairing1000 = await Pairing1000.deploy();\n            await pairing1000.deployed();\n\n            const EncyrptionVerifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n            const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n            await encryptionVerifier.deployed();\n            encryptionVerifierAddress = encryptionVerifier.address;\n\n            for (let i = 0; i < 10; i++) {\n                const decoder = new base32.Decoder();\n                cidraw.push(decoder.write(cids[idx + i].slice(1)).finalize());\n                _labels.push(labels[idx + i]);\n            }\n\n            // write cidraw into a json file\n            fs.writeFileSync(\"./test/cidraw.json\", JSON.stringify(cidraw.map((cid) => '0x' + cid.toString('hex'))));\n            // write _labels into a json file\n            fs.writeFileSync(\"./test/labels.json\", JSON.stringify(_labels));\n        });\n\n        it(\"Should reject deploying the contract is msg.value is 0\", async function () {\n            const owner = await ethers.provider.getSigner(0).getAddress();\n            const Bounty = await ethers.getContractFactory(\"Bounty\");\n            const bounty = await Bounty.deploy();\n            await bounty.deployed();\n\n            await expect(bounty.initialize(\n                owner,\n                \"Bounty 1\",\n                \"This is the first bounty\",\n                cidraw,\n                _labels,\n                70,\n                encryptionVerifierAddress,\n            )).to.be.revertedWith(\"Bounty reward must be greater than 0\");\n        });\n\n        it(\"Should deploy the contract and set owner to first input\", async function () {\n            const owner = await ethers.provider.getSigner(0).getAddress();\n            const Bounty = await ethers.getContractFactory(\"Bounty\");\n            const bounty = await Bounty.deploy();\n            await bounty.deployed();\n\n            const tx = await bounty.initialize(\n                owner,\n                \"Bounty 1\",\n                \"This is the first bounty\",\n                cidraw,\n                _labels,\n                70,\n                encryptionVerifierAddress,\n                { value: ethers.utils.parseEther(\"1\") }\n            );\n            await tx.wait();\n            expect(await bounty.name()).to.equal(\"Bounty 1\");\n            expect(await bounty.description()).to.equal(\"This is the first bounty\");\n            for (let i = 0; i < 10; i++) {\n                expect(await bounty.dataCIDs(i)).to.equal('0x' + cidraw[i].toString('hex'));\n                expect(await bounty.labels(i)).to.equal(_labels[i]);\n            }\n            expect(await bounty.owner()).to.equal(owner);\n            expect(await bounty.completedStep()).to.equal(1);\n        });\n    });\n\n    let a, b, c, Input;\n\n    describe(\"Tx 2: Submitting a bounty\", function () {\n        let bounty, verifier, encryptionVerifierAddress;\n        const digests = [];\n\n        before(async function () {\n            // deploy pairing contracts from pairing100 to pairing1000\n            const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n            const pairing100 = await Pairing100.deploy();\n            await pairing100.deployed();\n    \n            const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n            const pairing200 = await Pairing200.deploy();\n            await pairing200.deployed();\n    \n            const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n            const pairing300 = await Pairing300.deploy();\n            await pairing300.deployed();\n    \n            const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n            const pairing400 = await Pairing400.deploy();\n            await pairing400.deployed();\n    \n            const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n            const pairing500 = await Pairing500.deploy();\n            await pairing500.deployed();\n    \n            const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n            const pairing600 = await Pairing600.deploy();\n            await pairing600.deployed();\n    \n            const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n            const pairing700 = await Pairing700.deploy();\n            await pairing700.deployed();\n    \n            const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n            const pairing800 = await Pairing800.deploy();\n            await pairing800.deployed();\n    \n            const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n            const pairing900 = await Pairing900.deploy();\n            await pairing900.deployed();\n    \n            const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n            const pairing1000 = await Pairing1000.deploy();\n            await pairing1000.deployed();\n\n            const EncyrptionVerifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n            const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n            await encryptionVerifier.deployed();\n            encryptionVerifierAddress = encryptionVerifier.address;\n\n            const owner = await ethers.provider.getSigner(0).getAddress();\n            const Bounty = await ethers.getContractFactory(\"Bounty\");\n            bounty = await Bounty.deploy();\n            await bounty.deployed();\n\n            const tx = await bounty.initialize(\n                owner,\n                \"Bounty 1\",\n                \"This is the first bounty\",\n                cidraw,\n                _labels,\n                70,\n                encryptionVerifierAddress,\n                { value: ethers.utils.parseEther(\"1\") }\n            );\n            await tx.wait();\n\n            // Deploy the verifier\n            const Verifier = await ethers.getContractFactory(\"CircuitVerifier\");\n            verifier = await Verifier.deploy();\n            await verifier.deployed();\n\n            a = circuitCalldata.a;\n            b = circuitCalldata.b;\n            c = circuitCalldata.c;\n            Input = circuitCalldata.input;\n        });\n\n        it(\"Should reject a bounty with wrong proof\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    [0, 0],\n                    [[0, 0], [0, 0]],\n                    [0, 0],\n                    Input\n                )).to.be.revertedWith(\"Invalid proof\");\n        });\n\n        it(\"Should reject a bounty with wrong verifier\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    ethers.constants.AddressZero,\n                    a,\n                    b,\n                    c,\n                    Input\n                )).to.be.revertedWith(\"Invalid verifier address\");\n        });\n\n        it(\"Should reject a bounty with wrong input\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    [..._labels, ...Array(21).keys()]\n                )).to.be.revertedWith(\"Data CID mismatch\");\n        });\n\n        it(\"Should reject a bounty with low accuracy\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    [...Array(31).keys()]\n                )).to.be.revertedWith(\"Accuracy threshold not met\");\n        });\n\n        it(\"Should submit a bounty\", async function () {\n            const submitter = await ethers.provider.getSigner(1).getAddress();\n            const tx = await bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    Input\n                );\n            await tx.wait();\n\n            expect(tx).to.emit(bounty, \"BountySubmitted\");\n            expect(await bounty.bountyHunter()).to.equal(submitter);\n            expect(await bounty.completedStep()).to.equal(2);\n        });\n\n        it(\"Should reject submitting a submitted bounty\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    Input\n                )).to.be.revertedWith(\"Bounty already submitted\");\n        });\n    });\n\n    let publicKeys;\n\n    describe(\"Tx 3: Releasing a bounty\", function () {\n        let bounty, verifier, encryptionVerifierAddress;\n\n        before(async function () {\n            // deploy pairing contracts from pairing100 to pairing1000\n            const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n            const pairing100 = await Pairing100.deploy();\n            await pairing100.deployed();\n    \n            const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n            const pairing200 = await Pairing200.deploy();\n            await pairing200.deployed();\n    \n            const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n            const pairing300 = await Pairing300.deploy();\n            await pairing300.deployed();\n    \n            const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n            const pairing400 = await Pairing400.deploy();\n            await pairing400.deployed();\n    \n            const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n            const pairing500 = await Pairing500.deploy();\n            await pairing500.deployed();\n    \n            const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n            const pairing600 = await Pairing600.deploy();\n            await pairing600.deployed();\n    \n            const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n            const pairing700 = await Pairing700.deploy();\n            await pairing700.deployed();\n    \n            const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n            const pairing800 = await Pairing800.deploy();\n            await pairing800.deployed();\n    \n            const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n            const pairing900 = await Pairing900.deploy();\n            await pairing900.deployed();\n    \n            const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n            const pairing1000 = await Pairing1000.deploy();\n            await pairing1000.deployed();\n\n            const EncyrptionVerifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n            const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n            await encryptionVerifier.deployed();\n            encryptionVerifierAddress = encryptionVerifier.address;\n\n            const owner = await ethers.provider.getSigner(0).getAddress();\n            const Bounty = await ethers.getContractFactory(\"Bounty\");\n            bounty = await Bounty.deploy();\n            await bounty.deployed();\n            const tx = await bounty.initialize(\n                owner,\n                \"Bounty 1\",\n                \"This is the first bounty\",\n                cidraw,\n                _labels,\n                70,\n                encryptionVerifierAddress,\n                { value: ethers.utils.parseEther(\"1\") }\n            );\n            await tx.wait();\n\n            // Deploy the verifier\n            const Verifier = await ethers.getContractFactory(\"CircuitVerifier\");\n            verifier = await Verifier.deploy();\n            await verifier.deployed();\n\n            publicKeys = [encryptionCalldata.input[1003], encryptionCalldata.input[1004]];\n        });\n\n        it(\"Should reject releasing an unsubmitted bounty\", async function () {\n            await expect(bounty.releaseBounty(publicKeys)).to.be.revertedWith(\"Bounty hunter has not submitted proof\");\n        });\n\n        it(\"Should reject releasing a bounty by non-owner\", async function () {\n\n            const tx = await bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    Input\n                );\n            await tx.wait();\n            await expect(bounty.connect(ethers.provider.getSigner(1)).releaseBounty(publicKeys)).to.be.revertedWith(\"Ownable: caller is not the owner\");\n        });\n\n        it(\"Should release a bounty\", async function () {\n            const tx = await bounty.releaseBounty(publicKeys);\n            await tx.wait();\n\n            expect(tx).to.emit(bounty, \"BountyReleased\");\n            expect(await bounty.isComplete()).to.equal(true);\n            expect(await bounty.completedStep()).to.equal(3);\n        });\n\n        it(\"Should reject releasing a bounty twice\", async function () {\n            await expect(bounty.releaseBounty(publicKeys)).to.be.revertedWith(\"Bounty is already complete\");\n        });\n    });\n\n    describe(\"Tx 4: Claiming a bounty\", function () {\n        let bounty, verifier, encryptionVerifierAddress;\n\n        before(async function () {\n            // deploy pairing contracts from pairing100 to pairing1000\n            const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n            const pairing100 = await Pairing100.deploy();\n            await pairing100.deployed();\n    \n            const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n            const pairing200 = await Pairing200.deploy();\n            await pairing200.deployed();\n    \n            const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n            const pairing300 = await Pairing300.deploy();\n            await pairing300.deployed();\n    \n            const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n            const pairing400 = await Pairing400.deploy();\n            await pairing400.deployed();\n    \n            const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n            const pairing500 = await Pairing500.deploy();\n            await pairing500.deployed();\n    \n            const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n            const pairing600 = await Pairing600.deploy();\n            await pairing600.deployed();\n    \n            const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n            const pairing700 = await Pairing700.deploy();\n            await pairing700.deployed();\n    \n            const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n            const pairing800 = await Pairing800.deploy();\n            await pairing800.deployed();\n    \n            const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n            const pairing900 = await Pairing900.deploy();\n            await pairing900.deployed();\n    \n            const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n            const pairing1000 = await Pairing1000.deploy();\n            await pairing1000.deployed();\n\n            const EncyrptionVerifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n            const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n            await encryptionVerifier.deployed();\n            encryptionVerifierAddress = encryptionVerifier.address;\n\n            const owner = await ethers.provider.getSigner(0).getAddress();\n            const Bounty = await ethers.getContractFactory(\"Bounty\");\n            bounty = await Bounty.deploy();\n            await bounty.deployed();\n\n            let tx = await bounty.initialize(\n                owner,\n                \"Bounty 1\",\n                \"This is the first bounty\",\n                cidraw,\n                _labels,\n                70,\n                encryptionVerifierAddress,\n                { value: ethers.utils.parseEther(\"1\") }\n            );\n            await tx.wait();\n\n            // Deploy the verifier\n            const Verifier = await ethers.getContractFactory(\"CircuitVerifier\");\n            verifier = await Verifier.deploy();\n            await verifier.deployed();\n\n            tx = await bounty.connect(ethers.provider.getSigner(1)).\n                submitBounty(\n                    0x0,\n                    0x0,\n                    0x0,\n                    verifier.address,\n                    a,\n                    b,\n                    c,\n                    Input\n                );\n            await tx.wait();\n\n            a = encryptionCalldata.a;\n            b = encryptionCalldata.b;\n            c = encryptionCalldata.c;\n            Input = encryptionCalldata.input;\n        });\n\n        it(\"Should reject claiming a bounty by non bounty hunter\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(2))\n                .claimBounty(a, b, c, Input)).to.be.revertedWith(\"Only bounty hunter can claim bounty\");\n        });\n\n        it(\"Should reject claiming an uncompleted bounty\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1))\n                .claimBounty(a, b, c, Input))\n                .to.be.revertedWith(\"Bounty is not complete\");\n        });\n\n        it(\"Should claim a bounty\", async function () {\n            const bountyHunter = await ethers.provider.getSigner(1).getAddress();\n            const balance = await ethers.provider.getBalance(bountyHunter);\n            let tx = await bounty.releaseBounty(publicKeys);\n            await tx.wait();\n\n            tx = await bounty.connect(ethers.provider.getSigner(1))\n                .claimBounty(a, b, c, Input);\n            await tx.wait();\n\n            expect(tx).to.emit(bounty, \"BountyClaimed\");\n            // Check that the bounty hunter has been paid\n            expect(await ethers.provider.getBalance(bountyHunter)).to.greaterThan(balance);\n            expect(await bounty.completedStep()).to.equal(4);\n        });\n\n        it(\"Should reject claiming a claimed bounty\", async function () {\n            await expect(bounty.connect(ethers.provider.getSigner(1))\n                .claimBounty(a, b, c, Input))\n                .to.be.revertedWith(\"Bounty already claimed\");\n        });\n\n        // TODO: add more tests for new features\n    });\n});\n"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "hardhat/test/3.factory.test.js",
        "content": "const { expect } = require(\"chai\");\nconst { ethers } = require(\"hardhat\");\n\nconst fs = require(\"fs\");\nconst base32 = require(\"base32.js\");\n\nconst labels = require(\"../assets/labels.json\");\n\n// read ../assets/cid.txt into an array of strings\nconst cids = fs.readFileSync(\"assets/cid.txt\").toString().split(\"\\r\");\n\nconst idx = 567;\n\nconst _labels = [];\n\ndescribe(\"BountyFactory test\", function () {\n    let factory;\n    let Bounty;\n    const cidraw = []; // raw CIDs of the uploaded files\n\n    before(async function () {\n        // deploy pairing contracts from pairing100 to pairing1000\n        const Pairing100 = await ethers.getContractFactory(\"Pairing100\");\n        const pairing100 = await Pairing100.deploy();\n        await pairing100.deployed();\n\n        const Pairing200 = await ethers.getContractFactory(\"Pairing200\");\n        const pairing200 = await Pairing200.deploy();\n        await pairing200.deployed();\n\n        const Pairing300 = await ethers.getContractFactory(\"Pairing300\");\n        const pairing300 = await Pairing300.deploy();\n        await pairing300.deployed();\n\n        const Pairing400 = await ethers.getContractFactory(\"Pairing400\");\n        const pairing400 = await Pairing400.deploy();\n        await pairing400.deployed();\n\n        const Pairing500 = await ethers.getContractFactory(\"Pairing500\");\n        const pairing500 = await Pairing500.deploy();\n        await pairing500.deployed();\n\n        const Pairing600 = await ethers.getContractFactory(\"Pairing600\");\n        const pairing600 = await Pairing600.deploy();\n        await pairing600.deployed();\n\n        const Pairing700 = await ethers.getContractFactory(\"Pairing700\");\n        const pairing700 = await Pairing700.deploy();\n        await pairing700.deployed();\n\n        const Pairing800 = await ethers.getContractFactory(\"Pairing800\");\n        const pairing800 = await Pairing800.deploy();\n        await pairing800.deployed();\n\n        const Pairing900 = await ethers.getContractFactory(\"Pairing900\");\n        const pairing900 = await Pairing900.deploy();\n        await pairing900.deployed();\n\n        const Pairing1000 = await ethers.getContractFactory(\"Pairing1000\");\n        const pairing1000 = await Pairing1000.deploy();\n        await pairing1000.deployed();\n\n        const EncyrptionVerifier = await ethers.getContractFactory(\"EncryptionVerifier\");\n        const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address);\n        await encryptionVerifier.deployed();\n\n        const BountyFactory = await ethers.getContractFactory(\"BountyFactory\");\n        factory = await BountyFactory.deploy(encryptionVerifier.address);\n        await factory.deployed();\n\n        Bounty = await ethers.getContractFactory(\"Bounty\");\n\n        for (let i = 0; i < 10; i++) {\n            const decoder = new base32.Decoder();\n            cidraw.push(decoder.write(cids[idx + i].slice(1)).finalize());\n            _labels.push(labels[idx + i]);\n        }\n    });\n\n    it(\"Should create a new bounty\", async function () {\n        const tx = await factory.createBounty(\n            \"Bounty 1\",\n            \"This is the first bounty\",\n            cidraw,\n            _labels,\n            70,\n            { value: ethers.utils.parseEther(\"1\") }\n        );\n        await tx.wait();\n\n        const bounty = await Bounty.attach(await factory.bounties(0));\n\n        expect(await bounty.owner()).to.equal(await ethers.provider.getSigner(0).getAddress());\n        expect(await ethers.provider.getBalance(bounty.address)).to.equal(ethers.utils.parseEther(\"1\"));\n        \n        expect(await bounty.name()).to.equal(\"Bounty 1\");\n        expect(await bounty.description()).to.equal(\"This is the first bounty\");\n        expect(await factory.bountyCount()).to.equal(1);\n\n        // TODO: add more checks\n    });\n\n    it(\"Should calculate future bounty address\", async function () {\n        const nonce = await ethers.provider.getTransactionCount(factory.address);\n        const futureAddress = ethers.utils.getContractAddress({ from: factory.address, nonce: nonce });\n\n        await expect(factory.createBounty(\n            \"Bounty 2\",\n            \"This is the second bounty\",\n            cidraw,\n            _labels,\n            70,\n            { value: ethers.utils.parseEther(\"1\") }\n        )).to.emit(factory, \"BountyCreated\").withArgs(futureAddress);\n        expect(await factory.bountyCount()).to.equal(2);\n    });\n});"
    },
    {
        "repo": "https://github.com/socathie/ZKaggleV2",
        "file_path": "pgm.ipynb",
        "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from tensorflow import keras\\n\",\n    \"from PIL import Image\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"for i in range(1000):\\n\",\n    \"    image = Image.fromarray(x_train[i], mode='L')\\n\",\n    \"    image.save('./hardhat/assets/'+str(i)+'.pgm')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with open('./hardhat/assets/labels.json', 'w') as f:\\n\",\n    \"    json.dump(y_train[:1000].tolist(), f)\\n\",\n    \"    f.close()\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"keras2circom\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.9.13\"\n  },\n  \"orig_nbformat\": 4\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
    }
]